{"text": "#include <gnuplot-iostream/gnuplot-iostream.h>\n#include <boost/tuple/tuple.hpp>\n#include <iostream>\n#include <iomanip>\n#include <functional>\n#include <vector>\n#include <cmath>\n#include \"Tools.hpp\"\n#define PI 3.14159265\nusing namespace std;\n\n/***********************************************************************\n\nSecond Case: 2D drag! DragObject2D is a class for a point particle in\n2D coordinates. Instead of individual accessor methods like Euler1D,\ngetAttrs returns a vector of the four instance variables. The Euler\nstep and updating code is all built in as well. A frequently used data\ntype in this program is vector<vector<double>>, usually called path.\nThe data stored is a vector of x values and y values in a projectile's \ntrajectory, ex. {{x1,x2,x3...},{y1,y2,y3...}}. Passing a data type like\nthis around is much easier than writing two methods or using evil\nlibraries to make functions return multiple values.\n\nThe getPath function takes an initial x and y velocity and performs the\nEuler method on an instance of DragObject2D, saving the x and y values\nin vectors. It simulates until a sign change is detected in y, meaning\nthe object has returned to the ground. For that reason,\nmaking v_i negative is a bad idea. After simulation, the function \nreturns a path. plotPath just plots the path given with axes of path[0],\npath[1].\n\nRangeVAngle is more complicated, as it performs all calculation and \nplots the range vs. angle graph. It iterates from -pi/2 to pi/2 with a \nstep size of dth. For each iteration, it gets the path with getPath. The\nfinal x value is the range when the object returns to the ground, by\nthe definition of the getPath function.\n\n***********************************************************************/\n\nconst double v_i = 10;\t\t// Initial velocity for both the trajectory and the range v. angle plot\nconst double th = PI/6;\t\t// Firing angle for the trajectory plot\nconst double y_0 = 1;\t\t// Global starting height, Should be either zero or something positive, as the range vs. angle graph must be complete.\n\nconst double g = 9.8;\t\t// Gravitational acceleration (negative)\nconst double b = 0;//.56832;\t// Calculated drag constant for Syd Miyasaki\nconst double dt = 0.001;\t// Timestep\nconst double dth = 0.001;\t// Step in angle for the range v. angle plot\n\nclass DragObject2D{\t// Problem-specific class\npublic:\n\tDragObject2D(double vx_0, double vy_0);\t// Constructor\n\tvector<double> getAttrs() const;\t\t// Accessor method for instance variables\n\tdouble getSpeed() const;\t\t\t\t// Accessor / calculation method for speed\n\tvoid update();\t// Euler step and updating\nprivate:\n\tdouble x, y, vx, vy;\n};\n\nDragObject2D::DragObject2D(double vx_0, double vy_0){\t// Constructor sets x to zero, y to starting height, initial velocities as arguments\n\tx = 0;\n\ty = y_0;\n\tvx = vx_0;\n\tvy = vy_0;\n}\n\nvector<double> DragObject2D::getAttrs() const {\t// Usage of anonymously declared vectors to return all instance variables\n\treturn vector<double>{x,y,vx,vy};\n}\n\ndouble DragObject2D::getSpeed() const {\t// *trivial* mechanics (component velocity to speed)\n\treturn sqrt(vx*vx + vy*vy);\n}\n\nvoid DragObject2D::update(){\t// Update all the things!\n\tdouble v = this->getSpeed();// Get speed on the current object instance. \"this\" returns a pointer to the instance, and -> is an abbreviation of (*this).getSpeed()\n\tx += vx*dt;\t\t\t\t// Update x and y\n\ty += vy*dt;\n\n\tvx += -(b*v*vx)*dt;\t\t// Euler step for x and y\n\tvy += -(g+b*v*vy)*dt;\n}\n\n\nvector<vector<double>> getPath(double vx_0, double vy_0){\t// Get the path thing\n\tvector<double> x_n;\t// Vectors for the path\n\tvector<double> y_n;\n\tdouble yval = 0;\t// The value of y\n\n\tDragObject2D object(vx_0, vy_0);// The object to track\n\n\twhile(yval >= 0){\t\t\t\t// Only track until the object hits the ground\n\t\tvector<double> attrs = object.getAttrs();\t// Get attributes (x, y, vx, vy)\n\t\tx_n.push_back(attrs[0]);\t// Add attributes to vectors, update y value\n\t\ty_n.push_back(attrs[1]);\n\t\tyval = attrs[1];\n\n\t\tobject.update();\t\t\t// Perform Euler step and updates\n\t}\n\n\treturn vector<vector<double>>{x_n,y_n};\t// Return the two vectors of x and y together\n}\n\n\nvoid plotPath(vector<vector<double>>& path){\t// Plot the path; pretty basic stuff\n\tGnuplot gp;\n\n\tgp << setprecision(3);\n\tgp << \"set xrange [0:\" << path[0].back() << \"]\\n\";\n\tgp << \"set yrange [0:\" << getMaxVal(path[1])*1.1 << \"]\\n\";\n\tgp << \"set format y \\\"%.1f\\\"\\n\";\n\tgp << \"set term png size 720,480 font \\\"FreeSerif,12\\\"\\n\";\n\tgp << \"set xlabel \\\"x (m)\\\"\\n\";\n\tgp << \"set ylabel \\\"y (m)\\\"\\n\";\n\tgp << \"set title \\\"Trajectory of Syd Under Rayleigh's Drag Equation\\\\nb = \" << b;\n\tgp << \", v_i = \" << v_i << \", {/Symbol q}_i = \" << th << \"\\\"\\n\";\n\tgp << \"set output \\\"Trajectory.png\\\"\\n\";\n\tgp << \"plot '-' with dots lc rgb \\\"black\\\" notitle\\n\";\n\tgp.send1d(boost::make_tuple(path[0],path[1]));\n}\n\n\nvoid rangeVAngle(){\t\t\t// Calculation and plotting of the range vs. angle plot\n\tvector<double> ranges;\t// Declare vectors\n\tvector<double> angles;\n\n\tfor(double ang = -PI/2; ang < PI/2; ang += dth){\t// From -pi/2 to pi/2, steps of dth\n\n\t\tdouble vx_0 = v_i*cos(ang);\t// From v_i and ang, determine the initial velocities\n\t\tdouble vy_0 = v_i*sin(ang);\t\n\t\tvector<vector<double>> path = getPath(vx_0, vy_0);\t// Generate path\n\t\tdouble range = path[0].back();\t// The last x value is the range\n\n\t\tangles.push_back(ang);\t// Save angle and range\n\t\tranges.push_back(range);\n\t}\n\n\tGnuplot gp;\t\t// Now plot!\n\n\tgp << setprecision(3);\n\tgp << \"set xrange [\" << -PI/2 << \":\" << PI/2 << \"]\\n\";\n\tgp << \"set yrange [0:\" << getMaxVal(ranges)*1.1 << \"]\\n\";\n\tgp << \"set format y \\\"%.1f\\\"\\n\";\n\tgp << \"set term png size 720,480 font \\\"FreeSerif,12\\\"\\n\";\n\tgp << \"set xlabel \\\"angle (rad)\\\"\\n\";\n\tgp << \"set ylabel \\\"range (m)\\\"\\n\";\n\tgp << \"set title \\\"Range vs. Firing Angle of Syd Under Rayleigh's Drag Equation, b = \" << b << \"\\\"\\n\"; \n\tgp << \"set output \\\"RangeAngle.png\\\"\\n\";\n\tgp << \"plot '-' with dots lc rgb \\\"black\\\" notitle\\n\";\n\tgp.send1d(boost::make_tuple(angles,ranges));\n}\n\n\nint main(){\t\t// Main function\n\tdouble vx_0 = v_i*cos(th);\t// Use v_i and the launch angle th to determine initial velocities by components\n\tdouble vy_0 = v_i*sin(th);\n\tvector<vector<double>> path = getPath(vx_0, vy_0);\t// Generate the path\n\tplotPath(path);\t// Plot it\n\n\trangeVAngle();\t// And make the range vs. angle plot!\n\n\treturn 0;\t// If it all worked, return 0\n}", "meta": {"hexsha": "f93e4d08b918c90d8a80c784a61bc257c80bb923", "size": 6309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Drag/SecondCase.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": "Drag/SecondCase.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": "Drag/SecondCase.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": 38.9444444444, "max_line_length": 163, "alphanum_fraction": 0.6712632747, "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650248, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5499460876373604}}
{"text": "/*\n * CurvatureFilter.cpp\n *\n *  Created on: Sep 23, 2017\n *      Author: Peter Fankhauser\n *   Institute: ETH Zurich, ANYbotics\n */\n\n#include <grid_map_filters/CurvatureFilter.hpp>\n\n#include <grid_map_core/grid_map_core.hpp>\n#include <pluginlib/class_list_macros.h>\n\n#include <Eigen/Dense>\n\nusing namespace filters;\n\nnamespace grid_map {\n\ntemplate<typename T>\nCurvatureFilter<T>::CurvatureFilter()\n{\n}\n\ntemplate<typename T>\nCurvatureFilter<T>::~CurvatureFilter()\n{\n}\n\ntemplate<typename T>\nbool CurvatureFilter<T>::configure()\n{\n  if (!FilterBase < T > ::getParam(std::string(\"input_layer\"), inputLayer_)) {\n    ROS_ERROR(\"Curvature filter did not find parameter `input_layer`.\");\n    return false;\n  }\n  ROS_DEBUG(\"Curvature filter input layer is = %s.\", inputLayer_.c_str());\n\n  if (!FilterBase < T > ::getParam(std::string(\"output_layer\"), outputLayer_)) {\n    ROS_ERROR(\"Curvature filter did not find parameter `output_layer`.\");\n    return false;\n  }\n  ROS_DEBUG(\"Curvature filter output_layer = %s.\", outputLayer_.c_str());\n\n  return true;\n}\n\ntemplate<typename T>\nbool CurvatureFilter<T>::update(const T& mapIn, T& mapOut)\n{\n  if (!mapIn.isDefaultStartIndex()) throw std::runtime_error(\n      \"CurvatureFilter cannot be used with grid maps that don't have a default buffer start index.\");\n\n  mapOut = mapIn;\n  mapOut.add(outputLayer_);\n  auto& input = mapOut[inputLayer_];\n  auto& curvature = mapOut[outputLayer_];\n  const float L2 = mapOut.getResolution() * mapOut.getResolution();\n\n  for (Eigen::Index j{0}; j < input.cols(); ++j) {\n    for (Eigen::Index i{0}; i < input.rows(); ++i) {\n      // http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/How_Curvature_works/00q90000000t000000/\n      if (!std::isfinite(input(i, j))) continue;\n      float D = ((input(i, j==0 ? j : j-1) + input(i, j==input.cols()-1 ? j : j + 1)) / 2.0 - input(i, j)) / L2;\n      float E = ((input(i==0 ? i : i-1, j) + input(i==input.rows()-1 ? i : i + 1, j)) / 2.0 - input(i, j)) / L2;\n      if (!std::isfinite(D)) D = 0.0;\n      if (!std::isfinite(E)) E = 0.0;\n      curvature(i, j) = -2.0 * (D + E);\n    }\n  }\n\n  return true;\n}\n\n} /* namespace */\n\nPLUGINLIB_EXPORT_CLASS(grid_map::CurvatureFilter<grid_map::GridMap>, filters::FilterBase<grid_map::GridMap>)\n", "meta": {"hexsha": "b880f2285d91dee0bc0ba3e0c74a240913dfffe3", "size": 2253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grid_map_filters/src/CurvatureFilter.cpp", "max_stars_repo_name": "Yibin-Li/grid_map", "max_stars_repo_head_hexsha": "a0dd138c2235ce5d316aca6ea0dd4eb54e6d4a02", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1305.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T14:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:44:18.000Z", "max_issues_repo_path": "grid_map_filters/src/CurvatureFilter.cpp", "max_issues_repo_name": "Yibin-Li/grid_map", "max_issues_repo_head_hexsha": "a0dd138c2235ce5d316aca6ea0dd4eb54e6d4a02", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 174.0, "max_issues_repo_issues_event_min_datetime": "2018-08-06T21:41:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T04:45:09.000Z", "max_forks_repo_path": "grid_map_filters/src/CurvatureFilter.cpp", "max_forks_repo_name": "Yibin-Li/grid_map", "max_forks_repo_head_hexsha": "a0dd138c2235ce5d316aca6ea0dd4eb54e6d4a02", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 423.0, "max_forks_repo_forks_event_min_datetime": "2018-08-07T13:37:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:07:26.000Z", "avg_line_length": 28.8846153846, "max_line_length": 112, "alphanum_fraction": 0.6608965823, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5499460855262582}}
{"text": "/* Boost example/filter.cpp\r\n * two examples of filters for computing the sign of a determinant\r\n * the second filter is based on an idea presented in\r\n * \"Interval arithmetic yields efficient dynamic filters for computational\r\n * geometry\" by Br\u00f6nnimann, Burnikel and Pion, 2001\r\n *\r\n * Copyright 2003 Guillaume Melquiond\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 <cstring>\r\n#include <iostream>\r\n\r\nnamespace dummy {\r\n  using namespace boost;\r\n  using namespace numeric;\r\n  using namespace interval_lib;\r\n  typedef save_state<rounded_arith_opp<double> > R;\r\n  typedef checking_no_nan<double, checking_no_empty<double> > P;\r\n  typedef interval<double, policies<R, P> > I;\r\n}\r\n\r\ntemplate<class T>\r\nclass vector {\r\n  T* ptr;\r\npublic:\r\n  vector(int d) { ptr = (T*)malloc(sizeof(T) * d); }\r\n  ~vector() { free(ptr); }\r\n  const T& operator[](int i) const { return ptr[i]; }\r\n  T& operator[](int i) { return ptr[i]; }\r\n};\r\n\r\ntemplate<class T>\r\nclass matrix {\r\n  int dim;\r\n  T* ptr;\r\npublic:\r\n  matrix(int d): dim(d) { ptr = (T*)malloc(sizeof(T) * dim * dim); }\r\n  ~matrix() { free(ptr); }\r\n  int get_dim() const { return dim; }\r\n  void assign(const matrix<T> &a) { memcpy(ptr, a.ptr, sizeof(T) * dim * dim); }\r\n  const T* operator[](int i) const { return &(ptr[i * dim]); }\r\n  T* operator[](int i) { return &(ptr[i * dim]); }\r\n};\r\n\r\ntypedef dummy::I I_dbl;\r\n\r\n/* compute the sign of a determinant using an interval LU-decomposition; the\r\n   function answers 1 or -1 if the determinant is positive or negative (and\r\n   more importantly, the result must be provable), or 0 if the algorithm was\r\n   unable to get a correct sign */\r\nint det_sign_algo1(const matrix<double> &a) {\r\n  int dim = a.get_dim();\r\n  vector<int> p(dim);\r\n  for(int i = 0; i < dim; i++) p[i] = i;\r\n  int sig = 1;\r\n  I_dbl::traits_type::rounding rnd;\r\n  typedef boost::numeric::interval_lib::unprotect<I_dbl>::type I;\r\n  matrix<I> u(dim);\r\n  for(int i = 0; i < dim; i++) {\r\n    const double* line1 = a[i];\r\n    I* line2 = u[i];\r\n    for(int j = 0; j < dim; j++)\r\n      line2[j] = line1[j];\r\n  }\r\n  // computation of L and U\r\n  for(int i = 0; i < dim; i++) {\r\n    // partial pivoting\r\n    {\r\n      int pivot = i;\r\n      double max = 0;\r\n      for(int j = i; j < dim; j++) {\r\n        const I &v = u[p[j]][i];\r\n        if (zero_in(v)) continue;\r\n        double m = norm(v);\r\n        if (m > max) { max = m; pivot = j; }\r\n      }\r\n      if (max == 0) return 0;\r\n      if (pivot != i) {\r\n        sig = -sig;\r\n        int tmp = p[i];\r\n        p[i] = p[pivot];\r\n        p[pivot] = tmp;\r\n      }\r\n    }\r\n    // U[i,?]\r\n    {\r\n      I *line1 = u[p[i]];\r\n      const I &pivot = line1[i];\r\n      if (boost::numeric::interval_lib::cerlt(pivot, 0.)) sig = -sig;\r\n      for(int k = i + 1; k < dim; k++) {\r\n        I *line2 = u[p[k]];\r\n        I fact = line2[i] / pivot;\r\n        for(int j = i + 1; j < dim; j++) line2[j] -= fact * line1[j];\r\n      }\r\n    }\r\n  }\r\n  return sig;\r\n}\r\n\r\n/* compute the sign of a determinant using a floating-point LU-decomposition\r\n   and an a posteriori interval validation; the meaning of the answer is the\r\n   same as previously */\r\nint det_sign_algo2(const matrix<double> &a) {\r\n  int dim = a.get_dim();\r\n  vector<int> p(dim);\r\n  for(int i = 0; i < dim; i++) p[i] = i;\r\n  int sig = 1;\r\n  matrix<double> lui(dim);\r\n  {\r\n    // computation of L and U\r\n    matrix<double> lu(dim);\r\n    lu.assign(a);\r\n    for(int i = 0; i < dim; i++) {\r\n      // partial pivoting\r\n      {\r\n        int pivot = i;\r\n        double max = std::abs(lu[p[i]][i]);\r\n        for(int j = i + 1; j < dim; j++) {\r\n          double m = std::abs(lu[p[j]][i]);\r\n          if (m > max) { max = m; pivot = j; }\r\n        }\r\n        if (max == 0) return 0;\r\n        if (pivot != i) {\r\n          sig = -sig;\r\n          int tmp = p[i];\r\n          p[i] = p[pivot];\r\n          p[pivot] = tmp;\r\n        }\r\n      }\r\n      // L[?,i] and U[i,?]\r\n      {\r\n        double *line1 = lu[p[i]];\r\n        double pivot = line1[i];\r\n        if (pivot < 0) sig = -sig;\r\n        for(int k = i + 1; k < dim; k++) {\r\n          double *line2 = lu[p[k]];\r\n          double fact = line2[i] / pivot;\r\n          line2[i] = fact;\r\n          for(int j = i + 1; j < dim; j++) line2[j] -= line1[j] * fact;\r\n        }\r\n      }\r\n    }\r\n\r\n    // computation of approximate inverses: Li and Ui\r\n    for(int j = 0; j < dim; j++) {\r\n      for(int i = j + 1; i < dim; i++) {\r\n        double *line = lu[p[i]];\r\n        double s = - line[j];\r\n        for(int k = j + 1; k < i; k++) s -= line[k] * lui[k][j];\r\n        lui[i][j] = s;\r\n      }\r\n      lui[j][j] = 1 / lu[p[j]][j];\r\n      for(int i = j - 1; i >= 0; i--) {\r\n        double *line = lu[p[i]];\r\n        double s = 0;\r\n        for(int k = i + 1; k <= j; k++) s -= line[k] * lui[k][j];\r\n        lui[i][j] = s / line[i];\r\n      }\r\n    }\r\n  }\r\n\r\n  // norm of PAUiLi-I computed with intervals\r\n  {\r\n    I_dbl::traits_type::rounding rnd;\r\n    typedef boost::numeric::interval_lib::unprotect<I_dbl>::type I;\r\n    vector<I> m1(dim);\r\n    vector<I> m2(dim);\r\n    for(int i = 0; i < dim; i++) {\r\n      for(int j = 0; j < dim; j++) m1[j] = 0;\r\n      const double *l1 = a[p[i]];\r\n      for(int j = 0; j < dim; j++) {\r\n        double v = l1[j];    // PA[i,j]\r\n        double *l2 = lui[j]; // Ui[j,?]\r\n        for(int k = j; k < dim; k++) {\r\n          using boost::numeric::interval_lib::mul;\r\n          m1[k] += mul<I>(v, l2[k]); // PAUi[i,k]\r\n        }\r\n      }\r\n      for(int j = 0; j < dim; j++) m2[j] = m1[j]; // PAUi[i,j] * Li[j,j]\r\n      for(int j = 1; j < dim; j++) {\r\n        const I &v = m1[j];  // PAUi[i,j]\r\n        double *l2 = lui[j]; // Li[j,?]\r\n        for(int k = 0; k < j; k++)\r\n          m2[k] += v * l2[k]; // PAUiLi[i,k]\r\n      }\r\n      m2[i] -= 1; // PAUiLi-I\r\n      double ss = 0;\r\n      for(int i = 0; i < dim; i++) ss = rnd.add_up(ss, norm(m2[i]));\r\n      if (ss >= 1) return 0;\r\n    }\r\n  }\r\n  return sig;\r\n}\r\n\r\nint main() {\r\n  int dim = 20;\r\n  matrix<double> m(dim);\r\n  for(int i = 0; i < dim; i++) for(int j = 0; j < dim; j++)\r\n    m[i][j] = /*1 / (i-j-0.001)*/ cos(1+i*sin(1 + j)) /*1./(1+i+j)*/;\r\n\r\n  // compute the sign of the determinant of a \"strange\" matrix with the two\r\n  // algorithms, the first should fail and the second succeed\r\n  std::cout << det_sign_algo1(m) << \" \" << det_sign_algo2(m) << std::endl;\r\n}\r\n", "meta": {"hexsha": "4ad0f30220ec98399130b0a37ade3d9c7d79efe6", "size": 6471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/libs/numeric/interval/examples/filter.cpp", "max_stars_repo_name": "Jackarain/tinyrpc", "max_stars_repo_head_hexsha": "07060e3466776aa992df8574ded6c1616a1a31af", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "third_party/boost/libs/numeric/interval/examples/filter.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "third_party/boost/libs/numeric/interval/examples/filter.cpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 30.8142857143, "max_line_length": 81, "alphanum_fraction": 0.5022407665, "num_tokens": 2030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5499460792961554}}
{"text": "/*\n * @brief Functions for computing Bezier curves and their derivatives.\n * @author Jenna Reher (jreher@caltech.edu)\n */\n\n#ifndef BEZIER_TOOLS_HPP\n#define BEZIER_TOOLS_HPP\n\n#include <Eigen/Dense>\n\nnamespace bezier_tools {\n\ndouble singleterm_bezier(int m, int k, double s);\ndouble bezier(const Eigen::VectorXd &coeff, double s);\nvoid bezier(const Eigen::MatrixXd &coeffs, double s, Eigen::VectorXd &out);\ndouble dbezier(const Eigen::VectorXd &coeff, double s);\nvoid dbezier(const Eigen::MatrixXd &coeffs, double s, Eigen::VectorXd &out);\ndouble d2bezier(const Eigen::VectorXd &coeff, double s);\nvoid d2bezier(const Eigen::MatrixXd &coeffs, double s, Eigen::VectorXd &out);\n\n\n}\n\n#endif // BEZIER_TOOLS_HPP\n", "meta": {"hexsha": "0f22e2e65de9430f20b4530e27960204b02265e8", "size": 705, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cassie_common_toolbox/bezier_tools.hpp", "max_stars_repo_name": "jpreher/cassie_common_toolbox", "max_stars_repo_head_hexsha": "e01065a56e4a0a71607bfe412834a9a8b541fe28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-11T22:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-11T22:56:02.000Z", "max_issues_repo_path": "include/cassie_common_toolbox/bezier_tools.hpp", "max_issues_repo_name": "jpreher/cassie_common_toolbox", "max_issues_repo_head_hexsha": "e01065a56e4a0a71607bfe412834a9a8b541fe28", "max_issues_repo_licenses": ["MIT"], "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/cassie_common_toolbox/bezier_tools.hpp", "max_forks_repo_name": "jpreher/cassie_common_toolbox", "max_forks_repo_head_hexsha": "e01065a56e4a0a71607bfe412834a9a8b541fe28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-04T21:22:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T21:22:53.000Z", "avg_line_length": 28.2, "max_line_length": 77, "alphanum_fraction": 0.7560283688, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5499373657916569}}
{"text": "//\n// Created by jhwangbo on 30.11.16.\n//\n\n#ifndef RAI_TYPEDEF_HPP\n#define RAI_TYPEDEF_HPP\n\n#include <Eigen/Core>\n\nnamespace rai {\n\ntypedef typename Eigen::Matrix<double, 4, 1> Quaternion;\ntypedef typename Eigen::Matrix<double, 3, 1> EulerVector;\ntypedef typename Eigen::Matrix<double, 3, 3> RotationMatrix;\ntypedef typename Eigen::Matrix<double, 4, 4> HomogeneousTransform;\ntypedef typename Eigen::Matrix<double, 3, 1> Position;\ntypedef typename Eigen::Matrix<double, 3, 1> AngularVelocity;\ntypedef typename Eigen::Matrix<double, 3, 1> AngularAcceleration;\ntypedef typename Eigen::Matrix<double, 3, 1> LinearVelocity;\ntypedef typename Eigen::Matrix<double, 3, 1> LinearAcceleration;\ntypedef typename Eigen::Matrix<double, 3, 1> Axis;\ntypedef typename Eigen::Matrix<double, 3, 1> Torque;\ntypedef typename Eigen::Matrix<double, 3, 1> Force;\ntypedef typename Eigen::Matrix<double, 3, 3> Inertia;\n\ntypedef typename Eigen::Matrix<float, 4, 1> Quaternionf;\ntypedef typename Eigen::Matrix<float, 3, 1> EulerVectorf;\ntypedef typename Eigen::Matrix<float, 3, 3> RotationMatrixf;\ntypedef typename Eigen::Matrix<float, 3, 1> Positionf;\ntypedef typename Eigen::Matrix<float, 3, 1> AngularVelocityf;\ntypedef typename Eigen::Matrix<float, 3, 1> AngularAccelerationf;\ntypedef typename Eigen::Matrix<float, 3, 1> LinearVelocityf;\ntypedef typename Eigen::Matrix<float, 3, 1> LinearAccelerationf;\ntypedef typename Eigen::Matrix<float, 3, 1> Axisf;\ntypedef typename Eigen::Matrix<float, 3, 1> Torquef;\ntypedef typename Eigen::Matrix<float, 3, 1> Forcef;\ntypedef typename Eigen::Matrix<float, 3, 3> Inertiaf;\n\ntypedef typename Eigen::MatrixXd MatrixXd;\ntypedef typename Eigen::VectorXd VectorXd;\n\n}\n\n#endif //RAI_TYPEDEF_HPP\n", "meta": {"hexsha": "281fd29d0c29530efe18eb8a881c638a24e897c1", "size": 1706, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/raiCommon/TypeDef.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/TypeDef.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/TypeDef.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": 37.9111111111, "max_line_length": 66, "alphanum_fraction": 0.7731535756, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5499373657916569}}
{"text": "/*\n * @Description: ceres residual block for LIO IMU pre-integration measurement\n * @Author: Ge Yao\n * @Date: 2020-11-29 15:47:49\n */\n#ifndef LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_FACTOR_PRVAG_IMU_PRE_INTEGRATION_HPP_\n#define LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_FACTOR_PRVAG_IMU_PRE_INTEGRATION_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 FactorPRVAGIMUPreIntegration : public ceres::SizedCostFunction<15, 15, 15> {\npublic:\n\tstatic const int INDEX_P = 0;\n\tstatic const int INDEX_R = 3;\n\tstatic const int INDEX_V = 6;\n\tstatic const int INDEX_A = 9;\n\tstatic const int INDEX_G = 12;\n\n  FactorPRVAGIMUPreIntegration(void) {};\n\n\tvoid SetT(const double &T) {\n\t\tT_ = T;\n\t}\n\n\tvoid SetGravitiy(const Eigen::Vector3d &g) {\n\t\tg_ = g;\n\t}\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\tvoid SetJacobian(const Eigen::MatrixXd &J) {\n\t\tJ_ = J;\n\t}\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\t\tEigen::Map<const Eigen::Vector3d>     vel_i(&parameters[0][INDEX_V]);\n\t\tEigen::Map<const Eigen::Vector3d>     b_a_i(&parameters[0][INDEX_A]);\n\t\tEigen::Map<const Eigen::Vector3d>     b_g_i(&parameters[0][INDEX_G]);\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\t\tEigen::Map<const Eigen::Vector3d>     vel_j(&parameters[1][INDEX_V]);\n\t\tEigen::Map<const Eigen::Vector3d>     b_a_j(&parameters[1][INDEX_A]);\n\t\tEigen::Map<const Eigen::Vector3d>     b_g_j(&parameters[1][INDEX_G]);\n\n    //\n    // parse measurement:\n    // \n\t\tconst Eigen::Vector3d &alpha_ij = m_.block<3, 1>(INDEX_P, 0);\n\t\tconst Eigen::Vector3d &theta_ij = m_.block<3, 1>(INDEX_R, 0);\n\t\tconst Eigen::Vector3d  &beta_ij = m_.block<3, 1>(INDEX_V, 0);\n\n    //\n    // TODO: get square root of information matrix:\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        // a. residual, position:\n\n        // b. residual, orientation:\n\n        // c. residual, velocity:\n\n        // d. residual, bias accel:\n\n        // d. residual, bias accel:\n      }\n\n      if ( jacobians[1] ) {\n        // a. residual, position:\n\n        // b. residual, orientation:\n\n        // c. residual, velocity:\n\n        // d. residual, bias accel:\n\n        // d. residual, bias accel:\n      }\n    }\n\n    //\n    // TODO: correct residual by square root of information matrix:\n    //\n\t\t\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\tdouble T_ = 0.0;\n\n\tEigen::Vector3d g_ = Eigen::Vector3d::Zero();\n\n  Eigen::VectorXd m_;\n  Eigen::MatrixXd I_;\n\n\tEigen::MatrixXd J_;\n};\n\n} // namespace sliding_window\n\n#endif // LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_FACTOR_PRVAG_IMU_PRE_INTEGRATION_HPP_\n", "meta": {"hexsha": "d3bf0839329da753343355f0b2e199b844087b3f", "size": 3907, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/factors/factor_prvag_imu_pre_integration.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_imu_pre_integration.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_imu_pre_integration.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.2064516129, "max_line_length": 103, "alphanum_fraction": 0.6224724853, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505964, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5499373552849937}}
{"text": "/*\n * Copyright 2020 Netherlands eScience Center\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 <Eigen/Core>\n#include <Eigen/Dense>\n#include <utility>\n\n#include <Spectra/GenEigsComplexShiftSolver.h>\n#include <Spectra/GenEigsRealShiftSolver.h>\n#include <Spectra/GenEigsSolver.h>\n#include <Spectra/MatOp/DenseGenComplexShiftSolve.h>\n#include <Spectra/MatOp/DenseGenMatProd.h>\n#include <Spectra/MatOp/DenseGenRealShiftSolve.h>\n#include <Spectra/MatOp/DenseSymMatProd.h>\n#include <Spectra/MatOp/DenseSymShiftSolve.h>\n#include <Spectra/MatOp/SymShiftInvert.h>\n#include <Spectra/SymEigsShiftSolver.h>\n#include <Spectra/SymEigsSolver.h>\n#include <Spectra/SymGEigsShiftSolver.h>\n\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n\nnamespace py = pybind11;\n\nusing ComplexMatrix = Eigen::MatrixXcd;\nusing ComplexVector = Eigen::VectorXcd;\nusing Matrix = Eigen::MatrixXd;\nusing Vector = Eigen::VectorXd;\nusing Eigen::Index;\n\nSpectra::SortRule string_to_sortrule(const std::string& name)\n{\n    std::unordered_map<std::string, Spectra::SortRule> rules = {\n        {\"LargestMagn\", Spectra::SortRule::LargestMagn},\n        {\"LargestReal\", Spectra::SortRule::LargestReal},\n        {\"LargestImag\", Spectra::SortRule::LargestImag},\n        {\"LargestAlge\", Spectra::SortRule::LargestAlge},\n        {\"SmallestMagn\", Spectra::SortRule::SmallestMagn},\n        {\"SmallestReal\", Spectra::SortRule::SmallestReal},\n        {\"SmallestImag\", Spectra::SortRule::SmallestImag},\n        {\"SmallestAlge\", Spectra::SortRule::SmallestAlge},\n        {\"BothEnds\", Spectra::SortRule::BothEnds}};\n    auto it = rules.find(name);\n    if (it != rules.cend())\n    {\n        return it->second;\n    }\n    else\n    {\n        std::ostringstream oss;\n        oss << \"There is no selection rule named: \" << name << \"\\n\"\n            << \"Available selection rules:\\n\";\n        for (const auto& pair : rules)\n        {\n            oss << pair.first << \"\\n\";\n        }\n        throw std::runtime_error(oss.str());\n    }\n}\n\n/// \\brief Run the computation and throw and error if it fails\ntemplate <typename ResultVector, typename ResultMatrix, typename Solver>\nstd::pair<ResultVector, ResultMatrix> compute_and_check(\n    Solver& eigs, const std::string& selection)\n{\n    // Initialize and compute\n    eigs.init();\n    // Compute using the user provided selection rule\n    eigs.compute(string_to_sortrule(selection));\n\n    // Retrieve results\n    if (eigs.info() == Spectra::CompInfo::Successful)\n    {\n        return std::make_pair(eigs.eigenvalues(), eigs.eigenvectors());\n    }\n    else\n    {\n        throw std::runtime_error(\n            \"The Spectra SymEigsSolver calculation has failed!\");\n    }\n}\n\n/// \\brief Call the Spectra::GenEigsSolver eigensolver\nstd::pair<ComplexVector, ComplexMatrix> geneigssolver(\n    const Matrix& mat, Index nvalues, Index nvectors,\n    const std::string& selection)\n{\n    using DenseOp = Spectra::DenseGenMatProd<double>;\n\n    // Construct matrix operation object using the wrapper class DenseSymMatProd\n    Spectra::DenseGenMatProd<double> op(mat);\n    Spectra::GenEigsSolver<double, DenseOp> eigs(op, nvalues, nvectors);\n    return compute_and_check<ComplexVector, ComplexMatrix>(eigs, selection);\n}\n\n/// \\brief Call the Spectra::GenEigsRealShiftSolver eigensolver\nstd::pair<ComplexVector, ComplexMatrix> geneigsrealshiftsolver(\n    const Matrix& mat, Index nvalues, Index nvectors, double sigma,\n    const std::string& selection)\n{\n    using DenseOp = Spectra::DenseGenRealShiftSolve<double>;\n    DenseOp op(mat);\n    Spectra::GenEigsRealShiftSolver<double, DenseOp> eigs(op, nvalues, nvectors,\n                                                          sigma);\n    return compute_and_check<ComplexVector, ComplexMatrix>(eigs, selection);\n}\n\n/// \\brief Call the Spectra::GenEigsComplexShiftSolver eigensolver\nstd::pair<ComplexVector, ComplexMatrix> geneigscomplexshiftsolver(\n    const Matrix& mat, Index nvalues, Index nvectors, double sigmar,\n    double sigmai, const std::string& selection)\n{\n    using DenseOp = Spectra::DenseGenComplexShiftSolve<double>;\n    DenseOp op(mat);\n    Spectra::GenEigsComplexShiftSolver<double, DenseOp> eigs(\n        op, nvalues, nvectors, sigmar, sigmai);\n    return compute_and_check<ComplexVector, ComplexMatrix>(eigs, selection);\n}\n\n/// \\brief Call the Spectra::DenseSymMatProd eigensolver\nstd::pair<Vector, Matrix> symeigssolver(const Matrix& mat, Index nvalues,\n                                        Index nvectors,\n                                        const std::string& selection)\n{\n    using DenseSym = Spectra::DenseSymMatProd<double>;\n    // Construct matrix operation object using the wrapper class DenseSymMatProd\n    DenseSym op(mat);\n    Spectra::SymEigsSolver<double, DenseSym> eigs(op, nvalues, nvectors);\n\n    return compute_and_check<Vector, Matrix>(eigs, selection);\n}\n\n/// \\brief Call the Spectra::SymEigsShiftSolver eigensolver\nstd::pair<Vector, Matrix> symeigsshiftsolver(const Matrix& mat, Index nvalues,\n                                             Index nvectors, double sigma,\n                                             const std::string& selection)\n{\n    using DenseSymShift = Spectra::DenseSymShiftSolve<double>;\n    // Construct matrix operation object using the wrapper class DenseSymMatProd\n    DenseSymShift op(mat);\n    Spectra::SymEigsShiftSolver<double, DenseSymShift> eigs(op, nvalues, nvectors,\n                                                            sigma);\n\n    return compute_and_check<Vector, Matrix>(eigs, selection);\n}\n\n/// \\brief Call the Spectra::SymGEigsShiftSolver eigensolver\nstd::pair<Vector, Matrix> symgeneigsshiftsolver(const Matrix& mat_A,\n                                                const Matrix& mat_B, Index nvalues,\n                                                Index nvectors, double sigma,\n                                                const std::string& selection)\n{\n    using SymShiftInvert =\n        Spectra::SymShiftInvert<double, Eigen::Dense, Eigen::Dense>;\n    using DenseSym = Spectra::DenseSymMatProd<double>;\n\n    // Construct matrix operation object using the wrapper class DenseSymMatProd\n    SymShiftInvert op_A(mat_A, mat_B);\n    DenseSym op_B(mat_B);\n    Spectra::SymGEigsShiftSolver<double, SymShiftInvert, DenseSym, Spectra::GEigsMode::ShiftInvert>\n        eigs(op_A, op_B, nvalues, nvectors, sigma);\n\n    return compute_and_check<Vector, Matrix>(eigs, selection);\n}\n\nPYBIND11_MODULE(spectra_dense_interface, m)\n{\n    m.doc() =\n        \"Interface to the C++ spectra library, see: \"\n        \"https://github.com/yixuan/spectra\";\n\n    m.def(\"general_eigensolver\", &geneigssolver,\n          py::return_value_policy::reference_internal);\n\n    m.def(\"general_real_shift_eigensolver\", &geneigsrealshiftsolver,\n          py::return_value_policy::reference_internal);\n\n    m.def(\"general_complex_shift_eigensolver\", &geneigscomplexshiftsolver,\n          py::return_value_policy::reference_internal);\n\n    m.def(\"symmetric_eigensolver\", &symeigssolver,\n          py::return_value_policy::reference_internal);\n\n    m.def(\"symmetric_shift_eigensolver\", &symeigsshiftsolver,\n          py::return_value_policy::reference_internal);\n\n    m.def(\"symmetric_generalized_shift_eigensolver\", &symgeneigsshiftsolver,\n          py::return_value_policy::reference_internal);\n}\n", "meta": {"hexsha": "4a62d900b7665a24f46ee830b7afe452a5928657", "size": 7803, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pyspectra/interface/spectra_dense_interface.cc", "max_stars_repo_name": "NLESC-JCER/pyspectra", "max_stars_repo_head_hexsha": "b7ece1fff537039f3306b23e00812aa1c8ffc729", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T01:52:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T01:52:31.000Z", "max_issues_repo_path": "pyspectra/interface/spectra_dense_interface.cc", "max_issues_repo_name": "NLESC-JCER/pyspectra", "max_issues_repo_head_hexsha": "b7ece1fff537039f3306b23e00812aa1c8ffc729", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-07-03T07:54:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-03T07:59:08.000Z", "max_forks_repo_path": "pyspectra/interface/spectra_dense_interface.cc", "max_forks_repo_name": "NLESC-JCER/pyspectra", "max_forks_repo_head_hexsha": "b7ece1fff537039f3306b23e00812aa1c8ffc729", "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.4384236453, "max_line_length": 99, "alphanum_fraction": 0.6852492631, "num_tokens": 1925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.549937337914038}}
{"text": "/** View a conflict graph as an implication graph and run Tarjan's strongly connected components algorithm */\n\n#include \"cliquetable_scc.hpp\"\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/strong_components.hpp>\n\nusing namespace boost;\n\n\nvoid make_domain_consistent(CliqueTableInstance* inst, IntSet* state_intset)\n{\n\ttypedef adjacency_list<vecS, vecS, bidirectionalS,\n\t        property<vertex_color_t, default_color_type, property<vertex_degree_t,int>>> ImplGraph;\n\ttypedef graph_traits<ImplGraph>::vertex_descriptor Vertex;\n\n\tImplGraph graph(2 * inst->nvars);\n\n\t// cout << \"Clique table:\" << endl;\n\t// inst->print();\n\n\t// For every edge (i,j), we have two arcs (i, not j) and (j, not i)\n\tfor (int i = 0; i < inst->nvars; ++i) {\n\t\tfor (int j = inst->adj[i].get_first(); j != inst->adj[i].get_end(); j = inst->adj[i].get_next(j)) {\n\t\t\tif (i < j && i != inst->get_complement(j)) {\n\t\t\t\tadd_edge(i, inst->get_complement(j), graph);\n\t\t\t\tadd_edge(j, inst->get_complement(i), graph);\n\t\t\t}\n\t\t}\n\t}\n\n\ttypedef graph_traits<ImplGraph>::edge_iterator edge_iterator;\n\tpair<edge_iterator, edge_iterator> ei = edges(graph);\n\n\t// Debugging info\n\t// cout << endl << \"Implication graph:\" << endl;\n\t// for (edge_iterator it = ei.first; it != ei.second; ++it) {\n\t// \tcout << \"(\" << source(*it, graph) << \", \" << target(*it, graph) << \")\" << \" \";\n\t// }\n\t// cout << endl;\n\n\t// Find strongly connected components\n\tint nv = num_vertices(graph);\n\tvector<int> component(nv), discover_time(nv);\n\tvector<default_color_type> color(nv);\n\tvector<Vertex> root(nv);\n\tint num = strong_components(graph, make_iterator_property_map(component.begin(), get(vertex_index, graph)),\n\t                            root_map(make_iterator_property_map(root.begin(), get(vertex_index, graph))).\n\t                            color_map(make_iterator_property_map(color.begin(), get(vertex_index, graph))).\n\t                            discover_time_map(make_iterator_property_map(discover_time.begin(), get(vertex_index, graph))));\n\n\t// cout << num << \" strong components\" << endl;\n\n\t// for (int j = num - 1; j >= 0; --j) {\n\t// \tcout << \"[ \";\n\t// \tfor (int i = 0; i < component.size(); ++i) {\n\t// \t\tif (j == component[i]) {\n\t// \t\t\tcout << i << \" \";\n\t// \t\t}\n\t// \t}\n\t// \tcout << \"] \";\n\t// }\n\n\t// Assert reverse topological ordering\n\tfor (edge_iterator it = ei.first; it != ei.second; ++it) {\n\t\tassert(component[source(*it, graph)] >= component[target(*it, graph)]);\n\t}\n\n\tvector<int> topological_order;\n\tfor (int j = num - 1; j >= 0; --j) {\n\t\tfor (int i = 0; i < (int) component.size(); ++i) {\n\t\t\tif (j == component[i]) {\n\t\t\t\ttopological_order.push_back(i);\n\t\t\t}\n\t\t}\n\t}\n\n\t// cout << \"Topological order:  \";\n\t// for (int i : topological_order) {\n\t// \tcout << i << \" \";\n\t// }\n\t// cout << endl;\n\n\tvector<vector<int>> vertices_in_component(component.size());\n\tfor (int i = 0; i < nv; ++i) {\n\t\tvertices_in_component[component[i]].push_back(i);\n\t}\n\n\t// // Debugging info\n\t// for (int i = 0; i < component.size(); ++i) {\n\t// \tcout << \"Component \" << i << \":  \";\n\t// \tfor (int j : vertices_in_component[i]) {\n\t// \t\tcout << j << \" \";\n\t// \t}\n\t// \tcout << endl;\n\t// }\n\n\t// Traverse components in topological order\n\tvector<set<int>> ancestors(component.size());\n\tfor (int c = nv - 1; c >= 0; --c) {\n\t\tfor (int v : vertices_in_component[c]) {\n\t\t\ttypename graph_traits<ImplGraph>::adjacency_iterator u, u_end;\n\t\t\tfor (tie(u, u_end) = adjacent_vertices(v, graph); u != u_end; ++u) {\n\t\t\t\t// Add current component and its own ancestors to ancestor list of adjacent component\n\t\t\t\tancestors[component[*u]].insert(c);\n\t\t\t\tfor (int ancestor : ancestors[c]) {\n\t\t\t\t\tancestors[component[*u]].insert(ancestor);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// // Debugging info\n\t// for (int i = 0; i < ancestors.size(); ++i) {\n\t// \tcout << \"Component \" << i << \" - ancestors:  \";\n\t// \tfor (int j : ancestors[i]) {\n\t// \t\tcout << j << \" \";\n\t// \t}\n\t// \tcout << endl;\n\t// }\n\n\t// If the same component contains both complement nodes, remove them\n\tfor (int v = 0; v < inst->nvars; ++v) {\n\t\tif (component[v] == component[inst->get_complement(v)]) {\n\t\t\tstate_intset->remove(v);\n\t\t\tstate_intset->remove(inst->get_complement(v));\n\t\t}\n\t}\n\n\t// For each vertex, check if it precedes its component; if so, remove the vertex from the domain\n\tfor (int v = 0; v < nv; ++v) {\n\t\tint complement = component[inst->get_complement(v)];\n\t\tif (ancestors[complement].find(component[v]) != ancestors[complement].end()) {\n\t\t\t// There exists a path from v to complement of v\n\t\t\tstate_intset->remove(v);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "b816484295022041562d3e48e8935bb1d5b2d598", "size": 4498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/problem/cliquetable/cliquetable_scc.cpp", "max_stars_repo_name": "ctjandra/ddopt-bounds", "max_stars_repo_head_hexsha": "aaf7407da930503a17969cee71718ffcf0c1fe96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problem/cliquetable/cliquetable_scc.cpp", "max_issues_repo_name": "ctjandra/ddopt-bounds", "max_issues_repo_head_hexsha": "aaf7407da930503a17969cee71718ffcf0c1fe96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problem/cliquetable/cliquetable_scc.cpp", "max_forks_repo_name": "ctjandra/ddopt-bounds", "max_forks_repo_head_hexsha": "aaf7407da930503a17969cee71718ffcf0c1fe96", "max_forks_repo_licenses": ["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.5942028986, "max_line_length": 125, "alphanum_fraction": 0.6151622944, "num_tokens": 1293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733955639775, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5499373356901127}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2013 Alec Jacobson <alecjacobson@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 \"all_pairs_distances.h\"\n#include <Eigen/Dense>\n\ntemplate <typename Mat>\nIGL_INLINE void igl::all_pairs_distances(\n  const Mat & V,\n  const Mat & U,\n  const bool squared,\n  Mat & D)\n{\n  // dimension should be the same\n  assert(V.cols() == U.cols());\n  // resize output\n  D.resize(V.rows(),U.rows());\n  for(int i = 0;i<V.rows();i++)\n  {\n    for(int j=0;j<U.rows();j++)\n    {\n      D(i,j) = (V.row(i)-U.row(j)).squaredNorm();\n      if(!squared)\n      {\n        D(i,j) = sqrt(D(i,j));\n      }\n    }\n  }\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\n// generated by autoexplicit.sh\ntemplate void igl::all_pairs_distances<Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::Matrix<double, -1, -1, 0, -1, -1> const&, Eigen::Matrix<double, -1, -1, 0, -1, -1> const&, bool, Eigen::Matrix<double, -1, -1, 0, -1, -1>&);\n#endif\n", "meta": {"hexsha": "608cf9b85773608c84336675b7d34ba16c6771f7", "size": 1187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/all_pairs_distances.cpp", "max_stars_repo_name": "aviadtzemah/animation2", "max_stars_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "igl/all_pairs_distances.cpp", "max_issues_repo_name": "aviadtzemah/animation2", "max_issues_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "igl/all_pairs_distances.cpp", "max_forks_repo_name": "aviadtzemah/animation2", "max_forks_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 29.675, "max_line_length": 229, "alphanum_fraction": 0.6259477675, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5499195630806024}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n#include \"vertex_degree.h\"\n#include <igl/edges.h>\n#include <Eigen/Dense>\n#include <iostream>\n////////////////////////////////////////////////////////////////////////////////\n\nnamespace cellogram {\n\n// -----------------------------------------------------------------------------\n\nvoid vertex_degree(const Eigen::MatrixXi &F, Eigen::VectorXi &degree)\n{\n\tdegree = Eigen::VectorXi::Zero(F.maxCoeff()+1);\n\t/*for (int i = 0; i < F.rows(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tdegree(F(i, j))++;\n\t\t\tdegree(F(i, (j + 1) % 3))++;\n\t\t}\n\t}*/\n\n\tEigen::MatrixXi E;\n\tigl::edges(F, E);\n\n\t//std::cout << E.transpose() << std::endl;\n\n\tfor (int i = 0; i < E.rows(); i++)\n\t{\n\t\tfor (int j = 0; j < 2; j++)\n\t\t{\n\t\t\tdegree(E(i, j))++;\n\t\t\tdegree(E(i, (j + 1) % 2))++;\n\t\t}\n\n\t}\n\tdegree /= 2;\n}\n\n// -----------------------------------------------------------------------------\n\n} // namespace cellogram\n", "meta": {"hexsha": "357e701b60efd8054f2558ed646dbcbe6fcb77f3", "size": 965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cellogram/vertex_degree.cpp", "max_stars_repo_name": "cellogram/cellogram", "max_stars_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-09-25T15:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T08:17:44.000Z", "max_issues_repo_path": "src/cellogram/vertex_degree.cpp", "max_issues_repo_name": "cellogram/cellogram", "max_issues_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cellogram/vertex_degree.cpp", "max_forks_repo_name": "cellogram/cellogram", "max_forks_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-14T01:36:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-11T20:27:57.000Z", "avg_line_length": 21.9318181818, "max_line_length": 80, "alphanum_fraction": 0.3523316062, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.5499195504987605}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n//#define GRAPHBLAS_LOGGING_LEVEL 2\n\n#include <graphblas/graphblas.hpp>\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE mxm_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nusing namespace grb;\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n//****************************************************************************\n\nnamespace\n{\n    static std::vector<std::vector<double> > A_dense_3x3 =\n    {{12, 7, 3},\n     {4,  5, 6},\n     {7,  8, 9}};\n\n    static std::vector<std::vector<double> > AT_dense_3x3 =\n    {{12, 4, 7},\n     {7,  5, 8},\n     {3,  6, 9}};\n\n    static std::vector<std::vector<double> > B_dense_3x4 =\n    {{5, 8, 1, 2},\n     {6, 7, 3, 0.},\n     {4, 5, 9, 1}};\n\n    static std::vector<std::vector<double> > BT_dense_3x4 =\n    {{5, 6, 4},\n     {8, 7, 5},\n     {1, 3, 9},\n     {2, 0, 1}};\n\n    static std::vector<std::vector<double> > Answer_dense =\n    {{114, 160, 60,  27},\n     {74,  97,  73,  14},\n     {119, 157, 112, 23}};\n\n    static std::vector<std::vector<double> > Answer_plus1_dense =\n    {{115, 161, 61,  28},\n     {75,  98,  74,  15},\n     {120, 158, 113, 24}};\n\n    static std::vector<std::vector<double> > A_sparse_3x3 =\n    {{12, 7,  0},\n     {0, -5,  0},\n     {7,  0,  9}};\n\n    static std::vector<std::vector<double> > AT_sparse_3x3 =\n    {{12, 0,  7},\n     {7, -5,  0},\n     {0,  0,  9}};\n\n    static std::vector<std::vector<double> > B_sparse_3x4 =\n    {{5., 8.,  0, -2.},\n     {0., -7,  3., 0.},\n     {4., 0,   0,  1.}};\n\n    static std::vector<std::vector<double> > BT_sparse_3x4 =\n    {{5.,  0., 4},\n     {8., -7,  0.},\n     {0.,  3,  0.},\n     {-2., 0,  1}};\n\n    // A_sparse_3x3 * A_sparse_3x3\n    static std::vector<std::vector<double> > AA_answer_sparse =\n    {{144.,  49., 0},\n     {0.0,   25., 0},\n     {147.,  49., 81.}};\n\n    // A_sparse_3x3 * B_sparse_3x4\n    static std::vector<std::vector<double> > Answer_sparse =\n    {{60,   47., 21,  -24},\n     {0.0,  35.,-15,  0.0},\n     {71.0, 56,  0.0, -5.0}};\n\n    static std::vector<std::vector<double> > Symmetric_4x4 =\n    {{1, 1, 0, 0},\n     {1, 2, 2, 0},\n     {0, 2, 3, 3},\n     {0, 0, 3, 4}};\n\n    static std::vector<std::vector<double> > Symmetric2_4x4 =\n    {{2, 3, 2, 0},\n     {3, 9,10, 6},\n     {2,10,22,21},\n     {0, 6,21,25}};\n\n    static std::vector<std::vector<double> > Ones_4x4 =\n    {{1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > Ones_3x4 =\n    {{1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > Ones_3x3 =\n    {{1, 1, 1},\n     {1, 1, 1},\n     {1, 1, 1}};\n\n    static std::vector<std::vector<double> > Identity_3x3 =\n    {{1, 0, 0},\n     {0, 1, 0},\n     {0, 0, 1}};\n\n    static std::vector<std::vector<double> > Lower_3x3 =\n    {{1, 0, 0},\n     {1, 1, 0},\n     {1, 1, 1}};\n\n    static std::vector<std::vector<double> > Lower_3x4 =\n    {{1, 0, 0, 0},\n     {1, 1, 0, 0},\n     {1, 1, 1, 0}};\n\n    static std::vector<std::vector<double> > Lower_4x4 =\n    {{1, 0, 0, 0},\n     {1, 1, 0, 0},\n     {1, 1, 1, 0},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > NotLower_3x3 =\n    {{0, 1, 1},\n     {0, 0, 1},\n     {0, 0, 0}};\n\n    static std::vector<std::vector<double> > NotLower_3x4 =\n    {{0, 1, 1, 1},\n     {0, 0, 1, 1},\n     {0, 0, 0, 1}};\n\n    static std::vector<std::vector<double> > NotLower_4x4 =\n    {{0, 1, 1, 1},\n     {0, 0, 1, 1},\n     {0, 0, 0, 1},\n     {0, 0, 0, 0}};\n\n    static std::vector<std::vector<double> > LowerMask_3x4 =\n    {{1, 0,    0,   0},\n     {1, 0.5,  0,   0},\n     {1, -1.0, 1.5, 0}};\n\n    static std::vector<std::vector<bool> > LowerBool_3x4 =\n    {{true, false, false, false},\n     {true, true,  false, false},\n     {true, true,  true,  false}};\n\n    static std::vector<std::vector<bool> > LowerBool_3x3 =\n    {{true, false, false},\n     {true, true,  false},\n     {true, true,  true}};\n\n    static std::vector<std::vector<bool> > NotLowerBool_3x3 =\n    {{false,  true, true},\n     {false, false, true},\n     {false, false, false}};\n\n}\n\n//****************************************************************************\n// NoMask_NoAccum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB)\n{\n    grb::Matrix<double> C(3, 4);\n    grb::Matrix<double> A(AT_sparse_3x3, 0.);\n    grb::Matrix<double> B(B_sparse_3x4, 0.);\n\n    grb::Matrix<double> answer(Answer_sparse, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    for (grb::IndexType ix = 0; ix < answer.nrows(); ++ix)\n    {\n        for (grb::IndexType iy = 0; iy < answer.ncols(); ++iy)\n        {\n            BOOST_CHECK_EQUAL(C.hasElement(ix, iy), answer.hasElement(ix, iy));\n            if (C.hasElement(ix, iy))\n            {\n                BOOST_CHECK_CLOSE(C.extractElement(ix,iy),\n                                  answer.extractElement(ix,iy), 0.0001);\n            }\n        }\n    }\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_empty)\n{\n    grb::Matrix<double> Zero(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(Ones_3x3, 0.);\n    grb::Matrix<double> mD(Ones_3x3, 0.);\n\n    grb::mxm(C,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Zero), Ones);\n    BOOST_CHECK_EQUAL(C, Zero);\n\n    grb::mxm(mD,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Zero);\n    BOOST_CHECK_EQUAL(mD, Zero);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_dense)\n{\n    Matrix<double, DirectedMatrixTag> A(AT_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(B_dense_3x4, 0.);\n\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n\n    mxm(result,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(A), B);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 7, 15},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11, 15}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    std::vector<std::vector<double>> answer_vals = {{0, 8, 0, 8},\n                                                    {0, 1, 0, 1},\n                                                    {0, 4, 0, 4}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_ABdup)\n{\n    // Build some matrices.\n    Matrix<double, DirectedMatrixTag> mat(Symmetric_4x4, 0.);\n    Matrix<double, DirectedMatrixTag> m3(4, 4);\n    Matrix<double, DirectedMatrixTag> answer(Symmetric2_4x4, 0.);\n\n    mxm(m3,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(m3, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_ACdup)\n{\n    grb::Matrix<double> C(AT_sparse_3x3, 0.);\n    grb::Matrix<double> B(A_sparse_3x3, 0.);\n\n    grb::Matrix<double> answer(AA_answer_sparse, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), B);\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_BCdup)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.);\n    grb::Matrix<double> C(B_sparse_3x4, 0.);\n\n    grb::Matrix<double> answer(Answer_sparse, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n//****************************************************************************\n// NoMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATB)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.); // 3x3\n    grb::Matrix<double> B(B_dense_3x4, 0.); // 3x4\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(Answer_dense, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATB_empty)\n{\n    grb::Matrix<double> Zero(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(Ones_3x3, 0.);\n    grb::Matrix<double> mD(Ones_3x3, 0.);\n\n    grb::mxm(C,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Zero), Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    grb::mxm(mD,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Zero);\n    BOOST_CHECK_EQUAL(mD, Ones);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATB_stored_zero_result)\n{\n    // Build some matrices.\n    std::vector<std::vector<int> > B_mat = {{ 1,-2, 0,  0},\n                                            {-1, 1, 0,  0},\n                                            { 0, 0, 3, -4},\n                                            { 0, 0,-3,  3}};\n    grb::Matrix<double> A(Symmetric_4x4, 0);\n    grb::Matrix<int> B(B_mat, 0);\n    grb::Matrix<int> result(4, 4);\n\n    // use a different sentinel value so that stored zeros are preserved.\n    int const NIL(666);\n    std::vector<std::vector<int> > ans = {{  0,  -1, NIL, NIL},\n                                          { -1,   0,   6,  -8},\n                                          { -2,   2,   0,  -3},\n                                          {NIL, NIL,  -3,   0}};\n    grb::Matrix<int> answer(ans, NIL);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<int>(),\n             grb::ArithmeticSemiring<int>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(result, answer);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATB_ABdup_Cempty)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> result(4, 4);\n    grb::Matrix<double> answer(Symmetric2_4x4, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    std::vector<std::vector<double>> answer_vals = {{2, 1, 8, 16},\n                                                    {1, 1, 1, 1},\n                                                    {10,1, 12, 16}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> result(Ones_3x4, 0.);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    std::vector<std::vector<double>> answer_vals = {{1, 9, 1, 9},\n                                                    {1, 2, 1, 2},\n                                                    {1, 5, 1, 5}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> result(Ones_3x4, 0.);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATB_ABdup)\n{\n    // Build some matrices.\n    Matrix<double> mat(AT_sparse_3x3,0.);\n    Matrix<double> m3(Ones_3x3, 0.);\n\n    // A_sparse_3x3 * A_sparse_3x3 + Ones\n    static std::vector<std::vector<double> > ans =\n        {{194., -34.,  85.},\n         {-34.,  26.,   1.},\n         { 85.,   1,  131.}};\n\n    Matrix<double> answer(ans, 0.);\n\n    mxm(m3,\n        grb::NoMask(), grb::Plus<double>(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(m3, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATB_ACdup)\n{\n    grb::Matrix<double> C(AT_sparse_3x3, 0.);\n    grb::Matrix<double> B(A_sparse_3x3, 0.);\n\n    // A_sparse_3x3 * A_sparse_3x3 + A_sparse_3x3\n    static std::vector<std::vector<double> > ans =\n        {{156.,  49., 7},\n         {7.0,   20., 0},\n         {147.,  49., 90.}};\n    Matrix<double> answer(ans, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), B);\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATB_BCdup)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.);\n    grb::Matrix<double> C(A_sparse_3x3, 0.);\n\n    // A_sparse_3x3 * A_sparse_3x3 + A_sparse_3x3\n    static std::vector<std::vector<double> > ans =\n        {{156.,  56., 0},\n         {0.0,   20., 0},\n         {154.,  49., 90.}};\n    Matrix<double> answer(ans, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n// ****************************************************************************\n// Mask_NoAccum\n// ****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATB)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> AT(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             Ones, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, AT);\n\n    C = Ones;\n    grb::mxm(C,\n             AT, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             Ones, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, AT);\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATBM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATB_Merge_full_mask)\n{\n    Matrix<double, DirectedMatrixTag> A(AT_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(B_dense_3x4, 0.);\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n\n    Matrix<double, DirectedMatrixTag> mask(Ones_3x4, 0.);\n\n    mxm(result,\n        mask, grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(A), B);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATB_mask_not_full)\n{\n    Matrix<double, DirectedMatrixTag> A(AT_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(B_dense_3x4, 0.);\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    Matrix<double, DirectedMatrixTag> mask(Answer_dense, 0.);\n\n    mxm(result,\n        mask, grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(A), B);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATB_Merge_Cones_Mlower_stored_zero)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(Lower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATB_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0},\n                                               {1, 0, 1},\n                                               {0, 0, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATB_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATB_ACdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATB_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATB_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\n// Mask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> AT(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             AT, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             Ones, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBMempty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 15, 7},\n                                                    {0,  0, 1},\n                                                    {0,  0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1,15, 7},\n                                                     {1, 1, 1},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_ACdup)\n{\n\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  0,  0,  0},\n                                             {4, 10,  0,  0},\n                                             {3, 11, 23,  0},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_Replace_lower_mask_result_ones)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(LowerMask_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_Replace_bool_masked_result_ones)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<bool> M(LowerBool_3x4, false);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_Replace_mask_stored_zero_result_ones)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(Lower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B,\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_Merge_Cones_Mlower)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > M_3x4 = {{1, 0, 0, 0},\n                                                      {1, 1, 0, 0},\n                                                      {1, 1, 1, 0}};\n    grb::Matrix<double> M(M_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompMask_NoAccum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATB)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> AT(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > Not_AT_sparse_3x3 =\n        {{0,  1,  0},\n         {0,  0,  1},\n         {1,  1,  0}};\n    grb::Matrix<double> NotAT(Not_AT_sparse_3x3, 0.0);\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 1,  7},\n         {7, -5,  1},\n         {1,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, AT);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotAT), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, AT);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATB_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> Identity(Identity_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Ones);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATB_Merge_Cones_Mlower_stored_zero)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             complement(M),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATB_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0},\n                                               {1, 0, 1},\n                                               {0, 0, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x3, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATB_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATB_ACdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATB_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATB_Replace_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    static std::vector<std::vector<double> > Not_A_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_3x3, 0.0);\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotA), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Empty), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> MNotLower(NotLowerBool_3x3, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_ACdup)\n{\n\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_Replace_Cones_Mnlower)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B,\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_Replace_Mstored_zero)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n\n    M.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B,\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_Merge)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_Merge_Mstored_zero)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_Merge_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// Structure tests\n//****************************************************************************\n\n// ****************************************************************************\n// StructMask_NoAccum\n// ****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATB)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> AT(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, AT);\n    Ones.setElement(0, 0, 1.);\n\n    C = Ones;\n    AT.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(AT), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, AFilled);\n    AT.setElement(0, 0, 12.);\n\n    C = Ones;\n    MLower.setElement(2, 0, 0.);\n    grb::mxm(C,\n             structure(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    MNotLower.setElement(0, 2, 0.);\n    grb::mxm(C,\n             structure(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, AT);\n    Ones.setElement(0, 0, 1.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    MLower.setElement(2, 0, 1.);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    MNotLower.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATBM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n    M.setElement(2, 0, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATB_Merge_full_mask)\n{\n    Matrix<double, DirectedMatrixTag> A(AT_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(B_dense_3x4, 0.);\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n\n    Matrix<double, DirectedMatrixTag> mask(Ones_3x4, 0.);\n    mask.setElement(0, 0, 0.);\n\n    mxm(result,\n        structure(mask), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(A), B);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATB_mask_not_full)\n{\n    Matrix<double, DirectedMatrixTag> A(AT_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(B_dense_3x4, 0.);\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    Matrix<double, DirectedMatrixTag> mask(Answer_dense, 0.);\n    mask.setElement(0, 0, 0.);\n\n    mxm(result,\n        structure(mask), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(A), B);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 1, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATB_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0},\n                                               {1, 0, 1},\n                                               {0, 0, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATB_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATB_ACdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATB_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATB_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             structure(C),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             structure(C),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\n// StructMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATB)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> AT(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    MLower.setElement(2, 0, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n    MNotLower.setElement(0, 1, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mfull vs Mlower\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    AT.setElement(2, 0, 0.);\n    grb::mxm(C,\n             structure(AT), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mfull vs Mlower\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATBMempty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n    M.setElement(2, 0, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Empty), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Empty), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATB_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 15, 7},\n                                                    {0,  0, 1},\n                                                    {0,  0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1,15, 7},\n                                                     {1, 1, 1},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATB_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATB_ACdup)\n{\n\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATB_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATB_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  0,  0,  0},\n                                             {4, 10,  0,  0},\n                                             {2, 11, 23,  0},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             structure(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {2, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             structure(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATB_Replace_lower_mask_result_ones)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(LowerMask_3x4, 0.);\n    M.setElement(2, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             structure(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATB_Replace_bool_masked_result_ones)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<bool> M(LowerBool_3x4, false);\n    M.setElement(2, 0, false);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             structure(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATB_Merge_Cones_Mlower)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > M_3x4 = {{1, 0, 0, 0},\n                                                      {1, 1, 0, 0},\n                                                      {1, 1, 1, 0}};\n    grb::Matrix<double> M(M_3x4, 0.);\n    M.setElement(2, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             structure(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompStructMask_NoAccum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATB)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> AT(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    MLower.setElement(2, 0, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n    MNotLower.setElement(0, 2, 0.);\n\n    static std::vector<std::vector<double> > Not_AT_sparse_3x3 =\n        {{0,  1,  0},\n         {0,  0,  1},\n         {1,  1,  0}};\n    grb::Matrix<double> NotAT(Not_AT_sparse_3x3, 0.0);\n    NotAT.setElement(0, 1, 0.);\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 1,  7},\n         {7, -5,  1},\n         {1,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, AT);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotAT)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n    Ones.setElement(0, 0, 1.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, AT);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    MLower.setElement(2, 0, 1.);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    MNotLower.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATB_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> Identity(Identity_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n    M.setElement(2, 0, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n    mUpper.setElement(0, 2, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones);\n    mUpper.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    mUpper.setElement(0, 2, 0.);\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty);\n    mUpper.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Ones);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATB_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0},\n                                               {1, 0, 1},\n                                               {0, 0, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x3, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Lower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Lower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATB_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATB_ACdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATB_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATB_Replace_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n    M.setElement(0, 1, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompStructMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATB)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    MLower.setElement(2, 0, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n    MNotLower.setElement(0, 2, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    static std::vector<std::vector<double> > Not_A_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_3x3, 0.0);\n    NotA.setElement(1, 0, 0.);\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotA)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Empty)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATBM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> MNotLower(NotLowerBool_3x3, false);\n    MNotLower.setElement(0, 2, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    Ones.setElement(0, 2, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Ones);\n    Ones.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    Ones.setElement(0, 2, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x4, 0.);\n    MNotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATB_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATB_ACdup)\n{\n\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATB_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATB_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  0,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {99, 6, 21, 25}};\n    grb::Matrix<double> answer(ans, 99.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(structure(C)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(structure(C)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATB_Replace_Cones_Mnlower)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B,\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATB_Merge)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATB_Merge_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n    M.setElement(0, 1, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "9f535ee90d152a3a6aaf80c6b35f0027c639ce8e", "size": 156244, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_mxm_ATB.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_mxm_ATB.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_mxm_ATB.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 33.3569598634, "max_line_length": 83, "alphanum_fraction": 0.4577903792, "num_tokens": 43064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5499195504987605}}
{"text": "#include \"cutting_plane.hpp\"\r\n#include \"ell.hpp\"\r\n#include \"profit_oracle.hpp\"\r\n#include \"ldlt_ext.hpp\"\r\n//#include <boost/numeric/ublas/symmetric.hpp>\r\n#include <xtensor/xarray.hpp>\r\n#include <xtensor-blas/xlinalg.hpp>\r\n//#include <fmt/format.h>\r\n#include <iostream>\r\n\r\n//#include <boost/numeric/ublas/io.hpp>\r\n\r\n// Versions: (latest first)\r\n// http://melpon.org/wandbox/permlink/CcvL0BHfVJhHZH4M\r\n// http://melpon.org/wandbox/permlink/ExQoromITFQ7WOxO\r\n// http://melpon.org/wandbox/permlink/YiLtKIriWtkigZs8\r\n\r\nint test1() {\r\n  //namespace bnu = boost::numeric::ublas;\r\n  //using Vec = bnu::vector<double>;\r\n  //using Mat = xt::xarray<double, xt::layout_type::row_major>;\r\n  using Vec = xt::xarray<double, xt::layout_type::row_major>;\r\n \r\n  double p = 20, A = 40, alpha = 0.1, beta = 0.4;\r\n  double v1 = 10, v2 = 35, k = 30.5;\r\n  double fb;\r\n  int niter, status;\r\n  bool feasible;\r\n\r\n  {\r\n    ell E(100., Vec{0., 0.});\r\n    profit_oracle P(p, A, alpha, beta, v1, v2, k);\r\n    std::tie(std::ignore, fb, niter, feasible, status) =\r\n        cutting_plane_dc(P, E, 0.);\r\n    // fmt::print(\"{:f} {} {} {} \\n\", fb, niter, feasible, status);\r\n    std::cout << fb << \", \" << niter << \", \" << feasible << \", \" << status << \"\\n\";\r\n  }\r\n\r\n  double ui = 1., e1 = 0.003, e2 = 0.007, e3 = 1.;\r\n\r\n  {\r\n    ell E1(100., Vec{0., 0.});\r\n    profit_rb_oracle P1(p, A, alpha, beta, v1, v2, k, ui, e1, e2, e3);\r\n    std::tie(std::ignore, fb, niter, feasible, status) =\r\n        cutting_plane_dc(P1, E1, 0.);\r\n    // fmt::print(\"{:f} {} {} {} \\n\", fb, niter, feasible, status);\r\n    std::cout << fb << \", \" << niter << \", \" << feasible << \", \" << status\r\n              << \"\\n\";\r\n  }\r\n\r\n  {\r\n    ell E2(100., Vec{2., 0.});\r\n    profit_q_oracle P2(p, A, alpha, beta, v1, v2, k);\r\n    std::tie(std::ignore, fb, niter, feasible, status) =\r\n        cutting_plane_q(P2, E2, 0.);\r\n    // fmt::print(\"{:f} {} {} {} \\n\", fb, niter, feasible, status);\r\n    std::cout << fb << \", \" << niter << \", \" << feasible << \", \" << status\r\n             << \"\\n\";\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\nint main() {\r\n  using Arr = xt::xarray<double, xt::layout_type::row_major>;\r\n  using xt::placeholders::_;\r\n  using xt::linalg::dot;\r\n\r\n  auto m1 = Arr({{25., 15., -5.},\r\n                {15., 18.,  0.},\r\n                {-5.,  0., 11.}});\r\n  std::cout << m1.shape()[0] << \"\\n\";\r\n  auto Q1 = ldlt_ext(m1.shape()[0]);\r\n  Q1.factorize(m1);\r\n  if (!Q1.is_sd()) {\r\n    auto v = Q1.witness();\r\n    auto p = v.size();\r\n    auto sub = xt::range(0, p);\r\n    Arr App = xt::view(m1, sub, sub);\r\n    Arr Appv = dot(App, v);\r\n    auto fj = -dot(v, Appv)();\r\n    std::cout << fj << std::endl;\r\n  }\r\n\r\n\r\n  auto m2 = Arr({{18., 22.,  54.,  42.},\r\n                {22., -70.,  86.,  62.},\r\n                {54., 86., -174., 134.},\r\n                {42., 62., 134., -106.}});\r\n  std::cout << m2.shape()[0] << \"\\n\";\r\n  auto Q2 = ldlt_ext(m2.shape()[0]);\r\n  Q2.factorize(m2);\r\n  if (!Q2.is_sd()) {\r\n    auto v = Q2.witness();\r\n    auto p = v.size();\r\n    auto sub = xt::range(0, p);\r\n    Arr App = xt::view(m2, sub, sub);\r\n    Arr Appv = dot(App, v);\r\n    auto fj = -dot(v, Appv)();\r\n    std::cout << fj << std::endl;\r\n  }\r\n\r\n  return 0;\r\n}", "meta": {"hexsha": "7a47ba2c56fa439289366e8488b55f1b326e60ba", "size": 3167, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "app/src/profit_main.tpp", "max_stars_repo_name": "luk036/ellcpp", "max_stars_repo_head_hexsha": "3415e7ffb70b63edb9ce4d6c2b9fee92898538bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-26T04:58:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T06:29:59.000Z", "max_issues_repo_path": "app/src/profit_main.tpp", "max_issues_repo_name": "luk036/ellcpp", "max_issues_repo_head_hexsha": "3415e7ffb70b63edb9ce4d6c2b9fee92898538bc", "max_issues_repo_licenses": ["MIT"], "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/src/profit_main.tpp", "max_forks_repo_name": "luk036/ellcpp", "max_forks_repo_head_hexsha": "3415e7ffb70b63edb9ce4d6c2b9fee92898538bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-06-03T08:20:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-30T10:41:49.000Z", "avg_line_length": 30.4519230769, "max_line_length": 84, "alphanum_fraction": 0.509314809, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5499033949414339}}
{"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// Critical temperature of hexagonal lattice Ising model\n\n#pragma once\n\n#include <cmath>\n#include <stdexcept>\n#include <boost/math/differentiation/autodiff.hpp>\n#include <standards/newton.hpp>\n\nnamespace {\n  \ntemplate<typename T>\nstruct func {\n  func(T Ja, T Jb, T Jc) : Ja_(Ja), Jb_(Jb), Jc_(Jc) {}\n  auto operator()(T beta) const -> decltype(boost::math::differentiation::make_fvar<T, 2>(beta)) {\n    using std::tanh;\n    auto beta_fvar = boost::math::differentiation::make_fvar<T, 2>(beta);\n    auto za = tanh(beta_fvar * Ja_);\n    auto zb = tanh(beta_fvar * Jb_);\n    auto zc = tanh(beta_fvar * Jc_);\n    return za * zb + zb * zc + zc * za - 1;\n  }\n  T Ja_, Jb_, Jc_;\n};\n\n}\n\nnamespace ising {\nnamespace tc {\n\ntemplate<typename T>\ninline T hexagonal(T Ja, T Jb, T Jc) {\n  Ja = abs(Ja);\n  Jb = abs(Jb);\n  Jc = abs(Jc);\n  if (Ja * Jb * Jc <= 0) throw(std::invalid_argument(\"Ja * Jb * Jc should be non-zero\"));\n  auto result = standards::newton_1d(func<T>(Ja, Jb, Jc), 1 / (Ja + Jb + Jc));\n  if (!result.second) throw(std::runtime_error(\"convergence error\"));\n  return 1 / result.first;\n}\n\n} // end namespace tc\n} // end namespace ising\n", "meta": {"hexsha": "55b4198ffdd04248c56a91dfd81dd3660c356e36", "size": 1767, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ising/tc/hexagonal.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/tc/hexagonal.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/tc/hexagonal.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": 29.45, "max_line_length": 98, "alphanum_fraction": 0.6791171477, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5499033885706802}}
{"text": "#include <boost/numeric/odeint.hpp>\n#include \"stochastic_euler.hpp\"\n#include \"cahnhilliard.h\"\n#include \"cahnhilliard_thermal.h\"\n#include \"cahnhilliard_thermal_nodiffusion.h\"\n#include \"run_ch_solver.h\"\n\nvoid run_ch_solver_non_thermal( CHparamsVector& chparams , SimInfo& info )\n{\n\n  // Instantiate rhs\n  CahnHilliard2DRHS rhs = CahnHilliard2DRHS( chparams , info );\n  \n  std::vector<double> x;\n  if (info.t0 == 0) {\n    rhs.setInitialConditions(x);\n    int iter = 0;\n  }\n  else {\n    x        = info.x;\n    int iter = info.iter;\n  }\n  \n  // define adaptive stepper\n  typedef boost::numeric::odeint::runge_kutta_cash_karp54<std::vector<double>> error_stepper_type;\n\n  // define runge kutta\n  typedef boost::numeric::odeint::controlled_runge_kutta<error_stepper_type> controlled_stepper_type;\n\n  controlled_stepper_type controlled_stepper;\n\n  const double stability_limit = chparams.compute_stability_limit(info.dx , info.dy); // just an estimate\n  const double res0            = rhs.l2residual(x);\n\n  std::cout << \"residual at initial condition: \" << res0 << std::endl;\n  if (info.iter == 0)\n    rhs.write_state(x,0,info.nx,info.ny,info.outdir);\n\n  if (chparams.sigma_noise < 1e-2) {\n    std::cout << \"Solving deterministic (noise-free) CH\" << std::endl;\n    integrate_adaptive(controlled_stepper, rhs, x, info.t0, info.tf, stability_limit/2.);\n    //boost::numeric::odeint::integrate_const(controlled_stepper, rhs, x, info.t0, info.tf, stability_limit/2.);\n  }\n  else {\n    std::cout << \"Solving stochastic CH\" << std::endl;\n    boost::mt19937 rng;\n    boost::numeric::odeint::integrate_const( stochastic_euler() ,\n\t\t     std::make_pair( rhs , ornstein_stoch( rng , chparams.sigma_noise ) ),\n\t\t     x , info.t0 , info.tf , stability_limit/40. );\n  }\n  info.iter += 1;\n  std::cout << \"iter: \" << info.iter << \" , t = \" << info.tf << \", relative residual: \" << rhs.l2residual(x) / res0 << std::endl;\n  rhs.write_state(x,info.iter,info.nx,info.ny,info.outdir);\n  info.x = x;\n\n};\n\n\nvoid run_ch_solver_thermal_no_diffusion( CHparamsVector& chparams , SimInfo& info )\n{\n\n  // Instantiate rhs\n  CahnHilliard2DRHS_thermal_nodiffusion rhs = CahnHilliard2DRHS_thermal_nodiffusion( chparams , info );\n  \n  std::vector<double> x;\n  if (info.t0 == 0) {\n    rhs.setInitialConditions(x);\n    int iter = 0;\n  }\n  else {\n    x        = info.x;\n    int iter = info.iter;\n  }\n  \n  // define adaptive stepper\n  typedef boost::numeric::odeint::runge_kutta_cash_karp54<std::vector<double>> error_stepper_type;\n\n  // define runge kutta\n  typedef boost::numeric::odeint::controlled_runge_kutta<error_stepper_type> controlled_stepper_type;\n\n  controlled_stepper_type controlled_stepper;\n\n  const double stability_limit = chparams.compute_stability_limit(info.dx , info.dy); // just an estimate\n  const double res0            = rhs.l2residual(x);\n\n  std::cout << \"residual at initial condition: \" << res0 << std::endl;\n  if (info.iter == 0)\n    rhs.write_state(x,0,info.nx,info.ny,info.outdir);\n\n  if (chparams.sigma_noise < 1e-2) {\n    std::cout << \"Solving deterministic (noise-free) CH\" << std::endl;\n    integrate_adaptive(controlled_stepper, rhs, x, info.t0, info.tf, stability_limit/2.);\n    //boost::numeric::odeint::integrate_const(controlled_stepper, rhs, x, info.t0, info.tf, stability_limit/2.);\n  }\n  else {\n    std::cout << \"Solving stochastic CH\" << std::endl;\n    boost::mt19937 rng;\n    boost::numeric::odeint::integrate_const( stochastic_euler() ,\n\t\t     std::make_pair( rhs , ornstein_stoch( rng , chparams.sigma_noise ) ),\n\t\t     x , info.t0 , info.tf , stability_limit/40. );\n  }\n  info.iter += 1;\n  std::cout << \"iter: \" << info.iter << \" , t = \" << info.tf << \", relative residual: \" << rhs.l2residual(x) / res0 << std::endl;\n  rhs.write_state(x,info.iter,info.nx,info.ny,info.outdir);\n  info.x = x;\n\n};\n\n\nvoid run_ch_solver_thermal_with_diffusion( CHparamsVector& chparams , SimInfo& info )\n{\n\n  // Instantiate rhs\n  CahnHilliard2DRHS_thermal rhs = CahnHilliard2DRHS_thermal( chparams , info );\n  \n  std::vector<double> x;\n  if (info.t0 == 0) {\n    rhs.setInitialConditions(x);\n    int iter = 0;\n  }\n  else {\n    x        = info.x;\n    int iter = info.iter;\n  }\n  \n  // define adaptive stepper\n  typedef boost::numeric::odeint::runge_kutta_cash_karp54<std::vector<double>> error_stepper_type;\n\n  // define runge kutta\n  typedef boost::numeric::odeint::controlled_runge_kutta<error_stepper_type> controlled_stepper_type;\n\n  controlled_stepper_type controlled_stepper;\n\n  const double stability_limit = chparams.compute_stability_limit(info.dx , info.dy); // just an estimate\n  const double res0            = rhs.l2residual(x);\n\n  std::cout << \"residual at initial condition: \" << res0 << std::endl;\n  if (info.iter == 0)\n    rhs.write_state(x,0,info.nx,info.ny,info.outdir);\n\n  if (chparams.sigma_noise < 1e-2) {\n    std::cout << \"Solving deterministic (noise-free) CH\" << std::endl;\n    integrate_adaptive(controlled_stepper, rhs, x, info.t0, info.tf, stability_limit/2.);\n    //boost::numeric::odeint::integrate_const(controlled_stepper, rhs, x, info.t0, info.tf, stability_limit/2.);\n  }\n  else {\n    std::cout << \"Solving stochastic CH\" << std::endl;\n    boost::mt19937 rng;\n    boost::numeric::odeint::integrate_const( stochastic_euler() ,\n\t\t     std::make_pair( rhs , ornstein_stoch( rng , chparams.sigma_noise ) ),\n\t\t     x , info.t0 , info.tf , stability_limit/40. );\n  }\n  info.iter += 1;\n  std::cout << \"iter: \" << info.iter << \" , t = \" << info.tf << \", relative residual: \" << rhs.l2residual(x) / res0 << std::endl;\n  rhs.write_state(x,info.iter,info.nx,info.ny,info.outdir);\n  info.x = x;\n\n};\n\n\nvoid run_ch_solver_non_thermal( CHparamsScalar& chparams , SimInfo& info )\n{\n\n  // Instantiate rhs\n  CahnHilliard2DRHS rhs = CahnHilliard2DRHS( chparams , info );\n  \n  std::vector<double> x;\n  if (info.t0 == 0) {\n    rhs.setInitialConditions(x);\n    int iter = 0;\n  }\n  else {\n    x        = info.x;\n    int iter = info.iter;\n  }\n  \n  // define adaptive stepper\n  typedef boost::numeric::odeint::runge_kutta_cash_karp54<std::vector<double>> error_stepper_type;\n\n  // define runge kutta\n  typedef boost::numeric::odeint::controlled_runge_kutta<error_stepper_type> controlled_stepper_type;\n\n  controlled_stepper_type controlled_stepper;\n\n  const double stability_limit = chparams.compute_stability_limit(info.dx , info.dy); // just an estimate\n  const double res0            = rhs.l2residual(x);\n\n  std::cout << \"residual at initial condition: \" << res0 << std::endl;\n  if (info.iter == 0)\n    rhs.write_state(x,0,info.nx,info.ny,info.outdir);\n\n  if (chparams.sigma_noise < 1e-2) {\n    std::cout << \"Solving deterministic (noise-free) CH\" << std::endl;\n    integrate_adaptive(controlled_stepper, rhs, x, info.t0, info.tf, stability_limit/2.);\n    //boost::numeric::odeint::integrate_const(controlled_stepper, rhs, x, info.t0, info.tf, stability_limit/2.);\n  }\n  else {\n    std::cout << \"Solving stochastic CH\" << std::endl;\n    boost::mt19937 rng;\n    boost::numeric::odeint::integrate_const( stochastic_euler() ,\n\t\t     std::make_pair( rhs , ornstein_stoch( rng , chparams.sigma_noise ) ),\n\t\t     x , info.t0 , info.tf , stability_limit/40. );\n  }\n  info.iter += 1;\n  std::cout << \"iter: \" << info.iter << \" , t = \" << info.tf << \", relative residual: \" << rhs.l2residual(x) / res0 << std::endl;\n  rhs.write_state(x,info.iter,info.nx,info.ny,info.outdir);\n  info.x = x;\n\n};\n\n\nvoid run_ch_solver_thermal_no_diffusion( CHparamsScalar& chparams , SimInfo& info )\n{\n\n  // Instantiate rhs\n  CahnHilliard2DRHS_thermal_nodiffusion rhs = CahnHilliard2DRHS_thermal_nodiffusion( chparams , info );\n  \n  std::vector<double> x;\n  if (info.t0 == 0) {\n    rhs.setInitialConditions(x);\n    int iter = 0;\n  }\n  else {\n    x        = info.x;\n    int iter = info.iter;\n  }\n  \n  // define adaptive stepper\n  typedef boost::numeric::odeint::runge_kutta_cash_karp54<std::vector<double>> error_stepper_type;\n\n  // define runge kutta\n  typedef boost::numeric::odeint::controlled_runge_kutta<error_stepper_type> controlled_stepper_type;\n\n  controlled_stepper_type controlled_stepper;\n\n  const double stability_limit = chparams.compute_stability_limit(info.dx , info.dy); // just an estimate\n  const double res0            = rhs.l2residual(x);\n\n  std::cout << \"residual at initial condition: \" << res0 << std::endl;\n  if (info.iter == 0)\n    rhs.write_state(x,0,info.nx,info.ny,info.outdir);\n\n  if (chparams.sigma_noise < 1e-2) {\n    std::cout << \"Solving deterministic (noise-free) CH\" << std::endl;\n    integrate_adaptive(controlled_stepper, rhs, x, info.t0, info.tf, stability_limit/2.);\n    //boost::numeric::odeint::integrate_const(controlled_stepper, rhs, x, info.t0, info.tf, stability_limit/2.);\n  }\n  else {\n    std::cout << \"Solving stochastic CH\" << std::endl;\n    boost::mt19937 rng;\n    boost::numeric::odeint::integrate_const( stochastic_euler() ,\n\t\t     std::make_pair( rhs , ornstein_stoch( rng , chparams.sigma_noise ) ),\n\t\t     x , info.t0 , info.tf , stability_limit/40. );\n  }\n  info.iter += 1;\n  std::cout << \"iter: \" << info.iter << \" , t = \" << info.tf << \", relative residual: \" << rhs.l2residual(x) / res0 << std::endl;\n  rhs.write_state(x,info.iter,info.nx,info.ny,info.outdir);\n  info.x = x;\n\n};\n\n\nvoid run_ch_solver_thermal_with_diffusion( CHparamsScalar& chparams , SimInfo& info )\n{\n\n  // Instantiate rhs\n  CahnHilliard2DRHS_thermal rhs = CahnHilliard2DRHS_thermal( chparams , info );\n  \n  std::vector<double> x;\n  if (info.t0 == 0) {\n    rhs.setInitialConditions(x);\n    int iter = 0;\n  }\n  else {\n    x        = info.x;\n    int iter = info.iter;\n  }\n  \n  // define adaptive stepper\n  typedef boost::numeric::odeint::runge_kutta_cash_karp54<std::vector<double>> error_stepper_type;\n\n  // define runge kutta\n  typedef boost::numeric::odeint::controlled_runge_kutta<error_stepper_type> controlled_stepper_type;\n\n  controlled_stepper_type controlled_stepper;\n\n  const double stability_limit = chparams.compute_stability_limit(info.dx , info.dy); // just an estimate\n  const double res0            = rhs.l2residual(x);\n\n  std::cout << \"residual at initial condition: \" << res0 << std::endl;\n  if (info.iter == 0)\n    rhs.write_state(x,0,info.nx,info.ny,info.outdir);\n\n  if (chparams.sigma_noise < 1e-2) {\n    std::cout << \"Solving deterministic (noise-free) CH\" << std::endl;\n    integrate_adaptive(controlled_stepper, rhs, x, info.t0, info.tf, stability_limit/2.);\n    //boost::numeric::odeint::integrate_const(controlled_stepper, rhs, x, info.t0, info.tf, stability_limit/2.);\n  }\n  else {\n    std::cout << \"Solving stochastic CH\" << std::endl;\n    boost::mt19937 rng;\n    boost::numeric::odeint::integrate_const( stochastic_euler() ,\n\t\t     std::make_pair( rhs , ornstein_stoch( rng , chparams.sigma_noise ) ),\n\t\t     x , info.t0 , info.tf , stability_limit/40. );\n  }\n  info.iter += 1;\n  std::cout << \"iter: \" << info.iter << \" , t = \" << info.tf << \", relative residual: \" << rhs.l2residual(x) / res0 << std::endl;\n  rhs.write_state(x,info.iter,info.nx,info.ny,info.outdir);\n  info.x = x;\n\n};\n\nvoid run_ch_solver( CHparamsVector& chparams , SimInfo& info )\n{\n  \n  if      (info.rhs_type.compare(\"ch_non_thermal\") == 0) {\n    run_ch_solver_non_thermal( chparams , info );\n  }\n  else if (info.rhs_type.compare(\"ch_thermal_no_diffusion\") == 0) {\n    run_ch_solver_thermal_no_diffusion( chparams , info );\n  }\n  else if (info.rhs_type.compare(\"ch_thermal_with_diffusion\") == 0) {\n    run_ch_solver_thermal_with_diffusion( chparams , info );\n  }\n\n};\n\nvoid run_ch_solver( CHparamsScalar& chparams , SimInfo& info )\n{\n  \n  if      (info.rhs_type.compare(\"ch_non_thermal\") == 0) {\n    run_ch_solver_non_thermal( chparams , info );\n  }\n  else if (info.rhs_type.compare(\"ch_thermal_no_diffusion\") == 0) {\n    run_ch_solver_thermal_no_diffusion( chparams , info );\n  }\n  else if (info.rhs_type.compare(\"ch_thermal_with_diffusion\") == 0) {\n    run_ch_solver_thermal_with_diffusion( chparams , info );\n  }\n\n};\n", "meta": {"hexsha": "0999bcb243f735ef9d5bee77b5773bcc913375f0", "size": 11906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/run_ch_solver.cpp", "max_stars_repo_name": "ISI-apex/cahnhilliard_2d", "max_stars_repo_head_hexsha": "dc9992866e92ed09b431ebb9612002f207805d18", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-12-21T09:25:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T04:11:59.000Z", "max_issues_repo_path": "cpp/src/run_ch_solver.cpp", "max_issues_repo_name": "exalearn/cahnhilliard_2d", "max_issues_repo_head_hexsha": "cbf272bbac8080ff97c1cc93e7e7246bee04e075", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-07-08T23:06:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-24T18:51:15.000Z", "max_forks_repo_path": "cpp/src/run_ch_solver.cpp", "max_forks_repo_name": "exalearn/cahnhilliard_2d", "max_forks_repo_head_hexsha": "cbf272bbac8080ff97c1cc93e7e7246bee04e075", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-04T01:09:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T01:10:50.000Z", "avg_line_length": 34.8128654971, "max_line_length": 129, "alphanum_fraction": 0.6783974467, "num_tokens": 3504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5499033781664645}}
{"text": "/*    Copyright (c) 2010-2016, 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 *      120203    B. Tong Minh      Copied RungeKutta4Stepsize unit test.\n *      120207    K. Kumar          Adapted to use modified benchmark functions in Tudat Core.\n *      120213    K. Kumar          Modified getCurrentInterval( ) to getIndependentVariable( );\n *                                  transferred to Boost unit test framework.\n *      120321    K. Kumar          Updated (Burden and Faires, 2011) benchmark function call.\n *      120323    K. Kumar          Rewrote unit tests to use benchmark data from\n *                                  (Burden and Faires, 2011); removed test against benchmark\n *                                  functions; renamed file to RFK45 unit test. Other unit tests\n *                                  for other Runge-Kutta methods will appear in other dedicated\n *                                  unit test files.\n *      120327    K. Kumar          Added missing comments; added unit test based on output data\n *                                  generated by (The Mathworks, 2012).\n *      120328    K. Kumar          Moved (Burden and Faires, 2011) test class to its own file;\n *                                  modified MATLAB unit tests to test forward and backwards in\n *                                  time and \"forced\" and \"free\" adaptive step size adjustment and\n *                                  moved to separate file (added call to function to run Matlab\n *                                  tests); added rollback tests for all cases.\n *      120404    K. Kumar          Updated Matlab unit test by adding discrete-event data file.\n *      130118    K. Kumar          Rewrote unit test to make use of testing code for numerical\n *                                  integrators migrated to Tudat Core.\n *      130906    K. Kumar          Updated error tolerances for MuPAD-based tests.\n *\n *      160321    R. Hoogendoorn    Created Runge Kutta 56 test\n *\n *    References\n *      Burden, R.L., Faires, J.D. Numerical Analysis, 7th Edition, Books/Cole, 2001.\n *      Montenbruck, O., Gill, E. Satellite Orbits: Models, Methods, Applications, Springer, 2005.\n *      The MathWorks, Inc. RKF54b, Symbolic Math Toolbox, 2012.\n *\n *    Notes\n *      For the tests using data from the Symbolic Math Toolbox (MathWorks, 2012), the single step\n *      and full integration error tolerances were picked to be as small as possible, without\n *      causing the tests to fail. These values are not deemed to indicate any bugs in the code;\n *      however, it is important to take these discrepancies into account when using this numerical\n *      integrator.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <limits>\n#include <string>\n\n#include <cmath>\n\n#include <Eigen/Core>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaVariableStepSizeIntegrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaCoefficients.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/UnitTests/numericalIntegratorTestFunctions.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_runge_kutta_fehlberg_56_integrator )\n\nusing numerical_integrator_test_functions::computeNonAutonomousModelStateDerivative;\nusing numerical_integrator_test_functions::computeVanDerPolStateDerivative;\nusing numerical_integrator_test_functions::computeFehlbergLogirithmicTestODEStateDerivative;\nusing numerical_integrator_test_functions::computeAnalyticalStateFehlbergODE;\n\nusing namespace numerical_integrators;\n\n//! Compare with analytical solution of Fehlberg\nBOOST_AUTO_TEST_CASE( test_RungeKuttaFehlberg56_Integrator_Fehlberg_Benchmark )\n{\n    RungeKuttaCoefficients coeff56 =\n        RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg56);\n\n    // Integrator settings\n    double minimumStepSize   = std::numeric_limits< double >::epsilon( );\n    double maximumStepSize   = std::numeric_limits< double >::infinity( );\n    double initialStepSize   = 1E-6; // Don't make this too small\n    double relativeTolerance = 1E-16;\n    double absoluteTolerance = 1E-16;\n\n    // Initial conditions\n    double initialTime = 0.0;\n    double finalTime   = 5.0;\n    Eigen::Vector2d initialState( exp( 1.0 ), 1.0);\n\n    // Setup integrator\n    RungeKuttaVariableStepSizeIntegratorXd integrator56(\n                coeff56, computeFehlbergLogirithmicTestODEStateDerivative,\n                initialTime, initialState, minimumStepSize,\n                maximumStepSize, relativeTolerance, absoluteTolerance );\n\n\n    // Obtain numerical solution\n    Eigen::Vector2d numericalSolution = integrator56.integrateTo( finalTime, initialStepSize );\n\n    // Analytical solution\n    // (page 30, Fehlberg, E. (1968). Classical Fifth-, Sixth-, Seventh- and Eigth-Order Runge-Kutta\n    // Formulas with Stepsize Control)\n    Eigen::Vector2d analyticalSolution =\n        computeAnalyticalStateFehlbergODE( finalTime, initialState );\n\n    Eigen::Vector2d computedError = numericalSolution - analyticalSolution;\n    BOOST_CHECK_SMALL( std::fabs( computedError( 0 ) ), 1E-12 );\n    BOOST_CHECK_SMALL( std::fabs( computedError( 1 ) ), 1E-12 );\n\n    // Error calculated by -> Fehlberg, E. (1968) page 30\n    // Initial stepsize unknown..\n    Eigen::VectorXd fehlbergError( 2 );\n    fehlbergError << 0.1072E-12, -0.2190E-12;\n\n    // Sign check\n    // Not always same sign -> initial step size = 1 or 1E-2, failure: computedError( 1 ),\n    // fehlbergError( 1 ) not same sign\n    BOOST_CHECK_GE( computedError( 0 ) / fehlbergError( 0 ), 0.0 );\n    BOOST_CHECK_GE( computedError( 1 ) / fehlbergError( 1 ), 0.0 );\n\n    // Check error is similar in magnitude\n    BOOST_CHECK_SMALL( std::fabs( computedError( 0 ) / fehlbergError( 0 ) ), 3.0);\n    BOOST_CHECK_SMALL( std::fabs( computedError( 1 ) / fehlbergError( 1 ) ), 1.0);\n}\n\n\n//! Test Compare with Runge Kutta 78\nBOOST_AUTO_TEST_CASE( test_RungeKuttaFehlberg56_Integrator_Compare78 )\n{\n    // Setup integrator\n    RungeKuttaCoefficients coeff56 =\n            RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg56);\n\n    RungeKuttaCoefficients coeff78 =\n            RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78);\n\n    // Integrator settings\n    double minimumStepSize = std::numeric_limits< double >::epsilon( );\n    double maximumStepSize = std::numeric_limits< double >::infinity( );\n    double initialStepSize = 1E-4; // Don't make this too small\n    double relativeTolerance = 1E-15;\n    double absoluteTolerance = 1E-15;\n\n    // Initial conditions\n    double initialTime = 0.5;\n    Eigen::VectorXd InitialState( 1 );\n    InitialState << 0.5; // 1 large error\n\n    // Setup integrator\n    RungeKuttaVariableStepSizeIntegratorXd integrator56(\n                coeff56, computeNonAutonomousModelStateDerivative, initialTime, InitialState,\n                minimumStepSize, maximumStepSize, relativeTolerance, absoluteTolerance );\n\n    RungeKuttaVariableStepSizeIntegratorXd integrator78(\n                coeff78, computeNonAutonomousModelStateDerivative, initialTime, InitialState,\n                minimumStepSize, maximumStepSize, relativeTolerance, absoluteTolerance );\n\n    double endTime = 1.5;\n    Eigen::VectorXd solution56 = integrator56.integrateTo( endTime, initialStepSize );\n    Eigen::VectorXd solution78 = integrator78.integrateTo( endTime, initialStepSize );\n\n    Eigen::VectorXd difference = solution78 - solution56;\n\n    BOOST_CHECK_SMALL( std::fabs( difference( 0 ) ), 1E-13 );\n}\n\n//! Test Compare with Runge Kutta 78\nBOOST_AUTO_TEST_CASE( test_RungeKuttaFehlberg56_Integrator_Compare78_v2 )\n{\n    // Setup integrator\n    RungeKuttaCoefficients coeff56 =\n            RungeKuttaCoefficients::get(\n                RungeKuttaCoefficients::rungeKuttaFehlberg56 );\n\n    RungeKuttaCoefficients coeff78 =\n            RungeKuttaCoefficients::get(\n                RungeKuttaCoefficients::rungeKuttaFehlberg78 );\n\n    // Integrator settings\n    double minimumStepSize = std::numeric_limits< double >::epsilon( );\n    double maximumStepSize = std::numeric_limits< double >::infinity( );\n    double initialStepSize = 1.0; // Don't make this too small\n    double relativeTolerance = 1E-10;\n    double absoluteTolerance = 1E-10;\n\n    // Initial conditions\n    double initialTime = 0.2;\n    Eigen::VectorXd InitialState( 1 );\n    InitialState << -1.0;\n\n    // Setup integrator\n    RungeKuttaVariableStepSizeIntegratorXd integrator56(\n                coeff56, computeNonAutonomousModelStateDerivative, initialTime, InitialState,\n                minimumStepSize, maximumStepSize, relativeTolerance, absoluteTolerance );\n\n    RungeKuttaVariableStepSizeIntegratorXd integrator78(\n                coeff78, computeNonAutonomousModelStateDerivative, initialTime, InitialState,\n                minimumStepSize, maximumStepSize, relativeTolerance, absoluteTolerance );\n\n    double endTime = 2.0;\n    Eigen::VectorXd solution56 = integrator56.integrateTo( endTime, initialStepSize );\n    Eigen::VectorXd solution78 = integrator78.integrateTo( endTime, initialStepSize );\n\n    Eigen::VectorXd difference = solution78 - solution56;\n\n    BOOST_CHECK_SMALL( std::fabs( difference( 0 ) ), 1E-8 );\n}\n\n//! Test Compare with Runge Kutta 78\nBOOST_AUTO_TEST_CASE( test_RungeKuttaFehlberg56_Integrator_Compare78_VanDerPol )\n{\n    // Setup integrator\n    RungeKuttaCoefficients coeff56 =\n            RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg56 );\n\n    RungeKuttaCoefficients coeff78 =\n            RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78 );\n\n    // Integrator settings\n    double minimumStepSize = std::numeric_limits< double >::epsilon( );\n    double maximumStepSize = std::numeric_limits< double >::infinity( );\n    double initialStepSize = 1; // Don't make this too small\n    double relativeTolerance = 1E-15;\n    double absoluteTolerance = 1E-15;\n\n    // Initial conditions\n    double initialTime = 0.2;\n    Eigen::VectorXd InitialState( 2 );\n    InitialState << -1.0, 1.0;\n\n    // Setup integrator\n    RungeKuttaVariableStepSizeIntegratorXd integrator56(\n                coeff56, computeVanDerPolStateDerivative, initialTime, InitialState, minimumStepSize,\n                maximumStepSize, relativeTolerance, absoluteTolerance );\n\n    RungeKuttaVariableStepSizeIntegratorXd integrator78(\n                coeff78, computeVanDerPolStateDerivative, initialTime, InitialState, minimumStepSize,\n                maximumStepSize, relativeTolerance, absoluteTolerance );\n\n    double endTime = 1.4;\n    Eigen::VectorXd solution56 = integrator56.integrateTo(endTime,initialStepSize);\n    Eigen::VectorXd solution78 = integrator78.integrateTo(endTime,initialStepSize);\n\n    Eigen::VectorXd difference = solution78 - solution56;\n\n    BOOST_CHECK_SMALL( std::fabs( difference( 0 ) ), 1E-13 );\n    BOOST_CHECK_SMALL( std::fabs( difference( 1 ) ), 1E-13 );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "32c040899e079df2db3329b00769617bd8bd78b7", "size": 12670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/NumericalIntegrators/UnitTests/unitTestRungeKuttaFehlberg56Integrator.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/NumericalIntegrators/UnitTests/unitTestRungeKuttaFehlberg56Integrator.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/NumericalIntegrators/UnitTests/unitTestRungeKuttaFehlberg56Integrator.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": 45.9057971014, "max_line_length": 101, "alphanum_fraction": 0.7029202841, "num_tokens": 3101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.5499033765737761}}
{"text": "//\n//  eigen_utils.hpp\n//\n//  Created By Davis Blalock on 3/2/16.\n//  Copyright (c) 2016 Davis Blalock. All rights reserved.\n//\n\n#ifndef __EIGEN_UTILS_HPP\n#define __EIGEN_UTILS_HPP\n\n#define EIGEN_DONT_PARALLELIZE // ensure no multithreading\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n// ================================================================\n// typealiases\n// ================================================================\n\ntemplate <class T, int Rows = Eigen::Dynamic, int Cols = Eigen::Dynamic>\nusing RowMatrix = Eigen::Matrix<T, Rows, Cols, Eigen::RowMajor>;\n\ntemplate <class T, int Rows = Eigen::Dynamic, int Cols = Eigen::Dynamic>\nusing ColMatrix = Eigen::Matrix<T, Rows, Cols, Eigen::ColMajor>;\n\ntemplate <class T> using ColVector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\ntemplate <class T>\nusing RowVector = Eigen::Matrix<T, 1, Eigen::Dynamic, Eigen::RowMajor>;\n\n#endif\n", "meta": {"hexsha": "1c56cfc709e125c6d404f2a45b94c2aa63fe8825", "size": 912, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "maddness/cpp/src/include/eigen_utils.hpp", "max_stars_repo_name": "joennlae/halutmatmul", "max_stars_repo_head_hexsha": "69340d3386298401d421b0e67dcb0649534b0c12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "maddness/cpp/src/include/eigen_utils.hpp", "max_issues_repo_name": "joennlae/halutmatmul", "max_issues_repo_head_hexsha": "69340d3386298401d421b0e67dcb0649534b0c12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maddness/cpp/src/include/eigen_utils.hpp", "max_forks_repo_name": "joennlae/halutmatmul", "max_forks_repo_head_hexsha": "69340d3386298401d421b0e67dcb0649534b0c12", "max_forks_repo_licenses": ["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.5, "max_line_length": 73, "alphanum_fraction": 0.6184210526, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5499033758291721}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/rcond.hpp\n *\n * \\brief Matrix reciprocal condition number estimate.\n *\n * The condition number of a regular (square) matrix is the product\n * of the \\e norm of the matrix and the norm of its inverse (or\n * pseudo-inverse), and hence depends on the kind of matrix-norm.\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_RCOND_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_RCOND_HPP\n\n\n#include <algorithm>\n#include <boost/numeric/bindings/lapack/auxiliary/lange.hpp>\n#include <boost/numeric/bindings/lapack/computational/gbcon.hpp>\n#include <boost/numeric/bindings/lapack/computational/gbtrf.hpp>\n#include <boost/numeric/bindings/lapack/computational/gecon.hpp>\n#include <boost/numeric/bindings/lapack/computational/getrf.hpp>\n#include <boost/numeric/bindings/lapack/computational/hecon.hpp>\n#include <boost/numeric/bindings/lapack/computational/hetrf.hpp>\n#include <boost/numeric/bindings/lapack/computational/sycon.hpp>\n#include <boost/numeric/bindings/lapack/computational/sytrf.hpp>\n#include <boost/numeric/bindings/lapack/computational/trcon.hpp>\n#include <boost/numeric/bindings/ublas.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/exception.hpp>\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/hermitian.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/symmetric.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/vector.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/qr.hpp>\n#include <stdexcept>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\nnamespace detail {\n\nenum matrix_norm_category\n{\n\tmatrix_norm_1,\n\tmatrix_norm_2,\n\tmatrix_norm_frobenius,\n\tmatrix_norm_inf\n};\n\n\n//template <\n//\ttypename ValueT,\n//\ttypename LayoutT,\n//\ttypename StorageT\n//>\n//ValueT* band_mat_to_lapack_vec(banded_matrix<ValueT,LayoutT,StorageT> const& A, ::fortran_int_t& n)\n//{\n//\ttypedef banded_matrix<ValueT,LayoutT,StorageT> matrix_type;\n//\ttypedef typename matrix_traits<matrix_type>::size_type size_type;\n//\n//\tconst size_type kl = A.lower();\n//\tconst size_type ku = A.upper();\n//\tconst size_type nr = num_rows(A);\n//\tconst size_type nc = num_columns(A);\n//\n//\tn = (2*kl+ku+1)*nc;\n//\n//\tValueT* v = new ValueT[n];\n//\n//\tfor (size_type r = 0; r < nr; ++r)\n//\t{\n//\t\tfor (size_type c = 0; c < nc; ++c)\n//\t\t{\n//\t\t\tsize_type rr = kl+ku+r-c;\n//\t\t\tsize_type k = (2*kl+ku+1)*c+rr;\n//\n//\t\t\tif ((r == c) || (c <= (ku+r) && r <= (c+kl)))\n//\t\t\t{\n//\t\t\t\t// In band\n//\t\t\t\tv[k] = A(r,c);\n//\t\t\t}\n//\t\t\telse\n//\t\t\t{\n//\t\t\t\t// Out of band\n//\t\t\t\tv[k] = ValueT();\n//\t\t\t}\n//\t\t}\n//\t}\n//\n//\treturn v;\n//}\n\n//template <typename T>\n//void print_vector(std::string const& desc, T const* a, std::size_t n)\n//{\n//\tstd::cout << std::endl << desc << std::endl << \"  [\";\n//\tfor(std::size_t i = 0; i < n; ++i)\n//\t{\n//\t\tstd::cout << \" \" << std::fixed << a[i];\n//\t}\n//\tstd::cout << \"]\" << std::endl;\n//}\n\n\n\ntemplate <typename MatrixT>\ntypename type_traits<\n\ttypename matrix_traits<MatrixT>::value_type\n>::real_type rcond_impl(MatrixT const& A, matrix_norm_category norm_category, column_major_tag)\n{\n    typedef typename matrix_traits<MatrixT>::value_type value_type;\n\ttypedef typename type_traits<value_type>::real_type result_type;\n\ttypedef typename matrix_traits<MatrixT>::size_type size_type;\n\ttypedef matrix<value_type, column_major> work_matrix_type;\n\n\tsize_type nr = num_rows(A);\n\tsize_type nc = num_columns(A);\n\tsize_type k = ::std::min(nr,nc);\n\n\t// Check if A is a square matrix\n\tif (nr != nc)\n\t{\n\t\t// Non-square matrix -> Use QR decomposition\n\t\tif (nr < nc)\n\t\t{\n\t\t\treturn rcond_impl(qr_decompose(trans(A)).R(false), norm_category, column_major_tag());\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn rcond_impl(qr_decompose(A).R(false), norm_category, column_major_tag());\n\t\t}\n\t}\n\n\tchar what_norm;\n\tresult_type norm;\n\tresult_type res;\n\n\t//FIXME: actually, in bindings this function is broken\n//\tswitch (norm_category)\n//\t{\n//\t\tcase matrix_norm_1:\n//\t\t\twhat_norm = 'O';\n//\t\t\tbreak;\n//\t\tcase matrix_norm_inf:\n//\t\t\twhat_norm = 'I';\n//\t\t\tbreak;\n////\t\tcase matrix_norm_frobenius:\n////\t\t\twhat_norm = 'F';\n////\t\t\tbreak;\n//\t\tdefault:\n//\t\t\tthrow std::runtime_error(\"[rcond::detail::rcond_impl] Unsupported norm category.\");\n//\t}\n\n\t// Compute the norm of A\n\t//FIXME: actually, in bindings this function is broken\n//\t::boost::numeric::bindings::lapack::lange(\n//\t\twhat_norm,\n//\t\tA\n//\t);\n\tswitch (norm_category)\n\t{\n\t\tcase matrix_norm_1:\n\t\t\twhat_norm = 'O';\n\t\t\tnorm = norm_1(A);\n\t\t\tbreak;\n\t\tcase matrix_norm_inf:\n\t\t\twhat_norm = 'I';\n\t\t\tnorm = norm_inf(A);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"[rcond::detail::rcond_impl] Unsupported norm category.\");\n\t}\n\n\t// Compute the LUP factorization of A\n\twork_matrix_type tmp_LU(A);\n\tvector< ::fortran_int_t > dummy_ipiv(k);\n\t::boost::numeric::bindings::lapack::getrf(\n\t\ttmp_LU,\n\t\tdummy_ipiv\n\t);\n\tdummy_ipiv.resize(0, false); // free memory\n\n\t// Finally, compute the reciprocal condition number\n\t::boost::numeric::bindings::lapack::gecon(\n\t\twhat_norm,\n\t\ttmp_LU,\n\t\tnorm,\n\t\tres\n\t);\n\n\treturn res;\n}\n\n\ntemplate <typename MatrixT>\ntypename type_traits<\n\ttypename matrix_traits<MatrixT>::value_type\n>::real_type rcond_impl(MatrixT const& A, matrix_norm_category norm_category, row_major_tag)\n{\n\ttypedef matrix<\n\t\t\t\ttypename matrix_traits<MatrixT>::value_type,\n\t\t\t\tcolumn_major\n\t\t\t> work_matrix_type;\n\n\twork_matrix_type tmp_A(A);\n\n\treturn rcond_impl(tmp_A, norm_category, column_major_tag());\n}\n\n\ntemplate <\n\ttypename ValueT,\n\ttypename TriangularT,\n\ttypename StorageT\n>\ntypename type_traits<ValueT>::real_type rcond_impl(triangular_matrix<ValueT,TriangularT,column_major,StorageT> const& A, matrix_norm_category norm_category, column_major_tag)\n{\n\ttypedef triangular_matrix<ValueT,TriangularT,column_major,StorageT> matrix_type;\n    typedef typename matrix_traits<matrix_type>::value_type value_type;\n\ttypedef typename matrix_traits<matrix_type>::size_type size_type;\n\ttypedef typename type_traits<value_type>::real_type result_type;\n\ttypedef matrix<value_type,column_major> auxiliary_matrix_type;\n\ttypedef triangular_adaptor<auxiliary_matrix_type, TriangularT> work_matrix_type;\n\n\tsize_type nr = num_rows(A);\n\tsize_type nc = num_columns(A);\n\n\t// Check if A is a square matrix\n\tif (nr != nc)\n\t{\n\t\t// Non-square matrix -> Use QR decomposition\n\t\tif (nr < nc)\n\t\t{\n\t\t\treturn rcond_impl(qr_decompose(trans(A)).R(), norm_category, column_major_tag());\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn rcond_impl(qr_decompose(A).R(), norm_category, column_major_tag());\n\t\t}\n\t}\n\n\n\tchar what_norm;\n\tresult_type res;\n\n\tswitch (norm_category)\n\t{\n\t\tcase matrix_norm_1:\n\t\t\twhat_norm = 'O';\n\t\t\tbreak;\n\t\tcase matrix_norm_inf:\n\t\t\twhat_norm = 'I';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"[rcond::detail::rcond_impl] Unsupported norm category.\");\n\t}\n\n\tauxiliary_matrix_type aux_A(A);\n\twork_matrix_type tmp_A(aux_A);\n\n\t// Finally, compute the reciprocal condition number\n\t::boost::numeric::bindings::lapack::trcon(\n\t\twhat_norm,\n\t\ttmp_A,\n\t\tres\n\t);\n\n\treturn res;\n}\n\n\ntemplate <\n\ttypename ValueT,\n\ttypename TriangularT,\n\ttypename StorageT\n>\ntypename type_traits<ValueT>::real_type rcond_impl(triangular_matrix<ValueT,TriangularT,row_major,StorageT> const& A, matrix_norm_category norm_category, row_major_tag)\n{\n\ttypedef triangular_matrix<ValueT,TriangularT,column_major,StorageT> work_matrix_type;\n\n\twork_matrix_type tmp_A(A);\n\n\treturn rcond_impl(tmp_A, norm_category, column_major_tag());\n}\n\n\n/*\ntemplate <\n\ttypename ValueT,\n\ttypename StorageT\n>\ntypename type_traits<ValueT>::real_type rcond_impl(banded_matrix<ValueT,column_major,StorageT> const& A, matrix_norm_category norm_category, column_major_tag)\n{\n\ttypedef banded_matrix<ValueT,column_major,StorageT> matrix_type;\n    typedef typename matrix_traits<matrix_type>::value_type value_type;\n\ttypedef typename matrix_traits<matrix_type>::size_type size_type;\n\ttypedef typename type_traits<value_type>::real_type result_type;\n\t//typedef matrix<value_type,LayoutT> auxiliary_matrix_type;\n\t//typedef banded_adaptor<auxiliary_matrix_type> work_matrix_type;\n\ttypedef banded_matrix<ValueT,row_major,StorageT> work_matrix_type;\n\ttypedef vector< ::fortran_int_t > vector_type;\n\n\tsize_type nr = num_rows(A);\n\tsize_type nc = num_columns(A);\n\n\t// Check if A is a square matrix\n\tif (nr != nc)\n\t{\n\t\t// Non-square matrix -> Use QR decomposition\n\t\tif (nr < nc)\n\t\t{\n\t\t\treturn rcond_impl(qr_decompose(trans(A)).R(), norm_category, column_major_tag());\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn rcond_impl(qr_decompose(A).R(), norm_category, column_major_tag());\n\t\t}\n\t}\n\n\tchar what_norm;\n\tresult_type norm;\n\tresult_type res;\n\tsize_type k = ::std::min(nr,nc);\n\tsize_type kl = A.lower();\n\tsize_type ku = A.upper();\n//\tsize_type ldab = 2*kl+ku+1;\n\n\tswitch (norm_category)\n\t{\n\t\tcase matrix_norm_1:\n\t\t\twhat_norm = 'O';\n\t\t\tbreak;\n\t\tcase matrix_norm_inf:\n\t\t\twhat_norm = 'I';\n\t\t\tbreak;\n//\t\tcase matrix_norm_frobenius:\n//\t\t\twhat_norm = 'F';\n//\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"[rcond::detail::rcond_impl] Unsupported norm category.\");\n\t}\n\n\t// Compute the norm of A\n\t//FIXME: actually, in bindings this function is broken\n//\t::boost::numeric::bindings::lapack::lange(\n//\t\twhat_norm,\n//\t\tA\n//\t);\n\tswitch (norm_category)\n\t{\n\t\tcase matrix_norm_1:\n\t\t\tnorm = norm_1(A);\n\t\t\tbreak;\n\t\tcase matrix_norm_inf:\n\t\t\tnorm = norm_inf(A);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"[rcond::detail::rcond_impl] Unsupported norm category.\");\n\t}\n\n\t// Compute the LUP factorization of A\n//\t::fortran_int_t* aux_ab = band_mat_to_lapack_vec(A, n);\n//\tvector< ::fortran_int_t> tmp_ipiv(k);\n//\t::std::ptrdiff_t info;\n//\tinfo = ::boost::numeric::bindings::lapack::detail::gbtrf(\n//\t\tnr,\n//\t\tnc,\n//\t\tkl,\n//\t\tku,\n//\t\taux_ab,\n//\t\tldab,\n//\t\ttmp_ipiv.data().begin()\n//\t);\n\twork_matrix_type AB(A, kl, kl+ku); //NOTE: \"kl+ku\" is not a typo\n\tvector_type ipiv(k);\n\t::boost::numeric::bindings::lapack::gbtrf(AB, ipiv);\n\n\t// Finally, compute the reciprocal condition number\n\t::boost::numeric::bindings::lapack::gbcon(\n\t\twhat_norm,\n\t\tAB,\n\t\tipiv,\n\t\tnorm,\n\t\tres\n\t);\n\n\treturn res;\n}\n*/\n\n\ntemplate <\n\ttypename ValueT,\n\ttypename StorageT\n>\ntypename type_traits<ValueT>::real_type rcond_impl(banded_matrix<ValueT,column_major,StorageT> const& A, matrix_norm_category norm_category, column_major_tag)\n{\n\ttypedef banded_matrix<ValueT,row_major,StorageT> work_matrix_type;\n\n\twork_matrix_type tmp_A(A, A.lower(), A.upper());\n\n\treturn rcond_impl(tmp_A, norm_category, row_major_tag());\n}\n\n\ntemplate <\n\ttypename ValueT,\n\ttypename StorageT\n>\ntypename type_traits<ValueT>::real_type rcond_impl(banded_matrix<ValueT,row_major,StorageT> const& A, matrix_norm_category norm_category, row_major_tag)\n{\n\ttypedef banded_matrix<ValueT,row_major,StorageT> matrix_type;\n    typedef typename matrix_traits<matrix_type>::value_type value_type;\n\ttypedef typename matrix_traits<matrix_type>::size_type size_type;\n\ttypedef typename type_traits<value_type>::real_type result_type;\n\ttypedef banded_matrix<ValueT,row_major,StorageT> work_matrix_type;\n\ttypedef vector< ::fortran_int_t > vector_type;\n\n\tsize_type nr = num_rows(A);\n\tsize_type nc = num_columns(A);\n\n\t// Check if A is a square matrix\n\tif (nr != nc)\n\t{\n\t\t// Non-square matrix -> Use QR decomposition\n\t\tif (nr < nc)\n\t\t{\n\t\t\treturn rcond_impl(qr_decompose(trans(A)).R(), norm_category, column_major_tag());\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn rcond_impl(qr_decompose(A).R(), norm_category, column_major_tag());\n\t\t}\n\t}\n\n\tchar what_norm;\n\tresult_type norm;\n\tresult_type res;\n\tsize_type k = ::std::min(nr,nc);\n\tsize_type kl = A.lower();\n\tsize_type ku = A.upper();\n//\tsize_type ldab = 2*kl+ku+1;\n\n\tswitch (norm_category)\n\t{\n\t\tcase matrix_norm_1:\n\t\t\twhat_norm = 'O';\n\t\t\tbreak;\n\t\tcase matrix_norm_inf:\n\t\t\twhat_norm = 'I';\n\t\t\tbreak;\n//\t\tcase matrix_norm_frobenius:\n//\t\t\twhat_norm = 'F';\n//\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"[rcond::detail::rcond_impl] Unsupported norm category.\");\n\t}\n\n\t// Compute the norm of A\n\t//FIXME: actually, in bindings this function is broken\n//\t::boost::numeric::bindings::lapack::lange(\n//\t\twhat_norm,\n//\t\tA\n//\t);\n\tswitch (norm_category)\n\t{\n\t\tcase matrix_norm_1:\n\t\t\tnorm = norm_1(A);\n\t\t\tbreak;\n\t\tcase matrix_norm_inf:\n\t\t\tnorm = norm_inf(A);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"[rcond::detail::rcond_impl] Unsupported norm category.\");\n\t}\n\n\t// Compute the LUP factorization of A\n//\t::fortran_int_t* aux_ab = band_mat_to_lapack_vec(A, n);\n//\tvector< ::fortran_int_t> tmp_ipiv(k);\n//\t::std::ptrdiff_t info;\n//\tinfo = ::boost::numeric::bindings::lapack::detail::gbtrf(\n//\t\tnr,\n//\t\tnc,\n//\t\tkl,\n//\t\tku,\n//\t\taux_ab,\n//\t\tldab,\n//\t\ttmp_ipiv.data().begin()\n//\t);\n\twork_matrix_type AB(A, kl, kl+ku); //NOTE: \"kl+ku\" is not a typo\n\tvector_type ipiv(k);\n\t::boost::numeric::bindings::lapack::gbtrf(AB, ipiv);\n\n\t// Finally, compute the reciprocal condition number\n\t::boost::numeric::bindings::lapack::gbcon(\n\t\twhat_norm,\n\t\tAB,\n\t\tipiv,\n\t\tnorm,\n\t\tres\n\t);\n\n\treturn res;\n}\n\n\ntemplate <\n\ttypename ValueT,\n\ttypename TriangularT,\n\ttypename StorageT\n>\ntypename type_traits<ValueT>::real_type rcond_impl(symmetric_matrix<ValueT,TriangularT,column_major,StorageT> const& A, matrix_norm_category norm_category, column_major_tag)\n{\n\ttypedef symmetric_matrix<ValueT,TriangularT,column_major,StorageT> matrix_type;\n    typedef typename matrix_traits<matrix_type>::value_type value_type;\n\ttypedef typename matrix_traits<matrix_type>::size_type size_type;\n\ttypedef typename type_traits<value_type>::real_type result_type;\n\ttypedef matrix<ValueT,column_major> auxiliary_matrix_type;\n\ttypedef symmetric_adaptor<auxiliary_matrix_type,TriangularT> work_matrix_type;\n\ttypedef vector< ::fortran_int_t > vector_type;\n\n\tsize_type nr = num_rows(A);\n\tsize_type nc = num_columns(A);\n\tsize_type n = ::std::min(nr, nc);\n\n\t// Check if A is a square matrix\n\tif (nr != nc)\n\t{\n\t\t// Non-square matrix -> Use QR decomposition\n\t\tif (nr < nc)\n\t\t{\n\t\t\treturn rcond_impl(qr_decompose(trans(A)).R(), norm_category, column_major_tag());\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn rcond_impl(qr_decompose(A).R(), norm_category, column_major_tag());\n\t\t}\n\t}\n\n\tresult_type norm;\n\tresult_type res;\n\n\t// Compute the norm of A\n\t//FIXME: actually, in bindings this function is broken\n//\t::boost::numeric::bindings::lapack::lange(\n//\t\twhat_norm,\n//\t\tA\n//\t);\n\tswitch (norm_category)\n\t{\n\t\tcase matrix_norm_1:\n\t\t\tnorm = norm_1(A);\n\t\t\tbreak;\n\t\tcase matrix_norm_inf:\n\t\t\tnorm = norm_inf(A);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"[rcond::detail::rcond_impl] Unsupported norm category.\");\n\t}\n\n\t// Compute the LUP factorization of A\n\t//work_matrix_type AB(A);\n\tauxiliary_matrix_type aux_A(A);\n\twork_matrix_type AB(aux_A);\n\tvector_type ipiv(n);\n\t::boost::numeric::bindings::lapack::sytrf(AB, ipiv);\n\n\t// Finally, compute the reciprocal condition number\n\t::boost::numeric::bindings::lapack::sycon(\n\t\tAB,\n\t\tipiv,\n\t\tnorm,\n\t\tres\n\t);\n\n\treturn res;\n}\n\n\ntemplate <\n\ttypename ValueT,\n\ttypename TriangularT,\n\ttypename StorageT\n>\ntypename type_traits<ValueT>::real_type rcond_impl(symmetric_matrix<ValueT,TriangularT,row_major,StorageT> const& A, matrix_norm_category norm_category, row_major_tag)\n{\n\ttypedef symmetric_matrix<ValueT,TriangularT,column_major,StorageT> work_matrix_type;\n\n\twork_matrix_type tmp_A(A);\n\n\treturn rcond_impl(tmp_A, norm_category, column_major_tag());\n}\n\n\ntemplate <\n\ttypename ValueT,\n\ttypename TriangularT,\n\ttypename StorageT\n>\ntypename type_traits<ValueT>::real_type rcond_impl(hermitian_matrix<ValueT,TriangularT,column_major,StorageT> const& A, matrix_norm_category norm_category, column_major_tag)\n{\n\ttypedef hermitian_matrix<ValueT,TriangularT,column_major,StorageT> matrix_type;\n    typedef typename matrix_traits<matrix_type>::value_type value_type;\n\ttypedef typename matrix_traits<matrix_type>::size_type size_type;\n\ttypedef typename type_traits<value_type>::real_type result_type;\n\ttypedef matrix<ValueT,column_major> auxiliary_matrix_type;\n\ttypedef hermitian_adaptor<auxiliary_matrix_type,TriangularT> work_matrix_type;\n\ttypedef vector< ::fortran_int_t > vector_type;\n\n\tsize_type nr = num_rows(A);\n\tsize_type nc = num_columns(A);\n\tsize_type n = ::std::min(nr, nc);\n\n\t// Check if A is a square matrix\n\tif (nr != nc)\n\t{\n\t\t// Non-square matrix -> Use QR decomposition\n\t\tif (nr < nc)\n\t\t{\n\t\t\treturn rcond_impl(qr_decompose(trans(A)).R(), norm_category, column_major_tag());\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn rcond_impl(qr_decompose(A).R(), norm_category, column_major_tag());\n\t\t}\n\t}\n\n\tresult_type norm;\n\tresult_type res;\n\n\t// Compute the norm of A\n\t//FIXME: actually, in bindings this function is broken\n//\t::boost::numeric::bindings::lapack::lange(\n//\t\twhat_norm,\n//\t\tA\n//\t);\n\tswitch (norm_category)\n\t{\n\t\tcase matrix_norm_1:\n\t\t\tnorm = norm_1(A);\n\t\t\tbreak;\n\t\tcase matrix_norm_inf:\n\t\t\tnorm = norm_inf(A);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"[rcond::detail::rcond_impl] Unsupported norm category.\");\n\t}\n\n\t// Compute the LUP factorization of A\n\tauxiliary_matrix_type aux_A(A);\n\twork_matrix_type AB(aux_A);\n\tvector_type ipiv(n);\n\t::boost::numeric::bindings::lapack::hetrf(AB, ipiv);\n\n\t// Finally, compute the reciprocal condition number\n\t::boost::numeric::bindings::lapack::hecon(\n\t\tAB,\n\t\tipiv,\n\t\tnorm,\n\t\tres\n\t);\n\n\treturn res;\n}\n\n\ntemplate <\n\ttypename ValueT,\n\ttypename TriangularT,\n\ttypename StorageT\n>\ntypename type_traits<ValueT>::real_type rcond_impl(hermitian_matrix<ValueT,TriangularT,row_major,StorageT> const& A, matrix_norm_category norm_category, row_major_tag)\n{\n\ttypedef hermitian_matrix<ValueT,TriangularT,column_major,StorageT> work_matrix_type;\n\n\twork_matrix_type tmp_A(A);\n\n\treturn rcond_impl(tmp_A, norm_category, column_major_tag());\n}\n\n} // Namespace detail\n\n\n/**\n * \\brief Matrix reciprocal condition number estimate based on 1-norm.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param A The input \\e square matrix expression.\n * \\return The estimate of the reciprocal condition number of \\a A.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\ntypename type_traits<\n\ttypename matrix_traits<MatrixExprT>::value_type\n>::real_type rcond(matrix_expression<MatrixExprT> const& A)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::orientation_category orientation_category;\n\n\treturn detail::rcond_impl(A(), detail::matrix_norm_1, orientation_category());\n}\n\n\n//FIXME: Does we also need this?\n///**\n// * \\brief Matrix reciprocal condition number estimate based on the matrix norm\n// *  defined by parameter \\a what_norm.\n// *\n// * \\tparam MatrixExprT The type of the input matrix expression.\n// * \\tparam NormTagT The type of the matrix norm category.\n// *\n// * \\param A The input \\e square matrix expression.\n// * \\param what_norm The matrix norm category.\n// * \\return The estimate of the reciprocal condition number of \\a A.\n// *\n// * \\author Marco Guazzone, marco.guazzone@gmail.com\n// */\n//template <typename MatrixExprT, typename NormTagT>\n//typename type_traits<\n//\ttypename matrix_traits<MatrixExprT>::value_type\n//>::real_type rcond(matrix_expression<MatrixExprT> const& A, NormTagT what_norm)\n//{\n//\ttypedef typename matrix_traits<MatrixExprT>::orientation_category orientation_category;\n//\n//\treturn detail::rcond_impl(A(), detail::matrix_norm_1, orientation_category());\n//}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_RCOND_HPP\n", "meta": {"hexsha": "9321b8ce761ee98e8036e356b0c2d647cdafb0d1", "size": 19671, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/rcond.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/rcond.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/rcond.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": 26.2630173565, "max_line_length": 174, "alphanum_fraction": 0.7274668293, "num_tokens": 5407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5499033677622486}}
{"text": "/**\n * @file distribution_test.cpp\n * @author Ryan Curtin\n * @author Yannis Mentekidis\n *\n * Tests for the classes:\n *  * mlpack::distribution::DiscreteDistribution\n *  * mlpack::distribution::GaussianDistribution\n *  * mlpack::distribution::GammaDistribution\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\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::distribution;\nusing namespace mlpack::math;\n\nBOOST_AUTO_TEST_SUITE(DistributionTest);\n\n/*********************************/\n/** Discrete Distribution Tests **/\n/*********************************/\n\n/**\n * Make sure we initialize correctly.\n */\nBOOST_AUTO_TEST_CASE(DiscreteDistributionConstructorTest)\n{\n  DiscreteDistribution d(5);\n\n  BOOST_REQUIRE_EQUAL(d.Probabilities().n_elem, 5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"0\"), 0.2, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"1\"), 0.2, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"2\"), 0.2, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"3\"), 0.2, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"4\"), 0.2, 1e-5);\n}\n\n/**\n * Make sure we get the probabilities of observations right.\n */\nBOOST_AUTO_TEST_CASE(DiscreteDistributionProbabilityTest)\n{\n  DiscreteDistribution d(5);\n\n  d.Probabilities() = \"0.2 0.4 0.1 0.1 0.2\";\n\n  BOOST_REQUIRE_CLOSE(d.Probability(\"0\"), 0.2, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"1\"), 0.4, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"2\"), 0.1, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"3\"), 0.1, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"4\"), 0.2, 1e-5);\n}\n\n/**\n * Make sure we get random observations correct.\n */\nBOOST_AUTO_TEST_CASE(DiscreteDistributionRandomTest)\n{\n  DiscreteDistribution d(arma::Col<size_t>(\"3\"));\n\n  d.Probabilities() = \"0.3 0.6 0.1\";\n\n  arma::vec actualProb(3);\n\n  actualProb.zeros();\n\n  for (size_t i = 0; i < 50000; i++)\n    actualProb((size_t) (d.Random()[0] + 0.5))++;\n\n  // Normalize.\n  actualProb /= accu(actualProb);\n\n  // 8% tolerance, because this can be a noisy process.\n  BOOST_REQUIRE_CLOSE(actualProb(0), 0.3, 8.0);\n  BOOST_REQUIRE_CLOSE(actualProb(1), 0.6, 8.0);\n  BOOST_REQUIRE_CLOSE(actualProb(2), 0.1, 8.0);\n}\n\n/**\n * Make sure we can estimate from observations correctly.\n */\nBOOST_AUTO_TEST_CASE(DiscreteDistributionTrainTest)\n{\n  DiscreteDistribution d(4);\n\n  arma::mat obs(\"0 0 1 1 2 2 2 3\");\n\n  d.Train(obs);\n\n  BOOST_REQUIRE_CLOSE(d.Probability(\"0\"), 0.25, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"1\"), 0.25, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"2\"), 0.375, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"3\"), 0.125, 1e-5);\n}\n\n/**\n * Estimate from observations with probabilities.\n */\nBOOST_AUTO_TEST_CASE(DiscreteDistributionTrainProbTest)\n{\n  DiscreteDistribution d(3);\n\n  arma::mat obs(\"0 0 1 2\");\n\n  arma::vec prob(\"0.25 0.25 0.5 1.0\");\n\n  d.Train(obs, prob);\n\n  BOOST_REQUIRE_CLOSE(d.Probability(\"0\"), 0.25, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"1\"), 0.25, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"2\"), 0.5, 1e-5);\n}\n\n/**\n * Achieve multidimensional probability distribution.\n */\nBOOST_AUTO_TEST_CASE(MultiDiscreteDistributionTrainProbTest)\n{\n  DiscreteDistribution d(\"10 10 10\");\n\n  arma::mat obs(\"0 1 1 1 2 2 2 2 2 2;\"\n                \"0 0 0 1 1 1 2 2 2 2;\"\n                \"0 0 0 1 1 2 2 2 2 2;\");\n\n  d.Train(obs);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"0 0 0\"), 0.009, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"0 1 2\"), 0.015, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"2 1 0\"), 0.054, 1e-5);\n}\n\n/**\n * Make sure we initialize multidimensional probability distribution\n * correctly.\n */\nBOOST_AUTO_TEST_CASE(MultiDiscreteDistributionConstructorTest)\n{\n  DiscreteDistribution d(\"4 4 4 4\");\n\n  BOOST_REQUIRE_EQUAL(d.Probabilities(0).size(), 4);\n  BOOST_REQUIRE_EQUAL(d.Dimensionality(), 4);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"0 0 0 0\"), 0.00390625, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"0 1 2 3\"), 0.00390625, 1e-5);\n}\n\n/**\n * Achieve multidimensional probability distribution.\n */\nBOOST_AUTO_TEST_CASE(MultiDiscreteDistributionTrainTest)\n{\n  std::vector<arma::vec> pro;\n  pro.push_back(arma::vec(\"0.1, 0.3, 0.6\"));\n  pro.push_back(arma::vec(\"0.3, 0.3, 0.3\"));\n  pro.push_back(arma::vec(\"0.25, 0.25, 0.5\"));\n\n  DiscreteDistribution d(pro);\n\n  BOOST_REQUIRE_CLOSE(d.Probability(\"0 0 0\"), 0.0083333, 1e-3);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"0 1 2\"), 0.0166666, 1e-3);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"2 1 0\"), 0.05, 1e-5);\n}\n\n/**\n * Estimate multidimensional probability distribution from observations with\n * probabilities.\n */\nBOOST_AUTO_TEST_CASE(MultiDiscreteDistributionTrainProTest)\n{\n  DiscreteDistribution d(\"5 5 5\");\n\n  arma::mat obs(\"0 0 1 1 2;\"\n                \"0 1 1 2 2;\"\n                \"0 1 1 2 2\");\n\n  arma::vec prob(\"0.25 0.25 0.25 0.25 1\");\n\n  d.Train(obs, prob);\n\n  BOOST_REQUIRE_CLOSE(d.Probability(\"0 0 0\"), 0.00390625, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"1 0 1\"), 0.0078125, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.Probability(\"2 1 0\"), 0.015625, 1e-5);\n}\n\n/*********************************/\n/** Gaussian Distribution Tests **/\n/*********************************/\n\n/**\n * Make sure Gaussian distributions are initialized correctly.\n */\nBOOST_AUTO_TEST_CASE(GaussianDistributionEmptyConstructor)\n{\n  GaussianDistribution d;\n\n  BOOST_REQUIRE_EQUAL(d.Mean().n_elem, 0);\n  BOOST_REQUIRE_EQUAL(d.Covariance().n_elem, 0);\n}\n\n/**\n * Make sure Gaussian distributions are initialized to the correct\n * dimensionality.\n */\nBOOST_AUTO_TEST_CASE(GaussianDistributionDimensionalityConstructor)\n{\n  GaussianDistribution d(4);\n\n  BOOST_REQUIRE_EQUAL(d.Mean().n_elem, 4);\n  BOOST_REQUIRE_EQUAL(d.Covariance().n_rows, 4);\n  BOOST_REQUIRE_EQUAL(d.Covariance().n_cols, 4);\n}\n\n/**\n * Make sure Gaussian distributions are initialized correctly when we give a\n * mean and covariance.\n */\nBOOST_AUTO_TEST_CASE(GaussianDistributionDistributionConstructor)\n{\n  arma::vec mean(3);\n  arma::mat covariance(3, 3);\n\n  mean.randu();\n  covariance.randu();\n  covariance *= covariance.t();\n  covariance += arma::eye<arma::mat>(3, 3);\n\n  GaussianDistribution d(mean, covariance);\n\n  for (size_t i = 0; i < 3; i++)\n    BOOST_REQUIRE_CLOSE(d.Mean()[i], mean[i], 1e-5);\n\n  for (size_t i = 0; i < 3; i++)\n    for (size_t j = 0; j < 3; j++)\n      BOOST_REQUIRE_CLOSE(d.Covariance()(i, j), covariance(i, j), 1e-5);\n}\n\n/**\n * Make sure the probability of observations is correct.\n */\nBOOST_AUTO_TEST_CASE(GaussianDistributionProbabilityTest)\n{\n  arma::vec mean(\"5 6 3 3 2\");\n  arma::mat cov(\"6 1 1 1 2;\"\n                \"1 7 1 0 0;\"\n                \"1 1 4 1 1;\"\n                \"1 0 1 7 0;\"\n                \"2 0 1 0 6\");\n\n  GaussianDistribution d(mean, cov);\n\n  BOOST_REQUIRE_CLOSE(d.LogProbability(\"0 1 2 3 4\"), -13.432076798791542, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.LogProbability(\"3 2 3 7 8\"), -15.814880322345738, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.LogProbability(\"2 2 0 8 1\"), -13.754462857772776, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.LogProbability(\"2 1 5 0 1\"), -13.283283233107898, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.LogProbability(\"3 0 5 1 0\"), -13.800326511545279, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.LogProbability(\"4 0 6 1 0\"), -14.900192463287908, 1e-5);\n}\n\n/**\n * Test GaussianDistribution::Probability() in the univariate case.\n */\nBOOST_AUTO_TEST_CASE(GaussianUnivariateProbabilityTest)\n{\n  GaussianDistribution g(arma::vec(\"0.0\"), arma::mat(\"1.0\"));\n\n  // Simple case.\n  BOOST_REQUIRE_CLOSE(g.Probability(arma::vec(\"0.0\")), 0.398942280401433, 1e-5);\n  BOOST_REQUIRE_CLOSE(g.Probability(arma::vec(\"1.0\")), 0.241970724519143, 1e-5);\n  BOOST_REQUIRE_CLOSE(g.Probability(arma::vec(\"-1.0\")), 0.241970724519143,\n      1e-5);\n\n  // A few more cases...\n  arma::mat covariance;\n\n  covariance = 2.0;\n  g.Covariance(std::move(covariance));\n  BOOST_REQUIRE_CLOSE(g.Probability(arma::vec(\"0.0\")), 0.282094791773878, 1e-5);\n  BOOST_REQUIRE_CLOSE(g.Probability(arma::vec(\"1.0\")), 0.219695644733861, 1e-5);\n  BOOST_REQUIRE_CLOSE(g.Probability(arma::vec(\"-1.0\")), 0.219695644733861,\n      1e-5);\n\n  g.Mean().fill(1.0);\n  covariance = 1.0;\n  g.Covariance(std::move(covariance));\n  BOOST_REQUIRE_CLOSE(g.Probability(arma::vec(\"1.0\")), 0.398942280401433, 1e-5);\n\n  covariance = 2.0;\n  g.Covariance(std::move(covariance));\n  BOOST_REQUIRE_CLOSE(g.Probability(arma::vec(\"-1.0\")), 0.103776874355149,\n      1e-5);\n}\n\n/**\n * Test GaussianDistribution::Probability() in the multivariate case.\n */\nBOOST_AUTO_TEST_CASE(GaussianMultivariateProbabilityTest)\n{\n  // Simple case.\n  arma::vec mean = \"0 0\";\n  arma::mat cov = \"1 0; 0 1\";\n  arma::vec x = \"0 0\";\n\n  GaussianDistribution g(mean, cov);\n\n  BOOST_REQUIRE_CLOSE(g.Probability(x), 0.159154943091895, 1e-5);\n\n  arma::mat covariance;\n  covariance = \"2 0; 0 2\";\n  g.Covariance(std::move(covariance));\n\n  BOOST_REQUIRE_CLOSE(g.Probability(x), 0.0795774715459477, 1e-5);\n\n  x = \"1 1\";\n\n  BOOST_REQUIRE_CLOSE(g.Probability(x), 0.0482661763150270, 1e-5);\n  BOOST_REQUIRE_CLOSE(g.Probability(-x), 0.0482661763150270, 1e-5);\n\n  g.Mean() = \"1 1\";\n  BOOST_REQUIRE_CLOSE(g.Probability(x), 0.0795774715459477, 1e-5);\n  g.Mean() *= -1;\n  BOOST_REQUIRE_CLOSE(g.Probability(-x), 0.0795774715459477, 1e-5);\n\n  g.Mean() = \"1 1\";\n  covariance = \"2 1.5; 1.5 4\";\n  g.Covariance(std::move(covariance));\n\n  BOOST_REQUIRE_CLOSE(g.Probability(x), 0.066372199406187285, 1e-5);\n  g.Mean() *= -1;\n  BOOST_REQUIRE_CLOSE(g.Probability(-x), 0.066372199406187285, 1e-5);\n\n  g.Mean() = \"1 1\";\n  x = \"-1 4\";\n\n  BOOST_REQUIRE_CLOSE(g.Probability(x), 0.00072147262356379415, 1e-5);\n  BOOST_REQUIRE_CLOSE(g.Probability(-x), 0.00085851785428674523, 1e-5);\n\n  // Higher-dimensional case.\n  x = \"0 1 2 3 4\";\n  g.Mean() = \"5 6 3 3 2\";\n\n  covariance = \"6 1 1 1 2;\"\n               \"1 7 1 0 0;\"\n               \"1 1 4 1 1;\"\n               \"1 0 1 7 0;\"\n               \"2 0 1 0 6\";\n  g.Covariance(std::move(covariance));\n\n  BOOST_REQUIRE_CLOSE(g.Probability(x), 1.4673143531128877e-06, 1e-5);\n  BOOST_REQUIRE_CLOSE(g.Probability(-x), 7.7404143494891786e-09, 1e-8);\n\n  g.Mean() *= -1;\n  BOOST_REQUIRE_CLOSE(g.Probability(-x), 1.4673143531128877e-06, 1e-5);\n  BOOST_REQUIRE_CLOSE(g.Probability(x), 7.7404143494891786e-09, 1e-8);\n}\n\n/**\n * Test the phi() function, for multiple points in the multivariate Gaussian\n * case.\n */\nBOOST_AUTO_TEST_CASE(GaussianMultipointMultivariateProbabilityTest)\n{\n  // Same case as before.\n  arma::vec mean = \"5 6 3 3 2\";\n  arma::mat cov(\"6 1 1 1 2;\"\n                \"1 7 1 0 0;\"\n                \"1 1 4 1 1;\"\n                \"1 0 1 7 0;\"\n                \"2 0 1 0 6\");\n\n  arma::mat points = \"0 3 2 2 3 4;\"\n                     \"1 2 2 1 0 0;\"\n                     \"2 3 0 5 5 6;\"\n                     \"3 7 8 0 1 1;\"\n                     \"4 8 1 1 0 0;\";\n\n  arma::vec phis;\n  GaussianDistribution g(mean, cov);\n  g.LogProbability(points, phis);\n\n  BOOST_REQUIRE_EQUAL(phis.n_elem, 6);\n\n  BOOST_REQUIRE_CLOSE(phis(0), -13.432076798791542, 1e-5);\n  BOOST_REQUIRE_CLOSE(phis(1), -15.814880322345738, 1e-5);\n  BOOST_REQUIRE_CLOSE(phis(2), -13.754462857772776, 1e-5);\n  BOOST_REQUIRE_CLOSE(phis(3), -13.283283233107898, 1e-5);\n  BOOST_REQUIRE_CLOSE(phis(4), -13.800326511545279, 1e-5);\n  BOOST_REQUIRE_CLOSE(phis(5), -14.900192463287908, 1e-5);\n}\n\n/**\n * Make sure random observations follow the probability distribution correctly.\n */\nBOOST_AUTO_TEST_CASE(GaussianDistributionRandomTest)\n{\n  arma::vec mean(\"1.0 2.25\");\n  arma::mat cov(\"0.85 0.60;\"\n                \"0.60 1.45\");\n\n  GaussianDistribution d(mean, cov);\n\n  arma::mat obs(2, 5000);\n\n  for (size_t i = 0; i < 5000; i++)\n    obs.col(i) = d.Random();\n\n  // Now make sure that reflects the actual distribution.\n  arma::vec obsMean = arma::mean(obs, 1);\n  arma::mat obsCov = ccov(obs);\n\n  // 10% tolerance because this can be noisy.\n  BOOST_REQUIRE_CLOSE(obsMean[0], mean[0], 10.0);\n  BOOST_REQUIRE_CLOSE(obsMean[1], mean[1], 10.0);\n\n  BOOST_REQUIRE_CLOSE(obsCov(0, 0), cov(0, 0), 10.0);\n  BOOST_REQUIRE_CLOSE(obsCov(0, 1), cov(0, 1), 10.0);\n  BOOST_REQUIRE_CLOSE(obsCov(1, 0), cov(1, 0), 10.0);\n  BOOST_REQUIRE_CLOSE(obsCov(1, 1), cov(1, 1), 10.0);\n}\n\n/**\n * Make sure that we can properly estimate from given observations.\n */\nBOOST_AUTO_TEST_CASE(GaussianDistributionTrainTest)\n{\n  arma::vec mean(\"1.0 3.0 0.0 2.5\");\n  arma::mat cov(\"3.0 0.0 1.0 4.0;\"\n                \"0.0 2.4 0.5 0.1;\"\n                \"1.0 0.5 6.3 0.0;\"\n                \"4.0 0.1 0.0 9.1\");\n\n  // Now generate the observations.\n  arma::mat observations(4, 10000);\n\n  arma::mat transChol = trans(chol(cov));\n  for (size_t i = 0; i < 10000; i++)\n    observations.col(i) = transChol * arma::randn<arma::vec>(4) + mean;\n\n  // Now estimate.\n  GaussianDistribution d;\n\n  // Find actual mean and covariance of data.\n  arma::vec actualMean = arma::mean(observations, 1);\n  arma::mat actualCov = ccov(observations);\n\n  d.Train(observations);\n\n  // Check that everything is estimated right.\n  for (size_t i = 0; i < 4; i++)\n    BOOST_REQUIRE_SMALL(d.Mean()[i] - actualMean[i], 1e-5);\n\n  for (size_t i = 0; i < 4; i++)\n    for (size_t j = 0; j < 4; j++)\n      BOOST_REQUIRE_SMALL(d.Covariance()(i, j) - actualCov(i, j), 1e-5);\n}\n\n/**\n * This test verifies the fitting of GaussianDistribution works properly when\n * probabilities for each sample is given.\n */\nBOOST_AUTO_TEST_CASE(GaussianDistributionTrainWithProbabilitiesTest)\n{\n  arma::vec mean = (\"5.0\");\n  arma::vec cov = (\"2.0\");\n\n  GaussianDistribution dist(mean, cov);\n  size_t N = 5000;\n  size_t d = 1;\n\n  arma::mat rdata(d, N);\n  for (size_t i = 0; i < N; i++)\n    rdata.col(i) = dist.Random();\n\n  arma::vec probabilities(N);\n  for (size_t i = 0; i < N; i++)\n    probabilities(i) = Random();\n\n  // Fit distribution with probabilities and data.\n  GaussianDistribution guDist;\n  guDist.Train(rdata, probabilities);\n\n  // Fit distribution only with data.\n  GaussianDistribution guDist2;\n  guDist2.Train(rdata);\n\n  BOOST_REQUIRE_CLOSE(guDist.Mean()[0], guDist2.Mean()[0], 6);\n  BOOST_REQUIRE_CLOSE(guDist.Covariance()[0], guDist2.Covariance()[0], 6);\n\n  BOOST_REQUIRE_CLOSE(guDist.Mean()[0], mean[0], 6);\n  BOOST_REQUIRE_CLOSE(guDist.Covariance()[0], cov[0], 6);\n}\n\n/**\n * This test ensures that the same result is obtained when trained with\n * probabilities all set to 1 and with no probabilities at all.\n */\nBOOST_AUTO_TEST_CASE(GaussianDistributionWithProbabilties1Test)\n{\n  arma::vec mean = (\"5.0\");\n  arma::vec cov  = (\"4.0\");\n\n  GaussianDistribution dist(mean, cov);\n  size_t N = 50000;\n  size_t d = 1;\n\n  arma::mat rdata(d, N);\n\n  for (size_t i = 0; i < N; i++)\n      rdata.col(i) = Random();\n\n  arma::vec probabilities(N, arma::fill::ones);\n\n  // Fit the distribution with only data.\n  GaussianDistribution guDist;\n  guDist.Train(rdata);\n\n  // Fit the distribution with data and each probability as 1.\n  GaussianDistribution guDist2;\n  guDist2.Train(rdata, probabilities);\n\n  BOOST_REQUIRE_CLOSE(guDist.Mean()[0], guDist2.Mean()[0], 1e-15);\n  BOOST_REQUIRE_CLOSE(guDist.Covariance()[0], guDist2.Covariance()[0], 1e-2);\n}\n\n/**\n * This test draws points from two different normal distributions, sets the\n * probabilities for points from the first distribution to something small and\n * the probabilities for the second to something large.\n *\n * We expect that the distribution we recover after training to be the same as\n * the second normal distribution (the one with high probabilities).\n */\nBOOST_AUTO_TEST_CASE(GaussianDistributionTrainWithTwoDistProbabilitiesTest)\n{\n  arma::vec mean1 = (\"5.0\");\n  arma::vec cov1 = (\"4.0\");\n\n  arma::vec mean2 = (\"3.0\");\n  arma::vec cov2 = (\"1.0\");\n\n  // Create two GaussianDistributions with different parameters.\n  GaussianDistribution dist1(mean1, cov1);\n  GaussianDistribution dist2(mean2, cov2);\n\n  size_t N = 50000;\n  size_t d = 1;\n\n  arma::mat rdata(d, N);\n  arma::vec probabilities(N);\n\n  // Fill even numbered columns with random points from dist1 and odd numbered\n  // columns with random points from dist2.\n  for (size_t j = 0; j < N; j++)\n  {\n    if (j % 2 == 0)\n      rdata.col(j) = dist1.Random();\n    else\n      rdata.col(j) = dist2.Random();\n  }\n\n  // Assign high probabilities to points drawn from dist1 and low probabilities\n  // to numbers drawn from dist2.\n  for (size_t i = 0 ; i < N ; i++)\n  {\n    if (i % 2 == 0)\n      probabilities(i) = Random(0.98, 1);\n    else\n      probabilities(i) = Random(0, 0.02);\n  }\n\n  GaussianDistribution guDist;\n  guDist.Train(rdata, probabilities);\n\n  BOOST_REQUIRE_CLOSE(guDist.Mean()[0], mean1[0], 5);\n  BOOST_REQUIRE_CLOSE(guDist.Covariance()[0], cov1[0], 5);\n}\n\n/******************************/\n/** Gamma Distribution Tests **/\n/******************************/\n/**\n * Make sure that using an object to fit one reference set and then asking\n * to fit another works properly.\n */\nBOOST_AUTO_TEST_CASE(GammaDistributionTrainTest)\n{\n  // Create a gamma distribution random generator.\n  double alphaReal = 5.3;\n  double betaReal = 1.5;\n  std::gamma_distribution<double> dist(alphaReal, betaReal);\n\n  // Create a N x d gamma distribution data and fit the results.\n  size_t N = 200;\n  size_t d = 2;\n  arma::mat rdata(d, N);\n\n  // Random generation of gamma-like points.\n  for (size_t j = 0; j < d; ++j)\n    for (size_t i = 0; i < N; ++i)\n      rdata(j, i) = dist(math::randGen);\n\n  // Create Gamma object and call Train() on reference set.\n  GammaDistribution gDist;\n  gDist.Train(rdata);\n\n  // Training must estimate d pairs of alpha and beta parameters.\n  BOOST_REQUIRE_EQUAL(gDist.Dimensionality(), d);\n  BOOST_REQUIRE_EQUAL(gDist.Dimensionality(), d);\n\n  // Create a N' x d' gamma distribution, fit results without new object.\n  size_t N2 = 350;\n  size_t d2 = 4;\n  arma::mat rdata2(d2, N2);\n\n  // Random generation of gamma-like points.\n  for (size_t j = 0; j < d2; ++j)\n    for (size_t i = 0; i < N2; ++i)\n      rdata2(j, i) = dist(math::randGen);\n\n  // Fit results using old object.\n  gDist.Train(rdata2);\n\n  // Training must estimate d' pairs of alpha and beta parameters.\n  BOOST_REQUIRE_EQUAL(gDist.Dimensionality(), d2);\n  BOOST_REQUIRE_EQUAL(gDist.Dimensionality(), d2);\n}\n\n/**\n * This test verifies that the fitting procedure for GammaDistribution works\n * properly when probabilities for each sample is given.\n */\nBOOST_AUTO_TEST_CASE(GammaDistributionTrainWithProbabilitiesTest)\n{\n  double alphaReal = 5.4;\n  double betaReal = 6.7;\n\n  // Create a gamma distribution random generator.\n  std::gamma_distribution<double> dist(alphaReal, betaReal);\n\n  size_t N = 50000;\n  size_t d = 2;\n  arma::mat rdata(d, N);\n\n  for (size_t j = 0; j < d; j++)\n    for (size_t i = 0; i < N; i++)\n      rdata(j, i) = dist(math::randGen);\n\n  // Fill the probabilities randomly.\n  arma::vec probabilities(N, arma::fill::randu);\n\n  // Fit results with probabilities and data.\n  GammaDistribution gDist;\n  gDist.Train(rdata, probabilities);\n\n  // Fit results with only data.\n  GammaDistribution gDist2;\n  gDist2.Train(rdata);\n\n  BOOST_REQUIRE_CLOSE(gDist2.Alpha(0), gDist.Alpha(0), 1.5);\n  BOOST_REQUIRE_CLOSE(gDist2.Beta(0), gDist.Beta(0), 1.5);\n\n  BOOST_REQUIRE_CLOSE(gDist2.Alpha(1), gDist.Alpha(1), 1.5);\n  BOOST_REQUIRE_CLOSE(gDist2.Beta(1), gDist.Beta(1), 1.5);\n\n  BOOST_REQUIRE_CLOSE(alphaReal, gDist.Alpha(0), 3.0);\n  BOOST_REQUIRE_CLOSE(betaReal, gDist.Beta(0), 3.0);\n\n  BOOST_REQUIRE_CLOSE(alphaReal, gDist.Alpha(1), 3.0);\n  BOOST_REQUIRE_CLOSE(betaReal, gDist.Beta(1), 3.0);\n}\n\n/**\n * This test ensures that the same result is obtained when trained with\n * probabilities all set to 1 and with no probabilities at all.\n */\nBOOST_AUTO_TEST_CASE(GammaDistributionTrainAllProbabilities1Test)\n{\n  double alphaReal = 5.4;\n  double betaReal = 6.7;\n\n  // Create a gamma distribution random generator.\n  std::gamma_distribution<double> dist(alphaReal, betaReal);\n\n  size_t N = 1000;\n  size_t d = 2;\n  arma::mat rdata(d, N);\n\n  for (size_t j = 0; j < d; j++)\n    for (size_t i = 0; i < N; i++)\n      rdata(j, i) = dist(math::randGen);\n\n  // Fit results with only data.\n  GammaDistribution gDist;\n  gDist.Train(rdata);\n\n  // Fit results with data and each probability as 1.\n  GammaDistribution gDist2;\n  arma::vec allProbabilities1(N, arma::fill::ones);\n  gDist2.Train(rdata, allProbabilities1);\n\n  BOOST_REQUIRE_CLOSE(gDist2.Alpha(0), gDist.Alpha(0), 1e-5);\n  BOOST_REQUIRE_CLOSE(gDist2.Beta(0), gDist.Beta(0), 1e-5);\n\n  BOOST_REQUIRE_CLOSE(gDist2.Alpha(1), gDist.Alpha(1), 1e-5);\n  BOOST_REQUIRE_CLOSE(gDist2.Beta(1), gDist.Beta(1), 1e-5);\n}\n\n/**\n * This test draws points from two different gamma distributions, sets the\n * probabilities for the points from the first distribution to something small\n * and the probabilities for the second to something large.  It ensures that the\n * gamma distribution recovered has the same parameters as the second gamma\n * distribution with high probabilities.\n */\nBOOST_AUTO_TEST_CASE(GammaDistributionTrainTwoDistProbabilities1Test)\n{\n  double alphaReal = 5.4;\n  double betaReal = 6.7;\n\n  double alphaReal2 = 1.9;\n  double betaReal2 = 8.4;\n\n  // Create two gamma distribution random generators.\n  std::gamma_distribution<double> dist(alphaReal, betaReal);\n  std::gamma_distribution<double> dist2(alphaReal2, betaReal2);\n\n  size_t N = 50000;\n  size_t d = 2;\n  arma::mat rdata(d, N);\n  arma::vec probabilities(N);\n\n  // Draw points alternately from the two different distributions.\n  for (size_t j = 0; j < d; j++)\n  {\n    for (size_t i = 0; i < N; i++)\n    {\n      if (i % 2 == 0)\n        rdata(j, i) = dist(math::randGen);\n      else\n        rdata(j, i) = dist2(math::randGen);\n    }\n  }\n\n  for (size_t i = 0; i < N; i++)\n  {\n    if (i % 2 == 0)\n      probabilities(i) = 0.02 * math::Random();\n    else\n      probabilities(i) = 0.98 + 0.02 * math::Random();\n  }\n\n  GammaDistribution gDist;\n  gDist.Train(rdata, probabilities);\n\n  BOOST_REQUIRE_CLOSE(alphaReal2, gDist.Alpha(0), 5);\n  BOOST_REQUIRE_CLOSE(betaReal2, gDist.Beta(0), 5);\n\n  BOOST_REQUIRE_CLOSE(alphaReal2, gDist.Alpha(1), 5);\n  BOOST_REQUIRE_CLOSE(betaReal2, gDist.Beta(1), 5);\n}\n\n/**\n * This test verifies that the fitting procedure for GammaDistribution works\n * properly and converges near the actual gamma parameters. We do this twice\n * with different alpha/beta parameters so we make sure we don't have some weird\n * bug that always converges to the same number.\n */\nBOOST_AUTO_TEST_CASE(GammaDistributionFittingTest)\n{\n  // Offset from the actual alpha/beta. 10% is quite a relaxed tolerance since\n  // the random points we generate are few (for test speed) and might be fitted\n  // better by a similar distribution.\n  double errorTolerance = 10;\n\n  size_t N = 5000;\n  size_t d = 1; // Only 1 dimension is required for this.\n\n  /** Iteration 1 (first parameter set) **/\n\n  // Create a gamma-random generator and data.\n  double alphaReal = 5.3;\n  double betaReal = 1.5;\n  std::gamma_distribution<double> dist(alphaReal, betaReal);\n\n  // Random generation of gamma-like points.\n  arma::mat rdata(d, N);\n  for (size_t j = 0; j < d; ++j)\n    for (size_t i = 0; i < N; ++i)\n      rdata(j, i) = dist(math::randGen);\n\n  // Create Gamma object and call Train() on reference set.\n  GammaDistribution gDist;\n  gDist.Train(rdata);\n\n  // Estimated parameter must be close to real.\n  BOOST_REQUIRE_CLOSE(gDist.Alpha(0), alphaReal, errorTolerance);\n  BOOST_REQUIRE_CLOSE(gDist.Beta(0), betaReal, errorTolerance);\n\n  /** Iteration 2 (different parameter set) **/\n\n  // Create a gamma-random generator and data.\n  double alphaReal2 = 7.2;\n  double betaReal2 = 0.9;\n  std::gamma_distribution<double> dist2(alphaReal2, betaReal2);\n\n  // Random generation of gamma-like points.\n  arma::mat rdata2(d, N);\n  for (size_t j = 0; j < d; ++j)\n    for (size_t i = 0; i < N; ++i)\n      rdata2(j, i) = dist2(math::randGen);\n\n  // Create Gamma object and call Train() on reference set.\n  GammaDistribution gDist2;\n  gDist2.Train(rdata2);\n\n  // Estimated parameter must be close to real.\n  BOOST_REQUIRE_CLOSE(gDist2.Alpha(0), alphaReal2, errorTolerance);\n  BOOST_REQUIRE_CLOSE(gDist2.Beta(0), betaReal2, errorTolerance);\n}\n\n/**\n * Test that Train() and the constructor that takes data give the same resulting\n * distribution.\n */\nBOOST_AUTO_TEST_CASE(GammaDistributionTrainConstructorTest)\n{\n  const arma::mat data = arma::randu<arma::mat>(10, 500);\n\n  GammaDistribution d1(data);\n  GammaDistribution d2;\n  d2.Train(data);\n\n  for (size_t i = 0; i < 10; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(d1.Alpha(i), d2.Alpha(i), 1e-5);\n    BOOST_REQUIRE_CLOSE(d1.Beta(i), d2.Beta(i), 1e-5);\n  }\n}\n\n/**\n * Test that Train() with a dataset and Train() with dataset statistics return\n * the same results.\n */\nBOOST_AUTO_TEST_CASE(GammaDistributionTrainStatisticsTest)\n{\n  const arma::mat data = arma::randu<arma::mat>(1, 500);\n\n  // Train object d1 with the data.\n  GammaDistribution d1(data);\n\n  // Train object d2 with the data's statistics.\n  GammaDistribution d2;\n  const arma::vec meanLogx = arma::mean(arma::log(data), 1);\n  const arma::vec meanx = arma::mean(data, 1);\n  const arma::vec logMeanx = arma::log(meanx);\n  d2.Train(logMeanx, meanLogx, meanx);\n\n  BOOST_REQUIRE_CLOSE(d1.Alpha(0), d2.Alpha(0), 1e-5);\n  BOOST_REQUIRE_CLOSE(d1.Beta(0), d2.Beta(0), 1e-5);\n}\n\n/**\n * Tests that Random() generates points that can be reasonably well fit by the\n * distribution that generated them.\n */\nBOOST_AUTO_TEST_CASE(GammaDistributionRandomTest)\n{\n  const arma::vec a(\"2.0 2.5 3.0\"), b(\"0.4 0.6 1.3\");\n  const size_t numPoints = 2000;\n\n  // Distribution to generate points.\n  GammaDistribution d1(a, b);\n  arma::mat data(3, numPoints); // 3-d points.\n\n  for (size_t i = 0; i < numPoints; ++i)\n    data.col(i) = d1.Random();\n\n  // Distribution to fit points.\n  GammaDistribution d2(data);\n  for (size_t i = 0; i < 3; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(d2.Alpha(i), a(i), 10); // Within 10%\n    BOOST_REQUIRE_CLOSE(d2.Beta(i), b(i), 10);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(GammaDistributionProbabilityTest)\n{\n  // Train two 1-dimensional distributions.\n  const arma::vec a1(\"2.0\"), b1(\"0.9\"), a2(\"3.1\"), b2(\"1.4\");\n  arma::mat x1(\"2.0\"), x2(\"2.94\");\n  arma::vec prob1, prob2;\n\n  // Evaluated at wolfram|alpha\n  GammaDistribution d1(a1, b1);\n  d1.Probability(x1, prob1);\n  BOOST_REQUIRE_CLOSE(prob1(0), 0.267575, 1e-3);\n\n  // Evaluated at wolfram|alpha\n  GammaDistribution d2(a2, b2);\n  d2.Probability(x2, prob2);\n  BOOST_REQUIRE_CLOSE(prob2(0), 0.189043, 1e-3);\n\n  // Check that the overload that returns the probability for 1 dimension\n  // agrees.\n  BOOST_REQUIRE_CLOSE(prob2(0), d2.Probability(2.94, 0), 1e-5);\n\n  // Combine into one 2-dimensional distribution.\n  const arma::vec a3(\"2.0 3.1\"), b3(\"0.9 1.4\");\n  arma::mat x3(2, 2);\n  x3 << 2.0 << 2.94 << arma::endr\n     << 2.0 << 2.94;\n  arma::vec prob3;\n\n  // Expect that the 2-dimensional distribution returns the product of the\n  // 1-dimensional distributions (evaluated at wolfram|alpha).\n  GammaDistribution d3(a3, b3);\n  d3.Probability(x3, prob3);\n  BOOST_REQUIRE_CLOSE(prob3(0), 0.04408, 1e-2);\n  BOOST_REQUIRE_CLOSE(prob3(1), 0.026165, 1e-2);\n}\n\nBOOST_AUTO_TEST_CASE(GammaDistributionLogProbabilityTest)\n{\n  // Train two 1-dimensional distributions.\n  const arma::vec a1(\"2.0\"), b1(\"0.9\"), a2(\"3.1\"), b2(\"1.4\");\n  arma::mat x1(\"2.0\"), x2(\"2.94\");\n  arma::vec prob1, prob2;\n\n  // Evaluated at wolfram|alpha\n  GammaDistribution d1(a1, b1);\n  d1.LogProbability(x1, prob1);\n  BOOST_REQUIRE_CLOSE(prob1(0), std::log(0.267575), 1e-3);\n\n  // Evaluated at wolfram|alpha\n  GammaDistribution d2(a2, b2);\n  d2.LogProbability(x2, prob2);\n  BOOST_REQUIRE_CLOSE(prob2(0), std::log(0.189043), 1e-3);\n\n  // Combine into one 2-dimensional distribution.\n  const arma::vec a3(\"2.0 3.1\"), b3(\"0.9 1.4\");\n  arma::mat x3(2, 2);\n  x3\n    << 2.0 << 2.94 << arma::endr\n    << 2.0 << 2.94;\n  arma::vec prob3;\n\n  // Expect that the 2-dimensional distribution returns the product of the\n  // 1-dimensional distributions (evaluated at wolfram|alpha).\n  GammaDistribution d3(a3, b3);\n  d3.LogProbability(x3, prob3);\n  BOOST_REQUIRE_CLOSE(prob3(0), std::log(0.04408), 1e-3);\n  BOOST_REQUIRE_CLOSE(prob3(1), std::log(0.026165), 1e-3);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b442f11fa06226e55feb1390cc5aad159386a566", "size": 28135, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/distribution_test.cpp", "max_stars_repo_name": "bhavya01/mlpack", "max_stars_repo_head_hexsha": "43e65f4850f261e0dc4c24a204b07b988cf052d6", "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": "2019-01-04T16:51:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-04T16:51:20.000Z", "max_issues_repo_path": "src/mlpack/tests/distribution_test.cpp", "max_issues_repo_name": "gopalkrgautam/mlpack", "max_issues_repo_head_hexsha": "376c17e11d2797e258b9c1c34aa393d953eccd22", "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/distribution_test.cpp", "max_forks_repo_name": "gopalkrgautam/mlpack", "max_forks_repo_head_hexsha": "376c17e11d2797e258b9c1c34aa393d953eccd22", "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.2463617464, "max_line_length": 80, "alphanum_fraction": 0.6717966945, "num_tokens": 8983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5498439233827379}}
{"text": "#pragma once\n\n\n#include <boost/gil/gil_all.hpp>\n\n\ntemplate<typename Pixel, typename View>\nvoid clip_pixel(std::int64_t const& x, std::int64_t const& y, Pixel const& pixel, View& view)\n{\n\tif(x < 0 || y < 0)\n\t{\n\t\treturn;\n\t}\n\telse if(x < view.width() && y < view.height())\n\t{\n\t\tview(x, y) = pixel;\n\t}\n}\n\n\ntemplate<typename Pixel, typename View>\nvoid bresenham_line(std::int64_t const& x1, std::int64_t const& y1, std::int64_t const& x2, std::int64_t const& y2, Pixel const& pixel, View& view)\n{\n\t// Adapted from http://www.etechplanet.com/codesnippets/computer-graphics-draw-a-line-using-bresenham-algorithm.aspx\n\n\tstd::int64_t const dx(x2 - x1);\n\tstd::int64_t const dy(y2 - y1);\n\tstd::int64_t const adx(std::abs(dx));\n\tstd::int64_t const ady(std::abs(dy));\n\tstd::int64_t px(2 * ady - adx);\n\tstd::int64_t py(2 * adx - ady);\n\tstd::int64_t x, y, xe, ye;\n\tif(adx < ady)\n\t{\n\t\tif(dy < 0)\n\t\t{\n\t\t\tx = x2;\n\t\t\ty = y2;\n\t\t\tye = y1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tx = x1;\n\t\t\ty = y1;\n\t\t\tye = y2;\n\t\t}\n\t\tclip_pixel(x, y, pixel, view);\n\n\t\tfor(std::int64_t i(0); y < ye; ++ i)\n\t\t{\n\t\t\ty = y + 1;\n\t\t\tif(py > 0)\n\t\t\t{\n\t\t\t\tif((dx < 0 && dy < 0) || (dx > 0 && dy > 0))\n\t\t\t\t{\n\t\t\t\t\tx = x + 1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tx = x - 1;\n\t\t\t\t}\n\t\t\t\tpy = py + 2 * (adx - ady);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpy = py + 2 * adx;\n\t\t\t}\n\t\t\tclip_pixel(x, y, pixel, view);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(dx < 0)\n\t\t{\n\t\t\tx = x2;\n\t\t\ty = y2;\n\t\t\txe = x1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tx = x1;\n\t\t\ty = y1;\n\t\t\txe = x2;\n\t\t}\n\t\tclip_pixel(x, y, pixel, view);\n\n\t\tfor(std::int64_t i(0); x < xe; ++ i)\n\t\t{\n\t\t\tx = x + 1;\n\t\t\tif(px < 0)\n\t\t\t{\n\t\t\t\tpx = px + 2 * ady;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif((dx < 0 && dy < 0) || (dx > 0 && dy > 0))\n\t\t\t\t{\n\t\t\t\t\ty = y + 1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ty = y - 1;\n\t\t\t\t}\n\t\t\t\tpx = px + 2 * (ady - adx);\n\t\t\t}\n\t\t\tclip_pixel(x, y, pixel, view);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "b8aeb267681a68ed9966ee133c2400cb08683194", "size": 1770, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bresenham.hpp", "max_stars_repo_name": "mdyring/tumor_phenotyping", "max_stars_repo_head_hexsha": "dcc5ee38bc56128d649759b96a2f984b54375d18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bresenham.hpp", "max_issues_repo_name": "mdyring/tumor_phenotyping", "max_issues_repo_head_hexsha": "dcc5ee38bc56128d649759b96a2f984b54375d18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bresenham.hpp", "max_forks_repo_name": "mdyring/tumor_phenotyping", "max_forks_repo_head_hexsha": "dcc5ee38bc56128d649759b96a2f984b54375d18", "max_forks_repo_licenses": ["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.0909090909, "max_line_length": 147, "alphanum_fraction": 0.4943502825, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5498439211344094}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \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#include <vector>\n#include <string>\n#include <boost/graph/topological_sort.hpp>\n#include <boost/graph/leda_graph.hpp>\n// Undefine macros from LEDA that conflict with the C++ Standard Library.\n#undef string\n#undef vector\n\nint\nmain()\n{\n  using namespace boost;\n  typedef GRAPH < std::string, char >graph_t;\n  graph_t leda_g;\n  typedef graph_traits < graph_t >::vertex_descriptor vertex_t;\n  std::vector < vertex_t > vert(7);\n  vert[0] = add_vertex(std::string(\"pick up kids from school\"), leda_g);\n  vert[1] = add_vertex(std::string(\"buy groceries (and snacks)\"), leda_g);\n  vert[2] = add_vertex(std::string(\"get cash at ATM\"), leda_g);\n  vert[3] =\n    add_vertex(std::string(\"drop off kids at soccer practice\"), leda_g);\n  vert[4] = add_vertex(std::string(\"cook dinner\"), leda_g);\n  vert[5] = add_vertex(std::string(\"pick up kids from soccer\"), leda_g);\n  vert[6] = add_vertex(std::string(\"eat dinner\"), leda_g);\n\n  add_edge(vert[0], vert[3], leda_g);\n  add_edge(vert[1], vert[3], leda_g);\n  add_edge(vert[1], vert[4], leda_g);\n  add_edge(vert[2], vert[1], leda_g);\n  add_edge(vert[3], vert[5], leda_g);\n  add_edge(vert[4], vert[6], leda_g);\n  add_edge(vert[5], vert[6], leda_g);\n\n  std::vector < vertex_t > topo_order;\n  node_array < default_color_type > color_array(leda_g);\n\n  topological_sort(leda_g, std::back_inserter(topo_order),\n                   color_map(make_leda_node_property_map(color_array)));\n\n  std::reverse(topo_order.begin(), topo_order.end());\n  int n = 1;\n  for (std::vector < vertex_t >::iterator i = topo_order.begin();\n       i != topo_order.end(); ++i, ++n)\n    std::cout << n << \": \" << leda_g[*i] << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "cd24b76e30c462b8dda3792194064b4f41c7dd9e", "size": 2038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/graph/example/topo-sort-with-leda.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/graph/example/topo-sort-with-leda.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/graph/example/topo-sort-with-leda.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": 37.0545454545, "max_line_length": 74, "alphanum_fraction": 0.6324828263, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.5498439198213094}}
{"text": "// Copyright 2017 Nest Labs, Inc.\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 \"graph.hpp\"\n#include \"detector.hpp\"\n#include \"graphanalyzer.hpp\"\n#include \"processorcontainer.hpp\"\n#include \"lag.hpp\"\n\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <sstream>\n#include <string>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace DetectorGraph;\nusing namespace Eigen;\n\n/**\n * @file robotlocalization.cpp\n * @brief A localization system for a mobile robot with Lag-based feedback loop.\n *\n * @section ex-rl-intro Introduction\n * Back in the 2000s all [_citation needed_] robots were _differential wheeled\n * robots_ [1] and localization with sensor fusion was a popular problem.\n * This example shows a simple solution to that problem using DetectorGraph.\n * It uses an Extended Kalman Filter [2] to continuously predict and correct\n * the robot's Pose (and associated uncertainty) from two information sources:\n * the input to the wheels and a GPS-like system.\n *\n * @section ex-rl-fpvslag FuturePublisher vs. Lag\\<T\\>\n * This localization algorithm depends on a feedback-loop in that the output of\n * one graph evaluation (i.e. `LocalizationBelief`) is used as an input for the\n * next one (i.e. `Lagged<LocalizationBelief>`):\n @snippetlineno robotlocalization.cpp KalmanPoseCorrector Feedback Loop\n * Note that in this graph the TopicState where the feedback loop closes is a\n * legitimate output in itself and it's very likely that new Detectors in the\n * graph would subscribe to it. In cases like this the use of\n * DetectorGraph::Lag is preferred as it is more extensible and it preserves\n * the normal TopicState guarantee for the TopicState in question as well as it\n * makes the Lagged version of the TopicState clearly documented and also\n * available. Lag allows even for detectors that subscribes to both the immediate\n * and the Lagged version of a TopicState - this could be useful for things like\n * differentiation etc.\n *\n * @section ex-rl-conf-topicstates Configuration TopicStates\n * It also shows how TopicStates can be used for static/configuration data\n * (e.g. `RobotConfig`). This allows for easy dependency tracking, visualization\n * and testing at pretty much no runtime cost.\n *\n * @section ex-rl-localization Localization Algorithm\n * Regarding the Localization algorithm itself, it's mostly taken from [3]\n * except for the correction model where this example uses a different input\n * (i.e. `GPSPosition`) with much simpler transfer function to the Pose vector.\n *\n * @section ex-rl-arch Architecture\n * The graph below shows the relationships between the topics (rectangles) and\n * detectors (ellipses). Note that this graph can be automatically generated\n * for any instance of DetectorGraph::Graph using DetectorGraph::GraphAnalyzer.\n *  @dot \"RobotBrain\"\ndigraph GraphAnalyzer {\n    rankdir = \"LR\";\n    node[fontname=Helvetica];\n    size=\"12,5\";\n\n    \"RobotConfig\" [label=\"0:RobotConfig\",style=filled, shape=box, color=lightblue];\n        \"RobotConfig\" -> \"ExtendedKalmanPosePredictor\";\n    \"InitialPose\" [label=\"1:InitialPose\",style=filled, shape=box, color=lightblue];\n        \"InitialPose\" -> \"ExtendedKalmanPosePredictor\";\n    \"WheelSpeeds\" [label=\"2:WheelSpeeds\",style=filled, shape=box, color=lightblue];\n        \"WheelSpeeds\" -> \"ExtendedKalmanPosePredictor\";\n    \"GPSPosition\" [label=\"3:GPSPosition\",style=filled, shape=box, color=lightblue];\n        \"GPSPosition\" -> \"KalmanPoseCorrector\";\n    \"LaggedLocalizationBelief\" [label=\"4:Lagged<LocalizationBelief>\",style=filled, shape=box, color=lightblue];\n        \"LaggedLocalizationBelief\" -> \"ExtendedKalmanPosePredictor\";\n        \"LaggedLocalizationBelief\" -> \"KalmanPoseCorrector\";\n    \"KalmanPoseCorrector\" [label=\"6:KalmanPoseCorrector\", color=blue];\n        \"KalmanPoseCorrector\" -> \"LocalizationBelief\";\n    \"ExtendedKalmanPosePredictor\" [label=\"5:ExtendedKalmanPosePredictor\", color=blue];\n        \"ExtendedKalmanPosePredictor\" -> \"LocalizationBelief\";\n    \"LocalizationBelief\" [label=\"7:LocalizationBelief\",style=filled, shape=box, color=red];\n        \"LocalizationBelief\" -> \"LagLocalizationBelief\";\n    \"LagLocalizationBelief\" [label=\"8:Lag<LocalizationBelief>\", color=blue];\n        \"LagLocalizationBelief\" -> \"LaggedLocalizationBelief\" [style=dotted, color=red, constraint=false];\n}\n *  @enddot\n *\n *\n * @section ex-rl-other-notes Other Notes\n * This example also uses the Eigen library [4] for matrix/vector arithmetic\n * and linear-algebraic operations.\n *\n * Note that this entire algorithm is contained in a single file for the sake\n * of unity as an example. In real-world scenarios the suggested pattern is to\n * split the code into:\n *\n @verbatim\n   detectorgraph/\n        include/\n            robotbrain.hpp (RobotBrain header)\n        src/\n            robotbrain.hpp (RobotBrain implementation)\n        detectors/\n            include/\n                ExtendedKalmanPosePredictor.hpp\n                KalmanPoseCorrector.hpp\n            src/\n                ExtendedKalmanPosePredictor.cpp\n                KalmanPoseCorrector.cpp\n        topicstates/\n            include/\n                RobotConfig.hpp\n                InitialPose.hpp\n                WheelSpeeds.hpp\n                LocalizationBelief.hpp\n                GPSPosition.hpp\n@endverbatim\n *\n * @section ex-rl-refs References\n *  - [1] Differential Wheeled Robots - https://en.wikipedia.org/wiki/Differential_wheeled_robot\n *  - [2] Extended Kalman Filter - https://en.wikipedia.org/wiki/Extended_Kalman_filter\n *  - [3] EKF applied to Mobile Robot\u2019s Localization (Section 2.4.4, page 17) - http://cpscotti.com/pdf/pfc_scotti.pdf\n *  - [4] Eigen - http://eigen.tuxfamily.org/dox/index.html\n */\n\n/// @cond DO_NOT_DOCUMENT\n\n// Contains the configuration parameters of this differential mobile Robot\n// or vehicle.\nstruct RobotConfig : public TopicState\n{\n    RobotConfig() : r(), b(), e() {}\n    RobotConfig(double aR, double aB, double aE)\n        : r(aR), b(aB), e(aE) {}\n    double r; // wheels r\n    double b; // displacement between wheels 2*l (l=d(wheel,center))\n\n    double e; // relative wheel slippage/error\n};\n\nstruct InitialPose : public TopicState\n{\n    InitialPose() : timestampMs(0), pose(Vector3d::Zero()) {}\n    InitialPose(Vector3d aPose) : timestampMs(0), pose(aPose) {}\n    InitialPose(uint64_t aTimestampMs, Vector3d aPose) : timestampMs(aTimestampMs), pose(aPose) {}\n    uint64_t timestampMs;\n    Vector3d pose;\n};\n\n// The measured (via encoders or other odometry method) wheel speeds\nstruct WheelSpeeds : public TopicState\n{\n    WheelSpeeds() : timestampMs(), phi(Vector2d::Zero()) {}\n    WheelSpeeds(uint64_t ts, Vector2d aPhi) : timestampMs(ts), phi(aPhi) {}\n    WheelSpeeds(uint64_t ts, double r, double l) : timestampMs(ts), phi(r, l) {}\n    uint64_t timestampMs;\n\n    // phi_r, phi_l in radians\n    Vector2d phi;\n};\n\n//! [TopicStates Composition Example]\nstruct KalmanState\n{\n    KalmanState() : pose(Vector3d::Zero()), error(Matrix3d::Zero()) {}\n    KalmanState(Vector3d aPose, Matrix3d aError) : pose(aPose), error(aError) {}\n    Vector3d pose;\n    Matrix3d error;\n};\n\n//! [Mutually Atomic Variables]\nstruct LocalizationBelief : public TopicState\n{\n    LocalizationBelief() : timestampMs(), state() {}\n    LocalizationBelief(uint64_t ts, const KalmanState& aState) : timestampMs(ts), state(aState) {}\n    LocalizationBelief(uint64_t ts, const Vector3d& aPose, const Matrix3d& aError) : timestampMs(ts), state(aPose, aError) {}\n    uint64_t timestampMs;\n    KalmanState state;\n};\n//! [Mutually Atomic Variables]\n\nstruct GPSPosition : public TopicState\n{\n    GPSPosition() : timestampMs(), state() {}\n    GPSPosition(uint64_t ts, const KalmanState& aState) : timestampMs(ts), state(aState) {}\n    uint64_t timestampMs;\n    KalmanState state;\n};\n//! [TopicStates Composition Example]\n\ndouble WrapAngle(double th)\n{\n    // remainder requires C++11\n    return std::remainder(th, 2. * M_PI);\n}\n\nclass ExtendedKalmanPosePredictor : public Detector,\n    public SubscriberInterface<RobotConfig>,\n    public SubscriberInterface<InitialPose>,\n    public SubscriberInterface< Lagged<LocalizationBelief> >,\n    public SubscriberInterface<WheelSpeeds>,\n    public Publisher<LocalizationBelief>\n{\npublic:\n    ExtendedKalmanPosePredictor(Graph* graph) : Detector(graph), mCurrentBelief(), mConfig()\n    {\n        Subscribe<RobotConfig>(this);\n        Subscribe<InitialPose>(this);\n        Subscribe< Lagged<LocalizationBelief> >(this);\n        Subscribe<WheelSpeeds>(this);\n        SetupPublishing<LocalizationBelief>(this);\n    }\n\n    virtual void Evaluate(const RobotConfig& aConfig)\n    {\n        mConfig = aConfig;\n    }\n\n    virtual void Evaluate(const InitialPose& aInitialPose)\n    {\n        mCurrentBelief.state = KalmanState(aInitialPose.pose, Matrix3d::Zero());\n        mCurrentBelief.timestampMs = aInitialPose.timestampMs;\n    }\n\n    virtual void Evaluate(const Lagged<LocalizationBelief>& aLaggedBelief)\n    {\n        mCurrentBelief.state = aLaggedBelief.data.state;\n        mCurrentBelief.timestampMs = aLaggedBelief.data.timestampMs;\n    }\n\n    virtual void Evaluate(const WheelSpeeds& aWheelSpeeds)\n    {\n        // [\\Delta S_{r}, \\Delta S_{l}] from phi\n        Vector2d wheelLinearSpeed = aWheelSpeeds.phi * mConfig.r;\n\n        // Eq. 2.36\n        double d_th = (wheelLinearSpeed.x() - wheelLinearSpeed.y()) / mConfig.b;\n        // Eq. 2.37\n        double d_travel = (wheelLinearSpeed.x() + wheelLinearSpeed.y()) / 2.;\n\n        double theta = mCurrentBelief.state.pose.z();\n\n        // Used on most equations below\n        double th_dth2 = theta + d_th / 2.;\n\n        // Eq. 2.33 on [3]\n        Vector3d cartesianSpeed;\n        cartesianSpeed << d_travel * cos(th_dth2),\n                          d_travel * sin(th_dth2),\n                                             d_th;\n\n\n        // Compute Time Delta\n        double tDelta = (aWheelSpeeds.timestampMs - mCurrentBelief.timestampMs) * 1e-3;\n\n        // Eq. 2.33 (i.e. 2.23) on [3]\n        mCurrentBelief.state.pose = mCurrentBelief.state.pose + (cartesianSpeed * tDelta);\n        mCurrentBelief.state.pose.z() = WrapAngle(mCurrentBelief.state.pose.z());\n\n        // Eq. 2.34 on [3]\n        Matrix3d G;\n        G << 1, 0, -d_travel * sin(th_dth2),\n             0, 1,  d_travel * cos(th_dth2),\n             0, 0,                        1;\n\n        // Eq. 2.35 on [3]\n        Matrix<double, 3, 2> V;\n        V << 0.5 * cos(th_dth2) - (d_travel / (2. * mConfig.b)) * sin(th_dth2), 0.5 * cos(th_dth2) + (d_travel / (2. * mConfig.b)) * sin(th_dth2),\n             0.5 * sin(th_dth2) + (d_travel / (2. * mConfig.b)) * cos(th_dth2), 0.5 * sin(th_dth2) - (d_travel / (2. * mConfig.b)) * cos(th_dth2),\n                                                                  1./mConfig.b,                                                     -1./mConfig.b;\n\n        // Eq. 2.38 on [3]\n        Matrix2d M;\n        M << mConfig.e * abs(wheelLinearSpeed.x()),                                     0,\n                                                 0, mConfig.e * abs(wheelLinearSpeed.y());\n\n        // Eq. 2.24 on [3]\n        mCurrentBelief.state.error = G * mCurrentBelief.state.error * G.transpose() + V * M * V.transpose();\n\n        mCurrentBelief.timestampMs = aWheelSpeeds.timestampMs;\n        Publish(mCurrentBelief);\n    }\n\n    LocalizationBelief mCurrentBelief;\n    RobotConfig mConfig;\n};\n\n///! [KalmanPoseCorrector Feedback Loop]\nclass KalmanPoseCorrector : public Detector,\n    public SubscriberInterface< Lagged<LocalizationBelief> >,\n    public SubscriberInterface<GPSPosition>,\n    public Publisher<LocalizationBelief>\n{\npublic:\n    KalmanPoseCorrector(Graph* graph) : Detector(graph), mCurrentBelief()\n    {\n        Subscribe< Lagged<LocalizationBelief> >(this);\n        Subscribe<GPSPosition>(this);\n        SetupPublishing<LocalizationBelief>(this);\n    }\n///! [KalmanPoseCorrector Feedback Loop]\n\n    virtual void Evaluate(const Lagged<LocalizationBelief>& aLaggedBelief)\n    {\n        mCurrentBelief.state = aLaggedBelief.data.state;\n        mCurrentBelief.timestampMs = aLaggedBelief.data.timestampMs;\n    }\n\n    virtual void Evaluate(const GPSPosition& aCorrectionInput)\n    {\n        // C = Identity(3)\n\n        // Eq. 2.15 on [3]\n        Matrix3d K = mCurrentBelief.state.error * (mCurrentBelief.state.error + aCorrectionInput.state.error).inverse();\n\n        // Eq. 2.13 on [3]\n        mCurrentBelief.state.pose = mCurrentBelief.state.pose + K * (aCorrectionInput.state.pose - mCurrentBelief.state.pose);\n\n        // Eq. 2.14 on [3]\n        mCurrentBelief.state.error = (Matrix3d::Identity() - K) * mCurrentBelief.state.error;\n\n        Publish(mCurrentBelief);\n    }\n\n    LocalizationBelief mCurrentBelief;\n};\n\n//![RobotBrain Static]\nclass RobotBrain : public ProcessorContainer\n{\npublic:\n    RobotBrain()\n    : mPosePredictor(&mGraph)\n    , mKalmanPoseCorrector(&mGraph)\n    , mBeliefFeedback(&mGraph)\n    {\n    }\n\n    ExtendedKalmanPosePredictor mPosePredictor;\n    KalmanPoseCorrector mKalmanPoseCorrector;\n    Lag<LocalizationBelief> mBeliefFeedback;\n    //![RobotBrain Static]\n\n    virtual void ProcessOutput()\n    {\n        Topic<LocalizationBelief>* correctedStateTopic = mGraph.ResolveTopic<LocalizationBelief>();\n        if (correctedStateTopic->HasNewValue())\n        {\n            const LocalizationBelief& belief = correctedStateTopic->GetNewValue();\n            const auto& pose = belief.state.pose;\n            cout << \"Pose = [\" << pose.x() << \", \" << pose.y() << \", \" << pose.z() << \"], \";\n            const auto& error = belief.state.error.diagonal();\n            cout << \"Error = [\" << error.x() << \", \" << error.y() << \", \" << error.z() << \"]\";\n            cout << endl;\n        }\n    }\n};\n\nint main()\n{\n    RobotBrain robot;\n\n    uint64_t kSimStep = 1000;\n    uint64_t dataIndex = 0;\n\n    robot.ProcessData(RobotConfig(1, 1, 0.1));\n    robot.ProcessData(InitialPose(Vector3d(10.0, 10.0, 0.0)));\n\n    // Circular Movement\n    // for (int i=0;i<100;i++) robot.ProcessData(WheelSpeeds((dataIndex++)*kSimStep, 1., 0.5));\n\n    // Fwd, Rotate ~180, Fwd, GPS Update\n    robot.ProcessData(WheelSpeeds((dataIndex++)*kSimStep, 1, 1));\n    robot.ProcessData(WheelSpeeds((dataIndex++)*kSimStep, 1, 1));\n    robot.ProcessData(WheelSpeeds((dataIndex++)*kSimStep, 1, 1));\n    robot.ProcessData(WheelSpeeds((dataIndex++)*kSimStep, 1, 1));\n    robot.ProcessData(WheelSpeeds((dataIndex++)*kSimStep, 1, 1));\n    robot.ProcessData(WheelSpeeds((dataIndex++)*kSimStep, 1, -1));\n    robot.ProcessData(WheelSpeeds((dataIndex++)*kSimStep, 1, -1));\n    robot.ProcessData(WheelSpeeds((dataIndex++)*kSimStep, 1, 1));\n    robot.ProcessData(WheelSpeeds((dataIndex++)*kSimStep, 1, 1));\n    robot.ProcessData(WheelSpeeds((dataIndex++)*kSimStep, 1, 1));\n    robot.ProcessData(WheelSpeeds((dataIndex++)*kSimStep, 1, 1));\n    robot.ProcessData(WheelSpeeds((dataIndex++)*kSimStep, 1, 1));\n    robot.ProcessData(GPSPosition((dataIndex++)*kSimStep,\n        KalmanState(Vector3d(10., 10., 4),  // Position\n                    Vector3d(0.1,0.1,300000).asDiagonal()  // Error\n            )));\n\n    cout << \"---- Done ----\" << endl;\n\n    GraphAnalyzer analyzer(robot.mGraph);\n    analyzer.GenerateDotFile(\"robot_localization.dot\");\n\n    return 0;\n}\n\n/// @endcond DO_NOT_DOCUMENT\n", "meta": {"hexsha": "9e6fad6a627fd0873645a24f665d491e33385479", "size": 15760, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/robotlocalization.cpp", "max_stars_repo_name": "google/detectorgraph", "max_stars_repo_head_hexsha": "d6c923f8e495a21137312b236e35c36a55d3a755", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T07:13:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T01:54:06.000Z", "max_issues_repo_path": "examples/robotlocalization.cpp", "max_issues_repo_name": "google/detectorgraph", "max_issues_repo_head_hexsha": "d6c923f8e495a21137312b236e35c36a55d3a755", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-09-20T04:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-21T08:05:33.000Z", "max_forks_repo_path": "examples/robotlocalization.cpp", "max_forks_repo_name": "google/detectorgraph", "max_forks_repo_head_hexsha": "d6c923f8e495a21137312b236e35c36a55d3a755", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-05-17T09:03:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-13T16:38:15.000Z", "avg_line_length": 38.2524271845, "max_line_length": 146, "alphanum_fraction": 0.6680837563, "num_tokens": 4076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.5498439126984523}}
{"text": "/**\n * @file utils.cpp\n * @brief Usefult utilities\n * @author Parker Lusk <plusk@mit.edu>\n * @date 12 October 2020\n */\n\n#include <functional>\n#include <queue>\n#include <random>\n#include <utility>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"clipper/utils.h\"\n\nnamespace clipper {\nnamespace utils {\n\nEigen::VectorXd randvec(size_t n)\n{\n  std::random_device rd;\n  std::mt19937 gen(rd());\n  std::uniform_real_distribution<double> dis(0, 1);\n\n  return Eigen::VectorXd::NullaryExpr(n, 1, [&](){ return dis(gen); });\n}\n\n// ----------------------------------------------------------------------------\n\nstd::vector<int> findIndicesOfkLargest(const Eigen::VectorXd& x, int k)\n{\n  using T = std::pair<double, int>; // pair value to be compared and index\n  if (k < 1) return {}; // invalid input\n  // n.b., the top of this queue is smallest element\n  std::priority_queue<T, std::vector<T>, std::greater<T>> q;\n  for (size_t i=0; i<x.rows(); ++i) {\n    if (q.size() < k) {\n      q.push({x(i), i});\n    } else if (q.top().first < x(i)) {\n      q.pop();\n      q.push({x(i), i});\n    }\n  }\n\n  std::vector<int> indices(k);\n  for (size_t i=0; i<k; ++i) {\n    indices[k - i - 1] = q.top().second;\n    q.pop();\n  }\n\n  return indices;\n}\n\n} // ns utils\n} // ns clipper", "meta": {"hexsha": "4bca19357f6e7d054e2687cb7665c6cc8432ca20", "size": 1254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils.cpp", "max_stars_repo_name": "ash-aldujaili/clipper", "max_stars_repo_head_hexsha": "2e56b2058e8482c33ece3390b3b1b558301eacbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2021-02-17T15:56:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:57:08.000Z", "max_issues_repo_path": "src/utils.cpp", "max_issues_repo_name": "ash-aldujaili/clipper", "max_issues_repo_head_hexsha": "2e56b2058e8482c33ece3390b3b1b558301eacbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T09:33:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T03:48:05.000Z", "max_forks_repo_path": "src/utils.cpp", "max_forks_repo_name": "ash-aldujaili/clipper", "max_forks_repo_head_hexsha": "2e56b2058e8482c33ece3390b3b1b558301eacbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2021-06-09T12:54:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T15:22:29.000Z", "avg_line_length": 22.0, "max_line_length": 79, "alphanum_fraction": 0.5669856459, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.5498439100722521}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2006-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NASA Vision Workbench is licensed under the Apache License,\n//  Version 2.0 (the \"License\"); you may not use this file except in\n//  compliance with the License. You may obtain a copy of the License at\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// __END_LICENSE__\n\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <iomanip>\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <vw/Cartography/GeoReference.h>\n#include <vw/Image/ImageView.h>\n#include <vw/Image/MaskViews.h>\n#include <vw/Image/Statistics.h>\n#include <vw/FileIO/DiskImageResource.h>\n#include <vw/FileIO/DiskImageView.h>\n\n\nusing namespace vw;\n\n/// \\file imagestats.cc Computes a number of statistics about an image\n\n\n\n// TODO: Move this class to a library file!\n/// Class to compute a running standard deviation\n/// - Code adapted from http://www.johndcook.com/standard_deviation.html\nclass RunningStatistics\n{\npublic:\n  RunningStatistics() : m_n(0), m_oldM(0), m_newM(0), m_oldS(0), m_newS(0) \n  {\n    m_min = std::numeric_limits<double>::max();\n    m_max = std::numeric_limits<double>::min();\n  }\n\n  void Clear()\n  {\n    m_n = 0;\n  }\n\n  void Push(double x)\n  {\n    m_n++;\n\n    if (x < m_min)\n        m_min = x;\n    if (x > m_max)\n        m_max = x;\n\n    // See Knuth TAOCP vol 2, 3rd edition, page 232\n    if (m_n == 1)\n    {\n      m_oldM = m_newM = x;\n      m_oldS = 0.0;\n    }\n    else\n    {\n      m_newM = m_oldM + (x - m_oldM)/m_n;\n      m_newS = m_oldS + (x - m_oldM)*(x - m_newM);\n\n      // set up for next iteration\n      m_oldM = m_newM; \n      m_oldS = m_newS;\n    }\n  }\n\n  int NumDataValues() const\n  {\n    return m_n;\n  }\n\n\n  double Min() const\n  {\n    return m_min;\n  }\n\n  double Max() const\n  {\n    return m_max;\n  }\n\n  double Mean() const\n  {\n    return (m_n > 0) ? m_newM : 0.0;\n  }\n\n  double Variance() const\n  {\n    return ( (m_n > 1) ? m_newS/(m_n - 1) : 0.0 );\n  }\n\n  double StandardDeviation() const\n  {\n    return sqrt( Variance() );\n  }\n\nprivate:\n  int    m_n;\n  double m_oldM, m_newM, m_oldS, m_newS;\n  double m_max, m_min;\n\n};\n\n\n/// Function to write the output statistics to an output stream\nbool writeOutput(const std::vector<float > &cdfVector, \n                 const std::vector<double> &levels, \n                 const std::vector<size_t> &hist,\n                 const RunningStatistics   &statCalc,\n                       std::ostream        &stream)\n{\n  \n  stream << \"Mean elevation difference = \" << statCalc.Mean()              << std::endl;\n  stream << \"Standard deviation        = \" << statCalc.StandardDeviation() << std::endl;\n  stream << \"Num valid pixels          = \" << statCalc.NumDataValues()     << std::endl << std::endl;\n\n  // Print out the percentile distribution  \n  stream << \"Image distribution (approximated 5 percent intervals): \" << std::endl;\n  stream.setf(std::ios::fixed, std::ios::floatfield);\n  stream.precision(2);\n  stream.fill(' ');\n  for (size_t i=0; i<cdfVector.size(); ++i)\n  {    \n    double percent = i * 0.05;\n    stream << \"Percentile \" << std::right << std::setw(4) << percent << \" = \" << std::setw(7) << cdfVector[i] << std::endl;\n  }\n  \n  stream << std::endl; // Put a space between the \"charts\"\n\n  // Print out the histogram\n  stream << \"Image histogram (20 bins):\" << std::endl;\n  stream.fill(' ');\n  double ratio = 100.0 / statCalc.NumDataValues();\n  for (size_t i=0; i<hist.size(); ++i)\n  {    \n    stream << std::right << std::setw(8) << levels[i] << \" <-->\" << std::setw(7) << levels[i+1] << \" =\" \n           << std::setw(8) << hist[i] << \" =\" << std::setw(6) << hist[i]*ratio << \"%\" << std::endl;\n  }\n  \n  return true;\n}\n\n//TODO: Print help when no input arguments are used!\nint main( int argc, char *argv[] ) {\n\n  const int numBins = 20; // 5% intervals\n\n  std::string inputImagePath, outputPath=\"\";\n  int removeHistogramOutliers=0;\n  bool absolute;\n\n  po::options_description general_options(\"Options\");\n  general_options.add_options()\n    (\"help,h\",        \"Display this help message\")  \n    (\"output-file,o\", po::value<std::string>(&outputPath)->default_value(\"\"), \"Specify an output text file to store the program output\")\n    (\"limit-hist\",    po::value<int        >(&removeHistogramOutliers)->default_value(0), \"Limits the histogram to +/- N standard deviations from the mean\");\n    (\"absolute\",      po::value<bool       >(&absolute)->default_value(false), \"Work in absolute values\");\n\n  po::options_description positional(\"\");\n  positional.add_options()\n    (\"input-image\",   po::value(&inputImagePath), \"Path to input image file\");\n\n  po::positional_options_description positional_desc;\n  positional_desc.add(\"input-image\",  1);\n\n  std::string usage(\"[options] <input-image>\\n\");\n  po::variables_map vm;\n  try {\n    po::options_description all_options;\n    all_options.add(general_options).add(positional);\n\n    po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).style( po::command_line_style::unix_style ).run(), vm );\n\n    po::notify( vm );\n  } catch (po::error const& e) {\n    vw::vw_throw( vw::ArgumentErr() << \"Error parsing input:\\n\"\n                  << e.what() << \"\\n\" << usage << general_options );\n  }\n\n  if ( !vm.count(\"input-image\") )\n    vw_throw( vw::ArgumentErr() << \"Requires <input-image> input in order to proceed.\\n\\n\"\n              << usage << general_options );\n\n\n  try {\n  \n    //TODO: Operate on multi-channel images of different data types!\n    // Load the image from disk\n    DiskImageView<PixelGray<float> > inputImage(inputImagePath);\n  \n    // First pass computes min, max, mean, and std_dev\n    RunningStatistics statCalc;\n    for (int row=0; row<inputImage.rows(); ++row)\n    {\n    \n      for (int col=0; col<inputImage.cols(); ++col)\n      {\n      \n        if (is_valid(inputImage(col,row))) // Skip invalid pixels\n        {\n          float diff = inputImage(col,row)[0];\n          if (diff > -32767) // Avoid flag value\n          {\n            if (absolute)\n              diff = fabs(diff);\n            statCalc.Push(diff);\n          }\n        }\n      } // End loop through cols\n\n    } // End loop through rows\n   \n    double meanPixelValue   = statCalc.Mean();\n    double stdDevPixelValue = statCalc.StandardDeviation();\n    double minVal           = statCalc.Min();\n    double maxVal           = statCalc.Max();\n\n    if (removeHistogramOutliers > 0) // Cut off range at +/- N std\n    {\n      printf(\"Image min = %lf\\n\", minVal);\n      printf(\"Image max = %lf\\n\", maxVal);\n\n      minVal = meanPixelValue - removeHistogramOutliers*stdDevPixelValue;\n      if (minVal < statCalc.Min())\n        minVal = statCalc.Min();\n      maxVal = meanPixelValue + removeHistogramOutliers*stdDevPixelValue;\n      if (maxVal > statCalc.Max())\n        maxVal = statCalc.Max();\n\n      printf(\"Restricting histogram to +/- %d standard deviations: %lf <--> %lf\\n\", removeHistogramOutliers, minVal, maxVal);\n    }\n\n    double range   = maxVal - minVal;\n    double binSize = range / numBins;\n    double factor  = 1.0 / binSize;\n\n    // Set up levels structure\n    int numLevels = numBins + 1;\n    std::vector<double> levels(numLevels);\n    for (int i=0; i<numLevels; ++i)\n      levels[i] = minVal + i*binSize;\n\n    // CDF \n    vw::math::CDFAccumulator<float> cdfCalc(1000, 251); //TODO: What values to pass in?\n\n    // Next pass fill in histogram\n    std::vector<vw::uint64> hist;\n    hist.assign(numBins, 0);\n    for (int row = 0; row < inputImage.rows(); row++)\n    {\n      for (int col = 0; col < inputImage.cols(); col++)\n      {\n        if (!is_valid(inputImage(col,row))) // Skip invalid pixels\n          continue;\n        float diff = inputImage(col,row)[0];\n        if (diff <= -32767) // Avoid flag value\n          continue;\n        if (absolute)\n          diff = fabs(diff);\n\n        int bin = (int)floor( factor * (diff - minVal)  );\n        if ((bin >= 0) && (bin < numBins)) // If removeHistogramOutliers is set some values will not fit in a bin\n        {\n          ++(hist[bin]);\n          //std::cout << \"bin \" << bin << \" = \" << hist[bin] << std::endl;\n        }\n        else // Invalid bin\n        {\n          //printf(\"range = %lf, binSize = %lf, factor = %lf, minVal = %lf, diff = %lf\\n\", range, binSize, factor, minVal, diff);\n          //std::cout << \"bin \" << bin << std::endl; \n        }\n\n        cdfCalc(diff);\n\n      } // End column loop\n    } // End row loop\n\n    // Fill out the CDF\n    std::vector<float> cdfVector(numLevels);\n    for (int i=0; i<numLevels; ++i) // --> 0.0 to 1.0\n    {    \n      double percent = 0.05 * i;\n      cdfVector[i]   = cdfCalc.quantile(percent);\n    }\n\n    // Write output to console\n    writeOutput(cdfVector, levels, hist, statCalc, std::cout);\n\n    if (!outputPath.empty())  // Write output to file\n    {\n      std::ofstream file(outputPath.c_str());\n      writeOutput(cdfVector, levels, hist, statCalc, file);\n      file.close();\n    }     \n  }\n  catch (const Exception& e) {\n    std::cerr << \"Error: \" << e.what() << std::endl;\n  }\n\n  return 0;\n}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "b5b489bebbf1c667d37741e0389566663113c6d8", "size": 9632, "ext": "cc", "lang": "C++", "max_stars_repo_path": "imagestats.cc", "max_stars_repo_name": "NeoGeographyToolkit/Tools", "max_stars_repo_head_hexsha": "b1a8f4070c4995e7a1787f8f0d9ae603b0699f6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-05-13T22:49:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-08T19:57:11.000Z", "max_issues_repo_path": "imagestats.cc", "max_issues_repo_name": "NeoGeographyToolkit/Tools", "max_issues_repo_head_hexsha": "b1a8f4070c4995e7a1787f8f0d9ae603b0699f6f", "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": "imagestats.cc", "max_forks_repo_name": "NeoGeographyToolkit/Tools", "max_forks_repo_head_hexsha": "b1a8f4070c4995e7a1787f8f0d9ae603b0699f6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-12-17T22:34:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T18:57:32.000Z", "avg_line_length": 28.6666666667, "max_line_length": 158, "alphanum_fraction": 0.6049626246, "num_tokens": 2637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.7826624688140728, "lm_q1q2_score": 0.5498439091370236}}
{"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 rank_features() function \n    from the dlib C++ Library.  \n\n    This example creates a simple set of data and then shows\n    you how to use the rank_features() function to find a good \n    set of features (where \"good\" means the feature set will probably\n    work well with a classification algorithm).\n\n    The data used in this example will be 4 dimensional data and will\n    come from a distribution where points with a distance less than 10\n    from the origin are labeled +1 and all other points are labeled\n    as -1.  Note that this data is conceptually 2 dimensional but we\n    will add two extra features for the purpose of showing what\n    the rank_features() function does.\n*/\n\n\n#include <iostream>\n#include <dlib/svm.h>\n#include <dlib/rand.h>\n#include <vector>\n\nusing namespace std;\nusing namespace dlib;\n\n\nint main()\n{\n\n    // This first typedef declares a matrix with 4 rows and 1 column.  It will be the\n    // object that contains each of our 4 dimensional samples.  \n    typedef matrix<double, 4, 1> sample_type;\n\n\n\n    // Now lets make some vector objects that can hold our samples \n    std::vector<sample_type> samples;\n    std::vector<double> labels;\n\n    dlib::rand rnd;\n\n    for (int x = -30; x <= 30; ++x)\n    {\n        for (int y = -30; y <= 30; ++y)\n        {\n            sample_type samp;\n\n            // the first two features are just the (x,y) position of our points and so\n            // we expect them to be good features since our two classes here are points\n            // close to the origin and points far away from the origin.\n            samp(0) = x;\n            samp(1) = y;\n\n            // This is a worthless feature since it is just random noise.  It should\n            // be indicated as worthless by the rank_features() function below.\n            samp(2) = rnd.get_random_double();\n\n            // This is a version of the y feature that is corrupted by random noise.  It\n            // should be ranked as less useful than features 0, and 1, but more useful\n            // than the above feature.\n            samp(3) = y*0.2 + (rnd.get_random_double()-0.5)*10;\n\n            // add this sample into our vector of samples.\n            samples.push_back(samp);\n\n            // if this point is less than 15 from the origin then label it as a +1 class point.  \n            // otherwise it is a -1 class point\n            if (sqrt((double)x*x + y*y) <= 15)\n                labels.push_back(+1);\n            else\n                labels.push_back(-1);\n        }\n    }\n\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.\n    const sample_type m(mean(mat(samples)));  // compute a mean vector\n    const sample_type sd(reciprocal(stddev(mat(samples)))); // compute a standard deviation vector\n    // now normalize each sample\n    for (unsigned long i = 0; i < samples.size(); ++i)\n        samples[i] = pointwise_multiply(samples[i] - m, sd); \n\n    // This is another thing that is often good to do from a numerical stability point of view.  \n    // However, in our case it doesn't really matter.   It's just here to show you how to do it.\n    randomize_samples(samples,labels);\n\n\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    // 4D sample_type objects.  In general, I would suggest using the same kernel for\n    // classification and feature ranking. \n    typedef radial_basis_kernel<sample_type> kernel_type;\n\n    // The radial_basis_kernel has a parameter called gamma that we need to set.  Generally,\n    // you should try the same gamma that you are using for training.  But if you don't\n    // have a particular gamma in mind then you can use the following function to\n    // find a reasonable default gamma for your data.  Another reasonable way to pick a gamma\n    // is often to use 1.0/compute_mean_squared_distance(randomly_subsample(samples, 2000)).  \n    // It computes the mean squared distance between 2000 randomly selected samples and often\n    // works quite well.\n    const double gamma = verbose_find_gamma_with_big_centroid_gap(samples, labels);\n\n    // Next we declare an instance of the kcentroid object.  It is used by rank_features() \n    // two represent the centroids of the two classes.  The kcentroid has 3 parameters \n    // you need to set.  The first argument to the constructor is the kernel we wish to \n    // use.  The second is a parameter that determines the numerical accuracy with which \n    // the object will perform part of the ranking algorithm.  Generally, smaller values \n    // give better results but cause the algorithm to attempt to use more dictionary vectors \n    // (and thus run slower and use more memory).  The third argument, however, is the \n    // maximum number of dictionary vectors a kcentroid is allowed to use.  So you can use\n    // it to put an upper limit on the runtime complexity.  \n    kcentroid<kernel_type> kc(kernel_type(gamma), 0.001, 25);\n\n    // And finally we get to the feature ranking. Here we call rank_features() with the kcentroid we just made,\n    // the samples and labels we made above, and the number of features we want it to rank.  \n    cout << rank_features(kc, samples, labels) << endl;\n\n    // The output is:\n    /*\n        0 0.749265 \n        1        1 \n        3 0.933378 \n        2 0.825179 \n    */\n\n    // The first column is a list of the features in order of decreasing goodness.  So the rank_features() function\n    // is telling us that the samples[i](0) and samples[i](1) (i.e. the x and y) features are the best two.  Then\n    // after that the next best feature is the samples[i](3) (i.e. the y corrupted by noise) and finally the worst\n    // feature is the one that is just random noise.  So in this case rank_features did exactly what we would\n    // intuitively expect.\n\n\n    // The second column of the matrix is a number that indicates how much the features up to that point\n    // contribute to the separation of the two classes.  So bigger numbers are better since they\n    // indicate a larger separation.  The max value is always 1.  In the case below we see that the bad\n    // features actually make the class separation go down.\n\n    // So to break it down a little more.\n    //    0 0.749265   <-- class separation of feature 0 all by itself\n    //    1        1   <-- class separation of feature 0 and 1\n    //    3 0.933378   <-- class separation of feature 0, 1, and 3\n    //    2 0.825179   <-- class separation of feature 0, 1, 3, and 2\n        \n\n}\n\n", "meta": {"hexsha": "4adaa687fe7fa4d83d7a6bf1a33dbb043685a547", "size": 6898, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DynamicGestures/dlib-18.5/examples/rank_features_ex.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": "DynamicGestures/dlib-18.5/examples/rank_features_ex.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": "DynamicGestures/dlib-18.5/examples/rank_features_ex.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": 45.0849673203, "max_line_length": 115, "alphanum_fraction": 0.6717889243, "num_tokens": 1650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5497652558173322}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\n\nnamespace {\n    bool intersection(const std::set<nombre> &a, const std::set<nombre> &b) {\n        std::set<nombre> i;\n        std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::inserter(i, i.begin()));\n        return i.empty();\n    }\n}\n\nENREGISTRER_PROBLEME(215, \"Crack-free Walls\") {\n    // Consider the problem of building a wall out of 2\u00d71 and 3\u00d71 bricks (horizontal\u00d7vertical dimensions) such that, for\n    // extra strength, the gaps between horizontally-adjacent bricks never line up in consecutive layers, i.e. never\n    // form a \"running crack\".\n    //\n    // For example, the following 9\u00d73 wall is not acceptable due to the running crack shown in red:\n    //\n    // There are eight ways of forming a crack-free 9\u00d73 wall, written W(9,3) = 8.\n    //\n    // Calculate W(32,10).\n    nombre taille = 32;\n    nombre hauteur = 10;\n    std::vector<std::set<nombre>> murs;\n    for (nombre n = 0; 3 * n <= taille; ++n) {\n        if ((taille - 3 * n) % 2 == 0) {\n            vecteur mur((taille - 3 * n) / 2, 2);\n            mur.insert(mur.end(), n, 3);\n            do {\n                std::set<nombre> set_mur;\n                nombre l = 0;\n                for (auto m: mur) {\n                    set_mur.insert(l);\n                    l += m;\n                }\n                set_mur.erase(set_mur.begin());\n                murs.push_back(set_mur);\n            } while (std::next_permutation(mur.begin(), mur.end()));\n        }\n    }\n\n    std::map<std::set<nombre>, std::vector<std::set<nombre>>> I;\n    for (const auto &m1: murs)\n        for (const auto &m2: murs) {\n            if (intersection(m1, m2))\n                I[m1].push_back(m2);\n        }\n\n    std::map<std::set<nombre>, nombre> dp;\n    for (const auto&[k, v]: I)\n        dp[k] = v.size();\n\n    for (nombre h = 2; h < hauteur; ++h) {\n        std::map<std::set<nombre>, nombre> suite_dp;\n        for (const auto&[k, v]: dp) {\n            for (const auto &i: I[k])\n                suite_dp[i] += v;\n        }\n\n        std::swap(suite_dp, dp);\n    }\n\n    nombre resultat = 0;\n    for (const auto&[k, v]: dp)\n        resultat += v;\n\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "e5bf861b38149cb21f087301e041db14226e0c9b", "size": 2316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme2xx/probleme215.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/probleme215.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/probleme215.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.2972972973, "max_line_length": 120, "alphanum_fraction": 0.5349740933, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5497652388783173}}
{"text": "// =============================================================================\n//  BoostIncludes.hpp\n//\n//  MIT License\n//\n//  Copyright (c) 2007-2018 Dairoku Sekiguchi\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\t\\file\t\tBoostIncludes.hpp\n\t\\author\t\tDairoku Sekiguchi\n\t\\version\t1.0\n\t\\date\t\t2008/02/22\n\t\\brief\n*/\n#ifndef __BOOST_INCLUDES_H\n#define __BOOST_INCLUDES_H\n\n\n#pragma warning(disable:4996)\t\t// to suppress std::uninitialized_copy warning\n\n\n// -----------------------------------------------------------------------------\n// \tinclude files\n// -----------------------------------------------------------------------------\n#include <boost/numeric/ublas/vector.hpp>\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/bindings/lapack/gesv.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace traits = boost::numeric::bindings::traits;\n\n\n#endif\t// #ifdef __BOOST_INCLUDES_H\n", "meta": {"hexsha": "5a7c37eeab2e6557037bf63618d1a0a5c99cc399", "size": 2224, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Applications/Sources/BoostIncludes.hpp", "max_stars_repo_name": "dairoku/Calibra", "max_stars_repo_head_hexsha": "f482cf414c24ddbe103b49c1d3a22a8605bb9b03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Applications/Sources/BoostIncludes.hpp", "max_issues_repo_name": "dairoku/Calibra", "max_issues_repo_head_hexsha": "f482cf414c24ddbe103b49c1d3a22a8605bb9b03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Applications/Sources/BoostIncludes.hpp", "max_forks_repo_name": "dairoku/Calibra", "max_forks_repo_head_hexsha": "f482cf414c24ddbe103b49c1d3a22a8605bb9b03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-10T12:43:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-10T12:43:26.000Z", "avg_line_length": 39.7142857143, "max_line_length": 82, "alphanum_fraction": 0.6470323741, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5497317803565531}}
{"text": "#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/storage.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublasx/container/sequence_vector.hpp>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\n\nnamespace ublas = ::boost::numeric::ublas;\nnamespace ublasx = ::boost::numeric::ublasx;\n\n\nBOOST_UBLASX_TEST_DEF( creation_incr )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: Creation - Increasing Sequence\");\n\n\ttypedef short value_type;\n\n\tconst std::size_t n(3);\n\n\tublasx::sequence_vector<value_type> res;\n\tublas::vector<value_type> expect_res(n);\n\n\tres = ublasx::sequence_vector<value_type>(0, 2, n);\n\n\tvalue_type x(0);\n\tfor (std::size_t i = 0; i < n; ++i)\n\t{\n\t\texpect_res(i) = x;\n\t\tx += 2;\n\t}\n\n\tBOOST_UBLASX_DEBUG_TRACE( \"res = \" << res );\n\tBOOST_UBLASX_DEBUG_TRACE( \"expect res = \" << expect_res );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_EQ( res, expect_res, n );\n}\n\n\nBOOST_UBLASX_TEST_DEF( creation_decr )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: Creation - Decreasing Sequence\");\n\n\ttypedef short value_type;\n\n\tconst std::size_t n(3);\n\n\tublasx::sequence_vector<value_type> res;\n\tublas::vector<value_type> expect_res(n);\n\n\tres = ublasx::sequence_vector<value_type>(0, -2, n);\n\n\tvalue_type x(0);\n\tfor (std::size_t i = 0; i < n; ++i)\n\t{\n\t\texpect_res(i) = x;\n\t\tx -= 2;\n\t}\n\n\tBOOST_UBLASX_DEBUG_TRACE( \"res = \" << res );\n\tBOOST_UBLASX_DEBUG_TRACE( \"expect res = \" << expect_res );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_EQ( res, expect_res, n );\n}\n\n\nBOOST_UBLASX_TEST_DEF( creation_from_range )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: Creation - Range\");\n\n\ttypedef short value_type;\n\n\tconst std::size_t n(3);\n\n\tublasx::sequence_vector<value_type> res;\n\tublas::vector<value_type> expect_res(n);\n\n\tres = ublasx::sequence_vector<value_type>(ublas::range(4, 4+n));\n\n\tvalue_type x(4);\n\tfor (std::size_t i = 0; i < n; ++i)\n\t{\n\t\texpect_res(i) = x;\n\t\t++x;\n\t}\n\n\tBOOST_UBLASX_DEBUG_TRACE( \"res = \" << res );\n\tBOOST_UBLASX_DEBUG_TRACE( \"expect res = \" << expect_res );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_EQ( res, expect_res, n );\n}\n\n\nBOOST_UBLASX_TEST_DEF( creation_from_slice )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: Creation - Slice\");\n\n\ttypedef short value_type;\n\n\tconst std::size_t n(3);\n\n\tublasx::sequence_vector<value_type> res;\n\tublas::vector<value_type> expect_res(n);\n\n\tres = ublasx::sequence_vector<value_type>(ublas::slice(5, 3, n));\n\n\tvalue_type x(5);\n\tfor (std::size_t i = 0; i < n; ++i)\n\t{\n\t\texpect_res(i) = x;\n\t\tx += 3;\n\t}\n\n\tBOOST_UBLASX_DEBUG_TRACE( \"res = \" << res );\n\tBOOST_UBLASX_DEBUG_TRACE( \"expect res = \" << expect_res );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_EQ( res, expect_res, n );\n}\n\n\nint main()\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Suite: Sequence Vector class\");\n\n\tBOOST_UBLASX_TEST_BEGIN();\n\n\tBOOST_UBLASX_TEST_DO( creation_incr );\n\tBOOST_UBLASX_TEST_DO( creation_decr );\n\tBOOST_UBLASX_TEST_DO( creation_from_range );\n\tBOOST_UBLASX_TEST_DO( creation_from_slice );\n\n\tBOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "1b71cbcac03ce1a700fe881e960021a58fa1395b", "size": 2912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/sequence_vector.cpp", "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": "libs/numeric/ublasx/test/sequence_vector.cpp", "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": "libs/numeric/ublasx/test/sequence_vector.cpp", "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": 22.5736434109, "max_line_length": 71, "alphanum_fraction": 0.7156593407, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.5497317671894367}}
{"text": "/*\n * Copyright 2010,\n * Fran\u00e7ois Bleibel,\n * Olivier Stasse,\n *\n * CNRS/AIST\n *\n */\n\n#ifndef __SOT_MATRIX_SVD_H__\n#define __SOT_MATRIX_SVD_H__\n\n/* --- Matrix --- */\n#include <Eigen/SVD>\n#include <dynamic-graph/linear-algebra.h>\n\n/* --------------------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\nnamespace dynamicgraph {\n\ntypedef Eigen::JacobiSVD<Matrix> SVD_t;\n\nvoid pseudoInverse(Matrix &_inputMatrix, Matrix &_inverseMatrix,\n                   const double threshold = 1e-6);\n\nvoid dampedInverse(const SVD_t &svd, Matrix &_inverseMatrix,\n                   const double threshold = 1e-6);\n\nvoid dampedInverse(const Matrix &_inputMatrix, Matrix &_inverseMatrix,\n                   Matrix &Uref, Vector &Sref, Matrix &Vref,\n                   const double threshold = 1e-6);\n\nvoid dampedInverse(const Matrix &_inputMatrix, Matrix &_inverseMatrix,\n                   const double threshold = 1e-6);\n\n} // namespace dynamicgraph\n\n#endif /* #ifndef __SOT_MATRIX_SVD_H__ */\n", "meta": {"hexsha": "b9f1f040100f83da18340d6a743aab803ed5d3f9", "size": 1133, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/sot/core/matrix-svd.hh", "max_stars_repo_name": "Rascof/sot-core", "max_stars_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T07:15:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T13:41:06.000Z", "max_issues_repo_path": "include/sot/core/matrix-svd.hh", "max_issues_repo_name": "Rascof/sot-core", "max_issues_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 121.0, "max_issues_repo_issues_event_min_datetime": "2015-02-17T08:38:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T10:54:05.000Z", "max_forks_repo_path": "include/sot/core/matrix-svd.hh", "max_forks_repo_name": "Rascof/sot-core", "max_forks_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-07-01T16:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T15:06:58.000Z", "avg_line_length": 28.325, "max_line_length": 75, "alphanum_fraction": 0.5357458076, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.549706598560958}}
{"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  Vector4d v = Vector4d::Random();\nProjective3d P(Matrix4d::Random());\ncout << \"v                   = \" << v.transpose() << \"]^T\" << endl;\ncout << \"v.hnormalized()     = \" << v.hnormalized().transpose() << \"]^T\" << endl;\ncout << \"P*v                 = \" << (P*v).transpose() << \"]^T\" << endl;\ncout << \"(P*v).hnormalized() = \" << (P*v).hnormalized().transpose() << \"]^T\" << endl;\n  return 0;\n}\n", "meta": {"hexsha": "003027228a79b8f4336e29acddd9b46112c2ef3b", "size": 596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_MatrixBase_hnormalized.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_hnormalized.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_hnormalized.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": 25.9130434783, "max_line_length": 85, "alphanum_fraction": 0.567114094, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5496812427617958}}
{"text": "/**\n * @file cne_test.cpp\n * @author Marcus Edel\n * @author Kartik Nighania\n *\n * Test file for CNE (Conventional Neural Evolution).\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\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/logistic_regression/logistic_regression.hpp>\n\n#include <mlpack/core/optimizers/cne/cne.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\nusing namespace mlpack::distribution;\nusing namespace mlpack::regression;\n\nBOOST_AUTO_TEST_SUITE(CNETest);\n\n/**\n * Training a vanilla network for 2 input XOR function\n */\nBOOST_AUTO_TEST_CASE(CNEXORTest)\n{\n  /*\n   * Create the four cases for XOR with two variable\n   *\n   *  Input    Output\n   * 0 XOR 0  =  0\n   * 1 XOR 1  =  0\n   * 0 XOR 1  =  1\n   * 1 XOR 0  =  1\n   */\n  arma::mat train(\"1, 0, 0, 1; 1, 0, 1, 0\");\n  arma::mat labels(\"1, 1, 2, 2\");\n\n  // CNE may fail to find a good optimum.  But if it can succeed one out of 6\n  // times I think that is sufficient to say it is working.\n  size_t successes = 0;\n  for (size_t trial = 0; trial < 6; ++trial)\n  {\n    // Build a network with 2 input, 2 hidden, and 2 output layers.\n    FFN<NegativeLogLikelihood<> > network;\n\n    network.Add<Linear<> >(2, 2);\n    network.Add<SigmoidLayer<> >();\n    network.Add<Linear<> >(2, 2);\n    network.Add<LogSoftMax<> >();\n\n    // CNE object.\n    CNE opt(60, 5000, 0.1, 0.02, 0.2, 0.1, -1);\n\n    // Training the network with CNE\n    network.Train(train, labels, opt);\n\n    // Predicting for the same train data\n    arma::mat predictionTemp;\n    network.Predict(train, predictionTemp);\n\n    arma::mat prediction = arma::zeros<arma::mat>(1, predictionTemp.n_cols);\n\n    for (size_t i = 0; i < predictionTemp.n_cols; ++i)\n    {\n      prediction(i) = arma::as_scalar(arma::find(\n          arma::max(predictionTemp.col(i)) == predictionTemp.col(i), 1)) + 1;\n    }\n\n    // 1 means 0 and 2 means 1 as the output to XOR.\n    if ((prediction[0] == 1) &&\n        (prediction[1] == 1) &&\n        (prediction[2] == 2) &&\n        (prediction[3] == 2))\n    {\n      ++successes;\n      break;\n    }\n  }\n\n  BOOST_REQUIRE_GT(successes, 0);\n}\n\n/**\n * Train and test a logistic regression function using CNE optimizer\n */\nBOOST_AUTO_TEST_CASE(CNELogisticRegressionTest)\n{\n  // Generate a two-Gaussian dataset.\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  // Shuffle the dataset.\n  arma::uvec indices = arma::shuffle(arma::linspace<arma::uvec>(0,\n      data.n_cols - 1, data.n_cols));\n  arma::mat shuffledData(3, 1000);\n  arma::Row<size_t> shuffledResponses(1000);\n  for (size_t i = 0; i < data.n_cols; ++i)\n  {\n    shuffledData.col(i) = data.col(indices[i]);\n    shuffledResponses[i] = responses[indices[i]];\n  }\n\n  // Create a test set.\n  arma::mat testData(3, 1000);\n  arma::Row<size_t> testResponses(1000);\n  for (size_t i = 0; i < 500; ++i)\n  {\n    testData.col(i) = g1.Random();\n    testResponses[i] = 0;\n  }\n  for (size_t i = 500; i < 1000; ++i)\n  {\n    testData.col(i) = g2.Random();\n    testResponses[i] = 1;\n  }\n\n  CNE opt(200, 10000, 0.2, 0.2, 0.3, 65, -1);\n\n  LogisticRegression<> lr(shuffledData, shuffledResponses, opt, 0.5);\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, 0.3); // 0.3% error tolerance.\n\n  const double testAcc = lr.ComputeAccuracy(testData, testResponses);\n  BOOST_REQUIRE_CLOSE(testAcc, 100.0, 0.6); // 0.6% error tolerance.\n}\n\n/**\n * Training a vanilla network on a larger dataset using CNE optimizer.\n */\nBOOST_AUTO_TEST_CASE(VanillaNetworkWithCNETest)\n{\n  // Load the datasets.\n  arma::mat trainData;\n  data::Load(\"iris_train.csv\", trainData, true);\n\n  arma::mat testData;\n  data::Load(\"iris_test.csv\", testData, true);\n\n  arma::mat trainLabels;\n  data::Load(\"iris_train_labels.csv\", trainLabels, true);\n  trainLabels += 1;\n\n  arma::mat testLabels;\n  data::Load(\"iris_test_labels.csv\", testLabels, true);\n  testLabels += 1;\n\n  // Training the network may fail, so we will try a few times.\n  size_t successes = 0;\n  for (size_t trial = 0; trial < 4; ++trial)\n  {\n    // Create vanilla network with 4 input, 4 hidden and 3 output nodes.\n    FFN<NegativeLogLikelihood<> > model;\n    model.Add<Linear<> >(trainData.n_rows, 4);\n    model.Add<SigmoidLayer<> >();\n    model.Add<Linear<> >(4, 3);\n    model.Add<LogSoftMax<> >();\n\n    // Creating CNE object.\n    // The tolerance and objectiveChange are not taken into consideration.\n    CNE opt(30, 200, 0.2, 0.2, 0.3, -1, -1);\n\n    model.Train(trainData, trainLabels, opt);\n\n    arma::mat predictionTemp;\n    model.Predict(testData, predictionTemp);\n    arma::mat prediction = arma::zeros<arma::mat>(1, predictionTemp.n_cols);\n\n    for (size_t i = 0; i < predictionTemp.n_cols; ++i)\n    {\n      prediction(i) = arma::as_scalar(arma::find(\n          arma::max(predictionTemp.col(i)) == predictionTemp.col(i), 1)) + 1;\n    }\n\n    size_t error = 0;\n    for (size_t i = 0; i < testData.n_cols; i++)\n    {\n      if (int(arma::as_scalar(prediction.col(i))) ==\n          int(arma::as_scalar(testLabels.col(i))))\n      {\n        error++;\n      }\n    }\n\n    double classificationError = 1 - double(error) / testData.n_cols;\n    if (classificationError <= 0.1)\n    {\n      ++successes;\n      break;\n    }\n  }\n\n  BOOST_REQUIRE_GT(successes, 0);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "3e9a7e57be3ee146e370a5fbbbe9f4e4caabc1e4", "size": 6097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/cne_test.cpp", "max_stars_repo_name": "chigur/mlpack", "max_stars_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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-05-02T21:10:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T21:10:55.000Z", "max_issues_repo_path": "src/mlpack/tests/cne_test.cpp", "max_issues_repo_name": "chigur/mlpack", "max_issues_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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/cne_test.cpp", "max_forks_repo_name": "chigur/mlpack", "max_forks_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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": 27.3408071749, "max_line_length": 80, "alphanum_fraction": 0.6383467279, "num_tokens": 1892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5496812373940065}}
{"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_FNMS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FNMS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing fnms capabilities\n\n    Computes the fused substract-multiply of three value.\n\n    @par semantic:\n    For any given value @c x,  @c y,  @c z of type @c T:\n\n    @code\n    T r = fnms(x, y, z);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    T r = -(x*y-s);\n    @endcode\n\n    @par Note:\n\n    fnms can be called with the same modalities as @ref fma\n    and can use the decorator conformant_ to ensure the correct\n    one rounding, no intermediate overflow  behaviour\n\n    @see  fms, fma, fnma\n\n  **/\n  Value fnms(Value const& v0, Value const& v1, Value const& v2);\n} }\n#endif\n\n#include <boost/simd/function/scalar/fnms.hpp>\n#include <boost/simd/function/simd/fnms.hpp>\n\n#endif\n", "meta": {"hexsha": "a3f140f617a67a2b85f31c65cbfef84c220e0c46", "size": 1297, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/fnms.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/fnms.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/fnms.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": 23.5818181818, "max_line_length": 100, "alphanum_fraction": 0.5851966076, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.5496812314170979}}
{"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 dlib C++ library's\r\n    implementation of the pegasos algorithm for online training of support \r\n    vector machines.   \r\n\r\n    This example creates a simple binary classification problem and shows\r\n    you how to train a support vector machine on that data.\r\n\r\n    The data used in this example will be 2 dimensional data and will\r\n    come from a distribution where points with a distance less than 10\r\n    from the origin are labeled +1 and all other points are labeled\r\n    as -1.\r\n        \r\n*/\r\n\r\n\r\n#include <iostream>\r\n#include <ctime>\r\n#include <vector>\r\n#include <dlib/svm.h>\r\n\r\nusing namespace std;\r\nusing namespace dlib;\r\n\r\n\r\nint main()\r\n{\r\n    // The svm functions use column vectors to contain a lot of the data on which they \r\n    // operate. So the first thing we do here is declare a convenient typedef.  \r\n\r\n    // This typedef declares a matrix with 2 rows and 1 column.  It will be the\r\n    // object that contains each of our 2 dimensional samples.   (Note that if you wanted \r\n    // more than 2 features in this vector you can simply change the 2 to something else.\r\n    // Or if you don't know how many features you want until runtime then you can put a 0\r\n    // here and use the matrix.set_size() member function)\r\n    typedef matrix<double, 2, 1> sample_type;\r\n\r\n\r\n    // This is a typedef for the type of kernel we are going to use in this example.\r\n    // In this case I have selected the radial basis kernel that can operate on our\r\n    // 2D sample_type objects\r\n    typedef radial_basis_kernel<sample_type> kernel_type;\r\n\r\n\r\n    // Here we create an instance of the pegasos svm trainer object we will be using.\r\n    svm_pegasos<kernel_type> trainer;\r\n    // Here we setup the parameters to this object.  See the dlib documentation for a \r\n    // description of what these parameters are. \r\n    trainer.set_lambda(0.00001);\r\n    trainer.set_kernel(kernel_type(0.005));\r\n\r\n    // Set the maximum number of support vectors we want the trainer object to use\r\n    // in representing the decision function it is going to learn.  In general, \r\n    // supplying a bigger number here will only ever give you a more accurate\r\n    // answer.  However, giving a smaller number will make the algorithm run\r\n    // faster and decision rules that involve fewer support vectors also take\r\n    // less time to evaluate.  \r\n    trainer.set_max_num_sv(10);\r\n\r\n    std::vector<sample_type> samples;\r\n    std::vector<double> labels;\r\n\r\n    // make an instance of a sample matrix so we can use it below\r\n    sample_type sample, center;\r\n\r\n    center = 20, 20;\r\n\r\n    // Now let's go into a loop and randomly generate 1000 samples.\r\n    srand(time(0));\r\n    for (int i = 0; i < 10000; ++i)\r\n    {\r\n        // Make a random sample vector. \r\n        sample = randm(2,1)*40 - center;\r\n\r\n        // Now if that random vector is less than 10 units from the origin then it is in \r\n        // the +1 class.\r\n        if (length(sample) <= 10)\r\n        {\r\n            // let the svm_pegasos learn about this sample\r\n            trainer.train(sample,+1);\r\n\r\n            // save this sample so we can use it with the batch training examples below\r\n            samples.push_back(sample);\r\n            labels.push_back(+1);\r\n        }\r\n        else\r\n        {\r\n            // let the svm_pegasos learn about this sample\r\n            trainer.train(sample,-1);\r\n\r\n            // save this sample so we can use it with the batch training examples below\r\n            samples.push_back(sample);\r\n            labels.push_back(-1);\r\n        }\r\n    }\r\n\r\n    // Now we have trained our SVM.  Let's see how well it did.  \r\n    // Each of these statements prints out the output of the SVM given a particular sample.  \r\n    // The SVM outputs a number > 0 if a sample is predicted to be in the +1 class and < 0 \r\n    // if a sample is predicted to be in the -1 class.\r\n\r\n    sample(0) = 3.123;\r\n    sample(1) = 4;\r\n    cout << \"This is a +1 example, its SVM output is: \" << trainer(sample) << endl;\r\n\r\n    sample(0) = 13.123;\r\n    sample(1) = 9.3545;\r\n    cout << \"This is a -1 example, its SVM output is: \" << trainer(sample) << endl;\r\n\r\n    sample(0) = 13.123;\r\n    sample(1) = 0;\r\n    cout << \"This is a -1 example, its SVM output is: \" << trainer(sample) << endl;\r\n\r\n\r\n\r\n\r\n\r\n    // The previous part of this example program showed you how to perform online training\r\n    // with the pegasos algorithm.  But it is often the case that you have a dataset and you \r\n    // just want to perform batch learning on that dataset and get the resulting decision\r\n    // function.  To support this the dlib library provides functions for converting an online\r\n    // training object like svm_pegasos into a batch training object.  \r\n\r\n    // First let's clear out anything in the trainer object.\r\n    trainer.clear();\r\n\r\n    // Now to begin with, you might want to compute the cross validation score of a trainer object\r\n    // on your data.  To do this you should use the batch_cached() function to convert the svm_pegasos object\r\n    // into a batch training object.  Note that the second argument to batch_cached() is the minimum \r\n    // learning rate the trainer object must report for the batch_cached() function to consider training\r\n    // complete.  So smaller values of this parameter cause training to take longer but may result\r\n    // in a more accurate solution. \r\n    // Here we perform 4-fold cross validation and print the results\r\n    cout << \"cross validation: \" << cross_validate_trainer(batch_cached(trainer,0.1), samples, labels, 4);\r\n\r\n    // Here is an example of creating a decision function.  Note that we have used the verbose_batch_cached()\r\n    // function instead of batch_cached() as above.  They do the same things except verbose_batch_cached() will\r\n    // print status messages to standard output while training is under way.\r\n    decision_function<kernel_type> df = verbose_batch_cached(trainer,0.1).train(samples, labels);\r\n\r\n    // At this point we have obtained a decision function from the above batch mode training.\r\n    // Now we can use it on some test samples exactly as we did above.\r\n\r\n    sample(0) = 3.123;\r\n    sample(1) = 4;\r\n    cout << \"This is a +1 example, its SVM output is: \" << df(sample) << endl;\r\n\r\n    sample(0) = 13.123;\r\n    sample(1) = 9.3545;\r\n    cout << \"This is a -1 example, its SVM output is: \" << df(sample) << endl;\r\n\r\n    sample(0) = 13.123;\r\n    sample(1) = 0;\r\n    cout << \"This is a -1 example, its SVM output is: \" << df(sample) << endl;\r\n\r\n\r\n}\r\n\r\n", "meta": {"hexsha": "fed7869f7429f3ee5fc4acd9b57ac2c507ea8b5f", "size": 6648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/svm_pegasos_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/svm_pegasos_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/svm_pegasos_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": 41.2919254658, "max_line_length": 112, "alphanum_fraction": 0.6592960289, "num_tokens": 1579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5496812301988585}}
{"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#include <boost/multiprecision/mpfr.hpp>\n#include <boost/multiprecision/float128.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/math/tools/ulps_plot.hpp>\n#include <boost/math/special_functions/rsqrt.hpp>\n\nint main()\n{\n    using boost::multiprecision::number;\n    using PreciseReal = number<boost::multiprecision::mpfr_float_backend<1000>>;\n    using CoarseReal = boost::multiprecision::float128;\n    using boost::math::tools::ulps_plot;\n    std::string filename = \"rsqrt_quad_0_100.svg\";\n    int samples = 2500;\n    int width = 1100;\n    auto f = [](PreciseReal x) {\n        using boost::math::rsqrt;\n        return rsqrt(x);\n    };\n    auto plot03 = ulps_plot<decltype(f), PreciseReal, CoarseReal>(f, std::numeric_limits<CoarseReal>::min(), CoarseReal(100), samples);\n    plot03.width(width);\n    std::string title = \"rsqrt ULPs plot at quad precision\";\n    plot03.title(title);\n    plot03.vertical_lines(6);\n    auto g = [](CoarseReal x) {\n        return boost::math::rsqrt(x);\n    };\n    plot03.add_fn(g);\n    plot03.write(filename);\n}\n", "meta": {"hexsha": "8a7b0c1383c2bb4d17b459c18a9d77906ebe8d7b", "size": 1293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/reporting/accuracy/test_rsqrt.cpp", "max_stars_repo_name": "anarthal/boost-unix-mirror", "max_stars_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T13:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T13:52:18.000Z", "max_issues_repo_path": "libs/math/reporting/accuracy/test_rsqrt.cpp", "max_issues_repo_name": "anarthal/boost-unix-mirror", "max_issues_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/reporting/accuracy/test_rsqrt.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 35.9166666667, "max_line_length": 135, "alphanum_fraction": 0.6960556845, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5496812254401893}}
{"text": "static char help[] = \"Solve small CMEs to benchmark intranode performance.\\n\\n\";\n\n#include<iomanip>\n#include <petscmat.h>\n#include <petscvec.h>\n#include <petscviewer.h>\n#include <Sys.h>\n#include <armadillo>\n#include <cmath>\n#include <sys/stat.h>\n#include \"pacmensl_all.h\"\n\nnamespace repressilator_cme {\n// stoichiometric matrix of the toggle switch model\narma::Mat<PetscInt> SM{{1,-1,0,0,0,0},\n                       {0,0,1,-1,0,0},\n                       {0,0,0,0,1,-1},};\n\n// reaction parameters\nconst PetscReal k1{100.0},ka{20.0},ket{6.0},kg{1.0};\n\n// Function to constraint the shape of the Fsp\nint lhs_constr(PetscInt num_species,\n               PetscInt num_constrs,\n               PetscInt num_states,\n               PetscInt *states,\n               int *vals,\n               void *args)\n{\n  if (num_species != 3) return -1;\n  if (num_constrs != 6) return -1;\n  for (int i{0}; i < num_states; ++i)\n  {\n    vals[i * num_constrs]     = (states[num_species * i]);\n    vals[i * num_constrs + 1] = (states[num_species * i + 1]);\n    vals[i * num_constrs + 2] = (states[num_species * i + 2]);\n    vals[i * num_constrs + 3] = (states[num_species * i]) * (states[num_species * i + 1]);\n    vals[i * num_constrs + 4] = (states[num_species * i + 2]) * (states[num_species * i + 1]);\n    vals[i * num_constrs + 5] = (states[num_species * i]) * (states[num_species * i + 2]);\n  }\n  return 0;\n}\n\narma::Row<int>    rhs_constr{22,2,2,44,4,44};\narma::Row<double> expansion_factors{0.2,0.2,0.2,0.2,0.2,0.2};\narma::Row<int>    rhs_constr_hyperrec{22,2,2};\narma::Row<double> expansion_factors_hyperrec{0.2,0.2,0.2};\n\n// propensity function\ninline PetscReal propensity_rep(const PetscInt *X,const PetscInt k)\n{\n  switch (k)\n  {\n    case 0:return k1 / (1.0 + ka * pow(1.0 * PetscReal(X[1]),ket));\n    case 1:return kg * PetscReal(X[0]);\n    case 2:return k1 / (1.0 + ka * pow(1.0 * PetscReal(X[2]),ket));\n    case 3:return kg * PetscReal(X[1]);\n    case 4:return k1 / (1.0 + ka * pow(1.0 * PetscReal(X[0]),ket));\n    case 5:return kg * PetscReal(X[2]);\n    default:return 0.0;\n  }\n}\n\nint propensity(const int reaction,\n               const int num_species,\n               const int num_states,\n               const int *states,\n               PetscReal *outputs,\n               void *args)\n{\n  int (*X)[3] = ( int (*)[3] ) states;\n  for (int i = 0; i < num_states; ++i)\n  {\n    outputs[i] = propensity_rep(X[i],reaction);\n  }\n  return 0;\n}\n\n}\n\nusing arma::dvec;\nusing arma::Col;\nusing arma::Row;\nusing std::cout;\nusing std::endl;\n\nusing namespace repressilator_cme;\nusing namespace pacmensl;\n\nvoid output_marginals(MPI_Comm comm,std::string model_name,PartitioningType fsp_par_type,\n                      PartitioningApproach fsp_repart_approach,std::string constraint_type,\n                      DiscreteDistribution &solution,arma::Row<int> constraints);\n\nvoid output_performance(MPI_Comm comm,std::string &model_name,PartitioningType fsp_par_type,\n                        PartitioningApproach fsp_repart_approach,std::string constraint_type,\n                        ODESolverType ode_type,\n                        FspSolverMultiSinks &fsp_solver);\n\nint ParseOptions(MPI_Comm comm,\n                 PartitioningType &fsp_par_type,\n                 PartitioningApproach &fsp_repart_approach,\n                 PetscBool &output_marginal,\n                 PetscBool &fsp_log_events,\n                 ODESolverType &ode_solver);\n\nint main(int argc,char *argv[])\n{\n  Environment my_env(&argc,&argv,help);\n\n  PetscMPIInt    ierr,myRank,num_procs;\n  PetscErrorCode petsc_err;\n  MPI_Comm       comm;\n  std::string    part_type;\n  std::string    part_approach;\n\n  MPI_Comm_dup(PETSC_COMM_WORLD,&comm);\n  MPI_Comm_size(comm,&num_procs);\n\n  // Register PETSc stages\n  PetscLogStage stages[4];\n  petsc_err = PetscLogStageRegister(\"Solve with adaptive custom state set shape\",&stages[0]);\n  CHKERRQ(petsc_err);\n  petsc_err = PetscLogStageRegister(\"Solve with fixed custom state set shape\",&stages[1]);\n  CHKERRQ(petsc_err);\n  petsc_err = PetscLogStageRegister(\"Solve with adaptive default state set shape\",&stages[2]);\n  CHKERRQ(petsc_err);\n  petsc_err = PetscLogStageRegister(\"Solve with fixed default state set shape\",&stages[3]);\n  CHKERRQ(petsc_err);\n\n  // Default problem\n  PetscReal           t_final    = 10.0;\n  PetscReal           fsp_tol    = 1.0e-4;\n  std::string         model_name = \"repressilator\";\n  Model               repressilator_model(SM,nullptr,propensity,nullptr,nullptr,std::vector<int>());\n  arma::Mat<PetscInt> X0         = {21,0,0};\n  X0 = X0.t();\n  arma::Col<PetscReal> p0         = {1.0};\n  arma::Mat<PetscInt>  stoich_mat = SM;\n\n  // Default options\n  PartitioningType     fsp_par_type        = PartitioningType::GRAPH;\n  PartitioningApproach fsp_repart_approach = PartitioningApproach::REPARTITION;\n  ODESolverType        fsp_odes_type       = CVODE;\n  PetscBool            output_marginal     = PETSC_FALSE;\n  PetscBool            fsp_log_events      = PETSC_FALSE;\n\n  ierr = ParseOptions(comm,fsp_par_type,fsp_repart_approach,output_marginal,fsp_log_events,fsp_odes_type);\n  CHKERRQ(ierr);\n\n  FspSolverMultiSinks fsp_solver(comm,fsp_par_type,fsp_odes_type);\n  fsp_solver.SetFromOptions();\n  fsp_solver.SetModel(repressilator_model);\n  fsp_solver.SetInitialDistribution(X0,p0);\n  DiscreteDistribution solution;\n\n  petsc_err = PetscLogStagePush(stages[0]);\n  CHKERRQ(petsc_err);\n  // Solve using adaptive custom constraints\n  fsp_solver.SetConstraintFunctions(lhs_constr,nullptr);\n  fsp_solver.SetInitialBounds(rhs_constr);\n  fsp_solver.SetExpansionFactors(expansion_factors);\n  fsp_solver.SetOdeTolerances(1.0e-4,1.0e-14);\n  fsp_solver.SetUp();\n  solution = fsp_solver.Solve(t_final,fsp_tol,0);\n\n  std::shared_ptr<const StateSetConstrained>\n                 fss                 = std::static_pointer_cast<const StateSetConstrained>(fsp_solver.GetStateSet());\n  arma::Row<int> final_custom_constr = fss->GetShapeBounds();\n  if (fsp_log_events)\n  {\n    output_performance(PETSC_COMM_WORLD,model_name,fsp_par_type,fsp_repart_approach,\n                       std::string(\"adaptive_custom\"),fsp_odes_type,fsp_solver);\n  }\n  if (output_marginal)\n  {\n    output_marginals(PETSC_COMM_WORLD,model_name,fsp_par_type,fsp_repart_approach,\n                     std::string(\"adaptive_custom\"),solution,final_custom_constr);\n  }\n  fsp_solver.ClearState();\n  PetscPrintf(comm,\"\\n ================ \\n\");\n\n  petsc_err = PetscLogStagePop();\n  CHKERRQ(petsc_err);\n  petsc_err = PetscLogStagePush(stages[1]);\n  CHKERRQ(petsc_err);\n  // Solve using fixed custom constraints\n  fsp_solver.SetConstraintFunctions(lhs_constr,nullptr);\n  fsp_solver.SetInitialBounds(final_custom_constr);\n  fsp_solver.SetOdeTolerances(1.0e-4,1.0e-14);\n  fsp_solver.SetUp();\n  solution = fsp_solver.Solve(t_final,fsp_tol,0);\n  if (fsp_log_events)\n  {\n    output_performance(PETSC_COMM_WORLD,model_name,fsp_par_type,fsp_repart_approach,\n                       std::string(\"fixed_custom\"),fsp_odes_type,fsp_solver);\n  }\n  if (output_marginal)\n  {\n    output_marginals(PETSC_COMM_WORLD,model_name,fsp_par_type,fsp_repart_approach,\n                     std::string(\"fixed_custom\"),solution,final_custom_constr);\n  }\n  fsp_solver.ClearState();\n  PetscPrintf(comm,\"\\n ================ \\n\");\n\n  petsc_err = PetscLogStagePop();\n  CHKERRQ(petsc_err);\n  petsc_err = PetscLogStagePush(stages[2]);\n  CHKERRQ(petsc_err);\n  // Solve using adaptive default constraints\n  fsp_solver.SetInitialBounds(rhs_constr_hyperrec);\n  fsp_solver.SetExpansionFactors(expansion_factors_hyperrec);\n  fsp_solver.SetFromOptions();\n  fsp_solver.SetOdeTolerances(1.0e-4,1.0e-14);\n  fsp_solver.SetUp();\n  solution = fsp_solver.Solve(t_final,fsp_tol,0);\n  fss      = std::static_pointer_cast<const StateSetConstrained>(fsp_solver.GetStateSet());\n  arma::Row<int> final_hyperrec_constr = fss->GetShapeBounds();\n  if (fsp_log_events)\n  {\n    output_performance(PETSC_COMM_WORLD,model_name,fsp_par_type,fsp_repart_approach,\n                       std::string(\"adaptive_default\"),fsp_odes_type,fsp_solver);\n  }\n  if (output_marginal)\n  {\n    output_marginals(PETSC_COMM_WORLD,model_name,fsp_par_type,fsp_repart_approach,\n                     std::string(\"adaptive_default\"),solution,final_hyperrec_constr);\n  }\n  fsp_solver.ClearState();\n  PetscPrintf(comm,\"\\n ================ \\n\");\n\n  petsc_err = PetscLogStagePop();\n  CHKERRQ(petsc_err);\n  petsc_err = PetscLogStagePush(stages[3]);\n  CHKERRQ(petsc_err);\n  // Solve using fixed default constraints\n  fsp_solver.SetInitialBounds(final_hyperrec_constr);\n  fsp_solver.SetExpansionFactors(expansion_factors_hyperrec);\n  fsp_solver.SetFromOptions();\n  fsp_solver.SetOdeTolerances(1.0e-4,1.0e-14);\n  fsp_solver.SetUp();\n  solution = fsp_solver.Solve(t_final,fsp_tol,0);\n  if (fsp_log_events)\n  {\n    output_performance(PETSC_COMM_WORLD,model_name,fsp_par_type,fsp_repart_approach,\n                       std::string(\"fixed_default\"),fsp_odes_type,fsp_solver);\n  }\n  if (output_marginal)\n  {\n    output_marginals(PETSC_COMM_WORLD,model_name,fsp_par_type,fsp_repart_approach,\n                     std::string(\"fixed_default\"),solution,final_hyperrec_constr);\n  }\n  fsp_solver.ClearState();\n  PetscPrintf(comm,\"\\n ================ \\n\");\n  return ierr;\n}\n\nint ParseOptions(MPI_Comm comm,\n                 PartitioningType &fsp_par_type,\n                 PartitioningApproach &fsp_repart_approach,\n                 PetscBool &output_marginal,\n                 PetscBool &fsp_log_events,\n                 ODESolverType &ode_solver)\n{\n  std::string part_type;\n  std::string part_approach;\n  part_type     = part2str(fsp_par_type);\n  part_approach = partapproach2str(fsp_repart_approach);\n\n  // Read options for fsp\n  char      opt[100];\n  PetscBool opt_set;\n  int       ierr;\n  ierr = PetscOptionsGetString(NULL,PETSC_NULL,\"-fsp_partitioning_type\",opt,100,&opt_set);\n  CHKERRQ(ierr);\n  if (opt_set)\n  {\n    fsp_par_type = str2part(std::string(opt));\n  }\n\n  ierr = PetscOptionsGetString(NULL,PETSC_NULL,\"-fsp_repart_approach\",opt,100,&opt_set);\n  CHKERRQ(ierr);\n  if (opt_set)\n  {\n    fsp_repart_approach = str2partapproach(std::string(opt));\n  }\n\n  ierr = PetscOptionsGetString(NULL,PETSC_NULL,\"-fsp_output_marginal\",opt,100,&opt_set);\n  CHKERRQ(ierr);\n  if (opt_set)\n  {\n    if (strcmp(opt,\"1\") == 0 || strcmp(opt,\"true\") == 0)\n    {\n      output_marginal = PETSC_TRUE;\n    }\n  }\n\n  ierr = PetscOptionsGetString(NULL,PETSC_NULL,\"-fsp_log_events\",opt,100,&opt_set);\n  CHKERRQ(ierr);\n  if (opt_set)\n  {\n    if (strcmp(opt,\"1\") == 0 || strcmp(opt,\"true\") == 0)\n    {\n      fsp_log_events = PETSC_TRUE;\n    }\n  }\n\n  ierr = PetscOptionsGetString(NULL,PETSC_NULL,\"-fsp_use_solver\",opt,100,&opt_set);\n  CHKERRQ(ierr);\n  if (opt_set)\n  {\n    if (strcmp(opt,\"krylov\") == 0)\n    {\n      ode_solver = KRYLOV;\n    } else\n    {\n      ode_solver = CVODE;\n    }\n  }\n\n  PetscPrintf(comm,\"Partitiniong option %s \\n\",part2str(fsp_par_type).c_str());\n  PetscPrintf(comm,\"Repartitoning option %s \\n\",partapproach2str(fsp_repart_approach).c_str());\n  return 0;\n}\n\nvoid output_performance(MPI_Comm comm,std::string &model_name,PartitioningType fsp_par_type,\n                        PartitioningApproach fsp_repart_approach,std::string constraint_type,\n                        ODESolverType ode_type,\n                        FspSolverMultiSinks &fsp_solver)\n{\n  int myRank,num_procs;\n  MPI_Comm_rank(comm,&myRank);\n  MPI_Comm_size(comm,&num_procs);\n\n  std::string ode;\n  if (ode_type == KRYLOV)\n  {\n    ode = \"krylov\";\n  } else\n  {\n    ode = \"cvode\";\n  }\n\n  std::string part_type;\n  std::string part_approach;\n  part_type     = part2str(fsp_par_type);\n  part_approach = partapproach2str(fsp_repart_approach);\n\n  // Output time breakdowns\n  FspSolverComponentTiming    sum_times, min_times, max_times;\n  sum_times = fsp_solver.ReduceComponentTiming(\"sum\");\n  min_times = fsp_solver.ReduceComponentTiming(\"min\");\n  max_times = fsp_solver.ReduceComponentTiming(\"max\");\n\n  if (myRank == 0)\n  {\n    struct stat buffer;\n    int fstat;\n\n    std::string   filename =\n                      model_name + \"_time_breakdown.dat\";\n\n    fstat = stat (filename.c_str(), &buffer);\n\n    std::ofstream file;\n    file.open(filename,std::ios_base::app);\n\n    if (fstat != 0){\n      file << \"ncpu,partitioner,fsp_shape,ode_solver,min_cput,max_cput,avg_cput,mat_gen_time,ode_time,state_expand_time,min_flops,max_flops,avg_flops \\n\";\n    }\n\n    file << num_procs << \",\"\n        << part_type << \",\"\n        << constraint_type << \",\"\n        << ode << \",\"\n        << min_times.TotalTime << \",\"\n        << max_times.TotalTime << \",\"\n        << sum_times.TotalTime/num_procs << \",\"\n        << sum_times.MatrixGenerationTime/num_procs << \",\"\n        << sum_times.ODESolveTime/num_procs << \",\"\n        << sum_times.StatePartitioningTime/num_procs << \",\"\n        << min_times.TotalFlops << \",\"\n        << max_times.TotalFlops << \",\"\n        << sum_times.TotalFlops/num_procs << \"\\n\"\n        ;\n    file.close();\n  }\n\n  FiniteProblemSolverPerfInfo perf_info   = fsp_solver.GetSolverPerfInfo();\n\n  if (myRank == 0){\n    std::string filename =\n        model_name + \"_perf_info_\" + std::to_string(num_procs) + \"_\" + part_type + \"_\" + part_approach + \"_\" +\n            constraint_type + \".dat\";\n    std::ofstream file;\n    file.open(filename);\n    file << \"Model time, ODEs size, Average processor time (sec) \\n\";\n    for (auto i{0}; i < perf_info.n_step; ++i)\n    {\n      file << perf_info.model_time[i] << \",\" << perf_info.n_eqs[i] << \",\" << perf_info.cpu_time[i] << \"\\n\";\n    }\n    file.close();\n  }\n}\n\nvoid output_marginals(MPI_Comm comm,std::string model_name,PartitioningType fsp_par_type,\n                      PartitioningApproach fsp_repart_approach,std::string constraint_type,\n                      DiscreteDistribution &solution,arma::Row<int> constraints)\n{\n  int myRank,num_procs;\n  MPI_Comm_rank(comm,&myRank);\n  MPI_Comm_size(comm,&num_procs);\n\n  std::string part_type;\n  std::string part_approach;\n  part_type     = part2str(fsp_par_type);\n  part_approach = partapproach2str(fsp_repart_approach);\n\n  /* Compute the marginal distributions */\n  std::vector<arma::Col<PetscReal>> marginals(solution.states_.n_rows);\n  for (PetscInt                     i{0}; i < marginals.size(); ++i)\n  {\n    marginals[i] = Compute1DMarginal(solution,i);\n  }\n\n  MPI_Comm_rank(PETSC_COMM_WORLD,&myRank);\n  if (myRank == 0)\n  {\n    for (PetscInt i{0}; i < marginals.size(); ++i)\n    {\n      std::string filename =\n                      model_name.append(\"_marginal_\").append(std::to_string(i)).append(\"_\").append(std::to_string(num_procs)).append(\"_\").append(part_type + \"_\" + part_approach + \"_\" + constraint_type + \".dat\");\n      marginals[i].save(filename,arma::raw_ascii);\n    }\n    std::string   filename =\n                      model_name + \"_constraint_bounds_\" + std::to_string(num_procs) + \"_\" + part_type + \"_\"\n                          + part_approach +\n                          \"_\" + constraint_type + \".dat\";\n    constraints.save(filename,arma::raw_ascii);\n  }\n}\n", "meta": {"hexsha": "a5f471a75972808ea918e3a30a128cb8f67506f2", "size": 14974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/repressilator.cpp", "max_stars_repo_name": "voduchuy/pacmensl", "max_stars_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_stars_repo_licenses": ["MIT"], "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/repressilator.cpp", "max_issues_repo_name": "voduchuy/pacmensl", "max_issues_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_issues_repo_licenses": ["MIT"], "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/repressilator.cpp", "max_forks_repo_name": "voduchuy/pacmensl", "max_forks_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_forks_repo_licenses": ["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.9546485261, "max_line_length": 211, "alphanum_fraction": 0.6608788567, "num_tokens": 4151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5496751968539831}}
{"text": "#include <Eigen/Eigenvalues>\n#include <cmath>\n#include <iostream>\n#include <solvers/bfgs.hpp>\n#include <solvers/sqp.hpp>\n\n#ifndef SOLVER_ASSERT\n#define SOLVER_ASSERT(x) eigen_assert(x)\n#endif\n\nnamespace sqp {\n\ntemplate <typename T>\nSQP<T>::SQP() {\n    // TODO(mi): Performance strongly depends on QP solver settings, which is bad.\n    qp_solver_.settings().warm_start = true;\n    qp_solver_.settings().check_termination = 10;\n    qp_solver_.settings().eps_abs = 1e-4;\n    qp_solver_.settings().eps_rel = 1e-4;\n    qp_solver_.settings().max_iter = 100;\n    qp_solver_.settings().adaptive_rho = true;\n    qp_solver_.settings().adaptive_rho_interval = 50;\n    qp_solver_.settings().alpha = 1.6;\n}\n\ntemplate <typename T>\nvoid SQP<T>::solve(Problem& prob, const Vector& x0, const Vector& lambda0) {\n    x_ = x0;\n    lambda_ = lambda0;\n    run_solve(prob);\n}\n\ntemplate <typename T>\nvoid SQP<T>::solve(Problem& prob) {\n    const int nx = prob.num_var;\n    const int nc = prob.num_constr;\n\n    x_.setZero(nx);\n    lambda_.setZero(nc);\n    run_solve(prob);\n}\n\ntemplate <typename T>\nvoid SQP<T>::run_solve(Problem& prob) {\n    Vector p;         // search direction\n    Vector p_lambda;  // dual search direction\n    Scalar alpha;     // step size\n\n    const int nx = prob.num_var;\n    const int nc = prob.num_constr;\n\n    p.resize(nx);\n    p_lambda.resize(nc);\n\n    step_prev_.resize(nx);\n    grad_L_.resize(nx);\n    delta_grad_L_.resize(nx);\n\n    Hess_.resize(nx, nx);\n    grad_obj_.resize(nx);\n    Jac_constr_.resize(nc, nx);\n    constr_.resize(nc);\n    l_.resize(nc);\n    u_.resize(nc);\n\n    info_.qp_solver_iter = 0;\n\n    if (settings_.iteration_callback) {\n        settings_.iteration_callback(*this);\n    }\n\n    int& iter = info_.iter;\n    for (iter = 1; iter <= settings_.max_iter; iter++) {\n        // Solve QP\n        solve_qp(prob, p, p_lambda);\n        p_lambda -= lambda_;\n\n        alpha = line_search(prob, p);\n\n        // take step\n        x_ = x_ + alpha * p;\n        lambda_ = lambda_ + alpha * p_lambda;\n\n        // update step info\n        step_prev_ = alpha * p;\n        primal_step_norm_ = alpha * p.template lpNorm<Eigen::Infinity>();\n        dual_step_norm_ = alpha * p_lambda.template lpNorm<Eigen::Infinity>();\n\n        if (settings_.iteration_callback) {\n            settings_.iteration_callback(*this);\n        }\n\n        if (termination_criteria(x_, prob)) {\n            info_.status = SOLVED;\n            break;\n        }\n    }\n    if (iter > settings_.max_iter) {\n        info_.status = MAX_ITER_EXCEEDED;\n    }\n}\n\ntemplate <typename Matrix>\nbool is_posdef_eigen(Matrix H) {\n    Eigen::EigenSolver<Matrix> eigensolver(H);\n    for (int i = 0; i < eigensolver.eigenvalues().rows(); i++) {\n        double v = eigensolver.eigenvalues()(i).real();\n        if (v <= 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename Matrix>\nbool is_posdef(Matrix H) {\n    Eigen::LLT<Matrix> llt(H);\n    if (llt.info() == Eigen::NumericalIssue) {\n        return false;\n    }\n    return true;\n}\n\ntemplate <typename T>\nbool SQP<T>::termination_criteria(const Vector& x, Problem& prob) {\n    if (primal_step_norm_ <= settings_.eps_prim && dual_step_norm_ <= settings_.eps_dual &&\n        max_constraint_violation(x, prob) <= settings_.eps_prim) {\n        return true;\n    }\n    return false;\n}\n\ntemplate <typename Derived>\ninline bool is_nan(const Eigen::MatrixBase<Derived>& x) {\n    // return ((x.array() == x.array())).all();\n    return x.array().isNaN().any();\n}\n\ntemplate <typename T>\nvoid SQP<T>::solve_qp(Problem& prob, Vector& step, Vector& lambda) {\n    /* QP from linearized NLP:\n     * minimize     0.5 x'.P.x + q'.x\n     * subject to   l <= A.x + b <= u\n     *\n     * with:\n     *   P      Hessian of Lagrangian\n     *   q      objective gradient\n     *   A,b    linearized constraint at current iterate\n     *   l,u    constraint bounds\n     *\n     * transform to:\n     * minimize     0.5 x'.P.x + q'.x\n     * subject to   l <= A.x <= u\n     *\n     * Where the constraint bounds l,u set to l=u for equality constraints or\n     * set to +/-INFINITY if unbounded.\n     */\n    prob.objective_linearized(x_, grad_obj_, obj_);\n    prob.constraint_linearized(x_, Jac_constr_, constr_, l_, u_);\n\n    delta_grad_L_ = -grad_L_;\n    grad_L_ = grad_obj_ + Jac_constr_.transpose() * lambda_;\n\n    // BFGS update\n    if (info_.iter == 1) {\n        Hess_.setIdentity();\n    } else {\n        delta_grad_L_ += grad_L_;  // delta_grad_L_ = grad_L_prev - grad_L\n        BFGS_update(Hess_, step_prev_, delta_grad_L_);\n    }\n\n    if (!is_posdef(Hess_)) {\n        std::cout << \"Hessian not positive definite\\n\";\n        Scalar tau = 1e-3;\n        Vector v = Vector(prob.num_var);\n        while (!is_posdef(Hess_)) {\n            v.setConstant(tau);\n            Hess_ += v.asDiagonal();\n            tau *= 10;\n        }\n    }\n    if (is_nan(Hess_)) {\n        std::cout << \"Hessian is NaN\\n\";\n    }\n\n    SOLVER_ASSERT(is_posdef(Hess_));\n    SOLVER_ASSERT(!is_nan(Hess_));\n\n    // Constraints\n    // from   l <= A.x + b <= u\n    // to   l-b <= A.x     <= u-b\n    Vector l = l_ - constr_;\n    Vector u = u_ - constr_;\n    Matrix& A = Jac_constr_;\n    Matrix& P = Hess_;\n    Vector& q = grad_obj_;\n\n    // solve the QP\n    run_solve_qp(P, q, A, l, u, step, lambda);\n\n    if (settings_.second_order_correction) {\n        second_order_correction(prob, step, lambda);\n    }\n\n    // TODO:\n    // B is not convex then use grad_L as step direction\n    // i.e. fallback to steepest descent of Lagrangian\n}\n\ntemplate <typename T>\nbool SQP<T>::run_solve_qp(const Matrix& P, const Vector& q, const Matrix& A, const Vector& l,\n                          const Vector& u, Vector& prim, Vector& dual) {\n    qp_solver::QuadraticProblem<Scalar> qp_;\n\n    qp_.P = &P;\n    qp_.q = &q;\n    qp_.A = &A;\n    qp_.l = &l;\n    qp_.u = &u;\n\n    qp_solver_.setup(qp_);\n    qp_solver_.solve(qp_);\n\n    info_.qp_solver_iter += qp_solver_.info().iter;\n\n    if (qp_solver_.info().status == qp_solver::NUMERICAL_ISSUES) {\n        std::cout << \"QPSolver NUMERICAL_ISSUES\\n\";\n        return false;\n    }\n    // if (qp_solver_.info().status == qp_solver::MAX_ITER_EXCEEDED) {\n    //     std::cout << \"QPSolver MAX_ITER_EXCEEDED\\n\";\n    //     return false;\n    // }\n\n    prim = qp_solver_.primal_solution();\n    dual = qp_solver_.dual_solution();\n\n    SOLVER_ASSERT(!is_nan(prim));\n    SOLVER_ASSERT(!is_nan(dual));\n\n    return true;\n}\n\ntemplate <typename T>\nvoid SQP<T>::second_order_correction(Problem& prob, Vector& p, Vector& lambda) {\n    // Scalar mu, constr_l1, phi_l1;\n    // constr_l1 = constraint_norm(constr_, l_, u_);\n    // mu = (grad_obj_.dot(p) + 0.5 * p.dot(Hess_ * p)) / ((1 - settings_.rho) * constr_l1);\n    // phi_l1 = obj_ + mu * constr_l1;\n\n    // Scalar obj_step, constr_l1_step, phi_l1_step;\n    // Vector x_step = x_ + p;\n    // prob.objective(x_step, obj_step);\n    // constr_l1_step = constraint_norm(x_step, prob);\n    // phi_l1_step = obj_step + mu * constr_l1_step;\n\n    // printf(\"phi_l1_step %f  phi_l1 %f  constr_l1_step %f  constr_l1 %f\\n\", phi_l1_step, phi_l1,\n    //        constr_l1_step, constr_l1);\n    // if (phi_l1_step >= phi_l1 && constr_l1_step >= constr_l1) {\n    {\n        Vector x_step = x_ + p;\n        Vector constr_step(constr_.rows());\n        prob.constraint(x_step, constr_step, l_, u_);\n\n        Matrix& A = Jac_constr_;\n        Matrix& P = Hess_;\n        Vector& q = grad_obj_;\n\n        Vector d = constr_step - A * p;\n        Vector l = l_ - d;\n        Vector u = u_ - d;\n\n        // TODO: only l and u change, possible to update QP solver more efficiently\n        run_solve_qp(P, q, A, l, u, p, lambda);\n    }\n}\ntemplate <typename T>\ntypename SQP<T>::Scalar SQP<T>::line_search(Problem& prob, const Vector& p) {\n    // Note: using members obj_ and grad_obj_, which are updated in solve_qp().\n\n    Scalar mu, phi_l1, Dp_phi_l1;\n    const Scalar tau = settings_.tau;  // line search step decrease, 0 < tau < settings.tau\n\n    Scalar constr_l1 = constraint_norm(constr_, l_, u_);\n\n    // get mu from merit function model using hessian of Lagrangian instead\n    mu = (grad_obj_.dot(p) + 0.5 * p.dot(Hess_ * p)) / ((1 - settings_.rho) * constr_l1);\n\n    phi_l1 = obj_ + mu * constr_l1;\n    Dp_phi_l1 = grad_obj_.dot(p) - mu * constr_l1;\n\n    Scalar alpha = 1.0;\n    int i;\n    for (i = 1; i < settings_.line_search_max_iter; i++) {\n        Scalar obj_step;\n        Vector x_step = x_ + alpha * p;\n        prob.objective(x_step, obj_step);\n\n        Scalar phi_l1_step = obj_step + mu * constraint_norm(x_step, prob);\n        if (phi_l1_step <= phi_l1 + alpha * settings_.eta * Dp_phi_l1) {\n            // accept step\n            break;\n        } else {\n            alpha = tau * alpha;\n        }\n    }\n    return alpha;\n}\n\ntemplate <typename T>\ntypename SQP<T>::Scalar SQP<T>::constraint_norm(const Vector &constr, const Vector &l, const Vector &u) const {\n    Scalar c_l1 = DIV_BY_ZERO_REGUL;\n\n    // l <= c(x) <= u\n    c_l1 += (l - constr).cwiseMax(0.0).sum();\n    c_l1 += (constr - u).cwiseMax(0.0).sum();\n\n    return c_l1;\n}\n\ntemplate <typename T>\ntypename SQP<T>::Scalar SQP<T>::constraint_norm(const Vector& x, Problem& prob) {\n    // Note: uses members constr_, l_ and u_ as temporary\n    prob.constraint(x, constr_, l_, u_);\n\n    return constraint_norm(constr_, l_, u_);\n}\n\ntemplate <typename T>\ntypename SQP<T>::Scalar SQP<T>::max_constraint_violation(const Vector& x, Problem& prob) {\n    // Note: uses members constr_, l_ and u_ as temporary\n\n    Scalar c_max = 0;\n    prob.constraint(x, constr_, l_, u_);\n\n    // l <= c(x) <= u\n    if (prob.num_constr > 0) {\n        c_max = fmax(c_max, (l_ - constr_).maxCoeff());\n        c_max = fmax(c_max, (constr_ - u_).maxCoeff());\n    }\n\n    return c_max;\n}\n\ntemplate class SQP<double>;\ntemplate class SQP<float>;\n\n}  // namespace sqp\n", "meta": {"hexsha": "57e0bc11489f3ab79808b051e9cb3a628f3e4dae", "size": 9818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sqp.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": "src/sqp.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": "src/sqp.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": 28.1318051576, "max_line_length": 111, "alphanum_fraction": 0.6067427175, "num_tokens": 2800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5496751828740075}}
{"text": "#include \"PhysicsTools/Utilities/interface/BreitWigner.h\"\n#include \"PhysicsTools/Utilities/interface/HistoChiSquare.h\"\n#include \"PhysicsTools/Utilities/interface/HistoPoissonLikelihoodRatio.h\"\n#include \"PhysicsTools/Utilities/interface/RootMinuitCommands.h\"\n#include \"PhysicsTools/Utilities/interface/RootMinuit.h\"\n#include \"PhysicsTools/Utilities/interface/Parameter.h\"\n#include \"PhysicsTools/Utilities/interface/rootTf1.h\"\n#include \"PhysicsTools/Utilities/interface/rootPlot.h\"\n#include \"TFile.h\"\n#include \"TH1.h\"\n#include \"TF1.h\"\n#include \"TCanvas.h\"\n#include \"TROOT.h\"\n#include <boost/shared_ptr.hpp>\n#include <iostream>\n#include \"PhysicsTools/Utilities/interface/Operations.h\"\n//using namespace std;\n//using namespace boost;\n\ntypedef funct::Product<funct::Parameter, funct::BreitWigner>::type FitFunction;\ntypedef fit::HistoChiSquare<FitFunction> ChiSquared;\ntypedef fit::HistoPoissonLikelihoodRatio<FitFunction> PoissonLR;\n\ntemplate <typename T>\nint main_t(const std::string tag) {\n  try {\n    fit::RootMinuitCommands<T> commands(\"PhysicsTools/Utilities/test/testZMassFit.txt\");\n\n    const char* kYield = \"Yield\";\n    const char* kMass = \"Mass\";\n    const char* kGamma = \"Gamma\";\n\n    funct::Parameter yield(kYield, commands.par(kYield));\n    funct::Parameter mass(kMass, commands.par(kMass));\n    funct::Parameter gamma(kGamma, commands.par(kGamma));\n    funct::BreitWigner bw(mass, gamma);\n\n    FitFunction f = yield * bw;\n    TF1 startFun = root::tf1(\"startFun\", f, 0, 200, yield, mass, gamma);\n    TH1D histo(\"histo\", \"Z mass (GeV/c)\", 200, 0, 200);\n    histo.FillRandom(\"startFun\", yield);\n    TCanvas canvas;\n    startFun.Draw();\n    canvas.SaveAs((tag + \"breitWigner.eps\").c_str());\n    histo.Draw();\n    canvas.SaveAs((tag + \"breitWignerHisto.eps\").c_str());\n    startFun.Draw(\"same\");\n    canvas.SaveAs((tag + \"breitWignerHistoFun.eps\").c_str());\n    histo.Draw(\"e\");\n    startFun.Draw(\"same\");\n\n    T chi2(f, &histo, 80, 120);\n    int fullBins = chi2.numberOfBins();\n    std::cout << \"N. deg. of freedom: \" << fullBins << std::endl;\n    fit::RootMinuit<T> minuit(chi2, true);\n    commands.add(minuit, yield);\n    commands.add(minuit, mass);\n    commands.add(minuit, gamma);\n    commands.run(minuit);\n    ROOT::Math::SMatrix<double, 3, 3, ROOT::Math::MatRepSym<double, 3> > err;\n    minuit.getErrorMatrix(err);\n    std::cout << \"error matrix:\" << std::endl;\n    for (size_t i = 0; i < 3; ++i) {\n      for (size_t j = 0; j < 3; ++j) {\n        std::cout << err(i, j) << \"\\t\";\n      }\n      std::cout << std::endl;\n    }\n    root::plot<FitFunction>((tag + \"breitWignerHistoFunFit.eps\").c_str(), histo, f, 80, 120, yield, mass, gamma);\n  } catch (std::exception& err) {\n    std::cerr << \"Exception caught:\\n\" << err.what() << std::endl;\n    return 1;\n  }\n\n  return 0;\n}\n\nint main() {\n  gROOT->SetStyle(\"Plain\");\n  std::cout << \"=== chi-2 fit ===\" << std::endl;\n  int ret1 = main_t<ChiSquared>(\"chi2_\");\n  if (ret1 != 0)\n    return ret1;\n  std::cout << \"=== poisson LR fit ===\" << std::endl;\n  int ret2 = main_t<PoissonLR>(\"possLR_\");\n  if (ret2 != 0)\n    return ret2;\n  return 0;\n}\n", "meta": {"hexsha": "d2939eda73f009cc68480e3c14a0b3f9dfba4699", "size": 3093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PhysicsTools/Utilities/test/testZMassFit.cpp", "max_stars_repo_name": "NTrevisani/cmssw", "max_stars_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-08T11:39:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-08T11:39:24.000Z", "max_issues_repo_path": "PhysicsTools/Utilities/test/testZMassFit.cpp", "max_issues_repo_name": "NTrevisani/cmssw", "max_issues_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-07-17T02:34:54.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-13T07:58:37.000Z", "max_forks_repo_path": "PhysicsTools/Utilities/test/testZMassFit.cpp", "max_forks_repo_name": "NTrevisani/cmssw", "max_forks_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-27T08:33:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-14T10:52:30.000Z", "avg_line_length": 34.3666666667, "max_line_length": 113, "alphanum_fraction": 0.6650501132, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5496751803167601}}
{"text": "#define DEBUG 1\n/**\n * File    : F.cpp\n * Author  : Kazune Takahashi\n * Created : 2020/7/3 5:48:55\n * Powered by Visual Studio Code\n */\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n// ----- boost -----\n#include <boost/integer/common_factor_rt.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/rational.hpp>\n// ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::integer::gcd; // for C++14 or for cpp_int\nusing boost::integer::lcm; // for C++14 or for cpp_int\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n// ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n// constexpr ll MOD{998'244'353LL}; // be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nbool ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\ntemplate <typename T>\nbool ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\n// ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(Mint const &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(Mint const &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(Mint const &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator/=(Mint const &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }\n  bool operator<(Mint const &a) const { return x < a.x; }\n  bool operator<=(Mint const &a) const { return x <= a.x; }\n  bool operator>(Mint const &a) const { return x > a.x; }\n  bool operator>=(Mint const &a) const { return x >= a.x; }\n  bool operator==(Mint const &a) const { return x == a.x; }\n  bool operator!=(Mint const &a) const { return !(*this == a); }\n  Mint power(ll N) const\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N / 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }\ntemplate <ll MOD>\nMint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }\n// ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i{2LL}; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i{1LL}; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\n// ----- for C++17 -----\ntemplate <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>\nsize_t popcount(T x) { return bitset<64>(x).count(); }\nsize_t popcount(string const &S) { return bitset<200010>{S}.count(); }\n// ----- Infty -----\ntemplate <typename T>\nconstexpr T Infty() { return numeric_limits<T>::max(); }\ntemplate <typename T>\nconstexpr T mInfty() { return numeric_limits<T>::min(); }\n// ----- frequently used constexpr -----\n// constexpr double epsilon{1e-10};\n// constexpr ll infty{1'000'000'000'000'010LL}; // or\n// constexpr int infty{1'000'000'010};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"INF\" << endl;\n  exit(0);\n}\n\n// ----- 2D, 3D, 4D vectors -----\n// Referring to ymatsux-san's source code: https://atcoder.jp/contests/abc138/submissions/7018300\n\ntemplate <typename T>\nvector<vector<T>> Make2DVector(size_t d0, size_t d1, T v = T{})\n{\n  return vector<vector<T>>(d0, vector<T>(d1, v));\n}\n\ntemplate <typename T>\nvector<vector<vector<T>>> Make3DVector(size_t d0, size_t d1, size_t d2, T v = T{})\n{\n  return vector<vector<vector<T>>>(d0, Make2DVector(d1, d2, v));\n}\n\ntemplate <typename T>\nvector<vector<vector<vector<T>>>> Make4DVector(size_t d0, size_t d1, size_t d2, size_t d3, T v = T{})\n{\n  return vector<vector<vector<vector<T>>>>(d0, Make3DVector(d1, d2, d3, v));\n}\n\n// ----- Compressor -----\n// referring to ymatsux-san's code:\n// https://atcoder.jp/contests/abc168/submissions/13337691\n\ntemplate <typename T = ll>\nclass Compressor\n{\n  vector<T> raw;\n  map<T, int> index;\n\npublic:\n  Compressor() {}\n\n  template <typename Container>\n  Compressor(Container const &V) { append(V); }\n\n  template <typename Iter>\n  Compressor(Iter first, Iter last) { append(first, last); }\n\n  template <typename Container>\n  void append(Container const &V) { append(V.begin(), V.end()); }\n\n  template <typename Iter>\n  void append(Iter first, Iter last)\n  {\n    set<T> S(first, last);\n    raw = vector<T>(S.begin(), S.end());\n    sort(raw.begin(), raw.end());\n    for (auto i = size_t{0}; i < raw.size(); ++i)\n    {\n      index[raw[i]] = i;\n    }\n  }\n\n  T to_raw(int i) { return raw[i]; }\n  int to_index(T t) { return index[t]; }\n  size_t size() { return raw.size(); }\n};\n\nconstexpr int dx[4] = {1, 0, -1, 0};\nconstexpr int dy[4] = {0, 1, 0, -1};\n\n// ----- Solve -----\n\nstruct Point\n{\n  int x, y;\n};\n\nostream &operator<<(ostream &os, vector<vector<bool>> v)\n{\n  for (auto i{size_t{0}}; i < v.size(); ++i)\n  {\n    for (auto j{size_t{0}}; j < v[i].size(); ++j)\n    {\n      os << (v[i][j] ? '#' : '.');\n    }\n    os << endl;\n  }\n  return os;\n}\n\nclass Solve\n{\n  int n, m;\n  vector<ll> a, b, c, d, e, f;\n  Compressor<ll> x, y;\n  vector<vector<bool>> visited;\n  vector<vector<vector<bool>>> dir;\n  int size_x, size_y;\n\npublic:\n  Solve(int n, int m) : n{n}, m{m}, a(n), b(n), c(n), d(m), e(m), f(m)\n  {\n    for (auto i{0}; i < n; ++i)\n    {\n      cin >> a[i] >> b[i] >> c[i];\n    }\n    for (auto i{0}; i < m; ++i)\n    {\n      cin >> d[i] >> e[i] >> f[i];\n    }\n    vector<ll> xs{mInfty<ll>(), 0LL, Infty<ll>()}, ys{mInfty<ll>(), 0LL, Infty<ll>()};\n    copy(a.begin(), a.end(), back_inserter(xs));\n    copy(b.begin(), b.end(), back_inserter(xs));\n    copy(c.begin(), c.end(), back_inserter(ys));\n    copy(d.begin(), d.end(), back_inserter(xs));\n    copy(e.begin(), e.end(), back_inserter(ys));\n    copy(f.begin(), f.end(), back_inserter(ys));\n    x.append(xs);\n    y.append(ys);\n    size_x = x.size() - 1;\n    size_y = y.size() - 1;\n    visited = Make2DVector<bool>(size_x, size_y, false);\n    dir = Make3DVector<bool>(size_x, size_y, 4, true);\n    set_segment();\n  }\n\n  void flush()\n  {\n    bfs();\n#if DEBUG == 1\n    cerr << visited;\n#endif\n    cout << answer() << endl;\n  }\n\nprivate:\n  void bfs()\n  {\n    queue<Point> q;\n    {\n      int i{x.to_index(0)};\n      int j{y.to_index(0)};\n      q.push(Point{i, j});\n    }\n    while (!q.empty())\n    {\n      auto p{q.front()};\n      q.pop();\n      for (auto k{0}; k < 4; ++k)\n      {\n        if (!dir[p.x][p.y][k])\n        {\n          continue;\n        }\n        auto nx{p.x + dx[k]};\n        auto ny{p.y + dy[k]};\n        if (!valid(nx, ny))\n        {\n          continue;\n        }\n        if (visited[nx][ny])\n        {\n          continue;\n        }\n        visited[nx][ny] = true;\n        q.push(Point{nx, ny});\n      }\n    }\n  }\n\n  void set_segment()\n  {\n    for (auto i{0}; i < n; ++i)\n    {\n      set_segment_x(a[i], b[i], c[i]);\n    }\n    for (auto i{0}; i < m; ++i)\n    {\n      set_segment_y(d[i], e[i], f[i]);\n    }\n  }\n\n  void set_segment_x(ll xa, ll xb, ll yc)\n  {\n    int ia = x.to_index(xa);\n    int ib = x.to_index(xb);\n    int jc = y.to_index(yc);\n    for (auto i{ia}; i < ib; ++i)\n    {\n      dir.at(i).at(jc - 1).at(1) = false;\n      dir.at(i).at(jc).at(3) = false;\n    }\n  }\n\n  void set_segment_y(ll xd, ll ye, ll yf)\n  {\n    int id = x.to_index(xd);\n    int je = y.to_index(ye);\n    int jf = y.to_index(yf);\n    for (auto j{je}; j < jf; ++j)\n    {\n      dir.at(id - 1).at(j).at(0) = false;\n      dir.at(id).at(j).at(2) = false;\n    }\n  }\n\n  bool valid(int i, int j)\n  {\n    return 0 <= i && i < size_x && 0 <= j && j < size_y;\n  }\n\n  ll area(int i, int j)\n  {\n    ll width{x.to_raw(i + 1) - x.to_raw(i)};\n    ll height{y.to_raw(j + 1) - y.to_raw(j)};\n    return height * width;\n  }\n\n  ll answer()\n  {\n    for (auto i{0}; i < size_x; ++i)\n    {\n      if (visited[i][0] || visited[i][size_y - 1])\n      {\n        No();\n      }\n    }\n    for (auto j{0}; j < size_y; ++j)\n    {\n      if (visited[0][j] || visited[size_x - 1][j])\n      {\n        No();\n      }\n    }\n    ll ans{0};\n    for (auto i{1}; i < size_x - 1; ++i)\n    {\n      for (auto j{1}; j < size_y - 1; ++j)\n      {\n        if (visited[i][j])\n        {\n          ans += area(i, j);\n        }\n      }\n    }\n    return ans;\n  }\n};\n\n// ----- main() -----\n\nint main()\n{\n  int n, m;\n  cin >> n >> m;\n  Solve solve(n, m);\n  solve.flush();\n}\n", "meta": {"hexsha": "87552983fe1f6483c33683fd419fe97737411aac", "size": 10721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/0703_ABC168/F.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2020/0703_ABC168/F.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/0703_ABC168/F.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 22.9081196581, "max_line_length": 101, "alphanum_fraction": 0.5485495756, "num_tokens": 3461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5496751777595126}}
{"text": "#include <blitzml/sparse_linear/logreg_solver.h>\n\n#include <blitzml/base/math_util.h>\n#include <blitzml/base/vector_util.h>\n\n#include \"math.h\"\n\nnamespace BlitzML {\n\ninline value_t SparseLogRegSolver::compute_prob(index_t j) {\n  return is_positive_label[j] ? 1 / (1 + exp_Aomega[j])\n                              : 1 - 1 / (1 + exp_Aomega[j]);\n}\n\n\ninline value_t SparseLogRegSolver::compute_x_value(index_t j) {\n  return is_positive_label[j] ? -1 / (1 + exp_Aomega[j])\n                              : 1 - 1 / (1 + exp_Aomega[j]);\n}\n\nvoid SparseLogRegSolver::initialize_blitz_variables(value_t* initial_conditions) {\n  initialize_is_positive_label();\n  initialize_model(initial_conditions);\n  check_for_degenerate_problem();\n  initialize_x_variables();\n  check_for_poor_initialization();\n  update_bias(30);\n  initialize_y_and_z_variables();\n}\n\n\nvoid SparseLogRegSolver::initialize_is_positive_label() {\n  is_positive_label.assign(num_examples, false);\n  const value_t* labels = data->b_values();\n  num_positive_labels = 0;\n  for (index_t j = 0; j < num_examples; ++j) {\n    if (labels[j] > 0.) {\n      is_positive_label[j] = true;\n      ++num_positive_labels;\n    }\n  }\n}\n\n\nvoid SparseLogRegSolver::initialize_x_variables() {\n  compute_Aomega();\n\n  if (l0_norm(Aomega) == 0) {\n    exp_Aomega.assign(num_examples, 1);\n  } else {\n    exp_Aomega.resize(num_examples);\n    for (index_t j = 0; j < num_examples; ++j) {\n      exp_Aomega[j] = exp(Aomega[j]);\n    }\n  }\n\n  x.resize(num_examples);\n  ATx.resize(num_components);\n  kappa_x = 1.;\n  sum_x = 0.;\n  for (index_t j = 0; j < num_examples; ++j) {\n    x[j] = compute_x_value(j);\n    sum_x += x[j];\n  }\n}\n\n\nvoid SparseLogRegSolver::initialize_y_and_z_variables() {\n  y.assign(num_examples, 0.);\n  ATy.assign(num_components, 0.);\n\n  z = x;\n  ATz.assign(num_components, 0.);\n  kappa_z = 1.0;\n  z_match_x = true;\n  z_match_y = false;\n}\n\n\nvoid SparseLogRegSolver::check_for_degenerate_problem() {\n  problem_is_degenerate = false;\n  if (use_bias) {\n    if (num_positive_labels == 0) {\n      problem_is_degenerate = true;\n      bias = -100.;\n    } else if (num_positive_labels == num_examples) {\n      problem_is_degenerate = true;\n      bias = 100.;\n    }\n    if (problem_is_degenerate) {\n      omega.assign(num_components, 0.);\n    }\n  }\n}\n\n\nvoid SparseLogRegSolver::check_for_poor_initialization() {\n  value_t max_exp_Aomega = max_vector(exp_Aomega);\n  if (max_exp_Aomega > 1e30 || max_exp_Aomega != max_exp_Aomega) {\n    omega.assign(num_components, 0.);\n    initialize_x_variables();\n  }\n}\n\n\nvoid SparseLogRegSolver::update_bias(int max_newton_itr) {\n  if (!use_bias || problem_is_degenerate) {\n    return;\n  }\n\n  value_t exp_delta_total = 1.0;\n  if (is_vector_const(exp_Aomega)) {\n    // Special case closed-form solution:\n    // (this case occurs when we initialize model as all zeros)\n    exp_delta_total = (exp_Aomega[0] * num_positive_labels) /\n                      (num_examples - num_positive_labels);\n    scale_vector(exp_Aomega, exp_delta_total);\n    max_newton_itr = 0;\n  }\n\n  bool last_update_positive = false;\n  for (int itr = 0; itr < max_newton_itr; ++itr) {\n    // Compute derivative:\n    value_t sum_p = 0.;\n    value_t h = 0.;\n    for (index_t j = 0; j < num_examples; ++j) {\n      value_t p = 1 / (1 + exp_Aomega[j]);\n      sum_p += (1 - p);\n      h += p * (1 - p);\n    }\n\n    // Compute update:\n    value_t deriv = num_positive_labels - sum_p;\n    value_t exp_delta = 1 + deriv / h;\n\n    if (exp_delta > 1.) {\n      last_update_positive = true;\n    } else if (last_update_positive) {\n      break;\n    } else if (exp_delta < 0.01) {\n      exp_delta = num_positive_labels / sum_p;\n    }\n\n    // Apply update:\n    exp_delta_total *= exp_delta;\n    scale_vector(exp_Aomega, exp_delta);\n  }\n\n  value_t change = log(exp_delta_total);\n  bias += change;\n\n  sum_x = 0.;\n  for (index_t j = 0; j < num_examples; ++j) {\n    Aomega[j] += change;\n    x[j] = compute_x_value(j);\n    sum_x += x[j];\n  }\n  z_match_x = false;\n}\n\n\nvoid SparseLogRegSolver::perform_backtracking() {\n  if (problem_is_degenerate) {\n    return;\n  }\n\n  std::vector<value_t> low_exp_Aomega = exp_Aomega;\n\n  sum_x = 0.;\n  for (int j = 0; j < num_examples; ++j) {\n    exp_Aomega[j] = exp(Aomega[j] + Delta_Aomega[j] + Delta_bias);\n    x[j] = compute_x_value(j);\n    sum_x += x[j];\n  }\n  value_t deriv_high = compute_backtracking_step_size_derivative(1.0);\n\n  value_t step_size = 1.0;\n\n  if (deriv_high > 0) {\n    value_t high_step = 1.0;\n    std::vector<value_t> high_exp_Aomega = exp_Aomega;\n    value_t low_step = 0.;\n\n    step_size = 0.5;\n    int backtrack_itr = 0;\n    while (++backtrack_itr) {\n      sum_x = 0.;\n      for (index_t j = 0; j < num_examples; ++j) {\n        if (high_exp_Aomega[j] < 1e15 && high_exp_Aomega[j] > 1e-15 &&\n             low_exp_Aomega[j] < 1e15 &&  low_exp_Aomega[j] > 1e-15) {\n          exp_Aomega[j] = sqrt(high_exp_Aomega[j] * low_exp_Aomega[j]);\n        } else {\n          exp_Aomega[j] = exp(Aomega[j] +\n                              step_size * (Delta_Aomega[j] + Delta_bias));\n        }\n        x[j] = compute_x_value(j);\n        sum_x += x[j];\n      }\n\n      value_t deriv = compute_backtracking_step_size_derivative(step_size);\n      if (backtrack_itr >= 5 && deriv < 0) {\n        break;\n      } else if (backtrack_itr >= 20) {\n        break;\n      }\n\n      if (deriv < 0) {\n        low_step = step_size;\n        low_exp_Aomega = exp_Aomega;\n      } else {\n        high_step = step_size;\n        high_exp_Aomega = exp_Aomega;\n      }\n      step_size = (high_step + low_step) / 2;\n    }\n  }\n\n  for (const_index_itr ind = ws.begin_indices();\n       ind != ws.end_indices();\n       ++ind) {\n    index_t i = ws.ith_member(*ind);\n    omega[i] += step_size * Delta_omega[*ind];\n  }\n  bias += step_size * Delta_bias;\n  for (index_t j = 0; j < num_examples; ++j) {\n    Aomega[j] += step_size * (Delta_Aomega[j] + Delta_bias);\n  }\n}\n\n\nvalue_t SparseLogRegSolver::compute_dual_obj() const {\n  value_t loss = 0.;\n  for (index_t j = 0; j < num_examples; ++j) {\n    if (is_positive_label[j]) {\n      if (Aomega[j] > -50) {\n        loss += log1p(1/exp_Aomega[j]);\n      }  else {\n        loss -= Aomega[j];\n      }\n    } else {\n      loss += log1p(exp_Aomega[j]);\n    }\n  }\n  return -(loss + l1_penalty * l1_norm(omega));\n}\n\n\nvoid SparseLogRegSolver::update_subproblem_obj_vals() {\n  obj_vals.set_dual_obj(compute_dual_obj());\n\n  value_t gap = 0.;\n  if (kappa_x >= 1) {\n    kappa_x = 1;\n  }\n  value_t log_kappa = log1p(kappa_x - 1);\n  if (log_kappa != log_kappa) {\n    throw log_kappa;\n  }\n  for (int j = 0; j < num_examples; ++j) {\n    value_t prob, mid_term, last_term;\n    if (is_positive_label[j]) {\n      prob = kappa_x / (1 + exp_Aomega[j]);\n      mid_term = log1p(exp_Aomega[j] - kappa_x);\n      last_term = -Aomega[j];\n    } else {\n      prob = kappa_x - kappa_x / (1 + exp_Aomega[j]);\n      mid_term = log1p(1 / exp_Aomega[j] - kappa_x);\n      last_term = Aomega[j];\n    }\n    gap += prob * log_kappa + (1 - prob) * mid_term + last_term;\n  }\n\n  gap += l1_penalty * l1_norm(omega);\n\n  obj_vals.set_primal_obj_x(obj_vals.dual_obj() + gap);\n}\n\n\nvoid SparseLogRegSolver::update_newton_2nd_derivatives(value_t epsilon_to_add) {\n  sum_newton_2nd_derivatives = 0.;\n  for (index_t j = 0; j < num_examples; ++j) {\n    value_t prob = compute_prob(j);\n    newton_2nd_derivatives[j] = prob * (1 - prob) + epsilon_to_add;\n    sum_newton_2nd_derivatives += newton_2nd_derivatives[j];\n  }\n}\n\n} // namespace BlitzML\n", "meta": {"hexsha": "921f1dfb486417ff1aa81a5b7c6a6138c8670245", "size": 7456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sparse_linear/logreg_solver.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/sparse_linear/logreg_solver.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/sparse_linear/logreg_solver.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": 25.7993079585, "max_line_length": 82, "alphanum_fraction": 0.6220493562, "num_tokens": 2211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5496751740085266}}
{"text": "#include \"pso.h\"\n\n#include <Eigen/StdVector>\n\n\n\ntemplate <\n  typename Scalar, \n  typename DerivedX,\n  typename DerivedLB, \n  typename DerivedUB>\nIGL_INLINE Scalar igl::pso(\n  const std::function< Scalar (DerivedX &) > f,\n  const Eigen::MatrixBase<DerivedLB> & LB,\n  const Eigen::MatrixBase<DerivedUB> & UB,\n  const int max_iters,\n  const int population,\n  DerivedX & X)\n{\n  const Eigen::Array<bool,Eigen::Dynamic,1> P =\n    Eigen::Array<bool,Eigen::Dynamic,1>::Zero(LB.size(),1);\n  return igl::pso(f,LB,UB,P,max_iters,population,X);\n}\n\ntemplate <\n  typename Scalar, \n  typename DerivedX,\n  typename DerivedLB, \n  typename DerivedUB,\n  typename DerivedP>\nIGL_INLINE Scalar igl::pso(\n  const std::function< Scalar (DerivedX &) > f,\n  const Eigen::MatrixBase<DerivedLB> & LB,\n  const Eigen::MatrixBase<DerivedUB> & UB,\n  const Eigen::DenseBase<DerivedP> & P,\n  const int max_iters,\n  const int population,\n  DerivedX & X)\n{\n  const int dim = LB.size();\n  assert(UB.size() == dim && \"UB should match LB size\");\n  assert(P.size() == dim && \"P should match LB size\");\n  typedef std::vector<DerivedX,Eigen::aligned_allocator<DerivedX> > VectorList;\n  VectorList position(population);\n  VectorList best_position(population);\n  VectorList velocity(population);\n  Eigen::Matrix<Scalar,Eigen::Dynamic,1> best_f(population);\n  // https://en.wikipedia.org/wiki/Particle_swarm_optimization#Algorithm\n  //\n  // g \u2192 X\n  // p_i \u2192 best[i]\n  // v_i \u2192 velocity[i]\n  // x_i \u2192 position[i]\n  Scalar min_f = std::numeric_limits<Scalar>::max();\n  for(int p=0;p<population;p++)\n  {\n    {\n      const DerivedX R = DerivedX::Random(dim).array()*0.5+0.5;\n      position[p] = LB.array() + R.array()*(UB-LB).array();\n    }\n    best_f[p] = f(position[p]);\n    best_position[p] = position[p];\n    if(best_f[p] < min_f)\n    {\n      min_f = best_f[p];\n      X = best_position[p];\n    }\n    {\n      const DerivedX R = DerivedX::Random(dim);\n      velocity[p] = (UB-LB).array() * R.array();\n    }\n  }\n\n  int iter = 0;\n  Scalar omega = 0.98;\n  Scalar phi_p = 0.01;\n  Scalar phi_g = 0.01;\n  while(true)\n  {\n    //if(iter % 10 == 0)\n    //{\n    //  std::cout<<iter<<\":\"<<std::endl;\n    //  for(int p=0;p<population;p++)\n    //  {\n    //    std::cout<<\"  \"<<best_f[p]<<\", \"<<best_position[p]<<std::endl;\n    //  }\n    //  std::cout<<std::endl;\n    //}\n\n    for(int p=0;p<population;p++)\n    {\n      const DerivedX R_p = DerivedX::Random(dim).array()*0.5+0.5;\n      const DerivedX R_g = DerivedX::Random(dim).array()*0.5+0.5;\n      velocity[p] = \n        omega * velocity[p].array() +\n        phi_p * R_p.array() *(best_position[p] - position[p]).array() + \n        phi_g * R_g.array() *(               X - position[p]).array();\n      position[p] += velocity[p];\n      // Clamp to bounds\n      for(int d = 0;d<dim;d++)\n      {\n//#define IGL_PSO_REFLECTION\n#ifdef IGL_PSO_REFLECTION\n        assert(!P(d));\n        // Reflect velocities if exceeding bounds\n        if(position[p](d) < LB(d))\n        {\n          position[p](d) = LB(d);\n          if(velocity[p](d) < 0.0) velocity[p](d) *= -1.0;\n        }\n        if(position[p](d) > UB(d))\n        {\n          position[p](d) = UB(d);\n          if(velocity[p](d) > 0.0) velocity[p](d) *= -1.0;\n        }\n#else\n//#warning \"trying no bounds on periodic\"\n//        // TODO: I'm not sure this is the right thing to do/enough. The\n//        // velocities could be weird. Suppose the current \"best\" value is \u03b5 and\n//        // the value is -\u03b5 and the \"periodic bounds\" [0,2\u03c0]. Moding will send\n//        // the value to 2\u03c0-\u03b5 but the \"velocity\" term will now be huge pointing\n//        // all the way from 2\u03c0-\u03b5 to \u03b5.\n//        //\n//        // Q: Would it be enough to try (all combinations) of \u00b1(UB-LB) before\n//        // computing velocities to \"best\"s? In the example above, instead of\n//        //\n//        //     v += best - p = \u03b5 - (2\u03c0-\u03b5) = -2\u03c0+2\u03b5\n//        //\n//        // you'd use\n//        //\n//        //     v +=  / argmin  |b - p|            \\  - p = (\u03b5+2\u03c0)-(2\u03c0-\u03b5) = 2\u03b5\n//        //          |                              |\n//        //           \\ b\u2208{best, best+2\u03c0, best-2\u03c0} /\n//        //\n//        // Though, for multivariate b,p,v this would seem to explode\n//        // combinatorially.\n//        //\n//        // Maybe periodic things just shouldn't be bounded and we hope that the\n//        // forces toward the current minima \"regularize\" them away from insane\n//        // values.\n//        if(P(d))\n//        {\n//          position[p](d) = std::fmod(position[p](d)-LB(d),UB(d)-LB(d))+LB(d);\n//        }else\n//        {\n//          position[p](d) = std::max(LB(d),std::min(UB(d),position[p](d)));\n//        }\n        position[p](d) = std::max(LB(d),std::min(UB(d),position[p](d)));\n#endif\n      }\n      const Scalar fp = f(position[p]);\n      if(fp<best_f[p])\n      {\n        best_f[p] = fp;\n        best_position[p] = position[p];\n        if(best_f[p] < min_f)\n        {\n          min_f = best_f[p];\n          X = best_position[p];\n        }\n      }\n    }\n    iter++;\n    if(iter>=max_iters)\n    {\n      break;\n    }\n  }\n  return min_f;\n}\n\n#ifdef IGL_STATIC_LIBRARY\ntemplate float igl::pso<float, Eigen::Matrix<float, 1, -1, 1, 1, -1>, Eigen::Matrix<float, 1, -1, 1, 1, -1>, Eigen::Matrix<float, 1, -1, 1, 1, -1> >(std::function<float (Eigen::Matrix<float, 1, -1, 1, 1, -1>&)>, Eigen::MatrixBase<Eigen::Matrix<float, 1, -1, 1, 1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<float, 1, -1, 1, 1, -1> > const&, int, int, Eigen::Matrix<float, 1, -1, 1, 1, -1>&);\n#endif\n", "meta": {"hexsha": "8b05ee642afa05ed983337f8477bd3376c0d4949", "size": 5490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "External/libigl-2.1.0/include/igl/pso.cpp", "max_stars_repo_name": "RokKos/eol-cloth", "max_stars_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "External/libigl-2.1.0/include/igl/pso.cpp", "max_issues_repo_name": "RokKos/eol-cloth", "max_issues_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "External/libigl-2.1.0/include/igl/pso.cpp", "max_forks_repo_name": "RokKos/eol-cloth", "max_forks_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3714285714, "max_line_length": 394, "alphanum_fraction": 0.5468123862, "num_tokens": 1695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5496751714512793}}
{"text": "/* The Computer Language Benchmarks Game\n * http://benchmarksgame.alioth.debian.org/\n *\n * contributed by Marcin Zalewski & Jeremiah Willcock\n */\n\n\n#include <iostream>\n#include <gmpxx.h>\n#include <boost/lexical_cast.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <algorithm>\n\nusing namespace boost;\n\nclass Digits {\nprivate:\n  unsigned int j;\n  tuple<mpz_class, mpz_class, mpz_class> nad;\n  mpz_class tmp1, tmp2;\n\npublic:\n  Digits() { j = 0; get<0>(nad) = 1; get<1>(nad) = 0; get<2>(nad) = 1; }\n\n  inline char operator()() {\n    ++j;\n    next_term();\n\n    if(get<0>(nad) > get<1>(nad)) return (*this)();\n\n    mpz_mul_2exp(tmp1.get_mpz_t(), get<0>(nad).get_mpz_t(), 1);\n    tmp1 += get<0>(nad);\n    tmp1 += get<1>(nad);\n\n    mpz_fdiv_qr(tmp1.get_mpz_t(), tmp2.get_mpz_t(), tmp1.get_mpz_t(), get<2>(nad).get_mpz_t());\n\n    tmp2 += get<0>(nad);\n\n    if(tmp2 >= get<2>(nad)) {\n      return (*this)();\n    } else {\n      unsigned int d = tmp1.get_ui();\n      eliminate_digit(d);\n      return d + '0';\n    }\n  }\n\nprivate:\n\n  inline void next_term() {\n    unsigned int y = j * 2 + 1;\n    mpz_mul_2exp(tmp1.get_mpz_t(), get<0>(nad).get_mpz_t(), 1);\n    get<1>(nad) += tmp1;\n    get<1>(nad) *= y;\n    get<0>(nad) *= j;\n    get<2>(nad) *= y;\n  }\n\n  inline void eliminate_digit(unsigned int d) {\n    mpz_submul_ui(get<1>(nad).get_mpz_t(), get<2>(nad).get_mpz_t(), d);\n    get<0>(nad) *= 10;\n    get<1>(nad) *= 10;\n  }\n\n};\n\nvoid pi(unsigned int n) {\n  unsigned int i = 0;\n  Digits digits;\n\n  while((i += 10) <= n) {\n    for(int count = 0; count < 10; ++count) {\n      std::cout << digits();\n    }\n    std::cout << \"\\t:\" << i << '\\n';\n  }\n  \n  i -= 10;\n  if(n > i) {\n    for(int count = 0; count < n - i; ++count) {\n      std::cout << digits();\n    }\n    i += 10;\n    for(int count = 0; count < i - n; ++count) {\n      std::cout << ' ';\n    }\n    std::cout << \"\\t:\" << n << '\\n';\n  }\n}\n\nint main(int argc, char** argv) {\n  std::cout.sync_with_stdio(false);\n  unsigned int count = (argc >= 2 ? boost::lexical_cast<unsigned int>(argv[1]) : 10000);\n  pi(count);\n  return 0;\n}\n", "meta": {"hexsha": "c0434f43f173c003eda423db46406727fa384b94", "size": 2059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "progs/pidigits/pidigits.cpp", "max_stars_repo_name": "qznc/d-shootout", "max_stars_repo_head_hexsha": "40164a864f1d0a08140cde63f7bd2d36010d5332", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-10T15:06:51.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-10T15:06:51.000Z", "max_issues_repo_path": "progs/pidigits/pidigits.cpp", "max_issues_repo_name": "qznc/d-shootout", "max_issues_repo_head_hexsha": "40164a864f1d0a08140cde63f7bd2d36010d5332", "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": "progs/pidigits/pidigits.cpp", "max_forks_repo_name": "qznc/d-shootout", "max_forks_repo_head_hexsha": "40164a864f1d0a08140cde63f7bd2d36010d5332", "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.2268041237, "max_line_length": 95, "alphanum_fraction": 0.5536668286, "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5496751700877696}}
{"text": "// Copyright (c) 2019, Torsten Sattler\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//\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//\n//     * Neither the name of the copyright holder 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 <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// author: Torsten Sattler, torsten.sattler.de@googlemail.com\n\n#include <iostream>\n\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n#include <Eigen/StdVector>\n\n#include \"calibrated_absolute_pose_estimator.h\"\n\nnamespace ransac_lib {\n\nnamespace calibrated_absolute_pose {\n\nstruct NormalizedReprojectionError {\n  NormalizedReprojectionError(double x, double y, double X, double Y, double Z,\n                              double fx, double fy)\n      : point2D_x(x),\n        point2D_y(y),\n        point3D_X(X),\n        point3D_Y(Y),\n        point3D_Z(Z),\n        f_x(fx),\n        f_y(fy) {}\n\n  template <typename T>\n  bool operator()(const T* const camera, T* residuals) const {\n    // The last three entries are the camera position.\n    T p[3];\n    p[0] = point3D_X - camera[3];\n    p[1] = point3D_Y - camera[4];\n    p[2] = point3D_Z - camera[5];\n\n    // The first three entries correspond to the rotation matrix stored in an\n    // angle-axis representation.\n    T p_rot[3];\n    ceres::AngleAxisRotatePoint(camera, p, p_rot);\n\n    T x_proj = static_cast<T>(f_x) * p_rot[0] / p_rot[2];\n    T y_proj = static_cast<T>(f_y) * p_rot[1] / p_rot[2];\n\n    residuals[0] = static_cast<T>(point2D_x) - x_proj;\n    residuals[1] = static_cast<T>(point2D_y) - y_proj;\n\n    return true;\n  }\n\n  // Factory function\n  static ceres::CostFunction* CreateCost(const double x, const double y,\n                                         const double X, const double Y,\n                                         const double Z, const double fx,\n                                         const double fy) {\n    return (new ceres::AutoDiffCostFunction<NormalizedReprojectionError, 2, 6>(\n        new NormalizedReprojectionError(x, y, X, Y, Z, fx, fy)));\n  }\n\n  // Assumes that the measurement is centered around the principal point.\n  // This camera model does not take any radial distortion into account. If\n  // radial distortion is present, one should undistort the measurements first.\n  double point2D_x;\n  double point2D_y;\n  // The 3D point position is fixed as we are only interested in refining the\n  // camera parameters.\n  double point3D_X;\n  double point3D_Y;\n  double point3D_Z;\n  double f_x;\n  double f_y;\n};\n\nCalibratedAbsolutePoseEstimator::CalibratedAbsolutePoseEstimator(\n    const double f_x, const double f_y, const double squared_inlier_threshold,\n    const Points2D& points2D, const ViewingRays& rays, const Points3D& points3D)\n    : focal_x_(f_x),\n      focal_y_(f_y),\n      squared_inlier_threshold_(squared_inlier_threshold),\n      points2D_(points2D),\n      points3D_(points3D),\n      adapter_(rays, points3D) {\n  num_data_ = static_cast<int>(points2D_.size());\n}\n\nint CalibratedAbsolutePoseEstimator::MinimalSolver(\n    const std::vector<int>& sample, CameraPoses* poses) const {\n  poses->clear();\n  CameraPoses p3p_poses = opengv::absolute_pose::p3p_kneip(adapter_, sample);\n  if (p3p_poses.empty()) return 0;\n  for (const CameraPose& pose : p3p_poses) {\n    CameraPose P = pose;\n    // OpenGV returns the transformation from the camera to the world coordinate\n    // system. We store the rotation from the world to the local coordinate\n    // system instead.\n    P.topLeftCorner<3, 3>() = pose.topLeftCorner<3, 3>().transpose();\n    const double kError = EvaluateModelOnPoint(P, sample[3]);\n    if (kError < squared_inlier_threshold_) {\n      //      // Refine using all four points.\n      //      LeastSquares(sample, &P);\n      poses->push_back(P);\n      // At most one pose should be correct.\n      break;\n    }\n  }\n\n  return static_cast<int>(poses->size());\n}\n\n// Returns 0 if no model could be estimated and 1 otherwise.\n// Implemented by a simple linear least squares solver.\nint CalibratedAbsolutePoseEstimator::NonMinimalSolver(\n    const std::vector<int>& sample, CameraPose* pose) const {\n  // Alternative: Run minimal solver and polish.\n  CameraPoses poses;\n  if (MinimalSolver(sample, &poses) == 1) {\n    *pose = poses[0];\n    LeastSquares(sample, pose);\n    return 1;\n  } else {\n    return 0;\n  }\n      \n//   CameraPose P = opengv::absolute_pose::epnp(adapter_, sample);\n//   // OpenGV returns the transformation from the camera to the world coordinate\n//   // system. We store the rotation from the world to the local coordinate\n//   // system instead.\n//   *pose = P;\n//   pose->topLeftCorner<3, 3>() = P.topLeftCorner<3, 3>().transpose();\n//   return 1;\n}\n\n// Evaluates the pose on the i-th data point.\ndouble CalibratedAbsolutePoseEstimator::EvaluateModelOnPoint(\n    const CameraPose& pose, int i) const {\n  Eigen::Vector3d p_c =\n      pose.topLeftCorner<3, 3>() * (points3D_[i] - pose.col(3));\n\n  // Check whether point projects behind the camera.\n  if (p_c[2] < 0.0) return std::numeric_limits<double>::max();\n\n  Eigen::Vector2d p_2d = p_c.head<2>() / p_c[2];\n  p_2d[0] *= focal_x_;\n  p_2d[1] *= focal_y_;\n\n  return (p_2d - points2D_[i]).squaredNorm();\n}\n\n// Reference implementation using Ceres for refinement.\nvoid CalibratedAbsolutePoseEstimator::LeastSquares(\n    const std::vector<int>& sample, CameraPose* pose) const {\n  Eigen::AngleAxisd aax(pose->topLeftCorner<3, 3>());\n  Eigen::Vector3d aax_vec = aax.axis() * aax.angle();\n  double camera[6];\n  camera[0] = aax_vec[0];\n  camera[1] = aax_vec[1];\n  camera[2] = aax_vec[2];\n  camera[3] = pose->col(3)[0];\n  camera[4] = pose->col(3)[1];\n  camera[5] = pose->col(3)[2];\n\n  ceres::Problem refinement_problem;\n//  ceres::LossFunction* cauchy_loss = new ceres::CauchyLoss(1.0);\n  const int kSampleSize = static_cast<int>(sample.size());\n  for (int i = 0; i < kSampleSize; ++i) {\n    const int kIdx = sample[i];\n    const Eigen::Vector2d& p_img = points2D_[kIdx];\n    const Eigen::Vector3d& p_3D = points3D_[kIdx];\n    ceres::CostFunction* cost_function =\n        NormalizedReprojectionError::CreateCost(\n            p_img[0], p_img[1], p_3D[0], p_3D[1], p_3D[2], focal_x_, focal_y_);\n//     double error_i = std::sqrt(EvaluateModelOnPoint(*pose, sample[i]));\n//     error_i = std::max(0.00001, error_i);\n    refinement_problem.AddResidualBlock(cost_function, nullptr, camera);\n//    refinement_problem.AddResidualBlock(cost_function, cauchy_loss, camera);\n//     refinement_problem.AddResidualBlock(cost_function,\n//                                         new ceres::ScaledLoss(nullptr,\n//                                                               1.0 / error_i,\n//                                                               ceres::DO_NOT_TAKE_OWNERSHIP),\n//                                         camera);\n  }\n\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::DENSE_QR;\n  options.minimizer_progress_to_stdout = false;\n  //  options.function_tolerance = 0.000001;\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &refinement_problem, &summary);\n\n  //  std::cout << summary.BriefReport() << std::endl;\n//  delete cauchy_loss;\n//  cauchy_loss = nullptr;\n\n  if (summary.IsSolutionUsable()) {\n    Eigen::Vector3d axis(camera[0], camera[1], camera[2]);\n    double angle = axis.norm();\n    axis.normalize();\n    aax.axis() = axis;\n    aax.angle() = angle;\n\n    pose->topLeftCorner<3, 3>() = aax.toRotationMatrix();\n    pose->col(3) = Eigen::Vector3d(camera[3], camera[4], camera[5]);\n  }\n}\n\n//// Reference implementation using OpenGV's non-linear refinement.\n// void CalibratedAbsolutePoseEstimator::LeastSquares(\n//    const std::vector<int>& sample, CameraPose* pose) const {\n//  // OpenGV returns the transformation from the camera to the world coordinate\n//  // system. We store the rotation from the world to the local coordinate\n//  // system instead.\n//  Eigen::Matrix3d R = pose->topLeftCorner<3, 3>().transpose();\n//  Eigen::Vector3d c = pose->col(3);\n//  // At the moment, we need to copy data as we need to add the current pose\n//  // estimate to the adapter, which would break the requirement that this\n//  // function is constant.\n//  const int kSampleSize = static_cast<int>(sample.size());\n//  opengv::bearingVectors_t bearing_vectors(kSampleSize);\n//  opengv::points_t points(kSampleSize);\n//  for (int i = 0; i < kSampleSize; ++i) {\n//    const int kIdx = sample[i];\n//    bearing_vectors[i] = adapter_.getBearingVector(kIdx);\n//    points[i] = adapter_.getPoint(kIdx);\n//  }\n//\n//  opengv::absolute_pose::CentralAbsoluteAdapter lsq_adapter(bearing_vectors,\n//                                                            points, c, R);\n//\n//  CameraPose P = opengv::absolute_pose::optimize_nonlinear(lsq_adapter);\n//  *pose = P;\n//  pose->topLeftCorner<3, 3>() = P.topLeftCorner<3, 3>().transpose();\n//}\n\nvoid CalibratedAbsolutePoseEstimator::PixelsToViewingRays(\n    const double focal_x, const double focal_y, const Points2D& points2D,\n    ViewingRays* rays) {\n  const int kNumData = static_cast<int>(points2D.size());\n\n  // Creates the bearing vectors and points for the OpenGV adapter.\n  rays->resize(kNumData);\n  for (int i = 0; i < kNumData; ++i) {\n    (*rays)[i] = points2D[i].homogeneous();\n    (*rays)[i][0] /= focal_x;\n    (*rays)[i][1] /= focal_y;\n    (*rays)[i].normalize();\n  }\n}\n}  // namespace calibrated_absolute_pose\n\n}  // namespace ransac_lib\n", "meta": {"hexsha": "4bd3a382d8a76dc274b1a024c987c9dd1f995971", "size": 10672, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/calibrated_absolute_pose_estimator.cc", "max_stars_repo_name": "yocabon/RansacLib", "max_stars_repo_head_hexsha": "4669343cb682efdb0317d4608ea50c808558379d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 216.0, "max_stars_repo_stars_event_min_datetime": "2019-08-17T14:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T06:19:08.000Z", "max_issues_repo_path": "examples/calibrated_absolute_pose_estimator.cc", "max_issues_repo_name": "NamDinhRobotics/RansacLib", "max_issues_repo_head_hexsha": "b66c74b3b3ca3974651dd6343eeecb8ee1d04e56", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-09-27T07:26:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T16:41:41.000Z", "max_forks_repo_path": "examples/calibrated_absolute_pose_estimator.cc", "max_forks_repo_name": "NamDinhRobotics/RansacLib", "max_forks_repo_head_hexsha": "b66c74b3b3ca3974651dd6343eeecb8ee1d04e56", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2019-08-18T05:52:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:01:54.000Z", "avg_line_length": 38.6666666667, "max_line_length": 95, "alphanum_fraction": 0.6684782609, "num_tokens": 2828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5496751612222892}}
{"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 and cols\n    auto row1 = make_row_vector<float> (bm1,0);\n    auto row2 = make_row_vector<float> (bm1,1);\n    auto col1 = make_col_vector<float> (bm1,0);\n    auto col2 = make_col_vector<float> (bm1,1);\n\n    // updating row2 and col2 of bm1, using gemv (matrix-vector multiplication)\n    gemv<float>(bm2,row1,row2); // row2-of-bm1 = bm2 * row1-of-bm1\n    gemv<float>(bm2,col1,col2); // col2-of-bm1 = bm2 * col1-of-bm1\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": "e4fcbe45d9ec6f2d1bc92227b6176ba28b4c1b9f", "size": 1183, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/matrix/test8.7-1/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-1/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-1/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": 30.3333333333, "max_line_length": 79, "alphanum_fraction": 0.6762468301, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5495170149652634}}
{"text": "#include <rubbishrsa/keys.hpp>\n\n#include <rubbishrsa/log.hpp>\n\n#include <boost/property_tree/json_parser.hpp>\n\n#include <boost/multiprecision/miller_rabin.hpp>\n\nnamespace rubbishrsa {\n  private_key private_key::from_factors(const bigint& p, const bigint& q, bigint e) {\n    // We can now start filling in our result\n    private_key ret;\n    ret.n = p * q;\n    // This is automatically done\n    ret.e = e;\n\n    auto lambda_n = carmichael_semiprime(p, q);\n    ret.d = modinv(ret.e, lambda_n); // $d \\equiv e^{-1} \\pmod{\\lambda(n)}$\n\n\n    return ret;\n  }\n\n  private_key private_key::generate(uint_fast16_t bits) {\n    // Apparently we should differ in lengths by a few digits\n    // this will differ in length by log10(2^8) = ~3 digits\n    auto p = generate_prime(bits / 2 + 4);\n    auto q = generate_prime(bits / 2 - 3);\n\n    RUBBISHRSA_LOG_INFO(std::cerr << \"(p, q) = (\" << p.str() << \", \" << q.str() << ')' << std::endl);\n\n    // Now we have a good p and q, we can pass it along\n    return private_key::from_factors(p, q);\n  }\n\n  void public_key::serialise(std::ostream& os) const {\n    boost::property_tree::ptree data;\n    data.put(\"e\", e);\n    data.put(\"n\", n);\n    boost::property_tree::write_json(os, data, false);\n  }\n\n  void private_key::serialise(std::ostream& os) const {\n    boost::property_tree::ptree data;\n    data.put(\"e\", e);\n    data.put(\"d\", d);\n    data.put(\"n\", n);\n    boost::property_tree::write_json(os, data, false);\n  }\n\n  public_key public_key::deserialise(std::istream& is) {\n    boost::property_tree::ptree data;\n    boost::property_tree::read_json(is, data);\n    public_key ret;\n\n    ret.e = data.get<bigint>(\"e\");\n    ret.n = data.get<bigint>(\"n\");\n\n    return ret;\n  }\n\n  private_key private_key::deserialise(std::istream& is) {\n    boost::property_tree::ptree data;\n    boost::property_tree::read_json(is, data);\n    private_key ret;\n\n    ret.e = data.get<bigint>(\"e\");\n    ret.d = data.get<bigint>(\"d\");\n    ret.n = data.get<bigint>(\"n\");\n\n    return ret;\n  }\n}\n", "meta": {"hexsha": "ce2e0a1d3429bfec9df7d5b111577e81084fd905", "size": 1994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/keys.cpp", "max_stars_repo_name": "Cyclic3/rubbishrsa", "max_stars_repo_head_hexsha": "d1755b6ed464c84fa7a44e8665631f28766ee7fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/keys.cpp", "max_issues_repo_name": "Cyclic3/rubbishrsa", "max_issues_repo_head_hexsha": "d1755b6ed464c84fa7a44e8665631f28766ee7fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/keys.cpp", "max_forks_repo_name": "Cyclic3/rubbishrsa", "max_forks_repo_head_hexsha": "d1755b6ed464c84fa7a44e8665631f28766ee7fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9459459459, "max_line_length": 101, "alphanum_fraction": 0.6339017051, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5495170149652634}}
{"text": "\n#include <boost/numeric/ublas/matrix.hpp>\n#include <cmath>\n#include <iostream>\n#include <vector> \n\nstruct Point\n{\npublic:\n\t\tPoint(int x, int y)\n\t\t{\n\t\t\t\tthis->x = x;\n\t\t\t\tthis->y = y;\n\t\t}\n\n\t\tint x;\n\t\tint y;\n};\n\nstruct AStarNode\n{\npublic:\n\t\tAStarNode() {}\n\t\tAStarNode(const AStarNode& p, const Point& pos)\n\t\t{\n\t\t\t\tif (&parent != nullptr)\n\t\t\t\t\t\tparent = std::make_shared<AStarNode>(p);\n\n\t\t\t\tif (&position != nullptr)\n\t\t\t\t\t\tposition = std::make_shared<Point>(pos);\n\t\t}\n\n\t\tbool eq(const AStarNode& x)\n\t\t{\n\t\t\t\tif (&x == nullptr) return false;\n\n\t\t\t\treturn (position->x == x.position->x &&\n\t\t\t\t\t\tposition->y == x.position->y);\n\t\t}\n\n\t\tstd::shared_ptr<AStarNode> parent{};\n\t\tstd::shared_ptr<Point> position{};\n\t\tint f = 0;\n\t\tint g = 0;\n\t\tint h = 0;\n};\n\nclass AStarPathFinder\n{\npublic:\n\t\tAStarPathFinder(boost::numeric::ublas::matrix<int> map)\n\t\t{\n\t\t\t\tthis->map = std::make_shared<boost::numeric::ublas::matrix<int>>(map);\n\t\t}\n\n\t\tstd::shared_ptr<std::vector<Point>> FindPath(Point start, Point end);\n\nprivate:\n\t\tstd::shared_ptr<boost::numeric::ublas::matrix<int>> map;\n};\n\nstd::shared_ptr<std::vector<Point>> AStarPathFinder::FindPath(Point start, Point end)\n{\n\t\tauto path = std::make_shared<std::vector<Point>>();\n\n\t\tAStarNode none{};\n\n\t\tauto start_node = std::make_shared<AStarNode>(none, start);\n\t\tauto end_node = std::make_shared<AStarNode>(none, end);\n\t\tauto open_list = std::make_shared<std::vector<std::shared_ptr<AStarNode>>>();\n\t\tauto closed_list = std::make_shared<std::vector<std::shared_ptr<AStarNode>>>();\n\n\t\tPoint pos_array[4] = {\n\t\t\t\t{ 0, -1 },\n\t\t\t\t{ 0, 1 },\n\t\t\t\t{ -1, 0 },\n\t\t\t\t{ 1, 0 },\n\t\t};\n\n\t\topen_list->emplace_back(start_node);\n\n\t\twhile (open_list->size() > 0)\n\t\t{\n\t\t\t\tauto current_node = open_list->front();\n\t\t\t\tint current_index = 0;\n\n\t\t\t\tint _index = 0;\n\t\t\t\tfor (const auto& item : *open_list)\n\t\t\t\t{\n\t\t\t\t\t\tif (item->f < current_node->f)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcurrent_node = item;\n\t\t\t\t\t\t\t\tcurrent_index = _index;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_index++;\n\t\t\t\t}\n\n\t\t\t\topen_list->erase(open_list->begin() + current_index);\n\t\t\t\tclosed_list->emplace_back(current_node);\n\n\t\t\t\tif (current_node->eq(*end_node))\n\t\t\t\t{\n\t\t\t\t\t\tauto current = current_node;\n\t\t\t\t\t\twhile (current != nullptr && current->position != nullptr)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tPoint path_point = { current->position->x, current->position->y };\n\t\t\t\t\t\t\t\tpath->emplace_back(path_point);\n\t\t\t\t\t\t\t\tcurrent = current->parent;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstd::reverse(path->begin(), path->end());\n\t\t\t\t\t\treturn path;\n\t\t\t\t}\n\n\t\t\t\tauto children = std::make_shared<std::vector<std::shared_ptr<AStarNode>>>();\n\n\t\t\t\tfor (const auto& new_position : pos_array)\n\t\t\t\t{\n\t\t\t\t\t\tauto node_position = std::make_shared<Point>(current_node->position->x + new_position.x, current_node->position->y + new_position.y);\n\n\t\t\t\t\t\tif (node_position->x > (map->size2() - 1) || node_position->x < 0 ||\n\t\t\t\t\t\t\t\tnode_position->y >(map->size1() - 1) || node_position->y < 0) continue;\n\n\t\t\t\t\t\tif ((*map)(node_position->y, node_position->x) != 0) continue;\n\n\t\t\t\t\t\tauto child = std::make_shared<AStarNode>(*current_node, *node_position);\n\t\t\t\t\t\tchildren->emplace_back(child);\n\t\t\t\t}\n\n\t\t\t\tfor (const auto& child : *children)\n\t\t\t\t{\n\t\t\t\t\t\tauto closed_list_result = std::find_if(closed_list->begin(), closed_list->end(),\n\t\t\t\t\t\t\t\t[&](const std::shared_ptr<AStarNode>& c) {\n\t\t\t\t\t\t\t\t\t\treturn c->eq(*child);\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (closed_list_result != closed_list->end() && *closed_list_result != nullptr) \n\t\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tchild->g = current_node->g + 1;\n\t\t\t\t\t\tchild->h = (int)pow(child->position->x - end_node->position->x, 2) + (int)pow(child->position->y - end_node->position->y, 2);\n\t\t\t\t\t\tchild->f = child->g + child->h;\n\n\t\t\t\t\t\tauto open_node_result = std::find_if(open_list->begin(), open_list->end(),\n\t\t\t\t\t\t\t\t[&](const std::shared_ptr<AStarNode>& o) {\n\t\t\t\t\t\t\t\t\t\treturn child->eq(*o) && child->g > o->g;\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (open_node_result != open_list->end() && *open_node_result != nullptr) \n\t\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\topen_list->emplace_back(child);\n\t\t\t\t}\n\t\t}\n\n\t\treturn nullptr;\n}\n\nint main()\n{\n\t\tint map[10][10] = {\n\t\t\t\t{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },\n\t\t\t\t{ 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 },\n\t\t\t\t{ 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 },\n\t\t\t\t{ 0, 1, 1, 1, 1, 1, 1, 1, 0, 0 },\n\t\t\t\t{ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 },\n\t\t\t\t{ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 },\n\t\t\t\t{ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 },\n\t\t\t\t{ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 },\n\t\t\t\t{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },\n\t\t\t\t{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }\n\t\t};\n\n\t\tauto _map = std::make_shared<boost::numeric::ublas::matrix<int>>(10,10);\n\n\t\t// convert map to a boost matrix\n\t\tfor (int r = 0; r < 10; ++r)\n\t\t{\n\t\t\t\tfor (int c = 0; c < 10; ++c)\n\t\t\t\t{\n\t\t\t\t\t\t(*_map)(r, c) = map[r][c];\n\t\t\t\t}\n\t\t}\n\n\t\tauto astar = std::make_shared<AStarPathFinder>(*_map);\n\t\tauto path = astar->FindPath({ 1, 0 }, { 6, 2 });\n\n\t\tstd::cout << \"path steps: \" << path->size() << std::endl;\n\n\t\tfor (int r = 0; r < 10; ++r)\n\t\t{\n\t\t\t\tfor (int c = 0; c < 10; ++c)\n\t\t\t\t{\n\t\t\t\t\t\tauto p = std::find_if(path->begin(), path->end(),\n\t\t\t\t\t\t\t\t[&](const Point& s) {\n\t\t\t\t\t\t\t\t\t\treturn s.x == c && s.y == r;\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (p != path->end()) std::cout << \"+\";\n\t\t\t\t\t\telse if ((*_map)(r, c) == 0) std::cout << \".\";\n\t\t\t\t\t\telse if ((*_map)(r, c) == 1) std::cout << \"#\";\n\t\t\t\t}\n\n\t\t\t\tstd::cout << std::endl;\n\t\t}\n\n\t\t//for (const auto& step : *path)\n\t\t//{\n\t\t//\t\tstd::cout << \"(\" << step.x << \", \" << step.y << \")\" << std::endl;\n\t\t//}\n\n\t\treturn 0;\n}", "meta": {"hexsha": "3fb36abf5f5f85499fada2329a5bf639ea3b5ca0", "size": 5328, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "frankhale/AStarPathFinder_CPP", "max_stars_repo_head_hexsha": "0d0e9d0f760636d0a96911cff0d3c6a1e42cb34b", "max_stars_repo_licenses": ["MIT"], "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": "frankhale/AStarPathFinder_CPP", "max_issues_repo_head_hexsha": "0d0e9d0f760636d0a96911cff0d3c6a1e42cb34b", "max_issues_repo_licenses": ["MIT"], "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": "frankhale/AStarPathFinder_CPP", "max_forks_repo_head_hexsha": "0d0e9d0f760636d0a96911cff0d3c6a1e42cb34b", "max_forks_repo_licenses": ["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.014084507, "max_line_length": 139, "alphanum_fraction": 0.5523648649, "num_tokens": 1845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5494637598939397}}
{"text": "#include <maya/MVector.h>\n#include <maya/MFnTypedAttribute.h>\n#include <maya/MFnNumericAttribute.h>\n#include <maya/MFnPlugin.h>\n#include <maya/MPointArray.h>\n#include <maya/MFnMesh.h>\n#include <maya/MMatrix.h>\n#include <maya/MItGeometry.h>\n#include <maya/MDagPath.h>\n\n#include <numeric>\n#include <cmath>\n#include <vector>\n#include <array>\n\n#include \"tbb/tick_count.h\"\n#include \"tbb/parallel_for.h\"\n#include \"tbb/task_scheduler_init.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n\n#include \"green_cage_deformer.h\"\n\n\nconst MTypeId GreenCageDeformer::s_node_id(0xBBBB9255);\nconst MString GreenCageDeformer::s_node_name(\"green_cage_deformer\");\nMObject GreenCageDeformer::s_cage_mesh;\n\n\nnamespace {\n\tconst Eigen::Vector3d NULL_VECTOR(0.0, 0.0, 0);\n\tconstexpr auto TOLERANCE = 1e-6;\n}\n\n\nnamespace MathConstants {\n\tconstexpr auto PI = 3.14159265358979323846;\n\tconstexpr auto ONE_OVER_FOUR_PI = 0.07957747154594767;\n\tconstexpr auto SQRT8 = 2.828427124746190097603;\n};\n\n\nconst double GCTriInt(const Eigen::Vector3d& p, const Eigen::Vector3d& v1, const Eigen::Vector3d& v2)\n{\n\tconst auto v2_v1 = v2 - v1;\n\tconst auto p_v1 = p - v1;\n\tconst auto v1_p = v1 - p;\n\tconst auto v2_p = v2 - p;\n\n\tconst auto alpha = std::acos(std::min(std::max(((v2_v1).dot((p_v1))) / ((v2_v1).norm() * (p_v1).norm()), -1.0), 1.0));\n\tif (abs(alpha - MathConstants::PI) < TOLERANCE || abs(alpha) < TOLERANCE) {\n\t\treturn 0.0;\n\t}\n\n\tconst auto beta = std::acos(std::min(std::max((((v1_p).dot((v2_p)))) / ((v1_p).norm() * (v2_p).norm()), -1.0), 1.0));\n\tconst auto lambda = p_v1.squaredNorm() * std::sin(alpha) * std::sin(alpha);\n\tconst auto c = p.squaredNorm();\n\n\tconst auto sqrt_c = sqrt(c);\n\tconst auto sqrt_lambda = sqrt(lambda);\n\n\tconst std::array<double, 2> theta{ MathConstants::PI - alpha, MathConstants::PI - alpha - beta };\n\tstd::array<double, 2> I;\n\n\tfor (size_t i = 0; i < 2; ++i)\n\t{\n\t\tconst auto S = std::sin(theta[i]);\n\t\tconst auto C = std::cos(theta[i]);\n\t\tconst auto sign = S < 0 ? -1.0 : 1.0;\n\n\t\tconst auto SS = S*S;\n\t\tconst auto half_sign = (-sign * 0.5);\n\t\tconst auto tan_part = (2 * sqrt_c * std::atan2((sqrt_c * C), sqrt(lambda + (SS * c))));\n\t\tconst auto log_part = log(((2 * sqrt_lambda * SS) / std::pow(1.0 - C, 2)) * (1.0 - ((2 * c * C) / ((c*(1 + C) + lambda + sqrt((lambda * lambda) + (lambda * c * SS)))))));\n\n\t\tI[i] = half_sign * (tan_part + (sqrt_lambda * log_part));\n\t}\n\n\treturn -MathConstants::ONE_OVER_FOUR_PI * abs(I[0] - I[1] - sqrt_c * beta);\n}\n\n\nvoid GCDeformData::setup_cage() {\n\tMStatus stat;\n\tMFnMesh fn_mesh(m_cage_object);\n\tMIntArray m_tri_counts;\n\tfn_mesh.getTriangles(m_tri_counts, m_tri_verts);\n\n\tm_nr_of_tris = 0;\n\tfor (unsigned int i = 0; i < m_tri_counts.length(); ++i)\n\t{\n\t\tm_nr_of_tris += m_tri_counts[i];\n\t}\n\n\n\tMPointArray cage_points;\n\tfn_mesh.getPoints(cage_points);\n\tm_nr_of_verts = fn_mesh.numVertices();\n\tm_vertices.resize(m_nr_of_verts);\n\n\tfor (unsigned int i = 0; i < cage_points.length(); ++i) {\n\t\tconst auto point = cage_points[i];\n\t\tm_vertices[i] = Eigen::Vector3d(point.x, point.y, point.z);\n\t}\n\n\tm_scale_factor.resize(m_nr_of_tris);\n\tm_tri_areas.resize(m_nr_of_tris);\n\tm_tri_normals.resize(m_nr_of_tris);\n\tm_tri_points.resize(m_nr_of_tris);\n\tm_tri_edges.resize(m_nr_of_tris);\n\n\tfor (unsigned int j = 0; j < m_nr_of_tris; ++j) {\n\t\tconst auto tri_idx = j * 3;\n\t\tconst auto v0 = m_vertices[m_tri_verts[tri_idx + 0]];\n\t\tconst auto v1 = m_vertices[m_tri_verts[tri_idx + 1]];\n\t\tconst auto v2 = m_vertices[m_tri_verts[tri_idx + 2]];\n\t\tm_tri_points[j][0] = v0;\n\t\tm_tri_points[j][1] = v1;\n\t\tm_tri_points[j][2] = v2;\n\t\t// ccw order\n\t\tconst Eigen::Vector3d edge1{ v1 - v0 };\n\t\tconst Eigen::Vector3d edge2{ v2 - v1 };\n\t\tconst Eigen::Vector3d cross = edge1.cross(edge2);\n\t\tm_tri_areas[j] = cross.norm()*0.5;\n\t\tm_tri_normals[j] = cross.normalized();\n\t\tm_tri_edges[j] = std::make_pair(edge1, edge2);\n\t}\n\n}\n\n// variable names based on pseudocode\nvoid GCDeformData::calc_green_coords(MItGeometry& iter, const MMatrix& mat)\n{\n\tMPointArray target_vertices;\n\titer.allPositions(target_vertices);\n\tm_nr_of_targetverts = iter.exactCount();\n\tm_psi.resize(m_nr_of_tris*m_nr_of_targetverts, 0.0);\n\tm_phi.resize(m_nr_of_verts*m_nr_of_targetverts, 0.0);\n\n\ttbb::parallel_for(tbb::blocked_range<unsigned int>(0, m_nr_of_targetverts), [&](const tbb::blocked_range<unsigned int>& r) {\n\t\tfor (unsigned int idx = r.begin(); idx < r.end(); ++idx) {\n\t\t\tconst auto maya_vec = target_vertices[idx] * mat;\n\t\t\tconst Eigen::Vector3d pvec(maya_vec.x, maya_vec.y, maya_vec.z);\n\t\t\tEigen::Vector3d s;\n\t\t\tEigen::Vector3d I;\n\t\t\tstd::array<double, 3> II;\n\t\t\tstd::array<Eigen::Vector3d, 3> N;\n\t\t\tfor (unsigned int i = 0; i < m_nr_of_tris; ++i) {\n\t\t\t\tconst auto nrm = m_tri_normals[i];\n\t\t\t\tstd::array<Eigen::Vector3d, 3> vj;\n\t\t\t\tfor (size_t l = 0; l < 3; ++l) {\n\t\t\t\t\tvj[l] = m_tri_points[i][l] - pvec;\n\t\t\t\t}\n\t\t\t\tconst auto p = nrm * (vj[0].dot(nrm));\n\t\t\t\tfor (size_t k = 0; k < 3; ++k) {\n\t\t\t\t\tconst auto v0 = vj[k];\n\t\t\t\t\tconst auto v1 = vj[(k + 1) % 3];\n\t\t\t\t\tconst auto lg = ((v0 - p).cross((v1 - p))).dot(nrm);\n\t\t\t\t\ts[k] = lg < 0 ? -1.0 : 1.0;\n\t\t\t\t\t// eta always zero(?)\n\t\t\t\t\tI[k] = GCTriInt(p, v0, v1);\n\t\t\t\t\tII[k] = GCTriInt(NULL_VECTOR, v1, v0);\n\t\t\t\t\tN[k] = (v1.cross(v0)).normalized();\n\t\t\t\t}\n\n\t\t\t\tconst auto I_ = -abs(s.dot(I));\n\n\t\t\t\tm_psi[(idx*m_nr_of_tris) + i] = -I_;\n\n\t\t\t\tEigen::Vector3d w = I_ * nrm;\n\t\t\t\tfor (int k = 0; k < 3; k++)\n\t\t\t\t\tw += (II[k] * N[k]);\n\n\t\t\t\tif (w.norm() > DBL_EPSILON) {\n\t\t\t\t\tfor (unsigned int l = 0; l < 3; l++)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst auto l1 = (l + 1) % 3;\n\t\t\t\t\t\tconst auto a1 = N[l1];\n\t\t\t\t\t\tconst auto a2 = w;\n\t\t\t\t\t\tconst auto a3 = vj[l];\n\t\t\t\t\t\tconst auto val = ((a1.dot(a2)) / (a1.dot(a3)));\n\t\t\t\t\t\tm_phi[m_nr_of_verts*idx + m_tri_verts[(i * 3) + l]] += val;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n}\n\n\nconst MPoint GCDeformData::calc_pos(unsigned int idx) const\n{\n\tEigen::Vector3d pnt(0.0, 0.0, 0.0);\n\tconst auto current_tri = idx*m_nr_of_tris;\n\tconst auto current_vert = idx*m_nr_of_verts;\n\n\tfor (unsigned int i = 0; i < m_nr_of_verts; ++i) {\n\t\tpnt += m_phi[current_vert + i] * m_vertices[i];\n\t}\n\n\tfor (unsigned int i = 0; i < m_nr_of_tris; ++i) {\n\n\t\tpnt += m_psi[current_tri + i] * m_scale_factor[i] * m_tri_normals[i];\n\t}\n\n\treturn MPoint(pnt.x(), pnt.y(), pnt.z());\n}\n\n\nvoid GCDeformData::calc_scale_factor()\n{\n\n\tfor (unsigned int i = 0; i < m_nr_of_tris; ++i) {\n\t\tconst auto rest_edges = m_original_edges[i];\n\t\tconst auto current_edges = m_tri_edges[i];\n\n\t\tconst auto u0 = rest_edges.first;\n\t\tconst auto v0 = rest_edges.second;\n\n\t\tconst auto u1 = current_edges.first;\n\t\tconst auto v1 = current_edges.second;\n\n\t\tm_scale_factor[i] = sqrt((u1.squaredNorm()) * (v0.squaredNorm()) - 2.0 * (u1.dot(v1)) * (u0.dot(v0)) + (v1.squaredNorm()) * (u0.squaredNorm())) / (MathConstants::SQRT8 * m_original_areas[i]);\n\n\t}\n}\n\n\nvoid GCDeformData::save_original_cage_data()\n{\n\tm_original_areas.reserve(m_nr_of_tris);\n\tm_original_areas = m_tri_areas;\n\n\tm_original_edges.reserve(m_nr_of_tris);\n\tm_original_edges = m_tri_edges;\n}\n\n\nMStatus GreenCageDeformer::deform(MDataBlock& block, MItGeometry& iter, const MMatrix& mat, unsigned int multiIndex)\n{\n\tMStatus stat;\n\n\t// not yet supported\n\tif (multiIndex > 0)\n\t\treturn stat;\n\n\tif (!m_cage_connected)\n\t\treturn stat;\n\n\tconst auto envelope_val = block.inputValue(envelope).asDouble();\n\tif (envelope_val <= 0.0)\n\t\treturn stat;\n\n\tconst auto h_cage = block.inputValue(s_cage_mesh);\n\n\t// since we are getting the worldMesh lets not fiddle around with local to world transformations\n\tconst auto cage_object = h_cage.asMeshTransformed();\n\n\tp_cage_data->m_cage_object = cage_object;\n\tp_cage_data->setup_cage();\n\n\tif (!m_green_calculated) {\n\t\tMArrayDataHandle h_input_array = block.outputArrayValue(input, &stat);\n\t\t// atm multiIndex will be only 0\n\t\tstat = h_input_array.jumpToElement(multiIndex);\n\t\tp_cage_data->calc_green_coords(iter, mat);\n\t\tp_cage_data->save_original_cage_data();\n\t\tm_green_calculated = true;\n\t\t// TODO: write out green coords w/ original cage to be able to reload scene without calculating(also correctly) everytime we open it\n\t}\n\n\tp_cage_data->calc_scale_factor();\n\tMPointArray new_arr;\n\tnew_arr.setLength(p_cage_data->m_nr_of_targetverts);\n\n\tconst auto inverse_mat = mat.inverse();\n\ttbb::parallel_for(tbb::blocked_range<unsigned int>(0, p_cage_data->m_nr_of_targetverts), [&](const tbb::blocked_range<unsigned int>& r) {\n\t\tfor (unsigned int idx = r.begin(); idx < r.end(); ++idx) {\n\t\t\tnew_arr[idx] = p_cage_data->calc_pos(idx) * inverse_mat;\n\t\t}\n\t});\n\n\titer.setAllPositions(new_arr);\n\treturn stat;\n}\n\nvoid GreenCageDeformer::postConstructor()\n{\n\tm_cage_connected = false;\n\tm_green_calculated = false;\n}\n\nMStatus GreenCageDeformer::connectionMade(const MPlug & plug, const MPlug & otherPlug, bool asSrc)\n{\n\tif (!asSrc && plug == s_cage_mesh) {\t\t\n\t\tp_cage_data.reset(new GCDeformData());\n\t\tm_cage_connected = true;\n\t}\n\n\treturn MPxDeformerNode::connectionMade(plug, otherPlug, asSrc);\n}\n\nMStatus GreenCageDeformer::connectionBroken(const MPlug & plug, const MPlug & otherPlug, bool asSrc)\n{\n\tif (!asSrc && plug == s_cage_mesh) {\n\t\tp_cage_data.reset();\n\t\tm_cage_connected = false;\n\t\tm_green_calculated = false;\n\t}\n\n\treturn MPxDeformerNode::connectionBroken(plug, otherPlug, asSrc);\n}\n\n\nvoid* GreenCageDeformer::creator()\n{\n\treturn new GreenCageDeformer();\n}\n\n\nMStatus GreenCageDeformer::initialize()\n{\n\tMStatus stat;\n\tMFnTypedAttribute tAttr;\n\n\ts_cage_mesh = tAttr.create(\"cageMesh\", \"cm\", MFnData::kMesh, &stat);\n\tCHECK_MSTATUS_AND_RETURN_IT(stat);\n\tstat = addAttribute(s_cage_mesh);\n\tCHECK_MSTATUS_AND_RETURN_IT(stat);\n\tstat = attributeAffects(s_cage_mesh, outputGeom);\n\n\treturn stat;\n}\n\n\nMStatus initializePlugin(MObject obj)\n{\n\tMStatus stat;\n\n\tMFnPlugin plugin(obj, \"Balazs Pataki\", \"1.0\", \"Any\");\n\tstat = plugin.registerNode(GreenCageDeformer::s_node_name, GreenCageDeformer::s_node_id, &GreenCageDeformer::creator, &GreenCageDeformer::initialize, MPxNode::kDeformerNode);\n\tCHECK_MSTATUS_AND_RETURN_IT(stat);\n\n\treturn stat;\n}\n\n\nMStatus uninitializePlugin(MObject obj)\n{\n\tMStatus stat;\n\n\tMFnPlugin plugin(obj);\n\tstat = plugin.deregisterNode(GreenCageDeformer::s_node_id);\n\tCHECK_MSTATUS_AND_RETURN_IT(stat);\n\n\treturn stat;\n}\n", "meta": {"hexsha": "a771666c2f3c84da50e749997bd26011c1c1fab6", "size": 10069, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/green_cage_deformer.cc", "max_stars_repo_name": "blaisebundle/green_cage_deformer", "max_stars_repo_head_hexsha": "5a2b32624fb04042d058161b02f2c35d306cbdc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-06-18T19:01:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T12:22:42.000Z", "max_issues_repo_path": "src/green_cage_deformer.cc", "max_issues_repo_name": "RiggestOu/green_cage_deformer", "max_issues_repo_head_hexsha": "5a2b32624fb04042d058161b02f2c35d306cbdc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/green_cage_deformer.cc", "max_forks_repo_name": "RiggestOu/green_cage_deformer", "max_forks_repo_head_hexsha": "5a2b32624fb04042d058161b02f2c35d306cbdc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-12T22:53:47.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-29T08:41:22.000Z", "avg_line_length": 28.0473537604, "max_line_length": 193, "alphanum_fraction": 0.6853709405, "num_tokens": 3198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5494094438424463}}
{"text": "#include \"conditional_algorithm.h\"\n\n#include <Eigen/Dense>\n#include <stan/math/prim/fun.hpp>\n\n#include \"algorithm_state.pb.h\"\n#include \"base_algorithm.h\"\n#include \"src/collectors/base_collector.h\"\n\nEigen::VectorXd ConditionalAlgorithm::lpdf_from_state(\n    const Eigen::MatrixXd &grid, const Eigen::RowVectorXd &hier_covariate,\n    const Eigen::RowVectorXd &mix_covariate) {\n  // Read mixing state\n  unsigned int n_data = curr_state.cluster_allocs_size();\n  unsigned int n_clust = curr_state.cluster_states_size();\n  mixing->set_state_from_proto(curr_state.mixing_state());\n  // Initialize estimate containers\n  Eigen::MatrixXd lpdf_local(grid.rows(), n_clust);\n  Eigen::VectorXd lpdf_final(grid.rows());\n  auto temp_hier = unique_values[0]->clone();\n  // Loop over grid points\n  for (size_t i = 0; i < grid.rows(); i++) {\n    // Get mixing weights for the i-th grid point\n    Eigen::VectorXd logweights =\n        mixing->get_weights(true, false, mix_covariate);\n    // Loop over clusters\n    for (size_t j = 0; j < n_clust; j++) {\n      temp_hier->set_state_from_proto(curr_state.cluster_states(j));\n      // Get local, single-point estimate\n      lpdf_local(i, j) =\n          logweights(j) + temp_hier->like_lpdf(grid.row(i), hier_covariate);\n    }\n    // Final estimate for i-th grid point\n    lpdf_final(i) = stan::math::log_sum_exp(lpdf_local.row(i));\n  }\n  return lpdf_final;\n}\n", "meta": {"hexsha": "37097234fec50905f4dbc24c1f0dec276897bb44", "size": 1384, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/algorithms/conditional_algorithm.cc", "max_stars_repo_name": "mberaha/bayesmix", "max_stars_repo_head_hexsha": "4448f0e9f69ac71f3aacc11a239e3114790c1aaa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-10-13T16:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T13:50:42.000Z", "max_issues_repo_path": "src/algorithms/conditional_algorithm.cc", "max_issues_repo_name": "mberaha/bayesmix", "max_issues_repo_head_hexsha": "4448f0e9f69ac71f3aacc11a239e3114790c1aaa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-10-26T09:49:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:23:38.000Z", "max_forks_repo_path": "src/algorithms/conditional_algorithm.cc", "max_forks_repo_name": "mberaha/bayesmix", "max_forks_repo_head_hexsha": "4448f0e9f69ac71f3aacc11a239e3114790c1aaa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2020-11-17T06:52:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T12:08:47.000Z", "avg_line_length": 36.4210526316, "max_line_length": 76, "alphanum_fraction": 0.7080924855, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.5494094174526581}}
{"text": "#include <iostream>\n#include <cassert>\n#include <vector>\n#include <map>\n#include <deque>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/iterator/function_output_iterator.hpp>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\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 boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, long>> Graph;\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Delaunay_triangulation_2<K> Triangulation;\n\nbool testcase()\n{\n  int n;\n  std::cin >> n;\n  if (n == 0)\n  {\n    return false;\n  }\n  assert(n >= 2 && n <= 6e4);\n\n  DEBUG(1, \"\\ntest case; n = \" << n);\n\n  std::vector<K::Point_2> infected_points;\n  for (int i = 0; i < n; i++)\n  {\n    int x, y;\n    std::cin >> x >> y;\n    assert(abs(x) < (1 << 24) && abs(y) < (1 << 24));\n    infected_points.emplace_back(x, y);\n  }\n\n  int m;\n  std::cin >> m;\n  assert(m >= 1 && m <= 4e4);\n\n  std::vector<std::pair<K::Point_2, long>> healthy_points;\n  for (int i = 0; i < m; i++)\n  {\n    int x, y;\n    long d;\n    std::cin >> x >> y >> d;\n    assert(abs(x) < (1 << 24) && abs(y) < (1 << 24));\n    assert(d >= 0 && d < (long(1) << 49));\n    healthy_points.push_back(std::make_pair(K::Point_2(x, y), d));\n  }\n\n  Triangulation triangulation;\n  triangulation.insert(infected_points.begin(), infected_points.end());\n\n  const int indexed_face_count = triangulation.number_of_faces() + 1;\n  Graph mst_input_graph(indexed_face_count);\n  auto mst_input_weights = boost::get(boost::edge_weight, mst_input_graph);\n  std::map<Triangulation::Face_handle, int> face_indices_by_handle;\n  int next_free_face_index = 0;\n  const int infinite_face_index = next_free_face_index++;\n  auto index_from_face_handle = [&face_indices_by_handle, &next_free_face_index, &triangulation, indexed_face_count, infinite_face_index](Triangulation::Face_handle fh) {\n    if (triangulation.is_infinite(fh))\n    {\n      DEBUG(4, \"infinite face\");\n      return infinite_face_index;\n    }\n\n    int face_index;\n    if (face_indices_by_handle.count(fh) == 1)\n    {\n      DEBUG(4, \"existing face\");\n      face_index = face_indices_by_handle.at(fh);\n    }\n    else\n    {\n      DEBUG(4, \"new face\");\n      assert(face_indices_by_handle.count(fh) == 0);\n      face_index = next_free_face_index++;\n      face_indices_by_handle.insert(std::make_pair(fh, face_index));\n    }\n    DEBUG(4, \"face_index \" << face_index << \" limit \" << indexed_face_count);\n    assert(face_index >= 0 && face_index < indexed_face_count);\n    return face_index;\n  };\n  for (auto it = triangulation.finite_edges_begin(); it != triangulation.finite_edges_end(); it++)\n  {\n    long weight = -CGAL::squared_distance(it->first->vertex((it->second + 1) % 3)->point(), it->first->vertex((it->second + 2) % 3)->point());\n    int vertex_a = index_from_face_handle(it->first);\n    int vertex_b = index_from_face_handle(it->first->neighbor(it->second));\n    if (vertex_a > vertex_b)\n    {\n      std::swap(vertex_a, vertex_b);\n    }\n    assert(vertex_a < vertex_b);\n    DEBUG(3, \"vertex_a \" << vertex_a << \" vertex_b \" << vertex_b << \" weight \" << weight);\n    auto edge_result = boost::edge(vertex_a, vertex_b, mst_input_graph);\n    if (edge_result.second)\n    {\n      long &saved_weight = mst_input_weights[edge_result.first];\n      saved_weight = std::min(saved_weight, weight);\n    }\n    else\n    {\n      boost::add_edge(vertex_a, vertex_b, weight, mst_input_graph);\n    }\n  }\n\n  Graph mst(indexed_face_count);\n  auto add_mst_edge = [&mst, &mst_input_graph](Graph::edge_descriptor edge) {\n    long weight = boost::get(boost::edge_weight_t(), mst_input_graph, edge);\n    DEBUG(3, \"add_mst_edge \" << edge.m_source << \" \" << edge.m_target << \" \" << weight);\n    boost::add_edge(edge.m_source, edge.m_target, weight, mst);\n  };\n  boost::kruskal_minimum_spanning_tree(mst_input_graph, boost::make_function_output_iterator(std::ref(add_mst_edge)));\n\n  std::deque<std::pair<int, long>> bfs_queue{std::make_pair(infinite_face_index, std::numeric_limits<long>::max())};\n  std::vector<long> largest_escape_by_face(indexed_face_count, 0);\n  while (!bfs_queue.empty())\n  {\n    int prev_vertex = bfs_queue.front().first;\n    long prev_largest_escape = bfs_queue.front().second;\n    bfs_queue.pop_front();\n\n    assert(largest_escape_by_face.at(prev_vertex) == 0);\n    largest_escape_by_face.at(prev_vertex) = prev_largest_escape;\n    DEBUG(3, \"prev_vertex \" << prev_vertex << \" prev_largest_escape \" << prev_largest_escape);\n\n    for (auto its = boost::out_edges(prev_vertex, mst); its.first != its.second; its.first++)\n    {\n      int next_vertex = its.first->m_target;\n      assert(next_vertex != prev_vertex);\n      if (largest_escape_by_face.at(next_vertex) > 0)\n      {\n        continue;\n      }\n      DEBUG(3, \"next_vertex \" << next_vertex);\n\n      long limit_of_this_edge = -boost::get(boost::edge_weight_t(), mst, *its.first);\n      long next_largest_escape = std::min(prev_largest_escape, limit_of_this_edge);\n      DEBUG(3, \"limit_of_this_edge \" << limit_of_this_edge << \" next_largest_escape \" << next_largest_escape)\n      assert(next_largest_escape > 0);\n\n      bfs_queue.push_back(std::make_pair(next_vertex, next_largest_escape));\n    }\n  }\n  int min_largest_escape_by_triangle = *std::min_element(largest_escape_by_face.begin(), largest_escape_by_face.end());\n  DEBUG(2, \"min_largest_escape_by_triangle \" << min_largest_escape_by_triangle);\n  assert(min_largest_escape_by_triangle > 0);\n\n  std::vector<bool> can_escape_by_index(m);\n  for (int i = 0; i < m; i++)\n  {\n    auto &healthy_point = healthy_points.at(i);\n    Triangulation::Face_handle face = triangulation.locate(healthy_point.first);\n    int face_index = index_from_face_handle(face);\n    DEBUG(2, \"face_index \" << face_index);\n    long largest_escape = largest_escape_by_face.at(face_index);\n    DEBUG(2, \"largest_escape (initial) \" << largest_escape);\n\n    auto nearest = triangulation.nearest_vertex(healthy_point.first);\n    DEBUG(3, \"limiting using point \" << nearest->point());\n    largest_escape = std::min(largest_escape, 4 * long(CGAL::squared_distance(healthy_point.first, nearest->point())));\n\n    DEBUG(2, \"largest_escape (adjusted) \" << largest_escape);\n    can_escape_by_index.at(i) = 4 * healthy_point.second <= largest_escape;\n  }\n\n  for (bool v : can_escape_by_index)\n  {\n    std::cout << (v ? \"y\" : \"n\");\n  }\n  std::cout << \"\\n\";\n\n  return true;\n}\n\nint main()\n{\n  std::ios_base::sync_with_stdio(false);\n\n  while (testcase())\n  {\n  }\n\n  return 0;\n}", "meta": {"hexsha": "8e4355c27f861b9df9326121069c7ee1ac3e09bb", "size": 6774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-08/h1n1/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-08/h1n1/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-08/h1n1/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": 34.7384615385, "max_line_length": 170, "alphanum_fraction": 0.6737525834, "num_tokens": 1861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5493822291713836}}
{"text": "#define _USE_MATH_DEFINES\n\n#include \"mesh.hpp\"\n#include \"plane2d.hpp\"\n#include \"line_interval.hpp\"\n#include \"found_path.hpp\"\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n#include <limits>\n#include <functional>\n#include <future>\n#include <cmath>\n#include <thread>\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nMesh::Mesh(const int numVertices, const int numFaces, const int numCells){\n    vertices.reserve(numVertices);\n    faces.reserve(numFaces);\n    tetrahedrons.reserve(numCells);\n}\n\nvoid Mesh::setVertices(const vector<array<double, 3>> & _vertices){\n\n    for(unsigned long int i=0; i < _vertices.size(); ++i){\n\tVertex3d pt(_vertices[i]);\n\tvertices.push_back(pt);\n    }\n\n}\n\n\nvoid Mesh::addTetrahedron(const int id, const array<int, 4> vertexIds, \n\tconst vector<unsigned long int> neighborIds, const double weight, const int label){\n\n    vector<reference_wrapper<Vertex3d>> refs = {vertices[vertexIds[0]], vertices[vertexIds[1]], vertices[vertexIds[2]], vertices[vertexIds[3]]};\n\n    Tetrahedron tet(id, refs, weight, label);\n\n    unsigned long int current_size = tetrahedrons.size();\n\n    for(unsigned long int i=0; i<neighborIds.size(); ++i){\n\tif(neighborIds[i]<current_size){\n\t    Tetrahedron& neighbor = tetrahedrons[neighborIds[i]];\n\t    \n\t    neighbor.addNeighbor(tet.Id());\n\t    tet.addNeighbor(neighbor.Id());\n\t}\n    }\n    tetrahedrons.push_back(tet);\n}\n\nvoid Mesh::addFace(const array<int, 3> vertexIds, const int tetId){\n    vector<reference_wrapper<Vertex3d>> refs = {vertices[vertexIds[0]], vertices[vertexIds[1]], vertices[vertexIds[2]]};\n\n    Face face(refs, tetId);\n    faces.push_back(face);\n}\n\nbool Mesh::setTarget(array<double, 3> _target){\n    bool targetSet=false;\n    for(unsigned long int i=0; i < tetrahedrons.size(); ++i){\n\tif (tetrahedrons[i].contains(_target)){\n\t    Vector3d t(_target[0], _target[1], _target[2]);\n\t    target = t;\n\t    targetTetId=i;\n\t    targetSet=true;\n\t    break;\n\t}\n    }\n    return targetSet;\n}\n\nvector<Shape3d> Mesh::sliceIndv(array<double, 2> rotation){\n    vector<int> planeLastChecked;\n    planeLastChecked.reserve(tetrahedrons.size());\n    for(unsigned long int i=0; i<tetrahedrons.size(); i++){\n\tplaneLastChecked.push_back(-1);\n    }\n\n    Plane3d plane(0, rotation[0], rotation[1], target);\n    return slice(plane, planeLastChecked);\n}\n\nvector<FoundPath> Mesh::findPaths(vector<Plane3d> planes, double distBound){\n    vector<int> planeLastChecked;\n    planeLastChecked.reserve(tetrahedrons.size());\n    for(unsigned long int i=0; i<tetrahedrons.size(); i++){\n\tplaneLastChecked.push_back(-1);\n    }\n\n    double minUpperBound=numeric_limits<double>::max();\n\n    //vector<vector<LineInterval>> allCandidateIntervals;\n    vector<vector<FoundPath>> allFoundPaths;\n\n    for(int i=0; i<planes.size(); ++i){\n\tvector<Shape3d> planeSlice = slice(planes[i], planeLastChecked);\n\tPlane2d plane2d(planeSlice, planes[i]);\n\tvector<FoundPath> planePaths=plane2d.FindPaths(distBound);\n\t//cout << \"plane paths size:\" << endl;\n\t//cout << planePaths.size() << endl;\n\tallFoundPaths.push_back(planePaths);\n\tif(plane2d.MinUpperBound()<minUpperBound){\n\t    minUpperBound=plane2d.MinUpperBound();\n\t}\n    }\n    vector<FoundPath> foundPaths;\n    //cout << \"min upper bound:\" << endl;\n    //cout << minUpperBound << endl;\n    //cout << \"all found paths size:\" << endl;\n    //cout << allFoundPaths.size() << endl;\n\n    for(int i=0; i<planes.size(); ++i){\n\tvector<FoundPath> planePaths=allFoundPaths[i];\n\n\tfor(int j=0; j<planePaths.size(); ++j){\n\t    FoundPath foundPath=planePaths[j];\n\t    if(foundPath.LowerBound()<minUpperBound){\n\t\tarray<Vector3d, 2> endPoints=foundPath.Points();\n\t\tVector3d pt0=planes[i].Get3dPoint(endPoints[0]);\n\t\tVector3d pt1=planes[i].Get3dPoint(endPoints[1]);\n\n\t\tFoundPath fp(planes[i].Id(), pt0, pt1, foundPath.LowerBound(), foundPath.UpperBound());\n\t\tfoundPaths.push_back(fp);\n\t    }\n\t}\n    }\n    //cout << \"return paths size:\" << endl;\n    //cout << foundPaths.size() << endl;\n    return foundPaths;\n}\n\nvector<Shape3d> Mesh::slice(Plane3d plane, vector<int> &planeLastChecked){\n    vector<Shape3d> slice = computeSliceComponent(plane, planeLastChecked, targetTetId);\n\n    for(unsigned long int i=0; i<faces.size(); i++){\n\tif(faces[i].intersectsPlane(plane) && planeLastChecked[faces[i].TetId()]!=plane.Id()){\n\t    vector<Shape3d> sliceComponent = computeSliceComponent(plane, planeLastChecked, faces[i].TetId());\n\t    slice.insert(slice.end(), sliceComponent.begin(), sliceComponent.end());\n\t}\n    }\n    return slice;\n}\n\nvector<Shape3d> Mesh::computeSliceComponent(Plane3d plane, vector<int> &planeLastChecked, unsigned long int initTet){\n    \n    vector<unsigned long int> tetStack;\n    tetStack.push_back(initTet);\n\n    vector<Shape3d> allPoints;\n\n    while(tetStack.size() > 0){\n\tTetrahedron& tet = tetrahedrons[tetStack.back()];\n\ttetStack.pop_back();\n\t\n\tif(planeLastChecked[tet.Id()]!=plane.Id()){\n\n\t    vector<array<double, 3>> intersectionPoints = tet.intersectsPlane(plane);\n\n\t    if(intersectionPoints.size()>2){\n\t\tShape3d shape(tet.Id(), intersectionPoints, tet.Weight(), tet.Label());\n\t\tallPoints.push_back(shape);\n\t\tvector<unsigned long int> neighbors = tet.Neighbors();\n\n\t\tfor(int i=0; i<neighbors.size();++i){\n\t\t    tetStack.push_back(neighbors[i]);\n\t\t}\n\t    }\n\n\t    planeLastChecked[tet.Id()]=plane.Id();\n\t}\n    }\n\n    return allPoints;\n}\n\n\nvector<FoundPath> Mesh::shortestPaths(const int epsilon, const int numThreads, double distBound){\n\n    future<vector<FoundPath>> futures[numThreads];\n\n    vector<Plane3d> planes;\n    //cout << numThreads << endl;\n\n    for(int i=0; i<epsilon; i++){\n\tfor(int j=0; j<epsilon; j++){\n\t    Plane3d plane((i*epsilon)+j, i*M_PI/epsilon, j*M_PI/epsilon, target);\n\t    planes.push_back(plane);\n\t}\n    }\n\n    int subarraySize = ((epsilon * epsilon) + numThreads - 1) / numThreads;\n\n    for(int i=0; i<numThreads; i++){\n\tint start=i*subarraySize;\n\tint end=start+subarraySize;\n\tif(end>(epsilon*epsilon)){\n\t    end=epsilon*epsilon;\n\t}\n\n\tvector<Plane3d> planeVector;\n\n\tfor(int idx=start; idx<end; idx++){\n\t    planeVector.push_back(planes[idx]);\n\t}\n\n\tfutures[i]=async(&Mesh::findPaths, this, planeVector, distBound);\n    }\n\n    vector<FoundPath> allFoundPaths;\n    double minUpperBound=numeric_limits<double>::max();\n    for(unsigned long int i=0; i<numThreads; ++i){\n\t//cout << i << endl;\n\tvector<FoundPath> foundPaths=futures[i].get();\n\tfor(unsigned long int j=0; j<foundPaths.size(); ++j){\n\t    if(foundPaths[j].UpperBound()<minUpperBound){\n\t\tminUpperBound=foundPaths[j].UpperBound();\n\t    }\n\t    allFoundPaths.push_back(foundPaths[j]);\n\t}\n\t//vector<FoundPath> foundPaths=futures[i].get();\n\t//allFoundPaths.push_back(foundPaths);\n    }\n\n    \n    vector<FoundPath> ret;\n    for(unsigned long int i=0; i<allFoundPaths.size(); ++i){\n\tif(allFoundPaths[i].LowerBound()<minUpperBound){\n\t    ret.push_back(allFoundPaths[i]);\n\t}\n    }\n\n    //cout << \"ret size:\" << endl;\n    //cout << ret.size() << endl;\n    return ret;\n}\n\n\nunsigned long int Mesh::getTargetTetId(){\n    return targetTetId;\n}\n\n", "meta": {"hexsha": "f41bec9ec8abcac8495044f3089a6486844d6252", "size": 7035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mesh.cpp", "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.cpp", "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.cpp", "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": 28.2530120482, "max_line_length": 144, "alphanum_fraction": 0.6823027719, "num_tokens": 1929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5493822091048596}}
{"text": "/**********************************************************************************************************************\nThis file is part of the Control Toolbox (https://adrlab.bitbucket.io/ct), copyright by ETH Zurich, Google Inc.\nAuthors:  Michael Neunert, Markus Giftthaler, Markus St\u00e4uble, Diego Pardo, Farbod Farshidian\nLicensed under Apache2 license (see LICENSE file in main directory)\n**********************************************************************************************************************/\n\n#include <memory>\n#include <array>\n\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include <ct/core/core.h>\n#include <ct/rbd/rbd.h>\n\n#include \"ct/models/HyA/HyA.h\"\n\nusing namespace ct;\nusing namespace ct::rbd;\n\n#define Debug\n\nTEST(HyaLinearizerTest, NumDiffComparison)\n{\n    typedef FixBaseFDSystem<HyA::Dynamics> HyASystem;\n\n    const size_t STATE_DIM = HyASystem::STATE_DIM;\n    const size_t CONTROL_DIM = HyASystem::CONTROL_DIM;\n\n    std::shared_ptr<HyASystem> hyaSystem(new HyASystem);\n    std::shared_ptr<HyASystem> hyaSystem2(new HyASystem);\n\n    RbdLinearizer<HyASystem> rbdLinearizer(hyaSystem, true);\n    core::SystemLinearizer<STATE_DIM, CONTROL_DIM> systemLinearizer(hyaSystem2, true);\n\n    core::StateVector<STATE_DIM> x;\n    x.setZero();\n    core::ControlVector<CONTROL_DIM> u;\n    u.setZero();\n\n    auto A_rbd = rbdLinearizer.getDerivativeState(x, u, 1.0);\n    auto B_rbd = rbdLinearizer.getDerivativeControl(x, u, 1.0);\n\n    auto A_system = systemLinearizer.getDerivativeState(x, u, 1.0);\n    auto B_system = systemLinearizer.getDerivativeControl(x, u, 1.0);\n\n    ASSERT_LT((A_rbd - A_system).array().abs().maxCoeff(), 1e-5);\n    ASSERT_LT((B_rbd - B_system).array().abs().maxCoeff(), 1e-4);\n\n    size_t nTests = 1000;\n    for (size_t i = 0; i < nTests; i++)\n    {\n        x.setRandom();\n        u.setRandom();\n\n        auto A_rbd = rbdLinearizer.getDerivativeState(x, u, 0.0);\n        auto B_rbd = rbdLinearizer.getDerivativeControl(x, u, 0.0);\n\n        auto A_system = systemLinearizer.getDerivativeState(x, u, 0.0);\n        auto B_system = systemLinearizer.getDerivativeControl(x, u, 0.0);\n\n        ASSERT_LT((A_rbd - A_system).array().abs().maxCoeff(), 1e-5);\n\n        ASSERT_LT((B_rbd - B_system).array().abs().maxCoeff(), 1e-4);\n    }\n}\n\nTEST(CodegenLinearizerTest, NumDiffComparison)\n{\n    typedef FixBaseFDSystem<HyA::Dynamics> HyASystem;\n\n    const size_t STATE_DIM = HyASystem::STATE_DIM;\n    const size_t CONTROL_DIM = HyASystem::CONTROL_DIM;\n\n    std::shared_ptr<HyASystem> hyaSystem(new HyASystem);\n\n    RbdLinearizer<HyASystem> rbdLinearizer(hyaSystem, true);\n\n    ct::models::HyA::HyALinearizedForward hyaLinear;\n\n    core::StateVector<STATE_DIM> x;\n    core::ControlVector<CONTROL_DIM> u;\n\n    size_t nTests = 1000;\n    for (size_t i = 0; i < nTests; i++)\n    {\n        x.setRandom();\n        u.setRandom();\n\n        auto A_rbd = rbdLinearizer.getDerivativeState(x, u, 0.0);\n        auto A_gen = hyaLinear.getDerivativeState(x, u, 0.0);\n\n        auto B_rbd = rbdLinearizer.getDerivativeControl(x, u, 0.0);\n        auto B_gen = hyaLinear.getDerivativeControl(x, u, 0.0);\n\n        ASSERT_LT((A_rbd - A_gen).array().abs().maxCoeff(), 1e-5);\n        ASSERT_LT((B_rbd - B_gen).array().abs().maxCoeff(), 1e-4);\n    }\n}\n\nTEST(IntegratorTest, IntegratorTestHya)\n{\n    typedef FixBaseFDSystem<HyA::Dynamics> HyASystem;\n\n    const size_t STATE_DIM = HyASystem::STATE_DIM;\n\n    std::shared_ptr<HyASystem> hyaSystem(new HyASystem);\n\n    core::Integrator<STATE_DIM> integratorEulerOdeint(hyaSystem, core::EULER);\n    core::Integrator<STATE_DIM> integratorRk4Odeint(hyaSystem, core::RK4);\n\n    core::Integrator<STATE_DIM> integratorEulerCT(hyaSystem, core::EULERCT);\n    core::Integrator<STATE_DIM> integratorRK4CT(hyaSystem, core::RK4CT);\n\n    double dt = 0.001;\n    double startTime = 0.0;\n    size_t numSteps = 10;\n\n    size_t nTests = 10000;\n    std::vector<core::StateVector<STATE_DIM>, Eigen::aligned_allocator<core::StateVector<STATE_DIM>>> xEulerOdeint(\n        nTests),\n        xEulerCt(nTests), xRk4Odeint(nTests), xRk4CT(nTests);\n\n    for (size_t i = 0; i < nTests; ++i)\n    {\n        xEulerOdeint[i].setRandom();\n        xEulerCt[i] = xEulerOdeint[i];\n        xRk4Odeint[i].setRandom();\n        xRk4CT[i] = xRk4Odeint[i];\n    }\n\n    auto start = std::chrono::high_resolution_clock::now();\n    for (size_t i = 0; i < nTests; i++)\n    {\n        integratorEulerOdeint.integrate_n_steps(xEulerOdeint[i], startTime, numSteps, dt);\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    auto diff = end - start;\n    double msTotal = std::chrono::duration<double, std::micro>(diff).count() / 1000.0;\n    std::cout << \"integratorEulerOdeint: \" << msTotal << \" ms. Average: \" << msTotal / double(nTests) << \" ms\"\n              << std::endl;\n\n\n    start = std::chrono::high_resolution_clock::now();\n    for (size_t i = 0; i < nTests; i++)\n    {\n        integratorEulerCT.integrate_n_steps(xEulerCt[i], startTime, numSteps, dt);\n    }\n    end = std::chrono::high_resolution_clock::now();\n    diff = end - start;\n    msTotal = std::chrono::duration<double, std::micro>(diff).count() / 1000.0;\n    std::cout << \"integratorEulerCT: \" << msTotal << \" ms. Average: \" << msTotal / double(nTests) << \" ms\" << std::endl;\n\n    start = std::chrono::high_resolution_clock::now();\n    for (size_t i = 0; i < nTests; i++)\n    {\n        integratorRk4Odeint.integrate_n_steps(xRk4Odeint[i], startTime, numSteps, dt);\n    }\n    end = std::chrono::high_resolution_clock::now();\n    diff = end - start;\n    msTotal = std::chrono::duration<double, std::micro>(diff).count() / 1000.0;\n    std::cout << \"integratorRk4Odeint: \" << msTotal << \" ms. Average: \" << msTotal / double(nTests) << \" ms\"\n              << std::endl;\n\n\n    start = std::chrono::high_resolution_clock::now();\n    for (size_t i = 0; i < nTests; i++)\n    {\n        integratorRK4CT.integrate_n_steps(xRk4CT[i], startTime, numSteps, dt);\n    }\n    end = std::chrono::high_resolution_clock::now();\n    diff = end - start;\n    msTotal = std::chrono::duration<double, std::micro>(diff).count() / 1000.0;\n    std::cout << \"integratorRK4CT: \" << msTotal << \" ms. Average: \" << msTotal / double(nTests) << \" ms\" << std::endl;\n\n\n    for (size_t i = 0; i < nTests; ++i)\n    {\n        ASSERT_LT((xRk4CT[i] - xRk4Odeint[i]).array().abs().maxCoeff(), 1e-12);\n        ASSERT_LT((xEulerCt[i] - xEulerOdeint[i]).array().abs().maxCoeff(), 1e-12);\n    }\n}\n\n\nint main(int argc, char **argv)\n{\n    testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "7433eed75c29d23e4cf29d4028eaa555ed6a2bdf", "size": 6564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/ct/ct_models/test/HyA/HyATest.cpp", "max_stars_repo_name": "Ewpratten/frc_971_mirror", "max_stars_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "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": "third_party/ct/ct_models/test/HyA/HyATest.cpp", "max_issues_repo_name": "Ewpratten/frc_971_mirror", "max_issues_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "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": "third_party/ct/ct_models/test/HyA/HyATest.cpp", "max_forks_repo_name": "Ewpratten/frc_971_mirror", "max_forks_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "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": 34.0103626943, "max_line_length": 120, "alphanum_fraction": 0.6316270567, "num_tokens": 1992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5493384889279863}}
{"text": "/*\n * G_mod_p.cpp\n *\n *  Created on: 20.09.2010\n *      Author: stephaniebayer\n */\n\n#include \"G_mod_p.h\"\n#include <NTL/ZZ.h>\nNTL_CLIENT\n\n\n#include <time.h>\nG_mod_p::G_mod_p() {\n\t// TODO Auto-generated constructor stub\n\n}\n\n//Sets the generator to gen and the mod to p, checks if the generator has the right modular value p\nG_mod_p::G_mod_p(Mod_p gen,  long p){\n\n\tgenerator = gen;\n\tmod = to_ZZ(p);\n\tif (gen.get_mod() != p)\n\t\tcout  << \"The modular value of the generator and p are not equal\" << endl;\n}\n\n//Sets the generator to gen and the mod to p, checks if the generator has the right modular value p\nG_mod_p::G_mod_p(Mod_p gen,  ZZ p){\n\n\tgenerator = gen;\n\tmod = p;\n\n\tif (gen.get_mod() != p)\n\t\tcout  << \"The modular value of the generator and p are not equal\" << endl;\n\n}\n\n//Sets the generator to the value gen and the mod to p\nG_mod_p::G_mod_p(ZZ val,  long p){\n\n\tgenerator = Mod_p(val, p);\n\tmod = to_ZZ(p);\n\n}\n\n//Sets the generator to the value gen and the mod to p\nG_mod_p::G_mod_p(ZZ val, ZZ p){\n\n\tgenerator = Mod_p(val, p);\n\tmod = p;\n\n}\n\n//Sets the generator to the value gen and the mod to p\nG_mod_p::G_mod_p(long val,  long p){\n\n\tgenerator = Mod_p(val, p);\n\tmod = to_ZZ(p);\n\n}\n\n//Sets the generator to the value gen and the mod to p\nG_mod_p::G_mod_p(long val, ZZ p){\n\n\tgenerator = Mod_p(val, p);\n\tmod = p;\n\n}\n\n//Creates a group given the generator, mod is set to modular value if gen\nG_mod_p::G_mod_p(Mod_p gen){\n\n\tgenerator = gen;\n\tmod = gen.get_mod();\n}\n\n//Creates a group ZZ/p, the function sets the generator to the smallest possible one\nG_mod_p::G_mod_p(ZZ p){\n\n\tZZ i;\n\tmod = p;\n\tfor (i = to_ZZ(1); i < p; ++i)\n\t{\n\t\tif (is_generator(i))\n\t\t{\n\t\t\tgenerator = Mod_p(i,p);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n//Creates a group ZZ/p, the function sets the generator to the smallest possible one\nG_mod_p::G_mod_p(long p){\n\n\tlong i;\n\tmod = p;\n\tfor (i = 1; i < p; ++i)\n\t{\n\t\tif (is_generator(i))\n\t\t{\n\t\t\tgenerator = Mod_p(i,p);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n//Destructor\nG_mod_p::~G_mod_p() {\n\t// TODO Auto-generated destructor stub\n}\n\n//Returns the generator\nMod_p G_mod_p::get_gen()const{\n\n\treturn generator;\n}\n\n//Returns the modular value\nZZ G_mod_p::get_mod()const{\n\n\treturn mod;\n}\n\n//Checks if an element is a generator of the group\nbool G_mod_p::is_generator(const Mod_p& el){\n\tZZ pow;\n\tbool b;\n\tb=false;\n\tpow = PowerMod(el.get_val(),(mod-1)/2,mod);\n\tif(pow == (mod-1))\n\t{\n\t\tif(el.get_val()!=(mod-1))\n\t\t{b=true;\n\t\t}\n\t}\n\treturn b;\n}\n\n//Checks if an element with value x is a generator of the group\nbool G_mod_p::is_generator(const ZZ& x){\n\tZZ pow;\n\tbool b;\n\tb=false;\n\tpow = PowerMod(x,(mod-1)/2,mod);\n\n\n\tif(pow == (mod-1))\n\t{\n\t\tif(x!=(mod-1))\n\t\t{b=true;\n\t\t}\n\t}\n\n\treturn b;\n}\n\n//Checks if an element with value x is a generator of the group\nbool G_mod_p::is_generator(const long& x){\n\tZZ pow;\n\tbool b;\n\tpow = PowerMod(to_ZZ(x),(mod-1)/2, mod);\n\tif(pow == (mod-1))\n\t{\n\t\tif(x!=(mod-1))\n\t\t{b=true;\n\t\t}\n\t}\n\n\treturn b;\n}\n\n//Returns the identity of the group\nMod_p G_mod_p::identity(){\n\n\treturn Mod_p(1, mod);\n}\n\n//return a random element of the group\nMod_p G_mod_p::random_el(){\n\n\tZZ ran;\n\tSetSeed(to_ZZ(time(0)));\n\tran = RandomBnd(mod);\n\n\treturn Mod_p(ran,mod);\n\n}\n\n//Creates an element with the value v modular mod\nMod_p G_mod_p::element(ZZ v){\n\n\n\treturn Mod_p(v,mod);\n\n}\n\n//Creates an element with the value v modular mod\nMod_p G_mod_p::element(long v){\n\n\n\treturn Mod_p(v,mod);\n\n}\n\n//Returns a n-th root of unity of the group\nMod_p G_mod_p::rootofunity(long n){\n\n\tZZ i;\n\tZZ pow;\n\tif ((mod-1) % n == 0)\n\t{\tfor(i =  to_ZZ(2); i<mod;++i)\n\t\t{\n\t\t\tif(GCD(i,mod)==to_ZZ(1))\n\t\t\t{\n\n\t\t\t\tif (n&1)\n\t\t\t\t{\n\t\t\t\t\tpow = PowerMod(i,n, mod);\n\t\t\t\t\tif(pow==1)\n\t\t\t\t\t\treturn Mod_p(i,mod);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpow = PowerMod(i,n/2,mod);\n\t\t\t\t\tif(pow == (mod-1))\n\t\t\t\t\t{\n\t\t\t\t\t\treturn Mod_p(i,mod);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tcout << \"There is no\" << n <<\"-th root of unity\"<< endl;\n\t\treturn Mod_p(1,mod);\n\t}\n\treturn Mod_p(1,mod);\n}\n\n//Returns a n-th root of unity of the group\nMod_p G_mod_p::rootofunity(ZZ n){\n\n\tZZ i;\n\tZZ pow;\n\tif ((mod-1) % n == 0)\n\t{\tfor(i =  to_ZZ(2); i<mod;++i)\n\t\t{\n\t\t\tif(GCD(i,mod)==to_ZZ(1))\n\t\t\t{\n\n\t\t\t\tif (IsOdd(n))\n\t\t\t\t{\n\t\t\t\t\tpow = PowerMod(i,n, mod);\n\t\t\t\t\tif(pow==1)\n\t\t\t\t\t\treturn Mod_p(i,mod);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpow = PowerMod(i,n/2,mod);\n\t\t\t\t\tif(pow == (mod-1))\n\t\t\t\t\t{\n\t\t\t\t\t\treturn Mod_p(i,mod);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tcout << \"There is no\" << n <<\"-th root of unity\"<< endl;\n\t\treturn Mod_p(1,mod);\n\t}\n\treturn Mod_p(1,mod);\n}\n\n//Returns the inverse of an element with value x\nMod_p G_mod_p::inverse(ZZ x){\n\n\tZZ temp;\n\ttemp = InvMod(x,mod);\n\treturn Mod_p(temp,mod);\n}\n\n//Returns the inverse of an element with value x\nMod_p G_mod_p::inverse(long x){\n\n\tZZ temp;\n\ttemp = InvMod(to_ZZ(x),mod);\n\treturn Mod_p(temp,mod);\n}\n\n//Assignment operator of the group\nvoid G_mod_p::operator =(const G_mod_p& H){\n\n\tgenerator = H.get_gen();\n\tmod = H.get_mod();\n}\n\n\n\n\n", "meta": {"hexsha": "2086711927bf9421ce360f717ecfad2a9f1086f9", "size": 4863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/G_mod_p.cpp", "max_stars_repo_name": "3for/verifiable-shuffle", "max_stars_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T14:06:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T08:28:26.000Z", "max_issues_repo_path": "src/G_mod_p.cpp", "max_issues_repo_name": "3for/verifiable-shuffle", "max_issues_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "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/G_mod_p.cpp", "max_forks_repo_name": "3for/verifiable-shuffle", "max_forks_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T06:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T15:21:49.000Z", "avg_line_length": 15.9967105263, "max_line_length": 99, "alphanum_fraction": 0.6156693399, "num_tokens": 1616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5493384755746199}}
{"text": "// Copyright (c) 2016\n// Author: Chrono Law\n#include <std.hpp>\nusing namespace std;\n\n//#include <boost/type_traits.hpp>\n\n#include <boost/mpl/integral_c.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/next_prior.hpp>\n\nusing namespace boost;\nusing namespace boost::mpl;\n\n///////////////////////////////////////\n\n\nvoid case1()\n{\n    typedef int_<2> i2;\n    typedef integral_c<short, 2> s2;\n\n    assert(i2::value == 2);\n    assert(i2::value == s2::value);\n\n    assert((is_same<i2::type, i2>::value));\n    assert((is_same<s2::value_type, short>::value));\n\n    assert(i2::next::value == 3);\n    assert(prior<s2>::type::value == 1);\n\n    i2 two1;\n    s2 two2;\n\n    int i = two1 + two2;\n    assert(i == int_<4>());\n\n}\n\n///////////////////////////////////////\n\n#include <boost/mpl/bool.hpp>\n\nvoid case2()\n{\n    assert(true_::value == true);\n    assert(false_::value == false);\n\n    assert((is_same<true_::type, bool_<true> >::value));\n    assert((is_same<false_::value_type, bool>::value));\n\n    //next<true_>::type;\n\n}\n\n///////////////////////////////////////\n\n#include <boost/mpl/arithmetic.hpp>\n#include <boost/mpl/logical.hpp>\n#include <boost/mpl/comparison.hpp>\n\nvoid case3()\n{\n    typedef int_<2> i2;\n    typedef int_<5> i5;\n    typedef int_<7> i7;\n\n    assert((boost::mpl::plus<i2, i5, i7>::type::value == 14));\n    assert((boost::mpl::equal_to<boost::mpl::minus<i7, i5>::type, i2>::type::value));\n\n    assert((boost::mpl::less<i2, i7>::type::value));\n    assert((is_same<boost::mpl::greater<i5, i2>::type, true_>::value));\n\n    assert((not_<and_<true_, false_>::type>::type::value));\n    assert((or_<true_, false_>::type()));\n\n}\n\n///////////////////////////////////////\n\n#include <boost/mpl/char.hpp>\n#include <boost/mpl/long.hpp>\n\nvoid case4()\n{\n    typedef boost::mpl::plus<int_<1>, char_<2>, long_<3>>::type\n            result;\n\n    assert(!(is_same<result, long_<6>>::type::value));\n\n    assert((is_same<result, integral_c<long, 6>>::type::value));\n\n}\n\n///////////////////////////////////////\n\nint main()\n{\n    std::cout << \"hello integral\" << std::endl;\n\n    case1();\n    case2();\n    case3();\n}\n", "meta": {"hexsha": "68433288d8306c0904915fecc02649ff182ba22e", "size": 2106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mpl/integral.cpp", "max_stars_repo_name": "MaxHonggg/professional_boost", "max_stars_repo_head_hexsha": "6fff73d3b9832644068dc8fe0443be813c7237b4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-05-20T08:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T01:17:07.000Z", "max_issues_repo_path": "mpl/integral.cpp", "max_issues_repo_name": "MaxHonggg/professional_boost", "max_issues_repo_head_hexsha": "6fff73d3b9832644068dc8fe0443be813c7237b4", "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": "mpl/integral.cpp", "max_forks_repo_name": "MaxHonggg/professional_boost", "max_forks_repo_head_hexsha": "6fff73d3b9832644068dc8fe0443be813c7237b4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-07-25T04:52:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T03:55:08.000Z", "avg_line_length": 20.0571428571, "max_line_length": 85, "alphanum_fraction": 0.5546058879, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5493384738321936}}
{"text": "// fifteen puzzle\n\n#include <iostream>\n#include <queue>\n#include <vector>\n#include <algorithm>\n\n#ifndef CLOSED_USE_VECTOR\n#include <unordered_set>\n#endif\n\n// #define DUMP\n// #define CLOSED_USE_VECTOR   // 2800 ms VS 46 ms !!!!!\n\ntemplate <class State>\nclass BreadthFirst\n{\npublic:\n    BreadthFirst(const State& start, const State& _end) : end(_end)\n    {\n        open.push(start);        \n    }\n    bool Solve()\n    {\n        do\n        {\n            auto current = open.front();\n            open.pop();\n            if ( NextStep(current) )\n            {\n                solution = current;\n                return true;\n            }\n        }\n        while(!open.empty());\n\n        return false;\n    }\n    State Solution() const { return solution; }\n    void PrintStatistics() const\n    {\n        std::cout << \"Visited states: \" << closed.size() << std::endl;\n    }\nprivate:\n    bool NextStep(const State& current)\n    {\n#ifdef DUMP        \n        std::cout << \"\\n********* new iteration *************\\n\" << std::endl;\n        std::cout << \"current:\\n\";\n        current.Print();\n#endif\n\n        if (current == end)\n            return true; // found\n#ifdef CLOSED_USE_VECTOR\n        closed.push_back(current);\n#else\n        closed.insert(current);\n#endif\n        auto nextStates = current.Next();\n\n#ifdef DUMP\n        std::cout << \"\\nnext:\\n\";\n#endif\n\n        for (auto s: nextStates)\n        {\n#ifdef CLOSED_USE_VECTOR\n            if (std::find(closed.begin(), closed.end(), s) == closed.end()) // not visited yet\n#else\n            if ( closed.find(s) == closed.end() ) // not visited yet\n#endif\n            {\n#ifdef DUMP\n                s.Print();\n#endif\n                open.push(s);\n            }\n        }\n        return false;\n    }\n\n    const State end;\n    State solution;\n    std::queue<State> open;\n#ifdef CLOSED_USE_VECTOR\n    std::vector<State> closed;\n#else\n    std::unordered_set<State> closed;\n#endif\n};\n\n//\n\n#include <array>\n#include <cassert>\n#include <iomanip>\n#include <boost/functional/hash.hpp>\n\nclass FState\n{\npublic:\n    FState() : configuration( {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0} )\n    {\n    }    \n    FState(std::array<int, 16>&& s) : configuration(std::move(s)) {}\n    FState(const FState& s) : configuration(s.configuration), moves(s.moves) {}\n    FState(FState&& s) : configuration(std::move(s.configuration)), moves(std::move(s.moves)) {}\n    FState& operator = (const FState& s)\n    { \n        if (&s != this)\n        {\n            configuration = s.configuration;\n            moves = s.moves;\n        }\n        return *this;\n    }    \n    std::vector<FState> Next() const\n    {\n        auto emptyIt = std::find(configuration.begin(), configuration.end(), 0);\n        auto emptyPosition = emptyIt - configuration.begin();\n        using V = std::vector<FState>;\n        switch (emptyPosition)\n        {\n            case 0: return V{ Move(0, 1), Move(0, 4) }; break;\n            case 1: return V{ Move(1, 0), Move(1, 5), Move(1, 2) }; break;\n            case 2: return V{ Move(2, 1), Move(2, 6), Move(2, 3) }; break;\n            case 3: return V{ Move(3, 2), Move(3, 7) }; break;\n            case 4: return V{ Move(4, 0), Move(4, 5), Move(4, 8) }; break;\n            case 5: return V{ Move(5, 1), Move(5, 4), Move(5, 6), Move(5, 9) }; break;\n            case 6: return V{ Move(6, 2), Move(6, 5), Move(6, 7), Move(6, 10) }; break;\n            case 7: return V{ Move(7, 3), Move(7, 6), Move(7, 11) }; break;\n            case 8: return V{ Move(8, 4), Move(8, 9), Move(8, 12) }; break;\n            case 9: return V{ Move(9, 5), Move(9, 8), Move(9, 10), Move(9, 13) }; break;\n            case 10: return V{ Move(10, 6), Move(10, 9), Move(10, 11), Move(10, 14) }; break;\n            case 11: return V{ Move(11, 7), Move(11, 10), Move(11, 15) }; break;\n            case 12: return V{ Move(12, 8), Move(12, 13)}; break;\n            case 13: return V{ Move(13, 12), Move(13, 9), Move(13, 14) }; break;\n            case 14: return V{ Move(14, 13), Move(14, 10), Move(14, 15) }; break;\n            case 15: return V{ Move(15, 11), Move(15, 14)}; break;\n            default: assert(false);\n        }\n        return {};\n    }\n    bool operator == (const FState& other) const\n    {\n        return configuration == other.configuration;\n    }\n    void Print() const\n    {\n        std::cout << std::endl;\n        PrintItem(0);\n        PrintItem(1);\n        PrintItem(2);\n        PrintItem(3);\n        std::cout << std::endl;\n        PrintItem(4);\n        PrintItem(5);\n        PrintItem(6);\n        PrintItem(7);\n        std::cout << std::endl;\n        PrintItem(8);\n        PrintItem(9);\n        PrintItem(10);\n        PrintItem(11);        \n        std::cout << std::endl;\n        PrintItem(12);\n        PrintItem(13);\n        PrintItem(14);\n        PrintItem(15);\n        std::cout << std::endl;\n    }\n    void PrintMoves() const\n    {\n        for (auto move: moves)\n            std::cout << move << ' ';\n        std::cout << std::endl;\n    }\n    std::size_t Hash() const\n    {\n        return boost::hash_range(std::begin(configuration), std::end(configuration));\n    }\nprivate:\n    void PrintItem(std::size_t pos) const\n    {\n        std::cout << std::setw(3);\n        std::cout << configuration[pos];\n    }\n    FState Move(std::size_t pivot, std::size_t item) const\n    {\n        auto cfg = *this;\n        std::swap(cfg.configuration[pivot], cfg.configuration[item]);\n        cfg.moves.push_back(item);\n        return cfg;\n    }\n\n    std::array<int, 16> configuration;\n    std::vector<int> moves;\n};\n\n// custom specialization of std::hash can be injected in namespace std\nnamespace std\n{\n    template<> struct hash<FState>\n    {\n        typedef FState argument_type;\n        typedef std::size_t result_type;\n        result_type operator()(argument_type const& s) const noexcept\n        {\n            return s.Hash();\n        }\n    };\n}\n\n#include <boost/chrono/chrono.hpp>\n#include <boost/chrono/process_cpu_clocks.hpp>\n\nusing namespace boost::chrono;\n\nint main()\n{\n    //const FState start( std::array<int, 16>({1,12,6,4,9,7,11,10,15,3,2,13,5,8,14,0}) );\n    const FState start( std::array<int, 16>({2,3,7,4,1,0,11,8,5,6,10,12,9,13,14,15}) );\n    const FState goal;\n    BreadthFirst<FState> search(start, goal);\n    \n    auto t0 = process_user_cpu_clock::now(); // boost\n    \n    bool found = search.Solve();\n\n    auto t1 = process_user_cpu_clock::now(); // boost   \n    using ms = boost::chrono::milliseconds;\n    ms d = boost::chrono::duration_cast<ms>(t1-t0); \n    std::cout << d.count() << \" ms\" << std::endl;\n\n    if (found)\n    {\n        std::cout << \"Solution found:\" << std::endl;\n        search.Solution().PrintMoves();        \n    }\n    else\n    {\n        std::cout << \"Solution not found!\" << std::endl;\n    }\n    search.PrintStatistics();\n\n    return 0;\n}", "meta": {"hexsha": "889180af3c948ff19df8616f36cf9418ae23d0dc", "size": 6805, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fifteenpuzzle/fifteen.cpp", "max_stars_repo_name": "daniele77/samples", "max_stars_repo_head_hexsha": "042bb3ea89410cc7dde83eabbe5e5d2fa1260c85", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-11-30T18:05:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-17T21:19:30.000Z", "max_issues_repo_path": "fifteenpuzzle/fifteen.cpp", "max_issues_repo_name": "daniele77/samples", "max_issues_repo_head_hexsha": "042bb3ea89410cc7dde83eabbe5e5d2fa1260c85", "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": "fifteenpuzzle/fifteen.cpp", "max_forks_repo_name": "daniele77/samples", "max_forks_repo_head_hexsha": "042bb3ea89410cc7dde83eabbe5e5d2fa1260c85", "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.439516129, "max_line_length": 96, "alphanum_fraction": 0.533137399, "num_tokens": 1941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5493384738321936}}
{"text": "/// \\file\n/// \\brief Unit tests for dfe::poly\n\n#include <array>\n#include <valarray>\n#include <vector>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"dfe/dfe_poly.hpp\"\n\n// make std::pair printable to allow direct comparision w/ boost::test\n\nnamespace std {\ntemplate<typename T>\ninline ostream&\noperator<<(ostream& os, const pair<T, T>& x)\n{\n  os << \"{\" << x.first << \", \" << x.second << \"}\";\n  return os;\n};\n} // namespace std\n\n// test different input container types\n\n#define COEFFS \\\n  { \\\n    1.0, 2.0, 0.25, 0.025 \\\n  }\nconstexpr double X0 = 0.5;\nconstexpr double Y0 = 2.065625;\nconstexpr double D0 = 2.2687500000000003;\nconstexpr std::pair<double, double> YD0 = {Y0, D0};\n\nBOOST_AUTO_TEST_CASE(poly_initializerlist)\n{\n  BOOST_TEST(dfe::polynomial_val(X0, COEFFS) == Y0);\n  BOOST_TEST(dfe::polynomial_der(X0, COEFFS) == D0);\n  BOOST_TEST(dfe::polynomial_valder(X0, COEFFS) == YD0);\n}\n\nBOOST_AUTO_TEST_CASE(poly_array)\n{\n  double coeffs[] = COEFFS;\n  BOOST_TEST(dfe::polynomial_val(X0, coeffs) == Y0);\n  BOOST_TEST(dfe::polynomial_der(X0, coeffs) == D0);\n  BOOST_TEST(dfe::polynomial_valder(X0, coeffs) == YD0);\n}\n\nBOOST_AUTO_TEST_CASE(poly_stdarray)\n{\n  std::array<double, 4> coeffs = COEFFS;\n  BOOST_TEST(dfe::polynomial_val(X0, coeffs) == Y0);\n  BOOST_TEST(dfe::polynomial_der(X0, coeffs) == D0);\n  BOOST_TEST(dfe::polynomial_valder(X0, coeffs) == YD0);\n}\n\nBOOST_AUTO_TEST_CASE(poly_stdvector)\n{\n  std::vector<double> coeffs = COEFFS;\n  BOOST_TEST(dfe::polynomial_val(X0, coeffs) == Y0);\n  BOOST_TEST(dfe::polynomial_der(X0, coeffs) == D0);\n  BOOST_TEST(dfe::polynomial_valder(X0, coeffs) == YD0);\n}\n\n// use std::valarray to calculate polynomial for multiple x values at once\n\nBOOST_AUTO_TEST_CASE(poly_valarray)\n{\n  std::valarray<float> x(1024);\n  for (std::size_t i = 0; i < x.size(); ++i) {\n    x[i] = -1.0 + (2.0 / x.size()) * i;\n  }\n  auto linear = dfe::polynomial_val(x, {0.0, 1.0});\n  auto quadratic = dfe::polynomial_val(x, {0.5, 0.0, 1.0});\n\n  BOOST_TEST(x.size() == linear.size());\n  BOOST_TEST(x.size() == quadratic.size());\n  BOOST_TEST((x - linear).sum() == 0.0);\n  BOOST_TEST((0.5 + x * x - quadratic).sum() == 0.0);\n}\n\n// special case of empty coefficients\n\nBOOST_AUTO_TEST_CASE(poly_empty)\n{\n  BOOST_TEST(dfe::polynomial_val(-1.0, std::array<double, 0>{}) == 0.0);\n  BOOST_TEST(dfe::polynomial_val(+0.0, std::array<double, 0>{}) == 0.0);\n  BOOST_TEST(dfe::polynomial_val(+1.0, std::array<double, 0>{}) == 0.0);\n}\n\n// test different fixed polynomial orders\n\nBOOST_AUTO_TEST_CASE(poly_const)\n{\n  BOOST_TEST(dfe::polynomial_val(-1.0, {42.0}) == 42.0);\n  BOOST_TEST(dfe::polynomial_val(+0.0, {42.0}) == 42.0);\n  BOOST_TEST(dfe::polynomial_val(+1.0, {42.0}) == 42.0);\n}\n\nBOOST_AUTO_TEST_CASE(poly_linear)\n{\n  BOOST_TEST(dfe::polynomial_val(-0.5, {42.0, 1.0}) == 41.5);\n  BOOST_TEST(dfe::polynomial_val(+0.0, {42.0, 1.0}) == 42.0);\n  BOOST_TEST(dfe::polynomial_val(+0.5, {42.0, 1.0}) == 42.5);\n}\n\nBOOST_AUTO_TEST_CASE(poly_quadratic)\n{\n  BOOST_TEST(dfe::polynomial_val(-0.5, {42.0, 1.0, 0.5}) == 41.625);\n  BOOST_TEST(dfe::polynomial_val(+0.0, {42.0, 1.0, 0.5}) == 42.0);\n  BOOST_TEST(dfe::polynomial_val(+0.5, {42.0, 1.0, 0.5}) == 42.625);\n}\n\nBOOST_AUTO_TEST_CASE(poly_cubic)\n{\n  BOOST_TEST(dfe::polynomial_val(-0.5, {42.0, 1.0, 0.5, -1.0}) == 41.75);\n  BOOST_TEST(dfe::polynomial_val(+0.0, {42.0, 1.0, 0.5, -1.0}) == 42.0);\n  BOOST_TEST(dfe::polynomial_val(+0.5, {42.0, 1.0, 0.5, -1.0}) == 42.5);\n}\n", "meta": {"hexsha": "81d66cf489bdfd3c4aebc619ae5a2bc189f283eb", "size": 3417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/test_poly.cpp", "max_stars_repo_name": "pinkenburg/dfelibs", "max_stars_repo_head_hexsha": "7bba35028409728170ea785a301175aac88b0cc3", "max_stars_repo_licenses": ["MIT"], "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/test_poly.cpp", "max_issues_repo_name": "pinkenburg/dfelibs", "max_issues_repo_head_hexsha": "7bba35028409728170ea785a301175aac88b0cc3", "max_issues_repo_licenses": ["MIT"], "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/test_poly.cpp", "max_forks_repo_name": "pinkenburg/dfelibs", "max_forks_repo_head_hexsha": "7bba35028409728170ea785a301175aac88b0cc3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T21:07:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T21:07:58.000Z", "avg_line_length": 28.2396694215, "max_line_length": 74, "alphanum_fraction": 0.6581796898, "num_tokens": 1237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5493384738321936}}
{"text": "#include <TriPQ/CGAL_Spherical_Polyhedron_Traits.h>\n#include <TriPQ/SelectNearestEdge3.h>\n#include <TriPQ/StartFromMostLocatedEdge.h>\n#include <TriPQ/StartFromFixedEdge.h>\n#include <TriPQ/TriPQ.h>\n\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Polyhedron_items_with_id_3.h>\n#include <CGAL/Polyhedron_incremental_builder_3.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Simple_cartesian.h>\n#include <boost/iterator/transform_iterator.hpp>\n#include <CGAL/IO/Polyhedron_iostream.h>\n\n#include <array>\n#include <cmath>\n#include <chrono>\n#include <random>\n#include <vector>\n\ntypedef CGAL::Simple_cartesian<double> Kernel;\ntypedef CGAL::Polyhedron_items_with_id_3 Polyhedron_items;\ntypedef CGAL::Polyhedron_3<Kernel, Polyhedron_items> Polyhedron;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<std::size_t, Kernel> Vb;\ntypedef CGAL::Triangulation_face_base_2<Kernel> Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb, Fb> Tds;\ntypedef CGAL::Delaunay_triangulation_2<Kernel, Tds> Delaunay;\ntypedef Kernel::Point_3 Point_3;\ntypedef Kernel::Point_2 Point_2;\n\nPoint_3 sphericalToCart(Point_2 const &s) {\n  using std::sin;\n  using std::cos;\n  return Point_3(sin(s[0]) * cos(s[1]), sin(s[0]) * sin(s[1]), -cos(s[0]));\n}\n\ninline Point_2 PhiN(Point_3 const &x) {\n  return Point_2(x[0] / (1.0 - x[2]), x[1] / (1.0 - x[2]));\n}\n\nstd::vector<std::array<std::size_t, 3>>\ntriangulate(std::vector<Point_3> &points) {\n  std::size_t vertexIndex = 0;\n  auto const f = [&vertexIndex](auto const &p) {\n    return std::make_pair(PhiN(p), vertexIndex++);\n  };\n\n  typedef boost::transform_iterator<\n      decltype(f), std::vector<Point_3>::const_iterator> Iterator;\n\n  // Delaunay dt(Iterator(points.cbegin(), f), Iterator(points.cend(), f));\n  Delaunay dt;\n\n  // ensure that no three points inserted to dt are collinear\n  std::vector<std::pair<Point_2, std::size_t>> pt(Iterator(points.cbegin(), f),\n                                                  Iterator(points.cend(), f));\n  auto p0 = pt[0], p1 = pt[1];\n  pt.erase(pt.begin());\n  pt.erase(pt.begin());\n  auto iter = pt.begin();\n  while (!pt.empty()) {\n    auto p2 = *iter;\n    if (CGAL::collinear(p0.first, p1.first, p2.first)) {\n      ++iter;\n      continue;\n    }\n    dt.push_back(iter->first)->info() = iter->second;\n    p0 = p1;\n    p1 = p2;\n    iter = pt.erase(iter);\n    if (iter == pt.end()) iter = pt.begin();\n  }\n\n  std::size_t const N = points.size();\n  std::vector<std::array<std::size_t, 3>> facets;\n  facets.reserve(dt.number_of_faces());\n  for (auto t = dt.all_faces_begin(); t != dt.all_faces_end(); ++t) {\n    auto const v0 = t->vertex(0);\n    auto const v1 = t->vertex(1);\n    auto const v2 = t->vertex(2);\n    auto const i0 = dt.is_infinite(v0) ? N : v0->info();\n    auto const i1 = dt.is_infinite(v1) ? N : v1->info();\n    auto const i2 = dt.is_infinite(v2) ? N : v2->info();\n    facets.push_back({i0, i1, i2});\n  }\n  // The infinite point is the south pole\n  points.emplace_back(0, 0, 1);\n\n  return facets;\n}\n\nstd::vector<Point_3> genPoints(std::size_t const N,\n                               Point_2 offset = Point_2(0, 0)) {\n  std::vector<Point_3> v;\n  assert(N >= 2 && \"N must be at leat 2\");\n  v.reserve(N * (N - 2) + 2);\n  for (unsigned int i = 0; i <= N; ++i) {\n    double const theta = offset[0] + M_PI * double(i) / double(N);\n    for (unsigned int j = 0; j < N; ++j) {\n      double const phi = offset[1] + 2.0 * M_PI * double(j) / double(N);\n      Point_3 const pCart(sphericalToCart(Point_2(theta, phi)));\n      v.push_back(pCart);\n      if (i == 0 || i == N) break;\n    }\n  }\n  return v;\n}\n\nPolyhedron constructPolyhedron() {\n  typedef Polyhedron::HalfedgeDS HDS;\n  auto v = genPoints(500);\n  // remove north pole\n  v.pop_back();\n  auto const f = triangulate(v);\n\n  struct Builder : public CGAL::Modifier_base<HDS> {\n    std::vector<Point_3> const &v_;\n    std::vector<std::array<std::size_t, 3>> const &f_;\n    Builder(std::vector<Point_3> const &vv,\n            std::vector<std::array<std::size_t, 3>> const &ff)\n        : v_(vv), f_(ff) {}\n    void operator()(HDS &hds) {\n      CGAL::Polyhedron_incremental_builder_3<HDS> b(hds, true);\n      std::size_t vIdx = 0;\n      b.begin_surface(v_.size(), f_.size());\n      for (auto const &p : v_) { b.add_vertex(p)->id() = vIdx++; }\n      for (auto const &t : f_) {\n        b.begin_facet();\n        b.add_vertex_to_facet(t[2]);\n        b.add_vertex_to_facet(t[1]);\n        b.add_vertex_to_facet(t[0]);\n        b.end_facet();\n      }\n      b.end_surface();\n    }\n  } builder(v, f);\n  Polyhedron p;\n  p.delegate(builder);\n  return p;\n}\n\nstatic std::size_t comparisonCount = 0;\n\ntemplate <class P>\nstruct CountingTraits\n    : public TriPQ::CGALSphericalPolyhedronTraitsBase<P, CountingTraits<P>> {\n  typedef TriPQ::CGALSphericalPolyhedronTraits<P> Base;\n  typedef CountingTraits<P> Self;\n  struct IsRightOf {\n    template <class Point>\n    inline bool operator()(typename Self::Edge e, Point const &p) const {\n      ++comparisonCount;\n      return typename Base::IsRightOf()(e, p);\n    }\n  };\n};\n\nnamespace std {\n\ntemplate <>\nstruct hash<typename CountingTraits<Polyhedron>::Edge>\n    : public hash<void const *> {\n  size_t operator()(typename CountingTraits<Polyhedron>::Edge e) const {\n    return hash<void const *>()(static_cast<void const *>(&*e));\n  }\n};\n\n} // namespace std\n\ntemplate <class Edge, class Point>\nbool assertPointInTriangle(Edge e, Point const &x) {\n  typedef TriPQ::CGALSphericalPolyhedronTraits<Polyhedron> T;\n\n  if (typename T::IsRightOf()(e, x)) return false;\n  if (typename T::IsRightOf()(e->next(), x)) return false;\n  if (typename T::IsRightOf()(e->next()->next(), x)) return false;\n  return true;\n}\n\ntemplate <class Query, class Points>\nvoid runQuery(Query const &q, Points const &p) {\n  comparisonCount = 0;\n  using Clock = std::chrono::high_resolution_clock;\n  using TimePoint = std::chrono::time_point<Clock>;\n  std::cout << \"\\tQuerying \" << p.size() << \" points...\" << std::flush;\n  TimePoint const start = Clock::now();\n\n  auto const edges = q(p);\n\n  using ms = std::chrono::milliseconds;\n  TimePoint const end = Clock::now();\n  auto const timeDiff = end - start;\n  std::cout << \"Done.\" << std::endl;\n  std::cout << \"\\tTook \" << std::chrono::duration_cast<ms>(timeDiff).count()\n            << \"ms\" << std::endl;\n  std::cout << \"\\tOn average \" << double(comparisonCount) / double(p.size())\n            << \" comparisons\" << std::endl;\n\n  for (unsigned int i = 0; i < p.size(); ++i) {\n    if (!assertPointInTriangle(edges[i], p[i])) {\n      std::cerr << \"Point not in triangle\" << std::endl;\n      std::cerr << \"Point \" << p[i] << std::endl;\n      std::cerr << \"Edge: (\" << edges[i]->opposite()->vertex()->id() << \", \"\n                << edges[i]->vertex()->id() << \")\" << std::endl;\n      std::cerr << \"Triangle \" << edges[i]->vertex()->id() << \", \"\n                << edges[i]->next()->vertex()->id() << \", \"\n                << edges[i]->next()->next()->vertex()->id() << std::endl;\n      exit(EXIT_FAILURE);\n    }\n  }\n}\n\nint main(int, char **) {\n  std::random_device rd;\n  std::mt19937 gen(rd());\n  std::uniform_real_distribution<double> theta(0, M_PI);\n  std::uniform_real_distribution<double> phi(0, 2.0 * M_PI);\n\n  typedef TriPQ::PointQuery<CountingTraits<Polyhedron>,\n                            TriPQ::StartFromFixedEdge,\n                            TriPQ::RandomEdgeSelect> QueryFixedRandom;\n  typedef TriPQ::PointQuery<CountingTraits<Polyhedron>,\n                            TriPQ::StartFromFixedEdge,\n                            TriPQ::SelectNearestEdge3> QueryFixedNearest;\n  typedef TriPQ::PointQuery<CountingTraits<Polyhedron>,\n                            TriPQ::StartFromLastEdge,\n                            TriPQ::RandomEdgeSelect> QueryLastRandom;\n  typedef TriPQ::PointQuery<CountingTraits<Polyhedron>,\n                            TriPQ::StartFromLastEdge,\n                            TriPQ::SelectNearestEdge3> QueryLastNearest;\n  typedef TriPQ::PointQuery<CountingTraits<Polyhedron>,\n                            TriPQ::StartFromMostLocatedEdge,\n                            TriPQ::RandomEdgeSelect> QueryMRRandom;\n  typedef TriPQ::PointQuery<CountingTraits<Polyhedron>,\n                            TriPQ::StartFromMostLocatedEdge,\n                            TriPQ::SelectNearestEdge3> QueryMRNearest;\n  typedef TriPQ::PointQuery<CountingTraits<Polyhedron>,\n                            TriPQ::StartFromMostLocatedEdgeUnordered,\n                            TriPQ::RandomEdgeSelect> QueryMRURandom;\n  typedef TriPQ::PointQuery<CountingTraits<Polyhedron>,\n                            TriPQ::StartFromMostLocatedEdgeUnordered,\n                            TriPQ::SelectNearestEdge3> QueryMRUNearest;\n\n  std::size_t const N = 40000;\n  // std::size_t const N = 4;\n\n  // Generate polyhedron\n  std::cout << \"Constructing triangulation... \" << std::flush;\n  auto const p = constructPolyhedron();\n  std::cout << \"done.\" << std::endl;\n\n  std::vector<Point_3> randomPoints(N - 1);\n  // generate query points\n  for (unsigned int i = 0; i < N - 1; ++i) {\n    randomPoints[i] = sphericalToCart(Point_2(theta(gen), phi(gen)));\n  }\n\n  auto const sequencialPoints =\n      genPoints(std::sqrt(N), Point_2(theta(gen), phi(gen)));\n\n  auto const e0 = p.halfedges_begin();\n\n  std::cout << \"Triangulation dimensions:\" << std::endl;\n  std::cout << \"\\t\" << p.size_of_vertices() << \" vertices\" << std::endl;\n  std::cout << \"\\t\" << p.size_of_facets() << \" triangles\" << std::endl;\n  std::cout << \"\\t\" << p.size_of_halfedges() / 2 << \" edges\" << std::endl;\n\n  std::cout << \"Fixed starting edge, random edge select\" << std::endl;\n  std::cout << \"Random points\" << std::endl;\n  runQuery(QueryFixedRandom(e0), randomPoints);\n  std::cout << \"Sequencial points\" << std::endl;\n  runQuery(QueryFixedRandom(e0), sequencialPoints);\n\n  std::cout << \"Fixed starting edge, nearest edge\" << std::endl;\n  std::cout << \"Random points\" << std::endl;\n  runQuery(QueryFixedNearest(e0), randomPoints);\n  std::cout << \"Sequencial points\" << std::endl;\n  runQuery(QueryFixedNearest(e0), sequencialPoints);\n\n  std::cout << \"Last starting edge, random edge\" << std::endl;\n  std::cout << \"Random points\" << std::endl;\n  runQuery(QueryLastRandom(e0), randomPoints);\n  std::cout << \"Sequencial points\" << std::endl;\n  runQuery(QueryLastRandom(e0), sequencialPoints);\n\n  std::cout << \"Last starting edge, nearest edge\" << std::endl;\n  std::cout << \"Random points\" << std::endl;\n  runQuery(QueryLastNearest(e0), randomPoints);\n  std::cout << \"Sequencial points\" << std::endl;\n  runQuery(QueryLastNearest(e0), sequencialPoints);\n\n  std::cout << \"Most located starting edge, random edge\" << std::endl;\n  std::cout << \"Random points\" << std::endl;\n  runQuery(QueryMRRandom(e0), randomPoints);\n  std::cout << \"Sequencial points\" << std::endl;\n  runQuery(QueryMRRandom(e0), sequencialPoints);\n\n  std::cout << \"Most located starting edge, nearest edge\" << std::endl;\n  std::cout << \"Random points\" << std::endl;\n  runQuery(QueryMRNearest(e0), randomPoints);\n  std::cout << \"Sequencial points\" << std::endl;\n  runQuery(QueryMRNearest(e0), sequencialPoints);\n\n  std::cout << \"Most located starting edge (unordered map), random edge\"\n            << std::endl;\n  std::cout << \"Random points\" << std::endl;\n  runQuery(QueryMRUNearest(e0), randomPoints);\n  std::cout << \"Sequencial points\" << std::endl;\n  runQuery(QueryMRURandom(e0), sequencialPoints);\n\n  std::cout << \"Most located starting edge (unordered map), nearest edge\"\n            << std::endl;\n  std::cout << \"Random points\" << std::endl;\n  runQuery(QueryMRUNearest(e0), randomPoints);\n  std::cout << \"Sequencial points\" << std::endl;\n  runQuery(QueryMRUNearest(e0), sequencialPoints);\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "596b246e2377720228c8051725a69cfb345eb286", "size": 11730, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/exampleSphericalTriangulation.cpp", "max_stars_repo_name": "ithron/TriPQ", "max_stars_repo_head_hexsha": "5559dab04bb6f4b632e516b70e7eb9a4eb211f65", "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/exampleSphericalTriangulation.cpp", "max_issues_repo_name": "ithron/TriPQ", "max_issues_repo_head_hexsha": "5559dab04bb6f4b632e516b70e7eb9a4eb211f65", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/exampleSphericalTriangulation.cpp", "max_forks_repo_name": "ithron/TriPQ", "max_forks_repo_head_hexsha": "5559dab04bb6f4b632e516b70e7eb9a4eb211f65", "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.5420560748, "max_line_length": 79, "alphanum_fraction": 0.6332480818, "num_tokens": 3410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5493119928024592}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n\nTEST(MathFunctions, digamma) {\n  EXPECT_FLOAT_EQ(boost::math::digamma(0.5), stan::math::digamma(0.5));\n  EXPECT_FLOAT_EQ(boost::math::digamma(-1.5), stan::math::digamma(-1.5));\n}  \n\nTEST(MathFunctions, digamma_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::digamma(nan));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::digamma(-1));\n}\n", "meta": {"hexsha": "a9725aaf9c066f379f28a30612bca63ee635d41b", "size": 635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/digamma_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/digamma_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/digamma_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.2380952381, "max_line_length": 73, "alphanum_fraction": 0.6881889764, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5493069762817807}}
{"text": "#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint module2()\n{\n    BZ_USING_NAMESPACE(blitz::tensor)\n\n    Array<int,1> A(4);\n    A = pow2(i);\n    return 0;\n}\n\n", "meta": {"hexsha": "4c8d38d780a1c1ddd055cc1544e705c92008c67a", "size": 165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/module2.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/module2.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/module2.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": 11.7857142857, "max_line_length": 37, "alphanum_fraction": 0.6303030303, "num_tokens": 54, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5493069595389527}}
{"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_EVALUATE_HPP\n#define CRYPTO3_MATH_EVALUATE_HPP\n\n#include <algorithm>\n#include <vector>\n\n#include <boost/math/tools/polynomial.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace math {\n            /*!\n             * @brief\n             * Naive evaluation of a *single* polynomial, used for testing purposes.\n             *\n             * The inputs are:\n             * - an integer m\n             * - a vector coeff representing monomial P of size m\n             * - a field element element t\n             * The output is the polynomial P(x) evaluated at x = t.\n             */\n            template<typename FieldValueType, typename ContiguousIterator>\n            inline FieldValueType evaluate_polynomial(ContiguousIterator first, ContiguousIterator last,\n                                                      const FieldValueType &t, std::size_t m) {\n                BOOST_ASSERT(std::distance(first, last) == m);\n\n                return boost::math::tools::evaluate_polynomial(&*first, t, m);\n            }\n\n            template<typename FieldValueType, typename ContiguousContainer>\n            inline FieldValueType evaluate_polynomial(const ContiguousContainer &coeff, const FieldValueType &t,\n                                                      std::size_t m) {\n                return evaluate_polynomial(coeff.begin(), coeff.end(), t, m);\n            }\n\n            /*!\n             * @brief\n             * Naive evaluation of a *single* Lagrange polynomial, used for testing purposes.\n             *\n             * The inputs are:\n             * - an integer m\n             * - a domain S = (a_{0},...,a_{m-1}) of size m\n             * - a field element element t\n             * - an index idx in {0,...,m-1}\n             * The output is the polynomial L_{idx,S}(z) evaluated at z = t.\n             */\n            template<typename FieldValueType, typename InputIterator>\n            inline FieldValueType evaluate_lagrange_polynomial(InputIterator first, InputIterator last,\n                                                               const FieldValueType &t, std::size_t m,\n                                                               std::size_t idx) {\n                typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n\n                BOOST_STATIC_ASSERT(std::is_same<value_type, FieldValueType>::value);\n\n                if (m != std::distance(first, last)) {\n                    throw std::invalid_argument(\"expected m == domain.size()\");\n                }\n                if (idx >= m) {\n                    throw std::invalid_argument(\"expected idx < m\");\n                }\n\n                value_type num = value_type::one();\n                value_type denom = value_type::one();\n\n                for (std::size_t k = 0; k < m; ++k) {\n                    if (k == idx) {\n                        continue;\n                    }\n\n                    num *= t - *(first + k);\n                    denom *= *(first + idx) - *(first + k);\n                }\n\n                return num * denom.inversed();\n            }\n\n            template<typename FieldValueType, typename Range>\n            inline FieldValueType evaluate_lagrange_polynomial(const Range &domain, const FieldValueType &t,\n                                                               std::size_t m, std::size_t idx) {\n                typedef FieldValueType value_type;\n                BOOST_STATIC_ASSERT(std::is_same<value_type, typename std::iterator_traits<decltype(std::begin(\n                                                                 std::declval<Range>()))>::value_type>::value);\n\n                return evaluate_lagrange_polynomial(domain.begin(), domain.end(), t, m, idx);\n            }\n        }    // namespace math\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // ALGEBRA_FFT_NAIVE_EVALUATE_HPP\n", "meta": {"hexsha": "92f8a89f92f9171ebd1d3cfce8e88cbf5bbf0db8", "size": 5269, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/math/polynomial/evaluate.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/evaluate.hpp", "max_issues_repo_name": "NilFoundation/fft", "max_issues_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-12-19T23:19:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T20:10:27.000Z", "max_forks_repo_path": "include/nil/crypto3/math/polynomial/evaluate.hpp", "max_forks_repo_name": "NilFoundation/crypto3-math", "max_forks_repo_head_hexsha": "9351ff8c0f1a75022457e82475b0eba2447ceecc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4224137931, "max_line_length": 112, "alphanum_fraction": 0.5496299108, "num_tokens": 1016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5493069595389526}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#define VMATH_CORE_SWIZZLE_ENABLE_ELEMENT_ACCESSORS\n#include <vmath/core/vector.hpp>\n#include <vmath/core/swizzle/swizzle3.hpp>\n\nBOOST_AUTO_TEST_SUITE(Swizzle3)\n\nBOOST_AUTO_TEST_CASE(negate_op) {\n\tvmath::core::Vector<float, 3> V;\n\tV.x = 20.12f;\n\tV.y = 100.89f;\n\tV.z = -18.2f;\n\tvmath::core::Vector<float, 3> V_neg;\n\tV_neg = -V.yzx;\n\tBOOST_CHECK_CLOSE(V_neg.x, -100.89f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_neg.y, 18.2f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_neg.z, -20.12f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(add_op) {\n\tvmath::core::Vector<float, 3> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = -18.2f;\n\tvmath::core::Vector<float, 3> V2;\n\tV2.x = 10.34f;\n\tV2.y = -15.5f;\n\tV2.z = 20.2f;\n\tvmath::core::Vector<float, 3> V_add;\n\tV_add = V1.yxy + V2.xxx;\n\tBOOST_CHECK_CLOSE(V_add.x, 111.23f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.y, 30.46f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.z, 111.23f, 1e-4f);\n\tV_add = V2.xxx + V1.yxy;\n\tBOOST_CHECK_CLOSE(V_add.x, 111.23f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.y, 30.46f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.x, 111.23f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(add_eq_op) {\n\tvmath::core::Vector<float, 3> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = -18.2f;\n\tvmath::core::Vector<float, 3> V2;\n\tV2.x = 10.34f;\n\tV2.y = -15.5f;\n\tV2.z = 20.2f;\n\tvmath::core::Vector<float, 3> V_add = V1;\n\tV_add.yxz += V2.xxx;\n\tBOOST_CHECK_CLOSE(V_add.x, 30.46f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.y, 111.23f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.z, -7.859999999f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(sub_op) {\n\tvmath::core::Vector<float, 3> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = -18.2f;\n\tvmath::core::Vector<float, 3> V2;\n\tV2.x = 10.34f;\n\tV2.y = -15.5f;\n\tV2.z = 20.12f;\n\tvmath::core::Vector<float, 3> V_sub;\n\tV_sub = V1.yxx - V2.xxz;\n\tBOOST_CHECK_CLOSE(V_sub.x, 90.55f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_sub.y, 9.78f, 1e-4f);\n\tBOOST_CHECK_SMALL(V_sub.z, 1e-7f);\n\tV_sub = V2.xxz - V1.yxx;\n\tBOOST_CHECK_CLOSE(V_sub.x, -90.55f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_sub.y, -9.78f, 1e-4f);\n\tBOOST_CHECK_SMALL(V_sub.z, 1e-7f);\n}\n\nBOOST_AUTO_TEST_CASE(sub_eq_op) {\n\tvmath::core::Vector<float, 3> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = -18.2f;\n\tvmath::core::Vector<float, 3> V2;\n\tV2.x = 10.34f;\n\tV2.y = -15.5f;\n\tV2.z = 20.2f;\n\tvmath::core::Vector<float, 3> V_sub = V1;\n\tV_sub.yxz -= V2.xxx;\n\tBOOST_CHECK_CLOSE(V_sub.x, 9.78f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_sub.y, 90.55f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_sub.z, -28.54f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(mult_op) {\n\tvmath::core::Vector<float, 3> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = -18.2f;\n\tvmath::core::Vector<float, 3> V2;\n\tV2.x = 10.34f;\n\tV2.y = -15.5f;\n\tV2.z = 20.2f;\n\tvmath::core::Vector<float, 3> V_mult;\n\tV_mult = V1.yxx * V2.xxx;\n\tBOOST_CHECK_CLOSE(V_mult.x, 1043.2026f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.y, 208.0408f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.z, 208.0408f, 1e-4f);\n\tV_mult = V2.xxx * V1.yxx;\n\tBOOST_CHECK_CLOSE(V_mult.x, 1043.2026f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.y, 208.0408f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.z, 208.0408f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(mult_eq_op) {\n\tvmath::core::Vector<float, 3> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = -18.2f;\n\tvmath::core::Vector<float, 3> V2;\n\tV2.x = 10.34f;\n\tV2.y = -15.5f;\n\tV2.z = 20.2f;\n\tvmath::core::Vector<float, 3> V_mult = V1;\n\tV_mult.yxz *= V2.xyx;\n\tBOOST_CHECK_CLOSE(V_mult.x, -311.86f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.y, 1043.2026f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.z, -188.188f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(div_op) {\n\tvmath::core::Vector<float, 3> V1;\n\tV1.x = 20.0f;\n\tV1.y = 40.0f;\n\tV1.z = 60.0f;\n\tvmath::core::Vector<float, 3> V2;\n\tV2.x = 2.0f;\n\tV2.y = 4.0f;\n\tV2.z = 6.0f;\n\tvmath::core::Vector<float, 3> V_div;\n\tV_div = V1.yxx / V2.xxx;\n\tBOOST_CHECK_CLOSE(V_div.x, 20.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.y, 10.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.z, 10.0f, 1e-4f);\n\tV_div = V1.xxx / V2.yxx;\n\tBOOST_CHECK_CLOSE(V_div.x, 5.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.y, 10.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.z, 10.0f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(div_eq_op) {\n\tvmath::core::Vector<float, 3> V1;\n\tV1.x = 20.0f;\n\tV1.y = 40.0f;\n\tV1.z = 60.0f;\n\tvmath::core::Vector<float, 3> V2;\n\tV2.x = 2.0f;\n\tV2.y = 4.0f;\n\tV2.z = 6.0f;\n\tvmath::core::Vector<float, 3> V_div = V1;\n\tV_div.yxz /= V2.yxx;\n\tBOOST_CHECK_CLOSE(V_div.x, 10.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.y, 10.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.z, 30.0f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(scalar_mult_op) {\n\tvmath::core::Vector<float, 3> V;\n\tV.x = 20.12f;\n\tV.y = 100.89f;\n\tV.z = -18.2f;\n\tfloat s = -34.45f;\n\tvmath::core::Vector<float, 3> V_mult;\n\tV_mult = V.xyz * s;\n\tBOOST_CHECK_CLOSE(V_mult.x, -693.134f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.y, -3475.6605f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.z, 626.99f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(scalar_mult_eq_op) {\n\tvmath::core::Vector<float, 3> V;\n\tV.x = 20.12f;\n\tV.y = 100.89f;\n\tV.z = -18.2f;\n\tfloat s = -34.45f;\n\tvmath::core::Vector<float, 3> V_mult = V;\n\tV_mult.zyx *= s;\n\tBOOST_CHECK_CLOSE(V_mult.x, -693.134f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.y, -3475.6605f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.z, 626.99f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(scalar_div_op) {\n\tvmath::core::Vector<float, 3> V;\n\tV.x = 20.12f;\n\tV.y = 100.89f;\n\tV.z = -18.2f;\n\tfloat s = -34.45f;\n\tvmath::core::Vector<float, 3> V_div;\n\tV_div.xyz = V / s;\n\tBOOST_CHECK_CLOSE(V_div.x, -0.5840348330914369f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.y, -2.9285921625544264f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.z, 0.5283018867924527f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(scalar_div_eq_op) {\n\tvmath::core::Vector<float, 3> V;\n\tV.x = 20.12f;\n\tV.y = 100.89f;\n\tV.z = -18.2f;\n\tfloat s = -34.45f;\n\tvmath::core::Vector<float, 3> V_div = V;\n\tV_div.zxy /= s;\n\tBOOST_CHECK_CLOSE(V_div.x, -0.5840348330914369f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.y, -2.9285921625544264f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.z, 0.5283018867924527f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(swizzles) {\n\tvmath::core::Vector<float, 3> V;\n\tV.x = 20.12f;\n\tV.y = 100.89f;\n\tV.z = -18.2f;\n\t// 2d swizzles <x, y, z>\n\tauto xx = V.xx;\n\tBOOST_CHECK_CLOSE(xx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xx.getE2(), V.x, 1e-4f);\n\tauto xy = V.xy;\n\tBOOST_CHECK_CLOSE(xy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xy.getE2(), V.y, 1e-4f);\n\tauto xz = V.xz;\n\tBOOST_CHECK_CLOSE(xz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xz.getE2(), V.z, 1e-4f);\n\tauto yx = V.yx;\n\tBOOST_CHECK_CLOSE(yx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yx.getE2(), V.x, 1e-4f);\n\tauto yy = V.yy;\n\tBOOST_CHECK_CLOSE(yy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yy.getE2(), V.y, 1e-4f);\n\tauto yz = V.yz;\n\tBOOST_CHECK_CLOSE(yz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yz.getE2(), V.z, 1e-4f);\n\tauto zx = V.zx;\n\tBOOST_CHECK_CLOSE(zx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zx.getE2(), V.x, 1e-4f);\n\tauto zy = V.zy;\n\tBOOST_CHECK_CLOSE(zy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zy.getE2(), V.y, 1e-4f);\n\tauto zz = V.zz;\n\tBOOST_CHECK_CLOSE(zz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zz.getE2(), V.z, 1e-4f);\n\t// 3d swizzles <x, y, z>\n\tauto xxx = V.xxx;\n\tBOOST_CHECK_CLOSE(xxx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxx.getE3(), V.x, 1e-4f);\n\tauto xxy = V.xxy;\n\tBOOST_CHECK_CLOSE(xxy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxy.getE3(), V.y, 1e-4f);\n\tauto xxz = V.xxz;\n\tBOOST_CHECK_CLOSE(xxz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxz.getE3(), V.z, 1e-4f);\n\tauto xyx = V.xyx;\n\tBOOST_CHECK_CLOSE(xyx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyx.getE3(), V.x, 1e-4f);\n\tauto xyy = V.xyy;\n\tBOOST_CHECK_CLOSE(xyy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyy.getE3(), V.y, 1e-4f);\n\tauto xyz = V.xyz;\n\tBOOST_CHECK_CLOSE(xyz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyz.getE3(), V.z, 1e-4f);\n\tauto xzx = V.xzx;\n\tBOOST_CHECK_CLOSE(xzx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzx.getE3(), V.x, 1e-4f);\n\tauto xzy = V.xzy;\n\tBOOST_CHECK_CLOSE(xzy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzy.getE3(), V.y, 1e-4f);\n\tauto xzz = V.xzz;\n\tBOOST_CHECK_CLOSE(xzz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzz.getE3(), V.z, 1e-4f);\n\tauto yxx = V.yxx;\n\tBOOST_CHECK_CLOSE(yxx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxx.getE3(), V.x, 1e-4f);\n\tauto yxy = V.yxy;\n\tBOOST_CHECK_CLOSE(yxy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxy.getE3(), V.y, 1e-4f);\n\tauto yxz = V.yxz;\n\tBOOST_CHECK_CLOSE(yxz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxz.getE3(), V.z, 1e-4f);\n\tauto yyx = V.yyx;\n\tBOOST_CHECK_CLOSE(yyx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyx.getE3(), V.x, 1e-4f);\n\tauto yyy = V.yyy;\n\tBOOST_CHECK_CLOSE(yyy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyy.getE3(), V.y, 1e-4f);\n\tauto yyz = V.yyz;\n\tBOOST_CHECK_CLOSE(yyz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyz.getE3(), V.z, 1e-4f);\n\tauto yzx = V.yzx;\n\tBOOST_CHECK_CLOSE(yzx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzx.getE3(), V.x, 1e-4f);\n\tauto yzy = V.yzy;\n\tBOOST_CHECK_CLOSE(yzy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzy.getE3(), V.y, 1e-4f);\n\tauto yzz = V.yzz;\n\tBOOST_CHECK_CLOSE(yzz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzz.getE3(), V.z, 1e-4f);\n\tauto zxx = V.zxx;\n\tBOOST_CHECK_CLOSE(zxx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxx.getE3(), V.x, 1e-4f);\n\tauto zxy = V.zxy;\n\tBOOST_CHECK_CLOSE(zxy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxy.getE3(), V.y, 1e-4f);\n\tauto zxz = V.zxz;\n\tBOOST_CHECK_CLOSE(zxz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxz.getE3(), V.z, 1e-4f);\n\tauto zyx = V.zyx;\n\tBOOST_CHECK_CLOSE(zyx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyx.getE3(), V.x, 1e-4f);\n\tauto zyy = V.zyy;\n\tBOOST_CHECK_CLOSE(zyy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyy.getE3(), V.y, 1e-4f);\n\tauto zyz = V.zyz;\n\tBOOST_CHECK_CLOSE(zyz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyz.getE3(), V.z, 1e-4f);\n\tauto zzx = V.zzx;\n\tBOOST_CHECK_CLOSE(zzx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzx.getE3(), V.x, 1e-4f);\n\tauto zzy = V.zzy;\n\tBOOST_CHECK_CLOSE(zzy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzy.getE3(), V.y, 1e-4f);\n\tauto zzz = V.zzz;\n\tBOOST_CHECK_CLOSE(zzz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzz.getE3(), V.z, 1e-4f);\n\t// 4d swizzles <x, y, z>\n\tauto xxxx = V.xxxx;\n\tBOOST_CHECK_CLOSE(xxxx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxx.getE4(), V.x, 1e-4f);\n\tauto xxxy = V.xxxy;\n\tBOOST_CHECK_CLOSE(xxxy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxy.getE4(), V.y, 1e-4f);\n\tauto xxxz = V.xxxz;\n\tBOOST_CHECK_CLOSE(xxxz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxz.getE4(), V.z, 1e-4f);\n\tauto xxyx = V.xxyx;\n\tBOOST_CHECK_CLOSE(xxyx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyx.getE4(), V.x, 1e-4f);\n\tauto xxyy = V.xxyy;\n\tBOOST_CHECK_CLOSE(xxyy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyy.getE4(), V.y, 1e-4f);\n\tauto xxyz = V.xxyz;\n\tBOOST_CHECK_CLOSE(xxyz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyz.getE4(), V.z, 1e-4f);\n\tauto xxzx = V.xxzx;\n\tBOOST_CHECK_CLOSE(xxzx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzx.getE4(), V.x, 1e-4f);\n\tauto xxzy = V.xxzy;\n\tBOOST_CHECK_CLOSE(xxzy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzy.getE4(), V.y, 1e-4f);\n\tauto xxzz = V.xxzz;\n\tBOOST_CHECK_CLOSE(xxzz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzz.getE4(), V.z, 1e-4f);\n\tauto xyxx = V.xyxx;\n\tBOOST_CHECK_CLOSE(xyxx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxx.getE4(), V.x, 1e-4f);\n\tauto xyxy = V.xyxy;\n\tBOOST_CHECK_CLOSE(xyxy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxy.getE4(), V.y, 1e-4f);\n\tauto xyxz = V.xyxz;\n\tBOOST_CHECK_CLOSE(xyxz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxz.getE4(), V.z, 1e-4f);\n\tauto xyyx = V.xyyx;\n\tBOOST_CHECK_CLOSE(xyyx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyx.getE4(), V.x, 1e-4f);\n\tauto xyyy = V.xyyy;\n\tBOOST_CHECK_CLOSE(xyyy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyy.getE4(), V.y, 1e-4f);\n\tauto xyyz = V.xyyz;\n\tBOOST_CHECK_CLOSE(xyyz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyz.getE4(), V.z, 1e-4f);\n\tauto xyzx = V.xyzx;\n\tBOOST_CHECK_CLOSE(xyzx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzx.getE4(), V.x, 1e-4f);\n\tauto xyzy = V.xyzy;\n\tBOOST_CHECK_CLOSE(xyzy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzy.getE4(), V.y, 1e-4f);\n\tauto xyzz = V.xyzz;\n\tBOOST_CHECK_CLOSE(xyzz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzz.getE4(), V.z, 1e-4f);\n\tauto xzxx = V.xzxx;\n\tBOOST_CHECK_CLOSE(xzxx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxx.getE4(), V.x, 1e-4f);\n\tauto xzxy = V.xzxy;\n\tBOOST_CHECK_CLOSE(xzxy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxy.getE4(), V.y, 1e-4f);\n\tauto xzxz = V.xzxz;\n\tBOOST_CHECK_CLOSE(xzxz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxz.getE4(), V.z, 1e-4f);\n\tauto xzyx = V.xzyx;\n\tBOOST_CHECK_CLOSE(xzyx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyx.getE4(), V.x, 1e-4f);\n\tauto xzyy = V.xzyy;\n\tBOOST_CHECK_CLOSE(xzyy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyy.getE4(), V.y, 1e-4f);\n\tauto xzyz = V.xzyz;\n\tBOOST_CHECK_CLOSE(xzyz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyz.getE4(), V.z, 1e-4f);\n\tauto xzzx = V.xzzx;\n\tBOOST_CHECK_CLOSE(xzzx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzx.getE4(), V.x, 1e-4f);\n\tauto xzzy = V.xzzy;\n\tBOOST_CHECK_CLOSE(xzzy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzy.getE4(), V.y, 1e-4f);\n\tauto xzzz = V.xzzz;\n\tBOOST_CHECK_CLOSE(xzzz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzz.getE4(), V.z, 1e-4f);\n\tauto yxxx = V.yxxx;\n\tBOOST_CHECK_CLOSE(yxxx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxx.getE4(), V.x, 1e-4f);\n\tauto yxxy = V.yxxy;\n\tBOOST_CHECK_CLOSE(yxxy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxy.getE4(), V.y, 1e-4f);\n\tauto yxxz = V.yxxz;\n\tBOOST_CHECK_CLOSE(yxxz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxz.getE4(), V.z, 1e-4f);\n\tauto yxyx = V.yxyx;\n\tBOOST_CHECK_CLOSE(yxyx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyx.getE4(), V.x, 1e-4f);\n\tauto yxyy = V.yxyy;\n\tBOOST_CHECK_CLOSE(yxyy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyy.getE4(), V.y, 1e-4f);\n\tauto yxyz = V.yxyz;\n\tBOOST_CHECK_CLOSE(yxyz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyz.getE4(), V.z, 1e-4f);\n\tauto yxzx = V.yxzx;\n\tBOOST_CHECK_CLOSE(yxzx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzx.getE4(), V.x, 1e-4f);\n\tauto yxzy = V.yxzy;\n\tBOOST_CHECK_CLOSE(yxzy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzy.getE4(), V.y, 1e-4f);\n\tauto yxzz = V.yxzz;\n\tBOOST_CHECK_CLOSE(yxzz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzz.getE4(), V.z, 1e-4f);\n\tauto yyxx = V.yyxx;\n\tBOOST_CHECK_CLOSE(yyxx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxx.getE4(), V.x, 1e-4f);\n\tauto yyxy = V.yyxy;\n\tBOOST_CHECK_CLOSE(yyxy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxy.getE4(), V.y, 1e-4f);\n\tauto yyxz = V.yyxz;\n\tBOOST_CHECK_CLOSE(yyxz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxz.getE4(), V.z, 1e-4f);\n\tauto yyyx = V.yyyx;\n\tBOOST_CHECK_CLOSE(yyyx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyx.getE4(), V.x, 1e-4f);\n\tauto yyyy = V.yyyy;\n\tBOOST_CHECK_CLOSE(yyyy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyy.getE4(), V.y, 1e-4f);\n\tauto yyyz = V.yyyz;\n\tBOOST_CHECK_CLOSE(yyyz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyz.getE4(), V.z, 1e-4f);\n\tauto yyzx = V.yyzx;\n\tBOOST_CHECK_CLOSE(yyzx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzx.getE4(), V.x, 1e-4f);\n\tauto yyzy = V.yyzy;\n\tBOOST_CHECK_CLOSE(yyzy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzy.getE4(), V.y, 1e-4f);\n\tauto yyzz = V.yyzz;\n\tBOOST_CHECK_CLOSE(yyzz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzz.getE4(), V.z, 1e-4f);\n\tauto yzxx = V.yzxx;\n\tBOOST_CHECK_CLOSE(yzxx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxx.getE4(), V.x, 1e-4f);\n\tauto yzxy = V.yzxy;\n\tBOOST_CHECK_CLOSE(yzxy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxy.getE4(), V.y, 1e-4f);\n\tauto yzxz = V.yzxz;\n\tBOOST_CHECK_CLOSE(yzxz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxz.getE4(), V.z, 1e-4f);\n\tauto yzyx = V.yzyx;\n\tBOOST_CHECK_CLOSE(yzyx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyx.getE4(), V.x, 1e-4f);\n\tauto yzyy = V.yzyy;\n\tBOOST_CHECK_CLOSE(yzyy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyy.getE4(), V.y, 1e-4f);\n\tauto yzyz = V.yzyz;\n\tBOOST_CHECK_CLOSE(yzyz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyz.getE4(), V.z, 1e-4f);\n\tauto yzzx = V.yzzx;\n\tBOOST_CHECK_CLOSE(yzzx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzx.getE4(), V.x, 1e-4f);\n\tauto yzzy = V.yzzy;\n\tBOOST_CHECK_CLOSE(yzzy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzy.getE4(), V.y, 1e-4f);\n\tauto yzzz = V.yzzz;\n\tBOOST_CHECK_CLOSE(yzzz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzz.getE4(), V.z, 1e-4f);\n\tauto zxxx = V.zxxx;\n\tBOOST_CHECK_CLOSE(zxxx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxx.getE4(), V.x, 1e-4f);\n\tauto zxxy = V.zxxy;\n\tBOOST_CHECK_CLOSE(zxxy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxy.getE4(), V.y, 1e-4f);\n\tauto zxxz = V.zxxz;\n\tBOOST_CHECK_CLOSE(zxxz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxz.getE4(), V.z, 1e-4f);\n\tauto zxyx = V.zxyx;\n\tBOOST_CHECK_CLOSE(zxyx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyx.getE4(), V.x, 1e-4f);\n\tauto zxyy = V.zxyy;\n\tBOOST_CHECK_CLOSE(zxyy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyy.getE4(), V.y, 1e-4f);\n\tauto zxyz = V.zxyz;\n\tBOOST_CHECK_CLOSE(zxyz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyz.getE4(), V.z, 1e-4f);\n\tauto zxzx = V.zxzx;\n\tBOOST_CHECK_CLOSE(zxzx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzx.getE4(), V.x, 1e-4f);\n\tauto zxzy = V.zxzy;\n\tBOOST_CHECK_CLOSE(zxzy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzy.getE4(), V.y, 1e-4f);\n\tauto zxzz = V.zxzz;\n\tBOOST_CHECK_CLOSE(zxzz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzz.getE4(), V.z, 1e-4f);\n\tauto zyxx = V.zyxx;\n\tBOOST_CHECK_CLOSE(zyxx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxx.getE4(), V.x, 1e-4f);\n\tauto zyxy = V.zyxy;\n\tBOOST_CHECK_CLOSE(zyxy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxy.getE4(), V.y, 1e-4f);\n\tauto zyxz = V.zyxz;\n\tBOOST_CHECK_CLOSE(zyxz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxz.getE4(), V.z, 1e-4f);\n\tauto zyyx = V.zyyx;\n\tBOOST_CHECK_CLOSE(zyyx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyx.getE4(), V.x, 1e-4f);\n\tauto zyyy = V.zyyy;\n\tBOOST_CHECK_CLOSE(zyyy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyy.getE4(), V.y, 1e-4f);\n\tauto zyyz = V.zyyz;\n\tBOOST_CHECK_CLOSE(zyyz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyz.getE4(), V.z, 1e-4f);\n\tauto zyzx = V.zyzx;\n\tBOOST_CHECK_CLOSE(zyzx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzx.getE4(), V.x, 1e-4f);\n\tauto zyzy = V.zyzy;\n\tBOOST_CHECK_CLOSE(zyzy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzy.getE4(), V.y, 1e-4f);\n\tauto zyzz = V.zyzz;\n\tBOOST_CHECK_CLOSE(zyzz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzz.getE4(), V.z, 1e-4f);\n\tauto zzxx = V.zzxx;\n\tBOOST_CHECK_CLOSE(zzxx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxx.getE4(), V.x, 1e-4f);\n\tauto zzxy = V.zzxy;\n\tBOOST_CHECK_CLOSE(zzxy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxy.getE4(), V.y, 1e-4f);\n\tauto zzxz = V.zzxz;\n\tBOOST_CHECK_CLOSE(zzxz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxz.getE4(), V.z, 1e-4f);\n\tauto zzyx = V.zzyx;\n\tBOOST_CHECK_CLOSE(zzyx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyx.getE4(), V.x, 1e-4f);\n\tauto zzyy = V.zzyy;\n\tBOOST_CHECK_CLOSE(zzyy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyy.getE4(), V.y, 1e-4f);\n\tauto zzyz = V.zzyz;\n\tBOOST_CHECK_CLOSE(zzyz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyz.getE4(), V.z, 1e-4f);\n\tauto zzzx = V.zzzx;\n\tBOOST_CHECK_CLOSE(zzzx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzx.getE4(), V.x, 1e-4f);\n\tauto zzzy = V.zzzy;\n\tBOOST_CHECK_CLOSE(zzzy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzy.getE4(), V.y, 1e-4f);\n\tauto zzzz = V.zzzz;\n\tBOOST_CHECK_CLOSE(zzzz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzz.getE4(), V.z, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(assign_op) {\n\tvmath::core::Vector<float, 2> V2;\n\tV2.x = 20.12f;\n\tV2.y = 100.89f;\n\tvmath::core::Vector<float, 3> V3;\n\tV3.x = 20.12f;\n\tV3.y = 100.89f;\n\tV3.z = -18.2f;\n\tvmath::core::Vector<float, 3> V;\n\tV.x = 0.0f;\n\tV.y = 0.0f;\n\tV.z = 0.0f;\n\t// 2d swizzle assign <x, y, z> from vector\n\tV.xy = V2;\n\tBOOST_CHECK_CLOSE(V.x, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.y, 1e-4f);\n\tBOOST_CHECK_SMALL(V.z, 1e-7f);\n\tV.xz = V2;\n\tBOOST_CHECK_CLOSE(V.x, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.y, 1e-4f);\n\tV.yx = V2;\n\tBOOST_CHECK_CLOSE(V.x, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.y, 1e-4f);\n\tV.yz = V2;\n\tBOOST_CHECK_CLOSE(V.x, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.y, 1e-4f);\n\tV.zx = V2;\n\tBOOST_CHECK_CLOSE(V.x, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.x, 1e-4f);\n\tV.zy = V2;\n\tBOOST_CHECK_CLOSE(V.x, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.x, 1e-4f);\n\t// 2d swizzle assign <x, y, z> from swizzle\n\tV.xy = V2.xx;\n\tBOOST_CHECK_CLOSE(V.x, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.x, 1e-4f);\n\tV.xz = V2.yy;\n\tBOOST_CHECK_CLOSE(V.x, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.y, 1e-4f);\n\tV.yx = V.xy;\n\tBOOST_CHECK_CLOSE(V.x, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.y, 1e-4f);\n\tV.yz = V.xx;\n\tBOOST_CHECK_CLOSE(V.x, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.x, 1e-4f);\n\tV.zx = V2.yy;\n\tBOOST_CHECK_CLOSE(V.x, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.y, 1e-4f);\n\tV.zy = V2.xy;\n\tBOOST_CHECK_CLOSE(V.x, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.x, 1e-4f);\n\t// 3d swizzle assign <x, y, z> from vector\n\tV.xyz = V3;\n\tBOOST_CHECK_CLOSE(V.x, V3.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.z, 1e-4f);\n\tV.xzy = V3;\n\tBOOST_CHECK_CLOSE(V.x, V3.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.y, 1e-4f);\n\tV.yxz = V3;\n\tBOOST_CHECK_CLOSE(V.x, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.z, 1e-4f);\n\tV.yzx = V3;\n\tBOOST_CHECK_CLOSE(V.x, V3.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.y, 1e-4f);\n\tV.zxy = V3;\n\tBOOST_CHECK_CLOSE(V.x, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.x, 1e-4f);\n\tV.zyx = V3;\n\tBOOST_CHECK_CLOSE(V.x, V3.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.x, 1e-4f);\n\t// 3d swizzle assign <x, y, z> from swizzle\n\tV.xyz = V3.xyz;\n\tBOOST_CHECK_CLOSE(V.x, V3.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.z, 1e-4f);\n\tV.xzy = V3.yyx;\n\tBOOST_CHECK_CLOSE(V.x, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.y, 1e-4f);\n\tV.yxz = V3.yxy;\n\tBOOST_CHECK_CLOSE(V.x, V3.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.y, 1e-4f);\n\tV.yzx = V3.zzz;\n\tBOOST_CHECK_CLOSE(V.x, V3.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.z, 1e-4f);\n\tV.zxy = V3.xyz;\n\tBOOST_CHECK_CLOSE(V.x, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.x, 1e-4f);\n\tV.zyx = V3.zyx;\n\tBOOST_CHECK_CLOSE(V.x, V3.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.z, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(equals) {\n\tvmath::core::Vector<float, 3> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = 18.2f;\n\tvmath::core::Vector<float, 3> V2;\n\tV2.x = 10.34f;\n\tV2.y = 15.5f;\n\tV2.z = 20.2f;\n\tvmath::core::Vector<float, 3> V3;\n\tV3.x = 20.12f;\n\tV3.y = 100.89f;\n\tV3.z = 18.2f;\n\tBOOST_CHECK(!V1.xyz.equals(V2));\n\tBOOST_CHECK(!V2.xyz.equals(V3));\n\tBOOST_CHECK(V1.xyz.equals(V1));\n\tBOOST_CHECK(V1.xyz.equals(V3));\n}\n\nBOOST_AUTO_TEST_CASE(equals_specify_ulp) {\n\tvmath::core::Vector<float, 3> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = 18.2f;\n\tvmath::core::Vector<float, 3> V2;\n\tV2.x = 10.34f;\n\tV2.y = 15.5f;\n\tV2.z = 20.2f;\n\tvmath::core::Vector<float, 3> V3;\n\tV3.x = 20.12f;\n\tV3.y = 100.89f;\n\tV3.z = 18.2f;\n\tBOOST_CHECK(!V1.xyz.equals(V2, 3));\n\tBOOST_CHECK(!V2.xyz.equals(V3, 3));\n\tBOOST_CHECK(V1.xyz.equals(V1, 3));\n\tBOOST_CHECK(V1.xyz.equals(V3, 3));\n}\n\nBOOST_AUTO_TEST_CASE(equals_op) {\n\tvmath::core::Vector<float, 3> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = 18.2f;\n\tvmath::core::Vector<float, 3> V2;\n\tV2.x = 10.34f;\n\tV2.y = 15.5f;\n\tV2.z = 20.2f;\n\tvmath::core::Vector<float, 3> V3;\n\tV3.x = 20.12f;\n\tV3.y = 100.89f;\n\tV3.z = 18.2f;\n\tBOOST_CHECK(V1.xyz != V2);\n\tBOOST_CHECK(V2.xyz != V3);\n\tBOOST_CHECK(V1.xyz == V1);\n\tBOOST_CHECK(V1.xyz == V3);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "58ed3e4a9a120f90dc3c7206c256244a502afad6", "size": 32469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/swizzle3.cpp", "max_stars_repo_name": "ChasingCarrots/vmath", "max_stars_repo_head_hexsha": "06cc93e0d3d152306dbd63b60fa7cc4761f331bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-15T13:56:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-15T13:56:26.000Z", "max_issues_repo_path": "test/swizzle3.cpp", "max_issues_repo_name": "kernan/math", "max_issues_repo_head_hexsha": "6c28e7e731a2ea47a7b66b5dd4170283e84f1e02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T19:11:09.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T21:19:58.000Z", "max_forks_repo_path": "test/swizzle3.cpp", "max_forks_repo_name": "kernan/vmath", "max_forks_repo_head_hexsha": "6c28e7e731a2ea47a7b66b5dd4170283e84f1e02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-06T21:00:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-06T21:00:34.000Z", "avg_line_length": 34.5782747604, "max_line_length": 57, "alphanum_fraction": 0.6753210755, "num_tokens": 14103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042765, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5493069595389525}}
{"text": "#pragma once\n\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <array>\n#include <sstream>\n\nnamespace futurehead_pow_server\n{\n/** A generic wrapper around multiprecision integers, adding convenience functions */\ntemplate <typename T, size_t SIZE_BYTES>\nstruct bigint\n{\n\tbigint () = default;\n\tbigint (T val)\n\t{\n\t\tset (val);\n\t}\n\n\tbigint (std::string const & val)\n\t{\n\t\tfrom_hex (val);\n\t}\n\n\tvoid set (T const & number_a)\n\t{\n\t\tbytes.fill (0);\n\t\tboost::multiprecision::export_bits (number_a, bytes.rbegin (), 8, false);\n\t}\n\n\tT number () const\n\t{\n\t\tT result;\n\t\tboost::multiprecision::import_bits (result, bytes.begin (), bytes.end ());\n\t\treturn result;\n\t}\n\n\tstd::string to_dec () const\n\t{\n\t\tstd::stringstream stream;\n\t\tstream << std::dec << std::noshowbase;\n\t\tstream << number ();\n\t\treturn stream.str ();\n\t}\n\n\tstd::string to_hex () const\n\t{\n\t\tstd::stringstream stream;\n\t\tstream << std::hex << std::uppercase << std::noshowbase << std::setw (SIZE_BYTES * 2) << std::setfill ('0');\n\t\tstream << number ();\n\t\treturn stream.str ();\n\t}\n\n\tvoid from_hex (std::string const & text)\n\t{\n\t\tif (!text.empty () && text.size () <= SIZE_BYTES * 2)\n\t\t{\n\t\t\tstd::stringstream stream (text);\n\t\t\tstream << std::hex << std::noshowbase;\n\n\t\t\tT number;\n\t\t\tstream >> number;\n\t\t\tset (number);\n\t\t\tif (!stream.eof ())\n\t\t\t{\n\t\t\t\tthrow std::runtime_error (\"from_hex failed: invalid input format\");\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::runtime_error (\"from_hex failed: invalid input size\");\n\t\t}\n\t}\n\n\tunion\n\t{\n\t\tstd::array<uint8_t, SIZE_BYTES> bytes;\n\t\tstd::array<uint64_t, SIZE_BYTES / sizeof (uint64_t)> qwords;\n\t};\n};\n\nusing u128 = bigint<boost::multiprecision::uint128_t, 16>;\nusing u256 = bigint<boost::multiprecision::uint256_t, 32>;\nusing u512 = bigint<boost::multiprecision::uint512_t, 64>;\nusing bigfloat = boost::multiprecision::cpp_bin_float_100;\n\ninline double to_multiplier (futurehead_pow_server::u128 const difficulty_a, futurehead_pow_server::u128 const base_difficulty_a)\n{\n\tassert (difficulty_a.number () > 0);\n\tbigfloat res = (bigfloat (difficulty_a.number ()) / bigfloat (base_difficulty_a.number ()));\n\treturn res.convert_to<double> ();\n}\n\ninline futurehead_pow_server::u128 from_multiplier (double const multiplier_a, futurehead_pow_server::u128 const base_difficulty_a)\n{\n\tbigfloat res = bigfloat (base_difficulty_a.number ()) * bigfloat (multiplier_a);\n\treturn res.convert_to<boost::multiprecision::uint128_t> ();\n}\n}\n", "meta": {"hexsha": "1d05d57c203d8a14e2a2f351fc6ccd32c604c1c9", "size": 2502, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "futurehead-pow-server/src/workserver/util.hpp", "max_stars_repo_name": "futureheadgroup/futurehead-node", "max_stars_repo_head_hexsha": "9995fb99462c77b07a880763cbb162a41279a5da", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-15T03:09:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-09T13:44:48.000Z", "max_issues_repo_path": "futurehead-pow-server/src/workserver/util.hpp", "max_issues_repo_name": "FutureHeadCoin/futurehead-node", "max_issues_repo_head_hexsha": "3871da56c478144b79cb12d43813f49ad280f6d4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "futurehead-pow-server/src/workserver/util.hpp", "max_forks_repo_name": "FutureHeadCoin/futurehead-node", "max_forks_repo_head_hexsha": "3871da56c478144b79cb12d43813f49ad280f6d4", "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.5294117647, "max_line_length": 131, "alphanum_fraction": 0.6954436451, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5493069534119956}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// random::poisson::devroye::crtp::parameters.hpp                        \t//\n//                                                                          //\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#ifndef BOOST_RANDOM_POISSON_EXT_DEVROYE_CRTP_PARAMETERS_HPP_ER_2010\n#define BOOST_RANDOM_POISSON_EXT_DEVROYE_CRTP_PARAMETERS_HPP_ER_2010\n#include <boost/math/constants/constants.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace poisson{\nnamespace devroye{            \n            \n    // These are quantities that remain fixed throughout sampling and are only\n    // modified if the poisson mean is changed.\n\ttemplate<typename Int,typename T, typename P,typename IntT>\n    struct parameters{\n        typedef IntT converter_;\n\n    \tpublic:\n        static const T pi;\n        static const T one;\n        static const T two;\n        static const T eps;\n        \n        typedef Int result_type;\n        typedef T input_type;\n        \n        parameters(){}\n    \texplicit parameters(const Int& i_mean)\n        {\n            using namespace boost::math;\n\t\t\tthis->m1_ = converter_::convert( i_mean );\n\t\t\tthis->m2_ = converter_::convert( 2 * i_mean );\t\n\t\t\tT m8  = converter_::convert( 8 * i_mean );\n            T m32 = converter_::convert( 32 * i_mean );\n            this->c1_ = converter_::convert(1) / m8; // Equation (6)\t\t\t\n            \n            // Equation (10)\n            this->delta_ = \tlog1p( m32 / pi, P() );\t\t\n            this->delta_ = \tsqrt( this->delta() * this->m1() );\t\n\n\t\t\t// Below equation (7)\n\t\t\tthis->sd1_ = sqrt( this->m1() + this->delta() / two );\n            this->shape2_ = this->delta() / ( this->m2() + this->delta() ); \n            \n            T a1, a2, a3, a;\n\t\t\t\n\t\t\ta1 = sqrt( pi * ( this->m2() + this->delta() ) ); \n            a1 *= exp( this->c1() ); \t\t\t\t\n            a2 = exp( -( this->delta() + one ) * this->shape2());\n            a2 /= this->shape2(); \t\t\t\t\t\t\n            a3 = one;\n            a = a1 + a2 + a3;\n            this->p1_ = a1 / a;\t\t\t\t\t\t\t\t\n            this->p2_ = a2 / a;\t\t\t\t\t\t\t\t\t\t\t\t\n            this->p3_ = a3 / a;\t\t\t\t\t\t\t\t\t\t\t\t\n\n\t\t\t// Reconciliation with Fortran code\n            // RL\t\t\t\t\tm1\n            // TWO\t\t\t\t\tm2\n\t\t\t// CON \t\t\t\t\tc1\n            // D \t\t\t\t\tdelta\n            // D2\t\t\t\t\tdelta + m2\n\t\t\t// D3 \t\t\t\t\t1 / shape2\n            // STDDEV \t\t\t\tsd1\n            // SUM \t\t\t\t\ta1 + a2 + a3\n            // PBODY \t\t\t\tp3 = a3/(a+a2+a3) \n\t\t\t// PTAIL \t\t\t\tp2 + p3\n\n        }\n\n\t\tstd::ostream& parameters_description(std::ostream& os)const{\n        \treturn os \n                << '('\n                << \"m1 = \" \t\t<< this->m1()\n                << ','\n                << \" m2 = \"\t\t<< this->m2()\n                << ','\n                << \" delta = \" \t<< this->delta()\n                << ','\n                << \" loc1 = \"\t<< loc1()\n                << ','\n                << \" sd1 = \" \t<< this->sd1()\n                << ','\n                << \" shape2 = \"\t<< this->shape2()\n                << ','\n                << \" c1 = \"\t\t<< this->c1()\n                << ','\n                << \" p1 = \"\t\t<< this->p1()\n                << ','\n                << \" p2 = \"\t\t<< this->p2()\n                << ','\n                << \" p3 = \"\t\t<< this->p3()\n                << ')';\n        }\n\n\t\tconst T& m1()const{ return this->m1_; }\n\t\tconst T& m2()const{ return this->m2_; }\n\t\tconst T& delta()const{ return this->delta_; }\n\t\tstatic T loc1(){ return -one/two; }\n\t\tconst T& sd1()const{ return this->sd1_; }\n\t\tconst T& shape2()const{ return this->shape2_; }\n        const T& c1()const{ return this->c1_; }\n\t\tconst T& p1()const{ return this->p1_; }\n\t\tconst T& p2()const{ return this->p2_; }\n\t\tconst T& p3()const{ return this->p3_; }\n\n\t\tprivate:\n        T inv_m1_;\n\t\tT m1_;\n\t\tT m2_;\t\t\t\n        T delta_;\t\t\n\t\tT sd1_;\t\t\n\t\tT shape2_;\t\t\n  \n        T c1_;\t\t\t\n        T p1_;\t\t\t\n        T p2_;\t\t\n\t\tT p3_;\n\n    };\n\n    template<typename Int,typename T,typename P,typename IntT>\n    const T parameters<Int,T,P,IntT>::pi = boost::math::constants::pi<T>();\n\n    template<typename Int,typename T,typename P,typename IntT>\n    const T parameters<Int,T,P,IntT>::one = IntT::convert( 1 );\n\n    template<typename Int,typename T,typename P,typename IntT>\n    const T parameters<Int,T,P,IntT>::two = IntT::convert( 2 );\n\n    template<typename Int,typename T,typename P,typename IntT>\n    const T parameters<Int,T,P,IntT>::eps \n        = boost::numeric::bounds<T>::smallest();\n\n}// devroye\n}// poisson\n}// random\n}// boost\n\n#endif\n", "meta": {"hexsha": "aceceaa2d3a4503df0c20addeec49f29ea4fc9ed", "size": 4930, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/poisson_ext/devroye/crtp/parameters.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": "random/boost/random/poisson_ext/devroye/crtp/parameters.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": "random/boost/random/poisson_ext/devroye/crtp/parameters.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.3108108108, "max_line_length": 78, "alphanum_fraction": 0.4468559838, "num_tokens": 1312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.812867299704166, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5493069358501455}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2009 Jose Aparicio\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#ifndef recursive_cdo_engine_hpp\n#define recursive_cdo_engine_hpp\n\n#include <ql/math/integrals/gaussianquadratures.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/matrixutilities/factorreduction.hpp>\n#include <ql/experimental/credit/syntheticcdoengines.hpp>\n#include <ql/experimental/credit/onefactorgaussiancopula.hpp>\n#include <ql/experimental/credit/onefactorstudentcopula.hpp>\n#include <boost/bind.hpp>\n#include <map>\n#include <algorithm>\n\nnamespace QuantLib {\n\n    /*! Recursive STCDO pricing for a heterogeneous pool of names. The pool\n        names are heterogeneous in their default probabilities, notionals\n        and recovery rates. Correlations are pairwise. The recursive pricing\n        algorithm used here is described in Andersen, Sidenius and Basu;\n        \"All your hedges in one basket\", Risk, November 2003, pages 67-72\n\n        Notice that using copulas other than Gaussian it is only an\n        approximation (see remark on p.68).\n    */\n    template <class CDOEngine, class copulaT>\n    class RecursiveCdoEngine : public CDOEngine {\n      public:\n        // Base constructors call default Handle constructor, the copula is to\n        // be relinked by template partial specializations on the copula type\n\n        //! Single correlation construction\n        RecursiveCdoEngine(const Handle<Quote>& correl,\n                           Size nbuckets  = 1,\n                           Size quadOrder = 20)\n        : correlQuote_(correl), copula_(), nBuckets_(nbuckets),\n          integral_(quadOrder), wk_()\n        {\n            this->registerWith(correl);\n        }\n\n        //! Correlation name to name single factor construction\n        RecursiveCdoEngine(const Handle<Quote>& correl,\n                           const Matrix& correlMtrx,\n                           Size nbuckets  = 1,\n                           Size quadOrder = 20)\n        : correlQuote_(correl), copula_(), nBuckets_(nbuckets),\n          integral_(quadOrder), wk_(),\n          oneFactorCorrels_(factorReduction(correlMtrx))\n        {\n            // at least\n            QL_REQUIRE(!oneFactorCorrels_.empty(),\n                \"Invalid correlation parameter matrix.\");\n        }\n      protected:\n        void initialize() const;\n      private:\n        //! Weights the conditional portfolio loss by the mkt factor\n        //    distribtion\n        Real integratorLoss(const Date& date, Real mktFactor) const {\n            return expectedConditionalLoss(date, mktFactor) *\n               copula_->density(mktFactor);\n        }\n        //! Portfolio loss conditional to the market factor value\n        Real expectedConditionalLoss(const Date& date,\n                                     Real mktFactor) const;\n      public:\n        void update();\n\n        /*  Expected tranche Loss calculation.\n            This is computed from the first equation on page 70 (not numbered)\n            Notice that while we want to compute:\n            \\f[\n            EL(t) = \\sum_{l_k}l_k P(l;t) =\n              \\sum_{l_k}l_k \\int P(l_k;t|\\omega) d\\omega q(\\omega)\n            \\f]\n            One can invert the sumation and the integral order to:\n            \\f[\n            EL(t) = \\int\\,q(\\omega)\\,d\\omega\\,\\sum_{l_k}\\,l_k\\,P(l_k;t|\\omega) =\n              \\int\\,q(\\omega)\\,d\\omega\\,EL(t|\\omega)\n            \\f]\n            and this is the way it is integrated here. The recursion formula makes\n            it easier this way.\n        */\n        Real expectedTrancheLoss(const Date& date) const {\n            return\n                integral_(boost::bind(\n                    &RecursiveCdoEngine<CDOEngine, copulaT>::integratorLoss,\n                    this,\n                    date,\n                    _1)\n                );\n        }\n      protected:\n        const Handle<Quote> correlQuote_;\n        mutable RelinkableHandle<copulaT> copula_;\n      private:\n        // loss model descriptor members\n        Size nBuckets_;\n       const GaussHermiteIntegration integral_;\n        mutable std::vector<Real> wk_;\n        mutable Real loss_unit_;\n        //! name to name factor loadings (betas). In the single factor copula:\n        //    correl = beta * beta\n        // When constructing through a single correlation number the factor is\n        //   taken to be the positive swuare root of this number in the copula.\n        mutable std::vector<Real> oneFactorCorrels_;\n    };\n\n\n    template <class CDOEngine, class copulaT>\n    void RecursiveCdoEngine<CDOEngine, copulaT>::update() {\n        oneFactorCorrels_.clear();\n        CDOEngine::update();\n    }\n\n\n    template <class CDOEngine, class copulaT>\n    void RecursiveCdoEngine<CDOEngine, copulaT>::initialize() const {\n        wk_.clear();\n        Date today = Settings::instance().evaluationDate();\n        Date start = this->arguments_.schedule.startDate();\n        boost::shared_ptr<Basket>& basket = this->arguments_.basket;\n        /*\n          Remove defaulted names and adjust the subordination.\n        */\n        std::vector<std::string> names =\n            basket->remainingNames(start, today);\n        std::vector<Real> notionals\n            = basket->remainingNotionals(start, today);\n        Real a = basket->remainingAttachmentRatio(start, today);\n        Real d = basket->remainingDetachmentRatio(start, today);\n        const boost::shared_ptr<Pool> pool = basket->pool();\n        this->remainingBasket_ =\n            boost::shared_ptr<Basket>(new Basket(names, notionals, pool,\n                                                basket->remainingDefaultKeys(start, today),\n                                                basket->remainingRecModels(start, today),\n                                                 a, d));\n\n        this->results_.xMin = this->remainingBasket_->attachmentAmount();\n        this->results_.xMax = this->remainingBasket_->detachmentAmount();\n        this->results_.remainingNotional =\n            this->results_.xMax - this->results_.xMin;\n        //----------------------------------------------------------------\n        if(oneFactorCorrels_.empty())\n            oneFactorCorrels_ = std::vector<Real>(names.size(),\n                                    correlQuote_->value());\n        // check size of factors:\n        QL_REQUIRE(oneFactorCorrels_.size() == names.size(),\n            \"Size of matrix must match number of names in the basket.\");\n        //\n        std::vector<Real> lgdsTmp, lgds = this->remainingBasket_->LGDs();\n        lgdsTmp = lgds;\n        lgds.erase(std::remove(lgds.begin(), lgds.end(), 0.), lgds.end());\n        loss_unit_ = *(std::min_element(lgds.begin(), lgds.end()))\n            / nBuckets_;\n\n        for(Size i = 0; i<names.size(); i++)\n            wk_.push_back(std::floor(lgdsTmp[i]/loss_unit_ + .5));\n\n        // Could not check parameters at construction time because we\n        //   had no arguments yet, do it now:\n        if(oneFactorCorrels_.size() == 1)\n            oneFactorCorrels_ =\n                std::vector<Real>(pool->size(), oneFactorCorrels_[0]);\n        else\n            QL_REQUIRE(oneFactorCorrels_.size() == this->remainingBasket_->size(),\n                \"Incompatible correl matrix, pool size.\");\n        //----------------------------------------------------------------\n        const std::vector<Date>& dates = this->arguments_.schedule.dates();\n        for (Size i = 0; i < dates.size(); i++) {\n            if (dates[i] <= today)\n                this->results_.expectedTrancheLoss.push_back(0.0);\n            else {\n                Real L = expectedTrancheLoss(dates[i]);\n                this->results_.expectedTrancheLoss.push_back(L);\n            }\n        }\n\n    }\n\n\n    //! Portfolio loss conditional to the market factor value\n    template <class CDOEngine, class copulaT>\n    Real RecursiveCdoEngine<CDOEngine, copulaT>::expectedConditionalLoss(\n                                 const Date& date,\n                                 Real mktFactor) const {\n        const std::vector<std::string>& names = this->remainingBasket_->names();\n\n        // eq. 10 p.68\n        // attainable losses distribution, recursive algorithm\n        std::vector<Probability> uncDefProb =\n            this->remainingBasket_->probabilities(date);;\n        std::map<Real, Probability> pIndepDistrib;\n        // K=0\n        pIndepDistrib.insert(std::make_pair(0., 1.));\n        for(Size iName=0; iName<names.size(); iName++) {\n\n            // to do: allow for matrix constructor and uncoment this\n            // correlQuote_->setValue(oneFactorCorrels_[iName]);\n\n            Probability pDef =\n                copula_->conditionalProbability(uncDefProb[iName],\n                                                mktFactor);\n            // iterate on all possible losses in the distribution:\n            std::map<Real, Probability> pDistTemp;\n            std::map<Real, Probability>::iterator distIt =\n                pIndepDistrib.begin();\n            while(distIt != pIndepDistrib.end()) {\n                // update prob if this name does not default\n                std::map<Real, Probability>::iterator matchIt\n                    = pDistTemp.find(distIt->first);\n                if(matchIt != pDistTemp.end()) {\n                    matchIt->second += distIt->second * (1.-pDef);\n                }else{\n                    pDistTemp.insert(std::make_pair(distIt->first,\n                        distIt->second * (1.-pDef)));\n                }\n                // and if it does\n                matchIt = pDistTemp.find(distIt->first + wk_[iName]);\n                if(matchIt != pDistTemp.end()) {\n                    matchIt->second += distIt->second * pDef;\n                }else{\n                    pDistTemp.insert(std::make_pair(\n                        distIt->first+wk_[iName], distIt->second * pDef));\n                }\n                distIt++;\n            }\n            // copy back\n            pIndepDistrib = pDistTemp;\n        }\n\n        // get the expected value subject to the value of the market\n        //   factor.\n        Real expLoss = 0.;\n        //---------------------------------------------------------------\n        /* This is the original (easy to read) loop which I have partially\n             unroll below to take profit of the fact that once we go over\n             the tranche top the loss amount is fixed:\n\n        std::map<Real, Probability>::iterator distIt =\n            pIndepDistrib.begin();\n        while(distIt != pIndepDistrib.end()) {\n            Real loss = distIt->first * loss_unit_\n                                ;\n            loss = std::max(std::min(loss,\n                results_.xMax)-results_.xMin, 0.);\n            expLoss += loss * distIt->second;\n            distIt++;\n        }\n        return expLoss ;\n        */\n        //---------------------------------------------------------------\n        Real relativeMax = this->results_.xMax / loss_unit_;\n        Real relativeMin = this->results_.xMin / loss_unit_;\n        Size relativeMinIdx = std::floor(relativeMin);\n        std::map<Real, Probability>::iterator\n            distIt = pIndepDistrib.lower_bound(relativeMinIdx),\n            itTop  = pIndepDistrib.lower_bound(relativeMax);\n        for(; distIt != itTop; distIt++)\n            expLoss += std::max(std::min(distIt->first, relativeMax)\n                                -relativeMin, 0.) * distIt->second;\n        Real sumProbs = 0.;\n        for(;distIt != pIndepDistrib.end(); distIt++)\n            sumProbs += distIt->second;\n        return expLoss * loss_unit_ + this->results_.remainingNotional * sumProbs;\n    }\n\n\n\n    // Partial specializations on the copula type. Kind\n    //   of template virtual constructions. Allows to own the correlation\n    //   quote and the copula for each specific copula type. It only\n    //   needs to know its particular copula constructor.\n    // These and the base correlation pricers use a unifactorial copula\n    //   which needs to be modified for different parameters of the\n    //   correlation per name to name if theres such an structure or\n    //   because the correlation parameter has got a time or/and loss\n    //   level surface.\n    //\n    // TO do: Correlation matrix constructors.\n\n    //! Specialization for Gaussian copula, the integration still remains\n    //    to be defined by the user out of the available ones in\n    //    syntheticcdoengines.\n    template <class CDOEngine>\n    class GaussianRecursiveCdoEngine : public\n        RecursiveCdoEngine<CDOEngine, OneFactorGaussianCopula> {\n      public:\n        //! quote constructor.\n        GaussianRecursiveCdoEngine(\n            const Handle<Quote>& correlQuote,\n            Size nbuckets  = 1,\n            Size quadOrder = 12,\n            Real maxval    = 5.,\n            Size steps     = 50)\n            :\n            RecursiveCdoEngine<CDOEngine, OneFactorGaussianCopula>(correlQuote,\n                    nbuckets, quadOrder) {\n                this->copula_.linkTo(boost::shared_ptr<OneFactorGaussianCopula>(\n                new OneFactorGaussianCopula(correlQuote,  maxval, steps)), true);\n        }\n    };\n\n    template <class CDOEngine>\n    class StudentRecursiveCdoEngine : public\n        RecursiveCdoEngine<CDOEngine, OneFactorStudentCopula> {\n      public:\n        //! quote constructor.\n        StudentRecursiveCdoEngine(\n            const Handle<Quote>& correlQuote,\n            Size nz,\n            Size nm,\n            Size nbuckets  = 1,\n            Size quadOrder = 12,\n            Real maxval    = 5.,\n            Size steps     = 50)\n            :\n            RecursiveCdoEngine<CDOEngine, OneFactorStudentCopula>(correlQuote,\n                    nbuckets, quadOrder) {\n                this->copula_.linkTo(boost::shared_ptr<OneFactorStudentCopula>(\n                new OneFactorStudentCopula(correlQuote, nz, nm, maxval, steps)), true);\n        }\n    };\n\n\n\n    typedef GaussianRecursiveCdoEngine<MidPointCDOEngine> GaussRecCDOEngine;\n    typedef StudentRecursiveCdoEngine<MidPointCDOEngine>  StudentRecCDOEngine;\n\n}\n\n#endif\n", "meta": {"hexsha": "876d33a2d437fd5e4c443b4fac10cef1df8d5641", "size": 14752, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/credit/recursivecdoengine.hpp", "max_stars_repo_name": "quantosaurosProject/quantLib", "max_stars_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "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": "ql/experimental/credit/recursivecdoengine.hpp", "max_issues_repo_name": "quantosaurosProject/quantLib", "max_issues_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/credit/recursivecdoengine.hpp", "max_forks_repo_name": "quantosaurosProject/quantLib", "max_forks_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-29T05:44:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:44:27.000Z", "avg_line_length": 41.9090909091, "max_line_length": 91, "alphanum_fraction": 0.5797180043, "num_tokens": 3250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.5492754549251732}}
{"text": "#include <iostream>\n#include <fstream>\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 <vector>\n#include <cmath>\n\n#include \"NRGclasses.hpp\"\n#include \"NRGfunctions.hpp\"\n#include \"TwoChQS.hpp\"\n\n#ifndef pi\n#define pi 3.141592653589793238462643383279502884197169\n#endif\n\n\n\n\nint main (int argc, char* argv[]){\n\n  //char ModelOption[]=\"Anderson\";\n  //int ModelNo=0;\n\n  // command-line model options\n#include\"ModelOpt.cpp\"\n\n  CNRGarray Aeig(2);\n\n  CNRGbasisarray AeigCut(2);\n\n  CNRGbasisarray Abasis(2);\n\n  CNRGbasisarray SingleSite(3);\n\n  CNRGmatrix* MatArray;\n  int NumNRGarrays=2;\n  // MatArray 0 is nd\n  // MatArray 1 is cd\n\n\n  // Thermodynamics\n  CNRGthermo Suscep;\n  CNRGthermo Entropy;\n\n\n  // STL vector\n\n  CNRGmatrix Qm1fNQ[2];\n\n  CNRGmatrix MQQp1;\n\n  double U,ed,Gamma1,Gamma2;\n  vector<double> Params;\n  double Lambda;\n  double HalfLambdaFactor;\n  double Dband=1.0;\n  int calcdens;\n\n  double DN=0.0;\n  double TM=0.0;\n  double betabar=0.727;\n  double Temp=0.0;\n  double Sus=0.0;\n  //vector<double> SuscepChain;\n  char arqSus[32],arqname[32];\n\n\n\n  double chi_m1,chi_N[2];\n  double daux[4];\n\n  int Nsites=0,Nsitesmax=2;\n\n  int Ncutoff=700;\n  int UpdateBefCut=0;\n  int auxIn;\n\n  // outstream\n  ofstream OutFile;\n  // instream\n  ifstream InFile;\n\n\n  int ii,jj,i1,i2;\n\n  // STL iterator:\n\n  vector<double>::iterator diter;\n\n  // Phonon\n  // Test!! Remove later\n  double Nph=1.0;\n  double w0=0.2;\n  double lambda=0.4;\n  double alpha=0.4;\n  double tp=0.2;\n\n\n  ///            ///\n  /// Begin code ///\n  ///            ///\n  U=0.5;\n  ed=-0.5*U;\n  Gamma1=0.0282691;\n  Gamma2=0.0;\n  Lambda=2.5;\n  \n  // Steps: Input parameters\n  InFile.open(\"nrg_input_TwoCh.dat\");\n  if (InFile.is_open())\n    {\n      InFile >> Nsitesmax;\n      InFile >> Ncutoff;\n      InFile >> U;\n      InFile >> Gamma1;\n      InFile >> Gamma2;\n      InFile >> ed;\n      InFile >> Lambda;\n      InFile >> Dband;\n      InFile >> auxIn;\n      InFile >> UpdateBefCut;\n      InFile >> calcdens;\n    }\n  else cout << \"can't open nrg_input_TwoCh.dat\" << endl;\n\n  InFile.close();\n\n  if (ModelNo==4)\n    {\n      InFile.open(\"Input_Phonon.dat\");\n      if (InFile.is_open())\n\t{\n\t  InFile >> Nph;\n\t  InFile >> w0;\n\t  InFile >> lambda;\n\t  InFile >> tp;\n\t  InFile >> alpha;\n\t}\n      else cout << \"can't open Input_Phonon.dat\" << endl;\n      InFile.close();\n      Gamma1=pi*tp*tp;\n      Gamma2=alpha*alpha*Gamma1;\n    }\n  // end if phonon\n\n\n  ///////////////////////////\n  ///////////////////////////\n\n  // New stuff\n   strcpy(Suscep.ArqName,\"SuscepImp2Ch_25_726.dat\");\n   strcpy(Suscep.ChainArqName,\"SuscepChain2Ch.dat\");\n   Suscep.Calc=CalcSuscep;\n  \n   strcpy(Entropy.ArqName,\"EntropyImp2Ch_25_726.dat\");\n   strcpy(Entropy.ChainArqName,\"EntropyChain2Ch.dat\");\n   Entropy.Calc=CalcEntropy;\n\n   // Chain model\n   if(ModelNo==3) calcdens=3;\n\n   if (calcdens==2)\n     {\n       Suscep.CalcChain=false;\n       Entropy.CalcChain=false;\n       Suscep.Nsite0Chain=0; // Anderson chains\n       Entropy.Nsite0Chain=0; // Anderson chains\n       \n       if ( (!FileExists(Suscep.ChainArqName))||\n\t    (!FileExists(Entropy.ChainArqName)) )\n\t {\n\t   cout << \" Can't find chain files: \" << endl \n\t\t<< \"   \" << Suscep.ChainArqName << endl\n\t\t<< \"   \" << Entropy.ChainArqName << endl;\n\t   cout << \" Exiting... \" << endl;\n\t   exit(0);\n\t }\n       else\n\t cout << \" Found files \" \n\t      << Suscep.ChainArqName << \", \" \n\t      << Entropy.ChainArqName \n\t      << endl;\n     }\n   if (calcdens==3)\n     {\n       //strcpy(arqSus,\"SuscepChain.dat\");\n       Suscep.CalcChain=true;\n       Entropy.CalcChain=true;\n       if ( (FileExists(Suscep.ChainArqName))||\n\t    (FileExists(Entropy.ChainArqName)) )\n\t {\n\t   cout << \" Error: Chain files already exist: \" << endl\n\t\t<< \"   \" << Suscep.ChainArqName << endl\n\t\t<< \"   \" << Entropy.ChainArqName << endl;\n\t   cout << \" Not rewriting. Exiting... \" << endl;\n\t   exit(0);\n\t }\n       U=0.0;ed=0.0;Gamma1=0.0;Gamma2=0.0;\n     }\n\n  ///////////////////////////\n  ///////////////////////////\n\n  HalfLambdaFactor=0.5*(1.0+(1.0/Lambda));\n  chi_m1=sqrt(2.0*Gamma1/pi)/(sqrt(Lambda)*HalfLambdaFactor);\n\n  double U_tilde=0.5*U/HalfLambdaFactor;\n  double ed_tilde=ed/HalfLambdaFactor;\n  double Gamma1_tilde=Gamma1*(2.0/pi)/(HalfLambdaFactor*HalfLambdaFactor);\n  double Gamma2_tilde=Gamma2*(2.0/pi)/(HalfLambdaFactor*HalfLambdaFactor);\n\n\n  OutFile.open(\"NRG_in.txt\");\n  OutFile << \"Begin NRG 2-ch calculation\" << endl;\n  OutFile << \" Model : \" << ModelOption << endl;\n  OutFile << \" Nsitesmax    = \" << Nsitesmax-1 << endl;\n  OutFile << \" Ncutoff      = \" << Ncutoff << endl;\n  OutFile << \" U            = \" << U << endl;\n  OutFile << \" Gamma1        = \" << Gamma1 << endl;\n  OutFile << \" Gamma2        = \" << Gamma2 << endl;\n  OutFile << \" ed           = \" << ed << endl;\n  OutFile << \" Lambda       = \" << Lambda << endl;\n  OutFile << \" Dband        = \" << Dband << endl;\n  OutFile << \" UpdateBefCut = \" << UpdateBefCut << endl;\n  OutFile << \" calcdens     = \" << calcdens << endl;\n  OutFile << \"=================================\" << endl;\n  OutFile << \"U~ = \" << U_tilde << endl;\n  OutFile << \"ed~ = \" <<  ed_tilde << endl;\n  OutFile << \"Gamma1~ = \" <<  Gamma1_tilde<< endl;\n  OutFile << \"Gamma2~ = \" <<  Gamma2_tilde<< endl;\n  OutFile << \"=================================\" << endl;\n  if (ModelNo==4)\n    {\n      OutFile << \"Nph = \" <<  Nph << endl;\n      OutFile << \"w0 = \" <<  w0 << endl;\n      OutFile << \"lambda = \" <<  lambda << endl;\n      OutFile << \"tp = \" <<  tp << endl;\n      OutFile << \"alpha = \" <<  alpha << endl;\n      OutFile << \"chi_S_tilde = \" <<  sqrt(Gamma1_tilde) << endl;\n      OutFile << \"chi_A_tilde = \" <<  alpha*sqrt(Gamma1_tilde) << endl;\n      OutFile << \"=================================\" << endl;\n    }\n  OutFile.close();\n\n\n\n  // Define H0 (impurity + 1s site)\n  // Output:\n  //       Aeig,\n  //       fd_{1sigma} and fd_{2sigma} matrix elements\n  //\n\n  // Set single site (use pointers in the subroutines!!)\n\n  TwoChQS_SetSingleSite(&SingleSite);\n\n  Params.push_back(U_tilde/sqrt(Lambda));\n  Params.push_back(ed_tilde/sqrt(Lambda));\n  Params.push_back(sqrt(Gamma1_tilde/Lambda));\n  Params.push_back(sqrt(Gamma2_tilde/Lambda));\n\n  Nsites=0;\n  DN=HalfLambdaFactor*pow(Lambda,(-(Nsites-1)/2.0) );\n  TM=DN/betabar;\n  cout << \"DN = \" << DN << \"  TM = \" << TM << endl;\n\n\n\n  switch (ModelNo)\n    {\n    case 0 :\n      TwoChQS_SetH0Anderson(Params,&SingleSite,&Aeig,&Abasis);\n      Suscep.dImpValue=1.0/8.0;\n      Entropy.dImpValue=2.0*log(2.0);\n      break;\n\n    case 1 :\n      cout << \" Testing 2ch Kondo model. \" << endl;\n      Params.clear();\n      Params.push_back(Gamma1);\n      Params.push_back(Gamma2);\n      TwoChQS_SetH0Kondo(Params,&SingleSite,&Aeig,&Abasis,MatArray);\n      Suscep.dImpValue=1.0/4.0;\n      Entropy.dImpValue=log(2.0);\n      break;\n\n    case 3 :\n      TwoChQS_SetH0Chain(Params,&SingleSite,&Aeig,&Abasis);\n      Suscep.dImpValue=0.0;\n      Entropy.dImpValue=0.0; // Check this!!\n      Suscep.CalcChain=true;\n      Entropy.CalcChain=true;\n      break;\n    case 4 :\n      Params.push_back(w0); //\n      Params.push_back(lambda); //\n      Params.push_back(alpha); //\n      Params.push_back(Nph); //\n      // Using the untransformed Hamiltonian\n      //TwoChQS_SetH0CMphononwTransf(Params,&SingleSite,&Aeig,&Abasis,MatArray);\n      TwoChQS_SetH0CMphonon(Params,&SingleSite,&Aeig,&Abasis,MatArray);\n      // Qm1fQ needs special updates\n      for (int ich=0;ich<=1;ich++)\n\t{\n\t  Qm1fNQ[ich].NeedOld=false;\n\t  Qm1fNQ[ich].CheckForMatEl=TwoChQS_cd_check;\n\t}\n\n      Qm1fNQ[0].CalcMatEl=TwoChQS_cd_ich1_Phonon_MatEl;\n      Qm1fNQ[1].CalcMatEl=TwoChQS_cd_ich2_Phonon_MatEl;\n      /////////\n      Suscep.dImpValue=0.0;\n      Entropy.dImpValue=0.0; // Check this!!\n      strcpy(Suscep.ArqName,\"SuscepImp2Ch_Phonon.dat\");\n      strcpy(Entropy.ArqName,\"EntropyImp2Ch_Phonon.dat\");\n      // Update with a new scheme\n      cout << \" Updating! \" << endl;\n      AeigCut.CNRGbasisarray::ClearAll();\n      AeigCut=CutStates(&Aeig, Ncutoff);\n      UpdateMatrices(&SingleSite,&AeigCut, \n\t\t     &Abasis,&Qm1fNQ[0], 2);\n\n      break;\n    default :\n      cout << \" Model not implemented. Exiting... \" << endl;\n      exit(0);\n      break;\n    }\n  //end switch models\n\n  Aeig.PrintEn();\n\n  if (ModelNo!=4){TwoChQS_UpdateQm1fQ(&SingleSite,&Aeig,&Abasis,Qm1fNQ);}\n\n  cout << \" f0_ch1 : \" << endl;\n  //Qm1fNQ[0].PrintAllBlocks();\n  Qm1fNQ[0].PrintMatBlock(1,3);\n  Qm1fNQ[0].PrintMatBlock(2,3);\n  cout << \" f0_ch1 : \" << endl;\n  //Qm1fNQ[1].PrintAllBlocks();\n  Qm1fNQ[1].PrintMatBlock(1,3);\n  Qm1fNQ[1].PrintMatBlock(2,3);\n\n\n  // Calculate Susceptibility at Nsites=0!\n\n  if ( (calcdens==2)||(calcdens==3) )\n    {\n      TM=DN/betabar;\n      Params.clear();\n      Params.push_back(betabar);\n\n      Suscep.ReadNChainValue(Nsites,0);\n      Suscep.AddValue(Params,&Aeig,1,true,TM);\n      Suscep.SaveNValue(Nsites,0);\n      \n      Entropy.ReadNChainValue(Nsites,0);\n      Entropy.AddValue(Params,&Aeig,1,true,TM);\n      Entropy.SaveNValue(Nsites,0);\n\n    }\n  //end if calcdens=2 or 3\n\n  //TwoChQS_UpdateQm1fQ(&SingleSite,&Aeig,&Abasis,Qm1fNQ);\n\n\n\n  // Check Matrix\n//    for (int ich=1;ich<=2;ich++)\n//      {\n//        cout << \" Printing Qm1fQ channel: \" << ich << endl;\n//        for (int ibl=0; ibl<Qm1fNQ[ich-1].NumMatBlocks();ibl++)\n//  \t{\n//  \t  Qm1fNQ[ich-1].PrintMatBlock(ibl);\n//  \t}\n//      }\n\n  // Loop on Nsites: start from Nsites=0 (imp+1)\n  //\n\n  Nsites=1;\n  while (Nsites<=Nsitesmax)\n    {\n\n      DN=HalfLambdaFactor*pow(Lambda,(-(Nsites-1)/2.0) );\n      TM=DN/betabar;\n      cout << \"DN = \" << DN << \"TM = \" << TM << endl;\n\n      // 0 - Update chi_N, eps_N\n\n      daux[0]=(double)( 1.0-pow(Lambda,(-Nsites)) );\n      daux[1]=(double)sqrt( 1.0-pow(Lambda,-(2*Nsites-1)) );\n      daux[2]=(double)sqrt( 1.0-pow(Lambda,-(2*Nsites+1)) );  \n      daux[3]=0.5*(1.0+(1.0/Lambda))*(double)sqrt(Lambda);\n\n      chi_N[0]=daux[0]/(daux[1]*daux[2]);\n      chi_N[1]=daux[0]/(daux[1]*daux[2]);\n\n      cout << \"chi_N = \" << chi_N[0] << \"  \" << chi_N[1] << endl;\n\n\n      cout << \"Nsites = \" << Nsites << endl;\n      cout << \"BEG Eig Nshell = \" << Aeig.Nshell << endl;\n\n      // 1 - Eliminate states and Build Abasis\n\n      cout << \" Nstates: \";\n      cout <<  Aeig.Nstates() << endl;\n\n\n      cout << \"Cutting states...\" << endl;\n      AeigCut.CNRGbasisarray::ClearAll();\n      AeigCut=CutStates(&Aeig, Ncutoff);\n\n      cout << \"... done cutting states.\" << endl;\n\n      // Calculate new matrix elements using the CUT basis:\n      // update Qm1fNQ, Qm1cdQ, etc.\n\n      if ( (UpdateBefCut==0)&&(Nsites>1) )\n\t{\n\t  cout << \"Updating matrices after cutting... \" << endl;    \n\t  TwoChQS_UpdateMatrixAfterCutting(&SingleSite,\n\t  \t\t\t\t    &AeigCut, &Abasis, Qm1fNQ, &MQQp1);\n\t  cout << \"... done updating matrices. \" << endl;\n\t}\n\n      // Spec density calculation, other similar things woudl go HERE\n\n      // This is where the loop really begins...\n\n      QS_BuildBasis(&AeigCut,&Abasis,&SingleSite,UpdateBefCut);\n\n\n      cout << \"No blocks = \" << Abasis.NumBlocks() << endl;\n      \n      cout << \"No states = \" << Abasis.Nstates() << endl;\n\n      //Abasis.PrintAll();\n\n\n      // 2 - Build and diagonalize H_N+1\n\n      Params.clear();\n      Params.push_back(chi_N[0]);\n      Params.push_back(chi_N[1]);\n      Params.push_back(Lambda);\n\n      cout << \"Diagonalizing HN... \" << endl;    \n\n      TwoChQS_DiagHN(Params,&Abasis,&SingleSite,Qm1fNQ,&Aeig);\n\n      Aeig.PrintEn();\n\n      cout << \"..done diagonalizing HN. \" << endl;    \n\n      // 3 - Update Qm1f1NQ, Qm1f2Q, Qm1cdQ, etc.\n\n      if ( (UpdateBefCut==1)&&(Nsites<Nsitesmax) )\n\t{\n\t  cout << \"Updating matrices before cutting... \" << endl;\n\t  TwoChQS_UpdateQm1fQ(&SingleSite,&Aeig,&Abasis,Qm1fNQ);\n\t  cout << \"... done updating matrices. \" << endl;\n\n\t}\n\n\n      // Calculate Susceptibility/Entropy\n\n      if ( (calcdens==2)||(calcdens==3) )\n\t{\n\t  TM=DN/betabar;\n\t  Params.clear();\n\t  Params.push_back(betabar);\n\n\t  Suscep.ReadNChainValue(Nsites,0);\n\t  Suscep.AddValue(Params,&Aeig,1,true,TM);\n\t  Suscep.SaveNValue(Nsites,0);\n      \n\t  Entropy.ReadNChainValue(Nsites,0);\n\t  Entropy.AddValue(Params,&Aeig,1,true,TM);\n\t  Entropy.SaveNValue(Nsites,0);\n\t}\n  //end if calcdens=2 or 3\n\n\n      // 4 - Update Nsites\n\n      Nsites++;\n\n    }\n \n  cout << \"=== Calculation Finished! ==== \"<< endl;\n  OutFile.open(\"NRG_end.txt\");\n  OutFile << \"END NRG calculation\" << endl;\n  OutFile.close();\n  \n  cout << \"Calling destructors \" << endl;\n\n}\n//END code\n\n\n\n///////////////////////\n//       else\n// \t{\n// \t  while (!InFile.eof())\n// \t    {\n// \t      InFile >> Temp >> daux[0] >> daux[0] >> Sus;\n// \t      SuscepChain.push_back(Sus);\n// \t    }\n// \t  SuscepChain.pop_back();\n// \t  if (SuscepChain.size()<Nsitesmax-1)\n// \t    {\n// \t      cout << \"Nsuscep = \" << SuscepChain.size() << \" Nsitesmax = \" << Nsitesmax << endl;\n// \t      cout << \" Longer SuscepChain needed! Doing it all over...\" << endl;\n// \t      SuscepChain.clear();\n// \t      strcpy(arqSus,\"SuscepChain.dat\");\n// \t      calcdens=3;\n// \t    } \n// \t}\n//       InFile.close();\n//////////////////////////\n\n      //SuscepChain.clear();\n//       strcpy(arqSus,\"SuscepImp_25_726.dat\");\n  \n//       strcpy(arqname,\"SuscepChain.dat\");\n//       InFile.open(arqname);\n//       if (InFile.fail())\n// \t{\n// \t  cout << \"Can't find \" << arqname << endl;\n// \t  strcpy(arqSus,\"SuscepChain.dat\");\n// \t  calcdens=3;\n// \t}\n\n//       Sus=CalcSuscep(Params,&Aeig,1,true);\n//       double Sus0=0.0;\n//       int nlines=0;\n//       if (calcdens==2)\n// \t{\n// \t  InFile.open(\"SuscepChain.dat\");\n// \t  InFile.clear(); \n// \t  InFile.seekg(0, ios::beg); // rewind\n// \t  if (InFile.fail())\n// \t    {\n// \t      cout << \"Can't open  SuscepChain.dat\"<< endl;\n// \t    }\n// \t  else\n// \t    {\n// \t      while ( (!InFile.eof())&&(nlines<=Nsites) ) \n// \t\t{\n// \t\t  InFile >> daux[0] >> daux[0] >> daux[0] >> Sus0;\n// \t\t  nlines++;\n// \t\t}\n// \t    }\n// \t  InFile.close();\n// \t}\n//        else \n// \tSus-=1.0/8.0; // exclude dot site in the chain.\n//       if (Nsites==0) OutFile.open(arqSus);\n//       else OutFile.open(arqSus,ofstream::app);\n//       OutFile.precision(20);\n//       OutFile << scientific << TM << \" \" << Sus << \" \" << Sus0 << \" \" << Sus-Sus0 << endl;\n//       OutFile.close();\n\n\n// \t  Sus=CalcSuscep(Params,&Aeig,1,true);\n// \t  double Sus0=0.0;\n// \t  int nlines=0;\n// \t  // Gets SuscepChain iteration by iteration\n// \t  if (calcdens==2)\n// \t    {\n// \t      InFile.open(\"SuscepChain.dat\");\n// \t      InFile.clear(); \n// \t      InFile.seekg(0, ios::beg); // rewind\n// \t      if (InFile.fail())\n// \t\t{\n// \t\t  cout << \"Can't find \" << arqname << endl;\n// \t\t}\n// \t      else\n// \t\t{\n// \t\t  while ( (!InFile.eof())&&(nlines<=Nsites) ) \n// \t\t    {\n// \t\t      InFile >> daux[0] >> daux[0] >> daux[0] >> Sus0;\n// \t\t      nlines++;\n// \t\t    }\n// \t\t}\n// \t      InFile.close();\n// \t    }\n// \t  //if (calcdens==2) Sus0=SuscepChain[Nsites];\n// \t  else Sus-=1.0/8.0; // exclude dot site in the chain.\n\n// \t  if (Nsites==0) OutFile.open(arqSus);\n// \t  else OutFile.open(arqSus,ofstream::app);\n// \t  OutFile.precision(20);\n// \t  OutFile << scientific << TM << \" \" << Sus << \" \" << Sus0 << \" \" << Sus-Sus0 << endl;\n// \t  OutFile.close();\n", "meta": {"hexsha": "483c1e908f24474e19bcbdf1c51bc2fac836c947", "size": 15134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TwoChQS/TwoChQS.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/TwoChQS/TwoChQS.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TwoChQS/TwoChQS.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["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.0562913907, "max_line_length": 93, "alphanum_fraction": 0.5627064887, "num_tokens": 5036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5492342424671384}}
{"text": "// Copyright 2017 Nicolas Mellado\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// Authors: Dror Aiger, Yoni Weill, Nicolas Mellado\n//\n// This file is part of the implementation of the 4-points Congruent Sets (4PCS)\n// algorithm presented in:\n//\n// 4-points Congruent Sets for Robust Surface Registration\n// Dror Aiger, Niloy J. Mitra, Daniel Cohen-Or\n// ACM SIGGRAPH 2008 and ACM Transaction of Graphics.\n//\n// Given two sets of points in 3-space, P and Q, the algorithm applies RANSAC\n// in roughly O(n^2) time instead of O(n^3) for standard RANSAC, using an\n// efficient method based on invariants, to find the set of all 4-points in Q\n// that can be matched by rigid transformation to a given set of 4-points in P\n// called a base. This avoids the need to examine all sets of 3-points in Q\n// against any base of 3-points in P as in standard RANSAC.\n// The algorithm can use colors and normals to speed-up the matching\n// and to improve the quality. It can be easily extended to affine/similarity\n// transformation but then the speed-up is smaller because of the large number\n// of congruent sets. The algorithm can also limit the range of transformations\n// when the application knows something on the initial pose but this is not\n// necessary in general (though can speed the runtime significantly).\n\n// Home page of the 4PCS project (containing the paper, presentations and a\n// demo): http://graphics.stanford.edu/~niloy/research/fpcs/fpcs_sig_08.html\n// Use google search on \"4-points congruent sets\" to see many related papers\n// and applications.\n\n#include \"super4pcs/algorithms/match4pcsBase.h\"\n#include \"super4pcs/shared4pcs.h\"\n#include \"super4pcs/sampling.h\"\n#include \"super4pcs/accelerators/kdtree.h\"\n\n#include <vector>\n#include <atomic>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nconst double pi = std::acos(-1);\n\n\n\n// Compute the closest points between two 3D line segments and obtain the two\n// invariants corresponding to the closet points. This is the \"intersection\"\n// point that determines the invariants. Since the 4 points are not exactly\n// planar, we use the center of the line segment connecting the two closest\n// points as the \"intersection\".\ntemplate < typename VectorType, typename Scalar>\nstatic Scalar\ndistSegmentToSegment(const VectorType& p1, const VectorType& p2,\n                     const VectorType& q1, const VectorType& q2,\n                     Scalar& invariant1, Scalar& invariant2) {\n\n  static const Scalar kSmallNumber = 0.0001;\n  VectorType u = p2 - p1;\n  VectorType v = q2 - q1;\n  VectorType w = p1 - q1;\n  Scalar a = u.dot(u);\n  Scalar b = u.dot(v);\n  Scalar c = v.dot(v);\n  Scalar d = u.dot(w);\n  Scalar e = v.dot(w);\n  Scalar f = a * c - b * b;\n  // s1,s2 and t1,t2 are the parametric representation of the intersection.\n  // they will be the invariants at the end of this simple computation.\n  Scalar s1 = 0.0;\n  Scalar s2 = f;\n  Scalar t1 = 0.0;\n  Scalar t2 = f;\n\n  if (f < kSmallNumber) {\n    s1 = 0.0;\n    s2 = 1.0;\n    t1 = e;\n    t2 = c;\n  } else {\n    s1 = (b * e - c * d);\n    t1 = (a * e - b * d);\n    if (s1 < 0.0) {\n      s1 = 0.0;\n      t1 = e;\n      t2 = c;\n    } else if (s1 > s2) {\n      s1 = s2;\n      t1 = e + b;\n      t2 = c;\n    }\n  }\n\n  if (t1 < 0.0) {\n    t1 = 0.0;\n    if (-d < 0.0)\n      s1 = 0.0;\n    else if (-d > a)\n      s1 = s2;\n    else {\n      s1 = -d;\n      s2 = a;\n    }\n  } else if (t1 > t2) {\n    t1 = t2;\n    if ((-d + b) < 0.0)\n      s1 = 0;\n    else if ((-d + b) > a)\n      s1 = s2;\n    else {\n      s1 = (-d + b);\n      s2 = a;\n    }\n  }\n  invariant1 = (std::abs(s1) < kSmallNumber ? 0.0 : s1 / s2);\n  invariant2 = (std::abs(t1) < kSmallNumber ? 0.0 : t1 / t2);\n\n  return ( w + (invariant1 * u) - (invariant2 * v)).norm();\n}\n\n\nnamespace GlobalRegistration{\n\nMatch4PCSBase::Match4PCSBase(  const Match4PCSOptions& options\n                             , const Utils::Logger& logger\n#ifdef SUPER4PCS_USE_OPENMP\n                             , const int omp_nthread_congruent\n#endif\n                               )\n  :number_of_trials_(0)\n  , max_base_diameter_(-1)\n  , P_mean_distance_(1.0)\n  , best_LCP_(0.0)\n  , options_(options)\n  , randomGenerator_(options.randomSeed)\n  , logger_(logger)\n#ifdef SUPER4PCS_USE_OPENMP\n  , omp_nthread_congruent_(omp_nthread_congruent)\n#endif\n{\n  base_3D_.resize(4);\n}\n\nMatch4PCSBase::~Match4PCSBase(){}\n\nMatch4PCSBase::Scalar\nMatch4PCSBase::MeanDistance() {\n  const Scalar kDiameterFraction = 0.2;\n  using RangeQuery = GlobalRegistration::KdTree<Scalar>::RangeQuery<>;\n\n  int number_of_samples = 0;\n  Scalar distance = 0.0;\n\n  for (size_t i = 0; i < sampled_P_3D_.size(); ++i) {\n\n    RangeQuery query;\n    query.sqdist = P_diameter_ * kDiameterFraction;\n    query.queryPoint = sampled_P_3D_[i].pos().cast<Scalar>();\n\n    GlobalRegistration::KdTree<Scalar>::Index resId =\n        kd_tree_.doQueryRestrictedClosestIndex(query , i);\n\n    if (resId != GlobalRegistration::KdTree<Scalar>::invalidIndex()) {\n      distance += (sampled_P_3D_[i].pos() - sampled_P_3D_[resId].pos()).norm();\n      number_of_samples++;\n    }\n  }\n\n  return distance / number_of_samples;\n}\n\n\nbool Match4PCSBase::SelectRandomTriangle(int &base1, int &base2, int &base3) {\n      int number_of_points = sampled_P_3D_.size();\n      base1 = base2 = base3 = -1;\n\n      // Pick the first point at random.\n      int first_point = randomGenerator_() % number_of_points;\n\n      const Scalar sq_max_base_diameter_ = max_base_diameter_*max_base_diameter_;\n\n      // Try fixed number of times retaining the best other two.\n      Scalar best_wide = 0.0;\n      for (int i = 0; i < kNumberOfDiameterTrials; ++i) {\n        // Pick and compute\n        const int second_point = randomGenerator_() % number_of_points;\n        const int third_point = randomGenerator_() % number_of_points;\n        const VectorType u =\n                sampled_P_3D_[second_point].pos() -\n                sampled_P_3D_[first_point].pos();\n        const VectorType w =\n                sampled_P_3D_[third_point].pos() -\n                sampled_P_3D_[first_point].pos();\n        // We try to have wide triangles but still not too large.\n        Scalar how_wide = (u.cross(w)).norm();\n        if (how_wide > best_wide &&\n                u.squaredNorm() < sq_max_base_diameter_ &&\n                w.squaredNorm() < sq_max_base_diameter_) {\n          best_wide = how_wide;\n          base1 = first_point;\n          base2 = second_point;\n          base3 = third_point;\n        }\n      }\n      return base1 != -1 && base2 != -1 && base3 != -1;\n}\n\n\n\n// Try the current base in P and obtain the best pairing, i.e. the one that\n// gives the smaller distance between the two closest points. The invariants\n// corresponding the the base pairing are computed.\nbool Match4PCSBase::TryQuadrilateral(Scalar &invariant1, Scalar &invariant2,\n                                     int& id1, int& id2, int& id3, int& id4) {\n\n  Scalar min_distance = std::numeric_limits<Scalar>::max();\n  int best1, best2, best3, best4;\n  best1 = best2 = best3 = best4 = -1;\n  for (int i = 0; i < 4; ++i) {\n    for (int j = 0; j < 4; ++j) {\n      if (i == j) continue;\n      int k = 0;\n      while (k == i || k == j) k++;\n      int l = 0;\n      while (l == i || l == j || l == k) l++;\n      double local_invariant1;\n      double local_invariant2;\n      // Compute the closest points on both segments, the corresponding\n      // invariants and the distance between the closest points.\n      Scalar segment_distance = distSegmentToSegment(\n                  base_3D_[i].pos(), base_3D_[j].pos(),\n                  base_3D_[k].pos(), base_3D_[l].pos(),\n                  local_invariant1, local_invariant2);\n      // Retail the smallest distance and the best order so far.\n      if (segment_distance < min_distance) {\n        min_distance = segment_distance;\n        best1 = i;\n        best2 = j;\n        best3 = k;\n        best4 = l;\n        invariant1 = local_invariant1;\n        invariant2 = local_invariant2;\n      }\n    }\n  }\n\n  if(best1 < 0 || best2 < 0 || best3 < 0 || best4 < 0 ) return false;\n\n  std::vector<Point3D> tmp = base_3D_;\n  base_3D_[0] = tmp[best1];\n  base_3D_[1] = tmp[best2];\n  base_3D_[2] = tmp[best3];\n  base_3D_[3] = tmp[best4];\n\n  std::array<int, 4> tmpId = {id1, id2, id3, id4};\n  id1 = tmpId[best1];\n  id2 = tmpId[best2];\n  id3 = tmpId[best3];\n  id4 = tmpId[best4];\n\n  return true;\n}\n\n\n// Selects a good base from P and computes its invariants. Returns false if\n// a good planar base cannot can be found.\nbool Match4PCSBase::SelectQuadrilateral(Scalar& invariant1, Scalar& invariant2,\n                                        int& base1, int& base2, int& base3,\n                                        int& base4) {\n\n  const Scalar kBaseTooSmall (0.2);\n  int current_trial = 0;\n\n  // Try fix number of times.\n  while (current_trial < kNumberOfDiameterTrials) {\n    // Select a triangle if possible. otherwise fail.\n    if (!SelectRandomTriangle(base1, base2, base3)){\n      return false;\n    }\n\n    base_3D_[0] = sampled_P_3D_[base1];\n    base_3D_[1] = sampled_P_3D_[base2];\n    base_3D_[2] = sampled_P_3D_[base3];\n\n    // The 4th point will be a one that is close to be planar to the other 3\n    // while still not too close to them.\n    const double x1 = base_3D_[0].x();\n    const double y1 = base_3D_[0].y();\n    const double z1 = base_3D_[0].z();\n    const double x2 = base_3D_[1].x();\n    const double y2 = base_3D_[1].y();\n    const double z2 = base_3D_[1].z();\n    const double x3 = base_3D_[2].x();\n    const double y3 = base_3D_[2].y();\n    const double z3 = base_3D_[2].z();\n\n    // Fit a plan.\n    Scalar denom = (-x3 * y2 * z1 + x2 * y3 * z1 + x3 * y1 * z2 - x1 * y3 * z2 -\n                    x2 * y1 * z3 + x1 * y2 * z3);\n\n    if (denom != 0) {\n      Scalar A =\n          (-y2 * z1 + y3 * z1 + y1 * z2 - y3 * z2 - y1 * z3 + y2 * z3) / denom;\n      Scalar B =\n          (x2 * z1 - x3 * z1 - x1 * z2 + x3 * z2 + x1 * z3 - x2 * z3) / denom;\n      Scalar C =\n          (-x2 * y1 + x3 * y1 + x1 * y2 - x3 * y2 - x1 * y3 + x2 * y3) / denom;\n      base4 = -1;\n      Scalar best_distance = std::numeric_limits<Scalar>::max();\n      // Go over all points in P.\n      const Scalar too_small = std::pow(max_base_diameter_ * kBaseTooSmall, 2);\n      for (unsigned int i = 0; i < sampled_P_3D_.size(); ++i) {\n        if ((sampled_P_3D_[i].pos()- sampled_P_3D_[base1].pos()).squaredNorm() >= too_small &&\n            (sampled_P_3D_[i].pos()- sampled_P_3D_[base2].pos()).squaredNorm() >= too_small &&\n            (sampled_P_3D_[i].pos()- sampled_P_3D_[base3].pos()).squaredNorm() >= too_small) {\n          // Not too close to any of the first 3.\n          const Scalar distance =\n              std::abs(A * sampled_P_3D_[i].x() + B * sampled_P_3D_[i].y() +\n                   C * sampled_P_3D_[i].z() - 1.0);\n          // Search for the most planar.\n          if (distance < best_distance) {\n            best_distance = distance;\n            base4 = int(i);\n          }\n        }\n      }\n      // If we have a good one we can quit.\n      if (base4 != -1) {\n        base_3D_[3] = sampled_P_3D_[base4];\n        if(TryQuadrilateral(invariant1, invariant2, base1, base2, base3, base4))\n            return true;\n      }\n    }\n    current_trial++;\n  }\n\n  // We failed to find good enough base..\n  return false;\n}\n\nvoid Match4PCSBase::initKdTree(){\n  size_t number_of_points = sampled_P_3D_.size();\n\n  // Build the kdtree.\n  kd_tree_ = GlobalRegistration::KdTree<Scalar>(number_of_points);\n\n  for (size_t i = 0; i < number_of_points; ++i) {\n    kd_tree_.add(sampled_P_3D_[i].pos());\n  }\n  kd_tree_.finalize();\n}\n\nbool Match4PCSBase::ComputeRigidTransformation(\n        const std::array<Point3D, 4>& ref,\n        const std::array<Point3D, 4>& candidate,\n        const Eigen::Matrix<Scalar, 3, 1>& centroid1,\n        Eigen::Matrix<Scalar, 3, 1> centroid2,\n        Scalar max_angle,\n        Eigen::Ref<MatrixType> transform,\n        Scalar& rms_,\n        bool computeScale ) const {\n\n  rms_ = kLargeNumber;\n\n  Scalar kSmallNumber = 1e-6;\n\n  // We only use the first 3 pairs. This simplifies the process considerably\n  // because it is the planar case.\n\n  const VectorType& p0 = ref[0].pos();\n  const VectorType& p1 = ref[1].pos();\n  const VectorType& p2 = ref[2].pos();\n        VectorType  q0 = candidate[0].pos();\n        VectorType  q1 = candidate[1].pos();\n        VectorType  q2 = candidate[2].pos();\n\n  Scalar scaleEst (1.);\n\n  // Compute scale factor if needed\n  if (computeScale){\n      const VectorType& p3 = ref[3].pos();\n      const VectorType& q3 = candidate[3].pos();\n\n      const Scalar ratio1 = (p1 - p0).norm() / (q1 - q0).norm();\n      const Scalar ratio2 = (p3 - p2).norm() / (q3 - q2).norm();\n\n      const Scalar ratioDev  = std::abs(ratio1/ratio2 - Scalar(1.));  // deviation between the two\n      const Scalar ratioMean = (ratio1+ratio2)/Scalar(2.);            // mean of the two\n\n      if ( ratioDev > Scalar(0.1) )\n          return kLargeNumber;\n\n\n      //Log<LogLevel::Verbose>( ratio1, \" \", ratio2, \" \", ratioDev, \" \", ratioMean);\n      scaleEst = ratioMean;\n\n      // apply scale factor to q\n      q0 = q0*scaleEst;\n      q1 = q1*scaleEst;\n      q2 = q2*scaleEst;\n      centroid2 *= scaleEst;\n  }\n\n  VectorType vector_p1 = p1 - p0;\n  if (vector_p1.squaredNorm() == 0) return kLargeNumber;\n  vector_p1.normalize();\n  VectorType vector_p2 = (p2 - p0) - ((p2 - p0).dot(vector_p1)) * vector_p1;\n  if (vector_p2.squaredNorm() == 0) return kLargeNumber;\n  vector_p2.normalize();\n  VectorType vector_p3 = vector_p1.cross(vector_p2);\n\n  VectorType vector_q1 = q1 - q0;\n  if (vector_q1.squaredNorm() == 0) return kLargeNumber;\n  vector_q1.normalize();\n  VectorType vector_q2 = (q2 - q0) - ((q2 - q0).dot(vector_q1)) * vector_q1;\n  if (vector_q2.squaredNorm() == 0) return kLargeNumber;\n  vector_q2.normalize();\n  VectorType vector_q3 = vector_q1.cross(vector_q2);\n\n  //cv::Mat rotation = cv::Mat::eye(3, 3, CV_64F);\n  Eigen::Matrix<Scalar, 3, 3> rotation = Eigen::Matrix<Scalar, 3, 3>::Identity();\n\n  Eigen::Matrix<Scalar, 3, 3> rotate_p;\n  rotate_p.row(0) = vector_p1;\n  rotate_p.row(1) = vector_p2;\n  rotate_p.row(2) = vector_p3;\n\n  Eigen::Matrix<Scalar, 3, 3> rotate_q;\n  rotate_q.row(0) = vector_q1;\n  rotate_q.row(1) = vector_q2;\n  rotate_q.row(2) = vector_q3;\n\n  rotation = rotate_p.transpose() * rotate_q;\n\n\n  // Discard singular solutions. The rotation should be orthogonal.\n  if (((rotation * rotation).diagonal().array() - Scalar(1) > kSmallNumber).any())\n      return false;\n\n  //FIXME\n  if (max_angle >= 0) {\n      // Discard too large solutions (todo: lazy evaluation during boolean computation\n      if (! (\n                  std::abs(std::atan2(rotation(2, 1), rotation(2, 2)))\n                  <= max_angle &&\n\n                  std::abs(std::atan2(-rotation(2, 0),\n                                      std::sqrt(std::pow(rotation(2, 1),2) +\n                                                std::pow(rotation(2, 2),2))))\n                  <= max_angle &&\n\n                  std::abs(atan2(rotation(1, 0), rotation(0, 0)))\n                  <= max_angle\n             ))\n          return false;\n  }\n\n\n  //FIXME\n  // Compute rms and return it.\n  rms_ = Scalar(0.0);\n  {\n      VectorType first, transformed;\n\n      //cv::Mat first(3, 1, CV_64F), transformed;\n      for (int i = 0; i < 3; ++i) {\n          first = scaleEst*candidate[i].pos() - centroid2;\n          transformed = rotation * first;\n          rms_ += (transformed - ref[i].pos() + centroid1).norm();\n      }\n  }\n\n  rms_ /= Scalar(ref.size());\n\n  Eigen::Transform<Scalar, 3, Eigen::Affine> etrans (Eigen::Transform<Scalar, 3, Eigen::Affine>::Identity());\n  transform = etrans\n      .scale(scaleEst)\n      .translate(centroid1)\n      .rotate(rotation)\n      .translate(-centroid2)\n      .matrix();\n\n  return true;\n}\n\n\n\n// Verify a given transformation by computing the number of points in P at\n// distance at most (normalized) delta from some point in Q. In the paper\n// we describe randomized verification. We apply deterministic one here with\n// early termination. It was found to be fast in practice.\nMatch4PCSBase::Scalar\nMatch4PCSBase::Verify(const Eigen::Ref<const MatrixType> &mat) const {\n  using RangeQuery = GlobalRegistration::KdTree<Scalar>::RangeQuery<>;\n\n#ifdef TEST_GLOBAL_TIMINGS\n    Timer t_verify (true);\n#endif\n\n  // We allow factor 2 scaling in the normalization.\n  const Scalar epsilon = options_.delta;\n  std::atomic_uint good_points(0);\n  const size_t number_of_points = sampled_Q_3D_.size();\n  const size_t terminate_value = best_LCP_ * number_of_points;\n\n  const Scalar sq_eps = epsilon*epsilon;\n\n  for (size_t i = 0; i < number_of_points; ++i) {\n\n    // Use the kdtree to get the nearest neighbor\n#ifdef TEST_GLOBAL_TIMINGS\n    Timer t (true);\n#endif\n\n    RangeQuery query;\n    query.queryPoint = (mat * sampled_Q_3D_[i].pos().homogeneous()).head<3>();\n    query.sqdist     = sq_eps;\n\n    GlobalRegistration::KdTree<Scalar>::Index resId =\n    kd_tree_.doQueryRestrictedClosestIndex( query );\n\n#ifdef TEST_GLOBAL_TIMINGS\n    kdTreeTime += Scalar(t.elapsed().count()) / Scalar(CLOCKS_PER_SEC);\n#endif\n\n    if ( resId != GlobalRegistration::KdTree<Scalar>::invalidIndex() ) {\n//      Point3D& q = sampled_P_3D_[near_neighbor_index[0]];\n//      bool rgb_good =\n//          (p.rgb()[0] >= 0 && q.rgb()[0] >= 0)\n//              ? cv::norm(p.rgb() - q.rgb()) < options_.max_color_distance\n//              : true;\n//      bool norm_good = norm(p.normal()) > 0 && norm(q.normal()) > 0\n//                           ? fabs(p.normal().ddot(q.normal())) >= cos_dist\n//                           : true;\n//      if (rgb_good && norm_good) {\n        good_points++;\n//      }\n    }\n\n    // We can terminate if there is no longer chance to get better than the\n    // current best LCP.\n    if (number_of_points - i + good_points < terminate_value) {\n      break;\n    }\n  }\n\n#ifdef TEST_GLOBAL_TIMINGS\n  verifyTime += Scalar(t_verify.elapsed().count()) / Scalar(CLOCKS_PER_SEC);\n#endif\n  return Scalar(good_points) / Scalar(number_of_points);\n}\n\n} // namespace Super4PCS\n\n", "meta": {"hexsha": "ef104c2a18a953fc755941f1b3f1efc9083f6062", "size": 18600, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/super4pcs/algorithms/match4pcsBase.cc", "max_stars_repo_name": "zengzhen/Super4PCS", "max_stars_repo_head_hexsha": "736f31122532f52c31dbfd6b9077bc77be518d97", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-31T01:17:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-07T19:52:41.000Z", "max_issues_repo_path": "src/super4pcs/algorithms/match4pcsBase.cc", "max_issues_repo_name": "RioWong/Super4PCS", "max_issues_repo_head_hexsha": "7971c7fab0ffcbe9a2a4a517c0211edc37ba7af8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-11-11T14:39:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-11T14:39:20.000Z", "max_forks_repo_path": "src/super4pcs/algorithms/match4pcsBase.cc", "max_forks_repo_name": "RioWong/Super4PCS", "max_forks_repo_head_hexsha": "7971c7fab0ffcbe9a2a4a517c0211edc37ba7af8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-09T12:48:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-22T06:09:42.000Z", "avg_line_length": 32.8042328042, "max_line_length": 109, "alphanum_fraction": 0.6137634409, "num_tokens": 5425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.54923423594241}}
{"text": "#include <gtest/gtest.h>\n#include <carl/core/Variable.h>\n#include <carl/core/Monomial.h>\n#include <carl/core/MonomialPool.h>\n#include <list>\n#include <boost/variant.hpp>\n\n#include \"../Common.h\"\n\nTEST(Monomial, Constructor)\n{\n\tauto x = carl::freshRealVariable(\"x\");\n\t\n\tauto m = carl::createMonomial(x, 3);\n\tEXPECT_TRUE(m->exponents().size() == 1);\n\tEXPECT_TRUE(m->exponents().front().first == x);\n\tEXPECT_TRUE(m->exponents().front().second == 3);\n}\n\nTEST(Monomial, tdeg)\n{\n\tauto x = carl::freshRealVariable(\"x\");\n\tauto y = carl::freshRealVariable(\"y\");\n\n\tcarl::Monomial::Arg m1 = x*x*x;\n\tEXPECT_TRUE(m1->tdeg() == 3);\n\tcarl::Monomial::Arg m2 = x*x*y;\n\tEXPECT_TRUE(m2->tdeg() == 3);\n\tcarl::Monomial::Arg m3 = x*y*y*y;\n\tEXPECT_TRUE(m3->tdeg() == 4);\n}\n\nTEST(Monomial, degreeCategories)\n{\n\tauto x = carl::freshRealVariable(\"x\");\n\t\n\tcarl::Monomial::Arg m1 = carl::createMonomial(x, 1);\n\tEXPECT_FALSE(m1->isConstant());\n\tEXPECT_TRUE(m1->isLinear());\n\tEXPECT_TRUE(m1->isAtMostLinear());\n\tEXPECT_FALSE(m1->isSquare());\n\tcarl::Monomial::Arg m2 = carl::createMonomial(x, 2);\n\tEXPECT_FALSE(m2->isConstant());\n\tEXPECT_FALSE(m2->isLinear());\n\tEXPECT_FALSE(m2->isAtMostLinear());\n\tEXPECT_TRUE(m2->isSquare());\n}\n\nTEST(Monomial, hasNoOtherVariable)\n{\n\tauto x = carl::freshRealVariable(\"x\");\n\tauto y = carl::freshRealVariable(\"y\");\n\tcarl::Monomial::Arg m1 = carl::createMonomial(x, 1);\n\tcarl::Monomial::Arg m2 = x*x;\n\tcarl::Monomial::Arg m3 = x*x*y;\n\tcarl::Monomial::Arg m4 = carl::createMonomial(y, 1);\n\tcarl::Monomial::Arg m5 = y*y;\n\tcarl::Monomial::Arg m6 = y*y*x;\n\t\n\tEXPECT_TRUE(m1->hasNoOtherVariable(x));\n\tEXPECT_FALSE(m1->hasNoOtherVariable(y));\n\tEXPECT_TRUE(m2->hasNoOtherVariable(x));\n\tEXPECT_FALSE(m2->hasNoOtherVariable(y));\n\tEXPECT_FALSE(m3->hasNoOtherVariable(x));\n\tEXPECT_FALSE(m3->hasNoOtherVariable(y));\n\tEXPECT_FALSE(m4->hasNoOtherVariable(x));\n\tEXPECT_TRUE(m4->hasNoOtherVariable(y));\n\tEXPECT_FALSE(m5->hasNoOtherVariable(x));\n\tEXPECT_TRUE(m5->hasNoOtherVariable(y));\n\tEXPECT_FALSE(m6->hasNoOtherVariable(x));\n\tEXPECT_FALSE(m6->hasNoOtherVariable(y));\n}\n\nTEST(Monomial, Operators)\n{\n\tauto v0 = carl::freshRealVariable(\"a\");\n\tauto v1 = carl::freshRealVariable(\"b\");\n\tauto v2 = carl::freshRealVariable(\"c\");\n\n\tcarl::Monomial::Arg m0 = carl::createMonomial(v0, 1);\n\tm0 = m0 * v1;\n\tEXPECT_EQ((unsigned)1,m0->exponentOfVariable(v1));\n\tm0 = m0 * v1;\n\tEXPECT_EQ((unsigned)2,m0->exponentOfVariable(v1));\n\tEXPECT_EQ((unsigned)3,m0->tdeg());\n\tEXPECT_EQ((unsigned)0,m0->exponentOfVariable(v2));\n\tm0 = m0 * v2;\n\tEXPECT_EQ((unsigned)4,m0->tdeg());\n\tEXPECT_EQ((unsigned)3,m0->nrVariables());\n\n\tcarl::Monomial::Arg m3 = carl::createMonomial(v1, 1);\n\tcarl::Monomial::Arg m2 = carl::createMonomial(v1, 1);\n\tm2 = m2 * v1;\n\tm3 = m3 * v1;\n\tEXPECT_EQ(m2, m3);\n}\n\nTEST(Monomial, VariableMultiplication)\n{\n\tauto x = carl::freshRealVariable(\"x\");\n\tauto y = carl::freshRealVariable(\"y\");\n\t//EXPECT_EQ(carl::createMonomial(std::initializer_list<std::pair<Variable, exponent>>({std::make_pair(x, 1)})), x);\n\tEXPECT_EQ(carl::createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(x, 1), std::make_pair(y, 1)})), x * y);\n\t//EXPECT_EQ(carl::createMonomial(std::initializer_list<std::pair<Variable, exponent>>({std::make_pair(x, 2), std::make_pair(y, 1)})), x * x * y);\n\t//EXPECT_EQ(carl::createMonomial(std::initializer_list<std::pair<Variable, exponent>>({std::make_pair(x, 1), std::make_pair(y, 2)})), y * x * y);\n\t//EXPECT_EQ(carl::createMonomial(std::initializer_list<std::pair<Variable, exponent>>({std::make_pair(x, 3)})), x * x * x);\n}\n\nTEST(Monomial, MonomialMultiplication)\n{\n\tauto x = carl::freshRealVariable(\"x\");\n\tauto y = carl::freshRealVariable(\"y\");\n\tEXPECT_EQ(\n\t\tcarl::createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(x, 2), std::make_pair(y, 3)})),\n\t\tcarl::createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(x, 1), std::make_pair(y, 2)})) * carl::createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(x, 1), std::make_pair(y, 1)}))\n\t);\n\tEXPECT_EQ(\n\t\tcarl::createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(x, 2), std::make_pair(y, 3)})),\n\t\tcarl::createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(x, 2)})) * carl::createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(y, 3)}))\n\t);\n\tEXPECT_EQ(\n\t\tcarl::createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(x, 5), std::make_pair(y, 3)})),\n\t\tcarl::createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(x, 2)})) * carl::createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(x, 3), std::make_pair(y, 3)}))\n\t);\n}\n\nTEST(Monomial, derivative)\n{\n\tauto v0 = carl::freshRealVariable(\"x\");\n\tauto v1 = carl::freshRealVariable(\"y\");\n\tauto m0 = v0 * v1;\n\tauto d1 = m0->derivative(v0);\n\tEXPECT_EQ(1, d1.first);\n\tEXPECT_EQ(v1, d1.second);\n}\n\nTEST(Monomial, division)\n{\n\tauto v0 = carl::freshRealVariable(\"x\");\n\tauto v1 = carl::freshRealVariable(\"y\");\n\tauto v2 = carl::freshRealVariable(\"z\");\n\n\tcarl::Monomial::Arg m0 = v0 * v0 * v1 * v1 * v2;\n\tcarl::Monomial::Arg m1 = v0 * v0 * v0;\n\tcarl::Monomial::Arg m2 = v0 * v0 * v1 * v2;\n\tcarl::Monomial::Arg m0x = v0 * v0 * v1 * v2;\n\tcarl::Monomial::Arg m0y = v0 * v0 * v1 * v1;\n\tcarl::Monomial::Arg m0z = v0 * v1;\n\tcarl::Monomial::Arg tmp;\n\tcarl::Monomial::Arg one;\n\tEXPECT_TRUE(m0->divide(one, tmp));\n\tEXPECT_EQ(m0, tmp);\n\tEXPECT_TRUE(m1->divide(one, tmp));\n\tEXPECT_EQ(m1, tmp);\n\tEXPECT_FALSE(m0->divide(m1, tmp));\n\tEXPECT_FALSE(m1->divide(m0, tmp));\n\tEXPECT_TRUE(m0->divide(v1, tmp));\n\tEXPECT_EQ(m0x, tmp);\n\tEXPECT_TRUE(m0->divide(v2, tmp));\n\tEXPECT_EQ(m0y, tmp);\n\tEXPECT_TRUE(m0->divide(m2, tmp));\n\tEXPECT_EQ(v1, tmp);\n}\n\nTEST(Monomial, divisible)\n{\n\tauto x = carl::freshRealVariable(\"x\");\n\tauto y = carl::freshRealVariable(\"y\");\n\tauto m1 = carl::createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(y, 2), std::make_pair(x, 2)}));\n\tauto m2 = carl::createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(x, 1), std::make_pair(y, 1)}));\n\tauto m3 = carl::createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(y, 1), std::make_pair(x, 1)}));\n//\tstd::cout << m1 << \" divisible by \" << m2 << std::endl;\n//\tstd::cout << m2 << \" == \" << m3 << std::endl;\n\tEXPECT_TRUE(m2==m3);\n\tEXPECT_TRUE(m1->divisible(m2));\n\t\n\t{\n\t\tauto m1 = createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(y, 2)}));\n\t\tauto m2 = createMonomial(std::initializer_list<std::pair<carl::Variable, carl::exponent>>({std::make_pair(y, 2), std::make_pair(x, 2)}));\n\t\tEXPECT_TRUE(m2->divisible(m1));\n\t}\n}\n\nTEST(Monomial, Comparison)\n{\n\tauto x = carl::freshRealVariable(\"x\");\n\tauto y = carl::freshRealVariable(\"y\");\n\tauto z = carl::freshRealVariable(\"z\");\n\n\tComparisonList<carl::Monomial::Arg> monomials;\n\tmonomials.push_back(x * x * x);\n\tmonomials.push_back(x * x * y);\n\tmonomials.push_back(x * y * y);\n\tmonomials.push_back(x * y * z);\n\tmonomials.push_back(y * y * y);\n\tmonomials.push_back(x * x * z * z);\n\tmonomials.push_back(x * y * y * z);\n\n\texpectRightOrder(monomials);\n}\n\n\nTEST(Monomial, OtherComparison)\n{\n\tComparisonList<carl::Variable,carl::Monomial::Arg> list;\n\n\tauto x = carl::freshRealVariable(\"x\");\n\tauto y = carl::freshRealVariable(\"y\");\n\n\tlist.push_back(x);\n\tlist.push_back(y);\n\tlist.push_back(x * x);\n\tlist.push_back(x * y);\n\tlist.push_back(y * y);\n\tlist.push_back(x * x * x);\n\tlist.push_back(x * x * y);\n\tlist.push_back(x * x * x * x);\n\n\texpectRightOrder(list);\n}\n\nTEST(Monomial, sqrt)\n{\n\tauto x = carl::freshRealVariable(\"x\");\n\tauto y = carl::freshRealVariable(\"y\");\n\tcarl::Monomial::Arg m1 = x*x*y*y*y*y;\n\tcarl::Monomial::Arg m2 = x*y*y;\n\tEXPECT_EQ(m2, m1->sqrt());\n}\n\nTEST(Monomial, pow)\n{\n\tauto x = carl::freshRealVariable(\"x\");\n\tauto y = carl::freshRealVariable(\"y\");\n\tcarl::Monomial::Arg one;\n\tcarl::Monomial::Arg m1 = x*y*y;\n\tcarl::Monomial::Arg m2 = x*x*y*y*y*y;\n\tEXPECT_EQ(one, m1->pow(0));\n\tEXPECT_EQ(m1, m1->pow(1));\n\tEXPECT_EQ(m2, m1->pow(2));\n}\n\nTEST(Monomial, CalcLCM)\n{\n\tauto x = carl::freshRealVariable(\"x\");\n\tauto y = carl::freshRealVariable(\"y\");\n\tcarl::Monomial::Arg m1 = y*y;\n\tcarl::Monomial::Arg m2 = x*x*y;\n\tEXPECT_EQ(y, carl::Monomial::calcLcmAndDivideBy(m1, m2));\n}\n", "meta": {"hexsha": "230e9ada1d45075bb791e9fe282a04a0e1d2651e", "size": 8532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/core/Test_Monomial.cpp", "max_stars_repo_name": "smtrat/carl-windows", "max_stars_repo_head_hexsha": "22b3a7677477cdbed9adc7619479ce82a0304666", "max_stars_repo_licenses": ["MIT"], "max_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/core/Test_Monomial.cpp", "max_issues_repo_name": "smtrat/carl-windows", "max_issues_repo_head_hexsha": "22b3a7677477cdbed9adc7619479ce82a0304666", "max_issues_repo_licenses": ["MIT"], "max_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/core/Test_Monomial.cpp", "max_forks_repo_name": "smtrat/carl-windows", "max_forks_repo_head_hexsha": "22b3a7677477cdbed9adc7619479ce82a0304666", "max_forks_repo_licenses": ["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.9920318725, "max_line_length": 269, "alphanum_fraction": 0.6800281294, "num_tokens": 2845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.54923423594241}}
{"text": "/*\n# linalgCpp\nCollection of basic tools or examples for linear algebra in c++\nOriginal code from https://github.com/leopoldcambier/linalgCpp\n*/\n\n#ifndef MMIO_HPP\n#define MMIO_HPP\n\n#include <assert.h>\n\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <complex>\n#include <string>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\nnamespace mmio {\n\n    /** Read a line real / cplx **/\n    template<typename V>\n    V read_entry(std::istringstream& vals) {\n        V v;\n        vals >> v;\n        return v;\n    };\n    template<>\n    std::complex<double> read_entry(std::istringstream& vals) {\n        double v1, v2;\n        vals >> v1 >> v2;\n        return std::complex<double>(v1, v2);\n    };\n    template<>\n    std::complex<float> read_entry(std::istringstream& vals) {\n        float v1, v2;\n        vals >> v1 >> v2;\n        return std::complex<float>(v1, v2);\n    };\n\n    /** Read a line real / cplx of coordinate values **/\n    template<typename V, typename I>\n    Eigen::Triplet<V,I> read_line(std::istringstream& vals) {\n        I i, j;\n        V v;\n        vals >> i >> j >> v;\n        return Eigen::Triplet<V,I>(i-1,j-1,v);\n    };\n    template<>\n    Eigen::Triplet<std::complex<double>,int> read_line(std::istringstream& vals) {\n        int i, j; double v1, v2;\n        vals >> i >> j >> v1 >> v2;\n        return Eigen::Triplet<std::complex<double>,int>(i-1,j-1,std::complex<double>(v1, v2));\n    };\n    template<>\n    Eigen::Triplet<std::complex<float>,int> read_line(std::istringstream& vals) {\n        int i, j; float v1, v2;\n        vals >> i >> j >> v1 >> v2;\n        return Eigen::Triplet<std::complex<float>,int>(i-1,j-1,std::complex<float>(v1, v2));\n    };\n\n    /** Write a line real / cplx of coordinate values **/\n    template<typename V, typename I>\n    std::string get_line(I i, I j, V v) {\n        return std::to_string(i+1) + \" \" + std::to_string(j+1) + \" \" + std::to_string(v);\n    };\n    template<>\n    std::string get_line(int i, int j, std::complex<double> v) {\n        return std::to_string(i+1) + \" \" + std::to_string(j+1) + \" \" + std::to_string(v.real()) + \" \" + std::to_string(v.imag());\n    };\n    template<>\n    std::string get_line(int i, int j, std::complex<float> v) {\n        return std::to_string(i+1) + \" \" + std::to_string(j+1) + \" \" + std::to_string(v.real()) + \" \" + std::to_string(v.imag());\n    };\n\n    /** Symmetric (real) / hermitian (cplx) **/\n    template<typename V, typename I>\n    Eigen::Triplet<V,I> symmetric(Eigen::Triplet<V,I>& a) {\n        return Eigen::Triplet<V,I>(a.col(), a.row(), a.value());\n    }\n    template<>\n    Eigen::Triplet<std::complex<double>,int> symmetric(Eigen::Triplet<std::complex<double>,int>& a) {\n        return Eigen::Triplet<std::complex<double>,int>(a.col(), a.row(), std::conj(a.value()));\n    }\n    template<>\n    Eigen::Triplet<std::complex<float>,int> symmetric(Eigen::Triplet<std::complex<float>,int>& a) {\n        return Eigen::Triplet<std::complex<float>,int>(a.col(), a.row(), std::conj(a.value()));\n    }\n\n    /** Skew-symmetric (real only, really) **/\n    template<typename V, typename I>\n    Eigen::Triplet<V,I> skew_symmetric(Eigen::Triplet<V,I>& a) {\n        return Eigen::Triplet<V,I>(a.col(), a.row(), - a.value());\n    }\n\n    enum class format {coordinate, array};\n    enum class type {real, integer, complex, pattern};\n    enum class property {general, symmetric, hermitian, skew_symmetric};\n\n    std::string prop2str(property p) {\n        if(p == property::general) return \"general\";\n        else if(p == property::symmetric) return \"symmetric\";\n        else if(p == property::hermitian) return \"hermitian\";\n        else return \"skew_symmetric\";\n    }\n\n    template<typename V>\n    struct V2str {\n        static std::string value() {\n            if (std::is_same<V,std::complex<double>>::value || std::is_same<V,std::complex<float>>::value) {\n                return \"complex\";\n            } else if (std::is_integral<V>::value) {\n                return \"integer\";\n            } else {\n                return \"real\";\n            }\n        }\n    };\n\n    struct Header {\n        bool bannerOK;\n        bool objectOK;\n        format f;\n        type   t;\n        property p;\n        Header(std::istringstream& header) {\n            std::string banner, object, format, type, properties;\n            header >> banner >> object >> format >> type >> properties;\n            std::transform(object.begin(),      object.end(),       object.begin(),       ::tolower);\n            std::transform(format.begin(),      format.end(),       format.begin(),       ::tolower);\n            std::transform(type.begin(),        type.end(),         type.begin(),         ::tolower);\n            std::transform(properties.begin(),  properties.end(),   properties.begin(),   ::tolower);\n            this->bannerOK = ! banner.compare(\"%%MatrixMarket\");\n            this->objectOK = ! object.compare(\"matrix\");\n            assert(this->bannerOK);\n            assert(this->objectOK);\n            if(! format.compare(\"coordinate\")) {\n                this->f = format::coordinate;\n            } else if(! format.compare(\"array\")) {\n                this->f = format::array;\n            } else {\n                assert(false);\n            }\n            if (! type.compare(\"real\")) {\n                this->t = type::real;\n            } else if (! type.compare(\"integer\")) {\n                this->t = type::integer;\n            } else if (! type.compare(\"complex\")) {\n                this->t = type::complex;\n            } else if (! type.compare(\"pattern\")) {\n                this->t = type::pattern;\n            } else { \n                assert(false);\n            }\n            if (! properties.compare(\"general\")) {\n                this->p = property::general;\n            } else if (! properties.compare(\"symmetric\")) {\n                this->p = property::symmetric;\n            } else if (! properties.compare(\"skew-symmetric\")) {\n                this->p = property::skew_symmetric;\n            } else if (! properties.compare(\"hermitian\")) {\n                this->p = property::hermitian;\n            } else { \n                assert(false);\n            }\n        }\n    };\n\n    /**\n     * Read a sparse matrix in MM format\n     */\n    template<typename V, typename I>\n    Eigen::SparseMatrix<V, Eigen::ColMajor, I> sp_mmread(std::string filename) {\n        std::ifstream mfile(filename);\n        if (mfile.is_open()) {\n            std::string line;\n            /** Header **/\n            std::getline(mfile, line);\n            std::istringstream header(line);\n            Header h(header);\n            assert(h.f == format::coordinate);\n            // assert(h.t != type::pattern);\n            /** Find M N K row **/\n            while(std::getline(mfile, line)) {\n                if(line.size() == 0 || line[0] == '%') continue;\n                else break;\n            }\n            I M, N, K;\n            std::istringstream MNK(line);\n            MNK >> M >> N >> K;\n            std::vector<Eigen::Triplet<V,I>> data;\n            if(h.p != property::general) {\n                data.reserve(2*K);\n            } else {\n                data.reserve(K);\n            }\n            /** Read data **/\n            int lineread = 0;\n            while(std::getline(mfile, line)) {\n                if(line.size() == 0 || line[0] == '%') continue;\n                if (h.t == type::pattern) line = line + \" 1\";\n                std::istringstream vals(line);\n                Eigen::Triplet<V,I> dataline = read_line<V,I>(vals);\n                data.push_back(dataline);\n                if(dataline.row() != dataline.col() && (h.p == property::symmetric || h.p == property::hermitian)) {\n                    Eigen::Triplet<V,I> dataline2 = symmetric(dataline);\n                    data.push_back(dataline2);\n                }\n                if(dataline.row() != dataline.col() && (h.p == property::skew_symmetric)) {\n                    Eigen::Triplet<V,I> dataline2 = skew_symmetric(dataline);\n                    data.push_back(dataline2);\n                }\n                if(h.p == property::skew_symmetric && dataline.row() == dataline.col()) {\n                    assert(false);\n                }\n                if(h.p != property::general && dataline.row() < dataline.col()) {\n                    assert(false);\n                }\n                lineread ++;\n            }\n            assert(lineread == K);\n            Eigen::SparseMatrix<V, Eigen::ColMajor, I> A(M, N);\n            A.setFromTriplets(data.begin(), data.end());\n            return std::move(A);\n        } else {\n            throw(\"Couldn't open file\");\n        }\n    }\n\n    /**\n     * Reads a dense matrix in MM format\n     */\n    template<typename V>\n    Eigen::Matrix<V, Eigen::Dynamic, Eigen::Dynamic> dense_mmread(std::string filename) {\n        std::ifstream mfile(filename);\n        if (mfile.is_open()) {\n            std::string line;\n            /** Header **/\n            std::getline(mfile, line);\n            std::istringstream header(line);\n            Header h(header);\n            assert(h.p == property::general);\n            assert(h.f == format::array);\n            assert(h.t != type::pattern);\n            /** Find M N row **/\n            while(std::getline(mfile, line)) {\n                if(line.size() == 0 || line[0] == '%') continue;\n                else break;\n            }\n            int M, N;\n            std::istringstream MNK(line);\n            MNK >> M >> N;\n            Eigen::Matrix<V, Eigen::Dynamic, Eigen::Dynamic> A(M, N); \n            /** Read data **/\n            int lineread = 0;\n            while(std::getline(mfile, line)) {\n                if(line.size() == 0 || line[0] == '%') continue;\n                std::istringstream vals(line);\n                V v = read_entry<V>(vals);\n                int i = (lineread % M);\n                int j = (lineread / M);\n                A(i,j) = v;\n                lineread ++;\n            }\n            assert(lineread == M*N);\n            return std::move(A);\n        } else {\n            throw(\"Couldn't open file\");\n        }\n    }\n\n    /**\n     * Reads a dense vector in MM format\n     */\n    template<typename V>\n    Eigen::Matrix<V, Eigen::Dynamic, 1> vector_mmread(std::string filename) {\n        std::ifstream mfile(filename);\n        if (mfile.is_open()) {\n            std::string line;\n            /** Header **/\n            std::getline(mfile, line);\n            std::istringstream header(line);\n            Header h(header);\n            assert(h.p == property::general);\n            assert(h.f == format::array);\n            assert(h.t != type::pattern);\n            /** Find M N row **/\n            while(std::getline(mfile, line)) {\n                if(line.size() == 0 || line[0] == '%') continue;\n                else break;\n            }\n            int M, N;\n            std::istringstream MNK(line);\n            MNK >> M >> N;\n            assert(N ==1);\n            Eigen::Matrix<V, Eigen::Dynamic, 1> b(M); \n            /** Read data **/\n            int lineread = 0;\n            while(std::getline(mfile, line)) {\n                if(line.size() == 0 || line[0] == '%') continue;\n                std::istringstream vals(line);\n                V v = read_entry<V>(vals);\n                int i = (lineread % M);\n                // int j = (lineread / M);\n                // A(i,j) = v;\n                b(i) = v;\n                lineread ++;\n            }\n            assert(lineread == M*N);\n            return std::move(b);\n        } else {\n            throw(\"Couldn't open file\");\n        }\n    }\n\n    /**\n     * Writes a sparse matrix in MM format, using the optional property p.\n     * Wether the matrix satisfies or not p is not verified\n     */\n    template<typename V, int S, typename I>\n    void sp_mmwrite(std::string filename, Eigen::SparseMatrix<V,S,I> mat, property p = property::general) {\n        std::ofstream mfile;\n        mfile.open (filename);\n        if (mfile.is_open()) {\n            std::string type = V2str<V>::value();\n            std::string prop = prop2str(p);\n            mfile << \"%%MatrixMarket matrix coordinate \" << type << \" \" << prop << \"\\n\";\n            int NNZ = 0;\n            for (int k = 0; k < mat.outerSize(); ++k) {\n                for (typename Eigen::SparseMatrix<V,S,I>::InnerIterator it(mat,k); it; ++it) {\n                    if( (p == property::symmetric || p == property::hermitian) && (it.row() < it.col()) ) continue;\n                    if( (p == property::skew_symmetric) && (it.row() <= it.col()) ) continue;\n                    NNZ ++;\n                }\n            }\n            mfile << mat.rows() << \" \" << mat.cols() << \" \" << NNZ << \"\\n\";\n            for (int k = 0; k < mat.outerSize(); ++k) {\n                for (typename Eigen::SparseMatrix<V,S,I>::InnerIterator it(mat,k); it; ++it) {\n                    if( (p == property::symmetric || p == property::hermitian) && (it.row() < it.col()) ) continue;\n                    if( (p == property::skew_symmetric) && (it.row() <= it.col()) ) continue;\n                    mfile << get_line(it.row(), it.col(), it.value()) << \"\\n\";\n                }\n            }\n        } else {\n            throw(\"Couldn't open file\");\n        }\n    }\n\n    /**\n     * Writes a dense matrix in MM format, using the optional property p.\n     * Wether the matrix satisfies or not p is not verified\n     */\n    template<typename V>\n    void dense_mmwrite(std::string filename, Eigen::Matrix<V, Eigen::Dynamic, Eigen::Dynamic> mat, property p = property::general) {\n        std::ofstream mfile;\n        mfile.open (filename);\n        if (mfile.is_open()) {\n            std::string type = V2str<V>::value();\n            std::string prop = prop2str(p);\n            mfile << \"%%MatrixMarket matrix array \" << type << \" \" << prop << \"\\n\";\n            mfile << mat.rows() << \" \" << mat.cols() << \"\\n\";\n            for(int j = 0; j < mat.cols(); j++) {\n                for(int i = 0; i < mat.rows(); i++) {\n                    if( (p == property::symmetric || p == property::hermitian) && (i < j) ) continue;\n                    if( (p == property::skew_symmetric) && (i <= j) ) continue;\n                    mfile << mat(i,j) << \"\\n\";\n                }\n            }\n        } else {\n            throw(\"Couldn't open file\");\n        }\n    }\n\n}\n\n#endif", "meta": {"hexsha": "82ac2aa591813818f0f724c3d7291093324b7889", "size": 14287, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mmio.hpp", "max_stars_repo_name": "Abeynaya/spaQR_public", "max_stars_repo_head_hexsha": "4fd28b1a23c73feb914b40e4285d5a076ffc9058", "max_stars_repo_licenses": ["MIT"], "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/mmio.hpp", "max_issues_repo_name": "Abeynaya/spaQR_public", "max_issues_repo_head_hexsha": "4fd28b1a23c73feb914b40e4285d5a076ffc9058", "max_issues_repo_licenses": ["MIT"], "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/mmio.hpp", "max_forks_repo_name": "Abeynaya/spaQR_public", "max_forks_repo_head_hexsha": "4fd28b1a23c73feb914b40e4285d5a076ffc9058", "max_forks_repo_licenses": ["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.7962962963, "max_line_length": 132, "alphanum_fraction": 0.4865262126, "num_tokens": 3465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.7090191399336401, "lm_q1q2_score": 0.5491944448475022}}
{"text": "/*\n [auto_generated]\n boost/numeric/odeint/stepper/symplectic_rkn_sb3a_mclachlan.hpp\n \n [begin_description]\n Implementation of the symplectic MacLachlan stepper for separable Hamiltonian system.\n [end_description]\n \n Copyright 2009-2011 Karsten Ahnert\n Copyright 2009-2011 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#ifndef BOOST_NUMERIC_ODEINT_STEPPER_SYMPLECTIC_RKN_SB3A_MCLACHLAN_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_STEPPER_SYMPLECTIC_RKN_SB3A_MCLACHLAN_HPP_INCLUDED\n\n\n#include <boost/numeric/odeint/stepper/base/symplectic_rkn_stepper_base.hpp>\n\n#include <boost/numeric/odeint/algebra/range_algebra.hpp>\n#include <boost/numeric/odeint/algebra/default_operations.hpp>\n\n#include <boost/array.hpp>\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\n\n#ifndef DOXYGEN_SKIP\nnamespace detail {\nnamespace symplectic_rkn_sb3a_mclachlan {\n\n    /*\n      exp( a1 t A ) exp( b1 t B )\n      exp( a2 t A ) exp( b2 t B )\n      exp( a3 t A ) exp( b3 t B ) exp( a3 t A )\n      exp( b2 t B ) exp( a2 t A )\n      exp( b1 t B ) exp( a1 t A )\n    */\n\n    template< class Value >\n    struct coef_a_type : public boost::array< Value , 6 >\n    {\n        coef_a_type( void )\n        {\n            (*this)[0] = static_cast< Value >( 0.40518861839525227722 );\n            (*this)[1] = static_cast< Value >( -0.28714404081652408900 );\n            (*this)[2] = static_cast< Value >( 1 ) / static_cast< Value >( 2 ) - ( (*this)[0] + (*this)[1] );\n            (*this)[3] = (*this)[2];\n            (*this)[4] = (*this)[1];\n            (*this)[5] = (*this)[0];\n\n        }\n    };\n\n    template< class Value >\n    struct coef_b_type : public boost::array< Value , 6 >\n    {\n        coef_b_type( void )\n        {\n            (*this)[0] = static_cast< Value >( -3 ) / static_cast< Value >( 73 );\n            (*this)[1] = static_cast< Value >( 17 ) / static_cast< Value >( 59 );\n            (*this)[2] = static_cast< Value >( 1 ) - static_cast< Value >( 2 ) * ( (*this)[0] + (*this)[1] );\n            (*this)[3] = (*this)[1];\n            (*this)[4] = (*this)[0];\n            (*this)[5] = static_cast< Value >( 0 );\n        }\n    };\n\n} // namespace symplectic_rkn_sb3a_mclachlan\n} // namespace detail\n#endif // DOXYGEN_SKIP\n\n\n\ntemplate<\n    class Coor ,\n    class Momentum = Coor ,\n    class Value = double ,\n    class CoorDeriv = Coor ,\n    class MomentumDeriv = Coor ,\n    class Time = Value ,\n    class Algebra = range_algebra ,\n    class Operations = default_operations ,\n    class Resizer = initially_resizer\n    >\n#ifndef DOXYGEN_SKIP\nclass symplectic_rkn_sb3a_mclachlan :\n        public symplectic_nystroem_stepper_base\n<\n    6 , 4 ,\n    Coor , Momentum , Value , CoorDeriv , MomentumDeriv , Time , Algebra , Operations , Resizer\n    >\n#else\nclass symplectic_rkn_sb3a_mclachlan : public symplectic_nystroem_stepper_base\n#endif\n{\npublic:\n#ifndef DOXYGEN_SKIP\n    typedef symplectic_nystroem_stepper_base\n    <\n    6 , 4 ,\n    Coor , Momentum , Value , CoorDeriv , MomentumDeriv , Time , Algebra , Operations , Resizer\n    > stepper_base_type;\n#endif\n    typedef typename stepper_base_type::algebra_type algebra_type;\n    typedef typename stepper_base_type::value_type value_type;\n\n\n    symplectic_rkn_sb3a_mclachlan( const algebra_type &algebra = algebra_type() )\n        : stepper_base_type(\n            detail::symplectic_rkn_sb3a_mclachlan::coef_a_type< value_type >() ,\n            detail::symplectic_rkn_sb3a_mclachlan::coef_b_type< value_type >() ,\n            algebra )\n    { }\n};\n\n\n/************* DOXYGEN ***********/\n\n/**\n * \\class symplectic_rkn_sb3a_mclachlan\n * \\brief Implement of the symmetric B3A method of Runge-Kutta-Nystroem method of sixth order.\n *\n * The method is of fourth order and has six stages. It is described HERE. This method cannot be used\n * with multiprecision types since the coefficients are not defined analytically.\n *\n * ToDo Add reference to the paper.\n *\n * \\tparam Order The order of the stepper.\n * \\tparam Coor The type representing the coordinates q.\n * \\tparam Momentum The type representing the coordinates p.\n * \\tparam Value The basic value type. Should be something like float, double or a high-precision type.\n * \\tparam CoorDeriv The type representing the time derivative of the coordinate dq/dt.\n * \\tparam MomemtnumDeriv The type representing the time derivative of the momentum dp/dt.\n * \\tparam Time The type representing the time t.\n * \\tparam Algebra The algebra.\n * \\tparam Operations The operations.\n * \\tparam Resizer The resizer policy.\n */\n\n    /**\n     * \\fn symplectic_rkn_sb3a_mclachlan::symplectic_rkn_sb3a_mclachlan( const algebra_type &algebra )\n     * \\brief Constructs the symplectic_rkn_sb3a_mclachlan. This constructor can be used as a default\n     * constructor if the algebra has a default constructor.\n     * \\param algebra A copy of algebra is made and stored inside explicit_stepper_base.\n     */\n\n} // namespace odeint\n} // namespace numeric\n} // namespace boost\n\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_SYMPLECTIC_RKN_SB3A_MCLACHLAN_HPP_INCLUDED\n", "meta": {"hexsha": "3bd26d10eb2b6e6b6567d69f8779bb5a553a7258", "size": 5137, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost/boost/numeric/odeint/stepper/symplectic_rkn_sb3a_mclachlan.hpp", "max_stars_repo_name": "creatologist/openFrameworks0084", "max_stars_repo_head_hexsha": "aa74f188f105b62fbcecb7baf2b41d56d97cf7bc", "max_stars_repo_licenses": ["MIT"], "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": "libs/boost/boost/numeric/odeint/stepper/symplectic_rkn_sb3a_mclachlan.hpp", "max_issues_repo_name": "creatologist/openFrameworks0084", "max_issues_repo_head_hexsha": "aa74f188f105b62fbcecb7baf2b41d56d97cf7bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1667.0, "max_issues_repo_issues_event_min_datetime": "2017-03-27T14:41:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:50:06.000Z", "max_forks_repo_path": "libs/boost/boost/numeric/odeint/stepper/symplectic_rkn_sb3a_mclachlan.hpp", "max_forks_repo_name": "creatologist/openFrameworks0084", "max_forks_repo_head_hexsha": "aa74f188f105b62fbcecb7baf2b41d56d97cf7bc", "max_forks_repo_licenses": ["MIT"], "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": 32.3081761006, "max_line_length": 109, "alphanum_fraction": 0.6782168581, "num_tokens": 1417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5491944400849399}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2017 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_FORMULAS_ELLIPTIC_ARC_LENGTH_HPP\n#define BOOST_GEOMETRY_FORMULAS_ELLIPTIC_ARC_LENGTH_HPP\n\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/geometry/core/radius.hpp>\n#include <boost/geometry/core/srs.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/normalize_spheroidal_coordinates.hpp>\n\n#include <boost/geometry/formulas/flattening.hpp>\n\nnamespace boost { namespace geometry { namespace formula\n{\n\n/*!\n\\brief Compute the arc length of an ellipse.\n*/\n\ntemplate <typename CT, unsigned int Order = 1>\nclass elliptic_arc_length\n{\n\npublic :\n\n    struct result\n    {\n        result()\n            : distance(0)\n            , meridian(false)\n        {}\n\n        CT distance;\n        bool meridian;\n    };\n\n    template <typename T, typename Spheroid>\n    static result apply(T lon1, T lat1, T lon2, T lat2, Spheroid const& spheroid)\n    {\n        result res;\n\n        CT c0 = 0;\n        CT pi = math::pi<CT>();\n        CT half_pi = pi/CT(2);\n        CT diff = geometry::math::longitude_distance_signed<geometry::radian>(lon1, lon2);\n\n        if (lat1 > lat2)\n        {\n            std::swap(lat1, lat2);\n        }\n\n        if ( math::equals(diff, c0) ||\n            (math::equals(lat2, half_pi) && math::equals(lat1, -half_pi)) )\n        {\n            // single meridian not crossing pole\n            res.distance = apply(lat2, spheroid) - apply(lat1, spheroid);\n            res.meridian = true;\n        }\n\n        if (math::equals(math::abs(diff), pi))\n        {\n            // meridian crosses pole\n            CT lat_sign = 1;\n            if (lat1+lat2 < c0)\n            {\n                lat_sign = CT(-1);\n            }\n            res.distance = math::abs(lat_sign * CT(2) * apply(half_pi, spheroid)\n                               - apply(lat1, spheroid) - apply(lat2, spheroid));\n            res.meridian = true;\n        }\n        return res;\n    }\n\n    // Distance computation on meridians using series approximations\n    // to elliptic integrals. Formula to compute distance from lattitude 0 to lat\n    // https://en.wikipedia.org/wiki/Meridian_arc\n    // latitudes are assumed to be in radians and in [-pi/2,pi/2]\n    template <typename T, typename Spheroid>\n    static CT apply(T lat, Spheroid const& spheroid)\n    {\n        CT const a = get_radius<0>(spheroid);\n        CT const f = formula::flattening<CT>(spheroid);\n        CT n = f / (CT(2) - f);\n        CT M = a/(1+n);\n        CT C0 = 1;\n\n        if (Order == 0)\n        {\n           return M * C0 * lat;\n        }\n\n        CT C2 = -1.5 * n;\n\n        if (Order == 1)\n        {\n            return M * (C0 * lat + C2 * sin(2*lat));\n        }\n\n        CT n2 = n * n;\n        C0 += .25 * n2;\n        CT C4 = 0.9375 * n2;\n\n        if (Order == 2)\n        {\n            return M * (C0 * lat + C2 * sin(2*lat) + C4 * sin(4*lat));\n        }\n\n        CT n3 = n2 * n;\n        C2 += 0.1875 * n3;\n        CT C6 = -0.729166667 * n3;\n\n        if (Order == 3)\n        {\n            return M * (C0 * lat + C2 * sin(2*lat) + C4 * sin(4*lat)\n                      + C6 * sin(6*lat));\n        }\n\n        CT n4 = n2 * n2;\n        C4 -= 0.234375 * n4;\n        CT C8 = 0.615234375 * n4;\n\n        if (Order == 4)\n        {\n            return M * (C0 * lat + C2 * sin(2*lat) + C4 * sin(4*lat)\n                      + C6 * sin(6*lat) + C8 * sin(8*lat));\n        }\n\n        CT n5 = n4 * n;\n        C6 += 0.227864583 * n5;\n        CT C10 = -0.54140625 * n5;\n\n        // Order 5 or higher\n        return M * (C0 * lat + C2 * sin(2*lat) + C4 * sin(4*lat)\n                  + C6 * sin(6*lat) + C8 * sin(8*lat) + C10 * sin(10*lat));\n\n    }\n\n    // Iterative method to elliptic arc length based on\n    // http://www.codeguru.com/cpp/cpp/algorithms/article.php/c5115/\n    // Geographic-Distance-and-Azimuth-Calculations.htm\n    // latitudes are assumed to be in radians and in [-pi/2,pi/2]\n    template <typename T1, typename T2, typename Spheroid>\n    CT interative_method(T1 lat1,\n                         T2 lat2,\n                         Spheroid const& spheroid)\n    {\n        CT result = 0;\n        CT const zero = 0;\n        CT const one = 1;\n        CT const c1 = 2;\n        CT const c2 = 0.5;\n        CT const c3 = 4000;\n\n        CT const a = get_radius<0>(spheroid);\n        CT const f = formula::flattening<CT>(spheroid);\n\n        // how many steps to use\n\n        CT lat1_deg = lat1 * geometry::math::r2d<CT>();\n        CT lat2_deg = lat2 * geometry::math::r2d<CT>();\n\n        int steps = c1 + (c2 + (lat2_deg > lat1_deg) ? CT(lat2_deg - lat1_deg)\n                                                     : CT(lat1_deg - lat2_deg));\n        steps = (steps > c3) ? c3 : steps;\n\n        //std::cout << \"Steps=\" << steps << std::endl;\n\n        CT snLat1 = sin(lat1);\n        CT snLat2 = sin(lat2);\n        CT twoF   = 2 * f - f * f;\n\n        // limits of integration\n        CT x1 = a * cos(lat1) /\n                sqrt(1 - twoF * snLat1 * snLat1);\n        CT x2 = a * cos(lat2) /\n                sqrt(1 - twoF * snLat2 * snLat2);\n\n        CT dx = (x2 - x1) / (steps - one);\n        CT x, y1, y2, dy, dydx;\n        CT adx = (dx < zero) ? -dx : dx;    // absolute value of dx\n\n        CT a2 = a * a;\n        CT oneF = 1 - f;\n\n        // now loop through each step adding up all the little\n        // hypotenuses\n        for (int i = 0; i < (steps - 1); i++){\n            x = x1 + dx * i;\n            dydx = ((a * oneF * sqrt((one - ((x+dx)*(x+dx))/a2))) -\n                    (a * oneF * sqrt((one - (x*x)/a2)))) / dx;\n            result += adx * sqrt(one + dydx*dydx);\n        }\n\n        return result;\n    }\n};\n\n}}} // namespace boost::geometry::formula\n\n\n#endif // BOOST_GEOMETRY_FORMULAS_ELLIPTIC_ARC_LENGTH_HPP\n", "meta": {"hexsha": "75881f3d0d5a346f12260762100189ea12db6077", "size": 6094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tether/boost/geometry/formulas/elliptic_arc_length.hpp", "max_stars_repo_name": "fictheader/fcolorwheel", "max_stars_repo_head_hexsha": "ae78ae582c6132964b7ef838a74cda9c075e74dc", "max_stars_repo_licenses": ["MIT"], "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": "tether/boost/geometry/formulas/elliptic_arc_length.hpp", "max_issues_repo_name": "fictheader/fcolorwheel", "max_issues_repo_head_hexsha": "ae78ae582c6132964b7ef838a74cda9c075e74dc", "max_issues_repo_licenses": ["MIT"], "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": "tether/boost/geometry/formulas/elliptic_arc_length.hpp", "max_forks_repo_name": "fictheader/fcolorwheel", "max_forks_repo_head_hexsha": "ae78ae582c6132964b7ef838a74cda9c075e74dc", "max_forks_repo_licenses": ["MIT"], "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": 28.3441860465, "max_line_length": 90, "alphanum_fraction": 0.5182146373, "num_tokens": 1809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5491944327060307}}
{"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://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestFunctionalBind\n#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n\n#include <boost/compute/function.hpp>\n#include <boost/compute/algorithm/copy_n.hpp>\n#include <boost/compute/algorithm/count_if.hpp>\n#include <boost/compute/algorithm/find_if.hpp>\n#include <boost/compute/algorithm/transform.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/functional/bind.hpp>\n#include <boost/compute/functional/common.hpp>\n#include <boost/compute/functional/operator.hpp>\n#include <boost/compute/types/struct.hpp>\n\n// simple test struct\nstruct data_struct\n{\n    int int_value;\n    float float_value;\n};\n\nBOOST_COMPUTE_ADAPT_STRUCT(data_struct, data_struct, (int_value, float_value))\n\n#include \"quirks.hpp\"\n#include \"check_macros.hpp\"\n#include \"context_setup.hpp\"\n\nnamespace compute = boost::compute;\n\nusing compute::placeholders::_1;\nusing compute::placeholders::_2;\n\nBOOST_AUTO_TEST_CASE(transform_plus_two)\n{\n    int data[] = { 1, 2, 3, 4 };\n    compute::vector<int> vector(4, context);\n    compute::copy_n(data, 4, vector.begin(), queue);\n\n    compute::transform(\n        vector.begin(), vector.end(), vector.begin(),\n        compute::bind(compute::plus<int>(), _1, 2),\n        queue\n    );\n\n    CHECK_RANGE_EQUAL(int, 4, vector, (3, 4, 5, 6));\n}\n\nBOOST_AUTO_TEST_CASE(transform_pow_two)\n{\n    float data[] = { 2, 3, 4, 5 };\n    compute::vector<float> vector(4, context);\n    compute::copy_n(data, 4, vector.begin(), queue);\n\n    compute::transform(\n        vector.begin(), vector.end(), vector.begin(),\n        compute::bind(compute::pow<float>(), 2.0f, _1),\n        queue\n    );\n\n    compute::copy(vector.begin(), vector.end(), data, queue);\n    BOOST_CHECK_CLOSE(data[0], 4.0f, 1e-4);\n    BOOST_CHECK_CLOSE(data[1], 8.0f, 1e-4);\n    BOOST_CHECK_CLOSE(data[2], 16.0f, 1e-4);\n    BOOST_CHECK_CLOSE(data[3], 32.0f, 1e-4);\n}\n\nBOOST_AUTO_TEST_CASE(find_if_equal)\n{\n    int data[] = { 1, 2, 3, 4 };\n    compute::vector<int> vector(4, context);\n    compute::copy_n(data, 4, vector.begin(), queue);\n\n    BOOST_CHECK(\n        compute::find_if(\n            vector.begin(), vector.end(),\n            compute::bind(compute::equal_to<int>(), _1, 3),\n            queue\n        ) == vector.begin() + 2\n    );\n}\n\nBOOST_AUTO_TEST_CASE(compare_less_than)\n{\n    int data[] = { 1, 2, 3, 4 };\n    compute::vector<int> vector(data, data + 4, queue);\n\n    int count = boost::compute::count_if(\n        vector.begin(), vector.end(),\n        compute::bind(compute::less<int>(), _1, 3),\n        queue\n    );\n    BOOST_CHECK_EQUAL(count, 2);\n\n    count = boost::compute::count_if(\n        vector.begin(), vector.end(),\n        compute::bind(compute::less<int>(), 3, _1),\n        queue\n    );\n    BOOST_CHECK_EQUAL(count, 1);\n}\n\nBOOST_AUTO_TEST_CASE(subtract_ranges)\n{\n    int data1[] = { 1, 2, 3, 4 };\n    int data2[] = { 4, 3, 2, 1 };\n\n    compute::vector<int> vector1(data1, data1 + 4, queue);\n    compute::vector<int> vector2(data2, data2 + 4, queue);\n\n    compute::vector<int> result(4, context);\n\n    compute::transform(\n        vector1.begin(),\n        vector1.end(),\n        vector2.begin(),\n        result.begin(),\n        compute::bind(compute::minus<int>(), _1, _2),\n        queue\n    );\n    CHECK_RANGE_EQUAL(int, 4, result, (-3, -1, 1, 3));\n\n    compute::transform(\n        vector1.begin(),\n        vector1.end(),\n        vector2.begin(),\n        result.begin(),\n        compute::bind(compute::minus<int>(), _2, _1),\n        queue\n    );\n    CHECK_RANGE_EQUAL(int, 4, result, (3, 1, -1, -3));\n\n    compute::transform(\n        vector1.begin(),\n        vector1.end(),\n        vector2.begin(),\n        result.begin(),\n        compute::bind(compute::minus<int>(), 5, _1),\n        queue\n    );\n    CHECK_RANGE_EQUAL(int, 4, result, (4, 3, 2, 1));\n\n    compute::transform(\n        vector1.begin(),\n        vector1.end(),\n        vector2.begin(),\n        result.begin(),\n        compute::bind(compute::minus<int>(), 5, _2),\n        queue\n    );\n    CHECK_RANGE_EQUAL(int, 4, result, (1, 2, 3, 4));\n}\n\nBOOST_AUTO_TEST_CASE(clamp_values)\n{\n    int data[] = { 1, 2, 3, 4 };\n    compute::vector<int> vector(data, data + 4, queue);\n\n    compute::transform(\n        vector.begin(), vector.end(), vector.begin(),\n        compute::bind(compute::clamp<int>(), _1, 2, 3),\n        queue\n    );\n    CHECK_RANGE_EQUAL(int, 4, vector, (2, 2, 3, 3));\n}\n\nBOOST_AUTO_TEST_CASE(bind_custom_function)\n{\n    int data[] = { 1, 2, 3, 4 };\n    compute::vector<int> vector(data, data + 4, queue);\n\n    BOOST_COMPUTE_FUNCTION(int, x_if_odd_else_y, (int x, int y),\n    {\n        if(x & 1)\n            return x;\n        else\n            return y;\n    });\n\n    compute::transform(\n        vector.begin(), vector.end(), vector.begin(),\n        compute::bind(x_if_odd_else_y, _1, 9),\n        queue\n    );\n    CHECK_RANGE_EQUAL(int, 4, vector, (1, 9, 3, 9));\n\n    compute::copy(\n        data, data + 4, vector.begin(), queue\n    );\n\n    compute::transform(\n        vector.begin(), vector.end(), vector.begin(),\n        compute::bind(x_if_odd_else_y, 2, _1),\n        queue\n    );\n    CHECK_RANGE_EQUAL(int, 4, vector, (1, 2, 3, 4));\n}\n\nBOOST_AUTO_TEST_CASE(bind_struct)\n{\n    if(bug_in_struct_assignment(device)){\n        std::cerr << \"skipping bind_struct test\" << std::endl;\n        return;\n    }\n\n    BOOST_COMPUTE_FUNCTION(int, add_struct_value, (int x, data_struct s),\n    {\n        return s.int_value + x;\n    });\n\n    data_struct data;\n    data.int_value = 3;\n    data.float_value = 4.56f;\n\n    int input[] = { 1, 2, 3, 4 };\n    compute::vector<int> vec(input, input + 4, queue);\n\n    compute::transform(\n        vec.begin(), vec.end(), vec.begin(),\n        compute::bind(add_struct_value, _1, data),\n        queue\n    );\n    CHECK_RANGE_EQUAL(int, 4, vec, (4, 5, 6, 7));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f6b979ce83e675a7392eb2b0679e7094bae2fb68", "size": 6253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_functional_bind.cpp", "max_stars_repo_name": "roshanr95/compute", "max_stars_repo_head_hexsha": "377e509acd16af466cdb133d70e2dcd525ec1a87", "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_functional_bind.cpp", "max_issues_repo_name": "roshanr95/compute", "max_issues_repo_head_hexsha": "377e509acd16af466cdb133d70e2dcd525ec1a87", "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_functional_bind.cpp", "max_forks_repo_name": "roshanr95/compute", "max_forks_repo_head_hexsha": "377e509acd16af466cdb133d70e2dcd525ec1a87", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-11-26T11:52:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T07:42:58.000Z", "avg_line_length": 26.2731092437, "max_line_length": 79, "alphanum_fraction": 0.589477051, "num_tokens": 1723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.5491944305598153}}
{"text": "#include \"path_finding.h\"\n\n#include \"error_handling.h\"\n#include \"rover.h\"\n#include \"geometry.h\"\n#include \"robot_configuration.h\"\n\n#include <opencv2/opencv.hpp>\n\n#include <vector>\n#include <queue>\n\n#include <boost/functional/hash.hpp>\n#include <boost/optional.hpp>\n#include <boost/range/algorithm/reverse.hpp>\n\n// A* path finding algorithm\ntemplate<typename TNode, typename T, typename FMinimalNodeCost, typename FForEachNeighbor, typename FIsGoal>\nboost::optional<TNode> GenericAStar(rbt::pose<T> const& poseStart, \n    rbt::point<T> const& ptEnd, \n    FMinimalNodeCost MinimalNodeCost, \n    FForEachNeighbor ForEachNeighbor,\n\tFIsGoal IsGoal\n) {\n    auto GreaterDistance = [&](TNode const& lhs, TNode const& rhs) noexcept {\n        return (lhs.Position() - ptEnd).Abs() + lhs.m_fCost > (rhs.Position() - ptEnd).Abs() + rhs.m_fCost;\n    };\n\n    std::priority_queue<TNode, std::vector<TNode>, decltype(GreaterDistance)> queue(GreaterDistance);\n    \n    TNode nodeStart(poseStart);\n    queue.push(nodeStart);\n    MinimalNodeCost(nodeStart) = nodeStart.m_fCost;\n\n    while(!queue.empty()) {\n        auto const nodeTop = queue.top();\n        queue.pop();\n\n        if(MinimalNodeCost(nodeTop) < nodeTop.m_fCost) continue;\n\n        if(IsGoal(nodeTop, ptEnd)) return nodeTop;\n\n        ForEachNeighbor(\n            nodeTop, \n            [&](TNode const& nodeNeighbor) {\n                if(rbt::assign_min(MinimalNodeCost(nodeNeighbor), nodeNeighbor.m_fCost)) {\n                    queue.push(nodeNeighbor);\n                }\n            });\n    }\n\n    return boost::none;\n}\n\nstd::vector<rbt::point<double>> FindPath(cv::Mat matn, rbt::pose<double> const& posefStart, rbt::point<double> const& ptfEnd) {\n    cv::Mat matnEroded;\n    auto const nMaxExtent = std::max(c_nRobotWidth/c_nScale, c_nRobotHeight/c_nScale);\n    cv::erode(\n        matn, \n        matnEroded, \n        cv::Mat::ones(nMaxExtent, nMaxExtent, CV_8U)\n    );\n    \n    // Include costs of traveling close to an obstacle in calculation\n    cv::Mat matnGauss;\n    auto const nMaxExtentOdd = 2*nMaxExtent + 1;\n    cv::GaussianBlur(matnEroded, matnGauss, cv::Size(nMaxExtentOdd, nMaxExtentOdd), 0, 0);\n\n    float aanMinimalCost[c_nMapExtent][c_nMapExtent];\n    std::fill_n(&aanMinimalCost[0][0], c_nMapExtent*c_nMapExtent, std::numeric_limits<float>::max());\n\n    struct node {\n        node() {}\n        node(rbt::pose<int> const& pose) : m_pt(pose.m_pt), m_fCost(0) {}\n        node(rbt::point<int> const& pt, float fCost) : m_pt(pt), m_fCost(fCost) {}\n\n\t\trbt::point<int> Position() const { return m_pt; }\n\n        rbt::point<int> m_pt; // in grid coordinates\n        float m_fCost;\n    };\n\n    auto MinimalNodeCost = [&](node const& node) noexcept -> float& {\n        return aanMinimalCost[node.m_pt.x][node.m_pt.y];\n    };\n\n    auto ForEachNeighbor = [&](node const& n, auto fn) noexcept {\n        for(int x = -1; x <= 1; ++x) {\n            for(int y = -1; y <= 1; ++y) {\n                auto const ptNext = n.m_pt + rbt::size<int>(x, y);\n                if((0!=x || 0!=y)\n                && 128<matnGauss.at<std::uint8_t>(ptNext.y, ptNext.x)) {\n                    fn(node(\n                        ptNext,\n                        n.m_fCost + (0==x || 0==y ? 1.0f : M_SQRT2) * (1 + (255 - matnGauss.at<std::uint8_t>(ptNext.y, ptNext.x))/10)\n                    ));\n                }\n            }\n        }\n    };\n\tauto IsGoal = [](node const& n, rbt::point<int> const& ptnEnd) {\n\t\treturn n.m_pt == ptnEnd;\n\t};\n\n\tauto const posenStart = ToGridCoordinate(posefStart);\n\n    std::vector<rbt::point<double>> vecptfResult;\n    if(auto onode = GenericAStar<node>(posenStart, ToGridCoordinate(ptfEnd), MinimalNodeCost, ForEachNeighbor, IsGoal)) {\n        vecptfResult.emplace_back(ptfEnd);\n        auto const ptnStart = posenStart.m_pt;\n        for(auto nodePrev = *onode; nodePrev.m_pt!=ptnStart; ) {\n            float fMinCost = std::numeric_limits<float>::max();\n            node nodeMin;\n            ForEachNeighbor(\n                nodePrev,\n                [&](node const& node) {\n                    if(rbt::assign_min(fMinCost, MinimalNodeCost(node))) {\n                        nodeMin = node;\n                    }\n                }\n            );\n\n            nodePrev = nodeMin;\n            vecptfResult.emplace_back(ToWorldCoordinate(rbt::point<double>(nodeMin.m_pt)));\n        }\n    }\n    return vecptfResult;\n}\n\n\nnamespace {\n    struct config_space_node {\n\t\tconfig_space_node() {}\n        config_space_node(rbt::pose<double> const& pose) : m_pose(pose) {}\n        \n\t\trbt::point<double> Position() const { return m_pose.m_pt; }\n\t\t\n\t\tint RoundedYaw() const { return (int)std::round(m_pose.m_fYaw*100); }\n\t\trbt::point<int> RoundedPosition() const { \n\t\t\treturn rbt::point<int>((int)std::round(m_pose.m_pt.x), (int)std::round(m_pose.m_pt.y));\n\t\t}\n        rbt::pose<double> m_pose;\n\n\t\t// as used for robot commands, encoder ticks / s?\n        int m_nSpeedLeft = 0;\n        int m_nSpeedRight = 0;\n\n        // path cost\n        float m_fCost = 0;\n\n\t\tconfig_space_node const* m_pnodeParent = nullptr;\n\n        friend bool operator==(config_space_node const& lhs, config_space_node const& rhs) {\n            return lhs.RoundedPosition()==rhs.RoundedPosition()\n\t\t\t\t&& lhs.RoundedYaw()==rhs.RoundedYaw()\n                && lhs.m_nSpeedLeft==rhs.m_nSpeedLeft\n                && rhs.m_nSpeedRight==rhs.m_nSpeedRight;\n        }\n    };\n\n\tconstexpr int c_nSpeedStep = 100;\n\tconstexpr double c_fTimeStep = 0.2; // s\n\tconst float c_fHighTravelDistance = encoderTicksToCm(c_nMaxSpeed*0.8*c_fTimeStep);\n}\n\nnamespace std {\n\ttemplate <> struct hash<config_space_node> {\n\t\tsize_t operator()(config_space_node const& node) const {\n\t\t\tstd::size_t seed = 0;\n\t\t\tauto pt = node.RoundedPosition();\n\t\t\tboost::hash_combine(seed, pt.x);\n\t\t\tboost::hash_combine(seed, pt.y);\n\t\t\tboost::hash_combine(seed, node.RoundedYaw());\n\t\t\tboost::hash_combine(seed, node.m_nSpeedLeft);\n\t\t\tboost::hash_combine(seed, node.m_nSpeedRight);\n\t\t\treturn seed;\n\t\t}\n\t};\n}\n\nstd::vector<rbt::pose<double>> PathConfigurationSpace(cv::Mat matn, rbt::pose<double> const& posefStart, rbt::point<double> const& ptfEnd) {\n    auto const vecptf = FindPath(matn, posefStart, ptfEnd);\n\n\t// TODO: Share code?\n\tcv::Mat matnEroded;\n    auto const nMaxExtent = std::max(c_nRobotWidth/c_nScale, c_nRobotHeight/c_nScale);\n    cv::erode(\n        matn, \n        matnEroded, \n        cv::Mat::ones(nMaxExtent, nMaxExtent, CV_8U)\n    );\n    \n    cv::Mat matnGauss;\n    auto const nMaxExtentOdd = 2*nMaxExtent + 1;\n    cv::GaussianBlur(matnEroded, matnGauss, cv::Size(nMaxExtentOdd, nMaxExtentOdd), 0, 0);\n\n\tcv::Mat matnPath = cv::Mat::zeros(matn.size(), CV_8U);\n\trbt::point<int> ptnPrev = ToGridCoordinate(vecptf.front());\n\tboost::for_each(vecptf, [&](rbt::point<double> const& ptf) {\n\t\tauto const ptnGrid = ToGridCoordinate(ptf);\n        cv::line(matnPath, ptnPrev, ptnGrid, cv::Scalar(255), 50/c_nScale);\n        ptnPrev = ptnGrid;\n\t});\n\n\tint cExpanded = 0;\n\tstd::unordered_map<config_space_node, float> mapnodefCosts;\n\tauto onode = GenericAStar<config_space_node>(\n\t\tposefStart, \n\t\t// Calculating a longer path in configuration space takes too much time to compute due to large state space.\n\t\t*(vecptf.end() - 80), \n\t\t[&](config_space_node const& node) noexcept -> float& {\n\t\t\treturn mapnodefCosts.emplace(node, std::numeric_limits<float>::max()).first->second;\n\t\t},\n\t\t[&](config_space_node const& node, auto fn) noexcept {\n\t\t\t++cExpanded;\n\n\t\t\tauto const pnodeParent = [&] {\n\t\t\t\tauto const itpair = mapnodefCosts.find(node);\n\t\t\t\tASSERT(itpair!=mapnodefCosts.end());\n\t\t\t\treturn &itpair->first;\n\t\t\t}();\n\n\t\t\tfor(int nStepLeft = -1; nStepLeft <= 1; ++nStepLeft) {\n\t\t\t\t// [decelerate both, left, right, no change, accelerate right, left, both]\n\t\t\t\tfor(int nStepRight = -1; nStepRight <= 1; ++nStepRight) {\n\t\t\t\t\t// -> Calculate new positions / angle \n\t\t\t\t\tauto nodeNeighbor = node;\n\t\t\t\t\tnodeNeighbor.m_pnodeParent = pnodeParent;\n\t\t\t\t\tnodeNeighbor.m_nSpeedLeft += nStepLeft * c_nSpeedStep;\n\t\t\t\t\tnodeNeighbor.m_nSpeedRight += nStepRight * c_nSpeedStep;\n\n\t\t\t\t\tif(std::abs(nodeNeighbor.m_nSpeedLeft)<=c_nMaxSpeed\n\t\t\t\t\t&& std::abs(nodeNeighbor.m_nSpeedRight)<=c_nMaxSpeed\n\t\t\t\t\t&& std::abs(nodeNeighbor.m_nSpeedRight-nodeNeighbor.m_nSpeedLeft)<=400) \n\t\t\t\t\t{\n\t\t\t\t\t\tnodeNeighbor.m_pose = UpdatePose(\n\t\t\t\t\t\t\tnode.m_pose, \n\t\t\t\t\t\t\tnodeNeighbor.m_nSpeedLeft*c_fTimeStep, \n\t\t\t\t\t\t\tnodeNeighbor.m_nSpeedRight*c_fTimeStep\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tcv::LineIterator itpt(\n\t\t\t\t\t\t\tmatn, \n\t\t\t\t\t\t\tToGridCoordinate(node.Position()), \n\t\t\t\t\t\t\tToGridCoordinate(nodeNeighbor.Position())\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tfloat fWeightedCost = 0;\n\t\t\t\t\t\tfor(int i = 0; i < itpt.count; ++i, ++itpt) {    \t\n\t\t\t\t\t\t\tauto const pt = rbt::point<int>(itpt.pos());\n\t\t\t\t\t\t\t// -> check if still in range of shortest path \n\t\t\t\t\t\t\tif(matnPath.at<std::uint8_t>(pt.y, pt.x)<255) {\n\t\t\t\t\t\t\t\tgoto outside_range;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// integrate costs over node.m_pt -> nodeNeighbor.m_pt\n\t\t\t\t\t\t\tfWeightedCost += std::pow((255.0 - matnGauss.at<std::uint8_t>(pt.y, pt.x))/30, 2);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfWeightedCost = std::max(1.f, fWeightedCost/itpt.count);\n\t\t\t\t\t\t\tfloat const fDistance = (nodeNeighbor.Position()-node.Position()).Abs();\n\t\t\t\t\t\t\t// Penalize several short moves, i.e., slow moves\n\t\t\t\t\t\t\tnodeNeighbor.m_fCost += fDistance * std::max(1.0, std::pow(c_fHighTravelDistance/fDistance, 2)) * fWeightedCost;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfn(nodeNeighbor);\n\noutside_range: \n\t\t\t\t\t\t;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t[](config_space_node const& node, rbt::point<double> const ptfEnd) {\n\t\t\treturn (node.m_pose.m_pt - ptfEnd).SqrAbs() < c_nScale*c_nScale;\n\t\t}\n\t);\n\n\tstd::cout << \"Discovered \" << mapnodefCosts.size() << \" states, \" << cExpanded << \" expanded.\" << std::endl;\n\tstd::vector<rbt::pose<double>> vecposef;\n\tif(onode) {\t\n\t\tauto const* pnodeNext = &*onode;\n\t\twhile(pnodeNext) {\n\t\t\tstd::cout << pnodeNext->m_pose << \n\t\t\t\" (\" << pnodeNext->m_nSpeedLeft << \", \" << pnodeNext->m_nSpeedRight << \") \" << std::endl;\n\n\t\t\tvecposef.emplace_back(pnodeNext->m_pose);\n\t\t\tpnodeNext = pnodeNext->m_pnodeParent;\n\t\t}\n\t\tboost::reverse(vecposef);\n\t} \n\treturn vecposef;\n}", "meta": {"hexsha": "8b879a6c3b4f05dc81185b24f6bcdfe4863d9ae0", "size": 10041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "raspberry/path_finding.cpp", "max_stars_repo_name": "stheophil/MappingRover2", "max_stars_repo_head_hexsha": "25d968a4f27016a3eb61b70e48d3f137887d440c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-11-12T11:12:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T02:15:23.000Z", "max_issues_repo_path": "raspberry/path_finding.cpp", "max_issues_repo_name": "stheophil/MappingRover2", "max_issues_repo_head_hexsha": "25d968a4f27016a3eb61b70e48d3f137887d440c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "raspberry/path_finding.cpp", "max_forks_repo_name": "stheophil/MappingRover2", "max_forks_repo_head_hexsha": "25d968a4f27016a3eb61b70e48d3f137887d440c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-11-12T03:10:28.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-02T21:38:21.000Z", "avg_line_length": 34.2696245734, "max_line_length": 140, "alphanum_fraction": 0.6282242805, "num_tokens": 2900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.5491893699394098}}
{"text": "#include \"core/hosvd.hpp\"\n#include \"video/video.hpp\"\n#include \"utils/utils.hpp\"\n#include \"tests/tests.hpp\"\n#include \"core/compression.hpp\"\n#include <iostream>\n#include <random>\n#include <chrono>\n#include <Eigen/Eigen>\n#include <Eigen/SVD>\n#include <fstream>\n#include <charconv>\n#include <args.hxx>\n#include <filesystem>\n#include <thread>\n\n// CRT's memory leak detection\n#ifndef NDEBUG \n#if defined(_MSC_VER)\n#define _CRTDBG_MAP_ALLOC\n#include <crtdbg.h>\n#endif\n#endif\n\nvoid benchmarkSVD(int sx, int sy)\n{\n\tstd::default_random_engine rng;\n\tstd::normal_distribution<float> dist;\n\n\tusing namespace Eigen;\n\tMatrixXf testMat(sx, sy);\n\tfor (int i = 0; i < sx; ++i)\n\t\tfor (int j = 0; j < sy; ++j)\n\t\t\ttestMat(i, j) = dist(rng);\n\n\tauto start = std::chrono::high_resolution_clock::now();\n\tBDCSVD<MatrixXf> svd(testMat);\n\tauto end = std::chrono::high_resolution_clock::now();\n\n\tstd::cout << \"SVD takes \" << std::chrono::duration<float>(end - start).count() << std::endl;\n\n\tstd::cout << svd.singularValues().size() << std::endl;\n}\n\n\ntemplate<int K, int Dim>\nvoid flattenTest(Tensor<float, Dim>& tensor, float& sum)\n{\n\tauto start = std::chrono::high_resolution_clock::now();\n\tauto m = tensor.template flatten<K>();\n\tauto end = std::chrono::high_resolution_clock::now();\n\tfloat t = std::chrono::duration<float>(end - start).count();\n\tstd::cout << \"Flatten in dimension \" << K << \"  \\t\" << std::chrono::duration<float>(end - start).count() << std::endl;\n\t//\tm *= 2.14f;\n\t//\tsum += m.trace();\n\n\tstart = std::chrono::high_resolution_clock::now();\n\ttensor.template set<K>(m);\n\tend = std::chrono::high_resolution_clock::now();\n\tstd::cout << \"Unflatten in dimension \" << K << \"\\t\" << std::chrono::duration<float>(end - start).count() << std::endl;\n\tt += std::chrono::duration<float>(end - start).count();\n\tsum += t;//tensor.norm()\n}\n\ntemplate<int Dim>\nvoid benchmarkTensor(const std::array<int, Dim>& _sizeVec)\n{\n\tstd::cout << \"Benchmarking a tensor with size \" << _sizeVec << \"^\" << Dim << std::endl;\n\n\tstd::default_random_engine rng;\n\tstd::uniform_real_distribution<float> dist;\n\n\tauto start = std::chrono::high_resolution_clock::now();\n\n\tTensor<float, Dim> tensor(_sizeVec);\n\ttensor.set([&](auto) { return dist(rng); });\n\t\n\tauto end = std::chrono::high_resolution_clock::now();\n\tstd::cout << \"Fill with random elements \" << std::chrono::duration<float>(end - start).count() << std::endl;\n\n\tfloat sum = 0.f;\n\t//for (int k = 0; k < Dim; ++k)\n\n\tflattenTest<0>(tensor, sum);\n\tflattenTest<1>(tensor, sum);\n\tflattenTest<2>(tensor, sum);\n\tflattenTest<3>(tensor, sum);\n\n\tstart = std::chrono::high_resolution_clock::now();\n\tconst auto&[U, C] = hosvdInterlaced(tensor, truncation::Tolerance(0.05f));\n\tend = std::chrono::high_resolution_clock::now();\n\tstd::cout << \"hosvd                   \\t\" << std::chrono::duration<float>(end - start).count() << std::endl;\n\t\n\tstart = std::chrono::high_resolution_clock::now();\n\tauto tensor2 = multilinearProduct(U, C);\n\tend = std::chrono::high_resolution_clock::now();\n\tstd::cout << \"multilinear product     \\t\" << std::chrono::duration<float>(end - start).count() << std::endl;\n\n\tstart = std::chrono::high_resolution_clock::now();\n\tauto tensor3 = tensor - tensor2;\n\tend = std::chrono::high_resolution_clock::now();\n\tstd::cout << \"subtract                \\t\" << std::chrono::duration<float>(end - start).count() << std::endl;\n\n\tstart = std::chrono::high_resolution_clock::now();\n\tsum += tensor3.norm();\n\tend = std::chrono::high_resolution_clock::now();\n\tstd::cout << \"norm                    \\t\" << std::chrono::duration<float>(end - start).count() << std::endl;\n\t\n\tstd::cout << sum + C.norm();\n}\n\nenum struct TruncationMode\n{\n\tZero,\n\tRank,\n\tTolerance,\n\tToleranceSum,\n};\n\nconst std::unordered_map<std::string, TruncationMode> TRUNCATION_NAMES =\n{ {\n\t{\"zero\", TruncationMode::Zero},\n\t{\"rank\", TruncationMode::Rank},\n\t{\"tolerance\", TruncationMode::Tolerance},\n\t{\"tolerance_sum\", TruncationMode::ToleranceSum},\n} };\n\nenum struct PixelFormat \n{\n\tRGB,\n\tYUV444\n};\n\nconst std::unordered_map<std::string, PixelFormat> PIXEL_FORMATS =\n{ {\n\t{\"RGB\", PixelFormat::RGB},\n\t{\"YUV444\", PixelFormat::YUV444}\n} };\n\nint main(int argc, char** args)\n{\n#ifndef NDEBUG \n#if defined(_MSC_VER)\n\t_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);\n\t//\t_CrtSetBreakAlloc(12613);\n#endif\n\tTests tests;\n\ttests.run();\n#endif\n\n\t//\tbenchmarkSVD(1920, 1080);\n\t//\tbenchmarkTensor<4>({3,800,600,14});\n\n\targs::ArgumentParser parser(\"HOSVD video compressor.\");\n\targs::HelpFlag help(parser, \"help\", \"display this help menu\", { 'h', \"help\" });\n\n\targs::ValueFlag<std::string> inputFile(parser, \"input file\",\n\t\t\"path of the video file to process\",\n\t\t{ 'i', \"input\" });\n\targs::ValueFlag<std::string> outputFile(parser, \"output file\",\n\t\t\"name of the output file\",\n\t\t{ 'o', \"output\" });\n\n\targs::MapFlag<std::string, TruncationMode> truncationMode(parser, \"truncation mode\",\n\t\t\"rule which is applied to truncate singular values\", { \"trunc\" }, TRUNCATION_NAMES,\n\t\tTruncationMode::Tolerance);\n\targs::MapFlag<std::string, PixelFormat> pixelFormat(parser, \"pixel format\",\n\t\t\"pixel format on which tensors are defined; independent of the format used by input/output videos\", { \"pix_fmt\" }, \n\t\tPIXEL_FORMATS, PixelFormat::YUV444);\n\targs::PositionalList<float> truncationThreshold(parser, \"truncation threshold\",\n\t\t\"values used for truncation in each dimension\");\n\targs::ValueFlag<int> framesPerBlock(parser, \"frames per block\",\n\t\t\"number of frames combined to a single tensor; if 0, the whole video is used (larger blocks allow for better compression but reduce encode and decode performance)\",\n\t\t{ \"block_size\" }, 24);\n\targs::ValueFlag<int> numThreads(parser, \"max threads\",\n\t\t\"maximum number of threads used during computations\",\n\t\t{ \"num_threads\" }, std::thread::hardware_concurrency() / 2);\n\n\ttry\n\t{\n\t\tparser.ParseCLI(argc, args);\n\t}\n\tcatch (const args::Help&)\n\t{\n\t\tstd::cout << parser;\n\t\treturn 0;\n\t}\n\tcatch (const args::ParseError& e)\n\t{\n\t\tstd::cerr << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\tcatch (const args::ValidationError& e)\n\t{\n\t\tstd::cerr << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\n\tnamespace fs = std::filesystem;\n\tconst fs::path inputPath = args::get(inputFile);\n\tif (!fs::exists(inputPath) || !fs::is_regular_file(inputPath))\n\t{\n\t\tstd::cerr << \"[Error] The input file \" << inputFile << \" does not exist.\\n\";\n\t\treturn 1;\n\t}\n\n\tEigen::setNbThreads(args::get(numThreads));\n\n\tauto process = [&](const auto& pixelFormat)\n\t{\n\t\tauto compressor = compression::HOSVDCompressor(pixelFormat);\n\t\tcompressor.setFramesPerBlock(args::get(framesPerBlock));\n\n\t\tstd::vector<float> rank = args::get(truncationThreshold);\n\t\tif (rank.size() < 4)\n\t\t{\n\t\t\tstd::cout << \"[Warning] Less than 4 truncation threshold values given. Default may not work with every truncation mode.\\n\";\n\t\t}\n\t\tswitch (args::get(truncationMode))\n\t\t{\n\t\tcase TruncationMode::Zero:\n\t\t\tcompressor.setTruncation(truncation::Zero());\n\t\t\tbreak;\n\t\tcase TruncationMode::Rank:\n\t\t\tif (rank.empty()) \n\t\t\t\trank.push_back(1);\n\t\t\tcompressor.setTruncation(truncation::Rank(std::vector<int>(rank.begin(), rank.end())));\n\t\t\tbreak;\n\t\tcase TruncationMode::Tolerance:\n\t\t\tif (rank.empty())\n\t\t\t\trank.push_back(0.1f);\n\t\t\tcompressor.setTruncation(truncation::Tolerance(rank));\n\t\t\tbreak;\n\t\tcase TruncationMode::ToleranceSum:\n\t\t\tif (rank.empty())\n\t\t\t\trank.push_back(0.2f);\n\t\t\tcompressor.setTruncation(truncation::ToleranceSum(rank));\n\t\t\tbreak;\n\t\t}\n\n\t\tif (inputPath.extension() == \"ten\")\n\t\t{\n\t\t\tstd::cout << \"Loading tensor file \" << args::get(inputFile) << \".\\n\";\n\t\t\tcompressor.load(args::get(inputFile));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"Loading video \" << args::get(inputFile) << \".\\n\";\n\t\t\tVideo video(args::get(inputFile));\n\t\t\tstd::cout << \"Applying HOSVD.\\n\";\n\t\t\tcompressor.encode(video);\n\t\t}\n\n\t\tstruct Stats\n\t\t{\n\t\t\tint min = std::numeric_limits<int>::max();\n\t\t\tint max = 0;\n\t\t\tint sum = 0;\n\t\t};\n\t\tconst auto& singularValues = compressor.singularValues();\n\t\tstd::vector<Stats> stats(singularValues.front().order());\n\n\t\tfor (auto s : singularValues)\n\t\t{\n\t\t\tfor (size_t dim = 0; dim < s.size().size(); ++dim)\n\t\t\t{\n\t\t\t\tconst int r = s.size()[dim];\n\t\t\t\tstats[dim].min = std::min(stats[dim].min, r);\n\t\t\t\tstats[dim].max = std::max(stats[dim].max, r);\n\t\t\t\tstats[dim].sum += r;\n\t\t\t}\n\t\t}\n\t\tstd::cout << \"Statistics of the resulting tensors: \\n dimension\\\\rank min max mean\\n\";\n\t\tfor (auto& stat : stats)\n\t\t\tstd::cout << stat.min << \" \" << stat.max << \" \" << stat.sum / singularValues.size() << \"\\n\";\n\n\t\tnamespace fs = std::filesystem;\n\t\tconst fs::path outputPath = args::get(outputFile);\n\t\tif (outputPath.extension() == \"ten\")\n\t\t{\n\t\t\tstd::cout << \"Saving tensors as \" << args::get(outputFile) << \".\\n\";\n\t\t\tcompressor.save(args::get(outputFile));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"Saving video as \" << args::get(outputFile) << \".\\n\";\n\t\t\tVideo video = compressor.decode();\n\t\t\tvideo.save(args::get(outputFile));\n\t\t}\n\t};\n\n\tswitch (args::get(pixelFormat))\n\t{\n\tcase PixelFormat::RGB:\n\t\tprocess(Video::RGB());\n\t\tbreak;\n\tcase PixelFormat::YUV444:\n\t\tprocess(Video::YUV444());\n\t\tbreak;\n\t}\n\n#if false\n\tVideo video(\"TestScene.mp4\");\n\t/*\tauto tensor = video.asTensor(0, 80, Video::YUV420());\n\t\tVideo video2(tensor, Video::FrameRate{1,24}, Video::YUV420());\n\t\tvideo2.save(\"TestSceneRestoredYUV420.avi\");*/\n\t/**/compression::HOSVDCompressor compressor;\n\tcompressor.setTruncation(truncation::Rank{ 2,100,100,10 });\n\tcompressor.encode(video);\n\tVideo video2 = compressor.decode();\n\tvideo2.save(\"TestSceneRestoredYUV4.avi\");\n#endif\n\n\treturn 0;\n}", "meta": {"hexsha": "446871820706bc08032fc0eaf889b6a5c214791b", "size": 9424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Thanduriel/tensorCompress", "max_stars_repo_head_hexsha": "5b571ed91064fb7ac1f2987f97340466f4487f44", "max_stars_repo_licenses": ["MIT"], "max_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": "Thanduriel/tensorCompress", "max_issues_repo_head_hexsha": "5b571ed91064fb7ac1f2987f97340466f4487f44", "max_issues_repo_licenses": ["MIT"], "max_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": "Thanduriel/tensorCompress", "max_forks_repo_head_hexsha": "5b571ed91064fb7ac1f2987f97340466f4487f44", "max_forks_repo_licenses": ["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.9174603175, "max_line_length": 166, "alphanum_fraction": 0.6670203735, "num_tokens": 2687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5491893535868921}}
{"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/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass HPS\n{\n\npublic:\n  void processFrame(const RealVectorView& input, RealVectorView output,\n                    index nHarmonics, double minFreq, double maxFreq,\n                    double sampleRate)\n  {\n    using namespace Eigen;\n    using namespace std;\n\n    ArrayXd::Index maxIndex;\n\n    ArrayXd mag = _impl::asEigen<Array>(input);\n    ArrayXd hps = mag;\n    index   nBins = mag.size();\n    double  binHz = sampleRate / ((nBins - 1) * 2);\n    index   minBin = lrint(minFreq / binHz);\n    index   maxBin = lrint(maxFreq / binHz);\n    double  f0 = 0;\n    double  confidence = 0;\n    double hpsSum = 0;\n\n    for (index i = 2; i < nHarmonics; i++)\n    {\n      index   hBins = nBins / i;\n      ArrayXd h = ArrayXd::Zero(hBins);\n      for (index j = 0; j < hBins; j++) h(j) = mag(j * i);\n      ArrayXd hp = ArrayXd::Zero(nBins);\n      hp.segment(0, hBins) = h;\n      hps = hps * hp;\n    }\n    hpsSum = hps.sum();\n\n    if (maxBin > minBin &&  hpsSum > 0)\n    {\n      hps = hps.segment(minBin, maxBin - minBin);\n      double maxVal = hps.maxCoeff(&maxIndex);\n      confidence = maxVal / hpsSum;\n      f0 = (minBin + maxIndex) * binHz;\n    }\n    output(0) = f0;\n    output(1) = confidence;\n  }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "693f2eacd97e5d10cc272b39f0abb75d8b13d577", "size": 1843, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/HPS.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/HPS.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/HPS.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 27.1029411765, "max_line_length": 74, "alphanum_fraction": 0.634834509, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5491893448819266}}
{"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// These functions are largely based off the the Ceres solver polynomial\n// functions which are not available through the public interface. The license\n// is below:\n//\n// Ceres Solver - A fast non-linear least squares minimizer\n// Copyright 2012 Google Inc. All rights reserved.\n// http://code.google.com/p/ceres-solver/\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,\n//   this list of conditions and the following disclaimer.\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// * Neither the name of Google Inc. nor the names of its contributors may be\n//   used to endorse or promote products derived from this software without\n//   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// Author: moll.markus@arcor.de (Markus Moll)\n//         sameeragarwal@google.com (Sameer Agarwal)\n\n#include \"theia/math/polynomial.h\"\n\n#include <Eigen/Core>\n#include <glog/logging.h>\n\n#include <cmath>\n#include <limits>\n\n#include \"theia/math/find_polynomial_roots_companion_matrix.h\"\n\nnamespace theia {\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::VectorXcd;\n\nbool FindPolynomialRoots(const VectorXd& polynomial,\n                         VectorXd* real,\n                         VectorXd* imaginary) {\n  return FindPolynomialRootsCompanionMatrix(polynomial, real, imaginary);\n}\n\n// Remove leading terms with zero coefficients.\nVectorXd RemoveLeadingZeros(const VectorXd& polynomial_in) {\n  int i = 0;\n  while (i < (polynomial_in.size() - 1) && polynomial_in(i) == 0) {\n    ++i;\n  }\n  return polynomial_in.tail(polynomial_in.size() - i);\n}\n\nVectorXd DifferentiatePolynomial(const VectorXd& polynomial) {\n  const int degree = polynomial.rows() - 1;\n  CHECK_GE(degree, 0);\n\n  // Degree zero polynomials are constants, and their derivative does\n  // not result in a smaller degree polynomial, just a degree zero\n  // polynomial with value zero.\n  if (degree == 0) {\n    return VectorXd::Zero(1);\n  }\n\n  VectorXd derivative(degree);\n  for (int i = 0; i < degree; ++i) {\n    derivative(i) = (degree - i) * polynomial(i);\n  }\n\n  return derivative;\n}\n\nVectorXd MultiplyPolynomials(const VectorXd& poly1, const VectorXd& poly2) {\n  VectorXd multiplied_poly = VectorXd::Zero(poly1.size() + poly2.size() - 1);;\n  for (int i = 0; i < poly1.size(); i++) {\n    for (int j = 0; j < poly2.size(); j++) {\n      multiplied_poly.reverse().operator()(i + j) +=\n          poly1.reverse()(i) * poly2.reverse()(j);\n    }\n  }\n  return multiplied_poly;\n}\n\nvoid DividePolynomial(const VectorXd& polynomial,\n                      const VectorXd& divisor,\n                      VectorXd* quotient,\n                      VectorXd* remainder) {\n  // If the divisor is higher degree than the polynomial then it cannot be\n  // divided so we simply return the remainder.\n  if (polynomial.size() < divisor.size()) {\n    *quotient = VectorXd::Zero(1);\n    *remainder = polynomial;\n    return;\n  }\n\n  VectorXd numerator = RemoveLeadingZeros(polynomial);\n  VectorXd denominator;\n  *quotient = VectorXd::Zero(numerator.size() - divisor.size() + 1);\n  while (numerator.size() >= divisor.size()) {\n    denominator = VectorXd::Zero(numerator.size());\n    denominator.head(divisor.size()) = divisor;\n\n    const double quotient_scalar = numerator(0) / denominator(0);\n    quotient->reverse().operator()(numerator.size() - divisor.size()) =\n        quotient_scalar;\n    denominator = denominator * quotient_scalar;\n    numerator = numerator - denominator;\n    // Sometimes there are floating point errors that result in a non-zero first\n    // value.\n    numerator(0) = 0;\n    numerator = RemoveLeadingZeros(numerator);\n  }\n  *remainder = numerator;\n}\n\nVectorXd AddPolynomials(const VectorXd& poly1, const VectorXd& poly2) {\n  if (poly1.size() > poly2.size()) {\n    VectorXd sum = poly1;\n    sum.tail(poly2.size()) += poly2;\n    return sum;\n  } else {\n    VectorXd sum = poly2;\n    sum.tail(poly1.size()) += poly1;\n    return sum;\n  }\n}\n\nvoid FindLinearPolynomialRoots(const VectorXd& polynomial,\n                               VectorXd* real,\n                               VectorXd* imaginary) {\n  CHECK_EQ(polynomial.size(), 2);\n  if (real != NULL) {\n    real->resize(1);\n    (*real)(0) = -polynomial(1) / polynomial(0);\n  }\n\n  if (imaginary != NULL) {\n    imaginary->setZero(1);\n  }\n}\n\nvoid FindQuadraticPolynomialRoots(const VectorXd& polynomial,\n                                  VectorXd* real,\n                                  VectorXd* imaginary) {\n  CHECK_EQ(polynomial.size(), 3);\n  const double a = polynomial(0);\n  const double b = polynomial(1);\n  const double c = polynomial(2);\n  const double D = b * b - 4 * a * c;\n  const double sqrt_D = sqrt(fabs(D));\n  if (real != NULL) {\n    real->setZero(2);\n  }\n  if (imaginary != NULL) {\n    imaginary->setZero(2);\n  }\n\n  // Real roots.\n  if (D >= 0) {\n    if (real != NULL) {\n      // Stable quadratic roots according to BKP Horn.\n      // http://people.csail.mit.edu/bkph/articles/Quadratics.pdf\n      if (b >= 0) {\n        (*real)(0) = (-b - sqrt_D) / (2.0 * a);\n        (*real)(1) = (2.0 * c) / (-b - sqrt_D);\n      } else {\n        (*real)(0) = (2.0 * c) / (-b + sqrt_D);\n        (*real)(1) = (-b + sqrt_D) / (2.0 * a);\n      }\n    }\n    return;\n  }\n\n  // Use the normal quadratic formula for the complex case.\n  if (real != NULL) {\n    (*real)(0) = -b / (2.0 * a);\n    (*real)(1) = -b / (2.0 * a);\n  }\n  if (imaginary != NULL) {\n    (*imaginary)(0) = sqrt_D / (2.0 * a);\n    (*imaginary)(1) = -sqrt_D / (2.0 * a);\n  }\n}\n\nvoid MinimizePolynomial(const VectorXd& polynomial,\n                        const double x_min,\n                        const double x_max,\n                        double* optimal_x,\n                        double* optimal_value) {\n  // Find the minimum of the polynomial at the two ends.\n  //\n  // We start by inspecting the middle of the interval. Technically\n  // this is not needed, but we do this to make this code as close to\n  // the minFunc package as possible.\n  *optimal_x = (x_min + x_max) / 2.0;\n  *optimal_value = EvaluatePolynomial(polynomial, *optimal_x);\n\n  const double x_min_value = EvaluatePolynomial(polynomial, x_min);\n  if (x_min_value < *optimal_value) {\n    *optimal_value = x_min_value;\n    *optimal_x = x_min;\n  }\n\n  const double x_max_value = EvaluatePolynomial(polynomial, x_max);\n  if (x_max_value < *optimal_value) {\n    *optimal_value = x_max_value;\n    *optimal_x = x_max;\n  }\n\n  // If the polynomial is linear or constant, we are done.\n  if (polynomial.rows() <= 2) {\n    return;\n  }\n\n  const VectorXd derivative = DifferentiatePolynomial(polynomial);\n  VectorXd roots_real;\n  if (!FindPolynomialRoots(derivative, &roots_real, NULL)) {\n    LOG(WARNING) << \"Unable to find the critical points of \"\n                 << \"the interpolating polynomial.\";\n    return;\n  }\n\n  // This is a bit of an overkill, as some of the roots may actually\n  // have a complex part, but its simpler to just check these values.\n  for (int i = 0; i < roots_real.rows(); ++i) {\n    const double root = roots_real(i);\n    if ((root < x_min) || (root > x_max)) {\n      continue;\n    }\n\n    const double value = EvaluatePolynomial(polynomial, root);\n    if (value < *optimal_value) {\n      *optimal_value = value;\n      *optimal_x = root;\n    }\n  }\n}\n\n// An iterative solver to find the closest root based on an initial guess. We\n// use Laguerre's method, which is a polynomial root finding method that\n// converges to a root with very high certainty. For multiple roots, the\n// convergence is linear, otherwise it is cubic.\ndouble FindRootIterativeLaguerre(const VectorXd& polynomial,\n                                 const double x0,\n                                 const double epsilon,\n                                 const int max_iter) {\n  const double kSmallestValue = 1e-10;\n\n  // Constant symbolic derivitives.\n  const VectorXd f_prime = DifferentiatePolynomial(polynomial);\n  const VectorXd f_prime_prime = DifferentiatePolynomial(f_prime);\n  const double k = static_cast<double>(polynomial.size());\n\n  double x = x0;\n\n  for (int i = 0; i < max_iter; i++) {\n    const double f_of_x = EvaluatePolynomial(polynomial, x);\n    if (std::abs(f_of_x) < kSmallestValue) {\n      break;\n    }\n\n    const double g = EvaluatePolynomial(f_prime, x) / f_of_x;\n    const double h = g * g - EvaluatePolynomial(f_prime_prime, x) / f_of_x;\n    const double denom_part = std::sqrt(std::abs((k - 1.0) * (k * h - g * g)));\n    const double denom = (g < 0) ? g - denom_part : g + denom_part;\n    const double delta =  k / denom;\n    if (std::abs(delta) < epsilon) {\n      break;\n    }\n\n    x -= delta;\n  }\n\n  return x;\n}\n\ndouble FindRootIterativeNewton(const Eigen::VectorXd& polynomial,\n                               const double x0,\n                               const double epsilon,\n                               const int max_iterations) {\n  double root = x0;\n  const Eigen::VectorXd derivative = DifferentiatePolynomial(polynomial);\n  double prev = std::numeric_limits<double>::max();\n  for (int i = 0; i < max_iterations && std::abs(prev - root) > epsilon; i++) {\n    prev = root;\n    root -= EvaluatePolynomial(polynomial, root) /\n            EvaluatePolynomial(derivative, root);\n  }\n  return root;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "f388dd84a16b9a0ba9fca9bb30f70d92e4a61acb", "size": 12105, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/math/polynomial.cc", "max_stars_repo_name": "nuernber/TheiaSfM", "max_stars_repo_head_hexsha": "0475f6b7b021a36d1d5c0d4a30608a2f45a1decb", "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/theia/math/polynomial.cc", "max_issues_repo_name": "nuernber/TheiaSfM", "max_issues_repo_head_hexsha": "0475f6b7b021a36d1d5c0d4a30608a2f45a1decb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/math/polynomial.cc", "max_forks_repo_name": "nuernber/TheiaSfM", "max_forks_repo_head_hexsha": "0475f6b7b021a36d1d5c0d4a30608a2f45a1decb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-11T04:09:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-11T04:09:18.000Z", "avg_line_length": 35.6029411765, "max_line_length": 80, "alphanum_fraction": 0.6592317224, "num_tokens": 2951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5491893415868571}}
{"text": "\n#include <deal.II/grid/tria.h>\n#include <deal.II/dofs/dof_handler.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_accessor.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.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/affine_constraints.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/numerics/data_out.h>\n\n#include <deal.II/lac/petsc_sparse_matrix.h>\n#include <deal.II/lac/petsc_vector.h>\n#include <deal.II/lac/petsc_solver.h>\n#include <deal.II/lac/petsc_precondition.h>\n\n#include <deal.II/base/utilities.h>\n\n#include <deal.II/lac/slepc_solver.h>\n\n#include <deal.II/base/timer.h>\n#include <deal.II/base/conditional_ostream.h>\n#include <deal.II/base/index_set.h>\n\n#include <deal.II/lac/sparsity_tools.h>\n\n#include <deal.II/distributed/tria.h>\n#include <deal.II/distributed/grid_refinement.h>\n\n#include <fstream>\n#include <iostream>\n#include <math.h>\n#include <random>\n#include <mpi.h>\n\nusing namespace dealii;\nclass ParallelKL\n{\npublic:\n  ParallelKL();\n  void run();\nprivate:\n  void make_grid();\n  void setup_system();\n  void assemble_system();\n  void solve();\n  void create_random_field();\n  void stats_for_random_field();\n  void output_results() const;\n  void output_results_parallel();\n\n  MPI_Comm mpi_communicator;\n\n  parallel::distributed::Triangulation<2> triangulation;\n\n  FE_Q<2>          fe;\n  DoFHandler<2>    dof_handler;\n\n  IndexSet         locally_owned_dofs;\n  IndexSet         locally_relevant_dofs;\n\n  AffineConstraints<double> constraints;\n\n  SparsityPattern      sparsity_pattern;\n\n  PETScWrappers::MPI::SparseMatrix system_mass_matrix;\n  PETScWrappers::MPI::SparseMatrix system_stiffness_matrix;\n\n  PETScWrappers::MPI::Vector randomfield_vector;\n\n  std::vector<double> eigenvalues;\n  std::vector<PETScWrappers::MPI::Vector> eigenvectors;\n\n  std::vector<double> normalized_gaussian;\n  std::default_random_engine generator;\n  std::normal_distribution<double> distribution;\n\n  unsigned int this_mpi_process, n_mpi_processes;\n\n  ConditionalOStream pcout;\n  TimerOutput        computing_timer;\n};\n\nParallelKL::ParallelKL()\n  : mpi_communicator(MPI_COMM_WORLD)\n  , triangulation(mpi_communicator,\n                  typename Triangulation<2>::MeshSmoothing(\n                  Triangulation<2>::smoothing_on_refinement |\n                  Triangulation<2>::smoothing_on_coarsening))\n  , fe(1)\n  , dof_handler(triangulation)\n  , this_mpi_process(Utilities::MPI::this_mpi_process(mpi_communicator))\n  , n_mpi_processes(Utilities::MPI::n_mpi_processes(mpi_communicator))\n  , pcout(std::cout,\n        (Utilities::MPI::this_mpi_process(mpi_communicator) == 0))\n  , computing_timer(mpi_communicator,\n                    pcout,\n                    TimerOutput::summary,\n                    TimerOutput::wall_times)\n{}\n\nvoid ParallelKL::make_grid()\n{\n  GridGenerator::hyper_cube(triangulation, -1, 1);\n  triangulation.refine_global(5);\n\n  //parallel console output\n  pcout << \"Number of active cells: \" << triangulation.n_active_cells()\n        << std::endl;\n}\n\nvoid ParallelKL::setup_system()\n{\n  TimerOutput::Scope t(computing_timer, \"setup\");\n\n  dof_handler.distribute_dofs(fe);\n  pcout << \"Number of degrees of freedom: \" << dof_handler.n_dofs()\n            << std::endl;\n\n  locally_owned_dofs = dof_handler.locally_owned_dofs();\n  DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs);\n\n  DynamicSparsityPattern dsp(locally_relevant_dofs);\n  DoFTools::make_sparsity_pattern(dof_handler, dsp);\n\n  SparsityTools::distribute_sparsity_pattern(dsp,\n                                             locally_owned_dofs,\n                                             mpi_communicator,\n                                             locally_relevant_dofs);\n\n  system_stiffness_matrix.reinit(locally_owned_dofs,\n                                 locally_owned_dofs,\n                                 dsp,\n                                 mpi_communicator);\n\n  system_mass_matrix.reinit(locally_owned_dofs,\n                            locally_owned_dofs,\n                            dsp,\n                            mpi_communicator);\n\n  randomfield_vector.reinit(locally_owned_dofs, mpi_communicator);\n\n  constraints.clear();\n  constraints.reinit(locally_relevant_dofs);\n  constraints.close();\n}\n\nvoid ParallelKL::assemble_system()\n{\n  TimerOutput::Scope t(computing_timer, \"assembly\");\n\n  system_stiffness_matrix = 0.;\n  system_mass_matrix = 0.;\n\n  QGauss<2> quadrature_formula(fe.degree + 1);\n\n  FEValues<2> fe_values(fe,\n                        quadrature_formula,\n                        update_values | update_gradients | update_JxW_values | update_quadrature_points);\n\n  const unsigned int dofs_per_cell = fe.dofs_per_cell;\n\n  FullMatrix<double> cell_mass_matrix(dofs_per_cell, dofs_per_cell);\n  FullMatrix<double> cell_stiffness_matrix(dofs_per_cell, dofs_per_cell);\n\n  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\n  for (const auto &cell : dof_handler.active_cell_iterators())\n    { if (cell->is_locally_owned())\n       {\n          fe_values.reinit(cell);\n          cell_mass_matrix = 0.;\n          cell_stiffness_matrix = 0.;\n\n          for (const unsigned int q_index : fe_values.quadrature_point_indices())\n            {\n              Point<2> quad_pointq = fe_values.quadrature_point(q_index);\n              for (const unsigned int i : fe_values.dof_indices())\n                for (const unsigned int j : fe_values.dof_indices())\n                  cell_mass_matrix(i, j) +=\n                    (fe_values.shape_value(i, q_index) * // grad phi_i(x_q)\n                    fe_values.shape_value(j, q_index) * // grad phi_j(x_q)\n                    fe_values.JxW(q_index));           // dx\n\n              for (const unsigned int l_index : fe_values.quadrature_point_indices())\n                {\n                  Point<2> quad_pointl = fe_values.quadrature_point(l_index);\n                  const double point_distance = quad_pointl.distance(quad_pointq);\n\n                  for (const unsigned int i : fe_values.dof_indices())\n                    for (const unsigned int j : fe_values.dof_indices())\n                        cell_stiffness_matrix(i, j) +=\n                        (exp(-0.5*point_distance/(0.05*0.05))*          // R(x,x')\n                        fe_values.shape_value(i, q_index) * // grad phi_i(x_q)\n                        fe_values.shape_value(j, l_index) * // grad phi_j(x_l)\n                        fe_values.JxW(q_index)*fe_values.JxW(l_index));           // dx\n                }\n            }\n          cell->get_dof_indices(local_dof_indices);\n\n          constraints.distribute_local_to_global(cell_stiffness_matrix,\n                                         local_dof_indices,\n                                         system_stiffness_matrix);\n\n          constraints.distribute_local_to_global(cell_mass_matrix,\n                                         local_dof_indices,\n                                         system_mass_matrix);\n       }\n    }\n\nsystem_mass_matrix.compress(VectorOperation::add);\nsystem_stiffness_matrix.compress(VectorOperation::add);\n\n//system_mass_matrix.print(std::cout);\n//system_stiffness_matrix.print(std::cout);\n}\n\nvoid ParallelKL::solve()\n{\n  const unsigned int num_eigenpairs_requested = 100;\n\n  eigenvalues.resize(num_eigenpairs_requested);\n  eigenvectors.resize(num_eigenpairs_requested);\n\n  normalized_gaussian.resize(num_eigenpairs_requested);\n\n  for (unsigned int i = 0; i < num_eigenpairs_requested; ++i)\n    eigenvectors[i].reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n\n  SolverControl eigen_solver_control (10000, 1e-10);\n\n  SLEPcWrappers::SolverKrylovSchur eigensolver(eigen_solver_control, mpi_communicator);\n\n  eigensolver.set_which_eigenpairs(EPS_LARGEST_REAL);\n\n  eigensolver.set_problem_type(EPS_GHEP);\n\n  pcout << \"Beginning Eigensolve...\" << std::endl;\n  eigensolver.solve(system_stiffness_matrix,\n                    system_mass_matrix,\n                    eigenvalues,\n                    eigenvectors,\n                    num_eigenpairs_requested);\n\n  for (unsigned int i = 0; i < num_eigenpairs_requested; i++)\n  {\n    double temporary_sample = 0.0;\n\n    if (this_mpi_process == 0)\n      temporary_sample = distribution(generator);\n\n    double temporary_sum = 0.0;\n\n    MPI_Allreduce (&temporary_sample, &temporary_sum, 1, MPI_DOUBLE, MPI_SUM, mpi_communicator);\n\n    normalized_gaussian[i] = temporary_sum;\n\n  }\n}\n\nvoid ParallelKL::create_random_field()\n{\n  randomfield_vector = 0.0;\n\n  PETScWrappers::MPI::Vector tmp_locally_owned_vector(locally_owned_dofs, mpi_communicator);\n\n  for (unsigned int i = 0; i < eigenvalues.size(); i++)\n    {\n      const double multiplier = sqrt(eigenvalues[i])*normalized_gaussian[i];\n      tmp_locally_owned_vector = eigenvectors[i];\n      randomfield_vector.add(multiplier, tmp_locally_owned_vector);\n    }\n}\n\nvoid ParallelKL::stats_for_random_field()\n{\n  PETScWrappers::MPI::Vector relevent_randomfield_vector(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n  relevent_randomfield_vector = randomfield_vector;\n\n  QGauss<2> quadrature_formula(fe.degree + 1);\n\n  FEValues<2> fe_values(fe,\n                        quadrature_formula,\n                        update_values | update_JxW_values);\n\n  double vol_on_current_processor = 0.;\n  double random_field_volume_integral_on_current_processor = 0.;\n\n  std::vector<double> local_dof_values(fe.dofs_per_cell);\n  std::vector<double> current_function_values(quadrature_formula.size());\n\n  const FEValuesExtractors::Scalar r_field(0);\n\n  for (const auto &cell : dof_handler.active_cell_iterators())\n  { if (cell->is_locally_owned())\n       {\n          fe_values.reinit(cell);\n          cell->get_dof_values(relevent_randomfield_vector, local_dof_values.begin(), local_dof_values.end());\n          fe_values[r_field].get_function_values_from_local_dof_values(local_dof_values, current_function_values);\n\n          for (const unsigned int q_index : fe_values.quadrature_point_indices())\n            {\n              vol_on_current_processor  += fe_values.JxW(q_index);\n              random_field_volume_integral_on_current_processor += current_function_values[q_index]*fe_values.JxW(q_index);\n            }\n       }\n  }\n\n  double total_random_field_volume_integral = 0.0;\n  double total_volume = 0.0;\n\n  MPI_Allreduce (&random_field_volume_integral_on_current_processor, &total_random_field_volume_integral, 1, MPI_DOUBLE, MPI_SUM, mpi_communicator);\n  MPI_Allreduce (&vol_on_current_processor, &total_volume, 1, MPI_DOUBLE, MPI_SUM, mpi_communicator);\n\n  double volume_average_of_random_field = total_random_field_volume_integral/total_volume;\n\n  pcout << \"Volume Average of Random Field = \" << volume_average_of_random_field << std::endl;\n  pcout << \"Total Volume = \" << total_volume << std::endl;\n\n}\n\nvoid ParallelKL::output_results() const\n{\n  DataOut<2> data_out;\n  data_out.attach_dof_handler(dof_handler);\n  /*\n  Vector<float> subdomain(triangulation.n_active_cells());\n  for (unsigned int i = 0; i < subdomain.size(); ++i)\n      subdomain(i) = triangulation.locally_owned_subdomain();\n  data_out.add_data_vector(subdomain, \"subdomain\");\n*/\n  for (unsigned int i = 0; i < eigenvalues.size(); i++)\n  {\n    //std::cout << eigenvectors[i] << \"\\n\" << std::endl;\n    std::string tmpname = \"solution\";\n    tmpname += Utilities::int_to_string(i, 3);\n    //std::cout << \"Eigen_val = \" << eigenvalues[i] << \" \" << \"Normalized_gaussian = \" << normalized_gaussian[i] << \"\\n\"  << std::endl;\n    data_out.add_data_vector(eigenvectors[i], tmpname);\n  }\n\n  data_out.build_patches();\n  std::ofstream output(\"solution.vtk\");\n  data_out.write_vtk(output);\n}\n\nvoid ParallelKL::output_results_parallel()\n{\n    TimerOutput::Scope t(computing_timer, \"output parallel\");\n\n    PETScWrappers::MPI::Vector relevent_randomfield_vector(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    relevent_randomfield_vector = randomfield_vector;\n\n    DataOut<2> data_out;\n\n    // ############################################################\n    // #######                   OUTPUT                     #######\n    // ############################################################\n\n    data_out.add_data_vector(dof_handler, relevent_randomfield_vector,\n                               \"RandomField\");\n\n  /*\n    for (unsigned int i = 0; i < eigenvalues.size(); i++)\n      {\n        std::string tmpname = \"solution\";\n        tmpname += Utilities::int_to_string(i, 3);\n        data_out.add_data_vector(eigenvectors[i], tmpname);\n      }\n      */\n\n    std::vector<Vector<double>> buckling_eigenmodes_out;\n\n    buckling_eigenmodes_out.resize(eigenvalues.size());\n    for (unsigned int i = 0; i < eigenvalues.size(); ++i)\n      {\n        buckling_eigenmodes_out[i].reinit(dof_handler.n_dofs(), 0.0);\n        buckling_eigenmodes_out[i] = eigenvectors[i];\n        const std::string buckling_mode_string = std::string(\"EigenVector\") + Utilities::int_to_string(i, 2);\n\n        data_out.add_data_vector(dof_handler, buckling_eigenmodes_out[i],\n                                 buckling_mode_string);\n      }\n\n    // ############################################################\n    // #######                 WRITE VTU FILE               #######\n    // ############################################################\n    data_out.build_patches ();\n    const std::string filename = \"Solution.\" +\n                                  Utilities::int_to_string (this_mpi_process, 2) + \".vtu\";\n\n    std::ofstream output (filename.c_str());\n    data_out.write_vtu (output);\n    output.close();\n\n    // ############################################################\n    // #######                 WRITE PVTU FILE              #######\n    // ############################################################\n    if (this_mpi_process == 0)\n    {\n      std::vector<std::string> filenames;\n      for (unsigned int i=0; i < n_mpi_processes; ++i)\n        filenames.push_back (\"Solution.\" +\n                                  Utilities::int_to_string (i, 2) + \".vtu\");\n\n      std::ofstream master_output (\"Solution.pvtu\");\n\n      data_out.write_pvtu_record (master_output, filenames);\n    }\n}\n\nvoid ParallelKL::run()\n{\n  pcout << \"Running with \" << \"PETSc\" << \" on \" << Utilities::MPI::n_mpi_processes(mpi_communicator)\n          << \" MPI rank(s)...\" << std::endl;\n\n  make_grid();\n\n  setup_system();\n\n  pcout << \"   Number of active cells:       \"\n        << triangulation.n_global_active_cells() << std::endl\n        << \"   Number of degrees of freedom: \" << dof_handler.n_dofs()\n        << std::endl;\n\n  assemble_system();\n  solve();\n  create_random_field();\n  stats_for_random_field();\n\n  if (Utilities::MPI::n_mpi_processes(mpi_communicator) <= 32)\n    {\n      TimerOutput::Scope t(computing_timer, \"output\");\n      //output_results();\n      output_results_parallel();\n\n    }\n}\n\nint main(int argc, char* argv[])\n{\n  Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);\n\n  deallog.depth_console(0);\n\n  ParallelKL klexpansion_2d;\n  klexpansion_2d.run();\n  return 0;\n}\n", "meta": {"hexsha": "3c74c3692a9d68a6fbba534ded62ba21275e4aaa", "size": 15461, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/klexpansion.cpp", "max_stars_repo_name": "gh2546/Project_APMA4302", "max_stars_repo_head_hexsha": "e7db5dc5b2bb2d2aa8e32eced6af070f3fda03e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/klexpansion.cpp", "max_issues_repo_name": "gh2546/Project_APMA4302", "max_issues_repo_head_hexsha": "e7db5dc5b2bb2d2aa8e32eced6af070f3fda03e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/klexpansion.cpp", "max_forks_repo_name": "gh2546/Project_APMA4302", "max_forks_repo_head_hexsha": "e7db5dc5b2bb2d2aa8e32eced6af070f3fda03e6", "max_forks_repo_licenses": ["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.5379609544, "max_line_length": 148, "alphanum_fraction": 0.6447836492, "num_tokens": 3660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.549189334529426}}
{"text": "#include \"testsuite.h\"\n#include <blitz/array.h>\n#include <blitz/array.cc>\n#include <blitz/array/stencil-et.h>\n#include <blitz/array/stencilops.h>\n#include <blitz/array/stencil-et-macros.h>\n//#include <blitz/tinyvec-et.h>\n//#include <blitz/matrix.h>\n//#include <blitz/tinymatexpr.h>\n#include <random/uniform.h>\n\nBZ_USING_NAMESPACE(blitz)\n\n// Tests that the various stencil operators work with\n// expressions. Does NOT test that the stencils produce the correct\n// output, only that they compile and that the output is consistent\n// between different identical expressions.\n\ntypedef blitz::Array<double,1> array_1;\ntypedef blitz::Array<double,2> array_2;\ntypedef blitz::Array<double,3> array_3;\ntypedef Array<TinyVector<double, 2>, 2> array_2v;\ntypedef Array<TinyMatrix<double, 2, 2>, 2> array_2m;\ntypedef Array<TinyVector<double, 3>, 3> array_3v;\ntypedef Array<TinyMatrix<double, 3, 3>, 3> array_3m;\n\n// test with functors\nclass doubler {\npublic:\n  double operator()(double x) const {return 2.0*x;}\n  BZ_DECLARE_FUNCTOR(doubler);\n};\n\nclass multiplier {\npublic:\n  double operator()(double a, double b) const {return a*b;}\n  BZ_DECLARE_FUNCTOR2(multiplier);\n};\n/*\n// Test two expressions for equality\ntemplate<typename T1, typename T2>\nvoid test_expr(const T1& d1, const T2& d2)\n{\n  BZTEST(all(d1==d2));\n}\n*/\n#define test_expr(d1,d2) BZTEST(all((d1)==(d2)));\n\n// Test two vector expressions for equality\ntemplate<typename T1, typename T2>\nvoid test_vexpr(const T1& d1, const T2& d2)\n{\n  Array<typename T1::T_numtype, T1::rank_> a(d1),b(d2);\n  for(int i=0; i<T1::T_numtype::numElements(); ++i)\n    BZTEST(all(a[i]==b[i]));\n}\n\n// Test two matrix expressions for equality\ntemplate<typename T1, typename T2>\nvoid test_mexpr(const T1& d1, const T2& d2)\n{\n  // there appears to be no way to tell the size of a TinyMatrix... or to compare them.\n  // so for now we're happy just to have the call succeed.\n}\n\nBZ_DECLARE_DIFF(shifter) {\n  return A.shift(1,dim); }\n\nBZ_ET_STENCIL_DIFF(shifter, 1,1)\n\n\nint main()\n{\n  // create some arrays to operate on\n  const int sz=5;\n\n  ranlib::Uniform<float> rnd;\n  rnd.seed(42);\n\n  array_3 field3(sz,sz+1,sz+2), result3(sz,sz+1,sz+2),\n    fx(field3.shape()), fy(field3.shape()), fz(field3.shape());\n  for(int i=0; i<field3.size();++i) {\n    field3.data()[i]=rnd.random();\n    fx.data()[i]=rnd.random();\n    fy.data()[i]=rnd.random();\n    fz.data()[i]=rnd.random();\n  }\n  array_2 field2(sz,sz+1), result2(field2.shape());\n  field2=sin(0.5*(tensor::i+2*tensor::j));\n  array_3v vfield3(field3.shape());\n  vfield3[0]=fx;\n  vfield3[1]=fy;\n  vfield3[2]=fz;\n  array_2v vfield2(sz,sz+1);\n  vfield2[0]=vfield3(Range::all(), Range::all(), 0)[0];\n  vfield2[1]=vfield3(Range::all(), Range::all(), 0)[1];\n\n  doubler doubleit;\n  multiplier multiplyit;\n\n  // Now apply \"all\" possible stencil types to arrays and expressions,\n  // as well as recursive applications\n\n\n  // defined with BZ_ET_STENCIL:\n  test_expr(Laplacian2D(field2), Laplacian2D(1.0*field2));\n  test_expr(Laplacian2D(field2), 1.0*Laplacian2D(field2));\n  test_expr(Laplacian2D(const_cast<const array_2&>(field2)),\n\t    Laplacian2D(1.0*field2));\n  test_expr(Laplacian2D(Laplacian2D(field2)), \n\t    Laplacian2D(Laplacian2D(1.0*field2)));\n  test_expr(Laplacian2D(Laplacian2D(field2)), \n\t    Laplacian2D(1.0*Laplacian2D(field2)));\n  test_expr(Laplacian2D(Laplacian2D(field2+field2)), \n\t    Laplacian2D(Laplacian2D(field2)+Laplacian2D(field2)));\n  test_expr(Laplacian2D(field3), Laplacian2D(1.0*field3));\n\n  // and some more complicated expressions and assignments\n  result2(_bz_shrinkDomain(result2.domain(),shape(-1,-1),shape(1,1))) =\n    Laplacian2D(where(field2>0.5,0.,1.));\n  test_expr(result2(_bz_shrinkDomain(result2.domain(),shape(-1,-1),shape(1,1))), \n\t    Laplacian2D(where(field2>0.5,0.,1.)));\n  test_expr(where(Laplacian2D(field2)>0.5,0.,1.),\n\t    where(Laplacian2D(2*field2)>1,0.,1.));\n  test_expr(where(Laplacian2D(field2)>0.5, \n\t\t  0.0*field2(_bz_shrinkDomain(result2.domain(),shape(-1,-1),shape(1,1))), \n\t\t  0.0*field2(_bz_shrinkDomain(result2.domain(),shape(-1,-1),shape(1,1)))+2.0),\n\t    2*where(Laplacian2D(2*field2)>1.0, 0., 1.));\n  test_expr(Laplacian2D(2.0*field2), Laplacian2D(doubleit(field2)));\n  test_expr(Laplacian2D(field2*field3(0,Range(0,sz-1), Range(1,sz+1))), \n\t    Laplacian2D(multiplyit(field2, field3(0,Range(0,sz-1), Range(1,sz+1)))));\n\n  // reductions of stencil results\n  {\n    array_2 temp(Laplacian2D(field2));\n    BZTEST(sum(temp) == sum(Laplacian2D(field2)));\n    test_expr(sum(temp, tensor::j), sum(Laplacian2D(field2), tensor::j));\n  }\n  {\n    array_3 temp(Laplacian2D(field3));\n    BZTEST(sum(temp) == sum(Laplacian2D(field3)));\n    test_expr(sum(temp, tensor::k), sum(Laplacian2D(field3), tensor::k));\n  }\n\n  // and expressions involving index remappings. we do these on arrays\n  // with different sizes in all dimensions to make it less likely we\n  // don't detect a screwup\n  test_expr(shifter(field2,firstDim), \n\t    shifter(field2(tensor::i, tensor::j),firstDim));\n  {\n    array_2 temp(field2(tensor::j, tensor::i));\n    test_expr(shifter(temp,firstDim), \n\t      shifter(field2(tensor::j, tensor::i),firstDim));\n    test_expr(shifter(temp,secondDim), \n\t      shifter(field2(tensor::j, tensor::i),secondDim));\n  }\n  test_expr(shifter(field3,firstDim), \n\t    shifter(field3(tensor::i, tensor::j, tensor::k),firstDim));\n  test_expr(shifter(field3,thirdDim), \n\t    shifter(field3(tensor::i, tensor::j, tensor::k),thirdDim));\n\n  {\n    array_3 temp(shifter(field3,thirdDim));\n    test_expr(temp(tensor::i, tensor::k, tensor::j), \n\t      shifter(field3(tensor::i, tensor::k, tensor::j),secondDim));\n\t      }\n  {\n    array_3 temp(Laplacian3D(field3));\n    test_expr(temp(tensor::k, tensor::i, tensor::j),\n\t      Laplacian3D(field3(tensor::k, tensor::i, tensor::j)));\n  }\n  {\n    array_3 temp(field3.shape());\n    temp=field3(tensor::i, tensor::j, tensor::k)*field2(tensor::i, tensor::j);\n    test_expr(Laplacian3D(temp),\n\t      Laplacian3D(field3(tensor::i, tensor::j, tensor::k)*\n\t\t\t  field2(tensor::i, tensor::j)));\n    test_expr(mixed22(temp, firstDim, secondDim),\n\t      mixed22(field3(tensor::i, tensor::j, tensor::k)*\n\t\t      field2(tensor::i, tensor::j), firstDim, secondDim));\n  }\n  /* index placeholders don't work\n  { array_3 temp(field3.shape());\n    temp=100*tensor::k+10*tensor::j+tensor::i;\n    test_expr(Laplacian3D(temp), Laplacian3D(100*tensor::k+10*tensor::j+tensor::i));\n  }\n  */\n\n  // defined with BZ_ET_STENCIL2:\n  test_expr(div(vfield2[0],vfield2[1]),\n\t    div(vfield2[0],1.0*vfield2[1]));\n  test_expr(div(vfield2[0],vfield2[1]),\n\t    div(1.0*vfield2[0],vfield2[1]));\n  test_expr(div(vfield2[0],vfield2[1]),\n\t    div(1.0*vfield2[0],1.0*vfield2[1]));\n  test_expr(div(vfield2[0],vfield2[1]),\n\t    div(1.0*vfield2[0],const_cast<const array_2v&>(vfield2)[1]));\n  test_expr(div(vfield2[0],vfield2[1]),\n\t    div(const_cast<const array_2v&>(vfield2)[0],\n\t\tconst_cast<const array_2v&>(vfield2)[1]));\n\n  // defined with BZ_ET_STENCILM. \n  test_mexpr(Jacobian3D(vfield3),\n\t     Jacobian3D(const_cast<const array_3v&>(vfield3)));\n  test_mexpr(Jacobian3D(vfield3),\n\t     Jacobian3D(1.0*vfield3));\n  test_mexpr(Jacobian3D(const_cast<const array_3v&>(vfield3)),\n\t     Jacobian3D(1.0*vfield3));\n\n  // defined with BZ_ET_STENCILV\n  test_vexpr(grad3D(field3),\n\t     grad3D(const_cast<const array_3&>(field3)));\n  test_vexpr(grad3D(field3),\n\t     grad3D(1.0*field3));\n\n  // defined with BZ_ET_STENCIL_SCA\n  test_expr(div2D(vfield2),\n\t    div2D(const_cast<const array_2v&>(vfield2)));\n  test_expr(div2D(vfield2),\n\t    div2D(1.0*vfield2));\n\n  // defined with BZ_ET_STENCIL_DIFF\n  test_expr(central12(field3, firstDim),\n\t    central12(const_cast<const array_3&>(field3), firstDim));\n  test_expr(central12(field3, firstDim),\n\t    central12(1.0*field3, firstDim));\n\n  result2(_bz_shrinkDomain(result2.domain(),shape(0,-1),shape(0,1))) =\n    central12(where(field2>0.5,0.,1.), secondDim);\n  test_expr(result2(_bz_shrinkDomain(result2.domain(),shape(0,-1),shape(0,1))), \n\t    central12(where(field2>0.5,0.,1.), secondDim));\n  test_expr(where(central12(field2,firstDim)>0.5,0.,1.),\n\t    where(central12(2*field2, firstDim)>1,0.,1.));\n  test_expr(where(central12(field2, firstDim)>0.5, \n\t\t  0.0*field2(_bz_shrinkDomain(field2.domain(),shape(-1,0),shape(1,0))),\n\t\t  0.0*field2(_bz_shrinkDomain(field2.domain(),shape(-1,0),shape(1,0)))+2.0),\n\t    2*where(central12(2*field2, firstDim)>1.0, 0., 1.));\n  test_expr(central12(sin(1.0*field3),thirdDim), \n\t    central12(1.0*sin(field3), thirdDim));\n  result2 = pow(field3(Range::all(), 1, Range(0,sz)), field2);\n  test_expr(central12(result2, secondDim), \n\t    central12(pow(field3(Range::all(), 1, Range(0,sz)), 1.0*field2), secondDim));\n\n  // defined with BZ_ET_STENCIL_MULTIDIFF\n  test_expr(central12(vfield3, firstDim, secondDim),\n\t    central12(const_cast<const array_3v&>(vfield3), firstDim, secondDim));\n\n  array_3v ee(1.0*vfield3);\n  test_expr(central12(vfield3, firstDim, secondDim),\n\t    central12(1.0*vfield3, firstDim, secondDim));\n  test_expr(where(central12(vfield2, firstDim, secondDim)>0.5, \n\t\t  0.0*field2(_bz_shrinkDomain(field2.domain(),shape(0,-1),shape(0,1))),\n\t\t  0.0*field2(_bz_shrinkDomain(field2.domain(),shape(0,-1),shape(0,1)))+2.0),\n\t    2*where(central12(2*vfield2, firstDim, secondDim)>1.0, 0., 1.));\n\n  // defined with BZ_ET_STENCIL_DIFF2\n  test_expr(mixed22(field3, firstDim, secondDim),\n\t    mixed22(const_cast<const array_3&>(field3), firstDim, secondDim));\n  test_expr(mixed22(field3, firstDim, secondDim),\n\t    mixed22(1.0*field3, firstDim, secondDim));\n  test_expr(where(mixed22(field3, thirdDim, secondDim)>0.5, \n\t\t  0.0*field3(_bz_shrinkDomain(field3.domain(),shape(0,-1,-1),shape(0,1,1))),\n\t\t  0.0*field3(_bz_shrinkDomain(field3.domain(),shape(0,-1,-1),shape(0,1,1)))+2.0),\n\t    2*where(mixed22(2*field3, thirdDim, secondDim)>1.0, 0., 1.));\n\n    return 0;\n}\n\n", "meta": {"hexsha": "b23e97973ca7fa02be245fd5bfd651a79e32a231", "size": 9847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/stencil-et.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/stencil-et.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/stencil-et.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": 36.6059479554, "max_line_length": 87, "alphanum_fraction": 0.6869097187, "num_tokens": 3385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5491305090299619}}
{"text": "/**\n * @file radauthreetimestepping_main.cc\n * @brief NPDE homework RadauThreeTimestepping\n * @author Erick Schulz\n * @date 08/04/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include <lf/assemble/assemble.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\n#include <Eigen/Core>\n#include <iostream>\n#include <memory>\n\n#include \"radauthreetimestepping.h\"\n#include \"radauthreetimesteppingode.h\"\n\nusing namespace RadauThreeTimestepping;\n\nint main(int /*argc*/, char ** /*argv*/) {\n  /* Solving the ODE problem */\n  // This function prints to the terminal the convergence rates and average rate\n  // of a convergence study performed for the ODE (d/dt)y = -y.\n  testConvergenceTwoStageRadauLinScalODE();\n\n  /* Solving the parabolic heat equation */\n  // Create a Lehrfem++ square tensor product mesh\n  lf::mesh::utils::TPTriagMeshBuilder builder(\n      std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2));\n  // Set mesh parameters following the Builder pattern\n  // Domain is the unit square\n  builder.setBottomLeftCorner(Eigen::Vector2d{-1.0, -1.0})\n      .setTopRightCorner(Eigen::Vector2d{1, 1})\n      .setNumXCells(50)\n      .setNumYCells(50);\n  auto mesh_p = builder.Build();\n\n  /* SAM_LISTING_BEGIN_1 */\n  //====================\n  // Your code goes here\n  //====================\n\n  return 0;\n}\n", "meta": {"hexsha": "d96ba41c6f9226c5c729b9902b9d6e1a54b95cf0", "size": 1379, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/RadauThreeTimestepping/templates/radauthreetimestepping_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/RadauThreeTimestepping/templates/radauthreetimestepping_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/RadauThreeTimestepping/templates/radauthreetimestepping_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 28.1428571429, "max_line_length": 80, "alphanum_fraction": 0.6903553299, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.5491305034112628}}
{"text": "// Copyright (c) 2021 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#include <gtest/gtest.h>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/p_square_quantile.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <fstream>\n#include <random>\n\n#include \"pyinterp/detail/math/descriptive_statistics.hpp\"\n#include \"pyinterp/detail/math/streaming_histogram.hpp\"\n\nnamespace math = pyinterp::detail::math;\n\nconstexpr auto POINTS = 1000;\n\nauto quantile(const std::vector<double>& x, double q) {\n  const auto ix = (x.size() - 1) * q;\n  const auto lo = floor(ix);\n  const auto hi = ceil(ix);\n\n  return (x[lo] + x[hi]) * 0.5;\n}\n\nTEST(math_streaming_histogram, push) {\n  auto instance = math::StreamingHistogram<double>(3, false);\n\n  instance(10);\n  const auto& bins = instance.bins();\n  ASSERT_EQ(bins.size(), 1);\n  EXPECT_EQ(bins[0].value, 10);\n  EXPECT_EQ(bins[0].weight, 1);\n\n  instance(13);\n  ASSERT_EQ(bins.size(), 2);\n  EXPECT_EQ(bins[0].value, 10);\n  EXPECT_EQ(bins[0].weight, 1);\n  EXPECT_EQ(bins[1].value, 13);\n  EXPECT_EQ(bins[1].weight, 1);\n\n  instance(3);\n  ASSERT_EQ(bins.size(), 3);\n  EXPECT_EQ(bins[0].value, 3);\n  EXPECT_EQ(bins[0].weight, 1);\n  EXPECT_EQ(bins[1].value, 10);\n  EXPECT_EQ(bins[1].weight, 1);\n  EXPECT_EQ(bins[2].value, 13);\n  EXPECT_EQ(bins[2].weight, 1);\n\n  instance(13);\n  ASSERT_EQ(bins.size(), 3);\n  EXPECT_EQ(bins[0].value, 3);\n  EXPECT_EQ(bins[0].weight, 1);\n  EXPECT_EQ(bins[1].value, 10);\n  EXPECT_EQ(bins[1].weight, 1);\n  EXPECT_EQ(bins[2].value, 13);\n  EXPECT_EQ(bins[2].weight, 2);\n\n  instance(3);\n  ASSERT_EQ(bins.size(), 3);\n  EXPECT_EQ(bins[0].value, 3);\n  EXPECT_EQ(bins[0].weight, 2);\n  EXPECT_EQ(bins[1].value, 10);\n  EXPECT_EQ(bins[1].weight, 1);\n  EXPECT_EQ(bins[2].value, 13);\n  EXPECT_EQ(bins[2].weight, 2);\n\n  instance(10);\n  ASSERT_EQ(bins.size(), 3);\n  EXPECT_EQ(bins[0].value, 3);\n  EXPECT_EQ(bins[0].weight, 2);\n  EXPECT_EQ(bins[1].value, 10);\n  EXPECT_EQ(bins[1].weight, 2);\n  EXPECT_EQ(bins[2].value, 13);\n  EXPECT_EQ(bins[2].weight, 2);\n\n  instance(11);\n  ASSERT_EQ(bins.size(), 3);\n  EXPECT_EQ(bins[0].value, 3);\n  EXPECT_EQ(bins[0].weight, 2);\n  EXPECT_NEAR(bins[1].value, 10 + 1.0 / 3.0, 1e-9);\n  EXPECT_EQ(bins[1].weight, 3);\n  EXPECT_EQ(bins[2].value, 13);\n  EXPECT_EQ(bins[2].weight, 2);\n}\n\nTEST(math_streaming_histogram, sum_of_weights) {\n  auto instance = math::StreamingHistogram<double>(3, false);\n  EXPECT_EQ(instance.count(), 0);\n  EXPECT_EQ(instance.size(), 0);\n  EXPECT_EQ(instance.sum_of_weights(), 0);\n\n  instance(0, 4);\n  EXPECT_EQ(instance.count(), 1);\n  EXPECT_EQ(instance.size(), 1);\n  EXPECT_EQ(instance.sum_of_weights(), 4);\n\n  instance(1, 3);\n  EXPECT_EQ(instance.count(), 2);\n  EXPECT_EQ(instance.size(), 2);\n  EXPECT_EQ(instance.sum_of_weights(), 7);\n\n  instance(2, 5);\n  EXPECT_EQ(instance.count(), 3);\n  EXPECT_EQ(instance.size(), 3);\n  EXPECT_EQ(instance.sum_of_weights(), 12);\n}\n\nTEST(math_streaming_histogram, bounds) {\n  auto rd = std::random_device();\n  auto gen = std::mt19937(rd());\n  auto normal = std::normal_distribution<>();\n  auto instance = math::StreamingHistogram<double>();\n  auto min = std::numeric_limits<double>::max();\n  auto max = std::numeric_limits<double>::min();\n\n  for (auto ix = 0; ix < POINTS; ++ix) {\n    auto value = normal(gen);\n    instance(value);\n    min = std::min(min, value);\n    max = std::max(max, value);\n  }\n  EXPECT_NEAR(min, instance.min(), 1e-6);\n  EXPECT_NEAR(max, instance.max(), 1e-6);\n}\n\nTEST(math_streaming_histogram, quantile) {\n  auto instance = math::StreamingHistogram<double>(3, false);\n  instance(1, 4);\n  instance(5, 3);\n  instance(10, 5);\n\n  auto expected = instance.quantile(0.5);\n  EXPECT_NEAR(expected, 5.625, 1e-9);\n}\n\nTEST(math_streaming_histogram, quantile_not_enough_elements) {\n  auto instance = math::StreamingHistogram<double>(10, false);\n  for (const auto& item : std::vector<double>({31, 56, 40, 39, 82, 17})) {\n    instance(item);\n  }\n\n  auto expected = instance.quantile(0.5);\n  EXPECT_NEAR(expected, 39.5, 1e-9);\n}\n\nTEST(math_streaming_histogram, quantile_on_left) {\n  auto instance = math::StreamingHistogram<double>(6, false);\n  for (const auto& item : std::vector<double>(\n           {3.075, 1.3, 1.35, 1.225, 1.375, 1.4, 2.05, 7.6325, 5.875, 3.495})) {\n    instance(item);\n  }\n\n  auto expected = instance.quantile(0.01);\n  auto exact = 1.23175;\n  EXPECT_NEAR(expected, exact, exact * 0.01);\n\n  expected = instance.quantile(0.05);\n  exact = 1.25875;\n  EXPECT_NEAR(expected, exact, exact * 0.05);\n\n  expected = instance.quantile(0.25);\n  exact = 1.35625;\n  EXPECT_NEAR(expected, exact, exact * 0.05);\n}\n\nTEST(math_streaming_histogram, quantile_on_right) {\n  auto instance = math::StreamingHistogram<double>(6, false);\n  for (const auto& item :\n       std::vector<double>({3.075, 2.05, 25.1325, 5.875, 3.495, 50., 50.05,\n                            50.2, 50.1, 50.025})) {\n    instance(item);\n  }\n\n  auto expected = instance.quantile(0.99);\n  auto exact = 50.191;\n  EXPECT_NEAR(expected, exact, exact * 0.01);\n\n  expected = instance.quantile(0.85);\n  exact = 50.0825;\n  EXPECT_NEAR(expected, exact, exact * 0.01);\n}\n\nTEST(math_streaming_histogram, stats) {\n  auto rd = std::random_device();\n  auto gen = std::mt19937(rd());\n  auto normal = std::normal_distribution<>();\n  auto acc = math::DescriptiveStatistics<double>();\n  auto instance = math::StreamingHistogram<double>(40, false);\n  auto values = std::vector<double>();\n\n  for (auto ix = 0; ix < POINTS; ++ix) {\n    auto value = normal(gen);\n    instance(value);\n    acc(value);\n    values.push_back(value);\n  }\n\n  std::sort(values.begin(), values.end());\n\n  auto expected = instance.quantile(0.5);\n  auto exact = quantile(values, 0.5);\n  ASSERT_NEAR(std::abs(expected - exact), 0, 0.2);\n\n  expected = instance.quantile(0.8);\n  exact = quantile(values, 0.8);\n  ASSERT_NEAR(std::abs(expected - exact), 0, 0.2);\n\n  EXPECT_EQ(acc.count(), instance.count());\n  EXPECT_EQ(acc.min(), instance.min());\n  EXPECT_EQ(acc.max(), instance.max());\n  EXPECT_EQ(acc.sum_of_weights(), instance.sum_of_weights());\n  acc.clear();\n  for (const auto& item : instance.bins()) {\n    acc(item.value, item.weight);\n  }\n  EXPECT_NEAR(acc.mean(), instance.mean(), 1e-6);\n  EXPECT_NEAR(acc.variance(), instance.variance(), 1e-6);\n  EXPECT_NEAR(acc.skewness(), instance.skewness(), 1e-6);\n  EXPECT_NEAR(acc.kurtosis(), instance.kurtosis(), 1e-6);\n}\n\nTEST(math_streaming_histogram, merge) {\n  auto rd = std::random_device();\n  auto gen = std::mt19937(rd());\n  auto normal = std::normal_distribution<>();\n  auto acc = math::DescriptiveStatistics<double>();\n  auto instance1 = math::StreamingHistogram<double>(40, false);\n  auto instance2 = math::StreamingHistogram<double>(40, false);\n  auto values = std::vector<double>();\n\n  for (auto ix = 0; ix < POINTS / 2; ++ix) {\n    auto value = normal(gen);\n    instance1(value);\n    acc(value);\n    values.push_back(value);\n  }\n\n  for (auto ix = 0; ix < POINTS / 2; ++ix) {\n    auto value = normal(gen);\n    instance2(value);\n    acc(value);\n    values.push_back(value);\n  }\n\n  std::sort(values.begin(), values.end());\n  instance1 += instance2;\n\n  auto expected = instance1.quantile(0.5);\n  auto exact = quantile(values, 0.5);\n  ASSERT_NEAR(std::abs(expected - exact), 0, 0.2);\n\n  expected = instance1.quantile(0.8);\n  exact = quantile(values, 0.8);\n  ASSERT_NEAR(std::abs(expected - exact), 0, 0.2);\n\n  EXPECT_EQ(acc.count(), instance1.count());\n  EXPECT_NEAR(acc.min(), instance1.min(), 1e-6);\n  EXPECT_NEAR(acc.max(), instance1.max(), 1e-6);\n  EXPECT_EQ(acc.sum_of_weights(), instance1.sum_of_weights());\n  acc.clear();\n  for (const auto& item : instance1.bins()) {\n    acc(item.value, item.weight);\n  }\n  EXPECT_NEAR(acc.mean(), instance1.mean(), 1e-6);\n  EXPECT_NEAR(acc.variance(), instance1.variance(), 1e-6);\n}\n\nTEST(math_streaming_histogram, quantile_out_of_bounds) {\n  auto instance = math::StreamingHistogram<double>(6, false);\n  EXPECT_TRUE(std::isnan(instance.quantile(-0.2)));\n\n  for (const auto& item : std::vector<double>({1, 2, 3, 4, 5, 6, 6.1, 6.2})) {\n    instance(item);\n  }\n\n  EXPECT_THROW(instance.quantile(-0.2), std::invalid_argument);\n  EXPECT_THROW(instance.quantile(10), std::invalid_argument);\n}\n\nTEST(math_streaming_histogram, serialization) {\n  auto instance = math::StreamingHistogram<double>(6, false);\n\n  auto dump = static_cast<std::string>(instance);\n  auto instance2 = math::StreamingHistogram<double>(dump);\n  ASSERT_EQ(instance.count(), instance2.count());\n  ASSERT_EQ(instance.sum_of_weights(), instance2.sum_of_weights());\n  ASSERT_EQ(instance.bins().size(), instance2.bins().size());\n\n  for (const auto& item :\n       std::vector<double>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10})) {\n    instance(item);\n  }\n\n  dump = static_cast<std::string>(instance);\n  instance2 = math::StreamingHistogram<double>(dump);\n  ASSERT_EQ(instance.count(), instance2.count());\n  ASSERT_EQ(instance.sum_of_weights(), instance2.sum_of_weights());\n  ASSERT_EQ(instance.size(), instance2.size());\n  for (size_t ix = 0; ix < instance.size(); ++ix) {\n    ASSERT_EQ(instance.bins()[ix].value, instance2.bins()[ix].value);\n  }\n\n  ASSERT_THROW(math::StreamingHistogram<double>(\"AZERTYUIOP\"),\n               std::invalid_argument);\n}\n\nTEST(math_streaming_histogram, weighted) {\n  static double x[20] = {0.00402322, 0.19509434, 0.6425439,  0.66463742,\n                         0.76523411, 0.91985221, 0.82729929, 0.21502902,\n                         0.48254104, 0.97854649, 0.61394511, 0.00583773,\n                         0.06630172, 0.57173946, 0.5881294,  0.30185368,\n                         0.18126563, 0.84524097, 0.13754961, 0.17343529};\n  static double w[20] = {0.45463566, 0.46341234, 0.2072285,  0.02272363,\n                         0.76796619, 0.01987153, 0.43634701, 0.1369698,\n                         0.65012667, 0.18825124, 0.96310554, 0.31995482,\n                         0.28808939, 0.69961506, 0.97369255, 0.98436659,\n                         0.05230501, 0.8073624,  0.40509977, 0.6325752};\n  auto acc = math::DescriptiveStatistics<double>();\n  auto instance = math::StreamingHistogram<double>(20, false);\n\n  for (auto ix = 0; ix < 20; ++ix) {\n    acc(x[ix], w[ix]);\n    instance(x[ix], w[ix]);\n  }\n\n  EXPECT_EQ(instance.count(), acc.count());\n  EXPECT_EQ(instance.sum_of_weights(), acc.sum_of_weights());\n  EXPECT_DOUBLE_EQ(instance.mean(), acc.mean());\n  EXPECT_NEAR(instance.variance(), acc.variance(), 1e-12);\n  EXPECT_NEAR(instance.quantile(0.5), 0.5716742560345885, 1e-12);\n\n  instance = math::StreamingHistogram<double>(10, false);\n\n  for (auto ix = 0; ix < 20; ++ix) {\n    instance(x[ix], w[ix]);\n  }\n\n  EXPECT_EQ(instance.count(), acc.count());\n  EXPECT_TRUE(instance.count() > instance.size());\n  EXPECT_NEAR(instance.sum_of_weights(), acc.sum_of_weights(), 1e-6);\n  EXPECT_NEAR(instance.mean(), acc.mean(), 1e-6);\n  EXPECT_NEAR(instance.variance(), acc.variance(), 1e-3);\n  EXPECT_NEAR(instance.quantile(0.5), 0.5716742560345885, 1e-1);\n}\n", "meta": {"hexsha": "6a51d7bce8d1761e57bc8ad3ecdf30d092b1c539", "size": 11024, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/tests/math_streaming_histogram.cpp", "max_stars_repo_name": "CNES/pangeo-pyinterp", "max_stars_repo_head_hexsha": "5f75f62a6c681db89c5aa8c74e43fc04a77418c3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2019-07-09T09:10:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T09:46:35.000Z", "max_issues_repo_path": "src/pyinterp/core/tests/math_streaming_histogram.cpp", "max_issues_repo_name": "CNES/pangeo-pyinterp", "max_issues_repo_head_hexsha": "5f75f62a6c681db89c5aa8c74e43fc04a77418c3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-07-15T13:54:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T05:06:34.000Z", "max_forks_repo_path": "src/pyinterp/core/tests/math_streaming_histogram.cpp", "max_forks_repo_name": "CNES/pangeo-pyinterp", "max_forks_repo_head_hexsha": "5f75f62a6c681db89c5aa8c74e43fc04a77418c3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-07-15T17:28:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T19:43:47.000Z", "avg_line_length": 31.5873925501, "max_line_length": 80, "alphanum_fraction": 0.6598330914, "num_tokens": 3394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5491304970811444}}
{"text": "#ifndef RASTERIZER_HPP\n#define RASTERIZER_HPP\n\n#include <algorithm>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <limits>\n\nnamespace rasterize {\n\nnamespace bg = boost::geometry;\n\n/*  rasterize a polygon implementation  */\n\ntemplate <typename point_t, typename float_t = double, typename int_t = int64_t>\nstruct Edge {\n  typedef bg::model::segment<point_t> segment_t;\n  float_t x, xNorm, yNorm;\n  float_t minX, maxX;\n  float_t slope;\n  int_t yMax, yMin; // min-max of edge\n  float_t dX, dY;\n  segment_t line;\n  Edge(const point_t &a, const point_t &b) : line{a, b} {\n    auto &pMin = (bg::get<1>(a) < bg::get<1>(b) ? a : b);\n    auto &pMax = (bg::get<1>(a) < bg::get<1>(b) ? b : a);\n\n    yMax = bg::get<1>(pMax);\n    yMin = bg::get<1>(pMin);\n\n    x = bg::get<0>(pMin);                          // start x\n    minX = std::min(bg::get<0>(a), bg::get<0>(b)); // start x\n    maxX = std::max(bg::get<0>(a), bg::get<0>(b)); // start x\n\n    dX = (bg::get<0>(pMax) - bg::get<0>(pMin));\n    dY = (bg::get<1>(pMax) - bg::get<1>(pMin));\n    slope = dY != 0 ? slope = dX / dY : 0;\n\n    auto yOff = yMin - std::floor(yMin);\n    auto xOff = x - std::floor(x);\n\n    yNorm = std::round(yMin) + 0.5;\n    xNorm = x + (yNorm - yMin) * slope;\n  }\n\n  friend std::ostream &operator<<(std::ostream &stream, const Edge &edge) {\n    return std::cout << \"Edge bucket: \" << edge.yMin << \"=>\" << edge.yMax\n                     << \"dx=\" << edge.dX << \"; dy=\" << edge.dY\n                     << \"; x=\" << edge.x << \";\" << std::endl;\n  }\n};\n\ntemplate <typename point_t, typename float_t = double> struct Rasterizer {\n  typedef bg::model::polygon<point_t> polygon_t;\n  typedef Edge<point_t, float_t> edge_t;\n  struct {\n    bool operator()(const edge_t &a, const edge_t &b) const {\n      return a.yMin < b.yMin;\n    }\n  } yMinCompare;\n\n  enum { STEP_INTERSECT, STEP_RASTERIZE };\n  std::list<edge_t> ET; // edge table\n  std::list<edge_t> AL; // active list\n\n  int scanline;\n\n  std::pair<bool, int> custom_scanline;\n\n  void set_scanline(int _scanline) {\n    custom_scanline = std::make_pair(true, _scanline);\n  }\n\n  void clear_scanline() { custom_scanline = std::make_pair(false, 0); }\n\n  void clear() {\n    clear_scanline();\n    ET.clear();\n    AL.clear();\n  }\n\n  void init(const polygon_t &p) {\n    clear();\n    if (p.outer().size() < 3) // don't render invalid polygons\n      return;\n    // build edge table containing all edges n=>0, 0=>1, ...n-1=>n\n    edge_t e = {p.outer().back(), p.outer()[0]};\n    if (e.dY != 0)\n      ET.push_back(e);\n    for (size_t i = 0; i < p.outer().size() - 1; i++) {\n      e = {p.outer()[i], p.outer()[i + 1]};\n      if (e.dY != 0)\n        ET.push_back(e);\n    }\n    // sort according to yMin\n    ET.sort(yMinCompare);\n\n    //\tstd::cout << bg::wkt(p) << std::endl;\n    if (ET.empty())\n      return;\n\n    if (!custom_scanline.first) {\n      scanline = ET.front().yMin;\n    } else {\n      auto _scanline = custom_scanline.second;\n      if (ET.front().yMin != _scanline)\n        //\t    std::cout << \"Starting at different scanlines: \" <<\n        // ET.front().yMin << \" vs.\" << scanline << std::endl;\n        scanline = ET.front().yMin;\n      //\t    std::cout << \"silent step should now do \" << scanline << \"\n      // until \" << _scanline << std::endl;\n      while (scanline < _scanline) {\n        //\t      std::cout << \"silent step:\" << scanline << \" towards \" <<\n        //_scanline << std::endl;\n        step_intersect([](int x, int y) {});\n      }\n    }\n  }\n\n  bool done() { return (ET.empty() && AL.empty()); }\n  template <typename func> void step_intersect(func putpixel) {\n#ifdef DEBUG_LOG\n    std::cout << \"scanline(\" << scanline << \"):\" << std::endl;\n#endif\n    // all edges that start here are moved from ET to AL\n    for (auto it = ET.begin(); it != ET.end();) {\n      if (std::floor(it->yMin - 1) <= scanline) {\n        AL.push_back(*it);\n#ifdef DEBUG_LOG\n        std::cout << \"erase (\" << it->yMin << \") \";\n#endif\n        it = ET.erase(it);\n      } else\n        it++;\n    }\n#ifdef DEBUG_LOG\n    std::cout << \"active(\" << AL.size() << \") \";\n#endif\n    // all edges that end here, are removed from AL\n    for (auto it = AL.begin(); it != AL.end();) {\n      if (std::ceil(it->yMax + 1) < scanline) {\n        it = AL.erase(it);\n      } else\n        it++;\n    }\n\n    // theoretic: for multipolygons, this could become empty. However, for\n    // polygons it should always have at least two active edges\n    if (AL.empty()) {\n      scanline++;\n      return;\n    }\n\n    // sort according to X coordinate\n    AL.sort([](const edge_t &a, const edge_t &b) {\n      // it is an iterator pointing to Edge\n      // sort by x and slope\n      return (a.x < b.x || (a.x == b.x && a.slope < b.slope));\n    });\n#ifdef DEBUG_LOG\n    std::cout << \"-> (\" << AL.size() << \"):\" << std::endl;\n    for (auto &a : AL) {\n      std::cout << \"{(\" << a.line.first.get<0>() << \",\" << a.line.first.get<1>()\n                << \"),\"\n                << \"(\" << a.line.second.get<0>() << \",\"\n                << a.line.second.get<1>() << \")},\";\n    }\n#endif\n\n    // prepare scanline filling\n    auto minX = std::floor(AL.front().minX - 1);\n    auto maxX = std::ceil(AL.back().maxX);\n    auto line = typename edge_t::segment_t(point_t(minX, scanline + 0.5),\n                                           point_t(maxX, scanline + 0.5));\n\n    std::vector<point_t> output;\n    for (auto &e : AL) {\n      bg::intersection(line, e.line, output);\n#ifdef DEBUG_LOG\n      std::cout << \"[\";\n      for (auto i = output.begin(); i != output.end(); ++i)\n        std::cout << \"(\" << bg::get<0>(*i) << ',' << bg::get<1>(*i) << \"),\";\n      std::cout << \"], \";\n#endif\n    }\n#ifdef DEBUG_LOG\n    std::cout << \" | sum: \" << output.size() << std::endl;\n#endif\n    // assert(output.size() % 2 == 0);\n    std::sort(output.begin(), output.end(),\n              ([](const point_t &a, const point_t &b) {\n                // sort by x\n                return bg::get<0>(a) < bg::get<0>(b);\n              }));\n#ifdef BORDERS_ONLY\n    // Just the borders\n    auto index = 0;\n    for (auto &i : output) {\n      //\tfloat_t pixelX = bg::get<0>(i) - std::floor(bg::get<0>(i));\n\n      int x = index % 2 == 0 ? std::round(bg::get<0>(i))\n                             : std::floor(bg::get<0>(i) - 0.5);\n\n      putpixel(x, scanline);\n      index++;\n    }\n#else\n    if (output.size() > 0) {\n\n      for (auto i = 1; i < output.size(); i += 2) {\n        auto xstart = std::round(bg::get<0>(output[i - 1]));\n        auto xend = std::floor(bg::get<0>(output[i]) - 0.5);\n#ifdef DEBUG_LOG\n        std::cout << \"xstart: \" << xstart << \" xend: \" << xend << std::endl;\n#endif\n        for (auto x = xstart; x <= xend; x++)\n          putpixel(x, scanline);\n      }\n    }\n#endif\n\n    scanline++;\n    return;\n  }\n  template <typename func> void step_rasterize(func putpixel) {\n//#define DEBUG_LOG\n#ifdef DEBUG_LOG\n    std::cout << \"scanline(\" << scanline << \"):\" << std::endl;\n#endif\n    // all edges that start here are moved from ET to AL\n    for (auto it = ET.begin(); it != ET.end();) {\n      if (std::floor(it->yNorm) <= scanline) {\n        AL.push_back(*it);\n#ifdef DEBUG_LOG\n        std::cout << \"erase (\" << it->yMin << \") \";\n#endif\n        it = ET.erase(it);\n      } else\n        it++;\n    }\n#ifdef DEBUG_LOG\n    std::cout << \"active(\" << AL.size() << \") \";\n#endif\n    // all edges that end here, are removed from AL\n    for (auto it = AL.begin(); it != AL.end();) {\n      if (std::ceil(it->yMax - 1) < scanline) {\n        it = AL.erase(it);\n      } else\n        it++;\n    }\n\n    // theoretic: for multipolygons, this could become empty. However, for\n    // polygons it should always have at least two active edges\n    if (AL.empty()) {\n      scanline++;\n      return;\n    }\n\n    // sort according to X coordinate\n    AL.sort([](const edge_t &a, const edge_t &b) {\n      // it is an iterator pointing to Edge\n      // sort by x and slope\n      return ((a.xNorm < b.xNorm) || (a.xNorm == b.xNorm && a.slope < b.slope));\n    });\n#ifdef DEBUG_LOG\n    std::cout << \"-> (\" << AL.size() << \"):\" << std::endl;\n    for (auto &a : AL) {\n      std::cout << \"{(\" << a.line.first.get<0>() << \",\" << a.line.first.get<1>()\n                << \"),\"\n                << \"(\" << a.line.second.get<0>() << \",\"\n                << a.line.second.get<1>() << \")},\";\n    }\n#endif\n\n    // prepare scanline filling\n    auto minX = std::floor(AL.front().minX - 2);\n    auto maxX = std::ceil(AL.back().maxX);\n    typename edge_t::segment_t line(point_t(minX, scanline + 0.5),\n                                    point_t(maxX, scanline + 0.5));\n    auto it = AL.begin();\n    bool inside = false;\n#ifdef DEBUG_LOG\n    std::cout << \"[\" << std::endl;\n#endif\n    for (float_t x = minX; x <= maxX; x++) {\n      auto go = true;\n      while (go) {\n        go = false;\n        if (!inside) {\n          if (x + 0.5 >= it->xNorm && it != AL.end()) {\n            inside = !inside;\n            it++;\n            go = true;\n          }\n        } else {\n          if ((x + 0.499999) > it->xNorm) {\n#ifdef DEBUG_LOG\n            std::cout.precision(std::numeric_limits<float_t>::max_digits10);\n            std::cout << std::endl\n                      << \"(\" << x + 0.5 << \" > \" << it->xNorm << \")\"\n                      << std::endl;\n            std::cout.precision(2);\n#endif\n            inside = !inside;\n            it++;\n            go = true;\n          }\n        }\n        if (it == AL.end())\n          break;\n      }\n#ifdef DEBUG_LOG\n      std::cout << \"n:\" << it->xNorm << \"~\" << it->x << \" x:\" << x\n                << \" in:\" << inside << \", \";\n#endif\n\n      if (inside)\n        putpixel(x, scanline);\n    }\n#ifdef DEBUG_LOG\n    std::cout << \"]\" << std::endl;\n#endif\n\n    // increment all the X based on slope\n    for (auto &e : AL) {\n      if (e.dX != 0)\n        e.xNorm += e.slope;\n    }\n\n    scanline++;\n    return;\n  }\n\n  void rasterize(const polygon_t &p,\n                 std::function<void(float_t, float_t)> putpixel,\n                 int step_id = STEP_RASTERIZE, int steps = -1) {\n    init(p);\n\n    switch (step_id) {\n    case STEP_INTERSECT:\n      while (!done()) {\n        step_intersect(putpixel);\n      }\n      break;\n    case STEP_RASTERIZE:\n      while (!done()) {\n        step_rasterize(putpixel);\n      }\n      break;\n    }\n    // Process ET=>AL=>(void)\n  }\n};\n\n} // namespace rasterize\n\n#endif\n", "meta": {"hexsha": "c4d37ea7d5047a10cf654be294422f517e62c5da", "size": 10310, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "experiments/src/rasterizer.hpp", "max_stars_repo_name": "mlaass/globimap", "max_stars_repo_head_hexsha": "6bbcbf33cc39ed343662e6b98871dc6dfbc4648f", "max_stars_repo_licenses": ["MIT"], "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/src/rasterizer.hpp", "max_issues_repo_name": "mlaass/globimap", "max_issues_repo_head_hexsha": "6bbcbf33cc39ed343662e6b98871dc6dfbc4648f", "max_issues_repo_licenses": ["MIT"], "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/src/rasterizer.hpp", "max_forks_repo_name": "mlaass/globimap", "max_forks_repo_head_hexsha": "6bbcbf33cc39ed343662e6b98871dc6dfbc4648f", "max_forks_repo_licenses": ["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.8795518207, "max_line_length": 80, "alphanum_fraction": 0.5057225994, "num_tokens": 3059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5491304949759487}}
{"text": "#ifndef _RBF_HPP\n#define _RBF_HPP\n\n#include <armadillo>\n#include <vector>\n#include <math.h>\n\nusing namespace arma;\nusing namespace std;\n\nclass rbf {\n    double sigma;\n    vector<double> w;\n    vector<double> g;\npublic:\n    rbf(vector<double> &x, vector<double> &y,\n                           double lambda);\n\n    double gaussian(double xi, double xj);\n\n    double get_output(double x);\n\n    vector<double> test(const vector<double> &x);\n};\n\n\n\n\n\n\n\n\n\n#endif", "meta": {"hexsha": "78c918b408c854cebe3c2dd071a02c248ded00fa", "size": 455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RBF/src/rbf.hpp", "max_stars_repo_name": "jesuswr/RBF", "max_stars_repo_head_hexsha": "0d11d763ccc75616f7e08ed9822ac3968f2533fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RBF/src/rbf.hpp", "max_issues_repo_name": "jesuswr/RBF", "max_issues_repo_head_hexsha": "0d11d763ccc75616f7e08ed9822ac3968f2533fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RBF/src/rbf.hpp", "max_forks_repo_name": "jesuswr/RBF", "max_forks_repo_head_hexsha": "0d11d763ccc75616f7e08ed9822ac3968f2533fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.3823529412, "max_line_length": 49, "alphanum_fraction": 0.632967033, "num_tokens": 108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5491304942645288}}
{"text": "// Example of using Array<T,N>::iterator \n\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n    // Create a 4x4 array and fill it with some numbers\n\n    Array<int,2> A(4,4);\n    A = tensor::i * 10 + tensor::j; \n    cout << \"A = \" << A << endl;\n\n\n    // Use an iterator to list the array elements\n\n    Array<int,2>::iterator iter = A.begin(), end = A.end();\n\n    while (iter != end)\n    {\n        cout << iter.position() << '\\t' << (*iter) << endl;\n        ++iter;\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "ec3001d780891f2f3bea4a58e7c28d2830c3941d", "size": 505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/iter.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/iter.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/iter.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.4137931034, "max_line_length": 59, "alphanum_fraction": 0.5386138614, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.5491304935676412}}
{"text": "/*\n * matrices.cpp\n *\n *  Created on: Jan 12, 2012\n *      Author: eba\n */\n#include \"mhfpython.h\"\n#include <eigen3/Eigen/Dense>\n#include <GaussianHypothesis.h>\n#include <boost/python/stl_iterator.hpp>\n#include <list>\n#include <numpy/noprefix.h>\n#include <string>\n\nusing namespace Eigen;\n\n\ntypedef GaussianHypothesis<dim>::MeanMatrix MeanMatrix;\ntypedef GaussianHypothesis<dim>::CovMatrix CovMatrix;\n\ntypedef Matrix<double,1,1> ScalarMatrix;\n\n\ntemplate<int rows, int cols>\nvoid matrix_assign(Matrix<double, rows, cols>& m, boost::python::object o) {\n    // Turn a Python sequence into an STL input range\n    boost::python::stl_input_iterator<double > begin(o), end;\n    std::list<double> l; l.assign(begin,end);\n    std::list<double>::iterator it = l.begin();\n    for(int r = 0; r<rows; r++)\n    \tfor(int c=0; c<cols; c++)\n    \t\tm(r,c) = *(it++);\n}\n\ntemplate<int rows, int cols>\n//boost::python::numeric::array *\nPyObject *\npyArray(Matrix<double, rows, cols> & mat) {\n\tnpy_intp N[] = {rows,cols};\n\t//return new array(handle<>(PyArray_SimpleNewFromData(2,N, PyArray_DOUBLE, mat.data())));\n\t//return static_cast<array>(handle<>(PyArray_SimpleNewFromData(2,N, PyArray_DOUBLE, mat.data())));\n\treturn PyArray_SimpleNewFromData(2,N, PyArray_DOUBLE, mat.data()); // EIGEN_DEFAULT_TO_ROW_MAJOR is needed!!\n}\n\ntemplate<int rows, int cols>\nMatrix<double, rows,cols> * createMatrix(object o) {\n\tMatrix<double, rows, cols> * result = new Matrix<double, rows, cols>();\n\tfor(int r = 0; r<rows; r++)\n\t\tfor(int c = 0; c<cols; c++)\n\t\t\t(*result)(r,c) = extract<double>(o.attr(\"__getitem__\")(r).attr(\"__getitem__\")(c));\n\treturn result;\n\n}\n\ntemplate<int rows, int cols>\nclass export_proxy {\npublic:\n\tstatic bool exported;\n};\n\ntemplate<int rows, int cols >\nbool export_proxy<rows,cols>::exported = false;\n\ntemplate<int rows, int cols>\nvoid export_matrix() {\n\n\tif(export_proxy<rows,cols>::exported) return;\n\ttypedef Matrix<double, rows, cols> Mat;\n\tstring name = \"Matrix\" + lexical_cast<string>(rows) + lexical_cast<string>(cols);\n\n    double &(Mat::*MemberAccess) (typename Mat::Index) = &Mat::operator();\n    class_<Mat>(name.c_str())\n    \t    .def(\"__init__\", make_constructor(createMatrix<rows,cols>) )\n\t\t\t.def(\"__call__\", MemberAccess, return_value_policy<copy_non_const_reference>())\n    \t\t.def(self_ns::str(self))\n\t;\n    def(\"assign\",matrix_assign<rows,cols>);\n    def(\"pyArray\", pyArray<rows,cols>, with_custodian_and_ward_postcall<0,1>());\n    export_proxy<rows,cols>::exported=true;\n}\n\ntemplate<int rows, int cols>\nMatrix<double, rows, cols> * construct_matrix() {\n\treturn new Matrix<double, rows, cols>();\n}\n\ntemplate<int rows, int cols>\nvoid export_matrix(string name) {\n\tdef(name.c_str(), make_constructor(createMatrix<rows,cols>));\n\tdef(name.c_str(), construct_matrix<rows, cols>, return_value_policy<manage_new_object >());\n\texport_matrix<rows, cols>();\n}\n\nvoid export_matrices() {\n\n\timport_array();\n\tarray::set_module_and_type(\"numpy\", \"ndarray\");\n\n\texport_matrix<1,1>(\"ScalarMatrix\");\n\texport_matrix<dim,1>(\"MeanMatrix\");\n\texport_matrix<dim,dim>(\"CovMatrix\");\n\texport_matrix<inputdim,1>();\n\texport_matrix<procnoisedim,1>();\n\texport_matrix<procnoisedim,procnoisedim>();\n\texport_matrix<measdim,1>();\n\texport_matrix<measdim,measdim>();\n\texport_matrix<1,1>();\n\texport_matrix<2,1>();\n\n}\n", "meta": {"hexsha": "530f8b3221bd94e259e9ba2a7d01d01a43ff5139", "size": 3276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MHFPython/matrices.cpp", "max_stars_repo_name": "enobayram/MHFlib", "max_stars_repo_head_hexsha": "bfb978aee59ac1916b0a54ce881d4eb35311e763", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-29T08:50:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-29T08:50:55.000Z", "max_issues_repo_path": "MHFPython/matrices.cpp", "max_issues_repo_name": "enobayram/MHFlib", "max_issues_repo_head_hexsha": "bfb978aee59ac1916b0a54ce881d4eb35311e763", "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": "MHFPython/matrices.cpp", "max_forks_repo_name": "enobayram/MHFlib", "max_forks_repo_head_hexsha": "bfb978aee59ac1916b0a54ce881d4eb35311e763", "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.5135135135, "max_line_length": 109, "alphanum_fraction": 0.7045177045, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5491304851323271}}
{"text": "//=======================================================================\n// Copyright 2002 Indiana University.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\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/*\n  Adapted from the GIRTH program of the Stanford GraphBase.\n\n  Sample output:\n\n  This program explores the girth and diameter of Ramanujan graphs.\n  The bipartite graphs have q^3-q vertices, and the non-bipartite\n  graphs have half that number. Each vertex has degree p+1.\n  Both p and q should be odd prime numbers;\n    or you can try p = 2 with q = 17 or 43.\n\n  Choose a branching factor, p: 2\n  Ok, now choose the cube root of graph size, q: 17\n  Starting at any given vertex, there are\n  3 vertices at distance 1,\n  6 vertices at distance 2,\n  12 vertices at distance 3,\n  24 vertices at distance 4,\n  46 vertices at distance 5,\n  90 vertices at distance 6,\n  169 vertices at distance 7,\n  290 vertices at distance 8,\n  497 vertices at distance 9,\n  634 vertices at distance 10,\n  521 vertices at distance 11,\n  138 vertices at distance 12,\n  13 vertices at distance 13,\n  3 vertices at distance 14,\n  1 vertices at distance 15.\n  So the diameter is 15, and the girth is 9.\n  \n */\n\n#include <boost/config.hpp>\n#include <vector>\n#include <list>\n#include <iostream>\n#include <boost/limits.hpp>\n#include <boost/graph/stanford_graph.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/graph_utility.hpp>\n\ntypedef boost::graph_traits<Graph*> Traits;\ntypedef Traits::vertex_descriptor vertex_descriptor;\ntypedef Traits::edge_descriptor edge_descriptor;\ntypedef Traits::vertex_iterator vertex_iterator;\n\nstd::vector<std::size_t> distance_list;\n\ntypedef boost::v_property<long> dist_t;\nboost::property_map<Graph*, dist_t>::type d_map;\n\ntypedef boost::u_property<vertex_descriptor> pred_t;\nboost::property_map<Graph*, pred_t>::type p_map;\n\ntypedef boost::w_property<long> color_t;\nboost::property_map<Graph*, color_t>::type c_map;\n\nclass diameter_and_girth_visitor : public boost::bfs_visitor<>\n{\npublic:\n  diameter_and_girth_visitor(std::size_t& k_, std::size_t& girth_)\n    : k(k_), girth(girth_) { }\n\n  void tree_edge(edge_descriptor e, Graph* g) {\n    vertex_descriptor u = source(e, g), v = target(e, g);\n    k = d_map[u] + 1;\n    d_map[v] = k;\n    ++distance_list[k];\n    p_map[v] = u;\n  }\n  void non_tree_edge(edge_descriptor e, Graph* g) {\n    vertex_descriptor u = source(e, g), v = target(e, g);\n    k = d_map[u] + 1;\n    if (d_map[v] + k < girth && v != p_map[u])\n      girth = d_map[v]+ k;\n  }\nprivate:\n  std::size_t& k;\n  std::size_t& girth;\n};\n\n\nint\nmain()\n{\n  std::cout <<\n    \"This program explores the girth and diameter of Ramanujan graphs.\" \n            << std::endl;\n  std::cout <<\n    \"The bipartite graphs have q^3-q vertices, and the non-bipartite\" \n            << std::endl;\n  std::cout << \n    \"graphs have half that number. Each vertex has degree p+1.\" \n            << std::endl;\n  std::cout << \"Both p and q should be odd prime numbers;\" << std::endl;\n  std::cout << \"  or you can try p = 2 with q = 17 or 43.\" << std::endl;\n\n  while (1) {\n\n    std::cout << std::endl\n              << \"Choose a branching factor, p: \";\n    long p = 0, q = 0;\n    std::cin >> p;\n    if (p == 0)\n      break;\n    std::cout << \"Ok, now choose the cube root of graph size, q: \";\n    std::cin >> q;\n    if (q == 0)\n      break;\n\n    Graph* g;\n    g = raman(p, q, 0L, 0L);\n    if (g == 0) {\n      std::cerr << \" Sorry, I couldn't make that graph (error code \"\n        << panic_code << \")\" << std::endl;\n      continue;\n    }\n    distance_list.clear();\n    distance_list.resize(boost::num_vertices(g), 0);\n\n    // obtain property maps\n    d_map = get(dist_t(), g);\n    p_map = get(pred_t(), g);\n    c_map = get(color_t(), g);\n\n    vertex_iterator i, end;\n    for (boost::tie(i, end) = boost::vertices(g); i != end; ++i)\n      d_map[*i] = 0;\n\n    std::size_t k = 0;\n    std::size_t girth = (std::numeric_limits<std::size_t>::max)();\n    diameter_and_girth_visitor vis(k, girth);\n\n    vertex_descriptor s = *boost::vertices(g).first;\n\n    boost::breadth_first_search(g, s, visitor(vis).color_map(c_map));\n\n    std::cout << \"Starting at any given vertex, there are\" << std::endl;\n\n    for (long d = 1; distance_list[d] != 0; ++d)\n      std::cout << distance_list[d] << \" vertices at distance \" << d\n                << (distance_list[d+1] != 0 ? \",\" : \".\") << std::endl;\n\n    std::cout << \"So the diameter is \" << k - 1\n              << \", and the girth is \" << girth\n              << \".\" << std::endl;\n  } // end while\n\n  return 0;\n}\n", "meta": {"hexsha": "9c9cc23cc22fd1e9823737269052e2954794f06b", "size": 4760, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/graph/example/girth.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/graph/example/girth.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/graph/example/girth.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": 29.5652173913, "max_line_length": 73, "alphanum_fraction": 0.6180672269, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5491304802105161}}
{"text": "/* This file is part of the Tomographer project, which is distributed under the\n * terms of the MIT license.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 ETH Zurich, Institute for Theoretical Physics, Philippe Faist\n * Copyright (c) 2017 Caltech, Institute for Quantum Information and Matter, Philippe Faist\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n//#include <iostream>\n#include <cmath>\n\n#include <string>\n#include <sstream>\n#include <random>\n\n#include <boost/math/constants/constants.hpp>\n\n// definitions for Tomographer test framework -- this must be included before any\n// <Eigen/...> or <tomographer/...> header\n#include \"test_tomographer.h\"\n\n#include <tomographer/mathtools/sphcoords.h>\n#include <tomographer/tools/eigenutil.h>\n#include <tomographer/mathtools/check_derivatives.h>\n\n\n\n// --------------------------------------------------------------------------------\n\n// for checking debug results\n// see http://en.wikipedia.org/wiki/N-sphere\n\ninline double known_vol_sph(int);\n\ninline double known_surf_sph(int sphdim)\n{\n  if (sphdim == 0) {\n    return 2;\n  }\n  return 2 * M_PI * known_vol_sph(sphdim - 1);\n}\ninline double known_vol_sph(int cartdim)\n{\n  if (cartdim == 0) {\n    return 1;\n  }\n  return known_surf_sph(cartdim - 1) / cartdim;\n}\n\n// ------------------------------------------------------\n\nstatic const double pi = boost::math::constants::pi<double>();\n\n// utility to check for cart_to_sph_jacobian\ntemplate<int CART_DIM = 3, int SPH_DIM = CART_DIM - 1>\nstruct TestSphJacFixture\n{\n  TestSphJacFixture() { }\n  ~TestSphJacFixture() { }\n\n  double calc_montecarlo_vol(std::mt19937::result_type seed, std::size_t npoints)\n  {\n    // random number generator with reproducable results\n    std::mt19937 rng(seed);\n    // generate uniformly distributed numbers in [0.0, 1.0[\n    std::uniform_real_distribution<double> dist(0.0, 1.0);\n\n    // do very naive monte carlo integration to obtain volume of a sphere\n    const int ds = SPH_DIM;\n    const double R = 1.0; // radius of ball\n    \n    double vol = 0;\n\n    Eigen::VectorXd rtheta(CART_DIM);\n    \n    for (std::size_t k = 0; k < npoints; ++k) {\n      // get a random point in theta-space; weigh with jacobian to estimate volume of n-ball\n      rtheta = Tomographer::Tools::denseRandom<Eigen::VectorXd>(rng, dist, CART_DIM);\n      // so translate them to the correct ranges.\n      rtheta(0) *= R; // rtheta(0) in [0, R]\n      rtheta.segment(1,ds-1) = rtheta.segment(1,ds-1) * pi; // theta_i in [0, pi] for 1 <= i < ds\n      rtheta(ds) = rtheta(ds) * 2 * pi; // theta_{ds} in [0, 2*pi]\n\n      vol += Tomographer::MathTools::SphCoords::cart_to_sph_jacobian(rtheta);\n    }\n\n    // average all volume elements\n    vol /= npoints;\n\n    // multiply by volume of parameter space\n    vol *=  R * 2*pi *  Eigen::VectorXd::Constant(ds-1, pi).array().prod();\n\n    return vol;\n  }\n\n  double calc_montecarlo_surf(std::mt19937::result_type seed, std::size_t npoints)\n  {\n    // random number generator with reproducable results\n    std::mt19937 rng(seed);\n    // generate uniformly distributed numbers in [0.0, 1.0[\n    std::uniform_real_distribution<double> dist(0.0, 1.0);\n\n    // do very naive monte carlo integration to obtain volume of a sphere\n    const int ds = SPH_DIM;\n    const double pi = boost::math::constants::pi<double>();\n\n    Eigen::VectorXd theta((Eigen::VectorXd::Index)ds);\n    double surf = 0;\n\n    for (std::size_t k = 0; k < npoints; ++k) {\n      // get a random point in theta-space; add weighted with Jacobian to estimate surface of n-sphere\n      theta = Tomographer::Tools::denseRandom<Eigen::VectorXd>(rng, dist, SPH_DIM);\n      // so translate them to the correct ranges.\n      theta.block(0,0,ds-1,1) = theta.block(0,0,ds-1,1) * pi; // theta_i in [0, pi] for 0 <= i < ds-1\n      theta(ds-1) = theta(ds-1) * 2 * pi; // theta_{ds-1} in [0, 2*pi]\n\n      surf += Tomographer::MathTools::SphCoords::surf_sph_jacobian(theta);\n    }\n\n    // average all volume elements\n    surf /= npoints;\n\n    // multiply by volume of parameter space: 2*pi * pi^(ds-1)\n    surf *=  2*pi *  Eigen::VectorXd::Constant(ds-1, pi).array().prod();\n    \n    return surf;\n  }\n};\n\n// -----------------------------------------------------------------------------\n// test suites\n\nBOOST_AUTO_TEST_SUITE(test_sph_cart)\n\nBOOST_AUTO_TEST_CASE(test_cart_to_sph_3)\n{\n  Eigen::Vector3d cart;\n  cart << 1.0, 2.0, 3.0; // a random point in 3d space\n\n  Eigen::Vector3d rtheta;\n  Tomographer::MathTools::SphCoords::cart_to_sph(rtheta, cart); // cart -> rtheta\n\n  BOOST_CHECK_CLOSE(rtheta(0), cart.norm(), tol_percent);\n  BOOST_CHECK_CLOSE(rtheta(0)*std::cos(rtheta(1)), cart(0), tol_percent);\n  BOOST_CHECK_CLOSE(rtheta(0)*std::sin(rtheta(1))*std::cos(rtheta(2)), cart(1), tol_percent);\n  BOOST_CHECK_CLOSE(rtheta(0)*std::sin(rtheta(1))*std::sin(rtheta(2)), cart(2), tol_percent);\n\n  Eigen::Vector3d backtocart = Eigen::Vector3d::Zero();\n  Tomographer::MathTools::SphCoords::sph_to_cart(backtocart, rtheta); // back to -> cart\n  BOOST_CHECK_CLOSE(backtocart(0), cart(0), tol_percent);\n  BOOST_CHECK_CLOSE(backtocart(1), cart(1), tol_percent);\n  BOOST_CHECK_CLOSE(backtocart(2), cart(2), tol_percent);\n  BOOST_CHECK_CLOSE(backtocart.norm(), rtheta(0), tol_percent);\n\n  // test sphsurf\n  Eigen::Vector3d cartonsphsurf = Eigen::Vector3d::Zero();\n  Tomographer::MathTools::SphCoords::sphsurf_to_cart(cartonsphsurf, rtheta.segment(1,2));\n  double orignorm = cart.norm();\n  BOOST_CHECK_CLOSE(cartonsphsurf(0)*orignorm, cart(0), tol_percent);\n  BOOST_CHECK_CLOSE(cartonsphsurf(1)*orignorm, cart(1), tol_percent);\n  BOOST_CHECK_CLOSE(cartonsphsurf(2)*orignorm, cart(2), tol_percent);\n}\n\nBOOST_AUTO_TEST_CASE(test_cart_to_sph_7)\n{\n  Eigen::VectorXd cart(7);\n  cart << 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0;\n\n  Eigen::VectorXd rtheta(7);\n  Tomographer::MathTools::SphCoords::cart_to_sph(rtheta, cart); // cart -> rtheta\n\n  BOOST_CHECK_CLOSE(rtheta(0), cart.norm(), tol_percent);\n  BOOST_CHECK_CLOSE(rtheta(0)*std::cos(rtheta(1)), cart(0), tol_percent);\n  BOOST_CHECK_CLOSE(rtheta(0)*std::sin(rtheta(1))*std::cos(rtheta(2)), cart(1), tol_percent);\n  BOOST_CHECK_CLOSE(rtheta(0)*std::sin(rtheta(1))*std::sin(rtheta(2))*std::cos(rtheta(3)), cart(2), tol_percent);\n  BOOST_CHECK_CLOSE(rtheta(0)*std::sin(rtheta(1))*std::sin(rtheta(2))*std::sin(rtheta(3))*std::cos(rtheta(4)), cart(3), tol_percent);\n  BOOST_CHECK_CLOSE(rtheta(0)*std::sin(rtheta(1))*std::sin(rtheta(2))*std::sin(rtheta(3))*std::sin(rtheta(4))*std::cos(rtheta(5)), cart(4), tol_percent);\n  BOOST_CHECK_CLOSE(rtheta(0)*std::sin(rtheta(1))*std::sin(rtheta(2))*std::sin(rtheta(3))*std::sin(rtheta(4))*std::sin(rtheta(5))*std::cos(rtheta(6)), cart(5), tol_percent);\n  BOOST_CHECK_CLOSE(rtheta(0)*std::sin(rtheta(1))*std::sin(rtheta(2))*std::sin(rtheta(3))*std::sin(rtheta(4))*std::sin(rtheta(5))*std::sin(rtheta(6)), cart(6), tol_percent);\n\n  Eigen::VectorXd backtocart = Eigen::VectorXd::Zero(7);\n  Tomographer::MathTools::SphCoords::sph_to_cart(backtocart, rtheta); // back to -> cart\n  BOOST_CHECK_CLOSE(backtocart(0), cart(0), tol_percent);\n  BOOST_CHECK_CLOSE(backtocart(1), cart(1), tol_percent);\n  BOOST_CHECK_CLOSE(backtocart(2), cart(2), tol_percent);\n  BOOST_CHECK_CLOSE(backtocart(3), cart(3), tol_percent);\n  BOOST_CHECK_CLOSE(backtocart(4), cart(4), tol_percent);\n  BOOST_CHECK_CLOSE(backtocart(5), cart(5), tol_percent);\n  BOOST_CHECK_CLOSE(backtocart(6), cart(6), tol_percent);\n\n  // test sphsurf\n  Eigen::VectorXd cartonsphsurf = Eigen::VectorXd::Zero(7);\n  Tomographer::MathTools::SphCoords::sphsurf_to_cart(cartonsphsurf, rtheta.segment(1,6));\n  double orignorm = cart.norm();\n  BOOST_CHECK_CLOSE(cartonsphsurf(0)*orignorm, cart(0), tol_percent);\n  BOOST_CHECK_CLOSE(cartonsphsurf(1)*orignorm, cart(1), tol_percent);\n  BOOST_CHECK_CLOSE(cartonsphsurf(2)*orignorm, cart(2), tol_percent);\n  BOOST_CHECK_CLOSE(cartonsphsurf(3)*orignorm, cart(3), tol_percent);\n  BOOST_CHECK_CLOSE(cartonsphsurf(4)*orignorm, cart(4), tol_percent);\n  BOOST_CHECK_CLOSE(cartonsphsurf(5)*orignorm, cart(5), tol_percent);\n  BOOST_CHECK_CLOSE(cartonsphsurf(6)*orignorm, cart(6), tol_percent);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n// =============================================================================\n\nBOOST_AUTO_TEST_SUITE(test_sph_jacobians)\n\nstatic const int NPOINTS = 1000000;\n\nBOOST_FIXTURE_TEST_CASE(test_sph_jacobians_3, TestSphJacFixture<3>)\n{\n  const int CART_DIM = 3;\n\n  // first time with seed=0\n  double vol = calc_montecarlo_vol(0, NPOINTS);\n  // another time with a different seed\n  double vol2 = calc_montecarlo_vol(4689392, NPOINTS);\n\n  const double ok_vol = known_vol_sph(CART_DIM);\n  BOOST_CHECK_CLOSE(vol, ok_vol, 1.0/*one percent*/);\n  BOOST_CHECK_CLOSE(vol2, ok_vol, 1.0/*one percent*/);\n\n  // ... and do the same for the surface of a sphere\n  double surf = calc_montecarlo_surf(0, NPOINTS);\n  \n  const double ok_surf = known_surf_sph(CART_DIM - 1);\n  BOOST_CHECK_CLOSE(surf, ok_surf, 1.0/*one percent*/);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_sph_jacobians_5, TestSphJacFixture<5>)\n{\n  const int CART_DIM = 5;\n\n  // first time with seed=0\n  double vol = calc_montecarlo_vol(0, NPOINTS);\n  // another time with a different seed\n  double vol2 = calc_montecarlo_vol(4689392, NPOINTS);\n\n  const double ok_vol = known_vol_sph(CART_DIM);\n  BOOST_CHECK_CLOSE(vol, ok_vol, 1.0/*one percent*/);\n  BOOST_CHECK_CLOSE(vol2, ok_vol, 1.0/*one percent*/);\n\n  // ... and do the same for the surface of a sphere\n  double surf = calc_montecarlo_surf(0, NPOINTS);\n  \n  const double ok_surf = known_surf_sph(CART_DIM - 1);\n  BOOST_CHECK_CLOSE(surf, ok_surf, 1.0/*one percent*/);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n// ================================================================================\n\nstruct sphsurf_to_cart_fn {\n  template<typename Der1, typename Der2>\n  void operator()(Eigen::MatrixBase<Der2>& cart, const Eigen::MatrixBase<Der1>& theta) {\n    Tomographer::MathTools::SphCoords::sphsurf_to_cart(cart, theta);\n  }\n};\n\ntemplate<int N, int DS = N-1>\nstruct sphsurf_to_diffcart_fn {\n  template<typename Der1, typename Der2>\n  void operator()(Eigen::MatrixBase<Der2>& dxdthetalinear, const Eigen::MatrixBase<Der1>& theta) {\n    Eigen::Array<double, N, DS> dxdtheta;\n    //std::cout << \"start fn eval\\n\";\n    Tomographer::MathTools::SphCoords::sphsurf_diffjac(dxdtheta, theta);\n    //std::cout << \"mid fn eval, dxdtheta's shape is (rows=\"<<dxdtheta.rows()<<\",cols=\"<<dxdtheta.cols()<<\")\\n\";\n    for (int i = 0; i < DS; ++i) {\n      dxdthetalinear.block(N*i, 0, N, 1) = dxdtheta.block(0, i, N, 1);\n    }\n    //std::cout << \"end fn eval\\n\";\n  }\n};\n\ntemplate<int DEF_N_>\nstruct test_diffjac_fixture {\n  enum {\n    DEF_N = DEF_N_,\n    DEF_DS = DEF_N_-1\n  };\n\n  Eigen::Matrix<double, DEF_DS, 1> theta;\n\n  test_diffjac_fixture()\n  {\n    // some interesting theta point\n    for (int k = 0; k < DEF_DS; ++k) {\n      theta(k) = k;\n    }\n  }\n};\n\nBOOST_AUTO_TEST_SUITE(test_diffjacs)\n\nconst double tol_der = 1e-6;\n\nBOOST_FIXTURE_TEST_CASE(test_diffjac, test_diffjac_fixture<11>)\n{\n  Eigen::Array<double, DEF_N, DEF_DS> dxdtheta;\n  Tomographer::MathTools::SphCoords::sphsurf_diffjac(dxdtheta, theta);\n\n  std::stringstream msgstream;\n  bool ok = Tomographer::MathTools::check_derivatives(\n      dxdtheta, // derivatives\n      theta, // point\n      sphsurf_to_cart_fn(), // fn\n      DEF_N, // valdims\n      tol_der,\n      tol_der,\n      msgstream\n      );\n  std::string msg = msgstream.str();\n  if (msg.size()) {\n    BOOST_MESSAGE(msg.c_str());\n  }\n  BOOST_CHECK(ok);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_diffjac2, test_diffjac_fixture<8>)\n{\n  // now, check second derivatives\n  Eigen::Array<double, DEF_N, DEF_DS*DEF_DS> ddxddtheta;\n  Tomographer::MathTools::SphCoords::sphsurf_diffjac2(ddxddtheta, theta);\n\n  Eigen::Array<double, DEF_N*DEF_DS, DEF_DS> ddxddtheta_reshaped;\n  for (int k = 0; k < DEF_N; ++k) {\n    for (int i = 0; i < DEF_DS; ++i) {\n      for (int j = 0; j < DEF_DS; ++j) {\n        ddxddtheta_reshaped(DEF_N*i + k, j) = ddxddtheta(k, i+DEF_DS*j);\n      }\n    }\n  }\n\n  std::stringstream msgstream;\n  bool ok = Tomographer::MathTools::check_derivatives(\n      ddxddtheta_reshaped, // derivatives of the derivatives :)\n      theta, // point\n      sphsurf_to_diffcart_fn<DEF_N,DEF_DS>(), //fn\n      DEF_N*DEF_DS, // valdims\n      tol_der,\n      tol_der,\n      msgstream\n      );\n  std::string msg = msgstream.str();\n  if (msg.size()) {\n    BOOST_MESSAGE(msg.c_str());\n  }\n  BOOST_CHECK(ok);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "d920729309693dc28f0ea3a23cc0dad1d108b832", "size": 13443, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/test_mathtools_sphcoords.cxx", "max_stars_repo_name": "Tomographer/tomographer", "max_stars_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T02:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T02:26:00.000Z", "max_issues_repo_path": "test/test_mathtools_sphcoords.cxx", "max_issues_repo_name": "Tomographer/tomographer", "max_issues_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-12T15:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-21T15:14:59.000Z", "max_forks_repo_path": "test/test_mathtools_sphcoords.cxx", "max_forks_repo_name": "Tomographer/tomographer", "max_forks_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-10-12T15:32:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-08T11:39:49.000Z", "avg_line_length": 35.848, "max_line_length": 173, "alphanum_fraction": 0.6783456074, "num_tokens": 3932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.548994436383021}}
{"text": "#include <stdio.h>\n#include <iostream>\n#include <Eigen/Eigen>\n#include \"NeuralNetwork.h\"\n\n\nint main(void)\n{\n  NeuralNetwork nn;\n\n  float loss;\n  Matrix<float, Dynamic, Dynamic> out;\n\n#if 1\n  Matrix<float, 1, 2> input[4];\n  Matrix<float, 1, 1> expect[4];\n  Matrix<float, Dynamic, Dynamic> W1(2,2);\n  Matrix<float, Dynamic, Dynamic> W2(2,1);\n\n  input[0] << 0, 0; expect[0] << 0;\n  input[1] << 0, 1; expect[1] << 1;\n  input[2] << 1, 0; expect[2] << 1;\n  input[3] << 1, 1; expect[3] << 0;\n\n  W1 << -0.0032973, -0.02393722, -0.02107663, 0.01280219 ;\n  W2 << -0.01024167, -0.01514217;\n\n  nn.createNewLayer(2,2, false, &W1);\n  nn.createNewLayer(2,1, true,  &W2);\n\n  loss = 100.f;\n  nn.printnet();\n  // while (loss > 0.001f)\n  for(int j=0; j<10; j++)\n    {\n      loss = 0.f;\n      for(int i=0; i<4; i++)\n        {\n          // std::cout << \"==== \" << i+1 << \" ====\"  << std::endl;\n          out = nn.forward( input[i] );\n          loss += nn.backward(0.1f, expect[i]);\n          nn.printnet();\n          // std::cout << \"   out = \" << out << std::endl;\n        }\n      loss /= 4;\n      std::cout << \"loss = \" << loss << std::endl;\n      nn.printnet();\n    }\n\n  for(int i=0; i<4; i++)\n    {\n      std::cout << \"Expect = \" << expect[i] << \" Input  = \" << input[i] << std::endl;\n      out = nn.forward( input[i] );\n      std::cout << \"Output = \" << out << std::endl;\n    }\n\n#else\n  Matrix<float, 1, 2> input;\n  Matrix<float, 1, 2> expect;\n\n  input << 3, 3;\n  expect << 0, 1;\n\n  nn.createNewLayer(2, 5);\n  nn.createNewLayer(5, 3);\n  nn.createNewLayer(3, 2, true);\n\n  std::cout << \"tmp input = \" << input << std::endl;\n  std::cout << \"expect = \" << expect << std::endl;\n  std::cout << \"input * expect = \" << input.array() * expect.array() << std::endl;\n\n  std::cout << \"input = \" << input << std::endl;\n  input = input.array() + 1;\n  std::cout << \"input = \" << input << std::endl;\n  \n\n  out = nn.forward( input );\n  std::cout << \"out.rows = \" << out.rows() << std::endl;\n  std::cout << \"out.cols = \" << out.cols() << std::endl;\n  std::cout << \"out = \" << out << std::endl;\n\n  loss = 100.f;\n  while (loss > 0.001f)\n    {\n      out = nn.forward( input );\n      loss = nn.backward(0.1f, expect);\n      std::cout << \"out = \" << out << std::endl;\n      std::cout << \"loss = \" << loss << std::endl;\n    }\n#endif\n\n  return 0;\n}\n\n", "meta": {"hexsha": "4288f1922e82f5133402457bf04073344458e528", "size": 2309, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "eigen_test/main.cxx", "max_stars_repo_name": "takayoshi-k/marubatsu", "max_stars_repo_head_hexsha": "cfda9544aa02cb23ead41c67b980a8af47d5d50c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eigen_test/main.cxx", "max_issues_repo_name": "takayoshi-k/marubatsu", "max_issues_repo_head_hexsha": "cfda9544aa02cb23ead41c67b980a8af47d5d50c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen_test/main.cxx", "max_forks_repo_name": "takayoshi-k/marubatsu", "max_forks_repo_head_hexsha": "cfda9544aa02cb23ead41c67b980a8af47d5d50c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3052631579, "max_line_length": 85, "alphanum_fraction": 0.5028150715, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.548984847010704}}
{"text": "#include <SDL2/SDL.h>\n#include <vector>\n#include <armadillo>\n#include <cmath>\n#include <cstdlib>\n#include <cstdio>\n#include <sys/types.h>\n#include <unistd.h>\n#include <iostream>\n\ndouble cos_rule_angle(double A, double B, double C) {\n  if (fabs((A + B) - C) < 0.000001) {\n    return M_PI;\n  }\n  if (!(A + B >= C)) {\n    fprintf(stderr, \"Assertion Error: A + B >= C\\n\");\n    exit(1);\n  }\n  return acos((A * A + B * B - C * C) / (2.0 * A * B));\n}\n\nbool concave(const arma::vec &l, const arma::vec &c, const arma::vec &r, double lrad, double crad, double rrad) {\n  double dlcx = c(0) - l(0);\n  double dlcy = c(1) - l(1);\n  double drcx = c(0) - r(0);\n  double drcy = c(1) - r(1);\n  double lc = sqrt(dlcx * dlcx + dlcy * dlcy);\n  double rc = sqrt(drcx * drcx + drcy * drcy);\n  double theta1 = cos_rule_angle(lc, crad, lrad);\n  double theta2 = cos_rule_angle(rc, crad, rrad);\n  return ((theta1 + theta2) - M_PI) > -0.1;\n}\n\nbool within(const arma::vec &l, const arma::vec &c, const arma::vec &r, double lrad, double crad, double rrad) {\n  if (crad == 0.0) {\n    return true;\n  }\n  return concave(l, c, r, lrad, crad, rrad);\n}\n\nstd::vector<arma::vec> get_filled_boundary(const std::vector<arma::vec> &pts) {\n  arma::vec X(pts.size());\n  arma::vec Y(pts.size());\n  for (int i = 0; i < pts.size(); i++) {\n    X(i) = pts[i](0) * cos(pts[i](1));\n    Y(i) = pts[i](0) * sin(pts[i](1));\n  }\n  int min_x = 0;\n  int min_y = 0;\n  int max_x = 0;\n  int max_y = 0;\n  int tx;\n  int ty;\n  for (int i = 0; i < pts.size(); i++) {\n    tx = (int)floor(X(i));\n    if (tx < min_x) {\n      min_x = tx;\n    }\n    tx = (int)ceil(X(i));\n    if (tx > max_x) {\n      max_x = tx;\n    }\n    ty = (int)floor(Y(i));\n    if (ty < min_y) {\n      min_y = ty;\n    }\n    ty = (int)ceil(Y(i));\n    if (ty > max_y) {\n      max_y = ty;\n    }\n  }\n  max_x++;\n  max_y++;\n  // create vmap\n  arma::mat vmap = arma::zeros<arma::mat>(max_y - min_y, max_x - min_x);\n  std::vector<arma::vec> colored;\n  std::vector<arma::vec> infection_queue = {{ 0.0, 0.0 }};\n  vmap(-min_y, -min_x) = 1.0;\n  int index = 0;\n  while (infection_queue.size() > index) {\n    double x = infection_queue[index](0);\n    double y = infection_queue[index](1);\n\n    double theta = atan2(y, x);\n    if (theta < 0.0) {\n      theta += 2.0 * M_PI;\n    }\n    double radius = sqrt(x * x + y * y);\n    // binary search\n    int left = 0;\n    int right = pts.size() - 1;\n    if (pts[right](1) <= theta || theta < pts[left](1)) {\n      left = right;\n      right = 0;\n    } else {\n      int mid = (left + right) / 2;\n      while (left + 1 != right) {\n        if (theta >= pts[mid](1)) {\n          left = mid;\n        } else {\n          right = mid;\n        }\n        mid = (left + right) / 2;\n      }\n    }\n\n    // bfs\n    arma::vec l({X(left), Y(left)});\n    arma::vec c({x, y});\n    arma::vec r({X(right), Y(right)});\n    int dx = x - min_x;\n    int dy = y - min_y;\n    if (within(l, c, r, pts[left](0), radius, pts[right](0))) {\n      colored.push_back(c);\n      if (y + 1 < max_y && vmap(dy + 1, dx) == 0.0) {\n        infection_queue.push_back({x, y + 1});\n        vmap(dy + 1, dx) = 1.0;\n      }\n      if (y - 1 >= min_y && vmap(dy - 1, dx) == 0.0) {\n        infection_queue.push_back({x, y - 1});\n        vmap(dy - 1, dx) = 1.0;\n      }\n      if (x + 1 < max_x && vmap(dy, dx + 1) == 0.0) {\n        infection_queue.push_back({x + 1, y});\n        vmap(dy, dx + 1) = 1.0;\n      }\n      if (x - 1 >= min_x && vmap(dy, dx - 1) == 0.0) {\n        infection_queue.push_back({x - 1, y});\n        vmap(dy, dx - 1) = 1.0;\n      }\n    }\n    //infection_queue.erase(infection_queue.begin());\n    index++;\n  }\n  return colored;\n}\n\nstd::vector<arma::vec> lidar_read(void) {\n  std::vector<arma::vec> pts;\n  double theta = 0.0;\n  while (theta < 360.0) {\n    theta += (double)rand() / (double)RAND_MAX + 2.0;\n    if (theta > 360.0) {\n      break;\n    }\n    double radius = (double)rand() / (double)RAND_MAX * 100.0 + 100.0;\n    pts.push_back(arma::vec({radius, theta * M_PI / 180.0}));\n  }\n  return pts;\n}\n\nint main(int argc, char *argv[]) {\n  arma::vec center = { 300.0, 300.0 };\n\n  srand(getpid());\n  SDL_Init(SDL_INIT_VIDEO);\n  SDL_Window *window = SDL_CreateWindow(\"raycast\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 640, SDL_WINDOW_SHOWN);\n  SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);\n  SDL_Surface *screen = SDL_CreateRGBSurface(0, 640, 640, 32, 0, 0, 0, 0);\n  SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, screen);\n\n  bool done = false;\n  uint32_t color_black = SDL_MapRGB(screen->format, 0, 0, 0);\n  uint32_t color_red = SDL_MapRGB(screen->format, 255, 0, 0);\n  uint32_t color_green = SDL_MapRGB(screen->format, 0, 255, 0);\n  uint32_t color_blue = SDL_MapRGB(screen->format, 0, 0, 255);\n  while (true) {\n    SDL_Event e;\n    while (SDL_PollEvent(&e)) {\n      if (e.type == SDL_QUIT) {\n        done = true;\n        break;\n      }\n    }\n    if (done) {\n      break;\n    }\n    \n    std::vector<arma::vec> data = lidar_read();\n    printf(\"getting raycast area...\\n\");\n    std::vector<arma::vec> raycast_area = get_filled_boundary(data);\n\n    SDL_FillRect(screen, NULL, color_black);\n    for (arma::vec &pt : raycast_area) {\n      int x = (int)(pt(0) + center(0));\n      int y = (int)(-pt(1) + center(1));\n      ((uint32_t *)screen->pixels)[y * 640 + x] = color_red;\n    }\n    for (arma::vec &pt : data) {\n      int x = (int)(pt(0) * cos(pt(1)) + center(0));\n      int y = (int)(-pt(0) * sin(pt(1)) + center(1));\n      ((uint32_t *)screen->pixels)[y * 640 + x] = color_green;\n    }\n    ((uint32_t *)screen->pixels)[300 * 640 + 299] = color_blue;\n    ((uint32_t *)screen->pixels)[300 * 640 + 300] = color_blue;\n    ((uint32_t *)screen->pixels)[300 * 640 + 301] = color_blue;\n    ((uint32_t *)screen->pixels)[299 * 640 + 300] = color_blue;\n    ((uint32_t *)screen->pixels)[301 * 640 + 300] = color_blue;\n\n    SDL_UpdateTexture(texture, NULL, screen->pixels, screen->pitch);\n    SDL_RenderClear(renderer);\n    SDL_RenderCopy(renderer, texture, NULL, NULL);\n    SDL_RenderPresent(renderer);\n    SDL_Delay(25);\n  }\n  SDL_DestroyTexture(texture);\n  SDL_FreeSurface(screen);\n  SDL_DestroyRenderer(renderer);\n  SDL_DestroyWindow(window);\n  SDL_Quit();\n  return 0;\n}\n", "meta": {"hexsha": "b92347b97a14aa436636aea942bd814471ad607c", "size": 6252, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slam/raycast/raycast.cpp", "max_stars_repo_name": "timrobot/Tachikoma-Project", "max_stars_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-11T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-11T19:04:33.000Z", "max_issues_repo_path": "slam/raycast/raycast.cpp", "max_issues_repo_name": "TimothyYong/Tachikoma-Project", "max_issues_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slam/raycast/raycast.cpp", "max_forks_repo_name": "TimothyYong/Tachikoma-Project", "max_forks_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_forks_repo_licenses": ["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.3521126761, "max_line_length": 127, "alphanum_fraction": 0.5591810621, "num_tokens": 2148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5488493748829715}}
{"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 GRADIENT_FUNCTOR_INC_HPP\n#define GRADIENT_FUNCTOR_INC_HPP\n\n#include \"gradient_functor.hpp\"\n\n#include <boost/bind.hpp>\n#include <boost/gil/extension/numeric/kernel.hpp>\n#include <boost/gil/extension/numeric/convolve.hpp>\n#include <boost/gil/extension/io_new/tiff_read.hpp>\n\nnamespace internal {\n\n#if !defined(M_PI)\n    const double M_PI = 4.0 * atan(1.0);\n#endif\n\n    template<typename Kernel1D>\n    void initKernelGaussian1D(Kernel1D& kernel, double m_sigma)\n    {\n\t// Gaussian smoothing\n        typedef\ttypename Kernel1D::value_type vt;\n        const vt z = 1.0 / (std::sqrt(2 * M_PI) * m_sigma);\n        const vt m_sigmasquared = m_sigma * m_sigma;\n        vt x = -1.0 * kernel.center();\n        typename Kernel1D::iterator i;\n        vt sum = 0.;\n        for (i=kernel.begin(); i!=kernel.end(); ++i, ++x)\n        {\n            *i = z * (std::exp(-0.5*(x*x/m_sigmasquared)));\n            sum += *i;\n        }\n        for (i=kernel.begin(); i!=kernel.end(); ++i) *i /= sum;\n    }\n\n    template<typename Kernel1D>\n    void initKernelGaussianDeriv1D(Kernel1D& kernel, double m_sigma)\n    {\n\t// Gaussian derivative smoothing\n        typedef\ttypename Kernel1D::value_type vt;\n        const vt z = 1.0 / (std::sqrt(2 * M_PI) * m_sigma);\n        const vt m_sigmasquared = m_sigma * m_sigma;\n        vt x = -1.0 * kernel.center();\n        typename Kernel1D::iterator i;\n        vt sum = 0.;\n        for (i=kernel.begin(); i!=kernel.end(); ++i, ++x)\n        {\n            *i = - (x/m_sigmasquared) * z * (std::exp(-0.5*(x*x/m_sigmasquared)));\n            sum += *i * x;\n        }\n        for (i=kernel.begin(); i!=kernel.end(); ++i) *i /= sum;\n    }\n\n}\n\ntemplate<typename Image, typename View>\ntypename gradient_functor::result_type gradient_functor::operator()(Image& g, const View& v) const\n{\n    using namespace boost::gil;\n\n    typedef typename Image::view_t g_view_t;\n    typedef typename get_pixel_type<g_view_t>::type g_pixel_t;\n    typedef typename kth_element_type<g_pixel_t,0>::type element_0_t;\n    typedef typename kth_element_type<g_pixel_t,1>::type element_1_t;\n    typedef pixel<element_0_t, gray_layout_t > g0_pixel_t;\n    typedef pixel<element_1_t, gray_layout_t > g1_pixel_t;\n\n    g.recreate(v.dimensions());\n\n    unsigned int half_size = (unsigned int) (3* m_sigma) ;\n    const size_t kws = 2 * half_size + 1;\n    kernel_1d<float> ksmooth(kws, kws / 2);\n    kernel_1d<float> kderiv(kws, kws / 2);\n    internal::initKernelGaussian1D(ksmooth, m_sigma);\n    internal::initKernelGaussianDeriv1D(kderiv, m_sigma);\n\n    convolve_cols<g0_pixel_t> (v, ksmooth, kth_channel_view<0> (view(g)), convolve_option_extend_constant);\n    convolve_rows<g0_pixel_t> (kth_channel_view<0> (view(g)), kderiv, kth_channel_view<0> (view(g)), convolve_option_extend_constant);\n\n    convolve_rows<g1_pixel_t> (v, ksmooth, kth_channel_view<1> (view(g)), convolve_option_extend_constant);\n    convolve_cols<g1_pixel_t> (kth_channel_view<1> (view(g)), kderiv, kth_channel_view<1> (view(g)), convolve_option_extend_constant);\n}\n\n#endif // GRADIENT_FUNCTOR_INC_HPP\n", "meta": {"hexsha": "f81e9bab75b4214f21329cbc0b42b4e21afd2212", "size": 4858, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rjmcmc/image/gradient_functor_inc.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/image/gradient_functor_inc.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/image/gradient_functor_inc.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.4833333333, "max_line_length": 134, "alphanum_fraction": 0.6930835735, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5488263581553926}}
{"text": "#include <map>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include \"DatasetAR.h\"\n#include \"DatasetARX.h\"\n#include \"GaussSeq.h\"\n#include \"ARSeq.h\"\n#include \"ARPoly.h\"\n#include \"utils.h\"\nusing utils::my_float;\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::random::uniform_real_distribution;\n\n\nint main() {\n    boost::random::mt19937 gen {};\n    uniform_real_distribution<my_float> u(-1, 1);\n\n    // prepare \n    std::map<int, my_float> coeff {\n        {3, 0.2},\n        {20, 0.5},\n    };\n    std::map<int, my_float> coeff_2 {\n        {3, 0.75},\n        {20, -0.9},\n    };\n    std::vector<my_float> v_seed(20);\n\n    // Stationary AR process\n    for (auto type = 0; type < 5; type++) {\n        for (auto samp = 0; samp < utils::N_SAMPLE; samp++) {\n            // Seed differently\n            for (auto i = 0; i < 20; i++) {\n                v_seed[i] = u(gen);\n            }\n            ARSeq targ_seq(coeff, u(gen));\n            targ_seq.seed_prev_vals(v_seed);\n\n            DatasetAR dat(\"./ARStat/ARStat-\" + std::to_string(type) + \n                \"/Sample-\" + std::to_string(samp), targ_seq, type);\n            dat.write_csv();\n        }\n    }\n\n    // Non-stationary AR process\n    for (auto type = 0; type < 5; type++) {\n        for (auto samp = 0; samp < utils::N_SAMPLE; samp++) {\n            // Seed differently\n            for (auto i = 0; i < 20; i++) {\n                v_seed[i] = u(gen);\n            }\n            ARSeq targ_seq(coeff_2, u(gen));\n            targ_seq.seed_prev_vals(v_seed);\n\n            DatasetAR dat(\"./ARNStat/ARNStat-\" + std::to_string(type) + \n                \"/Sample-\" + std::to_string(samp), targ_seq, type);\n            dat.write_csv();\n        }\n    }\n\n    // Non-stationary ARX process\n    for (auto type = 1; type < 5; type++) {\n        for (auto samp = 0; samp < utils::N_SAMPLE; samp++) {\n            DatasetARX dat(\"./ARXNStat/ARXNStat-\" + std::to_string(type) + \n                \"/Sample-\" + std::to_string(samp), type);\n            dat.write_csv();\n        }\n    }\n    return 0;\n}\n", "meta": {"hexsha": "0016046576d7fe16b4ac6e55a73c58130371609d", "size": 2217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gen-data/main/gen-train-1.cpp", "max_stars_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_stars_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gen-data/main/gen-train-1.cpp", "max_issues_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_issues_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gen-data/main/gen-train-1.cpp", "max_forks_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_forks_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_forks_repo_licenses": ["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.7922077922, "max_line_length": 75, "alphanum_fraction": 0.5444294091, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5488220441944583}}
{"text": "#ifndef OCV_CBIR_BOVW_HPP\n#define OCV_CBIR_BOVW_HPP\n\n#include \"../arma/type_traits.hpp\"\n\n#include <opencv2/core.hpp>\n\n#include <armadillo>\n\n/*!\n *  \\addtogroup ocv\n *  @{\n */\nnamespace ocv{\n\n/*!\n *  \\addtogroup cbir\n *  @{\n */\nnamespace cbir{\n\n/**\n *Convert the features of images into histogram\n *@tparam T type of the code_book and features\n *@tparam Hist type of histogram\n *@code\n *arma::Mat<float> code_book;\n *code_book.load(\"ukbench.h5\", arma::hdf5_binary);\n *bovw<float> bv(std::move(code_book));\n *arma::Mat<float> features;\n *features.load(\"uk3000\", arma::raw_ascii);\n *auto const hist = bv.describe(features);\n *@endcode\n */\ntemplate<typename T, typename Hist = arma::SpMat<arma::uword>>\nclass bovw\n{    \npublic:\n    bovw()\n    {\n        static_assert(std::is_arithmetic<T>::value,\n                      \"T should be arithmetic type\");\n\n        static_assert(armd::is_arma_matrix<Hist>::value,\n                      \"Hist should be arma::SpMat, arma::Mat,\"\n                      \"arma::Col or arma::Row\");\n    }\n\n    /**\n     * Convert the features of images into histogram\n     * @param features features of the image\n     * @param code_book code book of the data sets\n     * @return histogram of bovw\n     */\n    Hist describe(arma::Mat<T> const &features,\n                  arma::Mat<T> const &code_book) const\n    {\n        arma::Mat<T> dist(features.n_cols, code_book.n_cols);\n        for(arma::uword i = 0; i != features.n_cols; ++i){\n            dist.row(i) = euclidean_dist(features.col(i),\n                                         code_book);\n        }\n        //dist.print(\"dist\");\n\n        Hist hist = create_hist(dist.n_cols,\n                                armd::is_two_dim<Hist>::type());\n        for(arma::uword i = 0; i != dist.n_rows; ++i){\n            arma::uword min_idx;\n            dist.row(i).min(min_idx);\n            ++hist(min_idx);\n        }\n        //hist.print(\"\\nhist\");\n\n        return hist;\n    }\n\nprivate:    \n    Hist create_hist(arma::uword size, std::true_type) const\n    {\n        return arma::zeros<Hist>(size,1);\n    }\n\n    Hist create_hist(arma::uword size, std::false_type) const\n    {\n        return arma::zeros<Hist>(size);\n    }\n\n    template<typename U>\n    arma::Mat<T> euclidean_dist(U const &x,\n                                arma::Mat<T> const &y) const\n    {\n        return arma::sqrt(arma::sum\n                          (arma::square(y.each_col() - x)));\n    }\n};\n\n} /*! @} End of Doxygen Groups*/\n\n} /*! @} End of Doxygen Groups*/\n\n#endif // OCV_CBIR_BOVW_HPP\n", "meta": {"hexsha": "ca6fecf59ba24634eab8fc5cb81dbf76a7f9e251", "size": 2523, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cbir/bovw.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": "cbir/bovw.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": "cbir/bovw.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": 24.7352941176, "max_line_length": 64, "alphanum_fraction": 0.560443916, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5488220441944583}}
{"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_SQRT1PM1_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SQRT1PM1_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing sqrt1pm1 capabilities\n\n    Returns \\f$\\sqrt{1+x}-1\\f$ and the\n    result is accurate even for x  with small modulus\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = sqrt1pm1(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = dec(sqrt(Oneplus(x));\n    @endcode\n\n    @see lol1p, expm1.\n\n  **/\n  Value sqrt1pm1(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sqrt1pm1.hpp>\n#include <boost/simd/function/simd/sqrt1pm1.hpp>\n\n#endif\n", "meta": {"hexsha": "5ec772ba53b1f74a7fa618e9f01b59948ccc544c", "size": 1112, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sqrt1pm1.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/sqrt1pm1.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/sqrt1pm1.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": 21.8039215686, "max_line_length": 100, "alphanum_fraction": 0.5764388489, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5488220347308046}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,\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#include <boost/config.hpp>\n#include <iostream>\n#include <fstream>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\nusing namespace boost;\n\nint\nmain(int, char *[])\n{\n  typedef adjacency_list_traits<listS, listS,\n    directedS>::vertex_descriptor vertex_descriptor;\n  typedef adjacency_list < listS, listS, directedS,\n    property<vertex_index_t, int,\n    property<vertex_name_t, char,\n    property<vertex_distance_t, int,\n    property<vertex_predecessor_t, vertex_descriptor> > > >,\n    property<edge_weight_t, int> > graph_t;\n  typedef std::pair<int, int> Edge;\n\n  const int num_nodes = 5;\n  enum nodes { A, B, C, D, E };\n  Edge edge_array[] = { Edge(A, C), Edge(B, B), Edge(B, D), Edge(B, E),\n    Edge(C, B), Edge(C, D), Edge(D, E), Edge(E, A), Edge(E, B)\n  };\n  int weights[] = { 1, 2, 1, 2, 7, 3, 1, 1, 1 };\n  int num_arcs = sizeof(edge_array) / sizeof(Edge);\n  graph_traits<graph_t>::vertex_iterator i, iend;\n\n  graph_t g(edge_array, edge_array + num_arcs, weights, num_nodes);\n  property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);\n\n  // Manually intialize the vertex index and name maps\n  property_map<graph_t, vertex_index_t>::type indexmap = get(vertex_index, g);\n  property_map<graph_t, vertex_name_t>::type name = get(vertex_name, g);\n  int c = 0;\n  for (boost::tie(i, iend) = vertices(g); i != iend; ++i, ++c) {\n    indexmap[*i] = c;\n    name[*i] = 'A' + c;\n  }\n\n  vertex_descriptor s = vertex(A, g);\n\n  property_map<graph_t, vertex_distance_t>::type\n    d = get(vertex_distance, g);\n  property_map<graph_t, vertex_predecessor_t>::type\n    p = get(vertex_predecessor, g);\n  dijkstra_shortest_paths(g, s, predecessor_map(p).distance_map(d));\n\n  std::cout << \"distances and parents:\" << std::endl;\n  graph_traits < graph_t >::vertex_iterator vi, vend;\n  for (boost::tie(vi, vend) = vertices(g); vi != vend; ++vi) {\n    std::cout << \"distance(\" << name[*vi] << \") = \" << d[*vi] << \", \";\n    std::cout << \"parent(\" << name[*vi] << \") = \" << name[p[*vi]] << std::\n      endl;\n  }\n  std::cout << std::endl;\n\n  std::ofstream dot_file(\"figs/dijkstra-eg.dot\");\n  dot_file << \"digraph D {\\n\"\n    << \"  rankdir=LR\\n\"\n    << \"  size=\\\"4,3\\\"\\n\"\n    << \"  ratio=\\\"fill\\\"\\n\"\n    << \"  edge[style=\\\"bold\\\"]\\n\" << \"  node[shape=\\\"circle\\\"]\\n\";\n\n  graph_traits < graph_t >::edge_iterator ei, ei_end;\n  for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\n    graph_traits < graph_t >::edge_descriptor e = *ei;\n    graph_traits < graph_t >::vertex_descriptor\n      u = source(e, g), v = target(e, g);\n    dot_file << name[u] << \" -> \" << name[v]\n      << \"[label=\\\"\" << get(weightmap, e) << \"\\\"\";\n    if (p[v] == u)\n      dot_file << \", color=\\\"black\\\"\";\n    else\n      dot_file << \", color=\\\"grey\\\"\";\n    dot_file << \"]\";\n  }\n  dot_file << \"}\";\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "60e9d871022bec41245ed8eb7882f2e9c1c3c11e", "size": 3255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/dijkstra-example-listS.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/graph/example/dijkstra-example-listS.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/graph/example/dijkstra-example-listS.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": 35.3804347826, "max_line_length": 78, "alphanum_fraction": 0.5993855607, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5488220347308046}}
{"text": "#pragma once\n\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n#include <pcl/conversions.h>\n#include <pcl/point_cloud.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <eigen_conversions/eigen_msg.h>\n\n#include <ndt_map/pointcloud_utils.h>\n#include <ndt_rviz/ndt_rviz.h>\n\n#include <sstream>\n\n#include <visualization_msgs/MarkerArray.h>\n\nEigen::Affine3d getAsAffine(const Eigen::Vector3d &transl, const Eigen::Vector3d &euler) {\n  Eigen::Affine3d T;\n  {\n    Eigen::Matrix3d m;\n    m = Eigen::AngleAxisd(euler[0], Eigen::Vector3d::UnitX())\n      * Eigen::AngleAxisd(euler[1], Eigen::Vector3d::UnitY())\n      * Eigen::AngleAxisd(euler[2], Eigen::Vector3d::UnitZ());\n    Eigen::Translation3d v(transl);\n    T = v*m;\n  }\n  return T;\n}\n\n\nstd::string affine3dToString(const Eigen::Affine3d &T) {\n  std::ostringstream stream;\n  stream << std::setprecision(std::numeric_limits<double>::digits10);\n  Eigen::Vector3d rot = T.rotation().eulerAngles(0,1,2);\n\n  stream << T.translation().transpose() << \" \" << rot.transpose();\n  return stream.str();\n}\n\n\n\nclass NDTCalibScan {\npublic:\n  pcl::PointCloud<pcl::PointXYZ> cloud; // cloud in sensor coords\n  Eigen::Affine3d pose;  // estimated pose in global frame (preferably from a GT system)...\n  Eigen::Affine3d estSensorPose; // estimated sensor pose in global frame (typically from a SLAM / registration system)\n  double stamp;\n  \n  NDTCalibScan() {\n    \n  }\n \n  NDTCalibScan(const Eigen::Affine3d &_pose, const Eigen::Affine3d &_estSensorPose, double _stamp) : pose(_pose), estSensorPose(_estSensorPose), stamp(_stamp) {\n    \n  }\n\n  NDTCalibScan(const pcl::PointCloud<pcl::PointXYZ> &_cloud, const Eigen::Affine3d &_pose, double _stamp) : cloud(_cloud), pose(_pose), stamp(_stamp) \n  {\n\n  }\n    \n  NDTCalibScan(const pcl::PointCloud<pcl::PointXYZ> &_cloud, const Eigen::Affine3d &_pose, const Eigen::Affine3d &_estSensorPose, double _stamp)  : cloud(_cloud), pose(_pose), estSensorPose(_estSensorPose), stamp(_stamp)\n  {\n    \n  }\n\n  void appendPointCloudGlobal(const Eigen::Affine3d &Ts, pcl::PointCloud<pcl::PointXYZ> &p) const {\n    \n    pcl::PointCloud<pcl::PointXYZ> c =cloud;\n    Eigen::Affine3d T = pose * Ts;\n    perception_oru::transformPointCloudInPlace(T, c);\n    p += c;\n  }\n\n  // Simply the euclidean offset bettwen the estimated sensor pose and the given gt poses\n  double scoreEstSensorPose(const Eigen::Affine3d &Ts) const {\n    Eigen::Affine3d T = pose * Ts;\n    return (T * estSensorPose.inverse()).translation().norm();\n  }\n\n    // Return Ts from the global estimate sensor pose and the vehicle pose (both in the same global reference frame).  \n  Eigen::Affine3d getTs() const {\n    return (pose.inverse() * estSensorPose);\n  }\n  \n  Eigen::Affine3d getSensorPoseFromPose(const Eigen::Affine3d &Ts) const  {\n    return pose*Ts;\n  }\n};\n\nEigen::VectorXd getTranslationEulerAnglesVector(const Eigen::Affine3d &T) {\n  Eigen::VectorXd ret(6);\n  ret[0] = T.translation()[0];\n  ret[1] = T.translation()[1];\n  ret[2] = T.translation()[2];\n  Eigen::Vector3d rot = T.rotation().eulerAngles(0,1,2);\n  ret[3] = rot[0];\n  ret[4] = rot[1];\n  ret[5] = rot[2];\n  \n  return ret;\n}\n\n\nclass NDTCalibScanPair {\n\npublic:\t\n  NDTCalibScan first;\n  NDTCalibScan second;\n\n  NDTCalibScanPair() {\n\n  }\n  NDTCalibScanPair(const pcl::PointCloud<pcl::PointXYZ> &p1, const Eigen::Affine3d &pose1,\n                   const pcl::PointCloud<pcl::PointXYZ> &p2, const Eigen::Affine3d &pose2) :\n    first(NDTCalibScan(p1, pose1, -1.)), second(NDTCalibScan(p2, pose2, -1.))\n  {    \n\n  }\n\n  Eigen::Affine3d getRelativePose() const {\n    return this->second.pose * this->first.pose.inverse();\n  }\n\n  Eigen::Affine3d getRelativeEstSensorPose() const {\n    return this->second.estSensorPose * this->first.estSensorPose.inverse();\n  }\n  \n  // Compute the score for a relative sensor pose offset - that is the pose and the est sensor pose don't have to be in the same coordinate frame.\n  double scoreEstSensorPoseRel(const Eigen::Affine3d &Ts) const {\n    Eigen::Affine3d rel = getRelativePose();\n    Eigen::Affine3d rel_est = getRelativeEstSensorPose();\n    return (Ts * rel_est * Ts.inverse() * rel.inverse()).translation().norm();\n  }\n\n  // Compute the predicted relative estimated sensor pose.\n  Eigen::Affine3d getPredictedRelativeEstSensorPose(const Eigen::Affine3d &Ts) const {\n    Eigen::Affine3d rel = getRelativePose();\n    return (Ts.inverse() * rel * Ts);\n  }\n\n  // Compute difference between the relative estimated and the predicted sensor pose\n  Eigen::Affine3d getDifference(const Eigen::Affine3d &Ts) const {\n    Eigen::Affine3d T = getPredictedRelativeEstSensorPose(Ts);\n    Eigen::Affine3d rel_est = getRelativeEstSensorPose();\n    \n    return rel_est.inverse()*T;\n  }\n\n  // Get the difference in x,y,z and euler angles\n  Eigen::VectorXd getDifferenceVector(const Eigen::Affine3d &Ts)  const {\n    return getTranslationEulerAnglesVector(getDifference(Ts));\n  }\n  \n  ///Get point cloud in global coords\n  void appendPointCloudGlobal(const Eigen::Affine3d &Ts, pcl::PointCloud<pcl::PointXYZ> &p) const {\n    \n    this->first.appendPointCloudGlobal(Ts, p);\n    this->second.appendPointCloudGlobal(Ts, p);\n  }\n\n  /**\n   * Compute ICP score for sensor offset\n   */\n  double scoreICP(const Eigen::Affine3d &Ts) const {\n    pcl::PointCloud<pcl::PointXYZ> c1=this->first.cloud;\n    Eigen::Affine3d p1 = this->first.pose * Ts;\n    perception_oru::transformPointCloudInPlace(p1, c1);\n    \n    pcl::PointCloud<pcl::PointXYZ> c2=this->second.cloud;\n    Eigen::Affine3d p2 = this->second.pose * Ts;\n    perception_oru::transformPointCloudInPlace(p2, c2);\n    \n    pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;\n    typename pcl::KdTree<pcl::PointXYZ>::PointCloudPtr mp (new pcl::PointCloud<pcl::PointXYZ>);\n    if(c1.size()==0){\n      fprintf(stderr,\"Check -> num points = %d\\n\",(int)c1.size());\n    }\n    //fprintf(stderr,\"1: '%d' -- \",c1.size());\n    (*mp) = c1;\n    //fprintf(stderr,\"2: '%d' == '%d'\\n\",c1.size(), mp->size());\n    kdtree.setInputCloud (mp);\n    int K = 1;\n    std::vector<int> pointIdxNKNSearch(K);\n    std::vector<float> pointNKNSquaredDistance(K);\n    double e=0, error_th=0.1*0.1;\n    \n    for(unsigned int i=0;i<c2.size();i++){\n      if ( kdtree.nearestKSearch (c2[i], K, pointIdxNKNSearch, pointNKNSquaredDistance) > 0 ){\n        if(pointNKNSquaredDistance[0] > error_th){\n          e+=error_th;\n        }\n        else{\n          e+= pointNKNSquaredDistance[0];\n        }\n        //fprintf(f,\"%f\\n\",pointNKNSquaredDistance[0]);\n      }\n    }//FOR\n    \n    return e;\n  }\n};\n\n\n// Load the evaluation files that are generated by the fuser, <timestamp> x y x qx qy qz qw.\nstd::vector<Eigen::Affine3d> loadAffineFromEvalFile(const std::string &fileName) {\n  std::vector<Eigen::Affine3d> ret;\n  std::string line;\n  std::ifstream myfile (fileName.c_str());\n  if (myfile.is_open())\n  {\n    while ( getline (myfile,line) )\n    {\n      double time, x, y, z, qx, qy, qz, qw;\n      std::istringstream ss(line);\n      ss >> time >> x >> y >> z >> qx >> qy >> qz >> qw;\n      ret.push_back(Eigen::Translation3d(x,y,z)*Eigen::Quaterniond(qw, qx, qy, qz));\n    }\n    myfile.close();\n  }\n  else {\n    std::cout << \"Unable to open file : \" << fileName << std::endl;\n  } \n  \n  return ret;\n}\n\n// Load timestamps from the evaluation files that are generated by the fuser...\nstd::vector<double> loadTimeStampFromEvalFile(const std::string &fileName) {\n  std::vector<double> ret;\n  std::string line;\n  std::ifstream myfile (fileName.c_str());\n  if (myfile.is_open())\n  {\n    while ( getline (myfile,line) )\n    {\n      double time, x, y, z, qx, qy, qz, qw;\n      std::istringstream ss(line);\n      ss >> time >> x >> y >> z >> qx >> qy >> qz >> qw;\n      ret.push_back(time);\n   }\n   myfile.close();\n }\n  else std::cout << \"Unable to open file : \" << fileName << std::endl;; \n  \n  return ret;\n}\n\n\nvoid loadNDTCalibScanPairs(const std::string &gt_file, const std::string &est_sensorpose_file, const std::string &base_name_pcd, std::vector<NDTCalibScanPair> &scans) {\n  scans.resize(0);\n\n  // Load the data...\n  std::vector<double> stamps = loadTimeStampFromEvalFile(gt_file);\n  std::vector<Eigen::Affine3d> Tgt = loadAffineFromEvalFile(gt_file);\n  std::vector<Eigen::Affine3d> Test_sensorpose = loadAffineFromEvalFile(est_sensorpose_file);\n\n  if (Tgt.size() != stamps.size() || Tgt.size() != Test_sensorpose.size()) {\n    std::cerr << \"Warning: the length of the provided files to not match(!)\" << std::endl;\n  }\n\n  // Need to find a pair of scans which is useful in the optimization scheme. Pair of scans with limited translation but with some rotation...\n  size_t j = 0;\n  for (size_t i = 1; i < Tgt.size(); i++) {\n    Eigen::Affine3d Tmotion = Tgt[j].inverse()*Tgt[i];\n\n    Eigen::Affine3d Ttest = Tgt[j]*Tmotion;\n    // while (Tmotion.translation().norm() > 3) {\n    //   j++;\n    //   Tmotion = Tgt[i] * Tgt[j].inverse();\n    // }\n    if (Tmotion.translation().norm() > 3) {\n      j = i; // reset -> make this better, could be that many potential pairs are left out..., add a while loop instead.\n      continue;\n    }\n    if (Tmotion.rotation().eulerAngles(0,1,2).norm() < 5.0*M_PI/180.0) {\n      continue;\n    }\n    \n    // Good pair found...\n    NDTCalibScanPair pair;\n    pair.first = NDTCalibScan(Tgt[j], Test_sensorpose[j], stamps[j]);\n    pair.second = NDTCalibScan(Tgt[i], Test_sensorpose[i], stamps[i]);\n    scans.push_back(pair);\n    j = i; // reset\n  }\n  \n}\n\n\n\n// // Helper functions for ROS\n// geometry_msgs::PoseStamped getGtPoseFromCalibScan(const NDTCalibScan &scan) {\n//   geometry_msgs::PoseStamped p;\n//   tf::poseEigenToMsg (scan.pose, p.pose);\n//   p.header.stamp = ros::Time(scan.stamp);\n//   p.header.frame_id = std::string(\"/world\");\n  \n//   return p; \n// }\n\n// geometry_msgs::Pose getEstSensorPoseFromCalibScan(const NDTCalibScan &scan) {\n//   geometry_msgs::PoseStamped p;\n//   tf::poseEigenToMsg (scan.estSensorPose, p.pose);\n//   p.header.stamp = ros::Time(scan.stamp);\n//   p.header.frame_id = std::string(\"/world\");\n  \n//   return p;\n// }\n\n\n\n\nnamespace ndt_visualisation {\n\n\n// Visualization markers.\nvoid appendMarkerArray(visualization_msgs::MarkerArray &array, const visualization_msgs::MarkerArray &add) {\n  for (size_t i = 0; i < add.markers.size(); i++) {\n    array.markers.push_back(add.markers[i]);\n  }\n}\n\n\nvisualization_msgs::Marker getMarkerArrowAffine3d(const Eigen::Affine3d &T, int id, int color, const std::string &ns) {\n  visualization_msgs::Marker m;\n  assignDefault(m);\n  assignColor(m, color);\n  m.ns = ns;\n  m.type = visualization_msgs::Marker::ARROW;\n  m.action = visualization_msgs::Marker::ADD;\n  m.scale.y = 0.1; m.scale.z = 0.1;\n  m.id = id;\n  tf::poseEigenToMsg (T, m.pose);\n  return m;\n} \n\n\nvisualization_msgs::Marker getMarkerCylinder(const Eigen::Affine3d &T,\n                                                  int id, int color,\n                                                  double length, double radius,\n                                                  const std::string &ns) {\n  visualization_msgs::Marker m;\n  assignDefault(m);\n  assignColor(m, color);\n  m.ns = ns;\n  m.type = visualization_msgs::Marker::CYLINDER;\n  m.action = visualization_msgs::Marker::ADD;\n  m.id = id;\n\n  m.scale.x = radius; m.scale.y = radius; m.scale.z = length;\n  tf::poseEigenToMsg(T, m.pose);\n  return m;\n}\n\n/// Draw an x,y,z coordsystem given an affine3d.\nvisualization_msgs::MarkerArray getMarkerFrameAffine3d(const Eigen::Affine3d &T, const std::string &ns, double length, double radius) {\n\n  visualization_msgs::MarkerArray m;\n  // X\n  {\n    Eigen::Affine3d T_x =\n      Eigen::Translation3d(length / 2.0, 0, 0) * Eigen::AngleAxisd(M_PI / 2.0, Eigen::Vector3d::UnitY());\n    T_x = T * T_x;\n    m.markers.push_back(getMarkerCylinder(T_x, 0, 0, length, radius, ns));\n  }\n  // Y\n  {\n    Eigen::Affine3d T_y =\n      Eigen::Translation3d(0, length / 2.0, 0) * Eigen::AngleAxisd(M_PI / 2.0, Eigen::Vector3d::UnitX());\n    T_y = T * T_y;\n    m.markers.push_back(getMarkerCylinder(T_y, 1, 1, length, radius, ns));\n  }\n  // Z\n  {\n    Eigen::Affine3d T_z = Eigen::Translation3d(0, 0, length / 2.0) * Eigen::AngleAxisd(0, Eigen::Vector3d::UnitZ());\n    T_z = T * T_z;\n    m.markers.push_back(getMarkerCylinder(T_z, 2, 2, length, radius, ns));\n  }\n  return m;\n}\n\nvisualization_msgs::Marker getMarkerPoseFromNDTCalibScan(const NDTCalibScan &scan, int id, int color) {\n  return getMarkerArrowAffine3d(scan.pose, id, color, \"ndt_calib_pose\");\n}\n\nvisualization_msgs::Marker getMarkerEstSensorPoseFromNDTCalibScan(const NDTCalibScan &scan, int id, int color) {\n  return getMarkerArrowAffine3d(scan.estSensorPose, id, color, \"ndt_calib_est_sensor_pose\");\n}\n\nvisualization_msgs::Marker getCorrMarkerPoseToEstSensorPose(const NDTCalibScan &scan, int id, int color) {\n visualization_msgs::Marker m;\n assignDefault(m);\n assignColor(m, color);\n m.type = visualization_msgs::Marker::LINE_STRIP;\n m.action = visualization_msgs::Marker::ADD;\n m.id = id;\n m.ns = \"ndt_calib_corr_pose_est_sensor_pose\";\n m.scale.x = 0.05;\n\n geometry_msgs::Point p;\n tf::pointEigenToMsg (scan.pose.translation(), p);\n m.points.push_back(p);\n tf::pointEigenToMsg (scan.estSensorPose.translation(), p);\n m.points.push_back(p);\n return m;\n}\n\nvisualization_msgs::MarkerArray getMarkerArrayFromNDTCalibScanPairs(const std::vector<NDTCalibScanPair> &pairs) {\n  visualization_msgs::MarkerArray m;\n\n  for (size_t i = 0; i < pairs.size(); i++) {\n    m.markers.push_back(getMarkerPoseFromNDTCalibScan(pairs[i].first, 2*i, 0));\n    m.markers.push_back(getMarkerPoseFromNDTCalibScan(pairs[i].second, 2*i+1, 1));\n    m.markers.push_back(getMarkerEstSensorPoseFromNDTCalibScan(pairs[i].first, 2*i, 2));\n    m.markers.push_back(getMarkerEstSensorPoseFromNDTCalibScan(pairs[i].second, 2*i+1, 2));\n    m.markers.push_back(getCorrMarkerPoseToEstSensorPose(pairs[i].first, i, 0));\n  }  \n  return m;\n}\n\n\n\nvisualization_msgs::MarkerArray getMarkerArrayRelFromNDTCalibScanPair(const NDTCalibScanPair &pair, const Eigen::Affine3d &Ts) {\n  visualization_msgs::MarkerArray m;\n\n  // Draw the coordinate system of the relative frames.\n  appendMarkerArray(m, getMarkerFrameAffine3d(pair.getRelativePose(), \n                                               std::string(\"ndt_calib_rel_pose\"), 1.0, 0.1));\n  appendMarkerArray(m, getMarkerFrameAffine3d(pair.getRelativeEstSensorPose(), \n                                              std::string(\"ndt_calib_rel_est_sensor_pose\"), 1.0, 0.1));\n  appendMarkerArray(m, getMarkerFrameAffine3d(pair.getPredictedRelativeEstSensorPose(Ts),\n                                              std::string(\"ndt_calib_pred_rel_est_sensor_pose\"), 1.0, 0.1));\n\n\n\n  appendMarkerArray(m, getMarkerFrameAffine3d(pair.first.getSensorPoseFromPose(Ts), std::string(\"ndt_calib_sensor_pose_from_first_pose\"), 1., 0.1));\n  appendMarkerArray(m, getMarkerFrameAffine3d(pair.first.getSensorPoseFromPose(Ts), std::string(\"ndt_calib_sensor_pose_from_second_pose\"), 1., 0.1));\n  \n\n  \n  return m;\n}\n\n\n} // namespace ndt_visualisation\n\n\n\n\n", "meta": {"hexsha": "404f328c7c83da7cde8c28d5085caca516894b53", "size": 14985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_calibration/include/ndt_calibration/ndt_calib_test.cpp", "max_stars_repo_name": "lllray/ndt-loam", "max_stars_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-14T08:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-14T08:21:13.000Z", "max_issues_repo_path": "perception_oru-port-kinetic/ndt_calibration/include/ndt_calibration/ndt_calib_test.cpp", "max_issues_repo_name": "lllray/ndt-loam", "max_issues_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-28T04:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T04:47:56.000Z", "max_forks_repo_path": "perception_oru-port-kinetic/ndt_calibration/include/ndt_calibration/ndt_calib_test.cpp", "max_forks_repo_name": "lllray/ndt-loam", "max_forks_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-18T11:25:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T12:59:59.000Z", "avg_line_length": 33.0794701987, "max_line_length": 220, "alphanum_fraction": 0.6704704705, "num_tokens": 4353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6791786991753931, "lm_q1q2_score": 0.5488220326684791}}
{"text": "/*BISHOPS - Bishops\n#math #big-numbers #ad-hoc-1\n\nYesterday was Sam's birthday. The most interesting gift was definitely the chessboard. Sam quickly learned the rules of chess and defeated his father, all his friends, his little sister, and now no one wants to play with him any more.\n\nSo he decided to play with another birthday gift \u2013 a Book of Math Problems for Young Mathematicians. He opened the book somewhere in the middle and read the following problem: \"How many knights can be placed on a chessboard without threatening each other?\" After a while he realized that this was trivial and moved on to the next problem: \"How many bishops can be placed on a chessboard without threatening each other?\". Sam is in trouble here. He is not able to solve this problem and needs your help.\n\nSam's chessboard has size N x N. A bishop can move to any distance in any of the four diagonal directions. A bishop threatens another bishop if it can move to the other bishop's position. Your task is to compute the maximum number of bishops that can be placed on a chessboard in such a way that no two bishops threaten each other.\nInput\n\nThe input file consists of several lines. The line number i contains a single positive integer N representing the size of the i-th chessboard. [1 <= N <= 10^100]\nOutput\n\nThe output file should contain the same number of lines as the input file. The i-th line should contain one number \u2013 the maximum number of bishops that can be placed on i-th chessboard without threatening each other.\nExample\n\nInput:\n2\n3\n\nOutput:\n2\n4\n\n*/\n\n#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nint main()\n{\n    using namespace boost::multiprecision;\n    \n    cpp_int num;\n    \n    while (std::cin >> num)\n    {\n        std::cout << (num <= 1 ? num : 2*num - 2) << std::endl;\n    }\n    \n    return 0;\n}\n", "meta": {"hexsha": "da9b988a8be64c76035c95c751b0419bc4049570", "size": 1827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SPOJ/BISHOPS - Bishops.cpp", "max_stars_repo_name": "ravirathee/Competitive-Programming", "max_stars_repo_head_hexsha": "20a0bfda9f04ed186e2f475644e44f14f934b533", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-11-26T02:38:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T00:16:41.000Z", "max_issues_repo_path": "SPOJ/BISHOPS - Bishops.cpp", "max_issues_repo_name": "ravirathee/Competitive-Programming", "max_issues_repo_head_hexsha": "20a0bfda9f04ed186e2f475644e44f14f934b533", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-30T09:25:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-05T08:33:56.000Z", "max_forks_repo_path": "SPOJ/BISHOPS - Bishops.cpp", "max_forks_repo_name": "ravirathee/Competitive-Programming", "max_forks_repo_head_hexsha": "20a0bfda9f04ed186e2f475644e44f14f934b533", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-16T07:15:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T06:26:07.000Z", "avg_line_length": 42.488372093, "max_line_length": 502, "alphanum_fraction": 0.746031746, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.548743272650867}}
{"text": "#ifndef BG_TYPES_HPP\n#define BG_TYPES_HPP\n\n#include <boost/geometry.hpp>\n\nusing PointGeo = boost::geometry::model::d2::point_xy<\n    double, boost::geometry::cs::geographic<boost::geometry::degree>>;\nusing BoxGeo = boost::geometry::model::box<PointGeo>;\nusing LinestringGeo = boost::geometry::model::linestring<PointGeo>;\nusing RingGeo = boost::geometry::model::ring<PointGeo>;\nusing PolygonGeo = boost::geometry::model::polygon<PointGeo>;\nusing MultipolygonGeo = boost::geometry::model::multi_polygon<PolygonGeo>;\n\nusing Point2D = boost::geometry::model::d2::point_xy<double>;\nusing Box2D = boost::geometry::model::box<Point2D>;\nusing Linestring2D = boost::geometry::model::linestring<Point2D>;\nusing Ring2D = boost::geometry::model::ring<Point2D>;\nusing Polygon2D = boost::geometry::model::polygon<Point2D>;\nusing Multipolygon2D = boost::geometry::model::multi_polygon<Polygon2D>;\n\n#endif  // BG_TYPES_HPP", "meta": {"hexsha": "6f5bb15c953d344ecb9a1f0351e0c5242700c60e", "size": 907, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bg_types.hpp", "max_stars_repo_name": "fhamonic/osm2sorted_geojson", "max_stars_repo_head_hexsha": "de2b83e43dab9756464a0de42f45335aa3562ce4", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T11:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T11:56:01.000Z", "max_issues_repo_path": "include/bg_types.hpp", "max_issues_repo_name": "fhamonic/osm2geojson", "max_issues_repo_head_hexsha": "de2b83e43dab9756464a0de42f45335aa3562ce4", "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/bg_types.hpp", "max_forks_repo_name": "fhamonic/osm2geojson", "max_forks_repo_head_hexsha": "de2b83e43dab9756464a0de42f45335aa3562ce4", "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.1904761905, "max_line_length": 74, "alphanum_fraction": 0.7640573319, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5486935599739278}}
{"text": "//==================================================================================================\n/*!\n  @file\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_ERF_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ERF_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-euler\n   This function object computes  the error function:\n   \\f$\\displaystyle \\frac{2}{\\sqrt\\pi}\\int_0^{x} e^{-t^2}\\mbox{d}t\\f$\n\n\n    @par Header <boost/simd/function/erf.hpp>\n\n    @par Decorators\n\n      - std_ calls @c std::erf\n\n    @see erfc,  erfcx\n\n    @par Example:\n\n      @snippet erf.cpp erf\n\n    @par Possible output:\n\n      @snippet erf.txt erf\n  **/\n  IEEEValue erf(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/erf.hpp>\n#include <boost/simd/function/simd/erf.hpp>\n\n#endif\n", "meta": {"hexsha": "ede4e883df2ea07098b0282d0ad82fbda6de5990", "size": 1080, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/erf.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/function/erf.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/function/erf.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": 22.9787234043, "max_line_length": 100, "alphanum_fraction": 0.562962963, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5486935599077786}}
{"text": "#ifndef TEST_CASE_H_\n#define TEST_CASE_H_\n\n#include <Eigen/Dense>\n\nclass Case1 {\npublic:\n  Case1(const Eigen::Ref<const Eigen::MatrixXd> &matM,\n        const Eigen::Ref<const Eigen::MatrixXd> &matD,\n        const Eigen::Ref<const Eigen::MatrixXd> &matK);\n\nprivate:\n  const int ndim_;\n  Eigen::MatrixXd matM_, matD_, matK_;\n  Eigen::MatrixXd matC_, matG_;\n\npublic:\n  Eigen::VectorXcd alphas;\n  Eigen::VectorXd betas;\n};\n\n#endif", "meta": {"hexsha": "318cca8b523017e1f7cfd57235eea1847e642f7d", "size": 426, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/case.hpp", "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.hpp", "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.hpp", "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": 19.3636363636, "max_line_length": 55, "alphanum_fraction": 0.7018779343, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5486935487187734}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2014 Jianwei Cui <thucjw@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/CXX11/Tensor>\n\nusing Eigen::Tensor;\n\ntemplate <int DataLayout>\nstatic void test_fft_2D_golden() {\n  Tensor<float, 2, DataLayout, long> input(2, 3);\n  input(0, 0) = 1;\n  input(0, 1) = 2;\n  input(0, 2) = 3;\n  input(1, 0) = 4;\n  input(1, 1) = 5;\n  input(1, 2) = 6;\n\n  array<int, 2> fft;\n  fft[0] = 0;\n  fft[1] = 1;\n\n  Tensor<std::complex<float>, 2, DataLayout, long> output = input.template fft<Eigen::BothParts, Eigen::FFT_FORWARD>(fft);\n\n  std::complex<float> output_golden[6]; // in ColMajor order\n  output_golden[0] = std::complex<float>(21, 0);\n  output_golden[1] = std::complex<float>(-9, 0);\n  output_golden[2] = std::complex<float>(-3, 1.73205);\n  output_golden[3] = std::complex<float>( 0, 0);\n  output_golden[4] = std::complex<float>(-3, -1.73205);\n  output_golden[5] = std::complex<float>(0 ,0);\n\n  std::complex<float> c_offset = std::complex<float>(1.0, 1.0);\n\n  if (DataLayout == ColMajor) {\n    VERIFY_IS_APPROX(output(0) + c_offset, output_golden[0] + c_offset);\n    VERIFY_IS_APPROX(output(1) + c_offset, output_golden[1] + c_offset);\n    VERIFY_IS_APPROX(output(2) + c_offset, output_golden[2] + c_offset);\n    VERIFY_IS_APPROX(output(3) + c_offset, output_golden[3] + c_offset);\n    VERIFY_IS_APPROX(output(4) + c_offset, output_golden[4] + c_offset);\n    VERIFY_IS_APPROX(output(5) + c_offset, output_golden[5] + c_offset);\n  }\n  else {\n    VERIFY_IS_APPROX(output(0)+ c_offset, output_golden[0]+ c_offset);\n    VERIFY_IS_APPROX(output(1)+ c_offset, output_golden[2]+ c_offset);\n    VERIFY_IS_APPROX(output(2)+ c_offset, output_golden[4]+ c_offset);\n    VERIFY_IS_APPROX(output(3)+ c_offset, output_golden[1]+ c_offset);\n    VERIFY_IS_APPROX(output(4)+ c_offset, output_golden[3]+ c_offset);\n    VERIFY_IS_APPROX(output(5)+ c_offset, output_golden[5]+ c_offset);\n  }\n}\n\nstatic void test_fft_complex_input_golden() {\n  Tensor<std::complex<float>, 1, ColMajor, long> input(5);\n  input(0) = std::complex<float>(1, 1);\n  input(1) = std::complex<float>(2, 2);\n  input(2) = std::complex<float>(3, 3);\n  input(3) = std::complex<float>(4, 4);\n  input(4) = std::complex<float>(5, 5);\n\n  array<int, 1> fft;\n  fft[0] = 0;\n\n  Tensor<std::complex<float>, 1, ColMajor, long> forward_output_both_parts = input.fft<BothParts, FFT_FORWARD>(fft);\n  Tensor<std::complex<float>, 1, ColMajor, long> reverse_output_both_parts = input.fft<BothParts, FFT_REVERSE>(fft);\n\n  Tensor<float, 1, ColMajor, long> forward_output_real_part = input.fft<RealPart, FFT_FORWARD>(fft);\n  Tensor<float, 1, ColMajor, long> reverse_output_real_part = input.fft<RealPart, FFT_REVERSE>(fft);\n\n  Tensor<float, 1, ColMajor, long> forward_output_imag_part = input.fft<ImagPart, FFT_FORWARD>(fft);\n  Tensor<float, 1, ColMajor, long> reverse_output_imag_part = input.fft<ImagPart, FFT_REVERSE>(fft);\n\n  VERIFY_IS_EQUAL(forward_output_both_parts.dimension(0), input.dimension(0));\n  VERIFY_IS_EQUAL(reverse_output_both_parts.dimension(0), input.dimension(0));\n\n  VERIFY_IS_EQUAL(forward_output_real_part.dimension(0), input.dimension(0));\n  VERIFY_IS_EQUAL(reverse_output_real_part.dimension(0), input.dimension(0));\n\n  VERIFY_IS_EQUAL(forward_output_imag_part.dimension(0), input.dimension(0));\n  VERIFY_IS_EQUAL(reverse_output_imag_part.dimension(0), input.dimension(0));\n\n  std::complex<float> forward_golden_result[5];\n  std::complex<float> reverse_golden_result[5];\n\n  forward_golden_result[0] = std::complex<float>(15.000000000000000,+15.000000000000000);\n  forward_golden_result[1] = std::complex<float>(-5.940954801177935, +0.940954801177934);\n  forward_golden_result[2] = std::complex<float>(-3.312299240582266, -1.687700759417735);\n  forward_golden_result[3] = std::complex<float>(-1.687700759417735, -3.312299240582266);\n  forward_golden_result[4] = std::complex<float>( 0.940954801177934, -5.940954801177935);\n\n  reverse_golden_result[0] = std::complex<float>( 3.000000000000000, + 3.000000000000000);\n  reverse_golden_result[1] = std::complex<float>( 0.188190960235587, - 1.188190960235587);\n  reverse_golden_result[2] = std::complex<float>(-0.337540151883547, - 0.662459848116453);\n  reverse_golden_result[3] = std::complex<float>(-0.662459848116453, - 0.337540151883547);\n  reverse_golden_result[4] = std::complex<float>(-1.188190960235587, + 0.188190960235587);\n\n  for(int i = 0; i < 5; ++i) {\n    VERIFY_IS_APPROX(forward_output_both_parts(i), forward_golden_result[i]);\n    VERIFY_IS_APPROX(forward_output_real_part(i), forward_golden_result[i].real());\n    VERIFY_IS_APPROX(forward_output_imag_part(i), forward_golden_result[i].imag());\n  }\n\n  for(int i = 0; i < 5; ++i) {\n    VERIFY_IS_APPROX(reverse_output_both_parts(i), reverse_golden_result[i]);\n    VERIFY_IS_APPROX(reverse_output_real_part(i), reverse_golden_result[i].real());\n    VERIFY_IS_APPROX(reverse_output_imag_part(i), reverse_golden_result[i].imag());\n  }\n}\n\nstatic void test_fft_real_input_golden() {\n  Tensor<float, 1, ColMajor, long> input(5);\n  input(0) = 1.0;\n  input(1) = 2.0;\n  input(2) = 3.0;\n  input(3) = 4.0;\n  input(4) = 5.0;\n\n  array<int, 1> fft;\n  fft[0] = 0;\n\n  Tensor<std::complex<float>, 1, ColMajor, long> forward_output_both_parts = input.fft<BothParts, FFT_FORWARD>(fft);\n  Tensor<std::complex<float>, 1, ColMajor, long> reverse_output_both_parts = input.fft<BothParts, FFT_REVERSE>(fft);\n\n  Tensor<float, 1, ColMajor, long> forward_output_real_part = input.fft<RealPart, FFT_FORWARD>(fft);\n  Tensor<float, 1, ColMajor, long> reverse_output_real_part = input.fft<RealPart, FFT_REVERSE>(fft);\n\n  Tensor<float, 1, ColMajor, long> forward_output_imag_part = input.fft<ImagPart, FFT_FORWARD>(fft);\n  Tensor<float, 1, ColMajor, long> reverse_output_imag_part = input.fft<ImagPart, FFT_REVERSE>(fft);\n\n  VERIFY_IS_EQUAL(forward_output_both_parts.dimension(0), input.dimension(0));\n  VERIFY_IS_EQUAL(reverse_output_both_parts.dimension(0), input.dimension(0));\n\n  VERIFY_IS_EQUAL(forward_output_real_part.dimension(0), input.dimension(0));\n  VERIFY_IS_EQUAL(reverse_output_real_part.dimension(0), input.dimension(0));\n\n  VERIFY_IS_EQUAL(forward_output_imag_part.dimension(0), input.dimension(0));\n  VERIFY_IS_EQUAL(reverse_output_imag_part.dimension(0), input.dimension(0));\n\n  std::complex<float> forward_golden_result[5];\n  std::complex<float> reverse_golden_result[5];\n\n\n  forward_golden_result[0] = std::complex<float>(  15, 0);\n  forward_golden_result[1] = std::complex<float>(-2.5, +3.44095480117793);\n  forward_golden_result[2] = std::complex<float>(-2.5, +0.81229924058227);\n  forward_golden_result[3] = std::complex<float>(-2.5, -0.81229924058227);\n  forward_golden_result[4] = std::complex<float>(-2.5, -3.44095480117793);\n\n  reverse_golden_result[0] = std::complex<float>( 3.0, 0);\n  reverse_golden_result[1] = std::complex<float>(-0.5, -0.688190960235587);\n  reverse_golden_result[2] = std::complex<float>(-0.5, -0.162459848116453);\n  reverse_golden_result[3] = std::complex<float>(-0.5, +0.162459848116453);\n  reverse_golden_result[4] = std::complex<float>(-0.5, +0.688190960235587);\n\n  std::complex<float> c_offset(1.0, 1.0);\n  float r_offset = 1.0;\n\n  for(int i = 0; i < 5; ++i) {\n    VERIFY_IS_APPROX(forward_output_both_parts(i) + c_offset, forward_golden_result[i] + c_offset);\n    VERIFY_IS_APPROX(forward_output_real_part(i)  + r_offset, forward_golden_result[i].real() + r_offset);\n    VERIFY_IS_APPROX(forward_output_imag_part(i)  + r_offset, forward_golden_result[i].imag() + r_offset);\n  }\n\n  for(int i = 0; i < 5; ++i) {\n    VERIFY_IS_APPROX(reverse_output_both_parts(i) + c_offset, reverse_golden_result[i] + c_offset);\n    VERIFY_IS_APPROX(reverse_output_real_part(i)  + r_offset, reverse_golden_result[i].real() + r_offset);\n    VERIFY_IS_APPROX(reverse_output_imag_part(i)  + r_offset, reverse_golden_result[i].imag() + r_offset);\n  }\n}\n\n\ntemplate <int DataLayout, typename RealScalar, bool isComplexInput, int FFTResultType, int FFTDirection, int TensorRank>\nstatic void test_fft_real_input_energy() {\n\n  Eigen::DSizes<long, TensorRank> dimensions;\n  int total_size = 1;\n  for (int i = 0; i < TensorRank; ++i) {\n    dimensions[i] = rand() % 20 + 1;\n    total_size *= dimensions[i];\n  }\n  const DSizes<long, TensorRank> arr = dimensions;\n\n  typedef typename internal::conditional<isComplexInput == true, std::complex<RealScalar>, RealScalar>::type InputScalar;\n\n  Tensor<InputScalar, TensorRank, DataLayout, long> input;\n  input.resize(arr);\n  input.setRandom();\n\n  array<int, TensorRank> fft;\n  for (int i = 0; i < TensorRank; ++i) {\n    fft[i] = i;\n  }\n\n  typedef typename internal::conditional<FFTResultType == Eigen::BothParts, std::complex<RealScalar>, RealScalar>::type OutputScalar;\n  Tensor<OutputScalar, TensorRank, DataLayout> output;\n  output = input.template fft<FFTResultType, FFTDirection>(fft);\n\n  for (int i = 0; i < TensorRank; ++i) {\n    VERIFY_IS_EQUAL(output.dimension(i), input.dimension(i));\n  }\n\n  float energy_original = 0.0;\n  float energy_after_fft = 0.0;\n\n  for (int i = 0; i < total_size; ++i) {\n    energy_original += pow(std::abs(input(i)), 2);\n  }\n\n  for (int i = 0; i < total_size; ++i) {\n    energy_after_fft += pow(std::abs(output(i)), 2);\n  }\n\n  if(FFTDirection == FFT_FORWARD) {\n    VERIFY_IS_APPROX(energy_original, energy_after_fft / total_size);\n  }\n  else {\n    VERIFY_IS_APPROX(energy_original, energy_after_fft * total_size);\n  }\n}\n\nvoid test_cxx11_tensor_fft() {\n    test_fft_complex_input_golden();\n    test_fft_real_input_golden();\n\n    test_fft_2D_golden<ColMajor>();\n    test_fft_2D_golden<RowMajor>();\n\n    test_fft_real_input_energy<ColMajor, float,  true,  Eigen::BothParts, FFT_FORWARD, 1>();\n    test_fft_real_input_energy<ColMajor, double, true,  Eigen::BothParts, FFT_FORWARD, 1>();\n    test_fft_real_input_energy<ColMajor, float,  false,  Eigen::BothParts, FFT_FORWARD, 1>();\n    test_fft_real_input_energy<ColMajor, double, false,  Eigen::BothParts, FFT_FORWARD, 1>();\n\n    test_fft_real_input_energy<ColMajor, float,  true,  Eigen::BothParts, FFT_FORWARD, 2>();\n    test_fft_real_input_energy<ColMajor, double, true,  Eigen::BothParts, FFT_FORWARD, 2>();\n    test_fft_real_input_energy<ColMajor, float,  false,  Eigen::BothParts, FFT_FORWARD, 2>();\n    test_fft_real_input_energy<ColMajor, double, false,  Eigen::BothParts, FFT_FORWARD, 2>();\n\n    test_fft_real_input_energy<ColMajor, float,  true,  Eigen::BothParts, FFT_FORWARD, 3>();\n    test_fft_real_input_energy<ColMajor, double, true,  Eigen::BothParts, FFT_FORWARD, 3>();\n    test_fft_real_input_energy<ColMajor, float,  false,  Eigen::BothParts, FFT_FORWARD, 3>();\n    test_fft_real_input_energy<ColMajor, double, false,  Eigen::BothParts, FFT_FORWARD, 3>();\n\n    test_fft_real_input_energy<ColMajor, float,  true,  Eigen::BothParts, FFT_FORWARD, 4>();\n    test_fft_real_input_energy<ColMajor, double, true,  Eigen::BothParts, FFT_FORWARD, 4>();\n    test_fft_real_input_energy<ColMajor, float,  false,  Eigen::BothParts, FFT_FORWARD, 4>();\n    test_fft_real_input_energy<ColMajor, double, false,  Eigen::BothParts, FFT_FORWARD, 4>();\n\n    test_fft_real_input_energy<RowMajor, float,  true,  Eigen::BothParts, FFT_FORWARD, 1>();\n    test_fft_real_input_energy<RowMajor, double, true,  Eigen::BothParts, FFT_FORWARD, 1>();\n    test_fft_real_input_energy<RowMajor, float,  false,  Eigen::BothParts, FFT_FORWARD, 1>();\n    test_fft_real_input_energy<RowMajor, double, false,  Eigen::BothParts, FFT_FORWARD, 1>();\n\n    test_fft_real_input_energy<RowMajor, float,  true,  Eigen::BothParts, FFT_FORWARD, 2>();\n    test_fft_real_input_energy<RowMajor, double, true,  Eigen::BothParts, FFT_FORWARD, 2>();\n    test_fft_real_input_energy<RowMajor, float,  false,  Eigen::BothParts, FFT_FORWARD, 2>();\n    test_fft_real_input_energy<RowMajor, double, false,  Eigen::BothParts, FFT_FORWARD, 2>();\n\n    test_fft_real_input_energy<RowMajor, float,  true,  Eigen::BothParts, FFT_FORWARD, 3>();\n    test_fft_real_input_energy<RowMajor, double, true,  Eigen::BothParts, FFT_FORWARD, 3>();\n    test_fft_real_input_energy<RowMajor, float,  false,  Eigen::BothParts, FFT_FORWARD, 3>();\n    test_fft_real_input_energy<RowMajor, double, false,  Eigen::BothParts, FFT_FORWARD, 3>();\n\n    test_fft_real_input_energy<RowMajor, float,  true,  Eigen::BothParts, FFT_FORWARD, 4>();\n    test_fft_real_input_energy<RowMajor, double, true,  Eigen::BothParts, FFT_FORWARD, 4>();\n    test_fft_real_input_energy<RowMajor, float,  false,  Eigen::BothParts, FFT_FORWARD, 4>();\n    test_fft_real_input_energy<RowMajor, double, false,  Eigen::BothParts, FFT_FORWARD, 4>();\n}\n", "meta": {"hexsha": "0f6e09106160d30595229548d4f52d1ade8629a6", "size": 12830, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen/unsupported/test/cxx11_tensor_fft.cpp", "max_stars_repo_name": "Achierius/SysSim", "max_stars_repo_head_hexsha": "067c32a3a03418819d11284db4050fdb43505abc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2016-09-22T08:41:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T02:49:45.000Z", "max_issues_repo_path": "include/Eigen/unsupported/test/cxx11_tensor_fft.cpp", "max_issues_repo_name": "Achierius/SysSim", "max_issues_repo_head_hexsha": "067c32a3a03418819d11284db4050fdb43505abc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-09-06T11:25:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-31T12:29:50.000Z", "max_forks_repo_path": "include/Eigen/unsupported/test/cxx11_tensor_fft.cpp", "max_forks_repo_name": "Achierius/SysSim", "max_forks_repo_head_hexsha": "067c32a3a03418819d11284db4050fdb43505abc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2016-08-30T07:17:51.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-08T07:29:18.000Z", "avg_line_length": 46.8248175182, "max_line_length": 133, "alphanum_fraction": 0.7276695246, "num_tokens": 3866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5486935487187734}}
{"text": "//  Copyright John Maddock 2009.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include \"required_defines.hpp\"\r\n\r\n#include \"performance_measure.hpp\"\r\n\r\n#include <boost/math/special_functions/beta.hpp>\r\n#include <boost/array.hpp>\r\n\r\n#define T double\r\n#  include \"../test/beta_small_data.ipp\"\r\n#  include \"../test/beta_med_data.ipp\"\r\n#  include \"../test/beta_exp_data.ipp\"\r\n\r\ntemplate <std::size_t N>\r\ndouble beta_evaluate2(const boost::array<boost::array<T, 3>, N>& data)\r\n{\r\n   double result = 0;\r\n   for(unsigned i = 0; i < N; ++i)\r\n      result += boost::math::beta(data[i][0], data[i][1]);\r\n   return result;\r\n}\r\n\r\nBOOST_MATH_PERFORMANCE_TEST(beta_test, \"beta\")\r\n{\r\n   double result = beta_evaluate2(beta_small_data);\r\n   result += beta_evaluate2(beta_med_data);\r\n   result += beta_evaluate2(beta_exp_data);\r\n\r\n   consume_result(result);\r\n   set_call_count(\r\n      (sizeof(beta_small_data) \r\n      + sizeof(beta_med_data) \r\n      + sizeof(beta_exp_data)) / sizeof(beta_exp_data[0]));\r\n}\r\n\r\n#ifdef TEST_DCDFLIB\r\n#include <dcdflib.h>\r\n\r\ntemplate <std::size_t N>\r\ndouble beta_evaluate2_dcd(const boost::array<boost::array<T, 3>, N>& data)\r\n{\r\n   double result = 0;\r\n   for(unsigned i = 0; i < N; ++i)\r\n      result += ::beta(data[i][0], data[i][1]);\r\n   return result;\r\n}\r\n\r\nBOOST_MATH_PERFORMANCE_TEST(beta_test_dcd, \"beta-dcd\")\r\n{\r\n   double result = beta_evaluate2_dcd(beta_small_data);\r\n   result += beta_evaluate2_dcd(beta_med_data);\r\n   result += beta_evaluate2_dcd(beta_exp_data);\r\n\r\n   consume_result(result);\r\n   set_call_count(\r\n      (sizeof(beta_small_data) \r\n      + sizeof(beta_med_data) \r\n      + sizeof(beta_exp_data)) / sizeof(beta_exp_data[0]));\r\n}\r\n\r\n#endif\r\n\r\n\r\n", "meta": {"hexsha": "f3e8921a1ad050f8777abf61944fc8ae88644537", "size": 1833, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/performance/test_beta.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/math/performance/test_beta.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/math/performance/test_beta.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": 26.9558823529, "max_line_length": 75, "alphanum_fraction": 0.6732133115, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5486755083728985}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \r\n//\r\n// This file is part of the Boost Graph Library\r\n//\r\n// You should have received a copy of the License Agreement for the\r\n// Boost Graph Library along with the software; see the file LICENSE.\r\n// If not, contact Office of Research, Indiana University,\r\n// Bloomington, IN 47405.\r\n//\r\n// Permission to modify the code and to distribute the code is\r\n// granted, provided the text of this NOTICE is retained, a notice if\r\n// the code was modified is included with the above COPYRIGHT NOTICE\r\n// and with the COPYRIGHT NOTICE in the LICENSE file, and that the\r\n// LICENSE file is distributed with the modified code.\r\n//\r\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\r\n// By way of example, but not limitation, Licensor MAKES NO\r\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\r\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\r\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\r\n// OR OTHER RIGHTS.\r\n//=======================================================================\r\n#include <boost/config.hpp>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <vector>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/graph/graphviz.hpp>\r\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  GraphvizGraph g_dot;\r\n  read_graphviz(\"figs/telephone-network.dot\", g_dot);\r\n\r\n  typedef adjacency_list < vecS, vecS, undirectedS, no_property,\r\n    property < edge_weight_t, int > > Graph;\r\n  Graph g(num_vertices(g_dot));\r\n  property_map < GraphvizGraph, edge_attribute_t >::type\r\n    edge_attr_map = get(edge_attribute, g_dot);\r\n  graph_traits < GraphvizGraph >::edge_iterator ei, ei_end;\r\n  for (tie(ei, ei_end) = edges(g_dot); ei != ei_end; ++ei) {\r\n    int weight = lexical_cast < int >(edge_attr_map[*ei][\"label\"]);\r\n    property < edge_weight_t, int >edge_property(weight);\r\n    add_edge(source(*ei, g_dot), target(*ei, g_dot), edge_property, g);\r\n  }\r\n\r\n  typedef graph_traits < Graph >::vertex_descriptor Vertex;\r\n  std::vector < Vertex > parent(num_vertices(g));\r\n  property_map < Graph, edge_weight_t >::type weight = get(edge_weight, g);\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  property_map<Graph, vertex_index_t>::type indexmap = get(vertex_index, g);  \r\n  std::vector<std::size_t> distance(num_vertices(g));\r\n  prim_minimum_spanning_tree(g, *vertices(g).first, &parent[0], &distance[0],\r\n                             weight, indexmap, default_dijkstra_visitor());\r\n#else\r\n  prim_minimum_spanning_tree(g, &parent[0]);\r\n#endif\r\n\r\n  int total_weight = 0;\r\n  for (int v = 0; v < num_vertices(g); ++v)\r\n    if (parent[v] != v)\r\n      total_weight += get(weight, edge(parent[v], v, g).first);\r\n  std::cout << \"total weight: \" << total_weight << std::endl;\r\n\r\n  for (int u = 0; u < num_vertices(g); ++u)\r\n    if (parent[u] != u)\r\n      edge_attr_map[edge(parent[u], u, g_dot).first][\"color\"] = \"black\";\r\n  std::ofstream out(\"figs/telephone-mst-prim.dot\");\r\n  graph_property < GraphvizGraph, graph_edge_attribute_t >::type &\r\n    graph_edge_attr_map = get_property(g_dot, graph_edge_attribute);\r\n  graph_edge_attr_map[\"color\"] = \"gray\";\r\n  write_graphviz(out, g_dot);\r\n\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "6bc13299dbe87f77c807883af49be8f03f9877f6", "size": 3390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/graph/example/prim-telephone.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/graph/example/prim-telephone.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/libs/graph/example/prim-telephone.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9113924051, "max_line_length": 79, "alphanum_fraction": 0.6696165192, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5486351590433733}}
{"text": "/**  PrecompData_multi.h\n\n\tCopyright 2016 Pietro Mele\n\tApache License 2.0\n*/\n\n#ifndef PRECOMP_DATA_MULTI_H\n#define PRECOMP_DATA_MULTI_H\n\n//#define PRECOMPDATA_DEVICE\n\n#include <string>\n#include <boost/multi_array.hpp>\n\n#ifdef PRECOMPDATA_DEVICE\n#include <vector>\n#include <boost/compute/algorithm/copy.hpp>\n#include <boost/compute/container/vector.hpp>\n#endif\n\nnamespace Utilities {\n\n\n\n/** PrecompData\n\tSet of points approximating a multidimensional function/hypersurface\n\tf: X --> Y\n  */\n\ntemplate<\n    typename TX = float,   /* data type of independent vector */\n    typename TY = float,   /* data type of dependent vector   */\n    int nx,                /* number of dimensions of the independent vector */\n    int ny                 /* number of dimensions of the dependent vector   */\n>\nclass PrecompData\n{\npublic:\n\n\t// Data types for the dependent and independent data and indices\n\ttypedef boost::multi_array<TX, nx> XData;\n\ttypedef boost::multi_array<TY, ny> YData;\n\ttypedef typename XData::index X;\n\ttypedef typename YData::index Y;\n\npublic:\n\n\tPrecompData();\n\tPrecompData(const std::string _funcName);\n\n\tint          SetFunctionName(const std::string &_funcName);\n\tint          SetComment(const std::string &_comment);\n\tstd::string  FunctionName() const;\n\tstd::string  Comment()      const;\n\tint          SetOversampling(float ovs);\n\tfloat        Oversamping()  const { return overSampling; }\n\n\tint          nxDimensions() const { return nx; }\n\tint          nyDimensions() const { return ny; }\n\n\t// Precompute constant values\n\tint PreComputeValues();\n\n\t// Coordinate <--> index transformation\n\tsize_t VectorToIndex(X x)      const;     // vector --> index\n\tsize_t ScalarToIndex(TX x)     const;     // scalar --> index\n\tX      IndexToVector(size_t i) const;     // index  --> vector\n\tTX     IndexToScalar(size_t i) const;     // index  --> scalar\n\n\t/// Data loading\n\n\t// Regular grid, computed\n\tsize_t  Set(Y (*Func)(X x), X xmin, X xmax, size_t nPoints);\n\tsize_t  Set(TY (*Func)(TX x), TX xmin, TX xmax, size_t nPoints);\n\n\t// Automatic irregular grid, computed\n\tsize_t  AutoSet(Y (*Func)(X x), X xmin, X xmax, size_t nPoints = 100);\n\tsize_t  AutoSet(TY (*Func)(TX x), TX xmin, TX xmax, size_t nPoints = 100);\n\n\t// Regular grid, load from file\n\tsize_t  Set(const std::string &dataFilename, X xmin, X xmax);\n\n\t// Irregular grid, load from file\n\tsize_t  Set(const std::string &dataFilename);      // grid contained in the file\n\n\n\t/// Data retrieval\n\n\t// Range UNchecked, 0 degree interpolation accessors\n\tY  operator()(X x)  const;\n\tTY operator()(TX x) const;\n\n\t// Range checked accessors; check Status()\n\tY get(X x);\n\n\t// Range checked accessors, interpolated; check Status()\n\tY  Interpolate(X x);\n\tTY Interpolate(TX x);\n\n\tint Status() const { return status; }\n\n\tint  Interpolation() const { return interpolation; }\n\tvoid Interpolation(int order);\n\n\tint RangeCheck(X x);\n\tint RangeCheck(TX x);\n\n\t// Get the whole value set\n\tint Get(std::vector<X> &_xData, std::vector<Y> &_yData) const;\n\tint Get(std::vector<TX> &_xData, std::vector<TY> &_yData) const;\n\tint Dump(int n = 0) const;\n\tint DumpElement(size_t j) const;\n\n\t// Evaluate error\n\tY  EvaluateErrorKnownData() const;              // error on each dimension on known data\n\tTY EvaluateAbsErrorKnownData() const;           // absolute error on known data\n\tY  EvaluateError(int nTestPoints) const;        // error on each dimension on random points\n\tTY EvaluateAbsError(int nTestPoints) const;     // absolute error on random points\n\n\t/// GPGPU\n\n#ifdef PRECOMPDATA_DEVICE\n\tint InitDevice();\n\n\tint CopyOnDevice(boost::compute::device         &device,\n\t                 boost::compute::context        &context,\n\t                 boost::compute::command_queue  &queue,\n\t                 boost::compute::vector<T>      &device_line);\n\n\tint CopyOnDevice(boost::compute::device         **device      = nullptr,\n\t                 boost::compute::context        **context     = nullptr,\n\t                 boost::compute::command_queue  **queue       = nullptr,\n\t                 boost::compute::vector<T>      **device_line = nullptr);\n\n\t// Copy a subset\n\tint CopyOnDevice(T xbeg, T xend);\n\tint CopyOnDevice(T xbeg, T xend, T ybeg, T yend);\n\tint CopyOnDevice(T xbeg, T xend, T ybeg, T yend, T zbeg, T zend);\n#endif // PRECOMPDATA_DEVICE\n\npublic:\n\t// Error return values\n\tstatic const int err_no_data              = -1,\n\t                 err_device_not_available = -2;\n\n\t// Warning return values\n\tstatic const int wrn_x_less_than_min      = -101,\n\t                 wrn_x_more_than_max      = -102,\n\t                 wrn_invalid_oversampling = -103;\n\npublic:\n\t// Test\n\tfriend class PrecompData_test;\n\nprotected:\n\tTY Norm(const Y&) const;\n\tTY FirstDerivative(TX x1, TY y1, TX x2, TY y2) const;\n\tTY SecondDerivative(TX x1, TY y1, TX x2, TY y2, TX x3, TY y3) const;\n\tint PickBestPoints(Y (*Func)(X x), const size_t nPoints, const float overSampling = 2.0f);\n\tint PickBestPoints(TY (*Func)(TX x), const size_t nPoints, const float overSampling = 2.0f);\n\nprivate:\n\n\tstd::string     funcName, comment;\n\tint             interpolation;\n\tint             status;\n\n\tY  (*FuncX)(X x);\n\tTY (*FuncTX)(TX x);\n\n\tXData   xData;\n\tYData   yData;\n\tX       min, max, step;\n\tX       kRealInt, kIntReal;     // conversion factors\n\n\tbool    regularGrid;            // true if points are equally spaced on all axes\n\tfloat   overSampling;\n\n#ifdef PRECOMPDATA_DEVICE\n\tboost::compute::vector<T>  device_line;\n#endif\n\n};\n\n\n} // Utilities\n\n\n// Implementation include files\n#include \"PrecompData_impl.h\"\n#include \"PrecompDataDevice_impl.h\"\n#include \"PrecompData_dump.h\"\n\n#endif // PRECOMP_DATA_MULTI_H\n", "meta": {"hexsha": "84539fd70355cd8020d98d9bc3ae7d3a95b28883", "size": 5618, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PrecompData_multi.hpp", "max_stars_repo_name": "pietrom16/PrecompData", "max_stars_repo_head_hexsha": "bd2f6397299d7088f8a4cb1e2f91f620c3edb89c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-10-12T17:37:00.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-12T17:37:00.000Z", "max_issues_repo_path": "PrecompData_multi.hpp", "max_issues_repo_name": "pietrom16/PrecompData", "max_issues_repo_head_hexsha": "bd2f6397299d7088f8a4cb1e2f91f620c3edb89c", "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": "PrecompData_multi.hpp", "max_forks_repo_name": "pietrom16/PrecompData", "max_forks_repo_head_hexsha": "bd2f6397299d7088f8a4cb1e2f91f620c3edb89c", "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.8102564103, "max_line_length": 93, "alphanum_fraction": 0.6600213599, "num_tokens": 1448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5486066089672259}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\ntemplate <class Scalar>\nclass Twist {\n  using Vector3x = Eigen::Matrix<Scalar, 3, 1>;\n\n public:\n  Twist() {}\n  Twist(const Vector3x& rotation, const Vector3x& translation)\n      : rotation_(rotation), translation_(translation) {}\n\n  Twist(const Twist& twist)\n      : rotation_(twist.rotation_), translation_(twist.translation_) {}\n\n  const Vector3x& Translation() const { return translation_; }\n\n  Vector3x& Translation() { return translation_; }\n\n  const Vector3x& Rotation() const { return rotation_; }\n\n  Vector3x& Rotation() { return rotation_; }\n\n private:\n  Vector3x rotation_;\n  Vector3x translation_;\n};\n\ntemplate <class Scalar>\nTwist<Scalar> operator*(const Twist<Scalar>& twist, const float scale) {\n  return Twist<Scalar>{twist.Rotation() * scale, twist.Translation() * scale};\n}\n\ntemplate <class Scalar>\nTwist<Scalar> operator*(const float scale, const Twist<Scalar>& twist) {\n  return Twist<Scalar>{twist.Rotation() * scale, twist.Translation() * scale};\n}\n\n/**\n * se3 -> SE3\n */\ntemplate <class Scalar>\nEigen::Transform<Scalar, 3, Eigen::Isometry> Exp(const Twist<Scalar>& T) {\n  const auto& w = T.Rotation();\n  const auto& v = T.Translation();\n\n  const float t2 = w.dot(w);\n  const float t = std::sqrt(t2);\n  const bool is_small_angle = (t <= std::numeric_limits<float>::epsilon());\n  const Eigen::AngleAxis<Scalar> rotation(t, is_small_angle ? w : w / t);\n\n  if (is_small_angle) {\n    const Eigen::Matrix<Scalar, 3, 1> position = v + 0.5 * w.cross(v);\n    return Eigen::Translation<Scalar, 3>{position} * rotation;\n  }\n\n  const float ct = std::cos(t);\n  const float st = std::sin(t);\n  const float awxv = (1.0 - ct) / t2;\n  const float av = (st / t);\n  const float aw = (1.0 - av) / t2;\n\n  const Eigen::Matrix<Scalar, 3, 1> position =\n      av * v + aw * w.dot(v) * w + awxv * w.cross(v);\n\n  return Eigen::Translation<Scalar, 3>{position} * rotation;\n}\n\n/**\n * SE3 -> se3\n */\ntemplate <class Scalar>\nTwist<Scalar> Log(const Eigen::Transform<Scalar, 3, Eigen::Isometry>& T) {\n  Twist<Scalar> out;\n\n  // Extract components.\n  const Eigen::AngleAxis<Scalar> axa{T.linear()};\n  const Eigen::Matrix<Scalar, 3, 1>& w = axa.axis() * axa.angle();\n  const Eigen::Matrix<Scalar, 3, 1>& p = T.translation();\n\n  // Set intermediate values.\n  const float t = axa.angle();\n  const float t2 = t * t;\n  const bool is_small_angle = (t <= std::numeric_limits<float>::epsilon());\n\n  if (is_small_angle) {\n    const Eigen::Matrix<Scalar, 3, 1>& v = p + 0.5 * p.cross(w);\n    return Twist<Scalar>{w, v};\n  }\n\n  const float st = std::sin(t);\n  const float ct = std::cos(t);\n  const float alpha = (t * st / (2.0 * (1.0 - ct)));\n  const float beta = (1.0 / t2 - st / (2.0 * t * (1.0 - ct)));\n  const Eigen::Matrix<Scalar, 3, 1>& v =\n      (alpha * p - 0.5 * w.cross(p) + beta * w.dot(p) * w);\n  return Twist<Scalar>{w, v};\n}\n", "meta": {"hexsha": "981da0ccb8fd6ec3ec3a349f4309c6b6a62d7a01", "size": 2880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/raycaster/twist.hpp", "max_stars_repo_name": "yycho0108/PCLRayCaster", "max_stars_repo_head_hexsha": "b80fda4c5357a7777e4e9ea31f36fc09b6502312", "max_stars_repo_licenses": ["MIT"], "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/raycaster/twist.hpp", "max_issues_repo_name": "yycho0108/PCLRayCaster", "max_issues_repo_head_hexsha": "b80fda4c5357a7777e4e9ea31f36fc09b6502312", "max_issues_repo_licenses": ["MIT"], "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/raycaster/twist.hpp", "max_forks_repo_name": "yycho0108/PCLRayCaster", "max_forks_repo_head_hexsha": "b80fda4c5357a7777e4e9ea31f36fc09b6502312", "max_forks_repo_licenses": ["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.5148514851, "max_line_length": 78, "alphanum_fraction": 0.6427083333, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7057850340255387, "lm_q1q2_score": 0.5486066089672259}}
{"text": "//=====================================================\n// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n//=====================================================\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 2\n// of the License, or (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// You should have received a copy of the GNU General Public License\n// along with this program; if not, write to the Free Software\n// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n//\n#ifndef EIGEN3_INTERFACE_HH\n#define EIGEN3_INTERFACE_HH\n\n#include <Eigen/Eigen>\n#include <vector>\n#include \"btl.hh\"\n\nusing namespace Eigen;\n\ntemplate<class real, int SIZE=Dynamic>\nclass eigen3_interface\n{\n\npublic :\n\n  enum {IsFixedSize = (SIZE!=Dynamic)};\n\n  typedef real real_type;\n\n  typedef std::vector<real> stl_vector;\n  typedef std::vector<stl_vector> stl_matrix;\n\n  typedef Eigen::Matrix<real,SIZE,SIZE> gene_matrix;\n  typedef Eigen::Matrix<real,SIZE,1> gene_vector;\n\n  static inline std::string name( void )\n  {\n    return EIGEN_MAKESTRING(BTL_PREFIX);\n  }\n\n  static void free_matrix(gene_matrix & /*A*/, int /*N*/) {}\n\n  static void free_vector(gene_vector & /*B*/) {}\n\n  static BTL_DONT_INLINE void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){\n    A.resize(A_stl[0].size(), A_stl.size());\n\n    for (unsigned int j=0; j<A_stl.size() ; j++){\n      for (unsigned int i=0; i<A_stl[j].size() ; i++){\n        A.coeffRef(i,j) = A_stl[j][i];\n      }\n    }\n  }\n\n  static BTL_DONT_INLINE  void vector_from_stl(gene_vector & B, stl_vector & B_stl){\n    B.resize(B_stl.size(),1);\n\n    for (unsigned int i=0; i<B_stl.size() ; i++){\n      B.coeffRef(i) = B_stl[i];\n    }\n  }\n\n  static BTL_DONT_INLINE  void vector_to_stl(gene_vector & B, stl_vector & B_stl){\n    for (unsigned int i=0; i<B_stl.size() ; i++){\n      B_stl[i] = B.coeff(i);\n    }\n  }\n\n  static BTL_DONT_INLINE  void matrix_to_stl(gene_matrix & A, stl_matrix & A_stl){\n    int  N=A_stl.size();\n\n    for (int j=0;j<N;j++){\n      A_stl[j].resize(N);\n      for (int i=0;i<N;i++){\n        A_stl[j][i] = A.coeff(i,j);\n      }\n    }\n  }\n\n  static inline void matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int  /*N*/){\n    X.noalias() = A*B;\n  }\n\n  static inline void transposed_matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int  /*N*/){\n    X.noalias() = A.transpose()*B.transpose();\n  }\n\n//   static inline void ata_product(const gene_matrix & A, gene_matrix & X, int  /*N*/){\n//     X.noalias() = A.transpose()*A;\n//   }\n\n  static inline void aat_product(const gene_matrix & A, gene_matrix & X, int  /*N*/){\n    X.template triangularView<Lower>().setZero();\n    X.template selfadjointView<Lower>().rankUpdate(A);\n  }\n\n  static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int  /*N*/){\n    X.noalias() = A*B;\n  }\n\n  static inline void symv(const gene_matrix & A, const gene_vector & B, gene_vector & X, int  /*N*/){\n    X.noalias() = (A.template selfadjointView<Lower>() * B);\n//     internal::product_selfadjoint_vector<real,0,LowerTriangularBit,false,false>(N,A.data(),N, B.data(), 1, X.data(), 1);\n  }\n\n  template<typename Dest, typename Src> static void triassign(Dest& dst, const Src& src)\n  {\n    typedef typename Dest::Scalar Scalar;\n    typedef typename internal::packet_traits<Scalar>::type Packet;\n    const int PacketSize = sizeof(Packet)/sizeof(Scalar);\n    int size = dst.cols();\n    for(int j=0; j<size; j+=1)\n    {\n//       const int alignedEnd = alignedStart + ((innerSize-alignedStart) & ~packetAlignedMask);\n      Scalar* A0 = dst.data() + j*dst.stride();\n      int starti = j;\n      int alignedEnd = starti;\n      int alignedStart = (starti) + internal::first_aligned(&A0[starti], size-starti);\n      alignedEnd = alignedStart + ((size-alignedStart)/(2*PacketSize))*(PacketSize*2);\n\n      // do the non-vectorizable part of the assignment\n      for (int index = starti; index<alignedStart ; ++index)\n      {\n        if(Dest::Flags&RowMajorBit)\n          dst.copyCoeff(j, index, src);\n        else\n          dst.copyCoeff(index, j, src);\n      }\n\n      // do the vectorizable part of the assignment\n      for (int index = alignedStart; index<alignedEnd; index+=PacketSize)\n      {\n        if(Dest::Flags&RowMajorBit)\n          dst.template copyPacket<Src, Aligned, Unaligned>(j, index, src);\n        else\n          dst.template copyPacket<Src, Aligned, Unaligned>(index, j, src);\n      }\n\n      // do the non-vectorizable part of the assignment\n      for (int index = alignedEnd; index<size; ++index)\n      {\n        if(Dest::Flags&RowMajorBit)\n          dst.copyCoeff(j, index, src);\n        else\n          dst.copyCoeff(index, j, src);\n      }\n      //dst.col(j).tail(N-j) = src.col(j).tail(N-j);\n    }\n  }\n\n  static EIGEN_DONT_INLINE void syr2(gene_matrix & A,  gene_vector & X, gene_vector & Y, int  N){\n    // internal::product_selfadjoint_rank2_update<real,0,LowerTriangularBit>(N,A.data(),N, X.data(), 1, Y.data(), 1, -1);\n    for(int j=0; j<N; ++j)\n      A.col(j).tail(N-j) += X[j] * Y.tail(N-j) + Y[j] * X.tail(N-j);\n  }\n\n  static EIGEN_DONT_INLINE void ger(gene_matrix & A,  gene_vector & X, gene_vector & Y, int  N){\n    for(int j=0; j<N; ++j)\n      A.col(j) += X * Y[j];\n  }\n\n  static EIGEN_DONT_INLINE void rot(gene_vector & A,  gene_vector & B, real c, real s, int  /*N*/){\n    internal::apply_rotation_in_the_plane(A, B, JacobiRotation<real>(c,s));\n  }\n\n  static inline void atv_product(gene_matrix & A, gene_vector & B, gene_vector & X, int  /*N*/){\n    X.noalias() = (A.transpose()*B);\n  }\n\n  static inline void axpy(real coef, const gene_vector & X, gene_vector & Y, int  /*N*/){\n    Y += coef * X;\n  }\n\n  static inline void axpby(real a, const gene_vector & X, real b, gene_vector & Y, int  /*N*/){\n    Y = a*X + b*Y;\n  }\n\n  static EIGEN_DONT_INLINE void copy_matrix(const gene_matrix & source, gene_matrix & cible, int  /*N*/){\n    cible = source;\n  }\n\n  static EIGEN_DONT_INLINE void copy_vector(const gene_vector & source, gene_vector & cible, int  /*N*/){\n    cible = source;\n  }\n\n  static inline void trisolve_lower(const gene_matrix & L, const gene_vector& B, gene_vector& X, int  /*N*/){\n    X = L.template triangularView<Lower>().solve(B);\n  }\n\n  static inline void trisolve_lower_matrix(const gene_matrix & L, const gene_matrix& B, gene_matrix& X, int  /*N*/){\n    X = L.template triangularView<Upper>().solve(B);\n  }\n\n  static inline void trmm(const gene_matrix & L, const gene_matrix& B, gene_matrix& X, int  /*N*/){\n    X.noalias() = L.template triangularView<Lower>() * B;\n  }\n\n  static inline void cholesky(const gene_matrix & X, gene_matrix & C, int  /*N*/){\n    C = X;\n    internal::llt_inplace<real,Lower>::blocked(C);\n    //C = X.llt().matrixL();\n//     C = X;\n//     Cholesky<gene_matrix>::computeInPlace(C);\n//     Cholesky<gene_matrix>::computeInPlaceBlock(C);\n  }\n\n  static inline void lu_decomp(const gene_matrix & X, gene_matrix & C, int  /*N*/){\n    C = X.fullPivLu().matrixLU();\n  }\n\n  static inline void partial_lu_decomp(const gene_matrix & X, gene_matrix & C, int  N){\n    Matrix<DenseIndex,1,Dynamic> piv(N);\n    DenseIndex nb;\n    C = X;\n    internal::partial_lu_inplace(C,piv,nb);\n//     C = X.partialPivLu().matrixLU();\n  }\n\n  static inline void tridiagonalization(const gene_matrix & X, gene_matrix & C, int  N){\n    typename Tridiagonalization<gene_matrix>::CoeffVectorType aux(N-1);\n    C = X;\n    internal::tridiagonalization_inplace(C, aux);\n  }\n\n  static inline void hessenberg(const gene_matrix & X, gene_matrix & C, int  /*N*/){\n    C = HessenbergDecomposition<gene_matrix>(X).packedMatrix();\n  }\n\n\n\n};\n\n#endif\n", "meta": {"hexsha": "b821fd721174d08ecf51feeb3d604248e1c68c1c", "size": 8077, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/bench/btl/libs/eigen3/eigen3_interface.hh", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/bench/btl/libs/eigen3/eigen3_interface.hh", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/bench/btl/libs/eigen3/eigen3_interface.hh", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 33.5145228216, "max_line_length": 129, "alphanum_fraction": 0.6408319921, "num_tokens": 2306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5486066089672259}}
{"text": "/* Boost example/horner.cpp\r\n * example of unprotecting rounding for a whole function computation\r\n *\r\n * Copyright Guillaume Melquiond 2002-2003\r\n * Permission to use, copy, modify, sell, and distribute this software\r\n * is hereby granted without fee provided that the above copyright notice\r\n * appears in all copies and that both that copyright notice and this\r\n * permission notice appear in supporting documentation.\r\n *\r\n * None of the above authors nor Polytechnic University make any\r\n * representation about the suitability of this software for any\r\n * purpose. It is provided \"as is\" without express or implied warranty.\r\n *\r\n * $Id: horner.cpp,v 1.2 2003/02/05 17:34:34 gmelquio Exp $\r\n */\r\n\r\n#include <boost/numeric/interval.hpp>\r\n#include <boost/numeric/interval/io.hpp>\r\n#include <iostream>\r\n\r\n// I is an interval class, the polynom is a simple array\r\ntemplate<class I>\r\nI horner(const I& x, const I p[], int n) {\r\n\r\n  // initialize and restore the rounding mode\r\n  typename I::traits_type::rounding rnd;\r\n\r\n  // define the unprotected version of the interval type\r\n  typedef typename boost::numeric::interval_lib::unprotect<I>::type R;\r\n\r\n  const R& a = x;\r\n  R y = p[n - 1];\r\n  for(int i = n - 2; i >= 0; i--) {\r\n    y = y * a + (const R&)(p[i]);\r\n  }\r\n  return y;\r\n\r\n  // restore the rounding mode with the destruction of rnd\r\n}\r\n\r\nint main() {\r\n  typedef boost::numeric::interval<double> I;\r\n  I p[3] = { -1.0, 0, 1.0 };\r\n  I x = 1.0;\r\n  std::cout << horner(x, p, 3) << std::endl;\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "1b1b79214076c35d2c659658a9db294f2e2b4e76", "size": 1516, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/examples/horner.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/examples/horner.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/libs/numeric/interval/examples/horner.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "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": 74, "alphanum_fraction": 0.672823219, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5486066089672259}}
{"text": "\ufeff\r\n#include <iostream>\r\n#include <boost/random.hpp>\r\n\r\nint main()\r\n{\r\n\tstd::size_t seed = 0;\r\n\r\n\tboost::mt19937 gen(seed);\r\n\tboost::random::uniform_int_distribution<> dist(0, 10);\r\n\r\n\tfor (int i = 0; i < 3; ++i) \r\n\t{\r\n\t\tstd::cout << dist(gen) << std::endl;\r\n\t}\r\n\r\n\tstd::cout << \"-- seed \uc7ac\uc124\uc815 --\" << std::endl;\r\n\t\r\n\tgen.seed(seed); \r\n\r\n\tfor (int i = 0; i < 3; ++i) {\r\n\t\tstd::cout << dist(gen) << std::endl;\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\n", "meta": {"hexsha": "cc454a20a5f4359dafda1d93e485dad20fd409f9", "size": 429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Boost_20140423/random_12/random_12.cpp", "max_stars_repo_name": "jacking75/book_semina_samples", "max_stars_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_stars_repo_licenses": ["MIT"], "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_20140423/random_12/random_12.cpp", "max_issues_repo_name": "jacking75/book_semina_samples", "max_issues_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_issues_repo_licenses": ["MIT"], "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_20140423/random_12/random_12.cpp", "max_forks_repo_name": "jacking75/book_semina_samples", "max_forks_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_forks_repo_licenses": ["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.3214285714, "max_line_length": 56, "alphanum_fraction": 0.5151515152, "num_tokens": 143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5486066089672258}}
{"text": "/*SLAMBOOK2\u91cc\u9762\uff0c\u4f7f\u7528\u667a\u80fd\u6307\u9488\u5b9e\u73b0G2O\u7684\u7248\u672c*/\n\n#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// \u66f2\u7ebf\u6a21\u578b\u7684\u9876\u70b9\uff0c\u6a21\u677f\u53c2\u6570\uff1a\u4f18\u5316\u53d8\u91cf\u7ef4\u5ea6\u548c\u6570\u636e\u7c7b\u578b\nclass CurveFittingVertex : public g2o::BaseVertex<3, Eigen::Vector3d> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  // \u91cd\u7f6e\n  virtual void setToOriginImpl() override {\n    _estimate << 0, 0, 0;\n  }\n\n  // \u66f4\u65b0\n  virtual void oplusImpl(const double *update) override {\n    _estimate += Eigen::Vector3d(update);\n  }\n\n  // \u5b58\u76d8\u548c\u8bfb\u76d8\uff1a\u7559\u7a7a\n  virtual bool read(istream &in) {}\n\n  virtual bool write(ostream &out) const {}\n};\n\n// \u8bef\u5dee\u6a21\u578b \u6a21\u677f\u53c2\u6570\uff1a\u89c2\u6d4b\u503c\u7ef4\u5ea6\uff0c\u7c7b\u578b\uff0c\u8fde\u63a5\u9876\u70b9\u7c7b\u578b\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  // \u8ba1\u7b97\u66f2\u7ebf\u6a21\u578b\u8bef\u5dee\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  // \u8ba1\u7b97\u96c5\u53ef\u6bd4\u77e9\u9635\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 \u503c\uff0c y \u503c\u4e3a _measurement\n};\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  double inv_sigma = 1.0 / w_sigma;\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 * w_sigma));\n  }\n\n  // \u6784\u5efa\u56fe\u4f18\u5316\uff0c\u5148\u8bbe\u5b9ag2o\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<3, 1>> BlockSolverType;  // \u6bcf\u4e2a\u8bef\u5dee\u9879\u4f18\u5316\u53d8\u91cf\u7ef4\u5ea6\u4e3a3\uff0c\u8bef\u5dee\u503c\u7ef4\u5ea6\u4e3a1\n  typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType; // \u7ebf\u6027\u6c42\u89e3\u5668\u7c7b\u578b\n\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  // \u5f80\u56fe\u4e2d\u589e\u52a0\u9876\u70b9\n  CurveFittingVertex *v = new CurveFittingVertex();\n  v->setEstimate(Eigen::Vector3d(ae, be, ce));\n  v->setId(0);\n  optimizer.addVertex(v);\n\n  // \u5f80\u56fe\u4e2d\u589e\u52a0\u8fb9\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);                // \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n    edge->setMeasurement(y_data[i]);      // \u89c2\u6d4b\u6570\u503c\n    edge->setInformation(Eigen::Matrix<double, 1, 1>::Identity() * 1 / (w_sigma * w_sigma)); // \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n    optimizer.addEdge(edge);\n  }\n\n  // \u6267\u884c\u4f18\u5316\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  // \u8f93\u51fa\u4f18\u5316\u503c\n  Eigen::Vector3d abc_estimate = v->estimate();\n  cout << \"estimated model: \" << abc_estimate.transpose() << endl;\n\n  return 0;\n}", "meta": {"hexsha": "c8cfc726a323beea4f6a6d5227af485df8e1e536", "size": 4156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/g2o_curve_fitting/g2oCurveFitting.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": "ch6/g2o_curve_fitting/g2oCurveFitting.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": "ch6/g2o_curve_fitting/g2oCurveFitting.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": 32.46875, "max_line_length": 108, "alphanum_fraction": 0.656641001, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5486066041568844}}
{"text": "/**\n * Interface class for all the modules\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n\nnamespace DeepLearningFramework {\nclass Module {\npublic:\n  virtual ~Module() = default;\n\n  virtual void forward(Eigen::MatrixXf &out, const Eigen::MatrixXf &x) = 0;\n\n  virtual void backward(Eigen::MatrixXf &ddout,\n                        const Eigen::MatrixXf &dout) = 0;\n\n  virtual void printDescription() = 0;\n\n  virtual void setLR(float lr) = 0;\n\n  virtual uint32_t getParametersCount() = 0;\n};\n}; // namespace DeepLearningFramework\n", "meta": {"hexsha": "e6ac740d24b5723b04db569943ef045aedd43e81", "size": 522, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Module/Module.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/Module/Module.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/Module/Module.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": 20.0769230769, "max_line_length": 75, "alphanum_fraction": 0.6781609195, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5486066041568843}}
{"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 ITL_CG_INCLUDE\n#define ITL_CG_INCLUDE\n\n#include <cmath>\n#include <cassert>\n#include <iostream>\n#include <boost/mpl/bool.hpp>\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/itl/itl_fwd.hpp>\n#include <boost/numeric/itl/iteration/basic_iteration.hpp>\n#include <boost/numeric/itl/pc/identity.hpp>\n#include <boost/numeric/itl/pc/is_identity.hpp>\n#include <boost/numeric/mtl/operation/dot.hpp>\n#include <boost/numeric/mtl/operation/unary_dot.hpp>\n#include <boost/numeric/mtl/operation/conj.hpp>\n#include <boost/numeric/mtl/operation/resource.hpp>\n#include <boost/numeric/mtl/operation/lazy.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace itl {\n\n/// Conjugate Gradients without preconditioning\ntemplate < typename LinearOperator, typename HilbertSpaceX, typename HilbertSpaceB, \n\t   typename Iteration >\nint cg(const LinearOperator& A, HilbertSpaceX& x, const HilbertSpaceB& b, \n       Iteration& iter)\n{\n    mtl::vampir_trace<7001> tracer;\n    using std::abs; using mtl::conj; using mtl::lazy;\n    typedef HilbertSpaceX Vector;\n    typedef typename mtl::Collection<HilbertSpaceX>::value_type Scalar;\n    typedef typename Iteration::real                            Real;\n\n    Scalar rho(0), rho_1(0), alpha(0), alpha_1(0);\n    Vector p(resource(x)), q(resource(x)), r(resource(x)), z(resource(x));\n  \n    r = b - A*x;\n    rho = dot(r, r);\n    while (! iter.finished(Real(sqrt(abs(rho))))) {\n\t++iter;\n\tif (iter.first())\n\t    p = r;\n\telse \n\t    p = r + (rho / rho_1) * p;\t   \n\n\t// q = A * p; alpha = rho / dot(p, q);\n\t(lazy(q)= A * p) || (lazy(alpha_1)= lazy_dot(p, q));\n\talpha= rho / alpha_1;\n\t\n\tx += alpha * p;\n\trho_1 = rho;\n\t(lazy(r) -= alpha * q) || (lazy(rho) = lazy_unary_dot(r));\n    }\n\n    return iter;\n}\n\n/// Conjugate Gradients\ntemplate < typename LinearOperator, typename HilbertSpaceX, typename HilbertSpaceB, \n\t   typename Preconditioner, typename Iteration >\nint cg(const LinearOperator& A, HilbertSpaceX& x, const HilbertSpaceB& b, \n       const Preconditioner& L, Iteration& iter)\n{\n    using pc::is_identity;\n    if (is_identity(L))\n\treturn cg(A, x, b, iter);\n\n    mtl::vampir_trace<7002> tracer;\n    using std::abs; using mtl::conj; using mtl::lazy;\n    typedef HilbertSpaceX Vector;\n    typedef typename mtl::Collection<HilbertSpaceX>::value_type Scalar;\n    typedef typename Iteration::real                            Real;\n\n    Scalar rho(0), rho_1(0), rr, alpha(0), alpha_1;\n    Vector p(resource(x)), q(resource(x)), r(resource(x)), z(resource(x));\n  \n    r = b - A*x;\n    rr = dot(r, r);\n    while (! iter.finished(Real(sqrt(abs(rr))))) {\n\t++iter;\n\t(lazy(z)= solve(L, r)) || (lazy(rho)= lazy_dot(r, z));\n\n\tif (iter.first())\n\t    p = z;\n\telse \n\t    p = z + (rho / rho_1) * p;\n\t\n\t(lazy(q)= A * p) || (lazy(alpha_1)= lazy_dot(p, q));\n\talpha= rho / alpha_1;\n      \n\tx += alpha * p;\n\trho_1 = rho;\n\t(lazy(r) -= alpha * q) || (lazy(rr) = lazy_unary_dot(r));\n    }\n    return iter;\n}\n\n/// Conjugate Gradients with ignored right preconditioner to unify interface\ntemplate < typename LinearOperator, typename HilbertSpaceX, typename HilbertSpaceB, \n\t   typename Preconditioner, typename RightPreconditioner, typename Iteration >\nint cg(const LinearOperator& A, HilbertSpaceX& x, const HilbertSpaceB& b, \n       const Preconditioner& L, const RightPreconditioner&, Iteration& iter)\n{\n    return cg(A, x, b, L, iter);\n}\n\n/// Solver class for CG method; right preconditioner ignored (prints warning if not identity)\ntemplate < typename LinearOperator, typename Preconditioner, \n\t   typename RightPreconditioner>\nclass cg_solver\n{\n  public:\n    /// Construct solver from a linear operator; generate (left) preconditioner from it\n    explicit cg_solver(const LinearOperator& A) : A(A), L(A) \n    {\n\tif (!pc::static_is_identity<RightPreconditioner>::value)\n\t    std::cerr << \"Right Preconditioner ignored!\" << std::endl;\n    }\n\n    /// Construct solver from a linear operator and (left) preconditioner\n    cg_solver(const LinearOperator& A, const Preconditioner& L) : A(A), L(L) \n    {\n\tif (!pc::static_is_identity<RightPreconditioner>::value)\n\t    std::cerr << \"Right Preconditioner ignored!\" << std::endl;\n    }\n\n    /// Solve linear system approximately as specified by \\p iter\n    template < typename HilbertSpaceB, typename HilbertSpaceX, typename Iteration >\n    int solve(const HilbertSpaceB& b, HilbertSpaceX& x, Iteration& iter) const\n    {\n\treturn cg(A, x, b, L, iter);\n    }\n\n    /// Perform one CG iteration on linear system\n    template < typename HilbertSpaceB, typename HilbertSpaceX >\n    int solve(const HilbertSpaceB& b, HilbertSpaceX& x) const\n    {\n\titl::basic_iteration<double> iter(x, 1, 0, 0);\n\treturn solve(b, x, iter);\n    }\n    \n  private:\n    const LinearOperator& A;\n    Preconditioner        L;\n};\n\n\n} // namespace itl\n\n#endif // ITL_CG_INCLUDE\n", "meta": {"hexsha": "f1f2eeedbee8ecbaa8fe07b69b14c32d72d79019", "size": 5270, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/itl/krylov/cg.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/itl/krylov/cg.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/itl/krylov/cg.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": 32.1341463415, "max_line_length": 94, "alphanum_fraction": 0.675142315, "num_tokens": 1471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.5486065872540177}}
{"text": "#pragma once\n\n\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/moment.hpp>\n#include <boost/accumulators/statistics/tail_quantile.hpp>\n#include <boost/accumulators/statistics.hpp>\n\n\nnamespace nifty{\nnamespace features{\n\n    namespace bacc = boost::accumulators;\n\n    template<class T>\n    class DefaultAccumulatedStatistics{\n    public:\n\n\n        typedef bacc::accumulator_set<\n            T, \n            bacc::stats<\n                bacc::tag::count,\n                bacc::tag::mean,\n                bacc::tag::min, \n                bacc::tag::max,\n                bacc::tag::moment<2>,\n                bacc::tag::moment<3>,\n                bacc::tag::tail_quantile<bacc::right>\n            > \n        > AccType;\n\n        typedef std::integral_constant<int, 1>  NPasses;\n        typedef std::integral_constant<int, 11> NFeatures;\n\n        DefaultAccumulatedStatistics(const std::size_t rightTailCacheSize = 1000)\n        :   acc_(bacc::right_tail_cache_size = rightTailCacheSize){\n\n        }\n        DefaultAccumulatedStatistics & acc(const T & val, const std::size_t pass=0){\n            acc_(val);\n            return *this;\n        }\n\n        template<class RESULT_ITER>\n        void result(RESULT_ITER rBegin, RESULT_ITER rEnd){\n            using namespace boost::accumulators;\n            const auto count = extract_result< tag::count>(acc_);\n            const auto d = std::distance(rBegin,rEnd);\n            NIFTY_ASSERT_OP(NFeatures::value,==,d);\n            // 11 features\n            auto mean = extract_result< tag::mean >(acc_);\n            rBegin[0]  = mean;                                                             \n            rBegin[1]  = mean*d;                                               \n            rBegin[2]  = extract_result< tag::min >(acc_);                                 \n            rBegin[3]  = extract_result< tag::max >(acc_);                                 \n            rBegin[4]  = replaceRotten(extract_result< tag::moment<2> >(acc_),0.0);        \n            rBegin[5]  = replaceRotten(extract_result< tag::moment<3> >(acc_),0.0);        \n            rBegin[6]  = replaceRotten(quantile(acc_, quantile_probability = 0.1 ), mean);  \n            rBegin[7]  = replaceRotten(quantile(acc_, quantile_probability = 0.25 ),mean); \n            rBegin[8]  = replaceRotten(quantile(acc_, quantile_probability = 0.5 ), mean);  \n            rBegin[9]  = replaceRotten(quantile(acc_, quantile_probability = 0.75 ),mean); \n            rBegin[10] = replaceRotten(quantile(acc_, quantile_probability = 0.90 ),mean); \n\n        }\n\n        std::size_t requiredPasses()const{\n            return 1;\n        }\n        std::size_t nFeatures()const{\n            return NFeatures::value;\n        }\n    private:\n\n        T replaceRotten(const T & val, const T & replaceVal){\n            if(std::isfinite(val))\n                return val;\n            else\n                return replaceVal;\n        }\n\n\n        AccType acc_;\n\n\n    };\n\n\n\n}\n}\n\n", "meta": {"hexsha": "9c5cb832ce8ee7ad0289ba974eee01de0b1fe166", "size": 3097, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/nifty/features/accumulated_features.hxx", "max_stars_repo_name": "konopczynski/nifty", "max_stars_repo_head_hexsha": "dc02ac60febaabfaf9b2ee5a854bb61436ebdc97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2016-06-29T07:42:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T09:25:25.000Z", "max_issues_repo_path": "include/nifty/features/accumulated_features.hxx", "max_issues_repo_name": "tbullmann/nifty", "max_issues_repo_head_hexsha": "00119fd4753817b931272d6d3120b6ebd334882a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2016-07-27T16:07:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T17:24:36.000Z", "max_forks_repo_path": "include/nifty/features/accumulated_features.hxx", "max_forks_repo_name": "tbullmann/nifty", "max_forks_repo_head_hexsha": "00119fd4753817b931272d6d3120b6ebd334882a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2016-01-25T21:21:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T09:25:16.000Z", "avg_line_length": 32.6, "max_line_length": 92, "alphanum_fraction": 0.5440749112, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5486056825757035}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 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 analytichestonadengine.hpp\n    \\brief analytic Heston-model engine\n*/\n\n#ifndef quantlib_analytic_heston_ad_engine_hpp\n#define quantlib_analytic_heston_ad_engine_hpp\n\n#include <ql/math/integrals/integral.hpp>\n#include <ql/math/integrals/gaussianadquadratures.hpp>\n#include <ql/pricingengines/genericmodelengine.hpp>\n#include <ql/models/equity/hestonmodel.hpp>\n#include <ql/instruments/vanillaoption.hpp>\n\n#include <boost/function.hpp>\n#include <cppad/cppad.hpp>\n\n#include <complex>\n\nnamespace QuantLib {\n\n    //! analytic Heston-model engine based on Fourier transform\n    class AnalyticHestonADEngine\n        : public GenericModelEngine<HestonModel,\n                                    VanillaOption::arguments,\n                                    VanillaOption::results> {\n      public:\n        class Integration;\n        enum ComplexLogFormula { Gatheral, BranchCorrection };\n\n        // Constructor using Laguerre integration\n        // and Gatheral's version of complex log.\n        AnalyticHestonADEngine(const boost::shared_ptr<HestonModel>& model,\n                               Size integrationOrder = 144);\n\n\n        void calculate() const;\n        Size numberOfEvaluations() const;\n\n        static void doCalculation(Real riskFreeDiscount,\n                                             Real dividendDiscount,\n                                             Real spotPrice,\n                                             Real strikePrice,\n                                             Real term,\n                                             Real kappa, Real theta, Real sigma, Real v0, Real rho,\n                                             const TypePayoff& type,\n                                             const Integration& integration,\n                                             const ComplexLogFormula cpxLog,\n                                             const AnalyticHestonADEngine* const enginePtr,\n                                             VanillaOption::results& results,\n                                             Size& evaluations);\n\n      protected:\n\n      private:\n        class Fj_Helper;\n\n        mutable Size evaluations_;\n        const ComplexLogFormula cpxLog_;\n        const boost::shared_ptr<Integration> integration_;\n    };\n\n\n    class AnalyticHestonADEngine::Integration {\n      public:\n        // non adaptive integration algorithms based on Gaussian quadrature\n        static Integration gaussLaguerre    (Size integrationOrder = 128);\n        static Integration gaussLegendre    (Size integrationOrder = 128);\n        static Integration gaussChebyshev   (Size integrationOrder = 128);\n        static Integration gaussChebyshev2nd(Size integrationOrder = 128);\n\n        CppAD::AD<Real> calculate(\n        \tconst boost::function<CppAD::AD<Real>(Real)>& f) const;\n\n        Size numberOfEvaluations() const;\n\n      private:\n        enum Algorithm\n            { GaussLaguerre, GaussLegendre,\n              GaussChebyshev, GaussChebyshev2nd };\n\n        Integration(Algorithm intAlgo,\n                    const boost::shared_ptr<GaussianADQuadrature>& quadrature);\n\n        const Algorithm intAlgo_;\n        const boost::shared_ptr<GaussianADQuadrature> gaussianQuadrature_;\n    };\n}\n\n#endif\n", "meta": {"hexsha": "27a6e0852a2ed32a7cffc54adc661dedd1cb48e9", "size": 4035, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ShineNgine/Volatility/analytichestonadengine.hpp", "max_stars_repo_name": "FinancialEngineerLab/fineQuantlib", "max_stars_repo_head_hexsha": "a07eb659a440964ded9e9f636de0fd379672f4c3", "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": "ShineNgine/Volatility/analytichestonadengine.hpp", "max_issues_repo_name": "FinancialEngineerLab/fineQuantlib", "max_issues_repo_head_hexsha": "a07eb659a440964ded9e9f636de0fd379672f4c3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShineNgine/Volatility/analytichestonadengine.hpp", "max_forks_repo_name": "FinancialEngineerLab/fineQuantlib", "max_forks_repo_head_hexsha": "a07eb659a440964ded9e9f636de0fd379672f4c3", "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.0183486239, "max_line_length": 99, "alphanum_fraction": 0.6188351921, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5486056771052588}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <Eigen/Sparse>\nusing namespace std;\nusing namespace Eigen;\n\ntemplate <class scalar>\nstruct TripletMatrix;\n\n\nvector <Triplet<double>> triplet;\ntriplet=\nSparseMatrix<double, row major> spMat(size_t n,size_t m);\n", "meta": {"hexsha": "0ba303cd7733164745aab75a93efe68f26f9d068", "size": 261, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS3/triplet.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/triplet.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/triplet.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": 18.6428571429, "max_line_length": 57, "alphanum_fraction": 0.7739463602, "num_tokens": 61, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5486056713652614}}
{"text": "/** @file\n *****************************************************************************\n \n Arithmetic in the finite field Fp, for prime p of fixed length using\n NTL as the backend.\n\n *****************************************************************************\n * @author     Samir Menon, Brennan Shacklett, and David J. Wu\n * @copyright  MIT license (see LICENSE file)\n *****************************************************************************/\n\n#ifndef NTLFP_HPP_\n#define NTLFP_HPP_\n\n#include <cstddef>\n#include <iostream>\n#include <NTL/ZZ_p.h>\n#include <libsnark/common/libsnark_serialization.hpp>\n#include <libff/algebra/fields/bigint.hpp>\n\nnamespace libsnark {\n\ntemplate<unsigned long modulus>\nclass NTLFp_model;\n\ntemplate<unsigned long modulus>\nstd::ostream& operator<<(std::ostream &, const NTLFp_model<modulus>&);\n\ntemplate<unsigned long modulus>\nstd::istream& operator>>(std::istream &, NTLFp_model<modulus> &);\n\ntemplate<unsigned long modulus>\nclass NTLFp_model {\nprivate:\n    NTL::ZZ_p value;\npublic:\n    static const constexpr unsigned long& mod = modulus;\n    static size_t s; // log2(modulus) OR modulus = 2^s * t + 1\n    static size_t t; // with t odd\n    static NTLFp_model<modulus> multiplicative_generator; // generator of Fp^*\n    static NTLFp_model<modulus> root_of_unity; // generator^((modulus-1)/2^s)m\n    static size_t num_bits;\n\n    NTLFp_model();\n    NTLFp_model(long x);\n    NTLFp_model(const NTLFp_model &other);\n    NTLFp_model(const NTL::ZZ_p &value) : value(value) {}\n\n    NTL::ZZ_p as_ZZ_p() const { return this->value; }\n    static NTL::ZZ mod_zz() { return NTL::ZZ(modulus); }\n\n    bool operator==(const NTLFp_model& other) const;\n    bool operator!=(const NTLFp_model& other) const;\n    bool is_zero() const;\n\n    void print() const;\n\n    NTLFp_model& operator+=(const NTLFp_model& other);\n    NTLFp_model& operator-=(const NTLFp_model& other);\n    NTLFp_model& operator*=(const NTLFp_model& other);\n    NTLFp_model& operator/=(const NTLFp_model& other);\n    NTLFp_model& operator^=(const NTLFp_model& other);\n    NTLFp_model& operator^=(unsigned long pwr);\n    NTLFp_model& operator^=(const libff::bigint<1>& pwr);\n\n    NTLFp_model operator+(const NTLFp_model& other) const;\n    NTLFp_model operator-(const NTLFp_model& other) const;\n    NTLFp_model operator*(const NTLFp_model& other) const;\n    NTLFp_model operator/(const NTLFp_model& other) const;\n    NTLFp_model operator-() const;\n\n    NTLFp_model squared() const;\n    NTLFp_model& invert();\n    NTLFp_model inverse() const;\n    NTLFp_model sqrt() const;\n    void get_s_and_t(unsigned long& s, unsigned long& t);\n\n    NTLFp_model operator^(unsigned long pwr) const;\n    NTLFp_model operator^(const libff::bigint<1>& pwr) const;\n    NTLFp_model operator^(const NTLFp_model& other) const;\n    \n\n    static size_t size_in_bits() { return num_bits; }\n    static size_t capacity() { return num_bits - 1; }\n    static unsigned long field_char() { return modulus; }\n    static NTLFp_model<modulus> geometric_generator() { return NTLFp_model<modulus>::multiplicative_generator; }\n    static NTLFp_model<modulus> arithmetic_generator() { return 1; }\n\n    static NTLFp_model<modulus> zero();\n    static NTLFp_model<modulus> one();\n    static NTLFp_model<modulus> random_element();\n\n    friend std::ostream& operator<< <modulus>(std::ostream &out, const NTLFp_model<modulus> &p);\n    friend std::istream& operator>> <modulus>(std::istream &in, NTLFp_model<modulus> &p);\n};\n\ntemplate<unsigned long modulus>\nsize_t NTLFp_model<modulus>::num_bits;\n\ntemplate<unsigned long modulus>\nsize_t NTLFp_model<modulus>::s;\n\ntemplate<unsigned long modulus>\nsize_t NTLFp_model<modulus>::t;\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::multiplicative_generator;\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::root_of_unity;\n\n} // libsnark\n\n#include \"ntlfp.tcc\"\n\n#endif // NTLFP_HPP_\n", "meta": {"hexsha": "0d6593c35230717880d77e967f025e1dabcdac51", "size": 3913, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lattice_snarg/algebra/fields/ntlfp.hpp", "max_stars_repo_name": "dwu4/lattice-snarg", "max_stars_repo_head_hexsha": "f5ef3e75d7200ee2b794d04b102fc7502b149628", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T16:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-02T03:16:15.000Z", "max_issues_repo_path": "lattice_snarg/algebra/fields/ntlfp.hpp", "max_issues_repo_name": "dwu4/lattice-snarg", "max_issues_repo_head_hexsha": "f5ef3e75d7200ee2b794d04b102fc7502b149628", "max_issues_repo_licenses": ["MIT"], "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_snarg/algebra/fields/ntlfp.hpp", "max_forks_repo_name": "dwu4/lattice-snarg", "max_forks_repo_head_hexsha": "f5ef3e75d7200ee2b794d04b102fc7502b149628", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-12T07:11:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-16T18:20:57.000Z", "avg_line_length": 33.4444444444, "max_line_length": 112, "alphanum_fraction": 0.6815742397, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5486056713652614}}
{"text": "#include <Eigen/Core>\n#include \"mex.h\"\n\nusing namespace Eigen;\nusing namespace std;\n\n// TODO openmp version\n\n// NOTE: mxSetProperty and possibly mxGetProperty make copies, even with\n// classdef < handle! lame! I believe mxGetField does NOT make a copy, though I\n// haven't tested it recently\n\nvoid mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )\n{\n\n    /* SETUP */\n    if (nrhs != 3) { mexErrMsgTxt(\"wrong number of arguments\\n\"); }\n\n    //// pull out inputs\n\n    // data\n    if (!mxGetField(prhs[0],0,\"data\")) { mexErrMsgTxt(\"data missing 'data' field\\n\"); }\n    int8_t *alldata = (int8_t *) mxGetData(mxGetField(prhs[0],0,\"data\"));\n    int bigT = mxGetN(mxGetField(prhs[0],0,\"data\")); // total length of the data\n    int num_subparts = mxGetM(mxGetField(prhs[0],0,\"data\")); // number of sub-parts\n\n    if (!mxGetField(prhs[0],0,\"resources\")) { mexErrMsgTxt(\"data missing 'resources' field\\n\"); }\n    int16_t *allresources = (int16_t *) mxGetData(mxGetField(prhs[0],0,\"resources\"));\n\n    if (!mxGetField(prhs[0],0,\"starts\")) { mexErrMsgTxt(\"data missing 'starts' field\\n\"); }\n    int32_t *starts = (int32_t *) mxGetData(mxGetField(prhs[0],0,\"starts\"));\n    int num_sequences = max(mxGetN(mxGetField(prhs[0],0,\"starts\")),\n            mxGetM(mxGetField(prhs[0],0,\"starts\")));\n\n    if (!mxGetField(prhs[0],0,\"lengths\")) { mexErrMsgTxt(\"data missing 'lengths' field\\n\"); }\n    int32_t *lengths = (int32_t *) mxGetData(mxGetField(prhs[0],0,\"lengths\"));\n\n    // parameters struct\n    if (!mxGetField(prhs[1],0,\"learns\")) { mexErrMsgTxt(\"model missing 'learns' field\\n\"); }\n    double *learns = mxGetPr(mxGetField(prhs[1],0,\"learns\"));\n    int num_resources = max(mxGetM(mxGetField(prhs[1],0,\"learns\")),\n            mxGetN(mxGetField(prhs[1],0,\"learns\")));\n\n    if (!mxGetField(prhs[1],0,\"forgets\")) { mexErrMsgTxt(\"model missing 'forgets' field\\n\"); }\n    double *forgets = mxGetPr(mxGetField(prhs[1],0,\"forgets\"));\n\n    if (!mxGetField(prhs[1],0,\"guesses\")) { mexErrMsgTxt(\"model missing 'guesses' field\\n\"); }\n    double *guess = mxGetPr(mxGetField(prhs[1],0,\"guesses\"));\n\n    if (!mxGetField(prhs[1],0,\"slips\")) { mexErrMsgTxt(\"model missing 'slips' field\\n\"); }\n    double *slip = mxGetPr(mxGetField(prhs[1],0,\"slips\"));\n\n    if (!mxGetField(prhs[1],0,\"prior\")) { mexErrMsgTxt(\"model missing 'prior' field\\n\"); }\n    double prior = mxGetScalar(mxGetField(prhs[1],0,\"prior\"));\n\n    Array2d initial_distn;\n    initial_distn << 1-prior, prior;\n\n    MatrixXd As(2,2*num_resources);\n    for (int n=0; n<num_resources; n++) {\n        As.col(2*n) << 1-learns[n], learns[n];\n        As.col(2*n+1) << forgets[n], 1-forgets[n];\n    }\n\n    // forward messages\n    double *all_forward_messages = mxGetPr(prhs[2]);\n\n    //// outputs\n\n    // lhs outputs\n    if (nlhs != 1) { mexErrMsgTxt(\"must have one output\\n\"); }\n    plhs[0] = mxCreateDoubleMatrix(2,bigT,mxREAL);\n    double *all_predictions = mxGetPr(plhs[0]);\n    Map<Array2Xd,Aligned> predictions(mxGetPr(plhs[0]),2,bigT);\n\n    /* COMPUTATION */\n\n    for (int sequence_index=0; sequence_index < num_sequences; sequence_index++) {\n        // NOTE: -1 because Matlab indexing starts at 1\n        int sequence_start = ((int) starts[sequence_index]) - 1;\n        int T = (int) lengths[sequence_index];\n\n        int16_t *resources = allresources + sequence_start;\n        Map<MatrixXd> forward_messages(all_forward_messages + 2*sequence_start,2,T);\n        Map<MatrixXd> predictions(all_predictions + 2*sequence_start,2,T);\n\n        predictions.col(0) = initial_distn;\n        for (int t=0; t<T-1; t++) {\n            predictions.col(t+1) = As.block(0,2*(resources[t]-1),2,2) * forward_messages.col(t);\n        }\n    }\n}\n\n", "meta": {"hexsha": "47ebb436df38e24b155a1951c5377faf80cf980b", "size": 3684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "+fit/predict_onestep_states.cpp", "max_stars_repo_name": "CAHLR/xBKT", "max_stars_repo_head_hexsha": "73fae02218094a8cf1896992308e2b495d7c610a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-10-10T19:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T06:28:17.000Z", "max_issues_repo_path": "+fit/predict_onestep_states.cpp", "max_issues_repo_name": "CAHLR/xBKT", "max_issues_repo_head_hexsha": "73fae02218094a8cf1896992308e2b495d7c610a", "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": "+fit/predict_onestep_states.cpp", "max_forks_repo_name": "CAHLR/xBKT", "max_forks_repo_head_hexsha": "73fae02218094a8cf1896992308e2b495d7c610a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-01T21:14:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-18T09:39:08.000Z", "avg_line_length": 39.1914893617, "max_line_length": 97, "alphanum_fraction": 0.6433224756, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5486056708261552}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n#include <valarray>\n#include <sstream>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"vlasovpp/field.h\"\n#include \"vlasovpp/weno.h\"\n#include \"vlasovpp/fft.h\"\n#include \"vlasovpp/array_view.h\"\n#include \"vlasovpp/poisson.h\"\n\n#ifndef SIGMA\n#define SIGMA (2.*std::sqrt(2.))\n#endif\n#define E_MAX (0.6)\n\n/*\ntemplate <unsigned int i>\nstruct phi\n{\n  static std::complex<double>\n  operator () ( std::complex<double> const & z ) {\n    static std::valarray<std::complex<double>> coeff(i);\n    coeff[0] = 1.;\n\n    for ( unsigned int k=1 ; k<coeff.size() ; ++k ) {\n      coeff[k] = coeff[k-1] * z / (double(k));\n    }\n\n    return (std::exp(z) - std::accumulate( std::begin(coeff) , std::end(coeff) , std::complex<double>(0.,0.) ))/(std::pow(z,i));\n  }\n};\n*/\ntemplate <unsigned int i>\nstd::complex<double>\nphi ( std::complex<double> const & _z )\n{\n  std::valarray<std::complex<double>> coeff(i);\n  coeff[0] = 1.;\n\n  std::complex<double> z = _z;\n  if ( _z == 0. ) { z = std::complex<double>(1.,0.); }\n\n  for ( unsigned int k=1 ; k<coeff.size() ; ++k ) {\n    coeff[k] = coeff[k-1] * z / (double(k));\n  }\n  //std::copy(std::begin(coeff),std::end(coeff),std::ostream_iterator<std::complex<double>>(std::cout,\" . \"));\n  //std::cout << std::endl;\n\n  if ( z != 0. ) {\n    return (std::exp(z) - std::accumulate( std::begin(coeff) , std::end(coeff) , std::complex<double>(0.,0.) ))/(std::pow(z,i));  \n  }\n  return coeff[i-1];\n}\n\nnamespace o2 {\n  template < typename _T , std::size_t NumDimsV >\n  auto\n  trp_v ( field<_T,NumDimsV> const & u , ublas::vector<_T> const& E )\n  {\n    field<_T,NumDimsV> trp(tools::array_view<const std::size_t>(u.shape(),NumDimsV+1));\n\n    { auto k=0, km1=trp.size(0)-1;\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[k+1][i]-u[km1][i])/(2.*u.step.dv) );\n      }\n    }\n    for ( auto k=1 ; k<trp.size(0)-1 ; ++k ) {\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[k+1][i]-u[k-1][i])/(2.*u.step.dv) );\n      }\n    }\n    { auto k=trp.size(0)-1, kp1=0;\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[kp1][i]-u[k-1][i])/(2.*u.step.dv) );\n      }\n    }\n\n    return trp;\n  }\n}\n\nnamespace math = boost::math::constants;\nconst std::complex<double> & I = std::complex<double>(0.,1.);\n\n#define SQ(X) ((X)*(X))\n#define Xi(i) (i*f.step.dx+f.range.x_min)\n#define Vk(k) (k*f.step.dv+f.range.v_min)\n\nint main(int,char**)\n{\n\tstd::size_t Nx = 135, Nv = 256 , Nb_iter=10;\n\tfield<double,1> f(boost::extents[Nv][Nx]);\n\n\tf.range.v_min = -8.; f.range.v_max = 8.;\n\tf.step.dv = (f.range.v_max-f.range.v_min)/Nv;\n\n  const double Kx = 0.3;\n  f.range.x_min = 0.; f.range.x_max = 2./Kx*math::pi<double>();\n\t//f.range.x_min = 0.; f.range.x_max = 20.*math::pi<double>();\n  //f.range.x_min = 0.; f.range.x_max = 4.0*math::pi<double>();\n  //f.range.x_min = -8.; f.range.x_max = 8.;\n\tf.step.dx = (f.range.x_max-f.range.x_min)/Nx;\n\n  // SIGMA is the CFL number 0.45 is E_max in our test case\n\tconst double dt = 0.05;//SIGMA*f.step.dv/E_MAX; //1.606*f.step.dv/0.6; //0.005; //1.606*f.step.dv/0.6; //0.5*6.*math::pi<double>()/(Nv*f.range.v_max);\n\n  //field<double,1> f_sol = f;\n  //field<double,1> f_ini = f;\n\t\n\tublas::vector<double> v (Nv,0.);\n  ublas::vector<double> E (Nx,0.),rho(Nx);\n  for ( std::size_t k=0 ; k<Nv ; ++k ) { v[k] = Vk(k); }\n  //for ( std::size_t i=0 ; i<Nx ; ++i ) { E[i] = -Xi(i); }\n\n\tconst double l = f.range.x_max-f.range.x_min;\n\tublas::vector<double> kx(Nx);\n\t//for ( auto i=0 ; i<Nx/2+1 ; ++i )   { kx[i] = 2.*math::pi<double>()*i/l; }\n\t//for ( auto i=0 ; i<((Nx/2)) ; ++i ) { kx[i+Nx/2+1] = -kx[Nx/2-i]; }\n  for ( auto i=0 ; i<Nx/2 ; ++i ) { kx[i]    = 2.*math::pi<double>()*i/l; }\n  for ( int i=-Nx/2 ; i<0 ; ++i ) { kx[Nx+i] = 2.*math::pi<double>()*i/l; }\n\t\n\n  double ui = 3.4;\n  double alpha = 0.1;\n  double Tc = 0.0001;\n\n  //double np = 0.9 , nb = 0.2 , ui = 4.5;\n  for (field<double,2>::size_type k=0 ; k<f.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<f.size(1) ; ++i ) {\n      //f[k][i] = ( std::exp(-0.5*SQ(Vk(k)))*np/std::sqrt(2.*math::pi<double>()) + nb/std::sqrt(2.*math::pi<double>())*std::exp(-0.5*SQ(Vk(k)-ui)/0.25) )*(1.+0.04*std::cos(0.5*Xi(i)));\n      \n      // Bump on Tail\n      f[k][i] = ( std::exp(-0.5*SQ(Vk(k)))*np/std::sqrt(2.*math::pi<double>()) + nb/std::sqrt(2.*math::pi<double>())*std::exp(-0.5*SQ(Vk(k)-ui)/0.25) )*(1.+0.04*std::cos(0.3*Xi(i)));\n      // Landau dumpping test\n      //f[k][i] = (1./std::sqrt(2*math::pi<double>()))*std::exp(-0.5*SQ(Vk(k)))*(1.+0.001*std::cos(0.5*Xi(i)));\n      \n      //f[k][i] = std::exp( -SQ(Xi(i)-6) );\n      //f[k][i] = std::exp(-SQ(Xi(i)-3)/0.5 - SQ(Vk(k))/2.);\n      //f_sol[k][i] = std::exp(-SQ(Xi(i)-3)/0.5 - SQ(Vk(k))/2.);\n      //f[k][i] = SQ(v(k))*std::exp(-0.5*SQ(Vk(k)))/std::sqrt(2.*math::pi<double>())*(1.+0.01*std::cos(0.5*Xi(i)));\n      //f_ini[k][i] = f[k][i];\n      //f_sol[k][i] =  std::exp(-SQ(Xi(i)-3.-v[k]*Nb_iter*dt)/0.5 - SQ(Vk(k)-E[i]*Nb_iter*dt)/2.);\n\n      // triple bump\n      //f[k][i] = ( 0.5*alpha/std::sqrt(2.*math::pi<double>())*std::exp(-0.5*SQ(Vk(k)-ui)) + 0.5*alpha/std::sqrt(2.*math::pi<double>())*std::exp(-0.5*SQ(Vk(k)+ui)) )*(1.+0.04*std::cos(Kx*Xi(i))) + ((1-alpha)/(std::sqrt(2.*math::pi<double>()*Tc))*std::exp(-0.5*SQ(Vk(k))/Tc));\n    }\n  }\n  f.write(\"vphl/kin/init.dat\");\n\n  poisson<double> poisson_solver(Nx,l);\n  rho = f.density();\n  E = poisson_solver(rho);\n  \n\n  //double Tf = 60.;//2*math::pi<double>();\n  double Tf = 40.;\n  int i_t=0;\n\n  std::cout << \"Nx: \" << Nx << \"\\n\";\n  std::cout << \"Nv: \" << Nv << \"\\n\";\n  std::cout << \"v_min: \" << f.range.v_min << \"\\n\";\n  std::cout << \"v_max: \" << f.range.v_max << \"\\n\";\n  std::cout << \"x_min: \" << f.range.x_min << \"\\n\";\n  std::cout << \"x_max: \" << f.range.x_max << \"\\n\";\n  std::cout << \"dt: \" << dt << \"\\n\";\n  std::cout << \"dx: \" << f.step.dx << \"\\n\";\n  std::cout << \"dv: \" << f.step.dv << \"\\n\";\n  std::cout << \"Tf: \" << Tf << \"\\n\";\n  std::cout << \"f_0: \" << \"\\\"bot\\\"\" << \"\\n\";\n  std::cout << std::endl;\n\n  std::ofstream info(\"info.yaml\");\n\n  info << \"Nx: \" << Nx << \"\\n\";\n  info << \"Nv: \" << Nv << \"\\n\";\n  info << \"v_min: \" << f.range.v_min << \"\\n\";\n  info << \"v_max: \" << f.range.v_max << \"\\n\";\n  info << \"x_min: \" << f.range.x_min << \"\\n\";\n  info << \"x_max: \" << f.range.x_max << \"\\n\";\n  info << \"dt: \" << dt << \"\\n\";\n  info << \"dx: \" << f.step.dx << \"\\n\";\n  info << \"dv: \" << f.step.dv << \"\\n\";\n  info << \"Tf: \" << Tf << \"\\n\";\n  info << \"f_0: \" << \"\\\"bot\\\"\" << \"\\n\";\n  info << std::endl;\n  info.close();\n\n  ublas::vector<double> ee(int(std::ceil(Tf/dt))+1,0.);\n  ublas::vector<double> Emax(int(std::ceil(Tf/dt))+1,0.);\n  ublas::vector<double> H(int(std::ceil(Tf/dt))+1,0.);\n  //ublas::vector<double> ee(Nb_iter);\n  //ublas::vector<double> Emax(Nb_iter);\n  //ublas::vector<double> H(Nb_iter);\n\n  field<double,1> f1(tools::array_view<const std::size_t>(f.shape(),2)),f2(tools::array_view<const std::size_t>(f.shape(),2)),f3(tools::array_view<const std::size_t>(f.shape(),2)),f4(tools::array_view<const std::size_t>(f.shape(),2)),f5(tools::array_view<const std::size_t>(f.shape(),2));\n  fft::spectrum_ hf(Nx),hf1(Nx),hf2(Nx),hf3(Nx),hf4(Nx),hf5(Nx),hEdvf(Nx),hEdvf1(Nx),hEdvf2(Nx),hEdvf3(Nx),hEdvf4(Nx);\n\n\n  rho = f.density();\n  E = poisson_solver(rho);\n  //for ( int i=0 ; i<E.size() ; ++i ) { E[i] = 1.; }\n  //for ( int i=0 ; i<E.size() ; ++i ) { std::cout << E[i] << \" \"; }\n  //  std::cout << std::endl;\n\n  //ee(i_t) = 0.;\n  //for ( auto i=0 ; i<Nx ; ++i ) {\n  //  ee(i_t) += SQ(E(i))*f.step.dx;\n  //}\n  //ee(i_t) = std::sqrt(ee(i_t));\n  H(i_t) = energy(f,E);\n\n\n#define L (-v(k)*I*kx[i])\n//#define L (0.)\n  while (  i_t*dt < Tf ) {\n  //while (  i_t < Nb_iter ) {\n  \t//if (t%32==0) { std::cout<<\"\\r\"<<t<<\" \"<<std::flush ; }\n    std::cout<<\" [\"<<std::setw(5)<<i_t<<\"] \"<<i_t*dt<<\"\\r\"<<std::flush;\n    Emax(i_t) = std::abs(*std::max_element( E.begin() , E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} ));\n    ee(i_t) = 0.;\n    for ( auto i=0 ; i<Nx ; ++i ) { ee(i_t) += SQ(E(i))*f.step.dx; }\n    ee(i_t) = std::sqrt(ee(i_t));\n\n    /**\n    // exprk(2,2) =============================================================\n    #define SCHEME \"expRK22\"\n    // SIGMA = 0.551 (10^-2)\n    E = poisson_solver(f.density());\n    field<double,1> Edvf = o2::trp_v(f,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf1[i] = std::exp(-L*dt)*hf[i] + dt*phi<1>(dt*L)*hEdvf[i];\n      }\n      hf1.ifft(&(f1[k][0]));\n    }\n\n    E = poisson_solver(f1.density());\n    field<double,1> Edvf1 = o2::trp_v(f1,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&f[k][0]);\n      hf1.fft(&f1[k][0]);\n      hEdvf.fft(&(Edvf[k][0]));\n      hEdvf1.fft(&(Edvf1[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf[i] = std::exp(-L*dt)*hf[i] + dt*( (phi<1>(dt*L)-phi<2>(dt*L))*hEdvf[i] + phi<2>(dt*L)*hEdvf1[i] );\n      }\n\n      hf.ifft(&(f[k][0]));\n    }\n\n    **/\n    /**\n    // Cox-Matthews ===========================================================\n    #define SCHEME \"CM\"\n    // SIGMA = 0.450 (10^-2)\n    E = poisson_solver( f.density() );\n    field<double,1> Edvf = o2::trp_v(f,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf1[i] = std::exp(-0.5*L*dt)*hf[i] + 0.5*dt*phi<1>(-0.5*L*dt)*hEdvf[i];\n      }\n\n      hf1.ifft(&(f1[k][0]));\n    }\n\n    E = poisson_solver( f1.density() );\n    field<double,1> Edvf1 = o2::trp_v(f1,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n      hEdvf1.fft(&(Edvf1[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf2[i] = std::exp(-0.5*L*dt)*hf[i] + 0.5*dt*phi<1>(-0.5*L*dt)*hEdvf1[i];\n      }\n      \n      hf2.ifft(&(f2[k][0]));\n    }\n\n    E = poisson_solver( f2.density() );\n    field<double,1> Edvf2 = o2::trp_v(f2,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n      hEdvf1.fft(&(Edvf1[k][0]));\n      hEdvf2.fft(&(Edvf2[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf3[i] = std::exp(-L*dt)*hf[i] + 0.5*dt*phi<1>(-0.5*L*dt)*(std::exp(-0.5*L*dt)-1.)*hEdvf[i] + dt*phi<1>(-0.5*L*dt)*hEdvf2[i];\n      }\n\n      hf3.ifft(&(f3[k][0]));\n    }\n\n    E = poisson_solver( f3.density() );\n    field<double,1> Edvf3  = o2::trp_v(f3,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hf3.fft(&(f3[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n      hEdvf1.fft(&(Edvf1[k][0]));\n      hEdvf2.fft(&(Edvf2[k][0]));\n      hEdvf3.fft(&(Edvf3[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf4[i] = std::exp(-L*dt)*hf[i] + dt*( (phi<1>(-L*dt)-3.*phi<2>(-L*dt)+4.*phi<3>(-L*dt))*hEdvf[i]\n                                             + (2.*phi<2>(-L*dt)-4.*phi<3>(-L*dt))*(hEdvf1[i]+hEdvf2[i])\n                                             + (-phi<2>(-L*dt)+4.*phi<3>(-L*dt))*hEdvf3[i] );\n      }\n\n      hf4.ifft(&(f[k][0]));\n    }\n\n    **/\n    /**\n    // Krogstad ===============================================================\n    #define SCHEME \"K\"\n    // SIGMA = 0.200 (10^-2)\n    E = poisson_solver( f.density() );\n    field<double,1> Edvf = o2::trp_v(f,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf1[i] = std::exp(-0.5*L*dt)*hf[i] + 0.5*dt*phi<1>(-0.5*L*dt)*hEdvf[i];\n      }\n\n      hf1.ifft(&(f1[k][0]));\n    }\n\n    E = poisson_solver( f1.density() );\n    field<double,1> Edvf1 = o2::trp_v(f1,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n      hEdvf1.fft(&(Edvf1[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf2[i] = std::exp(-0.5*L*dt)*hf[i] + dt*(0.5*phi<1>(-0.5*L*dt)-phi<2>(-0.5*L*dt))*hEdvf[i] + dt*phi<2>(-0.5*L*dt)*hEdvf1[i];\n      }\n      \n      hf2.ifft(&(f2[k][0]));\n    }\n\n    E = poisson_solver( f2.density() );\n    field<double,1> Edvf2 = o2::trp_v(f2,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n      hEdvf1.fft(&(Edvf1[k][0]));\n      hEdvf2.fft(&(Edvf2[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf3[i] = std::exp(-L*dt)*hf[i] + dt*(phi<1>(-L*dt)-2.*phi<2>(-0.5*L*dt))*hEdvf[i] + 2.*dt*phi<2>(-L*dt)*hEdvf2[i];\n      }\n\n      hf3.ifft(&(f3[k][0]));\n    }\n\n    E = poisson_solver( f3.density() );\n    field<double,1> Edvf3  = o2::trp_v(f3,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hf3.fft(&(f3[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n      hEdvf1.fft(&(Edvf1[k][0]));\n      hEdvf2.fft(&(Edvf2[k][0]));\n      hEdvf3.fft(&(Edvf3[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf4[i] = std::exp(-L*dt)*hf[i] + dt*( (phi<1>(-L*dt)-3.*phi<2>(-L*dt)+4.*phi<3>(-L*dt))*hEdvf[i]\n                                             + (2.*phi<2>(-L*dt)-4.*phi<3>(-L*dt))*(hEdvf1[i]+hEdvf2[i])\n                                             + (-phi<2>(-L*dt)+4.*phi<3>(-L*dt))*hEdvf3[i] );\n      }\n\n      hf4.ifft(&(f[k][0]));\n    }\n\n    **/\n    /**\n    // Hochbruck-Ostermann ====================================================\n    #define SCHEME \"HO\"\n    // SIGMA = 0.501 (10^-2)\n    E = poisson_solver( f.density() );\n    field<double,1> Edvf = o2::trp_v(f,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf1[i] = std::exp(-0.5*L*dt)*hf[i] + 0.5*dt*phi<1>(-0.5*L*dt)*hEdvf[i];\n      }\n\n      hf1.ifft(&(f1[k][0]));\n    }\n\n    E = poisson_solver( f1.density() );\n    field<double,1> Edvf1 = o2::trp_v(f1,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n      hEdvf1.fft(&(Edvf1[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf2[i] = std::exp(-0.5*L*dt)*hf[i] + dt*(0.5*phi<1>(-0.5*L*dt)-phi<2>(-0.5*L*dt))*hEdvf[i] + dt*phi<2>(-0.5*L*dt)*hEdvf1[i];\n      }\n      \n      hf2.ifft(&(f2[k][0]));\n    }\n\n    E = poisson_solver( f2.density() );\n    field<double,1> Edvf2 = o2::trp_v(f2,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n      hEdvf1.fft(&(Edvf1[k][0]));\n      hEdvf2.fft(&(Edvf2[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf3[i] = std::exp(-L*dt)*hf[i] + dt*(phi<1>(-L*dt)-2.*phi<2>(-L*dt))*hEdvf[i] + dt*phi<2>(-L*dt)*hEdvf1[i] + dt*phi<2>(-L*dt)*hEdvf2[i];\n      }\n\n      hf3.ifft(&(f3[k][0]));\n    }\n\n    E = poisson_solver( f3.density() );\n    field<double,1> Edvf3  = o2::trp_v(f3,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hf3.fft(&(f3[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n      hEdvf1.fft(&(Edvf1[k][0]));\n      hEdvf2.fft(&(Edvf2[k][0]));\n      hEdvf3.fft(&(Edvf3[k][0]));\n\n#define a52 (0.5*phi<2>(-0.5*L*dt)-phi<3>(-L*dt)+0.25*phi<2>(-L*dt)-0.5*phi<3>(-0.5*L*dt))\n#define a54 (0.25*phi<2>(-0.5*L*dt)-a52)\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf4[i] = std::exp(-0.5*L*dt)*hf[i] + dt*(0.5*phi<1>(-0.5*L*dt)-2.*a52-a54)*hEdvf[i] + dt*a52*(hEdvf1[i]+hEdvf2[i]) + dt*(0.25*phi<2>(-0.5*L*dt)-a52)*hEdvf3[i];\n      }\n#undef a54\n#undef a52\n\n      hf4.ifft(&(f4[k][0]));\n    }\n\n    E = poisson_solver( f4.density() );\n    field<double,1> Edvf4  = o2::trp_v(f4,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hf3.fft(&(f3[k][0]));\n      hf4.fft(&(f4[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n      hEdvf1.fft(&(Edvf1[k][0]));\n      hEdvf2.fft(&(Edvf2[k][0]));\n      hEdvf3.fft(&(Edvf3[k][0]));\n      hEdvf4.fft(&(Edvf4[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf5[i] = std::exp(-L*dt)*hf[i] + dt*( (phi<1>(-L*dt)-3.*phi<2>(-L*dt)+4.*phi<3>(-L*dt))*hEdvf[i]\n                                             + (-phi<2>(-L*dt)+4.*phi<3>(-L*dt))*hEdvf3[i]\n                                             + (4.*phi<2>(-L*dt)-8.*phi<3>(-L*dt))*hEdvf4[i] );\n      }\n\n      hf5.ifft(&(f[k][0]));\n    }\n    **/\n    /**\n    // RK(3,2) best ===========================================================\n    #define SCHEME \"RK32\"\n    // SIGMA = 2. (y_max)\n    // SIGMA = 1.344 (WENO)\n    E = poisson_solver(f.density());\n    field<double,1> Edvf = o2::trp_v(f,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf1[i] = std::exp(0.5*L*dt)*( hf[i]-0.5*dt*hEdvf[i] );\n      }\n      hf1.ifft(&(f1[k][0]));\n    }\n\n    E = poisson_solver(f1.density());\n    Edvf = o2::trp_v(f1,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      //hf1.fft(&(f1[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf2[i] = std::exp(0.5*L*dt)*hf[i] - 0.5*dt*hEdvf[i];\n      }\n      hf2.ifft(&(f2[k][0]));\n    }\n\n    E = poisson_solver(f2.density());\n    Edvf = o2::trp_v(f2,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      //hf1.fft(&(f1[k][0]));\n      //hf2.fft(&(f2[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf[i] = std::exp(L*dt)*hf[i] - dt*std::exp(0.5*L*dt)*hEdvf[i];\n      }\n      hf.ifft(&(f[k][0]));\n    }\n    **/\n    /**/\n    // RK(3,3) ================================================================\n    // RK(3,3) eq19 ===========================================================\n    #define SCHEME \"RK33\"\n    //#define SCHEME \"RK33_eq19\"\n    // SIGMA = std::sqrt(3) (y_max)\n    // SIGMA = 1.433 (WENO)\n    E = poisson_solver(f.density());\n    \n    //std::cout << \"\\n\" << L << \" \" << *std::max_element(E.begin(),E.end()) << \" \" << *std::min_element(E.begin(),E.end()) << std::endl;\n\n    field<double,1> Edvf = weno::trp_v(f,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf1[i] = std::exp(L*dt)*( hf[i]-dt*hEdvf[i] );\n        //hf1[i] = 0.5*std::exp((2./3.)*L*dt)*hf[i] + 0.5*std::exp((2./3.)*dt*L)*( hf[i] - (4./3.)*dt*hEdvf[i] );\n      }\n      hf1.ifft(&(f1[k][0]));\n    }\n\n    E = poisson_solver(f1.density());\n    Edvf = weno::trp_v(f1,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf2[i] = 0.75*std::exp(0.5*L*dt)*hf[i] + 0.25*std::exp(-0.5*L*dt)*( hf1[i]-dt*hEdvf[i] );\n        //hf2[i] = (2./3.)*std::exp((2./3.)*dt*L)*hf[i] + (1./3.)*( hf1[i] - (4./3.)*dt*hEdvf[i] );\n      }\n      hf2.ifft(&(f2[k][0]));\n    }\n\n    E = poisson_solver(f2.density());\n    Edvf = weno::trp_v(f2,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf[i] = (1./3.)*std::exp(L*dt)*hf[i] + (2./3.)*std::exp(0.5*L*dt)*( hf2[i]-dt*hEdvf[i] );\n        //hf[i] = (59./128.)*std::exp(L*dt)*hf[i] + (15./128.)*std::exp(L*dt)*( 2.*hf1[i]*std::exp(-(2./3.)*L*dt) - hf[i] ) + (27./64.)*std::exp((1./3.)*dt*L)*( hf2[i] - (4./3.)*dt*hEdvf[i] );\n      }\n      hf.ifft(&(f[k][0]));\n    }\n    /**/\n    /**\n    // RK(4,4) ================================================================\n    // RK(4,4) 3/8 rule =======================================================\n    #define SCHEME \"RK44\"\n    //#define SCHEME \"RK44_38\"\n    // SIGMA = 2.*std::sqrt(2.) (y_max)\n    // SIGMA = 1.731 (WENO)\n    E = poisson_solver( f.density() );\n    field<double,1> Edvf = weno::trp_v(f,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf1[i] = std::exp(0.5*L*dt)*( hf[i] - 0.5*dt*hEdvf[i] );\n        //hf1[i] = std::exp((1./3.)*L*dt)*( hf[i] - (1./3.)*dt*hEdvf[i] );\n      }\n\n      hf1.ifft(&(f1[k][0]));\n    }\n\n    E = poisson_solver( f1.density() );\n    Edvf = weno::trp_v(f1,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf2[i] = std::exp(0.5*L*dt)*hf[i] - 0.5*dt*hEdvf[i] ;\n        //hf2[i] = 2.*std::exp((2./3.)*L*dt)*hf[i] - std::exp((1./3.)*L*dt)*hf1[i] - dt*std::exp((1./3.)*L*dt)*hEdvf[i];\n      }\n      \n      hf2.ifft(&(f2[k][0]));\n    }\n\n    E = poisson_solver( f2.density() );\n    Edvf = weno::trp_v(f2,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf3[i] = std::exp(L*dt)*hf[i] - dt*std::exp(0.5*L*dt)*hEdvf[i];\n        //hf3[i] = 2.*std::exp((2./3.)*L*dt)*hf1[i] - std::exp((1./3.)*L*dt)*hf2[i] - dt*std::exp((1./3.)*L*dt)*hEdvf[i];\n      }\n\n      hf3.ifft(&(f3[k][0]));\n    }\n\n    E = poisson_solver( f3.density() );\n    Edvf  = weno::trp_v(f3,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hf3.fft(&(f3[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf[i] = -(1./3.)*std::exp(L*dt)*hf[i] + (1./3.)*std::exp(0.5*L*dt)*hf1[i] + (2./3.)*std::exp(0.5*L*dt)*hf2[i] + (1./3.)*hf3[i] - (1./6.)*dt*hEdvf[i];\n        //hf[i] = -(1./8.)*std::exp(L*dt)*hf[i] + 0.75*std::exp((1./3.)*L*dt)*hf2[i] + (3./8.)*hf3[i] - (1./8.)*dt*hEdvf[i];\n      }\n\n      hf.ifft(&(f[k][0]));\n    }\n    **/\n    /**\n    // RK(5,3) ================================================================\n    #define SCHEME \"RK53\"\n    E = poisson_solver(f.density());\n    field<double,1> Edvf = weno::trp_v(f,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf1[i] = std::exp((1./7.)*L*dt)*hf[i] - (1./7.)*dt*std::exp((1./7.)*L*dt)*hEdvf[i];\n      }\n      hf1.ifft(&(f1[k][0]));\n    }\n\n    E = poisson_solver(f1.density());\n    Edvf = weno::trp_v(f1,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf2[i] = std::exp((3./16.)*L*dt)*hf[i] - (3./16.)*dt*std::exp((5./112.)*L*dt)*hEdvf[i];\n      }\n      hf2.ifft(&(f2[k][0]));\n    }\n\n    E = poisson_solver(f2.density());\n    Edvf = weno::trp_v(f2,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf3[i] = std::exp((1./3.)*L*dt)*hf[i] - (1./3.)*dt*std::exp((7./48.)*L*dt)*hEdvf[i];\n      }\n      hf3.ifft(&(f3[k][0]));\n    }\n\n    E = poisson_solver(f3.density());\n    Edvf = weno::trp_v(f3,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf4[i] = std::exp((2./3.)*L*dt)*hf[i] - (2./3.)*dt*std::exp((1./3.)*L*dt)*hEdvf[i];\n      }\n      hf4.ifft(&(f4[k][0]));\n    }\n\n    E = poisson_solver(f4.density());\n    Edvf = weno::trp_v(f4,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf[i] = -0.75*std::exp(L*dt)*hf[i] + 1.75*std::exp((6./7.)*L*dt)*hf1[i] - 0.75*dt*std::exp((1./3.)*L*dt)*hEdvf[i];\n      }\n      hf.ifft(&(f[k][0]));\n    }\n    **/\n    /**\n    // DP5  ===================================================================\n    #define SCHEME \"DP5\"\n    E = poisson_solver(f.density());\n    field<double,1> Edvf = weno::trp_v(f,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf1[i] = std::exp((1./5.)*L*dt)*hf[i] - (1./5.)*dt*std::exp((1./5.)*L*dt)*hEdvf[i];\n      }\n      hf1.ifft(&(f1[k][0]));\n    }\n\n    E = poisson_solver(f1.density());\n    Edvf = weno::trp_v(f1,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf2[i] = (5./8.)*std::exp((3./10.)*L*dt)*hf[i] + (3./8.)*std::exp((1./10.)*L*dt)*hf1[i] - (9./40.)*dt*std::exp((1./10.)*L*dt)*hEdvf[i];\n      }\n      hf2.ifft(&(f2[k][0]));\n    }\n\n    E = poisson_solver(f2.density());\n    Edvf = weno::trp_v(f2,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf3[i] = (175./27.)*std::exp((4./5.)*L*dt)*hf[i] + (100./9.)*std::exp((3./5.)*L*dt)*hf1[i] - (448./27.)*std::exp(0.5*L*dt)*hf2[i] - (32./9.)*dt*std::exp(0.5*L*dt)*hEdvf[i];\n      }\n      hf3.ifft(&(f3[k][0]));\n    }\n\n    E = poisson_solver(f3.density());\n    Edvf = weno::trp_v(f3,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hf3.fft(&(f3[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf4[i] = (3551./6561.)*std::exp((8./9.)*L*dt)*hf[i] + (7420./2187.)*std::exp((31./45.)*L*dt)*hf1[i] - (37376./6561.)*std::exp((53./90.)*L*dt)*hf2[i] + (2014./729.)*std::exp((4./45.)*L*dt)*hf3[i] + (212./729.)*dt*std::exp((4./45.)*L*dt)*hEdvf[i];\n      }\n      hf4.ifft(&(f4[k][0]));\n    }\n\n    E = poisson_solver(f4.density());\n    Edvf = weno::trp_v(f4,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hf3.fft(&(f3[k][0]));\n      hf4.fft(&(f4[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf5[i] = (313397./335808.)*std::exp(L*dt)*hf[i] + (424025./55968.)*std::exp((4./5.)*L*dt)*hf1[i] - (61400./5247.)*std::exp((7./10.)*L*dt)*hf2[i] + (96075./18656.)*std::exp((1./5.)*L*dt)*hf3[i] - (35721./37312.)*std::exp((1./9.)*L*dt)*hf4[i] + (5103./18656.)*dt*std::exp((1./9.)*L*dt)*hEdvf[i];\n      }\n      hf5.ifft(&(f5[k][0]));\n    }\n\n    E = poisson_solver(f5.density());\n    Edvf = weno::trp_v(f5,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hf3.fft(&(f3[k][0]));\n      hf4.fft(&(f4[k][0]));\n      hf5.fft(&(f5[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf[i] = -(563./3456.)*std::exp(L*dt)*hf[i] - (575./252.)*std::exp((4./5.)*L*dt)*hf1[i] + (31400./10017.)*std::exp((7./10.)*L*dt)*hf2[i] + (325./1344.)*std::exp((1./5.)*L*dt)*hf3[i] - (7533./6784.)*std::exp((1./9.)*L*dt)*hf4[i] + (33./28.)*hf5[i] - (11./84.)*dt*hEdvf[i];\n      }\n      hf.ifft(&(f[k][0]));\n    }\n\n    **/\n    /**\n    // RK(8,6) ================================================================\n    #define SCHEME\"RK86\"\n    E = poisson_solver(f.density());\n    field<double,1> Edvf = weno::trp_v(f,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf1[i] = std::exp((1./9.)*L*dt)*hf[i] - (1./9.)*dt*std::exp((1./9.)*dt*L)*hEdvf[i];\n      }\n      hf1.ifft(&(f1[k][0]));\n    }\n\n    E = poisson_solver(f1.density());\n    Edvf = weno::trp_v(f1,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf2[i] = (5./8.)*std::exp((1./6.)*L*dt)*hf[i] + (3./8.)*std::exp((1./18.)*L*dt)*hf1[i] - (1./8.)*dt*std::exp((1./18.)*L*dt)*hEdvf[i];\n      }\n      hf2.ifft(&(f2[k][0]));\n    }\n\n    E = poisson_solver(f2.density());\n    Edvf = weno::trp_v(f2,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf3[i] = 2.*std::exp((1./3.)*L*dt)*hf[i] + 3.*std::exp((2./9.)*L*dt)*hf1[i] -4.*std::exp((1./6.)*L*dt)*hf2[i] - (2./3.)*dt*std::exp((1./6.)*L*dt)*hEdvf[i];\n      }\n      hf3.ifft(&(f3[k][0]));\n    }\n\n    E = poisson_solver(f3.density());\n    Edvf = weno::trp_v(f3,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hf3.fft(&(f3[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf4[i] = (305./1268.)*std::exp(0.5*L*dt)*hf[i] + (2817./1268.)*std::exp((7./18.)*L*dt)*hf1[i] - (927./317.)*std::exp((1./3.)*L*dt)*hf2[i] + (927./634.)*std::exp((1./6.)*L*dt)*hf3[i] - (321./1268.)*dt*std::exp((1./6.)*L*dt)*hEdvf[i];\n      }\n      hf4.ifft(&(f4[k][0]));\n    }\n\n    E = poisson_solver(f4.density());\n    Edvf = weno::trp_v(f4,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hf3.fft(&(f3[k][0]));\n      hf4.fft(&(f4[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf5[i] = (3191./321.)*std::exp((2./3.)*L*dt)*hf[i] - (2436./107.)*std::exp((5./9.)*L*dt)*hf1[i] - (2404./107.)*std::exp(0.5*L*dt)*hf2[i] + (12330./107.)*std::exp((1./3.)*L*dt)*hf3[i] - (25340./321.)*std::exp((1./6.)*L*dt)*hf4[i] - 8.*dt*std::exp((1./6.)*L*dt)*hEdvf[i];\n      }\n      hf5.ifft(&(f5[k][0]));\n    }\n\n    E = poisson_solver(f5.density());\n    Edvf = weno::trp_v(f5,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hf3.fft(&(f3[k][0]));\n      hf4.fft(&(f4[k][0]));\n      hf5.fft(&(f5[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf6[i] = -(15130159./6286464.)*std::exp((5./6.)*L*dt)*hf[i] + (2014319./349248.)*std::exp((13./18.)*L*dt)*hf1[i] + (1194095./523872.)*std::exp((2./3.)*L*dt)*hf2[i] - (1471057./116416.)*std::exp(0.5*L*dt)*hf3[i] + (12601453./1571616.)*std::exp((1./3.)*L*dt)*hf4[i] - (433./19584.)*std::exp((1./6.)*L*dt)*hf5[i] - (33./1088.)*dt*std::exp((1./6.)*L*dt)*hEdvf[i];\n      }\n      hf6.ifft(&(f6[k][0]));\n    }\n\n    E = poisson_solver(f6.density());\n    Edvf = weno::trp_v(f6,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hf3.fft(&(f3[k][0]));\n      hf4.fft(&(f4[k][0]));\n      hf5.fft(&(f5[k][0]));\n      hf6.fft(&(f6[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf7[i] = (805187./78966.)*std::exp(L*dt)*hf[i] - (2263766./48257.)*std::exp((8./9.)*L*dt)*hf1[i] + (2745422./144771.)*std::exp((5./6.)*L*dt)*hf2[i] + (2271108./48257.)*std::exp((2./3.)*L*dt)*hf3[i] - (13115270./434313.)*std::exp(0.5*L*dt)*hf4[i] - (227./2706.)*std::exp((1./3.)*L*dt)*hf5[i] + (888./451.)*std::exp((1./6.)*L*dt)*hf6[i] - (36./41.)*dt*std::exp((1./6.)*L*dt)*hEdvf[i];\n      }\n      hf7.ifft(&(f7[k][0]));\n    }\n\n    E = poisson_solver(f7.density());\n    Edvf = weno::trp_v(f7,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hf3.fft(&(f3[k][0]));\n      hf4.fft(&(f4[k][0]));\n      hf5.fft(&(f5[k][0]));\n      hf6.fft(&(f6[k][0]));\n      hf7.fft(&(f7[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        hf[i] = -(193999./179760.)*std::exp(L*dt)*hf[i] + (2487363./329560.)*std::exp((8./9.)*L*dt)*hf1[i] - (847909./164780.)*std::exp((5./6.)*L*dt)*hf2[i] - (1600251./329560.)*std::exp((2./3.)*L*dt)*hf3[i] + (362713./98868.)*std::exp(0.5*L*dt)*hf4[i] + (109./1232.)*std::exp((1./3.)*L*dt)*hf5[i] + (186./385.)*std::exp((1./6.)*L*dt)*hf6[i] + (41./140.)*hf7[i] - (41./840.)*dt*hEdvf[i];\n      }\n      hf.ifft(&(f[k][0]));\n    }\n    **/\n\n    // end of time loop\n    ++i_t;\n    rho = f.density();\n    E = poisson_solver(rho);\n    //ee(i_t) = 0.;\n    //for ( auto i=0 ; i<Nx ; ++i ) {\n    //  ee(i_t) += SQ(E(i))*f.step.dx;\n    //}\n    //ee(i_t) = std::sqrt(ee(i_t));\n    H(i_t) = energy(f,E);\n\n\n//#define FOLDER \"lukas/vp/\"\n#define FOLDER \"vphl/kin/\"\n#define SPACE_SCHEME \"weno\"\n/*\n    if ( i_t == int(15./dt) ) {\n      std::stringstream ss; ss << FOLDER << \"vp_\" << SCHEME << \"_\" << SPACE_SCHEME << \"_15.dat\";\n      f.write(ss.str());\n      std::cout << std::endl;\n    }\n    if ( i_t == int(20./dt) ) {\n      std::stringstream ss; ss << FOLDER << \"vp_\" << SCHEME << \"_\" << SPACE_SCHEME << \"_20.dat\";\n      f.write(ss.str());\n      std::cout << std::endl;\n    }\n    if ( i_t == int(25./dt) ) {\n      std::stringstream ss; ss << FOLDER << \"vp_\" << SCHEME << \"_\" << SPACE_SCHEME << \"_25.dat\";\n      f.write(ss.str());\n      std::cout << std::endl;\n    }\n    if ( i_t == int(30./dt) ) {\n      std::stringstream ss; ss << FOLDER << \"vp_\" << SCHEME << \"_\" << SPACE_SCHEME << \"_30.dat\";\n      f.write(ss.str());\n      std::cout << std::endl;\n    }\n    if ( i_t == int(35./dt) ) {\n      std::stringstream ss; ss << FOLDER << \"vp_\" << SCHEME << \"_\" << SPACE_SCHEME << \"_35.dat\";\n      f.write(ss.str());\n      std::cout << std::endl;\n    }\n*/\n\t} // while (  i_t*dt < Tf )\n#undef L\n  std::cout<<\" [\"<<std::setw(5)<<i_t<<\"] \"<<i_t*dt<<\"   \\r\"<<std::endl;\n\n  std::stringstream ss; ss << FOLDER << \"vp_\" << SCHEME << \"_\" << SPACE_SCHEME << \"_dt\" << dt << \".dat\";\n  f.write(ss.str());\n\n  rho = f.density();\n  auto dx_y = [&,count=0](auto const& y) mutable { std::stringstream ss; ss<<Xi(count++)<<\" \"<<y; return ss.str(); };\n  ss.str(std::string());\n  ss << FOLDER << \"rho_\" << SCHEME << \"_\" << SPACE_SCHEME << \"_\" << Tf << \".dat\";\n  std::ofstream of;\n  of.open(ss.str()); ss.str(std::string());\n  std::transform( rho.begin() , rho.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dx_y );\n  of.close();\n\n  ss.str(std::string());\n  //std::ofstream of;\n  std::size_t count = 0;\n  auto dt_y = [&,count=0](auto const& y) mutable { std::stringstream ss; ss<<(count++)*dt<<\" \"<<y; return ss.str(); };\n  ss << FOLDER << \"ee_\" << SCHEME << \"_\" << SPACE_SCHEME << \"_10.dat\";\n  of.open(ss.str()); ss.str(std::string());\n  for ( auto i=0; i<ee.size() ; ++i ) {\n    of << i*dt <<\" \" << ee[i] << \"\\n\";\n  }\n  of.close();\n  ss << FOLDER << \"H_\" << SCHEME << \"_\" << SPACE_SCHEME << \".dat\";\n  of.open(ss.str()); ss.str(std::string());\n  for ( auto i=0; i<H.size() ; ++i ) {\n    of << i*dt <<\" \" << (H[i]-H[0])/std::abs(H[0]) << \"\\n\";\n  }\n\n  //double h = std::abs(*std::max_element( H.begin() , H.end() , [&](double a,double b){return ( std::abs((a-H[0])/std::abs(H[0])) < std::abs((b-H[0])/std::abs(H[0])) );} ));\n  //std::cout << dt << \" \" << std::abs((h-H[0])/std::abs(H[0])) << \"\\n\";\n\n  of.close();\n  ss << FOLDER << \"Emax_\" << SCHEME << \"_\" << SPACE_SCHEME << \"_10.dat\";\n  of.open(ss.str()); ss.str(std::string());\n  std::transform( Emax.begin() , Emax.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dt_y );\n  of.close();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "70fd7b20924f0338bd3bb06aa17f52208f748d75", "size": 35449, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/main.cc", "max_stars_repo_name": "kivvix/vlasovpp", "max_stars_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_stars_repo_licenses": ["MIT"], "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/main.cc", "max_issues_repo_name": "kivvix/vlasovpp", "max_issues_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_issues_repo_licenses": ["MIT"], "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/main.cc", "max_forks_repo_name": "kivvix/vlasovpp", "max_forks_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_forks_repo_licenses": ["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.2833655706, "max_line_length": 390, "alphanum_fraction": 0.4452029676, "num_tokens": 14213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5486056705566016}}
{"text": "\n//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_SPECIAL_HERMITE_HPP\n#define BOOST_MATH_SPECIAL_HERMITE_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/tools/config.hpp>\n#include <boost/math/policies/error_handling.hpp>\n\nnamespace boost{\nnamespace math{\n\n// Recurrence relation for Hermite polynomials:\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type \n   hermite_next(unsigned n, T1 x, T2 Hn, T3 Hnm1)\n{\n   return (2 * x * Hn - 2 * n * Hnm1);\n}\n\nnamespace detail{\n\n// Implement Hermite polynomials via recurrence:\ntemplate <class T>\nT hermite_imp(unsigned n, T x)\n{\n   T p0 = 1;\n   T p1 = 2 * x;\n\n   if(n == 0)\n      return p0;\n\n   unsigned c = 1;\n\n   while(c < n)\n   {\n      std::swap(p0, p1);\n      p1 = hermite_next(c, x, p0, p1);\n      ++c;\n   }\n   return p1;\n}\n\n} // namespace detail\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type \n   hermite(unsigned n, T x, const Policy&)\n{\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::hermite_imp(n, static_cast<value_type>(x)), \"boost::math::hermite<%1%>(unsigned, %1%)\");\n}\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type \n   hermite(unsigned n, T x)\n{\n   return boost::math::hermite(n, x, policies::policy<>());\n}\n\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_SPECIAL_HERMITE_HPP\n\n\n\n", "meta": {"hexsha": "dcc352f55f279bbe7fc92af67b6f3b5b88d225e2", "size": 1778, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/special_functions/hermite.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/special_functions/hermite.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/special_functions/hermite.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": 23.0909090909, "max_line_length": 160, "alphanum_fraction": 0.6996625422, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.548605659885266}}
{"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/nearest_cov.h>\n#include <Eigen/Dense>\n\nnamespace mars\n{\nNearestCov::NearestCov(const Eigen::MatrixXd& covariance) : cov_mat_(covariance)\n{\n  // Ensure the matrix is square\n  assert(covariance.rows() == covariance.cols());\n}\n\nEigen::MatrixXd NearestCov::EigenCorrectionUsingCovariance(NearestCovMethod method)\n{\n  Eigen::EigenSolver<Eigen::MatrixXd> vd(cov_mat_);\n\n  Eigen::EigenSolver<Eigen::MatrixXd>::EigenvectorsType V(vd.eigenvectors());\n  Eigen::EigenSolver<Eigen::MatrixXd>::EigenvalueType D(vd.eigenvalues());\n\n  if (!(V.imag().isZero() && D.imag().isZero()))\n  {\n    std::cout << \"Warning: Eigenvalue decomposition has imaginary components\" << std::endl;\n  }\n\n  Eigen::MatrixXd V_real(V.real());\n  Eigen::VectorXd D_real(D.real());\n\n  // determine if the matrix is already positive-semi-definite\n  bool no_negative_eigenvalues = true;\n  for (int k = 0; k < D_real.size(); k++)\n  {\n    if (D_real[k] < 0)\n    {\n      no_negative_eigenvalues = false;\n    }\n  }\n\n  if (no_negative_eigenvalues)\n  {\n    return cov_mat_;\n  }\n\n  Eigen::VectorXd D_corrected(D_real);\n\n  // Correct the covariance matrix\n  switch (method)\n  {\n    case NearestCovMethod::abs:\n      // replace negative Eigenvalues with their absolut value\n      for (int k = 0; k < D_corrected.size(); k++)\n      {\n        if (D_corrected[k] < 0)\n        {\n          D_corrected[k] = std::abs(D_corrected[k]);\n        }\n      }\n      break;\n\n    case NearestCovMethod::zero:\n      // replace negative Eigenvalues with zero\n      for (int k = 0; k < D_corrected.size(); k++)\n      {\n        if (D_corrected[k] < 0)\n        {\n          D_corrected[k] = 0.0;\n        }\n      }\n      break;\n\n    case NearestCovMethod::delta:\n      // replace negative Eigenvalues with a positive delta\n      for (int k = 0; k < D_corrected.size(); k++)\n      {\n        if (D_corrected[k] < 0)\n        {\n          D_corrected[k] = delta_;\n        }\n      }\n      break;\n\n    default:\n      std::cout << \"Warning: Unexpected method for nearest_cov\" << std::endl;\n      break;\n  }\n\n  Eigen::MatrixXd result(V_real * D_corrected.asDiagonal() * V_real.inverse());\n  return result;\n}\n\nEigen::MatrixXd NearestCov::EigenCorrectionUsingCorrelation(NearestCovMethod method)\n{\n  // TODO\n  return {};\n}\n}\n", "meta": {"hexsha": "2c46283fa053f86860d8a26ce12e108d7b28b0a3", "size": 2664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/mars/source/nearest_cov.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/nearest_cov.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/nearest_cov.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": 25.3714285714, "max_line_length": 105, "alphanum_fraction": 0.643018018, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.548552904569264}}
{"text": "#include \"ExtendedKalmanFilter4d.h\"\n\n#include <Eigen/Eigenvalues>\n\nExtendedKalmanFilter4d::ExtendedKalmanFilter4d(const Eigen::Vector4d& state, const Eigen::Matrix2d& processNoiseStdSingleDimension, const Eigen::Matrix2d& measurementNoiseCovariances, const Eigen::Matrix2d& initialStateStdSingleDimension):\n    x(state)\n{\n    Eigen::Matrix2d q;\n    q = processNoiseStdSingleDimension.cwiseProduct(processNoiseStdSingleDimension);\n\n    // covariance matrix of process noise (values taken from old kalman filter)\n    Q << q, Eigen::Matrix2d::Zero(), Eigen::Matrix2d::Zero(), q;\n\n    // covariance matrix of measurement noise\n    Eigen::Matrix2d r;\n    R << measurementNoiseCovariances;\n\n    // inital covariance matrix of current state (values taken from old kalman filter)\n    //double p = 62500;\n    Eigen::Matrix2d p;\n    p = initialStateStdSingleDimension.cwiseProduct(initialStateStdSingleDimension);\n    P << p, Eigen::Matrix2d::Zero(), Eigen::Matrix2d::Zero(), p;\n\n    P_pre = P;  // covariance matrix of predicted state\n    P_corr = P; // covariance matrix of corrected state\n\n    x_pre = x;\n    x_corr = x;\n\n    updateEllipses();\n}\n\nExtendedKalmanFilter4d::~ExtendedKalmanFilter4d()\n{\n\n}\n\nvoid ExtendedKalmanFilter4d::predict(const Eigen::Vector2d& u, double dt)\n{\n    // adapt state transition matrix\n    F << 1, dt, 0, 0,\n         0,  1, 0, 0,\n         0,  0, 1, dt,\n         0,  0, 0, 1;\n\n    // adapt control matrix to dt\n    B << dt*dt/2, 0,\n         dt     , 0,\n         0      , dt*dt/2,\n         0      , dt;\n\n    // predict\n    x_pre = F * x + B * u;\n    P_pre = F * P * F.transpose() + Q;\n\n    x = x_pre;\n    P = P_pre;\n\n    updateEllipses();\n}\n\nvoid ExtendedKalmanFilter4d::update(const Eigen::Vector2d& z, const Measurement_Function_H& h)\n{\n    Eigen::Vector2d predicted_measurement;\n\n    predicted_measurement = getStateInMeasurementSpace(h);\n\n    // approximate H with central differential quotient\n    H = approximateH(h);\n\n    Eigen::Matrix2d temp1 = H * P_pre * H.transpose() + R;\n\n    K = P_pre * H.transpose() * temp1.inverse();\n\n    // just for debugging - begin\n    x_pre = x;\n    P_pre = P;\n    // just for debugging - end\n\n    x_corr = x_pre + K * (z - predicted_measurement);\n\n    P_corr = (Eigen::Matrix4d::Identity()-K*H)*P_pre;\n\n    x = x_corr;\n    P = P_corr;\n\n    updateEllipses();\n}\n\nEigen::Matrix<double,2,4> ExtendedKalmanFilter4d::approximateH(const Measurement_Function_H &h) const {\n    double e = 1e-4;\n    Eigen::Vector2d dx1, dx2, dy1, dy2;\n\n    dx1 = h(x(0)-e,x(2));\n    dx2 = h(x(0)+e,x(2));\n\n    dy1 = h(x(0),x(2)-e);\n    dy2 = h(x(0),x(2)+e);\n\n    Eigen::Vector2d dx = (dx2-dx1)/(2*e);\n    Eigen::Vector2d dy = (dy2-dy1)/(2*e);\n\n    Eigen::Matrix<double,2,4> H_approx;\n    H_approx << dx(0), 0, dy(0), 0,\n                dx(1), 0, dy(1), 0;\n\n    return H_approx;\n}\n\n//--- setter ---//\n\nvoid ExtendedKalmanFilter4d::setState(Eigen::Vector4d& state)\n{\n    x = state;\n}\n\nvoid ExtendedKalmanFilter4d::setCovarianceOfProcessNoise(const Eigen::Matrix2d& q){\n    Q << q, Eigen::Matrix2d::Zero(), Eigen::Matrix2d::Zero(), q;\n}\n\nvoid ExtendedKalmanFilter4d::setCovarianceOfState(const Eigen::Matrix4d& p){\n    P << p;\n}\n\nvoid ExtendedKalmanFilter4d::setCovarianceOfMeasurementNoise(const Eigen::Matrix2d& r){\n    R << r;\n}\n\n//--- getter ---//\nEigen::Matrix2d ExtendedKalmanFilter4d::getStateCovarianceInMeasurementSpace(const Measurement_Function_H& h) const // horizontal, vertical\n{\n    Eigen::Matrix<double,2,4> H_approx;\n\n    H_approx = approximateH(h);\n\n    return H_approx * P * H_approx.transpose();\n}\n\nvoid ExtendedKalmanFilter4d::updateEllipses()\n{\n    Eigen::EigenSolver< Eigen::Matrix<double,2,2> > es;\n\n    // determine error ellipse for the location\n    Eigen::Matrix2d loc_cov;\n\n    loc_cov << P(0,0), P(0,2),\n               P(2,0), P(2,2);\n\n    es.compute(loc_cov,true);\n\n    if(std::abs(es.eigenvalues()[0]) > std::abs(es.eigenvalues()[1]))\n    {\n        ellipse_location.minor = std::sqrt(5.99*std::abs(es.eigenvalues()[1]));\n        ellipse_location.major = std::sqrt(5.99*std::abs(es.eigenvalues()[0]));\n        ellipse_location.angle = std::atan2(es.eigenvectors()(1,1).real(),es.eigenvectors()(0,1).real());\n    } else {\n        ellipse_location.minor = std::sqrt(5.99*std::abs(es.eigenvalues()[0]));\n        ellipse_location.major = std::sqrt(5.99*std::abs(es.eigenvalues()[1]));\n        ellipse_location.angle = std::atan2(es.eigenvectors()(1,0).real(),es.eigenvectors()(0,0).real());\n    }\n\n    // determine error ellipse of the velocity\n    Eigen::Matrix2d vol_cov;\n\n    vol_cov << P(1,1), P(1,3),\n               P(3,1), P(3,3);\n\n    es.compute(vol_cov,true);\n\n    if(std::abs(es.eigenvalues()[0]) > std::abs(es.eigenvalues()[1]))\n    {\n        ellipse_velocity.minor = std::sqrt(5.99*std::abs(es.eigenvalues()[1]));\n        ellipse_velocity.major = std::sqrt(5.99*std::abs(es.eigenvalues()[0]));\n        ellipse_velocity.angle = std::atan2(es.eigenvectors()(1,1).real(),es.eigenvectors()(0,1).real());\n    } else {\n        ellipse_velocity.minor = std::sqrt(5.99*std::abs(es.eigenvalues()[0]));\n        ellipse_velocity.major = std::sqrt(5.99*std::abs(es.eigenvalues()[1]));\n        ellipse_velocity.angle = std::atan2(es.eigenvectors()(1,0).real(),es.eigenvectors()(0,0).real());\n    }\n}\n", "meta": {"hexsha": "1bfa817219cc65b695fa3b4e51648b0613ad83d8", "size": 5255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NaoTHSoccer/Source/Tools/Filters/KalmanFilter/ExtendedKalmanFilter4d.cpp", "max_stars_repo_name": "BerlinUnited/NaoTH", "max_stars_repo_head_hexsha": "02848ac10c16a5349f1735da8122a64d601a5c75", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T10:46:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T05:13:14.000Z", "max_issues_repo_path": "NaoTHSoccer/Source/Tools/Filters/KalmanFilter/ExtendedKalmanFilter4d.cpp", "max_issues_repo_name": "BerlinUnited/NaoTH", "max_issues_repo_head_hexsha": "02848ac10c16a5349f1735da8122a64d601a5c75", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-20T21:07:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-22T14:00:28.000Z", "max_forks_repo_path": "NaoTHSoccer/Source/Tools/Filters/KalmanFilter/ExtendedKalmanFilter4d.cpp", "max_forks_repo_name": "BerlinUnited/NaoTH", "max_forks_repo_head_hexsha": "02848ac10c16a5349f1735da8122a64d601a5c75", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-02-07T18:18:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T17:01:41.000Z", "avg_line_length": 29.0331491713, "max_line_length": 239, "alphanum_fraction": 0.6367269267, "num_tokens": 1595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5485421470012666}}
{"text": "// MSVC has a bug where it chokes on complex Eigen expressions\n\n#ifdef _MSC_VER\n#define EIGEN_STRONG_INLINE inline\n#endif\n\n#include \"MidedgeAngleSinFormulation.h\"\n#include \"../GeometryDerivatives.h\"\n#include \"../MeshConnectivity.h\"\n#include <iostream>\n#include <random>\n#include <Eigen/Geometry>\n\n\nstatic double edgeTheta(\n    const MeshConnectivity& mesh,\n    const Eigen::MatrixXd& curPos,\n    int edge,\n    Eigen::Matrix<double, 1, 12>* derivative, // edgeVertex, then edgeOppositeVertex\n    Eigen::Matrix<double, 12, 12>* hessian)\n{\n    if (derivative)\n        derivative->setZero();\n    if (hessian)\n        hessian->setZero();\n    int v0 = mesh.edgeVertex(edge, 0);\n    int v1 = mesh.edgeVertex(edge, 1);\n    int v2 = mesh.edgeOppositeVertex(edge, 0);\n    int v3 = mesh.edgeOppositeVertex(edge, 1);\n    if (v2 == -1 || v3 == -1)\n        return 0; // boundary edge\n\n    Eigen::Vector3d q0 = curPos.row(v0);\n    Eigen::Vector3d q1 = curPos.row(v1);\n    Eigen::Vector3d q2 = curPos.row(v2);\n    Eigen::Vector3d q3 = curPos.row(v3);\n\n    Eigen::Vector3d n0 = (q0 - q2).cross(q1 - q2);\n    Eigen::Vector3d n1 = (q1 - q3).cross(q0 - q3);\n    Eigen::Vector3d axis = q1 - q0;\n    Eigen::Matrix<double, 1, 9> angderiv;\n    Eigen::Matrix<double, 9, 9> anghess;\n\n    double theta = angle(n0, n1, axis, (derivative || hessian) ? &angderiv : NULL, hessian ? &anghess : NULL);\n\n    if (derivative)\n    {\n        derivative->block<1, 3>(0, 0) += angderiv.block<1, 3>(0, 0) * crossMatrix(q2 - q1);\n        derivative->block<1, 3>(0, 3) += angderiv.block<1, 3>(0, 0) * crossMatrix(q0 - q2);\n        derivative->block<1, 3>(0, 6) += angderiv.block<1, 3>(0, 0) * crossMatrix(q1 - q0);\n\n        derivative->block<1, 3>(0, 0) += angderiv.block<1, 3>(0, 3) * crossMatrix(q1 - q3);\n        derivative->block<1, 3>(0, 3) += angderiv.block<1, 3>(0, 3) * crossMatrix(q3 - q0);\n        derivative->block<1, 3>(0, 9) += angderiv.block<1, 3>(0, 3) * crossMatrix(q0 - q1);\n    }\n\n    if (hessian)\n    {\n        Eigen::Matrix3d vqm[3];\n        vqm[0] = crossMatrix(q0 - q2);\n        vqm[1] = crossMatrix(q1 - q0);\n        vqm[2] = crossMatrix(q2 - q1);\n        Eigen::Matrix3d wqm[3];\n        wqm[0] = crossMatrix(q0 - q1);\n        wqm[1] = crossMatrix(q1 - q3);\n        wqm[2] = crossMatrix(q3 - q0);\n\n        int vindices[3] = { 3, 6, 0 };\n        int windices[3] = { 9, 0, 3 };\n\n        for (int i = 0; i < 3; i++)\n        {\n            for (int j = 0; j < 3; j++)\n            {\n                hessian->block<3, 3>(vindices[i], vindices[j]) += vqm[i].transpose() * anghess.block<3, 3>(0, 0) * vqm[j];\n                hessian->block<3, 3>(vindices[i], windices[j]) += vqm[i].transpose() * anghess.block<3, 3>(0, 3) * wqm[j];\n                hessian->block<3, 3>(windices[i], vindices[j]) += wqm[i].transpose() * anghess.block<3, 3>(3, 0) * vqm[j];\n                hessian->block<3, 3>(windices[i], windices[j]) += wqm[i].transpose() * anghess.block<3, 3>(3, 3) * wqm[j];\n            }\n\n            hessian->block<3, 3>(vindices[i], 3) += vqm[i].transpose() * anghess.block<3, 3>(0, 6);\n            hessian->block<3, 3>(3, vindices[i]) += anghess.block<3, 3>(6, 0) * vqm[i];\n            hessian->block<3, 3>(vindices[i], 0) += -vqm[i].transpose() * anghess.block<3, 3>(0, 6);\n            hessian->block<3, 3>(0, vindices[i]) += -anghess.block<3, 3>(6, 0) * vqm[i];\n\n            hessian->block<3, 3>(windices[i], 3) += wqm[i].transpose() * anghess.block<3, 3>(3, 6);\n            hessian->block<3, 3>(3, windices[i]) += anghess.block<3, 3>(6, 3) * wqm[i];\n            hessian->block<3, 3>(windices[i], 0) += -wqm[i].transpose() * anghess.block<3, 3>(3, 6);\n            hessian->block<3, 3>(0, windices[i]) += -anghess.block<3, 3>(6, 3) * wqm[i];\n\n        }\n\n        Eigen::Vector3d dang1 = angderiv.block<1, 3>(0, 0).transpose();\n        Eigen::Vector3d dang2 = angderiv.block<1, 3>(0, 3).transpose();\n\n        Eigen::Matrix3d dang1mat = crossMatrix(dang1);\n        Eigen::Matrix3d dang2mat = crossMatrix(dang2);\n\n        hessian->block<3, 3>(6, 3) += dang1mat;\n        hessian->block<3, 3>(0, 3) -= dang1mat;\n        hessian->block<3, 3>(0, 6) += dang1mat;\n        hessian->block<3, 3>(3, 0) += dang1mat;\n        hessian->block<3, 3>(3, 6) -= dang1mat;\n        hessian->block<3, 3>(6, 0) -= dang1mat;\n\n        hessian->block<3, 3>(9, 0) += dang2mat;\n        hessian->block<3, 3>(3, 0) -= dang2mat;\n        hessian->block<3, 3>(3, 9) += dang2mat;\n        hessian->block<3, 3>(0, 3) += dang2mat;\n        hessian->block<3, 3>(0, 9) -= dang2mat;\n        hessian->block<3, 3>(9, 3) -= dang2mat;\n    }\n\n    return theta;\n}\n\nstatic Eigen::Vector3d secondFundamentalFormEntries(\n    const MeshConnectivity& mesh,\n    const Eigen::MatrixXd& curPos,\n    const Eigen::VectorXd& edgeThetas,\n    int face,\n    Eigen::Matrix<double, 3, 21>* derivative,\n    std::vector<Eigen::Matrix<double, 21, 21> >* hessian)\n{\n    if (derivative)\n        derivative->setZero();\n    if (hessian)\n    {\n        hessian->resize(3);\n        for (int i = 0; i < 3; i++)\n            (*hessian)[i].setZero();\n    }\n\n    Eigen::Vector3d II;\n    for (int i = 0; i < 3; i++)\n    {\n        Eigen::Matrix<double, 1, 9> hderiv;\n        Eigen::Matrix<double, 9, 9> hhess;\n        double altitude = triangleAltitude(mesh, curPos, face, i, (derivative || hessian) ? &hderiv : NULL, hessian ? &hhess : NULL);\n\n        int edge = mesh.faceEdge(face, i);\n        Eigen::Matrix<double, 1, 12> thetaderiv;\n        Eigen::Matrix<double, 12, 12> thetahess;\n        double theta = edgeTheta(mesh, curPos, edge, (derivative || hessian) ? &thetaderiv : NULL, hessian ? &thetahess : NULL);\n\n        double orient = mesh.faceEdgeOrientation(face, i) == 0 ? 1.0 : -1.0;\n        double alpha = 0.5 * theta + orient * edgeThetas[edge];\n\n        double sinAlpha = sin(alpha);\n        double cosAlpha = cos(alpha);\n\n        II[i] = 2.0 * altitude * sinAlpha;\n\n        if (derivative)\n        {\n            int hv0 = i;\n            int hv1 = (i + 1) % 3;\n            int hv2 = (i + 2) % 3;\n            derivative->block<1, 3>(i, 3 * hv0) += 2.0 * sinAlpha * hderiv.block<1, 3>(0, 0);\n            derivative->block<1, 3>(i, 3 * hv1) += 2.0 * sinAlpha * hderiv.block<1, 3>(0, 3);\n            derivative->block<1, 3>(i, 3 * hv2) += 2.0 * sinAlpha * hderiv.block<1, 3>(0, 6);\n\n            int av0, av1, av2, av3;\n            if (mesh.faceEdgeOrientation(face, i) == 0)\n            {\n                av0 = (i + 1) % 3;\n                av1 = (i + 2) % 3;\n                av2 = i;\n                av3 = 3 + i;\n            }\n            else\n            {\n                av0 = (i + 2) % 3;\n                av1 = (i + 1) % 3;\n                av2 = 3 + i;\n                av3 = i;\n            }\n            derivative->block<1, 3>(i, 3 * av0) += altitude * cosAlpha * thetaderiv.block<1, 3>(0, 0);\n            derivative->block<1, 3>(i, 3 * av1) += altitude * cosAlpha * thetaderiv.block<1, 3>(0, 3);\n            derivative->block<1, 3>(i, 3 * av2) += altitude * cosAlpha * thetaderiv.block<1, 3>(0, 6);\n            derivative->block<1, 3>(i, 3 * av3) += altitude * cosAlpha * thetaderiv.block<1, 3>(0, 9);\n            (*derivative)(i, 18 + i) += 2.0 * altitude * cosAlpha * orient;\n        }\n\n        if (hessian)\n        {\n            int hv[3];\n            hv[0] = i;\n            hv[1] = (i + 1) % 3;\n            hv[2] = (i + 2) % 3;\n            for (int j = 0; j < 3; j++)\n            {\n                for (int k = 0; k < 3; k++)\n                {\n                    (*hessian)[i].block<3, 3>(3 * hv[j], 3 * hv[k]) += 2.0 * sinAlpha * hhess.block<3, 3>(3 * j, 3 * k);\n                }\n            }\n\n            int av[4];\n            if (mesh.faceEdgeOrientation(face, i) == 0)\n            {\n                av[0] = (i + 1) % 3;\n                av[1] = (i + 2) % 3;\n                av[2] = i;\n                av[3] = 3 + i;\n            }\n            else\n            {\n                av[0] = (i + 2) % 3;\n                av[1] = (i + 1) % 3;\n                av[2] = 3 + i;\n                av[3] = i;\n            }\n\n            for (int k = 0; k < 3; k++)\n            {\n                for (int j = 0; j < 4; j++)\n                {\n                    (*hessian)[i].block<3, 3>(3 * av[j], 3 * hv[k]) += cosAlpha * thetaderiv.block<1, 3>(0, 3 * j).transpose() * hderiv.block<1, 3>(0, 3 * k);\n                    (*hessian)[i].block<3, 3>(3 * hv[k], 3 * av[j]) += cosAlpha * hderiv.block<1, 3>(0, 3 * k).transpose() * thetaderiv.block<1, 3>(0, 3 * j);\n                }\n                (*hessian)[i].block<1, 3>(18 + i, 3 * hv[k]) += 2.0 * cosAlpha * orient * hderiv.block<1, 3>(0, 3 * k);\n                (*hessian)[i].block<3, 1>(3 * hv[k], 18 + i) += 2.0 * cosAlpha * orient * hderiv.block<1, 3>(0, 3 * k).transpose();\n            }\n\n            for (int k = 0; k < 4; k++)\n            {\n                for (int j = 0; j < 4; j++)\n                {\n                    (*hessian)[i].block<3, 3>(3 * av[j], 3 * av[k]) += altitude * cosAlpha * thetahess.block<3, 3>(3 * j, 3 * k);\n                    (*hessian)[i].block<3, 3>(3 * av[j], 3 * av[k]) += -0.5 * altitude * sinAlpha * thetaderiv.block<1, 3>(0, 3 * j).transpose() * thetaderiv.block<1, 3>(0, 3 * k);\n                }\n                (*hessian)[i].block<1, 3>(18 + i, 3 * av[k]) += -1.0 * altitude * sinAlpha * orient * thetaderiv.block<1, 3>(0, 3 * k);\n                (*hessian)[i].block<3, 1>(3 * av[k], 18 + i) += -1.0 * altitude * sinAlpha * orient * thetaderiv.block<1, 3>(0, 3 * k).transpose();\n            }\n\n            (*hessian)[i](18 + i, 18 + i) += -2.0 * altitude * sinAlpha;\n        }\n    }\n\n    return II;\n}\n\n\nEigen::Matrix2d MidedgeAngleSinFormulation::secondFundamentalForm(\n    const MeshConnectivity &mesh,\n    const Eigen::MatrixXd &curPos,\n    const Eigen::VectorXd &extraDOFs,\n    int face,\n    Eigen::MatrixXd *derivative, \n    std::vector<Eigen::MatrixXd> *hessian) const\n{\n    if (derivative)\n    {\n        derivative->resize(4, 21);\n        derivative->setZero();\n    }\n    if (hessian)\n    {\n        hessian->resize(4);\n        for (int i = 0; i < 4; i++)\n        {\n            (*hessian)[i].resize(21, 21);\n            (*hessian)[i].setZero();\n        }\n    }\n\n\n    Eigen::Matrix<double, 3, 21> IIderiv;\n    std::vector < Eigen::Matrix<double, 21, 21> > IIhess;\n\n    Eigen::Vector3d II = secondFundamentalFormEntries(mesh, curPos, extraDOFs, face, derivative ? &IIderiv : NULL, hessian ? &IIhess : NULL);\n\n    Eigen::Matrix2d result;\n    result << II[0] + II[1], II[0], II[0], II[0] + II[2];\n\n    if (derivative)\n    {\n        derivative->row(0) += IIderiv.row(0);\n        derivative->row(0) += IIderiv.row(1);\n\n        derivative->row(1) += IIderiv.row(0);\n        derivative->row(2) += IIderiv.row(0);\n\n        derivative->row(3) += IIderiv.row(0);\n        derivative->row(3) += IIderiv.row(2);\n    }\n    if (hessian)\n    {\n        (*hessian)[0] += IIhess[0];\n        (*hessian)[0] += IIhess[1];\n\n        (*hessian)[1] += IIhess[0];\n        (*hessian)[2] += IIhess[0];\n\n        (*hessian)[3] += IIhess[0];\n        (*hessian)[3] += IIhess[2];\n    }\n\n    return result;\n}\n\nstatic void testSecondFundamentalFormEntries(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F)\n{\n    double eps = 1e-6;\n    MeshConnectivity mesh(F);\n    int nfaces = mesh.nFaces();\n    int nedges = mesh.nEdges();\n    Eigen::VectorXd thetas(nedges);\n    thetas.setConstant(0.3);\n    int ntests = 100;\n\n    std::random_device rd;\n    std::mt19937 rng(rd());\n    std::uniform_int_distribution<int> uni(0, nfaces);\n\n    std::cout << \"Testing \" << ntests << \" random faces\" << std::endl;\n\n    for(int i=0; i<ntests; i++)\n    {\n        int face = uni(rng);\n        Eigen::Matrix<double, 3, 21> deriv;\n        std::vector<Eigen::Matrix<double, 21, 21> > hess;\n        Eigen::Vector3d b = secondFundamentalFormEntries(mesh, V, thetas, face, &deriv, &hess);\n\n        for(int j=0; j<3; j++)\n        {\n            for(int k=0; k<3; k++)\n            {\n                Eigen::MatrixXd Vpert(V);\n                Vpert(mesh.faceVertex(face, j), k) += 1e-6;\n                Eigen::Matrix<double, 3, 21> derivpert;\n                Eigen::Vector3d bpert = secondFundamentalFormEntries(mesh, Vpert, thetas, face, &derivpert, NULL);\n                Eigen::Vector3d findiff = (bpert-b)/1e-6;\n                Eigen::Vector3d exact = deriv.col(3*j+k);\n                std::cout << \"q\" << j << \"[\" << k <<\"]: \" << exact.transpose() << \" / \" << findiff.transpose() << std::endl;\n\n                Eigen::Matrix<double, 3, 21> findiffhess = (derivpert-deriv)/1e-6;\n                for(int l=0; l<3; l++)\n                {\n                    std::cout << \" hess[\" << l << \"]: \" << hess[l].col(3*j+k).transpose() << \" / \" << findiffhess.row(l) << std::endl;;\n                }\n            }\n            int edge = mesh.faceEdge(face, j);\n            int ofaceidx = 0;\n            if(mesh.edgeFace(edge, ofaceidx) == face)\n                ofaceidx = 1;\n            if(mesh.edgeFace(edge, ofaceidx) == -1)\n                continue;\n            int pidx = mesh.edgeOppositeVertex(edge, ofaceidx);\n            for(int k=0; k<3; k++)\n            {\n                Eigen::MatrixXd Vpert(V);\n                Vpert(pidx, k) += 1e-6;\n                Eigen::Matrix<double, 3, 21> derivpert;\n                Eigen::Vector3d bpert = secondFundamentalFormEntries(mesh, Vpert, thetas, face, &derivpert, NULL);\n                Eigen::Vector3d findiff = (bpert-b)/1e-6;\n                Eigen::Vector3d exact = deriv.col(9 + 3*j+k);\n                std::cout << \"p\" << j << \"[\" << k <<\"]: \" << exact.transpose() << \" / \" << findiff.transpose() << std::endl;\n\n                Eigen::Matrix<double, 3, 21> findiffhess = (derivpert-deriv)/1e-6;\n                for(int l=0; l<3; l++)\n                {\n                    std::cout << \" hess[\" << l << \"]: \" << hess[l].col(9 + 3*j+k).transpose() << \" / \" << findiffhess.row(l) << std::endl;;\n                }\n            }\n            Eigen::VectorXd thetapert(thetas);\n            thetapert[edge] += 1e-6;\n            Eigen::Matrix<double, 3, 21> derivpert;\n            Eigen::Vector3d bpert = secondFundamentalFormEntries(mesh, V, thetapert, face, &derivpert, NULL);\n            Eigen::Vector3d findiff = (bpert-b)/1e-6;\n            Eigen::Vector3d exact = deriv.col(18+j);\n            std::cout << \"theta[\" << j << \"]: \" << exact.transpose() << \" / \" << findiff.transpose() << std::endl;            \n\n            Eigen::Matrix<double, 3, 21> findiffhess = (derivpert-deriv)/1e-6;\n            for(int l=0; l<3; l++)\n            {\n                std::cout << \" hess[\" << l << \"]: \" << hess[l].col(18 + j).transpose() << \" / \" << findiffhess.row(l) << std::endl;;\n            }\n        }\n    }\n}\n\nstatic void testThetas(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F)\n{\n    double eps = 1e-6;\n    MeshConnectivity mesh(F);\n    int nfaces = mesh.nFaces();\n    int nedges = mesh.nEdges();\n    int ntests = 100;\n\n    std::random_device rd;\n    std::mt19937 rng(rd());\n    std::uniform_int_distribution<int> uni(0, nedges);\n\n    std::cout << \"Testing \" << ntests << \" random edges\" << std::endl;\n\n    for (int i = 0; i < ntests; i++)\n    {\n        int edge = uni(rng);\n        Eigen::Matrix<double, 1, 12> deriv;\n        Eigen::Matrix<double, 12, 12> hess;\n        double theta = edgeTheta(mesh, V, edge, &deriv, &hess);\n\n        int v[2];\n        v[0] = mesh.edgeVertex(edge, 0);\n        v[1] = mesh.edgeVertex(edge, 1);\n\n        int vo[2];\n        vo[0] = mesh.edgeOppositeVertex(edge, 0);\n        vo[1] = mesh.edgeOppositeVertex(edge, 1);\n\n        for (int j = 0; j < 2; j++)\n        {\n            for (int k = 0; k < 3; k++)\n            {\n                Eigen::MatrixXd Vpert(V);\n                Vpert(v[j], k) += 1e-6;\n                Eigen::Matrix<double, 1, 12> derivpert;\n                double thetapert = edgeTheta(mesh, Vpert, edge, &derivpert, NULL);\n                double findiff = (thetapert - theta) / 1e-6;\n                double exact = deriv(0, 3 * j + k);\n                std::cout << \"edgeVert\" << j << \"[\" << k << \"]: \" << exact << \" / \" << findiff << std::endl;\n\n                Eigen::Matrix<double, 1, 12> findiffhess = (derivpert-deriv)/1e-6;\n                std::cout << \" hess: \" << hess.col(3 * j + k).transpose() << \" / \" << findiffhess << std::endl;\n            }\n\n            if (vo[j] != -1)\n            {\n                for (int k = 0; k < 3; k++)\n                {\n                    Eigen::MatrixXd Vpert(V);\n                    Vpert(vo[j], k) += 1e-6;\n                    Eigen::Matrix<double, 1, 12> derivpert;\n                    double thetapert = edgeTheta(mesh, Vpert, edge, &derivpert, NULL);\n                    double findiff = (thetapert - theta) / 1e-6;\n                    double exact = deriv(0, 6 + 3 * j + k);\n                    std::cout << \"edgeOppVert\" << j << \"[\" << k << \"]: \" << exact << \" / \" << findiff << std::endl;\n\n                    Eigen::Matrix<double, 1, 12> findiffhess = (derivpert-deriv)/1e-6;\n                    std::cout << \" hess: \" << hess.col(6 + 3 * j + k).transpose() << \" / \" << findiffhess << std::endl;\n                }\n            }\n        }\n    }\n}\n\nint MidedgeAngleSinFormulation::numExtraDOFs() const\n{\n    return 1;\n}\n\nvoid MidedgeAngleSinFormulation::initializeExtraDOFs(Eigen::VectorXd &extraDOFs, const MeshConnectivity &mesh, const Eigen::MatrixXd &curPos) const\n{\n    extraDOFs.resize(mesh.nEdges());\n    extraDOFs.setZero();\n}\n", "meta": {"hexsha": "6006c4d1c1f53f122d0b8d9cef4269cf22042b86", "size": 17410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SecondFundamentalForm/MidedgeAngleSinFormulation.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": "SecondFundamentalForm/MidedgeAngleSinFormulation.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": "SecondFundamentalForm/MidedgeAngleSinFormulation.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": 37.9302832244, "max_line_length": 180, "alphanum_fraction": 0.4901780586, "num_tokens": 5797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5485421399266481}}
{"text": "#define BOOST_TEST_MODULE \"dsn::parallel_for\"\n\n#include <array>\n#include <chrono>\n#include <cmath>\n#include <iostream>\n\n#include <dsnutil/parallel_for.h>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/unit_test.hpp>\n\nusing Clock = std::chrono::high_resolution_clock;\nusing TimePoint = Clock::time_point;\n\nusing std::chrono::duration_cast;\nusing std::chrono::milliseconds;\n\nBOOST_AUTO_TEST_CASE(parallel_for)\n{\n    static const size_t size{ static_cast<size_t>(1e4) };\n    std::array<double, size> result;\n    std::fill(result.begin(), result.end(), 0.0);\n\n    auto f = [](size_t i) -> double {\n        return std::sin(2.0 * boost::math::constants::pi<double>() / static_cast<double>(i + 1));\n    };\n\n    std::cout << \"launching parallel_for loop for \" << size << \" elements...\" << std::endl;\n    TimePoint parallel_start = Clock::now();\n    dsn::parallel_for(size, [&](size_t index) { result[index] = f(index); });\n    TimePoint parallel_end = Clock::now();\n    auto parallel_time = duration_cast<milliseconds>(parallel_end - parallel_start).count();\n    std::cout << \"parallel_for loop execution finished in \" << parallel_time << \"ms\" << std::endl;\n}\n", "meta": {"hexsha": "44d3b870bdfde3a21dfc728e66d13ed2dd87f50a", "size": 1173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/parallel_for.cpp", "max_stars_repo_name": "png85/dsnutil_cpp", "max_stars_repo_head_hexsha": "d577fec7c76949ef87b7a001ac638893ca672781", "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/parallel_for.cpp", "max_issues_repo_name": "png85/dsnutil_cpp", "max_issues_repo_head_hexsha": "d577fec7c76949ef87b7a001ac638893ca672781", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/parallel_for.cpp", "max_forks_repo_name": "png85/dsnutil_cpp", "max_forks_repo_head_hexsha": "d577fec7c76949ef87b7a001ac638893ca672781", "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.5833333333, "max_line_length": 98, "alphanum_fraction": 0.6862745098, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5484516040943589}}
{"text": "#define BOOST_TEST_MODULE \"test_vector\"\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/Vector.hpp>\n\n#include <random>\n#include <cstdint>\n\nconstexpr std::uint32_t seed = 123456789;\nconstexpr std::size_t   N    = 10000;\ntypedef boost::mpl::list<double, float> test_targets;\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(test_vector_construction, Real, test_targets)\n{\n    using namespace mjolnir;\n    using mjolnir::math::X;\n    using mjolnir::math::Y;\n    using mjolnir::math::Z;\n\n    math::Vector<Real, 3> vec(1.0, 2.0, 3.0);\n    BOOST_TEST(X(vec) == 1.0);\n    BOOST_TEST(Y(vec) == 2.0);\n    BOOST_TEST(Z(vec) == 3.0);\n\n    X(vec) = 4.0;\n    Y(vec) = 5.0;\n    Z(vec) = 6.0;\n\n    BOOST_TEST(X(vec) == 4.0);\n    BOOST_TEST(Y(vec) == 5.0);\n    BOOST_TEST(Z(vec) == 6.0);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_vector_add, Real, test_targets)\n{\n    using namespace mjolnir;\n    using mjolnir::math::X;\n    using mjolnir::math::Y;\n    using mjolnir::math::Z;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-100.0, 100.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Vector<Real, 3> lhs(uni(mt), uni(mt), uni(mt)),\n                              rhs(uni(mt), uni(mt), uni(mt));\n        const auto add = lhs + rhs;\n        BOOST_TEST(X(add) == X(lhs) + X(rhs), test::tolerance<Real>());\n        BOOST_TEST(Y(add) == Y(lhs) + Y(rhs), test::tolerance<Real>());\n        BOOST_TEST(Z(add) == Z(lhs) + Z(rhs), test::tolerance<Real>());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_vector_sub, Real, test_targets)\n{\n    using namespace mjolnir;\n    using mjolnir::math::X;\n    using mjolnir::math::Y;\n    using mjolnir::math::Z;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-100.0, 100.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Vector<Real, 3> lhs(uni(mt), uni(mt), uni(mt)),\n                              rhs(uni(mt), uni(mt), uni(mt));\n        const auto sub = lhs - rhs;\n        BOOST_TEST(X(sub) == X(lhs) - X(rhs), test::tolerance<Real>());\n        BOOST_TEST(Y(sub) == Y(lhs) - Y(rhs), test::tolerance<Real>());\n        BOOST_TEST(Z(sub) == Z(lhs) - Z(rhs), test::tolerance<Real>());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_vector_mul, Real, test_targets)\n{\n    using namespace mjolnir;\n    using mjolnir::math::X;\n    using mjolnir::math::Y;\n    using mjolnir::math::Z;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-100.0, 100.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const Real            lhs(uni(mt));\n        const math::Vector<Real, 3> rhs(uni(mt), uni(mt), uni(mt));\n        const auto mul = lhs * rhs;\n        BOOST_TEST(X(mul) == lhs * X(rhs), test::tolerance<Real>());\n        BOOST_TEST(Y(mul) == lhs * Y(rhs), test::tolerance<Real>());\n        BOOST_TEST(Z(mul) == lhs * Z(rhs), test::tolerance<Real>());\n    }\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Vector<Real, 3> lhs(uni(mt), uni(mt), uni(mt));\n        const Real            rhs(uni(mt));\n        const auto mul = lhs * rhs;\n        BOOST_TEST(X(mul) == X(lhs) * rhs, test::tolerance<Real>());\n        BOOST_TEST(Y(mul) == Y(lhs) * rhs, test::tolerance<Real>());\n        BOOST_TEST(Z(mul) == Z(lhs) * rhs, test::tolerance<Real>());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_vector_div, Real, test_targets)\n{\n    using namespace mjolnir;\n    using mjolnir::math::X;\n    using mjolnir::math::Y;\n    using mjolnir::math::Z;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-100.0, 100.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Vector<Real, 3> lhs(uni(mt), uni(mt), uni(mt));\n        const Real            rhs(uni(mt));\n        const auto div = lhs / rhs;\n        BOOST_TEST(X(div) == X(lhs) / rhs, test::tolerance<Real>());\n        BOOST_TEST(Y(div) == Y(lhs) / rhs, test::tolerance<Real>());\n        BOOST_TEST(Z(div) == Z(lhs) / rhs, test::tolerance<Real>());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_vector_dot, Real, test_targets)\n{\n    using namespace mjolnir;\n    using mjolnir::math::X;\n    using mjolnir::math::Y;\n    using mjolnir::math::Z;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-1.0, 1.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Vector<Real, 3> lhs(uni(mt), uni(mt), uni(mt));\n        const math::Vector<Real, 3> rhs(uni(mt), uni(mt), uni(mt));\n        const Real dot = math::dot_product(lhs, rhs);\n        BOOST_TEST(dot == X(lhs) * X(rhs) + Y(lhs) * Y(rhs) + Z(lhs) * Z(rhs),\n                   test::tolerance<Real>());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_vector_len, Real, test_targets)\n{\n    using namespace mjolnir;\n    using mjolnir::math::X;\n    using mjolnir::math::Y;\n    using mjolnir::math::Z;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-1.0, 1.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Vector<Real, 3> lhs(uni(mt), uni(mt), uni(mt));\n        const Real dot   = math::dot_product(lhs, lhs);\n        const Real lensq = math::length_sq(lhs);\n        const Real len   = math::length(lhs);\n        BOOST_TEST(lensq == dot, test::tolerance<Real>());\n\n        BOOST_TEST(lensq == dot,            test::tolerance<Real>());\n        BOOST_TEST(len   == std::sqrt(dot), test::tolerance<Real>());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_vector_rlen, Real, test_targets)\n{\n    using namespace mjolnir;\n    using mjolnir::math::X;\n    using mjolnir::math::Y;\n    using mjolnir::math::Z;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-1.0, 1.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Vector<Real, 3> lhs(uni(mt), uni(mt), uni(mt));\n        const Real len  = math::length(lhs);\n        const Real rlen = math::rlength(lhs);\n        BOOST_TEST(rlen * len == Real(1.0), test::tolerance<Real>());\n        BOOST_TEST(rlen == Real(1) / len,   test::tolerance<Real>());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_vector_cross_product, Real, test_targets)\n{\n    using namespace mjolnir;\n    using mjolnir::math::X;\n    using mjolnir::math::Y;\n    using mjolnir::math::Z;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-1.0, 1.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Vector<Real, 3> lhs(uni(mt), uni(mt), uni(mt));\n        const math::Vector<Real, 3> rhs(uni(mt), uni(mt), uni(mt));\n        const math::Vector<Real, 3> cross = math::cross_product(lhs, rhs);\n        const Real dotl = math::dot_product(cross, lhs);\n        const Real dotr = math::dot_product(cross, rhs);\n\n        BOOST_TEST(dotl == static_cast<Real>(0.0), test::tolerance<Real>());\n        BOOST_TEST(dotr == static_cast<Real>(0.0), test::tolerance<Real>());\n        const Real lenc = math::length(cross);\n\n        const Real lenl = math::length(lhs);\n        const Real lenr = math::length(rhs);\n        const Real dot  = math::dot_product(lhs, rhs);\n        const Real cost = dot / (lenl * lenr);\n        const Real sint = std::sqrt(1.0 - cost * cost);\n\n        BOOST_TEST(lenc == lenl * lenr * sint, test::tolerance<Real>());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_vector_tensor_product, Real, test_targets)\n{\n    using namespace mjolnir;\n    using mjolnir::math::X;\n    using mjolnir::math::Y;\n    using mjolnir::math::Z;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(0, 1);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Vector<Real, 3> v1(uni(mt), uni(mt), uni(mt));\n        const math::Vector<Real, 3> v2(uni(mt), uni(mt), uni(mt));\n        const math::Vector<Real, 3> v3(uni(mt), uni(mt), uni(mt));\n        const auto t1 = math::tensor_product(v1, v3);\n        const auto t2 = math::tensor_product(v2, v3);\n        const auto t3 = math::tensor_product(v1 + v2, v3);\n\n        static_assert(std::is_same<math::Matrix<Real, 3, 3>,\n                typename std::remove_const<decltype(t1)>::type>::value, \"\");\n\n        for(std::size_t i=0; i<9; ++i)\n        {\n            BOOST_TEST(t1.at(i) + t2.at(i) == t3.at(i), test::tolerance<Real>());\n        }\n        const auto t4 = math::tensor_product(v1, v2);\n        const auto t5 = math::tensor_product(v1, v3);\n        const auto t6 = math::tensor_product(v1, v2 + v3);\n        for(std::size_t i=0; i<9; ++i)\n        {\n            BOOST_TEST(t4.at(i) + t5.at(i) == t6.at(i), test::tolerance<Real>());\n        }\n        const auto t7 = math::tensor_product(2 * v1, v2);\n        for(std::size_t i=0; i<9; ++i)\n        {\n            BOOST_TEST(2 * t4.at(i) == t7.at(i), test::tolerance<Real>());\n        }\n    }\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Vector<Real, 3> v1(uni(mt), uni(mt), uni(mt));\n        const math::Vector<Real, 3> v2(uni(mt), uni(mt), uni(mt));\n        const auto t1 = math::tensor_product(v1, v2);\n        const auto t2 = v1 * math::transpose(v2);\n        for(std::size_t i=0; i<9; ++i)\n        {\n            BOOST_TEST(t1.at(i) == t2.at(i), test::tolerance<Real>());\n        }\n    }\n}\n", "meta": {"hexsha": "c0e3dba0964570c4059ab941c36cd6a132ace04c", "size": 9853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_vector.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_vector.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_vector.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": 33.1750841751, "max_line_length": 82, "alphanum_fraction": 0.6004262661, "num_tokens": 2944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5484516008910588}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2009 Andrea Odetti\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#ifndef quantlib_longstaff_schwartz_multi_path_pricer_hpp\n#define quantlib_longstaff_schwartz_multi_path_pricer_hpp\n\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <ql/math/functional.hpp>\n#include <ql/methods/montecarlo/pathpricer.hpp>\n#include <ql/methods/montecarlo/multipath.hpp>\n#include <ql/methods/montecarlo/lsmbasissystem.hpp>\n#include <ql/experimental/mcbasket/pathpayoff.hpp>\n#include <boost/bind.hpp>\n#include <boost/function.hpp>\n\nnamespace QuantLib {\n\n    //! Longstaff-Schwarz path pricer for early exercise options\n    /*! References:\n\n        Francis Longstaff, Eduardo Schwartz, 2001. Valuing American Options\n        by Simulation: A Simple Least-Squares Approach, The Review of\n        Financial Studies, Volume 14, No. 1, 113-147\n\n        \\ingroup mcarlo\n\n        \\test the correctness of the returned value is tested by\n              reproducing results available in web/literature\n    */\n    class LongstaffSchwartzMultiPathPricer : public PathPricer<MultiPath> {\n      public:\n\n        LongstaffSchwartzMultiPathPricer(\n            const boost::shared_ptr<PathPayoff>& ,\n            const std::vector<Size> &,\n            const std::vector<Handle<YieldTermStructure> > &,\n            const Array &,\n            Size ,\n            LsmBasisSystem::PolynomType );\n\n        Real operator()(const MultiPath& multiPath) const;\n        virtual void calibrate();\n\n      protected:\n        struct PathInfo {\n            PathInfo(Size numberOfTimes);\n\n            Size pathLength() const;\n\n            Array                   payments;\n            Array                   exercises;\n            std::vector<Array>      states;\n        };\n\n        PathInfo transformPath(const MultiPath& path) const;\n\n        bool  calibrationPhase_;\n\n        const boost::shared_ptr<PathPayoff> payoff_;\n\n        boost::scoped_array<Array> coeff_;\n        boost::scoped_array<Real> lowerBounds_;\n\n        const std::vector<Size> timePositions_;\n        const std::vector<Handle<YieldTermStructure> > forwardTermStructures_;\n        const Array dF_;\n\n        mutable std::vector<PathInfo> paths_;\n        const   std::vector<boost::function1<Real, Array> > v_;\n    };\n\n}\n\n\n#endif\n", "meta": {"hexsha": "9ced3e7e6abc12983e67584f83acb2d3217dc327", "size": 2991, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/mcbasket/longstaffschwartzmultipathpricer.hpp", "max_stars_repo_name": "quantosaurosProject/quantLib", "max_stars_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "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": "ql/experimental/mcbasket/longstaffschwartzmultipathpricer.hpp", "max_issues_repo_name": "quantosaurosProject/quantLib", "max_issues_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/mcbasket/longstaffschwartzmultipathpricer.hpp", "max_forks_repo_name": "quantosaurosProject/quantLib", "max_forks_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-29T05:44:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:44:27.000Z", "avg_line_length": 32.5108695652, "max_line_length": 79, "alphanum_fraction": 0.6833834838, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5484104851886754}}
{"text": "#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n\n#include \"LSLOpt/BFGS.hpp\"\n\n#include \"ModelSystem.hpp\"\n\n\nint main(int argc, char* argv[])\n{\n  ModelSystem modelSystem;\n\n  std::cerr << std::setprecision(16);\n\n  double angle_eps = 0.1 * M_PI / 180.0;\n\n  unsigned n_steps = static_cast<unsigned>((2 * M_PI) / angle_eps) + 1;\n\n  for (unsigned i = 0; i < n_steps; ++i) {\n    double angle = angle_eps * i;\n    double x = modelSystem.x0.norm() * std::sin(angle);\n    double y = modelSystem.x0.norm() * std::cos(angle);\n    Eigen::VectorXd x0 = Eigen::VectorXd::Zero(1);\n    x0[0] = angle;\n\n    double val = modelSystem.value(x0);\n\n    std::cerr << angle << \";\" << x << \";\" << y << \";\" << val << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "4e70abf274751f7a2f86479d06f0d6711e59a706", "size": 732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PaperExamples/Plot2d.cpp", "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/Plot2d.cpp", "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/Plot2d.cpp", "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": 21.5294117647, "max_line_length": 74, "alphanum_fraction": 0.6024590164, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5484104788258802}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_CBRT_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_CBRT_HPP\n\n#include <stan/math/prim/scal/fun/boost_policy.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/fun/is_inf.hpp>\n#include <stan/math/prim/scal/fun/is_nan.hpp>\n#include <boost/math/special_functions/cbrt.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Return the cube root of the specified value\n     *\n     * @param[in] x Argument.\n     * @return Cube root of the argument.\n     * @throw std::domain_error If argument is negative.\n     */\n    inline double cbrt(double x) {\n      if (is_nan(x))\n        return NOT_A_NUMBER;\n      if (is_inf(x))\n        return x < 0 ? NEGATIVE_INFTY : INFTY;\n      return boost::math::cbrt(x, boost_policy_t());\n    }\n\n    /**\n     * Integer version of cbrt.\n     *\n     * @param[in] x Argument.\n     * @return Cube root of the argument.\n     * @throw std::domain_error If argument is less than 1.\n     */\n    inline double cbrt(int x) {\n      return cbrt(static_cast<double>(x));\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "0e408817e461212d13cca033998e9bb6f2159f92", "size": 1061, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/fun/cbrt.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/fun/cbrt.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/fun/cbrt.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2619047619, "max_line_length": 59, "alphanum_fraction": 0.6475023563, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5484104734140905}}
{"text": "#include <replay/planar_direction.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <catch2/catch.hpp>\n\nusing namespace replay;\nnamespace\n{\n    constexpr auto pi = boost::math::constants::pi<float>();\n    constexpr auto two_pi = boost::math::constants::two_pi<float>();\n    constexpr auto half_pi = boost::math::constants::half_pi<float>();\n}\n\nTEST_CASE(\"can_move_around_singularities\", \"[planar_direction]\")\n{\n    planar_direction current(-4.32833433f);\n    planar_direction to(1.95485115f);\n\n    auto next = planar_direction::move(current, to, 1000.f);\n    REQUIRE(next == to);\n}\n\nTEST_CASE(\"can_move_toward_a_target\", \"[planar_direction]\")\n{\n    planar_direction current(2.f);\n    planar_direction to(1.f);\n\n    auto next = planar_direction::move(current, to, 0.5f);\n    REQUIRE(next.angle() == 1.5f);\n}\n\nTEST_CASE(\"move_picks_the_shorter_arc\", \"[planar_direction]\")\n{\n    planar_direction current(0.1f);\n    planar_direction to(two_pi - 0.1f);\n    auto next = planar_direction::move(current, to, 0.1f);\n    REQUIRE(next.angle() == 0.f);\n}\n\nTEST_CASE(\"normalizes_high_values_correctly\", \"[planar_direction]\")\n{\n    REQUIRE(planar_direction(boost::math::constants::two_pi<float>()).normalized().angle() == Approx(0.f));\n}\n\nTEST_CASE(\"normalizes_low_values_correctly\", \"[planar_direction]\")\n{\n    REQUIRE(planar_direction(-1.5f * pi).normalized().angle() == Approx(pi * 0.5f));\n}\n\nTEST_CASE(\"can_interpolate_between_positive_values\", \"[planar_direction]\")\n{\n    REQUIRE(lerp(planar_direction(0.f), planar_direction(pi*2.5f), 0.25f).angle() == Approx(pi * 0.125f));\n}", "meta": {"hexsha": "c762abea968898fb3f590a72ef303e10e1b60a65", "size": 1577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/planar_direction.t.cpp", "max_stars_repo_name": "ltjax/replay", "max_stars_repo_head_hexsha": "33680beae225c9c388f33e3f7ffd7e8bae4643e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T19:52:50.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-15T19:52:50.000Z", "max_issues_repo_path": "test/planar_direction.t.cpp", "max_issues_repo_name": "ltjax/replay", "max_issues_repo_head_hexsha": "33680beae225c9c388f33e3f7ffd7e8bae4643e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-12-03T21:53:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-23T02:11:50.000Z", "max_forks_repo_path": "test/planar_direction.t.cpp", "max_forks_repo_name": "ltjax/replay", "max_forks_repo_head_hexsha": "33680beae225c9c388f33e3f7ffd7e8bae4643e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3269230769, "max_line_length": 107, "alphanum_fraction": 0.7102092581, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5484104684778034}}
{"text": "#include \"plane.h\"\n#include <vector>\n#include <math.h>\n#include <Eigen/Dense>\n\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nbool line3d::ClosestPoint(const line3d &L1, const line3d &L2, Vector3d &Result1, Vector3d &Result2)\n{\n\tVector3d NewDir = L1.D.cross(L2.D);\n\tfloat Length = NewDir.norm();\n\tif (Length == 0.0f) {\n\t\treturn false;\n\t}\n\n\tplane P1 = plane::fromPointVectors(L1.P0, NewDir, L1.D);\n\tplane P2 = plane::fromPointVectors(L2.P0, NewDir, L2.D);\n\n\tResult1 = P2.IntersectLine(L1);\n\tResult2 = P1.IntersectLine(L2);\n\treturn true;\n}\n\nfloat line3d::Dist(const line3d &L1, const line3d &L2)\n{\n\tVector3d Cross = L1.D.cross(L2.D);\n\tVector3d v = L2.P0 - L1.P0;\n\n\treturn abs(v.dot(Cross)) / Cross.norm();\n}\n\nfloat line3d::DistSq(const line3d &L1, const line3d &L2)\n{\n\tVector3d Cross = L1.D.cross(L2.D);\n\n\tVector3d v = L2.P0 - L1.P0;\n\tfloat Dot = v.dot(Cross);\n\treturn (Dot * Dot) / Cross.squaredNorm();\n}\n\nfloat line3d::DistToPoint(const Vector3d &P) const\n{\n\tfloat t0 = D.dot(P - P0) / D.dot(D);\n\n\tVector3d v = P0 + t0 * D;\n\n\t// TODO: Replace this with the eigen equivalent\n\tfloat x = P.x() + v.x();\n\tfloat y = P.y() + v.y();\n\tfloat z = P.z() + v.z();\n\n\tfloat distanceLine = sqrt(x*x + y*y + z*z);\n\treturn distanceLine;\n}\n\n//-----------------------------------------------------------------------------\n\nplane::plane()\n{\n\n}\n\nfloat plane::get_x(float y, float z)\n{\n\treturn -(b*y + c*z + d) / a;\n}\n\nfloat plane::get_y(float x, float z)\n{\n\treturn -(a*x + c*z + d) / b;\n}\n\nfloat plane::get_z(float x, float y)\n{\n\treturn -(a*x + b*y + d) / c;\n}\n\nplane::plane(const plane &P)\n{\n\ta = P.a;\n\tb = P.b;\n\tc = P.c;\n\td = P.d;\n}\n\nplane::plane(float _a, float _b, float _c, float _d)\n{\n\ta = _a;\n\tb = _b;\n\tc = _c;\n\td = _d;\n}\n\nplane::plane(const Vector3d &NormalizedNormal, float _d)\n{\n\ta = NormalizedNormal(0);\n\tb = NormalizedNormal(1);\n\tc = NormalizedNormal(2);\n\td = _d;\n}\n\nplane plane::fromPointNormal(const Vector3d &Pt, const Vector3d &Normal)\n{\n\tplane Result;\n\tVector3d NormalizedNormal = Normal;\n\tNormalizedNormal.normalize();\n\n\tResult.a = NormalizedNormal(0);\n\tResult.b = NormalizedNormal(1);\n\tResult.c = NormalizedNormal(2);\n\tResult.d = -Pt.dot(NormalizedNormal);\n\treturn Result;\n}\n\nplane plane::fromPointVectors(const Vector3d &Pt, const Vector3d &V1, const Vector3d &V2)\n{\n\tVector3d Normal = V1.cross(V2);\n\treturn fromPointNormal(Pt, Normal);\n}\n\nplane plane::Normalize()\n{\n\tplane Result;\n\tfloat Distance = sqrtf(a * a + b * b + c * c);\n\tResult.a = a / Distance;\n\tResult.b = b / Distance;\n\tResult.c = c / Distance;\n\tResult.d = d / Distance;\n\treturn Result;\n}\n\nplane plane::fromPoints(const Vector3d &V0, const Vector3d &V1, const Vector3d &V2)\n{\n\tVector3d t0 = V1 - V0;\n\tVector3d t1 = V2 - V0;\n\tVector3d Normal = t0.cross(t1);\n\tNormal.normalize();\n\treturn fromPointNormal(V0, Normal);\n}\n\nVector3d plane::IntersectLine(const line3d &Line) const\n{\n\treturn IntersectLine(Line.P0, Line.P0 + Line.D);\n}\n\nVector3d plane::IntersectLine(const Vector3d &V1, const Vector3d &V2) const\n{\n\tVector3d Diff = V1 - V2;\n\tfloat Denominator = a * Diff(0) + b * Diff(1) + c * Diff(2);\n\tif (Denominator == 0.0f) {\n\t\treturn (V1 + V2) * 0.5f;\n\t}\n\tfloat u = (a * V1(0) + b * V1(1) + c * V1(2) + d) / Denominator;\n\n\treturn (V1 + u * (V2 - V1));\n}\n\nVector3d plane::IntersectLine(const Vector3d &V1, const Vector3d &V2, bool &Hit) const\n{\n\tHit = true;\n\tVector3d Diff = V2 - V1;\n\tfloat denominator = a * Diff(0) + b * Diff(1) + c * Diff(2);\n\tif (denominator == 0) { Hit = false; return V1; }\n\tfloat u = (a * V1(0) + b * V1(1) + c * V1(2) + d) / denominator;\n\n\treturn (V1 + u * (V2 - V1));\n}\n\nfloat plane::IntersectLineRatio(const Vector3d &V1, const Vector3d &V2)\n{\n\tVector3d Diff = V2 - V1;\n\tfloat Denominator = a * Diff(0) + b * Diff(1) + c * Diff(2);\n\tif (Denominator == 0.0f) {\n\t\treturn 0.0f;\n\t}\n\treturn (a * V1(0) + b * V1(1) + c * V1(2) + d) / -Denominator;\n}\n\nfloat plane::signedDistance(const Vector3d &Pt) const\n{\n\treturn (a * Pt(0) + b * Pt(1) + c * Pt(2) + d);\n}\n\nfloat plane::unsignedDistance(const Vector3d &Pt) const\n{\n\treturn abs(a * Pt(0) + b * Pt(1) + c * Pt(2) + d);\n}\n\nVector3d plane::ClosestPoint(const Vector3d &Point)\n{\n\treturn (Point - Normal() * signedDistance(Point));\n}\n\nbool plane::planePlaneIntersection(const plane &P1, const plane &P2, line3d &L)\n{\n\tfloat Denominator = P1.a * P2.b - P1.b * P2.a;\n\tif (Denominator == 0.0f) {\n\t\t// this case should be handled by switching axes...\n\t\treturn false;\n\t}\n\tL.P0 = Vector3d((P2.d * P1.b - P1.d * P2.b) /\n\t\tDenominator, (P1.d * P2.a - P2.d * P1.a) /\n\t\tDenominator, 0.0f);\n\n\tL.D = P1.Normal().cross(P2.Normal());\n\tif (L.D.norm() == 0.0f) {\n\t\treturn false;\n\t}\n\tL.D.normalize();\n\n\treturn true;\n}\n\nfloat plane::Dot(const plane &P, const Vector4d &V)\n{\n\treturn P.a * V(0) + P.b * V(1) + P.c * V(2) + P.d * V(3);\n}\n\nfloat plane::DotCoord(const plane &P, const Vector3d &V)\n{\n\treturn P.a * V(0) + P.b * V(1) + P.c * V(2) + P.d;\n}\n\nfloat plane::DotNormal(const plane &P, const Vector3d &V)\n{\n\treturn P.a * V(0) + P.b * V(1) + P.c * V(2);\n}\n\n", "meta": {"hexsha": "ef2cb18f0bb4e10c5c0c35bfe63bfe38e19d07b4", "size": 4986, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algebra/plane.cpp", "max_stars_repo_name": "earthrover/er_vision_pipeline", "max_stars_repo_head_hexsha": "bdc1cc9e90be4dfaef78253828288e96dbd95cb1", "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/algebra/plane.cpp", "max_issues_repo_name": "earthrover/er_vision_pipeline", "max_issues_repo_head_hexsha": "bdc1cc9e90be4dfaef78253828288e96dbd95cb1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algebra/plane.cpp", "max_forks_repo_name": "earthrover/er_vision_pipeline", "max_forks_repo_head_hexsha": "bdc1cc9e90be4dfaef78253828288e96dbd95cb1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-01-18T15:55:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-01T21:33:52.000Z", "avg_line_length": 21.4913793103, "max_line_length": 99, "alphanum_fraction": 0.6179302046, "num_tokens": 1744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5484104675267977}}
{"text": "#ifndef OBJECT_DETECTION_MSGS_NON_MAXIMUM_SUPPRESSOR_HPP\n#define OBJECT_DETECTION_MSGS_NON_MAXIMUM_SUPPRESSOR_HPP\n\n#include <functional> // for std::greater<>\n#include <iterator>   // for std::advance()\n#include <map>\n#include <string>\n#include <utility> // for std::make_pair()\n#include <vector>\n\n#include <nodelet/nodelet.h>\n#include <object_detection_msgs/Objects.h>\n#include <object_detection_msgs/Points.h>\n#include <object_detection_msgs/cv_conversions.hpp>\n#include <ros/node_handle.h>\n#include <ros/publisher.h>\n#include <ros/subscriber.h>\n\n#include <opencv2/core.hpp>\n#include <opencv2/imgproc.hpp>\n\n#include <boost/foreach.hpp>\n\nnamespace object_detection_msgs {\n\n// calc overlap of 2 contours\nstatic inline double computeOverlap(const std::vector<cv::Point> &a,\n                                    const std::vector<cv::Point> &b) {\n  // rectangle of interest\n  const cv::Rect roi(cv::boundingRect(a) & cv::boundingRect(b));\n  const cv::Point offset(-roi.tl());\n\n  // draw a polygon represented by contour A\n  cv::Mat poly_a(cv::Mat::zeros(roi.size(), CV_8UC1));\n  cv::fillPoly(poly_a, std::vector<std::vector<cv::Point>>(1, a), 1, cv::LINE_8, 1, offset);\n\n  // draw a polygon represented by contour B\n  cv::Mat poly_b(cv::Mat::zeros(roi.size(), CV_8UC1));\n  cv::fillPoly(poly_b, std::vector<std::vector<cv::Point>>(1, b), 1, cv::LINE_8, 1, offset);\n\n  // calc <area of polygon A and B> / <area of polygon A or B>\n  //    (0: no overlap, 1: complete overlap)\n  return static_cast<double>(cv::countNonZero(poly_a & poly_b)) / cv::countNonZero(poly_a | poly_b);\n}\n\n// variant of cv::dnn::NMSBoxes() for general contours\nstatic inline void NMSContours(const std::vector<std::vector<cv::Point>> &contours,\n                               const std::vector<double> &scores, const double score_threshold,\n                               const double nms_threshold, std::vector<int> &indices,\n                               const double eta = 1., const int top_k = 0) {\n  // sort scores (with corresponding indices)\n  typedef std::multimap<double, int, std::greater<double>> ScoreMap;\n  ScoreMap score_map;\n  for (std::size_t i = 0; i < std::min(scores.size(), contours.size()); ++i) {\n    // validate score\n    const double score(scores[i]);\n    if (score < 0. || score < score_threshold || score > 1.) {\n      continue;\n    }\n    // validate contour associated to score\n    if (contours[i].empty()) {\n      continue;\n    }\n    score_map.insert(std::make_pair(score, i));\n  }\n\n  // keep top_k scores if needed.\n  if (top_k > 0 && top_k < score_map.size()) {\n    ScoreMap::iterator erase_begin(score_map.begin());\n    std::advance(erase_begin, top_k);\n    score_map.erase(erase_begin, score_map.end());\n  }\n\n  // do nms.\n  double adaptive_threshold(nms_threshold);\n  indices.clear();\n  BOOST_FOREACH (const ScoreMap::value_type &score_pair, score_map) {\n    const int idx(score_pair.second);\n    bool keep(true);\n    BOOST_FOREACH (const int kept_idx, indices) {\n      if (computeOverlap(contours[idx], contours[kept_idx]) > adaptive_threshold) {\n        keep = false;\n        break;\n      }\n    }\n    if (keep) {\n      indices.push_back(idx);\n      if (eta < 1. && adaptive_threshold > 0.5) {\n        adaptive_threshold *= eta;\n      }\n    }\n  }\n}\n\nclass NonMaximumSuppressor : public nodelet::Nodelet {\npublic:\n  NonMaximumSuppressor() {}\n  virtual ~NonMaximumSuppressor() {}\n\nprivate:\n  virtual void onInit() {\n    ros::NodeHandle &nh(getNodeHandle());\n    ros::NodeHandle &pnh(getPrivateNodeHandle());\n\n    score_threshold_ = pnh.param(\"score_threshold\", 0.4);\n    nms_threshold_ = pnh.param(\"nms_threshold\", 0.5);\n    eta_ = pnh.param(\"eta\", 1.);\n    top_k_ = pnh.param(\"top_k\", 0);\n\n    publisher_ = nh.advertise<Objects>(\"objects_out\", 1, true);\n    subscriber_ = nh.subscribe(\"objects_in\", 1, &NonMaximumSuppressor::suppress, this);\n  }\n\n  void suppress(const ObjectsConstPtr &object_in) {\n    // non maximum suppression\n    std::vector<int> indices;\n    NMSContours(toCvContours(object_in->contours), object_in->probabilities, score_threshold_,\n                nms_threshold_, indices, eta_, top_k_);\n\n    // pick kept objects\n    const ObjectsPtr object_out(new Objects);\n    object_out->header.stamp = object_in->header.stamp;\n    BOOST_FOREACH (const int idx, indices) {\n      object_out->names.push_back(idx < object_in->names.size() ? object_in->names[idx]\n                                                                : std::string(\"\"));\n      object_out->contours.push_back(idx < object_in->contours.size() ? object_in->contours[idx]\n                                                                      : Points());\n      object_out->probabilities.push_back(\n          idx < object_in->probabilities.size() ? object_in->probabilities[idx] : -1.);\n    }\n\n    // publish kept objects\n    publisher_.publish(object_out);\n  }\n\nprivate:\n  double score_threshold_, nms_threshold_, eta_;\n  int top_k_;\n\n  ros::Publisher publisher_;\n  ros::Subscriber subscriber_;\n};\n} // namespace object_detection_msgs\n\n#endif", "meta": {"hexsha": "fb859a56986af67dc5db72c76d77a886179575c8", "size": 5024, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/object_detection_msgs/non_maximum_suppressor.hpp", "max_stars_repo_name": "yoshito-n-students/object_detection_msgs", "max_stars_repo_head_hexsha": "fee93c0bdeb0c27f65ddf025264dc94c439244bf", "max_stars_repo_licenses": ["MIT"], "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/object_detection_msgs/non_maximum_suppressor.hpp", "max_issues_repo_name": "yoshito-n-students/object_detection_msgs", "max_issues_repo_head_hexsha": "fee93c0bdeb0c27f65ddf025264dc94c439244bf", "max_issues_repo_licenses": ["MIT"], "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/object_detection_msgs/non_maximum_suppressor.hpp", "max_forks_repo_name": "yoshito-n-students/object_detection_msgs", "max_forks_repo_head_hexsha": "fee93c0bdeb0c27f65ddf025264dc94c439244bf", "max_forks_repo_licenses": ["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.6482758621, "max_line_length": 100, "alphanum_fraction": 0.6510748408, "num_tokens": 1257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5484104675267977}}
{"text": "#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/quote.hpp>\n#include <boost/mpl/protect.hpp>\n#include <boost/mpl/bind.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <cmath>\n#include <boost/safe_float.hpp>\n#include <boost/safe_float/convenience.hpp>\n#include <boost/safe_float/policy/check_subtraction_overflow.hpp>\n#include <boost/safe_float/policy/check_subtraction_underflow.hpp>\n#include <boost/safe_float/policy/check_subtraction_inexact.hpp>\n#include <boost/safe_float/policy/check_subtraction_invalid_result.hpp>\n\n//types to be tested\nusing test_types=boost::mpl::list<\n    float, double, long double\n>;\n\nusing namespace boost::safe_float;\n\n/**\n  This test suite checks different policies on subtraction operations using default parameters for the other policies.\n  */\nBOOST_AUTO_TEST_SUITE( safe_float_subtraction_test_suite )\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_subtraction_throws_on_overflow, FPT, test_types){\n    // define two FPT numbers suppose to positive overflow\n    FPT a = std::numeric_limits<FPT>::max();\n    FPT b = std::numeric_limits<FPT>::lowest();\n    // check FPT overflows to inf after subtract\n    BOOST_CHECK(std::isinf(a-b));\n\n    // construct safe_float version of the same two numbers\n    safe_float<FPT, policy::check_subtraction_overflow> c(std::numeric_limits<FPT>::max());\n    safe_float<FPT, policy::check_subtraction_overflow> d(std::numeric_limits<FPT>::lowest());\n\n    // check the subtraction throws\n    BOOST_CHECK_THROW(c-d, std::exception);\n\n    // define two FPT numbers suppose to negative overflow\n    FPT e = std::numeric_limits<FPT>::lowest();\n    FPT f = std::numeric_limits<FPT>::max();\n    // check FPT overflows to inf after add\n    BOOST_CHECK(std::isinf(e-f));\n\n    // construct safe_float version of the same two numbers\n    safe_float<FPT, policy::check_subtraction_overflow> g(std::numeric_limits<FPT>::lowest());\n    safe_float<FPT, policy::check_subtraction_overflow> h(std::numeric_limits<FPT>::max());\n\n    // check the subtraction throws\n    BOOST_CHECK_THROW(g-h, std::exception);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_subtraction_inexact_rounding, FPT, test_types){\n    // define two FPT numbers suppose to round the result inexactly\n    FPT a = std::numeric_limits<FPT>::min();\n    FPT b = pow(2, std::numeric_limits<FPT>::digits);\n\n    // check substracting a from b is a new value.\n    BOOST_CHECK(b-a == b);\n\n    // construct safe_float version of the same two numbers\n    safe_float<FPT, policy::check_subtraction_inexact> c(std::numeric_limits<FPT>::min());\n    safe_float<FPT, policy::check_subtraction_inexact> d((FPT)pow(2, std::numeric_limits<FPT>::digits));\n\n    // check the subtraction throws\n    BOOST_CHECK_THROW(d-c, std::exception);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_subtraction_underflow, FPT, test_types){\n    // define two FPT numbers suppose to underflow\n    FPT a, b, c;\n    if (std::is_same<FPT, float>()) {\n        a = 4.01254977e-38f;\n        b = 4.01254949e-38f;\n\n        BOOST_CHECK(std::isnormal(a));\n        BOOST_CHECK(std::isnormal(b));\n\n        //check the subtraction produces an denormal result (considered underflow)\n        c = a - b;\n        BOOST_CHECK( std::fpclassify( c ) == FP_SUBNORMAL ) ;\n\n        // construct safe_float version of the same two numbers\n        safe_float<FPT, policy::check_subtraction_underflow> d(a);\n        safe_float<FPT, policy::check_subtraction_underflow> e(b);\n\n        // check the subtraction throws\n        BOOST_CHECK_THROW(d-e, std::exception);\n    } else if (std::is_same<FPT, double>()) {\n        a =  2.2250738585072019e-308;\n        b =  2.2250738585072014e-308;\n\n        BOOST_CHECK(std::isnormal(a));\n        BOOST_CHECK(std::isnormal(b));\n\n        //check the subtraction produces an denormal result (considered underflow)\n        c = a - b;\n        BOOST_CHECK( std::fpclassify( c ) == FP_SUBNORMAL ) ;\n\n        // construct safe_float version of the same two numbers\n        safe_float<FPT, policy::check_subtraction_underflow> d(a);\n        safe_float<FPT, policy::check_subtraction_underflow> e(b);\n\n        // check the subtraction throws\n        BOOST_CHECK_THROW(d-e, std::exception);\n    } else if (std::is_same<FPT, long double>()) {\n        a = 3.40132972460942461217e-4932l;\n        b = 3.40132972460942461181e-4932l;\n\n        BOOST_CHECK(std::isnormal(a));\n        BOOST_CHECK(std::isnormal(b));\n\n        //check the subtraction produces an denormal result (considered underflow)\n        c = a - b;\n        BOOST_CHECK( std::fpclassify( c ) == FP_SUBNORMAL ) ;\n\n        // construct safe_float version of the same two numbers\n        safe_float<FPT, policy::check_subtraction_underflow> d(a);\n        safe_float<FPT, policy::check_subtraction_underflow> e(b);\n\n        // check the subtraction throws\n        BOOST_CHECK_THROW(d-e, std::exception);\n    } else {\n        BOOST_ERROR(\"underflow test only implemented for double so far\");\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_subtraction_invalid_result, FPT, test_types){\n    // define two FPT numbers suppose to produce a NAN\n    FPT a = std::numeric_limits<FPT>::infinity();\n    FPT b = std::numeric_limits<FPT>::infinity();\n\n    // check adding produced NaN\n    BOOST_CHECK(std::isnan(a-b));\n\n    // construct safe_float version of the same two numbers\n    safe_float<FPT, policy::check_subtraction_invalid_result> c(std::numeric_limits<FPT>::infinity());\n    safe_float<FPT, policy::check_subtraction_invalid_result> d((std::numeric_limits<FPT>::infinity()));\n\n    // check the subtraction throws\n    BOOST_CHECK_THROW(c-d, std::exception);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n", "meta": {"hexsha": "51da2c00335df953a280e64b7ca5d57c5717fd29", "size": 5719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/safe_float_subtraction_test.cpp", "max_stars_repo_name": "aTom3333/safefloat", "max_stars_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-08T01:24:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-08T01:24:16.000Z", "max_issues_repo_path": "test/safe_float_subtraction_test.cpp", "max_issues_repo_name": "aTom3333/safefloat", "max_issues_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "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/safe_float_subtraction_test.cpp", "max_forks_repo_name": "aTom3333/safefloat", "max_forks_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T11:31:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-12T21:55:25.000Z", "avg_line_length": 36.8967741935, "max_line_length": 118, "alphanum_fraction": 0.7043189369, "num_tokens": 1419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5483672870615905}}
{"text": "/**\n * @file mtgp64-calc-poly.cpp\n *\n * @brief calculate characteristic polynomial for 64bit mtgp.\n *\n * @author Mutsuo Saito (Hiroshima University)\n * @author Makoto Matsumoto (Hiroshima University)\n *\n * Copyright (c) 2012 Mutsuo Saito, Makoto Matsumoto, Hiroshima\n * University and University of Tokyo. All rights reserved.\n *\n * The new BSD License is applied to this software, see LICENSE.txt\n */\n#include <stdint.h>\n#include <inttypes.h>\n#include <time.h>\n#include <string.h>\n#include <string>\n#include <errno.h>\n#include <NTL/GF2X.h>\n#include <NTL/vec_GF2.h>\n#include <NTL/GF2XFactoring.h>\n#include \"mtgp64-calc-poly.hpp\"\n#include \"mtgp-calc-jump.hpp\"\n#include \"mtgp64-fast.h\"\n\nusing namespace std;\nusing namespace NTL;\n\n/**\n * calculate the characteristic polynomial for given 64-bit MTGP.\n * MinPolySeq is defined in NTL.\n * @param[out] poly calculated characteristic polynomial.\n * @param[in] mtgp64 generator\n */\nvoid mtgp64_calc_characteristic(GF2X& poly, mtgp64_fast_t * mtgp64)\n{\n    vec_GF2 seq;\n    int mexp = mtgp64->params.mexp;\n    seq.SetLength(2 * mexp);\n    for (int i = 0; i < 2 * mexp; i++) {\n\tseq[i] = mtgp64_genrand_uint64(mtgp64) & 1;\n    }\n    MinPolySeq(poly, seq, mexp);\n}\n\n/**\n * calculate the characteristic polynomial for given 64-bit MTGP.\n * MinPolySeq is defined in NTL.\n * @param[out] str calculated characteristic polynomial in string format.\n * @param[in] mtgp64 generator\n */\nvoid mtgp64_calc_characteristic(string& str, mtgp64_fast_t * mtgp64)\n{\n    GF2X poly;\n    mtgp64_calc_characteristic(poly, mtgp64);\n    polytostring(str, poly);\n}\n\n\n#if defined(MAIN)\n/**\n * main function for executable.\n * @param[in] argc number of arguments.\n * @param[in] argv an array of arguments.\n * @return 0 if normal, other abnormal.\n */\nint main(int argc, char *argv[]) {\n    int mexp;\n    int no;\n    uint32_t seed = 1;\n    mtgp64_params_fast_t *params;\n    mtgp64_fast_t mtgp64;\n    int rc;\n\n    if (argc <= 2) {\n\tprintf(\"%s: mexp no.\\n\", argv[0]);\n\treturn 1;\n    }\n    mexp = strtol(argv[1], NULL, 10);\n    if (errno) {\n\tprintf(\"%s: mexp no.\\n\", argv[0]);\n\treturn 2;\n    }\n    no = strtol(argv[2], NULL, 10);\n    if (errno) {\n\tprintf(\"%s: mexp no.\\n\", argv[0]);\n\treturn 3;\n    }\n    switch (mexp) {\n    case 23209:\n\tparams = mtgp64_params_fast_23209;\n\tbreak;\n    case 44497:\n\tparams = mtgp64_params_fast_44497;\n\tbreak;\n    case 110503:\n\tparams = mtgp64_params_fast_110503;\n\tbreak;\n    default:\n\tprintf(\"%s: mexp no.\\n\", argv[0]);\n\tprintf(\"mexp shuould be 23209, 44497 or 110503\\n\");\n\treturn 4;\n    }\n    if (no >= 128 || no < 0) {\n\tprintf(\"%s: mexp no.\\n\", argv[0]);\n\tprintf(\"no must be between 0 and 127\\n\");\n\treturn 5;\n    }\n    params += no;\n    rc = mtgp64_init(&mtgp64, params, seed);\n    if (rc) {\n\tprintf(\"failure in mtgp64_init\\n\");\n\treturn -1;\n    }\n    mtgp64_print_idstring(&mtgp64, stdout);\n    string s;\n    mtgp64_calc_characteristic(s, &mtgp64);\n    printf(\"%s\\n\", s.c_str());\n    mtgp64_free(&mtgp64);\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "40aa9b7fc432b606bb53b75147952d2596ab7dd2", "size": 2969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mtgp64-calc-poly.cpp", "max_stars_repo_name": "mkt-matsumoto-lab/MTGP", "max_stars_repo_head_hexsha": "9cea3283dc67d9fc6cfc044b7ae38fe9ef32afb3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T06:39:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-10T09:48:37.000Z", "max_issues_repo_path": "mtgp64-calc-poly.cpp", "max_issues_repo_name": "mkt-matsumoto-lab/MTGP", "max_issues_repo_head_hexsha": "9cea3283dc67d9fc6cfc044b7ae38fe9ef32afb3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-10T07:15:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T07:15:53.000Z", "max_forks_repo_path": "mtgp64-calc-poly.cpp", "max_forks_repo_name": "mkt-matsumoto-lab/MTGP", "max_forks_repo_head_hexsha": "9cea3283dc67d9fc6cfc044b7ae38fe9ef32afb3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-27T21:05:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T09:47:58.000Z", "avg_line_length": 23.9435483871, "max_line_length": 73, "alphanum_fraction": 0.6604917481, "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5483672771239165}}
{"text": "//\n// Copyright (c) Leonid Seniukov. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for details.\n//\n\n#include \"relativePoseEstimators/Estimator3Points.h\"\n\n#include <Eigen/Eigen>\n\nnamespace gdr {\n\n    SE3 Estimator3Points::getRt(const Eigen::Matrix4Xd &toBeTransformed3Points,\n                                const Eigen::Matrix4Xd &dest3Points,\n                                const CameraRGBD &cameraIntrToBeTransformed,\n                                const CameraRGBD &cameraIntrDestination) const {\n        int dim = 3;\n        int minNumPoints = 3;\n        int numPoints = toBeTransformed3Points.cols();\n        assert(numPoints == minNumPoints);\n        assert(numPoints == dest3Points.cols());\n\n        Eigen::Matrix4d umeyama3p = umeyama(toBeTransformed3Points.block(0, 0, dim, dim),\n                                            dest3Points.block(0, 0, dim, dim));\n        return SE3(umeyama3p);\n    }\n}", "meta": {"hexsha": "c21a522f556caf3fd0600ee13c36ab2a5fc695fd", "size": 956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/relativePoseEstimators/Estimator3Points.cpp", "max_stars_repo_name": "leoneed03/reconstrutor", "max_stars_repo_head_hexsha": "5e6417ed2b090617202cad1a10010141e4ce6615", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/relativePoseEstimators/Estimator3Points.cpp", "max_issues_repo_name": "leoneed03/reconstrutor", "max_issues_repo_head_hexsha": "5e6417ed2b090617202cad1a10010141e4ce6615", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-21T15:52:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-24T11:34:46.000Z", "max_forks_repo_path": "src/relativePoseEstimators/Estimator3Points.cpp", "max_forks_repo_name": "leoneed03/reconstrutor", "max_forks_repo_head_hexsha": "5e6417ed2b090617202cad1a10010141e4ce6615", "max_forks_repo_licenses": ["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.7692307692, "max_line_length": 89, "alphanum_fraction": 0.6087866109, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5483514075429144}}
{"text": "#include <math.h>\n#include <stdio.h>\n\n#include <boost/math/quaternion.hpp>\n\nstatic double inertia_z = 6.55929728e-05;\nstatic double frequency =3.0;\n\n\nstatic double stiffness= inertia_z * pow(2*M_PI*frequency,2);\nstatic double angle_init = -0.2300258882727588;\n//static double angle_init = -0.8;\n\n\nextern \"C\" void externalForces(double t, double *f, unsigned int size_z, double *z)\n{\n  f[0]=0;\n  f[1]=0;\n  f[2]=-10;\n}\nextern \"C\" void externalMoment(double t,double *m, unsigned int size_z, double *z)\n{\n  m[0]=0;\n  m[1]=0;\n  m[2]=0;\n}\n\nextern \"C\" void internalForces(double t, double *q, double *v, double *f, unsigned int size_z,double *z)\n{\n  // Simple spring in z direction.\n  f[0]=0;\n  f[1]=0;\n  f[2]=0.;\n  // printf(\"internalForcesB1 :\\n\");\n  // printf(\"f[0] = %e\\t f[1] = %e\\t, f[2]=%e\\n\",f[0],f[1],f[2]);\n}\n\nextern \"C\" void internalForcesB1_Jacq(double t, double *q, double *v, double *jac, unsigned int size_z,double *z)\n{\n  for(int i =0; i < 3; i++)\n  {\n    for(int j=0; j<7; j++)\n      jac[i+j*3]=0.0;\n  }\n  jac[2+2*3]=1e4;\n  // printf(\"internalForcesB1_Jacq :\\n\");\n  // printf(\"jac[2+2*3] = %e\\n\", jac[2+2*3]);\n}\n\nextern \"C\" void internalMomentsBalanceWheel(double t, double *q, double *v, double *m, unsigned int size_z,double *z)\n{\n  //  printf(\"internalMomentsB1 :\\n\");\n  // Simple torsional spring around z axis\n  // printf(\"q[3] = %e\\n\", q[3]);\n  // printf(\"q[4] = %e\\n\", q[4]);\n  // printf(\"q[5] = %e\\n\", q[5]);\n  // printf(\"q[6] = %e\\n\", q[6]);\n\n  double angle = 2*asin(q[6]);\n  //printf(\"angle = %e\\n\", angle);\n  //printf(\"stiffness = %e \\n\", stiffness);\n  m[0]=0.0;\n  m[1]=0.;\n  m[2]=stiffness * (angle-angle_init);\n  //printf(\"m[0] = %e\\t m[1] = %e\\t, m[2]=%e\\n\",m[0],m[1],m[2]);\n}\n\nextern \"C\" void internalMomentsBalanceWheel_Jacq(double t, double *q, double *v, double *jac, unsigned int size_z,double *z)\n{\n  //printf(\"internalMomentsB1_Jacq :\\n\");\n  for(int i =0; i < 3; i++)\n  {\n    for(int j=0; j<7; j++)\n      jac[i+j*3]=0.0;\n  }\n  // printf(\"q[3] = %e\\n\", q[3]);\n  // printf(\"q[4] = %e\\n\", q[4]);\n  // printf(\"q[5] = %e\\n\", q[5]);\n  // printf(\"q[6] = %e\\n\", q[6]);\n\n  //double angle = 2*asin(q[6]);\n  // printf(\"angle = %e\\n\", angle);\n  jac[2+6*3]=stiffness * 2.0 / sqrt(1 - q[6]*q[6]) ;\n  // printf(\"jac[3+3*3] = %e\\n\", jac[3+3*3]);\n}\n\nextern \"C\" void externalMomentEscapeWheel(double t,double *m, unsigned int size_z, double *z)\n{\n  m[0]=0;\n  m[1]=0;\n  m[2]=-0.001;\n}\n\n\nextern \"C\" void prescribedvelocityB1(double time, unsigned int sizeofprescribedvelocity, double *pv)\n{\n  /* the plugin implements v(t) = C + A cos(omega *t) */\n\n  double C = -150.0 ;\n  // double omega = M_PI / 2.0;\n  // double A = 10.0;\n\n  //pv[0] =  A * cos(omega * time*100.0);\n  pv[0] =  C;\n  //printf(\"prescribed velocity = %e\\n\", pv[0]);\n}\n", "meta": {"hexsha": "29685318bcd3a16d70b4772e10a7ad8ea80e0ff1", "size": 2745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mechanics/MultiBodySystems/WatchEscapment/Plugin/WatchEscapementPlugin.cpp", "max_stars_repo_name": "vacary/siconos-tutorials", "max_stars_repo_head_hexsha": "93c0158321077a313692ed52fed69ff3c256ae32", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-01-12T23:09:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T17:03:58.000Z", "max_issues_repo_path": "examples/mechanics/MultiBodySystems/WatchEscapment/Plugin/WatchEscapementPlugin.cpp", "max_issues_repo_name": "vacary/siconos-tutorials", "max_issues_repo_head_hexsha": "93c0158321077a313692ed52fed69ff3c256ae32", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T13:44:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-17T13:57:27.000Z", "max_forks_repo_path": "examples/mechanics/MultiBodySystems/WatchEscapment/Plugin/WatchEscapementPlugin.cpp", "max_forks_repo_name": "vacary/siconos-tutorials", "max_forks_repo_head_hexsha": "93c0158321077a313692ed52fed69ff3c256ae32", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-22T13:30:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-06T10:19:57.000Z", "avg_line_length": 25.6542056075, "max_line_length": 124, "alphanum_fraction": 0.5785063752, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5483514034831002}}
{"text": "#ifndef STAN_MATH_FWD_SCAL_FUN_BINOMIAL_COEFFICIENT_LOG_HPP\n#define STAN_MATH_FWD_SCAL_FUN_BINOMIAL_COEFFICIENT_LOG_HPP\n\n#include <stan/math/fwd/meta.hpp>\n#include <stan/math/fwd/core.hpp>\n\n#include <boost/math/special_functions/digamma.hpp>\n#include <stan/math/prim/scal/fun/binomial_coefficient_log.hpp>\n\nnamespace stan {\nnamespace math {\n\ntemplate <typename T>\ninline fvar<T> binomial_coefficient_log(const fvar<T>& x1, const fvar<T>& x2) {\n  using boost::math::digamma;\n  using std::log;\n  const double cutoff = 1000;\n  if ((x1.val_ < cutoff) || (x1.val_ - x2.val_ < cutoff)) {\n    return fvar<T>(binomial_coefficient_log(x1.val_, x2.val_),\n                   x1.d_ * digamma(x1.val_ + 1) - x2.d_ * digamma(x2.val_ + 1)\n                       - (x1.d_ - x2.d_) * digamma(x1.val_ - x2.val_ + 1));\n  } else {\n    return fvar<T>(\n        binomial_coefficient_log(x1.val_, x2.val_),\n        x2.d_ * log(x1.val_ - x2.val_)\n            + x2.val_ * (x1.d_ - x2.d_) / (x1.val_ - x2.val_)\n            + x1.d_ * log(x1.val_ / (x1.val_ - x2.val_))\n            + (x1.val_ + 0.5) / (x1.val_ / (x1.val_ - x2.val_))\n                  * (x1.d_ * (x1.val_ - x2.val_) - (x1.d_ - x2.d_) * x1.val_)\n                  / ((x1.val_ - x2.val_) * (x1.val_ - x2.val_))\n            - x1.d_ / (12.0 * x1.val_ * x1.val_) - x2.d_\n            + (x1.d_ - x2.d_)\n                  / (12.0 * (x1.val_ - x2.val_) * (x1.val_ - x2.val_))\n            - digamma(x2.val_ + 1) * x2.d_);\n  }\n}\n\ntemplate <typename T>\ninline fvar<T> binomial_coefficient_log(const fvar<T>& x1, double x2) {\n  using boost::math::digamma;\n  using std::log;\n  const double cutoff = 1000;\n  if ((x1.val_ < cutoff) || (x1.val_ - x2 < cutoff)) {\n    return fvar<T>(\n        binomial_coefficient_log(x1.val_, x2),\n        x1.d_ * digamma(x1.val_ + 1) - x1.d_ * digamma(x1.val_ - x2 + 1));\n  } else {\n    return fvar<T>(binomial_coefficient_log(x1.val_, x2),\n                   x2 * x1.d_ / (x1.val_ - x2)\n                       + x1.d_ * log(x1.val_ / (x1.val_ - x2))\n                       + (x1.val_ + 0.5) / (x1.val_ / (x1.val_ - x2))\n                             * (x1.d_ * (x1.val_ - x2) - x1.d_ * x1.val_)\n                             / ((x1.val_ - x2) * (x1.val_ - x2))\n                       - x1.d_ / (12.0 * x1.val_ * x1.val_)\n                       + x1.d_ / (12.0 * (x1.val_ - x2) * (x1.val_ - x2)));\n  }\n}\n\ntemplate <typename T>\ninline fvar<T> binomial_coefficient_log(double x1, const fvar<T>& x2) {\n  using boost::math::digamma;\n  using std::log;\n  const double cutoff = 1000;\n  if ((x1 < cutoff) || (x1 - x2.val_ < cutoff)) {\n    return fvar<T>(\n        binomial_coefficient_log(x1, x2.val_),\n        -x2.d_ * digamma(x2.val_ + 1) - x2.d_ * digamma(x1 - x2.val_ + 1));\n  } else {\n    return fvar<T>(binomial_coefficient_log(x1, x2.val_),\n                   x2.d_ * log(x1 - x2.val_) + x2.val_ * -x2.d_ / (x1 - x2.val_)\n                       - x2.d_\n                       - x2.d_ / (12.0 * (x1 - x2.val_) * (x1 - x2.val_))\n                       + x2.d_ * (x1 + 0.5) / (x1 - x2.val_)\n                       - digamma(x2.val_ + 1) * x2.d_);\n  }\n}\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "40c6ea91b6ae84460d2ef24794c2a9be1bc6b4c1", "size": 3149, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/fwd/scal/fun/binomial_coefficient_log.hpp", "max_stars_repo_name": "PhilClemson/math", "max_stars_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T14:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-23T14:57:41.000Z", "max_issues_repo_path": "stan/math/fwd/scal/fun/binomial_coefficient_log.hpp", "max_issues_repo_name": "Capri2014/math", "max_issues_repo_head_hexsha": "d4042bdf8623bba5a1633b557227325a324e32e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-23T19:58:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T12:03:41.000Z", "max_forks_repo_path": "stan/math/fwd/scal/fun/binomial_coefficient_log.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": 39.3625, "max_line_length": 80, "alphanum_fraction": 0.525563671, "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5483514014127693}}
{"text": "\ufeff#include \"STIPNode.h\"\n\n#include <Eigen/Core>\n\n#include <boost/timer.hpp>\n\n#include <iostream>\n#include <numeric>\n\nnamespace nuisken {\nnamespace randomforests {\n\nSTIPNode::MeasureType STIPNode::decideType() {\n    std::uniform_int_distribution<> distribution(0, 1);\n    int typeNumber = distribution(RandomGenerator::getInstance().generator_);\n    switch (typeNumber) {\n        case 0:\n            return CLASS;\n        case 1:\n            return VECTOR;\n        default:\n            return CLASS;\n    }\n}\n\nSTIPSplitParameters STIPNode::generateRandomParameter() {\n    std::uniform_int_distribution<> channelDistribution(0, numberOfFeatureChannels - 1);\n    int featureChannel = channelDistribution(RandomGenerator::getInstance().generator_);\n\n    std::uniform_int_distribution<> indexDistribution(\n            0, numberOfFeatureDimensions.at(featureChannel) - 1);\n    int index1 = indexDistribution(RandomGenerator::getInstance().generator_);\n    // int index2;\n    // do {\n    int index2 = indexDistribution(RandomGenerator::getInstance().generator_);\n    //} while (index1 == index2);\n\n    return STIPSplitParameters(index1, index2, featureChannel);\n}\n\ndouble STIPNode::evaluateSplit(const std::vector<FeatureRawPtr>& leftFeatures,\n                               const std::vector<FeatureRawPtr>& rightFeatures) const {\n    auto leftValue = 0.0;\n    auto rightValue = 0.0;\n\n    switch (type) {\n        case CLASS:\n            leftValue = calculateClassUncertainty(leftFeatures);\n            rightValue = calculateClassUncertainty(rightFeatures);\n            break;\n        case VECTOR:\n            leftValue = calculateVectorUncertainty(leftFeatures);\n            rightValue = calculateVectorUncertainty(rightFeatures);\n            break;\n    }\n\n    return (leftValue + rightValue) / (leftFeatures.size() + rightFeatures.size());\n}\n\ndouble STIPNode::calculateClassUncertainty(const std::vector<FeatureRawPtr>& features) const {\n    //\u5404\u30af\u30e9\u30b9\u306e\u5272\u5408\u3092\u8a08\u7b97\n    Eigen::VectorXd classProbabilities = Eigen::VectorXd::Zero(numberOfClasses);\n    auto oneProbability = 1.0 / features.size();\n    for (const auto& feature : features) {\n        classProbabilities(feature->getClassLabel()) += oneProbability;\n    }\n\n    //\u66d6\u6627\u3055\uff08\u30a8\u30f3\u30c8\u30ed\u30d4\u30fc\uff09\u3092\u8a08\u7b97\n    double uncertainty = 0.0;\n    for (auto i = 0; i < classProbabilities.size(); ++i) {\n        if (0.0 != classProbabilities(i)) {\n            uncertainty += classProbabilities(i) * std::log(classProbabilities(i));\n        }\n    }\n    uncertainty *= static_cast<double>(features.size());\n\n    return uncertainty;\n}\n\ndouble STIPNode::calculateVectorUncertainty(const std::vector<FeatureRawPtr>& features) const {\n    // displacementVector\u306e\u5e73\u5747\u3092\u8a08\u7b97\n    std::vector<cv::Vec3f> meanDisplacementVectors(numberOfClasses);\n    Eigen::VectorXi sizes = Eigen::VectorXi::Zero(numberOfClasses);\n\n    auto end = std::end(features);\n    for (auto itr = std::begin(features); itr != end; ++itr) {\n        auto displacementVector = (*itr)->getDisplacementVector();\n        auto classLabel = (*itr)->getClassLabel();\n\n        meanDisplacementVectors.at(classLabel) += displacementVector;\n\n        ++sizes(classLabel);\n    }\n    for (auto i = 0; i < numberOfClasses; ++i) {\n        meanDisplacementVectors.at(i) /= static_cast<double>(sizes(i));\n    }\n\n    //\u66d6\u6627\u3055\u3092\u8a08\u7b97\n    auto uncertainty = 0.0;\n    for (auto itr = std::begin(features); itr != end; ++itr) {\n        // cv::Vec3i\u3092cv::Vec3f\u306b\u5909\u63db\n        cv::Vec3f displacementVector((*itr)->getDisplacementVector());\n        auto difference = displacementVector - meanDisplacementVectors.at((*itr)->getClassLabel());\n\n        uncertainty += cv::norm(difference);\n    }\n\n    return -uncertainty;\n}\n\nbool STIPNode::decision(const FeatureRawPtr& feature, const STIPSplitParameters& splitParameter,\n                        double tau) const {\n    double value1 = feature->getFeatureValue(splitParameter.getIndex1(),\n                                             splitParameter.getFeatureChannel());\n    double value2 = feature->getFeatureValue(splitParameter.getIndex2(),\n                                             splitParameter.getFeatureChannel());\n\n    if (value1 < (value2 + tau)) {\n        return true;\n    } else {\n        return false;\n    }\n}\n\nstd::shared_ptr<STIPLeaf> STIPNode::calculateLeafData(\n        const std::vector<FeatureRawPtr>& features) const {\n    std::vector<STIPLeaf::FeatureInfo> featureInfo;\n\n    auto end = std::end(features);\n    for (auto itr = std::begin(features); itr != end; ++itr) {\n        featureInfo.emplace_back((*itr)->getIndex(), (*itr)->getClassLabel(),\n                                 (*itr)->getSpatialScale(), (*itr)->getTemporalScale(),\n                                 (*itr)->getDisplacementVector());\n    }\n\n    return std::make_shared<STIPLeaf>(featureInfo);\n}\n\nstd::shared_ptr<STIPLeaf> STIPNode::loadLeafData(std::queue<std::string>& nodeElements) const {\n    auto leaf = std::make_shared<STIPLeaf>();\n    leaf->load(nodeElements);\n\n    return leaf;\n}\n}\n}", "meta": {"hexsha": "f02ee2ec0dad65012940abb82841a703924c2dfb", "size": 4953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/STIPNode.cpp", "max_stars_repo_name": "kenshohara/hough-forests-for-action-detection", "max_stars_repo_head_hexsha": "54067748dc4814fc34f91bcd465edc11089942e9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-01-16T00:46:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T12:08:39.000Z", "max_issues_repo_path": "src/STIPNode.cpp", "max_issues_repo_name": "kenshohara/hough-forests-for-action-detection", "max_issues_repo_head_hexsha": "54067748dc4814fc34f91bcd465edc11089942e9", "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/STIPNode.cpp", "max_forks_repo_name": "kenshohara/hough-forests-for-action-detection", "max_forks_repo_head_hexsha": "54067748dc4814fc34f91bcd465edc11089942e9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-03-03T21:14:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-18T07:23:12.000Z", "avg_line_length": 33.9246575342, "max_line_length": 99, "alphanum_fraction": 0.6470825762, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5483513912632341}}
{"text": "/**\n * @file cv_test.cpp\n *\n * Unit tests for the cross-validation module.\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\n#include <type_traits>\n\n#include <mlpack/core/cv/meta_info_extractor.hpp>\n#include <mlpack/core/cv/metrics/accuracy.hpp>\n#include <mlpack/core/cv/metrics/f1.hpp>\n#include <mlpack/core/cv/metrics/mse.hpp>\n#include <mlpack/core/cv/metrics/precision.hpp>\n#include <mlpack/core/cv/metrics/recall.hpp>\n#include <mlpack/core/cv/simple_cv.hpp>\n#include <mlpack/core/cv/k_fold_cv.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/init_rules/const_init.hpp>\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/loss_functions/mean_squared_error.hpp>\n#include <mlpack/methods/decision_tree/decision_tree.hpp>\n#include <mlpack/methods/decision_tree/information_gain.hpp>\n#include <mlpack/methods/hoeffding_trees/hoeffding_tree.hpp>\n#include <mlpack/methods/lars/lars.hpp>\n#include <mlpack/methods/linear_regression/linear_regression.hpp>\n#include <mlpack/methods/logistic_regression/logistic_regression.hpp>\n#include <mlpack/methods/naive_bayes/naive_bayes_classifier.hpp>\n#include <mlpack/methods/softmax_regression/softmax_regression.hpp>\n#include <mlpack/core/data/confusion_matrix.hpp>\n#include <ensmallen.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"mock_categorical_data.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\nusing namespace mlpack::cv;\nusing namespace mlpack::naive_bayes;\nusing namespace mlpack::regression;\nusing namespace mlpack::tree;\nusing namespace mlpack::data;\n\nBOOST_AUTO_TEST_SUITE(CVTest);\n\n/**\n * Test metrics for binary classification.\n */\nBOOST_AUTO_TEST_CASE(BinaryClassificationMetricsTest)\n{\n  // Using the same data for training and testing.\n  arma::mat data = arma::linspace<arma::rowvec>(1.0, 10.0, 10);\n\n  // Labels that will be considered as \"ground truth\".\n  arma::Row<size_t> labels(\"0 0 1 0 0  1 0 1 0 1\");\n\n  // Labels that make the data linearly separable. These labels will be\n  // predicted in response to the data since we use them for training.\n  arma::Row<size_t> predictedLabels(\"0 0 0 0 0  1 1 1 1 1\");\n\n  LogisticRegression<> lr(data, predictedLabels);\n\n  BOOST_REQUIRE_CLOSE(Accuracy::Evaluate(lr, data, labels), 0.7, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(Precision<Binary>::Evaluate(lr, data, labels), 0.6, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(Recall<Binary>::Evaluate(lr, data, labels), 0.75, 1e-5);\n\n  double f1 = 2 * 0.6 * 0.75 / (0.6 + 0.75);\n  BOOST_REQUIRE_CLOSE(F1<Binary>::Evaluate(lr, data, labels), f1, 1e-5);\n}\n\n/**\n * Test for confusion matrix.\n */\nBOOST_AUTO_TEST_CASE(ConfusionMatrixTest)\n{\n  // Labels that will be considered as \"ground truth\".\n  arma::Row<size_t> labels(\"0 0 1 0 0  1 0 1 0 1\");\n\n  // Predicted labels.\n  arma::Row<size_t> predictedLabels(\"0 0 0 0 0  1 1 1 1 1\");\n  // Confusion matrix.\n  arma::Mat<int> output;\n  data::ConfusionMatrix(predictedLabels, labels, output, 2);\n  BOOST_REQUIRE_EQUAL(output(0, 0), 4);\n  BOOST_REQUIRE_EQUAL(output(0, 1), 1);\n  BOOST_REQUIRE_EQUAL(output(1, 0), 2);\n  BOOST_REQUIRE_EQUAL(output(1, 1), 3);\n}\n\n/**\n * Test metrics for multiclass classification.\n */\nBOOST_AUTO_TEST_CASE(MulticlassClassificationMetricsTest)\n{\n  // Using the same data for training and testing.\n  arma::mat data = arma::linspace<arma::rowvec>(1.0, 12.0, 12);\n\n  // Labels that will be considered as \"ground truth\".\n  arma::Row<size_t> labels(\"0 1  0 1  2 2 1 2  3 3 3 3\");\n\n  // These labels should be predicted in response to the data since we use them\n  // for training.\n  arma::Row<size_t> predictedLabels(\"0 0  1 1  2 2 2 2  3 3 3 3\");\n  size_t numClasses = 4;\n\n  NaiveBayesClassifier<> nb(data, predictedLabels, numClasses);\n\n  // Assert that the Naive Bayes model really predicts the labels above in\n  // response to the data.\n  BOOST_REQUIRE_CLOSE(Accuracy::Evaluate(nb, data, predictedLabels), 1.0, 1e-5);\n\n  double microaveragedPrecision = double(1 + 1 + 3 + 4) / 12;\n  BOOST_REQUIRE_CLOSE(Precision<Micro>::Evaluate(nb, data, labels),\n      microaveragedPrecision, 1e-5);\n\n  double microaveragedRecall = double(1 + 1 + 3 + 4) / 12;\n  BOOST_REQUIRE_CLOSE(Recall<Micro>::Evaluate(nb, data, labels),\n      microaveragedRecall, 1e-5);\n\n  double microaveragedF1 = 2 * microaveragedPrecision * microaveragedRecall /\n    (microaveragedPrecision + microaveragedRecall);\n  BOOST_REQUIRE_CLOSE(F1<Micro>::Evaluate(nb, data, labels),\n      microaveragedF1, 1e-5);\n\n  double macroaveragedPrecision = (0.5 + 0.5 + 0.75 + 1.0) / 4;\n  BOOST_REQUIRE_CLOSE(Precision<Macro>::Evaluate(nb, data, labels),\n      macroaveragedPrecision, 1e-5);\n\n  double macroaveragedRecall = (0.5 + 1.0 / 3 + 1.0 + 1.0) / 4;\n  BOOST_REQUIRE_CLOSE(Recall<Macro>::Evaluate(nb, data, labels),\n      macroaveragedRecall, 1e-5);\n\n  double macroaveragedF1 = (2 * 0.5 * 0.5 / (0.5 + 0.5) +\n      2 * 0.5 * (1.0 / 3) / (0.5 + (1.0 / 3)) + 2 * 0.75 * 1.0 / (0.75 + 1.0) +\n      2 * 1.0 * 1.0 / (1.0 + 1.0)) / 4;\n  BOOST_REQUIRE_CLOSE(F1<Macro>::Evaluate(nb, data, labels),\n      macroaveragedF1, 1e-5);\n}\n\n/**\n * Test the mean squared error.\n */\nBOOST_AUTO_TEST_CASE(MSETest)\n{\n  // Making two points that define the linear function f(x) = x - 1\n  arma::mat trainingData(\"0 1\");\n  arma::rowvec trainingResponses(\"-1 0\");\n\n  LinearRegression lr(trainingData, trainingResponses);\n\n  // Making three responses that differ from the correct ones by 0, 1, and 2\n  // respectively\n  arma::mat data(\"2 3 4\");\n  arma::rowvec responses(\"1 3 5\");\n\n  double expectedMSE = (0 * 0 + 1 * 1 + 2 * 2) / 3.0;\n\n  BOOST_REQUIRE_CLOSE(MSE::Evaluate(lr, data, responses), expectedMSE, 1e-5);\n}\n\n/**\n * Test the mean squared error with matrix responses.\n */\nBOOST_AUTO_TEST_CASE(MSEMatResponsesTest)\n{\n  arma::mat data(\"1 2\");\n  arma::mat trainingResponses(\"1 2; 3 4\");\n\n  FFN<MeanSquaredError<>, ConstInitialization> ffn(MeanSquaredError<>(),\n    ConstInitialization(0));\n  ffn.Add<Linear<>>(1, 2);\n  ffn.Add<IdentityLayer<>>();\n\n  ens::RMSProp opt(0.2);\n  opt.BatchSize() = 1;\n  opt.Shuffle() = false;\n  ffn.Train(data, trainingResponses, opt);\n\n  // Making four responses that differ from the correct ones by 0, 1, 2 and 3\n  // respectively\n  arma::mat responses(\"1 3; 5 7\");\n\n  double expectedMSE = (0 * 0 + 1 * 1 + 2 * 2 + 3 * 3) / 4.0;\n\n  BOOST_REQUIRE_CLOSE(MSE::Evaluate(ffn, data, responses), expectedMSE, 1e-1);\n}\n\ntemplate<typename Class,\n         typename ExpectedPT,\n         typename PassedMT = arma::mat,\n         typename PassedPT = arma::Row<size_t>>\nvoid CheckPredictionsType()\n{\n  using Extractor = MetaInfoExtractor<Class, PassedMT, PassedPT>;\n  using ActualPT = typename Extractor::PredictionsType;\n  static_assert(std::is_same<ExpectedPT, ActualPT>::value,\n      \"Should be the same\");\n}\n\n/**\n * Test MetaInfoExtractor correctly recognizes the type of predictions for a\n * given machine learning algorithm.\n */\nBOOST_AUTO_TEST_CASE(PredictionsTypeTest)\n{\n  CheckPredictionsType<LinearRegression, arma::rowvec>();\n  // CheckPredictionsType<FFN<>, arma::mat>();\n\n  CheckPredictionsType<LogisticRegression<>, arma::Row<size_t>>();\n  CheckPredictionsType<SoftmaxRegression, arma::Row<size_t>>();\n  CheckPredictionsType<HoeffdingTree<>, arma::Row<size_t>, arma::mat>();\n  CheckPredictionsType<HoeffdingTree<>, arma::Row<size_t>, arma::imat>();\n  CheckPredictionsType<DecisionTree<>, arma::Row<size_t>, arma::mat,\n      arma::Row<size_t>>();\n  CheckPredictionsType<DecisionTree<>, arma::Row<char>, arma::mat,\n      arma::Row<char>>();\n}\n\n/**\n * Test MetaInfoExtractor correctly identifies whether a given machine learning\n * algorithm supports weighted learning.\n */\nBOOST_AUTO_TEST_CASE(SupportsWeightsTest)\n{\n  static_assert(MetaInfoExtractor<LinearRegression>::SupportsWeights,\n      \"Value should be true\");\n  static_assert(MetaInfoExtractor<DecisionTree<>>::SupportsWeights,\n      \"Value should be true\");\n  static_assert(MetaInfoExtractor<DecisionTree<>, arma::mat, arma::urowvec,\n      arma::Row<float>>::SupportsWeights, \"Value should be true\");\n\n  static_assert(!MetaInfoExtractor<LARS>::SupportsWeights,\n      \"Value should be false\");\n  static_assert(!MetaInfoExtractor<LogisticRegression<>>::SupportsWeights,\n      \"Value should be false\");\n}\n\ntemplate<typename Class,\n         typename ExpectedWT,\n         typename PassedMT = arma::mat,\n         typename PassedPT = arma::Row<size_t>,\n         typename PassedWT = arma::rowvec>\nvoid CheckWeightsType()\n{\n  using Extractor = MetaInfoExtractor<Class, PassedMT, PassedPT, PassedWT>;\n  using ActualWT = typename Extractor::WeightsType;\n  static_assert(std::is_same<ExpectedWT, ActualWT>::value,\n      \"Should be the same\");\n}\n\n/**\n * Test MetaInfoExtractor correctly recognizes the type of weights for a given\n * machine learning algorithm.\n */\nBOOST_AUTO_TEST_CASE(WeightsTypeTest)\n{\n  CheckWeightsType<LinearRegression, arma::rowvec>();\n  CheckWeightsType<DecisionTree<>, arma::rowvec>();\n  CheckWeightsType<DecisionTree<>, arma::Row<float>, arma::mat,\n      arma::Row<size_t>, arma::Row<float>>();\n}\n\n/**\n * Test MetaInfoExtractor correctly identifies whether a given machine learning\n * algorithm takes a data:DatasetInfo parameter.\n */\nBOOST_AUTO_TEST_CASE(TakesDatasetInfoTest)\n{\n  static_assert(MetaInfoExtractor<DecisionTree<>>::TakesDatasetInfo,\n      \"Value should be true\");\n  static_assert(!MetaInfoExtractor<LinearRegression>::TakesDatasetInfo,\n      \"Value should be false\");\n  static_assert(!MetaInfoExtractor<SoftmaxRegression>::TakesDatasetInfo,\n      \"Value should be false\");\n}\n\n/**\n * Test MetaInfoExtractor correctly identifies whether a given machine learning\n * algorithm takes the numClasses parameter.\n */\nBOOST_AUTO_TEST_CASE(TakesNumClassesTest)\n{\n  static_assert(MetaInfoExtractor<DecisionTree<>>::TakesNumClasses,\n      \"Value should be true\");\n  static_assert(MetaInfoExtractor<SoftmaxRegression>::TakesNumClasses,\n      \"Value should be true\");\n  static_assert(!MetaInfoExtractor<LinearRegression>::TakesNumClasses,\n      \"Value should be false\");\n  static_assert(!MetaInfoExtractor<LARS>::TakesNumClasses,\n      \"Value should be false\");\n}\n\n/**\n * Test the simple cross-validation strategy implementation with the Accuracy\n * metric.\n */\nBOOST_AUTO_TEST_CASE(SimpleCVAccuracyTest)\n{\n  // Using the first half of data for training and the rest for validation.\n  // The validation labels are 75% correct.\n  arma::mat data =\n    arma::mat(\"1 0; 2 0; 1 1; 2 1; 1 0; 2 0; 1 1; 2 1\").t();\n  arma::Row<size_t> labels(\"0 0 1 1 0 1 1 1\");\n\n  SimpleCV<LogisticRegression<>, Accuracy> cv(0.5, data, labels);\n\n  BOOST_REQUIRE_CLOSE(cv.Evaluate(), 0.75, 1e-5);\n}\n\n/**\n * Test the simple cross-validation strategy implementation with the MSE metric.\n */\nBOOST_AUTO_TEST_CASE(SimpleCVMSETest)\n{\n  // Using the first two points for training and remaining three for validation.\n  // See the test MSETest for more explanation.\n  arma::mat data(\"0 1 2 3 4\");\n  arma::rowvec responses(\"-1 0 1 3 5\");\n\n  double expectedMSE = (0 * 0 + 1 * 1 + 2 * 2) / 3.0;\n\n  SimpleCV<LinearRegression, MSE> cv(0.6, data, responses);\n\n  BOOST_REQUIRE_CLOSE(cv.Evaluate(), expectedMSE, 1e-5);\n\n  arma::mat noiseData(\"-1 -2 -3 -4 -5\");\n  arma::rowvec noiseResponses(\"10 20 30 40 50\");\n\n  arma::mat allData = arma::join_rows(noiseData, data);\n  arma::rowvec allResponces = arma::join_rows(noiseResponses, responses);\n\n  arma::rowvec weights = arma::join_rows(arma::zeros(noiseData.n_cols).t(),\n      arma::ones(data.n_cols).t());\n\n  SimpleCV<LinearRegression, MSE> weightedCV(0.3, allData, allResponces,\n      weights);\n\n  BOOST_REQUIRE_CLOSE(weightedCV.Evaluate(), expectedMSE, 1e-5);\n\n  arma::rowvec weights2 = arma::join_rows(arma::zeros(noiseData.n_cols - 1).t(),\n      arma::ones(data.n_cols + 1).t());\n\n  SimpleCV<LinearRegression, MSE> weightedCV2(0.3, allData, allResponces,\n      weights2);\n\n  BOOST_REQUIRE_GT(std::abs(weightedCV2.Evaluate() - expectedMSE), 1e-5);\n}\n\ntemplate<typename... DTArgs>\narma::Row<size_t> PredictLabelsWithDT(const arma::mat& data,\n                                      const DTArgs&... args)\n{\n  DecisionTree<InformationGain> dt(args...);\n  arma::Row<size_t> predictedLabels;\n  dt.Classify(data, predictedLabels);\n  return predictedLabels;\n}\n\n/**\n * Test the simple cross-validation strategy implementation with decision trees\n * constructed in multiple ways.\n */\nBOOST_AUTO_TEST_CASE(SimpleCVWithDTTest)\n{\n  arma::mat data;\n  arma::Row<size_t> labels;\n  data::DatasetInfo datasetInfo;\n  MockCategoricalData(data, labels, datasetInfo);\n\n  arma::mat trainingData = data.cols(0, 1999);\n  arma::mat testData = data.cols(2000, 3999);\n  arma::Row<size_t> trainingLabels = labels.subvec(0, 1999);\n\n  arma::rowvec weights(4000, arma::fill::randu);\n\n  size_t numClasses = 5;\n  size_t minimumLeafSize = 8;\n\n  {\n    arma::Row<size_t> predictedLabels = PredictLabelsWithDT(testData,\n        trainingData, trainingLabels, numClasses, minimumLeafSize);\n    SimpleCV<DecisionTree<InformationGain>, Accuracy> cv(0.5, data,\n        arma::join_rows(trainingLabels, predictedLabels), numClasses);\n    BOOST_REQUIRE_CLOSE(cv.Evaluate(minimumLeafSize), 1.0, 1e-5);\n  }\n  {\n    arma::Row<size_t> predictedLabels = PredictLabelsWithDT(testData,\n        trainingData, datasetInfo, trainingLabels, numClasses, minimumLeafSize);\n    SimpleCV<DecisionTree<InformationGain>, Accuracy> cv(0.5, data, datasetInfo,\n        arma::join_rows(trainingLabels, predictedLabels), numClasses);\n    BOOST_REQUIRE_CLOSE(cv.Evaluate(minimumLeafSize), 1.0, 1e-5);\n  }\n  {\n    arma::Row<size_t> predictedLabels = PredictLabelsWithDT(testData,\n        trainingData, trainingLabels, numClasses, weights, minimumLeafSize);\n    SimpleCV<DecisionTree<InformationGain>, Accuracy> cv(0.5, data,\n        arma::join_rows(trainingLabels, predictedLabels), numClasses, weights);\n    BOOST_REQUIRE_CLOSE(cv.Evaluate(minimumLeafSize), 1.0, 1e-5);\n  }\n  {\n    arma::Row<size_t> predictedLabels = PredictLabelsWithDT(testData,\n        trainingData, datasetInfo, trainingLabels, numClasses, weights,\n        minimumLeafSize);\n    SimpleCV<DecisionTree<InformationGain>, Accuracy> cv(0.5, data, datasetInfo,\n        arma::join_rows(trainingLabels, predictedLabels), numClasses, weights);\n    BOOST_REQUIRE_CLOSE(cv.Evaluate(minimumLeafSize), 1.0, 1e-5);\n  }\n}\n\n/**\n * Test k-fold cross-validation with the MSE metric.\n */\nBOOST_AUTO_TEST_CASE(KFoldCVMSETest)\n{\n  // Defining dataset with two sets of responses for the same two data points.\n  arma::mat data(\"0 1  0 1\");\n  arma::rowvec responses(\"0 1  1 3\");\n\n  // 2-fold cross-validation, no shuffling.\n  KFoldCV<LinearRegression, MSE> cv(2, data, responses, false);\n\n  // In each of two validation tests the MSE value should be the same.\n  double expectedMSE =\n      double((1 - 0) * (1 - 0) + (3 - 1) * (3 - 1)) / 2 * 2 / 2;\n\n  BOOST_REQUIRE_CLOSE(cv.Evaluate(), expectedMSE, 1e-5);\n\n  // Assert we can access a trained model without the exception of\n  // uninitialization.\n  cv.Model();\n}\n\n/**\n * Test k-fold cross-validation with the Accuracy metric.\n */\nBOOST_AUTO_TEST_CASE(KFoldCVAccuracyTest)\n{\n  // Making a 10-points dataset. The last point should be classified wrong when\n  // it is tested separately.\n  arma::mat data(\"0 1 2 3 100 101 102 103 104 5\");\n  arma::Row<size_t> labels(\"0 0 0 0 1 1 1 1 1 1\");\n  size_t numClasses = 2;\n\n  // 10-fold cross-validation, no shuffling.\n  KFoldCV<NaiveBayesClassifier<>, Accuracy> cv(10, data, labels, numClasses,\n      false);\n\n  // We should succeed in classifying separately the first nine samples, and\n  // fail with the remaining one.\n  double expectedAccuracy = (9 * 1.0 + 0.0) / 10;\n\n  BOOST_REQUIRE_CLOSE(cv.Evaluate(), expectedAccuracy, 1e-5);\n\n  // Assert we can access a trained model without the exception of\n  // uninitialization.\n  cv.Model();\n}\n\n/**\n * Test k-fold cross-validation with weighted linear regression.\n */\nBOOST_AUTO_TEST_CASE(KFoldCVWithWeightedLRTest)\n{\n  // Each fold will be filled with this dataset.\n  arma::mat data(\"1 2 3 4\");\n  arma::rowvec responses(\"1 2 30 40\");\n  arma::rowvec weights(\"1 1 0 0\");\n\n  KFoldCV<LinearRegression, MSE> cv(2, arma::join_rows(data, data),\n      arma::join_rows(responses, responses), arma::join_rows(weights, weights),\n      false);\n  cv.Evaluate();\n\n  arma::mat testData(\"3 4\");\n  arma::rowvec testResponses(\"3 4\");\n\n  double mse = MSE::Evaluate(cv.Model(), testData, testResponses);\n\n  BOOST_REQUIRE_CLOSE(1.0 - mse, 1.0, 1e-5);\n}\n\n/**\n * Test k-fold cross-validation with decision trees constructed in multiple\n * ways.\n */\nBOOST_AUTO_TEST_CASE(KFoldCVWithDTTest)\n{\n  arma::mat originalData;\n  arma::Row<size_t> originalLabels;\n  data::DatasetInfo datasetInfo;\n  MockCategoricalData(originalData, originalLabels, datasetInfo);\n\n  // Each fold will be filled with this dataset.\n  arma::mat data = originalData.cols(0, 1199);\n  arma::Row<size_t> labels = originalLabels.cols(0, 1199);\n  arma::rowvec weights(data.n_cols, arma::fill::randu);\n\n  arma::mat doubledData = arma::join_rows(data, data);\n  arma::Row<size_t> doubledLabels = arma::join_rows(labels, labels);\n  arma::rowvec doubledWeights = arma::join_rows(weights, weights);\n\n  size_t numClasses = 5;\n  size_t minimumLeafSize = 8;\n\n  {\n    KFoldCV<DecisionTree<InformationGain>, Accuracy> cv(2, doubledData,\n        doubledLabels, numClasses, false);\n    cv.Evaluate(minimumLeafSize);\n    arma::Row<size_t> predictedLabels = PredictLabelsWithDT(data, data, labels,\n        numClasses, minimumLeafSize);\n    double accuracy = Accuracy::Evaluate(cv.Model(), data, predictedLabels);\n    BOOST_REQUIRE_CLOSE(accuracy, 1.0, 1e-5);\n  }\n  {\n    KFoldCV<DecisionTree<InformationGain>, Accuracy> cv(2, doubledData,\n        datasetInfo, doubledLabels, numClasses, false);\n    cv.Evaluate(minimumLeafSize);\n    arma::Row<size_t> predictedLabels = PredictLabelsWithDT(data, data,\n        datasetInfo, labels, numClasses, minimumLeafSize);\n    double accuracy = Accuracy::Evaluate(cv.Model(), data, predictedLabels);\n    BOOST_REQUIRE_CLOSE(accuracy, 1.0, 1e-5);\n  }\n  {\n    KFoldCV<DecisionTree<InformationGain>, Accuracy> cv(2, doubledData,\n        doubledLabels, numClasses, doubledWeights, false);\n    cv.Evaluate(minimumLeafSize);\n    arma::Row<size_t> predictedLabels = PredictLabelsWithDT(data, data, labels,\n        numClasses, weights, minimumLeafSize);\n    double accuracy = Accuracy::Evaluate(cv.Model(), data, predictedLabels);\n    BOOST_REQUIRE_CLOSE(accuracy, 1.0, 1e-5);\n  }\n  {\n    KFoldCV<DecisionTree<InformationGain>, Accuracy> cv(2, doubledData,\n        datasetInfo, doubledLabels, numClasses, doubledWeights, false);\n    cv.Evaluate(minimumLeafSize);\n    arma::Row<size_t> predictedLabels = PredictLabelsWithDT(data, data,\n        datasetInfo, labels, numClasses, weights, minimumLeafSize);\n    double accuracy = Accuracy::Evaluate(cv.Model(), data, predictedLabels);\n    BOOST_REQUIRE_CLOSE(accuracy, 1.0, 1e-5);\n  }\n}\n\n/**\n * Test k-fold cross-validation with decision trees constructed in multiple\n * ways, but with larger k and no shuffling.\n */\nBOOST_AUTO_TEST_CASE(KFoldCVWithDTTestLargeKNoShuffle)\n{\n  arma::mat data;\n  arma::Row<size_t> labels;\n  data::DatasetInfo datasetInfo;\n  MockCategoricalData(data, labels, datasetInfo);\n\n  size_t numClasses = 5;\n  size_t minimumLeafSize = 5;\n\n  KFoldCV<DecisionTree<InformationGain>, Accuracy> cv(5, data,\n      datasetInfo, labels, numClasses, false);\n  cv.Evaluate(minimumLeafSize);\n  double accuracy = Accuracy::Evaluate(cv.Model(), data, labels);\n\n  // This is a very loose tolerance, but we expect about the same as we would\n  // from an individual decision tree training.\n  BOOST_REQUIRE_GT(accuracy, 0.7);\n}\n\n/**\n * Test k-fold cross-validation with decision trees constructed in multiple\n * ways, but with larger k such that the number of points in each\n * cross-validation bin is not even (the last is smaller), and also with no\n * shuffling.\n */\nBOOST_AUTO_TEST_CASE(KFoldCVWithDTTestUnevenBinsNoShuffle)\n{\n  arma::mat data;\n  arma::Row<size_t> labels;\n  data::DatasetInfo datasetInfo;\n  MockCategoricalData(data, labels, datasetInfo);\n\n  size_t numClasses = 5;\n  size_t minimumLeafSize = 5;\n\n  KFoldCV<DecisionTree<InformationGain>, Accuracy> cv(7, data, datasetInfo,\n      labels, numClasses, false);\n  cv.Evaluate(minimumLeafSize);\n  double accuracy = Accuracy::Evaluate(cv.Model(), data, labels);\n\n  // This is a very loose tolerance, but we expect about the same as we would\n  // from an individual decision tree training.\n  BOOST_REQUIRE_GT(accuracy, 0.7);\n}\n\n/**\n * Test k-fold cross-validation with decision trees constructed in multiple\n * ways, but with larger k.\n */\nBOOST_AUTO_TEST_CASE(KFoldCVWithDTTestLargeK)\n{\n  arma::mat data;\n  arma::Row<size_t> labels;\n  data::DatasetInfo datasetInfo;\n  MockCategoricalData(data, labels, datasetInfo);\n\n  size_t numClasses = 5;\n  size_t minimumLeafSize = 5;\n\n  KFoldCV<DecisionTree<InformationGain>, Accuracy> cv(5, data,\n      datasetInfo, labels, numClasses);\n  cv.Evaluate(minimumLeafSize);\n  double accuracy = Accuracy::Evaluate(cv.Model(), data, labels);\n\n  // This is a very loose tolerance, but we expect about the same as we would\n  // from an individual decision tree training.\n  BOOST_REQUIRE_GT(accuracy, 0.7);\n}\n\n/**\n * Test k-fold cross-validation with decision trees constructed in multiple\n * ways, but with larger k such that the number of points in each\n * cross-validation bin is not even (the last is smaller).\n */\nBOOST_AUTO_TEST_CASE(KFoldCVWithDTTestUnevenBins)\n{\n  arma::mat data;\n  arma::Row<size_t> labels;\n  data::DatasetInfo datasetInfo;\n  MockCategoricalData(data, labels, datasetInfo);\n\n  size_t numClasses = 5;\n  size_t minimumLeafSize = 5;\n\n  KFoldCV<DecisionTree<InformationGain>, Accuracy> cv(7, data, datasetInfo,\n      labels, numClasses);\n  cv.Evaluate(minimumLeafSize);\n  double accuracy = Accuracy::Evaluate(cv.Model(), data, labels);\n\n  // This is a very loose tolerance, but we expect about the same as we would\n  // from an individual decision tree training.\n  BOOST_REQUIRE_GT(accuracy, 0.7);\n}\n\n/**\n * Test k-fold cross-validation with decision trees constructed in multiple\n * ways, but with larger k and weights.\n */\nBOOST_AUTO_TEST_CASE(KFoldCVWithDTTestLargeKWeighted)\n{\n  arma::mat data;\n  arma::Row<size_t> labels;\n  data::DatasetInfo datasetInfo;\n  MockCategoricalData(data, labels, datasetInfo);\n  arma::rowvec weights(data.n_cols, arma::fill::randu);\n\n  size_t numClasses = 5;\n  size_t minimumLeafSize = 5;\n\n  KFoldCV<DecisionTree<InformationGain>, Accuracy> cv(5, data,\n      datasetInfo, labels, numClasses, weights);\n  cv.Evaluate(minimumLeafSize);\n  double accuracy = Accuracy::Evaluate(cv.Model(), data, labels);\n\n  // This is a very loose tolerance, but we expect about the same as we would\n  // from an individual decision tree training.\n  BOOST_REQUIRE_GT(accuracy, 0.7);\n}\n\n/**\n * Test k-fold cross-validation with decision trees constructed in multiple\n * ways, but with larger k such that the number of points in each\n * cross-validation bin is not even (the last is smaller) and weights.\n */\nBOOST_AUTO_TEST_CASE(KFoldCVWithDTTestUnevenBinsWeighted)\n{\n  arma::mat data;\n  arma::Row<size_t> labels;\n  data::DatasetInfo datasetInfo;\n  MockCategoricalData(data, labels, datasetInfo);\n  arma::rowvec weights(data.n_cols, arma::fill::randu);\n\n  size_t numClasses = 5;\n  size_t minimumLeafSize = 5;\n\n  KFoldCV<DecisionTree<InformationGain>, Accuracy> cv(7, data, datasetInfo,\n      labels, numClasses, weights);\n  cv.Evaluate(minimumLeafSize);\n  double accuracy = Accuracy::Evaluate(cv.Model(), data, labels);\n\n  // This is a very loose tolerance, but we expect about the same as we would\n  // from an individual decision tree training.\n  BOOST_REQUIRE_GT(accuracy, 0.7);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b4182ac1fbe2adefb4ba79647d508b6ac26381df", "size": 23891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/cv_test.cpp", "max_stars_repo_name": "tomjpsun/mlpack", "max_stars_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "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": "2020-01-11T14:14:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T14:14:30.000Z", "max_issues_repo_path": "src/mlpack/tests/cv_test.cpp", "max_issues_repo_name": "tomjpsun/mlpack", "max_issues_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "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/cv_test.cpp", "max_forks_repo_name": "tomjpsun/mlpack", "max_forks_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "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": 34.13, "max_line_length": 80, "alphanum_fraction": 0.7197689507, "num_tokens": 6617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5483272315934974}}
{"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_TAN_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_TAN_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing tan capabilities\n\n    tangent of the input in radians.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = tan(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = sin(x)/cos(x);\n    @endcode\n\n    As most other trigonometric function tan can be called with a second optional parameter\n    which is a tag on speed and accuracy (see @ref cos for further details)\n\n    @see tand, tanpi\n\n  **/\n  const boost::dispatch::functor<tag::tan_> tan = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/tan.hpp>\n#include <boost/simd/function/simd/tan.hpp>\n\n#endif\n", "meta": {"hexsha": "4bc7523ecc2d532fbbefc9eaf3739ad5a336baf0", "size": 1241, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/tan.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/tan.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/tan.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": 22.9814814815, "max_line_length": 100, "alphanum_fraction": 0.5906526994, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5483272253683702}}
{"text": "#pragma once\n\n#include <polyfem/ElasticityUtils.hpp>\n#include <polyfem/AutodiffTypes.hpp>\n#include <Eigen/Dense>\n\nnamespace polyfem {\nnamespace autogen {\nvoid linear_elasticity_2d_function(const AutodiffHessianPt &pt, const double lambda, const double mu, Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> &res);\nvoid linear_elasticity_3d_function(const AutodiffHessianPt &pt, const double lambda, const double mu, Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> &res);\n\nvoid hooke_2d_function(const AutodiffHessianPt &pt, const ElasticityTensor &C, Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> &res);\nvoid hooke_3d_function(const AutodiffHessianPt &pt, const ElasticityTensor &C, Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> &res);\n\nvoid saint_venant_2d_function(const AutodiffHessianPt &pt, const ElasticityTensor &C, Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> &res);\nvoid saint_venant_3d_function(const AutodiffHessianPt &pt, const ElasticityTensor &C, Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> &res);\n\nvoid neo_hookean_2d_function(const AutodiffHessianPt &pt, const double lambda, const double mu, Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> &res);\nvoid neo_hookean_3d_function(const AutodiffHessianPt &pt, const double lambda, const double mu, Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> &res);\n\n\n}}\n", "meta": {"hexsha": "548b1bf271b35005a6049004f0b39844307f96a3", "size": 1344, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/autogen/auto_elasticity_rhs.hpp", "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": "src/autogen/auto_elasticity_rhs.hpp", "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": "src/autogen/auto_elasticity_rhs.hpp", "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": 58.4347826087, "max_line_length": 158, "alphanum_fraction": 0.7641369048, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5483272243128304}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n *\n *  This is an example illustrating the use the general purpose non-linear\n *  optimization routines from the dlib C++ Library.\n *\n *  The library provides implementations of many popular algorithms such as L-BFGS\n *  and BOBYQA.  These algorithms allow you to find the minimum or maximum of a\n *  function of many input variables.  This example walks though a few of the ways\n *  you might put these routines to use.\n *\n */\n\n\n#include <iostream>\n#include <dlib/optimization.h>\n#include <dlib/global_optimization.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n#include \"ViennaRNA/utils/basic.h\"\n#ifdef __cplusplus\n}\n#endif\n\n#include \"wrap_dlib.h\"\n\nusing namespace std;\nusing namespace dlib;\n\n// ----------------------------------------------------------------------------------------\n\n// In dlib, most of the general purpose solvers optimize functions that take a\n// column vector as input and return a double.  So here we make a typedef for a\n// variable length column vector of doubles.  This is the type we will use to\n// represent the input to our objective functions which we will be minimizing.\ntypedef matrix<double, 0, 1> column_vector;\n\n/*\n *  function to minimize to obtain equlibrium concentrations\n *  of multistrand systems. We use the transformation\n *\n *  L_a = lambda_a + ln Z_a\n *\n *  such that h(L) reads\n *\n *  h(L) = -\\sum_a (c_a L_a - exp(L_a)) + sum_k K_k exp(sum_b L_b A_{b,k}\n *\n *  with total concentration c_a of strand a, equilibrium constant\n *  K_k of strand k, and membership matrix A[b][k] denoting the number\n *  of strands b in complex k\n *\n *  Note, here we minimize h(L) due to implementation issues whereas\n *  in our publication we've written h'(L) = -h(L) to effectively\n *  maximize the function instead.\n */\nPRIVATE double\nh(const column_vector&  L,\n  const double          *eq_constants,\n  const double          *concentration_strands_tot,\n  const unsigned int    **A,\n  size_t                strands,\n  size_t                complexes)\n{\n  double h, hh, *K, maxK;\n\n  K = (double *)vrna_alloc(sizeof(double) * complexes);\n  h = 0.;\n  maxK = (double)(-INF);\n\n  for (size_t a = 0; a < strands; a++) {\n//    printf(\"L[%u] = %g\\n\", a, L(a));\n    maxK = (maxK < L(a)) ? L(a) : maxK;\n  }\n\n  for (size_t k = 0; k < complexes; k++) {\n    K[k] = log(eq_constants[k]);\n\n    for (size_t a = 0; a < strands; a++) {\n      K[k] += L(a) *\n              (double)A[a][k];\n    }\n\n    maxK = (maxK < K[k]) ? K[k] : maxK;\n  }\n\n  for (size_t a = 0; a < strands; a++)\n    h -= concentration_strands_tot[a] *\n         L(a);\n\n//  printf(\"h = %g\\n\", h);\n  hh = 0;\n\n  for (size_t a = 0; a < strands; a++)\n    hh += exp(L(a) - maxK);\n\n  for (size_t k = 0; k < complexes; k++)\n    hh += exp(K[k] - maxK);\n\n  h += exp(maxK + log(hh));\n//  printf(\"h = %g\\n\", h);\n\n  free(K);\n\n  return h;\n}\n\n\n/*\n *  Get gradient of h(L)\n */\nPRIVATE const column_vector\nh_derivative(const column_vector& L,\n             const double         *eq_constants,\n             const double         *concentration_strands_tot,\n             const unsigned int   **A,\n             size_t               strands,\n             size_t               complexes)\n{\n  double        *K, *maxK;\n  column_vector g(strands);\n\n  K     = (double *)vrna_alloc(sizeof(double) * complexes);\n  maxK  = (double *)vrna_alloc(sizeof(double) * strands);\n\n  for (size_t a = 0; a < strands; a++)\n    maxK[a] = L(a);\n\n  for (size_t k = 0; k < complexes; k++) {\n    K[k] = log(eq_constants[k]);\n    for (size_t a = 0; a < strands; a++)\n      K[k] += L(a) *\n              (double)A[a][k];\n\n    for (size_t a = 0; a < strands; a++)\n      if (A[a][k] > 0)\n        maxK[a] = (maxK[a] < K[k] + log((double)A[a][k])) ?\n                  K[k] + log((double)A[a][k]) :\n                  maxK[a];\n  }\n\n  for (size_t a = 0; a < strands; a++) {\n    g(a) = -concentration_strands_tot[a];\n\n    double hh = exp(L(a) - maxK[a]);\n    for (size_t k = 0; k < complexes; k++)\n      if (A[a][k] > 0)\n        hh += exp(log((double)A[a][k]) +\n                  K[k] -\n                  maxK[a]);\n\n    g(a) += exp(maxK[a] + log(hh));\n//    printf(\"g(%u) = %g\\n\", a, g(a));\n  }\n\n  free(K);\n  free(maxK);\n\n  return g;\n}\n\n\n/*\n *  Get Hessian of h(L)\n */\nPRIVATE matrix<double>\nh_hessian(const column_vector&  L,\n          const double          *eq_constants,\n          const unsigned int    **A,\n          size_t                strands,\n          size_t                complexes)\n{\n  double                  *K, **xs;\n\n  PRIVATE matrix<double>  H(strands, strands);\n\n  K = (double *)vrna_alloc(sizeof(double) * complexes);\n  xs = (double **)vrna_alloc(sizeof(double *) * strands);\n\n  for (size_t a = 0; a < strands; a++) {\n    xs[a] = (double *)vrna_alloc(sizeof(double) * strands);\n    for (size_t b = 0; b < strands; b++)\n      xs[a][b] = (a == b) ? L(a) : (double)(-INF);\n  }\n\n  for (size_t k = 0; k < complexes; k++) {\n    K[k] = log(eq_constants[k]);\n    for (size_t a = 0; a < strands; a++)\n      K[k] += L(a) *\n              (double)A[a][k];\n\n    for (size_t a = 0; a < strands; a++)\n      for (size_t b = 0; b < strands; b++) {\n        if ((A[a][k] > 0) && (A[b][k] > 0))\n          xs[a][b] = (xs[a][b] < K[k] + log((double)A[a][k]) + log((double)A[b][k])) ?\n                      K[k] + log((double)A[a][k]) + log((double)A[b][k]) :\n                      xs[a][b];\n      }\n  }\n\n  for (size_t a = 0; a < strands; a++) {\n    for (size_t b = 0; b < strands; b++) {\n      double hh = (a == b) ? exp(L(a) - xs[a][b]) : 0.;\n\n      for (size_t k = 0; k < complexes; k++)\n        if ((A[a][k] > 0) && (A[b][k] > 0))\n          hh += exp(log((double)A[a][k]) +\n                    log((double)A[b][k]) +\n                    K[k] -\n                    xs[a][b]);\n\n      H(a,b) = exp(xs[a][b] + log(hh));\n//      H(b,a) = H(a,b);\n//      printf(\"H(%u,%u) = %g\\n\", a, b, H(a,b));\n    }\n  }\n\n  free(K);\n  for (size_t a = 0; a < strands; a++)\n    free(xs[a]);\n  free(xs);\n\n  return H;\n}\n\n\nclass h_model\n{\n/*!\n *  This object is a \"function model\" which can be used with the\n *  find_min_trust_region() routine.\n * !*/\n\npublic:\ntypedef ::column_vector column_vector;\ntypedef matrix<double> general_matrix;\n\nconst double *eq_constants;\nconst double *concentration_strands_tot;\nconst unsigned int **A;\nsize_t strands;\nsize_t complexes;\n\ndouble\noperator()(const column_vector& x) const\n{\n  return h(x, eq_constants, concentration_strands_tot, A, strands, complexes);\n}\n\n\nvoid\ninit(const double       *eq_constants,\n     const double       *concentration_strands_tot,\n     const unsigned int **A,\n     size_t             strands,\n     size_t             complexes)\n{\n  this->eq_constants              = eq_constants;\n  this->concentration_strands_tot = concentration_strands_tot;\n  this->A                         = A;\n  this->strands                   = strands;\n  this->complexes                 = complexes;\n}\n\n\nvoid\nget_derivative_and_hessian(const column_vector& x,\n                           column_vector&       der,\n                           general_matrix&      hess) const\n{\n  der   = h_derivative(x, eq_constants, concentration_strands_tot, A, strands, complexes);\n  hess  = h_hessian(x, eq_constants, A, strands, complexes);\n}\n};\n\n\n/*\n *  Get concentrations of single strands from\n *  a given vector L (that minimizes h(L))\n */\nPRIVATE double *\nconc_single_strands(const column_vector&  L,\n                    size_t                strands)\n{\n  double *c = (double *)vrna_alloc(sizeof(double) * strands);\n\n  for (size_t a = 0; a < strands; a++)\n    c[a] = exp(L(a));\n\n  return c;\n}\n\n\n/*\n *  Get concentrations of complexes from\n *  a given vector L (that minimizes h(L))\n */\nPRIVATE double *\nconc_complexes(const column_vector& L,\n               const double         *eq_const,\n               const unsigned int   **A,\n               size_t               strands,\n               size_t               complexes)\n{\n  double *c;\n\n  c = (double *)vrna_alloc(sizeof(double) * complexes);\n\n  for (size_t k = 0; k < complexes; k++) {\n    c[k] = log(eq_const[k]);\n\n    for (size_t a = 0; a < strands; a++)\n      c[k] += (double)A[a][k] * L(a);\n\n    c[k] = exp(c[k]);\n  }\n\n  return c;\n}\n\n\ndouble *\nvrna_equilibrium_conc(const double        *eq_constants,\n                      double              *concentration_strands,\n                      const unsigned int  **A,\n                      size_t              num_strands,\n                      size_t              num_complexes)\n{\n  double        *r = NULL;\n\n  column_vector starting_point;\n\n  h_model       h;\n\n  h.init(eq_constants,\n         concentration_strands,\n         A,\n         num_strands,\n         num_complexes);\n\n  starting_point.set_size(num_strands);\n\n  for (size_t a = 0; a < num_strands; a++)\n    starting_point(a) = 0.;\n\n  find_min_trust_region(objective_delta_stop_strategy(1e-18),\n                        h,\n                        starting_point,\n                        1   // initial trust region radius\n                        );\n\n  double *conc_monomers = conc_single_strands(starting_point, num_strands);\n\n  for (size_t a = 0; a < num_strands; a++)\n    concentration_strands[a] = conc_monomers[a];\n\n  r = conc_complexes(starting_point, eq_constants, A, num_strands, num_complexes);\n\n  free(conc_monomers);\n\n  return r;\n}\n", "meta": {"hexsha": "5ebd84365c2cc70e597c9b9d160b393162a8f483", "size": 9316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ViennaRNA/wrap_dlib.cpp", "max_stars_repo_name": "tsjzz/ViennaRNA", "max_stars_repo_head_hexsha": "f58f58ac6fb3e050f12e69cbbf7f0a95bc625d99", "max_stars_repo_licenses": ["Python-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-02T06:38:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T06:38:05.000Z", "max_issues_repo_path": "src/ViennaRNA/wrap_dlib.cpp", "max_issues_repo_name": "tsjzz/ViennaRNA", "max_issues_repo_head_hexsha": "f58f58ac6fb3e050f12e69cbbf7f0a95bc625d99", "max_issues_repo_licenses": ["Python-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/ViennaRNA/wrap_dlib.cpp", "max_forks_repo_name": "tsjzz/ViennaRNA", "max_forks_repo_head_hexsha": "f58f58ac6fb3e050f12e69cbbf7f0a95bc625d99", "max_forks_repo_licenses": ["Python-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.5934065934, "max_line_length": 91, "alphanum_fraction": 0.5434735938, "num_tokens": 2613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5482889311530774}}
{"text": "/*\n *  Distributed under the MIT License (See accompanying file /LICENSE )\n */\n#include <doctest/doctest.h>  // for ResultBuilder\n\n#include <array>                             // for operator==\n#include <boost/multiprecision/cpp_int.hpp>  // for cpp_int\n#include <ostream>                           // for operator<<\n#include <tuple>                             // for tuple\n#include <type_traits>                       // for move\n\n#include \"projgeom/ck_plane.hpp\"            // for ellck, hyck\n#include \"projgeom/common_concepts.h\"       // for Value_type\n#include \"projgeom/fractions.hpp\"           // for operator*\n#include \"projgeom/persp_plane.hpp\"         // for persp_eucl...\n#include \"projgeom/pg_common.hpp\"           // for cross\n#include \"projgeom/pg_line.hpp\"             // for pg_line\n#include \"projgeom/pg_object.hpp\"           // for operator*\n#include \"projgeom/pg_point.hpp\"            // for pg_point\n#include \"projgeom/proj_plane.hpp\"          // for coincident\n#include \"projgeom/proj_plane_measure.hpp\"  // for x_ratio\n// #include <iostream>\n\nusing namespace fun;\n\nstatic const auto Zero = doctest::Approx(0).epsilon(0.01);\n\n/**\n * @brief\n *\n * @param[in] a\n * @return true\n * @return false\n */\ntemplate <typename T> inline auto ApproxZero(const T& a) -> bool {\n    return a[0] == Zero && a[1] == Zero && a[2] == Zero;\n}\n\ntemplate <typename PG> void chk_ck(const PG& myck) {\n    using P = typename PG::point_t;\n    using K = Value_type<P>;\n\n    auto a1 = P{1, -2, 3};\n    auto a2 = P{4, 0, 6};\n    auto a3 = P{-7, 1, 2};\n    const auto triangle = std::tuple{std::move(a1), std::move(a2), std::move(a3)};\n    const auto trilateral = tri_dual(triangle);\n    const auto& [l1, l2, l3] = trilateral;\n    const auto [t1, t2, t3] = myck.tri_altitude(triangle);\n\n    auto o = myck.orthocenter(triangle);\n    const auto tau = myck.reflect(l1);\n    const auto Q = std::tuple{myck.tri_quadrance(triangle)};\n    const auto S = std::tuple{myck.tri_spread(trilateral)};\n\n    const auto a4 = P{3, 0, 2};\n\n    if constexpr (Integral<K>) {\n        CHECK(incident(l1, a2));\n        CHECK(myck.is_perpendicular(t1, l1));\n        CHECK(coincident(t1 * t2, t3));\n        CHECK(o == t2 * t3);\n        CHECK(a1 == myck.orthocenter(std::tuple{std::move(o), std::move(a2), std::move(a3)}));\n        CHECK(tau(tau(a4)) == a4);\n        // CHECK(myck.spread(l2, l2) == K(0));\n        // CHECK(myck.spread(l3, l3) == K(0));\n        // CHECK(myck.quadrance(a1, a1) == K(0));\n        CHECK(check_sine_law(Q, S));\n        CHECK(check_sine_law(S, Q));\n    } else {\n        CHECK(l1.dot(a2) == Zero);\n        CHECK(l1.dot(myck.perp(t1)) == Zero);\n        CHECK(t1.dot(t2 * t3) == Zero);\n        CHECK(ApproxZero(cross(o, t2 * t3)));\n        const auto o2 = myck.orthocenter(std::tuple{std::move(o), std::move(a2), std::move(a3)});\n        CHECK(ApproxZero(cross(a1, o2)));\n        CHECK(ApproxZero(cross(tau(tau(a4)), a4)));\n        CHECK(myck.measure(l2, l2) == Zero);\n        CHECK(myck.measure(l3, l3) == Zero);\n        CHECK(myck.measure(a1, a1) == Zero);\n        const auto& [q1, q2, q3] = Q;\n        const auto& [s1, s2, s3] = S;\n\n        const auto r1 = q1 * s2 - q2 * s1;\n        const auto r2 = q2 * s3 - q3 * s2;\n        CHECK(r1 == Zero);\n        CHECK(r2 == Zero);\n    }\n}\n\ntemplate <typename P, typename L = typename P::dual>\nrequires Projective_plane_prim<P, L>  // c++20 concept\nstruct myck : ck<P, L, myck> {\n    [[nodiscard]] constexpr auto perp(const P& v) const -> L {\n        return L(-2 * v[0], v[1], -2 * v[2]);\n    }\n\n    [[nodiscard]] constexpr auto perp(const L& v) const -> P { return P(-v[0], 2 * v[1], -v[2]); }\n\n    template <Projective_plane2 _P>\n    [[nodiscard]] constexpr auto measure(const _P& a1, const _P& a2) const {\n        auto x = x_ratio(a1, a2, this->perp(a2), this->perp(a1));\n        // using Q_t = decltype(x);\n        return 1 - x;\n    }\n};\n\nTEST_CASE(\"CK plane chk_ck (int)\") {\n    // using boost::multiprecision::cpp_int;\n    // namespace mp = boost::multiprecision;\n    using boost::multiprecision::cpp_int;\n\n    chk_ck(myck<pg_point<cpp_int>>());\n    chk_ck(myck<pg_line<cpp_int>>());\n    chk_ck(ellck<pg_point<cpp_int>>());\n    chk_ck(ellck<pg_line<cpp_int>>());\n    chk_ck(hyck<pg_point<cpp_int>>());\n    chk_ck(hyck<pg_line<cpp_int>>());\n\n    auto Ire = pg_point<cpp_int>{0, 1, 1};\n    auto Iim = pg_point<cpp_int>{1, 0, 0};\n    auto l_inf = pg_line<cpp_int>{0, -1, 1};\n\n    auto P = persp_euclid_plane{std::move(Ire), std::move(Iim), std::move(l_inf)};\n    chk_ck(P);\n}\n\nTEST_CASE(\"CK plane chk_ck (float)\") {\n    chk_ck(myck<pg_point<double>>());\n    chk_ck(myck<pg_line<double>>());\n    chk_ck(ellck<pg_point<float>>());\n    chk_ck(ellck<pg_line<float>>());\n    chk_ck(hyck<pg_point<double>>());\n    chk_ck(hyck<pg_line<double>>());\n\n    auto Ire = pg_point{0., 1., 1.};\n    auto Iim = pg_point{1., 0., 0.};\n    auto l_inf = pg_line{0., -1., 1.};\n\n    auto P = persp_euclid_plane{std::move(Ire), std::move(Iim), std::move(l_inf)};\n    chk_ck(P);\n}\n", "meta": {"hexsha": "e3abde1fb970646fb29f88bb1e1e9ad0694b0c58", "size": 4993, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/source/test_ck_plane.cpp", "max_stars_repo_name": "luk036/projgeom-cpp", "max_stars_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/source/test_ck_plane.cpp", "max_issues_repo_name": "luk036/projgeom-cpp", "max_issues_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/source/test_ck_plane.cpp", "max_forks_repo_name": "luk036/projgeom-cpp", "max_forks_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9160839161, "max_line_length": 98, "alphanum_fraction": 0.5798117364, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6406358548398979, "lm_q1q2_score": 0.5482889311530773}}
{"text": "#include <iostream>\n#include <complex>\n#include <cstdlib>\n#include <Eigen/Eigen>\n\nint main(int argc, char const *argv[])\n{\n  Eigen::Matrix<float, 2, 2> a = Eigen::Matrix<float, 2, 2>::Zero();\n  a(1,1) = 1;\n  Eigen::Matrix<std::complex<double>, 2, 2> b, c;\n  b << std::complex<double>(), std::complex<double>(1,1), std::complex<double>(2,2), std::complex<double>(3,3);\n  c = a.cast<std::complex<double>>()*b;\n  std::cout << \"a = \" << std::endl << a << std::endl;\n  std::cout << \"b = \" << std::endl << b << std::endl;\n  std::cout << \"c = \" << std::endl << c << std::endl;\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "efec933337593d7f5e80900ed252a90e2331d339", "size": 595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HelloEigen/main.cpp", "max_stars_repo_name": "reinhar2/SamplesWorld", "max_stars_repo_head_hexsha": "e765a2db8569b4cc538d82cb2140e8eb3abc39ec", "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": "HelloEigen/main.cpp", "max_issues_repo_name": "reinhar2/SamplesWorld", "max_issues_repo_head_hexsha": "e765a2db8569b4cc538d82cb2140e8eb3abc39ec", "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": "HelloEigen/main.cpp", "max_forks_repo_name": "reinhar2/SamplesWorld", "max_forks_repo_head_hexsha": "e765a2db8569b4cc538d82cb2140e8eb3abc39ec", "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.0555555556, "max_line_length": 111, "alphanum_fraction": 0.5781512605, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5482889264422112}}
{"text": "#define _USE_MATH_DEFINES\n\n#include <igvc_msgs/velocity_pair.h>\n#include <nav_msgs/Odometry.h>\n#include <nav_msgs/Path.h>\n#include <ros/ros.h>\n#include <tf/transform_datatypes.h>\n#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n#include \"SmoothControl.h\"\n\nros::Publisher cmd_pub;\nros::Publisher target_pub;\nros::Publisher trajectory_pub;\n\nnav_msgs::PathConstPtr path;\n\ndouble lookahead_dist, maximum_vel;\n\nSmoothControl controller;\n\nvoid path_callback(const nav_msgs::PathConstPtr& msg)\n{\n  ROS_INFO(\"Follower got path\");\n  path = msg;\n}\n\ndouble get_distance(double x1, double y1, double x2, double y2)\n{\n  return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));\n}\n\nvoid position_callback(const nav_msgs::OdometryConstPtr& msg)\n{\n  if (path.get() == nullptr)\n  {\n    return;\n  }\n  if (path->poses.empty() || path->poses.size() < 2)\n  {\n    ROS_INFO(\"Path empty.\");\n    igvc_msgs::velocity_pair vel;\n    vel.left_velocity = 0.;\n    vel.right_velocity = 0.;\n    cmd_pub.publish(vel);\n    path.reset();\n    return;\n  }\n\n  float cur_x = msg->pose.pose.position.x;\n  float cur_y = msg->pose.pose.position.y;\n  tf::Quaternion q;\n  tf::quaternionMsgToTF(msg->pose.pose.orientation, q);\n  float cur_theta = tf::getYaw(q);\n\n  float tar_x, tar_y, tar_theta;\n  geometry_msgs::Point end = path->poses[path->poses.size() - 1].pose.position;\n  double path_index = 0;\n  double closest = std::abs(get_distance(cur_x, cur_y, path->poses[0].pose.position.x, path->poses[0].pose.position.y));\n  double temp = std::abs(\n      get_distance(cur_x, cur_y, path->poses[path_index].pose.position.x, path->poses[path_index].pose.position.y));\n  while (path_index < path->poses.size() && temp <= closest)\n  {\n    if (temp < closest)\n    {\n      closest = temp;\n    }\n    path_index++;\n    temp = std::abs(\n        get_distance(cur_x, cur_y, path->poses[path_index].pose.position.x, path->poses[path_index].pose.position.y));\n  }\n\n  if (get_distance(cur_x, cur_y, end.x, end.y) > lookahead_dist)\n  {\n    double distance = 0;\n    bool cont = true;\n    while (cont && path_index < path->poses.size() - 1)\n    {\n      geometry_msgs::Point point1, point2;\n      point1 = path->poses[path_index].pose.position;\n      point2 = path->poses[path_index + 1].pose.position;\n      double increment = get_distance(point1.x, point1.y, point2.x, point2.y);\n      if (distance + increment > lookahead_dist)\n      {\n        cont = false;\n        Eigen::Vector3d first(point1.x, point1.y, 0);\n        Eigen::Vector3d second(point2.x, point2.y, 0);\n        Eigen::Vector3d slope = second - first;\n        // ROS_INFO_STREAM(\"first = \" << first[0] << \", \" << first[1]);\n        // ROS_INFO_STREAM(\"slope = \" << slope[0] << \", \" << slope[1]);\n        // ROS_INFO_STREAM(\"look = \" << lookahead_dist << \" dista = \" << distance);\n        // ROS_INFO_STREAM(\"increment = \" << increment << \" look - dist = \" << (distance - lookahead_dist) + increment);\n        slope /= increment;\n        slope *= (distance - lookahead_dist) + increment;\n        // ROS_INFO_STREAM(\"slope2 = \" << slope[0] << \", \" << slope[1]);\n        slope += first;\n        tar_x = slope[0];\n        tar_y = slope[1];\n      }\n      else\n      {\n        path_index++;\n        distance += increment;\n      }\n    }\n  }\n  else\n  {\n    tar_x = end.x;\n    tar_y = end.y;\n  }\n\n  double yDiff = tar_y - cur_y;\n  double xDiff = tar_x - cur_x;\n\n  if (xDiff == 0)\n  {\n    tar_theta = yDiff > 0 ? M_PI : -M_PI;\n  }\n  else\n  {\n    tar_theta = atan2((yDiff), (xDiff));\n  }\n\n  ros::Time time = ros::Time::now();\n\n  geometry_msgs::PointStamped target_point;\n  target_point.header.frame_id = \"/odom\";\n  target_point.header.stamp = time;\n  target_point.point.x = tar_x;\n  target_point.point.y = tar_y;\n  target_pub.publish(target_point);\n\n  igvc_msgs::velocity_pair vel;\n  vel.header.stamp = time;\n\n  nav_msgs::Path trajectory_msg;\n  trajectory_msg.header.stamp = ros::Time::now();\n  trajectory_msg.header.frame_id = \"/odom\";\n\n  Eigen::Vector3d cur_pos(cur_x, cur_y, cur_theta);\n  Eigen::Vector3d target(tar_x, tar_y, tar_theta);\n  controller.getTrajectory(vel, trajectory_msg, cur_pos, target);\n\n  ROS_INFO_STREAM(\"distance = \" << get_distance(tar_x, tar_y, cur_x, cur_y));\n\n  if (vel.right_velocity > maximum_vel || vel.left_velocity > maximum_vel)\n  {\n    ROS_ERROR_STREAM(\"Large velocity output stopping \" << vel.right_velocity << \", \" << vel.left_velocity);\n    vel.right_velocity = 0;\n    vel.left_velocity = 0;\n  }\n  // ROS_INFO_STREAM(\"target \" << tar_x << \" \" << tar_y << \"\\n\");\n\n  cmd_pub.publish(vel);\n  trajectory_pub.publish(trajectory_msg);\n}\n\nint main(int argc, char** argv)\n{\n  ros::init(argc, argv, \"path_follower\");\n\n  ros::NodeHandle nh;\n  ros::NodeHandle pNh(\"~\");\n\n  pNh.param(std::string(\"target_v\"), controller.v, 1.0);\n  pNh.param(std::string(\"axle_length\"), controller.axle_length, 0.52);\n  pNh.param(std::string(\"k1\"), controller.k1, 1.0);\n  pNh.param(std::string(\"k2\"), controller.k2, 3.0);\n  pNh.param(std::string(\"roll_out_time\"), controller.rollOutTime, 2.0);\n  pNh.param(std::string(\"lookahead_dist\"), lookahead_dist, 2.0);\n  pNh.param(std::string(\"maximum_vel\"), maximum_vel, 1.6);\n\n  ros::Subscriber path_sub = nh.subscribe(\"/path\", 1, path_callback);\n\n  ros::Subscriber pose_sub = nh.subscribe(\"/odometry/filtered\", 1, position_callback);\n\n  cmd_pub = nh.advertise<igvc_msgs::velocity_pair>(\"/motors\", 1);\n\n  target_pub = nh.advertise<geometry_msgs::PointStamped>(\"/target_point\", 1);\n\n  trajectory_pub = nh.advertise<nav_msgs::Path>(\"/trajectory\", 1);\n\n  ros::spin();\n\n  return 0;\n}\n", "meta": {"hexsha": "2bded88600e7625b847a692423255fd2574c29ef", "size": 5520, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igvc_navigation/src/path_follower/main.cpp", "max_stars_repo_name": "Litagano-M/igvc-software", "max_stars_repo_head_hexsha": "5859c88a456edbb9a0fd901a09c778f7cccc469a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "igvc_navigation/src/path_follower/main.cpp", "max_issues_repo_name": "Litagano-M/igvc-software", "max_issues_repo_head_hexsha": "5859c88a456edbb9a0fd901a09c778f7cccc469a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "igvc_navigation/src/path_follower/main.cpp", "max_forks_repo_name": "Litagano-M/igvc-software", "max_forks_repo_head_hexsha": "5859c88a456edbb9a0fd901a09c778f7cccc469a", "max_forks_repo_licenses": ["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.2063492063, "max_line_length": 120, "alphanum_fraction": 0.65, "num_tokens": 1549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604134, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5482889217313446}}
{"text": "\n#include <boost/test/unit_test.hpp>\n#include \"line.h\"\n#include \"capsule.h\"\n#include \"sphere.h\"\n\nBOOST_AUTO_TEST_SUITE(test_sphere)\n\nBOOST_AUTO_TEST_CASE (test_sphere_line_intersection)\n{\n\tmath::sphere<2> s;\n\ts.centre.set(1, 0);\n\ts.radius = 1;\n\n\tmath::line<2> l;\n\tl.A.set(0, 1);\n\tl.B.set(0, -1);\n\n\tmath::vec<2> p1, p2;\n\tint npoints = s.query_intersection(l, p1, p2);\n\n\tBOOST_REQUIRE (npoints == 1);\n\tBOOST_REQUIRE ((p1 - math::vec<2>(0, 0)).length() < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_CASE (test_sphere_capsule_intersection_1)\n{\n\tmath::sphere<3> s(math::vec<3>(0, 0, 0), 0.5f);\n\tmath::capsule<3> c(math::vec<3>(0.7f, -1, 0), math::vec<3>(0.7f, 1, 0), 0.5f);\n\n\tBOOST_REQUIRE (s.test_intersection(c) == true);\n}\n\nBOOST_AUTO_TEST_CASE (test_sphere_capsule_intersection_2)\n{\n\tmath::sphere<3> s(math::vec<3>(0, 0, 0), 0.5f);\n\tmath::capsule<3> c(math::vec<3>(1.7f, -1, 0), math::vec<3>(1.7f, 1, 0), 0.5f);\n\n\tBOOST_REQUIRE (s.test_intersection(c) == false);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "17a6876a60ff20f5008a8f4b6939826974a5466f", "size": 984, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/math/test_sphere.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_sphere.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_sphere.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": 22.8837209302, "max_line_length": 79, "alphanum_fraction": 0.6676829268, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.640635841117624, "lm_q1q2_score": 0.5482889099871207}}
{"text": "// Copyright (c) 2020 Chris Richardson & Matthew Scroggs\n// FEniCS Project\n// SPDX-License-Identifier:    MIT\n\n#include \"brezzi-douglas-marini.h\"\n#include \"core/dof-permutations.h\"\n#include \"core/element-families.h\"\n#include \"core/mappings.h\"\n#include \"core/moments.h\"\n#include \"core/polyset.h\"\n#include \"core/quadrature.h\"\n#include \"lagrange.h\"\n#include \"nedelec.h\"\n#include <Eigen/Dense>\n#include <numeric>\n#include <vector>\n\nusing namespace basix;\n\n//----------------------------------------------------------------------------\nFiniteElement basix::create_bdm(cell::type celltype, int degree)\n{\n  if (celltype != cell::type::triangle and celltype != cell::type::tetrahedron)\n    throw std::runtime_error(\"Unsupported cell type\");\n\n  const int tdim = cell::topological_dimension(celltype);\n\n  const cell::type facettype\n      = (tdim == 2) ? cell::type::interval : cell::type::triangle;\n\n  // The number of order (degree) scalar polynomials\n  const int npoly = polyset::dim(celltype, degree);\n  const int ndofs = npoly * tdim;\n\n  // Create coefficients for order (degree-1) vector polynomials\n  Eigen::MatrixXd wcoeffs = Eigen::MatrixXd::Identity(ndofs, ndofs);\n\n  // Dual space\n  Eigen::MatrixXd dual = Eigen::MatrixXd::Zero(ndofs, ndofs);\n\n  // quadrature degree\n  int quad_deg = 5 * degree;\n\n  // Add rows to dualmat for integral moments on facets\n  const int facet_count = tdim + 1;\n  const int facet_dofs = polyset::dim(facettype, degree);\n\n  dual.block(0, 0, facet_count * facet_dofs, ndofs)\n      = moments::make_normal_integral_moments(\n          create_dlagrange(facettype, degree), celltype, tdim, degree,\n          quad_deg);\n\n  const int internal_dofs = ndofs - facet_count * facet_dofs;\n\n  // Add rows to dualmat for integral moments on interior\n  if (degree > 1)\n  {\n    // Interior integral moment\n    dual.block(facet_count * facet_dofs, 0, internal_dofs, ndofs)\n        = moments::make_dot_integral_moments(\n            create_nedelec(celltype, degree - 1), celltype, tdim, degree,\n            quad_deg);\n  }\n\n  const std::vector<std::vector<std::vector<int>>> topology\n      = cell::topology(celltype);\n\n  int perm_count = 0;\n  for (int i = 1; i < tdim; ++i)\n    perm_count += topology[i].size() * i;\n\n  std::vector<Eigen::MatrixXd> base_permutations(\n      perm_count, Eigen::MatrixXd::Identity(ndofs, ndofs));\n  if (tdim == 2)\n  {\n    Eigen::ArrayXi edge_ref = dofperms::interval_reflection(degree + 1);\n    Eigen::ArrayXXd edge_dir\n        = dofperms::interval_reflection_tangent_directions(degree + 1);\n    for (int edge = 0; edge < facet_count; ++edge)\n    {\n      const int start = edge_ref.size() * edge;\n      for (int i = 0; i < edge_ref.size(); ++i)\n      {\n        base_permutations[edge](start + i, start + i) = 0;\n        base_permutations[edge](start + i, start + edge_ref[i]) = 1;\n      }\n      Eigen::MatrixXd directions = Eigen::MatrixXd::Identity(ndofs, ndofs);\n      directions.block(edge_dir.rows() * edge, edge_dir.cols() * edge,\n                       edge_dir.rows(), edge_dir.cols())\n          = edge_dir;\n      base_permutations[edge] *= directions;\n    }\n  }\n  else if (tdim == 3)\n  {\n    Eigen::ArrayXi face_ref = dofperms::triangle_reflection(degree + 1);\n    Eigen::ArrayXi face_rot = dofperms::triangle_rotation(degree + 1);\n\n    for (int face = 0; face < facet_count; ++face)\n    {\n      const int start = face_ref.size() * face;\n      for (int i = 0; i < face_rot.size(); ++i)\n      {\n        base_permutations[6 + 2 * face](start + i, start + i) = 0;\n        base_permutations[6 + 2 * face](start + i, start + face_rot[i]) = 1;\n        base_permutations[6 + 2 * face + 1](start + i, start + i) = 0;\n        base_permutations[6 + 2 * face + 1](start + i, start + face_ref[i])\n            = -1;\n      }\n    }\n  }\n\n  // BDM has facet_dofs dofs on each facet, and ndofs-facet_count*facet_dofs in\n  // the interior\n  std::vector<std::vector<int>> entity_dofs(topology.size());\n  for (int i = 0; i < tdim - 1; ++i)\n    entity_dofs[i].resize(topology[i].size(), 0);\n  entity_dofs[tdim - 1].resize(topology[tdim - 1].size(), facet_dofs);\n  entity_dofs[tdim] = {internal_dofs};\n\n  Eigen::MatrixXd coeffs = compute_expansion_coefficients(wcoeffs, dual);\n\n  return FiniteElement(element::family::BDM, celltype, degree, {tdim}, coeffs,\n                       entity_dofs, base_permutations, {}, {},\n                       mapping::type::contravariantPiola);\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "4561a66aa8a43770264c92d59f2120c201551679", "size": 4481, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/elements/brezzi-douglas-marini.cpp", "max_stars_repo_name": "draenog/basix", "max_stars_repo_head_hexsha": "172720a7ecf2caaf4619a4718fa3f3e1cbe0c1e4", "max_stars_repo_licenses": ["MIT"], "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/elements/brezzi-douglas-marini.cpp", "max_issues_repo_name": "draenog/basix", "max_issues_repo_head_hexsha": "172720a7ecf2caaf4619a4718fa3f3e1cbe0c1e4", "max_issues_repo_licenses": ["MIT"], "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/elements/brezzi-douglas-marini.cpp", "max_forks_repo_name": "draenog/basix", "max_forks_repo_head_hexsha": "172720a7ecf2caaf4619a4718fa3f3e1cbe0c1e4", "max_forks_repo_licenses": ["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.0078125, "max_line_length": 79, "alphanum_fraction": 0.6244141933, "num_tokens": 1236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5482800631976062}}
{"text": "\ufeff//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include \"RefWorkloadFactoryHelper.hpp\"\n\n#include <backendsCommon/test/LayerTests.hpp>\n\n#include <reference/RefWorkloadFactory.hpp>\n\n#include <test/TensorHelpers.hpp>\n#include <test/UnitTests.hpp>\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(Compute_Reference)\n\nusing namespace armnn;\n\nusing FactoryType = RefWorkloadFactory;\n\n// ============================================================================\n// UNIT tests\n\n// Convolution\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5, SimpleConvolution2d3x5Test, true, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5Uint8, SimpleConvolution2d3x5Uint8Test, true, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5Nhwc, SimpleConvolution2d3x5Test, true, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5Uint8Nhwc, SimpleConvolution2d3x5Uint8Test, true, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5QSymm16, SimpleConvolution2d3x5QSymm16Test, true, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5QSymm16Nhwc, SimpleConvolution2d3x5QSymm16Test, true, DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(UnbiasedConvolution2d, SimpleConvolution2d3x5Test, false, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedConvolutionUint8, SimpleConvolution2d3x5Uint8Test, false, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedConvolution2dNhwc, SimpleConvolution2d3x5Test, false, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedConvolutionUint8Nhwc, SimpleConvolution2d3x5Uint8Test, false, DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution1d, Convolution1dTest, true)\nARMNN_AUTO_TEST_CASE(SimpleConvolution1dUint8, Convolution1dUint8Test, true)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3, SimpleConvolution2d3x3Test, true, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3Uint8, SimpleConvolution2d3x3Uint8Test, true, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3QSymm16, SimpleConvolution2d3x3QSymm16Test, true, DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3Nhwc, SimpleConvolution2d3x3Test, true, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3Uint8Nhwc, SimpleConvolution2d3x3Uint8Test, true, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3QSymm16Nhwc, SimpleConvolution2d3x3QSymm16Test, true,\n                     DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(UnbiasedConvolution2dSquare, SimpleConvolution2d3x3Test, false, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedConvolution2dSquareNhwc, SimpleConvolution2d3x3Test, false, DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(UnbiasedConvolution2dSquareStride2x2Nhwc,\n                     SimpleConvolution2d3x3Stride2x2Test,\n                     false,\n                     DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution2dAsymmetricPaddingLargerThanHalfKernelSize,\n                     Convolution2dAsymmetricPaddingLargerThanHalfKernelSizeTest,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2dAsymmetricPadding, Convolution2dAsymmetricPaddingTest, DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution2dAsymmetricPaddingLargerThanHalfKernelSizeNhwc,\n                     Convolution2dAsymmetricPaddingLargerThanHalfKernelSizeTest,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2dAsymmetricPaddingNhwc,\n                     Convolution2dAsymmetricPaddingTest,\n                     DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution2dSquareNhwc, SimpleConvolution2d3x3NhwcTest, false)\n\nARMNN_AUTO_TEST_CASE(Convolution2d3x3Dilation3x3,\n                     Convolution2d3x3Dilation3x3Test<DataType::Float32, DataType::Float32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(Convolution2d3x3Dilation3x3Nhwc,\n                     Convolution2d3x3Dilation3x3Test<DataType::Float32, DataType::Float32>,\n                     false,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(Convolution2d3x3Dilation3x3Uint8,\n                     Convolution2d3x3Dilation3x3Test<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(Convolution2d3x3Dilation3x3NhwcUint8,\n                     Convolution2d3x3Dilation3x3Test<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     false,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(Convolution2d3x3Dilation3x3Int16,\n                     Convolution2d3x3Dilation3x3Test<DataType::QuantisedSymm16, DataType::Signed32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(Convolution2d3x3Dilation3x3NhwcInt16,\n                     Convolution2d3x3Dilation3x3Test<DataType::QuantisedSymm16, DataType::Signed32>,\n                     false,\n                     DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(Convolution2d2x3x3Dilation3x3,\n                     Convolution2d2x3x3Dilation3x3Test<DataType::Float32, DataType::Float32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(Convolution2d2x3x3Dilation3x3Nhwc,\n                     Convolution2d2x3x3Dilation3x3Test<DataType::Float32, DataType::Float32>,\n                     false,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(Convolution2d2x3x3Dilation3x3Uint8,\n                     Convolution2d2x3x3Dilation3x3Test<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(Convolution2d2x3x3Dilation3x3NhwcUint8,\n                     Convolution2d2x3x3Dilation3x3Test<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     false,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(Convolution2d2x3x3Dilation3x3Int16,\n                     Convolution2d2x3x3Dilation3x3Test<DataType::QuantisedSymm16, DataType::Signed32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(Convolution2d2x3x3Dilation3x3NhwcInt16,\n                     Convolution2d2x3x3Dilation3x3Test<DataType::QuantisedSymm16, DataType::Signed32>,\n                     false,\n                     DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(Convolution2d2x2Dilation2x2Padding2x2Stride3x3,\n                     Convolution2d2x2Dilation2x2Padding2x2Stride3x3Test<DataType::Float32, DataType::Float32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(Convolution2d2x2Dilation2x2Padding2x2Stride3x3Nhwc,\n                     Convolution2d2x2Dilation2x2Padding2x2Stride3x3Test<DataType::Float32, DataType::Float32>,\n                     false,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(Convolution2d2x2Dilation2x2Padding2x2Stride3x3Uint8,\n                     Convolution2d2x2Dilation2x2Padding2x2Stride3x3Test<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(Convolution2d2x2Dilation2x2Padding2x2Stride3x3NhwcUint8,\n                     Convolution2d2x2Dilation2x2Padding2x2Stride3x3Test<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     false,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(Convolution2d2x2Dilation2x2Padding2x2Stride3x3Int16,\n                     Convolution2d2x2Dilation2x2Padding2x2Stride3x3Test<DataType::QuantisedSymm16, DataType::Signed32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(Convolution2d2x2Dilation2x2Padding2x2Stride3x3NhwcInt16,\n                     Convolution2d2x2Dilation2x2Padding2x2Stride3x3Test<DataType::QuantisedSymm16, DataType::Signed32>,\n                     false,\n                     DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(Convolution2dPerAxisQuantTestNchw, Convolution2dPerAxisQuantTest, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(Convolution2dPerAxisQuantTestNhwc, Convolution2dPerAxisQuantTest, DataLayout::NHWC);\n\n// Depthwise Convolution\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d, DepthwiseConvolution2dTest, true, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dUint8, DepthwiseConvolution2dUint8Test, true, DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2d, DepthwiseConvolution2dTest, false, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dUint8,\n                     DepthwiseConvolution2dUint8Test,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dQSymm16, DepthwiseConvolution2dInt16Test, true, DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dNhwc, DepthwiseConvolution2dTest, true, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dUint8Nhwc, DepthwiseConvolution2dUint8Test, true, DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dNhwc, DepthwiseConvolution2dTest, false, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dUint8Nhwc,\n                     DepthwiseConvolution2dUint8Test,\n                     false,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthNhwc, DepthwiseConvolution2dDepthNhwcTest, false)\nARMNN_AUTO_TEST_CASE(SimpleDepthwiseConvolution2d3x3Dilation3x3Nhwc,\n                     SimpleDepthwiseConvolution2d3x3Dilation3x3NhwcTest)\n\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d3x3Dilation3x3,\n                     DepthwiseConvolution2d3x3Dilation3x3Test<DataType::Float32, DataType::Float32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d3x3Dilation3x3Nhwc,\n                     DepthwiseConvolution2d3x3Dilation3x3Test<DataType::Float32, DataType::Float32>,\n                     false,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d3x3Dilation3x3Uint8,\n                     DepthwiseConvolution2d3x3Dilation3x3Test<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d3x3Dilation3x3NhwcUint8,\n                     DepthwiseConvolution2d3x3Dilation3x3Test<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     false,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d3x3Dilation3x3Int16,\n                     DepthwiseConvolution2d3x3Dilation3x3Test<DataType::QuantisedSymm16, DataType::Signed32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d3x3Dilation3x3NhwcInt16,\n                     DepthwiseConvolution2d3x3Dilation3x3Test<DataType::QuantisedSymm16, DataType::Signed32>,\n                     false,\n                     DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d2x3x3Dilation3x3,\n                     DepthwiseConvolution2d2x3x3Dilation3x3Test<DataType::Float32, DataType::Float32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d2x3x3Dilation3x3Nhwc,\n                     DepthwiseConvolution2d2x3x3Dilation3x3Test<DataType::Float32, DataType::Float32>,\n                     false,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d2x3x3Dilation3x3Uint8,\n                     DepthwiseConvolution2d2x3x3Dilation3x3Test<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d2x3x3Dilation3x3NhwcUint8,\n                     DepthwiseConvolution2d2x3x3Dilation3x3Test<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     false,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d2x3x3Dilation3x3Int16,\n                     DepthwiseConvolution2d2x3x3Dilation3x3Test<DataType::QuantisedSymm16, DataType::Signed32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d2x3x3Dilation3x3NhwcInt16,\n                     DepthwiseConvolution2d2x3x3Dilation3x3Test<DataType::QuantisedSymm16, DataType::Signed32>,\n                     false,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dMult4,\n                     DepthwiseConvolution2dMult4Test<armnn::DataType::Float32, armnn::DataType::Float32>,\n                     false,\n                     armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dMult2,\n                     DepthwiseConvolution2dMult2Test<armnn::DataType::Float32, armnn::DataType::Float32>,\n                     false,\n                     armnn::DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthMul1,\n                     DepthwiseConvolution2dDepthMul1Test, true, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthMul1Uint8,\n                     DepthwiseConvolution2dDepthMul1Uint8Test, true, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthMul1Int16,\n                     DepthwiseConvolution2dDepthMul1Int16Test, true, DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dDepthMul1,\n                     DepthwiseConvolution2dDepthMul1Test, false, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dDepthMul1Uint8,\n                     DepthwiseConvolution2dDepthMul1Uint8Test, false, DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthMul1Nhwc,\n                     DepthwiseConvolution2dDepthMul1Test, true, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthMul1Uint8Nhwc,\n                     DepthwiseConvolution2dDepthMul1Uint8Test, true, DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dDepthMul1Nhwc,\n                     DepthwiseConvolution2dDepthMul1Test, false, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dDepthMul1Uint8Nhwc,\n                     DepthwiseConvolution2dDepthMul1Uint8Test, false, DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dAsymmetric,\n                     DepthwiseConvolution2dAsymmetricTest, true, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dAsymmetric,\n                     DepthwiseConvolution2dAsymmetricTest, false, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dAsymmetricNhwc,\n                     DepthwiseConvolution2dAsymmetricTest, true, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dAsymmetricNhwc,\n                     DepthwiseConvolution2dAsymmetricTest, false, DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthMul64, DepthwiseConvolution2dDepthMul64Test);\n\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dPerAxisQuantTestNchw, DepthwiseConvolution2dPerAxisQuantTest,\n                     DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dPerAxisQuantTestNhwc, DepthwiseConvolution2dPerAxisQuantTest,\n                     DataLayout::NHWC);\n\n// Pooling\n//MaxPooling\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize2x2Stride2x2, SimpleMaxPooling2dSize2x2Stride2x2Test, false)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize2x2Stride2x2Uint8, SimpleMaxPooling2dSize2x2Stride2x2Uint8Test, false)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize2x2Stride2x2Int16, SimpleMaxPooling2dSize2x2Stride2x2Int16Test, false)\n\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize3x3Stride2x4, SimpleMaxPooling2dSize3x3Stride2x4Test, false)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize3x3Stride2x4Uint8, SimpleMaxPooling2dSize3x3Stride2x4Uint8Test, false)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize3x3Stride2x4Int16, SimpleMaxPooling2dSize3x3Stride2x4Int16Test, false)\n\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2d, SimpleMaxPooling2dTest, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dNhwc, SimpleMaxPooling2dTest, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dUint8, SimpleMaxPooling2dUint8Test, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dInt16, SimpleMaxPooling2dInt16Test, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dUint8Nhwc, SimpleMaxPooling2dUint8Test, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dInt16Nhwc, SimpleMaxPooling2dInt16Test, DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleMaxPooling2d, IgnorePaddingSimpleMaxPooling2dTest)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleMaxPooling2dUint8, IgnorePaddingSimpleMaxPooling2dUint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleMaxPooling2dInt16, IgnorePaddingSimpleMaxPooling2dInt16Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingMaxPooling2dSize3, IgnorePaddingMaxPooling2dSize3Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingMaxPooling2dSize3Uint8, IgnorePaddingMaxPooling2dSize3Uint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingMaxPooling2dSize3Int16, IgnorePaddingMaxPooling2dSize3Int16Test)\n\n//AveragePooling\nARMNN_AUTO_TEST_CASE(SimpleAveragePooling2d, SimpleAveragePooling2dTest, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleAveragePooling2dNhwc, SimpleAveragePooling2dTest, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleAveragePooling2dUint8, SimpleAveragePooling2dUint8Test, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleAveragePooling2dInt16, SimpleAveragePooling2dInt16Test, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleAveragePooling2dUint8Nhwc, SimpleAveragePooling2dUint8Test, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleAveragePooling2dInt16Nhwc, SimpleAveragePooling2dInt16Test, DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2d, IgnorePaddingSimpleAveragePooling2dTest)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2dUint8, IgnorePaddingSimpleAveragePooling2dUint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2dInt16, IgnorePaddingSimpleAveragePooling2dInt16Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2dNoPadding, IgnorePaddingSimpleAveragePooling2dNoPaddingTest)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2dNoPaddingUint8,\n                     IgnorePaddingSimpleAveragePooling2dNoPaddingUint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2dNoPaddingInt16,\n                     IgnorePaddingSimpleAveragePooling2dNoPaddingInt16Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingAveragePooling2dSize3, IgnorePaddingAveragePooling2dSize3Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingAveragePooling2dSize3Uint8, IgnorePaddingAveragePooling2dSize3Uint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingAveragePooling2dSize3Int16, IgnorePaddingAveragePooling2dSize3Int16Test)\n\nARMNN_AUTO_TEST_CASE(IgnorePaddingAveragePooling2dSize3x2Stride2x2,\n                     IgnorePaddingAveragePooling2dSize3x2Stride2x2Test, false)\nARMNN_AUTO_TEST_CASE(IgnorePaddingAveragePooling2dSize3x2Stride2x2NoPadding,\n                     IgnorePaddingAveragePooling2dSize3x2Stride2x2Test, true)\n\nARMNN_AUTO_TEST_CASE(LargeTensorsAveragePooling2d, LargeTensorsAveragePooling2dTest)\nARMNN_AUTO_TEST_CASE(LargeTensorsAveragePooling2dUint8, LargeTensorsAveragePooling2dUint8Test)\nARMNN_AUTO_TEST_CASE(LargeTensorsAveragePooling2dInt16, LargeTensorsAveragePooling2dInt16Test)\n\n//L2Pooling\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleL2Pooling2d, IgnorePaddingSimpleL2Pooling2dTest)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleL2Pooling2dUint8, IgnorePaddingSimpleL2Pooling2dUint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleL2Pooling2dInt16, IgnorePaddingSimpleL2Pooling2dInt16Test)\n\nARMNN_AUTO_TEST_CASE(IgnorePaddingL2Pooling2dSize3, IgnorePaddingL2Pooling2dSize3Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingL2Pooling2dSize3Uint8, IgnorePaddingL2Pooling2dSize3Uint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingL2Pooling2dSize3Int16, IgnorePaddingL2Pooling2dSize3Int16Test)\n\nARMNN_AUTO_TEST_CASE(SimpleL2Pooling2d, SimpleL2Pooling2dTest, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleL2Pooling2dNhwc, SimpleL2Pooling2dTest, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleL2Pooling2dUint8, SimpleL2Pooling2dUint8Test, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleL2Pooling2dInt16, SimpleL2Pooling2dInt16Test, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleL2Pooling2dNhwcUint8, SimpleL2Pooling2dUint8Test, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleL2Pooling2dNhwcInt16, SimpleL2Pooling2dInt16Test, DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(L2Pooling2dSize7, L2Pooling2dSize7Test)\nARMNN_AUTO_TEST_CASE(L2Pooling2dSize7Uint8, L2Pooling2dSize7Uint8Test)\nARMNN_AUTO_TEST_CASE(L2Pooling2dSize7Int16, L2Pooling2dSize7Int16Test)\n\n//NonSquarePooling\nARMNN_AUTO_TEST_CASE(AsymmNonSquarePooling2d, AsymmetricNonSquarePooling2dTest)\nARMNN_AUTO_TEST_CASE(AsymmNonSquarePooling2dUint8, AsymmetricNonSquarePooling2dUint8Test)\nARMNN_AUTO_TEST_CASE(AsymmNonSquarePooling2dInt16, AsymmetricNonSquarePooling2dInt16Test)\n\n\n// Linear Activation\nARMNN_AUTO_TEST_CASE(ConstantLinearActivation, ConstantLinearActivationTest)\nARMNN_AUTO_TEST_CASE(ConstantLinearActivationUint8, ConstantLinearActivationUint8Test)\nARMNN_AUTO_TEST_CASE(ConstantLinearActivationInt16, ConstantLinearActivationInt16Test)\n\n// InstanceNormalization\nARMNN_AUTO_TEST_CASE(InstanceNormFloat32Nchw, InstanceNormFloat32Test, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(InstanceNormFloat16Nchw, InstanceNormFloat16Test, DataLayout::NCHW);\n\nARMNN_AUTO_TEST_CASE(InstanceNormFloat32Nhwc, InstanceNormFloat32Test, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(InstanceNormFloat16Nhwc, InstanceNormFloat16Test, DataLayout::NHWC);\n\nARMNN_AUTO_TEST_CASE(InstanceNormFloat32Nchw2, InstanceNormFloat32Test2, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(InstanceNormFloat16Nchw2, InstanceNormFloat16Test2, DataLayout::NCHW);\n\nARMNN_AUTO_TEST_CASE(InstanceNormFloat32Nhwc2, InstanceNormFloat32Test2, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(InstanceNormFloat16Nhwc2, InstanceNormFloat16Test2, DataLayout::NHWC);\n\n// Normalization\nARMNN_AUTO_TEST_CASE(SimpleNormalizationAcross, SimpleNormalizationAcrossTest)\nARMNN_AUTO_TEST_CASE(SimpleNormalizationWithin, SimpleNormalizationWithinTest)\nARMNN_AUTO_TEST_CASE(SimpleNormalizationAcrossNhwc, SimpleNormalizationAcrossNhwcTest)\n\n// Softmax\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxBeta1, SimpleSoftmaxTest, 1.0f)\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxBeta2, SimpleSoftmaxTest, 2.0f)\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxBeta1Uint8, SimpleSoftmaxUint8Test, 1.0f)\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxBeta2Uint8, SimpleSoftmaxUint8Test, 2.0f)\n\nARMNN_AUTO_TEST_CASE(Simple3dSoftmax, Simple3dSoftmaxTest, 1.0f)\nARMNN_AUTO_TEST_CASE(Simple3dSoftmaxUint8, Simple3dSoftmaxUint8Test, 1.0f)\n\nARMNN_AUTO_TEST_CASE(Simple4dSoftmax, Simple4dSoftmaxTest, 1.0f)\nARMNN_AUTO_TEST_CASE(Simple4dSoftmaxUint8, Simple4dSoftmaxUint8Test, 1.0f)\n\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxFloat16, SimpleSoftmaxFloat16Test, 1.0f)\nARMNN_AUTO_TEST_CASE(Simple3dSoftmaxFloat16, Simple3dSoftmaxFloat16Test, 1.0f)\nARMNN_AUTO_TEST_CASE(Simple4dSoftmaxFloat16, Simple4dSoftmaxFloat16Test, 1.0f)\n\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxUint16, SimpleSoftmaxUint16Test, 1.0f)\nARMNN_AUTO_TEST_CASE(Simple3dSoftmaxUint16, Simple3dSoftmaxUint16Test, 1.0f)\nARMNN_AUTO_TEST_CASE(Simple4dSoftmaxUint16, Simple4dSoftmaxUint16Test, 1.0f)\n\nARMNN_AUTO_TEST_CASE(Simple2dAxis0Softmax, SimpleAxisSoftmaxTest, 1.0f, 0)\nARMNN_AUTO_TEST_CASE(Simple2dAxis1Softmax, SimpleAxisSoftmaxTest, 1.0f, 1)\n\nARMNN_AUTO_TEST_CASE(Simple2dAxis0NegSoftmax, SimpleAxisSoftmaxTest, 1.0f, -2)\nARMNN_AUTO_TEST_CASE(Simple2dAxis1NegSoftmax, SimpleAxisSoftmaxTest, 1.0f, -1)\n\nARMNN_AUTO_TEST_CASE(Simple3dAxis0Softmax, Simple3dAxisSoftmaxTest, 1.0f, 0)\nARMNN_AUTO_TEST_CASE(Simple3dAxis1Softmax, Simple3dAxisSoftmaxTest, 1.0f, 1)\nARMNN_AUTO_TEST_CASE(Simple3dAxis2Softmax, Simple3dAxisSoftmaxTest, 1.0f, 2)\n\nARMNN_AUTO_TEST_CASE(Simple3dAxis0NegSoftmax, Simple3dAxisSoftmaxTest, 1.0f, -3)\nARMNN_AUTO_TEST_CASE(Simple3dAxis1NegSoftmax, Simple3dAxisSoftmaxTest, 1.0f, -2)\nARMNN_AUTO_TEST_CASE(Simple3dAxis2NegSoftmax, Simple3dAxisSoftmaxTest, 1.0f, -1)\n\nARMNN_AUTO_TEST_CASE(Simple4dAxis0Softmax, Simple4dAxisSoftmaxTest, 1.0f, 0)\nARMNN_AUTO_TEST_CASE(Simple4dAxis1Softmax, Simple4dAxisSoftmaxTest, 1.0f, 1)\nARMNN_AUTO_TEST_CASE(Simple4dAxis2Softmax, Simple4dAxisSoftmaxTest, 1.0f, 2)\nARMNN_AUTO_TEST_CASE(Simple4dAxis3Softmax, Simple4dAxisSoftmaxTest, 1.0f, 3)\n\nARMNN_AUTO_TEST_CASE(Simple4dAxis0NegSoftmax, Simple4dAxisSoftmaxTest, 1.0f, -4)\nARMNN_AUTO_TEST_CASE(Simple4dAxis1NegSoftmax, Simple4dAxisSoftmaxTest, 1.0f, -3)\nARMNN_AUTO_TEST_CASE(Simple4dAxis2NegSoftmax, Simple4dAxisSoftmaxTest, 1.0f, -2)\nARMNN_AUTO_TEST_CASE(Simple4dAxis3NegSoftmax, Simple4dAxisSoftmaxTest, 1.0f, -1)\n\n// Sigmoid Activation\nARMNN_AUTO_TEST_CASE(SimpleSigmoid, SimpleSigmoidTest)\nARMNN_AUTO_TEST_CASE(SimpleSigmoidUint8, SimpleSigmoidUint8Test)\nARMNN_AUTO_TEST_CASE(SimpleSigmoidInt16, SimpleSigmoidInt16Test)\n\n// BoundedReLU Activation\nARMNN_AUTO_TEST_CASE(ReLu1, BoundedReLuUpperAndLowerBoundTest)\nARMNN_AUTO_TEST_CASE(ReLu6, BoundedReLuUpperBoundOnlyTest)\nARMNN_AUTO_TEST_CASE(ReLu1Uint8, BoundedReLuUint8UpperAndLowerBoundTest)\nARMNN_AUTO_TEST_CASE(ReLu6Uint8, BoundedReLuUint8UpperBoundOnlyTest)\nARMNN_AUTO_TEST_CASE(BoundedReLuInt16, BoundedReLuInt16Test)\n\n// ReLU Activation\nARMNN_AUTO_TEST_CASE(ReLu, ReLuTest)\nARMNN_AUTO_TEST_CASE(ReLuUint8, ReLuUint8Test)\nARMNN_AUTO_TEST_CASE(ReLuInt16, ReLuInt16Test)\n\n// SoftReLU Activation\nARMNN_AUTO_TEST_CASE(SoftReLu, SoftReLuTest)\nARMNN_AUTO_TEST_CASE(SoftReLuUint8, SoftReLuUint8Test)\nARMNN_AUTO_TEST_CASE(SoftReLuInt16, SoftReLuInt16Test)\n\n\n// LeakyReLU Activation\nARMNN_AUTO_TEST_CASE(LeakyReLu, LeakyReLuTest)\nARMNN_AUTO_TEST_CASE(LeakyReLuUint8, LeakyReLuUint8Test)\nARMNN_AUTO_TEST_CASE(LeakyReLuInt16, LeakyReLuInt16Test)\n\n// Abs Activation\nARMNN_AUTO_TEST_CASE(Abs, AbsTest)\nARMNN_AUTO_TEST_CASE(AbsUint8, AbsUint8Test)\nARMNN_AUTO_TEST_CASE(AbsInt16, AbsInt16Test)\n\n// Sqrt Activation\nARMNN_AUTO_TEST_CASE(Sqrt, SqrtTest)\nARMNN_AUTO_TEST_CASE(SqrtNN, SqrtNNTest)\nARMNN_AUTO_TEST_CASE(SqrtUint8, SqrtUint8Test)\nARMNN_AUTO_TEST_CASE(SqrtInt16, SqrtInt16Test)\n\n// Square Activation\nARMNN_AUTO_TEST_CASE(Square, SquareTest)\nARMNN_AUTO_TEST_CASE(SquareUint8, SquareUint8Test)\nARMNN_AUTO_TEST_CASE(SquareInt16, SquareInt16Test)\n\n// Tanh Activation\nARMNN_AUTO_TEST_CASE(Tanh, TanhTest)\nARMNN_AUTO_TEST_CASE(TanhUint8, TanhUint8Test)\nARMNN_AUTO_TEST_CASE(TanhInt16, TanhInt16Test)\n\n\n// Fully Connected\nARMNN_AUTO_TEST_CASE(SimpleFullyConnected, FullyConnectedFloat32Test, false, false)\nARMNN_AUTO_TEST_CASE(FullyConnectedUint8, FullyConnectedTest<DataType::QuantisedAsymm8>, false)\nARMNN_AUTO_TEST_CASE(FullyConnectedQSymm16, FullyConnectedTest<DataType::QuantisedSymm16>, false)\nARMNN_AUTO_TEST_CASE(SimpleFullyConnectedWithBias, FullyConnectedFloat32Test, true, false)\nARMNN_AUTO_TEST_CASE(FullyConnectedBiasedUint8, FullyConnectedTest<DataType::QuantisedAsymm8>, true)\nARMNN_AUTO_TEST_CASE(FullyConnectedBiasedQSymm16, FullyConnectedTest<DataType::QuantisedSymm16>, true)\nARMNN_AUTO_TEST_CASE(SimpleFullyConnectedWithTranspose, FullyConnectedFloat32Test, false, true)\n\nARMNN_AUTO_TEST_CASE(FullyConnectedLarge, FullyConnectedLargeTest, false)\nARMNN_AUTO_TEST_CASE(FullyConnectedLargeTransposed, FullyConnectedLargeTest, true)\n\n// Splitter\nARMNN_AUTO_TEST_CASE(SimpleSplitterFloat32, SplitterFloat32Test)\nARMNN_AUTO_TEST_CASE(SimpleSplitterFloat16, SplitterFloat16Test)\nARMNN_AUTO_TEST_CASE(SimpleSplitterUint8, SplitterUint8Test)\nARMNN_AUTO_TEST_CASE(SimpleSplitterInt16, SplitterInt16Test)\n\nARMNN_AUTO_TEST_CASE(CopyViaSplitterFloat32, CopyViaSplitterFloat32Test)\nARMNN_AUTO_TEST_CASE(CopyViaSplitterFloat16, CopyViaSplitterFloat16Test)\nARMNN_AUTO_TEST_CASE(CopyViaSplitterUint8, CopyViaSplitterUint8Test)\nARMNN_AUTO_TEST_CASE(CopyViaSplitterInt16, CopyViaSplitterInt16Test)\n\n// Concat\nARMNN_AUTO_TEST_CASE(SimpleConcat, ConcatTest)\nARMNN_AUTO_TEST_CASE(ConcatFloat16, ConcatFloat16Test)\nARMNN_AUTO_TEST_CASE(ConcatUint8, ConcatUint8Test)\nARMNN_AUTO_TEST_CASE(ConcatUint8DifferentQParams, ConcatUint8DifferentQParamsTest)\nARMNN_AUTO_TEST_CASE(ConcatUint16, ConcatUint16Test)\nARMNN_AUTO_TEST_CASE(ConcatUint8DifferentInputOutputQParam,\n                     ConcatDifferentInputOutputQParamTest<DataType::QuantisedAsymm8>, true)\nARMNN_AUTO_TEST_CASE(ConcatInt16DifferentInputOutputQParam,\n                     ConcatDifferentInputOutputQParamTest<DataType::QuantisedSymm16>, true)\n\n// Add\nARMNN_AUTO_TEST_CASE(SimpleAdd, AdditionTest)\nARMNN_AUTO_TEST_CASE(Add5d, Addition5dTest)\nARMNN_AUTO_TEST_CASE(AddBroadcast1Element, AdditionBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(AddBroadcast, AdditionBroadcastTest)\n\nARMNN_AUTO_TEST_CASE(AdditionUint8, AdditionUint8Test)\nARMNN_AUTO_TEST_CASE(AddBroadcastUint8, AdditionBroadcastUint8Test)\nARMNN_AUTO_TEST_CASE(AddBroadcast1ElementUint8, AdditionBroadcast1ElementUint8Test)\n\nARMNN_AUTO_TEST_CASE(AdditionInt16, AdditionInt16Test)\nARMNN_AUTO_TEST_CASE(AddBroadcastInt16, AdditionBroadcastInt16Test)\nARMNN_AUTO_TEST_CASE(AddBroadcast1ElementInt16, AdditionBroadcast1ElementInt16Test)\n\n// Sub\nARMNN_AUTO_TEST_CASE(SimpleSub, SubtractionTest)\nARMNN_AUTO_TEST_CASE(SubBroadcast1Element, SubtractionBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(SubBroadcast, SubtractionBroadcastTest)\n\nARMNN_AUTO_TEST_CASE(SimpleSubFloat16, SubtractionTest)\nARMNN_AUTO_TEST_CASE(SubBroadcast1ElementFloat16, SubtractionBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(SubBroadcastFloat16, SubtractionBroadcastTest)\n\nARMNN_AUTO_TEST_CASE(SubtractionUint8, SubtractionUint8Test)\nARMNN_AUTO_TEST_CASE(SubBroadcastUint8, SubtractionBroadcastUint8Test)\nARMNN_AUTO_TEST_CASE(SubBroadcast1ElementUint8, SubtractionBroadcast1ElementUint8Test)\n\nARMNN_AUTO_TEST_CASE(SubtractionInt16, SubtractionInt16Test)\nARMNN_AUTO_TEST_CASE(SubBroadcastInt16, SubtractionBroadcastInt16Test)\nARMNN_AUTO_TEST_CASE(SubBroadcast1ElementInt16, SubtractionBroadcast1ElementInt16Test)\n\n// Div\nARMNN_AUTO_TEST_CASE(SimpleDivision, DivisionTest)\nARMNN_AUTO_TEST_CASE(DivisionByZero, DivisionByZeroTest)\nARMNN_AUTO_TEST_CASE(DivisionBroadcast1Element, DivisionBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(DivisionBroadcast1DVector, DivisionBroadcast1DVectorTest)\n\nARMNN_AUTO_TEST_CASE(DivisionFloat16, DivisionFloat16Test)\nARMNN_AUTO_TEST_CASE(DivisionFloat16Broadcast1Element, DivisionBroadcast1ElementFloat16Test)\nARMNN_AUTO_TEST_CASE(DivisionFloat16Broadcast1DVector, DivisionBroadcast1DVectorFloat16Test)\n\n// NOTE: division by zero for quantized div needs more attention\n//       see IVGCVSW-1849\nARMNN_AUTO_TEST_CASE(DivisionUint8, DivisionUint8Test)\nARMNN_AUTO_TEST_CASE(DivisionUint8Broadcast1Element, DivisionBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(DivisionUint8Broadcast1DVector, DivisionBroadcast1DVectorUint8Test)\n\nARMNN_AUTO_TEST_CASE(DivisionInt16, DivisionInt16Test)\nARMNN_AUTO_TEST_CASE(DivisionInt16Broadcast1Element, DivisionBroadcast1ElementInt16Test)\nARMNN_AUTO_TEST_CASE(DivisionInt16Broadcast1DVector, DivisionBroadcast1DVectorInt16Test)\n\n// Equal\nARMNN_AUTO_TEST_CASE(EqualSimple,            EqualSimpleTest)\nARMNN_AUTO_TEST_CASE(EqualBroadcast1Element, EqualBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(EqualBroadcast1dVector, EqualBroadcast1dVectorTest)\n\nARMNN_AUTO_TEST_CASE(EqualSimpleFloat16,            EqualSimpleFloat16Test)\nARMNN_AUTO_TEST_CASE(EqualBroadcast1ElementFloat16, EqualBroadcast1ElementFloat16Test)\nARMNN_AUTO_TEST_CASE(EqualBroadcast1dVectorFloat16, EqualBroadcast1dVectorFloat16Test)\n\nARMNN_AUTO_TEST_CASE(EqualSimpleUint8,            EqualSimpleUint8Test)\nARMNN_AUTO_TEST_CASE(EqualBroadcast1ElementUint8, EqualBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(EqualBroadcast1dVectorUint8, EqualBroadcast1dVectorUint8Test)\n\n// Greater\nARMNN_AUTO_TEST_CASE(GreaterSimple,            GreaterSimpleTest)\nARMNN_AUTO_TEST_CASE(GreaterBroadcast1Element, GreaterBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(GreaterBroadcast1dVector, GreaterBroadcast1dVectorTest)\n\nARMNN_AUTO_TEST_CASE(GreaterSimpleFloat16,            GreaterSimpleFloat16Test)\nARMNN_AUTO_TEST_CASE(GreaterBroadcast1ElementFloat16, GreaterBroadcast1ElementFloat16Test)\nARMNN_AUTO_TEST_CASE(GreaterBroadcast1dVectorFloat16, GreaterBroadcast1dVectorFloat16Test)\n\nARMNN_AUTO_TEST_CASE(GreaterSimpleUint8,            GreaterSimpleUint8Test)\nARMNN_AUTO_TEST_CASE(GreaterBroadcast1ElementUint8, GreaterBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(GreaterBroadcast1dVectorUint8, GreaterBroadcast1dVectorUint8Test)\n\n// GreaterOrEqual\nARMNN_AUTO_TEST_CASE(GreaterOrEqualSimple,            GreaterOrEqualSimpleTest)\nARMNN_AUTO_TEST_CASE(GreaterOrEqualBroadcast1Element, GreaterOrEqualBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(GreaterOrEqualBroadcast1dVector, GreaterOrEqualBroadcast1dVectorTest)\n\nARMNN_AUTO_TEST_CASE(GreaterOrEqualSimpleFloat16,            GreaterOrEqualSimpleFloat16Test)\nARMNN_AUTO_TEST_CASE(GreaterOrEqualBroadcast1ElementFloat16, GreaterOrEqualBroadcast1ElementFloat16Test)\nARMNN_AUTO_TEST_CASE(GreaterOrEqualBroadcast1dVectorFloat16, GreaterOrEqualBroadcast1dVectorFloat16Test)\n\nARMNN_AUTO_TEST_CASE(GreaterOrEqualSimpleUint8,            GreaterOrEqualSimpleUint8Test)\nARMNN_AUTO_TEST_CASE(GreaterOrEqualBroadcast1ElementUint8, GreaterOrEqualBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(GreaterOrEqualBroadcast1dVectorUint8, GreaterOrEqualBroadcast1dVectorUint8Test)\n\n// Less\nARMNN_AUTO_TEST_CASE(LessSimple,            LessSimpleTest)\nARMNN_AUTO_TEST_CASE(LessBroadcast1Element, LessBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(LessBroadcast1dVector, LessBroadcast1dVectorTest)\n\nARMNN_AUTO_TEST_CASE(LessSimpleFloat16,            LessSimpleFloat16Test)\nARMNN_AUTO_TEST_CASE(LessBroadcast1ElementFloat16, LessBroadcast1ElementFloat16Test)\nARMNN_AUTO_TEST_CASE(LessBroadcast1dVectorFloat16, LessBroadcast1dVectorFloat16Test)\n\nARMNN_AUTO_TEST_CASE(LessSimpleUint8,            LessSimpleUint8Test)\nARMNN_AUTO_TEST_CASE(LessBroadcast1ElementUint8, LessBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(LessBroadcast1dVectorUint8, LessBroadcast1dVectorUint8Test)\n\n// GreaterOrEqual\nARMNN_AUTO_TEST_CASE(LessOrEqualSimple,            LessOrEqualSimpleTest)\nARMNN_AUTO_TEST_CASE(LessOrEqualBroadcast1Element, LessOrEqualBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(LessOrEqualBroadcast1dVector, LessOrEqualBroadcast1dVectorTest)\n\nARMNN_AUTO_TEST_CASE(LessOrEqualSimpleFloat16,            LessOrEqualSimpleFloat16Test)\nARMNN_AUTO_TEST_CASE(LessOrEqualBroadcast1ElementFloat16, LessOrEqualBroadcast1ElementFloat16Test)\nARMNN_AUTO_TEST_CASE(LessOrEqualBroadcast1dVectorFloat16, LessOrEqualBroadcast1dVectorFloat16Test)\n\nARMNN_AUTO_TEST_CASE(LessOrEqualSimpleUint8,            LessOrEqualSimpleUint8Test)\nARMNN_AUTO_TEST_CASE(LessOrEqualBroadcast1ElementUint8, LessOrEqualBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(LessOrEqualBroadcast1dVectorUint8, LessOrEqualBroadcast1dVectorUint8Test)\n\n// NotEqual\nARMNN_AUTO_TEST_CASE(NotEqualSimple,            NotEqualSimpleTest)\nARMNN_AUTO_TEST_CASE(NotEqualBroadcast1Element, NotEqualBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(NotEqualBroadcast1dVector, NotEqualBroadcast1dVectorTest)\n\nARMNN_AUTO_TEST_CASE(NotEqualSimpleFloat16,            NotEqualSimpleFloat16Test)\nARMNN_AUTO_TEST_CASE(NotEqualBroadcast1ElementFloat16, NotEqualBroadcast1ElementFloat16Test)\nARMNN_AUTO_TEST_CASE(NotEqualBroadcast1dVectorFloat16, NotEqualBroadcast1dVectorFloat16Test)\n\nARMNN_AUTO_TEST_CASE(NotEqualSimpleUint8,            NotEqualSimpleUint8Test)\nARMNN_AUTO_TEST_CASE(NotEqualBroadcast1ElementUint8, NotEqualBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(NotEqualBroadcast1dVectorUint8, NotEqualBroadcast1dVectorUint8Test)\n\n// Max\nARMNN_AUTO_TEST_CASE(SimpleMaximum, MaximumSimpleTest)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1Element, MaximumBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1DVector, MaximumBroadcast1DVectorTest)\nARMNN_AUTO_TEST_CASE(MaximumFloat16, MaximumFloat16Test)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1ElementFloat16, MaximumBroadcast1ElementFloat16Test)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1DVectorFloat16, MaximumBroadcast1DVectorFloat16Test)\nARMNN_AUTO_TEST_CASE(MaximumUint8, MaximumUint8Test)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1ElementUint8, MaximumBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1DVectorUint8, MaximumBroadcast1DVectorUint8Test)\nARMNN_AUTO_TEST_CASE(MaximumInt16, MaximumInt16Test)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1ElementInt16, MaximumBroadcast1ElementInt16Test)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1DVectorInt16, MaximumBroadcast1DVectorInt16Test)\n\n// Min\nARMNN_AUTO_TEST_CASE(SimpleMinimum1, MinimumBroadcast1ElementTest1)\nARMNN_AUTO_TEST_CASE(SimpleMinimum2, MinimumBroadcast1ElementTest2)\nARMNN_AUTO_TEST_CASE(Minimum1DVectorUint8, MinimumBroadcast1DVectorUint8Test)\nARMNN_AUTO_TEST_CASE(MinimumFloat16, MinimumFloat16Test)\nARMNN_AUTO_TEST_CASE(MinimumBroadcast1ElementFloat16, MinimumBroadcast1ElementFloat16Test)\nARMNN_AUTO_TEST_CASE(MinimumBroadcast1DVectorFloat16, MinimumBroadcast1DVectorFloat16Test)\nARMNN_AUTO_TEST_CASE(MinimumInt16, MinimumInt16Test)\nARMNN_AUTO_TEST_CASE(MinimumBroadcast1ElementInt16, MinimumBroadcast1ElementInt16Test)\nARMNN_AUTO_TEST_CASE(MinimumBroadcast1DVectorInt16, MinimumBroadcast1DVectorInt16Test)\n\n// Mul\nARMNN_AUTO_TEST_CASE(SimpleMultiplication, MultiplicationTest)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1Element, MultiplicationBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1DVector, MultiplicationBroadcast1DVectorTest)\nARMNN_AUTO_TEST_CASE(MultiplicationUint8, MultiplicationUint8Test)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1ElementUint8, MultiplicationBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1DVectorUint8, MultiplicationBroadcast1DVectorUint8Test)\nARMNN_AUTO_TEST_CASE(MultiplicationInt16, MultiplicationInt16Test)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1ElementInt16, MultiplicationBroadcast1ElementInt16Test)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1DVectorInt16, MultiplicationBroadcast1DVectorInt16Test)\nARMNN_AUTO_TEST_CASE(Multiplication5d, Multiplication5dTest)\n\n// Batch Norm\nARMNN_AUTO_TEST_CASE(BatchNormFloat32, BatchNormFloat32Test)\nARMNN_AUTO_TEST_CASE(BatchNormFloat32Nhwc, BatchNormFloat32NhwcTest)\nARMNN_AUTO_TEST_CASE(BatchNormFloat16, BatchNormFloat16Test)\nARMNN_AUTO_TEST_CASE(BatchNormFloat16Nhwc, BatchNormFloat16NhwcTest)\nARMNN_AUTO_TEST_CASE(BatchNormUint8, BatchNormUint8Test)\nARMNN_AUTO_TEST_CASE(BatchNormUint8Nhwc, BatchNormUint8NhwcTest)\nARMNN_AUTO_TEST_CASE(BatchNormInt16, BatchNormInt16Test)\nARMNN_AUTO_TEST_CASE(BatchNormInt16Nhwc, BatchNormInt16NhwcTest)\n\n// Resize Bilinear - NCHW\nARMNN_AUTO_TEST_CASE(SimpleResizeBilinear,\n                     SimpleResizeBilinearTest<DataType::Float32>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleResizeBilinearFloat16,\n                     SimpleResizeBilinearTest<DataType::Float16>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleResizeBilinearUint8,\n                     SimpleResizeBilinearTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleResizeBilinearUint16,\n                     SimpleResizeBilinearTest<DataType::QuantisedSymm16>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearNop,\n                     ResizeBilinearNopTest<DataType::Float32>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearNopFloat16,\n                     ResizeBilinearNopTest<DataType::Float16>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearNopUint8,\n                     ResizeBilinearNopTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(esizeBilinearNopUint16,\n                     SimpleResizeBilinearTest<DataType::QuantisedSymm16>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearSqMin,\n                     ResizeBilinearSqMinTest<DataType::Float32>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearSqMinFloat16,\n                     ResizeBilinearSqMinTest<DataType::Float16>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearSqMinUint8,\n                     ResizeBilinearSqMinTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearSqMinUint16,\n                     SimpleResizeBilinearTest<DataType::QuantisedSymm16>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMin,\n                     ResizeBilinearMinTest<DataType::Float32>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMinFloat16,\n                     ResizeBilinearMinTest<DataType::Float16>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMinUint8,\n                     ResizeBilinearMinTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMinUint16,\n                     SimpleResizeBilinearTest<DataType::QuantisedSymm16>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMag,\n                     ResizeBilinearMagTest<DataType::Float32>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMagFloat16,\n                     ResizeBilinearMagTest<DataType::Float16>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMagUint8,\n                     ResizeBilinearMagTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMagUint16,\n                     SimpleResizeBilinearTest<DataType::QuantisedSymm16>,\n                     DataLayout::NCHW)\n\n// Resize Bilinear - NHWC\nARMNN_AUTO_TEST_CASE(ResizeBilinearNopNhwc,\n                     ResizeBilinearNopTest<DataType::Float32>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearNopNhwcFloat16,\n                     ResizeBilinearNopTest<DataType::Float16>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearNopUint8Nhwc,\n                     ResizeBilinearNopTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearNopUint16Nhwc,\n                     ResizeBilinearNopTest<DataType::QuantisedSymm16>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleResizeBilinearNhwc,\n                     SimpleResizeBilinearTest<DataType::Float32>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleResizeBilinearNhwcFloat16,\n                     SimpleResizeBilinearTest<DataType::Float16>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleResizeBilinearUint8Nhwc,\n                     SimpleResizeBilinearTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleResizeBilinearUint16Nhwc,\n                     ResizeBilinearNopTest<DataType::QuantisedSymm16>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearSqMinNhwc,\n                     ResizeBilinearSqMinTest<DataType::Float32>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearSqMinNhwcFloat16,\n                     ResizeBilinearSqMinTest<DataType::Float16>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearSqMinUint8Nhwc,\n                     ResizeBilinearSqMinTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearSqMinUint16Nhwc,\n                     ResizeBilinearNopTest<DataType::QuantisedSymm16>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMinNhwc,\n                     ResizeBilinearMinTest<DataType::Float32>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMinNhwcFloat16,\n                     ResizeBilinearMinTest<DataType::Float16>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMinUint8Nhwc,\n                     ResizeBilinearMinTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMinUint16Nhwc,\n                     ResizeBilinearNopTest<DataType::QuantisedSymm16>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMagNhwc,\n                     ResizeBilinearMagTest<DataType::Float32>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMagNhwcFloat16,\n                     ResizeBilinearMagTest<DataType::Float16>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMagUint8Nhwc,\n                     ResizeBilinearMagTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMagUint16Nhwc,\n                     ResizeBilinearNopTest<DataType::QuantisedSymm16>,\n                     DataLayout::NHWC)\n\n// Resize NearestNeighbor - NCHW\nARMNN_AUTO_TEST_CASE(SimpleResizeNearestNeighbor,\n                     SimpleResizeNearestNeighborTest<DataType::Float32>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleResizeNearestNeighborUint8,\n                     SimpleResizeNearestNeighborTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleResizeNearestNeighborUint16,\n                     SimpleResizeNearestNeighborTest<DataType::QuantisedSymm16>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborNop,\n                     ResizeNearestNeighborNopTest<DataType::Float32>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborNopUint8,\n                     ResizeNearestNeighborNopTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(esizeNearestNeighborNopUint16,\n                     SimpleResizeNearestNeighborTest<DataType::QuantisedSymm16>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborSqMin,\n                     ResizeNearestNeighborSqMinTest<DataType::Float32>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborSqMinUint8,\n                     ResizeNearestNeighborSqMinTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborSqMinUint16,\n                     SimpleResizeNearestNeighborTest<DataType::QuantisedSymm16>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborMin,\n                     ResizeNearestNeighborMinTest<DataType::Float32>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborMinUint8,\n                     ResizeNearestNeighborMinTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborMinUint16,\n                     SimpleResizeNearestNeighborTest<DataType::QuantisedSymm16>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborMag,\n                     ResizeNearestNeighborMagTest<DataType::Float32>,\n                     DataLayout::NCHW, 0.10f, 50, 0.11f, 20)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborMagUint8,\n                     ResizeNearestNeighborMagTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NCHW, 0.10f, 50, 0.11f, 20)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborMagUint16,\n                     SimpleResizeNearestNeighborTest<DataType::QuantisedSymm16>,\n                     DataLayout::NCHW)\n\n// Resize NearestNeighbor - NHWC\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborNopNhwc,\n                     ResizeNearestNeighborNopTest<DataType::Float32>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborNopUint8Nhwc,\n                     ResizeNearestNeighborNopTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborNopUint16Nhwc,\n                     ResizeNearestNeighborNopTest<DataType::QuantisedSymm16>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleResizeNearestNeighborNhwc,\n                     SimpleResizeNearestNeighborTest<DataType::Float32>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleResizeNearestNeighborUint8Nhwc,\n                     SimpleResizeNearestNeighborTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleResizeNearestNeighborUint16Nhwc,\n                     ResizeNearestNeighborNopTest<DataType::QuantisedSymm16>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborSqMinNhwc,\n                     ResizeNearestNeighborSqMinTest<DataType::Float32>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborSqMinUint8Nhwc,\n                     ResizeNearestNeighborSqMinTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborSqMinUint16Nhwc,\n                     ResizeNearestNeighborNopTest<DataType::QuantisedSymm16>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborMinNhwc,\n                     ResizeNearestNeighborMinTest<DataType::Float32>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborMinUint8Nhwc,\n                     ResizeNearestNeighborMinTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborMinUint16Nhwc,\n                     ResizeNearestNeighborNopTest<DataType::QuantisedSymm16>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborMagNhwc,\n                     ResizeNearestNeighborMagTest<DataType::Float32>,\n                     DataLayout::NHWC, 0.10f, 50, 0.11f, 20)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborMagUint8Nhwc,\n                     ResizeNearestNeighborMagTest<DataType::QuantisedAsymm8>,\n                     DataLayout::NHWC, 0.10f, 50, 0.11f, 20)\nARMNN_AUTO_TEST_CASE(ResizeNearestNeighborMagUint16Nhwc,\n                     ResizeNearestNeighborNopTest<DataType::QuantisedSymm16>,\n                     DataLayout::NHWC)\n\n// Fake Quantization\nARMNN_AUTO_TEST_CASE(FakeQuantization, FakeQuantizationTest)\n\n// L2 Normalization\nARMNN_AUTO_TEST_CASE(L2Normalization1d, L2Normalization1dTest, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(L2Normalization2d, L2Normalization2dTest, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(L2Normalization3d, L2Normalization3dTest, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(L2Normalization4d, L2Normalization4dTest, DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(L2Normalization1dInt16, L2Normalization1dInt16Test, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(L2Normalization2dInt16, L2Normalization2dInt16Test, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(L2Normalization3dInt16, L2Normalization3dInt16Test, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(L2Normalization4dInt16, L2Normalization4dInt16Test, DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(L2Normalization1dUint8, L2Normalization1dUint8Test, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(L2Normalization2dUint8, L2Normalization2dUint8Test, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(L2Normalization3dUint8, L2Normalization3dUint8Test, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(L2Normalization4dUint8, L2Normalization4dUint8Test, DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(L2Normalization1dNhwc, L2Normalization1dTest, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(L2Normalization2dNhwc, L2Normalization2dTest, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(L2Normalization3dNhwc, L2Normalization3dTest, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(L2Normalization4dNhwc, L2Normalization4dTest, DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(L2Normalization1dInt16Nhwc, L2Normalization1dInt16Test, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(L2Normalization2dInt16Nhwc, L2Normalization2dInt16Test, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(L2Normalization3dInt16Nhwc, L2Normalization3dInt16Test, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(L2Normalization4dInt16Nhwc, L2Normalization4dInt16Test, DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(L2Normalization1dUint8Nhwc, L2Normalization1dUint8Test, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(L2Normalization2dUint8Nhwc, L2Normalization2dUint8Test, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(L2Normalization3dUint8Nhwc, L2Normalization3dUint8Test, DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(L2Normalization4dUint8Nhwc, L2Normalization4dUint8Test, DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(L2Normalization2dShape, L2Normalization2dShapeTest);\n\nARMNN_AUTO_TEST_CASE(L2NormalizationDefaultEpsilon, L2NormalizationDefaultEpsilonTest, DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(L2NormalizationNonDefaultEpsilon, L2NormalizationNonDefaultEpsilonTest, DataLayout::NCHW)\n\n// LogSoftmax\nARMNN_AUTO_TEST_CASE(LogSoftmaxFloat32_1, LogSoftmaxTest1<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(LogSoftmaxFloat32_2, LogSoftmaxTest2<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(LogSoftmaxFloat32_3, LogSoftmaxTest3<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(LogSoftmaxFloat32_4, LogSoftmaxTest4<DataType::Float32>)\n\nARMNN_AUTO_TEST_CASE(LogSoftmaxFloat16_1, LogSoftmaxTest1<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(LogSoftmaxFloat16_2, LogSoftmaxTest2<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(LogSoftmaxFloat16_3, LogSoftmaxTest3<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(LogSoftmaxFloat16_4, LogSoftmaxTest4<DataType::Float16>)\n\n// Pad\nARMNN_AUTO_TEST_CASE(PadFloat322d, PadFloat322dTest)\nARMNN_AUTO_TEST_CASE(PadFloat322dCustomPadding, PadFloat322dCustomPaddingTest)\nARMNN_AUTO_TEST_CASE(PadFloat323d, PadFloat323dTest)\nARMNN_AUTO_TEST_CASE(PadFloat324d, PadFloat324dTest)\n\nARMNN_AUTO_TEST_CASE(PadUint82d, PadUint82dTest)\nARMNN_AUTO_TEST_CASE(PadUint82dCustomPadding, PadUint82dCustomPaddingTest)\nARMNN_AUTO_TEST_CASE(PadUint83d, PadUint83dTest)\nARMNN_AUTO_TEST_CASE(PadUint84d, PadUint84dTest)\n\nARMNN_AUTO_TEST_CASE(Pad2dQSymm16, Pad2dTestCommon<DataType::QuantisedSymm16>, 2.0f, 0, 0.0f)\nARMNN_AUTO_TEST_CASE(Pad2dQSymm16CustomPadding, Pad2dTestCommon<DataType::QuantisedSymm16>, 2.0f, 0, 1.0f)\nARMNN_AUTO_TEST_CASE(Pad3dQSymm16, Pad3dTestCommon<DataType::QuantisedSymm16>, 2.0f, 0)\nARMNN_AUTO_TEST_CASE(Pad4dQSymm16, Pad4dTestCommon<DataType::QuantisedSymm16>, 2.0f, 0)\n\n// Constant\nARMNN_AUTO_TEST_CASE(Constant, ConstantTest)\nARMNN_AUTO_TEST_CASE(ConstantUint8, ConstantUint8CustomQuantizationScaleAndOffsetTest)\nARMNN_AUTO_TEST_CASE(ConstantInt16, ConstantInt16CustomQuantizationScaleAndOffsetTest)\n\n// Concat\nARMNN_AUTO_TEST_CASE(Concat1d, Concat1dTest)\nARMNN_AUTO_TEST_CASE(Concat1dUint8, Concat1dUint8Test)\n\nARMNN_AUTO_TEST_CASE(Concat2dDim0, Concat2dDim0Test)\nARMNN_AUTO_TEST_CASE(Concat2dDim0Uint8, Concat2dDim0Uint8Test)\nARMNN_AUTO_TEST_CASE(Concat2dDim1, Concat2dDim1Test)\nARMNN_AUTO_TEST_CASE(Concat2dDim1Uint8, Concat2dDim1Uint8Test)\n\nARMNN_AUTO_TEST_CASE(Concat2dDim0DiffInputDims, Concat2dDim0DiffInputDimsTest)\nARMNN_AUTO_TEST_CASE(Concat2dDim0DiffInputDimsUint8, Concat2dDim0DiffInputDimsUint8Test)\nARMNN_AUTO_TEST_CASE(Concat2dDim1DiffInputDims, Concat2dDim1DiffInputDimsTest)\nARMNN_AUTO_TEST_CASE(Concat2dDim1DiffInputDimsUint8, Concat2dDim1DiffInputDimsUint8Test)\n\nARMNN_AUTO_TEST_CASE(Concat3dDim0, Concat3dDim0Test)\nARMNN_AUTO_TEST_CASE(Concat3dDim0Uint8, Concat3dDim0Uint8Test)\nARMNN_AUTO_TEST_CASE(Concat3dDim1, Concat3dDim1Test)\nARMNN_AUTO_TEST_CASE(Concat3dDim1Uint8, Concat3dDim1Uint8Test)\nARMNN_AUTO_TEST_CASE(Concat3dDim2, Concat3dDim2Test, true)\nARMNN_AUTO_TEST_CASE(Concat3dDim2Uint8, Concat3dDim2Uint8Test, true)\n\nARMNN_AUTO_TEST_CASE(Concat3dDim0DiffInputDims, Concat3dDim0DiffInputDimsTest)\nARMNN_AUTO_TEST_CASE(Concat3dDim0DiffInputDimsUint8, Concat3dDim0DiffInputDimsUint8Test)\nARMNN_AUTO_TEST_CASE(Concat3dDim1DiffInputDims, Concat3dDim1DiffInputDimsTest)\nARMNN_AUTO_TEST_CASE(Concat3dDim1DiffInputDimsUint8, Concat3dDim1DiffInputDimsUint8Test)\nARMNN_AUTO_TEST_CASE(Concat3dDim2DiffInputDims, Concat3dDim2DiffInputDimsTest, true)\nARMNN_AUTO_TEST_CASE(Concat3dDim2DiffInputDimsUint8, Concat3dDim2DiffInputDimsUint8Test, true)\n\nARMNN_AUTO_TEST_CASE(Concat4dDim0, Concat4dDim0Test)\nARMNN_AUTO_TEST_CASE(Concat4dDim1, Concat4dDim1Test)\nARMNN_AUTO_TEST_CASE(Concat4dDim2, Concat4dDim2Test)\nARMNN_AUTO_TEST_CASE(Concat4dDim3, Concat4dDim3Test, true)\nARMNN_AUTO_TEST_CASE(Concat4dDim0Uint8, Concat4dDim0Uint8Test)\nARMNN_AUTO_TEST_CASE(Concat4dDim1Uint8, Concat4dDim1Uint8Test)\nARMNN_AUTO_TEST_CASE(Concat4dDim2Uint8, Concat4dDim2Uint8Test)\nARMNN_AUTO_TEST_CASE(Concat4dDim3Uint8, Concat4dDim3Uint8Test, true)\n\nARMNN_AUTO_TEST_CASE(Concat4dDiffShapeDim0, Concat4dDiffShapeDim0Test)\nARMNN_AUTO_TEST_CASE(Concat4dDiffShapeDim1, Concat4dDiffShapeDim1Test)\nARMNN_AUTO_TEST_CASE(Concat4dDiffShapeDim2, Concat4dDiffShapeDim2Test)\nARMNN_AUTO_TEST_CASE(Concat4dDiffShapeDim3, Concat4dDiffShapeDim3Test, true)\nARMNN_AUTO_TEST_CASE(Concat4dDiffShapeDim0Uint8, Concat4dDiffShapeDim0Uint8Test)\nARMNN_AUTO_TEST_CASE(Concat4dDiffShapeDim1Uint8, Concat4dDiffShapeDim1Uint8Test)\nARMNN_AUTO_TEST_CASE(Concat4dDiffShapeDim2Uint8, Concat4dDiffShapeDim2Uint8Test)\nARMNN_AUTO_TEST_CASE(Concat4dDiffShapeDim3Uint8, Concat4dDiffShapeDim3Uint8Test, true)\n\n// Floor\nARMNN_AUTO_TEST_CASE(SimpleFloor, SimpleFloorTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(SimpleFloorFloat16, SimpleFloorTest<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(SimpleFloorQuantisedSymm16, SimpleFloorTest<DataType::QuantisedSymm16>)\n\n// Reshape\nARMNN_AUTO_TEST_CASE(SimpleReshapeFloat32, SimpleReshapeTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(SimpleReshapeQuantisedAsymm8, SimpleReshapeTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(SimpleReshapeQuantisedSymm16, SimpleReshapeTest<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(Reshape5d, Reshape5dTest<DataType::Float32>)\n\n// Rsqrt\nARMNN_AUTO_TEST_CASE(Rsqrt2d, Rsqrt2dTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(Rsqrt3d, Rsqrt3dTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(RsqrtZero, RsqrtZeroTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(RsqrtNegative, RsqrtNegativeTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(Rsqrt2dFloat16, Rsqrt2dTest<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(Rsqrt3dFloat16, Rsqrt3dTest<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(Rsqrt2dQuantisedAsymm8, Rsqrt2dTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(Rsqrt3dQuantisedAsymm8, Rsqrt3dTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(Rsqrt2dQuantisedSymm16, Rsqrt2dTest<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(Rsqrt3dQuantisedSymm16, Rsqrt3dTest<DataType::QuantisedSymm16>)\n\n// Permute\nARMNN_AUTO_TEST_CASE(SimplePermuteFloat32, SimplePermuteTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(PermuteFloat32ValueSet1Test, PermuteValueSet1Test<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(PermuteFloat32ValueSet2Test, PermuteValueSet2Test<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(PermuteFloat32ValueSet3Test, PermuteValueSet3Test<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(SimplePermuteQASymm8, SimplePermuteTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(PermuteQASymm8ValueSet1Test, PermuteValueSet1Test<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(PermuteQASymm8ValueSet2Test, PermuteValueSet2Test<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(PermuteQASymm8ValueSet3Test, PermuteValueSet3Test<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(SimplePermuteQSymm16, SimplePermuteTest<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(PermuteQSymm16ValueSet1Test, PermuteValueSet1Test<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(PermuteQSymm16ValueSet2Test, PermuteValueSet2Test<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(PermuteQSymm16ValueSet3Test, PermuteValueSet3Test<DataType::QuantisedSymm16>)\n\n// Lstm\nBOOST_AUTO_TEST_CASE(LstmUtilsZeroVector) {\n                     LstmUtilsZeroVectorTest(); }\nBOOST_AUTO_TEST_CASE(LstmUtilsMeanStddevNormalization) {\n                     LstmUtilsMeanStddevNormalizationNoneZeroInputTest();\n                     LstmUtilsMeanStddevNormalizationAllZeroInputTest();\n                     LstmUtilsMeanStddevNormalizationMixedZeroInputTest(); }\nBOOST_AUTO_TEST_CASE(LstmUtilsVectorBatchVectorCwiseProduct) {\n                     LstmUtilsVectorBatchVectorCwiseProductTest(); }\nBOOST_AUTO_TEST_CASE(LstmUtilsVectorBatchVectorAdd) {\n                     LstmUtilsVectorBatchVectorAddTest(); }\n\nARMNN_AUTO_TEST_CASE(LstmLayerFloat32WithCifgWithPeepholeNoProjection,\n                     LstmLayerFloat32WithCifgWithPeepholeNoProjectionTest)\nARMNN_AUTO_TEST_CASE(LstmLayerFloat32NoCifgNoPeepholeNoProjection,\n                     LstmLayerFloat32NoCifgNoPeepholeNoProjectionTest)\nARMNN_AUTO_TEST_CASE(LstmLayerFloat32NoCifgWithPeepholeWithProjection,\n                     LstmLayerFloat32NoCifgWithPeepholeWithProjectionTest)\n\nARMNN_AUTO_TEST_CASE(LstmLayerFloat32NoCifgWithPeepholeWithProjectionWithLayerNorm,\n                     LstmLayerFloat32NoCifgWithPeepholeWithProjectionWithLayerNormTest)\n\nARMNN_AUTO_TEST_CASE(LstmLayerInt16NoCifgNoPeepholeNoProjection,\n                     LstmLayerInt16NoCifgNoPeepholeNoProjectionTest)\nARMNN_AUTO_TEST_CASE(LstmLayerInt16WithCifgWithPeepholeNoProjection,\n                     LstmLayerInt16WithCifgWithPeepholeNoProjectionTest)\nARMNN_AUTO_TEST_CASE(LstmLayerInt16NoCifgWithPeepholeWithProjection,\n                     LstmLayerInt16NoCifgWithPeepholeWithProjectionTest)\nARMNN_AUTO_TEST_CASE(LstmLayerInt16NoCifgNoPeepholeNoProjectionInt16Constant,\n                     LstmLayerInt16NoCifgNoPeepholeNoProjectionInt16ConstantTest)\n\n// Convert from Float16 to Float32\nARMNN_AUTO_TEST_CASE(SimpleConvertFp16ToFp32, SimpleConvertFp16ToFp32Test)\n// Convert from Float32 to Float16\nARMNN_AUTO_TEST_CASE(SimpleConvertFp32ToFp16, SimpleConvertFp32ToFp16Test)\n\n// Mean\nARMNN_AUTO_TEST_CASE(MeanSimpleFloat32, MeanSimpleTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(MeanSimpleAxisFloat32, MeanSimpleAxisTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(MeanKeepDimsFloat32, MeanKeepDimsTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(MeanMultipleDimsFloat32, MeanMultipleDimsTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(MeanVts1Float32, MeanVts1Test<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(MeanVts2Float32, MeanVts2Test<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(MeanVts3Float32, MeanVts3Test<DataType::Float32>)\n\nARMNN_AUTO_TEST_CASE(MeanSimpleQuantisedAsymm8, MeanSimpleTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(MeanSimpleAxisQuantisedAsymm8, MeanSimpleAxisTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(MeanKeepDimsQuantisedAsymm8, MeanKeepDimsTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(MeanMultipleDimsQuantisedAsymm8, MeanMultipleDimsTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(MeanVts1QuantisedAsymm8, MeanVts1Test<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(MeanVts2QuantisedAsymm8, MeanVts2Test<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(MeanVts3QuantisedAsymm8, MeanVts3Test<DataType::QuantisedAsymm8>)\n\nARMNN_AUTO_TEST_CASE(MeanSimpleQuantisedSymm16, MeanSimpleTest<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(MeanSimpleAxisQuantisedSymm16, MeanSimpleAxisTest<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(MeanKeepDimsQuantisedSymm16, MeanKeepDimsTest<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(MeanMultipleDimsQuantisedSymm16, MeanMultipleDimsTest<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(MeanVts1QuantisedSymm16, MeanVts1Test<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(MeanVts2QuantisedSymm16, MeanVts2Test<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(MeanVts3QuantisedSymm16, MeanVts3Test<DataType::QuantisedSymm16>)\n\nARMNN_AUTO_TEST_CASE(AdditionAfterMaxPool, AdditionAfterMaxPoolTest)\n\n// ArgMinMax\nARMNN_AUTO_TEST_CASE(ArgMaxFloat32, ArgMaxSimpleTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(ArgMinFloat32, ArgMinSimpleTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(ArgMinChannelFloat32, ArgMinChannelTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(ArgMaxChannelFloat32, ArgMaxChannelTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(ArgMaxHeightFloat32, ArgMaxHeightTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(ArgMinWidthFloat32, ArgMinWidthTest<DataType::Float32>)\n\nARMNN_AUTO_TEST_CASE(ArgMaxSigned32, ArgMaxSimpleTest<DataType::Signed32>)\nARMNN_AUTO_TEST_CASE(ArgMinSigned32, ArgMinSimpleTest<DataType::Signed32>)\nARMNN_AUTO_TEST_CASE(ArgMinChannelSigned32, ArgMinChannelTest<DataType::Signed32>)\nARMNN_AUTO_TEST_CASE(ArgMaxChannelSigned32, ArgMaxChannelTest<DataType::Signed32>)\nARMNN_AUTO_TEST_CASE(ArgMaxHeightSigned32, ArgMaxHeightTest<DataType::Signed32>)\nARMNN_AUTO_TEST_CASE(ArgMinWidthSigned32, ArgMinWidthTest<DataType::Signed32>)\n\nARMNN_AUTO_TEST_CASE(ArgMaxSimpleQuantisedAsymm8, ArgMaxSimpleTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(ArgMinSimpleQuantisedAsymm8, ArgMinSimpleTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(ArgMinChannelQuantisedAsymm8, ArgMinChannelTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(ArgMaxChannelQuantisedAsymm8, ArgMaxChannelTest<DataType::QuantisedAsymm8>)\n\nARMNN_AUTO_TEST_CASE(ArgMaxSimpleQuantisedSymm16, ArgMaxSimpleTest<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(ArgMinSimpleQuantisedSymm16, ArgMinSimpleTest<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(ArgMinChannelQuantisedSymm16, ArgMinChannelTest<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(ArgMaxChannelQuantisedSymm16, ArgMaxChannelTest<DataType::QuantisedSymm16>)\n\n// Space To Batch Nd\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdSimpleFloat32, SpaceToBatchNdSimpleFloat32Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiChannelsFloat32, SpaceToBatchNdMultiChannelsFloat32Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiBlockFloat32, SpaceToBatchNdMultiBlockFloat32Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdPaddingFloat32, SpaceToBatchNdPaddingFloat32Test)\n\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdSimpleFloat16, SpaceToBatchNdSimpleFloat16Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiChannelsFloat16, SpaceToBatchNdMultiChannelsFloat16Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiBlockFloat16, SpaceToBatchNdMultiBlockFloat16Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdPaddingFloat16, SpaceToBatchNdPaddingFloat16Test)\n\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdSimpleUint8, SpaceToBatchNdSimpleUint8Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiChannelsUint8, SpaceToBatchNdMultiChannelsUint8Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiBlockUint8, SpaceToBatchNdMultiBlockUint8Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdPaddingUint8, SpaceToBatchNdPaddingUint8Test)\n\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdSimpleNhwcFloat32, SpaceToBatchNdSimpleNhwcFloat32Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiChannelsNhwcFloat32, SpaceToBatchNdMultiChannelsNhwcFloat32Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiBlockNhwcFloat32, SpaceToBatchNdMultiBlockNhwcFloat32Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdPaddingNhwcFloat32, SpaceToBatchNdPaddingNhwcFloat32Test)\n\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdSimpleNhwcFloat16, SpaceToBatchNdSimpleNhwcFloat16Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiChannelsNhwcFloat16, SpaceToBatchNdMultiChannelsNhwcFloat16Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiBlockNhwcFloat16, SpaceToBatchNdMultiBlockNhwcFloat16Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdPaddingNhwcFloat16, SpaceToBatchNdPaddingNhwcFloat16Test)\n\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdSimpleNhwcUint8, SpaceToBatchNdSimpleNhwcUint8Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiChannelsNhwcUint8, SpaceToBatchNdMultiChannelsNhwcUint8Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiBlockNhwcUint8, SpaceToBatchNdMultiBlockNhwcUint8Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdPaddingNhwcUint8, SpaceToBatchNdPaddingNhwcUint8Test)\n\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdSimpleUint16, SpaceToBatchNdSimpleUint16Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiChannelsUint16, SpaceToBatchNdMultiChannelsUint16Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiBlockUint16, SpaceToBatchNdMultiBlockUint16Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdPaddingUint16, SpaceToBatchNdPaddingUint16Test)\n\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdSimpleNhwcUint16, SpaceToBatchNdSimpleNhwcUint16Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiChannelsNhwcUint16, SpaceToBatchNdMultiChannelsNhwcUint16Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiBlockNhwcUint16, SpaceToBatchNdMultiBlockNhwcUint16Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdPaddingNhwcUint16, SpaceToBatchNdPaddingNhwcUint16Test)\n\n// BatchToSpace\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat32_1, BatchToSpaceNdNhwcTest1<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat32_2, BatchToSpaceNdNhwcTest2<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat32_3, BatchToSpaceNdNhwcTest3<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat32_4, BatchToSpaceNdNhwcTest4<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat32_5, BatchToSpaceNdNhwcTest5<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat32_6, BatchToSpaceNdNhwcTest6<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat32_7, BatchToSpaceNdNhwcTest7<DataType::Float32>)\n\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat16_1, BatchToSpaceNdNhwcTest1<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat16_2, BatchToSpaceNdNhwcTest2<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat16_3, BatchToSpaceNdNhwcTest3<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat16_4, BatchToSpaceNdNhwcTest4<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat16_5, BatchToSpaceNdNhwcTest5<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat16_6, BatchToSpaceNdNhwcTest6<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat16_7, BatchToSpaceNdNhwcTest7<DataType::Float16>)\n\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcUint1,  BatchToSpaceNdNhwcTest1<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcUint2,  BatchToSpaceNdNhwcTest2<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcUint3,  BatchToSpaceNdNhwcTest3<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcUint4,  BatchToSpaceNdNhwcTest4<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcUint5,  BatchToSpaceNdNhwcTest5<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcUint6,  BatchToSpaceNdNhwcTest6<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcUint7,  BatchToSpaceNdNhwcTest7<DataType::QuantisedAsymm8>)\n\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcQsymm16_1,  BatchToSpaceNdNhwcTest1<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcQsymm16_2,  BatchToSpaceNdNhwcTest2<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcQsymm16_3,  BatchToSpaceNdNhwcTest3<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcQsymm16_4,  BatchToSpaceNdNhwcTest4<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcQsymm16_5,  BatchToSpaceNdNhwcTest5<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcQsymm16_6,  BatchToSpaceNdNhwcTest6<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcQsymm16_7,  BatchToSpaceNdNhwcTest7<DataType::QuantisedSymm16>)\n\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwFloat16_1, BatchToSpaceNdNchwTest1<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwFloat16_2, BatchToSpaceNdNchwTest2<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwFloat16_3, BatchToSpaceNdNchwTest3<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwFloat16_4, BatchToSpaceNdNchwTest4<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwFloat16_5, BatchToSpaceNdNchwTest5<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwFloat16_6, BatchToSpaceNdNchwTest6<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwFloat16_7, BatchToSpaceNdNchwTest7<DataType::Float16>)\n\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwUint1,  BatchToSpaceNdNchwTest1<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwUint2,  BatchToSpaceNdNchwTest2<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwUint3,  BatchToSpaceNdNchwTest3<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwUint4,  BatchToSpaceNdNchwTest4<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwUint5,  BatchToSpaceNdNchwTest5<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwUint6,  BatchToSpaceNdNchwTest6<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwUint7,  BatchToSpaceNdNchwTest7<DataType::QuantisedAsymm8>)\n\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwQsymm16_1,  BatchToSpaceNdNchwTest1<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwQsymm16_2,  BatchToSpaceNdNchwTest2<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwQsymm16_3,  BatchToSpaceNdNchwTest3<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwQsymm16_4,  BatchToSpaceNdNchwTest4<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwQsymm16_5,  BatchToSpaceNdNchwTest5<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwQsymm16_6,  BatchToSpaceNdNchwTest6<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwQsymm16_7,  BatchToSpaceNdNchwTest7<DataType::QuantisedSymm16>)\n\n// DepthToSpace\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwFloat32_1, DepthToSpaceTest1<DataType::Float32>, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwFloat32_2, DepthToSpaceTest2<DataType::Float32>, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwFloat32_3, DepthToSpaceTest3<DataType::Float32>, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwFloat32_4, DepthToSpaceTest4<DataType::Float32>, DataLayout::NCHW);\n\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwFloat16_1, DepthToSpaceTest1<DataType::Float16>, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwFloat16_2, DepthToSpaceTest2<DataType::Float16>, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwFloat16_3, DepthToSpaceTest3<DataType::Float16>, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwFloat16_4, DepthToSpaceTest4<DataType::Float16>, DataLayout::NCHW);\n\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwUint8_1, DepthToSpaceTest1<DataType::QuantisedAsymm8>, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwUint8_2, DepthToSpaceTest2<DataType::QuantisedAsymm8>, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwUint8_3, DepthToSpaceTest3<DataType::QuantisedAsymm8>, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwUint8_4, DepthToSpaceTest4<DataType::QuantisedAsymm8>, DataLayout::NCHW);\n\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwInt16_1, DepthToSpaceTest1<DataType::QuantisedSymm16>, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwInt16_2, DepthToSpaceTest2<DataType::QuantisedSymm16>, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwInt16_3, DepthToSpaceTest3<DataType::QuantisedSymm16>, DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNchwInt16_4, DepthToSpaceTest4<DataType::QuantisedSymm16>, DataLayout::NCHW);\n\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcFloat32_1, DepthToSpaceTest1<DataType::Float32>, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcFloat32_2, DepthToSpaceTest2<DataType::Float32>, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcFloat32_3, DepthToSpaceTest3<DataType::Float32>, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcFloat32_4, DepthToSpaceTest4<DataType::Float32>, DataLayout::NHWC);\n\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcFloat16_1, DepthToSpaceTest1<DataType::Float16>, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcFloat16_2, DepthToSpaceTest2<DataType::Float16>, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcFloat16_3, DepthToSpaceTest3<DataType::Float16>, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcFloat16_4, DepthToSpaceTest4<DataType::Float16>, DataLayout::NHWC);\n\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcUint8_1, DepthToSpaceTest1<DataType::QuantisedAsymm8>, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcUint8_2, DepthToSpaceTest2<DataType::QuantisedAsymm8>, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcUint8_3, DepthToSpaceTest3<DataType::QuantisedAsymm8>, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcUint8_4, DepthToSpaceTest4<DataType::QuantisedAsymm8>, DataLayout::NHWC);\n\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcInt16_1, DepthToSpaceTest1<DataType::QuantisedSymm16>, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcInt16_2, DepthToSpaceTest2<DataType::QuantisedSymm16>, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcInt16_3, DepthToSpaceTest3<DataType::QuantisedSymm16>, DataLayout::NHWC);\nARMNN_AUTO_TEST_CASE(DepthToSpaceNhwcInt16_4, DepthToSpaceTest4<DataType::QuantisedSymm16>, DataLayout::NHWC);\n\n// SpaceToDepth\nARMNN_AUTO_TEST_CASE(SpaceToDepthNchwAsymmQ8, SpaceToDepthNchwAsymmQ8Test)\nARMNN_AUTO_TEST_CASE(SpaceToDepthNhwcAsymmQ8, SpaceToDepthNhwcAsymmQ8Test)\n\nARMNN_AUTO_TEST_CASE(SpaceToDepthNhwc1Float32, SpaceToDepthNhwcFloat32Test1)\nARMNN_AUTO_TEST_CASE(SpaceToDepthNchw1Float32, SpaceToDepthNchwFloat32Test1)\n\nARMNN_AUTO_TEST_CASE(SpaceToDepthNhwc2Float32, SpaceToDepthNhwcFloat32Test2)\nARMNN_AUTO_TEST_CASE(SpaceToDepthNchw2Float32, SpaceToDepthNchwFloat32Test2)\n\nARMNN_AUTO_TEST_CASE(SpaceToDepthNhwcQSymm16, SpaceToDepthNhwcQSymm16Test)\nARMNN_AUTO_TEST_CASE(SpaceToDepthNchwQSymm16, SpaceToDepthNchwQSymm16Test)\n\n// Strided Slice\nARMNN_AUTO_TEST_CASE(StridedSlice4dFloat32, StridedSlice4dFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSlice4dReverseFloat32, StridedSlice4dReverseFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceSimpleStrideFloat32, StridedSliceSimpleStrideFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceSimpleRangeMaskFloat32, StridedSliceSimpleRangeMaskFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskFloat32, StridedSliceShrinkAxisMaskFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskCTSFloat32, StridedSliceShrinkAxisMaskCTSFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition0Dim3Float32,\n                     StridedSliceShrinkAxisMaskBitPosition0Dim3Float32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition0Float32, StridedSliceShrinkAxisMaskBitPosition0Float32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition1Float32, StridedSliceShrinkAxisMaskBitPosition1Float32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition2Float32, StridedSliceShrinkAxisMaskBitPosition2Float32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition3Float32, StridedSliceShrinkAxisMaskBitPosition3Float32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition0And1Float32,\n                     StridedSliceShrinkAxisMaskBitPosition0And1Float32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition0And2Float32,\n                     StridedSliceShrinkAxisMaskBitPosition0And2Float32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition0And3Float32,\n                     StridedSliceShrinkAxisMaskBitPosition0And3Float32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition0And1And3Float32,\n                     StridedSliceShrinkAxisMaskBitPosition0And1And3Float32Test)\nARMNN_AUTO_TEST_CASE(StridedSlice3dFloat32, StridedSlice3dFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSlice3dReverseFloat32, StridedSlice3dReverseFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSlice2dFloat32, StridedSlice2dFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSlice2dReverseFloat32, StridedSlice2dReverseFloat32Test)\n\nARMNN_AUTO_TEST_CASE(StridedSlice4dUint8, StridedSlice4dUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSlice4dReverseUint8, StridedSlice4dReverseUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceSimpleStrideUint8, StridedSliceSimpleStrideUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceSimpleRangeMaskUint8, StridedSliceSimpleRangeMaskUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskUint8, StridedSliceShrinkAxisMaskUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition0Dim3Uint8,\n                     StridedSliceShrinkAxisMaskBitPosition0Dim3Uint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition0Uint8, StridedSliceShrinkAxisMaskBitPosition0Uint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition1Uint8, StridedSliceShrinkAxisMaskBitPosition1Uint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition2Uint8, StridedSliceShrinkAxisMaskBitPosition2Uint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition3Uint8, StridedSliceShrinkAxisMaskBitPosition3Uint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition0And1Uint8,\n                     StridedSliceShrinkAxisMaskBitPosition0And1Uint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition0And2Uint8,\n                     StridedSliceShrinkAxisMaskBitPosition0And2Uint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition0And3Uint8,\n                     StridedSliceShrinkAxisMaskBitPosition0And3Uint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskBitPosition0And1And3Uint8,\n                     StridedSliceShrinkAxisMaskBitPosition0And1And3Uint8Test)\nARMNN_AUTO_TEST_CASE(StridedSlice3dUint8, StridedSlice3dUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSlice3dReverseUint8, StridedSlice3dReverseUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSlice2dUint8, StridedSlice2dUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSlice2dReverseUint8, StridedSlice2dReverseUint8Test)\n\nARMNN_AUTO_TEST_CASE(StridedSlice4dInt16, StridedSlice4dInt16Test)\nARMNN_AUTO_TEST_CASE(StridedSlice4dReverseInt16, StridedSlice4dReverseInt16Test)\nARMNN_AUTO_TEST_CASE(StridedSliceSimpleStrideInt16, StridedSliceSimpleStrideInt16Test)\nARMNN_AUTO_TEST_CASE(StridedSliceSimpleRangeMaskInt16, StridedSliceSimpleRangeMaskInt16Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskInt16, StridedSliceShrinkAxisMaskInt16Test)\nARMNN_AUTO_TEST_CASE(StridedSlice3dInt16, StridedSlice3dInt16Test)\nARMNN_AUTO_TEST_CASE(StridedSlice3dReverseInt16, StridedSlice3dReverseInt16Test)\nARMNN_AUTO_TEST_CASE(StridedSlice2dInt16, StridedSlice2dInt16Test)\nARMNN_AUTO_TEST_CASE(StridedSlice2dReverseInt16, StridedSlice2dReverseInt16Test)\n\n// Debug\nARMNN_AUTO_TEST_CASE(Debug4dFloat32, Debug4dFloat32Test)\nARMNN_AUTO_TEST_CASE(Debug3dFloat32, Debug3dFloat32Test)\nARMNN_AUTO_TEST_CASE(Debug2dFloat32, Debug2dFloat32Test)\nARMNN_AUTO_TEST_CASE(Debug1dFloat32, Debug1dFloat32Test)\n\nARMNN_AUTO_TEST_CASE(Debug4dUint8, Debug4dUint8Test)\nARMNN_AUTO_TEST_CASE(Debug3dUint8, Debug3dUint8Test)\nARMNN_AUTO_TEST_CASE(Debug2dUint8, Debug2dUint8Test)\nARMNN_AUTO_TEST_CASE(Debug1dUint8, Debug1dUint8Test)\n\nARMNN_AUTO_TEST_CASE(Debug4dQSymm16, Debug4dInt16Test)\nARMNN_AUTO_TEST_CASE(Debug3dQSymm16, Debug3dInt16Test)\nARMNN_AUTO_TEST_CASE(Debug2dQSymm16, Debug2dInt16Test)\nARMNN_AUTO_TEST_CASE(Debug1dQSymm16, Debug1dInt16Test)\n\n// Gather\nARMNN_AUTO_TEST_CASE(Gather1dParamsFloat32, Gather1dParamsFloat32Test)\nARMNN_AUTO_TEST_CASE(Gather1dParamsFloat16, Gather1dParamsFloat16Test)\nARMNN_AUTO_TEST_CASE(Gather1dParamsUint8, Gather1dParamsUint8Test)\nARMNN_AUTO_TEST_CASE(Gather1dParamsInt16, Gather1dParamsInt16Test)\nARMNN_AUTO_TEST_CASE(GatherMultiDimParamsFloat32, GatherMultiDimParamsFloat32Test)\nARMNN_AUTO_TEST_CASE(GatherMultiDimParamsFloat16, GatherMultiDimParamsFloat16Test)\nARMNN_AUTO_TEST_CASE(GatherMultiDimParamsUint8, GatherMultiDimParamsUint8Test)\nARMNN_AUTO_TEST_CASE(GatherMultiDimParamsInt16, GatherMultiDimParamsInt16Test)\nARMNN_AUTO_TEST_CASE(GatherMultiDimParamsMultiDimIndicesFloat32, GatherMultiDimParamsMultiDimIndicesFloat32Test)\nARMNN_AUTO_TEST_CASE(GatherMultiDimParamsMultiDimIndicesFloat16, GatherMultiDimParamsMultiDimIndicesFloat16Test)\nARMNN_AUTO_TEST_CASE(GatherMultiDimParamsMultiDimIndicesUint8, GatherMultiDimParamsMultiDimIndicesUint8Test)\nARMNN_AUTO_TEST_CASE(GatherMultiDimParamsMultiDimIndicesInt16, GatherMultiDimParamsMultiDimIndicesInt16Test)\n\n// Abs\nARMNN_AUTO_TEST_CASE(Abs2d, Abs2dTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(Abs3d, Abs3dTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(AbsZero, AbsZeroTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(Abs2dFloat16, Abs2dTest<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(Abs3dFloat16, Abs3dTest<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(Abs2dQuantisedAsymm8, Abs2dTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(Abs3dQuantisedAsymm8, Abs3dTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(Abs2dQuantisedSymm16, Abs2dTest<DataType::QuantisedSymm16>)\nARMNN_AUTO_TEST_CASE(Abs3dQuantisedSymm16, Abs3dTest<DataType::QuantisedSymm16>)\n\n// Detection PostProcess\nBOOST_AUTO_TEST_CASE(DetectionPostProcessRegularNmsFloat)\n{\n    DetectionPostProcessRegularNmsFloatTest<RefWorkloadFactory>();\n}\nBOOST_AUTO_TEST_CASE(DetectionPostProcessFastNmsFloat)\n{\n    DetectionPostProcessFastNmsFloatTest<RefWorkloadFactory>();\n}\nBOOST_AUTO_TEST_CASE(DetectionPostProcessRegularNmsUint8)\n{\n    DetectionPostProcessRegularNmsQuantizedTest<\n        RefWorkloadFactory, DataType::QuantisedAsymm8>();\n}\nBOOST_AUTO_TEST_CASE(DetectionPostProcessFastNmsUint8)\n{\n    DetectionPostProcessRegularNmsQuantizedTest<\n        RefWorkloadFactory, DataType::QuantisedAsymm8>();\n}\nBOOST_AUTO_TEST_CASE(DetectionPostProcessRegularNmsInt16)\n{\n    DetectionPostProcessRegularNmsQuantizedTest<\n        RefWorkloadFactory, DataType::QuantisedSymm16>();\n}\nBOOST_AUTO_TEST_CASE(DetectionPostProcessFastNmsInt16)\n{\n    DetectionPostProcessFastNmsQuantizedTest<\n        RefWorkloadFactory, DataType::QuantisedSymm16>();\n}\n\n// Dequantize\nARMNN_AUTO_TEST_CASE(DequantizeSimpleUint8, DequantizeSimpleUint8Test)\nARMNN_AUTO_TEST_CASE(DequantizeOffsetUint8, DequantizeOffsetUint8Test)\nARMNN_AUTO_TEST_CASE(DequantizeSimpleInt16, DequantizeSimpleInt16Test)\nARMNN_AUTO_TEST_CASE(DequantizeSimpleUint8ToFp16, DequantizeSimpleUint8ToFp16Test)\nARMNN_AUTO_TEST_CASE(DequantizeSimpleInt16ToFp16, DequantizeSimpleInt16ToFp16Test)\n\n// Quantize\nARMNN_AUTO_TEST_CASE(QuantizeSimpleUint8, QuantizeSimpleUint8Test)\nARMNN_AUTO_TEST_CASE(QuantizeClampUint8, QuantizeClampUint8Test)\nARMNN_AUTO_TEST_CASE(QuantizeClampInt16, QuantizeClampInt16Test)\n\n// PReLU\nARMNN_AUTO_TEST_CASE(PreluFloat32, PreluTest<DataType::Float32>)\nARMNN_AUTO_TEST_CASE(PreluFloat16, PreluTest<DataType::Float16>)\nARMNN_AUTO_TEST_CASE(PreluUint8,   PreluTest<DataType::QuantisedAsymm8>)\nARMNN_AUTO_TEST_CASE(PreluInt16,   PreluTest<DataType::QuantisedSymm16>)\n\n// Slice\nARMNN_AUTO_TEST_CASE(Slice4dFloat32, Slice4dFloat32Test)\nARMNN_AUTO_TEST_CASE(Slice3dFloat32, Slice3dFloat32Test)\nARMNN_AUTO_TEST_CASE(Slice2dFloat32, Slice2dFloat32Test)\nARMNN_AUTO_TEST_CASE(Slice1dFloat32, Slice1dFloat32Test)\n\nARMNN_AUTO_TEST_CASE(Slice4dUint8, Slice4dUint8Test)\nARMNN_AUTO_TEST_CASE(Slice3dUint8, Slice3dUint8Test)\nARMNN_AUTO_TEST_CASE(Slice2dUint8, Slice2dUint8Test)\nARMNN_AUTO_TEST_CASE(Slice1dUint8, Slice1dUint8Test)\n\nARMNN_AUTO_TEST_CASE(Slice4dInt16, Slice4dInt16Test)\nARMNN_AUTO_TEST_CASE(Slice3dInt16, Slice3dInt16Test)\nARMNN_AUTO_TEST_CASE(Slice2dInt16, Slice2dInt16Test)\nARMNN_AUTO_TEST_CASE(Slice1dInt16, Slice1dInt16Test)\n\n// TransposeConvolution2d\nARMNN_AUTO_TEST_CASE(SimpleTransposeConvolution2dFloatNchw,\n                     SimpleTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleTransposeConvolution2dFloatNhwc,\n                     SimpleTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     true,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleTransposeConvolution2dUint8Nchw,\n                     SimpleTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleTransposeConvolution2dUint8Nhwc,\n                     SimpleTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     true,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleTransposeConvolution2dInt16Nchw,\n                     SimpleTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleTransposeConvolution2dInt16Nhwc,\n                     SimpleTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(UnbiasedSimpleTransposeConvolution2dFloatNchw,\n                     SimpleTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedSimpleTransposeConvolution2dFloatNhwc,\n                     SimpleTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     true,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedSimpleTransposeConvolution2dUint8Nchw,\n                     SimpleTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedSimpleTransposeConvolution2dUint8Nhwc,\n                     SimpleTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     true,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedSimpleTransposeConvolution2dInt16Nchw,\n                     SimpleTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedSimpleTransposeConvolution2dInt16Nhwc,\n                     SimpleTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(PaddedTransposeConvolution2dFloatNchw,\n                     PaddedTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(PaddedTransposeConvolution2dFloatNhwc,\n                     PaddedTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     true,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(PaddedTransposeConvolution2dUint8Nchw,\n                     PaddedTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(PaddedTransposeConvolution2dUint8Nhwc,\n                     PaddedTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     true,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(PaddedTransposeConvolution2dInt16Nchw,\n                     PaddedTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(PaddedTransposeConvolution2dInt16Nhwc,\n                     PaddedTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(UnbiasedPaddedTransposeConvolution2dFloatNchw,\n                     PaddedTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedPaddedTransposeConvolution2dFloatNhwc,\n                     PaddedTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     true,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedPaddedTransposeConvolution2dUint8Nchw,\n                     PaddedTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedPaddedTransposeConvolution2dUint8Nhwc,\n                     PaddedTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     true,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedPaddedTransposeConvolution2dInt16Nchw,\n                     PaddedTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedPaddedTransposeConvolution2dInt16Nhwc,\n                     PaddedTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(StridedTransposeConvolution2dFloatNchw,\n                     StridedTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(StridedTransposeConvolution2dFloatNhwc,\n                     StridedTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     true,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(StridedTransposeConvolution2dUint8Nchw,\n                     StridedTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(StridedTransposeConvolution2dUint8Nhwc,\n                     StridedTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     true,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(StridedTransposeConvolution2dInt16Nchw,\n                     StridedTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(StridedTransposeConvolution2dInt16Nhwc,\n                     StridedTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(UnbiasedStridedTransposeConvolution2dFloatNchw,\n                     StridedTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     false,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedStridedTransposeConvolution2dFloatNhwc,\n                     StridedTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     true,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedStridedTransposeConvolution2dUint8Nchw,\n                     StridedTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedStridedTransposeConvolution2dUint8Nhwc,\n                     StridedTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     true,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedStridedTransposeConvolution2dInt16Nchw,\n                     StridedTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedStridedTransposeConvolution2dInt16Nhwc,\n                     StridedTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     true,\n                     DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(MultiChannelTransposeConvolution2dFloatNchw,\n                     MultiChannelTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(MultiChannelTransposeConvolution2dFloatNhwc,\n                     MultiChannelTransposeConvolution2dTest<DataType::Float32, DataType::Float32>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(MultiChannelTransposeConvolution2dUint8Nchw,\n                     MultiChannelTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(MultiChannelTransposeConvolution2dUint8Nhwc,\n                     MultiChannelTransposeConvolution2dTest<DataType::QuantisedAsymm8, DataType::Signed32>,\n                     DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(MultiChannelTransposeConvolution2dInt16Nchw,\n                     MultiChannelTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(MultiChannelTransposeConvolution2dInt16Nhwc,\n                     MultiChannelTransposeConvolution2dTest<DataType::QuantisedSymm16, DataType::Signed32>,\n                     DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(TransposeConvolution2dPerAxisQuantTestNchw,\n                     TransposeConvolution2dPerAxisQuantTest,\n                     DataLayout::NCHW);\nARMNN_AUTO_TEST_CASE(TransposeConvolution2dPerAxisQuantTestNhwc,\n                     TransposeConvolution2dPerAxisQuantTest,\n                     DataLayout::NHWC);\n\n// Stack\nARMNN_AUTO_TEST_CASE(Stack0Axis,           StackAxis0Float32Test)\nARMNN_AUTO_TEST_CASE(StackOutput4DAxis1,   StackOutput4DAxis1Float32Test)\nARMNN_AUTO_TEST_CASE(StackOutput4DAxis2,   StackOutput4DAxis2Float32Test)\nARMNN_AUTO_TEST_CASE(StackOutput4DAxis3,   StackOutput4DAxis3Float32Test)\nARMNN_AUTO_TEST_CASE(StackOutput3DInputs3, StackOutput3DInputs3Float32Test)\nARMNN_AUTO_TEST_CASE(StackOutput5D,        StackOutput5DFloat32Test)\nARMNN_AUTO_TEST_CASE(StackFloat16,         StackFloat16Test)\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a397e935c120496ce3fc312ec818accee8c3111d", "size": 96794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backends/reference/test/RefLayerTests.cpp", "max_stars_repo_name": "vivint-smarthome/armnn", "max_stars_repo_head_hexsha": "6b1bf1a40bebf4cc108d39f8b8e0c29bdfc51ce1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/backends/reference/test/RefLayerTests.cpp", "max_issues_repo_name": "vivint-smarthome/armnn", "max_issues_repo_head_hexsha": "6b1bf1a40bebf4cc108d39f8b8e0c29bdfc51ce1", "max_issues_repo_licenses": ["MIT"], "max_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/test/RefLayerTests.cpp", "max_forks_repo_name": "vivint-smarthome/armnn", "max_forks_repo_head_hexsha": "6b1bf1a40bebf4cc108d39f8b8e0c29bdfc51ce1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.0207317073, "max_line_length": 119, "alphanum_fraction": 0.8165382152, "num_tokens": 26927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5482800547398338}}
{"text": "/*\n * LaplaceM2L.cpp\n *\n *  Created on: Oct 12, 2016\n *      Author: wyan\n */\n\n#include \"SVD_pvfmm.hpp\"\n\n#include <Eigen/Dense>\n\n#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n\n#define DIRECTLAYER 2\n#define PI314 (static_cast<double>(3.1415926535897932384626433))\n\nnamespace Laplace3D3D {\n\nusing EVec3 = Eigen::Vector3d;\nusing EVec4 = Eigen::Vector4d;\nconstexpr double eps = 1e-10;\n\n// real and wave sum of 2D Laplace kernel Ewald\n\ninline double freal(double xi, double r) { return std::erfc(xi * r) / r; }\n\ninline double frealp(double xi, double r) {\n    return -(2. * exp(-r * r * (xi * xi)) * xi) / (sqrt(M_PI) * r) - std::erfc(r * xi) / (r * r);\n}\n\n// xm: target, xn: source\ninline double realSum(const double xi, const EVec3 &xn, const EVec3 &xm) {\n    EVec3 rmn = xm - xn;\n    double rnorm = rmn.norm();\n    if (rnorm < eps) {\n        return 0;\n    }\n    return freal(xi, rnorm);\n}\n\ninline double potEwald(const EVec3 &xm, const EVec3 &xn) {\n    const double xi = 2; // recommend for box=1 to get machine precision\n    EVec3 target = xm;\n    EVec3 source = xn;\n    target[0] = target[0] - floor(target[0]); // periodic BC\n    target[1] = target[1] - floor(target[1]);\n    target[2] = target[2] - floor(target[2]);\n    source[0] = source[0] - floor(source[0]);\n    source[1] = source[1] - floor(source[1]);\n    source[2] = source[2] - floor(source[2]);\n\n    // real sum\n    int rLim = 4;\n    double Kreal = 0;\n    for (int i = -rLim; i <= rLim; i++) {\n        for (int j = -rLim; j <= rLim; j++) {\n            for (int k = -rLim; k <= rLim; k++) {\n                Kreal += realSum(xi, target, source - EVec3(i, j, k));\n            }\n        }\n    }\n\n    // wave sum\n    int wLim = 4;\n    double Kwave = 0;\n    EVec3 rmn = target - source;\n    const double xi2 = xi * xi;\n    const double rmnnorm = rmn.norm();\n    for (int i = -wLim; i <= wLim; i++) {\n        for (int j = -wLim; j <= wLim; j++) {\n            for (int k = -wLim; k <= wLim; k++) {\n                if (i == 0 && j == 0 && k == 0) {\n                    continue;\n                }\n                EVec3 kvec = EVec3(i, j, k) * (2 * PI314);\n                double k2 = kvec.dot(kvec);\n                Kwave += 4 * PI314 * cos(kvec.dot(rmn)) * exp(-k2 / (4 * xi2)) / k2;\n            }\n        }\n    }\n\n    double Kself = rmnnorm < 1e-10 ? -2 * xi / sqrt(PI314) : 0;\n\n    return Kreal + Kwave + Kself - PI314 / xi2;\n}\n\ninline void realGradSum(double xi, const EVec3 &target, const EVec3 &source, EVec3 &v) {\n    EVec3 rvec = target - source;\n    double rnorm = rvec.norm();\n    if (rnorm < eps) {\n        v.setZero();\n    } else {\n        v = (frealp(xi, rnorm) / rnorm) * rvec;\n    }\n}\n\ninline void gradkernel(const EVec3 &target, const EVec3 &source, EVec3 &answer) {\n    EVec3 rst = target - source;\n    double rnorm = rst.norm();\n    if (rnorm < eps) {\n        answer.setZero();\n        return;\n    }\n    double rnorm3 = rnorm * rnorm * rnorm;\n    answer = -rst / rnorm3;\n}\n\n// grad of Laplace potential, without 1/4pi prefactor, periodic of -r_k/r^3\ninline void gradEwald(const EVec3 &target_, const EVec3 &source_, EVec3 &answer) {\n    EVec3 target = target_;\n    EVec3 source = source_;\n    target[0] = target[0] - floor(target[0]); // periodic BC\n    target[1] = target[1] - floor(target[1]);\n    target[2] = target[2] - floor(target[2]);\n    source[0] = source[0] - floor(source[0]);\n    source[1] = source[1] - floor(source[1]);\n    source[2] = source[2] - floor(source[2]);\n\n    double xi = 0.54;\n\n    // real sum\n    int rLim = 10;\n    EVec3 Kreal = EVec3::Zero();\n    for (int i = -rLim; i < rLim + 1; i++) {\n        for (int j = -rLim; j < rLim + 1; j++) {\n            for (int k = -rLim; k < rLim + 1; k++) {\n                EVec3 v = EVec3::Zero();\n                realGradSum(xi, target, source + EVec3(i, j, k), v);\n                Kreal += v;\n            }\n        }\n    }\n\n    // wave sum\n    int wLim = 10;\n    EVec3 rmn = target - source;\n    double xi2 = xi * xi;\n    EVec3 Kwave(0., 0., 0.);\n    for (int i = -wLim; i < wLim + 1; i++) {\n        for (int j = -wLim; j < wLim + 1; j++) {\n            for (int k = -wLim; k < wLim + 1; k++) {\n                if (i == 0 && j == 0 && k == 0)\n                    continue;\n                EVec3 kvec = EVec3(i, j, k) * (2 * M_PI);\n                double k2 = kvec.dot(kvec);\n                double knorm = kvec.norm();\n                Kwave += -kvec * (sin(kvec.dot(rmn)) * exp(-k2 / (4 * xi2)) / k2);\n            }\n        }\n    }\n\n    answer = Kreal + Kwave;\n}\n\ninline double pot(const EVec3 &target, const EVec3 &source) {\n    EVec3 rst = target - source;\n    double rnorm = rst.norm();\n    return rnorm < eps ? 0 : 1 / rnorm;\n}\n\ninline EVec4 gKernel(const EVec3 &target, const EVec3 &source) {\n    EVec3 rst = target - source;\n    EVec4 pgrad = EVec4::Zero();\n    double rnorm = rst.norm();\n    if (rnorm < eps) {\n        pgrad.setZero();\n    } else {\n        pgrad[0] = 1 / rnorm;\n        double rnorm3 = rnorm * rnorm * rnorm;\n        pgrad.block<3, 1>(1, 0) = -rst / rnorm3;\n    }\n    return pgrad;\n}\n\ninline EVec4 gKernelEwald(const EVec3 &target, const EVec3 &source) {\n    EVec4 pgrad = EVec4::Zero();\n    pgrad[0] = potEwald(target, source);\n    EVec3 grad;\n    gradEwald(target, source, grad);\n    pgrad[1] = grad[0];\n    pgrad[2] = grad[1];\n    pgrad[3] = grad[2];\n    return pgrad;\n}\n\ninline EVec4 gKernelNF(const EVec3 &target, const EVec3 &source, int N = DIRECTLAYER) {\n    EVec4 gNF = EVec4::Zero();\n    for (int i = -N; i < N + 1; i++) {\n        for (int j = -N; j < N + 1; j++) {\n            for (int k = -N; k < N + 1; k++) {\n                EVec4 gFree = gKernel(target, source + EVec3(i, j, k));\n                gNF += gFree;\n            }\n        }\n    }\n    return gNF;\n}\n\n// Out of Direct Sum Layer, far field part\ninline EVec4 gKernelFF(const EVec3 &target, const EVec3 &source) {\n    EVec4 fEwald = gKernelEwald(target, source);\n    fEwald -= gKernelNF(target, source);\n    return fEwald;\n}\n\ninline double potNF(const EVec3 &target, const EVec3 &source, int N = DIRECTLAYER) {\n    double gNF = 0;\n    for (int i = -N; i < N + 1; i++) {\n        for (int j = -N; j < N + 1; j++) {\n            for (int k = -N; k < N + 1; k++) {\n                gNF += pot(target, source + EVec3(i, j, k));\n            }\n        }\n    }\n    return gNF;\n}\n\n// Out of Direct Sum Layer, far field part\ninline double potFF(const EVec3 &target, const EVec3 &source) {\n    double fEwald = potEwald(target, source);\n    fEwald -= potNF(target, source);\n    return fEwald;\n}\n\n/**\n * \\brief Returns the coordinates of points on the surface of a cube.\n * \\param[in] p Number of points on an edge of the cube is (n+1)\n * \\param[in] c Coordinates to the centre of the cube (3D array).\n * \\param[in] alpha Scaling factor for the size of the cube.\n * \\param[in] depth Depth of the cube in the octree.\n * \\return Vector with coordinates of points on the surface of the cube in the\n * format [x0 y0 z0 x1 y1 z1 .... ].\n */\n\ntemplate <class Real_t>\nstd::vector<Real_t> surface(int p, Real_t *c, Real_t alpha, int depth) {\n    size_t n_ = (6 * (p - 1) * (p - 1) + 2); // Total number of points.\n\n    std::vector<Real_t> coord(n_ * 3);\n    coord[0] = coord[1] = coord[2] = -1.0;\n    size_t cnt = 1;\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = -1.0;\n            coord[cnt * 3 + 1] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = (2.0 * j - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * i - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = -1.0;\n            coord[cnt * 3 + 2] = (2.0 * (j + 1) - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = (2.0 * j - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = -1.0;\n            cnt++;\n        }\n    for (size_t i = 0; i < (n_ / 2) * 3; i++)\n        coord[cnt * 3 + i] = -coord[i];\n\n    Real_t r = 0.5 * pow(0.5, depth);\n    Real_t b = alpha * r;\n    for (size_t i = 0; i < n_; i++) {\n        coord[i * 3 + 0] = (coord[i * 3 + 0] + 1.0) * b + c[0];\n        coord[i * 3 + 1] = (coord[i * 3 + 1] + 1.0) * b + c[1];\n        coord[i * 3 + 2] = (coord[i * 3 + 2] + 1.0) * b + c[2];\n    }\n    return coord;\n}\n\nint main(int argc, char **argv) {\n    Eigen::initParallel();\n    Eigen::setNbThreads(1);\n\n    std::cout << std::scientific << std::setprecision(18);\n\n    std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n    const int pEquiv = atoi(argv[1]); // (8-1)^2*6 + 2 points\n    const int pCheck = atoi(argv[1]);\n    const double scaleEquiv = 1.05;\n    const double scaleCheck = 2.95;\n    const double pCenterEquiv[3] = {-(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2};\n    const double pCenterCheck[3] = {-(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2};\n\n    const double scaleLEquiv = 1.05;\n    const double scaleLCheck = 2.95;\n    const double pCenterLEquiv[3] = {-(scaleLEquiv - 1) / 2, -(scaleLEquiv - 1) / 2, -(scaleLEquiv - 1) / 2};\n    const double pCenterLCheck[3] = {-(scaleLCheck - 1) / 2, -(scaleLCheck - 1) / 2, -(scaleLCheck - 1) / 2};\n\n    auto pointMEquiv = surface(pEquiv, (double *)&(pCenterEquiv[0]), scaleEquiv, 0);\n    // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointMCheck = surface(pCheck, (double *)&(pCenterCheck[0]), scaleCheck, 0);\n    // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    auto pointLEquiv = surface(pEquiv, (double *)&(pCenterLCheck[0]), scaleLCheck, 0);\n    // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointLCheck = surface(pCheck, (double *)&(pCenterLEquiv[0]), scaleLEquiv, 0);\n    // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    // calculate the operator M2L with least square\n    const int equivN = pointMEquiv.size() / 3;\n    const int checkN = pointLCheck.size() / 3;\n    Eigen::MatrixXd M2L(equivN, equivN); // Laplace, 1->1\n\n    // Aup for solving MEquiv\n    Eigen::MatrixXd Aup(checkN, equivN);\n    Eigen::MatrixXd AuppinvU(Aup.cols(), Aup.rows());\n    Eigen::MatrixXd AuppinvVT(Aup.cols(), Aup.rows());\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Vector3d Cpoint(pointMCheck[3 * k], pointMCheck[3 * k + 1], pointMCheck[3 * k + 2]);\n        for (int l = 0; l < equivN; l++) {\n            const Eigen::Vector3d Lpoint(pointMEquiv[3 * l], pointMEquiv[3 * l + 1], pointMEquiv[3 * l + 2]);\n            Aup(k, l) = pot(Cpoint, Lpoint);\n        }\n    }\n    pinv(Aup, AuppinvU, AuppinvVT);\n\n    // condition number\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(Aup);\n    double cond = svd.singularValues()(0) / svd.singularValues()(svd.singularValues().size() - 1);\n    std::cout << cond << std::endl;\n    std::cout << \"s:\" << svd.singularValues() << std::endl;\n\n    // Adown for solving LEquiv\n    Eigen::MatrixXd Adown(checkN, equivN);\n    Eigen::MatrixXd AdownpinvU(Adown.cols(), Adown.rows());\n    Eigen::MatrixXd AdownpinvVT(Adown.cols(), Adown.rows());\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1], pointLCheck[3 * k + 2]);\n        for (int l = 0; l < equivN; l++) {\n            const Eigen::Vector3d Lpoint(pointLEquiv[3 * l], pointLEquiv[3 * l + 1], pointLEquiv[3 * l + 2]);\n            Adown(k, l) = pot(Cpoint, Lpoint);\n        }\n    }\n    pinv(Adown, AdownpinvU, AdownpinvVT);\n\n#pragma omp parallel for\n    for (int i = 0; i < equivN; i++) {\n        const Eigen::Vector3d Mpoint(pointMEquiv[3 * i], pointMEquiv[3 * i + 1], pointMEquiv[3 * i + 2]);\n        const EVec3 Npoint(0.5, 0.5, 0.5);\n        Eigen::VectorXd f(checkN);\n        f.setZero();\n        for (int k = 0; k < checkN; k++) {\n            EVec3 Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1], pointLCheck[3 * k + 2]);\n            f[k] = potFF(Cpoint, Mpoint) - potFF(Cpoint, Npoint);\n        }\n\n        M2L.col(i) = (AdownpinvU.transpose() * (AdownpinvVT.transpose() * f));\n    }\n    std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();\n    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();\n\n    // dump M2L\n    for (int i = 0; i < equivN; i++) {\n        for (int j = 0; j < equivN; j++) {\n            std::cout << i << \" \" << j << \" \" << std::scientific << std::setprecision(18) << M2L(i, j) << std::endl;\n        }\n    }\n\n    std::cout << \"Precomputing time:\" << duration / 1e6 << std::endl;\n\n    // Test\n    EVec3 center(0.6, 0.5, 0.5);\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> chargePoint(2);\n    std::vector<double> chargeValue(2);\n    chargePoint[0] = center + EVec3(0.1, 0, 0);\n    chargeValue[0] = 1;\n    chargePoint[1] = center + EVec3(-0.1, 0., 0.);\n    chargeValue[1] = -1;\n    // chargePoint[2] = center + EVec3(-0.2, 0., 0.);\n    // chargeValue[2] = 1;\n\n    // solve M\n    Eigen::VectorXd f(checkN);\n    for (int k = 0; k < checkN; k++) {\n        double temp = 0;\n        Eigen::Vector3d Cpoint(pointMCheck[3 * k], pointMCheck[3 * k + 1], pointMCheck[3 * k + 2]);\n        for (size_t p = 0; p < chargePoint.size(); p++) {\n            temp = temp + pot(Cpoint, chargePoint[p]) * (chargeValue[p]);\n        }\n        f[k] = temp;\n    }\n    Eigen::VectorXd Msource = (AuppinvU.transpose() * (AuppinvVT.transpose() * f));\n\n    std::cout << \"Msource \" << Msource << std::endl;\n\n    std::cout << \"backward error: \" << f - Aup * Msource << std::endl;\n\n    // check dipole moment\n    {\n        EVec3 dipole = EVec3::Zero();\n        for (int i = 0; i < chargePoint.size(); i++) {\n            dipole += chargeValue[i] * chargePoint[i];\n        }\n        std::cout << \"charge dipole \" << dipole.transpose() << std::endl;\n    }\n    {\n        EVec3 dipole = EVec3::Zero();\n        for (int i = 0; i < equivN; i++) {\n            Eigen::Vector3d Mpoint(pointMEquiv[3 * i], pointMEquiv[3 * i + 1], pointMEquiv[3 * i + 2]);\n            dipole += Mpoint * Msource[i];\n        }\n        std::cout << \"Mequiv dipole \" << dipole.transpose() << std::endl;\n    }\n\n    Eigen::VectorXd M2Lsource = M2L * (Msource);\n\n    for (int is = 0; is < 5; is++) {\n\n        Eigen::Vector3d samplePoint = EVec3::Random() * 0.2 + EVec3(0.5, 0.5, 0.5);\n\n        EVec4 UFFL2T = EVec4::Zero();\n        EVec4 UFFS2T = EVec4::Zero();\n        EVec4 UFFM2T = EVec4::Zero();\n\n#pragma omp sections\n        {\n#pragma omp section\n            for (int p = 0; p < chargePoint.size(); p++) {\n                UFFS2T += gKernelFF(samplePoint, chargePoint[p]) * chargeValue[p];\n            }\n\n#pragma omp section\n            for (int p = 0; p < equivN; p++) {\n                Eigen::Vector3d Lpoint(pointLEquiv[3 * p], pointLEquiv[3 * p + 1], pointLEquiv[3 * p + 2]);\n                UFFL2T += gKernel(samplePoint, Lpoint) * M2Lsource[p];\n            }\n\n#pragma omp section\n            for (int p = 0; p < equivN; p++) {\n                Eigen::Vector3d Mpoint(pointMEquiv[3 * p], pointMEquiv[3 * p + 1], pointMEquiv[3 * p + 2]);\n                UFFM2T += gKernelFF(samplePoint, Mpoint) * Msource[p];\n            }\n        }\n        std::cout << std::scientific << std::setprecision(10);\n        std::cout << \"-----------------------------------------------\" << std::endl;\n        std::cout << \"samplePoint:\" << samplePoint.transpose() << std::endl;\n        std::cout << \"UFF S2T: \" << UFFS2T.transpose() << std::endl;\n        std::cout << \"UFF M2T: \" << UFFM2T.transpose() << std::endl;\n        std::cout << \"UFF L2T: \" << UFFL2T.transpose() << std::endl;\n        std::cout << \"Error M2T: \" << (UFFM2T - UFFS2T).transpose() << std::endl;\n        std::cout << \"Error L2T: \" << (UFFL2T - UFFS2T).transpose() << std::endl;\n    }\n\n    return 0;\n}\n\n} // namespace Laplace3D3D\n\n#undef DIRECTLAYER\n#undef PI314\n", "meta": {"hexsha": "c6c0bd55158b43e7f4bbc62f18e3821eeec82d86", "size": 16041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "M2L/Laplace/Laplace3D3D.cpp", "max_stars_repo_name": "lamsoa729/STKFMM", "max_stars_repo_head_hexsha": "26d7d971c198e3bed68eb8373e5590a6eb72f764", "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": "M2L/Laplace/Laplace3D3D.cpp", "max_issues_repo_name": "lamsoa729/STKFMM", "max_issues_repo_head_hexsha": "26d7d971c198e3bed68eb8373e5590a6eb72f764", "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": "M2L/Laplace/Laplace3D3D.cpp", "max_forks_repo_name": "lamsoa729/STKFMM", "max_forks_repo_head_hexsha": "26d7d971c198e3bed68eb8373e5590a6eb72f764", "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.8717391304, "max_line_length": 116, "alphanum_fraction": 0.5290817281, "num_tokens": 5583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5482800529192301}}
{"text": "#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>\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);\nbool InvertMatrixGen(const ublas::matrix<double>& input, ublas::matrix<double>& inverse);\n#endif //INVERT_MATRIX_HPP\n", "meta": {"hexsha": "c4e78dff98bc9ae7ed6cb22924c834b5a60eb15d", "size": 716, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/InvertMatrix.hpp", "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.hpp", "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.hpp", "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": 39.7777777778, "max_line_length": 89, "alphanum_fraction": 0.780726257, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5482800384119677}}
{"text": "/** @file\n *****************************************************************************\n\n Declaration of interfaces for a secret-key lattice-based additively homomorphic\n vector encryption scheme.\n\n This includes:\n - class for secret key\n - class for ciphertext\n - key generation algorithm\n - encryption algorithm\n - decryption algorithm\n - operations for homomorphic addition and scalar multiplication of ciphertexts\n\n The implementation instantiates (a modification of) the LWE-based cryptosystem\n from [LP10] (described in [Pei16, Section 5.2.3]). The implementation encodes\n the message in the low-order bits of the ciphertext.\n\n References:\n\n  [LP10]: Richard Lindner and Chris Peikert. Better Key Sizes (and Attacks) for\n          LWE-Based Encryption. In CT-RSA, 2011.\n\n  [Pei16]: Chris Peikert. A Decade of Lattice Cryptography. Available as\n           Report 2015/939 on IACR Cryptology ePrint Archive \n           (https://eprint.iacr.org/2015/939.pdf).\n\n *****************************************************************************\n * @author     Samir Menon, Brennan Shacklett, and David J. Wu\n * @copyright  MIT license (see LICENSE file)\n *****************************************************************************/\n\n#ifndef LWE_HPP_\n#define LWE_HPP_\n\n#include <NTL/mat_ZZ_p.h>\n#include <random>\n#include \"lwe_params.hpp\"\n\nnamespace LWE {\n\nusing matrix = NTL::mat_ZZ_p;\nusing vector = NTL::vec_ZZ_p;\nusing plaintext = vector;\n\nclass secret_key {\npublic:\n    matrix A {NTL::INIT_SIZE, n + pt_dim, n};\n    matrix S {NTL::INIT_SIZE, n + pt_dim, pt_dim};\n};\n\nclass ciphertext {\npublic:\n  // Assignment operator\n  ciphertext& operator=(const ciphertext& other);\n\n  // Homomorphic addition\n  ciphertext operator+(const ciphertext &other) const;\n  ciphertext& operator+=(const ciphertext &other);\n\n  // Homomorphic scalar multiplication\n  ciphertext operator*(uint64_t val) const;\n  ciphertext operator*(const NTL::ZZ_p &val) const;\n  ciphertext& operator*=(uint64_t val);\n  ciphertext& operator*=(const NTL::ZZ_p &val);\n\nprivate:\n  vector ctxt;\n\nfriend ciphertext encrypt(const secret_key &sk, const plaintext &pt);\nfriend plaintext  decrypt(const secret_key &sk, const ciphertext &ct);\n};\n\nsecret_key keygen();\nciphertext encrypt(const secret_key &sk, const plaintext &pt);\nplaintext  decrypt(const secret_key &sk, const ciphertext &ct);\n\nciphertext operator*(uint64_t val, const ciphertext& ct);\nciphertext operator*(const NTL::ZZ_p &val, const ciphertext& ct);\n\n}\n\n#endif // LWE_HPP_\n", "meta": {"hexsha": "144478c2bd5722afe3e51ffb74f4b75c5e7489d1", "size": 2498, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lattice_snarg/algebra/lattice/lwe.hpp", "max_stars_repo_name": "dwu4/lattice-snarg", "max_stars_repo_head_hexsha": "f5ef3e75d7200ee2b794d04b102fc7502b149628", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T16:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-02T03:16:15.000Z", "max_issues_repo_path": "lattice_snarg/algebra/lattice/lwe.hpp", "max_issues_repo_name": "dwu4/lattice-snarg", "max_issues_repo_head_hexsha": "f5ef3e75d7200ee2b794d04b102fc7502b149628", "max_issues_repo_licenses": ["MIT"], "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_snarg/algebra/lattice/lwe.hpp", "max_forks_repo_name": "dwu4/lattice-snarg", "max_forks_repo_head_hexsha": "f5ef3e75d7200ee2b794d04b102fc7502b149628", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-12T07:11:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-16T18:20:57.000Z", "avg_line_length": 29.7380952381, "max_line_length": 80, "alphanum_fraction": 0.6685348279, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197771, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.5482603500184443}}
{"text": "//\n// Extended boost::date_time functionality\n//\n\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <string>\n#include <sstream>\n#include <vector>\n\nusing namespace boost::gregorian;\n\n// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * \n// Helper functions\n\nauto inc_year(date d, int n = 1) noexcept\n    // increment the year but keep month and day the same\n{\n    return date{d.year() + n, d.month(), d.day()};\n}\n\nauto date_in_year(date d, greg_year y = day_clock::local_day().year()) noexcept\n    // return date d in the provided year\n{\n    return date{y, d.month(), d.day()};\n}\n\nauto next_occurrence(date d, date ref = day_clock::local_day()) noexcept\n    // return the next occurrence of date d after reference date\n{\n    auto d_ref_year = date_in_year(d, ref.year());\n    return (d_ref_year <= ref) ? inc_year(d_ref_year) : d_ref_year;\n}\n\nauto next_date_of_day(date d, greg_day wd) noexcept\n    // return the year in which date d falls on weekday wd\n{\n    do {\n        d = inc_year(d);\n    } while (d.day_of_week() != wd);\n\n    return d;\n}\n\n// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * \n\nauto get_date_results(const std::string& s)\n    // return vector<string> report of date data\n{\n    std::vector<std::string> res;\n    std::stringstream ss1;          // QUESTION: Is there a better way?\n    std::stringstream ss2;\n    std::stringstream ss3;\n\n    res.push_back(s);\n\n    auto birthday(from_simple_string(s));\n    ss1 << \"You were born on a \"\n        << birthday.day_of_week().as_long_string() << '.';\n    res.emplace_back(ss1.str());\n\n    auto this_bd = date_in_year(birthday);\n    auto next_bd = next_occurrence(this_bd);\n    auto days_away = (next_bd - day_clock::local_day()).days();\n    ss2 << \"Your next birthday is in \"\n        << days_away << \" days on a \"\n        << next_bd.day_of_week().as_long_string() << '.';\n    res.emplace_back(ss2.str());\n\n    auto sat_bd = next_date_of_day(inc_year(next_bd), Saturday);\n    ss3 << \"The next time your birthday is on a Saturday is in \"\n        << sat_bd.year() << '.';\n    res.emplace_back(ss3.str());\n\n    return res;\n}\n", "meta": {"hexsha": "aac9671c90a2a2c60d74a7cb9887ef8db759f9cf", "size": 2144, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/date_time_ext.hpp", "max_stars_repo_name": "Chrinkus/birthday", "max_stars_repo_head_hexsha": "9477efd099f2d87937954e3f021ba2d4abf3f334", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/date_time_ext.hpp", "max_issues_repo_name": "Chrinkus/birthday", "max_issues_repo_head_hexsha": "9477efd099f2d87937954e3f021ba2d4abf3f334", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/date_time_ext.hpp", "max_forks_repo_name": "Chrinkus/birthday", "max_forks_repo_head_hexsha": "9477efd099f2d87937954e3f021ba2d4abf3f334", "max_forks_repo_licenses": ["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.2105263158, "max_line_length": 79, "alphanum_fraction": 0.6012126866, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5482253439930996}}
{"text": " //\n// Created by Himatya on 2018/05/22.\n//\n\n#pragma once\n\n#include <chrono>\n#include <vector>\n#include <iterator>\n\n#include <boost/optional.hpp>\n\nnamespace mk2 {\nnamespace chrono {\n\n    namespace detail\n    {\n        class frame_counter_container\n        {\n        public:\n            frame_counter_container(std::chrono::nanoseconds range) : range_(range) {}\n\n            void push(std::chrono::nanoseconds ns)\n            {\n                while (time_ + (ns - time_split_.front()) > range_)\n                {\n                    time_ -= time_split_.front();\n                    time_split_.erase(std::begin(time_split_));\n                }\n                time_ += ns;\n                time_split_.emplace_back(ns);\n            }\n\n            bool is_valid() const\n            { return range_ <= time_; }\n\n            auto get_time() const\n            { return time_; }\n\n            auto get_range() const\n            { return range_; }\n\n            auto get_frame() const\n            { return time_split_.size(); }\n\n        private:\n            std::vector<std::chrono::nanoseconds> time_split_;\n            std::chrono::nanoseconds range_;\n            std::chrono::nanoseconds time_;\n        };\n    }\n\n    class frame_counter\n    {\n    public:\n        frame_counter(std::chrono::nanoseconds range) : container_(range) {}\n\n        ~frame_counter() = default;\n\n        void tick()\n        {\n            auto point = std::chrono::steady_clock::now();\n            auto dlt = point - time_point_;\n            container_.push(std::chrono::duration_cast<std::chrono::milliseconds>(dlt));\n            time_point_ = point;\n        }\n\n        boost::optional<double> get_fps()\n        {\n            if(!container_.is_valid())\n                return boost::none;\n\n            return (double)container_.get_frame().count() * container_.get_time().count() / container_.get_range().count();\n        }\n\n    private:\n        std::chrono::time_point time_point_;\n        mk2::chrono::detail::frame_counter_container container_;\n    };\n\n}\n}", "meta": {"hexsha": "bf5dd2c6cafdd7c1d57332d281c5790babef0167", "size": 2028, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mk2/chrono/frame_counter.hpp", "max_stars_repo_name": "SachiSakurane/libmk2", "max_stars_repo_head_hexsha": "e8acf044ee5de160ad8a6f0a3c955beddea8d8c2", "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/mk2/chrono/frame_counter.hpp", "max_issues_repo_name": "SachiSakurane/libmk2", "max_issues_repo_head_hexsha": "e8acf044ee5de160ad8a6f0a3c955beddea8d8c2", "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/mk2/chrono/frame_counter.hpp", "max_forks_repo_name": "SachiSakurane/libmk2", "max_forks_repo_head_hexsha": "e8acf044ee5de160ad8a6f0a3c955beddea8d8c2", "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.7317073171, "max_line_length": 123, "alphanum_fraction": 0.533530572, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5482253363160413}}
{"text": "/**\n * Some additional useful distributions (only bare operator()).\n */\n#ifndef SKYLARK_DISTRIBUTIONS_HPP\n#define SKYLARK_DISTRIBUTIONS_HPP\n\n#include <boost/random.hpp>\n\nnamespace skylark {\nnamespace utility {\n\n\n/**\n * Levy distribution\n */\ntemplate< typename ValueType >\nstruct standard_levy_distribution_t {\n\n    // TODO not really sure this is the standard, or implemented correctly\n\n    typedef ValueType result_type;\n\n    standard_levy_distribution_t() {\n\n    }\n\n    template< typename URNG >\n    ValueType operator()(URNG &prng) const {\n        boost::random::gamma_distribution<ValueType> dist(0.5, 2);\n        result_type y = static_cast<ValueType>(dist(prng));\n        return (1.0 / y);\n    }\n    void reset() {}\n\n};\n\n/**\n * Radamachar distribution - +1 and -1 with equal probability.\n */\ntemplate< typename ValueType >\nstruct rademacher_distribution_t {\n\n    typedef ValueType result_type;\n\n    template< typename URNG >\n    ValueType operator()(URNG &prng) const {\n        double probabilities[] = { 0.5, 0.0, 0.5 };\n        boost::random::discrete_distribution<> dist(probabilities);\n        return static_cast<ValueType>(dist(prng)) - 1.0;\n    }\n    void reset() {}\n};\n\n/**\n * Uniform distribution\n */\ntemplate <typename ValueType> struct uniform_distribution_t {\n    typedef ValueType result_type;\n};\n\n/**\n * Uniform distribution specialization for double's\n */\ntemplate <> struct uniform_distribution_t <double> {\n\n    typedef double result_type;\n\n    boost::random::uniform_real_distribution<double> distribution;\n\n    uniform_distribution_t() {}\n\n    uniform_distribution_t(double low, double high) :\n      distribution(low, high) {}\n\n    template< typename URNG >\n    double operator()(URNG &urng) const {\n        return distribution(urng);\n    }\n    void reset() {}\n};\n\n/**\n * Uniform distribution specialization for int's\n */\ntemplate <> struct uniform_distribution_t <int> {\n\n    typedef int result_type;\n\n    boost::random::uniform_int_distribution<int> distribution;\n\n    uniform_distribution_t() {}\n\n    uniform_distribution_t(int low, int high) :\n      distribution(low, high) {}\n\n    template< typename URNG >\n    int operator()(URNG &urng) const {\n        return distribution(urng);\n    }\n    void reset() {}\n};\n\n/**\n * Uniform distribution specialization for size_t\n */\ntemplate <> struct uniform_distribution_t <size_t> {\n\n    typedef int result_type;\n\n    boost::random::uniform_int_distribution<size_t> distribution;\n\n    uniform_distribution_t() {}\n\n    uniform_distribution_t(size_t low, size_t high) :\n      distribution(low, high) {}\n\n    template< typename URNG >\n    int operator()(URNG &urng) const {\n        return distribution(urng);\n    }\n    void reset() {}\n};\n\n\n/**\n * Uniform distribution specialization for bool's\n */\ntemplate <> struct uniform_distribution_t <bool> {\n\n    typedef bool result_type;\n\n    boost::random::uniform_int_distribution<int> distribution;\n\n    uniform_distribution_t() {}\n\n    template< typename URNG >\n    bool operator()(URNG &urng) const {\n        return (1==distribution(urng));\n    }\n    void reset() {}\n};\n\n} // namespace utility\n} // namespace skylark\n\n#endif // SKYLARK_DISTRIBUTIONS_HPP\n", "meta": {"hexsha": "1d03f711e486341d62e28aa8e387c2c334aa4068", "size": 3166, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utility/distributions.hpp", "max_stars_repo_name": "wangg12/libskylark", "max_stars_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "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": "utility/distributions.hpp", "max_issues_repo_name": "cjiyer/libskylark", "max_issues_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "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": "utility/distributions.hpp", "max_forks_repo_name": "cjiyer/libskylark", "max_forks_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "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": 21.537414966, "max_line_length": 74, "alphanum_fraction": 0.6803537587, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5482253323752203}}
{"text": "\r\n#include \"../../def_submodule.hpp\"\r\n\r\n#include \"../../../../../type/math/coord.hpp\"\r\n#include \"../../../../../type/math/matrix.hpp\"\r\n\r\n\r\n#include <boost/python.hpp>\r\n\r\ntypedef GS_DDMRM::S_IceRay::S_type::GT_size                GTs_size;\r\ntypedef GS_DDMRM::S_IceRay::S_type::GT_scalar              GTs_scalar;\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_scalar3D   GTs_coord3D;\r\n\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_matrix::GT_scalar2D  GTs_matrix2D;\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_matrix::GT_scalar3D  GTs_matrix3D;\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_matrix::GT_scalar4D  GTs_matrix4D;\r\n\r\n\r\nnamespace\r\n {\r\n  GTs_matrix3D & GFs_set( GTs_matrix3D & P_matrix, GTs_size P_row, GTs_size const& P_column, GTs_scalar const& P_value )\r\n   {\r\n    P_matrix[ P_row ][ P_column ] = P_value;\r\n     // TODO PyErr_SetString(PyExc_IndexError, \"index out of range\" );\r\n     return P_matrix;\r\n   }\r\n\r\n  GTs_coord3D GFs_rowGet( GTs_matrix3D & P_matrix, GTs_size P_row  )\r\n   {\r\n    GTs_coord3D Ir_row;\r\n    Ir_row[0] = P_matrix[ P_row ][ 0 ];\r\n    Ir_row[1] = P_matrix[ P_row ][ 1 ];\r\n    Ir_row[2] = P_matrix[ P_row ][ 2 ];\r\n\r\n    return Ir_row;\r\n   }\r\n\r\n  GTs_matrix3D & GFs_rowSet( GTs_matrix3D & P_matrix, GTs_size P_row, GTs_coord3D const& P_value )\r\n   {\r\n    P_matrix[ P_row ][ 0 ] = P_value[0];\r\n    P_matrix[ P_row ][ 1 ] = P_value[1];\r\n    P_matrix[ P_row ][ 2 ] = P_value[2];\r\n    return P_matrix;\r\n   }\r\n\r\n  GTs_coord3D GFs_columnGet( GTs_matrix3D & P_matrix, GTs_size P_column  )\r\n   {\r\n    GTs_coord3D Ir_column;\r\n\r\n    Ir_column[0] = P_matrix[ 0 ][ P_column ];\r\n    Ir_column[1] = P_matrix[ 1 ][ P_column ];\r\n    Ir_column[2] = P_matrix[ 2 ][ P_column ];\r\n    return Ir_column;\r\n   }\r\n\r\n  GTs_matrix3D &  GFs_columnSet( GTs_matrix3D & P_matrix, GTs_size P_column, GTs_coord3D const& P_value )\r\n   {\r\n    P_matrix[ 0 ][ P_column ] = P_value[0];\r\n    P_matrix[ 1 ][ P_column ] = P_value[1];\r\n    P_matrix[ 2 ][ P_column ] = P_value[2];\r\n    return P_matrix;\r\n   }\r\n\r\n  GTs_matrix3D &  GFs_scale1( GTs_matrix3D & P_matrix, GTs_scalar const& P_value )\r\n   {\r\n    P_matrix[ 0 ][ 0 ] *= P_value;\r\n    P_matrix[ 1 ][ 1 ] *= P_value;\r\n    P_matrix[ 2 ][ 2 ] *= P_value;\r\n    return P_matrix;\r\n   }\r\n\r\n  GTs_matrix3D &  GFs_scale3( GTs_matrix3D & P_matrix, GTs_coord3D const& P_value )\r\n   {\r\n    P_matrix[ 0 ][ 0 ] *= P_value[0];\r\n    P_matrix[ 1 ][ 1 ] *= P_value[1];\r\n    P_matrix[ 2 ][ 2 ] *= P_value[2];\r\n    return P_matrix;\r\n   }\r\n\r\n  GTs_matrix3D &  GFs_load( GTs_matrix3D & P_matrix, GTs_coord3D const& P_x, GTs_coord3D const& P_y, GTs_coord3D const& P_z )\r\n   {\r\n    P_matrix[ 0 ][ 0 ] = P_x[0];\r\n    P_matrix[ 1 ][ 0 ] = P_x[1];\r\n    P_matrix[ 2 ][ 0 ] = P_x[2];\r\n\r\n    P_matrix[ 0 ][ 1 ] = P_y[0];\r\n    P_matrix[ 1 ][ 1 ] = P_y[1];\r\n    P_matrix[ 2 ][ 1 ] = P_y[2];\r\n\r\n    P_matrix[ 0 ][ 2 ] = P_z[0];\r\n    P_matrix[ 1 ][ 2 ] = P_z[1];\r\n    P_matrix[ 2 ][ 2 ] = P_z[2];\r\n\r\n    return P_matrix;\r\n   }\r\n   \r\n  GTs_matrix3D &  GFs_id3( GTs_matrix3D & P_matrix )\r\n   {\r\n    ::math::linear::matrix::id( P_matrix );\r\n    return P_matrix;\r\n   }\r\n\r\n  GTs_matrix3D &  GFs_zero3( GTs_matrix3D & P_matrix )\r\n   {\r\n    ::math::linear::matrix::zero( P_matrix );\r\n    return P_matrix;\r\n   }\r\n }\r\n\r\nvoid expose_math_type_matrix2D()\r\n {\r\n  //MAKE_SUBMODULE( IceRay );\r\n  MAKE_SUBMODULE( library   );\r\n  MAKE_SUBMODULE( math   );\r\n\r\n  boost::python::class_<GTs_matrix2D>( \"MathTypeMatrix2D\" )\r\n    .def( boost::python::init<>() );\r\n\r\n }\r\n\r\nvoid expose_math_type_matrix3D()\r\n {\r\n  //MAKE_SUBMODULE( IceRay );\r\n  MAKE_SUBMODULE( library   );\r\n  MAKE_SUBMODULE( math   );\r\n\r\n  //typedef  GTs_scalar const& (GTs_matrix3D::*Tf_getScalar )( GTs_size const& P_row, GTs_size const& P_column )const;\r\n  //Tf_getScalar I_getScalar = &GTs_matrix3D::F_element;\r\n\r\n  //typedef  GTs_scalar     & (GTs_matrix3D::*Tf_accessScalar )( GTs_size const& P_row, GTs_size const& P_column );\r\n  //Tf_accessScalar I_accessScalar = &GTs_matrix3D::F_element;\r\n\r\n  boost::python::class_<GTs_matrix3D>( \"MathTypeMatrix3D\" )\r\n    .def( boost::python::init<>() )\r\n    //.def( boost::python::init< GTs_scalar >() )\r\n    //.def( boost::python::init< GTs_coord3D,GTs_coord3D,GTs_coord3D >() )\r\n\r\n    .def( \"load\", &GFs_load, boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n\r\n    //.def( \"element\", I_getScalar,    boost::python::return_value_policy<boost::python::copy_const_reference>()  )\r\n    .def( \"element\",   &GFs_set,       boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n    .def( \"row\",       &GFs_rowGet    )\r\n    .def( \"row\",       &GFs_rowSet,    boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n    .def( \"column\",    &GFs_columnGet )\r\n    .def( \"column\",    &GFs_columnSet, boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n    .def( \"scale\",     &GFs_scale1,    boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n    .def( \"scale\",     &GFs_scale3,    boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n    .def( \"identity\",  &GFs_id3,       boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n    .def( \"zero\",      &GFs_zero3,     boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n\r\n    //.def( \"rotate_z\" )\r\n    //.def( \"rotate_axis\" )\r\n\r\n    //.def( boost::python::self + boost::python::self )\r\n    //.def( boost::python::self - boost::python::self )\r\n    //.def( boost::python::self * GTs_scalar3D::T_value() )\r\n    //.def( GTs_scalar3D::T_value() * boost::python::self  )\r\n    //.def( boost::python::self / GTs_scalar3D::T_value() )\r\n    //.def( boost::python::self += boost::python::self )\r\n    //.def( boost::python::self -= boost::python::self )\r\n  ;\r\n }\r\n\r\nvoid expose_math_type_matrix4D()\r\n {\r\n  //MAKE_SUBMODULE( IceRay );\r\n  MAKE_SUBMODULE( library   );\r\n  MAKE_SUBMODULE( math   );\r\n\r\n  boost::python::class_<GTs_matrix4D>( \"MathTypeMatrix4D\" )\r\n    .def( boost::python::init<>() );\r\n\r\n }\r\n\r\n\r\nvoid expose_math_type_matrix()\r\n {\r\n  expose_math_type_matrix2D();\r\n  expose_math_type_matrix3D();\r\n  expose_math_type_matrix4D();\r\n }\r\n", "meta": {"hexsha": "9234d119aee179e326eb7230bdcd44ab6a5d095e", "size": 6194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/IceRay/main/interface/python/library/math/matrix.cpp", "max_stars_repo_name": "dmilos/IceRay", "max_stars_repo_head_hexsha": "4e01f141363c0d126d3c700c1f5f892967e3d520", "max_stars_repo_licenses": ["MIT-0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-04T12:27:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T14:49:40.000Z", "max_issues_repo_path": "src/IceRay/main/interface/python/library/math/matrix.cpp", "max_issues_repo_name": "dmilos/IceRay", "max_issues_repo_head_hexsha": "4e01f141363c0d126d3c700c1f5f892967e3d520", "max_issues_repo_licenses": ["MIT-0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IceRay/main/interface/python/library/math/matrix.cpp", "max_forks_repo_name": "dmilos/IceRay", "max_forks_repo_head_hexsha": "4e01f141363c0d126d3c700c1f5f892967e3d520", "max_forks_repo_licenses": ["MIT-0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-04T12:27:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-04T12:27:52.000Z", "avg_line_length": 34.032967033, "max_line_length": 126, "alphanum_fraction": 0.6277042299, "num_tokens": 1964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5482253259435743}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 2020 - 2021 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 at\n * the top level of the deal.II distribution.\n *\n * ---------------------------------------------------------------------\n\n *\n * Author: Timo Heister and Jiaqi Zhang, Clemson University, 2020\n */\n\n// The first few files have already been covered in previous examples and will\n// thus not be further commented on:\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/function_lib.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/sparse_direct.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/fe/mapping_q1.h>\n// Here the discontinuous finite elements and FEInterfaceValues are defined.\n#include <deal.II/fe/fe_dgq.h>\n#include <deal.II/fe/fe_interface_values.h>\n\n#include <deal.II/numerics/derivative_approximation.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/base/convergence_table.h>\n\n#include <deal.II/meshworker/copy_data.h>\n#include <deal.II/meshworker/mesh_loop.h>\n#include <deal.II/meshworker/scratch_data.h>\n\nnamespace Step74\n{\n  using namespace dealii;\n\n  // @sect3{Equation data}\n  // Here we define two test cases: convergence_rate for a smooth function\n  // and l_singularity for the Functions::LSingularityFunction.\n  enum class TestCase\n  {\n    convergence_rate,\n    l_singularity\n  };\n\n\n\n  // A smooth solution for the convergence test:\n  template <int dim>\n  class SmoothSolution : public Function<dim>\n  {\n  public:\n    SmoothSolution()\n      : Function<dim>()\n    {}\n\n    virtual void value_list(const std::vector<Point<dim>> &points,\n                            std::vector<double> &          values,\n                            const unsigned int component = 0) const override;\n\n    virtual Tensor<1, dim>\n    gradient(const Point<dim> & point,\n             const unsigned int component = 0) const override;\n  };\n\n\n\n  template <int dim>\n  void SmoothSolution<dim>::value_list(const std::vector<Point<dim>> &points,\n                                       std::vector<double> &          values,\n                                       const unsigned int /*component*/) const\n  {\n    using numbers::PI;\n    for (unsigned int i = 0; i < values.size(); ++i)\n      values[i] =\n        std::sin(2. * PI * points[i][0]) * std::sin(2. * PI * points[i][1]);\n  }\n\n\n\n  template <int dim>\n  Tensor<1, dim>\n  SmoothSolution<dim>::gradient(const Point<dim> &point,\n                                const unsigned int /*component*/) const\n  {\n    Tensor<1, dim> return_value;\n    using numbers::PI;\n    return_value[0] =\n      2. * PI * std::cos(2. * PI * point[0]) * std::sin(2. * PI * point[1]);\n    return_value[1] =\n      2. * PI * std::sin(2. * PI * point[0]) * std::cos(2. * PI * point[1]);\n    return return_value;\n  }\n\n\n\n  // The corresponding right-hand side of the smooth function:\n  template <int dim>\n  class SmoothRightHandSide : public Function<dim>\n  {\n  public:\n    SmoothRightHandSide()\n      : Function<dim>()\n    {}\n\n    virtual void value_list(const std::vector<Point<dim>> &points,\n                            std::vector<double> &          values,\n                            const unsigned int /*component*/) const override;\n  };\n\n\n\n  template <int dim>\n  void\n  SmoothRightHandSide<dim>::value_list(const std::vector<Point<dim>> &points,\n                                       std::vector<double> &          values,\n                                       const unsigned int /*component*/) const\n  {\n    using numbers::PI;\n    for (unsigned int i = 0; i < values.size(); ++i)\n      values[i] = 8. * PI * PI * std::sin(2. * PI * points[i][0]) *\n                  std::sin(2. * PI * points[i][1]);\n  }\n\n\n\n  // The right-hand side that corresponds to the function\n  // Functions::LSingularityFunction, where we\n  // assume that the diffusion coefficient $\\nu = 1$:\n  template <int dim>\n  class SingularRightHandSide : public Function<dim>\n  {\n  public:\n    SingularRightHandSide()\n      : Function<dim>()\n    {}\n\n    virtual void value_list(const std::vector<Point<dim>> &points,\n                            std::vector<double> &          values,\n                            const unsigned int /*component*/) const override;\n\n  private:\n    const Functions::LSingularityFunction ref;\n  };\n\n\n\n  template <int dim>\n  void\n  SingularRightHandSide<dim>::value_list(const std::vector<Point<dim>> &points,\n                                         std::vector<double> &          values,\n                                         const unsigned int /*component*/) const\n  {\n    for (unsigned int i = 0; i < values.size(); ++i)\n      values[i] = -ref.laplacian(points[i]);\n  }\n\n\n\n  // @sect3{Auxiliary functions}\n  // The following two auxiliary functions are used to compute\n  // jump terms for $u_h$ and $\\nabla u_h$ on a face,\n  // respectively.\n  template <int dim>\n  void get_function_jump(const FEInterfaceValues<dim> &fe_iv,\n                         const Vector<double> &        solution,\n                         std::vector<double> &         jump)\n  {\n    const unsigned int                 n_q = fe_iv.n_quadrature_points;\n    std::array<std::vector<double>, 2> face_values;\n    jump.resize(n_q);\n    for (unsigned int i = 0; i < 2; ++i)\n      {\n        face_values[i].resize(n_q);\n        fe_iv.get_fe_face_values(i).get_function_values(solution,\n                                                        face_values[i]);\n      }\n    for (unsigned int q = 0; q < n_q; ++q)\n      jump[q] = face_values[0][q] - face_values[1][q];\n  }\n\n\n\n  template <int dim>\n  void get_function_gradient_jump(const FEInterfaceValues<dim> &fe_iv,\n                                  const Vector<double> &        solution,\n                                  std::vector<Tensor<1, dim>> & gradient_jump)\n  {\n    const unsigned int          n_q = fe_iv.n_quadrature_points;\n    std::vector<Tensor<1, dim>> face_gradients[2];\n    gradient_jump.resize(n_q);\n    for (unsigned int i = 0; i < 2; ++i)\n      {\n        face_gradients[i].resize(n_q);\n        fe_iv.get_fe_face_values(i).get_function_gradients(solution,\n                                                           face_gradients[i]);\n      }\n    for (unsigned int q = 0; q < n_q; ++q)\n      gradient_jump[q] = face_gradients[0][q] - face_gradients[1][q];\n  }\n\n  // This function computes the penalty $\\sigma$.\n  double get_penalty_factor(const unsigned int fe_degree,\n                            const double       cell_extent_left,\n                            const double       cell_extent_right)\n  {\n    const unsigned int degree = std::max(1U, fe_degree);\n    return degree * (degree + 1.) * 0.5 *\n           (1. / cell_extent_left + 1. / cell_extent_right);\n  }\n\n\n  // @sect3{The CopyData}\n  // In the following, we define \"Copy\" objects for the MeshWorker::mesh_loop(),\n  // which is essentially the same as step-12. Note that the\n  // \"Scratch\" object is not defined here because we use\n  // MeshWorker::ScratchData<dim> instead. (The use of \"Copy\" and \"Scratch\"\n  // objects is extensively explained in the WorkStream namespace documentation.\n  struct CopyDataFace\n  {\n    FullMatrix<double>                   cell_matrix;\n    std::vector<types::global_dof_index> joint_dof_indices;\n    std::array<double, 2>                values;\n    std::array<unsigned int, 2>          cell_indices;\n  };\n\n\n\n  struct CopyData\n  {\n    FullMatrix<double>                   cell_matrix;\n    Vector<double>                       cell_rhs;\n    std::vector<types::global_dof_index> local_dof_indices;\n    std::vector<CopyDataFace>            face_data;\n    double                               value;\n    unsigned int                         cell_index;\n\n\n    template <class Iterator>\n    void reinit(const Iterator &cell, const unsigned int dofs_per_cell)\n    {\n      cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n      cell_rhs.reinit(dofs_per_cell);\n      local_dof_indices.resize(dofs_per_cell);\n      cell->get_dof_indices(local_dof_indices);\n    }\n  };\n\n\n\n  // @sect3{The SIPGLaplace class}\n  // After these preparations, we proceed with the main class of this program,\n  // called `SIPGLaplace`. The overall structure of the class is as in many\n  // of the other tutorial programs. Major differences will only come up in the\n  // implementation of the assemble functions, since we use FEInterfaceValues to\n  // assemble face terms.\n  template <int dim>\n  class SIPGLaplace\n  {\n  public:\n    SIPGLaplace(const TestCase &test_case);\n    void run();\n\n  private:\n    void setup_system();\n    void assemble_system();\n    void solve();\n    void refine_grid();\n    void output_results(const unsigned int cycle) const;\n\n    void   compute_errors();\n    void   compute_error_estimate();\n    double compute_energy_norm_error();\n\n    Triangulation<dim>    triangulation;\n    const unsigned int    degree;\n    const QGauss<dim>     quadrature;\n    const QGauss<dim - 1> face_quadrature;\n    const QGauss<dim>     quadrature_overintegration;\n    const QGauss<dim - 1> face_quadrature_overintegration;\n    const MappingQ1<dim>  mapping;\n\n    using ScratchData = MeshWorker::ScratchData<dim>;\n\n    const FE_DGQ<dim> fe;\n    DoFHandler<dim>   dof_handler;\n\n    SparsityPattern      sparsity_pattern;\n    SparseMatrix<double> system_matrix;\n    Vector<double>       solution;\n    Vector<double>       system_rhs;\n\n    // The remainder of the class's members are used for the following:\n    // - Vectors to store error estimator square and energy norm square per\n    // cell.\n    // - Print convergence rate and errors on the screen.\n    // - The fiffusion coefficient $\\nu$ is set to 1.\n    // - Members that store information about the test case to be computed.\n    Vector<double> estimated_error_square_per_cell;\n    Vector<double> energy_norm_square_per_cell;\n\n    ConvergenceTable convergence_table;\n\n    const double diffusion_coefficient = 1.;\n\n    const TestCase                       test_case;\n    std::unique_ptr<const Function<dim>> exact_solution;\n    std::unique_ptr<const Function<dim>> rhs_function;\n  };\n\n  // The constructor here takes the test case as input and then\n  // determines the correct solution and right-hand side classes. The\n  // remaining member variables are initialized in the obvious way.\n  template <int dim>\n  SIPGLaplace<dim>::SIPGLaplace(const TestCase &test_case)\n    : degree(3)\n    , quadrature(degree + 1)\n    , face_quadrature(degree + 1)\n    , quadrature_overintegration(degree + 2)\n    , face_quadrature_overintegration(degree + 2)\n    , mapping()\n    , fe(degree)\n    , dof_handler(triangulation)\n    , test_case(test_case)\n  {\n    if (test_case == TestCase::convergence_rate)\n      {\n        exact_solution = std::make_unique<const SmoothSolution<dim>>();\n        rhs_function   = std::make_unique<const SmoothRightHandSide<dim>>();\n      }\n\n    else if (test_case == TestCase::l_singularity)\n      {\n        exact_solution =\n          std::make_unique<const Functions::LSingularityFunction>();\n        rhs_function = std::make_unique<const SingularRightHandSide<dim>>();\n      }\n    else\n      AssertThrow(false, ExcNotImplemented());\n  }\n\n\n\n  template <int dim>\n  void SIPGLaplace<dim>::setup_system()\n  {\n    dof_handler.distribute_dofs(fe);\n    DynamicSparsityPattern dsp(dof_handler.n_dofs());\n    DoFTools::make_flux_sparsity_pattern(dof_handler, dsp);\n    sparsity_pattern.copy_from(dsp);\n\n    system_matrix.reinit(sparsity_pattern);\n    solution.reinit(dof_handler.n_dofs());\n    system_rhs.reinit(dof_handler.n_dofs());\n  }\n\n\n\n  // @sect3{The assemble_system function}\n  // The assemble function here is similar to that in step-12 and step-47.\n  // Different from assembling by hand, we just need to focus\n  // on assembling on each cell, each boundary face, and each\n  // interior face. The loops over cells and faces are handled\n  // automatically by MeshWorker::mesh_loop().\n  //\n  // The function starts by defining a local (lambda) function that is\n  // used to integrate the cell terms:\n  template <int dim>\n  void SIPGLaplace<dim>::assemble_system()\n  {\n    const auto cell_worker =\n      [&](const auto &cell, auto &scratch_data, auto &copy_data) {\n        const FEValues<dim> &fe_v          = scratch_data.reinit(cell);\n        const unsigned int   dofs_per_cell = fe_v.dofs_per_cell;\n        copy_data.reinit(cell, dofs_per_cell);\n\n        const auto &       q_points    = scratch_data.get_quadrature_points();\n        const unsigned int n_q_points  = q_points.size();\n        const std::vector<double> &JxW = scratch_data.get_JxW_values();\n\n        std::vector<double> rhs(n_q_points);\n        rhs_function->value_list(q_points, rhs);\n\n        for (unsigned int point = 0; point < n_q_points; ++point)\n          for (unsigned int i = 0; i < fe_v.dofs_per_cell; ++i)\n            {\n              for (unsigned int j = 0; j < fe_v.dofs_per_cell; ++j)\n                copy_data.cell_matrix(i, j) +=\n                  diffusion_coefficient *     // nu\n                  fe_v.shape_grad(i, point) * // grad v_h\n                  fe_v.shape_grad(j, point) * // grad u_h\n                  JxW[point];                 // dx\n\n              copy_data.cell_rhs(i) += fe_v.shape_value(i, point) * // v_h\n                                       rhs[point] *                 // f\n                                       JxW[point];                  // dx\n            }\n      };\n\n    // Next, we need a function that assembles face integrals on the boundary:\n    const auto boundary_worker = [&](const auto &        cell,\n                                     const unsigned int &face_no,\n                                     auto &              scratch_data,\n                                     auto &              copy_data) {\n      const FEFaceValuesBase<dim> &fe_fv = scratch_data.reinit(cell, face_no);\n\n      const auto &       q_points      = scratch_data.get_quadrature_points();\n      const unsigned int n_q_points    = q_points.size();\n      const unsigned int dofs_per_cell = fe_fv.dofs_per_cell;\n\n      const std::vector<double> &        JxW = scratch_data.get_JxW_values();\n      const std::vector<Tensor<1, dim>> &normals =\n        scratch_data.get_normal_vectors();\n\n      std::vector<double> g(n_q_points);\n      exact_solution->value_list(q_points, g);\n\n      const double extent1 = cell->measure() / cell->face(face_no)->measure();\n      const double penalty = get_penalty_factor(degree, extent1, extent1);\n\n      for (unsigned int point = 0; point < n_q_points; ++point)\n        {\n          for (unsigned int i = 0; i < dofs_per_cell; ++i)\n            for (unsigned int j = 0; j < dofs_per_cell; ++j)\n              copy_data.cell_matrix(i, j) +=\n                (-diffusion_coefficient *        // - nu\n                   fe_fv.shape_value(i, point) * // v_h\n                   (fe_fv.shape_grad(j, point) * // (grad u_h .\n                    normals[point])              //  n)\n\n                 - diffusion_coefficient *         // - nu\n                     (fe_fv.shape_grad(i, point) * // (grad v_h .\n                      normals[point]) *            //  n)\n                     fe_fv.shape_value(j, point)   // u_h\n\n                 + diffusion_coefficient * penalty * // + nu sigma\n                     fe_fv.shape_value(i, point) *   // v_h\n                     fe_fv.shape_value(j, point)     // u_h\n\n                 ) *\n                JxW[point]; // dx\n\n          for (unsigned int i = 0; i < dofs_per_cell; ++i)\n            copy_data.cell_rhs(i) +=\n              (-diffusion_coefficient *        // - nu\n                 (fe_fv.shape_grad(i, point) * // (grad v_h .\n                  normals[point]) *            //  n)\n                 g[point]                      // g\n\n\n               + diffusion_coefficient * penalty *        // + nu sigma\n                   fe_fv.shape_value(i, point) * g[point] // v_h g\n\n               ) *\n              JxW[point]; // dx\n        }\n    };\n\n    // Finally, a function that assembles face integrals on interior\n    // faces. To reinitialize FEInterfaceValues, we need to pass\n    // cells, face and subface indices (for adaptive refinement) to\n    // the reinit() function of FEInterfaceValues:\n    const auto face_worker = [&](const auto &        cell,\n                                 const unsigned int &f,\n                                 const unsigned int &sf,\n                                 const auto &        ncell,\n                                 const unsigned int &nf,\n                                 const unsigned int &nsf,\n                                 auto &              scratch_data,\n                                 auto &              copy_data) {\n      const FEInterfaceValues<dim> &fe_iv =\n        scratch_data.reinit(cell, f, sf, ncell, nf, nsf);\n\n      const auto &       q_points   = fe_iv.get_quadrature_points();\n      const unsigned int n_q_points = q_points.size();\n\n      copy_data.face_data.emplace_back();\n      CopyDataFace &     copy_data_face = copy_data.face_data.back();\n      const unsigned int n_dofs_face    = fe_iv.n_current_interface_dofs();\n      copy_data_face.joint_dof_indices  = fe_iv.get_interface_dof_indices();\n      copy_data_face.cell_matrix.reinit(n_dofs_face, n_dofs_face);\n\n      const std::vector<double> &        JxW     = fe_iv.get_JxW_values();\n      const std::vector<Tensor<1, dim>> &normals = fe_iv.get_normal_vectors();\n\n      const double extent1 = cell->measure() / cell->face(f)->measure();\n      const double extent2 = ncell->measure() / ncell->face(nf)->measure();\n      const double penalty = get_penalty_factor(degree, extent1, extent2);\n\n      for (unsigned int point = 0; point < n_q_points; ++point)\n        {\n          for (unsigned int i = 0; i < n_dofs_face; ++i)\n            for (unsigned int j = 0; j < n_dofs_face; ++j)\n              copy_data_face.cell_matrix(i, j) +=\n                (-diffusion_coefficient *              // - nu\n                   fe_iv.jump(i, point) *              // [v_h]\n                   (fe_iv.average_gradient(j, point) * // ({grad u_h} .\n                    normals[point])                    //  n)\n\n                 - diffusion_coefficient *               // - nu\n                     (fe_iv.average_gradient(i, point) * // (grad v_h .\n                      normals[point]) *                  //  n)\n                     fe_iv.jump(j, point)                // [u_h]\n\n                 + diffusion_coefficient * penalty * // + nu sigma\n                     fe_iv.jump(i, point) *          // [v_h]\n                     fe_iv.jump(j, point)            // [u_h]\n\n                 ) *\n                JxW[point]; // dx\n        }\n    };\n\n    // The following lambda function will then copy data into the\n    // global matrix and right-hand side.  Though there are no hanging\n    // node constraints in DG discretization, we define an empty\n    // AffineConstraints object that allows us to use the\n    // AffineConstraints::distribute_local_to_global() functionality.\n    AffineConstraints<double> constraints;\n    constraints.close();\n    const auto copier = [&](const auto &c) {\n      constraints.distribute_local_to_global(c.cell_matrix,\n                                             c.cell_rhs,\n                                             c.local_dof_indices,\n                                             system_matrix,\n                                             system_rhs);\n\n      // Copy data from interior face assembly to the global matrix.\n      for (auto &cdf : c.face_data)\n        {\n          constraints.distribute_local_to_global(cdf.cell_matrix,\n                                                 cdf.joint_dof_indices,\n                                                 system_matrix);\n        }\n    };\n\n\n    // With the assembly functions defined, we can now create\n    // ScratchData and CopyData objects, and pass them together with\n    // the lambda functions above to MeshWorker::mesh_loop(). In\n    // addition, we need to specify that we want to assemble on\n    // interior faces exactly once.\n    const UpdateFlags cell_flags = update_values | update_gradients |\n                                   update_quadrature_points | update_JxW_values;\n    const UpdateFlags face_flags = update_values | update_gradients |\n                                   update_quadrature_points |\n                                   update_normal_vectors | update_JxW_values;\n\n    ScratchData scratch_data(\n      mapping, fe, quadrature, cell_flags, face_quadrature, face_flags);\n    CopyData copy_data;\n\n    MeshWorker::mesh_loop(dof_handler.begin_active(),\n                          dof_handler.end(),\n                          cell_worker,\n                          copier,\n                          scratch_data,\n                          copy_data,\n                          MeshWorker::assemble_own_cells |\n                            MeshWorker::assemble_boundary_faces |\n                            MeshWorker::assemble_own_interior_faces_once,\n                          boundary_worker,\n                          face_worker);\n  }\n\n\n\n  // @sect3{The solve() and output_results() function}\n  // The following two functions are entirely standard and without difficulty.\n  template <int dim>\n  void SIPGLaplace<dim>::solve()\n  {\n    SparseDirectUMFPACK A_direct;\n    A_direct.initialize(system_matrix);\n    A_direct.vmult(solution, system_rhs);\n  }\n\n\n\n  template <int dim>\n  void SIPGLaplace<dim>::output_results(const unsigned int cycle) const\n  {\n    const std::string filename = \"sol_Q\" + Utilities::int_to_string(degree, 1) +\n                                 \"-\" + Utilities::int_to_string(cycle, 2) +\n                                 \".vtu\";\n    std::ofstream output(filename);\n\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler(dof_handler);\n    data_out.add_data_vector(solution, \"u\", DataOut<dim>::type_dof_data);\n    data_out.build_patches(mapping);\n    data_out.write_vtu(output);\n  }\n\n\n  // @sect3{The compute_error_estimate() function}\n  // The assembly of the error estimator here is quite similar to\n  // that of the global matrix and right-had side and can be handled\n  // by the MeshWorker::mesh_loop() framework. To understand what\n  // each of the local (lambda) functions is doing, recall first that\n  // the local cell residual is defined as\n  // $h_K^2 \\left\\| f + \\nu \\Delta u_h \\right\\|_K^2$:\n  template <int dim>\n  void SIPGLaplace<dim>::compute_error_estimate()\n  {\n    const auto cell_worker =\n      [&](const auto &cell, auto &scratch_data, auto &copy_data) {\n        const FEValues<dim> &fe_v = scratch_data.reinit(cell);\n\n        copy_data.cell_index = cell->active_cell_index();\n\n        const auto &               q_points   = fe_v.get_quadrature_points();\n        const unsigned int         n_q_points = q_points.size();\n        const std::vector<double> &JxW        = fe_v.get_JxW_values();\n\n        std::vector<Tensor<2, dim>> hessians(n_q_points);\n        fe_v.get_function_hessians(solution, hessians);\n\n        std::vector<double> rhs(n_q_points);\n        rhs_function->value_list(q_points, rhs);\n\n        const double hk                   = cell->diameter();\n        double       residual_norm_square = 0;\n\n        for (unsigned int point = 0; point < n_q_points; ++point)\n          {\n            const double residual =\n              rhs[point] + diffusion_coefficient * trace(hessians[point]);\n            residual_norm_square += residual * residual * JxW[point];\n          }\n        copy_data.value = hk * hk * residual_norm_square;\n      };\n\n    // Next compute boundary terms $\\sum_{f\\in \\partial K \\cap \\partial \\Omega}\n    // \\sigma \\left\\| [  u_h-g_D ]  \\right\\|_f^2  $:\n    const auto boundary_worker = [&](const auto &        cell,\n                                     const unsigned int &face_no,\n                                     auto &              scratch_data,\n                                     auto &              copy_data) {\n      const FEFaceValuesBase<dim> &fe_fv = scratch_data.reinit(cell, face_no);\n\n      const auto &   q_points   = fe_fv.get_quadrature_points();\n      const unsigned n_q_points = q_points.size();\n\n      const std::vector<double> &JxW = fe_fv.get_JxW_values();\n\n      std::vector<double> g(n_q_points);\n      exact_solution->value_list(q_points, g);\n\n      std::vector<double> sol_u(n_q_points);\n      fe_fv.get_function_values(solution, sol_u);\n\n      const double extent1 = cell->measure() / cell->face(face_no)->measure();\n      const double penalty = get_penalty_factor(degree, extent1, extent1);\n\n      double difference_norm_square = 0.;\n      for (unsigned int point = 0; point < q_points.size(); ++point)\n        {\n          const double diff = (g[point] - sol_u[point]);\n          difference_norm_square += diff * diff * JxW[point];\n        }\n      copy_data.value += penalty * difference_norm_square;\n    };\n\n    // And finally interior face terms $\\sum_{f\\in \\partial K}\\lbrace \\sigma\n    // \\left\\| [u_h]  \\right\\|_f^2   +  h_f \\left\\|  [\\nu \\nabla u_h \\cdot\n    // \\mathbf n ] \\right\\|_f^2 \\rbrace$:\n    const auto face_worker = [&](const auto &        cell,\n                                 const unsigned int &f,\n                                 const unsigned int &sf,\n                                 const auto &        ncell,\n                                 const unsigned int &nf,\n                                 const unsigned int &nsf,\n                                 auto &              scratch_data,\n                                 auto &              copy_data) {\n      const FEInterfaceValues<dim> &fe_iv =\n        scratch_data.reinit(cell, f, sf, ncell, nf, nsf);\n\n      copy_data.face_data.emplace_back();\n      CopyDataFace &copy_data_face = copy_data.face_data.back();\n\n      copy_data_face.cell_indices[0] = cell->active_cell_index();\n      copy_data_face.cell_indices[1] = ncell->active_cell_index();\n\n      const std::vector<double> &        JxW     = fe_iv.get_JxW_values();\n      const std::vector<Tensor<1, dim>> &normals = fe_iv.get_normal_vectors();\n\n      const auto &       q_points   = fe_iv.get_quadrature_points();\n      const unsigned int n_q_points = q_points.size();\n\n      std::vector<double> jump(n_q_points);\n      get_function_jump(fe_iv, solution, jump);\n\n      std::vector<Tensor<1, dim>> grad_jump(n_q_points);\n      get_function_gradient_jump(fe_iv, solution, grad_jump);\n\n      const double h = cell->face(f)->diameter();\n\n      const double extent1 = cell->measure() / cell->face(f)->measure();\n      const double extent2 = ncell->measure() / ncell->face(nf)->measure();\n      const double penalty = get_penalty_factor(degree, extent1, extent2);\n\n      double flux_jump_square = 0;\n      double u_jump_square    = 0;\n      for (unsigned int point = 0; point < n_q_points; ++point)\n        {\n          u_jump_square += jump[point] * jump[point] * JxW[point];\n          const double flux_jump = grad_jump[point] * normals[point];\n          flux_jump_square +=\n            diffusion_coefficient * flux_jump * flux_jump * JxW[point];\n        }\n      copy_data_face.values[0] =\n        0.5 * h * (flux_jump_square + penalty * u_jump_square);\n      copy_data_face.values[1] = copy_data_face.values[0];\n    };\n\n    // Having computed local contributions for each cell, we still\n    // need a way to copy these into the global vector that will hold\n    // the error estimators for all cells:\n    const auto copier = [&](const auto &copy_data) {\n      if (copy_data.cell_index != numbers::invalid_unsigned_int)\n        estimated_error_square_per_cell[copy_data.cell_index] +=\n          copy_data.value;\n      for (auto &cdf : copy_data.face_data)\n        for (unsigned int j = 0; j < 2; ++j)\n          estimated_error_square_per_cell[cdf.cell_indices[j]] += cdf.values[j];\n    };\n\n    // After all of this set-up, let's do the actual work: We resize\n    // the vector into which the results will be written, and then\n    // drive the whole process using the MeshWorker::mesh_loop()\n    // function.\n    estimated_error_square_per_cell.reinit(triangulation.n_active_cells());\n\n    const UpdateFlags cell_flags =\n      update_hessians | update_quadrature_points | update_JxW_values;\n    const UpdateFlags face_flags = update_values | update_gradients |\n                                   update_quadrature_points |\n                                   update_JxW_values | update_normal_vectors;\n\n    ScratchData scratch_data(\n      mapping, fe, quadrature, cell_flags, face_quadrature, face_flags);\n\n    CopyData copy_data;\n    MeshWorker::mesh_loop(dof_handler.begin_active(),\n                          dof_handler.end(),\n                          cell_worker,\n                          copier,\n                          scratch_data,\n                          copy_data,\n                          MeshWorker::assemble_own_cells |\n                            MeshWorker::assemble_own_interior_faces_once |\n                            MeshWorker::assemble_boundary_faces,\n                          boundary_worker,\n                          face_worker);\n  }\n\n  // @sect3{The compute_energy_norm_error() function}\n  // Next, we evaluate the accuracy in terms of the energy norm.\n  // This function is similar to the assembling of the error estimator above.\n  // Here we compute the square of the energy norm defined by\n  // @f[\n  //   \\|u \\|_{1,h}^2 = \\sum_{K \\in \\Gamma_h} \\nu\\|\\nabla u \\|_K^2 +\n  //   \\sum_{f \\in F_i} \\sigma \\| [ u ] \\|_f^2 +\n  //   \\sum_{f \\in F_b} \\sigma  \\|u\\|_f^2.\n  // @f]\n  // Therefore the corresponding error is\n  // @f[\n  //   \\|u -u_h \\|_{1,h}^2 = \\sum_{K \\in \\Gamma_h} \\nu\\|\\nabla (u_h - u)  \\|_K^2\n  //   + \\sum_{f \\in F_i} \\sigma  \\|[ u_h ] \\|_f^2 + \\sum_{f \\in F_b}\\sigma\n  //   \\|u_h-g_D\\|_f^2.\n  // @f]\n  template <int dim>\n  double SIPGLaplace<dim>::compute_energy_norm_error()\n  {\n    energy_norm_square_per_cell.reinit(triangulation.n_active_cells());\n\n    // Assemble $\\sum_{K \\in \\Gamma_h} \\nu\\|\\nabla (u_h - u)  \\|_K^2 $.\n    const auto cell_worker =\n      [&](const auto &cell, auto &scratch_data, auto &copy_data) {\n        const FEValues<dim> &fe_v = scratch_data.reinit(cell);\n\n        copy_data.cell_index = cell->active_cell_index();\n\n        const auto &               q_points   = fe_v.get_quadrature_points();\n        const unsigned int         n_q_points = q_points.size();\n        const std::vector<double> &JxW        = fe_v.get_JxW_values();\n\n        std::vector<Tensor<1, dim>> grad_u(n_q_points);\n        fe_v.get_function_gradients(solution, grad_u);\n\n        std::vector<Tensor<1, dim>> grad_exact(n_q_points);\n        exact_solution->gradient_list(q_points, grad_exact);\n\n        double norm_square = 0;\n        for (unsigned int point = 0; point < n_q_points; ++point)\n          {\n            norm_square +=\n              (grad_u[point] - grad_exact[point]).norm_square() * JxW[point];\n          }\n        copy_data.value = diffusion_coefficient * norm_square;\n      };\n\n    // Assemble $\\sum_{f \\in F_b}\\sigma  \\|u_h-g_D\\|_f^2$.\n    const auto boundary_worker = [&](const auto &        cell,\n                                     const unsigned int &face_no,\n                                     auto &              scratch_data,\n                                     auto &              copy_data) {\n      const FEFaceValuesBase<dim> &fe_fv = scratch_data.reinit(cell, face_no);\n\n      const auto &   q_points   = fe_fv.get_quadrature_points();\n      const unsigned n_q_points = q_points.size();\n\n      const std::vector<double> &JxW = fe_fv.get_JxW_values();\n\n      std::vector<double> g(n_q_points);\n      exact_solution->value_list(q_points, g);\n\n      std::vector<double> sol_u(n_q_points);\n      fe_fv.get_function_values(solution, sol_u);\n\n      const double extent1 = cell->measure() / cell->face(face_no)->measure();\n      const double penalty = get_penalty_factor(degree, extent1, extent1);\n\n      double difference_norm_square = 0.;\n      for (unsigned int point = 0; point < q_points.size(); ++point)\n        {\n          const double diff = (g[point] - sol_u[point]);\n          difference_norm_square += diff * diff * JxW[point];\n        }\n      copy_data.value += penalty * difference_norm_square;\n    };\n\n    // Assemble $\\sum_{f \\in F_i} \\sigma  \\| [ u_h ] \\|_f^2$.\n    const auto face_worker = [&](const auto &        cell,\n                                 const unsigned int &f,\n                                 const unsigned int &sf,\n                                 const auto &        ncell,\n                                 const unsigned int &nf,\n                                 const unsigned int &nsf,\n                                 auto &              scratch_data,\n                                 auto &              copy_data) {\n      const FEInterfaceValues<dim> &fe_iv =\n        scratch_data.reinit(cell, f, sf, ncell, nf, nsf);\n\n      copy_data.face_data.emplace_back();\n      CopyDataFace &copy_data_face = copy_data.face_data.back();\n\n      copy_data_face.cell_indices[0] = cell->active_cell_index();\n      copy_data_face.cell_indices[1] = ncell->active_cell_index();\n\n      const std::vector<double> &JxW = fe_iv.get_JxW_values();\n\n      const auto &       q_points   = fe_iv.get_quadrature_points();\n      const unsigned int n_q_points = q_points.size();\n\n      std::vector<double> jump(n_q_points);\n      get_function_jump(fe_iv, solution, jump);\n\n      const double extent1 = cell->measure() / cell->face(f)->measure();\n      const double extent2 = ncell->measure() / ncell->face(nf)->measure();\n      const double penalty = get_penalty_factor(degree, extent1, extent2);\n\n      double u_jump_square = 0;\n      for (unsigned int point = 0; point < n_q_points; ++point)\n        {\n          u_jump_square += jump[point] * jump[point] * JxW[point];\n        }\n      copy_data_face.values[0] = 0.5 * penalty * u_jump_square;\n      copy_data_face.values[1] = copy_data_face.values[0];\n    };\n\n    const auto copier = [&](const auto &copy_data) {\n      if (copy_data.cell_index != numbers::invalid_unsigned_int)\n        energy_norm_square_per_cell[copy_data.cell_index] += copy_data.value;\n      for (auto &cdf : copy_data.face_data)\n        for (unsigned int j = 0; j < 2; ++j)\n          energy_norm_square_per_cell[cdf.cell_indices[j]] += cdf.values[j];\n    };\n\n    const UpdateFlags cell_flags =\n      update_gradients | update_quadrature_points | update_JxW_values;\n    UpdateFlags face_flags =\n      update_values | update_quadrature_points | update_JxW_values;\n\n    const ScratchData scratch_data(mapping,\n                                   fe,\n                                   quadrature_overintegration,\n                                   cell_flags,\n                                   face_quadrature_overintegration,\n                                   face_flags);\n\n    CopyData copy_data;\n    MeshWorker::mesh_loop(dof_handler.begin_active(),\n                          dof_handler.end(),\n                          cell_worker,\n                          copier,\n                          scratch_data,\n                          copy_data,\n                          MeshWorker::assemble_own_cells |\n                            MeshWorker::assemble_own_interior_faces_once |\n                            MeshWorker::assemble_boundary_faces,\n                          boundary_worker,\n                          face_worker);\n    const double energy_error =\n      std::sqrt(energy_norm_square_per_cell.l1_norm());\n    return energy_error;\n  }\n\n\n\n  // @sect3{The refine_grid() function}\n  template <int dim>\n  void SIPGLaplace<dim>::refine_grid()\n  {\n    const double refinement_fraction = 0.1;\n\n    GridRefinement::refine_and_coarsen_fixed_number(\n      triangulation, estimated_error_square_per_cell, refinement_fraction, 0.);\n\n    triangulation.execute_coarsening_and_refinement();\n  }\n\n\n\n  // @sect3{The compute_errors() function}\n  // We compute three errors in the $L_2$ norm, $H_1$ seminorm, and\n  // the energy norm, respectively. These are then printed to screen,\n  // but also stored in a table that records how these errors decay\n  // with mesh refinement and which can be output in one step at the\n  // end of the program.\n  template <int dim>\n  void SIPGLaplace<dim>::compute_errors()\n  {\n    double L2_error, H1_error, energy_error;\n\n    {\n      Vector<float> difference_per_cell(triangulation.n_active_cells());\n      VectorTools::integrate_difference(mapping,\n                                        dof_handler,\n                                        solution,\n                                        *(exact_solution.get()),\n                                        difference_per_cell,\n                                        quadrature_overintegration,\n                                        VectorTools::L2_norm);\n\n      L2_error = VectorTools::compute_global_error(triangulation,\n                                                   difference_per_cell,\n                                                   VectorTools::L2_norm);\n      convergence_table.add_value(\"L2\", L2_error);\n    }\n\n    {\n      Vector<float> difference_per_cell(triangulation.n_active_cells());\n      VectorTools::integrate_difference(mapping,\n                                        dof_handler,\n                                        solution,\n                                        *(exact_solution.get()),\n                                        difference_per_cell,\n                                        quadrature_overintegration,\n                                        VectorTools::H1_seminorm);\n\n      H1_error = VectorTools::compute_global_error(triangulation,\n                                                   difference_per_cell,\n                                                   VectorTools::H1_seminorm);\n      convergence_table.add_value(\"H1\", H1_error);\n    }\n\n    {\n      energy_error = compute_energy_norm_error();\n      convergence_table.add_value(\"Energy\", energy_error);\n    }\n\n    std::cout << \"  Error in the L2 norm         : \" << L2_error << std::endl\n              << \"  Error in the H1 seminorm     : \" << H1_error << std::endl\n              << \"  Error in the energy norm     : \" << energy_error\n              << std::endl;\n  }\n\n\n\n  // @sect3{The run() function}\n  template <int dim>\n  void SIPGLaplace<dim>::run()\n  {\n    const unsigned int max_cycle =\n      (test_case == TestCase::convergence_rate ? 6 : 20);\n    for (unsigned int cycle = 0; cycle < max_cycle; ++cycle)\n      {\n        std::cout << \"Cycle \" << cycle << std::endl;\n\n        switch (test_case)\n          {\n            case TestCase::convergence_rate:\n              {\n                if (cycle == 0)\n                  {\n                    GridGenerator::hyper_cube(triangulation);\n\n                    triangulation.refine_global(2);\n                  }\n                else\n                  {\n                    triangulation.refine_global(1);\n                  }\n                break;\n              }\n\n            case TestCase::l_singularity:\n              {\n                if (cycle == 0)\n                  {\n                    GridGenerator::hyper_L(triangulation);\n                    triangulation.refine_global(3);\n                  }\n                else\n                  {\n                    refine_grid();\n                  }\n                break;\n              }\n\n            default:\n              {\n                Assert(false, ExcNotImplemented());\n              }\n          }\n\n        std::cout << \"  Number of active cells       : \"\n                  << triangulation.n_active_cells() << std::endl;\n        setup_system();\n\n        std::cout << \"  Number of degrees of freedom : \" << dof_handler.n_dofs()\n                  << std::endl;\n\n        assemble_system();\n        solve();\n        output_results(cycle);\n        {\n          convergence_table.add_value(\"cycle\", cycle);\n          convergence_table.add_value(\"cells\", triangulation.n_active_cells());\n          convergence_table.add_value(\"dofs\", dof_handler.n_dofs());\n        }\n        compute_errors();\n\n        if (test_case == TestCase::l_singularity)\n          {\n            compute_error_estimate();\n            std::cout << \"  Estimated error              : \"\n                      << std::sqrt(estimated_error_square_per_cell.l1_norm())\n                      << std::endl;\n\n            convergence_table.add_value(\n              \"Estimator\",\n              std::sqrt(estimated_error_square_per_cell.l1_norm()));\n          }\n        std::cout << std::endl;\n      }\n\n    // Having run all of our computations, let us tell the convergence\n    // table how to format its data and output it to screen:\n    convergence_table.set_precision(\"L2\", 3);\n    convergence_table.set_precision(\"H1\", 3);\n    convergence_table.set_precision(\"Energy\", 3);\n\n    convergence_table.set_scientific(\"L2\", true);\n    convergence_table.set_scientific(\"H1\", true);\n    convergence_table.set_scientific(\"Energy\", true);\n\n    if (test_case == TestCase::convergence_rate)\n      {\n        convergence_table.evaluate_convergence_rates(\n          \"L2\", ConvergenceTable::reduction_rate_log2);\n        convergence_table.evaluate_convergence_rates(\n          \"H1\", ConvergenceTable::reduction_rate_log2);\n      }\n    if (test_case == TestCase::l_singularity)\n      {\n        convergence_table.set_precision(\"Estimator\", 3);\n        convergence_table.set_scientific(\"Estimator\", true);\n      }\n\n    std::cout << \"degree = \" << degree << std::endl;\n    convergence_table.write_text(\n      std::cout, TableHandler::TextOutputFormat::org_mode_table);\n  }\n} // namespace Step74\n\n\n\n// @sect3{The main() function}\n// The following <code>main</code> function is similar to previous examples as\n// well, and need not be commented on.\nint main()\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step74;\n\n      const TestCase test_case = TestCase::l_singularity;\n\n      SIPGLaplace<2> problem(test_case);\n      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\n  return 0;\n}\n", "meta": {"hexsha": "e82c46259601ef4f221458859000bb363fbd3d6b", "size": 43455, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-74/step-74.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-74/step-74.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-74/step-74.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.7541268462, "max_line_length": 80, "alphanum_fraction": 0.5659187665, "num_tokens": 9829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173791645582, "lm_q2_score": 0.6825737214979746, "lm_q1q2_score": 0.5482253239731637}}
{"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{\nMatrix4Xd M = Matrix4Xd::Random(4,5);\nProjective3d P(Matrix4d::Random());\ncout << \"The matrix M is:\" << endl << M << endl << endl;\ncout << \"M.colwise().hnormalized():\" << endl << M.colwise().hnormalized() << endl << endl;\ncout << \"P*M:\" << endl << P*M << endl << endl;\ncout << \"(P*M).colwise().hnormalized():\" << endl << (P*M).colwise().hnormalized() << endl << endl;\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "9cf6aee558dd9432fd826e031b9bdeeeb386fec2", "size": 901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_DirectionWise_hnormalized.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_DirectionWise_hnormalized.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_DirectionWise_hnormalized.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": 30.0333333333, "max_line_length": 224, "alphanum_fraction": 0.6492785794, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5482248677167957}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 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#include <boost/simd/function/scalar/round2even.hpp>\n#include <simd_test.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/mhalf.hpp>\n\nSTF_CASE_TPL ( \"round2even real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::round2even;\n  using r_t = decltype(round2even(T()));\n\n  // return type conformity test\n  STF_TYPE_IS( r_t, T );\n\n  // specific values tests\n  STF_ULP_EQUAL(round2even(T(1.4)), 1, 0);\n  STF_ULP_EQUAL(round2even(T(1.5)), 2, 0);\n  STF_ULP_EQUAL(round2even(T(1.6)), 2, 0);\n  STF_ULP_EQUAL(round2even(T(2.5)), 2, 0);\n  STF_ULP_EQUAL(round2even(bs::Half<T>()), bs::Zero<r_t>(), 0);\n  STF_ULP_EQUAL(round2even(bs::Inf<T>()), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(round2even(bs::Mhalf<T>()), bs::Zero<r_t>(), 0);\n  STF_ULP_EQUAL(round2even(bs::Minf<T>()), bs::Minf<r_t>(), 0);\n  STF_ULP_EQUAL(round2even(bs::Mone<T>()), bs::Mone<r_t>(), 0);\n  STF_ULP_EQUAL(round2even(bs::Nan<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(round2even(bs::One<T>()), bs::One<r_t>(), 0);\n  STF_ULP_EQUAL(round2even(bs::Zero<T>()), bs::Zero<r_t>(), 0);\n} // end of test for floating_\n\nSTF_CASE_TPL (\" round2evenunsigned_int__1_0\",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::round2even;\n  using r_t = decltype(round2even(T()));\n\n  // return type conformity test\n  STF_TYPE_IS( r_t, T );\n\n  // specific values tests\n  STF_ULP_EQUAL(round2even(bs::One<T>()), bs::One<r_t>(), 0);\n  STF_ULP_EQUAL(round2even(bs::Zero<T>()), bs::Zero<r_t>(), 0);\n} // end of test for unsigned_int_\n\nSTF_CASE_TPL (\" round2evensigned_ int\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::round2even;\n  using r_t = decltype(round2even(T()));\n\n  // return type conformity test\n  STF_TYPE_IS( r_t, T );\n\n  // specific values tests\n  STF_ULP_EQUAL(round2even(bs::Mone<T>()), bs::Mone<r_t>(), 0);\n  STF_ULP_EQUAL(round2even(bs::One<T>()), bs::One<r_t>(), 0);\n  STF_ULP_EQUAL(round2even(bs::Zero<T>()), bs::Zero<T>(), 0);\n} // end of test for signed_int_\n", "meta": {"hexsha": "ebf294024398c19b57a250d6b616e17a86a6339e", "size": 2769, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/round2even.cpp", "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": "test/function/scalar/round2even.cpp", "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": "test/function/scalar/round2even.cpp", "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": 35.961038961, "max_line_length": 100, "alphanum_fraction": 0.639219935, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5482248630672863}}
{"text": "/*=========================================================================\n\nLibrary:   TubeTK\n\nCopyright 2010 Kitware Inc. 28 Corporate Drive,\nClifton Park, NY, 12065, USA.\n\nAll rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n=========================================================================*/\n\n#include \"tubeMessage.h\"\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/p_square_quantile.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/foreach.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n#include <itkImageFileReader.h>\n#include <itkImageRegionConstIterator.h>\n#include <itkStatisticsImageFilter.h>\n\n#include \"ComputeImageQuantilesCLP.h\"\n\nenum { Dimension = 3 };\n\n//using namespace boost;\nusing namespace boost::accumulators;\n\ntypedef itk::Image< float, Dimension >                      ImageType;\ntypedef ImageType::IndexType                                ImageIndexType;\ntypedef ImageType::PixelType                                ImagePixelType;\ntypedef ImageType::SizeType                                 ImageSizeType;\ntypedef itk::ImageFileReader< ImageType >                   ImageReaderType;\ntypedef itk::StatisticsImageFilter< ImageType >             StatisticsImageFilterType;\ntypedef accumulator_set< ImagePixelType,\n                         stats< tag::p_square_quantile > >  QuantileAccumulatorType;\ntypedef itk::ImageRegionConstIterator<ImageType>            ImageIteratorType;\n\n\n/**\n * Take an image and compute a collection of pixel/voxel quantiles\n * using the BOOST accumulators. The function uses P^2 quantile\n * computation which gives an approximate quantile and is very\n * efficient in terms of storage and runtime complexity. The values\n * are actually never stored.\n */\nvoid computeQuantiles( ImageType::Pointer image,\n                       const std::vector<float> & quantiles,\n                       std::vector<ImagePixelType> & quantileValues)\n{\n  assert(quantileValues.empty());\n\n  // Create a and configure a vector of length N of pointers\n  // to BOOST accumulators -- Each of the N accumulators will\n  // estimate exactly one of the given N desired quantile. If\n  // the desired quantile is not within (0,1), throw an exception.\n  std::vector<QuantileAccumulatorType *> accVec;\n  BOOST_FOREACH(float q, quantiles)\n    {\n    if( q <= 0 || q >= 1 )\n      {\n      tube::ErrorMessage(\"Check quantile range!\");\n      throw std::exception();\n      }\n    tube::FmtInfoMessage(\"Configure accumulator for quantile = %.2f\", q);\n\n    QuantileAccumulatorType *acc = new QuantileAccumulatorType(\n      quantile_probability = q);\n    accVec.push_back(acc);\n    }\n\n\n  // Use an image iterator to iterate over all pixel/voxel and\n  // and then add those values to all the accumulators. Adding\n  // the values will incrementally compute the quantile estimates.\n  ImageIteratorType imIt( image, image->GetLargestPossibleRegion() );\n  imIt.GoToBegin();\n  while( !imIt.IsAtEnd() )\n    {\n    ImagePixelType p = imIt.Get();\n    BOOST_FOREACH( QuantileAccumulatorType *acc, accVec )\n      {\n      (*acc)( p );\n      }\n    ++imIt;\n    }\n\n\n  // Finally, iterate over the accumulators, query the\n  // estimated quantiles and fill the output vector\n  BOOST_FOREACH( QuantileAccumulatorType *acc, accVec)\n    {\n    ImagePixelType qVal = p_square_quantile(*acc);\n    quantileValues.push_back(qVal);\n    delete acc;\n    acc = NULL;\n    }\n  return;\n}\n\n\n/**\n * Writes quantiles and quantile values to a file in JSON\n * format. Example (for quantiles 0.05, 0.5, 0.95):\n *\n *  {\n *     \"quantiles\":\n *     [\n *        <quantile0>,\n *        <quantile1>,\n *        ...\n *        <quantileN>\n *     ],\n *     \"quantileValues\":\n *     [\n *        <quantileValue0>,\n *        <quantileValue1>,\n *        ...\n *        <quantileValueN>\n *     ]\n *   }\n */\nvoid writeQuantilesToJSONFile( const std::vector<float>& quantiles,\n                           const std::vector<ImagePixelType>& quantileValues,\n                           const std::string &outFile )\n{\n  tube::FmtInfoMessage( \"Writing %d quantiles to %s\",\n        quantiles.size(), outFile.c_str());\n\n  try\n    {\n    boost::property_tree::ptree root;\n    boost::property_tree::ptree quantilesJSON;\n    boost::property_tree::ptree quantileValuesJSON;\n\n    for( unsigned int i=0; i<quantiles.size(); ++i )\n      {\n      boost::property_tree::ptree quantileElementJSON;\n      boost::property_tree::ptree quantileValueElementJSON;\n      quantileElementJSON.put( \"\", quantiles[i] );\n      quantileValueElementJSON.put( \"\", quantileValues[i] );\n      quantilesJSON.push_back(make_pair( \"\", quantileElementJSON ) );\n      quantileValuesJSON.push_back(make_pair( \"\", quantileValueElementJSON ) );\n      }\n    root.add_child( \"quantiles\", quantilesJSON);\n    root.add_child( \"quantileValues\", quantileValuesJSON );\n    boost::property_tree::write_json( outFile, root );\n    }\n  catch(boost::property_tree::json_parser::json_parser_error &e)\n    {\n    tube::ErrorMessage( e.message() );\n    throw std::exception();\n    }\n}\n\n\n/**\n * Writes the quantiles to a plain ASCII file, one\n * quantile value per line.\n */\nvoid writeQuantilesToTextFile( const std::vector<float> &quantiles,\n                               const std::string &outFile )\n{\n  std::ofstream quantileFile;\n  quantileFile.open( outFile.c_str() );\n  for( unsigned int i=0; i<quantiles.size(); ++i )\n    {\n    quantileFile << quantiles[i] << std::endl;\n    }\n  quantileFile.close();\n}\n\n\nint main( int argc, char * argv[] )\n{\n  PARSE_ARGS;\n\n  tube::FmtInfoMessage(\"Reading image file %s\",\n    imageFile.c_str());\n  ImageReaderType::Pointer imReader = ImageReaderType::New();\n  imReader->SetFileName( imageFile );\n  ImageType::Pointer im;\n\n  try\n    {\n    imReader->Update();\n    im = imReader->GetOutput();\n    }\n  catch( itk::ExceptionObject &ex )\n    {\n    tube::ErrorMessage( ex.GetDescription() );\n    return EXIT_FAILURE;\n    }\n\n  std::vector<float> quantileValues;\n   try\n    {\n    computeQuantiles(im, quantiles, quantileValues);\n    if( outputPlainText )\n      {\n      writeQuantilesToTextFile( quantileValues, outFile );\n      }\n    else\n      {\n      writeQuantilesToJSONFile( quantiles, quantileValues, outFile );\n      }\n    }\n  catch(std::exception &e)\n    {\n    return EXIT_FAILURE;\n    }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "c8cb15370eedfe084b0a1e7edb8c6f2389dd41fb", "size": 6809, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Applications/ComputeImageQuantiles/ComputeImageQuantiles.cxx", "max_stars_repo_name": "matthieuheitz/TubeTK", "max_stars_repo_head_hexsha": "1b255d71bb722fa3622df766a706858afacf18c7", "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": "Applications/ComputeImageQuantiles/ComputeImageQuantiles.cxx", "max_issues_repo_name": "matthieuheitz/TubeTK", "max_issues_repo_head_hexsha": "1b255d71bb722fa3622df766a706858afacf18c7", "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": "Applications/ComputeImageQuantiles/ComputeImageQuantiles.cxx", "max_forks_repo_name": "matthieuheitz/TubeTK", "max_forks_repo_head_hexsha": "1b255d71bb722fa3622df766a706858afacf18c7", "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.8640350877, "max_line_length": 86, "alphanum_fraction": 0.649140843, "num_tokens": 1622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.548224860080032}}
{"text": "#include <catch.hpp>\n#include <typeclass/eq/list.h>\n#include <typeclass/eq/optional.h>\n#include <typeclass/eq/vector.h>\n#include <typeclass/eq/scalar.h>\n#include <typeclass/functor.h>\n#include <typeclass/functor/list.h>\n#include <typeclass/functor/optional.h>\n#include <typeclass/functor/vector.h>\n#include <typeclass/functor/future.h>\n#include <boost/optional.hpp>\n#include <future>\n\n\nTEST_CASE(\"typeclass functor\") {\n    using namespace funcpp::typeclass::functor;\n    using namespace funcpp::typeclass::eq;\n    using namespace funcpp::typeclass::eq::operators;\n    GIVEN(\"a list of ints\") {\n        std::list<int> a{1,2,3};\n        auto result = fmap([](auto x){ return x*2; }, a);\n        REQUIRE((std::list<int>{2,4,6} == result));\n    }\n    GIVEN(\"a vector of ints\") {\n        std::vector<int> a{1,2,3};\n        auto result = fmap([](auto x){ return x*2; }, a);\n        REQUIRE((std::vector<int>{2,4,6} == result));\n    }\n    GIVEN(\"an optional int\") {\n        boost::optional<int> a{10};\n        auto result = fmap([](auto x){ return x*2; }, a);\n        REQUIRE((boost::optional<int>{20} == result));\n    }\n    GIVEN(\"a future of int\") {\n        std::promise<int> a;\n        auto result = fmap([](auto x){ return x*2; }, a.get_future());\n        a.set_value(10);\n        REQUIRE(20 == result.get());\n    }\n}", "meta": {"hexsha": "9774e8e806fa6cf2361202914ceec81fca0f52e2", "size": 1314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/typeclass/test/src/typeclass/functor.cpp", "max_stars_repo_name": "julian-becker/funcpp", "max_stars_repo_head_hexsha": "0e94c7c115d542fd0b1a16450975df7b02c56b4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/typeclass/test/src/typeclass/functor.cpp", "max_issues_repo_name": "julian-becker/funcpp", "max_issues_repo_head_hexsha": "0e94c7c115d542fd0b1a16450975df7b02c56b4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/typeclass/test/src/typeclass/functor.cpp", "max_forks_repo_name": "julian-becker/funcpp", "max_forks_repo_head_hexsha": "0e94c7c115d542fd0b1a16450975df7b02c56b4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.85, "max_line_length": 70, "alphanum_fraction": 0.6057838661, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5481066501446021}}
{"text": "#include \"interface.h\"\n\n#include <cmr/env.h>\n\n#include \"total_unimodularity.hpp\"\n#include \"unimodularity.hpp\"\n\n#include <boost/numeric/ublas/io.hpp>\n\nextern \"C\"\nCMR_ERROR CMRinterfaceTU(CMR* cmr, CMR_CHRMAT* matrix, bool* pisTU, CMR_DEC** pdec, CMR_SUBMAT** psubmatrix)\n{\n  assert(cmr);\n  assert(matrix);\n  assert(pisTU);\n  assert(!psubmatrix || !*psubmatrix);\n\n  tu::integer_matrix mat(matrix->numRows, matrix->numColumns, 0);\n  for (size_t row = 0; row < (size_t)matrix->numRows; ++row)\n  {\n    size_t first = matrix->rowSlice[row];\n    size_t beyond = matrix->rowSlice[row + 1];\n    for (size_t i = first; i < beyond; ++i)\n    {\n      size_t column = matrix->entryColumns[i];\n      mat(row,column) = matrix->entryValues[i];\n    }\n  }\n\n  tu::submatrix_indices violator;\n  if (psubmatrix)\n  {\n    *pisTU = tu::is_totally_unimodular(mat, violator);\n  }\n  else\n  {\n    *pisTU = tu::is_totally_unimodular(mat);\n  }\n\n  if (*pisTU && pdec)\n    fprintf(stderr, \"Retrieval of decomposition is not implemented, yet.\");\n\n  if (!violator.rows.empty())\n  {\n    CMR_CALL( CMRsubmatCreate(cmr, violator.rows.size(), violator.columns.size(), psubmatrix) );\n    CMR_SUBMAT* submatrix = *psubmatrix;\n    for (size_t row = 0; row < submatrix->numRows; ++row)\n      submatrix->rows[row] = violator.rows[row];\n    for (size_t column = 0; column < submatrix->numColumns; ++column)\n      submatrix->columns[column] = violator.columns[column];\n  }\n\n  return CMR_OKAY;\n}\n\nCMR_ERROR CMRinterfaceKModular(CMR* cmr, CMR_CHRMAT* matrix, size_t* pk)\n{\n  assert(cmr);\n  assert(matrix);\n  assert(pk);\n\n  tu::integer_matrix mat(matrix->numRows, matrix->numColumns, 0);\n  for (size_t row = 0; row < (size_t)matrix->numRows; ++row)\n  {\n    size_t first = matrix->rowSlice[row];\n    size_t beyond = matrix->rowSlice[row + 1];\n    for (size_t i = first; i < beyond; ++i)\n    {\n      size_t column = matrix->entryColumns[i];\n      mat(row,column) = matrix->entryValues[i];\n    }\n  }\n\n  size_t rank;\n  unsigned int k;\n  bool result = tu::is_k_modular(mat, rank, k);\n  *pk = result ? k : 0;\n\n  return CMR_OKAY;\n}\n", "meta": {"hexsha": "86e1520fcde4870519353d5ff775e54de85e0a4b", "size": 2076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cmr/interface.cpp", "max_stars_repo_name": "discopt/cmr", "max_stars_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-04-13T12:48:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T11:56:31.000Z", "max_issues_repo_path": "src/cmr/interface.cpp", "max_issues_repo_name": "xammy/unimodularity-test", "max_issues_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2021-08-19T09:06:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-27T23:18:47.000Z", "max_forks_repo_path": "src/cmr/interface.cpp", "max_forks_repo_name": "discopt/cmr", "max_forks_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_forks_repo_licenses": ["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.6296296296, "max_line_length": 108, "alphanum_fraction": 0.6526974952, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5481066447921894}}
{"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 crpMM test\n#include <boost/test/unit_test.hpp>\n\n#include <dpMM/crpMM.hpp>\n#include <dpMM/niwBaseMeasure.hpp>\n#include <dpMM/niwSphere.hpp>\n#include <dpMM/vmfBaseMeasure.hpp>\n#include <dpMM/vmfBaseMeasure3D.hpp>\n\nBOOST_AUTO_TEST_CASE(crpMM_test)\n{\n  uint32_t N=20;\n  MatrixXd x(3,N);\n  for(uint32_t i=0; i<N; ++i)\n    if(i<N/2)\n      x.col(i) << 0.0,0.0,0.0;\n    else\n      x.col(i) << 10.0,10.0,10.0;\n\n  double nu = 4.0;\n  double kappa = 4.0;\n  MatrixXd Delta(3,3);\n  Delta << .1,0.0,0.0,\n        0.0,.1,0.0,\n        0.0,0.0,.1;\n  VectorXd theta(3);\n  theta << 0.0,0.0,0.0;\n  double alpha = 1.0;\n\n  boost::mt19937 rndGen(9191);\n  NIW<double> niw(Delta,theta,nu,kappa,&rndGen);\n\n//  shared_ptr<NiwMarginalized<double> > niwMargBase(\n//      new NiwMarginalized<double>(niw));\n//  CrpMM<double> dirGMM_marg(alpha,niwMargBase,2,&rndGen);\n//  \n//  dirGMM_marg.initialize(x);\n//  cout<<\"------ sampling -- NIW marginalized\"<<endl;\n//  cout<<dirGMM_marg.labels().transpose()<<endl;\n//  for(uint32_t t=0; t<30; ++t)\n//  {\n//    dirGMM_marg.sampleLabels();\n//    dirGMM_marg.sampleParameters();\n//    cout<<dirGMM_marg.labels().transpose()\n//      <<\" logJoint=\"<<dirGMM_marg.logJoint()<<endl;\n//  }\n\n  shared_ptr<NiwSampled<double> > niwSampled(\n      new NiwSampled<double>(niw));\n  CrpMM<double> dirGMM_samp(alpha,niwSampled,2,&rndGen);\n  \n  dirGMM_samp.initialize(x);\n  cout<<\"------ sampling -- NIW sampled\"<<endl;\n  cout<<dirGMM_samp.labels().transpose()<<endl;\n  for(uint32_t t=0; t<30; ++t)\n  {\n    dirGMM_samp.sampleLabels();\n    dirGMM_samp.sampleParameters();\n    cout<<dirGMM_samp.labels().transpose()\n      <<\" logJoint=\"<<dirGMM_samp.logJoint()<<endl;\n  }\n};\n//\n//\nBOOST_AUTO_TEST_CASE(crpMM_Sphere_test)\n{\n  cout<<\"------ sampling -- NIW sphere\"<<endl;\n\n  double nu = 20.0;\n  MatrixXd Delta(2,2);\n  Delta << .01,0.0,\n        0.0,.01;\n  Delta *= nu;\n\n  boost::mt19937 rndGen(9191);\n  IW<double> iw(Delta,nu,&rndGen);\n  shared_ptr<NiwSphere<double> > niwSp( new NiwSphere<double>(iw,&rndGen));\n  double alpha = 1.0;\n  CrpMM<double> dirGMM_sp(alpha,niwSp,1,&rndGen);\n  \n  uint32_t N=20;\n  uint32_t K=2;\n  MatrixXd x(3,N);\n  MatrixXd mus = sampleClustersOnSphere<double>(x, K);\n\n  dirGMM_sp.initialize(x);\n\n  cout<<\"true means: \"<<endl<<mus<<endl;\n  cout<<dirGMM_sp.labels().transpose()<<endl;\n  for(uint32_t t=0; t<10; ++t)\n  {\n    dirGMM_sp.sampleParameters();\n//    for(uint32_t k=0; k<dirGMM_sp.getK(); ++k)\n//    {\n//      cout<<\"  k: \"<<k<<\" \"<<endl; \n//      dirGMM_sp.getTheta(k)->print();\n//    }\n    dirGMM_sp.sampleLabels();\n    cout<<\"@t=\"<<t<<\" \"<<dirGMM_sp.labels().transpose()\n      <<\" logJoint=\"<<dirGMM_sp.logJoint()<<endl;\n  }\n  MatrixXd logLikes;\n  MatrixXu inds = dirGMM_sp.mostLikelyInds(5,logLikes);\n  cout<<\"most likely indices\"<<endl;\n  cout<<inds<<endl;\n  cout<<\"----------------------------------------\"<<endl;\n};\n\nBOOST_AUTO_TEST_CASE(crpMM_vMF_test)\n{\n  cout<<\"------ sampling -- CRP-vMF\"<<endl;\n\n  double a0 = 2.0;\n  double b0 = 1.7;\n  double t0 = 0.01;\n  VectorXd m0(3);\n  m0 << 1.0,0.0,0.0;\n\n  boost::mt19937 rndGen(9191);\n\n  vMFpriorFull<double> vMFprior(m0,t0,a0,b0,&rndGen);\n  shared_ptr<vMFbase<double> > vMFsampled( new vMFbase<double>(vMFprior));\n  \n  double alpha = 1.0;\n  CrpMM<double> dirvMF_sp(alpha,vMFsampled,1,&rndGen);\n  \n  uint32_t N=100;\n  uint32_t K=2;\n  MatrixXd x(3,N);\n  MatrixXd mus = sampleClustersOnSphere<double>(x, K);\n\n  dirvMF_sp.initialize(x);\n\n  cout<<\"true means: \"<<endl<<mus<<endl;\n  cout<<dirvMF_sp.labels().transpose()<<endl;\n  for(uint32_t t=0; t<100; ++t)\n  {\n    dirvMF_sp.sampleParameters();\n//    for(uint32_t k=0; k<dirvMF_sp.getK(); ++k)\n//    {\n//      cout<<\"  k: \"<<k<<\" \"<<endl; \n//      dirvMF_sp.getTheta(k)->print();\n//    }\n    dirvMF_sp.sampleLabels();\n    cout<<\"@t=\"<<t<<\" \"<<dirvMF_sp.labels().transpose()\n      <<\" logJoint=\"<<dirvMF_sp.logJoint()<<endl;\n  }\n//  MatrixXd logLikes;\n//  MatrixXu inds = dirvMF_sp.mostLikelyInds(5,logLikes);\n//  cout<<\"most likely indices\"<<endl;\n//  cout<<inds<<endl;\n  cout<<\"----------------------------------------\"<<endl;\n};\n\nBOOST_AUTO_TEST_CASE(crpMM_vMFanalytic_test)\n{\n  cout<<\"------ sampling -- CRP-vMF (new with analytic marginalization)\"<<endl;\n\n  double a0 = 1.0;\n  double b0 = 0.1;\n  VectorXd m0(3);\n  m0 << 1.0,0.0,0.0;\n\n  boost::mt19937 rndGen(9191);\n\n  vMFprior<double> vMFprior(m0,a0,b0,&rndGen);\n  shared_ptr<vMFbase3D<double> > vMFsampled( new vMFbase3D<double>(vMFprior));\n  \n  double alpha = 1.0;\n  CrpMM<double> dirvMF_sp(alpha,vMFsampled,1,&rndGen);\n  \n  uint32_t N=100;\n  uint32_t K=2;\n  MatrixXd x(3,N);\n  MatrixXd mus = sampleClustersOnSphere<double>(x, K);\n\n  dirvMF_sp.initialize(x);\n\n  cout<<\"true means: \"<<endl<<mus<<endl;\n  cout<<dirvMF_sp.labels().transpose()<<endl;\n  for(uint32_t t=0; t<100; ++t)\n  {\n    dirvMF_sp.sampleParameters();\n//    for(uint32_t k=0; k<dirvMF_sp.getK(); ++k)\n//    {\n//      cout<<\"  k: \"<<k<<\" \"<<endl; \n//      dirvMF_sp.getTheta(k)->print();\n//    }\n    dirvMF_sp.sampleLabels();\n    cout<<\"@t=\"<<t<<\" \"<<dirvMF_sp.labels().transpose()\n      <<\" logJoint=\"<<dirvMF_sp.logJoint()<<endl;\n  }\n//  MatrixXd logLikes;\n//  MatrixXu inds = dirvMF_sp.mostLikelyInds(5,logLikes);\n//  cout<<\"most likely indices\"<<endl;\n//  cout<<inds<<endl;\n  cout<<\"----------------------------------------\"<<endl;\n};\n\n", "meta": {"hexsha": "2a6c75b775f98c6817d5e42bd8dbb1223d027141", "size": 5485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/crpMM.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/crpMM.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/crpMM.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": 26.6262135922, "max_line_length": 79, "alphanum_fraction": 0.6156791249, "num_tokens": 1886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5481066441083027}}
{"text": "#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <array>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Shape_detection/Efficient_RANSAC.h>\n#include <CGAL/structure_point_set.h>\n#include <CGAL/Delaunay_triangulation_3.h>\n#include <CGAL/Triangulation_vertex_base_with_info_3.h>\n#include <CGAL/Advancing_front_surface_reconstruction.h>\n#include <CGAL/IO/read_points.h>\n#include <CGAL/disable_warnings.h>\n\n#include <boost/lexical_cast.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel  Kernel;\ntypedef Kernel::Point_3  Point;\ntypedef std::pair<Kernel::Point_3, Kernel::Vector_3>         Point_with_normal;\ntypedef std::vector<Point_with_normal>                       Pwn_vector;\ntypedef CGAL::First_of_pair_property_map<Point_with_normal>  Point_map;\ntypedef CGAL::Second_of_pair_property_map<Point_with_normal> Normal_map;\n\n// Efficient RANSAC types\ntypedef CGAL::Shape_detection::Efficient_RANSAC_traits\n  <Kernel, Pwn_vector, Point_map, Normal_map>              Traits;\ntypedef CGAL::Shape_detection::Efficient_RANSAC<Traits>    Efficient_ransac;\ntypedef CGAL::Shape_detection::Plane<Traits>               Plane;\n\n// Point set structuring type\ntypedef CGAL::Point_set_with_structure<Kernel>               Structure;\n\n// Advancing front types\ntypedef CGAL::Advancing_front_surface_reconstruction_vertex_base_3<Kernel> LVb;\ntypedef CGAL::Advancing_front_surface_reconstruction_cell_base_3<Kernel> LCb;\ntypedef CGAL::Triangulation_data_structure_3<LVb,LCb> Tds;\ntypedef CGAL::Delaunay_triangulation_3<Kernel,Tds> Triangulation_3;\ntypedef Triangulation_3::Vertex_handle Vertex_handle;\n\ntypedef std::array<std::size_t,3> Facet;\n\n\n// Functor to init the advancing front algorithm with indexed points\nstruct On_the_fly_pair{\n  const Pwn_vector& points;\n  typedef std::pair<Point, std::size_t> result_type;\n\n  On_the_fly_pair(const Pwn_vector& points) : points(points) {}\n\n  result_type\n  operator()(std::size_t i) const\n  {\n    return result_type(points[i].first,i);\n  }\n};\n\n// Specialized priority functor that favor structure coherence\ntemplate <typename Structure>\nstruct Priority_with_structure_coherence {\n\n  Structure& structure;\n  double bound;\n\n  Priority_with_structure_coherence(Structure& structure,\n                                    double bound)\n    : structure (structure), bound (bound)\n  {}\n\n  template <typename AdvancingFront, typename Cell_handle>\n  double operator() (AdvancingFront& adv, Cell_handle& c,\n                     const int& index) const\n  {\n    // If perimeter > bound, return infinity so that facet is not used\n    if (bound != 0)\n      {\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\n    Facet f = {{ c->vertex ((index + 1) % 4)->info (),\n                 c->vertex ((index + 2) % 4)->info (),\n                 c->vertex ((index + 3) % 4)->info () }};\n\n    // facet_coherence takes values between -1 and 3, 3 being the most\n    // coherent and -1 being incoherent. Smaller weight means higher\n    // priority.\n    double weight = 100. * (5 - structure.facet_coherence (f));\n\n    return weight * adv.smallest_radius_delaunay_sphere (c, index);\n  }\n\n};\n\n// Advancing front type\ntypedef CGAL::Advancing_front_surface_reconstruction\n         <Triangulation_3,\n          Priority_with_structure_coherence<Structure> >\n        Reconstruction;\n\n\nint main (int argc, char* argv[])\n{\n  // Points with normals.\n  Pwn_vector points;\n\n  const char* fname = (argc>1) ? argv[1] : \"data/cube.pwn\";\n  // Loading point set from a file.\n\n  if (!CGAL::read_points(fname, std::back_inserter(points),\n                         CGAL::parameters::point_map(Point_map()).\n                                           normal_map(Normal_map())))\n  {\n      std::cerr << \"Error: cannot read file\" << std::endl;\n      return EXIT_FAILURE;\n  }\n\n  std::cerr << \"Shape detection... \";\n\n  Efficient_ransac ransac;\n  ransac.set_input(points);\n  ransac.add_shape_factory<Plane>(); // Only planes are useful for stucturing\n\n  // Default RANSAC parameters\n  Efficient_ransac::Parameters op;\n  op.probability = 0.05;\n  op.min_points = 100;\n  op.epsilon = (argc>2 ? boost::lexical_cast<double>(argv[2]) : 0.002);\n  op.cluster_epsilon = (argc>3 ? boost::lexical_cast<double>(argv[3]) : 0.02);\n  op.normal_threshold = 0.7;\n\n  ransac.detect(op); // Plane detection\n\n  Efficient_ransac::Plane_range planes = ransac.planes();\n\n  std::cerr << \"done\\nPoint set structuring... \";\n\n  Pwn_vector structured_pts;\n  Structure pss (points,\n                 planes,\n                 op.cluster_epsilon,  // Same parameter as RANSAC\n                 CGAL::parameters::point_map (Point_map()).\n                 normal_map (Normal_map()).\n                 plane_map (CGAL::Shape_detection::Plane_map<Traits>()).\n                 plane_index_map(CGAL::Shape_detection::Point_to_shape_index_map<Traits>(points, planes)));\n\n\n  for (std::size_t i = 0; i < pss.size(); ++ i)\n    structured_pts.push_back (pss[i]);\n\n  std::cerr << \"done\\nAdvancing front... \";\n\n  std::vector<std::size_t> point_indices(boost::counting_iterator<std::size_t>(0),\n                                         boost::counting_iterator<std::size_t>(structured_pts.size()));\n\n  Triangulation_3 dt (boost::make_transform_iterator(point_indices.begin(), On_the_fly_pair(structured_pts)),\n                      boost::make_transform_iterator(point_indices.end(), On_the_fly_pair(structured_pts)));\n\n\n  Priority_with_structure_coherence<Structure> priority (pss,\n                                                         1000. * op.cluster_epsilon); // Avoid too large facets\n  Reconstruction R(dt, priority);\n  R.run ();\n\n  std::cerr << \"done\\nWriting result... \";\n\n  std::vector<Facet> output;\n  const Reconstruction::TDS_2& tds = R.triangulation_data_structure_2();\n\n  for(Reconstruction::TDS_2::Face_iterator fit = tds.faces_begin(); fit != tds.faces_end(); ++fit)\n    if(fit->is_on_surface())\n      output.push_back (CGAL::make_array(fit->vertex(0)->vertex_3()->id(),\n                                         fit->vertex(1)->vertex_3()->id(),\n                                         fit->vertex(2)->vertex_3()->id()));\n\n  std::ofstream f (\"out.off\");\n  f << \"OFF\\n\" << structured_pts.size () << \" \" << output.size() << \" 0\\n\"; // Header\n  for (std::size_t i = 0; i < structured_pts.size (); ++ i)\n    f << structured_pts[i].first << std::endl;\n  for (std::size_t i = 0; i < output.size (); ++ i)\n    f << \"3 \"\n      << output[i][0] << \" \"\n      << output[i][1] << \" \"\n      << output[i][2] << std::endl;\n  std::cerr << \"all done\\n\" << std::endl;\n\n  f.close();\n\n  return 0;\n}\n", "meta": {"hexsha": "c0aedf6974b95f727851cd07ad889eb78d027a5a", "size": 7110, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Advancing_front_surface_reconstruction/examples/Advancing_front_surface_reconstruction/reconstruction_structured.cpp", "max_stars_repo_name": "yemaedahrav/cgal", "max_stars_repo_head_hexsha": "ef771049b173007f2c566375bbd85a691adcee17", "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": "Advancing_front_surface_reconstruction/examples/Advancing_front_surface_reconstruction/reconstruction_structured.cpp", "max_issues_repo_name": "yemaedahrav/cgal", "max_issues_repo_head_hexsha": "ef771049b173007f2c566375bbd85a691adcee17", "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": "Advancing_front_surface_reconstruction/examples/Advancing_front_surface_reconstruction/reconstruction_structured.cpp", "max_forks_repo_name": "szobov/cgal", "max_forks_repo_head_hexsha": "e7b91b92b8c6949e3b62023bdd1e9f3ad8472626", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-05T04:18:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:18:59.000Z", "avg_line_length": 35.9090909091, "max_line_length": 111, "alphanum_fraction": 0.6451476793, "num_tokens": 1798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5480639740337934}}
{"text": "/*\n * State.hpp\n *\n *  Created on: 30.10.2018\n *      Author: tomlucas\n */\n\n#ifndef ESTIMATORS_MODELS_STATE_HPP_\n#define ESTIMATORS_MODELS_STATE_HPP_\n#include \"../StateBoxes/StateBox.hpp\"\n#include <tuple>\n#include \"../../Plugins/sensor_plugin.hpp\"\n#include <boost/hana.hpp>\n#include <boost/hana/ext/std/tuple.hpp>\n#define INNER_TYPE 0\n#define OUTER_TYPE 1\n\n/**\n * The State Type Reader reads the sizes of the state boxes and tells the state how big the matrices have to be\n */\ntemplate<int inner, int outer, int input, typename ... ARGS>\nclass StateTypeReader {\npublic:\n\tstatic const int inner_, outer_;\n};\n\ntemplate<int inner, int outer, int input, typename first, typename ... ARGS>\nclass StateTypeReader<inner, outer, input, first, ARGS...> : public StateTypeReader<inner + first::inner_size,\n\t\touter + first::outer_size, input + first::input_size, ARGS ...> {\n\n};\n\ntemplate<int inner, int outer, int input>\nclass StateTypeReader<inner, outer, input> {\npublic:\n\tstatic const int inner_size = inner;\n\tstatic const int outer_size = outer;\n\tstatic const int input_size = input;\n\ttemplate<typename T>\n\tusing OUTER_T=Eigen::Matrix<T,outer,1>;\n\ttemplate<typename T>\n\tusing INNER_T=Eigen::Matrix<T,inner,1>;\n\ttemplate<typename T>\n\tusing INPUT_T=Eigen::Matrix<T,input,1>;\n};\n\nnamespace zavi\n::estimator::model {\n\t/**\n\t * default implementation for boxminus\n\t * @param a\n\t * @param b\n\t * @return b boxminus a\n\t */\n\ttemplate< int measure_dim>\n\tstruct base_measurement {\n\t\tstatic constexpr inline int output_size=measure_dim;\n\t\ttemplate<typename T,typename T2>\n\t\tstatic auto boxminus(const Eigen::Matrix<T,measure_dim,1> & a, const Eigen::Matrix<T2,measure_dim,1> & b) {\n\t\t\treturn b-a;\n\t\t}\n\t};\n\n\t/**\n\t * The state is constructed from so called state boxes\n\t * The state boxes implement a dynamic model, have inputs values, a boxplus and a boxminus operation\n\t * This class just collects the state boxes from the STATE_BOXES tuple and passes eigen matrices to the functions of the boxes\n\t * For Estimators, it provides a simple interface with  an eigen vector containing all states and functions to edit it\n\t */\n\ttemplate<typename ... STATE_BOXES>\n\tclass State {\n\tpublic:\n\t\t// Reads the sizes and creates all types\n\t\ttypedef StateTypeReader<0,0,0,STATE_BOXES ...> STATE_TYPE;\n\n\t\ttypedef typename STATE_TYPE::template OUTER_T<double> OUTER_DOUBLE;\n\t\tstatic const int inner_size=STATE_TYPE::inner_size;\n\t\tstatic const int outer_size=STATE_TYPE::outer_size;\n\t\tstatic const int input_size=STATE_TYPE::input_size;\n\t\tstatic const int cost_size=inner_size-input_size;\n\t\t//static const int cost_size=outer_size-input_size;\n\t\ttemplate<typename T>\n\t\tusing OUTER_T=typename STATE_TYPE::template OUTER_T<T>;\n\t\ttemplate<typename T>\n\t\tusing INNER_T=typename STATE_TYPE::template INNER_T<T>;\n\t\ttemplate<typename T>\n\t\tusing INPUT_T=typename STATE_TYPE::template INPUT_T<T>;\n\t\ttemplate<typename T>\n\t\tusing COST_T=Eigen::Matrix<T,cost_size,1>;;\n\t\ttypedef std::tuple<STATE_BOXES ...> BOXES_TUPLE;\n\t\tBOXES_TUPLE boxes;\n\t\tState(std::shared_ptr<plugin::SensorPlugin> sensor):boxes(initStates<0,STATE_BOXES ...>(sensor)) {\n\n\t\t}\n\t\tvirtual ~State() {}\n\t\t/**\n\t\t *\n\t\t * @return The outer size of the state\n\t\t */\n\t\tvirtual int GlobalSize() const {\n\t\t\treturn outer_size;\n\t\t}\n\n\t\t/**\n\t\t *\n\t\t * @return The inner size of the state\n\t\t */\n\t\tvirtual int LocalSize() const {\n\t\t\treturn inner_size;\n\t\t}\n\n\t\t/**\n\t\t * passes box_plus to ceres\n\t\t * @param x\n\t\t * @param delta\n\t\t * @param x_plus_delta\n\t\t * @return\n\t\t */\n\t\ttemplate<typename T>\n\t\tbool Plus(const T * x, const T* delta, T* x_plus_delta) const {\n\t\t\t(Eigen::Map<OUTER_T<T> >(x_plus_delta))=boxPlus<T>(Eigen::Map<const OUTER_T<T> >(x),Eigen::Map<const INNER_T<T> >(delta));\n\t\t\treturn true;\n\t\t}\n\n\t\t/**\n\t\t * Passes box_plus to ceres\n\t\t * @param x\n\t\t * @param delta\n\t\t * @param x_plus_delta\n\t\t * @return\n\t\t */\n\t\ttemplate<typename T>\n\t\tbool operator()(const T* x, const T* delta, T* x_plus_delta) const {\n\t\t\treturn Plus<T>(x,delta,x_plus_delta);\n\n\t\t}\n\n\t\t/**\n\t\t * Pass the sensor to all state boxes\n\t\t * @param sensor the sensor plugin (IMU PLugin)\n\t\t * @return a tuple with all boxes\n\t\t */\n\t\ttemplate<int current_depth,typename T,typename ... rest>\n\t\tBOXES_TUPLE initStates(std::shared_ptr<plugin::SensorPlugin> sensor) {\n\t\t\tstd::get<current_depth>(boxes)=T(sensor);\n\t\t\treturn initStates<current_depth+1,rest ...>(sensor);\n\t\t}\n\t\t/**\n\t\t * Just for the last recursion step, does nothing\n\t\t * @param sensor\n\t\t * @return\n\t\t */\n\t\ttemplate<int current_depth>\n\t\tBOXES_TUPLE initStates(std::shared_ptr<plugin::SensorPlugin> sensor) {\n\t\t\treturn boxes;\n\t\t}\n\n\t\t/**\n\t\t * Splits the state  and inner vector and passes them to all state boxes\n\t\t * @param state\n\t\t * @param delta\n\t\t * @return state boxplis delta\n\t\t */\n\t\ttemplate<typename T>\n\t\tOUTER_T<T> boxPlus(const OUTER_T<T> & state,const INNER_T<T> & delta) const {\n\t\t\tOUTER_T<T> result=OUTER_T<T>::Zero();\n\t\t\tint outer_index=0,inner_index=0;\n\t\t\tboost::hana::for_each(boxes,[&result,&state,&delta,&outer_index, &inner_index](auto const & foo) {\n\t\t\t\t\t\tresult.template block<foo.outer_size,1>(outer_index,0)=foo.template boxPlus<T>(state.template block<foo.outer_size,1>(outer_index,0),delta.template block<foo.inner_size,1>(inner_index,0));\n\t\t\t\t\t\touter_index+=foo.outer_size;\n\t\t\t\t\t\tinner_index+=foo.inner_size;\n\t\t\t\t\t});\n\t\t\treturn result;\n\t\t}\n\t\t/**\n\t\t * as boxPlus, but for the inner state\n\t\t * It is needed if the inner space itself is a manifold  (orientations)\n\t\t * @param delta1\n\t\t * @param delta2\n\t\t * @return\n\t\t */\n\t\ttemplate<typename T>\n\t\tINNER_T<T> boxPlusInnerSpace(const INNER_T<T> & delta1,const INNER_T<T> & delta2) const {\n\t\t\tINNER_T<T> result=INNER_T<T>::Zero();\n\t\t\tint inner_index=0;\n\t\t\tboost::hana::for_each(boxes,[&result,&delta1,&delta2, &inner_index](auto const & foo) {\n\t\t\t\t\t\tresult.template block<foo.inner_size,1>(inner_index,0)=foo.template boxPlusInnerSpace<T>(delta1.template block<foo.inner_size,1>(inner_index,0),delta2.template block<foo.inner_size,1>(inner_index,0));\n\t\t\t\t\t\tinner_index+=foo.inner_size;\n\t\t\t\t\t});\n\t\t\treturn result;\n\t\t}\n\t\t/**\n\t\t * As boxPlus but with boxMinus\n\t\t * @param a\n\t\t * @param b\n\t\t * @return\n\t\t */\n\t\ttemplate<typename T>\n\t\tINNER_T<T> boxMinus(const OUTER_T<T> & a,const OUTER_T<T> & b) {\n\t\t\tINNER_T<T> result=INNER_T<T>::Zero();\n\t\t\tint outer_index=0,inner_index=0;\n\t\t\tboost::hana::for_each(boxes,[&result,&a,&b,&outer_index, &inner_index](auto & foo) {\n\t\t\t\t\t\tresult.template block<foo.inner_size,1>(inner_index,0)=foo.template boxMinus<T>(a.template block<foo.outer_size,1>(outer_index,0),b.template block<foo.outer_size,1>(outer_index,0));\n\t\t\t\t\t\touter_index+=foo.outer_size;\n\t\t\t\t\t\tinner_index+=foo.inner_size;\n\t\t\t\t\t});\n\t\t\treturn result;\n\t\t}\n\n\t\t/**\n\t\t * Calls the state transition function on all boxes\n\t\t * @param state the current state\n\t\t * @param time_diff the passed time till last call\n\t\t * @return the new state\n\t\t */\n\t\ttemplate<typename T>\n\t\tOUTER_T<T> stateTransitionFunction(const OUTER_T<T> & state,const double time_diff) {\n\t\t\tOUTER_T<T> result=OUTER_T<T>::Zero();\n\t\t\tint outer_index=0;\n\t\t\tboost::hana::for_each(boxes,[&result,&state,time_diff,&outer_index](auto & foo) {\n\t\t\t\t\t\tresult.template block<foo.outer_size,1>(outer_index,0)=foo.template stateTransition<T>(state.template block<foo.outer_size,1>(outer_index,0),time_diff);\n\t\t\t\t\t\touter_index+=foo.outer_size;\n\t\t\t\t\t});\n\t\t\treturn result;\n\t\t}\n\t\t/*template<typename T>\n\t\t static INPUT_T<T> input_measurement(const OUTER_T<T> & state,void * prior) {\n\t\t BOXES_TUPLE *box=static_cast<BOXES_TUPLE*>(*prior);\n\t\t INPUT_T<T> result;\n\t\t int outer_index=0,input_index=0;\n\t\t boost::hana::for_each(*box,[&result,&state,&outer_index,&input_index](auto & foo) {\n\t\t outer_index+=foo.outer_size;\n\t\t result.template block<foo.input_size,1>(input_index,0)=state.template block<foo.input_size,1>(outer_index-foo.input_size,0);\n\t\t input_index+=foo.input_size;\n\t\t });\n\t\t return result;\n\t\t }*/\n\n\t\t/**\n\t\t * Calculates the transition cost between to states scaled by stiffness\n\t\t * @param state the current state\n\t\t * @param time_diff the \u00fcassed time between 2 states\n\t\t * @param after the next state\n\t\t * @return stiffness*(after boxminus transition(state))\n\t\t */\n\t\ttemplate<typename T>\n\t\tCOST_T<T> transitionCost(const OUTER_T<T> & state,const double time_diff, const OUTER_T<T> & after) {\n\t\t\tEigen::Matrix<double,cost_size,cost_size> stiffnes=(getTransitionSTD(time_diff)+COST_T<double>::Ones()*1e-6).cwiseInverse().asDiagonal();\n\t\t\t//zavi::plot::liveHeatMap<0>(stiffnes,\" stiffnes of transition\");\n\t\t\tCOST_T<T> result=COST_T<T>::Zero();\n\t\t\tint outer_index=0,cost_index=0;\n\t\t\tboost::hana::for_each(boxes,[&result,&state,time_diff,&after,&outer_index,&cost_index](auto & foo) {\n\t\t\t\t\t\tresult.template block<foo.inner_size-foo.input_size,1>(cost_index,0)=foo.template boxMinus<T>(foo.template stateTransition<T>(state.template block<foo.outer_size,1>(outer_index,0),time_diff),after.template block<foo.outer_size,1>(outer_index,0)).template block<foo.inner_size-foo.input_size,1>(0,0);\n\t\t\t\t\t\t//result.template block<foo.outer_size-foo.input_size,1>(cost_index,0)=(after.template block<foo.outer_size,1>(outer_index,0)-foo.template stateTransition<T>(state.template block<foo.outer_size,1>(outer_index,0),time_diff)).template block<foo.outer_size-foo.input_size,1>(0,0);\n\t\t\t\t\t\tcost_index+=foo.inner_size-foo.input_size;\n\t\t\t\t\t\t//cost_index+=foo.inner_size-foo.input_size;\n\t\t\t\t\t\touter_index+=foo.outer_size;\n\t\t\t\t\t});\n\t\t\tassert_inputs(stiffnes,result);\n\t\t\treturn stiffnes*result;\n\t\t\t//return result;\n\t\t}\n\t\t/**\n\t\t * Get the transition standard deviation (without inputs)\n\t\t * @param time_diff of the transition\n\t\t * @return a cost_T vector containing the stds\n\t\t */\n\t\tCOST_T<double> getTransitionSTD(const double time_diff) {\n\t\t\tCOST_T<double> result=COST_T<double>::Zero();\n\t\t\tint outer_index=0,cost_index=0;\n\t\t\tboost::hana::for_each(boxes,[&result,time_diff,&outer_index,&cost_index](auto & foo) {\n\t\t\t\t\t\tresult.template block<foo.inner_size-foo.input_size,1>(cost_index,0)=foo.getSTD(time_diff).template block<foo.inner_size-foo.input_size,1>(0,0);\n\t\t\t\t\t\tcost_index+=foo.inner_size-foo.input_size;\n\t\t\t\t\t\touter_index+=foo.outer_size;\n\t\t\t\t\t});\n\t\t\treturn result;\n\t\t}\n\t\t/**\n\t\t * Get the standard deviation  (with inputs)\n\t\t * @param time_diff of the transition\n\t\t * @return a cost_T vector containing the stds\n\t\t */\n\t\tINNER_T<double> getStateSTD(const double time_diff) {\n\t\t\tINNER_T<double> result=INNER_T<double>::Zero();\n\t\t\tint inner_index=0;\n\t\t\tboost::hana::for_each(boxes,[&result,time_diff,&inner_index](auto & foo) {\n\t\t\t\t\t\tresult.template block<foo.inner_size,1>(inner_index,0)=(foo.getSTD(time_diff));\n\t\t\t\t\t\tinner_index+=foo.inner_size;\n\t\t\t\t\t});\n\t\t\treturn result;\n\t\t}\n\n\t\t/**\n\t\t * Call normalise function of all state boxes\n\t\t * generally needed for orientation boxes to prevent numeric failures\n\t\t * @param state the current state\n\t\t * @return a normalised version of the state\n\t\t */\n\t\tOUTER_T<double> normalise(const OUTER_T<double> & state) const {\n\t\t\tOUTER_T<double> result=result.Zero();\n\t\t\tint outer_index=0;\n\t\t\tboost::hana::for_each(boxes,[&result,&state,&outer_index](auto const & foo) {\n\t\t\t\t\t\tresult.template block<foo.outer_size,1>(outer_index,0)=foo.normalise(state.template block<foo.outer_size,1>(outer_index,0));\n\t\t\t\t\t\touter_index+=foo.outer_size;\n\t\t\t\t\t});\n\t\t\treturn result;\n\t\t}\n\n\t};\n}\n\n#endif /* ESTIMATORS_MODELS_STATE_HPP_ */\n", "meta": {"hexsha": "d993761bfcbc01f21a5746f15c4ec9b5d16b7680", "size": 11281, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SixdaysCode/Estimators/Models/State.hpp", "max_stars_repo_name": "TomLKoller/ZaVI_TrackCycling", "max_stars_repo_head_hexsha": "7c23bc34e6e58c78ec249f6f55d4e70c7e91d315", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-15T07:20:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T07:20:08.000Z", "max_issues_repo_path": "SixdaysCode/Estimators/Models/State.hpp", "max_issues_repo_name": "TomLKoller/ZaVI_TrackCycling", "max_issues_repo_head_hexsha": "7c23bc34e6e58c78ec249f6f55d4e70c7e91d315", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SixdaysCode/Estimators/Models/State.hpp", "max_forks_repo_name": "TomLKoller/ZaVI_TrackCycling", "max_forks_repo_head_hexsha": "7c23bc34e6e58c78ec249f6f55d4e70c7e91d315", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-15T07:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T07:20:19.000Z", "avg_line_length": 36.0415335463, "max_line_length": 305, "alphanum_fraction": 0.7081818988, "num_tokens": 3104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5480418230906784}}
{"text": "//\n// Created by Hamza El-Kebir on 6/18/21.\n//\n\n#ifndef LODESTAR_BACKWARDDIFFERENCE_HPP\n#define LODESTAR_BACKWARDDIFFERENCE_HPP\n\n#include <Eigen/Dense>\n\nnamespace ls {\n    namespace primitives {\n        template<typename TType, size_t TSamples, size_t TOrder, typename TScalarType = double>\n        class BackwardDifference {\n            static_assert(TSamples > 1, \"Number of samples must be greater than one.\");\n\n            static_assert(TOrder > 1, \"Differentiation order must be greater than one.\");\n\n            static_assert(TSamples > TOrder, \"Number of samples must be greater than order.\");\n\n            static_assert(\n                    // First order\n                    (TSamples == 2 && TOrder == 1) ||\n                    (TSamples == 3 && TOrder == 1) ||\n                    (TSamples == 4 && TOrder == 1) ||\n                    (TSamples == 5 && TOrder == 1) ||\n                    (TSamples == 6 && TOrder == 1) ||\n                    (TSamples == 7 && TOrder == 1) ||\n                    // Second order\n                    (TSamples == 3 && TOrder == 2) ||\n                    (TSamples == 4 && TOrder == 2) ||\n                    (TSamples == 5 && TOrder == 2) ||\n                    (TSamples == 6 && TOrder == 2) ||\n                    (TSamples == 7 && TOrder == 2) ||\n                    // Third order\n                    (TSamples == 4 && TOrder == 3) ||\n                    (TSamples == 5 && TOrder == 3) ||\n                    (TSamples == 6 && TOrder == 3) ||\n                    (TSamples == 7 && TOrder == 3), \"Combination of samples and order is not supported.\");\n        };\n\n// ------- First derivative ---------\n\n        /**\n         * @brief Computes the first-order backward finite difference difference given two samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 2, 1, TScalarType> {\n        protected:\n            static TType compute(const TType &xNeg1, const TType &x0)\n            {\n                return x0 - xNeg1;\n            }\n\n        public:\n            static TType compute(const TType &xNeg1, const TType &x0, TScalarType h)\n            {\n                return compute(xNeg1, x0) / h;\n            }\n\n            static const int kOrder = 1;\n            static const int kErrorOrder = 1;\n        };\n\n        /**\n         * @brief Computes the first-order backward finite difference difference given three samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 3, 1, TScalarType> {\n        protected:\n            static TType compute(const TType &xNeg2, const TType &xNeg1, const TType &x0)\n            {\n                return (3.0 / 2.0) * x0 - 2.0 * xNeg1 + (1.0 / 2.0) * xNeg2;\n            }\n\n        public:\n            static TType compute(const TType &xNeg2, const TType &xNeg1, const TType &x0, TScalarType h)\n            {\n                return compute(xNeg2, xNeg1, x0) / h;\n            }\n\n            static const int kOrder = 1;\n            static const int kErrorOrder = 2;\n        };\n\n        /**\n         * @brief Computes the first-order backward finite difference difference given four samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 4, 1, TScalarType> {\n        protected:\n            static TType compute(const TType &xNeg3, const TType &xNeg2, const TType &xNeg1, const TType &x0)\n            {\n                return (11.0 / 6.0) * x0 - 3.0 * xNeg1 + (3.0 / 2.0) * xNeg2 - (1.0 / 3.0) * xNeg3;\n            }\n\n        public:\n            static TType\n            compute(const TType &xNeg3, const TType &xNeg2, const TType &xNeg1, const TType &x0, TScalarType h)\n            {\n                return compute(xNeg3, xNeg2, xNeg1, x0) / h;\n            }\n\n            static const int kOrder = 1;\n            static const int kErrorOrder = 3;\n        };\n\n        /**\n         * @brief Computes the first-order backward finite difference difference given five samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 5, 1, TScalarType> {\n        protected:\n            static TType\n            compute(const TType &xNeg4, const TType &xNeg3, const TType &xNeg2, const TType &xNeg1, const TType &x0)\n            {\n                return (25.0 / 12.0) * x0 - 4.0 * xNeg1 + 3.0 * xNeg2 - (4.0 / 3.0) * xNeg3 + (1.0 / 4.0) * xNeg4;\n            }\n\n        public:\n            static TType\n            compute(const TType &xNeg4, const TType &xNeg3, const TType &xNeg2, const TType &xNeg1, const TType &x0,\n                    TScalarType h)\n            {\n                return compute(xNeg4, xNeg3, xNeg2, xNeg1, x0) / h;\n            }\n\n            static const int kOrder = 1;\n            static const int kErrorOrder = 4;\n        };\n\n        /**\n         * @brief Computes the first-order backward finite difference difference given six samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 6, 1, TScalarType> {\n        protected:\n            static TType\n            compute(const TType &xNeg5, const TType &xNeg4, const TType &xNeg3, const TType &xNeg2, const TType &xNeg1,\n                    const TType &x0)\n            {\n                return (137.0 / 60.0) * x0 - 5.0 * xNeg1 + 5.0 * xNeg2 - (10.0 / 3.0) * xNeg3 + (5.0 / 4.0) * xNeg4 -\n                       (1.0 / 6.0) * xNeg5;\n            }\n\n        public:\n            static TType\n            compute(const TType &xNeg5, const TType &xNeg4, const TType &xNeg3, const TType &xNeg2, const TType &xNeg1,\n                    const TType &x0, TScalarType h)\n            {\n                return compute(xNeg5, xNeg4, xNeg3, xNeg2, xNeg1, x0) / h;\n            }\n\n            static const int kOrder = 1;\n            static const int kErrorOrder = 5;\n        };\n\n        /**\n         * @brief Computes the first-order backward finite difference difference given seven samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 7, 1, TScalarType> {\n        protected:\n            static TType\n            compute(const TType &xNeg6, const TType &xNeg5, const TType &xNeg4, const TType &xNeg3, const TType &xNeg2,\n                    const TType &xNeg1, const TType &x0)\n            {\n                return (49.0 / 20.0) * x0 - 6.0 * xNeg1 + (15.0 / 2.0) * xNeg2 - (20.0 / 3.0) * xNeg3 +\n                       (15.0 / 4.0) * xNeg4 - (6.0 / 5.0) * xNeg5 + (1.0 / 6.0) * xNeg6;\n            }\n\n        public:\n            static TType\n            compute(const TType &xNeg6, const TType &xNeg5, const TType &xNeg4, const TType &xNeg3, const TType &xNeg2,\n                    const TType &xNeg1, const TType &x0, TScalarType h)\n            {\n                return compute(xNeg6, xNeg5, xNeg4, xNeg3, xNeg2, xNeg1, x0) / h;\n            }\n\n            static const int kOrder = 1;\n            static const int kErrorOrder = 6;\n        };\n\n// ------- Second derivative ---------\n\n        /**\n         * @brief Computes the second-order backward finite difference difference given three samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 3, 2, TScalarType> {\n        protected:\n            static TType compute(const TType &xNeg2, const TType &xNeg1, const TType &x0)\n            {\n                return x0 - 2 * xNeg1 + xNeg2;\n            }\n\n        public:\n            static TType compute(const TType &xNeg2, const TType &xNeg1, const TType &x0, TScalarType h)\n            {\n                return compute(xNeg2, xNeg1, x0) / (h * h);\n            }\n\n            static const int kOrder = 2;\n            static const int kErrorOrder = 1;\n        };\n\n        /**\n         * @brief Computes the second-order backward finite difference difference given four samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 4, 2, TScalarType> {\n        protected:\n            static TType compute(const TType &xNeg3, const TType &xNeg2, const TType &xNeg1, const TType &x0)\n            {\n                return 2 * x0 - 5 * xNeg1 + 4 * xNeg2 - 1 * xNeg3;\n            }\n\n        public:\n            static TType\n            compute(const TType &xNeg3, const TType &xNeg2, const TType &xNeg1, const TType &x0, TScalarType h)\n            {\n                return compute(xNeg3, xNeg2, xNeg1, x0) / (h * h);\n            }\n\n            static const int kOrder = 2;\n            static const int kErrorOrder = 2;\n        };\n\n        /**\n         * @brief Computes the second-order backward finite difference difference given five samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 5, 2, TScalarType> {\n        protected:\n            static TType\n            compute(const TType &xNeg4, const TType &xNeg3, const TType &xNeg2, const TType &xNeg1, const TType &x0)\n            {\n                return (35.0 / 12.0) * x0 - (26.0 / 3.0) * xNeg1 + (19.0 / 2.0) * xNeg2 - (14.0 / 3.0) * xNeg3 +\n                       (11.0 / 12.0) * xNeg4;\n            }\n\n        public:\n            static TType\n            compute(const TType &xNeg4, const TType &xNeg3, const TType &xNeg2, const TType &xNeg1, const TType &x0,\n                    TScalarType h)\n            {\n                return compute(xNeg4, xNeg3, xNeg2, xNeg1, x0) / (h * h);\n            }\n\n            static const int kOrder = 2;\n            static const int kErrorOrder = 3;\n        };\n\n        /**\n         * @brief Computes the second-order backward finite difference difference given six samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 6, 2, TScalarType> {\n        protected:\n            static TType\n            compute(const TType &xNeg5, const TType &xNeg4, const TType &xNeg3, const TType &xNeg2, const TType &xNeg1,\n                    const TType &x0)\n            {\n                return (15.0 / 4.0) * x0 - (77.0 / 6.0) * xNeg1 + (107.0 / 6.0) * xNeg2 - 13.0 * xNeg3 +\n                       (61.0 / 12.0) * xNeg4 - (5.0 / 6.0) * xNeg5;\n            }\n\n        public:\n            static TType\n            compute(const TType &xNeg5, const TType &xNeg4, const TType &xNeg3, const TType &xNeg2, const TType &xNeg1,\n                    const TType &x0, TScalarType h)\n            {\n                return compute(xNeg5, xNeg4, xNeg3, xNeg2, xNeg1, x0) / (h * h);\n            }\n\n            static const int kOrder = 2;\n            static const int kErrorOrder = 4;\n        };\n\n        /**\n         * @brief Computes the second-order backward finite difference difference given seven samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 7, 2, TScalarType> {\n        protected:\n            static TType\n            compute(const TType &xNeg6, const TType &xNeg5, const TType &xNeg4, const TType &xNeg3, const TType &xNeg2,\n                    const TType &xNeg1, const TType &x0)\n            {\n                return (203.0 / 45.0) * x0 - (87.0 / 5.0) * xNeg1 + (117.0 / 4.0) * xNeg2 - (254.0 / 9.0) * xNeg3 +\n                       (33.0 / 2.0) * xNeg4 - (27.0 / 5.0) * xNeg5 + (137.0 / 180.0) * xNeg6;\n            }\n\n        public:\n            static TType\n            compute(const TType &xNeg6, const TType &xNeg5, const TType &xNeg4, const TType &xNeg3, const TType &xNeg2,\n                    const TType &xNeg1, const TType &x0, TScalarType h)\n            {\n                return compute(xNeg6, xNeg5, xNeg4, xNeg3, xNeg2, xNeg1, x0) / (h * h);\n            }\n\n            static const int kOrder = 2;\n            static const int kErrorOrder = 5;\n        };\n\n// ------- Third derivative ---------\n\n        /**\n         * @brief Computes the third-order backward finite difference difference given four samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 4, 3, TScalarType> {\n        protected:\n            static TType compute(const TType &xNeg3, const TType &xNeg2, const TType &xNeg1, const TType &x0)\n            {\n                return 1.0 * x0 - 3.0 * xNeg1 + 3.0 * xNeg2 - 1.0 * xNeg3;\n            }\n\n        public:\n            static TType\n            compute(const TType &xNeg3, const TType &xNeg2, const TType &xNeg1, const TType &x0, TScalarType h)\n            {\n                return compute(xNeg3, xNeg2, xNeg1, x0) / (h * h * h);\n            }\n\n            static const int kOrder = 3;\n            static const int kErrorOrder = 1;\n        };\n\n        /**\n         * @brief Computes the third-order backward finite difference difference given five samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 5, 3, TScalarType> {\n        protected:\n            static TType\n            compute(const TType &xNeg4, const TType &xNeg3, const TType &xNeg2, const TType &xNeg1, const TType &x0)\n            {\n                return (5.0 / 2.0) * x0 - 9.0 * xNeg1 + 12.0 * xNeg2 - 7.0 * xNeg3 + (3.0 / 2.0) * xNeg4;\n            }\n\n        public:\n            static TType\n            compute(const TType &xNeg4, const TType &xNeg3, const TType &xNeg2, const TType &xNeg1, const TType &x0,\n                    TScalarType h)\n            {\n                return compute(xNeg4, xNeg3, xNeg2, xNeg1, x0) / (h * h * h);\n            }\n\n            static const int kOrder = 3;\n            static const int kErrorOrder = 2;\n        };\n\n        /**\n         * @brief Computes the third-order backward finite difference difference given six samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 6, 3, TScalarType> {\n        protected:\n            static TType\n            compute(const TType &xNeg5, const TType &xNeg4, const TType &xNeg3, const TType &xNeg2, const TType &xNeg1,\n                    const TType &x0)\n            {\n                return (17.0 / 4.0) * x0 - (71.0 / 4.0) * xNeg1 + (59.0 / 2.0) * xNeg2 - (49.0 / 2.0) * xNeg3 +\n                       (41.0 / 4.0) * xNeg4 - (7.0 / 4.0) * xNeg5;\n            }\n\n        public:\n            static TType\n            compute(const TType &xNeg5, const TType &xNeg4, const TType &xNeg3, const TType &xNeg2, const TType &xNeg1,\n                    const TType &x0, TScalarType h)\n            {\n                return compute(xNeg5, xNeg4, xNeg3, xNeg2, xNeg1, x0) / (h * h * h);\n            }\n\n            static const int kOrder = 3;\n            static const int kErrorOrder = 3;\n        };\n\n        /**\n         * @brief Computes the third-order backward finite difference difference given seven samples.\n         *\n         * @tparam TType State type.\n         * @tparam TScalarType Spacing type.\n         */\n        template<typename TType, typename TScalarType>\n        class BackwardDifference<TType, 7, 3, TScalarType> {\n        protected:\n            static TType\n            compute(const TType &xNeg6, const TType &xNeg5, const TType &xNeg4, const TType &xNeg3, const TType &xNeg2,\n                    const TType &xNeg1, const TType &x0)\n            {\n                return (49.0 / 8.0) * x0 - 29.0 * xNeg1 + (461.0 / 8.0) * xNeg2 - 62.0 * xNeg3 + (307.0 / 8.0) * xNeg4 -\n                       13.0 * xNeg5 + (15.0 / 8.0) * xNeg6;\n            }\n\n        public:\n            static TType\n            compute(const TType &xNeg6, const TType &xNeg5, const TType &xNeg4, const TType &xNeg3, const TType &xNeg2,\n                    const TType &xNeg1, const TType &x0, TScalarType h)\n            {\n                return compute(xNeg6, xNeg5, xNeg4, xNeg3, xNeg2, xNeg1, x0) / (h * h * h);\n            }\n\n            static const int kOrder = 3;\n            static const int kErrorOrder = 4;\n        };\n\n    }\n}\n\n#endif //LODESTAR_BACKWARDDIFFERENCE_HPP\n", "meta": {"hexsha": "dfa253278b140ceee4b039bb775f21e180ab314c", "size": 17273, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lodestar/primitives/differentiators/BackwardDifference.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/primitives/differentiators/BackwardDifference.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/primitives/differentiators/BackwardDifference.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": 38.0462555066, "max_line_length": 120, "alphanum_fraction": 0.517628669, "num_tokens": 4846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224068675884, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5480418054804054}}
{"text": "#include <iostream>\n#include \"linop.h\"\n#include \"utils.h\"\n#include \"math.h\"\n#include <Eigen/Cholesky>\n\nusing namespace Rcpp;\nusing namespace RcppEigen;\n\nRcppExport SEXP gls(SEXP X, SEXP S, SEXP Y, SEXP maxit, SEXP tol)\n{\n  using namespace Rcpp;\n  using namespace RcppEigen;\n  try {\n    using Eigen::Map;\n    using Eigen::MatrixXd;\n    using Eigen::VectorXd;\n    using Rcpp::List;\n    \n    typedef Map<VectorXd> MapVecd;\n    typedef Map<Eigen::MatrixXd> MapMatd;\n    \n    const int maxiter(as<int>(maxit));\n    const double toler(as<double>(tol));\n    const Eigen::Map<MatrixXd> XX(as<MapMatd>(X));\n    const Eigen::Map<MatrixXd> SS(as<MapMatd>(S));\n    const Eigen::Map<VectorXd> YY(as<MapVecd>(Y));\n    \n    const int n(XX.rows());\n    const int p(XX.cols());\n    \n    MatrixXd SX(MatrixXd(n, p));\n    //MatrixXd XSX(MatrixXd(p, p));\n    \n    for (int i = 0; i < p; i++) {\n      SX.col(i) = conjugate_gradient(SS, XX.col(i), maxiter, toler);\n    }\n    \n    MatrixXd XSX((XX.adjoint()) * SX);\n    VectorXd XSY((SX.adjoint()) * YY);\n    \n    VectorXd beta = conjugate_gradient(XSX, XSY, maxiter, toler);\n    \n    \n    return List::create(Named(\"beta\") = beta);\n  } catch (std::exception &ex) {\n    forward_exception_to_r(ex);\n  } catch (...) {\n    ::Rf_error(\"C++ exception (unknown reason)\");\n  }\n  return R_NilValue; //-Wall\n}\n\nRcppExport SEXP gls_half_cg(SEXP X, SEXP S, SEXP Y, SEXP maxit, SEXP tol)\n{\n  using namespace Rcpp;\n  using namespace RcppEigen;\n  try {\n    using Eigen::Map;\n    using Eigen::MatrixXd;\n    using Eigen::VectorXd;\n    \n    using Rcpp::List;\n    \n    typedef Map<VectorXd> MapVecd;\n    typedef Map<Eigen::MatrixXd> MapMatd;\n    \n    const int maxiter(as<int>(maxit));\n    const double toler(as<double>(tol));\n    const Eigen::Map<MatrixXd> XX(as<MapMatd>(X));\n    const Eigen::Map<MatrixXd> SS(as<MapMatd>(S));\n    const Eigen::Map<VectorXd> YY(as<MapVecd>(Y));\n    \n    const int n(XX.rows());\n    const int p(XX.cols());\n    \n    MatrixXd SX(MatrixXd(n, p));\n    \n    SX = SS.llt().solve(XX);\n    \n    MatrixXd XSX((XX.adjoint()) * SX);\n    VectorXd XSY((SX.adjoint()) * YY);\n    \n    VectorXd beta = conjugate_gradient(XSX, XSY, maxiter, toler);\n    \n    \n    return List::create(Named(\"beta\") = beta);\n  } catch (std::exception &ex) {\n    forward_exception_to_r(ex);\n  } catch (...) {\n    ::Rf_error(\"C++ exception (unknown reason)\");\n  }\n  return R_NilValue; //-Wall\n}\n\n\nRcppExport SEXP gls_direct(SEXP X, SEXP S, SEXP Y, SEXP maxit, SEXP tol)\n{\n  using namespace Rcpp;\n  using namespace RcppEigen;\n  try {\n    using Eigen::Map;\n    using Eigen::MatrixXd;\n    using Eigen::VectorXd;\n    \n    using Rcpp::List;\n    \n    typedef Map<VectorXd> MapVecd;\n    typedef Map<Eigen::MatrixXd> MapMatd;\n    \n    const int maxiter(as<int>(maxit));\n    const double toler(as<double>(tol));\n    const Eigen::Map<MatrixXd> XX(as<MapMatd>(X));\n    const Eigen::Map<MatrixXd> SS(as<MapMatd>(S));\n    const Eigen::Map<VectorXd> YY(as<MapVecd>(Y));\n    \n    const int n(XX.rows());\n    const int p(XX.cols());\n    \n    MatrixXd SX(MatrixXd(n, p));\n    \n    SX = SS.llt().solve(XX);\n    \n    MatrixXd XSX((XX.adjoint()) * SX);\n    VectorXd XSY((SX.adjoint()) * YY);\n    \n    VectorXd beta = XSX.ldlt().solve(XSY);\n    \n    \n    return List::create(Named(\"beta\") = beta);\n  } catch (std::exception &ex) {\n    forward_exception_to_r(ex);\n  } catch (...) {\n    ::Rf_error(\"C++ exception (unknown reason)\");\n  }\n  return R_NilValue; //-Wall\n}\n\n", "meta": {"hexsha": "f46758aa37c062f77049302ee37871d4a00955d2", "size": 3452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gls.cpp", "max_stars_repo_name": "jaredhuling/rfunctions", "max_stars_repo_head_hexsha": "ee118166ce4b31b871e4c1d4e7fc35518098423a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2015-04-07T21:52:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T01:12:53.000Z", "max_issues_repo_path": "src/gls.cpp", "max_issues_repo_name": "jaredhuling/rfunctions", "max_issues_repo_head_hexsha": "ee118166ce4b31b871e4c1d4e7fc35518098423a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-02-24T20:48:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-06T05:08:23.000Z", "max_forks_repo_path": "src/gls.cpp", "max_forks_repo_name": "jaredhuling/rfunctions", "max_forks_repo_head_hexsha": "ee118166ce4b31b871e4c1d4e7fc35518098423a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-13T06:47:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T22:20:41.000Z", "avg_line_length": 24.8345323741, "max_line_length": 73, "alphanum_fraction": 0.6089223638, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6477982179521105, "lm_q1q2_score": 0.5480000134425911}}
{"text": "#define CATCH_CONFIG_MAIN\n\n#include \"CALPHADConcSolverBinaryThreePhase.h\"\n#include \"CALPHADFreeEnergyFunctionsBinary.h\"\n#include \"CALPHADFreeEnergyFunctionsBinaryThreePhase.h\"\n\n#include \"InterpolationType.h\"\n#include \"PhysicalConstants.h\"\n\n#include \"catch.hpp\"\n\n#include <boost/optional/optional.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n\n#include <fstream>\n#include <iostream>\n#include <string>\n\nnamespace pt = boost::property_tree;\n\nTEST_CASE(\"CALPHAD conc solver binary three phase KKS, two-phase consistancy\",\n    \"[conc solver binary three phase kks, two-phase consistancy]\")\n{\n    // Calculate the inputs and the reference solution\n    Thermo4PFM::EnergyInterpolationType energy_interp_func_type\n        = Thermo4PFM::EnergyInterpolationType::PBG;\n    Thermo4PFM::ConcInterpolationType conc_interp_func_type\n        = Thermo4PFM::ConcInterpolationType::PBG;\n\n    double temperature = 1450.;\n\n    std::cout << \" Read CALPHAD database...\" << std::endl;\n    pt::ptree calphad_db;\n    try\n    {\n        pt::read_json(\"../thermodynamic_data/calphadAuNi.json\", calphad_db);\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"exception caught: \" << e.what() << std::endl;\n    }\n\n    boost::optional<pt::ptree&> newton_db;\n\n    Thermo4PFM::CALPHADFreeEnergyFunctionsBinary cafe(\n        calphad_db, newton_db, energy_interp_func_type, conc_interp_func_type);\n\n    // Get the CALPHAD parameters\n    CalphadDataType fA[2];\n    CalphadDataType fB[2];\n    CalphadDataType Lmix_L[4];\n    CalphadDataType Lmix_A[4];\n\n    cafe.computeTdependentParameters(temperature, Lmix_L, Lmix_A, fA, fB);\n\n    // initial guesses\n    double c_init0 = 0.5;\n    double c_init1 = 0.5;\n\n    double sol_reference[2] = { c_init0, c_init1 };\n\n    // compute concentrations satisfying KKS equations\n    const double conc = 0.3;\n    const double phi  = 0.5;\n    cafe.computePhaseConcentrations(\n        temperature, &conc, &phi, &sol_reference[0]);\n\n    // Inputs to the solver\n    const double RTinv\n        = 1.0 / (Thermo4PFM::gas_constant_R_JpKpmol * temperature);\n\n    double hphi0 = interp_func(conc_interp_func_type, 1.0 - phi);\n    double hphi1 = interp_func(conc_interp_func_type, phi);\n    double hphi2 = 0.0;\n\n    CalphadDataType Lmix_S0[4];\n    CalphadDataType Lmix_S1[4];\n    for (int i = 0; i < 4; ++i)\n    {\n        Lmix_S0[i] = Lmix_A[i];\n        Lmix_S1[i] = Lmix_A[i];\n    }\n\n    const double tol    = 1.e-8;\n    const double alpha  = 0.5; // Using alpha=1 can lead to convergence issues\n    const int max_iters = 100;\n\n    // Create and set up the solver\n    CalphadDataType fA_threePhase[3];\n    CalphadDataType fB_threePhase[3];\n    fA_threePhase[0] = fA[0];\n    fA_threePhase[1] = fA[1];\n    fA_threePhase[2] = fA[1];\n    fB_threePhase[0] = fB[0];\n    fB_threePhase[1] = fB[1];\n    fB_threePhase[2] = fB[1];\n\n    Thermo4PFM::CALPHADConcSolverBinaryThreePhase solver;\n    solver.setup(conc, hphi0, hphi1, hphi2, RTinv, Lmix_L, Lmix_S0, Lmix_S1,\n        fA_threePhase, fB_threePhase);\n\n    // Run the solver\n    double sol_test[3] = { c_init0, c_init1, 1.0e-8 };\n    std::cout << \"First test...\" << std::endl;\n    int ret = solver.ComputeConcentration(sol_test, tol, max_iters, alpha);\n    std::cout << \"...completed\" << std::endl;\n    REQUIRE(ret >= 0);\n\n    // Plug the solution back into the RHS\n    double residual[3];\n    solver.RHS(sol_test, residual);\n\n    REQUIRE(std::abs(residual[0]) < 1.1 * tol);\n    REQUIRE(std::abs(residual[1]) < 1.1 * tol);\n    REQUIRE(std::abs(residual[2]) < 1.1 * tol);\n\n    // Make sure that it matches the binary case\n    REQUIRE(std::abs(sol_test[0] - sol_reference[0]) < 1.1 * tol);\n    REQUIRE(std::abs(sol_test[1] - sol_reference[1]) < 1.1 * tol);\n\n    // ----------\n    // Now do the same but for the second solid phase\n    hphi0 = interp_func(conc_interp_func_type, 1.0 - phi);\n    hphi1 = 0.0;\n    hphi2 = interp_func(conc_interp_func_type, phi);\n\n    Thermo4PFM::CALPHADConcSolverBinaryThreePhase solver2;\n    solver2.setup(conc, hphi0, hphi1, hphi2, RTinv, Lmix_L, Lmix_S0, Lmix_S1,\n        fA_threePhase, fB_threePhase);\n\n    // Run the solver\n    sol_test[0] = c_init0;\n    sol_test[1] = 1.0e-8;\n    sol_test[2] = c_init1;\n\n    residual[0] = 0.;\n    residual[1] = 0.;\n    residual[2] = 0.;\n\n    std::cout << \"Second test...\" << std::endl;\n    ret = solver2.ComputeConcentration(sol_test, tol, max_iters, alpha);\n    std::cout << \"...completed\" << std::endl;\n    REQUIRE(ret >= 0);\n\n    // Plug the solution back into the RHS\n    solver2.RHS(sol_test, residual);\n\n    REQUIRE(std::abs(residual[0]) < 1.1 * tol);\n    REQUIRE(std::abs(residual[1]) < 1.1 * tol);\n    REQUIRE(std::abs(residual[2]) < 1.1 * tol);\n\n    // Make sure that it matches the binary case\n    REQUIRE(std::abs(sol_test[0] - sol_reference[0]) < 2.0 * tol);\n    REQUIRE(std::abs(sol_test[2] - sol_reference[1]) < 2.0 * tol);\n}\n\nTEST_CASE(\"CALPHAD conc solver binary three phase KKS, three-phase convergence\",\n    \"[conc solver binary three phase kks, three-phase convergence]\")\n{\n    // Calculate the inputs and the reference solution\n    Thermo4PFM::EnergyInterpolationType energy_interp_func_type\n        = Thermo4PFM::EnergyInterpolationType::PBG;\n    Thermo4PFM::ConcInterpolationType conc_interp_func_type\n        = Thermo4PFM::ConcInterpolationType::PBG;\n\n    double temperature = 900.;\n\n    std::cout << \" Read CALPHAD database...\" << std::endl;\n    pt::ptree calphad_db;\n    try\n    {\n        pt::read_json(\n            \"../thermodynamic_data/calphadAlCuLFccBcc.json\", calphad_db);\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"exception caught: \" << e.what() << std::endl;\n    }\n\n    boost::optional<pt::ptree&> newton_db;\n\n    Thermo4PFM::CALPHADFreeEnergyFunctionsBinaryThreePhase cafe(\n        calphad_db, newton_db, energy_interp_func_type, conc_interp_func_type);\n\n    // Get the CALPHAD parameters\n    CalphadDataType fA[3];\n    CalphadDataType fB[3];\n    CalphadDataType Lmix_L[4];\n    CalphadDataType Lmix_A[4];\n    CalphadDataType Lmix_B[4];\n\n    cafe.computeTdependentParameters(\n        temperature, Lmix_L, Lmix_A, Lmix_B, fA, fB);\n\n    // initial guesses\n    double c_init0 = 0.9;\n    double c_init1 = 0.9;\n    double c_init2 = 0.9;\n\n    // compute concentrations satisfying KKS equations\n    const double conc = 0.9;\n\n    // Inputs to the solver\n    const double RTinv\n        = 1.0 / (Thermo4PFM::gas_constant_R_JpKpmol * temperature);\n\n    double hphi0 = interp_func(conc_interp_func_type, 0.5);\n    double hphi1 = interp_func(conc_interp_func_type, 0.4);\n    double hphi2 = interp_func(conc_interp_func_type, 0.1);\n\n    const double tol    = 1.e-8;\n    const double alpha  = 0.1; // Using alpha=1 can lead to convergence issues\n    const int max_iters = 10000;\n\n    // Create and set up the solver\n\n    Thermo4PFM::CALPHADConcSolverBinaryThreePhase solver;\n    solver.setup(\n        conc, hphi0, hphi1, hphi2, RTinv, Lmix_L, Lmix_A, Lmix_B, fA, fB);\n\n    // Run the solver\n    double sol_test[3] = { c_init0, c_init1, c_init2 };\n    std::cout << \"Third test...\" << std::endl;\n    int ret = solver.ComputeConcentration(sol_test, tol, max_iters, alpha);\n    std::cout << \"...completed\" << std::endl;\n    std::cout << sol_test[0] << \" \" << sol_test[1] << \" \" << sol_test[2]\n              << std::endl;\n    REQUIRE(ret >= 0);\n\n    // Plug the solution back into the RHS\n    double residual[3];\n    solver.RHS(sol_test, residual);\n\n    REQUIRE(std::abs(residual[0]) < 1.1 * tol);\n    REQUIRE(std::abs(residual[1]) < 1.1 * tol);\n    REQUIRE(std::abs(residual[2]) < 1.1 * tol);\n}\n", "meta": {"hexsha": "f830c9019f756a672d9f33f5e805fe2e0a78b24e", "size": 7583, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/testCALPHADConcSolverBinaryThreePhase.cc", "max_stars_repo_name": "stvdwtt/Thermo4PFM", "max_stars_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2022-01-21T17:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T21:00:24.000Z", "max_issues_repo_path": "tests/testCALPHADConcSolverBinaryThreePhase.cc", "max_issues_repo_name": "stvdwtt/Thermo4PFM", "max_issues_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-21T16:51:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T16:51:52.000Z", "max_forks_repo_path": "tests/testCALPHADConcSolverBinaryThreePhase.cc", "max_forks_repo_name": "stvdwtt/Thermo4PFM", "max_forks_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-13T14:29:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T18:12:51.000Z", "avg_line_length": 31.7280334728, "max_line_length": 80, "alphanum_fraction": 0.6589740208, "num_tokens": 2338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5480000084105558}}
{"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_SQRTVALMAX_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_SQRTVALMAX_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Sqrtvalmax Sqrtvalmax (function template)\n\n  Generates the square root of the greatest finite representable value.\n\n  @headerref{<boost/simd/constant/sqrtvalmax.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Sqrtvalmax();\n      @endcode\n\n  2.  @code\n      template<typename T> T Sqrtvalmax( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T that evaluates to the value of the greatest representable value\n  which square is also representable.\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 `sqrt(Valmax<T>())`\n\n  @par Requirements\n  - **T** models IEEEValue\n**/\n\n#include <boost/simd/constant/scalar/sqrtvalmax.hpp>\n#include <boost/simd/constant/simd/sqrtvalmax.hpp>\n\n#endif\n", "meta": {"hexsha": "327218362bb6a0dff93b569922e449ea28a8198e", "size": 1603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/sqrtvalmax.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/sqrtvalmax.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/sqrtvalmax.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.8269230769, "max_line_length": 100, "alphanum_fraction": 0.5570804741, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.547999998346485}}
{"text": "/*\n * Filename: markers.cpp\n *\n * Copyright 2020 Tecnalia\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 <manipulability_metrics/util/markers.h>\n\n#include <eigen_conversions/eigen_kdl.h>\n#include <eigen_conversions/eigen_msg.h>\n\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\n#include <algorithm>\n\nnamespace manipulability_metrics\n{\nvisualization_msgs::Marker ellipsoidMarker(const Eigen::Matrix<double, 3, Eigen::Dynamic>& half_jacobian,\n                                           const Eigen::Isometry3d& transform, const std::string& root,\n                                           const std::string& ns, const std_msgs::ColorRGBA& color)\n{\n  auto svd = Eigen::JacobiSVD<Eigen::Matrix<double, 3, Eigen::Dynamic>>{ half_jacobian, Eigen::ComputeFullU };\n  auto base = svd.matrixU();\n  auto len = static_cast<Eigen::Vector3d>(svd.singularValues().topRows<3>());\n  if (base.determinant() < 0)\n  {\n    base.col(1).swap(base.col(2));\n    len.row(1).swap(len.row(2));\n  }\n\n  auto ellipsoid_marker = visualization_msgs::Marker{};\n  ellipsoid_marker.type = visualization_msgs::Marker::SPHERE;\n  ellipsoid_marker.header.frame_id = root;\n  ellipsoid_marker.ns = ns;\n  ellipsoid_marker.color = color;\n  tf::pointEigenToMsg(transform.translation(), ellipsoid_marker.pose.position);\n  tf::quaternionEigenToMsg(static_cast<Eigen::Quaterniond>(base), ellipsoid_marker.pose.orientation);\n  tf::vectorEigenToMsg(len, ellipsoid_marker.scale);\n\n  return ellipsoid_marker;\n}\n\nvisualization_msgs::MarkerArray ellipsoidMarkers(const Chain& chain, const std::vector<double>& joint_positions,\n                                                 const std::string& ns_prefix)\n{\n  return ellipsoidMarkers(chain, KDL::Frame{}, joint_positions, ns_prefix);\n}\n\nvisualization_msgs::MarkerArray ellipsoidMarkers(const Chain& chain, const KDL::JntArray& joint_positions,\n                                                 const std::string& ns_prefix)\n{\n  return ellipsoidMarkers(chain, KDL::Frame{}, joint_positions, ns_prefix);\n}\n\nvisualization_msgs::MarkerArray ellipsoidMarkers(const Chain& chain, const KDL::Frame& tcp,\n                                                 const std::vector<double>& joint_positions,\n                                                 const std::string& ns_prefix)\n{\n  auto jnt_array = KDL::JntArray{ static_cast<unsigned int>(joint_positions.size()) };\n  jnt_array.data =\n      Eigen::Map<const Eigen::VectorXd>{ joint_positions.data(), static_cast<Eigen::Index>(joint_positions.size()) };\n  return ellipsoidMarkers(chain, tcp, jnt_array, ns_prefix);\n}\n\nvisualization_msgs::MarkerArray ellipsoidMarkers(const Chain& chain, const KDL::Frame& tcp,\n                                                 const KDL::JntArray& joint_positions, const std::string& ns_prefix)\n{\n  auto frame = KDL::Frame{};\n  auto jacobian = KDL::Jacobian{ static_cast<unsigned int>(chain.n_joints) };\n  if (!chain.transform(joint_positions, tcp, frame) || !chain.jacobian(joint_positions, tcp.p, jacobian))\n  {\n    return {};\n  }\n\n  const auto transform = [&] {\n    auto transform = Eigen::Isometry3d{};\n    tf::transformKDLToEigen(frame, transform);\n    return transform;\n  }();\n\n  auto marker_array = visualization_msgs::MarkerArray{};\n  marker_array.markers.reserve(2);\n  {\n    std_msgs::ColorRGBA transparent_green;\n    transparent_green.g = 1.0;\n    transparent_green.a = 0.5;\n    marker_array.markers.push_back(ellipsoidMarker(jacobian.data.topRows<3>(), transform, chain.root,\n                                                   ns_prefix + \"translational_ellipsoid\", transparent_green));\n  }\n  {\n    std_msgs::ColorRGBA transparent_red;\n    transparent_red.r = 1.0;\n    transparent_red.a = 0.5;\n    marker_array.markers.push_back(ellipsoidMarker(jacobian.data.bottomRows<3>(), transform, chain.root,\n                                                   ns_prefix + \"rotational_ellipsoid\", transparent_red));\n  }\n\n  return marker_array;\n}\n\nvisualization_msgs::MarkerArray desiredEllipsoidMarkers(const Ellipsoid& desired_ellipsoid, const std::string& frame_id,\n                                                        const KDL::Frame& transform)\n{\n  auto pseudoU = Eigen::Matrix<double, 6, 6>{};\n  auto pseudoS = Eigen::Matrix<double, 6, 6>{ Eigen::Matrix<double, 6, 6>::Zero() };\n  for (std::size_t i = 0; i < 6; ++i)\n  {\n    pseudoU.col(i) = desired_ellipsoid[i].unit;\n    pseudoS(i, i) = desired_ellipsoid[i].len;\n  }\n  const auto pseudojac = pseudoU * pseudoS;\n\n  const auto eigen_transform = [&] {\n    auto eigen_transform = Eigen::Isometry3d{};\n    tf::transformKDLToEigen(transform, eigen_transform);\n    return eigen_transform;\n  }();\n\n  auto markers = visualization_msgs::MarkerArray{};\n  markers.markers.reserve(2);\n  {\n    std_msgs::ColorRGBA transparent_light_green;\n    transparent_light_green.r = 0.2;\n    transparent_light_green.b = 0.2;\n    transparent_light_green.g = 1.0;\n    transparent_light_green.a = 0.5;\n\n    markers.markers.push_back(ellipsoidMarker(pseudojac.topRows<3>(), eigen_transform, frame_id,\n                                              \"desired_translational_ellipsoid\", transparent_light_green));\n  }\n  {\n    std_msgs::ColorRGBA transparent_light_red;\n    transparent_light_red.r = 1.0;\n    transparent_light_red.b = 0.2;\n    transparent_light_red.g = 0.2;\n    transparent_light_red.a = 0.5;\n\n    markers.markers.push_back(ellipsoidMarker(pseudojac.bottomRows<3>(), eigen_transform, frame_id,\n                                              \"desired_rotational_ellipsoid\", transparent_light_red));\n  }\n  return markers;\n}\n\n}  // namespace manipulability_metrics\n", "meta": {"hexsha": "68acc1210c9281b0382c2222fd04f0e8b99a4399", "size": 6096, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "manipulability_metrics/src/markers.cpp", "max_stars_repo_name": "tecnalia-medical-robotics/manipulability_metrics", "max_stars_repo_head_hexsha": "0e1360376a49fdc623e761fc8ca769e99fa11ac9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-02-15T16:15:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T03:01:22.000Z", "max_issues_repo_path": "manipulability_metrics/src/markers.cpp", "max_issues_repo_name": "iLoveVenki/manipulability_metrics", "max_issues_repo_head_hexsha": "0e1360376a49fdc623e761fc8ca769e99fa11ac9", "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": "manipulability_metrics/src/markers.cpp", "max_forks_repo_name": "iLoveVenki/manipulability_metrics", "max_forks_repo_head_hexsha": "0e1360376a49fdc623e761fc8ca769e99fa11ac9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-04-06T08:18:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T12:43:57.000Z", "avg_line_length": 38.582278481, "max_line_length": 120, "alphanum_fraction": 0.6699475066, "num_tokens": 1421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5479999976264763}}
{"text": "#include <stan/math/prim/mat.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathMatrix,dimensionValidation) {\n  using stan::math::determinant;\n  using Eigen::Matrix;\n  using Eigen::Dynamic;\n  Matrix<double,Dynamic,Dynamic> x(3,3);\n  x << 1, 2, 3, 1, 4, 9, 1, 8, 27;\n\n  ASSERT_FALSE(boost::math::isnan(determinant(x)));\n\n  Matrix<double,Dynamic,Dynamic> xx(3,2);\n  xx << 1, 2, 3, 1, 4, 9;\n  EXPECT_THROW(stan::math::determinant(xx), std::invalid_argument);\n}\n", "meta": {"hexsha": "f0818ff1702b49e43b1ca938dde8bc0ffdce2991", "size": 502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/fun/determinant_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/mat/fun/determinant_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/mat/fun/determinant_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.8888888889, "max_line_length": 67, "alphanum_fraction": 0.6912350598, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5479684618412723}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Hidekazu Ikeno\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\n * THE SOFTWARE.\n */\n\n///\n/// \\file fast_esprit.hpp\n///\n#ifndef MXPFIT_FAST_ESPRIT_HPP\n#define MXPFIT_FAST_ESPRIT_HPP\n\n#include <algorithm>\n#include <type_traits>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n#include <mxpfit/exponential_sum.hpp>\n#include <mxpfit/hankel_matrix.hpp>\n#include <mxpfit/partial_lanczos_bidiagonalization.hpp>\n\n// #include <mxpfit/matrix_free_gemv.hpp>\n// #include <mxpfit/vandermonde_least_squares.hpp>\n#include <mxpfit/prony_like_method_common.hpp>\n\nnamespace mxpfit\n{\n///\n/// ### FastESPRIT\n///\n/// \\brief Fast ESPRIT method for finding parameters of exponential sum\n/// approximation from sampled data on uniform grid.\n///\n/// \\tparam T  Scalar type of function values.\n///\n/// #### Description\n///\n/// For a given sequence \\f$ f_{k}=f(t_{k}) \\f$ sampled on a uniform grid\n/// \\f$t_{k}=t_{0}+hk\\, (k=0,1,\\dots,N-1)\\f$ and prescribed accuracy\n/// \\f$\\epsilon\\f$, this class finds exponential sum approximation of function\n/// \\f$ f(t) \\f$ such that,\n///\n/// \\f[\n///   \\left| f_{k}-\\sum_{j=1}^{M}c_{j}e^{-a_{j} t} \\right| < \\epsilon\n/// \\f]\n///\n/// with \\f$\\mathrm{Re}(a_{j}) > 0.\\f$ The problem is solved using the fast\n/// ESPRIT algorithm via partial Lanczos bidiagonalization which has been\n/// developed by Potts and Tasche (2015). The present algorithm was slightly\n/// modified from the original one.\n///\n/// #### References\n///\n/// 1. D. Potts and M. Tasche, \"Fast ESPRIT algorithms based on partial singular\n///    value decompositions\", Appl. Numer. Math. **88** (2015) 31-45.\n///    [DOI: https://doi.org/10.1016/j.apnum.2014.10.003]\n/// 2. D. Potts and M. Tasche,\"Parameter estimation for nonincreasing\n///    exponential sums by Prony-like methods\", Linear Algebra Appl. **439**\n///    (2013) 1024-1039.\n///    [DOI: https://doi.org/10.1016/j.laa.2012.10.036]\n/// 3. K. Browne, S. Qiao, and Y. Wei, \"A Lanczos bidiagonalization algorithm\n///    for Hankel matrices\", Linear Algebra Appl. **430** (2009) 1531-1543.\n///    [DOI: https://doi.org/10.1016/j.laa.2008.01.012]\n///\ntemplate <typename T>\nclass FastESPRIT\n{\npublic:\n    using Scalar        = T;\n    using RealScalar    = typename Eigen::NumTraits<Scalar>::Real;\n    using ComplexScalar = std::complex<RealScalar>;\n    using Index         = Eigen::Index;\n\n    using Vector        = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using RealVector    = Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>;\n    using ComplexVector = Eigen::Matrix<ComplexScalar, Eigen::Dynamic, 1>;\n\n    using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using RealMatrix =\n        Eigen::Matrix<RealScalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using ComplexMatrix =\n        Eigen::Matrix<ComplexScalar, Eigen::Dynamic, Eigen::Dynamic>;\n\n    using ResultType =\n        typename detail::gen_prony_like_method_result<T>::ResultType;\n\nprivate:\n    using HankelGEMV      = MatrixFreeGEMV<HankelMatrix<Scalar>>;\n    using VandermondeGEMV = MatrixFreeGEMV<VandermondeMatrix<ComplexScalar>>;\n    enum\n    {\n        IsComplex = Eigen::NumTraits<Scalar>::IsComplex,\n        Alignment = Eigen::internal::traits<Matrix>::Alignment\n    };\n\n    using MappedMatrix = Eigen::Map<Matrix, Alignment>;\n\n    Index m_rows;\n    Index m_cols;\n    Index m_max_terms;\n    Index m_extra_basis = 5;\n    HankelMatrix<Scalar> m_matH;\n    PartialLanczosBidiagonalization<HankelGEMV> m_plbd;\n\npublic:\n    ///\n    /// Default constructor\n    ///\n    FastESPRIT() = default;\n\n    ///\n    /// Constructor with memory preallocation\n    ///\n    /// \\param[in] N  Number of sampling points\n    /// \\param[in] L  Window size. This is equals to the number of rows of\n    ///               generalized Hankel matrix.\n    /// \\param[in] M  Maxumum number of terms used for the exponential sum.\n    /// \\pre  `N >= M >= 1` and `N - L + 1 >= M >= 1`.\n    ///\n    FastESPRIT(Index N, Index L, Index M)\n        : m_rows(L),\n          m_cols(N - L + 1),\n          m_max_terms(M),\n          m_extra_basis(5),\n          m_matH(m_rows, m_cols),\n          m_plbd(m_rows, m_cols,\n                 std::min({m_rows, m_cols, m_max_terms + m_extra_basis}))\n    {\n        assert(m_rows >= M && m_cols >= M && M >= 1);\n    }\n\n    /// Destructor\n    ~FastESPRIT()\n    {\n    }\n\n    ///\n    /// Memory reallocation\n    ///\n    /// \\param[in] N  Number of sampling points\n    /// \\param[in] L  Window size. This is equals to the number of rows of\n    ///               generalized Hankel matrix.\n    /// \\param[in] M  Maxumum number of terms used for the exponential sum.\n    /// \\pre  `N >= L >= N / 2 >= 1` and `N - L + 1 >= M >= 1`.\n    ///\n    void resize(Index N, Index L, Index M)\n    {\n        m_rows = L;\n        m_cols = N - L + 1;\n        assert(m_rows >= M && m_cols >= M && M >= 1);\n        m_max_terms = M;\n        m_matH.resize(m_rows, m_cols);\n        // Internal matrices of `m_plbd` are resized automatically during\n        // computation\n    }\n\n    ///\n    /// \\return Number of sampling points.\n    ///\n    Index size() const\n    {\n        return m_matH.size();\n    }\n\n    ///\n    /// Fit signals by a exponential sum\n    ///\n    /// \\param[in] f The array of signals sampled on the equispaced grid. The\n    ///    first `size()` elemnets of `f` are used as a sampled data. In case\n    ///    `f.size() < size()` then, last `size() - f.size()` elements are\n    ///    padded by zeros.\n    /// \\param[in] eps  Small positive number `(0 < eps < 1)` that\n    ///    controlls the accuracy of the fit.\n    /// \\param[in] x0  Argument of first sampling point\n    /// \\param[in] delta Spacing between neighboring sample points.\n    ///\n    template <typename VectorT>\n    ResultType compute(const Eigen::MatrixBase<VectorT>& h, RealScalar x0,\n                       RealScalar delta, RealScalar eps);\n};\n\ntemplate <typename T>\ntemplate <typename VectorT>\ntypename FastESPRIT<T>::ResultType\nFastESPRIT<T>::compute(const Eigen::MatrixBase<VectorT>& h, RealScalar x0,\n                       RealScalar delta, RealScalar eps)\n{\n    using Eigen::numext::sqrt;\n    assert(h.size() == size() && \"Number of data points mismatch.\");\n    //\n    // Form rectangular Hankel matrix and pre-compute for fast multiplication to\n    // the vector.\n    //\n    m_matH.setCoeffs(h);\n    const Index nr = m_matH.rows();\n    const Index nc = m_matH.cols();\n\n    //-------------------------------------------------------------------------\n    // Compute roots of Prony polynomials\n    //-------------------------------------------------------------------------\n    //\n    // Partial Lanczos bidiagonalization of Hankel matrix H = P B Q^H\n    //\n    HankelGEMV opH(m_matH);\n    m_plbd.setTolerance(eps);\n    m_plbd.compute(opH, std::min({nr, nc, m_max_terms + m_extra_basis}));\n    const Index nterms = m_plbd.rank();\n\n    if (nterms == 0)\n    {\n        return ResultType();\n    }\n\n    // {\n    //     Matrix denseH = m_matH.toDenseMatrix();\n    //     std::cout << \"Partial LBD error: ||H - P B Q*||_F  = \"\n    //               << (denseH - m_plbd.reconstructedMatrix()).norm()\n    //               << std::endl;\n    //     std::cout << \"(alpha):\\n\"\n    //               << m_plbd.diagonalAlpha().head(nterms) << \"\\n(beta):\\n\"\n    //               << m_plbd.superdiagonalBeta().head(nterms - 1) <<\n    //               std::endl;\n    // }\n\n    // --- Form the views of matrix Q\n    // Matrix Q excluding the last row\n    auto Q0 = m_plbd.matrixQ().block(0, 0, nc - 1, nterms);\n    // Matrix Q excluding the first row\n    auto Q1 = m_plbd.matrixQ().block(1, 0, nc - 1, nterms);\n    // adjoint of the last row of matrix Q\n    auto nu = m_plbd.matrixQ().block(nc - 1, 0, 1, nterms).adjoint();\n    //\n    // Compute the spectral matrix G = pinv(Q0) * Q1, where pinv indicate\n    // the Moore-Penrose pseudo-inverse. The computation of the\n    // pseudo-inverse of Q0 can be avoided.\n    //\n    Matrix G(Q0.adjoint() * Q1);\n    Vector phi(G.adjoint() * nu);\n    auto scal = RealScalar(1) / (RealScalar(1) - nu.squaredNorm());\n    G += scal * nu * phi.adjoint();\n    //\n    // Prony roots \\f$\\{z_i\\{\\}\\f$ are the eigenvalues of matrix G.\n    // The exponents for approximation are obtained as \\f$ \\log z_i \\f$\n    //\n    ComplexVector tmp_roots(G.eigenvalues());\n    // std::cout << \"\\n*** roots\\n\" << tmp_roots << std::endl;\n    //\n    // Find roots on unit disk \\f$z_{i} \\in \\mathbb{D}\\f$.\n    // If Scalar is a real type, neagative real roots will also be discarded.\n    //\n    tmp_roots =\n        detail::prony_roots_on_unit_disk<Scalar>::compute(tmp_roots, sqrt(eps));\n\n    ComplexVector roots(std::min(tmp_roots.size(), m_max_terms));\n    roots = tmp_roots.head(roots.size());\n\n    //----------------------------------------------------------------------\n    // Solve overdetermined Vandermonde system to obtain the weights\n    //----------------------------------------------------------------------\n    ComplexVector weights(roots.size());\n    detail::solve_overdetermined_vandermonde(\n        roots, h, weights, eps, std::max(Index(100), 5 * roots.size()));\n\n    // Rescale the exponents and weights, and return the result\n    ResultType ret(roots.size());\n    ret.exponents() = -roots.array().log() / delta;\n    if (x0 == RealScalar())\n    {\n        ret.weights() = weights.array(); // Don't forget to copy weights\n    }\n    else\n    {\n        ret.weights() = weights.array() * (-x0 * ret.exponents()).exp();\n    }\n\n    return ret;\n\n    // return detail::gen_prony_like_method_result<T>::create(\n    //     roots.array(), weights.array(), x0, delta);\n}\n\n} // namespace mxpfit\n\n#endif /* MXPFIT_FAST_ESPRIT_HPP */\n", "meta": {"hexsha": "23f9057715849b2ee0f606c5eaf2bb939fa95765", "size": 10676, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/fast_esprit.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/fast_esprit.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/fast_esprit.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": 35.1184210526, "max_line_length": 80, "alphanum_fraction": 0.6085612589, "num_tokens": 2857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5479684595134199}}
{"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    testRot3.cpp\n * @brief   Unit tests for Rot3Q class\n * @author  Richard Roberts\n */\n\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/base/Testable.h>\n#include <boost/math/constants/constants.hpp>\n#include <gtsam/base/numericalDerivative.h>\n#include <gtsam/base/lieProxies.h>\n#include <gtsam/geometry/Point3.h>\n#include <gtsam/geometry/Rot3.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/GaussNewtonOptimizer.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/slam/BetweenFactor.h>\n\nusing namespace gtsam;\n\ntypedef BetweenFactor<Rot3> Between;\ntypedef NonlinearFactorGraph Graph;\n\n/* ************************************************************************* */\nTEST(Rot3, optimize) {\n\n  // Optimize a circle\n  Values truth;\n  Values initial;\n  Graph fg;\n  fg.addPrior(Symbol('r',0), Rot3(), noiseModel::Isotropic::Sigma(3, 0.01));\n  for(int j=0; j<6; ++j) {\n    truth.insert(Symbol('r',j), Rot3::Rz(M_PI/3.0 * double(j)));\n    initial.insert(Symbol('r',j), Rot3::Rz(M_PI/3.0 * double(j) + 0.1 * double(j%2)));\n    fg += Between(Symbol('r',j), Symbol('r',(j+1)%6), Rot3::Rz(M_PI/3.0), noiseModel::Isotropic::Sigma(3, 0.01));\n  }\n\n  Values final = GaussNewtonOptimizer(fg, initial).optimize();\n\n  EXPECT(assert_equal(truth, final, 1e-5));\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "5746022a36a27dce2a46798f0b836efdbb56db2a", "size": 1923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testRot3Optimization.cpp", "max_stars_repo_name": "zwn/gtsam", "max_stars_repo_head_hexsha": "3422c3bb66bef319d66a950857bb6ec073b43703", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "tests/testRot3Optimization.cpp", "max_issues_repo_name": "zwn/gtsam", "max_issues_repo_head_hexsha": "3422c3bb66bef319d66a950857bb6ec073b43703", "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": "tests/testRot3Optimization.cpp", "max_forks_repo_name": "zwn/gtsam", "max_forks_repo_head_hexsha": "3422c3bb66bef319d66a950857bb6ec073b43703", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 565.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T16:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:53:04.000Z", "avg_line_length": 32.05, "max_line_length": 113, "alphanum_fraction": 0.5590223609, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5479684593112223}}
{"text": "/*\r\n * dct.cpp\r\n *\r\n * Author: M. Karnutsch (mkarnut@cosy.sbg.ac.at), C. Rathgeb (crathgeb@cosy.sbg.ac.at), P. Wild (pwild@cosy.sbg.ac.at)\r\n *\r\n * Generates an iris code from iris texture using the Monro et al. algorithm\r\n *\r\n */\r\n#include <cstdio>\r\n#include <map>\r\n#include <vector>\r\n#include <string>\r\n#include <cstring>\r\n#include <ctime>\r\n#include <fstream>\r\n#include <opencv2/core/core.hpp>\r\n#include <opencv2/imgproc/imgproc.hpp>\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <boost/regex.hpp>\r\n#include <boost/filesystem.hpp>\r\n#include <boost/date_time/posix_time/posix_time_types.hpp>\r\n\r\nusing namespace std;\r\nusing namespace cv;\r\n\r\n#define pi 3.1415926535897931\r\n#define M_PI 3.14159265358979323846\r\n#define pihalf 1.57079632679489661923\r\n\r\n/*\r\n * default options\r\n */\r\n#define DCT_CUTOFF 3\r\n#define DCT_DEGREE 65\r\n#define DCT_PATCHHEIGHT 8\r\n#define DCT_PATCHWIDTH 12\r\n#define DCT_PATCHES 85\r\n#define DCT_ROWS 12\r\n#define DCT_WNDHEIGHT 2\r\n#define DCT_WNDWIDTH 1\r\n#define DCT_COEFFSIZE 3\r\n\r\nstruct b_d{\r\n    unsigned char **data;\r\n    unsigned char **bits;\r\n    int size;\r\n    struct b_d *next;\r\n};\r\n\r\nstruct allshifts_and_bits{\r\n    int size;\r\n    struct b_d *bitsdata;\r\n};\r\n\r\nstruct window_functions\r\n{\r\n    double *window_w;\r\n    double *window_h;\r\n    int sizew;\r\n    int sizeh;\r\n};\r\n\r\n/** no globbing in win32 mode **/\r\nint _CRT_glob = 0;\r\n\r\n/** Program modes **/\r\nstatic const int MODE_MAIN = 1, MODE_HELP = 2;\r\n\r\n/*\r\n * Print command line usage for this program\r\n */\r\nvoid printUsage() {\r\n\tprintf(\"+-----------------------------------------------------------------------------+\\n\");\r\n\tprintf(\"| dct - Iris-code generation (feature extraction) using the Monro algorithm   |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| Monro D. M., Rakshit S., Zhang D.: DCT-based Iris Recognition,              |\\n\");\r\n\tprintf(\"| IEEE Trans Pattern Anal Mach Intell. 2007 Apr;29(4):586-95.                 |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| MODES                                                                       |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n    printf(\"| (# 1) DCT iris code extraction from iris textures                           |\\n\");\r\n    printf(\"| (# 2) usage                                                                 |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| ARGUMENTS                                                                   |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n    printf(\"| Name | Parameters | # | ? | Description                                     |\\n\");\r\n    printf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n    printf(\"| -i   | infile     | 1 | N | input iris texture (use * as wildcard, all other|\\n\");\r\n    printf(\"|      |            |   |   | file parameters may refer to n-th * with ?n)    |\\n\");\r\n    printf(\"| -o   | outfile    | 1 | N | output iris code image                          |\\n\");\r\n    printf(\"| -q   |            | 1 | Y | quiet mode on (off)                             |\\n\");\r\n    printf(\"| -t   |            | 1 | Y | time progress on (off)                          |\\n\");\r\n    printf(\"| -h   |            | 2 | N | prints usage                                    |\\n\");\r\n    printf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| EXAMPLE USAGE                                                               |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| -i s1.tiff -o s1.png                                                        |\\n\");\r\n    printf(\"| -i *.tiff -o ?1.png -q -t                                                   |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| AUTHORS                                                                     |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| Michael Karnutsch (mkarnut@cosy.sbg.ac.at)                                  |\\n\");\r\n    printf(\"| Christian Rathgeb (crathgeb@cosy.sbg.ac.at)                                 |\\n\");\r\n    printf(\"| Peter Wild (pwild@cosy.sbg.ac.at)                                           |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| COPYRIGHT                                                                   |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| (C) 2012 All rights reserved. Do not distribute without written permission. |\\n\");\r\n    printf(\"+-----------------------------------------------------------------------------+\\n\");\r\n}\r\n\r\n/** ------------------------------- image processing functions ------------------------------- **/\r\n\r\nunsigned char **data, **left4, **left8, **left12, **right4, **right8, **right12;\r\n\r\nstruct allshifts_and_bits *ab = NULL;\r\nstruct window_functions *window = NULL;\r\n\r\nint h;\r\nint w;\r\nint rotateDCT[3] = {4,8,12};\r\nint degree0[64] = {0};\r\nint degree10[64] = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15};\r\nint degree17[64] = {0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 14, 14, 14, 15, 15, 15, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 20, 20, 20, 21, 21, 21, 22, 22, 23, 23, 23};\r\nint degree25[64] = {0, 0,  1, 1, 2, 2,  3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31};\r\nint degree32[64] = {0, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 10, 11, 11, 12, 12, 13, 13, 14, 15, 16, 16, 17, 17, 18, 18, 19, 20, 21, 21, 22, 22, 23, 23, 24, 25, 26, 26, 27, 27, 28, 28, 29, 30, 31, 31, 32, 32, 33, 33, 34, 35, 36, 36, 37, 37, 38, 38, 39};\r\nint degree38[64] = {0, 1, 1, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9, 10, 10, 11, 12, 13, 13, 14, 15, 16, 16, 17, 18, 19, 19, 20, 21, 22, 22, 23, 24, 25, 25, 26, 27, 28, 28, 29, 30, 31, 31, 32, 33, 34, 34, 35, 36, 37, 37, 38, 39, 40, 40, 41, 42, 43, 43, 44, 45, 46, 46, 47};\r\nint degree41[64] = {0, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 21, 22, 23, 24, 24, 25, 26, 27, 28, 29, 30, 31, 31, 32, 33, 34, 35, 36, 37, 38, 38, 39, 40, 41, 42, 43, 44, 45, 45, 46, 47, 48, 49, 50, 51, 52, 52, 53, 54, 55};\r\nint degree45[64] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63};\r\nint degree50[64] = {0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39,  41, 42, 43, 44, 45,  46, 47, 48,  50, 51,  52, 53, 54, 55, 56, 57, 59, 60, 61, 62, 63, 64, 65, 66, 68, 69, 70, 71};\r\nint degree55[64] = {0, 1, 3, 4, 5, 6, 8, 9, 10, 11, 13, 14, 15, 16, 18, 19, 20, 21, 23, 24, 25, 26, 28, 29, 30, 31, 33, 34, 35, 36, 38, 39, 40, 41, 43, 44, 45, 46, 48, 49, 50, 51, 53, 54, 55, 56, 58, 59, 60, 61, 63, 64, 65, 66, 68, 69, 70, 71, 73, 74, 75, 76, 78, 79};\r\nint degree60[64] = {0, 1, 3, 5, 7, 9, 11, 12, 13, 14, 16, 18, 20, 22, 24, 25, 26, 27, 29, 31, 33, 35, 37, 38, 39, 40, 42, 44, 46, 48, 50, 51, 52, 53, 55, 57, 59, 61, 63, 64, 65, 66, 67, 69, 71, 73, 75, 77, 78, 79, 81, 83, 85, 87, 89, 90, 91, 92, 93, 95, 97, 99, 101, 102};\r\nint degree65[64] = {0, 2, 4, 6, 8,  10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88,  90,  92,  94,  96,  98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126};\r\nint degree70[64] = {0, 2, 5, 7, 10, 12, 15, 17, 18, 20, 23, 25, 28, 30, 33, 35, 36, 38, 41, 43, 45, 47, 50, 52, 53, 55, 58, 60, 63, 65, 68, 70, 71, 73,  76,  78,  81,  83,  85,  87,  88,  90,  93,  95,  98, 100, 103, 105, 106, 108, 111, 113, 116, 118, 121, 123, 124, 126, 129, 131, 134, 136, 139, 141};\r\nint degree75[64] = {0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99, 102, 105, 108, 111, 114, 117, 120, 123, 126, 129, 132, 135, 138, 141, 145, 148, 151, 154, 157, 160, 163, 166, 169, 172, 175, 178, 181, 184, 187, 190};\r\n\r\nvoid setBitTo1(uchar* code, int bitpos){\r\n\tcode[bitpos / 8] |= (1 << (bitpos % 8));\r\n}\r\n\r\nvoid setBitTo0(uchar* code, int bitpos){\r\n\tcode[bitpos / 8] &= (0xff ^ 1 << (bitpos % 8));\r\n}\r\n\r\nint signum(double i)\r\n{\r\n    if(i > 0.0) return 1;\r\n    else return -1;\r\n}\r\n\r\ndouble *mydct(double *i, int n)\r\n{\r\n    long bin,k;\r\n    double *d = (double*)malloc(sizeof(double) * n);\r\n    double arg;\r\n    double one = sqrt((float)n);\r\n    one = 1/one;\r\n    double two = 2/(float)n;\r\n    two = sqrt(two);\r\n    for (bin = 1; bin <= n; bin++)\r\n    {\r\n        d[bin - 1] = 0.;\r\n        for (k = 1; k <= n; k++)\r\n        {\r\n            arg = (2*k - 1) * (bin - 1)  / (float)n;\r\n            arg = arg * pihalf;\r\n            d[bin - 1] += i[k - 1] * cos(arg);\r\n        }\r\n        if(bin == 1)\r\n        {\r\n            d[bin - 1] = d[bin - 1] * one;\r\n        }\r\n        else\r\n        {\r\n            d[bin - 1] = d[bin - 1] * two;\r\n        }\r\n    }\r\n    return d;\r\n}\r\n\r\n\r\nunsigned char **truncate_image(const Mat& texture)\r\n{\r\n    h = (DCT_ROWS + 1)*(DCT_PATCHHEIGHT/2);\r\n    w = (DCT_PATCHES + 9)*(DCT_PATCHWIDTH/2);\r\n    unsigned char **image;\r\n    image = (unsigned char**)malloc( h * sizeof(unsigned char*));\r\n    int front = DCT_PATCHWIDTH;\r\n    int i = (DCT_CUTOFF)*(texture.cols);\r\n    int diff = w - texture.cols - front;\r\n    uchar* textureData = texture.data;\r\n    for(int q = 0; q < h; q++)\r\n    {\r\n        image[q] = (unsigned char*)malloc( w * sizeof(unsigned char));\r\n    }\r\n\r\n    if(diff > 0)\r\n    {\r\n      for(int r = 0; r < h*texture.cols; r++)\r\n      {\r\n          image[(r/512)][(r%512) + front] = textureData[r + i];\r\n      }\r\n        for(int q = 0; q < h; q++)\r\n        {\r\n            for(int e = 0; e < diff; e++)\r\n            {\r\n                image[q][texture.cols + e + front] = image[q][e + front];\r\n                //printf(\"(%i,%i) = %d \\n\", q, img->w + e, image[q][e]);\r\n            }\r\n            for(int t = 0; t < front; t++)\r\n            {\r\n                image[q][t] = image[q][texture.cols + t];\r\n            }\r\n        }\r\n    }\r\n    else\r\n    {\r\n        for(int q = 0; q < h; q++)\r\n        {\r\n            for(int e = 0; e < w; e++)\r\n            {\r\n                image[q][e] = textureData[q*texture.cols + i + e];\r\n            }\r\n        }\r\n    }\r\n    return image;\r\n}\r\n\r\n\r\nunsigned char **shift_image(unsigned char **img)\r\n{\r\n    int *shiftpointer;\r\n    switch(DCT_DEGREE)\r\n    {\r\n        case 0:\r\n          shiftpointer = degree0;\r\n          break;\r\n        case 10:\r\n          shiftpointer = degree10;\r\n          break;\r\n        case 17:\r\n          shiftpointer = degree17;\r\n          break;\r\n        case 25:\r\n          shiftpointer = degree25;\r\n          break;\r\n        case 32:\r\n          shiftpointer = degree32;\r\n          break;\r\n        case 38:\r\n          shiftpointer = degree38;\r\n          break;\r\n        case 41:\r\n          shiftpointer = degree41;\r\n          break;\r\n        case 45:\r\n          shiftpointer = degree45;\r\n          break;\r\n        case 50:\r\n          shiftpointer = degree50;\r\n          break;\r\n        case 55:\r\n          shiftpointer = degree55;\r\n          break;\r\n        case 60:\r\n          shiftpointer = degree60;\r\n          break;\r\n        case 65:\r\n          shiftpointer = degree65;\r\n          break;\r\n        case 70:\r\n          shiftpointer = degree70;\r\n          break;\r\n        case 75:\r\n          shiftpointer = degree75;\r\n          break;\r\n        default:\r\n          shiftpointer = degree45;\r\n          printf(\"degree: %i not possible, 45 used instead\\n\" , DCT_DEGREE);\r\n          break;\r\n    }\r\n    unsigned char **shifted = (unsigned char**)malloc( h * sizeof(unsigned char*));\r\n    int y = 0;\r\n    while(y < h)\r\n    {\r\n        shifted[y] = (unsigned char*)malloc( w * sizeof(unsigned char));\r\n        int i;\r\n        for(i = 0; i < w; i++)\r\n        {\r\n            shifted[y][(i + shiftpointer[y])%w] = img[y][i];\r\n        }\r\n        y++;\r\n    }\r\n    return shifted;\r\n}\r\n\r\nvoid rotate_image()\r\n{\r\n    left4 = (unsigned char**)malloc( h * sizeof(unsigned char*));\r\n    left8 = (unsigned char**)malloc( h * sizeof(unsigned char*));\r\n    left12 = (unsigned char**)malloc( h * sizeof(unsigned char*));\r\n    right4 = (unsigned char**)malloc( h * sizeof(unsigned char*));\r\n    right8 = (unsigned char**)malloc( h * sizeof(unsigned char*));\r\n    right12 = (unsigned char**)malloc( h * sizeof(unsigned char*));\r\n    int y = 0;\r\n    while(y < h)\r\n    {\r\n        left4[y] = (unsigned char*)malloc( w * sizeof(unsigned char));\r\n        left8[y] = (unsigned char*)malloc( w * sizeof(unsigned char));\r\n        left12[y] = (unsigned char*)malloc( w * sizeof(unsigned char));\r\n        right4[y] = (unsigned char*)malloc( w * sizeof(unsigned char));\r\n        right8[y] = (unsigned char*)malloc( w * sizeof(unsigned char));\r\n        right12[y] = (unsigned char*)malloc( w * sizeof(unsigned char));\r\n        int i;\r\n        for(i = 0; i < w; i++)\r\n        {\r\n          left4[y][i] = data[y][(i + rotateDCT[0])%w];\r\n          left8[y][i] = data[y][(i + rotateDCT[1])%w];\r\n          left12[y][i] = data[y][(i + rotateDCT[2])%w];\r\n          right4[y][i] = data[y][(i + w - rotateDCT[0])%w];\r\n          right8[y][i] = data[y][(i + w - rotateDCT[1])%w];\r\n          right12[y][i] = data[y][(i + w -rotateDCT[2])%w];\r\n        }\r\n        y++;\r\n    }\r\n    ab = (allshifts_and_bits*)malloc(sizeof(struct allshifts_and_bits ));\r\n    ab->size = 7;\r\n    struct b_d *left12bd = (b_d*)malloc(sizeof(struct b_d));\r\n    struct b_d *left8bd = (b_d*)malloc(sizeof(struct b_d));\r\n    struct b_d *left4bd = (b_d*)malloc(sizeof(struct b_d));\r\n    struct b_d *origbd = (b_d*)malloc(sizeof(struct b_d));\r\n    struct b_d *right4bd = (b_d*)malloc(sizeof(struct b_d));\r\n    struct b_d *right8bd = (b_d*)malloc(sizeof(struct b_d));\r\n    struct b_d *right12bd = (b_d*)malloc(sizeof(struct b_d));\r\n    origbd->data = data;\r\n    origbd->next = right4bd;\r\n    right4bd->data = right4;\r\n    right4bd->next = right8bd;\r\n    right8bd->data = right8;\r\n    right8bd->next = right12bd;\r\n    right12bd->data = right12;\r\n    right12bd->next = left4bd;\r\n    left4bd->data = left4;\r\n    left4bd->next = left8bd;\r\n    left8bd->data = left8;\r\n    left8bd->next = left12bd;\r\n    left12bd->data = left12;\r\n    left12bd->next = NULL;\r\n    ab->bitsdata = origbd;\r\n}\r\n\r\ndouble *compute_dct(double *patch)\r\n{\r\n    double *d, *all;\r\n    d= (double*)malloc(DCT_COEFFSIZE * sizeof(double));\r\n    all = mydct(patch, DCT_PATCHHEIGHT);\r\n    for(int i = 0; i < DCT_COEFFSIZE; i++)\r\n    {\r\n        d[i] = all[i];\r\n    }\r\n    return d;\r\n}\r\n\r\nunsigned char *generate_codes()\r\n{\r\n    struct b_d *actualstruct = ab->bitsdata;\r\n    unsigned char **actualdata;\r\n    double actualpatch[DCT_PATCHHEIGHT];\r\n    double *actualcoeff;\r\n    double dctvalues[DCT_COEFFSIZE][DCT_PATCHES + 2 + 3];\r\n    double diffs[DCT_COEFFSIZE][DCT_PATCHES + 1 + 3];\r\n    unsigned char **bits;\r\n    int howmanybits = DCT_PATCHES * DCT_ROWS;\r\n    int extrabits = 0;\r\n    int size = howmanybits;\r\n    if(howmanybits%8 > 0)\r\n    {\r\n        howmanybits = howmanybits + 8 - howmanybits%8;\r\n        size = howmanybits;\r\n        extrabits = 1;\r\n    }\r\n    int  r, p, ah, aw, c, d, halfpatchsizeheight = DCT_PATCHHEIGHT/2, halfpatchsizewidth = DCT_PATCHWIDTH/2;\r\n    while(actualstruct)\r\n    {\r\n        actualstruct->size = size;\r\n\t\r\n        bits = (uchar**)malloc(sizeof(unsigned char*) * DCT_COEFFSIZE);\r\n        int q;\r\n        for(q = 0; q < DCT_COEFFSIZE; q++)\r\n        {\r\n            bits[q] = (unsigned char*)malloc(sizeof(unsigned char) * size);\r\n        }\r\n        actualdata = actualstruct->data;\r\n        for(r = 0; r < DCT_ROWS; r++)\r\n        {\r\n            for(p = 0; p < DCT_PATCHES + 2 + 3; p++)\r\n            {\r\n                for(ah = 0; ah < DCT_PATCHHEIGHT; ah++)\r\n                {\r\n                    actualpatch[ah] = 0.0;\r\n                    for(aw = 0; aw < DCT_PATCHWIDTH; aw++)\r\n                    {\r\n                        actualpatch[ah] += (window->window_w[aw] * actualdata[halfpatchsizeheight*r + ah][halfpatchsizewidth*p + aw]);\r\n                    }\r\n                    actualpatch[ah] = actualpatch[ah] * window->window_h[ah];\r\n                }\r\n                actualcoeff = compute_dct(actualpatch);\r\n                for(c = 0; c < DCT_COEFFSIZE; c++)\r\n                {\r\n                    dctvalues[c][p] = actualcoeff[c];\r\n                }\r\n            }\r\n            for(c = 0; c < DCT_COEFFSIZE; c++)\r\n            {\r\n                for(d = 0; d < DCT_PATCHES + 1 + 3; d++)\r\n                {\r\n                    diffs[c][d] = dctvalues[c][d + 1] - dctvalues[c][d];\r\n                }\r\n                for(d = 0; d < DCT_PATCHES; d++)\r\n                {\r\n                    if(signum(diffs[c][d + 3])==signum(diffs[c][d + 4]))\r\n                    {\r\n                        bits[c][r*DCT_PATCHES + d] = 0;\r\n                    }\r\n                    else\r\n                    {\r\n                        bits[c][r*DCT_PATCHES + d] = 1;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        if(extrabits == 1)\r\n        {\r\n            for(c = 0; c < DCT_COEFFSIZE; c++)\r\n            {\r\n                for(int e = 0; e < size - DCT_PATCHES * DCT_ROWS; e++)\r\n                {\r\n                    int randbit = rand()%10 + 1;\r\n                    if(randbit > 5)\r\n                    {\r\n                        bits[c][DCT_PATCHES * DCT_ROWS + e] = 1;\r\n                    }\r\n                    else\r\n                    {\r\n                        bits[c][DCT_PATCHES * DCT_ROWS + e] = 0;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        actualstruct->bits = bits;\r\n        actualstruct = actualstruct->next;\r\n    }\r\n    \r\n    int idx_1,i;\r\n    unsigned char *code = (unsigned char*)malloc(512*21*2 * sizeof(unsigned char));\r\n    int cnt = 0;\r\n    actualstruct = ab->bitsdata;\r\n    while(actualstruct)\r\n    {\r\n        for(i = 0; i < DCT_COEFFSIZE; i++)\r\n        {\r\n            for (idx_1 = 0; idx_1 < actualstruct->size; idx_1++)\r\n            {\r\n                code[cnt*DCT_COEFFSIZE*actualstruct->size+i*actualstruct->size + idx_1] = actualstruct->bits[i][idx_1];\r\n            }\r\n        }\r\n        cnt++;\r\n        actualstruct = actualstruct->next;\r\n    }\r\n    return code;\r\n}\r\n\r\ndouble *hann(int size, int add)\r\n{\r\n    double *hh = (double*)malloc(sizeof(double) * size + 2*add);\r\n    double *r = (double*)malloc(sizeof(double) * size);\r\n    for(int j = 0; j < size; j++) r[j] = 0.0;\r\n\r\n    int L = size + 2*add + 2;\r\n    int N = L - 1;\r\n    for(int i = 1; i <= size + 2*add ; i++)\r\n    {\r\n        hh[i-1] = (double)0.5 * (1.0 - cos(2.0*pi*(double)(i) / (double)N));\r\n    }\r\n    if(add >= 0)\r\n    {\r\n        for(int j = 0; j < size; j++)\r\n        {\r\n            r[j] = 0.0;\r\n            r[j] = hh[j + add];\r\n        }\r\n    }\r\n    else\r\n    {\r\n        for(int i = 0; i < size; i++)\r\n        {\r\n            r[i] = (double)0.0;\r\n        }\r\n\r\n        for(int k = -add; k < size + add; k++)\r\n        {\r\n            r[k] = hh[k + add];\r\n        }\r\n    }\r\n    return r;\r\n}\r\n\r\nstruct window_functions  *compute_window()\r\n{\r\n    struct window_functions *we  = (window_functions*)malloc(sizeof(struct window_functions));\r\n    we->sizeh = DCT_PATCHHEIGHT + DCT_WNDHEIGHT;\r\n    we->sizew = DCT_PATCHWIDTH + DCT_WNDWIDTH;\r\n    we->window_h = hann(DCT_PATCHHEIGHT , DCT_WNDHEIGHT);\r\n    we->window_w = hann(DCT_PATCHWIDTH , DCT_WNDWIDTH);\r\n    return we;\r\n}\r\n\r\nvoid freeall()\r\n{\r\n    struct b_d *actualstruct = ab->bitsdata, *next;\r\n    unsigned char **actualdata;\r\n    unsigned char **actualbits;\r\n    while(actualstruct)\r\n    {\r\n        actualdata = actualstruct->data;\r\n        actualbits = actualstruct->bits;\r\n        next = actualstruct->next;\r\n        free(actualdata);\r\n        free(actualbits);\r\n        free(actualstruct);\r\n        actualstruct = next;\r\n    }\r\n    free(ab);\r\n    free(window);\r\n}\r\n\r\n/*\r\n * The Monro feature extraction algorithm\r\n *\r\n * code: Code matrix\r\n * texture: texture matrix\r\n */\r\nvoid featureExtract(Mat& code, const Mat& texture)\r\n{\r\n    /*truncate to size*/\r\n    unsigned char **temp;\r\n    uchar* features;\r\n    uchar* iris_code = code.data;\r\n    \r\n    //imagei = img;\r\n    temp = truncate_image(texture);\r\n    /*shift image by degree x*/\r\n    data = shift_image(temp);\r\n    /*rotates the image to the left and to the right and store in struct*/\r\n    rotate_image();\r\n    /*compute windowfunction*/\r\n    window = compute_window();\r\n    \r\n    /*generates the codes for the 7 shifted images*/\r\n    features = generate_codes();\r\n    \r\n    for (int i=0; i < texture.cols*(texture.rows/3)*2; i++)\r\n    {\r\n\t\tif (features[i] == 0) setBitTo0(iris_code,i);\r\n\t\telse setBitTo1(iris_code,i);\r\n    }\r\n    //freeall();\r\n}\r\n\r\n/** ------------------------------- commandline functions ------------------------------- **/\r\n\r\n/**\r\n * Parses a command line\r\n * This routine should be called for parsing command lines for executables.\r\n * Note, that all options require '-' as prefix and may contain an arbitrary\r\n * number of optional arguments.\r\n *\r\n * cmd: commandline representation\r\n * argc: number of parameters\r\n * argv: string array of argument values\r\n */\r\nvoid cmdRead(map<string ,vector<string> >& cmd, int argc, char *argv[]){\r\n\tfor (int i=1; i< argc; i++){\r\n\t\tchar * argument = argv[i];\r\n\t\tif (strlen(argument) > 1 && argument[0] == '-' && (argument[1] < '0' || argument[1] > '9')){\r\n\t\t\tcmd[argument]; // insert\r\n\t\t\tchar * argument2;\r\n\t\t\twhile (i + 1 < argc && (strlen(argument2 = argv[i+1]) <= 1 || argument2[0] != '-'  || (argument2[1] >= '0' && argument2[1] <= '9'))){\r\n\t\t\t\tcmd[argument].push_back(argument2);\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tCV_Error(CV_StsBadArg,\"Invalid command line format\");\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Checks, if each command line option is valid, i.e. exists in the options array\r\n *\r\n * cmd: commandline representation\r\n * validOptions: list of valid options separated by pipe (i.e. |) character\r\n */\r\nvoid cmdCheckOpts(map<string ,vector<string> >& cmd, const string validOptions){\r\n\tvector<string> tokens;\r\n\tconst string delimiters = \"|\";\r\n\tstring::size_type lastPos = validOptions.find_first_not_of(delimiters,0); // skip delimiters at beginning\r\n\tstring::size_type pos = validOptions.find_first_of(delimiters, lastPos); // find first non-delimiter\r\n\twhile (string::npos != pos || string::npos != lastPos){\r\n\t\ttokens.push_back(validOptions.substr(lastPos,pos - lastPos)); // add found token to vector\r\n\t\tlastPos = validOptions.find_first_not_of(delimiters,pos); // skip delimiters\r\n\t\tpos = validOptions.find_first_of(delimiters,lastPos); // find next non-delimiter\r\n\t}\r\n\tsort(tokens.begin(), tokens.end());\r\n\tfor (map<string, vector<string> >::iterator it = cmd.begin(); it != cmd.end(); it++){\r\n\t\tif (!binary_search(tokens.begin(),tokens.end(),it->first)){\r\n\t\t\tCV_Error(CV_StsBadArg,\"Command line parameter '\" + it->first + \"' not allowed.\");\r\n\t\t\ttokens.clear();\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\ttokens.clear();\r\n}\r\n\r\n/*\r\n * Checks, if a specific required option exists in the command line\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n */\r\nvoid cmdCheckOptExists(map<string ,vector<string> >& cmd, const string option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it == cmd.end()) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' is required, but does not exist.\");\r\n}\r\n\r\n/*\r\n * Checks, if a specific option has the appropriate number of parameters\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n * size: appropriate number of parameters for the option\r\n */\r\nvoid cmdCheckOptSize(map<string ,vector<string> >& cmd, const string option, const unsigned int size = 1){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it->second.size() != size) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' has unexpected size.\");\r\n}\r\n\r\n/*\r\n * Checks, if a specific option has the appropriate number of parameters\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n * min: minimum appropriate number of parameters for the option\r\n * max: maximum appropriate number of parameters for the option\r\n */\r\nvoid cmdCheckOptRange(map<string ,vector<string> >& cmd, string option, unsigned int min = 0, unsigned int max = 1){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tunsigned int size = it->second.size();\r\n\tif (size < min || size > max) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' is out of range.\");\r\n}\r\n\r\n/*\r\n * Returns the list of parameters for a given option\r\n *\r\n * cmd: commandline representation\r\n * option: name of the option\r\n */\r\nvector<string> * cmdGetOpt(map<string ,vector<string> >& cmd, const string option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\treturn (it != cmd.end()) ? &(it->second) : 0;\r\n}\r\n\r\n/*\r\n * Returns number of parameters in an option\r\n *\r\n * cmd: commandline representation\r\n * option: name of the option\r\n */\r\nunsigned int cmdSizePars(map<string ,vector<string> >& cmd, const string option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\treturn (it != cmd.end()) ? it->second.size() : 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (int) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nint cmdGetParInt(map<string ,vector<string> >& cmd, string option, unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn atoi(it->second[param].c_str());\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (float) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nfloat cmdGetParFloat(map<string ,vector<string> >& cmd, const string option, const unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn atof(it->second[param].c_str());\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (string) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nstring cmdGetPar(map<string ,vector<string> >& cmd, const string option, const unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn it->second[param];\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/** ------------------------------- timing functions ------------------------------- **/\r\n\r\n/**\r\n * Class for handling timing progress information\r\n */\r\nclass Timing{\r\npublic:\r\n\t/** integer indicating progress with respect tot total **/\r\n\tint progress;\r\n\t/** total count for progress **/\r\n\tint total;\r\n\r\n\t/*\r\n\t * Default constructor for timing initializing time.\r\n\t * Automatically calls init()\r\n\t *\r\n\t * seconds: update interval in seconds\r\n\t * eraseMode: if true, outputs sends erase characters at each print command\r\n\t */\r\n\tTiming(long seconds, bool eraseMode){\r\n\t\tupdateInterval = seconds;\r\n\t\tprogress = 1;\r\n\t\ttotal = 100;\r\n\t\teraseCount=0;\r\n\t\terase = eraseMode;\r\n\t\tinit();\r\n\t}\r\n\r\n\t/*\r\n\t * Destructor\r\n\t */\r\n\t~Timing(){}\r\n\r\n\t/*\r\n\t * Initializes timing variables\r\n\t */\r\n\tvoid init(void){\r\n\t\tstart = boost::posix_time::microsec_clock::universal_time();\r\n\t\tlastPrint = start - boost::posix_time::seconds(updateInterval);\r\n\t}\r\n\r\n\t/*\r\n\t * Clears printing (for erase option only)\r\n\t */\r\n\tvoid clear(void){\r\n\t\tstring erase(eraseCount,'\\r');\r\n\t\terase.append(eraseCount,' ');\r\n\t\terase.append(eraseCount,'\\r');\r\n\t\tprintf(\"%s\",erase.c_str());\r\n\t\teraseCount = 0;\r\n\t}\r\n\r\n\t/*\r\n\t * Updates current time and returns true, if output should be printed\r\n\t */\r\n\tbool update(void){\r\n\t\tcurrent = boost::posix_time::microsec_clock::universal_time();\r\n\t\treturn ((current - lastPrint > boost::posix_time::seconds(updateInterval)) || (progress == total));\r\n\t}\r\n\r\n\t/*\r\n\t * Prints timing object to STDOUT\r\n\t */\r\n\tvoid print(void){\r\n\t\tlastPrint = current;\r\n\t\tfloat percent = 100.f * progress / total;\r\n\t\tboost::posix_time::time_duration passed = (current - start);\r\n\t\tboost::posix_time::time_duration togo = passed * (total - progress) / max(1,progress);\r\n\t\tif (erase) {\r\n\t\t\tstring erase(eraseCount,'\\r');\r\n\t\t\tprintf(\"%s\",erase.c_str());\r\n\t\t\tint newEraseCount = (progress != total) ? printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03i Remaining ca. %i:%02i:%02i.%03i)\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000),togo.hours(),togo.minutes(),togo.seconds(),(int)(togo.total_milliseconds() % 1000)) : printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03d)\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000));\r\n\t\t\tif (newEraseCount < eraseCount) {\r\n\t\t\t\tstring erase(newEraseCount-eraseCount,' ');\r\n\t\t\t\terase.append(newEraseCount-eraseCount,'\\r');\r\n\t\t\t\tprintf(\"%s\",erase.c_str());\r\n\t\t\t}\r\n\t\t\teraseCount = newEraseCount;\r\n\t\t}\r\n\t\telse {\r\n\t\t\teraseCount = (progress != total) ? printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03i Remaining ca. %i:%02i:%02i.%03i)\\n\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000),togo.hours(),togo.minutes(),togo.seconds(),(int)(togo.total_milliseconds() % 1000)) : printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03d)\\n\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000));\r\n\t\t}\r\n\t}\r\nprivate:\r\n\tlong updateInterval;\r\n\tboost::posix_time::ptime start;\r\n\tboost::posix_time::ptime current;\r\n\tboost::posix_time::ptime lastPrint;\r\n\tint eraseCount;\r\n\tbool erase;\r\n};\r\n\r\n/** ------------------------------- file pattern matching functions ------------------------------- **/\r\n\r\n\r\n/*\r\n * Formats a given string, such that it can be used as a regular expression\r\n * I.e. escapes special characters and uses * and ? as wildcards\r\n *\r\n * pattern: regular expression path pattern\r\n * pos: substring starting index\r\n * n: substring size\r\n *\r\n * returning: escaped substring\r\n */\r\nstring patternSubstrRegex(string& pattern, size_t pos, size_t n){\r\n\tstring result;\r\n\tfor (size_t i=pos, e=pos+n; i < e; i++ ) {\r\n\t\tchar c = pattern[i];\r\n\t\tif ( c == '\\\\' || c == '.' || c == '+' || c == '[' || c == '{' || c == '|' || c == '(' || c == ')' || c == '^' || c == '$' || c == '}' || c == ']') {\r\n\t\t\tresult.append(1,'\\\\');\r\n\t\t\tresult.append(1,c);\r\n\t\t}\r\n\t\telse if (c == '*'){\r\n\t\t\tresult.append(\"([^/\\\\\\\\]*)\");\r\n\t\t}\r\n\t\telse if (c == '?'){\r\n\t\t\tresult.append(\"([^/\\\\\\\\])\");\r\n\t\t}\r\n\t\telse {\r\n\t\t\tresult.append(1,c);\r\n\t\t}\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n/*\r\n * Converts a regular expression path pattern into a list of files matching with this pattern by replacing wildcards\r\n * starting in position pos assuming that all prior wildcards have been resolved yielding intermediate directory path.\r\n * I.e. this function appends the files in the specified path according to yet unresolved pattern by recursive calling.\r\n *\r\n * pattern: regular expression path pattern\r\n * files: the list to which new files can be applied\r\n * pos: an index such that positions 0...pos-1 of pattern are already considered/matched yielding path\r\n * path: the current directory (or empty)\r\n */\r\nvoid patternToFiles(string& pattern, vector<string>& files, const size_t& pos, const string& path){\r\n\tsize_t first_unknown = pattern.find_first_of(\"*?\",pos); // find unknown * in pattern\r\n\tif (first_unknown != string::npos){\r\n\t\tsize_t last_dirpath = pattern.find_last_of(\"/\\\\\",first_unknown);\r\n\t\tsize_t next_dirpath = pattern.find_first_of(\"/\\\\\",first_unknown);\r\n\t\tif (next_dirpath != string::npos){\r\n\t\t\tboost::regex expr((last_dirpath != string::npos && last_dirpath > pos) ? patternSubstrRegex(pattern,last_dirpath+1,next_dirpath-last_dirpath-1) : patternSubstrRegex(pattern,pos,next_dirpath-pos));\r\n\t\t\tboost::filesystem::directory_iterator end_itr; // default construction yields past-the-end\r\n\t\t\ttry {\r\n\t\t\t\tfor ( boost::filesystem::directory_iterator itr( ((path.length() > 0) ? path + pattern[pos-1] : (last_dirpath != string::npos && last_dirpath > pos) ? \"\" : \"./\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) : \"\")); itr != end_itr; ++itr )\r\n\t\t\t\t{\r\n\t\t\t\t\tif (boost::filesystem::is_directory(itr->path())){\r\n\t\t\t\t\t\tboost::filesystem::path p = itr->path().filename();\r\n\t\t\t\t\t\tstring s =  p.string();\r\n\t\t\t\t\t\tif (boost::regex_match(s.c_str(), expr)){\r\n\t\t\t\t\t\t\tpatternToFiles(pattern,files,(int)(next_dirpath+1),((path.length() > 0) ? path + pattern[pos-1] : \"\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) + pattern[last_dirpath] : \"\") + s);\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}\r\n\t\t\tcatch (boost::filesystem::filesystem_error &e){}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tboost::regex expr((last_dirpath != string::npos && last_dirpath > pos) ? patternSubstrRegex(pattern,last_dirpath+1,pattern.length()-last_dirpath-1) : patternSubstrRegex(pattern,pos,pattern.length()-pos));\r\n\t\t\tboost::filesystem::directory_iterator end_itr; // default construction yields past-the-end\r\n\t\t\ttry {\r\n\t\t\t\tfor ( boost::filesystem::directory_iterator itr(((path.length() > 0) ? path +  pattern[pos-1] : (last_dirpath != string::npos && last_dirpath > pos) ? \"\" : \"./\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) : \"\")); itr != end_itr; ++itr )\r\n\t\t\t\t{\r\n\t\t\t\t\tboost::filesystem::path p = itr->path().filename();\r\n\t\t\t\t\tstring s =  p.string();\r\n\t\t\t\t\tif (boost::regex_match(s.c_str(), expr)){\r\n\t\t\t\t\t\tfiles.push_back(((path.length() > 0) ? path + pattern[pos-1] : \"\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) + pattern[last_dirpath] : \"\") + s);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch (boost::filesystem::filesystem_error &e){}\r\n\t\t}\r\n\t}\r\n\telse { // no unknown symbols\r\n\t\tboost::filesystem::path file(((path.length() > 0) ? path + \"/\" : \"\") + pattern.substr(pos,pattern.length()-pos));\r\n\t\tif (boost::filesystem::exists(file)){\r\n\t\t\tfiles.push_back(file.string());\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Converts a regular expression path pattern into a list of files matching with this pattern\r\n *\r\n * pattern: regular expression path pattern\r\n * files: the list to which new files can be applied\r\n */\r\nvoid patternToFiles(string& pattern, vector<string>& files){\r\n\tpatternToFiles(pattern,files,0,\"\");\r\n}\r\n\r\n/*\r\n * Renames a given filename corresponding to the actual file pattern using a renaming pattern.\r\n * Wildcards can be referred to as ?1, ?2, ... in the order they appeared in the file pattern.\r\n *\r\n * pattern: regular expression path pattern\r\n * renamePattern: renaming pattern using ?1, ?2, ... as placeholders for wildcards\r\n * infile: path of the file (matching with pattern) to be renamed\r\n * outfile: path of the renamed file\r\n * par: used parameter (default: '?')\r\n */\r\nvoid patternFileRename(string& pattern, const string& renamePattern, const string& infile, string& outfile, const char par = '?'){\r\n\tsize_t first_unknown = renamePattern.find_first_of(par,0); // find unknown ? in renamePattern\r\n\tif (first_unknown != string::npos){\r\n\t\tstring formatOut = \"\";\r\n\t\tfor (size_t i=0, e=renamePattern.length(); i < e; i++ ) {\r\n\t\t\tchar c = renamePattern[i];\r\n\t\t\tif ( c == par && i+1 < e) {\r\n\t\t\t\tc = renamePattern[i+1];\r\n\t\t\t\tif (c > '0' && c <= '9'){\r\n\t\t\t\t\tformatOut.append(1,'$');\r\n\t\t\t\t\tformatOut.append(1,c);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tformatOut.append(1,par);\r\n\t\t\t\t\tformatOut.append(1,c);\r\n\t\t\t\t}\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tformatOut.append(1,c);\r\n\t\t\t}\r\n\t\t}\r\n\t\tboost::regex patternOut(patternSubstrRegex(pattern,0,pattern.length()));\r\n\t\toutfile = boost::regex_replace(infile,patternOut,formatOut,boost::match_default | boost::format_perl);\r\n\t} else {\r\n\t\toutfile = renamePattern;\r\n\t}\r\n}\r\n\r\n/** ------------------------------- Program ------------------------------- **/\r\n\r\n/*\r\n * Main program\r\n */\r\nint main(int argc, char *argv[])\r\n{\r\n\tint mode = MODE_HELP;\r\n\tmap<string,vector<string> > cmd;\r\n\ttry {\r\n\t\tcmdRead(cmd,argc,argv);\r\n    \tif (cmd.size() == 0 || cmdGetOpt(cmd,\"-h\") != 0) mode = MODE_HELP;\r\n    \telse mode = MODE_MAIN;\r\n    \tif (mode == MODE_MAIN){\r\n\t\t\t// validate command line\r\n\t\t\tcmdCheckOpts(cmd,\"-i|-o|-q|-t\");\r\n\t\t\tcmdCheckOptExists(cmd,\"-i\");\r\n\t\t\tcmdCheckOptSize(cmd,\"-i\",1);\r\n\t\t\tstring inFiles = cmdGetPar(cmd,\"-i\");\r\n\t\t\tcmdCheckOptExists(cmd,\"-o\");\r\n\t\t\tcmdCheckOptSize(cmd,\"-o\",1);\r\n\t\t\tstring outFiles = cmdGetPar(cmd,\"-o\");\r\n\t\t\tstring imaskFiles, omaskFiles;\r\n\t\t\tbool quiet = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-q\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-q\",0);\r\n\t\t\t\tquiet = true;\r\n\t\t\t}\r\n\t\t\tbool time = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-t\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-t\",0);\r\n\t\t\t\ttime = true;\r\n\t\t\t}\r\n\t\t\t// starting routine\r\n\t\t\tTiming timing(1,quiet);\r\n\t\t\tvector<string> files;\r\n\t\t\tpatternToFiles(inFiles,files);\r\n\t\t\tCV_Assert(files.size() > 0);\r\n\t\t\ttiming.total = files.size();\r\n\t\t\tfor (vector<string>::iterator inFile = files.begin(); inFile != files.end(); ++inFile, timing.progress++){\r\n\t\t\t\tif (!quiet) printf(\"Loading texture '%s' ...\\n\", (*inFile).c_str());;\r\n\t\t\t\tMat img = imread(*inFile, CV_LOAD_IMAGE_GRAYSCALE);\r\n\t\t\t\tCV_Assert(img.data != 0);\r\n\t\t\t\tMat out;\r\n\t\t\t\tint w = img.cols;\r\n\t\t\t\tint h = (img.rows/DCT_COEFFSIZE)*2;\r\n\t\t\t\tif (!quiet) printf(\"Creating %d x %d iris-code ...\\n\", w, h);\r\n\t\t\t\tMat code (1,(w*h)/8,CV_8UC1);\r\n\t\t\t\tcode.setTo(0);\r\n\t\t\t\tfeatureExtract(code, img);\r\n\t\t\t\tout = code;\r\n\t\t\t\tstring outfile;\r\n\t\t\t\tpatternFileRename(inFiles,outFiles,*inFile,outfile);\r\n\t\t\t\tif (!quiet) printf(\"Storing code '%s' ...\\n\", outfile.c_str());\r\n\t\t\t\tif (!imwrite(outfile,out)) CV_Error(CV_StsError,\"Could not save image '\" + outfile + \"'\");\r\n\t\t\t\tif (time && timing.update()) timing.print();\r\n\t\t\t}\r\n\t\t\tif (time && quiet) timing.clear();\r\n    \t}\r\n    \telse if (mode == MODE_HELP){\r\n\t\t\t// validate command line\r\n\t\t\tcmdCheckOpts(cmd,\"-h\");\r\n\t\t\tif (cmdGetOpt(cmd,\"-h\") != 0) cmdCheckOptSize(cmd,\"-h\",0);\r\n\t\t\t// starting routine\r\n\t\t\tprintUsage();\r\n    \t}\r\n    }\r\n\tcatch (...){\r\n\t   \tprintf(\"Exit with errors.\\n\");\r\n\t   \texit(EXIT_FAILURE);\r\n\t}\r\n    return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "7fc25ad1da4de9c47babfaa666338479da64dbda", "size": 39378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TFM/USITv1.0.3/dct.cpp", "max_stars_repo_name": "jmanday/Master", "max_stars_repo_head_hexsha": "388ee71d04a3fb1f64ed4b2d1164f1b5ec45179f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-03-21T17:57:22.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-21T17:57:22.000Z", "max_issues_repo_path": "TFM/USITv1.0.3/dct.cpp", "max_issues_repo_name": "jmanday/Master", "max_issues_repo_head_hexsha": "388ee71d04a3fb1f64ed4b2d1164f1b5ec45179f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2016-10-16T19:42:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-14T21:29:48.000Z", "max_forks_repo_path": "TFM/USITv1.0.3/dct.cpp", "max_forks_repo_name": "jmanday/Master", "max_forks_repo_head_hexsha": "388ee71d04a3fb1f64ed4b2d1164f1b5ec45179f", "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.7907869482, "max_line_length": 513, "alphanum_fraction": 0.5314642694, "num_tokens": 11752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.7025300449389325, "lm_q1q2_score": 0.547968447267566}}
{"text": "#ifndef KOOPMAN_OPERATOR_HPP\n#define KOOPMAN_OPERATOR_HPP\n\n#include <armadillo>\n#include \"../system.hpp\"\n#include \"basis_functions/basis_template.hpp\"\n#include <math.h>\n\n\nclass KoopmanOperator : public System\n{\n\nprivate:\n    arma::mat _A;\n    arma::mat _G;\n    arma::mat _Ktrans;\npublic:\n    arma::mat _K;\n    arma::mat _Kx;\n    arma::mat _Ku;\n\n    int _nK;\n    int _nM;\n    int _nX;\n    int _nU;\n    int _nKU;\n\n    Basis* basis;\n\n    KoopmanOperator(Basis* _basis) : System(_basis->_nX, _basis->_nU) {\n        basis = _basis;\n        _nK = basis->_nK;\n        _nX = basis->_nX;\n        _nU = basis->_nU;\n        _nM = basis->_nM;\n        _nKU = basis->_nKU;\n        _A = arma::zeros<arma::mat>(_nK, _nK);\n        _G = arma::zeros<arma::mat>(_nK, _nK);\n        _K = arma::zeros<arma::mat>(_nK, _nK);\n        _Kx = 0.1*arma::ones<arma::mat>(_nX, _nX);\n        _Ku = 0.1*arma::ones<arma::mat>(_nX, _nKU);\n\n        _Ktrans = _K.t();\n    }\n\n    inline arma::vec f(const arma::vec& x, const arma::vec& u) {\n        if (x.n_rows < _nX) {\n            return _Kx * basis->fkx(x) + _Ku * basis->fku(x, u);\n        } else {\n            arma::vec fkx = basis->fkx(x.head_rows(_nM));\n            arma::vec fku = basis->fku(x.head_rows(_nM), u);\n            return _Kx * fkx + _Ku * fku;\n        }\n    }\n\n\n    inline arma::mat fdx(const arma::vec& x, const arma::vec& u) {\n        return _Kx;\n    }\n    inline arma::mat fdu(const arma::vec& x, const arma::vec& u) {\n        return _Ku * basis->fkudu(x.head_rows(_nM), u);\n    }\n\n    void gradStep(const arma::vec& dataIn, const arma::vec& hdataIn, const arma::vec& dataOut, const arma::vec& hdataOut) {\n\n        arma::vec phix = basis->fk(dataIn, hdataIn);\n        arma::vec phixpo = basis->fk(dataOut, hdataOut);\n\n        _G += phix * phix.t();\n        _A += phix * phixpo.t();\n\n        try {\n            _K = arma::pinv(_G) * _A;\n            _Ktrans = _K.t();\n            _Kx = _Ktrans.submat(0, 0, _nX-1, _nX-1);\n            _Ku = _Ktrans.submat(0, _nX, _nX-1, _nX + _nKU - 1);\n        } catch (std::runtime_error& e) {\n            std::cout << \"CAUGHT ERROR\" << std::endl;\n        }\n\n    }\n\n    void computeOperator() {\n      try {\n            _K = arma::pinv(_G) * _A;\n            _Ktrans = _K.t();\n            _Kx = _Ktrans.submat(0, 0, _nX-1, _nX-1);\n            _Ku = _Ktrans.submat(0, _nX, _nX-1, _nX + _nKU - 1);\n        } catch (std::runtime_error& e) {\n            std::cout << \"CAUGHT ERROR\" << std::endl;\n        }\n    }\n\n    void saveOperator(std::string filePath) {\n      _Ktrans.save(filePath + \".csv\", arma::raw_ascii);\n      _Ktrans.save(filePath + \".bin\");\n    }\n\n    void loadOperator(std::string filePath) {\n      _Ktrans.load(filePath);\n      _K = _Ktrans.t();\n      _Kx = _Ktrans.submat(0, 0 ,_nX-1, _nX-1);\n      _Ku = _Ktrans.submat(0, _nX, _nX-1, _nX + _nKU-1);\n      std::cout << \"Loaded Koopman Operator.\" << std::endl;\n    }\n\n    void showOperator() {\n        std::cout << _K.t() << std::endl;\n    }\n};\n\n\n#endif\n", "meta": {"hexsha": "abc64865c30cc1ab8f4a901406b87f219de31dfa", "size": 2979, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/model_based_shared_control/src/robotlib/dynamicalSystems/koopman/koopman_operator.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/koopman_operator.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/koopman_operator.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": 26.1315789474, "max_line_length": 123, "alphanum_fraction": 0.5280295401, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5479519364625052}}
{"text": "#include <iostream>\n#include <math.h>\n#include <Eigen/Dense>\nusing Eigen::Matrix;\n\nfloat dt;\nfloat vicon_R;\nfloat accelerometer_R;\nfloat sigma_J;\nfloat sigma_bAcc;\n\nMatrix<float, 12, 1> x_est;\nMatrix<float, 12, 12> p_est;\nMatrix<float, 12, 1> x_prd;\nMatrix<float, 12, 12> p_prd;\nMatrix<float, 12, 12> Q;           \nMatrix<float, 3, 3> R_vicon;\nMatrix<float, 3, 3> R_acc;\nMatrix<float, 12, 12> A;\nMatrix<float, 3, 12> H_pos;\nMatrix<float, 3, 12> H_v;\nMatrix<float, 3, 12> H_acc;  //Acceleration without bias\nMatrix<float, 3, 12> H_accm; //Measured acceleration (bias added)\nMatrix<float, 3, 3> S;\nMatrix<float, 3, 12> B;\nMatrix<float, 12, 3> K;\nMatrix<float, 3, 1> y;\nMatrix<float, 3, 1> v;\nMatrix<float, 3, 1> a;\nMatrix<float, 3, 1> bAcc;\nMatrix<float, 12, 1> result;\nMatrix<float, 12, 6> Gammak;\nMatrix<float, 6, 6> Qk;\nMatrix<float, 12, 12> I_12x12;\nMatrix<float, 3, 3> I_3x3;\nMatrix<float, 3, 3> Zero_3x3;\n\n\nvoid kalman_init()\n{\n\n\tdt = 0.010;             // 100 Hz\n  sigma_J = 20;           // Jerk process noise\n  sigma_bAcc = 0.01;      // Accelerometer bias process noise\n\tvicon_R = 0.0001;       // estimated vicon standard deviation\n  accelerometer_R = 0.5; // estimated accelerometer standard deviation\n  I_12x12 = Matrix<float, 12, 12>::Identity();\n  I_3x3 = Matrix<float, 3, 3>::Identity();\n  Zero_3x3 = Matrix<float, 3, 3>::Zero(3, 3);\n  \n  Gammak << I_3x3 * (pow(dt, 3)/6), Zero_3x3,\n            I_3x3 * (pow(dt, 2)/2), Zero_3x3,\n                        I_3x3 * dt, Zero_3x3,\n                          Zero_3x3, I_3x3*dt;\n  Qk << pow(sigma_J, 2)*I_3x3,                 Zero_3x3, \n                     Zero_3x3, pow(sigma_bAcc, 2)*I_3x3; //Process noise covariance matrix\n  Q = Gammak*Qk*Gammak.transpose();\n\n\tR_vicon = pow(vicon_R, 2) * I_3x3;       // Vicon measurement covariance matrix\n  R_acc = pow(accelerometer_R, 2) * I_3x3; // Accelerometer measurement covariance matrix\n\n  A << I_3x3,    dt*I_3x3, (pow(dt,2)/2)*I_3x3, Zero_3x3,\n       Zero_3x3,    I_3x3,            dt*I_3x3, Zero_3x3,\n       Zero_3x3, Zero_3x3,               I_3x3, Zero_3x3,\n       Zero_3x3, Zero_3x3,            Zero_3x3, I_3x3;\n\n  //Initial estimate: zeros\n  x_est = Matrix<float, 12, 1>::Zero();\n\n  //Initial covariance: we assume we don't know initial position, but velocity and \n  // acceleration are close to zero. Also, we don't know the accelerometer bias\n  p_est << 10*I_3x3,     Zero_3x3,     Zero_3x3,  Zero_3x3,\n            Zero_3x3, 0.0001*I_3x3,     Zero_3x3,  Zero_3x3,\n            Zero_3x3,     Zero_3x3, 0.0001*I_3x3,  Zero_3x3,\n            Zero_3x3,     Zero_3x3,     Zero_3x3, 1000*I_3x3;\n\n  H_pos  << I_3x3,    Zero_3x3, Zero_3x3, Zero_3x3;\n  H_v    << Zero_3x3, I_3x3,    Zero_3x3, Zero_3x3;\n  H_acc  << Zero_3x3, Zero_3x3,    I_3x3, Zero_3x3; //Acceleration we want to determine\n  H_accm << Zero_3x3, Zero_3x3,    I_3x3,    I_3x3; //Measured acceleration (includes bias)\n\n\n}\n\nMatrix<float, 12, 1> kalman_propagate()\n{\n  // Predicting state and covariance\n\n  x_prd = A * x_est;\n  p_prd = A * p_est * A.transpose() + Q;\n\n  y = H_pos * x_prd; // Position estimate\n  v = H_v * x_prd;   // Velocity estimate\n  a = H_acc * x_prd; // Velocity estimate\n  bAcc = (H_accm - H_acc)*x_prd; //Bias estimate\n\n  result << y,\n            v,\n            a,\n            bAcc;\n\n  x_est = x_prd;\n  p_est = p_prd;\n\n  return result;\n\n}\n\nMatrix<float, 12, 1> kalman_estimate_pos(Matrix<float, 3, 1> z)\n{\n\n// Estimating state and covariance\n\n  S = H_pos * p_prd.transpose() * H_pos.transpose() + R_vicon;\n  B = H_pos * p_prd.transpose();\n  K = (S.inverse() * B).transpose();\n\n  x_est = x_prd + K * (z - H_pos * x_prd);\n  p_est = (I_12x12 - K * H_pos) * p_prd * (I_12x12 - K * H_pos).transpose() + K * R_vicon * K.transpose();   // Joseph form \n\n// Computing measurements\n  y = H_pos * x_est;   // Position estimate\n  v = H_v * x_est; // Velocity estimate\n  a = H_acc * x_est; // Acc estimate\n  bAcc = (H_accm - H_acc)*x_prd; //Bias estimate\n\n  result << y,\n            v,\n            a,\n            bAcc;\n\n  //These are necessary if the acceleration is updated\n  x_prd = x_est;\n  p_prd = p_est;\n\n  return result;\n}\n\n\nMatrix<float, 12, 1> kalman_estimate_acc(Matrix<float, 3, 1> z)\n{\n\n// Estimating state and covariance\n\n  S = H_accm * p_prd.transpose() * H_accm.transpose() + R_acc;\n  B = H_accm * p_prd.transpose();\n  K = (S.inverse() * B).transpose();\n\n  x_est = x_prd + K * (z - H_accm * x_prd);\n  p_est = (I_12x12 - K * H_accm) * p_prd * (I_12x12 - K * H_accm).transpose() + K * R_acc * K.transpose();   // Joseph form \n\n// Computing measurements\n  y = H_pos * x_est;   // Position estimate\n  v = H_v * x_est; // Velocity estimate\n  a = H_acc * x_est;\n  bAcc = (H_accm - H_acc)*x_prd; //Bias estimate\n\n  result << y,\n            v,\n            a,\n            bAcc;\n\n  // std::cout << x_est << std::endl << std::endl;\n  // std::cout << p_est << std::endl << std::endl;\n\n  return result;\n}\n\n\n// int main()\n// {\n\n// \tkalman_init();\n\n// \tMatrixXd z(3,1);   // measurement vector\n\n// \tz << 1,\n// \t     1,\n// \t     1;\n\n// \tstd::cout << kalman(z) << std::endl;\n\n// }", "meta": {"hexsha": "ce0b7434f0b19068661bc4ba8d6b9aeafdd2e7c0", "size": 5053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/AGNC-Lab_Quad/multithreaded/kalman.cpp", "max_stars_repo_name": "khairulislam/phys", "max_stars_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data/AGNC-Lab_Quad/multithreaded/kalman.cpp", "max_issues_repo_name": "khairulislam/phys", "max_issues_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/AGNC-Lab_Quad/multithreaded/kalman.cpp", "max_forks_repo_name": "khairulislam/phys", "max_forks_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6120218579, "max_line_length": 124, "alphanum_fraction": 0.6024144073, "num_tokens": 1874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5479519296855452}}
{"text": "#include <iostream>\n#include <cassert>\n#include <vector>\n#include <deque>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_data_structure_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Triangulation_face_base_2.h>\n#include <boost/graph/adjacency_list.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> TVB;\ntypedef CGAL::Triangulation_face_base_2<K> TFB;\ntypedef CGAL::Triangulation_data_structure_2<TVB, TFB> TriangulationDataStructure;\ntypedef CGAL::Delaunay_triangulation_2<K, TriangulationDataStructure> Triangulation;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph;\n\nK::Point_2 read_point()\n{\n  int x, y;\n  std::cin >> x >> y;\n  assert(abs(x) < (1 << 24) && abs(y) < (1 << 24));\n  return K::Point_2(x, y);\n}\n\ninline Triangulation::Vertex_handle vertex_from_edge(Triangulation::Edge &edge, int i)\n{\n  assert(i == 0 || i == 1);\n  return edge.first->vertex((edge.second + 1 + i) % 3);\n}\n\ninline Triangulation::Vertex_handle other_vertex_from_edge(Triangulation::Edge &edge, Triangulation::Vertex_handle &v)\n{\n  auto vertex_a = vertex_from_edge(edge, 0);\n  auto vertex_b = vertex_from_edge(edge, 1);\n  if (vertex_a == v)\n  {\n    return vertex_b;\n  }\n  else if (vertex_b == v)\n  {\n    return vertex_a;\n  }\n  assert(false);\n  __builtin_unreachable();\n}\n\nstruct NetworkAnalysis\n{\n  NetworkAnalysis(int n) : valid(false), component_map(n, -1){};\n\n  bool valid;\n  std::vector<int> component_map;\n};\n\nNetworkAnalysis analyze_network(std::vector<std::pair<K::Point_2, int>> radio_stations, Triangulation &all_stations_triangulation, std::function<bool(double)> is_close_enough)\n{\n  const int n = radio_stations.size();\n  NetworkAnalysis network_analysis(n);\n\n  std::vector<Triangulation::Vertex_handle> all_stations_triangulation_handles(n);\n  for (auto it = all_stations_triangulation.finite_vertices_begin(); it != all_stations_triangulation.finite_vertices_end(); it++)\n  {\n    all_stations_triangulation_handles.at(it->info()) = it;\n  }\n\n  std::deque<std::pair<int, int>> queue;\n  std::vector<int> color_by_station(n, -1);\n  int next_connected_component = 0;\n  for (int queue_starter = 0; queue_starter < n; queue_starter++)\n  {\n    if (network_analysis.component_map.at(queue_starter) >= 0)\n    {\n      continue;\n    }\n    queue.push_back(std::make_pair(queue_starter, 0));\n    const int this_connected_component = next_connected_component++;\n    network_analysis.component_map.at(queue_starter) = this_connected_component;\n\n    while (!queue.empty())\n    {\n      int prev_index = queue.front().first;\n      int prev_color = queue.front().second;\n      queue.pop_front();\n      K::Point_2 &prev_point = radio_stations.at(prev_index).first;\n\n      assert(color_by_station.at(prev_index) == -1);\n      color_by_station.at(prev_index) = prev_color;\n\n      auto &prev_vertex = all_stations_triangulation_handles.at(prev_index);\n      Triangulation::Edge_circulator c = all_stations_triangulation.incident_edges(prev_vertex);\n      do\n      {\n        if (all_stations_triangulation.is_infinite(c))\n        {\n          continue;\n        }\n\n        auto next_vertex = other_vertex_from_edge(*c, prev_vertex);\n        int next_index = next_vertex->info();\n        K::Point_2 &next_point = next_vertex->point();\n        int next_color = 1 - prev_color;\n\n        if (network_analysis.component_map.at(next_index) == -1 && is_close_enough(CGAL::squared_distance(prev_point, next_point)))\n        {\n          network_analysis.component_map.at(next_index) = this_connected_component;\n          queue.push_front(std::make_pair(next_index, next_color));\n        }\n      } while (++c != all_stations_triangulation.incident_edges(prev_vertex));\n    }\n  }\n\n  assert(*std::min_element(network_analysis.component_map.begin(), network_analysis.component_map.end()) >= 0);\n\n  std::vector<std::vector<K::Point_2>> point_vectors_by_color(2);\n  for (int i = 0; i < n; i++)\n  {\n    int color = color_by_station.at(i);\n    point_vectors_by_color.at(color).push_back(radio_stations.at(i).first);\n  }\n\n  for (auto &points_this_color : point_vectors_by_color)\n  {\n    Triangulation color_triangulation;\n    color_triangulation.insert(points_this_color.begin(), points_this_color.end());\n    for (auto it = color_triangulation.finite_edges_begin(); it != color_triangulation.finite_edges_end(); it++)\n    {\n      if (is_close_enough(color_triangulation.segment(it).squared_length()))\n      {\n        return network_analysis;\n      }\n    }\n  }\n\n  network_analysis.valid = true;\n  return network_analysis;\n}\n\nvoid testcase()\n{\n  int n, m, r;\n  std::cin >> n >> m >> r;\n  assert(n >= 1 && n <= 9e4 && m >= 1 && m <= 9e4 && r > 0 && r < (1 << 24));\n\n  const double r_squared = pow(double(r), 2);\n  const auto is_close_enough = [r_squared](double sqlen) { return sqlen <= r_squared; };\n\n  std::vector<std::pair<K::Point_2, int>> radio_stations;\n  for (int i = 0; i < n; i++)\n  {\n    radio_stations.push_back(std::make_pair(read_point(), i));\n  }\n\n  std::vector<std::pair<K::Point_2, K::Point_2>> clues;\n  for (int i = 0; i < m; i++)\n  {\n    auto p1 = read_point();\n    auto p2 = read_point();\n    clues.push_back(std::make_pair(p1, p2));\n  }\n\n  Triangulation all_stations_triangulation;\n  all_stations_triangulation.insert(radio_stations.begin(), radio_stations.end());\n\n  NetworkAnalysis network_analysis = analyze_network(radio_stations, all_stations_triangulation, is_close_enough);\n  DEBUG(2, \"network_analysis.valid \" << network_analysis.valid);\n\n  const auto network_component_from_radio_set = [&is_close_enough, &all_stations_triangulation, &network_analysis](K::Point_2 &radio_set) -> int {\n    auto nearest_station = all_stations_triangulation.nearest_vertex(radio_set);\n    double set_station_sq_dist = CGAL::squared_distance(radio_set, nearest_station->point());\n    if (!is_close_enough(set_station_sq_dist))\n    {\n      return -1;\n    }\n    return network_analysis.component_map.at(nearest_station->info());\n  };\n\n  std::vector<bool> can_transmit_by_clue(m, false);\n  if (network_analysis.valid)\n  {\n    for (int i = 0; i < m; i++)\n    {\n      DEBUG(3, \"clue \" << i);\n      auto &clue = clues.at(i);\n      if (is_close_enough(CGAL::squared_distance(clue.first, clue.second)))\n      {\n        can_transmit_by_clue.at(i) = true;\n      }\n      else\n      {\n        int first_component = network_component_from_radio_set(clue.first);\n        if (first_component >= 0 && first_component == network_component_from_radio_set(clue.second))\n        {\n          can_transmit_by_clue.at(i) = true;\n        }\n      }\n    }\n  }\n\n  for (bool can_transmit : can_transmit_by_clue)\n  {\n    std::cout << (can_transmit ? \"y\" : \"n\");\n  }\n  std::cout << \"\\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": "24fc66112695247e83473c48ceb62a5b56f9c24c", "size": 7169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-08/clues/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-08/clues/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-08/clues/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": 31.4429824561, "max_line_length": 175, "alphanum_fraction": 0.6858697168, "num_tokens": 1935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5479519279913051}}
{"text": "#include \"acceleration/two_grid/spectral_shape/spectral_shape.hpp\"\n\n#include <deal.II/lac/petsc_full_matrix.h>\n#include <numeric>\n\n#include \"solver/eigenvalue/tests/spectral_radius_mock.hpp\"\n#include \"test_helpers/gmock_wrapper.h\"\n#include \"test_helpers/test_helper_functions.h\"\n\nnamespace  {\n\nusing namespace bart;\nusing ::testing::Return, ::testing::ResultOf, ::testing::ContainerEq, ::testing::Pointwise, ::testing::DoubleNear;\n\nclass CalculatorTwoGridSpectralShapeTest : public ::testing::Test {\n public:\n  using Matrix = dealii::FullMatrix<double>;\n  using PETScFullMatrix = dealii::PETScWrappers::FullMatrix;\n  using EigenvalueSolver = solver::eigenvalue::SpectralRadiusMock;\n  using MatrixValues = std::vector<std::vector<double>>;\n  using TestClass = acceleration::two_grid::spectral_shape::SpectralShape;\n\n  // Test object\n  std::unique_ptr<TestClass> test_class_{ nullptr };\n\n  // Supporting objects\n  Matrix sigma_t, sigma_s;\n  PETScFullMatrix expected_a;\n\n  // Supporting mocks and observation pointers\n  EigenvalueSolver* eigenvalue_solver_obs_ptr_{ nullptr };\n\n\n  // test parameters\n  const MatrixValues expected_a_values{{0, 1.0/4.0, 1.0/2.0}, {0, 1.0/20.0, 7.0/10.0}, {0, 13.0/120.0, 31.0/60.0}};\n  static constexpr int n_groups{ 3 };\n  const double eigenvalue_{ test_helpers::RandomDouble(-100, 100) };\n  std::vector<double> eigenvector_;\n  std::vector<double> spectral_shape_function_;\n\n  auto SetUp() -> void override;\n};\n\nauto CalculatorTwoGridSpectralShapeTest::SetUp() -> void {\n\n  const MatrixValues sigma_t_values{{7, 0, 0}, {0, 10, 0}, {0, 0, 13}};\n  const MatrixValues sigma_s_values{{3, 1, 2}, {1, 5, 3}, {2, 3, 7}};\n\n  sigma_t.reinit(n_groups, n_groups);\n  sigma_s.reinit(n_groups, n_groups);\n  expected_a.reinit(n_groups, n_groups);\n\n  for (int i = 0; i < n_groups; ++i) {\n    for (int j = 0; j < n_groups; ++j) {\n      sigma_t.set(i, j, sigma_t_values.at(i).at(j));\n      sigma_s.set(i, j, sigma_s_values.at(i).at(j));\n      expected_a.set(i, j, expected_a_values.at(i).at(j));\n    }\n  }\n  // The eigenvector will be returned normalized in the L2 norm\n  eigenvector_ = test_helpers::RandomVector(n_groups, 0, 100);\n\n  double magnitude{ 0.0 };\n  for (int i = 0; i < n_groups; ++i)\n    magnitude += eigenvector_.at(i) * eigenvector_.at(i);\n\n  std::for_each(eigenvector_.begin(), eigenvector_.end(), [magnitude](double& val) { val /= std::sqrt(magnitude); });\n  double sum{ 0.0 };\n  for (int i = 0; i < n_groups; ++i) {\n    sum += eigenvector_.at(i);\n  }\n  // The spectral shape function should be normalized in the L1 norm\n  spectral_shape_function_ = eigenvector_;\n  for (int i = 0; i < n_groups; ++i) {\n    spectral_shape_function_.at(i) /= sum;\n  }\n\n  auto eigenvalue_solver_ptr = std::make_unique<EigenvalueSolver>();\n  eigenvalue_solver_obs_ptr_ = eigenvalue_solver_ptr.get();\n\n  test_class_ = std::make_unique<TestClass>(std::move(eigenvalue_solver_ptr));\n}\n\nTEST_F(CalculatorTwoGridSpectralShapeTest, Getters) {\n  ASSERT_NE(test_class_->eigenvalue_solver_ptr(), nullptr);\n  EXPECT_EQ(test_class_->eigenvalue_solver_ptr(), eigenvalue_solver_obs_ptr_);\n}\n\nTEST_F(CalculatorTwoGridSpectralShapeTest, ConstructorThrowsOnNullDependency) {\n  EXPECT_ANY_THROW(TestClass(nullptr););\n}\n\nauto vectorize_matrix(const dealii::PETScWrappers::MatrixBase& to_vectorize) {\n  std::vector<std::vector<double>> return_vector;\n  for (unsigned int i = 0; i < to_vectorize.m(); ++i) {\n    std::vector<double> row_values;\n    for (unsigned int j = 0; j < to_vectorize.n(); ++j) {\n      row_values.push_back(to_vectorize(i, j));\n    }\n    return_vector.push_back(row_values);\n  }\n  return return_vector;\n}\n\nMATCHER(VectorsNear, \"\") {\n  std::vector<double> result;\n  auto v1 = std::get<0>(arg);\n  auto v2 = std::get<1>(arg);\n  std::transform(v1.begin(), v1.end(), v2.begin(), std::back_inserter(result), std::minus<double>());\n  for (const auto val : result) {\n    if (std::abs(val) > 1e-6)\n      return false;\n  }\n  return true;\n}\n\n// SpectralShape should return the correct value\nTEST_F(CalculatorTwoGridSpectralShapeTest, SpectralShape) {\n  std::pair<double, std::vector<double>> eigenpair{eigenvalue_, eigenvector_};\n\n  EXPECT_CALL(*this->eigenvalue_solver_obs_ptr_, SpectralRadius(ResultOf(vectorize_matrix,\n                                                                         Pointwise(VectorsNear(), expected_a_values))))\n      .WillOnce(Return(eigenpair));\n  auto spectral_shape_vector = test_class_->CalculateSpectralShape(sigma_t, sigma_s);\n  EXPECT_THAT(spectral_shape_vector, ContainerEq(spectral_shape_function_));\n}\n\n// Spectral shape should fix the returned vector if it is negative (it should be normalized already)\nTEST_F(CalculatorTwoGridSpectralShapeTest, SpectralShapeNegative) {\n  std::vector<double> negative_eigenvector(eigenvector_);\n  std::for_each(negative_eigenvector.begin(), negative_eigenvector.end(), [](double& val) { val *= -1; });\n\n  std::pair<double, std::vector<double>> eigenpair{eigenvalue_, negative_eigenvector};\n\n  EXPECT_CALL(*this->eigenvalue_solver_obs_ptr_, SpectralRadius(ResultOf(vectorize_matrix,\n                                                                         Pointwise(VectorsNear(), expected_a_values))))\n      .WillOnce(Return(eigenpair));\n  auto spectral_shape_vector = test_class_->CalculateSpectralShape(sigma_t, sigma_s);\n  EXPECT_THAT(spectral_shape_vector, ContainerEq(spectral_shape_function_));\n}\n\nTEST_F(CalculatorTwoGridSpectralShapeTest, BadMatrixSize) {\n  for (const int bad_size : {0, n_groups + 1, n_groups - 1} ) {\n    Matrix bad_rows(bad_size, n_groups);\n    Matrix bad_cols(n_groups, bad_size);\n    for (auto matrix : {sigma_t, sigma_s}) {\n      EXPECT_ANY_THROW(test_class_->CalculateSpectralShape(matrix, bad_rows));\n      EXPECT_ANY_THROW(test_class_->CalculateSpectralShape(bad_rows, matrix));\n      EXPECT_ANY_THROW(test_class_->CalculateSpectralShape(matrix, bad_cols));\n      EXPECT_ANY_THROW(test_class_->CalculateSpectralShape(bad_cols, matrix));\n    }\n  }\n}\n\n} // namespace\n\n", "meta": {"hexsha": "c9549008a78b7bc0f19929c18928235fa84c4ca1", "size": 5977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/acceleration/two_grid/spectral_shape/tests/spectral_shape_test.cpp", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/acceleration/two_grid/spectral_shape/tests/spectral_shape_test.cpp", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/acceleration/two_grid/spectral_shape/tests/spectral_shape_test.cpp", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 38.0700636943, "max_line_length": 119, "alphanum_fraction": 0.7125648319, "num_tokens": 1619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5478580862198648}}
{"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//[register_multi_point\r\n//` Show the use of the macro BOOST_GEOMETRY_REGISTER_MULTI_POINT\r\n\r\n#include <iostream>\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\r\n#include <boost/geometry/multi/geometries/register/multi_point.hpp>\r\n#include <boost/geometry/multi/io/wkt/wkt.hpp>\r\n\r\ntypedef boost::tuple<float, float> point_type;\r\n\r\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\r\nBOOST_GEOMETRY_REGISTER_MULTI_POINT(std::deque< ::point_type >)\r\n\r\nint main()\r\n{\r\n    // Normal usage of std::\r\n    std::deque<point_type> multi_point;\r\n    multi_point.push_back(point_type(1, 1));\r\n    multi_point.push_back(point_type(3, 2));\r\n    \r\n    // Usage of Boost.Geometry\r\n    std::cout << \"WKT: \"  << boost::geometry::wkt(multi_point) << std::endl;\r\n    \r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[register_multi_point_output\r\n/*`\r\nOutput:\r\n[pre\r\nWKT: MULTIPOINT((1 1),(3 2))\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "f363d44d2ccb9dadc384da0b8b926612f911aff5", "size": 1267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/geometries/register/multi_point.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/geometries/register/multi_point.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/geometries/register/multi_point.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": 26.3958333333, "max_line_length": 80, "alphanum_fraction": 0.7024467245, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5478323807222872}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Polyhedron_items_with_id_3.h>\n\n#include <boost/graph/breadth_first_search.hpp>\n\n#include <fstream>\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;\n\n\n\nint main(int, char** argv) {\n\n  Polyhedron P;  \n  std::ifstream in(argv[1]);\n  in >> P ;\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  // This is the vector where the distance gets written to\n  std::vector<int> distance(P.size_of_vertices());  \n  \n\n  // Here we start at an arbitrary vertex \n  // Any other vertex could be the starting point\n  boost::tie(vb,ve)=vertices(P);\n  vertex_descriptor  vd = *vb;\n  \n  std::cout << \"We compute distances to \" << vd->point() << std::endl;\n  \n\n  // bfs = breadth first search explores the graph\n  // Just as the distance_recorder there is a way to record the predecessor of a vertex  \n  boost::breadth_first_search(P, \n\t\t\t      vd,\n\t\t\t      visitor(boost::make_bfs_visitor(boost::record_distances(make_iterator_property_map(distance.begin(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t get(boost::vertex_index, P)),\n\t\t\t\t\t\t\t\t\t\t      boost::on_tree_edge()))));\n\n\n\n  // Traverse all vertices and show at what distance they are\n  for(boost::tie(vb,ve)=vertices(P); vb!=ve; ++vb ){\n    vd = *vb;\n    std::cout <<  vd->point() << \"  is \" << distance[vd->id()] << \" hops away\" << std::endl;\n  }\n  \n  return 0;\n}\n", "meta": {"hexsha": "51da1ac49d7787b68745b8b89996c7cf51dc6483", "size": 2017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_polyhedron_3/distance.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/distance.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/distance.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": 31.0307692308, "max_line_length": 109, "alphanum_fraction": 0.6539414973, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5478323639494354}}
{"text": "/*\n * Array can  perform coefficient-wise operations, which might not have a linear algebraic meaning.\n * Refs:\n * https://eigen.tuxfamily.org/dox/group__TutorialArrayClass.html\n * */\n\n#include <iostream>\n#include <Eigen/Dense>\n\n#define PRINT(x) std::cout << #x << \": \" << std::endl << (x) << std::endl << std::endl\n#define PRINT_SIZE(x) std::cout << #x << \" is of size \" << x.rows() << \"x\" << x.cols() << std::endl << std::endl\n#define SECTION(x) std::cout << \"======================== \" << x << \" =======================\" << std::endl << std::endl\n\nint main() {\n\n  using namespace Eigen;\n\n  SECTION(\"Initialisations\");\n  ArrayXXf m1(2,2); // Array<double,Dynamic,Dynamic>\n  m1 = Array22f::Ones();\n  PRINT(m1);\n  Array22f m2;\n  m2 << 1, 2, 3, 4;\n\n  // https://eigen.tuxfamily.org/dox/group__TutorialAdvancedInitialization.html\n  ArrayXXf table(10, 4);\n  table.col(0) = ArrayXf::LinSpaced(10, 0, 90);\n  table.col(1) = M_PI / 180 * table.col(0);\n  table.col(2) = table.col(1).sin();\n  table.col(3) = table.col(1).cos();\n  std::cout << \"table: \" << std::endl;\n  std::cout << \"\\tDegrees\\t\\tRadians\\t\\tSine\\t\\tCosine\\n\";\n  std::cout << table << std::endl;\n\n  SECTION(\"Operations\");\n  PRINT(m1+5);\n  PRINT(m1+m2);\n  PRINT(m1*2);\n  PRINT(m1*m2);\n\n  SECTION(\"Reduction\");\n  Array33f m3 = Array33f::Random();\n  PRINT(m3);\n  PRINT(m3.abs().sqrt());\n  PRINT(m3.min(m3.abs().sqrt()));\n  // more coefficient-wise & Array operators https://eigen.tuxfamily.org/dox/group__QuickRefPage.html\n  // boolean https://eigen.tuxfamily.org/dox/group__TutorialReductionsVisitorsBroadcasting.html\n  PRINT((m3 > 0).all());\n  PRINT((m3 > 0).any());\n  PRINT((m3 > 0).count());\n\n  SECTION(\"Types converting\");\n  // convert type\n  MatrixXf m(2,2);\n  MatrixXf n(2,2);\n  MatrixXf result(2,2);\n  m << 1,2,\n  3,4;\n  n << 5,6,\n  7,8;\n  PRINT(m);\n  PRINT(n);\n  result = m * n;\n  std::cout << \"-- Matrix m*n: --\" << std::endl << result << std::endl << std::endl;\n  result = m.array() * n.array();\n  std::cout << \"-- Array m*n: --\" << std::endl << result << std::endl << std::endl;\n  result = m.cwiseProduct(n);\n  std::cout << \"-- With cwiseProduct: --\" << std::endl << result << std::endl << std::endl;\n  result = m.array() + 4;\n  std::cout << \"-- Array m + 4: --\" << std::endl << result << std::endl << std::endl;\n  result = (m.array() + 4).matrix() * m;\n  std::cout << \"-- Combination 1: --\" << std::endl << result << std::endl << std::endl;\n  result = (m.array() * n.array()).matrix() * m;\n  std::cout << \"-- Combination 2: --\" << std::endl << result << std::endl << std::endl;\n\n  ArrayXXd arr_result = result.array().cast<double>();\n  PRINT(arr_result);\n}\n", "meta": {"hexsha": "aaaede405c3ba8bc0e622c9cdcec815df0956b63", "size": 2623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/103_Array/main.cpp", "max_stars_repo_name": "GeneKao/Eigen-Cpp-Notes", "max_stars_repo_head_hexsha": "fbc558af3926cb2f033a44403923af621fee1e92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/103_Array/main.cpp", "max_issues_repo_name": "GeneKao/Eigen-Cpp-Notes", "max_issues_repo_head_hexsha": "fbc558af3926cb2f033a44403923af621fee1e92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/103_Array/main.cpp", "max_forks_repo_name": "GeneKao/Eigen-Cpp-Notes", "max_forks_repo_head_hexsha": "fbc558af3926cb2f033a44403923af621fee1e92", "max_forks_repo_licenses": ["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.2025316456, "max_line_length": 120, "alphanum_fraction": 0.5829203202, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.5477636933342122}}
{"text": "//\n// Add --log_level=message to see the messages!\n//\n#define BOOST_TEST_MODULE \"Functions Tests\"\n\n#include <boost/test/unit_test.hpp>\n\n#include <algorithm>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\n#include \"core/types.h\"\n#include \"core/random.h\"\n#include \"core/utils.h\"\n#include \"core/functions.h\"\n\n#include \"timer.h\"\n#include \"test_utils.h\"\n\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::unit_test;\nusing namespace boost::numeric;\nusing namespace yann;\nusing namespace yann::test;\n\n\nstruct FunctionsTestFixture\n{\n  const size_t min_steps = 5;\n\n  FunctionsTestFixture()\n  {\n\n  }\n  ~FunctionsTestFixture()\n  {\n\n  }\n\n  void softmax_vector(const RefConstVector & input, RefVector output, const Value & beta)\n  {\n    YANN_CHECK(is_same_size(input, output));\n    YANN_CHECK_EQ(input.rows(), 1); // RowMajor layout, breaks for ColMajor\n\n    Value max = input.maxCoeff(); // adjust the computations to avoid overflowing\n    Value sum = exp((input.array() - max) * beta).sum();\n    output.array() = (exp((input.array() - max) * beta)) / sum;\n  }\n\n  void softmax(const RefConstMatrix & input, RefMatrix output, const Value & beta = 3.0)\n  {\n    YANN_CHECK(is_same_size(input, output));\n    for(MatrixSize ii = 0; ii < input.rows(); ++ii) {\n      softmax_vector(input.row(ii), output.row(ii), beta);\n    }\n  }\n\n  pair<Matrix, Value> test_cost_function(\n      const unique_ptr<CostFunction> & cost_function,\n      const RefConstMatrix & actual0, const RefConstMatrix & expected, const Value & cost0,\n      double learning_rate,\n      const size_t & epochs,\n      bool use_softmax = false)\n  {\n    YANN_CHECK(is_same_size(actual0, expected));\n\n    // setup\n    Matrix delta, actual;\n    delta.resizeLike(expected);\n    actual = actual0;\n    Value cost = 0;\n\n    // ensure we don't do allocations in eigen\n    {\n      BlockAllocations block;\n\n      // check activation_function\n      cost = cost_function->f(actual0, expected);\n      BOOST_CHECK_CLOSE(cost, cost0, TEST_TOLERANCE);\n\n      // check activation_derivative\n      size_t progress_step = max(epochs / 10, min_steps);\n      for (size_t ii = 0; ii < epochs; ++ii) {\n        cost_function->derivative(actual, expected, delta);\n        actual -= learning_rate * delta;\n        if(use_softmax) {\n          softmax(actual, actual);\n        }\n        cost = cost_function->f(actual, expected);\n\n        if (ii % progress_step == 0) {\n          BOOST_TEST_MESSAGE(\"epoch=\" << ii << \" out of \" << epochs << \" cost=\" << cost);\n        }\n      }\n    }\n\n    return make_pair(actual, cost);\n  }\n\n  pair<Vector, Vector> test_activation_function(\n      const unique_ptr<ActivationFunction> & activation_function,\n      const unique_ptr<CostFunction> & cost_function,\n      const Vector & input0, const Vector & output0, const Vector & expected,\n      double learning_rate = 1.0, const size_t & epochs = 10,\n      int alloc_check_flags = BlockAllocations::None)\n  {\n    YANN_CHECK_EQ(input0.size(), output0.size());\n    YANN_CHECK_EQ(input0.size(), expected.size());\n\n    // setup\n    const size_t size = input0.size();\n    Vector output(size);\n    Vector delta(size);\n    Vector input(input0), gradient(size), cost_derivative(size);\n\n    // ensure we don't do allocations in eigen\n    {\n      BlockAllocations block(alloc_check_flags);\n\n      // check activation_function\n      activation_function->f(input0, output);\n      BOOST_CHECK(output0.isApprox(output, TEST_TOLERANCE));\n\n      // check activation_derivative\n      size_t progress_step = max(epochs / 10, min_steps);\n      for (size_t ii = 0; ii < epochs; ++ii) {\n        // calculate gradient\n        activation_function->derivative(output, delta);\n        cost_function->derivative(output, expected, cost_derivative);\n        gradient.array() = cost_derivative.array() * delta.array();\n\n        input -= learning_rate * gradient;\n\n        // next iteration\n        activation_function->f(input, output);\n        if (ii % progress_step == 0) {\n          BOOST_TEST_MESSAGE(\"epoch=\" << ii << \" out of \" << epochs << \" cost=\" << cost_function->f(output, expected));\n        }\n      }\n    }\n\n    return make_pair(input, output);\n  }\n\n};\n// struct FunctionsTestFixture\n\nBOOST_FIXTURE_TEST_SUITE(FunctionsTest, FunctionsTestFixture);\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// cost functions tests\n//\nBOOST_AUTO_TEST_CASE(QuadraticCost_Test)\n{\n  const size_t size = 2;\n  Vector actual0(size);\n  Vector expected(size);\n  Value cost0;\n  const double learning_rate = 0.25;\n  size_t epochs = 50;\n\n  actual0 << 11.0, 1;\n  expected << 1.0, 6.0;\n  cost0 = 125;\n\n  pair<Vector, Value> res = test_cost_function(\n      make_unique<QuadraticCost>(),\n      actual0, expected, cost0,\n      learning_rate, epochs);\n\n  BOOST_TEST_MESSAGE(\"expected=\" << expected << \" actual=\" << res.first << \" cost=\" << res.second);\n  BOOST_CHECK(expected.isApprox(res.first, TEST_TOLERANCE));\n  BOOST_CHECK_SMALL(res.second, TEST_TOLERANCE);\n}\n\nBOOST_AUTO_TEST_CASE(ExponentialCost_Test)\n{\n  const size_t size = 2;\n  Vector actual0(size);\n  Vector expected(size);\n  Value cost0;\n  const double learning_rate = 0.001;\n  size_t epochs = 100;\n\n  actual0 << 11.0, 1;\n  expected << 1.0, 6.0;\n  cost0 = 349.03430;\n\n  pair<Vector, Value> res = test_cost_function(\n      make_unique<ExponentialCost>(100.0),\n      actual0, expected, cost0,\n      learning_rate, epochs);\n\n  BOOST_TEST_MESSAGE(\"expected=\" << expected << \" actual=\" << res.first << \" cost=\" << res.second);\n  BOOST_CHECK(expected.isApprox(res.first, TEST_TOLERANCE));\n  BOOST_CHECK_CLOSE(100.00, res.second, TEST_TOLERANCE);\n}\n\nBOOST_AUTO_TEST_CASE(CrossEntrypyCost_Test)\n{\n  const size_t size = 2;\n  Vector actual0(size);\n  Vector expected(size);\n  Value cost0;\n  const double learning_rate = 0.1;\n  size_t epochs = 15;\n\n  // f(actual, expected) = sum(-(expected * ln(actual) + (1 - expected) * ln(1 - actual)))\n  actual0 << 0.9, 0.3;\n  expected << 0.3, 0.8;\n  cost0 = 2.677931;\n\n  pair<Vector, Value> res = test_cost_function(\n      make_unique<CrossEntropyCost>(),\n      actual0, expected, cost0,\n      learning_rate, epochs);\n\n  BOOST_TEST_MESSAGE(\"expected=\" << expected << \" actual=\" << res.first << \" cost=\" << res.second);\n  BOOST_CHECK(expected.isApprox(res.first, TEST_TOLERANCE));\n  BOOST_CHECK_CLOSE(1.111266, res.second, TEST_TOLERANCE);\n}\n\nBOOST_AUTO_TEST_CASE(HellingerDistanceCost_Test)\n{\n  const size_t size = 2;\n  Vector actual0(size);\n  Vector expected(size);\n  Value cost0;\n  const double learning_rate = 0.75;\n  size_t epochs = 15;\n\n  actual0 << 0.9, 0.1;\n  expected << 0.3, 0.7;\n  cost0 = 0.43150;\n  pair<Vector, Value> res = test_cost_function(\n      make_unique<HellingerDistanceCost>(0.0001),\n      actual0, expected, cost0,\n      learning_rate, epochs);\n\n  BOOST_TEST_MESSAGE(\"expected=\" << expected << \" actual=\" << res.first << \" cost=\" << res.second);\n  BOOST_CHECK(expected.isApprox(res.first, TEST_TOLERANCE));\n  BOOST_CHECK_SMALL(res.second, TEST_TOLERANCE);\n}\n\nBOOST_AUTO_TEST_CASE(SquaredHingeLoss_Test)\n{\n  const size_t size = 4;\n  Vector actual0(size);\n  Vector actual_expected(size);\n  Vector expected(size);\n  Value cost0;\n  const double learning_rate = 0.5;\n  size_t epochs = 10;\n\n  actual0   << 0.6, 0.1, 0.3, 0.0;\n  expected  << 0.0, 1.0, 0.0, 0.0;\n  actual_expected << 0.049, 0.852, 0.049, 0.049;\n  cost0  = 0.81;\n  pair<Vector, Value> res = test_cost_function(\n      make_unique<SquaredHingeLoss>(),\n      actual0, expected, cost0,\n      learning_rate, epochs, true); // use softmax\n\n  BOOST_TEST_MESSAGE(\"expected=\" << expected << \" actual=\" << res.first << \" cost=\" << res.second);\n  BOOST_CHECK(actual_expected.isApprox(res.first, TEST_TOLERANCE));\n  BOOST_CHECK_CLOSE(0.02177566296, res.second, TEST_TOLERANCE);\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// activations functions tests\n//\nBOOST_AUTO_TEST_CASE(IdentityFunction_Test)\n{\n  const size_t size = 2;\n  Vector input0(size);\n  Vector output0(size);\n  Vector input_expected(size);\n  Vector expected(size);\n  const double learning_rate = 0.75;\n  size_t epochs = 1000;\n\n  input0   << -5,  10;\n  output0  << -5, 10;\n  expected << 20, -5;\n  input_expected << 20, -5;\n  pair<Vector, Vector> res = test_activation_function(\n      make_unique<IdentityFunction>(),\n      make_unique<QuadraticCost>(),\n      input0, output0, expected,\n      learning_rate, epochs);\n\n  BOOST_TEST_MESSAGE(\"intput expected=\" << input_expected << \" actual=\" << res.first);\n  BOOST_TEST_MESSAGE(\"output expected=\" << expected << \" actual=\" << res.second);\n  BOOST_CHECK(input_expected.isApprox(res.first, TEST_TOLERANCE));\n  BOOST_CHECK(expected.isApprox(res.second, TEST_TOLERANCE));\n}\n\nBOOST_AUTO_TEST_CASE(SigmoidFunction_Test)\n{\n  const size_t size = 2;\n  Vector input0(size);\n  Vector output0(size);\n  Vector input_expected(size);\n  Vector expected(size);\n  const double learning_rate = 0.75;\n  size_t epochs = 1000;\n\n  input0 << 10, 10;\n  output0 << 1.0, 1.0;\n  expected << 0.8, 0.1;\n  input_expected << 1.3862943611, -2.1972245773; // x = -ln(1/y - 1)\n  pair<Vector, Vector> res = test_activation_function(\n      make_unique<SigmoidFunction>(),\n      make_unique<QuadraticCost>(),\n      input0, output0, expected,\n      learning_rate, epochs);\n\n  BOOST_TEST_MESSAGE(\"intput expected=\" << input_expected << \" actual=\" << res.first);\n  BOOST_TEST_MESSAGE(\"output expected=\" << expected << \" actual=\" << res.second);\n  BOOST_CHECK(input_expected.isApprox(res.first, TEST_TOLERANCE));\n  BOOST_CHECK(expected.isApprox(res.second, TEST_TOLERANCE));\n}\n\n\nBOOST_AUTO_TEST_CASE(FastSigmoidFunction_Test)\n{\n  const size_t size = 2;\n  Vector input0(size);\n  Vector output0(size);\n  Vector input_expected(size);\n  Vector expected(size);\n  const double learning_rate = 0.75;\n  size_t epochs = 1000;\n\n  input0 << 10, 10;\n  output0 << 1.0, 1.0;\n  expected << 0.8, 0.1;\n  input_expected << 1.3862943611, -2.1972245773; // x = -ln(1/y - 1)\n  pair<Vector, Vector> res = test_activation_function(\n      make_unique<FastSigmoidFunction>(10000), // increase internal table size to improve accuracy\n      make_unique<QuadraticCost>(),\n      input0, output0, expected,\n      learning_rate, epochs);\n\n  BOOST_TEST_MESSAGE(\"intput expected=\" << input_expected << \" actual=\" << res.first);\n  BOOST_TEST_MESSAGE(\"output expected=\" << expected << \" actual=\" << res.second);\n  BOOST_CHECK(input_expected.isApprox(res.first, TEST_TOLERANCE));\n  BOOST_CHECK(expected.isApprox(res.second, TEST_TOLERANCE));\n}\n\nBOOST_AUTO_TEST_CASE(ReluFunction_Test)\n{\n  const size_t size = 2;\n  Vector input0(size);\n  Vector output0(size);\n  Vector input_expected(size);\n  Vector expected(size);\n  const double learning_rate = 0.75;\n  size_t epochs = 1000;\n\n  input0   << -5,  10;\n  output0  << -0.5, 10;\n  expected << 20, -5;\n  input_expected << 20, -50;\n  pair<Vector, Vector> res = test_activation_function(\n      make_unique<ReluFunction>(0.1),\n      make_unique<QuadraticCost>(),\n      input0, output0, expected,\n      learning_rate, epochs);\n\n  BOOST_TEST_MESSAGE(\"intput expected=\" << input_expected << \" actual=\" << res.first);\n  BOOST_TEST_MESSAGE(\"output expected=\" << expected << \" actual=\" << res.second);\n  BOOST_CHECK(input_expected.isApprox(res.first, TEST_TOLERANCE));\n  BOOST_CHECK(expected.isApprox(res.second, TEST_TOLERANCE));\n}\n\nBOOST_AUTO_TEST_CASE(TahhFunction_Test)\n{\n  const size_t size = 2;\n  Vector input0(size);\n  Vector output0(size);\n  Vector input_expected(size);\n  Vector expected(size);\n  const double learning_rate = 0.75;\n  size_t epochs = 1000;\n\n  input0   << 1,  10;\n  output0  << 0.99992, 1.71589;\n  expected << 0.1, -0.5;\n  input_expected << 0.08753, -0.45018;\n  pair<Vector, Vector> res = test_activation_function(\n      make_unique<TanhFunction>(1.7159, 0.6666),\n      make_unique<QuadraticCost>(),\n      input0, output0, expected,\n      learning_rate, epochs);\n\n  BOOST_TEST_MESSAGE(\"intput expected=\" << input_expected << \" actual=\" << res.first);\n  BOOST_TEST_MESSAGE(\"output expected=\" << expected << \" actual=\" << res.second);\n  BOOST_CHECK(input_expected.isApprox(res.first, TEST_TOLERANCE));\n  BOOST_CHECK(expected.isApprox(res.second, TEST_TOLERANCE));\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "7bfa6fb1486caaab67254aa73d33c7c55a1db149", "size": 12278, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_functions.cpp", "max_stars_repo_name": "lsh123/yann", "max_stars_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:14:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-01T10:25:07.000Z", "max_issues_repo_path": "src/test/test_functions.cpp", "max_issues_repo_name": "lsh123/yann", "max_issues_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_issues_repo_licenses": ["MIT"], "max_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_functions.cpp", "max_forks_repo_name": "lsh123/yann", "max_forks_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_forks_repo_licenses": ["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.7288135593, "max_line_length": 119, "alphanum_fraction": 0.669327252, "num_tokens": 3208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.5477636877084855}}
{"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  Matrix4d m = Vector4d(1,2,3,4).asDiagonal();\ncout << \"Here is the matrix m:\" << endl << m << endl;\ncout << \"Here is m.fixed<2, 2>(2, 2):\" << endl << m.block<2, 2>(2, 2) << endl;\nm.block<2, 2>(2, 0) = m.block<2, 2>(2, 2);\ncout << \"Now the matrix m is:\" << endl << m << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "4fde09716631b0ce22d5a089bac13dea79ef5b95", "size": 758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_MatrixBase_fixedBlock_int_int.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_MatrixBase_fixedBlock_int_int.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_MatrixBase_fixedBlock_int_int.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.1538461538, "max_line_length": 224, "alphanum_fraction": 0.6319261214, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.547755204565514}}
{"text": "#include <deque>\n#include <vector>\n#include <list>\n#include <iostream>\n#include <boost/graph/topological_sort.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/range.hpp>\n#include <boost/range/adaptor/indexed.hpp>\n\nint main()\n{\n    using namespace boost;\n\n    const char * tasks[] = {\n        \"pick up kids from school\",\n        \"buy groceries (and snack)\",\n        \"get cash at ATM\",\n        \"drop off kids at soccer practice\",\n        \"cook dinner\",\n        \"pick up kids from soccer\",\n        \"eat dinner\"\n    };\n\n    const int n_tasks = sizeof(tasks) /sizeof(char*);\n\n    adjacency_list<listS, vecS, directedS> g(n_tasks);\n    add_edge(0, 3, g);\n    add_edge(1, 3, g);\n    add_edge(1, 4, g);\n    add_edge(2, 1, g);\n    add_edge(3, 5, g);\n    add_edge(4, 6, g);\n    add_edge(5, 6, g);\n\n    std::deque<int> topo_order;\n\n    topological_sort(g, std::front_inserter(topo_order),\n            vertex_index_map(identity_property_map()));\n\n    for(const auto& [index, i] : topo_order \n            | boost::adaptors::indexed())\n    {\n        std::cout << tasks[i.head] << std::endl;\n    }\n\n\n    return 0;\n}\n", "meta": {"hexsha": "be4a086535cd6ff7d372f614d244f76176f04fc5", "size": 1115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "chapter1/topo-sort2.cpp", "max_stars_repo_name": "Zilleplus/boost_graph", "max_stars_repo_head_hexsha": "65d6dee7d060fc9aa76a822fde55c244e9468b0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter1/topo-sort2.cpp", "max_issues_repo_name": "Zilleplus/boost_graph", "max_issues_repo_head_hexsha": "65d6dee7d060fc9aa76a822fde55c244e9468b0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter1/topo-sort2.cpp", "max_forks_repo_name": "Zilleplus/boost_graph", "max_forks_repo_head_hexsha": "65d6dee7d060fc9aa76a822fde55c244e9468b0d", "max_forks_repo_licenses": ["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.7551020408, "max_line_length": 56, "alphanum_fraction": 0.598206278, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5477551917407247}}
{"text": "#include \"normal_modes.h\"\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <list>\n#include <array>\n#include <armadillo>\n\n#include \"id_map.h\"\n#include \"dump_reader.h\"\n\ntypedef std::vector<std::array<double,3> > coord_block;\n\n\nvoid normal_mode_analysis( dump_reader &r,  py_int N, void *eigenvalues,\n                           void *eigenvectors )\n{\n\tstd::list< coord_block > blocks;\n\tblock_data b;\n\t\n\twhile( r.next_block( b ) ){\n\t\tid_map im( b.ids, b.N );\n\t\tpy_int Nparticles = b.N;\n\t\t\n\t\tcoord_block block( Nparticles );\n\t\tfor( int i = 0; i < Nparticles; ++i ){\n\t\t\tint id  = i + 1;\n\t\t\tint idx = im[id];\n\n\t\t\tblock[i][0] = b.x[i][0];\n\t\t\tblock[i][1] = b.x[i][1];\n\t\t\tblock[i][2] = b.x[i][2];\n\t\t}\n\n\t\tblocks.push_back( block );\n\t}\n\tstd::cerr << \"Done reading dump file...\\n\";\n\n\tget_normal_modes( blocks, N, eigenvalues, eigenvectors );\n\n}\n\n\nvoid read_blocks_from_pipe( const char *pname,\n                            std::list< coord_block > &bs )\n{\n\tstd::ifstream in(pname);\n\tstd::string line;\n\tstd::ofstream out(\"pipe_test2\");\n\t\n\t/*\n\t  Expected format:\n\t  First line: Number of particles\n\t  N times 3 coordinates, ordered along id.\n\t*/\n\n\tint block_idx = 1;\n\t\n\t// Make sure you exhaust the pipe:\n\twhile( in ){\n\t\tstd::getline( in, line );\n\t\tint Nparticles = 0;\n\t\tstd::stringstream ss(line);\n\t\tss >> Nparticles;\n\n\t\tif( Nparticles <= 0 ) break;\n\t\t\n\t\tcoord_block block(Nparticles);\n\n\t\t\n\t\tfor( int i = 0; i < Nparticles; ++i ){\n\t\t\tstd::getline( in, line );\n\t\t\tss.str(\"\");\n\t\t\tss.clear();\n\t\t\tss << line;\n\t\t\tss  >> block[i][0] >> block[i][1] >> block[i][2];\n\t\t}\n\t\tblock_idx++;\n\t\tbs.push_back( block );\n\t}\n\tstd::cerr << \"Grabbed \" << bs.size() << \" blocks in total.\\n\";\n}\n\n\nvoid average_positions( const std::list< coord_block > &block_data, py_int N,\n                        std::vector<double> &X_avg )\n{\n\tint Nparticles = block_data.begin()->size();\n\tfor( int i = 0; i < N; ++i ) X_avg[i] = 0.0;\n\n\tstd::cerr << \"Averaging positions...\\n\";\n\tfor( const coord_block &b : block_data ){\n\t\tfor( int i = 0; i < Nparticles; ++i ){\n\t\t\tX_avg[3*i + 0] += b[i][0];\n\t\t\tX_avg[3*i + 1] += b[i][1];\n\t\t\tX_avg[3*i + 2] += b[i][2];\n\t\t}\n\t}\n}\n\n\nvoid get_normal_modes( const std::list< coord_block > &block_data, py_int N,\n                       void *eigenvalues, void *eigenvectors,\n                       std::vector<double> *X_avg_ptr )\n{\n\t// Perform the normal mode analysis...\n\tint Nparticles = block_data.begin()->size();\n\tdouble c = 1.0 / static_cast<double>( block_data.size() );\n\tif( 3*Nparticles != N ){\n\t\tstd::cerr << \"Something fishy is going on...\\n\";\n\t\tstd::cerr << \"Nparticles = \" << Nparticles << \", 3*Nparticles = \"\n\t\t          << 3*Nparticles << \" != N = \" << N << \"!\\n\";\n\t\treturn;\n\t}\n\n\tstd::vector<double> X_avg;\n\tstd::cerr << \"Averaging positions...\\n\";\n\tif( !X_avg_ptr ){\n\t\tX_avg.resize(N);\n\t\tX_avg_ptr = &X_avg;\n\t\taverage_positions( block_data, N, *X_avg_ptr );\n\t}else{\n\t\tX_avg = *X_avg_ptr;\n\t\taverage_positions( block_data, N, *X_avg_ptr );\n\t}\n\t\n\t// Extract covariance matrix:\n\tstd::cerr << \"Constructing covariance matrix...\\n\";\n\tarma::mat covar(N,N);\n\t\n\tfor( int i = 0; i < N; ++i ){\n\t\tfor( int j = 0; j < N; ++j ){\n\t\t\tcovar(i, j) = 0.0;\n\t\t}\n\t}\n\t\n\tfor( const coord_block &b : block_data ){\n\t\tfor( int i = 0; i < Nparticles; ++i ){\n\t\t\tdouble dxi = b[i][0] - X_avg[3*i];\n\t\t\tdouble dyi = b[i][1] - X_avg[3*i+1];\n\t\t\tdouble dzi = b[i][2] - X_avg[3*i+2];\n\n\t\t\tfor( int j = 0; j < Nparticles; ++j ){\n\t\t\t\tdouble dxj = b[j][0] - X_avg[3*j];\n\t\t\t\tdouble dyj = b[j][1] - X_avg[3*j+1];\n\t\t\t\tdouble dzj = b[j][2] - X_avg[3*j+2];\n\n\t\t\t\tcovar(3*i  , 3*j  ) += dxi*dxj*c;\n\t\t\t\tcovar(3*i  , 3*j+1) += dxi*dyj*c;\n\t\t\t\tcovar(3*i  , 3*j+2) += dxi*dzj*c;\n\n\t\t\t\tcovar(3*i+1, 3*j  ) += dyi*dxj*c;\n\t\t\t\tcovar(3*i+1, 3*j+1) += dyi*dyj*c;\n\t\t\t\tcovar(3*i+1, 3*j+2) += dyi*dzj*c;\n\n\t\t\t\tcovar(3*i+2, 3*j  ) += dzi*dxj*c;\n\t\t\t\tcovar(3*i+2, 3*j+1) += dzi*dyj*c;\n\t\t\t\tcovar(3*i+2, 3*j+2) += dzi*dzj*c;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Perform the decomposition:\n\tstd::cerr << \"Performing decomposition in normal modes...\\n\";\n\tconst char *method = \"std\";\n\tarma::vec eigval(N);\n\tarma::mat eigvec(N,N);\n\tarma::eig_sym( eigval, eigvec, covar, method );\n\t\n\tstd::cerr << \"Writing \" << N << \" eigenvalues to \" << eigenvalues\n\t          << \" and eigenvectors to \" << eigenvectors << \"\\n\";\n\n\tdouble **eigenvecs = static_cast<double**>(eigenvectors);\n\tdouble *eigenvals  = static_cast<double*> (eigenvalues);\n\n\tfor( int i = 0; i < N; ++i ){\n\t\teigenvals[i] = eigval(i);\n\t\tfor( int j = 0; j < N; ++j ){\n\t\t\teigenvecs[i][j] = eigvec(i,j);\n\t\t}\n\t}\n\tstd::cerr << \"Done!\\n\";\n\n}\n\n\nvoid normal_mode_analysis( const char *pname, void *eigenvalues,\n                           void *eigenvectors, py_int N  )\n{\n\n\tstd::list< coord_block > block_data;\n\n\tread_blocks_from_pipe( pname, block_data );\n\t\n\tget_normal_modes( block_data, N, eigenvalues, eigenvectors );\n}\n\n", "meta": {"hexsha": "777295e9b5e02793b7e946452449712bdc76c63f", "size": 4809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c_lib/normal_modes.cpp", "max_stars_repo_name": "Pakketeretet2/lammps-tools", "max_stars_repo_head_hexsha": "1e2109018a7412c33c80bb3eceb1f97003495341", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-09-04T14:39:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-07T01:30:00.000Z", "max_issues_repo_path": "c_lib/normal_modes.cpp", "max_issues_repo_name": "Pakketeretet2/lammps-tools", "max_issues_repo_head_hexsha": "1e2109018a7412c33c80bb3eceb1f97003495341", "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": "c_lib/normal_modes.cpp", "max_forks_repo_name": "Pakketeretet2/lammps-tools", "max_forks_repo_head_hexsha": "1e2109018a7412c33c80bb3eceb1f97003495341", "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.045, "max_line_length": 77, "alphanum_fraction": 0.5733000624, "num_tokens": 1616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5476929678312173}}
{"text": "#include <vector>\n\n#include <boost/shared_ptr.hpp>\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n\n#include <cmath>\n\n#include \"caffe/blob.hpp\"\n#include \"caffe/common.hpp\"\n#include \"caffe/layers/random_affine_layer.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n\n\nnamespace caffe {\n\n\ntemplate <typename Dtype>\nvoid RandomAffineLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top) {\n\t//do nothing\n}\n\ntemplate <typename Dtype>\nvoid RandomAffineLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top) {\n\t//set in batch size\n\tuint32_t batchSize = this->layer_param_.random_affine_param().batch_size();\n\tvector<int> shape_top(4);\n\tshape_top[0] = batchSize;\n\tshape_top[1] = 1;\n\tshape_top[2] = 2;\n\tshape_top[3] = 3;\n\ttop[0]->Reshape(shape_top);\n\n\t//check valid bottom\n\tif(bottom.size() == 1){\n\t\tCHECK_EQ(top[0]->shape(0), bottom[0]->shape(0)) << \"Bottom batch size not the same\";\n\t\tCHECK_EQ(top[0]->shape(1), bottom[0]->shape(1)) << \"Bottom should have 1 channel\";\n\t\tCHECK_EQ(top[0]->shape(2), bottom[0]->shape(2)) << \"Bottom not 2x3 affine\";\n\t\tCHECK_EQ(top[0]->shape(3), bottom[0]->shape(3)) << \"Bottom not 2x3 affine\";\n\t}\n\n\t//set working variables\n\tvector<int> shape_transform(4);\n\tshape_transform[0] = batchSize;\n\tshape_transform[1] = 1;\n\tshape_transform[2] = 3;\n\tshape_transform[3] = 3;\n\n\tt1_.Reshape(shape_transform);\n\tt2_.Reshape(shape_transform);\n\tt3_.Reshape(shape_transform);\n\tbottomExpanded.Reshape(shape_transform);\n\tt4_.Reshape(shape_transform);\n\n\t//transform params\n\tvector<int> shape_param(4);\n\tshape_param[0] = batchSize;\n\tshape_param[1] = 1;\n\tshape_param[2] = 1;\n\tshape_param[3] = 1;\n\n\ttranslation_x.Reshape(shape_param);\n\ttranslation_y.Reshape(shape_param);\n\trotation.Reshape(shape_param);\n\tscale.Reshape(shape_param);\n\tflipping_rand.Reshape(shape_param);\n}\n\ntemplate <typename Dtype>\nvoid RandomAffineLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top) {\n\t//read in transformation distributions\n\tDtype max_translation_x = this->layer_param_.random_affine_param().max_translation_x();\n\tDtype max_translation_y = this->layer_param_.random_affine_param().max_translation_y();\n\tDtype max_rotation = this->layer_param_.random_affine_param().max_rotation();\n\tDtype min_scale = this->layer_param_.random_affine_param().min_scale();\n\tDtype max_scale = this->layer_param_.random_affine_param().max_scale();\n\tbool horizontalFlipping = this->layer_param_.random_affine_param().horizontal_flipping();\n\n\t//helpers\n\tDtype* t1 = t1_.mutable_cpu_data();\n\tDtype* t2 = t2_.mutable_cpu_data();\n\tDtype* t3 = t3_.mutable_cpu_data();\n\tDtype* bottomExpandedData = bottomExpanded.mutable_cpu_data();\n\tDtype* t4 = t4_.mutable_cpu_data();\n\tDtype* top_data = top[0]->mutable_cpu_data();\n\n\tcaffe_set(t1_.count(), (Dtype)0, t1);\n\tcaffe_set(t2_.count(), (Dtype)0, t2);\n\tcaffe_set(t3_.count(), (Dtype)0, t3);\n\tcaffe_set(bottomExpanded.count(), (Dtype)0, bottomExpandedData);\n\tcaffe_set(t4_.count(), (Dtype)0, t4);\n\n\tint N = top[0]->shape(0);\n\n\t//generate transform params\n\tDtype* tx = translation_x.mutable_cpu_data();\n\tDtype* ty = translation_y.mutable_cpu_data();\n\tDtype* rot = rotation.mutable_cpu_data();\n\tDtype* scal = scale.mutable_cpu_data();\n\tDtype* flip = flipping_rand.mutable_cpu_data();\n\n\tcaffe_rng_uniform(N,-max_translation_x,max_translation_x,tx);\n\tcaffe_rng_uniform(N,-max_translation_y,max_translation_y,ty);\n\tcaffe_rng_uniform(N,-max_rotation,max_rotation,rot);\n\tcaffe_rng_uniform(N,min_scale,max_scale,scal);\n\tif(horizontalFlipping){\n\t\tcaffe_rng_uniform(N,(Dtype)0,(Dtype)1,flip);\n\t}\n\telse{\n\t\tcaffe_set(N, (Dtype)0, flip);\n\t}\n\n\tfor(int n=0;n<N;n++){\n\t\t//translation\n\t\tt1[9*n + 2] = tx[n];\n\t\tt1[9*n + 5] = ty[n];\n\t\tt1[9*n + 8] = 1;\n\t\t//rotation\n\t\tDtype ang = rot[n];\n\t\tt1[9*n] = cos(ang); t1[9*n + 1] = -sin(ang);\n\t\tt1[9*n + 3] = sin(ang); t1[9*n + 4] = cos(ang);\n\n\t\t//scale\n\t\tDtype scaleFactor = scal[n];\n\t\tscaleFactor = 1/scaleFactor;\n\t\tif(flip[n] > 0.5){\n\t\t\tt2[9*n] = scaleFactor;\n\t\t\tt2[9*n + 4] = -scaleFactor;\n\t\t\tt2[9*n + 8] = 1;\n\t\t}\n\t\telse{\n\t\t\tt2[9*n] = scaleFactor;\n\t\t\tt2[9*n + 4] = scaleFactor;\n\t\t\tt2[9*n + 8] = 1;\n\t\t}\n\n\t\tcaffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, 3, 3, 3, (Dtype)1.0,\n\t\t      &t1[9*n], &t2[9*n], (Dtype)0.0, &t3[9*n]);\n\n\t\t//transfer to top\n\t\tif(bottom.size() == 1){\n\t\t\tcaffe_copy(6, &(bottom[0]->mutable_cpu_data()[6*n]), &bottomExpandedData[9*n]);\n\t\t\tbottomExpandedData[9*n + 8] = 1;\n\n\t\t\tcaffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, 3, 3, 3, (Dtype)1.0,\n\t\t      \t\t&t3[9*n], &bottomExpandedData[9*n], (Dtype)0.0, &t4[9*n]);\n\t\t\tcaffe_copy(6, &t4[9*n], &top_data[6*n]);\n\t\t}\n\t\telse{\n\t\t\tcaffe_copy(6, &t3[9*n], &top_data[6*n]);\n\t\t}\n\t}\n}\n\ntemplate <typename Dtype>\nvoid RandomAffineLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& top) {\n\t//do nothing\n}\n\n\n#ifdef CPU_ONLY\nSTUB_GPU(RandomAffineLayer);\n#endif\n\nINSTANTIATE_CLASS(RandomAffineLayer);\nREGISTER_LAYER_CLASS(RandomAffine);\n\n}  // namespace caffe\n", "meta": {"hexsha": "11f35ca71ebe2ff83595ab685942e4d84705a85c", "size": 5062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/layers/random_affine_layer.cpp", "max_stars_repo_name": "bryanyzhu/GuidedNet", "max_stars_repo_head_hexsha": "4c87d392addc38700caf2856b450f2c74a79e122", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2017-06-05T19:19:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T14:36:37.000Z", "max_issues_repo_path": "src/caffe/layers/random_affine_layer.cpp", "max_issues_repo_name": "zmlshiwo/GuidedNet", "max_issues_repo_head_hexsha": "4c87d392addc38700caf2856b450f2c74a79e122", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-15T11:48:01.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-15T11:52:13.000Z", "max_forks_repo_path": "src/caffe/layers/random_affine_layer.cpp", "max_forks_repo_name": "zmlshiwo/GuidedNet", "max_forks_repo_head_hexsha": "4c87d392addc38700caf2856b450f2c74a79e122", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T16:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-16T18:31:17.000Z", "avg_line_length": 29.2601156069, "max_line_length": 90, "alphanum_fraction": 0.6985381272, "num_tokens": 1608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.547692950165029}}
{"text": "// [[Rcpp::depends(RcppArmadillo)]]\n#define ARMA_DONT_PRINT_ERRORS\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <armadillo>\n#include <errno.h>\n#include <RcppArmadillo.h>\n//' Get observation location in 2D space\n//'\n//' @param  time time to return observer position\n//' @param  strip_size size of strip in (x, y) dimensions\n//' @param  buffer buffer size\n//' @param  delta (dx, dt) vector\n//' @param  transect_type 0 = line, 1 = point\n//' @param  observer_speed speed of observer\n//'\n//' @return  (x, y) location of observer at time t\n// [[Rcpp::export]]\narma::vec GetObserverPosition(const double time,\n                        const arma::vec strip_size,\n                        const double buffer,\n                        const arma::vec delta,\n                        const int transect_type,\n                        const double observer_speed) {\n  arma::vec pos(2);\n  pos(0) = 0.5 * strip_size(0);\n  if (transect_type == 1) {\n    // point transect assumed to be center of grid\n\t  pos(1) = 0.5 * strip_size(1);\n  } else {\n    pos(1) = observer_speed * time + buffer;\n  }\n  return pos;\n}\n//' Calculates the sparse transition rate matrix\n//'\n//' @param  num_cells vector with number of cells in (total space, x-direction,\n//'     y-direction)\n//' @param  sd vector of diffusive standard deviation for each behavioural state\n//' @param  dx grid cell size in the space (c.f. delta(0))\n//'\n//' @return sparse transition rate matrix\n// [[Rcpp::export]]\narma::sp_mat CalcTrm(const arma::vec num_cells, const double sd, const double dx) {\n  arma::sp_mat tpr = arma::zeros<arma::sp_mat>(num_cells(0), num_cells(0));\n  double rate = sd * sd / (2 * dx * dx);\n  int s;\n  for (int i = 0; i < num_cells(1); ++i) {\n    for (int j = 0; j < num_cells(2); ++j) {\n      s = i + num_cells(1) * j;\n      if (i < num_cells(1) - 1) {\n        tpr(s, s + 1) = rate;\n      }\n      if (i > 0) {\n        tpr(s, s - 1) = rate;\n      }\n      if (j < num_cells(2) - 1) {\n        tpr(s, s + num_cells(1)) = rate;\n      }\n      if (j > 0) {\n        tpr(s, s - num_cells(1)) = rate;\n      }\n      tpr(s, s) = -4 * rate;\n    }\n  }\n  return tpr.t();\n}\n//' Diffuse probability distribution over space\n//'\n//' @description Calculate product of v with matrix exponential of a using\n//' the Arnoldi process. Thereby diffusing the probability distribution\n//' according to Brownian motion. Code is transcribed from Expokit package.\n//' \n//' @note NOTICE\n//' Permission to use, copy, modify, and distribute EXPOKIT and its\n//'   supporting documentation for non-commercial purposes, is hereby\n//'     granted without fee, provided that this permission message and\n//'     copyright notice appear in all copies. Approval must be sought for\n//'       commercial purposes as testimony of its usage in applications.\n//'     \n//'     Neither the Institution (University of Queensland) nor the Author\n//'       make any representations about the suitability of this software for\n//'         any purpose.  This software is provided ``as is'' without express or\n//'        implied warranty.\n//'       \n//'       The work resulting from EXPOKIT has been published in ACM-Transactions \n//'         on Mathematical Software, 24(1):130-156, 1998.\n//'       \n//'       The bibtex record of the citation:\n//'         \n//'         ARTICLE{EXPOKIT,\n//'                  AUTHOR  = {Sidje, R. B.},\n//'                  TITLE   = {{Expokit.} {A} Software Package for\n//'                    Computing Matrix Exponentials},\n//'                    JOURNAL = {ACM Trans. Math. Softw.},\n//'                    VOLUME  = {24},\n//'                    NUMBER  = {1},\n//'                    PAGES   = {130-156}\n//'           YEAR    = {1998}\n//'         }\n//'       \n//'       Certain elements of the current software may include inadequacies\n//'         that may be corrected at any time, as they are discovered. The Web \n//'         always contains the latest updates.\n//'       \n//'       Original Author:\n//'         Roger B. Sidje <rbs@maths.uq.edu.au>\n//'         Department of Mathematics, University of Queensland \n//'         Brisbane, QLD-4072, Australia, (c) 1996-2006 All Rights Reserved\n//'\n//' @param a transition rate matrix\n//' @param  v vector to be multiplied\n//' @param  t time to diffuse over\n//' @param  num_cells vector with number of cells in (total space, x-direction,\n//'     y-direction)\n//' @param  krylov_dim dimension of the approximating Krylov space\n//' @param  tol tolerance in error\n//'\n//' @return  diffused probability distribution\n// [[Rcpp::export]]\narma::rowvec Diffuse(const arma::sp_mat a,\n                     const arma::rowvec v,\n                     const double t,\n                     const arma::vec num_cells,\n                     const int& krylov_dim = 30,\n                     const double& tol = 1e-10) {\n  double m = fmin(a.n_rows, krylov_dim);\n  double anorm = norm(a, \"Inf\");\n  double mxrej = 10;\n  double mx;\n  double btol = 1e-7;\n  double gamma = 0.9;\n  double mb = m;\n  int nstep = 0;\n  double t_now = 0;\n  double t_step;\n  double delta = 1.2;\n  double t_out = fabs(t);\n  double s_error = 0;\n  double rndoff = anorm * 1e-16;\n  int k1 = 1;\n  double xm = 1 / m;\n  double normv = norm(v);\n  double avnorm;\n  double beta = normv;\n  double fact = std::pow((m + 1) / std::exp(1), m + 1) * std::sqrt(2 * M_PI * (m + 1));\n  double t_new = (1.0 / anorm) * std::pow((fact * tol) / (4 * beta * anorm), xm);\n  double s = std::pow(10, std::floor(std::log10(t_new)) - 1);\n  t_new = std::ceil(t_new / s) * s;\n  double sgn = t > 0 ? 1 : -1;\n  int ireject;\n  double err_loc;\n  double phi1;\n  double phi2;\n  arma::vec w = v.t();\n  double hump = normv;\n  arma::mat vmat = arma::zeros<arma::mat>(a.n_rows, m + 1);\n  arma::mat hmat = arma::zeros<arma::mat>(m + 2, m + 2);\n  arma::mat fmat;\n  arma::vec p;\n  while (t_now < t_out) {\n    Rcpp::checkUserInterrupt();\n    ++nstep;\n    t_step = fmin(t_out - t_now, t_new);\n    vmat.zeros();\n    hmat.zeros();\n    vmat.col(0) = (1 / beta) * w;\n    for (int j = 0; j < m; ++j) {\n      p = a * vmat.col(j);\n      for (int i = 0; i <= j; ++i) {\n        hmat(i, j) = dot(vmat.col(i), p);\n        p -= hmat(i, j) * vmat.col(i);\n      }\n      s = norm(p);\n      if (s < btol) {\n        k1 = 0;\n        mb = j;\n        t_step = t_out - t_now;\n        break;\n      }\n      hmat(j + 1, j) = s;\n      vmat.col(j + 1) = (1 / s) * p;\n    }\n    if (k1 != 0) {\n      hmat(m + 1, m) = 1;\n      avnorm = norm(a * vmat.col(m));\n    }\n    ireject = 0;\n    while (ireject <= mxrej) {\n      mx = mb + k1;\n      fmat = expmat(sgn * t_step * hmat.submat(0, 0, mx, mx));\n\n      if (k1 == 0) {\n        err_loc = btol;\n        break;\n      }\n      else {\n        phi1 = fabs(beta * fmat(m, 0));\n        phi2 = fabs(beta * fmat(m + 1, 0) * avnorm);\n        if (phi1 > 10 * phi2) {\n          err_loc = phi2;\n          xm = 1 / m;\n        }\n        else if (phi1 > phi2) {\n          err_loc = (phi1 * phi2) / (phi1 - phi2);\n          xm = 1 / m;\n        }\n        else {\n          err_loc = phi1;\n          xm = 1 / (m - 1);\n        }\n      }\n      if (err_loc <= delta * t_step * tol) break;\n      else {\n        t_step = gamma * t_step * std::pow(t_step * tol / err_loc, xm);\n        s = std::pow(10, std::floor(std::log10(t_step)) - 1);\n        t_step = std::ceil(t_step / s) * s;\n        if (ireject == mxrej) {\n          Rcpp::Rcout << \"error: requested tolerance too high for Krylov approximation\" << std::endl;\n        }\n        ++ireject;\n      }\n    }\n    mx = mb + fmax(0, k1 - 1);\n    w = vmat.cols(0, mx) * beta * fmat.col(0).rows(0, mx);\n    beta = norm(w);\n    hump = fmax(hump, beta);\n\n    t_now = t_now + t_step;\n    t_new = gamma * t_step * std::pow(t_step * tol / err_loc, xm);\n    s = std::pow(10, std::floor(std::log10(t_new) - 1));\n    t_new = std::ceil(t_new / s) * s;\n\n    err_loc = fmax(err_loc, rndoff);\n    s_error += err_loc;\n  }\n  double err = s_error;\n  hump = hump / normv;\n  return w.t();\n}\n//' Calculates the initial distribution of animal locations.\n//' Assumes uniform distribution relative to transect.\n//'\n//' @param  num_cells vector with number of cells in (total space, x-direction,\n//'     y-direction)\n//' @param  delta spatial and temporal increments (dx, dt)\n//' @param  region_size size of survey region in (x,y) extents\n//'\n//' @return Row vector with i^th entry probability animal in i^th grid cell initially\n// [[Rcpp::export]]\narma::rowvec CalcInitialDistribution(const arma::vec num_cells,\n                                     const arma::vec delta,\n                                     const arma::vec region_size) {\n  arma::rowvec initial_phi = arma::ones<arma::rowvec>(num_cells(0));\n  initial_phi *= delta(0) * delta(0);\n  initial_phi /=  prod(region_size);\n  return(initial_phi);\n}\n//' Transform working parameters (for the optimiser) to natural parameters\n//' @param working_parameter working parameters \n//' @param hzfn hazard function type \n//' @return natural parameters \n// [[Rcpp::export]]\narma::vec Working2Natural(arma::vec working_parameter, int hzfn = 1) {\n  arma::vec parameter = arma::exp(working_parameter);\n  //parameter(1) += 2; \n  return parameter;\n}\n//' Transform natural parameters to unconstrained working parameters\n//' @param parameter natural parameters \n//' @param hzfn hazard function type \n//' @return working parameters \n// [[Rcpp::export]]\narma::vec Natural2Working(arma::vec parameter, int hzfn = 1) {\n  arma::vec working_parameter(parameter);\n  //working_parameter(1) -= 2; \n  working_parameter = arma::log(working_parameter);\n  return working_parameter;\n}\n\n//' Calculates hazard of detection\n//'\n//' @param  x relative x coordinate\n//' @param  y relative y coordinate\n//' @param  dt time increment\n//' @param observer_speed speed of the observer\n//' @param parameter vector of (detection shape, detection scale)\n//' @param  type transect type (0 = line, 1 = point)\n//' @param hzfn hazard function code (see ?hazardfns)\n//'\n//' @return  hazard of detection\n// [[Rcpp::export]]\ndouble CalcHazard(const double x,\n                  const double y,\n                  const double dt,\n                  const double observer_speed,\n                  const arma::vec parameter,\n                  const int type,\n                  const int hzfn) {\n  double hazard = 0;\n  double r0, r1, abeta, abeta2, y1;\n  double s, sx, sy, d, c, k; \n  switch(hzfn) {\n  case 0:\n    // Hayes and Buckland isotropic h(r) = (r/s)^(-2)\n    // parameter = (s, d)\n    s = parameter(0); \n    d = 1; \n    c = pow(s, d); \n    r0 = x * x + y * y;\n    if (type == 1) {\n      hazard = dt * c / pow(r0, 0.5 * d);\n    }\n    else {\n      // assume cannot detect behind observer\n      if (y < 0) return 0;\n      abeta = 0.5 * (d - 1.0);\n      y1 = y - observer_speed * dt;\n      if (y1 < 0) y1 = 0;\n      r1 = x * x  + y1 * y1;\n      if (r1 < 1e-10) return arma::datum::inf;\n      if (fabs(x) < 1e-10) {\n        if (fabs(d - 1) < 1e-10) {\n          hazard = log(sqrt(r1)) - log(sqrt(r0));\n          hazard *= c;\n        } else {\n          hazard = 1.0 / pow(r1, abeta) - 1.0 / pow(r0, abeta);\n          hazard *= c  / (d - 1.0);\n        }\n      } else {\n        hazard = R::pbeta(x * x / r1, abeta, 0.5, 1, 0) - R::pbeta(x * x / r0,\n                          abeta, 0.5, 1, 0);\n        hazard *= R::beta(abeta, 0.5) * c / (2.0 * pow(fabs(x),\n                                             d - 1.0));\n      }\n    }\n    return hazard;\n    break;\n  \n  case 1:\n    // Hayes and Buckland isotropic h(r) = (r/s)^(-d)\n    // parameter = (s, d)\n    s = parameter(0); \n    d = 1 + parameter(1); \n    c = pow(s, d); \n    r0 = x * x + y * y;\n    if (type == 1) {\n      hazard = dt * c / pow(r0, 0.5 * d);\n    }\n    else {\n      // assume cannot detect behind observer\n      if (y < 0) return 0;\n      abeta = 0.5 * (d - 1.0);\n      y1 = y - observer_speed * dt;\n      if (y1 < 0) y1 = 0;\n      r1 = x * x  + y1 * y1;\n      if (r1 < 1e-10) return arma::datum::inf;\n      if (fabs(x) < 1e-10) {\n        if (fabs(d - 1) < 1e-10) {\n          hazard = log(sqrt(r0)) - log(sqrt(r1));\n          hazard *= c;\n        } else {\n          hazard = 1.0 / pow(r1, abeta) - 1.0 / pow(r0, abeta);\n          hazard *= c / (d - 1.0);\n        }\n      } else {\n        hazard = R::pbeta(x * x / r1, abeta, 0.5, 1, 0) - R::pbeta(x * x / r0,\n                          abeta, 0.5, 1, 0);\n        hazard *= R::beta(abeta, 0.5) * c / (2.0 * pow(fabs(x),\n                                                 d - 1.0)); \n      }\n    }\n    return hazard;\n    break;\n\n  case 2:\n    // Hayes and Buckland anisotropic h(r) = (x^2/sx^2 + y^2/sy^2)^(-d/2)\n    // parameter = (sx, sy, d)\n    sx = parameter(0);\n    sy = parameter(1); \n    d = 1 + parameter(2); \n    r0 = (x * x) / (sx * sx) + (y * y) / (sy * sy);\n    if (type == 1) {\n      hazard = dt * pow(r0, -0.5 * d); \n    }\n    else {\n      // assume cannot detect behind observer\n      if (y < 0) return 0;\n      abeta = 0.5 * (d - 1.0);\n      y1 = y - observer_speed * dt;\n      if (y1 < 0) y1 = 0;\n      r1 = (x * x) / (sx * sx)  + (y1 * y1) / (sy * sy);\n      if (r1 < 1e-10) return arma::datum::inf;\n      if (fabs(x) < 1e-10) {\n        if (fabs(d - 1) < 1e-10) {\n          hazard = log(sqrt(y)) - log(sqrt(y1));\n          hazard *= pow(sy, d);\n        } else {\n          hazard = 1.0 / pow(y1, abeta) - 1.0 / pow(y, abeta);\n          hazard *= pow(sy, d) / (d - 1.0);\n        }\n      } else {\n        hazard = R::pbeta(x * x / (sx * sx * r1), abeta, 0.5, 1, 0) - R::pbeta(x * x / (sx * sx * r0),\n                          abeta, 0.5, 1, 0);\n        hazard *= R::beta(abeta, 0.5) * pow(sx, d - 1) * sy / (2.0 * pow(fabs(x),\n                                             d - 1.0));\n      }\n    }\n    return hazard;\n    break;\n    \n  case 3:\n    // Hayes and Buckland shape-anisotropic h(r) = (x^2+(y+k)^2)^(-d/2)\n    // parameter = (s, d, k)\n    s = parameter(0); \n    d = 1 + parameter(1); \n    k = parameter(2); \n    c = pow(s, d); \n    r0 = x * x / (s * s) + (y / s + k) * (y / s + k); \n    if (type == 1) {\n      hazard = dt * c * (1 + k * y / sqrt(r0)) / pow(r0, 0.5 * d);\n    }\n    else {\n      // assume cannot detect behind observer\n      if (y < 0) return 0;\n      abeta = 0.5 * (d - 1.0);\n      y1 = y - observer_speed * dt;\n      if (y1 < 0) y1 = 0;\n      r1 = x * x / (s * s) + (y1 / s + k) * (y1 / s + k); \n      if (r1 < 1e-10) return arma::datum::inf;\n      if (fabs(x) < 1e-10) {\n        if (fabs(d - 1) < 1e-10) {\n          hazard = log(sqrt(y + s * k)) - log(sqrt(y1 + s * k));\n          hazard *= c;\n        } else {\n          hazard = 1.0 / pow(y1 + s * k, abeta) - 1.0 / pow(y + s * k, abeta);\n          hazard *= c / (d - 1.0);\n        }\n      } else {\n        hazard = R::pbeta(x * x / (s * s * r1), abeta, 0.5, 1, 0) - R::pbeta(x * x / (s * s * r0),\n                          abeta, 0.5, 1, 0);\n        hazard *= R::beta(abeta, 0.5) * c / (2.0 * pow(fabs(x), d - 1.0)); \n      }\n    }\n    return hazard;\n    break;\n    \n  case 4:\n    // Hayes and Buckland anisotropic h(r) = (x^2/sx^2 + (y/sy + k)^2)^(-d/2)\n    // parameter = (sx, sy, d, k)\n    sx = parameter(0);\n    sy = parameter(1); \n    d = 1 + parameter(2);\n    k = parameter(3); \n    r0 = (x * x) / (sx * sx) + pow(y / sy + k, 2.0); \n    if (type == 1) {\n      hazard = dt * pow(r0, -0.5 * d); \n    }\n    else {\n      // assume cannot detect behind observer\n      if (y < 0) return 0;\n      abeta = 0.5 * (d - 1.0);\n      y1 = y - observer_speed * dt;\n      if (y1 < 0) y1 = 0;\n      r1 = (x * x) / (sx * sx)  + pow(y1 / sy + k, 2.0); \n      if (r1 < 1e-10) return arma::datum::inf;\n      if (fabs(x) < 1e-10) {\n        if (fabs(d - 1) < 1e-10) {\n          hazard = log(sqrt(y)) - log(sqrt(y1));\n          hazard *= pow(sy, d);\n        } else {\n          hazard = 1.0 / pow(y1, abeta) - 1.0 / pow(y, abeta);\n          hazard *= pow(sy, d) / (d - 1.0);\n        }\n      } else {\n        hazard = R::pbeta(x * x / (sx * sx * r1), abeta, 0.5, 1, 0) - R::pbeta(x * x / (sx * sx * r0),\n                          abeta, 0.5, 1, 0);\n        hazard *= R::beta(abeta, 0.5) * pow(sx, d - 1) * sy / (2.0 * pow(fabs(x),\n                                            d - 1.0));\n      }\n    }\n    return hazard;\n    break;\n\n  default:\n    Rcpp::Rcout << \"error: no hazard specified.\" << std::endl;\n  return -arma::datum::inf;\n  }\n}\n//' Computes the probability of survival for each spatial location\n//'\n//' @param t time step\n//' @param parameter (scale, shape, diffusion) parameter\n//' @param num_cells number of cells in (x, y, all) dimensions\n//' @param delta (dx, dt) vector\n//' @param strip_size size of strip in (x, y) dimensions\n//' @param buffer buffer size\n//' @param observer_speed speed of the observer\n//' @param type transect type\n//' @param hzfn hazard function code\n//' @param nint not used\n//'\n//'  @return row vector of survival probabilities over space\n// [[Rcpp::export]]\narma::rowvec CalcSurvivalPr(const int t,\n                      const arma::vec parameter,\n                      const arma::vec num_cells,\n                      const arma::vec delta,\n                      const arma::vec strip_size,\n                      const double buffer,\n                      const double observer_speed,\n                      const int type,\n                      const int hzfn,\n                      const int nint = 4) {\n\n  arma::rowvec pr_survive = arma::ones<arma::rowvec>(num_cells(0));\n  arma::vec observer_position(GetObserverPosition(t * delta(1), strip_size, buffer, delta, type,\n                                            observer_speed));\n  double x, ix;\n  double y, iy;\n  int s;\n  int ymin = 0; \n  if (type == 0) ymin = floor(observer_position(1) / delta(0)); \n  for (int x_cell = 0; x_cell < num_cells(1); ++x_cell) {\n    for (int y_cell = ymin; y_cell < num_cells(2); ++y_cell) {\n      s = x_cell + num_cells(1) * y_cell;\n      pr_survive(s) = 0; \n      x = x_cell * delta(0) - observer_position(0);\n      y = y_cell * delta(0) - observer_position(1); \n      for (int i = 0; i < nint; ++i) {\n        //for (int j = 0; j < nint; ++j) {\n          ix = x + (i * delta(0)) / nint; \n          //iy = y + (j * delta(0)) / nint; \n          pr_survive(s) += CalcHazard(ix, y, delta(1), observer_speed, parameter, type, hzfn);\n       // }\n      }\n      //pr_survive(s) /= 1.0*nint*nint; \n      pr_survive(s) /= 1.0*nint; \n      pr_survive(s) = exp(-pr_survive(s)); \n    }\n  }\n  return pr_survive;\n}\n\n//' Thins probability distribution by the proportion detected in each grid cell\n//'\n//' @param t time step\n//' @param pr probability distribution over finite grid\n//' @param parameter (scale, shape, diffusion) parameter\n//' @param num_cells number of cells in (x, y, all) dimensions\n//' @param delta (dx, dt) vector\n//' @param strip_size size of strip in (x, y) dimensions\n//' @param buffer buffer width \n//' @param observer_speed speed of the observer\n//' @param type transect type\n//' @param hzfn hazard function code \n//'  \n//'  @return  thinned probability distribution\n// [[Rcpp::export]]\narma::rowvec Detect(const int t,\n                    const arma::rowvec pr,\n                    const arma::vec parameter,\n                    const arma::vec num_cells,\n                    const arma::vec delta,\n                    const arma::vec strip_size,\n                    const double buffer,\n                    const double observer_speed,\n                    const int type,\n                    const int hzfn) {\n  arma::rowvec pr_survive = CalcSurvivalPr(t, parameter, num_cells, delta,\n\t\t  strip_size, buffer, observer_speed, type, hzfn);\n  pr_survive %= pr;\n  return(pr_survive);\n}\n\n//' Compute hazard of each detection within time-step\n//'\n//' @param data (x, y, t) data matrix\n//' @param dt time step\n//' @param transdat transect data matrix\n//' @param parameter (scale, shape, diffusion) parameters\n//' @param observer_speed speed of observer\n//' @param type 1 = point, 0 = line transect\n//' @param hzfn hazard function code (see ?hazardfns)\n//' @return PDF for within-timestep detection\n// [[Rcpp::export]]\ndouble CalcHazardDetected(const arma::mat data,\n                          double dt,\n                          arma::mat transdat,\n                          arma::vec parameter,\n                          double observer_speed,\n                          int type,\n                          const int hzfn) {\n  arma::vec r2, cosang;\n  arma::vec t_remaining = data.col(4) - floor((data.col(4)) / dt) * dt;\n  double log_hazard = 0;\n  for (int i = 0; i < data.n_rows; ++i) {\n    log_hazard -= CalcHazard(data(i, 2), data(i, 3) + t_remaining(i) *\n\t\t    observer_speed, t_remaining(i), observer_speed, parameter, type, hzfn);\n  }\n\n  double s, sx, sy, d, c, k; \n  switch(hzfn) {\n  case 0:\n    s = parameter(0); \n    d = 1; \n    c = pow(s, d); \n    r2 = sum(data.cols(2, 3) % data.cols(2, 3), 1);\n    log_hazard += arma::accu(log(c) - 0.5 * d * log(r2));\n    break;\n  \n  case 1:\n    s = parameter(0); \n    d = 1 + parameter(1); \n    c = pow(s, d); \n    r2 = sum(data.cols(2, 3) % data.cols(2, 3), 1);\n    log_hazard += arma::accu(log(c) - 0.5 * d * log(r2));\n   break;\n\n  case 2:\n    sx = parameter(0); \n    sy = parameter(1); \n    d = 1 + parameter(2);\n    log_hazard += -0.5 * d * arma::accu(log(data.col(2) % data.col(2) / (sx * sx) + data.col(3) % data.col(3) / (sy * sy))); \n    break;\n\n  case 3:\n    s = parameter(0); \n    d = 1 + parameter(1);\n    k = parameter(2); \n    r2 = data.col(2) % data.col(2) / (s * s) + pow(data.col(3) / s + k, 2.0); \n    log_hazard += arma::accu(- 0.5 * d * log(r2));\n    break;\n    \n  case 4:\n    sx = parameter(0); \n    sy = parameter(1); \n    d = 1 + parameter(2);\n    k = parameter(3); \n    r2 = data.col(2) % data.col(2) / (sx * sx) + pow(data.col(3) / sy + k, 2.0); \n    log_hazard += arma::accu(- 0.5 * d * log(r2));\n    break;\n    \n  default:\n    Rcpp::Rcout << \"error: no hazard specified.\" << std::endl;\n    return -arma::datum::inf;\n  }\n  return log_hazard;\n}\n//' Calculates movement model log-likelihood\n//'\n//' @param  sd diffusion\n//' @param  data Rcpp List where each component represent an individual path\n//' and continas a matrix where each row is an observed location (x,y,t)\n//'\n//' @return log-likelihood\n// [[Rcpp::export]]\ndouble CalcMovementLogLikelihood(const double sd, const Rcpp::List data) {\n  double log_likelihood = 0;\n  arma::vec xdiff, ydiff;\n  int ntags = data.size();\n  arma::mat tag;\n  for (int i = 0; i < ntags; ++i) {\n    tag = Rcpp::as<arma::mat>(data(i));\n    arma::vec xdiff = arma::diff(tag.col(0));\n    arma::vec ydiff = arma::diff(tag.col(1));\n    arma::vec tdiff = arma::diff(tag.col(2));\n    log_likelihood -= tag.n_rows * log(2 * M_PI * sd * sd);\n    log_likelihood -= accu(log(tdiff) + (xdiff % xdiff + ydiff % ydiff) / (2 * sd * sd * tdiff));\n  }\n  return log_likelihood;\n}\n//' Computes what grid cells are inside and outside transect\n//'\n//' @param  num_cells number of cells in (total, x, y) direction \n//' @param strip_size size of strip in (x,y) directions\n//' @param dx grid cell size \n//' @param w for lines, half-width, for points radius \n//' @param ymax maximum forward distance for lines \n//' @param buffer distance\n//' @param type =0 for lines, =1 for points \n//'\n//' @return vector with 1 for each grid cell inside and 0 otherwise \n// [[Rcpp::export]]\narma::rowvec InTransect(const arma::vec num_cells,\n                        const arma::vec strip_size, \n                        const double dx, \n                        const double w,\n                        const double ymax, \n                        const double buffer, \n                        const int type) {\n  arma::rowvec intrans = arma::zeros<arma::rowvec>(num_cells(0)); \n  double x, y, r; \n  double top, bot, lenx, leny; \n  if (type == 0) {\n    for (int i = 0; i < num_cells(1); ++i) {\n      x = i * dx - strip_size(0) * 0.5;\n      top = fmin(x + dx, w);\n      bot = fmax(x, -w);\n      lenx = top - bot; \n      if (lenx < 0) lenx = 0; \n      for (int j = 0; j < num_cells(2); ++j) {\n        y = j * dx - buffer;\n        top = fmin(y + dx, ymax); \n        bot = fmax(y, 0); \n        leny = top - bot; \n        if (leny < 0) leny = 0; \n        intrans(i + j * num_cells(1)) = lenx * leny / (dx * dx);\n      }\n    }\n  } else {\n    for (int i = 0; i < num_cells(1); ++i) {\n      x = i * dx - strip_size(0) * 0.5; \n      for (int j = 0; j < num_cells(2); ++j) {\n        y = j * dx - strip_size(1) * 0.5; \n        r = x * x + y * y; \n        if (r <= w*w) intrans(i + j * num_cells(1)) = 1; \n      }\n    }\n  }\n  return intrans; \n}\n\n\n//' Computes negative log-likelihood of moveDs model\n//'\n//' @param  working_parameter unconstrained version of parameter vector containing\n//'     (detection shape, detection scale, diffusion sd)\n//' @param start start value for parameters on natural scale \n//' @param  data matrix with (trans id, grid cell,t) distance sampling survey data (assumed to be ordered by transect and time)\n//' @param  transdat matrix with (stripsize(1), numcells in y, totaltimestep, number of observations)\n//' @param  auxiliary_data vector containing (area x extent, area y extent, strip width, transect_type)\n//' @param  delta vector of (dx, dt) spacetime increments\n//' @param  num_cells number of cells in (total space, x-direction, y-direction)\n//' @param  T total time of survey for longest transect\n//' @param  ymax maximum length of a transect\n//' @param  buffer buffer distance\n//' @param  movement_data field object where each component represents an individual\n//'   path and contains a matrix where each row is an observed location (x,y,t)\n//' @param fixed_sd if move_method = 2\n//' @param hzfn hazard function code (see ?hazardfns)\n//' @param  move_method 0 = 2d CDS model, 1 = 2d MDS model (movement estimated),\n//'    2 = 2d MDS model (movement fixed)\n//' @param  print if TRUE then print likelihood and parmeters after evaluation\n//' @param con parameters are constrained to be between 1/con * start value and \n//' con * start value \n//'\n//' @return  negative log-likelihood\n// [[Rcpp::export]]\ndouble NegativeLogLikelihood(const arma::vec working_parameter,\n                             const arma::vec start, \n                             const arma::mat data,\n                             const arma::mat transdat,\n                             const arma::vec auxiliary_data,\n                             const arma::vec delta,\n                             const arma::vec num_cells,\n                             const int T,\n                             const double ymax,\n                             const double buffer,\n                             const Rcpp::List movement_data,\n                             const double fixed_sd = 0,\n                             const int hzfn = 1,\n                             const int move_method = 1,\n                             const bool print = false,\n                             const double con = 100) {\n  // unpack auxiliary data\n  arma::vec region_size(auxiliary_data.rows(0, 1));\n  arma::vec strip_size(2);\n  strip_size(0) = 2 * auxiliary_data(2) + 2 * buffer;\n  strip_size(1) = ymax + 2 * buffer;\n  double observer_speed = auxiliary_data(3);\n  int num_transects = transdat.n_rows;\n  int transect_type = auxiliary_data(4);\n  double dx = delta(0);\n  double dt = delta(1);\n  // unpack parameters\n  arma::vec parameter = Working2Natural(working_parameter, hzfn);\n  int npar = parameter.n_elem;\n  // constraints \n  for (int p = 0; p < npar; ++p) {\n    if (parameter(p) > con * start(p)) return arma::datum::inf; \n    if (parameter(p) < start(p) / con) return arma::datum::inf; \n  }\n  double sd = 0;\n  if (move_method == 1) sd = parameter(npar - 1);\n  if (move_method == 2) sd = fixed_sd;\n  // setup variables\n  int curtrans = 0;\n  int curobs = 0;\n  double pr_survived;\n  double pr_outside;\n  double accu_hazard;\n  double pdet; \n  double llk = 0;\n  // calculate initial probability in each grid cell\n  arma::rowvec pr_t = CalcInitialDistribution(num_cells, delta, region_size);\n  arma::rowvec old_pr_t(pr_t);\n  // probability outside buffer region at t = 0\n  pr_outside = 1.0 - arma::prod(strip_size) / arma::prod(region_size);\n  // compute movement matrices for survey\n  arma::sp_mat trm;\n  arma::rowvec flux = arma::ones<arma::rowvec>(num_cells(0));\n  if (move_method > 0) {\n    trm = CalcTrm(num_cells, sd, dx);\n    flux = Diffuse(trm.t(), flux, dt, num_cells);\n    flux = 1.0 - flux;\n  }\n  double num_boundary_states = floor(prod(region_size) / (dx * dx)) - num_cells(0);\n  // intialise variables\n  double curt = floor((data(curobs, 4)) / dt);\n  if (curt < 0) curt = 0; \n  if ((curt > T - 1) & (curt < T + 1)) curt = T - 1; \n  int endtime = transdat(curtrans, 2);\n  arma::rowvec intrans = InTransect(num_cells, strip_size, dx, auxiliary_data(2), ymax, buffer, transect_type); \n  accu_hazard = 0;\n  pdet = 0; \n  double diff = 0; \n  // compute HMM approximation\n  for (int t = 0; t < T; ++t) {\n    Rcpp::checkUserInterrupt();\n    // add to pr_obs, the observations that occur during time interval t\n    while (t == curt) {\n      if (data(curobs, 1) > num_cells(0)) {\n        Rcpp::Rcout << \"Warning: buffer region too small to include all detections.\" << std::endl;\n      } else {\n        llk += log(pr_t(data(curobs, 1))) + accu_hazard - log(dx * dx);\n      }\n      ++curobs;\n      if (curobs > data.n_rows - 1) {\n        curt = T + 1;\n      } else {\n        curt = floor((data(curobs, 4)) / dt);\n        if (curt < 0) curt = 0;\n        if ((curt > T - 1) & (curt < T + 1)) curt = T - 1; \n      }\n    }\n    // thin pr_t by those that are detected\n    diff = 0; \n    diff += arma::accu(pr_t % intrans); \n    pr_t = Detect(t, pr_t, parameter, num_cells, delta, strip_size, buffer, observer_speed, transect_type, hzfn);\n    diff -= arma::accu(pr_t % intrans); \n    pdet += diff * exp(accu_hazard); \n    if (arma::accu(pr_t) < 1e-10) return(arma::datum::inf);\n    // move animals \n    if (move_method > 0) {\n      old_pr_t = pr_t;\n      //move animals that are inside strip\n      try {\n        pr_t = Diffuse(trm, pr_t, dt, num_cells);\n      } catch(...) {\n        return arma::datum::inf; \n      }\n      //move animals outside strip that come into strip\n      pr_t += flux * pr_outside / num_boundary_states;\n      //account for transversal of boundary\n      pr_outside += accu(old_pr_t % flux) - accu(flux) * pr_outside / num_boundary_states;\n    }\n    // add contribution to accu_hazard\n    pr_survived = accu(pr_t) + pr_outside;\n    accu_hazard += log(pr_survived);\n    // scale to avoid underflow\n    pr_t /= pr_survived;\n    pr_outside /=  pr_survived;\n    // if transect ends divide by conditional probability\n    while (endtime == t) {\n     llk -= transdat(curtrans, 1) * log(pdet);\n     ++curtrans;\n     if (curtrans > transdat.n_rows - 1) {\n       endtime = T + 1;\n     } else {\n       endtime = transdat(curtrans, 2);\n     }\n    }\n }\n // add hazard of detections\n llk += CalcHazardDetected(data, dt, transdat, parameter, observer_speed, transect_type, hzfn);\n double movement_log_likelihood = 0;\n if (move_method == 1) movement_log_likelihood = CalcMovementLogLikelihood(sd, movement_data);\n double negative_log_likelihood = -llk - movement_log_likelihood;\n if (print) {\n   int old_precision = Rcpp::Rcout.precision();\n   Rcpp::Rcout.precision(4);\n   Rcpp::Rcout << -negative_log_likelihood << \"   \";\n   for (int par = 0; par < npar; ++par) Rcpp::Rcout << parameter(par) << \"   \";\n   Rcpp::Rcout << std::endl;\n }\n return negative_log_likelihood;\n}\n//' Computes covered area for entire survey\n//'\n//' @param  working_parameter unconstrained version of parameter vector containing\n//'     (detection shape, detection scale, diffusion sd)\n//' @param  transdat matrix with (stripsize(1), numcells in y, totaltimestep, number of observations)\n//' @param  auxiliary_data vector containing (area x extent, area y extent, strip width, transect_type)\n//' @param  delta vector of (dx, dt) spacetime increments\n//' @param  num_cells number of cells in (total space, x-direction, y-direction)\n//' @param  T total time of survey for longest transect\n//' @param  ymax maximum length of a transect\n//' @param  buffer buffer distance\n//' @param fixed_sd if move_method = 2\n//' @param hzfn hazard function code (see ?hazardfns)\n//' @param  move_method 0 = 2d CDS model, 1 = 2d MDS model (movement estimated),\n//'    2 = 2d MDS model (movement fixed)\n//'\n//' @return  negative log-likelihood\n//' @return covered area\n//' unpack auxiliary data\n// [[Rcpp::export]]\ndouble GetPenc(const arma::vec working_parameter,\n               const arma::mat transdat,\n               const arma::vec auxiliary_data,\n               const arma::vec delta,\n               const arma::vec num_cells,\n               const int T,\n               const double ymax,\n               const double buffer,\n               const double fixed_sd,\n               const int hzfn,\n               int move_method) {\n\n  arma::vec region_size(auxiliary_data.rows(0, 1));\n  arma::vec strip_size(2);\n  strip_size(0) = 2 * auxiliary_data(2) + 2 * buffer;\n  strip_size(1) = ymax + 2 * buffer;\n  double observer_speed = auxiliary_data(3);\n  int num_transects = transdat.n_rows;\n  int transect_type = auxiliary_data(4);\n  double dx = delta(0);\n  double dt = delta(1);\n  // unpack parameters\n  arma::vec parameter = Working2Natural(working_parameter, hzfn);\n  int npar = parameter.n_elem;\n  double sd = 0;\n  if (move_method == 1) sd = parameter(npar - 1);\n  if (move_method == 2) sd = fixed_sd;\n  // setup variables\n  int curtrans = 0;\n  int curobs = 0;\n  double pr_survived;\n  double pr_outside;\n  double accu_hazard;\n  double pdet; \n  arma::vec penc(num_transects); penc.zeros();\n  // calculate initial probability in each grid cell\n  arma::rowvec pr_t = CalcInitialDistribution(num_cells, delta, region_size);\n  arma::rowvec old_pr_t(pr_t);\n  // probability outside buffer region at t = 0\n  pr_outside = 1.0 - arma::prod(strip_size) / arma::prod(region_size);\n  // compute movement matrices for survey\n  arma::sp_mat trm;\n  arma::rowvec flux = arma::ones<arma::rowvec>(num_cells(0));\n  if (move_method > 0) {\n    trm = CalcTrm(num_cells, sd, dx);\n    flux = Diffuse(trm.t(), flux, dt, num_cells);\n    flux = 1.0 - flux;\n  }\n  double num_boundary_states = floor(prod(region_size) / (dx * dx)) - num_cells(0);\n  // intialise variables\n  int endtime = transdat(curtrans, 2);\n  arma::rowvec intrans = InTransect(num_cells, strip_size, dx, auxiliary_data(2), ymax, buffer, transect_type); \n  accu_hazard = 0;\n  pdet = 0; \n  double diff; \n  // compute HMM approximation\n  for (int t = 0; t < T; ++t) {\n    Rcpp::checkUserInterrupt();\n    // thin pr_t by those that are detected\n    diff = 0; \n    diff += arma::accu(pr_t % intrans); \n    pr_t = Detect(t, pr_t, parameter, num_cells, delta, strip_size, buffer, observer_speed, transect_type, hzfn);\n    diff -= arma::accu(pr_t % intrans); \n    pdet += diff * exp(accu_hazard); \n    // move animals\n    if (move_method > 0) {\n      old_pr_t = pr_t;\n      // move animals that are inside strip\n      pr_t = Diffuse(trm, pr_t, dt, num_cells);\n      // move animals outside strip that come into strip\n      pr_t += flux * pr_outside / num_boundary_states;\n      // account for transversal of boundary\n      pr_outside += accu(old_pr_t % flux) - accu(flux) * pr_outside / num_boundary_states;\n    }\n    // add contribution to accu_hazard\n    pr_survived = accu(pr_t) + pr_outside;\n    accu_hazard += log(pr_survived);\n    // scale to avoid underflow\n    pr_t /= pr_survived;\n    pr_outside /=  pr_survived;\n    // if transect ends divide by conditional probability\n    while (endtime == t) {\n      penc(curtrans) = pdet;\n      ++curtrans;\n      if (curtrans > transdat.n_rows - 1) {\n        endtime = T + 1;\n      } else {\n        endtime = transdat(curtrans, 2);\n      }\n    }\n  }\n  return arma::accu(penc);\n}\n//' Computes PDF of observed detections for each (x,y) cell around the observer.\n//'\n//' @param  working_parameter unconstrained version of parameter vector containing\n//'     (detection shape, detection scale, diffusion sd)\n//' @param range to compute out to in x and y directions \n//' @param  transdat matrix with (stripsize(1), numcells in y, totaltimestep, number of observations)\n//' @param  auxiliary_data vector containing (area x extent, area y extent, strip width, transect_type)\n//' @param  delta vector of (dx, dt) spacetime increments\n//' @param  num_cells number of cells in (total space, x-direction, y-direction)\n//' @param  T total time of survey for longest transect\n//' @param  ymax maximum length of a transect\n//' @param  buffer buffer distance\n//' @param fixed_sd if move_method = 2\n//' @param hzfn hazard function code (see ?hazardfns)\n//' @param  move_method 0 = 2d CDS model, 1 = 2d MDS model (movement estimated),\n//'    2 = 2d MDS model (movement fixed)\n//'\n//' @return  matrix where (i,j) entry is cell i*dx perpendicular and j*dx forward of\n//'   observer\n//' unpack auxiliary data\n// [[Rcpp::export]]\narma::mat GetHist(const arma::vec working_parameter,\n               const arma::vec range,\n               const arma::mat transdat,\n               const arma::vec auxiliary_data,\n               const arma::vec delta,\n               const arma::vec num_cells,\n               const int T,\n               const double ymax,\n               const double buffer,\n               const double fixed_sd = 0,\n               const int hzfn = 1,\n               int move_method = 1) {\n\n  arma::vec region_size(auxiliary_data.rows(0, 1));\n  arma::vec strip_size(2);\n  strip_size(0) = 2 * auxiliary_data(2) + 2 * buffer;\n  strip_size(1) = ymax + 2 * buffer;\n  double observer_speed = auxiliary_data(3);\n  int num_transects = transdat.n_rows;\n  int transect_type = auxiliary_data(4);\n  double dx = delta(0);\n  double dt = delta(1);\n  // unpack parameters\n  arma::vec parameter = Working2Natural(working_parameter, hzfn);\n  int npar = parameter.n_elem;\n  double sd = 0;\n  if (move_method == 1) sd = parameter(npar - 1);\n  if (move_method == 2) sd = fixed_sd;\n  // setup variables\n  int curtrans = 0;\n  int curobs = 0;\n  double pr_survived;\n  double pr_outside;\n  double accu_hazard;\n  arma::vec obspos;\n  int sobs;\n  int smax;\n  int Nperp = floor(2 * range(0) / dx);\n  int Nforw = floor(range(1) / dx);\n  arma::rowvec count(num_cells(1) * Nforw); count.zeros();\n  arma::rowvec accum(num_cells(1) * Nforw); accum.zeros();\n  // nalive is the number of transect still being surveyed in the meta-transect\n  int nalive = num_transects;\n  // calculate initial probability in each grid cell\n  arma::rowvec pr_t = CalcInitialDistribution(num_cells, delta, region_size);\n  arma::rowvec old_pr_t(pr_t);\n  // probability outside buffer region at t = 0\n  pr_outside = 1.0 - arma::prod(strip_size) / arma::prod(region_size);\n  // compute movement matrices for survey\n  arma::sp_mat trm;\n  arma::rowvec flux = arma::ones<arma::rowvec>(num_cells(0));\n  if (move_method > 0) {\n    trm = CalcTrm(num_cells, sd, dx);\n    flux = Diffuse(trm.t(), flux, dt, num_cells);\n    flux = 1.0 - flux;\n  }\n  double num_boundary_states = floor(prod(region_size) / (dx * dx)) - num_cells(0);\n  arma::rowvec intrans = InTransect(num_cells, strip_size, dx, auxiliary_data(2), ymax, buffer, transect_type); \n  // intialise variables\n  int endtime = transdat(curtrans, 2);\n  accu_hazard = 0;\n  // compute HMM approximation\n  for (int t = 0; t < T; ++t) {\n    Rcpp::checkUserInterrupt();\n    obspos = GetObserverPosition(t * dt, strip_size, buffer, delta, transect_type, observer_speed);\n    // observer grid cell\n    sobs = num_cells(1) * floor(obspos(1) / dx);\n    // sum from that point to 2 * Nperp * Nforw state or max size\n    smax = sobs + num_cells(1) * Nforw - 1;\n    if (smax >= num_cells(0)) smax = num_cells(0) - 1;\n    if (sobs >= num_cells(0)) sobs = num_cells(0) - 1;\n    // add in all animals present in cell\n    count.cols(0, smax - sobs) += exp(log(pr_t.cols(sobs, smax) % intrans.cols(sobs, smax)) + accu_hazard);\n    // thin pr_t by those that are detected\n    pr_t = Detect(t, pr_t, parameter, num_cells, delta, strip_size, buffer, observer_speed, transect_type, hzfn);\n    // subtract those animals still present (failed to be detected)\n    count.cols(0, smax - sobs) -= exp(log(pr_t.cols(sobs, smax) % intrans.cols(sobs, smax)) + accu_hazard);\n    if (move_method > 0) {\n      old_pr_t = pr_t;\n      // move animals that are inside strip\n      pr_t = Diffuse(trm, pr_t, dt, num_cells);\n      // move animals outside strip that come into strip\n      pr_t += flux * pr_outside / num_boundary_states;\n      // account for transversal of boundary\n      pr_outside += accu(old_pr_t % flux) - accu(flux) * pr_outside / num_boundary_states;\n    }\n    // add contribution to accu_hazard\n    pr_survived = accu(pr_t) + pr_outside;\n    accu_hazard += log(pr_survived);\n    // scale to avoid underflow\n    pr_t /= pr_survived;\n    pr_outside /=  pr_survived;\n    // if transect ends divide by conditional probability\n    while (endtime == t) {\n      accum += count; \n      --nalive;\n      ++curtrans;\n      if (curtrans > transdat.n_rows - 1) {\n        endtime = T + 1;\n      } else {\n        endtime = transdat(curtrans, 2);\n      }\n    }\n  }\n  return accum;\n}\n", "meta": {"hexsha": "436cd11ff3f0bb55efe44f950287843a0f7340e2", "size": 41050, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/moveds.cc", "max_stars_repo_name": "r-glennie/moveds", "max_stars_repo_head_hexsha": "3fb04969cd0548e65b230ee4dcfb750ee1560b46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/moveds.cc", "max_issues_repo_name": "r-glennie/moveds", "max_issues_repo_head_hexsha": "3fb04969cd0548e65b230ee4dcfb750ee1560b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/moveds.cc", "max_forks_repo_name": "r-glennie/moveds", "max_forks_repo_head_hexsha": "3fb04969cd0548e65b230ee4dcfb750ee1560b46", "max_forks_repo_licenses": ["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.3274336283, "max_line_length": 127, "alphanum_fraction": 0.570864799, "num_tokens": 12426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5476929457672746}}
{"text": "#define BOOST_TEST_MODULE \"test_matrix\"\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/Matrix.hpp>\n#include <random>\n#include <cstdint>\n\nconstexpr std::uint32_t seed = 123456789;\nconstexpr std::size_t   N    = 10000;\ntypedef boost::mpl::list<double, float> test_targets;\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, 8)));}\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(add_matrix_3x3, Real, test_targets)\n{\n    using namespace mjolnir;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-1.0, 1.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Matrix<Real, 3, 3> lhs(\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt)\n            ), rhs(\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt)\n            );\n        const auto add = lhs + rhs;\n\n        BOOST_TEST(add(0, 0) == lhs(0, 0) + rhs(0, 0), test::tolerance<Real>());\n        BOOST_TEST(add(0, 1) == lhs(0, 1) + rhs(0, 1), test::tolerance<Real>());\n        BOOST_TEST(add(0, 2) == lhs(0, 2) + rhs(0, 2), test::tolerance<Real>());\n        BOOST_TEST(add(1, 0) == lhs(1, 0) + rhs(1, 0), test::tolerance<Real>());\n        BOOST_TEST(add(1, 1) == lhs(1, 1) + rhs(1, 1), test::tolerance<Real>());\n        BOOST_TEST(add(1, 2) == lhs(1, 2) + rhs(1, 2), test::tolerance<Real>());\n        BOOST_TEST(add(2, 0) == lhs(2, 0) + rhs(2, 0), test::tolerance<Real>());\n        BOOST_TEST(add(2, 1) == lhs(2, 1) + rhs(2, 1), test::tolerance<Real>());\n        BOOST_TEST(add(2, 2) == lhs(2, 2) + rhs(2, 2), test::tolerance<Real>());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(sub_matrix_3x3, Real, test_targets)\n{\n    using namespace mjolnir;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-1.0, 1.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Matrix<Real, 3, 3> lhs(\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt)\n            ), rhs(\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt)\n            );\n        const auto sub = lhs - rhs;\n\n        BOOST_TEST(sub(0, 0) == lhs(0, 0) - rhs(0, 0), test::tolerance<Real>());\n        BOOST_TEST(sub(0, 1) == lhs(0, 1) - rhs(0, 1), test::tolerance<Real>());\n        BOOST_TEST(sub(0, 2) == lhs(0, 2) - rhs(0, 2), test::tolerance<Real>());\n        BOOST_TEST(sub(1, 0) == lhs(1, 0) - rhs(1, 0), test::tolerance<Real>());\n        BOOST_TEST(sub(1, 1) == lhs(1, 1) - rhs(1, 1), test::tolerance<Real>());\n        BOOST_TEST(sub(1, 2) == lhs(1, 2) - rhs(1, 2), test::tolerance<Real>());\n        BOOST_TEST(sub(2, 0) == lhs(2, 0) - rhs(2, 0), test::tolerance<Real>());\n        BOOST_TEST(sub(2, 1) == lhs(2, 1) - rhs(2, 1), test::tolerance<Real>());\n        BOOST_TEST(sub(2, 2) == lhs(2, 2) - rhs(2, 2), test::tolerance<Real>());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(scalar_mul_matrix_3x3, Real, test_targets)\n{\n    using namespace mjolnir;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-1.0, 1.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const Real lhs = uni(mt);\n        const math::Matrix<Real, 3, 3> rhs(\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt)\n            );\n        const auto mul = lhs * rhs;\n\n        BOOST_TEST(mul(0, 0) == lhs * rhs(0, 0), test::tolerance<Real>());\n        BOOST_TEST(mul(0, 1) == lhs * rhs(0, 1), test::tolerance<Real>());\n        BOOST_TEST(mul(0, 2) == lhs * rhs(0, 2), test::tolerance<Real>());\n        BOOST_TEST(mul(1, 0) == lhs * rhs(1, 0), test::tolerance<Real>());\n        BOOST_TEST(mul(1, 1) == lhs * rhs(1, 1), test::tolerance<Real>());\n        BOOST_TEST(mul(1, 2) == lhs * rhs(1, 2), test::tolerance<Real>());\n        BOOST_TEST(mul(2, 0) == lhs * rhs(2, 0), test::tolerance<Real>());\n        BOOST_TEST(mul(2, 1) == lhs * rhs(2, 1), test::tolerance<Real>());\n        BOOST_TEST(mul(2, 2) == lhs * rhs(2, 2), test::tolerance<Real>());\n    }\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Matrix<Real, 3, 3> lhs(\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt)\n            );\n        const Real rhs = uni(mt);\n        const auto mul = lhs * rhs;\n\n        BOOST_TEST(mul(0, 0) == lhs(0, 0) * rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(0, 1) == lhs(0, 1) * rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(0, 2) == lhs(0, 2) * rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(1, 0) == lhs(1, 0) * rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(1, 1) == lhs(1, 1) * rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(1, 2) == lhs(1, 2) * rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(2, 0) == lhs(2, 0) * rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(2, 1) == lhs(2, 1) * rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(2, 2) == lhs(2, 2) * rhs, test::tolerance<Real>());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(scalar_div_matrix_3x3, Real, test_targets)\n{\n    using namespace mjolnir;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-1.0, 1.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Matrix<Real, 3, 3> lhs(\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt)\n            );\n        const Real rhs = uni(mt);\n        const auto mul = lhs / rhs;\n\n        BOOST_TEST(mul(0, 0) == lhs(0, 0) / rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(0, 1) == lhs(0, 1) / rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(0, 2) == lhs(0, 2) / rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(1, 0) == lhs(1, 0) / rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(1, 1) == lhs(1, 1) / rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(1, 2) == lhs(1, 2) / rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(2, 0) == lhs(2, 0) / rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(2, 1) == lhs(2, 1) / rhs, test::tolerance<Real>());\n        BOOST_TEST(mul(2, 2) == lhs(2, 2) / rhs, test::tolerance<Real>());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(mul_matrix_3x3, Real, test_targets)\n{\n    using namespace mjolnir;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-1.0, 1.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Matrix<Real, 3, 3> lhs(\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt)\n            ), rhs(\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt)\n            );\n        const auto mul = lhs * rhs;\n\n        for(std::size_t i=0; i<3; ++i)\n        {\n            for(std::size_t j=0; j<3; ++j)\n            {\n                Real sum = 0.;\n                for(std::size_t k=0; k<3; ++k)\n                {\n                    sum += lhs(i, k) * rhs(k, j);\n                }\n                BOOST_TEST(mul(i, j) == sum, test::tolerance<Real>());\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(matrix_3x3_inverse, Real, test_targets)\n{\n    using namespace mjolnir;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<Real> uni(-1.0, 1.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const math::Matrix<Real, 3, 3> lhs(\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt),\n                uni(mt), uni(mt), uni(mt)\n            );\n        if(determinant(lhs) == 0.0)\n        {\n            continue;\n        }\n\n        const auto inv = inverse(lhs);\n        const auto unit1 = lhs * inv;\n        const auto unit2 = inv * lhs;\n\n        BOOST_TEST(unit1(0, 0) == static_cast<Real>(1.0), test::tolerance<Real>());\n        BOOST_TEST(unit1(1, 1) == static_cast<Real>(1.0), test::tolerance<Real>());\n        BOOST_TEST(unit1(2, 2) == static_cast<Real>(1.0), test::tolerance<Real>());\n        BOOST_TEST(unit1(0, 1) == static_cast<Real>(0.0), test::tolerance<Real>());\n        BOOST_TEST(unit1(0, 2) == static_cast<Real>(0.0), test::tolerance<Real>());\n        BOOST_TEST(unit1(1, 0) == static_cast<Real>(0.0), test::tolerance<Real>());\n        BOOST_TEST(unit1(1, 2) == static_cast<Real>(0.0), test::tolerance<Real>());\n        BOOST_TEST(unit1(2, 0) == static_cast<Real>(0.0), test::tolerance<Real>());\n        BOOST_TEST(unit1(2, 1) == static_cast<Real>(0.0), test::tolerance<Real>());\n\n        BOOST_TEST(unit2(0, 0) == static_cast<Real>(1.0), test::tolerance<Real>());\n        BOOST_TEST(unit2(1, 1) == static_cast<Real>(1.0), test::tolerance<Real>());\n        BOOST_TEST(unit2(2, 2) == static_cast<Real>(1.0), test::tolerance<Real>());\n        BOOST_TEST(unit2(0, 1) == static_cast<Real>(0.0), test::tolerance<Real>());\n        BOOST_TEST(unit2(0, 2) == static_cast<Real>(0.0), test::tolerance<Real>());\n        BOOST_TEST(unit2(1, 0) == static_cast<Real>(0.0), test::tolerance<Real>());\n        BOOST_TEST(unit2(1, 2) == static_cast<Real>(0.0), test::tolerance<Real>());\n        BOOST_TEST(unit2(2, 0) == static_cast<Real>(0.0), test::tolerance<Real>());\n        BOOST_TEST(unit2(2, 1) == static_cast<Real>(0.0), test::tolerance<Real>());\n    }\n}\n\n", "meta": {"hexsha": "a4dba7bf62768e08656b19f1474df2d94a9b4d04", "size": 10139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_matrix.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_matrix.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_matrix.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": 39.4513618677, "max_line_length": 83, "alphanum_fraction": 0.5425584377, "num_tokens": 3242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5476929395803503}}
{"text": "/*    Copyright (c) 2010-2018, 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 *    References\n *      PyKEP toolbox, Dario Izzo, ESA Advanced Concepts Team.\n *      Richard H. An Introduction to the Mathematics and Methods of Astrodynamics, Revised\n *          Edition.\n *      Battin, AIAA Education Series.\n *\n */\n\n#include <cmath>\n\n#include <boost/math/special_functions.hpp> // for asinh and acosh\n\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\n#include \"Tudat/Astrodynamics/MissionSegments/multiRevolutionLambertTargeterIzzo.h\"\n#include \"Tudat/Mathematics/BasicMathematics/convergenceException.h\"\n\nnamespace tudat\n{\nnamespace mission_segments\n{\n\n//! Compute solution for N revolutions and branch.\nvoid MultiRevolutionLambertTargeterIzzo::computeForRevolutionsAndBranch(\n        const int aNumberOfRevolutions, const bool aIsRightBranch )\n{\n    // Adjust parameters for new solution\n    numberOfRevolutions = aNumberOfRevolutions;\n    isRightBranch = aIsRightBranch;\n\n    // Check whether number of revolutions is possible\n    sanityCheckNumberOfRevolutions( );\n\n    // Execute problem solving for new solution\n    execute( );\n}\n\n//! Get maximum number of revolutions calculated.\nint MultiRevolutionLambertTargeterIzzo::getMaximumNumberOfRevolutions( )\n{\n    if ( !solved )\n    {\n        transformDimensions( );\n        sanityCheckNumberOfRevolutions( );\n    }\n\n    return maximumNumberOfRevolutions;\n}\n\n//! Sanity check number of revolutions.\nvoid MultiRevolutionLambertTargeterIzzo::sanityCheckNumberOfRevolutions( )\n{\n    // If not yet defined, calculate number of revolutions possible.\n    if ( maximumNumberOfRevolutions == NO_MAXIMUM_REVOLUTIONS )\n    {\n        // Temporarily store specified number, as numberOfRevolutions is needed to calculate max\n        // (this is a tricky way to work, but on the other hand this makes this approach decidedly\n        // different from PyKEP routines and it also happens only once per object).\n        int copyOfOriginalNumberOfRevolutions = numberOfRevolutions;\n\n        // Calculate first guess of maximum, by dividing the time of flight of the minimum energy\n        // ellipse by the normalized time of flight.\n        numberOfRevolutions = static_cast< int >(\n                    normalizedTimeOfFlight / (\n                        mathematical_constants::PI / 2.0\n                        * std::sqrt( 2.0 * normalizedSemiPerimeter\n                                     * normalizedSemiPerimeter\n                                     * normalizedSemiPerimeter ) ) );\n\n        // If the current guess for the maximum is non-zero, then additional analysis is required to\n        // determine the correct maximum.\n        if( numberOfRevolutions != 0)\n        {\n            // The following try-block is meant to check whether the solution converges or not. If\n            // the current guess for the maximum number of revolutions is correct, then the problem\n            // will converge. If it does not, an exception will be thrown stating that it did not\n            // converge. Catching this exception allows to decrease the guess only when the\n            // exception occurs, and not under other circumstances.\n            try\n            {\n                // Compute root (no further information is required)\n                computeRootTimeOfFlight();\n            }\n            catch( basic_mathematics::ConvergenceException )\n            {\n                // If the rootfinder did not converge, then the current guess is wrong and needs to\n                // be decreased\n                numberOfRevolutions--;\n            }\n        }\n        // No further analysis is needed of the current guess is equal to zero.\n\n        // Maximum is now found.\n        maximumNumberOfRevolutions = numberOfRevolutions;\n\n        // Reinstating original number of revolutions specified.\n        numberOfRevolutions = copyOfOriginalNumberOfRevolutions;\n    }\n\n    // Default: compare maximum with specified number of revolutions.\n    // If specified is larger than maximum, no solution is possible.\n    if ( numberOfRevolutions > maximumNumberOfRevolutions )\n    {\n        // Throw exception.\n        throw std::runtime_error(  \"Number of revolutions specified in Lambert problem is larger than possible. Specified number of revolutions is \" +\n                                   std::to_string( numberOfRevolutions )  + \" while the maximum is \" +\n                                   std::to_string( maximumNumberOfRevolutions ) );\n    }\n    // Else, nothing wrong.\n}\n\n//! Execute solving procedure (for multiple revolutions).\nvoid MultiRevolutionLambertTargeterIzzo::execute( )\n{\n    // Sanity checks.\n    sanityCheckTimeOfFlight( );\n    sanityCheckGravitationalParameter( );\n\n    // Transform dimensions.\n    transformDimensions( );\n\n    /*// Sanity check for number of revolutions (must be after dimension removal).\n    sanityCheckNumberOfRevolutions( );*/\n\n    if ( numberOfRevolutions == 0 )\n    {\n        // call base class function that works on zero revolutions.\n        ZeroRevolutionLambertTargeterIzzo::execute( );\n    }\n    else\n    {\n        // Solve multi-rev root.\n        double multipleRevolutionXParameter = computeRootTimeOfFlight( );\n\n        // Reconstruct velocities.\n        computeVelocities( multipleRevolutionXParameter );\n    }\n\n    solved = true;\n}\n\n//! Compute time-of-flight using Lagrange's equation (for multiple revolutions).\ndouble MultiRevolutionLambertTargeterIzzo::computeTimeOfFlight( const double xParameter )\n{\n    // Determine semi-major axis.\n    const double semiMajorAxis = normalizedMinimumEnergySemiMajorAxis\n            / ( 1.0 - xParameter * xParameter );\n\n    // If x < 1, the solution is an ellipse.\n    if ( xParameter < 1.0 )\n    {\n        // Alpha parameter in Lagrange's equation (no explanation available).\n        const double alphaParameter = 2.0 * std::acos( xParameter );\n\n        // Beta parameter in Lagrange's equation (no explanation available).\n        double betaParameter;\n\n        // If long transfer arc.\n        if ( isLongway )\n        {\n            betaParameter = -2.0 * std::asin(\n                        std::sqrt( ( normalizedSemiPerimeter - normalizedChord )\n                                   / ( 2.0 * semiMajorAxis ) ) );\n        }\n        // Otherwise short transfer arc.\n        else\n        {\n            betaParameter = 2.0 * std::asin(\n                        std::sqrt( ( normalizedSemiPerimeter - normalizedChord )\n                                   / ( 2.0 * semiMajorAxis ) ) );\n        }\n\n        // Time-of-flight according to Lagrange including multiple revolutions.\n        const double timeOfFlight = semiMajorAxis * std::sqrt( semiMajorAxis ) *\n                ( ( alphaParameter - std::sin( alphaParameter ) )\n                  - ( betaParameter - std::sin( betaParameter ) )\n                  + 2.0 * mathematical_constants::PI\n                  * numberOfRevolutions );\n\n        return timeOfFlight;\n    }\n    // Otherwise it is a hyperbola.\n    else\n    {\n        // Alpha parameter in Lagrange's equation (no explanation available).\n        const double alphaParameter = 2.0 * boost::math::acosh( xParameter );\n\n        // Beta parameter in Lagrange's equation (no explanation available).\n        double betaParameter;\n\n        // If long transfer arc.\n        if ( isLongway )\n        {\n            betaParameter = -2.0 * boost::math::asinh( std::sqrt( ( normalizedSemiPerimeter\n                                                                    - normalizedChord )\n                                                                  / ( -2.0 * semiMajorAxis ) ) );\n        }\n        // Otherwise short transfer arc\n        else\n        {\n            betaParameter = 2.0 * boost::math::asinh( std::sqrt( ( normalizedSemiPerimeter\n                                                                   - normalizedChord )\n                                                                 / ( -2.0 * semiMajorAxis ) ) );\n        }\n\n        // Time-of-flight according to Lagrange.\n        const double timeOfFlightLagrange = -semiMajorAxis * std::sqrt( -semiMajorAxis ) *\n                ( ( std::sinh( alphaParameter ) - alphaParameter )\n                  - ( std::sinh( betaParameter ) - betaParameter ) );\n\n        return timeOfFlightLagrange;\n    }\n}\n\n//! Solve the time of flight equation for x (for multiple revolutions).\ndouble MultiRevolutionLambertTargeterIzzo::computeRootTimeOfFlight( )\n{\n    using mathematical_constants::PI;\n\n    // Define initial guesses for abcissae (x) and ordinates (y).\n    double x1, x2;\n\n    if ( isRightBranch )\n    { // right branch solution.\n        x1 = std::tan( .7234 * PI / 2.0 );\n        x2 = std::tan( .5234 * PI / 2.0 );\n    }\n    else\n    { // left branch solution.\n        x1 = std::tan( -.5234 * PI / 2.0 );\n        x2 = std::tan( -.2234 * PI / 2.0 );\n    }\n\n    double y1 = computeTimeOfFlight( std::atan( x1 ) * 2.0 / PI ) - normalizedTimeOfFlight;\n\n    double y2 = computeTimeOfFlight( std::atan( x2 ) * 2.0 / PI ) - normalizedTimeOfFlight;\n\n    // Declare and initialize root-finding parameters.\n    double rootFindingError = 1.0, xNew = 0.0, yNew = 0.0;\n    int iterator = 0;\n\n    // Root-finding loop.\n    while ( ( rootFindingError > convergenceTolerance ) && ( y1 != y2 )\n            && ( iterator < maximumNumberOfIterations ) )\n    {\n        // Update iterator.\n        iterator++;\n\n        // Compute new x-value.\n        xNew = ( x1 * y2 - y1 * x2 ) / ( y2 - y1 );\n\n        // Compute corresponding y-value.\n        yNew = computeTimeOfFlight( std::atan( xNew ) * 2.0 / PI ) - normalizedTimeOfFlight;\n\n        // Update abcissae and ordinates.\n        x1 = x2;\n        y1 = y2;\n        x2 = xNew;\n        y2 = yNew;\n\n        // Compute root-finding error.\n        rootFindingError = std::fabs( x1 - xNew );\n    }\n\n    // Verify that root-finder has converged.\n    if ( iterator == maximumNumberOfIterations )\n    {\n        throw basic_mathematics::ConvergenceException(\n                    \"Multi-Revolution Lambert targeter failed to converge to a solution. Reached the maximum number of iterations: %d\"\n                    + std::to_string( maximumNumberOfIterations ) );;\n    }\n\n    // Revert to x parameter.\n    double xParameter = std::atan( xNew ) * 2.0 / PI;\n    return xParameter;\n}\n\n// Add compute maximum number of revolutions routine?\n\n} // namespace mission_segments\n} // namespace tudat\n", "meta": {"hexsha": "e797e6acf453b5dc104daabda60900ba63a1a0f4", "size": 10773, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/MissionSegments/multiRevolutionLambertTargeterIzzo.cpp", "max_stars_repo_name": "J-Westin/tudat", "max_stars_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "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/MissionSegments/multiRevolutionLambertTargeterIzzo.cpp", "max_issues_repo_name": "J-Westin/tudat", "max_issues_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/MissionSegments/multiRevolutionLambertTargeterIzzo.cpp", "max_forks_repo_name": "J-Westin/tudat", "max_forks_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "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.0206185567, "max_line_length": 150, "alphanum_fraction": 0.6152418082, "num_tokens": 2426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5476322915307634}}
{"text": "///////////////////////////////////////////////////////////////////////////////////////////\n// distribution::survival::example::data::random.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 <ostream>\n#include <fstream>\n#include <stdexcept>\n#include <string> //needed?\n#include <algorithm>\n#include <iterator>\n#include <vector>\n\n#include <boost/typeof/typeof.hpp>\n#include <boost/range.hpp>\n#include <boost/assert.hpp>\n#include <boost/foreach.hpp> \n#include <boost/accumulators/accumulators.hpp>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <boost/fusion/container/generation/make_map.hpp>\n#include <boost/fusion/include/make_map.hpp>\n\n#include <boost/statistics/detail/non_parametric/kolmogorov_smirnov/check_convergence.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/exponential/include.hpp>\n\n#include <boost/statistics/detail/distribution/survival/record/key/include.hpp>\n#include <boost/statistics/detail/distribution/survival/response/types/right_truncated/include.hpp>\n#include <boost/statistics/detail/distribution/survival/failure_time/meta/include.hpp>\n#include <boost/statistics/detail/distribution/survival/models/exponential/scalar/include.hpp>\n\n#include <libs/statistics/detail/distribution/survival/example/data/random.h>\n\nvoid example_data_random(std::ostream& os)\n{\n    os << \"-> example_data_random : \" << std::endl;\n\n    // Generate failure-time data randomly\n    // Computes kolmogorov-smirnov statistics at various iterations to verify\n    // convergence to the desired distribution\n\n    using namespace boost;\n    namespace stat = boost::statistics::detail;\n    namespace ds = stat::distribution::survival;\n    namespace dt = stat::distribution::toolkit;\n    namespace dm = stat::distribution::model;\n    namespace ks = stat::kolmogorov_smirnov;\n\n    typedef ds::record::tag::entry_time     tag_et_;\n    typedef ds::record::tag::failure_time   tag_ft_;\n    typedef dm::tag::covariate          \ttag_x_;\n    typedef boost::mpl::int_<1>         \ttag_cdf_;\n    typedef mt19937                     \turng_;\n    typedef double                      \tval_;\n    typedef ds::exponential_model<val_> \tm_;\n    typedef ds::failure_time::distribution<m_>::type           d_;\n    typedef ds::failure_time::random_distribution<m_>::type    r_;\n    typedef boost::variate_generator<urng_&,r_>                g_;\n\ttypedef ks::check_convergence<val_> check_;\n\n    const int n_loops = 1.5e1;\n    const int n_init = 2;\n    const int n_factor = 2;\n\n    urng_ urng;\n    m_ m;\n    val_ x = -1.0;\n    val_ p = 1.0;\n    m.set_parameter(p);\n    d_ d = ds::failure_time::make_distribution( x, m );\n    g_ g(\n        urng,\n        ds::failure_time::make_random_distribution( x, m )\n    );\n    \n\tcheck_ check;\n    \n    check(n_loops,n_init,n_factor,d,g,os);\n\n}", "meta": {"hexsha": "4034c897a5a229ff10f4c44d2ea107a26d1c3b9c", "size": 3314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "distribution_survival/libs/statistics/detail/distribution/survival/example/data/random.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": "distribution_survival/libs/statistics/detail/distribution/survival/example/data/random.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": "distribution_survival/libs/statistics/detail/distribution/survival/example/data/random.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": 38.9882352941, "max_line_length": 99, "alphanum_fraction": 0.6270368135, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5476322892403754}}
{"text": "//\n// Copyright 2019 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_DETAIL_MATH_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_DETAIL_MATH_HPP\n\n#include <array>\n#include <boost/gil/extension/numeric/kernel.hpp>\n\nnamespace boost {\nnamespace gil {\nnamespace detail {\n\nstatic constexpr double pi = 3.14159265358979323846;\n\nstatic constexpr std::array<float, 9> dx_sobel = {\n    {-1, 0, 1, -2, 0, 2, -1, 0, 1}};\nstatic constexpr std::array<float, 9> dx_scharr = {\n    {-1, 0, 1, -1, 0, 1, -1, 0, 1}};\nstatic constexpr std::array<float, 9> dy_sobel = {\n    {1, 2, 1, 0, 0, 0, -1, -2, -1}};\nstatic constexpr std::array<float, 9> dy_scharr = {\n    {1, 1, 1, 0, 0, 0, -1, -1, -1}};\n\ntemplate <typename T, typename Allocator>\ninline detail::kernel_2d<T, Allocator> get_identity_kernel() {\n  detail::kernel_2d<T, Allocator> kernel(1, 0, 0);\n  kernel[0] = 1;\n  return kernel;\n}\n\n} // namespace detail\n} // namespace gil\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "4fa4761b52eceebba8c03e47486a62e4a50e6c05", "size": 1165, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/detail/math.hpp", "max_stars_repo_name": "sdebionne/gil-reformated", "max_stars_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/gil/detail/math.hpp", "max_issues_repo_name": "sdebionne/gil-reformated", "max_issues_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/gil/detail/math.hpp", "max_forks_repo_name": "sdebionne/gil-reformated", "max_forks_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "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.4146341463, "max_line_length": 80, "alphanum_fraction": 0.6901287554, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5476322846595995}}
{"text": "#include \"MeshGeometry.h\"\n#include \"MeshConnectivity.h\"\n#include <Eigen/Dense>\n\nMeshGeometry::MeshGeometry()\n{\n    \n}\n\nMeshGeometry::MeshGeometry(const Eigen::MatrixXd &V, MeshConnectivity &mesh)\n{\n    // compute barycentric matrices and Js\n    int nfaces = mesh.nFaces();\n    Bs.resize(nfaces);\n    Js.resize(2 * nfaces, 2);\n    faceNormals.resize(nfaces, 3);\n\n    averageEdgeLength = 0;\n    for (int i = 0; i < nfaces; i++)\n    {\n        Eigen::Vector3d v0 = V.row(mesh.faces()(i, 0));\n        Eigen::Vector3d v1 = V.row(mesh.faces()(i, 1));\n        Eigen::Vector3d v2 = V.row(mesh.faces()(i, 2));\n        Bs[i].col(0) = v1 - v0;\n        Bs[i].col(1) = v2 - v0;\n\n        averageEdgeLength += (v1 - v0).norm();\n        averageEdgeLength += (v2 - v1).norm();\n        averageEdgeLength += (v0 - v2).norm();\n\n        Eigen::Vector3d n = (v1 - v0).cross(v2 - v0);\n        n /= n.norm();\n        faceNormals.row(i) = n.transpose();\n\n        Eigen::Matrix2d BTB = Bs[i].transpose() * Bs[i];\n        Eigen::Matrix<double, 3, 2> ncrossB;\n        ncrossB.col(0) = n.cross(v1 - v0);\n        ncrossB.col(1) = n.cross(v2 - v0);\n        Js.block<2, 2>(2 * i, 0) = BTB.inverse() * Bs[i].transpose() * ncrossB;\n    }\n\n    averageEdgeLength /= 3.0 * nfaces;\n\n    // compute cDiffs and transition matrices\n    int nedges = mesh.nEdges();\n    cDiffs.resize(2 * nedges, 2);\n    Ts.resize(2 * nedges, 4);\n    for (int edgeidx = 0; edgeidx < nedges; edgeidx++)\n    {        \n        //collect neighboring face indices\n        int face1 = mesh.edgeFace(edgeidx, 0);\n        int face2 = mesh.edgeFace(edgeidx, 1);\n\n        if(face1 == -1 || face2 == -1)\n            continue;\n\n        int v1 = mesh.edgeVertex(edgeidx, 0);\n        int v2 = mesh.edgeVertex(edgeidx, 1);\n\n        Eigen::Vector3d n1 = faceNormals.row(face1).transpose();\n        Eigen::Vector3d n2 = faceNormals.row(face2).transpose();\n        // collect: (1) the midpoint of the common edge, (2) unit vector in direction of common edge,\n        // (3) the face normals, (4) the centroid of neighboring faces\n\n        Eigen::Vector3d midpt = 0.5 * (V.row(v1).transpose() + V.row(v2).transpose());\n        Eigen::Vector3d commone = V.row(v2).transpose() - V.row(v1).transpose();\n        commone /= commone.norm();\n        Eigen::Vector3d centroids[2];\n        centroids[0].setZero();\n        centroids[1].setZero();\n\n        for (int i = 0; i < 3; i++)\n        {\n            centroids[0] += V.row(mesh.faces()(face1, i)).transpose();\n            centroids[1] += V.row(mesh.faces()(face2, i)).transpose();\n        }\n\n        centroids[0] /= 3.0;\n        centroids[1] /= 3.0;\n\n        //rotate each centroid into the plane of the opposite triangle and compute ci minus c\n\n        Eigen::Vector3d t1 = n1.cross(commone);\n        Eigen::Vector3d t2 = n2.cross(commone);\n        Eigen::Vector3d diff2 = centroids[1] - midpt;\n        double alpha = commone.dot(diff2);\n        double beta = t2.dot(diff2);\n\n        Eigen::Matrix2d BTB1 = Bs[face1].transpose() * Bs[face1];\n        Eigen::Matrix2d BTB2 = Bs[face2].transpose() * Bs[face2];\n\n        cDiffs.row(2 * edgeidx) = BTB1.inverse() * Bs[face1].transpose() * (midpt + alpha * commone + beta * t1 - centroids[0]);\n        Eigen::Vector3d diff1 = centroids[0] - midpt;\n        alpha = commone.dot(diff1);\n        beta = t1.dot(diff1);\n        cDiffs.row(2 * edgeidx + 1) = BTB2.inverse() * Bs[face2].transpose() * (midpt + alpha*commone + beta * t2 - centroids[1]);\n\n        Eigen::Vector3d e1 = V.row(mesh.faces()(face1, 1)).transpose() - V.row(mesh.faces()(face1, 0)).transpose();\n        Eigen::Vector3d e2 = V.row(mesh.faces()(face1, 2)).transpose() - V.row(mesh.faces()(face1, 0)).transpose();\n\n        double alpha1 = commone.dot(e1);\n        double beta1 = t1.dot(e1);\n        Eigen::Vector3d newe1 = alpha1*commone + beta1 * t2;\n        Ts.block<2, 1>(2 * edgeidx, 0) = BTB2.inverse() * Bs[face2].transpose() * newe1;\n\n        double alpha2 = commone.dot(e2);\n        double beta2 = t1.dot(e2);\n        Eigen::Vector3d newe2 = alpha2*commone + beta2*t2;\n        Ts.block<2, 1>(2 * edgeidx, 1) = BTB2.inverse() * Bs[face2].transpose() * newe2;\n\n        e1 = V.row(mesh.faces()(face2, 1)).transpose() - V.row(mesh.faces()(face2, 0)).transpose();\n        e2 = V.row(mesh.faces()(face2, 2)).transpose() - V.row(mesh.faces()(face2, 0)).transpose();\n\n        alpha1 = commone.dot(e1);\n        beta1 = t2.dot(e1);\n        newe1 = alpha1 * commone + beta1 * t1;\n        Ts.block<2, 1>(2 * edgeidx, 2) = BTB1.inverse() * Bs[face1].transpose() * newe1;\n\n        alpha2 = commone.dot(e2);\n        beta2 = t2.dot(e2);\n        newe2 = alpha2*commone + beta2*t1;\n        Ts.block<2, 1>(2 * edgeidx, 3) = BTB1.inverse() * Bs[face1].transpose() * newe2;\n    }\n}\n", "meta": {"hexsha": "ca2ca5af8c6a752a769f7770540b8862961f6e98", "size": 4743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MeshGeometry.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": "MeshGeometry.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": "MeshGeometry.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": 37.944, "max_line_length": 130, "alphanum_fraction": 0.5694707991, "num_tokens": 1491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5476322819733183}}
{"text": "#ifndef PR_TREE_POINT_HPP\n#define PR_TREE_POINT_HPP\n#include <boost/type_index.hpp>\n#include <type_traits>\n#include <utility>\n#include <array>\n#include <cmath>\n\nnamespace perior\n{\n\nnamespace meta\n{\ntemplate<typename ... Ts>\nstruct and_{};\ntemplate<typename T>\nstruct and_<T>: std::integral_constant<bool, T::value>{};\ntemplate<typename T, typename ...Ts>\nstruct and_<T, Ts...>: std::integral_constant<bool,\n    (T::value ? and_<Ts...>::value : false)>{};\n} // meta\n\ntemplate<typename T, std::size_t N>\nstruct point\n{\n    typedef T value_type;\n    typedef value_type scalar_type;\n    constexpr static std::size_t dim = N;\n\n    point() noexcept   = default;\n    ~point() noexcept  = default;\n\n    template<typename ...Ts, typename std::enable_if<(sizeof...(Ts) == dim) &&\n        meta::and_<std::is_convertible<Ts, scalar_type>...>::value,\n        std::nullptr_t>::type = nullptr>\n    point(Ts&& ... xs) noexcept : v_{{std::forward<scalar_type>(xs)...}}{}\n\n    point(const point& rhs) noexcept = default;\n    point(point&&      rhs) noexcept = default;\n    point& operator=(const point& rhs) noexcept = default;\n    point& operator=(point&&      rhs) noexcept = default;\n\n    point& operator+=(const point& rhs) noexcept\n    {\n        for(std::size_t i=0; i<N; ++i)\n        {\n            v_[i] += rhs[i];\n        }\n        return *this;\n    }\n    point& operator-=(const point& rhs)\n    {\n        for(std::size_t i=0; i<N; ++i)\n        {\n            v_[i] -= rhs[i];\n        }\n        return *this;\n    }\n    point& operator*=(const scalar_type rhs)\n    {\n        for(std::size_t i=0; i<N; ++i)\n        {\n            v_[i] *= rhs;\n        }\n        return *this;\n    }\n    point& operator/=(const scalar_type rhs)\n    {\n        for(std::size_t i=0; i<N; ++i)\n        {\n            v_[i] /= rhs;\n        }\n        return *this;\n    }\n\n    constexpr inline std::size_t size() const noexcept {return dim;}\n\n    scalar_type& operator[](const std::size_t i)       noexcept {return v_[i];}\n    scalar_type  operator[](const std::size_t i) const noexcept {return v_[i];}\n    scalar_type& at(const std::size_t i)       {return v_.at(i);}\n    scalar_type  at(const std::size_t i) const {return v_.at(i);}\n\n  private:\n    std::array<value_type, dim> v_;\n};\n\ntemplate<typename T, std::size_t N>\ninline bool\noperator==(const point<T, N>& lhs, const point<T, N>& rhs) noexcept\n{\n    for(std::size_t i=0; i<N; ++i)\n    {\n        if(lhs[i] != rhs[i]){return false;}\n    }\n    return true;\n}\n\ntemplate<typename T, std::size_t N>\ninline bool\noperator!=(const point<T, N>& lhs, const point<T, N>& rhs) noexcept\n{\n    for(std::size_t i=0; i<N; ++i)\n    {\n        if(lhs[i] != rhs[i]){return true;}\n    }\n    return false;\n}\n\ntemplate<typename T, std::size_t N>\ninline point<T, N>\noperator+(const point<T, N>& lhs, const point<T, N>& rhs) noexcept\n{\n    point<T, N> p;\n    for(std::size_t i=0; i<N; ++i)\n    {\n        p[i] = lhs[i] + rhs[i];\n    }\n    return p;\n}\ntemplate<typename T, std::size_t N>\ninline point<T, N>\noperator-(const point<T, N>& lhs, const point<T, N>& rhs) noexcept\n{\n    point<T, N> p;\n    for(std::size_t i=0; i<N; ++i)\n    {\n        p[i] = lhs[i] - rhs[i];\n    }\n    return p;\n}\ntemplate<typename T, std::size_t N>\ninline point<T, N>\noperator*(const point<T, N>& lhs, const T rhs) noexcept\n{\n    point<T, N> p;\n    for(std::size_t i=0; i<N; ++i)\n    {\n        p[i] = lhs[i] * rhs;\n    }\n    return p;\n}\ntemplate<typename T, std::size_t N>\ninline point<T, N>\noperator*(const T lhs, const point<T, N>& rhs) noexcept\n{\n    point<T, N> p;\n    for(std::size_t i=0; i<N; ++i)\n    {\n        p[i] = lhs * rhs[i];\n    }\n    return p;\n}\ntemplate<typename T, std::size_t N>\ninline point<T, N>\noperator/(const point<T, N>& lhs, const T rhs) noexcept\n{\n    point<T, N> p;\n    for(std::size_t i=0; i<N; ++i)\n    {\n        p[i] = lhs[i] / rhs;\n    }\n    return p;\n}\n\ntemplate<typename charT, typename traits, typename realT, std::size_t N>\ninline std::basic_ostream<charT, traits>&\noperator<<(std::basic_ostream<charT, traits>& os,\n           const point<realT, N>& pos)\n{\n    os << \"point<\" << boost::typeindex::type_id<realT>().pretty_name() << \", \" << N << \">(\";\n    for(std::size_t i=0; i<N-1; ++i)\n    {\n        os << pos[i] << \", \";\n    }\n    os << pos[N-1] << ')';\n    return os;\n}\n\ntemplate<typename T, std::size_t N>\ninline point<T, N>\nabs(const point<T, N>& lhs) noexcept\n{\n    point<T, N> p;\n    for(std::size_t i=0; i<N; ++i)\n    {\n        p[i] = std::abs(lhs[i]);\n    }\n    return p;\n}\n\ntemplate<typename T, std::size_t N>\ninline T\ndot_product(const point<T, N>& lhs, const point<T, N>& rhs) noexcept\n{\n    T retval = 0;\n    for(std::size_t i=0; i<N; ++i)\n    {\n        retval += lhs[i] * rhs[i];\n    }\n    return retval;\n}\n\ntemplate<typename T, std::size_t N>\ninline point<T, N>\ncross_product(const point<T, 3>& lhs, const point<T, 3>& rhs) noexcept\n{\n    return point<T, N>(lhs[1] * rhs[2] - lhs[2] * rhs[1],\n                    lhs[2] * rhs[0] - lhs[0] * rhs[2],\n                    lhs[0] * rhs[1] - lhs[1] * rhs[0]);\n}\n\ntemplate<typename T, std::size_t N>\ninline T\nlength_sq(const point<T, N>& lhs) noexcept\n{\n    return dot_product(lhs, lhs);\n}\n\ntemplate<typename T, std::size_t N>\ninline T\nlength(const point<T, N>& lhs) noexcept\n{\n    return std::sqrt(length_sq(lhs));\n}\n\n}// perior\n#endif//TEST_PERIOR_TREE_POINT_TRAITS_HPP\n", "meta": {"hexsha": "d2a2bb8f85349713e0aa10c81142b1044cefcacd", "size": 5332, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "experimental/point.hpp", "max_stars_repo_name": "lasergyro/periortree", "max_stars_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-09-01T14:46:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T11:11:50.000Z", "max_issues_repo_path": "experimental/point.hpp", "max_issues_repo_name": "lasergyro/periortree", "max_issues_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-02-14T03:37:38.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-14T12:16:29.000Z", "max_forks_repo_path": "experimental/point.hpp", "max_forks_repo_name": "lasergyro/periortree", "max_forks_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-02-14T03:52:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T15:49:30.000Z", "avg_line_length": 23.3859649123, "max_line_length": 92, "alphanum_fraction": 0.5692048012, "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5476266379730718}}
{"text": "//\n//  Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n#include <iostream>\n#include <random>\n#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"utility.hpp\"\n\nBOOST_AUTO_TEST_SUITE ( test_tensor_static_rank_matrix_interoperability )\n\nusing test_types = zip<int,float>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_tensor_matrix_copy_ctor, value,  test_types)\n{\n  namespace ublas  = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout = typename value::second_type;\n    using tensor = ublas::tensor_static_rank<value_type, 2,layout>;\n    using matrix = typename tensor::matrix_type;\n\n    auto a2 = tensor( matrix(1,1) );\n    BOOST_CHECK_EQUAL(  a2.size() , 1 );\n    BOOST_CHECK( !a2.empty() );\n    BOOST_CHECK_NE(  a2.data() , nullptr);\n\n    auto a3 = tensor( matrix(2,1) );\n    BOOST_CHECK_EQUAL(  a3.size() , 2 );\n    BOOST_CHECK( !a3.empty() );\n    BOOST_CHECK_NE(  a3.data() , nullptr);\n\n    auto a4 = tensor( matrix(1,2) );\n    BOOST_CHECK_EQUAL(  a4.size() , 2 );\n    BOOST_CHECK( !a4.empty() );\n    BOOST_CHECK_NE(  a4.data() , nullptr);\n\n    auto a5 = tensor( matrix(2,3) );\n    BOOST_CHECK_EQUAL(  a5.size() , 6 );\n    BOOST_CHECK( !a5.empty() );\n    BOOST_CHECK_NE(  a5.data() , nullptr);\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_tensor_vector_copy_ctor, value,  test_types)\n{\n  namespace ublas  = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type  = ublas::tensor_static_rank<value_type, 2,layout_type>;\n    using vector_type = typename tensor_type::vector_type;\n\n    auto a2 = tensor_type( vector_type(1) );\n    BOOST_CHECK_EQUAL(  a2.size() , 1 );\n    BOOST_CHECK( !a2.empty() );\n    BOOST_CHECK_NE(  a2.data() , nullptr);\n\n    auto a3 = tensor_type( vector_type(2) );\n    BOOST_CHECK_EQUAL(  a3.size() , 2 );\n    BOOST_CHECK( !a3.empty() );\n    BOOST_CHECK_NE(  a3.data() , nullptr);\n\n    auto a4 = tensor_type( vector_type(2) );\n    BOOST_CHECK_EQUAL(  a4.size() , 2 );\n    BOOST_CHECK( !a4.empty() );\n    BOOST_CHECK_NE(  a4.data() , nullptr);\n\n    auto a5 = tensor_type( vector_type(3) );\n    BOOST_CHECK_EQUAL(  a5.size() , 3 );\n    BOOST_CHECK( !a5.empty() );\n    BOOST_CHECK_NE(  a5.data() , nullptr);\n}\n\n\nstruct fixture\n{\n    template<size_t N>\n    using extents_type = boost::numeric::ublas::extents<N>;\n\n    std::tuple<\n        extents_type<2>, // 0\n        extents_type<2>, // 1\n        extents_type<2>, // 2\n        extents_type<2>, // 3\n        extents_type<2>  // 4\n    > extents = {\n        {1,1},\n        {1,2},\n        {2,1},\n        {6,6},\n        {9,7},        \n    };\n};\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_matrix_copy_ctor_extents, value,  test_types, fixture )\n{\n  namespace ublas  = boost::numeric::ublas;\n  using value_type  = typename value::first_type;\n  using layout_type = typename value::second_type;\n\n  auto check = [](auto const& /*unused*/, auto& e) {\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(e)>>;\n    using tensor = ublas::tensor_static_rank<value_type, size,layout_type>;\n    using matrix = typename tensor::matrix_type;\n\n    assert(ublas::size(e)==2);\n    tensor t = matrix{e[0],e[1]};\n    BOOST_CHECK_EQUAL (  t.size() , ublas::product(e) );\n    BOOST_CHECK_EQUAL (  t.rank() , ublas::size   (e) );\n    BOOST_CHECK       ( !t.empty()    );\n    BOOST_CHECK_NE    (  t.data() , nullptr);\n  };\n\n  for_each_in_tuple(extents,check);\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_vector_copy_ctor_extents, value,  test_types, fixture )\n{\n  namespace ublas  = boost::numeric::ublas;\n  using value_type  = typename value::first_type;\n  using layout_type = typename value::second_type;\n\n\n  auto check = [](auto const& /*unused*/, auto& e) {\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(e)>>;\n    using tensor = ublas::tensor_static_rank<value_type, size,layout_type>;\n    using vector = typename tensor::vector_type;\n\n    assert(ublas::size(e)==2);\n    if(ublas::empty(e))\n      return;\n\n    tensor t = vector (product(e));\n    BOOST_CHECK_EQUAL (  t.size() , ublas::product(e) );\n    BOOST_CHECK_EQUAL (  t.rank() , ublas::size   (e) );\n    BOOST_CHECK       ( !t.empty()    );\n    BOOST_CHECK_NE    (  t.data() , nullptr);\n  };\n\n  for_each_in_tuple(extents,check);\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_matrix_copy_assignment, value,  test_types, fixture )\n{\n  namespace ublas  = boost::numeric::ublas;\n  using value_type  = typename value::first_type;\n  using layout_type = typename value::second_type;\n\n\n  for_each_in_tuple(extents, [](auto const& /*unused*/, auto& e) {\n    using etype  = std::decay_t<decltype(e)>;\n    constexpr auto size = std::tuple_size_v<etype>;\n    using tensor = ublas::tensor_static_rank<value_type,size,layout_type>;\n    using matrix = typename tensor::matrix_type;\n\n    assert(ublas::size(e) == 2);\n    auto t = tensor{e[1],e[0]};\n    auto r = matrix(e[0],e[1]);\n    std::iota(r.data().begin(),r.data().end(), 1);\n    t = r;\n\n    BOOST_CHECK_EQUAL (  t.extents().at(0) , e.at(0) );\n    BOOST_CHECK_EQUAL (  t.extents().at(1) , e.at(1) );\n    BOOST_CHECK_EQUAL (  t.size() , ublas::product(e) );\n    BOOST_CHECK_EQUAL (  t.rank() , ublas::size   (e) );\n    BOOST_CHECK       ( !t.empty()    );\n    BOOST_CHECK_NE    (  t.data() , nullptr);\n\n    for(auto j = 0ul; j < t.size(1); ++j){\n      for(auto i = 0ul; i < t.size(0); ++i){\n        BOOST_CHECK_EQUAL( t.at(i,j), r(i,j)  );\n      }\n    }\n  });\n\n  //for_each_in_tuple(extents,check);\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_vector_copy_assignment, value,  test_types, fixture )\n{\n  namespace ublas  = boost::numeric::ublas;\n  using value_type  = typename value::first_type;\n  using layout_type = typename value::second_type;\n\n  auto check = [](auto const& /*unused*/, auto& e) {\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(e)>>;\n    using tensor_type = ublas::tensor_static_rank<value_type, size,layout_type>;\n    using vector_type = typename tensor_type::vector_type;\n\n    assert(ublas::size(e) == 2);\n    auto t = tensor_type{e[1],e[0]};\n    auto r = vector_type(e[0]*e[1]);\n    std::iota(r.data().begin(),r.data().end(), 1);\n    t = r;\n\n    BOOST_CHECK_EQUAL (  t.extents().at(0) , e.at(0)*e.at(1) );\n    BOOST_CHECK_EQUAL (  t.extents().at(1) , 1);\n    BOOST_CHECK_EQUAL (  t.size() , ublas::product(e) );\n    BOOST_CHECK_EQUAL (  t.rank() , ublas::size   (e) );\n    BOOST_CHECK       ( !t.empty()    );\n    BOOST_CHECK_NE    (  t.data() , nullptr);\n\n    for(auto i = 0ul; i < t.size(); ++i){\n      BOOST_CHECK_EQUAL( t[i], r(i)  );\n    }\n  };\n\n  for_each_in_tuple(extents,check);\n}\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_matrix_move_assignment, value,  test_types, fixture )\n{\n  namespace ublas  = boost::numeric::ublas;\n  using value_type  = typename value::first_type;\n  using layout_type = typename value::second_type;\n\n\n  auto check = [](auto const& /*unused*/, auto& e) {\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(e)>>;\n    using tensor_type = ublas::tensor_static_rank<value_type, size,layout_type>;\n    using matrix_type = typename tensor_type::matrix_type;\n\n    assert(ublas::size(e) == 2);\n    auto t = tensor_type{e[1],e[0]};\n    auto r = matrix_type(e[0],e[1]);\n    std::iota(r.data().begin(),r.data().end(), 1);\n    auto q = r;\n    t = std::move(r);\n\n    BOOST_CHECK_EQUAL (  t.extents().at(0) , e.at(0) );\n    BOOST_CHECK_EQUAL (  t.extents().at(1) , e.at(1) );\n    BOOST_CHECK_EQUAL (  t.size() , ublas::product(e) );\n    BOOST_CHECK_EQUAL (  t.rank() , ublas::size   (e) );\n    BOOST_CHECK       ( !t.empty()    );\n    BOOST_CHECK_NE    (  t.data() , nullptr);\n\n    for(auto j = 0ul; j < t.size(1); ++j){\n      for(auto i = 0ul; i < t.size(0); ++i){\n        BOOST_CHECK_EQUAL( t.at(i,j), q(i,j)  );\n      }\n    }\n  };\n\n  for_each_in_tuple(extents,check);\n}\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_vector_move_assignment, value,  test_types, fixture )\n{\n  namespace ublas  = boost::numeric::ublas;\n  using value_type  = typename value::first_type;\n  using layout_type = typename value::second_type;\n\n  auto check = [](auto const& /*unused*/, auto& e) {\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(e)>>;\n    using tensor_type = ublas::tensor_static_rank<value_type, size,layout_type>;\n    using vector_type = typename tensor_type::vector_type;\n\n    assert(ublas::size(e) == 2);\n    auto t = tensor_type{e[1],e[0]};\n    auto r = vector_type(e[0]*e[1]);\n    std::iota(r.data().begin(),r.data().end(), 1);\n    auto q = r;\n    t = std::move(r);\n\n    BOOST_CHECK_EQUAL (  t.extents().at(0) , e.at(0) * e.at(1));\n    BOOST_CHECK_EQUAL (  t.extents().at(1) , 1);\n    BOOST_CHECK_EQUAL (  t.size() , ublas::product(e) );\n    BOOST_CHECK_EQUAL (  t.rank() , ublas::size   (e) );\n    BOOST_CHECK       ( !t.empty()    );\n    BOOST_CHECK_NE    (  t.data() , nullptr);\n\n    for(auto i = 0ul; i < t.size(); ++i){\n      BOOST_CHECK_EQUAL( t[i], q(i)  );\n    }\n  };\n\n  for_each_in_tuple(extents,check);\n}\n\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_matrix_expressions, value,  test_types, fixture )\n{\n  namespace ublas  = boost::numeric::ublas;\n  using value_type  = typename value::first_type;\n  using layout_type = typename value::second_type;\n\n\n  auto check = [](auto const& /*unused*/, auto& e) {\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(e)>>;\n    using tensor_type = ublas::tensor_static_rank<value_type, size,layout_type>;\n    using matrix_type = typename tensor_type::matrix_type;\n\n    assert(ublas::size(e) == 2);\n    auto t = tensor_type{e[1],e[0]};\n    auto r = matrix_type(e[0],e[1]);\n    std::iota(r.data().begin(),r.data().end(), 1);\n    t = r + 3*r;\n    tensor_type s = r + 3*r;\n    tensor_type q = s + r + 3*r + s; // + 3*r\n\n\n    BOOST_CHECK_EQUAL (  t.extents().at(0) , e.at(0) );\n    BOOST_CHECK_EQUAL (  t.extents().at(1) , e.at(1) );\n    BOOST_CHECK_EQUAL (  t.size() , ublas::product(e) );\n    BOOST_CHECK_EQUAL (  t.rank() , ublas::size   (e) );\n    BOOST_CHECK       ( !t.empty()    );\n    BOOST_CHECK_NE    (  t.data() , nullptr);\n\n    BOOST_CHECK_EQUAL (  s.extents().at(0) , e.at(0) );\n    BOOST_CHECK_EQUAL (  s.extents().at(1) , e.at(1) );\n    BOOST_CHECK_EQUAL (  s.size() , ublas::product(e) );\n    BOOST_CHECK_EQUAL (  s.rank() , ublas::size   (e) );\n    BOOST_CHECK       ( !s.empty()    );\n    BOOST_CHECK_NE    (  s.data() , nullptr);\n\n    BOOST_CHECK_EQUAL (  q.extents().at(0) , e.at(0) );\n    BOOST_CHECK_EQUAL (  q.extents().at(1) , e.at(1) );\n    BOOST_CHECK_EQUAL (  q.size() , ublas::product(e) );\n    BOOST_CHECK_EQUAL (  q.rank() , ublas::size   (e) );\n    BOOST_CHECK       ( !q.empty()    );\n    BOOST_CHECK_NE    (  q.data() , nullptr);\n\n\n    for(auto j = 0ul; j < t.size(1); ++j){\n      for(auto i = 0ul; i < t.size(0); ++i){\n        BOOST_CHECK_EQUAL( t.at(i,j), 4*r(i,j)  );\n        BOOST_CHECK_EQUAL( s.at(i,j), t.at(i,j)  );\n        BOOST_CHECK_EQUAL( q.at(i,j), 3*s.at(i,j)  );\n      }\n    }\n  };\n\n  for_each_in_tuple(extents,check);\n}\n\n\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_vector_expressions, value,  test_types, fixture )\n{\n  namespace ublas  = boost::numeric::ublas;\n  using value_type  = typename value::first_type;\n  using layout_type = typename value::second_type;\n\n  auto check = [](auto const& /*unused*/, auto& e) {\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(e)>>;\n    using tensor_type = ublas::tensor_static_rank<value_type, size,layout_type>;\n    using vector_type = typename tensor_type::vector_type;\n\n    assert(ublas::size(e) == 2);\n    auto t = tensor_type{e[1],e[0]};\n    auto r = vector_type(e[0]*e[1]);\n    std::iota(r.data().begin(),r.data().end(), 1);\n    t = r + 3*r;\n    tensor_type s = r + 3*r;\n    tensor_type q = s + r + 3*r + s; // + 3*r\n\n\n    BOOST_CHECK_EQUAL (  t.extents().at(0) , e.at(0)*e.at(1) );\n    BOOST_CHECK_EQUAL (  t.extents().at(1) , 1);\n    BOOST_CHECK_EQUAL (  t.size() , ublas::product(e) );\n    BOOST_CHECK_EQUAL (  t.rank() , ublas::size   (e) );\n    BOOST_CHECK       ( !t.empty()    );\n    BOOST_CHECK_NE    (  t.data() , nullptr);\n\n    BOOST_CHECK_EQUAL (  s.extents().at(0) , e.at(0)*e.at(1) );\n    BOOST_CHECK_EQUAL (  s.extents().at(1) , 1);\n    BOOST_CHECK_EQUAL (  s.size() , ublas::product(e) );\n    BOOST_CHECK_EQUAL (  s.rank() , ublas::size   (e) );\n    BOOST_CHECK       ( !s.empty()    );\n    BOOST_CHECK_NE    (  s.data() , nullptr);\n\n    BOOST_CHECK_EQUAL (  q.extents().at(0) , e.at(0)*e.at(1) );\n    BOOST_CHECK_EQUAL (  q.extents().at(1) , 1);\n    BOOST_CHECK_EQUAL (  q.size() , ublas::product(e) );\n    BOOST_CHECK_EQUAL (  q.rank() , ublas::size   (e) );\n    BOOST_CHECK       ( !q.empty()    );\n    BOOST_CHECK_NE    (  q.data() , nullptr);\n\n\n\n    for(auto i = 0ul; i < t.size(); ++i){\n      BOOST_CHECK_EQUAL( t.at(i), 4*r(i)  );\n      BOOST_CHECK_EQUAL( s.at(i), t.at(i)  );\n      BOOST_CHECK_EQUAL( q.at(i), 3*s.at(i)  );\n    }\n  };\n\n  for_each_in_tuple(extents,check);\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_matrix_vector_expressions, pair,  test_types, fixture )\n{\n  namespace ublas  = boost::numeric::ublas;\n  using value  = typename pair::first_type;\n  using layout = typename pair::second_type;\n\n\n  auto check = [](auto const& /*unused*/, auto& e) {\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(e)>>;\n    using tensor = ublas::tensor_static_rank<value, size, layout>;\n    using matrix = typename tensor::matrix_type;\n    using vector = typename tensor::vector_type;\n\n    if(product(e) <= 2)\n      return;\n    assert(ublas::size(e) == 2);\n    auto Q = tensor{e[0],1};\n    auto A = matrix(e[0],e[1]);\n    auto b = vector(e[1]);\n    auto c = vector(e[0]);\n    std::iota(b.data().begin(),b.data().end(), 1);\n    std::fill(A.data().begin(),A.data().end(), 1);\n    std::fill(c.data().begin(),c.data().end(), 2);\n    std::fill(Q.begin(),Q.end(), 2);\n\n    tensor T = Q + (ublas::prod(A , b) + 2*c) + 3*Q;\n\n    BOOST_CHECK_EQUAL (  T.extents().at(0) , Q.extents().at(0) );\n    BOOST_CHECK_EQUAL (  T.extents().at(1) , Q.extents().at(1));\n    BOOST_CHECK_EQUAL (  T.size() , Q.size() );\n    BOOST_CHECK_EQUAL (  T.size() , c.size() );\n    BOOST_CHECK_EQUAL (  T.rank() , Q.rank() );\n    BOOST_CHECK       ( !T.empty()    );\n    BOOST_CHECK_NE    (  T.data() , nullptr);\n\n    const auto n   = e[1];\n    const auto ab  = value(std::div(n*(n+1),2).quot);\n    const auto ref = ab+4*Q(0)+2*c(0);\n    BOOST_CHECK( std::all_of(T.begin(),T.end(), [ref](auto cc){ return ref == cc; }) );\n\n//    for(auto i = 0ul; i < T.size(); ++i){\n//      auto n = e[1];\n//      auto ab = n * (n+1) / 2;\n//      BOOST_CHECK_EQUAL( T(i), ab+4*Q(0)+2*c(0)  );\n//    }\n\n  };\n  for_each_in_tuple(extents,check);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "5ed7a4f567eb85e93ffbfc45fa91f2c769c0090c", "size": 15284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_fixed_rank_tensor_matrix_vector.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_fixed_rank_tensor_matrix_vector.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_fixed_rank_tensor_matrix_vector.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 32.3128964059, "max_line_length": 129, "alphanum_fraction": 0.6189479194, "num_tokens": 4618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5476266332895642}}
{"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:  Shows how to exchange data between ViennaCL and MTL4 (http://www.mtl4.org/) objects.\n*   \n*/\n\n//\n// include necessary system headers\n//\n#include <iostream>\n\n//\n// Include MTL4 headers\n//\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\n//\n// Must be set prior to any ViennaCL includes if you want to use ViennaCL algorithms on MTL4 objects\n//\n#define VIENNACL_WITH_MTL4 1\n\n//#define VIENNACL_BUILD_INFO\n//#define VIENNACL_DEBUG_ALL\n\n//\n// ViennaCL includes\n//\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/linalg/vector_operations.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n\n#include \"viennacl/linalg/ilu.hpp\"\n#include \"viennacl/linalg/cg.hpp\"\n#include \"viennacl/linalg/bicgstab.hpp\"\n#include \"viennacl/linalg/gmres.hpp\"\n\n\n// Some helper functions for this tutorial:\n#include \"Random.hpp\"\n#include \"vector-io.hpp\"\n#include \"../benchmarks/benchmark-utils.hpp\"\n\ntemplate<typename ScalarType>\nvoid run_test()\n{\n  typedef mtl::dense2D<ScalarType>        MTL4DenseMatrix;\n  typedef mtl::compressed2D<ScalarType>   MTL4SparseMatrix;\n  \n  //\n  // Create and fill dense matrices from the MTL4 library:\n  //\n  mtl::dense2D<ScalarType>   mtl4_densemat(5, 5);\n  mtl::dense2D<ScalarType>   mtl4_densemat2(5, 5);\n  mtl4_densemat(0,0) = 2.0;   mtl4_densemat(0,1) = -1.0;\n  mtl4_densemat(1,0) = -1.0;  mtl4_densemat(1,1) =  2.0;  mtl4_densemat(1,2) = -1.0;\n  mtl4_densemat(2,1) = -1.0;  mtl4_densemat(2,2) = -1.0;  mtl4_densemat(2,3) = -1.0;\n  mtl4_densemat(3,2) = -1.0;  mtl4_densemat(3,3) =  2.0;  mtl4_densemat(3,4) = -1.0;\n                              mtl4_densemat(4,4) = -1.0;  mtl4_densemat(4,4) = -1.0;\n  \n  \n  //\n  // Create and fill sparse matrices from the MTL4 library:\n  //\n  MTL4SparseMatrix mtl4_sparsemat;\n  set_to_zero(mtl4_sparsemat);  \n  mtl4_sparsemat.change_dim(5, 5);\n\n  MTL4SparseMatrix mtl4_sparsemat2;\n  set_to_zero(mtl4_sparsemat2);  \n  mtl4_sparsemat2.change_dim(5, 5);\n  \n  {\n    mtl::matrix::inserter< MTL4SparseMatrix >  ins(mtl4_sparsemat);\n    typedef typename mtl::Collection<MTL4SparseMatrix>::value_type  ValueType;\n    ins(0,0) <<  ValueType(2.0);   ins(0,1) << ValueType(-1.0);\n    ins(1,1) <<  ValueType(2.0);   ins(1,2) << ValueType(-1.0);\n    ins(2,2) << ValueType(-1.0);   ins(2,3) << ValueType(-1.0);\n    ins(3,3) <<  ValueType(2.0);   ins(3,4) << ValueType(-1.0);\n    ins(4,4) << ValueType(-1.0);\n  }\n  \n  //\n  // Create and fill a few vectors from the MTL4 library:\n  //\n  mtl::dense_vector<ScalarType> mtl4_rhs(5, 0.0);\n  mtl::dense_vector<ScalarType> mtl4_result(5, 0.0);\n  mtl::dense_vector<ScalarType> mtl4_temp(5, 0.0);\n  \n\n  mtl4_rhs(0) = 10.0;\n  mtl4_rhs(1) = 11.0;\n  mtl4_rhs(2) = 12.0;\n  mtl4_rhs(3) = 13.0;\n  mtl4_rhs(4) = 14.0;\n  \n  //\n  // Let us create the ViennaCL analogues:\n  //\n  viennacl::vector<ScalarType> vcl_rhs(5);\n  viennacl::vector<ScalarType> vcl_result(5);\n  viennacl::matrix<ScalarType> vcl_densemat(5, 5);\n  viennacl::compressed_matrix<ScalarType> vcl_sparsemat(5, 5);\n\n  //\n  // Directly copy the MTL4 objects to ViennaCL objects\n  //\n  viennacl::copy(&(mtl4_rhs[0]), &(mtl4_rhs[0]) + 5, vcl_rhs.begin());  //method 1: via iterator interface (cf. std::copy())\n  viennacl::copy(mtl4_rhs, vcl_rhs);  //method 2: via built-in wrappers (convenience layer)\n  \n  viennacl::copy(mtl4_densemat, vcl_densemat);\n  viennacl::copy(mtl4_sparsemat, vcl_sparsemat);\n  \n  // For completeness: Copy matrices from ViennaCL back to Eigen:\n  viennacl::copy(vcl_densemat, mtl4_densemat2);\n  viennacl::copy(vcl_sparsemat, mtl4_sparsemat2);\n  \n  //\n  // Run matrix-vector products and compare results:\n  //\n  mtl4_result = mtl4_densemat * mtl4_rhs;\n  vcl_result = viennacl::linalg::prod(vcl_densemat, vcl_rhs);\n  viennacl::copy(vcl_result, mtl4_temp);\n  mtl4_result -= mtl4_temp;\n  std::cout << \"Difference for dense matrix-vector product: \" << mtl::two_norm(mtl4_result) << std::endl;\n  mtl4_result = mtl4_densemat2 * mtl4_rhs - mtl4_temp;\n  std::cout << \"Difference for dense matrix-vector product (MTL4->ViennaCL->MTL4): \"\n            << mtl::two_norm(mtl4_result) << std::endl;\n  \n  //\n  // Same for sparse matrix:\n  //          \n  mtl4_result = mtl4_sparsemat * mtl4_rhs;\n  vcl_result = viennacl::linalg::prod(vcl_sparsemat, vcl_rhs);\n  viennacl::copy(vcl_result, mtl4_temp);\n  mtl4_result -= mtl4_temp;\n  std::cout << \"Difference for sparse matrix-vector product: \" << mtl::two_norm(mtl4_result) << std::endl;\n  mtl4_result = mtl4_sparsemat2 * mtl4_rhs - mtl4_temp;\n  std::cout << \"Difference for sparse matrix-vector product (MTL4->ViennaCL->MTL4): \"\n            << mtl::two_norm(mtl4_result) << std::endl;\n            \n  //\n  // Please have a look at the other tutorials on how to use the ViennaCL types\n  //\n}\n\n\n\nint main(int, char *[])\n{\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << \"## Single precision\" << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  run_test<float>();\n  \n#ifdef VIENNACL_HAVE_OPENCL   \n  if ( viennacl::ocl::current_device().double_support() )\n#endif\n  {\n    std::cout << \"----------------------------------------------\" << std::endl;\n    std::cout << \"## Double precision\" << std::endl;\n    std::cout << \"----------------------------------------------\" << std::endl;\n    run_test<double>();\n  }\n  \n  std::cout << std::endl;\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n  std::cout << std::endl;\n}\n", "meta": {"hexsha": "745804a26ff2ee216a6d051a11ca8fd0611c95f2", "size": 6254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/mtl4-with-viennacl.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/mtl4-with-viennacl.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/mtl4-with-viennacl.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.2659574468, "max_line_length": 124, "alphanum_fraction": 0.6124080588, "num_tokens": 1951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5476266289002936}}
{"text": "#pragma once\n\n#include \"ArithmeticProgression.hpp\"\n#include \"Misc.hpp\"\n#include \"Sequences.hpp\"\n#include \"VectorHelpers.hpp\"\n#include <boost/iterator/iterator_facade.hpp>\n\nnamespace discreture\n{\n\n////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Class for iterating through all dyck (dyck) paths.\n/// \\param IntType must be a SIGNED integer type.\n///\n/// Dyck paths, also called Catalan Paths, are paths that go from \\f$(0,0)\\f$ to\n/// \\f$(0,2n)\\f$, which never go below the \\f$ y=0\\f$ line, in which each step\n/// is from \\f$(x,y)\\f$ to either \\f$(x+1,y+1)\\f$ or \\f$(x+1,y-1)\\f$ #Example\n/// Usage:\n///\n///     dyck_paths X(3)\n///     for (auto&& x : X)\n///         cout << x << endl;\n/// Prints out:\n///     [ 1 1 1 -1 -1 -1 ]\n///     [ 1 1 -1 1 -1 -1 ]\n///     [ 1 -1 1 1 -1 -1 ]\n///     [ 1 1 -1 -1 1 -1 ]\n///     [ 1 -1 1 -1 1 -1 ]\n///\n/// # Example: Parenthesis\n///\n///     dyck_paths X(3)\n///     for (auto&& x : X)\n///         cout << dyck_paths::to_string(x, \"()\") << endl;\n///\n/// Prints out:\n///     ((()))\n///     (()())\n///     ()(())\n///     (())()\n///     ()()()\n///\n/////////////////////////////////////////////////////////////////////////////////////\ntemplate <class IntType = int, class RAContainerInt = std::vector<IntType>>\nclass DyckPaths\n{\npublic:\n    static_assert(std::is_integral<IntType>::value,\n                  \"Template parameter IntType must be integral\");\n    static_assert(std::is_signed<IntType>::value,\n                  \"Template parameter IntType must be signed\");\n    using value_type = RAContainerInt;\n    using dyck_path = value_type;\n    using difference_type = std::ptrdiff_t;\n    using size_type = difference_type;\n    class iterator;\n    using const_iterator = iterator;\n\n    // **************** Begin static functions\n    static void next_dyck_path(dyck_path& data)\n    {\n        size_t n_ = data.size()/2;\n\n        if (n_ == 0)\n            return;\n\n        if (data[1] != -1)\n        {\n            size_t loc = 2;\n\n            while (data[loc] != -1)\n                ++loc;\n\n            data[loc] = 1;\n            data[loc - 1] = -1;\n\n            return;\n        }\n\n        size_t verif = 0;\n        size_t i = 1;\n\n        while (i < n_ && verif == 0)\n        {\n            if (data[(2*i) + 1] == 1)\n                verif = ((2*i) + 1);\n\n            ++i;\n        }\n\n        //          for(nuint i=1; i<t; ++t)\n        //          {\n        //              if(data[(2*i)+1]==0)\n        //                  verif=((2*i)+1);\n        //          }\n\n        if (verif == 0)\n        {\n            return;\n        }\n\n        size_t cont = 0;\n        auto encontrar = verif + 1;\n\n        for (size_t i = 0; i < verif; ++i)\n        {\n            if (data[i] == -1)\n            {\n                data[i] = 1;\n                ++cont;\n            }\n        }\n\n        while (data[encontrar] != -1)\n            ++encontrar;\n\n        data[encontrar] = 1;\n        data[encontrar - 1] = -1;\n\n        while (cont != 0)\n        {\n            data[encontrar - 1 - cont] = -1;\n            --cont;\n        }\n    }\n\n    static std::string to_string(const dyck_path& data,\n                                 const std::string& delim = \"()\")\n    {\n        std::string toReturn;\n\n        for (auto i : data)\n        {\n            auto j = 1 - (i + 1)/2;\n            toReturn.push_back(delim[j]);\n        }\n\n        return toReturn;\n    }\n\n    // **************** End static functions\n\npublic:\n    ////////////////////////////////////////////////////////////\n    /// \\brief Constructor\n    ///\n    /// \\param n is an integer >= 0\n    ///\n    ////////////////////////////////////////////////////////////\n    explicit DyckPaths(IntType n) : n_(n) {}\n\n    ////////////////////////////////////////////////////////////\n    /// \\brief The total number of dyck_paths\n    ///\n    /// \\return binomial(2n,n)/(n+1)\n    ///\n    ////////////////////////////////////////////////////////////\n    size_type size() const { return catalan(n_); }\n\n    IntType get_n() const { return n_; }\n\n    ////////////////////////////////////////////////////////////\n    /// \\brief Forward iterator class.\n    ////////////////////////////////////////////////////////////\n    class iterator\n        : public boost::iterator_facade<iterator, const dyck_path&, boost::forward_traversal_tag>\n    {\n    public:\n        iterator() = default; // empty initializer\n        explicit iterator(IntType n) : ID_(0), data_(2*n, 1)\n        {\n            for (size_t i = n; i < data_.size(); ++i)\n                data_[i] = -1;\n        }\n\n        size_type ID() const { return ID_; }\n\n        bool is_at_end(IntType n) const { return ID_ == catalan(n); }\n\n        void reset(IntType n)\n        {\n            ID_ = 0;\n            data_.resize(2*n);\n            auto r = static_cast<size_t>(n);\n            for (size_t i = 0; i < r; ++i)\n                data_[i] = 1;\n\n            for (size_t i = r; i < data_.size(); ++i)\n                data_[i] = -1;\n        }\n\n        static const iterator make_invalid_with_id(size_type id)\n        {\n            iterator it;\n            it.ID_ = id;\n            return it;\n        }\n\n    private:\n        void increment()\n        {\n            ++ID_;\n\n            next_dyck_path(data_);\n        }\n\n        const dyck_path& dereference() const { return data_; }\n\n        bool equal(const iterator& it) const { return it.ID() == ID(); }\n\n    private:\n        size_type ID_{0};\n        dyck_path data_{};\n\n        friend class boost::iterator_core_access;\n    }; // end class iterator\n\n    iterator begin() const { return iterator(n_); }\n\n    const iterator end() const\n    {\n        return iterator::make_invalid_with_id(size());\n    }\n\nprivate:\n    IntType n_;\n\n}; // end class DyckPaths\n\nusing boost::container::static_vector;\n\nusing dyck_paths = DyckPaths<int>;\nusing dyck_paths_stack = DyckPaths<int, static_vector<int, 48>>;\n\n} // namespace discreture\n", "meta": {"hexsha": "579d01a5f70e330597409c694d5288b3c230bfd8", "size": 5913, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Discreture/DyckPaths.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/DyckPaths.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/DyckPaths.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": 24.9493670886, "max_line_length": 97, "alphanum_fraction": 0.4336208354, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5476266245110226}}
{"text": "#ifndef FRACTIONAL_FIT_HH\n#define FRACTIONAL_FIT_HH\n#include <Eigen/Dense>\n#include <vector>\n\n/* this class intends to fit probability of processes to the data\n * with sim_1(x), sim_2(x), sim_3(x) samples, a,b,c probabilities, where a+b+c=1\n * and data(x) sample\n *   a*sim_1 + b*sim_2 + c*sim_3 = data\n * is achieved, via fitting the moments of the 1,2,3 distributions to the moments of the data\n * utilized by correlation_tensor_serie\n */\n\n\ntemplate<class T>\nclass fractional_fit{\ntypedef Eigen::LDLT< Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic > > decomposition;\n  typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic > Matrix;\n  typedef Eigen::Matrix<T, Eigen::Dynamic, 1> Vector;\n public:\n \n  fractional_fit(Matrix const & A, Matrix const & B, Matrix const & D, \n\t\t //Vector const & m, Vector const & n, Vector const & d );\n\t\t std::vector<T> const &m, std::vector<T> const &n, std::vector<T> const &d);\n  ~fractional_fit(){}\n//  void solve();\n  void analytic_solve();\n  double operator()(double a);\n\n  T a_min, chi2; \nprivate:\n  Matrix A, B, D;\n  Vector m, n, d;\n  \n  Matrix Sigma; //depends on the 'a' fraction\n  Vector l;\n\n\n};\n\n\n\n#endif //FRACTIONAL_FIT_HH\n", "meta": {"hexsha": "7ee7e860354ae57fc344943f44d1aa54a3da2a2a", "size": 1172, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/fractional_fit.hh", "max_stars_repo_name": "freemeson/multinomial", "max_stars_repo_head_hexsha": "9bf1913a0e6d24ac40f219d44f757393decd1ad6", "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/fractional_fit.hh", "max_issues_repo_name": "freemeson/multinomial", "max_issues_repo_head_hexsha": "9bf1913a0e6d24ac40f219d44f757393decd1ad6", "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/fractional_fit.hh", "max_forks_repo_name": "freemeson/multinomial", "max_forks_repo_head_hexsha": "9bf1913a0e6d24ac40f219d44f757393decd1ad6", "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.6363636364, "max_line_length": 93, "alphanum_fraction": 0.6885665529, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652496, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5476091734853384}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////\n//  Observable functions for Kitaev Quantum Monte Carlo\n//  written by: Tim Eschmann, June 2016\n//  Modified version: February 2019\n//////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////\n   \n#define _USE_MATH_DEFINES\n\n#include <iostream>\n#include <cmath>\n#include <complex>\n#include <armadillo>\n\nusing namespace arma;\n   \n///////////////////////////////////////////////////////////////\n// Calculate free energy for a given Z2 configuration:\n///////////////////////////////////////////////////////////////\n\ndouble free_en(vec ev, double b)\n{\n    int p; // running index\n    double fe = 0; // free energy\n    \n    // Calculating:\n    for (p = 0; p < size(ev)[0]/2; p++)\n    {\n        fe -= (1/b)*logl(2*coshl(b*ev[p]/2));      \n    }\n\n    return fe;\n       \n}\n    \n///////////////////////////////////////////////////////////////\n// Calculate internal energy of the Majorana fermion system:\n///////////////////////////////////////////////////////////////\n\ndouble en(vec ev, double b)\n{\n    int q; // running index;\n    double en = 0; // internal energy\n    \n    for (q = 0; q < size(ev)[0]/2; q++)\n    {\n        en += ev[q]/2 * tanhl(-b * ev[q]/2);\n    }\n    \n    return en;\n}\n\n///////////////////////////////////////////////////////////////\n// Calculate derivative of E w.r.t. beta:\n///////////////////////////////////////////////////////////////\n\ndouble diffE(vec ev, double b)\n{\n    int qq; // running index\n    double drv = 0;\n    for (qq = 0; qq < size(ev)[0]/2; qq++)\n    {\n        //drv += ev[qq]*ev[qq]/4. * (1 - tanh(-beta_ * ev[qq]/2)*tanh(-beta_ * ev[qq]/2));\n        drv += powl(ev[qq], 2)/4. / powl((coshl(-b * ev[qq]/2)),2);\n    }\n\n    return drv;\n}\n     \n///////////////////////////////////////////////////////////////\n// Calculate average flux per elementary plaquette:\n///////////////////////////////////////////////////////////////\n\nstd::complex <double> flux(cx_mat ham, Mat<int> plaq)\n{\n    std::complex <double> flux;\n    std::complex <double> av_flux = std::complex<double>(0.0, 0.0);\n    int N = size(ham)[0];\n    int M1 = size(plaq)[0];\n    int M2 = size(plaq)[1];\n    int coord1, coord2;\n        \n    for (int i = 0; i < M1; i++)\n    {\n        flux = std::complex<double>(1.0, 0.0);\n        for (int j = 0; j < M2; j++)\n        {\n            coord1 = plaq(i,j) / N;\n            coord2 = plaq(i,j) % N;\n            \n            // Plaquette operator: W_p = prod_<i,j> (-i*u_ij)\n            flux *= (-ham(coord1, coord2)) / std::abs(ham(coord1, coord2));\n        }\n        av_flux += flux;\n    }\n\n    av_flux /= double(M1);\n\n    return av_flux;\n        \n}\n\n///////////////////////////////////////////////////////////////\n// Calculate flux disorder ratio p:\n///////////////////////////////////////////////////////////////\n\ndouble get_p(cx_mat ham, Mat<int> plaq)\n{\n    std::complex <double> flux;\n    double p;\n    int N = size(ham)[0];\n    int M1 = size(plaq)[0];\n    int M2 = size(plaq)[1];\n    int coord1, coord2;\n        \n    for (int i = 0; i < M1; i++)\n    {\n        flux = std::complex<double>(1.0, 0.0);\n        for (int j = 0; j < M2; j++)\n        {\n            coord1 = plaq(i,j) / N;\n            coord2 = plaq(i,j) % N;\n            \n            // Plaquette operator: W_p = prod_<i,j> (-i*u_ij)\n            flux *= (-ham(coord1, coord2)) / std::abs(ham(coord1, coord2));\n        }\n        if ((M2 % 4 == 0) && (flux == std::complex<double>(-1, 0)))\n            p += 1;\n        else if ((M2 % 4 == 2) && (flux == std::complex<double>(1, 0)))\n            p += 1;\n        else if ((M2 % 2 != 0) && (flux == std::complex<double>(0, 1)))\n            p += 1;\n    }\n\n    p /= double(M1);\n\n    return p;\n        \n}\n\n///////////////////////////////////////////////////////////////\n// Give flux configurations as output:\n///////////////////////////////////////////////////////////////\ncx_vec flux_confs(cx_mat ham, Mat<int> plaq)\n{\n    int M1 = size(plaq)[0];\n    int M2 = size(plaq)[1];\n    int N = size(ham)[0];\n    int coord1, coord2;\n    cx_vec confs(M1);\n    std::complex <double> flux;\n\n    for (int i = 0; i < M1; i++)\n    {\n        flux = std::complex<double>(1.0, 0.0);\n        for (int j = 0; j < M2; j++)\n        {\n            coord1 = plaq(i,j) / N;\n            coord2 = plaq(i,j) % N;\n            \n            // Plaquette operator: W_p = prod_<i,j> (-i*u_ij)\n            flux *= (-ham(coord1, coord2)) / std::abs(ham(coord1, coord2));\n        }\n\n        confs[i] = flux;\n    }\n\n    return confs;\n\n} \n\n///////////////////////////////////////////////////////////////\n// Calculate spin-spin correlation:\n// Make sure only to include one subset of bonds\n///////////////////////////////////////////////////////////////\n\ndouble correlation(cx_mat ham, std::vector<int> v_, double b)\n{\n    double value = 0.;\n    std::complex<double> av;\n    vec eigval;\n    cx_mat eigvec;\n    int N = size(ham)[0];\n    int coord1, coord2;\n      \n    eig_sym(eigval, eigvec, ham);\n    //eigvec = normalise(eigvec);\n\n    for (int j = 0; j < v_.size(); j++)\n    {\n        coord1 = v_[j]/N;\n        coord2 = v_[j]%N;\n        \n        for (int i = size(eigval)[0]/2; i < size(eigval)[0]; i++)\n        {\n            av = conj(eigvec(coord1,i))*((-ham(coord1, coord2)) / std::abs(ham(coord1, coord2)))*eigvec(coord2, i);\n            av += conj(eigvec(coord2,i))*((-ham(coord2, coord1)) / std::abs(ham(coord2, coord1)))*eigvec(coord1, i);\n            value -= real(av)*tanhl(b * eigval[i]/2.);\n        }\n    }\n\n    value *= 2/double(N);    \n    return value;\n        \n}\n\n/////////////////////////////////////////////////////////\n// Set up simulation temperatures (w. different options):\n/////////////////////////////////////////////////////////  \n\ndouble calc_temp(double T_min, double T_max, int me, int np, std::string dist)\n{\n    int i;\n    double T;\n        \n    // a) Read temperature distribution from file:\n    if (dist == \"external\")\n    {\n        double temperatures[np];\n        std::ifstream tempfile(\"temp.saved\", std::ifstream::in);\n        if(tempfile.good())\n        {\n            for (i = 0; i < np; i++)\n            {\n                tempfile >> temperatures[i];\n            }\n        }\n\n        T = temperatures[me - 1];\n    }\n\n    // b) Linear temperature distribution:\n    else if (dist == \"lin\")\n    {\n        T = T_min + (T_max - T_min)*(me - 1)/float(np);\n    }\n    // c) Logarithmic temperature distribution:*/    \n    else if (dist == \"log\")\n    {\n        T = pow(10,log10(T_min)+((log10(T_max) - log10(T_min))*(me - 1)/double(np)));\n    }\n    // d) Double-logarithmic temperature distribution:\n    else if (dist == \"double_log\")\n    {\n        T = pow(10,log10(T_min)+((log10(T_max) - log10(T_min))*pow(10, -(np - (me - 1))/double(np))));\n    }\n\n    return T;\n\n\n}\n\n\n\n//////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////\n//  Ensemble optimization functions \n//  -> check if MC replica has been at T_min or T_max latest and assign\n// \"+1\" or \"-1\" accordingly \n//////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////////////////////////////////////////////////////////\n// Record if replica has been at lowest or highest T latest ...      ////////\n/////////////////////////////////////////////////////////////////////////////\n\nint check_sign_i(int i, int np, int s_i, int s_i_plus_1)\n{\n    int sign;\n    \n    if (i != 1 && (i+1 != (np - 1)))\n    {\n        if (s_i == 1 && s_i_plus_1 == 0) \n            sign = 0;\n        else if (s_i == 0 && s_i_plus_1 == 1)\n            sign = 1;\n        else if (s_i == 1 && s_i_plus_1 == -1)\n            sign = -1;\n        else if (s_i == -1 && s_i_plus_1 == 1)\n            sign = 1;\n        else if (s_i == 0 && s_i_plus_1 == -1)\n            sign = -1;\n        else if (s_i == -1 && s_i_plus_1 == 0)\n            sign = 0;     \n        else if (s_i == 0 && s_i_plus_1 == 0)\n            sign = 0;\n        else if (s_i == 1 && s_i_plus_1 == 1)\n            sign = 1;\n        else if (s_i == -1 && s_i_plus_1 == -1)\n            sign = -1;\n    }\n    else if (i == 1)\n        sign = 1;\n    else if (i+1 == np - 1)\n        sign = -1;\n    else\n        sign = 0;\n\n    return sign;\n\n}\n\nint check_sign_i_plus_1(int i, int np, int s_i, int s_i_plus_1)\n{\n    int sign;\n    \n    if (i != 1 && (i+1 != (np - 1)))\n    {\n        if (s_i == 1 && s_i_plus_1 == 0)   \n            sign = 1;\n        else if (s_i == 0 && s_i_plus_1 == 1)\n            sign = 0;\n        else if (s_i == 1 && s_i_plus_1 == -1)\n            sign = 1;\n        else if (s_i == -1 && s_i_plus_1 == 1)\n            sign = -1;\n        else if (s_i == 0 && s_i_plus_1 == -1)\n            sign = 0;\n        else if (s_i == -1 && s_i_plus_1 == 0)\n            sign = -1;     \n        else if (s_i == 0 && s_i_plus_1 == 0)\n            sign = 0;\n        else if (s_i == 1 && s_i_plus_1 == 1)\n            sign = 1;\n        else if (s_i == -1 && s_i_plus_1 == -1)\n            sign = -1;  \n    }\n    else if (i == 1)\n        sign = 1;\n    else if (i+1 == np - 1)\n        sign = -1;\n    else \n        sign = 0;\n\n    return sign;\n}\n\n\n\n", "meta": {"hexsha": "c2fc698f1c8f22f6ac16d3cd204f377f0e63ff48", "size": 9427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "functions.hpp", "max_stars_repo_name": "timeschmann/Kitaev_QMC", "max_stars_repo_head_hexsha": "eab9167571507bcbbad35a2c4ff1367b21604d59", "max_stars_repo_licenses": ["MIT"], "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.hpp", "max_issues_repo_name": "timeschmann/Kitaev_QMC", "max_issues_repo_head_hexsha": "eab9167571507bcbbad35a2c4ff1367b21604d59", "max_issues_repo_licenses": ["MIT"], "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.hpp", "max_forks_repo_name": "timeschmann/Kitaev_QMC", "max_forks_repo_head_hexsha": "eab9167571507bcbbad35a2c4ff1367b21604d59", "max_forks_repo_licenses": ["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.6451612903, "max_line_length": 116, "alphanum_fraction": 0.3883526042, "num_tokens": 2510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5475727778634613}}
{"text": "#include \"reconstruction.h\"\n#include \"simulation.h\"\n#include <Eigen/SVD>\n#include <Eigen/StdVector>\n#include <igl/PI.h>\n#include <igl/copyleft/marching_cubes.h>\n#include <iostream>\n#include <tbb/parallel_for.h>\n\nvoid reconstruct(Eigen::MatrixXd &V, Eigen::MatrixXi &F, const Eigen::MatrixXd &P, const Eigen::Vector3i &res,\n                 const Eigen::VectorXd &mass, const Eigen::VectorXd &density, double h, double isovalue) {\n    auto W_k = 10. / (7. * igl::PI);\n    auto P1 = [&](double r) {\n        auto q = r;\n        auto res = 0.0;\n        if (q <= 1.0)\n            res = (1 - 1.5 * q * q + 0.75 * q * q * q);\n        else if (q < 2.0) {\n            auto q2 = 2 - q;\n            res = 0.25 * q2 * q2 * q2;\n        }\n        return res;\n    };\n\n    printf(\"P.rows() = %d\\n\", P.rows());\n    using igl::copyleft::marching_cubes;\n    // Eigen::Vector3d lower = Eigen::Vector3d::Zero() - Eigen::Vector3d::Constant(2 * h); // = P.colwise().minCoeff();\n    // Eigen::Vector3d upper = Eigen::Vector3d::Ones() + Eigen::Vector3d::Constant(2 * h); // P.colwise().maxCoeff();\n    Eigen::Vector3d lower = Eigen::Vector3d(P.colwise().minCoeff()) - Eigen::Vector3d::Constant(2 * h);\n    Eigen::Vector3d upper = Eigen::Vector3d(P.colwise().maxCoeff()) + Eigen::Vector3d::Constant(2 * h);\n    Eigen::Vector3d extent = upper - lower;\n    Eigen::VectorXd S;\n    Eigen::MatrixXd GV;\n    S.resize(res.prod());\n    GV.resize(res.prod(), 3);\n    Eigen::Vector3d nn_cell_size(2 * h, 2 * h, 2 * h);\n    Eigen::Vector3i nn_grid_size;\n    nn_grid_size << extent[0] / nn_cell_size[0], extent[1] / nn_cell_size[1], extent[2] / nn_cell_size[2];\n    Eigen::Vector3d grid_cell_size = extent.array() / (res - Eigen::Vector3i::Ones()).cast<double>().array();\n    for (int i = 0; i < res.prod(); i++) {\n        int x = i % res[0];\n        int y = (i % (res[0] * res[1])) / res[0];\n        int z = i / (res[0] * res[1]);\n        Eigen::Vector3d p = Eigen::Vector3d(Eigen::Array3d(x, y, z) * grid_cell_size.array()) + lower;\n        GV.row(i) = p;\n    }\n    // std::cout << GV << std::endl;\n    struct Cell {\n        std::vector<int> particles;\n    };\n    std::vector<Cell> grid(nn_grid_size.prod());\n    std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>> G(P.rows());\n    std::vector<std::vector<int>> neighbors(P.rows());\n    Eigen::MatrixXd X;\n    X.resizeLike(P);\n    // auto get_cell_index = [&](const Eigen::Vector3d &x) -> Eigen::Vector3i {\n    //     Eigen::Vector3i ip =\n    //         Eigen::Vector3i(((x - lower).array() / extent.array() * res.array().cast<double>()).cast<int>());\n    //     for (int i = 0; i < 3; i++) {\n    //         ip[i] = std::min(res[i] - 1, std::max(ip[i], 0));\n    //     }\n    //     return ip;\n    // };\n    // auto get_linear_index = [&](const Eigen::Vector3i &ip) { return ip[0] + ip[1] * res[0] + ip[2] * res[0] * res[1];\n    // };\n    auto get_nn_cell_index = [&](const Eigen::Vector3d &x) -> Eigen::Vector3i {\n        Eigen::Vector3i ip = Eigen::Vector3i(((x - lower).array() / nn_cell_size.array()).cast<int>());\n        for (int i = 0; i < 3; i++) {\n            ip[i] = std::min(nn_grid_size[i] - 1, std::max(ip[i], 0));\n        }\n        return ip;\n    };\n    auto get_nn_linear_index = [&](const Eigen::Vector3i &ip) {\n        return ip[0] + ip[1] * nn_grid_size[0] + ip[2] * nn_grid_size[0] * nn_grid_size[1];\n    };\n    for (int i = 0; i < P.rows(); i++) {\n        Eigen::Vector3i ip = get_nn_cell_index(P.row(i));\n        auto idx = get_nn_linear_index(ip);\n        CHECK(idx < grid.size());\n        // printf(\"%d\\n\", idx);\n        grid[idx].particles.push_back(i);\n    }\n    for (int i = 0; i < P.rows(); i++) {\n\n        Eigen::Vector3d p = P.row(i);\n        Eigen::Vector3i ip = get_nn_cell_index(p);\n        for (int dx = -1; dx <= 1; dx++) {\n            for (int dy = -1; dy <= 1; dy++) {\n                for (int dz = -1; dz <= 1; dz++) {\n                    Eigen::Vector3i cell_idx = ip + Eigen::Vector3i(dx, dy, dz);\n                    if ((cell_idx.array() >= Eigen::Array3i::Zero()).all() &&\n                        (cell_idx.array() < nn_grid_size.array()).all()) {\n                        auto &cell = grid[get_nn_linear_index(cell_idx)];\n                        for (auto &j : cell.particles) {\n                            if (i == j)\n                                continue;\n                            Eigen::Vector3d q = P.row(j);\n                            if ((p - q).norm() < 2 * h) {\n                                neighbors[i].push_back(j);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    CHECK(neighbors.size() == P.rows());\n    // for (int i = 0; i < P.rows(); i++) {\n    tbb::parallel_for<int>(0, P.rows(), [&](int i) {\n        Eigen::Vector3d xi = P.row(i);\n        Eigen::Vector3d xiw(0, 0, 0);\n        Eigen::Matrix3d C;\n        Eigen::Vector3d x_bar(0.0, 0.0, 0.0);\n        const auto lambda = 0.92;\n        C.setZero();\n        if (!neighbors.empty()) {\n            double sum_w = 0.0;\n\n            for (auto &j : neighbors[i]) {\n                CHECK(j < P.rows());\n                Eigen::Vector3d xj = P.row(j);\n                const auto r = 2 * h;\n                auto w = 0.0;\n                if ((xi - xj).norm() <= r && (xi - xj).norm() > 0.0) {\n                    w = 1.0 - std::pow((xi - xj).norm() / r, 3);\n                }\n                sum_w += w;\n                xiw += w * xj;\n            }\n            xiw /= sum_w;\n            x_bar = (1.0 - lambda) * xi + lambda * xiw;\n            X.row(i) = x_bar;\n        } else {\n            X.row(i) = xi;\n            xiw = xi;\n        }\n        {\n            double sum_w = 0.0;\n            for (auto &j : neighbors[i]) {\n                Eigen::Vector3d xj = P.row(j);\n                const auto r = 2 * h;\n                auto w = 0.0;\n                if ((xi - xj).norm() <= r && (xi - xj).norm() > 0.0) {\n                    w = 1.0 - std::pow((xi - xj).norm() / r, 3);\n                }\n                sum_w += w;\n                C += w * (xj - xiw) * (xj - xiw).transpose();\n            }\n            // std::cout << C << std::endl;\n            C /= sum_w;\n        }\n        Eigen::JacobiSVD<Eigen::Matrix3d> svd(C, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        Eigen::Matrix3d R = svd.matrixU();\n        Eigen::Vector3d sigmas = svd.singularValues();\n        const auto kr = 4.0;\n        const auto ks = 1400.0;\n        const auto kn = 0.5;\n        const int Ne = 25;\n        double sigma1 = sigmas[0];\n        for (int i = 0; i < 3; i++) {\n            sigmas[i] = std::fmax(sigmas[i], sigma1 / kr);\n        }\n        auto N = (int)neighbors[i].size();\n        // std::cout << \"N: \" << N << std::endl;\n        Eigen::DiagonalMatrix<double, 3> Sigma;\n        if (N < Ne) {\n            Sigma = kn * Eigen::Vector3d::Ones().asDiagonal();\n        } else {\n            Sigma = ks * sigmas.asDiagonal();\n        }\n        G[i] = 1.0 / h * R * Sigma.inverse() * R.transpose();\n        // G[i] = 1.0 / h * Eigen::Matrix3d::Identity();\n        // std::cout << G[i] << std::endl;\n    });\n    for (auto &cell : grid) {\n        cell.particles.clear();\n    }\n    for (int i = 0; i < P.rows(); i++) {\n        Eigen::Vector3i ip = get_nn_cell_index(P.row(i));\n        auto idx = get_nn_linear_index(ip);\n        CHECK(idx < grid.size());\n        grid[idx].particles.push_back(i);\n    }\n    neighbors.clear();\n    neighbors.resize(GV.rows());\n    // for (int i = 0; i < GV.rows(); i++) {\n    tbb::parallel_for<int>(0, GV.rows(), [&](int i) {\n        // int x = i % res[0];\n        // int y = (i % (res[0] * res[1])) / res[0];\n        // int z = i / (res[0] * res[1]);\n        // Eigen::Vector3i gv_p(x, y, z);\n        Eigen::Vector3d p = GV.row(i);\n        Eigen::Vector3i ip = get_nn_cell_index(p);\n        for (int dx = -1; dx <= 1; dx++) {\n            for (int dy = -1; dy <= 1; dy++) {\n                for (int dz = -1; dz <= 1; dz++) {\n                    Eigen::Vector3i cell_idx = ip + Eigen::Vector3i(dx, dy, dz);\n                    if ((cell_idx.array() >= Eigen::Array3i::Zero()).all() &&\n                        (cell_idx.array() < nn_grid_size.array()).all()) {\n                        auto &cell = grid[get_nn_linear_index(cell_idx)];\n                        for (auto &j : cell.particles) {\n                            Eigen::Vector3d q = X.row(j);\n                            if ((p - q).norm() < 2 * h) {\n                                neighbors[i].push_back(j);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    });\n\n    // for (int i = 0; i < GV.rows(); i++) {\n    tbb::parallel_for<int>(0, GV.rows(), [&](int i) {\n        const double r = 2 * h;\n        // Eigen::Vector3i ip;\n        // {\n        //     int x = i % res[0];\n        //     int y = (i % (res[0] * res[1])) / res[0];\n        //     int z = i / (res[0] * res[1]);\n        //     ip = Eigen::Vector3i(x, y, z);\n        // }\n        Eigen::Vector3d x = GV.row(i);\n        double s = 0.0;\n        for (auto j : neighbors[i]) {\n            Eigen::Vector3d xj = X.row(j);\n            Eigen::Vector3d r = x - xj;\n            auto W = W_k / (h * h) * G[j].norm() * P1((G[j] * r).norm());\n            // std::cout << (G[j] * r).norm() << std::endl;\n            // std::cout << (r.norm() / h) << std::endl;\n            s += mass[j] / density[j] * W;\n        }\n        S[i] = s;\n\n        // double s = 0.0;\n        // for (auto j : neighbors[i]) {\n        //     Eigen::Vector3d xj = P.row(j);\n        //     Eigen::Vector3d r = x - xj;\n        //     auto W = W_k / (h * h * h) * P1(r.norm() / h);\n        //     s += mass[j] / density[j] * W;\n        // }\n\n        // S[i] = s;\n    });\n    // std::cout << S << std::endl;\n    printf(\"S.mean() = %f\\n\", S.mean());\n\n    marching_cubes(S, GV, res[0], res[1], res[2], isovalue, V, F);\n}", "meta": {"hexsha": "25a8f45ae296a60e10351481a1804fec32eb91a3", "size": 9900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/reconstruction.cpp", "max_stars_repo_name": "shiinamiyuki/Accurate-Large-Scale-Ferrofluids", "max_stars_repo_head_hexsha": "b39565ee94043b6ae19f14318af20f7489bc9312", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-12-22T04:19:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T15:47:32.000Z", "max_issues_repo_path": "src/reconstruction.cpp", "max_issues_repo_name": "shiinamiyuki/Accurate-Large-Scale-Ferrofluids", "max_issues_repo_head_hexsha": "b39565ee94043b6ae19f14318af20f7489bc9312", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reconstruction.cpp", "max_forks_repo_name": "shiinamiyuki/Accurate-Large-Scale-Ferrofluids", "max_forks_repo_head_hexsha": "b39565ee94043b6ae19f14318af20f7489bc9312", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-12-22T03:39:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T04:42:16.000Z", "avg_line_length": 39.7590361446, "max_line_length": 120, "alphanum_fraction": 0.4441414141, "num_tokens": 2990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5475727729668382}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <vector>\n#include <cstdlib>\n#include <fstream>\n\n#include \"world_rep.h\"\n\n\nint main(int argc, const char **argv)\n{\n    // Values for single neuron.\n    int snn_id = 2;\n    int n_inputs = 2;\n    int n_lateral = 1;\n    std::vector<double> init_d({2, 4});\n    std::vector<double> init_w({4});\n    double tau_m = 2;\n    double u_rest = 0;\n    double init_v = 20; // when testing math, make this large\n    unsigned char t_rest = 2;\n    double kappa_naugh = 3;\n    double round_zero = 0.1;\n    double u_max = 10;\n\n    SpikeResponseModelNeuron single_neuron = SpikeResponseModelNeuron(\n        snn_id, n_inputs, init_d, tau_m, u_rest,\n        init_v, t_rest, kappa_naugh, round_zero, u_max);\n    std::cout << \"Created individual neuron.\" << std::endl;\n\n    std::vector<std::vector<bool>> presynaptic_train = {\n        {0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0},\n        {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}\n    };\n\n\n    std::ofstream exp_res;\n    exp_res.open(\"experiment_results.log\");\n    exp_res << \"[\";\n    for(unsigned int epoch = 0; epoch < presynaptic_train.at(0).size(); epoch++)\n    {\n        exp_res << single_neuron.membrane_potential() << \", \";\n        // load dendrites with current value\n        single_neuron.dendrite.at(0) = DelayedSpike(0, presynaptic_train.at(0).at(epoch));\n        single_neuron.dendrite.at(1) = DelayedSpike(0, presynaptic_train.at(1).at(epoch));\n\n        // Move network forward\n        single_neuron.t_pulse();\n        \n    }\n    exp_res << \"]\" << std::endl;\n\n    printf(\"Testing FSTNs\\n\");\n    double alpha = 1;\n    FirstSpikeTimeNeuron fstn = FirstSpikeTimeNeuron(0, alpha);\n    fstn.dendrite = 2;\n    fstn.encode();\n\n    unsigned char total_pulses = 10;\n\n    exp_res << \"First Spike Time Neuron spike after \" << total_pulses << \"pulses.\" << std::endl << \"[\";\n    exp_res << fstn.axon.signal << \", \";\n    for(unsigned char pulse= 0; pulse < total_pulses; pulse++)\n    {\n        fstn.t_pulse();\n        exp_res << fstn.axon.signal << \", \";\n    }\n    exp_res << \"]\" << std::endl;\n\n    exp_res.close();\n\n    // Testing training algorthm\n    unsigned int n_data = 2;\n    tau_m = 0.8;\n    u_rest = 0;\n    init_v = 5;\n    unsigned int t_reset = 3;\n    double k_nought = 3;\n    round_zero = 0.05;\n    alpha = 1;\n    // note that n_x * n_y = h_layer_size\n    unsigned int n_x = 8;\n    unsigned int n_y = 8;\n    double delay_distance = 0.2;\n    unsigned int distance_unit = 1;\n    double sigma_neighbor = 1;\n    double eta_d = 1.7;\n    unsigned int t_max = 25;\n    u_max = 10;\n\n    printf(\"Create SNN\\n\");\n    SNN model(n_data, tau_m, u_rest, init_v, \n    t_reset, k_nought, round_zero, alpha, n_x, n_y, delay_distance,\n    distance_unit, sigma_neighbor, eta_d, t_max, u_max);\n\n    std::vector<std::vector<double>> data = {\n        {0, 0, 0, 1, 2, 2, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0},\n        {0, 1, 2, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 7, 6, 5, 4, 3, 2, 1, 0}\n    };\n    std::vector<std::vector<double>> data_2 = {\n        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n        {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1},\n    };\n\n    printf(\"Create output file\\n\");\n\n    // save delays into file:\n    std::ofstream delay_file;\n    delay_file.open(\"training_delays.txt\");\n    \n    // print out delays\n    delay_file << \"Delays before training:\" << std::endl;\n    for(unsigned int i = 0; i < model.snn->d_ji.size(); i++)\n    {\n        delay_file << \"[ \";\n        for(unsigned int j = 0; j < model.snn->d_ji.at(i).size(); j++)\n        {\n            delay_file << model.snn->d_ji.at(i).at(j) << \", \";\n        }\n        delay_file << \"]\" << std::endl;\n    }\n   \n    for(unsigned int p = 0; p < 1; p++)\n        model.train(data);\n\n    delay_file << std::endl << \"Delays after training:\"<< std::endl;\n     for(unsigned int i = 0; i < model.snn->d_ji.size(); i++)\n    {\n        delay_file << \"[ \";\n        for(unsigned int j = 0; j < model.snn->d_ji.at(i).size(); j++)\n        {\n            delay_file << model.snn->d_ji.at(i).at(j) << \", \";\n        }\n        delay_file << \"]\" << std::endl;\n    }\n\n\n    for(unsigned int p = 0; p < 8; p++, sigma_neighbor -= 0.1)\n    {\n        model = SNN(n_data, tau_m, u_rest, init_v, \n        t_reset, k_nought, round_zero, alpha, n_x, n_y, delay_distance,\n        distance_unit, sigma_neighbor, eta_d, t_max, u_max);\n        \n        model.train(data);\n\n        delay_file << std::endl << \"Delays after training with sigma_neighbor = \" << sigma_neighbor << \": \\n\" << std::endl;\n        for(unsigned int i = 0; i < model.snn->d_ji.size(); i++)\n        {\n            delay_file << \"[ \";\n            for(unsigned int j = 0; j < model.snn->d_ji.at(i).size(); j++)\n            {\n                delay_file << model.snn->d_ji.at(i).at(j) << \", \";\n            }\n            delay_file << \"]\" << std::endl;\n        }\n    }\n\n    printf(\"test world representation and planner.\\n\");\n\n\n    sigma_neighbor = 0.3;\n\n    std::ofstream planner_file;\n    planner_file.open(\"world_representation.txt\");\n\n    double prune_dist = 0.1;\n\n    WorldRep planner = WorldRep(k_nought, tau_m, init_v, round_zero,\n    n_x, n_y, delay_distance, sigma_neighbor, eta_d, t_max, u_max, \n    prune_dist);\n\n    planner.train(data);\n\n    planner_file << std::endl << \"Delays after training:\"<< std::endl;\n    for(unsigned int i = 0; i < planner.snn.snn->d_ji.size(); i++)\n    {\n        planner_file << \"[ \";\n        for(unsigned int j = 0; j < planner.snn.snn->d_ji.at(i).size(); j++)\n        {\n            planner_file << planner.snn.snn->d_ji.at(i).at(j) << \", \";\n        }\n        planner_file << \"]\" << std::endl;\n    }\n\n\n    std::vector<std::vector<double>> world_rep = planner.get_map();\n    \n    planner_file << std::endl << \"Delays after training with sigma_neighbor = \" << sigma_neighbor << \" and prunning with value:\" << prune_dist << std::endl;\n\n    for(unsigned int i = 0; i < world_rep.size(); i++)\n    {\n        planner_file << \"[ \";\n        for(unsigned int j = 0; j < world_rep.at(i).size(); j++)\n        {\n            planner_file << world_rep.at(i).at(j) << \", \";\n        }\n        planner_file << \"]\" << std::endl;\n    }\n\n    planner.dijkstra(28, 409);\n    std::vector<double> src_coor, goal_coor;\n    src_coor = std::vector<double>({0, 0});\n    goal_coor = std::vector<double>({0, 7});\n    std::vector<std::vector<double>> path = planner.get_path(WorldRep::PathAlgorithm::dijkstras, src_coor, goal_coor);\n    printf(\"[\");\n    for(unsigned int x = 0; x < path.at(0).size(); x++)\n    {\n        printf(\"[%f, %f], \", path.at(0).at(x), path.at(1).at(x));\n    }\n    printf(\"]\\n\");\n    planner_file.close();\n}", "meta": {"hexsha": "0ed47f326ccb809cb5d4465dbf7f17fdc460c36a", "size": 7000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_snn.cpp", "max_stars_repo_name": "aguilarjose11/world_rep_snn", "max_stars_repo_head_hexsha": "fa519f9cbe32b7ee61ff5514b361b2c73959d57c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-06T18:45:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-06T18:45:33.000Z", "max_issues_repo_path": "test_snn.cpp", "max_issues_repo_name": "aguilarjose11/world_rep_snn", "max_issues_repo_head_hexsha": "fa519f9cbe32b7ee61ff5514b361b2c73959d57c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-19T19:12:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-19T19:12:04.000Z", "max_forks_repo_path": "test_snn.cpp", "max_forks_repo_name": "aguilarjose11/world_rep_snn", "max_forks_repo_head_hexsha": "fa519f9cbe32b7ee61ff5514b361b2c73959d57c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-29T15:38:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T15:38:07.000Z", "avg_line_length": 33.0188679245, "max_line_length": 249, "alphanum_fraction": 0.5421428571, "num_tokens": 2497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.547572771148346}}
{"text": "// Copyright \u00a9 2016-2021 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#include <boost/math/special_functions/log1p.hpp>\n#include <vinecopulib/misc/tools_eigen.hpp>\n\nnamespace vinecopulib {\ninline ClaytonBicop::ClaytonBicop()\n{\n  family_ = BicopFamily::clayton;\n  parameters_ = Eigen::VectorXd(1);\n  parameters_lower_bounds_ = Eigen::VectorXd(1);\n  parameters_upper_bounds_ = Eigen::VectorXd(1);\n  parameters_ << 1e-10;\n  parameters_lower_bounds_ << 1e-10;\n  parameters_upper_bounds_ << 28;\n}\n\ninline double\nClaytonBicop::generator(const double& u)\n{\n  double theta = double(this->parameters_(0));\n  return (std::pow(u, -theta) - 1) / theta;\n}\n\ninline double\nClaytonBicop::generator_inv(const double& u)\n{\n  double theta = double(this->parameters_(0));\n  return std::pow(1 + theta * u, -1 / theta);\n}\n\ninline double\nClaytonBicop::generator_derivative(const double& u)\n{\n  return (-1) * std::pow(u, -1 - this->parameters_(0));\n}\n\n// inline double ClaytonBicop::generator_derivative2(const double &u)\n//{\n//    double theta = double(this->parameters_(0));\n//    return (1 + theta) * std::pow(u, -2 - theta);\n//}\n\ninline Eigen::VectorXd\nClaytonBicop::pdf_raw(const Eigen::MatrixXd& u)\n{\n  double theta = static_cast<double>(parameters_(0));\n  // avoid numerical issues when copula is too close to independence\n  if (theta < 1e-10) {\n    auto f = [](const double&, const double&) { return 1.0; };\n    return tools_eigen::binaryExpr_or_nan(u, f);\n  }\n\n  auto f = [theta](const double& u1, const double& u2) {\n    double temp = boost::math::log1p(theta) - (1.0 + theta) * std::log(u1 * u2);\n    temp = temp - (2.0 + 1.0 / (theta)) *\n                    std::log(std::pow(u1, -theta) + std::pow(u2, -theta) - 1.0);\n    return std::exp(temp);\n  };\n  return tools_eigen::binaryExpr_or_nan(u, f);\n}\n\ninline Eigen::VectorXd\nClaytonBicop::hinv1_raw(const Eigen::MatrixXd& u)\n{\n  double theta = double(this->parameters_(0));\n  Eigen::VectorXd hinv = u.col(0).array().pow(theta + 1.0);\n  if (theta < 75) {\n    hinv = u.col(1).cwiseProduct(hinv);\n    hinv = hinv.array().pow(-theta / (theta + 1.0));\n    Eigen::VectorXd x = u.col(0);\n    x = x.array().pow(-theta);\n    hinv = hinv - x + Eigen::VectorXd::Ones(x.size());\n    hinv = hinv.array().pow(-1 / theta);\n  } else {\n    hinv = hinv1_num(u);\n  }\n  return hinv;\n}\n\ninline Eigen::MatrixXd\nClaytonBicop::tau_to_parameters(const double& tau)\n{\n  Eigen::VectorXd parameters(1);\n  parameters(0) = 2 * std::fabs(tau) / (1 - std::fabs(tau));\n  return parameters.cwiseMax(parameters_lower_bounds_)\n    .cwiseMin(parameters_upper_bounds_);\n}\n\ninline double\nClaytonBicop::parameters_to_tau(const Eigen::MatrixXd& parameters)\n{\n  return parameters(0) / (2 + std::fabs(parameters(0)));\n}\n\ninline Eigen::VectorXd\nClaytonBicop::get_start_parameters(const double tau)\n{\n  Eigen::VectorXd par = tau_to_parameters(tau);\n  par = par.cwiseMax(parameters_lower_bounds_);\n  par = par.cwiseMin(parameters_upper_bounds_);\n  return par;\n}\n}\n", "meta": {"hexsha": "39135b15612fb78a748b3fce1e8507842d817674", "size": 3168, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "include/vinecopulib/bicop/implementation/clayton.ipp", "max_stars_repo_name": "tvatter/vinecoplib", "max_stars_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-05-05T13:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T23:40:01.000Z", "max_issues_repo_path": "include/vinecopulib/bicop/implementation/clayton.ipp", "max_issues_repo_name": "vinecopulib/vinecopulib", "max_issues_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 264.0, "max_issues_repo_issues_event_min_datetime": "2017-03-28T10:07:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T10:04:39.000Z", "max_forks_repo_path": "include/vinecopulib/bicop/implementation/clayton.ipp", "max_forks_repo_name": "tvatter/vinecoplib", "max_forks_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-04-24T13:54:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T16:56:17.000Z", "avg_line_length": 29.0642201835, "max_line_length": 80, "alphanum_fraction": 0.6824494949, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5475544944879164}}
{"text": "#include <armadillo>\n\n// json parser\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <utility>\nnamespace pt = boost::property_tree;\n\n#include \"ReflectionCoefficientsLocSlab.h\"\n\n// direct constructor\nReflectionCoefficientsLocSlab::ReflectionCoefficientsLocSlab(\n    std::shared_ptr<Permittivity> permittivity, double thickness)\n    : permittivity(std::move(permittivity)), thickness(thickness) {}\n\n// constructor from .json file\nReflectionCoefficientsLocSlab::ReflectionCoefficientsLocSlab(\n    const std::string &input_file) {\n  // set permittivity\n  // set parameters\n  this->permittivity = PermittivityFactory::create(input_file);\n  // Create a root\n  pt::ptree root;\n\n  // Load the json file in this ptree\n  pt::read_json(input_file, root);\n\n  // read parameters\n  this->thickness = root.get<double>(\"ReflectionCoefficients.thickness\");\n}\n\n// calculate the p-polarized reflection coefficient\nvoid ReflectionCoefficientsLocSlab::calculate(double omega,\n                                              std::complex<double> kappa,\n                                              std::complex<double> &r_p,\n                                              std::complex<double> &r_s) const {\n  // absolute value of omega. r_p is always calculated for positive omega and if\n  // needed complex conjugated after the calculation\n  double omega_abs = std::abs(omega);\n  std::complex<double> eps = this->permittivity->calculate(omega_abs);\n  std::complex<double> eps_omega = this->permittivity->calculate_times_omega(omega_abs);\n  std::complex<double> I(0., 1.);\n\n  // kapppa as well as kappa_epsilon are defined to have either a purely\n  // positive real part or purely negatively imaginary part\n  std::complex<double> kappa_epsilon =\n      sqrt(kappa * kappa - (eps - 1.) * omega_abs * omega_abs);\n  kappa_epsilon = std::complex<double>(std::abs(kappa_epsilon.real()),\n                                       -std::abs(kappa_epsilon.imag()));\n  // Defining the reflection coefficients in transverse magnetice polarization\n  // (p) and in transverse electric polarization (s)\n  std::complex<double> r_p_bulk =\n      (kappa * eps_omega - kappa_epsilon * omega_abs) / (kappa * eps_omega + kappa_epsilon * omega_abs);\n  std::complex<double> r_s_bulk =\n      (kappa - kappa_epsilon) / (kappa + kappa_epsilon);\n\n  r_p = r_p_bulk * (1. - exp(-2. * kappa_epsilon * this->thickness)) /\n        (1. - pow(r_p_bulk * exp(-kappa_epsilon * this->thickness), 2));\n  r_s = r_s_bulk * (1. - exp(-2. * kappa_epsilon * this->thickness)) /\n        (1. - pow(r_s_bulk * exp(-kappa_epsilon * this->thickness), 2));\n\n  // Imposing crossing relation\n  if (omega < 0.) {\n    r_p = conj(r_p);\n    r_s = conj(r_s);\n  }\n}\nvoid ReflectionCoefficientsLocSlab::print_info(std::ostream &stream) const {\n  stream << \"# ReflectionCoefficientsLocSlab\\n#\\n\"\n         << \"# thickness = \" << thickness << \"\\n\";\n  permittivity->print_info(stream);\n}\n", "meta": {"hexsha": "ad15de148357eff3e665e2aea98815313b9aad9e", "size": 2948, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ReflectionCoefficients/ReflectionCoefficientsLocSlab.cpp", "max_stars_repo_name": "QuaCaTeam/quaca", "max_stars_repo_head_hexsha": "ab2d213f3e0e357bd72930ae1e4e703184130270", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T09:01:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T07:57:54.000Z", "max_issues_repo_path": "src/ReflectionCoefficients/ReflectionCoefficientsLocSlab.cpp", "max_issues_repo_name": "myoelmy/quaca", "max_issues_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T08:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-28T07:33:35.000Z", "max_forks_repo_path": "src/ReflectionCoefficients/ReflectionCoefficientsLocSlab.cpp", "max_forks_repo_name": "myoelmy/quaca", "max_forks_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_forks_repo_licenses": ["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.3835616438, "max_line_length": 104, "alphanum_fraction": 0.6733378562, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.547554492667088}}
{"text": "/*\n * PolynomialSplineContainer.hpp\n *\n *  Created on: Dec 8, 2014\n *      Author: C. Dario Bellicoso, Peter Fankhauser\n */\n\n#pragma once\n\n#include \"curves/polynomial_splines.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <limits>\n\nnamespace curves {\n\nclass PolynomialSplineContainer {\n public:\n\n  using SplineType = PolynomialSplineQuintic;\n  using SplineList = std::vector<SplineType>;\n\n  PolynomialSplineContainer();\n  virtual ~PolynomialSplineContainer();\n\n  bool advance(double dt);\n  bool addSpline(const SplineType& spline);\n  bool addSpline(SplineType&& spline);\n  bool reset();\n  bool resetTime();\n\n  double getContainerDuration() const;\n\n  double getPosition() const;\n  double getVelocity() const;\n  double getAcceleration() const;\n\n  double getPositionAtTime(double t) const;\n  double getVelocityAtTime(double t) const;\n  double getAccelerationAtTime(double t) const;\n\n  double getEndPosition() const;\n  double getEndVelocity() const;\n  double getEndAcceleration() const;\n\n  double getContainerTime() const;\n\n  int getActiveSplineIndex() const;\n  int getActiveSplineIndexAtTime(double t, double& timeOffset) const;\n  bool isEmpty() const;\n\n  virtual void setData(const std::vector<double>& knotPositions,\n                       const std::vector<double>& knotValues,\n                       double initialVelocity,\n                       double initialAcceleration,\n                       double finalVelocity,\n                       double finalAcceleration);\n\n  SplineType* getSpline(int splineIndex);\n\n  void setContainerTime(double t);\n\n  const SplineList& getSplines() const;\n\n  static constexpr double undefinedValue = std::numeric_limits<double>::quiet_NaN();\n\n protected:\n  int getCoeffIndex(int splineIdx, int aIdx) const;\n  int getSplineColumnIndex(int splineIdx) const;\n\n  SplineList splines_;\n  double timeOffset_;\n  double containerTime_;\n  double containerDuration_;\n  int activeSplineIdx_;\n};\n\n} /* namespace */\n", "meta": {"hexsha": "8f3e6361bb76f04bc20eb0023828b73416a0dd56", "size": 1949, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "curves/include/curves/PolynomialSplineContainer.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/PolynomialSplineContainer.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/PolynomialSplineContainer.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": 24.6708860759, "max_line_length": 84, "alphanum_fraction": 0.7152385839, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5475544894723268}}
{"text": "// \n// Implements iLQR (on a traditional chain) for nonlinear dynamics and cost.\n//\n// Arun Venkatraman (arunvenk@cs.cmu.edu)\n// December 2016\n//\n\n#pragma once\n\n#include <ilqr/ilqr_taylor_expansions.hh>\n\n#include <Eigen/Dense>\n\n#include <tuple>\n#include <vector>\n\nnamespace ilqr\n{\n\nclass iLQR\n{\npublic:\n    // Stores linearization points x, u and the Taylor expansions of the dynamics and cost.\n    using TaylorExpansion = std::tuple<Eigen::VectorXd, Eigen::VectorXd, ilqr::Dynamics, ilqr::Cost>;\n\n    iLQR(const DynamicsFunc &dynamics, const CostFunc &cost, \n            const std::vector<Eigen::VectorXd> &Xs, \n            const std::vector<Eigen::VectorXd> &Us);\n\n    void backwards_pass();\n\n    void forward_pass(std::vector<double> &costs, \n            std::vector<Eigen::VectorXd> &states,\n            std::vector<Eigen::VectorXd> &controls, \n            bool update_linearizations\n            );\n\n    std::vector<Eigen::VectorXd> states();\n    std::vector<Eigen::VectorXd> controls();\n\nprivate:\n    int state_dim_ = -1;\n    int control_dim_  = -1;\n    int T_ = -1; // time horizon\n\n    DynamicsFunc true_dynamics_; \n    CostFunc true_cost_; \n\n    // Taylor series expansion points and expanded dynamics, cost.\n    std::vector<TaylorExpansion> expansions_;\n\n    // Feedback control gains.\n    std::vector<Eigen::MatrixXd> Ks_;\n    std::vector<Eigen::VectorXd> ks_;\n};\n\n} // namespace lqr\n\n", "meta": {"hexsha": "ecb4d0ddf3a3320aadcb956f57a308469d92bc90", "size": 1395, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/ilqr/iLQR.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.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.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": 23.6440677966, "max_line_length": 101, "alphanum_fraction": 0.6630824373, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5475544894723268}}
{"text": "#define BOOST_TEST_MODULE example\n#include <boost/test/included/unit_test.hpp>\n\n//____________________________________________________________________________//\n\n#include <cmath>\n\nBOOST_AUTO_TEST_CASE( test )\n{\n    double res = std::sin( 45. );\n\n    BOOST_WARN_MESSAGE( res > 1, \"sin(45){\" << res << \"} is <= 1. Hmm.. Strange. \" );\n}\n\n//____________________________________________________________________________//\n", "meta": {"hexsha": "f38a36331a244f7e706b247ea23638ec8312b932", "size": 416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/test/doc/src/examples/example38.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/test/doc/src/examples/example38.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/test/doc/src/examples/example38.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": 26.0, "max_line_length": 85, "alphanum_fraction": 0.7548076923, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5475544858306697}}
{"text": "/*\n# Copyright 2018 HyphaROS Workshop.\n# Developer: HaoChih, LIN (hypha.ros@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#include \"MPC_last.h\"\n//#include <cppad/cppad.hpp>\n#include <cppad/ipopt/solve.hpp>\n#include <Eigen/Core>\n\n// The program use fragments of code from\n// https://github.com/udacity/CarND-MPC-Quizzes\n\nusing CppAD::AD;\n\n// =========================================\n// FG_eval class definition implementation.\n// =========================================\nclass FG_eval \n{\n    public:\n        // Fitted polynomial coefficients\n        Eigen::VectorXd coeffs;\n\n        double _dt, _ref_cte, _ref_etheta, _ref_vel; \n        double  _w_cte, _w_etheta, _w_vel, _w_angvel, _w_accel, _w_angvel_d, _w_accel_d;\n        int _mpc_steps, _x_start, _y_start, _theta_start, _v_start, _cte_start, _etheta_start, _angvel_start, _a_start;\n\n        AD<double> cost_cte, cost_etheta, cost_vel;\n        // Constructor\n        FG_eval(Eigen::VectorXd coeffs) \n        { \n            this->coeffs = coeffs; \n\n            // Set default value    \n            _dt = 0.1;  // in sec\n            _ref_cte   = 0;\n            _ref_etheta  = 0;\n            _ref_vel   = 0.5; // m/s\n            _w_cte     = 100;\n            _w_etheta    = 100;\n            _w_vel     = 1;\n            _w_angvel   = 100;\n            _w_accel   = 50;\n            _w_angvel_d = 0;\n            _w_accel_d = 0;\n\n            _mpc_steps   = 40;\n            _x_start     = 0;\n            _y_start     = _x_start + _mpc_steps;\n            _theta_start   = _y_start + _mpc_steps;\n            _v_start     = _theta_start + _mpc_steps;\n            _cte_start   = _v_start + _mpc_steps;\n            _etheta_start  = _cte_start + _mpc_steps;\n            _angvel_start = _etheta_start + _mpc_steps;\n            _a_start     = _angvel_start + _mpc_steps - 1;\n        }\n\n        // Load parameters for constraints\n        void LoadParams(const std::map<string, double> &params)\n        {\n            _dt = params.find(\"DT\") != params.end() ? params.at(\"DT\") : _dt;\n            _mpc_steps = params.find(\"STEPS\") != params.end()    ? params.at(\"STEPS\") : _mpc_steps;\n            _ref_cte   = params.find(\"REF_CTE\") != params.end()  ? params.at(\"REF_CTE\") : _ref_cte;\n            _ref_etheta  = params.find(\"REF_ETHETA\") != params.end() ? params.at(\"REF_ETHETA\") : _ref_etheta;\n            _ref_vel   = params.find(\"REF_V\") != params.end()    ? params.at(\"REF_V\") : _ref_vel;\n            \n            _w_cte   = params.find(\"W_CTE\") != params.end()   ? params.at(\"W_CTE\") : _w_cte;\n            _w_etheta  = params.find(\"W_EPSI\") != params.end()  ? params.at(\"W_EPSI\") : _w_etheta;\n            _w_vel   = params.find(\"W_V\") != params.end()     ? params.at(\"W_V\") : _w_vel;\n            _w_angvel = params.find(\"W_ANGVEL\") != params.end() ? params.at(\"W_ANGVEL\") : _w_angvel;\n            _w_accel = params.find(\"W_A\") != params.end()     ? params.at(\"W_A\") : _w_accel;\n            _w_angvel_d = params.find(\"W_DANGVEL\") != params.end() ? params.at(\"W_DANGVEL\") : _w_angvel_d;\n            _w_accel_d = params.find(\"W_DA\") != params.end()     ? params.at(\"W_DA\") : _w_accel_d;\n\n            _x_start     = 0;\n            _y_start     = _x_start + _mpc_steps;\n            _theta_start   = _y_start + _mpc_steps;\n            _v_start     = _theta_start + _mpc_steps;\n            _cte_start   = _v_start + _mpc_steps;\n            _etheta_start  = _cte_start + _mpc_steps;\n            _angvel_start = _etheta_start + _mpc_steps;\n            _a_start     = _angvel_start + _mpc_steps - 1;\n            \n            //cout << \"\\n!! FG_eval Obj parameters updated !! \" << _mpc_steps << endl; \n        }\n\n        // MPC implementation (cost func & constraints)\n        typedef CPPAD_TESTVECTOR(AD<double>) ADvector; \n        // fg: function that evaluates the objective and constraints using the syntax       \n        void operator()(ADvector& fg, const ADvector& vars) \n        {\n            // fg[0] for cost function\n            fg[0] = 0;\n            cost_cte =  0;\n            cost_etheta = 0;\n            cost_vel = 0;\n\n            /*\n            for (int i = 0; i < _mpc_steps; i++) \n            {\n                cout << i << endl;\n                cout << \"_x_start\" << vars[_x_start + i] <<endl;\n                cout << \"_y_start\" << vars[_y_start + i] <<endl;\n                cout << \"_theta_start\" << vars[_theta_start + i] <<endl;\n                cout << \"_v_start\" << vars[_v_start + i] <<endl;\n                cout << \"_cte_start\" << vars[_cte_start + i] <<endl;\n                cout << \"_etheta_start\" << vars[_etheta_start + i] <<endl;\n            }*/\n\n            for (int i = 0; i < _mpc_steps; i++) \n            {\n              fg[0] += _w_cte * CppAD::pow(vars[_cte_start + i] - _ref_cte, 2); // cross deviation error\n              fg[0] += _w_etheta * CppAD::pow(vars[_etheta_start + i] - _ref_etheta, 2); // heading error\n              fg[0] += _w_vel * CppAD::pow(vars[_v_start + i] - _ref_vel, 2); // speed error\n\n              cost_cte +=  _w_cte * CppAD::pow(vars[_cte_start + i] - _ref_cte, 2);\n              cost_etheta +=  (_w_etheta * CppAD::pow(vars[_etheta_start + i] - _ref_etheta, 2)); \n              cost_vel +=  (_w_vel * CppAD::pow(vars[_v_start + i] - _ref_vel, 2)); \n            }\n            cout << \"-----------------------------------------------\" <<endl;\n            cout << \"cost_cte, etheta, velocity: \" << cost_cte << \", \" << cost_etheta  << \", \" << cost_vel << endl;\n            \n\n            // Minimize the use of actuators.\n            for (int i = 0; i < _mpc_steps - 1; i++) {\n              fg[0] += _w_angvel * CppAD::pow(vars[_angvel_start + i], 2);\n              fg[0] += _w_accel * CppAD::pow(vars[_a_start + i], 2);\n            }\n            cout << \"cost of actuators: \" << fg[0] << endl; \n\n            // Minimize the value gap between sequential actuations.\n            for (int i = 0; i < _mpc_steps - 2; i++) {\n              fg[0] += _w_angvel_d * CppAD::pow(vars[_angvel_start + i + 1] - vars[_angvel_start + i], 2);\n              fg[0] += _w_accel_d * CppAD::pow(vars[_a_start + i + 1] - vars[_a_start + i], 2);\n            }\n            cout << \"cost of gap: \" << fg[0] << endl; \n            \n\n            // fg[x] for constraints\n            // Initial constraints\n            fg[1 + _x_start] = vars[_x_start];\n            fg[1 + _y_start] = vars[_y_start];\n            fg[1 + _theta_start] = vars[_theta_start];\n            fg[1 + _v_start] = vars[_v_start];\n            fg[1 + _cte_start] = vars[_cte_start];\n            fg[1 + _etheta_start] = vars[_etheta_start];\n\n            // Add system dynamic model constraint\n            for (int i = 0; i < _mpc_steps - 1; i++)\n            {\n                // The state at time t+1 .\n                AD<double> x1 = vars[_x_start + i + 1];\n                AD<double> y1 = vars[_y_start + i + 1];\n                AD<double> theta1 = vars[_theta_start + i + 1];\n                AD<double> v1 = vars[_v_start + i + 1];\n                AD<double> cte1 = vars[_cte_start + i + 1];\n                AD<double> etheta1 = vars[_etheta_start + i + 1];\n\n                // The state at time t.\n                AD<double> x0 = vars[_x_start + i];\n                AD<double> y0 = vars[_y_start + i];\n                AD<double> theta0 = vars[_theta_start + i];\n                AD<double> v0 = vars[_v_start + i];\n                AD<double> cte0 = vars[_cte_start + i];\n                AD<double> etheta0 = vars[_etheta_start + i];\n\n                // Only consider the actuation at time t.\n                //AD<double> angvel0 = vars[_angvel_start + i];\n                AD<double> w0 = vars[_angvel_start + i];\n                AD<double> a0 = vars[_a_start + i];\n\n\n                //AD<double> f0 = coeffs[0] + coeffs[1] * x0 + coeffs[2] * CppAD::pow(x0, 2) + coeffs[3] * CppAD::pow(x0, 3);\n                AD<double> f0 = 0.0;\n                for (int i = 0; i < coeffs.size(); i++) \n                {\n                    f0 += coeffs[i] * CppAD::pow(x0, i); //f(0) = y\n                }\n\n                //AD<double> trj_grad0 = CppAD::atan(coeffs[1] + 2 * coeffs[2] * x0 + 3 * coeffs[3] * CppAD::pow(x0, 2));\n                AD<double> trj_grad0 = 0.0;\n                for (int i = 1; i < coeffs.size(); i++) \n                {\n                    trj_grad0 += i*coeffs[i] * CppAD::pow(x0, i-1); // f'(x0) = f(1)/1\n                }\n                trj_grad0 = CppAD::atan(trj_grad0);\n\n\n                // Here's `x` to get you started.\n                // The idea here is to constraint this value to be 0.\n                //\n                // NOTE: The use of `AD<double>` and use of `CppAD`!\n                // This is also CppAD can compute derivatives and pass\n                // these to the solver.\n                // TODO: Setup the rest of the model constraints\n                fg[2 + _x_start + i] = x1 - (x0 + v0 * CppAD::cos(theta0) * _dt);\n                fg[2 + _y_start + i] = y1 - (y0 + v0 * CppAD::sin(theta0) * _dt);\n                fg[2 + _theta_start + i] = theta1 - (theta0 +  w0 * _dt);\n                fg[2 + _v_start + i] = v1 - (v0 + a0 * _dt);\n                \n                fg[2 + _cte_start + i] = cte1 - ((f0 - y0) + (v0 * CppAD::sin(etheta0) * _dt));\n                //fg[2 + _etheta_start + i] = etheta1 - ((theta0 - trj_grad0) + w0 * _dt);//theta0-trj_grad0)->etheta : it can have more curvature prediction, but its gradient can be only adjust positive plan.   \n                fg[2 + _etheta_start + i] = etheta1 - (etheta0 + w0 * _dt);\n            }\n        }\n};\n\n// ====================================\n// MPC class definition implementation.\n// ====================================\nMPC::MPC() \n{\n    // Set default value    \n    _mpc_steps = 20;\n    _max_angvel = 3.0; // Maximal angvel radian (~30 deg)\n    _max_throttle = 1.0; // Maximal throttle accel\n    _bound_value  = 1.0e3; // Bound value for other variables\n\n    _x_start     = 0;\n    _y_start     = _x_start + _mpc_steps;\n    _theta_start   = _y_start + _mpc_steps;\n    _v_start     = _theta_start + _mpc_steps;\n    _cte_start   = _v_start + _mpc_steps;\n    _etheta_start  = _cte_start + _mpc_steps;\n    _angvel_start = _etheta_start + _mpc_steps;\n    _a_start     = _angvel_start + _mpc_steps - 1;\n\n}\n\nvoid MPC::LoadParams(const std::map<string, double> &params)\n{\n    _params = params;\n    //Init parameters for MPC object\n    _mpc_steps = _params.find(\"STEPS\") != _params.end() ? _params.at(\"STEPS\") : _mpc_steps;\n    _max_angvel = _params.find(\"ANGVEL\") != _params.end() ? _params.at(\"ANGVEL\") : _max_angvel;\n    _max_throttle = _params.find(\"MAXTHR\") != _params.end() ? _params.at(\"MAXTHR\") : _max_throttle;\n    _bound_value  = _params.find(\"BOUND\") != _params.end()  ? _params.at(\"BOUND\") : _bound_value;\n    \n    _x_start     = 0;\n    _y_start     = _x_start + _mpc_steps;\n    _theta_start   = _y_start + _mpc_steps;\n    _v_start     = _theta_start + _mpc_steps;\n    _cte_start   = _v_start + _mpc_steps;\n    _etheta_start  = _cte_start + _mpc_steps;\n    _angvel_start = _etheta_start + _mpc_steps;\n    _a_start     = _angvel_start + _mpc_steps - 1;\n\n    cout << \"\\n!! MPC Obj parameters updated !! \" << endl; \n}\n\n\nvector<double> MPC::Solve(Eigen::VectorXd state, Eigen::VectorXd coeffs) \n{\n    bool ok = true;\n    size_t i;\n    typedef CPPAD_TESTVECTOR(double) Dvector;\n    const double x = state[0];\n    const double y = state[1];\n    const double theta = state[2];\n    const double v = state[3];\n    const double cte = state[4];\n    const double etheta = state[5];\n\n    // Set the number of model variables (includes both states and inputs).\n    // For example: If the state is a 4 element vector, the actuators is a 2\n    // element vector and there are 10 timesteps. The number of variables is:\n    // 4 * 10 + 2 * 9\n    size_t n_vars = _mpc_steps * 6 + (_mpc_steps - 1) * 2;\n    \n    // Set the number of constraints\n    size_t n_constraints = _mpc_steps * 6;\n\n    // Initial value of the independent variables.\n    // SHOULD BE 0 besides initial state.\n    Dvector vars(n_vars);\n    for (int i = 0; i < n_vars; i++) \n    {\n        vars[i] = 0;\n    }\n\n    // Set the initial variable values\n    vars[_x_start] = x;\n    vars[_y_start] = y;\n    vars[_theta_start] = theta;\n    vars[_v_start] = v;\n    vars[_cte_start] = cte;\n    vars[_etheta_start] = etheta;\n\n    // Set lower and upper limits for variables.\n    Dvector vars_lowerbound(n_vars);\n    Dvector vars_upperbound(n_vars);\n    \n    // Set all non-actuators upper and lowerlimits\n    // to the max negative and positive values.\n    for (int i = 0; i < _angvel_start; i++) \n    {\n        vars_lowerbound[i] = -_bound_value;\n        vars_upperbound[i] = _bound_value;\n    }\n    // The upper and lower limits of angvel are set to -25 and 25\n    // degrees (values in radians).\n    for (int i = _angvel_start; i < _a_start; i++) \n    {\n        vars_lowerbound[i] = -_max_angvel;\n        vars_upperbound[i] = _max_angvel;\n    }\n    // Acceleration/decceleration upper and lower limits\n    for (int i = _a_start; i < n_vars; i++)  \n    {\n        vars_lowerbound[i] = -_max_throttle;\n        vars_upperbound[i] = _max_throttle;\n    }\n\n\n    // Lower and upper limits for the constraints\n    // Should be 0 besides initial state.\n    Dvector constraints_lowerbound(n_constraints);\n    Dvector constraints_upperbound(n_constraints);\n    for (int i = 0; i < n_constraints; i++)\n    {\n        constraints_lowerbound[i] = 0;\n        constraints_upperbound[i] = 0;\n    }\n    constraints_lowerbound[_x_start] = x;\n    constraints_lowerbound[_y_start] = y;\n    constraints_lowerbound[_theta_start] = theta;\n    constraints_lowerbound[_v_start] = v;\n    constraints_lowerbound[_cte_start] = cte;\n    constraints_lowerbound[_etheta_start] = etheta;\n    constraints_upperbound[_x_start] = x;\n    constraints_upperbound[_y_start] = y;\n    constraints_upperbound[_theta_start] = theta;\n    constraints_upperbound[_v_start] = v;\n    constraints_upperbound[_cte_start] = cte;\n    constraints_upperbound[_etheta_start] = etheta;\n\n    // object that computes objective and constraints\n    FG_eval fg_eval(coeffs);\n    fg_eval.LoadParams(_params);\n\n\n    // options for IPOPT solver\n    std::string options;\n    // Uncomment this if you'd like more print information\n    options += \"Integer print_level  0\\n\";\n    // NOTE: Setting sparse to true allows the solver to take advantage\n    // of sparse routines, this makes the computation MUCH FASTER. If you\n    // can uncomment 1 of these and see if it makes a difference or not but\n    // if you uncomment both the computation time should go up in orders of\n    // magnitude.\n    options += \"Sparse  true        forward\\n\";\n    options += \"Sparse  true        reverse\\n\";\n    // NOTE: Currently the solver has a maximum time limit of 0.5 seconds.\n    // Change this as you see fit.\n    options += \"Numeric max_cpu_time          0.5\\n\";\n\n    // place to return solution\n    CppAD::ipopt::solve_result<Dvector> solution;\n\n    // solve the problem\n    CppAD::ipopt::solve<Dvector, FG_eval>(\n      options, vars, vars_lowerbound, vars_upperbound, constraints_lowerbound,\n      constraints_upperbound, fg_eval, solution);\n\n    // Check some of the solution values\n    ok &= solution.status == CppAD::ipopt::solve_result<Dvector>::success;\n\n    // Cost\n    auto cost = solution.obj_value;\n    std::cout << \"------------ Total Cost(solution): \" << cost << \"------------\" << std::endl;\n    cout << \"-----------------------------------------------\" <<endl;\n\n    this->mpc_x = {};\n    this->mpc_y = {};\n    this->mpc_theta = {};\n    for (int i = 0; i < _mpc_steps; i++) \n    {\n        this->mpc_x.push_back(solution.x[_x_start + i]);\n        this->mpc_y.push_back(solution.x[_y_start + i]);\n        this->mpc_theta.push_back(solution.x[_theta_start + i]);\n    }\n    \n    vector<double> result;\n    result.push_back(solution.x[_angvel_start]);\n    result.push_back(solution.x[_a_start]);\n    return result;\n}\n", "meta": {"hexsha": "b48fd3edb086b4de7ee5fc6b74c786141351af0b", "size": 16442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MPC_last.cpp", "max_stars_repo_name": "fangzheng81/mpc_ros", "max_stars_repo_head_hexsha": "3b438cff3a8ed03f3df9cabafa8b8fad88934811", "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/MPC_last.cpp", "max_issues_repo_name": "fangzheng81/mpc_ros", "max_issues_repo_head_hexsha": "3b438cff3a8ed03f3df9cabafa8b8fad88934811", "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/MPC_last.cpp", "max_forks_repo_name": "fangzheng81/mpc_ros", "max_forks_repo_head_hexsha": "3b438cff3a8ed03f3df9cabafa8b8fad88934811", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-05T12:30:19.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-30T13:13:40.000Z", "avg_line_length": 41.0024937656, "max_line_length": 212, "alphanum_fraction": 0.5578396789, "num_tokens": 4712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5475544858306697}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp> \n\nusing namespace std; \nusing namespace boost; \ntypedef boost::adjacency_list<listS, vecS, undirectedS> graphAL; \n\nint main() { \n  graphAL g;\n  add_edge(0, 1, g);\n  add_edge(0, 3, g);\n  add_edge(1, 2, g);\n  add_edge(2, 3, g);\n  graphAL::vertex_iterator vertexIt, vertexEnd;\n  graphAL::adjacency_iterator neighbourIt, neighbourEnd;\n  tie(vertexIt, vertexEnd) = vertices(g);\n  for (; vertexIt != vertexEnd; ++vertexIt) { \n    cout << *vertexIt << \" is connected with \"; \n    tie(neighbourIt, neighbourEnd) = adjacent_vertices(*vertexIt, g); \n    for (; neighbourIt != neighbourEnd; ++neighbourIt) cout << *neighbourIt << \" \"; \n    cout << \"\\n\"; \n  }\n}\n", "meta": {"hexsha": "75cb5b302c022fcb44ded5362b9ce4aac130c8a1", "size": 712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "practice/graph0.cpp", "max_stars_repo_name": "ShiZhan/graph-study", "max_stars_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-14T07:27:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-15T03:11:31.000Z", "max_issues_repo_path": "practice/graph0.cpp", "max_issues_repo_name": "Zhan2012/graph-study", "max_issues_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practice/graph0.cpp", "max_forks_repo_name": "Zhan2012/graph-study", "max_forks_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "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.6666666667, "max_line_length": 84, "alphanum_fraction": 0.6699438202, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867969424066, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5475158034818175}}
{"text": "/***************************************************************************\n *   Copyright (c) 2011 Konstantinos Poulios <logari81@gmail.com>          *\n *                                                                         *\n *   This file is part of the FreeCAD CAx development system.              *\n *                                                                         *\n *   This library is free software; you can redistribute it and/or         *\n *   modify it under the terms of the GNU Library General Public           *\n *   License as published by the Free Software Foundation; either          *\n *   version 2 of the License, or (at your option) any later version.      *\n *                                                                         *\n *   This library  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 Library General Public License for more details.                  *\n *                                                                         *\n *   You should have received a copy of the GNU Library General Public     *\n *   License along with this library; see the file COPYING.LIB. If not,    *\n *   write to the Free Software Foundation, Inc., 59 Temple Place,         *\n *   Suite 330, Boston, MA  02111-1307, USA                                *\n *                                                                         *\n ***************************************************************************/\n\n#ifdef _MSC_VER\n#pragma warning(disable : 4244)\n#endif\n\n#include <iostream>\n#include <Eigen/QR>\n\nusing namespace Eigen;\n\n// minimizes ( 0.5 * x^T * H * x + g^T * x ) under the condition ( A*x + c = 0 )\n// it returns the solution in x, the row-space of A in Y, and the null space of A in Z\nint qp_eq(MatrixXd &H, VectorXd &g, MatrixXd &A, VectorXd &c,\n          VectorXd &x, MatrixXd &Y, MatrixXd &Z)\n{\n    FullPivHouseholderQR<MatrixXd> qrAT(A.transpose());\n    MatrixXd Q = qrAT.matrixQ ();\n\n    size_t params_num = qrAT.rows();\n    size_t constr_num = qrAT.cols();\n    size_t rank = qrAT.rank();\n\n    if (rank != constr_num || constr_num > params_num)\n        return -1;\n\n    // A^T = Q*R*P^T = Q1*R1*P^T\n    // Q = [Q1,Q2], R=[R1;0]\n    // Y = Q1 * inv(R^T) * P^T\n    // Z = Q2\n    Y = qrAT.matrixQR().topRows(constr_num)\n                       .triangularView<Upper>()\n                       .transpose()\n                       .solve<OnTheRight>(Q.leftCols(rank))\n        * qrAT.colsPermutation().transpose();\n    if (params_num == rank)\n        x = - Y * c;\n    else {\n        Z = Q.rightCols(params_num-rank);\n\n        MatrixXd ZTHZ = Z.transpose() * H * Z;\n        VectorXd rhs = Z.transpose() * (H * Y * c - g);\n\n        VectorXd y = ZTHZ.colPivHouseholderQr().solve(rhs);\n\n        x = - Y * c + Z * y;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "7eeb58fafc13e2c34f1743b6ee0b7686bd033269", "size": 2954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/PlaneGCS/qp_eq.cpp", "max_stars_repo_name": "xzrunner/constraints2", "max_stars_repo_head_hexsha": "91a48120afdd06a21124a2fb79bcc9f6d05045c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-14T06:34:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T06:34:14.000Z", "max_issues_repo_path": "external/PlaneGCS/qp_eq.cpp", "max_issues_repo_name": "xzrunner/constraints2", "max_issues_repo_head_hexsha": "91a48120afdd06a21124a2fb79bcc9f6d05045c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-14T08:42:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-17T12:37:56.000Z", "max_forks_repo_path": "external/PlaneGCS/qp_eq.cpp", "max_forks_repo_name": "xzrunner/constraints2", "max_forks_repo_head_hexsha": "91a48120afdd06a21124a2fb79bcc9f6d05045c2", "max_forks_repo_licenses": ["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.6056338028, "max_line_length": 86, "alphanum_fraction": 0.4749492214, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5475157968957475}}
{"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_ARCH_COMMON_SIMD_FUNCTION_FRAC_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_FRAC_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/function/if_allbits_else.hpp>\n#include <boost/simd/function/is_invalid.hpp>\n#include <boost/simd/function/trunc.hpp>\n#include <boost/simd/constant/zero.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF(frac_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::arithmetic_<A0>, X>\n                          )\n   {\n     BOOST_FORCEINLINE A0 operator()(const A0&)const\n      {\n        return Zero<A0>();\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD_IF(frac_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        return if_allbits_else(is_invalid(a0), a0-bs::trunc(a0));\n      }\n   };\n\n} } }\n#endif\n\n\n", "meta": {"hexsha": "d40fff72942361177fdf02f2c688f26d11e432c3", "size": 1728, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/frac.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/arch/common/simd/function/frac.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/arch/common/simd/function/frac.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.4181818182, "max_line_length": 100, "alphanum_fraction": 0.5179398148, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5475157917713086}}
{"text": "//\n// Created by cheyulin on 7/10/16.\n//\n\n#define some_int 1\n\nstruct some_type;\n//\u7f16\u5199\u5143\u51fd\u6570\u5c31\u50cf\u662f\u7f16\u5199\u4e00\u4e2a\u666e\u901a\u7684\u8fd0\u884c\u51fd\u6570\uff0c\u4f46\u5f62\u5f0f\u4e0a\u786e\u662f\u4e00\u4e2a\u6a21\u677f\u7c7b\ntemplate<typename arg1, typename arg2> // \u5143\u51fd\u6570\u53c2\u6570\u5217\u8868\nstruct meta_function {\n    typedef some_type type;  //type \u662f \u5143\u6570\u636e  \u503c\u4e3a some_type\n    //using type = some_type\n    static int const value = some_int;\n};\n\n#include <boost/config.hpp>\n#include <iostream>\n\ntemplate<int N, int M>  //\u4e24\u4e2a\u6574\u6570\u5143\u6570\u636e\nstruct meta_function1 {\n    BOOST_STATIC_CONSTANT(int, value = N + M); //\u7f16\u8bd1\u5668\u8ba1\u7b97\u6574\u6570\u4e4b\u548c\n};\n\nint main() {\n    using namespace std;\n    cout << meta_function1<10, 10>::value << endl;\n}", "meta": {"hexsha": "782e9adc10882366a6e65018ad916eb5448ab991", "size": 575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Meta-Programming/MetaFunction.cpp", "max_stars_repo_name": "YcheLanguageStudio/STL-Study", "max_stars_repo_head_hexsha": "ac8ad4ef2c3b381b40c29f63ffc651550ec0949a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-02-07T07:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-29T06:01:51.000Z", "max_issues_repo_path": "Meta-Programming/MetaFunction.cpp", "max_issues_repo_name": "CheYulin/STL-Study", "max_issues_repo_head_hexsha": "ac8ad4ef2c3b381b40c29f63ffc651550ec0949a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Meta-Programming/MetaFunction.cpp", "max_forks_repo_name": "CheYulin/STL-Study", "max_forks_repo_head_hexsha": "ac8ad4ef2c3b381b40c29f63ffc651550ec0949a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-11T09:46:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-04T04:55:54.000Z", "avg_line_length": 21.2962962963, "max_line_length": 58, "alphanum_fraction": 0.6956521739, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5475157851852385}}
{"text": "#include <NTL/quad_float.h>\n#include <NTL/RR.h>\n\n#include <cfloat>\n\nNTL_START_IMPL\n\n\n#if (NTL_BITS_PER_LONG >= NTL_DOUBLE_PRECISION)\n\n\nquad_float to_quad_float(long n)\n{\n   double xhi, xlo;\n\n   xhi = TrueDouble(n);\n\n   // Because we are assuming 2's compliment integer\n   // arithmetic, the following prevents long(xhi) from overflowing.\n\n   if (n > 0)\n      xlo = TrueDouble(n+long(-xhi));\n   else\n      xlo = TrueDouble(n-long(xhi));\n\n   // renormalize...just to be safe\n\n   quad_float z;\n   quad_float_normalize(z, xhi, xlo);\n   return z;\n}\n\nquad_float to_quad_float(unsigned long n)\n{\n   double xhi, xlo, t;\n\n   const double bnd = double(1L << (NTL_BITS_PER_LONG-2))*4.0;\n\n   xhi = TrueDouble(n);\n   \n   if (xhi >= bnd)\n      t = xhi - bnd;\n   else\n      t = xhi;\n\n   // we use the \"to_long\" function here to be as portable as possible.\n   long llo = to_long(n - (unsigned long)(t));\n   xlo = TrueDouble(llo);\n\n   quad_float z;\n   quad_float_normalize(z, xhi, xlo);\n   return z;\n}\n#endif\n\n\nNTL_CHEAP_THREAD_LOCAL\nlong quad_float::oprec = 10;\n\nvoid quad_float::SetOutputPrecision(long p)\n{\n   if (p < 1) p = 1;\n\n   if (NTL_OVERFLOW(p, 1, 0)) \n      ResourceError(\"quad_float: output precision too big\");\n\n   oprec = p;\n}\n\n\n\nvoid power(quad_float& z, const quad_float& a, long e)\n{\n   quad_float res, u;\n   unsigned long k;\n\n   if (e < 0)\n      k = -((unsigned long) e);\n   else\n      k = e;\n\n   res = 1.0;\n   u = a;\n\n   while (k) {\n      if (k & 1)\n         res = res * u;\n\n      k = k >> 1;\n      if (k)\n         u = u * u;\n   }\n\n   if (e < 0)\n      z = 1.0/res;\n   else\n      z = res;\n}\n\n\nvoid power2(quad_float& z, long e)\n{\n   z.hi = _ntl_ldexp(1.0, e);\n   z.lo = 0;\n}\n\n\nlong to_long(const quad_float& x)\n{\n   double fhi, flo;\n\n   fhi = floor(x.hi);\n\n   if (fhi == x.hi) \n      flo = floor(x.lo);\n   else\n      flo = 0;\n\n   // the following code helps to prevent unnecessary integer overflow,\n   // and guarantees that to_long(to_quad_float(a)) == a, for all long a,\n   // provided long's are not too wide.\n\n   if (fhi > 0)\n      return long(flo) - long(-fhi);\n   else\n      return long(fhi) + long(flo);\n}\n\n\n\n// This version of ZZ to quad_float coversion relies on the\n// precise rounding rules implemented by the ZZ to double conversion.\n\n\nvoid conv(quad_float& z, const ZZ& a)\n{\n   double xhi, xlo;\n\n   conv(xhi, a);\n\n   if (!IsFinite(&xhi)) {\n      z.hi = xhi;\n      z.lo = 0;\n      return;\n   }\n\n   NTL_ZZRegister(t);\n\n   conv(t, xhi);\n   sub(t, a, t);\n\n   conv(xlo, t);\n\n   quad_float_normalize(z, xhi, xlo);\n} \n\nvoid conv(ZZ& z, const quad_float& x)\n{ \n   NTL_ZZRegister(t1);\n   NTL_ZZRegister(t2);\n   NTL_ZZRegister(t3);\n\n   double fhi, flo;\n\n   fhi = floor(x.hi);\n\n   if (fhi == x.hi) {\n      flo = floor(x.lo);\n\n      conv(t1, fhi);\n      conv(t2, flo);\n\n      add(z, t1, t2);\n   }\n   else\n      conv(z, fhi);\n}\n\n\n\nostream& operator<<(ostream& s, const quad_float& a)\n{\n   quad_float aa = a;\n\n   if (!IsFinite(&aa)) {\n      s << \"NaN\";\n      return s;\n   }\n\n   RRPush push;\n   RROutputPush opush;\n\n   RR::SetPrecision(long(3.33*quad_float::oprec) + 10);\n   RR::SetOutputPrecision(quad_float::oprec);\n\n   NTL_TLS_LOCAL(RR, t);\n\n   conv(t, a);\n   s << t;\n\n   return s;\n}\n\nistream& operator>>(istream& s, quad_float& x)\n{\n   RRPush push;\n   RR::SetPrecision(4*NTL_DOUBLE_PRECISION);\n\n   NTL_TLS_LOCAL(RR, t);\n   NTL_INPUT_CHECK_RET(s, s >> t);\n   conv(x, t);\n\n   return s;\n}\n\nvoid random(quad_float& x)\n{\n   RRPush push;\n   RR::SetPrecision(4*NTL_DOUBLE_PRECISION);\n\n   NTL_TLS_LOCAL(RR, t);\n   random(t);\n   conv(x, t);\n}\n\nquad_float random_quad_float()\n{\n   quad_float x;\n   random(x);\n   return x;\n}\n      \nlong IsFinite(quad_float *x)\n{\n   return IsFinite(&x->hi) && IsFinite(&x->lo);\n}\n\n\nquad_float floor(const quad_float& x)\n{\n   double fhi = floor(x.hi);\n\n   if (fhi != x.hi)\n      return quad_float(fhi, 0.0);\n   else {\n      double flo = floor(x.lo);\n      quad_float z;\n      quad_float_normalize(z, fhi, flo);\n      return z;\n   }\n}\n\n\nquad_float ceil(const quad_float& x) { \n  return -floor(-x);\n}\n\nquad_float trunc(const quad_float& x) { \n  if (x>=0.0) return floor(x); else return -floor(-x);\n}\n\n\n\nlong compare(const quad_float& x, const quad_float& y)\n{\n   if (x.hi > y.hi) \n      return 1;\n   else if (x.hi < y.hi)\n      return -1;\n   else if (x.lo > y.lo)\n      return 1;\n   else if (x.lo < y.lo) \n      return -1;\n   else\n      return 0;\n}\n\n\nquad_float fabs(const quad_float& x) \n{ if (x.hi>=0.0) return x; else return -x; }\n\n\nquad_float ldexp(const quad_float& x, long exp) { // x*2^exp\n   double xhi, xlo;\n   quad_float z;\n\n   xhi = _ntl_ldexp(x.hi, exp);\n   xlo = _ntl_ldexp(x.lo, exp);\n\n   quad_float_normalize(z, xhi, xlo);\n   return z;\n}\n\n\nquad_float exp(const quad_float& x) { // New version 97 Aug 05\n/*\n!  Calculate a quadruple-precision exponential\n!  Method:\n!   x    x.log2(e)    nint[x.log2(e)] + frac[x.log2(e)]\n!  e  = 2          = 2\n!\n!                     iy    fy\n!                  = 2   . 2\n!  Then\n!   fy    y.loge(2)\n!  2   = e\n!\n!  Now y.loge(2) will be less than 0.3466 in absolute value.\n!  This is halved and a Pade aproximation is used to approximate e^x over\n!  the region (-0.1733, +0.1733).   This approximation is then squared.\n*/\n  if (x.hi<DBL_MIN_10_EXP*2.302585092994045684017991) \n    return to_quad_float(0.0);\n  if (x.hi>DBL_MAX_10_EXP*2.302585092994045684017991) {\n    ResourceError(\"exp(quad_float): overflow\");\n  }\n\n  static const quad_float Log2 = to_quad_float(\"0.6931471805599453094172321214581765680755\");\n  // GLOBAL (assumes C++11 thread-safe init)\n\n  quad_float y,temp,ysq,sum1,sum2;\n  long iy;\n  y=x/Log2;\n  temp = floor(y+0.5);\n  iy = to_long(temp);\n  y=(y-temp)*Log2;\n  y=ldexp(y,-1L);\n  ysq=y*y;\n  sum1=y*((((ysq+3960.0)*ysq+2162160.0)*ysq+302702400.0)*ysq+8821612800.0);\n  sum2=(((90.0*ysq+110880.0)*ysq+30270240.0)*ysq+2075673600.0)*ysq+17643225600.0;\n/*\n!                     sum2 + sum1         2.sum1\n! Now approximation = ----------- = 1 + ----------- = 1 + 2.temp\n!                     sum2 - sum1       sum2 - sum1\n!\n! Then (1 + 2.temp)^2 = 4.temp.(1 + temp) + 1\n*/\n  temp=sum1/(sum2-sum1);\n  y=temp*(temp+1);\n  y=ldexp(y,2L);\n  return ldexp(y+1,iy);\n}\n\nquad_float log(const quad_float& t) { // Newton method. See Bailey, MPFUN\n  if (t.hi <= 0.0) {\n    ArithmeticError(\"log(quad_float): argument must be positive\");\n  }\n\n  quad_float s = to_quad_float(log(t.hi));\n  // NOTE: in case log yields excess precision, this assumes\n  // that to_quad_float removes it\n\n  quad_float e = exp(s);\n  return s+(t-e)/e;  // Newton step\n}\n\nquad_float sqrt(const quad_float& y)\n{\n  if (y.hi < 0.0)\n    ArithmeticError(\"quad_float: square root of negative number\");\n  if (y.hi == 0.0) return quad_float(0.0,0.0);\n\n  double c = TrueDouble(sqrt(y.hi));\n  // NOTE: we call TrueDouble, just in case sqrt yields excess precision\n\n  quad_float yy = y;\n  quad_float_in_place_sqrt(yy, c);\n  return yy;\n}\n\n\nlong operator> (const quad_float& x, const quad_float& y) {\n   return (x.hi> y.hi) || (x.hi==y.hi && x.lo> y.lo); }\nlong operator>=(const quad_float& x, const quad_float& y) {\n   return (x.hi>y.hi) || (x.hi==y.hi && x.lo>=y.lo); }\nlong operator< (const quad_float& x, const quad_float& y) {\n   return (x.hi< y.hi) || (x.hi==y.hi && x.lo< y.lo); }\nlong operator<=(const quad_float& x, const quad_float& y) {\n   return (x.hi<y.hi) || (x.hi==y.hi && x.lo<=y.lo); }\nlong operator==(const quad_float& x, const quad_float& y)\n   { return x.hi==y.hi && x.lo==y.lo; }\nlong operator!=(const quad_float& x, const quad_float& y)\n   { return x.hi!=y.hi || x.lo!=y.lo; }\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "63e771bb3c9f78a258629847138ff19c31c2bf42", "size": 7545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/quad_float1.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-03-21T19:39:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T06:14:16.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/quad_float1.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-12-24T22:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-25T10:03:13.000Z", "max_forks_repo_path": "LibSource/ExtendedNTL/src/quad_float1.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2016-01-16T07:59:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T10:27:23.000Z", "avg_line_length": 19.496124031, "max_line_length": 93, "alphanum_fraction": 0.5960238569, "num_tokens": 2560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.5474466917500677}}
{"text": "#include \"testsuite.h\"\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n    // 3x3 C-style row major storage, base zero\n    Array<int,2> A(3, 3);\n\n    // 3x3 Fortran-style column major storage, base one\n    Array<int,2> B(3, 3, ColumnMajorArray<2>());\n\n    // A custom storage format: \n    // Indices have range 0..3, 0..3\n    // Column major ordering\n    // Rows are stored ascending, columns stored descending\n    GeneralArrayStorage<2> storage;\n    storage.ordering() = firstRank, secondRank;\n    storage.base() = 0, 0;\n    storage.ascendingFlag() = true, false;\n\n    //    Array<int,2> C(3, 3, storage);\n    Array<int,2> C;\n    C.setStorage(storage);\n    C.resize(3,3);\n\n    // Set each array equal to\n    // [ 1 2 3 ]\n    // [ 4 5 6 ]\n    // [ 7 8 9 ]\n\n    A = 1, 2, 3,\n        4, 5, 6, \n        7, 8, 9;\n\n    // Comma-delimited lists initialize in memory-storage order only.\n    // Hence we list the values in column-major order to initialize B:\n\n    B = 1, 4, 7, 2, 5, 8, 3, 6, 9;\n\n    BZTEST(all(A == B));\n    BZTEST(B(2,1) == 8);\n    BZTEST(B(0,2) == 3);\n\n    // Array C is stored in column major, plus the columns are stored\n    // in descending order\n\n    C = 3, 6, 9, 2, 5, 8, 1, 4, 7;\n    BZTEST(all(A == C));\n    BZTEST(count(A==C) == 9);\n\n    Array<int,2> D(3,3);\n    D = A + B + C;\n\n    Array<int,2> E(3,3);\n    E = 3 * A;\n    BZTEST(all(D == E));\n    BZTEST(!all(D == A));\n\n    return 0;\n}\n\n", "meta": {"hexsha": "aa04beef53833366b269723c3efd35502cb51567", "size": 1425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/storage.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/storage.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/storage.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.265625, "max_line_length": 70, "alphanum_fraction": 0.5515789474, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5474466820894672}}
{"text": "#pragma once\n#include <Eigen/Sparse>\n\nnamespace edp\n{\nnamespace internal\n{\n\tinline uint32_t ipow(uint32_t base, uint32_t exp)\n\t{\n\t\tuint32_t result = 1U;\n\t\twhile (exp)\n\t\t{\n\t\t\tif (exp & 1U)\n\t\t\t\tresult *= base;\n\t\t\texp >>= 1U;\n\t\t\tbase *= base;\n\t\t}\n\n\t\treturn result;\n\t}\n}\n\ntemplate<typename T>\nstruct TwoSiteTerm\n{\n\tstd::pair<uint32_t, uint32_t> sites;\n\tEigen::SparseMatrix<T> m;\n\n\tTwoSiteTerm(const std::pair<uint32_t, uint32_t>& p1, const Eigen::SparseMatrix<T>& p2)\n\t\t: sites(p1), m(p2)\n\t{\n\t}\n\tTwoSiteTerm(std::pair<uint32_t, uint32_t>&& p1, Eigen::SparseMatrix<T>&& p2)\n\t\t: sites(p1), m(p2)\n\t{\n\t}\n};\n\ntemplate<typename T>\nstruct OneSiteTerm\n{\n\tuint32_t site;\n\tEigen::SparseMatrix<T> m;\n\n\tOneSiteTerm(uint32_t p1, const Eigen::SparseMatrix<T>& p2)\n\t\t: site(p1), m(p2)\n\t{\n\t}\n\n\tOneSiteTerm(uint32_t p1, Eigen::SparseMatrix<T>&& p2)\n\t\t: site(p1), m(p2)\n\t{\n\t}\n};\n\ntemplate<typename T>\nclass LocalHamiltonian\n{\nprivate:\n\tuint32_t numSites_;\n\tuint64_t d_; //local Hibert dimension\n\n\tstd::vector<TwoSiteTerm<T> > twoSiteTerms_;\n\tstd::vector<OneSiteTerm<T> > oneSiteTerms_;\n\n\tuint32_t swapBaseD(uint32_t idx, uint32_t pos, uint32_t val) const\n\t{\n\t\tuint32_t b = internal::ipow(d_, pos);\n\t\tuint32_t upper = (idx / (b*d_))*d_ + val;\n\t\treturn upper*b + (idx % b);\n\t}\npublic:\n\tLocalHamiltonian(uint32_t numSites, uint32_t d)\n\t\t: numSites_{numSites}, d_{d}\n\t{\n\t}\n\tLocalHamiltonian(const LocalHamiltonian&) = default;\n\tLocalHamiltonian(LocalHamiltonian&&) = default;\n\n\tLocalHamiltonian& operator=(const LocalHamiltonian&) = default;\n\tLocalHamiltonian& operator=(LocalHamiltonian&&) = default;\n\n\tvoid clearTerms()\n\t{\n\t\tstd::vector<TwoSiteTerm<T> >().swap(twoSiteTerms_);\n\t\tstd::vector<OneSiteTerm<T> >().swap(oneSiteTerms_);\n\t}\n\tuint32_t getNumSites() const\n\t{\n\t\treturn numSites_;\n\t}\n\n\tstd::map<uint32_t, T> getCol(uint32_t n) const;\n\tinline std::map<uint32_t, T> operator()(uint32_t n) const\n\t{\n\t\treturn getCol(n);\n\t}\n\n\tvoid addTwoSiteTerm(const std::pair<int,int>& site, Eigen::SparseMatrix<T> m)\n\t{\n\t\tm.makeCompressed();\n\t\ttwoSiteTerms_.emplace_back(site, std::move(m));\n\t}\n\tvoid addOneSiteTerm(uint32_t site, Eigen::SparseMatrix<T> m)\n\t{\n\t\tm.makeCompressed();\n\t\toneSiteTerms_.emplace_back(site, std::move(m));\n\t}\n};\n\n}\n\ntemplate<typename T>\nstd::map<uint32_t, T> edp::LocalHamiltonian<T>::getCol(uint32_t n) const\n{\n\tusing internal::ipow;\n\tusing Eigen::SparseMatrix;\n\n\tstd::map<uint32_t, T> m;\n\n\tfor(auto& twoSiteTerm : twoSiteTerms_)\n\t{\n\t\tauto a = (n/ipow(d_,twoSiteTerm.sites.first))%d_;\n\t\tauto b = (n/ipow(d_,twoSiteTerm.sites.second))%d_;\n\t\t//auto col = twoSiteTerm.m.col(a*d_ + b);\n\t\tauto col = b*d_ + a;\n\t\tfor(typename SparseMatrix<T>::InnerIterator it(twoSiteTerm.m, col); it; ++it)\n\t\t{\n\t\t\tuint32_t r = it.row();\n\t\t\tuint32_t t = n;\n\t\t\tt = swapBaseD(t, twoSiteTerm.sites.first, r%d_);\n\t\t\tt = swapBaseD(t, twoSiteTerm.sites.second, r/d_);\n\t\t\tm[t] += it.value();\n\t\t}\n\t}\n\tfor(auto& oneSiteTerm: oneSiteTerms_)\n\t{\n\t\tuint32_t a = (n/ipow(d_,oneSiteTerm.site))%d_;\n\t\t//auto col = oneSiteTerm.m.col(a);\n\t\tauto col = a;\n\n\t\tfor(typename SparseMatrix<T>::InnerIterator it(oneSiteTerm.m, col); it; ++it)\n\t\t{\n\t\t\tuint32_t r = it.row();\n\t\t\tuint32_t t = n;\n\t\t\tt = swapBaseD(t, oneSiteTerm.site, r);\n\t\t\tm[t] += it.value();\n\t\t}\n\t}\n\treturn m;\n}\n", "meta": {"hexsha": "0f7cce9d791d3a7a7b0d6e529105e4ec767c472e", "size": 3219, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/edlib/EDP/LocalHamiltonian.hpp", "max_stars_repo_name": "chaeyeunpark/ExactDiagonalization", "max_stars_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T08:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:47:05.000Z", "max_issues_repo_path": "include/edlib/EDP/LocalHamiltonian.hpp", "max_issues_repo_name": "chaeyeunpark/ExactDiagonalization", "max_issues_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T19:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T19:02:14.000Z", "max_forks_repo_path": "include/edlib/EDP/LocalHamiltonian.hpp", "max_forks_repo_name": "chaeyeunpark/ExactDiagonalization", "max_forks_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-22T18:59:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T18:59:11.000Z", "avg_line_length": 21.1776315789, "max_line_length": 87, "alphanum_fraction": 0.6731904318, "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.547280889701593}}
{"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 *    References\n *      Montebruck O, Gill E. Satellite Orbits, Corrected Third Printing, Springer, 2005.\n *      Bate R. Fundamentals of Astrodynamics, Courier Dover Publications, 1971.\n *\n */\n\n#include <Eigen/Core>\n#include <cmath>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/missionGeometry.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\n\nnamespace tudat\n{\n\nnamespace mission_geometry\n{\n\n//! Compute whether an orbit is retrograde based on inclination.\nbool isOrbitRetrograde( const double inclination )\n{\n    bool isRetrograde = false;\n\n    // Check which range inclination is in and return value accordingly.\n    if ( inclination < 0.0 || inclination > mathematical_constants::PI )\n    {\n        throw std::runtime_error(\n                    \"The inclination is in the wrong range when determining retrogradeness\" );\n    }\n    else if ( inclination <= mathematical_constants::PI / 2.0 )\n    {\n        isRetrograde = false;\n    }\n    else if ( inclination > mathematical_constants::PI / 2.0 )\n    {\n        isRetrograde = true;\n    }\n\n    return isRetrograde;\n}\n\n//! Compute whether an orbit is retrograde based on Keplerian state.\nbool isOrbitRetrograde( const Eigen::Vector6d& keplerElements )\n{\n    // Get inclination from vector and call overloaded function.\n    return isOrbitRetrograde(\n                keplerElements(\n                    orbital_element_conversions::inclinationIndex ) );\n}\n\n//! Compute the shadow function.\ndouble computeShadowFunction( const Eigen::Vector3d& occultedBodyPosition,\n                              const double occultedBodyRadius,\n                              const Eigen::Vector3d& occultingBodyPosition,\n                              const double occultingBodyRadius,\n                              const Eigen::Vector3d& satellitePosition )\n{\n    // Calculate coordinates of the spacecraft with respect to the occulting body.\n    const Eigen::Vector3d satellitePositionRelativeToOccultingBody = satellitePosition\n            - occultingBodyPosition;\n\n    // Calculate apparent radius of occulted body.\n    const double occultedBodyApparentRadius\n            = std::asin( occultedBodyRadius\n                         / ( occultedBodyPosition - satellitePosition ).norm( ) );\n\n    // Calculate apparent radius of occulting body.\n    const double occultingBodyApparentRadius =\n            std::asin( occultingBodyRadius / satellitePositionRelativeToOccultingBody.norm( ) );\n\n    // Calculate apparent separation of the center of both bodies.\n    const double apparentSeparationPartOne = -satellitePositionRelativeToOccultingBody.transpose( )\n            * ( occultedBodyPosition - satellitePosition );\n    const double apparentSeparationPartTwo = satellitePositionRelativeToOccultingBody.norm( )\n            * ( occultedBodyPosition - satellitePosition ).norm( );\n    const double apparentSeparation = std::acos( apparentSeparationPartOne\n                                                 / apparentSeparationPartTwo );\n\n    // Set initial value for the shadow function.\n    double shadowFunction = 1.0;\n\n    // Check if partial occultation takes place\n    if ( std::fabs( occultedBodyApparentRadius - occultingBodyApparentRadius ) < apparentSeparation\n         && apparentSeparation < occultedBodyApparentRadius + occultingBodyApparentRadius )\n    {\n        // Pre-compute values for optimal computations.\n        const double apparentSeparationSquared = apparentSeparation * apparentSeparation;\n        const double occultedBodyApparentRadiusSquared = occultedBodyApparentRadius\n                * occultedBodyApparentRadius;\n        const double occultingBodyApparentRadiusSquared = occultingBodyApparentRadius\n                * occultingBodyApparentRadius;\n\n        // Partial occultation takes place, calculate the occulted area.\n        const double occultedAreaPartOne\n                = ( apparentSeparationSquared + occultedBodyApparentRadiusSquared\n                    - occultingBodyApparentRadiusSquared ) / ( 2.0 * apparentSeparation );\n        const double occultedAreaPartTwo = std::sqrt( occultedBodyApparentRadiusSquared\n                                                      - occultedAreaPartOne * occultedAreaPartOne );\n        const double occultedArea = occultedBodyApparentRadiusSquared\n                * std::acos( occultedAreaPartOne / occultedBodyApparentRadius )\n                + occultingBodyApparentRadiusSquared\n                * std::acos( ( apparentSeparation - occultedAreaPartOne )\n                             / occultingBodyApparentRadius )\n                - apparentSeparation * occultedAreaPartTwo;\n        shadowFunction = 1.0 - occultedArea / ( mathematical_constants::PI *\n                                                occultedBodyApparentRadiusSquared );\n    }\n\n    else\n    {\n        // Full or no occultation takes place.\n        // Check for type of occultation.\n        if ( apparentSeparation < occultingBodyApparentRadius - occultedBodyApparentRadius &&\n             occultedBodyApparentRadius < occultingBodyApparentRadius )\n        {\n            // Total occultation.\n            shadowFunction = 0.0;\n        }\n\n        else if ( apparentSeparation < occultedBodyApparentRadius - occultingBodyApparentRadius &&\n                  occultedBodyApparentRadius > occultingBodyApparentRadius )\n        {\n            // Maximum partial occultation.\n            shadowFunction = 0.0;\n        }\n\n        else if ( occultedBodyApparentRadius + occultingBodyApparentRadius <= apparentSeparation )\n        {\n            // No occultation\n            shadowFunction = 1.0;\n        }\n    }\n\n    // Return the shadow function\n    return shadowFunction;\n}\n\ndouble computeSphereOfInfluence( const double distanceToCentralBody,\n                                 const double ratioOfOrbitingToCentralBodyMass )\n{\n    // Return the radius of the sphere of influence.\n    return distanceToCentralBody * std::pow( ratioOfOrbitingToCentralBodyMass, 0.4 );\n}\n\n//! Compute the sphere of influence.\ndouble computeSphereOfInfluence( const double distanceToCentralBody,\n                                 const double massOrbitingBody,\n                                 const double massCentralBody )\n{\n    // Return the radius of the sphere of influence.\n    return computeSphereOfInfluence( distanceToCentralBody, massOrbitingBody / massCentralBody );\n}\n\n} // namespace mission_geometry\n\n} // namespace tudat\n", "meta": {"hexsha": "d25202f8202e9b9868e96e46ed800ba7b1a267dd", "size": 6904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/missionGeometry.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/BasicAstrodynamics/missionGeometry.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/BasicAstrodynamics/missionGeometry.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": 41.3413173653, "max_line_length": 100, "alphanum_fraction": 0.6720741599, "num_tokens": 1462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.5472808753882651}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/maybe.hpp>\n#include <boost/hana/tuple.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [ap]\nBOOST_HANA_CONSTEXPR_CHECK(\n    ap(make<Tuple>(_+_), make<Tuple>(1, 2), make<Tuple>(3, 4, 5))\n        ==\n    make<Tuple>(\n        1 + 3,      1 + 4,      1 + 5,\n        2 + 3,      2 + 4,      2 + 5\n    )\n);\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto g = [](auto a, auto b, auto c) {\n    return a * b * c;\n};\nBOOST_HANA_CONSTEXPR_CHECK(\n    ap(just(g), just(1), just(2), just(3)) == just(1 * 2 * 3)\n);\nBOOST_HANA_CONSTANT_CHECK(\n    ap(just(g), just(1), nothing, just(3)) == nothing\n);\n//! [ap]\n\n}{\n\n//! [lift]\nBOOST_HANA_CONSTEXPR_CHECK(lift<Tuple>('x') == make<Tuple>('x'));\nBOOST_HANA_CONSTEXPR_CHECK(lift<Maybe>('x') == just('x'));\n//! [lift]\n\n}\n\n}\n", "meta": {"hexsha": "d16cd1abd9e858edaae09716d60b617e4397f4c2", "size": 1043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/applicative.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/applicative.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/applicative.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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.86, "max_line_length": 78, "alphanum_fraction": 0.6136145733, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624840223698, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5472802070546989}}
{"text": "//=======================================================================\r\n// Copyright 2007 Aaron Windsor - Ben Sisson\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 <iostream>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/properties.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/ref.hpp>\r\n#include <vector>\r\n\r\n#include <boost/graph/make_biconnected_planar.hpp>\r\n#include <boost/graph/make_maximal_planar.hpp>\r\n#include <boost/graph/planar_face_traversal.hpp>\r\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\r\n#include <boost/graph/planar_canonical_ordering.hpp>\r\n#include <boost/graph/chrobak_payne_drawing.hpp>\r\n#include <boost/graph/is_straight_line_drawing.hpp>\r\n\r\n\r\nusing namespace boost;\r\n\r\n\r\n//a class to hold the coordinates of the straight line embedding\r\nstruct coord_t{\r\n  std::size_t x;\r\n  std::size_t y;\r\n};\r\n\r\nint main(int argc, char** argv){\r\n\r\n  typedef adjacency_list\r\n    < vecS,\r\n      vecS,\r\n      undirectedS,\r\n      property<vertex_index_t, int>,\r\n      property<edge_index_t, int>\r\n    > \r\n    graph;\r\n\r\n  graph g(7);\r\n  add_edge(0,1,g);\r\n  add_edge(1,2,g);\r\n  add_edge(2,3,g);\r\n  add_edge(3,0,g);\r\n  add_edge(0,4,g);\r\n  add_edge(1,5,g);\r\n  add_edge(2,6,g);\r\n  add_edge(3,7,g);\r\n  add_edge(4,5,g);\r\n  add_edge(5,6,g);\r\n  add_edge(6,7,g);\r\n  add_edge(7,4,g);\r\n\r\n  //Initialize the interior edge index\r\n  property_map<graph, edge_index_t>::type e_index = get(edge_index, g);\r\n  graph_traits<graph>::edges_size_type edge_count = 0;\r\n  graph_traits<graph>::edge_iterator ei, ei_end;\r\n  for(boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\r\n    put(e_index, *ei, edge_count++);\r\n  \r\n  \r\n  //Test for planarity; compute the planar embedding as a side-effect\r\n  typedef std::vector< graph_traits<graph>::edge_descriptor > vec_t;\r\n  std::vector<vec_t> embedding(num_vertices(g));\r\n  boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\r\n                                   boyer_myrvold_params::embedding = \r\n                                       &embedding[0]\r\n                                   );\r\n  \r\n  make_biconnected_planar(g, &embedding[0]);\r\n\r\n  // Re-initialize the edge index, since we just added a few edges\r\n  edge_count = 0;\r\n  for(boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\r\n    put(e_index, *ei, edge_count++);\r\n\r\n\r\n  //Test for planarity again; compute the planar embedding as a side-effect\r\n  boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\r\n                                   boyer_myrvold_params::embedding = \r\n                                       &embedding[0]\r\n                                   );\r\n\r\n  make_maximal_planar(g, &embedding[0]);\r\n\r\n  // Re-initialize the edge index, since we just added a few edges\r\n  edge_count = 0;\r\n  for(boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\r\n    put(e_index, *ei, edge_count++);\r\n\r\n  boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\r\n                                   boyer_myrvold_params::embedding = \r\n                                       &embedding[0]\r\n                                   );\r\n\r\n  // Find a canonical ordering\r\n  std::vector<graph_traits<graph>::vertex_descriptor> ordering;\r\n  planar_canonical_ordering(g, &embedding[0], std::back_inserter(ordering));\r\n\r\n\r\n  //Set up a property map to hold the mapping from vertices to coord_t's\r\n  typedef std::vector< coord_t > straight_line_drawing_storage_t;\r\n  typedef boost::iterator_property_map\r\n    < straight_line_drawing_storage_t::iterator, \r\n      property_map<graph, vertex_index_t>::type \r\n    >\r\n    straight_line_drawing_t;\r\n\r\n  straight_line_drawing_storage_t straight_line_drawing_storage\r\n    (num_vertices(g));\r\n  straight_line_drawing_t straight_line_drawing\r\n    (straight_line_drawing_storage.begin(), \r\n     get(vertex_index,g)\r\n     );\r\n\r\n\r\n\r\n  // Compute the straight line drawing\r\n  chrobak_payne_straight_line_drawing(g, \r\n                                      embedding, \r\n                                      ordering.begin(),\r\n                                      ordering.end(),\r\n                                      straight_line_drawing\r\n                                      );\r\n  \r\n\r\n\r\n  std::cout << \"The straight line drawing is: \" << std::endl;\r\n  graph_traits<graph>::vertex_iterator vi, vi_end;\r\n  for(boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\r\n    {\r\n      coord_t coord(get(straight_line_drawing,*vi));\r\n      std::cout << *vi << \" -> (\" << coord.x << \", \" << coord.y << \")\" \r\n                << std::endl;\r\n    }\r\n\r\n  // Verify that the drawing is actually a plane drawing\r\n  if (is_straight_line_drawing(g, straight_line_drawing))\r\n    std::cout << \"Is a plane drawing.\" << std::endl;\r\n  else\r\n    std::cout << \"Is not a plane drawing.\" << std::endl;\r\n\r\n  return 0;\r\n}", "meta": {"hexsha": "69438eb5d5210d74960bbe93929475555103ef39", "size": 5026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "embed.cpp", "max_stars_repo_name": "benmsisson/chrobak_embedding", "max_stars_repo_head_hexsha": "391e601b5ec686b256e68d7bfb3a34e240dd1fb3", "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": "embed.cpp", "max_issues_repo_name": "benmsisson/chrobak_embedding", "max_issues_repo_head_hexsha": "391e601b5ec686b256e68d7bfb3a34e240dd1fb3", "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": "embed.cpp", "max_forks_repo_name": "benmsisson/chrobak_embedding", "max_forks_repo_head_hexsha": "391e601b5ec686b256e68d7bfb3a34e240dd1fb3", "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.7315436242, "max_line_length": 77, "alphanum_fraction": 0.5955033824, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5472802056942949}}
{"text": "#include <iostream>\r\n#include <pcl/console/parse.h>\r\n#include <pcl/filters/extract_indices.h>\r\n#include <pcl/io/pcd_io.h>\r\n#include <pcl/point_types.h>\r\n#include <pcl/sample_consensus/ransac.h>\r\n#include <pcl/sample_consensus/sac_model_plane.h>\r\n#include <pcl/sample_consensus/sac_model_sphere.h>\r\n#include <pcl/visualization/pcl_visualizer.h>\r\n#include <boost/thread/thread.hpp>\r\n\r\nboost::shared_ptr<pcl::visualization::PCLVisualizer>\r\nsimpleVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud)\r\n{\r\n  // --------------------------------------------\r\n  // -----Open 3D viewer and add point cloud-----\r\n  // --------------------------------------------\r\n  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer (\"3D Viewer\"));\r\n  viewer->setBackgroundColor (0, 0, 0);\r\n  viewer->addPointCloud<pcl::PointXYZ> (cloud, \"sample cloud\");\r\n  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, \"sample cloud\");\r\n  //viewer->addCoordinateSystem (1.0);\r\n  viewer->initCameraParameters ();\r\n  return (viewer);\r\n}\r\n\r\nint\r\nmain(int argc, char** argv)\r\n{\r\n  // initialize PointClouds\r\n  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);\r\n  pcl::PointCloud<pcl::PointXYZ>::Ptr final (new pcl::PointCloud<pcl::PointXYZ>);\r\n\r\n  // populate our PointCloud with points\r\n  cloud->width    = 500;\r\n  cloud->height   = 1;\r\n  cloud->is_dense = false;\r\n  cloud->points.resize (cloud->width * cloud->height);\r\n  for (size_t i = 0; i < cloud->points.size (); ++i)\r\n  {\r\n    if (pcl::console::find_argument (argc, argv, \"-s\") >= 0 || pcl::console::find_argument (argc, argv, \"-sf\") >= 0)\r\n    {\r\n      cloud->points[i].x = 1024 * rand () / (RAND_MAX + 1.0);\r\n      cloud->points[i].y = 1024 * rand () / (RAND_MAX + 1.0);\r\n      if (i % 5 == 0)\r\n        cloud->points[i].z = 1024 * rand () / (RAND_MAX + 1.0);\r\n      else if(i % 2 == 0)\r\n        cloud->points[i].z =  sqrt( 1 - (cloud->points[i].x * cloud->points[i].x)\r\n                                      - (cloud->points[i].y * cloud->points[i].y));\r\n      else\r\n        cloud->points[i].z =  - sqrt( 1 - (cloud->points[i].x * cloud->points[i].x)\r\n                                        - (cloud->points[i].y * cloud->points[i].y));\r\n    }\r\n    else\r\n    {\r\n      cloud->points[i].x = 1024 * rand () / (RAND_MAX + 1.0);\r\n      cloud->points[i].y = 1024 * rand () / (RAND_MAX + 1.0);\r\n      if( i % 2 == 0)\r\n        cloud->points[i].z = 1024 * rand () / (RAND_MAX + 1.0);\r\n      else\r\n        cloud->points[i].z = -1 * (cloud->points[i].x + cloud->points[i].y);\r\n    }\r\n  }\r\n\r\n  std::vector<int> inliers;\r\n\r\n  // created RandomSampleConsensus object and compute the appropriated model\r\n  pcl::SampleConsensusModelSphere<pcl::PointXYZ>::Ptr\r\n    model_s(new pcl::SampleConsensusModelSphere<pcl::PointXYZ> (cloud));\r\n  pcl::SampleConsensusModelPlane<pcl::PointXYZ>::Ptr\r\n    model_p (new pcl::SampleConsensusModelPlane<pcl::PointXYZ> (cloud));\r\n  if(pcl::console::find_argument (argc, argv, \"-f\") >= 0)\r\n  {\r\n    pcl::RandomSampleConsensus<pcl::PointXYZ> ransac (model_p);\r\n    ransac.setDistanceThreshold (.01);\r\n    ransac.computeModel();\r\n    ransac.getInliers(inliers);\r\n  }\r\n  else if (pcl::console::find_argument (argc, argv, \"-sf\") >= 0 )\r\n  {\r\n    pcl::RandomSampleConsensus<pcl::PointXYZ> ransac (model_s);\r\n    ransac.setDistanceThreshold (.01);\r\n    ransac.computeModel();\r\n    ransac.getInliers(inliers);\r\n  }\r\n\r\n  // copies all inliers of the model computed to another PointCloud\r\n  pcl::copyPointCloud<pcl::PointXYZ>(*cloud, inliers, *final);\r\n\r\n  // creates the visualization object and adds either our orignial cloud or all of the inliers\r\n  // depending on the command line arguments specified.\r\n  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;\r\n  if (pcl::console::find_argument (argc, argv, \"-f\") >= 0 || pcl::console::find_argument (argc, argv, \"-sf\") >= 0)\r\n    viewer = simpleVis(final);\r\n  else\r\n    viewer = simpleVis(cloud);\r\n  while (!viewer->wasStopped ())\r\n  {\r\n    viewer->spinOnce (100);\r\n    boost::this_thread::sleep (boost::posix_time::microseconds (100000));\r\n  }\r\n  return 0;\r\n }\r\n", "meta": {"hexsha": "88396d3b28d2d57bc597c23fd2f91eef1dd2a0b1", "size": 4170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/tutorials/content/sources/random_sample_consensus/random_sample_consensus.cpp", "max_stars_repo_name": "zhangxaochen/CuFusion", "max_stars_repo_head_hexsha": "e8bab7a366b1f2c85a80b95093d195d9f0774c11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2017-09-05T13:31:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T08:48:29.000Z", "max_issues_repo_path": "doc/tutorials/content/sources/random_sample_consensus/random_sample_consensus.cpp", "max_issues_repo_name": "GucciPrada/CuFusion", "max_issues_repo_head_hexsha": "522920bcf316d1ddf9732fc71fa457174168d2fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-05-17T22:45:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-01T21:46:42.000Z", "max_forks_repo_path": "doc/tutorials/content/sources/random_sample_consensus/random_sample_consensus.cpp", "max_forks_repo_name": "GucciPrada/CuFusion", "max_forks_repo_head_hexsha": "522920bcf316d1ddf9732fc71fa457174168d2fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2015-07-27T13:00:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T08:18:41.000Z", "avg_line_length": 40.0961538462, "max_line_length": 117, "alphanum_fraction": 0.6146282974, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.547280200789068}}
{"text": "/** A simple cartesian space controller.\n    It receives a destination, a duration and publishes the trajectory\n    in cartesian space at 200Hz\n    Note: the robot is required to be calibrated to the zero configuration\n    as used in the kdl chain model.\n**/\n#include \"ros/ros.h\"\n#include <boost/lexical_cast.hpp>\n#include <boost/thread/thread.hpp>\n#include <trajectory_msgs/JointTrajectory.h>\n#include \"bosch_arm_srvs/GetJointAngles.h\"\n#include <kdl/chain.hpp>\n#include <kdl/chainfksolver.hpp>\n#include <kdl/chainfksolverpos_recursive.hpp>\n#include <kdl/frames_io.hpp>\n#include <stdio.h>\n#include <iostream>\n#include <vector>\nusing namespace Eigen;\n\nclass BoschArmKinematicModel\n{\n  public:\n    double L0,L3,L4;\n    Vector3f getTipPosition(Vector4f q)\n    {\n      Vector3f tip;\n      double q1=q(0);\n      double q2=q(1);\n      double q3=q(2);\n      double q4=q(3);\n      tip(0)= - L4*(sin(q4)*(cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3)) + cos(q2)*cos(q4)*sin(q1)) - L3*cos(q2)*sin(q1);\n      tip(1)=  - L4*(cos(q4)*sin(q2) + cos(q2)*sin(q3)*sin(q4)) - L3*sin(q2);\n      tip(2)=L0 - L4*(sin(q4)*(cos(q3)*sin(q1) + cos(q1)*sin(q2)*sin(q3)) - cos(q1)*cos(q2)*cos(q4)) + L3*cos(q1)*cos(q2);\n      return tip;\n    }\n    Matrix3f getJacobianLockJoint3(Vector4f qlock)\n    {\n      Matrix3f jacob;\n      double q1=qlock(0);\n      double q2=qlock(1);\n      double q3=qlock(2);\n      double q4=qlock(3);\n      jacob(0,0)=L4*(sin(q4)*(cos(q3)*sin(q1) + cos(q1)*sin(q2)*sin(q3)) - cos(q1)*cos(q2)*cos(q4)) - L3*cos(q1)*cos(q2);\n      jacob(0,1)=L4*(cos(q4)*sin(q1)*sin(q2) + cos(q2)*sin(q1)*sin(q3)*sin(q4)) + L3*sin(q1)*sin(q2);\n      jacob(0,2)=-L4*(cos(q4)*(cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3)) - cos(q2)*sin(q1)*sin(q4));\n      jacob(1,0)=0;\n      jacob(1,1)=-L4*(cos(q2)*cos(q4) - sin(q2)*sin(q3)*sin(q4)) - L3*cos(q2);\n      jacob(1,2)=L4*(sin(q2)*sin(q4) - cos(q2)*cos(q4)*sin(q3));\n      jacob(2,0)=- L4*(sin(q4)*(cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3)) + cos(q2)*cos(q4)*sin(q1)) - L3*cos(q2)*sin(q1);\n      jacob(2,1)=- L4*(cos(q1)*cos(q4)*sin(q2) + cos(q1)*cos(q2)*sin(q3)*sin(q4)) - L3*cos(q1)*sin(q2);\n      jacob(2,2)=-L4*(cos(q4)*(cos(q3)*sin(q1) + cos(q1)*sin(q2)*sin(q3)) + cos(q1)*cos(q2)*sin(q4));\n      return jacob;\n    }\n\n    \n};\nint main ( int argc, char **argv )\n{\n  ros::init ( argc, argv, \"traj_gen\" );\n  ros::NodeHandle n;\n  ros::Publisher traj_pub =  n.advertise<trajectory_msgs::JointTrajectory> ( \"/traj_cmd\",1 );\n  //boost::thread t2 = boost::thread::thread ( boost::bind ( &pubTrajectory ) );\n  ros::ServiceClient client = n.serviceClient<bosch_arm_srvs::GetJointAngles> ( \"get_joint_angles\" );\n  bosch_arm_srvs::GetJointAngles srv;\n  client.call ( srv );\n\n  //read destination and duration\n  KDL::Vector des;\n  for ( int i=0;i<3;i++ )\n    des[i]=boost::lexical_cast<double> ( argv[i+1] );\n  double t=boost::lexical_cast<double> ( argv[4] );\n\n\n  //TODO convert destination to joint angles\n  \n  Segment seg0=Segment ( Joint ( Joint::None ),\n                         Frame ( Rotation::RPY ( M_PI/2,-M_PI/2,0 ),Vector ( 0,0,0.27 ) ) );\n  Segment seg1=Segment ( Joint ( Joint::RotZ ),\n                         Frame ( Rotation::RPY ( M_PI/2,-M_PI/2,0 ) ) );\n  Segment seg2=Segment ( Joint ( Joint::RotZ ),\n                         Frame ( Rotation::RPY ( M_PI/2,-M_PI/2,0 ) ) );\n  Segment seg3=Segment ( Joint ( Joint::None ),\n                         Frame ( Rotation::RPY ( M_PI/2,-M_PI/2,0 ),Vector ( 0,0,0.50 ) ) );\n  Segment seg4=Segment ( Joint ( Joint::RotZ ),\n                         Frame ( Vector ( 0.48,0,0 ) ) );\n  Chain chain;\n  chain.addSegment ( seg0 );\n  chain.addSegment ( seg1 );\n  chain.addSegment ( seg2 );\n  chain.addSegment ( seg3 );\n  chain.addSegment ( seg4 );\n  ChainFkSolverPos_recursive fksolver = ChainFkSolverPos_recursive ( chain );\n\n  //linear interpolation in joint space\n  trajectory_msgs::JointTrajectory traj;\n  traj.header.stamp=ros::Time::now();\n  traj.header.frame_id=\"\";\n  traj.header.seq=0;\n  traj.points.resize ( npts+1 );\n  traj.joint_names.resize ( 4 );\n  traj.joint_names[0]=\"joint1\";\n  traj.joint_names[1]=\"joint2\";\n  traj.joint_names[2]=\"joint3\";\n  traj.joint_names[3]=\"joint4\";\n  traj.points[i].positions.resize ( 4 );\n\n  int npts=ceil ( t*200 );\n  KDL::JntArray jointpositions = JntArray (3);\n  KDL::Frame cartpos;\n  double q3;\n  bool kinematics_status;\n  \n  for ( int i=0;i<=npts;i++ )\n  {\n    //get the current joint position\n    client.call ( srv );\n    //compute forward kinematics.\n    \n    jointpositions (0) =srv.response.joint_angles[0];\n    jointpositions (1) =srv.response.joint_angles[1];\n    q3                 =srv.response.joint_angles[2];\n    jointpositions (2) =srv.response.joint_angles[3]; \n    kinematics_status = fksolver.JntToCart ( jointpositions,cartpos );\n    if ( kinematics_status>=0 )\n    {\n      std::cout << cartpos.p <<std::endl;\n    }\n    else\n    {\n      printf ( \"%s \\n\",\"Error: could not calculate forward kinematics :(\" );\n    }\n    double steps_to_go=npts-i;\n    Vector step_length_cart= (des-cartpos.p)/steps_to_go;\n    \n    for ( int j=0;j<4;j++ )\n      traj.points[i].positions[j]=srv.response.joint_angles[j]+i*dq[j];\n    traj.points[i].time_from_start=ros::Duration ( i*t/npts );\n  }\n  //The first message is always lost\n  for ( int i=0;i<2;i++ )\n  {\n    traj_pub.publish ( traj );\n    sleep ( 1 );\n  }\n  ros::spin();\n  return 0;\n}\n", "meta": {"hexsha": "01d0f1445eeeac86f383203d61f7229bb0d247b5", "size": 5349, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bosch_arm/bosch_arm_control/src/cartesian_controller.cpp", "max_stars_repo_name": "atp42/jks-ros-pkg", "max_stars_repo_head_hexsha": "367fc00f2a9699f33d05c7957d319a80337f1ed4", "max_stars_repo_licenses": ["FTL"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-02-02T13:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-17T11:52:13.000Z", "max_issues_repo_path": "bosch_arm/bosch_arm_control/src/cartesian_controller.cpp", "max_issues_repo_name": "salisbury-robotics/jks-ros-pkg", "max_issues_repo_head_hexsha": "367fc00f2a9699f33d05c7957d319a80337f1ed4", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bosch_arm/bosch_arm_control/src/cartesian_controller.cpp", "max_forks_repo_name": "salisbury-robotics/jks-ros-pkg", "max_forks_repo_head_hexsha": "367fc00f2a9699f33d05c7957d319a80337f1ed4", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8993288591, "max_line_length": 123, "alphanum_fraction": 0.6126378762, "num_tokens": 1784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5472802007890679}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\r\n *    All rights reserved.\r\n *\r\n *    Redistribution and use in source and binary forms, with or without modification, are\r\n *    permitted provided that the following conditions are met:\r\n *      - Redistributions of source code must retain the above copyright notice, this list of\r\n *        conditions and the following disclaimer.\r\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\r\n *        conditions and the following disclaimer in the documentation and/or other materials\r\n *        provided with the distribution.\r\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\r\n *        may be used to endorse or promote products derived from this software without specific\r\n *        prior written permission.\r\n *\r\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\r\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\r\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\r\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\r\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\r\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\r\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *    Changelog\r\n *      YYMMDD    Author            Comment\r\n *      120926    E. Dekens         File created.\r\n *      121218    S. Billemont      Added output fuctions to display Legendre polynomial data,\r\n *                                  for debugging.\r\n *\r\n *    References\r\n *\r\n *    Notes\r\n *\r\n */\r\n\r\n#include <sstream>\r\n#include <stdexcept>\r\n\r\n#include <boost/exception/all.hpp>\r\n#include <boost/math/special_functions/factorials.hpp>\r\n\r\n#include \"Tudat/Mathematics/BasicMathematics/legendrePolynomials.h\"\r\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\r\n\r\nnamespace tudat\r\n{\r\nnamespace basic_mathematics\r\n{\r\n\r\n\r\n\r\n//! Default constructor, initializes cache object with 0 maximum degree and order.\r\nLegendreCache::LegendreCache( const bool useGeodesyNormalization )\r\n{\r\n    useGeodesyNormalization_  = useGeodesyNormalization;\r\n\r\n    if( useGeodesyNormalization_ )\r\n    {\r\n        legendrePolynomialFunction_ = geodesyNormalizedLegendrePolynomialFunction;\r\n    }\r\n    else\r\n    {\r\n        legendrePolynomialFunction_ = regularLegendrePolynomialFunction;\r\n    }\r\n\r\n    resetMaximumDegreeAndOrder( 0, 0 );\r\n\r\n}\r\n\r\n//! Constructor\r\nLegendreCache::LegendreCache( const int maximumDegree, const int maximumOrder, const bool useGeodesyNormalization  )\r\n{\r\n    useGeodesyNormalization_  = useGeodesyNormalization;\r\n\r\n    if( useGeodesyNormalization_ )\r\n    {\r\n        legendrePolynomialFunction_ = geodesyNormalizedLegendrePolynomialFunction;\r\n    }\r\n    else\r\n    {\r\n        legendrePolynomialFunction_ = regularLegendrePolynomialFunction;\r\n    }\r\n\r\n    resetMaximumDegreeAndOrder( maximumDegree, maximumOrder );\r\n}\r\n\r\n//! Get Legendre polynomial from cache when possible, and from direct computation otherwise.\r\nvoid LegendreCache::update( const double polynomialParameter  )\r\n{\r\n    currentPolynomialParameter_ = polynomialParameter;\r\n    currentPolynomialParameterComplement_ = std::sqrt( 1.0 - polynomialParameter * polynomialParameter ); // cosine of latitude is always positive!\r\n\r\n    LegendreCache& thisReference = *this;\r\n    for( int i = 0; i <= maximumDegree_; i++ )\r\n    {\r\n        for( int j = 0; ( ( j <= i ) && ( j <= maximumOrder_ ) ) ; j++ )\r\n        {\r\n            legendreValues_[ i * ( maximumOrder_ + 1 ) + j ] = legendrePolynomialFunction_( i, j, thisReference );\r\n        }\r\n    }\r\n}\r\n\r\n//! Update maximum degree and order of cache\r\nvoid LegendreCache::resetMaximumDegreeAndOrder( const int maximumDegree, const int maximumOrder )\r\n{\r\n    maximumDegree_ = maximumDegree;\r\n    maximumOrder_ = maximumOrder;\r\n    legendreValues_.resize( ( maximumDegree_ + 1 ) * ( maximumOrder_ + 1 ) );\r\n\r\n    currentPolynomialParameter_ = TUDAT_NAN;\r\n    currentPolynomialParameterComplement_ = TUDAT_NAN;\r\n}\r\n\r\n\r\n//! Get Legendre polynomial value from the cache.\r\ndouble LegendreCache::getLegendrePolynomial(\r\n        const int degree, const int order )\r\n{\r\n    if( degree > maximumDegree_ || order > maximumOrder_ )\r\n    {\r\n        std::cerr<<\"Error when requesting legendre cache, maximum degree or order exceeded \"<<\r\n                   degree<<\" \"<<maximumDegree_<<\" \"<<order<<\" \"<<maximumOrder_<<std::endl;\r\n        return TUDAT_NAN;\r\n    }\r\n    else if( order > degree )\r\n    {\r\n        return 0.0;\r\n    }\r\n    else\r\n    {\r\n        return legendreValues_[ degree * ( maximumOrder_ + 1  ) + order ];\r\n    };\r\n}\r\n\r\n//! Compute unnormalized associated Legendre polynomial.\r\ndouble computeLegendrePolynomial( const int degree,\r\n                                  const int order,\r\n                                  LegendreCache& legendreCache )\r\n{\r\n    if( legendreCache.getUseGeodesyNormalization( ) )\r\n    {\r\n        throw std::runtime_error( \"Error when computing Legendre polynomial, input uses normalization\" );\r\n    }\r\n\r\n    // If degree or order is negative...\r\n    if ( degree < 0 || order < 0 )\r\n    {\r\n        // Set error message.\r\n        std::stringstream errorMessage;\r\n        errorMessage << \"Error: the Legendre polynomial of = \" << degree << \" and order = \"\r\n                     << order << \" is undefined.\" << std::endl;\r\n\r\n        // Throw a run-time error.\r\n        boost::throw_exception( boost::enable_error_info( std::runtime_error(\r\n                                                              errorMessage.str( ) ) ) );\r\n    }\r\n\r\n    // Else if order is greater than degree...\r\n    else if ( order > degree && degree >= 0 )\r\n    {\r\n        // Return zero.\r\n        return 0.0;\r\n    }\r\n\r\n    // Else if order and degree are lower than 2...\r\n    else if ( degree <= 1 && order <= 1 )\r\n    {\r\n        // Compute polynomial explicitly.\r\n        return computeLegendrePolynomialExplicit( degree, order, legendreCache.getCurrentPolynomialParameter( ) );\r\n    }\r\n\r\n    // Else if degree and order are sectoral...\r\n    else if ( degree == order )\r\n    {\r\n        // Obtain polynomial of degree one and order one.\r\n        const double degreeOneOrderOnePolynomial = legendreCache.getLegendrePolynomial(\r\n                    1, 1 );\r\n\r\n        // Obtain prior sectoral polynomial.\r\n        const double priorSectoralPolynomial = legendreCache.getLegendrePolynomial(\r\n                    degree - 1, order - 1 );\r\n\r\n        // Compute polynomial.\r\n        return computeLegendrePolynomialDiagonal(\r\n                    degree, degreeOneOrderOnePolynomial, priorSectoralPolynomial );\r\n    }\r\n\r\n    // Else degree and order are zonal/tessoral...\r\n    else\r\n    {\r\n        // Obtain prior degree polynomial.\r\n        const double oneDegreePriorPolynomial = legendreCache.getLegendrePolynomial(\r\n                    degree - 1, order );\r\n\r\n        // Obtain two degrees prior polynomial.\r\n        const double twoDegreesPriorPolynomial = legendreCache.getLegendrePolynomial(\r\n                    degree - 2, order );\r\n\r\n        // Compute polynomial.\r\n        return computeLegendrePolynomialVertical( degree,\r\n                                                  order,\r\n                                                  legendreCache.getCurrentPolynomialParameter( ),\r\n                                                  oneDegreePriorPolynomial,\r\n                                                  twoDegreesPriorPolynomial );\r\n    }\r\n}\r\n\r\n\r\ndouble computeLegendrePolynomial( const int degree,\r\n                                  const int order,\r\n                                  const double legendreParameter )\r\n{\r\n    LegendreCache legendreCache( degree, order, 0 );\r\n    legendreCache.update( legendreParameter );\r\n    return computeLegendrePolynomial( degree, order, legendreCache );\r\n}\r\n\r\n\r\n//! Compute geodesy-normalized associated Legendre polynomial.\r\ndouble computeGeodesyLegendrePolynomial( const int degree,\r\n                                         const int order,\r\n                                         LegendreCache& geodesyLegendreCache )\r\n{\r\n\r\n    if( !geodesyLegendreCache.getUseGeodesyNormalization( ) )\r\n    {\r\n        throw std::runtime_error( \"Error when computing Legendre polynomial, input uses no normalization\" );\r\n    }\r\n\r\n    // If degree or order is negative...\r\n    if ( degree < 0 || order < 0 )\r\n    {\r\n        // Set error message.\r\n        std::stringstream errorMessage;\r\n        errorMessage << \"Error: the Legendre polynomial of = \" << degree << \" and order = \"\r\n                     << order << \" is undefined.\" << std::endl;\r\n\r\n        // Throw a run-time error.\r\n        boost::throw_exception( boost::enable_error_info( std::runtime_error(\r\n                                                              errorMessage.str( ) ) ) );\r\n    }\r\n\r\n    // Else if order is greater than degree...\r\n    else if ( order > degree && degree >= 0 )\r\n    {\r\n        // Return zero.\r\n        return 0.0;\r\n    }\r\n\r\n    // Else if order and degree are lower than 2...\r\n    else if ( degree <= 1 && order <= 1 )\r\n    {\r\n        // Compute polynomial explicitly.\r\n        return computeGeodesyLegendrePolynomialExplicit( degree, order, geodesyLegendreCache.getCurrentPolynomialParameter( ) );\r\n    }\r\n\r\n    // Else if degree and order are sectoral...\r\n    else if ( degree == order )\r\n    {\r\n        // Obtain polynomial of degree one and order one.\r\n        double degreeOneOrderOnePolynomial = geodesyLegendreCache.getLegendrePolynomial(\r\n                    1, 1 );\r\n\r\n        // Obtain prior sectoral polynomial.\r\n        double priorSectoralPolynomial = geodesyLegendreCache.getLegendrePolynomial(\r\n                    degree - 1, order - 1 );\r\n\r\n        // Compute polynomial.\r\n        return computeGeodesyLegendrePolynomialDiagonal(\r\n                    degree, degreeOneOrderOnePolynomial, priorSectoralPolynomial );\r\n    }\r\n\r\n    // Else degree and order are zonal/tessoral...\r\n    else\r\n    {\r\n        // Obtain prior degree polynomial.\r\n        double oneDegreePriorPolynomial = geodesyLegendreCache.getLegendrePolynomial(\r\n                    degree - 1, order );\r\n\r\n        // Obtain two degrees prior polynomial.\r\n        double twoDegreesPriorPolynomial = geodesyLegendreCache.getLegendrePolynomial(\r\n                    degree - 2, order );\r\n\r\n        // Compute polynomial.\r\n        return computeGeodesyLegendrePolynomialVertical( degree,\r\n                                                         order,\r\n                                                         geodesyLegendreCache.getCurrentPolynomialParameter( ),\r\n                                                         oneDegreePriorPolynomial,\r\n                                                         twoDegreesPriorPolynomial );\r\n    }\r\n}\r\n\r\ndouble computeGeodesyLegendrePolynomial( const int degree,\r\n                                         const int order,\r\n                                         const double legendreParameter )\r\n{\r\n    LegendreCache legendreCache( degree, order, 1 );\r\n    legendreCache.update( legendreParameter );\r\n    return computeGeodesyLegendrePolynomial( degree, order, legendreCache );\r\n}\r\n\r\n//! Compute derivative of unnormalized Legendre polynomial.\r\ndouble computeLegendrePolynomialDerivative( const int order,\r\n                                            const double polynomialParameter,\r\n                                            const double currentLegendrePolynomial,\r\n                                            const double incrementedLegendrePolynomial )\r\n{\r\n    // Return polynomial derivative.\r\n    return incrementedLegendrePolynomial\r\n            / std::sqrt( 1.0 - polynomialParameter * polynomialParameter )\r\n            - static_cast< double >( order ) * polynomialParameter\r\n            / ( 1.0 - polynomialParameter * polynomialParameter )\r\n            * currentLegendrePolynomial;\r\n}\r\n\r\n//! Compute derivative of geodesy-normalized Legendre polynomial.\r\ndouble computeGeodesyLegendrePolynomialDerivative( const int degree,\r\n                                                   const int order,\r\n                                                   const double polynomialParameter,\r\n                                                   const double currentLegendrePolynomial,\r\n                                                   const double incrementedLegendrePolynomial )\r\n{\r\n    // Compute normalization correction factor.\r\n    double normalizationCorrection = std::sqrt( ( static_cast< double >( degree )\r\n                                                  + static_cast< double >( order ) + 1.0 )\r\n                                                * ( static_cast< double >( degree - order ) ) );\r\n\r\n    // If order is zero apply multiplication factor.\r\n    if ( order == 0 )\r\n    {\r\n        normalizationCorrection *= std::sqrt( 0.5 );\r\n    }\r\n\r\n    // Return polynomial derivative.\r\n    return normalizationCorrection * incrementedLegendrePolynomial\r\n            / std::sqrt( 1.0 - polynomialParameter * polynomialParameter )\r\n            - static_cast< double >( order ) * polynomialParameter\r\n            / ( 1.0 - polynomialParameter * polynomialParameter )\r\n            * currentLegendrePolynomial;\r\n}\r\n\r\n//! Compute low degree/order unnormalized Legendre polynomial explicitly.\r\ndouble computeLegendrePolynomialExplicit( const int degree,\r\n                                          const int order,\r\n                                          const double polynomialParameter )\r\n{\r\n    // Check which order is required for Legendre polynomial.\r\n    switch( degree )\r\n    {\r\n    case 0:\r\n        switch( order )\r\n        {\r\n        case 0:\r\n            return 1.0;\r\n        default:\r\n            std::cerr << \"Error, explicit legendre polynomial not possible for \"\r\n                      << degree << \" \" << order << std::endl;\r\n        }\r\n        break;\r\n    case 1:\r\n        switch( order )\r\n        {\r\n        case 0:\r\n            return polynomialParameter;\r\n        case 1:\r\n            return std::sqrt( 1 - polynomialParameter * polynomialParameter );\r\n        default:\r\n            std::cerr << \"Error, explicit legendre polynomial not possible for \"\r\n                      << degree << \" \" << order << std::endl;\r\n        }\r\n        break;\r\n    case 2:\r\n        switch( order )\r\n        {\r\n        case 0:\r\n            return 0.5 * ( 3.0 * polynomialParameter * polynomialParameter - 1.0 );\r\n        case 1:\r\n            return 3.0 * polynomialParameter\r\n                    * std::sqrt( 1.0 - polynomialParameter * polynomialParameter );\r\n        case 2:\r\n            return 3.0 * ( 1.0 - polynomialParameter * polynomialParameter );\r\n        default:\r\n            std::cerr << \"Error, explicit legendre polynomial not possible for \"\r\n                      << degree << \" \" << order << std::endl;\r\n        }\r\n        break;\r\n    case 3:\r\n        switch( order )\r\n        {\r\n        case 0:\r\n            return 0.5 * polynomialParameter\r\n                    * ( 5.0 * polynomialParameter * polynomialParameter - 3.0 );\r\n        case 1:\r\n            return 1.5 * ( 5.0 * polynomialParameter * polynomialParameter - 1.0 )\r\n                    * std::sqrt( 1.0 - polynomialParameter * polynomialParameter );\r\n        case 2:\r\n            return 15.0 * polynomialParameter * ( 1.0 - polynomialParameter * polynomialParameter );\r\n        case 3:\r\n            return 15.0 * ( 1.0 - polynomialParameter * polynomialParameter )\r\n                    * std::sqrt( 1.0 - polynomialParameter * polynomialParameter );\r\n        default:\r\n            std::cerr << \"Error, a explicit legendre polynomial not possible for \"\r\n                      << degree << \" \" << order << std::endl;\r\n        }\r\n        break;\r\n    case 4:\r\n        switch( order )\r\n        {\r\n        case 0:\r\n            return ( 35.0 * polynomialParameter * polynomialParameter\r\n                     * polynomialParameter * polynomialParameter\r\n                     - 30.0 * polynomialParameter * polynomialParameter + 3.0 ) / 8.0;\r\n        case 1:\r\n            return -2.5 * ( 7.0 * polynomialParameter * polynomialParameter * polynomialParameter\r\n                            - 3.0 * polynomialParameter )\r\n                    * std::sqrt( 1.0 - polynomialParameter * polynomialParameter );\r\n        case 2:\r\n            return 15.0 / 2.0 * ( - 1.0 + 7.0 * polynomialParameter * polynomialParameter )\r\n                    * ( 1.0 - polynomialParameter * polynomialParameter );\r\n        case 3:\r\n            return -105.0 * polynomialParameter * ( 1.0 - polynomialParameter * polynomialParameter )\r\n                    * std::sqrt( 1.0 - polynomialParameter * polynomialParameter );\r\n        case 4:\r\n            return 105.0 * ( 1.0 - polynomialParameter * polynomialParameter )\r\n                    * ( 1.0 - polynomialParameter * polynomialParameter );\r\n\r\n        default:\r\n            std::cerr << \"Error, a explicit legendre polynomial not possible for \"\r\n                      << degree << \" \" << order << std::endl;\r\n        }\r\n        break;\r\n    default:\r\n        std::cerr << \"Error, explicit legendre polynomial not possible for \"\r\n                  << degree << \" \" << order << std::endl;\r\n    }\r\n    return TUDAT_NAN;\r\n}\r\n\r\n//! Compute low degree/order geodesy-normalized Legendre polynomials explicitly.\r\ndouble computeGeodesyLegendrePolynomialExplicit( const int degree,\r\n                                                 const int order,\r\n                                                 const double polynomialParameter )\r\n{\r\n    // If 0,0 term is requested return Legendre polynomial value.\r\n    if ( degree == 0 && order == 0 )\r\n    {\r\n        return 1.0;\r\n    }\r\n\r\n    // Else if 1,0 term is requested return polynomial value.\r\n    else if ( degree == 1 && order == 0 )\r\n    {\r\n        return std::sqrt( 3.0 ) * polynomialParameter;\r\n    }\r\n\r\n    // Else if 1,1 term is requested return polynomial value.\r\n    else if ( degree == 1 && order == 1 )\r\n    {\r\n        return std::sqrt( 3.0 - 3.0 * polynomialParameter * polynomialParameter );\r\n    }\r\n\r\n    // Else the requested term cannot be computed; throw a run-time error.\r\n    else\r\n    {\r\n        // Set error message.\r\n        std::stringstream errorMessage;\r\n        errorMessage  <<  \"Error: computation of Legendre polynomial of = \"  <<  degree\r\n                      <<  \" and order = \"  <<  order  <<  \" is not supported.\"  <<  std::endl;\r\n\r\n        // Throw a run-time error.\r\n        boost::throw_exception( boost::enable_error_info( std::runtime_error(\r\n                                                              errorMessage.str( ) ) ) );\r\n    }\r\n}\r\n\r\n//! Compute unnormalized Legendre polynomial through sectoral recursion.\r\ndouble computeLegendrePolynomialDiagonal( const int degree,\r\n                                          const double degreeOneOrderOnePolynomial,\r\n                                          const double priorSectoralPolynomial )\r\n{\r\n    // Return polynomial.\r\n    return ( 2.0 * static_cast< double >( degree ) - 1.0 )\r\n            * degreeOneOrderOnePolynomial * priorSectoralPolynomial;\r\n\r\n}\r\n\r\n//! Compute geodesy-normalized Legendre polynomial through sectoral recursion.\r\ndouble computeGeodesyLegendrePolynomialDiagonal( const int degree,\r\n                                                 const double degreeOneOrderOnePolynomial,\r\n                                                 const double priorSectoralPolynomial )\r\n{\r\n    // Return polynomial.\r\n    return std::sqrt( ( 2.0 * static_cast< double >( degree ) + 1.0 )\r\n                      / ( 6.0 * static_cast< double >( degree ) ) )\r\n            * degreeOneOrderOnePolynomial * priorSectoralPolynomial;\r\n}\r\n\r\n//! Compute unnormalized Legendre polynomial through degree recursion.\r\ndouble computeLegendrePolynomialVertical( const int degree,\r\n                                          const int order,\r\n                                          const double polynomialParameter,\r\n                                          const double oneDegreePriorPolynomial,\r\n                                          const double twoDegreesPriorPolynomial )\r\n{\r\n    // Return polynomial.\r\n    return ( ( 2.0 * static_cast< double >( degree ) - 1.0 ) * polynomialParameter\r\n             * oneDegreePriorPolynomial - ( static_cast< double >( degree + order ) - 1.0 )\r\n             * twoDegreesPriorPolynomial ) / ( static_cast< double >( degree - order ) );\r\n}\r\n\r\n//! Compute geodesy-normalized Legendre polynomial through degree recursion.\r\ndouble computeGeodesyLegendrePolynomialVertical( const int degree,\r\n                                                 const int order,\r\n                                                 const double polynomialParameter,\r\n                                                 const double oneDegreePriorPolynomial,\r\n                                                 const double twoDegreesPriorPolynomial )\r\n{\r\n    // Return polynomial.\r\n    return std::sqrt( ( 2.0 * static_cast< double >( degree ) + 1.0 )\r\n                      / ( ( static_cast< double >( degree + order ) ) * ( static_cast< double >( degree - order ) ) ) )\r\n            * ( std::sqrt( 2.0 * static_cast< double >( degree ) - 1.0 ) * polynomialParameter * oneDegreePriorPolynomial\r\n                - std::sqrt( ( static_cast< double >( degree + order ) - 1.0 )\r\n                             * ( static_cast< double >( degree - order ) - 1.0 )\r\n                             / ( 2.0 * static_cast< double >( degree ) - 3.0 ) )\r\n                * twoDegreesPriorPolynomial );\r\n}\r\n\r\n\r\n//! Function to calculate the normalization factor for Legendre polynomials to geodesy-normalized.\r\ndouble calculateLegendreGeodesyNormalizationFactor( const int degree, const int order )\r\n{\r\n\r\n    double deltaFunction = 0.0;\r\n    if( order == 0 )\r\n    {\r\n        deltaFunction = 1.0;\r\n    }\r\n\r\n    double factor = std::sqrt(\r\n        boost::math::factorial< double >( static_cast< double >( degree + order ) )\r\n        / ( ( 2.0 - deltaFunction ) * ( 2.0 * static_cast< double >( degree ) + 1.0 )\r\n            * boost::math::factorial< double >( static_cast< double >( degree - order ) ) ) );\r\n    return 1.0 / factor;\r\n}\r\n\r\n\r\n} // namespace basic_mathematics\r\n} // namespace tudat\r\n", "meta": {"hexsha": "237692aab7eba1bcff096c094e66eafce1e3fa37", "size": 22591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/legendrePolynomials.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/legendrePolynomials.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/legendrePolynomials.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": 41.0745454545, "max_line_length": 148, "alphanum_fraction": 0.5724403524, "num_tokens": 4591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5472518156976969}}
{"text": "#include \"tasktorrent/tasktorrent.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <fstream>\n#include <array>\n#include <random>\n#include <mutex>\n#include <iostream>\n#include <map>\n#include <memory>\n\n#include <mpi.h>\n\ntypedef array<int, 2> int2;\ntypedef array<int, 3> int3;\ntypedef array<int, 4> int4;\ntypedef array<int, 5> int5;\ntypedef array<int, 6> int6;\ntypedef array<int, 7> int7;\n\nstruct scoped_timer {\n  private:\n    std::atomic<long long int>* time_us_;\n    ttor::timer time_init_;\n  public:\n    scoped_timer(std::atomic<long long int>* time_us) {\n        time_us_ = time_us;\n        time_init_= ttor::wctime();\n    }\n    ~scoped_timer() {\n        ttor::timer time_end_ = ttor::wctime();\n        *time_us_ += static_cast<long long int>(1e6 * ttor::elapsed(time_init_, time_end_));\n    }\n};\n\nttor::view<double> make_view(Eigen::MatrixXd* A) {\n    return ttor::view<double>(A->data(), A->size());\n}\n\nEigen::MatrixXd make_from_view(ttor::view<double> A, int nrows) {\n    Eigen::MatrixXd Add = Eigen::MatrixXd::Zero(nrows, nrows);\n    assert(nrows * nrows == A.size());\n    memcpy(Add.data(), A.data(), sizeof(double) * A.size());\n    return Add;\n}\n\nvoid copy_from_view(Eigen::MatrixXd* dest, const ttor::view<double> A) {\n    assert(dest->size() == A.size());\n    memcpy(dest->data(), A.data(), sizeof(double) * A.size());\n}\n\nvoid accumulate(Eigen::MatrixXd* dest, const Eigen::MatrixXd* src) {\n    assert(dest->size() == src->size());\n    #pragma omp parallel for\n    for(int k = 0; k < dest->size(); k++) {\n        (*dest)(k) += (*src)(k);\n    }\n}\n\nstd::string to_string(int2 ij) {\n    return to_string(ij[0]) + \"_\" + to_string(ij[1]);\n}\n\nstd::string to_string(int3 ijk) {\n    return to_string(ijk[0]) + \"_\" + to_string(ijk[1]) + \"_\" + to_string(ijk[2]);\n}\n\n/**\n * Matrix is of size N (global)\n * Each rank works on Nr x Nr\n * Each thread works on Nt x Nt\n * \n * There are n sub blocks on a given rank\n */\nvoid gemm(const int N, const int Nt, const int n_threads, std::string logfile, const int verb, const bool test)\n{\n    const int rank = ttor::comm_rank();\n    const int n_ranks = ttor::comm_size();\n    const int n_ranks_1d = static_cast<int>(round(pow(n_ranks, 1.0/3.0)));\n    assert(n_ranks_1d * n_ranks_1d * n_ranks_1d == n_ranks);\n    const int rank_i = rank % n_ranks_1d;\n    const int rank_j = (rank / n_ranks_1d) % n_ranks_1d;\n    const int rank_k = rank / (n_ranks_1d * n_ranks_1d);\n    const int3 rank_ijk = {rank_i, rank_j, rank_k};\n    const int Nr = N / n_ranks_1d;\n    assert(Nr * n_ranks_1d == N);\n    const int n = Nr / Nt;\n    assert(Nt * n == Nr);\n    printf(\"Hello rank %d with 3d-index (%d %d %d) / (%d %d %d) from host %s, N %d, Nr %d, Nt %d, n %d\\n\", rank, rank_i, rank_j, rank_k, n_ranks_1d, n_ranks_1d, n_ranks_1d, \n        ttor::processor_name().c_str(), N, Nr, Nt, n);\n\n    printf(\"rank,%d\\n\", rank);\n    printf(\"rank_i,%d\\n\", rank_i);\n    printf(\"rank_j,%d\\n\", rank_j);\n    printf(\"rank_k,%d\\n\", rank_k);\n    printf(\"ntot,%d\\n\", N);\n    printf(\"nrank,%d\\n\", Nr);\n    printf(\"ntile,%d\\n\", Nt);\n    printf(\"nthreads,%d\\n\", n_threads);\n    printf(\"logfile,%s\\n\", logfile.c_str());\n    printf(\"verb,%d\\n\", verb);\n    printf(\"test,%d\\n\", test);\n    \n    auto rank_ijk_to_rank = [n_ranks_1d](int rank_i, int rank_j, int rank_k) {\n        return rank_k * n_ranks_1d * n_ranks_1d + rank_j * n_ranks_1d + rank_i;\n    };\n    assert(rank_ijk_to_rank(rank_i, rank_j, rank_k) == rank);\n\n    /**\n     * Record timings\n     **/\n    std::atomic<long long int> send_copy_us_t(0);\n    std::atomic<long long int> send_am_us_t(0);\n    std::atomic<long long int> bcst_copy_us_t(0);\n    std::atomic<long long int> bcst_am_us_t(0);\n    std::atomic<long long int> gemm_us_t(0);\n    std::atomic<long long int> gemm_copy_us_t(0);\n    std::atomic<long long int> gemm_am_us_t(0);\n    std::atomic<long long int> accu_us_t(0);\n\n    /**\n     * Original and final matrices\n     **/\n    // n x n matrix of Nt x Nt matrices, so Nr x Nr total\n    std::vector<std::vector<Eigen::MatrixXd>> A_ij(n, std::vector<Eigen::MatrixXd>(n, Eigen::MatrixXd::Zero(Nt, Nt)));\n    std::vector<std::vector<Eigen::MatrixXd>> C_ij(n, std::vector<Eigen::MatrixXd>(n, Eigen::MatrixXd::Zero(Nt, Nt)));\n    std::vector<std::vector<Eigen::MatrixXd>> B_ij(n, std::vector<Eigen::MatrixXd>(n, Eigen::MatrixXd::Zero(Nt, Nt)));\n\n    auto val_global = [](int i, int j) { return static_cast<double>(1 + i + j); };\n    if(rank_k == 0) {\n        for(int i = 0; i < n; i++) {\n            for(int j = 0; j < n; j++) {\n                auto val = [&](int i_, int j_) { return val_global(rank_i * Nr + i * Nt + i_, rank_j * Nr + j * Nt + j_); };\n                A_ij[i][j] = Eigen::MatrixXd::NullaryExpr(Nt, Nt, val);\n                B_ij[i][j] = Eigen::MatrixXd::NullaryExpr(Nt, Nt, val);\n            }\n        }\n    }\n\n    /** \n     * Workspace\n     **/\n    std::vector<std::vector<Eigen::MatrixXd>> A_ijk(n, std::vector<Eigen::MatrixXd>(n, Eigen::MatrixXd::Zero(Nt, Nt)));\n    std::vector<std::vector<Eigen::MatrixXd>> C_ijk(n, std::vector<Eigen::MatrixXd>(n, Eigen::MatrixXd::Zero(Nt, Nt)));\n    std::vector<std::vector<Eigen::MatrixXd>> B_ijk(n, std::vector<Eigen::MatrixXd>(n, Eigen::MatrixXd::Zero(Nt, Nt)));\n    std::vector<std::unique_ptr<std::atomic<int>>> C_ijk_counts(n * n);\n    for(int i = 0; i < n*n; i++) {\n        C_ijk_counts[i] = std::make_unique<std::atomic<int>>();\n        C_ijk_counts[i]->store(0);\n    }\n    \n    // C_ijk_accu[sub_i][sub_j][from] stores the results for (sub_i, sub_j) to be accumulated, from rank from\n    std::vector<std::vector<std::vector<Eigen::MatrixXd>>> C_ijk_accu(\n        n, std::vector<std::vector<Eigen::MatrixXd>>(\n        n, std::vector<Eigen::MatrixXd>(\n        n_ranks_1d, Eigen::MatrixXd::Zero(Nt, Nt))));\n    \n    MPI_Barrier(MPI_COMM_WORLD);\n\n    /**\n     * Initialize the runtime structures\n     **/\n    ttor::Communicator comm(MPI_COMM_WORLD, verb);\n    ttor::Threadpool tp(n_threads, &comm, verb, \"Wk_Gemm_\" + to_string(rank) + \"_\");\n\n    // send is indexed by int2, which are the sub blocks\n    ttor::Taskflow<int2> send_Aij(&tp, verb);  // (i,j,0) sends A_ij to (i,j,j) for all i,j\n    ttor::Taskflow<int2> send_Bij(&tp, verb);  // (i,j,0) sends B_ij to (i,j,i) for all i,j\n    // send is indexed by int2, which are the sub blocks\n    ttor::Taskflow<int2> bcst_Aij(&tp, verb);  // (i,j,j) sends A_ij along j to all (i,*,j) for all i,j\n    ttor::Taskflow<int2> bcst_Bij(&tp, verb);  // (i,j,i) sends B_ij along i to all (*,j,i) for all i,j\n    // gemm is indexed by int3, which are the sub blocks\n    ttor::Taskflow<int3> gemm_Cijk(&tp, verb); // (i,j,k) compute C_ijk = A_ik * B_kj, send for accumulation reduction on (i,j,0)\n    ttor::Taskflow<int3> accu_Cij(&tp, verb);  // accumulate (i,j,from) into (i,j)\n\n    ttor::Logger log(1000000);\n    if(logfile.size() > 0) {\n        tp.set_logger(&log);\n        comm.set_logger(&log);\n    }\n\n    /** \n     * Send\n     **/\n\n    auto send_Aij_am = comm.make_active_msg([&](ttor::view<double>& Aij, int& sub_i, int& sub_j) {\n        scoped_timer t(&send_am_us_t);\n        copy_from_view(&A_ijk[sub_i][sub_j], Aij);\n        bcst_Aij.fulfill_promise({sub_i, sub_j});\n    });\n\n    auto send_Bij_am = comm.make_active_msg([&](ttor::view<double>& Bij, int& sub_i, int& sub_j) {\n        scoped_timer t(&send_am_us_t);\n        copy_from_view(&B_ijk[sub_i][sub_j], Bij);\n        bcst_Bij.fulfill_promise({sub_i, sub_j});\n    });\n\n    // (i,j,0) sends A_ij to (i,j,j) for all i,j\n    send_Aij.set_task([&](int2 sub_ij){\n        assert(rank_k == 0);\n        scoped_timer t(&send_copy_us_t);\n        int sub_i = sub_ij[0];\n        int sub_j = sub_ij[1];\n        ttor::view<double> A_view = make_view(&A_ij[sub_i][sub_j]);\n        int dest = rank_ijk_to_rank(rank_i, rank_j, rank_j);\n        if(dest == rank) {\n            A_ijk[sub_i][sub_j] = A_ij[sub_i][sub_j];\n            bcst_Aij.fulfill_promise({sub_i, sub_j});\n        } else {\n            send_Aij_am->send(dest, A_view, sub_i, sub_j);\n        }\n    }).set_indegree([&](int2) {\n        return 1;\n    }).set_mapping([&](int2 sub_ij) {\n        // return (sub_ij[0] + n * sub_ij[1]) % n_threads;\n        // return 0;\n        return sub_ij[0] % n_threads;\n    }).set_priority([&](int2 sub_ij){\n        return 1.0 * n + (n - sub_ij[1]);\n    }).set_binding([&](int2 sub_ij){\n        return false;\n        // return true;\n    }).set_name([&](int2 sub_ij) { return \"send_A_\" + to_string(sub_ij) + \"_\" + to_string(rank_ijk); });\n\n    // (i,j,0) sends B_ij to (i,j,i) for all i,j\n    send_Bij.set_task([&](int2 sub_ij){\n        assert(rank_k == 0);\n        scoped_timer t(&send_copy_us_t);\n        int sub_i = sub_ij[0];\n        int sub_j = sub_ij[1];\n        ttor::view<double> B_view = make_view(&B_ij[sub_i][sub_j]);\n        int dest = rank_ijk_to_rank(rank_i, rank_j, rank_i);\n        if(dest == rank) {\n            B_ijk[sub_i][sub_j] = B_ij[sub_i][sub_j];\n            bcst_Bij.fulfill_promise({sub_i, sub_j});\n        } else {\n            send_Bij_am->send(dest, B_view, sub_i, sub_j);\n        }\n    }).set_indegree([&](int2) {\n        return 1;\n    }).set_mapping([&](int2 sub_ij) {\n        // return (sub_ij[0] + n * sub_ij[1]) % n_threads;\n        // return 0;\n        return (sub_ij[1] % n_threads);\n    }).set_priority([&](int2 sub_ij){\n        return 1.0 * n + (n - sub_ij[0]);\n    }).set_binding([&](int2 sub_ij){\n        return false;\n        //return true;\n    }).set_name([&](int2 sub_ij) { return \"send_B_\" + to_string(sub_ij) + \"_\" + to_string(rank_ijk); });\n\n    /** \n     * Broadcast\n     **/\n\n    auto bcst_Aij_am = comm.make_active_msg([&](ttor::view<double>& Aij, int &sub_i, int &sub_j) {\n        scoped_timer t(&bcst_am_us_t);\n        copy_from_view(&A_ijk[sub_i][sub_j], Aij);\n        for(int k = 0; k < n; k++)\n            gemm_Cijk.fulfill_promise({sub_i, k, sub_j});\n    });\n\n    auto bcst_Bij_am = comm.make_active_msg([&](ttor::view<double>& Bij, int &sub_i, int &sub_j) {\n        scoped_timer t(&bcst_am_us_t);\n        copy_from_view(&B_ijk[sub_i][sub_j], Bij);\n        for(int k = 0; k < n; k++)\n            gemm_Cijk.fulfill_promise({k, sub_j, sub_i});\n    });\n\n    // (i,j,j) sends A_ij along j to all (i,*,j) for all i,j\n    bcst_Aij.set_task([&](int2 sub_ij){\n        scoped_timer t(&bcst_copy_us_t);\n        assert(rank_j == rank_k);\n        int sub_i = sub_ij[0];\n        int sub_j = sub_ij[1];\n        ttor::view<double> A_view = make_view(&A_ijk[sub_i][sub_j]);\n        for(int k = 0; k < n_ranks_1d; k++) {\n            int dest = rank_ijk_to_rank(rank_i, k, rank_j);\n            if(dest == rank) {\n                for(int l = 0; l < n; l++)\n                    gemm_Cijk.fulfill_promise({sub_i, l, sub_j});\n            } else {\n                bcst_Aij_am->send(dest, A_view, sub_i, sub_j);\n            }\n        }\n    }).set_indegree([&](int2) {\n        return 1;\n    }).set_mapping([&](int2 sub_ij) {\n        // return (sub_ij[0] + n * sub_ij[1]) % n_threads;\n        // return 0;\n        return (sub_ij[0] % n_threads);\n    }).set_priority([&](int2 sub_ij){\n        return 1.0 * n + (n - sub_ij[1]);\n    }).set_binding([&](int2 sub_ij){\n        return false;\n        //return true;\n    }).set_name([&](int2 sub_ij) { return \"bcast_A_\" + to_string(sub_ij) + \"_\" + to_string(rank_ijk); });\n\n    // (i,j,i) sends B_ij along i to all (*,j,i) for all i,j\n    bcst_Bij.set_task([&](int2 sub_ij){\n        scoped_timer t(&bcst_copy_us_t);\n        assert(rank_i == rank_k);\n        int sub_i = sub_ij[0];\n        int sub_j = sub_ij[1];\n        ttor::view<double> B_view = make_view(&B_ijk[sub_i][sub_j]);\n        for(int k = 0; k < n_ranks_1d; k++) {\n            int dest = rank_ijk_to_rank(k, rank_j, rank_i);\n            if(dest == rank) {\n                for(int l = 0; l < n; l++)\n                    gemm_Cijk.fulfill_promise({l, sub_j, sub_i});\n            } else {\n                bcst_Bij_am->send(dest, B_view, sub_i, sub_j);\n            }\n        }\n    }).set_indegree([&](int2) {\n        return 1;\n    }).set_mapping([&](int2 sub_ij) {\n        // return (sub_ij[0] + n * sub_ij[1]) % n_threads;\n        // return 0;\n        return (sub_ij[1] % n_threads);\n    }).set_priority([&](int2 sub_ij){\n        return 1.0 * n + (n - sub_ij[0]);\n    }).set_binding([&](int2 sub_ij){\n        return false;\n        // return true;\n    }).set_name([&](int2 sub_ij) { return \"bcast_B_\" + to_string(sub_ij) + \"_\" + to_string(rank_ijk); });\n\n    /** \n     * GEMM\n     **/\n\n    auto gemm_Cijk_am = comm.make_active_msg([&](ttor::view<double>& Cijk, int &sub_i, int &sub_j, int& from) {\n        scoped_timer t(&gemm_am_us_t);\n        copy_from_view(&C_ijk_accu[sub_i][sub_j][from], Cijk);\n        accu_Cij.fulfill_promise({sub_i, sub_j, from});\n    });\n\n    // (i,j,k) compute C_ijk = A_ik * B_kj\n    gemm_Cijk.set_task([&](int3 sub_ijk){\n        int sub_i = sub_ijk[0];\n        int sub_j = sub_ijk[1];\n        int sub_k = sub_ijk[2];\n        {\n            scoped_timer t(&gemm_us_t);\n            C_ijk[sub_i][sub_j].noalias() += A_ijk[sub_i][sub_k] * B_ijk[sub_k][sub_j];\n        }\n        //(*(C_ijk_counts[sub_i * n + sub_j]))++;\n        scoped_timer t(&gemm_copy_us_t);\n        if(sub_ijk[2] < n-1) {\n            gemm_Cijk.fulfill_promise({sub_i, sub_j, sub_k+1});\n        } else {\n        //if(C_ijk_counts[sub_i * n + sub_j]->load() == n) {\n            auto C_ijk_view = make_view(&C_ijk[sub_i][sub_j]);\n            int dest = rank_ijk_to_rank(rank_i, rank_j, 0);\n            if(dest == rank) {\n                C_ijk_accu[sub_i][sub_j][rank_k] = C_ijk[sub_i][sub_j];\n                accu_Cij.fulfill_promise({sub_i, sub_j, rank_k});\n            } else {\n                int k = rank_k;\n                gemm_Cijk_am->send(dest, C_ijk_view, sub_i, sub_j, k);\n            }\n        }\n    }).set_indegree([&](int3 sub_ijk) {\n        return sub_ijk[2] == 0 ? 2 : 3; // 2 A_ik and B_kj blocks, + previous gemm\n        // return 2;\n    }).set_mapping([&](int3 sub_ijk) {\n        if(n_threads == 1) return 0;\n        // else return max(1, (sub_ijk[0] + sub_ijk[1] * n) % n_threads);\n        else return max(1, (sub_ijk[0] + sub_ijk[1] * n) % n_threads); // + sub_ijk[2] * n * n) % n_threads);\n        // return (sub_ijk[0] + sub_ijk[1] * n + sub_ijk[2] * n * n) % n_threads;\n    }).set_binding([&](int3 sub_ijk) {\n        return false;\n    }).set_priority([&](int3 sub_ijk){\n        return 0.0 * n + (n - sub_ijk[2]);\n    }).set_name([&](int3 sub_ijk) { return \"gemm_C_\" + to_string(sub_ijk) + \"_\" + to_string(rank_ijk); });\n\n    // (i,j,k) compute C_ijk = A_ik * B_kj\n    accu_Cij.set_task([&](int3 sub_ij_from){\n        scoped_timer t(&accu_us_t);\n        int sub_i = sub_ij_from[0];\n        int sub_j = sub_ij_from[1];\n        int from  = sub_ij_from[2];\n        C_ij[sub_i][sub_j] += C_ijk_accu[sub_i][sub_j][from];\n    }).set_indegree([&](int3) {\n        return 1;\n    }).set_mapping([&](int3 sub_ij_from) {\n        if(n_threads == 1) return 0;\n        else return max(1, (sub_ij_from[0] + n * sub_ij_from[1]) % n_threads);\n        // return (sub_ij_from[0] + n * sub_ij_from[1]) % n_threads;\n    }).set_binding([&](int3) {\n        return true;\n    }).set_priority([&](int3){\n        return 0.0;\n    }).set_name([&](int3 sub_ij_from) { return \"accu_C_\" + to_string(sub_ij_from) + \"_\" + to_string(rank_ijk); });\n\n    printf(\"Starting 3D Gemm...\\n\");\n    ttor::timer t0 = ttor::wctime();\n    if(rank_k == 0) {\n        for(int i = 0; i < n; i++) {\n            for(int j = 0; j < n; j++) {\n                send_Aij.fulfill_promise({i,j});\n                send_Bij.fulfill_promise({i,j});\n            }\n        }\n    }\n    tp.join();\n    ttor::timer t1 = ttor::wctime();\n    double total_time = ttor::elapsed(t0, t1);\n    double gemm_time = gemm_us_t.load() * 1e-6;\n    double gemm_time_per_thread = gemm_time / n_threads;\n    printf(\"Done\\n\");\n    printf(\"total_time,%e\\n\", ttor::elapsed(t0, t1));\n    printf(\"send_copy_us_t,%e\\n\",send_copy_us_t.load() * 1e-6);\n    printf(\"send_am_us_t,%e\\n\",send_am_us_t.load() * 1e-6);\n    printf(\"bcst_copy_us_t,%e\\n\",bcst_copy_us_t.load() * 1e-6);\n    printf(\"bcst_am_us_t,%e\\n\",bcst_am_us_t.load() * 1e-6);\n    printf(\"gemm_us_t,%e\\n\",gemm_us_t.load() * 1e-6);\n    printf(\"gemm_copy_us_t,%e\\n\",gemm_copy_us_t.load() * 1e-6);\n    printf(\"gemm_am_us_t,%e\\n\",gemm_am_us_t.load() * 1e-6);\n    printf(\"accu_us_t,%e\\n\",accu_us_t.load() * 1e-6);\n    // For easy CSV parsing\n    printf(\"[rank]>>>>Ntot,Nrank,Ntile,rank,n_ranks,nthreads,tot_time,gemm_time,gemm_time_per_thread\\n\");\n    printf(\"[%d]>>>>%d,%d,%d,%d,%d,%d,%e,%e,%e\\n\",rank,N,Nr,Nt,rank,n_ranks,n_threads,total_time,gemm_time,gemm_time_per_thread);\n\n    if(logfile.size() > 0) {\n        std::ofstream logstream;\n        std::string filename = logfile + \".log.\" + to_string(rank);\n        printf(\"Saving log to %s\\n\", filename.c_str());\n        logstream.open(filename);\n        logstream << log;\n        logstream.close();\n    }\n\n    MPI_Barrier(MPI_COMM_WORLD);\n    if(test && rank_k == 0) {\n        // Send all to 0\n        int n_received = 0;\n        int n_expected = (rank == 0 ? n * n * n_ranks_1d * n_ranks_1d : 0);\n        Eigen::MatrixXd C_test = Eigen::MatrixXd::Zero(N, N);\n        ttor::Communicator comm(MPI_COMM_WORLD, verb);\n        auto am = comm.make_active_msg([&](ttor::view<double>& A, int& rank_i_from, int& rank_j_from, int& sub_i, int& sub_j){\n            C_test.block(rank_i_from * Nr + sub_i * Nt, rank_j_from * Nr + sub_j * Nt, Nt, Nt) = make_from_view(A, Nt);\n            n_received++;\n        });\n        int rank_i_from = rank_i;\n        int rank_j_from = rank_j;\n        for(int sub_i = 0; sub_i < n; sub_i++) {\n            for(int sub_j = 0; sub_j < n; sub_j++) {\n                auto C_view = make_view(&C_ij[sub_i][sub_j]);\n                am->send(0, C_view, rank_i_from, rank_j_from, sub_i, sub_j);\n            }\n        }\n        while((!comm.is_done()) || (n_received < n_expected)) {\n            comm.progress();\n        }\n        // Compute reference on 0\n        if(rank == 0) {\n            Eigen::MatrixXd A_ref = Eigen::MatrixXd::NullaryExpr(N, N, val_global);\n            Eigen::MatrixXd B_ref = Eigen::MatrixXd::NullaryExpr(N, N, val_global);\n            ttor::timer t0 = ttor::wctime();\n            Eigen::MatrixXd C_ref = A_ref * B_ref;\n            ttor::timer t1 = ttor::wctime();\n            double error = (C_ref - C_test).norm() / C_ref.norm();\n            printf(\"\\n==> GEMM error %e\\n\\n\", error);\n            printf(\"Reference code took %e\\n\", ttor::elapsed(t0, t1));\n            assert(error <= 1e-12);\n        }\n    }\n}\n\nint main(int argc, char **argv)\n{\n    int req = MPI_THREAD_FUNNELED;\n    int prov = -1;\n\n    MPI_Init_thread(NULL, NULL, req, &prov);\n\n    assert(prov == req);\n\n    int N = 128;\n    int Nt = 8;\n    int n_threads = 1;\n    int verb = 0;\n    bool test = true;\n    std::string logfile = \"\";\n\n    if (argc >= 2)\n    {\n        N = atoi(argv[1]);\n        assert(N > 0);\n    }\n    \n    if (argc >= 3) {\n        Nt = atoi(argv[2]);\n        assert(Nt > 0);\n        assert(Nt <= N);\n    }\n\n    if (argc >= 4) {\n        n_threads = atoi(argv[3]);\n        assert(n_threads > 0);\n    }\n\n    if (argc >= 5) {\n        logfile = argv[4];\n    }\n\n    if (argc >= 6) {\n        verb = atoi(argv[5]);\n        assert(verb >= 0);\n    }\n\n    if (argc >= 7) {\n        test = static_cast<bool>(atoi(argv[6]));\n    }\n\n    if(ttor::comm_rank() == 0) printf(\"Usage: ./3d_gemm N Nt n_threads logfile verb test\\n\");\n    if(ttor::comm_rank() == 0) printf(\"Arguments: N (global matrix size) %d, Nt (smallest block size) %d, n_threads %d, logfile %s, verb %d, test %d\\n\", N, Nt, n_threads, logfile.c_str(), verb, test);\n\n    gemm(N, Nt, n_threads, logfile, verb, test);\n\n    MPI_Finalize();\n}\n", "meta": {"hexsha": "2c20bb095636d736bae432b0ccbc6a2c38948371", "size": 19673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "miniapp/3d_gemm/3d_gemm.cpp", "max_stars_repo_name": "RCambier/tasktorrent", "max_stars_repo_head_hexsha": "1432e30517d5cb7cbeca0ceb1a3f3f426e5bfcfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "miniapp/3d_gemm/3d_gemm.cpp", "max_issues_repo_name": "RCambier/tasktorrent", "max_issues_repo_head_hexsha": "1432e30517d5cb7cbeca0ceb1a3f3f426e5bfcfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "miniapp/3d_gemm/3d_gemm.cpp", "max_forks_repo_name": "RCambier/tasktorrent", "max_forks_repo_head_hexsha": "1432e30517d5cb7cbeca0ceb1a3f3f426e5bfcfd", "max_forks_repo_licenses": ["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.5438931298, "max_line_length": 200, "alphanum_fraction": 0.566512479, "num_tokens": 6278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5472518130012332}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// importance_sampling::find_scale_to_finite_sum.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_IMPORTANCE_SAMPLING_WEIGHTS_FIND_SCALE_TO_FINITE_SUM_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_IMPORTANCE_SAMPLING_WEIGHTS_FIND_SCALE_TO_FINITE_SUM_HPP_ER_2009\n#include <cmath>\n#include <numeric>\n#include <stdexcept>\n#include <boost/lambda/lambda.hpp>\n#include <boost/range.hpp>\n#include <boost/format.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/tools/precision.hpp>\n#include <boost/numeric/conversion/bounds.hpp>\n#include <boost/statistics/detail/importance_sampling/weights/maximal_finite_sums.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace importance_sampling{\n\n    // Finds c such that the sum over sum{*i/c, i in [b,e)} < inf using the\n    // bisection method.\n    //\n    // Warning: The value c is not insensitive to permutations of [b,e), due\n    // to non-associativity in the fp system\n    template<typename InIt>\n    typename iterator_value<InIt>::type \n    find_scale_to_finite_sum(\n        InIt b,InIt e,\n        typename iterator_value<InIt>::type low_init,\n        typename iterator_value<InIt>::type high_init\n    );\n    \n    // This version may be faster than that above with low = 1, high = highest\n    template<typename InIt>\n    typename iterator_value<InIt>::type \n    find_scale_to_finite_sum(InIt b,InIt e);\n\n    // Implementation //\n\n    template<typename InIt>\n    typename iterator_value<InIt>::type \n    find_scale_to_finite_sum(\n        InIt b,InIt e,\n        typename iterator_value<InIt>::type low_init,\n        typename iterator_value<InIt>::type high_init\n    ){\n        typedef typename iterator_value<InIt>::type val_;\n        static val_ zero = static_cast<val_>(0);\n        static val_ two = static_cast<val_>(2);\n        static val_ eps = boost::math::tools::epsilon<val_>();\n\n        BOOST_ASSERT(low_init < high_init);\n        BOOST_ASSERT(low_init > zero);\n        BOOST_ASSERT(high_init > zero);\n        val_ low = low_init;\n        val_ high = high_init;\n        val_ mid = (low + high)/two;\n        val_ delta, acc;\n        \n        do{\n            delta = high - low;\n            acc =\n                std::accumulate(b,e,zero, lambda::_1 + ( lambda::_2 / mid) );\n            if(boost::math::isinf(acc)){\n                low = mid;\n            }else{\n                high = mid;\n            }\n            mid = (low+high)/two;\n        }while(\n            delta - (high - low)>eps\n        );\n        static  \n            const char* str = \"%3% = find_scale_to_finite_sum(b,e,%1%,%2%) = inf\";\n        if(\n            boost::math::isinf(\n                std::accumulate(b,e,zero, lambda::_1 + ( lambda::_2 / high) )\n            )\n        ){\n            format f(str); f%low_init%high_init%high;\n            throw std::runtime_error(f.str());\n        }\n        return high;\n    }\n\n    template<typename InIt>\n    typename iterator_value<InIt>::type \n    find_scale_to_finite_sum(InIt b,InIt e){\n        typedef typename iterator_value<InIt>::type val_;\n        typedef numeric::bounds<val_>               bounds_;\n        typedef std::vector<val_>                   vec_;\n        static val_ zero = static_cast<val_>(0);\n        static val_ one = static_cast<val_>(1);\n        static val_ two = static_cast<val_>(2);\n        static val_ highest = bounds_::highest();\n        vec_ vec;\n        maximal_finite_sums(b,e,std::back_inserter(vec));\n        val_ low = one;\n        val_ high = highest;\n        val_ mid = find_scale_to_finite_sum(\n            boost::begin(vec),\n            boost::end(vec),\n            low,high\n        );\n        low = mid;\n        high = mid;\n        while( \n            !boost::math::isinf(\n                std::accumulate(b,e,zero, lambda::_1 + ( lambda::_2 / low) )\n            )\n        ){\n            low /= two;\n            if(low<one){\n                low = one;\n                break;\n            }\n        }\n        while( \n            boost::math::isinf(\n                std::accumulate(b,e,zero, lambda::_1 + ( lambda::_2 / high) )\n            )\n        ){\n            high *= two;\n            if(boost::math::isinf(high)){\n                high = highest;\n                break;\n            }\n        }\n        return find_scale_to_finite_sum(b,e,low,high);\n    }\n\n}// importance_weights\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "92423f0daa6b43d25ab3ef85f0daed13ecf33a08", "size": 4867, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "importance_sampling/boost/statistics/detail/importance_sampling/weights/find_scale_to_finite_sum.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": "importance_sampling/boost/statistics/detail/importance_sampling/weights/find_scale_to_finite_sum.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": "importance_sampling/boost/statistics/detail/importance_sampling/weights/find_scale_to_finite_sum.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.034965035, "max_line_length": 96, "alphanum_fraction": 0.546332443, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5472518109519808}}
{"text": "#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <iostream>\n#include <memory>\n#include <sstream>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\nusing Registers = std::unordered_map<std::string, int>;\n\nRegisters reg;\nint mm = 0;\n\nint& getReg(const std::string& name) {\n    return reg.insert({name, 0}).first->second;\n}\n\nbool eval_cond(const std::vector<std::string>& words)\n{\n    if (words[3] == \"if\") {\n        int& r = getReg(words[4]);\n        int val = stoi(words[6]);\n        std::cout << \", CR: \" << words[4] << \", op: \" << words[5] << \", val: \" << val;\n        if (words[5] == \"==\") {\n            return r == val;\n        } else if (words[5] == \">=\") {\n            return r >= val;\n        } else if (words[5] == \"<=\") {\n            return r <= val;\n        } else if (words[5] == \"!=\") {\n            return r != val;\n        } else if (words[5] == \">\") {\n            return r > val;\n        } else if (words[5] == \"<\") {\n            return r < val;\n        } else {\n            std::cerr << \"UNKNOWN CONDITIONAL OP: \" << words[5] << \"\\n\";\n            exit(1);\n        }\n    } else {\n        std::cerr << \"UNKNOWN CONDITIONAL: \" << words[3] << \"\\n\";\n        exit(1);\n    }\n}\n\nint main()\n{\n    std::string line;\n    while (std::getline(std::cin, line)) {\n        if (line.empty()) {\n            break;\n        }\n        std::vector<std::string> words;\n        boost::algorithm::split(\n            words, line, boost::is_any_of(\" \"), boost::algorithm::token_compress_on);\n\n        int& r = getReg(words[0]);\n        int val = stoi(words[2]);\n\n        std::cout << \"R: \" << words[0] << \", op: \" << words[1] << \", val: \" << val;\n        if (words.size() > 3 && !eval_cond(words)) {\n            std::cout << \" skip\\n\";\n            continue;\n        }\n\n        if (words[1] == \"inc\") {\n            std::cout << \", INC\\n\";\n            r += val;\n        } else if (words[1] == \"dec\") {\n            std::cout << \", DEC\\n\";\n            r -= val;\n        } else {\n            std::cerr << \"UNKNOWN OP: \" << words[1] << \"\\n\";\n            exit(1);\n        }\n        mm = std::max(mm, r);\n    }\n\n    auto m = std::max_element(\n        reg.begin(), reg.end(), [](const Registers::value_type& a, const Registers::value_type& b) {\n            return std::less<int>()(a.second, b.second);\n        });\n\n    std::cout << \"max: \" << m->second << \", mm: \" << mm << \"\\n\";\n    return 0;\n}\n", "meta": {"hexsha": "6a89478a6aeec1dcc6c7b384167d2c1a3bce586f", "size": 2450, "ext": "cc", "lang": "C++", "max_stars_repo_path": "puzzle_08_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_08_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_08_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": 27.8409090909, "max_line_length": 100, "alphanum_fraction": 0.4571428571, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426301, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5472517960676212}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_BETA_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_BETA_RNG_HPP\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_less_or_equal.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/fun/log1m.hpp>\n#include <stan/math/prim/scal/fun/multiply_log.hpp>\n#include <stan/math/prim/scal/fun/log_sum_exp.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/fun/digamma.hpp>\n#include <stan/math/prim/scal/fun/lgamma.hpp>\n#include <stan/math/prim/scal/fun/lbeta.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/scal/fun/grad_reg_inc_beta.hpp>\n#include <stan/math/prim/scal/fun/inc_beta.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Return a pseudorandom Beta variate with the supplied success and failure\n     * parameters and specified random number generator.\n     *\n     * @tparam RNG class of random number generator\n     * @param alpha positive finite success parameter\n     * @param beta positive finite failure parameter\n     * @param rng random number generator\n     * @return Beta random variate\n     * @throw std::domain_error if alpha or beta is nonpositive\n     */\n    template <class RNG>\n    inline double\n    beta_rng(double alpha,\n             double beta,\n             RNG& rng) {\n      using boost::variate_generator;\n      using boost::random::gamma_distribution;\n      using boost::random::uniform_real_distribution;\n      using std::log;\n      using std::exp;\n      static const char* function(\"beta_rng\");\n      check_positive_finite(function, \"First shape parameter\", alpha);\n      check_positive_finite(function, \"Second shape parameter\", beta);\n\n      // If alpha and beta are large, trust the usual ratio of gammas\n      // method for generating beta random variables. If any parameter\n      // is small, work in log space and use Marsaglia and Tsang's trick\n      if (alpha > 1.0 && beta > 1.0) {\n        variate_generator<RNG&, gamma_distribution<> >\n          rng_gamma_alpha(rng, gamma_distribution<>(alpha, 1.0));\n        variate_generator<RNG&, gamma_distribution<> >\n          rng_gamma_beta(rng, gamma_distribution<>(beta, 1.0));\n        double a = rng_gamma_alpha();\n        double b = rng_gamma_beta();\n        return a / (a + b);\n      } else {\n        variate_generator<RNG&, uniform_real_distribution<> >\n          uniform_rng(rng, uniform_real_distribution<>(0.0, 1.0));\n        variate_generator<RNG&, gamma_distribution<> >\n          rng_gamma_alpha(rng, gamma_distribution<>(alpha + 1, 1.0));\n        variate_generator<RNG&, gamma_distribution<> >\n          rng_gamma_beta(rng, gamma_distribution<>(beta + 1, 1.0));\n        double log_a = log(uniform_rng()) / alpha + log(rng_gamma_alpha());\n        double log_b = log(uniform_rng()) / beta + log(rng_gamma_beta());\n        double log_sum = log_sum_exp(log_a, log_b);\n        return exp(log_a - log_sum);\n      }\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "c37df527b21aee90b6a8c3e888953c42132406d1", "size": 3373, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/beta_rng.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/beta_rng.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/beta_rng.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6419753086, "max_line_length": 79, "alphanum_fraction": 0.7008597688, "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5472391391956419}}
{"text": "#include \"RenderMesh.h\"\r\n\r\n#include <boost/test/unit_test.hpp>\r\n#include <Eigen/Geometry>\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\nBOOST_AUTO_TEST_CASE(RenderMesh_Transform_Identity)\r\n{\r\n\tBOOST_CHECK_EQUAL\r\n\t\t( ::Transform(Matrix4f::Identity(), Vector3f(1.0f, 2.0f, 3.0f))\r\n\t\t, Vector3f(1.0f, 2.0f, 3.0f)\r\n\t\t);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RenderMesh_Tranform_Scale)\r\n{\r\n\tBOOST_CHECK_EQUAL\r\n\t\t( ::Transform(Affine3f(Translation3f(4.0f, 5.0f, 6.0f)).matrix(), Vector3f(1.0f, 2.0f, 3.0f))\r\n\t\t, Vector3f(5.0f, 7.0f, 9.0f)\r\n\t\t);\r\n}", "meta": {"hexsha": "319b3c07c2bf577a7fab08778d422b861480a9e1", "size": 535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "render/RenderTest/TestRenderMesh.cpp", "max_stars_repo_name": "don-reba/colors-visualization", "max_stars_repo_head_hexsha": "fe3937087be79715307127591a06f38b4647254f", "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": "render/RenderTest/TestRenderMesh.cpp", "max_issues_repo_name": "don-reba/colors-visualization", "max_issues_repo_head_hexsha": "fe3937087be79715307127591a06f38b4647254f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "render/RenderTest/TestRenderMesh.cpp", "max_forks_repo_name": "don-reba/colors-visualization", "max_forks_repo_head_hexsha": "fe3937087be79715307127591a06f38b4647254f", "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.2608695652, "max_line_length": 96, "alphanum_fraction": 0.6878504673, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5472391336247738}}
{"text": "#include <sstream>\n#include <string>\n#include <set>\n#include <exception>\n#include <iostream>\n\n// Boost property tree\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/foreach.hpp>\n\n// Boost program options\n#include \"boost/program_options.hpp\"\n\n// Boost.Geometry\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/segment.hpp>\n#include <boost/geometry/algorithms/intersection.hpp>\n#include <boost/geometry/geometries/register/segment.hpp>\n\nusing namespace boost::geometry;\nnamespace pt = boost::property_tree;\n\ntypedef model::d2::point_xy<double> Point;\ntypedef model::polygon<Point, false, false> Polygon;\ntypedef model::segment<Point> Segment;\n\nPolygon operator+(\n  const Polygon& poly,\n  const Point& offset)\n{\n  Polygon result;\n  result.outer().reserve(poly.outer().size());\n  for (auto&& p : poly.outer()) {\n    append(result, Point(p.x() + offset.x(), p.y() + offset.y()));\n  }\n  return result;\n}\n\ndouble run(\n  const std::string& sceneFile,\n  const std::string& outputFile)\n{\n  // Declare a stream and an SVG mapper\n  std::ofstream svg(outputFile);\n  boost::geometry::svg_mapper<Point> mapper(svg, 400, 400, \"width=\\\"400\\\" height=\\\"400\\\"\");\n\n  // Create empty property tree object\n  pt::ptree tree;\n\n  // Parse the JSON into the property tree.\n  pt::read_json(sceneFile, tree);\n\n  // read boundary\n  Polygon poly;\n  boost::geometry::read_wkt(tree.get<std::string>(\"boundary\"), poly);\n  mapper.add(poly);\n  mapper.map(poly, \"fill-opacity:1.0;fill:none;stroke:rgb(0,0,0);stroke-width:5\");\n\n  // read targets\n  std::vector<Polygon> objectPaths;\n  std::vector<double> objectVelocities;\n\n  for (auto& item : tree.get_child(\"targets\")) {\n    Polygon shape;\n    boost::geometry::read_wkt(item.second.get<std::string>(\"shape\"), shape);\n    Polygon path;\n    boost::geometry::read_wkt(item.second.get<std::string>(\"path\"), path);\n    double vel = item.second.get<double>(\"velocity\", 1.0);\n\n    mapper.map(shape + path.outer().front(), \"fill-opacity:1.0;fill:rgb(153,153,153)\");\n    mapper.map(path, \"fill-opacity:0.8;fill:none;stroke:rgb(0,0,255);stroke-width:2\");\n\n    if (path.outer().size() > 1) {\n      std::stringstream sstr;\n      sstr << vel << \" m/s\";\n      mapper.text(path.outer().front(), sstr.str(), \"fill:rgb(0,0,0);font-family:Arial;font-size:15px\");\n    }\n  }\n\n  // read obstacles\n  for (auto& item : tree.get_child(\"obstacles\")) {\n    Polygon shape;\n    boost::geometry::read_wkt(item.second.get<std::string>(\"shape\"), shape);\n    Polygon path;\n    boost::geometry::read_wkt(item.second.get<std::string>(\"path\"), path);\n    double vel = item.second.get<double>(\"velocity\", 1.0);\n\n    mapper.map(shape + path.outer().front(), \"fill-opacity:1.0;fill:rgb(80,80,80)\");\n    mapper.map(path, \"fill-opacity:0.8;fill:none;stroke:rgb(0,0,255);stroke-width:2\");\n\n    if (path.outer().size() > 1) {\n      std::stringstream sstr;\n      sstr << vel << \" m/s\";\n      mapper.text(path.outer().front(), sstr.str(), \"fill:rgb(0,0,0);font-family:Arial;font-size:15px\");\n    }\n  }\n\n  // read cameras\n  double cameraFoV = tree.get<double>(\"cameraFoV\") / 180 * M_PI;\n  for (auto& item : tree.get_child(\"cameras\")) {\n    Point pos;\n    boost::geometry::read_wkt(item.second.get<std::string>(\"pos\"), pos);\n    double angle = item.second.get<double>(\"angle\") / 180 * M_PI;\n    double maxVelocity = item.second.get<double>(\"maxVelocity\");\n    double maxAngularVelocity = item.second.get<double>(\"maxAngularVelocity\");\n\n    boost::geometry::model::linestring<Point> polyline;\n    const double length = 2;\n    append(polyline, Point(length * cos(angle - cameraFoV) + pos.x(), length * sin(angle - cameraFoV) + pos.y()));\n    append(polyline, pos);\n    append(polyline, Point(length * cos(angle + cameraFoV) + pos.x(), length * sin(angle + cameraFoV) + pos.y()));\n    mapper.map(pos, \"fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2\", 5);\n    mapper.map(polyline, \"fill-opacity:0.8;fill:none;stroke:rgb(153,204,0);stroke-width:2\");\n\n    std::stringstream sstr;\n    sstr << maxVelocity << \" m/s\\n\" << maxAngularVelocity << \" rad/s\";\n    mapper.text(pos, sstr.str(), \"fill:rgb(0,0,0);font-family:Arial;font-size:15px\");\n  }\n}\n\nint main(int argc, char** argv)\n{\n  namespace po = boost::program_options;\n  // Declare the supported options.\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n      (\"help\", \"produce help message\")\n      (\"scene,s\", po::value<std::string>()->required(), \"input file for scene\")\n      (\"output,o\", po::value<std::string>()->required(), \"output file\")\n  ;\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n\n  if (vm.count(\"help\")) {\n      std::cout << desc << std::endl;\n      return 1;\n  }\n\n  po::notify(vm);\n\n  run(\n    vm[\"scene\"].as<std::string>(),\n    vm[\"output\"].as<std::string>());\n\n  return 0;\n}\n", "meta": {"hexsha": "acb1e9a95c87ca1447125b42b471b01a7fbe02af", "size": 4916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "USC-ACTLab/coverage_benchmark", "max_stars_repo_head_hexsha": "3cfe1b81ae8856f7ae9966e25d5522bb1d36a8cd", "max_stars_repo_licenses": ["MIT"], "max_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": "USC-ACTLab/coverage_benchmark", "max_issues_repo_head_hexsha": "3cfe1b81ae8856f7ae9966e25d5522bb1d36a8cd", "max_issues_repo_licenses": ["MIT"], "max_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": "USC-ACTLab/coverage_benchmark", "max_forks_repo_head_hexsha": "3cfe1b81ae8856f7ae9966e25d5522bb1d36a8cd", "max_forks_repo_licenses": ["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.7733333333, "max_line_length": 114, "alphanum_fraction": 0.6615134255, "num_tokens": 1352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5472391281800922}}
{"text": "/*  Sirikata\n *  ExpIntegral.cpp\n *\n *  Copyright (c) 2010, Daniel Reiter Horn\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 *  * 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\n *    the documentation and/or other materials provided with the\n *    distribution.\n *  * Neither the name of Sirikata nor the names of its contributors may\n *    be used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * 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 <sirikata/core/util/Platform.hpp>\n#include \"ExpIntegral.hpp\"\n\n#ifndef SIRIKATA_BAD_BOOST_ERF\n#include <boost/math/special_functions/erf.hpp>\n#endif\n\n#include <iostream>\n#include <string.h>\n\nstatic double square(double x) {\n    return x*x;\n}\n\nstatic double expFunction(double k,double x, double y, double u, double v) {\n    return exp(-k*(square(x-u)+square(y-v)));\n}\nstatic double myerf(double value) {\n#ifndef SIRIKATA_BAD_BOOST_ERF\n    return boost::math::erf(value);\n#else\n    return 0;\n#endif\n}\nstatic double integralExpFunction(double k, double xmin, double xmax, double ymin, double ymax, double umin, double umax, double vmin, double vmax) {\n    double e=2.7182818284590451;\n    double j=xmin;\n    double l=xmax;\n    double m=ymin;\n    double n=ymax;\n    double p=umin;\n    double q=umax;\n    double r=vmin;\n    double s=vmax;\n    double pi=3.1415926535897931;\n    double sqrtloge=1;\n    double loge=1;\n    return (1./(4*k*log(e)))\n        *pi*(  ( j - p)*myerf(sqrt(k)*(j - p)*sqrtloge)\n             + (-l + p)*myerf(sqrt(k)*(l - p)*sqrtloge)\n             + (-j + q)*myerf(sqrt(k)*(j - q)*sqrtloge)\n             + ( l - q)*myerf(sqrt(k)*(l - q)*sqrtloge)\n               + (exp(-k*square(j - p))\n                  - exp(-k*square(j - q)))/(sqrt(k)*sqrt(pi)*sqrtloge) +\n               (-exp(-k*square(l - p)) + exp(-k*square(l - q)))/(sqrt(k)*sqrt(pi)*sqrtloge))\n        *(  ( m - r)*myerf(sqrt(k)*(m - r)*sqrtloge)\n            + (-n + r)*myerf(sqrt(k)*(n - r)*sqrtloge)\n            + (-m + s)*myerf(sqrt(k)*(m - s)*sqrtloge)\n            + ( n - s)*myerf(sqrt(k)*(n - s)*sqrtloge)\n            + (exp(-k*square(m - r)) - exp(-k*square(m - s)))/(sqrt(k)*sqrt(pi)*sqrtloge)\n            + (-exp(-k*square(n - r)) + exp(-k*square(n - s)))/(sqrt(k)*sqrt(pi)*sqrtloge));\n}\nnamespace Sirikata {\ndouble integralExpFunction(double k, const Vector3d& xymin, const Vector3d& xymax, const Vector3d& uvmin, const Vector3d& uvmax){\n    return ::integralExpFunction(k,xymin.x,xymax.x,xymin.y,xymax.y,uvmin.x,uvmax.x,uvmin.y,uvmax.y);\n}\n}\nint maino (int argc, char**argv) {\n    float k=atof(argv[1]);\n\n    float xmin=-1;\n    float xmax= 1;\n    float ymin=-1;\n    float ymax= 1;\n    float arg=atof(argv[2]);\n    float umin=-arg;\n    float umax= arg;\n    float vmin=-arg;\n    float vmax= arg;\n\n    std::cout << \" Function evaluated at hundred: \"<<\n        expFunction(1,100,100,100,100)<<\n        \" Integration of function over a lot \"<<integralExpFunction(k,\n                                xmin,\n                                xmax,\n                                ymin,\n                                ymax,\n                                umin,\n                                umax,\n                                vmin,\n                                vmax);\n    return 0;\n}\n", "meta": {"hexsha": "66e6a06be535aa41e4c159ec5192a07bc0e031d9", "size": 4393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libcore/plugins/weightexp/ExpIntegral.cpp", "max_stars_repo_name": "sirikata/sirikata", "max_stars_repo_head_hexsha": "3a0d54a8c4778ad6e25ef031d461b2bc3e264860", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-01-28T17:01:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T08:30:37.000Z", "max_issues_repo_path": "libcore/plugins/weightexp/ExpIntegral.cpp", "max_issues_repo_name": "sirikata/sirikata", "max_issues_repo_head_hexsha": "3a0d54a8c4778ad6e25ef031d461b2bc3e264860", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libcore/plugins/weightexp/ExpIntegral.cpp", "max_forks_repo_name": "sirikata/sirikata", "max_forks_repo_head_hexsha": "3a0d54a8c4778ad6e25ef031d461b2bc3e264860", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-08-02T18:39:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-11T10:32:30.000Z", "avg_line_length": 37.8706896552, "max_line_length": 149, "alphanum_fraction": 0.6191668564, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5472391281800922}}
{"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_ARCH_COMMON_DETAIL_SIMD_F_INVTRIG_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_SIMD_F_INVTRIG_HPP_INCLUDED\n\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/function/logical_and.hpp>\n#include <boost/simd/constant/constant.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/mhalf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/pio_2.hpp>\n#include <boost/simd/detail/constant/pio_2lo.hpp>\n#include <boost/simd/constant/pio_3.hpp>\n#include <boost/simd/constant/pio_4.hpp>\n#include <boost/simd/detail/constant/pio_4lo.hpp>\n#include <boost/simd/constant/tan_3pio_8.hpp>\n#include <boost/simd/constant/tanpio_8.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/twopio_3.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/bitofsign.hpp>\n#include <boost/simd/function/bitwise_xor.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/ifnot_plus.hpp>\n#include <boost/simd/function/if_plus.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_inf.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/oneminus.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/sqrt.hpp>\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    namespace bd =  boost::dispatch;\n    namespace bs =  boost::simd;\n\n  template < class A0 >\n  struct invtrig_base<A0,tag::radian_tag,tag::simd_type, float>\n  {\n    static BOOST_FORCEINLINE A0 asin(A0 const& a0)\n    {\n      A0 sgn, x;\n      x = bs::abs(a0);\n      sgn = bs::bitofsign(a0);\n      const auto x_larger_05 = x > bs::Half<A0>();\n      A0 z = if_else(x_larger_05, bs::Half<A0>()*bs::oneminus(x), bs::sqr(x));\n      x = if_else(x_larger_05, sqrt(z), x);\n      // Remez polynomial of degree 4 for (asin(rx)-rx)/(rx*rx*rx) in [0, 0.25]\n      // 2120752146 values (99.53%) within 0.0 ULPs\n      //    9954286 values (0.47%)  within 0.5 ULPs\n      // 4.0 cycles/element SSE4.2 g++-4.8\n      A0 z1 = horn<A0,\n        0x3e2aaae4,\n        0x3d9980f6,\n        0x3d3a3ec7,\n        0x3cc617e3,\n        0x3d2cb352\n        > (z);\n      z1 = bs::fma(z1, z*x, x);\n      z = if_else(x_larger_05, bs::Pio_2<A0>()-(z1+z1), z1);\n      return bs::bitwise_xor(z, sgn);\n    }\n\n    static BOOST_FORCEINLINE A0 acos(const A0& a0)\n    {\n      // 2130706432 values computed.\n      // 1968272987 values (92.38%) within 0.0 ULPs\n      //  162433445 values (7.62%)  within 0.5 ULPs\n      // 8.5 cycles/element SSE4.2 g++-4.8\n      A0 x = bs::abs(a0);\n      auto x_larger_05 = is_greater(x, bs::Half<A0>());\n      x  = if_else(x_larger_05, bs::sqrt(fma(bs::Mhalf<A0>(), x, bs::Half<A0>())), a0);\n      x  = asin(x);\n      x =  if_plus(x_larger_05, x, x);\n      x  = bs::if_else(a0 < bs::Mhalf<A0>(), bs::Pi<A0>()-x, x);\n      return bs::if_else(x_larger_05, x, bs::Pio_2<A0>()-x);\n    }\n\n    static BOOST_FORCEINLINE A0 atan(const A0& a0)\n    {\n      A0 absa0 =  bs::abs(a0);\n      const A0 x  = kernel_atan(absa0, bs::rec(absa0));\n      return bs::bitwise_xor(x, bs::bitofsign(a0));\n    }\n\n    static BOOST_FORCEINLINE A0 acot(const A0& a0)\n    {\n      A0 absa0 =  bs::abs(a0);\n      const A0 x  = kernel_atan(bs::rec(absa0), absa0);\n      return bs::bitwise_xor(x, bs::bitofsign(a0));\n    }\n\n    static BOOST_FORCEINLINE A0 kernel_atan(const A0&  x, const A0& recx)\n    {\n      //4278190076 values computed  in range: [-3.40282e+38, 3.40282e+38]\n      //4257598358 values (99.52%)  within 0.0 ULPs\n      //  20591718 values (0.48%)   within 0.5 ULPs\n\n      //here x is positive\n      const auto flag1 = x < Tan_3pio_8<A0>();\n      const auto flag2 = bs::logical_and(x >= Constant<A0, 0x3ed413cd>(), flag1);\n      A0 yy =  bs::if_zero_else(flag1, Pio_2<A0>());\n      yy =  bs::if_else(flag2, Pio_4<A0>(), yy);\n      A0 xx =   bs::if_else(flag1, x, -recx);\n      xx =  bs::if_else(flag2, (bs::dec(x)/bs::inc(x)),xx);\n      const A0 z = bs::sqr(xx);\n      A0 z1 = horn<A0\n        , 0xbeaaaa2aul  // -3.3333293e-01\n        , 0x3e4c925ful  //  1.9991724e-01\n        , 0xbe0e1b85ul  // -1.4031009e-01\n        , 0x3da4f0d1ul  //  8.5460119e-02\n        > (z);\n      z1 = bs::fma(xx, bs::multiplies( z1, z), xx);\n      z1 = if_plus(flag2, z1, Pio_4lo<A0>());\n      z1 = ifnot_plus(flag1, z1, Pio_2lo<A0>());\n      return yy+z1;\n    }\n  };\n}\n} }\n#endif\n", "meta": {"hexsha": "8eed1b1439bc8378a291ceaf6b0492c2d9b0bec6", "size": 4958, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/detail/simd/f_invtrig.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/arch/common/detail/simd/f_invtrig.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/arch/common/detail/simd/f_invtrig.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": 35.6690647482, "max_line_length": 100, "alphanum_fraction": 0.6151674062, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5472331173047907}}
{"text": "#include \"vtkReferenceFrameFilter.h\"\n#include <vtkImageData.h>\n#include <vtkObjectFactory.h>\n#include <vtkStreamingDemandDrivenPipeline.h>\n#include <vtkInformationVector.h>\n#include <vtkInformation.h>\n#include <vtkDataObject.h>\n#include <vtkSmartPointer.h>\n#include <vtkPointData.h>\n#include <vtkDataArray.h>\n#include <vtkVector.h>\n#include <Eigen\\Core>\n#include <Eigen\\StdVector>\n#include <Eigen\\QR>\n#include <vector>\n#include <vtkFloatArray.h>\n\nvtkStandardNewMacro(vtkReferenceFrameFilter);\n\n// Creates a 2x2 matrix from 2 column vectors\nstatic Eigen::Matrix2d make_Matrix2d(const Eigen::Vector2d& c0, const Eigen::Vector2d& c1)\n{\n\tEigen::Matrix2d M;\n\tM << c0.x(), c1.x(), c0.y(), c1.y();\n\treturn M;\n}\n\n// Create a 2x2 matrix from row-wise components\nstatic Eigen::Matrix2d make_Matrix2d(const double& m00, const double& m01, const double& m10, const double& m11)\n{\n\tEigen::Matrix2d M;\n\tM << m00, m01, m10, m11;\n\treturn M;\n}\n\n// Returns value of Binomial Coefficient C(n, k) \nstatic int binomialCoeff(int n, int k)\n{\n\tint res = 1;\n\tif (k > n - k)\n\t\tk = n - k;\n\tfor (int i = 0; i < k; ++i) {\n\t\tres *= (n - i);\n\t\tres /= (i + 1);\n\t}\n\treturn res;\n}\n\nstatic int factorial(int n)\n{\n\tint ret = 1;\n\tfor (int i = 1; i <= n; ++i)\n\t\tret *= i;\n\treturn ret;\n}\n\nstatic void ComputeDisplacementSystemMatrixCoefficients(int i, int j, const Eigen::Vector2d& xx, const Eigen::Vector2d& vv, const Eigen::Matrix2d& J, Eigen::Matrix2d& f, Eigen::Matrix2d& g)\n{\n\tf = make_Matrix2d(0, 0, 0, 0), g = make_Matrix2d(0, 0, 0, 0);\n\tEigen::Matrix2d I = make_Matrix2d(1, 0, 0, 1);\n\tdouble x = xx.x(), y = xx.y(), u = vv.x(), v = vv.y();\n\n\tdouble x_i = pow(x, i), x_i1 = pow(x, i - 1);\n\tdouble y_j = pow(y, j), y_j1 = pow(y, j - 1);\n\n\tint fac_i = factorial(i), fac_i1 = factorial(i - 1);\n\tint fac_j = factorial(j), fac_j1 = factorial(j - 1);\n\n\tf -= x_i * y_j / (fac_i * fac_j) * J;\n\tif (i != 0)\n\t\tf += u * x_i1*y_j / (fac_i1 * fac_j) * I;\n\tif (j != 0)\n\t\tf += v * x_i*y_j1 / (fac_i * fac_j1) * I;\n\n\tg = x_i * y_j / (fac_i * fac_j) * I;\n}\n\nvtkReferenceFrameFilter::vtkReferenceFrameFilter() : NeighborhoodU(10), Invariance(AffineInvariance), UseSummedAreaTables(true), TaylorOrder(2),\nFieldNameV(NULL), FieldNameVx(NULL), FieldNameVy(NULL), FieldNameVt(NULL)\n{\n\tSetFieldNameV(\"v\");\n\tSetFieldNameVx(\"vx\");\n\tSetFieldNameVy(\"vy\");\n\tSetFieldNameVt(\"vt\");\n}\n\nint vtkReferenceFrameFilter::RequestData(vtkInformation *vtkNotUsed(request),\n\tvtkInformationVector **inputVector,\n\tvtkInformationVector *outputVector)\n{\n\tusing namespace Eigen;\n\n\t// Get the info objects\n\tvtkInformation *inInfo = inputVector[0]->GetInformationObject(0);\n\tvtkInformation *outInfo = outputVector->GetInformationObject(0);\n\n\t// Get the input and ouptut\n\tvtkImageData *input = vtkImageData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT()));\n\tvtkImageData *output = vtkImageData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n\t// Get the information on the domain\n\tint* dims = input->GetDimensions();\n\tdouble* spacing = input->GetSpacing();\n\tdouble* boundsMin = input->GetOrigin();\n\n\t// select the system matrix size depending on the chosen invariance\n\tint systemSize = 6;\n\tswitch (Invariance) {\n\tdefault:\n\tcase Objectivity:\t\t\tsystemSize = 6;\t\tbreak;\n\tcase SimilarityInvariance:\tsystemSize = 8;\t\tbreak;\n\tcase AffineInvariance:\t\tsystemSize = 12;\tbreak;\n\tcase Displacement:\t\t\tsystemSize = 2 * TaylorOrder*TaylorOrder + TaylorOrder * 6 + 4; break;\n\t}\n\n\t// read the input data and abort if data is not present!\n\tfloat* input_v = NULL, *input_vx = NULL, *input_vy = NULL, *input_vt = NULL;\n\tif (vtkFloatArray::SafeDownCast(input->GetPointData()->GetArray(FieldNameV)) && input->GetPointData()->GetArray(FieldNameV)->GetNumberOfComponents() == 2)\n\t\tinput_v = vtkFloatArray::SafeDownCast(input->GetPointData()->GetArray(FieldNameV))->GetPointer(0);\n\telse { cout << \"Field \" << FieldNameV << \" was not found or does not have 2 components!\" << endl; return 0; }\n\n\tif (vtkFloatArray::SafeDownCast(input->GetPointData()->GetArray(FieldNameVx)) && input->GetPointData()->GetArray(FieldNameVx)->GetNumberOfComponents() == 2)\n\t\tinput_vx = vtkFloatArray::SafeDownCast(input->GetPointData()->GetArray(FieldNameVx))->GetPointer(0);\n\telse { cout << \"Field \" << FieldNameVx << \" was not found or does not have 2 components!\" << endl; return 0; }\n\n\tif (vtkFloatArray::SafeDownCast(input->GetPointData()->GetArray(FieldNameVy)) && input->GetPointData()->GetArray(FieldNameVy)->GetNumberOfComponents() == 2)\n\t\tinput_vy = vtkFloatArray::SafeDownCast(input->GetPointData()->GetArray(FieldNameVy))->GetPointer(0);\n\telse { cout << \"Field \" << FieldNameVy << \" was not found or does not have 2 components!\" << endl; return 0; }\n\n\tif (vtkFloatArray::SafeDownCast(input->GetPointData()->GetArray(FieldNameVt)) && input->GetPointData()->GetArray(FieldNameVt)->GetNumberOfComponents() == 2)\n\t\tinput_vt = vtkFloatArray::SafeDownCast(input->GetPointData()->GetArray(FieldNameVt))->GetPointer(0);\n\telse { cout << \"Field \" << FieldNameVt << \" was not found or does not have 2 components!\" << endl; return 0; }\n\n\t// Create an image to write the result to and copy the input into it (just for initialization)\n\tvtkSmartPointer<vtkImageData> image = vtkSmartPointer<vtkImageData>::New();\n\timage->DeepCopy(input);\n\n\tvtkDataArray* output_v = image->GetPointData()->GetArray(FieldNameV);\n\tvtkDataArray* output_vx = image->GetPointData()->GetArray(FieldNameVx);\n\tvtkDataArray* output_vy = image->GetPointData()->GetArray(FieldNameVy);\n\tvtkDataArray* output_vt = image->GetPointData()->GetArray(FieldNameVt);\n\n\t// Iterate the time steps (in parallel)\n#ifdef NDEBUG\n#pragma omp parallel for schedule(dynamic,16)\n#endif\n\tfor (int it = 0; it < dims[2]; it++)\n\t{\n\t\t// declare matrices for every voxel of a slice\n\t\tstd::vector<MatrixXd, aligned_allocator<MatrixXd> > _M(dims[0] * dims[1]);\n\t\tstd::vector<MatrixXd, aligned_allocator<MatrixXd> > _MTM(dims[0] * dims[1]);\n\t\tstd::vector<MatrixXd, aligned_allocator<MatrixXd> > _MTb(dims[0] * dims[1]);\n\n\t\t// setup the system matrix M and right hand side.\n\t\tfor (int iy = 0; iy < dims[1]; iy++)\n\t\t{\n\t\t\tdouble y = boundsMin[1] + iy * spacing[1];\n\t\t\tfor (int ix = 0; ix < dims[0]; ix++)\n\t\t\t{\n\t\t\t\tdouble x = boundsMin[0] + ix * spacing[0];\n\t\t\t\tint tupleIdx = it * dims[0] * dims[1] + iy * dims[0] + ix;\n\n\t\t\t\t// position, velocity and derivatives at the voxel\n\t\t\t\tVector2d xx(x, y);\n\t\t\t\tVector2d vv(input_v[tupleIdx * 2 + 0], input_v[tupleIdx * 2 + 1]);\n\t\t\t\tVector2d dx(input_vx[tupleIdx * 2 + 0], input_vx[tupleIdx * 2 + 1]);\n\t\t\t\tVector2d dy(input_vy[tupleIdx * 2 + 0], input_vy[tupleIdx * 2 + 1]);\n\t\t\t\tVector2d dt(input_vt[tupleIdx * 2 + 0], input_vt[tupleIdx * 2 + 1]);\n\n\t\t\t\t// compute 90 degree rotated vectors, setup Jacobian and compute products\n\t\t\t\tVector2d Xp(-xx.y(), xx.x());\n\t\t\t\tVector2d Vp(-vv.y(), vv.x());\n\t\t\t\tMatrix2d J = make_Matrix2d(dx, dy);\n\t\t\t\tVector2d Jxpvp = -J * Xp + Vp;\n\t\t\t\tVector2d Jxv = -J * xx + vv;\n\n\t\t\t\t// setup matrix M\n\t\t\t\tMatrixXd M(2, systemSize);\n\t\t\t\tswitch (Invariance)\n\t\t\t\t{\n\t\t\t\tdefault:\n\t\t\t\tcase Objectivity:\n\t\t\t\t\tM(0, 0) = Jxpvp.x(); \t M(0, 1) = dx.x(); M(0, 2) = dy.x();   M(0, 3) = 1; M(0, 4) = 0;   M(0, 5) = Xp.x();\n\t\t\t\t\tM(1, 0) = Jxpvp.y(); \t M(1, 1) = dx.y(); M(1, 2) = dy.y();   M(1, 3) = 0; M(1, 4) = 1;   M(1, 5) = Xp.y();\n\t\t\t\t\tbreak;\n\t\t\t\tcase SimilarityInvariance:\n\t\t\t\t\tM(0, 0) = Jxpvp.x(); \t M(0, 1) = dx.x(); M(0, 2) = dy.x();   M(0, 3) = 1; M(0, 4) = 0;   M(0, 5) = Xp.x(); M(0, 6) = Jxv.x(); M(0, 7) = xx.x();\n\t\t\t\t\tM(1, 0) = Jxpvp.y(); \t M(1, 1) = dx.y(); M(1, 2) = dy.y();   M(1, 3) = 0; M(1, 4) = 1;   M(1, 5) = Xp.y(); M(1, 6) = Jxv.y();\tM(1, 7) = xx.y();\n\t\t\t\t\tbreak;\n\t\t\t\tcase AffineInvariance:\n\t\t\t\t\tM(0, 0) = vv.x() - xx.x() * J(0, 0);\tM(0, 1) = 0 - xx.x() * J(0, 1);\t/**/  M(0, 2) = vv.y() - xx.y() * J(0, 0);  M(0, 3) = 0 - xx.y() * J(0, 1);  /**/  M(0, 4) = J(0, 0);  M(0, 5) = J(0, 1);  /**/  M(0, 6) = 1;  M(0, 7) = 0;  /**/  M(0, 8) = xx.x();  M(0, 9) = 0;       /**/  M(0, 10) = xx.y();  M(0, 11) = 0;\n\t\t\t\t\tM(1, 0) = 0 - xx.x() * J(1, 0);\tM(1, 1) = vv.x() - xx.x() * J(1, 1);\t/**/  M(1, 2) = 0 - xx.y() * J(1, 0);  M(1, 3) = vv.y() - xx.y() * J(1, 1);  /**/  M(1, 4) = J(1, 0);  M(1, 5) = J(1, 1);  /**/  M(1, 6) = 0;\tM(1, 7) = 1; /**/  M(1, 8) = 0;       M(1, 9) = xx.x();  /**/  M(1, 10) = 0;       M(1, 11) = xx.y();\n\t\t\t\t\tbreak;\n\t\t\t\tcase Displacement:\n\t\t\t\t{\n\t\t\t\t\tint index = 0;\n\t\t\t\t\tfor (int m = 0; m <= TaylorOrder; ++m)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int i = m; i >= 0; --i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint j = m - i;\n\t\t\t\t\t\t\tMatrix2d f, g;\n\t\t\t\t\t\t\tComputeDisplacementSystemMatrixCoefficients(i, j, xx, vv, J, f, g);\n\t\t\t\t\t\t\tM(0, index * 4 + 0) = f(0, 0);\t\tM(1, index * 4 + 0) = f(1, 0);\n\t\t\t\t\t\t\tM(0, index * 4 + 1) = f(0, 1);\t\tM(1, index * 4 + 1) = f(1, 1);\n\n\t\t\t\t\t\t\tM(0, index * 4 + 2) = g(0, 0);\t\tM(1, index * 4 + 2) = g(1, 0);\n\t\t\t\t\t\t\tM(0, index * 4 + 3) = g(0, 1);\t\tM(1, index * 4 + 3) = g(1, 1);\n\t\t\t\t\t\t\tindex += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// store MTM and MTb\n\t\t\t\tMatrixXd MT = M.transpose();\n\t\t\t\t_M[iy*dims[0] + ix] = M;\n\t\t\t\t_MTM[iy*dims[0] + ix] = MT * M;\n\t\t\t\t_MTb[iy*dims[0] + ix] = MT * dt * ((Invariance == Displacement) ? -1 : 1);\n\t\t\t}\n\t\t}\n\n\t\t// compute the prefix sum\n\t\tif (UseSummedAreaTables)\n\t\t{\n\t\t\tfor (int iy = 0; iy < dims[1]; iy++)\n\t\t\t\tfor (int ix = 0; ix < dims[0]; ix++)\n\t\t\t\t{\n\t\t\t\t\tif (ix > 0) {\n\t\t\t\t\t\t_MTM[iy*dims[0] + ix] += _MTM[iy*dims[0] + (ix - 1)];\n\t\t\t\t\t\t_MTb[iy*dims[0] + ix] += _MTb[iy*dims[0] + (ix - 1)];\n\t\t\t\t\t}\n\t\t\t\t\tif (iy > 0) {\n\t\t\t\t\t\t_MTM[iy*dims[0] + ix] += _MTM[(iy - 1)*dims[0] + ix];\n\t\t\t\t\t\t_MTb[iy*dims[0] + ix] += _MTb[(iy - 1)*dims[0] + ix];\n\t\t\t\t\t}\n\t\t\t\t\tif (ix > 0 && iy > 0) {\n\t\t\t\t\t\t_MTM[iy*dims[0] + ix] -= _MTM[(iy - 1)*dims[0] + (ix - 1)];\n\t\t\t\t\t\t_MTb[iy*dims[0] + ix] -= _MTb[(iy - 1)*dims[0] + (ix - 1)];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\n\t\t// solve the system for each pixel\n\t\tfor (int iy = 0; iy < dims[1]; iy++)\n\t\t{\n\t\t\tdouble y = boundsMin[1] + iy * spacing[1];\n\t\t\tfor (int ix = 0; ix < dims[0]; ix++)\n\t\t\t{\n\t\t\t\tdouble x = boundsMin[0] + ix * spacing[0];\n\t\t\t\tint tupleIdx = it * dims[0] * dims[1] + iy * dims[0] + ix;\n\n\t\t\t\t// corner indices of the neighborhood region\n\t\t\t\tint x1 = std::min(std::max(0, ix - NeighborhoodU - 1), dims[0] - 1);\n\t\t\t\tint y1 = std::min(std::max(0, iy - NeighborhoodU - 1), dims[1] - 1);\n\t\t\t\tint x2 = std::min(std::max(0, ix + NeighborhoodU), dims[0] - 1);\n\t\t\t\tint y2 = std::min(std::max(0, iy + NeighborhoodU), dims[1] - 1);\n\n\t\t\t\t// compute the sum of all matrices/vectors in neighborhood region\n\t\t\t\tMatrixXd MTM(systemSize, systemSize);\n\t\t\t\tMTM.setZero();\n\t\t\t\tVectorXd MTb(systemSize, 1);\n\t\t\t\tMTb.setZero();\n\n\t\t\t\tif (UseSummedAreaTables)\n\t\t\t\t{\n\t\t\t\t\tMTM = _MTM[y2*dims[0] + x2] + _MTM[y1*dims[0] + x1] - _MTM[y1*dims[0] + x2] - _MTM[y2*dims[0] + x1];\n\t\t\t\t\tMTb = _MTb[y2*dims[0] + x2] + _MTb[y1*dims[0] + x1] - _MTb[y1*dims[0] + x2] - _MTb[y2*dims[0] + x1];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfor (int wy = y1; wy <= y2; ++wy)\n\t\t\t\t\t\tfor (int wx = x1; wx <= x2; ++wx)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tMTM += _MTM[wy*dims[0] + wx];\n\t\t\t\t\t\t\tMTb += _MTb[wy*dims[0] + wx];\n\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// solve for reference frame parameters\n\t\t\t\tVectorXd uu = MTM.fullPivHouseholderQr().solve(MTb);\n\n\t\t\t\t// compute new vector field in optimal frame\n\t\t\t\tVector2d xx(x, y);\n\t\t\t\tVector2d vv(input_v[tupleIdx * 2 + 0], input_v[tupleIdx * 2 + 1]);\n\t\t\t\tVector2d dx(input_vx[tupleIdx * 2 + 0], input_vx[tupleIdx * 2 + 1]);\n\t\t\t\tVector2d dy(input_vy[tupleIdx * 2 + 0], input_vy[tupleIdx * 2 + 1]);\n\t\t\t\tVector2d dt(input_vt[tupleIdx * 2 + 0], input_vt[tupleIdx * 2 + 1]);\n\t\t\t\tMatrix2d J = make_Matrix2d(dx, dy);\n\t\t\t\tVector2d vnew(0, 0);\n\t\t\t\tMatrix2d Jnew = make_Matrix2d(0, 0, 0, 0);\n\t\t\t\tVector2d Xp(-xx.y(), xx.x());\n\t\t\t\tswitch (Invariance)\n\t\t\t\t{\n\t\t\t\tcase Objectivity:\n\t\t\t\t\tvnew = vv + Vector2d(uu(1), uu(2)) - uu(0) * Xp;\n\t\t\t\t\tJnew = J + make_Matrix2d(0, uu(0), -uu(0), 0);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SimilarityInvariance:\n\t\t\t\t\tvnew = vv + Vector2d(uu(1), uu(2)) - uu(0) * Xp - uu(6) * xx;\n\t\t\t\t\tJnew = J + make_Matrix2d(0, uu(0), -uu(0), 0) - make_Matrix2d(uu(6), 0, 0, uu(6));\n\t\t\t\t\tbreak;\n\t\t\t\tcase AffineInvariance:\n\t\t\t\t{\n\t\t\t\t\tMatrix2d H1 = make_Matrix2d(-uu(0), -uu(2), -uu(1), -uu(3));\n\t\t\t\t\tVector2d k1(uu(4), uu(5));\n\t\t\t\t\tvnew = vv + H1 * xx + k1;\n\t\t\t\t\tJnew = J + H1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase Displacement:\n\t\t\t\t{\n\t\t\t\t\t// construct velocity\n\t\t\t\t\t{\n\t\t\t\t\t\tVector2d Ft(0, 0);\n\t\t\t\t\t\tint fac_m = 1;\n\t\t\t\t\t\tfor (int m = 0; m <= TaylorOrder; ++m)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (m > 1)\n\t\t\t\t\t\t\t\tfac_m *= m;\n\n\t\t\t\t\t\t\tVector2d Ftpart(0, 0);\n\t\t\t\t\t\t\tfor (int i = 0; i <= m; ++i)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint fu_i = i, fu_j = m - i;\n\t\t\t\t\t\t\t\t// general formular to get the linear index:  (i+j)*(i+j+1) + 2*j\n\t\t\t\t\t\t\t\tint linear_fu = (fu_i + fu_j)*(fu_i + fu_j + 1) + 2 * fu_j;\n\t\t\t\t\t\t\t\tdouble fu = uu(2 * linear_fu + 0);\n\t\t\t\t\t\t\t\tdouble fv = uu(2 * linear_fu + 1);\n\n\t\t\t\t\t\t\t\tint binom = binomialCoeff(m, i);\n\t\t\t\t\t\t\t\tFtpart += binom * pow(xx.x(), i) * pow(xx.y(), m - i) * Vector2d(fu, fv);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tFt += Ftpart / fac_m;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvnew = vv + Ft;\n\t\t\t\t\t}\n\t\t\t\t\t// construct Jacobian\n\t\t\t\t\t{\n\t\t\t\t\t\tMatrix2d nablaFt = make_Matrix2d(0, 0, 0, 0);\n\t\t\t\t\t\tint fac_m = 1;\n\t\t\t\t\t\tfor (int m = 1; m <= TaylorOrder; ++m)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tMatrix2d nablaFtpart = make_Matrix2d(0, 0, 0, 0);\n\t\t\t\t\t\t\tfor (int i = 0; i <= m - 1; ++i)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint fx_i = i + 1, fx_j = m - 1 - i;\n\t\t\t\t\t\t\t\tint fy_i = i, fy_j = m - i;\n\t\t\t\t\t\t\t\t// general formular to get the linear index:  (i+j)*(i+j+1) + 2*j\n\t\t\t\t\t\t\t\tint linear_fx = (fx_i + fx_j)*(fx_i + fx_j + 1) + 2 * fx_j;\n\t\t\t\t\t\t\t\tint linear_fy = (fy_i + fy_j)*(fy_i + fy_j + 1) + 2 * fy_j;\n\t\t\t\t\t\t\t\tdouble fxu = uu(2 * linear_fx + 0);\n\t\t\t\t\t\t\t\tdouble fxv = uu(2 * linear_fx + 1);\n\t\t\t\t\t\t\t\tdouble fyu = uu(2 * linear_fy + 0);\n\t\t\t\t\t\t\t\tdouble fyv = uu(2 * linear_fy + 1);\n\n\t\t\t\t\t\t\t\tint binom = binomialCoeff(m - 1, i);\n\t\t\t\t\t\t\t\tnablaFtpart += binom * pow(xx.x(), i) * pow(xx.y(), m - 1 - i) * make_Matrix2d(fxu, fyu, fxv, fyv);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnablaFt += nablaFtpart / fac_m;\n\n\t\t\t\t\t\t\tif (m > 1)\n\t\t\t\t\t\t\t\tfac_m *= m;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tJnew = J + nablaFt;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tVector2d vtnew = dt - _M[iy * dims[0] + ix] * uu * ((Invariance == Displacement) ? -1 : 1);\n\n\t\t\t\t// store the result\n\t\t\t\toutput_v->SetTuple2(tupleIdx, vnew.x(), vnew.y());\n\t\t\t\toutput_vx->SetTuple2(tupleIdx, Jnew(0, 0), Jnew(1, 0));\n\t\t\t\toutput_vy->SetTuple2(tupleIdx, Jnew(0, 1), Jnew(1, 1));\n\t\t\t\toutput_vt->SetTuple2(tupleIdx, vtnew.x(), vtnew.y());\n\t\t\t}\n\t\t}\n\t}\n\n\t// Copy the computed image to the output\n\toutput->ShallowCopy(image);\n\n\t// Update the extent\n\tint extent[6];\n\tinput->GetExtent(extent);\n\toutput->SetExtent(extent);\n\toutInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), extent, 6);\n\toutInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent, 6);\n\treturn 1;\n}", "meta": {"hexsha": "f8f2793812ea9f12aef2f29153f0f5bc42e168ec", "size": 14570, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vtkReferenceFrameFilter.cxx", "max_stars_repo_name": "tobguent/optimal-frames", "max_stars_repo_head_hexsha": "87a2796024d2ade7e381187f564b0bc89ae72660", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-09-06T02:21:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T14:26:22.000Z", "max_issues_repo_path": "vtkReferenceFrameFilter.cxx", "max_issues_repo_name": "tobguent/optimal-frames", "max_issues_repo_head_hexsha": "87a2796024d2ade7e381187f564b0bc89ae72660", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-14T01:57:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-14T13:17:01.000Z", "max_forks_repo_path": "vtkReferenceFrameFilter.cxx", "max_forks_repo_name": "tobguent/optimal-frames", "max_forks_repo_head_hexsha": "87a2796024d2ade7e381187f564b0bc89ae72660", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-07T11:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-03T16:21:38.000Z", "avg_line_length": 37.1683673469, "max_line_length": 317, "alphanum_fraction": 0.5790665752, "num_tokens": 5535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5472331030193338}}
{"text": "/*    Copyright (c) 2010-2018, 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 *    References\n *      van der Ham, L. Interplanetary trajectory design using dynamical systems theory,\n *          MSc thesis, Delft University of Technology, Delft, The Netherlands, 2012.\n *      Mireles James, J.D. Celestial Mechanics Notes Set 4: The Circular Restricted Three Body\n *          Problem, 2006, http://www.math.utexas.edu/users/jjames/hw4Notes.pdf,\n *          last accessed: 18th May, 2012.\n *\n *    Notes\n *      WARNING: There seems to be a bug in the computation of the L3 location!\n *\n */\n\n#include <cmath>\n#include <stdexcept>\n\n#include <boost/bind.hpp>\n\n#include \"Tudat/Astrodynamics/Gravitation/librationPoint.h\"\n#include \"Tudat/Mathematics/BasicMathematics/functionProxy.h\"\n\nnamespace tudat\n{\nnamespace gravitation\n{\nnamespace circular_restricted_three_body_problem\n{\n\nusing namespace root_finders;\nusing namespace basic_mathematics;\n\n//! Compute location of Lagrange libration point.\nvoid LibrationPoint::computeLocationOfLibrationPoint(\n        LagrangeLibrationPoints lagrangeLibrationPoint )\n{\n    using std::pow;\n    using std::sqrt;\n\n    // Set functions for Newton-Raphson based on collinear libration point passed as input\n    // parameter, or computed locations directly of equilateral libration points.\n    switch( lagrangeLibrationPoint )\n    {\n    case l1:\n    {\n        // Create an object containing the function of which we whish to obtain the root from.\n        UnivariateProxyPointer rootFunction = std::make_shared< UnivariateProxy >(\n                    std::bind( &LibrationPoint::computeL1LocationFunction, this, std::placeholders::_1 ) );\n\n        // Add the first derivative of the root function.\n        rootFunction->addBinding( -1, std::bind( &LibrationPoint::\n                computeL1FirstDerivativeLocationFunction, this, std::placeholders::_1 ) );\n\n        // Set position vector of L1 in Cartesian elements based on result of Newton-Raphson\n        // root-finding algorithm.\n        positionOfLibrationPoint_ << rootFinder->execute( rootFunction, 1.0 ), 0.0, 0.0;\n    }\n        break;\n\n    case l2:\n    {\n        // Create an object containing the function of which we whish to obtain the root from.\n        UnivariateProxyPointer rootFunction = std::make_shared< UnivariateProxy >(\n                    std::bind( &LibrationPoint::computeL2LocationFunction, this, std::placeholders::_1 ) );\n\n        // Add the first derivative of the root function.\n        rootFunction->addBinding( -1, std::bind( &LibrationPoint::\n                computeL2FirstDerivativeLocationFunction, this, std::placeholders::_1 ) );\n\n        // Set position vector of L1 in Cartesian elements based on result of Newton-Raphson\n        // root-finding algorithm.\n        positionOfLibrationPoint_ << rootFinder->execute( rootFunction, 1.0 ), 0.0, 0.0;\n    }\n        break;\n\n    case l3:\n    {\n        // Create an object containing the function of which we whish to obtain the root from.\n        UnivariateProxyPointer rootFunction = std::make_shared< UnivariateProxy >(\n                    std::bind( &LibrationPoint::computeL3LocationFunction, this, std::placeholders::_1 ) );\n\n        // Add the first derivative of the root function.\n        rootFunction->addBinding( -1, std::bind( &LibrationPoint::\n                computeL3FirstDerivativeLocationFunction, this, std::placeholders::_1 ) );\n\n        // Set position vector of L1 in Cartesian elements based on result of Newton-Raphson\n        // root-finding algorithm.\n        positionOfLibrationPoint_ << rootFinder->execute( rootFunction, -1.0 ), 0.0, 0.0;\n    }\n        break;\n\n    case l4:\n\n        // Set position vector of L4 in Cartesian elements.\n        positionOfLibrationPoint_.x( ) = 0.5 - massParameter;\n        positionOfLibrationPoint_.y( ) = 0.5 * sqrt( 3.0 );\n        positionOfLibrationPoint_.z( ) = 0.0;\n\n        break;\n\n    case l5:\n\n        // Set position vector of L5 in Cartesian elements.\n        positionOfLibrationPoint_.x( ) = 0.5 - massParameter;\n        positionOfLibrationPoint_.y( ) = -0.5 * sqrt( 3.0 );\n        positionOfLibrationPoint_.z( ) = 0.0;\n\n        break;\n\n    default:\n\n        throw std::runtime_error(\n                            \"The Lagrange libration point requested does not exist.\" );\n    };\n}\n\n} // namespace circular_restricted_three_body_problem\n} // namespace gravitation\n} // namespace tudat\n", "meta": {"hexsha": "4d653d638ad68e6dbe286e683fbb777e80bd09b4", "size": 4768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Gravitation/librationPoint.cpp", "max_stars_repo_name": "different91988/tudat", "max_stars_repo_head_hexsha": "97b287fe759979cf2028c9180f0abafa2487dde4", "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/librationPoint.cpp", "max_issues_repo_name": "different91988/tudat", "max_issues_repo_head_hexsha": "97b287fe759979cf2028c9180f0abafa2487dde4", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/librationPoint.cpp", "max_forks_repo_name": "different91988/tudat", "max_forks_repo_head_hexsha": "97b287fe759979cf2028c9180f0abafa2487dde4", "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.5433070866, "max_line_length": 107, "alphanum_fraction": 0.6753355705, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.5472331025306898}}
{"text": "#pragma once\n#include <vector>\n#include <set>\n#include <Eigen/Dense>\n#include <utility>\n#include <ostream>\n#include <map>\n#include <atomic>\n#include <mutex>\n#include <span>\n\nnamespace ml\n{\n\nusing namespace Eigen;\n\nstruct topology\n{\n    std::vector<int> layers;\n};\n\nstd::ostream& operator<<(std::ostream& stream, const topology& topo);\n\nclass neural_network\n{\nprivate:\n    std::vector<MatrixXd>                 m_weights;\n    std::vector<VectorXd>                 m_biases;\n    topology                              m_topo;\n    const std::map<std::string, VectorXd> m_labels;\n    std::mutex                            mtx;\n    // Ideally m_latest_weight_gradients and m_latest_bias_gradients would not be properties of the class,\n    // however back_propagate's function signature was getting too large\n    std::vector<MatrixXd>                 m_latest_weight_gradients;\n    std::vector<VectorXd>                 m_latest_bias_gradients;\n\n    static void hadamard_product(VectorXd& lhs, const VectorXd& rhs);\n\n    static void logistic(VectorXd& vector);\n    static void logistic_derivative(VectorXd& vector);\n\n    [[nodiscard]] static std::map<std::string, VectorXd> generate_class_vector_map(std::set<std::string>);\n\npublic:\n    neural_network(topology topo, std::set<std::string> labels);\n    neural_network(std::vector<MatrixXd> weights, std::vector<VectorXd> biases, std::set<std::string> labels);\n\n    void randomize();\n\n    // returns the largest activation of the final layer and it's coresponding class\n    [[nodiscard]] std::pair<std::string, double>                classify(const VectorXd& input_activations) const;\n    // Generates a confusion matrix with the columns representing predicted labels and the rows representing actual labels, vector component\n    // of pair is to indicate ordering of labels in rows and columns\n    [[nodiscard]] std::pair<std::vector<std::string>, MatrixXi> generate_confusion_matrix(const std::vector<std::pair<VectorXd, std::string>>& test_data) const;\n    // returns a vector of all calculated activations and weighted sums\n    [[nodiscard]] std::vector<std::pair<VectorXd, VectorXd>>    forward_propagate_return_all(const VectorXd& input_activations, const std::vector<MatrixXd>& local_weights, const std::vector<VectorXd>& local_biases) const;\n\n    // performes back propagation. training_data is a vector of pairs of training input data and desired output classification\n    double back_propagate(const std::vector<std::pair<VectorXd, VectorXd>>& training_data, const std::span<int>& mini_batch, double learning_rate);\n    // trains network\n    void   train(const std::vector<std::pair<VectorXd, std::string>>& training_data, bool print_cost, std::atomic_bool& stopped, double learning_rate = 0.1, std::size_t mini_batch_size = 0);\n\n    friend std::ostream& operator<<(std::ostream&, const neural_network&);\n};\n\nstd::ostream& operator<<(std::ostream& stream, const neural_network& network);\n\n};", "meta": {"hexsha": "1ce7d77929a4d65ecbea8f43675c104509483896", "size": 2942, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/network.hpp", "max_stars_repo_name": "isaac868/SENG475-Neural-Network-Project", "max_stars_repo_head_hexsha": "b59568f0dc2dac5115ae481b9b4c27c78029264b", "max_stars_repo_licenses": ["MIT"], "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/network.hpp", "max_issues_repo_name": "isaac868/SENG475-Neural-Network-Project", "max_issues_repo_head_hexsha": "b59568f0dc2dac5115ae481b9b4c27c78029264b", "max_issues_repo_licenses": ["MIT"], "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/network.hpp", "max_forks_repo_name": "isaac868/SENG475-Neural-Network-Project", "max_forks_repo_head_hexsha": "b59568f0dc2dac5115ae481b9b4c27c78029264b", "max_forks_repo_licenses": ["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.2647058824, "max_line_length": 221, "alphanum_fraction": 0.7104010877, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317475, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5472194370647575}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <mimkl/definitions.hpp>\n#include <mimkl/kernels.hpp>\n#include <mimkl/linear_algebra.hpp>\n#include <stdexcept>\n\nint main(int argc, char **argv)\n{\n    try\n    {\n        Eigen::Matrix<double, 2, 3> X;\n        Eigen::SparseMatrix<double> L(3, 3);\n        Eigen::Matrix<double, 2, 1> diag;\n        Eigen::Matrix<double, 2, 1> diag_reference;\n\n        X << 1., 2., 3., 4., 5., 6.;\n        mimkl::linear_algebra::fill_sparse_diagonal(L, 1.0);\n\n        diag_reference << 14., 77.;\n\n        mimkl::induction::get_diagonal_from_square_induction(X, L, diag);\n        assert(((diag - diag_reference).norm() == 0.0) && \"Identity Inducer\");\n\n        Eigen::SparseMatrix<double> L1(3, 3);\n        typedef Eigen::Triplet<double> TripletDouble; // (row,col,coef)\n        std::vector<TripletDouble> triplet_list;\n        triplet_list.reserve(4);\n        triplet_list.push_back(TripletDouble(0, 1, 1.));\n        triplet_list.push_back(TripletDouble(1, 2, 1.));\n        triplet_list.push_back(TripletDouble(1, 0, 1.));\n        triplet_list.push_back(TripletDouble(2, 1, 1.));\n        L1.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n        diag_reference << 16., 100.;\n\n        mimkl::induction::get_diagonal_from_square_induction(X, L1, diag);\n        assert(((diag - diag_reference).norm() == 0.0) &&\n               \"unweighted Graph Inducer\");\n\n        return EXIT_SUCCESS;\n    }\n    catch (const std::exception &e)\n    {\n        std::cerr << e.what();\n        return EXIT_FAILURE;\n    }\n}\n", "meta": {"hexsha": "c97f0a7aa106c285dd28f3d6ca00a602544d3aef", "size": 1564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/diagonal_from_square_induction/main.cpp", "max_stars_repo_name": "vishalbelsare/mimkl", "max_stars_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T23:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:00:03.000Z", "max_issues_repo_path": "test/diagonal_from_square_induction/main.cpp", "max_issues_repo_name": "vishalbelsare/mimkl", "max_issues_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T13:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:20:55.000Z", "max_forks_repo_path": "test/diagonal_from_square_induction/main.cpp", "max_forks_repo_name": "vishalbelsare/mimkl", "max_forks_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T09:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:40:27.000Z", "avg_line_length": 31.28, "max_line_length": 78, "alphanum_fraction": 0.6131713555, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.5472194315512569}}
{"text": "//=======================================================================\n// Copyright (c)\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 knapsack_long_test.cpp\n * @brief\n * @author Piotr Wygocki\n * @version 1.0\n * @date 2013-09-20\n */\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/read_knapsack.hpp\"\n#include \"test_utils/knapsack_tags_utils.hpp\"\n#include \"test_utils/get_test_dir.hpp\"\n#include \"test_utils/system.hpp\"\n\n#include \"paal/dynamic/knapsack_unbounded.hpp\"\n#include \"paal/dynamic/knapsack_0_1.hpp\"\n#include \"paal/utils/floating.hpp\"\n#include \"paal/utils/parse_file.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/range/algorithm/random_shuffle.hpp>\n\n#include <fstream>\n\nusing namespace paal;\nusing namespace paal::utils;\nusing namespace paal::system;\n\nBOOST_AUTO_TEST_CASE(KnapsackLong) {\n    std::string test_dir = get_test_data_dir(\"KNAPSACK\");\n    parse(build_path(test_dir, \"cases.txt\"),\n          [&](const std::string & line, std::istream & is_test_cases) {\n        int testId = std::stoi(line);\n        LOGLN(\"test >>>>>>>>>>>>>>>>>>>>>>>>>>>> \" << testId);\n\n        int capacity;\n        std::vector<std::pair<int, int>> objects;\n        std::vector<int> optimal;\n\n        auto size = [](std::pair<int, int> object) { return object.first; }\n        ;\n        auto value = [](std::pair<int, int> object) { return object.second; }\n        ;\n\n        read(build_path(test_dir, \"cases\"), testId, capacity, objects, optimal);\n        LOGLN(\"capacity \" << capacity);\n        LOGLN(\"sizes \");\n\n        LOGLN(\"\");\n        LOGLN(\"size values\");\n        ON_LOG(for (auto o\n                    : objects) {\n            std::cout << \"{ size = \" << o.first << \", value = \" << o.second\n                      << \"} \";\n        });\n        LOGLN(\"\");\n        LOGLN(\"Optimal 0/1\");\n        LOG_COPY_RANGE_DEL(optimal, \" \");\n        LOGLN(\"\");\n        auto opt_0_1 = boost::accumulate(optimal, 0, [&](int sum, int i) {\n            return sum + objects[i].second;\n        });\n        ON_LOG(auto optSize = )\n            boost::accumulate(optimal, 0, [&](int sum, int i) {\n            return sum + objects[i].first;\n        });\n        LOGLN(\"Opt size \" << optSize << \" opt \" << opt_0_1);\n        LOGLN(\"\");\n\n        // KNAPSACK\n        auto opt =\n            detail_knapsack<pd::integral_value_and_size_tag, pd::unbounded_tag>(\n                objects, capacity, size, value).first;\n\n        boost::random_shuffle(objects);\n\n        auto maxValue =\n            detail_knapsack<pd::integral_value_tag, pd::unbounded_tag>(\n                objects, capacity, size, value);\n\n        boost::random_shuffle(objects);\n        BOOST_CHECK_EQUAL(opt, maxValue.first);\n        maxValue = detail_knapsack<pd::integral_size_tag, pd::unbounded_tag>(\n            objects, capacity, size, value);\n        boost::random_shuffle(objects);\n        BOOST_CHECK_EQUAL(opt, maxValue.first);\n\n        // KNAPSACK 0/1\n\n        maxValue =\n            detail_knapsack<pd::integral_value_and_size_tag, pd::zero_one_tag>(\n                objects, capacity, size, value);\n        boost::random_shuffle(objects);\n        BOOST_CHECK_EQUAL(opt_0_1, maxValue.first);\n        maxValue = detail_knapsack<pd::integral_size_tag, pd::zero_one_tag>(\n            objects, capacity, size, value);\n        boost::random_shuffle(objects);\n        BOOST_CHECK_EQUAL(opt_0_1, maxValue.first);\n        maxValue = detail_knapsack<pd::integral_value_tag, pd::zero_one_tag>(\n            objects, capacity, size, value);\n        boost::random_shuffle(objects);\n        BOOST_CHECK_EQUAL(opt_0_1, maxValue.first);\n\n        maxValue =\n            detail_knapsack<pd::integral_value_and_size_tag, pd::zero_one_tag,\n                            pd::no_retrieve_solution_tag>(objects, capacity,\n                                                          size, value);\n        boost::random_shuffle(objects);\n        BOOST_CHECK_EQUAL(opt_0_1, maxValue.first);\n        maxValue = detail_knapsack<pd::integral_size_tag, pd::zero_one_tag,\n                                   pd::no_retrieve_solution_tag>(\n            objects, capacity, size, value);\n        boost::random_shuffle(objects);\n        BOOST_CHECK_EQUAL(opt_0_1, maxValue.first);\n        maxValue = detail_knapsack<pd::integral_value_tag, pd::zero_one_tag,\n                                   pd::no_retrieve_solution_tag>(\n            objects, capacity, size, value);\n        boost::random_shuffle(objects);\n        BOOST_CHECK_EQUAL(opt_0_1, maxValue.first);\n\n        // FPTAS\n        auto epsilons = { 0.00001, 0.0001, 0.001, 0.01, 0.1, 0.2, 0.3, 0.4, 0.5,\n                          0.6, 0.7 };\n\n        for (auto epsilon : epsilons) {\n            // KNAPSACK unbounded on value\n            maxValue = detail_knapsack_fptas<pd::unbounded_tag,\n                                             pd::retrieve_solution_tag>(\n                epsilon, objects, capacity, size, value, on_value_tag{});\n            boost::random_shuffle(objects);\n            BOOST_CHECK(double(opt) * (1. - epsilon) <= maxValue.first);\n            BOOST_CHECK(capacity >= maxValue.second);\n\n            // KNAPSACK unbounded on size\n            // this might possibly fail since this version is not really a FPTAS\n            maxValue = detail_knapsack_fptas<pd::unbounded_tag,\n                                             pd::retrieve_solution_tag>(\n                epsilon, objects, capacity, size, value, on_size_tag{});\n            boost::random_shuffle(objects);\n            BOOST_CHECK(opt <= maxValue.first);\n            BOOST_CHECK(double(capacity) * (1. + epsilon) >= maxValue.second);\n\n            // KNAPSACK 0_1 on value\n            maxValue = detail_knapsack_fptas<pd::zero_one_tag,\n                                             pd::retrieve_solution_tag>(\n                epsilon, objects, capacity, size, value, on_value_tag{});\n            boost::random_shuffle(objects);\n            BOOST_CHECK(double(opt_0_1) * (1. - epsilon) <= maxValue.first);\n            BOOST_CHECK(capacity >= maxValue.second);\n\n            // KNAPSACK 0_1 on size\n            maxValue = detail_knapsack_fptas<pd::zero_one_tag,\n                                             pd::retrieve_solution_tag>(\n                epsilon, objects, capacity, size, value, on_size_tag{});\n            boost::random_shuffle(objects);\n            BOOST_CHECK(opt_0_1 <= maxValue.first);\n            BOOST_CHECK(double(capacity) * (1. + epsilon) >= maxValue.second);\n        }\n    });\n}\n", "meta": {"hexsha": "a58da6ab9484a242c4df84a0d87a3793b23521db", "size": 6652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/dynamic/knapsack/knapsack_long_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/dynamic/knapsack/knapsack_long_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/dynamic/knapsack/knapsack_long_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": 39.5952380952, "max_line_length": 80, "alphanum_fraction": 0.5670475045, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5472154439945527}}
{"text": "#include <mpi.h>\n#include <iostream>\n#include <iomanip>\n#include <armadillo>\nusing namespace std;\nusing namespace arma;\n\ndouble ** CreateMatrix(int m, int n){\n  double ** mat;\n  mat = new double*[m];\n  for(int i=0;i<m;i++){\n    mat[i] = new double[n];\n    for(int j=0;j<m;j++)\n      mat[i][j] = 0.0;\n  }\n  return mat;\n}\n\nvoid DestroyMatrix(double ** mat, int m, int n){\n  for(int i=0;i<m;i++)\n    delete[] mat[i];\n  delete[] mat;\n}\n\nint Jacobi_P(int, int, int, double **, double *, double *, double);\n\nint main(int argc, char * argv[]){\n  int i,j, N = 20;\n  double **A,*x,*q;\n  int totalnodes,mynode;\n\n  MPI_Init(&argc,&argv);\n  MPI_Comm_size(MPI_COMM_WORLD, &totalnodes);\n  MPI_Comm_rank(MPI_COMM_WORLD, &mynode);\n\n  if(mynode==0){\n    A = CreateMatrix(N,N);\n    x = new double[N];\n    q = new double[N];\n\n    for(i=0;i<N;i++){\n      q[i] = i+1;\n      A[i][i] = -2.0;\n      if(i<N-1){\n        A[i][i+1] = 1.0;\n        A[i+1][i] = 1.0;\n      }\n    }\n  }\n  Jacobi_P(mynode,totalnodes,N,A,x,q,1.0e-14);\n  if(mynode==0){\n    for(i=0;i<N;i++)\n      cout << x[i] << endl;\n    DestroyMatrix(A,N,N);\n    delete[] x;\n    delete[] q;\n  }\n  MPI_Finalize();\n}\n\n\nint Jacobi_P(int mynode, int numnodes, int N, double **A, double *x, double *b, double abstol){\n  int i,j,k,i_global;\n  int maxit = 100000;\n  int rows_local,local_offset,last_rows_local,*count,*displacements;\n  double sum1,sum2,*xold;\n  double error_sum_local, error_sum_global;\n  MPI_Status status;\n\n  rows_local = (int) floor((double)N/numnodes);\n  local_offset = mynode*rows_local;\n  if(mynode == (numnodes-1)) \n    rows_local = N - rows_local*(numnodes-1);\n\n  /*Distribute the Matrix and R.H.S. among the processors */\n  if(mynode == 0){\n    for(i=1;i<numnodes-1;i++){\n      for(j=0;j<rows_local;j++)\n        MPI_Send(A[i*rows_local+j],N,MPI_DOUBLE,i,j,MPI_COMM_WORLD);\n      MPI_Send(b+i*rows_local,rows_local,MPI_DOUBLE,i,rows_local,\n               MPI_COMM_WORLD);\n    }\n    last_rows_local = N-rows_local*(numnodes-1);\n    for(j=0;j<last_rows_local;j++)\n      MPI_Send(A[(numnodes-1)*rows_local+j],N,MPI_DOUBLE,numnodes-1,j,\n               MPI_COMM_WORLD);\n    MPI_Send(b+(numnodes-1)*rows_local,last_rows_local,MPI_DOUBLE,numnodes-1,\n             last_rows_local,MPI_COMM_WORLD);\n  }\n  else{\n    A = CreateMatrix(rows_local,N);\n    x = new double[rows_local];    \n    b = new double[rows_local];\n    for(i=0;i<rows_local;i++)\n      MPI_Recv(A[i],N,MPI_DOUBLE,0,i,MPI_COMM_WORLD,&status);\n    MPI_Recv(b,rows_local,MPI_DOUBLE,0,rows_local,MPI_COMM_WORLD,&status);\n  }\n\n\n  xold = new double[N];\n  count = new int[numnodes];\n  displacements = new int[numnodes];\n\n\n  //set initial guess to all 1.0\n  for(i=0; i<N; i++){\n    xold[i] = 1.0;\n  }\n\n  for(i=0;i<numnodes;i++){\n    count[i] = (int) floor((double)N/numnodes);\n    displacements[i] = i*count[i];\n  }\n  count[numnodes-1] = N - ((int)floor((double)N/numnodes))*(numnodes-1);\n  \n  for(k=0; k<maxit; k++){\n    error_sum_local = 0.0;\n    for(i = 0; i<rows_local; i++){\n      i_global = local_offset+i;\n      sum1 = 0.0; sum2 = 0.0;\n      for(j=0; j < i_global; j++)\n        sum1 = sum1 + A[i][j]*xold[j];\n      for(j=i_global+1; j < N; j++)\n        sum2 = sum2 + A[i][j]*xold[j];\n      \n      x[i] = (-sum1 - sum2 + b[i])/A[i][i_global];\n      error_sum_local += (x[i]-xold[i_global])*(x[i]-xold[i_global]);\n    }\n    \n    MPI_Allreduce(&error_sum_local,&error_sum_global,1,MPI_DOUBLE,\n                  MPI_SUM,MPI_COMM_WORLD);\n    MPI_Allgatherv(x,rows_local,MPI_DOUBLE,xold,count,displacements,\n                   MPI_DOUBLE,MPI_COMM_WORLD);\n    \n    if(sqrt(error_sum_global)<abstol){\n      if(mynode == 0){\n        for(i=0;i<N;i++)\n          x[i] = xold[i];\n      }\n      else{\n        DestroyMatrix(A,rows_local,N);\n        delete[] x;\n        delete[] b;\n      }\n      delete[] xold;\n      delete[] count;\n      delete[] displacements;\n      return k;\n    }\n  }\n\n  cerr << \"Jacobi: Maximum Number of Interations Reached Without Convergence\\n\";\n  if(mynode == 0){\n    for(i=0;i<N;i++)\n      x[i] = xold[i];\n  }\n  else{\n    DestroyMatrix(A,rows_local,N);\n    delete[] x;\n    delete[] b;\n  }\n  delete[] xold;\n  delete[] count;\n  delete[] displacements;\n  \n  return maxit;\n}\n\n\n\n", "meta": {"hexsha": "6a57dfa956cee6e6d13a439ca112cbb225e6fbc4", "size": 4190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/pde/pde/Programs/cpp/MPIdiffusion.cpp", "max_stars_repo_name": "kimrojas/ComputationalPhysicsMSU", "max_stars_repo_head_hexsha": "a47cfc18b3ad6adb23045b3f49fab18c0333f556", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 220.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T09:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:09:16.000Z", "max_issues_repo_path": "doc/src/pde/pde/Programs/cpp/MPIdiffusion.cpp", "max_issues_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_issues_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-04T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T12:55:10.000Z", "max_forks_repo_path": "doc/src/pde/pde/Programs/cpp/MPIdiffusion.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": 24.5029239766, "max_line_length": 95, "alphanum_fraction": 0.5849642005, "num_tokens": 1345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5472154395076573}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2020 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 \"weighted_alpha_complex\"\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <CGAL/Epick_d.h>\n#include <CGAL/Epeck_d.h>\n\n#include <cmath>  // float comparison\n#include <vector>\n#include <random>\n#include <array>\n#include <cmath> // for std::fabs\n\n#include <gudhi/Alpha_complex.h>\n#include <gudhi/Alpha_complex_3d.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Unitary_tests_utils.h>\n\nusing list_of_exact_kernel_variants = boost::mpl::list<CGAL::Epeck_d< CGAL::Dynamic_dimension_tag >,\n                                                       CGAL::Epeck_d< CGAL::Dimension_tag<4> >\n                                                       > ;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(Zero_weighted_alpha_complex, Kernel, list_of_exact_kernel_variants) {\n  // Check that in exact mode for static dimension 4 the code for dD unweighted and for dD weighted with all weights\n  // 0 give exactly the same simplex tree (simplices and filtration values).\n\n  // Random points construction\n  using Point_d = typename Kernel::Point_d;\n  std::vector<Point_d> points;\n  std::uniform_real_distribution<double> rd_pts(-10., 10.);\n  std::random_device rand_dev;\n  std::mt19937 rand_engine(rand_dev());\n  for (int idx = 0; idx < 20; idx++) {\n    std::vector<double> point {rd_pts(rand_engine), rd_pts(rand_engine), rd_pts(rand_engine), rd_pts(rand_engine)};\n    points.emplace_back(point.begin(), point.end());\n  }\n  \n  // Alpha complex from points\n  Gudhi::alpha_complex::Alpha_complex<Kernel, false> alpha_complex_from_points(points);\n  Gudhi::Simplex_tree<> simplex;\n  Gudhi::Simplex_tree<>::Filtration_value infty = std::numeric_limits<Gudhi::Simplex_tree<>::Filtration_value>::infinity();\n  BOOST_CHECK(alpha_complex_from_points.create_complex(simplex, infty, true));\n  std::clog << \"Iterator on alpha complex simplices in the filtration order, with [filtration value]:\"\n            << std::endl;\n  for (auto f_simplex : simplex.filtration_simplex_range()) {\n    std::clog << \"   ( \";\n    for (auto vertex : simplex.simplex_vertex_range(f_simplex)) {\n      std::clog << vertex << \" \";\n    }\n    std::clog << \") -> \" << \"[\" << simplex.filtration(f_simplex) << \"] \" << std::endl;\n  }\n\n  // Alpha complex from zero weighted points\n  std::vector<typename Kernel::FT> weights(20, 0.);\n  Gudhi::alpha_complex::Alpha_complex<Kernel, true> alpha_complex_from_zero_weighted_points(points, weights);\n  Gudhi::Simplex_tree<> zw_simplex;\n  BOOST_CHECK(alpha_complex_from_zero_weighted_points.create_complex(zw_simplex, infty, true));\n\n  std::clog << \"Iterator on zero weighted alpha complex simplices in the filtration order, with [filtration value]:\"\n            << std::endl;\n  for (auto f_simplex : zw_simplex.filtration_simplex_range()) {\n    std::clog << \"   ( \";\n    for (auto vertex : zw_simplex.simplex_vertex_range(f_simplex)) {\n      std::clog << vertex << \" \";\n    }\n    std::clog << \") -> \" << \"[\" << zw_simplex.filtration(f_simplex) << \"] \" << std::endl;\n  }\n\n  BOOST_CHECK(zw_simplex == simplex);\n}\n\ntemplate <typename Point_d>\nbool cgal_3d_point_sort (Point_d a,Point_d b) {\n  if (a[0] != b[0])\n    return a[0] < b[0];\n  if (a[1] != b[1])\n    return a[1] < b[1];\n  return a[2] < b[2];\n}\n\nBOOST_AUTO_TEST_CASE(Weighted_alpha_complex_3d_comparison) {\n  // check that for random weighted 3d points in safe mode the 3D and dD codes give the same result with some tolerance\n\n  // Random points construction\n  using Kernel_dD = CGAL::Epeck_d< CGAL::Dimension_tag<3> >;\n  using Bare_point_d = typename Kernel_dD::Point_d;\n  using Weighted_point_d = typename Kernel_dD::Weighted_point_d;\n  std::vector<Weighted_point_d> w_points_d;\n\n  using Exact_weighted_alpha_complex_3d =\n    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::EXACT, true, false>;\n  using Bare_point_3 = typename Exact_weighted_alpha_complex_3d::Bare_point_3;\n  using Weighted_point_3 = typename Exact_weighted_alpha_complex_3d::Weighted_point_3;\n  std::vector<Weighted_point_3> w_points_3;\n\n  std::uniform_real_distribution<double> rd_pts(-10., 10.);\n  std::uniform_real_distribution<double> rd_wghts(-0.5, 0.5);\n  std::random_device rand_dev;\n  std::mt19937 rand_engine(rand_dev());\n  for (int idx = 0; idx < 20; idx++) {\n    std::vector<double> point {rd_pts(rand_engine), rd_pts(rand_engine), rd_pts(rand_engine)};\n    double weight = rd_wghts(rand_engine);\n    w_points_d.emplace_back(Bare_point_d(point.begin(), point.end()), weight);\n    w_points_3.emplace_back(Bare_point_3(point[0], point[1], point[2]), weight);\n  }\n\n  // Structures necessary for comparison\n  using Points = std::vector<std::array<double,3>>;\n  using Points_and_filtrations = std::map<Points, double>;\n  Points_and_filtrations pts_fltr_dD;\n  Points_and_filtrations pts_fltr_3d;\n\n  // Weighted alpha complex for dD version\n  Gudhi::alpha_complex::Alpha_complex<Kernel_dD, true> alpha_complex_dD_from_weighted_points(w_points_d);\n  Gudhi::Simplex_tree<> w_simplex_d;\n  BOOST_CHECK(alpha_complex_dD_from_weighted_points.create_complex(w_simplex_d));\n\n  std::clog << \"Iterator on weighted alpha complex dD simplices in the filtration order, with [filtration value]:\"\n            << std::endl;\n  for (auto f_simplex : w_simplex_d.filtration_simplex_range()) {\n    Points points;\n    for (auto vertex : w_simplex_d.simplex_vertex_range(f_simplex)) {\n      CGAL::NT_converter<Kernel_dD::RT, double> cgal_converter;\n      Bare_point_d pt = alpha_complex_dD_from_weighted_points.get_point(vertex).point();\n      points.push_back({cgal_converter(pt[0]), cgal_converter(pt[1]), cgal_converter(pt[2])});\n    }\n    std::clog << \"   ( \";\n    std::sort (points.begin(), points.end());\n    for (auto point : points) {\n      std::clog << point[0] << \" \" << point[1] << \" \" << point[2] << \" | \";\n    }\n    std::clog << \") -> \" << \"[\" << w_simplex_d.filtration(f_simplex) << \"] \";\n    std::clog << std::endl;\n    pts_fltr_dD[points] = w_simplex_d.filtration(f_simplex);\n  }\n\n  // Weighted alpha complex for 3D version\n  Exact_weighted_alpha_complex_3d alpha_complex_3D_from_weighted_points(w_points_3);\n  Gudhi::Simplex_tree<> w_simplex_3;\n  BOOST_CHECK(alpha_complex_3D_from_weighted_points.create_complex(w_simplex_3));\n\n  std::clog << \"Iterator on weighted alpha complex 3D simplices in the filtration order, with [filtration value]:\"\n            << std::endl;\n  for (auto f_simplex : w_simplex_3.filtration_simplex_range()) {\n    Points points;\n    for (auto vertex : w_simplex_3.simplex_vertex_range(f_simplex)) {\n      Bare_point_3 pt = alpha_complex_3D_from_weighted_points.get_point(vertex).point();\n      CGAL::NT_converter<Exact_weighted_alpha_complex_3d::Kernel::RT, double> cgal_converter;\n      points.push_back({cgal_converter(pt[0]), cgal_converter(pt[1]), cgal_converter(pt[2])});\n    }\n    std::clog << \"   ( \";\n    std::sort (points.begin(), points.end());\n    for (auto point : points) {\n      std::clog << point[0] << \" \" << point[1] << \" \" << point[2] << \" | \";\n    }\n    std::clog << \") -> \" << \"[\" << w_simplex_3.filtration(f_simplex) << \"] \" << std::endl;\n    pts_fltr_3d[points] = w_simplex_d.filtration(f_simplex);\n  }\n\n  // Compares structures\n  auto d3_itr = pts_fltr_3d.begin();\n  auto dD_itr = pts_fltr_dD.begin();\n  for (; d3_itr != pts_fltr_3d.end() && dD_itr != pts_fltr_dD.end(); ++d3_itr) {\n    if (d3_itr->first != dD_itr->first) {\n      for(auto point : d3_itr->first)\n        std::clog << point[0] << \" \" << point[1] << \" \" << point[2] << \" | \";\n      std::clog << \" versus \";\n      for(auto point : dD_itr->first)\n        std::clog << point[0] << \" \" << point[1] << \" \" << point[2] << \" | \";\n      std::clog << std::endl;\n      BOOST_CHECK(false);\n    }\n    // In safe mode, relative error is less than 1e-5 (can be changed with set_relative_precision_of_to_double)\n    if (std::fabs(d3_itr->second - dD_itr->second) > 1e-5 * (std::fabs(d3_itr->second) + std::fabs(dD_itr->second))) {\n      std::clog << d3_itr->second << \" versus \" << dD_itr->second << \" diff \"\n                << std::fabs(d3_itr->second - dD_itr->second) << std::endl;\n      BOOST_CHECK(false);\n    }\n    ++dD_itr;\n  }\n}\n\nusing list_of_1d_kernel_variants = boost::mpl::list<CGAL::Epeck_d< CGAL::Dynamic_dimension_tag >,\n                                                    CGAL::Epeck_d< CGAL::Dimension_tag<1>>,\n                                                    CGAL::Epick_d< CGAL::Dynamic_dimension_tag >,\n                                                    CGAL::Epick_d< CGAL::Dimension_tag<1>>\n                                                    >;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(Weighted_alpha_complex_non_visible_points, Kernel, list_of_1d_kernel_variants) {\n  // check that for 2 closed weighted 1-d points, one with a high weight to hide the second one with a small weight,\n  // that the point with a small weight has the same high filtration value than the edge formed by the 2 points\n  using Point_d = typename Kernel::Point_d;\n  std::vector<Point_d> points;\n  std::vector<double> p1 {0.};\n  points.emplace_back(p1.begin(), p1.end());\n  // closed enough points\n  std::vector<double> p2 {0.1};\n  points.emplace_back(p2.begin(), p2.end());\n  std::vector<typename Kernel::FT> weights {100., 0.01};\n\n  Gudhi::alpha_complex::Alpha_complex<Kernel, true> alpha_complex(points, weights);\n  Gudhi::Simplex_tree<> stree;\n  BOOST_CHECK(alpha_complex.create_complex(stree));\n\n  std::clog << \"Iterator on weighted alpha complex simplices in the filtration order, with [filtration value]:\"\n            << std::endl;\n  for (auto f_simplex : stree.filtration_simplex_range()) {\n    std::clog << \"   ( \";\n    for (auto vertex : stree.simplex_vertex_range(f_simplex)) {\n      std::clog << vertex << \" \";\n    }\n    std::clog << \") -> \" << \"[\" << stree.filtration(f_simplex) << \"] \" << std::endl;\n  }\n\n  BOOST_CHECK(stree.filtration(stree.find({0})) == -100.);\n  BOOST_CHECK(stree.filtration(stree.find({1})) == stree.filtration(stree.find({0, 1})));\n  BOOST_CHECK(stree.filtration(stree.find({1})) > 100000);\n}", "meta": {"hexsha": "d267276c07e340ea6fdd0338a4bbd0031a047a9e", "size": 10372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Alpha_complex/test/Weighted_alpha_complex_unit_test.cpp", "max_stars_repo_name": "mglisse/gudhi-devel", "max_stars_repo_head_hexsha": "6811a26e8b45ba4fde5ad3268d0eb07d3070a349", "max_stars_repo_licenses": ["MIT"], "max_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_complex/test/Weighted_alpha_complex_unit_test.cpp", "max_issues_repo_name": "mglisse/gudhi-devel", "max_issues_repo_head_hexsha": "6811a26e8b45ba4fde5ad3268d0eb07d3070a349", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-24T14:34:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-24T14:34:45.000Z", "max_forks_repo_path": "src/Alpha_complex/test/Weighted_alpha_complex_unit_test.cpp", "max_forks_repo_name": "mglisse/gudhi-devel", "max_forks_repo_head_hexsha": "6811a26e8b45ba4fde5ad3268d0eb07d3070a349", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-06T07:16:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-06T07:16:17.000Z", "avg_line_length": 45.2925764192, "max_line_length": 123, "alphanum_fraction": 0.6698804474, "num_tokens": 2913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.5472154350207619}}
{"text": "#include <stdlib.h>\n#include <assert.h>\n#include <time.h>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <set>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include \"../Point.h\"\n#include \"../ANN.h\"\n#include \"../RMSUtils.h\"\n#include \"../IOUtil.h\"\n\nusing namespace std;\n\nvector<Point> validDirs;\nvector<double> validResults;\n\nbool validate_coreset(const vector<Point> &fatP, vector<size_t> &idxs, double epsilon) {\n    assert(idxs.size() <= fatP.size());\n\n    if (fatP.empty())\n        return true;\n\n    if (idxs.empty())\n        return false;\n\n    assert(idxs[0] >= 0 && idxs[idxs.size() - 1] < fatP.size());\n\n    for (size_t i = 0; i < validDirs.size(); i++) {\n        double cor_max = fatP[idxs[0]].dotP(validDirs[i]);\n        for (size_t j = 1; j < idxs.size(); j++) {\n            double corval = fatP[idxs[j]].dotP(validDirs[i]);\n            if (corval > cor_max)\n                cor_max = corval;\n        }\n\n        double ptval = validResults[i];\n        if (cor_max < (1 - epsilon) * ptval)\n            return false;\n    }\n    return true;\n}\n\nbool validate_eps_kernel(const vector<Point> &fatP, vector<size_t> &idxs, double epsilon) {\n    assert(idxs.size() <= fatP.size());\n\n    if (fatP.empty())\n        return true;\n\n    if (idxs.empty())\n        return false;\n\n    assert(idxs[0] >= 0 && idxs[idxs.size() - 1] < fatP.size());\n\n    size_t m = validDirs.size() / 2;\n    for (size_t i = 0; i < m; i++) {\n        double cor_max = fatP[idxs[0]].dotP(validDirs[2 * i]);\n        double cor_min = fatP[idxs[0]].dotP(validDirs[2 * i + 1]);\n        for (size_t j = 1; j < idxs.size(); j++) {\n            double cor_val1 = fatP[idxs[j]].dotP(validDirs[2 * i]);\n            double cor_val2 = fatP[idxs[j]].dotP(validDirs[2 * i + 1]);\n            if (cor_val1 > cor_max)\n                cor_max = cor_val1;\n            if (cor_val2 > cor_min)\n                cor_min = cor_val2;\n        }\n\n        if ((cor_max + cor_min) < (1 - epsilon) * (validResults[2 * i] + validResults[2 * i + 1]))\n            return false;\n    }\n    return true;\n}\n\nvoid coreset_by_sample(ANN *ann_ds, size_t dim, double outer_rad, double delta, size_t deltam, vector<size_t> &idxs) {\n    vector<Point> randomP;\n    RMSUtils::get_random_sphere_points(outer_rad, dim, deltam, randomP, false);\n\n    vector<size_t> new_idxs;\n    ann_ds->getANNs(randomP, delta, new_idxs);\n\n    //figure out all the distinct indices\n    set<size_t> unique_idxs;\n    for (size_t i = 0; i < idxs.size(); i++)\n        unique_idxs.insert(idxs[i]);\n    for (size_t i = 0; i < new_idxs.size(); i++)\n        unique_idxs.insert(new_idxs[i]);\n\n    idxs.clear();\n\n    set<size_t>::iterator it;\n    for (it = unique_idxs.begin(); it != unique_idxs.end(); ++it)\n        idxs.push_back((*it));\n}\n\nvector<size_t> get_coreset(const vector<Point> &fatP, const double epsilon, double &time) {\n    clock_t clockS = clock();\n\n    size_t dim = fatP[0].get_dimension();\n\n    double outer_rad;\n    outer_rad = 1 + sqrt(dim);\n    double delta = epsilon / (2 * outer_rad);\n\n    vector<size_t> idxs;\n    ANN *ann_ds = new ANN();\n    ann_ds->insertPts(fatP);\n\n    clock_t clockE = clock();\n\n    time += (double) (clockE - clockS);\n\n    size_t m = 10;\n    bool b = false;\n    while (!b) {\n        clockS = clock();\n        coreset_by_sample(ann_ds, dim, outer_rad, delta, m, idxs);\n        clockE = clock();\n        time += (double) (clockE - clockS);\n\n        b = validate_coreset(fatP, idxs, epsilon);\n        m *= 2;\n    }\n\n    delete ann_ds;\n\n    return idxs;\n}\n\nint main(int argc, char **argv) {\n    if (argc < 7) {\n        cerr << \"coreset: Usage \" << argv[0] << \"<eps> <dim> <data_path> <query_path> <valid_path> <output_path>\\n\";\n        exit(1);\n    }\n\n    double eps = atof(argv[1]);\n    size_t dim = atoi(argv[2]);\n\n    vector<Point> fatP;\n\n    IOUtil::read_input_points(argv[3], dim, fatP);\n    IOUtil::read_validate_dirs(argv[4], dim, validDirs);\n    IOUtil::read_validate_results(argv[5], validResults);\n\n    ofstream result_file;\n    result_file.open(argv[6], ofstream::out | ofstream::app);\n\n    cout << \"ann \" << argv[3] << \" \" << fatP.size() << \" \" << dim << endl;\n\n    result_file << \"dataset=\" << argv[3] << \" eps=\" << eps << \"\\n\" << flush;\n\n    for (int r = 0; r < 10; ++r) {\n        vector<size_t> idxs;\n        double time = 0;\n        idxs = get_coreset(fatP, eps, time);\n\n        int size = idxs.size();\n        time = (double) time / CLOCKS_PER_SEC;\n\n        result_file << \"time=\" << (time * 1000.0) << \" size=\" << size << \"\\n\" << flush;\n    }\n    result_file << \"\\n\" << flush;\n    result_file.close();\n}\n", "meta": {"hexsha": "35493643dbf264b6a3f99845f8838a8a400dad9d", "size": 4573, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ANN/coreset/coreset.cpp", "max_stars_repo_name": "yhwang1990/minimum-coresets", "max_stars_repo_head_hexsha": "8a81d6cb7260cc9de82d5d9160440296732d2620", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-19T13:01:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T13:01:43.000Z", "max_issues_repo_path": "ANN/coreset/coreset.cpp", "max_issues_repo_name": "yhwang1990/minimum-coresets", "max_issues_repo_head_hexsha": "8a81d6cb7260cc9de82d5d9160440296732d2620", "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": "ANN/coreset/coreset.cpp", "max_forks_repo_name": "yhwang1990/minimum-coresets", "max_forks_repo_head_hexsha": "8a81d6cb7260cc9de82d5d9160440296732d2620", "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.5481927711, "max_line_length": 118, "alphanum_fraction": 0.5683358845, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5472154305338662}}
{"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 <Eigen/Core>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n#include \"gtest/gtest.h\"\n\n#include \"theia/math/util.h\"\n#include \"theia/util/random.h\"\n#include \"theia/sfm/pose/four_point_homography.h\"\n#include \"theia/sfm/pose/test_util.h\"\n\nnamespace theia {\nnamespace {\nusing Eigen::AngleAxisd;\nusing Eigen::Matrix3d;\nusing Eigen::Quaterniond;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\n\nRandomNumberGenerator rng(53);\n\n// Creates a test scenario from ground truth 3D points and ground truth rotation\n// and translation. Projection (i.e., image) noise is optional (set to 0 for no\n// noise). The fundamental matrix is computed to ensure that the reprojection\n// errors are sufficiently small.\nvoid GenerateImagePoints(const std::vector<Vector3d>& points_3d,\n                         const double projection_noise_std_dev,\n                         const Quaterniond& expected_rotation,\n                         const Vector3d& expected_translation,\n                         std::vector<Vector2d>* image_1_points,\n                         std::vector<Vector2d>* image_2_points) {\n  image_1_points->reserve(points_3d.size());\n  image_2_points->reserve(points_3d.size());\n  for (int i = 0; i < points_3d.size(); i++) {\n    image_1_points->push_back(points_3d[i].hnormalized());\n    image_2_points->push_back((expected_rotation * points_3d[i] +\n                               expected_translation).hnormalized());\n  }\n\n  if (projection_noise_std_dev) {\n    for (int i = 0; i < points_3d.size(); i++) {\n      AddNoiseToProjection(projection_noise_std_dev, &rng,\n                           &((*image_1_points)[i]));\n      AddNoiseToProjection(projection_noise_std_dev, &rng,\n                           &((*image_2_points)[i]));\n    }\n  }\n}\n\n// Check that the symmetric error is small. NOTE: this is a different error than\n// the reprojection error.\nvoid CheckSymmetricError(const std::vector<Vector2d>& image_1_points,\n                         const std::vector<Vector2d>& image_2_points,\n                         const Matrix3d& homography_matrix,\n                         const double max_symmetric_error) {\n  const Matrix3d inv_homography = homography_matrix.inverse();\n  for (int i = 0; i < image_1_points.size(); i++) {\n    const Vector3d image_1_hat =\n        inv_homography * image_2_points[i].homogeneous();\n    const Vector3d image_2_hat =\n        homography_matrix * image_1_points[i].homogeneous();\n    // Compute reprojection error.\n    const double img_1_error =\n        (image_1_points[i] - image_1_hat.hnormalized()).squaredNorm();\n    const double img_2_error =\n        (image_2_points[i] - image_2_hat.hnormalized()).squaredNorm();\n\n    EXPECT_LT(img_1_error, max_symmetric_error);\n    EXPECT_LT(img_2_error, max_symmetric_error);\n  }\n}\n\n// Run a test for the homography with at least 4 points.\nvoid FourPointHomographyWithNoiseTest(const std::vector<Vector3d>& points_3d,\n                                      const double projection_noise_std_dev,\n                                      const Quaterniond& expected_rotation,\n                                      const Vector3d& expected_translation,\n                                      const double kMaxSymmetricError) {\n  std::vector<Vector2d> image_1_points;\n  std::vector<Vector2d> image_2_points;\n  GenerateImagePoints(points_3d, projection_noise_std_dev, expected_rotation,\n                      expected_translation, &image_1_points, &image_2_points);\n  // Compute homography matrix.\n  Matrix3d homography_matrix;\n  EXPECT_TRUE(FourPointHomography(image_1_points,\n                                  image_2_points,\n                                  &homography_matrix));\n\n  CheckSymmetricError(image_1_points, image_2_points, homography_matrix,\n                         kMaxSymmetricError);\n}\n\nvoid BasicTest() {\n  const std::vector<Vector3d> points_3d = {\n    Vector3d(-1.0, 3.0, 3.0),\n    Vector3d(1.0, -1.0, 2.0),\n    Vector3d(-1.0, 1.0, 2.0),\n    Vector3d(2.0, 1.0, 3.0),\n  };\n\n  const Quaterniond soln_rotation(\n      AngleAxisd(DegToRad(13.0), Vector3d(0.0, 0.0, 1.0)));\n  const Vector3d soln_translation(0.0, 0.0, 0.0);\n  const double kNoise = 0.0 / 512.0;\n  const double kMaxSymmetricError = 1e-12;\n\n  FourPointHomographyWithNoiseTest(\n      points_3d, kNoise, soln_rotation, soln_translation,\n      kMaxSymmetricError);\n}\n\nTEST(FourPointHomography, BasicTest) {\n  BasicTest();\n}\n\nTEST(FourPointHomography, NoiseTest) {\n  const std::vector<Vector3d> points_3d = {\n    Vector3d(-1.0, 3.0, 3.0),\n    Vector3d(1.0, -1.0, 2.0),\n    Vector3d(-1.0, 1.0, 2.0),\n    Vector3d(2.0, 1.0, 3.0),\n  };\n\n  const Quaterniond soln_rotation(\n      AngleAxisd(DegToRad(13.0), Vector3d(0.0, 0.0, 1.0)));\n  const Vector3d soln_translation(0.0, 0.0, 0.0);\n  const double kNoise = 1.0 / 512.0;\n  const double kMaxSymmetricError = 1e-4;\n\n  FourPointHomographyWithNoiseTest(points_3d, kNoise, soln_rotation,\n                                    soln_translation, kMaxSymmetricError);\n}\n\nTEST(FourPointHomography, PlanarPoints) {\n  const std::vector<Vector3d> points_3d = {\n    Vector3d(-1.0, 3.0, 5.0),\n    Vector3d(1.0, -1.0, 5.0),\n    Vector3d(-1.0, 1.0, 5.0),\n    Vector3d(2.0, 1.0, 5.0),\n  };\n\n  const Quaterniond soln_rotation(\n      AngleAxisd(DegToRad(13.0), Vector3d(0.0, 0.0, 1.0)));\n  const Vector3d soln_translation(1.0, -0.5, -1.0);\n  const double kNoise = 1.0 / 512.0;\n  const double kMaxSymmetricError = 1e-4;\n\n  FourPointHomographyWithNoiseTest(points_3d, kNoise, soln_rotation,\n                                    soln_translation, kMaxSymmetricError);\n}\n\nvoid ManyPointsTest() {\n  const Quaterniond soln_rotation(\n      AngleAxisd(DegToRad(13.0), Vector3d(0.0, 0.0, 1.0)));\n  const Vector3d soln_translation(0.0, 0.0, 0.0);\n  const double kNoise = 1.0 / 512.0;\n  const double kMaxSymmetricError = 1e-4;\n  const int num_points = 100;\n\n  std::vector<Vector3d> points_3d(num_points);\n  for (int j = 0; j < num_points; j++) {\n    points_3d[j] = Vector3d(rng.RandDouble(-2.0, 2.0),\n                            rng.RandDouble(-2.0, 2.0),\n                            rng.RandDouble(1.0, 5.0));\n  }\n\n  FourPointHomographyWithNoiseTest(points_3d, kNoise, soln_rotation,\n                                   soln_translation, kMaxSymmetricError);\n}\n\nTEST(FourPointHomography, ManyPoints) {\n  ManyPointsTest();\n}\n\n}  // namespace\n}  // namespace theia\n", "meta": {"hexsha": "f3c36c43d8678b31c399b41ffa6f24e0c42c110e", "size": 8118, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/four_point_homography_test.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/four_point_homography_test.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/four_point_homography_test.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": 38.6571428571, "max_line_length": 80, "alphanum_fraction": 0.667528948, "num_tokens": 2181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5472154305338661}}
{"text": "#include <blitz/timer.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nvoid initialize(double& c, double& d, double* a, double* b, int& N);\n\ntemplate<class T>\nvoid sink(T&)\n{ }\n\nvoid benchmarkLoops(int, long);\n\nint main()\n{\n    cout << \"This program measures the performance of DAXPY operations\" \n         << endl << \"using various C loop structures.\" << endl << endl;\n\n    cout << endl << \"In-cache:\" << endl;\n\n    benchmarkLoops(400,50000);\n\n    cout << endl << \"Out of cache:\" << endl;\n\n    benchmarkLoops(1000000,50);\n\n    return 0;\n}\n\nvoid benchmarkLoops(int N, long iterations)\n{\n    double* _bz_restrict a = new double[N];\n    double* _bz_restrict b = new double[N];\n    double c, d;\n    double t1, t2;\n\n    initialize(c, d, a, b, N);\n\n    double mflops = iterations * 4.0 * N / (1024.0 * 1024.0);\n\n    Timer timer;\n\n    cout << \"Mflops/s Description\" << endl;\n\n    long iter;\n    int i;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        for (i=0; i < N; ++i)\n            a[i] += c * b[i];\n\n        for (i=0; i < N; ++i)\n            a[i] += d * b[i];\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds()) \n         << \"   for, indirection, unit stride\" << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        for (i=0; i < N; ++i)\n            a[i] = a[i] + c * b[i];\n\n        for (i=0; i < N; ++i)\n            a[i] = a[i] + d * b[i];\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"   for, indirection, unit stride, no +=\" << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        for (i=N-1; i >= 0; --i)\n            a[i] += c * b[i];\n\n        for (i=N-1; i >= 0; --i)\n            a[i] += d * b[i];\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"   for, indirection, unit stride, backwards loops\" << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        double c2 = c;\n\n        int n1 = N & 3;\n        for (i=0; i < n1; ++i)\n            a[i] += c2 * b[i];\n\n        for (; i < N; i += 4)\n        {\n            a[i] += c2 * b[i];\n            a[i+1] += c2 * b[i+1];\n            a[i+2] += c2 * b[i+2];\n            a[i+3] += c2 * b[i+3];\n        }\n\n        double d2 = d;\n        int n2 = N & 3;\n        for (i=0; i < n2; ++i)\n            a[i] += d2 * b[i];\n\n        for (; i < N; i += 4)\n        {\n            a[i] += d2 * b[i];\n            a[i+1] += d2 * b[i+1];\n            a[i+2] += d2 * b[i+2];\n            a[i+3] += d2 * b[i+3];\n        } \n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    for, unroll=4, unit stride, constants loaded into temps\"\n         << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        double c2 = c;\n\n        int n1 = N & 3;\n        for (i=0; i < n1; ++i)\n            a[i] += c2 * b[i];\n\n        for (; i < N; i += 4)\n        {\n            double t1 = c2 * b[i];\n            double t2 = c2 * b[i+1];\n            double t3 = c2 * b[i+2];\n            double t4 = c2 * b[i+3];\n\n            a[i] += t1;\n            a[i+1] += t2;\n            a[i+2] += t3;\n            a[i+3] += t4;\n        }\n\n        double d2 = d;\n        int n2 = N & 3;\n        for (i=0; i < n2; ++i)\n            a[i] += d2 * b[i];\n\n        for (; i < N; i += 4)\n        {\n            double t1 = d2 * b[i];\n            double t2 = d2 * b[i+1];\n            double t3 = d2 * b[i+2];\n            double t4 = d2 * b[i+3];\n\n            a[i] += t1;\n            a[i+1] += t2;\n            a[i+2] += t3;\n            a[i+3] += t4;\n        }\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    for, unroll=4, unit stride, constants loaded into temps,\"\n         << endl << \"\\t\\t4 read then 4 write\" \n         << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        double c2 = c;\n\n        int n1 = N & 3;\n        for (i=0; i < n1; ++i)\n            a[i] += c2 * b[i];\n\n        for (; i < N; i += 4)\n        {\n            a[i] = a[i] + c2 * b[i];\n            a[i+1] = a[i+1] + c2 * b[i+1];\n            a[i+2] = a[i+2] + c2 * b[i+2];\n            a[i+3] = a[i+3] + c2 * b[i+3];\n        }\n\n        double d2 = d;\n        int n2 = N & 3;\n        for (i=0; i < n2; ++i)\n            a[i] += d2 * b[i];\n\n        for (; i < N; i += 4)\n        {\n            a[i] = a[i] + d2 * b[i];\n            a[i+1] = a[i+1] + d2 * b[i+1];\n            a[i+2] = a[i+2] + d2 * b[i+2];\n            a[i+3] = a[i+3] + d2 * b[i+3];\n        }\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    for, unroll=4, unit stride, constants loaded into temps,\"\n         << endl << \"            no += \"\n         << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        double c2 = c;\n\n        int n1 = N & 3;\n        for (i=0; i < n1; ++i)\n            a[i] += c2 * b[i];\n\n        for (; i < N; i += 4)\n        {\n            int i1 = i + 1;\n            a[i] += c2 * b[i];\n            int i2 = i + 2;\n            a[i1] += c2 * b[i1];\n            int i3 = i + 3;\n            a[i2] += c2 * b[i2];\n            a[i3] += c2 * b[i3];\n        }\n\n        double d2 = d;\n        int n2 = N & 3;\n        for (i=0; i < n2; ++i)\n            a[i] += d2 * b[i];\n\n        for (; i < N; i += 4)\n        {\n            int i1 = i + 1;\n            a[i] += d2 * b[i];\n            int i2 = i + 2;\n            a[i1] += d2 * b[i1];\n            int i3 = i + 3;\n            a[i2] += d2 * b[i2];\n            a[i3] += d2 * b[i3];\n        }\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    for, unroll=4, unit stride, constants loaded into temps,\"\n         << endl << \"        CSE for index offsets\"\n         << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        double c2 = c;\n\n        int n1 = N & 3;\n        for (i=0; i < n1; ++i)\n            a[i] += c2 * b[i];\n\n        double* pa = a+n1;\n        double* pb = b+n1;\n \n        int top = N - n1 - 4;\n\n        for (i=top; i >= 0; i -= 4)\n        {\n            pa[i] += c2 * pb[i];\n            pa[i+1] += c2 * pb[i+1];\n            pa[i+2] += c2 * pb[i+2];\n            pa[i+3] += c2 * pb[i+3];\n        }\n\n        double d2 = d;\n        int n2 = N & 3;\n        for (i=0; i < n2; ++i)\n            a[i] += d2 * b[i];\n\n        pa = a+n2;\n        pb = b+n2;\n\n        top = N - n2 - 4;\n        for (i=top; i >= 0; i -= 4)\n        {\n            pa[i] += d2 * pb[i];\n            pa[i+1] += d2 * pb[i+1];\n            pa[i+2] += d2 * pb[i+2];\n            pa[i+3] += d2 * pb[i+3];\n        }\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    for, unroll=4, unit stride, constants loaded into temps,\"\n         << \"            backwards\"\n         << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        double c2 = c;\n\n        int n1 = N & 7;\n        for (i=0; i < n1; ++i)\n            a[i] += c2 * b[i];\n\n        for (; i < N; i += 8)\n        {\n            a[i] += c2 * b[i];\n            a[i+1] += c2 * b[i+1];\n            a[i+2] += c2 * b[i+2];\n            a[i+3] += c2 * b[i+3];\n            a[i+4] += c2 * b[i+4];\n            a[i+5] += c2 * b[i+5];\n            a[i+6] += c2 * b[i+6];\n            a[i+7] += c2 * b[i+7];\n        }\n\n        double d2 = d;\n        int n2 = N & 7;\n        for (i=0; i < n2; ++i)\n            a[i] += d2 * b[i];\n\n        for (; i < N; i += 8)\n        {\n            a[i] += d2 * b[i];\n            a[i+1] += d2 * b[i+1];\n            a[i+2] += d2 * b[i+2];\n            a[i+3] += d2 * b[i+3];\n            a[i+4] += d2 * b[i+4];\n            a[i+5] += d2 * b[i+5];\n            a[i+6] += d2 * b[i+6];\n            a[i+7] += d2 * b[i+7];\n        }\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    for, unroll=8, unit stride, constants loaded into temps\"\n         << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        double c2 = c;\n        for (i=0; i < N; ++i)\n            a[i] += c2 * b[i];\n\n        double d2 = d;\n        for (i=0; i < N; ++i)\n            a[i] += d2 * b[i];\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"   for, indirection, unit stride, constants into temps\"\n         << endl;\n\n    /*********************************************************************/\n    \n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        int stride = 1;\n        sink(stride);    // Prevent copy propagation\n\n        for (i=0; i < N; i += stride)\n            a[i] += c * b[i];\n\n        for (i=0; i < N; i += stride)\n            a[i] += d * b[i];\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    for, indirection, non-unit stride\" << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        int stride = 1;\n        sink(stride);    // Prevent copy propagation\n\n        double c2 = c;\n        for (i=0; i < N; i += stride)\n            a[i] += c2 * b[i];\n\n        double d2 = d;\n        for (i=0; i < N; i += stride)\n            a[i] += d2 * b[i];\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    for, indirection, non-unit stride, constants \"\n            \"loaded into temps\" << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        double * _bz_restrict pa1 = a,\n               * _bz_restrict pb1 = b;\n        double * _bz_restrict paend1 = a + N;\n        while (pa1 != paend1)\n        {\n            *pa1 += c * (*pb1);\n            ++pa1;\n            ++pb1;\n        }\n\n        double * _bz_restrict pa2 = a,\n               * _bz_restrict pb2 = b;\n        double * _bz_restrict paend2 = a + N;\n        while (pa2 != paend2)\n        {\n            *pa2 += d * (*pb2);\n            ++pa2;\n            ++pb2;\n        }\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    while, pointer increment, unit stride\" << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        double * _bz_restrict pa1 = a,\n               * _bz_restrict pb1 = b;\n        double * _bz_restrict paend1 = a + N;\n        double c2 = c;\n        while (pa1 != paend1)\n        {\n            *pa1 += c2 * (*pb1);\n            ++pa1;\n            ++pb1;\n        }\n\n        double * _bz_restrict pa2 = a,\n               * _bz_restrict pb2 = b;\n        double * _bz_restrict paend2 = a + N;\n        double d2 = d;\n        while (pa2 != paend2)\n        {\n            *pa2 += d2 * (*pb2);\n            ++pa2;\n            ++pb2;\n        }\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    while, pointer increment, unit stride, \" << endl\n         << \"    constants loaded into temps\" \n         << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        int stride = 1;\n        sink(stride);\n\n        double * _bz_restrict pa1 = a,\n               * _bz_restrict pb1 = b;\n        double * _bz_restrict paend1 = a + N * stride;\n        while (pa1 != paend1)\n        {\n            *pa1 += c * (*pb1);\n            pa1 += stride;\n            pb1 += stride;\n        }\n\n        double * _bz_restrict pa2 = a,\n               * _bz_restrict pb2 = b;\n        double * _bz_restrict paend2 = a + N * stride;\n        while (pa2 != paend2)\n        {\n            *pa2 += d * (*pb2);\n            pa2 += stride;\n            pb2 += stride;\n        }\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    while, pointer increment, non-unit stride\" << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        int stride = 1;\n        sink(stride);\n\n        double * _bz_restrict pa1 = a,\n               * _bz_restrict pb1 = b;\n        double * _bz_restrict paend1 = a + N * stride;\n        double c2 = c;\n        int n1 = N & 3;\n\n        for (i=0; i < n1; ++i)\n        {\n            *pa1 += c2 * (*pb1);\n            pa1 += stride;\n            pb1 += stride;\n        }\n\n        while (pa1 != paend1)\n        {\n            pa1[0] += c2 * pb1[0];\n            pa1[1] += c2 * pb1[1];\n            pa1[2] += c2 * pb1[2];\n            pa1[3] += c2 * pb1[3];\n            pa1 += 4 * stride;\n            pb1 += 4 * stride;\n        }\n\n        double * _bz_restrict pa2 = a,\n               * _bz_restrict pb2 = b;\n        double * _bz_restrict paend2 = a + N * stride;\n        double d2 = d;\n        int n2 = N & 3;\n\n        for (i=0; i < n2; ++i)\n        {\n            *pa2 += d2 * (*pb2);\n            pa2 += stride;\n            pb2 += stride;\n        }\n\n        while (pa2 != paend2)\n        {\n            pa2[0] += d2 * pb2[0];\n            pa2[1] += d2 * pb2[1];\n            pa2[2] += d2 * pb2[2];\n            pa2[3] += d2 * pb2[3];\n            pa2 += 4 * stride;\n            pb2 += 4 * stride;\n        }\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    while, pointer increment, unroll=4, non-unit stride,\" << endl\n         << \"     constants loaded into temps\" << endl;\n\n    /*********************************************************************/\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        double c2 = c;\n\n        int n1 = N & 3;\n        for (i=0; i < n1; ++i)\n            a[i] += c2 * b[i];\n\n        for (; i < N; i += 4)\n        {\n            t1 = a[i+4];\n            a[i] += c2 * b[i];\n            a[i+1] += c2 * b[i+1];\n            t2 = b[i+4];\n            a[i+2] += c2 * b[i+2];\n            a[i+3] += c2 * b[i+3];\n        }\n\n        double d2 = d;\n        int n2 = N & 3;\n        for (i=0; i < n2; ++i)\n            a[i] += d2 * b[i];\n\n        for (; i < N; i += 4)\n        {\n            t1 = a[i+4];\n            a[i] += d2 * b[i];\n            a[i+1] += d2 * b[i+1];\n            t2 = b[i+4];\n            a[i+2] += d2 * b[i+2];\n            a[i+3] += d2 * b[i+3];\n        }\n    }\n    timer.stop();\n\n    \n    sink(t1);\n    sink(t2);\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    for, unroll=4, unit stride, constants loaded into temps,\"\n         << \"            prefetching\"\n         << endl;\n\n    /********************************************************************/\n\n    struct vectorPair {\n        double a;\n        double b;\n    };\n    vectorPair* v = new vectorPair[N];\n    int N2 = 2*N;\n    initialize(c, d, (double*)v, (double*)v, N2);\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        for (i=0; i < N; ++i)\n            v[i].a += c * v[i].b;\n\n        for (i=0; i < N; ++i)\n            v[i].a += d * v[i].b;\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"   interlaced, for, indirection, unit stride\" << endl;\n\n    /*********************************************************************/\n\n    initialize(c, d, (double*)v, (double*)v, N2);\n\n    timer.start();\n    for (iter=0; iter < iterations; ++iter)\n    {\n        double c2 = c;\n\n        int n1 = N & 3;\n        for (i=0; i < n1; ++i)\n            v[i].a += c2 * v[i].b;\n\n        for (; i < N; i += 4)\n        {\n            v[i].a += c2 * v[i].b;\n            v[i+1].a += c2 * v[i+1].b;\n            v[i+2].a += c2 * v[i+2].b;\n            v[i+3].a += c2 * v[i+3].b;\n        }\n\n        double d2 = d;\n        int n2 = N & 3;\n        for (i=0; i < n2; ++i)\n            v[i].a += d2 * v[i].b;\n\n        for (; i < N; i += 4)\n        {\n            v[i].a += d2 * v[i].b;\n            v[i+1].a += d2 * v[i+1].b;\n            v[i+2].a += d2 * v[i+2].b;\n            v[i+3].a += d2 * v[i+3].b;\n        }\n    }\n    timer.stop();\n\n    cout << setw(7) << setprecision(5) << (mflops/timer.elapsedSeconds())\n         << \"    for, unroll=4, unit stride, interlaced, \" << endl\n         << \"\\t\\tconstants loaded into temps\"\n         << endl;\n\n    delete [] v;\n\n    /********************************************************************/\n\n    delete [] a;\n    delete [] b;\n}\n\nvoid initialize(double& c, double& d, double* a, double* b, int& N)\n{\n    for (int i=0; i < N; ++i)\n    {\n        a[i] = 1/7.; \n        b[i] = 1/3.;\n    }\n    c = 0.398192839842;\n    d = - c;\n}\n\n", "meta": {"hexsha": "3bf4a34ec89cbf17da63185b986e1415384b3d6e", "size": 17805, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/looptest.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/looptest.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/looptest.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1483050847, "max_line_length": 78, "alphanum_fraction": 0.350856501, "num_tokens": 5419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5472154260469707}}
{"text": "/*\n * Copyright (c) 2019 Opticks Team. All Rights Reserved.\n *\n * This file is part of Opticks\n * (see https://bitbucket.org/simoncblyth/opticks).\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 <iomanip>\n#include <iostream>\n#include <functional>\n#include <boost/math/tools/roots.hpp>\n\n\ntemplate <class T>\nstruct fn\n{\n    T operator()(const T& x )\n    {\n        return (x-2.)*(x-5.) ; \n    }\n};\n\ntemplate <class T>\nstruct tolerance\n{\n    bool operator()(const T& min, const T& max )\n    {\n        return (max - min) < 0.001 ;   \n    }\n};\n\n\n\n\nint main()\n{\n\n   fn<float> f ; \n   tolerance<float> tol ; \n\n   float min = 1 ; \n   float max = 3 ; \n\n   std::pair<float, float> r = boost::math::tools::bisect(f, min, max, tol );\n\n   std::cout \n      << \" r \" << std::setw(15) << std::fixed << std::setprecision(4) << r.first\n      << \" \" << r.second \n      << std::endl \n      ;\n\n\n    return 0 ; \n}\n", "meta": {"hexsha": "bc006694782f955ac945d5cdc84aa6b35f4774b4", "size": 1421, "ext": "cc", "lang": "C++", "max_stars_repo_path": "boostrap/tests/BBisectTest.cc", "max_stars_repo_name": "hanswenzel/opticks", "max_stars_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-07-05T02:39:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T18:52:44.000Z", "max_issues_repo_path": "boostrap/tests/BBisectTest.cc", "max_issues_repo_name": "hanswenzel/opticks", "max_issues_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "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": "boostrap/tests/BBisectTest.cc", "max_forks_repo_name": "hanswenzel/opticks", "max_forks_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-03T20:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T07:42:21.000Z", "avg_line_length": 21.2089552239, "max_line_length": 80, "alphanum_fraction": 0.6213933849, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.5472154180531352}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <cstddef>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <utility>\n\n#include <boost/functional/hash.hpp>\n\n#include <common/traits.hpp>\n#include <common/types.hpp>\n\nnamespace vitamine\n{\n\ttemplate <typename T, typename Tag = void>\n\tstruct Vector2XZ\n\t{\n\t\tusing ComponentType = T;\n\n\t\tT x, z;\n\n\t\tVector2XZ() noexcept = default;\n\t\tconstexpr Vector2XZ(T x, T z) noexcept : x(x), z(z) {}\n\n\t\t[[nodiscard]]\n\t\tbool withinOrdered(Vector2XZ from, Vector2XZ to) const\n\t\t{\n\t\t\tassert(from.x <= to.x);\n\t\t\tassert(from.z <= to.z);\n\t\t\treturn x >= from.x && x <= to.x\n\t\t\t    && z >= from.z && z <= to.z;\n\t\t}\n\n\t\ttemplate <typename U = T>\n\t\t[[nodiscard]]\n\t\tconstexpr T lengthSquared() const\n\t\t{\n\t\t\tauto x = static_cast<U>(this->x);\n\t\t\tauto z = static_cast<U>(this->z);\n\t\t\treturn x * x + z * z;\n\t\t}\n\n\t\ttemplate <typename F = Float64>\n\t\t[[nodiscard]]\n\t\tF length() const\n\t\t{\n\t\t\tusing std::sqrt;\n\t\t\treturn sqrt(static_cast<F>(lengthSquared()));\n\t\t}\n\t};\n\n\ttemplate <typename T, typename Tag = void>\n\tstruct Vector3XYZ\n\t{\n\t\tusing ComponentType = T;\n\n\t\tT x, y, z;\n\n\t\tVector3XYZ() noexcept = default;\n\t\tconstexpr Vector3XYZ(T x, T y, T z) noexcept : x(x), y(y), z(z) {}\n\n\t\t[[nodiscard]]\n\t\tbool withinOrdered(Vector3XYZ from, Vector3XYZ to)\n\t\t{\n\t\t\tassert(from.x <= to.x);\n\t\t\tassert(from.y <= to.y);\n\t\t\tassert(from.z <= to.z);\n\t\t\treturn x >= from.x && x <= to.x\n\t\t\t    && y >= from.y && y <= to.y\n\t\t\t    && z >= from.z && z <= to.z;\n\t\t}\n\n\t\ttemplate <typename U = T>\n\t\t[[nodiscard]]\n\t\tconstexpr T lengthSquared() const\n\t\t{\n\t\t\tauto x = static_cast<U>(this->x);\n\t\t\tauto y = static_cast<U>(this->y);\n\t\t\tauto z = static_cast<U>(this->z);\n\t\t\treturn x * x + y * y + z * z;\n\t\t}\n\n\t\ttemplate <typename F = Float64>\n\t\t[[nodiscard]]\n\t\tF length() const\n\t\t{\n\t\t\tusing std::sqrt;\n\t\t\treturn sqrt(static_cast<F>(lengthSquared()));\n\t\t}\n\t};\n\n\tstatic_assert(std::is_trivial_v<Vector2XZ <Int>>);\n\tstatic_assert(std::is_trivial_v<Vector3XYZ<Int>>);\n\n\tstatic_assert(sizeof(Vector2XZ <Int>) == 2 * sizeof(Int));\n\tstatic_assert(sizeof(Vector3XYZ<Int>) == 3 * sizeof(Int));\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr bool operator==(Vector2XZ<T, Tag> a, Vector2XZ<T, Tag> b)\n\t{\n\t\treturn a.x == b.x && a.z == b.z;\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr bool operator==(Vector3XYZ<T, Tag> a, Vector3XYZ<T, Tag> b)\n\t{\n\t\treturn a.x == b.x && a.y == b.y && a.z == b.z;\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr bool operator!=(Vector2XZ<T, Tag> a, Vector2XZ<T, Tag> b)\n\t{\n\t\treturn !(a == b);\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr bool operator!=(Vector3XYZ<T, Tag> a, Vector3XYZ<T, Tag> b)\n\t{\n\t\treturn !(a == b);\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector2XZ<T, Tag>& operator+=(Vector2XZ<T, Tag>& a, Vector2XZ<T, Tag> b)\n\t{\n\t\ta.x += b.x;\n\t\ta.z += b.z;\n\t\treturn a;\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector3XYZ<T, Tag>& operator+=(Vector3XYZ<T, Tag>& a, Vector3XYZ<T, Tag> b)\n\t{\n\t\ta.x += b.x;\n\t\ta.y += b.y;\n\t\ta.z += b.z;\n\t\treturn a;\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector2XZ<T, Tag>& operator-=(Vector2XZ<T, Tag>& a, Vector2XZ<T, Tag> b)\n\t{\n\t\ta.x -= b.x;\n\t\ta.z -= b.z;\n\t\treturn a;\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector3XYZ<T, Tag>& operator-=(Vector3XYZ<T, Tag>& a, Vector3XYZ<T, Tag> b)\n\t{\n\t\ta.x -= b.x;\n\t\ta.y -= b.y;\n\t\ta.z -= b.z;\n\t\treturn a;\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector2XZ<T, Tag> operator+(Vector2XZ<T, Tag> a, Vector2XZ<T, Tag> b)\n\t{\n\t\treturn {a.x + b.x, a.z + b.z};\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector3XYZ<T, Tag> operator+(Vector3XYZ<T, Tag> a, Vector3XYZ<T, Tag> b)\n\t{\n\t\treturn {a.x + b.x, a.y + b.y, a.z + b.z};\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector2XZ<T, Tag> operator-(Vector2XZ<T, Tag> a, Vector2XZ<T, Tag> b)\n\t{\n\t\treturn {a.x - b.x, a.z - b.z};\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector3XYZ<T, Tag> operator-(Vector3XYZ<T, Tag> a, Vector3XYZ<T, Tag> b)\n\t{\n\t\treturn {a.x - b.x, a.y - b.y, a.z - b.z};\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector2XZ<T, Tag> operator*(Vector2XZ<T, Tag> v, typename Identity<T>::Type n)\n\t{\n\t\treturn {v.x * n, v.z * n};\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector3XYZ<T, Tag> operator*(Vector3XYZ<T, Tag> v, typename Identity<T>::Type n)\n\t{\n\t\treturn {v.x * n, v.y * n, v.z * n};\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector2XZ<T, Tag> operator*(typename Identity<T>::Type n, Vector2XZ<T, Tag> v)\n\t{\n\t\treturn {n * v.x, n * v.z};\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector3XYZ<T, Tag> operator*(typename Identity<T>::Type n, Vector3XYZ<T, Tag> v)\n\t{\n\t\treturn {n * v.x, n * v.y, n * v.z};\n\t}\n\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector2XZ<T, Tag> operator/(Vector2XZ<T, Tag> v, typename Identity<T>::Type n)\n\t{\n\t\treturn {v.x / n, v.z / n};\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector3XYZ<T, Tag> operator/(Vector3XYZ<T, Tag> v, typename Identity<T>::Type n)\n\t{\n\t\treturn {v.x / n, v.y / n, v.z / n};\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector2XZ<T, Tag> operator/(typename Identity<T>::Type n, Vector2XZ<T, Tag> v)\n\t{\n\t\treturn {n / v.x, n / v.z};\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tconstexpr Vector3XYZ<T, Tag> operator/(typename Identity<T>::Type n, Vector3XYZ<T, Tag> v)\n\t{\n\t\treturn {n / v.x, n / v.y, n / v.z};\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tstd::string toString(Vector2XZ<T, Tag> v)\n\t{\n\t\treturn '(' + std::to_string(v.x) + ',' + ' ' + std::to_string(v.z) + ')';\n\t}\n\n\ttemplate <typename T, typename Tag>\n\tstd::string toString(Vector3XYZ<T, Tag> v)\n\t{\n\t\treturn '(' + std::to_string(v.x) + ',' + ' ' + std::to_string(v.y) + ',' + ' ' + std::to_string(v.z) + ')';\n\t}\n}\n\nnamespace std\n{\n\ttemplate <typename T, typename Tag>\n\tstruct hash<vitamine::Vector2XZ<T, Tag>>\n\t{\n\t\tstd::size_t operator()(vitamine::Vector2XZ<T, Tag> v) const noexcept\n\t\t{\n\t\t\treturn boost::hash_value(std::tie(v.x, v.z));\n\t\t}\n\t};\n\n\ttemplate <typename T, typename Tag>\n\tstruct hash<vitamine::Vector3XYZ<T, Tag>>\n\t{\n\t\tstd::size_t operator()(vitamine::Vector3XYZ<T, Tag> v) const noexcept\n\t\t{\n\t\t\treturn boost::hash_value(std::tie(v.x, v.y, v.z));\n\t\t}\n\t};\n\n\ttemplate <typename T, typename Tag>\n\tstruct less<vitamine::Vector2XZ<T, Tag>>\n\t{\n\t\tconstexpr bool operator()(vitamine::Vector2XZ<T, Tag> a, vitamine::Vector2XZ<T, Tag> b) const noexcept\n\t\t{\n\t\t\tif(a.x < b.x)\n\t\t\t\treturn true;\n\n\t\t\tif(a.x > b.x)\n\t\t\t\treturn false;\n\n\t\t\treturn a.z < b.z;\n\t\t}\n\t};\n\n\ttemplate <typename T, typename Tag>\n\tstruct less<vitamine::Vector3XYZ<T, Tag>>\n\t{\n\t\tconstexpr bool operator()(vitamine::Vector3XYZ<T, Tag> a, vitamine::Vector3XYZ<T, Tag> b) const noexcept\n\t\t{\n\t\t\tif(a.x < b.x)\n\t\t\t\treturn true;\n\n\t\t\tif(a.x > b.x)\n\t\t\t\treturn false;\n\n\t\t\tif(a.y < b.y)\n\t\t\t\treturn true;\n\n\t\t\tif(a.y > b.y)\n\t\t\t\treturn false;\n\n\t\t\treturn a.z < b.z;\n\t\t}\n\t};\n}\n", "meta": {"hexsha": "af7ac5f717bdf0d635afc5e6d3f4092c905f13c9", "size": 6885, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/common/vector.hpp", "max_stars_repo_name": "mgrech/vitamine", "max_stars_repo_head_hexsha": "d2fab653a0146b0ad9eb40d62213c968af2a100b", "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": "source/common/vector.hpp", "max_issues_repo_name": "mgrech/vitamine", "max_issues_repo_head_hexsha": "d2fab653a0146b0ad9eb40d62213c968af2a100b", "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": "source/common/vector.hpp", "max_forks_repo_name": "mgrech/vitamine", "max_forks_repo_head_hexsha": "d2fab653a0146b0ad9eb40d62213c968af2a100b", "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.798013245, "max_line_length": 109, "alphanum_fraction": 0.6187363834, "num_tokens": 2230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5471682168945176}}
{"text": "// Author(s)     : Michael Hemmer <mhemmer@uni-mainz.de>\n\n\n\n/*! \\file CGAL/Residue.C\n  test for number type modul \n*/\n\n#include <CGAL/basic.h>\n#include <cassert>\n#include <CGAL/Residue.h>\n#include <CGAL/Modular_traits.h>\n#include <CGAL/Sqrt_extension.h>\n#include <CGAL/Polynomial.h>\n#include <CGAL/Lazy_exact_nt.h>\n//#include <CGAL/MP_Float.h>\n \n\n#ifdef CGAL_USE_LEDA\n#include <CGAL/leda_integer.h>\n#include <CGAL/leda_rational.h>\n#endif // CGAL_USE_LEDA\n\n#ifdef CGAL_USE_CORE\n#include <CGAL/CORE_BigInt.h>\n#endif // CGAL_USE_CORE\n\n#ifdef CGAL_USE_GMP\n#include <CGAL/Gmpz.h>\n#endif\n\n#ifdef CGAL_USE_GMPXX\n#include <CGAL/mpz_class.h>\n#endif // CGAL_USE_GMP\n\n\n\n#include <cstdlib>\n\n#include <boost/type_traits.hpp>\n\ntemplate <class TESTT>\nvoid test_modular_traits(){\n\n        typedef CGAL::Residue Residue;\n        typedef CGAL::Modular_traits<TESTT> MT;\n        typedef typename MT::Residue_type Residue_type;\n        typedef typename MT::Modular_image Modular_image;\n        typedef typename MT::Modular_image_representative Modular_image_representative;\n        typedef typename MT::Is_modularizable Is_modularizable;\n        typedef typename MT::NT NT;\n        \n        assert(\n            !(::boost::is_same<CGAL::Null_functor,Modular_image>::value));\n        assert(\n            !(::boost::is_same<CGAL::Null_functor,Modular_image_representative>::value));\n        assert(\n            (::boost::is_same<CGAL::Tag_true,Is_modularizable>::value));\n        assert(\n            (::boost::is_same<TESTT,NT>::value));\n        \n        Residue::set_current_prime(7);\n        Modular_image modular_image;\n        assert(modular_image(TESTT(10)+TESTT(10)) == Residue_type(-1)); \n        assert(modular_image(TESTT(2) *TESTT(10)) == Residue_type(-1)); \n        assert(modular_image(TESTT(20)) == Residue_type(-1)); \n        assert(modular_image(TESTT(20)) == Residue_type(6));   \n        assert(modular_image(TESTT(21)) == Residue_type(0));   \n        assert(modular_image(TESTT(22)) == Residue_type(1));\n        assert(modular_image(TESTT(777777722)) == Residue_type(1));\n\n        Modular_image_representative modular_image_representative;\n        assert(modular_image_representative(modular_image(TESTT(20)))\n            == TESTT(-1)); \n}\n\nint main()\n{ \n  // Enforce IEEE double precision and rounding mode to nearest\n  CGAL::Protect_FPU_rounding<true> pfr(CGAL_FE_TONEAREST);\n  \n    test_modular_traits<int>();\n   \n#ifdef CGAL_USE_LEDA\n    test_modular_traits<leda::integer>();\n    test_modular_traits<CGAL::Polynomial< leda::integer > >();\n    test_modular_traits<CGAL::Lazy_exact_nt< leda::integer > >();\n    test_modular_traits<CGAL::Sqrt_extension< leda::integer , leda::integer > >();\n#endif\n#ifdef CGAL_USE_CORE\n    test_modular_traits<CORE::BigInt>();\n    test_modular_traits<CGAL::Polynomial< CORE::BigInt > >();\n    test_modular_traits<CGAL::Lazy_exact_nt< CORE::BigInt > >();\n    test_modular_traits<CGAL::Sqrt_extension< CORE::BigInt , CORE::BigInt > >();\n#endif\n\n#ifdef CGAL_USE_GMP\n    test_modular_traits<CGAL::Gmpz>();\n#endif \n\n#ifdef CGAL_USE_GMPXX\n    test_modular_traits< mpz_class >();\n#endif\n    \n    // test Sqrt_extension\n    test_modular_traits<CGAL::Sqrt_extension< int , int > >();\n    assert(\n        (!CGAL::Modular_traits<CGAL::Sqrt_extension<double,double> >\n            ::Is_modularizable::value));\n\n    // test Polynomial \n    test_modular_traits<CGAL::Polynomial< int > >();\n    assert(\n        !CGAL::Modular_traits<CGAL::Polynomial<double> >\n        ::Is_modularizable::value);\n\n    // test_modular_traits<CGAL::MP_Float >();\n    \n    test_modular_traits< CGAL::Lazy_exact_nt<int> >();\n    assert(\n        !CGAL::Modular_traits<CGAL::Lazy_exact_nt< double > >\n        ::Is_modularizable::value);\n    \n    \n}\n", "meta": {"hexsha": "93367ed86ffd44575903890e34e5008907443f2a", "size": 3738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Modular_arithmetic/test/Modular_arithmetic/Modular_traits.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/Modular_arithmetic/test/Modular_arithmetic/Modular_traits.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/Modular_arithmetic/test/Modular_arithmetic/Modular_traits.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.6666666667, "max_line_length": 89, "alphanum_fraction": 0.6757624398, "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.547168211662922}}
{"text": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <limits>\n#include <cmath>\n\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\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\ntypedef traits::vertex_descriptor vertex_desc;\ntypedef traits::edge_descriptor edge_desc;\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;\n\n// Custom edge adder class, highly recommended\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\nstruct edge {\n  int u;\n  int v;\n  int length;\n  int width;\n};\n\n// Strategy:\n// - Find all edges that are part of some shortest path\n// - Run a max-flow algorithm on those edges\nvoid solve() {\n  int n, m, s, f;\n  cin >> n >> m >> s >> f;\n\n  // Dijkstra Graph\n  weighted_graph G(n);\n\n  // Read neighbors\n  vector<edge> edges;\n  edges.reserve(m);\n  int u, v, length, width;\n  for (int i = 0; i < m; ++i) {\n    cin >> u >> v >> width >> length;\n    boost::add_edge(u, v, length, G);\n    edges.push_back({u, v, length, width});\n  }\n\n  // Run dijkstra\n  std::vector<int> d(n);\n  boost::dijkstra_shortest_paths(G, s, boost::distance_map(boost::make_iterator_property_map( d.begin(), boost::get(boost::vertex_index, G))));\n\n  // Flow graph\n  graph gFlow(n);\n  edge_adder adder(gFlow);\n\n\n  // Find edges on a shortest path\n  vector<edge> shortestPathEdges;\n  for (auto e : edges) {\n    int diff = d[e.v] - d[e.u];\n    if (e.length == diff) {\n      adder.add_edge(e.u, e.v, e.width);\n    }\n    else if (e.length == -diff) {\n      adder.add_edge(e.v, e.u, e.width);\n    }\n  }\n\n  // Compute flow\n  long flow = boost::push_relabel_max_flow(gFlow, s, f);\n  cout << flow << endl;\n}\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  int t; cin >> t;\n  while (t--)\n  {\n    solve();\n  }\n  return 0;\n}", "meta": {"hexsha": "78717488868197856f00716acf0d39ce09277e21", "size": 2797, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/marathon.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/marathon.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/marathon.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.6380952381, "max_line_length": 143, "alphanum_fraction": 0.6628530568, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417088, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5471650397688306}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n//\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\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\n\ntemplate <typename Geometry>\nvoid test_circle(std::string const& wkt_geometry, bool expected)\n{\n    typedef bg::model::nsphere<bg::model::d2::point_xy<double>, double> circle_type;\n    circle_type circle;\n    bg::assign(circle, 1.0, 1.0, 3.0);\n\n    Geometry geometry;\n    bg::read_wkt(wkt_geometry, geometry);\n\n    /* todo: fix\n    bool detected = bg::within(geometry, circle);\n\n    BOOST_CHECK_MESSAGE(detected == expected,\n        \"within: \" << wkt_geometry\n        << \" in circle (1,1) with radius 3\"\n        << \" -> Expected: \" << expected\n        << \" detected: \" << detected);\n    */\n}\n\n\n\n\ntemplate <typename P>\nvoid test_circles()\n{\n    test_circle<P>(\"POINT(2 1)\", true);\n    test_circle<P>(\"POINT(12 1)\", false);\n\n    test_circle<bg::model::linestring<P> >(\"LINESTRING(1 1,2 1,2 2)\", true);\n    test_circle<bg::model::linestring<P> >(\"LINESTRING(1 1,2 1,2 2,10 10)\", false);\n}\n\n\nint test_main( int , char* [] )\n{\n    test_circles<bg::model::d2::point_xy<double> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "497d66b279d60f5920c1258f4f90338b12a3c43e", "size": 1604, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test_extensions/nsphere/within.cpp", "max_stars_repo_name": "juslee/boost-svn", "max_stars_repo_head_hexsha": "6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:55:56.000Z", "max_issues_repo_path": "libs/geometry/extensions/test/nsphere/within.cpp", "max_issues_repo_name": "graehl/boost", "max_issues_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "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/extensions/test/nsphere/within.cpp", "max_forks_repo_name": "graehl/boost", "max_forks_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "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.2950819672, "max_line_length": 84, "alphanum_fraction": 0.677680798, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5471537702779564}}
{"text": "#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <fmt/format.h>\n#include <string>\n#include <iomanip>\n#include <boost/variant.hpp>\n#include <unordered_map>\n#include <range/v3/all.hpp>\n#include \"combinations_algo.h\"\n#include \"matrix.h\"\nstruct Combinations\n{\n  FixedMatrix<int, 8, 8> networks_;\n  std::array<int, 8> a = { 0, 1, 2, 3, 4, 5, 6, 7 };\n  int min = std::numeric_limits<int>::max();\n  int min_distance() noexcept\n  {\n    auto f = [this](auto b, auto e) {\n      int s = 0;\n      for (; b != e - 1; ++b) {\n        s += networks_(*b, *(b + 1));\n      }\n      min = std::min(s, min);\n      return false;\n    };\n    for_each_reversible_permutation(a.begin(), a.end(), a.end(), f);\n    return min;\n  }\n};\nint main(int argc, char **argv)\n{\n  if (argc > 1) {\n    Combinations com;\n    std::ifstream ifs(argv[1]);\n    std::string s;\n    for (int i = 0; i < 7; ++i) {\n      int row = i;\n\n      int col = i + 1;\n      for (; col < 8; ++col) {\n        std::getline(ifs, s);\n        std::istringstream iss(s);\n        std::string ignore;\n        int value;\n        iss >> ignore >> ignore >> ignore >> ignore >> value;\n        com.networks_(row, col) = value;\n        com.networks_(col, row) = value;\n      }\n    }\n    std::cout << com.networks_ << std::endl;\n    std::cout << com.min_distance() << std::endl;\n  }\n}", "meta": {"hexsha": "5825d17824f63944586be5eb28075c0becaf0e4b", "size": 1346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc2015/aoc150901.cpp", "max_stars_repo_name": "jiayuehua/adventOfCode", "max_stars_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "aoc2015/aoc150901.cpp", "max_issues_repo_name": "jiayuehua/adventOfCode", "max_issues_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "aoc2015/aoc150901.cpp", "max_forks_repo_name": "jiayuehua/adventOfCode", "max_forks_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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.4727272727, "max_line_length": 68, "alphanum_fraction": 0.5497771174, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5471537533956279}}
{"text": "#include <igl/eigs.h>\n#include <igl/cotmatrix.h>\n#include <igl/massmatrix.h>\n#include <igl/opengl/glfw/Viewer.h>\n#include <igl/parula.h>\n#include <igl/read_triangle_mesh.h>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <queue>\n#include \"tutorial_shared_path.h\"\n\nEigen::MatrixXd V,U;\nEigen::MatrixXi F;\nint c=0;\ndouble bbd = 1;\nbool twod = 0;\nint main(int argc, char * argv[])\n{\n  using namespace Eigen;\n  using namespace std;\n  using namespace igl;\n  VectorXd D;\n  if(!read_triangle_mesh(\n     argc>1?argv[1]: TUTORIAL_SHARED_PATH \"/beetle.off\",V,F))\n  {\n    cout<<\"failed to load mesh\"<<endl;\n  }\n  twod = V.col(2).minCoeff()==V.col(2).maxCoeff();\n  bbd = (V.colwise().maxCoeff()-V.colwise().minCoeff()).norm();\n  SparseMatrix<double> L,M;\n  cotmatrix(V,F,L);\n  L = (-L).eval();\n  massmatrix(V,F,MASSMATRIX_TYPE_DEFAULT,M);\n  const size_t k = 5;\n  if(!eigs(L,M,k+1,EIGS_TYPE_SM,U,D))\n  {\n    cout<<\"failed.\"<<endl;\n  }\n  // Normalize\n  U = ((U.array()-U.minCoeff())/(U.maxCoeff()-U.minCoeff())).eval();\n\n  igl::opengl::glfw::Viewer viewer;\n  viewer.callback_key_down = [&](igl::opengl::glfw::Viewer & viewer,unsigned char key,int)->bool\n  {\n    switch(key)\n    {\n      default:\n        return false;\n      case ' ':\n      {\n        U = U.rightCols(k).eval();\n        // Rescale eigen vectors for visualization\n        VectorXd Z =\n          bbd*0.5*U.col(c);\n        Eigen::MatrixXd C;\n        igl::parula(U.col(c).eval(),false,C);\n        c = (c+1)%U.cols();\n        if(twod)\n        {\n          V.col(2) = Z;\n        }\n        viewer.data().set_mesh(V,F);\n        viewer.data().compute_normals();\n        viewer.data().set_colors(C);\n        return true;\n      }\n    }\n  };\n  viewer.callback_key_down(viewer,' ',0);\n  viewer.data().show_lines = false;\n  std::cout<<\nR\"(\n  [space] Cycle through eigen modes\n)\";\n  viewer.launch();\n}\n", "meta": {"hexsha": "579ef7d8c2b00ba187afbcc34ee94adc4ed1d2b5", "size": 1841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isometric-deformation/ext/libigl/tutorial/306_EigenDecomposition/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/306_EigenDecomposition/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/306_EigenDecomposition/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": 23.9090909091, "max_line_length": 96, "alphanum_fraction": 0.5958718088, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5471537482923506}}
{"text": "/*\n * \u8fd9\u662f TJU Robomasters \u4e0a\u4f4d\u673a\u6e90\u7801\uff0c\u672a\u7ecf\u7ba1\u7406\u5c42\u5141\u8bb8\u4e25\u7981\u4f20\u64ad\u7ed9\u5176\u4ed6\u4eba\uff08\u5305\u62ec\u961f\u5185\u4ee5\u53ca\u961f\u5916\uff09\n *\n * \u8be5\u6587\u4ef6\u5305\u542b\u5404\u79cd\u9884\u6d4b\u6a21\u578b\uff0c\u5e76\u5c01\u88c5\u5230\u4e86\u4ee5\u62bd\u8c61\u7c7bPredictor\u7c7b\u4e3a\u57fa\u7c7b\u7684\u7c7b\u4e2d\n */\n\n#pragma once\n\n#include <opencv2/opencv.hpp>\n#include <Eigen/Dense>\n#include \"util.hpp\"\n#include <atomic>\n#include \"KalmanFilter.hpp\"\nusing namespace cv;\n\ntypedef struct _prd_path_pt{\n\n    Point3f worldPosition;\n    Point2f targetPTZAngle;\n    Point2f selfWorldPosition;\n    double duration;\n\n    _prd_path_pt(Point3d _worldp,Point2f _tgtAngle,Point2f _sfworldp,float _dur)\n    {\n        worldPosition = _worldp;\n        targetPTZAngle = _tgtAngle;\n        selfWorldPosition = _sfworldp;\n        duration = _dur;\n    }\n\n    _prd_path_pt()\n    { }\n\n}PredictionPathPoint;\n\n\nclass Predictor\n{\npublic:\n    // \u6dfb\u52a0\u4e00\u4e2a\u8f68\u8ff9\u70b9\uff0c\u8be5\u51fd\u6570\u5e94\u8be5\u80fd\u591f\u81ea\u4e3b\u7504\u522b\u8f68\u8ff9\u70b9\u662f\u5426\u4e0e\u4e4b\u524d\u8ffd\u8e2a\u7684\u76ee\u6807\u4e00\u6837\uff0c\u5982\u679c\u4e0d\u662f\n    // \u9884\u6d4b\u5668\u81ea\u52a8\u6e05\u7a7a\u5386\u53f2\u6570\u636e\u91cd\u65b0\u5f00\u59cb\u9884\u6d4b\n    virtual void AddPredictPoint(PredictionPathPoint ppp) = 0;\n\n    // \u9884\u6d4b\u4e00\u6bb5\u65f6\u95f4\u4e4b\u540e\u76ee\u6807\u7684\u4f4d\u7f6e\n    virtual void Predict(double prdTime) = 0;\n    \n    // \u4e3b\u52a8\u6e05\u9664\u5386\u53f2\u8bb0\u5f55\n    virtual void ClearHistory() = 0;\n};\n// \u7ebf\u6027\u9884\u6d4b\u5668\uff0c\u7531\u5386\u53f2\u6570\u636e\u7ed9\u51fa\u7ebf\u6027\u7684\u9884\u6d4b\uff08\u5047\u8bbe\u76ee\u6807\u5300\u901f\u76f4\u7ebf\u8fd0\u52a8\uff09\nclass KFCPredictor : public Predictor\n{\npublic:\n    static const int HistorySize = 6;\n    Mat P, Q, H, R, F, K, x_;\n    int xstate = 0;\n    PredictionPathPoint present;\n    PredictionPathPoint lastpoint;\n    \n    KFCPredictor()\n    {\n        Mat P_in = Mat::eye(6,6,CV_32FC1);\n        Mat Q_in = Mat::eye(6,6,CV_32FC1);\n        Mat H_in = Mat::eye(6,6,CV_32FC1);\n        Mat R_in = Mat::eye(6,6,CV_32FC1);\n        P = P_in;\n        Q = Q_in;\n        H = H_in;\n        R = R_in;\n        lastpoint.targetPTZAngle=Point2f(0,0);\n    }\n    \n    KFCPredictor(Mat P_in, Mat Q_in, Mat H_in, Mat R_in)\n    {\n        P = P_in;\n        Q = Q_in;\n        H = H_in;\n        R = R_in;\n        lastpoint.targetPTZAngle=Point2f(0,0);\n    }\n    \n    void AddPredictPoint(PredictionPathPoint ppp)\n    {\n        if (Length(ppp.targetPTZAngle - lastpoint.targetPTZAngle) > 10)\n            ClearHistory();\n        present = ppp;\n    }\n    \n    void ClearHistory()\n    {\n        xstate = 0;\n        P = Mat::eye(6,6,CV_32FC1);\n    };\n\n    void FirstFind()\n    {\n        p_tx_old = present.worldPosition.x;\n        p_ty_old = present.worldPosition.y;\n        p_tz_old = present.worldPosition.z;\n        lastpoint = present;\n    }\n\n    void FirstSetFilter()\n    {\n        //\u5c06\u89c6\u89c9\u6839\u636e\u56fe\u50cf\u8ba1\u7b97\u51fa\u7684\u88c5\u7532\u677f\u5728\u76f8\u673a\u5750\u6807\u7cfb\u4e0b\u7684\u4f4d\u7f6e\u4f20\u7ed9\u9884\u6d4b\u7c7b\u4e2d\u7684worldposition \n        //\u4ee5\u5f53\u524d\u7684\u8ba1\u7b97\u4f5c\u4e3a\u6839\u636e\u4e0a\u4e00\u6b21\u8ba1\u7b97\u8fdb\u884c\u9884\u6d4b\u7684\u89c2\u6d4b\u503c\n        double t = present.duration;\n        float v_tx_now = (present.worldPosition.x - p_tx_old)/t;\n        float v_ty_now =(present.worldPosition.y - p_ty_old)/t;\n        float v_tz_now = (present.worldPosition.z - p_tz_old)/t;\n        x_ = (Mat_<float>(6,1) <<\n                   present.worldPosition.x, present.worldPosition.y, present.worldPosition.z,\n                   v_tx_now, v_ty_now, v_tz_now\n                   );\n        xstate = 1;\n        p_tx_old = present.worldPosition.x;\n        p_ty_old = present.worldPosition.y;\n        p_tz_old = present.worldPosition.z;\n        lastpoint = present;\n    }\n    void ContinueSetFilter()\n    {\n        double t = present.duration;\n        float v_tx_now = (present.worldPosition.x - p_tx_old)/t;\n        float v_ty_now = (present.worldPosition.y - p_ty_old)/t;\n        float v_tz_now = (present.worldPosition.z - p_tz_old)/t;\n\n        Mat z = (Mat_<float>(6,1) <<\n                   present.worldPosition.x, present.worldPosition.y, present.worldPosition.z,\n                   v_tx_now, v_ty_now, v_tz_now\n                   );\n\n        Predict(t);\n        update(z);\n\n        p_tx_old = x_.at<float>(0, 0);\n        p_ty_old = x_.at<float>(1, 0);\n        p_tz_old = x_.at<float>(2, 0);\n        lastpoint = present;\n    }\n\n    void Predict(double prdTime)\n    {\n        double t = prdTime;\n        F = (Mat_<float>(6,6) <<\n                   1.0, 0.0, 0.0, t, 0.0, 0.0,\n                   0.0, 1.0, 0.0, 0.0, t, 0.0,\n                   0.0, 0.0, 1.0, 0.0, 0.0, t,\n                   0.0, 0.0, 0.0, 1.0, 0.0, 0.0,\n                   0.0, 0.0, 0.0, 0.0, 1.0,0.0,\n                   0.0, 0.0, 0.0, 0.0, 0.0, 1.0\n                   );\n        //\u8d77\n        x_ = F * x_;\n        // return Point3f(x_.at<float>(0,0),x_.at<float>(0,1),x_.at<float>(0,2));\n    }\n\n    void update(Mat z)\n    {\n        //\u6309\n        P = F*P*F.t() + Q;\n        //\u987f\n        Mat S = H*P*H.t() + R; \n        K = P*H.t()*S.inv();\n        //\u632b\n        Mat y = z - H*x_;\n        x_ = x_ + (K*y);\n        //\u4e0b\u7b14\u98ce\u96f7\n        Mat I = Mat::eye(6,6,CV_32FC1);\n        P = (I - K*H)*P;\n    }\nprotected:\n    float p_tx_old;                  //\u4f4d\u7f6e\u4fdd\u7559\u91cf\n    float p_ty_old;\n    float p_tz_old;\n};\n\nclass AnglePredictor : public Predictor\n{\npublic:\n    \n    Mat P, Q, H, R, F, K, x_;\n    int xstate = 0;\n    PredictionPathPoint present;\n    PredictionPathPoint lastpoint;\n    \n    AnglePredictor()\n    {\n        Mat P_in = Mat::eye(4,4,CV_32FC1);\n        Mat Q_in = (Mat_<float>(4,4) <<\n                   5,0,0,0,\n                   0,1,0,0,\n                   0,0,5,0,\n                   0,0,0,1\n                   );\n        Mat H_in = (Mat_<float>(2,4) <<\n                   1,0,0,0,\n                   0,1,0,0\n                   );\n        Mat R_in = (Mat_<float>(2,2) <<\n                   200,0,\n                   0,200\n                   );\n        P = P_in;\n        Q = Q_in;\n        H = H_in;\n        R = R_in;\n        lastpoint.targetPTZAngle=Point2f(0,0);\n    }\n    \n    AnglePredictor(Mat P_in, Mat Q_in, Mat H_in, Mat R_in)\n    {\n        P = P_in;\n        Q = Q_in;\n        H = H_in;\n        R = R_in;\n        lastpoint.targetPTZAngle=Point2f(0,0);\n    }\n    \n    void AddPredictPoint(PredictionPathPoint ppp)\n    {\n        if (Length(ppp.targetPTZAngle - lastpoint.targetPTZAngle) > 10)\n            ClearHistory();\n        present = ppp;\n    }\n    \n    void ClearHistory()\n    {\n        xstate = 0;\n        P = Mat::eye(4,4,CV_32FC1);\n    };\n\n    void FirstFind()\n    {\n        \n        lastpoint = present;\n    }\n\n    void FirstSetFilter()\n    {\n        double t = present.duration;\n        float vx = (present.targetPTZAngle.x - lastpoint.targetPTZAngle.x)/t;\n        float vy =(present.targetPTZAngle.y - lastpoint.targetPTZAngle.y)/t;\n        \n        x_ = (Mat_<float>(4,1) <<\n                   present.targetPTZAngle.x, present.targetPTZAngle.y,\n                   vx, vy\n                   );\n        xstate = 1;\n        \n        lastpoint = present;\n    }\n    void ContinueSetFilter()\n    {\n        double t = present.duration;\n        float vx = (present.targetPTZAngle.x - lastpoint.targetPTZAngle.x)/t;\n        float vy =(present.targetPTZAngle.y - lastpoint.targetPTZAngle.y)/t;\n        Mat z = (Mat_<float>(2,1) <<\n                   present.targetPTZAngle.x, present.targetPTZAngle.y\n                   );\n\n        Predict(t);\n        update(z);\n        // cout << \"presemtangle: \" << present.targetPTZAngle << \" lastangle: \" << lastpoint.targetPTZAngle << endl;\n        // cout << \"speedx: \" << (present.targetPTZAngle.x-lastpoint.targetPTZAngle.x)/present.duration << endl;\n        // cout << \"speedy: \" << (present.targetPTZAngle.y-lastpoint.targetPTZAngle.y)/present.duration << endl;\n        lastpoint = present;\n    }\n\n    void Predict(double prdTime)\n    {\n        double t = prdTime;\n        F = (Mat_<float>(4,4) <<\n                   1.0, 0.0, t, 0.0, \n                   0.0, 1.0, 0.0, t, \n                   0.0, 0.0, 1.0, 0.0, \n                   0.0, 0.0, 0.0, 1.0\n                   );\n        //\u8d77\n        x_ = F * x_;\n        \n        //return Point2f(myx_.at<float>(0,0),myx_.at<float>(0,1));\n    }\n    Point2f PredictReal(double prdTime)\n    {\n        double t = prdTime;\n        F = (Mat_<float>(4,4) <<\n                   1.0, 0.0, t, 0.0, \n                   0.0, 1.0, 0.0, t, \n                   0.0, 0.0, 1.0, 0.0, \n                   0.0, 0.0, 0.0, 1.0\n                   );\n        //\u8d77\n        \n        Mat myx_ = F * x_;\n        return Point2f(myx_.at<float>(0,0),myx_.at<float>(0,1));\n    }\n\n    void update(Mat z)\n    {\n        //\u6309\n        P = F*P*F.t() + Q;\n        //\u987f\n        Mat S = H*P*H.t() + R; \n        K = P*H.t()*S.inv();\n        //\u632b\n        Mat y = z - H*x_;\n        x_ = x_ + (K*y);\n        //\u4e0b\u7b14\u98ce\u96f7\n        Mat I = Mat::eye(4,4,CV_32FC1);\n        P = (I - K*H)*P;\n    }\n};\n\nclass KalmanPredictor{\npublic:\nKalmanPredictor(){\n\n\tEigen::MatrixXd A(stateSize, stateSize);\n\tA << 1, 0, 1, 0,\n\t\t0, 1, 0, 1,\n\t\t0, 0, 1, 0,\n\t\t0, 0, 0, 1 ;\n\n\tEigen::MatrixXd H(measureSize, stateSize);\n\tH << 2, 0, 0, 0,\n\t\t0, 2, 0, 0,\n\t\t0, 0, 1, 0,\n\t\t0, 0, 0, 1;\n\n\tEigen::MatrixXd P(stateSize, stateSize);\n\tP << 1, 0, 0, 0,\n\t\t0, 1, 0, 0,\n\t\t0, 0, 1, 0,\n\t\t0, 0, 0, 1;\n\n\tEigen::MatrixXd Q(stateSize, stateSize);\n\tQ << 1, 0, 0, 0,\n\t\t0, 1, 0, 0,\n\t\t0, 0, 1, 0,\n\t\t0, 0, 0, 1;\n\n\tEigen::MatrixXd R(measureSize, measureSize);\n\tR << 900, 0, 0, 0,\n\t\t0, 900, 0, 0,\n\t\t0, 0, 700, 0,\n\t\t0, 0, 0, 700;\n\n\tKF.init(stateSize, measureSize, A, P, R, Q, H);\n\n\tx.resize(stateSize);\n\tx << 0, 0, 0, 0;\n}\npublic:\n\tEigen::MatrixXd F;\n\tEigen::VectorXd x;\n    cv::Point2f predict(float yaw, float pitch,float distance, float deltatime,int bulletSpeed) {\t\n\t    return kalmanPredict(yaw, pitch, (double)deltatime,distance/bulletSpeed * 0.001);\n\t}\n\n\tcv::Point2f kalmanPredict(float yaw, float pitch, double deltatime,float time){\n\tif (abs(x(0) - yaw) > 200) {\n\t\tx(0) = (double)yaw;\n\t\tyawSpeed = 0;\n\t\tx(2) = yawSpeed;\n\t}\n\tif (abs(x(2) - pitch) > 200) {\n\t\tx(1) = (double)pitch;\n\t\tpitchSpeed = 0;\n\t\tx(3) = pitchSpeed;\n\t}\n\n\tyawSpeed = (yaw - lastYaw) / deltatime;\n\tpitchSpeed = (pitch - lastPitch) / deltatime;\n\tif(abs(yawSpeed) > 50){\n\t\tyawSpeed = 0;\n\t}\n\tif(abs(pitchSpeed > 20)){\n\t\tpitchSpeed = 0;\n\t}\n\tEigen::VectorXd z(measureSize);\n\tEigen::VectorXd output;\n\tF = Eigen::MatrixXd(4, 4);\n\tcout << \"hello3\"<<endl;\n    F << 1.0,0.0,(double)deltatime,0.0,\n        0.0,1.0,0.0,(double)deltatime,\n        0.0,0.0,1.0,0.0,\n        0.0,0.0,0.0,1.0;\n\tz << (double)yaw, (double)pitch, (double)yawSpeed, (double)pitchSpeed;\n\tKF.predict(x,F);\n\tKF.update(x, z);\n\tlastYaw = yaw;\n\tlastPitch = pitch;\n\t//cout << \" X:\" << x(0) << \" v:\" << x(2) << endl;\n\tdouble predictYaw = x(0) + (time + 0.35) * x(2); \n\tdouble predictPitch = x(1) + (time + 0.35) * x(3);\n\n\treturn cv::Point2f((float)predictYaw, (float)predictPitch);\n}\nprivate:\n\tEigenKalman::KalmanFilter KF;\n\tdouble lastYaw;\n\tdouble lastPitch;\n\tdouble yawSpeed = 0;\n\tdouble pitchSpeed = 0;\n\tint measureSize = 4;\n\tint stateSize = 4;\npublic:\n\tatomic<int> shootSpeed;//\u53d1\u5c04\u901f\u5ea6 \u5355\u4f4d;\u7c73/\u79d2\n};\n", "meta": {"hexsha": "494f21d64d85d49eae9ff15edfeb290601c2a772", "size": 10351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "misc/predictor.hpp", "max_stars_repo_name": "LeonGoretzkatju/TJU_RM_VISION", "max_stars_repo_head_hexsha": "70c70c52de918f3e19bff01321c3fd64af590bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "misc/predictor.hpp", "max_issues_repo_name": "LeonGoretzkatju/TJU_RM_VISION", "max_issues_repo_head_hexsha": "70c70c52de918f3e19bff01321c3fd64af590bec", "max_issues_repo_licenses": ["MIT"], "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/predictor.hpp", "max_forks_repo_name": "LeonGoretzkatju/TJU_RM_VISION", "max_forks_repo_head_hexsha": "70c70c52de918f3e19bff01321c3fd64af590bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-22T11:33:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T11:33:35.000Z", "avg_line_length": 25.1849148418, "max_line_length": 116, "alphanum_fraction": 0.5195633272, "num_tokens": 3708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.547093339989821}}
{"text": "#include <iostream>\n#include <boost/concept_check.hpp>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_edge.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/solvers/dense/linear_solver_dense.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 <random>\n#include <chrono>\n#include <Eigen/Core>\n#include <opencv2/core/core.hpp>\n#include <cmath>\n\nusing namespace std;\nusing namespace g2o;\n\nclass hello_vertex: public BaseVertex<1, Eigen::Matrix<double,1,1>> {//\u6570\u636e\u7c7b\u578b\u8981\u4ee5Eigen::Matrix\u7ed9\u51fa,\u56e0\u4e3a\u9700\u8981\u8f6c\u7f6e\u64cd\u4f5c\n          /**\n         * update the position of the node from the parameters in v.\n         * Implement in your class!\n         */\n\t//optimizable_graph.h  \n        virtual void oplusImpl(const double* v) {\n\t\tcout << \"v: \" << *v << endl;\n\t\t_estimate(0,0) += *v;\t\t\t\t//_estimate\u7684\u7c7b\u578b\u5373\u4e3a\u7ee7\u627f\u6a21\u677f\u65f6\u4f20\u5165\u7684\u7c7b\u578b\n\t\tcout << \"_estimate: \" << _estimate(0,0) << endl;\n\t}\n\t\n        //! sets the node to the origin (used in the multilevel stuff)\n        //optimizable_graph.h\n        virtual void setToOriginImpl() {\n\t\tcout << \"setToOriginImpl \" << _estimate(0,0)  << endl;\n\t\t_estimate(0,0) = 0;\n\t}\n\t\n\t//! read the vertex from a stream, i.e., the internal state of the vertex\n        virtual bool read(std::istream& is) {}\n        //! write the vertex to a stream\n        virtual bool write(std::ostream& os) const {}\n};\n\nclass hello_edge: public BaseUnaryEdge<1, double, hello_vertex> {\n\t// computes the error of the edge and stores it in an internal structure\n\t//optimizable_graph.h\n        virtual void computeError() {\n\t\tconst hello_vertex* v = static_cast<const hello_vertex*> (_vertices[0]);\n\t\tconst Eigen::Matrix<double,1,1> est = v->estimate();\n\t\t//typedef Eigen::Matrix<double, D, 1, Eigen::ColMajor> ErrorVector;\n\t\t//_error = est - (Eigen::Matrix<double, 1, 1> )(10);\n\t\tcout << \"computeError: \" ;\n\t\t//_error(0,0) = _measurement - est(0,0);\n\t\t//\u6b64\u5904\u8bef\u5dee\u7684\u5b9a\u4e49\u5f71\u54cd\u540e\u7eed\u89e3\u6790\u6c42\u5bfc\u65f6Jacob\u77e9\u9635\u524d\u8fb9\u662f\u5426\u6dfb\u52a0\u8d1f\u53f7\n\t\t_error(0,0) = -_measurement + (est(0,0) + 1)*(est(0,0) + 1);\n\t\tcout << _error(0,0) << endl;\n\t}\n\t\n\tvirtual void linearizeOplus() {\n\t\tconst hello_vertex* v = static_cast<const hello_vertex*> (_vertices[0]);\n\t\tconst Eigen::Matrix<double,1,1> est = v->estimate();\n\t\t//\u9700\u8981\u63d0\u4f9b\u8d1f\u68af\u5ea6,\u4e0eCeres\u76f8\u540c\n\t\t//\u4e4b\u6240\u4ee5\u662f\u8d1f\u68af\u5ea6,\u56e0\u4e3aerr = _measurement - f(_estimate)\n\t\t//\u56e0\u6b64\u4e3a\u8d1f\u7684\n\t\t_jacobianOplusXi(0,0) = 2 * (est(0,0) + 1);\n\t\tcout << \"_jacobianOplusXi: \" << _jacobianOplusXi << endl;\n\t}\n\t\n\t//! read the vertex from a stream, i.e., the internal state of the vertex\n        virtual bool read(std::istream& is) {}\n        //! write the vertex to a stream\n        virtual bool write(std::ostream& os) const {}\n};\n/*\n *  default_random_engine generator;  \n *  normal_distribution<double> distribution(0.0,0.5);\n *  distribution(generator);\n */\n\n\n\nint main(int argc, char** argv)\n{\n\n\t// \u6784\u5efa\u56fe\u4f18\u5316\uff0c\u5148\u8bbe\u5b9ag2o\n\ttypedef g2o::BlockSolver< g2o::BlockSolverTraits<1,1> > Block;  // \u6bcf\u4e2a\u8bef\u5dee\u9879\u4f18\u5316\u53d8\u91cf\u7ef4\u5ea6\u4e3a3\uff0c\u8bef\u5dee\u503c\u7ef4\u5ea6\u4e3a1\n\tBlock::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>(); // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n\tBlock* solver_ptr = new Block( linearSolver );      // \u77e9\u9635\u5757\u6c42\u89e3\u5668\n\t// \u68af\u5ea6\u4e0b\u964d\u65b9\u6cd5\uff0c\u4eceGN, LM, DogLeg \u4e2d\u9009\n\tg2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg( solver_ptr );\n\t// g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton( solver_ptr );\n\t// g2o::OptimizationAlgorithmDogleg* solver = new g2o::OptimizationAlgorithmDogleg( solver_ptr );\n\tg2o::SparseOptimizer optimizer;     // \u56fe\u6a21\u578b\n\toptimizer.setAlgorithm( solver );   // \u8bbe\u7f6e\u6c42\u89e3\u5668\n\toptimizer.setVerbose( true );       // \u6253\u5f00\u8c03\u8bd5\u8f93\u51fa\n\n\t// \u5f80\u56fe\u4e2d\u589e\u52a0\u9876\u70b9\n\thello_vertex* v = new hello_vertex();\n\tv->setEstimate((Eigen::Matrix<double,1,1>) 100);\n\tv->setId(0);\n\toptimizer.addVertex( v );\n\n\t//\u52a0\u8fb9\n\thello_edge* edge = new hello_edge;\n\tedge->setId(0);\n\tedge->setVertex( 0, v );                // \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n\tedge->setMeasurement(66.6);      // \u89c2\u6d4b\u6570\u503c\n\tedge->setInformation(Eigen::Matrix<double,1,1>::Identity()*0.25); // \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n\toptimizer.addEdge( edge );\n\n\t// \u6267\u884c\u4f18\u5316\n\tcout<<\"start optimization\"<<endl;\n\tchrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n\toptimizer.initializeOptimization();\n\toptimizer.optimize(100);\n\tchrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n\tchrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>( t2-t1 );\n\tcout<<\"solve time cost = \"<<time_used.count()<<\" seconds. \"<<endl;\n\n\t// \u8f93\u51fa\u4f18\u5316\u503c\n\tEigen::Matrix<double,1,1> abc_estimate = v->estimate();\n\tcout<<\"estimated value: \"<<abc_estimate.transpose()<<endl;\n\t\n\t\n\t\n\treturn 0;\n}\n\n\n\n", "meta": {"hexsha": "78d7fdb0b1028c45f12fd959e38c9e5f5b897458", "size": 4580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "g2o/hello_g2o/hello_g2o.cpp", "max_stars_repo_name": "JiauZhang/camera", "max_stars_repo_head_hexsha": "37e37f9e5f5176c6c06d4a8fdd11d5532ab37eb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-10-08T01:46:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-11T08:17:44.000Z", "max_issues_repo_path": "g2o/hello_g2o/hello_g2o.cpp", "max_issues_repo_name": "JiauZhang/Camera", "max_issues_repo_head_hexsha": "37e37f9e5f5176c6c06d4a8fdd11d5532ab37eb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "g2o/hello_g2o/hello_g2o.cpp", "max_forks_repo_name": "JiauZhang/Camera", "max_forks_repo_head_hexsha": "37e37f9e5f5176c6c06d4a8fdd11d5532ab37eb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-11T07:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-16T04:55:01.000Z", "avg_line_length": 34.696969697, "max_line_length": 108, "alphanum_fraction": 0.6840611354, "num_tokens": 1490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5470933345344567}}
{"text": "#pragma once\n\n#include <random>\n\n#include <boost/random.hpp>\n#include <boost/random/random_device.hpp>\n\n#include \"ContainerByBitness.hh\"\n#include \"RandomGenerator.hh\"\n#include \"Typedefs.hh\"\n\nnamespace cml {\n\ntemplate <Uint32 numberBitness, typename ResultType = typename ContainerByBitness<numberBitness>::Type>\nclass Mt19937RandomGenerator : public RandomGenerator<ResultType> {\npublic:\n    static constexpr Uint32 bitness = numberBitness;\n\n    using Base = RandomGenerator<ResultType>;\n    using typename Base::Result;\n    using Engine = boost::random::independent_bits_engine<std::mt19937, bitness, Result>;\n\n    Mt19937RandomGenerator() = default;\n    explicit Mt19937RandomGenerator(const typename Engine::result_type& seed) : m_randomEngine(seed) {}\n\n    Result random() override\n    {\n        return m_randomEngine();\n    }\n\n    Result random(Result min, Result max) override\n    {\n        boost::random::uniform_int_distribution<Result> uid{ min, max };\n        return uid(m_randomEngine);\n    }\n\nprivate:\n    Engine m_randomEngine{ boost::random::random_device{}() };\n};\n\n} // namespace cml", "meta": {"hexsha": "42d93ac5ec8ebbdaae7d2abd8e1e48b3cbd9d4a2", "size": 1099, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/cml/Mt19937RandomGenerator.hh", "max_stars_repo_name": "LazyMechanic/cml", "max_stars_repo_head_hexsha": "b99b3417d2196e741ed01256618f61c9715d252a", "max_stars_repo_licenses": ["MIT"], "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/cml/Mt19937RandomGenerator.hh", "max_issues_repo_name": "LazyMechanic/cml", "max_issues_repo_head_hexsha": "b99b3417d2196e741ed01256618f61c9715d252a", "max_issues_repo_licenses": ["MIT"], "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/cml/Mt19937RandomGenerator.hh", "max_forks_repo_name": "LazyMechanic/cml", "max_forks_repo_head_hexsha": "b99b3417d2196e741ed01256618f61c9715d252a", "max_forks_repo_licenses": ["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.8048780488, "max_line_length": 103, "alphanum_fraction": 0.728844404, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5470933341915325}}
{"text": "/*\n * MedianFillFilter.hpp\n *\n *  Created on: September 7, 2020\n *      Author: Magnus G\u00e4rtner\n *   Institute: ETH Zurich, ANYbotics\n */\n\n#pragma once\n\n#include <Eigen/Core>\n#include <string>\n\n#include <filters/filter_base.hpp>\n#include <grid_map_core/GridMap.hpp>\n#include <grid_map_core/TypeDefs.hpp>\n#include <opencv2/core.hpp>\n\nnamespace grid_map {\n\n/*!\n * Uses std::nth_element to fill holes in the input layer by the median of the surrounding values. The result is put into the output_layer.\n * Note: Only values for which the fill_layer is true will be filled. The fill_layer is auto computed if not present in the input.\n */\nclass MedianFillFilter : public filters::FilterBase<GridMap> {\n public:\n  /*!\n   * Constructor\n   */\n  MedianFillFilter();\n\n  /*!\n   * Destructor.\n   */\n  ~MedianFillFilter() override;\n\n  /*!\n   * Configures the filter from parameters on the Parameter Server\n   */\n  bool configure() override;\n\n  /*!\n   * Adds a new output layer to the map.\n   * Uses the Boost accumulator median in the input layer.\n   * Saves the filter output in mapOut[output_layer].\n   * @param mapIn grid map containing input layer\n   * @param mapOut grid map containing mapIn and median filtered input layer.\n   */\n  bool update(const GridMap& mapIn, GridMap& mapOut) override;\n\n protected:\n  /*!\n   * Returns the median of the values in inputData in the neighbourhood around the centerIndex. The size of the quadratic neighbourhood is\n   * specified by radiusInPixels. If the number of values is even the \"lower center\" value is taken, eg with four values the second lowest\n   * is taken as median.\n   * @param inputMap The data layer to compute a local median.\n   * @param centerIndex The center cell of the neighbourhood.\n   * @param radiusInPixels The maximum L_inf distance from index.\n   * @param bufferSize The buffer size of the input\n   * @return The median of finites in the specified neighbourhood.\n   */\n  static float getMedian(Eigen::Ref<const Matrix> inputMap, const Index& centerIndex, size_t radiusInPixels, Size bufferSize);\n\n  /**\n   * Computes a mask of which cells to fill-in based on the validity of input cells. I.e small holes between (and including) valid cells are\n   * marked to be filled.\n   *\n   * @remark The returned fill_mask is also added as layer to the output to be reused in following iterations of this filter.\n   *         If debug is enabled, an intermediate mask is added as layer to the output grid map.\n   * @param inputMap The input layer, used to check which cells contain valid values.\n   * @param mapOut The output GridMap will contain the additional fill_mask layer afterwards.\n   * @return An eigen mask indicating which cells should be filled by the median filter.\n   */\n  Eigen::MatrixXf computeAndAddFillMask(const Eigen::MatrixXf& inputMap, GridMap& mapOut);\n\n  /**\n   * Remove sparse valid regions by morphological opening.\n   * @remark Check https://docs.opencv.org/master/d9/d61/tutorial_py_morphological_ops.html\n   * for more information about the opening operation.\n   * @param inputMask Initial mask possibly containing also sparse valid regions that will be removed.\n   * @return An opencv mask of the same size as input mask with small sparse valid regions removed.\n   */\n  static cv::Mat_<bool> cleanedMask(const cv::Mat_<bool>& inputMask);\n\n  /**\n   * Performs morphological closing on a boolean cv matrix mask.\n   * @param [in] isValidMask A 2d mask where holes up to a certain size will be filled.\n   * @param [in] numDilationClosingIterations Algorithm specific parameter. Higher means that bigger holes will still be filled.\n   * @return A mask of the same size as isValidMask but with small holes filled.\n   */\n  static cv::Mat_<bool> fillHoles(const cv::Mat_<bool>& isValidMask, size_t numDilationClosingIterations);\n\n  /**\n   * Adds a float cv matrix as layer to a given map.\n   * @param [in, out] gridMap The map to add the layer.\n   * @param [in] cvLayer The cv matrix to add.\n   * @param [in] layerName The layer name\n   */\n  static void addCvMatAsLayer(GridMap& gridMap, const cv::Mat& cvLayer, const std::string& layerName);\n\n private:\n  //! Median filtering radius of NaN values in the input.\n  double fillHoleRadius_;\n\n  //! Median filtering radius for existing values in the input.\n  double existingValueRadius_;\n\n  //! Flag indicating whether to also filter finite values.\n  bool filterExistingValues_;\n\n  //! Number of erode-dilate iterations to calculate mask. Higher means that bigger holes will still be filled.\n  int numErodeDilationIterations_;\n\n  //! Input layer name.\n  std::string inputLayer_;\n\n  //! Output layer name.\n  std::string outputLayer_;\n\n  //! Layer containing indicating which areas to fill, will be computed if not present.\n  std::string fillMaskLayer_ = \"should_fill\";\n\n  //! Layer used to visualize the intermediate, sparse outlier removed fill mask.\n  std::string debugInfillMaskLayer_ = \"debug_infill_mask\";\n\n  //! If set, the filtered grid_map is augmented with additional debug layers.\n  bool debug_;\n};\n\n}  // namespace grid_map\n", "meta": {"hexsha": "be05a855197624de8d7e89978e8e3a4252075f93", "size": 5044, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid_map_filters/include/grid_map_filters/MedianFillFilter.hpp", "max_stars_repo_name": "martorelltorres/grid_map", "max_stars_repo_head_hexsha": "ccc4ad60f16b2754860ab05355f849a7a756eea3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 358.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T12:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-04T14:04:53.000Z", "max_issues_repo_path": "grid_map_filters/include/grid_map_filters/MedianFillFilter.hpp", "max_issues_repo_name": "martorelltorres/grid_map", "max_issues_repo_head_hexsha": "ccc4ad60f16b2754860ab05355f849a7a756eea3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T11:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-30T14:53:48.000Z", "max_forks_repo_path": "grid_map_filters/include/grid_map_filters/MedianFillFilter.hpp", "max_forks_repo_name": "martorelltorres/grid_map", "max_forks_repo_head_hexsha": "ccc4ad60f16b2754860ab05355f849a7a756eea3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 218.0, "max_forks_repo_forks_event_min_datetime": "2015-03-19T04:41:02.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-06T02:36:16.000Z", "avg_line_length": 38.5038167939, "max_line_length": 140, "alphanum_fraction": 0.7335448057, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5470933290790924}}
{"text": "// g++ -O3 -std=c++17 -fopenmp stifness_assembly.cpp -I\"/usr/include/tbb\"\n// -I\"/usr/include/eigen3\" && ./a.out\n\n// // #include <tbb/task_scheduler_init.h>\n// #include <tbb/tbb.h>\n\n// clang-format off\n// Eigen::initParallel(); //TODO try this\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <omp.h>\n#include <tbb/tbb.h>\n\nint main() {\n  double t1 = omp_get_wtime();\n\n  auto const n = 10000;   // number of nodes\n  auto const n_el = 20; // number of elements\n\n  Eigen::MatrixXd Kdense = Eigen::MatrixXd::Zero(n, n); // global stiffness matrix\n  Eigen::MatrixXd Ke = Eigen::MatrixXd::Ones(n_el, n_el); // elemental stiffness\n#pragma omp declare reduction(+ : Eigen::MatrixXd : omp_out =  omp_out + omp_in) \\\n                initializer(omp_priv=Eigen::MatrixXd::Zero(n,n))\n\n#pragma omp parallel for reduction(+ : Kdense)\n  for (int i = 0; i < n - n_el + 1; i++) {\n    Kdense.block(i, i, n_el, n_el) += Ke;\n  }\n\n  double t2 = omp_get_wtime();\n  std::cout << Kdense.block(n - n_el, n - n_el, n_el, n_el) << std::endl;\n  std::cout << \"/* message */\" << t2 - t1 << '\\n';\n\n  using namespace tbb;\n    std::vector<double> a(20);\n    tbb::parallel_for( size_t(0), 10,1,  [&]( size_t i ) {\n        a.at(i)=i; return;\n    } );\n\n\n}\n\n// Eigen::SparseMatrix<double, Eigen::RowMajor> K(n, n);\n// K.coeffs() = 0.0;\n// auto Ke = Eigen::MatrixXd::Ones(n_el, n_el);\n\n// #pragma omp critical\n//     {\n//       for (auto b = 0; b < dofs.size(); b++) {\n//         for (auto a = 0; a < dofs.size(); a++) {\n// #pragma omp critical\n//           K.coeffRef(int(dofs[a]), int(dofs[b])) += Ke(a, b);\n//         }\n// }\n// }\n", "meta": {"hexsha": "e702e793b38ce6741c09f1aaaa8f83cf899143b7", "size": 1644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/stifness_assembly.cpp", "max_stars_repo_name": "shadialameddin/numerical_tools_and_friends", "max_stars_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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/stifness_assembly.cpp", "max_issues_repo_name": "shadialameddin/numerical_tools_and_friends", "max_issues_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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/stifness_assembly.cpp", "max_forks_repo_name": "shadialameddin/numerical_tools_and_friends", "max_forks_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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.8644067797, "max_line_length": 82, "alphanum_fraction": 0.5857664234, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5470933232808037}}
{"text": "/**\n * \\file rsa_key.cpp\n * \\author Julien Kauffmann <julien.kauffmann@freelan.org>\n * \\brief A RSA sample file.\n */\n\n#include <cryptoplus/cryptoplus.hpp>\n#include <cryptoplus/buffer.hpp>\n#include <cryptoplus/bio/bio_chain.hpp>\n#include <cryptoplus/pkey/rsa_key.hpp>\n#include <cryptoplus/hash/message_digest_context.hpp>\n#include <cryptoplus/error/error_strings.hpp>\n\n#include <boost/shared_ptr.hpp>\n\n#include <iostream>\n#include <string>\n#include <cstdio>\n\n#ifndef STDOUT_FILENO\n#define STDOUT_FILENO 1\n#endif\n\n#ifdef MSV\n#include <openssl/applink.c>\n#endif\n\nusing cryptoplus::buffer;\n\nnamespace\n{\n\tint pem_passphrase_callback(char* buf, int buf_len, int rwflag, void*)\n\t{\n\t\tstd::cout << \"Passphrase (max: \" << buf_len << \" characters): \" << std::flush;\n\t\tstd::string passphrase;\n\t\tstd::getline(std::cin, passphrase);\n\n\t\tif (passphrase.empty())\n\t\t{\n\t\t\tstd::cerr << \"Passphrase cannot be empty.\" << std::endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (passphrase.size() > static_cast<size_t>(buf_len))\n\t\t{\n\t\t\tstd::cerr << \"Passphrase cannot exceed \" << buf_len << \" characters.\" << std::endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (rwflag != 0)\n\t\t{\n\t\t\tstd::cout << \"Confirm: \" << std::flush;\n\t\t\tstd::string passphrase_confirmation;\n\t\t\tstd::getline(std::cin, passphrase_confirmation);\n\n\t\t\tif (passphrase_confirmation != passphrase)\n\t\t\t{\n\t\t\t\tstd::cerr << \"The two passphrases do not match !\" << std::endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\n\t\tstd::copy(passphrase.begin(), passphrase.end(), buf);\n\t\treturn passphrase.size();\n\t}\n}\n\nint main()\n{\n\tcryptoplus::crypto_initializer crypto_initializer;\n\tcryptoplus::algorithms_initializer algorithms_initializer;\n\tcryptoplus::error::error_strings_initializer error_strings_initializer;\n\n\tstd::cout << \"RSA sample\" << std::endl;\n\tstd::cout << \"==========\" << std::endl;\n\tstd::cout << std::endl;\n\n\tconst std::string private_key_filename = \"private_key.pem\";\n\tconst std::string public_key_filename = \"public_key.pem\";\n\tconst std::string certificate_public_key_filename = \"certificate_public_key.pem\";\n\n\tboost::shared_ptr<FILE> private_key_file(fopen(private_key_filename.c_str(), \"w\"), fclose);\n\tboost::shared_ptr<FILE> public_key_file(fopen(public_key_filename.c_str(), \"w\"), fclose);\n\tboost::shared_ptr<FILE> certificate_public_key_file(fopen(certificate_public_key_filename.c_str(), \"w\"), fclose);\n\n\tif (!private_key_file)\n\t{\n\t\tstd::cerr << \"Unable to open \\\"\" << private_key_filename << \"\\\" for writing.\" << std::endl;\n\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tif (!public_key_file)\n\t{\n\t\tstd::cerr << \"Unable to open \\\"\" << public_key_filename << \"\\\" for writing.\" << std::endl;\n\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tif (!certificate_public_key_file)\n\t{\n\t\tstd::cerr << \"Unable to open \\\"\" << certificate_public_key_filename << \"\\\" for writing.\" << std::endl;\n\n\t\treturn EXIT_FAILURE;\n\t}\n\n\ttry\n\t{\n\t\tstd::cout << \"Generating RSA key. This can take some time...\" << std::endl;\n\n\t\tcryptoplus::pkey::rsa_key rsa_key = cryptoplus::pkey::rsa_key::generate_private_key(1024, 17);\n\n\t\tstd::cout << \"Done.\" << std::endl;\n\n\t\trsa_key.write_private_key(private_key_file.get(), cryptoplus::cipher::cipher_algorithm(\"AES256\"), pem_passphrase_callback);\n\n\t\tstd::cout << \"Private RSA key written succesfully to \\\"\" << private_key_filename << \"\\\".\" << std::endl;\n\n\t\trsa_key.write_public_key(public_key_file.get());\n\n\t\tstd::cout << \"Public RSA key written succesfully to \\\"\" << public_key_filename << \"\\\".\" << std::endl;\n\n\t\trsa_key.write_certificate_public_key(certificate_public_key_file.get());\n\n\t\tstd::cout << \"Certificate public RSA key written succesfully to \\\"\" << certificate_public_key_filename << \"\\\".\" << std::endl;\n\t}\n\tcatch (std::exception& ex)\n\t{\n\t\tstd::cerr << \"Exception: \" << ex.what() << std::endl;\n\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tcertificate_public_key_file.reset();\n\tpublic_key_file.reset();\n\tprivate_key_file.reset(fopen(private_key_filename.c_str(), \"r\"), fclose);\n\n\tif (!private_key_file)\n\t{\n\t\tstd::cerr << \"Unable to open \\\"\" << private_key_filename << \"\\\" for reading.\" << std::endl;\n\n\t\treturn EXIT_FAILURE;\n\t}\n\n\ttry\n\t{\n\t\tstd::cout << \"Trying to read back the private RSA key from \\\"\" << private_key_filename << \"\\\"...\" << std::endl;\n\n\t\tcryptoplus::pkey::rsa_key rsa_key = cryptoplus::pkey::rsa_key::from_private_key(private_key_file.get(), pem_passphrase_callback);\n\n\t\tstd::cout << \"Done.\" << std::endl;\n\n\t\tcryptoplus::bio::bio_chain bio_chain(BIO_new_fd(STDOUT_FILENO, BIO_NOCLOSE));\n\t\trsa_key.print(bio_chain.first());\n\n\t\tconst std::string str = \"Hello World !\";\n\t\tconst std::string hash = \"SHA256\";\n\n\t\tstd::cout << \"Generating \" << hash << \" message digest for \\\"\" << str << \"\\\"...\" << std::endl;\n\n\t\tcryptoplus::hash::message_digest_algorithm algorithm(hash);\n\t\tcryptoplus::hash::message_digest_context context;\n\t\tcontext.initialize(algorithm);\n\t\tcontext.update(str.c_str(), str.size());\n    const buffer str_hash = context.finalize();\n\n\t\tstd::cout << \"Done.\" << std::endl;\n\n\t\tstd::cout << \"Generating RSA signature...\" << std::endl;\n\n    buffer str_sign = rsa_key.sign(str_hash, algorithm.type());\n\n\t\tstd::cout << \"Done.\" << std::endl;\n\n\t\tstd::cout << \"Verifying RSA signature...\" << std::endl;\n\n\t\trsa_key.verify(str_sign, str_hash, algorithm.type());\n\n\t\tstd::cout << \"Done.\" << std::endl;\n\t}\n\tcatch (std::exception& ex)\n\t{\n\t\tstd::cerr << \"Exception: \" << ex.what() << std::endl;\n\n\t\treturn EXIT_FAILURE;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "eed0f9ee330c7eee0c1385a7aecd69d8c5c56857", "size": 5313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "blades/freelan/samples/cryptoplus/rsa_key/rsa_key.cpp", "max_stars_repo_name": "krattai/AEBL", "max_stars_repo_head_hexsha": "a7b12c97479e1236d5370166b15ca9f29d7d4265", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T03:43:54.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-17T08:09:04.000Z", "max_issues_repo_path": "blades/freelan/samples/cryptoplus/rsa_key/rsa_key.cpp", "max_issues_repo_name": "krattai/AEBL", "max_issues_repo_head_hexsha": "a7b12c97479e1236d5370166b15ca9f29d7d4265", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T21:06:22.000Z", "max_issues_repo_issues_event_max_datetime": "2015-12-07T20:45:44.000Z", "max_forks_repo_path": "blades/freelan/samples/cryptoplus/rsa_key/rsa_key.cpp", "max_forks_repo_name": "krattai/AEBL", "max_forks_repo_head_hexsha": "a7b12c97479e1236d5370166b15ca9f29d7d4265", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T03:43:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-06T11:02:08.000Z", "avg_line_length": 27.9631578947, "max_line_length": 131, "alphanum_fraction": 0.6841709016, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5470471242550824}}
{"text": "#include \"rotate.h\"\n\n#include \"math_lib/degrees.h\"\n#include \"math_lib/radians.h\"\n\n#include \"dynamic_value/boolean_value.h\"\n#include \"dynamic_value/float_value.h\"\n#include \"dynamic_value/get_value_as.h\"\n#include \"geometry_component.h\"\n#include \"geometry_system.h\"\n#include \"hierarchical_component.h\"\n#include \"hierarchical_system.h\"\n#include \"math_lib/matrix_base.h\"\n#include \"procedural_object_system.h\"\n\n#include \"geometry_operations/matrix_transform.h\"\n\n#include <boost/qvm/map_vec_mat.hpp>\n#include <boost/qvm/mat_operations.hpp>\n\nnamespace pagoda\n{\nconst std::string Rotate::s_inputGeometry(\"in\");\nconst std::string Rotate::s_outputGeometry(\"out\");\n\nRotate::Rotate(ProceduralObjectSystemPtr objectSystem) : ProceduralOperation(objectSystem)\n{\n\tCreateInputInterface(s_inputGeometry);\n\tCreateOutputInterface(s_outputGeometry);\n\n\tRegisterValues({{\"x\", std::make_shared<FloatValue>(0.0f)},\n\t                {\"y\", std::make_shared<FloatValue>(0.0f)},\n\t                {\"z\", std::make_shared<FloatValue>(0.0f)},\n\t                {\"rotation_order\", std::make_shared<String>(\"xyz\")},\n\t                {\"world\", std::make_shared<Boolean>(false)}});\n}\n\nRotate::~Rotate() {}\n\nvoid Rotate::DoWork()\n{\n\tSTART_PROFILE;\n\n\tauto geometrySystem = m_proceduralObjectSystem->GetComponentSystem<GeometrySystem>();\n\tauto hierarchicalSystem = m_proceduralObjectSystem->GetComponentSystem<HierarchicalSystem>();\n\n\twhile (HasInput(s_inputGeometry))\n\t{\n\t\tProceduralObjectPtr inObject = GetInputProceduralObject(s_inputGeometry);\n\t\tProceduralObjectPtr outObject = CreateOutputProceduralObject(s_outputGeometry);\n\n\t\tauto inGeometryComponent = geometrySystem->GetComponentAs<GeometryComponent>(inObject);\n\t\tGeometryPtr inGeometry = inGeometryComponent->GetGeometry();\n\t\tauto outGeometryComponent = geometrySystem->CreateComponentAs<GeometryComponent>(outObject);\n\t\tauto outGeometry = std::make_shared<Geometry>();\n\t\toutGeometryComponent->SetGeometry(outGeometry);\n\n\t\tauto inScope = inGeometryComponent->GetScope();\n\t\tUpdateValue(\"x\");\n\t\tUpdateValue(\"y\");\n\t\tUpdateValue(\"z\");\n\t\tUpdateValue(\"rotation_order\");\n\t\tUpdateValue(\"world\");\n\n\t\tauto x = Degrees<float>(get_value_as<float>(*GetValue(\"x\")));\n\t\tauto y = Degrees<float>(get_value_as<float>(*GetValue(\"y\")));\n\t\tauto z = Degrees<float>(get_value_as<float>(*GetValue(\"z\")));\n\t\tauto rotationOrder = get_value_as<std::string>(*GetValue(\"rotation_order\"));\n\t\tauto world = get_value_as<std::string>(*GetValue(\"world\")) == \"true\";\n\n\t\tMat4x4F matrix(boost::qvm::diag_mat(Vec4F{1.0f, 1.0f, 1.0f, 1.0f}));\n\t\tif (world)\n\t\t{\n\t\t\tauto rot = inScope.GetRotation();\n\t\t\tboost::qvm::col<0>(matrix) = XYZ0(boost::qvm::col<0>(rot));\n\t\t\tboost::qvm::col<1>(matrix) = XYZ0(boost::qvm::col<1>(rot));\n\t\t\tboost::qvm::col<2>(matrix) = XYZ0(boost::qvm::col<2>(rot));\n\t\t\tboost::qvm::col<3>(matrix) = Vec4F{0, 0, 0, 1};\n\t\t}\n\n\t\tfor (std::size_t i = rotationOrder.size(); i > 0; --i)\n\t\t{\n\t\t\tchar order = rotationOrder[i - 1];\n\t\t\tswitch (order)\n\t\t\t{\n\t\t\t\tcase 'x':\n\t\t\t\t\tmatrix = matrix * boost::qvm::rotx_mat<4>(static_cast<float>(Radians(x)));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'y':\n\t\t\t\t\tmatrix = matrix * boost::qvm::roty_mat<4>(static_cast<float>(Radians(y)));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'z':\n\t\t\t\t\tmatrix = matrix * boost::qvm::rotz_mat<4>(static_cast<float>(Radians(z)));\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow Exception(\"Invalid rotation order \" + std::string(1, order));\n\t\t\t}\n\t\t}\n\n\t\tif (world)\n\t\t{\n\t\t\tauto rot = inScope.GetInverseRotation();\n\t\t\tMat4x4F invRot;\n\t\t\tboost::qvm::col<0>(invRot) = XYZ0(boost::qvm::col<0>(rot));\n\t\t\tboost::qvm::col<1>(invRot) = XYZ0(boost::qvm::col<1>(rot));\n\t\t\tboost::qvm::col<2>(invRot) = XYZ0(boost::qvm::col<2>(rot));\n\t\t\tboost::qvm::col<3>(invRot) = Vec4F{0, 0, 0, 1};\n\t\t\tmatrix = matrix * invRot;\n\t\t}\n\n\t\tMatrixTransform<Geometry> transform(matrix);\n\t\ttransform.Execute(inGeometry, outGeometry);\n\t\tMat3x3F rot;\n\t\tboost::qvm::col<0>(rot) = XYZ(boost::qvm::col<0>(matrix));\n\t\tboost::qvm::col<1>(rot) = XYZ(boost::qvm::col<1>(matrix));\n\t\tboost::qvm::col<2>(rot) = XYZ(boost::qvm::col<2>(matrix));\n\t\toutGeometryComponent->SetScope(\n\t\t    Scope::FromGeometryAndConstrainedRotation(outGeometry, rot * inScope.GetRotation()));\n\n\t\tauto inHierarchicalComponent = hierarchicalSystem->GetComponentAs<HierarchicalComponent>(inObject);\n\t\tauto outHierarchicalComponent = hierarchicalSystem->CreateComponentAs<HierarchicalComponent>(outObject);\n\t\thierarchicalSystem->SetParent(outHierarchicalComponent, inHierarchicalComponent);\n\t}\n}  // namespace pagoda\n}  // namespace pagoda\n", "meta": {"hexsha": "dca7ed556171d519aa7aa622c02e842cfa0b165b", "size": 4472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/procedural_objects/rotate.cpp", "max_stars_repo_name": "diegoarjz/selector", "max_stars_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T17:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-12T14:37:27.000Z", "max_issues_repo_path": "source/procedural_objects/rotate.cpp", "max_issues_repo_name": "diegoarjz/selector", "max_issues_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47.0, "max_issues_repo_issues_event_min_datetime": "2019-05-27T15:24:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T17:54:54.000Z", "max_forks_repo_path": "source/procedural_objects/rotate.cpp", "max_forks_repo_name": "diegoarjz/selector", "max_forks_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_forks_repo_licenses": ["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.4920634921, "max_line_length": 106, "alphanum_fraction": 0.7048300537, "num_tokens": 1239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5470262158768134}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <boost/lexical_cast.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\n\nclass Radix {\nprivate:\n    const char* s;\n    int a[128];\npublic:\n    Radix(const char* s = \"0123456789ABCDEF\") : s(s) {\n        int i;\n        for(i = 0; s[i]; ++i)\n            a[(int)s[i]] = i;\n    }\n    std::string to(long long p, int q) {\n        int i;\n        if(!p)\n            return \"0\";\n        char t[64] = { };\n        for(i = 62; p; --i) {\n            t[i] = s[p % q];\n            p /= q;\n        }\n        return std::string(t + i + 1);\n    }\n    std::string to(const std::string& t, int p, int q) {\n        return to(to(t, p), q);\n    }\n    long long to(const std::string& t, int p) {\n        int i;\n        long long sm = a[(int)t[0]];\n        for(i = 1; i < (int)t.length(); ++i)\n            sm = sm * p + a[(int)t[i]];\n        return sm;\n    }\n};\nint main() {\n    int k; cin >> k;\n    string a, b; cin >> a >> b;\n    Radix r;\n    boost::multiprecision::cpp_int x = boost::lexical_cast<boost::multiprecision::cpp_int>(r.to(a, k));\n    boost::multiprecision::cpp_int y = boost::lexical_cast<boost::multiprecision::cpp_int>(r.to(b, k));\n    cout << x * y << endl;\n}\n\n\n", "meta": {"hexsha": "e6d984376381db236bc507d248b3c25e4eb1343e", "size": 1277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc220/b/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/abc220/b/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/abc220/b/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": 24.5576923077, "max_line_length": 103, "alphanum_fraction": 0.5050900548, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5470262120958792}}
{"text": "//Code developed and used to produce the results of \n//\n//  Rhoads, D., Sol\u00e9-Ribalta, A., Gonz\u00e1lez, M. C., & Borge-Holthoefer, J. (2020). \n//  Planning for sustainable Open Streets in pandemic cities. \n//  arXiv preprint arXiv:2009.12548.\n//\n//Please cite the above paper in any works using or derived\n//from this software\n\n\n#define TRUE 1\n#define FALSE 0\n#define DEBUG 0\n#include \"mex.h\"\n#define MAX_COLA 65001\n#define MAX_NODES 65000\ntypedef unsigned long int node_id_type;\n#include \"predQueueCircStatic.h\"\n#include <string.h>\n#include <math.h>\n#include \"matrix.h\"\n#include <boost/heap/fibonacci_heap.hpp>\n\nchar outputString[150];\n\n//returns the value of a half-normal PDF with sigma=855 at x\ndouble halfNormalPDF(double x){\n\n    //855 is the sigma that corresponds to a situation where\n    //95% of trips fall within a distance of 1667 meters\n\n    return (sqrt(2)/(855*(sqrt(M_PI)))) * exp(-pow(x,2)/(2*pow(855,2)));\n\n}\n\n//returns one row of the estimated OD matrix, \n//corresponding to the number of trips from s \n//to all other nodes j\nvoid getOdRow(\n    node_id_type s, \n    double * vStores, \n    double * vPop, \n    double * vCoords, \n    node_id_type sizeSupra, \n    double * attraction_vectPr, \n    double * OD_rowPr\n){\n\n    double xi, yi, xj, yj, dist, mass, rowSum;\n\n    memset( attraction_vectPr, 0, sizeof(double)*sizeSupra );   \n    memset( OD_rowPr, 0, sizeof(double)*sizeSupra );   \n\n    //x and y coordinates of node s\n    xi = vCoords[s];\n    yi = vCoords[sizeSupra + s];\n\n    //keep track of a sum of the row, to normalize later\n    rowSum = 0;\n    //for all nodes j in the network...\n    for (node_id_type j=0; j<sizeSupra; j++){\n        if (s != j ){\n\n            //x and y coordinates of node j\n            xj = vCoords[j];\n            yj = vCoords[sizeSupra + j];\n\n            //Calculate distance between s and j\n            dist = sqrt(pow(xi-xj,2) + pow(yi-yj,2));\n\n            //mass = # stores at j * halfnorm(distance_sj)\n            mass = vStores[j] * halfNormalPDF(dist);\n            attraction_vectPr[j] = mass;\n            rowSum = rowSum + mass;\n\n        }\n        else {\n            attraction_vectPr[j] = 0;\n        }\n    }\n\n    for (node_id_type j=0; j<sizeSupra; j++){\n        //OD_row = population at source * normalized mass of j\n        OD_rowPr[j] = vPop[s]*(attraction_vectPr[j] / rowSum);\n    }\n}\n\nvoid printMatrix(double * P, int rows, int cols);\nvoid printMatrixInverted(double * P, int rows, int cols);\nvoid printSparseMatrix(int n, double * pr, size_t * ir, size_t * jc);\n//to use the heaps\nstruct dk_Node{\n    node_id_type nodeId;\n    double distance;\n    dk_Node(node_id_type id, double dist) : nodeId(id),distance(dist) { } //<-- this is a constructor\n};\nstruct compare_dk_Node{\n    bool operator()(const dk_Node& n1, const dk_Node& n2) const{\n        return n1.distance > n2.distance;\n    }\n};\n\n\n//prhs[0] -> Adjacency Matrix in time\n//prhs[1] -> N nodes\n//prhs[2] -> N layers = 1\n//prhs[3] -> vector s of services per node\n//prhs[4] -> vector p of population per node\n//prhs[5] -> vector c of node coordinates x,y\n\n//plhs[0] -> Node betweenness\n//plhs[1] -> Directed edge betweenness\n//plhs[2] -> Num at start node CHECK\n//plhs[3] -> Num at end node CHECK\n\n\nvoid mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ){\n\n\n    //output matrices\n    double tolerance = 0.000000001;\n    node_id_type numNodes = 0, numLayers = 0;\n    node_id_type sizeSupra = 0;\n    mwSignedIndex dimsP[3];\n    mxArray *rhs[1], *lhs[1];\n    \n    // get and check inputs\n    if (nrhs != 6) mexErrMsgTxt( \"Only 6 input arguments allowed.\" );\n    if (nlhs > 2) mexErrMsgTxt( \"Only 2 output argument allowed.\" );\n    sizeSupra = mxGetN( prhs[0] );\n    if (mxGetM( prhs[0] ) != sizeSupra) mexErrMsgTxt( \"Input matrix G needs to be square.\" );\n    if(mxIsSparse(prhs[0])==0) mexErrMsgTxt( \"Input matrix must be sparse\" );\n\n    numNodes = mxGetPr(prhs[1])[0];\n    numLayers = mxGetPr(prhs[2])[0];   \n\n    double * vStores = mxGetPr(prhs[3]);\n    double * vPop = mxGetPr(prhs[4]);\n    double * vCoords = mxGetPr(prhs[5]);  \n\n    mxArray * attraction_vect = mxCreateDoubleMatrix( sizeSupra, 1, mxREAL );\n    mxArray * OD_row = mxCreateDoubleMatrix( sizeSupra, 1, mxREAL );\n    double * attraction_vectPr = mxGetPr(attraction_vect);\n    double * OD_rowPr = mxGetPr(OD_row);             \n    \n    if(numLayers != 1){\n        mexErrMsgTxt(\"This code is not prepared to work in multiplex networks\" );\n    }\n    if((numNodes*numLayers)!=sizeSupra) mexErrMsgTxt( \"Incorrect size of the input matrix\" );\n\n\n\n    rhs[0] = mxDuplicateArray(prhs[0]);   \n    mexCallMATLAB(1, lhs, 1, rhs, \"'\");\n    mxDestroyArray(rhs[0]);\n\n    \n    double *Gpr = mxGetPr(lhs[0]);\n    size_t *Gir = mxGetIr(lhs[0]);\n    size_t *Gjc = mxGetJc(lhs[0]); \n\n    double edgeWeight = 0;\n    double min_dist = -1;\n    \n    long int sIndEdges;\n    long int eIndEdges;    \n    long int nInd;\n    node_id_type v,s,w,min_v;\n    double numPacketReachDest;       \n    double * C_B = 0;\n    double * spEBW = 0;\n    staticQueue * P = NULL;       \n    double * sigma = 0;\n    double * sigmaOrig = 0;    \n    double * d = 0;\n    double * delta = 0;\n    double * visited = 0;\n    staticQueue S;         \n    \n    //to store the nodes and the distance to them\n    boost::heap::fibonacci_heap< dk_Node, boost::heap::compare<compare_dk_Node> > dk_heap;        \n    boost::heap::fibonacci_heap< dk_Node, boost::heap::compare<compare_dk_Node> >::handle_type heapHandles[MAX_NODES];\n    \n    \n    plhs[0] = mxCreateDoubleMatrix( sizeSupra, 1, mxREAL );\n    C_B = mxGetPr(plhs[0]);    \n    plhs[1] = mxCreateDoubleMatrix( numLayers*numNodes, numLayers*numNodes, mxREAL );\n    spEBW = mxGetPr(plhs[1]);                      \n\n    visited = (double *)mxMalloc(sizeof(double)*sizeSupra);     \n    sigma = (double *)mxMalloc(sizeof(double)*sizeSupra); \n    sigmaOrig = (double *)mxMalloc(sizeof(double)*sizeSupra); \n    d = (double *)mxMalloc(sizeof(double)*sizeSupra); \n    P = (staticQueue *)mxMalloc(sizeof(staticQueue)*sizeSupra);\n    delta = (double *)mxMalloc(sizeof(double)*sizeSupra);     \n    \n    memset( C_B, 0, sizeof(double)*sizeSupra );   \n    memset( spEBW, 0, sizeof(double)*sizeSupra );    \n    \n    for( s = 0 ; s<numNodes; s++){ \n\n        sprintf(outputString,\"fprintf('Source = %lu\\\\n');\",s+1);\n\n        mexEvalString(outputString);\n\n        getOdRow(s, vStores, vPop, vCoords, sizeSupra, attraction_vectPr, OD_rowPr);\n        \n        //initializations\n        create(&S);  \n              \n        for( w = 0 ; w<sizeSupra ; w++){\n            create(&P[w]);       \n            sigma[w] = 0;                        \n            d[w] = mxGetInf();\n            visited[w] = 0;\n    \n            //store the handle in a table then use the table to access the handle\n            heapHandles[w] = dk_heap.push(dk_Node(w,d[w]));             \n        }            \n        d[s] = 0;\n        (*heapHandles[s]).distance = 0; dk_heap.decrease(heapHandles[s]);\n        sigma[s] = 1;      \n                 \n        //end initializations  \n                \n        min_v = dk_heap.top().nodeId;\n        min_dist = dk_heap.top().distance;\n        dk_heap.pop();        \n        \n      \n        \n\n        while( min_dist < mxGetInf()){\n        //Min_V := S;\n        //Min_Dist := 0.0;\n        //while Min_Dist /= Plus_Infinity loop\n\n            if(DEBUG){\n                sprintf(outputString,\"fprintf('min_v %lu, min_dist = %f\\\\n');\",min_v+1,min_dist);\n                mexEvalString(outputString);                                                             \n            }\n            \n            v = min_v;               \n                                                                           \n            \n            visited[v] = 1;\n            add(&S,v);                                                     \n\n            \n            if(DEBUG){\n                sprintf(outputString,\"fprintf('Exploring %lu\\\\n');\",v+1);\n                mexEvalString(outputString);                                                     \n            }            \n            \n            //for each neigbor of v\n            sIndEdges = Gjc[v];\n            eIndEdges = Gjc[v+1] - 1;            \n\n            if(DEBUG){\n                sprintf(outputString,\"fprintf('\\\\tmin_v = %lu, min_dist = %f\\\\n');\",min_v+1, min_dist);\n                mexEvalString(outputString);                                                                         \n            }\n                \n            for( nInd = sIndEdges ; nInd<=eIndEdges ; nInd++ ){                        \n            //while Has_Next(El) loop\n                w = Gir[nInd];\n                edgeWeight = Gpr[nInd];\n\n                if(DEBUG){\n                    sprintf(outputString,\"fprintf('\\tEdge from w=%lu to w=%lu and edgeWeight = %f\\\\n');\",v+1, w+1, edgeWeight);\n                    mexEvalString(outputString);                                                                         \n                }                    \n                \n                if(DEBUG){                    \n                    sprintf(outputString,\"fprintf('\\\\tedges out %lu\\\\n');\",w);\n                    mexEvalString(outputString);     \n                }\n\n                if (v != w){\n                //if V /= W then                    \n                    if(d[w] > d[v] + edgeWeight){ // new path to the vertex\n                        d[w] = d[v] + edgeWeight;\n                        \n                        (*heapHandles[w]).distance = d[w]; dk_heap.decrease(heapHandles[w]);                        \n\n                        sigma[w] = sigma[v];\n                        create(&P[w]);\n                        add(&P[w],v);\n                        \n                        if(DEBUG){   \n                            sprintf(outputString,\"fprintf('\\\\t\\\\tnew path to vertex %lu with dist  = %f\\\\n');\",w+1, d[w]);\n                            mexEvalString(outputString);                                                     \n                        }\n                    }else if( fabs(d[w] - d[v] - edgeWeight) < tolerance){ // the current path is of equal length\n                        sigma[w] = sigma[w] + sigma[v];\n                        add(&P[w],v);                                                           \n                    \n                        if(DEBUG){                           \n                            sprintf(outputString,\"fprintf('\\\\t\\\\tpath to equal length to %lu , path difference  =%f\\\\n');\",w+1, fabs(d[w] - d[v] - edgeWeight));\n                            mexEvalString(outputString);          \n                            sprintf(outputString,\"fprintf('\\\\t\\\\told length = %f, dist to %lu = %f and edgeweight = %f\\\\n');\",d[w],v+1,d[v],edgeWeight);\n                            mexEvalString(outputString);                             \n                        }\n                    }                                                            \n                 }\n                 //end if;\n            }\n            //end loop;\n\n\n            if(!dk_heap.empty()){\n                min_v = dk_heap.top().nodeId;\n                min_dist = dk_heap.top().distance;\n                dk_heap.pop();                    \n            }else{\n                min_v = -1;\n                min_dist = mxGetInf();            \n            }\n        }                        \n                 \n        //keep an original copy of the sigma\n        //memcpy(sigmaOrig,sigma,sizeof(double)*sizeSupra);                \n        for( w = 0 ; w<sizeSupra ; w++){\n            delta[w] = 0;    \n     \n        }          \n      \n    \n        while(!empty(&S)){\n            \n            w = pop(&S);\n   \n\n            if(DEBUG){\n                sprintf(outputString,\"fprintf('explore vertex w = %lu\\\\n');\",w+1);\n                mexEvalString(outputString);\n            }\n                        \n            if(DEBUG){\n                sprintf(outputString,\"fprintf('Distance from (s=%lu) to (w=%lu) = %f\\\\n');\",s+1,w+1,d[w]);\n                mexEvalString(outputString);                                                         \n            }\n                \n            while(!empty(&P[w])){ \n\n                v = pop(&P[w]);\n\n            \n                if(DEBUG){\n                    sprintf(outputString,\"fprintf('\\\\tvertex %lu has predecessor %lu\\\\n');\",w+1,v+1);\n                    mexEvalString(outputString);\n                }\n                \n                if(DEBUG){\n                    sprintf(outputString,\"fprintf('\\\\t\\\\tPred: (v=%lu)\\\\n');\",v);\n                    mexEvalString(outputString);                                                         \n                    sprintf(outputString,\"fprintf('\\\\t\\\\tsigma[v=%lu]=%i/sigma[w=%lu]=%i,delta[w=%lu]=%f\\\\n');\",v,(int)sigma[v],w,(int)sigma[w],w,delta[w]);\n                    mexEvalString(outputString);                           \n                }\n                \n\n                //--> Aqu\u00ed la OD matrix\n\n\n                numPacketReachDest = OD_rowPr[w];\n  \n\n                delta[v] = delta[v] + (sigma[v]/sigma[w])*(numPacketReachDest + delta[w]);  \n\n                if(v != s){\n\n                    spEBW[v + sizeSupra*w] = spEBW[v + sizeSupra*w] + (sigma[v]/sigma[w])*(numPacketReachDest + delta[w]);\n\n                }                \n                if(v == s){\n\n                    spEBW[v + sizeSupra*w] = spEBW[v + sizeSupra*w] + (sigma[v]/sigma[w])*(numPacketReachDest + delta[w]);                                          \n                  \n                }                \n\n\n                \n            }\n\n\n                \n            if(w!=s){\n\n                C_B[w] = C_B[w] + delta[w];  /// aqui la delta d'ha de normalizar no es poden sumar les betweenness\n                                                               // de les differents capes simplement\n                \n                if(DEBUG){\n                    sprintf(outputString,\"fprintf('\\\\t\\\\tBetweenness[w(%lu)]=%f\\\\n');\",w,C_B[w]);\n                    mexEvalString(outputString);                                           \n                }  \n            \n            }\n\n        }\n\n        \n    }\n\n\n\n    mxFree(sigma);\n    mxFree(sigmaOrig);\n    mxFree(d);\n    mxFree(P);\n    mxFree(delta);\n    mxFree(visited);\n}\n\n\nvoid printMatrix(double * P, int rows, int cols){\n    int rowIndex = 0, columnIndex = 0;\n    \n    //print the matrix\n    for(rowIndex = 0 ; rowIndex < rows; rowIndex++){\n        for(columnIndex = 0 ; columnIndex < cols; columnIndex++){            \n            mexPrintf(\"%1.4f \",P[rowIndex*cols + columnIndex]);   \n        }    \n        mexPrintf(\"\\n\");   \n    }        \n}\n\nvoid printMatrixInverted(double * P, int rows, int cols){\n    int rowIndex = 0, columnIndex = 0;\n    \n    //print the matrix\n    for(rowIndex = 0 ; rowIndex < rows; rowIndex++){\n        for(columnIndex = 0 ; columnIndex < cols; columnIndex++){            \n            mexPrintf(\"%1.4f \",P[columnIndex*rows + rowIndex]);   \n        }    \n        mexPrintf(\"\\n\");   \n    }        \n}\n\nvoid printSparseMatrix(int n, double * pr, size_t * ir, size_t * jc){\n    size_t nrow;\n\n    mexPrintf(\"This is from the .cpp\");\n\n    for (int y=0; y<n; y++){\n        nrow = jc[y+1] - jc[y];\n        for (int x = 0; x<nrow; x++){\n            mexPrintf(\"      (%d,%d)    %g\\n\", (*ir++)+1,y+1,*pr++);\n        }\n    }\n}\n    \n", "meta": {"hexsha": "a523bd60f7c8a6612c370ac66dc25d71f64c4965", "size": 15282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "get_ebw_make_od.cpp", "max_stars_repo_name": "COSIN3-UOC/sidewalk_networks", "max_stars_repo_head_hexsha": "061ed4ca2ceb2b1b24f020471c77cf58fdf8608e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T23:01:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T23:01:29.000Z", "max_issues_repo_path": "get_ebw_make_od.cpp", "max_issues_repo_name": "COSIN3-UOC/sidewalk_networks", "max_issues_repo_head_hexsha": "061ed4ca2ceb2b1b24f020471c77cf58fdf8608e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "get_ebw_make_od.cpp", "max_forks_repo_name": "COSIN3-UOC/sidewalk_networks", "max_forks_repo_head_hexsha": "061ed4ca2ceb2b1b24f020471c77cf58fdf8608e", "max_forks_repo_licenses": ["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.8097345133, "max_line_length": 164, "alphanum_fraction": 0.4697029185, "num_tokens": 3740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5469647996437041}}
{"text": "//------------------------------------------------------------------------------\n// \\file Rings_tests.cpp\n// \\ref https://www.cs.utexas.edu/users/fussell/courses/cs429h/lectures/Lecture_2-429h.pdf\n//------------------------------------------------------------------------------\n#include \"Algebra/Rings/Matrices2x2.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <cmath>\n#include <sstream>\n\nusing Algebra::Rings::Matrix2x2;\n\nBOOST_AUTO_TEST_SUITE(Algebra)\nBOOST_AUTO_TEST_SUITE(Rings)\nBOOST_AUTO_TEST_SUITE(Rings_tests)\n\nBOOST_AUTO_TEST_SUITE(Matrices2x2)\n\nBOOST_AUTO_TEST_SUITE(Interface)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ConstructsFrom4RealParameters)\n{\n\t{\n\t\tconst Matrix2x2<int> mat {1, 2, 3, 4};\n\n\t\tconst auto result {mat.data()};\n\n\t\tfor (int i {0}; i < 4; ++i)\n\t\t{\n\t\t\tBOOST_TEST(result.at(i) == (i + 1));\n\t\t}\n\t}\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(OperatorInsertsIntoStringStream)\n{\n\t{\n\t\tstd::ostringstream oss;\n\n\t\tconst Matrix2x2<double> mat {-5.6, 6.2, 7.1, -8.0};\n\n\t\toss << mat;\n\n\t\tBOOST_TEST(oss.str() == \"-5.6 6.2\\n7.1 -8\");\n\n\t\toss.flush();\n\t}\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(AdditiveIdentityReturnsZero)\n{\n  BOOST_TEST(true);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Interface\n\nBOOST_AUTO_TEST_SUITE(Operations)\n\n\nBOOST_AUTO_TEST_SUITE_END() // Operations\n\nBOOST_AUTO_TEST_SUITE_END() // Matrices2x2\n\nBOOST_AUTO_TEST_SUITE_END() // Rings_tests\nBOOST_AUTO_TEST_SUITE_END() // Rings\nBOOST_AUTO_TEST_SUITE_END() // Algebra", "meta": {"hexsha": "1262606acc5e613bdebb5afde3f8b3a594854cb9", "size": 1878, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Manifolds/Source/UnitTests/Algebra/Rings/Rings_tests.cpp", "max_stars_repo_name": "hhchi13/mathphysics", "max_stars_repo_head_hexsha": "61790697b65a987617ddd0c0404e345ae6072e98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2017-01-10T14:24:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:19:23.000Z", "max_issues_repo_path": "Manifolds/Source/UnitTests/Algebra/Rings/Rings_tests.cpp", "max_issues_repo_name": "hhchi13/mathphysics", "max_issues_repo_head_hexsha": "61790697b65a987617ddd0c0404e345ae6072e98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-09-29T09:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T03:12:29.000Z", "max_forks_repo_path": "Manifolds/Source/UnitTests/Algebra/Rings/Rings_tests.cpp", "max_forks_repo_name": "hhchi13/mathphysics", "max_forks_repo_head_hexsha": "61790697b65a987617ddd0c0404e345ae6072e98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2018-01-21T05:33:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T20:15:13.000Z", "avg_line_length": 26.0833333333, "max_line_length": 90, "alphanum_fraction": 0.4840255591, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.5469329431859521}}
{"text": "/**\n * \\file dcs/math/detail/float.hpp\n *\n * \\brief Utilities for floating-point comparison.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2012 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_DETAIL_FLOAT_HPP\n#define DCS_MATH_DETAIL_FLOAT_HPP\n\n\n#include <algorithm>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/utility/enable_if.hpp>\n//#include <cfloat>\n#include <cmath>\n\n\nnamespace dcs { namespace math { namespace detail {\n\n/// See also:\n/// - http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm\n/// - http://www.petebecker.com/js/js200012.html\n/// - http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-internal.h\n/// - http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.16\n/// - http://adtmag.com/articles/2000/03/16/comparing-floats-how-to-determine-if-floating-quantities-are-close-enough-once-a-tolerance-has-been.aspx\n/// - http://www.boost.org/doc/libs/1_47_0/libs/test/doc/html/utf/testing-tools/floating_point_comparison.html\n/// - http://learningcppisfun.blogspot.com/2010/04/comparing-floating-point-numbers.html\n/// - http://floating-point-gui.de/errors/comparison/\n/// - https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/\n/// .\n\n\n/**\n * \\brief x is approximately equal to y.\n *\n * Inspired by [1]:\n * \\f[\n *  $x \\approx y\\,\\text{ if and only if } |y-x|\\le\\epsilon\\max(|x|,|y|)\n * \\f]\n *\n * References:\n * -# Knuth, \"The Art of Computer Programming: Vol.2\" 3rd Ed, 1998, Sec. 4.2.2.\n * .\n */\ntemplate <typename T>\ninline\ntypename ::boost::enable_if<\n\t::boost::is_floating_point<T>,\n\tbool\n>::type approximately_equal(T x, T y, T tol)\n{\n\t// Try first with standard comparison (handles the case when both x and y are zero)\n\tif (x == y)\n\t{\n\t\treturn true;\n\t}\n\n\t// Handle degenerate cases\n\tif (::std::isnan(x) || ::std::isnan(y))\n\t{\n\t\t// According to IEEE, NaN are different even by itself\n\t\treturn false;\n\t}\n\tif (::std::isinf(x) && ::std::isinf(y))\n\t{\n\t\t// According to IEEE, Infinite operands of the same sign shall compare equal\n\t\treturn true;\n\t}\n\tif ((::std::isinf(x) && ::std::isfinite(y)) || (::std::isfinite(x) && ::std::isinf(y)))\n\t{\n\t\t// Infinity vs non-infinite operands are different\n\t\treturn false;\n\t}\n\n\treturn ::std::abs(x-y) <= (::std::max(::std::abs(x), ::std::abs(y))*tol);\n}\n\n\n/**\n * \\brief x is definitely equal to y.\n *\n * Inspired by [1]:\n * \\f[\n *  $x \\sim y\\,\\text{ if and only if } |y-x|\\le\\epsilon\\min(|x|,|y|)\n * \\f]\n *\n * References:\n * -# Knuth, \"The Art of Computer Programming: Vol.2\" 3rd Ed, 1998, Sec. 4.2.2.\n * .\n */\ntemplate <typename T>\ninline\ntypename ::boost::enable_if<\n\t::boost::is_floating_point<T>,\n\tbool\n>::type essentially_equal(T x, T y, T tol)\n{\n\t// Try first with standard comparison (handles the case when both x and y are zero)\n\tif (x == y)\n\t{\n\t\treturn true;\n\t}\n\t// Handle degenerate cases\n\tif (::std::isnan(x) || ::std::isnan(y))\n\t{\n\t\t// According to IEEE, NaN are different even by itself\n\t\treturn false;\n\t}\n\tif (::std::isinf(x) && ::std::isinf(y))\n\t{\n\t\t// According to IEEE, Infinite operands of the same sign shall compare equal\n\t\treturn true;\n\t}\n\tif ((::std::isinf(x) && ::std::isfinite(y)) || (::std::isfinite(x) && ::std::isinf(y)))\n\t{\n\t\t// Infinity vs non-infinite operands are different\n\t\treturn false;\n\t}\n\n\treturn ::std::abs(x-y) <= (::std::min(::std::abs(x), ::std::abs(y))*tol);\n}\n\n\n/**\n * \\brief x is definitely greater than y.\n *\n * Inspired by [1]:\n * \\f[\n *  $x \\succ y\\,\\text{ if and only if } x-y > \\epsilon\\max(|x|,|y|)\n * \\f]\n *\n * References:\n * -# Knuth, \"The Art of Computer Programming: Vol.2\" 3rd Ed, 1998, Sec. 4.2.2.\n * .\n */\ntemplate <typename T>\ninline\ntypename ::boost::enable_if<\n\t::boost::is_floating_point<T>,\n\tbool\n>::type definitely_greater(T x, T y, T tol)\n{\n\t// Try first with standard comparison\n\tif (x <= y)\n\t{\n\t\treturn false;\n\t}\n\n\t// Handle degenerate cases\n\tif (::std::isnan(x) || ::std::isnan(y))\n\t{\n\t\t// According to IEEE, NaN are different even by itself\n\t\treturn false;\n\t}\n\tif (::std::isinf(x) && ::std::isfinite(y))\n\t{\n\t\treturn true;\n\t}\n\tif (::std::isfinite(x) && ::std::isinf(y))\n\t{\n\t\treturn false;\n\t}\n\n\treturn (x-y) > (::std::max(::std::abs(x), ::std::abs(y))*tol);\n}\n\n\n/**\n * \\brief x is definitely less than y.\n *\n * Inspired by [1]:\n * \\f[\n *  $x \\prec y\\,\\text{ if and only if } y-x > \\epsilon\\max(|x|,|y|)\n * \\f]\n *\n * References:\n * -# Knuth, \"The Art of Computer Programming: Vol.2\" 3rd Ed, 1998, Sec. 4.2.2.\n * .\n */\ntemplate <typename T>\ninline\ntypename ::boost::enable_if<\n\t::boost::is_floating_point<T>,\n\tbool\n>::type definitely_less(T x, T y, T tol)\n{\n\t// Try first with standard comparison\n\tif (x >= y)\n\t{\n\t\treturn false;\n\t}\n\n\t// Handle degenerate cases\n\tif (::std::isnan(x) || ::std::isnan(y))\n\t{\n\t\t// According to IEEE, NaN are different even by itself\n\t\treturn false;\n\t}\n\tif (::std::isinf(x) && ::std::isfinite(y))\n\t{\n\t\treturn false;\n\t}\n\tif (::std::isfinite(x) && ::std::isinf(y))\n\t{\n\t\treturn true;\n\t}\n\n\treturn (y-x) > (::std::max(::std::abs(x), ::std::abs(y))*tol);\n}\n\n}}} // Namespace dcs::math::detail\n\n\n#endif // DCS_MATH_DETAIL_FLOAT_HPP\n", "meta": {"hexsha": "7e84b0926cd92f7b60b41c86c04d84ff445dcf7a", "size": 5697, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dcs/math/detail/float.hpp", "max_stars_repo_name": "sguazt/fog-gt", "max_stars_repo_head_hexsha": "92a01de4f3d71bf89741c7e4af1bebb965c64d28", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T19:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-26T19:03:40.000Z", "max_issues_repo_path": "include/dcs/math/detail/float.hpp", "max_issues_repo_name": "sguazt/fog-gt", "max_issues_repo_head_hexsha": "92a01de4f3d71bf89741c7e4af1bebb965c64d28", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dcs/math/detail/float.hpp", "max_forks_repo_name": "sguazt/fog-gt", "max_forks_repo_head_hexsha": "92a01de4f3d71bf89741c7e4af1bebb965c64d28", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4506437768, "max_line_length": 148, "alphanum_fraction": 0.6456029489, "num_tokens": 1723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5469329347024814}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main() {\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", "meta": {"hexsha": "8b2fc59ced3149a5b008d99ca2a2153e93b4024e", "size": 350, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen-3.3/doc/examples/tut_matrix_coefficient_accessors.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_matrix_coefficient_accessors.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_matrix_coefficient_accessors.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": 19.4444444444, "max_line_length": 59, "alphanum_fraction": 0.4942857143, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5469329347024814}}
{"text": "#include <iostream>\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/algorithm/minmax.hpp>\n#include <vector>\n#include <omp.h>\n\n#include \"dbscan.h\"\n\nnamespace clustering {\nDBSCAN::ClusterData DBSCAN::gen_cluster_data( size_t features_num, size_t elements_num )\n{\n    DBSCAN::ClusterData cl_d( elements_num, features_num );\n\n    for ( size_t i = 0; i < elements_num; ++i ) {\n        for ( size_t j = 0; j < features_num; ++j ) {\n            cl_d( i, j ) = ( -1.0 + rand() * ( 2.0 ) / RAND_MAX );\n        }\n    }\n\n    return cl_d;\n}\n\nDBSCAN::FeaturesWeights DBSCAN::std_weights( size_t s )\n{\n    // num cols\n    DBSCAN::FeaturesWeights ws( s );\n\n    for ( size_t i = 0; i < s; ++i ) {\n        ws( i ) = 1.0;\n    }\n\n    return ws;\n}\n\nDBSCAN::DBSCAN()\n{\n}\n\nstatic int num_threads_or_default( int nt )\n{\n    if ( !nt ) {\n        return omp_get_max_threads();\n    }\n    return nt;\n}\n\nvoid DBSCAN::init( double eps, size_t min_elems, int num_threads )\n{\n    m_eps = eps;\n    m_min_elems = min_elems;\n    m_num_threads = num_threads_or_default( num_threads );\n}\n\nDBSCAN::DBSCAN( double eps, size_t min_elems, int num_threads )\n    : m_eps( eps )\n    , m_min_elems( min_elems )\n    , m_num_threads( num_threads_or_default( num_threads ) )\n    , m_dmin( 0.0 )\n    , m_dmax( 0.0 )\n{\n    reset();\n}\n\nDBSCAN::~DBSCAN()\n{\n}\n\nvoid DBSCAN::reset()\n{\n    m_labels.clear();\n}\n\nvoid DBSCAN::prepare_labels( size_t s )\n{\n    m_labels.resize( s );\n\n    for ( auto& l : m_labels ) {\n        l = -1;\n    }\n}\n\nconst DBSCAN::DistanceMatrix DBSCAN::calc_dist_matrix( const DBSCAN::ClusterData& C, const DBSCAN::FeaturesWeights& W )\n{\n    DBSCAN::ClusterData cl_d = C;\n\n    omp_set_dynamic( 0 );\n    omp_set_num_threads( m_num_threads );\n#pragma omp parallel for\n    for ( size_t i = 0; i < cl_d.size2(); ++i ) {\n        ublas::matrix_column< DBSCAN::ClusterData > col( cl_d, i );\n\n        const auto r = minmax_element( col.begin(), col.end() );\n\n        double data_min = *r.first;\n        double data_range = *r.second - *r.first;\n\n        if ( data_range == 0.0 ) {\n            data_range = 1.0;\n        }\n\n        const double scale = 1 / data_range;\n        const double min = -1.0 * data_min * scale;\n\n        col *= scale;\n        col.plus_assign( ublas::scalar_vector< typename ublas::matrix_column< DBSCAN::ClusterData >::value_type >( col.size(), min ) );\n    }\n\n    // rows x rows\n    DBSCAN::DistanceMatrix d_m( cl_d.size1(), cl_d.size1() );\n    ublas::vector< double > d_max( cl_d.size1() );\n    ublas::vector< double > d_min( cl_d.size1() );\n\n    omp_set_dynamic( 0 );\n    omp_set_num_threads( m_num_threads );\n#pragma omp parallel for\n    for ( size_t i = 0; i < cl_d.size1(); ++i ) {\n        for ( size_t j = i; j < cl_d.size1(); ++j ) {\n            d_m( i, j ) = 0.0;\n\n            if ( i != j ) {\n                ublas::matrix_row< DBSCAN::ClusterData > U( cl_d, i );\n                ublas::matrix_row< DBSCAN::ClusterData > V( cl_d, j );\n\n                int k = 0;\n                for ( const auto e : ( U - V ) ) {\n                    d_m( i, j ) += fabs( e ) * W[k++];\n                }\n\n                d_m( j, i ) = d_m( i, j );\n            }\n        }\n\n        const auto cur_row = ublas::matrix_row< DBSCAN::DistanceMatrix >( d_m, i );\n        const auto mm = minmax_element( cur_row.begin(), cur_row.end() );\n\n        d_max( i ) = *mm.second;\n        d_min( i ) = *mm.first;\n    }\n\n    m_dmin = *( min_element( d_min.begin(), d_min.end() ) );\n    m_dmax = *( max_element( d_max.begin(), d_max.end() ) );\n\n    m_eps = ( m_dmax - m_dmin ) * m_eps + m_dmin;\n\n    return d_m;\n}\n\nDBSCAN::Neighbors DBSCAN::find_neighbors( const DBSCAN::DistanceMatrix& D, uint32_t pid )\n{\n    Neighbors ne;\n\n    for ( uint32_t j = 0; j < D.size1(); ++j ) {\n        if ( D( pid, j ) <= m_eps ) {\n            ne.push_back( j );\n        }\n    }\n    return ne;\n}\n\nvoid DBSCAN::dbscan( const DBSCAN::DistanceMatrix& dm )\n{\n    std::vector< uint8_t > visited( dm.size1() );\n\n    uint32_t cluster_id = 0;\n\n    for ( uint32_t pid = 0; pid < dm.size1(); ++pid ) {\n        if ( !visited[pid] ) {\n            visited[pid] = 1;\n\n            Neighbors ne = find_neighbors( dm, pid );\n\n            if ( ne.size() >= m_min_elems ) {\n                m_labels[pid] = cluster_id;\n\n                for ( uint32_t i = 0; i < ne.size(); ++i ) {\n                    uint32_t nPid = ne[i];\n\n                    if ( !visited[nPid] ) {\n                        visited[nPid] = 1;\n\n                        Neighbors ne1 = find_neighbors( dm, nPid );\n\n                        if ( ne1.size() >= m_min_elems ) {\n                            for ( const auto& n1 : ne1 ) {\n                                ne.push_back( n1 );\n                            }\n                        }\n                    }\n\n                    if ( m_labels[nPid] == -1 ) {\n                        m_labels[nPid] = cluster_id;\n                    }\n                }\n\n                ++cluster_id;\n            }\n        }\n    }\n}\n\nvoid DBSCAN::fit( const DBSCAN::ClusterData& C )\n{\n    const DBSCAN::FeaturesWeights W = DBSCAN::std_weights( C.size2() );\n    wfit( C, W );\n}\nvoid DBSCAN::fit_precomputed( const DBSCAN::DistanceMatrix& D )\n{\n    prepare_labels( D.size1() );\n    dbscan( D );\n}\n\nvoid DBSCAN::wfit( const DBSCAN::ClusterData& C, const DBSCAN::FeaturesWeights& W )\n{\n    prepare_labels( C.size1() );\n    const DBSCAN::DistanceMatrix D = calc_dist_matrix( C, W );\n    dbscan( D );\n}\n\nconst DBSCAN::Labels& DBSCAN::get_labels() const\n{\n    return m_labels;\n}\n\nstd::ostream& operator<<( std::ostream& o, DBSCAN& d )\n{\n    o << \"[ \";\n    for ( const auto& l : d.get_labels() ) {\n        o << \" \" << l;\n    }\n    o << \" ] \" << std::endl;\n\n    return o;\n}\n}\n", "meta": {"hexsha": "8dfcd312e428a37c8ed54ecb79a4068f641c36c2", "size": 5786, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dbscan.cpp", "max_stars_repo_name": "houwenbo87/DBSCAN", "max_stars_repo_head_hexsha": "3452d32186f2b59f2f1e515cebdf0ce15cb3e2f7", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-18T22:40:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-18T22:40:39.000Z", "max_issues_repo_path": "dbscan.cpp", "max_issues_repo_name": "conanhung/DBSCAN", "max_issues_repo_head_hexsha": "0bf4e6a83d61b83858f270dc5fbf78cd05ca3153", "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": "dbscan.cpp", "max_forks_repo_name": "conanhung/DBSCAN", "max_forks_repo_head_hexsha": "0bf4e6a83d61b83858f270dc5fbf78cd05ca3153", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-09T08:24:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-09T08:24:35.000Z", "avg_line_length": 24.4135021097, "max_line_length": 135, "alphanum_fraction": 0.5279986174, "num_tokens": 1646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.5468811177585031}}
{"text": "#include <iostream>\n#include \"ArchivoTrain.h\"\n#include \"Imagen.h\"\n#include \"Trabajador.h\"\n#include \"config.h\"\n#include \"ArchivoNeighbors.h\"\n#include <set>\n#include \"ActiveSet.h\"\n#include <fstream>\n#include <Eigen/Eigenvalues>\n#include <algorithm>\n#include <iterator>\n/**\n * Necesito que el archivo venga en \n * \"exactamente\" el mismo formato que \n * el train de kaggle, se detecta la\n * cantidad de dimensiones\n * */\n//weinberger 09 - p\u00e1ginas 33 a 35\nusing namespace std;\n\nvoid filtrarNegativos(Matriz& m){\n\tfor(int i = 0; i < m.rows(); i++){\n\t\tif(m(i,i)<0){\n\t\t\tm(i,i)=0;\n\t\t}\n\t}\n}\n\nvoid obtenerSalieron(\tConjuntoActiveSets& salieron,\n\t\t\t\t\t\tConjuntoActiveSets& activos, \n\t\t\t\t\t\tConjuntoActiveSets& anterior){\n\t//salieron = anterior - activos\n\tset_difference(\tanterior.begin(),anterior.end(),\n\t\t\t\t\tactivos.begin(),activos.end(), \n\t\t\t\t\tinserter(salieron,salieron.end()),\n\t\t\t\t\tCompararActiveSet()\n\t);\n}\nvoid obtenerEntraron(\tConjuntoActiveSets& entraron,\n\t\t\t\t\t\tConjuntoActiveSets& activos, \n\t\t\t\t\t\tConjuntoActiveSets& anterior){\n\t//entraron = activos - anterior\n\tset_difference(\tactivos.begin(),activos.end(),\n\t\t\t\t\tanterior.begin(),anterior.end(), \n\t\t\t\t\tinserter(entraron,entraron.end()),\n\t\t\t\t\tCompararActiveSet()\n\t);\n\t//notese que los argumentos est\u00e1n invertidos\n}\n\nint main(int argc, char* argv[]){\n\tif(argc==1){\n\t\tcout<<\"Y los argumentos?\"<<endl;\n\t}else{\n\t\tif(argv[1][0]=='n'){\n\t\t\tcout<<\"Recalculando target neighbours\"<<endl;\n\t\t\tArchivoTrain archivo;\n\t\t\tarchivo.conectarTargetNeighbors(5,0,1000);\n\t\t\tarchivo.guardarTargetNeighbours(0,1000);\n\t\t}else if(argv[1][0]=='m'){\n\t\t\tofstream off(\"M.dat\");\n\t\t\tcout<<\"Voy a calcular la matriz M\"<<endl;\n\t\t\tArchivoTrain archivo;\n\t\t\tArchivoNeighbors neighbors(archivo);\n\t\t\t\n\t\t\tMatriz m,g;\n\t\t\tm.setIdentity();//initialize with the identity matrix\n\t\t\tConjuntoActiveSets posibles_activos, activos, anteriores;//initialize active sets\n\t\t\t//neighbors.calcularG0(g);//initialize gradient\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\tfor(int i = 0; i<2; i++){//while not converged do\n\t\t\t\tcout<<\"Iniciando nueva iteracion:\"<<i<<endl;\n\t\t\t\tif(i==0){//if mod(i,10)==0 || casi convergencia then\n\t\t\t\t\tposibles_activos.clear();\n\t\t\t\t\tneighbors.agregarActiveSets(posibles_activos);//compute Nt+1 exactly\n\t\t\t\t\t//(es inviable hacer la b\u00fasqueda de active sets con la distancia Mahalanobis)\n\t\t\t\t\tactivos = posibles_activos;//update active set\n\t\t\t\t}else{\n\t\t\t\t\tanteriores = activos;\n\t\t\t\t\tneighbors.filtrarActivos(posibles_activos, activos,m);\n\t\t\t\t\t//compute Nt+1 only search active set\n\t\t\t\t}\n\t\t\t\tcout<<\"Posibles activos:\"<<activos.size()<<endl;\n\t\t\t\t\n\t\t\t\tcout<<\"Voy a calcular la G nueva\"<<endl;\n\t\t\t\t\n\t\t\t\tConjuntoActiveSets salieron, entraron;\n\t\t\t\tobtenerSalieron(salieron,activos,anteriores);\n\t\t\t\tobtenerEntraron(entraron,activos,anteriores);\n\t\t\t\tcout<<\"Ya tengo los que salientraron\"<<endl;\n\t\t\t\t\n\t\t\t\tMatriz gResta,gSuma;\n\t\t\t\tneighbors.calcularSegundoTerminoGradiente(gResta,salieron);\n\t\t\t\tneighbors.calcularSegundoTerminoGradiente(gSuma,entraron);\n\t\t\t\tg+=g-gResta+gSuma;//sumaresta de gradientes\n\t\t\t\t\n\t\t\t\tcout<<\"Descmponiendo las matrices\"<<endl;\n\t\t\t\t\n\t\t\t\tMatriz m_def = m-0.1*g;//Mt-alfa*Gt+1\n\t\t\t\tEigen::EigenSolver<Matriz> solver(m_def);\n\t\t\t\tMatriz delta = solver.pseudoEigenvalueMatrix();\n\t\t\t\tMatriz v = solver.pseudoEigenvectors();\n\t\t\t\tfiltrarNegativos(delta);//proyecci\u00f3n sobre semidefinidas positivas\n\t\t\t\tm=v*delta*v.transpose();//take gradient step\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\toff<<m;//output Mt\n\t\t\t\n\t\t}else if(argv[1][0]=='g'){\n\t\t\tofstream off(\"G0.dat\");\n\t\t\tcout<<\"Voy a calcular la matriz G0\"<<endl;\n\t\t\tArchivoTrain archivo;\n\t\t\tArchivoNeighbors neighbors(archivo);\n\t\t\tMatriz g0;\n\t\t\tneighbors.calcularG0(g0);\n\t\t\tcout<<\"G0 es \"<<g0<<endl;\n\t\t\toff<<g0;\n\t\t}else if(argv[1][0]=='a'){\n\t\t\tofstream off(\"G0.dat\");\n\t\t\tcout<<\"Voy a calcular los ActiveSets\"<<endl;\n\t\t\tMatriz m,g0;\n\t\t\tm.setIdentity();\n\t\t\tArchivoTrain archivo;\n\t\t\tArchivoNeighbors neighbors(archivo);\n\t\t\t\n\t\t\tConjuntoActiveSets caca;\n\t\t\tneighbors.agregarActiveSets(caca);\n\t\t\tcout<<\"Activesets: \"<<caca.size()<<endl;\n\t\t}\n\t}\n\treturn 0;\n}\n\n", "meta": {"hexsha": "bf68c43e1c85b93882b59bfa282b9fef6d8e17ca", "size": 3970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AprenderMetrica/src/main.cpp", "max_stars_repo_name": "soyyo5159/EnergyBasedChaos", "max_stars_repo_head_hexsha": "fcc5ef1852937f77cafb4537887cfeb0f4906202", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AprenderMetrica/src/main.cpp", "max_issues_repo_name": "soyyo5159/EnergyBasedChaos", "max_issues_repo_head_hexsha": "fcc5ef1852937f77cafb4537887cfeb0f4906202", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AprenderMetrica/src/main.cpp", "max_forks_repo_name": "soyyo5159/EnergyBasedChaos", "max_forks_repo_head_hexsha": "fcc5ef1852937f77cafb4537887cfeb0f4906202", "max_forks_repo_licenses": ["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.768115942, "max_line_length": 84, "alphanum_fraction": 0.683627204, "num_tokens": 1158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5468811162366798}}
{"text": "#include \"average_case_error.hpp\"\n\n#include <cudd_helpers.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace abo::error_metrics {\n\n    boost::multiprecision::cpp_dec_float_100 average_value(const std::vector<BDD> &f) {\n\n        boost::multiprecision::uint256_t sum = 0;\n        const boost::multiprecision::uint256_t one = 1;\n\n        int max_support_size = 0;\n        for (const auto &bdd : f) {\n            max_support_size = std::max(max_support_size, bdd.SupportSize());\n        }\n\n        for (unsigned int i = 0;i<f.size();i++) {\n            // TODO: CountMinterms returns a double, might loose precision\n            double minterms = f[i].CountMinterm(max_support_size);\n            sum += (one << i) * boost::multiprecision::uint256_t(minterms);\n        }\n\n        return boost::multiprecision::cpp_dec_float_100(sum) /\n                boost::multiprecision::cpp_dec_float_100(one << max_support_size);\n    }\n\n    boost::multiprecision::cpp_dec_float_100 mean_squared_value(const std::vector<BDD> &f) {\n\n        boost::multiprecision::uint256_t sum = 0;\n        const boost::multiprecision::uint256_t one = 1;\n\n        int max_support_size = 0;\n        for (const auto &bdd : f) {\n            max_support_size = std::max(max_support_size, bdd.SupportSize());\n        }\n\n        for (unsigned int i = 0;i<f.size();i++) {\n            for (unsigned int b = i;b<f.size();b++) {\n                // cudd handles the case i = b efficiently\n                BDD both = f[i] & f[b];\n                double minterms = both.CountMinterm(max_support_size);\n                // most terms (except for i == b), appear twice when factoring the square\n                boost::multiprecision::uint256_t doubling_factor = i == b ? 1 : 2;\n                sum += (one << i) * (one << b) * boost::multiprecision::uint256_t(minterms) * doubling_factor;\n            }\n        }\n\n        return boost::multiprecision::cpp_dec_float_100(sum) /\n                boost::multiprecision::cpp_dec_float_100(one << max_support_size);\n    }\n\n    boost::multiprecision::cpp_dec_float_100 average_case_error(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_value(absolute_difference);\n    }\n\n    boost::multiprecision::cpp_dec_float_100 mean_squared_error(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 mean_squared_value(absolute_difference);\n    }\n\n\n    boost::multiprecision::cpp_dec_float_100 average_case_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        std::vector<std::pair<double, unsigned long>> terminal_values = abo::util::add_terminal_values(diff);\n\n        boost::multiprecision::uint256_t sum = 0;\n        boost::multiprecision::uint256_t path_sum = 0;\n        for (auto p : terminal_values) {\n            sum += boost::multiprecision::uint256_t(p.first) * 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 mean_squared_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        std::vector<std::pair<double, unsigned long>> terminal_values = abo::util::add_terminal_values(diff);\n\n        boost::multiprecision::uint256_t sum = 0;\n        boost::multiprecision::uint256_t path_sum = 0;\n        for (auto p : terminal_values) {\n            boost::multiprecision::uint256_t value(p.first);\n            sum += value * 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}\n", "meta": {"hexsha": "d97e2a401766eb70dd1696d7c7fef5f3efda5915", "size": 4572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/error_metrics/average_case_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_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_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": 44.8235294118, "max_line_length": 142, "alphanum_fraction": 0.6084864392, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5468811073307273}}
{"text": "#include \"Gamma.h\"\n#include <boost/math/distributions/gamma.hpp>\n\nBaseDistributionGamma::BaseDistributionGamma(const Options& iOptions, const Data& iData) : BaseDistribution(iOptions, iData) {\n\n}\nfloat BaseDistributionGamma::getCdf(float iX, const std::vector<float>& iMoments) const {\n   assert(iMoments.size() == 2);\n   float mean     = iMoments[0];\n   float variance = iMoments[1];\n   if(variance == 0) {\n      return Global::MV;\n   }\n   float scale    = getScale(mean, variance);\n   float shape    = getShape(mean, variance);\n   boost::math::gamma_distribution<> dist(shape, scale);\n   return boost::math::cdf(dist, iX);\n}\nfloat BaseDistributionGamma::getPdf(float iX, const std::vector<float>& iMoments) const {\n   assert(iMoments.size() == 2);\n   float mean     = iMoments[0];\n   float variance = iMoments[1];\n   if(variance == 0) {\n      return Global::MV;\n   }\n   float scale    = getScale(mean, variance);\n   float shape    = getShape(mean, variance);\n   //std::cout << \"Scale, shape = \" << scale << \" \" << shape << std::endl;\n   boost::math::gamma_distribution<> dist(shape, scale);\n   //std::cout << scale << \" \" << shape << std::endl;\n   return boost::math::pdf(dist, iX);\n}\nfloat BaseDistributionGamma::getInv(float iCdf, const std::vector<float>& iMoments) const {\n   assert(iMoments.size() == 2);\n   float mean     = iMoments[0];\n   float variance = iMoments[1];\n   if(variance == 0) {\n      return Global::MV;\n   }\n   float scale    = getScale(mean, variance);\n   float shape    = getShape(mean, variance);\n   boost::math::gamma_distribution<> dist(shape, scale);\n   return boost::math::quantile(dist, iCdf);\n}\nint BaseDistributionGamma::getNumMoments() const {\n   return 2;\n}\nfloat BaseDistributionGamma::getShape(float iMean, float iVariance) {\n   // alpha (wiki: k)\n   return iMean*iMean / iVariance;\n}\nfloat BaseDistributionGamma::getScale(float iMean, float iVariance) {\n   // beta (wiki: theta)\n   return iVariance / iMean;\n}\n", "meta": {"hexsha": "183766d5d945587f16a23541ee4a10905504e3e5", "size": 1948, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BaseDistributions/Gamma.cpp", "max_stars_repo_name": "dsiuta/Comps", "max_stars_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "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/BaseDistributions/Gamma.cpp", "max_issues_repo_name": "dsiuta/Comps", "max_issues_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BaseDistributions/Gamma.cpp", "max_forks_repo_name": "dsiuta/Comps", "max_forks_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "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.7857142857, "max_line_length": 126, "alphanum_fraction": 0.6647843943, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5468811042870807}}
{"text": "#include <limits>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n// Includes\n// ========\n#include <iostream>\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/cycle_canceling.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n\n// Graph Type with nested interior edge properties for Cost Flow Algorithms\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,\n                boost::property <boost::edge_weight_t, long> > > > > graph; // new! weightmap corresponds to costs\n\ntypedef boost::graph_traits<graph>::edge_descriptor             edge_desc;\ntypedef boost::graph_traits<graph>::out_edge_iterator           out_edge_it; // Iterator\n\n// Custom edge adder class\nclass edge_adder {\n graph &G;\n\n public:\n  explicit edge_adder(graph &G) : G(G) {}\n  void add_edge(int from, int to, long capacity, long cost) {\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    auto w_map = boost::get(boost::edge_weight, G); // new!\n    const edge_desc e = boost::add_edge(from, to, G).first;\n    const edge_desc 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    w_map[e] = cost;   // new assign cost\n    w_map[rev_e] = -cost;   // new negative cost\n  }\n};\n\n\nint ind(int i, int j, int n) {\n    return  i * n + j;\n}\n\nvoid testcase() {\n    int n; std::cin >> n;\n    int nn = n * n;\n    int sum_a = 0;\n    std::vector<std::vector<int>> a(n, std::vector<int>(n));\n    for(int i = 0; i < n; i++) {\n        for(int j = 0; j < n; j++) {\n            std::cin >> a[i][j];\n            sum_a += a[i][j];\n        }\n    }\n\n    graph G(2 * nn);\n    edge_adder adder(G);\n    int max_a = 100;\n    const int v_source = nn;\n    const int v_sink = nn - 1;\n    for(int i = 0; i < n; i++) {\n        for(int j = 0; j < n; j++) {\n            if(i < n - 1) adder.add_edge(nn + ind(i,j,n), ind(i+1,j,n), 1, 0);\n            if(j < n - 1) adder.add_edge(nn + ind(i,j,n), ind(i,j+1,n), 1, 0);\n            if(!( (i == 0 && j == 0) || (i == n - 1 && j == n - 1))) {\n                adder.add_edge(ind(i,j,n), nn + ind(i,j,n), 1, -a[i][j] + max_a);\n            }\n        }\n    }\n    \n    boost::successive_shortest_path_nonnegative_weights(G, v_source, v_sink);\n    int cost1 = boost::find_flow_cost(G);\n    // std::cerr << cost1 << \" \" << (4 * n - 6) * max_a << std::endl;\n    std::cout << (4 * n - 6) * max_a - cost1 + a[0][0] + a[n-1][n-1] << std::endl;\n    return;\n}\n\nint main() {\n    std::ios_base::sync_with_stdio(false);\n\n    int t;\n    std::cin >> t;\n    for (int i = 0; i < t; ++i)\n        testcase();\n}\n", "meta": {"hexsha": "4a39549d14dce970fca62cb228c092d5940b400c", "size": 3178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week12-bonus_level/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/week12-bonus_level/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/week12-bonus_level/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": 32.7628865979, "max_line_length": 114, "alphanum_fraction": 0.5918816866, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5468811028777508}}
{"text": "//===------------------------------------------------------------*- C++ -*-===//\n///\n/// \\brief \u4eff\u5c04\u53d8\u6362\u3002\n/// \\details \u5373\u7ebf\u6027\u53d8\u6362\u548c\u4f4d\u79fb\u53d8\u6362\uff1a\u8f93\u51fa\u5411\u91cf v' = \u7ebf\u6027\u53d8\u6362\u77e9\u9635 M * \u8f93\u5165\u5411\u91cf v + \u4f4d\u79fb\u5411\u91cf k\u3002\n///\n/// \\sa <https://zh.wikipedia.org/wiki/\u4eff\u5c04\u53d8\u6362>\n///\n/// \\version 2021-11-08\n/// \\since 2021-11-08\n/// \\authors zhengrr\n/// \\copyright Unlicense\n///\n//===----------------------------------------------------------------------===//\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <gtest/gtest.h>\n\nTEST(AffineTransformation, Case)\n{\n    using Scalar = float;\n    constexpr Eigen::Index dimension = 2;\n    using Point = Eigen::Vector<Scalar, dimension>;\n    using LinearTransformationMatrix = Eigen::Matrix<Scalar, dimension, dimension>;\n    using AffineTransformationMatrix = Eigen::Transform<Scalar, dimension, Eigen::Affine>;\n    //                       [x ]\n    //                       [y ]\n    //                       [1 ]\n    //\n    // [M(0,0) M(0,1) k(x)]  [x'] = M(0,0)x + M(0,1)y + k(x)\n    // [M(1,0) M(1,1) k(y)]  [y'] = M(1,0)x + M(1,0)y + k(y)\n    // [0      0      1   ]  [1 ] = 1\n\n    // \u5355\u4f4d\u77e9\u9635\n    const auto i = AffineTransformationMatrix::Identity();\n\n    const Eigen::Matrix<Scalar, dimension + 1, dimension + 1> matrix {\n        {1, 0, 0},\n        {0, 1, 0},\n        {0, 0, 1}\n    };\n    const Eigen::Matrix<Scalar, dimension, dimension> rotation {\n        {1, 0},\n        {0, 1}\n    };\n    const Eigen::Matrix<Scalar, dimension, 1> translation {\n        {0},\n        {0}\n    };\n    EXPECT_EQ(i.matrix(), matrix);\n    EXPECT_EQ(i.rotation(), rotation);\n    EXPECT_EQ(i.translation(), translation);\n}\n", "meta": {"hexsha": "95de2e035b63b9b456842e08d2b5a523226f8b39", "size": 1592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rrEigen/Geometry/affine_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/affine_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/affine_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": 29.4814814815, "max_line_length": 90, "alphanum_fraction": 0.4817839196, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5468594457980308}}
{"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__LMPAR_HPP_\n#define SMOOTH__INTERNAL__LMPAR_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Jacobi>\n#include <Eigen/QR>\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n\n#include \"utils.hpp\"\n\nnamespace smooth::detail {\n\n/**\n * @brief Solve structured least-squares probelm\n *\n *   min_x \\| [J ; D] x + [r; 0] \\|^2\n *\n * Where a is a size N vector and J is M x N\n * and it must hold that J^T J + D^T D is positive semi-definite\n * where D = diag(d) is a diagonal matrix\n *\n * Let J P = Q R0  be a QR decomposition of J where P is a permutation matrix\n *\n * @param[in, out] R top left NxN corner of R0 (NxN upper triangular) (dense or sparse supported)\n * @param[in] Qt_r N-vector containing product Q' * r\n * @param[in] P NxN permutation matrix in QR decomposition\n * @param[in] d N-vector representing diagonal of D\n *\n * The function modifies R to be an upper triangular matrix Rt in the QR decomposition\n * of [R; P' D P] which satisfies\n *\n *    Rt' Rt = P' (J' J + D' D) P\n *\n * NOTE For systems with M < N, R and Qt_r should be filled with zeros at the bottom\n *\n * NOTE To maximize performance in the sparse case R should be Row-Major\n */\ntemplate<int N, typename MatrixType, typename PermIndex>\nEigen::Matrix<double, N, 1> solve_ls(MatrixType & R,\n  const Eigen::Matrix<double, N, 1> & Qt_r,\n  const Eigen::PermutationMatrix<N, N, PermIndex> & P,\n  const Eigen::Matrix<double, N, 1> & d)\n{\n  // true if R is sparse\n  static constexpr bool is_sparse =\n    std::is_base_of_v<Eigen::SparseMatrixBase<MatrixType>, MatrixType>;\n\n  const auto n                  = R.cols();\n  Eigen::Matrix<double, N, 1> a = Qt_r;\n\n  // We operate on B and b row-wise, so just need to allocate one row\n  Eigen::Matrix<double, N, 1> Bj(n);\n  double bj;\n\n  // QR decomposition of [R; P' D P] with Givens rotations;\n  // where it is known that A is upper triangular and B is diagonal\n  // algorithm:\n  //   R = A, Q = I\n  //   for each nonzero in B part:\n  //      find rotation G that eliminates nonzero without introducing new zeros\n  //      Q = Q G\n  //      R = G' R\n  Eigen::JacobiRotation<double> G;\n  for (auto j = 0u; j != n; ++j) {  // for each diagonal element\n    // find permuted diagonal index\n    const auto permidx = P.indices()(j);\n    // initialize row j of B and b\n    Bj.tail(n - 1 - j).setZero();\n    Bj(j) = d(permidx);  // Bj(k) represents B(j, k)\n    bj    = 0;           // bj represents b(j)\n\n    for (auto col = j; col != n; ++col) {  // for each column right of diagonal\n      if (R.coeff(col, col) >= 0 && Bj(col) == 0) { continue; }\n\n      double r;\n      G.makeGivens(R.coeff(col, col), Bj(col), &r);  // eliminates B(j, col)\n\n      // perform matrix multiplication R = G' R\n      // affects row 'col' of R and row 'j' of B\n      R.coeffRef(col, col) = r;\n      for (auto k = col + 1; k != n; ++k) {\n        const double tmp = G.c() * R.coeff(col, k) - G.s() * Bj(k);\n        Bj(k)            = G.s() * R.coeff(col, k) + G.c() * Bj(k);\n        if constexpr (is_sparse) {\n          if (R.coeff(col, k) != 0 || tmp != 0) { R.coeffRef(col, k) = tmp; }\n        } else {\n          R.coeffRef(col, k) = tmp;\n        }\n      }\n\n      // At the end we need Q matrix to multiply rhs as\n      // Q' * rhs = (I * G0 * ... * Gk)' * rhs = Gk' * ... * G0' * rhs\n      //\n      // We can therefore do it as we go, here we set\n      // rhs = G * rhs\n      const double tmp = G.c() * a(col) - G.s() * bj;\n      bj               = G.s() * a(col) + G.c() * bj;\n      a(col)           = tmp;\n    }\n  }\n\n  // solve triangular system R z = a to obtain z = R^-1 z\n  // first check rank of upper-diagonal R (may happen if d not full-rank)\n  int rank = 0;\n  for (; rank != n && R.coeff(rank, rank) >= Eigen::NumTraits<double>::dummy_precision(); ++rank) {}\n\n  Eigen::Matrix<double, N, 1> sol(n);\n  sol.tail(n - rank).setZero();\n  sol.head(rank) =\n    R.topLeftCorner(rank, rank).template triangularView<Eigen::Upper>().solve(a.head(rank));\n\n  // solution is now equal to -P z\n  return -(P * sol);\n}\n\n/**\n * @brief Solve structured least-squares probelm\n *\n *   min_x \\| [J ; D] x + [r; 0] \\|^2\n *\n * Where a is a size N vector and J is M x N\n * and it must hold that J^T J + D^T D is positive semi-definite\n * where D = diag(d) is a diagonal matrix\n *\n * @param J_qr QR decomposition J P = Q R of J with column pivoting\n * @param d vector of length N representing diagonal matrix\n * @param r vector with same number of elements as there are rows in J\n */\ntemplate<int N, int M, typename QrType>\nEigen::Matrix<double, N, 1> solve_ls(\n  const QrType & J_qr, const Eigen::Matrix<double, N, 1> & d, const Eigen::Matrix<double, M, 1> & r)\n{\n  // true if it's a sparse decomposition\n  static constexpr bool is_sparse =\n    std::is_base_of_v<Eigen::SparseMatrixBase<typename QrType::MatrixType>,\n      typename QrType::MatrixType>;\n\n  // figure type to use for A matrix\n  using AType = std::conditional_t<is_sparse,\n    Eigen::SparseMatrix<double, Eigen::RowMajor>,\n    Eigen::Matrix<double, N, N>>;\n\n  static constexpr int NM_min  = std::min(N, M);\n  static constexpr int NM_rest = NM_min == -1 ? -1 : N - NM_min;\n\n  // dynamic sizes\n  const auto n       = J_qr.cols();\n  const auto m       = J_qr.rows();\n  const auto nm_min  = std::min(n, m);\n  const auto nm_rest = n - nm_min;\n\n  AType R(n, n);\n  if constexpr (is_sparse) {\n    // allocate upper triangular pattern\n    Eigen::Matrix<Eigen::Index, N, 1> pattern(n);\n    for (auto i = 0u; i != n; ++i) { pattern(i) = i + 1; }\n    R.reserve(pattern);\n  } else {\n    R.template bottomRows<NM_rest>(nm_rest).setZero();\n  }\n  R.template topRows<NM_min>(nm_min) = J_qr.matrixR().template topRows<NM_min>(nm_min);\n\n  Eigen::Matrix<double, N, 1> Qt_r(n);\n  Qt_r.template head<NM_min>(nm_min) =\n    (J_qr.matrixQ().transpose() * r).template head<NM_min>(nm_min);\n  Qt_r.template bottomRows<NM_rest>(nm_rest).setZero();\n\n  return solve_ls<N>(R, Qt_r, J_qr.colsPermutation(), d);\n}\n\n/**\n * @brief Approximate a Levenberg-Marquardt parameter lambda s.t. if x solves\n *\n *   \\| [J; sqrt(lambda) * diag(d)] x  +  [r ; 0] \\|^2\n *\n * then either\n *  * lambda = 0 AND \\|diag(d) * x\\| <= 1.1 Delta\n *    OR\n *  * lambda > 0 AND 0.9 Delta <= \\|diag(d) * x\\| <= 1.1 Delta\n *\n * @param J matrix MxN (static/dynamic/sparse sizes supported)\n * @param d vector size Nx1 (static/dynamic sizes supported)\n * @param r vector size Mx1 (static/dynamic sizes supported)\n * @param Delta scalar\n * @return pair(lambda, x) where x solves the least-squares problem for lambda\n *\n * @note The sparse QR decomposition is numerically unstable for ill-conditioned matrices.\n * Consider using lmpar_sparse instead.\n */\ntemplate<int N, int M, typename MatrixT>\nstd::pair<double, Eigen::Matrix<double, N, 1>> lmpar(const MatrixT & J,\n  const Eigen::Matrix<double, N, 1> & d,\n  const Eigen::Matrix<double, M, 1> & r,\n  double Delta)\n{\n  static constexpr bool is_sparse = std::is_base_of_v<Eigen::SparseMatrixBase<MatrixT>, MatrixT>;\n\n  static constexpr int NM_min  = std::min(N, M);\n  static constexpr int NM_rest = NM_min == -1 ? -1 : N - NM_min;\n\n  // dynamic sizes\n  const auto m       = J.rows();\n  const auto n       = J.cols();\n  const auto nm_min  = std::min(n, m);\n  const auto nm_rest = n - nm_min;\n\n  // calculate qr decomposition of J\n  std::conditional_t<is_sparse,\n    Eigen::SparseQR<MatrixT, Eigen::COLAMDOrdering<int>>,\n    Eigen::ColPivHouseholderQR<MatrixT>> J_qr;\n\n  if constexpr (is_sparse) {\n    // sparse solver is not very good for close-to-singular matrices\n    // J_qr.setPivotThreshold(1e-1);\n  }\n\n  J_qr.compute(J);\n\n  // calculate size n Qt_r\n  Eigen::Matrix<double, N, 1> Qt_r(n);\n  Qt_r.template head<NM_min>(nm_min) =\n    (J_qr.matrixQ().transpose() * r).template head<NM_min>(nm_min);\n  Qt_r.template bottomRows<NM_rest>(nm_rest).setZero();\n\n  // calculate phi(0) by solving J x = -r as x = P R^-1 (-Q' r)\n  Eigen::Matrix<double, N, 1> x(n);\n  int rank     = J_qr.rank();\n  x.head(rank) = J_qr.matrixR()\n                   .topLeftCorner(rank, rank)\n                   .template triangularView<Eigen::Upper>()\n                   .solve(-Qt_r.head(rank));\n  x.tail(n - rank).setZero();\n  x.applyOnTheLeft(J_qr.colsPermutation());\n\n  Eigen::Matrix<double, N, 1> D_x_iter = d.cwiseProduct(x);\n  double D_x_iter_norm                 = D_x_iter.stableNorm();\n\n  double alpha = 0;\n  double phi   = D_x_iter_norm - Delta;\n  double dphi;\n\n  if (phi <= 0.1 * Delta) {\n    // alpha = 0 solution fulfills condition\n    return std::make_pair(alpha, std::move(x));\n  }\n\n  // lower bound\n  double l = 0;\n  if (J_qr.rank() == n) {\n    // full rank means we can calculate dphi(0)\n    // as - \\| D x \\| * \\| Rinv (P' D' D x) / \\| Dx \\| \\|^2\n    Eigen::Matrix<double, N, 1> y =\n      J_qr.colsPermutation().inverse() * (d.cwiseProduct(D_x_iter) / D_x_iter_norm);\n    J_qr.matrixR()\n      .template topLeftCorner<N, N>(n, n)\n      .template triangularView<Eigen::Upper>()\n      .transpose()\n      .solveInPlace(y);\n    dphi = -D_x_iter_norm * y.squaredNorm();\n    l    = std::max(l, -phi / dphi);\n  }\n\n  // upper bound\n  double u = (d.cwiseInverse().cwiseProduct(J.transpose() * r)).stableNorm() / Delta;\n\n  // it typically converges in 2 or 3 iterations\n  for (auto i = 0u; i != 20; ++i) {\n    // ensure alpha stays within bounds (and not equal to zero)\n    if (!(l < alpha && alpha < u)) { alpha = std::max<double>(0.001 * u, sqrt(l * u)); }\n\n    // solve least-squares problem\n    using RType = std::conditional_t<is_sparse,\n      Eigen::SparseMatrix<double, Eigen::RowMajor>,\n      Eigen::Matrix<double, N, N>>;\n    RType R(n, n);\n    R.template topRows<NM_min>(nm_min) = J_qr.matrixR().template topRows<NM_min>(nm_min);\n    if constexpr (!is_sparse) { R.template bottomRows<NM_rest>(nm_rest).setZero(); }\n    x = solve_ls<N>(R, Qt_r, J_qr.colsPermutation(), sqrt(alpha) * d);\n    if constexpr (is_sparse) { R.makeCompressed(); }\n\n    // calculate phi\n    D_x_iter      = d.cwiseProduct(x);\n    D_x_iter_norm = D_x_iter.stableNorm();\n    phi           = D_x_iter_norm - Delta;\n\n    if (std::abs(phi) <= 0.1 * Delta) {\n      break;  // condition fulfilled\n    }\n\n    // calculate derivative of phi wrt alpha\n    Eigen::Matrix<double, N, 1> y =\n      J_qr.colsPermutation().inverse() * (d.cwiseProduct(D_x_iter) / D_x_iter_norm);\n    R.template triangularView<Eigen::Upper>().transpose().solveInPlace(y);\n    dphi = -D_x_iter_norm * y.squaredNorm();\n\n    // update bounds\n    l = std::max<double>(l, alpha - phi / dphi);\n    if (phi < 0) { u = alpha; }\n\n    // update alpha\n    alpha = alpha - ((phi + Delta) / Delta) * (phi / dphi);\n  }\n\n  return std::make_pair(alpha, std::move(x));\n}\n\n}  // namespace smooth::detail\n\n#endif  // SMOOTH__INTERNAL__LMPAR_HPP_\n", "meta": {"hexsha": "36952309e3a143d6f8d89b31a3bd0fc16b1d5135", "size": 11950, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/internal/lmpar.hpp", "max_stars_repo_name": "NamDinhRobotics/smooth", "max_stars_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:18.000Z", "max_issues_repo_path": "include/smooth/internal/lmpar.hpp", "max_issues_repo_name": "NamDinhRobotics/smooth", "max_issues_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_issues_repo_licenses": ["MIT"], "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/lmpar.hpp", "max_forks_repo_name": "NamDinhRobotics/smooth", "max_forks_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_forks_repo_licenses": ["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.5654761905, "max_line_length": 100, "alphanum_fraction": 0.6328870293, "num_tokens": 3528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5468594404015468}}
{"text": "#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n\n#include \"LSLOpt/BFGS.hpp\"\n\n#include \"ModelSystem.hpp\"\n\n\nint main(int argc, char* argv[])\n{\n  int mode;\n  if (argc == 0) {\n    mode = 0;\n  }\n  else {\n    try {\n      mode = std::stoi(argv[1]);\n    }\n    catch (...) {\n      mode = 0;\n    }\n  }\n\n  ModelSystem modelSystem;\n\n  std::cerr << std::setprecision(16);\n\n  double angle_eps = 0.1 * M_PI / 180.0;\n\n  unsigned n_steps = static_cast<unsigned>((2 * M_PI) / angle_eps) + 1;\n\n  for (unsigned i = 0; i < n_steps; ++i) {\n    double angle = angle_eps * i;\n    double x = modelSystem.x0.norm() * std::sin(angle);\n    double y = modelSystem.x0.norm() * std::cos(angle);\n    Eigen::VectorXd x0 = Eigen::VectorXd::Zero(1);\n    x0[0] = angle;\n\n    LSLOpt::OptimizationParameters<double> params\n        = LSLOpt::getOptimizationParameters<double>();\n    LSLOpt::OstreamOutput output{LSLOpt::OutputLevel::Status, std::cout};\n\n    LSLOpt::OptimizationResult<double> result;\n    if (mode == 0) {\n      result = LSLOpt::lsl_bfgs(modelSystem, x0, params, output);\n    }\n    else {\n      result = LSLOpt::bfgs(modelSystem, x0, params, output);\n    }\n\n    double dist = sqrt(pow(modelSystem.to_cartesian(result.x)[0] - modelSystem.to_cartesian(x0)[0], 2)\n                     + pow(modelSystem.to_cartesian(result.x)[1] - modelSystem.to_cartesian(x0)[1], 2));\n    std::cerr << angle << \";\" << x << \";\" << y << \";\" << result.function_value << \";\" << dist << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "89b395308dabbeab1e65b490775d12809574f0c1", "size": 1485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PaperExamples/Plot2dOpt.cpp", "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/Plot2dOpt.cpp", "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/Plot2dOpt.cpp", "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": 24.75, "max_line_length": 107, "alphanum_fraction": 0.597979798, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5468594350050628}}
{"text": "// Original source code from:\n// https://github.com/stegua/MyBlogEntries/tree/master/Dijkstra\n\n/// My typedefs\n#include <boost/cstdint.hpp>\n#include <boost/integer_traits.hpp>\n#include <inttypes.h>\n\ntypedef int32_t node_t;\ntypedef int32_t edge_t;\ntypedef int64_t cost_t;\n\n/// From STL library\n#include <fstream>\n\n#include <vector>\nusing std::vector;\n\n#include <string>\n\nusing std::make_pair;\nusing std::pair;\n\n/// Lemon Graph Library\n#include <lemon/smart_graph.h>\nusing lemon::SmartDigraph;\n\n#include <lemon/adaptors.h>\n#include <lemon/concepts/maps.h>\n#include <lemon/dijkstra.h>\n#include <lemon/path.h>\ntypedef SmartDigraph::Arc Arc;\ntypedef SmartDigraph::Node Node;\ntypedef SmartDigraph::ArcMap<cost_t> LengthMap;\n\n#include <lemon/fib_heap.h>\ntypedef SmartDigraph::NodeMap<int> NodeMap;\ntypedef lemon::FibHeap<cost_t, NodeMap> FibonacciHeap;\n\n/// Boost Timer\n#include <boost/progress.hpp>\nusing boost::timer;\n\nusing namespace boost;\n\n/// Read input data, build graph, and run Dijkstra\ncost_t runDijkstra(char *argv[]) {\n  /// Read instance from the OR-lib\n  std::ifstream infile(argv[1]);\n  if (!infile)\n    exit(EXIT_FAILURE);\n\n  int n; /// Number of variables\n  int m; /// Number of constraints\n\n  // reads file of the form\n  // #nodes #edges\n  // e_1 = v_i v_j cost[e_m]\n  // ..\n  // e_m = v_i v_j cost[e_m]\n\n  /// Read the first line\n  infile >> n >> m;\n  fprintf(stdout, \"n %d, m %d\\t\", n, m);\n  /// Build the graph\n  SmartDigraph G;\n  G.reserveNode(n);\n  G.reserveArc(m);\n  vector<Node> vs;\n  vs.reserve(n);\n  for (int i = 0; i < n; ++i)\n    vs.push_back(G.addNode());\n\n  int v, w;\n  cost_t c;\n  cost_t T_dist;\n  LengthMap C(G);\n  for (int i = 0; i < m; i++) {\n    infile >> v >> w >> c;\n    Arc a;\n    a = G.addArc(vs[v - 1], vs[w - 1]);\n    C[a] = c;\n  }\n\n  timer TIMER;\n  for (int i = 0; i < 50; ++i) {\n    double t0 = TIMER.elapsed();\n    Node S = vs[i];\n    Node T = vs[n - 1 - i];\n    // NodeMap heap_cross_ref(G);\n    // FibonacciHeap heap(heap_cross_ref);\n    // lemon::Dijkstra<SmartDigraph, LengthMap>::SetHeap<FibonacciHeap,\n    // NodeMap>::Create spp(G, C); spp.heap( heap, heap_cross_ref );\n    lemon::Dijkstra<SmartDigraph, LengthMap> spp(G, C);\n    spp.run(S, T);\n    T_dist = spp.dist(T);\n    fprintf(stdout, \"Time %.4f Cost %\" PRId64 \"\\n\", TIMER.elapsed() - t0,\n            T_dist);\n  }\n  fprintf(stdout, \"Tot %.4f\\n\", TIMER.elapsed());\n\n  return T_dist;\n}\n\n/// Main function\nint main(int argc, char **argv) {\n  if (argc != 2) {\n    fprintf(stdout, \"usage: ./dijkstra <filename>\\n\");\n    exit(EXIT_FAILURE);\n  }\n  /// Measure overall time\n  timer TIMER;\n  /// Invoke the different Dijkstra algorithm implementations\n  cost_t T_dist = runDijkstra(argv);\n  /// Print basic figures\n  fprintf(stdout, \"Cost %\" PRId64 \" - Time %.3f\\n\", T_dist, TIMER.elapsed());\n\n  return 0;\n}\n", "meta": {"hexsha": "b0fc965290265515b5637edb6334615954f33bac", "size": 2800, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/dijkstra_lemon.cc", "max_stars_repo_name": "torressa/cpp_graph_benchmarks", "max_stars_repo_head_hexsha": "f1a39024afb09a476e431e019bdbcac1ea4aa76d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dijkstra_lemon.cc", "max_issues_repo_name": "torressa/cpp_graph_benchmarks", "max_issues_repo_head_hexsha": "f1a39024afb09a476e431e019bdbcac1ea4aa76d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dijkstra_lemon.cc", "max_forks_repo_name": "torressa/cpp_graph_benchmarks", "max_forks_repo_head_hexsha": "f1a39024afb09a476e431e019bdbcac1ea4aa76d", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 77, "alphanum_fraction": 0.6460714286, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5468594333558368}}
{"text": "/*\n * Filename: ellipsoid.cpp\n *\n * Copyright 2020 Tecnalia\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 \"ellipsoid.h\"\n\n#include <Eigen/SVD>\n\nnamespace manipulability_metrics\n{\nEllipsoid ellipsoidFromJacobian(const Eigen::Matrix<double, 6, Eigen::Dynamic>& jacobian)\n{\n  auto jac_svd = Eigen::JacobiSVD<Eigen::Matrix<double, 6, Eigen::Dynamic>>{ jacobian, Eigen::ComputeFullU };\n\n  return { { { jac_svd.matrixU().col(0), jac_svd.singularValues()(0) },\n             { jac_svd.matrixU().col(1), jac_svd.singularValues()(1) },\n             { jac_svd.matrixU().col(2), jac_svd.singularValues()(2) },\n             { jac_svd.matrixU().col(3), jac_svd.singularValues()(3) },\n             { jac_svd.matrixU().col(4), jac_svd.singularValues()(4) },\n             { jac_svd.matrixU().col(5), jac_svd.singularValues()(5) } } };\n}\n}  // namespace manipulability_metrics\n", "meta": {"hexsha": "2cf4a850f618ec66845ea43aa75f3054a9ab4ddc", "size": 1384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "KDLUtils/ellipsoid.cpp", "max_stars_repo_name": "hyu-ryeol/RTControlDualArm", "max_stars_repo_head_hexsha": "30467a95863c5e33c355ec494d9a705ce84f98cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-02-06T09:55:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T12:29:16.000Z", "max_issues_repo_path": "KDLUtils/ellipsoid.cpp", "max_issues_repo_name": "hyu-ryeol/RTControlDualArm", "max_issues_repo_head_hexsha": "30467a95863c5e33c355ec494d9a705ce84f98cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KDLUtils/ellipsoid.cpp", "max_forks_repo_name": "hyu-ryeol/RTControlDualArm", "max_forks_repo_head_hexsha": "30467a95863c5e33c355ec494d9a705ce84f98cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-27T06:12:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T13:54:46.000Z", "avg_line_length": 37.4054054054, "max_line_length": 109, "alphanum_fraction": 0.686416185, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5468594333558368}}
{"text": "#define DEBUG 1\n/**\n * File    : F.cpp\n * Author  : Kazune Takahashi\n * Created : 5/19/2020, 3:57:45 PM\n * Powered by Visual Studio Code\n */\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n// ----- boost -----\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n// ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n// ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n// constexpr ll MOD{998244353LL}; // be careful\nconstexpr ll MAX_SIZE{3000010LL};\n// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n  }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n  }\n}\n// ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(const Mint &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(const Mint &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(const Mint &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator/=(const Mint &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }\n  bool operator<(const Mint &a) const { return x < a.x; }\n  bool operator<=(const Mint &a) const { return x <= a.x; }\n  bool operator>(const Mint &a) const { return x > a.x; }\n  bool operator>=(const Mint &a) const { return x >= a.x; }\n  bool operator==(const Mint &a) const { return x == a.x; }\n  bool operator!=(const Mint &a) const { return !(*this == a); }\n  const Mint power(ll N)\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N / 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n  return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)\n{\n  return Mint<MOD>{lhs} / rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n  return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n  return stream << a.x;\n}\n// ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i = 2LL; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i = 1LL; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x / gcd(x, y) * y; }\n// ----- for C++17 -----\ntemplate <typename T>\nint popcount(T x) // C++20\n{\n  int ans{0};\n  while (x != 0)\n  {\n    ans += x & 1;\n    x >>= 1;\n  }\n  return ans;\n}\n// ----- frequently used constexpr -----\n// constexpr double epsilon{1e-10};\n// constexpr ll infty{1000000000000000LL}; // or\n// constexpr int infty{1'000'000'010};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\n// ----- LCA -----\n\nclass LCA\n{\n  // helper classes\n  struct Edge\n  {\n    // Initialized by initializer list. Take care fore the order of the field.\n    int src, dst;\n    ll cost;\n  };\n\n  struct Vertex\n  {\n    int depth;\n    ll length;\n  };\n\n  // fields\n  int N, root, L;\n  vector<vector<Edge>> E;\n  vector<Vertex> V;\n  vector<vector<int>> ancestors;\n\n  // methods\npublic:\n  LCA(int N, int root = 0);\n  void add_edge(int a, int b, ll c = 0);\n  void init();\n  void init(int root); // after adding all edges.\n\n  // LCA\n  int operator()(int a, int b);\n\n  int depth(int a, int b) { return V[a].depth + V[b].depth - 2 * V[(*this)(a, b)].depth; }\n  int depth(int v) { return depth(v, root); }\n  ll length(int a, int b) { return V[a].length + V[b].length - 2 * V[(*this)(a, b)].length; }\n  ll length(int v) { return length(v, root); }\n  int parent(int v) { return ancestors[v][0]; }\n\nprivate:\n  void dfs(int v, int d = 0, ll l = 0, int p = -1);\n};\n\n// LCA: implement\n\nLCA::LCA(int N, int root) : N{N}, root{root}, L{0}, E(N), V(N)\n{\n  while ((1 << L) < N)\n  {\n    ++L;\n  }\n  ancestors = vector<vector<int>>(N + 1, vector<int>(L, N));\n}\n\nvoid LCA::add_edge(int a, int b, ll c)\n{\n  E[a].push_back(LCA::Edge{a, b, c});\n  E[b].push_back(LCA::Edge{b, a, c});\n}\n\nvoid LCA::init(int root)\n{\n  LCA::root = root;\n  init();\n}\n\nvoid LCA::init()\n{\n  dfs(root);\n  for (auto i = 0; i < L - 1; i++)\n  {\n    for (auto v = 0; v < N; v++)\n    {\n      if (ancestors[v][i] != -1)\n      {\n        ancestors[v][i + 1] = ancestors[ancestors[v][i]][i];\n      }\n    }\n  }\n}\n\nint LCA::operator()(int a, int b)\n{\n  if (V[a].depth > V[b].depth)\n  {\n    swap(a, b);\n  }\n  int gap = V[b].depth - V[a].depth;\n  for (auto i = L - 1; i >= 0; i--)\n  {\n    int len{1 << i};\n    if (gap >= len)\n    {\n      gap -= len;\n      b = ancestors[b][i];\n    }\n  }\n  if (a == b)\n  {\n    return a;\n  }\n  for (auto i = L - 1; i >= 0; i--)\n  {\n    int na{ancestors[a][i]};\n    int nb{ancestors[b][i]};\n    if (na != nb)\n    {\n      a = na;\n      b = nb;\n    }\n  }\n  return ancestors[a][0];\n}\n\nvoid LCA::dfs(int v, int d, ll l, int p)\n{\n  if (p != -1)\n  {\n    ancestors[v][0] = p;\n  }\n  V[v].depth = d;\n  V[v].length = l;\n  for (auto const &e : E[v])\n  {\n    int u{e.dst};\n    if (u == p)\n    {\n      continue;\n    }\n    dfs(u, d + 1, l + e.cost, v);\n  }\n}\n\n// ----- main() -----\n\nstruct Query\n{\n  int id, color, y, coefficient;\n};\n\nstruct Edge\n{\n  int src, dst, color, cost;\n};\n\nclass Solve\n{\n  int N, Q;\n  vector<vector<Edge>> V;\n  vector<vector<Query>> W;\n  LCA lca;\n  vector<int> ans;\n  vector<int> sum, cnt;\n\npublic:\n  Solve(int N, int Q) : N{N}, Q{Q}, V(N), W(N), lca{N}, ans(Q), sum(N - 1, 0), cnt(N - 1, 0)\n  {\n    for (auto i = 0; i < N - 1; ++i)\n    {\n      int a, b, c, d;\n      cin >> a >> b >> c >> d;\n      --a;\n      --b;\n      --c;\n      V[a].push_back({a, b, c, d});\n      V[b].push_back({b, a, c, d});\n      lca.add_edge(a, b, d);\n    }\n    lca.init(0);\n    for (auto i = 0; i < Q; ++i)\n    {\n      int x, y, u, v;\n      cin >> x >> y >> u >> v;\n      --x;\n      --u;\n      --v;\n      W[u].push_back({i, x, y, 1});\n      W[v].push_back({i, x, y, 1});\n      W[lca(u, v)].push_back({i, x, y, -2});\n      ans[i] = lca.length(u, v);\n    }\n  }\n\n  void flush()\n  {\n    dfs();\n    for (auto i = 0; i < Q; ++i)\n    {\n      cout << ans[i] << endl;\n    }\n  }\n\nprivate:\n  void dfs(int u = 0, int p = -1)\n  {\n#if DEBUG == 1\n    cerr << \"u = \" << u << \", p = \" << p << endl;\n#endif\n    for (auto const &q : W[u])\n    {\n      ans[q.id] += q.coefficient * (-sum[q.color] + cnt[q.color] * q.y);\n#if DEBUG == 1\n      cerr << \"ans[\" << q.id << \"] += \" << q.coefficient << \" * (-\" << sum[q.color] << \" + \" << cnt[q.color] << \" * \" << q.y << \")\" << endl;\n#endif\n    }\n    for (auto const &e : V[u])\n    {\n      if (e.dst == p)\n      {\n        continue;\n      }\n      sum[e.color] += e.cost;\n      cnt[e.color]++;\n      dfs(e.dst, u);\n      sum[e.color] -= e.cost;\n      cnt[e.color]--;\n    }\n  }\n};\n\nint main()\n{\n  int N, Q;\n  cin >> N >> Q;\n  Solve solve(N, Q);\n  solve.flush();\n}\n", "meta": {"hexsha": "a76fd43bce619951cfbd5c059aa5f864d42b4e39", "size": 9217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/0707_ABC133/F.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2019/0707_ABC133/F.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "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/0707_ABC133/F.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 19.9502164502, "max_line_length": 140, "alphanum_fraction": 0.5205598351, "num_tokens": 3130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5468594285090954}}
{"text": "// -------------------------------------------------------------------------------------------------\n//                              Copyright 2016 - NumScale SAS\n//\n//                   Distributed under the Boost Software License, Version 1.0.\n//                        See accompanying file LICENSE.txt or copy at\n//                            http://www.boost.org/LICENSE_1_0.txt\n// -------------------------------------------------------------------------------------------------\n\n#include <simd_bench.hpp>\n#include <boost/simd/function/simd/ilog2.hpp>\n#include <boost/simd/pack.hpp>\n\nnamespace nsb = ns::bench;\nnamespace bs =  boost::simd;\n\nDEFINE_SIMD_BENCH(simd_ilog2, bs::ilog2);\n\nDEFINE_BENCH_MAIN()\n{\n  nsb::for_each<simd_ilog2, NS_BENCH_IEEE_TYPES>(-10, 10);\n}\n", "meta": {"hexsha": "cb2b5d94b5d79b68ef5f502997c613d6535d1086", "size": 773, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/function/simd/ilog2.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": "bench/function/simd/ilog2.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": "bench/function/simd/ilog2.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": 35.1363636364, "max_line_length": 100, "alphanum_fraction": 0.4540750323, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5466923935988984}}
{"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_transition_test.hpp\n * \\date October 2014\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#include <gtest/gtest.h>\n#include \"../../typecast.hpp\"\n\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <iostream>\n\n#include <fl/util/types.hpp>\n#include <fl/model/transition/linear_transition.hpp>\n\ntemplate <typename TestType>\nclass LinearTransitionTest:\n    public testing::Test\n{\npublic:\n    enum: signed int\n    {\n        StateDim = TestType::Parameter::StateDim,\n        InputDim = TestType::Parameter::InputDim,\n\n        StateSize = fl::TestSize<StateDim, TestType>::Value,\n        InputSize = fl::TestSize<InputDim, TestType>::Value\n    };\n\n    typedef Eigen::Matrix<fl::Real, StateDim, 1> State;\n    typedef Eigen::Matrix<fl::Real, InputDim, 1> Input;\n    typedef fl::LinearTransition<State, State, Input> LinearModel;\n\n    typedef typename LinearModel::Noise Noise;\n\n    LinearTransitionTest()\n        : model()\n    { }\n\n    void init_dimension_test()\n    {\n        EXPECT_EQ(model.state_dimension(), StateDim);\n        EXPECT_EQ(model.noise_dimension(), StateDim);\n        EXPECT_EQ(model.input_dimension(), InputDim);\n\n        EXPECT_EQ(model.dynamics_matrix().rows(), StateDim);\n        EXPECT_EQ(model.dynamics_matrix().cols(), StateDim);\n\n        EXPECT_EQ(model.noise_matrix().rows(), StateDim);\n        EXPECT_EQ(model.noise_matrix().cols(), StateDim);\n    }\n\n    void init_dynamics_matrix_value_test()\n    {\n        EXPECT_TRUE(model.dynamics_matrix().isIdentity());\n    }\n\n    void init_noise_matrix_value_test()\n    {\n        EXPECT_TRUE(model.noise_matrix().isIdentity());\n    }\n\n    void dynamics_matrix_value_test()\n    {\n        auto dynamics_matrix = model.dynamics_matrix();\n        dynamics_matrix.setRandom();\n        model.dynamics_matrix(dynamics_matrix);\n        EXPECT_TRUE(fl::are_similar(model.dynamics_matrix(), dynamics_matrix));\n    }\n\n    void noise_matrix_value_test()\n    {\n        auto noise_matrix = model.noise_matrix();\n        noise_matrix.setRandom();\n        model.noise_matrix(noise_matrix);\n        EXPECT_TRUE(fl::are_similar(model.noise_matrix(), noise_matrix));\n    }\n\n    void expected_state_test()\n    {\n        auto x = State(model.state_dimension());\n        auto u = Input(model.input_dimension());\n\n        x.setRandom();\n        u.setRandom();\n\n        EXPECT_TRUE(\n            fl::are_similar(\n                model.expected_state(x, u),\n                x + model.input_matrix() * u));\n    }\n\n    void state_with_zero_noise_test()\n    {\n        auto x = State(model.state_dimension());\n        auto u = Input(model.input_dimension());\n        auto w = Noise(model.noise_dimension());\n\n        x.setRandom();\n        u.setRandom();\n        w.setZero();\n\n        EXPECT_TRUE(\n            fl::are_similar(\n                model.state(x, w, u),\n                x + model.input_matrix() * u));\n    }\n\n    void state_test()\n    {\n        auto x = State(model.state_dimension());\n        auto u = Input(model.input_dimension());\n        auto w = Noise(model.noise_dimension());\n\n        x.setRandom();\n        u.setRandom();\n        w.setRandom();\n\n        EXPECT_TRUE(\n            fl::are_similar(\n                model.state(x, w, u),\n                x + model.input_matrix() * u + w));\n    }\n\nprotected:\n    LinearModel model;\n};\n\ntemplate <int StateDimension, int InputDimension>\nstruct Dimensions\n{\n    enum: signed int\n    {\n        StateDim = StateDimension,\n        InputDim = InputDimension\n    };\n};\n\ntypedef ::testing::Types<\n            fl::StaticTest<Dimensions<2, 1>>,\n            fl::StaticTest<Dimensions<2, 2>>,\n            fl::StaticTest<Dimensions<3, 3>>,\n            fl::StaticTest<Dimensions<10, 10>>,\n            fl::StaticTest<Dimensions<10, 20>>,\n            fl::StaticTest<Dimensions<100, 10>>,\n            fl::StaticTest<Dimensions<3, 100>>,\n            fl::StaticTest<Dimensions<100, 100>>,\n            fl::DynamicTest<Dimensions<2, 1>>,\n            fl::DynamicTest<Dimensions<2, 2>>,\n            fl::DynamicTest<Dimensions<3, 3>>,\n            fl::DynamicTest<Dimensions<10, 10>>,\n            fl::DynamicTest<Dimensions<10, 20>>,\n            fl::DynamicTest<Dimensions<100, 10>>,\n            fl::DynamicTest<Dimensions<3, 100>>,\n            fl::DynamicTest<Dimensions<100, 100>>\n        > TestTypes;\n\nTYPED_TEST_CASE(LinearTransitionTest, TestTypes);\n\nTYPED_TEST(LinearTransitionTest, init_dimension)\n{\n    TestFixture::init_dimension_test();\n}\n\nTYPED_TEST(LinearTransitionTest, init_dynamics_matrix_value)\n{\n    TestFixture::init_dynamics_matrix_value_test();\n}\nTYPED_TEST(LinearTransitionTest, init_noise_matrix_value)\n{\n    TestFixture::init_noise_matrix_value_test();\n}\n\nTYPED_TEST(LinearTransitionTest, dynamics_matrix)\n{\n    TestFixture::dynamics_matrix_value_test();\n}\n\nTYPED_TEST(LinearTransitionTest, noise_matrix)\n{\n    TestFixture::noise_matrix_value_test();\n}\n\nTYPED_TEST(LinearTransitionTest, expected_state)\n{\n    TestFixture::expected_state_test();\n}\n\nTYPED_TEST(LinearTransitionTest, state_with_zero_noise)\n{\n    TestFixture::state_with_zero_noise_test();\n}\n\nTYPED_TEST(LinearTransitionTest, state)\n{\n    TestFixture::state_test();\n}\n\n\n/// \\todo missing probability and log_probability tests\n", "meta": {"hexsha": "b3ba93ec3df7774bef10e9e2c66894f90cf9cc83", "size": 5619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/model/transition/linear_transition_test.cpp", "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": "test/model/transition/linear_transition_test.cpp", "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": "test/model/transition/linear_transition_test.cpp", "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": 26.0138888889, "max_line_length": 79, "alphanum_fraction": 0.6399715252, "num_tokens": 1289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5466923885368472}}
{"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 <complex>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/morton_dense.hpp> \n#include <boost/numeric/mtl/matrix/compressed2D.hpp> \n#include <boost/numeric/mtl/matrix/laplacian_setup.hpp> \n#include <boost/numeric/mtl/recursion/predefined_masks.hpp>\n#include <boost/numeric/mtl/operation/print.hpp>\n\n\nusing namespace std;  \n\ntemplate <typename Matrix>\nvoid test(Matrix& matrix, unsigned dim1, unsigned dim2, const char* name)\n{\n    cout << \"\\n\" << name << \"\\n\";\n    mtl::mat::laplacian_setup(matrix, dim1, dim2);\n    cout << \"Laplacian matrix:\\n\" << matrix << \"\\n\";\n    \n    if (dim1 > 1 && dim2 > 1) {\n\ttypename mtl::Collection<Matrix>::value_type four(4.0), minus_one(-1.0), zero(0.0);\n\tMTL_THROW_IF(matrix[0][0] != four, mtl::runtime_error(\"wrong diagonal\"));\n\tMTL_THROW_IF(matrix[0][1] != minus_one, mtl::runtime_error(\"wrong east neighbor\"));\n\tMTL_THROW_IF(matrix[0][dim2] != minus_one, mtl::runtime_error(\"wrong south neighbor\"));\n\tMTL_THROW_IF(dim2 > 2 && matrix[0][2] != zero, mtl::runtime_error(\"wrong zero-element\"));\n\tMTL_THROW_IF(matrix[1][0] != minus_one, mtl::runtime_error(\"wrong west neighbor\"));\n\tMTL_THROW_IF(matrix[dim2][0] != minus_one, mtl::runtime_error(\"wrong north neighbor\"));\n\tMTL_THROW_IF(dim2 > 2 && matrix[2][0] != zero, mtl::runtime_error(\"wrong zero-element\"));\n    }\n}\n\n\n\nint main(int argc, char* argv[])\n{\n    using namespace mtl;\n\n    unsigned dim1= 3, dim2= 4;\n\n    if (argc > 2) {dim1= atoi(argv[1]);dim2= atoi(argv[2]);}\n    unsigned size= dim1 * dim2; \n\n    dense2D<double>                                      dr(size, size);\n    dense2D<double, mat::parameters<col_major> >      dc(size, size);\n    morton_dense<double, recursion::morton_z_mask>       mzd(size, size);\n    morton_dense<double, recursion::doppled_2_row_mask>  d2r(size, size);\n    compressed2D<double>                                 cr(size, size);\n    compressed2D<double, mat::parameters<col_major> > cc(size, size);\n\n    dense2D<complex<double> >                            drc(size, size);\n    compressed2D<complex<double> >                       crc(size, size);\n\n    test(dr, dim1, dim2, \"Dense row major\");\n    test(dc, dim1, dim2, \"Dense column major\");\n    test(mzd, dim1, dim2, \"Morton Z-order\");\n    test(d2r, dim1, dim2, \"Hybrid 2 row-major\");\n    test(cr, dim1, dim2, \"Compressed row major\");\n    test(cc, dim1, dim2, \"Compressed column major\");\n    test(drc, dim1, dim2, \"Dense row major complex\");\n    test(crc, dim1, dim2, \"Compressed row major complex\");\n\n    return 0;\n}\n", "meta": {"hexsha": "80a2987ffa0bb60d006dfbdcb3d1b97a6fc58220", "size": 3071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/laplacian_setup_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/laplacian_setup_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/laplacian_setup_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": 39.3717948718, "max_line_length": 94, "alphanum_fraction": 0.6571149463, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.546692386857172}}
{"text": "// Copyright (C) 2012  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <dlib/svm.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.active_learning\");\n\n// ----------------------------------------------------------------------------------------\n\n    typedef matrix<double, 0, 1> sample_type;\n    typedef radial_basis_kernel<sample_type> kernel_type;\n\n// ----------------------------------------------------------------------------------------\n\n    void make_dataset (\n        std::vector<sample_type>& samples,\n        std::vector<double>& labels\n    )\n    {\n        for (int r = -10; r <= 10; ++r)\n        {\n            for (int c = -10; c <= 10; ++c)\n            {\n                sample_type samp(2);\n                samp(0) = r;\n                samp(1) = c;\n                samples.push_back(samp);\n\n                // if this point is less than 10 from the origin\n                if (sqrt((double)r*r + c*c) <= 8)\n                    labels.push_back(+1);\n                else\n                    labels.push_back(-1);\n\n            }\n        }\n\n\n        vector_normalizer<sample_type> normalizer;\n        normalizer.train(samples);\n        for (unsigned long i = 0; i < samples.size(); ++i)\n            samples[i] = normalizer(samples[i]); \n\n        randomize_samples(samples, labels);\n\n        /*\n        cout << \"samples.size(): \" << samples.size() << endl;\n        cout << \"num +1 samples: \"<< sum(mat(labels) > 0) << endl;\n        cout << \"num -1 samples: \"<< sum(mat(labels) < 0) << endl;\n        */\n\n        empirical_kernel_map<kernel_type> ekm;\n        ekm.load(kernel_type(0.15), samples);\n        for (unsigned long i = 0; i < samples.size(); ++i)\n            samples[i] = ekm.project(samples[i]);\n\n        //cout << \"dims: \"<< ekm.out_vector_size() << endl;\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    double test_rank_unlabeled_training_samples (\n        const std::vector<sample_type>& samples,\n        const std::vector<double>& labels,\n        active_learning_mode mode,\n        int iterations,\n        bool pick_front\n    )\n    {\n        matrix<double,2,1> s;\n        s = sum(mat(labels) > 0), sum(mat(labels) < 0);\n        s /= labels.size();\n\n\n        svm_c_linear_dcd_trainer<linear_kernel<sample_type> > trainer;\n        trainer.set_c(25);\n\n        const unsigned long initial_size = 1;\n        std::vector<sample_type> tsamples(samples.begin(), samples.begin()+initial_size); \n        std::vector<double> tlabels(labels.begin(), labels.begin()+initial_size); \n\n        decision_function<linear_kernel<sample_type> > df;\n\n        double random_score = 0;\n        double active_learning_score = 0;\n        for (int i = 0; i < iterations; ++i)\n        {\n            print_spinner();\n            random_subset_selector<sample_type> sss = randomly_subsample(samples,50,i);\n            random_subset_selector<double> ssl = randomly_subsample(labels,50,i);\n            std::vector<unsigned long> results;\n\n            results = rank_unlabeled_training_samples(trainer, tsamples, tlabels, sss, mode);\n\n            const unsigned long idx = pick_front ? results.front() : results.back();\n            tsamples.push_back(sss[idx]);\n            tlabels.push_back(ssl[idx]);\n\n            df = trainer.train(tsamples, tlabels);\n            //cout << \"tsamples.size(): \" << tsamples.size() << endl;\n            const unsigned long num = tsamples.size();\n            const double active = test_binary_decision_function(df, samples, labels)*s;\n            //cout << \"test: \"<< active;\n            df = trainer.train(randomly_subsample(samples,num,i), randomly_subsample(labels,num,i));\n            const double random = test_binary_decision_function(df, samples, labels)*s;\n            //cout << \"test: \"<< random << endl;\n\n            active_learning_score += active;\n            random_score += random;\n\n            //cout << \"\\n\\n***********\\n\\n\" << flush;\n        }\n\n        dlog << LINFO << \"pick_front: \" << pick_front << \"   mode: \"<< mode;\n        dlog << LINFO << \"active_learning_score: \"<< active_learning_score;\n        dlog << LINFO << \"random_score:          \"<< random_score;\n        return active_learning_score / random_score;\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    class test_active_learning : public tester\n    {\n    public:\n        test_active_learning (\n        ) :\n            tester (\"test_active_learning\",\n                \"Runs tests on the active learning components.\")\n        {}\n\n        void perform_test (\n        )\n        {\n            std::vector<sample_type> samples;\n            std::vector<double> labels;\n            print_spinner();\n            make_dataset(samples, labels);\n            dlog << LINFO << \"samples.size(): \"<< samples.size();\n\n            // When we pick the best/front ranked element then the active learning method\n            // shouldn't do much worse than random selection (and often much better).\n            DLIB_TEST(test_rank_unlabeled_training_samples(samples, labels, max_min_margin, 25, true) >= 0.97);\n            DLIB_TEST(test_rank_unlabeled_training_samples(samples, labels, ratio_margin, 25, true) >= 0.96);\n            // However, picking the worst ranked element should do way worse than random\n            // selection.\n            DLIB_TEST(test_rank_unlabeled_training_samples(samples, labels, max_min_margin, 25, false) < 0.8);\n            DLIB_TEST(test_rank_unlabeled_training_samples(samples, labels, ratio_margin, 25, false) < 0.8);\n        }\n    } a;\n\n}\n\n\n\n", "meta": {"hexsha": "a60f6de4fcfba28ee4301e49306278246d91d5ea", "size": 5731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/active_learning.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/active_learning.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/active_learning.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": 34.5240963855, "max_line_length": 111, "alphanum_fraction": 0.5367300646, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5466923817951209}}
{"text": "#include <Rcpp.h>\n// [[Rcpp::plugins(cpp11)]]\n\n// [[Rcpp::depends(BH)]]\n#include <boost/numeric/odeint.hpp>\n#include <boost/array.hpp>\n\nusing namespace boost::numeric::odeint;\n\nunsigned int n;\nRcpp::NumericMatrix g_a;\nRcpp::NumericVector g_r;\nstd::vector<double> out_t;\nstd::vector< std::vector<double> > out_x;\n\n// the model\nvoid LV (const std::vector<double> &x,\n         std::vector<double> &dxdt,\n         double t) {\n  for (int row = 0; row < g_a.nrow(); ++row) {\n    double c = 0;\n    for (int col = 0; col < g_a.ncol(); ++col) {\n      // Rcpp::numericMatrix is indexed like this\n      // matrixName(row, column)\n      c =  c + g_a(row, col) * x[col];\n    }\n    dxdt[row] = x[row] * (g_r[row] - c);\n  }\n}\n\n// the observer\nvoid write_LV (const std::vector<double> &x , const double t) {\n  // debugging output\n  // for (unsigned int i = 0; i < x.size(); ++i) {\n  //   std::cout << x[i] << \" \";\n  // }\n  // std::cout << std::endl;\n  \n  out_t.push_back(t);\n  \n  for (unsigned int i = 0; i < x.size(); ++i) {\n    out_x[i].push_back(x[i]);\n  }\n}\n\n// creates the output object\nRcpp::List createOutput() {\n  \n  Rcpp::List out;\n  out(\"Time\") = Rcpp::wrap(out_t);\n  for (unsigned int i = 0; i != n; ++i)\n  {\n    auto cnam = std::string(\"X\") + std::to_string(i + 1);\n    out(cnam) = Rcpp::wrap(out_x[i]);\n  }\n  out.attr(\"class\") = \"data.frame\";\n  int rows_out = out_t.size();\n  auto rn = Rcpp::IntegerVector::create(NA_INTEGER, -rows_out);\n  out.attr(\"row.names\") = rn;\n  return out;\n}\n  \n// function that will be called from R\n// [[Rcpp::export]]\nRcpp::List integrateModel(Rcpp::NumericVector init,\n                                   Rcpp::NumericVector r,\n                                   Rcpp::NumericMatrix a,\n                                   double t0,\n                                   double t1,\n                                   double dt) {\n  n = r.size();\n  \n  // initialize out_x\n  out_x = std::vector< std::vector<double> >(n);\n  for (unsigned int i = 0; i < n; ++i) {\n    out_x[i] = std::vector<double>();\n  }\n  \n  // initialize/reset out_t\n  out_t = std::vector<double>();\n  \n  // assign global variables, needed for function LV\n  g_a = a;\n  g_r = r;\n  \n  // init must be casted to std::vector for integrate function\n  std::vector<double> v_init = Rcpp::as< std::vector<double> >(init);\n  \n  \n  // for debugging: is the order of row/col iteration right?\n  // for (int i = 0; i < n; ++i) {\n  //   std::cout << r[i] << \" \";\n  // }\n  // std::cout << std::endl;\n  // \n  // for (int row = 0; row < a.nrow(); ++row) {\n  //   for (int col = 0; col < a.ncol(); ++col) {\n  //     std::cout << a(row, col) << \" \";\n  //   } \n  // }\n  // std::cout << std::endl;\n  \n  \n  // this is the integration step\n  // the function LV does the work\n  // the observer function write_LV catches the state of the\n  // stepper and pushes it to the global output variables\n  integrate(LV, v_init, t0, t1, dt, write_LV);\n  \n  return createOutput();\n}\n", "meta": {"hexsha": "c39d880d65c4b3e729bbeecdc193cf2ba7f63919", "size": 2936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/LV_model_wrapped.cpp", "max_stars_repo_name": "LoicChr/TransferTraitDemo", "max_stars_repo_head_hexsha": "d25be80ae3d9e39e5bf388666b7a430c1d630951", "max_stars_repo_licenses": ["MIT"], "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/LV_model_wrapped.cpp", "max_issues_repo_name": "LoicChr/TransferTraitDemo", "max_issues_repo_head_hexsha": "d25be80ae3d9e39e5bf388666b7a430c1d630951", "max_issues_repo_licenses": ["MIT"], "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/LV_model_wrapped.cpp", "max_forks_repo_name": "LoicChr/TransferTraitDemo", "max_forks_repo_head_hexsha": "d25be80ae3d9e39e5bf388666b7a430c1d630951", "max_forks_repo_licenses": ["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.2142857143, "max_line_length": 69, "alphanum_fraction": 0.5463215259, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5466923767330696}}
{"text": "\n#include <NTL/mat_lzz_pE.h>\n#include <NTL/BasicThreadPool.h>\n\nNTL_START_IMPL\n\n\n\n\n// ==========================================\n\n\n\n\n#define PAR_THRESH (40000.0)\n\nstatic double\nzz_pE_SizeInWords()\n{\n   return deg(zz_pE::modulus());\n}\n\n\nstatic\nvoid mul_aux(Mat<zz_pE>& X, const Mat<zz_pE>& A, const Mat<zz_pE>& B)  \n{  \n   long n = A.NumRows();  \n   long l = A.NumCols();  \n   long m = B.NumCols();  \n  \n   if (l != B.NumRows())  \n      LogicError(\"matrix mul: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n\n\n   zz_pContext zz_p_context;\n   zz_p_context.save();\n   zz_pEContext zz_pE_context;\n   zz_pE_context.save();\n   double sz = zz_pE_SizeInWords();\n\n   bool seq = (double(n)*double(l)*double(m)*sz*sz < PAR_THRESH);\n\n   NTL_GEXEC_RANGE(seq, m, first, last)\n   NTL_IMPORT(n)\n   NTL_IMPORT(l)\n   NTL_IMPORT(m)\n\n   zz_p_context.restore();\n   zz_pE_context.restore();\n\n   long i, j, k;  \n   zz_pX acc, tmp;  \n\n   Vec<zz_pE> B_col;\n   B_col.SetLength(l);\n\n   for (j = first; j < last; j++) {\n      for (k = 0; k < l; k++) B_col[k] = B[k][j];\n\n      for (i = 0; i < n; i++) {\n         clear(acc);\n         for (k = 0; k < l; k++) {\n            mul(tmp, rep(A[i][k]), rep(B_col[k]));\n            add(acc, acc, tmp);\n         }\n         conv(X[i][j], acc);\n      }\n   }\n\n   NTL_GEXEC_RANGE_END\n}  \n\n\nvoid mul(mat_zz_pE& X, const mat_zz_pE& A, const mat_zz_pE& B)  \n{  \n   if (&X == &A || &X == &B) {  \n      mat_zz_pE tmp;  \n      mul_aux(tmp, A, B);  \n      X = tmp;  \n   }  \n   else  \n      mul_aux(X, A, B);  \n}  \n  \n\nvoid inv(zz_pE& d, Mat<zz_pE>& X, const Mat<zz_pE>& A)\n{\n   long n = A.NumRows();\n\n   if (A.NumCols() != n)\n      LogicError(\"inv: nonsquare matrix\");\n\n   if (n == 0) {\n      set(d);\n      X.SetDims(0, 0);\n      return;\n   }\n\n   const zz_pXModulus& G = zz_pE::modulus();\n\n   zz_pX t1, t2;\n   zz_pX pivot;\n   zz_pX pivot_inv;\n\n   Vec< Vec<zz_pX> > M;\n   // scratch space\n\n   M.SetLength(n);\n   for (long i = 0; i < n; i++) {\n      M[i].SetLength(n);\n      for (long j = 0; j < n; j++) {\n         M[i][j].SetMaxLength(2*deg(G)-1);\n         M[i][j] = rep(A[i][j]);\n      }\n   }\n\n   zz_pX det;\n   det = 1;\n\n\n   Vec<long> P;\n   P.SetLength(n);\n   for (long k = 0; k < n; k++) P[k] = k;\n   // records swap operations\n   \n\n   zz_pContext zz_p_context;\n   zz_p_context.save();\n   double sz = zz_pE_SizeInWords();\n\n   bool seq = double(n)*double(n)*sz*sz < PAR_THRESH;\n\n   bool pivoting = false;\n\n   for (long k = 0; k < n; k++) {\n\n      long pos = -1;\n\n      for (long i = k; i < n; i++) {\n         rem(pivot, M[i][k], G);\n         if (pivot != 0) {\n            InvMod(pivot_inv, pivot, G);\n            pos = i;\n            break;\n         }\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n            negate(det, det); \n            P[k] = pos;\n            pivoting = true;\n         }\n\n         MulMod(det, det, pivot, G);\n\n         {\n            // multiply row k by pivot_inv\n            zz_pX *y = &M[k][0];\n            for (long j = 0; j < n; j++) {\n               rem(t2, y[j], G);\n               MulMod(y[j], t2, pivot_inv, G);\n            }\n            y[k] = pivot_inv;\n         }\n\n\n         NTL_GEXEC_RANGE(seq, n, first, last)  \n         NTL_IMPORT(n)\n         NTL_IMPORT(k)\n\n         zz_p_context.restore();\n\n         zz_pX *y = &M[k][0]; \n         zz_pX t1, t2;\n\n         for (long i = first; i < last; i++) {\n            if (i == k) continue; // skip row k\n\n            zz_pX *x = &M[i][0]; \n            rem(t1, x[k], G);\n            negate(t1, t1); \n            x[k] = 0;\n            if (t1 == 0) continue;\n\n            // add t1 * row k to row i\n            for (long j = 0; j < n; j++) {\n               mul(t2, y[j], t1);\n               add(x[j], x[j], t2);\n            }\n         }\n         NTL_GEXEC_RANGE_END\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   if (pivoting) {\n      // pivot colums, using reverse swap sequence\n\n      for (long i = 0; i < n; i++) {\n         zz_pX *x = &M[i][0]; \n\n         for (long k = n-1; k >= 0; k--) {\n            long pos = P[k];\n            if (pos != k) swap(x[pos], x[k]);\n         }\n      }\n   }\n\n   X.SetDims(n, n);\n   for (long i = 0; i < n; i++)\n      for (long j = 0; j < n; j++)\n         conv(X[i][j], M[i][j]);\n\n   conv(d, det);\n}\n\nstatic\nvoid solve_impl(zz_pE& d, Vec<zz_pE>& X, \n                const Mat<zz_pE>& A, const Vec<zz_pE>& b, bool trans)\n\n{\n   long n = A.NumRows();\n   if (A.NumCols() != n)\n      LogicError(\"solve: nonsquare matrix\");\n\n   if (b.length() != n)\n      LogicError(\"solve: dimension mismatch\");\n\n   if (n == 0) {\n      set(d);\n      X.SetLength(0);\n      return;\n   }\n\n   zz_pX t1, t2;\n\n   const zz_pXModulus& G = zz_pE::modulus();\n\n   Vec< Vec<zz_pX> > M;\n\n   M.SetLength(n);\n\n   for (long i = 0; i < n; i++) {\n      M[i].SetLength(n+1);\n      for (long j = 0; j < n; j++) M[i][j].SetMaxLength(2*deg(G)-1);\n\n      if (trans) \n         for (long j = 0; j < n; j++) M[i][j] = rep(A[j][i]);\n      else\n         for (long j = 0; j < n; j++) M[i][j] = rep(A[i][j]);\n\n      M[i][n] = rep(b[i]);\n   }\n\n   zz_pX det;\n   set(det);\n\n   zz_pContext zz_p_context;\n   zz_p_context.save();\n   double sz = zz_pE_SizeInWords();\n\n   for (long k = 0; k < n; k++) {\n      long pos = -1;\n      for (long i = k; i < n; i++) {\n         rem(t1, M[i][k], G);\n         M[i][k] = t1;\n         if (pos == -1 && !IsZero(t1)) {\n            pos = i;\n         }\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n            negate(det, det); \n         }\n\n         MulMod(det, det, M[k][k], G);\n\n         // make M[k, k] == -1 mod G, and make row k reduced\n\n         InvMod(t1, M[k][k], G);\n         negate(t1, t1); \n         for (long j = k+1; j <= n; j++) {\n            rem(t2, M[k][j], G);\n            MulMod(M[k][j], t2, t1, G);\n         }\n\n         bool seq =\n            double(n-(k+1))*(n-(k+1))*sz*sz < PAR_THRESH;\n\n         NTL_GEXEC_RANGE(seq, n-(k+1), first, last)\n         NTL_IMPORT(n)\n         NTL_IMPORT(k)\n\n         zz_p_context.restore();\n\n         zz_pX t1, t2;\n\n         for (long ii = first; ii < last; ii++) {\n            long i = ii + k+1;\n\n            // M[i] = M[i] + M[k]*M[i,k]\n\n            t1 = M[i][k];   // this is already reduced\n\n            zz_pX *x = M[i].elts() + (k+1);\n            zz_pX *y = M[k].elts() + (k+1);\n\n            for (long j = k+1; j <= n; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               mul(t2, *y, t1);\n               add(*x, *x, t2);\n            }\n         }\n\n         NTL_GEXEC_RANGE_END\n\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   X.SetLength(n);\n   for (long i = n-1; i >= 0; i--) {\n      clear(t1);\n      for (long j = i+1; j < n; j++) {\n         mul(t2, rep(X[j]), M[i][j]);\n         add(t1, t1, t2);\n      }\n      sub(t1, t1, M[i][n]);\n      conv(X[i], t1);\n   }\n\n   conv(d, det);\n}\n\n\nvoid solve(zz_pE& d, Vec<zz_pE>& x, \n               const Mat<zz_pE>& A, const Vec<zz_pE>& b)\n{\n   solve_impl(d, x, A, b, true);\n}\n\nvoid solve(zz_pE& d, const Mat<zz_pE>& A, \n               Vec<zz_pE>& x, const Vec<zz_pE>& b)\n{\n   solve_impl(d, x, A, b, false);\n}\n\n\n\nlong gauss(Mat<zz_pE>& M_in, long w)\n{\n   zz_pX t1, t2;\n   zz_pX piv;\n\n   long n = M_in.NumRows();\n   long m = M_in.NumCols();\n\n   if (w < 0 || w > m)\n      LogicError(\"gauss: bad args\");\n\n   const zz_pXModulus& G = zz_pE::modulus();\n\n   Vec< Vec<zz_pX> > M;\n\n   M.SetLength(n);\n   for (long i = 0; i < n; i++) {\n      M[i].SetLength(m);\n      for (long j = 0; j < m; j++) {\n         M[i][j].SetLength(2*deg(G)-1);\n         M[i][j] = rep(M_in[i][j]);\n      }\n   }\n\n   zz_pContext zz_p_context;\n   zz_p_context.save();\n   double sz = zz_pE_SizeInWords();\n\n   long l = 0;\n   for (long k = 0; k < w && l < n; k++) {\n\n      long pos = -1;\n      for (long i = l; i < n; i++) {\n         rem(t1, M[i][k], G);\n         M[i][k] = t1;\n         if (pos == -1 && !IsZero(t1)) {\n            pos = i;\n         }\n      }\n\n      if (pos != -1) {\n         swap(M[pos], M[l]);\n\n         InvMod(piv, M[l][k], G);\n         negate(piv, piv);\n\n         for (long j = k+1; j < m; j++) {\n            rem(M[l][j], M[l][j], G);\n         }\n\n         bool seq =\n            double(n-(l+1))*double(m-(k+1))*sz*sz < PAR_THRESH;\n\n         NTL_GEXEC_RANGE(seq, n-(l+1), first, last)\n         NTL_IMPORT(m)\n         NTL_IMPORT(k)\n         NTL_IMPORT(l)\n\n         zz_p_context.restore();\n\n         zz_pX t1, t2;\n\n\n         for (long ii = first; ii < last; ii++) {\n            long i = ii + l+1;\n\n            // M[i] = M[i] + M[l]*M[i,k]*piv\n\n            MulMod(t1, M[i][k], piv, G);\n\n            clear(M[i][k]);\n\n            zz_pX *x = M[i].elts() + (k+1);\n            zz_pX *y = M[l].elts() + (k+1);\n\n            for (long j = k+1; j < m; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               mul(t2, *y, t1);\n               add(t2, t2, *x);\n               *x = t2;\n            }\n         }\n\n         NTL_GEXEC_RANGE_END\n\n         l++;\n      }\n   }\n   \n   for (long i = 0; i < n; i++)\n      for (long j = 0; j < m; j++)\n         conv(M_in[i][j], M[i][j]);\n\n   return l;\n}\n\n\nlong gauss(Mat<zz_pE>& M)\n{\n   return gauss(M, M.NumCols());\n}\n\nvoid image(Mat<zz_pE>& X, const Mat<zz_pE>& A)\n{\n   Mat<zz_pE> M;\n   M = A;\n   long r = gauss(M);\n   M.SetDims(r, M.NumCols());\n   X = M;\n}\n\n\n\nvoid kernel(Mat<zz_pE>& X, const Mat<zz_pE>& A)\n{\n   long m = A.NumRows();\n   long n = A.NumCols();\n\n   const zz_pXModulus& G = zz_pE::modulus();\n\n   Mat<zz_pE> M;\n\n   transpose(M, A);\n   long r = gauss(M);\n\n   if (r == 0) {\n      ident(X, m);\n      return;\n   }\n\n   X.SetDims(m-r, m);\n\n   if (m-r == 0 || m == 0) return;\n\n\n   Vec<long> D;\n   D.SetLength(m);\n   for (long j = 0; j < m; j++) D[j] = -1;\n\n   Vec<zz_pE> inverses;\n   inverses.SetLength(m);\n\n   for (long i = 0, j = -1; i < r; i++) {\n      do {\n         j++;\n      } while (IsZero(M[i][j]));\n\n      D[j] = i;\n      inv(inverses[j], M[i][j]); \n   }\n\n   zz_pEContext zz_pE_context;\n   zz_pE_context.save();\n   zz_pContext zz_p_context;\n   zz_p_context.save();\n   double sz = zz_pE_SizeInWords();\n\n   bool seq = \n      double(m-r)*double(r)*double(r)*sz*sz < PAR_THRESH;\n\n   NTL_GEXEC_RANGE(seq, m-r, first, last)\n   NTL_IMPORT(m)\n   NTL_IMPORT(r)\n\n   zz_p_context.restore();\n   zz_pE_context.restore();\n\n   zz_pX t1, t2;\n   zz_pE T3;\n\n   for (long k = first; k < last; k++) {\n      Vec<zz_pE>& v = X[k];\n      long pos = 0;\n      for (long j = m-1; j >= 0; j--) {\n         if (D[j] == -1) {\n            if (pos == k)\n               set(v[j]);\n            else\n               clear(v[j]);\n            pos++;\n         }\n         else {\n            long i = D[j];\n\n            clear(t1);\n\n            for (long s = j+1; s < m; s++) {\n               mul(t2, rep(v[s]), rep(M[i][s]));\n               add(t1, t1, t2);\n            }\n\n            conv(T3, t1);\n            mul(T3, T3, inverses[j]);\n            negate(v[j], T3); \n         }\n      }\n   }\n\n   NTL_GEXEC_RANGE_END\n}\n\n\n\n\n\nvoid determinant(zz_pE& d, const Mat<zz_pE>& M_in)\n{\n   zz_pX t1, t2;\n\n   const zz_pXModulus& G = zz_pE::modulus();\n\n   long n = M_in.NumRows();\n\n   if (M_in.NumCols() != n)\n      LogicError(\"determinant: nonsquare matrix\");\n\n   if (n == 0) {\n      set(d);\n      return;\n   }\n\n   Vec< Vec<zz_pX> > M;\n\n   M.SetLength(n);\n   for (long i = 0; i < n; i++) {\n      M[i].SetLength(n);\n      for (long j = 0; j < n; j++) { \n         M[i][j].SetMaxLength(2*deg(G)-1);\n         M[i][j] = rep(M_in[i][j]);\n      }\n   }\n\n   zz_pX det;\n   set(det);\n\n   zz_pContext zz_p_context;\n   zz_p_context.save();\n   double sz = zz_pE_SizeInWords();\n\n   for (long k = 0; k < n; k++) {\n      long pos = -1;\n      for (long i = k; i < n; i++) {\n         rem(t1, M[i][k], G);\n         M[i][k] = t1;\n         if (pos == -1 && !IsZero(t1))\n            pos = i;\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n            negate(det, det);\n         }\n\n         MulMod(det, det, M[k][k], G);\n\n         // make M[k, k] == -1 mod G, and make row k reduced\n\n         InvMod(t1, M[k][k], G);\n         negate(t1, t1);\n         for (long j = k+1; j < n; j++) {\n            rem(t2, M[k][j], G);\n            MulMod(M[k][j], t2, t1, G);\n         }\n\n\n         bool seq =\n            double(n-(k+1))*(n-(k+1))*sz*sz < PAR_THRESH;\n\n         NTL_GEXEC_RANGE(seq, n-(k+1), first, last)\n         NTL_IMPORT(n)\n         NTL_IMPORT(k)\n\n         zz_p_context.restore();\n\n         zz_pX t1, t2;\n\n         for (long ii = first; ii < last; ii++) {\n            long i = ii + k+1;\n\n            // M[i] = M[i] + M[k]*M[i,k]\n\n            t1 = M[i][k];   // this is already reduced\n\n            zz_pX *x = M[i].elts() + (k+1);\n            zz_pX *y = M[k].elts() + (k+1);\n\n            for (long j = k+1; j < n; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               mul(t2, *y, t1);\n               add(*x, *x, t2);\n            }\n         }\n\n         NTL_GEXEC_RANGE_END\n\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   conv(d, det);\n}\n\n\n// ==========================================\n\n\n\n\n  \nvoid add(mat_zz_pE& X, const mat_zz_pE& A, const mat_zz_pE& B)  \n{  \n   long n = A.NumRows();  \n   long m = A.NumCols();  \n  \n   if (B.NumRows() != n || B.NumCols() != m)   \n      LogicError(\"matrix add: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n  \n   long i, j;  \n   for (i = 1; i <= n; i++)   \n      for (j = 1; j <= m; j++)  \n         add(X(i,j), A(i,j), B(i,j));  \n}  \n  \nvoid sub(mat_zz_pE& X, const mat_zz_pE& A, const mat_zz_pE& B)  \n{  \n   long n = A.NumRows();  \n   long m = A.NumCols();  \n  \n   if (B.NumRows() != n || B.NumCols() != m)  \n      LogicError(\"matrix sub: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n  \n   long i, j;  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= m; j++)  \n         sub(X(i,j), A(i,j), B(i,j));  \n}  \n\nvoid negate(mat_zz_pE& X, const mat_zz_pE& A)  \n{  \n   long n = A.NumRows();  \n   long m = A.NumCols();  \n  \n  \n   X.SetDims(n, m);  \n  \n   long i, j;  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= m; j++)  \n         negate(X(i,j), A(i,j));  \n}  \n\n\n  \nstatic\nvoid mul_aux(vec_zz_pE& x, const mat_zz_pE& A, const vec_zz_pE& b)  \n{  \n   long n = A.NumRows();  \n   long l = A.NumCols();  \n  \n   if (l != b.length())  \n      LogicError(\"matrix mul: dimension mismatch\");  \n  \n   x.SetLength(n);  \n  \n   long i, k;  \n   zz_pX acc, tmp;  \n  \n   for (i = 1; i <= n; i++) {  \n      clear(acc);  \n      for (k = 1; k <= l; k++) {  \n         mul(tmp, rep(A(i,k)), rep(b(k)));  \n         add(acc, acc, tmp);  \n      }  \n      conv(x(i), acc);  \n   }  \n}  \n  \n  \nvoid mul(vec_zz_pE& x, const mat_zz_pE& A, const vec_zz_pE& b)  \n{  \n   if (&b == &x || A.alias(x)) {\n      vec_zz_pE tmp;\n      mul_aux(tmp, A, b);\n      x = tmp;\n   }\n   else\n      mul_aux(x, A, b);\n}  \n\nstatic\nvoid mul_aux(vec_zz_pE& x, const vec_zz_pE& a, const mat_zz_pE& B)  \n{  \n   long n = B.NumRows();  \n   long l = B.NumCols();  \n  \n   if (n != a.length())  \n      LogicError(\"matrix mul: dimension mismatch\");  \n  \n   x.SetLength(l);  \n  \n   long i, k;  \n   zz_pX acc, tmp;  \n  \n   for (i = 1; i <= l; i++) {  \n      clear(acc);  \n      for (k = 1; k <= n; k++) {  \n         mul(tmp, rep(a(k)), rep(B(k,i)));\n         add(acc, acc, tmp);  \n      }  \n      conv(x(i), acc);  \n   }  \n}  \n\nvoid mul(vec_zz_pE& x, const vec_zz_pE& a, const mat_zz_pE& B)\n{\n   if (&a == &x) {\n      vec_zz_pE tmp;\n      mul_aux(tmp, a, B);\n      x = tmp;\n   }\n   else\n      mul_aux(x, a, B);\n\n}\n\n     \n  \nvoid ident(mat_zz_pE& X, long n)  \n{  \n   X.SetDims(n, n);  \n   long i, j;  \n  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= n; j++)  \n         if (i == j)  \n            set(X(i, j));  \n         else  \n            clear(X(i, j));  \n} \n\n\n\nlong IsIdent(const mat_zz_pE& A, long n)\n{\n   if (A.NumRows() != n || A.NumCols() != n)\n      return 0;\n\n   long i, j;\n\n   for (i = 1; i <= n; i++)\n      for (j = 1; j <= n; j++)\n         if (i != j) {\n            if (!IsZero(A(i, j))) return 0;\n         }\n         else {\n            if (!IsOne(A(i, j))) return 0;\n         }\n\n   return 1;\n}\n            \n\nvoid transpose(mat_zz_pE& X, const mat_zz_pE& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   long i, j;\n\n   if (&X == & A) {\n      if (n == m)\n         for (i = 1; i <= n; i++)\n            for (j = i+1; j <= n; j++)\n               swap(X(i, j), X(j, i));\n      else {\n         mat_zz_pE tmp;\n         tmp.SetDims(m, n);\n         for (i = 1; i <= n; i++)\n            for (j = 1; j <= m; j++)\n               tmp(j, i) = A(i, j);\n         X.kill();\n         X = tmp;\n      }\n   }\n   else {\n      X.SetDims(m, n);\n      for (i = 1; i <= n; i++)\n         for (j = 1; j <= m; j++)\n            X(j, i) = A(i, j);\n   }\n}\n   \n\n   \nvoid mul(mat_zz_pE& X, const mat_zz_pE& A, const zz_pE& b_in)\n{\n   zz_pE b = b_in;\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(n, m);\n\n   long i, j;\n   for (i = 0; i < n; i++)\n      for (j = 0; j < m; j++)\n         mul(X[i][j], A[i][j], b);\n}\n\nvoid mul(mat_zz_pE& X, const mat_zz_pE& A, const zz_p& b_in)\n{\n   NTL_zz_pRegister(b);\n   b = b_in;\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(n, m);\n\n   long i, j;\n   for (i = 0; i < n; i++)\n      for (j = 0; j < m; j++)\n         mul(X[i][j], A[i][j], b);\n}\n\nvoid mul(mat_zz_pE& X, const mat_zz_pE& A, long b_in)\n{\n   NTL_zz_pRegister(b);\n   b = b_in;\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(n, m);\n\n   long i, j;\n   for (i = 0; i < n; i++)\n      for (j = 0; j < m; j++)\n         mul(X[i][j], A[i][j], b);\n}\n\nvoid diag(mat_zz_pE& X, long n, const zz_pE& d_in)  \n{  \n   zz_pE d = d_in;\n   X.SetDims(n, n);  \n   long i, j;  \n  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= n; j++)  \n         if (i == j)  \n            X(i, j) = d;  \n         else  \n            clear(X(i, j));  \n} \n\nlong IsDiag(const mat_zz_pE& A, long n, const zz_pE& d)\n{\n   if (A.NumRows() != n || A.NumCols() != n)\n      return 0;\n\n   long i, j;\n\n   for (i = 1; i <= n; i++)\n      for (j = 1; j <= n; j++)\n         if (i != j) {\n            if (!IsZero(A(i, j))) return 0;\n         }\n         else {\n            if (A(i, j) != d) return 0;\n         }\n\n   return 1;\n}\n\n\nlong IsZero(const mat_zz_pE& a)\n{\n   long n = a.NumRows();\n   long i;\n\n   for (i = 0; i < n; i++)\n      if (!IsZero(a[i]))\n         return 0;\n\n   return 1;\n}\n\nvoid clear(mat_zz_pE& x)\n{\n   long n = x.NumRows();\n   long i;\n   for (i = 0; i < n; i++)\n      clear(x[i]);\n}\n\n\nmat_zz_pE operator+(const mat_zz_pE& a, const mat_zz_pE& b)\n{\n   mat_zz_pE res;\n   add(res, a, b);\n   NTL_OPT_RETURN(mat_zz_pE, res);\n}\n\nmat_zz_pE operator*(const mat_zz_pE& a, const mat_zz_pE& b)\n{\n   mat_zz_pE res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(mat_zz_pE, res);\n}\n\nmat_zz_pE operator-(const mat_zz_pE& a, const mat_zz_pE& b)\n{\n   mat_zz_pE res;\n   sub(res, a, b);\n   NTL_OPT_RETURN(mat_zz_pE, res);\n}\n\n\nmat_zz_pE operator-(const mat_zz_pE& a)\n{\n   mat_zz_pE res;\n   negate(res, a);\n   NTL_OPT_RETURN(mat_zz_pE, res);\n}\n\n\nvec_zz_pE operator*(const mat_zz_pE& a, const vec_zz_pE& b)\n{\n   vec_zz_pE res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_zz_pE, res);\n}\n\nvec_zz_pE operator*(const vec_zz_pE& a, const mat_zz_pE& b)\n{\n   vec_zz_pE res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_zz_pE, res);\n}\n\nvoid inv(mat_zz_pE& X, const mat_zz_pE& A)\n{\n   zz_pE d;\n   inv(d, X, A);\n   if (d == 0) ArithmeticError(\"inv: non-invertible matrix\");\n}\n\nvoid power(mat_zz_pE& X, const mat_zz_pE& A, const ZZ& e)\n{\n   if (A.NumRows() != A.NumCols()) LogicError(\"power: non-square matrix\");\n\n   if (e == 0) {\n      ident(X, A.NumRows());\n      return;\n   }\n\n   mat_zz_pE T1, T2;\n   long i, k;\n\n   k = NumBits(e);\n   T1 = A;\n\n   for (i = k-2; i >= 0; i--) {\n      sqr(T2, T1);\n      if (bit(e, i))\n         mul(T1, T2, A);\n      else\n         T1 = T2;\n   }\n\n   if (e < 0)\n      inv(X, T1);\n   else\n      X = T1;\n}\n\nvoid random(mat_zz_pE& x, long n, long m)\n{\n   x.SetDims(n, m);\n   for (long i = 0; i < n; i++) random(x[i], m);\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "29fa07f38e290b4e6763a428189a6eb4f17b639a", "size": 19976, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/mat_lzz_pE.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "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": "homomorphic_evaluation/ntl-11.3.2/src/mat_lzz_pE.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "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": "LibSource/ExtendedNTL/src/mat_lzz_pE.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "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": 18.9705603039, "max_line_length": 74, "alphanum_fraction": 0.4308169804, "num_tokens": 7039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.5466893627001777}}
{"text": "//=======================================================================\n// Copyright (c) 2014 Andrzej Pacuk, Piotr Wygocki\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 lsh_functions.hpp\n * @brief\n * @author Andrzej Pacuk, Piotr Wygocki\n * @version 1.0\n * @date 2014-10-07\n */\n#ifndef PAAL_LSH_FUNCTIONS_HPP\n#define PAAL_LSH_FUNCTIONS_HPP\n\n#include \"paal/data_structures/ublas_traits.hpp\"\n#include \"paal/utils/functors.hpp\"\n#include \"paal/utils/type_functions.hpp\"\n\n#include <boost/range/algorithm/equal.hpp>\n#include <boost/range/algorithm/generate.hpp>\n#include <boost/range/algorithm/min_element.hpp>\n#include <boost/range/algorithm_ext/iota.hpp>\n#include <boost/range/counting_range.hpp>\n#include <boost/range/empty.hpp>\n#include <boost/range/iterator.hpp>\n#include <boost/range/numeric.hpp>\n#include <boost/range/size.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_sparse.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n\n#include <cassert>\n#include <cmath>\n#include <cstddef>\n#include <random>\n#include <type_traits>\n#include <utility>\n\nnamespace paal {\n\nnamespace lsh {\n\n/**\n * @brief simple hash function\n */\ntemplate <typename IntType = std::size_t>\nclass projection_hash_function {\n    IntType m_chosen_position;\n\npublic:\n    ///serialize\n    template<class Archive>\n    void serialize(Archive & ar, const unsigned int version) {\n        ar & m_chosen_position;\n    }\n\n    ///default constructor\n    projection_hash_function() = default;\n\n    /**\n     * @brief constructor\n     *\n     * @param chosen_position\n     *\n     */\n    projection_hash_function(IntType chosen_position) :\n            m_chosen_position(chosen_position) {\n    }\n\n    ///operator==\n    bool operator==(projection_hash_function const & other) const {\n        return m_chosen_position == other.m_chosen_position;\n    }\n\n    /**\n     * @brief operator()\n     *\n     * @tparam Range\n     * @param range\n     *\n     * @return\n     */\n    template <typename Range>\n    //TODO change to decltype(auto), when it starts working\n    auto operator()(Range &&range) const ->\n            range_to_elem_t<decltype(range)> {\n        //TODO takes to long, use boost assert\n        //assert(m_chosen_position < boost::size(range));\n        return range[m_chosen_position];\n    }\n};\n\n/**\n * @brief Factory class for projection_hash_function\n */\ntemplate <typename RandomEngine = std::default_random_engine,\n          typename IntType = std::size_t>\nclass random_projection_hash_function_generator {\n    mutable RandomEngine m_generator;\n    using distribution_t = std::uniform_int_distribution<IntType>;\n    mutable distribution_t m_distribution;\n\n    static IntType convert_to_inclusive(IntType upper_bound) {\n        assert(upper_bound > 0);\n        return upper_bound - 1;\n    }\n\npublic:\n    /**\n     * @brief constructor\n     *\n     * @param range_size\n     * @param random_engine\n     */\n    random_projection_hash_function_generator(IntType range_size,\n            RandomEngine random_engine = RandomEngine{}) :\n            m_generator(std::move(random_engine)),\n            m_distribution(0, convert_to_inclusive(range_size)) {\n    }\n\n    /**\n     * @brief operator()\n     *\n     * @return new projection_hash_function\n     */\n    //TODO change to auto, when it starts working\n    projection_hash_function<IntType> operator()() const {\n        return projection_hash_function<IntType>(m_distribution(m_generator));\n    }\n};\n\nusing hamming_hash_function_generator =\n    random_projection_hash_function_generator<>;\n\n/**\n */\n/// hash_function for l_p distance for p in range (0,2]\ntemplate <typename FloatType = double>\nclass l_p_hash_function {\npublic:\n    using r_param_t = boost::numeric::ublas::vector<FloatType>;\n\nprivate:\n    r_param_t m_r;\n    FloatType m_b;\n    FloatType m_w;\n\npublic:\n\n    ///serialize\n    template<class Archive>\n    void serialize(Archive & ar, const unsigned int version) {\n        ar & m_r;\n        ar & m_b;\n        ar & m_w;\n    }\n\n    /**\n     * @brief constructor\n     *\n     * @param r r elements has to be generated by p-stable distribution\n     * @param b b is a random value from [0, w)\n     * @param w w should be much greater than expected points neighborhood\n     * radius\n     */\n    l_p_hash_function(r_param_t r,\n                      FloatType b, FloatType w) :\n            m_r(std::move(r)), m_b(b), m_w(w) {\n    }\n\n    ///default constructor\n    l_p_hash_function() = default;\n\n    ///operator==\n    bool operator==(l_p_hash_function const & other) const {\n        return boost::equal(m_r, other.m_r) &&\n               m_b == other.m_b &&\n               m_w == other.m_w;\n    }\n\n    /**\n     * @brief operator()\n     *\n     * @tparam Range\n     * @param range Range modeling boost uBLAS VectorExpression concept\n     *\n     * @return\n     */\n    template <typename Range>\n    auto operator()(Range &&range) const {\n        //TODO use concept check with VectorExpressionConcept<Range>,\n        //when it works\n\n        //TODO takes to long, use boost assert\n        //assert(boost::size(m_r) == boost::size(range));\n\n        using boost::numeric::ublas::inner_prod;\n        auto inner_product = inner_prod(m_r, range);\n        return std::floor((m_b + inner_product) / m_w);\n    }\n\n};\n\n/**\n * @brief Factory class for l_p_hash_function\n */\ntemplate <typename FloatType = double,\n          typename RandomEngine = std::default_random_engine,\n          typename Distribution = std::normal_distribution<FloatType>>\nclass l_p_hash_function_generator {\n    std::size_t m_range_size;\n    FloatType m_w;\n    mutable RandomEngine m_generator;\n    mutable Distribution m_r_distribution;\n    mutable std::uniform_real_distribution<FloatType> m_b_distribution;\n\npublic:\n    /**\n     * @brief constructor\n     *\n     * @param range_size\n     * @param w\n     * @param random_engine\n     */\n    l_p_hash_function_generator(std::size_t range_size,\n                                FloatType w,\n                                RandomEngine random_engine = RandomEngine{}) :\n            m_range_size(range_size),\n            m_w(w),\n            m_generator(std::move(random_engine)),\n            m_b_distribution(FloatType{}, w) {\n    }\n\n    /**\n     * @brief operator()\n     *\n     * @return new l_p_hash_function\n     */\n    l_p_hash_function<FloatType> operator()() const {\n        typename l_p_hash_function<FloatType>::r_param_t r(m_range_size);\n        boost::generate(r, [&]() {\n            return m_r_distribution(m_generator);\n        });\n\n        FloatType b = m_b_distribution(m_generator);\n        return l_p_hash_function<FloatType>(std::move(r), b, m_w);\n    }\n};\n\n/// Cauchy distribution is 1-stable\ntemplate <typename FloatType = double,\n          typename RandomEngine = std::default_random_engine>\nusing l_1_hash_function_generator =\n    l_p_hash_function_generator<FloatType, RandomEngine,\n                                std::cauchy_distribution<FloatType>>;\n\n/// Gaussian distribution is 2-stable\ntemplate <typename FloatType = double,\n          typename RandomEngine = std::default_random_engine>\nusing l_2_hash_function_generator =\n    l_p_hash_function_generator<FloatType, RandomEngine>;\n\n///min-wise independent permutations locality sensitive hashing (Jaccard)\nclass min_hash_function {\n    //permutation\n    std::vector<std::size_t> m_perm;\n\npublic:\n\n    ///serialize\n    template<class Archive>\n    void serialize(Archive & ar, const unsigned int version) {\n        ar & m_perm;\n    }\n\n    ///constructor\n    template <typename RandomEngine>\n    min_hash_function(std::size_t set_element_upper_bound, RandomEngine && rng)\n            : m_perm(set_element_upper_bound)  {\n        boost::iota(m_perm, 0);\n        std::shuffle(m_perm.begin(), m_perm.end(), rng);\n    }\n\n    ///default constructor\n    min_hash_function() = default;\n\n    ///operator==\n    bool operator==(min_hash_function const & other) const {\n        return boost::equal(m_perm, other.m_perm);\n    }\n\n    /**\n     * @brief operator()\n     *\n     * @tparam Range\n     * @param range forward range modeling boost uBLAS sparse VectorExpression concept,\n     * set is represented as set of indexes of range elements\n     *\n     * @return\n     */\n    template <typename Range>\n    auto operator()(Range &&range) const {\n        static_assert(data_structures::is_sparse_row<Range>::value, \"vector must be sparse\");\n        using iter_t = typename boost::range_iterator<Range>::type;\n\n        auto perm_function = [&](iter_t it) {\n            auto set_elem = it.index();\n            assert(set_elem < m_perm.size());\n            return m_perm[set_elem];\n        };\n        auto perm_range =\n                boost::counting_range(range)\n                | boost::adaptors::transformed(utils::make_assignable_functor(perm_function));\n\n        assert(!boost::empty(perm_range));\n        return *boost::min_element(perm_range);\n    }\n};\n\n///Factory class for min_hash_function\ntemplate <typename RandomEngine = std::default_random_engine>\nclass min_hash_function_generator {\n    std::size_t m_range_size;\n    mutable RandomEngine m_generator;\n\npublic:\n    ///constructor\n    min_hash_function_generator(std::size_t range_size,\n                                RandomEngine random_engine = RandomEngine{}) :\n            m_range_size(range_size),\n            m_generator(std::move(random_engine)) { }\n\n    ///operator()\n    min_hash_function operator()() const {\n        return min_hash_function(m_range_size, m_generator);\n    }\n};\nusing jaccard_hash_function_generator =\n    min_hash_function_generator<>;\n\n} //! lsh\n\n} //! paal\n\n#endif // PAAL_LSH_FUNCTIONS_HPP\n\n", "meta": {"hexsha": "8e6dd83952648c5e6a28a929dda05c0fecfa72ea", "size": 9839, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/regression/lsh_functions.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/regression/lsh_functions.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/regression/lsh_functions.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.0313390313, "max_line_length": 94, "alphanum_fraction": 0.6458989735, "num_tokens": 2208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7057850340255387, "lm_q1q2_score": 0.5466893601484574}}
{"text": "//==================================================================================================\n/*!\n  @file\n  @copyright 2015 NumScale SAS\n  @copyright 2015 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_ARCH_COMMON_FUNCTION_SCALAR_STIRLING_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_STIRLING_HPP_INCLUDED\n\n#include <boost/config.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/simd/arch/common/detail/generic/stirling_kernel.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/real.hpp>\n#include <boost/simd/constant/sqrt_2pi.hpp>\n#include <boost/simd/function/scalar/exp.hpp>\n#include <boost/simd/function/scalar/fma.hpp>\n#include <boost/simd/function/scalar/is_eqz.hpp>\n#include <boost/simd/function/scalar/pow.hpp>\n#include <boost/simd/function/scalar/rec.hpp>\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/function/scalar/is_nan.hpp>\n#endif\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( stirling_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      const A0 Stirlinglargelim = Real<A0, 0x4065800000000000ULL, 0X420C28F3UL>();// 172, 35.0399895f\n      const A0 Stirlingsplitlim = Real<A0, 0X4061E083BA3443D4ULL, 0X41D628F6UL>();// 143.01608, 26.77f\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      if (is_nan(a0)) return a0;\n      #endif\n      if (a0 > Stirlinglargelim) return Inf<A0>();\n      A0 w = rec(a0);\n      w = fma(w,detail::stirling_kernel<A0>::stirling1(w), One<A0>());\n      A0 y = exp(-a0);\n      if(is_eqz(y)) return Inf<A0>();\n      A0 z =  a0 - Half<A0>();\n      if( a0 >= Stirlingsplitlim )\n      { /* Avoid overflow in pow() */\n        const A0 v = pow(a0,z*Half<A0>());\n        y *= v;\n        y *= v;\n      }\n      else\n      {\n        y *= pow( a0, z );\n      }\n      y *= Sqrt_2pi<A0>()*w;\n      return y;\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "052c95b52093685682e08a580540018720919ff6", "size": 2431, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/stirling.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/arch/common/scalar/function/stirling.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/arch/common/scalar/function/stirling.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": 33.7638888889, "max_line_length": 102, "alphanum_fraction": 0.5939942411, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5466737499630243}}
{"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 <deque>                // to store the vertex ordering\r\n#include <vector>\r\n#include <list>\r\n#include <iostream>\r\n#include <boost/graph/vector_as_graph.hpp>\r\n#include <boost/graph/topological_sort.hpp>\r\n\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  const char *tasks[] = {\r\n    \"pick up kids from school\",\r\n    \"buy groceries (and snacks)\",\r\n    \"get cash at ATM\",\r\n    \"drop off kids at soccer practice\",\r\n    \"cook dinner\",\r\n    \"pick up kids from soccer\",\r\n    \"eat dinner\"\r\n  };\r\n  const int n_tasks = sizeof(tasks) / sizeof(char *);\r\n\r\n  std::vector < std::list < int > > g(n_tasks);\r\n  g[0].push_back(3);\r\n  g[1].push_back(3);\r\n  g[1].push_back(4);\r\n  g[2].push_back(1);\r\n  g[3].push_back(5);\r\n  g[4].push_back(6);\r\n  g[5].push_back(6);\r\n\r\n  std::deque < int >topo_order;\r\n\r\n  topological_sort(g, std::front_inserter(topo_order),\r\n                   vertex_index_map(identity_property_map()));\r\n\r\n  int n = 1;\r\n  for (std::deque < int >::iterator i = topo_order.begin();\r\n       i != topo_order.end(); ++i, ++n)\r\n    std::cout << tasks[*i] << std::endl;\r\n\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "14e375724b0e4dccc572318f594aea1f89894174", "size": 1479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/topo-sort1.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/topo-sort1.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/topo-sort1.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": 29.0, "max_line_length": 74, "alphanum_fraction": 0.553076403, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.5466737448449881}}
{"text": "//==================================================================================================\n/*!\n  @file\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_ERF_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ERF_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n  @ingroup group-euler\n    Function object implementing erf capabilities\n\n   Computes the error function:\n   \\f$\\displaystyle \\frac{2}{\\sqrt\\pi}\\int_0^{x} e^{-t^2}\\mbox{d}t\\f$\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = erf(x);\n    @endcode\n\n    @par Decorators\n\n    std_ for floating entries provides access to @c std::erf\n\n    @see erfc,  erfcx\n\n  **/\n  Value erf(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/erf.hpp>\n#include <boost/simd/function/simd/erf.hpp>\n\n#endif\n", "meta": {"hexsha": "3df73c797e5bf3def802444a26e3a0fa47cc9d22", "size": 1085, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/erf.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/erf.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/erf.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": 23.085106383, "max_line_length": 100, "alphanum_fraction": 0.5732718894, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5466737442249013}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EXPONENTIAL_FUNCTIONS_SCALAR_CBRT_HPP_INCLUDED\n#define NT2_EXPONENTIAL_FUNCTIONS_SCALAR_CBRT_HPP_INCLUDED\n\n#include <nt2/exponential/functions/cbrt.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/real_splat.hpp>\n#include <nt2/include/constants/third.hpp>\n#include <nt2/include/constants/three.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/bitofsign.hpp>\n#include <nt2/include/functions/scalar/bitwise_or.hpp>\n#include <nt2/include/functions/scalar/fast_frexp.hpp>\n#include <nt2/include/functions/scalar/fast_ldexp.hpp>\n#include <nt2/include/functions/scalar/is_gez.hpp>\n#include <nt2/include/functions/scalar/negate.hpp>\n#include <nt2/include/functions/scalar/sqr.hpp>\n#include <nt2/polynomials/functions/scalar/impl/horner.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/constants/inf.hpp>\n#endif\n\n#ifndef BOOST_SIMD_NO_DENORMALS\n#include <nt2/include/constants/smallestposval.hpp>\n#include <nt2/include/constants/twotomnmbo_3.hpp>\n#include <nt2/include/constants/twotonmb.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( cbrt_, tag::cpu_\n                            , (A0)\n                            , (scalar_< double_<A0> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      A0 z =  nt2::abs(a0);\n#ifndef BOOST_SIMD_NO_INFINITIES\n      if (z == nt2::Inf<A0>() || (z == 0)) return a0;\n#else\n      if (z == 0) return a0;\n#endif\n#ifndef BOOST_SIMD_NO_DENORMALS\n      A0 f = One<A0>();\n      if (z < Smallestposval<A0>())\n      {\n        z *= Twotonmb<A0>();\n        f  = Twotomnmbo_3<A0>();\n      }\n#endif\n      const A0 CBRT2  = double_constant< A0, 0x3ff428a2f98d728bll> ();\n      const A0 CBRT4  = double_constant< A0, 0x3ff965fea53d6e3dll> ();\n      const A0 CBRT2I = double_constant< A0, 0x3fe965fea53d6e3dll> ();\n      const A0 CBRT4I = double_constant< A0, 0x3fe428a2f98d728bll> ();\n      typedef typename meta::as_integer<A0, signed>::type int_type;\n      int_type e;\n      A0 x = fast_frexp(z, e);\n      x = horner < NT2_HORNER_COEFF_T(A0, 5,\n                            (0xbfc13c93386fdff6ll,\n                             0x3fe17e1fc7e59d58ll,\n                             0xbfee8a4ca3ba37b8ll,\n                             0x3ff23d6ee505873all,\n                             0x3fd9c0c12122a4fell)\n                            ) > (x);\n      const bool flag = is_gez(e);\n      int_type e1 =  nt2::abs(e);\n      int_type rem = e1;\n      e1 /= Three<int_type>();\n      rem -= e1*Three<int_type>();\n      e =  negate(e1, e);\n      const A0 cbrt2 = flag ? CBRT2 : CBRT2I;\n      const A0 cbrt4 = flag ? CBRT4 : CBRT4I;\n      A0 fact = (rem == One<int_type>()) ? cbrt2: One<A0>();\n      fact = (rem == Two<int_type>() ? cbrt4 : fact);\n      x = fast_ldexp(x*fact, e);\n      x -= (x-z/sqr(x))*Third<A0>();\n      x -= (x-z/sqr(x))*Third<A0>(); //two newton passes\n#ifndef BOOST_SIMD_NO_DENORMALS\n      return b_or(x, bitofsign(a0))*f;\n#else\n      return b_or(x, bitofsign(a0));\n#endif\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( cbrt_, tag::cpu_\n                            , (A0)\n                            , (scalar_< single_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      A0 z =  nt2::abs(a0);\n#ifndef BOOST_SIMD_NO_INFINITIES\n      if (z == nt2::Inf<A0>() || (z == 0)) return a0;\n#else\n      if  (z == 0) return a0;\n#endif\n#ifndef BOOST_SIMD_NO_DENORMALS\n      A0 f = One<A0>();\n      if (z < Smallestposval<A0>())\n      {\n        z *= Twotonmb<A0>();\n        f = Twotomnmbo_3<A0>();\n      }\n#endif\n      const A0 CBRT2  = single_constant< A0, 0x3fa14518> ();\n      const A0 CBRT4  = single_constant< A0, 0x3fcb2ff5> ();\n      const A0 CBRT2I = single_constant< A0, 0x3f4b2ff5> ();\n      const A0 CBRT4I = single_constant< A0, 0x3f214518> ();\n      typedef typename meta::as_integer<A0, signed>::type int_type;\n      int_type e;\n      A0 x = fast_frexp(z, e);\n      x = horner < NT2_HORNER_COEFF_T(A0, 5,\n                                      (0xbe09e49a,\n                                       0x3f0bf0fe,\n                                       0xbf745265,\n                                       0x3f91eb77,\n                                       0x3ece0609)\n                                     ) > (x);\n      const bool flag = is_gez(e);\n      int_type e1 =  nt2::abs(e);\n      int_type rem = e1;\n      e1 /= Three<int_type>();\n      rem -= e1*Three<int_type>();\n      e =  negate(e1, e);\n\n      const A0 cbrt2 = flag ? CBRT2 : CBRT2I;\n      const A0 cbrt4 = flag ? CBRT4 : CBRT4I;\n      A0 fact = (rem ==  One<int_type>()) ? cbrt2 : One<A0>();\n      fact = (rem == Two<int_type>()) ? cbrt4 : fact;\n      x = fast_ldexp(x*fact, e);\n      x -= (x-z/sqr(x))*Third<A0>();\n#ifndef BOOST_SIMD_NO_DENORMALS\n      return b_or(x, bitofsign(a0))*f;\n#else\n      return b_or(x, bitofsign(a0));\n#endif\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "a331901572c3130c217f66c73db45724a6400ab2", "size": 5577, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/functions/scalar/cbrt.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/exponential/include/nt2/exponential/functions/scalar/cbrt.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/exponential/include/nt2/exponential/functions/scalar/cbrt.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 34.85625, "max_line_length": 80, "alphanum_fraction": 0.5592612516, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5466737334002099}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n\nTEST(ProbDistributionsNegBinomial, error_check) {\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::neg_binomial_rng(6, 2, rng));\n  EXPECT_NO_THROW(stan::math::neg_binomial_rng(0.5, 1, rng));\n  EXPECT_NO_THROW(stan::math::neg_binomial_rng(1e9, 1, rng));\n\n  EXPECT_THROW(stan::math::neg_binomial_rng(0, -2, rng),\n                 std::domain_error);\n  EXPECT_THROW(stan::math::neg_binomial_rng(6, -2, rng),\n                   std::domain_error);\n  EXPECT_THROW(stan::math::neg_binomial_rng(-6, -0.1, rng),\n                   std::domain_error);\n  EXPECT_THROW(stan::math::neg_binomial_rng(\n                 stan::math::positive_infinity(), 2, rng),\n                 std::domain_error);\n  EXPECT_THROW(stan::math::neg_binomial_rng(\n                 stan::math::positive_infinity(), 6, rng),\n                 std::domain_error);\n  EXPECT_THROW(stan::math::neg_binomial_rng(2,\n                 stan::math::positive_infinity(), rng),\n                 std::domain_error);\n\n  std::string error_msg;\n  error_msg = \"neg_binomial_rng: Random number that \"\n              \"came from gamma distribution is\";\n  try {\n    stan::math::neg_binomial_rng(1e10, 1, rng);\n    FAIL() << \"neg_binomial_rng should have thrown\" << std::endl;\n  } catch (const std::exception& e) {\n    if (std::string(e.what()).find(error_msg) == std::string::npos)\n      FAIL() << \"Error message is different than expected\" << std::endl\n             << \"EXPECTED: \" << error_msg << std::endl\n             << \"FOUND: \" << e.what() << std::endl;\n    SUCCEED();\n  }\n}\n\nvoid expected_bin_sizes(double *expect, const int K,\n                        const int N,\n                        const double alpha, const double beta) {\n  double p = 0;\n  for(int i = 0 ; i < K; i++)  {\n    expect[i] = N * std::exp(stan::math::neg_binomial_log(i, alpha, beta));\n    p += std::exp(stan::math::neg_binomial_log(i, alpha, beta));\n  }\n  expect[K-1] = N * (1.0 - p);\n}\n\nTEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  double p = 0.6;\n  double alpha = 5;\n  double beta = p / (1 - p);\n  int N = 1000;\n  int K = boost::math::round(2 * std::pow(N, (1-p)));\n  boost::math::chi_squared mydist(K-1);\n\n  int loc[K - 1];\n  for(int i = 1; i < K; i++)\n    loc[i - 1] = i - 1;\n\n  int count = 0;\n  double bin [K];\n  double expect [K];\n\n  for(int i = 0 ; i < K; i++)\n    bin[i] = 0;\n  expected_bin_sizes(expect, K, N, alpha, beta);\n\n  while (count < N) {\n    int a = stan::math::neg_binomial_rng(alpha, beta, rng);\n    int i = 0;\n    while (i < K-1 && a > loc[i])\n      ++i;\n    ++bin[i];\n    count++;\n   }\n\n  double chi = 0;\n\n  for(int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < boost::math::quantile(boost::math::complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest2) {\n  boost::random::mt19937 rng;\n  double p = 0.8;\n  double alpha = 2.4;\n  double beta = p / (1 - p);\n  int N = 1000;\n  int K = boost::math::round(2 * std::pow(N, (1-p)));\n  boost::math::chi_squared mydist(K-1);\n\n  int loc[K - 1];\n  for(int i = 1; i < K; i++)\n    loc[i - 1] = i - 1;\n\n  int count = 0;\n  double bin [K];\n  double expect [K];\n\n  for(int i = 0 ; i < K; i++)\n    bin[i] = 0;\n  expected_bin_sizes(expect, K, N, alpha, beta);\n\n  while (count < N) {\n    int a = stan::math::neg_binomial_rng(alpha, beta, rng);\n    int i = 0;\n    while (i < K-1 && a > loc[i])\n      ++i;\n    ++bin[i];\n    count++;\n   }\n\n  double chi = 0;\n\n  for(int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < boost::math::quantile(boost::math::complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest3) {\n  boost::random::mt19937 rng;\n  double p = 0.2;\n  double alpha = 0.4;\n  double beta = p / (1 - p);\n  int N = 1000;\n  int K = boost::math::round(2 * std::pow(N, (1-p)));\n  boost::math::chi_squared mydist(K-1);\n\n  int loc[K - 1];\n  for(int i = 1; i < K; i++)\n    loc[i - 1] = i - 1;\n\n  int count = 0;\n  double bin [K];\n  double expect [K];\n\n  for(int i = 0 ; i < K; i++)\n    bin[i] = 0;\n  expected_bin_sizes(expect, K, N, alpha, beta);\n\n  while (count < N) {\n    int a = stan::math::neg_binomial_rng(alpha, beta, rng);\n    int i = 0;\n    while (i < K-1 && a > loc[i])\n      ++i;\n    ++bin[i];\n    count++;\n   }\n\n  double chi = 0;\n\n  for(int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < boost::math::quantile(boost::math::complement(mydist, 1e-6)));\n}\n", "meta": {"hexsha": "915e8486419583a67588d9c18a13a217b1fe51a0", "size": 4696, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/prob/neg_binomial_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/prob/neg_binomial_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/prob/neg_binomial_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.119760479, "max_line_length": 82, "alphanum_fraction": 0.569846678, "num_tokens": 1539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5465992983033384}}
{"text": "/*\n * testSudoku.cpp\n * @brief develop code for Sudoku CSP solver\n * @date Jan 29, 2012\n * @author Frank Dellaert\n */\n\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam_unstable/discrete/CSP.h>\n\n#include <boost/assign/std/map.hpp>\nusing boost::assign::insert;\n#include <stdarg.h>\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\nusing namespace gtsam;\n\n#define PRINT false\n\n/// A class that encodes Sudoku's as a CSP problem\nclass Sudoku : public CSP {\n  size_t n_;  ///< Side of Sudoku, e.g. 4 or 9\n\n  /// Mapping from base i,j coordinates to discrete keys:\n  using IJ = std::pair<size_t, size_t>;\n  std::map<IJ, DiscreteKey> dkeys_;\n\n public:\n  /// return DiscreteKey for cell(i,j)\n  const DiscreteKey& dkey(size_t i, size_t j) const {\n    return dkeys_.at(IJ(i, j));\n  }\n\n  /// return Key for cell(i,j)\n  Key key(size_t i, size_t j) const { return dkey(i, j).first; }\n\n  /// Constructor\n  Sudoku(size_t n, ...) : n_(n) {\n    // Create variables, ordering, and unary constraints\n    va_list ap;\n    va_start(ap, n);\n    for (size_t i = 0; i < n; ++i) {\n      for (size_t j = 0; j < n; ++j) {\n        // create the key\n        IJ ij(i, j);\n        Symbol key('1' + i, j + 1);\n        dkeys_[ij] = DiscreteKey(key, n);\n        // get the unary constraint, if any\n        int value = va_arg(ap, int);\n        if (value != 0) addSingleValue(dkeys_[ij], value - 1);\n      }\n      // cout << endl;\n    }\n    va_end(ap);\n\n    // add row constraints\n    for (size_t i = 0; i < n; i++) {\n      DiscreteKeys dkeys;\n      for (size_t j = 0; j < n; j++) dkeys += dkey(i, j);\n      addAllDiff(dkeys);\n    }\n\n    // add col constraints\n    for (size_t j = 0; j < n; j++) {\n      DiscreteKeys dkeys;\n      for (size_t i = 0; i < n; i++) dkeys += dkey(i, j);\n      addAllDiff(dkeys);\n    }\n\n    // add box constraints\n    size_t N = (size_t)sqrt(double(n)), i0 = 0;\n    for (size_t I = 0; I < N; I++) {\n      size_t j0 = 0;\n      for (size_t J = 0; J < N; J++) {\n        // Box I,J\n        DiscreteKeys dkeys;\n        for (size_t i = i0; i < i0 + N; i++)\n          for (size_t j = j0; j < j0 + N; j++) dkeys += dkey(i, j);\n        addAllDiff(dkeys);\n        j0 += N;\n      }\n      i0 += N;\n    }\n  }\n\n  /// Print readable form of assignment\n  void printAssignment(const DiscreteValues& assignment) const {\n    for (size_t i = 0; i < n_; i++) {\n      for (size_t j = 0; j < n_; j++) {\n        Key k = key(i, j);\n        cout << 1 + assignment.at(k) << \" \";\n      }\n      cout << endl;\n    }\n  }\n\n  /// solve and print solution\n  void printSolution() const {\n    auto MPE = optimize();\n    printAssignment(MPE);\n  }\n\n  // Print domain\n  void printDomains(const Domains& domains) {\n    for (size_t i = 0; i < n_; i++) {\n      for (size_t j = 0; j < n_; j++) {\n        Key k = key(i, j);\n        cout << domains.at(k).base1Str();\n        cout << \"\\t\";\n      }  // i\n      cout << endl;\n    }  // j\n  }\n};\n\n/* ************************************************************************* */\nTEST(Sudoku, small) {\n  Sudoku csp(4,           //\n             1, 0, 0, 4,  //\n             0, 0, 0, 0,  //\n             4, 0, 2, 0,  //\n             0, 1, 0, 0);\n\n  // optimize and check\n  auto solution = csp.optimize();\n  DiscreteValues expected;\n  insert(expected)(csp.key(0, 0), 0)(csp.key(0, 1), 1)(csp.key(0, 2), 2)(\n      csp.key(0, 3), 3)(csp.key(1, 0), 2)(csp.key(1, 1), 3)(csp.key(1, 2), 0)(\n      csp.key(1, 3), 1)(csp.key(2, 0), 3)(csp.key(2, 1), 2)(csp.key(2, 2), 1)(\n      csp.key(2, 3), 0)(csp.key(3, 0), 1)(csp.key(3, 1), 0)(csp.key(3, 2), 3)(\n      csp.key(3, 3), 2);\n  EXPECT(assert_equal(expected, solution));\n  // csp.printAssignment(solution);\n\n  // Do BP (AC1)\n  auto domains = csp.runArcConsistency(4, 3);\n  // csp.printDomains(domains);\n  Domain domain44 = domains.at(Symbol('4', 4));\n  EXPECT_LONGS_EQUAL(1, domain44.nrValues());\n\n  // Test Creation of a new, simpler CSP\n  CSP new_csp = csp.partiallyApply(domains);\n  // Should only be 16 new Domains\n  EXPECT_LONGS_EQUAL(16, new_csp.size());\n\n  // Check that solution\n  auto new_solution = new_csp.optimize();\n  // csp.printAssignment(new_solution);\n  EXPECT(assert_equal(expected, new_solution));\n}\n\n/* ************************************************************************* */\nTEST(Sudoku, easy) {\n  Sudoku csp(9,                          //\n             0, 0, 5, 0, 9, 0, 0, 0, 1,  //\n             0, 0, 0, 0, 0, 2, 0, 7, 3,  //\n             7, 6, 0, 0, 0, 8, 2, 0, 0,  //\n\n             0, 1, 2, 0, 0, 9, 0, 0, 4,  //\n             0, 0, 0, 2, 0, 3, 0, 0, 0,  //\n             3, 0, 0, 1, 0, 0, 9, 6, 0,  //\n\n             0, 0, 1, 9, 0, 0, 0, 5, 8,  //\n             9, 7, 0, 5, 0, 0, 0, 0, 0,  //\n             5, 0, 0, 0, 3, 0, 7, 0, 0);\n\n  // csp.printSolution(); // don't do it\n\n  // Do BP (AC1)\n  auto domains = csp.runArcConsistency(9, 10);\n  // csp.printDomains(domains);\n  Key key99 = Symbol('9', 9);\n  Domain domain99 = domains.at(key99);\n  EXPECT_LONGS_EQUAL(1, domain99.nrValues());\n\n  // Test Creation of a new, simpler CSP\n  CSP new_csp = csp.partiallyApply(domains);\n  // 81 new Domains, and still 26 all-diff constraints\n  EXPECT_LONGS_EQUAL(81 + 26, new_csp.size());\n\n  // csp.printSolution(); // still don't do it ! :-(\n}\n\n/* ************************************************************************* */\nTEST(Sudoku, extreme) {\n  Sudoku csp(9,                             //\n             0, 0, 9, 7, 4, 8, 0, 0, 0, 7,  //\n             0, 0, 0, 0, 0, 0, 0, 0, 0, 2,  //\n             0, 1, 0, 9, 0, 0, 0, 0, 0, 7,  //\n             0, 0, 0, 2, 4, 0, 0, 6, 4, 0,  //\n             1, 0, 5, 9, 0, 0, 9, 8, 0, 0,  //\n             0, 3, 0, 0, 0, 0, 0, 8, 0, 3,  //\n             0, 2, 0, 0, 0, 0, 0, 0, 0, 0,  //\n             0, 6, 0, 0, 0, 2, 7, 5, 9, 0, 0);\n\n  // Do BP\n  csp.runArcConsistency(9, 10);\n\n#ifdef METIS\n  VariableIndexOrdered index(csp);\n  index.print(\"index\");\n  ofstream os(\"/Users/dellaert/src/hmetis-1.5-osx-i686/extreme-dual.txt\");\n  index.outputMetisFormat(os);\n#endif\n\n  // Do BP (AC1)\n  auto domains = csp.runArcConsistency(9, 10);\n  // csp.printDomains(domains);\n  Key key99 = Symbol('9', 9);\n  Domain domain99 = domains.at(key99);\n  EXPECT_LONGS_EQUAL(2, domain99.nrValues());\n\n  // Test Creation of a new, simpler CSP\n  CSP new_csp = csp.partiallyApply(domains);\n  // 81 new Domains, and still 20 all-diff constraints\n  EXPECT_LONGS_EQUAL(81 + 20, new_csp.size());\n\n  // csp.printSolution(); // still don't do it ! :-(\n}\n\n/* ************************************************************************* */\nTEST(Sudoku, AJC_3star_Feb8_2012) {\n  Sudoku csp(9,                          //\n             9, 5, 0, 0, 0, 6, 0, 0, 0,  //\n             0, 8, 4, 0, 7, 0, 0, 0, 0,  //\n             6, 2, 0, 5, 0, 0, 4, 0, 0,  //\n\n             0, 0, 0, 2, 9, 0, 6, 0, 0,  //\n             0, 9, 0, 0, 0, 0, 0, 2, 0,  //\n             0, 0, 2, 0, 6, 3, 0, 0, 0,  //\n\n             0, 0, 9, 0, 0, 7, 0, 6, 8,  //\n             0, 0, 0, 0, 3, 0, 2, 9, 0,  //\n             0, 0, 0, 1, 0, 0, 0, 3, 7);\n\n  // Do BP (AC1)\n  auto domains = csp.runArcConsistency(9, 10);\n  // csp.printDomains(domains);\n  Key key99 = Symbol('9', 9);\n  Domain domain99 = domains.at(key99);\n  EXPECT_LONGS_EQUAL(1, domain99.nrValues());\n\n  // Test Creation of a new, simpler CSP\n  CSP new_csp = csp.partiallyApply(domains);\n  // Just the 81 new Domains\n  EXPECT_LONGS_EQUAL(81, new_csp.size());\n\n  // Check that solution\n  auto solution = new_csp.optimize();\n  // csp.printAssignment(solution);\n  EXPECT_LONGS_EQUAL(6, solution.at(key99));\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "8b285816995c0a8f80abd2b1662ece5c3c33b5a1", "size": 7759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam_unstable/discrete/tests/testSudoku.cpp", "max_stars_repo_name": "h-rover/gtsam", "max_stars_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T07:01:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T07:01:48.000Z", "max_issues_repo_path": "gtsam_unstable/discrete/tests/testSudoku.cpp", "max_issues_repo_name": "h-rover/gtsam", "max_issues_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam_unstable/discrete/tests/testSudoku.cpp", "max_forks_repo_name": "h-rover/gtsam", "max_forks_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-21T06:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T06:58:34.000Z", "avg_line_length": 29.3901515152, "max_line_length": 79, "alphanum_fraction": 0.4922026034, "num_tokens": 2817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.5465992884500905}}
{"text": "#include \"ray_intersect_triangle_mesh_brute_force.h\"\n#include \"Ray.h\"\n#include \"MeshTriangle.h\"\n#include \"Object.h\"\n#include \"AABBTree.h\"\n#include \"warnings.h\"\n#include \"VectorXb.h\"\n#include \"tictoc.h\"\n#include \"visualize_aabbtree.h\"\n#include <igl/read_triangle_mesh.h>\n#include <Eigen/Core>\n#include <string> // std::stoi\n#include <iostream>\n#include <iomanip> // std::setw\n#include <memory> // std::shared_ptr\n\nint main(int argc, char * argv[])\n{\n  /////////////////////////////////////////////////////////////////////////////\n  // RAY TRIANGLE MESH INTERSECTION\n  /////////////////////////////////////////////////////////////////////////////\n  std::cout<<\"# Ray Triangle Mesh Intersection\"<<std::endl;\n  // Read in a triangle mesh\n  Eigen::MatrixXd V;\n  Eigen::MatrixXi F;\n  igl::read_triangle_mesh(argc>1?argv[1]:\"../data/rubber-ducky.obj\",V,F);\n  std::cout<<\"  |V| \"<<V.rows()<<\"  \"<<std::endl;\n  std::cout<<\"  |F| \"<<F.rows()<<\"  \"<<std::endl<<std::endl;\n  // Make a bunch of random rays\n  std::vector<Ray> rays;\n  rays.reserve(argc>2?std::stoi(argv[2]):1000);\n  // Default bounds on ray\n  double min_t = 0;\n  double max_t = std::numeric_limits<double>::infinity();\n  for(int r = 0;r<rays.capacity();r++)\n  {\n    rays.emplace_back( Eigen::Vector3d::Random(), Eigen::Vector3d::Random());\n  }\n  std::cout<<\"  Firing \"<<rays.size()<<\" rays...\"<<std::endl<<std::endl;\n\n  // Brute Force\n  tic(); // Start the clock!\n  Eigen::VectorXb bf_hit(rays.size());\n  Eigen::VectorXd bf_t(rays.size());\n  Eigen::VectorXi bf_I(rays.size());\n  // loop over rays\n  for(int r = 0;r<rays.size();r++)\n  {\n    bf_hit(r) = \n      ray_intersect_triangle_mesh_brute_force(\n      rays[r], V, F, min_t, max_t, bf_t(r), bf_I(r));\n  }\n  std::cout<<\"  | Method      | Time in seconds |\"<<std::endl;\n  std::cout<<\"  |:------------|----------------:|\"<<std::endl;\n  std::cout<<\"  | brute force | \" << FLOAT15 << toc() << \" |\"<<std::endl;\n\n  // Build a tree\n  tic();\n  std::vector<std::shared_ptr<Object> > triangles;\n  triangles.reserve(F.rows());\n  // Create a box for each triangle\n  for(int f = 0;f<F.rows();f++)\n  {\n    triangles.emplace_back( std::make_shared<MeshTriangle>(V,F,f) );\n  }\n  std::shared_ptr<AABBTree> root = std::make_shared<AABBTree>(triangles);\n  std::cout<<\"  | build tree  | \" << FLOAT15 << toc() << \" |\"<<std::endl;\n\n  // Shoot rays at tree\n  tic();\n  Eigen::VectorXb tree_hit(rays.size());\n  Eigen::VectorXd tree_t(rays.size());\n  Eigen::VectorXi tree_I(rays.size());\n  {\n    // loop over rays\n    for(int r = 0;r<rays.size();r++)\n    {\n      std::shared_ptr<Object> hit_object;\n      tree_hit(r) = \n        root->ray_intersect(rays[r],min_t,max_t,tree_t(r),hit_object);\n      if(tree_hit(r))\n      {\n        const std::shared_ptr<MeshTriangle> hit_triangle = \n          std::static_pointer_cast<MeshTriangle>(hit_object);\n        tree_I(r) = hit_triangle->f;\n      }\n    }\n    std::cout<<\"  | use tree    | \" << FLOAT15 << toc() << \" |\"<<std::endl;\n  }\n\n  // Check that solutions match.\n  for(int r = 0;r<rays.size();r++)\n  {\n    WARN_IF_NOT_EQUAL(bf_hit,tree_hit,r);\n    if(bf_hit(r) && tree_hit(r))\n    {\n      WARN_IF_NOT_APPROX(bf_t,tree_t,r);\n      WARN_IF_NOT_EQUAL(bf_I,tree_I,r);\n    }\n  }\n\n  // Visualize the tree\n  visualize_aabbtree(V,F,root);\n}\n", "meta": {"hexsha": "7a72e1eec1d1ce332093d1e6efe935d859498990", "size": 3257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rays.cpp", "max_stars_repo_name": "ericpko/computer-graphics-bounding-volume-hierarchy", "max_stars_repo_head_hexsha": "9f4781ab2308ebf57d4ac89e1d37e51c311a17f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rays.cpp", "max_issues_repo_name": "ericpko/computer-graphics-bounding-volume-hierarchy", "max_issues_repo_head_hexsha": "9f4781ab2308ebf57d4ac89e1d37e51c311a17f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rays.cpp", "max_forks_repo_name": "ericpko/computer-graphics-bounding-volume-hierarchy", "max_forks_repo_head_hexsha": "9f4781ab2308ebf57d4ac89e1d37e51c311a17f4", "max_forks_repo_licenses": ["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.019047619, "max_line_length": 79, "alphanum_fraction": 0.5802886091, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5465992859212938}}
{"text": "\n//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_SPECIAL_LAGUERRE_HPP\n#define BOOST_MATH_SPECIAL_LAGUERRE_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/tools/config.hpp>\n#include <boost/math/policies/error_handling.hpp>\n\nnamespace boost{\nnamespace math{\n\n// Recurrance relation for Laguerre polynomials:\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type\n   laguerre_next(unsigned n, T1 x, T2 Ln, T3 Lnm1)\n{\n   typedef typename tools::promote_args<T1, T2, T3>::type result_type;\n   return ((2 * n + 1 - result_type(x)) * result_type(Ln) - n * result_type(Lnm1)) / (n + 1);\n}\n\nnamespace detail{\n\n// Implement Laguerre polynomials via recurrance:\ntemplate <class T>\nT laguerre_imp(unsigned n, T x)\n{\n   T p0 = 1;\n   T p1 = 1 - x;\n\n   if(n == 0)\n      return p0;\n\n   unsigned c = 1;\n\n   while(c < n)\n   {\n      std::swap(p0, p1);\n      p1 = laguerre_next(c, x, p0, p1);\n      ++c;\n   }\n   return p1;\n}\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type\nlaguerre(unsigned n, T x, const Policy&, const mpl::true_&)\n{\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::laguerre_imp(n, static_cast<value_type>(x)), \"boost::math::laguerre<%1%>(unsigned, %1%)\");\n}\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type\n   laguerre(unsigned n, unsigned m, T x, const mpl::false_&)\n{\n   return boost::math::laguerre(n, m, x, policies::policy<>());\n}\n\n} // namespace detail\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type\n   laguerre(unsigned n, T x)\n{\n   return laguerre(n, x, policies::policy<>());\n}\n\n// Recurrence for associated polynomials:\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type\n   laguerre_next(unsigned n, unsigned l, T1 x, T2 Pl, T3 Plm1)\n{\n   typedef typename tools::promote_args<T1, T2, T3>::type result_type;\n   return ((2 * n + l + 1 - result_type(x)) * result_type(Pl) - (n + l) * result_type(Plm1)) / (n+1);\n}\n\nnamespace detail{\n// Laguerre Associated Polynomial:\ntemplate <class T, class Policy>\nT laguerre_imp(unsigned n, unsigned m, T x, const Policy& pol)\n{\n   // Special cases:\n   if(m == 0)\n      return boost::math::laguerre(n, x, pol);\n\n   T p0 = 1;\n\n   if(n == 0)\n      return p0;\n\n   T p1 = m + 1 - x;\n\n   unsigned c = 1;\n\n   while(c < n)\n   {\n      std::swap(p0, p1);\n      p1 = laguerre_next(c, m, x, p0, p1);\n      ++c;\n   }\n   return p1;\n}\n\n}\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type\n   laguerre(unsigned n, unsigned m, T x, const Policy& pol)\n{\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::laguerre_imp(n, m, static_cast<value_type>(x), pol), \"boost::math::laguerre<%1%>(unsigned, unsigned, %1%)\");\n}\n\ntemplate <class T1, class T2>\ninline typename laguerre_result<T1, T2>::type\n   laguerre(unsigned n, T1 m, T2 x)\n{\n   typedef typename policies::is_policy<T2>::type tag_type;\n   return detail::laguerre(n, m, x, tag_type());\n}\n\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_SPECIAL_LAGUERRE_HPP\n", "meta": {"hexsha": "44211f6a8392751a293d3419823d631f7fc97bd1", "size": 3624, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/math/special_functions/laguerre.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/boost/math/special_functions/laguerre.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/boost/math/special_functions/laguerre.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": 26.4525547445, "max_line_length": 180, "alphanum_fraction": 0.6854304636, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.546542056535223}}
{"text": "#include <anie/activation_layers/sigmoid_layer.hpp>\n\n#include <cassert>\n#include <memory>\n#include <boost/compute.hpp>\n\nnamespace anie\n{\n\tsigmoid_layer::sigmoid_layer(const anie::device& device) noexcept\n\t\t: activation_layer(device), u_(device)\n\t{}\n\n\tstd::string_view sigmoid_layer::name() const noexcept\n\t{\n\t\treturn \"Sigmoid\";\n\t}\n\n\tmatrix sigmoid_layer::forward(const matrix& z) const\n\t{\n\t\tassert(device() == z.device());\n\n\t\tstatic BOOST_COMPUTE_FUNCTION(arithemtic_type, sigmoid, (const double x),\n\t\t{\n\t\t\treturn 1. / (1. + exp(-x));\n\t\t});\n\t\t\n\t\tmatrix result(z);\n\t\tboost::compute::transform(result.begin(), result.end(), result.begin(), sigmoid, device().queue());\n\n\t\tu_ = z;\n\t\treturn result;\n\t}\n\tmatrix sigmoid_layer::backward(const matrix& d)\n\t{\n\t\tassert(device() == d.device());\n\n\t\tstatic BOOST_COMPUTE_FUNCTION(arithemtic_type, dsigmoid, (const double x),\n\t\t{\n\t\t\tconst double y = 1. / (1. + exp(-x));\n\t\t\treturn y * (1. - y);\n\t\t});\n\n\t\tmatrix result(u_);\n\t\tboost::compute::transform(result.begin(), result.end(), result.begin(), dsigmoid, device().queue());\n\t\t\t\t\n\t\treturn result;\n\t}\n}\n\nnamespace anie\n{\n\tlayer_ptr sigmoid_layer_generator::operator()(const anie::device& device) const\n\t{\n\t\treturn std::make_shared<sigmoid_layer>(device);\n\t}\n\n\tlayer_generator_ptr sigmoid()\n\t{\n\t\treturn std::make_shared<sigmoid_layer_generator>();\n\t}\n\tlayer_ptr sigmoid(const anie::device& device)\n\t{\n\t\treturn std::make_shared<sigmoid_layer>(device);\n\t}\n}", "meta": {"hexsha": "fd2c4ef87fd05e9c3be29e71666f8a2977a2755e", "size": 1439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/activation_layers/sigmoid_layer.cpp", "max_stars_repo_name": "kmc7468/ANIE", "max_stars_repo_head_hexsha": "ed140830712fa04372c01319b090ef5c1be17ecf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-11-21T12:30:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-26T07:15:30.000Z", "max_issues_repo_path": "src/activation_layers/sigmoid_layer.cpp", "max_issues_repo_name": "kmc7468/ANIE", "max_issues_repo_head_hexsha": "ed140830712fa04372c01319b090ef5c1be17ecf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/activation_layers/sigmoid_layer.cpp", "max_forks_repo_name": "kmc7468/ANIE", "max_forks_repo_head_hexsha": "ed140830712fa04372c01319b090ef5c1be17ecf", "max_forks_repo_licenses": ["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.1384615385, "max_line_length": 102, "alphanum_fraction": 0.6879777623, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5465420544936384}}
{"text": "//\n//  Copyright Toon Knapen, Karl Meerbergen\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 \"../../blas/test/random.hpp\"\n\n#include <boost/numeric/bindings/lapack/geqrf.hpp>\n#include <boost/numeric/bindings/lapack/ormqr.hpp>\n#include <boost/numeric/bindings/lapack/orgqr.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <iostream>\n#include <limits>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\n\n// Randomize a matrix\ntemplate <typename M>\nvoid randomize(M& m) {\n   typedef typename M::size_type  size_type ;\n   typedef typename M::value_type value_type ;\n\n   size_type size1 = m.size1() ;\n   size_type size2 = m.size2() ;\n\n   for (size_type i=0; i<size2; ++i) {\n      for (size_type j=0; j<size1; ++j) {\n         m(j,i) = random_value< value_type >() ;\n      }\n   }\n} // randomize()\n\n\ntemplate <typename T>\nstruct transpose {\n   static const char value ;\n};\n\ntemplate <typename T>\nconst char transpose<T>::value = 'T';\n\n\n\ntemplate <typename T>\nstruct transpose< std::complex<T> > {\n   static const char value ;\n};\n\ntemplate <typename T>\nconst char transpose< std::complex<T> >::value = 'C';\n\ntemplate <typename M>\nublas::triangular_adaptor<const M, ublas::upper> upper_part(const M& m) {\n   return ublas::triangular_adaptor<const M, ublas::upper>( m );\n}\n\ntemplate <typename T, typename W>\nint do_memory_type(int n, W workspace) {\n   typedef typename boost::numeric::bindings::traits::type_traits<T>::real_type real_type ;\n   typedef std::complex< real_type >                                            complex_type ;\n\n   typedef ublas::matrix<T, ublas::column_major> matrix_type ;\n   typedef ublas::vector<T>                      vector_type ;\n\n   // Set matrix\n   matrix_type a( n, n );\n   vector_type tau( n );\n\n   randomize( a );\n   matrix_type a2( a );\n   matrix_type a3( a );\n\n   // Compute QR factorization.\n   lapack::geqrf( a, tau, workspace ) ;\n\n   // Apply the orthogonal transformations to a2\n   lapack::ormqr( 'L', transpose<T>::value, a, tau, a2, workspace );\n\n   // The upper triangular parts of a and a2 must be equal.\n   if (norm_frobenius( upper_part( a - a2 ) )\n            > std::numeric_limits<real_type>::epsilon() * 10.0 * norm_frobenius( upper_part( a ) ) ) return 255 ;\n\n   // Generate orthogonal matrix\n   lapack::orgqr( a, tau, workspace );\n\n   // The result of lapack::ormqr and the equivalent matrix product must be equal.\n   if (norm_frobenius( a2 - prod(herm(a), a3) )\n            > std::numeric_limits<real_type>::epsilon() * 10.0 * norm_frobenius( a2 ) ) return 255 ;\n\n   return 0 ;\n} // do_value_type()\n\n\n\ntemplate <typename T>\nint do_value_type() {\n   const int n = 8 ;\n   \n   if (do_memory_type<T,lapack::optimal_workspace>( n, lapack::optimal_workspace() ) ) return 255 ;\n   if (do_memory_type<T,lapack::minimal_workspace>( n, lapack::minimal_workspace() ) ) return 255 ;\n\n   ublas::vector<T> work( n );\n   do_memory_type<T, lapack::detail::workspace1<ublas::vector<T> > >( n, lapack::workspace(work) );\n   return 0;\n} // do_value_type()\n\n\nint main() {\n   // Run tests for different value_types\n   if (do_value_type<float>()) return 255;\n   if (do_value_type<double>()) return 255;\n   if (do_value_type< std::complex<float> >()) return 255;\n   if (do_value_type< std::complex<double> >()) return 255;\n\n   std::cout << \"Regression test succeeded\\n\" ;\n   return 0;\n}\n\n", "meta": {"hexsha": "5ba8126868662797dbd781a973653d02bfe101b0", "size": 3646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_geqrf.cpp", "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/lapack/test/ublas_geqrf.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_geqrf.cpp", "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": 28.2635658915, "max_line_length": 113, "alphanum_fraction": 0.6681294569, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5465420544936382}}
{"text": "//Link to Boost\n#define BOOST_TEST_DYN_LINK\n\n//VERY IMPORTANT - include this last\n//#include <boost/test/included/unit_test.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"test.h\"\n#include \"../BetheFunctions.h\"\n#include \"../BethePolynomials.h\"\n\nusing namespace std::literals::complex_literals;\n\n// test suite\nBOOST_FIXTURE_TEST_SUITE(BetheFactor_suite, SimpleTestFixture, * utf::label(\"BetheFactor\"))\n\nBOOST_AUTO_TEST_CASE(coef_test)\n{\n    int L = 6;\n    int M = 2;\n    BetheFactorLeft left(L, M);\n    BetheFactorRight right(L, M);\n    for (int i = 0; i < 3; i++) {\n        var_t *coef1Left = left.coef1((RootType)i);\n        var_t *coef1Right = right.coef1((RootType)i);\n        for (int j = 0; j < 3; j++) {\n            BOOST_TEST_INFO(\"i=\" << i << \", j=\" << j);\n            BOOST_TEST(isZero(std::conj(coef1Left[j]) - coef1Right[j]));\n        }\n    }\n    \n    for (int i = 0; i < 3; i++) {\n        for (int j = 0; j < 3; j++) {\n            var_t *coef2Left = left.coef2((RootType)i, (RootType)j);\n            var_t *coef2Right = right.coef2((RootType)i, (RootType)j);\n            for (int k = 0; k < 6; k++) {\n                BOOST_TEST_INFO(\"i=\" << i << \", j=\" << j << \", k=\" << k);\n                BOOST_TEST(isZero(std::conj(coef2Left[k]) - coef2Right[k]));\n            }\n        }\n    }\n}\n\n\nBOOST_DATA_TEST_CASE(eval_test_regular, bdata::random(4, 16) ^ bdata::xrange(20), L, index)\n{\n    int M = random64(L/2);\n    if (M <= 1) M = 2;\n    Vector roots(M);\n    for (int i = 0; i < M; i++) {\n        roots(i) = randomComplex(0.1, 0.9);\n    }\n        \n    BetheSolution sol1(roots, L, 0.0, 0.0);\n    InvertableSolution sol2(roots, L);\n    \n    BetheFactorLeft left1(L, M);\n    BetheFactorRight right1(L, M);\n    \n    //BethePolynomial left2(L, M, true);\n    BethePolynomialLeft left2(L, M);\n    //BethePolynomial right2(L, M, false);\n    BethePolynomialRight right2(L, M);\n    \n    \n    BOOST_TEST((left1.eval(sol1) - left2.eval(sol2)).norm() == 0, tt::tolerance(eps));\n    Vector v1 = right1.eval(sol1);\n    Vector v2 = right2.eval(sol2);\n    BOOST_TEST((v1 - v2).norm() == 0, tt::tolerance(eps));    \n}\n\nBOOST_DATA_TEST_CASE(eval_test_largest, bdata::random(4, 16) ^ bdata::xrange(20), L, index)\n{\n    int M = random64(L/2);\n    if (M <= 1) M = 2;\n    int indexOfLargest = random64(M - 1);    \n    Vector roots(M);\n    roots(indexOfLargest) = randomComplex(blowup_root_cutoff/0.3, blowup_root_cutoff/0.2);\n\n    for (int i = 0; i < M; i++) {\n        if (i == indexOfLargest) continue;\n        roots(i) = randomComplex(0.1, 0.9);\n    }\n        \n    BetheSolution sol1(roots, L, 0.0, 0.01);\n    InvertableSolution sol2(roots, L);\n    \n    BetheFactorLeft left1(L, M);\n    BetheFactorRight right1(L, M);\n    \n    BethePolynomialLeft left2(L, M);\n    BethePolynomialRight right2(L, M);\n    \n    \n    BOOST_TEST((left1.eval(sol1) - left2.eval(sol2)).norm() == 0, tt::tolerance(eps));\n    Vector v1 = right1.eval(sol1);\n    Vector v2 = right2.eval(sol2);\n//    std::cout << \"indexOfLargest=\" << indexOfLargest << std::endl;\n//    std::cout << \"v1=\" << v1 << std::endl;\n//    std::cout << \"v2=\" << v2 << std::endl;\n    BOOST_TEST((v1 - v2).norm() == 0, tt::tolerance(eps));    \n}\n\nBOOST_DATA_TEST_CASE(eval_test_largest_large, bdata::random(4, 16) ^ bdata::xrange(1), L, index)\n{\n    int M = 2;\n    int indexOfLargest = 0;\n    int indexOfLarge = 1;\n    \n    Vector roots(M);\n    roots(indexOfLargest) = randomComplex(blowup_root_cutoff/0.3, blowup_root_cutoff/0.2);\n    roots(indexOfLarge) = randomComplex(blowup_root_cutoff/0.5, blowup_root_cutoff/0.4);\n        \n    BetheSolution sol1(roots, L, 0.0, 0.01);\n    InvertableSolution sol2(roots, L);\n    \n    BetheFactorLeft left1(L, M);\n    BetheFactorRight right1(L, M);\n    \n    BethePolynomialLeft left2(L, M);\n    BethePolynomialRight right2(L, M);\n    \n    Vector v1 = left1.eval(sol1);\n    Vector v2 = left2.eval(sol2);\n    \n    var_t ratio = roots(indexOfLarge) / roots(indexOfLargest);\n    v2(indexOfLargest) *= roots(indexOfLarge);\n    v2(indexOfLarge) *= roots(indexOfLarge) * std::pow(ratio, L);\n    \n//    std::cout << \"v1=\" << v1 << std::endl;\n//    std::cout << \"v2=\" << v2 << std::endl;\n\n    BOOST_TEST((v1 - v2).norm() == 0, tt::tolerance(eps));\n    v1 = right1.eval(sol1);\n    v2 = right2.eval(sol2);\n    v2(indexOfLargest) *= roots(indexOfLarge);\n    v2(indexOfLarge) *= roots(indexOfLarge) * std::pow(ratio, L); \n//    std::cout << \"indexOfLargest=\" << indexOfLargest << std::endl;\n//    std::cout << \"v1=\" << v1 << std::endl;\n//    std::cout << \"v2=\" << v2 << std::endl;\n    BOOST_TEST((v1 - v2).norm() == 0, tt::tolerance(eps));    \n}\n\nBOOST_DATA_TEST_CASE(eval_test_singular, bdata::random(2, 16) ^ bdata::xrange(20), halfL, index)\n{\n    int L = 2 * halfL;\n    int M = 2;\n    int index1 = 0;\n    int index2 = 1;\n    \n    Vector roots(M);\n    roots(index2) = -0.5il;\n    roots(index1) = 0.5il;\n    BetheSolution sol(roots, L, 0.0, 0.01);\n        \n    BetheFactorLeft left(L, M);\n    BetheFactorRight right(L, M);\n    \n//    std::cout << \"left.eval() = \" << left.eval(sol) << std::endl;\n//    std::cout << \"right.eval() = \" << right.eval(sol) << std::endl;\n    \n    BOOST_TEST((left.eval(sol) - right.eval(sol)).norm() == 0, tt::tolerance(eps));\n}\n\n\nBOOST_DATA_TEST_CASE(diff_test_regular, bdata::random(4, 16) ^ bdata::xrange(20), L, index)\n{\n    int M = random64(L/2);\n    if (M <= 1) M = 2;\n    Vector roots(M);\n    for (int i = 0; i < M; i++) {\n        roots(i) = randomComplex(0.1, 0.9);\n    }\n        \n    BetheSolution sol1(roots, L, 0.0, 0.01);\n    InvertableSolution sol2(roots, L);\n    \n    BetheFactorLeft left1(L, M);\n    BetheFactorRight right1(L, M);\n    \n    BethePolynomialLeft left2(L, M);\n    BethePolynomialRight right2(L, M);\n    \n    BOOST_TEST((left1.diff(sol1) - left2.diff(sol2)).norm() == 0, tt::tolerance(eps));\n    Matrix v1 = right1.diff(sol1);\n    Matrix v2 = right2.diff(sol2);\n//    std::cout << \"v1-v2=\" << v1 - v2 << std::endl;\n    BOOST_TEST((v1 - v2).norm() == 0, tt::tolerance(eps));    \n}\n\nBOOST_DATA_TEST_CASE(diff_test_largest, bdata::random(4, 16) ^ bdata::xrange(20), L, index)\n{\n    int M = random64(L/2);\n    if (M <= 1) M = 2;\n    int indexOfLargest = random64(M - 1);    \n    Vector roots(M);\n    roots(indexOfLargest) = randomComplex(blowup_root_cutoff/0.3, blowup_root_cutoff/0.2);\n\n    for (int i = 0; i < M; i++) {\n        if (i == indexOfLargest) continue;\n        roots(i) = randomComplex(0.1, 0.9);\n    }\n        \n    BetheSolution sol1(roots, L, 0.0, 0.01);\n    InvertableSolution sol2(roots, L);\n    \n    BetheFactorLeft left1(L, M);\n    BetheFactorRight right1(L, M);\n    \n    BethePolynomialLeft left2(L, M);\n    BethePolynomialRight right2(L, M);\n    \n    Matrix w1 = left1.diff(sol1);\n    Matrix w2 = left2.diff(sol2);\n//    std::cout << \"M=\" << M << \", indexOfLargest=\" << indexOfLargest << std::endl;\n//    std::cout << \"w1=\" << w1 << std::endl;\n//    std::cout << \"w2=\" << w2 << std::endl;\n//    std::cout << \"diff=\" << w1-w2 << std::endl;\n\n    \n    BOOST_TEST((w1 - w2).norm() == 0, tt::tolerance(eps));\n    Matrix v1 = right1.diff(sol1);\n    Matrix v2 = right2.diff(sol2);\n//    std::cout << \"M=\" << M << \", indexOfLargest=\" << indexOfLargest << std::endl;\n//    std::cout << \"v1=\" << v1 << std::endl;\n//    std::cout << \"v2=\" << v2 << std::endl;\n//    std::cout << \"diff=\" << v1-v2 << std::endl;\n    BOOST_TEST((v1 - v2).norm() == 0, tt::tolerance(eps));    \n}\n\nBOOST_DATA_TEST_CASE(diff_test_LeftFactor, bdata::random(4, 16) ^ bdata::xrange(20), L, index)\n{\n    int M = random64(L/2);\n    if (M <= 1) M = 2;\n    int indexOfLargest = random64(M - 1);    \n    Vector roots(M);\n    Vector diff1(M); // infinetesimal differential of roots for regular roots\n    Vector diff2(M); // infinetesimal differential of roots for BetheSolution.root();\n    elem_t delta = 1e-4;\n    \n    roots(indexOfLargest) = randomComplex(blowup_root_cutoff/0.3, blowup_root_cutoff/0.2);\n    diff1(indexOfLargest) = delta * (random64(3) + 1) * randomComplex(1.0, 1.1);\n    diff2(indexOfLargest) = -diff1(indexOfLargest) / (roots(indexOfLargest) * roots(indexOfLargest));\n\n    for (int i = 0; i < M; i++) {\n        if (i == indexOfLargest) continue;\n        diff1(i) = delta * (random64(3) + 1) * randomComplex(1.0, 1.1);\n        if (i % 2 == 0) {\n            // large root\n            roots(i) = randomComplex(blowup_root_cutoff/0.5, blowup_root_cutoff/0.4);\n            diff2(i) = diff1(i) / roots(indexOfLargest) - diff1(indexOfLargest) * roots(i) / (roots(indexOfLargest) * roots(indexOfLargest));\n        } else {\n            // regular root\n            roots(i) = randomComplex(blowup_root_cutoff/1.5, blowup_root_cutoff/1.2);\n            diff2(i) = diff1(i);\n        }\n    }\n    \n    Vector roots2 = roots + diff1;\n    Vector roots3 = roots + diff1 * 0.5L;\n            \n    BetheSolution sol1(roots, L, 0.0, 0.01);\n    BetheSolution sol2(roots2, L, 0.0, 0.01);\n    BetheSolution sol3(roots3, L, 0.0, 0.01);\n    \n    BetheFactorLeft left(L, M);\n    Vector res1 = left.eval(sol1);\n    Vector res2 = left.eval(sol2);\n    Vector resDiff = res2 - res1;\n    \n    Matrix jacobian = left.diff(sol3);\n    Vector resDiff2 = jacobian * diff2;\n    \n//    std::cout << \"resDiff=\" << resDiff << std::endl;\n//    std::cout << \"resDiff2=\" << resDiff2 << std::endl;\n    for (int i = 0; i < M; i++) {\n        var_t v1 = resDiff(i);\n        var_t v2 = resDiff2(i);\n        BOOST_TEST_INFO(\"M=\" << M << \",i=\" << i << \", v1=\" << v1 << \", v2=\" << v2);\n        BOOST_TEST(std::abs(v1-v2)/std::max(std::abs(v1), std::abs(v2)) == 0, tt::tolerance(delta * 10));\n    }\n}\n\nBOOST_DATA_TEST_CASE(diff_test_RightFactor, bdata::random(4, 16) ^ bdata::xrange(20), L, index)\n{\n    int M = random64(L/2);\n    if (M <= 1) M = 2;\n    int indexOfLargest = random64(M - 1);    \n    Vector roots(M);\n    Vector diff1(M); // infinetesimal differential of roots for regular roots\n    Vector diff2(M); // infinetesimal differential of roots for BetheSolution.root();\n    elem_t delta = 1e-4;\n    \n    roots(indexOfLargest) = randomComplex(blowup_root_cutoff/0.3, blowup_root_cutoff/0.2);\n    diff1(indexOfLargest) = delta * (random64(3) + 1) * randomComplex(1.0, 1.1);\n    diff2(indexOfLargest) = -diff1(indexOfLargest) / (roots(indexOfLargest) * roots(indexOfLargest));\n\n    for (int i = 0; i < M; i++) {\n        if (i == indexOfLargest) continue;\n        diff1(i) = delta * (random64(3) + 1) * randomComplex(1.0, 1.1);\n        if (i % 2 == 0) {\n            // large root\n            roots(i) = randomComplex(blowup_root_cutoff/0.5, blowup_root_cutoff/0.4);\n            diff2(i) = diff1(i) / roots(indexOfLargest) - diff1(indexOfLargest) * roots(i) / (roots(indexOfLargest) * roots(indexOfLargest));\n        } else {\n            // regular root\n            roots(i) = randomComplex(blowup_root_cutoff/1.5, blowup_root_cutoff/1.2);\n            diff2(i) = diff1(i);\n        }\n    }\n    \n    Vector roots2 = roots + diff1;\n    Vector roots3 = roots + diff1 * 0.5L;\n            \n    BetheSolution sol1(roots, L, 0.0, 0.01);\n    BetheSolution sol2(roots2, L, 0.0, 0.01);\n    BetheSolution sol3(roots3, L, 0.0, 0.01);\n    \n    BetheFactorRight right(L, M);\n    Vector res1 = right.eval(sol1);\n    Vector res2 = right.eval(sol2);\n    Vector resDiff = res2 - res1;\n    \n    Matrix jacobian = right.diff(sol3);\n    Vector resDiff2 = jacobian * diff2;\n    \n//    std::cout << \"resDiff=\" << resDiff << std::endl;\n//    std::cout << \"resDiff2=\" << resDiff2 << std::endl;\n    for (int i = 0; i < M; i++) {\n        var_t v1 = resDiff(i);\n        var_t v2 = resDiff2(i);\n        BOOST_TEST_INFO(\"M=\" << M << \",i=\" << i << \", v1=\" << v1 << \", v2=\" << v2);\n        BOOST_TEST(std::abs(v1-v2)/std::max(std::abs(v1), std::abs(v2)) == 0, tt::tolerance(delta * 20));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(diff_test_singular)\n{\n    elem_t tmp = eps_may_be_singular;\n    eps_may_be_singular = 0.1L;\n    int L = 6;\n    int M = 3;\n    var_t r1(0.54236679461751705L,2.90957067279989408e-11L);\n    var_t r2(0.0968423125274162171L,0.500001874059868433L);\n    var_t r3(0.0968423125273995912L,-0.50000187418704665L);\n    elem_t beta = 0.914203L;\n\n    Vector roots(M);\n    roots(0) = r1;\n    roots(1) = r2;\n    roots(2) = r3;\n    BetheSolution sol(roots, L, beta, Pi/1000);\n    BOOST_TEST_REQUIRE(sol.indexOfSingularRoot1() >= 1);\n    BOOST_TEST_REQUIRE(sol.indexOfSingularRoot2() >= 1);\n\n    BetheFactorLeft left(L, M);\n    Vector res1 = left.eval(sol);\n    Matrix jacobian = left.diff(sol);\n    \n    Vector inc(M);\n    inc(0) = 0.0L;\n    inc(sol.indexOfSingularRoot1()) = 0.0L;\n    inc(sol.indexOfSingularRoot2()) = 0.0L;\n    inc(sol.indexOfSingularRoot2()) = 0.0L;\n    inc(0) = randomComplex(1e-3, 2e-3);\n    inc(sol.indexOfSingularRoot1()) = randomComplex(1e-1, 2e-1);\n    inc(sol.indexOfSingularRoot2()) = randomComplex(1e-3, 2e-3);\n    \n    sol.root() += inc;\n    Vector res2 = left.eval(sol);\n    Vector diff = res2 - res1;\n        \n    Vector expected = jacobian * inc;\n//    std::cout << \"res1=\" << res1 << std::endl;\n//    std::cout << \"res2=\" << res2 << std::endl;\n//    std::cout << \"diff=\" << diff << std::endl;\n//    std::cout << \"expected=\" << expected << std::endl;\n    \n    BOOST_TEST_INFO(\"inc=\" << inc);\n    BOOST_TEST((diff-expected).norm()/expected.norm() < 2e-2);\n\n    eps_may_be_singular = tmp;    \n}\n\nBOOST_AUTO_TEST_CASE(diff_test_singular_RightFactor)\n{\n    elem_t tmp = eps_may_be_singular;\n    eps_may_be_singular = 0.1L;\n    int L = 6;\n    int M = 3;\n    var_t r1(0.54236679461751705L,2.90957067279989408e-11L);\n    var_t r2(0.0968423125274162171L,0.500001874059868433L);\n    var_t r3(0.0968423125273995912L,-0.50000187418704665L);\n    elem_t beta = 0.914203L;\n\n    Vector roots(M);\n    roots(0) = r1;\n    roots(1) = r2;\n    roots(2) = r3;\n    BetheSolution sol(roots, L, beta, Pi/1000);\n    BOOST_TEST_REQUIRE(sol.indexOfSingularRoot1() >= 1);\n    BOOST_TEST_REQUIRE(sol.indexOfSingularRoot2() >= 1);\n\n    BetheFactorRight right(L, M);\n    Vector res1 = right.eval(sol);\n    Matrix jacobian = right.diff(sol);\n    \n    Vector inc(M);\n    inc(0) = 0.0L;\n    inc(sol.indexOfSingularRoot1()) = 0.0L;\n    inc(sol.indexOfSingularRoot2()) = 0.0L;\n    inc(sol.indexOfSingularRoot2()) = 0.0L;\n    inc(0) = randomComplex(1e-3, 2e-3);\n    inc(sol.indexOfSingularRoot1()) = randomComplex(1e-1, 2e-1);\n    inc(sol.indexOfSingularRoot2()) = randomComplex(1e-3, 2e-3);\n    \n    sol.root() += inc;\n    Vector res2 = right.eval(sol);\n    Vector diff = res2 - res1;\n        \n    Vector expected = jacobian * inc;\n//    std::cout << \"res1=\" << res1 << std::endl;\n//    std::cout << \"res2=\" << res2 << std::endl;\n//    std::cout << \"diff=\" << diff << std::endl;\n//    std::cout << \"expected=\" << expected << std::endl;\n    \n    BOOST_TEST_INFO(\"inc=\" << inc);\n    BOOST_TEST((diff-expected).norm()/expected.norm() < 2e-2);\n\n    eps_may_be_singular = tmp;    \n}\n\nBOOST_AUTO_TEST_CASE(diff_test_largest_LeftFactor)\n{\n    int L = 6;\n    int M = 3;\n    \n    var_t r1(0.288675134570472836L, -1.98390501120640128e-11L);\n    var_t r2(4833488737.1251517L, 8727942389.24525939L);\n    var_t r3(-5137763027.0882383L, 8552377948.96713318L);\n    elem_t beta = 1.5708L;\n\n    Vector roots(M);\n    roots(0) = r1;\n    roots(1) = r2;\n    roots(2) = r3;\n    BetheSolution sol(roots, L, beta, Pi/1000);\n    BOOST_TEST_REQUIRE(sol.indexOfBlowupRoot() >= 1);\n\n    BetheFactorRight left(L, M);\n    Vector res1 = left.eval(sol);\n    Matrix jacobian = left.diff(sol);\n    \n    Vector inc = Vector::Zero(M);\n    for (int i = 0; i < inc.size(); i++) {\n        if (sol.type(i) == regular) {\n            inc(i) = randomComplex(1e-4, 2e-4);\n        } else if (sol.type(i) == largest) {\n            elem_t phi = std::arg(sol.root(i));\n            inc(i) = -std::abs(sol.root(i)) * random(1.0, 1.5) * std::polar(1.0L, phi);;\n        } else {\n            inc(i) = randomComplex(1e-4, 2e-4);\n        }\n    }\n    \n    sol.root() += inc;\n    Vector res2 = left.eval(sol);\n    Vector diff = res2 - res1;\n        \n    Vector expected = jacobian * inc;\n//    std::cout << \"res1=\" << res1 << std::endl;\n//    std::cout << \"res2=\" << res2 << std::endl;\n//    std::cout << \"diff=\" << diff << std::endl;\n//    std::cout << \"expected=\" << expected << std::endl;\n    \n    BOOST_TEST_INFO(\"inc=\" << inc);\n    BOOST_TEST((diff-expected).norm()/expected.norm() < 1e-3);\n}\n\n\nBOOST_AUTO_TEST_CASE(diff_test_largest_RightFactor)\n{\n    int L = 6;\n    int M = 3;\n    \n    var_t r1(0.288675134570472836L, -1.98390501120640128e-11L);\n    var_t r2(4833488737.1251517L, 8727942389.24525939L);\n    var_t r3(-5137763027.0882383L, 8552377948.96713318L);\n    elem_t beta = 1.5708L;\n\n    Vector roots(M);\n    roots(0) = r1;\n    roots(1) = r2;\n    roots(2) = r3;\n    BetheSolution sol(roots, L, beta, Pi/1000);\n    BOOST_TEST_REQUIRE(sol.indexOfBlowupRoot() >= 1);\n\n    BetheFactorRight right(L, M);\n    Vector res1 = right.eval(sol);\n    Matrix jacobian = right.diff(sol);\n    \n    Vector inc = Vector::Zero(M);\n    for (int i = 0; i < inc.size(); i++) {\n        if (sol.type(i) == regular) {\n            inc(i) = randomComplex(1e-4, 2e-4);\n        } else if (sol.type(i) == largest) {\n            elem_t phi = std::arg(sol.root(i));\n            inc(i) = std::abs(sol.root(i)) * random(1.0, 1.5) * std::polar(1.0L, phi);;\n        } else {\n            inc(i) = randomComplex(1e-4, 2e-4);\n        }\n    }\n    \n    sol.root() += inc;\n    Vector res2 = right.eval(sol);\n    Vector diff = res2 - res1;\n        \n    Vector expected = jacobian * inc;\n//    std::cout << \"res1=\" << res1 << std::endl;\n//    std::cout << \"res2=\" << res2 << std::endl;\n//    std::cout << \"diff=\" << diff << std::endl;\n//    std::cout << \"expected=\" << expected << std::endl;\n    \n    BOOST_TEST_INFO(\"inc=\" << inc);\n    BOOST_TEST((diff-expected).norm()/expected.norm() < 1e-3);\n}\n/*\nBOOST_AUTO_TEST_CASE(diff_test_largest2)\n{\n    int L = 6;\n    int M = 2;\n    var_t r1(-2002453610.04371309,18872186.6385834396);\n    var_t r2(-2002453610.04371309,18872186.6385834396);\n    elem_t beta = 0.785398;\n    elem_t delta = Pi/1000;\n\n    Vector roots(M);\n    roots(0) = r1;\n    roots(1) = r2;\n    BetheSolution sol(roots, L, beta, delta);\n    BOOST_TEST_REQUIRE(sol.indexOfBlowupRoot() >= 0);\n\n    BetheFactorLeft left(L, M);\n    BetheFactorRight right(L, M);\n    Vector res1 = right.eval(sol);\n    Matrix jacobian1 = left.diff(sol);\n    Matrix jacobian2 = right.diff(sol);\n    Matrix jacobian = jacobian1 - jacobian2 * std::polar(1.0L, 2.0L * L * beta);\n    Matrix jacobianInv = jacobian.inverse();\n\n    Vector rhs = left.eval(sol) * var_t((elem_t)0.0, 2.0 * L);\n    \n//    std::cout << \"jacobian = \" << jacobian << std::endl;\n//    std::cout << \"jacobianInv=\" << jacobianInv << std::endl;\n//    std::cout << \"rhs=\" << std::setprecision(18) << rhs << std::endl;\n    \n    Vector inc1 = jacobianInv * rhs * delta/2.0;\n//    std::cout << \"jacobianInv.rhs=\" << std::setprecision(18) << inc1 << std::endl;\n//    std::cout << \"root=\" << sol.root() << std::endl;\n    sol.root() += inc1;\n//    std::cout << \"after root=\" << sol.normalRoot() << std::endl;\n}*/\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "97b4f86a77ad8db63b9745f23d2a89b1fd179a53", "size": 19029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/BetheFunctionTests.cpp", "max_stars_repo_name": "gaolichen/bethesolver", "max_stars_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_stars_repo_licenses": ["MIT"], "max_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/BetheFunctionTests.cpp", "max_issues_repo_name": "gaolichen/bethesolver", "max_issues_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_issues_repo_licenses": ["MIT"], "max_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/BetheFunctionTests.cpp", "max_forks_repo_name": "gaolichen/bethesolver", "max_forks_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_forks_repo_licenses": ["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.6201413428, "max_line_length": 141, "alphanum_fraction": 0.5835829523, "num_tokens": 6437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5465420515829247}}
{"text": "// cfiles, an analysis frontend for the Chemfiles library\n// Copyright (C) Guillaume Fraux and contributors -- BSD license\n\n#include <fstream>\n\n#include <docopt/docopt.h>\n#include <fmt/format.h>\n#include <fmt/ostream.h>\n#include <chemfiles.hpp>\n#include <Eigen/Dense>\n\n#include \"Elastic.hpp\"\n#include \"Errors.hpp\"\n\nusing namespace chemfiles;\n\nusing Matrix6 = Eigen::Matrix<double, 6, 6>;\n\nstatic size_t CARTESIAN_TO_VOIGT[][2] = {\n    {0, 0}, {1, 1}, {2, 2}, {1, 2}, {0, 2}, {0, 1},\n};\n\nstatic const std::string OPTIONS =\nR\"(Compute the elastic tensor of a system from the unit cell fluctuations during\na NPT simulation.\n\nThe values given here are highly dependent on having good statistic during the\nsimulation: both in term of having a long enough simulation time to get to the\nequilibrium, and using a good barostat that does produce isobaric-isothermal\nensemble fluctuations (not just average). The theory behind this code is\ndescribed in https://dx.doi.org/10.1080/08927022.2017.1313418.\n\nUsage:\n  cfiles elastic [options] <trajectory>\n  cfiles elastic (-h | --help)\n\nExamples:\n  cfiles elastic -t 328 -o elastic.dat trajectory.pdb\n\nOptions:\n  -h --help                        show this help\n  --format=<format>                force the input file format to be <format>\n  -t <temp>, --temperature=<temp>  temperature of the simulation, in kelvin\n  -o <file>, --output=<file>       write result to <file>. This default to the\n                                   trajectory file name with the `.angles.dat`\n                                   extension.\n  --steps=<steps>                  steps to use from the input. <steps> format\n                                   is <start>:<end>[:<stride>] with <start>,\n                                   <end> and <stride> optional. The used steps\n                                   goes from <start> to <end> (excluded) by\n                                   steps of <stride>. The default values are 0\n                                   for <start>, the number of steps for <end>\n                                   and 1 for <stride>.\n)\";\n\n\nstatic Elastic::Options parse_options(int argc, const char* argv[]) {\n    auto options_str = command_header(\"elastic\", Elastic().description());\n    options_str += \"Guillaume Fraux <guillaume@fraux.fr>\\n\\n\";\n    options_str += std::string(OPTIONS);\n    auto args = docopt::docopt(options_str, {argv, argv + argc}, true, \"\");\n\n    Elastic::Options options;\n    options.trajectory = args.at(\"<trajectory>\").asString();\n\n    if (args[\"--temperature\"]) {\n        options.temperature = string2double(args.at(\"--temperature\").asString());\n    } else {\n        throw CFilesError(\"missing --temperature argument\");\n    }\n\n    if (args.at(\"--steps\")) {\n        options.steps = steps_range::parse(args.at(\"--steps\").asString());\n    }\n\n    if (args[\"--output\"]) {\n        options.outfile = args.at(\"--output\").asString();\n    } else {\n        options.outfile = options.trajectory + \".elastic.dat\";\n    }\n\n    return options;\n}\n\nstd::string Elastic::description() const {\n    return \"compute elastic constants from unit cell fluctuations in NPT\";\n}\n\nint Elastic::run(int argc, const char* argv[]) {\n    auto options = parse_options(argc, argv);\n    auto cells = std::vector<Matrix3D>();\n\n    auto trajectory = Trajectory(options.trajectory, 'r', options.format);\n    for (auto step: options.steps) {\n        if (step >= trajectory.nsteps()) {\n            break;\n        }\n        auto frame = trajectory.read_step(step);\n        cells.emplace_back(frame.cell().matrix());\n    }\n\n    // Use the avrerage as the reference state\n    auto reference = Matrix3D::zero();\n    for (auto& cell: cells) {\n        reference += cell.invert();\n    }\n    reference /= cells.size();\n    auto reference_t = reference.transpose();\n\n    auto epsilons = std::vector<Matrix3D>();\n    epsilons.reserve(cells.size());\n    for (auto& cell: cells) {\n        epsilons.emplace_back(0.5 * (reference_t * cell.transpose() * cell * reference - Matrix3D::unit()));\n    }\n\n    // in GPa A^2 / K\n    auto BOLTZMANN = 1.38065e-2;\n    auto volume_inv = reference.determinant();\n    auto v_kt = 1.0 / (volume_inv * BOLTZMANN * options.temperature);\n    auto compute = [&](size_t ij[2], size_t kl[2]) {\n        auto i = ij[0];\n        auto j = ij[1];\n        auto k = kl[0];\n        auto l = kl[1];\n\n        // Multiplicative factors for cross terms yz xz xy\n        double factor = 1.0;\n        if (i != j) {\n            factor *= 2;\n        }\n        if (k != l) {\n            factor *= 2;\n        }\n\n        double eij = 0;\n        double ekl = 0;\n        double eij_ekl = 0;\n        for (auto& epsilon: epsilons) {\n            eij += epsilon[i][j];\n            ekl += epsilon[k][l];\n            eij_ekl += epsilon[i][j] * epsilon[k][l];\n        }\n        eij /= epsilons.size();\n        ekl /= epsilons.size();\n        eij_ekl /= epsilons.size();\n\n        return factor * v_kt * (eij_ekl - eij * ekl);\n    };\n\n    auto SVoigt = Matrix6();\n    for (size_t i=0; i<6; i++) {\n        for (size_t j=0; j<=i; j++) {\n            SVoigt(i, j) = compute(CARTESIAN_TO_VOIGT[i], CARTESIAN_TO_VOIGT[j]);\n        }\n    }\n    // Make the matrix symetric\n    for (size_t i=0; i<6; i++) {\n        for (size_t j=i+1; j<6; j++) {\n            SVoigt(i, j) = SVoigt(j, i);\n        }\n    }\n\n    if (std::abs(SVoigt.determinant()) < 100 * DBL_EPSILON) {\n        throw CFilesError(\"the compliance matrix is not invertible\");\n    }\n\n    auto CVoigt = SVoigt.inverse();\n    std::ofstream outfile(options.outfile, std::ios::out);\n    if (!outfile.is_open()) {\n        throw CFilesError(\"Could not open the '\" + options.outfile + \"' file.\");\n    }\n\n    fmt::print(outfile, \"# stiffness tensor in GPa from {}\\n\", options.trajectory);\n    for (size_t i=0; i<6; i++) {\n        for (size_t j=0; j<6; j++) {\n            if (j != 0) {\n                fmt::print(outfile, \" \");\n            }\n            if (j >= i) {\n                fmt::print(outfile, \"{:12.5f}\", CVoigt(i, j));\n            } else {\n                fmt::print(outfile, \"            \");\n            }\n        }\n        fmt::print(outfile, \"\\n\");\n    }\n\n    auto eigenvalues = CVoigt.eigenvalues();\n    auto sorter = [](std::complex<double> i, std::complex<double> j) {\n        return std::abs(i) < std::abs(j);\n    };\n    std::sort(eigenvalues.data(), eigenvalues.data() + eigenvalues.size(), sorter);\n    fmt::print(outfile, \"# eigen values of the stiffness tensor (GPa)\\n\");\n    for (size_t i=0; i<6; i++) {\n        auto& value = eigenvalues(i);\n        if (value.imag() == 0) {\n            fmt::print(outfile, \"{:12.5f}\\n\", value.real());\n        } else {\n            fmt::print(outfile, \"{:12.5f} + {:12.5f}i\\n\", value.real(), value.imag());\n        }\n    }\n\n    double A = (CVoigt(0, 0) + CVoigt(1, 1) + CVoigt(2, 2)) / 3.0;\n    double B = (CVoigt(1, 2) + CVoigt(0, 2) + CVoigt(0, 1)) / 3.0;\n    double C = (CVoigt(3, 3) + CVoigt(4, 4) + CVoigt(5, 5)) / 3.0;\n\n    double a = (SVoigt(0, 0) + SVoigt(1, 1) + SVoigt(2, 2)) / 3.0;\n    double b = (SVoigt(1, 2) + SVoigt(0, 2) + SVoigt(0, 1)) / 3.0;\n    double c = (SVoigt(3, 3) + SVoigt(4, 4) + SVoigt(5, 5)) / 3.0;\n\n    double KV = (A + 2.0 * B) / 3.0;\n    double GV = (A - B + 3.0 * C) / 5.0;\n    double YV = 1.0 / (1.0 / (3.0 * GV) + 1.0 / (9.0 * KV));\n    double PV = (1.0 - 3.0 * GV / (3.0 * KV + GV)) / 2.0;\n\n    double KR = 1.0 / (3.0 * a + 6.0 * b);\n    double GR = 5.0 / (4.0 * a - 4.0 * b + 3.0 * c);\n    double YR = 1.0 / (1.0 / (3.0 * GR) + 1.0 / (9.0 * KR));\n    double PR = (1.0 - 3.0 * GR / (3.0 * KR + GR)) / 2.0;\n\n    double KH = (KV + KR) / 2.0;\n    double GH = (GV + GR) / 2.0;\n    double YH = 1.0 / (1.0 / (3.0 * GH) + 1.0 / (9.0 * KH));\n    double PH = (1.0 - 3.0 * GH / (3.0 * KH + GH)) / 2.0;\n\n    fmt::print(outfile, \"# Bulk modulus (GPa) | Young's modulus (GPa) | Shear modulus (GPa) | Poisson's ratio\\n\");\n    fmt::print(outfile, \"# Voigt averaging\\n\");\n    fmt::print(outfile, \"{:12.5f} {:12.5f} {:12.5f} {:12.5f}\\n\", KV, YV, GV, PV);\n    fmt::print(outfile, \"# Reuss averaging\\n\");\n    fmt::print(outfile, \"{:12.5f} {:12.5f} {:12.5f} {:12.5f}\\n\", KR, YR, GR, PR);\n    fmt::print(outfile, \"# Hill averaging\\n\");\n    fmt::print(outfile, \"{:12.5f} {:12.5f} {:12.5f} {:12.5f}\\n\", KH, YH, GH, PH);\n\n    return 0;\n}\n", "meta": {"hexsha": "84c12d15470fcfa71bd6554f2c1fb2b7f043ccad", "size": 8263, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/commands/Elastic.cpp", "max_stars_repo_name": "Luthaf/chrp", "max_stars_repo_head_hexsha": "73c4aa76bc8e7154001fad819a2ad5a0b2663a60", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-12-03T20:32:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T16:32:49.000Z", "max_issues_repo_path": "src/commands/Elastic.cpp", "max_issues_repo_name": "Luthaf/chrp", "max_issues_repo_head_hexsha": "73c4aa76bc8e7154001fad819a2ad5a0b2663a60", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2016-03-04T14:25:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-22T16:48:42.000Z", "max_forks_repo_path": "src/commands/Elastic.cpp", "max_forks_repo_name": "Luthaf/chrp", "max_forks_repo_head_hexsha": "73c4aa76bc8e7154001fad819a2ad5a0b2663a60", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-03-07T20:42:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-23T06:50:40.000Z", "avg_line_length": 35.0127118644, "max_line_length": 114, "alphanum_fraction": 0.5425390294, "num_tokens": 2539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.54654204954134}}
{"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_PI_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_PI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate value \\f$\\pi\\f$ that is the half length of a circle of radius one\n    ... in normal temperature and pressure conditions.\n\n\n    @par Header <boost/simd/constant/pi.hpp>\n\n    @par Semantic:\n\n    @code\n    T r = Pi<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = T(4*atan(1));\n    @endcode\n\n    @return The Pi constant for the proper type\n  **/\n  template<typename T> T Pi();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant pi.\n\n      @return The Pi constant for the proper type\n    **/\n    Value Pi();\n  }\n} }\n#endif\n\n#include <boost/simd/constant/scalar/pi.hpp>\n#include <boost/simd/constant/simd/pi.hpp>\n\n#endif\n", "meta": {"hexsha": "0f4d505227d83d8b5925584bae0f93fadaca5a4b", "size": 1270, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/pi.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "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/pi.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "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/pi.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 21.5254237288, "max_line_length": 100, "alphanum_fraction": 0.5637795276, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5465420326428602}}
{"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 INTERP__BSPLINE_HPP_\n#define INTERP__BSPLINE_HPP_\n\n/**\n * @file\n * @brief B-splines on Lie groups.\n */\n\n#include <ranges>\n\n#include <Eigen/Sparse>\n\n#include \"smooth/concepts.hpp\"\n#include \"smooth/internal/utils.hpp\"\n#include \"smooth/manifold_vector.hpp\"\n#include \"smooth/optim.hpp\"\n\n#include \"common.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief Cardinal Bspline on a Lie group\n *\n * The curve is defined by\n * \\f[\n *  g(t) = g_0 * \\exp(\\tilde B_1(t) v_1) * ... \\exp(\\tilde B_N(t) v_N)\n * \\f]\n * where \\f$\\tilde B_i(t)\\f$ are cumulative Bspline basis functions and\n * \\f$v_i = g_i \\ominus g_{i-1}\\f$ are the control point differences.\n * The control points - knot time correspondence is as follows\n *\n \\verbatim\n KNOT  -K  -K+1   -K+2  ...    0    1   ...  N-K\n CTRL   0     1      2  ...    K  K+1          N\n                               ^               ^\n                             t_min           t_max\n \\endverbatim\n *\n * The first K ctrl_pts are exterior points and are outside\n * the support of the spline, which means that the spline is defined on\n * \\f$ [t_{min}, t_{max}] = [t0, (N-K)*dt] \\f$.\n *\n * For interpolation purposes use an odd spline degree and set\n \\verbatim\n t0 = (timestamp of first control point) + dt*(K-1)/2\n \\endverbatim\n * which aligns control points with the maximum of the corresponding\n * basis function.\n */\ntemplate<std::size_t K, LieGroup G>\nclass BSpline\n{\npublic:\n  /**\n   * @brief Construct a constant bspline defined on [0, 1) equal to identity.\n   */\n  BSpline() : t0_(0), dt_(1), ctrl_pts_(K + 1, G::Identity()) {}\n\n  /**\n   * @brief Create a BSpline\n   * @param t0 start of spline\n   * @param dt distance between spline knots\n   * @param ctrl_pts spline control points\n   */\n  BSpline(double t0, double dt, std::vector<G, Eigen::aligned_allocator<G>> && ctrl_pts)\n      : t0_(t0), dt_(dt), ctrl_pts_(std::move(ctrl_pts))\n  {}\n\n  /**\n   * @brief Create a BSpline\n   * @tparam R range type\n   * @param t0 start of spline\n   * @param dt distance between spline knots\n   * @param ctrl_pts spline control points\n   */\n  template<std::ranges::range R>\n  BSpline(double t0, double dt, const R & ctrl_pts)\n      : t0_(t0), dt_(dt), ctrl_pts_(std::ranges::begin(ctrl_pts), std::ranges::end(ctrl_pts))\n  {}\n\n  /// @brief Copy constructor\n  BSpline(const BSpline &) = default;\n  /// @brief Move constructor\n  BSpline(BSpline &&) = default;\n  /// @brief Copy assignment\n  BSpline & operator=(const BSpline &) = default;\n  /// @brief Move assignment\n  BSpline & operator=(BSpline &&) = default;\n  /// @brief Descructor\n  ~BSpline() = default;\n\n  /**\n   * @brief Distance between knots\n   */\n  double dt() const { return dt_; }\n\n  /**\n   * @brief Minimal time for which spline is defined.\n   */\n  double t_min() const { return t0_; }\n\n  /**\n   * @brief Maximal time for which spline is defined.\n   */\n  double t_max() const { return t0_ + (ctrl_pts_.size() - K) * dt_; }\n\n  /**\n   * @brief Access spline control points.\n   */\n  const std::vector<G, Eigen::aligned_allocator<G>> & ctrl_pts() const { return ctrl_pts_; }\n\n  /**\n   * @brief Evaluate Bspline.\n   *\n   * @param[in] t time point to evaluate at\n   * @param[out] vel output body velocity at evaluation time\n   * @param[out] acc output body acceleration at evaluation time\n   * @return spline value at time t\n   *\n   * @note Input \\p t is clamped to spline interval of definition\n   */\n  G eval(double t, detail::OptTangent<G> vel = {}, detail::OptTangent<G> acc = {}) const\n  {\n    // index of relevant interval\n    int64_t istar = static_cast<int64_t>((t - t0_) / dt_);\n\n    double u;\n    // clamp to end of range if necessary\n    if (istar < 0) {\n      istar = 0;\n      u     = 0;\n    } else if (istar + K + 1 > ctrl_pts_.size()) {\n      istar = ctrl_pts_.size() - K - 1;\n      u     = 1;\n    } else {\n      u = (t - t0_ - istar * dt_) / dt_;\n    }\n\n    constexpr auto Mstatic = detail::cum_coefmat<CSplineType::BSPLINE, double, K>().transpose();\n    Eigen::Map<const Eigen::Matrix<double, K + 1, K + 1, Eigen::RowMajor>> M(Mstatic[0].data());\n\n    G g = cspline_eval<K, G>(\n      ctrl_pts_ | std::views::drop(istar) | std::views::take(K + 1), M, u, vel, acc);\n\n    if (vel.has_value()) { vel.value() /= dt_; }\n    if (acc.has_value()) { acc.value() /= (dt_ * dt_); }\n\n    return g;\n  }\n\nprivate:\n  double t0_, dt_;\n  std::vector<G, Eigen::aligned_allocator<G>> ctrl_pts_;\n};\n\n/**\n * @brief Fit a bpsline to data points \\f$(t_i, g_i)\\f$\n *        by solving the optimization problem\n *\n * \\f[\n *   \\min_{p}  \\left\\| p(t_i) - g_i \\right\\|^2\n * \\f]\n *\n * @tparam K bspline degree\n * @tparam Rt, Rg input range types\n * @param tt time values t_i (doubles, non-decreasing)\n * @param gg data values t_i\n * @param dt distance between spline control points\n */\ntemplate<std::size_t K, std::ranges::range Rt, std::ranges::range Rg>\nBSpline<K, std::ranges::range_value_t<Rg>> fit_bspline(const Rt & tt, const Rg & gg, double dt)\n{\n  static_assert(LieGroup<std::ranges::range_value_t<Rg>>, \"Rg value type is LieGroup\");\n  static_assert(std::is_same_v<std::ranges::range_value_t<Rt>, double>, \"Rt value type is double\");\n\n  using G = std::ranges::range_value_t<Rg>;\n\n  auto [tmin_ptr, tmax_ptr] = std::minmax_element(std::ranges::begin(tt), std::ranges::end(tt));\n\n  const double t0 = *tmin_ptr;\n  const double t1 = *tmax_ptr;\n\n  const std::size_t NumData = std::min(std::ranges::size(tt), std::ranges::size(gg));\n  const std::size_t NumPts  = K + static_cast<std::size_t>((t1 - t0 + dt) / dt);\n\n  constexpr auto Mstatic = detail::cum_coefmat<CSplineType::BSPLINE, double, K>().transpose();\n  Eigen::Map<const Eigen::Matrix<double, K + 1, K + 1, Eigen::RowMajor>> M(Mstatic[0].data());\n\n  auto f = [&](const auto & var) {\n    Eigen::VectorXd ret(G::Dof * NumData);\n\n    Eigen::SparseMatrix<double, Eigen::RowMajor> Jac;\n    Jac.resize(G::Dof * NumData, G::Dof * NumPts);\n    Jac.reserve(Eigen::Matrix<int, -1, 1>::Constant(G::Dof * NumData, G::Dof * (K + 1)));\n\n    auto t_iter = std::ranges::begin(tt);\n    auto g_iter = std::ranges::begin(gg);\n\n    for (auto i = 0u; i != NumData; ++t_iter, ++g_iter, ++i) {\n      const int64_t istar = static_cast<int64_t>((*t_iter - t0) / dt);\n      const double u      = (*t_iter - t0 - istar * dt) / dt;\n\n      Eigen::Matrix<double, G::Dof, (K + 1) * G::Dof> d_vali_pts;\n      auto g_spline = cspline_eval<K, G>(\n        var | std::views::drop(istar) | std::views::take(K + 1), M, u, {}, {}, d_vali_pts);\n\n      const typename G::Tangent resi = g_spline - *g_iter;\n\n      ret.segment<G::Dof>(i * G::Dof) = resi;\n\n      const Eigen::Matrix<double, G::Dof, G::Dof> d_resi_vali          = G::dr_expinv(resi);\n      const Eigen::Matrix<double, G::Dof, (K + 1) * G::Dof> d_resi_pts = d_resi_vali * d_vali_pts;\n\n      for (auto r = 0u; r != G::Dof; ++r) {\n        for (auto c = 0u; c != G::Dof * (K + 1); ++c) {\n          Jac.insert(i * G::Dof + r, istar * G::Dof + c) = d_resi_pts(r, c);\n        }\n      }\n    }\n\n    Jac.makeCompressed();\n\n    return std::make_pair(std::move(ret), Eigen::MatrixXd(Jac));\n  };\n\n  // create optimization variable\n  ManifoldVector<G, Eigen::aligned_allocator> ctrl_pts(NumPts);\n\n  // create initial guess\n  auto t_iter = std::ranges::begin(tt);\n  auto g_iter = std::ranges::begin(gg);\n  for (auto i = 0u; i != NumPts; ++i) {\n    const double t_target = t0 + (i - static_cast<double>(K - 1) / 2) * dt;\n    while (t_iter + 1 < std::ranges::end(tt)\n           && std::abs(t_target - *(t_iter + 1)) < std::abs(t_target - *t_iter)) {\n      ++t_iter;\n      ++g_iter;\n    }\n    ctrl_pts[i] = *g_iter;\n  }\n\n  // fit to data with loose convergence criteria\n  MinimizeOptions opts;\n  opts.ftol     = 1e-3;\n  opts.ptol     = 1e-3;\n  opts.max_iter = 10;\n  minimize<diff::Type::ANALYTIC>(f, smooth::wrt(ctrl_pts), opts);\n\n  return BSpline<K, G>(t0, dt, std::move(ctrl_pts));\n}\n\n}  // namespace smooth\n\n#endif  // INTERP__BSPLINE_HPP_\n", "meta": {"hexsha": "e3db6a5745fb69e6cb87024ea302da1e518464e2", "size": 9131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/spline/bspline.hpp", "max_stars_repo_name": "NamDinhRobotics/smooth", "max_stars_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:18.000Z", "max_issues_repo_path": "include/smooth/spline/bspline.hpp", "max_issues_repo_name": "NamDinhRobotics/smooth", "max_issues_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_issues_repo_licenses": ["MIT"], "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/spline/bspline.hpp", "max_forks_repo_name": "NamDinhRobotics/smooth", "max_forks_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_forks_repo_licenses": ["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.4946619217, "max_line_length": 99, "alphanum_fraction": 0.6316942285, "num_tokens": 2730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5465313416475428}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// orientation_tests.cpp\n//\n//  Copyright 2021 Brandon Kohn. 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 <gtest/gtest.h>\n#include <gmock/gmock.h>\n#include \"./2d_kernel_fixture.hpp\"\n#include \"./3d_kernel_fixture.hpp\"\n#include \"./3d_kernel_units_fixture.hpp\"\n\n#include <geometrix/algorithm/orientation.hpp>\n#include <geometrix/algorithm/distance/point_line_distance.hpp>\n\n#include <geometrix/utility/utilities.hpp>\n#include <geometrix/utility/scope_timer.ipp>\n\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/algorithm/copy.hpp>\n#include <boost/range/algorithm_ext/erase.hpp>\n\n#include <exception>\n#include <iostream>\n\n//! Google tests\nTEST_F(geometry_kernel_2d_fixture, point_line_orientation_point_is_right_and_far_returns_right)\n{\n    using namespace geometrix;\n\n    auto p1 = point2 { 0., 0. };\n    auto p2 = point2 { 4., 4. };\n    auto l = make_line(p1, p2);\n    auto seg = make_segment(p1, p2);\n    auto p = point2 { 1.0, 0.0 };\n    auto r = point_line_distance(p, l) - 0.1;\n    auto c = circle2 { p, r };\n    auto o = circle_line_orientation(c, l, cmp);\n    \n    EXPECT_EQ(o, oriented_right);\n}\n\nTEST_F(geometry_kernel_2d_fixture, point_line_orientation_point_is_left_and_far_returns_left)\n{\n    using namespace geometrix;\n\n    auto p1 = point2 { 0., 0. };\n    auto p2 = point2 { 4., 4. };\n    auto l = make_line(p1, p2);\n    auto seg = make_segment(p1, p2);\n    auto p = point2 { 1.0, 1.5 };\n    auto r = point_line_distance(p, l) - 0.1;\n    auto c = circle2 { p, r };\n    auto o = circle_line_orientation(c, l, cmp);\n    \n    EXPECT_EQ(o, oriented_left);\n}\n\nTEST_F(geometry_kernel_2d_fixture, point_line_orientation_point_is_right_and_near_returns_collinear)\n{\n    using namespace geometrix;\n\n    auto p1 = point2 { 0., 0. };\n    auto p2 = point2 { 4., 4. };\n    auto l = make_line(p1, p2);\n    auto seg = make_segment(p1, p2);\n    auto p = point2 { 1.0, 0.0 };\n    auto r = point_line_distance(p, l) + 0.1;\n    auto c = circle2 { p, r };\n    auto o = circle_line_orientation(c, l, cmp);\n\n    EXPECT_EQ(o, oriented_collinear);\n}\n\n#include <geometrix/algorithm/orientation.hpp>\n\nTEST_F(geometry_kernel_2d_fixture, circle_polyline_orientation_corner_test_point_right)\n{\n    using namespace geometrix;\n    auto pline = polyline2 { { 0.0, 0.0 }, { 1.0, 0.0 }, { 1.0, 1.0 }, { 0.0, 1.0 } };\n    point2 p = pline[2] + 1.0 * normalize(vector2 { 1.0, 1.0 });\n    auto r = 0.5;\n    auto c = circle2 { p, r };\n    auto result = circle_polyline_orientation(c, pline, cmp);\n    EXPECT_EQ(result, oriented_right);\n}\n\nTEST_F(geometry_kernel_2d_fixture, circle_polyline_orientation_corner_test_point_overlaps_collinear)\n{\n    using namespace geometrix;\n    auto pline = polyline2 { { 0.0, 0.0 }, { 1.0, 0.0 }, { 1.0, 1.0 }, { 0.0, 1.0 } };\n    point2 p = pline[2] + 1.0 * normalize(vector2 { 1.0, 1.0 });\n    auto r = 1.5;\n    auto c = circle2 { p, r };\n    auto result = circle_polyline_orientation(c, pline, cmp);\n    EXPECT_EQ(result, oriented_collinear);\n}\n\nTEST_F(geometry_kernel_2d_fixture, point_segment_orientation_point_is_right)\n{\n    using namespace geometrix;\n    auto seg = segment2{ { 0.0, 0.0 }, { 4.0, 4.0 } };\n    auto p = point2{ 1.0, 0.0 };\n    auto result = point_segment_orientation(p, seg, cmp);\n    auto result2 = point_segment_orientation(p, seg.get_start(), seg.get_end(), cmp);\n    EXPECT_EQ(result, oriented_right);\n    EXPECT_EQ(result2, oriented_right);\n}\n\nTEST_F(geometry_kernel_2d_fixture, point_segment_orientation_point_is_left)\n{\n    using namespace geometrix;\n    auto seg = segment2{ { 0.0, 0.0 }, { 4.0, 4.0 } };\n    auto p = point2{ 1.0, 2.0 };\n    auto result = point_segment_orientation(p, seg, cmp);\n    auto result2 = point_segment_orientation(p, seg.get_start(), seg.get_end(), cmp);\n    EXPECT_EQ(result, oriented_left);\n    EXPECT_EQ(result2, oriented_left);\n}\n\nTEST_F(geometry_kernel_2d_fixture, point_segment_orientation_point_is_collinear)\n{\n    using namespace geometrix;\n    auto seg = segment2{ { 0.0, 0.0 }, { 4.0, 4.0 } };\n    auto p = point2{ 1.0, 1.0 };\n    auto result = point_segment_orientation(p, seg, cmp);\n    auto result2 = point_segment_orientation(p, seg.get_start(), seg.get_end(), cmp);\n    EXPECT_EQ(result, oriented_collinear);\n    EXPECT_EQ(result2, oriented_collinear);\n}\n\nTEST_F(geometry_kernel_3d_fixture, collinear_test_3d_points_true)\n{\n    using namespace geometrix;\n\tauto a = point3{ 0.0, 0.0, 0.0 };\n\tauto b = point3{ 1.0, 1.0, 1.0 };\n\tauto c = point3{ 2.0, 2.0, 2.0 };\n\n    auto o = is_collinear( c, a, b, cmp );\n\tEXPECT_TRUE( o );\n}\n\nTEST_F(geometry_kernel_3d_fixture, collinear_test_3d_points_false)\n{\n    using namespace geometrix;\n\tauto a = point3{ 0.0, 0.0, 0.0 };\n\tauto b = point3{ 1.0, 1.0, 1.0 };\n\tauto c = point3{ 2.0, 2.0, 0.0 };\n\n    auto o = is_collinear( c, a, b, cmp );\n\tEXPECT_FALSE( o );\n}\n\nTEST_F(geometry_kernel_3d_units_fixture, collinear_test_3d_points_false)\n{\n    using namespace geometrix;\n\tauto a = point3{ 0.0 * boost::units::si::meters, 0.0 * boost::units::si::meters, 0.0 * boost::units::si::meters };\n\tauto b = point3{ 1.0 * boost::units::si::meters, 1.0 * boost::units::si::meters, 1.0 * boost::units::si::meters };\n\tauto c = point3{ 2.0 * boost::units::si::meters, 2.0 * boost::units::si::meters, 0.0 * boost::units::si::meters };\n\n    auto o = is_collinear( c, a, b, cmp );\n\tEXPECT_FALSE( o );\n}\n\nTEST_F(geometry_kernel_3d_units_fixture, collinear_test_3d_points_true_all_same)\n{\n    using namespace geometrix;\n\tauto a = point3{ 1.0 * boost::units::si::meters, 0.0 * boost::units::si::meters, 0.0 * boost::units::si::meters };\n\tauto b = point3{ 1.0 * boost::units::si::meters, 0.0 * boost::units::si::meters, 0.0 * boost::units::si::meters };\n\tauto c = point3{ 1.0 * boost::units::si::meters, 0.0 * boost::units::si::meters, 0.0 * boost::units::si::meters };\n\n    auto o = is_collinear( c, a, b, cmp );\n\tEXPECT_TRUE( o );\n}\n", "meta": {"hexsha": "0932991e19591f1edc759d50e4fefdff64791a80", "size": 6047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geometry_test/orientation_tests.cpp", "max_stars_repo_name": "brandon-kohn/Geometrix", "max_stars_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometry_test/orientation_tests.cpp", "max_issues_repo_name": "brandon-kohn/Geometrix", "max_issues_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometry_test/orientation_tests.cpp", "max_forks_repo_name": "brandon-kohn/Geometrix", "max_forks_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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.3579545455, "max_line_length": 115, "alphanum_fraction": 0.6652885728, "num_tokens": 1936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5465313416475428}}
{"text": "/** \\file   cmr_time_stamp.h\n    \\brief  Implement functionalities to handle cardiac time stamps\n    \\author Hui Xue\n*/\n\n#include \"cmr_time_stamp.h\"\n#include \"hoNDArray_reductions.h\"\n#include \"hoNDArray_elemwise.h\"\n#include <boost/math/special_functions/sign.hpp>\n\nnamespace Gadgetron { \n\n    template <typename T> \n    void simple_line_fit(const std::vector<T>& x, const std::vector<T>& y, T& a, T& b)\n    {\n        try\n        {\n            size_t num = x.size();\n\n            if(num<2)\n            {\n                a = 0;\n                b = 0;\n                return;\n            }\n\n            T sx(0), sy(0);\n\n            size_t n;\n            for (n=0; n<num; n++)\n            {\n                sx += x[n];\n                sy += y[n];\n            }\n\n            T mx = sx / (T)(num);\n            T syy = 0;\n            b = 0;\n            for (n=0; n<num; n++)\n            {\n                T v = (x[n] - mx);\n                syy += v*v;\n                b += v*y[n];\n            }\n\n            syy = (std::abs(syy) > 0 ? syy : boost::math::sign(syy)*FLT_EPSILON);\n            b /= syy;\n            a = (sy - sx*b) / (T)(num);\n        }\n        catch(...)\n        {\n            GADGET_THROW(\"Exceptions happened in simple_line_fit ... \");\n        }\n    }\n\n    void correct_time_stamp_with_fitting(hoNDArray<float>& time_stamp, size_t startE1, size_t endE1)\n    {\n        try\n        {\n            size_t E1 = time_stamp.get_size(0);\n            size_t N = time_stamp.get_size(1);\n            size_t rE1 = endE1 - startE1 + 1;\n\n            size_t e1, n;\n\n            size_t num_acq_read_outs = 0;\n            for ( n=0; n<N; n++ )\n            {\n                for ( e1=0; e1<E1; e1++ )\n                {\n                    if ( time_stamp(e1, n) > 0 )\n                    {\n                        num_acq_read_outs++;\n                    }\n                }\n            }\n\n            GDEBUG_STREAM(\" Number of acquired lines : \" << num_acq_read_outs);\n\n            float a, b; // y = a + b*x\n            {\n                std::vector<float> x(num_acq_read_outs), y(num_acq_read_outs);\n\n                size_t ind = 0;\n                for ( n=0; n<N; n++ )\n                {\n                    for ( e1=startE1; e1<=endE1; e1++ )\n                    {\n                        float acq_time = time_stamp(e1, n);\n                        if ( acq_time > 0 )\n                        {\n                            x[ind] = (float)(e1-startE1 + n*rE1);\n                            y[ind] = acq_time;\n                            ind++;\n                        }\n                    }\n                }\n\n                Gadgetron::simple_line_fit(x, y, a, b);\n            }\n\n            for ( n=0; n<N; n++ )\n            {\n                for ( e1=startE1; e1<=endE1; e1++ )\n                {\n                    float x_v = (float)(e1-startE1 + n*rE1);\n                    time_stamp(e1, n) = a + b*x_v;\n                }\n            }\n        }\n        catch(...)\n        {\n            GADGET_THROW(\"Exceptions happened in correct_time_stamp_with_fitting(...) ... \");\n        }\n    }\n\n    void detect_heart_beat_with_time_stamp(hoNDArray<float>& cpt_time_stamp, hoNDArray<int>& ind_hb, \n                                        std::vector<size_t>& start_e1_hb, std::vector<size_t>& end_e1_hb, \n                                        std::vector<size_t>& start_n_hb, std::vector<size_t>& end_n_hb )\n    {\n        try\n        {\n            size_t E1 = cpt_time_stamp.get_size(0);\n            size_t N = cpt_time_stamp.get_size(1);\n\n            size_t e1, n, ind, ii;\n\n            size_t num_acq_read_outs = 0;\n            for ( n=0; n<N; n++ )\n            {\n                for ( e1=0; e1<E1; e1++ )\n                {\n                    if ( cpt_time_stamp(e1, n) >= 0 )\n                    {\n                        num_acq_read_outs++;\n                    }\n                }\n            }\n\n            ind_hb.create(E1, N);\n            Gadgetron::clear(ind_hb);\n\n            // --------------------------------------------------------\n            // cpt time stamps\n            // --------------------------------------------------------\n\n            std::vector<float> acquired_cpt(num_acq_read_outs);\n            std::vector<size_t> ind_acquired_cpt(num_acq_read_outs);\n\n            ind = 0;\n            for ( n=0; n<N; n++ )\n            {\n                for ( e1=0; e1<E1; e1++ )\n                {\n                    if ( cpt_time_stamp(e1, n) > -1 )\n                    {\n                        acquired_cpt[ind] = cpt_time_stamp(e1, n);\n                        ind_acquired_cpt[ind] = e1 + n*E1;\n                        ind++;\n                    }\n                }\n            }\n\n            // --------------------------------------------------------\n            // find the number of heart beats\n            // --------------------------------------------------------\n            size_t numOfHB = 0;\n\n            // store the line indexes for every heart beat\n            std::vector<size_t> ind_HB_start, ind_HB_end;\n            ind_HB_start.push_back(0);\n\n            for ( ind=1; ind<num_acq_read_outs; ind++ )\n            {\n                if ( acquired_cpt[ind] < acquired_cpt[ind-1] )\n                {\n                    // find a new heart beat\n                    numOfHB++;\n\n                    size_t end_ind_prev_HB = ind_acquired_cpt[ind-1];\n                    size_t start_ind_curr_HB = ind_acquired_cpt[ind];\n\n                    // if there is a gap between end and start ind, fill the gap\n                    if ( end_ind_prev_HB+1 != start_ind_curr_HB )\n                    {\n                        long long gap = start_ind_curr_HB - end_ind_prev_HB - 1;\n                        if ( gap % 2 == 0 )\n                        {\n                            end_ind_prev_HB += gap;\n                        }\n                        else\n                        {\n                            end_ind_prev_HB += gap;\n                        }\n\n                        if ( end_ind_prev_HB+1 != start_ind_curr_HB )\n                        {\n                            GWARN_STREAM(\"end_ind_prev_HB+1 ~= start_ind_curr_HB : \" << end_ind_prev_HB << \" \" << start_ind_curr_HB);\n                        }\n                    }\n\n                    ind_HB_end.push_back( end_ind_prev_HB );\n                    ind_HB_start.push_back( start_ind_curr_HB );\n                }\n            }\n\n            ind_HB_end.push_back( E1*N-1 );\n            numOfHB = ind_HB_end.size();\n\n            // --------------------------------------------------------\n            // fill the start and end indexes\n            // --------------------------------------------------------\n            start_e1_hb.resize(numOfHB, 0);\n            end_e1_hb.resize(numOfHB, 0);\n\n            start_n_hb.resize(numOfHB, 0);\n            end_n_hb.resize(numOfHB, 0);\n\n            std::vector<size_t> start, end;\n            for ( ii=0; ii<numOfHB; ii++ )\n            {\n                start_n_hb[ii] = ind_HB_start[ii] / E1;\n                start_e1_hb[ii] = ind_HB_start[ii] - start_n_hb[ii] * E1;\n\n                end_n_hb[ii] = ind_HB_end[ii] / E1;\n                end_e1_hb[ii] = ind_HB_end[ii] - end_n_hb[ii]*E1;\n\n                for (ind=ind_HB_start[ii]; ind<=ind_HB_end[ii]; ind++)\n                {\n                    ind_hb(ind) = ii;\n                }\n            }\n        }\n        catch(...)\n        {\n            GADGET_THROW(\"Exceptions happened in detect_heart_beat_with_time_stamp(...) ... \");\n        }\n    }\n\n    void correct_heart_beat_time_stamp_with_fitting(hoNDArray<float>& cpt_time_stamp, hoNDArray<int>& ind_hb, size_t startE1, size_t endE1, \n                                                const std::vector<size_t>& start_e1_hb, const std::vector<size_t>& end_e1_hb, \n                                                const std::vector<size_t>& start_n_hb, const std::vector<size_t>& end_n_hb )\n    {\n        try\n        {\n            size_t E1 = cpt_time_stamp.get_size(0);\n            size_t N = cpt_time_stamp.get_size(1);\n            size_t rE1 = endE1-startE1+1;\n\n            size_t e1, n, ind, ii;\n\n            size_t num_acq_read_outs = 0;\n            for ( n=0; n<N; n++ )\n            {\n                for ( e1=0; e1<E1; e1++ )\n                {\n                    if ( cpt_time_stamp(e1, n) >= 0 )\n                    {\n                        num_acq_read_outs++;\n                    }\n                }\n            }\n\n            size_t numOfHB = start_e1_hb.size();\n\n            std::vector<size_t> ind_HB_start(numOfHB);\n            std::vector<size_t> ind_HB_end(numOfHB);\n\n            for ( ind=0; ind<numOfHB; ind++ )\n            {\n                ind_HB_start[ind] = start_e1_hb[ind] + start_n_hb[ind] * E1;\n                ind_HB_end[ind] = end_e1_hb[ind] + end_n_hb[ind] * E1;\n            }\n\n            // --------------------------------------------------------\n            // fit a line to every heart beat\n            // --------------------------------------------------------\n            float a, b;\n            std::vector<float> A(numOfHB, 0.0f), B(numOfHB, 0.0f);\n            for ( ind=0; ind<numOfHB; ind++ )\n            {\n                std::vector<float> x, y;\n\n                size_t cpt;\n                for ( cpt=ind_HB_start[ind]; cpt<=ind_HB_end[ind]; cpt++ )\n                {\n                    size_t n = cpt / E1;\n                    size_t e1 = cpt - n*E1;\n\n                    if(e1>=startE1 && e1<=endE1)\n                    {\n                        if ( cpt_time_stamp[cpt] > -1 )\n                        {\n                            size_t x_ind = (e1-startE1) + n*rE1;\n                            x.push_back( (float)x_ind );\n                            y.push_back(cpt_time_stamp[cpt]);\n                        }\n                    }\n                }\n\n                if ( !x.empty() )\n                {\n                    Gadgetron::simple_line_fit(x, y, a, b);\n                    A[ind] = a;\n                    B[ind] = b;\n                }\n            }\n\n            // --------------------------------------------------------\n            // compute cpt time stamp for every line\n            // --------------------------------------------------------\n            size_t num = cpt_time_stamp.get_number_of_elements();\n            for ( ind=0; ind<num; ind++ )\n            {\n                n = ind / E1;\n                e1 = ind - n*E1;\n\n                if(e1>=startE1 && e1<=endE1)\n                {\n                    // find to which heart beat this line belongs\n                    bool foundHB = false;\n                    for ( ii=0; ii<numOfHB; ii++ )\n                    {\n                        size_t startHB = ind_HB_start[ii];\n                        size_t endHB = ind_HB_end[ii];\n\n                        if ( ii==0 && ind<=startHB )\n                        {\n                            foundHB = true;\n                            break;\n                        }\n\n                        if ( ii==numOfHB-1 && ind>=endHB )\n                        {\n                            foundHB = true;\n                            break;\n                        }\n\n                        if ( ind>=startHB && ind<=endHB )\n                        {\n                            foundHB = true;\n                            break;\n                        }\n                    }\n\n                    // if cannot find a heart beat, this kspace line will not be used\n                    if ( foundHB && (std::abs(B[ii])>0) )\n                    {\n                        ind_hb(e1, n) = ii;\n\n                        size_t x_ind = (e1-startE1) + n*rE1;\n                        cpt_time_stamp(e1, n) = (float)(A[ii] + B[ii]*x_ind);\n                    }\n                    else\n                    {\n                        ind_hb(e1, n) = -1;\n                    }\n                }\n                else\n                {\n                    cpt_time_stamp(e1, n) = -1;\n                    ind_hb(e1, n) = -1;\n                }\n            }\n        }\n        catch(...)\n        {\n            GADGET_THROW(\"Exceptions happened in correct_heart_beat_time_stamp_with_fitting(...) ... \");\n        }\n    }\n\n    void compute_phase_time_stamp(const hoNDArray<float>& time_stamp, const hoNDArray<float>& cpt_time_stamp, size_t startE1, size_t endE1, \n        hoNDArray<float>& phs_time_stamp, hoNDArray<float>& phs_cpt_time_stamp)\n    {\n        try\n        {\n            size_t E1 = time_stamp.get_size(0);\n            size_t N = time_stamp.get_size(1);\n            size_t rE1 = endE1 - startE1 + 1;\n\n            size_t e1, n;\n\n            for ( n=0; n<N; n++ )\n            {\n                // phase time stamp as the mean of all aquired lines\n                size_t num = 0;\n                float tt = 0.0f;\n                for ( e1=startE1; e1<=endE1; e1++ )\n                {\n                    if(time_stamp(e1, n)>0)\n                    {\n                        tt += time_stamp(e1, n);\n                        num++;\n                    }\n                }\n                phs_time_stamp(n, 0) = tt/((num>0) ? num : 1);\n\n                //// phase cpt time as the median of all acquired lines\n                //std::vector<float> cpt_buf(rE1, 0);\n                //for ( e1=startE1; e1<=endE1; e1++ )\n                //{\n                //    if(cpt_time_stamp(e1, n)>=0)\n                //        cpt_buf[e1-startE1] = cpt_time_stamp(e1, n);\n                //}\n\n                //std::sort(cpt_buf.begin(), cpt_buf.end());\n                //phs_cpt_time_stamp(n, 0) = cpt_buf[E1/2-startE1];\n\n                // phase cpt time as the cpt time of center line\n                phs_cpt_time_stamp(n, 0) = cpt_time_stamp(E1/2, n);\n            }\n        }\n        catch(...)\n        {\n            GADGET_THROW(\"Exceptions happened in compute_phase_time_stamp(...) ... \");\n        }\n    }\n\n    template <typename T> \n    void resample_cardiac_phase_cmr_array(const hoNDArray<T>& data, size_t output_N, hoNDArray<T>& res, size_t spline_degree)\n    {\n        try\n        {\n            std::vector<size_t> dims;\n            data.get_dimensions(dims);\n\n            size_t num_of_dims = dims.size();\n\n            GADGET_CHECK_THROW(num_of_dims >=2);\n\n            size_t N = dims[num_of_dims -1];\n\n            GADGET_CHECK_THROW(N>2);\n\n            std::vector<size_t> dims_res(dims);\n            dims_res[num_of_dims - 1] = output_N;\n\n            res.create(dims_res);\n            Gadgetron::clear(res);\n\n            long long num = data.get_number_of_elements()/N;\n\n            long long n;\n\n#pragma omp parallel default(none) shared(N, output_N, num, data, res, spline_degree, num_of_dims) private (n)\n            {\n                hoNDArray<T> data_in(N);\n                hoNDArray<T> data_res(output_N);\n                hoNDArray<T> coeff(N);\n                hoNDBSpline< T, 1 > interp;\n\n                float dx = (float(N)-1)/(float(output_N)-1);\n\n                std::vector<size_t> ind;\n\n                #pragma omp for \n                for (n=0; n<num; n++)\n                {\n                    ind = data.calculate_index(n);\n\n                    size_t ii;\n                    for(ii=0; ii<N; ii++)\n                    {\n                        ind[num_of_dims - 1] = ii;\n                        data_in(ii) = data(ind);\n                    }\n\n                    interp.computeBSplineCoefficients(data_in, spline_degree, coeff);\n\n                    for (ii = 0; ii<output_N; ii++)\n                    {\n                        ind[num_of_dims - 1] = ii;\n                        data_res(ii) = interp.evaluateBSpline(coeff.begin(), N, spline_degree, 0, ii*dx);\n                        res(ind) = data_res(ii);\n                    }\n                }\n            }\n        }\n        catch(...)\n        {\n            GADGET_THROW(\"Exceptions happened in resample_cardiac_phase_cmr_array(...) ... \");\n        }\n    }\n\n    template EXPORTCMR void resample_cardiac_phase_cmr_array(const hoNDArray<float>& data, size_t output_N, hoNDArray<float>& res, size_t spline_degree);\n    template EXPORTCMR void resample_cardiac_phase_cmr_array(const hoNDArray<double>& data, size_t output_N, hoNDArray<double>& res, size_t spline_degree);\n    template EXPORTCMR void resample_cardiac_phase_cmr_array(const hoNDArray< std::complex<float> >& data, size_t output_N, hoNDArray< std::complex<float> >& res, size_t spline_degree);\n    template EXPORTCMR void resample_cardiac_phase_cmr_array(const hoNDArray< std::complex<double> >& data, size_t output_N, hoNDArray< std::complex<double> >& res, size_t spline_degree);\n}\n", "meta": {"hexsha": "d6eeabce53039948d87f540feecc554058b9d036", "size": 16593, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolboxes/cmr/cmr_time_stamp.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "toolboxes/cmr/cmr_time_stamp.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolboxes/cmr/cmr_time_stamp.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["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.8632653061, "max_line_length": 187, "alphanum_fraction": 0.3993250166, "num_tokens": 3843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.546516487874477}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2009 Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n/** \n\\file\n    \n\\brief test_trig.cpp\n\n\\detailed\nTest trigonometric functions.\n\nOutput:\n@verbatim\n@endverbatim\n**/\n\n#include <cmath>\n#include <boost/units/cmath.hpp>\n#include <boost/units/systems/si/plane_angle.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/dimensionless.hpp>\n#include <boost/units/systems/angle/degrees.hpp>\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\nusing boost::units::si::radians;\nusing boost::units::si::si_dimensionless;\nusing boost::units::degree::degrees;\nBOOST_UNITS_STATIC_CONSTANT(degree_dimensionless, boost::units::degree::dimensionless);\nusing boost::units::si::meters;\n\nBOOST_AUTO_TEST_CASE(test_sin) {\n    BOOST_CHECK_EQUAL(boost::units::sin(2.0 * radians), std::sin(2.0) * si_dimensionless);\n    BOOST_CHECK_CLOSE_FRACTION(static_cast<double>(boost::units::sin(15.0 * degrees)), 0.2588, 0.0004);\n}\n\nBOOST_AUTO_TEST_CASE(test_cos) {\n    BOOST_CHECK_EQUAL(boost::units::cos(2.0 * radians), std::cos(2.0) * si_dimensionless);\n    BOOST_CHECK_CLOSE_FRACTION(static_cast<double>(boost::units::cos(75.0 * degrees)), 0.2588, 0.0004);\n}\n\nBOOST_AUTO_TEST_CASE(test_tan) {\n    BOOST_CHECK_EQUAL(boost::units::tan(2.0 * radians), std::tan(2.0) * si_dimensionless);\n    BOOST_CHECK_CLOSE_FRACTION(static_cast<double>(boost::units::tan(45.0 * degrees)), 1.0, 0.0001);\n}\n\nBOOST_AUTO_TEST_CASE(test_asin) {\n    BOOST_CHECK_EQUAL(boost::units::asin(0.2 * si_dimensionless), std::asin(0.2) * radians);\n    BOOST_CHECK_CLOSE_FRACTION(boost::units::asin(0.5 * degree_dimensionless).value(), 30.0, 0.0001);\n}\n\nBOOST_AUTO_TEST_CASE(test_acos) {\n    BOOST_CHECK_EQUAL(boost::units::acos(0.2 * si_dimensionless), std::acos(0.2) * radians);\n    BOOST_CHECK_CLOSE_FRACTION(boost::units::acos(0.5 * degree_dimensionless).value(), 60.0, 0.0001);\n}\n\nBOOST_AUTO_TEST_CASE(test_atan) {\n    BOOST_CHECK_EQUAL(boost::units::atan(0.2 * si_dimensionless), std::atan(0.2) * radians);\n    BOOST_CHECK_CLOSE_FRACTION(boost::units::atan(1.0 * degree_dimensionless).value(), 45.0, 0.0001);\n}\n\nBOOST_AUTO_TEST_CASE(test_atan2) {\n    BOOST_CHECK_EQUAL(boost::units::atan2(0.2 * si_dimensionless, 0.3 * si_dimensionless), std::atan2(0.2, 0.3) * radians);\n    BOOST_CHECK_EQUAL(boost::units::atan2(0.2 * meters, 0.3 * meters), std::atan2(0.2, 0.3) * radians);\n    BOOST_CHECK_CLOSE_FRACTION(boost::units::atan2(0.8660*degree_dimensionless,0.5*degree_dimensionless).value(), 60., 0.0002);\n}\n", "meta": {"hexsha": "164d794df75782e4df82f894331153aed7dc5c63", "size": 2756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/units/test/test_trig.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/units/test/test_trig.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/units/test/test_trig.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": 37.2432432432, "max_line_length": 127, "alphanum_fraction": 0.7380261248, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042765, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5465164711048764}}
{"text": "#include <UnitTest++/UnitTest++.h>\n#include \"../image_cleanup.h\"\n#include \"coela_random/src/random.h\"\n#include <boost/random/normal_distribution.hpp>\n#include <iostream>\n#include <sstream>\n\n\nusing namespace coela;\nusing namespace std;\nSUITE(image_cleanup)\n{\n\n    TEST(Notify_Suite_Has_Been_Run) {\n        cout << \"*** \\\"image_cleanup\\\" unit tests running ***\" <<endl;\n    }\n\n    TEST(Init_Unuran_Seed) {\n        //Need to do this within a function, hence declaration within a TEST macro.\n        std::vector < unsigned long > seed;\n\n        seed.push_back(111);\n        seed.push_back(222);\n        seed.push_back(333);\n        seed.push_back(444);\n        seed.push_back(555);\n        seed.push_back(666);\n\n        //NB changing the seed may cause some tests to fail due to overly tight / crude statistical checks.\n\n        if (! unuran::StreamWrapper::unuran_package_has_been_seeded()) {\n            unuran::StreamWrapper::set_unuran_package_seed(seed);\n        }\n    }\n\n    TEST(bias_pedestal_for_normally_distributed_pixel_image) {\n        PixelArray2d<float> img(1000,1000,0.0);\n\n        unuran::StreamWrapper rv;\n\n        double true_bias_pedestal = 750.8;\n        double var = 15;\n\n        unuran::GaussianRandomVariate gaussian_dist(true_bias_pedestal, var, rv);\n\n        int n_repeats=1;\n        for (int run=0; run!=n_repeats; ++run) {\n            for (PixelIterator i(img.range()); i!=i.end; ++i) {\n                img(i) = rint(gaussian_dist());\n            }\n\n            HistogramContainer14bit hist;\n            double est_bias_pedestal =\n                image_cleanup::determine_bias_pedestal_from_box_in_raw_image(img,\n                        img.range(), hist);\n\n            CHECK_CLOSE(true_bias_pedestal, est_bias_pedestal, 0.5);\n        }\n\n\n    }\n\n\n}\n\n", "meta": {"hexsha": "f5780b2d95a879f6aace0f22ceb3b54efe2c2798", "size": 1773, "ext": "cc", "lang": "C++", "max_stars_repo_path": "coela_luckypipe/src/unit_tests/image_cleanup_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_luckypipe/src/unit_tests/image_cleanup_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_luckypipe/src/unit_tests/image_cleanup_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": 26.8636363636, "max_line_length": 107, "alphanum_fraction": 0.6238014664, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5465164695869806}}
{"text": "#ifndef VERTEX_COVERING\r\n#define VERTEX_COVERING 1\r\n\r\n#include <LEDA/core/list.h>\r\n#include <LEDA/graph/graph.h>\r\n#include <cassert>\r\n#include <queue>\r\n\r\n\r\n/**\r\n * Primal-dual algorithm for minimum vertex cover problem\r\n */\r\ntemplate <typename T>\r\nT min_vc_pd(const leda::graph& G, const leda::node_array<T>& weight,\r\n    leda::list<leda::node>& S)\r\n{\r\n    leda::edge_array<bool> is_covered(G, false);\r\n    leda::node_array<bool> is_vc(G, false);\r\n    leda::node_array<T> gap(weight);\r\n\r\n    T total_primal_cost = 0;\r\n    T total_dual_cost = 0;\r\n\r\n    leda::edge e;\r\n    forall_edges(e, G)\r\n    {\r\n        if (is_covered[e])\r\n            continue;\r\n\r\n        leda::node s = G.source(e);\r\n        leda::node t = G.target(e);\r\n        if (gap[t] < gap[s])\r\n            std::swap(s, t);\r\n        is_vc[s] = true;\r\n        S.append(s);\r\n        gap[t] -= gap[s];\r\n        assert(gap[t] >= T(0));\r\n        // gap[s] = T(0);\r\n        leda::edge e2;\r\n        forall_adj_edges(e2, s)\r\n        {\r\n            is_covered[e2] = true;\r\n        }\r\n        total_primal_cost += weight[s];\r\n        total_dual_cost += gap[s];\r\n    }\r\n\r\n    leda::list_item it;\r\n    forall_items(it, S)\r\n    {\r\n        leda::node v = S.inf(it);\r\n        leda::node w;\r\n        bool found = false;\r\n        forall_adj_nodes(w, v)\r\n        {\r\n            if (!is_vc[w])\r\n            {\r\n                found = true;\r\n                break;\r\n            }\r\n        }\r\n        if (!found)\r\n        {\r\n            S.del_item(it);\r\n            total_primal_cost -= weight[v];\r\n            is_vc[v] = false;\r\n        }\r\n    }\r\n\r\n    assert(total_primal_cost >= total_dual_cost);\r\n    return total_primal_cost;\r\n}\r\n\r\n/**\r\n * Primal-dual algorithm for graph bipartization problem\r\n */\r\ntemplate <typename T>\r\nT min_bipartization_pd(const leda::graph& G, const leda::node_array<T>& weight,\r\n    leda::list<leda::node>& S)\r\n{\r\n    leda::face_map<bool> is_covered(G);\r\n    leda::node_array<bool> is_vc(G, false);\r\n    leda::node_array<T> gap(weight);\r\n\r\n    std::queue<leda::face> Q;\r\n\r\n    T total_primal_cost = 0;\r\n    T total_dual_cost = 0;\r\n\r\n    leda::face f;\r\n    forall_faces(f, G)\r\n    {\r\n        size_t deg = 0;\r\n        leda::edge e;\r\n        forall_face_edges(e, f)++ deg;\r\n        if ((deg & 1) == 1)\r\n        { // odd\r\n            Q.push(f);\r\n            is_covered[f] = false;\r\n        }\r\n        else\r\n        { // even\r\n            is_covered[f] = true;\r\n        }\r\n    }\r\n\r\n    while (!Q.empty())\r\n    {\r\n        leda::face f = Q.top();\r\n        Q.pop();\r\n        if (is_covered[f])\r\n            continue;\r\n\r\n        leda::edge e = G.first_face_edge(f);\r\n        leda::node s = G.source(e);\r\n        T min_gap = gap[s];\r\n        forall_face_edges(e, f)\r\n        {\r\n            leda::node v = G.source(e);\r\n            if (min_gap > gap[v])\r\n            {\r\n                s = v;\r\n                min_gap = gap[v];\r\n            }\r\n        }\r\n\r\n        is_vc[s] = true;\r\n        S.append(s);\r\n        forall_face_edges(e, f)\r\n        {\r\n            leda::node v = G.source(e);\r\n            gap[v] -= min_gap;\r\n        }\r\n        assert(gap[s] == 0);\r\n\r\n        leda::face f2;\r\n        forall_adj_faces(f2, s)\r\n        { // ???\r\n            is_covered[f2] = true;\r\n        }\r\n\r\n        // add new odd-cycle face ???\r\n\r\n        total_primal_cost += weight[s];\r\n        total_dual_cost += min_gap;\r\n    }\r\n\r\n    leda::list_item it;\r\n    forall_items(it, S)\r\n    {\r\n        leda::node v = S.inf(it);\r\n        leda::node w;\r\n        bool found = false;\r\n        forall_adj_nodes(w, v)\r\n        {\r\n            if (!is_vc[w])\r\n            {\r\n                found = true;\r\n                break;\r\n            }\r\n        }\r\n        if (!found)\r\n        {\r\n            S.del_item(it);\r\n            total_primal_cost -= weight[v];\r\n            is_vc[v] = false;\r\n        }\r\n    }\r\n\r\n    assert(total_primal_cost >= total_dual_cost);\r\n    return total_primal_cost;\r\n}\r\n\r\n#include <boost/heap/binomial_heap.hpp>\r\n\r\ntemplate <typename T>\r\nclass vc_order // for boost::heap\r\n{\r\n  public:\r\n    vc_order(const leda::node_array<T>& W, const leda::node_array<size_t>& D)\r\n        : _W(&W)\r\n        , _D(&D)\r\n    {\r\n    }\r\n    ~vc_order() { }\r\n\r\n    bool operator()(leda::node v, leda::node w) const\r\n    {\r\n        return (*_W)[v] * (*_D)[w] > (*_W)[w] * (*_D)[v];\r\n        // return (*_W)[v] > (*_W)[w];\r\n        // return (*_D)[w] > (*_D)[v];\r\n    }\r\n\r\n  private:\r\n    const leda::node_array<T>* _W;\r\n    const leda::node_array<size_t>* _D;\r\n};\r\n\r\n/**\r\n * Greedy algorithm for minimun vertex cover problem\r\n */\r\ntemplate <typename T>\r\nT min_vc_greedy(const leda::graph& G, const leda::node_array<T>& weight,\r\n    leda::list<leda::node>& S)\r\n{\r\n    typedef typename boost::heap::binomial_heap<leda::node,\r\n        boost::heap::compare<vc_order<T>>>\r\n        bpq_t;\r\n    typedef typename bpq_t::handle_type bh_t;\r\n\r\n    leda::node_array<size_t> D(G); // number of uncovered edges\r\n\r\n    leda::node v;\r\n    forall_nodes(v, G) D[v] = G.degree(v);\r\n\r\n    bpq_t Bpq(vc_order<T>(weight, D));\r\n    leda::node_array<bh_t> bh_handlers(G);\r\n    forall_nodes(v, G)\r\n    {\r\n        bh_t bh = Bpq.push(v);\r\n        bh_handlers[v] = bh;\r\n    }\r\n\r\n    leda::edge_array<bool> is_covered(G, false);\r\n    leda::node_array<bool> is_vc(G, false);\r\n\r\n    T total_cost = 0;\r\n    size_t num_edges = G.number_of_edges();\r\n\r\n    while (num_edges > 0 && !Bpq.empty())\r\n    {\r\n        leda::node s = Bpq.top();\r\n        Bpq.pop();\r\n        is_vc[s] = true;\r\n        S.append(s);\r\n        total_cost += weight[s];\r\n\r\n        leda::edge e2;\r\n        forall_adj_edges(e2, s)\r\n        {\r\n            if (is_covered[e2])\r\n                continue;\r\n            is_covered[e2] = true;\r\n            leda::node t = G.opposite(e2, s);\r\n            D[t] -= 1;\r\n            Bpq.update(bh_handlers[t]);\r\n            --num_edges;\r\n        }\r\n    }\r\n\r\n    leda::list_item it;\r\n    forall_items(it, S)\r\n    {\r\n        leda::node v = S.inf(it);\r\n        leda::node w;\r\n        bool found = false;\r\n        forall_adj_nodes(w, v)\r\n        {\r\n            if (!is_vc[w])\r\n            {\r\n                found = true;\r\n                break;\r\n            }\r\n        }\r\n        if (!found)\r\n        {\r\n            S.del_item(it);\r\n            total_cost -= weight[v];\r\n            is_vc[v] = false;\r\n        }\r\n    }\r\n\r\n    return total_cost;\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "6a882270b06cea293f32123de6e8f957cb7aec39", "size": 6362, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/vertex_cover.hpp", "max_stars_repo_name": "luk036/netoptimcpp", "max_stars_repo_head_hexsha": "29b24cea62f5bf70ffc04777ecf92da187110845", "max_stars_repo_licenses": ["MIT"], "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/vertex_cover.hpp", "max_issues_repo_name": "luk036/netoptimcpp", "max_issues_repo_head_hexsha": "29b24cea62f5bf70ffc04777ecf92da187110845", "max_issues_repo_licenses": ["MIT"], "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/vertex_cover.hpp", "max_forks_repo_name": "luk036/netoptimcpp", "max_forks_repo_head_hexsha": "29b24cea62f5bf70ffc04777ecf92da187110845", "max_forks_repo_licenses": ["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.9675090253, "max_line_length": 80, "alphanum_fraction": 0.4657340459, "num_tokens": 1697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.5465164604311076}}
{"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_FMA_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FMA_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-arithmetic\n    This function object computes the (fused) multiply add of these three parameters.\n\n\n    @par Header <boost/simd/function/fma.hpp>\n\n    @par Notes\n    The call `fma(x, y, z)` is similar to `x*y+z`\n\n    But really conformant fused multiply/add also implies\n\n    - only one rounding\n\n    - no \"intermediate\" overflow\n\n    fma provides this for all integral types and also each time it is reasonable\n    in terms of performance for floating ones (i.e. if the system has the hard\n    wired capability).\n\n    If you need pedantic fma capabilities in all circumstances in your own\n    code you can use the pedantic_ or std_ decorator\n    (although both can be very expensive).\n\n    @par Decorators\n\n    - std_ for floating entries to call directly std::fma. This generally implies pedantic\n      fma behaviour, but in no way improved performances.\n    - pedantic_ ensures the fma properties and allows SIMD acceleration if available.\n\n    @see fms, fnma, fnms\n\n    @par Example:\n\n      @snippet fma.cpp fma\n\n    @par Possible output:\n\n      @snippet fma.txt fma\n  **/\n  Value fma(Value const& x, Value const& y, Value const& z);\n} }\n#endif\n\n#include <boost/simd/function/scalar/fma.hpp>\n#include <boost/simd/function/simd/fma.hpp>\n\n#endif\n", "meta": {"hexsha": "120657fd1bd7228a4378dd99e5d7156a411bb1cc", "size": 1819, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/fma.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/function/fma.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/function/fma.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": 27.5606060606, "max_line_length": 100, "alphanum_fraction": 0.6382627817, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5465164596721602}}
{"text": "/*\n * COPYRIGHT AND PERMISSION NOTICE\n * Penn Software MSCKF_VIO\n * Copyright (C) 2017 The Trustees of the University of Pennsylvania\n * All rights reserved.\n */\n\n// The original file belongs to MSCKF_VIO (https://github.com/KumarRobotics/msckf_vio/)\n// Several changes have been made to use it in orcvio\n\n#ifndef FEATURE_HPP\n#define FEATURE_HPP\n\n#include <iostream>\n#include <map>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n\n#include <orcvio/utils/math_utils.hpp>\n#include <orcvio/imu_state.h>\n\nnamespace orcvio\n{\n\n  /*\n * @brief Feature Salient part of an image. Please refer\n *    to the Appendix of \"A Multi-State Constraint Kalman\n *    Filter for Vision-aided Inertial Navigation\" for how\n *    the 3d position of a feature is initialized.\n */\n  struct Feature\n  {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    /*\n   * @brief OptimizationConfig Configuration parameters\n   *    for 3d feature position optimization.\n   */\n    struct OptimizationConfig\n    {\n      double translation_threshold;\n      double huber_epsilon;\n      double estimation_precision;\n      double initial_damping;\n      int outer_loop_max_iteration;\n      int inner_loop_max_iteration;\n      double cost_threshold;\n      double init_final_dist_threshold;\n\n      OptimizationConfig() : translation_threshold(0.2),\n                             huber_epsilon(0.01),\n                             estimation_precision(5e-7),\n                             initial_damping(1e-3),\n                             outer_loop_max_iteration(10),\n                             inner_loop_max_iteration(10),\n                             cost_threshold(4.7673e-04),\n                             init_final_dist_threshold(5)\n      {\n        return;\n      }\n    };\n\n    // Constructors for the struct.\n    Feature() : id(0), position(Eigen::Vector3d::Zero()),\n                is_initialized(false), best_cost(99999.9),\n                id_anchor(-1), invParam(Eigen::Vector3d::Zero()),\n                in_state(false), totalObsNum(0), ekf_feature(false) {}\n\n    Feature(const FeatureIDType &new_id) : id(new_id),\n                                           position(Eigen::Vector3d::Zero()),\n                                           is_initialized(false), best_cost(99999.9),\n                                           id_anchor(-1), invParam(Eigen::Vector3d::Zero()),\n                                           in_state(false), totalObsNum(0), ekf_feature(false) {}\n\n    /*\n   * @brief triangulate feature position based on initial guess and LM\n   * @param cam_poses: all the camera poses \n   * @param measurements: measurements \n   * @param final_position: to hold the initial position \n   * @param final_position: to hold the position after LM \n   * @param T_c_w_last: to hold the pose of last camera  \n   * @return a flag indicating whether this feature is valid \n   */\n    inline bool triangulate_position(std::vector<Eigen::Isometry3d,\n                                                 Eigen::aligned_allocator<Eigen::Isometry3d>> &cam_poses,\n                                     const std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> &measurements,\n                                     Eigen::Vector3d &solution, Eigen::Vector3d &final_position, Eigen::Isometry3d &T_c_w_last);\n\n    /*\n   * @brief cost Compute the cost of the camera observations\n   * @param T_c0_c1 A rigid body transformation takes\n   *    a vector in c0 frame to ci frame.\n   * @param x The current estimation.\n   * @param z The ith measurement of the feature j in ci frame.\n   * @return e The cost of this observation.\n   */\n    inline void cost(const Eigen::Isometry3d &T_c0_ci,\n                     const Eigen::Vector3d &x, const Eigen::Vector2d &z,\n                     double &e) const;\n\n    /*\n   * @brief jacobian Compute the Jacobian of the camera observation\n   * @param T_c0_c1 A rigid body transformation takes\n   *    a vector in c0 frame to ci frame.\n   * @param x The current estimation.\n   * @param z The actual measurement of the feature in ci frame.\n   * @return J The computed Jacobian.\n   * @return r The computed residual.\n   * @return w Weight induced by huber kernel.\n   */\n    inline void jacobian(const Eigen::Isometry3d &T_c0_ci,\n                         const Eigen::Vector3d &x, const Eigen::Vector2d &z,\n                         Eigen::Matrix<double, 2, 3> &J, Eigen::Vector2d &r,\n                         double &w) const;\n\n    /*\n   * @brief generateInitialGuess Compute the initial guess of\n   *    the feature's 3d position using only two views.\n   * @param T_c1_c2: A rigid body transformation taking\n   *    a vector from c2 frame to c1 frame.\n   * @param z1: feature observation in c1 frame.\n   * @param z2: feature observation in c2 frame.\n   * @return p: Computed feature position in c1 frame.\n   */\n    inline void generateInitialGuess(\n        const Eigen::Isometry3d &T_c1_c2, const Eigen::Vector2d &z1,\n        const Eigen::Vector2d &z2, Eigen::Vector3d &p) const;\n\n    /*\n   * @brief checkMotion Check the input camera poses to ensure\n   *    there is enough translation to triangulate the feature\n   *    positon.\n   * @param imu_states : input to aquire camera poses.\n   \u00d7 @param if_tracked : if feature be tracked now.\n   * @return True if the translation between the input camera\n   *    poses is sufficient.\n   */\n    inline bool checkMotion(\n        const IMUStateServer &imu_states, bool if_tracked) const;\n\n    /*\n   * @brief InitializePosition Intialize the feature position\n   *    based on all current available measurements.\n   * @param imu_states: A map containing the camera poses with its\n   *    ID as the associated key value.\n   * @param curr_id: current camera id.\n   * @return The computed 3d position is used to set the position\n   *    member variable. Note the resulted position is in world\n   *    frame.\n   * @return True if the estimated 3d position of the feature\n   *    is valid.\n   */\n    inline bool initializePosition(\n        const IMUStateServer &imu_states, const StateIDType &curr_id);\n\n    /*\n   * @brief initializePosition_AssignAnchor Intialize the feature position\n   *    based on all current available measurements. Current camera would\n   *    be the anchor\n   * @param imu_states: A map containing the camera poses with its\n   *    ID as the associated key value.\n   * @param anchor_id: Assigned anchor camera id.\n   * @return The computed 3d position is used to set the position\n   *    member variable. Note the resulted position is in world\n   *    frame.\n   * @return True if the estimated 3d position of the feature\n   *    is valid.\n   */\n    inline bool initializePosition_AssignAnchor(\n        const IMUStateServer &imu_states);\n\n    /*\n   * @brief initializeInvParamPosition Intialize the feature position\n   *    based on all current available measurements. Result in \n   *    inverse depth parameterization in anchor frame.\n   * @param imu_states: A map containing the camera poses with its\n   *    ID as the associated key value.\n   * @param curr_id: current camera id.\n   * @return The computed 3d position is used to set the position\n   *    member variable. Note the resulted position is in world\n   *    frame.\n   * @return The computed inverse depth parameterizations is used to \n   *    set the invParam variable. Note the resulted inverse depth\n   *    parameterization is in the anchor frame, which is the newest \n   *    frame observing this feature except for current frame.\n   * @return True if the estimated 3d position of the feature\n   *    is valid.\n   */\n    inline bool initializeInvParamPosition(\n        const IMUStateServer &imu_states, const StateIDType &curr_id);\n\n    // An unique identifier for the feature.\n    // In case of long time running, the variable\n    // type of id is set to FeatureIDType in order\n    // to avoid duplication.\n    FeatureIDType id;\n\n    // id for next feature\n    static FeatureIDType next_id;\n\n    // Store the observations of the features in the\n    // state_id(key)-image_coordinates(value) manner.\n    std::map<StateIDType, Eigen::Vector2d, std::less<StateIDType>,\n             Eigen::aligned_allocator<\n                 std::pair<const StateIDType, Eigen::Vector2d>>>\n        observations;\n\n    // Store the observations of the features velocity in the\n    // state_id(key)-features_velocity(value) manner.\n    std::map<StateIDType, Eigen::Vector2d, std::less<StateIDType>,\n             Eigen::aligned_allocator<\n                 std::pair<const StateIDType, Eigen::Vector2d>>>\n        observations_vel;\n\n    // 3d postion of the feature in the world frame.\n    Eigen::Vector3d position;\n\n    // First estimate 3d position in world frame\n    Eigen::Vector3d position_FEJ;\n\n    // Best normalized cost, added by QXC\n    double best_cost;\n\n    // First observed camera pose, added by QXC\n    Eigen::Isometry3d firstCamPose;\n\n    // If failed because of nagtive depth of big reprojection error\n    bool failed_by_neg_dpth;\n    bool failed_by_big_proj;\n\n    // [x/z, y/z] under first observed camera coordinate, added by QXC\n    Eigen::Vector2d solutionInFirstCam;\n\n    // A indicator to show if the 3d postion of the feature\n    // has been initialized or not.\n    bool is_initialized;\n\n    // Optimization configuration for solving the 3d position.\n    static OptimizationConfig optimization_config;\n\n    // QXC debug log\n    inline double getMaxObsDiff();\n    inline double getTotalObsChange();\n\n    // Anchor camera id\n    StateIDType id_anchor;\n\n    // 3d inverse depth parameter position in anchor camera frame.\n    Eigen::Vector3d invParam;\n\n    // 1d inverse depth parameter position in anchor camera frame.\n    double invDepth;\n    // Corrected observation in anchor camera frame.\n    Eigen::Vector3d obs_anchor;\n\n    // If this feature is in filter state\n    bool in_state;\n\n    // Record total observation number\n    int totalObsNum;\n\n    // If this is a potential ekf feature\n    bool ekf_feature;\n  };\n\n  typedef std::map<FeatureIDType, Feature, std::less<int>,\n                   Eigen::aligned_allocator<\n                       std::pair<const FeatureIDType, Feature>>>\n      MapServer;\n\n  void Feature::cost(const Eigen::Isometry3d &T_c0_ci,\n                     const Eigen::Vector3d &x, const Eigen::Vector2d &z,\n                     double &e) const\n  {\n    // Compute hi1, hi2, and hi3 as Equation (37).\n    const double &alpha = x(0);\n    const double &beta = x(1);\n    const double &rho = x(2);\n\n    Eigen::Vector3d h = T_c0_ci.linear() *\n                            Eigen::Vector3d(alpha, beta, 1.0) +\n                        rho * T_c0_ci.translation();\n    double &h1 = h(0);\n    double &h2 = h(1);\n    double &h3 = h(2);\n\n    // Predict the feature observation in ci frame.\n    Eigen::Vector2d z_hat(h1 / h3, h2 / h3);\n\n    // Compute the residual.\n    e = (z_hat - z).squaredNorm();\n    return;\n  }\n\n  void Feature::jacobian(const Eigen::Isometry3d &T_c0_ci,\n                         const Eigen::Vector3d &x, const Eigen::Vector2d &z,\n                         Eigen::Matrix<double, 2, 3> &J, Eigen::Vector2d &r,\n                         double &w) const\n  {\n\n    // Compute hi1, hi2, and hi3 as Equation (37).\n    const double &alpha = x(0);\n    const double &beta = x(1);\n    const double &rho = x(2);\n\n    Eigen::Vector3d h = T_c0_ci.linear() *\n                            Eigen::Vector3d(alpha, beta, 1.0) +\n                        rho * T_c0_ci.translation();\n    double &h1 = h(0);\n    double &h2 = h(1);\n    double &h3 = h(2);\n\n    // Compute the Jacobian.\n    Eigen::Matrix3d W;\n    W.leftCols<2>() = T_c0_ci.linear().leftCols<2>();\n    W.rightCols<1>() = T_c0_ci.translation();\n\n    J.row(0) = 1 / h3 * W.row(0) - h1 / (h3 * h3) * W.row(2);\n    J.row(1) = 1 / h3 * W.row(1) - h2 / (h3 * h3) * W.row(2);\n\n    // Compute the residual.\n    Eigen::Vector2d z_hat(h1 / h3, h2 / h3);\n    r = z_hat - z;\n\n    // Compute the weight based on the residual.\n    double e = r.norm();\n    if (e <= optimization_config.huber_epsilon)\n      w = 1.0;\n    else\n      w = std::sqrt(2.0 * optimization_config.huber_epsilon / e);\n\n    return;\n  }\n\n  void Feature::generateInitialGuess(\n      const Eigen::Isometry3d &T_c1_c2, const Eigen::Vector2d &z1,\n      const Eigen::Vector2d &z2, Eigen::Vector3d &p) const\n  {\n    // Construct a least square problem to solve the depth.\n    Eigen::Vector3d m = T_c1_c2.linear() * Eigen::Vector3d(z1(0), z1(1), 1.0);\n\n    Eigen::Vector2d A(0.0, 0.0);\n    A(0) = m(0) - z2(0) * m(2);\n    A(1) = m(1) - z2(1) * m(2);\n\n    Eigen::Vector2d b(0.0, 0.0);\n    b(0) = z2(0) * T_c1_c2.translation()(2) - T_c1_c2.translation()(0);\n    b(1) = z2(1) * T_c1_c2.translation()(2) - T_c1_c2.translation()(1);\n\n    // Solve for the depth.\n    double depth = (A.transpose() * A).inverse() * A.transpose() * b;\n    p(0) = z1(0) * depth;\n    p(1) = z1(1) * depth;\n    p(2) = depth;\n    return;\n  }\n\n  bool Feature::checkMotion(\n      const IMUStateServer &imu_states, bool if_tracked) const\n  {\n\n    StateIDType first_cam_id = observations.begin()->first;\n    StateIDType last_cam_id;\n    if (if_tracked)\n      last_cam_id = (--(--observations.end()))->first;\n    else\n      last_cam_id = (--observations.end())->first;\n\n    Eigen::Isometry3d first_cam_pose;\n    first_cam_pose.linear() = imu_states.find(first_cam_id)->second.orientation_cam;\n    first_cam_pose.translation() =\n        imu_states.find(first_cam_id)->second.position_cam;\n\n    Eigen::Isometry3d last_cam_pose;\n    last_cam_pose.linear() = imu_states.find(last_cam_id)->second.orientation_cam;\n    last_cam_pose.translation() =\n        imu_states.find(last_cam_id)->second.position_cam;\n\n    // Get the direction of the feature when it is first observed.\n    // This direction is represented in the world frame.\n    Eigen::Vector3d feature_direction(\n        observations.begin()->second(0),\n        observations.begin()->second(1), 1.0);\n    feature_direction = feature_direction / feature_direction.norm();\n    feature_direction = first_cam_pose.linear() * feature_direction;\n\n    // Compute the translation between the first frame\n    // and the last frame. We assume the first frame and\n    // the last frame will provide the largest motion to\n    // speed up the checking process.\n    Eigen::Vector3d translation = last_cam_pose.translation() -\n                                  first_cam_pose.translation();\n    double parallel_translation =\n        translation.transpose() * feature_direction;\n    Eigen::Vector3d orthogonal_translation = translation -\n                                             parallel_translation * feature_direction;\n\n    if (orthogonal_translation.norm() >\n        optimization_config.translation_threshold)\n      return true;\n    else\n      return false;\n  }\n\n  bool Feature::initializePosition(\n      const IMUStateServer &imu_states, const StateIDType &curr_id)\n  {\n    // Organize camera poses and feature observations properly.\n    std::vector<Eigen::Isometry3d,\n                Eigen::aligned_allocator<Eigen::Isometry3d>>\n        cam_poses(0);\n    std::vector<Eigen::Vector2d,\n                Eigen::aligned_allocator<Eigen::Vector2d>>\n        measurements(0);\n\n    std::vector<StateIDType> cam_ids(0);\n    for (auto &m : observations)\n    {\n      // TODO: This should be handled properly. Normally, the\n      //    required camera states should all be available in\n      //    the input imu_states buffer.\n      auto state_iter = imu_states.find(m.first);\n      if (state_iter == imu_states.end())\n        continue;\n\n      if (curr_id == state_iter->first)\n        continue;\n\n      // Add the measurement.\n      measurements.push_back(m.second.head<2>());\n\n      // This camera pose will take a vector from this camera frame\n      // to the world frame.\n      Eigen::Isometry3d cam_pose;\n      cam_pose.linear() = state_iter->second.orientation_cam;\n      cam_pose.translation() = state_iter->second.position_cam;\n\n      cam_poses.push_back(cam_pose);\n\n      cam_ids.push_back(state_iter->first);\n    }\n\n    Eigen::Vector3d solution, final_position;\n    Eigen::Isometry3d T_c_w_last;\n    bool is_valid_solution = triangulate_position(cam_poses, measurements, solution, final_position, T_c_w_last);\n\n    if (is_valid_solution)\n    {\n      if (!is_initialized)\n        position_FEJ = position;\n      is_initialized = true;\n      position = T_c_w_last.linear() * final_position + T_c_w_last.translation();\n      invParam = solution;\n      id_anchor = cam_ids[cam_ids.size() - 1];\n      invDepth = 1 / final_position(2);\n      obs_anchor = Eigen::Vector3d(final_position(0) * invDepth, // correct observation\n                                   final_position(1) * invDepth, 1);\n      // obs_anchor = Eigen::Vector3d(measurements[cam_ids.size()-1](0),     // do not correct observation\n      //     measurements[cam_ids.size()-1](1), 1);\n    }\n\n    return is_valid_solution;\n  }\n\n  bool Feature::initializePosition_AssignAnchor(\n      const IMUStateServer &imu_states)\n  {\n    // Organize camera poses and feature observations properly.\n    std::vector<Eigen::Isometry3d,\n                Eigen::aligned_allocator<Eigen::Isometry3d>>\n        cam_poses(0);\n    std::vector<Eigen::Vector2d,\n                Eigen::aligned_allocator<Eigen::Vector2d>>\n        measurements(0);\n\n    std::vector<StateIDType> cam_ids(0);\n    for (auto &m : observations)\n    {\n      // TODO: This should be handled properly. Normally, the\n      //    required camera states should all be available in\n      //    the input imu_states buffer.\n      auto state_iter = imu_states.find(m.first);\n      if (state_iter == imu_states.end())\n        continue;\n\n      // Add the measurement.\n      measurements.push_back(m.second.head<2>());\n\n      // This camera pose will take a vector from this camera frame\n      // to the world frame.\n      Eigen::Isometry3d cam_pose;\n      cam_pose.linear() = state_iter->second.orientation_cam;\n      cam_pose.translation() = state_iter->second.position_cam;\n\n      cam_poses.push_back(cam_pose);\n\n      cam_ids.push_back(state_iter->first);\n    }\n\n    Eigen::Vector3d solution, final_position;\n    Eigen::Isometry3d T_c_w_last;\n    bool is_valid_solution = triangulate_position(cam_poses, measurements, solution, final_position, T_c_w_last);\n\n    if (is_valid_solution)\n    {\n      if (!is_initialized)\n        position_FEJ = position;\n      is_initialized = true;\n      position = T_c_w_last.linear() * final_position + T_c_w_last.translation();\n      invParam = solution;\n      id_anchor = cam_ids[cam_ids.size() - 1];\n      invDepth = 1 / final_position(2);\n      obs_anchor = Eigen::Vector3d(final_position(0) * invDepth, // correct observation\n                                   final_position(1) * invDepth, 1);\n      // obs_anchor = Eigen::Vector3d(measurements[cam_ids.size()-1](0),     // do not correct observation\n      //     measurements[cam_ids.size()-1](1), 1);\n    }\n\n    return is_valid_solution;\n  }\n\n  bool Feature::initializeInvParamPosition(\n      const IMUStateServer &imu_states, const StateIDType &curr_id)\n  {\n    // Organize camera poses and feature observations properly.\n    std::vector<Eigen::Isometry3d,\n                Eigen::aligned_allocator<Eigen::Isometry3d>>\n        cam_poses(0);\n    std::vector<Eigen::Vector2d,\n                Eigen::aligned_allocator<Eigen::Vector2d>>\n        measurements(0);\n\n    std::vector<StateIDType> cam_ids(0);\n    for (auto &m : observations)\n    {\n      // TODO: This should be handled properly. Normally, the\n      //    required camera states should all be available in\n      //    the input imu_states buffer.\n      auto state_iter = imu_states.find(m.first);\n      if (state_iter == imu_states.end())\n        continue;\n\n      if (curr_id == state_iter->first)\n        continue;\n\n      // Add the measurement.\n      measurements.push_back(m.second.head<2>());\n\n      // This camera pose will take a vector from this camera frame\n      // to the world frame.\n      Eigen::Isometry3d cam_pose;\n      cam_pose.linear() = state_iter->second.orientation_cam;\n      cam_pose.translation() = state_iter->second.position_cam;\n\n      cam_poses.push_back(cam_pose);\n\n      cam_ids.push_back(state_iter->first);\n    }\n\n    Eigen::Vector3d solution, final_position;\n    Eigen::Isometry3d T_c_w_last;\n    bool is_valid_solution = triangulate_position(cam_poses, measurements, solution, final_position, T_c_w_last);\n\n    if (is_valid_solution)\n    {\n      if (!is_initialized)\n        position_FEJ = position;\n      ekf_feature = true;\n      is_initialized = true;\n      position = T_c_w_last.linear() * final_position + T_c_w_last.translation();\n      invParam = solution;\n      id_anchor = cam_ids[cam_ids.size() - 1];\n      invDepth = 1 / final_position(2);\n      obs_anchor = Eigen::Vector3d(final_position(0) * invDepth, // correct observation\n                                   final_position(1) * invDepth, 1);\n      // obs_anchor = Eigen::Vector3d(measurements[cam_ids.size()-1](0),     // do not correct observation\n      //     measurements[cam_ids.size()-1](1), 1);\n    }\n\n    return is_valid_solution;\n  }\n\n  double Feature::getMaxObsDiff()\n  {\n    Eigen::Vector2d p0(observations.begin()->second(0),\n                       observations.begin()->second(1));\n    Eigen::Vector2d p1((--observations.end())->second(0),\n                       (--observations.end())->second(1));\n\n    return (p0 - p1).norm();\n  }\n\n  double Feature::getTotalObsChange()\n  {\n\n    std::vector<Eigen::Vector2d,\n                Eigen::aligned_allocator<Eigen::Vector2d>>\n        p(0);\n    for (const auto &obs : observations)\n      p.push_back(Eigen::Vector2d(obs.second(0), obs.second(1)));\n\n    double diff = 0.0;\n    for (int i = 1; i < p.size(); i++)\n    {\n      diff += (p[i] - p[i - 1]).norm();\n    }\n    return diff;\n  }\n\n  bool Feature::triangulate_position(std::vector<Eigen::Isometry3d,\n                                                 Eigen::aligned_allocator<Eigen::Isometry3d>> &cam_poses,\n                                     const std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> &measurements,\n                                     Eigen::Vector3d &solution, Eigen::Vector3d &final_position, Eigen::Isometry3d &T_c_w_last)\n  {\n\n    // All camera poses should be modified such that it takes a\n    // vector from the last camera frame in the buffer to this\n    // camera frame.\n    T_c_w_last = cam_poses[cam_poses.size() - 1];\n    for (auto &pose : cam_poses)\n      pose = pose.inverse() * T_c_w_last;\n\n    // Generate initial guess\n    Eigen::Vector3d initial_position(0.0, 0.0, 0.0);\n    if (!is_initialized)\n      generateInitialGuess(cam_poses[0], measurements[cam_poses.size() - 1],\n                           measurements[0], initial_position);\n    else\n      initial_position = T_c_w_last.inverse() * position;\n\n    solution << initial_position(0) / initial_position(2),\n        initial_position(1) / initial_position(2),\n        1.0 / initial_position(2);\n\n    // Apply Levenberg-Marquart method to solve for the 3d position.\n    double lambda = optimization_config.initial_damping;\n    int inner_loop_cntr = 0;\n    int outer_loop_cntr = 0;\n    bool is_cost_reduced = false;\n    double delta_norm = 0;\n\n    // Compute the initial cost.\n    double total_cost = 0.0;\n    for (int i = 0; i < cam_poses.size(); ++i)\n    {\n      double this_cost = 0.0;\n      cost(cam_poses[i], solution, measurements[i], this_cost);\n      total_cost += this_cost;\n    }\n\n    // Outer loop.\n    do\n    {\n      Eigen::Matrix3d A = Eigen::Matrix3d::Zero();\n      Eigen::Vector3d b = Eigen::Vector3d::Zero();\n\n      for (int i = 0; i < cam_poses.size(); ++i)\n      {\n        Eigen::Matrix<double, 2, 3> J;\n        Eigen::Vector2d r;\n        double w;\n\n        jacobian(cam_poses[i], solution, measurements[i], J, r, w);\n\n        if (w == 1)\n        {\n          A += J.transpose() * J;\n          b += J.transpose() * r;\n        }\n        else\n        {\n          double w_square = w * w;\n          A += w_square * J.transpose() * J;\n          b += w_square * J.transpose() * r;\n        }\n      }\n\n      // Inner loop.\n      // Solve for the delta that can reduce the total cost.\n      do\n      {\n        Eigen::Matrix3d damper = lambda * Eigen::Matrix3d::Identity();\n        Eigen::Vector3d delta = (A + damper).ldlt().solve(b);\n        Eigen::Vector3d new_solution = solution - delta;\n        delta_norm = delta.norm();\n\n        double new_cost = 0.0;\n        for (int i = 0; i < cam_poses.size(); ++i)\n        {\n          double this_cost = 0.0;\n          cost(cam_poses[i], new_solution, measurements[i], this_cost);\n          new_cost += this_cost;\n        }\n\n        if (new_cost < total_cost)\n        {\n          is_cost_reduced = true;\n          solution = new_solution;\n          total_cost = new_cost;\n          lambda = lambda / 10 > 1e-10 ? lambda / 10 : 1e-10;\n        }\n        else\n        {\n          is_cost_reduced = false;\n          lambda = lambda * 10 < 1e12 ? lambda * 10 : 1e12;\n        }\n\n      } while (inner_loop_cntr++ <\n                   optimization_config.inner_loop_max_iteration &&\n               !is_cost_reduced);\n\n      inner_loop_cntr = 0;\n\n    } while (outer_loop_cntr++ <\n                 optimization_config.outer_loop_max_iteration &&\n             delta_norm > optimization_config.estimation_precision);\n\n    // Covert the feature position from inverse depth\n    // representation to its 3d coordinate.\n    // Eigen::Vector3d final_position(solution(0)/solution(2),\n    //     solution(1)/solution(2), 1.0/solution(2));\n    final_position << solution(0) / solution(2),\n        solution(1) / solution(2), 1.0 / solution(2);\n\n    // Check if the solution is valid. Make sure the feature\n    // is in front of every camera frame observing it.\n    bool is_valid_solution = true;\n    failed_by_neg_dpth = false;\n    for (const auto &pose : cam_poses)\n    {\n      Eigen::Vector3d pos =\n          pose.linear() * final_position + pose.translation();\n      if (pos(2) <= 0)\n      {\n        is_valid_solution = false;\n        failed_by_neg_dpth = true;\n        break;\n      }\n    }\n\n    //  check total_cost\n    double normalized_cost =\n        total_cost / (2 * cam_poses.size() * cam_poses.size());\n    double uv_cost =\n        sqrt(total_cost / cam_poses.size());\n    failed_by_big_proj = false;\n\n    if ((final_position - initial_position).norm() > optimization_config.init_final_dist_threshold)\n    {\n      is_valid_solution = false;\n      failed_by_big_proj = true;\n    }\n\n    if (normalized_cost > optimization_config.cost_threshold)\n    {\n      is_valid_solution = false;\n      failed_by_big_proj = true;\n    }\n\n    return is_valid_solution;\n  }\n\n} // namespace orcvio\n\n#endif // FEATURE_HPP", "meta": {"hexsha": "2146be5f3e68148d91e7abac779bd249525d695f", "size": 26690, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/orcvio/feat/feature.hpp", "max_stars_repo_name": "shanmo/OrcVIO-Object-Mapping", "max_stars_repo_head_hexsha": "e5337a56da72b23ebf5c9d9f87534fe2edc9c54c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-14T03:31:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-14T03:31:16.000Z", "max_issues_repo_path": "include/orcvio/feat/feature.hpp", "max_issues_repo_name": "shanmo/OrcVIO-Object-Mapping", "max_issues_repo_head_hexsha": "e5337a56da72b23ebf5c9d9f87534fe2edc9c54c", "max_issues_repo_licenses": ["MIT"], "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/orcvio/feat/feature.hpp", "max_forks_repo_name": "shanmo/OrcVIO-Object-Mapping", "max_forks_repo_head_hexsha": "e5337a56da72b23ebf5c9d9f87534fe2edc9c54c", "max_forks_repo_licenses": ["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.7526041667, "max_line_length": 129, "alphanum_fraction": 0.6271637317, "num_tokens": 6645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5465164596721602}}
{"text": "#define EIGEN_USE_MKL_ALL\n#include <chrono>\n#include <Eigen/Dense>\n#include <iostream>\n\nusing Time_t = std::chrono::nanoseconds;\nusing namespace std::chrono_literals;\n\nint main(int argc, char* argv[]) {\n    int nr_prods {1};\n    if (argc > 1)\n        nr_prods = std::stoi(argv[1]);\n    std::chrono::duration<double> duration = 0ns;\n    for (int prod_nr = 0; prod_nr < nr_prods; ++prod_nr) {\n        Eigen::MatrixXd A = Eigen::MatrixXd::Random(10000, 2000);\n        Eigen::MatrixXd B = Eigen::MatrixXd::Random(2000, 8000);\n        auto stime {std::chrono::steady_clock::now()};\n        Eigen::MatrixXd C = A*B;\n        auto etime {std::chrono::steady_clock::now()};\n        duration += std::chrono::duration_cast<Time_t>(etime - stime);\n        std::cout << \"C.sum() = \" << C.sum() << std::endl;\n    }\n    std::cout << \"time: \" << duration.count()/nr_prods\n              << \" s\" << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "6b1305815b500ddde6e885045c5fb3c8d4f99f33", "size": 908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Eigen/Mkl/matrix_product.cpp", "max_stars_repo_name": "gjbex/Scientific-C-", "max_stars_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "source-code/Eigen/Mkl/matrix_product.cpp", "max_issues_repo_name": "gjbex/Scientific-C-", "max_issues_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "source-code/Eigen/Mkl/matrix_product.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": 33.6296296296, "max_line_length": 70, "alphanum_fraction": 0.5969162996, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5465164474804957}}
{"text": "/**********************************************************************************************************************\nThis file is part of the Control Toolbox (https://github.com/ethz-adrl/control-toolbox), copyright by ETH Zurich.\nLicensed under the BSD-2 license (see LICENSE file in main directory)\n**********************************************************************************************************************/\n\n/*! \\file\n *\t\\brief\t\tAuto-generated code for computing the derivative of qdd with respect to state and input\n *  \\author\t    Michael Neunert\n *\n *  @example \ttimingFullvsSeparateJacobian.cpp\n *  This is an example of how to use the generated code.\n *\n *  @example \ttimingFullJacobian.cpp\n *  This is an example of how to use the generated code.\n */\n\n#pragma once\n\n#include <array>\n#include <Eigen/Core>\n\nnamespace ct_HyA {\n\nEigen::Matrix<double, 12 + 6, 6> computeFullJacobianCodegen(const Eigen::Matrix<double, 12, 1>& state,\n    const Eigen::Matrix<double, 6, 1>& tau);\n}\n", "meta": {"hexsha": "0f6bb57f83b1a98be14f0e7ddbcbb3149e65b487", "size": 999, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ct_models/include/ct/models/HyA/codegen/fullJacobian.hpp", "max_stars_repo_name": "romainreignier/control-toolbox", "max_stars_repo_head_hexsha": "6ee83d401b1a8d2fbfda2646a0ec1ec0e67b7c96", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 864.0, "max_stars_repo_stars_event_min_datetime": "2019-04-26T18:18:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T17:38:48.000Z", "max_issues_repo_path": "ct_models/include/ct/models/HyA/codegen/fullJacobian.hpp", "max_issues_repo_name": "romainreignier/control-toolbox", "max_issues_repo_head_hexsha": "6ee83d401b1a8d2fbfda2646a0ec1ec0e67b7c96", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 154.0, "max_issues_repo_issues_event_min_datetime": "2019-04-27T05:32:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:17:00.000Z", "max_forks_repo_path": "ct_models/include/ct/models/HyA/codegen/fullJacobian.hpp", "max_forks_repo_name": "romainreignier/control-toolbox", "max_forks_repo_head_hexsha": "6ee83d401b1a8d2fbfda2646a0ec1ec0e67b7c96", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 249.0, "max_forks_repo_forks_event_min_datetime": "2019-05-03T11:34:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T19:17:05.000Z", "avg_line_length": 37.0, "max_line_length": 119, "alphanum_fraction": 0.5525525526, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681195338727, "lm_q2_score": 0.6370308082623216, "lm_q1q2_score": 0.5464247184883146}}
{"text": "#define DEBUG 1\n/**\n * File    : F.cpp\n * Author  : Kazune Takahashi\n * Created : 5/30/2021, 4:50:13 PM\n * Powered by Visual Studio Code\n */\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n#include <boost/integer/common_factor_rt.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/rational.hpp>\n#include <atcoder/all>\nusing namespace std;\n// using namespace atcoder;\nusing boost::rational;\nusing boost::integer::gcd; // for C++14 or for cpp_int\nusing boost::integer::lcm; // for C++14 or for cpp_int\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\n/***************************************************\n    Fundermental Tools\n ***************************************************/\n// ----- max_heap and min_heap -----\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nbool ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\ntemplate <typename T>\nbool ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\n// ----- mint -----\nusing mint = atcoder::modint1000000007;\n// using mint = atcoder::modint998244353;\n// using mint = atcoder::modint; // atcoder::modint::set_mod(xxx);\n// using mint = atcoder::static_modint<1000000009>;\n// using mint0 = dynamic_modint<xxx>;\n// using mint1 = dynamic_modint<yyy>;\nistream &operator>>(istream &is, mint &x)\n{\n  ll t;\n  is >> t;\n  x = t;\n  return is;\n}\nostream &operator<<(ostream &os, mint const &x)\n{\n  return os << x.val();\n}\n// ----- Combination -----\ntemplate <typename Mint = mint>\nclass Combination\n{\npublic:\n  constexpr static ll MAX_SIZE{4'000'010LL};\n  // constexpr static ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed\n\n  vector<mint> inv, fact, factinv;\n\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i{2LL}; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[Mint::mod() % i]) * (Mint::mod() / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i{1LL}; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n\n  Mint operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n\n  Mint catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing combination = Combination<mint>;\n// ----- for C++17 -----\ntemplate <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>\nsize_t popcount(T x) { return bitset<64>(x).count(); }\nsize_t popcount(string const &S) { return bitset<200010>{S}.count(); }\n// ----- Infty -----\ntemplate <typename T>\nconstexpr T Infty() { return numeric_limits<T>::max(); }\ntemplate <typename T>\nconstexpr T mInfty() { return numeric_limits<T>::min(); }\n/***************************************************\n    AtCoder Library / Data Structures\n ***************************************************/\n// ----- FenwickTree -----\ntemplate <typename T = ll>\nclass FenwickTree : public atcoder::fenwick_tree<T>\n{\npublic:\n  using atcoder::fenwick_tree<T>::fenwick_tree;\n\n  FenwickTree(vector<T> const &v) : FenwickTree(static_cast<int>(v.size()))\n  {\n    for (auto i{size_t{0}}; i < v.size(); ++i)\n    {\n      atcoder::fenwick_tree<T>::add(i, v[i]);\n    }\n  }\n\n  T operator[](int i)\n  {\n    return atcoder::fenwick_tree<T>::sum(i, i + 1);\n  }\n};\n/***************************************************\n    AtCoder Library / Math\n ***************************************************/\n// ----- Math -----\nusing atcoder::convolution;\nusing atcoder::convolution_ll;\nusing atcoder::floor_sum;\n/***************************************************\n    AtCoder Library / Graphs\n ***************************************************/\n// ----- UnionFind -----\nusing UnionFind = atcoder::dsu;\n// ----- MaxFlow -----\ntemplate <typename Cap = ll>\nclass MaxFlow : public atcoder::mf_graph<Cap>\n{\npublic:\n  using atcoder::mf_graph<Cap>::mf_graph;\n\n  int add_edge(int from, int to)\n  {\n    return atcoder::mf_graph<Cap>::add_edge(from, to, Cap{1});\n  }\n};\nostream &operator<<(ostream &os, typename atcoder::mf_graph<ll>::edge const &edge)\n{\n  return os << \"from: \" << edge.from << \", to: \" << edge.to << \", cap: \" << edge.cap << \", flow: \" << edge.flow;\n}\n// ----- MinCostFlow -----\ntemplate <typename Cap = ll, typename Cost = ll>\nclass MinCostFlow : public atcoder::mcf_graph<Cap, Cost>\n{\nprivate:\n  Cost infty;\n\npublic:\n  using atcoder::mcf_graph<Cap, Cost>::mcf_graph;\n\n  MinCostFlow(int n, Cost infty = Cost{0}) : atcoder::mcf_graph<Cap, Cost>::mcf_graph(n), infty{infty} {}\n\n  int add_edge(int from, int to, Cap cap)\n  {\n    return atcoder::mcf_graph<Cap, Cost>::add_edge(from, to, cap, Cost{0});\n  }\n\n  int add_edge(int from, int to, Cap cap, Cost cost)\n  {\n    return atcoder::mcf_graph<Cap, Cost>::add_edge(from, to, cap, cost + infty);\n  }\n\n  pair<Cap, Cost> flow(int s, int t)\n  {\n    return flow(s, t, std::numeric_limits<Cap>::max());\n  }\n\n  pair<Cap, Cost> flow(int s, int t, Cap flow_limit)\n  {\n    return slope(s, t, flow_limit).back();\n  }\n\n  vector<pair<Cap, Cost>> slope(int s, int t)\n  {\n    return slope(s, t, numeric_limits<Cap>::max());\n  }\n\n  vector<pair<Cap, Cost>> slope(int s, int t, Cap flow_limit)\n  {\n    auto res{atcoder::mcf_graph<Cap, Cost>::slope(s, t, flow_limit)};\n    for (auto &[cap, cost] : res)\n    {\n      cost -= cap * infty;\n    }\n    return res;\n  }\n\n  typename atcoder::mcf_graph<Cap, Cost>::edge get_edge(int i)\n  {\n    auto res{atcoder::mcf_graph<Cap, Cost>::get_edge(i)};\n    res.cost -= infty;\n    return res;\n  }\n\n  vector<typename atcoder::mcf_graph<Cap, Cost>::edge> edges()\n  {\n    auto res{atcoder::mcf_graph<Cap, Cost>::edges()};\n    for (auto &e : res)\n    {\n      e.cost -= infty;\n    }\n    return res;\n  }\n};\nostream &operator<<(ostream &os, typename atcoder::mcf_graph<ll, ll>::edge const &edge)\n{\n  return os << \"from: \" << edge.from << \", to: \" << edge.to << \", cap: \" << edge.cap << \", flow: \" << edge.flow << \", cost: \" << edge.cost;\n}\n// ----- StronglyConnectedComponents -----\nusing StronglyConnectedComponents = atcoder::scc_graph;\n// ----- TwoSat -----\nusing TwoSat = atcoder::two_sat;\n/***************************************************\n    My Library / DP-Typical\n ***************************************************/\n// ----- LongestIncreasingSubsequence -----\ntemplate <typename T>\nclass LongestIncreasingSubsequence\n{\n  struct Cache_LIS\n  {\n    typename vector<T>::iterator it;\n    T value;\n  };\n\n  int n; // fixed\n  T infty;\n  vector<T> dp;\n  stack<Cache_LIS> st;\n\npublic:\n  LongestIncreasingSubsequence() {}\n  LongestIncreasingSubsequence(int n, T infty = numeric_limits<T>::max()) : n{n}, infty{infty}, dp(n, infty) {}\n\n  int query(T a)\n  {\n    auto it{lower_bound(dp.begin(), dp.end(), a)};\n    auto value{*it};\n    st.push(Cache_LIS{it, value});\n    *it = a;\n    return lower_bound(dp.begin(), dp.end(), infty) - dp.begin();\n  }\n\n  bool rollback()\n  {\n    if (st.empty())\n    {\n      return false;\n    }\n    auto const &c{st.top()};\n    *c.it = c.value;\n    st.pop();\n    return true;\n  }\n\nprivate:\n};\n/***************************************************\n    My Library / Graphs\n ***************************************************/\n// ----- LowestCommonAncestor -----\nclass LowestCommonAncestor\n{\n  // helper classes\n  struct Edge\n  {\n    // Initialized by initializer list. Take care for the order of the field.\n    int src, dst;\n    ll cost;\n  };\n\n  struct Vertex\n  {\n    int depth;\n    ll length;\n  };\n\n  // fields\n  int N, root, L;\n  vector<vector<Edge>> E;\n  vector<Vertex> V;\n  vector<vector<int>> ancestors;\n\n  // methods\npublic:\n  LowestCommonAncestor(int N, int root = 0);\n  void add_edge(int a, int b, ll c = 0);\n  void init();\n  void init(int root); // after adding all edges.\n\n  // LowestCommonAncestor\n  int operator()(int a, int b);\n\n  int depth(int a, int b) { return V[a].depth + V[b].depth - 2 * V[(*this)(a, b)].depth; }\n  int depth(int v) { return depth(v, root); }\n  ll length(int a, int b) { return V[a].length + V[b].length - 2 * V[(*this)(a, b)].length; }\n  ll length(int v) { return length(v, root); }\n  int parent(int v) { return ancestors[v][0]; }\n\nprivate:\n  void dfs(int v, int d = 0, ll l = 0, int p = -1);\n};\n// LowestCommonAncestor: implement\nLowestCommonAncestor::LowestCommonAncestor(int N, int root) : N{N}, root{root}, L{0}, E(N), V(N)\n{\n  while ((1 << L) < N)\n  {\n    ++L;\n  }\n  ancestors = vector<vector<int>>(N + 1, vector<int>(L, N));\n}\nvoid LowestCommonAncestor::add_edge(int a, int b, ll c)\n{\n  E[a].push_back(LowestCommonAncestor::Edge{a, b, c});\n  E[b].push_back(LowestCommonAncestor::Edge{b, a, c});\n}\nvoid LowestCommonAncestor::init(int root)\n{\n  LowestCommonAncestor::root = root;\n  init();\n}\nvoid LowestCommonAncestor::init()\n{\n  dfs(root);\n  for (auto i = 0; i < L - 1; i++)\n  {\n    for (auto v = 0; v < N; v++)\n    {\n      if (ancestors[v][i] != -1)\n      {\n        ancestors[v][i + 1] = ancestors[ancestors[v][i]][i];\n      }\n    }\n  }\n}\nint LowestCommonAncestor::operator()(int a, int b)\n{\n  if (V[a].depth > V[b].depth)\n  {\n    swap(a, b);\n  }\n  int gap = V[b].depth - V[a].depth;\n  for (auto i = L - 1; i >= 0; i--)\n  {\n    int len{1 << i};\n    if (gap >= len)\n    {\n      gap -= len;\n      b = ancestors[b][i];\n    }\n  }\n  if (a == b)\n  {\n    return a;\n  }\n  for (auto i = L - 1; i >= 0; i--)\n  {\n    int na{ancestors[a][i]};\n    int nb{ancestors[b][i]};\n    if (na != nb)\n    {\n      a = na;\n      b = nb;\n    }\n  }\n  return ancestors[a][0];\n}\nvoid LowestCommonAncestor::dfs(int v, int d, ll l, int p)\n{\n  if (p != -1)\n  {\n    ancestors[v][0] = p;\n  }\n  V[v].depth = d;\n  V[v].length = l;\n  for (auto const &e : E[v])\n  {\n    int u{e.dst};\n    if (u == p)\n    {\n      continue;\n    }\n    dfs(u, d + 1, l + e.cost, v);\n  }\n}\n// ----- WarshallFloyd -----\ntemplate <typename T>\nvoid WarshallFloyd(vector<vector<T>> &V, T infinity = numeric_limits<T>::max())\n{\n  // It is valid to apply this method for\n  //  - a directed/undirected graph,\n  //  - a graph whose edge may be negative.\n  //    - Negative cycle can be detected by V[i][i] < 0 if we initialize V[i][i] = 0.\n  auto N{static_cast<int>(V.size())};\n  for (auto k{0}; k < N; ++k)\n  {\n    for (auto i{0}; i < N; ++i)\n    {\n      for (auto j{0}; j < N; ++j)\n      {\n        if (V[i][k] == infinity || V[k][j] == infinity)\n        {\n          continue;\n        }\n        ch_min(V[i][j], V[i][k] + V[k][j]);\n      }\n    }\n  }\n}\n/***************************************************\n    My Library / Math\n ***************************************************/\n// ----- Permutation -----\nstruct Permutation\n{\n  vector<int> V;\n\n  Permutation() {}\n  Permutation(vector<int> const &V) : V{V} {}\n\n  static Permutation unit(size_t N)\n  {\n    vector<int> X(N);\n    for (auto i = 0; i < static_cast<int>(N); ++i)\n    {\n      X[i] = i;\n    }\n    return Permutation{X};\n  }\n\n  size_t size() const { return V.size(); }\n  int operator[](size_t i) const { return V[i]; }\n\n  Permutation inverse() const\n  {\n    vector<int> Q(size());\n    for (auto i = 0; i < static_cast<int>(size()); ++i)\n    {\n      Q[(*this)[i]] = i;\n    }\n    return Permutation{Q};\n  }\n\n  Permutation operator*(Permutation const &Q) const\n  {\n    assert(size() == Q.size());\n    vector<int> R(size());\n    for (auto i = 0; i < static_cast<int>(size()); ++i)\n    {\n      R[i] = (*this)[Q[i]];\n    }\n    return Permutation{R};\n  }\n\n  Permutation &operator*=(Permutation const &Q)\n  {\n    return *this = *this * Q;\n  }\n\n  Permutation pow(int n)\n  {\n    if (n == 0)\n    {\n      return unit(size());\n    }\n    if (n & 1)\n    {\n      auto W{pow(n / 2)};\n      return W * W;\n    }\n    return *this * pow(n - 1);\n  }\n};\n// ----- Mat (matrix) and Vec -----\ntemplate <typename T = ll>\nusing Vec = vector<T>;\ntemplate <typename T = ll>\nusing Mat = Vec<Vec<T>>;\n// operators of Vec / Mat\ntemplate <typename T = ll>\nVec<T> operator+(Vec<T> const &A)\n{\n  return A;\n}\ntemplate <typename T = ll>\nVec<T> &operator+=(Vec<T> &A, Vec<T> const &B)\n{\n  assert(A.size() == B.size());\n  for (auto i = size_t{0}; i < A.size(); i++)\n  {\n    A[i] += B[i];\n  }\n  return A;\n}\ntemplate <typename T = ll>\nVec<T> &operator+=(Vec<T> &A, T K)\n{\n  for (auto i = size_t{0}; i < A.size(); i++)\n  {\n    A[i] += K;\n  }\n  return A;\n}\ntemplate <typename T = ll>\nVec<T> operator+(Vec<T> const &A, Vec<T> const &B)\n{\n  auto C{A};\n  C += B;\n  return C;\n}\ntemplate <typename T = ll>\nVec<T> operator+(Vec<T> const &A, T K)\n{\n  auto C{A};\n  C += K;\n  return C;\n}\ntemplate <typename T = ll>\nVec<T> operator+(T K, Vec<T> const &A)\n{\n  return A + K;\n}\ntemplate <typename T = ll>\nVec<T> operator-(Vec<T> const &A)\n{\n  Vec<T> C(A.size());\n  for (auto i = size_t{0}; i < A.size(); i++)\n  {\n    C[i] = -A[i];\n  }\n  return C;\n}\ntemplate <typename T = ll>\nVec<T> &operator-=(Vec<T> &A, Vec<T> const &B)\n{\n  return A += (-B);\n}\ntemplate <typename T = ll>\nVec<T> &operator-=(Vec<T> &A, T K)\n{\n  return A += (-K);\n}\ntemplate <typename T = ll>\nVec<T> operator-(Vec<T> const &A, Vec<T> const &B)\n{\n  return A + (-B);\n}\ntemplate <typename T = ll>\nVec<T> operator-(Vec<T> const &A, T K)\n{\n  return A + (-K);\n}\ntemplate <typename T = ll>\nVec<T> operator-(T K, Vec<T> const &A)\n{\n  return K + (-A);\n}\ntemplate <typename T = ll>\nVec<T> &operator*=(Vec<T> &A, T K)\n{\n  for (auto i = size_t{0}; i < A.size(); i++)\n  {\n    A[i] *= K;\n  }\n  return A;\n}\ntemplate <typename T = ll>\nVec<T> operator*(T K, Vec<T> const &A)\n{\n  auto C{A};\n  C *= K;\n  return C;\n}\ntemplate <typename T = ll>\nVec<T> operator*(Vec<T> const &A, T K)\n{\n  return K * A;\n}\ntemplate <typename T = ll>\nVec<T> &operator/=(Vec<T> &A, T K)\n{\n  return A *= (1 / K);\n}\ntemplate <typename T = ll>\nVec<T> operator/(Vec<T> const &A, T K)\n{\n  return A * (1 / K);\n}\ntemplate <typename T = ll>\nVec<T> &operator++(Vec<T> &A)\n{\n  for (auto i = size_t{0}; i < A.size(); i++)\n  {\n    ++A[i];\n  }\n  return A;\n}\ntemplate <typename T = ll>\nVec<T> operator++(Vec<T> &A, int)\n{\n  auto C{A};\n  ++A;\n  return C;\n}\ntemplate <typename T = ll>\nVec<T> &operator--(Vec<T> &A)\n{\n  for (auto i = size_t{0}; i < A.size(); i++)\n  {\n    --A[i];\n  }\n  return A;\n}\ntemplate <typename T = ll>\nVec<T> operator--(Vec<T> &A, int)\n{\n  auto C{A};\n  --A;\n  return C;\n}\n// generator of unit matrix\n// call example: Mat<T> A{unit_matrix<T>(s)};\ntemplate <typename T = ll>\nMat<T> UnitMatrix(size_t s)\n{\n  Mat<T> res(s, Vec<T>(s, T{0}));\n  for (auto i = size_t{0}; i < s; ++i)\n  {\n    res[i][i] = T{1};\n  }\n  return res;\n}\n// multiply operators\ntemplate <typename T = ll>\nMat<T> operator*(Mat<T> const &A, Mat<T> const &B)\n{\n  assert(A.front().size() == B.size());\n  Mat<T> C(A.size(), Vec<T>(B.front().size()));\n  for (auto i = size_t{0}; i < A.size(); i++)\n  {\n    for (auto j = size_t{0}; j < B.front().size(); j++)\n    {\n      for (auto k = size_t{0}; k < A.front().size(); k++)\n      {\n        C[i][j] += A[i][k] * B[k][j];\n      }\n    }\n  }\n  return C;\n}\ntemplate <typename T = ll>\nMat<T> &operator*=(Mat<T> &A, Mat<T> const &B)\n{\n  auto C{A * B};\n  return A = C;\n}\ntemplate <typename T = ll>\nVec<T> operator*(Mat<T> const &A, Vec<T> const &V)\n{\n  assert(A.front().size() == V.size());\n  Vec<T> W(A.size());\n  for (auto i = size_t{0}; i < A.size(); i++)\n  {\n    for (auto j = size_t{0}; j < A.front().size(); j++)\n    {\n      W[i] += A[i][j] * V[j];\n    }\n  }\n  return W;\n}\ntemplate <typename T = ll>\nMat<T> Power(Mat<T> const &A, ll n)\n{\n  assert(A.size() == A.front().size());\n  if (n == 0)\n  {\n    return UnitMatrix<T>(A.size());\n  }\n  if (n & 1)\n  {\n    return A * pow(A, n - 1);\n  }\n  auto B{pow(A, n / 2)};\n  return B * B;\n}\n// Transpose\ntemplate <typename T = ll>\nMat<T> Transpose(Mat<T> const &A)\n{\n  Mat<T> C(A.front().size(), Vec<T>(A.size()));\n  for (auto i = size_t{0}; i < A.size(); i++)\n  {\n    for (auto j = size_t{0}; j < A.front().size(); j++)\n    {\n      C[j][i] = A[i][j];\n    }\n  }\n  return C;\n}\n/***************************************************\n    My Library / Numbers\n ***************************************************/\n// ----- Sieve -----\nclass Sieve\n{\n  static constexpr ll MAX_SIZE{1000010LL};\n  ll N;\n  vector<ll> f;\n  vector<ll> prime_nums;\n\npublic:\n  Sieve(ll N = MAX_SIZE) : N{N}, f(N, 0), prime_nums{}\n  {\n    f[0] = f[1] = -1;\n    for (auto i = 2; i < N; i++)\n    {\n      if (f[i])\n      {\n        continue;\n      }\n      prime_nums.push_back(i);\n      f[i] = i;\n      for (auto j = 2 * i; j < N; j += i)\n      {\n        if (!f[j])\n        {\n          f[j] = i;\n        }\n      }\n    }\n  }\n\n  bool is_prime(ll x) const\n  { // 2 \\leq x \\leq MAX_SIZE^2\n    if (x < N)\n    {\n      return f[x] == x;\n    }\n    for (auto e : prime_nums)\n    {\n      if (x % e == 0)\n      {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  vector<ll> const &primes() const\n  {\n    return prime_nums;\n  }\n\n  vector<ll> factor_list(ll x) const\n  {\n    if (x < 2)\n    {\n      return {};\n    }\n    vector<ll> res;\n    auto it{prime_nums.begin()};\n    if (x < N)\n    {\n      while (x != 1)\n      {\n        res.push_back(f[x]);\n        x /= f[x];\n      }\n    }\n    else\n    {\n      while (x != 1 && it != prime_nums.end())\n      {\n        if (x % *it == 0)\n        {\n          res.push_back(*it);\n          x /= *it;\n        }\n        else\n        {\n          ++it;\n        }\n      }\n      if (x != 1)\n      {\n        res.push_back(x);\n      }\n    }\n    return res;\n  }\n\n  vector<tuple<ll, ll>> factor(ll x) const\n  {\n    if (x < 2)\n    {\n      return {};\n    }\n    auto factors{factor_list(x)};\n    vector<tuple<ll, ll>> res{make_tuple(factors[0], 0)};\n    for (auto x : factors)\n    {\n      if (x == get<0>(res.back()))\n      {\n        get<1>(res.back())++;\n      }\n      else\n      {\n        res.emplace_back(x, 1);\n      }\n    }\n    return res;\n  }\n};\n// ----- EulerNums -----\nclass EulerNums\n{\n  static constexpr ll MAX_SIZE{1000010LL};\n  ll N;\n  vector<ll> table;\n\npublic:\n  EulerNums(ll N = MAX_SIZE) : N{N}\n  {\n    table.resize(N);\n    for (auto i = 0; i < N; i++)\n    {\n      table[i] = i;\n    }\n    for (auto i = 2; i < N; i++)\n    {\n      if (table[i] == i)\n      {\n        for (auto j = i; j < N; j += i)\n        {\n          table[j] = table[j] / i * (i - 1);\n        }\n      }\n    }\n  }\n\n  ll euler(ll n)\n  {\n    if (n < N)\n    {\n      return table[N];\n    }\n    else\n    {\n      ll res{n};\n      for (auto i = 2LL; i * i <= n; i++)\n      {\n        if (n % i == 0)\n        {\n          res = res / i * (i - 1);\n        }\n        for (; n % i == 0; n /= i)\n        {\n        }\n      }\n      if (n != 1)\n      {\n        res = res / n * (n - 1);\n      }\n      return res;\n    }\n  }\n};\nclass LinearMod\n{\n  vector<ll> A, B, M;\n\npublic:\n  LinearMod() {}\n\n  void add(ll a, ll b, ll m)\n  {\n    A.push_back(a);\n    B.push_back(b);\n    M.push_back(m);\n  }\n\n  tuple<ll, ll> get()\n  {\n    assert(A.size() == B.size() && B.size() == M.size());\n    ll x{0}, m{1};\n    for (auto i = size_t{0}; i < A.size(); i++)\n    {\n      ll a{A[i] * m};\n      ll b{B[i] - A[i] * x};\n      ll d{gcd(M[i], a)};\n      if (b % d != 0)\n      {\n        return make_tuple(0, -1);\n      }\n      ll t{b / d * mod_inverse(a / d, M[i] / d) % (M[i] / d)};\n      x = x + m * t;\n      m *= M[i] / d;\n    }\n    return make_tuple(x % m, m);\n  }\n\nprivate:\n  static ll extra_gcd(ll a, ll b, ll &x, ll &y)\n  {\n    ll d{a};\n    if (b != 0)\n    {\n      d = extra_gcd(b, a % b, y, x);\n      y -= (a / b) * x;\n    }\n    else\n    {\n      x = 1;\n      y = 0;\n    }\n    return d;\n  }\n\n  static ll mod_inverse(ll a, ll m)\n  {\n    ll x, y;\n    extra_gcd(a, m, x, y);\n    return (m + x % m) % m;\n  }\n};\n/***************************************************\n    My Library / Tools\n ***************************************************/\n// ----- Compressor -----\ntemplate <typename T = ll>\nclass Compressor\n{\n  vector<T> raw;\n  map<T, int> index;\n\npublic:\n  Compressor() {}\n\n  template <typename Container>\n  Compressor(Container const &V) { append(V); }\n\n  template <typename Iter>\n  Compressor(Iter first, Iter last) { append(first, last); }\n\n  template <typename Container>\n  void append(Container const &V) { append(V.begin(), V.end()); }\n\n  template <typename Iter>\n  void append(Iter first, Iter last)\n  {\n    set<T> S(first, last);\n    raw = vector<T>(S.begin(), S.end());\n    sort(raw.begin(), raw.end());\n    for (auto i = size_t{0}; i < raw.size(); ++i)\n    {\n      index[raw[i]] = i;\n    }\n  }\n\n  T to_raw(int i) { return raw[i]; }\n  int to_index(T t) { return index[t]; }\n};\n// ----- RunLengthCompress -----\ntemplate <typename T>\nauto RunLengthCompress(T const &S) -> vector<tuple<remove_const_t<remove_reference_t<decltype(S[0])>>, int>>\n{\n  using U = remove_const_t<remove_reference_t<decltype(S[0])>>;\n  vector<tuple<U, int>> res;\n  U c{S[0]};\n  int x{0};\n  for (auto e : S)\n  {\n    if (c == e)\n    {\n      ++x;\n    }\n    else\n    {\n      res.emplace_back(c, x);\n      c = e;\n      x = 1;\n    }\n  }\n  res.emplace_back(c, x);\n  return res;\n}\n// ----- Make 2D, 3D, 4D Vectors -----\ntemplate <typename T>\nvector<vector<T>> Make2DVector(size_t d0, size_t d1, T v = T{})\n{\n  return vector<vector<T>>(d0, vector<T>(d1, v));\n}\ntemplate <typename T>\nvector<vector<vector<T>>> Make3DVector(size_t d0, size_t d1, size_t d2, T v = T{})\n{\n  return vector<vector<vector<T>>>(d0, Make2DVector(d1, d2, v));\n}\ntemplate <typename T>\nvector<vector<vector<vector<T>>>> Make4DVector(size_t d0, size_t d1, size_t d2, size_t d3, T v = T{})\n{\n  return vector<vector<vector<vector<T>>>>(d0, Make3DVector(d1, d2, d3, v));\n}\n// ----- vector istream and ostream -----\ntemplate <typename T>\nistream &operator>>(istream &is, vector<T> &v)\n{\n  for (auto it{v.begin()}; it != v.end(); ++it)\n  {\n    is >> *it;\n  }\n  return is;\n}\ntemplate <typename T>\nistream &operator>>(istream &is, vector<vector<T> *> &&v)\n{\n  for (auto it{v.begin()}; it + 1 != v.end(); ++it)\n  {\n    assert((*it)->size() == (*(it + 1))->size());\n  }\n  auto s{(*v.begin())->size()};\n  for (auto i{size_t{0}}; i < s; ++i)\n  {\n    for (auto it{v.begin()}; it != v.end(); ++it)\n    {\n      cin >> (**it)[i];\n    }\n  }\n  return is;\n}\ntemplate <typename T, typename U>\nostream &FlushVector(vector<T> const &v, U const &s = \"\\n\", ostream &os = cout)\n{\n  for (auto it{v.begin()}; it != v.end(); ++it)\n  {\n    os << *it;\n    if (it + 1 != v.end())\n    {\n      os << s;\n    }\n  }\n  return os;\n}\ntemplate <typename T>\nostream &operator<<(ostream &os, vector<T> const &v)\n{\n  return FlushVector(v, \"\\n\", os);\n}\n/***************************************************\n    Frequently Used Structures\n ***************************************************/\n// ----- Constants -----\n// constexpr double epsilon{1e-10};\n// constexpr ll infty{1'000'000'000'000'010LL}; // or\n// constexpr int infty{1'000'000'010};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n/***************************************************\n    Solutions\n ***************************************************/\n\n// ----- Solve -----\n\nclass Solve\n{\n  ll N, K, M;\n  Combination<mint> C;\n\npublic:\n  Solve()\n  {\n    cin >> N >> K;\n    M = 2 * N + 1;\n  }\n\n  void flush()\n  {\n    auto p{prob()};\n    cout << 1 - p / 2 << endl;\n  }\n\nprivate:\n  mint prob()\n  {\n    mint ans{0};\n    for (auto a{0}; M - 2 * a - 1 > 0; ++a)\n    {\n      for (auto b{0}; b <= M; ++b)\n      {\n        if (b % 2 != 0)\n        {\n          continue;\n        }\n        ll one{(M - 2 * a - 1 - b) / 2};\n        if (one <= 0)\n        {\n          break;\n        }\n        mint m_one{one};\n        auto p{m_one / (m_one + b) * (2 * a + 1) / (2 * a + 1 + b + 1)};\n        auto q{C(one + b, K)};\n        auto c{C(M, one) - C(M, one - 1)};\n#if DEBUG == 1\n        if (N == 1)\n        {\n          cerr << \"a = \" << a << \", b = \" << b << endl;\n          cerr << \"p = \" << p << \", q = \" << q << \", c = \" << c << endl;\n        }\n#endif\n        ans += p * q * c;\n      }\n    }\n    for (auto a{0}; M - 2 * a > 0; ++a)\n    {\n      for (auto b{0}; b <= M; ++b)\n      {\n        if (b % 2 != 1)\n        {\n          continue;\n        }\n        ll one{(M - 2 * a - b) / 2};\n        if (one <= 0)\n        {\n          break;\n        }\n        mint m_one{one};\n        auto p{m_one / (m_one + b) * (2 * a + 1) / (2 * a + b + 1)};\n        auto q{C(one + b, K)};\n        auto c{C(M, one) - C(M, one - 1)};\n#if DEBUG == 1\n        if (N == 1)\n        {\n          cerr << \"a = \" << a << \", b = \" << b << endl;\n          cerr << \"p = \" << p << \", q = \" << q << \", c = \" << c << endl;\n        }\n#endif\n        ans += p * q * c;\n      }\n    }\n    return ans / C(M, K) / mint{2}.pow(M - K);\n  }\n};\n\n// ----- main() -----\n\nint main()\n{\n  Solve solve;\n  solve.flush();\n}\n", "meta": {"hexsha": "582c576fd5bf55b12892be4e066f6fb619f6c703", "size": 25287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2021/0530_AGC053/F.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2021/0530_AGC053/F.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "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/0530_AGC053/F.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 20.8466611707, "max_line_length": 139, "alphanum_fraction": 0.4959069878, "num_tokens": 7995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5464247043504}}
{"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/TrustRegion.h\"\nusing namespace Scine::Molassembler;\n\nstruct Himmelblau {\n  double operator() (const Eigen::VectorXd& parameters) {\n    assert(parameters.size() == 2);\n\n    const double x = parameters(0);\n    const double y = parameters(1);\n\n    const double firstBracket = (x * x + y - 11);\n    const double secondBracket = (x + y * y - 7);\n\n    return firstBracket * firstBracket + secondBracket * secondBracket;\n  }\n\n  void operator() (\n    const Eigen::VectorXd& parameters,\n    double& value,\n    Eigen::Ref<Eigen::VectorXd> gradient,\n    Eigen::Ref<Eigen::MatrixXd> hessian\n  ) {\n    assert(parameters.size() == 2);\n    assert(gradient.size() == 2);\n    assert(hessian.cols() == 2 && hessian.rows() == 2);\n\n    const double x = parameters(0);\n    const double y = parameters(1);\n\n    const double firstBracket = (x * x + y - 11);\n    const double secondBracket = (x + y * y - 7);\n\n    value = firstBracket * firstBracket + secondBracket * secondBracket;\n\n    gradient(0) = 4 * x * firstBracket + 2 * secondBracket;\n    gradient(1) = 4 * y * secondBracket + 2 * firstBracket;\n\n    hessian(0, 0) = 8 * x * x + 4 * firstBracket + 2;\n    hessian(1, 1) = 8 * y * y + 4 * secondBracket + 2;\n    hessian(0, 1) = 4 * x + 4 * y;\n    hessian(1, 0) = hessian(0, 1);\n  }\n\n  bool shouldContinue(\n    const unsigned iteration,\n    const double /* value */,\n    const Eigen::VectorXd& gradient\n  ) {\n    return (\n      iteration <= 1000\n      && gradient.squaredNorm() > 1e-3\n    );\n  }\n};\n\nBOOST_AUTO_TEST_CASE(TrustRegionNewton, *boost::unit_test::label(\"Temple\")) {\n  Eigen::VectorXd parameters = Eigen::VectorXd::Random(2);\n  Eigen::VectorXd passParameters = parameters;\n\n  auto optimizationResult = Temple::TrustRegionOptimizer<>::minimize(\n    parameters,\n    Himmelblau {},\n    Himmelblau {}\n  );\n\n  BOOST_CHECK_MESSAGE(\n    std::fabs(optimizationResult.value) <= 1e-5,\n    \"Newton-Raphson trust region does not find minimization of Himmelblau function, value is \"\n    << optimizationResult.value << \" after \" << optimizationResult.iterations\n    << \" iterations at \" << parameters.transpose() << \". Gradient norm is \" << optimizationResult.gradient.norm()\n  );\n}\n", "meta": {"hexsha": "4b75670b77c865ba9ba0aa4230bdc495ca2c2b36", "size": 2432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Temple/Optimization/TrustRegionNewton.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/TrustRegionNewton.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/TrustRegionNewton.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.024691358, "max_line_length": 113, "alphanum_fraction": 0.6509046053, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5464246763152416}}
{"text": "// Copyright (c) 2020 Chris Richardson & Matthew Scroggs\n// FEniCS Project\n// SPDX-License-Identifier:    MIT\n\n#include \"nedelec.h\"\n#include \"dof-permutations.h\"\n#include \"lagrange.h\"\n#include \"moments.h\"\n#include \"polyset.h\"\n#include \"quadrature.h\"\n#include \"raviart-thomas.h\"\n#include <Eigen/Dense>\n#include <numeric>\n#include <vector>\n\nusing namespace libtab;\n\nnamespace\n{\n//-----------------------------------------------------------------------------\nEigen::MatrixXd create_nedelec_2d_space(int degree)\n{\n  // Number of order (degree) vector polynomials\n  const int nv = degree * (degree + 1) / 2;\n\n  // Number of order (degree-1) vector polynomials\n  const int ns0 = (degree - 1) * degree / 2;\n\n  // Number of additional polynomials in Nedelec set\n  const int ns = degree;\n\n  // Tabulate polynomial set at quadrature points\n  auto [Qpts, Qwts]\n      = quadrature::make_quadrature(cell::type::triangle, 2 * degree);\n  Eigen::ArrayXXd Pkp1_at_Qpts\n      = polyset::tabulate(cell::type::triangle, degree, 0, Qpts)[0];\n\n  const int psize = Pkp1_at_Qpts.cols();\n\n  // Create coefficients for order (degree-1) vector polynomials\n  Eigen::MatrixXd wcoeffs = Eigen::MatrixXd::Zero(nv * 2 + ns, psize * 2);\n  wcoeffs.block(0, 0, nv, nv) = Eigen::MatrixXd::Identity(nv, nv);\n  wcoeffs.block(nv, psize, nv, nv) = Eigen::MatrixXd::Identity(nv, nv);\n\n  // Create coefficients for the additional Nedelec polynomials\n  for (int i = 0; i < ns; ++i)\n  {\n    for (int k = 0; k < psize; ++k)\n    {\n      wcoeffs(2 * nv + i, k) = (Qwts * Pkp1_at_Qpts.col(ns0 + i) * Qpts.col(1)\n                                * Pkp1_at_Qpts.col(k))\n                                   .sum();\n      wcoeffs(2 * nv + i, k + psize) = (-Qwts * Pkp1_at_Qpts.col(ns0 + i)\n                                        * Qpts.col(0) * Pkp1_at_Qpts.col(k))\n                                           .sum();\n    }\n  }\n\n  return wcoeffs;\n}\n//-----------------------------------------------------------------------------\nEigen::MatrixXd create_nedelec_2d_dual(int degree)\n{\n  // Number of dofs and size of polynomial set P(k+1)\n  const int ndofs = 3 * degree + degree * (degree - 1);\n  const int psize = (degree + 1) * (degree + 2) / 2;\n\n  // Dual space\n  Eigen::MatrixXd dual = Eigen::MatrixXd::Zero(ndofs, psize * 2);\n\n  // dof counter\n  const int quad_deg = 5 * degree;\n\n  // Integral representation for the boundary (edge) dofs\n  dual.block(0, 0, 3 * degree, psize * 2)\n      = moments::make_tangent_integral_moments(\n          create_dlagrange(cell::type::interval, degree - 1),\n          cell::type::triangle, 2, degree, quad_deg);\n\n  if (degree > 1)\n  {\n    // Interior integral moment\n    dual.block(3 * degree, 0, degree * (degree - 1), psize * 2)\n        = moments::make_integral_moments(\n            create_dlagrange(cell::type::triangle, degree - 2),\n            cell::type::triangle, 2, degree, quad_deg);\n  }\n\n  return dual;\n}\n//-----------------------------------------------------------------------------\nstd::vector<Eigen::MatrixXd> create_nedelec_2d_base_perms(int degree)\n{\n  const int ndofs = degree * (degree + 2);\n  std::vector<Eigen::MatrixXd> base_permutations(\n      3, Eigen::MatrixXd::Identity(ndofs, ndofs));\n\n  Eigen::ArrayXi edge_ref = dofperms::interval_reflection(degree);\n  for (int edge = 0; edge < 3; ++edge)\n  {\n    const int start = edge_ref.size() * edge;\n    for (int i = 0; i < edge_ref.size(); ++i)\n    {\n      base_permutations[edge](start + i, start + i) = 0;\n      base_permutations[edge](start + i, start + edge_ref[i]) = 1;\n    }\n  }\n\n  Eigen::ArrayXXd edge_dir\n      = dofperms::interval_reflection_tangent_directions(degree);\n  for (int edge = 0; edge < 3; ++edge)\n  {\n    Eigen::MatrixXd directions = Eigen::MatrixXd::Identity(ndofs, ndofs);\n    directions.block(edge_dir.rows() * edge, edge_dir.cols() * edge,\n                     edge_dir.rows(), edge_dir.cols())\n        = edge_dir;\n    base_permutations[edge] *= directions;\n  }\n\n  return base_permutations;\n}\n//-----------------------------------------------------------------------------\nEigen::MatrixXd create_nedelec_3d_space(int degree)\n{\n  // Reference tetrahedron\n  const int tdim = 3;\n\n  // Number of order (degree) vector polynomials\n  const int nv = degree * (degree + 1) * (degree + 2) / 6;\n\n  // Number of order (degree-1) vector polynomials\n  const int ns0 = (degree - 1) * degree * (degree + 1) / 6;\n  // Number of additional Nedelec polynomials that could be added\n  const int ns = degree * (degree + 1) / 2;\n  // Number of polynomials that would be included that are not independent so\n  // are removed\n  const int ns_remove = degree * (degree - 1) / 2;\n\n  // Number of dofs in the space, ie size of polynomial set\n  const int ndofs = 6 * degree + 4 * degree * (degree - 1)\n                    + (degree - 2) * (degree - 1) * degree / 2;\n\n  // Tabulate polynomial basis at quadrature points\n  auto [Qpts, Qwts]\n      = quadrature::make_quadrature(cell::type::tetrahedron, 2 * degree);\n  Eigen::ArrayXXd Pkp1_at_Qpts\n      = polyset::tabulate(cell::type::tetrahedron, degree, 0, Qpts)[0];\n  const int psize = Pkp1_at_Qpts.cols();\n\n  // Create coefficients for order (degree-1) polynomials\n  Eigen::MatrixXd wcoeffs = Eigen::MatrixXd::Zero(ndofs, psize * tdim);\n  for (int i = 0; i < tdim; ++i)\n  {\n    wcoeffs.block(nv * i, psize * i, nv, nv)\n        = Eigen::MatrixXd::Identity(nv, nv);\n  }\n\n  // Create coefficients for additional Nedelec polynomials\n  for (int i = 0; i < ns; ++i)\n  {\n    for (int k = 0; k < psize; ++k)\n    {\n      const double w = (Qwts * Pkp1_at_Qpts.col(ns0 + i) * Qpts.col(2)\n                        * Pkp1_at_Qpts.col(k))\n                           .sum();\n      // Don't include polynomials (*, *, 0) that are dependant\n      if (i >= ns_remove)\n        wcoeffs(tdim * nv + i - ns_remove, psize + k) = -w;\n      wcoeffs(tdim * nv + i + ns - ns_remove, k) = w;\n    }\n  }\n\n  for (int i = 0; i < ns; ++i)\n  {\n    for (int k = 0; k < psize; ++k)\n    {\n      const double w = (Qwts * Pkp1_at_Qpts.col(ns0 + i) * Qpts.col(1)\n                        * Pkp1_at_Qpts.col(k))\n                           .sum();\n      wcoeffs(tdim * nv + i + ns * 2 - ns_remove, k) = -w;\n      // Don't include polynomials (*, *, 0) that are dependant\n      if (i >= ns_remove)\n        wcoeffs(tdim * nv + i - ns_remove, psize * 2 + k) = w;\n    }\n  }\n\n  for (int i = 0; i < ns; ++i)\n  {\n    for (int k = 0; k < psize; ++k)\n    {\n      const double w = (Qwts * Pkp1_at_Qpts.col(ns0 + i) * Qpts.col(0)\n                        * Pkp1_at_Qpts.col(k))\n                           .sum();\n      wcoeffs(tdim * nv + i + ns - ns_remove, psize * 2 + k) = -w;\n      wcoeffs(tdim * nv + i + ns * 2 - ns_remove, psize + k) = w;\n    }\n  }\n\n  return wcoeffs;\n}\n//-----------------------------------------------------------------------------\nEigen::MatrixXd create_nedelec_3d_dual(int degree)\n{\n  const int tdim = 3;\n\n  // Size of polynomial set P(k+1)\n  const int psize = (degree + 1) * (degree + 2) * (degree + 3) / 6;\n\n  // Work out number of dofs\n  const int ndofs = 6 * degree + 4 * degree * (degree - 1)\n                    + (degree - 2) * (degree - 1) * degree / 2;\n  Eigen::MatrixXd dual = Eigen::MatrixXd::Zero(ndofs, psize * tdim);\n\n  // Create quadrature scheme on the edge\n  const int quad_deg = 5 * degree;\n\n  // Integral representation for the boundary (edge) dofs\n  dual.block(0, 0, 6 * degree, psize * 3)\n      = moments::make_tangent_integral_moments(\n          create_dlagrange(cell::type::interval, degree - 1),\n          cell::type::tetrahedron, 3, degree, quad_deg);\n\n  if (degree > 1)\n  {\n    // Integral moments on faces\n    dual.block(6 * degree, 0, 4 * (degree - 1) * degree, psize * 3)\n        = moments::make_integral_moments(\n            create_dlagrange(cell::type::triangle, degree - 2),\n            cell::type::tetrahedron, 3, degree, quad_deg);\n  }\n\n  if (degree > 2)\n  {\n    // Interior integral moment\n    dual.block(6 * degree + 4 * degree * (degree - 1), 0,\n               (degree - 2) * (degree - 1) * degree / 2, psize * 3)\n        = moments::make_integral_moments(\n            create_dlagrange(cell::type::tetrahedron, degree - 3),\n            cell::type::tetrahedron, 3, degree, quad_deg);\n  }\n\n  return dual;\n}\n//-----------------------------------------------------------------------------\nstd::vector<Eigen::MatrixXd> create_nedelec_3d_base_perms(int degree)\n{\n  const int ndofs = 6 * degree + 4 * degree * (degree - 1)\n                    + (degree - 2) * (degree - 1) * degree / 2;\n  std::vector<Eigen::MatrixXd> base_permutations(\n      14, Eigen::MatrixXd::Identity(ndofs, ndofs));\n\n  Eigen::ArrayXi edge_ref = dofperms::interval_reflection(degree);\n  for (int edge = 0; edge < 6; ++edge)\n  {\n    const int start = edge_ref.size() * edge;\n    for (int i = 0; i < edge_ref.size(); ++i)\n    {\n      base_permutations[edge](start + i, start + i) = 0;\n      base_permutations[edge](start + i, start + edge_ref[i]) = 1;\n    }\n  }\n  Eigen::ArrayXi face_rot = dofperms::triangle_rotation(degree - 1);\n  Eigen::ArrayXi face_ref = dofperms::triangle_reflection(degree - 1);\n  for (int face = 0; face < 4; ++face)\n  {\n    const int start = edge_ref.size() * 6 + face_ref.size() * 2 * face;\n    for (int i = 0; i < face_rot.size(); ++i)\n    {\n      for (int b = 0; b < 2; ++b)\n      {\n        const int p = 6 + 2 * face;\n        const int p1 = start + 2 * i + b;\n        base_permutations[p](p1, start + i * 2 + b) = 0;\n        base_permutations[p](p1, start + face_rot[i] * 2 + b) = 1;\n        base_permutations[p + 1](p1, start + i * 2 + b) = 0;\n        base_permutations[p + 1](p1, start + face_ref[i] * 2 + b) = 1;\n      }\n    }\n  }\n\n  Eigen::ArrayXXd edge_dir\n      = dofperms::interval_reflection_tangent_directions(degree);\n  for (int edge = 0; edge < 6; ++edge)\n  {\n    Eigen::MatrixXd directions = Eigen::MatrixXd::Identity(ndofs, ndofs);\n    directions.block(edge_dir.rows() * edge, edge_dir.cols() * edge,\n                     edge_dir.rows(), edge_dir.cols())\n        = edge_dir;\n    base_permutations[edge] *= directions;\n  }\n\n  // Faces\n  Eigen::ArrayXXd face_dir_ref\n      = dofperms::triangle_reflection_tangent_directions(degree - 1);\n  Eigen::ArrayXXd face_dir_rot\n      = dofperms::triangle_rotation_tangent_directions(degree - 1);\n  for (int face = 0; face < 4; ++face)\n  {\n    // Rotate face\n    Eigen::MatrixXd rotation = Eigen::MatrixXd::Identity(ndofs, ndofs);\n    rotation.block(edge_dir.rows() * 6 + face_dir_rot.rows() * face,\n                   edge_dir.cols() * 6 + face_dir_rot.rows() * face,\n                   face_dir_rot.rows(), face_dir_rot.cols())\n        = face_dir_rot;\n    base_permutations[6 + 2 * face] *= rotation;\n\n    // Reflect face\n    Eigen::MatrixXd reflection = Eigen::MatrixXd::Identity(ndofs, ndofs);\n    reflection.block(edge_dir.rows() * 6 + face_dir_ref.rows() * face,\n                     edge_dir.cols() * 6 + face_dir_ref.rows() * face,\n                     face_dir_ref.rows(), face_dir_ref.cols())\n        = face_dir_ref;\n    base_permutations[6 + 2 * face + 1] *= reflection;\n  }\n\n  return base_permutations;\n}\n\n//-----------------------------------------------------------------------------\nEigen::MatrixXd create_nedelec2_2d_dual(int degree)\n{\n  // Number of dofs and size of polynomial set P(k+1)\n  const int ndofs = (degree + 1) * (degree + 2);\n  const int psize = (degree + 1) * (degree + 2) / 2;\n\n  // Dual space\n  Eigen::MatrixXd dual = Eigen::MatrixXd::Zero(ndofs, psize * 2);\n\n  // dof counter\n  int quad_deg = 5 * degree;\n\n  // Integral representation for the boundary (edge) dofs\n  dual.block(0, 0, 3 * (degree + 1), psize * 2)\n      = moments::make_tangent_integral_moments(\n          create_dlagrange(cell::type::interval, degree), cell::type::triangle,\n          2, degree, quad_deg);\n\n  if (degree > 1)\n  {\n    // Interior integral moment\n    dual.block(3 * (degree + 1), 0, (degree - 1) * (degree + 1), psize * 2)\n        = moments::make_dot_integral_moments(\n            create_rt(cell::type::triangle, degree - 1), cell::type::triangle,\n            2, degree, quad_deg);\n  }\n\n  return dual;\n}\n//-----------------------------------------------------------------------------\nEigen::MatrixXd create_nedelec2_3d_dual(int degree)\n{\n  const int tdim = 3;\n\n  // Size of polynomial set P(k+1)\n  const int psize = (degree + 1) * (degree + 2) * (degree + 3) / 6;\n\n  // Work out number of dofs\n  const int ndofs = (degree + 1) * (degree + 2) * (degree + 3) / 2;\n\n  Eigen::MatrixXd dual = Eigen::MatrixXd::Zero(ndofs, psize * tdim);\n\n  // Create quadrature scheme on the edge\n  int quad_deg = 5 * degree;\n\n  // Integral representation for the boundary (edge) dofs\n  dual.block(0, 0, 6 * (degree + 1), psize * 3)\n      = moments::make_tangent_integral_moments(\n          create_dlagrange(cell::type::interval, degree),\n          cell::type::tetrahedron, 3, degree, quad_deg);\n\n  if (degree > 1)\n  {\n    // Integral moments on faces\n    dual.block(6 * (degree + 1), 0, 4 * (degree - 1) * (degree + 1), psize * 3)\n        = moments::make_dot_integral_moments(\n            create_rt(cell::type::triangle, degree - 1),\n            cell::type::tetrahedron, 3, degree, quad_deg);\n  }\n\n  if (degree > 2)\n  {\n    // Interior integral moment\n    dual.block((6 + 4 * (degree - 1)) * (degree + 1), 0,\n               (degree - 1) * (degree - 2) * (degree + 1) / 2, psize * 3)\n        = moments::make_integral_moments(\n            create_dlagrange(cell::type::tetrahedron, degree - 2),\n            cell::type::tetrahedron, 3, degree, quad_deg);\n  }\n\n  return dual;\n}\n\n} // namespace\n\n//-----------------------------------------------------------------------------\nFiniteElement libtab::create_nedelec(cell::type celltype, int degree,\n                                     const std::string& name)\n{\n  Eigen::MatrixXd wcoeffs;\n  Eigen::MatrixXd dual;\n  std::vector<Eigen::MatrixXd> perms;\n  std::vector<Eigen::MatrixXd> directions;\n  if (celltype == cell::type::triangle)\n  {\n    wcoeffs = create_nedelec_2d_space(degree);\n    dual = create_nedelec_2d_dual(degree);\n    perms = create_nedelec_2d_base_perms(degree);\n  }\n  else if (celltype == cell::type::tetrahedron)\n  {\n    wcoeffs = create_nedelec_3d_space(degree);\n    dual = create_nedelec_3d_dual(degree);\n    perms = create_nedelec_3d_base_perms(degree);\n  }\n  else\n    throw std::runtime_error(\"Invalid celltype in Nedelec\");\n\n  // Nedelec has d dofs on each edge, d(d-1) on each face\n  // and d(d-1)(d-2)/2 on the interior in 3D\n  const std::vector<std::vector<std::vector<int>>> topology\n      = cell::topology(celltype);\n  std::vector<std::vector<int>> entity_dofs(topology.size());\n  entity_dofs[0].resize(topology[0].size(), 0);\n  entity_dofs[1].resize(topology[1].size(), degree);\n  entity_dofs[2].resize(topology[2].size(), degree * (degree - 1));\n  const int tdim = cell::topological_dimension(celltype);\n  if (tdim > 2)\n    entity_dofs[3] = {degree * (degree - 1) * (degree - 2) / 2};\n\n  const Eigen::MatrixXd coeffs = compute_expansion_coefficients(wcoeffs, dual);\n  return FiniteElement(name, celltype, degree, {tdim}, coeffs, entity_dofs,\n                       perms);\n}\n//-----------------------------------------------------------------------------\nFiniteElement libtab::create_nedelec2(cell::type celltype, int degree,\n                                      const std::string& name)\n{\n  const int tdim = cell::topological_dimension(celltype);\n  const int psize = polyset::dim(celltype, degree);\n  Eigen::MatrixXd wcoeffs\n      = Eigen::MatrixXd::Identity(tdim * psize, tdim * psize);\n\n  Eigen::MatrixXd dual;\n  if (celltype == cell::type::triangle)\n    dual = create_nedelec2_2d_dual(degree);\n  else if (celltype == cell::type::tetrahedron)\n    dual = create_nedelec2_3d_dual(degree);\n  else\n    throw std::runtime_error(\"Invalid celltype in Nedelec\");\n\n  // TODO: Implement base permutations\n  const std::vector<std::vector<std::vector<int>>> topology\n      = cell::topology(celltype);\n  const int ndofs = dual.rows();\n  int perm_count = 0;\n  for (int i = 1; i < tdim; ++i)\n    perm_count += topology[i].size() * i;\n  std::vector<Eigen::MatrixXd> base_permutations(\n      perm_count, Eigen::MatrixXd::Identity(ndofs, ndofs));\n\n  const Eigen::MatrixXd coeffs = compute_expansion_coefficients(wcoeffs, dual);\n\n  // Nedelec(2nd kind) has (d+1) dofs on each edge, (d+1)(d-1) on each face\n  // and (d-2)(d-1)(d+1)/2 on the interior in 3D\n  std::vector<std::vector<int>> entity_dofs(topology.size());\n  entity_dofs[0].resize(topology[0].size(), 0);\n  entity_dofs[1].resize(topology[1].size(), degree + 1);\n  entity_dofs[2].resize(topology[2].size(), (degree + 1) * (degree - 1));\n  if (tdim > 2)\n    entity_dofs[3] = {(degree - 2) * (degree - 1) * (degree + 1) / 2};\n\n  return FiniteElement(name, celltype, degree, {tdim}, coeffs, entity_dofs,\n                       base_permutations);\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "a918c7c20aea12152163d550c6126d97d2157558", "size": 16879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/nedelec.cpp", "max_stars_repo_name": "chrisrichardson/libtab", "max_stars_repo_head_hexsha": "1f6593409bf51427bd6d8d1036bb885f5fbb7a8c", "max_stars_repo_licenses": ["MIT"], "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/nedelec.cpp", "max_issues_repo_name": "chrisrichardson/libtab", "max_issues_repo_head_hexsha": "1f6593409bf51427bd6d8d1036bb885f5fbb7a8c", "max_issues_repo_licenses": ["MIT"], "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/nedelec.cpp", "max_forks_repo_name": "chrisrichardson/libtab", "max_forks_repo_head_hexsha": "1f6593409bf51427bd6d8d1036bb885f5fbb7a8c", "max_forks_repo_licenses": ["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.4600840336, "max_line_length": 79, "alphanum_fraction": 0.5761004799, "num_tokens": 4999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5462821252301475}}
{"text": "#pragma once\n\n#include <boost/multiprecision/gmp.hpp>\n#include <math.h>\n#include <time.h>\n\n#include \"FiniteFields.hpp\"\n#include \"FastFourierTransform.hpp\"\n\nnamespace ligero {\ntemplate <typename FieldT>\nclass \t\tSecretSharing {\n\tpublic:\n\t\t/* Constructors allowing some flexibility in the choice of domains */\n\t\tSecretSharing(size_t lSecretLength, size_t kDegree, size_t nShares) : lSecretLength_(lSecretLength), kDegree_(kDegree), nNumberShares_(nShares) {\n\t\t\t// In this implementation, we use an evaluation domain that is twice the size of the number of shares, and we discard\n\t\t\tthis->dCompositeDomainSize_ = nShares;\n\t\t};\n\n\t\tint share(FieldT *secret);\n\t\tint reconstruct(FieldT *eval, bool expanded = false);\n\n\t\tint padMany(FieldT *secrets, size_t lrows);\n\t\tint padIntrablocRandomnessMany(FieldT *secret, size_t lrows);\n\t\tint shareMany(FieldT *secrets, size_t lrows);\n\t\tint reconstructMany(FieldT *secrets, size_t lrows);\n\n\t\tbool degreeTest(FieldT *eval);\n\t\tbool zeroTest(FieldT *eval, bool expanded = false);\n\t\tbool zeroSumTest(FieldT *eval);\n\n\tprotected:\n\t\tint padSecret(FieldT *secret);\n\t\tint padPolynominal(FieldT *secret);\n\t\tint padShares(FieldT *secret);\n\t\tint padIntrablocRandomness(FieldT *secret);\n\n\t\tsize_t\tlSecretLength_;\n\t\tsize_t\tkDegree_;\n\t\tsize_t\tnNumberShares_;\n\t\tsize_t\tdCompositeDomainSize_;\n\t\tstd::vector<FieldT> rootsOfUnity_;\n};\n\ntemplate <typename FieldT>\nint SecretSharing<FieldT>::padSecret(FieldT *secret) {\n\tFieldT::randomVector(secret + this->lSecretLength_, this->kDegree_ - this->lSecretLength_, true);\n\treturn 0;\n}\n\ntemplate <typename FieldT>\nint SecretSharing<FieldT>::padIntrablocRandomness(FieldT *secret) {\n\tfor (size_t i = this->lSecretLength_; i < kDegree_ ;i++) {\n\t\tsecret[i] = FieldT(0); \n\t}\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\nint SecretSharing<FieldT>::padPolynominal(FieldT *secret) {\n\tfor (size_t i = this->kDegree_; i < nNumberShares_;i++) {\n\t\tsecret[i] = FieldT(0);\n\t}\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\nint SecretSharing<FieldT>::padShares(FieldT *secret) {\n\tfor (size_t i = this->nNumberShares_; i < dCompositeDomainSize_ ;i++) {\n\t\tsecret[i] = FieldT(0);\n\t}\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\nint SecretSharing<FieldT>::padMany(FieldT *secret, size_t lrows) {\n\n\t// Add randomness for padding\n\tfor (size_t i = 0; i < lrows; i++) {\n\t\tthis->padSecret(secret + i * this->nNumberShares_);\n\t}\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\nint SecretSharing<FieldT>::padIntrablocRandomnessMany(FieldT *secret, size_t lrows) {\n\n\t// Add randomness for padding\n\tfor (size_t i = 0; i < lrows; i++) {\n\t\tthis->padIntrablocRandomness(secret + i * this->nNumberShares_);\n\t}\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\nint SecretSharing<FieldT>::share(FieldT *secret) {\n\n\t// Interpolate a polynomial of degree k for the secret\n    iFFT<FieldT>(secret, kDegree_, rootsOfUnity_);\n\n\t// Evaluate the polynomial on a coset within the composite domain (size numberShares)\n\tthis->padPolynominal(secret);\n\tFFT<FieldT>(secret, nNumberShares_, FieldT(FieldT::getOmega(nNumberShares_)), rootsOfUnity_);\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\ninline int SecretSharing<FieldT>::reconstruct(FieldT *eval, bool expandedDegree) {\n\tsize_t degree = kDegree_;\n\tiFFT<FieldT>(eval, nNumberShares_, FieldT(FieldT::getOmega(nNumberShares_)), rootsOfUnity_);\n\n\tif (expandedDegree) {\n\t\tfor (size_t i = 0; i < kDegree_; i++) {eval[i] = eval[i] + eval[i + kDegree_];}\n\t}\n\n    FFT<FieldT>(eval, degree, rootsOfUnity_);\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\nbool SecretSharing<FieldT>::degreeTest(FieldT *eval) {\n\n\tstd::vector<FieldT> localCopy(eval, eval + this->nNumberShares_);\n\tiFFT<FieldT>(&localCopy[0], nNumberShares_, FieldT::getOmega(nNumberShares_), rootsOfUnity_);\n\n\tfor (size_t i = kDegree_; i < nNumberShares_; i++) {\n\t\tif (!(localCopy[i] == FieldT(0))) {\n\t\t\tDBG(\"val:\"<< localCopy[i].getValue() << \",degree>\" << i);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\ntemplate <typename FieldT>\nbool SecretSharing<FieldT>::zeroTest(FieldT *eval, bool largerDegree) {\n\n\tstd::vector<FieldT> localCopy(eval, eval + this->nNumberShares_);\n\treconstruct(&localCopy[0], largerDegree);\n\n\tfor (size_t i = 0; i < this->lSecretLength_; i++) {\n\t\tif (!(localCopy[i] == FieldT(0))) return false;\n\t}\n\n\treturn true;\n}\n\ntemplate <typename FieldT>\nbool SecretSharing<FieldT>::zeroSumTest(FieldT *eval) {\n\t\n\tstd::vector<FieldT> localCopy(eval, eval+ this->nNumberShares_);\n\treconstruct(&localCopy[0], true);\n\n\tFieldT sum = FieldT(0);\n\tfor (size_t i = 0; i < this->lSecretLength_; i++) {\n\t\tsum += localCopy[i];\n\t}\n\n\tif (sum == FieldT(0)) return true;\n\telse return false;\n}\n\ntemplate <typename FieldT>\nint SecretSharing<FieldT>::shareMany(FieldT *secret, size_t lrows) {\n\n\t// std::cout << \"Performing FFTs: \" << lrows << std::endl; \n\tfor (size_t i = 0; i < lrows; i++) {\n\t\tshare(secret + i * this->nNumberShares_);\n\t}\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\nint SecretSharing<FieldT>::reconstructMany(FieldT *secret, size_t lrows) {\n\n\tfor (size_t i = 0; i < lrows; i++) {\n\t\treconstruct(secret + i * this->nNumberShares_);\n\t}\n\n\treturn 0;\n}\n\n\n}\n", "meta": {"hexsha": "1dc354885cdde57a61ee44b55946c5a371235652", "size": 5049, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/SecretSharing.hpp", "max_stars_repo_name": "Eleven-Z/LigeroRSA", "max_stars_repo_head_hexsha": "17d8b3d00604da1e0272035e871fac3add8d7551", "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/SecretSharing.hpp", "max_issues_repo_name": "Eleven-Z/LigeroRSA", "max_issues_repo_head_hexsha": "17d8b3d00604da1e0272035e871fac3add8d7551", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-09T05:48:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-09T05:48:09.000Z", "max_forks_repo_path": "include/SecretSharing.hpp", "max_forks_repo_name": "Eleven-Z/LigeroRSA", "max_forks_repo_head_hexsha": "17d8b3d00604da1e0272035e871fac3add8d7551", "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.0257731959, "max_line_length": 147, "alphanum_fraction": 0.7130124777, "num_tokens": 1448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461006, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5462821235464068}}
{"text": "// error_policies_example.cpp\r\n\r\n// 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#include <boost/math/distributions/normal.hpp>\r\n  using boost::math::normal_distribution;\r\n\r\n#include <boost/math/distributions/students_t.hpp>\r\n   using boost::math::students_t;  // Probability of students_t(df, t).\r\n   using boost::math::students_t_distribution;\r\n\r\n//  using namespace boost::math;\r\n//.\\error_policy_normal.cpp(30) : error C2872: 'policy' : ambiguous symbol\r\n//        could be 'I:\\Boost-sandbox\\math_toolkit\\boost/math/policies/policy.hpp(392) : boost::math::policies::policy'\r\n//        or 'boost::math::policies'\r\n\r\n  // So can't use this using namespace command.\r\n// Suppose we want a statistical distribution to return infinities,\r\n// rather than throw exceptions (the default policy), then we can use:\r\n\r\n// std\r\n#include <iostream>\r\n   using std::cout;\r\n   using std::endl;\r\n\r\nusing boost::math::policies::policy;\r\n// Possible errors\r\nusing boost::math::policies::overflow_error;\r\nusing boost::math::policies::underflow_error;\r\nusing boost::math::policies::domain_error;\r\nusing boost::math::policies::pole_error;\r\nusing boost::math::policies::denorm_error;\r\nusing boost::math::policies::evaluation_error;\r\n\r\nusing boost::math::policies::ignore_error;\r\n\r\n// Define a custom policy to ignore just overflow:\r\ntypedef policy<\r\noverflow_error<ignore_error>\r\n      > my_policy;\r\n\r\n// Define another custom policy (perhaps ill-advised?)\r\n// to ignore all errors: domain, pole, overflow, underflow, denorm & evaluation:\r\ntypedef policy<\r\ndomain_error<ignore_error>,\r\npole_error<ignore_error>,\r\noverflow_error<ignore_error>,\r\nunderflow_error<ignore_error>,\r\ndenorm_error<ignore_error>,\r\nevaluation_error<ignore_error>\r\n      > my_ignoreall_policy;\r\n\r\n// Define a new distribution with a custom policy to ignore_error\r\n// (& thus perhaps return infinity for some arguments):\r\ntypedef boost::math::normal_distribution<double, my_policy> my_normal;\r\n// Note: uses default parameters zero mean and unit standard deviation.\r\n\r\n// We could also do the same for another distribution, for example:\r\nusing boost::math::students_t_distribution;\r\ntypedef students_t_distribution<double, my_ignoreall_policy> my_students_t;\r\n\r\nint main()\r\n{\r\n  cout << \"quantile(my_normal(), 0.05); = \" << quantile(my_normal(), 0.05) << endl; // 0.05 is argument within normal range.\r\n  cout << \"quantile(my_normal(), 0.); = \" << quantile(my_normal(), 0.) << endl; // argument zero, so expect infinity.\r\n  cout << \"quantile(my_normal(), 0.); = \" << quantile(my_normal(), 0.F) << endl; // argument zero, so expect infinity.\r\n\r\n  cout << \"quantile(my_students_t(), 0.); = \" << quantile(my_students_t(-1), 0.F) << endl; // 'bad' argument negative, so expect NaN.\r\n\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n  // Construct a (0, 1) normal distribution that ignores all errors,\r\n  // returning NaN, infinity, zero, or best guess,\r\n  // and NOT setting errno.\r\n  normal_distribution<long double, my_ignoreall_policy> my_normal2(0.L, 1.L); // explicit parameters for distribution.\r\n  cout << \"quantile(my_normal2(), 0.); = \" << quantile(my_normal2, 0.01) << endl; // argument 0.01, so result finite.\r\n  cout << \"quantile(my_normal2(), 0.); = \" << quantile(my_normal2, 0.) << endl; // argument zero, so expect infinity.\r\n#endif\r\n\r\n  return 0;\r\n}\r\n\r\n/*\r\n\r\nOutput:\r\n\r\nquantile(my_normal(), 0.05); = -1.64485\r\nquantile(my_normal(), 0.); = -1.#INF\r\nquantile(my_normal(), 0.); = -1.#INF\r\nquantile(my_students_t(), 0.); = 1.#QNAN\r\nquantile(my_normal2(), 0.); = -2.32635\r\nquantile(my_normal2(), 0.); = -1.#INF\r\n\r\n*/\r\n", "meta": {"hexsha": "28fd8ff50074b589d05f2c7d3d53117cbd2d445a", "size": 3800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/error_policies_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": 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/error_policies_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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/example/error_policies_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": 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.0, "max_line_length": 134, "alphanum_fraction": 0.7044736842, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5462146125380583}}
{"text": "//  (C) Copyright Eric Niebler 2005.\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// Test case for weighted_extended_p_square.hpp\n\n#include <iostream>\n#include <boost/random.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/numeric/functional/vector.hpp>\n#include <boost/accumulators/numeric/functional/complex.hpp>\n#include <boost/accumulators/numeric/functional/valarray.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/weighted_extended_p_square.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace boost::accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    typedef accumulator_set<double, stats<tag::weighted_extended_p_square>, double> accumulator_t;\n\n    // problem with small results: epsilon is relative (in percent), not absolute\n\n    // tolerance in %\n    double epsilon = 1;\n\n    // some random number generators\n    double mu1 = -1.0;\n    double mu2 =  1.0;\n    boost::lagged_fibonacci607 rng;\n    boost::normal_distribution<> mean_sigma1(mu1, 1);\n    boost::normal_distribution<> mean_sigma2(mu2, 1);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal1(rng, mean_sigma1);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal2(rng, mean_sigma2);\n\n    std::vector<double> probs_uniform, probs_normal1, probs_normal2, probs_normal_exact1, probs_normal_exact2;\n\n    double p1[] = {/*0.001,*/ 0.01, 0.1, 0.5, 0.9, 0.99, 0.999};\n    probs_uniform.assign(p1, p1 + sizeof(p1) / sizeof(double));\n\n    double p2[] = {0.001, 0.025};\n    double p3[] = {0.975, 0.999};\n    probs_normal1.assign(p2, p2 + sizeof(p2) / sizeof(double));\n    probs_normal2.assign(p3, p3 + sizeof(p3) / sizeof(double));\n\n    double p4[] = {-3.090232, -1.959963};\n    double p5[] = {1.959963, 3.090232};\n    probs_normal_exact1.assign(p4, p4 + sizeof(p4) / sizeof(double));\n    probs_normal_exact2.assign(p5, p5 + sizeof(p5) / sizeof(double));\n\n    accumulator_t acc_uniform(extended_p_square_probabilities = probs_uniform);\n    accumulator_t acc_normal1(extended_p_square_probabilities = probs_normal1);\n    accumulator_t acc_normal2(extended_p_square_probabilities = probs_normal2);\n\n    for (std::size_t i = 0; i < 100000; ++i)\n    {\n        acc_uniform(rng(), weight = 1.);\n\n        double sample1 = normal1();\n        double sample2 = normal2();\n        acc_normal1(sample1, weight = std::exp(-mu1 * (sample1 - 0.5 * mu1)));\n        acc_normal2(sample2, weight = std::exp(-mu2 * (sample2 - 0.5 * mu2)));\n    }\n\n    // check for uniform distribution\n    BOOST_CHECK_CLOSE(weighted_extended_p_square(acc_uniform)[0], probs_uniform[0], 6*epsilon);\n    BOOST_CHECK_CLOSE(weighted_extended_p_square(acc_uniform)[1], probs_uniform[1], 3*epsilon);\n    BOOST_CHECK_CLOSE(weighted_extended_p_square(acc_uniform)[2], probs_uniform[2], epsilon);\n    BOOST_CHECK_CLOSE(weighted_extended_p_square(acc_uniform)[3], probs_uniform[3], epsilon);\n    BOOST_CHECK_CLOSE(weighted_extended_p_square(acc_uniform)[4], probs_uniform[4], epsilon);\n    BOOST_CHECK_CLOSE(weighted_extended_p_square(acc_uniform)[5], probs_uniform[5], epsilon);\n\n    // check for standard normal distribution\n    for (std::size_t i = 0; i < probs_normal1.size(); ++i)\n    {\n        BOOST_CHECK_CLOSE(weighted_extended_p_square(acc_normal1)[i], probs_normal_exact1[i], epsilon);\n        BOOST_CHECK_CLOSE(weighted_extended_p_square(acc_normal2)[i], probs_normal_exact2[i], epsilon);\n    }\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"weighted_extended_p_square test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n\n", "meta": {"hexsha": "e13b0e3b1b353ea71f44c24334eb174db434c428", "size": 4139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/accumulators/test/weighted_extended_p_square.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/accumulators/test/weighted_extended_p_square.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/accumulators/test/weighted_extended_p_square.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": 40.9801980198, "max_line_length": 115, "alphanum_fraction": 0.6987194975, "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.546214607905598}}
{"text": "\n#include \"catch.hpp\"\n\n#include \"FringeGraph.h\"\n#include \"FringeSearch.h\"\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/erdos_renyi_generator.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/random_device.hpp>\n\n#include <cmath> \n\n// Number of graphs to compare shortest paths on\nstatic const unsigned int NUM_TEST_GRAPHS = 1000;\n// Number of nodes per test graph\nstatic const unsigned int NODES_PER_TEST_GRAPH = 1000;\n// The Erdos-Renyi input parameter\nstatic const float ER_PARAMETER = 0.005;\n\ntypedef boost::adjacency_list< boost::listS, boost::vecS, boost::directedS, boost::no_property, boost::property < boost::edge_weight_t, float > > graph_t;\ntypedef boost::erdos_renyi_iterator<boost::minstd_rand, graph_t> er_generator_t;\ntypedef boost::graph_traits < graph_t >::vertex_descriptor vertex_descriptor;\n\nTEST_CASE(\"Fringe search returns the same paths as Boost's Dijkstra implementation on random graphs\") {\n\n    boost::random_device rd;\n    boost::minstd_rand gen(rd);\n    SECTION(\"Generate a random graph and compare paths\") {\n        for (unsigned int i = 0; i < NUM_TEST_GRAPHS; i++) {\n            graph_t g(er_generator_t(gen, NODES_PER_TEST_GRAPH, ER_PARAMETER), er_generator_t(), NODES_PER_TEST_GRAPH);\n\n            // Set random weights\n            auto unweightedEdges = boost::edges(g);\n            for (auto eit = unweightedEdges.first; eit != unweightedEdges.second; eit++) {\n                float weight = 10.0f * (gen() - gen.min()) / (gen.max() - gen.min());\n                boost::put(boost::edge_weight_t(), g, *eit, weight);\n            }\n\n            std::vector<vertex_descriptor> predecessors(num_vertices(g));\n            std::vector<float> distances(num_vertices(g));\n            vertex_descriptor source(boost::vertex(0, g));\n            boost::dijkstra_shortest_paths(g, source,\n                                           boost::predecessor_map(&predecessors[0]).distance_map(&distances[0]));\n\n            std::vector<vertex_descriptor> path;\n            vertex_descriptor target(boost::vertex(NODES_PER_TEST_GRAPH - 1, g));\n\n            // Check that the target was reachable\n            if (predecessors[target] != target) {\n                vertex_descriptor current = target;\n                while (current != source) {\n                    path.push_back(current);\n                    current = predecessors[current];\n                }\n            }\n\n            // Convert boost graph to fringe search graph\n\n            // Create nodes\n            std::vector<FringeNode<void>* > fringeNodes;\n            for (unsigned int n = 0; n < NODES_PER_TEST_GRAPH; n++) {\n                fringeNodes.push_back(new FringeNode<void>(n));\n            }\n\n            // Convert edges\n            auto edges = boost::edges(g);\n            edge_id_t currentId = 0;\n            for (auto eit = edges.first; eit != edges.second; eit++) {\n                float weight = boost::get(boost::edge_weight_t(), g, *eit);\n                FringeNode<void> *edgeSource = fringeNodes[(*eit).m_source];\n                FringeNode<void> *edgeTarget = fringeNodes[(*eit).m_target];\n                FringeEdge<void> *edge = new FringeEdge<void>(currentId++, edgeSource, edgeTarget, weight);\n            }\n\n            FringeSearch search(fringeNodes[0]);\n            FringeNode<void> * fringeTarget = fringeNodes[NODES_PER_TEST_GRAPH - 1];\n            std::vector<BaseFringeNode *> *fringePath = search.search(fringeTarget);\n\n            if (path.size() == 0) {\n                // If the target was not reachable, no path should be output\n                REQUIRE(fringePath == nullptr);\n            } else {\n                REQUIRE(fringePath != nullptr);\n                float weightDifference = abs(distances[target] - search.cost(fringeTarget));\n                std::cout<< weightDifference << std::endl;\n                REQUIRE(weightDifference < 1E-6);\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "3d7883c73d79c438721d171857a3bbf378406e83", "size": 4031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/GraphFuzzingTest.cpp", "max_stars_repo_name": "Konijnendijk/C-Fringe-Search", "max_stars_repo_head_hexsha": "8cd9f2189165c2e36765847d974e07a6c767cfa9", "max_stars_repo_licenses": ["BSL-1.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": "test/GraphFuzzingTest.cpp", "max_issues_repo_name": "Konijnendijk/C-Fringe-Search", "max_issues_repo_head_hexsha": "8cd9f2189165c2e36765847d974e07a6c767cfa9", "max_issues_repo_licenses": ["BSL-1.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": "test/GraphFuzzingTest.cpp", "max_forks_repo_name": "Konijnendijk/C-Fringe-Search", "max_forks_repo_head_hexsha": "8cd9f2189165c2e36765847d974e07a6c767cfa9", "max_forks_repo_licenses": ["BSL-1.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": 42.8829787234, "max_line_length": 154, "alphanum_fraction": 0.6164723394, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.5461977883136009}}
{"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 sigma_point_additive_update_policy.hpp\n * \\date July 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#pragma once\n\n\n#include <Eigen/Dense>\n\n#include <fl/util/meta.hpp>\n#include <fl/util/traits.hpp>\n#include <fl/util/descriptor.hpp>\n#include <fl/filter/gaussian/transform/point_set.hpp>\n#include <fl/filter/gaussian/quadrature/sigma_point_quadrature.hpp>\n\nnamespace fl\n{\n\n// Forward declarations\ntemplate <typename...> class SigmaPointUpdatePolicy;\n\ntemplate <\n    typename SigmaPointQuadrature,\n    typename AdditiveSensorFunction\n>\nclass SigmaPointUpdatePolicy<\n          SigmaPointQuadrature,\n          Additive<AdditiveSensorFunction>>\n    : public Descriptor\n{\npublic:\n    typedef typename AdditiveSensorFunction::State State;\n    typedef typename AdditiveSensorFunction::Obsrv Obsrv;\n\n    enum : signed int\n    {\n        NumberOfPoints =\n            SigmaPointQuadrature::number_of_points(SizeOf<State>::Value)\n    };\n\n    typedef PointSet<State, NumberOfPoints> StatePointSet;\n    typedef PointSet<Obsrv, NumberOfPoints> ObsrvPointSet;\n\n    template <\n        typename Belief\n    >\n    void operator()(const AdditiveSensorFunction& obsrv_function,\n                    const SigmaPointQuadrature& quadrature,\n                    const Belief& prior_belief,\n                    const Obsrv& obsrv,\n                    Belief& posterior_belief)\n    {\n        auto&& h = [&](const State& x)\n        {\n           return obsrv_function.expected_observation(x);\n        };\n\n        quadrature.propergate_gaussian(h, prior_belief, X, Z);\n\n        auto&& prediction = Z.center();\n        auto&& Z_c = Z.points();\n        auto&& W = X.covariance_weights_vector();\n        auto&& X_c = X.centered_points();\n\n        auto innovation = (obsrv - prediction).eval();\n        auto cov_xx = (X_c * W.asDiagonal() * X_c.transpose()).eval();\n        auto cov_yy = (Z_c * W.asDiagonal() * Z_c.transpose()\n                       + obsrv_function.noise_covariance()).eval();\n        auto cov_xy = (X_c * W.asDiagonal() * Z_c.transpose()).eval();\n        auto K = (cov_xy * cov_yy.inverse()).eval();\n\n        posterior_belief.dimension(prior_belief.dimension());\n        posterior_belief.mean(X.mean() + K * innovation);\n        posterior_belief.covariance(cov_xx - K * cov_yy * K.transpose());\n    }\n\n    virtual std::string name() const\n    {\n        return \"SigmaPointUpdatePolicy<\"\n                + this->list_arguments(\n                       \"SigmaPointQuadrature\",\n                       \"Additive<AdditiveSensorFunction>\")\n                + \">\";\n    }\n\n    virtual std::string description() const\n    {\n        return \"Sigma Point based filter update policy for observation model\"\n               \" with additive noise\";\n    }\n\nprotected:\n    StatePointSet X;\n    ObsrvPointSet Z;\n};\n\n}\n\n\n\n", "meta": {"hexsha": "3a4c5ec1cd9183d90f192c7d2f8f188c455167c5", "size": 3219, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/filter/gaussian/update_policy/sigma_point_additive_update_policy.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/filter/gaussian/update_policy/sigma_point_additive_update_policy.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/filter/gaussian/update_policy/sigma_point_additive_update_policy.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": 27.75, "max_line_length": 79, "alphanum_fraction": 0.6352904629, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5461936225833639}}
{"text": "#include <Eigen/Dense>\n#include <map>\n#include <algorithm>\n#include <vector>\n\nint atom(int ao_index)\n{\n    int orbitals_per_atom=4;\n    return ao_index / orbitals_per_atom;\n}\n\nint indexOf(std::vector<std::string> my_list, std::string element)\n{\n    for(size_t i=0;i<my_list.size();i++)\n    {\n        if(element==my_list[i])\n        {\n            return i;\n        }\n    }\n    return -1;\n}\n\nbool list_contains(std::vector<std::string>  my_list, std::string element)\n{\n    bool found = 0;\n    for(size_t i=0;i<my_list.size();i++)\n    {\n        if(element==my_list[i])\n        {\n            found = 1;\n        }\n    }\n    return found;\n}\n\nstd::string orb(int ao_index, std::vector<std::string> orbital_types)\n{\n    int orbitals_per_atom=4;\n    int orb_index = ao_index % orbitals_per_atom;\n    return orbital_types[orb_index];\n}\n\nint ao_index(int atom_p, std::string orb_p, std::vector<std::string>  orbital_types)\n{\n        int orbitals_per_atom=4;\n        int p = atom_p * orbitals_per_atom;\n        p += indexOf(orbital_types,orb_p);\n        return p;\n}\n\nfloat chi_on_atom(std::string o1, std::string o2, std::string o3, std::vector<std::string> p_orbitals,double dipole)\n{\n    if(o1 == o2 && o3 == \"s\")\n        return 1.0;\n    bool o3_in_p_orbitals = list_contains(p_orbitals,o3);\n    if((o1 == o3 && o3_in_p_orbitals) && (o2 == \"s\"))\n        return dipole;\n    if ((o2 == o3 && o3_in_p_orbitals) && (o1 == \"s\"))\n        return dipole;\n    return 0.0;\n}\n\nEigen::MatrixXd fast_fock_matrix(Eigen::MatrixXd hamiltonian, Eigen::MatrixXd interaction, Eigen::MatrixXd rho,double dipole)\n{\n    std::vector<std::string> orbital_types ={\"s\",\"px\", \"py\", \"pz\"};\n    std::vector<std::string>  p_orbitals = {\"px\", \"py\", \"pz\"};\n    size_t ndof = hamiltonian.rows();\n    Eigen::MatrixXd fock_mat = hamiltonian;\n    //Hartree potential term\n    for(size_t p=0;p<ndof;p++)\n    {\n        for(auto orb_q: orbital_types)\n        {\n            int q = ao_index(atom(p), orb_q,orbital_types); // p & q on same atom\n            for(auto orb_t : orbital_types)\n            {\n                int t = ao_index(atom(p), orb_t,orbital_types); // p & t on same atom\n                float chi_pqt = chi_on_atom(orb(p,orbital_types), orb_q, orb_t,p_orbitals,dipole);\n                for(size_t r=0;r<ndof;r++)\n                {\n                    for(auto orb_s : orbital_types)\n                    {\n                        int s = ao_index(atom(r), orb_s,orbital_types); // r & s on same atom\n                        for(auto orb_u : orbital_types)\n                        {\n                            int u = ao_index(atom(r), orb_u,orbital_types); // r & u on same atom\n                            float chi_rsu = chi_on_atom(orb(r,orbital_types), orb_s, orb_u, p_orbitals,dipole);\n                            fock_mat(p,q) += 2.0 * chi_pqt * chi_rsu * interaction(t,u) * rho(r,s);\n                        }\n                    }\n                }\n            }\n        }   \n    }\n    //Fock exchange term\n    for(size_t p=0;p<ndof;p++)\n    {\n        for(auto orb_s: orbital_types)\n        {\n            int s = ao_index(atom(p), orb_s,orbital_types); // p & s on same atom\n            for(auto orb_u : orbital_types)\n            {\n                int u = ao_index(atom(p), orb_u,orbital_types); //p & u on same atom\n                float chi_psu = chi_on_atom(orb(p,orbital_types), orb_s, orb_u,p_orbitals,dipole);\n                for(size_t q=0; q<ndof; q++)\n                {\n                    for(auto orb_r : orbital_types)\n                    {\n                        int r = ao_index(atom(q), orb_r,orbital_types); // q & r on same atom\n                        for(auto orb_t : orbital_types)\n                        {\n                            int t = ao_index(atom(q), orb_t,orbital_types); //q & t on same atom\n                            float chi_rqt = chi_on_atom(orb_r, orb(q,orbital_types), orb_t, p_orbitals,dipole);\n                            fock_mat(p,q) -= chi_rqt * chi_psu * interaction(t,u) * rho(r,s);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return fock_mat;\n\n}\n\nint main(void)\n{\n    return 0;\n}", "meta": {"hexsha": "0edba0f97df547b1f87935a58ac6bc8183bab365", "size": 4161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fock_fast/fock_fast.cpp", "max_stars_repo_name": "MolSSI-Education/qm_2019_sss_6", "max_stars_repo_head_hexsha": "48b2a8229bd09ab61f7e50530a39acfc081f47b1", "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": "fock_fast/fock_fast.cpp", "max_issues_repo_name": "MolSSI-Education/qm_2019_sss_6", "max_issues_repo_head_hexsha": "48b2a8229bd09ab61f7e50530a39acfc081f47b1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T20:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-31T05:09:01.000Z", "max_forks_repo_path": "fock_fast/fock_fast.cpp", "max_forks_repo_name": "MolSSI-Education/qm_2019_sss_6", "max_forks_repo_head_hexsha": "48b2a8229bd09ab61f7e50530a39acfc081f47b1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2019-07-23T20:14:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-31T03:47:36.000Z", "avg_line_length": 32.2558139535, "max_line_length": 125, "alphanum_fraction": 0.5222302331, "num_tokens": 1106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.5461936164378182}}
{"text": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing namespace boost::multiprecision;\n\ncpp_int dp[55][4004];\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, k, x;\n    while (cin >> k >> n >> x) {\n        cpp_int nom = 0;\n        if (x <= k * n && x >= n) {\n            for (int i = 0; i <= 50; i++)\n                for (int j = 0; j <= 4000; j++)\n                    dp[i][j] = 0;\n\n            dp[0][0] = 1;\n\n            for (int i = 1; i <= k; i++)\n                dp[1][i] = 1;\n\n            for (int i = 2; i <= n; i++) {\n                cpp_int ps = 0;\n                for (int j = i; j <= k * i; j++) {\n                    ps += dp[i - 1][j - 1];\n                    if (j - i >= k)ps -= dp[i - 1][j - k - 1];\n                    dp[i][j] = ps;\n                }\n            }\n            nom = dp[n][x];\n        }\n\n        cpp_int denom = 1;\n        for (int i = 1; i <= n; i++)denom *= k;\n\n        cout << nom << \"/\" << denom << endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "bc683f478d5606d9add17bf5090271b6afe5577b", "size": 1039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Mathematics/Probability Theory/Standard/Throw the Dice.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": "Mathematics/Probability Theory/Standard/Throw the Dice.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": "Mathematics/Probability Theory/Standard/Throw the Dice.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": 24.1627906977, "max_line_length": 62, "alphanum_fraction": 0.3580365736, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5461936142810986}}
{"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 \"FFT.hpp\"\n#include \"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 TruePeak\n{\n\n  using ArrayXcd = Eigen::ArrayXcd;\n\npublic:\n  TruePeak(index maxSize) : mFFT(maxSize), mIFFT(maxSize * 4) {}\n\n  void init(index size, double sampleRate)\n  {\n    using namespace std;\n    mSampleRate = sampleRate;\n    mFFTSize = static_cast<index>(pow(2, ceil(log(size) / log(2))));\n    mFactor = sampleRate < 96000 ? 4 : 2;\n    mFFT.resize(mFFTSize);\n    mIFFT.resize(mFFTSize * mFactor);\n    mBuffer = ArrayXcd::Zero((mFFTSize * mFactor / 2) + 1);\n  }\n\n  double processFrame(const RealVectorView& input)\n  {\n    using namespace Eigen;\n    ArrayXd in = _impl::asEigen<Array>(input);\n    if (mSampleRate >= 192000) { return in.abs().maxCoeff(); }\n    else\n    {\n      double   peak;\n      ArrayXcd transform = mFFT.process(in);\n      mBuffer.setZero();\n      mBuffer.segment(0, transform.size()) = transform;\n      ArrayXd result = mIFFT.process(mBuffer);\n      ArrayXd scaled = result / mFFTSize;\n      peak = scaled.abs().maxCoeff();\n      return peak;\n    }\n  }\n\nprivate:\n  FFT      mFFT;\n  IFFT     mIFFT;\n  ArrayXcd mBuffer;\n  double   mSampleRate{44100.0};\n  index    mFactor{4};\n  index    mFFTSize{1024};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "26e432f2e3e7b03db6dd83a0c53890e445858dee", "size": 1812, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/TruePeak.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/TruePeak.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/TruePeak.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 25.8857142857, "max_line_length": 74, "alphanum_fraction": 0.6810154525, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5461532639626059}}
{"text": "#pragma once\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <array>\n#include <vector>\n#include <stdexcept>\n#include <iterator>\n#include <random>\n\nusing boost::multiprecision::pow;\nusing boost::multiprecision::cpp_int;\n\nnamespace PRNG\n{\n    class PRNG {\n        public:\n            // Generates a pseudorandom unsigned bigint with a\n            // given number of bytes \n            virtual cpp_int random(unsigned int bits) = 0;\n\n            // Generates a 32 bit unsigned pseudorandom int\n            virtual unsigned int random32() = 0;\n\n            // Generates a 64 bit unsigned pseudorandom int\n            virtual unsigned long long random64() = 0;\n    };\n\n    class Xorshift32: public PRNG {\n        public:\n            void srand(unsigned int seed);\n            cpp_int random(unsigned int bits);\n            unsigned int random32();\n            unsigned long long random64();\n            \n        private:\n            unsigned int state;\n            unsigned int xorshift32();\n            cpp_int xorshift4096_32();\n    };\n\n    class Xorshift64: public PRNG {\n        public:\n            void srand(unsigned long long seed);\n            cpp_int random(unsigned int bits);\n            unsigned int random32();\n            unsigned long long random64();\n            \n        private:\n            unsigned long long state;\n            unsigned long long xorshift64();\n            cpp_int xorshift4096_64();\n    };\n\n    class Xorshift128: public PRNG {\n        public:\n            void srand(std::array<unsigned int, 4> seed);\n            cpp_int random(unsigned int bits);\n            unsigned int random32();\n            unsigned long long random64();\n\n        private:\n            std::array<unsigned int,4> state;\n            unsigned int xorshift128();\n            cpp_int xorshift4096_128();\n    };\n\n    class CMWC: public PRNG {\n        public:\n            CMWC();\n            cpp_int random(unsigned int bits);\n            unsigned int random32();\n            unsigned long long random64();\n        private:\n            static const unsigned int CYCLE = 4096;\n            static const unsigned int C_MAX = 809430660;\n\n            struct State {\n                std::array<unsigned int, CYCLE> Q;\n                unsigned int c;\n                unsigned int i;\n            };\n\n            State state;\n            std::random_device rd;\n            unsigned int randCMWC();\n            cpp_int randCMWC4096();\n\n    };\n}\n\n\n", "meta": {"hexsha": "2077a9a847038104b483212c5f063bfe657aa536", "size": 2441, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rng.hpp", "max_stars_repo_name": "oshogun/RNGs", "max_stars_repo_head_hexsha": "870868464b5db7a271d17c347c65898ba8e42a2d", "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/rng.hpp", "max_issues_repo_name": "oshogun/RNGs", "max_issues_repo_head_hexsha": "870868464b5db7a271d17c347c65898ba8e42a2d", "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/rng.hpp", "max_forks_repo_name": "oshogun/RNGs", "max_forks_repo_head_hexsha": "870868464b5db7a271d17c347c65898ba8e42a2d", "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.5326086957, "max_line_length": 62, "alphanum_fraction": 0.5501843507, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5460765209254704}}
{"text": "/*******************************************************************************\n * Copyright 2013-2014 Sebastian Niemann <niemann@sra.uni-hannover.de>.\n * \n * Licensed under the MIT License (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://opensource.org/licenses/MIT\n * \n * Developers:\n *   Sebastian Niemann - Lead developer\n *   Daniel Kiechle - Unit testing\n ******************************************************************************/\n#include <Expected.hpp>\nusing armadilloJava::Expected;\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <utility>\nusing std::pair;\n\n#include <armadillo>\nusing arma::Mat;\nusing arma::min;\nusing arma::max;\nusing arma::prod;\nusing arma::sum;\nusing arma::mean;\nusing arma::median;\nusing arma::cumsum;\nusing arma::vectorise;\n\n#include <InputClass.hpp>\nusing armadilloJava::InputClass;\n\n#include <Input.hpp>\nusing armadilloJava::Input;\n\nnamespace armadilloJava {\n  class ExpectedGenMatDim : public Expected {\n    public:\n      ExpectedGenMatDim() {\n        cout << \"Compute ExpectedGenMatDim(): \" << endl;\n\n        vector<vector<pair<string, void*>>> inputs = Input::getTestParameters({\n          InputClass::GenMat,\n          InputClass::Dim\n        });\n\n        for (vector<pair<string, void*>> input : inputs) {\n          _fileSuffix = \"\";\n\n          int n = 0;\n          for (pair<string, void*> value : input) {\n            switch (n) {\n              case 0:\n                _fileSuffix += value.first;\n                _genMat = *static_cast<Mat<double>*>(value.second);\n                break;\n              case 1:\n                _fileSuffix += \",\" + value.first;\n                _dim = *static_cast<int*>(value.second);\n                break;\n            }\n            ++n;\n          }\n\n          cout << \"Using input: \" << _fileSuffix << endl;\n\n          expectedArmaMin();\n          expectedArmaMax();\n          expectedArmaProd();\n          expectedArmaSum();\n          expectedArmaMean();\n          expectedArmaMedian();\n          expectedArmaCumsum();\n          expectedArmaVectorise();\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n    protected:\n      Mat<double> _genMat;\n      int _dim;\n\n      void expectedArmaMin() {\n        cout << \"- Compute expectedArmaMin() ... \";\n        save<double>(\"Arma.min\", min(_genMat, _dim));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMax() {\n        cout << \"- Compute expectedArmaMax() ... \";\n        save<double>(\"Arma.max\", max(_genMat, _dim));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaProd() {\n        cout << \"- Compute expectedArmaProd() ... \";\n        save<double>(\"Arma.prod\", prod(_genMat, _dim));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSum() {\n        cout << \"- Compute expectedArmaSum() ... \";\n        save<double>(\"Arma.sum\", sum(_genMat, _dim));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMean() {\n        cout << \"- Compute expectedArmaMean() ... \";\n        save<double>(\"Arma.mean\", mean(_genMat, _dim));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMedian() {\n        cout << \"- Compute expectedArmaMedian() ... \";\n        save<double>(\"Arma.median\", median(_genMat, _dim));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCumsum() {\n        cout << \"- Compute expectedArmaCumsum() ... \";\n        save<double>(\"Arma.cumsum\", cumsum(_genMat, _dim));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaVectorise() {\n        cout << \"- Compute expectedArmaVectorise() ... \";\n        save<double>(\"Arma.vectorise\", vectorise(_genMat, _dim));\n        cout << \"done.\" << endl;\n      }\n\n  };\n}\n", "meta": {"hexsha": "ba86efe54764b2f7cba0144ae176780bef689c0d", "size": 3753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/cpp/src/ExpectedGenMatDim.cpp", "max_stars_repo_name": "SebastianNiemann/ArmadilloJava", "max_stars_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T02:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-15T07:43:53.000Z", "max_issues_repo_path": "src/test/cpp/src/ExpectedGenMatDim.cpp", "max_issues_repo_name": "sebiniemann/ArmadilloJava", "max_issues_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2019-10-20T21:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T21:53:47.000Z", "max_forks_repo_path": "src/test/cpp/src/ExpectedGenMatDim.cpp", "max_forks_repo_name": "sebiniemann/ArmadilloJava", "max_forks_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T17:01:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T18:45:14.000Z", "avg_line_length": 27.0, "max_line_length": 80, "alphanum_fraction": 0.5265121236, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5460765112432114}}
{"text": "/*\nThe MIT License\n\nCopyright (c) 2015-2017 Albert Murienne\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\nall copies 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\nTHE SOFTWARE.\n*/\n\n#include \"autothreshold.h\"\n\n#include \"CImg.h\"\n\n#include <boost/shared_array.hpp>\n\nusing namespace cimg_library;\n\n//************** WARNING : FOR NOW ONLY WORKS ON 0-256 DYNAMIC!!! **************//\n\ntemplate<typename T>\nint default_isodata( const T* data, const int length );\nint isodata( int* data, const int length );\n\nvoid auto_threshold( float* input, const int sizeX, const int sizeY )\n{\n    CImg<float> _input( input, sizeX, sizeY, 1, 1, true /*shared*/);\n\n    int threshold = default_isodata<cimg_ulong>( _input.get_histogram(256), 256 );\n    _input.threshold( threshold );\n}\n\n// One of the many autothreshold IJ implementations:\n// https://imagej.nih.gov/ij/developer/source/ij/process/AutoThresholder.java.html\n\ntemplate<typename T>\nint default_isodata( const T* data, const int length )\n{\n    int n = length;\n    boost::shared_array<int> data2( new int[n] );\n    int mode=0, maxCount=0;\n    for (int i=0; i<n; i++) {\n        data2[i] = std::round<int>( data[i] );\n        if (data2[i]>maxCount) {\n            maxCount = data2[i];\n            mode = i;\n        }\n    }\n    int maxCount2 = 0;\n    for (int i = 0; i<n; i++) {\n        if ((data2[i]>maxCount2) && (i!=mode))\n            maxCount2 = data2[i];\n    }\n    int hmax = maxCount;\n    if ((hmax>(maxCount2*2)) && (maxCount2!=0)) {\n        hmax = (int)(maxCount2 * 1.5);\n        data2[mode] = hmax;\n    }\n    return isodata(data2.get(),n);\n}\n\nint isodata( int* data, const int length )\n{\n    // This is the original ImageJ IsoData implementation, here for backward compatibility.\n    int level;\n    int maxValue = length - 1;\n    double result, sum1, sum2, sum3, sum4;\n    int count0 = data[0];\n    data[0] = 0; //set to zero so erased areas aren't included\n    int countMax = data[maxValue];\n    data[maxValue] = 0;\n    int min = 0;\n    while ((data[min]==0) && (min<maxValue))\n        min++;\n    int max = maxValue;\n    while ((data[max]==0) && (max>0))\n        max--;\n    if (min>=max) {\n        data[0]= count0; data[maxValue]=countMax;\n        level = length/2;\n        return level;\n    }\n    int movingIndex = min;\n    do {\n        sum1=sum2=sum3=sum4=0.0;\n        for (int i=min; i<=movingIndex; i++) {\n            sum1 += (double)i*data[i];\n            sum2 += data[i];\n        }\n        for (int i=(movingIndex+1); i<=max; i++) {\n            sum3 += (double)i*data[i];\n            sum4 += data[i];\n        }\n        result = (sum1/sum2 + sum3/sum4)/2.0;\n        movingIndex++;\n    } while ((movingIndex+1)<=result && movingIndex<max-1);\n    data[0]= count0; data[maxValue]=countMax;\n    level = std::round<int>(result);\n    return level;\n}\n", "meta": {"hexsha": "04ca436ed4a17a23e613c25954cc86209bb6c68b", "size": 3700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/imagetools/autothreshold.cpp", "max_stars_repo_name": "blackccpie/neurocl", "max_stars_repo_head_hexsha": "cfbb1978ba92d5085796330846d997944f604c93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-01-01T22:19:04.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T19:06:24.000Z", "max_issues_repo_path": "utils/imagetools/autothreshold.cpp", "max_issues_repo_name": "blackccpie/neurocl", "max_issues_repo_head_hexsha": "cfbb1978ba92d5085796330846d997944f604c93", "max_issues_repo_licenses": ["MIT"], "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/imagetools/autothreshold.cpp", "max_forks_repo_name": "blackccpie/neurocl", "max_forks_repo_head_hexsha": "cfbb1978ba92d5085796330846d997944f604c93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-19T08:17:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-19T08:17:54.000Z", "avg_line_length": 32.1739130435, "max_line_length": 91, "alphanum_fraction": 0.6383783784, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.5460765112432113}}
{"text": "#include <fstream>\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <boost/range/iterator_range.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n\n\ninline uint8_t scale8u(uint8_t value, uint8_t scale) {\n\treturn (value * scale + value) >> 8;\n}\n\n\nvoid cos(boost::filesystem::path outputPath) {\n\tstd::ofstream f((outputPath / \"cos8u10.h\").string());\n\tf << \"#pragma once\" << std::endl;\n\n\t// unsigned cosine with 8 bit output and 10 bit input, shifted to positive values\n\tf << \"uint16_t FLASH cos8Table[] = {\" << std::endl;\n\tfor (int j = 0; j < 64; ++j) {\n\t\tf << \"\\t\";\n\t\tfor (int i = 0; i < 16; ++i) {\n\t\t\tdouble x = double(i + 16*j) / 512.0 * M_PI;\n\t\t\t//int y = (i | j) == 0 ? 255 : 0;\n\t\t\tint y = int(round((cos(x) + 1.0) * 127.5));\n\t\t\tf << y << \", \";\n\t\t}\n\t\tf << std::endl;\n\t}\t\n\tf << \"};\" << std::endl;\n\tf << \"inline uint8_t cos8u10(uint16_t x) {return cos8Table[x];}\" << std::endl;\n}\n\nvoid exp(boost::filesystem::path outputPath) {\n\t{\n\t\t// write exp table with 5 bit input and 16 bit output\n\t\tstd::ofstream f((outputPath / \"exp16u5.h\").string());\n\t\tf << \"#pragma once\" << std::endl;\n\t\tf << \"uint16_t FLASH exp16u5Table[] = {\" << std::endl;\n\t\tf << \"\\t0\";\n\t\tfor (int i = 1; i < 32; ++i) {\n\t\t\t// x^31 = 65535 -> x = 65535^(1/31)\n\t\t\tint y = int(round(pow(65535.0, i / 31.0)));\n\t\t\tf << \", \" << y;\n\t\t}\n\t\tf << std::endl;\n\t\tf << \"};\" << std::endl;\n\t\tf << \"inline uint16_t exp16u5(uint8_t x) {return exp16u5Table[x];}\" << std::endl;\n\t}\n\t{\n\t\t// write exp table with 8 bit input and 16 bit output\n\t\tstd::ofstream f((outputPath / \"exp16u8.h\").string());\n\t\tf << \"#pragma once\" << std::endl;\n\t\tf << \"uint16_t FLASH exp16u8Table[] = {\" << std::endl;\n\t\tf << \"\\t0\";\n\t\tfor (int i = 1; i < 256; ++i) {\n\t\t\t// x^255 = 65535 -> x = 65535^(1/255)\n\t\t\tint y = int(round(pow(65535.0, i / 255.0)));\n\t\t\tf << \", \" << y;\n\t\t}\n\t\tf << std::endl;\n\t\tf << \"};\" << std::endl;\n\t\tf << \"inline uint16_t exp16u8(uint8_t x) {return exp16u8Table[x];}\" << std::endl;\n\t}\n}\n\nvoid permute(boost::filesystem::path outputPath) {\n\t// generate permute table\n\tsrand(1337);\n\tint permute[256];\n\tfor (int i = 0; i < 256; ++i) {\n\t\tpermute[i] = i;\n\t}\n\tfor (int i = 0; i < 10000; ++i) {\n\t\tint x = rand() & 0xff;\n\t\tint y = rand() & 0xff;\n\t\tstd::swap(permute[x], permute[y]);\n\t}\n\n\t// write permutation table and function\n\tstd::ofstream f((outputPath / \"permute8.h\").string());\n\tf << \"#pragma once\" << std::endl;\n\tf << \"uint8_t FLASH permute8Table[] = {\" << std::endl;\n\tf << \"\\t\";\n\tfor (int i = 0; i < 256; ++i) {\n\t\tif (i != 0)\n\t\t\tf << \", \";\n\t\tf << permute[i];\n\t}\n\tf << std::endl;\n\tf << \"};\" << std::endl;\n\tf << \"inline uint8_t permute8(uint8_t x) {return permute8Table[x];}\" << std::endl;\n}\n\nvoid ledSerial(boost::filesystem::path outputPath) {\n\t// generate pattern to send via serial port to led strip of WS2812b etc.\n\n\t// 8 bit are transferred like this (shown inverted) where first and last bit of each block are start and stop bit:\n\t// 1xx001xx00 1xx001xx00 1xx001xx00 1xx001xx00\n\n\t// write lookup table\n\tstd::ofstream f((outputPath / \"ledSerial.h\").string());\n\tf << \"#pragma once\" << std::endl;\n\tf << \"uint32_t FLASH ledSerialTable[] = {\" << std::endl;\n\tf << \"\\t\";\n\tfor (int v = 0; v < 256; ++v) {\n\t\tif (v != 0)\n\t\t\tf << \", \";\n\t\t\n\t\t// square the value to emulate gamma of 2\n\t\tint value = scale8u(v, v);\n\t\t\n\t\t// all ones in the middle of each block, omitting start bits (inverted)\n\t\tuint32_t pattern = ~0x08080808;\n\t\tfor (int i = 0; i < 8; ++i) {\n\t\t\tif (value & (1 << i)) {\n\t\t\t\t// offsets of the \"xx\" are 1, 6, 9, 14, 17, 22, 25, 30\n\t\t\t\tint offset = 1 + 4 * i + (i & 1 ? 1 : 0);\n\t\t\t\tpattern &= ~(3 << offset);\n\t\t\t}\n\t\t}\n\t\t\n\t\tf << pattern;\n\t}\n\tf << std::endl;\n\tf << \"};\" << std::endl;\n}\n\n\n\nstruct IndexColor {\n\tint index;\n\t\n\tint red;\n\tint green;\n\tint blue;\n\n\tIndexColor() = default;\n\tIndexColor(int index, uint8_t red, uint8_t green, uint8_t blue)\n\t\t: index(index), red(red), green(green), blue(blue) {}\n};\n\ninline int toInt(std::string const & s) {\n\tint base = 10;\n\tint i = 0;\n\tif (boost::starts_with(s, \"0x\")) {\n\t\tbase = 16;\n\t\ti = 2;\n\t}\n\t\n\tint value = 0;\n\tfor (; i < s.length(); ++i) {\n\t\tvalue *= base;\n\t\tchar ch = s[i];\n\t\t\n\t\tif (ch >= '0' && ch <= '9') {\n\t\t\tvalue += ch - '0';\n\t\t} else if (base == 16) {\n\t\t\tif (ch >= 'A' && ch <= 'F')\n\t\t\t\tvalue += ch - 'A' + 10;\n\t\t\telse if (ch >= 'a' && ch <= 'f')\n\t\t\t\tvalue += ch - 'a' + 10;\n\t\t}\n\t}\n\treturn value;\n}\n\n\nvoid interpolate(std::ofstream & f, const std::string &indent, int index1, int index2, int value1, int value2) {\n\tf << value1;\n\tif (value2 != value1) {\n\t\tf << (value2 > value1 ? \" + \" : \" - \");\n\t\tf << '(';\n\t\tif ((index1 & 0xff) == 0)\n\t\t\tf << \"(uint8_t)x\";\n\t\telse\n\t\t\tf << \"(uint8_t)(x - \" << index1 << \")\";\n\t\tf << \" * \" << std::abs(value2 - value1);\n\t\tint d = index2 - index1;\n\t\tint shift = 0;\n\t\twhile (d > 1) {\n\t\t\t++shift;\n\t\t\td >>= 1;\n\t\t}\n\t\tf << \" >> \" << shift;\n\t\tf << ')';\n\t}\n}\n\nvoid subdivide(std::ofstream & os, const std::string& indent, std::vector<IndexColor> const & palette, int begin, int end) {\n\tif (end - begin > 1) {\n\t\tint mid = (begin + end) / 2;\n\t\t\n\t\tos << indent << \"if (x < 0x\" << std::hex << palette[mid].index << std::dec << \") {\" << std::endl;\n\t\tsubdivide(os, indent + '\\t', palette, begin, mid);\n\t\tos << indent << \"} else {\" << std::endl;\n\t\tsubdivide(os, indent + '\\t', palette, mid, end);\n\t\tos << indent << \"}\" << std::endl;\n\t} else {\n\t\t// add index as comment\n\t\tos << indent << \"// 0x\" << std::hex << palette[begin].index << std::dec << std::endl;\n\n\t\t// interpolate colors\n\t\tIndexColor color1 = palette[begin];\n\t\tIndexColor color2 = palette[begin + 1];\n\t\tos << indent << \"color.red = \"; interpolate(os, indent, color1.index, color2.index, color1.red, color2.red); os << \";\" << std::endl;\n\t\tos << indent << \"color.green = \"; interpolate(os, indent, color1.index, color2.index, color1.green, color2.green); os << \";\" << std::endl;\n\t\tos << indent << \"color.blue = \"; interpolate(os, indent, color1.index, color2.index, color1.blue, color2.blue); os << \";\" << std::endl;\n\t}\n}\n\nvoid palette(boost::filesystem::path path, boost::filesystem::path outputPath) {\n\tstd::vector<IndexColor> palette;\n\n\t// read palette\n\tstd::ifstream is(path.string());\n\tstd::string line;\n\twhile (std::getline(is, line)) {\n\t\t// remove comment\n\t\tsize_t pos = line.find(\"//\");\n\t\tif (pos != std::string::npos)\n\t\t\tline = line.substr(0, pos);\n\t\t\n\t\t// trim\n\t\tboost::algorithm::trim(line);\n\t\t\n\t\t// split\n\t\tstd::vector<std::string> elements;\n\t\tboost::split(elements, line, boost::algorithm::is_any_of(\"\\t \"), boost::token_compress_on);\n\t\t\n\t\tif (elements.size() >= 2) {\n\t\t\n\t\t\tint index = toInt(elements[0]);\n\t\t\n\t\t\tif (elements.size() == 2) {\n\t\t\t\tif (elements[1] == \"loop\") {\n\t\t\t\t\tIndexColor ic = palette.front();\n\t\t\t\t\tic.index = index;\n\t\t\t\t\tpalette.push_back(ic);\n\t\t\t\t}\n\t\t\t} else if (elements.size() == 4) {\n\t\t\t\tint r = toInt(elements[1]);\n\t\t\t\tint g = toInt(elements[2]);\n\t\t\t\tint b = toInt(elements[3]);\n\t\t\t\t\n\t\t\t\tpalette.push_back(IndexColor(index, r, g, b));\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::string name = path.stem().string();\n\tstd::ofstream os((outputPath / (name + \".h\")).string());\n\tos << \"#pragma once\" << std::endl;\n\tos << \"inline RGB \" << name << \"(uint16_t x) {\" << std::endl;\n\t\n\t//os << \"\\tuint8_t r, g, b;\" << std::endl;\n\tos << \"\\tRGB color;\" << std::endl;\n\n\tsubdivide(os, \"\\t\", palette, 0, palette.size()-1);\n\t\n\t//os << \"\\tRGB color;\" << std::endl;\n\t//os << \"\\tcolor.red = r;\" << std::endl;\n\t//os << \"\\tcolor.green = g;\" << std::endl;\n\t//os << \"\\tcolor.blue = b;\" << std::endl;\n\tos << \"\\treturn color;\" << std::endl;\n\n\tos << \"}\" << std::endl;\n\tos.close();\n}\n\n\n\nint main(int argc, const char **argv) {\n\tboost::filesystem::path outputPath = \"generated\";\n\tboost::filesystem::create_directory(outputPath);\n\t\n\t// generate tables\n\tcos(outputPath);\n\texp(outputPath);\n\tpermute(outputPath);\n\tledSerial(outputPath);\n\t\n\t// convert palettes in current directory\n\tboost::filesystem::path p = \".\";\n\tfor (auto & entry : boost::make_iterator_range(boost::filesystem::directory_iterator(p), {})) {\n\t\tboost::filesystem::path path = entry.path();\n\t\tstd::string ext = path.extension().string();\n\t\tif (ext == \".palette\") {\n\t\t\tpalette(path, outputPath);\n\t\t}\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "bd4161981c709ac23257c36404e1f4a39e0d57b4", "size": 8090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Generator/main.cpp", "max_stars_repo_name": "Jochen0x90h/LedControl", "max_stars_repo_head_hexsha": "2e19bf3f3db0fb4b471e95ea234534a94caa3227", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Generator/main.cpp", "max_issues_repo_name": "Jochen0x90h/LedControl", "max_issues_repo_head_hexsha": "2e19bf3f3db0fb4b471e95ea234534a94caa3227", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Generator/main.cpp", "max_forks_repo_name": "Jochen0x90h/LedControl", "max_forks_repo_head_hexsha": "2e19bf3f3db0fb4b471e95ea234534a94caa3227", "max_forks_repo_licenses": ["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.3310810811, "max_line_length": 140, "alphanum_fraction": 0.5688504326, "num_tokens": 2727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5460632181630566}}
{"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#include <boost/math/bindings/rr.hpp>\r\n#include <boost/test/included/test_exec_monitor.hpp>\r\n#include <boost/math/special_functions/zeta.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/math/tools/test.hpp>\r\n#include <fstream>\r\n\r\n#include <boost/math/tools/test_data.hpp>\r\n\r\nusing namespace boost::math::tools;\r\nusing namespace std;\r\n\r\nstruct zeta_data_generator\r\n{\r\n   boost::math::ntl::RR operator()(boost::math::ntl::RR z)\r\n   {\r\n      std::cout << z << \" \";\r\n      boost::math::ntl::RR result = boost::math::zeta(z);\r\n      std::cout << result << std::endl;\r\n      return result;\r\n   }\r\n};\r\n\r\nstruct zeta_data_generator2\r\n{\r\n   std::tr1::tuple<boost::math::ntl::RR, boost::math::ntl::RR> operator()(boost::math::ntl::RR z)\r\n   {\r\n      std::cout << -z << \" \";\r\n      boost::math::ntl::RR result = boost::math::zeta(-z);\r\n      std::cout << result << std::endl;\r\n      return std::tr1::make_tuple(-z, result);\r\n   }\r\n};\r\n\r\n\r\nint test_main(int argc, char*argv [])\r\n{\r\n   boost::math::ntl::RR::SetPrecision(500);\r\n   boost::math::ntl::RR::SetOutputPrecision(40);\r\n\r\n   parameter_info<boost::math::ntl::RR> arg1;\r\n   test_data<boost::math::ntl::RR> data;\r\n\r\n   bool cont;\r\n   std::string line;\r\n\r\n   std::cout << \"Welcome.\\n\"\r\n      \"This program will generate spot tests for the zeta function:\\n\";\r\n\r\n   do{\r\n      if(0 == get_user_parameter_info(arg1, \"z\"))\r\n         return 1;\r\n      arg1.type |= dummy_param;\r\n      data.insert(zeta_data_generator2(), arg1);\r\n\r\n      std::cout << \"Any more data [y/n]?\";\r\n      std::getline(std::cin, line);\r\n      boost::algorithm::trim(line);\r\n      cont = (line == \"y\");\r\n   }while(cont);\r\n\r\n   std::cout << \"Enter name of test data file [default=zeta_data.ipp]\";\r\n   std::getline(std::cin, line);\r\n   boost::algorithm::trim(line);\r\n   if(line == \"\")\r\n      line = \"zeta_data.ipp\";\r\n   std::ofstream ofs(line.c_str());\r\n   write_code(ofs, data, \"zeta_data\");\r\n   \r\n   return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "445911f1731f56a13550a336c0bba07d092d8a80", "size": 2175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/zeta_data.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/tools/zeta_data.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/tools/zeta_data.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": 27.8846153846, "max_line_length": 98, "alphanum_fraction": 0.611954023, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5460632171926377}}
{"text": "#if defined __GNUC__ \\\n            && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) ) \\\n            && !defined __clang__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n\n#include <boost/type_traits.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n#include <boost/math/special_functions/pow.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#if defined __GNUC__ \\\n            && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) ) \\\n            && !defined __clang__\n#pragma GCC diagnostic pop\n#endif\n\n#include <cmath>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <limits>\n#include <valarray>\n\n#if __cplusplus >= 201103L\n  #include <type_traits>\n  #include <initializer_list>\n#endif\n", "meta": {"hexsha": "5c6b36dbaaff8ee6832adaf91f42191a3c364c18", "size": 979, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/precompiled.hpp", "max_stars_repo_name": "t-b/value-with-error", "max_stars_repo_head_hexsha": "ede8325d3572ac53601d0d7aabc09518850c8455", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-07T10:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T01:09:50.000Z", "max_issues_repo_path": "tests/precompiled.hpp", "max_issues_repo_name": "t-b/value-with-error", "max_issues_repo_head_hexsha": "ede8325d3572ac53601d0d7aabc09518850c8455", "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": "tests/precompiled.hpp", "max_forks_repo_name": "t-b/value-with-error", "max_forks_repo_head_hexsha": "ede8325d3572ac53601d0d7aabc09518850c8455", "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.9714285714, "max_line_length": 75, "alphanum_fraction": 0.7048008172, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5460632128864651}}
{"text": "/**\n * @file mtgp32-calc-poly.cpp\n *\n * @brief calculate characteristic polynomial for 32bit mtgp.\n *\n * @author Mutsuo Saito (Hiroshima University)\n * @author Makoto Matsumoto (Hiroshima University)\n *\n * Copyright (c) 2012 Mutsuo Saito, Makoto Matsumoto, Hiroshima\n * University and University of Tokyo. All rights reserved.\n *\n * The new BSD License is applied to this software, see LICENSE.txt\n */\n#include <stdint.h>\n#include <inttypes.h>\n#include <time.h>\n#include <string.h>\n#include <string>\n#include <errno.h>\n#include <NTL/GF2X.h>\n#include <NTL/vec_GF2.h>\n#include <NTL/GF2XFactoring.h>\n#include \"mtgp32-calc-poly.hpp\"\n#include \"mtgp-calc-jump.hpp\"\n#include \"mtgp32-fast.h\"\n\nusing namespace std;\nusing namespace NTL;\n\n/**\n * calculate the characteristic polynomial for given 32-bit MTGP.\n * MinPolySeq is defined in NTL.\n * @param[out] poly calculated characteristic polynomial.\n * @param[in] mtgp64 generator\n */\nvoid calc_characteristic(GF2X& poly, mtgp32_fast_t * mtgp32)\n{\n    vec_GF2 seq;\n    int mexp = mtgp32->params.mexp;\n    seq.SetLength(2 * mexp);\n    for (int i = 0; i < 2 * mexp; i++) {\n\tseq[i] = mtgp32_genrand_uint32(mtgp32) & 1;\n    }\n    MinPolySeq(poly, seq, mexp);\n}\n\n/**\n * calculate the characteristic polynomial for given 32-bit MTGP.\n * MinPolySeq is defined in NTL.\n * @param[out] str calculated characteristic polynomial in string format.\n * @param[in] mtgp64 generator\n */\nvoid calc_characteristic(string& str, mtgp32_fast_t * mtgp32)\n{\n    GF2X poly;\n    calc_characteristic(poly, mtgp32);\n    polytostring(str, poly);\n}\n\nvoid calc_characteristic(uint32_t array[], int size, mtgp32_fast_t * mtgp32)\n{\n    GF2X poly;\n    calc_characteristic(poly, mtgp32);\n    polytoarray(array, size, poly);\n}\n\n\n#if defined(MAIN)\n/**\n * main function for executable.\n * @param[in] argc number of arguments.\n * @param[in] argv an array of arguments.\n * @return 0 if normal, other abnormal.\n */\nint main(int argc, char *argv[]) {\n    int mexp;\n    int no;\n    uint32_t seed = 1;\n    mtgp32_params_fast_t *params;\n    mtgp32_fast_t mtgp32;\n    int rc;\n\n    if (argc <= 2) {\n\tprintf(\"%s: mexp no.\\n\", argv[0]);\n\treturn 1;\n    }\n    mexp = strtol(argv[1], NULL, 10);\n    if (errno) {\n\tprintf(\"%s: mexp no.\\n\", argv[0]);\n\treturn 2;\n    }\n    no = strtol(argv[2], NULL, 10);\n    if (errno) {\n\tprintf(\"%s: mexp no.\\n\", argv[0]);\n\treturn 3;\n    }\n    switch (mexp) {\n    case 11213:\n\tparams = mtgp32_params_fast_11213;\n\tbreak;\n    case 23209:\n\tparams = mtgp32_params_fast_23209;\n\tbreak;\n    case 44497:\n\tparams = mtgp32_params_fast_44497;\n\tbreak;\n    default:\n\tprintf(\"%s: mexp no.\\n\", argv[0]);\n\tprintf(\"mexp shuould be 11213, 23209 or 44497\\n\");\n\treturn 4;\n    }\n    if (no >= 128 || no < 0) {\n\tprintf(\"%s: mexp no.\\n\", argv[0]);\n\tprintf(\"no must be between 0 and 127\\n\");\n\treturn 5;\n    }\n    params += no;\n    rc = mtgp32_init(&mtgp32, params, seed);\n    if (rc) {\n\tprintf(\"failure in mtgp32_init\\n\");\n\treturn -1;\n    }\n    mtgp32_print_idstring(&mtgp32, stdout);\n#if 0\n    string s;\n    calc_characteristic(s, &mtgp32);\n    printf(\"%s\\n\", s.c_str());\n#else\n#endif\n    mtgp32_free(&mtgp32);\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "c24bfe60b102de88eb065604011903ff3e1f1d4c", "size": 3129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mtgp32-calc-poly.cpp", "max_stars_repo_name": "mkt-matsumoto-lab/MTGP", "max_stars_repo_head_hexsha": "9cea3283dc67d9fc6cfc044b7ae38fe9ef32afb3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T06:39:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-10T09:48:37.000Z", "max_issues_repo_path": "mtgp32-calc-poly.cpp", "max_issues_repo_name": "mkt-matsumoto-lab/MTGP", "max_issues_repo_head_hexsha": "9cea3283dc67d9fc6cfc044b7ae38fe9ef32afb3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-10T07:15:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T07:15:53.000Z", "max_forks_repo_path": "mtgp32-calc-poly.cpp", "max_forks_repo_name": "mkt-matsumoto-lab/MTGP", "max_forks_repo_head_hexsha": "9cea3283dc67d9fc6cfc044b7ae38fe9ef32afb3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-27T21:05:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T09:47:58.000Z", "avg_line_length": 23.3507462687, "max_line_length": 76, "alphanum_fraction": 0.6599552573, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5460632076098737}}
{"text": "//\n// Created by eliezer on 07.11.16.\n//\n\n\n#include <cmath>\n#include \"BatchPoissonPure.h\"\n#include <math.h>\n#include <limits>\n#include <algorithm>\n#include <cmath>\n#include <sstream>\n#include <stdexcept>\n#include <boost/math/special_functions/digamma.hpp>\n#include <chrono>\n#include <boost/math/special_functions/gamma.hpp>\n#ifndef M_PIl\n/** The constant Pi in high precision */\n#define M_PIl 3.1415926535897932384626433832795029L\n#endif\n#ifndef M_GAMMAl\n/** Euler's constant in high precision */\n#define M_GAMMAl 0.5772156649015328606065120900824024L\n#endif\n#ifndef M_LN2l\n/** the natural logarithm of 2 in high precision */\n#define M_LN2l 0.6931471805599453094172321214581766L\n#endif\n\n\ndouble gamma_term(double a, double b, double a_latent, double b_latent, double e_latent, double elog_latent) {\n    return lgamma(a_latent)-lgamma(a)+a*log(b)+a_latent*(1-log(b_latent))-b*e_latent+(a-a_latent)*elog_latent;\n}\n\nvoid compute_gama_expected(Arrayf& a_x, Arrayf& b_x, Arrayf& e_x,\n                           Arrayf& elog_x) {\n    for ( long i=0; i< a_x.rows();i++ ){\n        for( long k=0; k< a_x.cols();k++){\n            e_x(i,k) = a_x(i,k)/b_x(k);\n            //elog_x(i,k) = (double)(digammal(a_x(i,k))-log(b_x(k))); // using standalone implementation\n            elog_x(i, k) = boost::math::digamma(a_x(i, k)) - log(b_x(k)); // using boost implementation\n\n        }\n    }\n}\n\nsize_t sizes_var(vars v,size_t n_ratings, size_t n_wd_entries, size_t n_users, size_t n_items,size_t k_feat, size_t n_words, size_t n_max_neighbors){\n    size_t result=0;\n    switch(v){\n        case vars::a_beta:\n        case vars::e_beta:\n        case vars::elog_beta:\n            result= k_feat*n_words;\n            break;\n\n        case vars::a_epsilon:\n        case vars::e_epsilon:\n        case vars::elog_epsilon:\n        case vars::a_theta:\n        case vars::e_theta:\n        case vars::elog_theta:\n            result= k_feat*n_items;\n            break;\n\n        case vars::e_eta:\n        case vars::elog_eta:\n        case vars::a_eta:\n            result= k_feat*n_users;\n            break;\n\n        case vars::e_tau:\n        case vars::elog_tau:\n        case vars::a_tau:\n            result= n_max_neighbors*n_users;\n            break;\n\n        case vars::phi:\n            result=k_feat*n_wd_entries;\n            break;\n        case vars::xi_M:\n        case vars::xi_N:\n            result= k_feat*n_ratings;\n            break;\n        case vars::xi_S:\n            result= n_max_neighbors*n_ratings;\n            break;\n\n        case vars::b_theta:\n        case vars::b_eta:\n        case vars::b_epsilon:\n        case vars::b_beta:\n            result= k_feat;\n            break;\n\n        case vars::b_tau:\n            result= n_max_neighbors;\n            break;\n    }\n    //std::cout << EnumStrings[(int)v]<<\"= \"<<result<<'\\n';\n    return result;\n}\n\nsize_t total_memory(size_t n_ratings, size_t n_wd_entries, size_t n_users, size_t n_items,size_t k_feat, size_t n_words, size_t n_max_neighbors){\n    size_t sum=0;\n\n    for(vars i : vec_vars){\n        sum+=sizes_var(i,n_ratings,n_wd_entries, n_users,  n_items,k_feat, n_words,n_max_neighbors);\n    }\n    return sum;\n}\n\nBatchPoissonNewArray::BatchPoissonNewArray(size_t n_ratings, size_t n_wd_entries, size_t n_users, size_t n_items,\n                                           size_t k_feat, size_t n_words, size_t n_max_neighbors, double a, double b,\n                                           double c, double d, double e, double f, double g, double h, double k, double l) :\n        arrman(new ArrayManager<double>(2*total_memory(n_ratings,n_wd_entries, n_users,  n_items,k_feat, n_words,n_max_neighbors))),\n        _n_users(n_users), _n_items(n_items), _k_feat(k_feat),\n        _n_words(n_words), _n_ratings(n_ratings),\n        _n_wd_entries(n_wd_entries), _n_max_neighbors(n_max_neighbors),\n        a(a), b(b), c(c), d(d), e(e), f(f), g(g), h(h), k(k), l(l),\n        beta(arrman,n_words,k_feat,a,b),\n        theta(arrman,n_items,k_feat,c,d),\n        epsilon(arrman,n_items,k_feat,g,h),\n        eta(arrman,n_users,k_feat,e,f),\n        tau(arrman,n_users,n_max_neighbors,k,l),\n        phi(arrman->makeArray(n_wd_entries,k_feat)),\n        xi_M(arrman->makeArray(n_ratings,k_feat)),\n        xi_N(arrman->makeArray(n_ratings,k_feat)),\n        xi_S(arrman->makeArray(n_ratings,n_max_neighbors)),\n        user_items_map(pairmap(n_ratings)),\n        user_items_index(vector< pair<size_t,size_t>>(n_users)),\n        user_items_neighboors(vector< list <  pair<size_t, size_t > > >(n_ratings))\n{\n\n    mem_use= total_memory(n_ratings,n_wd_entries, n_users,  n_items,k_feat, n_words,n_max_neighbors);\n    std::cout << \"total = \" << mem_use <<\"\\n\";\n    std::cout << \"n_users = \" << n_users <<\"\\n\";\n    std::cout << \"n_items = \" << n_items <<\"\\n\";\n    std::cout << \"n_words = \" << n_words <<\"\\n\";\n    std::cout << \"n_max_neighbors = \" << n_max_neighbors <<\"\\n\";\n    std::cout << \"n_ratings = \" << n_ratings <<\"\\n\";\n    std::cout << \"n_wd_entries = \" << n_wd_entries <<\"\\n\";\n    std::cout << \"k_feat = \" << k_feat <<\"\\n\";\n\n\n\n}\n\nvoid BatchPoissonNewArray::train(size_t n_iter, double tol) {\n    try {\n        std::cout << \"n_iter = \" << n_iter <<\"\\n\";\n        std::cout << \"tol = \" << tol <<\"\\n\";\n        init_aux_latent();\n        double old_elbo=-std::numeric_limits<double>::infinity();\n        double elbo=0;\n\n        for(auto i=0;i<n_iter;i++){\n\n                std::cout << \"############ITERATION \"<<i<<\" of \"<<n_iter<<endl;\n                std::cout << \"Begin update latent variables\"<<endl;\n                update_latent();\n                std::cout << \"Begin update auxiliary variables\"<<endl;\n                update_aux_latent();\n                elbo = compute_elbo();\n\n\n\n                elbo_lst.push_back(elbo);\n                std::cout << \"Old ELBO=\"<<old_elbo<<\"  ---- new ELBO=\"<< elbo<< \" improvement = \" << abs((elbo-old_elbo)/old_elbo) << endl;\n\n                if(abs((elbo-old_elbo)/old_elbo) < tol)\n                    break;\n                else\n                    old_elbo=elbo;\n\n\n\n        }\n        std::cout << \"List os ELBO values\";\n        std::copy(elbo_lst.begin(),\n                  elbo_lst.end(),\n                  std::ostream_iterator<double>(std::cout, \" , \"));\n    } catch (const std::bad_alloc& e) {\n        std::cout << \"Allocation failed: \" << e.what() << '\\n';\n        exit(-1);\n    }\n}\n\n\n\n void BatchPoissonNewArray::init_train(vector<tuple<size_t, size_t, size_t>> r_entries,\n                                      vector<tuple<size_t, size_t, size_t>> w_entries,\n                                      vector< vector<size_t> > user_neighboors) {\n    this->r_entries=r_entries;\n    this->w_entries=w_entries;\n    this->user_neighboors=user_neighboors;\n    cout << \"init_train \" << endl;\n    std::cout << \"r_entries.size = \" << r_entries.size() <<\"\\n\";\n    std::cout << \"w_entries.size = \" << w_entries.size() <<\"\\n\";\n    std::cout << \"user_neighboors.size = \" << user_neighboors.size() <<\"\\n\";\n\n\n    pair<size_t,size_t> temp=make_pair(0,0);\n\n    size_t ud;\n    for(ud=0; ud< _n_ratings;ud++) {\n        auto user_u = std::get<0>(r_entries[ud]);\n        auto item_i = std::get<1>(r_entries[ud]);\n        temp.first=user_u;\n        temp.second=item_i;\n        user_items_map[temp]=  ud;\n\n    }\n    temp=make_pair(0,0);\n    size_t current_user=0;\n    for(ud = 0; ud < _n_ratings; ud++) {\n        auto user_u = std::get<0>(r_entries[ud]);\n        auto item_i = std::get<1>(r_entries[ud]);\n        tau.b_latent(user_u)+=std::get<2>(r_entries[ud]); // b_tau_user_i = l + \\sum_d r_{user_i,d}\n\n        if(current_user!=user_u){\n            // generate a index with beginning index and end index for item rated by user in the user_item_rating matrix\n            //\n            temp.second=ud;\n            user_items_index[current_user]=temp;\n            temp=make_pair(ud,0);\n            current_user=user_u;\n            //cout << \"(\"<<user_u << \", \" << item_i << \",\" << std::get<2>(r_entries[ud])<<\"),\";\n\n        }\n        size_t neigh_ord=0;\n        for(auto user_i : this->user_neighboors[user_u]){\n            // test which neighboor of user_u has item_i rated and point to the index on the rating matrix\n            pairmap::iterator ifind = user_items_map.find(make_pair(user_i,item_i));\n            if ( ifind != user_items_map.end() ){\n                // fill vector< list <  pair<size_t, size_t > > > user_items_neighboors;\n                // list<<pair<user_neighbor_i,index_in_r_entries>>\n                user_items_neighboors[ud].push_back(make_pair(user_i,ifind->second));\n\n            }\n            neigh_ord++;\n        }\n    }\n    temp.second=_n_ratings;\n    user_items_index[current_user]=temp;\n    //cout << \"###########\" <<endl;\n    //for(size_t i=0;i<user_items_index.size();i++)\n    //{\n    //    cout << \"(\"<<i<<\",\"<<user_items_index[i].first <<\",\"<<user_items_index[i].second  << \"),\";\n    //}\n    beta.init_b_latent();\n    theta.init_b_latent();\n    epsilon.init_b_latent();\n    eta.init_b_latent();\n    cout << \"tau_b=\"<< tau.b_latent << endl;\n}\n\nvoid BatchPoissonNewArray::init_aux_latent() {\n    phi.init_gamma_row_normalized();\n    xi_M.init_gamma_row_normalized();\n    xi_N.init_gamma_row_normalized();\n    xi_S.init_gamma_row_normalized();\n    //update_latent();\n    //update_expected();\n    //xi_S=0;\n    //xi_M=0;\n    //xi_N=0;\n    //xi_S=0;\n    //update_aux_latent();\n\n}\n\nvoid BatchPoissonNewArray::update_latent() {\n    beta.init_a_latent();\n    theta.init_a_latent();\n    epsilon.init_a_latent();\n    eta.init_a_latent();\n    tau.init_a_latent();\n    cout << \"INIT#theta\" << theta <<endl;\n    //cout << \"INIT#eta\" << eta <<endl;\n    //cout << \"INIT#tau\" << tau <<endl;\n    //cout << \"INIT#epsilon\" << epsilon <<endl;\n    //cout << \"INIT#beta\" << epsilon <<endl;\n\n\n    for(size_t ud=0; ud< _n_ratings;ud++){\n        auto user_u = std::get<0>(r_entries[ud]);\n        auto item_i = std::get<1>(r_entries[ud]);\n        auto r_ud= std::get<2>(r_entries[ud]);\n\n        for(size_t k=0; k< _k_feat;k++){\n            auto rudk_M=r_ud*xi_M(ud,k);\n            auto rudk_N=r_ud*xi_N(ud,k);\n            epsilon.a_latent(item_i,k)+=rudk_N;\n            theta.a_latent(item_i,k)+=rudk_M;\n            eta.a_latent(user_u,k)+=rudk_M+rudk_N;\n        }\n\n        for(auto neighb : user_items_neighboors[ud]) {\n            tau.a_latent(user_u,neighb.first)+=r_ud*xi_S(ud,neighb.first);\n        }\n    }\n    double temp_w;\n    for(size_t dv=0; dv< _n_wd_entries;dv++){\n\n        auto word_w = std::get<1>(w_entries[dv]);\n        auto item_i = std::get<0>(w_entries[dv]);\n        auto wdv= std::get<2>(w_entries[dv]);\n        for(size_t k=0; k< _k_feat;k++) {\n            temp_w=wdv*phi(dv,k);\n            beta.a_latent(word_w,k)+=temp_w;\n            theta.a_latent(item_i,k)+=temp_w;\n\n        }\n    }\n\n\n    beta.init_b_latent();\n    eta.init_b_latent();\n    for(size_t k=0; k< _k_feat;k++) {\n        double sum_d_epsilon = epsilon.e_expected.col_sum(k);\n        double sum_d_theta = theta.e_expected.col_sum(k);\n        beta.b_latent(k)+= sum_d_theta;\n        eta.b_latent(k) += sum_d_theta + sum_d_epsilon;\n    }\n    beta.update_expected();\n    eta.update_expected();\n\n\n    theta.init_b_latent();\n    epsilon.init_b_latent();\n    for(size_t k=0; k< _k_feat;k++) {\n        double sum_u_eta = eta.e_expected.col_sum(k);\n        double sum_v_beta = beta.e_expected.col_sum(k);\n        epsilon.b_latent(k) += sum_u_eta;\n        theta.b_latent(k) += sum_u_eta + sum_v_beta;\n    }\n    theta.update_expected();\n    epsilon.update_expected();\n    tau.update_expected();\n\n    //cout << \"END#theta\" << theta <<endl;\n    //cout << \"AFTERTHETA#xi_M\" << xi_M << endl;\n    //cout << \"END#eta\" << eta <<endl;\n    //cout << \"END#tau\" << tau <<endl;\n    //cout << \"END#epsilon\" << epsilon <<endl;\n    //cout << \"END#beta\" << epsilon <<endl;\n}\n\nvoid BatchPoissonNewArray::update_aux_latent() {\n    double sum_k=0;\n    for(auto ud=0; ud< _n_ratings;ud++) {\n        // TODO: implement LOG-SUM\n        sum_k=0;\n        auto user_u = std::get<0>(r_entries[ud]);\n        auto item_i = std::get<1>(r_entries[ud]);\n        for (auto k = 0; k < _k_feat; k++) {\n            // self.xi_M = np.exp(self.Elogeta[:, np.newaxis, :] + self.Elogtheta[:, :, np.newaxis])\n            xi_M(ud, k) = exp(eta.elog_expected(user_u, k) + theta.elog_expected(item_i, k));\n\n            // self.xi_N = np.exp(self.Elogeta[:, np.newaxis, :] + self.Elogepsilon[:, :, np.newaxis])\n            xi_N(ud, k) = exp(eta.elog_expected(user_u, k) + epsilon.elog_expected(item_i, k));\n            sum_k += xi_M(ud,k) + xi_N(ud,k);\n        }\n        xi_S.row(ud) = 0;\n        for (auto neighb : user_items_neighboors[ud]) {\n            // user_items_neighboors[ud].push_back(make_pair(user_i,ifind->second));\n            xi_S(ud,neighb.first) = std::get<2>(r_entries[neighb.second])\n                                     * exp(tau.elog_expected(user_u,neighb.first));\n            sum_k += xi_S(ud,neighb.first);\n\n        }\n        {\n            xi_M.row(ud) /= sum_k;\n        }\n        {\n            xi_N.row(ud) /= sum_k;\n        }\n        {\n            xi_S.row(ud) /= sum_k;\n        }\n    }\n    cout << endl;\n\n    for(auto dv=0; dv< _n_wd_entries;dv++){\n        sum_k=0;\n        auto word_w = std::get<1>(w_entries[dv]);\n        auto item_i = std::get<0>(w_entries[dv]);\n        for(auto k=0; k< _k_feat;k++){\n            // self.phi = np.exp(self.Elogbeta[:, np.newaxis, :] + self.Elogtheta[:, :, np.newaxis])\n            phi(dv,k)=exp(beta.elog_expected(word_w,k)+theta.elog_expected(item_i,k));\n            sum_k += phi(dv,k);\n        }\n        {\n            phi.row(dv)/=sum_k;\n        }\n\n    }\n    cout << \"#END UPDATE_AUX\" << endl;\n    cout << \"#xi_M\" << xi_M.row(11685) << endl;\n    cout << \"#xi_N\" << xi_N.row(11685) << endl;\n    //cout << \"#xi_S\" << xi_S.row(11685) << endl;\n    //cout << \"#xi_N\" << xi_N << endl;\n    //cout << \"#xi_S\" << xi_S << endl;\n    cout << \"#phi\" << phi.row(0) << endl;\n\n}\n\n\ndouble BatchPoissonNewArray::compute_elbo() {\n    double total_sum;\n    total_sum = 0.0;\n    double log_sum=0;\n    // poisson termo of the ELBO for user-document ratings\n    // sum_u,d,k{ Eq[log p(r_ud|*) ] }\n    cout << r_entries.size() << \" nrat \" << _n_ratings;\n    for(size_t  ud=0; ud< _n_ratings;ud++) {\n        size_t  user_u = std::get<0>(r_entries[ud]);\n        size_t  item_i = std::get<1>(r_entries[ud]);\n        size_t  r_ud = std::get<2>(r_entries[ud]);\n        log_sum=0;\n        for (size_t  k = 0; k < _k_feat; k++) {\n            if(xi_M(ud,k) > 0)\n                log_sum += xi_M(ud,k)*(eta.elog_expected(user_u,k)+theta.elog_expected(item_i,k)-log(xi_M(ud,k)));\n            if(xi_N(ud,k) > 0)\n                log_sum += xi_N(ud,k)*(eta.elog_expected(user_u,k)+epsilon.elog_expected(item_i,k)-log(xi_N(ud,k)));\n            if(log_sum!=log_sum)\n            {\n                cout << \"(NAN-logsum: ud=\"<<ud<<\", k=\"<<k<<\" xi_M(ud,k)=\"<<xi_M(ud,k)<<\" xi_N(ud,k)=\"<<xi_N(ud,k)\n                     <<\" E_q[log eta_uk]=\"<<eta.elog_expected(user_u,k)<<\" E_q[log the_dk]=\"<<theta.elog_expected(item_i,k)\n                     <<\" E_q[log eta_uk]=\"<<epsilon.elog_expected(user_u,k);\n            }\n        }\n        if(ud==0)\n            cout << \"logsum = \" << log_sum << \" \";\n        for (pair<size_t,size_t> neighb : user_items_neighboors[ud]) {\n            //neighb is user_i in N(user_u), neighb.first is its index in the trust tau variable\n            // user_items_neighboors[ud].push_back(make_pair(user_i,ifind->second));\n            size_t  r_id = std::get<2>(r_entries[neighb.second]);\n            if(xi_S(ud,neighb.first) > 0)\n                log_sum += xi_S(ud,neighb.first)*(tau.elog_expected(user_u,neighb.first)+log(r_id )\n                                                       -log(xi_S(ud,neighb.first)));\n        }\n        if(ud==0)\n            cout << \"logsum = \" << log_sum << \" \";\n        total_sum+=r_ud*log_sum-boost::math::lgamma(r_ud+1);\n        if(boost::math::isnan( total_sum))\n            cout << \"##LOG_SUM ud=\"<<ud<<\", user_u=\"<<user_u<<\"item_i=\"<<item_i<<\" r_ud=\"<<r_ud<<\"##\";\n        /** TODO:\n         * - sum_u,d,k over Eq[latent variables] (Eq without log probability)\n         */\n    }\n    // poisson termo of the ELBO for word-document count\n    // sum_v,d,k{ Eq[log p(w_dv|*) ] }\n    //cout << xi_M;\n    //cout << theta;\n   // cout << endl;\n    //cout << \"r entries \"<< std::get<0>(r_entries[0]) << \" \" << std::get<1>(r_entries[0]) << \" \" << boost::math::lgamma(std::get<2>(r_entries[0])+1) << \" \" <<endl;\n    cout << \"partial elbo 1 \"<<total_sum;\n    cout << endl;\n    for(size_t dv=0; dv< _n_wd_entries;dv++){\n        size_t  word_w = std::get<1>(w_entries[dv]);\n        size_t item_i = std::get<0>(w_entries[dv]);\n        size_t  w_dv = std::get<2>(w_entries[dv]);\n        log_sum=0;\n        for(size_t k=0; k< _k_feat;k++){\n            log_sum += phi(dv,k)*(beta.elog_expected(word_w,k)+theta.elog_expected(item_i,k)- log(phi(dv,k)));\n            if(boost::math::isnan( log_sum))\n                cout << \"##LOG_SUM dv=\"<<dv<<\", k=\"<<k<<\", word_w=\"<<word_w<<\"item_i=\"<<item_i<<\" phi(dv,k)=\"<<phi(dv,k)<<\", beta.elog_expected(word_w,k)=\"\n                     <<beta.elog_expected(word_w,k)\n                     <<\", beta.elog_expected(word_w,k)=\"<<beta.elog_expected(word_w,k)\n                     <<\",theta.elog_expected(item_i,k)=\"<<theta.elog_expected(item_i,k)\n                     <<\",log(phi(dv,k)))=\"<<log(phi(dv,k))\n                        <<\"##\";\n\n        }\n\n\n\n\n        total_sum+=(((double)w_dv)*log_sum)-boost::math::lgamma(w_dv+1);\n        if(boost::math::isnan( total_sum))\n            cout << \"##LOG_SUM dv=\"<<dv<<\", word_w=\"<<word_w<<\"item_i=\"<<item_i<<\" w_dv=\"<<w_dv<<\"##\";\n        /* if(w_dv >= 1){\n            try {\n                double x=boost::math::lgamma(w_dv+1);\n                //cout << \"boot lgamma =\" << x << \" wdv=\" << w_dv << endl ;\n                if(boost::math::isnan( log_sum))\n                    cout << \"##LOG_SUM dv=\"<<dv<<\", word_w=\"<<word_w<<\"item_i=\"<<item_i<<\" w_dv=\"<<w_dv<<\"log-fact=\"<<x<<\"##\";\n                total_sum-=x;\n                //cout << \"total_sum =\" << total_sum << endl ;\n            } catch (const std::bad_alloc& e) {\n                std::cout << \"Allocation failed: \" << e.what() << '\\n';\n                exit(-1);\n            }\n\n        }*/\n\n\n        /** TODO:\n         * - sum_v,d,k over Eq[latent variables] (Eq without log probability)\n         */\n\n    }\n\n    //term with sum of multiplication of expected-value of latent variables\n    // -sum_k,d,v E[theta_dk]*E[beta_vk]\n    total_sum+=theta.elbo_term_prod_linear_expectations(vector<gamma_latent*>({&beta}));\n    if(boost::math::isnan( total_sum ))\n        cout << \"##TOTAL_SUM theta*beta\";\n    // -sum_k,d,u E[theta_dk]*E[eta_uk]+E[epsilon_dk]*E[eta_uk]\n    total_sum+=eta.elbo_term_prod_linear_expectations(vector<gamma_latent*>({&theta,&epsilon}));\n    if(boost::math::isnan( total_sum ))\n        cout << \"##TOTAL_SUM theta*eta+epsilon*eta\";\n    total_sum+=tau_elbo_expected_linear_term();\n    if(boost::math::isnan( total_sum ))\n        cout << \"##TOTAL_SUM tau\";\n\n\n    // Gamma terms for the latent variables\n    total_sum+=beta.elbo_term();\n    if(boost::math::isnan( total_sum ))\n        cout << \"##TOTAL_SUM gamma beta\";\n    total_sum+=theta.elbo_term();\n    if(boost::math::isnan( total_sum ))\n        cout << \"##TOTAL_SUM gamma theta\";\n    total_sum+=epsilon.elbo_term();\n    if(boost::math::isnan( total_sum ))\n        cout << \"##TOTAL_SUM gamma epsilon\";\n    total_sum+=eta.elbo_term();\n    if(boost::math::isnan( total_sum ))\n        cout << \"##TOTAL_SUM  gamma eta\";\n    total_sum+=tau.elbo_term();\n    if(boost::math::isnan( total_sum ))\n        cout << \"##TOTAL_SUM  gamma tau\";\n    return total_sum;\n}\n/*\n * TODO:\n * - Change everything about tau variable. There is two options:\n * 1) kdim of tau variable is = n_users;\n * 2) kdim of tau variable is = n_users_that_are_neighbors.\n * In beginning to think that option 1) is better, but it will need some changing in other places\n *\n * UPDATE: implemented option 1\n */\n\ndouble BatchPoissonNewArray::tau_elbo_expected_linear_term() {\n    double total_sum=0;\n    for(size_t u=0;u < _n_users ;u++) {\n        for(size_t i : user_neighboors[u]) {\n            for(size_t d=user_items_index[i].first; d<user_items_index[i].second;d++) {\n                size_t r_id = std::get<2>(r_entries[d]);\n                total_sum+=tau.e_expected(u,i)*r_id;\n            }\n        }\n    }\n    return -total_sum;\n}\n\n\nvector<vector<double>>  BatchPoissonNewArray::estimate() {\n    cout << \"begin estimate\" <<endl;\n    vector<vector<double>> ret(_n_users);\n    for(size_t user_u=0;user_u < _n_users; user_u++){\n        for(size_t item_i=0;item_i < _n_items ; item_i++){\n            double r_ui = 0;\n            for(size_t k=0;k<_k_feat;k++){\n                r_ui += eta.e_expected(user_u,k)*(epsilon.e_expected(item_i,k)+theta.e_expected(item_i,k));\n            }\n            for(size_t user_i : user_neighboors[user_u]){\n                pairmap::iterator ifind = user_items_map.find(make_pair(user_i,item_i));\n                if ( ifind != user_items_map.end() )\n                    r_ui += tau.e_expected(user_u,user_i)*ifind->second;\n            }\n            ret[user_u].push_back(r_ui);\n        }\n    }\n    cout << \"end estimate\" <<endl;\n    return ret;\n}\n\nstruct predicate\n{\n    bool operator()(const std::pair<double,size_t> &left, const std::pair<double,size_t> &right)\n    {\n        return left.first < right.first;\n    }\n};\n\nvector<vector<size_t>> BatchPoissonNewArray::recommend(size_t m) {\n    cout << \"begin recommend\" <<endl;\n\n    vector< vector<double>> ret= estimate();\n    vector<vector<size_t>> rec;\n    ;\n\n    for(size_t user_u=0;user_u < _n_users; user_u++)\n    {\n        vector<pair<double,size_t>> scores;\n        for(size_t item_i=0;item_i < _n_items ; item_i++){\n            // recommend only items that are not already rated by the user\n            if(user_items_map.count(make_pair(user_u,item_i))<=0)\n                scores.push_back(make_pair(ret[user_u][item_i],item_i));\n        }\n        std::sort(scores.begin(),scores.end());\n        std::reverse(scores.begin(),scores.end());\n        vector<size_t> temp;\n        for(size_t i=0; i < m ; i++)\n        {\n            //cout << \"(\" <<scores[i].first <<\",\"<<scores[i].second<<\")\";\n            temp.push_back(scores[i].second);\n        }\n        //cout << endl;\n        rec.push_back(temp);\n    }\n    return rec;\n}\n\nvoid BatchPoissonNewArray::recommend(std::ostream &output, size_t m) {\n    cout << \"begin recommend save\" <<endl;\n\n    vector<vector<double>> ret= estimate();\n\n    for(size_t user_u=0;user_u < _n_users; user_u++)\n    {\n        vector<pair<double,size_t>> scores;\n        for(size_t item_i=0;item_i < _n_items ; item_i++){\n            // recommend only items that are not already rated by the user\n            if(user_items_map.count(make_pair(user_u,item_i))<=0)\n                scores.push_back(make_pair(ret[user_u][item_i],item_i));\n        }\n        std::sort(scores.begin(),scores.end());\n        std::reverse(scores.begin(),scores.end());\n        vector<size_t> temp;\n        for(size_t i=0; i < m ; i++)\n        {\n            //cout << \"(\" <<scores[i].first <<\",\"<<scores[i].second<<\")\";\n            temp.push_back(scores[i].second);\n        }\n        std::copy (temp.begin(), temp.end(), std::ostream_iterator<size_t>(output, \"\\t\"));\n        output << endl;\n    }\n}\n\nBatchPoissonNewArray::~BatchPoissonNewArray() {\n    arrman->~ArrayManager();\n}\n\n\nvars operator++(vars &x) { return x = (vars)(((int)(x) + 1)); }\n\n\n\nvoid gamma_latent::update_expected() {\n    for ( size_t i=0; i< a_latent.rows();i++ ){\n        for( size_t k=0; k< a_latent.cols();k++){\n            e_expected(i,k) = a_latent(i,k)/b_latent(k);\n            if(i==k && i==0)\n            {\n                if(boost::math::isnan( e_expected(i,k)))\n                    cout << \"NAN-EXP \"<<i<<\" \"<<k<<\" a_latent=\"<<a_latent(i,k)<<\" b_latent=\"<<b_latent(k);\n            }\n\n            //elog_x(i,k) = (double)(digammal(a_x(i,k))-log(b_x(k))); // using standalone implementation\n            elog_expected(i, k) = boost::math::digamma(a_latent(i, k)) - log(b_latent(k)); // using boost implementation\n            if(i==k && i==0) {\n                if (boost::math::isnan(elog_expected(i, k)))\n                    cout << \"NAN-LOGEXP \" << i << \" \" << k << \" digama a_latent=\"\n                         << boost::math::digamma(a_latent(i, k)) << \" b_latent=\" << b_latent(k) << \" log b\"\n                         << log(b_latent(k));\n            }\n        }\n    }\n}\n\ndouble gamma_latent::elbo_term() {\n    double total_sum=0;\n    for( size_t  d=0;d<a_latent.nrow;d++){\n        for( size_t  k=0; k<a_latent.ncol;k++){\n            total_sum+=gamma_term(a,b,a_latent(d,k),b_latent(k),e_expected(d,k),elog_expected(d,k));\n        }\n    }\n    return total_sum;\n}\n\ndouble gamma_latent::elbo_term(vector<gamma_latent*> vars) {\n    double total_sum=0;\n    for( size_t d=0;d<a_latent.nrow;d++){\n        for( size_t  k=0; k<a_latent.ncol;k++){\n            total_sum+=gamma_term(a,b,a_latent(d,k),b_latent(k),e_expected(d,k),elog_expected(d,k));\n            for(gamma_latent* var : vars){\n                if(var)\n                    total_sum+=gamma_term(var->a,var->b,var->a_latent(d,k),var->b_latent(k),var->e_expected(d,k),var->elog_expected(d,k));\n            }\n        }\n    }\n    return total_sum;\n}\n\n\n\n\ngamma_latent::gamma_latent(const Arrayf &a_latent, const Arrayf &b_latent, const Arrayf &e_expected,\n                           const Arrayf &elog_expected, double a, double b) :\n        a_latent(a_latent), b_latent(b_latent),\n        e_expected(e_expected),\n        elog_expected(elog_expected), a(a), b(b),\n        nvars(a_latent.nrow),kdim(a_latent.ncol){}\n\nvoid gamma_latent::init_b_latent() {\n    b_latent=b;\n}\n\nvoid gamma_latent::init_a_latent() {\n    a_latent=a;\n\n}\n\ndouble gamma_latent::elbo_term_prod_linear_expectations(vector<gamma_latent *> vars) {\n    double total_sum=0;\n\n\n    for(gamma_latent* var : vars)\n    {\n        if(var)\n        {\n\n            for( size_t  j=0;j<(var->nvars);j++)\n            {\n                for (int k = 0; k < kdim; ++k)\n                {\n                    auto expjk=var->e_expected(j,k);\n                    for( size_t  i=0;i<nvars;i++)\n                        total_sum+=e_expected(i,k)*expjk;\n                }\n            }\n        }\n    }\n\n\n    return (-total_sum);\n}\n\n\n\ngamma_latent::gamma_latent( ArrayManager<double>* arrman, size_t nrows, size_t ncols, double a, double b):\n        a(a), b(b), a_latent(arrman->makeArray(nrows,ncols,a)),b_latent(arrman->makeArray(ncols,b)),\n        e_expected(arrman->makeArray(nrows,ncols)),elog_expected(arrman->makeArray(nrows,ncols)),\n        nvars(nrows),kdim(ncols)\n{\n\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "5900dd8d25d98687fb3140f02ad4ca88e4e079a9", "size": 26752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BatchPoissonPure.cpp", "max_stars_repo_name": "zehsilva/poissonmf_cs", "max_stars_repo_head_hexsha": "5e870a6616ce8940d7de6aa108e005893edf184c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-09-05T12:29:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T12:44:55.000Z", "max_issues_repo_path": "BatchPoissonPure.cpp", "max_issues_repo_name": "zehsilva/poissonmf_cs", "max_issues_repo_head_hexsha": "5e870a6616ce8940d7de6aa108e005893edf184c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BatchPoissonPure.cpp", "max_forks_repo_name": "zehsilva/poissonmf_cs", "max_forks_repo_head_hexsha": "5e870a6616ce8940d7de6aa108e005893edf184c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T02:19:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T05:58:39.000Z", "avg_line_length": 35.2463768116, "max_line_length": 164, "alphanum_fraction": 0.5599955144, "num_tokens": 7472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.5460371095624997}}
{"text": "/*\n * world = K [R | t]\n */\n#include <Eigen/Dense>\n#include <iostream>\n#include <math.h>\n\nstruct rgbpoint\n{\n\trgbpoint(): r(0),g(0),b(0) {}\n\tchar r,g,b;\n} __attribute__((packed));\n\n// [sx 0 cx]\n// [0 sy cy]\n// [0 0 1]\n//\n// to 4x4\nvoid intrinsics2m44(Eigen::Matrix4d & out, Eigen::Matrix3d & in)\n{\n\tout.setZero();\n\tout.block<3,3>(0,0) = in;\n\tout(3,3) = 1;\n\n//\tout << in(0,0),in(0,1),0,in(0,2)    ,in(1,0),in(1,1),0,in (1,2),   0,0,1,0,   0,0,0,1;\n}\n\nvoid composerotot(Eigen::Matrix4d& out, const Eigen::Matrix3d & R, const Eigen::Vector3d & T)\n{\n\t\tout.setZero();\n\t\tout.block<3,3>(0,0) = R;\n\t\tout.block<3,1>(0,3) = T;\n\t\tout(3,3) = 1;\n\n}\n\n#ifdef __MINGW32__\n#define DE __declspec(dllexport)\n#else\n#define DE\n\n#endif\n\nextern \"C\"\n{\n\tvoid DE initlibanyregistration(){}\n\t/// output is color computed as depth in sizes \n\tvoid DE register2color(char * outrgb, int cw, int ch, const char * rgb, int dw, int dh, const uint16_t * depth, const double depthK[9], const double colorK[9], const double inrotation[9], const double position[3])\n\t{\t\n\t\tstatic_assert(sizeof(rgbpoint) == 3,\"rgpoint should be 3 bytes\");\n\n\t\tfloat maxdistance_mm = 10000;\n\n\n\t\tEigen::Matrix3d rotation = Eigen::Matrix<double, 3, 3, Eigen::RowMajor>::Map(inrotation);\n\t\tEigen::Vector3d translation = Eigen::Vector3d::Map(position);\n\t\tEigen::Matrix3d depth_matrix = Eigen::Matrix<double, 3, 3, Eigen::RowMajor>::Map(depthK);\n\t\tEigen::Matrix3d rgb_matrix = Eigen::Matrix<double, 3, 3, Eigen::RowMajor>::Map(colorK);\n\n\t\tstd::cout << \"Rotation is\\n \" << rotation << std::endl;\n\t\tstd::cout << \"Kdepth is\\n\" << depth_matrix << std::endl;\n\n\t\tEigen::Matrix4d rototranslationD2R;\n\t\tEigen::Matrix4d odepth_matrix;\n\t\tEigen::Matrix4d orgb_matrix;\n\t\t\n\t\tintrinsics2m44(odepth_matrix,depth_matrix);\n\t\tintrinsics2m44(orgb_matrix,rgb_matrix);\n\t\tcomposerotot(rototranslationD2R,rotation,translation);\n\n\t\tstd::cout << \"Kdepth4 is\\n\" << odepth_matrix << std::endl;\n\n\t\tstd::cout << \"rototraslation(W->D)\\n\" << rototranslationD2R << std::endl;\n\n\t\tEigen::Matrix4d depth2rgb4 = orgb_matrix * rototranslationD2R * odepth_matrix.inverse();\n//\t\tEigen::Matrix4d depth2rgb4 = orgb_matrix * (odepth_matrix*rototranslationD2R).inverse();\n\n\t\tstd::cout << \"depth2rgb4\\n\" << depth2rgb4 << std::endl;\n\n\t\tconst  uint16_t * inputdepth_mm = depth;\n\t\trgbpoint * out = (rgbpoint*)outrgb;\n\t\tconst rgbpoint * inputcolor = (rgbpoint*)rgb;\n\n\t\tmemset(out,0,dw*dh*3);\n\n\t\tfor(int y = 0; y < dh; ++y)\n\t\t{\t\n\t\t\tfor(size_t x = 0; x < dw; ++x, inputdepth_mm++,out++)\n\t\t\t{\n\t\t\t\tif(!*inputdepth_mm)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// Check for invalid measurements\n\t\t\t\tif(*inputdepth_mm >= maxdistance_mm)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tconst float depth_value = *inputdepth_mm / 1000.0f;\n\n\n\t\t\t\t//Eigen::Vector4d psd(x, y, 1.0, 1.0/depth_value);\n\t\t\t\t//Eigen::Vector4d psddiv = psd * depth_value;\n\t\t\t\t//Eigen::Vector4d pworld = depth2world * psddiv;\n\t\t\t\t//Eigen::Vector4d rgb_img_homo = world2rgb * pworld;\n\n\t\t\t\tEigen::Vector4d psd(x, y, 1.0, 1.0/depth_value);\n\t\t\t\tEigen::Vector4d rgb_img_homo = depth2rgb4 * (psd * depth_value);\n\t\t\t\tEigen::Vector4d rgb_img = rgb_img_homo / rgb_img_homo.z();\n\n\n\t\t\t\tint ix = rgb_img.x();\n\t\t\t\tint iy = rgb_img.y();\n\n\t\t\t\tif(ix >= 0 && ix < cw && iy >= 0 && iy < ch)\n\t\t\t\t{\t\n\t\t\t\t\t*out = inputcolor[iy*cw+ix];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// NOT WORKING DUE TO FILLING\n\t/// output is depth computed as color in size\n\tvoid DE register2depth(uint16_t * outdepth, int cw, int ch, const char * rgb, int dw, int dh, const uint16_t * depth, const double depthK[9], const double colorK[9], const double inrotation[9], const double position[3])\n\t{\t\n\t\tfloat maxdistance = 10;\n\n\t\tEigen::Matrix3d rotation = Eigen::Matrix<double, 3, 3, Eigen::RowMajor>::Map(inrotation);\n\t\tEigen::Vector3d translation = Eigen::Vector3d::Map(position);\n\t\tEigen::Matrix3d depth_matrix = Eigen::Matrix<double, 3, 3, Eigen::RowMajor>::Map(depthK);\n\t\tEigen::Matrix3d rgb_matrix = Eigen::Matrix<double, 3, 3, Eigen::RowMajor>::Map(colorK);\n\n\t\tEigen::Matrix4d rototranslationD2R;\n\t\tEigen::Matrix4d orgb_matrix,odepth_matrix;\n\n\t\tintrinsics2m44(odepth_matrix,depth_matrix);\n\t\tintrinsics2m44(orgb_matrix,rgb_matrix);\n\t\tcomposerotot(rototranslationD2R,rotation,-translation);\n\n\n\t\t//odepth_matrix.block<3,3>(0,0) = depth_matrix;\n\t\t//odepth_matrix(3,3) = 1;\n\n\t\t//orgb_matrix.block<3,3>(0,0) = rgb_matrix;\n\t\t//orgb_matrix(3,3) = 1;\n\n\t\tstd::cout << rototranslationD2R << std::endl;\n\n\t\tEigen::Matrix4d depth2rgb4 = orgb_matrix * rototranslationD2R * odepth_matrix.inverse();\n\t\tEigen::Matrix3d rgb2depth = depth2rgb4.block<3,3>(0,0).inverse();\n\n\n\t\tmemset(outdepth,0,cw*ch*2); // cleanup output (max value)\n\t\tauto po = outdepth;\n\n\t\tfor(int y = 0; y < ch; ++y)\n\t\t{\t\n\t\t\tfor(size_t x = 0; x < cw; ++x,++po)\n\t\t\t{\n\n\t\t\t\tEigen::Vector3d rgb_i(x,y,1); // 2D homo\n\t\t\t\tEigen::Vector3d depth_sub_i = rgb2depth * rgb_i; // to 2D homo\n\t\t\t\tint ix = depth_sub_i.x();\n\t\t\t\tint iy = depth_sub_i.y();\n\n\t\t\t\t// if inside, and valid and nearer than the current\n\t\t\t\tif(ix >= 0 && ix  < dw && iy >= 0 && iy < dh )\n\t\t\t\t{\n\t\t\t\t\t int off = iy*dw+ix;\n\t\t\t\t\t uint16_t current = depth[off];\n\t\t\t\t\t *po = current;\n\t\t\t\t\t //uint16_t *target = outdepth + off; // target output\n\t\t\t\t\t //if(current > 0 && (*target == 0 || *target > current))\n\t\t\t\t\t //*target = current;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t\tTo obtain world coords\n\t\t\t\t\tEigen::Vector4d psd(depth_sub_i.x(),depth_sub_i.y(), 1.0, 1.0/newdepth);\n\t\t\t\t\tEigen::Vector4d psddiv = psd * newdepth; // (x*newdepth,y*newdepth,newdepth,1)\n\t\t\t\t\tEigen::Vector4d pworld =  depth2world  * psddiv;\n\t\t\t\t*/\n\t\t\t}\n\t\t}\n\t}\n}", "meta": {"hexsha": "2219e583d6cb6afb47f818df57dc5297cf567691", "size": 5460, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extern/anyregistration/anyregistration.cpp", "max_stars_repo_name": "iiharu/pyoni", "max_stars_repo_head_hexsha": "3e62cedc1ed7dc726e421858ff143f7b7a713403", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-06-16T15:26:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-29T17:40:52.000Z", "max_issues_repo_path": "extern/anyregistration/anyregistration.cpp", "max_issues_repo_name": "iiharu/pyoni", "max_issues_repo_head_hexsha": "3e62cedc1ed7dc726e421858ff143f7b7a713403", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-06-16T15:39:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-19T16:14:53.000Z", "max_forks_repo_path": "extern/anyregistration/anyregistration.cpp", "max_forks_repo_name": "iiharu/pyoni", "max_forks_repo_head_hexsha": "3e62cedc1ed7dc726e421858ff143f7b7a713403", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T08:27:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-16T10:25:07.000Z", "avg_line_length": 29.5135135135, "max_line_length": 220, "alphanum_fraction": 0.6505494505, "num_tokens": 1914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5460290979523703}}
{"text": "/* Copyright Institute of Sound and Vibration Research - All rights reserved */\n\n#include \"time_frequency_inverse_transform.hpp\"\n\n#include <libefl/vector_functions.hpp>\n\n#include <libpml/time_frequency_parameter.hpp>\n#include <libpml/time_frequency_parameter_config.hpp>\n\n#include <librbbl/circular_buffer.hpp>\n#include <librbbl/fft_wrapper_base.hpp>\n#include <librbbl/fft_wrapper_factory.hpp>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <algorithm>\n#include <ciso646>\n#include <cmath>\n\nnamespace visr\n{\nnamespace rcl\n{\n\nTimeFrequencyInverseTransform::TimeFrequencyInverseTransform( SignalFlowContext const & context,\n                                                              char const * name,\n                                                              CompositeComponent * parent,\n                                                              std::size_t numberOfChannels,\n                                                              std::size_t dftLength,\n                                                              std::size_t hopSize,\n                                                              char const * fftImplementation /*= \"default\"*/ )\n : AtomicComponent( context, name, parent )\n , mAlignment( cVectorAlignmentSamples )\n , mNumberOfChannels( numberOfChannels )\n , mDftLength( dftLength )\n , mDftSamplesPerPeriod( period() / hopSize )\n , mHopSize( hopSize )\n , mAccumulationBuffer( mNumberOfChannels, mDftLength - mHopSize, mAlignment )\n , mFftWrapper( rbbl::FftWrapperFactory<SampleType>::create( fftImplementation, dftLength, mAlignment ) )\n , mCalcBuffer(mDftLength, mAlignment )\n , mInput( \"in\", *this, pml::TimeFrequencyParameterConfig( dftLength, hopSize, numberOfChannels, mDftSamplesPerPeriod ) )\n , mOutput( \"out\", *this, numberOfChannels )\n{\n  if( period() % hopSize != 0 )\n  {\n    throw std::invalid_argument( \"TimeFrequencyInverseTransform: Invalid hop size (no integer number of hops per audio processing period).\" );\n  }\n}\n\nTimeFrequencyInverseTransform::~TimeFrequencyInverseTransform() = default;\n\nvoid TimeFrequencyInverseTransform::process()\n{\n  pml::TimeFrequencyParameter<SampleType> const & inMtx = mInput.data();\n  const std::size_t accuElementsToCopy = mDftLength - mHopSize;\n  // operating channel by channel might save copying to and fro the accumulation buffer in case of multiple hops per period.\n  for( std::size_t channelIndex( 0 ); channelIndex < mNumberOfChannels; ++channelIndex )\n  {\n    efl::ErrorCode res;\n    for( std::size_t hopIndex( 0 ); hopIndex < mDftSamplesPerPeriod; ++hopIndex )\n    {\n      std::complex<SampleType> const * dftPtr = inMtx.dftSlice( channelIndex, hopIndex );\n      res = mFftWrapper->inverseTransform( dftPtr, mCalcBuffer.data() );\n      if( res != efl::noError )\n      {\n        throw std::runtime_error( \"TimeFrequencyInverseTransform: Error during FFT operation.\" );\n      }\n      res = efl::vectorAddInplace( mAccumulationBuffer.row(channelIndex), mCalcBuffer.data(), accuElementsToCopy );\n      if( res != efl::noError )\n      {\n        throw std::runtime_error( \"TimeFrequencyInverseTransform: Updating of output accumulator failed.\" );\n      }\n      // Copy the output buffer back into storage (skip first block to implement the shift)\n      if( (res = efl::vectorCopy( mCalcBuffer.data() + mHopSize, mAccumulationBuffer.row( channelIndex ), accuElementsToCopy )) != efl::noError )\n      {\n        throw std::runtime_error( \"TimeFrequencyInverseTransform: Storing partial results failed.\" );\n      }\n    }\n    // Copy first portion of accumulated result to output port.\n    if( (res = efl::vectorCopy( mCalcBuffer.data(), mOutput[channelIndex], period(), mAlignment )) != efl::noError )\n    {\n      throw std::runtime_error( \"TimeFrequencyInverseTransform: Error while copying output data.\" );\n    }\n  }\n}\n\n} // namespace rcl\n} // namespace visr\n", "meta": {"hexsha": "8962d6abb090706529ab7bebd31bda6c627e902e", "size": 3851, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/librcl/time_frequency_inverse_transform.cpp", "max_stars_repo_name": "s3a-spatialaudio/VISR", "max_stars_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-12T14:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T01:16:23.000Z", "max_issues_repo_path": "src/librcl/time_frequency_inverse_transform.cpp", "max_issues_repo_name": "s3a-spatialaudio/VISR", "max_issues_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_issues_repo_licenses": ["ISC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/librcl/time_frequency_inverse_transform.cpp", "max_forks_repo_name": "s3a-spatialaudio/VISR", "max_forks_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T12:53:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T10:08:08.000Z", "avg_line_length": 43.2696629213, "max_line_length": 145, "alphanum_fraction": 0.6626850169, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5460290979523703}}
{"text": "//Link to Boost\n#define BOOST_TEST_DYN_LINK\n\n//VERY IMPORTANT - include this last\n//#include <boost/test/included/unit_test.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"test.h\"\n#include \"../HomotopyContinuation.h\"\n#include \"../BetheHomotopy.h\"\n#include \"../BethePolynomialHomotopy.h\"\n\n\n// test suite\nBOOST_FIXTURE_TEST_SUITE(Integrated_suite, SimpleTestFixture, * utf::label(\"IntegratedTests\"))\n\nBOOST_AUTO_TEST_CASE(SimpleHomotopy_test1)\n{\n    UnityEquation start(1, 2);\n    std::vector<var_t> coefs({-20.0,1.0,1.0});\n    PolynomialFunction target(coefs);\n    SimpleHomotopy sh(&start, &target);\n    sh.setSteps(100);\n    SimpleHomotopyContinuation hc;\n    \n    // one root is 5 and the other one is -4\n    bool found1 = false;\n    bool found2 = false;\n    \n    for (int i = 0; i < start.numberOfRoots(); i++) {\n        Vector st = start.getRoot(i);\n        Solution sol(st);\n        hc.solve(sh, sol);\n        BOOST_TEST(sol.root().size() == 1);\n        if (std::abs(sol.get(0) - (elem_t)4.0)) {\n            found1 = true;\n        }\n        if (std::abs(sol.get(0) + (elem_t)5.0)) {\n            found2 = true;\n        }\n    }\n    BOOST_TEST(found1);\n    BOOST_TEST(found2);\n}\n\nBOOST_AUTO_TEST_CASE(SimpleHomotopy_test2)\n{\n    UnityEquation start(1, 4);\n    std::vector<var_t> coefs({-20.0,0,1.0,0,1.0});\n    PolynomialFunction target(coefs);\n    SimpleHomotopy sh(&start, &target);\n    sh.setSteps(100);\n    SimpleHomotopyContinuation hc;\n    \n    // there are found roots.\n    bool found1 = false;\n    bool found2 = false;\n    bool found3 = false;\n    bool found4 = false;\n    \n    for (int i = 0; i < start.numberOfRoots(); i++) {\n        Vector startRoot = start.getRoot(i);\n        Solution sol(startRoot);\n        hc.solve(sh, sol);\n        if (std::abs(sol.get(0) - (elem_t)2.0) < EPS) {\n            found1 = true;\n        }\n        if (std::abs(sol.get(0) + (elem_t)2.0) < EPS) {\n            found2 = true;\n        }\n        if (std::abs(sol.get(0) - var_t((elem_t).0, (elem_t)sqrt(5.0))) < 1e-6) {\n            found3 = true;\n        }\n        if (std::abs(sol.get(0) + var_t((elem_t).0, (elem_t)sqrt(5.0))) < 1e-6) {\n            found4 = true;\n        }\n    }\n    BOOST_TEST(found1);\n    BOOST_TEST(found2);\n    BOOST_TEST(found3);\n    BOOST_TEST(found4);\n}\n\nBOOST_AUTO_TEST_CASE(BethePolynomialHomotopy_L6M2)\n{\n    std::cout << \"Running integrated test for L=6, M=2 cases\" << std::endl;\n    int L = 6;\n    int M = 2;\n    elem_t totalPhase = Pi;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    BethePolynomialHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    \n    SET_LOG_LEVEL(Error);\n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n        LOG(\"processing root #\" << i << \":\\t\" << cache.getRoot(i), Warning);\n        std::string file = \"BS_L\" + ToString(L)+ \"M\" + ToString(M)+ \"r\" + ToString(i) + \".txt\";\n        hc.setTraceFile(file);\n\n        Vector startRoot = cache.getRoot(i);\n        InvertableSolution sol(startRoot, L);\n        std::cout << \"eps=\" << sol.epsilon() << \", c=\" << sol.c() << std::endl;\n        hc.solve(hom, sol);\n        std::cout <<\"i=\" << i << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps() << std::endl;\n        BOOST_TEST_INFO(\"i=\" << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps());\n        BOOST_TEST(hc.gaps().max() < .5L);\n\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi);\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n    SET_LOG_LEVEL(Error);\n}\n\nBOOST_AUTO_TEST_CASE(BethePolynomialHomotopy_L6M3)\n{\n    std::cout << \"Running integrated test for L=6, M=2 cases\" << std::endl;\n    int L = 6;\n    int M = 3;\n    elem_t totalPhase = Pi;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    BethePolynomialHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    \n    SET_LOG_LEVEL(Error);\n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n        LOG(\"processing root #\" << i << \":\\t\" << cache.getRoot(i), Warning);\n        Vector startRoot = cache.getRoot(i);\n        InvertableSolution sol(startRoot, L);\n        std::cout << \"eps=\" << sol.epsilon() << \", c=\" << sol.c() << std::endl;\n        hc.solve(hom, sol);\n        std::cout <<\"i=\" << i << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps() << std::endl;\n        BOOST_TEST_INFO(\"i=\" << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps());\n        BOOST_TEST(hc.gaps().max() < .5L);\n\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi);\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n    SET_LOG_LEVEL(Error);\n}\n\nBOOST_AUTO_TEST_CASE(BethePolynomialHomotopy_L7M2)\n{\n    int L = 7;\n    int M = 2;\n    std::cout << \"Running integrated test for L=\" << L << \", M=\" << M << \" cases\" << std::endl;\n    elem_t totalPhase = Pi;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    BethePolynomialHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    \n    SET_LOG_LEVEL(Error);\n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n        LOG(\"processing root #\" << i << \":\\t\" << cache.getRoot(i), Warning);\n        Vector startRoot = cache.getRoot(i);\n        InvertableSolution sol(startRoot, L);\n        std::cout << \"eps=\" << sol.epsilon() << \", c=\" << sol.c() << std::endl;\n        try {\n            hc.solve(hom, sol);\n        } catch (HomotopyContinuationException &ex) {\n            std::cout << ex.what() << std::endl;\n//            throw ex;\n        }\n        std::cout <<\"i=\" << i << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps() << std::endl;\n        BOOST_TEST_INFO(\"i=\" << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps());\n        BOOST_TEST(hc.gaps().max() < .5L);\n\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi);\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n    SET_LOG_LEVEL(Error);\n}\n\nBOOST_AUTO_TEST_CASE(BethePolynomialHomotopy_L7M3)\n{\n    int L = 7;\n    int M = 3;\n    std::cout << \"Running integrated test for L=\" << L << \", M=\" << M << \" cases\" << std::endl;\n    elem_t totalPhase = Pi;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    BethePolynomialHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    \n    SET_LOG_LEVEL(Error);\n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n        LOG(\"processing root #\" << i << \":\\t\" << cache.getRoot(i), Warning);\n        std::string file = \"BS_L\" + ToString(L)+ \"M\" + ToString(M)+ \"r\" + ToString(i) + \".txt\";\n//        hc.setTraceFile(file);\n\n        Vector startRoot = cache.getRoot(i);\n        InvertableSolution sol(startRoot, L);\n        if (sol.indexOfSingularRoot1() >= 0) {\n            std::cout << \"eps=\" << sol.epsilon() << \", c=\" << sol.c() << std::endl;\n        }\n        try {\n            hc.solve(hom, sol);\n        } catch (HomotopyContinuationException &ex) {\n            std::cout << ex.what() << std::endl;\n            throw ex;\n        }\n        \n        std::cout <<\"i=\" << i << std::endl << \"errors=\" << hc.errors() << std::endl << \"gaps=\" << hc.gaps() << std::endl;\n        BOOST_TEST_INFO(\"i=\" << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps());\n        BOOST_TEST(hc.gaps().max() < .5L);\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi);\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n    SET_LOG_LEVEL(Error);\n}\n\nBOOST_AUTO_TEST_CASE(BethePolynomialHomotopy_L8M2)\n{\n    int L = 8;\n    int M = 2;\n    std::cout << \"Running integrated test for L=\" << L << \", M=\" << M << \" cases\" << std::endl;\n    elem_t totalPhase = Pi;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    BethePolynomialHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    \n    SET_LOG_LEVEL(Error);\n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n        LOG(\"processing root #\" << i << \":\\t\" << cache.getRoot(i), Warning);\n        std::string file = \"BS_L\" + ToString(L)+ \"M\" + ToString(M)+ \"r\" + ToString(i) + \".txt\";\n//        hc.setTraceFile(file);\n        Vector startRoot = cache.getRoot(i);\n        InvertableSolution sol(startRoot, L);\n        std::cout << \"eps=\" << sol.epsilon() << \", c=\" << sol.c() << std::endl;\n        hc.solve(hom, sol);\n        std::cout <<\"i=\" << i << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps() << std::endl;\n        BOOST_TEST_INFO(\"i=\" << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps());\n        BOOST_TEST(hc.gaps().max() < .5L);\n\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi);\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n    SET_LOG_LEVEL(Error);\n}\n\nBOOST_AUTO_TEST_CASE(BethePolynomialHomotopy_L8M3)\n{\n    int L = 8;\n    int M = 3;\n    std::cout << \"Running integrated test for L=\" << L << \", M=\" << M << \" cases\" << std::endl;\n    elem_t totalPhase = Pi;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    BethePolynomialHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    \n    SET_LOG_LEVEL(Error);\n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n        LOG(\"processing root #\" << i << \":\\t\" << cache.getRoot(i), Warning);\n        Vector startRoot = cache.getRoot(i);\n        InvertableSolution sol(startRoot, L);\n        std::cout << \"eps=\" << sol.epsilon() << \", c=\" << sol.c() << std::endl;\n        hc.solve(hom, sol);\n        std::cout <<\"i=\" << i << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps() << std::endl;\n        BOOST_TEST_INFO(\"i=\" << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps());\n        BOOST_TEST(hc.gaps().max() < .5L);\n\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi);\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n    SET_LOG_LEVEL(Error);\n}\n\nBOOST_AUTO_TEST_CASE(BethePolynomialHomotopy_L8M4)\n{\n    int L = 8;\n    int M = 4;\n    std::cout << \"Running integrated test for L=\" << L << \", M=\" << M << \" cases\" << std::endl;\n    elem_t totalPhase = 2 * Pi;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    BethePolynomialHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    hc.setMaxNumberOfNewtonRaphonEachStep(50);\n    hc.setMaxDepth(14);\n    \n    SET_LOG_LEVEL(Error);\n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n        LOG(\"processing root #\" << i << \":\\t\" << cache.getRoot(i), Warning);\n        std::string file = \"BS_L\" + ToString(L)+ \"M\" + ToString(M)+ \"r\" + ToString(i) + \".txt\";\n//        hc.setTraceFile(file);\n\n        Vector startRoot = cache.getRoot(i);\n        InvertableSolution sol(startRoot, L);\n        std::cout << \"eps=\" << sol.epsilon() << \", c=\" << sol.c() << std::endl;\n        hc.solve(hom, sol);\n        std::cout <<\"i=\" << i << \", errors=\" << hc.errors() << std::endl << \"gaps=\" << hc.gaps() << std::endl;\n        BOOST_TEST_INFO(\"i=\" << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps());\n        BOOST_TEST(hc.gaps().max() < .5L);\n\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi);\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n    SET_LOG_LEVEL(Error);\n}\n\nBOOST_AUTO_TEST_CASE(BethePolynomialHomotopy_L10M4)\n{\n    int L = 10;\n    int M = 4;\n    std::cout << \"Running integrated test for L=\" << L << \", M=\" << M << \" cases\" << std::endl;\n    elem_t totalPhase = Pi;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    BethePolynomialHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    hc.setMaxNumberOfNewtonRaphonEachStep(50);\n    \n    SET_LOG_LEVEL(Error);\n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n        LOG(\"processing root #\" << i << \":\\t\" << cache.getRoot(i), Warning);\n        std::string file = \"BS_L\" + ToString(L)+ \"M\" + ToString(M)+ \"r\" + ToString(i) + \".txt\";\n//        hc.setTraceFile(file);\n        Vector startRoot = cache.getRoot(i);\n        InvertableSolution sol(startRoot, L);\n        if (sol.indexOfSingularRoot1() >= 0) { \n            std::cout << \"eps=\" << sol.epsilon() << \", c=\" << sol.c() << std::endl;\n        }\n        \n        hc.solve(hom, sol);\n        std::cout <<\"i=\" << i << std::endl << \"errors=\" << hc.errors() << std::endl << \"gaps=\" << hc.gaps() << std::endl;\n        BOOST_TEST_INFO(\"i=\" << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps());\n        BOOST_TEST(hc.gaps().max() < .5L);\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi << \",normalRoot=\" << sol.root());\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n    SET_LOG_LEVEL(Error);\n}\n\nBOOST_AUTO_TEST_CASE(BethePolynomialHomotopy_L10M5)\n{\n    int L = 10;\n    int M = 5;\n    std::cout << \"Running integrated test for L=\" << L << \", M=\" << M << \" cases\" << std::endl;\n    elem_t totalPhase = Pi;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    BethePolynomialHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    hc.setMaxNumberOfNewtonRaphonEachStep(50);\n    \n    SET_LOG_LEVEL(Error);\n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n//        if (i == 15) continue;\n        LOG(\"processing root #\" << i << \":\\t\" << cache.getRoot(i), Warning);\n        std::string file = \"BS_L\" + ToString(L)+ \"M\" + ToString(M)+ \"r\" + ToString(i) + \".txt\";\n//        hc.setTraceFile(file);\n        Vector startRoot = cache.getRoot(i);\n        InvertableSolution sol(startRoot, L);\n        if (sol.indexOfSingularRoot1() >= 0) { \n            std::cout << \"eps=\" << sol.epsilon() << \", c=\" << sol.c() << std::endl;\n        }\n        \n        hc.solve(hom, sol);\n        std::cout <<\"i=\" << i << std::endl << \"errors=\" << hc.errors() << std::endl << \"gaps=\" << hc.gaps() << std::endl;\n        BOOST_TEST_INFO(\"i=\" << \", errors=\" << hc.errors() << \", gaps=\" << hc.gaps());\n        BOOST_TEST(hc.gaps().max() < .5L);\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi << \",normalRoot=\" << sol.root());\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n    SET_LOG_LEVEL(Error);\n}\n\n\nBOOST_AUTO_TEST_CASE(PoleFreeBetheHomotopy_L6M2)\n{\n    std::cout << \"Running integrated test for L=6, M=2 cases\" << std::endl;\n    int L = 6;\n    int M = 2;\n    elem_t totalPhase = Pi;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    PoleFreeBetheHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    \n    SET_LOG_LEVEL(Error);\n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n        LOG(\"processing root #\" << i << \":\\t\" << cache.getRoot(i), Warning);\n        Vector startRoot = cache.getRoot(i);\n        BetheSolution sol(startRoot, L, 0.0, totalPhase / hom.getSteps());\n        std::cout << \"eps=\" << sol.epsilon() << \", c=\" << sol.c() << std::endl;\n        hc.solve(hom, sol);\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi);\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n    SET_LOG_LEVEL(Error);\n}\n\nBOOST_AUTO_TEST_CASE(PoleFreeBetheHomotopy_L6M3)\n{\n    std::cout << \"Running integrated test for L=6, M=3 cases\" << std::endl;\n\n    int L = 6;\n    int M = 3;\n    elem_t totalPhase = Pi;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    PoleFreeBetheHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    SET_LOG_LEVEL(Error);\n    \n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n        Vector startRoot = cache.getRoot(i);\n        BetheSolution sol(startRoot, L, 0.0, totalPhase / hom.getSteps());\n        hc.solve(hom, sol);\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi);\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(PoleFreeBetheHomotopy_L7M2)\n{\n    std::cout << \"Running integrated test for L=7, M=2 cases\" << std::endl;\n    int L = 7;\n    int M = 2;\n    elem_t totalPhase = random(1.0, 2.0) * Pi;\n//    elem_t totalPhase = 1.27095 * Pi;\n//    elem_t totalPhase = 1.81386 * Pi;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    PoleFreeBetheHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    SET_LOG_LEVEL(Error);\n    \n    // i = 1: at two identical infinity roots\n    // i = 3 and 8: two conjugate finite roots.\n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n        Vector startRoot = cache.getRoot(i);\n        BetheSolution sol(startRoot, L, 0.0, totalPhase / hom.getSteps());\n        hc.solve(hom, sol);\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"totalPhass/Pi=\" << totalPhase/Pi << \", i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi);\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(PoleFreeBetheHomotopy_L7M3)\n{\n    std::cout << \"Running integrated test for L=7, M=3 cases\" << std::endl;\n    int L = 7;\n    int M = 3;\n    elem_t totalPhase = 1.3453 * Pi;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    PoleFreeBetheHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    SET_LOG_LEVEL(Error);\n    \n    // i = 1: at two identical infinity roots\n    // i = 3 and 8: two conjugate finite roots.\n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n        Vector startRoot = cache.getRoot(i);\n        BetheSolution sol(startRoot, L, 0.0, totalPhase / hom.getSteps());\n        hc.solve(hom, sol);\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi);\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(PoleFreeBetheHomotopy_L8M3)\n{\n    std::cout << \"Running integrated test for L=8, M=3 cases\" << std::endl;\n    int L = 8;\n    int M = 3;\n//    elem_t totalPhase = random(1.0, 2.0) * Pi;\n    elem_t totalPhase = 3.66417L;\n    elem_t expectedMomentumDiff = floatMod(2 * M * totalPhase, 2 * Pi);\n    PoleFreeBetheHomotopy hom(L, M, totalPhase);\n    BetheRootCache cache(L, M);\n    BetheHomotopyContinuation hc;\n    SET_LOG_LEVEL(Error);\n    \n    // i = 1: at two identical infinity roots\n    // i = 3 and 8: two conjugate finite roots.\n    for (int i = 0; i < cache.numberOfRoots(); i++) {\n//        std::string file = \"BS_L\" + ToString(L)+ \"M\" + ToString(M)+ \"r\" + ToString(i) + \".txt\";\n//        hc.setTraceFile(file);\n        std::cout << \"i=\" << i << std::endl;\n\n        Vector startRoot = cache.getRoot(i);\n        BetheSolution sol(startRoot, L, 0.0, totalPhase / hom.getSteps());\n        hc.solve(hom, sol);\n        elem_t m1 = momentum(startRoot);\n        elem_t m2 = momentum(sol.normalRoot());\n        BOOST_TEST_INFO(\"i=\" << i << \", m1/Pi=\" << m1/(elem_t)Pi << \", m2/Pi=\" << m2/(elem_t)Pi << \", expectedDiff/Pi=\" << expectedMomentumDiff/(elem_t)Pi);\n        BOOST_TEST(std::abs(floatMod(m2 - m1 - expectedMomentumDiff, 2.0 * Pi)) < 1e-4);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "eb63cdbcd004d55db5f52b0b92cf369621c5bc65", "size": 21716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/IntegratedTests.cpp", "max_stars_repo_name": "gaolichen/bethesolver", "max_stars_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_stars_repo_licenses": ["MIT"], "max_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/IntegratedTests.cpp", "max_issues_repo_name": "gaolichen/bethesolver", "max_issues_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_issues_repo_licenses": ["MIT"], "max_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/IntegratedTests.cpp", "max_forks_repo_name": "gaolichen/bethesolver", "max_forks_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_forks_repo_licenses": ["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.4427480916, "max_line_length": 195, "alphanum_fraction": 0.5735402468, "num_tokens": 6690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5457915115722151}}
{"text": "#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nnamespace enjambre {\n\nclass Individuo {\npublic:\n    Individuo(const vector<pair<double, double>>& limites);\n\n    vec getPosicion() const { return posicion; }\n    void setPosicion(const vec& value);\n\n    vec getVelocidad() const { return velocidad; }\n    void setVelocidad(const vec& value);\n\n    vec getMejorLocal() const { return mejorLocal; }\n    void setMejorLocal(const vec& value);\n\n    double aptitudMejorLocal;\n\n    Individuo& operator=(const Individuo& other);\n\nprivate:\n    const vector<pair<double, double>> m_limites;\n    vec posicion;\n    vec velocidad;\n    vec mejorLocal;\n};\n\nIndividuo::Individuo(const vector<pair<double, double>>& limites)\n    : aptitudMejorLocal{-numeric_limits<double>::max()}\n    , m_limites{limites}\n{\n    const unsigned int nVariables = m_limites.size();\n\n    posicion = randu(nVariables);\n\n    if (m_limites.size() != nVariables)\n        throw runtime_error(\"N\u00famero de l\u00edmites no concuerda con la cantidad de variables\");\n\n    for (unsigned int i = 0; i < posicion.n_elem; ++i) {\n        double rangoVariable = m_limites.at(i).second - m_limites.at(i).first;\n\n        posicion(i) = posicion(i) * rangoVariable + m_limites.at(i).first;\n    }\n\n    velocidad = zeros(nVariables);\n    mejorLocal = posicion;\n}\n\nvoid Individuo::setPosicion(const vec& value)\n{\n    if (value.n_elem != this->posicion.n_elem)\n        throw runtime_error(\"La dimensi\u00f3n del vector es incorrecta\");\n\n    for (unsigned int i = 0; i < m_limites.size(); ++i) {\n        if (value.at(i) > m_limites.at(i).second)\n            posicion.at(i) = m_limites.at(i).second; // Nos pasamos de largo por derecha\n        else if (value.at(i) < m_limites.at(i).first)\n            posicion.at(i) = m_limites.at(i).first; // Nos pasamos de largo por izquierda\n        else\n            posicion.at(i) = value.at(i); // No nos pasamos de largo\n    }\n}\n\nvoid Individuo::setVelocidad(const vec& value)\n{\n    if (value.n_elem != this->velocidad.n_elem)\n        throw runtime_error(\"La dimensi\u00f3n del vector es incorrecta\");\n\n    velocidad = value;\n}\n\nvoid Individuo::setMejorLocal(const vec& value)\n{\n    if (value.n_elem != this->posicion.n_elem)\n        throw runtime_error(\"La dimensi\u00f3n del vector es incorrecta\");\n\n    mejorLocal = value;\n}\n\nIndividuo& Individuo::operator=(const Individuo& other)\n{\n    if (other.m_limites != this->m_limites)\n        throw runtime_error(\"Los individuos tienen distintos limites en las variables\");\n\n    this->posicion = other.posicion;\n    this->velocidad = other.velocidad;\n    this->mejorLocal = other.mejorLocal;\n    this->aptitudMejorLocal = other.aptitudMejorLocal;\n\n    return *this;\n}\n\nclass Enjambre {\npublic:\n    Enjambre(function<double(Individuo)> fitness,\n             const vector<pair<double, double>>& limites,\n             const double c1,\n             const double c2,\n             unsigned int nIndividuos,\n             int umbral);\n\n    bool evaluarPoblacion();\n    void epoca();\n    const vector<Individuo>& individuos() const { return m_individuos; }\n    const Individuo& mejorGlobal() const { return m_mejorGlobal; }\n    double fitnessPromedio() const { return m_fitnessPromedio; }\n    bool termino() const { return m_termino; }\n\nprivate:\n    vector<Individuo> m_individuos;\n    Individuo m_mejorGlobal;\n    double m_mejorAptitud;\n    double m_fitnessPromedio;\n    function<double(Individuo)> m_fitness;\n    const double m_c1, m_c2;\n    int m_umbral;\n    int m_epocasSinMejora;\n    bool m_termino;\n};\n\nEnjambre::Enjambre(function<double(Individuo)> fitness,\n                   const vector<pair<double, double>>& limites,\n                   const double c1,\n                   const double c2,\n                   unsigned int nIndividuos,\n                   int umbral)\n    : m_mejorGlobal{limites}\n    , m_mejorAptitud{-numeric_limits<double>::max()}\n    , m_fitness{fitness}\n    , m_c1{c1}\n    , m_c2{c2}\n    , m_umbral{umbral}\n    , m_epocasSinMejora{0}\n    , m_termino{false}\n{\n    for (unsigned int i = 0; i < nIndividuos; ++i) {\n        m_individuos.push_back(Individuo{limites});\n\n        evaluarPoblacion();\n    }\n}\n\nbool Enjambre::evaluarPoblacion()\n{\n    bool mejoro = false;\n    double sumaFitness = 0;\n\n    for (Individuo& ind : m_individuos) {\n        double aptitud = m_fitness(ind);\n        sumaFitness += aptitud;\n\n        if (aptitud > ind.aptitudMejorLocal) {\n            ind.setMejorLocal(ind.getPosicion());\n            ind.aptitudMejorLocal = aptitud;\n\n            if (aptitud > m_mejorAptitud) {\n                m_mejorGlobal = ind;\n                m_mejorAptitud = aptitud;\n                mejoro = true;\n            }\n        }\n    }\n\n    m_fitnessPromedio = sumaFitness / m_individuos.size();\n\n    return mejoro;\n}\n\nvoid Enjambre::epoca()\n{\n    const int nVariables = m_individuos.front().getPosicion().n_elem;\n\n    for (Individuo& ind : m_individuos) {\n        // C\u00e1lculo de la nueva velocidad\n        // Componente cognitiva\n        const vec r1 = randu(nVariables);\n        const vec distanciaMejorLocal = ind.getMejorLocal() - ind.getPosicion();\n\n        const vec compCognitiva = m_c1 * r1 % distanciaMejorLocal;\n\n        // Componente social\n        const vec r2 = randu(nVariables);\n        const vec distanciaMejorGlobal = m_mejorGlobal.getPosicion() - ind.getPosicion();\n\n        const vec compSocial = m_c2 * r2 % distanciaMejorGlobal;\n\n        // Actualizaci\u00f3n\n        ind.setVelocidad(ind.getVelocidad() + compCognitiva + compSocial);\n        ind.setPosicion(ind.getPosicion() + ind.getVelocidad());\n    }\n\n    if (evaluarPoblacion())\n        m_epocasSinMejora = 0;\n    else {\n        if (m_epocasSinMejora == m_umbral)\n            m_termino = true;\n\n        ++m_epocasSinMejora;\n    }\n}\n} // namespace enjambre\n", "meta": {"hexsha": "34dacb3401113be1c2d36794c3603b80a5897cf2", "size": 5763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia4/enjambre.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": "guia4/enjambre.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": "guia4/enjambre.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": 27.9757281553, "max_line_length": 91, "alphanum_fraction": 0.6411591185, "num_tokens": 1585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5457915067559865}}
{"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// Algorithm inspired by Nick Vannieuwenhoven, written by Cornelius Steinhardt\n\n#  define MTL_VPT_LEVEL 5\n\n#include <iostream>\n#include <limits>\n\n#include <boost/timer.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n#include <boost/numeric/mtl/io/read_el_matrix.hpp>\n#include <boost/numeric/itl/pc/matrix_algorithms.hpp>\n#include <boost/numeric/itl/pc/imf_preconditioner.hpp>\n#include <boost/numeric/itl/pc/imf_algorithms.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n#ifdef MTL_HAS_VPT\n  #include <vt_user.h> \n#endif \n\ntemplate< class ElementStructure >\nvoid setup(ElementStructure& A, int lofi)\n{\n    typedef double value_type; \n      \n    int size( A.get_total_vars() );\n   \n    mtl::dense_vector<value_type>              x(size, 1), b(size), ident(size); \n     iota(ident);\n\n     std::cout<< \"read ok, start with precond\\n\";\n    boost::timer factorization;\n    itl::pc::imf_preconditioner<value_type> precond(A, lofi);\n    double ftime= factorization.elapsed();\n    std::cout<< \"imf ready\\n\";\n    \n//     for (int i= 0; i < size; i++)\n//       x[i]= std::numeric_limits<value_type>::quiet_NaN();\n\n    std::cout<< \"size(rhs2)=\" << num_rows(b) << \"\\n\";\n    mtl::compressed2D<double> B;\n    assemble_compressed(A, B, ident);\n    std::cout << \"NNZ == \" << B.nnz() << \"\\n\";\n    \n    b= B * x;\n\n#if 0\n\tmtl::io::tout << \"------------------------------- STATISTICS -------------------------------\" << std::endl;\n\tint rows = num_rows(*master_mat);\n\tint cols = num_cols(*master_mat);\n \tint nnz = (*master_mat).nnz();\n\tmtl::io::tout << \"Dimensions: \" << rows << \" x \" << cols << std::endl;\n\tmtl::io::tout << \"Non-zeros: \" << nnz << std::endl;\n\tmtl::io::tout << \"Sparsity (%): \" << ((double(nnz) / rows) / cols) << std::endl;\n\tmtl::io::tout << \"Avg nnz/row: \" << double(nnz) / rows << std::endl;\n\tmtl::io::tout << std::endl;\n\tmtl::io::tout << \"Elements: \" << es.get_total_elements() << std::endl;\n\tmtl::io::tout << \"Variables: \" << es.get_total_vars() << std::endl;\n\tmtl::io::tout << \"--------------------------------------------------------------------------\" << std::endl;\n// calculate eigenvalues\n\tmtl::dense2D<value_type> E(size,size),A(*master_mat);\n\tfor(int i=0; i<size;i++){\n\t  mtl::dense_vector<value_type> tmp(A[mtl::irange(0, mtl::imax)][i]);\n\t  E[mtl::irange(0, mtl::imax)][i] = precond.solve(tmp);\n\t}\n\tmtl::io::tout<< \"E=\\n\"<<E <<\"\\n\";\n#endif\n\n\tstd::cout<< \"start solver\\n\";\n    itl::cyclic_iteration<value_type>          iter(b, size, 1.e-8, 0.0, 5);\n    x= 0;\n    boost::timer solver;\n     bicgstab(B, x, b, precond, iter);\n     std::cout << \"Factorization took \" << ftime << \"s, solution took \" << solver.elapsed() << \"s\\n\";\n}\n\nint main(int, char** argv)\n{\n    mtl::vampir_trace<9999> tracer;\n    typedef double value_type;\n       \n    std::string program_dir= mtl::io::directory_name(argv[0]),\n  \t        matrix_file= mtl::io::join(program_dir, \"../../mtl/test/matrix_market/square3.mtx\");\n//  \t        matrix_file= mtl::io::join(program_dir, \"../../../../../data/sysMat_elem.mtx\");\n// \t\tmatrix_file= mtl::io::join(program_dir, \"../../mtl/test/matrix_market/obstacle_small.mtx\");\n// \t        matrix_file= mtl::io::join(program_dir, \"../../../../../data/matrix_market/obstacle_q1q1_e64/obstacle_q1q1_e64_r00800.mtx\");\n\n    mtl::mat::element_structure<value_type> A;\n    read_el_matrix(matrix_file, A);\n\t\n    setup(A, 5);\n    return 0;\n}\n", "meta": {"hexsha": "849dbdf3809e2f6fbca6fa560c73140bac48e402", "size": 3828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/imf_bicg_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/itl/test/imf_bicg_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/itl/test/imf_bicg_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": 36.1132075472, "max_line_length": 136, "alphanum_fraction": 0.6107628004, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.545787834970629}}
{"text": "/** \\file   cmr_t2_mapping.cpp\n    \\brief  Implement CMR T1 mapping for 2D acquisition\n    \\author Hui Xue\n*/\n\n#include \"cmr_t2_mapping.h\"\n#include \"log.h\"\n\n#include \"hoNDArray_reductions.h\"\n#include \"hoNDArray_elemwise.h\"\n#include \"hoNDArray_math.h\"\n#include \"hoNDArray_linalg.h\"\n\n#include \"simplexLagariaSolver.h\"\n#include \"twoParaExpDecayOperator.h\"\n#include \"curveFittingCostFunction.h\"\n\n#include <boost/math/special_functions/sign.hpp>\n\nnamespace Gadgetron { \n\ntemplate <typename T> \nCmrT2Mapping<T>::CmrT2Mapping() : BaseClass()\n{\n    max_iter_ = 150;\n    max_fun_eval_ = 1000;\n    thres_fun_ = 1e-4;\n\n    max_map_value_ = 2500;\n}\n\ntemplate <typename T> \nCmrT2Mapping<T>::~CmrT2Mapping()\n{\n}\n\ntemplate <typename T>\nvoid CmrT2Mapping<T>::get_initial_guess(const VectorType& ti, const VectorType& yi, VectorType& guess)\n{\n    if (guess.size() != this->get_num_of_paras())\n    {\n        guess.resize(this->get_num_of_paras(), 0);\n    }\n\n    // do a log linear fit\n    size_t numpts = yi.size();\n    GADGET_CHECK_THROW(numpts>0);\n\n    T default_A = *std::max_element(yi.begin(), yi.end());\n    T default_T2 = ti[ti.size() / 2];;\n\n    try\n    {\n        size_t i;\n        for (i = 0; i < numpts; i++)\n        {\n            if(yi[i]<=0)\n            {\n                guess[0] = default_A;\n                guess[1] = default_T2;\n                return;\n            }\n        }\n\n        hoNDArray<T> log_yi(numpts), bi_est(2);\n        hoNDArray<T> xi(numpts);\n        for (size_t i = 0; i < numpts; i++)\n        {\n            xi[i] = ti[i];\n            log_yi[i] = std::log(yi[i]);\n        }\n\n        T a, b;\n        Gadgetron::linFit(xi, log_yi, a, b);\n\n        guess[0] = std::exp(b);\n        guess[1] = -1.0 / a;\n    }\n    catch(...)\n    {\n        guess[0] = default_A;\n        guess[1] = default_T2;\n    }\n\n    if(guess[1]<0)\n    {\n        guess[0] = default_A;\n        guess[1] = default_T2;\n    }\n}\n\ntemplate <typename T>\nvoid CmrT2Mapping<T>::compute_map(const VectorType& ti, const VectorType& yi, const VectorType& guess, VectorType& bi, T& map_v)\n{\n    try\n    {\n        bi = guess;\n        map_v = 0;\n\n        typedef Gadgetron::twoParaExpDecayOperator< std::vector<T> > SignalType;\n        typedef Gadgetron::leastSquareErrorCostFunction< std::vector<T> > CostType;\n\n        // define solver\n        Gadgetron::simplexLagariaSolver< VectorType, SignalType, CostType > solver;\n\n        // define signal model\n        SignalType t2;\n\n        // define cost function\n        CostType lse;\n\n        solver.signal_model_ = &t2;\n        solver.cf_ = &lse;\n\n        solver.max_iter_ = max_iter_;\n        solver.max_fun_eval_ = max_fun_eval_;\n        solver.thres_fun_ = thres_fun_;\n\n        solver.x_ = ti;\n        solver.y_ = yi;\n\n        solver.solve(bi, guess);\n\n        if (bi[0] > 0 && bi[1] > 0)\n        {\n            map_v = bi[1];\n            if (map_v >= max_map_value_) map_v = hole_marking_value_;\n            if (map_v <= min_map_value_) map_v = hole_marking_value_;\n        }\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Exceptions happened in CmrT2Mapping<T>::compute_map(...) ... \");\n    }\n}\n\ntemplate <typename T>\nvoid CmrT2Mapping<T>::compute_sd(const VectorType& ti, const VectorType& yi, const VectorType& bi, VectorType& sd, T& map_sd)\n{\n    try\n    {\n        sd.clear();\n        sd.resize(bi.size(), 0);\n\n        map_sd = 0;\n\n        typedef Gadgetron::twoParaExpDecayOperator< std::vector<T> > SignalType;\n        SignalType t2;\n\n        // compute fitting values\n        VectorType y;\n        t2.magnitude(ti, bi, y);\n\n        // compute residual\n        VectorType res(y), abs_res(y);\n\n        size_t num = ti.size();\n        size_t N = this->get_num_of_paras();\n\n        size_t n;\n        for (n = 0; n < num; n++)\n        {\n            res[n] = y[n] - yi[n];\n            abs_res[n] = std::abs(res[n]);\n        }\n\n        hoNDArray<T> grad;\n        grad.create(N, num);\n        Gadgetron::clear(grad);\n\n        VectorType gradVec(N);\n        for (n = 0; n < num; n++)\n        {\n            t2.gradient(ti[n], bi, gradVec);\n            memcpy(grad.begin() + n*N, &gradVec[0], sizeof(T)*N);\n        }\n\n        GADGET_CATCH_THROW(this->compute_sd_impl(ti, yi, bi, abs_res, grad, sd));\n\n        map_sd = sd[1];\n        if (map_sd > max_map_value_) map_sd = this->hole_marking_value_;\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Exceptions happened in CmrT2Mapping<T>::compute_map(...) ... \");\n    }\n}\n\ntemplate <typename T>\nsize_t CmrT2Mapping<T>::get_num_of_paras() const\n{\n    return 2; // A and T2\n}\n\n// ------------------------------------------------------------\n// Instantiation\n// ------------------------------------------------------------\n\ntemplate class EXPORTCMR CmrT2Mapping< float >;\n\n}\n", "meta": {"hexsha": "dadf3582449201e9d2eb274255a1b462efbf09d4", "size": 4735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolboxes/cmr/cmr_t2_mapping.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "toolboxes/cmr/cmr_t2_mapping.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolboxes/cmr/cmr_t2_mapping.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["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.4405940594, "max_line_length": 128, "alphanum_fraction": 0.5472016895, "num_tokens": 1339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387956435734, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5457878210584404}}
{"text": "#include <scitbx/math/tetrahedron.h>\n\n#include <boost/python/class.hpp>\n#include <boost/python/copy_const_reference.hpp>\n#include <boost/python/return_value_policy.hpp>\n\nnamespace scitbx { namespace math {\n\nnamespace {\n\ntemplate<typename T>\nstruct tetrahedron_wrapper\n{\n  typedef tetrahedron<T> wt;\n\n  static void wrap() {\n    using namespace boost::python;\n    return_value_policy<copy_const_reference> ccr;\n    class_<wt>(\"tetrahedron\", no_init)\n      .def(init<typename wt::vertices_t const&>((arg(\"vertices\"))))\n      .add_property(\"vertices\", make_function(&wt::vertices, ccr))\n      .def(\"volume\", &wt::volume)\n      .def(\"gradients\", &wt::gradients)\n      ;\n  }\n};\n\n}\n\nnamespace boost_python {\n  void wrap_tetrahedron() {\n    tetrahedron_wrapper<double>::wrap();\n  }\n}\n\n}}\n", "meta": {"hexsha": "e5bc1d3a375ba4627176a29d13da59d457503a3d", "size": 780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/math/boost_python/tetrahedron.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/math/boost_python/tetrahedron.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/math/boost_python/tetrahedron.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 21.0810810811, "max_line_length": 67, "alphanum_fraction": 0.6948717949, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6584174871563662, "lm_q1q2_score": 0.5457878071813792}}
{"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_ORTH_INCLUDE\n#define MTL_ORTH_INCLUDE\n\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/matrix/parameter.hpp>\n#include <boost/numeric/mtl/operation/size.hpp>\n#include <boost/numeric/mtl/operation/size1D.hpp>\n#include <boost/numeric/mtl/operation/entry1D.hpp>\n#include <boost/numeric/mtl/operation/dot.hpp>\n#include <boost/numeric/mtl/operation/two_norm.hpp>\n#include <boost/numeric/mtl/operation/is_negative.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace mtl { namespace vec {\n\n    namespace impl {\n\n\ttemplate <typename VVector>\n\tinline void orth(VVector& v, typename mtl::Collection<VVector>::size_type j, tag::vector)\n\t{\n\t\tvampir_trace<2018> tracer;\n\t    using mtl::two_norm; using mtl::size1D;\n\t    MTL_DEBUG_THROW_IF(is_negative(j) || j >= size1D(v), index_out_of_range());\n\n\t    typedef typename mtl::Collection<VVector>::size_type  Size;\n\t    for (Size i= 0; i < j; ++i)\n\t\tentry1D(v, j)-= dot(entry1D(v, i), entry1D(v, j)) * entry1D(v, i);\n\t    entry1D(v, j)/= two_norm(entry1D(v, j));\n\t}\n\n\ttemplate <typename VVector>\n\tinline void orth(VVector& v, tag::vector)\n\t{\n\t    typedef typename mtl::Collection<VVector>::size_type  Size;\n\t    using mtl::size1D;\n\t    for (Size j= 0; j < size1D(v); ++j)\n\t\torth(v, j, tag::vector());\n\t}\n\n\n\ttemplate <typename VVector>\n\tmtl::mat::dense2D<typename mtl::Collection\n\t\t   <typename mtl::Collection<VVector>::value_type\n\t\t    >::value_type, mat::parameters<> >\n\tinline orthogonalize_factors(VVector& v, tag::vector)\n\t{\t\n\t    vampir_trace<2019> tracer;\n\t    using ::mtl::two_norm; using math::zero; using mtl::size1D;\n\t    typedef typename mtl::Collection<VVector>::size_type  Size;\n\t    typedef typename mtl::Collection<VVector>::value_type Vector;\n\t    typedef typename mtl::Collection<Vector>::value_type  Scalar;\n\n\t    mtl::mat::dense2D<Scalar, mat::parameters<> > tau(size1D(v), size1D(v));\n\t    tau= zero(Scalar());\n\n\t    if (size1D(v) == 0)\n\t\treturn tau;\n\n\t    tau[0][0]= dot(entry1D(v, 0), entry1D(v, 0));\n\n\t    for (Size j= 1; j < size1D(v); ++j) {\n#ifdef MTL_WITH_FUSED_ORTHOGONALIZATION\n\t\tScalar t= dot(entry1D(v, 0), entry1D(v, j)) / tau[0][0], t2;\n\t\ttau[0][j]= t;\n\t\tfor (Size i= 1; i < j; ++i) {\n\t\t    (lazy(entry1D(v, j))-= t * entry1D(v, i-1)) || (lazy(t2)= lazy_dot(entry1D(v, i), entry1D(v, j)));\n\t\t    t= tau[i][j]= t2 / tau[i][i];\n\t\t}\n\t\tentry1D(v, j)-= t * entry1D(v, j-1);\n#else\n\t\tfor (Size i= 0; i < j; ++i) {\n\t\t    Scalar t= dot(entry1D(v, i), entry1D(v, j)) / tau[i][i];\n\t\t    tau[i][j]= t;\n\t\t    entry1D(v, j)-= t * entry1D(v, i);\n\t\t}\n#endif\n\t\ttau[j][j]= dot(entry1D(v, j), entry1D(v, j));\n\t    }\n\t    return tau;\n\t}\n\n    } // impl\n\n\n\n/*! Orthonormalize a vector of vectors.\n\n    The outer type must be a random access collection and\n    the vector type must provide a dot function. \n    For instance dense_vector<dense_vector<double> > or\n    std::vector<dense_vector<std::complex<double> > > are eligible.\n    It is planned to implement the function for matrices as well\n    where the columns will be ortho-normalized.\n**/\ntemplate <typename Value>\ninline void orth(Value& value)\n{\n    impl::orth(value, typename traits::category<Value>::type());\n}\n\n/*! Orthonormalize the i-th entry of a vector of vectors.\n\n    The i-th vector is orthogonalized w.r.t. to the preceeding ones and\n    consecutively normalized.\n    The outer type must be a random access collection and\n    the vector type must provide a dot function. \n    For instance dense_vector<dense_vector<double> > or\n    std::vector<dense_vector<std::complex<double> > > are eligible.\n    It is planned to implement the function for matrices as well\n    where the columns will be ortho-normalized.\n**/\ntemplate <typename Value>\ninline void orth(Value& value, typename mtl::Collection<Value>::size_type i)\n{\n    impl::orth(value, i, typename traits::category<Value>::type());\n}\n\n\n/*! Orthogonalize a vector of vectors.\n\n    Opposed to orth the vectors are not normalized. \n    An upper matrix with the factors used in the orthogonalization is returned.\n    The diagonal contains dot(v[i], v[i]).\n    The returned factors are for instance used in bicgstab_ell.\n    The outer type must be a random access collection and\n    the vector type must provide a dot function. \n    For instance dense_vector<dense_vector<double> > or\n    std::vector<dense_vector<std::complex<double> > > are eligible.\n**/\ntemplate <typename Value>\nmtl::mat::dense2D<typename mtl::Collection\n\t<typename mtl::Collection<Value>::value_type\n\t >::value_type, mat::parameters<>  >\ninline orthogonalize_factors(Value& v)\n{\n    return impl::orthogonalize_factors(v, typename traits::category<Value>::type());\n}\n\n} // namespace vector\n\nnamespace mat {\n\n    // If other matrix types will be supported within a template function, it needs reimplementation!!!\n    template <typename Vector>\n    inline void orth(multi_vector<Vector>& A)\n    {\n\tmtl::vec::impl::orth(A, mtl::tag::vector());\n    }\n}\n\nusing vec::orth;\nusing vec::orthogonalize_factors;\n\n} // namespace mtl\n\n#endif // MTL_ORTH_INCLUDE\n", "meta": {"hexsha": "48a83e58da58d49fe2928ea418487ae0aa001bc6", "size": 5673, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/orth.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": "boost/numeric/mtl/operation/orth.hpp", "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": "boost/numeric/mtl/operation/orth.hpp", "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": 32.7919075145, "max_line_length": 104, "alphanum_fraction": 0.6885245902, "num_tokens": 1601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6584174871563662, "lm_q1q2_score": 0.5457878071813791}}
{"text": "#define DEBUG 1\n/**\n * File    : E.cpp\n * Author  : Kazune Takahashi\n * Created : 4/23/2020, 7:08:47 PM\n * Powered by Visual Studio Code\n */\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n// ----- boost -----\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n// ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n// ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n// constexpr ll MOD{998244353LL}; // be careful\nconstexpr ll MAX_SIZE{3000010LL};\n// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n  }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n  }\n}\n// ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(const Mint &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(const Mint &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint &operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint &operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(const Mint &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator/=(const Mint &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }\n  bool operator<(const Mint &a) const { return x < a.x; }\n  bool operator<=(const Mint &a) const { return x <= a.x; }\n  bool operator>(const Mint &a) const { return x > a.x; }\n  bool operator>=(const Mint &a) const { return x >= a.x; }\n  bool operator==(const Mint &a) const { return x == a.x; }\n  bool operator!=(const Mint &a) const { return !(*this == a); }\n  const Mint power(ll N)\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N / 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n  return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)\n{\n  return Mint<MOD>{lhs} / rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n  return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n  return stream << a.x;\n}\n// ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i = 2LL; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i = 1LL; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x / gcd(x, y) * y; }\n// ----- for C++17 -----\ntemplate <typename T>\nint popcount(T x) // C++20\n{\n  int ans{0};\n  while (x != 0)\n  {\n    ans += x & 1;\n    x >>= 1;\n  }\n  return ans;\n}\n// ----- frequently used constexpr -----\n// constexpr double epsilon{1e-10};\n// constexpr ll infty{1000000000000000LL}; // or\n// constexpr int infty{1'000'000'010};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\n// ----- Point -----\n\nusing Point = tuple<int, int>;\n\nostream &operator<<(ostream &os, Point const &pt)\n{\n  return os << get<0>(pt) << \" \" << get<1>(pt);\n}\n\n// ----- Cycle -----\n\nclass Cycle\n{\n  int num;\n  bool pos;\n\npublic:\n  Cycle(int num, bool pos) : num{num}, pos{pos} {}\n\n  vector<Point> path() const\n  {\n    vector<Point> ans;\n    for (auto i = 0; i <= num; ++i)\n    {\n      ans.push_back(Point(i, 0));\n    }\n    if (pos)\n    {\n      ans.push_back(Point(num + 1, 0));\n      ans.push_back(Point(num + 1, 1));\n      ans.push_back(Point(num, 1));\n    }\n    else\n    {\n      ans.push_back(Point(num, 1));\n      ans.push_back(Point(num + 1, 1));\n      ans.push_back(Point(num + 1, 0));\n    }\n    for (auto i = num; i >= 1; --i)\n    {\n      ans.push_back(Point(i, 0));\n    }\n    return ans;\n  }\n\n  Cycle inv() const\n  {\n    return Cycle(num, !pos);\n  }\n};\n\nclass Chain\n{\n  vector<Cycle> V;\n\npublic:\n  Chain() {}\n  Chain(Cycle c) : V{c} {}\n  Chain(vector<Cycle> V) : V(V) {}\n\n  Chain(int mask)\n  {\n    int cnt{0};\n    while ((mask >> cnt) != 0)\n    {\n      if ((mask >> cnt) & 1)\n      {\n        merge(cnt);\n      }\n      ++cnt;\n    }\n  }\n\n  vector<Point> path() const\n  {\n    vector<Point> ans;\n    for (auto const &e : V)\n    {\n      auto tmp{e.path()};\n      copy(tmp.begin(), tmp.end(), back_inserter(ans));\n    }\n    return ans;\n  }\n\n  vector<Cycle> const &seq() const\n  {\n    return V;\n  }\n\n  void operator+=(Chain const &other)\n  {\n    copy(other.seq().begin(), other.seq().end(), back_inserter(V));\n  }\n\nprivate:\n  void merge(int n)\n  {\n    if (V.empty())\n    {\n      V.push_back(Cycle{n, true});\n    }\n    else\n    {\n      auto inverse{inv()};\n      *this += Chain{Cycle{n, true}};\n      *this += inverse;\n      *this += Chain{Cycle{n, false}};\n    }\n  }\n\n  Chain inv() const\n  {\n    vector<Cycle> W;\n    for (auto it = V.rbegin(); it != V.rend(); ++it)\n    {\n      W.push_back(it->inv());\n    }\n    return Chain(W);\n  }\n};\n\n// ----- Solve -----\n\nclass Solve\n{\n  int N;\n  vector<bool> V;\n  Chain C;\n  bool possible;\n\npublic:\n  Solve(int N, string A) : N{N}, V(1 << N), possible{true}\n  {\n    for (auto i = 0; i < 1 << N; ++i)\n    {\n      V[i] = (A[i] == '1');\n    }\n  }\n\n  void answer()\n  {\n    if (check())\n    {\n      construct();\n    }\n    else\n    {\n      possible = false;\n    }\n    flush();\n  }\n\nprivate:\n  bool check() const\n  {\n    if (!V[0])\n    {\n      return false;\n    }\n    for (auto i = 0; i < 1 << N; ++i)\n    {\n      for (auto j = 0; j < 1 << N; ++j)\n      {\n        if (i != j && (i & j) == j)\n        {\n          if (!V[j] && V[i])\n          {\n            return false;\n          }\n        }\n      }\n    }\n    return true;\n  }\n\n  void construct()\n  {\n    for (auto i = 0; i < 1 << N; ++i)\n    {\n      if (V[i])\n      {\n        continue;\n      }\n      bool create{true};\n      for (auto j = 0; j < 1 << N; ++j)\n      {\n        if (i != j && (i & j) == j && !V[j])\n        {\n          create = false;\n          break;\n        }\n      }\n      if (create)\n      {\n        C += Chain{i};\n      }\n    }\n  }\n\n  void flush() const\n  {\n    if (possible)\n    {\n      cout << \"Possible\" << endl;\n    }\n    else\n    {\n      cout << \"Impossible\" << endl;\n      return;\n    }\n    auto tmp{C.path()};\n    cout << tmp.size() << endl;\n    tmp.push_back(Point(0, 0));\n    for (auto const &e : tmp)\n    {\n      cout << e << endl;\n    }\n  }\n};\n\n// ----- main() -----\n\nint main()\n{\n  int N;\n  cin >> N;\n  string A;\n  cin >> A;\n  Solve solve(N, A);\n  solve.answer();\n}\n", "meta": {"hexsha": "0e8bdd83b60cc69bd4141b0561f943a25dd1a70d", "size": 8668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/0321_AGC043/E.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2020/0321_AGC043/E.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/0321_AGC043/E.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 18.6408602151, "max_line_length": 67, "alphanum_fraction": 0.5154591601, "num_tokens": 2751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5457878016077219}}
{"text": "\n// inverting A\n// using getrf() & getri() \n\n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/blas/level3.hpp>\n#include <boost/numeric/bindings/lapack/computational/getri.hpp>\n#include <boost/numeric/bindings/lapack/computational/getrf.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace blas = boost::numeric::bindings::blas;\nnamespace lapack = boost::numeric::bindings::lapack;\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  lapack::getrf (a, ipiv);  // no lu_factor() alias for getrf() available\n  lapack::getri (a, ipiv);  // no lu_invert() alias for getrf() available\n\n  m_t i1 (n, n), i2 (n, n);  \n  blas::gemm (1.0, a, aa, 0.0, i1);   // i1 should be (almost) identity matrix\n  blas::gemm (1.0, aa, a, 0.0, 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 = lapack::getrf (ca, ipiv2);\n  if (ierr == 0) {\n    lapack::getri (ca, ipiv2); \n    cm_t ii (3, 3); \n    blas::gemm (1.0, ca, caa, 0.0, ii);\n    print_m (ii, \"I = CA^(-1) * CA\"); \n    cout << endl; \n    blas::gemm (1.0, caa, ca, 0.0, 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": "dfb781348b293366d088695e9b5b4698376af147", "size": 2663, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_getri.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/atlas/ublas_getri.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/atlas/ublas_getri.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.8878504673, "max_line_length": 78, "alphanum_fraction": 0.5527600451, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.54578123500297}}
{"text": "// Filename: ranged_for_iteration.cpp (part of MTL4)\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace mtl;\n    \ntemplate <typename Matrix>\nvoid f(Matrix& A)\n{\n    A= 7.0;  // Set values in diagonal\n    \n#if defined(MTL_WITH_AUTO) && defined(MTL_WITH_RANGEDFOR)\n    // Define the property maps\n    auto row=   row_map(A); \n    auto col=   col_map(A);\n    auto value= const_value_map(A); \n\n    // Now iterate over the matrix    \n    for (auto c : major_of(A))      // rows or columns\n\tfor (auto i : nz_of(c))     // non-zeros within\n\t    std::cout << \"A[\" << row(i) << \", \" << col(i) << \"] = \" << value(i) << '\\n';    \n#endif\n}\n\n\nint main(int, char**)\n{\n    // Define a row-major sparse and a column-major dense matrix\n    compressed2D<double>                             A(3, 3); \n    dense2D<double, mat::parameters<col_major> >  B(3, 3); \n\n    f(A);\n    f(B);\n    \n    return 0;\n}\n", "meta": {"hexsha": "636b01d86cbe21b58997d5634159bdf1a74c57ab", "size": 908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/ranged_for_iteration.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/ranged_for_iteration.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/ranged_for_iteration.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.8947368421, "max_line_length": 85, "alphanum_fraction": 0.5726872247, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5457789858221688}}
{"text": "\n// BLAS level 3\n\n//#define F_USE_STD_VECTOR\n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <iostream>\n#include <boost/numeric/bindings/atlas/cblas3.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#ifdef F_USE_STD_VECTOR\n#include <vector>\n#include <boost/numeric/bindings/traits/std_vector.hpp> \n#endif \n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::cout;\nusing std::endl; \n\n#ifndef F_USE_STD_VECTOR\ntypedef ublas::matrix<double, ublas::row_major> m_t;\n#else\ntypedef ublas::matrix<double, ublas::column_major, std::vector<double> > m_t;\n#endif \n\nint main() {\n\n  cout << endl; \n\n  m_t a (4, 4);\n  init_m (a, kpp (1)); \n  print_m (a, \"a\"); \n  cout << endl; \n\n  m_t b (4, 6);\n  init_m (b, cls1()); \n  print_m (b, \"b\"); \n  cout << endl; \n  \n  m_t c (4, 6);\n\n  // c = a b\n  atlas::gemm (a, b, c); \n  print_m (c, \"c = a b\"); \n  cout << endl; \n  atlas::gemm (CblasNoTrans, CblasNoTrans, 1.0, a, b, 0.0, c); \n  print_m (c, \"c = a b\"); \n  cout << endl; \n\n  init_m (c, const_val<double> (1)); \n  print_m (c, \"c\"); \n  cout << endl; \n  // c = 2 a b + 0.5 c\n  atlas::gemm (2.0, a, b, 0.05, c);\n  print_m (c, \"c = 2 a b + 0.05 c\"); \n  cout << endl; \n\n  m_t d (6, 4);\n\n  // d = b^T a^T\n  atlas::gemm (CblasTrans, CblasTrans, 1.0, b, a, 0.0, d);\n  print_m (d, \"d = b^T a^T\"); \n  cout << endl; \n\n  // c = a^T b \n  atlas::gemm (CblasTrans, CblasNoTrans, 1.0, a, b, 0.0, c); \n  print_m (c, \"c = a^T b\"); \n  cout << endl; \n\n  // d = b^T a\n  atlas::gemm (CblasTrans, CblasNoTrans, 1.0, b, a, 0.0, d);\n  print_m (d, \"d = b^T a\"); \n  cout << endl; \n\n  init_m (d, const_val<double> (0)); \n  ublas::matrix_range<m_t> br (b, ublas::range (0, 4), ublas::range (0, 4)); \n  ublas::matrix_range<m_t> dr (d, ublas::range (1, 5), ublas::range (0, 4)); \n\n  // d[1..5][0..4] = a b[0..4][0..4]  \n  atlas::gemm (a, br, dr); \n  print_m (d, \"d[1..5][0..4] = a b[0..4][0..4]\"); \n  cout << endl; \n  \n  // d[1..5][0..4] = b[0..4][0..4] a\n  atlas::gemm (br, a, dr); \n  print_m (d, \"d[1..5][0..4] = b[0..4][0..4] a\"); \n  cout << endl; \n  \n  // d[1..5][0..4] = b[0..4][0..4] a^T\n  atlas::gemm (CblasNoTrans, CblasTrans, 1.0, br, a, 0.0, dr);\n  print_m (d, \"d[1..5][0..4] = b[0..4][0..4] a^T\"); \n  cout << endl; \n\n  // d[1..5][0..4] = a b[0..4][0..4]^T\n  atlas::gemm (CblasNoTrans, CblasTrans, 1.0, a, br, 0.0, dr);\n  print_m (d, \"d[1..5][0..4] = a b[0..4][0..4]^T\"); \n  cout << endl; \n\n}\n", "meta": {"hexsha": "b552b4d4023c3ceaa54b706e50c37df4f988b14c", "size": 2546, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_matr3.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_matr3.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_matr3.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": 24.2476190476, "max_line_length": 77, "alphanum_fraction": 0.5604870385, "num_tokens": 1096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5457542359220168}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <ctime>\n#include <cassert>\n#include \"chrono.h\"\n\ndouble dot1(const Eigen::VectorXd &vec1, const Eigen::VectorXd &vec2) {\n    assert(vec1.size() == vec2.size() && \"Vectors must have the same size\");\n    double result = 0.0f;\n    for (size_t i = 0; i < vec1.size(); ++i) {\n        result += vec1[i] * vec2[i];\n    }\n    return result;\n}\n\nEigen::MatrixXd matProduct(const Eigen::MatrixXd& mat1, const Eigen::MatrixXd& mat2) {\n    assert(mat1.size() == mat2.size() && \"Matrices must have the same size\");\n    Eigen::MatrixXd result = Eigen::MatrixXd::Zero(mat1.rows(), mat1.cols());\n    \n    for (size_t i = 0; i < result.rows(); i++) {\n        for (size_t j = 0; j < result.cols(); j++) {\n            for (size_t k = 0; k < mat1.cols(); k++) {\n                result(i, j) += mat1(i, k) * mat2(k, j);\n            }\n        }\n    }\n    \n    return result;\n}\n\nint main() {\n    const size_t dimension = 500;\n    TP_CPP_IMAC2::Chrono chrono;\n\n    Eigen::MatrixXd A = Eigen::MatrixXd::Random(dimension, dimension);\n    Eigen::MatrixXd B = Eigen::MatrixXd::Random(dimension, dimension);\n\n    chrono.start();\n    Eigen::MatrixXd eingenResult = A * B;\n    std::cout << \"Eignen mean : \" << chrono.timeSpan() << std::endl;\n    chrono.stop();\n\n    chrono.start();\n    Eigen::MatrixXd myResult = matProduct(A, B);\n    std::cout << \"My mean : \" << chrono.timeSpan() << std::endl;\n    chrono.stop();\n\n    std::cout << (eingenResult - myResult).norm() << std::endl;\n\n    /*\n\n    chrono.start();\n    std::cout << \"mean : \" << chrono.timeSpan() << std::endl;\n    chrono.stop();\n    \n    Eigen::VectorXd vec1 = Eigen::VectorXd::Random(dimension);\n    Eigen::VectorXd vec2 = Eigen::VectorXd::Random(dimension);\n\n    std::cout << \"My dot1 : \" << dot1(vec1, vec2) << std::endl;\n    std::cout << \"My dot2 : \" << dot2(vec1, vec2) << std::endl;\n    std::cout << \"Eignen dot : \" << vec1.dot(vec2) << std::endl;\n    */\n\n    /*\n    Eigen::VectorXd v1(5);\n    v1 << 1, 2, 3, 4, 5;\n    std::cout << \"v1 : \" << v1.transpose() << std::endl\n              << std::endl;\n\n    Eigen::Vector4f v2 = Eigen::Vector4f::Zero();\n    std::cout << \"v2 : \" << v2.transpose() << std::endl\n              << std::endl;\n\n    v2 = Eigen::Vector4f::Ones();\n    std::cout << \"v2 : \" << v2.transpose() << std::endl\n              << std::endl;\n\n    Eigen::Vector4f v3 = Eigen::Vector4f::Random();\n    std::cout << \"v3 : \" << v3.transpose() << std::endl\n              << std::endl;\n    v3 = v3 + v2;\n    std::cout << \"v3 : \" << v3.transpose() << std::endl\n              << std::endl;\n\n    Eigen::MatrixXd A = Eigen::MatrixXd::Random(3, 4);\n    std::cout << \"A :\\n\"\n              << A << std::endl\n              << std::endl;\n\n    Eigen::Matrix4d B = Eigen::Matrix4d::Random(4, 4);\n    std::cout << \"B :\\n\"\n              << B << std::endl\n              << std::endl;\n\n    Eigen::MatrixXd C(3, 4);\n\n    clock_t begin = clock();\n    C = A * B;\n    clock_t end = clock();\n    double tempsCalc = double(end - begin) / CLOCKS_PER_SEC;\n\n    std::cout << \"temps calcul du produit matriciel: \" << tempsCalc << \"s \" << std::endl;\n    std::cout << \"A + 2*A :\\n\"\n              << A + 2 * A << std::endl\n              << std::endl;\n    std::cout << \"A * B :\\n\"\n              << A * B << std::endl\n              << std::endl;\n\n              */\n\n    return 0;\n}\n", "meta": {"hexsha": "34aed21e12c49421c92cf098da262c9ebe4162ee", "size": 3341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/semestre-3/maths-2/ex1/eigensample.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-2/ex1/eigensample.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-2/ex1/eigensample.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": 29.3070175439, "max_line_length": 89, "alphanum_fraction": 0.5160131697, "num_tokens": 1005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5457542359220168}}
{"text": "#if HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include \"HigherStat.h\"\n#include \"PowerSpectrum.h\"\n#include \"LinearPS.h\"\n#include \"Quadrature.h\"\n#include \"SpecialFunctions.h\"\n#include \"array.h\"\n#include \"Spline.h\"\n#include <gsl/gsl_sf_bessel.h>\n#include <gsl/gsl_deriv.h>\n\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cerrno>\n#include <cstdlib>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <math.h>\n#include <vector>\n#include <boost/bind.hpp>\nusing boost::cref;\n\nconst real KMIN_e = 0.0001;\nconst real KMAX_e = 30.;\n\n// Load Linear PS\nHigherStat::HigherStat(const Cosmology& C, const PowerSpectrum& P_l, real epsrel_)\n: C(C), P_l(P_l),kintegral(*this)\n{\nMonteCarloIntegral::Range domain[5] = {\n    { KMIN_e, KMAX_e },\n    { KMIN_e, KMAX_e },\n    { KMIN_e, KMAX_e },\n    { -0.999999, 0.999999 },\n    { -0.999999, 0.999999 },\n};\nkintegral.SetDomain(domain);\nepsrel = epsrel_;\n}\nHigherStat::~HigherStat() {\n}\n\n\n//Filters\ninline double w_filter(double k, int a){\n  switch (a) {\n  case 1:\n    return 3./k*SphericalBesselJ1(k); //TOPHAT\n    break;\n  case 2:\n\t  return exp(-pow2(k)/2.); //GAUSSIAN\n    break;\n  case 3:\n\t  return 1.; // NO FILTER\n    break;\n    default:\n     warning(\"Filter: invalid indices\");\n     return 0;\n    }\n}\n\n\n/*Gamma 1 and Gamma 2 (logarithmic derivatives of variance) */\n\n// Create splines functions of sigma^2\nSpline sig2_spline;\nvoid HigherStat::sigsqr_init(int a) const{\n  int loop_N = 1000;\n  double RMAX =250;\n  double RMIN = 1.;\n  double Rval, sigval, vars[4];\n  vector<double> Rval_tab, sigval_tab;\nfor(int i = 0; i< loop_N; i++){\n    Rval = RMIN + i*(RMAX-RMIN)/(loop_N-1);//RMIN * exp(i*log(RMAX/RMIN)/(loop_N-1));\n    sigval = sig_sqr(Rval,a,1,vars);\n    Rval_tab.push_back(Rval);\n    sigval_tab.push_back(sigval);\n      }\n  sig2_spline = LinearSpline(Rval_tab,sigval_tab);\n}\n\n//function for derivative\n\nstatic double mysigsqr(double R,void * params){\n  (void)(params);\n  return sig2_spline(R);\n}\n\nstatic double gam1(double R, void * params1){\n  (void)(params1);\ngsl_function F;\ndouble result, abserr;\n  F.params = 0;\n  F.function = &mysigsqr;\n  gsl_deriv_central(&F, R, 1e-3, &result, &abserr);\nreturn R*result/sig2_spline(R);\n}\n\nstatic double gam2(double R){\ngsl_function F;\ndouble result, abserr;\n  F.params = 0;\n  F.function = &gam1;\n  gsl_deriv_central(&F, R, 1e-4, &result, &abserr);\nreturn R*result;\n}\n\n\n\n// b selects analytic (1) or numerical (2)\n// a selects window function form\n\n/* Variance */\nstatic double var_integranda(const PowerSpectrum& P_l, double R, int a,double k){\n\treturn pow2(k*w_filter(k*R,a)*D_spt/dnorm_spt)*P_l(k);\n}\n\nstatic double gam1_test(double R, const PowerSpectrum& P_l){\ndouble step = 0.00001;\ndouble top = Integrate(bind(var_integranda, cref(P_l), R + step, 1, _1), KMIN_e , KMAX_e, 1e-4)/(2.*pow2(M_PI));\ndouble bot = Integrate(bind(var_integranda, cref(P_l), R - step, 1, _1), KMIN_e , KMAX_e, 1e-4)/(2.*pow2(M_PI));\ndouble mid = Integrate(bind(var_integranda, cref(P_l), R, 1, _1), KMIN_e , KMAX_e, 1e-4)/(2.*pow2(M_PI));\nreturn R*(top-bot)/(2.*step)/mid;\n}\n\nstatic double gam2_test(double R, double step, const PowerSpectrum& P_l){\ndouble top = gam1_test(R+step, cref(P_l));\ndouble bot = gam1_test(R-step, cref(P_l));\ndouble mid = gam1_test(R, cref(P_l));\nreturn R*(top-bot)/(2.*step)/mid;\n}\n\n\n\n\nstatic double var_integrandn(const PowerSpectrum& P_l, double R, int a, double vars[], double k){\n  IOW iow;\n  iow.initn_lin(0, vars[4], k, vars[0], vars[1], vars[2], vars[3]);\n\treturn pow2(k*w_filter(k*R,a)*F1_nk/dnorm_spt)*P_l(k);\n}\n\n// vars is for numerical skewness only : vars[0]=omega0, vars[1-3] = MG params and vars[4]=scale factor\n// a chooses filter, b chooses analytic or numerical (1 or 2 resp)\ndouble HigherStat::sig_sqr(double R, int a, int b, double vars[]) const{\n  switch (b) {\n    case 1:\n        return  Integrate(bind(var_integranda, cref(P_l), R, a, _1), KMIN_e , KMAX_e, epsrel)/(2.*pow2(M_PI));\n    break;\n    case 2:\n         return  Integrate(bind(var_integrandn, cref(P_l), R, a, vars, _1), KMIN_e , KMAX_e, epsrel)/(2.*pow2(M_PI));\n    break;\n  }\n\n}\n\n/* Skewness */\n// analytic (GR AND nDGP)\nstatic double s3_num_integranda(const PowerSpectrum& P_l, double R, int a, double k1, double k2, double x){\n   double k1s = pow2(k1);\n   double k2s = pow2(k2);\n\treturn k1s*k2s*w_filter(k1*R,a)*w_filter(k2*R,a)*w_filter(sqrt(k1s+k2s+2.*k1*k2*x)*R,a)*(pow2(D_spt)*F2eds(k1,k2,x) + F_spt*(1.-x*x))*pow2(D_spt)/pow4(dnorm_spt)*P_l(k1)*P_l(k2);\n}\n// numerical\nstatic double s3_num_integrandn(const PowerSpectrum& P_l, double R, int a, double vars[], double k1, double k2, double x){\n  double kargs[4],kv[3],xv[3], p22,p13,d;\n  double k1s = pow2(k1);\n  double k2s = pow2(k2);\n  IOW iow;\n        kv[0] = k1;\n        kv[1] = k2;\n        kv[2] = kv[1];\n        xv[0] = -0.99999999;\n        xv[1] = x;\n        xv[2] = -x;\n        kargs[0] = sqrt(kv[1]*kv[1]+kv[0]*kv[0]-2.*kv[1]*kv[0]*xv[1]);\n        kargs[2] = sqrt(kv[1]*kv[1]+2.*kv[1]*kv[2]*xv[0]+kv[2]*kv[2]);\n        kargs[1] = sqrt(kv[2]*kv[2]+2.*kv[2]*kv[0]*xv[2]+kv[0]*kv[0]);\n        kargs[3] = sqrt(kv[0]*kv[0]+2.*kv[0]*kv[1]*xv[1]+kv[1]*kv[1]);\n        iow.initn2(vars[4],kv,xv,kargs,vars[0],vars[1],vars[2],vars[3]);\n\treturn k1s*k2s*w_filter(k1*R,a)*w_filter(k2*R,a)*w_filter(sqrt(k1s+k2s+2.*k1*k2*x)*R,a)*F2A_nk[0]*F1p_nk[0]*F1_nk/pow4(dnorm_spt)*P_l(k1)*P_l(k2);\n}\n\n// vars is for numerical skewness only : vars[0]=omega0, vars[1-3] = MG params and vars[4]=scale factor\n// a chooses window functions (see w_filter)\n// b chooses (1) analytic (2) numerical (3) gamma1 approx for top-hat filter\ndouble HigherStat::skewness(double R, int a, int b, double vars[]) const{\n  double c[3] = {KMIN_e,KMIN_e,-0.99999999};\n  double d[3] = {KMAX_e,KMAX_e,0.99999999};\n  void * params;\n\n  switch (b) {\n    case 1:\n\t     return  3./4./pow4(M_PI) * Integrate<3>(bind(s3_num_integranda, cref(P_l), R, a, _1, _2, _3), c,d, epsrel);\n    break;\n    case 2:\n      return  3./4./pow4(M_PI) * Integrate<3>(bind(s3_num_integrandn, cref(P_l), R, a, vars, _1, _2, _3), c,d, epsrel);\n    break;\n    case 3:\n      return (34./7. + gam1(R,params)) * pow2(sig2_spline(R));\n    break;\n  }\n}\n\n/* Analytic Kurtosis */\n\nstatic double s4_num_integranda1(const PowerSpectrum& P_l, double R, int a, double args[], double k[], double x12, double x23, double x13){\n   double k1 = k[0];\n   double k2 = k[1];\n   double k3 = k[2];\n   double k1s = args[0];\n   double k2s = args[1];\n   double k3s = args[2];\n   double filt1 = args[3];\n   double filt2 = args[4];\n   double filt3 = args[5];\n   double k12 = sqrt(k1s+k2s+2.*k1*k2*x12);\n   double k23 = sqrt(k2s+k3s-2.*k2*k3*x23);\n   double k13 = sqrt(k1s+k3s+2.*k1*k3*x13);\n   double filt12  = w_filter(k12*R,a);\n   double filt23 = w_filter(k23*R,a);\n   double term1, term2;\n\n   term1 = F2eds(k1,k2,x12)*F2eds(k2,k3,-x23)*filt23*filt12*filt1*filt3;\n   term2 = 0.;\n   if (a>=2) {\n     double k123 = sqrt(k1s + k2s + k3s + 2.*k1*k2*x12 + 2.*k2*k3*x23 + 2.*k1*k3*x13);\n     double filt123 = w_filter(k123*R,a);\n     term2 = 0.5*filt1*filt2*filt3*F3edsb(k1,k2,k3,k23,k12,k13,x23,x12,x13)*filt123;\n   }\n\treturn term1 + term2;\n}\n\nstatic double s4_num_integranda2(const PowerSpectrum& P_l, double R, int a, double k1, double k2, double k3){\n   double c[3] = {-1.,-1.,-1.};\n   double d[3] = {1.,1.,1.};\n   double k[3];\n   k[0] = k1;\n   k[1] = k2;\n   k[2] = k3;\n   double args[6];\n   args[0]= pow2(k1);\n   args[1]= pow2(k2);\n   args[2]= pow2(k3);\n   args[3]= w_filter(k1*R,a);\n   args[4]= w_filter(k2*R,a);\n   args[5]= w_filter(k3*R,a);\n\treturn args[0]*args[1]*args[2]*P_l(k1)*P_l(k2)*P_l(k3)*Integrate<3>(bind(s4_num_integranda1, cref(P_l), R, a,args,k, _1, _2, _3), c,d, 1e-4);\n}\n\n// vars is for numerical kurtosis only : vars[0]=omega0, vars[1-3] = MG params and vars[4]=scale factor\n// a chooses window functions (see w_filter)\n// b chooses (1) analytic (2) numerical (3) gamma1 + gamma2 approx for top-hat filter\n\n\nHigherStat::kurtosis_integral::kurtosis_integral(const HigherStat& hs_)\n    : MonteCarloIntegral(5), hs(hs_)\n{\n    maxeval = 10000000;\n}\n\nvoid HigherStat::kurtosis_integral::Integrand(const double x[], double* f, double* param) const {\n  double R = *param;\n  double k1 = x[0];\n  double k2 = x[1];\n  double k3 = x[2];\n  double x12 = x[3];\n  double x23 = x[4];\n  double k1s= pow2(k1);\n  double k2s = pow2(k2);\n  double k3s =  pow2(k3);\n  double filt1 = w_filter(k1*R,1);\n  double filt3 = w_filter(k3*R,1);\n  double k12 = sqrt(k1s+k2s+2.*k1*k2*x12);\n  double k23 = sqrt(k2s+k3s+2.*k2*k3*x23);\n  double filt12  = w_filter(k12*R,1);\n  double filt23  = w_filter(k23*R,1);\n  double term1 =  F2eds(k1,k2,x12)*F2eds(k2,k3,x23)*filt23*filt12*filt1;\n  f[0] = 2.*k1s*k2s*k3s*hs.P_l(k1)*hs.P_l(k2)*hs.P_l(k3)*filt3*(term1);\n}\n\n\n/* kbar definition (EQ. A.25 OF 9312026)*/\nstatic double kbar_integrand(const PowerSpectrum& P_l, double R, double k){\n\treturn pow2(pow2(k)*w_filter(k*R,1)*D_spt/dnorm_spt)*P_l(k);\n}\n\ndouble HigherStat::kurtosis(double R, int a, int b, double vars[]) const{\n  double c[3] = {KMIN_e,KMIN_e,KMIN_e};\n  double d[3] = {KMAX_e,KMAX_e,KMAX_e};\n  double term4 = 0.;\n  double kbar;\n  double sigsqr = sig_sqr(R, 1, 1, vars);\n  if (b==1 && a ==1) {\n    kbar = Integrate(bind(kbar_integrand, cref(P_l), R, _1), KMIN_e , KMAX_e, epsrel)/(2.*pow2(M_PI)*sigsqr);\n    term4 =  2./189.*pow3(sigsqr)*(1364. + 9.*gam1_test(R,cref(P_l)) * (60. + 7. * gam1_test(R,cref(P_l))) - 126. * kbar);\n  }\n  switch (b) {\n    case 1:\n      return  term4;//0.75 * pow6(D_spt/(M_PI*dnorm_spt)) * Integrate<3>(bind(s4_num_integranda2, cref(P_l), R, a, _1, _2, _3), c,d, epsrel); //+ term4;\n    case 2:\n      return (60712./1323. + 62./3.*gam1_test(R,cref(P_l)) + 7./3.*pow2(gam1_test(R,cref(P_l))) + 2./3.*gam2_test(R,epsrel,cref(P_l))) * pow3(sigsqr);\n    case 3:\n    return 0.75 * pow6(D_spt/(M_PI*dnorm_spt)) * Integrate<3>(bind(s4_num_integranda2, cref(P_l), R, a, _1, _2, _3), c,d, epsrel);\n  }\n}\n", "meta": {"hexsha": "22f80792d4c7242fe02f837683035c2e73d018c5", "size": 9862, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reactions/src/extra_libraries/HigherStat.cpp", "max_stars_repo_name": "PedroCarrilho/ReACT", "max_stars_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T11:34:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T12:48:05.000Z", "max_issues_repo_path": "reactions/src/extra_libraries/HigherStat.cpp", "max_issues_repo_name": "PedroCarrilho/ReACT", "max_issues_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z", "max_forks_repo_path": "reactions/src/extra_libraries/HigherStat.cpp", "max_forks_repo_name": "PedroCarrilho/ReACT", "max_forks_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T15:35:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T15:35:28.000Z", "avg_line_length": 31.8129032258, "max_line_length": 179, "alphanum_fraction": 0.6410464409, "num_tokens": 3746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5457542290235272}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_FUNCTIONS_MNORM_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_MNORM_HPP_INCLUDED\n#include <nt2/include/functor.hpp>\n#include <nt2/sdk/meta/as_real.hpp>\n#include <boost/mpl/int.hpp>\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/tags.hpp>\n\nnamespace nt2 { namespace tag\n  {\n    /*!\n     @brief globalnorm generic tag\n\n      Represents the mnorm function in generic contexts.\n\n      @par Models:\n      Hierarchy\n    **/\n    struct mnorm_ :  ext::abstract_<mnorm_>\n    {\n      /// INTERNAL ONLY\n      typedef ext::abstract_<mnorm_> parent;\n      template<class... Args>\n      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)\n      BOOST_AUTO_DECLTYPE_BODY( dispatching_mnorm_( ext::adl_helper(), static_cast<Args&&>(args)... ) )\n    };\n  }\n  namespace ext\n  {\n    template<class Site>\n    BOOST_FORCEINLINE generic_dispatcher<tag::mnorm_, Site> dispatching_mnorm_(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)\n    {\n      return generic_dispatcher<tag::mnorm_, Site>();\n    }\n    template<class... Args>\n    struct impl_mnorm_;\n  }\n\n  /*!\n    @brief Matricial norm\n\n    Computes the matricial norms of a matrix expression with static or dynamic choice from\n    by the optional second parameter\n    that can be 1, nt2::tag::one_  2, nt2::two_, , nt2::inf_ or , nt2::fro_\n    or the template parameter\n    that can be 1, nt2::tag::one_  2, nt2::tag::two_, , nt2::tag::inf_ or , nt2::tag::fro_\n\n    Call protocols to mnorm are summarized in the following table. We advise to use static\n    calls whenever possible as it prevents cascaded run-time if clauses and goes directly\n    to the right call at execution.\n\n    @code\n    |-------------------|-------------------|------------------------------|-------------------|\n    | mnorm(a0, p)                                                                             |\n    |-------------------|-------------------|------------------------------|-------------------|\n    |    static p       |  dynamic p        |     formula  (pseudo-code)   |  equivalent to    |\n    |-------------------|-------------------|------------------------------|-------------------|\n    | nt2::one_         | 1                 |       max(sum(abs(x)))       | mnorm1(x)         |\n    | nt2::two_         | 2                 |         max(svd(x))          | mnorm2(x)         |\n    | nt2::inf_         | nt2::Inf<T>()     |   max(sum(abs(ctrans(x))))   | mnorminf(x)       |\n    | nt2::fro_         | -1                | sqrt(sum(diag(ctrans(x)*x))) | mnormfro(x)       |\n    |-------------------|-------------------|------------------------------|-------------------|\n    | mnorm<p>(a0)                                                                             |\n    |-------------------|-------------------|------------------------------|-------------------|\n    |    static p       |                   |     matrix                   |                   |\n    |-------------------|-------------------|------------------------------|-------------------|\n    | nt2::tag::one_    |        -          |       max(sum(abs(x)))       |  mnorm1(x)        |\n    | nt2::tag::two_    |        -          |         max(svd(x))          |  mnorm2(x)        |\n    | nt2::tag::inf_    |        -          |   max(sum(abs(ctrans(x))))   |  mnorminf(x)      |\n    | nt2::tag::fro_    |        -          | sqrt(sum(diag(ctrans(x)*x))) |  mnormfro(x)      |\n    |-------------------|-------------------|------------------------------|-------------------|\n    @endcode\n\n    @par Semantic:\n    1, 2 and inf can be given dynamically or statically as template parameter ie:\n\n    For any expression @c a0 of type @c A0, the following call:\n\n    @code\n    as_real<A0::value_type>::type x = mnorm(a0);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    as_real<A0::value_type>::type x = svd(a0)(1);\n    @endcode\n\n    For any expression @c a0 of type @c A0 and any value x in {one_, two_, inf_, fro_}\n    following call:\n\n    @code\n    as_real<A0::value_type>::type r = mnorm(a0,nt2::x);\n    @endcode\n\n    or\n\n    @code\n    as_real<A0::value_type>::type r = mnorm<nt2::tag::x>(a0);\n    @endcode\n    is equivalent to:\n\n    @code\n    as_real<A0::value_type>::type r = mnormx(a0);\n    @endcode\n\n    @param a0 Expression to compute the norm of\n    @param a1 Type of norm to compute\n  **/\n\n\n\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::mnorm_, mnorm, 1)\n\n  /// @overload\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::mnorm_, mnorm, 2)\n\n  /// @overload\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::mnorm_, mnorm2, 1)\n\n  /// @overload\n  template < class T, class A>\n  BOOST_FORCEINLINE\n  typename meta::as_real<typename A::value_type>::type\n  mnorm(const A& a)\n  {\n    return mnorm(a, nt2::meta::as_<T>());\n  }\n  /// @overload\n  template < int Value, typename A>\n  BOOST_FORCEINLINE\n  typename meta::as_real<typename A::value_type>::type\n  mnorm(const A& a)\n  {\n    return mnorm(a, boost::mpl::int_<Value>());\n  }\n}\n\n\n#endif\n", "meta": {"hexsha": "42c2dedd2a780e30b644eea42018e632da9a7589", "size": 5523, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/mnorm.hpp", "max_stars_repo_name": "feelpp/nt2", "max_stars_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/linalg/include/nt2/linalg/functions/mnorm.hpp", "max_issues_repo_name": "feelpp/nt2", "max_issues_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "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": "modules/core/linalg/include/nt2/linalg/functions/mnorm.hpp", "max_forks_repo_name": "feelpp/nt2", "max_forks_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 36.82, "max_line_length": 134, "alphanum_fraction": 0.4823465508, "num_tokens": 1411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5457542259238184}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/assert.hpp>\n#include <boost/hana/integral_constant.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [minus]\nBOOST_HANA_CONSTANT_CHECK(minus(int_<3>, int_<5>) == int_<-2>);\nBOOST_HANA_CONSTEXPR_CHECK(minus(1, 2) == -1);\n//! [minus]\n\n}{\n\n//! [negate]\nBOOST_HANA_CONSTANT_CHECK(negate(int_<3>) == int_<-3>);\nBOOST_HANA_CONSTEXPR_CHECK(negate(2) == -2);\n//! [negate]\n\n}\n\n}\n", "meta": {"hexsha": "0e3c3fada6189f8614ff11b327038deec3147123", "size": 573, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/group.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/group.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/group.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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.4838709677, "max_line_length": 78, "alphanum_fraction": 0.6998254799, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.545754220924719}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/def.hpp>\n\n#include <scitbx/math/distributions.h>\n\n#if defined(__GNUC__) && __GNUC__ == 3 && __GNUC_MINOR__ == 2\n# define SCITBX_MATH_STUDENTS_T_DISABLED // to avoid compilation errors\n#endif\n\nnamespace scitbx { namespace math {\n\n/*! Wrappers for boost::math statistical distributions.\n    See also:\n    http://www.boost.org/libs/math/doc/sf_and_dist/html/math_toolkit/dist.html\n */\nnamespace {\n\n  template <typename FloatType>\n  struct normal_distribution_wrappers\n  {\n    typedef boost::math::normal_distribution<FloatType> wt;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n\n      class_<wt>(\"normal_distribution\", no_init)\n        .def(init<FloatType, FloatType>((arg(\"mean\")=0, arg(\"sd\")=1)))\n      ;\n    }\n  };\n\n#ifndef SCITBX_MATH_STUDENTS_T_DISABLED\n  template <typename FloatType>\n  struct students_t_distribution_wrappers\n  {\n    typedef FloatType ft;\n    typedef boost::math::students_t_distribution<FloatType> wt;\n\n    // workaround for Intel C++ 12.0.3\n    static FloatType\n    find_degrees_of_freedom_wrapper(\n      ft difference_from_mean, ft alpha, ft beta, ft sd, ft hint)\n    {\n      return wt::find_degrees_of_freedom(\n        difference_from_mean, alpha, beta, sd, hint);\n    }\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n\n      class_<wt>(\"students_t_distribution\", no_init)\n        .def(init<FloatType>(arg(\"v\")))\n        .def(\"degrees_of_freedom\", &wt::degrees_of_freedom)\n        .def(\"find_degrees_of_freedom\", find_degrees_of_freedom_wrapper, (\n          arg(\"difference_from_mean\"),\n          arg(\"alpha\"),\n          arg(\"beta\"),\n          arg(\"sd\"),\n          arg(\"hint\")=100))\n        .staticmethod(\"find_degrees_of_freedom\")\n      ;\n    }\n  };\n#endif\n\n  template <typename FloatType, class Distribution>\n  struct non_member_function_wrappers\n  {\n    typedef Distribution wt;\n\n    #define NEW_MEMBER(name)                \\\n    static FloatType name(wt const &self) { \\\n      return boost::math::name(self);                    \\\n    }\n\n    NEW_MEMBER(mean);\n    NEW_MEMBER(median);\n    NEW_MEMBER(mode);\n    NEW_MEMBER(variance);\n    NEW_MEMBER(standard_deviation);\n    NEW_MEMBER(skewness);\n    NEW_MEMBER(kurtosis);\n\n    #undef NEW_MEMBER\n\n    #define NEW_MEMBER(name)                               \\\n    static FloatType name(wt const &self, FloatType arg) { \\\n      return boost::math::name(self, arg);                              \\\n    }\n\n    NEW_MEMBER(pdf);\n    NEW_MEMBER(cdf);\n    NEW_MEMBER(quantile);\n\n    #undef NEW_MEMBER\n\n    static scitbx::af::shared<FloatType> quantiles(wt const &self, std::size_t n) {\n      return scitbx::math::quantiles<FloatType>(self, n);\n    }\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      def(\"mean\"              , mean);\n      def(\"median\"            , median);\n      def(\"mode\"              , mode);\n      def(\"variance\"          , variance);\n      def(\"standard_deviation\", standard_deviation);\n      def(\"skewness\"          , skewness);\n      def(\"kurtosis\"          , kurtosis);\n      def(\"pdf\"               , pdf);\n      def(\"cdf\"               , cdf);\n      def(\"quantile\"          , quantile);\n      def(\"quantiles\"         , quantiles);\n    }\n  };\n\n} // namespace <anonymous>\n\nnamespace boost_python {\n\n  void wrap_distributions()\n  {\n    normal_distribution_wrappers<double>::wrap();\n    non_member_function_wrappers<\n      double, boost::math::normal_distribution<double> >::wrap();\n#ifndef SCITBX_MATH_STUDENTS_T_DISABLED\n    students_t_distribution_wrappers<double>::wrap();\n    non_member_function_wrappers<\n      double, boost::math::students_t_distribution<double> >::wrap();\n#endif\n  }\n\n}}} // namespace scitbx::math::boost_python\n", "meta": {"hexsha": "3d16a9c46d97bb77f9645c8ab4359b88c94473fa", "size": 3846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/math/boost_python/distributions.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/math/boost_python/distributions.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/math/boost_python/distributions.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 26.8951048951, "max_line_length": 83, "alphanum_fraction": 0.6263650546, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5457398960856321}}
{"text": "#include <tdp/testing/testing.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include <tdp/manifold/SO3.h>\n#include <tdp/manifold/rotation.h>\n#include <tdp/manifold/SE3.h>\n#include <tdp/eigen/dense.h>\n\nusing namespace tdp;\n\nTEST(SE3, deriv) {\n  float eps = 1e-3;\n\n  for (size_t i=0; i<100; ++i) {\n    Eigen::Vector3f p_c = Eigen::Vector3f::Random();\n    tdp::SE3f T_wc = tdp::SE3f::Random();\n    for (size_t j=0; j<6; ++j) {\n      Eigen::Matrix<float,6,1> delta = Eigen::Matrix<float,6,1>::Zero();\n      delta(j) = eps;\n      tdp::SE3f T_wcDelta = T_wc.Exp(delta);\n      Eigen::Vector3f diffGt = T_wcDelta*p_c - T_wc*p_c ; \n      Eigen::Matrix<float,3,6> J;\n      J << -T_wc.rotation().matrix() * tdp::SO3f::invVee(p_c), T_wc.rotation().matrix();\n      Eigen::Vector3f diffJ = J*delta;\n      std::cout << j << \": \" << (diffGt-diffJ).norm() << std::endl;\n//        << \";\\t\" << diffGt.transpose() << \" \" << diffJ.transpose() << std::endl;\n    }\n  }\n}\n\nTEST(SE3, derivofInverse) {\n  float eps = 1e-3;\n\n  for (size_t i=0; i<100; ++i) {\n    Eigen::Vector3f p_w = Eigen::Vector3f::Random();\n    tdp::SE3f T_wc = tdp::SE3f::Random();\n    for (size_t j=0; j<6; ++j) {\n      Eigen::Matrix<float,6,1> delta = Eigen::Matrix<float,6,1>::Zero();\n      delta(j) = eps;\n      tdp::SE3f T_wcDelta = T_wc.Exp(delta);\n      Eigen::Vector3f diffGt = T_wcDelta.Inverse()*p_w- T_wc.Inverse()*p_w; \n      Eigen::Matrix<float,3,6> J;\n      J << tdp::SO3f::invVee(T_wc.rotation().Inverse()*(p_w-T_wc.translation())), - Eigen::Matrix3f::Identity();\n      Eigen::Vector3f diffJ = J*delta;\n\n      std::cout << j << \": \" << (diffGt-diffJ).norm() \n        << \";\\t\" << diffGt.transpose() << \" \" << diffJ.transpose() << std::endl;\n    }\n  }\n}\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "b1ead14ea0c5303c19b3072d6a4c75b1ebb96c57", "size": 1816, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/SE3derivs.cpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "test/SE3derivs.cpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "test/SE3derivs.cpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 32.4285714286, "max_line_length": 112, "alphanum_fraction": 0.5842511013, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5457398904727309}}
{"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 \"Algebra.h\"\n#include \"params.h\"\n#include \"FFT.h\"\n#include \"Random.h\"\n\nusing namespace std;\nusing namespace NTL;\n\n\nZZX FastMod(const ZZX& f)\n{\n    return (trunc(f,N0) - (f>>N0));\n}\n\nZZX Cyclo()\n{\n    ZZX phi0;\n    phi0.SetLength(N0+1);\n    phi0[0] = 1;\n    phi0[N0] = 1;\n    return phi0;\n}\n\nconst ZZX phi = Cyclo();\n\n\n//==============================================================================\n//Computes the squared norm of a polynomial f   \n//==============================================================================\nZZ SquaredNorm(const ZZX& f, const unsigned int degree)\n{\n    unsigned int i;\n    ZZ somme;\n    for(i=0; i<=degree; i++)\n    {\n        somme += sqr(f[i]);\n    }\n    return somme;\n}\n\n\n//==============================================================================\n//Verifies that for a parameter N, polynomials f, g are a valid semi-basis for building a NTRU lattice.\n//If PGCD!=1, then (f,g) isn't a valid pair\n//==============================================================================\nvoid ValidPair(ZZ& PGCD, ZZ& Alpha, ZZ& Beta, ZZX& rho_f, ZZX& rho_g, const ZZX& f, const ZZX& g)\n{\n    ZZX Res_fx, Res_gx, iphi;\n    ZZ Res_f, Res_g; \n\n    XGCD(Res_f, rho_f, iphi, f, phi, 0);\n    if(GCD(Res_f, q1)!=1)\n    {\n        PGCD = 0;\n    }\n    else\n    {    XGCD(Res_g, rho_g, iphi, g, phi, 0);\n         XGCD(PGCD, Alpha, Beta, Res_f, Res_g);\n    }\n}\n\n\n//==============================================================================\n//Computes f(1/x) mod (x^N + 1)\n//If f = a0 + a1*x + ... + a_{N-1}*x^{N-1}, then\n//Reverse(f) = a0 + a_{N-1}*x + ... + a1*x^{N-1}\n//==============================================================================\nZZX Reverse(const ZZX& f)\n{\n    assert(deg(f)>=0);\n    assert(deg(f)<N0);\n\n    ZZX fb;\n    unsigned int i;\n    fb.SetLength(N0);\n    fb[0] = f[0];\n    fb.SetLength(N0);\n    for(i=N0-deg(f); i<N0; i++)\n    {\n        fb[i] = -f[N0-i];\n    }\n    fb[0] = f[0];\n    return fb;\n}\n\n\n\n\n//==============================================================================\n//Computes the polynomial k such that (F,G) <-- (F,G) - k*(f,g) minimizes the size of (F,G)\n//==============================================================================\nZZX ReductionCoefficient(const ZZX& f, const ZZX& g, const ZZX& F, const ZZX& G, unsigned int & mb)\n{\n    unsigned int i;\n    ZZ a;\n    ZZX fb, gb, num, den, iden, iphi, k;\n\n    fb = Reverse(f);\n    gb = Reverse(g);\n    num = FastMod(fb*F + gb*G);\n    den = FastMod(f*fb + g*gb);\n    mb = MaxBits(num);\n\n\n    XGCD(a, iden, iphi, den, phi);\n    k = FastMod(num*iden);\n\n    k.SetLength(N0);\n    for(i=0; i<N0; i++)\n    {\n        k[i] /= a;\n    }\n\n    return k;\n}\n\n\n//==============================================================================\n//Computes the polynomial k such that (F,G) <-- (F,G) - k*(f,g) minimizes the size of (F,G)\n//==============================================================================\nZZX FastReductionCoefficient(const ZZX& f, const ZZX& g, const ZZX& F, const ZZX& G)\n{\n    unsigned int i;\n    ZZX k;\n    CC_t f_FFT[N0], g_FFT[N0], F_FFT[N0], G_FFT[N0], num_FFT[N0], den_FFT[N0], k_FFT[N0];\n\n    assert(MaxBits(f)<900);\n    ZZXToFFT(f_FFT, f);\n\n    assert(MaxBits(g)<900);\n    ZZXToFFT(g_FFT, g);\n\n    assert(MaxBits(F)<900);\n    ZZXToFFT(F_FFT, F);\n\n    assert(MaxBits(G)<900);\n    ZZXToFFT(G_FFT, G);\n\n    for(i=0; i<N0; i++)\n    {\n        num_FFT[i] = f_FFT[N0-1-i]*F_FFT[i] + g_FFT[N0-1-i]*G_FFT[i];\n        den_FFT[i] = f_FFT[N0-1-i]*f_FFT[i] + g_FFT[N0-1-i]*g_FFT[i];\n        k_FFT[i] = num_FFT[i]/den_FFT[i];\n    }\n\n    FFTToZZX(k, k_FFT);\n    return k;\n}\n\n\n\n//==============================================================================\n//Returns the anticircular matrix associated to integral polynomial f and integer N\n//==============================================================================\nmat_ZZ AnticircularMatrix(const ZZX& f)\n{\n    unsigned int i,j;\n    int df;\n    mat_ZZ M;\n    M.SetDims(N0, N0);\n    df = deg(f);\n    if(df==-1)\n    {\n        return M;\n    }\n    unsigned dfu;\n    dfu = ((unsigned) df);\n    if(dfu>=N0)\n    {\n        cout << \"df = \" << dfu << endl;\n        cout << \"f = \" << f << endl;\n    }\n    assert(dfu<N0);\n\n\n    for(i=0; i<N0; i++)\n    {\n        for(j=i; ((j<=dfu+i)&&(j<N0)); j++)\n        {\n            M[i][j] = f[j-i];\n        }\n        for(j=0; (j+N0)<=(dfu+i); j++)\n        {\n            M[i][j] = -f[j-i+N0];\n        }\n    }\n    return M;\n}\n\n\n\n//==============================================================================\n//Generates a basis from the double pair (f,g), (F,G) and N\n//This basis has the form :\n//    |f g|\n//M = |F G|\n//==============================================================================\nmat_ZZ BasisFromPolynomials(const ZZX& f, const ZZX& g, const ZZX& F, const ZZX& G)\n{\n    unsigned int i,j;\n    mat_ZZ A,M;\n    M.SetDims(2*N0, 2*N0);\n    A = AnticircularMatrix(f);\n    for(i=0; i<N0; i++){\n    for(j=0; j<N0; j++){\n        M[i][j] = A[i][j];\n    }}\n\n    A = AnticircularMatrix(g);\n    for(i=0; i<N0; i++){\n    for(j=0; j<N0; j++){\n        M[i][j+N0] = A[i][j];\n    }}\n\n    A = AnticircularMatrix(F);\n    for(i=0; i<N0; i++){\n    for(j=0; j<N0; j++){\n        M[i+N0][j] = A[i][j];\n    }}\n\n    A = AnticircularMatrix(G);\n    for(i=0; i<N0; i++){\n    for(j=0; j<N0; j++){\n        M[i+N0][j+N0] = A[i][j];\n    }}\n\n    return M;\n}\n\n\n\n//==============================================================================\n//Computes the Inverse of f (mod phi) (mod q)\n//==============================================================================\nZZ_pX Inverse(const ZZX& f)\n{\n    ZZ_p::init(q1);\n    ZZX rho_f, iphi;\n    ZZ Res_f;\n    ZZ_p Res_f_1;\n    XGCD(Res_f, rho_f, iphi, f, phi, 0);    \n    inv(Res_f_1, conv<ZZ_p>(Res_f));\n    assert(Res_f_1*conv<ZZ_p>(Res_f) == 1);\n\n    return ( Res_f_1 * conv<ZZ_pX>(rho_f) );\n}\n\n\n//==============================================================================\n//Computes h = g/f (mod phi) (mod q)\n//==============================================================================\nZZ_pX Quotient(const ZZX& f, const ZZX& g)\n{\n    ZZ_pX f_1, g0, h0, phi0;\n    f_1 = Inverse(f);\n    g0 = conv<ZZ_pX>(g);\n    phi0 = conv<ZZ_pX>(phi);\n    h0 = (f_1*g0)%phi0;\n    return h0;\n}\n\n\n\n//==============================================================================\n//Computes the Gram-Schmidt norm of the basis B generated from f,g\n//==============================================================================\nvoid GS_Norm(const ZZX fx, const ZZX gx, int& flag)\n{\n    unsigned int i;\n\n    double acc, acc3, Fred[N0], Gred[N0];\n    CC_t f[N0], g[N0], F[N0], G[N0];\n\n    acc = 0;\n    for(i=0; i<N0; i++)\n    {\n        acc += conv<double>(fx[i]*fx[i] + gx[i]*gx[i]);\n    }\n    acc = sqrt(acc);\n\n    ZZXToFFT(f, fx);\n    ZZXToFFT(g, gx);\n\n    for(i=0; i<N0; i++)\n    {\n        F[i] = f[i]/(f[i]*f[N0-1-i]+g[i]*g[N0-1-i]);\n        G[i] = g[i]/(f[i]*f[N0-1-i]+g[i]*g[N0-1-i]);\n    }\n    MyRealReverseFFT(Fred, F);\n    MyRealReverseFFT(Gred, G);\n\n    acc3 = 0;\n    for(i=0; i<N0; i++)\n    {\n        acc3 += Fred[i]*Fred[i] + Gred[i]*Gred[i];\n    }\n    acc3 = q0*sqrt(acc3);\n    if(acc3<acc)\n    {\n        flag = 1;\n    }\n}\n\n\n\n//==============================================================================\n//Generates a secret basis (f,g),(F,G) from the parameters N,q,Norme\n//This bases generates a NTRU lattice\n//==============================================================================\nvoid GenerateBasis(ZZX& f, ZZX& g, ZZX& F, ZZX& G, const ZZ& Norme)\n{\n    int i;\n    ZZX rho_f, rho_g, k, aux, fb, gb, num;\n    ZZ PGCD, Alpha, Beta;\n\n    int flag = 0;\n\n    while( (PGCD!=1) || (flag==0) )\n    {\n        flag = 1;\n        f = RandomPolyFixedSqNorm(Norme,N0-1);\n        g = RandomPolyFixedSqNorm(Norme,N0-1);\n        GS_Norm(f, g, flag);\n        ValidPair(PGCD, Alpha, Beta, rho_f, rho_g, f, g);\n    }\n    F = -q1*Beta*rho_g;\n    G = q1*Alpha*rho_f;\n\n    f.SetLength(N0);\n    g.SetLength(N0);\n\n    unsigned int mb;\n    k = ReductionCoefficient(f, g, F, G, mb);\n    while(deg(k)>=0)\n    {\n        i++;\n\n        F = FastMod(F - k*f);\n        G = FastMod(G - k*g);\n\n        fb = Reverse(f);\n        gb = Reverse(g);\n\n        num = FastMod(fb*F + gb*G);\n        mb = MaxBits(num);\n\n\n        k = ReductionCoefficient(f, g, F, G, mb);\n        k.normalize();\n    }\n\n    aux = FastMod(f*G - g*F);\n\n    assert(aux[0]==q1);\n    assert(deg(aux)==0);\n    aux.SetLength(N0);\n}\n\n\nRR_t DotProduct(const RR_t * x1, const RR_t * x2)\n{\n    unsigned int i;\n    RR_t rep = 0;\n    for(i=0; i<2*N0; i++)\n    {\n        rep += x1[i]*x2[i];\n    }\n    return rep;\n}\n\n\nvoid Rotate(RR_t * const dest, RR_t const * const src)\n{\n    unsigned int i;\n    for(i=0; i<N0-1; i++)\n    {\n        dest[i+1] = src[i];\n        dest[N0+i+1] = src[N0+i];\n    }\n    dest[0] = -src[N0-1];\n    dest[N0] = -src[2*N0-1];\n}\n\n\n\nvoid ClassicMGS(RR_t Bstar[2*N0][2*N0], const RR_t B[2*N0][2*N0])\n{\n    RR_t SquareNorm[2*N0], aux[2*N0];\n    unsigned int i,j,k;\n\n    SquareNorm[0] = DotProduct(B[0], B[0]);\n    for(j=0; j<2*N0; j++)\n    {\n\n        Bstar[0][j] = B[0][j];\n    }\n\n    for(i=1; i<2*N0; i++)\n    {\n        for(k=0; k<2*N0; k++)\n        {\n            Bstar[i][k] = B[i][k];\n        }\n        for(j=0; j<i; j++)\n        {\n            aux[j]= DotProduct(Bstar[i], Bstar[j]) / SquareNorm[j];\n        }\n        for(k=0; k<2*N0; k++)\n        {\n            for(j=0; j<i; j++)\n            {\n                Bstar[i][k] -= aux[j]*Bstar[j][k];\n            }\n        }\n        SquareNorm[i] = DotProduct(Bstar[i], Bstar[i]);\n    }\n}\n\n\nvoid FastMGS(RR_t Bst[2*N0][2*N0], const RR_t B[2*N0][2*N0])\n{\n    RR_t v[2*N0], v1[2*N0], C_k, D_k, C_ko, D_ko, aux;\n    //RR_t C[2*N0], D[2*N0];\n    unsigned int j, k;\n\n    cout << endl;\n    //Reducing first vector (obvious)\n    for(j=0; j<2*N0; j++)\n    {    Bst[0][j] = B[0][j];    }\n\n\n    //Initialising the vector v = b_N - Proj(b_N, (b_1...b_k-2) )\n    for(j=0; j<N0-1; j++)\n    {    v[j] = Bst[0][j+1];\n         v[j+N0] = Bst[0][j+1+N0];    }\n    v[N0-1] = -Bst[0][0];\n    v[2*N0-1] = -Bst[0][N0];\n\n    for(j=0; j<2*N0; j++)\n    {    v1[j] = v[j];    }\n\n\n    //Initialising recurring variables\n    C_k = DotProduct(Bst[0], v);\n    D_k = DotProduct(v, v);\n\n    //C[0] = C_k;\n    //D[0] = D_k;\n    //CD[0] = C[0]/D[0];\n\n\n    //Reducing b_2 to b_N and updating v at the same time\n    for(k=1; k<N0; k++)\n    {\n        //b~k <-- r(b~_{k-1}) - <b~_{k-1},b_N>/<v_{k-1},b_N> r(v)\n        aux = C_k/D_k;\n        Bst[k][0] = -Bst[k-1][N0-1] + aux*v[N0-1];\n        Bst[k][N0] = -Bst[k-1][2*N0-1] + aux*v[2*N0-1];\n        for(j=1; j<N0; j++)\n        {\n            Bst[k][j] = Bst[k-1][j-1] - aux*v[j-1];\n            Bst[k][j+N0] = Bst[k-1][j+N0-1] - aux*v[j+N0-1];\n        }\n\n        //v <-- v - Proj(v, b~_{k-1} )\n        for(j=0; j<2*N0; j++)\n        {\n            v[j] -= aux*Bst[k-1][j];\n        }\n        //sqnorm_v -= aux*aux*SquareNorm[k-1];\n\n        C_ko = C_k;\n        D_ko = D_k;\n\n        C_k = DotProduct(Bst[k], v1);\n        D_k = D_ko - C_ko*C_ko/D_ko;\n\n        //C[k] = C_k;\n        //D[k] = D_k;\n        //CD[k] = C[k]/D[k];\n        //printf (\"C[%d]= %Lf\t\t\", k, C_k);\n        //printf (\"D[%d]= %Lf\\n\", k, D_k);\n    }\n\n\n\n    //Reducing second half!\n    //cout << \"aux = \" << (1<<10)/D[N0-1] << endl;\n    for(j=0; j<N0; j++)\n    {    Bst[N0][N0+j] = Bst[N0-1][N0-1-j]*q0/D_k;\n         Bst[N0][j] = -Bst[N0-1][2*N0-1-j]*q0/D_k;    }\n\n    //Initialising the vector v = b_N - Proj(b_N, (b_1...b_k-2) )\n    for(j=0; j<N0-1; j++)\n    {    v[j] = Bst[N0][j+1];\n         v[j+N0] = Bst[N0][j+1+N0];    }\n    v[N0-1] = -Bst[N0][0];\n    v[2*N0-1] = -Bst[N0][N0];\n\n    for(j=0; j<2*N0; j++)\n    {    v1[j] = v[j];    }\n\n\n    //Initialising recursive variables\n    C_k = DotProduct(Bst[N0], v1);\n    D_k = DotProduct(Bst[N0], Bst[N0]);\n\n    //C[N0] = C_k;\n    //D[N0] = D_k;\n    //CD[N0] = C[N0]/D[N0];\n\n\n    //Reducing b_2 to b_N and updating v at the same time\n    for(k=N0+1; k<2*N0; k++)\n    {\n        //b~k <-- r(b~_{k-1}) - <b~_{k-1},b_N>/<v_{k-1},b_N> r(v)\n        aux = C_k/D_k;\n        Bst[k][0] = -Bst[k-1][N0-1] + aux*v[N0-1];\n        Bst[k][N0] = -Bst[k-1][2*N0-1] + aux*v[2*N0-1];\n        for(j=1; j<N0; j++)\n        {\n            Bst[k][j] = Bst[k-1][j-1] - aux*v[j-1];\n            Bst[k][j+N0] = Bst[k-1][j+N0-1] - aux*v[j+N0-1];\n        }\n        //SquareNorm[k] = SquareNorm[k-1] - aux*aux*sqnorm_v;\n\n\n        //v <-- v - Proj(v, b~_{k-1} )\n        for(j=0; j<2*N0; j++)\n        {\n            v[j] -= aux*Bst[k-1][j];\n        }\n        //sqnorm_v -= aux*aux*SquareNorm[k-1];\n\n        C_ko = C_k;\n        D_ko = D_k;\n\n        C_k = DotProduct(Bst[k], v1);\n        D_k = D_ko - C_ko*C_ko/D_ko;\n\n        //C[k] = C_k;\n        //D[k] = D_k;\n        //CD[k] = C[k]/D[k];\n    }\n}", "meta": {"hexsha": "27941f7a86a2cedf253c8ebd7282ece0c59fbc0a", "size": 12925, "ext": "cc", "lang": "C++", "max_stars_repo_path": "NTRU-PEKS/Algebra.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": "Algebra.cc", "max_issues_repo_name": "Rbehnia/NTRUPEKS", "max_issues_repo_head_hexsha": "780d5ef54baaa6c09386185e4d4fce1dc2e394f7", "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/Algebra.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": 23.2882882883, "max_line_length": 103, "alphanum_fraction": 0.4108317215, "num_tokens": 4447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5457398854333638}}
{"text": "#include <iostream>\n#include <cstdlib>\n#include <getopt.h>\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/math/interpolators/cubic_b_spline.hpp>\n\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n\n/* Set parameters */\nconst double alpha = 0.0025, //priming rate\n             delta = 0.019;    // death rate immune cells\n\nconst double hI = 571, // Michaelis constant\n             hT = 571; // Michaelis constant\n\n      double xi = 0.005, // default killing rate immune cells\n             R = 2; // growth rate tumor\n\n         int STOCHASTIC_KILLING = 0, // default flag stochastic killing (= off)\n             STOCHASTIC_GROWTH = 0; // default flag stochastic growth (= off)\n\n      double DIAGNOSIS_THRESHOLD = 65*1e8,\n             DIAGNOSED_AT = numeric_limits<double>::infinity(),\n             RAISE_KILLING = 1.0, // multiplication factor of killing rate by imm. therapy\n             TREATMENT_DURATION = numeric_limits<double>::infinity();\n\n      double DRIFT_XI = 0, // drift terms\n             DRIFT_R = 0;\n\n      double t_max = 1825.0; // simulation duration\n\n      double seed = time(0)+getpid();\n\ntypedef boost::array< double , 4 > state_type;\n\n\n/* Make interpolation function */\nvector<double> f(500);\nvector<double> g(500);\nboost::math::cubic_b_spline<double> spline_f, spline_g;\n\n// Function to generate time-dep. killing rate\ndouble xi_t( double t ){\n    return ( xi * ( 1 + DRIFT_XI * ( t / t_max ) ) * spline_f(t)); // / ((t + 365) / 365);\n}\n\n// Function for time-depedent growth rate\ndouble R_t( double t ){\n    return (R * (1 + DRIFT_R * (t / t_max ) ) * spline_g(t)); // / ((t + 365) / 365);\n}\n\n/* TUMOR MODEL */\nvoid tumormodel( const state_type &x , state_type &dxdt , double t )\n{\n    const double T = x[0], N = x[3], S = x[2], I = x[1];\n\n    const double t_cell_activation = alpha * ( T / (1e7 + T) ) * N;\n\n    double killing, growth;\n\n    // Set time of diagnosis\n    if( T > DIAGNOSIS_THRESHOLD ){\n        if( t < DIAGNOSED_AT )\n            DIAGNOSED_AT = t;\n    }\n\n\n    if( STOCHASTIC_KILLING )\n        killing = xi_t(t) * I * T / (1 + I/hI + T / hT); // time-dependent killing\n    else\n         killing = xi * I * T / (1 + I/hI + T / hT);      // time-independent killing\n\n\n    if( STOCHASTIC_GROWTH )\n        growth = R_t(t); // time-dependent growth\n    else\n        growth = R;\n\n    // Start immunotherapy if: one day after diagnosis, a treatment effect is set (RAISE_KILLING),\n    // and time is within treatment duration\n    if( (t > (DIAGNOSED_AT+1)) && (RAISE_KILLING != 1.0) && (t <= (DIAGNOSED_AT + TREATMENT_DURATION)) )\n        killing *= RAISE_KILLING;\n\n\n    if ( T < 1 )\n        dxdt[0] = -T;                                  // tumor cells\n    else\n        dxdt[0] = growth * pow( T , 4./5. ) - killing; // tumor cells\n\n    dxdt[1] = S - delta*I;                             // TILs\n    dxdt[2] = t_cell_activation;                       // specific T cells\n    dxdt[3] = - t_cell_activation;                     // naive T cells\n}\n\n\n/* Print output */\nvoid write_solution( const state_type &x , const double t)\n{\n    if( STOCHASTIC_GROWTH ){\n         cout << t << \"\\t\"<< R_t(t);\n    } else {\n         cout << t << \"\\t\" << R;\n    }\n    if( STOCHASTIC_KILLING )\n        cout << \"\\t\" << xi_t(t);\n    else\n        cout << \"\\t\" << xi;\n    for( int i = 0 ; i < 4 ; i ++ )\n        cout << \"\\t\" << x[i];\n  cout << endl;\n}\n\n\n#define XI_OPT 1000\n#define R_OPT 1001\n#define STOCHASTIC_KILLING_OPT 1002\n#define RAISE_KILLING_OPT 1003\n#define TREATMENT_DURATION_OPT 1004\n#define STOCHASTIC_GROWTH_OPT 1005\n#define DRIFT_XI_OPT 1006\n#define DRIFT_R_OPT 1007\n#define SEED_OPT 1008\n\n\nstatic struct option command_line_options[] =\n{\n    {\"xi\", required_argument, NULL, XI_OPT},\n    {\"R\", required_argument, NULL, R_OPT},\n    {\"stochastic-killing\", required_argument, NULL, STOCHASTIC_KILLING_OPT},\n    {\"raise-killing\", required_argument, NULL, RAISE_KILLING_OPT},\n    {\"treatment-duration\", required_argument, NULL, TREATMENT_DURATION_OPT},\n    {\"stochastic-growth\", required_argument, NULL, STOCHASTIC_GROWTH_OPT},\n    {\"drift-xi\", required_argument, NULL, DRIFT_XI_OPT},\n    {\"drift-R\", required_argument, NULL, DRIFT_R_OPT},\n    {\"seed\", required_argument, NULL, SEED_OPT}\n};\n\n\nint main(int argc, char **argv)\n{\n    // Parse command line options\n    int c;\n    double KILLING_SD = 0;\n    double GROWTH_SD = 0;\n    while ((c = getopt_long(argc, argv, \"\", command_line_options, NULL)) != -1){\n        switch(c){\n            case XI_OPT:\n                xi = atof(optarg);\n                break;\n            case R_OPT:\n                R = atof(optarg);\n                break;\n            case STOCHASTIC_KILLING_OPT:\n                STOCHASTIC_KILLING = 1;\n                KILLING_SD = atof(optarg);\n                break;\n            case STOCHASTIC_GROWTH_OPT:\n                STOCHASTIC_GROWTH = 1;\n                GROWTH_SD = atof(optarg);\n                break;\n            case RAISE_KILLING_OPT:\n                RAISE_KILLING = atof(optarg);\n                break;\n            case TREATMENT_DURATION_OPT:\n                TREATMENT_DURATION = atof(optarg);\n                break;\n            case DRIFT_XI_OPT:\n                DRIFT_XI = atof(optarg);\n                break;\n            case DRIFT_R_OPT:\n                DRIFT_R = atof(optarg);\n                break;\n            case SEED_OPT:\n                if(atof(optarg) != 0){\n                    seed = atof(optarg);\n                }\n            break;\n        }\n    }\n\n    /*Function to generate a random number*/\n    boost::mt19937 rng(seed);\n    boost::normal_distribution<> nd(0.0, 1.0);\n    boost::variate_generator<boost::mt19937&,\n                           boost::normal_distribution<> > rnorm(rng, nd);\n    \n    // Fill vector f with i, returns a vector (size=500) with scaled random numbers\n    for (auto& i: f)\n        i = 1 + rnorm()*KILLING_SD;\n    f[0] = 1;\n    \n    // Create object cubic_b_spline (constructor);\n    spline_f = boost::math::cubic_b_spline<double>(f.begin(), f.end(), 0.0, 30.5);\n\n\n    for (auto& i: g)\n        i = 1 + rnorm()*GROWTH_SD;\n    g[0] = 1;\n    \n    spline_g = boost::math::cubic_b_spline<double>(g.begin(), g.end(), 0.0, 30.5);\n\n    state_type x = {{ 1.0, 0., 0., 1e6 }};\n    //integrate(tumormodel, x, 0.0, 2500.0, 1.0, write_solution );\n    controlled_runge_kutta<runge_kutta_dopri5 < state_type >> stepper;\n\n    integrate_const( stepper, tumormodel, x, 0.0, t_max, 1.0, write_solution );\n}\n", "meta": {"hexsha": "14b74561958ffd27577597441b0e832efc341319", "size": 6549, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "model.cpp", "max_stars_repo_name": "jeroencreemers/tipping-point-cancer-immune-dynamics", "max_stars_repo_head_hexsha": "73b05ae578f6b868b09f2b1dba4688dd4933dc91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model.cpp", "max_issues_repo_name": "jeroencreemers/tipping-point-cancer-immune-dynamics", "max_issues_repo_head_hexsha": "73b05ae578f6b868b09f2b1dba4688dd4933dc91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model.cpp", "max_forks_repo_name": "jeroencreemers/tipping-point-cancer-immune-dynamics", "max_forks_repo_head_hexsha": "73b05ae578f6b868b09f2b1dba4688dd4933dc91", "max_forks_repo_licenses": ["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.4604651163, "max_line_length": 104, "alphanum_fraction": 0.5748969308, "num_tokens": 1871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5457398850510081}}
{"text": "// Based on the Boost histogram example\r\n// https://www.boost.org/doc/libs/1_70_0/libs/histogram/doc/html/histogram/getting_started.html\r\n#include <algorithm>\r\n#include <boost/format.hpp>\r\n#include <boost/histogram.hpp>\r\n#include <functional>\r\n#include <iostream>\r\n#include <sstream>\r\n#include <vector>\r\n\r\nnamespace {\r\n#include \"axes_compile_time.inc\"\r\n}\r\n\r\nint main(int argc, char* argv[]) {\r\n    using namespace boost::histogram;\r\n\r\n    auto h = make_histogram(axis::regular<>(48, -12.0, 12.0, \"x\"));\r\n    std::for_each(data.begin(), data.end(), std::ref(h));\r\n\r\n    std::ostringstream oss;\r\n    for (auto x : indexed(h, coverage::all)) {\r\n        oss << boost::format(\"bin %2i [%5.1f, %5.1f): %i\\n\") %\r\n            x.index() % x.bin().lower() % x.bin().upper() % *x;\r\n    }\r\n\r\n    std::cout << oss.str() << std::flush;\r\n    return 0;\r\n}\r\n\r\n/*\r\nLocal Variables:\r\nmode: c++\r\ncoding: utf-8-dos\r\ntab-width: nil\r\nc-file-style: \"stroustrup\"\r\nEnd:\r\n*/\r\n", "meta": {"hexsha": "b0e17d92cab3a431d3b6c9819fda06f51d45f723", "size": 949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scripts/axes_compile_time/axes_compile_time.cpp", "max_stars_repo_name": "zettsu-t/cPlusPlusFriend", "max_stars_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-04-15T00:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-10T05:11:14.000Z", "max_issues_repo_path": "scripts/axes_compile_time/axes_compile_time.cpp", "max_issues_repo_name": "zettsu-t/cPlusPlusFriend", "max_issues_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/axes_compile_time/axes_compile_time.cpp", "max_forks_repo_name": "zettsu-t/cPlusPlusFriend", "max_forks_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T22:47:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-23T22:47:08.000Z", "avg_line_length": 24.3333333333, "max_line_length": 96, "alphanum_fraction": 0.6101159115, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5457398848598296}}
{"text": "/**\n * linalg.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 <cmath>\n#include <numeric>\n#include <iostream>\n#include <algorithm>\n\n#include <Eigen/Eigenvalues>\n\n#include \"err.hpp\"\n#include \"linalg.hpp\"\n\nusing std::min;\nusing std::max;\nusing std::iota;\nusing std::fill;\nusing std::sort;\nusing std::vector;\nusing std::string;\nusing std::accumulate;\n\nusing Eigen::Ref;\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\nusing Eigen::Matrix3d;\nusing Eigen::VectorXd;\nusing Eigen::VectorXi;\n\ntypedef Eigen::Triplet<double>      Triplet;\ntypedef Eigen::SparseMatrix<double> Sparse;\ntypedef Eigen::PardisoLDLT<Sparse>  PardisoLDLT;\n\n/* Parameters for the Krylov-Schur eigensolver */\n#define KRYLOV_MAXITER           300\n#define KRYLOV_TOL               1e-15\n#define KRYLOV_RES_TOL           2.22e-16\n#define KRYLOV_SUBSPACE_MAX_SIZE 20\n\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(Ref<VectorXi> ei, Ref<VectorXi> ej, int& num_nodes) {\n    \n    int num_edges = (int) ei.rows();\n    \n    // Obtain node list from edges\n    vector<int> nodes;\n    \n    nodes.insert(nodes.end(), ei.data(), ei.data() + num_edges);\n    nodes.insert(nodes.end(), ej.data(), ej.data() + num_edges);\n        \n    sort(nodes.begin(), nodes.end());\n    auto last = unique(nodes.begin(), nodes.end());\n    \n    num_nodes = (int) (last - nodes.begin());\n    \n    // Build edge map\n    vector<int> idx_map(num_nodes);\n    \n    for (int i = 0; i < num_nodes ; ++i)\n        idx_map[nodes[i]] = i;\n    \n    // Store matrix indices\n    for (int i = 0; i < num_edges; ++i) {\n        ei(i) = idx_map[ei(i)];\n        ej(i) = idx_map[ej(i)];\n    };\n};\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 Ref<VectorXi> ei, const Ref<VectorXi> ej, int num_edges, bool sym, Sparse& dst) {\n    \n    int buffer_size = num_edges;\n    \n    if (sym)\n        buffer_size *= 2;\n    \n    // Allocate buffer\n    vector<Triplet> buffer(buffer_size);\n    \n    // Fill in the data\n    for (int i = 0; i < num_edges; ++i)\n        buffer[i] = Triplet( ei(i), ej(i), 1.0f );\n\n    // Duplicate entries if symmetric flag is true\n    if (sym)\n        for (int i = 0; i < num_edges; ++i)\n            buffer[num_edges + i] = Triplet( ej(i), ei(i),  1.0f );\n\n    dst.setFromTriplets(buffer.begin(), buffer.end());\n};\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 Ref<VectorXi> ei,\n                  const Ref<VectorXi> ej,\n                  const Ref<MatrixXd> blocks,\n                  int block_height,\n                  int block_width,\n                  int num_blocks,\n                  bool sym,\n                  Sparse& dst) {\n        \n    int buffer_size = num_blocks * block_height * block_width;\n    \n    if (sym)\n        buffer_size *= 2;\n    \n    // Allocate buffer\n    vector<Triplet> buffer(buffer_size);\n\n    // Fill in the data\n    int k = 0;\n    for (int i = 0; i < num_blocks; ++i) {\n        for (int jj = 0; jj < block_width; ++jj) {\n            for (int ii = 0; ii < block_height; ++ii) {\n                buffer[k] = Triplet( ei(i)*block_height + ii, ej(i)*block_width + jj, blocks(ii, i*block_width + jj) );\n                k++;\n            };\n        };\n    };\n\n    // Duplicate entries if symmetric flag is true\n    if (sym)\n        for (int i = 0; i < num_blocks; ++i) {\n            for (int jj = 0; jj < block_width; ++jj) {\n                for (int ii = 0; ii < block_height; ++ii) {\n                    buffer[k] = Triplet( ej(i)*block_width + jj, ei(i)*block_height + ii,  blocks(ii, i*block_width + jj) );\n                    k++;\n                };\n            };\n        };\n    \n    dst.setFromTriplets(buffer.begin(), buffer.end());\n};\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(Ref<Matrix3d> mat) {\n    Eigen::JacobiSVD<Matrix3d> svd(mat, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Matrix3d U = svd.matrixU();\n    Matrix3d R = U * svd.matrixV().transpose();\n    U.col(2) *= R.determinant();\n    mat = U * svd.matrixV().transpose();\n};\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(Ref<Matrix3d> mat) {\n    Eigen::JacobiSVD<Matrix3d> svd(mat, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    mat = svd.matrixU() * svd.matrixV().transpose();\n};\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 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 Eigen::VectorXd - The component of the vector in the subspace spanned by the first\n *         idx columns of the input matrix A\n */\nVectorXd projectionOnto(const Ref<MatrixXd> subspace_basis, unsigned int idx, const Ref<VectorXd> v) {\n    VectorXd w = subspace_basis.leftCols(idx).transpose() * v;\n    VectorXd proj = subspace_basis.leftCols(idx) * w;\n    return proj;\n};\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 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 Ref<MatrixXd> subspace_basis, unsigned int idx, Ref<VectorXd> v) {\n    VectorXd w = subspace_basis.leftCols(idx).transpose() * v;\n    v -= subspace_basis.leftCols(idx) * w;\n};\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(PardisoLDLT* solver, const Sparse& mat, const Ref<MatrixXd> rhs, Ref<MatrixXd> x) {\n    solver->factorize(mat);\n    x = solver->solve(rhs);\n};\n\n\n/**\n * Robust reorthogonalization function. 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 activate if everything fails.\n * (See G. W. Stewart 2001)\n *\n * @param V Dense matrix of doubles whose columns contain orthogonal basis vectors\n * @param r Vector to orthogonalize\n * @param residual_norm Residual norm or r after it has been orthogonalized against the first j columns of V.\n * @param idx Index specifying the number of columns of V used in the orthogonalization.\n * @param stop 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 Ref<MatrixXd> V, Ref<VectorXd> r, double& residual_norm, unsigned int idx, int& stop) {\n    stop = 0;\n    double normr0 = r.norm();\n    \n    projectOnto(V, idx, r);\n    \n    residual_norm = r.norm();\n\n    // Iteratively tries to reorthogonalize r against the columns of V\n    unsigned int num_reorths = 1;\n    while((residual_norm <= (1.0 / sqrt(2)) * normr0) && num_reorths < 5) {\n        projectOnto(V, idx, r);\n        normr0 = residual_norm;\n        residual_norm = r.norm();\n        num_reorths++;\n    };\n    \n    /* Cannot reorthogonalize: Invariant subspace found. Restart with\n     * a new random vector and try another 3 times */\n    if (residual_norm <= (1.0 / sqrt(2)) * normr0) {\n        residual_norm = 0;\n        stop = 1;\n        // Try another 3 times with random restarts\n        for (int j = 0; j < 3; ++j) {\n            r = VectorXd::Random(r.rows(),1);\n            projectOnto(V, idx, r);\n            r.normalize();\n            \n            // Reorthogonalize if necessary\n            for (unsigned int k = 0; k < 5; ++k) {\n                VectorXd Mr = r;\n                VectorXd proj = projectionOnto(V, idx, Mr);\n                double rMr = sqrt(abs(r.transpose() * Mr));\n                \n                if (abs(rMr - 1.0f) <= 1e-10) {\n                    stop = 0;\n                    break;\n                };\n                \n                // Reorthogonalize\n                r -= proj;\n                r.normalize();\n            };\n            if (!stop)\n                break;\n        };\n    } else {\n        r /= residual_norm;\n    };\n};\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(PardisoLDLT*  solver,\n                       const Sparse& mat,\n                       Ref<VectorXd> eigenvalues,\n                       Ref<MatrixXd> eigenvectors,\n                       unsigned int  k,\n                       double        sigma) {\n    \n    long n = mat.rows();\n    \n    // Sparse identity matrix\n    Sparse speye(n,n);\n    speye.setIdentity();\n    \n    Sparse shiftInvert = mat;\n    shiftInvert -= sigma * speye;\n    \n    // Get LDLt factorization of A - sigma I\n    solver->factorize(shiftInvert);\n    \n    MKS_ASSERT(solver->info()==Eigen::Success, mksGetStatusString(mksEigenPardisoLDLErr));\n    \n    // Matrix to hold the orthogonal Krylov basis\n    MatrixXd krylov_basis = MatrixXd::Zero(n, KRYLOV_SUBSPACE_MAX_SIZE);\n    \n    // Size of the V matrix (not actual size but size in use)\n    unsigned int size_krylov_basis = 0;\n    \n    // Stop the algorithm flag (reorthogonalization gone bad)\n    int stop = 0;\n    \n    // Number of selected eigenvalues\n    unsigned int k0 = k;\n\n    // Store projection data\n    vector<double> Alpha;\n    Alpha.reserve(KRYLOV_SUBSPACE_MAX_SIZE);\n    \n    // Store projection data\n    vector<double> Beta;\n    Beta.reserve(KRYLOV_SUBSPACE_MAX_SIZE);\n    \n    MatrixXd c;\n\n    double residual_norm = 0;\n    bool restarted = false;\n    unsigned int nconv = 0;\n    vector<int> converged(k0);\n\n    MatrixXd ritz_vectors;\n    MatrixXd ritz_values;\n\n    // Used to compute argsorts\n    vector<int> idx_vec(KRYLOV_SUBSPACE_MAX_SIZE);\n\n    // H matrix\n    MatrixXd H(KRYLOV_SUBSPACE_MAX_SIZE, KRYLOV_SUBSPACE_MAX_SIZE);\n\n    // Starting vector for the Krylov iterations\n    VectorXd v0 = VectorXd::Random(n,1);\n    v0.normalize();\n    \n    // One step of the power iteration\n    VectorXd v = solver->solve(v0);\n    v.normalize();\n    \n    // Main loop of the Krylov-Schur method\n    for (unsigned int i = 0; i < KRYLOV_MAXITER; ++i) {\n        // Loop to build the invariant subspace in V, H\n        for (unsigned int j = size_krylov_basis; j < KRYLOV_SUBSPACE_MAX_SIZE; ++j) {\n            \n            // Store the Krylov vector v from the previous iteration in the Krylov matrix V\n            krylov_basis.col(j) = v;\n            // Compute Krylov power using Cholesky solver: r = (A-sigma I)^-1 * v\n            VectorXd r = solver->solve(v);\n            // Component of the new vector r in the direction of the previous vector v\n            double alpha = v.transpose() * r;\n\n            // Orthogonalization\n            if (j == 0) {\n                // 1st iteration: just subtract the projection on the previous vector\n                r.noalias() -= alpha * v;\n            } else if (restarted) {\n                VectorXd w = krylov_basis.leftCols(j+1).transpose() * r;\n                r.noalias() -= krylov_basis.leftCols(j+1) * w;\n                restarted = false;\n            } else {\n                // Subtract projection on the previous vector and residuals before that\n                r.noalias() -= alpha * v;\n                r.noalias() -= residual_norm * krylov_basis.col(j-1);\n            };\n\n            /* Robust reorthogonalization of r against the columns of V.\n             * This helps prevent numerical errors */\n            reorthogonalize(krylov_basis, r, residual_norm, j+1, stop);\n\n            /* Check if it was possible to reorthogonalize. If not, we cannot find the\n             * invariant subspace and must exit the program */\n            MKS_ASSERT(!stop, mksGetStatusString(mksKrylovReorthogonalizationErr));\n            \n            // Save projection of r on the the previous vector v (alpha)\n            Alpha.push_back(alpha);\n            // Save projection of r on the previous previous vector (beta)\n            Beta.push_back(residual_norm);\n            // Set the current vector v as the orthogonalized vector r\n            v = r;\n        };\n\n        // Build matrix H\n        Eigen::Map<VectorXd> Alpha_vec(Alpha.data(), Alpha.size());\n        Eigen::Map<VectorXd> Beta_vec(Beta.data(), Beta.size()-1);\n\n        MatrixXd H1 = MatrixXd::Zero(Alpha.size(), Alpha.size());\n        H1.diagonal(-1).array() += Beta_vec.array();\n        H1.diagonal(0).array()  += Alpha_vec.array();\n        H1.diagonal(1).array()  += Beta_vec.array();\n        \n        // H matrix\n        H = MatrixXd::Zero(KRYLOV_SUBSPACE_MAX_SIZE, KRYLOV_SUBSPACE_MAX_SIZE);\n        H.bottomRightCorner(H1.rows(), H1.cols()) += H1;\n\n        if (ritz_values.rows() > 0)\n            H.topLeftCorner(ritz_values.rows(),ritz_values.rows()) += ritz_values.asDiagonal();\n\n        if (ritz_values.rows() > 0) {\n            for (unsigned int l = 0; l < k; ++l) {\n                H(l,k) = c(0,l);\n                H(k,l) = c(0,l);\n            };\n        };\n\n        Alpha.resize(0);\n        Beta.resize(0);\n\n        // Compute Ritz pairs (eigenpairs of the H matrix)\n        Eigen::SelfAdjointEigenSolver<MatrixXd> eig(H);\n        ritz_vectors = eig.eigenvectors();\n        ritz_values  = eig.eigenvalues();\n\n        // Compute residuals to find out what has converged\n        vector<double> res(ritz_vectors.cols());\n        for (unsigned int l = 0; l < ritz_vectors.cols(); ++l)\n            res[l] = abs(residual_norm * ritz_vectors(ritz_vectors.rows()-1, l));\n\n        // Argsort eigenvalues descending order\n        iota(idx_vec.begin(), idx_vec.end(), 0);\n        sort(idx_vec.begin(), idx_vec.end(), [&](size_t a, size_t b) { return abs(ritz_values(a)) > abs(ritz_values(b)); });\n\n        // Check which ones have converged\n        for (unsigned int l = 0; l < k0; ++l)\n            converged[l] = (int) ( res[idx_vec[l]] < KRYLOV_TOL * max(KRYLOV_RES_TOL, abs(ritz_values(idx_vec[l]))) );\n\n        // Number of eigenvalues which have converged\n        nconv = accumulate(converged.begin(), converged.end(), 0);\n                \n        // More than k0 eigenvalues converged: We're good to go\n        if (nconv >= k0) {\n            break;\n        } else {\n            // Adjust k to prevent stagnation\n            k = k0 + min( (float) nconv, (float) floor(((float) (KRYLOV_SUBSPACE_MAX_SIZE-k0)) / 2.0f) );\n            if (k == 1)\n                k = floor(KRYLOV_SUBSPACE_MAX_SIZE / 2.0f);\n        };\n\n        // Use previous eigenvalue argsort to sort eigenvalues and eigenvectors\n        MatrixXd ritz_vectors_ = MatrixXd::Zero(KRYLOV_SUBSPACE_MAX_SIZE, k);\n        VectorXd ritz_values_  = VectorXd::Zero(KRYLOV_SUBSPACE_MAX_SIZE, 1);\n        \n        for (unsigned int i = 0; i < k; ++i) {\n            ritz_vectors_.col(i) += ritz_vectors.col(idx_vec[i]);\n            ritz_values_(i) += ritz_values(idx_vec[i]);\n        };\n        \n        ritz_vectors = ritz_vectors_;\n        ritz_values = ritz_values_;\n\n        // Store variables for the next iteration\n        krylov_basis.leftCols(k) = krylov_basis * ritz_vectors;\n        c = residual_norm * ritz_vectors.bottomRows<1>();\n\n        restarted = true;\n        size_krylov_basis = k;\n    };\n    \n    MatrixXd ritz_vectors_ = MatrixXd::Zero(ritz_vectors.rows(), k0);\n    eigenvalues = VectorXd::Zero(k0);\n\n    for (unsigned int i = 0; i < k0; ++i) {\n        eigenvalues(i) += ritz_values(idx_vec[i]);\n        ritz_vectors_.col(i) += ritz_vectors.col(idx_vec[i]);\n    };\n\n    c = residual_norm * ritz_vectors_.bottomRows<1>();\n\n    eigenvectors = krylov_basis * ritz_vectors_;\n    eigenvectors = eigenvectors.array().rowwise() * eigenvalues.transpose().array();\n    eigenvectors.noalias() += v * c;\n\n    // Eigenvector normalization\n    VectorXd norms = eigenvectors.colwise().norm();\n    eigenvectors.array().rowwise() /= norms.array().transpose();\n\n    // Eigenvalue reverse the shift and invert\n    eigenvalues.array() = 1.0f / eigenvalues.array() + sigma;\n};\n\n};\n\n", "meta": {"hexsha": "eb0a10499bcc6485479d63b38393c5a4a9a8a60e", "size": 18668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/linalg.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/linalg.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/linalg.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.828358209, "max_line_length": 150, "alphanum_fraction": 0.6128669381, "num_tokens": 4861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5457398848598295}}
{"text": "/****************************************************************************\n**\n** This file is part of the LibreCAD project, a 2D CAD program\n**\n** Copyright (C) 2010 R. van Twisk (librecad@rvt.dds.nl)\n** Copyright (C) 2001-2003 RibbonSoft. All rights reserved.\n**\n**\n** This file may be distributed and/or modified under the terms of the\n** GNU General Public License version 2 as published by the Free Software\n** Foundation and appearing in the file gpl-2.0.txt included in the\n** packaging of this file.\n**\n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this program; if not, write to the Free Software\n** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n**\n** This copyright notice MUST APPEAR in all copies of the script!\n**\n**********************************************************************/\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/math/special_functions/ellint_2.hpp>\n\n#include <cmath>\n//#include <muParser.h>\n#include <QString>\n#include <QDebug>\n\n#include \"rs_settings.h\"\n#include \"rs_units.h\"\n#include \"rs_math.h\"\n#include \"rs_vector.h\"\n#include \"rs_debug.h\"\n\nnamespace {\nconstexpr double m_piX2 = M_PI*2; //2*PI\n}\n\n/**\n * Rounds the given double to the closest int.\n */\nint RS_Math::round(double v) {\n    return (int) lrint(v);\n}\n\n/**\n * Save pow function\n */\ndouble RS_Math::pow(double x, double y) {\n    errno = 0;\n    double ret = ::pow(x, y);\n    if (errno==EDOM) {\n        RS_DEBUG->print(RS_Debug::D_ERROR,\n                        \"RS_Math::pow: EDOM in pow\");\n        ret = 0.0;\n    }\n    else if (errno==ERANGE) {\n        RS_DEBUG->print(RS_Debug::D_WARNING,\n                        \"RS_Math::pow: ERANGE in pow\");\n        ret = 0.0;\n    }\n    return ret;\n}\n\n/* pow of vector components */\nRS_Vector RS_Math::pow(RS_Vector vp, double y) {\n    return RS_Vector(pow(vp.x,y),pow(vp.y,y));\n}\n\n/**\n * Save equal function for real types\n */\nbool RS_Math::equal(const double d1, const double d2)\n{\n    return fabs(d1 - d2) < RS_TOLERANCE;\n}\n\n/**\n * Converts radians to degrees.\n */\ndouble RS_Math::rad2deg(double a) {\n\treturn 180./M_PI*a;\n}\n\n/**\n * Converts degrees to radians.\n */\ndouble RS_Math::deg2rad(double a) {\n\treturn M_PI/180.0*a;\n}\n\n/**\n * Converts radians to gradians.\n */\ndouble RS_Math::rad2gra(double a) {\n\treturn 200./M_PI*a;\n}\n\ndouble RS_Math::gra2rad(double a) {\n\treturn M_PI/200.*a;\n}\n\n\n/**\n * Finds greatest common divider using Euclid's algorithm.\n */\nunsigned RS_Math::findGCD(unsigned a, unsigned b) {\n\n\twhile (b) {\n\t\tunsigned rem = a % b;\n        a = b;\n        b = rem;\n    }\n\n    return a;\n}\n\n\n\n/**\n * Tests if angle a is between a1 and a2. a, a1 and a2 must be in the\n * range between 0 and 2*PI.\n * All angles in rad.\n *\n * @param reversed true for clockwise testing. false for ccw testing.\n * @return true if the angle a is between a1 and a2.\n */\nbool RS_Math::isAngleBetween(double a,\n                             double a1, double a2,\n                             bool reversed) {\n\n\tif (reversed) std::swap(a1,a2);\n\tif(getAngleDifferenceU(a2, a1 ) < RS_TOLERANCE_ANGLE) return true;\n\tconst double tol=0.5*RS_TOLERANCE_ANGLE;\n\tconst double diff0=correctAngle(a2 -a1) + tol;\n\n\treturn diff0 >= correctAngle(a - a1) || diff0 >= correctAngle(a2 - a);\n}\n\n/**\n * Corrects the given angle to the range of 0 to +PI*2.0.\n */\ndouble RS_Math::correctAngle(double a) {\n    return fmod(M_PI + remainder(a - M_PI, m_piX2), m_piX2);\n}\n\n/**\n * Corrects the given angle to the range of -PI to +PI.\n */\ndouble RS_Math::correctAngle2(double a) {\n    return remainder(a, m_piX2);\n}\n\n/**\n * Returns the given angle as an Unsigned Angle in the range of 0 to +PI.\n */\ndouble RS_Math::correctAngleU(double a) {\n    return fabs(remainder(a, m_piX2));\n}\n\n\n/**\n * @return The angle that needs to be added to a1 to reach a2.\n *         Always positive and less than 2*pi.\n */\ndouble RS_Math::getAngleDifference(double a1, double a2, bool reversed) {\n\tif(reversed) std::swap(a1, a2);\n\treturn correctAngle(a2 - a1);\n}\n\ndouble RS_Math::getAngleDifferenceU(double a1, double a2)\n{\n\treturn correctAngleU(a1 - a2);\n}\n\n\n/**\n* Makes a text constructed with the given angle readable. Used\n* for dimension texts and for mirroring texts.\n*\n* @param readable true: make angle readable, false: unreadable\n* @param corrected Will point to true if the given angle was\n*   corrected, false otherwise.\n*\n * @return The given angle or the given angle+PI, depending which on\n * is readable from the bottom or right.\n */\ndouble RS_Math::makeAngleReadable(double angle, bool readable,\n                                  bool* corrected) {\n\n    double ret=correctAngle(angle);\n\n    bool cor = isAngleReadable(ret) ^ readable;\n\n    // quadrant 1 & 4\n    if (cor) {\n        //        ret = angle;\n        //    }\n        // quadrant 2 & 3\n        //    else {\n        ret = correctAngle(angle+M_PI);\n    }\n\n    if (corrected) {\n        *corrected = cor;\n    }\n\n    return ret;\n}\n\n\n/**\n * @return true: if the given angle is in a range that is readable\n * for texts created with that angle.\n */\nbool RS_Math::isAngleReadable(double angle) {\n\tconst double tolerance=0.001;\n    if (angle>M_PI_2)\n        return fabs(remainder(angle, m_piX2)) < (M_PI_2 - tolerance);\n    else\n        return fabs(remainder(angle, m_piX2)) < (M_PI_2 + tolerance);\n}\n\n/**\n * @param tol Tolerance in rad.\n * @retval true The two angles point in the same direction.\n */\nbool RS_Math::isSameDirection(double dir1, double dir2, double tol) {\n\treturn getAngleDifferenceU(dir1, dir2) < tol;\n}\n\n/**\n * Evaluates a mathematical expression and returns the result.\n * If an error occurred, the given default value 'def' will be returned.\n */\n//double RS_Math::eval(const QString& expr, double def) {\n//\n//    bool ok;\n//    double res = RS_Math::eval(expr, &ok);\n//\n//    if (!ok) {\n//        //std::cerr << \"RS_Math::evaluate: Parse error at col \"\n//        //<< ret << \": \" << fp.ErrorMsg() << \"\\n\";\n//        return def;\n//    }\n//\n//    return res;\n//}\n\n/**\n * generic replaceAll will allow substitution of one string for another\n * as many times as it exists within a given string.\n */\nvoid RS_Math::replaceAll(QString& str, const std::string& from, const std::string& to) {\n\n    QString qfrom = QString::fromStdString(from);\n    QString qto = QString::fromStdString(to);\n    if(qfrom.isEmpty())\n        return;\n    int start_pos = 0;\n    while((start_pos = str.indexOf(qfrom, start_pos)) != -1) {\n        str.replace(start_pos, qfrom.length(), qto);\n        start_pos += qto.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'\n    }\n}\n\n/**\n * Translate imperial shortform to inch equivalent math statements\n * this only holds true for simple +,- operators *,/ require manual braces..\n * which is probably a good thing.\n */\nvoid RS_Math::imperialTranslate(QString& str) {\n\n    if (str.isEmpty())\n       return;\n    // put brackets around everything first\n    str = \"(\" + str + \")\";\n    replaceAll(str,\"+\",\")+(\");\n    replaceAll(str,\"-\",\")-(\");\n    // convert foot shortform\n    replaceAll(str,\"\\'\",\"*12+\");\n    // convert inch shortform\n    replaceAll(str,\"\\\"\",\"+\");\n    // fix for inch with no fraction component\n    replaceAll(str,\"+)\",\")\");  // -- cleanup\n}\n\n/**\n * Evaluates a mathematical expression and returns the result.\n * If an error occurred, ok will be set to false (if ok isn't NULL).\n */\n//double RS_Math::eval(const QString& expr, bool* ok) {\n//    bool okTmp(false);\n//\tif(!ok) ok=&okTmp;\n//    if (expr.isEmpty()) {\n//        *ok = false;\n//        return 0.0;\n//    }\n//    double ret(0.);\n//    // create a local copy of expr\n//    QString expr_copy = expr;\n//    // main drawing unit:\n//    int insunits = RS_Units::stringToUnit(RS_SETTINGS->readEntry(\"/Unit\", \"None\"));\n//    // only apply imperial shorthand conversion if current units are 'inch'\n//    if (insunits==RS2::Inch) {\n//        // translate imperial shorthand before you eval\n//        imperialTranslate(expr_copy);\n//    }\n//    try{\n//        mu::Parser p;\n//        //p.DefineConst(\"pi\",M_PI);\n//        //p.SetExpr(expr_copy.toStdString());\n//        ret=p.Eval();\n//        *ok=true;\n//    }\n//    catch (mu::Parser::exception_type &e)\n//    {\n//        //std::cout << e.GetMsg() << std::endl;\n//        *ok=false;\n//    }\n//    return ret;\n//}\n\n\n/**\n * Converts a double into a string which is as short as possible\n *\n * @param value The double value\n * @param prec Precision e.g. a precision of 1 would mean that a\n *     value of 2.12030 will be converted to \"2.1\". 2.000 is always just \"2\").\n */\nQString RS_Math::doubleToString(double value, double prec) {\n    if (prec< RS_TOLERANCE ) {\n\t\tRS_DEBUG->print(RS_Debug::D_ERROR,\n\t\t\t\t\t\t\"RS_Math::doubleToString: invalid precision\");\n\t\treturn QString().setNum(value, prec);\n    }\n\n\tdouble const num = RS_Math::round(value / prec)*prec;\n\n\tQString exaStr = RS_Math::doubleToString(1./prec, 10);\n\tint const dotPos = exaStr.indexOf('.');\n\n    if (dotPos==-1) {\n\t\t//big numbers for the precision\n\t\treturn QString().setNum(RS_Math::round(num));\n    } else {\n\t\t//number of digits after the point\n\t\tint digits = dotPos - 1;\n\t\treturn RS_Math::doubleToString(num, digits);\n    }\n}\n\n/**\n * Converts a double into a string which is as short as possible.\n *\n * @param value The double value\n * @param prec Precision\n */\nQString RS_Math::doubleToString(double value, int prec) {\n    QString valStr;\n\n    valStr.setNum(value, 'f', prec);\n\n    if(valStr.contains('.')) {\n        // Remove tailing point and zeros:\n//        valStr.replace(QRegExp(\"0*$\"), \"\");\n//        valStr.replace(QRegExp(R\"(\\.$)\"), \"\");\n//        while (valStr.at(valStr.length()-1)=='0') {\n//            valStr.truncate(valStr.length()-1);\n//        }\n\n        if(valStr.at(valStr.length()-1)=='.') {\n            valStr.truncate(valStr.length()-1);\n        }\n\n    }\n\n    return valStr;\n}\n\n\n\n/**\n * Performs some testing for the math class.\n */\nvoid RS_Math::test() {\n\t{\n\t\tstd::cout<<\"testing quadratic solver\"<<std::endl;\n\t\t//equations x^2 + v[0] x + v[1] = 0\n\t\tstd::vector<std::vector<double>> const eqns{\n\t\t\t{-1., -1.},\n\t\t\t{-101., -1.},\n\t\t\t{-1., -100.},\n\t\t\t{2., 1.},\n\t\t\t{-2., 1.}\n\t\t};\n\t\t//expected roots\n\t\tstd::vector<std::vector<double>> roots{\n\t\t\t{-0.6180339887498948, 1.6180339887498948},\n\t\t\t{-0.0099000196991084878, 101.009900019699108},\n\t\t\t{-9.5124921972503929, 10.5124921972503929},\n\t\t\t{-1.},\n\t\t\t{1.}\n\t\t};\n\n\t\tfor(size_t i=0; i < eqns.size(); i++) {\n\t\t\tstd::cout<<\"Test quadratic solver, test case: x^2 + (\"\n\t\t\t\t\t<<eqns[i].front()<<\") x + (\"\n\t\t\t\t   <<eqns[i].back()<<\") = 0\"<<std::endl;\n\t\t\tauto sol = quadraticSolver(eqns[i]);\n\t\t\tassert(sol.size()==roots[i].size());\n\t\t\tif (sol.front() > sol.back())\n\t\t\t\tstd::swap(sol[0], sol[1]);\n\t\t\tauto expected=roots[i];\n\t\t\tif (expected.front() > expected.back())\n\t\t\t\tstd::swap(expected[0], expected[1]);\n\t\t\tfor (size_t j=0; j < sol.size(); j++) {\n\t\t\t\tdouble x0 = sol[j];\n\t\t\t\tdouble x1 = expected[j];\n\t\t\t\tdouble const prec = (x0 - x1)/(fabs(x0 + x1) + RS_TOLERANCE2);\n\t\t\t\tstd::cout<<\"root \"<<j<<\" : precision level = \"<<prec<<std::endl;\n\t\t\t\tstd::cout<<std::setprecision(17)<<\"found: \"<<x0<<\"\\texpected: \"<<x1<<std::endl;\n\t\t\t\tassert(prec < RS_TOLERANCE);\n\t\t\t}\n\t\t\tstd::cout<<std::endl;\n\t\t}\n\t\treturn;\n\t}\n\tQString s;\n    double v;\n\n    std::cout << \"RS_Math::test: doubleToString:\\n\";\n\n    v = 0.1;\n    s = RS_Math::doubleToString(v, 0.1);\n\tassert(s==\"0.1\");\n    s = RS_Math::doubleToString(v, 0.01);\n\tassert(s==\"0.10\");\n\n    v = 0.01;\n    s = RS_Math::doubleToString(v, 0.1);\n\tassert(s==\"0.0\");\n    s = RS_Math::doubleToString(v, 0.01);\n\tassert(s==\"0.01\");\n\ts = RS_Math::doubleToString(v, 0.001);\n\tassert(s==\"0.010\");\n\n    v = 0.001;\n    s = RS_Math::doubleToString(v, 0.1);\n\tassert(s==\"0.0\");\n    s = RS_Math::doubleToString(v, 0.01);\n\tassert(s==\"0.00\");\n    s = RS_Math::doubleToString(v, 0.001);\n\tassert(s==\"0.001\");\n\n    std::cout << \"RS_Math::test: imperialTranslate:\\n\";\n\n    s = \"20'2\\\"+10'11\\\"3/4\";\n    RS_Math::imperialTranslate(s);\n    assert(s==\"(20*12+2)+(10*12+11+3/4)\");\n\n    s = \"20'2\\\"-10'11\\\"3/4\";\n    RS_Math::imperialTranslate(s);\n    assert(s==\"(20*12+2)-(10*12+11+3/4)\");\n\n    s = \"-10'11\\\"3/4\";\n    RS_Math::imperialTranslate(s);\n    assert(s==\"()-(10*12+11+3/4)\");\n\n\tstd::cout << \"RS_Math::test: complete\"<<std::endl;\n}\n\n\n\n//Equation solvers\n\n// quadratic, cubic, and quartic equation solver\n// @ ce[] contains coefficient of the cubic equation:\n// @ returns a vector contains real roots\n//\n// solvers assume arguments are valid, and there's no attempt to verify validity of the argument pointers\n//\n// @author Dongxu Li <dongxuli2011@gmail.com>\nstd::vector<double> RS_Math::quadraticSolver(const std::vector<double>& ce)\n//quadratic solver for\n// x^2 + ce[0] x + ce[1] =0\n{\n    std::vector<double> ans(0,0.);\n\tif (ce.size() != 2) return ans;\n\tusing LDouble = long double;\n\tLDouble const b = -0.5L * ce[0];\n\tLDouble const c = ce[1];\n\t// x^2 -2 b x + c=0\n\t// (x - b)^2 = b^2 - c\n\t// b^2 >= fabs(c)\n\t// x = b \\pm b sqrt(1. - c/(b^2))\n\tLDouble const b2= b * b;\n\tLDouble const discriminant= b2 - c;\n\tLDouble const fc = std::abs(c);\n\n\t//TODO, fine tune to tolerance level\n\tLDouble const TOL = 1e-24L;\n\n\tif (discriminant < 0.L)\n\t\t//negative discriminant, no real root\n\t\treturn ans;\n\n\t//find the radical\n\tLDouble r;\n\n\t// given |p| >= |q|\n\t// sqrt(p^2 \\pm q^2) = p sqrt(1 \\pm q^2/p^2)\n\tif (b2 >= fc)\n\t\tr = std::abs(b) * std::sqrt(1.L - c/b2);\n\telse\n\t\t// c is negative, because b2 - c is non-negative\n\t\tr = std::sqrt(fc) * std::sqrt(1.L + b2/fc);\n\n\tif (r >= TOL*std::abs(b)) {\n\t\t//two roots\n\t\tif (b >= 0.L)\n\t\t\t//since both (b,r)>=0, avoid (b - r) loss of significance\n\t\t\tans.push_back(b + r);\n\t\telse\n\t\t\t//since b<0, r>=0, avoid (b + r) loss of significance\n\t\t\tans.push_back(b - r);\n\n\t\t//Vieta's formulas for the second root\n\t\tans.push_back(c/ans.front());\n\t} else\n\t\t//multiple roots\n\t\tans.push_back(b);\n\treturn ans;\n}\n\n\nstd::vector<double> RS_Math::cubicSolver(const std::vector<double>& ce)\n//cubic equation solver\n// x^3 + ce[0] x^2 + ce[1] x + ce[2] = 0\n{\n//    std::cout<<\"x^3 + (\"<<ce[0]<<\")*x^2+(\"<<ce[1]<<\")*x+(\"<<ce[2]<<\")==0\"<<std::endl;\n    std::vector<double> ans(0,0.);\n\tif (ce.size() != 3) return ans;\n    // depressed cubic, Tschirnhaus transformation, x= t - b/(3a)\n    // t^3 + p t +q =0\n    double shift=(1./3)*ce[0];\n    double p=ce[1] -shift*ce[0];\n    double q=ce[0]*( (2./27)*ce[0]*ce[0]-(1./3)*ce[1])+ce[2];\n    //Cardano's method,\n    //\tt=u+v\n    //\tu^3 + v^3 + ( 3 uv + p ) (u+v) + q =0\n    //\tselect 3uv + p =0, then,\n    //\tu^3 + v^3 = -q\n    //\tu^3 v^3 = - p^3/27\n    //\tso, u^3 and v^3 are roots of equation,\n    //\tz^2 + q z - p^3/27 = 0\n    //\tand u^3,v^3 are,\n    //\t\t-q/2 \\pm sqrt(q^2/4 + p^3/27)\n    //\tdiscriminant= q^2/4 + p^3/27\n    //std::cout<<\"p=\"<<p<<\"\\tq=\"<<q<<std::endl;\n    double discriminant= (1./27)*p*p*p+(1./4)*q*q;\n    if ( fabs(p)< 1.0e-75) {\n        ans.push_back((q>0)?-pow(q,(1./3)):pow(-q,(1./3)));\n        ans[0] -= shift;\n//        DEBUG_HEADER\n//        std::cout<<\"cubic: one root: \"<<ans[0]<<std::endl;\n        return ans;\n    }\n    //std::cout<<\"discriminant=\"<<discriminant<<std::endl;\n    if(discriminant>0) {\n        std::vector<double> ce2(2,0.);\n        ce2[0]=q;\n        ce2[1]=-1./27*p*p*p;\n\t\tauto r=quadraticSolver(ce2);\n        if ( r.size()==0 ) { //should not happen\n\t\t\tstd::cerr<<__FILE__<<\" : \"<<__func__<<\" : line\"<<__LINE__<<\" :cubicSolver()::Error cubicSolver(\"<<ce[0]<<' '<<ce[1]<<' '<<ce[2]<<\")\\n\";\n        }\n        double u,v;\n        u= (q<=0) ? pow(r[0], 1./3): -pow(-r[1],1./3);\n        //u=(q<=0)?pow(-0.5*q+sqrt(discriminant),1./3):-pow(0.5*q+sqrt(discriminant),1./3);\n        v=(-1./3)*p/u;\n        //std::cout<<\"u=\"<<u<<\"\\tv=\"<<v<<std::endl;\n        //std::cout<<\"u^3=\"<<u*u*u<<\"\\tv^3=\"<<v*v*v<<std::endl;\n        ans.push_back(u+v - shift);\n\n//        DEBUG_HEADER\n//        std::cout<<\"cubic: one root: \"<<ans[0]<<std::endl;\n\t}else{\n\t\tstd::complex<double> u(q,0),rt[3];\n\t\tu=std::pow(-0.5*u-sqrt(0.25*u*u+p*p*p/27),1./3);\n\t\trt[0]=u-p/(3.*u)-shift;\n\t\tstd::complex<double> w(-0.5,sqrt(3.)/2);\n\t\trt[1]=u*w-p/(3.*u*w)-shift;\n\t\trt[2]=u/w-p*w/(3.*u)-shift;\n\t\t//        DEBUG_HEADER\n\t\t//        std::cout<<\"Roots:\\n\";\n\t\t//        std::cout<<rt[0]<<std::endl;\n\t\t//        std::cout<<rt[1]<<std::endl;\n\t\t//        std::cout<<rt[2]<<std::endl;\n\t\tans.push_back(rt[0].real());\n\t\tans.push_back(rt[1].real());\n\t\tans.push_back(rt[2].real());\n\t}\n\t// newton-raphson\n\tfor(double& x0: ans){\n\t\tdouble dx=0.;\n\t\tfor(size_t i=0; i<20; ++i){\n\t\t\tdouble f=( (x0 + ce[0])*x0 + ce[1])*x0 +ce[2];\n\t\t\tdouble df=(3.*x0+2.*ce[0])*x0 +ce[1];\n\t\t\tif(fabs(df)>fabs(f)+RS_TOLERANCE){\n\t\t\t\tdx=f/df;\n\t\t\t\tx0 -= dx;\n\t\t\t}else\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n    return ans;\n}\n\n/** quartic solver\n* x^4 + ce[0] x^3 + ce[1] x^2 + ce[2] x + ce[3] = 0\n@ce, a vector of size 4 contains the coefficient in order\n@return, a vector contains real roots\n**/\nstd::vector<double> RS_Math::quarticSolver(const std::vector<double>& ce)\n{\n    std::vector<double> ans(0,0.);\n    if(RS_DEBUG->getLevel()>=RS_Debug::D_INFORMATIONAL){\n\t\tDEBUG_HEADER\n        std::cout<<\"expected array size=4, got \"<<ce.size()<<std::endl;\n    }\n    if(ce.size() != 4) return ans;\n    if(RS_DEBUG->getLevel()>=RS_Debug::D_INFORMATIONAL){\n        std::cout<<\"x^4+(\"<<ce[0]<<\")*x^3+(\"<<ce[1]<<\")*x^2+(\"<<ce[2]<<\")*x+(\"<<ce[3]<<\")==0\"<<std::endl;\n    }\n\n    // x^4 + a x^3 + b x^2 +c x + d = 0\n    // depressed quartic, x= t - a/4\n    // t^4 + ( b - 3/8 a^2 ) t^2 + (c - a b/2 + a^3/8) t + d - a c /4 + a^2 b/16 - 3 a^4/256 =0\n    // t^4 + p t^2 + q t + r =0\n    // p= b - (3./8)*a*a;\n    // q= c - 0.5*a*b+(1./8)*a*a*a;\n    // r= d - 0.25*a*c+(1./16)*a*a*b-(3./256)*a^4\n    double shift=0.25*ce[0];\n    double shift2=shift*shift;\n    double a2=ce[0]*ce[0];\n    double p= ce[1] - (3./8)*a2;\n    double q= ce[2] + ce[0]*((1./8)*a2 - 0.5*ce[1]);\n    double r= ce[3] - shift*ce[2] + (ce[1] - 3.*shift2)*shift2;\n    if(RS_DEBUG->getLevel()>=RS_Debug::D_INFORMATIONAL){\n\t\tDEBUG_HEADER\n        std::cout<<\"x^4+(\"<<p<<\")*x^2+(\"<<q<<\")*x+(\"<<r<<\")==0\"<<std::endl;\n    }\n    if (q*q <= 1.e-4*RS_TOLERANCE*fabs(p*r)) {// Biquadratic equations\n        double discriminant= 0.25*p*p -r;\n        if (discriminant < -1.e3*RS_TOLERANCE) {\n\n//            DEBUG_HEADER\n//            std::cout<<\"discriminant=\"<<discriminant<<\"\\tno root\"<<std::endl;\n            return ans;\n        }\n        double t2[2];\n        t2[0]=-0.5*p-sqrt(fabs(discriminant));\n        t2[1]= -p - t2[0];\n        //        std::cout<<\"t2[0]=\"<<t2[0]<<std::endl;\n        //        std::cout<<\"t2[1]=\"<<t2[1]<<std::endl;\n        if ( t2[1] >= 0.) { // two real roots\n            ans.push_back(sqrt(t2[1])-shift);\n            ans.push_back(-sqrt(t2[1])-shift);\n        }\n        if ( t2[0] >= 0. ) {// four real roots\n            ans.push_back(sqrt(t2[0])-shift);\n            ans.push_back(-sqrt(t2[0])-shift);\n        }\n//        DEBUG_HEADER\n//        for(int i=0;i<ans.size();i++){\n//            std::cout<<\"root x: \"<<ans[i]<<std::endl;\n//        }\n        return ans;\n    }\n    if ( fabs(r)< 1.0e-75 ) {\n        std::vector<double> cubic(3,0.);\n        cubic[1]=p;\n        cubic[2]=q;\n        ans.push_back(0.);\n\t\tauto r=cubicSolver(cubic);\n\t\tstd::copy(r.begin(),r.end(), std::back_inserter(ans));\n        for(size_t i=0; i<ans.size(); i++) ans[i] -= shift;\n        return ans;\n    }\n    // depressed quartic to two quadratic equations\n    // t^4 + p t^2 + q t + r = ( t^2 + u t + v) ( t^2 - u t + w)\n    // so,\n    // \tp + u^2= w+v\n    // \tq/u= w-v\n    // \tr= wv\n    // so,\n    //  (p+u^2)^2 - (q/u)^2 = 4 r\n    //  y=u^2,\n    //  y^3 + 2 p y^2 + ( p^2 - 4 r) y - q^2 =0\n    //\n    std::vector<double> cubic(3,0.);\n    cubic[0]=2.*p;\n    cubic[1]=p*p-4.*r;\n    cubic[2]=-q*q;\n\tauto r3= cubicSolver(cubic);\n    //std::cout<<\"quartic_solver:: real roots from cubic: \"<<ret<<std::endl;\n    //for(unsigned int i=0; i<ret; i++)\n    //   std::cout<<\"cubic[\"<<i<<\"]=\"<<cubic[i]<<\" x= \"<<croots[i]<<std::endl;\n\t//newton-raphson\n    if (r3.size()==1) { //one real root from cubic\n        if (r3[0]< 0.) {//this should not happen\n\t\t\tDEBUG_HEADER\n\t\t\tqDebug()<<\"Quartic Error:: Found one real root for cubic, but negative\\n\";\n            return ans;\n        }\n        double sqrtz0=sqrt(r3[0]);\n        std::vector<double> ce2(2,0.);\n        ce2[0]=\t-sqrtz0;\n        ce2[1]=0.5*(p+r3[0])+0.5*q/sqrtz0;\n        auto r1=quadraticSolver(ce2);\n        if (r1.size()==0 ) {\n            ce2[0]=\tsqrtz0;\n            ce2[1]=0.5*(p+r3[0])-0.5*q/sqrtz0;\n            r1=quadraticSolver(ce2);\n        }\n\t\tfor(auto& x: r1){\n\t\t\tx -= shift;\n\t\t}\n        return r1;\n    }\n    if ( r3[0]> 0. && r3[1] > 0. ) {\n        double sqrtz0=sqrt(r3[0]);\n        std::vector<double> ce2(2,0.);\n        ce2[0]=\t-sqrtz0;\n        ce2[1]=0.5*(p+r3[0])+0.5*q/sqrtz0;\n        ans=quadraticSolver(ce2);\n        ce2[0]=\tsqrtz0;\n        ce2[1]=0.5*(p+r3[0])-0.5*q/sqrtz0;\n\t\tauto r1=quadraticSolver(ce2);\n\t\tstd::copy(r1.begin(),r1.end(),std::back_inserter(ans));\n\t\tfor(auto& x: ans){\n\t\t\tx -= shift;\n\t\t}\n    }\n\t// newton-raphson\n\tfor(double& x0: ans){\n\t\tdouble dx=0.;\n\t\tfor(size_t i=0; i<20; ++i){\n\t\t\tdouble f=(( (x0 + ce[0])*x0 + ce[1])*x0 +ce[2])*x0 + ce[3] ;\n\t\t\tdouble df=((4.*x0+3.*ce[0])*x0 +2.*ce[1])*x0+ce[2];\n//\t\t\tDEBUG_HEADER\n//\t\t\tqDebug()<<\"i=\"<<i<<\"\\tx0=\"<<x0<<\"\\tf=\"<<f<<\"\\tdf=\"<<df;\n\t\t\tif(fabs(df)>RS_TOLERANCE2){\n\t\t\t\tdx=f/df;\n\t\t\t\tx0 -= dx;\n\t\t\t}else\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n    return ans;\n}\n\n/** quartic solver\n* ce[4] x^4 + ce[3] x^3 + ce[2] x^2 + ce[1] x + ce[0] = 0\n@ce, a vector of size 5 contains the coefficient in order\n@return, a vector contains real roots\n*ToDo, need a robust algorithm to locate zero terms, better handling of tolerances\n**/\nstd::vector<double> RS_Math::quarticSolverFull(const std::vector<double>& ce)\n{\n    if(RS_DEBUG->getLevel()>=RS_Debug::D_INFORMATIONAL){\n\t\tDEBUG_HEADER\n        std::cout<<ce[4]<<\"*y^4+(\"<<ce[3]<<\")*y^3+(\"<<ce[2]<<\"*y^2+(\"<<ce[1]<<\")*y+(\"<<ce[0]<<\")==0\"<<std::endl;\n    }\n\n    std::vector<double> roots(0,0.);\n    if(ce.size()!=5) return roots;\n    std::vector<double> ce2(4,0.);\n\n    if ( fabs(ce[4]) < 1.0e-14) { // this should not happen\n        if ( fabs(ce[3]) < 1.0e-14) { // this should not happen\n            if ( fabs(ce[2]) < 1.0e-14) { // this should not happen\n                if( fabs(ce[1]) > 1.0e-14) {\n                    roots.push_back(-ce[0]/ce[1]);\n                } else { // can not determine y. this means overlapped, but overlap should have been detected before, therefore return empty set\n                    return roots;\n                }\n            } else {\n                ce2.resize(2);\n                ce2[0]=ce[1]/ce[2];\n                ce2[1]=ce[0]/ce[2];\n                //std::cout<<\"ce2[2]={ \"<<ce2[0]<<' '<<ce2[1]<<\" }\\n\";\n                roots=RS_Math::quadraticSolver(ce2);\n            }\n        } else {\n            ce2.resize(3);\n            ce2[0]=ce[2]/ce[3];\n            ce2[1]=ce[1]/ce[3];\n            ce2[2]=ce[0]/ce[3];\n            //std::cout<<\"ce2[3]={ \"<<ce2[0]<<' '<<ce2[1]<<' '<<ce2[2]<<\" }\\n\";\n            roots=RS_Math::cubicSolver(ce2);\n        }\n    } else {\n        ce2[0]=ce[3]/ce[4];\n        ce2[1]=ce[2]/ce[4];\n        ce2[2]=ce[1]/ce[4];\n        ce2[3]=ce[0]/ce[4];\n        if(RS_DEBUG->getLevel()>=RS_Debug::D_INFORMATIONAL){\n\t\t\tDEBUG_HEADER\n            std::cout<<\"ce2[4]={ \"<<ce2[0]<<' '<<ce2[1]<<' '<<ce2[2]<<' '<<ce2[3]<<\" }\\n\";\n        }\n        if(fabs(ce2[3])<= RS_TOLERANCE15) {\n            //constant term is zero, factor 0 out, solve a cubic equation\n            ce2.resize(3);\n            roots=RS_Math::cubicSolver(ce2);\n            roots.push_back(0.);\n        }else\n            roots=RS_Math::quarticSolver(ce2);\n    }\n    return roots;\n}\n\n//linear Equation solver by Gauss-Jordan\n/**\n  * Solve linear equation set\n  *@ mt holds the augmented matrix\n  *@ sn holds the solution\n  *@ return true, if the equation set has a unique solution, return false otherwise\n  *\n  *@Author: Dongxu Li\n  */\n\nbool RS_Math::linearSolver(const std::vector<std::vector<double> >& mt, std::vector<double>& sn){\n    //verify the matrix size\n\tsize_t mSize(mt.size()); //rows\n\tsize_t aSize(mSize+1); //columns of augmented matrix\n\tif(std::any_of(mt.begin(), mt.end(), [&aSize](const std::vector<double>& v)->bool{\n\t\t\t\t   return v.size() != aSize;\n}))\n\t\treturn false;\n    sn.resize(mSize);//to hold the solution\n#if false\n    boost::numeric::ublas::matrix<double> bm (mSize, mSize);\n    boost::numeric::ublas::vector<double> bs(mSize);\n\n    for(int i=0;i<mSize;i++) {\n        for(int j=0;j<mSize;j++) {\n            bm(i,j)=mt[i][j];\n        }\n        bs(i)=mt[i][mSize];\n    }\n    //solve the linear equation set by LU decomposition in boost ublas\n\n    if ( boost::numeric::ublas::lu_factorize<boost::numeric::ublas::matrix<double> >(bm) ) {\n\t\tstd::cout<<__FILE__<<\" : \"<<__func__<<\" : line \"<<__LINE__<<std::endl;\n        std::cout<<\" linear solver failed\"<<std::endl;\n        //        RS_DEBUG->print(RS_Debug::D_WARNING, \"linear solver failed\");\n        return false;\n    }\n\n    boost::numeric::ublas:: triangular_matrix<double, boost::numeric::ublas::unit_lower>\n            lm = boost::numeric::ublas::triangular_adaptor< boost::numeric::ublas::matrix<double>,  boost::numeric::ublas::unit_lower>(bm);\n    boost::numeric::ublas:: triangular_matrix<double,  boost::numeric::ublas::upper>\n            um =  boost::numeric::ublas::triangular_adaptor< boost::numeric::ublas::matrix<double>,  boost::numeric::ublas::upper>(bm);\n    ;\n    boost::numeric::ublas::inplace_solve(lm,bs, boost::numeric::ublas::lower_tag());\n    boost::numeric::ublas::inplace_solve(um,bs, boost::numeric::ublas::upper_tag());\n    for(int i=0;i<mSize;i++){\n        sn[i]=bs(i);\n    }\n    //    std::cout<<\"dn=\"<<dn<<std::endl;\n    //    data.center.set(-0.5*dn(1)/dn(0),-0.5*dn(3)/dn(2)); // center\n    //    double d(1.+0.25*(dn(1)*dn(1)/dn(0)+dn(3)*dn(3)/dn(2)));\n    //    if(fabs(dn(0))<RS_TOLERANCE2\n    //            ||fabs(dn(2))<RS_TOLERANCE2\n    //            ||d/dn(0)<RS_TOLERANCE2\n    //            ||d/dn(2)<RS_TOLERANCE2\n    //            ) {\n    //        //ellipse not defined\n    //        return false;\n    //    }\n    //    d=sqrt(d/dn(0));\n    //    data.majorP.set(d,0.);\n    //    data.ratio=sqrt(dn(0)/dn(2));\n#else\n    // solve the linear equation by Gauss-Jordan elimination\n\tstd::vector<std::vector<double> > mt0(mt); //copy the matrix;\n\tfor(size_t i=0;i<mSize;++i){\n\t\tsize_t imax(i);\n        double cmax(fabs(mt0[i][i]));\n\t\tfor(size_t j=i+1;j<mSize;++j) {\n            if(fabs(mt0[j][i]) > cmax ) {\n                imax=j;\n                cmax=fabs(mt0[j][i]);\n            }\n        }\n        if(cmax<RS_TOLERANCE2) return false; //singular matrix\n        if(imax != i) {//move the line with largest absolute value at column i to row i, to avoid division by zero\n            std::swap(mt0[i],mt0[imax]);\n\t\t}\n\t\tfor(size_t k=i+1;k<=mSize;++k) { //normalize the i-th row\n            mt0[i][k] /= mt0[i][i];\n        }\n\t\tmt0[i][i]=1.;\n\t\tfor(size_t j=0;j<mSize;++j) {//Gauss-Jordan\n            if(j != i ) {\n\t\t\t\tdouble& a = mt0[j][i];\n\t\t\t\tfor(size_t k=i+1;k<=mSize;++k) {\n\t\t\t\t\tmt0[j][k] -= mt0[i][k]*a;\n                }\n\t\t\t\ta=0.;\n            }\n\t\t}\n\t\t//output gauss-jordan results for debugging\n//\t\tstd::cout<<\"========\"<<i<<\"==========\\n\";\n//\t\tfor(auto v0: mt0){\n//\t\t\tfor(auto v1:v0)\n//\t\t\t\tstd::cout<<v1<<'\\t';\n//\t\t\tstd::cout<<std::endl;\n//\t\t}\n    }\n\tfor(size_t i=0;i<mSize;++i) {\n        sn[i]=mt0[i][mSize];\n    }\n#endif\n\n    return true;\n}\n\n/**\n * wrapper of elliptic integral of the second type, Legendre form\n * @param k the elliptic modulus or eccentricity\n * @param phi elliptic angle, must be within range of [0, M_PI]\n *\n * @author: Dongxu Li\n */\ndouble RS_Math::ellipticIntegral_2(const double& k, const double& phi)\n{\n    double a= remainder(phi-M_PI_2,M_PI);\n    if(a>0.) {\n        return boost::math::ellint_2<double,double>(k,a);\n    } else {\n        return - boost::math::ellint_2<double,double>(k,fabs(a));\n    }\n}\n\n/** solver quadratic simultaneous equations of set two **/\n/* solve the following quadratic simultaneous equations,\n  *  ma000 x^2 + ma011 y^2 - 1 =0\n  * ma100 x^2 + 2 ma101 xy + ma111 y^2 + mb10 x + mb11 y +mc1 =0\n  *\n  *@m, a vector of size 8 contains coefficients in the strict order of:\n  ma000 ma011 ma100 ma101 ma111 mb10 mb11 mc1\n  * m[0] m[1] must be positive\n  *@return a vector contains real roots\n  */\nRS_VectorSolutions RS_Math::simultaneousQuadraticSolver(const std::vector<double>& m)\n{\n    RS_VectorSolutions ret(0);\n    if(m.size() != 8 ) return ret; // valid m should contain exact 8 elements\n    std::vector< double> c1(0,0.);\n    std::vector< std::vector<double> > m1(0,c1);\n    c1.resize(6);\n    c1[0]=m[0];\n    c1[1]=0.;\n    c1[2]=m[1];\n    c1[3]=0.;\n    c1[4]=0.;\n    c1[5]=-1.;\n    m1.push_back(c1);\n    c1[0]=m[2];\n    c1[1]=2.*m[3];\n    c1[2]=m[4];\n    c1[3]=m[5];\n    c1[4]=m[6];\n    c1[5]=m[7];\n    m1.push_back(c1);\n\n    return simultaneousQuadraticSolverFull(m1);\n}\n\n/** solver quadratic simultaneous equations of a set of two **/\n/* solve the following quadratic simultaneous equations,\n  * ma000 x^2 + ma001 xy + ma011 y^2 + mb00 x + mb01 y + mc0 =0\n  * ma100 x^2 + ma101 xy + ma111 y^2 + mb10 x + mb11 y + mc1 =0\n  *\n  *@m, a vector of size 2 each contains a vector of size 6 coefficients in the strict order of:\n  ma000 ma001 ma011 mb00 mb01 mc0\n  ma100 ma101 ma111 mb10 mb11 mc1\n  *@return a RS_VectorSolutions contains real roots (x,y)\n  */\nRS_VectorSolutions RS_Math::simultaneousQuadraticSolverFull(const std::vector<std::vector<double> >& m)\n{\n    RS_VectorSolutions ret;\n    if(m.size()!=2)  return ret;\n    if( m[0].size() ==3 || m[1].size()==3 ){\n        return simultaneousQuadraticSolverMixed(m);\n    }\n    if(m[0].size()!=6 || m[1].size()!=6) return ret;\n    /** eliminate x, quartic equation of y **/\n    auto& a=m[0][0];\n    auto& b=m[0][1];\n    auto& c=m[0][2];\n    auto& d=m[0][3];\n    auto& e=m[0][4];\n    auto& f=m[0][5];\n\n    auto& g=m[1][0];\n    auto& h=m[1][1];\n    auto& i=m[1][2];\n    auto& j=m[1][3];\n    auto& k=m[1][4];\n    auto& l=m[1][5];\n    /**\n      Collect[Eliminate[{ a*x^2 + b*x*y+c*y^2+d*x+e*y+f==0,g*x^2+h*x*y+i*y^2+j*x+k*y+l==0},x],y]\n      **/\n    /*\n     f^2 g^2 - d f g j + a f j^2 - 2 a f g l + (2 e f g^2 - d f g h - b f g j + 2 a f h j - 2 a f g k) y + (2 c f g^2 - b f g h + a f h^2 - 2 a f g i) y^2\n ==\n -(d^2 g l) + a d j l - a^2 l^2\n+\n (d e g j - a e j^2 - d^2 g k + a d j k - 2 b d g l + 2 a e g l + a d h l + a b j l - 2 a^2 k l) y\n+\n (-(e^2 g^2) + d e g h - d^2 g i + c d g j + b e g j - 2 a e h j + a d i j - a c j^2 - 2 b d g k + 2 a e g k + a d h k + a b j k - a^2 k^2 - b^2 g l + 2 a c g l + a b h l - 2 a^2 i l) y^2\n +\n(-2 c e g^2 + c d g h + b e g h - a e h^2 - 2 b d g i + 2 a e g i + a d h i + b c g j - 2 a c h j + a b i j - b^2 g k + 2 a c g k + a b h k - 2 a^2 i k) y^3\n+\n (-(c^2 g^2) + b c g h - a c h^2 - b^2 g i + 2 a c g i + a b h i - a^2 i^2) y^4\n\n\n      */\n    double a2=a*a;\n    double b2=b*b;\n    double c2=c*c;\n    double d2=d*d;\n    double e2=e*e;\n    double f2=f*f;\n\n    double g2=g*g;\n    double  h2=h*h;\n    double  i2=i*i;\n    double  j2=j*j;\n    double  k2=k*k;\n    double  l2=l*l;\n    std::vector<double> qy(5,0.);\n    //y^4\n    qy[4]=-c2*g2 + b*c*g*h - a*c*h2 - b2*g*i + 2.*a*c*g*i + a*b*h*i - a2*i2;\n    //y^3\n    qy[3]=-2.*c*e*g2 + c*d*g*h + b*e*g*h - a*e*h2 - 2.*b*d*g*i + 2.*a*e*g*i + a*d*h*i +\n            b*c*g*j - 2.*a*c*h*j + a*b*i*j - b2*g*k + 2.*a*c*g*k + a*b*h*k - 2.*a2*i*k;\n    //y^2\n    qy[2]=(-e2*g2 + d*e*g*h - d2*g*i + c*d*g*j + b*e*g*j - 2.*a*e*h*j + a*d*i*j - a*c*j2 -\n           2.*b*d*g*k + 2.*a*e*g*k + a*d*h*k + a*b*j*k - a2*k2 - b2*g*l + 2.*a*c*g*l + a*b*h*l - 2.*a2*i*l)\n            - (2.*c*f*g2 - b*f*g*h + a*f*h2 - 2.*a*f*g*i);\n    //y\n    qy[1]=(d*e*g*j - a*e*j2 - d2*g*k + a*d*j*k - 2.*b*d*g*l + 2.*a*e*g*l + a*d*h*l + a*b*j*l - 2.*a2*k*l)\n            -(2.*e*f*g2 - d*f*g*h - b*f*g*j + 2.*a*f*h*j - 2.*a*f*g*k);\n    //y^0\n    qy[0]=-d2*g*l + a*d*j*l - a2*l2\n            - ( f2*g2 - d*f*g*j + a*f*j2 - 2.*a*f*g*l);\n\tif(RS_DEBUG->getLevel()>=RS_Debug::D_INFORMATIONAL){\n\t\tDEBUG_HEADER\n        std::cout<<qy[4]<<\"*y^4 +(\"<<qy[3]<<\")*y^3+(\"<<qy[2]<<\")*y^2+(\"<<qy[1]<<\")*y+(\"<<qy[0]<<\")==0\"<<std::endl;\n\t}\n    //quarticSolver\n\tauto roots=quarticSolverFull(qy);\n    if(RS_DEBUG->getLevel()>=RS_Debug::D_INFORMATIONAL){\n        std::cout<<\"roots.size()= \"<<roots.size()<<std::endl;\n    }\n\n    if (roots.size()==0 ) { // no intersection found\n        return ret;\n    }\n    std::vector<double> ce(0,0.);\n\n    for(size_t i0=0;i0<roots.size();i0++){\n        if(RS_DEBUG->getLevel()>=RS_Debug::D_INFORMATIONAL){\n\t\t\tDEBUG_HEADER\n            std::cout<<\"y=\"<<roots[i0]<<std::endl;\n        }\n        /*\n          Collect[Eliminate[{ a*x^2 + b*x*y+c*y^2+d*x+e*y+f==0,g*x^2+h*x*y+i*y^2+j*x+k*y+l==0},x],y]\n          */\n        ce.resize(3);\n        ce[0]=a;\n        ce[1]=b*roots[i0]+d;\n        ce[2]=c*roots[i0]*roots[i0]+e*roots[i0]+f;\n//    DEBUG_HEADER\n//                std::cout<<\"(\"<<ce[0]<<\")*x^2 + (\"<<ce[1]<<\")*x + (\"<<ce[2]<<\") == 0\"<<std::endl;\n        if(fabs(ce[0])<1e-75 && fabs(ce[1])<1e-75) {\n            ce[0]=g;\n            ce[1]=h*roots[i0]+j;\n            ce[2]=i*roots[i0]*roots[i0]+k*roots[i0]+f;\n//            DEBUG_HEADER\n//            std::cout<<\"(\"<<ce[0]<<\")*x^2 + (\"<<ce[1]<<\")*x + (\"<<ce[2]<<\") == 0\"<<std::endl;\n\n        }\n        if(fabs(ce[0])<1e-75 && fabs(ce[1])<1e-75) continue;\n\n        if(fabs(a)>1e-75){\n            std::vector<double> ce2(2,0.);\n            ce2[0]=ce[1]/ce[0];\n            ce2[1]=ce[2]/ce[0];\n//                DEBUG_HEADER\n//                        std::cout<<\"x^2 +(\"<<ce2[0]<<\")*x+(\"<<ce2[1]<<\")==0\"<<std::endl;\n\t\t\tauto xRoots=quadraticSolver(ce2);\n            for(size_t j0=0;j0<xRoots.size();j0++){\n//                DEBUG_HEADER\n//                std::cout<<\"x=\"<<xRoots[j0]<<std::endl;\n                RS_Vector vp(xRoots[j0],roots[i0]);\n                if(simultaneousQuadraticVerify(m,vp)) ret.push_back(vp);\n            }\n            continue;\n        }\n        RS_Vector vp(-ce[2]/ce[1],roots[i0]);\n        if(simultaneousQuadraticVerify(m,vp)) ret.push_back(vp);\n    }\n\tif(RS_DEBUG->getLevel()>=RS_Debug::D_INFORMATIONAL){\n\t\tDEBUG_HEADER\n        std::cout<<\"ret=\"<<ret<<std::endl;\n\t}\n    return ret;\n}\n\nRS_VectorSolutions RS_Math::simultaneousQuadraticSolverMixed(const std::vector<std::vector<double> >& m)\n{\n    RS_VectorSolutions ret;\n    auto p0=& (m[0]);\n    auto p1=& (m[1]);\n    if(p1->size()==3){\n        std::swap(p0,p1);\n    }\n    if(p1->size()==3) {\n            //linear\n\t\t\tstd::vector<double> sn(2,0.);\n\t\t\tstd::vector<std::vector<double> > ce;\n\t\t\tce.push_back(m[0]);\n\t\t\tce.push_back(m[1]);\n            ce[0][2]=-ce[0][2];\n            ce[1][2]=-ce[1][2];\n            if( RS_Math::linearSolver(ce,sn)) ret.push_back(RS_Vector(sn[0],sn[1]));\n            return ret;\n    }\n//    DEBUG_HEADER\n//    std::cout<<\"p0: size=\"<<p0->size()<<\"\\n Solve[{(\"<< p0->at(0)<<\")*x + (\"<<p0->at(1)<<\")*y + (\"<<p0->at(2)<<\")==0,\";\n//    std::cout<<\"(\"<< p1->at(0)<<\")*x^2 + (\"<<p1->at(1)<<\")*x*y + (\"<<p1->at(2)<<\")*y^2 + (\"<<p1->at(3)<<\")*x +(\"<<p1->at(4)<<\")*y+(\"\n//            <<p1->at(5)<<\")==0},{x,y}]\"<<std::endl;\n    const double& a=p0->at(0);\n    const double& b=p0->at(1);\n    const double& c=p0->at(2);\n    const double& d=p1->at(0);\n    const double& e=p1->at(1);\n    const double& f=p1->at(2);\n    const double& g=p1->at(3);\n    const double& h=p1->at(4);\n    const double& i=p1->at(5);\n    /**\n      y (2 b c d-a c e)-a c g+c^2 d = y^2 (a^2 (-f)+a b e-b^2 d)+y (a b g-a^2 h)+a^2 (-i)\n      */\n    std::vector<double> ce(3,0.);\n\tconst double& a2=a*a;\n\tconst double& b2=b*b;\n\tconst double& c2=c*c;\n    ce[0]= -f*a2+a*b*e-b2*d;\n    ce[1]=a*b*g-a2*h- (2*b*c*d-a*c*e);\n    ce[2]=a*c*g-c2*d-a2*i;\n//    DEBUG_HEADER\n//    std::cout<<\"(\"<<ce[0]<<\") y^2 + (\"<<ce[1]<<\") y + (\"<<ce[2]<<\")==0\"<<std::endl;\n    std::vector<double> roots(0,0.);\n    if( fabs(ce[1])>RS_TOLERANCE15 && fabs(ce[0]/ce[1])<RS_TOLERANCE15){\n        roots.push_back( - ce[2]/ce[1]);\n    }else{\n        std::vector<double> ce2(2,0.);\n        ce2[0]=ce[1]/ce[0];\n        ce2[1]=ce[2]/ce[0];\n        roots=quadraticSolver(ce2);\n    }\n//    for(size_t i=0;i<roots.size();i++){\n//    std::cout<<\"x=\"<<roots.at(i)<<std::endl;\n//    }\n\n\n    if(roots.size()==0)  {\n        return RS_VectorSolutions();\n    }\n    for(size_t i=0;i<roots.size();i++){\n        ret.push_back(RS_Vector(-(b*roots.at(i)+c)/a,roots.at(i)));\n//        std::cout<<ret.at(ret.size()-1).x<<\", \"<<ret.at(ret.size()-1).y<<std::endl;\n    }\n\n    return ret;\n\n}\n\n/** verify a solution for simultaneousQuadratic\n  *@m the coefficient matrix\n  *@v, a candidate to verify\n  *@return true, for a valid solution\n  **/\nbool RS_Math::simultaneousQuadraticVerify(const std::vector<std::vector<double> >& m, RS_Vector& v)\n{\n\tRS_Vector v0=v;\n\tauto& a=m[0][0];\n\tauto& b=m[0][1];\n\tauto& c=m[0][2];\n\tauto& d=m[0][3];\n\tauto& e=m[0][4];\n\tauto& f=m[0][5];\n\n\tauto& g=m[1][0];\n\tauto& h=m[1][1];\n\tauto& i=m[1][2];\n\tauto& j=m[1][3];\n\tauto& k=m[1][4];\n\tauto& l=m[1][5];\n    /**\n      * tolerance test for bug#3606099\n      * verifying the equations to floating point tolerance by terms\n      */\n\tdouble sum0=0., sum1=0.;\n\tdouble f00=0.,f01=0.;\n\tdouble amax0, amax1;\n\tfor(size_t i0=0; i0<20; ++i0){\n\t\tdouble& x=v.x;\n\t\tdouble& y=v.y;\n\t\tdouble x2=x*x;\n\t\tdouble y2=y*y;\n\t\tdouble const terms0[12]={ a*x2, b*x*y, c*y2, d*x, e*y, f, g*x2, h*x*y, i*y2, j*x, k*y, l};\n\t\tamax0=fabs(terms0[0]), amax1=fabs(terms0[6]);\n\t\tdouble px=2.*a*x+b*y+d;\n\t\tdouble py=b*x+2.*c*y+e;\n\t\tsum0=0.;\n\t\tfor(int i=0; i<6; i++) {\n\t\t\tif(amax0<fabs(terms0[i])) amax0=fabs(terms0[i]);\n\t\t\tsum0 += terms0[i];\n\t\t}\n\t\tstd::vector<std::vector<double>> nrCe;\n\t\tnrCe.push_back(std::vector<double>{px, py, sum0});\n\t\tpx=2.*g*x+h*y+j;\n\t\tpy=h*x+2.*i*y+k;\n\t\tsum1=0.;\n\t\tfor(int i=6; i<12; i++) {\n\t\t\tif(amax1<fabs(terms0[i])) amax1=fabs(terms0[i]);\n\t\t\tsum1 += terms0[i];\n\t\t}\n\t\tnrCe.push_back(std::vector<double>{px, py, sum1});\n\t\tstd::vector<double> dn;\n\t\tbool ret=linearSolver(nrCe, dn);\n//\t\tDEBUG_HEADER\n//\t\tqDebug()<<\"i0=\"<<i0<<\"\\tf=(\"<<sum0<<','<<sum1<<\")\\tdn=(\"<<dn[0]<<\",\"<<dn[1]<<\")\";\n\t\tif(!i0){\n\t\t\tf00=sum0;\n\t\t\tf01=sum1;\n\t\t}\n\t\tif(!ret) break;\n\t\tv -= RS_Vector(dn[0], dn[1]);\n\t}\n\tif( fabs(sum0)> fabs(f00) && fabs(sum1)>fabs(f01)){\n\t\tv=v0;\n\t\tsum0=f00;\n\t\tsum1=f01;\n\t}\n\n//    DEBUG_HEADER\n//    std::cout<<\"verifying: x=\"<<x<<\"\\ty=\"<<y<<std::endl;\n//    std::cout<<\"0: maxterm: \"<<amax0<<std::endl;\n//    std::cout<<\"verifying: fabs(a*x2 + b*x*y+c*y2+d*x+e*y+f)/maxterm=\"<<fabs(sum0)/amax0<<\" required to be smaller than \"<<sqrt(6.)*sqrt(DBL_EPSILON)<<std::endl;\n//    std::cout<<\"1: maxterm: \"<<amax1<<std::endl;\n//    std::cout<<\"verifying: fabs(g*x2+h*x*y+i*y2+j*x+k*y+l)/maxterm=\"<< fabs(sum1)/amax1<<std::endl;\n    const double tols=2.*sqrt(6.)*sqrt(DBL_EPSILON); //experimental tolerances to verify simultaneous quadratic\n\n    return (amax0<=tols || fabs(sum0)/amax0<tols) &&  (amax1<=tols || fabs(sum1)/amax1<tols);\n}\n//EOF\n", "meta": {"hexsha": "93174ef6a1d1b544c14aceabfff8d62e19858888", "size": 39170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/math/rs_math.cpp", "max_stars_repo_name": "iamjinlei/dxf2png", "max_stars_repo_head_hexsha": "f6f44b50e181e96e463f0a74510e5d4d595e9cc0", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2018-07-21T01:36:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T12:03:00.000Z", "max_issues_repo_path": "src/lib/math/rs_math.cpp", "max_issues_repo_name": "AbidIqbal007/dxf2png", "max_issues_repo_head_hexsha": "f6f44b50e181e96e463f0a74510e5d4d595e9cc0", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-31T10:18:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T11:36:33.000Z", "max_forks_repo_path": "src/lib/math/rs_math.cpp", "max_forks_repo_name": "AbidIqbal007/dxf2png", "max_forks_repo_head_hexsha": "f6f44b50e181e96e463f0a74510e5d4d595e9cc0", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-08-14T01:58:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T06:49:00.000Z", "avg_line_length": 30.4587869362, "max_line_length": 187, "alphanum_fraction": 0.5445238703, "num_tokens": 13626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5457398684034828}}
{"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_ASIND_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASIND_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the inverse sine in degree.\n\n\n    @par Header <boost/simd/function/asind.hpp>\n\n    @par Note\n\n      For every parameter of floating type `asind(x)`\n      returns the arc @c r in the interval  \\f$[-90, 90[\\f$ such that\n      <tt>sin(r) == x</tt>.  If @c x is outside \\f$[-1, 1[\\f$ the result is Nan.\n\n    @see asin,  asinpi\n\n    @par Example:\n\n      @snippet asind.cpp asind\n\n    @par Possible output:\n\n      @snippet asind.txt asind\n\n  **/\n  IEEEValue asind(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/asind.hpp>\n#include <boost/simd/function/simd/asind.hpp>\n\n#endif\n", "meta": {"hexsha": "b8537f927c037c6f63ab79ec27a519248dbacd58", "size": 1217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/asind.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/function/asind.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/function/asind.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": 24.34, "max_line_length": 100, "alphanum_fraction": 0.5743631882, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.545730209758838}}
{"text": "#ifndef __fovis_initial_homography_estimator_hpp__\n#define __fovis_initial_homography_estimator_hpp__\n\n#include <vector>\n#include <stdint.h>\n#include <Eigen/Dense>\n\nnamespace fovis\n{\n\n/**\n * \\brief Estimates a rough 2D homography registering two images.\n */\nclass InitialHomographyEstimator {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\npublic:\n  /**\n   * Set the template image to the passed in arguments.\n   * assumes the image data is row-major.\n   * The image will be downsampled by \\f$ 1/2^{downsampleFactor} \\f$\n   */\n  void setTemplateImage(const uint8_t * grayData, int width, int height, int stride, int downsampleFactor);\n\n  /**\n   * Set the test image accordingly. The opimization will warp this image to\n   * match the template assumes the image data is row-major.\n   * The image will be downsampled by \\f$ 1/2^{downsampleFactor} \\f$\n   */\n  void setTestImage(const uint8_t * grayData, int width, int height, int stride, int downsampleFactor);\n\n  /**\n   * Run ESM to find the homography between the template and test images. These\n   * should have already been passed in using the methods setTemplateImage(), and\n   * setTestImage().\n   */\n  Eigen::Matrix3f track(const Eigen::Matrix3f &init_H, int nIters, double *finalRMS);\n\nprivate:\n  int template_rows, template_cols; //size of the template\n  Eigen::MatrixXf templateImage, testImage; //the images\n  Eigen::MatrixXf warpedTestImage; //storage for the warped testImage on the current iteration\n  Eigen::MatrixXf errorIm; //the difference between the templateImage and the warpedTestImage\n  Eigen::ArrayXf templateDxRow, templateDyRow; //the gradient of the template flattened into a row vector\n  Eigen::MatrixXf templatePoints; //nx3 matrix storing the x,y,1 for each pixel\n  Eigen::ArrayXf xx, yy; //convenience array storing the original x/y for each pixel in the flattened image\n\n  //internal functions\n\n  /**\n   * Compute the x/y gradient of the passed in image\n   */\n  static void computeGradient(const Eigen::MatrixXf &image, Eigen::MatrixXf * dxp, Eigen::MatrixXf *dyp);\n\n  /**\n   * Compute the error (RMS) for the passed in difference image\n   */\n  static double computeError(const Eigen::MatrixXf &error);\n\n  /**\n   * form the Jacobian\n   */\n  Eigen::MatrixXf computeJacobian(const Eigen::ArrayXf &dx, const Eigen::ArrayXf &dy) const;\n\n  /**\n   * Compute the homography from the lie parameterization\n   */\n  Eigen::Matrix3f lieToH(const Eigen::VectorXf &lie) const;\n\n  /**\n   * Warp srcImage according to the warped points\n   */\n  Eigen::MatrixXf constructWarpedImage(const Eigen::MatrixXf &srcImage, const Eigen::MatrixXf &warpedPoints) const;\n\n  /**\n   * Flatten an image stored as a matrix down into a row vector\n   */\n  static Eigen::ArrayXf flattenMatrix(Eigen::MatrixXf &m);\n\n};\n\n}\n\n#endif\n", "meta": {"hexsha": "9396175046a725ae2a7c6c2ce2304f51e2b31d56", "size": 2768, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "navigation_layer/fovis/libfovis/libfovis/libfovis/initial_homography_estimation.hpp", "max_stars_repo_name": "kartavya2000/Anahita", "max_stars_repo_head_hexsha": "9afbf6c238658188df7d0d97b2fec3bd48028c03", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-03-21T15:18:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T07:52:10.000Z", "max_issues_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/libfovis/initial_homography_estimation.hpp", "max_issues_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_issues_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-10-03T12:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-07T09:33:14.000Z", "max_forks_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/libfovis/initial_homography_estimation.hpp", "max_forks_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_forks_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2018-09-09T12:35:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-03T09:28:19.000Z", "avg_line_length": 32.5647058824, "max_line_length": 115, "alphanum_fraction": 0.7333815029, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5457302093360058}}
{"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_ACSCH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACSCH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-hyperbolic\n    This function object returns the hyperbolic cosecant argument\n    \\f$\\mathop{\\textrm{asinh}}(1/x)\\f$\n\n    @par Header <boost/simd/function/acsch.hpp>\n\n    @see cosh, sinh,  acosh, asinh, atanh, asech, acoth, atanh\n\n\n    @par Example:\n\n      @snippet acsch.cpp acsch\n\n    @par Possible output:\n\n      @snippet acsch.txt acsch\n\n\n  **/\n  IEEEValue acsch(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acsch.hpp>\n#include <boost/simd/function/simd/acsch.hpp>\n\n#endif\n", "meta": {"hexsha": "5953f3da466cd4b434188a74c1e1b3cd1bdd328f", "size": 1079, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acsch.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/function/acsch.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/function/acsch.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": 22.9574468085, "max_line_length": 100, "alphanum_fraction": 0.5801668211, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.545730209124589}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/assert.hpp>\n#include <boost/hana/back.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/front.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/range.hpp>\n#include <boost/hana/tail.hpp>\nnamespace hana = boost::hana;\n\n\nBOOST_HANA_CONSTANT_CHECK(hana::front(hana::range_c<int, 0, 5>) == hana::int_c<0>);\nBOOST_HANA_CONSTANT_CHECK(hana::back(hana::range_c<unsigned long, 0, 5>) == hana::ulong_c<4>);\nBOOST_HANA_CONSTANT_CHECK(hana::tail(hana::range_c<int, 0, 5>) == hana::make_range(hana::int_c<1>, hana::int_c<5>));\n\nint main() { }\n", "meta": {"hexsha": "6d81848a222d90c9564df621959b347697532a17", "size": 754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/range/range_c.cpp", "max_stars_repo_name": "qicosmos/hana", "max_stars_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-06T05:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T21:48:27.000Z", "max_issues_repo_path": "example/range/range_c.cpp", "max_issues_repo_name": "qicosmos/hana", "max_issues_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "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/range/range_c.cpp", "max_forks_repo_name": "qicosmos/hana", "max_forks_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-06T10:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-06T10:50:17.000Z", "avg_line_length": 34.2727272727, "max_line_length": 116, "alphanum_fraction": 0.7360742706, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5457302034146767}}
{"text": "#define BOOST_TEST_MODULE \"test_uniform_lennard_jones_potential\"\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#include <mjolnir/forcefield/global/UniformLennardJonesPotential.hpp>\n#include <mjolnir/util/make_unique.hpp>\n\nBOOST_AUTO_TEST_CASE(UniformLennardJones_double)\n{\n    using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;\n    using real_type   = typename traits_type::real_type;\n    using molecule_id_type = mjolnir::Topology::molecule_id_type;\n    using group_id_type    = mjolnir::Topology::group_id_type;\n    constexpr std::size_t N = 10000;\n    constexpr real_type   h = 1e-6;\n\n    constexpr real_type sigma   = 3.0;\n    constexpr real_type epsilon = 1.0;\n    mjolnir::UniformLennardJonesPotential<traits_type> lj{\n        sigma, epsilon,\n        mjolnir::UniformLennardJonesPotential<traits_type>::default_cutoff(), {}, {},\n        mjolnir::IgnoreMolecule<molecule_id_type>(\"Nothing\"),\n        mjolnir::IgnoreGroup   <group_id_type   >({})\n    };\n    const real_type cutoff = lj.cutoff_ratio();\n\n    const real_type x_min = 0.8 * sigma;\n    const real_type x_max = cutoff * sigma;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + i * dx;\n        const real_type pot1 = lj.potential(0, 1, x + h);\n        const real_type pot2 = lj.potential(0, 1, x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = lj.derivative(0, 1, x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(UniformLennardJones_float)\n{\n    using traits_type = mjolnir::SimulatorTraits<float, mjolnir::UnlimitedBoundary>;\n    using real_type   = typename traits_type::real_type;\n    using molecule_id_type = mjolnir::Topology::molecule_id_type;\n    using group_id_type    = mjolnir::Topology::group_id_type;\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 0.002;\n    constexpr real_type tol = 0.005;\n\n    constexpr real_type sigma   = 3.0;\n    constexpr real_type epsilon = 1.0;\n    mjolnir::UniformLennardJonesPotential<traits_type> lj{\n        sigma, epsilon,\n        mjolnir::UniformLennardJonesPotential<traits_type>::default_cutoff(), {}, {},\n        mjolnir::IgnoreMolecule<molecule_id_type>(\"Nothing\"),\n        mjolnir::IgnoreGroup   <group_id_type   >({})\n    };\n    const real_type cutoff = lj.cutoff_ratio();\n\n    const real_type x_min = 0.8 * sigma;\n    const real_type x_max = cutoff * sigma;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + i * dx;\n        const real_type pot1 = lj.potential(0, 1, x + h);\n        const real_type pot2 = lj.potential(0, 1, x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = lj.derivative(0, 1, x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(tol));\n    }\n}\n", "meta": {"hexsha": "7584e8bb1263c2c7f3433e34dffac32faeff5118", "size": 3014, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_uniform_lennard_jones_potential.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "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/core/test_uniform_lennard_jones_potential.cpp", "max_issues_repo_name": "yutakasi634/Mjolnir", "max_issues_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T11:41:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T10:01:38.000Z", "max_forks_repo_path": "test/core/test_uniform_lennard_jones_potential.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["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.2098765432, "max_line_length": 85, "alphanum_fraction": 0.6708692767, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.545730197916181}}
{"text": "#include <cnoid/Plugin>\n#include <cnoid/ItemTreeView>\n#include <cnoid/BodyItem>\n#include <cnoid/ToolBar>\n#include <cnoid/Body>\n#include <cnoid/JointPath>\n#include <cnoid/Jacobian>\n#include <cnoid/BodyLoader>\n#include <cnoid/Link>\n\n#include <Eigen/Core>\n\nusing namespace std;\nusing namespace cnoid;\nusing namespace Eigen;\n\nclass ComJacobianPlugin : public Plugin\n{\npublic:\n    \n    ComJacobianPlugin() : Plugin(\"ComJacobianTest\")\n    {;\n        require(\"Body\");\n    }\n    \n    virtual bool initialize()\n    {\n        ToolBar* bar = new ToolBar(\"ComJacobianTest\");\n        bar->addButton(\"Increment\")\n            ->sigClicked().connect(bind(&ComJacobianPlugin::onButtonClicked, this, 0.02));\n        bar->addButton(\"Decrement\")\n                ->sigClicked().connect(bind(&ComJacobianPlugin::onButtonClicked, this, -0.02));\n        addToolBar(bar);\n\n        return true;\n    }\n\n    void onButtonClicked(double ref_com_pos)\n    {\n        ItemList<BodyItem> bodyItems =\n            ItemTreeView::mainInstance()->selectedItems<BodyItem>();\n\n\t\tconst double ik_gain = 0.5;\n\t\tconst int iteration = 100;\n\t\tconst double erreps = 1e-06;\n\t\tColPivHouseholderQR<MatrixXd> QR;\n\t\tconst double ik_lambda = 1.0e-12;\n\n\t\tBodyPtr robot = bodyItems[0]->body();\n\n\t\tJointPathPtr leg = getCustomJointPath(robot, robot->link(\"RLEG_ANKLE_R\"), robot->link(\"WAIST\"));\n\n\t\t// \u9806\u904b\u52d5\u5b66\u3067\u30ea\u30f3\u30af\u306e\u4f4d\u7f6e\u59ff\u52e2\u66f4\u65b0\n\t\trobot->calcForwardKinematics();\n\n\t\t// \u30ef\u30fc\u30eb\u30c9\u5ea7\u6a19\u7cfb\u306b\u304a\u3051\u308b\u91cd\u5fc3\u4f4d\u7f6e\u3092\u66f4\u65b0\n\t\tVector3d cur_com(robot->calcCenterOfMass());\n\t\tVector3d ref_com(cur_com);\n\t\tref_com.y() += ref_com_pos;\n\n\t\t// \u76ee\u6a19\u95a2\u7bc0\u89d2\u5ea6\u306e\u5dee\u5206\n\t\tVectorXd dq(robot->numJoints());\n\t\t// \u53ce\u675f\u30eb\u30fc\u30d7\n\t\tfor(int n=0;n<iteration;n++)\n\t\t{\n\t\t\tif(ref_com.dot(ref_com) < erreps) break;\n\t\t\t// \u91cd\u5fc3\u30e4\u30b3\u30d3\u30a2\u30f3\n\t\t\tMatrixXd J_com(3, robot->numJoints());\n\n\t\t\t// \u91cd\u5fc3\u30e4\u30b3\u30d3\u30a2\u30f3\u3092\u8a08\u7b97\n\t\t\tcalcCMJacobian(robot, leg->baseLink(), J_com);\n\n\t\t\tMatrixXd JJ = J_com * J_com.transpose() + ik_lambda*MatrixXd::Identity(J_com.rows(), J_com.rows());\n\t\t\tdq = J_com.transpose() * QR.compute(JJ).solve(ref_com - cur_com) * ik_gain;\n\t\t}\n        \n        for(size_t i=0; i < bodyItems.size(); ++i){\n            for(int j=0; j < robot->numJoints(); ++j)\n                robot->joint(j)->q() += dq[j];\n            bodyItems[i]->notifyKinematicStateChange(true);\n        }\n    }\n};\n\n\nCNOID_IMPLEMENT_PLUGIN_ENTRY(ComJacobianPlugin)\n", "meta": {"hexsha": "323fef7e68444abd3eff88e3a5f3c1dcb0e30910", "size": 2269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plugin/ComJacobianPlugin/ComJacobianPlugin.cpp", "max_stars_repo_name": "RyuYamamoto/ChoreonoidSample", "max_stars_repo_head_hexsha": "7e8ff3b7a5cc7d864ce13b4ca400ebcdcc2ef7e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plugin/ComJacobianPlugin/ComJacobianPlugin.cpp", "max_issues_repo_name": "RyuYamamoto/ChoreonoidSample", "max_issues_repo_head_hexsha": "7e8ff3b7a5cc7d864ce13b4ca400ebcdcc2ef7e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plugin/ComJacobianPlugin/ComJacobianPlugin.cpp", "max_forks_repo_name": "RyuYamamoto/ChoreonoidSample", "max_forks_repo_head_hexsha": "7e8ff3b7a5cc7d864ce13b4ca400ebcdcc2ef7e3", "max_forks_repo_licenses": ["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.0804597701, "max_line_length": 102, "alphanum_fraction": 0.6500661084, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5457087746223293}}
{"text": "\n#include <iostream>\n#include <array>\n#include <bitset>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n\nusing namespace boost::multiprecision::literals;\nusing boost::multiprecision::number;\nusing boost::multiprecision::backends::cpp_int_backend;\nusing boost::multiprecision::cpp_integer_type;\nusing boost::multiprecision::cpp_int_check_type;\n\nusing std::cout;\n\n#define BLS12_381_MODULUS_LEN 255\n#define GRAIN_LFSR_STATE_LEN 80\n\n\nBOOST_MP_DEFINE_SIZED_CPP_INT_LITERAL(BLS12_381_MODULUS_LEN);\nBOOST_MP_DEFINE_SIZED_CPP_INT_LITERAL(GRAIN_LFSR_STATE_LEN);\n\n\ntemplate<std::size_t t, std::size_t full_rounds, std::size_t part_rounds>\nstruct round_constants_generator {\n    constexpr static std::size_t modulus_bits = BLS12_381_MODULUS_LEN;\n    constexpr static std::size_t state_bits = GRAIN_LFSR_STATE_LEN;\n\n    typedef number<cpp_int_backend<modulus_bits, modulus_bits, cpp_integer_type::unsigned_magnitude, cpp_int_check_type::unchecked, void>>\n        integral_type;\n    typedef number<cpp_int_backend<state_bits, state_bits, cpp_integer_type::unsigned_magnitude, cpp_int_check_type::unchecked, void>>\n        state_type;\n\n    constexpr static integral_type mod = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001_cppui255;\n\n\n    constexpr void generate_round_constants() {\n        integral_type constant = 0x0_cppui255;\n        state_type lfsr_state = get_lfsr_init_state();\n\n        for (std::size_t i = 0; i < (full_rounds + part_rounds) * t; i++) {\n            while (true) {\n                constant = 0x0_cppui255;\n                for (std::size_t i = 0; i < modulus_bits; i++) {\n                    lfsr_state = update_state(lfsr_state);\n                    constant = set_new_bit<integral_type>(constant, get_state_bit(lfsr_state, state_bits - 1));\n                }\n                if (constant < 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001_cppui255) {\n                    constants[i] = constant;\n                    break;\n                }\n            }\n        }\n    }\n\n    constexpr void generate_round_constants_unfolded() {\n        integral_type constant = 0x0_cppui255;\n        bool new_bit = false;\n        state_type lfsr_state = get_lfsr_init_state();\n\n        for (std::size_t i = 0; i < (full_rounds + part_rounds) * t; i++) {\n            while (true) {\n                constant = 0x0_cppui255;\n                for (std::size_t i = 0; i < modulus_bits; i++) {\n                    while (true) {\n                        new_bit = ((lfsr_state & (0x1_cppui80 << (state_bits - 1))) != 0) !=\n                                  ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 13))) != 0) !=\n                                  ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 23))) != 0) !=\n                                  ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 38))) != 0) !=\n                                  ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 51))) != 0) !=\n                                  ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 62))) != 0);\n                        lfsr_state = (lfsr_state << 1) | (new_bit ? 1 : 0);\n                        if (new_bit)\n                            break;\n                        else {\n                            new_bit = ((lfsr_state & (0x1_cppui80 << (state_bits - 1))) != 0) !=\n                                      ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 13))) != 0) !=\n                                      ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 23))) != 0) !=\n                                      ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 38))) != 0) !=\n                                      ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 51))) != 0) !=\n                                      ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 62))) != 0);\n                            lfsr_state = (lfsr_state << 1) | (new_bit ? 1 : 0);\n                        }\n                    }\n                    new_bit = ((lfsr_state & (0x1_cppui80 << (state_bits - 1))) != 0) !=\n                              ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 13))) != 0) !=\n                              ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 23))) != 0) !=\n                              ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 38))) != 0) !=\n                              ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 51))) != 0) !=\n                              ((lfsr_state & (0x1_cppui80 << (state_bits - 1 - 62))) != 0);\n                    lfsr_state = (lfsr_state << 1) | (new_bit ? 1 : 0);\n                    constant = (constant << 1) | (lfsr_state & 1);\n                }\n                if (constant < 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001_cppui255) {\n                    constants[i] = constant;\n                    break;\n                }\n            }\n        }\n    }\n\n    constexpr static integral_type get_round_constant(std::size_t constant_number) {\n        integral_type constant = 0x0_cppui255;\n\n        state_type lfsr_state = get_lfsr_init_state();\n\n        // previous constants\n        for (std::size_t i = 0; i < constant_number; i++) {\n            constant = 0x0_cppui255;\n            while (true) {\n                constant = 0x0_cppui255;\n                for (std::size_t i = 0; i < modulus_bits; i++) {\n                    lfsr_state = update_state(lfsr_state);\n                    constant = set_new_bit<integral_type>(constant, get_state_bit(lfsr_state, state_bits - 1));\n                }\n                if (constant < 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001_cppui255)\n                    break;\n            }\n        }\n\n        // requested constant\n        while (true) {\n            constant = 0x0_cppui255;\n            for (std::size_t i = 0; i < modulus_bits; i++) {\n                lfsr_state = update_state(lfsr_state);\n                constant = set_new_bit<integral_type>(constant, get_state_bit(lfsr_state, state_bits - 1));\n            }\n            if (constant < 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001_cppui255)\n                break;\n        }\n\n        return constant;\n    }\n\n    constexpr static state_type get_lfsr_init_state() {\n        state_type state = 0x0_cppui80;\n        int i = 0;\n        for (i = 1; i >= 0; i--)\n            state = set_new_bit(state, (1 >> i) & 1); // field - as in filecoin\n        for (i = 3; i >= 0; i--)\n            state = set_new_bit(state, (1 >> i) & 1); // s-box - as in filecoin\n        for (i = 11; i >= 0; i--)\n            state = set_new_bit(state, (modulus_bits >> i) & 1);\n        for (i = 11; i >= 0; i--)\n            state = set_new_bit(state, (t >> i) & 1);\n        for (i = 9; i >= 0; i--)\n            state = set_new_bit(state, (full_rounds >> i) & 1);\n        for (i = 9; i >= 0; i--)\n            state = set_new_bit(state, (part_rounds >> i) & 1);\n        for (i = 29; i >= 0; i--)\n            state = set_new_bit(state, 1);\n        // idling\n        for (i = 0; i < 160; i++)\n            state = update_state_raw(state);\n        return state;\n    }\n\n    constexpr static state_type update_state(state_type state) {\n        while (true) {\n            state = update_state_raw(state);\n            if (get_state_bit(state, state_bits - 1))\n                break;\n            else\n                state = update_state_raw(state);\n        }\n        return update_state_raw(state);\n    }\n\n    constexpr static state_type update_state_raw(state_type state) {\n        bool new_bit = get_state_bit(state, 0) != get_state_bit(state, 13) != get_state_bit(state, 23) !=\n                       get_state_bit(state, 38) != get_state_bit(state, 51) != get_state_bit(state, 62);\n        return set_new_bit(state, new_bit);\n    }\n\n    constexpr static bool get_state_bit(state_type state, std::size_t pos) {\n        state_type bit_getter = 0x1_cppui80;\n        bit_getter <<= (state_bits - 1 - pos);\n        return (state & bit_getter) ? true : false;\n    }\n\n    template<typename T>\n    constexpr static T set_new_bit(T var, bool new_bit) {\n        return (var << 1) | (new_bit ? 1 : 0);\n    }\n\n    constexpr round_constants_generator() : constants() {\n        // generate_round_constants();\n        generate_round_constants_unfolded();\n        \n    }\n\n    integral_type constants[(full_rounds + part_rounds) * t];\n\n};\n\n\nint main() {\n    constexpr std::size_t width = 4;\n    constexpr std::size_t full_rounds = 8;\n    constexpr std::size_t part_rounds = 56;\n    typedef round_constants_generator<width, full_rounds, part_rounds> rcg;\n    \n    // Add option -fconstexpr-ops-limit=4294967296 to compiler\n    constexpr rcg gen;\n    for (std::size_t i = 0; i < (8 + 56) * 4; i++)\n        cout << gen.constants[i] << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "cbdab3963f9230727bca73aa3caefaa793b2a6ae", "size": 8782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tmp_poseidon_constexpr_generation.cpp", "max_stars_repo_name": "JasonCoombs/crypto3-hash", "max_stars_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "max_stars_repo_licenses": ["MIT"], "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/tmp_poseidon_constexpr_generation.cpp", "max_issues_repo_name": "JasonCoombs/crypto3-hash", "max_issues_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T23:11:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T00:09:30.000Z", "max_forks_repo_path": "test/tmp_poseidon_constexpr_generation.cpp", "max_forks_repo_name": "JasonCoombs/crypto3-hash", "max_forks_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-11T15:35:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-11T15:35:55.000Z", "avg_line_length": 41.6208530806, "max_line_length": 138, "alphanum_fraction": 0.5413345479, "num_tokens": 2425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171069, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5457087709534584}}
{"text": "#define BOOST_TEST_MODULE binary_number_test\n\n#include <boost/test/included/unit_test.hpp>\n\n#include \"genetic_algorithm/genetic_algorithm.h\"\n\nBOOST_AUTO_TEST_CASE(test) {\n\n  using namespace gaus;\n\n  const int target = 27;\n\n  const std::function<double(arma::uvec)> fitness_function =\n      [&target](const arma::uvec & genes) {\n\n        const auto powers_of_two = arma::uvec{32, 16, 8, 4, 2, 1};\n\n        const int strength = arma::accu(powers_of_two % genes);\n\n        std::cout << \"strength \" << strength << std::endl;\n        genes.t().print(\"genes\");\n\n        return std::abs(strength - target);\n      };\n\n  const auto solution =\n      genetic_algorithm::find_solution(fitness_function, 20, arma::SizeMat{6, 1}, 0.8, 0.1);\n\n  const arma::uvec answer = {0, 1, 1, 0, 1, 1};\n\n  BOOST_TEST(arma::approx_equal(solution.genes, answer, \"absdiff\", 0));\n\n}", "meta": {"hexsha": "1bd1fc5e4568debb691fa70eb54205da1248a479", "size": 851, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/run/binary_number_test.cpp", "max_stars_repo_name": "Oliver-Feighan/ga_underground_maps", "max_stars_repo_head_hexsha": "637a7f59e23b045ffb58e8baa8a336833eb3377c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/run/binary_number_test.cpp", "max_issues_repo_name": "Oliver-Feighan/ga_underground_maps", "max_issues_repo_head_hexsha": "637a7f59e23b045ffb58e8baa8a336833eb3377c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/run/binary_number_test.cpp", "max_forks_repo_name": "Oliver-Feighan/ga_underground_maps", "max_forks_repo_head_hexsha": "637a7f59e23b045ffb58e8baa8a336833eb3377c", "max_forks_repo_licenses": ["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.7878787879, "max_line_length": 92, "alphanum_fraction": 0.6568742656, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5457071563281937}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2013 Alec Jacobson <alecjacobson@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 \"bone_heat.h\"\n#include \"EmbreeIntersector.h\"\n#include \"bone_visible.h\"\n#include \"../project_to_line_segment.h\"\n#include \"../cotmatrix.h\"\n#include \"../massmatrix.h\"\n#include \"../mat_min.h\"\n#include <Eigen/Sparse>\n\nbool igl::embree::bone_heat(\n  const Eigen::MatrixXd & V,\n  const Eigen::MatrixXi & F,\n  const Eigen::MatrixXd & C,\n  const Eigen::VectorXi & P,\n  const Eigen::MatrixXi & BE,\n  const Eigen::MatrixXi & CE,\n  Eigen::MatrixXd & W)\n{\n  using namespace std;\n  using namespace Eigen;\n  assert(CE.rows() == 0 && \"Cage edges not supported.\");\n  assert(C.cols() == V.cols() && \"V and C should have same #cols\");\n  assert(BE.cols() == 2 && \"BE should have #cols=2\");\n  assert(F.cols() == 3 && \"F should contain triangles.\");\n  assert(V.cols() == 3 && \"V should contain 3D positions.\");\n\n  const int n = V.rows();\n  const int np = P.rows();\n  const int nb = BE.rows();\n  const int m = np + nb;\n\n  // \"double sided lighting\"\n  MatrixXi FF;\n  FF.resize(F.rows()*2,F.cols());\n  FF << F, F.rowwise().reverse();\n  // Initialize intersector\n  EmbreeIntersector ei;\n  ei.init(V.cast<float>(),F.cast<int>());\n\n  typedef Matrix<bool,Dynamic,1> VectorXb;\n  typedef Matrix<bool,Dynamic,Dynamic> MatrixXb;\n  MatrixXb vis_mask(n,m);\n  // Distances\n  MatrixXd D(n,m);\n  // loop over points\n  for(int j = 0;j<np;j++)\n  {\n    const Vector3d p = C.row(P(j));\n    D.col(j) = (V.rowwise()-p.transpose()).rowwise().norm();\n    VectorXb vj;\n    bone_visible(V,F,ei,p,p,vj);\n    vis_mask.col(j) = vj;\n  }\n\n  // loop over bones\n  for(int j = 0;j<nb;j++)\n  {\n    const Vector3d s = C.row(BE(j,0));\n    const Vector3d d = C.row(BE(j,1));\n    VectorXd t,sqrD;\n    project_to_line_segment(V,s,d,t,sqrD);\n    D.col(np+j) = sqrD.array().sqrt();\n    VectorXb vj;\n    bone_visible(V,F,ei,s,d,vj);\n    vis_mask.col(np+j) = vj;\n  }\n\n  if(CE.rows() > 0)\n  {\n    cerr<<\"Error: Cage edges are not supported. Ignored.\"<<endl;\n  }\n\n  MatrixXd PP = MatrixXd::Zero(n,m);\n  VectorXd min_D;\n  VectorXd Hdiag = VectorXd::Zero(n);\n  VectorXi J;\n  mat_min(D,2,min_D,J);\n  for(int i = 0;i<n;i++)\n  {\n    PP(i,J(i)) = 1;\n    if(vis_mask(i,J(i)))\n    {\n      double hii = pow(min_D(i),-2.); \n      Hdiag(i) = (hii>1e10?1e10:hii);\n    }\n  }\n  SparseMatrix<double> Q,L,M;\n  cotmatrix(V,F,L);\n  massmatrix(V,F,MASSMATRIX_TYPE_DEFAULT,M);\n  const auto & H = Hdiag.asDiagonal();\n  Q = (-L+M*H);\n  SimplicialLLT <SparseMatrix<double > > llt;\n  llt.compute(Q);\n  switch(llt.info())\n  {\n    case Eigen::Success:\n      break;\n    case Eigen::NumericalIssue:\n      cerr<<\"Error: Numerical issue.\"<<endl;\n      return false;\n    default:\n      cerr<<\"Error: Other.\"<<endl;\n      return false;\n  }\n\n  const auto & rhs = M*H*PP;\n  W = llt.solve(rhs);\n  return true;\n}\n", "meta": {"hexsha": "8a85af98cf3b564014da36700c085568986f1581", "size": 3060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/embree/bone_heat.cpp", "max_stars_repo_name": "aviadtzemah/animation2", "max_stars_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "igl/embree/bone_heat.cpp", "max_issues_repo_name": "aviadtzemah/animation2", "max_issues_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "igl/embree/bone_heat.cpp", "max_forks_repo_name": "aviadtzemah/animation2", "max_forks_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 26.1538461538, "max_line_length": 78, "alphanum_fraction": 0.6183006536, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5457071444042465}}
{"text": "#include \"average_case_error.hpp\"\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <cudd_helpers.hpp>\n\nusing abo::util::NumberRepresentation;\nusing boost::multiprecision::cpp_dec_float_100;\nusing boost::multiprecision::uint256_t;\n\nnamespace abo::error_metrics {\n\ncpp_dec_float_100 average_value(const std::vector<BDD>& f)\n{\n\n    uint256_t sum = 0;\n    const uint256_t one = 1;\n\n    int max_support_size = 0;\n    for (const auto& bdd : f)\n    {\n        max_support_size = std::max(max_support_size, bdd.SupportSize());\n    }\n\n    for (unsigned int i = 0; i < f.size(); i++)\n    {\n        // TODO: CountMinterms returns a double, might loose precision\n        double minterms = f[i].CountMinterm(max_support_size);\n        sum += (one << i) * uint256_t(minterms);\n    }\n\n    return cpp_dec_float_100(sum) /\n           cpp_dec_float_100(one << max_support_size);\n}\n\ncpp_dec_float_100 mean_squared_value(const std::vector<BDD>& f)\n{\n\n    uint256_t sum = 0;\n    const uint256_t one = 1;\n\n    int max_support_size = 0;\n    for (const auto& bdd : f)\n    {\n        max_support_size = std::max(max_support_size, bdd.SupportSize());\n    }\n\n    for (unsigned int i = 0; i < f.size(); i++)\n    {\n        for (unsigned int b = i; b < f.size(); b++)\n        {\n            // cudd handles the case i = b efficiently\n            BDD both = f[i] & f[b];\n            double minterms = both.CountMinterm(max_support_size);\n            // most terms (except for i == b), appear twice when factoring the square\n            uint256_t doubling_factor = i == b ? 1 : 2;\n            sum += (one << i) * (one << b) * uint256_t(minterms) *\n                   doubling_factor;\n        }\n    }\n\n    return cpp_dec_float_100(sum) /\n           cpp_dec_float_100(one << max_support_size);\n}\n\ncpp_dec_float_100\naverage_case_error(const Cudd& mgr, const std::vector<BDD>& f,\n                   const std::vector<BDD>& f_hat,\n                   const util::NumberRepresentation num_rep)\n{\n\n    std::vector<BDD> absolute_difference =\n        abo::util::bdd_absolute_difference(mgr, f, f_hat, num_rep);\n    return average_value(absolute_difference);\n}\n\ncpp_dec_float_100\nmean_squared_error(const Cudd& mgr, const std::vector<BDD>& f,\n                   const std::vector<BDD>& f_hat,\n                   const util::NumberRepresentation num_rep)\n{\n\n    std::vector<BDD> absolute_difference =\n        abo::util::bdd_absolute_difference(mgr, f, f_hat, num_rep);\n    return mean_squared_value(absolute_difference);\n}\n\ncpp_dec_float_100 average_case_error_add(const Cudd& mgr,\n                                        const std::vector<BDD>& f,\n                                        const std::vector<BDD>& f_hat,\n                                        const NumberRepresentation num_rep)\n{\n\n    ADD diff = abo::util::absolute_difference_add(mgr, f, f_hat, num_rep);\n    std::vector<std::pair<double, unsigned long>> terminal_values =\n        abo::util::add_terminal_values(diff);\n\n    uint256_t sum = 0;\n    uint256_t path_sum = 0;\n    for (auto p : terminal_values)\n    {\n        sum += uint256_t(p.first) * p.second;\n        path_sum += p.second;\n    }\n    return cpp_dec_float_100(sum) /\n           cpp_dec_float_100(path_sum);\n}\n\ncpp_dec_float_100 mean_squared_error_add(const Cudd& mgr,\n                                        const std::vector<BDD>& f,\n                                        const std::vector<BDD>& f_hat,\n                                        const NumberRepresentation num_rep)\n{\n\n    ADD diff = abo::util::absolute_difference_add(mgr, f, f_hat, num_rep);\n    std::vector<std::pair<double, unsigned long>> terminal_values =\n        abo::util::add_terminal_values(diff);\n\n    uint256_t sum = 0;\n    uint256_t path_sum = 0;\n    for (auto p : terminal_values)\n    {\n        uint256_t value(p.first);\n        sum += value * value * p.second;\n        path_sum += p.second;\n    }\n    return cpp_dec_float_100(sum) /\n           cpp_dec_float_100(path_sum);\n}\n\n} // namespace abo::error_metrics\n", "meta": {"hexsha": "a6dd013c162ec7e86f2d02de7c5be46f5110451a", "size": 3981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/error_metrics/average_case_error.cpp", "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/error_metrics/average_case_error.cpp", "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/error_metrics/average_case_error.cpp", "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": 30.3893129771, "max_line_length": 85, "alphanum_fraction": 0.6028636021, "num_tokens": 988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5457071444042465}}
{"text": "#define BOOST_TEST_MODULE graphing_test\n\n#include <boost/test/included/unit_test.hpp>\n\n#include \"underground_modelling/graphing.h\"\n\nBOOST_AUTO_TEST_SUITE( graphing_tests )\n\nBOOST_AUTO_TEST_CASE( graph ){\n\n  using namespace gaus::underground_modelling;\n\n  const arma::umat adjacency =\n      {{0, 1, 1},\n       {1, 0, 0},\n       {1, 0, 0}};\n\n  const Graph graph = make_graph(adjacency);\n\n  BOOST_TEST(boost::num_edges(graph) == 4);\n  BOOST_TEST(boost::num_vertices(graph) == 3);\n\n}\n\nBOOST_AUTO_TEST_CASE( cost ){\n\n  using namespace gaus::underground_modelling;\n\n  const arma::umat adjacency =\n      {{0, 1},\n       {1, 0}\n      };\n\n\n  const StationCoordinates s_coords =\n      {{0, 1},\n       {0, 0}\n      };\n\n\n  const auto cost = calculate_cost(adjacency, s_coords, {0.5, 0.2});\n\n  BOOST_TEST(cost == 0.7);\n}\n\nBOOST_AUTO_TEST_CASE( terminal_stations ){\n\n  using namespace gaus::underground_modelling;\n\n  const arma::umat adjacency =\n      {{0, 0},\n       {0, 0}\n      };\n\n  const auto f_terminal = find_terminal_stations(adjacency);\n\n  std::cout << \"f_terminal \" << f_terminal << std::endl;\n\n  BOOST_TEST(f_terminal == 2);\n}\n\n\nBOOST_AUTO_TEST_CASE( connectivity ){\n  using namespace gaus::underground_modelling;\n\n  const arma::umat adjacency =\n      {{0, 1, 0, 0},\n       {1, 0, 0, 0},\n       {0, 0, 0, 1},\n       {0, 0, 1, 0},\n      };\n\n  const double connectivity = check_connectivity(adjacency);\n\n  std::cout << \"connectivity \" << connectivity << std::endl;\n\n  BOOST_TEST(connectivity == 2);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "35328b90fa164d334d6d54e768cfb179ad0ec44b", "size": 1524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/underground_modelling/graphing_test.cpp", "max_stars_repo_name": "Oliver-Feighan/ga_underground_maps", "max_stars_repo_head_hexsha": "637a7f59e23b045ffb58e8baa8a336833eb3377c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/underground_modelling/graphing_test.cpp", "max_issues_repo_name": "Oliver-Feighan/ga_underground_maps", "max_issues_repo_head_hexsha": "637a7f59e23b045ffb58e8baa8a336833eb3377c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/underground_modelling/graphing_test.cpp", "max_forks_repo_name": "Oliver-Feighan/ga_underground_maps", "max_forks_repo_head_hexsha": "637a7f59e23b045ffb58e8baa8a336833eb3377c", "max_forks_repo_licenses": ["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.05, "max_line_length": 68, "alphanum_fraction": 0.6404199475, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5457071369840015}}
{"text": "\ufeff/*\r\n * Copyright (c) 2007-2010 Tao Wang <dancefire@gmail.org>\r\n * See the file \"LICENSE.txt\" for usage and redistribution license requirements\r\n *\r\n *\t$Id$\r\n */\r\n#pragma once\r\n#ifndef _OPENCLAS_K_SHORTEST_PATH_HPP_\r\n#define _OPENCLAS_K_SHORTEST_PATH_HPP_\r\n\r\n//\tworkaround for remove VC min(a,b) macro function definition,\r\n//\twhich is make std::min() not working.\r\n#if defined(_MSC_VER) && defined(min)\r\n#undef min\r\n#endif\t//\tmin\r\n\r\n#include \"common.hpp\"\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/graph_concepts.hpp>\r\n#include <boost/graph/dag_shortest_paths.hpp>\r\n#include <list>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nnamespace openclas {\r\n\r\n\tusing namespace boost;\r\n\r\n\tstruct path_type {\r\n\t\tdouble weight;\r\n\t\tstd::vector<size_t> nodelist;\r\n\t\tpath_type()\r\n\t\t\t: weight(0), nodelist()\r\n\t\t{}\r\n\t};\r\n\r\n\tinline bool operator < (const path_type& left, const path_type& right)\r\n\t{\r\n\t\treturn left.weight < right.weight;\r\n\t}\r\n\r\n\t//\tFind all paths of given pair of node in a DAG. (DFS-like algorithm)\r\n\ttemplate <class IncidenceGraph>\r\n\tvoid dag_all_paths(IncidenceGraph& g, \r\n\t\ttypename graph_traits<IncidenceGraph>::vertex_descriptor begin, \r\n\t\ttypename graph_traits<IncidenceGraph>::vertex_descriptor end,\r\n\t\tstd::vector<path_type>& result_paths,\r\n\t\tpath_type current_path = path_type())\r\n\t{\r\n\t\tfunction_requires<IncidenceGraphConcept<IncidenceGraph> >();\r\n\r\n\t\tif (num_vertices(g) == 0)\r\n\t\t\treturn;\t//\treturn if g is empty\r\n\r\n\t\tcurrent_path.nodelist.push_back(begin);\r\n\t\tif (begin == end) {\r\n\t\t\tresult_paths.push_back(current_path);\r\n\t\t} else {\r\n\t\t\ttypename graph_traits<IncidenceGraph>::out_edge_iterator ei, ei_end;\r\n\t\t\ttypename property_map<IncidenceGraph, edge_weight_t>::type\r\n\t\t\t\tw_map = get(edge_weight, g);\r\n\t\t\tdouble original_weight = current_path.weight;\r\n\t\t\tfor (tie(ei, ei_end) = out_edges(begin, g); ei != ei_end; ++ei) {\r\n\t\t\t\ttypename graph_traits<IncidenceGraph>::vertex_descriptor v = target(*ei, g);\r\n\t\t\t\tcurrent_path.weight = original_weight + w_map[edge(begin, v, g).first];\r\n\t\t\t\tdag_all_paths(g, v, end, result_paths, current_path);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t//\tFind k-shortest-path in DAG.\r\n\ttemplate <class IncidenceGraph>\r\n\tvoid dag_k_shortest_paths(IncidenceGraph& g, \r\n\t\ttypename graph_traits<IncidenceGraph>::vertex_descriptor begin, \r\n\t\ttypename graph_traits<IncidenceGraph>::vertex_descriptor end,\r\n\t\tstd::vector<path_type>& result_paths,\r\n\t\tint k)\r\n\t{\r\n\t\tif (num_vertices(g) == 0)\r\n\t\t\treturn;\t//\treturn if g is empty\r\n\r\n\t\tif (k == 1) {\r\n\t\t\tpath_type shortest_path;\r\n\t\t\tdag_shortest_path(g, begin, end, shortest_path);\r\n\t\t\tresult_paths.push_back(shortest_path);\r\n\t\t}else{\r\n\t\t\tstd::vector<path_type> candidate_paths;\r\n\t\t\tdag_all_paths(g, begin, end, candidate_paths);\r\n\r\n\t\t\tk = std::min(k, static_cast<int>(candidate_paths.size()));\r\n\t\t\tstd::partial_sort(candidate_paths.begin(), candidate_paths.begin() + k, candidate_paths.end());\r\n\t\t\tresult_paths.assign(candidate_paths.begin(), candidate_paths.begin() + k);\r\n\t\t}\r\n\t}\r\n\r\n\t//\tFind shortest-path in DAG. O(n+m)\r\n\ttemplate <class Graph>\r\n\tvoid dag_shortest_path(Graph& g, \r\n\t\ttypename graph_traits<Graph>::vertex_descriptor begin, \r\n\t\ttypename graph_traits<Graph>::vertex_descriptor end,\r\n\t\tpath_type& result_path)\r\n\t{\r\n\t\tif (num_vertices(g) == 0)\r\n\t\t\treturn;\t//\treturn if g is empty\r\n\r\n\t\ttypename property_map<Graph, vertex_distance_t>::type\r\n\t\t\td_map = get(vertex_distance, g);\r\n\t\ttypename property_map<Graph, vertex_predecessor_t>::type\r\n\t\t\tp_map = get(vertex_predecessor, g);\r\n\r\n\t\tif (begin == end) {\r\n\t\t\tresult_path.nodelist.push_back(begin);\r\n\t\t} else {\r\n\t\t\tdag_shortest_paths(g, begin, distance_map(d_map).predecessor_map(p_map));\r\n\r\n\t\t\tif (end == p_map[end])\t//\t[begin] is not connected with [end]\r\n\t\t\t\treturn;\r\n\r\n\t\t\tresult_path.weight = d_map[end];\r\n\t\t\tresult_path.nodelist.push_back(end);\r\n\r\n\t\t\tsize_t current = end;\r\n\t\t\twhile(current != begin)\r\n\t\t\t{\r\n\t\t\t\tcurrent = p_map[current];\r\n\t\t\t\tresult_path.nodelist.push_back(current);\r\n\t\t\t}\r\n\t\t\tstd::reverse(result_path.nodelist.begin(), result_path.nodelist.end());\r\n\t\t}\r\n\t}\r\n}\r\n\r\n//\t_OPENCLAS_K_SHORTEST_PATH_HPP_\r\n#endif\r\n", "meta": {"hexsha": "4ac5ed1386680404e16c8f0c2d1adb8decc8fdb5", "size": 4070, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/include/openclas/k_shortest_path.hpp", "max_stars_repo_name": "dancefire/openclas", "max_stars_repo_head_hexsha": "af15aad1891cb7e597dfe9dbc92dbd91093d613e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/include/openclas/k_shortest_path.hpp", "max_issues_repo_name": "dancefire/openclas", "max_issues_repo_head_hexsha": "af15aad1891cb7e597dfe9dbc92dbd91093d613e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/include/openclas/k_shortest_path.hpp", "max_forks_repo_name": "dancefire/openclas", "max_forks_repo_head_hexsha": "af15aad1891cb7e597dfe9dbc92dbd91093d613e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1481481481, "max_line_length": 99, "alphanum_fraction": 0.6992628993, "num_tokens": 1049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5456255642955368}}
{"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#include <cmath>\n#include <gtest/gtest.h>\n#include <boost/math/differentiation/autodiff.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"ising/mp_wrapper.hpp\"\n#include \"ising/free_energy/common.hpp\"\n#include \"ising/free_energy/square.hpp\"\n\nusing namespace boost::multiprecision;\nusing namespace ising::free_energy;\n\nTEST(IsingFreeEnergy, SquareCount0) {\n  typedef double real_t;\n  unsigned Lx = 4;\n  unsigned Ly = 4;\n  auto Jx = convert<real_t>(\"1.5\");\n  auto Jy = convert<real_t>(\"2.5\");\n  auto t = convert<real_t>(\"2\");\n  auto vars = boost::math::differentiation::make_ftuple<real_t, 2, 2>(1 / t, 0);\n  auto& beta = std::get<0>(vars);\n  auto& h = std::get<1>(vars);\n  auto f = square::finite_count(Lx, Ly, Jx, Jy, beta, h);\n  EXPECT_DOUBLE_EQ(-4.087359662653047e+00, free_energy(f, beta, h));\n  EXPECT_DOUBLE_EQ(-3.994108759068211e+00, energy(f, beta, h));\n  EXPECT_DOUBLE_EQ(2.452622208849045e-02, specific_heat(f, beta, h));\n  EXPECT_DOUBLE_EQ(1.597700713244840e+01, magnetization2(f, beta, h));\n}\n", "meta": {"hexsha": "05c28a7669c3c92f031395703d0d174ff8660ad3", "size": 1648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ising/free_energy/square_count_gt.cpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "ising/free_energy/square_count_gt.cpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "ising/free_energy/square_count_gt.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": 37.4545454545, "max_line_length": 80, "alphanum_fraction": 0.7281553398, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5455878544768582}}
{"text": "/* Copyright (c) 2018, Skolkovo Institute of Science and Technology (Skoltech)\n * All rights reserved.\n *\n * See LICENSE file in the root of the mrob library.\n *\n *\n * planeRegistration.hpp\n *\n *  Created on: Jan 28, 2019\n *      Author: Gonzalo Ferrer\n *              g.ferrer@skoltech.ru\n *              Mobile Robotics Lab, Skoltech\n */\n\n#ifndef PLANEREGISTRATION_HPP_\n#define PLANEREGISTRATION_HPP_\n\n#include <vector>\n#include \"mrob/SE3.hpp\"\n#include <Eigen/StdVector>\n#include \"mrob/plane.hpp\"\n#include \"mrob/optimizer.hpp\"\n\n#include <unordered_map>\n#include <memory>\n\n\nnamespace mrob{\n\n/**\n * class PlaneRegistration introduced a class for the alignment of\n * planes.\n */\nclass PlaneRegistration: public Optimizer{\n\n  public:\n    // XXX is this mode used anymore? deprecated?\n    enum TrajectoryMode{SEQUENCE=0, INTERPOLATION};\n    // XXX Solve method is almost deprecated\n    //enum SolveModeGrad{GRADIENT_DESCENT_NAIVE=0, GRADIENT_DESCENT_INCR, STEEPEST, HEAVYBALL, MOMENTUM, MOMENTUM_SEQ, BENGIOS_NAG, GRADIENT_DESCENT_BACKTRACKING, BFGS};\n    enum SolveMode{INITIALIZE=0,\n                   GRADIENT,\n                   GRADIENT_BENGIOS_NAG,\n                   GN_HESSIAN,\n                   GN_CLAMPED_HESSIAN,\n                   LM_SPHER,\n                   LM_ELLIP};\n\n  public:\n    PlaneRegistration();\n    //PlaneRegistration(uint_t numberPlanes , uint_t numberPoses);\n    ~PlaneRegistration();\n\n    // Function from the parent class Optimizer\n    virtual matData_t calculate_error() override;\n    virtual void calculate_gradient_hessian() override;\n    virtual void update_state(const MatX1 &dx) override;\n    virtual void bookkeep_state() override;\n    virtual void update_state_from_bookkeep() override;\n\n\n    // Specific methods\n    void set_number_planes_and_poses(uint_t numPlanes, uint_t numPoses);\n    uint_t get_number_planes() const {return numberPlanes_;};\n    uint_t get_number_poses() const {return numberPoses_;};\n\n    /**\n     * solve() calculates the poses on trajectory such that the minimization objective\n     * is met: J = sum (lamda_min_plane)\n     */\n    uint_t solve(SolveMode mode, bool singleIteration = false);\n    /**\n     * solve_interpolate() calculates the poses on trajectory such that the minimization objective\n     * is met: J = sum (lamda_min_plane), and the trajectory is described as an interpolation from I to T_f\n     */\n    uint_t solve_interpolate_gradient(bool singleIteration = false);\n    /**\n     * solve_interpolate_hessian() calculates the poses on trajectory such that the minimization objective\n     * is met: J = sum (lamda_min_plane), and the trajectory is described as an interpolation from I to T_f\n     * using second order methods with Hessian. Very similar to solve_interpolate\n     */\n    uint_t solve_interpolate_hessian(bool singleIteration = false);\n    /**\n     * Initialization_solve give a first guess on all poses by using classical point-point\n     * methods SVD-based to calculate an initial condition closer to the true solution\n     */\n    uint_t solve_initialize();\n    /**\n     * Solve quaternion plane uses a paramteric representation for each plane, a quaternion,\n     * and optimizes both the plane parameters and the trajectory variables\n     */\n    uint_t solve_quaternion_plane();\n    /**\n     * reset_solution, resets the current calculated solution while maintainting all data (planes)\n     * This function is intended for comparing different solvers without replicating data\n     */\n    void reset_solution();\n    double get_current_error() const;\n    /**\n     * Get trajectory returns a smart pointer to the vector of transformations,\n     * which is already shared by all Plane objects.\n     * It serves for checking the solution and for modifying the initial conditions for optimization (if any).\n     */\n    //std::shared_ptr<std::vector<SE3>>& get_trajectory() {return trajectory_;};//if solved\n    Mat4 get_trajectory(uint_t time);\n\n    /**\n     * add_plane adds a plane structure already initialized and filled with data\n     */\n    void add_plane(uint_t id, std::shared_ptr<Plane> &plane);\n    std::shared_ptr<Plane> & get_plane(uint_t id);\n\n    std::unordered_map<uint_t, std::shared_ptr<Plane>>& get_all_planes() {return planes_;};\n\n    void set_alpha_parameter(double alpha) {alpha_ = alpha;};\n    void set_beta_parameter(double beta) {beta_ = beta;};\n\n    double calculate_poses_rmse(std::vector<SE3> & groundTruth) const;\n\n    void print(bool plotPlanes = true) const;\n\n    /**\n     * print evaluate looks for degenerate cases, such as planes normal vectors,\n     * Hessian rank, det of all normals, etc. Basically this function tries to answer\n     * if the problem is ill-conditioned\n     *\n     * Returns: 0) current error\n     *          1) number of iters,\n     *          2) determinant\n     *          3) number of negative eigenvalues\n     *          4) conditioning number\n     */\n    std::vector<double> print_evaluate();\n\n    /**\n     * add point_cloud requires a complete set of points observed at a given time\n     * stamp (XXX now only an integer) and fills in the registration structure.\n     */\n    void add_point_cloud_planes(uint_t time, std::vector<Mat31>& points, std::vector<uint_t>& point_ids);\n    /**\n     * get_point_cloud gets all raw point, according to the current time index\n     * from trajectory. It does not distinguish between planes.\n     */\n    std::vector<Mat31> get_point_cloud(uint_t time);\n    std::vector<Mat31> get_point_plane_ids(uint_t time);\n\n  protected:\n    // flag for detecting when is has been solved\n    uint_t numberPlanes_, numberPoses_;\n    uint_t isSolved_;\n    PlaneRegistration::TrajectoryMode trajMode_;\n    uint_t time_;\n    std::unordered_map<uint_t, std::shared_ptr<Plane>> planes_;\n    std::shared_ptr<std::vector<SE3>> trajectory_;\n    SE3 bookept_trajectory_;//last pose is stored/bookept\n    double tau_;//variable for weighting the number of poses in traj\n    uint_t solveIters_;\n\n    // 1st order parameters methods if used\n    PlaneRegistration::SolveMode solveMode_;\n    std::vector<Mat61> previousState_;\n    double c1_, c2_;    //parameters for the Wolfe conditions DEPRECATED?\n    double alpha_, beta_;\n\n\n    //2nd order data (if used) TODO remove since they are defined in parent class\n    Mat61 gradient__;\n    Mat6 hessian__;\n\n};\n\n\n\n}// namespace\n#endif /* PLANEREGISTRATION_HPP_ */\n", "meta": {"hexsha": "1936fd3bad8a42504fbe71d3e69c7ec8f39439c6", "size": 6364, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/PCRegistration/mrob/plane_registration.hpp", "max_stars_repo_name": "anastasiia-kornilova/mrob", "max_stars_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-10T09:36:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-10T09:36:50.000Z", "max_issues_repo_path": "src/PCRegistration/mrob/plane_registration.hpp", "max_issues_repo_name": "anastasiia-kornilova/mrob", "max_issues_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PCRegistration/mrob/plane_registration.hpp", "max_forks_repo_name": "anastasiia-kornilova/mrob", "max_forks_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "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.1590909091, "max_line_length": 169, "alphanum_fraction": 0.7000314268, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5455878491963294}}
{"text": "#include <boost/math/special_functions/cbrt.hpp>\n", "meta": {"hexsha": "897ea2af2c325d2d23a6e6581f73e40bce89a9a3", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_cbrt.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_cbrt.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_cbrt.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8163265306, "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5455878435274347}}
{"text": "#include <matrixlib/MatrixUtils.h>\n#include <NTL/vec_GF2.h>\n\nvoid random(NTL::mat_GF2 &L, int n1, int n2)\n{\n\tL.SetDims(n1,n2);\n\tint hw;\n\tfor (int i = 0; i < n1; i++)\n\t{\n\t\tdo\n\t    \t{\n\t    \t\thw = 0;\n\t\t\t\tfor (int j = 0; j < n2; j++)\n\t\t\t\t{\n\t\t\t\t\tL[i][j] = NTL::random_GF2();\n\t\t\t\t\tif (L[i][j] == 1)\n\t\t\t            hw += 1;\n\t\t\t\t}\n\t\t\t} while (hw == 1);\n\t}\n}\nint initMatrixFromBit(NTL::mat_GF2 &M, long *data) {\n    long i,j,n,m;\n\tfor(i=0, n=M.NumRows(); i<n; i++){\n\t\tlong t = *data;\n\t\tfor(j=M.NumCols()-1; j>=0; j--){\n\t\t\tM.put(i,j,t%2);\n\t\t\tt >>= 1;\n\t\t}\n\t\tdata++;\n\t}\n\n\treturn 0;\n}\n\nint initVecFromBit(NTL::vec_GF2 &M, long data, int len) {\n\tM.SetLength(len);\n    long i,j,n,m;\n\tfor(i=len-1; i>=0; i--){\n\t\tM.put(i, data%2);\n\t\tdata >>=1;\n\t}\n\treturn 0;\n}\nint genRandomAffineAugmentedMatrix(NTL::mat_GF2 &X,  NTL::mat_GF2 &Y, int n) {\n\tNTL::mat_GF2 L;\n\trandom(L, n, n);\n\twhile(determinant(L)==0) {\n\t\trandom(L, n, n);\n\t}\n\tNTL::mat_GF2 LINV = inv(L);\n\tNTL::vec_GF2 tran;\n\t// tran.SetLength(m);\n\trandom(tran, n);\n\tNTL::mat_GF2 AugmentedMatrix;\n\n\tX.SetDims(n+1, n+1);\n\tint i,j;\n\tfor (i=0; i<n; i++) {\n\t\tfor ( j=0; j<n; j++) {\n\t\t\tX.put(i,j, L.get(i, j));\n\t\t}\n\t}\n\n\tfor (j=0; j<n; j++) {\n\t\tX.put(n, j, 0);\n\t}\n\tX.put(n, n, 1);\n\n\tfor (i=0; i<n; i++) {\n\t\tX.put(i, n, tran.get(i));\n\t}\n\n\tNTL::GF2 d;\n\t\n\tinv(d, Y, X);\n\n\treturn 0;\n\n}\n\nint genRandomAffineMatrix(NTL::mat_GF2 &X,  NTL::mat_GF2 &Y, NTL::vec_GF2 &V, int n) {\n\trandom(X, n, n);\n\twhile(determinant(X)==0) {\n\t\trandom(X, n, n);\n\t}\n\tNTL::GF2 d;\n\tinv(d, Y, X);\n\trandom(V, n);\n\treturn 0;\n}\n\nint genRandomAffineMatrix(NTL::mat_GF2 &x,  NTL::mat_GF2 &inv_x, NTL::vec_GF2 &v, NTL::vec_GF2 &inv_v, int n) {\n\trandom(x, n, n);\n\twhile(determinant(x)==0) {\n\t\trandom(x, n, n);\n\t}\n\tNTL::GF2 d;\n\tinv(d, inv_x, x);\n\trandom(v, n);\n\tmul(inv_v, inv_x, v);\n\treturn 0;\n}\n\nint genRandomInvMatrix(NTL::mat_GF2 &x,  NTL::mat_GF2 &inv_x, int n) {\n\trandom(x, n, n);\n\twhile(determinant(x)==0) {\n\t\trandom(x, n, n);\n\t}\n\tNTL::GF2 d;\n\tinv(d, inv_x, x);\n\treturn 0;\n}\n\n\nuint32_t getDigitalFromVec(NTL::vec_GF2 &s) {\n\tuint32_t d = 0;\n\tint i;\n\tint m = s.length();\n\tfor (i=0; i<m; i++) {\n\t\td <<=1 ;\n\t\td += ((s.get(i)==1)?1:0);\n\t}\n\treturn d;\n}\n\n\nuint32_t get32FromVec(NTL::vec_GF2 &s) {\n\tuint32_t d = 0;\n\tint i;\n\tfor (i=0; i<32; i++) {\n\t\td <<=1 ;\n\t\td += ((s.get(i)==1)?1:0);\n\t}\n\treturn d;\n}\n\nuint8_t get8FromVec(const vector_transform_t &s) {\n\tuint8_t d = 0;\n\tint i;\n\tfor (i=0; i<8; i++) {\n\t\td <<=1 ;\n\t\td += ((s.get(i)==1)?1:0);\n\t}\n\treturn d;\n}\n\n\nint getVecFrom32(NTL::vec_GF2 &d,uint32_t s) {\n\td.SetLength(32);\n\tint i;\n\tfor (i=31; i>=0; i--) {\n\t\td.put(i, s%2);\n\t\ts>>=1;\n\t}\n\treturn 0;\n}\n\nint getAugmentedVecFrom32(NTL::vec_GF2 &d, uint32_t s) {\n\td.SetLength(33);\n\tint i;\n\tfor (i=31; i>=0; i--) {\n\t\td.put(i, s%2);\n\t\ts>>=1;\n\t}\n\td.put(32, 1);\n\treturn 0;\n}\n\nint combineDiagMat(NTL::mat_GF2 &d, NTL::mat_GF2 &s1, NTL::mat_GF2 &s2) {\n\tlong n1 = s1.NumCols();\n\tlong n2 = s2.NumCols();\n\td.SetDims(n1+n2, n1+n2);\n\tint i,j;\n\tfor (i=0; i<n1; i++) {\n\t\tfor (j=0; j<n1; j++) {\n\t\t\td.put(i, j, s1.get(i,j));\n\t\t}\n\t\tfor (j=0; j<n2; j++) {\n\t\t\td.put(i, n1+j, 0);\n\t\t}\n\t}\n\tfor (i=0; i<n2; i++) {\n\t\tfor (j=0; j<n1; j++) {\n\t\t\td.put(n1+i, j, 0);\n\t\t}\n\t\tfor (j=0; j<n2; j++) {\n\t\t\td.put(n1+i, n1+j, s2.get(i,j));\n\t\t}\n\t}\n\treturn 0;\n}\n\nuint32_t applyAffineToU32(const affine_transform_t &aff, uint32_t data ) {\n\tNTL::vec_GF2 a,b;\n\tinitVecFromBit(a, data, 32);\n\t// dumpVector(a);\n\t// dumpMatrix(aff.linearMap);\n\tb = aff.linearMap * a + aff.vectorTranslation;\n\treturn get32FromVec(b);\n}\n\nuint8_t applyAffineToU8(const affine_transform_t &aff, uint8_t data) {\n\tNTL::vec_GF2 a,b;\n\tinitVecFromBit(a, data, 8);\n\t// dumpVector(a);\n\t// dumpMatrix(aff.linearMap);\n\tb = aff.linearMap * a + aff.vectorTranslation;\n\treturn (uint8_t)getDigitalFromVec(b);\n}\n\nuint8_t applyMatToU8(const NTL::mat_GF2 &mat, uint8_t data) {\n\tNTL::vec_GF2 a,b;\n\tinitVecFromBit(a, data, 8);\n\tb = mat*a;\n\treturn (uint8_t)getDigitalFromVec(b);\n}\n\nuint32_t applyMatToU32(const matrix_transform_t &mat, uint32_t data) {\n\tvector_transform_t a,b;\n\tinitVecFromBit(a, data, 32);\n\tb = mat*a;\n\treturn (uint32_t)getDigitalFromVec(b);\n}\n\nuint32_t addVecToU32(NTL::vec_GF2 &vec, uint32_t data) {\n\tNTL::vec_GF2 a,b;\n\tinitVecFromBit(a, data, 32);\n\tb = vec+a;\n\treturn (uint32_t)getDigitalFromVec(b);\n}\n\nuint8_t addVecToU8(NTL::vec_GF2 &vec, uint8_t data) {\n\tNTL::vec_GF2 a,b;\n\tinitVecFromBit(a, data, 8);\n\tb = vec+a;\n\treturn (uint8_t)getDigitalFromVec(b);\n}\n\n\nint genIndMatrix(NTL::mat_GF2 &mat, int size) {\n\tmat.SetDims(size, size);\n\tint i,j;\n\tfor (i=0; i<size; i++) {\n\t\tfor (j=0; j<size; j++) {\n\t\t\tmat.put(i, j, i==j);\n\t\t}\n\t}\n\treturn 0;\t\n}\n\nint genZeroVec(NTL::vec_GF2 &vec, int size) {\n\tvec.SetLength(size);\n\tint i;\n\tfor (i=0; i<size; i++) {\n\t\tvec.put(i, 0);\n\t}\n\treturn 0;\t\n}\n", "meta": {"hexsha": "3cbc0a1afa99e2b73661c13b73043120e45ae7f1", "size": 4693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/WBSM4/NTL/src/matrixlib/MatrixUtils.cpp", "max_stars_repo_name": "scnucrypto/WBMatrix", "max_stars_repo_head_hexsha": "97ca91dc1e0e9d3f67b9393e404fc4c44d1ac865", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-07-17T14:39:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T08:00:49.000Z", "max_issues_repo_path": "test/WBSM4/NTL/src/matrixlib/MatrixUtils.cpp", "max_issues_repo_name": "scnucrypto/WBMatrix", "max_issues_repo_head_hexsha": "97ca91dc1e0e9d3f67b9393e404fc4c44d1ac865", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-17T06:01:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-29T14:29:26.000Z", "max_forks_repo_path": "test/WBSM4/NTL/src/matrixlib/MatrixUtils.cpp", "max_forks_repo_name": "Nexus-TYF/WBMatrix", "max_forks_repo_head_hexsha": "0043eb53e4ee1d7641c06c0155b5f2357bce18e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-04-16T10:52:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T02:51:23.000Z", "avg_line_length": 18.05, "max_line_length": 111, "alphanum_fraction": 0.5751118687, "num_tokens": 1940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5455878272974817}}
{"text": "#include <boost/math/differentiation/autodiff.hpp>\n#include <iostream>\n\n\ntemplate <typename T> \nT fourth_power(T const& x){\n\tT x4 = x*x;\n\tx4 *= x4;\n\treturn x4;\n}\n\ntemplate <typename T>\nT func(T const& x, T const& y){\n\treturn x*y;\n}\n\nint main(int argc, char **argv){\n\tusing namespace boost::math::differentiation;\n\n\tconstexpr unsigned Order = 5;\n\t\n\tauto const x = make_fvar<double, Order>(2.0);\n\t//auto const y = make_fvar<double, Order>(3.0);\n\tauto const f = fourth_power(x);\n\n\tfor(unsigned int i=0; i<=Order; ++i)\n\t\tstd::cout<< \"f.derivative(\"<< i << \") = \" << f.derivative(i) << std::endl;\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "4909159e5c5fa78d0771f5abbf26b8821d5a9eb6", "size": 607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/automatic_diff/obsolete/main.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.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.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": 18.96875, "max_line_length": 76, "alphanum_fraction": 0.647446458, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5455878265207502}}
{"text": "\ufeff#include \"simulator.h\"\r\n#include <Eigen/Eigenvalues>\r\n#include <future>\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <limits>\r\n#include <set>\r\n\r\nusing namespace Simulator;\r\n\r\nstd::string Simulator::AlgorithmToStr(const Algorithms algorithm)\r\n{\r\n\tswitch (algorithm) {\r\n\tcase Algorithms::Metropolis:\r\n\t\treturn { \"Metropolis method\" };\r\n\tcase Algorithms::Glauber:\r\n\t\treturn { \"Glauber dynamics\" };\r\n\tcase Algorithms::SCA:\r\n\t\treturn { \"Stochastic cellular automata\" };\r\n\tcase Algorithms::fcSCA:\r\n\t\treturn { \"Flip-Constrained Stochastic Cellular Automata\" };\r\n\tcase Algorithms::MA:\r\n\t\treturn { \"Momentum annealing\" };\r\n\tcase Algorithms::MMA:\r\n\t\treturn { \"Modified momentum annealing\" };\r\n\tcase Algorithms::HillClimbing:\r\n\t\treturn { \"Hill climbing\" };\r\n\tdefault:\r\n\t\treturn { \"Warning: Unknown type.\" };\r\n\t}\r\n}\r\n\r\n// quadratic\u306e\u30ad\u30fc\u306e\u30da\u30a2 (i, j) \u306f\u9806\u756a\u304c i < j \u3068\u306a\u3063\u3066\u3044\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3002\r\nIsingModel::IsingModel(const LinearBiases linear, const QuadraticBiases quadratic)\r\n\t: rand(std::make_unique<Rand>())\r\n\t, temperature(0.e0)\r\n\t, pinningParameter(0.e0)\r\n\t, flipTrialRate(0.e0)\r\n\t, algorithm(Algorithms::Metropolis)\r\n{\r\n\t// spins\u306e\u6dfb\u5b57\u3068\u9802\u70b9\u306e\u540d\u524d\u3068\u306e\u5bfe\u5fdc\u8868\u3092\u4f5c\u6210\u3002\r\n\tstd::set<Node> nodes;\r\n\tfor (auto iter = linear.begin(); iter != linear.end(); iter++)\r\n\t\tnodes.insert(iter->first);\r\n\tfor (auto iter = quadratic.begin(); iter != quadratic.end(); iter++) {\r\n\t\tnodes.insert(iter->first.first);\r\n\t\tnodes.insert(iter->first.second);\r\n\t}\r\n\tstd::size_t index = 0;\r\n\tfor (const auto& key : nodes)\r\n\t\tnodeIndices[key] = index++;\r\n\r\n\t// Hamiltonian\u306e\u5b9a\u6570\u3068\u5909\u6570\u3092\u521d\u671f\u5316\u3002\r\n\tauto maxNodes = nodeIndices.size();\r\n\tspins.setConstant(maxNodes, Spin::Up);\r\n\tpreviousSpins = spins;\r\n\texternalMagneticField.resize(maxNodes);\r\n\tfor (const auto& node : nodeIndices) {\r\n\t\tauto iter = linear.find(node.first);\r\n\t\tif (iter != linear.end())\r\n\t\t\texternalMagneticField(node.second) = iter->second;\r\n\t\telse\r\n\t\t\texternalMagneticField(node.second) = 0.e0;\r\n\t}\r\n\tcouplingCoefficients = Eigen::MatrixXd::Zero(maxNodes, maxNodes);\r\n\tfor (const auto& row : nodeIndices) {\r\n\t\tfor (const auto& column : nodeIndices) {\r\n\t\t\tif (row.first > column.first)\r\n\t\t\t\tcontinue;\r\n\t\t\tauto iter = quadratic.find(std::make_pair(row.first, column.first));\r\n\t\t\tif (iter != quadratic.end())\r\n\t\t\t\tcouplingCoefficients(row.second, column.second) = couplingCoefficients(column.second, row.second) = iter->second;\r\n\t\t\telse\r\n\t\t\t\tcouplingCoefficients(row.second, column.second) = couplingCoefficients(column.second, row.second) = 0.e0;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n// \u884c\u5217 (-J_{x, y})_{x, y} \u306e\u6700\u5927\u56fa\u6709\u5024\u3092\u8a08\u7b97\u3059\u308b\u3002\r\ndouble IsingModel::CalcLargestEigenvalue() const\r\n{\r\n\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(-couplingCoefficients);\r\n\treturn solver.eigenvalues().reverse()(0);\r\n}\r\n\r\ndouble IsingModel::GetEnergy() const\r\n{\r\n\t// Remove double-counting duplicates by multiplying the sum by 1/2.\r\n\treturn -spins.cast<double>().transpose() * (0.5e0 * couplingCoefficients * spins.cast<double>() + externalMagneticField);\r\n}\r\n\r\ndouble IsingModel::GetEnergyOnBipartiteGraph() const\r\n{\r\n\treturn -0.5e0 * spins.cast<double>().transpose() * couplingCoefficients * spins.cast<double>()\r\n\t\t- 0.5e0 * externalMagneticField.dot(spins.cast<double>() + previousSpins.cast<double>())\r\n\t\t+ 0.5e0 * pinningParameter * (spins.size() - spins.cast<double>().dot(previousSpins.cast<double>()));\r\n}\r\n\r\nvoid IsingModel::GiveSpins(const ConfigurationsType configurationType)\r\n{\r\n\tswitch (configurationType) {\r\n\tcase ConfigurationsType::AllDown:\r\n\t\tspins.fill(Spin::Down);\r\n\t\tbreak;\r\n\tcase ConfigurationsType::AllUp:\r\n\t\tspins.fill(Spin::Up);\r\n\t\tbreak;\r\n\tcase ConfigurationsType::Uniform:\r\n\t\tfor (auto i = 0; i < spins.size(); i++)\r\n\t\t\tspins(i) = rand->Bernoulli(0.5e0) ? Spin::Down : Spin::Up;\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\tpreviousSpins = spins;\r\n}\r\n\r\nvoid IsingModel::Update()\r\n{\r\n\tauto metropolisMethod = [this]() {\r\n\t\tunsigned int updatedNodeIndex = (*rand)(spins.size());\r\n\t\tdouble energyDifference = 2.e0 * static_cast<int>(spins(updatedNodeIndex)) * calcLocalMagneticField(updatedNodeIndex);\r\n\t\tif (energyDifference < 0.e0)\r\n\t\t\tspins(updatedNodeIndex) = flip(spins(updatedNodeIndex));\r\n\t\telse if (rand->Bernoulli(std::exp(-energyDifference / temperature)))\r\n\t\t\tspins(updatedNodeIndex) = flip(spins(updatedNodeIndex));\r\n\t};\r\n\r\n\tauto glauberDynamics = [this]() {\r\n\t\tunsigned int updatedNodeIndex = (*rand)(spins.size());\r\n\t\tif (rand->Bernoulli(1.e0 / (1.e0 + std::exp(-2.e0 * calcLocalMagneticField(updatedNodeIndex) / temperature))))\r\n\t\t\tspins(updatedNodeIndex) = Spin::Up;\r\n\t\telse\r\n\t\t\tspins(updatedNodeIndex) = Spin::Down;\r\n\t};\r\n\r\n\tauto stochasticCellularAutomata = [this]() {\r\n\t\tpreviousSpins = spins;\r\n\t\tspins = (\r\n\t\t\tcalcLocalMagneticField(spins) + pinningParameter * spins.cast<double>()\r\n\t\t\t- temperature * Eigen::VectorXd::NullaryExpr(spins.size(), [this]() -> double { return rand->Logistic(); })\r\n\t\t).array().sign().cast<Spin>();  // \u5b9f\u8cea\u8d77\u3053\u3089\u306a\u3044\u304c\u3001\u7b26\u53f7\u95a2\u6570\u306b\u6e21\u3057\u3066\u3044\u308b\u305f\u3081\u3001\u30b9\u30d4\u30f3\u304c0\u306b\u306a\u308b\u5834\u5408\u304c\u3042\u308b\u3002\r\n\t};\r\n\r\n\tauto flipConstrainedStochasticCellularAutomata = [this]() {\r\n\t\tpreviousSpins = spins;\r\n\t\t//auto bernoulli =  Eigen::VectorXd::NullaryExpr(spins.size(), [this]() -> bool { return rand->Bernoulli(flipTrialRate) ; });  // = true w.p. flipTrialRate and = false w.p. 1 - flipTrialRate.\r\n\t\tspins = (\r\n\t\t\tcalcLocalMagneticField(spins) + pinningParameter * spins.cast<double>()\r\n\t\t\t- temperature * Eigen::VectorXd::NullaryExpr(spins.size(), [this]() -> double { return rand->Logistic(); })\r\n\t\t\t+ Eigen::VectorXd::NullaryExpr(spins.size(), [this]() -> double {\r\n\t\t\t\treturn rand->Bernoulli(flipTrialRate) ? 0.e0 : std::numeric_limits<double>::infinity();\r\n\t\t\t}).cwiseProduct(spins.cast<double>())\r\n\t\t\t//+ bernoulli.unaryExpr([](bool b) -> double { return b ? 0.e0 : std::numeric_limits<double>::infinity(); }).cwiseProduct(spins.cast<double>())\r\n\t\t).array().sign().cast<Spin>();  // \u5b9f\u8cea\u8d77\u3053\u3089\u306a\u3044\u304c\u3001\u7b26\u53f7\u95a2\u6570\u306b\u6e21\u3057\u3066\u3044\u308b\u305f\u3081\u3001\u30b9\u30d4\u30f3\u304c0\u306b\u306a\u308b\u5834\u5408\u304c\u3042\u308b\u3002\r\n\t};\r\n\r\n\t// \u6e29\u5ea6\u3092\u4e0b\u3052\u306a\u3051\u308c\u3070 ``annealing'' \u3067\u306f\u306a\u3044\u304c\u3001\u8ad6\u6587\u3067\u306f\u533a\u5225\u3057\u3066\u3044\u306a\u3044\u306e\u3067\u3001\u3053\u3053\u3067\u3082\u3053\u306e\u540d\u79f0\u3092\u7528\u3044\u308b\u3002\r\n\tauto momentumAnnealing = [this]() {\r\n\t\tConfiguration temp = (\r\n\t\t\tcalcLocalMagneticField(spins) + pinningParameter * spins.cast<double>()\r\n\t\t\t- temperature * Eigen::VectorXd::NullaryExpr(spins.size(), [this]() -> double { return rand->Exponential(); }).cwiseProduct(previousSpins.cast<double>())\r\n\t\t).array().sign().cast<Spin>();  // \u5b9f\u8cea\u8d77\u3053\u3089\u306a\u3044\u304c\u3001\u7b26\u53f7\u95a2\u6570\u306b\u6e21\u3057\u3066\u3044\u308b\u305f\u3081\u3001\u30b9\u30d4\u30f3\u304c0\u306b\u306a\u308b\u5834\u5408\u304c\u3042\u308b\u3002\r\n\t\tpreviousSpins = spins;\r\n\t\tspins = temp;\r\n\t};\r\n\r\n\tauto modifiedMomentumAnnealing = [this]() {\r\n\t\tpreviousSpins = spins;\r\n\t\tspins = (\r\n\t\t\tcalcLocalMagneticField(spins) + pinningParameter * spins.cast<double>()\r\n\t\t\t- temperature * Eigen::VectorXd::NullaryExpr(spins.size(), [this]() -> double { return rand->Exponential(); }).cwiseProduct(spins.cast<double>())\r\n\t\t).array().sign().cast<Spin>();  // \u5b9f\u8cea\u8d77\u3053\u3089\u306a\u3044\u304c\u3001\u7b26\u53f7\u95a2\u6570\u306b\u6e21\u3057\u3066\u3044\u308b\u305f\u3081\u3001\u30b9\u30d4\u30f3\u304c0\u306b\u306a\u308b\u5834\u5408\u304c\u3042\u308b\u3002\r\n\t};\r\n\r\n\tauto hillClimbing = [this]() {\r\n\t\tConfiguration currentConfiguration = spins;\r\n\t\twhile (true) {\r\n\t\t\t//double nextEval = std::numeric_limits<double>::infinity();\r\n\t\t\tdouble energyDifference = 0.e0;\r\n\t\t\tConfiguration nextConfiguration = currentConfiguration;\r\n\t\t\tfor (auto i = 0; i < spins.size(); i++) {\r\n\t\t\t\tdouble beforeEnergy = -1.e0 * static_cast<int>(currentConfiguration(i)) * calcLocalMagneticField(i);\r\n\t\t\t\tdouble afterEnergy = -1.e0 * static_cast<int>(flip(currentConfiguration(i))) * calcLocalMagneticField(i);\r\n\t\t\t\tif (energyDifference > afterEnergy - beforeEnergy) {\r\n\t\t\t\t\tenergyDifference = afterEnergy - beforeEnergy;\r\n\t\t\t\t\tnextConfiguration(i) = flip(nextConfiguration(i));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (energyDifference >= 0.e0)\r\n\t\t\t\tbreak;\r\n\t\t\tcurrentConfiguration = nextConfiguration;\r\n\t\t}\r\n\t\tspins = currentConfiguration;\r\n\t};\r\n\r\n\tswitch (algorithm) {\r\n\tcase Algorithms::Metropolis:\r\n\t\tmetropolisMethod();\r\n\t\tbreak;\r\n\tcase Algorithms::Glauber:\r\n\t\tglauberDynamics();\r\n\t\tbreak;\r\n\tcase Algorithms::SCA:\r\n\t\tstochasticCellularAutomata();\r\n\t\tbreak;\r\n\tcase Algorithms::fcSCA:\r\n\t\tflipConstrainedStochasticCellularAutomata();\r\n\t\tbreak;\r\n\tcase Algorithms::MA:\r\n\t\tmomentumAnnealing();\r\n\t\tbreak;\r\n\tcase Algorithms::MMA:\r\n\t\tmodifiedMomentumAnnealing();\r\n\t\tbreak;\r\n\tcase Algorithms::HillClimbing:\r\n\t\thillClimbing();\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nvoid IsingModel::Write() const\r\n{\r\n\tstd::cout << \"Current spin configuration:\" << std::endl;\r\n\tfor (auto i = 0; i < spins.size(); i++)\r\n\t\tstd::cout << std::setw(2) << static_cast<int>(spins(i));\r\n\tstd::cout << \"External magnetic field:\" << std::endl;\r\n\tstd::cout << externalMagneticField.transpose() << std::endl;\r\n\tstd::cout << \"Coupling coefficinets:\" << std::endl;\r\n\tstd::cout << couplingCoefficients << std::endl;\r\n\tstd::cout << \"Algorithm: \" << AlgorithmToStr(algorithm) << std::endl;\r\n\tstd::cout << \"Temperature: \" << temperature << std::endl;\r\n\tstd::cout << \"Pinning parameter: \" << pinningParameter << std::endl;\r\n\tstd::cout << \"Flip trial rate: \" << flipTrialRate << std::endl;\r\n}\r\n", "meta": {"hexsha": "9821891cdecfc2d7b77417987a170a82b4048f0a", "size": 8701, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/simulator.cpp", "max_stars_repo_name": "Wandao123/ising_model", "max_stars_repo_head_hexsha": "36c1beafaffb4dd03cb7658d951a9e049532fc74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-10-24T07:25:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-14T10:42:02.000Z", "max_issues_repo_path": "cpp/simulator.cpp", "max_issues_repo_name": "Wandao123/ising_model", "max_issues_repo_head_hexsha": "36c1beafaffb4dd03cb7658d951a9e049532fc74", "max_issues_repo_licenses": ["MIT"], "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/simulator.cpp", "max_forks_repo_name": "Wandao123/ising_model", "max_forks_repo_head_hexsha": "36c1beafaffb4dd03cb7658d951a9e049532fc74", "max_forks_repo_licenses": ["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.5588235294, "max_line_length": 194, "alphanum_fraction": 0.6822204344, "num_tokens": 2513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5455878216285871}}
{"text": "/* User code: This file will not be overwritten by TASTE. */\n\n#include \"printer.h\"\n#include <iostream>\n#include <fstream>\n#include \"base_support/Base-samples-RigidBodyStateConvert.hpp\"\n#include \"base_support/OpaqueConversion.hpp\"\n#include <Eigen/Core>\n#include <vector>\n\nvoid printer_startup()\n{\n    /* Write your initialization code here,\n       but do not make any call to a required interface. */\n}\n\n// EIGEN HELPER METHODS\nvoid to4d(Eigen::Matrix3d r, Eigen::Vector3d t, Eigen::Matrix4d & h){\n\t\n  h<< 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          0,      0,      0,    1;\n}\n\nvoid printer_PI_update_amp(const asn1SccBase_samples_RigidBodyState *IN_pose)\n{\n  base::Vector3d t;\n  base::Quaterniond q;\n  Eigen::Matrix3d r;\n\n  static int i = 0;\n\n  // extract orientation / translation\n  asn1Scc_Vector3d_fromAsn1(t, IN_pose->position);\n  asn1Scc_Quaterniond_fromAsn1(q, IN_pose->orientation);\n  // convert quaternion to rotation mat\n  r = q.normalized().toRotationMatrix();\n\n  Eigen::Matrix4d p;\n\n  to4d(r,t,p);\n  \n  std::ifstream f(\"marker.csv\");\n  bool good = f.good();\n  \n  std::ofstream myfile;\n  if (good) myfile.open (\"marker.csv\", std::ios::app);\n  else myfile.open (\"marker.csv\", std::ios::out);\n\n  myfile << \"\\n\" << std::floor(((p(0,3)) * 100000) + .5) / 100000 \n\t << \",\"  << std::floor(((p(1,3)) * 100000) + .5) / 100000 \n\t << \",\"  << std::floor(((p(2,3)) * 100000) + .5) / 100000;   \n\n  myfile.close();\n\n  i++;\n\n  std::cout << \"got marker position:\\n\" << p << std::endl;\n}\n\nvoid printer_PI_update_arp(const asn1SccBase_samples_RigidBodyState *IN_pose)\n{\n  base::Vector3d t;\n  base::Quaterniond q;\n  Eigen::Matrix3d r;\n  // extract orientation / translation\n  asn1Scc_Vector3d_fromAsn1(t, IN_pose->position);\n  asn1Scc_Quaterniond_fromAsn1(q, IN_pose->orientation);\n  // convert quaternion to rotation mat\n  r = q.normalized().toRotationMatrix();\n\n  Eigen::Matrix4d p;\n\n  to4d(r,t,p);\n\n  std::ifstream f(\"marker.csv\");\n  bool good = f.good();\n  \n  std::ofstream myfile;\n  if (good) myfile.open (\"marker.csv\", std::ios::app);\n  else myfile.open (\"marker.csv\", std::ios::out);\n\n  myfile << \"\\n\" << std::floor(((p(0,3)) * 100000) + .5) / 100000 \n\t << \",\"  << std::floor(((p(1,3)) * 100000) + .5) / 100000 \n\t << \",\"  << std::floor(((p(2,3)) * 100000) + .5) / 100000;   \n\n  myfile.close();\n  std::cout << \"got robot position:\\n\" << p << std::endl;\n}\n\n", "meta": {"hexsha": "e4eaae4820b7c25164e2d5243a3af4ce080c317b", "size": 2421, "ext": "cc", "lang": "C++", "max_stars_repo_path": "printer/printer.cc", "max_stars_repo_name": "ESROCOS/plex-transformer_test", "max_stars_repo_head_hexsha": "22631794cffaa29858de5bc4307d9124f2d26f1d", "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": "printer/printer.cc", "max_issues_repo_name": "ESROCOS/plex-transformer_test", "max_issues_repo_head_hexsha": "22631794cffaa29858de5bc4307d9124f2d26f1d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "printer/printer.cc", "max_forks_repo_name": "ESROCOS/plex-transformer_test", "max_forks_repo_head_hexsha": "22631794cffaa29858de5bc4307d9124f2d26f1d", "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.3152173913, "max_line_length": 77, "alphanum_fraction": 0.6253614209, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5455878159596923}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <tuple>\n\n//! The gradient of the shape function (on the reference element)\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\treturn Eigen::Vector2d(-1 + (i > 0) + (i == 1),\n\t                       -1 + (i > 0) + (i == 2));\n}\n", "meta": {"hexsha": "bfec1be295329987836e88f7be2caa272f6806c5", "size": 565, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series4/2d-rad-cooling/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": "series4/2d-rad-cooling/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": "series4/2d-rad-cooling/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": 31.3888888889, "max_line_length": 89, "alphanum_fraction": 0.6389380531, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5455741512129967}}
{"text": "#include <ostream>\n\n#define NOMINMAX\n#define BOOST_TEST_MAIN\n#include <boost/test/included/unit_test.hpp>\n\n#include \"SimpleSparseMat.hpp\"\n\n#define FOR_MAT(W, H) for (size_t y = 0; y < H; ++y) for (size_t x = 0; x < W; ++x)\n\nnamespace ssmat\n{\n\ttemplate<typename T>\n\tinline std::ostream& operator<<(std::ostream& s, const ssmat::SparseEntry<T>& entry)\n\t{\n\t\treturn s << \"(\" << entry.x << \", \" << entry.y << \" | \" << entry.v << \")\";\n\t}\n}\n\nnamespace\n{\n\ttemplate<typename T, size_t W, size_t H>\n\tssmat::SparseMat<T> FromArray(const T(&vs)[H][W])\n\t{\n\t\tstd::vector<ssmat::SparseEntry<T>> entries;\n\t\tentries.reserve(W * H);\n\t\tfor (ssmat::IndexT y = 0; y < H; ++y)\n\t\t{\n\t\t\tfor (ssmat::IndexT x = 0; x < W; ++x)\n\t\t\t{\n\t\t\t\tconst T val = vs[y][x];\n\t\t\t\tif (val != static_cast<T>(0))\n\t\t\t\t{\n\t\t\t\t\tentries.emplace_back(x, y, val);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ssmat::SparseMat<T>(entries, ssmat::SparseFormat::CSR);\n\t}\n\n\ttemplate<typename T, size_t W, size_t H>\n\tvoid ToArray(const ssmat::SparseMat<T>& sparseMat, T(&matOut)[H][W])\n\t{\n\t\tswitch (sparseMat.getFormat())\n\t\t{\n\t\tcase ssmat::SparseFormat::CSR:\n\t\t\tfor (size_t y = 0; y < sparseMat.rowCount(); ++y)\n\t\t\t{\n\t\t\t\tfor (size_t i = sparseMat.rowBegin(y); i < sparseMat.rowEnd(y); ++i)\n\t\t\t\t{\n\t\t\t\t\tmatOut[y][sparseMat.getX(i)] = sparseMat.getV(i);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ssmat::SparseFormat::CSC:\n\t\t\tfor (size_t y = 0; y < sparseMat.rowCount(); ++y)\n\t\t\t{\n\t\t\t\tfor (size_t i = sparseMat.rowBegin(y); i < sparseMat.rowEnd(y); ++i)\n\t\t\t\t{\n\t\t\t\t\tmatOut[sparseMat.getX(i)][y] = sparseMat.getV(i);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n\ttemplate<typename T, size_t W_A, size_t H_A, size_t W_B>\n\tvoid MultipleMat(const T(&matA)[H_A][W_A], const T(&matB)[W_A][W_B], T(&matC)[H_A][W_B])\n\t{\n\t\tfor (size_t i = 0; i < H_A; ++i)\n\t\t{\n\t\t\tfor (size_t j = 0; j < W_B; ++j)\n\t\t\t{\n\t\t\t\tfor (size_t k = 0; k < W_A; ++k)\n\t\t\t\t{\n\t\t\t\t\tmatC[i][j] += matA[i][k] * matB[k][j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE(aa)\n\nBOOST_AUTO_TEST_CASE(SparseMat_Init)\n{\n\tconstexpr int width = 4;\n\tconstexpr int height = 3;\n\tconst int matIn[height][width] = {\n\t\t{0, 1, 2, 1},\n\t\t{2, 3, 0, 5},\n\t\t{1, 0, 4, 0},\n\t};\n\n\tconst auto sparseMat = FromArray(matIn);\n\n\tint matOut[height][width] = {};\n\tToArray(sparseMat, matOut);\n\n\tFOR_MAT(width, height)\n\t{\n\t\tBOOST_CHECK_EQUAL(matIn[y][x], matOut[y][x]);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(SparseMat_Init2)\n{\n\tauto data = ssmat::MakeEntries(\n\t\t{ 2,1,3,3,2,0,0,1 },\n\t\t{ 2,1,0,1,0,2,1,0 },\n\t\t{ 4,3,1,5,2,1,2,1 }\n\t);\n\tconst auto entriesIn = SortEntries(data, ssmat::SparseFormat::CSR);\n\n\tconst ssmat::SparseMat<int> sparseMat(entriesIn, ssmat::SparseFormat::CSR);\n\tconst auto entriesOut = sparseMat.decompressEntries();\n\n\tBOOST_CHECK_EQUAL(entriesIn.size(), entriesOut.size());\n\tfor (size_t i = 0; i < entriesIn.size(); ++i)\n\t{\n\t\tBOOST_CHECK_EQUAL(entriesIn[i], entriesOut[i]);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(SparseMat_Init3)\n{\n\tauto data = ssmat::MakeEntries(\n\t\t{ 2,1,3,3,2,0,0,1 },\n\t\t{ 2,1,0,1,0,2,1,0 },\n\t\t{ 4,3,1,5,2,1,2,1 }\n\t);\n\tconst auto entriesIn = SortEntries(data, ssmat::SparseFormat::CSC);\n\n\tconst ssmat::SparseMat<int> sparseMat(entriesIn, ssmat::SparseFormat::CSC);\n\tconst auto entriesOut = sparseMat.decompressEntries();\n\n\tBOOST_CHECK_EQUAL(entriesIn.size(), entriesOut.size());\n\tfor (size_t i = 0; i < entriesIn.size(); ++i)\n\t{\n\t\tBOOST_CHECK_EQUAL(entriesIn[i], entriesOut[i]);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(SparseMat_Multiplication)\n{\n\tconstexpr int width = 4;\n\tconstexpr int height = 3;\n\tconst int matA[height][width] = {\n\t\t{0, 1, 2, 1},\n\t\t{2, 3, 0, 5},\n\t\t{1, 0, 4, 0},\n\t};\n\tconst int matB[width][height] = {\n\t\t{0, 1, 2},\n\t\t{1, 4, 0},\n\t\t{0, 0, 1},\n\t\t{0, 3, 0},\n\t};\n\tint matC[height][height] = {};\n\tMultipleMat(matA, matB, matC);\n\n\tauto sparseMatA = FromArray(matA);\n\tauto sparseMatB = FromArray(matB);\n\tconst auto sparseMatC = sparseMatA * sparseMatB;\n\n\tint matC_[height][height] = {};\n\tToArray(sparseMatC, matC_);\n\n\tFOR_MAT(height, height)\n\t{\n\t\tBOOST_CHECK_EQUAL(matC[y][x], matC_[y][x]);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(SparseMat_Summation)\n{\n\tconstexpr int width = 4;\n\tconstexpr int height = 3;\n\tconst int matA[height][width] = {\n\t\t{0, 1, 2, 1},\n\t\t{2, 3, 0, 5},\n\t\t{1, 0, 4, 0},\n\t};\n\tconst int matB[height][width] = {\n\t\t{3, 1, 2, 1},\n\t\t{0, 0, 1, 0},\n\t\t{1, 0, 3, 4},\n\t};\n\n\tconst auto sparseMatA = FromArray(matA);\n\tconst auto sparseMatB = FromArray(matB);\n\tconst auto sparseMatC = sparseMatA + sparseMatB;\n\n\tint matC_[height][width] = {};\n\tToArray(sparseMatC, matC_);\n\n\tFOR_MAT(width, height)\n\t{\n\t\tBOOST_CHECK_EQUAL(matA[y][x] + matB[y][x], matC_[y][x]);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(SparseMat_Insert)\n{\n\tconstexpr int width = 4;\n\tconstexpr int height = 3;\n\tint matIn[height][width] = {\n\t\t{0, 0, 2, 1},\n\t\t{2, 0, 0, 5},\n\t\t{0, 0, 4, 0},\n\t};\n\n\tauto sparseMatA = FromArray(matIn);\n\n\tmatIn[1][2] = 3;\n\tmatIn[2][3] = 1;\n\tsparseMatA.insert(2, 1, 3);\n\tsparseMatA.insert(3, 2, 1);\n\n\tint matOut[height][width] = {};\n\tToArray(sparseMatA, matOut);\n\n\tFOR_MAT(height, height)\n\t{\n\t\tBOOST_CHECK_EQUAL(matIn[y][x], matOut[y][x]);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(SparseMat_Append)\n{\n\tconstexpr int width = 4;\n\tconstexpr int height = 3;\n\tint matIn[height][width] = {\n\t\t{1, 0, 0, 0},\n\t\t{0, 0, 1, 0},\n\t\t{0, 1, 0, 0},\n\t};\n\n\tauto sparseMatA = FromArray(matIn);\n\tmatIn[1][3] = 3;\n\tmatIn[0][3] = 1;\n\tmatIn[2][0] = 1;\n\tstd::vector<ssmat::SparseEntry<int>> additionalEntries;\n\tadditionalEntries.emplace_back(3, 1, 3);\n\tadditionalEntries.emplace_back(3, 0, 1);\n\tadditionalEntries.emplace_back(0, 2, 1);\n\tsparseMatA.append(additionalEntries);\n\n\tint matOut[height][width] = {};\n\tToArray(sparseMatA, matOut);\n\n\tFOR_MAT(height, height)\n\t{\n\t\tBOOST_CHECK_EQUAL(matIn[y][x], matOut[y][x]);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(SparseMat_Fill0)\n{\n\tssmat::SparseMat<int> sparseMat;\n\tsparseMat.fill(3, 7, 0);\n\n\tconst auto& rowBeginIndices = sparseMat.getRowBeginIndices();\n\tconst auto& xs = sparseMat.getXs();\n\tconst auto& vs = sparseMat.getVs();\n\n\tBOOST_CHECK_EQUAL(rowBeginIndices.size(), 0);\n\tBOOST_CHECK_EQUAL(xs.size(), 0);\n\tBOOST_CHECK_EQUAL(vs.size(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(SparseMat_Fill1)\n{\n\tconstexpr int width = 3;\n\tconstexpr int height = 7;\n\n\tssmat::SparseMat<int> sparseMat;\n\tsparseMat.fill(width, height, 2);\n\tsparseMat.fill(height, width, 1);\n\n\tint matOut[height][width] = {};\n\tToArray(sparseMat, matOut);\n\n\tFOR_MAT(width, height)\n\t{\n\t\tBOOST_CHECK_EQUAL(matOut[y][x], 1);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(SparseMat_Transpose)\n{\n\tconstexpr int width = 4;\n\tconstexpr int height = 3;\n\tconst int matA[height][width] = {\n\t\t{0, 5, 0, 3},\n\t\t{2, 0, 0, 5},\n\t\t{1, 7, 0, 0},\n\t};\n\tconst int matAt[width][height] = {\n\t\t{0, 2, 1},\n\t\t{5, 0, 7},\n\t\t{0, 0, 0},\n\t\t{3, 5, 0},\n\t};\n\n\tauto sparseMat = FromArray(matA);\n\tsparseMat.transpose();\n\tint matOut[width][height] = {};\n\tToArray(sparseMat, matOut);\n\n\tFOR_MAT(height, width)\n\t{\n\t\tBOOST_CHECK_EQUAL(matOut[y][x], matAt[y][x]);\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ef7785c82f9ec2234b849b49285d2cac60a01f6b", "size": 6789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test.cpp", "max_stars_repo_name": "agehama/SimpleSparseMat", "max_stars_repo_head_hexsha": "ca84da925a01819a89e3f241a4b9500406463a76", "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.cpp", "max_issues_repo_name": "agehama/SimpleSparseMat", "max_issues_repo_head_hexsha": "ca84da925a01819a89e3f241a4b9500406463a76", "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.cpp", "max_forks_repo_name": "agehama/SimpleSparseMat", "max_forks_repo_head_hexsha": "ca84da925a01819a89e3f241a4b9500406463a76", "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.215625, "max_line_length": 89, "alphanum_fraction": 0.6305788776, "num_tokens": 2488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5455741510658738}}
{"text": "#include \"wx/wxprec.h\"\n#include \"wx/wx.h\"\n#include \"sample.xpm\"\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n//wxAppHeat\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\nclass wxAppHeat : public wxApp\n{\npublic:\n  virtual bool OnInit();\n};\n\nwxIMPLEMENT_APP(wxAppHeat);\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n//wxFrameHeat\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\nclass wxFrameHeat : public wxFrame\n{\npublic:\n  wxFrameHeat(const wxString& title);\n  void OnQuit(wxCommandEvent& event);\n  void OnAbout(wxCommandEvent& event);\n  virtual void OnPaint(wxPaintEvent& event);\n  wxColour to_color(float N);\n\n  ~wxFrameHeat()\n  {\n    delete[] T_fvm;\n    delete[] T_fdm_1;\n    delete[] Tn_fdm_1;\n    delete[] T_fdm_2;\n    delete[] Tn_fdm_2;\n  }\n\nprivate:\n  void init_constants();\n  void solve_fvm();\n  void solve_fdm_1();\n  void solve_fdm_2();\n  void draw_cell(wxDC* dc, float N, wxCoord x, wxCoord y, wxCoord width, wxCoord height);\n\n  //temperature at the left hand side of the bar(deg C)\n  float T_A;\n\n  //temperature at the left hand side of the bar(deg C)\n  float T_B;\n\n  //thermal conductivity k, [W/mK]\n  float k;\n\n  //heat source per unit volume (W/m3)\n  float S;\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n  //FVM\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n  //number of cells for FVM\n  Index m_nbr_fvm;\n\n  //temperature (solution)\n  float* T_fvm;\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n  //FDM\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n  //number of cells for FVM\n  int m_nbr_fdm;\n\n  //temperature (solution)\n  float* T_fdm_1;\n  float* Tn_fdm_1;\n\n  //temperature (solution)\n  float* T_fdm_2;\n  float* Tn_fdm_2;\n\nprivate:\n  wxDECLARE_EVENT_TABLE();\n};\n\nwxBEGIN_EVENT_TABLE(wxFrameHeat, wxFrame)\nEVT_MENU(wxID_EXIT, wxFrameHeat::OnQuit)\nEVT_MENU(wxID_ABOUT, wxFrameHeat::OnAbout)\nEVT_PAINT(wxFrameHeat::OnPaint)\nwxEND_EVENT_TABLE()\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n//wxAppHeat::OnInit()\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\nbool wxAppHeat::OnInit()\n{\n  if (!wxApp::OnInit())\n  {\n    return false;\n  }\n  wxFrameHeat* frame = new wxFrameHeat(\"Heat\");\n  frame->Maximize(true);\n  frame->Show(true);\n  return true;\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n//wxFrameHeat::wxFrameHeat\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\nwxFrameHeat::wxFrameHeat(const wxString& title)\n  : wxFrame(NULL, wxID_ANY, title)\n{\n  SetIcon(wxICON(sample));\n  wxMenu* menu_file = new wxMenu;\n  menu_file->Append(wxID_EXIT, \"E&xit\\tAlt-X\", \"Quit this program\");\n  wxMenu* menu_help = new wxMenu;\n  menu_help->Append(wxID_ABOUT, \"&About\\tF1\", \"Show about dialog\");\n  wxMenuBar* menu_bar = new wxMenuBar();\n  menu_bar->Append(menu_file, \"&File\");\n  menu_bar->Append(menu_help, \"&Help\");\n  SetMenuBar(menu_bar);\n  CreateStatusBar(2);\n  SetStatusText(\"Ready\");\n  init_constants();\n  solve_fvm();\n  solve_fdm_1();\n  solve_fdm_2();\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n//wxFrameHeat::OnQuit\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid wxFrameHeat::OnQuit(wxCommandEvent& WXUNUSED(event))\n{\n  Close(true);\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n//wxFrameHeat::OnAbout\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid wxFrameHeat::OnAbout(wxCommandEvent& WXUNUSED(event))\n{\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n//wxFrameHeat::to_color\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\nwxColour wxFrameHeat::to_color(float N)\n{\n  wxColour C;\n  if (N < 130) C = wxColour(187, 206, 255);\n  else if (N < 160) C = wxColour(132, 166, 250);\n  else if (N < 190) C = wxColour(66, 108, 218);\n  else if (N < 200) C = wxColour(50, 72, 141);\n  else C = wxColour(34, 47, 87);\n  return C;\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n//wxFrameHeat::draw_cell\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid wxFrameHeat::draw_cell(wxDC* dc, float N, wxCoord x, wxCoord y, wxCoord width, wxCoord height)\n{\n  dc->SetBrush(wxBrush(wxColour(to_color(N))));\n  dc->DrawRectangle(x, y - height / 2, width, height);\n  wxString str = wxString::Format(wxT(\"%.1f\"), N);\n  dc->DrawText(str, x + width / 2, y);\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n//wxFrameHeat::OnDraw\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid wxFrameHeat::OnPaint(wxPaintEvent&)\n{\n  wxPaintDC dc(this);\n  wxFont font(wxFontInfo(8).FaceName(\"Courier\"));\n  dc.SetFont(font);\n  wxCoord width = 100;\n  wxCoord height = 50;\n  wxCoord x = 0, y = height / 2;\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n  //FVM\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n  //boundary\n  draw_cell(&dc, T_A, x, y, width, height);\n  x += width;\n  //interior\n  for (int idx = 0; idx < m_nbr_fvm; idx++)\n  {\n    draw_cell(&dc, T_fvm[idx], x, y, width, height);\n    x += width;\n  }\n  //boundary\n  draw_cell(&dc, T_B, x, y, width, height);\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n  //FDM_1\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n  x = 0; y += 100;\n  for (int idx = 0; idx < m_nbr_fdm; idx++)\n  {\n    draw_cell(&dc, T_fdm_1[idx], x, y, width, height);\n    x += width;\n  }\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n  //FDM_2\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n  x = 0; y += 100;\n  for (int idx = 0; idx < m_nbr_fdm; idx++)\n  {\n    draw_cell(&dc, T_fdm_2[idx], x, y, width, height);\n    x += width;\n  }\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n//wxFrameHeat::init_constants\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid wxFrameHeat::init_constants()\n{\n  //temperature at the left hand side of the bar(deg C)\n  T_A = 100;\n\n  //temperature at the left hand side of the bar(deg C)\n  T_B = 200;\n\n  //thermal conductivity k, [W/mK]\n  k = 100;\n\n  //heat source per unit volume (W/m3)\n  S = 1000.0f;;\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n//wxFrameHeat::solve_fvm\n//Finite Volume Method\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid wxFrameHeat::solve_fvm()\n{\n  //number of cells\n  m_nbr_fvm = 5;\n\n  ////////////////////////////////////////////////////////////////////////////////////////////////////\n //allocate solution vectors\n /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n //FVM\n  T_fvm = new float[m_nbr_fvm];\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n  //geometry\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n  //length of the bar(m)\n  const float length = 5;\n\n  //coordinates of the cell faces\n  float* x_faces = new float[m_nbr_fvm + 1];\n  x_faces[0] = 0;\n  for (int idx = 1; idx < m_nbr_fvm + 1; idx++)\n  {\n    x_faces[idx] = x_faces[idx - 1] + length / m_nbr_fvm;\n    wxLogDebug(\"x_faces [%d]=%f\", idx, x_faces[idx]);\n  }\n\n  //coordinates of the cell centroids\n  float* x_center = new float[m_nbr_fvm];\n  for (int idx = 0; idx < m_nbr_fvm; idx++)\n  {\n    x_center[idx] = 0.5f * (x_faces[idx + 1] + x_faces[idx]);\n    wxLogDebug(\"x_center [%d]=%f\", idx, x_center[idx]);\n  }\n\n  //length of each cell\n  float* cell_length = new float[m_nbr_fvm];\n  for (int idx = 0; idx < m_nbr_fvm; idx++)\n  {\n    cell_length[idx] = x_faces[idx + 1] - x_faces[idx];\n    wxLogDebug(\"cell_length [%d]=%f\", idx, cell_length[idx]);\n  }\n\n  //distance between cell centroids\n  float* dist_centroids = new float[m_nbr_fvm + 1];\n  for (int idx = 0; idx < m_nbr_fvm - 1; idx++)\n  {\n    dist_centroids[idx] = x_center[idx + 1] - x_center[idx];\n    wxLogDebug(\"dist_centroids [%d]=%f\", idx, dist_centroids[idx]);\n  }\n\n  //for the boundary cell on the left, the distance is double the distance\n  //from the cell centroid to the boundary face\n  float dist_left = 2 * (x_center[0] - x_faces[0]);\n\n  //for the boundary cell on the right, the distance is double the distance from\n  //the cell centroid to the boundary cell face\n  float dist_right = 2 * (x_faces[m_nbr_fvm] - x_center[m_nbr_fvm - 1]);\n\n  for (int idx = 0; idx < m_nbr_fvm; idx++)\n  {\n    dist_centroids[idx + 1] = dist_centroids[idx];\n  }\n  dist_centroids[0] = dist_left;\n  dist_centroids[m_nbr_fvm] = dist_right;\n  for (int idx = 0; idx < m_nbr_fvm + 1; idx++)\n  {\n    wxLogDebug(\"dist_centroids [%d]=%f\", idx, dist_centroids[idx]);\n  }\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n  //constants\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n  //cross-sectional area A, [m2]\n  const float Area = 0.1f;\n\n  //cell volume\n  float* cell_volume = new float[m_nbr_fvm];\n  for (int idx = 0; idx < m_nbr_fvm; idx++)\n  {\n    cell_volume[idx] = cell_length[idx] * Area;\n    wxLogDebug(\"cell_volume [%d]=%f\", idx, cell_volume[idx]);\n  }\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n  //create the matrices\n  //zero initially\n  /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n  MatrixXf A = MatrixXf::Zero(m_nbr_fvm, m_nbr_fvm);\n  VectorXf B = VectorXf::Zero(m_nbr_fvm);\n\n  for (Index n = 0; n < m_nbr_fvm; n++)\n  {\n    /////////////////////////////////////////////////////////////////////////////////////////////////////\n    //left boundary cell\n    /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    if (n == 0)\n    {\n      //left coefficient aP, T at n\n      float aP = k * Area / dist_centroids[n] + k * Area / dist_centroids[n] * 2.0;\n      wxLogDebug(\"left A[%lld,%lld]=%f\", n, n, aP);\n      A(n, n) = aP;\n\n      //right coefficient aR, T at n+1\n      float aR = k * Area / dist_centroids[n];\n      wxLogDebug(\"left A[%lld,%lld]=%f\", n, n + 1, -1.0 * aR);\n      A(n, n + 1) = -1.0 * aR;\n\n      //source\n      float source = S * cell_volume[n];\n      //additional boundary source, temperature A\n      source += T_A * Area * k / dist_centroids[n] * 2.0;\n      wxLogDebug(\"B[%lld]=%f\", n, source);\n      B(n) = source;\n    }\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////\n    //right boundary cell\n    /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    else if (n == m_nbr_fvm - 1)\n    {\n      //left coefficient aL, T at n-1\n      float aL = k * Area / dist_centroids[n];;\n      wxLogDebug(\"right A[%lld,%lld]=%f\", n, n - 1, -1.0 * aL);\n      A(n, n - 1) = -1.0 * aL;\n\n      //right coefficient aP, T at n\n      float aP = k * Area / dist_centroids[n] + k * Area / dist_centroids[n] * 2.0;\n      wxLogDebug(\"right A[%lld,%lld]=%f\", n, n, aP);\n      A(n, n) = aP;\n\n      //source\n      float source = S * cell_volume[n];\n      //additional boundary source, temperature B\n      source += T_B * Area * k / dist_centroids[n] * 2.0;\n      wxLogDebug(\"B[%lld]=%f\", n, source);\n      B(n) = source;\n    }\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////\n    //interior cells\n    /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    else\n    {\n      //left coefficient aL, T at n-1\n      float aL = k * Area / dist_centroids[n];\n      wxLogDebug(\"A[%lld,%lld]=%f\", n, n - 1, -1.0 * aL);\n      A(n, n - 1) = -1.0 * aL;\n\n      //right coefficient aR, T at n+1\n      float aR = k * Area / dist_centroids[n];\n      wxLogDebug(\"A[%lld,%lld]=%f\", n, n + 1, -1.0 * aR);\n      A(n, n + 1) = -1.0 * aR;\n\n      //middle coefficient aP, T at n\n      float aP = aR + aL;\n      wxLogDebug(\"A[%lld,%lld]=%f\", n, n, aP);\n      A(n, n) = aP;\n\n      //source\n      float source = S * cell_volume[n];\n      wxLogDebug(\"B[%lld]=%f\", n, source);\n      B(n) = source;\n    }\n  }\n\n  //solve \n  VectorXf T_vec = A.colPivHouseholderQr().solve(B);\n  float* t = T_vec.data();\n  for (int idx = 0; idx < m_nbr_fvm; idx++)\n  {\n    T_fvm[idx] = t[idx];\n    wxLogDebug(\"%.1f\", t[idx]);\n  }\n\n  delete[] x_faces;\n  delete[] x_center;\n  delete[] cell_length;\n  delete[] dist_centroids;\n  delete[] cell_volume;\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n//wxFrameHeat::solve_fdm_1\n//Finite Differences Method\n//diffusion only\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid wxFrameHeat::solve_fdm_1()\n{\n  //number of cells\n  m_nbr_fdm = 7;\n\n  ////////////////////////////////////////////////////////////////////////////////////////////////////\n //allocate solution vectors\n /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n  //FDM\n  T_fdm_1 = new float[m_nbr_fdm];\n  Tn_fdm_1 = new float[m_nbr_fdm];\n\n  //time step\n  float dt = 0.005f;\n  float dx = 1.0f;\n\n  //initial and boundary values\n  for (int i = 0; i < m_nbr_fdm; i++)\n  {\n    T_fdm_1[i] = 0;\n  }\n  T_fdm_1[0] = T_A;\n  T_fdm_1[m_nbr_fdm - 1] = T_B;\n\n  for (int i = 0; i < m_nbr_fdm; i++)\n  {\n    wxLogDebug(\"T[%d]=%.1f\", i, T_fdm_1[i]);\n  }\n\n  //F must be <= 0.5\n  float F = k * dt / (dx * dx);\n  wxLogDebug(\"F=%.4f\", F);\n  for (int n = 0; n < 100; n++)\n  {\n    for (int i = 1; i < m_nbr_fdm - 1; i++)\n    {\n      Tn_fdm_1[i] = T_fdm_1[i] + F * (T_fdm_1[i - 1] - 2 * T_fdm_1[i] + T_fdm_1[i + 1]) + dt * S;\n    }\n    for (int i = 1; i < m_nbr_fdm - 1; i++)\n    {\n      T_fdm_1[i] = Tn_fdm_1[i];\n    }\n    for (int i = 0; i < m_nbr_fdm; i++)\n    {\n      wxLogDebug(\"T[%d]=%.1f\", i, T_fdm_1[i]);\n    }\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n//wxFrameHeat::solve_fdm_2\n//Finite Differences Method\n//advection only\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid wxFrameHeat::solve_fdm_2()\n{\n  //number of cells\n  m_nbr_fdm = 7;\n\n  ////////////////////////////////////////////////////////////////////////////////////////////////////\n //allocate solution vectors\n /////////////////////////////////////////////////////////////////////////////////////////////////////\n\n  //FDM\n  T_fdm_2 = new float[m_nbr_fdm];\n  Tn_fdm_2 = new float[m_nbr_fdm];\n\n  //time step\n  float dt = 0.5f;\n  float dx = 1.0f;\n\n  //initial and boundary values\n  for (int i = 0; i < m_nbr_fdm; i++)\n  {\n    T_fdm_2[i] = 0;\n  }\n  T_fdm_2[0] = T_A;\n  T_fdm_2[m_nbr_fdm - 1] = T_B;\n\n  for (int i = 0; i < m_nbr_fdm; i++)\n  {\n    wxLogDebug(\"T[%d]=%.1f\", i, T_fdm_2[i]);\n  }\n\n  int iter = 500;\n  float time = dt * (float)iter;\n  float U = 1.0f; //velocity\n  float C = U * dt / dx; //courant number <= 1\n  wxLogDebug(\"time=%.1f F=%.4f\", time, C);\n  for (int n = 0; n < iter; n++)\n  {\n    for (int i = 1; i < m_nbr_fdm - 1; i++)\n    {\n      Tn_fdm_2[i] = T_fdm_2[i] - C * (T_fdm_2[i] - T_fdm_2[i - 1]);\n    }\n    for (int i = 1; i < m_nbr_fdm - 1; i++)\n    {\n      T_fdm_2[i] = Tn_fdm_2[i];\n    }\n    for (int i = 0; i < m_nbr_fdm; i++)\n    {\n      wxLogDebug(\"T[%d]=%.1f\", i, T_fdm_2[i]);\n    }\n  }\n}\n\n", "meta": {"hexsha": "9e32eff9e88131c07a972a1c14b3b247a812768a", "size": 16744, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transport.cc", "max_stars_repo_name": "pedro-vicente/transport", "max_stars_repo_head_hexsha": "a12a7aa9085ba2cfc0b835473c0e45518c887cab", "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": "transport.cc", "max_issues_repo_name": "pedro-vicente/transport", "max_issues_repo_head_hexsha": "a12a7aa9085ba2cfc0b835473c0e45518c887cab", "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": "transport.cc", "max_forks_repo_name": "pedro-vicente/transport", "max_forks_repo_head_hexsha": "a12a7aa9085ba2cfc0b835473c0e45518c887cab", "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.0071684588, "max_line_length": 105, "alphanum_fraction": 0.4025322504, "num_tokens": 4171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5455741427140177}}
{"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\n#include <NTL/ZZ.h>\n#include <helib/polyEval.h>\n#include <helib/EncryptedArray.h>\n#include <helib/debugging.h>\n\n#include \"gtest/gtest.h\"\n#include \"test_common.h\"\n\nnamespace {\nstruct Parameters\n{\n  const long p; //   p is the plaintext base\n  const long r; //   r is the lifting\n  const long m; //   m is a specific cyclotomic ring\n  const long d; //   d is the polynomial degree\n  const long k; //   k is the baby-step parameter\n  const long max_d;\n  const long L;\n  const bool isMonic;\n\n  Parameters(long p,\n             long r,\n             long m,\n             long d,\n             long k,\n             long max_d,\n             long L,\n             bool isMonic) :\n      p(p), r(r), m(m), d(d), k(k), max_d(max_d), L(L), isMonic(isMonic){};\n\n  friend std::ostream& operator<<(std::ostream& os, const Parameters& params)\n  {\n    return os << \"{\"\n              << \"p=\" << params.p << \",\"\n              << \"r=\" << params.r << \",\"\n              << \"m=\" << params.m << \",\"\n              << \"d=\" << params.d << \",\"\n              << \"k=\" << params.k << \",\"\n              << \"max_d=\" << params.max_d << \",\"\n              << \"L=\" << params.L << \",\"\n              << \"isMonic=\" << params.isMonic << \"}\";\n  };\n};\n\nclass GTestPolyEval : public ::testing::TestWithParam<Parameters>\n{\nprotected:\n  long p;\n  long r;\n  long d;\n  long max_d;\n  long L;\n  bool isMonic;\n  long m;\n  long k;\n  helib::Context context;\n  long p2r;\n  std::shared_ptr<helib::EncryptedArray> ea;\n  helib::SecKey secretKey;\n  const helib::PubKey& publicKey;\n\n  GTestPolyEval() :\n      p(GetParam().p),\n      r(GetParam().r),\n      d(GetParam().d),\n      max_d(GetParam().max_d),\n      L(GetParam().L),\n      isMonic(GetParam().isMonic),\n      m(GetParam().m),\n      k(GetParam().k),\n      context((helib::setDryRun(helib_test::dry), m), p, r),\n      p2r(context.alMod.getPPowR()),\n      ea(std::make_shared<helib::EncryptedArray>(\n          (helib::buildModChain(context, L, /*c=*/3), context))),\n      secretKey(context),\n      publicKey((secretKey.GenSecKey(), secretKey))\n      //  addSome1DMatrices(secretKey); // compute key-switching matrices\n      {};\n\n  virtual void SetUp() override\n  {\n#ifdef DEBUG_PRINTOUT\n    helib::dbgEa = ea; // for debugging purposes\n    helib::dbgKey = &secretKey;\n#endif\n    if (!helib_test::noPrint)\n      std::cout << (helib::isDryRun() ? \"* dry run, \" : \"* \") << \"degree-\" << d\n                << \", m=\" << m << \", L=\" << L << \", p^r=\" << p2r << std::endl;\n  };\n\n  virtual void TearDown() override { helib::cleanupGlobals(); }\n};\n\nTEST_P(GTestPolyEval, encryptedPolynomialsEvaluateAtEncryptedPointCorrectly)\n{\n  NTL::zz_pBak bak;\n  bak.save();\n  NTL::zz_p::init(p);\n  NTL::zz_pXModulus phimX = NTL::conv<NTL::zz_pX>(ea->getPAlgebra().getPhimX());\n\n  // Choose random plaintext polynomials\n  NTL::zz_pX pX = NTL::random_zz_pX(deg(phimX) - 1);\n  NTL::Vec<NTL::zz_pX> ppoly(NTL::INIT_SIZE, d);\n  for (long i = 0; i < ppoly.length(); i++)\n    random(ppoly[i], deg(phimX) - 1);\n\n  // Evaluate the non-encrypted polynomial\n  NTL::zz_pX pres =\n      (ppoly.length() > 0) ? ppoly[ppoly.length() - 1] : NTL::zz_pX::zero();\n  for (long i = ppoly.length() - 2; i >= 0; i--) {\n    MulMod(pres, pres, pX, phimX);\n    pres += ppoly[i];\n  }\n\n  // Encrypt the random polynomials\n  helib::Ctxt cX(publicKey);\n  NTL::Vec<helib::Ctxt> cpoly(NTL::INIT_SIZE, d, cX);\n\n  secretKey.Encrypt(cX, NTL::conv<NTL::ZZX>(pX));\n\n  for (long i = 0; i < ppoly.length(); i++)\n    secretKey.Encrypt(cpoly[i], NTL::conv<NTL::ZZX>(ppoly[i]));\n\n  // Evaluate the encrypted polynomial\n  helib::polyEval(cX, cpoly, cX);\n\n  // Compare the results\n  NTL::ZZX ret;\n  secretKey.Decrypt(ret, cX);\n  NTL::zz_pX cres = NTL::conv<NTL::zz_pX>(ret);\n  EXPECT_EQ(cres, pres) << \"encrypted poly MISMATCH\";\n};\n\nTEST_P(GTestPolyEval, evaluatePolynomialOnCiphertext)\n{\n  // evaluate at random points (at least one co-prime with p)\n  std::vector<long> x;\n  ea->random(x);\n  while (NTL::GCD(x[0], p) != 1) {\n    x[0] = NTL::RandomBnd(p2r);\n  }\n  helib::Ctxt inCtxt(publicKey), outCtxt(publicKey);\n  ea->encrypt(inCtxt, publicKey, x);\n\n  NTL::ZZX poly;\n  for (long i = d; i >= 0; i--)\n    SetCoeff(poly, i, NTL::RandomBnd(p2r)); // coefficients are random\n  if (isMonic)\n    SetCoeff(poly, d); // set top coefficient to 1\n\n  // Evaluate poly on the ciphertext\n  helib::polyEval(outCtxt, poly, inCtxt, k);\n\n  // Check the result\n  std::vector<long> y;\n  ea->decrypt(outCtxt, secretKey, y);\n  for (long i = 0; i < ea->size(); i++) {\n    EXPECT_EQ(helib::polyEvalMod(poly, x[i], p2r), y[i])\n        << \"plaintext poly MISMATCH\\n\";\n  }\n};\n\nstd::vector<Parameters> getParameters()\n{\n  std::vector<Parameters> allParams;\n\n  // SLOW\n  const long p = 7;\n  const long r = 2;\n  long m = 0;\n  const long k = 0;\n  long d = 34;\n\n  // FAST\n  // const long p = 3;\n  // const long r = 2;\n  //      long m = 91;\n  // const long k = 0;\n  // long d = -1;\n\n  const long max_d = (d <= 0) ? 35 : d;\n  const long L = (7 + NTL::NextPowerOfTwo(max_d)) * 30;\n\n  if (m < 2) {\n    m = helib::FindM(\n        /*secprm=*/80, L, /*c=*/3, p, 1, 0, m, !helib_test::noPrint);\n  }\n\n  // Test both monic and non-monic polynomials of this degree\n  if (d >= 0) {\n    allParams.emplace_back(Parameters{p, r, m, d, k, max_d, L, false});\n    allParams.emplace_back(Parameters{p, r, m, d, k, max_d, L, true});\n  } else {\n    // Test degrees 1 to 3 and 25 through 35\n    for (d = 1; d <= 3; d += 2)\n      allParams.emplace_back(Parameters{p, r, m, d, k, max_d, L, true});\n    for (d = 25; d <= 33; d += 2)\n      allParams.emplace_back(Parameters{p, r, m, d, k, max_d, L, true});\n  }\n  return allParams;\n};\n\nINSTANTIATE_TEST_SUITE_P(manyDegrees,\n                         GTestPolyEval,\n                         ::testing::ValuesIn(getParameters()));\n\n} // namespace\n", "meta": {"hexsha": "c1b0be57a4df4cfcac0a5318d660e58cc58ad841", "size": 6398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/GTestPolyEval.cpp", "max_stars_repo_name": "Souhail-MEFTAH/HElib", "max_stars_repo_head_hexsha": "5f97813b99407d6f9a6251cee920b4e419edc028", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/GTestPolyEval.cpp", "max_issues_repo_name": "Souhail-MEFTAH/HElib", "max_issues_repo_head_hexsha": "5f97813b99407d6f9a6251cee920b4e419edc028", "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/GTestPolyEval.cpp", "max_forks_repo_name": "Souhail-MEFTAH/HElib", "max_forks_repo_head_hexsha": "5f97813b99407d6f9a6251cee920b4e419edc028", "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.0818181818, "max_line_length": 80, "alphanum_fraction": 0.5926852141, "num_tokens": 2028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5455656940598997}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nnamespace hacky_toolkit {\n\n//! \\brief A Plane (or hyperplane) is a susbspace of which its dimension is one\n//! less than of its ambient space. The template argument of the dimension of\n//! the plane equals that of its ambient space. I.e., a Plane<float, 2> is a\n//! line in a 2d space. A plane is represented by a vector of Dim + 1 parameters\n//! that can be used to obtain the general form of the plane equation:\n//! a.dot((x, 1)) + d = 0\ntemplate <typename Scalar_, int Dim_>\nclass Plane {\n  static_assert(Dim_ > 0, \"DYNAMIC_DIMENSION_NOT_SUPPORTED\");\n\n public:\n  inline Plane() = default;\n\n  template <typename Derived>\n  inline Plane(Eigen::MatrixBase<Derived> const& p) : a_(p) {}\n\n  template <typename Derived>\n  inline Plane(Eigen::MatrixBase<Derived> const& normal, Scalar_ d) {\n    a_.template head<Dim_>() = normal;\n    a_(Dim_) = d;\n  }\n\n  //! \\brief Creates a normalized plane using two points. The spatial dimension\n  //! of the Plane must equal 2 when using this constructor. Input points can be\n  //! of dimension 2 or 3.\n  template <typename Derived0, typename Derived1>\n  inline Plane(\n      Eigen::MatrixBase<Derived0> const& x,\n      Eigen::MatrixBase<Derived1> const& y) {\n    static_assert(Dim_ == 2);\n    static_assert(\n        Derived0::SizeAtCompileTime == Dim_ ||\n        Derived0::SizeAtCompileTime == Dim_ + 1);\n    static_assert(Derived0::SizeAtCompileTime == Derived1::SizeAtCompileTime);\n    if constexpr (Derived0::SizeAtCompileTime == Dim_) {\n      a_ = x.homogeneous().cross(y.homogeneous());\n    } else {\n      a_ = x.cross(y);\n    }\n    Normalize();\n  }\n\n  //! \\brief Creates a normalized plane using three points. The spatial\n  //! dimension of the Plane must equal 3 when using this constructor. Input\n  //! points can be of dimension 3 or 4.\n  template <typename Derived0, typename Derived1, typename Derived2>\n  inline Plane(\n      Eigen::MatrixBase<Derived0> const& x,\n      Eigen::MatrixBase<Derived1> const& y,\n      Eigen::MatrixBase<Derived2> const& z) {\n    static_assert(Dim_ == 3);\n    static_assert(\n        Derived0::SizeAtCompileTime == Dim_ ||\n        Derived0::SizeAtCompileTime == Dim_ + 1);\n    static_assert(\n        Derived0::SizeAtCompileTime == Derived1::SizeAtCompileTime &&\n        Derived1::SizeAtCompileTime == Derived2::SizeAtCompileTime);\n    if constexpr (Derived0::SizeAtCompileTime == Dim_) {\n      a_.template head<3>() = (y - x).cross(z - x);\n      a_(Dim_) = -x.dot(a_.template head<3>());\n    } else {\n      auto xn = x.hnormalized().eval();\n      a_.template head<3>() =\n          (y.hnormalized() - xn).cross(z.hnormalized() - xn);\n      a_(Dim_) = -xn.dot(a_.template head<3>());\n    }\n    Normalize();\n  }\n\n  template <typename Derived>\n  inline Scalar_ SignedDistance(Eigen::MatrixBase<Derived> const& x) const {\n    static_assert(\n        Derived::SizeAtCompileTime == Dim_ ||\n        Derived::SizeAtCompileTime == Dim_ + 1);\n    if constexpr (Derived::SizeAtCompileTime == Dim_) {\n      return a_.dot(x.homogeneous());\n    } else {\n      return a_.dot(x);\n    }\n  }\n\n  template <typename Derived>\n  inline Scalar_ Distance(Eigen::MatrixBase<Derived> const& x) const {\n    return std::abs(SignedDistance(x));\n  }\n\n  template <typename Derived>\n  inline bool Positive(Eigen::MatrixBase<Derived> const& x) const {\n    return SignedDistance(x) > Scalar_(0.0);\n  }\n\n  template <typename Derived>\n  inline bool Negative(Eigen::MatrixBase<Derived> const& x) const {\n    return SignedDistance(x) < Scalar_(0.0);\n  }\n\n  //! \\brief Tests is a point is considered to lie on the plane.\n  //! \\returns true if \\p x is on the plane.\n  template <typename Derived>\n  inline bool Test(\n      Eigen::MatrixBase<Derived> const& x,\n      Scalar_ threshold = Eigen::NumTraits<Scalar_>::dummy_precision()) const {\n    return Distance(x) < threshold;\n  }\n\n  //! \\brief Normalizes the plane such that the length of the normal (the first\n  //! Dim parameters of a()) equals 1.\n  inline void Normalize() { a_ /= a_.template head<Dim_>().norm(); }\n\n  //! \\brief Point on the plane closest to the origin.\n  inline Eigen::Matrix<Scalar_, Dim_, 1> Origin() const {\n    return normal() * -d();\n  }\n\n  //! \\brief Generates a random point on the unit hypersphere of the subspace\n  //! defined by this plane at a distance of \\p distance from the point returned\n  //! by the Origin() method. The plane does not have to be normalized.\n  //! \\returns A random point on the plane.\n  inline Eigen::Matrix<Scalar_, Dim_, 1> RandomPoint(\n      Scalar_ distance = Scalar_(1.0)) const {\n    // Perturb the normal with some noise.\n    // What are the odds that the added noise equals 0?\n    Eigen::Matrix<Scalar_, Dim_, 1> v =\n        normal() + Eigen::Matrix<Scalar_, Dim_, 1>::Random();\n    // Apply Gram-Schmidt process to get an orthogonal vector. Ie, subtract the\n    // projection of v on the normal from v.\n    return (v - normal() * normal().dot(v) / normal().squaredNorm())\n                   .normalized() *\n               distance +\n           Origin();\n  }\n\n  //! \\brief The orientation of the plane is defined by its normal. Not\n  //! guaranteed to be normalized.\n  //! \\returns The plane normal.\n  inline auto normal() const {\n    // Eigen::VectorBlock<VectorType const, Dim_>\n    return a_.template head<Dim_>();\n  }\n\n  //! \\brief The negative of the distance from the origin to the plane in the\n  //! direction of the normal. That is, the closest point on the plane to the\n  //! origin equals:\n  //! \\code\n  //! plane.normal() * -plane.d()\n  //! \\endcode\n  //! \\returns Negative distance from the origin to the plane.\n  Scalar_ const& d() const { return a_(Dim_); }\n\n  //! \\brief The parameters of the plane. They describe the General form of the\n  //! plane equation: a.dot((x, 1)) = 0\n  auto const& a() const { return a_; }\n\n  //! \\brief Generates a Plane with a random normal at a distance somewhere in\n  //! the range of [-max_distance:max_distance].\n  static Plane Random(Scalar_ max_distance = Scalar_(1.0)) {\n    return {\n        Eigen::Matrix<Scalar_, Dim_, 1>::Random().normalized(),\n        Eigen::Matrix<Scalar_, 1, 1>::Random()(0) * max_distance};\n  }\n\n private:\n  Eigen::Matrix<Scalar_, Dim_ + 1, 1> a_;\n};\n\nusing Plane2d = Plane<double, 2>;\nusing Plane3d = Plane<double, 3>;\n\nusing Plane2f = Plane<float, 2>;\nusing Plane3f = Plane<float, 3>;\n\n}  // namespace hacky_toolkit\n", "meta": {"hexsha": "795e0c24861b020b7682613b98335a7711bffd62", "size": 6375, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/hacky_toolkit/hacky_toolkit/plane.hpp", "max_stars_repo_name": "Jaybro/hacky_sac", "max_stars_repo_head_hexsha": "9eea07eb4d5af8e5847d8afdd377d06f0a5740dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T13:42:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T13:42:15.000Z", "max_issues_repo_path": "examples/hacky_toolkit/hacky_toolkit/plane.hpp", "max_issues_repo_name": "Jaybro/hacky_sac", "max_issues_repo_head_hexsha": "9eea07eb4d5af8e5847d8afdd377d06f0a5740dc", "max_issues_repo_licenses": ["MIT"], "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/hacky_toolkit/hacky_toolkit/plane.hpp", "max_forks_repo_name": "Jaybro/hacky_sac", "max_forks_repo_head_hexsha": "9eea07eb4d5af8e5847d8afdd377d06f0a5740dc", "max_forks_repo_licenses": ["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.6145251397, "max_line_length": 80, "alphanum_fraction": 0.6600784314, "num_tokens": 1681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5455656936432778}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <deal.II/base/index_set.h>\n#include <cmath>\n\n#include \"base/numbers.hpp\"\n#include \"enum/enum.hpp\"\n#include \"quadrature/qmidpoint.hpp\"\n#include \"quadrature/quad_handler1d.hpp\"\n#include \"quadrature/tensor_product_quadrature.hpp\"\n#include \"spectral/basis/spectral_elem_accessor.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n\n\nnamespace boltzmann {\nclass Momentum\n{\n private:\n  typedef Eigen::Vector2d value_t;\n\n public:\n  Momentum() {}\n\n  template <typename SPECTRAL_BASIS>\n  Momentum(const SPECTRAL_BASIS& spectral_basis)\n  {\n    init(spectral_basis);\n  }\n\n  template <typename SPECTRAL_BASIS>\n  void init(const SPECTRAL_BASIS& spectral_basis);\n\n  /**\n   * @brief compute momentum,\n   *\n   * @param dst\n   * @param src\n   * @param count #physical dofs\n   */\n  template <typename NUMERIC_T>\n  void compute(NUMERIC_T* dstx, NUMERIC_T* dsty, const NUMERIC_T* src, int count) const;\n\n  template <typename VEC_IN, typename VEC_OUT, typename INDEXER>\n  void compute(VEC_OUT& dstx,\n               VEC_OUT& dsty,\n               const VEC_IN& src,\n               const dealii::IndexSet& relevant_dofs,\n               const INDEXER& indexer) const;\n\n  template <typename NUMERIC_T>\n  value_t compute(const NUMERIC_T* src) const;\n\n private:\n  typedef std::pair<unsigned int, value_t> entry_t;\n\n private:\n  unsigned int n_velo_dofs;\n  std::vector<entry_t> contributions;\n\n public:\n  const std::vector<entry_t>& entries() const { return contributions; }\n};\n\n// ------------------------------------------------------------\ntemplate <typename SPECTRAL_BASIS>\nvoid\nMomentum::init(const SPECTRAL_BASIS& spectral_basis)\n{\n  n_velo_dofs = spectral_basis.n_dofs();\n\n  typedef typename std::tuple_element<1, typename SPECTRAL_BASIS::elem_t::container_t>::type\n      radial_elem_t;\n\n  typedef typename std::tuple_element<0, typename SPECTRAL_BASIS::elem_t::container_t>::type\n      angular_elem_t;\n\n  auto& QR_handler = QuadHandler<MaxwellQuadrature>::GetInstance();\n  typedef QuadAdaptor<MaxwellQuadrature> qr_adapt;\n\n  unsigned int nqR = spectral::get_max_k(spectral_basis) + 2;\n  Eigen::VectorXd pts_qR(nqR);\n  Eigen::VectorXd wts_qR(nqR);\n\n  qr_adapt::apply(pts_qR.data(), wts_qR.data(), QR_handler.get(nqR), 0.5);\n\n  typedef typename SPECTRAL_BASIS::elem_t elem_t;\n  for (auto it = spectral_basis.begin(); it != spectral_basis.end(); ++it) {\n    typename elem_t::Acc::template get<radial_elem_t> getter;\n    typename elem_t::Acc::template get<angular_elem_t> geta;\n\n    const auto& rr = getter(*it);\n\n    if (geta(*it).get_id().l != 1) continue;\n\n    // make sure we are using the right basis\n    const double w = rr.w();\n    if (abs(0.5 - w) > 1e-10) throw std::runtime_error(\"Error: wrong weight in Momentum::init\");\n\n    value_t sum;\n    sum[0] = 0.0;\n    sum[1] = 0.0;\n    if (geta(*it).get_id().t == TRIG::SIN) {\n      // sin\n      for (unsigned int q = 0; q < pts_qR.size(); ++q) {\n        const double r = pts_qR[q];\n        sum[TRIG::SIN] += rr.evaluate(r) * r * wts_qR[q];\n      }\n    } else if (geta(*it).get_id().t == TRIG::COS) {\n      for (unsigned int q = 0; q < pts_qR.size(); ++q) {\n        const double r = pts_qR[q];\n        sum[TRIG::COS] += rr.evaluate(r) * r * wts_qR[q];\n      }\n    }\n\n    const unsigned int i = it - spectral_basis.begin();\n    contributions.push_back(std::make_pair(i, numbers::PI * sum));\n  }\n}\n\n// // ------------------------------------------------------------\ntemplate <typename NUMERIC_T>\nvoid\nMomentum::compute(NUMERIC_T* dstx, NUMERIC_T* dsty, const NUMERIC_T* src, int count) const\n{\n#pragma omp parallel for\n  for (int i = 0; i < count; ++i) {\n    const NUMERIC_T* local_src = src + i * n_velo_dofs;\n    value_t sum;\n    sum[0] = 0;\n    sum[1] = 0;\n    for (unsigned int j = 0; j < contributions.size(); ++j) {\n      sum += contributions[j].second * local_src[contributions[j].first];\n    }\n    dstx[i] = sum[0];\n    dsty[i] = sum[1];\n  }\n}\n\n// ------------------------------------------------------------\ntemplate <typename NUMERIC_T>\nMomentum::value_t\nMomentum::compute(const NUMERIC_T* src) const\n{\n  value_t sum;\n  sum[0] = 0;\n  sum[1] = 0;\n  for (unsigned int j = 0; j < contributions.size(); ++j) {\n    sum += contributions[j].second * src[contributions[j].first];\n  }\n  return sum;\n}\n\n// // ------------------------------------------------------------\ntemplate <typename VEC_IN, typename VEC_OUT, typename INDEXER>\nvoid\nMomentum::compute(VEC_OUT& dstx,\n                  VEC_OUT& dsty,\n                  const VEC_IN& src,\n                  const dealii::IndexSet& relevant_dofs,\n                  const INDEXER& indexer) const\n{\n#pragma omp parallel for\n  for (unsigned int ix = 0; ix < relevant_dofs.size(); ++ix) {\n    if (relevant_dofs.is_element(ix)) {\n      value_t sum;\n      sum[0] = 0;\n      sum[1] = 0;\n      for (unsigned int j = 0; j < contributions.size(); ++j) {\n        unsigned int jx = contributions[j].first;\n        sum += contributions[j].second * src[indexer.to_global(ix, jx)];\n      }\n      dstx[ix] = sum[0];\n      dsty[ix] = sum[1];\n    }\n  }\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "173b280926a364ed58e24130dd138a7f143fc349", "size": 5096, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/post_processing/momentum.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/post_processing/momentum.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/post_processing/momentum.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": 28.3111111111, "max_line_length": 96, "alphanum_fraction": 0.6165620094, "num_tokens": 1453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5455656827630153}}
{"text": "// File: recursator2.cpp\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/mtl/recursion/matrix_recursator.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl; using std::cout;\n\n    typedef morton_dense<double, recursion::morton_z_mask>  matrix_type;\n    matrix_type                                             A(10, 10);\n    mat::hessian_setup(A, 3.0);\n    mat::recursator<matrix_type>                          rec(A);\n\n    // Create a recursator for the north_east quadrant of A\n    mat::recursator<matrix_type>                          ne(north_east(rec));\n\n    cout << \"Test if recursator 'ne' refers to an empty matrix (shouldn't): \" << is_empty(ne) << \"\\n\";\n    cout << \"Test if north_east of 'ne' refers to an empty matrix (it should): \" << is_empty(north_east(ne)) << \"\\n\";\n\n    cout << \"Number of rows and columns of north_east quadrant is: \" << num_rows(ne)\n\t << \" and \" << num_cols(ne) << \"\\n\";\n\n    cout << \"Test if 'ne' fills ils virtual quadrant (shouldn't): \" << is_full(ne) << \"\\n\";\n    cout << \"Test if north_west fills its virtual quadrant (it should): \" << is_full(north_west(rec)) << \"\\n\";\n\n    return 0;\n}\n\n", "meta": {"hexsha": "69317af54f39b8d7b53878f44522b5f10a4e69ed", "size": 1162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/recursator2.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/recursator2.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/recursator2.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": 37.4838709677, "max_line_length": 117, "alphanum_fraction": 0.6015490534, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.545498544652705}}
{"text": "//! \\file examples/Arrangement_on_surface_2/bgl_dual_adapter.cpp\n// Adapting the dual of an arrangement to a BGL graph.\n\n#include \"arr_rational_nt.h\"\n#include <CGAL/Cartesian.h>\n#include <CGAL/Arr_segment_traits_2.h>\n#include <CGAL/Arr_extended_dcel.h>\n#include <CGAL/Arrangement_2.h>\n#include <CGAL/graph_traits_dual_arrangement_2.h>\n#include <CGAL/Arr_face_index_map.h>\n\n#include <climits>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/visitors.hpp>\n\n#include \"arr_print.h\"\n\n// A property map that reads/writes the information to/from the extended \n// face.\ntemplate <typename Arrangement, class Type> class Extended_face_property_map {\npublic:\n  typedef typename Arrangement::Face_handle       Face_handle;\n\n  // Boost property type definitions.\n  typedef boost::read_write_property_map_tag      category;\n  typedef Type                                    value_type;\n  typedef value_type&                             reference;\n  typedef Face_handle                             key_type;\n\n  // The get function is required by the property map concept.\n  friend reference get(const Extended_face_property_map&, key_type key)\n  { return key->data(); }\n\n  // The put function is required by the property map concept.\n  friend void put(const Extended_face_property_map&,\n                  key_type key, value_type val)\n  { key->set_data(val); }\n};\n\ntypedef CGAL::Cartesian<Number_type>                         Kernel;\ntypedef CGAL::Arr_segment_traits_2<Kernel>                   Traits_2;\ntypedef CGAL::Arr_face_extended_dcel<Traits_2, unsigned int> Dcel;\ntypedef CGAL::Arrangement_2<Traits_2, Dcel>                  Ex_arrangement;\ntypedef CGAL::Dual<Ex_arrangement>                           Dual_arrangement;\ntypedef CGAL::Arr_face_index_map<Ex_arrangement>             Face_index_map;\ntypedef Extended_face_property_map<Ex_arrangement,unsigned int>\n                                                             Face_property_map;\ntypedef Kernel::Point_2                                      Point_2;\ntypedef Kernel::Segment_2                                    Segment_2;\n\nint main()\n{\n  // Construct an arrangement of seven intersecting line segments.\n  Point_2 p1(1, 1), p2(1, 4), p3(2, 2), p4(3, 7), p5(4, 4), p6(7, 1), p7(9, 3);\n  Ex_arrangement  arr;\n  insert(arr, Segment_2(p1, p6));\n  insert(arr, Segment_2(p1, p4));  insert(arr, Segment_2(p2, p6));\n  insert(arr, Segment_2(p3, p7));  insert(arr, Segment_2(p3, p5));\n  insert(arr, Segment_2(p6, p7));  insert(arr, Segment_2(p4, p7));\n\n  // Create a mapping of the arrangement faces to indices.\n  Face_index_map  index_map(arr);\n\n  // Perform breadth-first search from the unbounded face, using the event\n  // visitor to associate each arrangement face with its discover time.\n  unsigned int    time = 0;\n  boost::breadth_first_search(Dual_arrangement(arr), arr.unbounded_face(),\n                              boost::vertex_index_map(index_map).visitor\n                              (boost::make_bfs_visitor\n                               (stamp_times(Face_property_map(), time,\n                                            boost::on_discover_vertex()))));\n\n  // Print the discover time of each arrangement face.\n  Ex_arrangement::Face_iterator  fit;\n  for (fit = arr.faces_begin(); fit != arr.faces_end(); ++fit) {\n    std::cout << \"Discover time \" << fit->data() << \" for \";\n    if (fit != arr.unbounded_face()) {\n      std::cout << \"face \";\n      print_ccb<Ex_arrangement>(fit->outer_ccb());\n    }\n    else std::cout << \"the unbounded face.\" << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "3ca5598ea278335bb0109c853f49ccbaa9dc57ba", "size": 3559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/examples/BGL_arrangement_2/arrangement_dual.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_arrangement_2/arrangement_dual.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_arrangement_2/arrangement_dual.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": 41.8705882353, "max_line_length": 79, "alphanum_fraction": 0.6428772127, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5454985342214423}}
{"text": "#define BOOST_TEST_MODULE MixedLatticeSolveTests\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 DenseLat1_lsqr(2*m1,n1,p);\r\n    denseType DenseLat2(m1,n2,p);\r\n\n    denseType DenseLat3;\r\n    denseType DenseLat3_mixed;\r\n\r\n    sparseType SparseLat1;\n    sparseType SparseLat2;\r\n    sparseType SparseLat1_lsqr;\n    sparseType SparseLat3;\n\n    random_matrix(DenseLat1,0.4);\r\n    random_matrix(DenseLat1_lsqr,0.4,false,true);\r\n    random_matrix(DenseLat2,0.4,false);\r\n\r\n    SparseLat1=DenseLat1;\r\n    SparseLat2=DenseLat2;\r\n    SparseLat1_lsqr=DenseLat1_lsqr;\r\n\r\n    DenseLat3=DenseLat1.solve(DenseLat2);\r\n    DenseLat3_mixed=DenseLat1.solve(SparseLat2);\r\n\r\n\r\n\r\n    BOOST_CHECK_MESSAGE(DenseLat3.fuzzy_equals(DenseLat3_mixed,test_precision<data_type>()),std::string(\"Full Dimension Solve Test 1 for \")+typeid(data_type).name());\r\n    //now invert the sparse version instead\r\n\r\n    DenseLat3_mixed=SparseLat1.solve(DenseLat2);\r\n\r\n    BOOST_CHECK_MESSAGE(DenseLat3.fuzzy_equals(DenseLat3_mixed,test_precision<data_type>()),std::string(\"Full Dimension Solve Test 2 for \")+typeid(data_type).name());\r\n\r\n\r\n    DenseLat2=denseType(2*m1,n2,p);\r\n    random_matrix(DenseLat2,0.4,false);\r\n    SparseLat2=DenseLat2;\r\n\r\n    DenseLat3=DenseLat1_lsqr.solve(DenseLat2);\r\n    DenseLat3_mixed=DenseLat1_lsqr.solve(SparseLat2);\r\n\r\n    BOOST_CHECK_MESSAGE(DenseLat3.fuzzy_equals(DenseLat3_mixed,test_precision<data_type>()),std::string(\"LSQR Solve Test 1 for \")+typeid(data_type).name());\r\n\r\n    DenseLat3_mixed=SparseLat1_lsqr.solve(DenseLat2);\r\n    BOOST_CHECK_MESSAGE(DenseLat3.fuzzy_equals(DenseLat3_mixed,test_precision<data_type>()),std::string(\"LSQR Solve Test 2 for \")+typeid(data_type).name());\n\n}\n\nBOOST_AUTO_TEST_CASE( MixedLatticeSolveTests )\n{\n\n\n    //multwork<double>(3,3,3,3);\r\n    //solvework<double>(5,5,5,5);\r\n    //solvework<double>(20,20,10,20);\n    solvework<float>(20,20,10,20);\r\n\n\n\n\n}\r\n", "meta": {"hexsha": "e8c45c3842f8d6ba91f9d7a0b8e4f76b2c5480a1", "size": 3845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/Lattice/mixed_lattice_solve_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/Lattice/mixed_lattice_solve_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/Lattice/mixed_lattice_solve_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": 30.0390625, "max_line_length": 167, "alphanum_fraction": 0.6416124837, "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5454985330374179}}
{"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 barycentric_rational\n\n#include <cmath>\n#include <random>\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/floating_point_comparison.hpp>\n#include <boost/math/interpolators/barycentric_rational.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\nusing std::sqrt;\nusing std::abs;\nusing std::numeric_limits;\nusing boost::multiprecision::cpp_bin_float_50;\n\ntemplate<class Real>\nvoid test_interpolation_condition()\n{\n    std::cout << \"Testing interpolation condition for barycentric interpolation on type \" << boost::typeindex::type_id<Real>().pretty_name()  << \"\\n\";\n    std::mt19937 gen(4);\n    boost::random::uniform_real_distribution<Real> dis(0.1f, 1);\n    std::vector<Real> x(500);\n    std::vector<Real> y(500);\n    x[0] = dis(gen);\n    y[0] = dis(gen);\n    for (size_t i = 1; i < x.size(); ++i)\n    {\n        x[i] = x[i-1] + dis(gen);\n        y[i] = dis(gen);\n    }\n\n    boost::math::barycentric_rational<Real> interpolator(x.data(), y.data(), y.size());\n\n    for (size_t i = 0; i < x.size(); ++i)\n    {\n        Real z = interpolator(x[i]);\n        BOOST_CHECK_CLOSE(z, y[i], 100*numeric_limits<Real>::epsilon());\n    }\n}\n\ntemplate<class Real>\nvoid test_interpolation_condition_high_order()\n{\n    std::cout << \"Testing interpolation condition in high order for barycentric interpolation on type \" << boost::typeindex::type_id<Real>().pretty_name()  << \"\\n\";\n    std::mt19937 gen(5);\n    boost::random::uniform_real_distribution<Real> dis(0.1f, 1);\n    std::vector<Real> x(500);\n    std::vector<Real> y(500);\n    x[0] = dis(gen);\n    y[0] = dis(gen);\n    for (size_t i = 1; i < x.size(); ++i)\n    {\n        x[i] = x[i-1] + dis(gen);\n        y[i] = dis(gen);\n    }\n\n    // Order 5 approximation:\n    boost::math::barycentric_rational<Real> interpolator(x.data(), y.data(), y.size(), 5);\n\n    for (size_t i = 0; i < x.size(); ++i)\n    {\n        Real z = interpolator(x[i]);\n        BOOST_CHECK_CLOSE(z, y[i], 100*numeric_limits<Real>::epsilon());\n    }\n}\n\n\ntemplate<class Real>\nvoid test_constant()\n{\n    std::cout << \"Testing that constants are interpolated correctly using barycentric interpolation on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n\n    std::mt19937 gen(6);\n    boost::random::uniform_real_distribution<Real> dis(0.1f, 1);\n    std::vector<Real> x(500);\n    std::vector<Real> y(500);\n    Real constant = -8;\n    x[0] = dis(gen);\n    y[0] = constant;\n    for (size_t i = 1; i < x.size(); ++i)\n    {\n        x[i] = x[i-1] + dis(gen);\n        y[i] = y[0];\n    }\n\n    boost::math::barycentric_rational<Real> interpolator(x.data(), y.data(), y.size());\n\n    for (size_t i = 0; i < x.size(); ++i)\n    {\n        // Don't evaluate the constant at x[i]; that's already tested in the interpolation condition test.\n        Real t = x[i] + dis(gen);\n        Real z = interpolator(t);\n        BOOST_CHECK_CLOSE(z, constant, 100*sqrt(numeric_limits<Real>::epsilon()));\n        BOOST_CHECK_SMALL(interpolator.prime(t), sqrt(numeric_limits<Real>::epsilon()));\n    }\n}\n\ntemplate<class Real>\nvoid test_constant_high_order()\n{\n    std::cout << \"Testing that constants are interpolated correctly in high order using barycentric interpolation on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n\n    std::mt19937 gen(7);\n    boost::random::uniform_real_distribution<Real> dis(0.1f, 1);\n    std::vector<Real> x(500);\n    std::vector<Real> y(500);\n    Real constant = 5;\n    x[0] = dis(gen);\n    y[0] = constant;\n    for (size_t i = 1; i < x.size(); ++i)\n    {\n        x[i] = x[i-1] + dis(gen);\n        y[i] = y[0];\n    }\n\n    // Set interpolation order to 7:\n    boost::math::barycentric_rational<Real> interpolator(x.data(), y.data(), y.size(), 7);\n\n    for (size_t i = 0; i < x.size(); ++i)\n    {\n        Real t = x[i] + dis(gen);\n        Real z = interpolator(t);\n        BOOST_CHECK_CLOSE(z, constant, 1000*sqrt(numeric_limits<Real>::epsilon()));\n        BOOST_CHECK_SMALL(interpolator.prime(t), 100*sqrt(numeric_limits<Real>::epsilon()));\n    }\n}\n\n\ntemplate<class Real>\nvoid test_runge()\n{\n    std::cout << \"Testing interpolation of Runge's 1/(1+25x^2) function using barycentric interpolation on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n\n    std::mt19937 gen(8);\n    boost::random::uniform_real_distribution<Real> dis(0.005f, 0.01f);\n    std::vector<Real> x(500);\n    std::vector<Real> y(500);\n    x[0] = -2;\n    y[0] = 1/(1+25*x[0]*x[0]);\n    for (size_t i = 1; i < x.size(); ++i)\n    {\n        x[i] = x[i-1] + dis(gen);\n        y[i] = 1/(1+25*x[i]*x[i]);\n    }\n\n    boost::math::barycentric_rational<Real> interpolator(x.data(), y.data(), y.size(), 5);\n\n    for (size_t i = 0; i < x.size(); ++i)\n    {\n        Real t = x[i];\n        Real z = interpolator(t);\n        BOOST_CHECK_CLOSE(z, y[i], 0.03);\n        Real z_prime = interpolator.prime(t);\n        Real num = -50*t;\n        Real denom = (1+25*t*t)*(1+25*t*t);\n        if (abs(num/denom) > 0.00001)\n        {\n            BOOST_CHECK_CLOSE_FRACTION(z_prime, num/denom, 0.03);\n        }\n    }\n\n\n    Real tol = 0.0001;\n    for (size_t i = 0; i < x.size(); ++i)\n    {\n        Real t = x[i] + dis(gen);\n        Real z = interpolator(t);\n        BOOST_CHECK_CLOSE(z, 1/(1+25*t*t), tol);\n        Real z_prime = interpolator.prime(t);\n        Real num = -50*t;\n        Real denom = (1+25*t*t)*(1+25*t*t);\n        Real runge_prime = num/denom;\n\n        if (abs(runge_prime) > 0 && abs(z_prime - runge_prime)/abs(runge_prime) > tol)\n        {\n            std::cout << \"Error too high for t = \" << t << \" which is a distance \" << t - x[i] << \" from node \" << i << \"/\" << x.size() << \" associated with data (\" << x[i] << \", \" << y[i] << \")\\n\";\n            BOOST_CHECK_CLOSE_FRACTION(z_prime, runge_prime, tol);\n        }\n    }\n}\n\ntemplate<class Real>\nvoid test_weights()\n{\n    std::cout << \"Testing weights are calculated correctly using barycentric interpolation on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n\n    std::mt19937 gen(9);\n    boost::random::uniform_real_distribution<Real> dis(0.005, 0.01);\n    std::vector<Real> x(500);\n    std::vector<Real> y(500);\n    x[0] = -2;\n    y[0] = 1/(1+25*x[0]*x[0]);\n    for (size_t i = 1; i < x.size(); ++i)\n    {\n        x[i] = x[i-1] + dis(gen);\n        y[i] = 1/(1+25*x[i]*x[i]);\n    }\n\n    boost::math::detail::barycentric_rational_imp<Real> interpolator(x.data(), x.data() + x.size(), y.data(), 0);\n\n    for (size_t i = 0; i < x.size(); ++i)\n    {\n        Real w = interpolator.weight(i);\n        if (i % 2 == 0)\n        {\n            BOOST_CHECK_CLOSE(w, 1, 0.00001);\n        }\n        else\n        {\n            BOOST_CHECK_CLOSE(w, -1, 0.00001);\n        }\n    }\n\n    // d = 1:\n    interpolator = boost::math::detail::barycentric_rational_imp<Real>(x.data(), x.data() + x.size(), y.data(), 1);\n\n    for (size_t i = 1; i < x.size() -1; ++i)\n    {\n        Real w = interpolator.weight(i);\n        Real w_expect = 1/(x[i] - x[i - 1]) + 1/(x[i+1] - x[i]);\n        if (i % 2 == 0)\n        {\n            BOOST_CHECK_CLOSE(w, -w_expect, 0.00001);\n        }\n        else\n        {\n            BOOST_CHECK_CLOSE(w, w_expect, 0.00001);\n        }\n    }\n\n}\n\n\nBOOST_AUTO_TEST_CASE(barycentric_rational)\n{\n    test_weights<double>();\n    test_constant<float>();\n    test_constant<double>();\n    test_constant<long double>();\n    test_constant<cpp_bin_float_50>();\n\n    test_constant_high_order<float>();\n    test_constant_high_order<double>();\n    test_constant_high_order<long double>();\n    test_constant_high_order<cpp_bin_float_50>();\n\n    test_interpolation_condition<float>();\n    test_interpolation_condition<double>();\n    test_interpolation_condition<long double>();\n    test_interpolation_condition<cpp_bin_float_50>();\n\n    test_interpolation_condition_high_order<float>();\n    test_interpolation_condition_high_order<double>();\n    test_interpolation_condition_high_order<long double>();\n    test_interpolation_condition_high_order<cpp_bin_float_50>();\n\n    test_runge<double>();\n    test_runge<long double>();\n    test_runge<cpp_bin_float_50>();\n\n#ifdef BOOST_HAS_FLOAT128\n    test_interpolation_condition<boost::multiprecision::float128>();\n        test_constant<boost::multiprecision::float128>();\n        test_constant_high_order<boost::multiprecision::float128>();\n        test_interpolation_condition_high_order<boost::multiprecision::float128>();\n        test_runge<boost::multiprecision::float128>();\n#endif\n\n}\n", "meta": {"hexsha": "819b31d2be1f8a69e7ff5efeb20c9bd4b6040b08", "size": 8841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/boost/libs/math/test/test_barycentric_rational.cpp", "max_stars_repo_name": "alexhenrie/poedit", "max_stars_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "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": "deps/boost/libs/math/test/test_barycentric_rational.cpp", "max_issues_repo_name": "alexhenrie/poedit", "max_issues_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "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": "deps/boost/libs/math/test/test_barycentric_rational.cpp", "max_forks_repo_name": "alexhenrie/poedit", "max_forks_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "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": 31.462633452, "max_line_length": 198, "alphanum_fraction": 0.604908947, "num_tokens": 2532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5454985290058109}}
{"text": "#include <iostream>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_edge.h>\n#include <g2o/core/base_unary_edge.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 <Eigen/Core>\n#include <opencv2/core/core.hpp>\n#include <cmath>\n#include <chrono>\n#include <boost/concept_check.hpp>\n\nusing namespace std; \nusing namespace g2o;\n//Vertex\u6570\u91cfn,\u8fd9n\u4e2aVertex\u5b58\u50a8\u7684\u6570\u636e\u7c7b\u578b\nclass powell_vertex: public BaseVertex<4, Eigen::Matrix<double,1,4>> {\n\tvirtual void oplusImpl(const double* v) {\n\t\t//base_vertex.h: EstimateType _estimate;\n\t\t//cout << \"oplus: \"  << endl;\n\t\t//cout << Eigen::Matrix<double,1,4>(v) << endl;\n\t\t_estimate += Eigen::Matrix<double,1,4>(v);\n\t\t//cout << \"_estimate: \" << _estimate << endl;\n\t}\n        virtual void setToOriginImpl() {\n\t\t//cout << \"initial _estimate\" << endl;\n\t\t_estimate << 0.5,1.5,2.5,3.5;\n\t}\n\t\n\tvirtual bool read(std::istream& is) {}\n        virtual bool write(std::ostream& os) const {}\t//const \u4e0d\u80fd\u5ffd\u7565\n};\n//e(xi)\u7684\u7ef4\u5ea6\u3001\u7c7b\u578b; vertex\u7684\u7c7b\u578b\nclass powell_edge: public BaseUnaryEdge<4, Eigen::Matrix<double,1,4>, powell_vertex> {\n\tvirtual void computeError() {\n\t\t//vertex* vtx = new vertex;\n\t\tconst powell_vertex* v = static_cast<const powell_vertex*> (_vertices[0]);\n\t\tEigen::Matrix<double,1,4> est =  v->estimate();\n\t\t//cout << \"est: \" << est(0,0)  << \"---\" << est(0,1)  <<\"---\" << est(0,2) <<  \"---\"<< est(0,3) << endl;\n// \t\t_error(0,0) = (&_measurement)[0] - (est(0,0) + 10*est(0,1));\n// \t\t_error(0,1) = (&_measurement)[1] - sqrt(5)*(est(0,2) - est(0,3));\n// \t\t_error(0,2) = (&_measurement)[2] - (est(0,1) - 2*est(0,2))*(est(0,1) - 2*est(0,2));\n// \t\t_error(0,3) = (&_measurement)[3] - sqrt(10)*(est(0,0) - est(0,2))*(est(0,0) - est(0,2));\n\t\t_error(0,0) = _measurement(0,0)- (est(0,0) + 10*est(0,1));\n\t\t_error(1,0) = _measurement(0,1) - sqrt(5)*(est(0,2) - est(0,3));\n\t\t_error(2,0) = _measurement(0,2) - (est(0,1) - 2*est(0,2))*(est(0,1) - 2*est(0,2));\n\t\t_error(3,0) = _measurement(0,3) - sqrt(10)*(est(0,0) - est(0,2))*(est(0,0) - est(0,2));\n\t\tcout << \"_error: \" << _error.transpose() << endl;\n\t}\n\t\n\tvirtual bool read(std::istream& is) {}\n        virtual bool write(std::ostream& os) const {}\t//const \u4e0d\u80fd\u5ffd\u7565\n};\n\nint main(int argc, char **argv) {    \n\t// \u6784\u5efa\u56fe\u4f18\u5316\uff0c\u5148\u8bbe\u5b9ag2o\n\t//\u6ce8\u610f\u7ef4\u5ea6\u5bf9\u5e94--\u8fb9--\u9876\u70b9---\n\ttypedef g2o::BlockSolver< g2o::BlockSolverTraits<4,4> > Block;  // int _PoseDim, int _LandmarkDim\n\tBlock::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>(); // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n\tBlock* solver_ptr = new Block( linearSolver );      // \u77e9\u9635\u5757\u6c42\u89e3\u5668\n\t// \u68af\u5ea6\u4e0b\u964d\u65b9\u6cd5\uff0c\u4eceGN, LM, DogLeg \u4e2d\u9009\n\tcout << \"config blocksolver\" << endl;\n\tg2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg( solver_ptr );\n\t// g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton( solver_ptr );\n\t// g2o::OptimizationAlgorithmDogleg* solver = new g2o::OptimizationAlgorithmDogleg( solver_ptr );\n\tg2o::SparseOptimizer optimizer;     // \u56fe\u6a21\u578b\n\toptimizer.setAlgorithm( solver );   // \u8bbe\u7f6e\u6c42\u89e3\u5668\n\toptimizer.setVerbose( true );       // \u6253\u5f00\u8c03\u8bd5\u8f93\u51fa\n\tcout << \"add Vertex\" << endl;\n\t// \u5f80\u56fe\u4e2d\u589e\u52a0\u9876\u70b9\n\tpowell_vertex* v = new powell_vertex;\n\tEigen::Matrix<double,1,4> estimate_initial;\n\testimate_initial <<0.5,1.5,2.5,3.5;\n\tv->setEstimate(estimate_initial);\n\tv->setId(0);\n\toptimizer.addVertex( v );\n\tcout << \"add Edge\" << endl;\n\t//\u52a0\u8fb9\n\tpowell_edge* eg = new powell_edge;\n\t//double measurement_initial[4] = {21,-sqrt(5),16,9*sqrt(10)};\n\t//for (int i=0;i<4;i++) {\n\t\teg->setId(0);\n\t\teg->setVertex( 0, v );                // \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n\t\tEigen::Matrix<double,1,4> measurement_initial;\n\t\tmeasurement_initial << 21,-sqrt(5),16,9*sqrt(10);\n\t\teg->setMeasurement(measurement_initial);      // \u89c2\u6d4b\u6570\u503c\n\t\t//\u8fd9\u4e2a'4'\u5bf9\u5e94\u4e8epowell_edge\u7b2c\u4e00\u4e2a\u53c2\u6570\n\t\teg->setInformation(Eigen::Matrix<double,4,4>::Identity()*1/0.25); // \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n\t\toptimizer.addEdge( eg );\n\t//}\n\t// \u6267\u884c\u4f18\u5316\n\tcout<<\"start optimization\"<<endl;\n\tchrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n\tcout<<\"initial optimization\"<<endl;\n\toptimizer.initializeOptimization();\n\tcout<<\"start\"<<endl;\n\toptimizer.optimize(200);\n\tchrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n\tchrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>( t2-t1 );\n\tcout<<\"solve time cost = \"<<time_used.count()<<\" seconds. \"<<endl;\n\n\t// \u8f93\u51fa\u4f18\u5316\u503c\n\tEigen::Matrix<double,1,4> abc_estimate = v->estimate();\n\tcout<<\"estimated value: \"<<abc_estimate.transpose()<<endl;\n    \n    return 0;\n}\n", "meta": {"hexsha": "d86a2d64e998f2f620524fd764bc812b716f0578", "size": 4616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "g2o/g2o_powell/main.cpp", "max_stars_repo_name": "JiauZhang/camera", "max_stars_repo_head_hexsha": "37e37f9e5f5176c6c06d4a8fdd11d5532ab37eb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-10-08T01:46:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-11T08:17:44.000Z", "max_issues_repo_path": "g2o/g2o_powell/main.cpp", "max_issues_repo_name": "JiauZhang/Camera", "max_issues_repo_head_hexsha": "37e37f9e5f5176c6c06d4a8fdd11d5532ab37eb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "g2o/g2o_powell/main.cpp", "max_forks_repo_name": "JiauZhang/Camera", "max_forks_repo_head_hexsha": "37e37f9e5f5176c6c06d4a8fdd11d5532ab37eb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-11T07:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-16T04:55:01.000Z", "avg_line_length": 41.5855855856, "max_line_length": 108, "alphanum_fraction": 0.6642114385, "num_tokens": 1652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5454985226061553}}
{"text": "#pragma once\n\n// -*- coding: utf-8 -*-\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <py2cpp/nx2bgl.hpp>\n#include <utility> // for std::pair\n\nusing graph_t = boost::adjacency_list<boost::listS, boost::vecS,\n    boost::directedS, boost::no_property,\n    boost::property<boost::edge_weight_t, int,\n        boost::property<boost::edge_index_t, int>>>;\nusing Vertex = boost::graph_traits<graph_t>::vertex_descriptor;\nusing Edge_it = boost::graph_traits<graph_t>::edge_iterator;\n\ntemplate <typename Container>\ninline auto create_test_case1(const Container& weights) -> xn::grAdaptor<graph_t>\n{\n    using Edge = std::pair<int, int>;\n    const auto num_nodes = 5;\n    enum nodes\n    {\n        A,\n        B,\n        C,\n        D,\n        E\n    };\n    static Edge edge_array[] = {\n        Edge {A, B}, Edge {B, C}, Edge {C, D}, Edge {D, E}, Edge {E, A}};\n    // int weights[] = {-5, 1, 1, 1, 1};\n    int num_arcs = sizeof(edge_array) / sizeof(Edge);\n    auto g = graph_t(edge_array, edge_array + num_arcs, weights, num_nodes);\n    return xn::grAdaptor<graph_t> {std::move(g)};\n}\n\ntemplate <typename Container>\ninline auto create_test_case_timing(const Container& weights)\n    -> xn::grAdaptor<graph_t>\n{\n    using Edge = std::pair<int, int>;\n    constexpr auto num_nodes = 3;\n    enum nodes\n    {\n        A,\n        B,\n        C\n    };\n    static Edge edge_array[] = {Edge {A, B}, Edge {B, A}, Edge {B, C},\n        Edge {C, B}, Edge {B, C}, Edge {C, B}, Edge {C, A}, Edge {A, C}};\n    // int weights[] = {7, 0, 3, 1, 6, 4, 2, 5};\n    constexpr int num_arcs = sizeof(edge_array) / sizeof(Edge);\n    auto g = graph_t(edge_array, edge_array + num_arcs, weights, num_nodes);\n    return xn::grAdaptor<graph_t> {std::move(g)};\n}\n", "meta": {"hexsha": "eba92d6a8c6ea563d1cf96d2ef141cc49f64fd1d", "size": 1759, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/netoptim/test_cases_boost.hpp", "max_stars_repo_name": "luk036/netoptimcpp", "max_stars_repo_head_hexsha": "29b24cea62f5bf70ffc04777ecf92da187110845", "max_stars_repo_licenses": ["MIT"], "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/netoptim/test_cases_boost.hpp", "max_issues_repo_name": "luk036/netoptimcpp", "max_issues_repo_head_hexsha": "29b24cea62f5bf70ffc04777ecf92da187110845", "max_issues_repo_licenses": ["MIT"], "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/netoptim/test_cases_boost.hpp", "max_forks_repo_name": "luk036/netoptimcpp", "max_forks_repo_head_hexsha": "29b24cea62f5bf70ffc04777ecf92da187110845", "max_forks_repo_licenses": ["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.4107142857, "max_line_length": 81, "alphanum_fraction": 0.6196702672, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.5454713199591712}}
{"text": "/**\n * @ file PointEvaluationRhs_main.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 <lf/assemble/assemble.h>\n#include <lf/base/base.h>\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/mesh_hierarchy.h>\n\n#include <Eigen/Core>\n#include <iomanip>\n#include <memory>\n#include <sstream>\n#include <utility>\n#include <vector>\n\n#include \"pointevaluationrhs.h\"\n\nint main() {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(1, 1.0);\n\n  // Start of numerical experiment\n  std::vector<double> dof_a{};\n  std::vector<double> l2_a{};\n  std::vector<double> h1_a{};\n  Eigen::VectorXd sol_vec;\n\n  // Runs with initial mesh\n  lf::assemble::UniformFEDofHandler dofh_initial(\n      mesh_p, {{lf::base::RefEl::kPoint(), 1}});\n  auto result = PointEvaluationRhs::normsSolutionPointLoadDirichletBVP(\n      dofh_initial, Eigen::Vector2d(1.3, 1.7), sol_vec);\n  unsigned N_dofs = dofh_initial.NumDofs();\n  dof_a.push_back(N_dofs);\n  l2_a.push_back(result.first);\n  h1_a.push_back(result.second);\n\n  // Necessary for regular refinement\n  std::unique_ptr<lf::mesh::hybrid2d::MeshFactory> mesh_factory2 =\n      std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::refinement::MeshHierarchy my_hierarchy(mesh_p, std::move(mesh_factory2));\n\n  for (int k = 1; k < 7; k++) {\n    my_hierarchy.RefineRegular();\n\n    mesh_p = my_hierarchy.getMesh(k);\n    lf::assemble::UniformFEDofHandler dofh(mesh_p,\n                                           {{lf::base::RefEl::kPoint(), 1}});\n    unsigned N_dofs = dofh.NumDofs();\n    dof_a.push_back(N_dofs);\n    sol_vec.resize(N_dofs);\n\n    result = PointEvaluationRhs::normsSolutionPointLoadDirichletBVP(\n        dofh, Eigen::Vector2d(1.3, 1.7), sol_vec);\n    l2_a.push_back(result.first);\n    h1_a.push_back(result.second);\n    // Write vtk file\n    std::stringstream filename;\n    filename << \"rhseval\" << k << \".vtk\";\n    lf::io::VtkWriter vtk_writer(mesh_p, filename.str());\n    // need the newest pointer\n    auto mds = lf::mesh::utils::make_CodimMeshDataSet<double>(mesh_p, 2);\n    for (auto *node : mesh_p->Entities(2)) {\n      mds->operator()(*node) = sol_vec(dofh.GlobalDofIndices(*node)[0]);\n    }\n    vtk_writer.WritePointData(\"solution_data\", *mds);\n  }\n\n  // Print to std output\n  std::cout << \" dof      l2         h1 \" << std::endl;\n  for (int i = 0; i < dof_a.size(); i++) {\n    std::cout << std::setw(5) << dof_a.at(i) << \"   \" << std::setw(5)\n              << l2_a.at(i) << \"   \" << std::setw(5) << h1_a.at(i) << std::endl;\n  }\n}\n", "meta": {"hexsha": "60f72de4675acf7ac8c89092b060f487c0d5544c", "size": 2751, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/PointEvaluationRhs/templates/pointevaluationrhs_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/PointEvaluationRhs/templates/pointevaluationrhs_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/PointEvaluationRhs/templates/pointevaluationrhs_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": 33.1445783133, "max_line_length": 80, "alphanum_fraction": 0.657215558, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.5454713121957875}}
{"text": "/*\n * This file is part of the alglib project.\n *\n * (c) Divyanshu Kakwani <divkakwani@gmail.com>\n *\n * For the full copyright and license information, please view the LICENSE file\n * that was distributed with this source code.\n */\n\n#include <iostream>\n#include <alglib/heap/binary_heap.h>\n\nusing namespace alglib::heap;\nusing std::cout;\nusing std::endl;\n\nint main() {\n    /* unkeyed binary heap test */\n    unkeyed_binary_heap<int> h;\n    h.insert(4);\n    h.insert(2);\n    h.insert(12);\n    while (!h.empty()) {\n        cout << h.get_min() << \"\\t\";\n        h.delete_min();\n    }\n    cout << endl;\n\n    /* keyed binary_heap_test */\n    keyed_binary_heap<int, int> kh;\n    kh.insert(4, 20);\n    kh.insert(5, 10);\n    kh.insert(10, 30);\n\n    while (!kh.empty()) {\n        cout << kh.get_min_elt() << \"\\t\";\n        kh.delete_min();\n    }\n    cout << endl;\n}\n", "meta": {"hexsha": "dfc124c77e13596da0ca9611c1c89d2dafdde81e", "size": 855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/heap/binary_heap.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/heap/binary_heap.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/heap/binary_heap.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": 20.8536585366, "max_line_length": 79, "alphanum_fraction": 0.5941520468, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.545471311705484}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"math/tensor.h\" // header to test\n#include \"tools/mapper.h\"\n\nusing namespace biosim;\n\nBOOST_AUTO_TEST_SUITE(suite_tensor)\n\nBOOST_AUTO_TEST_CASE(tensor_rank0) {\n  double d(3.14);\n  math::tensor<double> dbl_tensor({});\n  BOOST_CHECK(dbl_tensor.get_rank() == 0);\n  BOOST_CHECK(dbl_tensor.get_size(0) == 0);\n  dbl_tensor({}) = d;\n  BOOST_CHECK(dbl_tensor({}) == d);\n  BOOST_REQUIRE_THROW(dbl_tensor({5}), std::out_of_range);\n\n  float f(2.17);\n  math::tensor<float> flt_tensor({});\n  BOOST_CHECK(flt_tensor.get_rank() == 0);\n  BOOST_CHECK(flt_tensor.get_size(0) == 0);\n  flt_tensor({}) = f;\n  BOOST_CHECK(flt_tensor({}) == f);\n  BOOST_REQUIRE_THROW(flt_tensor({5}), std::out_of_range);\n\n  int i(-10);\n  math::tensor<int> int_tensor({});\n  BOOST_CHECK(int_tensor.get_rank() == 0);\n  BOOST_CHECK(int_tensor.get_size(0) == 0);\n  int_tensor({}) = i;\n  BOOST_CHECK(int_tensor({}) == i);\n  BOOST_REQUIRE_THROW(int_tensor({5}), std::out_of_range);\n\n  size_t s(25);\n  math::tensor<size_t> szt_tensor({});\n  BOOST_CHECK(szt_tensor.get_rank() == 0);\n  BOOST_CHECK(szt_tensor.get_size(0) == 0);\n  szt_tensor({}) = s;\n  BOOST_CHECK(szt_tensor({}) == s);\n  BOOST_REQUIRE_THROW(szt_tensor({5}), std::out_of_range);\n}\n\nBOOST_AUTO_TEST_CASE(tensor_rank1) {\n  math::tensor<double> t({2});\n  BOOST_CHECK(t.get_rank() == 1);\n  BOOST_CHECK(t.get_size(0) == 2);\n  t({0}) = 10;\n  BOOST_CHECK(t({0}) == 10);\n  t({1}) = 11;\n  BOOST_CHECK(t({1}) == 11);\n  BOOST_REQUIRE_THROW(t({2}), std::out_of_range);\n  BOOST_REQUIRE_THROW(t({1, 5}), std::out_of_range);\n  BOOST_REQUIRE_THROW(t({}), std::out_of_range);\n}\n\nBOOST_AUTO_TEST_CASE(tensor_rank2) {\n  math::tensor<size_t> t({3, 2});\n  BOOST_CHECK(t.get_rank() == 2);\n  BOOST_CHECK(t.get_size(0) == 3);\n  BOOST_CHECK(t.get_size(1) == 2);\n  BOOST_REQUIRE_THROW(t({0, 3}), std::out_of_range);\n\n  size_t input(10);\n  for(size_t pos1(0); pos1 < t.get_size(1); ++pos1) {\n    for(size_t pos0(0); pos0 < t.get_size(0); ++pos0, ++input) {\n      t({pos0, pos1}) = input;\n      BOOST_CHECK(t({pos0, pos1}) == input);\n    } // for\n  } // for\n  BOOST_CHECK(t({2, 0}) == 12); // last value of first row\n  BOOST_CHECK(t({0, 1}) == 13); // first value of second row\n\n  t = math::tensor<size_t>({1, 1});\n  BOOST_CHECK(t.get_rank() == 2);\n  BOOST_CHECK(t.get_size(0) == 1);\n  BOOST_CHECK(t.get_size(1) == 1);\n  BOOST_REQUIRE_THROW(t({0, 1}), std::out_of_range);\n\n  input = 10;\n  for(size_t pos1(0); pos1 < t.get_size(1); ++pos1) {\n    for(size_t pos0(0); pos0 < t.get_size(0); ++pos0, ++input) {\n      t({pos0, pos1}) = input;\n      BOOST_CHECK(t({pos0, pos1}) == input);\n    } // for\n  } // for\n}\n\nBOOST_AUTO_TEST_CASE(tensor_rank3) {\n  math::tensor<size_t> t({4, 3, 2});\n  BOOST_CHECK(t.get_rank() == 3);\n  BOOST_CHECK(t.get_size(0) == 4);\n  BOOST_CHECK(t.get_size(1) == 3);\n  BOOST_CHECK(t.get_size(2) == 2);\n\n  size_t input(10);\n  for(size_t pos2(0); pos2 < t.get_size(2); ++pos2) {\n    for(size_t pos1(0); pos1 < t.get_size(1); ++pos1) {\n      for(size_t pos0(0); pos0 < t.get_size(0); ++pos0, ++input) {\n        t({pos0, pos1, pos2}) = input;\n        BOOST_CHECK(t({pos0, pos1, pos2}) == input);\n      } // for\n    } // for\n  } // for\n}\n\nBOOST_AUTO_TEST_CASE(tensor_rank5) {\n  math::tensor<size_t> t({2, 2, 2, 3, 2});\n  size_t input(10);\n  tools::mapper<std::vector<size_t>> m(t.get_mapper_alphabets());\n  for(size_t i(m.get_min()), i_max(m.get_max()); i <= i_max; ++i, ++input) {\n    std::vector<size_t> pos(m.encode(i));\n    t(pos) = input;\n    BOOST_CHECK(t(pos) == input);\n  } // for\n}\n\nBOOST_AUTO_TEST_CASE(tensor_sub) {\n  math::tensor<size_t> t({3, 3, 3});\n  size_t input(10);\n  for(size_t pos2(0); pos2 < t.get_size(2); ++pos2) {\n    for(size_t pos1(0); pos1 < t.get_size(1); ++pos1) {\n      for(size_t pos0(0); pos0 < t.get_size(0); ++pos0, ++input) {\n        t({pos0, pos1, pos2}) = input;\n        BOOST_CHECK(t({pos0, pos1, pos2}) == input);\n      } // for\n    } // for\n  } // for\n\n  math::tensor<size_t> subt(t.sub({}, {0, 0, 0}));\n  BOOST_CHECK(subt.get_rank() == 0);\n  BOOST_CHECK(subt({}) == 10);\n  BOOST_REQUIRE_THROW(t.sub({}, {0, 1, 3}), std::out_of_range);\n  BOOST_REQUIRE_THROW(t.sub({}, {0, 1, 2, 4}), std::out_of_range);\n\n  subt = t.sub({2}, {2, 1});\n  BOOST_CHECK(subt.get_rank() == 1);\n  BOOST_CHECK(subt.get_size(0) == 3);\n  BOOST_CHECK(subt({0}) == 15);\n  BOOST_CHECK(subt({1}) == 24);\n  BOOST_CHECK(subt({2}) == 33);\n  subt = t.sub({1}, {2, 1});\n  BOOST_CHECK(subt.get_rank() == 1);\n  BOOST_CHECK(subt.get_size(0) == 3);\n  BOOST_CHECK(subt({0}) == 21);\n  BOOST_CHECK(subt({1}) == 24);\n  BOOST_CHECK(subt({2}) == 27);\n  subt = t.sub({0}, {2, 1});\n  BOOST_CHECK(subt.get_rank() == 1);\n  BOOST_CHECK(subt.get_size(0) == 3);\n  BOOST_CHECK(subt({0}) == 25);\n  BOOST_CHECK(subt({1}) == 26);\n  BOOST_CHECK(subt({2}) == 27);\n\n  subt = t.sub({1, 2}, {0});\n  BOOST_CHECK(subt.get_rank() == 2);\n  BOOST_CHECK(subt.get_size(0) == 3);\n  BOOST_CHECK(subt.get_size(1) == 3);\n  BOOST_CHECK(subt({0, 0}) == 10);\n  BOOST_CHECK(subt({1, 0}) == 13);\n  BOOST_CHECK(subt({2, 0}) == 16);\n  BOOST_CHECK(subt({0, 1}) == 19);\n  BOOST_CHECK(subt({0, 2}) == 28);\n  BOOST_CHECK(subt({2, 2}) == 34);\n  subt = t.sub({0, 2}, {0});\n  BOOST_CHECK(subt.get_rank() == 2);\n  BOOST_CHECK(subt.get_size(0) == 3);\n  BOOST_CHECK(subt.get_size(1) == 3);\n  BOOST_CHECK(subt({0, 0}) == 10);\n  BOOST_CHECK(subt({1, 0}) == 11);\n  BOOST_CHECK(subt({2, 0}) == 12);\n  BOOST_CHECK(subt({0, 1}) == 19);\n  BOOST_CHECK(subt({0, 2}) == 28);\n  BOOST_CHECK(subt({2, 2}) == 30);\n  subt = t.sub({0, 1}, {0});\n  BOOST_CHECK(subt.get_rank() == 2);\n  BOOST_CHECK(subt.get_size(0) == 3);\n  BOOST_CHECK(subt.get_size(1) == 3);\n  BOOST_CHECK(subt({0, 0}) == 10);\n  BOOST_CHECK(subt({1, 0}) == 11);\n  BOOST_CHECK(subt({2, 0}) == 12);\n  BOOST_CHECK(subt({0, 1}) == 13);\n  BOOST_CHECK(subt({0, 2}) == 16);\n  BOOST_CHECK(subt({2, 2}) == 18);\n  subt = t.sub({0, 1, 2}, {});\n  BOOST_CHECK(subt.get_rank() == 3);\n  BOOST_CHECK(subt.get_size(0) == 3);\n  BOOST_CHECK(subt.get_size(1) == 3);\n  BOOST_CHECK(subt.get_size(2) == 3);\n  for(size_t pos2(0); pos2 < t.get_size(2); ++pos2) {\n    for(size_t pos1(0); pos1 < t.get_size(1); ++pos1) {\n      for(size_t pos0(0); pos0 < t.get_size(0); ++pos0, ++input) {\n        BOOST_CHECK(t({pos0, pos1, pos2}) == subt({pos0, pos1, pos2}));\n      } // for\n    } // for\n  } // for\n  subt = t.sub({2, 1, 0}, {});\n  BOOST_CHECK(subt.get_rank() == 3);\n  BOOST_CHECK(subt.get_size(0) == 3);\n  BOOST_CHECK(subt.get_size(1) == 3);\n  BOOST_CHECK(subt.get_size(2) == 3);\n  for(size_t pos2(0); pos2 < t.get_size(2); ++pos2) {\n    for(size_t pos1(0); pos1 < t.get_size(1); ++pos1) {\n      for(size_t pos0(0); pos0 < t.get_size(0); ++pos0, ++input) {\n        BOOST_CHECK(t({pos0, pos1, pos2}) == subt({pos0, pos1, pos2}));\n      } // for\n    } // for\n  } // for\n\n  t = math::tensor<size_t>({2, 3, 4});\n  subt = t.sub({0, 1, 2}, {});\n  BOOST_CHECK(subt.get_rank() == 3);\n  BOOST_CHECK(subt.get_size(0) == 2);\n  BOOST_CHECK(subt.get_size(1) == 3);\n  BOOST_CHECK(subt.get_size(2) == 4);\n  for(size_t pos2(0); pos2 < t.get_size(2); ++pos2) {\n    for(size_t pos1(0); pos1 < t.get_size(1); ++pos1) {\n      for(size_t pos0(0); pos0 < t.get_size(0); ++pos0, ++input) {\n        BOOST_CHECK(t({pos0, pos1, pos2}) == subt({pos0, pos1, pos2}));\n      } // for\n    } // for\n  } // for\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e5cc360ec69860fa89f79f0b390895cc0bc4c945", "size": 7332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/tensor.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/tensor.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/tensor.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": 32.4424778761, "max_line_length": 76, "alphanum_fraction": 0.5926077469, "num_tokens": 2659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5454713034517965}}
{"text": "#define BOOST_TEST_MODULE SolutionTest\n\n#include \"solution.hpp\"\n\n//#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(SolutionSuite)\n\nBOOST_AUTO_TEST_CASE(PlainTest1)\n{\n    vector<string> line = {\"2\", \"1\", \"+\", \"3\", \"*\"};\n    int result = Solution().evalRPN(line);\n\n    int expected = 9;\n\n    BOOST_REQUIRE_EQUAL(result, expected);\n}\n\nBOOST_AUTO_TEST_CASE(PlainTest2)\n{\n    vector<string> line = {\"4\", \"13\", \"5\", \"/\", \"+\"};\n    int result = Solution().evalRPN(line);\n\n    int expected = 6;\n\n    BOOST_REQUIRE_EQUAL(result, expected);\n}\n\nBOOST_AUTO_TEST_CASE(PlainTest3)\n{\n    vector<string> line = {\"10\", \"6\", \"9\", \"3\", \"+\", \"-11\", \"*\", \"/\", \"*\", \"17\", \"+\", \"5\", \"+\"};\n    int result = Solution().evalRPN(line);\n\n    int expected = 22;\n\n    BOOST_REQUIRE_EQUAL(result, expected);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "1cdc9235afa12f3d728a3c3eaac19aed1fcb1ea8", "size": 846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "150-Evaluate-Reverse-Polish-Notation/solution_test.cpp", "max_stars_repo_name": "johnhany/leetcode", "max_stars_repo_head_hexsha": "453a86ac16360e44893262e04f77fd350d1e80f2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-05-27T06:47:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T05:57:10.000Z", "max_issues_repo_path": "150-Evaluate-Reverse-Polish-Notation/solution_test.cpp", "max_issues_repo_name": "johnhany/leetcode", "max_issues_repo_head_hexsha": "453a86ac16360e44893262e04f77fd350d1e80f2", "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": "150-Evaluate-Reverse-Polish-Notation/solution_test.cpp", "max_forks_repo_name": "johnhany/leetcode", "max_forks_repo_head_hexsha": "453a86ac16360e44893262e04f77fd350d1e80f2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-04-01T10:26:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T18:21:01.000Z", "avg_line_length": 21.15, "max_line_length": 96, "alphanum_fraction": 0.6382978723, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.545413488785623}}
{"text": "#include <Eigen/Core>\n#include <igl/opengl/glfw/Viewer.h>\n#include <igl/opengl/glfw/imgui/ImGuiMenu.h>\n\n\nint main(int argc, char* argv[])\n{\n\tEigen::MatrixXd V(3, 3);\n\tV <<\n\t\t0, 0, 0,\n\t\t1, 0, 0,\n\t\t1, 1, 0,\n\t\t0, 1, 0;\n\n\n\tEigen::MatrixXi F(2, 3);\n\tF <<\n\t\t0, 1, 2,\n\t\t1, 2, 3;\n\n\n\tigl::opengl::glfw::Viewer viewer;\n\tviewer.data().set_mesh(V, F);\n\n\treturn 0;\n}", "meta": {"hexsha": "c86f42def6b3b282a53fab412dc5705bc2a1a5b7", "size": 353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libigl_playground/main.cpp", "max_stars_repo_name": "neonerd0/libigl_playground", "max_stars_repo_head_hexsha": "4ec4b2412b73e9305353e90ca94efe4296bacc9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libigl_playground/main.cpp", "max_issues_repo_name": "neonerd0/libigl_playground", "max_issues_repo_head_hexsha": "4ec4b2412b73e9305353e90ca94efe4296bacc9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libigl_playground/main.cpp", "max_forks_repo_name": "neonerd0/libigl_playground", "max_forks_repo_head_hexsha": "4ec4b2412b73e9305353e90ca94efe4296bacc9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.5769230769, "max_line_length": 44, "alphanum_fraction": 0.5779036827, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5454134790086317}}
{"text": "/**\n * @file carDynamicsSim.hpp\n * @author Ezra Tal\n * @brief Car dynamics simulator class header file\n * \n */\n\n#ifndef CARDYNAMICSSIM_H\n#define CARDYNAMICSSIM_H\n\n#include <random>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n/**\n * @brief Car dynamics simulator class\n * \n */\nclass CarDynamicsSim{\n    public:\n        CarDynamicsSim(\n            const double maxSteeringAngle,\n            const double minSpeed,\n            const double maxSpeed,\n            const Eigen::Vector2d & velProcNoiseAutoCorr);\n\n        void setNoiseSeed(\n            const unsigned seed);\n\n        void setVehicleProperties(\n            const double maxSteeringAngle,\n            const double minSpeed,\n            const double maxSpeed,\n            const Eigen::Vector2d & velProcNoiseAutoCorr);\n\n        void setVehicleState(\n            const Eigen::Vector2d & position,\n            const Eigen::Vector2d & velocity,\n            const Eigen::Rotation2Dd & heading);\n\n        void getVehicleState(\n            Eigen::Vector2d & position,\n            Eigen::Vector2d & velocity,\n            Eigen::Rotation2Dd & heading);\n\n        void setVehiclePosition(const Eigen::Vector2d & position);\n        void setVehicleVelocity(const Eigen::Vector2d & velocity);\n        void setVehicleHeading(const Eigen::Rotation2Dd & heading);\n        Eigen::Vector2d getVehiclePosition(void);\n        Eigen::Vector2d getVehicleVelocity(void);\n        Eigen::Rotation2Dd getVehicleHeading(void);\n\n        void proceedState_ExplicitEuler(\n            const double dt_secs,\n            const double speed,\n            const double steeringAngle);\n\n    private:\n        /// @name Vehicle properties\n        //@{\n        double maxSteeringAngle_;\n        double minSpeed_;\n        double maxSpeed_;\n        Eigen::Vector2d velocityProcessNoiseAutoCorrelation_;\n        //@}\n\n        /// @name Vehicle state\n        //@{\n        Eigen::Vector2d position_;\n        Eigen::Vector2d velocity_;\n        Eigen::Rotation2Dd heading_;\n        //@}\n\n        /// @name Std normal RNG\n        //@{\n        std::default_random_engine randomNumberGenerator_;\n        std::normal_distribution<double> standardNormalDistribution_ = std::normal_distribution<double>(0.0,1.0);\n        //@}\n\n        Eigen::Vector2d getPositionDerivative(void);\n        double getHeadingDerivative(const double steeringAngle);\n};\n\n#endif // CARDYNAMICSSIM_H", "meta": {"hexsha": "9bf696000f7b2764496fb391b0a8795394dfd22b", "size": 2385, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "carDynamicsSim.hpp", "max_stars_repo_name": "mit-aera/carDynamicsSim", "max_stars_repo_head_hexsha": "a1df6a29f4361d2990e74934214a712a8e7a5898", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "carDynamicsSim.hpp", "max_issues_repo_name": "mit-aera/carDynamicsSim", "max_issues_repo_head_hexsha": "a1df6a29f4361d2990e74934214a712a8e7a5898", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "carDynamicsSim.hpp", "max_forks_repo_name": "mit-aera/carDynamicsSim", "max_forks_repo_head_hexsha": "a1df6a29f4361d2990e74934214a712a8e7a5898", "max_forks_repo_licenses": ["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.3928571429, "max_line_length": 113, "alphanum_fraction": 0.6268343816, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5454134718563819}}
{"text": "//   Boost pow.hpp header file\n//   Computes a power with exponent known at compile-time\n\n//  (C) Copyright Bruno Lalande 2008.\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 for updates, documentation, and revision history.\n\n\n#ifndef BOOST_MATH_POW_HPP\n#define BOOST_MATH_POW_HPP\n\n\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/policies/policy.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <boost/mpl/greater_equal.hpp>\n\n\nnamespace boost {\nnamespace math {\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4702) // Unreachable code, only triggered in release mode and /W4\n#endif\n\nnamespace detail {\n\n\ntemplate <int N, int M = N%2>\nstruct positive_power\n{\n    template <typename T>\n    static T result(T base)\n    {\n        T power = positive_power<N/2>::result(base);\n        return power * power;\n    }\n};\n\ntemplate <int N>\nstruct positive_power<N, 1>\n{\n    template <typename T>\n    static T result(T base)\n    {\n        T power = positive_power<N/2>::result(base);\n        return base * power * power;\n    }\n};\n\ntemplate <>\nstruct positive_power<1, 1>\n{\n    template <typename T>\n    static T result(T base){ return base; }\n};\n\n\ntemplate <int N, bool>\nstruct power_if_positive\n{\n    template <typename T, class Policy>\n    static T result(T base, const Policy&)\n    { return positive_power<N>::result(base); }\n};\n\ntemplate <int N>\nstruct power_if_positive<N, false>\n{\n    template <typename T, class Policy>\n    static T result(T base, const Policy& policy)\n    {\n        if (base == 0)\n        {\n            return policies::raise_overflow_error<T>(\n                       \"boost::math::pow(%1%)\",\n                       \"Attempted to compute a negative power of 0\",\n                       policy\n                   );\n        }\n\n        return T(1) / positive_power<-N>::result(base);\n    }\n};\n\ntemplate <>\nstruct power_if_positive<0, true>\n{\n    template <typename T, class Policy>\n    static T result(T base, const Policy& policy)\n    {\n        if (base == 0)\n        {\n            return policies::raise_indeterminate_result_error<T>(\n                       \"boost::math::pow(%1%)\",\n                       \"The result of pow<0>(%1%) is undetermined\",\n                       base,\n                       T(1),\n                       policy\n                   );\n        }\n\n        return T(1);\n    }\n};\n\n\ntemplate <int N>\nstruct select_power_if_positive\n{\n    typedef typename mpl::greater_equal<\n                         boost::integral_constant<int, N>,\n                         boost::integral_constant<int, 0>\n                     >::type is_positive;\n\n    typedef power_if_positive<N, is_positive::value> type;\n};\n\n\n}  // namespace detail\n\n\ntemplate <int N, typename T, class Policy>\ninline typename tools::promote_args<T>::type pow(T base, const Policy& policy)\n{ \n   typedef typename tools::promote_args<T>::type result_type;\n   return detail::select_power_if_positive<N>::type::result(static_cast<result_type>(base), policy); \n}\n\n\ntemplate <int N, typename T>\ninline typename tools::promote_args<T>::type pow(T base)\n{ return pow<N>(base, policies::policy<>()); }\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\n}  // namespace math\n}  // namespace boost\n\n\n#endif\n", "meta": {"hexsha": "9c92116acd02166e89401ece825321ba06161dc7", "size": 3426, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/lib/include/boost/math/special_functions/pow.hpp", "max_stars_repo_name": "mamil/demo", "max_stars_repo_head_hexsha": "32240d95b80175549e6a1904699363ce672a1591", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2019-02-12T12:53:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:14:38.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/boost/math/special_functions/pow.hpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/boost/math/special_functions/pow.hpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2020-02-27T14:07:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T07:53:36.000Z", "avg_line_length": 22.9932885906, "max_line_length": 101, "alphanum_fraction": 0.619089317, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5453331758467727}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_INV_GAMMA_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_INV_GAMMA_RNG_HPP\n\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_greater_or_equal.hpp>\n#include <stan/math/prim/scal/err/check_less_or_equal.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/fun/lgamma.hpp>\n#include <stan/math/prim/scal/fun/gamma_q.hpp>\n#include <stan/math/prim/scal/fun/digamma.hpp>\n#include <stan/math/prim/scal/meta/length.hpp>\n#include <stan/math/prim/scal/meta/VectorBuilder.hpp>\n#include <stan/math/prim/scal/meta/return_type.hpp>\n#include <stan/math/prim/scal/fun/grad_reg_inc_gamma.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template <class RNG>\n    inline double\n    inv_gamma_rng(double alpha,\n                  double beta,\n                  RNG& rng) {\n      using boost::variate_generator;\n      using boost::random::gamma_distribution;\n\n      static const char* function(\"inv_gamma_rng\");\n\n      check_positive_finite(function, \"Shape parameter\", alpha);\n      check_positive_finite(function, \"Scale parameter\", beta);\n\n      variate_generator<RNG&, gamma_distribution<> >\n        gamma_rng(rng, gamma_distribution<>(alpha, 1 / beta));\n      return 1 / gamma_rng();\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "639b9c324795a70d2adf1e832cec584db99132dd", "size": 1663, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/inv_gamma_rng.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/inv_gamma_rng.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/inv_gamma_rng.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3829787234, "max_line_length": 64, "alphanum_fraction": 0.7456404089, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5453331701227206}}
{"text": "#include <boost/functional/hash.hpp>\n#include <unordered_map>\n#include <memory>\n#include \"MPIProvider.hpp\"\n#include \"BayesOptVQEBackend.hpp\"\n#include <boost/math/constants/constants.hpp>\n\nnamespace xacc {\nnamespace vqe {\n\nconst VQETaskResult BayesOptVQEBackend::minimize(Eigen::VectorXd parameters) {\n\n\tVQETaskResult r;\n\tconst int dim = parameters.size();\n\tauto pi = boost::math::constants::pi<double>();\n\tauto computeTask = std::make_shared<ComputeEnergyVQETask>(program);\n\tbayesopt::Parameters par;\n\tpar = initialize_parameters_to_default();\n\tpar.n_iterations = xacc::optionExists(\"bo-n-iter\") ? std::stoi(xacc::getOption(\"bo-n-iter\")) : par.n_iterations;\n\tpar.noise = xacc::optionExists(\"bo-noise\") ? std::stod(xacc::getOption(\"bo-noise\")) : par.noise;\n\tpar.l_type = xacc::optionExists(\"bo-learn-type\") ? str2learn(xacc::getOption(\"bo-learn-type\").c_str()) : par.l_type;\n\tpar.n_init_samples = xacc::optionExists(\"bo-n-init-iter\") ? std::stoi(xacc::getOption(\"bo-n-init-iter\")) : par.n_init_samples;\n\tpar.verbose_level = xacc::optionExists(\"bo-verbose-level\") ? std::stoi(xacc::getOption(\"bo-verbose-level\")) : par.verbose_level;\n\tpar.epsilon = xacc::optionExists(\"bo-epsilon\") ? std::stod(xacc::getOption(\"bo-epsilon\")) : par.epsilon;\n\tpar.crit_name = xacc::optionExists(\"bo-crit-name\") ? std::string(xacc::getOption(\"bo-crit-name\")) : par.crit_name;\n\tpar.kernel.name = xacc::optionExists(\"bo-kernel-name\") ? std::string(xacc::getOption(\"bo-kernel-name\")) : par.kernel.name;\n\tpar.sc_type = xacc::optionExists(\"bo-score-type\") ? str2score(xacc::getOption(\"bo-score-type\").c_str()) : par.sc_type;\n\tpar.surr_name = xacc::optionExists(\"bo-surrogate-name\") ? std::string(xacc::getOption(\"bo-surrogate-name\")) : par.surr_name;\n\tpar.mean.name = xacc::optionExists(\"bo-mean-name\") ? std::string(xacc::getOption(\"bo-mean-name\")) : par.mean.name;\n\t//par.kernel.hp_mean = xacc::optionExists(\"bo-kernel-mean\") ? std::stod(xacc::getOption(\"bo-kernel-mean\")) : par.kernel.hp_mean;\n\t//par.kernel.hp_std = xacc::optionExists(\"bo-kernel-std\") ? std::stod(xacc::getOption(\"bo-kernel-std\")) : par.kernel.hp_std;\n\tVQEBayesOptFunction f(par, computeTask, dim);\n\n\t// Map parameters to boost vector\n\n\tboost::numeric::ublas::vector<double> result(dim);\n\tdouble* p = parameters.data();\n\tstd::copy(result.begin(), result.end(), p);\n\n\tboost::numeric::ublas::vector<double> lowerBound(dim);\n\tboost::numeric::ublas::vector<double> upperBound(dim);\n\tfor (int i = 0; i < dim; i++) {lowerBound[i] = -1*pi;upperBound[i] = pi;}\n\n\tf.setBoundingBox(lowerBound,upperBound);\n\n\tf.optimize(result);\n\n\tr.energy = f.getValueAtMinimum();\n\tauto resultAngles = f.getFinalResult();\n\tconst double * data = &(resultAngles.data()[0]);\n  r.angles = Eigen::Map<const Eigen::VectorXd>(data, parameters.size());\n\n\treturn r;\n\n}\n\n}\n}\n", "meta": {"hexsha": "47d79b94f9bb35badc68f88d7f631350ceb62530", "size": 2782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "backend/BayesOptVQEBackend.cpp", "max_stars_repo_name": "zpparks314/xacc-vqe-bayesopt", "max_stars_repo_head_hexsha": "0c01904350f2e79f654d4f8edcc04f3908b916e9", "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": "backend/BayesOptVQEBackend.cpp", "max_issues_repo_name": "zpparks314/xacc-vqe-bayesopt", "max_issues_repo_head_hexsha": "0c01904350f2e79f654d4f8edcc04f3908b916e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "backend/BayesOptVQEBackend.cpp", "max_forks_repo_name": "zpparks314/xacc-vqe-bayesopt", "max_forks_repo_head_hexsha": "0c01904350f2e79f654d4f8edcc04f3908b916e9", "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": 47.1525423729, "max_line_length": 129, "alphanum_fraction": 0.7156721783, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5453331541159477}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <Eigen/Core>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/eigen/vector.hpp>\n#include <boost/numeric/bindings/eigen/matrix.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include \"print.hpp\"\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef ublas::vector<double> vector;\n    typedef ublas::matrix<double, ublas::column_major> matrix;\n    typedef vector::size_type size_type;\n    rand_normal<double>::reset();\n    size_type m=6, n=8;\n    matrix A(m, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<m; ++i) \n  \tA(i, j)=rand_normal<double>::get();\n    vector x(m);\n    for (size_type i=0; i<m; ++i)\n      x(i)=rand_normal<double>::get();\n    vector y(n);\n    for (size_type i=0; i<n; ++i)\n      y(i)=rand_normal<double>::get();\n    double alpha(rand_normal<double>::get());\n    matrix A1(alpha*ublas::outer_prod(x, y)+A);\n    matrix A2(A);\n    blas::gerh(alpha, x, y, A2);\n    std::cout << print_mat(A1) << '\\n'\n  \t      << print_mat(A2) << '\\n';\n  }\n  {\n    typedef std::complex<double> complex;\n    typedef ublas::vector<complex> vector;\n    typedef ublas::matrix<complex, ublas::column_major> matrix;\n    typedef vector::size_type size_type;\n    rand_normal<complex>::reset();\n    size_type m=6, n=8;\n    matrix A(m, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<m; ++i) \n \tA(i, j)=rand_normal<complex>::get();\n    vector x(m);\n    for (size_type i=0; i<m; ++i)\n      x(i)=rand_normal<complex>::get();\n    vector y(n);\n    for (size_type i=0; i<n; ++i)\n      y(i)=rand_normal<complex>::get();\n    complex alpha(rand_normal<complex>::get());\n    matrix A1(alpha*ublas::outer_prod(x, ublas::conj(y))+A);\n    matrix A2(A);\n    blas::gerh(alpha, x, y, A2);\n    std::cout << print_mat(A1) << '\\n'\n\t      << print_mat(A2) << '\\n';\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "821b15613178608e90f40518ce919e8a6e113d38", "size": 2151, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/gerh.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/gerh.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/gerh.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.6323529412, "max_line_length": 63, "alphanum_fraction": 0.6317991632, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.545333148974587}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2014, Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\r\n\r\n// Licensed under the Boost Software License version 1.0.\r\n// http://www.boost.org/users/license.html\r\n\r\n#ifndef BOOST_TEST_MODULE\r\n#define BOOST_TEST_MODULE test_math_sqrt\r\n#endif\r\n\r\n#include <cmath>\r\n#include <iostream>\r\n\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\n#include <boost/config.hpp>\r\n#include <boost/type_traits/is_fundamental.hpp>\r\n\r\n#include \"number_types.hpp\"\r\n\r\n// important: the include above must precede the include below,\r\n// otherwise the test will fail for the custom number type:\r\n// custom_with_global_sqrt\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/geometry/algorithms/not_implemented.hpp>\r\n\r\n#ifdef HAVE_TTMATH\r\n#  include <boost/geometry/extensions/contrib/ttmath_stub.hpp>\r\n#endif\r\n\r\nnamespace bg = boost::geometry;\r\n\r\n\r\n\r\n\r\n// call BOOST_CHECK\r\ntemplate <typename Argument, bool IsFundamental /* true */>\r\nstruct check\r\n{\r\n    template <typename Result>\r\n    static inline void apply(Argument const& arg, Result const& result)\r\n    {\r\n        BOOST_CHECK_CLOSE(static_cast<double>(bg::math::sqrt(arg)),\r\n                          static_cast<double>(result),\r\n                          0.00001);        \r\n    }\r\n};\r\n\r\n\r\ntemplate <typename Argument>\r\nstruct check<Argument, false>\r\n{\r\n    template <typename Result>\r\n    static inline void apply(Argument const& arg, Result const& result)\r\n    {\r\n        Result const tol(0.00001);\r\n        BOOST_CHECK( bg::math::abs(bg::math::sqrt(arg) - result) < tol );\r\n    }\r\n};\r\n\r\n\r\n\r\n\r\n\r\n\r\n// test sqrt return type and value\r\ntemplate\r\n<\r\n    typename Argument,\r\n    typename ExpectedResult,\r\n    typename Result = typename bg::math::detail::square_root\r\n        <\r\n            Argument\r\n        >::return_type,\r\n    bool IsFundamental = boost::is_fundamental<Argument>::value\r\n>\r\nstruct check_sqrt\r\n    : bg::not_implemented<Argument, Result, ExpectedResult>\r\n{};\r\n\r\n\r\ntemplate <typename Argument, typename Result, bool IsFundamental>\r\nstruct check_sqrt<Argument, Result, Result, IsFundamental>\r\n{\r\n    static inline void apply(Argument const& arg, Result const& result)\r\n    {\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n        std::cout << \"testing: \" << typeid(Result).name()\r\n                  << \" sqrt(\" << typeid(Argument).name()\r\n                  << \")\" << std::endl;\r\n#endif\r\n        check<Argument, IsFundamental>::apply(arg, result);\r\n    }\r\n};\r\n\r\n\r\n\r\n\r\n\r\n\r\n// test cases\r\nBOOST_AUTO_TEST_CASE( test_math_sqrt_fundamental )\r\n{\r\n    static const double sqrt2 = std::sqrt(2.0);\r\n    static const long double sqrt2L = std::sqrt(2.0L);\r\n    static const float sqrt2F = std::sqrt(2.0F);\r\n\r\n    check_sqrt<float, float>::apply(2.0F, sqrt2F);\r\n    check_sqrt<double, double>::apply(2.0, sqrt2);\r\n    check_sqrt<long double, long double>::apply(2.0L, sqrt2L);\r\n\r\n    check_sqrt<char, double>::apply(2, sqrt2);\r\n    check_sqrt<signed char, double>::apply(2, sqrt2);\r\n    check_sqrt<short, double>::apply(2, sqrt2);\r\n    check_sqrt<int, double>::apply(2, sqrt2);\r\n    check_sqrt<long, double>::apply(2L, sqrt2);\r\n#if !defined(BOOST_NO_LONG_LONG)\r\n    check_sqrt<long long, double>::apply(2LL, sqrt2);\r\n#endif\r\n#ifdef BOOST_HAS_LONG_LONG\r\n    check_sqrt\r\n        <\r\n            boost::long_long_type, double\r\n        >::apply(boost::long_long_type(2), sqrt2);\r\n#endif\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_math_sqrt_custom )\r\n{\r\n    typedef number_types::custom<double> custom1;\r\n    typedef custom_global<double> custom2;\r\n    typedef number_types::custom_with_global_sqrt<double> custom3;\r\n\r\n    static const double sqrt2 = std::sqrt(2.0);\r\n\r\n    check_sqrt<custom1, custom1>::apply(custom1(2.0), custom1(sqrt2));\r\n    check_sqrt<custom2, custom2>::apply(custom2(2.0), custom2(sqrt2));\r\n    check_sqrt<custom3, custom3>::apply(custom3(2.0), custom3(sqrt2));\r\n\r\n#ifdef HAVE_TTMATH\r\n    typedef ttmath_big custom4;\r\n    typedef ttmath::Big<1, 4> custom5;\r\n\r\n    check_sqrt<custom4, custom4>::apply(custom4(2.0), custom4(sqrt2));\r\n    check_sqrt<custom5, custom5>::apply(custom5(2.0), custom5(sqrt2));\r\n#endif\r\n}\r\n", "meta": {"hexsha": "4f4b7c7201e3e348356b86f5e418853e837d7b82", "size": 4200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/util/math_sqrt.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/test/util/math_sqrt.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/test/util/math_sqrt.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": 27.2727272727, "max_line_length": 74, "alphanum_fraction": 0.6628571429, "num_tokens": 1028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.5453171090786528}}
{"text": "/*******\nedit_distance: STL and Boost compatible edit distance functions for C++\n\nCopyright (c) 2013 Erik Erlandson\n\nAuthor:  Erik Erlandson <erikerlandson@yahoo.com>\n\nDistributed under the Boost Software License, Version 1.0.\nSee accompanying file LICENSE or copy at\nhttp://www.boost.org/LICENSE_1_0.txt\n*******/\n\n#include <ctype.h>\n\n#include \"edit_distance_common.hpp\"\n\n\n// get the edit_alignment() function\n#include <boost/algorithm/sequence/edit_distance.hpp>\nusing boost::algorithm::sequence::edit_distance;\nusing boost::algorithm::sequence::unit_cost;\nusing namespace boost::algorithm::sequence::parameter;\n\n\n// define a custom cost function where case changes cost less\nstruct cost_case_less {\n    typedef float cost_type;     // edit costs may be fractional\n\n    cost_type insertion(char c) const { return 1; }\n    cost_type deletion(char c) const { return 1; }\n\n    // changes in case cost less than other edit operations:\n    cost_type substitution(char c, char d) const { \n        if (toupper(c) == toupper(d)) return 0.5;\n        return 1;\n    }\n};\n\n\nint main(int argc, char** argv) {\n    char const* str1 = \"Try to find XXX capitalized\";\n    char const* str2 = \"xxx\";\n\n    // Match the substring 'xxx' against the larger string, with cheap case changes,\n    // identifies the correct location of 'XXX' in the larger string\n    stringstream_tuple_output<cost_case_less, char const*> out;\n    float dist = edit_distance(str1, str2, _script = out, _cost = cost_case_less(), _substitution=true);\n    std::cout << \"dist= \" << dist << \"   edit operations=  \\\"\" << out.ss.str() << \"\\\"\\n\";    \n\n    // compare to the behavior with the default cost function:\n    out.ss.str(\"\");\n    dist = edit_distance(str1, str2, _script = out, _substitution=true);\n    std::cout << \"dist= \" << dist << \"   edit operations=  \\\"\" << out.ss.str() << \"\\\"\\n\";    \n\n    return 0;\n}\n", "meta": {"hexsha": "9951620b2c468d7d534aa00b78df531ede79d07b", "size": 1867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/edit_script_cost_example.cpp", "max_stars_repo_name": "xietian1/mpkix-judgement", "max_stars_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-10-22T05:25:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T14:03:12.000Z", "max_issues_repo_path": "example/edit_script_cost_example.cpp", "max_issues_repo_name": "xietian1/mpkix-judgement", "max_issues_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-01-23T20:26:59.000Z", "max_issues_repo_issues_event_max_datetime": "2015-01-23T20:26:59.000Z", "max_forks_repo_path": "example/edit_script_cost_example.cpp", "max_forks_repo_name": "xietian1/mpkix-judgement", "max_forks_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-27T04:38:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-27T04:38:41.000Z", "avg_line_length": 32.7543859649, "max_line_length": 104, "alphanum_fraction": 0.6813069095, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.5453171009231259}}
{"text": "#pragma once\n\n#include <polyvec/core/macros.hpp>\n#include <polyvec/core/types.hpp>\n#include <polyvec/utils/num.hpp>\n#include <polyvec/geometry/path.hpp>\n#include <polyvec/utils/matrix.hpp>\n\n#include <Eigen/Geometry>\n\n#define PF_RAD(deg) ((double)deg * M_PI / 180.)\n#define PF_DEG(rad) ((double)rad * 180. / M_PI)\n#define PF_ISNAN(v) (!((v) == (v)))\n\nNAMESPACE_BEGIN(polyfit)\nNAMESPACE_BEGIN(AngleUtils)\n\n/*\n\tReturns true if both points are in the same quadrant. The test is inclusive\n\tif any of the two points lie exactly along one of the axis.\n*/\nPV_INLINE bool lie_in_the_same_quadrant(\n\tconst vec2& p0,\n\tconst vec2& p1\n);\n\nPV_INLINE double deviation_from_horizontal(const vec2& d);\nPV_INLINE double deviation_from_horizontal(double angle);\n\nPV_INLINE double deviation_from_vertical(const vec2& d);\nPV_INLINE double deviation_from_vertical(double angle);\n\nPV_INLINE double spanned_shortest(const vec2 & p0, const vec2 & p1, const vec2 & p2);\n\nPV_INLINE double spanned_shortest_between(const vec2 & d0, const vec2 & d1);\n\nPV_INLINE double spanned_clockwise_between(const vec2& d0, const vec2& d1);\n\nPV_INLINE bool have_opposite_convexity(const vec2 & p0, const vec2 & p1, const vec2 & p2, const vec2 & p3);\n\nPV_INLINE bool have_opposite_convexity_with_tol(const vec2 & p0, const vec2 & p1, const vec2 & p2, const vec2 & p3);\n\nPV_INLINE int count_inflections(const mat2x & points, bool circular = true);\n\nPV_INLINE bool is_flat(const vec2 pp, const vec2 p, const vec2 pn);\n\nPV_INLINE int convexity(const vec2 pp, const vec2 p, const vec2 pn, int orientation);\n\nPV_INLINE int number_of_neighbors_with_different_convexity(const Eigen::Matrix2Xd& polygon, int corner);\n\n// convexity should be writable for 1 + 2 * neighborhood_size elements\n// the polygon should contain enough elements before and after the first/last neighboring corners to be able to compute the convexity\nPV_INLINE void neighborhood_convexity(const Eigen::Matrix2Xd& P, const int corner, const int neighborhood_size, int* convexity);\n\n/*\n\tReturns the number of edges in P which overlap 1-pixel axis-aligned steps in B.\n\n\tB is assumed to be the raster boundary which P is approximating, though there are \n\tno requirements on the points except that they should have the same ordering.\n*/\nPV_INLINE int count_visually_degenerate_edges(\n\tconst mat2x& B, \n\tconst vecXi& P, \n\tconst bool circular = false\n);\n\nPV_INLINE int count_visually_inconsistent_edges(const mat2x & P, bool circular = false);\n\n#include \"angle.inl\"\n\nNAMESPACE_END(AngleUtils)\nNAMESPACE_END(polyfit)", "meta": {"hexsha": "27ec7a6451b2e4881e8f000b9556d65336562d86", "size": 2529, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/polyvec/geometry/angle.hpp", "max_stars_repo_name": "ShnitzelKiller/polyfit", "max_stars_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T17:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:49:12.000Z", "max_issues_repo_path": "include/polyvec/geometry/angle.hpp", "max_issues_repo_name": "ShnitzelKiller/polyfit", "max_issues_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T07:19:22.000Z", "max_forks_repo_path": "include/polyvec/geometry/angle.hpp", "max_forks_repo_name": "ShnitzelKiller/polyfit", "max_forks_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T23:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:06:07.000Z", "avg_line_length": 35.125, "max_line_length": 133, "alphanum_fraction": 0.7765915382, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5453170920813946}}
{"text": "/******************************************************************************\n * Author:   Laurent Kneip                                                    *\n * Contact:  kneip.laurent@gmail.com                                          *\n * License:  Copyright (c) 2013 Laurent Kneip, ANU. 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 * * 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 ANU nor the names of its contributors may be         *\n *   used to endorse or promote products derived from this software without   *\n *   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 ANU OR THE 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         *\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 * \\file arun.hpp\n * \\brief Arun's method for computing the rotation between two point sets.\n */\n\n#ifndef OPENGV_ARUN_HPP_\n#define OPENGV_ARUN_HPP_\n\n#include <stdlib.h>\n#include <Eigen/Eigen>\n#include <opengv/types.hpp>\n\n/**\n * \\brief The namespace of this library.\n */\nnamespace opengv\n{\n/**\n * \\brief The namespace of the math tools.\n */\nnamespace math\n{\n\n/**\n * \\brief Arun's method for computing the rotation between two point sets.\n *        Core function [13].\n *\n * \\param[in] Hcross The summation over the exterior products between the\n *            normalized points.\n * \\return The rotation matrix that aligns the points.\n */\nrotation_t arun( const Eigen::MatrixXd & Hcross );\n\n/**\n * \\brief Arun's method for complete point cloud alignment [13]. The method\n *        actually does the same than threept_arun, but has a different\n *        interface.\n *\n * \\param[in] p1 The points expressed in the first frame.\n * \\param[in] p2 The points expressed in the second frame.\n * \\return The Transformation from frame 2 to frame 1 (\n *         \\f$ \\mathbf{T} = \\left(\\begin{array}{cc} \\mathbf{R} & \\mathbf{t} \\end{array}\\right) \\f$,\n *         with \\f$ \\mathbf{t} \\f$ being the position of frame 2 seen from\n *         frame 1, and \\f$ \\mathbf{R} \\f$ being the rotation from\n *         frame 2 to frame 1).\n */\ntransformation_t arun_complete( const points_t & p1, const points_t & p2 );\n\n}\n}\n\n#endif /* OPENGV_ARUN_HPP_ */\n", "meta": {"hexsha": "b85a033586f1bf1e1c203e2e9b1174e69c0863b6", "size": 3753, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/opengv/math/arun.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "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/opengv/math/arun.hpp", "max_issues_repo_name": "PXLVision/opengv", "max_issues_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/opengv/math/arun.hpp", "max_forks_repo_name": "PXLVision/opengv", "max_forks_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "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": 45.2168674699, "max_line_length": 99, "alphanum_fraction": 0.5835331735, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410784, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5452929281243526}}
{"text": "/*******************************************************************************\n * Adaptive array domain\n *\n * Initially, an array is modeled by mapping sequences of consecutive\n * bytes (segments) to cells. A cell is pair <offset, size> where:\n *\n * - offset is an unsigned number\n * - size is an unsigned number\n *\n * A cell, when associated to an array A, is mapped to a scalar\n * variable in the base domain representing the byte contents of the\n * array segment A[offset,...,offset+size-1]\n *\n * The domain is general enough to represent any possible sequence of\n * consecutive bytes including sequences of bytes starting at the same\n * offsets but different sizes, overlapping sequences starting at\n * different offsets, etc.\n *\n * However, the domain only keeps track precisely of all bytes\n * contents as long as array writes use constant indexes. If an array\n * write with a non-constant index occurs then the array is _smashed_\n * into a single summarized variable. After that, all array writes are\n * modeled as weak updates but we still ensure that the number of\n * accessed bytes and the offset are consistent with previous array\n * accesses.\n ******************************************************************************/\n\n#pragma once\n\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/abstract_domain_params.hpp>\n#include <crab/domains/abstract_domain_specialized_traits.hpp>\n#include <crab/domains/array_smashing.hpp>\n#include <crab/domains/interval.hpp>\n#include <crab/domains/patricia_trees.hpp>\n#include <crab/support/debug.hpp>\n#include <crab/support/stats.hpp>\n#include <crab/types/indexable.hpp>\n\n#include <algorithm>\n#include <functional>\n#include <set>\n#include <unordered_map>\n#include <vector>\n\n#include <boost/optional.hpp>\n\nnamespace crab {\nnamespace domains {\n\n// forward declaration\ntemplate <typename Domain> class array_adaptive_domain;\n\nnamespace array_adaptive_impl {\n\n// Trivial constant propagation lattice\nclass cp_domain_t {\n  using bound_t = ikos::bound<ikos::z_number>;\n\n  bool m_is_bottom;\n  bound_t m_val;\n\n  void set_to_top();\n\n  void set_to_bot();\n\n  cp_domain_t(bool is_bottom);\n\npublic:\n  cp_domain_t();\n\n  cp_domain_t(int64_t sz);\n\n  cp_domain_t(const ikos::interval<ikos::z_number> &sz);\n\n  bool is_top() const;\n\n  bool is_bottom() const;\n\n  bool is_zero() const; \n\n  bool is_negative() const; \n\n  bound_t val() const;\n\n  boost::optional<uint64_t> get_uint64_val() const;\n\n  static cp_domain_t bottom();\n\n  static cp_domain_t top();\n\n  bool operator==(const cp_domain_t &o) const;\n\n  bool operator<=(const cp_domain_t &o) const;\n\n  void operator|=(const cp_domain_t &o);\n\n  cp_domain_t operator|(const cp_domain_t &o) const;\n\n  cp_domain_t operator&(const cp_domain_t &o) const;\n\n  cp_domain_t operator||(const cp_domain_t &o) const;\n\n  cp_domain_t operator&&(const cp_domain_t &o) const;\n\n  void write(crab_os &o) const;\n};\n\n// forward declaration\nclass offset_map;\n\n/*\n * Wrapper for using ikos::index_t as patricia_tree keys\n */\nclass offset_t : public indexable {\n  ikos::index_t m_val;\n\npublic:\n  explicit offset_t(ikos::index_t v);\n\n  virtual ikos::index_t index() const override;\n\n  size_t hash() const;\n\n  bool operator<(const offset_t &o) const;\n\n  bool operator==(const offset_t &o) const;\n\n  bool operator!=(const offset_t &o) const;\n\n  offset_t operator%(const offset_t &o) const;\n\n  offset_t operator-(const offset_t &o) const;\n\n  bool is_negative() const;\n\n  bool is_zero() const;\n\n  virtual void write(crab::crab_os &o) const override;\n\n  friend crab::crab_os &operator<<(crab::crab_os &o, const offset_t &v) {\n    v.write(o);\n    return o;\n  }\n};\n\n/*\n *  A synthetic cell is used to give a symbolic name to the byte\n *  contents of some array segment represented by\n *\n *     [m_offset, m_offset+1,...,m_offset+m_size-1]\n *\n */\nclass cell_t {\nprivate:\n  friend class offset_map_t;\n  using interval_t = ikos::interval<ikos::z_number>;\n  offset_t m_offset;\n  uint64_t m_size;\n  //// Boolean flag to indicate if the cell has been removed.  When\n  //// smashing is enabled we need to know which cells have been\n  //// created and join them regardless whether they have been removed\n  //// or not. If this flag is enabled then overlap and\n  //// symbolic_overlap pretend the cell does not exist and return\n  //// always false but the cell is not destroyed.\n  bool m_removed;\n\n  // Only offset_map class can create cells\n  cell_t();\n\n  cell_t(offset_t offset, uint64_t size);\n\n  static interval_t to_interval(const offset_t o, uint64_t size);\n\n  interval_t to_interval() const;\n\npublic:\n  bool is_null() const;\n\n  offset_t get_offset() const;\n\n  size_t get_size() const;\n\n  cell_t clone(void) const;\n\n  void mark_as_removed(bool v);\n\n  bool is_removed(void) const;\n\n  size_t hash() const;\n\n  // inclusion test\n  bool operator<=(const cell_t &o) const;\n\n  bool operator==(const cell_t &o) const;\n\n  bool operator<(const cell_t &o) const;\n\n  // Return true if [o, o+size) definitely overlaps with the cell,\n  // where o is a constant expression.\n  bool overlap(const offset_t &o, uint64_t size) const;\n\n  // Return true if [symb_lb, symb_ub] may overlap with the cell,\n  // where symb_lb and symb_ub are not constant expressions.\n  template <typename Dom>\n  bool symbolic_overlap(const typename Dom::linear_expression_t &symb_lb,\n                        const typename Dom::linear_expression_t &symb_ub,\n                        const Dom &dom) const {\n    if (m_removed)\n      return false;\n\n    using linear_expression_t = typename Dom::linear_expression_t;\n\n    interval_t x = to_interval();\n    assert(x.lb().is_finite());\n    assert(x.ub().is_finite());\n    linear_expression_t lb(*(x.lb().number()));\n    linear_expression_t ub(*(x.ub().number()));\n\n    CRAB_LOG(\"array-adaptive-overlap\", Dom tmp(dom);\n             linear_expression_t tmp_symb_lb(symb_lb);\n             linear_expression_t tmp_symb_ub(symb_ub);\n             crab::outs() << \"**Checking if \" << *this\n                          << \" overlaps with symbolic \"\n                          << \"[\" << tmp_symb_lb << \",\" << tmp_symb_ub << \"]\"\n                          << \" with abstract state=\" << tmp << \"\\n\";);\n\n    Dom tmp1(dom);\n    tmp1 += (lb >= symb_lb);\n    tmp1 += (lb <= symb_ub);\n    if (!tmp1.is_bottom()) {\n      CRAB_LOG(\"array-adaptive-overlap\", crab::outs() << \"\\tyes.\\n\";);\n      return true;\n    }\n\n    Dom tmp2(dom);\n    tmp2 += (ub >= symb_lb);\n    tmp2 += (ub <= symb_ub);\n    if (!tmp2.is_bottom()) {\n      CRAB_LOG(\"array-adaptive-overlap\", crab::outs() << \"\\tyes.\\n\";);\n      return true;\n    }\n\n    CRAB_LOG(\"array-adaptive-overlap\", crab::outs() << \"\\tno.\\n\";);\n    return false;\n  }\n\n  void write(crab::crab_os &o) const;\n\n  friend crab::crab_os &operator<<(crab::crab_os &o, const cell_t &c) {\n    c.write(o);\n    return o;\n  }\n};\n\nnamespace cell_set_impl {\ntemplate <typename Set> inline Set set_intersection(Set &s1, Set &s2) {\n  Set s3;\n  std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),\n                        std::inserter(s3, s3.end()));\n  return s3;\n}\n\ntemplate <typename Set> inline Set set_union(Set &s1, Set &s2) {\n  Set s3;\n  std::set_union(s1.begin(), s1.end(), s2.begin(), s2.end(),\n                 std::inserter(s3, s3.end()));\n  return s3;\n}\n\ntemplate <typename Set> inline bool set_inclusion(Set &s1, Set &s2) {\n  Set s3;\n  std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),\n                      std::inserter(s3, s3.end()));\n  return s3.empty();\n}\n\ntemplate <typename Set> inline Set set_difference(Set &s1, Set &s2) {\n  Set s3;\n  std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),\n                      std::inserter(s3, s3.end()));\n  return s3;\n}\n\ntemplate <typename Set>\ninline Set set_difference(Set &s1, const typename Set::key_type &e) {\n  Set s3;\n  Set s2;\n  s2.insert(e);\n  std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),\n                      std::inserter(s3, s3.end()));\n  return s3;\n}\n} // end namespace cell_set_impl\n\n/*\n * A Patricia tree that maps numerical offsets to synthetic cells.\n */\nclass offset_map_t {\nprivate:\n  template <typename Dom>\n  friend class crab::domains::array_adaptive_domain;\n\n  using cell_set_t = std::set<cell_t>;\n\n  /*\n    The keys in the patricia tree are processing in big-endian\n    order. This means that the keys are sorted. Sortedeness is\n    very important to perform efficiently operations such as\n    checking for overlap cells. Since keys are treated as bit\n    patterns, negative offsets can be used but they are treated\n    as large unsigned numbers.\n  */\n  using patricia_tree_t = ikos::patricia_tree<offset_t, cell_set_t>;\n  using binary_op_t = typename patricia_tree_t::binary_op_t;\n  using partial_order_t = typename patricia_tree_t::partial_order_t;\n\n  patricia_tree_t m_map;\n\n  // for algorithm::lower_bound and algorithm::upper_bound\n  struct compare_binding_t {\n    bool operator()(const typename patricia_tree_t::binding_t &kv,\n                    const offset_t &o) const {\n      return kv.first < o;\n    }\n    bool operator()(const offset_t &o,\n                    const typename patricia_tree_t::binding_t &kv) const {\n      return o < kv.first;\n    }\n    bool operator()(const typename patricia_tree_t::binding_t &kv1,\n                    const typename patricia_tree_t::binding_t &kv2) const {\n      return kv1.first < kv2.first;\n    }\n  };\n\n  patricia_tree_t apply_operation(binary_op_t &o, patricia_tree_t t1,\n                                  const patricia_tree_t &t2) const {\n    bool res = t1.merge_with(t2, o);\n    if (res) {\n      CRAB_ERROR(\"array_adaptive::offset_map should not return bottom\");\n    }\n    return t1;\n  }\n\n  class join_op : public binary_op_t {\n    // apply is called when two bindings (one each from a\n    // different map) have the same key(i.e., offset).\n    std::pair<bool, boost::optional<cell_set_t>> apply(cell_set_t x,\n                                                       cell_set_t y) {\n      return {false, cell_set_impl::set_union(x, y)};\n    }\n    // if one map does not have a key in the other map we add it.\n    bool default_is_absorbing() { return false; }\n  };\n\n  class meet_op : public binary_op_t {\n    std::pair<bool, boost::optional<cell_set_t>> apply(cell_set_t x,\n                                                       cell_set_t y) {\n      return {false, cell_set_impl::set_union(x, y)};\n    }\n    // if one map does not have a key in the other map we ignore\n    // it.\n    bool default_is_absorbing() { return true; }\n  };\n\n  class domain_po : public partial_order_t {\n    bool leq(cell_set_t x, cell_set_t y) {\n      return cell_set_impl::set_inclusion(x, y);\n    }\n    // default value is bottom (i.e., empty map)\n    bool default_is_top() { return false; }\n  }; // class domain_po\n\n  // Delete completely the cell\n  void erase_cell(const cell_t &c);\n\n  // Pretend the cell is removed by marking it as \"removed\"\n  void remove_cell(const cell_t &c); \n\n  void insert_cell(const cell_t &c);\n\n  cell_t get_cell(const offset_t &o, uint64_t size) const;\n\n  // create a fresh _unamed_ cell\n  cell_t mk_cell(const offset_t &o, uint64_t size /*bytes*/);\n\n  offset_map_t(patricia_tree_t &&m);\n\npublic:\n  offset_map_t();\n\n  offset_map_t(const offset_map_t &o);\n\n  offset_map_t(const offset_map_t &&o);\n\n  offset_map_t &operator=(const offset_map_t &o);\n\n  offset_map_t &operator=(const offset_map_t &&o);\n  \n  bool empty() const;\n\n  std::size_t size() const;\n\n  // leq operator\n  bool operator<=(const offset_map_t &o) const;\n\n  // set union: if two cells with same offset do not agree on\n  // size then they are ignored.\n  offset_map_t operator|(const offset_map_t &o) const;\n\n  // set intersection: if two cells with same offset do not agree\n  // on size then they are ignored.\n  offset_map_t operator&(const offset_map_t &o) const;\n\n  // Completely delete the cell from the offset map\n  void erase(const cell_t &c);\n\n  void erase(const std::vector<cell_t> &cells);\n\n  // Pretend the cell is removed so no other cells overlap with it but\n  // the cell is not actually deleted from the offset map. We need to\n  // know all created cells when smashing occurs.\n  void remove(const cell_t &c);\n\n  void remove(const std::vector<cell_t> &cells);\n\n  // cells are sorted by offset\n  std::vector<cell_t> get_all_cells() const;\n\n  unsigned get_number_cells() const;\n\n  // Return in out all cells that might overlap with (o, size).\n  //\n  // It is not marked as const because we insert temporary a cell.\n  // However, upon completion this method leaves unmodified the object.\n  void get_overlap_cells(const offset_t &o, uint64_t size,\n                         std::vector<cell_t> &out);\n  \n  template <typename Dom>\n  void get_overlap_cells_symbolic_offset(\n      const Dom &dom, const typename Dom::linear_expression_t &symb_lb,\n      const typename Dom::linear_expression_t &symb_ub,\n      std::vector<cell_t> &out) const {\n\n    for (auto it = m_map.begin(), et = m_map.end(); it != et; ++it) {\n      const cell_set_t &o_cells = it->second;\n      // All cells in o_cells have the same offset. They only differ\n      // in the size. If the largest cell overlaps with [offset,\n      // offset + size) then the rest of cells are considered to\n      // overlap. This is an over-approximation because [offset,\n      // offset+size) can overlap with the largest cell but it\n      // doesn't necessarily overlap with smaller cells. For\n      // efficiency, we assume it overlaps with all.\n      cell_t largest_cell;\n      for (auto &c : o_cells) {\n        if (largest_cell.is_null()) {\n          largest_cell = c;\n        } else {\n          assert(c.get_offset() == largest_cell.get_offset());\n          if (largest_cell < c) {\n            largest_cell = c;\n          }\n        }\n      }\n      if (!largest_cell.is_null()) {\n        if (largest_cell.symbolic_overlap(symb_lb, symb_ub, dom)) {\n          for (auto &c : o_cells) {\n            out.push_back(c);\n          }\n        }\n      }\n    }\n  }\n\n  void clear(void);\n\n  void write(crab::crab_os &o) const;\n\n  friend crab::crab_os &operator<<(crab::crab_os &o, const offset_map_t &m) {\n    m.write(o);\n    return o;\n  }\n\n  /* Operations needed if used as value in a patricia tree */\n  bool operator==(const offset_map_t &o) const {\n    return *this <= o && o <= *this;\n  }\n  bool is_top() const { return empty(); }\n  bool is_bottom() const { return false; }\n  /*\n     a patricia tree only calls bottom if operator[] is called over\n     a bottom state. Thus, we will make sure that we don't call\n     operator[] in that case.\n  */\n  static offset_map_t bottom() {\n    CRAB_ERROR(\"offset_map::bottom() cannot be called\");\n  }\n  /* Top is called when a key is not found in a patricia tree */\n  static offset_map_t top() { return offset_map_t(); }\n};\n} // end namespace array_adaptive_impl\n\ntemplate <typename NumDomain>\nclass array_adaptive_domain final\n    : public abstract_domain_api<array_adaptive_domain<NumDomain>> {\n\npublic:\n  using number_t = typename NumDomain::number_t;\n  using varname_t = typename NumDomain::varname_t;\n\nprivate:\n  using array_adaptive_domain_t = array_adaptive_domain<NumDomain>;\n  using abstract_domain_t = abstract_domain_api<array_adaptive_domain_t>;\n\npublic:\n  using typename abstract_domain_t::disjunctive_linear_constraint_system_t;\n  using typename abstract_domain_t::interval_t;\n  using typename abstract_domain_t::linear_constraint_system_t;\n  using typename abstract_domain_t::linear_constraint_t;\n  using typename abstract_domain_t::linear_expression_t;\n  using typename abstract_domain_t::reference_constraint_t;\n  using typename abstract_domain_t::variable_or_constant_t;\n  using typename abstract_domain_t::variable_t;\n  using typename abstract_domain_t::variable_vector_t;\n  using typename abstract_domain_t::variable_or_constant_vector_t;  \n  using base_domain_t = array_smashing<NumDomain>;\n\nprivate:\n  using type_t = typename variable_t::type_t;\n  using offset_t = array_adaptive_impl::offset_t;\n  using offset_map_t = array_adaptive_impl::offset_map_t;\n  using cell_t = array_adaptive_impl::cell_t;\n  using cp_domain_t = array_adaptive_impl::cp_domain_t;\n\n  /* A map from an array variable to a vector of pairs of cell and\n   * scalar variable.\n   *\n   * The vector is sorted so that finding/inserting/erasing cells is\n   * faster.\n   */\n  class cell_varmap_t {\n  public:\n    using sorted_cell_var_vector = std::vector<std::pair<cell_t, variable_t>>;\n\n  private:\n    struct less_cell_var {\n      bool operator()(const std::pair<cell_t, variable_t> &p,\n                      const cell_t &c) const {\n        return p.first < c;\n      }\n    };\n    std::unordered_map<variable_t, sorted_cell_var_vector> m_map;\n\n  public:\n    using iterator =\n        typename std::unordered_map<variable_t,\n                                    sorted_cell_var_vector>::iterator;\n    using const_iterator =\n        typename std::unordered_map<variable_t,\n                                    sorted_cell_var_vector>::const_iterator;\n    using cell_var_iterator = typename sorted_cell_var_vector::iterator;\n\n    cell_varmap_t() {}\n\n    iterator begin() { return m_map.begin(); }\n    iterator end() { return m_map.end(); }\n    const_iterator begin() const { return m_map.begin(); }\n    const_iterator end() const { return m_map.end(); }\n\n    cell_var_iterator begin_cells(const variable_t &array) {\n      return m_map[array].begin();\n    }\n    cell_var_iterator end_cells(const variable_t &array) {\n      return m_map[array].end();\n    }\n\n    boost::optional<variable_t> find(const variable_t &array,\n                                     const cell_t &c) const {\n      auto it = m_map.find(array);\n      if (it == m_map.end()) {\n        return boost::none;\n      }\n\n      const sorted_cell_var_vector &cell_vars = it->second;\n      less_cell_var cmp;\n      auto lb = std::lower_bound(cell_vars.begin(), cell_vars.end(), c, cmp);\n      if (lb != cell_vars.end() && !(c < (*lb).first)) {\n        return (*lb).second;\n      } else {\n        return boost::none;\n      }\n    }\n\n    void erase(const variable_t &array, const cell_t &c) {\n      auto it = m_map.find(array);\n      if (it == m_map.end()) {\n        return;\n      }\n\n      sorted_cell_var_vector &cell_vars = it->second;\n      less_cell_var cmp;\n      auto lb = std::lower_bound(cell_vars.begin(), cell_vars.end(), c, cmp);\n      if (lb != cell_vars.end() && !(c < (*lb).first)) {\n        cell_vars.erase(lb);\n      }\n    }\n\n    void erase(const variable_t &array) { m_map.erase(array); }\n\n    void insert(const variable_t &array, const cell_t &c,\n                const variable_t &base_v) {\n      std::vector<std::pair<cell_t, variable_t>> vs;\n      auto it = m_map.insert({array, vs}).first;\n      sorted_cell_var_vector &cell_vars = it->second;\n      less_cell_var cmp;\n      auto lb = std::lower_bound(cell_vars.begin(), cell_vars.end(), c, cmp);\n      if (lb != cell_vars.end() && !(c < (*lb).first)) {\n        // already exists\n        return;\n      }\n      cell_vars.insert(lb, {c, base_v});\n    }\n\n    void insert(const variable_t &array) {\n      sorted_cell_var_vector vec;\n      auto res = m_map.insert({array, vec});\n      if (!res.second) {\n        CRAB_ERROR(\"cell_varmap_t::insert already exists\");\n      }\n    }\n\n    void write(crab_os &o) const {\n      for (auto &kv : m_map) {\n        o << kv.first << \":\\n\";\n        for (auto &cv : kv.second) {\n          o << \"\\t\" << cv.first << \" --> \" << cv.second << \"\\n\";\n        }\n      }\n    }\n  };\n\n  using smashed_varmap_t = std::unordered_map<variable_t, variable_t>;\n\n  class array_state {\n    // whether the array has been smashed\n    bool m_is_smashed;\n    // element size of the array if smashed\n    cp_domain_t m_element_sz;\n    // precise array contents if no smashed\n    offset_map_t m_offset_map;\n\n    static bool consistent_offset(const offset_t &o, size_t elem_size) {\n      if (o.is_negative()) {\n        CRAB_LOG(\"array-adaptive-smash\",\n                 crab::outs() << \"cannot smash because negative offset\\n\";);\n        return false;\n      }\n      size_t n = static_cast<size_t>(o.index());\n      if (n % elem_size != 0) {\n        CRAB_LOG(\"array-adaptive-smash\", crab::outs()\n                                             << \"cannot smash because \" << n\n                                             << \"%\" << elem_size << \"!= 0\\n\");\n        return false;\n      }\n      return true;\n    }\n\n    // Smash the array if it's safe to do so.\n    // Return true if the array ha\n    void smash_array(const variable_t &a, const cp_domain_t &elem_sz,\n                     cell_varmap_t &cvm, smashed_varmap_t &svm,\n                     base_domain_t &base_dom) {\n\n      // we only smash the array if elem_sz is a constant value and\n      // all array elements are consistent wrt elem_sz. Leave the\n      // array without smashing is always sound.\n\n      std::vector<cell_t> cells = get_offset_map().get_all_cells();\n      if (cells.empty()) {\n        return;\n      }\n\n      if (cells.size() > crab_domain_params_man::get().array_adaptive_max_smashable_cells()) {\n        // Smashing is expensive because it will go over all cells\n        // performing one join per weak update even if the smashed\n        // array is already unconstrained. We don't smash if the\n        // number of cells to be smashed is too large.\n        CRAB_WARN(\"array adaptive did not smash array because its size is \"\n                  \"greater than \",\n                  crab_domain_params_man::get().array_adaptive_max_smashable_cells());\n        return;\n      }\n\n      if (!crab_domain_params_man::get().array_adaptive_smash_at_nonzero_offset() &&\n          !cells[0].get_offset().is_zero()) {\n        return;\n      }\n\n      if (boost::optional<uint64_t> sz_opt = elem_sz.get_uint64_val()) {\n        bool can_be_smashed = true;\n        variable_t smashed_a =\n            array_adaptive_domain_t::get_smashed_variable(a, svm);\n        for (unsigned k = 0, num_cells = cells.size(); k < num_cells; ++k) {\n          const cell_t &c = cells[k];\n          if (!consistent_offset(c.get_offset(), *sz_opt)) {\n            CRAB_LOG(\n                \"array-adaptive\",\n                CRAB_WARN(\"cannot smashing because of inconsistent offsets\"););\n            can_be_smashed = false;\n            break;\n          }\n          const bool is_strong_update = (k == 0);\n          linear_expression_t idx(number_t(c.get_offset().index()));\n          if (boost::optional<variable_t> c_scalar_var = cvm.find(a, c)) {\n            base_dom.array_store(smashed_a, c.get_size(), idx, *c_scalar_var,\n                                 is_strong_update);\n          } else {\n            CRAB_LOG(\n                \"array-adaptive\",\n                CRAB_WARN(\n                    \"cannot smashing because of scalar variable for array \", a,\n                    \" and cell \", c, \" not found in \");\n                cvm.write(crab::outs()); crab::outs() << \"\\n\";);\n            can_be_smashed = false;\n            break;\n          }\n        }\n\n        if (can_be_smashed) {\n          for (unsigned k = 0, num_cells = cells.size(); k < num_cells; ++k) {\n            const cell_t &c = cells[k];\n            if (boost::optional<variable_t> c_scalar_var = cvm.find(a, c)) {\n              // remove the synthethic cell from the base domain and\n              // from the offset map\n              base_dom -= *c_scalar_var;\n            }\n            get_offset_map().erase(c);\n            cvm.erase(a, c);\n          }\n          m_is_smashed = true;\n          m_element_sz = elem_sz;\n        } else {\n          base_dom -= smashed_a;\n        }\n      }\n    }\n\n    void do_sanity_checks() const {\n      if (m_element_sz.is_bottom()) {\n        CRAB_ERROR(\"array_state::m_element_sz cannot be bottom\");\n      }\n      if (m_offset_map.is_bottom()) {\n        CRAB_ERROR(\"array_state::m_offset_map cannot be bottom\");\n      }\n    }\n\n  public:\n    array_state() : m_is_smashed(false), m_element_sz((int64_t)0) {}\n\n    array_state(bool &&is_smashed, cp_domain_t &&sz, offset_map_t &&om)\n        : m_is_smashed(std::move(is_smashed)), m_element_sz(std::move(sz)),\n          m_offset_map(std::move(om)) {\n      do_sanity_checks();\n    }\n\n    array_state(const array_state &o)\n        : m_is_smashed(o.m_is_smashed), m_element_sz(o.m_element_sz),\n          m_offset_map(o.m_offset_map) {\n      do_sanity_checks();\n    }\n\n    array_state(const array_state &&o)\n        : m_is_smashed(std::move(o.m_is_smashed)),\n          m_element_sz(std::move(o.m_element_sz)),\n          m_offset_map(std::move(o.m_offset_map)) {\n      do_sanity_checks();\n    }\n\n    array_state &operator=(const array_state &o) {\n      if (this != &o) {\n        m_is_smashed = o.m_is_smashed;\n        m_element_sz = o.m_element_sz;\n        m_offset_map = o.m_offset_map;\n      }\n      do_sanity_checks();\n      return *this;\n    }\n\n    array_state &operator=(const array_state &&o) {\n      if (this != &o) {\n        m_is_smashed = std::move(o.m_is_smashed);\n        m_element_sz = std::move(o.m_element_sz);\n        m_offset_map = std::move(o.m_offset_map);\n      }\n      do_sanity_checks();\n      return *this;\n    }\n\n    /*** begin mergeable_map API ***/\n    array_state join(const variable_t &v, const array_state &o,\n                     cell_varmap_t &cvm_left, smashed_varmap_t &svm_left,\n                     base_domain_t &dom_left, cell_varmap_t &cvm_right,\n                     smashed_varmap_t &svm_right,\n                     base_domain_t &dom_right) const {\n      if (m_is_smashed && !o.m_is_smashed) {\n        array_state right(o);\n        right.smash_array(v, get_element_sz(), cvm_right, svm_right, dom_right);\n        return array_state(m_is_smashed | right.m_is_smashed,\n                           m_element_sz | right.m_element_sz,\n                           m_offset_map | right.m_offset_map);\n      } else if (!m_is_smashed && o.m_is_smashed) {\n        array_state left(*this);\n        left.smash_array(v, o.get_element_sz(), cvm_left, svm_left, dom_left);\n        return array_state(left.m_is_smashed | o.m_is_smashed,\n                           left.m_element_sz | o.m_element_sz,\n                           left.m_offset_map | o.m_offset_map);\n      } else {\n        return array_state(m_is_smashed | o.m_is_smashed,\n                           m_element_sz | o.m_element_sz,\n                           m_offset_map | o.m_offset_map);\n      }\n    }\n\n    array_state meet(const variable_t &v, const array_state &o,\n                     cell_varmap_t &cvm_left, smashed_varmap_t &svm_left,\n                     base_domain_t &dom_left, cell_varmap_t &cvm_right,\n                     smashed_varmap_t &svm_right,\n                     base_domain_t &dom_right) const {\n      if (m_is_smashed && !o.m_is_smashed) {\n        array_state right(o);\n        right.smash_array(v, get_element_sz(), cvm_right, svm_right, dom_right);\n        return array_state(m_is_smashed & right.m_is_smashed,\n                           m_element_sz & right.m_element_sz,\n                           m_offset_map & right.m_offset_map);\n      } else if (!m_is_smashed && o.m_is_smashed) {\n        array_state left(*this);\n        left.smash_array(v, o.get_element_sz(), cvm_left, svm_left, dom_left);\n        return array_state(left.m_is_smashed & o.m_is_smashed,\n                           left.m_element_sz & o.m_element_sz,\n                           left.m_offset_map & o.m_offset_map);\n      } else {\n        return array_state(m_is_smashed & o.m_is_smashed,\n                           m_element_sz & o.m_element_sz,\n                           m_offset_map & o.m_offset_map);\n      }\n    }\n\n    bool operator==(const array_state &o) {\n      if (m_is_smashed != o.m_is_smashed) {\n        return false;\n      }\n      if (m_is_smashed) {\n        return (m_element_sz == o.m_element_sz);\n      } else {\n        return m_offset_map == o.m_offset_map;\n      }\n    }\n\n    bool is_top() const { return false; }\n    bool is_bottom() const { return false; }\n    /*\n     a patricia tree only calls bottom if operator[] is called over\n     a bottom state. Thus, we will make sure that we don't call\n     operator[] in that case.\n    */\n    static array_state bottom() {\n      CRAB_ERROR(\"array_state::bottom() cannot be called\");\n    }\n    /* Top is called when a key is not found in a patricia tree */\n    static array_state top() {\n      CRAB_ERROR(\"array_state::top() cannot be called\");\n      // return array_state();\n    }\n\n    /*** end mergeable_map API ***/\n\n    bool is_smashed() const { return m_is_smashed; }\n\n    void set_smashed(bool v) { m_is_smashed = v; }\n\n    offset_map_t &get_offset_map() { return m_offset_map; }\n\n    const offset_map_t &get_offset_map() const { return m_offset_map; }\n\n    cp_domain_t &get_element_sz() { return m_element_sz; }\n\n    const cp_domain_t &get_element_sz() const { return m_element_sz; }\n\n    static bool can_be_smashed(const std::vector<cell_t> &cells,\n                               uint64_t elem_sz,\n                               bool allow_start_at_nonzero_offset) {\n      if (cells.empty()) {\n        return false;\n      }\n\n      offset_t start_offset = cells[0].get_offset();\n\n      if (!allow_start_at_nonzero_offset) {\n        if (!start_offset.is_zero()) {\n          CRAB_LOG(\"array-adaptive-smash\",\n                   crab::outs() << \"cannot smash because array does not start \"\n                                   \"at offset 0\\n\";);\n          return false;\n        }\n      }\n\n      for (unsigned i = 0, e = cells.size(); i < e; ++i) {\n        const cell_t &c = cells[i];\n        if (c.get_size() != elem_sz) {\n          CRAB_LOG(\"array-adaptive-smash\",\n                   crab::outs() << \"cannot smash because array elements have \"\n                                   \"different sizes\\n\");\n          return false;\n        }\n        // note that we adjust the cell's offset\n        if (!consistent_offset(c.get_offset() - start_offset, elem_sz)) {\n          return false;\n        }\n      }\n      return true;\n    }\n\n    bool can_be_smashed(uint64_t elem_sz) const {\n      if (m_is_smashed) {\n        // already smashed, bail out ...\n        return false;\n      }\n      std::vector<cell_t> cells = m_offset_map.get_all_cells();\n      return can_be_smashed(cells, elem_sz,\n\t\t\t    crab_domain_params_man::get().array_adaptive_smash_at_nonzero_offset());\n    }\n\n    void write(crab_os &o) const {\n      if (m_is_smashed) {\n        o << \"smashed with element size=\";\n        m_element_sz.write(o);\n      } else {\n        m_offset_map.write(o);\n      }\n    }\n  };\n\n  class array_state_map_t {\n  private:\n    using patricia_tree_t = ikos::patricia_tree<variable_t, array_state>;\n    using key_binary_op_t = typename patricia_tree_t::key_binary_op_t;\n\n  public:\n    using iterator = typename patricia_tree_t::iterator;\n\n  private:\n    patricia_tree_t m_tree;\n\n    class join_op : public key_binary_op_t {\n      cell_varmap_t &m_cvm_left;\n      smashed_varmap_t &m_svm_left;\n      base_domain_t &m_dom_left;\n      cell_varmap_t &m_cvm_right;\n      smashed_varmap_t &m_svm_right;\n      base_domain_t &m_dom_right;\n\n    public:\n      join_op(cell_varmap_t &cvm_left, smashed_varmap_t &svm_left,\n              base_domain_t &dom_left, cell_varmap_t &cvm_right,\n              smashed_varmap_t &svm_right, base_domain_t &dom_right)\n          : m_cvm_left(cvm_left), m_svm_left(svm_left), m_dom_left(dom_left),\n            m_cvm_right(cvm_right), m_svm_right(svm_right),\n            m_dom_right(dom_right) {}\n\n      std::pair<bool, boost::optional<array_state>>\n      apply(const variable_t &k, array_state x, array_state y) {\n        array_state z = x.join(k, y, m_cvm_left, m_svm_left, m_dom_left,\n                               m_cvm_right, m_svm_right, m_dom_right);\n        return {false, boost::optional<array_state>(z)};\n      }\n\n      bool default_is_absorbing() { return true; }\n    }; // class join_op\n\n    class meet_op : public key_binary_op_t {\n      cell_varmap_t &m_cvm_left;\n      smashed_varmap_t &m_svm_left;\n      base_domain_t &m_dom_left;\n      cell_varmap_t &m_cvm_right;\n      smashed_varmap_t &m_svm_right;\n      base_domain_t &m_dom_right;\n\n    public:\n      meet_op(cell_varmap_t &cvm_left, smashed_varmap_t &svm_left,\n              base_domain_t &dom_left, cell_varmap_t &cvm_right,\n              smashed_varmap_t &svm_right, base_domain_t &dom_right)\n          : m_cvm_left(cvm_left), m_svm_left(svm_left), m_dom_left(dom_left),\n            m_cvm_right(cvm_right), m_svm_right(svm_right),\n            m_dom_right(dom_right) {}\n\n      std::pair<bool, boost::optional<array_state>>\n      apply(const variable_t &k, array_state x, array_state y) {\n        array_state z = x.meet(k, y, m_cvm_left, m_svm_left, m_dom_left,\n                               m_cvm_right, m_svm_right, m_dom_right);\n        return {false, boost::optional<array_state>(z)};\n      }\n      bool default_is_absorbing() { return false; }\n    }; // class meet_op\n\n    patricia_tree_t apply_operation(key_binary_op_t &o, patricia_tree_t t1,\n                                    const patricia_tree_t &t2) const {\n      bool res = t1.merge_with(t2, o);\n      if (res) {\n        CRAB_ERROR(\n            \"array_adaptive::array_state_map_t should not return bottom\");\n      }\n      return t1;\n    }\n\n    array_state_map_t(patricia_tree_t &&t) : m_tree(std::move(t)) {}\n\n  public:\n    array_state_map_t() {}\n\n    array_state_map_t(const array_state_map_t &o) : m_tree(o.m_tree) {}\n\n    array_state_map_t(const array_state_map_t &&o)\n        : m_tree(std::move(o.m_tree)) {}\n\n    array_state_map_t &operator=(const array_state_map_t &o) {\n      if (this != &o) {\n        m_tree = o.m_tree;\n      }\n      return *this;\n    }\n\n    array_state_map_t &operator=(const array_state_map_t &&o) {\n      if (this != &o) {\n        m_tree = std::move(o.m_tree);\n      }\n      return *this;\n    }\n\n    iterator begin() const { return m_tree.begin(); }\n\n    iterator end() const { return m_tree.end(); }\n\n    size_t size() const { return m_tree.size(); }\n\n    // Join\n    array_state_map_t join(const array_state_map_t &o, cell_varmap_t &cvm_left,\n                           smashed_varmap_t &svm_left, base_domain_t &dom_left,\n                           cell_varmap_t &cvm_right,\n                           smashed_varmap_t &svm_right,\n                           base_domain_t &dom_right) const {\n      join_op op(cvm_left, svm_left, dom_left, cvm_right, svm_right, dom_right);\n      patricia_tree_t res = apply_operation(op, m_tree, o.m_tree);\n      return array_state_map_t(std::move(res));\n    }\n\n    // Meet\n    array_state_map_t meet(const array_state_map_t &o, cell_varmap_t &cvm_left,\n                           smashed_varmap_t &svm_left, base_domain_t &dom_left,\n                           cell_varmap_t &cvm_right,\n                           smashed_varmap_t &svm_right,\n                           base_domain_t &dom_right) const {\n      meet_op op(cvm_left, svm_left, dom_left, cvm_right, svm_right, dom_right);\n      patricia_tree_t res = apply_operation(op, m_tree, o.m_tree);\n      return array_state_map_t(std::move(res));\n    }\n\n    void set(variable_t k, array_state v) { m_tree.insert(k, v); }\n\n    array_state_map_t &operator-=(const variable_t &k) {\n      m_tree.remove(k);\n      return *this;\n    }\n\n    const array_state *find(const variable_t &k) const {\n      return m_tree.find(k);\n    }\n\n    // Assume that from does not have duplicates.\n    void rename(const std::vector<variable_t> &from,\n                const std::vector<variable_t> &to) {\n      if (from.size() != to.size()) {\n        CRAB_ERROR(\"array_adaptive::array_state_t::rename received input \"\n                   \"vectors of different sizes\");\n      }\n\n      if (m_tree.size() == 0) {\n        return;\n      }\n\n      for (unsigned i = 0, sz = from.size(); i < sz; ++i) {\n        variable_t k = from[i];\n        variable_t new_k = to[i];\n        if (k == new_k) { // nothing to rename\n          continue;\n        }\n\n        if (::crab::CrabSanityCheckFlag) {\n          if (m_tree.lookup(new_k)) {\n            CRAB_ERROR(\"array_adaptive::array_state_t:rename assumes that  \",\n                       new_k, \" does not exist\");\n          }\n        }\n\n        if (boost::optional<array_state> k_val_opt = m_tree.lookup(k)) {\n          if (!(*k_val_opt).is_top()) {\n            m_tree.insert(new_k, *k_val_opt);\n          }\n          m_tree.remove(k);\n        }\n      }\n    }\n\n    void write(crab::crab_os &o) const {\n      o << \"{\";\n      for (auto it = m_tree.begin(); it != m_tree.end();) {\n        variable_t k = it->first;\n        k.write(o);\n        o << \" -> \";\n        array_state v = it->second;\n        v.write(o);\n        ++it;\n        if (it != m_tree.end()) {\n          o << \"; \";\n        }\n      }\n      o << \"}\";\n    }\n\n    friend crab::crab_os &operator<<(crab::crab_os &o,\n                                     const array_state_map_t &m) {\n      m.write(o);\n      return o;\n    }\n  }; // class array_state_map_t\n\n  // -- scalar domain containing scalar variables, synthetic scalar\n  // -- variables from cells and synthetic summarized smashed\n  // -- variables.\n  base_domain_t m_inv;\n\n  // -- map an array variable to its synthetic cells\n  array_state_map_t m_array_map;\n\n  // -- map a synthetic cell to a scalar variable used in m_inv\n  cell_varmap_t m_cell_varmap;\n\n  // -- map an array variable to its smashed version used in m_inv\n  smashed_varmap_t m_smashed_varmap;\n\nprivate:\n  const array_state &lookup_array_state(const variable_t &v) {\n    if (is_bottom()) {\n      CRAB_ERROR(\"cannot call lookup_array_state on bottom\");\n    }\n    const array_state *as = m_array_map.find(v);\n    if (as) {\n      return *as;\n    }\n    array_state s;\n    m_array_map.set(v, s);\n    as = m_array_map.find(v);\n    if (!as) {\n      CRAB_ERROR(\"array_state::lookup_array_state returned null\");\n    }\n    return *as;\n  }\n\n  static std::string mk_scalar_name(const varname_t &a, const offset_t &o,\n                                    uint64_t size) {\n    crab::crab_string_os os;\n    os << a << \"[\";\n    if (size == 1) {\n      os << o;\n    } else {\n      os << o << \"...\" << o.index() + size - 1;\n    }\n    os << \"]\";\n    return os.str();\n  }\n\n  static variable_type_kind get_array_element_type(type_t array_type) {\n    if (array_type.is_bool_array()) {\n      return BOOL_TYPE;\n    } else if (array_type.is_integer_array()) {\n      return INT_TYPE;\n    } else {\n      assert(array_type.is_real_array());\n      return REAL_TYPE;\n    }\n  }\n\n  // Return a named cell, i.e., a cell with a scalar variable\n  // associated to it.\n  std::pair<cell_t, variable_t> mk_named_cell(const variable_t &a,\n                                              const offset_t &o,\n                                              uint64_t sz /*bytes*/,\n                                              offset_map_t &om) {\n    // create first an unnamed cell\n    cell_t c = om.mk_cell(o, sz);\n\n    if (boost::optional<variable_t> scalar_v = m_cell_varmap.find(a, c)) {\n      return {c, *scalar_v};\n    } else {\n      assert(!c.is_null());\n      // assign a scalar variable to the cell\n      auto &vfac = const_cast<varname_t *>(&(a.name()))->get_var_factory();\n      std::string vname = mk_scalar_name(a.name(), o, sz);\n      variable_type_kind vtype_kind = get_array_element_type(a.get_type());\n      variable_t scalar_var(vfac.get(vname), vtype_kind,\n                            (vtype_kind == BOOL_TYPE\n                                 ? 1\n                                 : (vtype_kind == INT_TYPE ? 8 * sz : 0)));\n      m_cell_varmap.insert(a, c, scalar_var);\n      return {c, scalar_var};\n    }\n  }\n\n  using variable_opt_t = boost::optional<variable_t>;\n  variable_opt_t get_scalar(const variable_t &array_v, const cell_t &c) {\n    if (!array_v.get_type().is_array()) {\n      CRAB_ERROR(\"array_adaptive::get_scalar only if array variable\");\n    }\n    return m_cell_varmap.find(array_v, c);\n  }\n\n  static variable_t mk_smashed_variable(const variable_t &v) {\n    if (!v.get_type().is_array()) {\n      CRAB_ERROR(\n          \"array_adaptive::mk_smashed_variable only takes array variables\");\n    }\n\n    auto &vfac = const_cast<varname_t *>(&(v.name()))->get_var_factory();\n    crab::crab_string_os os;\n    os << \"smashed(\" << v << \")\";\n    return variable_t(vfac.get(os.str()), v.get_type());\n  }\n\n  static variable_t get_smashed_variable(const variable_t &a,\n                                         smashed_varmap_t &svm) {\n    if (!a.get_type().is_array()) {\n      CRAB_ERROR(\n          \"array_adaptive::get_smashed_variable only takes array variables\");\n    }\n\n    auto it = svm.find(a);\n    if (it != svm.end()) {\n      return it->second;\n    } else {\n      variable_t smashed_var = mk_smashed_variable(a);\n      svm.insert({a, smashed_var});\n      return smashed_var;\n    }\n  }\n\n  std::vector<variable_t> get_array_variables() const {\n    std::vector<variable_t> res;\n    res.reserve(m_array_map.size());\n    for (auto it = m_array_map.begin(), et = m_array_map.end(); it != et;\n         ++it) {\n      res.push_back(it->first);\n    }\n    return res;\n  }\n\n  void forget_array(const variable_t &v) {\n    if (!v.get_type().is_array()) {\n      CRAB_ERROR(\"cannot call forget_array on a non-array variable\");\n    }\n\n    std::vector<variable_t> scalar_vars;\n    const array_state &as = lookup_array_state(v);\n    if (!as.is_smashed()) {\n      /// We extract all the synthetic cells from the array and forget\n      /// them from the underlying abstract domain.\n      const offset_map_t &om = as.get_offset_map();\n      std::vector<cell_t> cells = om.get_all_cells();\n      for (auto &c : cells) {\n        if (variable_opt_t v_opt = get_scalar(v, c)) {\n          scalar_vars.push_back(*v_opt);\n        }\n      }\n    } else {\n      scalar_vars.push_back(get_smashed_variable(v, m_smashed_varmap));\n    }\n\n    m_array_map -= v;\n    m_cell_varmap.erase(v);\n    m_smashed_varmap.erase(v);\n    m_inv.forget(scalar_vars);\n  }\n\n  interval_t to_interval(const linear_expression_t &expr, base_domain_t inv) {\n    interval_t r(expr.constant());\n    for (auto kv : expr) {\n      interval_t c(kv.first);\n      r += c * inv[kv.second];\n    }\n    return r;\n  }\n\n  interval_t to_interval(const linear_expression_t &expr) {\n    return to_interval(expr, m_inv);\n  }\n\n  void kill_cells(const variable_t &a, const std::vector<cell_t> &cells,\n                  offset_map_t &offset_map) {\n\n    assert(a.get_type().is_array());\n\n    if (!cells.empty()) {\n      // Forget the scalars from the numerical domain\n      for (unsigned i = 0, e = cells.size(); i < e; ++i) {\n        const cell_t &c = cells[i];\n        if (variable_opt_t c_scalar_opt = get_scalar(a, c)) {\n          m_inv -= *c_scalar_opt;\n        }\n      }\n      if (!crab_domain_params_man::get().array_adaptive_is_smashable()) {\n        // Delete completely the cells. If needed again they they will\n        // be re-created.\n        for (unsigned i = 0, e = cells.size(); i < e; ++i) {\n          const cell_t &c = cells[i];\n          offset_map.erase(c);\n          m_cell_varmap.erase(a, c);\n        }\n      } else {\n        // if an array is smashable then we don't delete the cells\n        // from the offset map. Otherwise, smashing might be unsound.\n        // Instead, we mark them as \"removed\" so they cannot overlap\n        // with other cells.\n        offset_map.remove(cells);\n      }\n    }\n  }\n\n  // Helper that assign rhs to lhs by switching to the version with\n  // the right type.\n  void do_assign(const variable_t &lhs, const variable_t &rhs) {\n    if (lhs.get_type() != rhs.get_type()) {\n      CRAB_ERROR(\"array_adaptive assignment \", lhs, \":=\", rhs,\n                 \" with different types\");\n    }\n    auto lhs_ty = lhs.get_type();\n    if (lhs_ty.is_bool()) {\n      m_inv.assign_bool_var(lhs, rhs, false);\n    } else if (lhs_ty.is_integer() || lhs_ty.is_real()) {\n      m_inv.assign(lhs, rhs);\n    } else {\n      CRAB_ERROR(\n          \"array_adaptive assignment with unexpected array element type\");\n    }\n  }\n\n  // helper to assign an array store's value\n  void do_assign(const variable_t &lhs, const linear_expression_t &v) {\n    auto lhs_ty = lhs.get_type();\n    if (lhs_ty.is_bool()) {\n      if (v.is_constant()) {\n        if (v.constant() >= number_t(1)) {\n          m_inv.assign_bool_cst(lhs, linear_constraint_t::get_true());\n        } else {\n          m_inv.assign_bool_cst(lhs, linear_constraint_t::get_false());\n        }\n      } else if (auto var = v.get_variable()) {\n        m_inv.assign_bool_var(lhs, (*var), false);\n      }\n    } else if (lhs_ty.is_integer() || lhs_ty.is_real()) {\n      m_inv.assign(lhs, v);\n    } else {\n      CRAB_ERROR(\n          \"array_adaptive assignment with unexpected array element type\");\n    }\n  }\n\n  // Helper that assign backward rhs to lhs by switching to the\n  // version with the right type.\n  void do_backward_assign(const variable_t &lhs, const variable_t &rhs,\n                          const base_domain_t &dom) {\n    if (lhs.get_type() != rhs.get_type()) {\n      CRAB_ERROR(\"array_adaptive backward assignment with different types\");\n    }\n    auto lhs_ty = lhs.get_type();\n    if (lhs_ty.is_bool()) {\n      m_inv.backward_assign_bool_var(lhs, rhs, false, dom);\n    } else if (lhs_ty.is_integer() || lhs_ty.is_real()) {\n      m_inv.backward_assign(lhs, rhs, dom);\n    } else {\n      CRAB_ERROR(\"array_adaptive backward_assignment with unexpected array \"\n                 \"element type\");\n    }\n  }\n\n  // helper to assign backward a cell into a variable\n  void do_backward_assign(const variable_t &lhs, const variable_t &a,\n                          const cell_t &rhs_c, const base_domain_t &dom) {\n    if (!a.get_type().is_array()) {\n      CRAB_ERROR(\"array_adaptive assignment 1st argument must be array type\");\n    }\n    variable_opt_t rhs_v_opt = get_scalar(a, rhs_c);\n    if (!rhs_v_opt) {\n      CRAB_LOG(\n          \"array-adaptive\",\n          CRAB_WARN(\n              \"array_adaptive cell without scalar in do_backward_assign\"););\n      return;\n    }\n    do_backward_assign(lhs, *rhs_v_opt, dom);\n  }\n\n  // helper to assign backward a linear expression into a cell\n  void do_backward_assign(const variable_t &a, const cell_t &lhs_c,\n                          const linear_expression_t &v,\n                          const base_domain_t &dom) {\n    if (!a.get_type().is_array()) {\n      CRAB_ERROR(\"array_adaptive assignment 1st argument must be array type\");\n    }\n    variable_opt_t lhs_v_opt = get_scalar(a, lhs_c);\n    if (!lhs_v_opt) {\n      CRAB_LOG(\n          \"array-adaptive\",\n          CRAB_WARN(\n              \"array_adaptive cell without scalar in do_backward_assign\"););\n      return;\n    }\n    variable_t lhs = *lhs_v_opt;\n    auto lhs_ty = lhs.get_type();\n    if (lhs_ty.is_bool()) {\n      if (v.is_constant()) {\n        if (v.constant() >= number_t(1)) {\n          m_inv.backward_assign_bool_cst(lhs, linear_constraint_t::get_true(),\n                                         dom);\n        } else {\n          m_inv.backward_assign_bool_cst(lhs, linear_constraint_t::get_false(),\n                                         dom);\n        }\n      } else if (auto var = v.get_variable()) {\n        m_inv.backward_assign_bool_var(lhs, (*var), false, dom);\n      }\n    } else if (lhs_ty.is_integer() || lhs_ty.is_real()) {\n      m_inv.backward_assign(lhs, v, dom);\n    } else {\n      CRAB_ERROR(\"array_adaptive backward assignment with unexpected array \"\n                 \"element type\");\n    }\n  }\n\n  // The internal representation contains summarized variables of\n  // array type and add them as dimensions in the underlying numerical\n  // domain. This is OK but it shouldn't be exposed outside via linear\n  // constraints.\n  //\n  // XXX: we should also probably filter out scalar variables\n  // originated from cells.\n  linear_constraint_system_t\n  filter_nonscalar_vars(linear_constraint_system_t &&csts) const {\n    linear_constraint_system_t res;\n    for (auto const &cst : csts) {\n      if (std::all_of(\n              cst.expression().variables_begin(),\n              cst.expression().variables_end(), [](const variable_t &v) {\n                return v.get_type().is_integer() || v.get_type().is_bool();\n              })) {\n        res += cst;\n      }\n    }\n    return res;\n  }\n\n  uint64_t check_and_get_elem_size(const linear_expression_t &elem_size) {\n    interval_t i_elem_size = to_interval(elem_size);\n    if (boost::optional<number_t> n_bytes = i_elem_size.singleton()) {\n      if (static_cast<int64_t>(*n_bytes) > 0) {\n        return (uint64_t) static_cast<int64_t>(*n_bytes);\n      }\n    }\n    CRAB_ERROR(\"array adaptive domain expects constant array element sizes \",\n               \"between 1 and \", std::numeric_limits<uint64_t>::max(),\n               \". Found \", elem_size);\n  }\n\n  void do_renaming_for_join(base_domain_t &left_dom, base_domain_t &right_dom,\n                            smashed_varmap_t &left_svm,\n                            smashed_varmap_t &right_svm,\n                            cell_varmap_t &left_cvm, cell_varmap_t &right_cvm,\n                            smashed_varmap_t &out_svm,\n                            cell_varmap_t &out_cvm) const {\n\n    std::vector<variable_t> old_vars_left, old_vars_right, new_vars;\n\n    // Common renaming for smashed scalars\n    for (auto &kv : left_svm) {\n      variable_t &v1 = kv.second;\n      auto &vfac = const_cast<varname_t *>(&(v1.name()))->get_var_factory();\n      auto it = right_svm.find(kv.first);\n      if (it != right_svm.end()) {\n        variable_t &v2 = it->second;\n        if (v1 != v2) {\n          assert(v1.name().str() == v2.name().str());\n          assert(v1.get_type() == v2.get_type());\n          variable_t outv(vfac.get(v1.name().str()), v1.get_type());\n          old_vars_left.push_back(v1);\n          old_vars_right.push_back(v2);\n          new_vars.push_back(outv);\n          out_svm.insert({kv.first, outv});\n        } else {\n          out_svm.insert(kv);\n        }\n      }\n    }\n\n    /// Rename the base domains\n    left_dom.rename(old_vars_left, new_vars);\n    right_dom.rename(old_vars_right, new_vars);\n\n    old_vars_left.clear();\n    old_vars_right.clear();\n    new_vars.clear();\n\n    // Common renaming for cell scalars\n    for (auto &kv : left_cvm) {\n      for (auto &cv : kv.second) {\n        const variable_t &array_var = kv.first;\n        const cell_t &c = cv.first;\n        const variable_t &v1 = cv.second;\n        auto &vfac = const_cast<varname_t *>(&(v1.name()))->get_var_factory();\n        if (boost::optional<variable_t> v2 = right_cvm.find(array_var, c)) {\n          if (v1 != *v2) {\n            assert(v1.name().str() == (*v2).name().str());\n            assert(v1.get_type() == (*v2).get_type());\n            variable_t outv(vfac.get(v1.name().str()), v1.get_type());\n            old_vars_left.push_back(v1);\n            old_vars_right.push_back(*v2);\n            new_vars.push_back(outv);\n            out_cvm.insert(array_var, c, outv);\n          } else {\n            out_cvm.insert(array_var, c, v1);\n          }\n        }\n      }\n    }\n\n    /// Rename the base domains\n    left_dom.rename(old_vars_left, new_vars);\n    right_dom.rename(old_vars_right, new_vars);\n  }\n\n  void do_renaming_for_meet(base_domain_t &left_dom, base_domain_t &right_dom,\n                            smashed_varmap_t &left_svm,\n                            smashed_varmap_t &right_svm,\n                            cell_varmap_t &left_cvm, cell_varmap_t &right_cvm,\n                            smashed_varmap_t &out_svm,\n                            cell_varmap_t &out_cvm) const {\n\n    std::vector<variable_t> old_vars_left, old_vars_right, new_vars;\n\n    /* Figure out common renaming for smashed scalars */\n\n    // Add all mappings from the left operand\n    for (auto &kv : left_svm) {\n      variable_t &v1 = kv.second;\n      auto &vfac = const_cast<varname_t *>(&(v1.name()))->get_var_factory();\n      auto it = right_svm.find(kv.first);\n      if (it != right_svm.end()) {\n        variable_t &v2 = it->second;\n        if (v1 != v2) {\n          // same key but different scalar -> create a fresh common scalar\n          assert(v1.name().str() == v2.name().str());\n          assert(v1.get_type() == v2.get_type());\n          variable_t outv(vfac.get(v1.name().str()), v1.get_type());\n          old_vars_left.push_back(v1);\n          old_vars_right.push_back(v2);\n          new_vars.push_back(outv);\n          out_svm.insert({kv.first, outv});\n          continue;\n        }\n      }\n      out_svm.insert(kv);\n    }\n\n    // Add the rest of mappings from the right operand\n    for (auto &kv : right_svm) {\n      auto it = left_svm.find(kv.first);\n      if (it == left_svm.end()) {\n        out_svm.insert(kv);\n      }\n    }\n\n    left_dom.rename(old_vars_left, new_vars);\n    right_dom.rename(old_vars_right, new_vars);\n\n    old_vars_left.clear();\n    old_vars_right.clear();\n    new_vars.clear();\n\n    /* Figure out common renaming for cell scalars */\n\n    // Add all mappings from the left operand\n    for (auto &kv : left_cvm) {\n      for (auto &cv : kv.second) {\n        const variable_t &array_var = kv.first;\n        const cell_t &c = cv.first;\n        const variable_t &v1 = cv.second;\n        auto &vfac = const_cast<varname_t *>(&(v1.name()))->get_var_factory();\n        if (boost::optional<variable_t> v2 = right_cvm.find(array_var, c)) {\n          if (v1 != *v2) {\n            // same key but different scalar -> create a fresh common scalar\n            assert(v1.name().str() == (*v2).name().str());\n            assert(v1.get_type() == (*v2).get_type());\n            variable_t outv(vfac.get(v1.name().str()), v1.get_type());\n            old_vars_left.push_back(v1);\n            old_vars_right.push_back(*v2);\n            new_vars.push_back(outv);\n            out_cvm.insert(array_var, c, outv);\n            continue;\n          }\n        }\n        out_cvm.insert(array_var, c, v1);\n      }\n    }\n\n    // Add the rest of mappings from the right operand\n    for (auto &kv : right_cvm) {\n      for (auto &cv : kv.second) {\n        const variable_t &array_var = kv.first;\n        const cell_t &c = cv.first;\n        const variable_t &v = cv.second;\n        if (!left_cvm.find(array_var, c)) {\n          out_cvm.insert(array_var, c, v);\n        }\n      }\n    }\n\n    left_dom.rename(old_vars_left, new_vars);\n    right_dom.rename(old_vars_right, new_vars);\n  }\n\n  array_adaptive_domain(base_domain_t &&inv, array_state_map_t &&amap,\n                        cell_varmap_t &&cvarmap, smashed_varmap_t &&svarmap)\n      : m_inv(std::move(inv)), m_array_map(std::move(amap)),\n        m_cell_varmap(std::move(cvarmap)),\n        m_smashed_varmap(std::move(svarmap)) {}\n\npublic:\n  array_adaptive_domain(bool is_bottom = false) {\n    if (is_bottom) {\n      m_inv.set_to_bottom();\n    } else {\n      m_inv.set_to_top();\n    }\n  }\n\n  array_adaptive_domain make_top() const override {\n    array_adaptive_domain out(false);\n    return out;\n  }\n\n  array_adaptive_domain make_bottom() const override {\n    array_adaptive_domain out(true);\n    return out;\n  }\n\n  void set_to_top() override {\n    array_adaptive_domain abs(false);\n    std::swap(*this, abs);\n  }\n\n  void set_to_bottom() override {\n    array_adaptive_domain abs(true);\n    std::swap(*this, abs);\n  }\n\n  array_adaptive_domain(const array_adaptive_domain_t &other)\n      : m_inv(other.m_inv), m_array_map(other.m_array_map),\n        m_cell_varmap(other.m_cell_varmap),\n        m_smashed_varmap(other.m_smashed_varmap) {\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n  }\n\n  array_adaptive_domain(const array_adaptive_domain_t &&other)\n      : m_inv(std::move(other.m_inv)),\n        m_array_map(std::move(other.m_array_map)),\n        m_cell_varmap(std::move(other.m_cell_varmap)),\n        m_smashed_varmap(std::move(other.m_smashed_varmap)) {\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n  }\n\n  array_adaptive_domain_t &operator=(const array_adaptive_domain_t &other) {\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n    if (this != &other) {\n      m_inv = other.m_inv;\n      m_array_map = other.m_array_map;\n      m_cell_varmap = other.m_cell_varmap;\n      m_smashed_varmap = other.m_smashed_varmap;\n    }\n    return *this;\n  }\n\n  array_adaptive_domain_t &operator=(const array_adaptive_domain_t &&other) {\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n    if (this != &other) {\n      m_inv = std::move(other.m_inv);\n      m_array_map = std::move(other.m_array_map);\n      m_cell_varmap = std::move(other.m_cell_varmap);\n      m_smashed_varmap = std::move(other.m_smashed_varmap);\n    }\n    return *this;\n  }\n\n  bool is_bottom() const override { return (m_inv.is_bottom()); }\n\n  bool is_top() const override { return (m_inv.is_top()); }\n\n  bool operator<=(const array_adaptive_domain_t &other) const override {\n    crab::CrabStats::count(domain_name() + \".count.leq\");\n    crab::ScopedCrabStats __st__(domain_name() + \".leq\");\n\n    if (is_bottom()) {\n      return true;\n    } else if (other.is_top()) {\n      return true;\n    } else {\n\n      CRAB_LOG(\"array-adaptive\", array_adaptive_domain_t left(*this);\n               array_adaptive_domain_t right(other);\n               crab::outs() << \"Check if \" << left << \" <= \" << right << \"\\n\");\n\n      base_domain_t left_dom(m_inv);\n      base_domain_t right_dom(other.m_inv);\n      std::vector<variable_t> old_vars_left, old_vars_right, new_vars;\n\n      /* Figure out common renaming */\n\n      for (auto &kv : m_smashed_varmap) {\n        const variable_t &v1 = kv.second;\n        auto &vfac = const_cast<varname_t *>(&(v1.name()))->get_var_factory();\n        auto it = other.m_smashed_varmap.find(kv.first);\n        // cell exists in both\n        if (it != other.m_smashed_varmap.end()) {\n          const variable_t &v2 = it->second;\n          assert(v1.name().str() == v2.name().str());\n          assert(v1.get_type() == v2.get_type());\n          // same name and type but different variable id\n          if (v1 != v2) {\n            variable_t outv(vfac.get(v1.name().str()), v1.get_type());\n            old_vars_left.push_back(v1);\n            old_vars_right.push_back(v2);\n            new_vars.push_back(outv);\n          }\n        }\n      }\n      left_dom.rename(old_vars_left, new_vars);\n      right_dom.rename(old_vars_right, new_vars);\n\n      old_vars_left.clear();\n      old_vars_right.clear();\n      new_vars.clear();\n\n      for (auto &kv : m_cell_varmap) {\n        for (auto &cv : kv.second) {\n          const variable_t &array_var = kv.first;\n          const cell_t &c = cv.first;\n          const variable_t &v1 = cv.second;\n          auto &vfac = const_cast<varname_t *>(&(v1.name()))->get_var_factory();\n          // cell exists in both\n          if (boost::optional<variable_t> v2 =\n                  other.m_cell_varmap.find(array_var, c)) {\n            assert(v1.name().str() == (*v2).name().str());\n            assert(v1.get_type() == (*v2).get_type());\n            // same name and type but different variable id\n            if (v1 != (*v2)) {\n              variable_t outv(vfac.get(v1.name().str()), v1.get_type());\n              old_vars_left.push_back(v1);\n              old_vars_right.push_back(*v2);\n              new_vars.push_back(outv);\n            }\n          }\n        }\n      }\n\n      left_dom.rename(old_vars_left, new_vars);\n      right_dom.rename(old_vars_right, new_vars);\n\n      // We need to be careful if one array state is smashed and the\n      // other is not.\n      bool res = (left_dom <= right_dom);\n      CRAB_LOG(\"array-adaptive\", crab::outs() << \"Res=\" << res << \"\\n\";);\n      return res;\n    }\n  }\n\n  bool operator==(array_adaptive_domain_t other) {\n    return (m_inv <= other.m_inv && other.m_inv <= m_inv);\n  }\n\n  void operator|=(const array_adaptive_domain_t &other) override {\n    crab::CrabStats::count(domain_name() + \".count.join\");\n    crab::ScopedCrabStats __st__(domain_name() + \".join\");\n\n    CRAB_LOG(\"array-adaptive\",\n             crab::outs() << \"Join \" << *this << \" and \" << other << \"\\n\";);\n\n    if (other.is_bottom() || is_top()) {\n      CRAB_LOG(\"array-adaptive\", crab::outs() << \"Res=\" << *this << \"\\n\";);\n      return;\n    } else if (is_bottom() || other.is_top()) {\n      *this = other;\n      CRAB_LOG(\"array-adaptive\", crab::outs() << \"Res=\" << *this << \"\\n\";);\n    } else {\n\n      base_domain_t right_dom(other.m_inv);\n      cell_varmap_t right_cell_varmap(other.m_cell_varmap);\n      smashed_varmap_t right_smashed_varmap(other.m_smashed_varmap);\n\n      // this must be done before the renaming\n      m_array_map = std::move(m_array_map.join(\n          other.m_array_map, m_cell_varmap, m_smashed_varmap, m_inv,\n          right_cell_varmap, right_smashed_varmap, right_dom));\n\n      smashed_varmap_t out_smashed_varmap;\n      cell_varmap_t out_cell_varmap;\n      do_renaming_for_join(m_inv, right_dom, m_smashed_varmap,\n                           right_smashed_varmap, m_cell_varmap,\n                           right_cell_varmap, out_smashed_varmap,\n                           out_cell_varmap);\n      m_inv |= right_dom;\n      std::swap(m_cell_varmap, out_cell_varmap);\n      std::swap(m_smashed_varmap, out_smashed_varmap);\n      CRAB_LOG(\"array-adaptive\", crab::outs() << \"Res=\" << *this << \"\\n\";);\n    }\n  }\n\n  array_adaptive_domain_t\n  operator|(const array_adaptive_domain_t &other) const override {\n    crab::CrabStats::count(domain_name() + \".count.join\");\n    crab::ScopedCrabStats __st__(domain_name() + \".join\");\n    if (other.is_bottom() || is_top()) {\n      return *this;\n    } else if (is_bottom() || other.is_top()) {\n      return other;\n    } else {\n      CRAB_LOG(\"array-adaptive\",\n               crab::outs() << \"Join \" << *this << \" and \" << other << \"\\n\";);\n\n      base_domain_t left_dom(m_inv);\n      cell_varmap_t left_cell_varmap(m_cell_varmap);\n      smashed_varmap_t left_smashed_varmap(m_smashed_varmap);\n\n      base_domain_t right_dom(other.m_inv);\n      cell_varmap_t right_cell_varmap(other.m_cell_varmap);\n      smashed_varmap_t right_smashed_varmap(other.m_smashed_varmap);\n\n      // Must be done before the renaming.\n      auto out_array_map = std::move(m_array_map.join(\n          other.m_array_map, left_cell_varmap, left_smashed_varmap, left_dom,\n          right_cell_varmap, right_smashed_varmap, right_dom));\n\n      smashed_varmap_t out_smashed_varmap;\n      cell_varmap_t out_cell_varmap;\n      do_renaming_for_join(left_dom, right_dom, left_smashed_varmap,\n                           right_smashed_varmap, left_cell_varmap,\n                           right_cell_varmap, out_smashed_varmap,\n                           out_cell_varmap);\n\n      array_adaptive_domain_t res(\n          left_dom | right_dom, std::move(out_array_map),\n          std::move(out_cell_varmap), std::move(out_smashed_varmap));\n\n      CRAB_LOG(\"array-adaptive\", crab::outs() << \"Res=\" << res << \"\\n\";);\n      return res;\n    }\n  }\n\n  array_adaptive_domain_t\n  operator&(const array_adaptive_domain_t &other) const override {\n    crab::CrabStats::count(domain_name() + \".count.meet\");\n    crab::ScopedCrabStats __st__(domain_name() + \".meet\");\n    if (is_bottom() || other.is_top()) {\n      return *this;\n    } else if (is_top() || other.is_bottom()) {\n      return other;\n    } else {\n      CRAB_LOG(\"array-adaptive\",\n               crab::outs() << \"Meet \" << *this << \" and \" << other << \"\\n\";);\n\n      base_domain_t left_dom(m_inv);\n      cell_varmap_t left_cell_varmap(m_cell_varmap);\n      smashed_varmap_t left_smashed_varmap(m_smashed_varmap);\n\n      base_domain_t right_dom(other.m_inv);\n      cell_varmap_t right_cell_varmap(other.m_cell_varmap);\n      smashed_varmap_t right_smashed_varmap(other.m_smashed_varmap);\n\n      // Must be done before the renaming.\n      auto out_array_map = m_array_map.meet(\n          other.m_array_map, left_cell_varmap, left_smashed_varmap, left_dom,\n          right_cell_varmap, right_smashed_varmap, right_dom);\n\n      smashed_varmap_t out_smashed_varmap;\n      cell_varmap_t out_cell_varmap;\n      do_renaming_for_meet(left_dom, right_dom, left_smashed_varmap,\n                           right_smashed_varmap, left_cell_varmap,\n                           right_cell_varmap, out_smashed_varmap,\n                           out_cell_varmap);\n\n      array_adaptive_domain_t res(\n          left_dom & right_dom, std::move(out_array_map),\n          std::move(out_cell_varmap), std::move(out_smashed_varmap));\n      CRAB_LOG(\"array-adaptive\", crab::outs() << \"Res=\" << res << \"\\n\";);\n      return res;\n    }\n  }\n\n  array_adaptive_domain_t\n  operator||(const array_adaptive_domain_t &other) const override {\n    crab::CrabStats::count(domain_name() + \".count.widening\");\n    crab::ScopedCrabStats __st__(domain_name() + \".widening\");\n    if (other.is_bottom()) {\n      return *this;\n    } else if (is_bottom()) {\n      return other;\n    } else {\n      CRAB_LOG(\"array-adaptive\", crab::outs() << \"Widening \" << *this << \" and \"\n                                              << other << \"\\n\";);\n\n      base_domain_t left_dom(m_inv);\n      cell_varmap_t left_cell_varmap(m_cell_varmap);\n      smashed_varmap_t left_smashed_varmap(m_smashed_varmap);\n\n      base_domain_t right_dom(other.m_inv);\n      cell_varmap_t right_cell_varmap(other.m_cell_varmap);\n      smashed_varmap_t right_smashed_varmap(other.m_smashed_varmap);\n\n      // Must be done before the renaming.\n      auto out_array_map = m_array_map.join(\n          other.m_array_map, left_cell_varmap, left_smashed_varmap, left_dom,\n          right_cell_varmap, right_smashed_varmap, right_dom);\n\n      smashed_varmap_t out_smashed_varmap;\n      cell_varmap_t out_cell_varmap;\n\n      do_renaming_for_join(left_dom, right_dom, left_smashed_varmap,\n                           right_smashed_varmap, left_cell_varmap,\n                           right_cell_varmap, out_smashed_varmap,\n                           out_cell_varmap);\n\n      array_adaptive_domain_t res(\n          left_dom || right_dom, std::move(out_array_map),\n          std::move(out_cell_varmap), std::move(out_smashed_varmap));\n      CRAB_LOG(\"array-adaptive\", crab::outs() << \"Res=\" << res << \"\\n\";);\n      return res;\n    }\n  }\n\n  array_adaptive_domain_t widening_thresholds(\n      const array_adaptive_domain_t &other,\n      const iterators::thresholds<number_t> &ts) const override {\n    crab::CrabStats::count(domain_name() + \".count.widening\");\n    crab::ScopedCrabStats __st__(domain_name() + \".widening\");\n    if (other.is_bottom()) {\n      return *this;\n    } else if (is_bottom()) {\n      return other;\n    } else {\n      CRAB_LOG(\"array-adaptive\", crab::outs() << \"Widening \" << *this << \" and \"\n                                              << other << \"\\n\";);\n\n      base_domain_t left_dom(m_inv);\n      cell_varmap_t left_cell_varmap(m_cell_varmap);\n      smashed_varmap_t left_smashed_varmap(m_smashed_varmap);\n\n      base_domain_t right_dom(other.m_inv);\n      cell_varmap_t right_cell_varmap(other.m_cell_varmap);\n      smashed_varmap_t right_smashed_varmap(other.m_smashed_varmap);\n\n      // Must be done before the renaming.\n      auto out_array_map = m_array_map.join(\n          other.m_array_map, left_cell_varmap, left_smashed_varmap, left_dom,\n          right_cell_varmap, right_smashed_varmap, right_dom);\n\n      smashed_varmap_t out_smashed_varmap;\n      cell_varmap_t out_cell_varmap;\n      do_renaming_for_join(left_dom, right_dom, left_smashed_varmap,\n                           right_smashed_varmap, left_cell_varmap,\n                           right_cell_varmap, out_smashed_varmap,\n                           out_cell_varmap);\n\n      array_adaptive_domain_t res(\n          left_dom.widening_thresholds(right_dom, ts), std::move(out_array_map),\n          std::move(out_cell_varmap), std::move(out_smashed_varmap));\n      CRAB_LOG(\"array-adaptive\", crab::outs() << \"Res=\" << res << \"\\n\";);\n      return res;\n    }\n  }\n\n  array_adaptive_domain_t\n  operator&&(const array_adaptive_domain_t &other) const override {\n    crab::CrabStats::count(domain_name() + \".count.narrowing\");\n    crab::ScopedCrabStats __st__(domain_name() + \".narrowing\");\n    if (is_bottom()) {\n      return *this;\n    } else if (other.is_bottom()) {\n      return other;\n    } else {\n      CRAB_LOG(\"array-adaptive\", crab::outs() << \"Narrowing \" << *this\n                                              << \" and \" << other << \"\\n\";);\n\n      base_domain_t left_dom(m_inv);\n      cell_varmap_t left_cell_varmap(m_cell_varmap);\n      smashed_varmap_t left_smashed_varmap(m_smashed_varmap);\n\n      base_domain_t right_dom(other.m_inv);\n      cell_varmap_t right_cell_varmap(other.m_cell_varmap);\n      smashed_varmap_t right_smashed_varmap(other.m_smashed_varmap);\n\n      // Must be done before the renaming.\n      auto out_array_map = m_array_map.join(\n          other.m_array_map, left_cell_varmap, left_smashed_varmap, left_dom,\n          right_cell_varmap, right_smashed_varmap, right_dom);\n\n      smashed_varmap_t out_smashed_varmap;\n      cell_varmap_t out_cell_varmap;\n\n      do_renaming_for_meet(left_dom, right_dom, left_smashed_varmap,\n                           right_smashed_varmap, left_cell_varmap,\n                           right_cell_varmap, out_smashed_varmap,\n                           out_cell_varmap);\n\n      array_adaptive_domain_t res(\n          left_dom && right_dom, std::move(out_array_map),\n          std::move(out_cell_varmap), std::move(out_smashed_varmap));\n\n      CRAB_LOG(\"array-adaptive\", crab::outs() << \"Res=\" << res << \"\\n\";);\n      return res;\n    }\n  }\n\n  void forget(const variable_vector_t &variables) override {\n    crab::CrabStats::count(domain_name() + \".count.forget\");\n    crab::ScopedCrabStats __st__(domain_name() + \".forget\");\n\n    if (is_bottom() || is_top()) {\n      return;\n    }\n\n    variable_vector_t scalar_variables;\n    scalar_variables.reserve(variables.size());\n    for (variable_t v : variables) {\n      if (v.get_type().is_array()) {\n        CRAB_LOG(\"array-adaptive\",\n                 crab::outs() << \"Forget array variable \" << v << \"\\n\";);\n        forget_array(v);\n      } else {\n        CRAB_LOG(\"array-adaptive\",\n                 crab::outs() << \"Forget scalar variable \" << v << \"\\n\";);\n        scalar_variables.push_back(v);\n      }\n    }\n    m_inv.forget(scalar_variables);\n  }\n\n  void project(const variable_vector_t &variables) override {\n    crab::CrabStats::count(domain_name() + \".count.project\");\n    crab::ScopedCrabStats __st__(domain_name() + \".project\");\n\n    if (is_bottom() || is_top()) {\n      return;\n    }\n\n    // if we must keep array variable v then we need to keep all its\n    // synthetic cells in m_inv.\n\n    variable_vector_t keep_vars;\n    std::set<variable_t> keep_arrays;\n    for (variable_t v : variables) {\n      if (v.get_type().is_array()) {\n        keep_arrays.insert(v);\n      } else {\n        keep_vars.push_back(v);\n      }\n    }\n\n    std::vector<variable_t> array_variables = get_array_variables();\n    for (variable_t v : array_variables) {\n      if (keep_arrays.count(v) > 0) {\n        // keep all cells of v\n        const array_state &as = lookup_array_state(v);\n        if (!as.is_smashed()) {\n          const offset_map_t &om = as.get_offset_map();\n          std::vector<cell_t> cells = om.get_all_cells();\n          for (auto &c : cells) {\n            if (variable_opt_t v_opt = get_scalar(v, c)) {\n              keep_vars.push_back(*v_opt);\n            }\n          }\n        } else {\n          keep_vars.push_back(get_smashed_variable(v, m_smashed_varmap));\n        }\n      } else {\n        m_array_map -= v;\n        m_cell_varmap.erase(v);\n        m_smashed_varmap.erase(v);\n      }\n    }\n\n    // Finally we project\n    m_inv.project(keep_vars);\n  }\n\n  void normalize() override {\n    CRAB_WARN(\"array adaptive normalize not implemented\");\n  }\n\n  void minimize() override { m_inv.minimize(); }\n\n  virtual interval_t operator[](const variable_t &v) override {\n    if (!v.get_type().is_array()) {\n      return m_inv[v];\n    } else {\n      return interval_t::top();\n    }\n  }\n\n  /* begin intrinsics operations */\n  void intrinsic(std::string name,\n\t\t const variable_or_constant_vector_t &inputs,\n                 const variable_vector_t &outputs) override {\n    if ((std::all_of(inputs.begin(), inputs.end(),\n                     [](const variable_or_constant_t &v) {\n                       return v.get_type().is_integer() ||\n                              v.get_type().is_bool();\n                     })) &&\n        (std::all_of(outputs.begin(), outputs.end(),\n\t\t     [](const variable_t &v) {\n          return v.get_type().is_integer() || v.get_type().is_bool();\n        }))) {\n      m_inv.intrinsic(name, inputs, outputs);\n    } else {\n      CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", domain_name());\n    }\n  }\n\n  void backward_intrinsic(std::string name,\n\t\t\t  const variable_or_constant_vector_t &inputs,\n                          const variable_vector_t &outputs,\n                          const array_adaptive_domain_t &invariant) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", domain_name());\n  }\n  /* end intrinsics operations */\n\n  void operator+=(const linear_constraint_system_t &csts) override {\n    crab::CrabStats::count(domain_name() + \".count.add_constraints\");\n    crab::ScopedCrabStats __st__(domain_name() + \".add_constraints\");\n\n    m_inv += csts;\n\n    CRAB_LOG(\"array-adaptive\",\n             crab::outs() << \"assume(\" << csts << \")  \" << *this << \"\\n\";);\n  }\n\n  void operator-=(const variable_t &var) override {\n    crab::CrabStats::count(domain_name() + \".count.forget\");\n    crab::ScopedCrabStats __st__(domain_name() + \".forget\");\n\n    if (is_bottom()) {\n      return;\n    }\n\n    if (var.get_type().is_array()) {\n      forget_array(var);\n    } else {\n      m_inv -= var;\n    }\n  }\n\n  void assign(const variable_t &x, const linear_expression_t &e) override {\n    crab::CrabStats::count(domain_name() + \".count.assign\");\n    crab::ScopedCrabStats __st__(domain_name() + \".assign\");\n\n    m_inv.assign(x, e);\n\n    CRAB_LOG(\"array-adaptive\", crab::outs() << \"apply \" << x << \" := \" << e\n                                            << \" \" << *this << \"\\n\";);\n  }\n\n  void apply(arith_operation_t op, const variable_t &x, const variable_t &y,\n             number_t z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    m_inv.apply(op, x, y, z);\n\n    CRAB_LOG(\"array-adaptive\", crab::outs()\n                                   << \"apply \" << x << \" := \" << y << \" \" << op\n                                   << \" \" << z << \" \" << *this << \"\\n\";);\n  }\n\n  void apply(arith_operation_t op, const variable_t &x, const variable_t &y,\n             const variable_t &z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    m_inv.apply(op, x, y, z);\n\n    CRAB_LOG(\"array-adaptive\", crab::outs()\n                                   << \"apply \" << x << \" := \" << y << \" \" << op\n                                   << \" \" << z << \" \" << *this << \"\\n\";);\n  }\n\n  void select(const variable_t &lhs, const linear_constraint_t &cond,\n\t\t      const linear_expression_t &e1,  const linear_expression_t &e2) override {\n    m_inv.select(lhs, cond, e1, e2);\n  }\n  \n  void backward_assign(const variable_t &x, const linear_expression_t &e,\n                       const array_adaptive_domain_t &inv) override {\n    m_inv.backward_assign(x, e, inv.m_inv);\n  }\n\n  void backward_apply(arith_operation_t op, const variable_t &x,\n                      const variable_t &y, number_t z,\n                      const array_adaptive_domain_t &inv) override {\n    m_inv.backward_apply(op, x, y, z, inv.m_inv);\n  }\n\n  void backward_apply(arith_operation_t op, const variable_t &x,\n                      const variable_t &y, const variable_t &z,\n                      const array_adaptive_domain_t &inv) override {\n    m_inv.backward_apply(op, x, y, z, inv.m_inv);\n  }\n\n  void apply(int_conv_operation_t op, const variable_t &dst,\n             const variable_t &src) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    m_inv.apply(op, dst, src);\n  }\n\n  void apply(bitwise_operation_t op, const variable_t &x, const variable_t &y,\n             const variable_t &z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    m_inv.apply(op, x, y, z);\n\n    CRAB_LOG(\"array-adaptive\", crab::outs()\n                                   << \"apply \" << x << \" := \" << y << \" \" << op\n                                   << \" \" << z << \" \" << *this << \"\\n\";);\n  }\n\n  void apply(bitwise_operation_t op, const variable_t &x, const variable_t &y,\n             number_t k) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    m_inv.apply(op, x, y, k);\n\n    CRAB_LOG(\"array-adaptive\", crab::outs()\n                                   << \"apply \" << x << \" := \" << y << \" \" << op\n                                   << \" \" << k << \" \" << *this << \"\\n\";);\n  }\n\n  \n  \n  // boolean operators\n  virtual void assign_bool_cst(const variable_t &lhs,\n                               const linear_constraint_t &rhs) override {\n    m_inv.assign_bool_cst(lhs, rhs);\n  }\n\n  virtual void assign_bool_ref_cst(const variable_t &lhs,\n                                   const reference_constraint_t &rhs) override {\n    m_inv.assign_bool_ref_cst(lhs, rhs);\n  }\n\n  virtual void assign_bool_var(const variable_t &lhs, const variable_t &rhs,\n                               bool is_not_rhs) override {\n    m_inv.assign_bool_var(lhs, rhs, is_not_rhs);\n  }\n\n  virtual void apply_binary_bool(bool_operation_t op, const variable_t &x,\n                                 const variable_t &y,\n                                 const variable_t &z) override {\n    m_inv.apply_binary_bool(op, x, y, z);\n  }\n\n  virtual void assume_bool(const variable_t &v, bool is_negated) override {\n    m_inv.assume_bool(v, is_negated);\n  }\n\n  virtual void select_bool(const variable_t &lhs, const variable_t &cond,\n\t\t\t   const variable_t &b1, const variable_t &b2) override {\n    m_inv.select_bool(lhs, cond, b1, b2);\n  }\n  \n  // backward boolean operators\n  virtual void\n  backward_assign_bool_cst(const variable_t &lhs,\n                           const linear_constraint_t &rhs,\n                           const array_adaptive_domain_t &inv) override {\n    m_inv.backward_assign_bool_cst(lhs, rhs, inv.m_inv);\n  }\n\n  virtual void\n  backward_assign_bool_ref_cst(const variable_t &lhs,\n                               const reference_constraint_t &rhs,\n                               const array_adaptive_domain_t &inv) override {\n    m_inv.backward_assign_bool_ref_cst(lhs, rhs, inv.m_inv);\n  }\n\n  virtual void\n  backward_assign_bool_var(const variable_t &lhs, const variable_t &rhs,\n                           bool is_not_rhs,\n                           const array_adaptive_domain_t &inv) override {\n    m_inv.backward_assign_bool_var(lhs, rhs, is_not_rhs, inv.m_inv);\n  }\n\n  virtual void\n  backward_apply_binary_bool(bool_operation_t op, const variable_t &x,\n                             const variable_t &y, const variable_t &z,\n                             const array_adaptive_domain_t &inv) override {\n    m_inv.backward_apply_binary_bool(op, x, y, z, inv.m_inv);\n  }\n\n  /// array_adaptive is a functor domain that implements all\n  /// operations except region/reference operations.\n  REGION_AND_REFERENCE_OPERATIONS_NOT_IMPLEMENTED(array_adaptive_domain_t)\n\n  // array_operators_api\n\n  // array_init returns a fresh array where all elements between\n  // lb_idx and ub_idx are initialized to val. Thus, the first thing\n  // we need to do is to kill existing cells.\n  virtual void array_init(const variable_t &a,\n                          const linear_expression_t &elem_size,\n                          const linear_expression_t &lb_idx,\n                          const linear_expression_t &ub_idx,\n                          const linear_expression_t &val) override {\n    crab::CrabStats::count(domain_name() + \".count.array_init\");\n    crab::ScopedCrabStats __st__(domain_name() + \".array_init\");\n\n    if (is_bottom())\n      return;\n\n    const array_state &as = lookup_array_state(a);\n    // The array shouldn't be smashed yet\n    if (!as.is_smashed()) {\n      array_state next_as(as); // important to make the copy\n      offset_map_t &om = next_as.get_offset_map();\n      std::vector<cell_t> old_cells = om.get_all_cells();\n      if (!old_cells.empty()) {\n        kill_cells(a, old_cells, om);\n        m_array_map.set(a, next_as);\n      }\n    }\n\n    array_store_range(a, elem_size, lb_idx, ub_idx, val);\n  }\n\n  virtual void array_load(const variable_t &lhs, const variable_t &a,\n                          const linear_expression_t &elem_size,\n                          const linear_expression_t &i) override {\n    crab::CrabStats::count(domain_name() + \".count.array_load\");\n    crab::ScopedCrabStats __st__(domain_name() + \".array_load\");\n\n    if (is_bottom())\n      return;\n\n    uint64_t e_sz = check_and_get_elem_size(elem_size);\n    const array_state &as = lookup_array_state(a);\n    if (as.is_smashed()) {\n      // Check smashed array is consistent with elem_size\n      const cp_domain_t &a_elem_size = as.get_element_sz();\n      cp_domain_t cp_e_sz((int64_t)e_sz);\n      cp_e_sz |= a_elem_size;\n      if (!cp_e_sz.is_top()) {\n        variable_t smashed_a = get_smashed_variable(a, m_smashed_varmap);\n        m_inv.array_load(lhs, smashed_a, elem_size, i);\n        goto array_load_end;\n      } else {\n        // lhs will be forgotten\n      }\n    } else {\n      interval_t ii = to_interval(i);\n      if (boost::optional<number_t> n = ii.singleton()) {\n        array_state next_as(as); // important to make the copy\n        offset_map_t &offset_map = next_as.get_offset_map();\n        offset_t o(static_cast<int64_t>(*n));\n        std::vector<cell_t> cells;\n        offset_map.get_overlap_cells(o, e_sz, cells);\n        CRAB_LOG(\"array-adaptive\",\n                 crab::outs() << \"Number of overlapping cells=\" << cells.size()\n                              << \"\\n\";);\n\n        if (!cells.empty()) {\n          CRAB_LOG(\"array-adaptive\",\n                   CRAB_WARN(\"Ignored read from cell \", a, \"[\", o, \"...\",\n                             o.index() + e_sz - 1, \"]\",\n                             \" because it overlaps with \", cells.size(),\n                             \" cells\"););\n          /*\n            TODO: we can apply here \"Value Recomposition\" 'a la'\n            Mine'06 to construct values of some type from a sequence\n            of bytes. It can be endian-independent but it would more\n            precise if we choose between little- and big-endian.\n          */\n        } else {\n          variable_t rhs = mk_named_cell(a, o, e_sz, offset_map).second;\n          // Here it's ok to do assignment (instead of expand)\n          // because c is not a summarized variable. Otherwise, it\n          // would be unsound.\n          do_assign(lhs, rhs);\n          m_array_map.set(a, next_as);\n          goto array_load_end;\n        }\n      } else {\n        linear_expression_t symb_lb(i);\n        linear_expression_t symb_ub(i + number_t(e_sz - 1));\n        std::vector<cell_t> cells;\n        const offset_map_t &offset_map = as.get_offset_map();\n        offset_map.get_overlap_cells_symbolic_offset(m_inv, symb_lb, symb_ub,\n                                                     cells);\n        // XXX: if we have a large array that is never smashed but we\n        // do many reads with symbolic offsets then it might be better\n        // to smash the array so that each read is cheaper.\n        if (crab_domain_params_man::get().array_adaptive_is_smashable()) {\n          if (array_state::can_be_smashed(cells, e_sz, true)) {\n            // we smash all overlapping cells into a fresh array\n            // (summarized) variable\n            auto &vfac =\n                const_cast<varname_t *>(&(a.name()))->get_var_factory();\n            variable_t fresh_var(vfac.get(), a.get_type());\n            bool found_cell_without_scalar = false;\n            for (unsigned k = 0, num_cells = cells.size(); k < num_cells; ++k) {\n              const cell_t &c = cells[k];\n              auto c_scalar_opt = get_scalar(a, c);\n              if (!c_scalar_opt) {\n                CRAB_LOG(\"array-adaptive\",\n                         CRAB_WARN(\"array adaptive: ignored array load from \",\n                                   a, \" because non-constant array index \", i,\n                                   \"=\", ii, \" because found unnamed cell \",\n                                   c););\n\n                found_cell_without_scalar = true;\n                break;\n              }\n              const bool is_strong_update = (k == 0);\n              m_inv.array_store(fresh_var, elem_size, i, *c_scalar_opt,\n                                is_strong_update);\n            }\n            if (found_cell_without_scalar) {\n              m_inv -= lhs;\n            } else {\n              // we read from the temporary summarized variable\n              m_inv.array_load(lhs, fresh_var, elem_size, i);\n            }\n            // we forget the temporary summarized variable\n            m_inv -= fresh_var;\n            goto array_load_end;\n          } else {\n            CRAB_LOG(\"array-adaptive\",\n                     CRAB_WARN(\"array adaptive: ignored array load from \", a,\n                               \" because non-constant array index \", i, \"=\", ii,\n                               \" and cannot smash the array\"););\n          }\n        } else {\n          CRAB_LOG(\"array-adaptive\",\n                   CRAB_WARN(\"array adaptive: ignored array load from \", a,\n                             \" because non-constant array index \", i, \"=\",\n                             ii););\n        }\n      }\n    }\n    m_inv -= lhs;\n\n  array_load_end:\n    CRAB_LOG(\"array-adaptive\", linear_expression_t ub = i + elem_size - 1;\n             crab::outs() << lhs << \":=\" << a << \"[\" << i << \"...\" << ub\n                          << \"]  -- \" << *this << \"\\n\";);\n  }\n\n  virtual void array_store(const variable_t &a,\n                           const linear_expression_t &elem_size,\n                           const linear_expression_t &i,\n                           const linear_expression_t &val,\n                           bool is_strong_update) override {\n    crab::CrabStats::count(domain_name() + \".count.array_store\");\n    crab::ScopedCrabStats __st__(domain_name() + \".array_store\");\n\n    if (is_bottom())\n      return;\n\n    uint64_t e_sz = check_and_get_elem_size(elem_size);\n    const array_state &as = lookup_array_state(a);\n\n    if (as.is_smashed()) {\n      variable_t smashed_a = get_smashed_variable(a, m_smashed_varmap);\n      const cp_domain_t &a_elem_size = as.get_element_sz();\n      cp_domain_t cp_e_sz((int64_t)e_sz);\n      cp_e_sz |= a_elem_size;\n      if (!cp_e_sz.is_top()) {\n        m_inv.array_store(smashed_a, elem_size, i, val, is_strong_update);\n      } else {\n        m_inv -= smashed_a;\n      }\n    } else {\n      interval_t ii = to_interval(i);\n      array_state next_as(as);\n      offset_map_t &offset_map = next_as.get_offset_map();\n      boost::optional<number_t> n_opt = ii.singleton();\n      if (n_opt && (offset_map.get_number_cells() <\n\t\t    crab_domain_params_man::get().array_adaptive_max_array_size())) {\n\n        // -- Constant index: kill overlapping cells + perform strong update\n        std::vector<cell_t> cells;\n        offset_t o(static_cast<int64_t>(*n_opt));\n        offset_map.get_overlap_cells(o, e_sz, cells);\n        if (cells.size() > 0) {\n          CRAB_LOG(\"array-adaptive\",\n                   CRAB_WARN(\"Killed \", cells.size(),\n                             \" overlapping cells with \", \"[\", o, \"...\",\n                             o.index() + e_sz - 1, \"]\", \" before writing.\"));\n          kill_cells(a, cells, offset_map);\n        }\n        // Perform scalar update\n        // -- create a new cell it there is no one already\n        variable_t scalar_v = mk_named_cell(a, o, e_sz, offset_map).second;\n        // -- strong update\n        do_assign(scalar_v, val);\n      } else {\n        // -- Non-constant index: kill overlapping cells\n\n        if (n_opt) {\n          CRAB_LOG(\"array-adaptive\",\n                   crab::outs()\n                       << \"array write to \" << a << \" with constant index \" << i\n                       << \"=\" << ii << \" but array size exceeded threshold of \"\n\t\t       << crab_domain_params_man::get().array_adaptive_max_array_size()\n                       << \" so smashing is happening.\\n\";);\n        } else {\n          CRAB_LOG(\"array-adaptive\", crab::outs() << \"array write to \" << a\n                                                  << \" with non-constant index \"\n                                                  << i << \"=\" << ii << \"\\n\";);\n        }\n\n        bool smashed = false; // whether smashing took place\n        if (crab_domain_params_man::get().array_adaptive_is_smashable()) {\n          std::vector<cell_t> cells = offset_map.get_all_cells();\n          if (next_as.can_be_smashed(e_sz) &&\n              // Smashing is expensive because it will go over all cells\n              // performing one join per weak update even if the smashed\n              // array is already unconstrained. We don't smash if the\n              // number of cells to be smashed is too large.\n              (cells.size() <= crab_domain_params_man::get().array_adaptive_max_smashable_cells())) {\n            smashed = true;\n            CRAB_LOG(\"array-adaptive-smash\",\n                     crab::outs() << \"Array \" << a << \" will be smashed\\n\";);\n            bool found_cell_without_scalar = false;\n            variable_t smashed_a = get_smashed_variable(a, m_smashed_varmap);\n            for (unsigned k = 0, num_cells = cells.size(); k < num_cells; ++k) {\n              const cell_t &c = cells[k];\n              auto c_scalar_opt = get_scalar(a, c);\n              if (!c_scalar_opt) {\n                found_cell_without_scalar = true;\n                break;\n              }\n              const bool is_strong_update = (k == 0);\n              m_inv.array_store(smashed_a, elem_size, i, *c_scalar_opt,\n                                is_strong_update);\n              CRAB_LOG(\"array-adaptive-smash\",\n                       crab::outs() << \"\\tAfter smashing \" << *c_scalar_opt\n                                    << \"=\" << m_inv << \"\\n\";);\n            }\n\n            if (found_cell_without_scalar) {\n              m_inv -= smashed_a;\n            } else {\n              // Finally the array store\n              m_inv.array_store(smashed_a, elem_size, i, val, is_strong_update);\n            }\n\n            // The removal of cells from offset_map must be done after\n            // the array has been fully smashed.\n            for (unsigned k = 0, num_cells = cells.size(); k < num_cells; ++k) {\n              const cell_t &c = cells[k];\n              if (auto c_scalar_opt = get_scalar(a, c)) {\n                // destroy the synthethic cell from the base domain and\n                // from the offset map\n                m_inv -= *c_scalar_opt;\n              }\n              offset_map.erase(c);\n              m_cell_varmap.erase(a, c);\n            }\n            next_as.set_smashed(true);\n            next_as.get_element_sz() = cp_domain_t(number_t(e_sz));\n\n            CRAB_LOG(\"array-adaptive-smash\",\n                     crab::outs() << \"Array \" << a\n                                  << \" has been smashed:\" << m_inv << \"\\n\";);\n          } else {\n            CRAB_LOG(\"array-adaptive\",\n                     if (cells.size() >\n\t\t\t crab_domain_params_man::get().array_adaptive_max_smashable_cells()) {\n                       CRAB_WARN(\"Array \", a,\n                                 \" cannot be smashed because too many cells \",\n                                 cells.size(), \". Array write at index \", i,\n                                 \"=\", ii, \" is safely ignored\");\n                     } else {\n                       CRAB_WARN(\"Array \", a,\n                                 \" cannot be smashed so array write at index \",\n                                 i, \"=\", ii, \" is safely ignored\");\n                     });\n          }\n        }\n\n        if (!smashed) {\n          linear_expression_t symb_lb(i);\n          linear_expression_t symb_ub(i + number_t(e_sz - 1));\n          std::vector<cell_t> cells;\n          offset_map.get_overlap_cells_symbolic_offset(m_inv, symb_lb, symb_ub,\n                                                       cells);\n          CRAB_LOG(\n              \"array-adaptive\", crab::outs() << \"Killed cells: {\";\n              for (unsigned j = 0; j < cells.size();) {\n                crab::outs() << cells[j];\n                ++j;\n                if (j < cells.size()) {\n                  crab::outs() << \",\";\n                }\n              } crab::outs()\n              << \"}\\n\";);\n\n          kill_cells(a, cells, offset_map);\n        }\n      }\n      m_array_map.set(a, next_as);\n    }\n    CRAB_LOG(\"array-adaptive\", linear_expression_t ub = i + elem_size - 1;\n             crab::outs() << a << \"[\" << i << \"...\" << ub << \"]:=\" << val\n                          << \" -- \" << *this << \"\\n\";);\n  }\n\n  // Perform array stores over an array segment [lb_idx, ub_idx]\n  virtual void array_store_range(const variable_t &a,\n                                 const linear_expression_t &elem_size,\n                                 const linear_expression_t &lb_idx,\n                                 const linear_expression_t &ub_idx,\n                                 const linear_expression_t &val) override {\n    crab::CrabStats::count(domain_name() + \".count.array_store_range\");\n    crab::ScopedCrabStats __st__(domain_name() + \".array_store_range\");\n\n    if (is_bottom())\n      return;\n\n    uint64_t e_sz = check_and_get_elem_size(elem_size);\n    interval_t lb_i = to_interval(lb_idx);\n    auto lb = lb_i.singleton();\n    if (!lb) {\n      CRAB_WARN(\"array adaptive store range ignored because \", \"lower bound\",\n                lb_idx, \" is not constant\");\n      return;\n    }\n\n    interval_t ub_i = to_interval(ub_idx);\n    auto ub = ub_i.singleton();\n    if (!ub) {\n      CRAB_WARN(\"array adaptive store range ignored because \", \"upper bound \",\n                ub_idx, \" is not constant\");\n      return;\n    }\n\n    if (!(*lb <= *ub)) {\n      CRAB_WARN(\"array adaptive store range ignored because lower bound \", *lb,\n                \" is not less or equal than upper bound \", *ub);\n      return;\n    }\n\n    number_t num_elems = (*ub - *lb) / e_sz;\n    number_t e = *ub;\n    if (num_elems >\n\tcrab_domain_params_man::get().array_adaptive_max_array_size()) {\n      e = *lb +\n\t((number_t(crab_domain_params_man::get().array_adaptive_max_array_size()) - 1) * e_sz);\n      CRAB_WARN(\"array adaptive store range will ignore indexes greater than \",\n                e);\n    }\n\n    for (number_t i = *lb; i <= e;) {\n      array_store(a, elem_size, i, val, false);\n      i = i + e_sz;\n    }\n  }\n\n  virtual void array_assign(const variable_t &lhs,\n                            const variable_t &rhs) override {\n    CRAB_LOG(\"array-adaptive\",\n             crab::outs() << \"Array assign \" << lhs << \" := \" << rhs << \"\\n\";);\n\n    if (is_bottom()) {\n      return;\n    }\n\n    const array_state &as = lookup_array_state(rhs);\n    if (!as.is_smashed()) {\n      offset_map_t lhs_om;\n      const offset_map_t &rhs_om = as.get_offset_map();\n      std::map<variable_t, variable_t> renmap;\n      CRAB_LOG(\"array-adaptive-array-assign\", crab::outs() << \"Not smashed\\n\";);\n      std::vector<cell_t> cells = rhs_om.get_all_cells();\n      for (auto &c : cells) {\n        variable_opt_t c_scalar_opt = get_scalar(rhs, c);\n        if (!c_scalar_opt) {\n          continue;\n        }\n        // Create a new cell for lhs from rhs's cell.\n        auto named_cell =\n            mk_named_cell(lhs, c.get_offset(), c.get_size(), lhs_om);\n        variable_t new_c_scalar = named_cell.second;\n        renmap.insert({new_c_scalar, *c_scalar_opt});\n      }\n\n      cp_domain_t elem_sz = as.get_element_sz();\n      m_array_map.set(\n          lhs, array_state(false, std::move(elem_sz), std::move(lhs_om)));\n\n      CRAB_LOG(\n          \"array-adaptive-array-assign\", crab::outs() << \"array variables={\";\n          std::vector<variable_t> array_variables = get_array_variables();\n          for (unsigned i = 0, e = array_variables.size(); i < e;\n               ++i) { crab::outs() << array_variables[i] << \";\"; } crab::outs()\n          << \"}\\n\";);\n\n      for (auto &kv : renmap) {\n        CRAB_LOG(\"array-adaptive-array-assign\",\n                 crab::outs() << \"Base domain assign \" << kv.first\n                              << \" := \" << kv.second << \"\\n\";);\n        do_assign(kv.first, kv.second);\n      }\n    } else if (crab_domain_params_man::get().array_adaptive_is_smashable()) {\n      CRAB_LOG(\"array-adaptive-array-assign\", crab::outs() << \"Smashed\\n\";);\n      variable_t smashed_lhs = get_smashed_variable(lhs, m_smashed_varmap);\n      variable_t smashed_rhs = get_smashed_variable(rhs, m_smashed_varmap);\n      m_inv.array_assign(smashed_lhs, smashed_rhs);\n      m_array_map.set(lhs, as);\n    }\n    CRAB_LOG(\"array-adaptive\", crab::outs() << \"Res=\" << *this << \"\\n\";);\n  }\n\n  // backward array operations\n\n  virtual void\n  backward_array_init(const variable_t &a, const linear_expression_t &elem_size,\n                      const linear_expression_t &lb_idx,\n                      const linear_expression_t &ub_idx,\n                      const linear_expression_t &val,\n                      const array_adaptive_domain_t &invariant) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_array_init\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_array_init\");\n\n    if (is_bottom())\n      return;\n\n    // make all array cells uninitialized\n    const array_state &as = lookup_array_state(a);\n    if (!as.is_smashed()) {\n      array_state next_as(as);\n      offset_map_t &om = next_as.get_offset_map();\n      std::vector<cell_t> old_cells = om.get_all_cells();\n      if (!old_cells.empty()) {\n        kill_cells(a, old_cells, om);\n        m_array_map.set(a, next_as);\n      }\n    } else {\n      CRAB_WARN(\"array_adaptive::backward_array_init not implemented if array \"\n                \"smashed\");\n    }\n\n    // meet with forward invariant\n    *this = *this & invariant;\n  }\n\n  virtual void\n  backward_array_load(const variable_t &lhs, const variable_t &a,\n                      const linear_expression_t &elem_size,\n                      const linear_expression_t &i,\n                      const array_adaptive_domain_t &invariant) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_array_load\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_array_load\");\n\n    if (is_bottom())\n      return;\n\n    uint64_t e_sz = check_and_get_elem_size(elem_size);\n\n    const array_state &as = lookup_array_state(a);\n    if (as.is_smashed()) {\n      CRAB_WARN(\"array_adaptive::backward_array_load not implemented if array \"\n                \"smashed\");\n    } else {\n      // XXX: we use the forward invariant to extract the array index\n      interval_t ii = to_interval(i, invariant.get_content_domain());\n      if (boost::optional<number_t> n = ii.singleton()) {\n        array_state next_as(as);\n        offset_map_t &om = next_as.get_offset_map();\n        offset_t o(static_cast<int64_t>(*n));\n        cell_t c = mk_named_cell(a, o, e_sz, om).first;\n        do_backward_assign(lhs, a, c, invariant.m_inv);\n        m_array_map.set(a, next_as);\n      } else {\n        CRAB_LOG(\"array-adaptive\",\n                 CRAB_WARN(\"array index is not a constant value\"););\n        // -- Forget lhs\n        m_inv -= lhs;\n        // -- Meet with forward invariant\n        *this = *this & invariant;\n      }\n    }\n\n    CRAB_LOG(\"array-adaptive\", linear_expression_t ub = i + elem_size - 1;\n             crab::outs() << \"BACKWARD \" << lhs << \":=\" << a << \"[\" << i\n                          << \"...\" << ub << \"]  -- \" << *this << \"\\n\";);\n  }\n\n  virtual void backward_array_store(\n      const variable_t &a, const linear_expression_t &elem_size,\n      const linear_expression_t &i, const linear_expression_t &val,\n      bool /*is_strong_update*/,\n      const array_adaptive_domain_t &invariant) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_array_store\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_array_store\");\n\n    if (is_bottom())\n      return;\n\n    uint64_t e_sz = check_and_get_elem_size(elem_size);\n\n    // XXX: we use the forward invariant to extract the array index\n    const array_state &as = lookup_array_state(a);\n    if (as.is_smashed()) {\n      CRAB_WARN(\"array_adaptive::backward_array_store not implemented if array \"\n                \"smashed\");\n    } else {\n      array_state next_as(as);\n      offset_map_t &om = next_as.get_offset_map();\n      // XXX: we use the forward invariant to extract the array index\n      interval_t ii = to_interval(i, invariant.m_inv);\n      if (boost::optional<number_t> n = ii.singleton()) {\n        // -- Constant index and the store updated one single cell:\n        // -- backward assign in the base domain.\n        offset_t o(static_cast<int64_t>(*n));\n        std::vector<cell_t> cells;\n        om.get_overlap_cells(o, e_sz, cells);\n        // post: forall c \\in cells:: c != [o,e_sz)\n        // that is, get_overlap_cells returns cells different from [o, e_sz)\n        if (cells.size() >= 1) {\n          kill_cells(a, cells, om);\n          *this = *this & invariant;\n        } else {\n          // c might be in m_inv or not.\n          cell_t c = mk_named_cell(a, o, e_sz, om).first;\n          do_backward_assign(a, c, val, invariant.m_inv);\n        }\n      } else {\n        // TODOX: smash the array if needed\n\n        // -- Non-constant index or multiple overlapping cells: kill\n        // -- overlapping cells and meet with forward invariant.\n        linear_expression_t symb_lb(i);\n        linear_expression_t symb_ub(i + number_t(e_sz - 1));\n        std::vector<cell_t> cells;\n        om.get_overlap_cells_symbolic_offset(invariant.m_inv, symb_lb, symb_ub,\n                                             cells);\n        kill_cells(a, cells, om);\n        *this = *this & invariant;\n      }\n      m_array_map.set(a, next_as);\n    }\n\n    CRAB_LOG(\"array-adaptive\", linear_expression_t ub = i + elem_size - 1;\n             crab::outs() << \"BACKWARD \" << a << \"[\" << i << \"...\" << ub\n                          << \"]:=\" << val << \" -- \" << *this << \"\\n\";);\n  }\n\n  virtual void backward_array_store_range(\n      const variable_t &a, const linear_expression_t &elem_size,\n      const linear_expression_t &lb_idx, const linear_expression_t &ub_idx,\n      const linear_expression_t &val,\n      const array_adaptive_domain_t &invariant) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_array_store_range\");\n    crab::ScopedCrabStats __st__(domain_name() +\n                                 \".count.backward_array_store_range\");\n\n    if (is_bottom())\n      return;\n\n    uint64_t e_sz = check_and_get_elem_size(elem_size);\n\n    // make copy to avoid one extra copy\n    base_domain_t base_dom(invariant.m_inv);\n    interval_t lb_i = to_interval(lb_idx, base_dom);\n    auto lb = lb_i.singleton();\n    if (!lb) {\n      return;\n    }\n\n    interval_t ub_i = to_interval(ub_idx, base_dom);\n    auto ub = ub_i.singleton();\n    if (!ub) {\n      return;\n    }\n\n    if (!(*lb <= *ub)) {\n      return;\n    }\n\n    number_t num_elems = (*ub - *lb) / e_sz;\n    number_t e = *ub;\n    if (num_elems > crab_domain_params_man::get().array_adaptive_max_array_size()) {\n      e = *lb +\n\t((number_t(crab_domain_params_man::get().array_adaptive_max_array_size()) - 1) * e_sz);\n    }\n\n    for (number_t i = *lb; i <= e;) {\n      backward_array_store(a, elem_size, i, val, false, invariant);\n      i = i + e_sz;\n    }\n  }\n\n  virtual void\n  backward_array_assign(const variable_t &lhs, const variable_t &rhs,\n                        const array_adaptive_domain_t &invariant) override {\n    CRAB_WARN(\"backward_array_assign in array_adaptive domain not implemented\");\n  }\n\n  linear_constraint_system_t to_linear_constraint_system() const override {\n    crab::CrabStats::count(domain_name() +\n                           \".count.to_linear_constraint_system\");\n    crab::ScopedCrabStats __st__(domain_name() +\n                                 \".to_linear_constraint_system\");\n\n    return filter_nonscalar_vars(\n        std::move(m_inv.to_linear_constraint_system()));\n  }\n\n  disjunctive_linear_constraint_system_t\n  to_disjunctive_linear_constraint_system() const override {\n    disjunctive_linear_constraint_system_t res;\n    auto disj_csts = m_inv.to_disjunctive_linear_constraint_system();\n    for (auto &csts : disj_csts) {\n      auto filtered_csts = filter_nonscalar_vars(std::move(csts));\n      if (!filtered_csts.is_true()) {\n        res += filtered_csts;\n      }\n    }\n    return res;\n  }\n\n  base_domain_t get_content_domain() const { return m_inv; }\n\n  base_domain_t &get_content_domain() { return m_inv; }\n\n  void write(crab_os &o) const override {\n    o << m_inv;\n    CRAB_LOG(\n        \"array-adaptive-print-details\", crab::outs() << \"\\n\";\n        crab::outs() << \"=== CELLS PER ARRAY === \\n\";\n        for (auto it = m_array_map.begin(), et = m_array_map.end(); it != et;\n             ++it) {\n          const variable_t &v = it->first;\n          const array_state &as = it->second;\n          crab::outs() << \"ARRAY VAR \" << v << \":\\n\";\n          as.write(crab::outs());\n          crab::outs() << \"\\n\";\n        } crab::outs()\n        << \"=== MAP FROM CELLS TO SCALARS === \\n\";\n        for (auto const &kv\n             : m_cell_varmap) {\n          for (auto &cv : kv.second) {\n            crab::outs() << \"\\t\" << kv.first << \"#\" << cv.first << \" -> \"\n                         << cv.second << \"\\n\";\n          }\n        } crab::outs()\n        << \"=== SMASHED VARIABLES ===\\n\";\n        if (m_smashed_varmap.empty()) {\n          crab::outs() << \"No smashed variables\\n\";\n        } else {\n          for (auto const &kv : m_smashed_varmap) {\n            crab::outs() << kv.first << \" --> \" << kv.second << \"\\n\";\n          }\n        });\n  }\n\n  std::string domain_name() const override {\n    std::string name(\"ArrayAdaptive(\" + m_inv.domain_name() + \")\");\n    return name;\n  }\n\n  void expand(const variable_t &v, const variable_t &new_v) override {\n    if (is_bottom() || is_top()) {\n      return;\n    }\n\n    if (v.get_type() != new_v.get_type()) {\n      CRAB_ERROR(domain_name(), \"::expand must preserve same type\");\n    }\n\n    if (v.get_type().is_array()) {\n      CRAB_WARN(domain_name(), \"::expand not implemented for array variable\");\n    } else {\n      m_inv.expand(v, new_v);\n    }\n  }\n\n  void rename(const variable_vector_t &from,\n              const variable_vector_t &to) override {\n    if (is_bottom() || is_top()) {\n      return;\n    }\n\n    if (from.size() != to.size()) {\n      CRAB_ERROR(domain_name(), \"::rename expects vectors same sizes\");\n    }\n\n    CRAB_LOG(\"array-adaptive\", crab::outs()\n                                   << \"Before renaming \" << *this << \"\\n\";);\n\n    // Split into array and scalar variables\n    variable_vector_t array_from, array_to, scalar_from, scalar_to;\n    for (unsigned i = 0, sz = from.size(); i < sz; ++i) {\n      variable_t old_v = from[i];\n      variable_t new_v = to[i];\n      if (old_v.get_type() != new_v.get_type()) {\n        CRAB_ERROR(domain_name(), \"::rename must preserve same type\");\n      }\n      if (new_v.get_type().is_array()) {\n        array_from.push_back(old_v);\n        array_to.push_back(new_v);\n      } else {\n        scalar_from.push_back(old_v);\n        scalar_to.push_back(new_v);\n      }\n    }\n\n    unsigned num_arr_vars = array_from.size();\n    for (unsigned i = 0; i < num_arr_vars; ++i) {\n      variable_t old_v = array_from[i];\n      variable_t new_v = array_to[i];\n\n      // Rename m_smashed_varmap\n      auto it = m_smashed_varmap.find(old_v);\n      if (it != m_smashed_varmap.end()) {\n        variable_t new_smashed_v = mk_smashed_variable(new_v);\n        variable_t old_smashed_v = it->second;\n        m_smashed_varmap.erase(it);\n        m_smashed_varmap.insert({new_v, new_smashed_v});\n        // renaming in the base domain\n        scalar_from.push_back(old_smashed_v);\n        scalar_to.push_back(new_smashed_v);\n      }\n\n      // Rename m_cell_varmap and m_array_map\n      if (const array_state *old_as = m_array_map.find(old_v)) {\n        array_state new_as;\n        new_as.set_smashed(old_as->is_smashed());\n        cp_domain_t &new_cp_dom = new_as.get_element_sz();\n        new_cp_dom = old_as->get_element_sz();\n        offset_map_t &offset_map = new_as.get_offset_map();\n        // We insert here an empty vector so that no resizing can happen\n        // while we iterate over m_cell_varmap.\n        m_cell_varmap.insert(new_v);\n        for (auto it = m_cell_varmap.begin_cells(old_v),\n                  et = m_cell_varmap.end_cells(old_v);\n             it != et; ++it) {\n          const cell_t &old_c = (*it).first;\n          const variable_t &old_scalar = (*it).second;\n          /// Modify m_cell_varmap but it doesn't invalidate iterators\n          /// because new_v is already in m_cell_varmap.\n          auto named_cell = mk_named_cell(new_v, old_c.get_offset(),\n                                          old_c.get_size(), offset_map);\n          variable_t new_scalar = named_cell.second;\n          // renaming in the base domain\n          scalar_from.push_back(old_scalar);\n          scalar_to.push_back(new_scalar);\n        }\n        m_array_map -= old_v;\n        m_array_map.set(new_v, new_as);\n      }\n      m_cell_varmap.erase(old_v);\n    } // end for\n\n    m_inv.rename(scalar_from, scalar_to);\n    CRAB_LOG(\"array-adaptive\", crab::outs()\n                                   << \"After renaming \" << *this << \"\\n\";);\n  }\n\n}; // end array_adaptive_domain\n\ntemplate <typename Dom>\nstruct abstract_domain_traits<array_adaptive_domain<Dom>> {\n  using number_t = typename Dom::number_t;\n  using varname_t = typename Dom::varname_t;\n};\n\ntemplate <typename Dom>\nclass checker_domain_traits<array_adaptive_domain<Dom>> {\npublic:\n  using this_type = array_adaptive_domain<Dom>;\n  using base_domain_t = typename this_type::base_domain_t;\n  using linear_constraint_t = typename this_type::linear_constraint_t;\n  using disjunctive_linear_constraint_system_t =\n      typename this_type::disjunctive_linear_constraint_system_t;\n\n  static bool entail(this_type &lhs,\n                     const disjunctive_linear_constraint_system_t &rhs) {\n    base_domain_t &lhs_dom = lhs.get_content_domain();\n    return checker_domain_traits<base_domain_t>::entail(lhs_dom, rhs);\n  }\n\n  static bool entail(const disjunctive_linear_constraint_system_t &lhs,\n                     this_type &rhs) {\n    base_domain_t &rhs_dom = rhs.get_content_domain();\n    return checker_domain_traits<base_domain_t>::entail(lhs, rhs_dom);\n  }\n\n  static bool entail(this_type &lhs, const linear_constraint_t &rhs) {\n    base_domain_t &lhs_dom = lhs.get_content_domain();\n    return checker_domain_traits<base_domain_t>::entail(lhs_dom, rhs);\n  }\n\n  static bool intersect(this_type &inv, const linear_constraint_t &cst) {\n    base_domain_t &dom = inv.get_content_domain();\n    return checker_domain_traits<base_domain_t>::intersect(dom, cst);\n  }\n};\n\n} // namespace domains\n} // namespace crab\n", "meta": {"hexsha": "0b50476b9db8977a226bf9a7dc387f91d47af58b", "size": 111539, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/array_adaptive.hpp", "max_stars_repo_name": "LinerSu/crab", "max_stars_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 152.0, "max_stars_repo_stars_event_min_datetime": "2016-02-28T06:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:44:56.000Z", "max_issues_repo_path": "include/crab/domains/array_adaptive.hpp", "max_issues_repo_name": "LinerSu/crab", "max_issues_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2017-07-03T06:25:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T21:09:32.000Z", "max_forks_repo_path": "include/crab/domains/array_adaptive.hpp", "max_forks_repo_name": "LinerSu/crab", "max_forks_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-11-22T15:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T00:46:57.000Z", "avg_line_length": 35.4993634628, "max_line_length": 101, "alphanum_fraction": 0.597862631, "num_tokens": 27179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5452929244974096}}
{"text": "/*!\n* Copyright 2007  Technical University of Catalonia\n*\n* Use, modification and distribution is subject to the Boost Software\n* License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n* http://www.boost.org/LICENSE_1_0.txt)\n*\n*  Authors: Dmitry Bufistov\n*           Andrey Parfenov\n*/\n#include <boost/graph/howard_cycle_ratio.hpp>\n#include <boost/random/mersenne_twister.hpp> \n#include <boost/random/uniform_real.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/property_iter_range.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n\nusing namespace boost;\ntypedef adjacency_list<listS, listS, directedS, property<vertex_index_t, int, property<boost::vertex_name_t, std::string> >, \n        property<edge_weight_t, double, property<edge_weight2_t, double, property<edge_index_t, int> > > > grap_real_t;\n\ntemplate <typename TGraph>      \nvoid gen_rand_graph(TGraph& g, size_t nV, size_t nE)\n{\n        g.clear();\n        boost::mt19937 rng;\n        boost::generate_random_graph(g, nV, nE, rng, true, true);\n        boost::uniform_real<> ur(-1,10); \n        boost::variate_generator<boost::mt19937&, boost::uniform_real<> >       ew1rg(rng, ur);\n        randomize_property<edge_weight_t>(g, ew1rg);\n        boost::uniform_int<> uint(1,5); \n        boost::variate_generator<boost::mt19937&, boost::uniform_int<> >        ew2rg(rng, uint);\n        randomize_property<edge_weight2_t>(g, ew2rg);\n}\n\nint main(int argc, char* argv[])\n{\n        const double epsilon = 0.000000001;\n        double min_cr, max_cr; ///Minimum and maximum cycle ratio\n        typedef std::vector<graph_traits<grap_real_t>::edge_descriptor> ccReal_t; \n        ccReal_t cc; ///For storing critical edges\n        \n        \n        grap_real_t tgr;\n        property_map<grap_real_t, vertex_index_t>::type vim = get(vertex_index, tgr);\n        property_map<grap_real_t, edge_weight_t>::type ew1m = get(edge_weight, tgr);\n        property_map<grap_real_t, edge_weight2_t>::type ew2m = ew2m;\n        \n        gen_rand_graph(tgr, 1000, 300000);\n        std::cout << \"Vertices number: \" << num_vertices(tgr) << '\\n';\n        std::cout << \"Edges number: \" << num_edges(tgr) << '\\n';\n        int i = 0;\n        BGL_FORALL_VERTICES(vd, tgr, grap_real_t) put(vertex_index, tgr, vd, i++); ///Initialize vertex index property\n        boost::posix_time::ptime        st = boost::posix_time::microsec_clock::local_time();\n        max_cr = maximum_cycle_ratio(tgr, get(vertex_index, tgr), get(edge_weight, tgr), get(edge_weight2, tgr));\n        std::cout << \"Maximum cycle ratio is \" << max_cr << '\\n';\n        std::cout << \"Run time of the maximum_cycle_ratio() is \" << to_simple_string(boost::posix_time::microsec_clock::local_time() - st) << '\\n';\n\n        \n        ///One way to get the \"good\" value of the plus_infinity parameter\n        double pl_infnt = double(*std::max_element(get_property_iter_range(tgr, edge_weight).first, get_property_iter_range(tgr, edge_weight).second)) / \n                *std::min_element(get_property_iter_range(tgr, edge_weight2).first, get_property_iter_range(tgr, edge_weight2).second);\n        std::cout << \"Set infinity for minimum_cycle_ratio() call to \" << pl_infnt << '\\n';\n        i = 0;\n        BGL_FORALL_EDGES(ed, tgr, grap_real_t) put(edge_index, tgr, ed, i++); ///Initialize edge index property\n        min_cr = minimum_cycle_ratio(tgr, get(vertex_index, tgr), get(edge_weight, tgr), get(edge_weight2, tgr), get(edge_index, tgr), &cc, pl_infnt);\n        std::cout << \"Minimal cycle ratio is \" << min_cr << '\\n';\n        std::pair<double, double> cr(.0,.0);\n        std::cout << \"\\nCritical cycle is:\\n\";\n        for (ccReal_t::iterator itr = cc.begin(); itr != cc.end(); ++itr) \n        {\n                cr.first += get(edge_weight, tgr, *itr); cr.second += get(edge_weight2, tgr, *itr);\n                std::cout << \"(\" << get(vertex_index, tgr, source(*itr, tgr)) << \",\" << get(vertex_index, tgr, target(*itr, tgr)) << \") \";\n        }\n        std::cout << '\\n';\n        assert(std::abs(cr.first / cr.second - min_cr) < epsilon);\n        \n        return 0;\n}\n\n", "meta": {"hexsha": "4f543079a55c5f8ad35fd4f03008d4f91f059937", "size": 4227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/cycle_ratio_example.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/graph/example/cycle_ratio_example.cpp", "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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/graph/example/cycle_ratio_example.cpp", "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": 49.7294117647, "max_line_length": 153, "alphanum_fraction": 0.6531819257, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5452929203649576}}
{"text": "/*!\n * Distance.h\n *\n *  Created on: 2012/12/29\n *  \\author Hiroki Sudo\n *\n */\n\n#ifndef DISTANCE_H_\n#define DISTANCE_H_\n\n#include <vector>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/shared_ptr.hpp>\n#include \"Element.h\"\n\n/*!\n *\n */\nnamespace {\n/*!\n * Distance\n */\nnamespace Distance {\n\n/*!\n * Element\u30af\u30e9\u30b9\u306eVector\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3092\u5f15\u6570\u306b2\u3064\u53d6\u308a\u3001\u305d\u308c\u305e\u308c\u306e\u7de8\u96c6\u8ddd\u96e2(Levenstein\u8ddd\u96e2)\u3092\u8a08\u7b97\u3057\u307e\u3059\u3002\n * \u8fd4\u5024\u306f\u5f15\u6570\u306b\u6e21\u3055\u308c\u308bVector\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u306e\u8981\u7d20\u6570\u3067\u5272\u3089\u308c\u308b\u305f\u3081\u30010~1\u306e\u5024\u3092\u53d6\u308a\u307e\u3059\u3002\n * \u5024\u304c\u5927\u304d\u3051\u308c\u3070\u8ddd\u96e2\u306f\u96e2\u308c\u3066\u3044\u3066\u3001\u5c0f\u3055\u3051\u308c\u3070\u8ddd\u96e2\u304c\u8fd1\u3044\u3068\u8a00\u3046\u610f\u5473\u306b\u306a\u308a\u307e\u3059\u3002\u8a08\u7b97\u91cf\u306fO((n*m)^(1/2))\n */\ntemplate<class E>\ndouble levenstein(std::vector<E> ex1, std::vector<E> ex2) {\n    \n\tboost::numeric::ublas::matrix<int> matrix(0, 0);\n\tint col_size, row_size;\n\tint cost_delta, cost1, cost2, cost3, cost;\n\n\tif (ex1.size() == 0 && ex2.size() != 0)\n\t\treturn ex2.size();\n\tif (ex1.size() != 0 && ex2.size() == 0)\n\t\treturn ex1.size();\n\tif (ex1.size() == 0 && ex2.size() == 0)\n\t\treturn 0;\n\n\trow_size = ex1.size() + 1;\n\tcol_size = ex2.size() + 1;\n\n\tmatrix.resize(row_size, col_size);\n\n\tfor (int j = 0; j < col_size; j++) {\n\t\tmatrix(0, j) = j;\n\t}\n\tfor (int i = 0; i < row_size; i++) {\n\t\tmatrix(i, 0) = i;\n\t}\n\n\tfor (int index_ex1 = 0; index_ex1 < ex1.size(); index_ex1++) {\n\t\tfor (int index_ex2 = 0; index_ex2 < ex2.size(); index_ex2++) {\n\n\t\t\tif (ex1[index_ex1].is_sym() && ex2[index_ex2].is_sym()) {\n\t\t\t\tcost_delta = ex1[index_ex1] == ex2[index_ex2] ? 0 : 1;\n\t\t\t} else if (ex1[index_ex1].is_cat() && ex2[index_ex2].is_cat()) {\n\t\t\t\tcost_delta = ex1[index_ex1].obj == ex2[index_ex2].obj ? 0 : 1;\n\t\t\t} else {\n\t\t\t\tcost_delta = 1;\n\t\t\t}\n\n\t\t\tint x, y;\n\t\t\ty = index_ex1 + 1;\n\t\t\tx = index_ex2 + 1;\n\t\t\tcost1 = matrix(y - 1, x) + 1;\n\t\t\tcost2 = matrix(y, x - 1) + 1;\n\t\t\tcost3 = matrix(y - 1, x - 1) + cost_delta;\n\n\t\t\tcost = cost1;\n\t\t\tcost = cost2 < cost ? cost2 : cost;\n\t\t\tcost = cost3 < cost ? cost3 : cost;\n\n\t\t\tmatrix(y, x) = cost;\n\t\t}\n\t}\n\n\tint len;\n\tif (row_size > col_size)\n\t\tlen = row_size;\n\telse\n\t\tlen = col_size;\n\n\treturn (matrix(matrix.size1() - 1, matrix.size2() - 1))\n\t\t\t/ (static_cast<double>(len));\n}\n\n/*!\n * Vector\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u306e\u8981\u7d20\u6570\u3067\u5272\u3089\u306a\u3044\u305f\u3081\uff0c\u5024\u306f0~\u7121\u9650\u3068\u306a\u308bLevenstein\u8ddd\u96e2\n */\ntemplate<class E>\ndouble levenstein2(std::vector<E> ex1, std::vector<E> ex2) {\n    \n\tboost::numeric::ublas::matrix<int> matrix(0, 0);\n\tint col_size, row_size;\n\tint cost_delta, cost1, cost2, cost3, cost;\n\n\tif (ex1.size() == 0 && ex2.size() != 0)\n\t\treturn ex2.size();\n\tif (ex1.size() != 0 && ex2.size() == 0)\n\t\treturn ex1.size();\n\tif (ex1.size() == 0 && ex2.size() == 0)\n\t\treturn 0;\n\n\trow_size = ex1.size() + 1;\n\tcol_size = ex2.size() + 1;\n\n\tmatrix.resize(row_size, col_size);\n\n\tfor (int j = 0; j < col_size; j++) {\n\t\tmatrix(0, j) = j;\n\t}\n\tfor (int i = 0; i < row_size; i++) {\n\t\tmatrix(i, 0) = i;\n\t}\n\n\tfor (int index_ex1 = 0; index_ex1 < ex1.size(); index_ex1++) {\n\t\tfor (int index_ex2 = 0; index_ex2 < ex2.size(); index_ex2++) {\n\n\t\t\tif (ex1[index_ex1].is_sym() && ex2[index_ex2].is_sym()) {\n\t\t\t\tcost_delta = ex1[index_ex1] == ex2[index_ex2] ? 0 : 1;\n\t\t\t} else if (ex1[index_ex1].is_cat() && ex2[index_ex2].is_cat()) {\n\t\t\t\tcost_delta = ex1[index_ex1].obj == ex2[index_ex2].obj ? 0 : 1;\n\t\t\t} else {\n\t\t\t\tcost_delta = 1;\n\t\t\t}\n\n\t\t\tint x, y;\n\t\t\ty = index_ex1 + 1;\n\t\t\tx = index_ex2 + 1;\n\t\t\tcost1 = matrix(y - 1, x) + 1;\n\t\t\tcost2 = matrix(y, x - 1) + 1;\n\t\t\tcost3 = matrix(y - 1, x - 1) + cost_delta;\n\n\t\t\tcost = cost1;\n\t\t\tcost = cost2 < cost ? cost2 : cost;\n\t\t\tcost = cost3 < cost ? cost3 : cost;\n\n\t\t\tmatrix(y, x) = cost;\n\t\t}\n\t}\n\n\tint len;\n\tif (row_size > col_size)\n\t\tlen = row_size;\n\telse\n\t\tlen = col_size;\n\n\treturn (matrix(matrix.size1() - 1, matrix.size2() - 1));\n}\n\n\ntemplate <class E>\nint snake(int k, int y, std::vector<E >& ary1, std::vector<E >& ary2, int m, int n) {\n\tint x;\n\tx = y - k;\n\twhile (x < m && y < n && ary1[x] == ary2[y]) {\n\t\tx++;\n\t\ty++;\n\t}\n\n\treturn y;\n}\n/*!\n * O(np)\u6cd5\u306e\u5b9f\u88c5\n */\ntemplate<class E>\ndouble onp_lv(std::vector<E>& ary1, std::vector<E>& ary2, double limit = -1) {\n\tstd::vector<E> temp;\n\tstd::vector<int> fp;\n\tint size = 0;\n\tint delta = 0;\n\tint offset = 0;\n\tint n = 0;\n\tint m = 0;\n\tint p;\n\tint k;\n\tint i;\n\n\tif (ary1.size() > ary2.size()) {\n\t\ttemp = ary1;\n\t\tary1 = ary2;\n\t\tary2 = temp;\n\t}\n\n\tm = ary1.size();\n\tn = ary2.size();\n\n\toffset = m + 1;\n\tdelta = n - m;\n\tsize = m + n + 3;\n\n\tif (limit == -1) {\n\t\tlimit = 2 * m + delta;\n\t}\n\n\tfp = std::vector<int>(size, -1);\n\tp = -1;\n\tk = 0;\n\n\twhile (fp[delta + offset] < n) {\n\t\tp++;\n\n\t\tif (2 * p + delta >= (limit) * ary2.size() ) {\n\t\t\t//std::cerr << \"Cutted\" << std::endl;\n\t\t\treturn 1.0;\n\t\t}\n\n\t\tk = -p;\n\t\twhile (k < delta) {\n\t\t\tfp[k + offset] = fp[k - 1 + offset] + 1 > fp[k + 1 + offset] ?\n\t\t\t\tsnake(k, fp[k - 1 + offset] + 1, ary1, ary2, m, n) :\n\t\t\t\tsnake(k, fp[k + 1 + offset], ary1, ary2, m, n);\n\t\t\tk++;\n\t\t}\n\n\t\tk = delta + p;\n\t\twhile (k > delta) {\n\t\t\tfp[k + offset] = fp[k - 1 + offset] + 1 > fp[k + 1 + offset] ?\n\t\t\t\tsnake(k, fp[k - 1 + offset] + 1, ary1, ary2, m, n) :\n\t\t\t\tsnake(k, fp[k + 1 + offset], ary1, ary2, m, n);\n\t\t\tk--;\n\t\t}\n\n\t\tfp[delta + offset] = fp[delta - 1 + offset] + 1 > fp[delta + 1 + offset] ?\n\t\t\t\tsnake(delta, fp[delta - 1 + offset] + 1, ary1, ary2, m,\tn) :\n\t\t\t\tsnake(delta, fp[delta + 1 + offset], ary1, ary2, m, n);\n\t}\n\n\treturn (delta + 2 * p)/(static_cast<double>(ary2.size()));\n}\n\ntemplate<class E> \ndouble hamming(std::vector<E> ex1, std::vector<E> ex2){\n        \n    if(ex1.size()!=ex2.size()){\n        std::cerr <<  \"Happened error on hamming distance method.\" << std::endl;\n        std::exit(0);\n    }\n    typename std::vector<E>::iterator ex1_it;\n\n    ex1_it = ex1.begin();\n    int cnt = 0;\n    double ham_sum=0;\n    for(; ex1_it != ex1.end(); ex1_it++) {\n        \n        if((*ex1_it)!=ex2[cnt])\n            ham_sum+=1;\n        \n        cnt+=1;\n    }\n    return (ham_sum/(double)cnt);\n}\n\n} /*Distance*/\n}\n#endif /* DISTANCE_H_ */\n", "meta": {"hexsha": "23b224aee56f1d451ec94bf4ecc7149e43c94e5e", "size": 5689, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SOURCE/Distance.hpp", "max_stars_repo_name": "asciian/MSILM", "max_stars_repo_head_hexsha": "bfaea503888574d9d78ffb0b55f583f251ac6ea8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-04-17T08:43:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-17T08:43:28.000Z", "max_issues_repo_path": "SOURCE/Distance.hpp", "max_issues_repo_name": "asciian/MSILM", "max_issues_repo_head_hexsha": "bfaea503888574d9d78ffb0b55f583f251ac6ea8", "max_issues_repo_licenses": ["MIT"], "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/Distance.hpp", "max_forks_repo_name": "asciian/MSILM", "max_forks_repo_head_hexsha": "bfaea503888574d9d78ffb0b55f583f251ac6ea8", "max_forks_repo_licenses": ["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.5492424242, "max_line_length": 85, "alphanum_fraction": 0.5579187906, "num_tokens": 2226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5452929143596458}}
{"text": "/*\n* Copyright (c) by CryptoLab inc.\n* This program is licensed under a\n* Creative Commons Attribution-NonCommercial 3.0 Unported License.\n* You should have received a copy of the license along with this\n* work.  If not, see <http://creativecommons.org/licenses/by-nc/3.0/>.\n*/\n#include \"TestScheme.h\"\n\n#include <NTL/BasicThreadPool.h>\n#include <NTL/ZZ.h>\n#include <complex>\n\n#include \"Ciphertext.h\"\n#include \"EvaluatorUtils.h\"\n#include \"Ring.h\"\n#include \"Scheme.h\"\n#include \"SchemeAlgo.h\"\n#include \"SecretKey.h\"\n#include \"StringUtils.h\"\n#include \"TimeUtils.h\"\n#include \"SerializationUtils.h\"\n\nusing namespace std;\nusing namespace NTL;\n\n\n//----------------------------------------------------------------------------------\n//   STANDARD TESTS\n//----------------------------------------------------------------------------------\n\n\nvoid TestScheme::testEncrypt(long logq, long logp, long logn) {\n\tcout << \"!!! START TEST ENCRYPT !!!\" << endl;\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\tlong n = (1 << logn);\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\tCiphertext cipher;\n\n\ttimeutils.start(\"Encrypt\");\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\ttimeutils.stop(\"Encrypt\");\n\n\ttimeutils.start(\"Decrypt\");\n\tcomplex<double>* dvec = scheme.decrypt(secretKey, cipher);\n\ttimeutils.stop(\"Decrypt\");\n\n\tStringUtils::compare(mvec, dvec, n, \"val\");\n\n\tcout << \"!!! END TEST ENCRYPT !!!\" << endl;\n}\n\nvoid TestScheme::testEncryptSingle(long logq, long logp) {\n\tcout << \"!!! START TEST ENCRYPT SINGLE !!!\" << endl;\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\tcomplex<double> mval = EvaluatorUtils::randomComplex();\n\tCiphertext cipher;\n\n\ttimeutils.start(\"Encrypt Single\");\n\tscheme.encryptSingle(cipher, mval, logp, logq);\n\ttimeutils.stop(\"Encrypt Single\");\n\n\tcomplex<double> dval = scheme.decryptSingle(secretKey, cipher);\n\n\tStringUtils::compare(mval, dval, \"val\");\n\n\tcout << \"!!! END TEST ENCRYPT SINGLE !!!\" << endl;\n}\n\nvoid TestScheme::testAdd(long logq, long logp, long logn) {\n\tcout << \"!!! START TEST ADD !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\tlong n = (1 << logn);\n\tcomplex<double>* mvec1 = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* mvec2 = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* madd = new complex<double>[n];\n\n\tfor(long i = 0; i < n; i++) {\n\t\tmadd[i] = mvec1[i] + mvec2[i];\n\t}\n\n\tCiphertext cipher1, cipher2;\n\tscheme.encrypt(cipher1, mvec1, n, logp, logq);\n\tscheme.encrypt(cipher2, mvec2, n, logp, logq);\n\n\ttimeutils.start(\"Addition\");\n\tscheme.multAndEqual(cipher1, cipher2);\n\ttimeutils.stop(\"Addition\");\n\n\tcomplex<double>* dadd = scheme.decrypt(secretKey, cipher1);\n\n\t//StringUtils::showVec(mvec1, n);\n\t//StringUtils::showVec(mvec2, n);\n\t//<StringUtils::showVec(madd, n);\n\n\tStringUtils::compare(madd, dadd, n, \"add\");\n\n\tcout << \"!!! END TEST ADD !!!\" << endl;\n}\n\nvoid TestScheme::testMult(long logq, long logp, long logn) {\n\tcout << \"!!! START TEST MULT !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\tlong n = (1 << logn);\n\tcomplex<double>* mvec1 = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* mvec2 = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* mmult = new complex<double>[n];\n\n\tStringUtils::showVec(mvec1, n);\n\tStringUtils::showVec(mvec2, n);\n\n\tfor(long i = 0; i < n; i++) {\n\t\tmmult[i] = mvec1[i] * mvec2[i];\n\t}\n\n\tCiphertext cipher1, cipher2;\n\tscheme.encrypt(cipher1, mvec1, n, logp, logq);\n\tscheme.encrypt(cipher2, mvec2, n, logp, logq);\n\n\ttimeutils.start(\"Multiplication\");\n\tscheme.multAndEqual(cipher1, cipher2);\n\ttimeutils.stop(\"Multiplication\");\n\n\tcomplex<double>* dmult = scheme.decrypt(secretKey, cipher1);\n\n\tStringUtils::showVec(mmult, n);\n\n\tStringUtils::compare(mmult, dmult, n, \"mult\");\n\n\tcout << \"!!! END TEST MULT !!!\" << endl;\n}\n\nvoid TestScheme::testimult(long logq, long logp, long logn) {\n\tcout << \"!!! START TEST i MULTIPLICATION !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\tlong n = (1 << logn);\n\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* imvec = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\timvec[i].real(-mvec[i].imag());\n\t\timvec[i].imag(mvec[i].real());\n\t}\n\n\tStringUtils::showVec(mvec, n);\n\tStringUtils::showVec(imvec, n);\n\n\tCiphertext cipher;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(\"Multiplication by i\");\n\tscheme.imultAndEqual(cipher);\n\ttimeutils.stop(\"Multiplication by i\");\n\n\tcomplex<double>* idvec = scheme.decrypt(secretKey, cipher);\n\n\tStringUtils::compare(imvec, idvec, n, \"imult\");\n\n\tcout << \"!!! END TEST i MULTIPLICATION !!!\" << endl;\n}\n\n\n//----------------------------------------------------------------------------------\n//   ROTATE & CONJUGATE\n//----------------------------------------------------------------------------------\n\n\nvoid TestScheme::testRotateFast(long logq, long logp, long logn, long logr) {\n\tcout << \"!!! START TEST ROTATE FAST !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\tlong n = (1 << logn);\n\tlong r = (1 << logr);\n\tscheme.addLeftRotKey(secretKey, r);\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\tCiphertext cipher;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(\"Left Rotate Fast\");\n\tscheme.leftRotateFastAndEqual(cipher, r);\n\ttimeutils.stop(\"Left Rotate Fast\");\n\n\tcomplex<double>* dvec = scheme.decrypt(secretKey, cipher);\n\n\tStringUtils::showVec(mvec, n);\n\n\tEvaluatorUtils::leftRotateAndEqual(mvec, n, r);\n\n\tStringUtils::showVec(mvec, n);\n\t//StringUtils::showVec(mvec, n);\n\t//StringUtils::showVec(dvec, n);\n\tStringUtils::compare(mvec, dvec, n, \"rot\");\n\n\tcout << \"!!! END TEST ROTATE BY POWER OF 2 BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testConjugate(long logq, long logp, long logn) {\n\tcout << \"!!! START TEST CONJUGATE !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tscheme.addConjKey(secretKey);\n\n\tlong n = (1 << logn);\n\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* mvecconj = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmvecconj[i] = conj(mvec[i]);\n\t}\n\n\tCiphertext cipher;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(\"Conjugate\");\n\tscheme.conjugateAndEqual(cipher);\n\ttimeutils.stop(\"Conjugate\");\n\n\tcomplex<double>* dvecconj = scheme.decrypt(secretKey, cipher);\n\tStringUtils::showVec(mvec, n);\n\tStringUtils::showVec(mvecconj, n);\n\tStringUtils::compare(mvecconj, dvecconj, n, \"conj\");\n\n\tcout << \"!!! END TEST CONJUGATE !!!\" << endl;\n}\n\n\n//----------------------------------------------------------------------------------\n//   POWER & PRODUCT TESTS\n//----------------------------------------------------------------------------------\n\n\nvoid TestScheme::testPowerOf2(long logq, long logp, long logn, long logdeg) {\n\tcout << \"!!! START TEST POWER OF 2 !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tlong degree = 1 << logdeg;\n\tcomplex<double>* mvec = new complex<double>[n];\n\t//cout << \"mvec and mpow 2^\" << logdeg << endl;\n\tcomplex<double>* mpow = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmvec[i] = EvaluatorUtils::randomCircle();\n\t\tmpow[i] = pow(mvec[i], degree);\n\t}\n\t//StringUtils::showVec(mvec, n);\n\t//StringUtils::showVec(mpow, n);\n\n\tCiphertext cipher, cpow;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(\"Power of 2\");\n\talgo.powerOf2(cpow, cipher, logp, logdeg);\n\ttimeutils.stop(\"Power of 2\");\n\n\tcomplex<double>* dpow = scheme.decrypt(secretKey, cpow);\n\tStringUtils::compare(mpow, dpow, n, \"pow2\");\n\n\tcout << \"!!! END TEST POWER OF 2 !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testPower(long logq, long logp, long logn, long degree) {\n\tcout << \"!!! START TEST POWER !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomCircleArray(n);\n\tcout << \"mvec and mpow ^\"<< degree << endl;\n\tStringUtils::showVec(mvec, n);\n\n\tcomplex<double>* mpow = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmpow[i] = pow(mvec[i], degree);\n\t}\n\tStringUtils::showVec(mpow, n);\n\n\tCiphertext cipher, cpow;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(\"Power\");\n\talgo.power(cpow, cipher, logp, degree);\n\ttimeutils.stop(\"Power\");\n\n\tcomplex<double>* dpow = scheme.decrypt(secretKey, cpow);\n\tStringUtils::compare(mpow, dpow, n, \"pow\");\n\n\tcout << \"!!! END TEST POWER !!!\" << endl;\n}\n\n\n//----------------------------------------------------------------------------------\n//   FUNCTION TESTS\n//----------------------------------------------------------------------------------\n\n\nvoid TestScheme::testInverse(long logq, long logp, long logn, long steps) {\n\tcout << \"!!! START TEST INVERSE !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomCircleArray(n, 0.1);\n\t//cout << \"mvec and minv\" << endl;\n\t//StringUtils::showVec(mvec, n);\n\tcomplex<double>* minv = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tminv[i] = 1. / mvec[i];\n\t}\n\t//StringUtils::showVec(minv, n);\n\t\n\tCiphertext cipher, cinv;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(\"Inverse\");\n\talgo.inverse(cinv, cipher, logp, steps);\n\ttimeutils.stop(\"Inverse\");\n\n\tcomplex<double>* dinv = scheme.decrypt(secretKey, cinv);\n\tStringUtils::compare(minv, dinv, n, \"inv\");\n\n\tcout << \"!!! END TEST INVERSE !!!\" << endl;\n}\n\nvoid TestScheme::testLogarithm(long logq, long logp, long logn, long degree) {\n\tcout << \"!!! START TEST LOGARITHM !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n, 0.1);\n\t//cout << \"mvec and mlog\" << endl;\n\t//StringUtils::showVec(mvec, n);\n\tcomplex<double>* mlog = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmlog[i] = log(mvec[i] + 1.);\n\t}\n\t//StringUtils::showVec(mlog, n);\n\n\tCiphertext cipher, clog;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(LOGARITHM);\n\talgo.function(clog, cipher, LOGARITHM, logp, degree);\n\ttimeutils.stop(LOGARITHM);\n\n\tcomplex<double>* dlog = scheme.decrypt(secretKey, clog);\n\tStringUtils::compare(mlog, dlog, n, LOGARITHM);\n\n\tcout << \"!!! END TEST LOGARITHM !!!\" << endl;\n}\n\nvoid TestScheme::testExponent(long logq, long logp, long logn, long degree) {\n\tcout << \"!!! START TEST EXPONENT !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\t//cout << \"mvec and mexp\" << endl;\n\t//StringUtils::showVec(mvec, n);\n\tcomplex<double>* mexp = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmexp[i] = exp(mvec[i]);\n\t}\n\t//StringUtils::showVec(mexp, n);\n\n\tCiphertext cipher, cexp;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(EXPONENT);\n\talgo.function(cexp, cipher, EXPONENT, logp, degree);\n\ttimeutils.stop(EXPONENT);\n\n\tcomplex<double>* dexp = scheme.decrypt(secretKey, cexp);\n\tStringUtils::compare(mexp, dexp, n, EXPONENT);\n\n\tcout << \"!!! END TEST EXPONENT !!!\" << endl;\n}\n\n\n\nvoid TestScheme::testSqrt4(long logq, long logp, long logn) {\n\tcout << \"!!! START TEST SQRT4 !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n, 20); // get a rdm vector in [0, 20]^n\n\tcomplex<double>* msqrt = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmvec[i]  = complex<double>(mvec[i].real(), 0);\n\t\tmsqrt[i] = complex<double>(sqrt(abs(mvec[i].real())), sqrt(abs(mvec[i].imag())));\n\t}\n\tStringUtils::showVec(mvec, n);\n\n\tCiphertext cipher, csqrt;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(SQRT4);\n\talgo.function(csqrt, cipher, SQRT4, logp, 5);\n\ttimeutils.stop(SQRT4);\n\n\tcomplex<double>* dsqrt = scheme.decrypt(secretKey, csqrt);\n\t//StringUtils::showVec(dsqrt, n);\n\tStringUtils::compare(msqrt, dsqrt, n, SQRT4);\t\n\n\tcout << \"!!! END TEST SQRT4 !!!\" << endl;\n}\n\n\nvoid TestScheme::testSqrt8(long logq, long logp, long logn) {\n\tcout << \"!!! START TEST SQRT8 !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n, 12); // get a rdm vector in [0, 12]^n\n\tcomplex<double>* msqrt = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmvec[i]  = complex<double>(mvec[i].real(), 0.);\n\t\tmsqrt[i] = complex<double>(sqrt(abs(mvec[i].real())), sqrt(abs(mvec[i].imag())));\n\t}\n\n\tCiphertext cipher, csqrt;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(SQRT8);\n\talgo.function(csqrt, cipher, SQRT8, logp, 9);\n\ttimeutils.stop(SQRT8);\n\n\tcomplex<double>* dsqrt = scheme.decrypt(secretKey, csqrt);\n\tStringUtils::compare(msqrt, dsqrt, n, SQRT8);\n\n\tcout << \"!!! END TEST SQRT8 !!!\" << endl;\n}\n\n\n\nvoid TestScheme::testAllSqrt(long logq, long logp, long logn) {\n\tcout << \"!!! START TEST SQRT8 !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n, 10); // get a rdm vector in [0, 12]^n\n\tcomplex<double>* msqrt = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmvec[i]  = complex<double>(mvec[i].real(), 0.);\n\t\tmsqrt[i] = complex<double>(sqrt(abs(mvec[i].real())), sqrt(abs(mvec[i].imag())));\n\t}\n\n\tCiphertext cipher, csqrt, csqrt2;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(SQRT8);\n\talgo.function(csqrt, cipher, SQRT8, logp, 9);\n\ttimeutils.stop(SQRT8);\n\n\ttimeutils.start(SQRT8);\n\tCiphertext cipher2;\n\n\tscheme.square(cipher2, cipher);\n\t//cout << \"c2_logQ = \"<<cipher2.logq << endl;\n\n\tscheme.reScaleByAndEqual(cipher2, logp); // cipher2.logq : logq - logp\n\t//cout << \"c2_logQ = \"<<cipher2.logq << endl;\n\n\tCiphertext cipher4;\n\tscheme.square(cipher4, cipher2);\n\t//cout << \"c4_logQ = \"<<cipher4.logq << endl;\n\tscheme.reScaleByAndEqual(cipher4, logp); // cipher4.logq : logq -2logp\n\t//cout << \"c4_logQ = \"<<cipher4.logq << endl;\n\n\tCiphertext cipher8;\n\tscheme.square(cipher8, cipher4);\n\t//cout << \"c8_logQ = \"<<cipher8.logq << endl;\n\tscheme.reScaleByAndEqual(cipher8, logp); // cipher4.logq : logq -2logp\n\t//cout << \"c8_logQ = \"<<cipher8.logq << endl;\n\n\tRR c;\n\tc =  45./144; //a0/a1\n\tCiphertext cipher01;\n\tscheme.addConst(cipher01, cipher, c, logp); \n\t//cout << \"cip1_logQ = \"<<cipher01.logq << endl;\n\n\n\tc = 288./323; //a1\n\tscheme.multByConstAndEqual(cipher01, c, logp);\n\t//cout << \"cip1_logQ = \"<<cipher01.logq << endl;\n\tscheme.reScaleByAndEqual(cipher01, logp); \n\t//cout << \"cip1_logQ = \"<<cipher01.logq << endl;\n\n\tc = -125./24; //a2/a3\n\tCiphertext cipher23;\n\tscheme.addConst(cipher23, cipher, c, logp); \n\t//cout << \"cip23_logQ = \"<<cipher23.logq << endl;\n\n\tc = 44352./1009375;//a3\n\tscheme.multByConstAndEqual(cipher23, c, logp);\n\t//cout << \"cip23_logQ = \"<<cipher23.logq << endl;\n\tscheme.reScaleByAndEqual(cipher23, logp);\n\t//cout << \"cip23_logQ = \"<<cipher23.logq << endl;\n\n\tscheme.multAndEqual(cipher23, cipher2);\n\t//cout << \"cip23_logQ = \"<<cipher23.logq << endl;\n\tscheme.reScaleByAndEqual(cipher23, logp); \n\t//cout << \"cip23_logQ = \"<<cipher23.logq << endl;\n\n\tscheme.addAndEqual(cipher23, cipher01); \n\t//cout << \"cip23_logQ = \"<<cipher23.logq << endl;\n\n\tc = -5625./392; //a4/a5\n\tCiphertext cipher45;\n\tscheme.addConst(cipher45, cipher, c, logp); \n\t//cout << \"cip45_logQ = \"<<cipher45.logq << endl;\n\n\tc = 224224./630859375; //a5\n\tscheme.multByConstAndEqual(cipher45, c, logp);\n\t//cout << \"cip45_logQ = \"<<cipher45.logq << endl;\n\tscheme.reScaleByAndEqual(cipher45, logp); \n\t//cout << \"cip45_logQ = \"<<cipher45.logq << endl;\n\n\tc = -15925./352; // a6/a7\n\tscheme.addConstAndEqual(cipher, c, logp); \n\t//cout << \"cip_logQ = \"<<cipher.logq << endl;\n\n\tc = 25344./78857421875; // a7\n\tscheme.multByConstAndEqual(cipher, c, logp);\n\t//cout << \"cip_logQ = \"<<cipher.logq << endl;\n\tscheme.reScaleByAndEqual(cipher, logp); \n\t//cout << \"cip_logQ = \"<<cipher.logq << endl;\n\n\tscheme.multAndEqual(cipher, cipher2);\n\t//cout << \"cip_logQ = \"<<cipher.logq << endl;\n\tscheme.reScaleByAndEqual(cipher, logp); \n\t//cout << \"cip_logQ = \"<<cipher.logq << endl;\n\n\tscheme.modDownByAndEqual(cipher45, logp); \n\t//cout << \"cip_logQ = \"<<cipher.logq << endl;\n\tscheme.addAndEqual(cipher, cipher45); \n\t//cout << \"cip_logQ = \"<<cipher.logq << endl;\n\n\tscheme.multAndEqual(cipher, cipher4);\n\t//cout << \"cip_logQ = \"<<cipher.logq << endl;\n\tscheme.reScaleByAndEqual(cipher, logp); \n\t//cout << \"cip_logQ = \"<<cipher.logq << endl;\n\n\tscheme.modDownByAndEqual(cipher23, logp);\n\tscheme.addAndEqual(cipher, cipher23); \n\t//cout << \"cip_logQ = \"<<cipher.logq << endl;\n\t\n\tc = -1716./579833984375; //a8\n\tscheme.multByConstAndEqual(cipher8, c, logp);\n\tscheme.reScaleByAndEqual(cipher8, logp); \n\tscheme.addAndEqual(cipher, cipher8);\n\ttimeutils.stop(SQRT8);\n\n\n\tcomplex<double>* dsqrt = scheme.decrypt(secretKey, csqrt);\n\tcomplex<double>* dsqrt2 = scheme.decrypt(secretKey, cipher);\n\tStringUtils::compare(msqrt, dsqrt, n, SQRT8);\n\tcout<<\" \"<<endl;\n\tStringUtils::compare(msqrt, dsqrt2, n, SQRT8);\n\n\n\tcout << \"!!! END TEST SQRT8 !!!\" << endl;\n}\n\n\nvoid TestScheme::testExponentLazy(long logq, long logp, long logn, long degree) {\n\tcout << \"!!! START TEST EXPONENT LAZY !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\t//cout << \"mvec and mexp\" << endl;\n\t//StringUtils::showVec(mvec, n);\n\tcomplex<double>* mexp = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmexp[i] = exp(mvec[i]);\n\t}\n\t//StringUtils::showVec(mexp, n);\n\n\tCiphertext cipher, cexp;\n\tscheme.encrypt(cipher, mvec, n, logp, logQ);\n\n\ttimeutils.start(EXPONENT + \" lazy\");\n\talgo.functionLazy(cexp, cipher, EXPONENT, logp, degree);\n\ttimeutils.stop(EXPONENT + \" lazy\");\n\n\tcomplex<double>* dexp = scheme.decrypt(secretKey, cexp);\n\tStringUtils::compare(mexp, dexp, n, EXPONENT);\n\n\tcout << \"!!! END TEST EXPONENT LAZY !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testSigmoid(long logq, long logp, long logn, long degree) {\n\tcout << \"!!! START TEST SIGMOID !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\t//cout << \"mvec and msig\" << endl;\n\t//StringUtils::showVec(mvec, n);\n\tcomplex<double>* msig = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmsig[i] = exp(mvec[i]) / (1. + exp(mvec[i]));\n\t}\n\t//StringUtils::showVec(msig, n);\n\n\tCiphertext cipher, csig;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(SIGMOID);\n\talgo.function(csig, cipher, SIGMOID, logp, degree);\n\ttimeutils.stop(SIGMOID);\n\n\tcomplex<double>* dsig = scheme.decrypt(secretKey, csig);\n\tStringUtils::compare(msig, dsig, n, SIGMOID);\n\n\tcout << \"!!! END TEST SIGMOID !!!\" << endl;\n}\n\nvoid TestScheme::testSigmoidLazy(long logq, long logp, long logn, long degree) {\n\tcout << \"!!! START TEST SIGMOID LAZY !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\t//cout << \"mvec and msig\" << endl;\n\t//StringUtils::showVec(mvec, n);\n\tcomplex<double>* msig = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmsig[i] = exp(mvec[i]) / (1. + exp(mvec[i]));\n\t}\n\t//StringUtils::showVec(msig, n);\n\n\tCiphertext cipher, csig;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(SIGMOID + \" lazy\");\n\talgo.functionLazy(csig, cipher, SIGMOID, logp, degree);\n\ttimeutils.stop(SIGMOID + \" lazy\");\n\n\tcomplex<double>* dsig = scheme.decrypt(secretKey, csig);\n\tStringUtils::compare(msig, dsig, n, SIGMOID);\n\n\tcout << \"!!! END TEST SIGMOID LAZY !!!\" << endl;\n}\n\n\nvoid TestScheme::testDistance(long logq, long logp, long logn, complex<double>* mvec, complex<double>* mbin, complex<double>* mDes, int points, int norm, double realDistance) {\n\tcout << \"!!! START DISTANCE !!!\" << endl;\n\tsrand(time(NULL));\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = (1 << logn);\n\tlong r = (1 << 0);\n\tscheme.addLeftRotKey(secretKey, r);\n\tlong r2 = n/2;\n\tscheme.addLeftRotKey(secretKey, r2);\n\n\n\ttimeutils.start(ENC);\n\t//* Encrypt the plaintext\n\tCiphertext cipher;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\ttimeutils.stop(ENC);\n\n\n\ttimeutils.start(DISTANCE);\n\t//* Create the difference vector\n\tCiphertext diff;\n\tscheme.leftRotateFast(diff, cipher, r);\n\tscheme.subAndEqual(cipher, diff);\n\n\t//* Distroy elements in slot point and n/2+point\n\tCiphertext cbin;\n\tscheme.encrypt(cbin, mbin, n, logp, logq);//encode(plain, vals, n, logp, logq);\n\tscheme.multAndEqual(cipher, cbin);\n\tscheme.reScaleByAndEqual(cipher, logp);\n\n\tPlaintext plnBin;\n\n\t//* Square each slot \n\tscheme.squareAndEqual(cipher);\n\tscheme.reScaleByAndEqual(cipher, logp);\n\n\t//* Sum subdistances\n\tCiphertext subd;\n\tscheme.leftRotateFast(subd, cipher, r2);\n\tscheme.addAndEqual(cipher, subd);\n\tcomplex<double>* tmp10 = scheme.decrypt(secretKey, cipher);\t\n\t\n\n\t// Check range for square root\n\tfor (long i = 0; i < points-1; ++i) {\n\t\t\tif (tmp10[i].real()>9){\n\t\t\tcout<<\"distance \"<<i<<\" out of sqrt range : \"<<tmp10[i].real()<<endl;\n\t\t}\n\t\t\tif (tmp10[i].real()<0.2){\n\t\t\tcout<<\"distance \"<<i<<\" out of sqrt range inf : \"<<tmp10[i].real()<<endl;\n\t\t}\n\t}\n\n\t//* Take square root of each slot\n\tCiphertext csqrt;\n\talgo.function(csqrt, cipher, SQRT8, logp, 9); //SQRT9\n\n\t///* Show The subdistance vector\n\tcomplex<double>* dm = scheme.decrypt(secretKey, csqrt);\t\n\n\t///* Remove non necessary slots before summation\n\tCiphertext cDes;\n\tscheme.encrypt(cDes, mDes, n, logp, logq);\n\tscheme.multAndEqual(csqrt, cDes);\n\tscheme.reScaleByAndEqual(csqrt, logp);\n\n\n\t///* Sum to slot 0\n\tfor (long j =0; j< log(points-1)/log(2); j++) {\n\t\tCiphertext rot;\n\t\tscheme.addLeftRotKey(secretKey, pow(2,j));\n\t\tscheme.leftRotateFast(rot, csqrt, pow(2,j));\n\t\tscheme.addAndEqual(csqrt, rot);\n\t\t//cout << \"sum logq = \"<<csqrt.logq << endl;\n\t}\n\ttimeutils.stop(DISTANCE);\n\n\t//cout << \"sum logq = \"<<csqrt.logq << endl;\n\n\t// DECRYPTION \n\ttimeutils.start(DEC);\n\t///* Decrypt \n\tcomplex<double>* decDir = scheme.decrypt(secretKey, csqrt);\n\ttimeutils.stop(DEC);\n\tcout<<\"distance = \"<<decDir[0].real()*norm<<endl;\n\n\tdouble distance = 0;\n\tfor (long i = 0; i < points-1; ++i) {\n\t\tdistance += dm[i].real();\n\t}\n\n\t// Print for Latex\n\t// log n  | logq  |  logp  | RealDist | Distance  | error | t_i\n\tdouble result = decDir[0].real()*norm;\n\tcout<< logn <<\" & \"<< logq <<\" & \"<< logp <<\" & \"<< points <<\" & \"<<realDistance <<\" & \"<< decDir[0].real()*norm <<\" & \"<< distance*norm <<\" & \"<< floor((result*100./realDistance -100)*100)/100;//<<\" & \"<< floor(tenc/10)/100 <<\" & \"<< floor(tdist/10)/100 <<\" & \" << floor(tdec)/1000<<\" & \"<<counter;\n\n\n}\n\n\n\n\nvoid TestScheme::testWriteAndRead(long logq, long logp, long logSlots) {\n\tcout << \"!!! START TEST WRITE AND READ !!!\" << endl;\n\n\tcout << \"!!! END TEST WRITE AND READ !!!\" << endl;\n}\n\n\nvoid TestScheme::testBootstrap(long logq, long logQ, long logp, long logSlots, long logT) {\n\t/**\n\t * Testing bootstrapping procedure for single real value\n\t * number of modulus bits up: depends on parameters\n\t * @param[in] logN: input parameter for Params class\n\t * @param[in] logq: log of initial modulus\n\t * @param[in] logQ: input parameter for Params class\n\t * @param[in] logSlots: log of number of slots\n\t * @param[in] nu: auxiliary parameter, corresonds to message bits (message bits is logq - nu)\n\t * @param[in] logT: auxiliary parameter, corresponds to number of iterations in removeIpart (num of iterations is logI + logT)\n\t * testBootstrap(long logq, long logQ, long logp, long logn, long logT); as of Nov18\n\n\t */\n\n\n\tcout << \"!!! START TEST BOOTSTRAP !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\ttimeutils.start(\"Key generating\");\n\tscheme.addBootKey(secretKey, logSlots, logq + 4);\n\ttimeutils.stop(\"Key generated\");\n\n\tlong slots = (1 << logSlots);\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots);\n\n\tCiphertext cipher;\n\tscheme.encrypt(cipher, mvec, slots, logp, logq);\n\n\tcout << \"cipher logq before: \" << cipher.logq << endl;\n\n\tscheme.modDownToAndEqual(cipher, logq);\n\tscheme.normalizeAndEqual(cipher);\n\tcipher.logq = logQ;\n\tcipher.logp = logq + 4;\n\n\tCiphertext rot;\n\ttimeutils.start(\"SubSum\");\n\tfor (long i = logSlots; i < logNh; ++i) {\n\t\tscheme.leftRotateFast(rot, cipher, (1 << i));\n\t\tscheme.addAndEqual(cipher, rot);\n\t}\n\tscheme.divByPo2AndEqual(cipher, logNh);\n\ttimeutils.stop(\"SubSum\");\n\n\ttimeutils.start(\"CoeffToSlot\");\n\tscheme.coeffToSlotAndEqual(cipher); // Issue here with default parameters\n\ttimeutils.stop(\"CoeffToSlot\");\n\n\ttimeutils.start(\"EvalExp\");\n\tscheme.evalExpAndEqual(cipher, logT);\n\ttimeutils.stop(\"EvalExp\");\n\n\ttimeutils.start(\"SlotToCoeff\");\n\tscheme.slotToCoeffAndEqual(cipher);\n\ttimeutils.stop(\"SlotToCoeff\");\n\n\tcipher.logp = logp;\n\tcout << \"cipher logq after: \" << cipher.logq << endl;\n\n\tcomplex<double>* dvec = scheme.decrypt(secretKey, cipher);\n\n\tStringUtils::compare(mvec, dvec, slots, \"boot\");\n\n\tcout << \"!!! END TEST BOOTSRTAP !!!\" << endl;\n}\n\nvoid TestScheme::testBootstrapSingleReal(long logq, long logQ, long logp, long logT) {\n\tcout << \"!!! START TEST BOOTSTRAP SINGLE REAL !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\ttimeutils.start(\"Key generating\");\n\tscheme.addBootKey(secretKey, 0, logq + 4);\n\ttimeutils.stop(\"Key generated\");\n\n\tcout << \"key ok\" << endl;\n\n\tdouble mval = EvaluatorUtils::randomReal();\n\n\tCiphertext cipher;\n\tscheme.encryptSingle(cipher, mval, logp, logq);\n\n\tcout << \"cipher logq before: \" << cipher.logq << endl;\n\tscheme.modDownToAndEqual(cipher, logq);\n\tscheme.normalizeAndEqual(cipher);\n\tcipher.logq = logQ;\n\n\tCiphertext rot, cconj;\n\ttimeutils.start(\"SubSum\");\n\tfor (long i = 0; i < logNh; ++i) {\n\t\tscheme.leftRotateFast(rot, cipher, 1 << i);\n\t\tscheme.addAndEqual(cipher, rot);\n\t}\n\tscheme.conjugate(cconj, cipher);\n\tscheme.addAndEqual(cipher, cconj);\n\tscheme.divByPo2AndEqual(cipher, logN);\n\ttimeutils.stop(\"SubSum\");\n\n\ttimeutils.start(\"EvalExp\");\n\tscheme.evalExpAndEqual(cipher, logT);\n\ttimeutils.stop(\"EvalExp\");\n\n\tcout << \"cipher logq after: \" << cipher.logq << endl;\n\n\tcipher.logp = logp;\n\tcomplex<double> dval = scheme.decryptSingle(secretKey, cipher);\n\n\tStringUtils::compare(mval, dval.real(), \"boot\");\n\n\tcout << \"!!! END TEST BOOTSRTAP SINGLE REAL !!!\" << endl;\n}\n\n\n\nvoid TestScheme::test() {\n}\n\n", "meta": {"hexsha": "3d9ef9039a103bd9d8319b4101e76dbe77142fae", "size": 28280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ZKCE/ZKCE_Arith/src/TestScheme.cpp", "max_stars_repo_name": "ldsec/CRISP", "max_stars_repo_head_hexsha": "90eec8a3fe274f184f76af4ea30e981989bdbed6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-22T07:34:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T16:14:26.000Z", "max_issues_repo_path": "ZKCE/ZKCE_Arith/src/TestScheme.cpp", "max_issues_repo_name": "ldsec/CRISP", "max_issues_repo_head_hexsha": "90eec8a3fe274f184f76af4ea30e981989bdbed6", "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": "ZKCE/ZKCE_Arith/src/TestScheme.cpp", "max_forks_repo_name": "ldsec/CRISP", "max_forks_repo_head_hexsha": "90eec8a3fe274f184f76af4ea30e981989bdbed6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-29T22:03:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-29T22:03:03.000Z", "avg_line_length": 27.9170779862, "max_line_length": 300, "alphanum_fraction": 0.6559405941, "num_tokens": 8450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5452929077300469}}
{"text": "#include <tiny_math_types.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\ntypedef tiny::MathTypes<double>  MT;\ntypedef MT::value_traits         VT;\n\n\nBOOST_AUTO_TEST_SUITE(tiny_degrees_and_radians);\n\nBOOST_AUTO_TEST_CASE(conversion)\n{\n  double const degrees180 = 180.0;\n  double const radians180 = VT::convert_to_radians(degrees180);\n\n  BOOST_CHECK_CLOSE( radians180, VT::pi(), 0.1 );\n\n  double const radiansPI = VT::pi();\n  double const degreesPI = VT::convert_to_degrees(radiansPI);\n\n  BOOST_CHECK_CLOSE( degreesPI, 180.0, 0.1 );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "2938df66253c043d46ebb7debfcdf407a68e6e82", "size": 724, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_degrees_and_radians/tiny_degrees_and_radians.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_degrees_and_radians/tiny_degrees_and_radians.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_degrees_and_radians/tiny_degrees_and_radians.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3548387097, "max_line_length": 63, "alphanum_fraction": 0.7651933702, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5452926015470172}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/log10.hpp>\n#include <boost/simd/function/std.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/ten.hpp>\n#include <boost/simd/constant/three.hpp>\n\n\nSTF_CASE_TPL (\" log10 std\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::log10;\n\n  using r_t = decltype(log10(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(bs::std_(log10)(bs::Inf<T>()), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(log10)(bs::Minf<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(log10)(bs::Nan<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(log10)(bs::Mone<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(log10)(bs::Zero<T>()), bs::Minf<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(log10)(bs::Mzero<T>()), bs::Minf<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(bs::std_(log10)(bs::One<T>()), bs::Zero<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(log10)(bs::Two<T>()), T(0.301029995663981195213738894724), 0);\n}\n", "meta": {"hexsha": "587ba5343ad02a0516b12ed1e1c537488c0a31f6", "size": 1714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/log10.std.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/scalar/log10.std.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/log10.std.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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": 36.4680851064, "max_line_length": 100, "alphanum_fraction": 0.6108518086, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5452925912650481}}
{"text": "#include \"core/algebra/EncVec.hpp\"\n#include \"core/algebra/EncMat.hpp\"\n#include \"HElib/FHE.h\"\n#include \"HElib/EncryptedArray.h\"\n#include \"core/coda.hpp\"\n#include <NTL/vector.h>\n#include <NTL/mat_ZZ.h>\nint test1(core::sk_ptr sk, core::pk_ptr pk, const EncryptedArray *ea) {\n    core::EncVec encVec(pk);\n    NTL::vec_ZZ slots;\n    slots.SetLength(4);\n    for (int i = 0; i < slots.length(); i++)\n        slots[i] = NTL::to_ZZ(i + 1);\n    encVec.pack(slots);\n\n    long width = 4;\n    long idx = 2;\n    auto tmp = encVec.replicate(idx, width);\n    NTL::vec_ZZ _slots;\n    tmp.unpack(_slots, sk, true); // [5, 5, 5, 5]\n    std::cout << slots << \" \" << _slots << std::endl;\n    if (_slots.length() != width)\n        return -1;\n    for (auto t : _slots) {\n        if (t != slots[idx]) return -1;\n    }\n\n    core::EncMat encMat(pk);\n    NTL::mat_ZZ matrix;\n    matrix.SetDims(3, 4);\n    for (int r = 0; r < matrix.NumRows(); r++)\n        for (int c = 0; c < matrix.NumCols(); c++)\n            matrix.put(r, c, NTL::to_ZZ(1));\n    encMat.pack(matrix);\n\n    core::EncMat encMat2(pk);\n    NTL::mat_ZZ matrix2;\n    matrix2.SetDims(4, 5);\n    for (int r = 0; r < matrix2.NumRows(); r++)\n        for (int c = 0; c < matrix2.NumCols(); c++)\n            matrix2.put(r, c, NTL::to_ZZ(1));\n    encMat2.pack(matrix2);\n\n    encMat.dot(encMat2);\n    NTL::mat_ZZ _mat;\n    encMat.unpack(_mat, sk, false);\n    NTL::mat_ZZ zM, zM2, zM3;\n    matrix *= matrix2;\n    if (matrix != _mat)\n        return -1;\n    return 0;\n}\n\nint test2(core::sk_ptr sk, core::pk_ptr pk, const EncryptedArray *ea) {\n    long p = pk->getContext().alMod.getPPowR();\n    NTL::mat_ZZ X;\n    X.SetDims(4, 4);\n    NTL::ZZ range = NTL::to_ZZ(3);\n    for (int r = 0; r < X.NumRows(); r++) {\n        for (int c = r; c < X.NumCols(); c++) {\n            auto rnd = NTL::RandomBnd(range);\n            X.put(r, c, rnd);\n            X.put(c, r, rnd);\n        }\n    }\n\n    NTL::vec_ZZ v;\n    v.SetLength(4);\n    for (int c = 0; c < v.length(); c++)\n        v[c] = NTL::RandomBnd(range);\n\n    core::EncMat encMat(pk);\n    core::EncVec encVec(pk);\n    encMat.pack(X);\n    encVec.pack(v);\n\n    NTL::ZZ_p::init(NTL::to_ZZ(p));\n    NTL::mat_ZZ_p Xp;\n    NTL::vec_ZZ_p Vp;\n    NTL::conv(Xp, X);\n    NTL::conv(Vp, v);\n    long T = 4;\n    for (int t = 0; t < T; t++) {\n        encVec = encMat.sym_dot(encVec); // only works for symmetric\n        NTL::mul(Vp, Xp, Vp);\n    }\n\n    NTL::vec_ZZ_p modV;\n    encVec.unpack(v, sk);\n    NTL::conv(modV, v);\n    if (modV != Vp)\n        return -1;\n    return 0;\n}\n\nint test3(core::sk_ptr sk, core::pk_ptr pk, const EncryptedArray *ea) {\n    long p = pk->getContext().alMod.getPPowR();\n    NTL::mat_ZZ X, Y;\n    X.SetDims(4, 4);\n    Y.SetDims(4, 4);\n    NTL::ZZ range = NTL::to_ZZ(3);\n    for (int r = 0; r < X.NumRows(); r++) {\n        for (int c = 0; c < X.NumCols(); c++) {\n            X.put(r, c, NTL::RandomBnd(range));\n            Y.put(r, c, NTL::RandomBnd(range));\n        }\n    }\n\n    NTL::ZZ_p::init(NTL::to_ZZ(p));\n    NTL::mat_ZZ_p Xp, Yp;\n    NTL::conv(Xp, X);\n    NTL::conv(Yp, Y);\n\n    core::EncMat encMat(pk), encMat2(pk);\n    encMat.pack(X);\n    encMat2.pack(Y);\n\n    long T = 4;\n    for (int t = 0; t < T; t++) {\n        encMat.dot(encMat2);\n        NTL::mul(Xp, Xp, Yp);\n    }\n    encMat.unpack(X, sk);\n    NTL::conv(Yp, X);\n    if (Xp != Yp)\n        return -1;\n    return 0;\n}\n\nint test4(core::sk_ptr sk, core::pk_ptr pk, const EncryptedArray *ea) {\n    NTL::mat_ZZ X, Y;\n    X.SetDims(4, 4);\n    NTL::ZZ range = NTL::to_ZZ(3);\n    for (int r = 0; r < X.NumRows(); r++) {\n        for (int c = 0; c < X.NumCols(); c++) {\n            X.put(r, c, NTL::RandomBnd(range));\n        }\n    }\n\n    {\n        core::EncMat encMat(pk);\n        encMat.add(X);\n        encMat.unpack(Y, sk);\n        if (X != Y)\n            return -1;\n        core::EncMat encMat2(pk);\n        encMat2.sub(X);\n        encMat2.unpack(Y, sk, true);\n        auto tmp(X);\n        NTL::negate(tmp, X);\n        if (tmp != Y)\n            return -1;\n    } // Test empty matrix adds plain matrix\n    {\n        core::EncMat encMat(pk), encMat2(pk), encMat3(pk);\n        encMat2.pack(X);\n        encMat.add(encMat2);\n        encMat.unpack(Y, sk);\n        if (X != Y)\n            return -1;\n        encMat3.sub(encMat2);\n        encMat3.unpack(Y, sk, true);\n        auto tmp(X);\n        NTL::negate(tmp, X);\n        if (tmp != Y)\n            return -1;\n    } // Test empty matrix adds cipher matrix\n    return 0;\n}\n\nint testIO(core::sk_ptr sk, core::pk_ptr pk, const EncryptedArray *ea) {\n    core::EncVec encVec(pk);\n    NTL::vec_ZZ slots;\n    slots.SetLength(7);\n    for (int i = 0; i < slots.length(); i++)\n        slots[i] = NTL::to_ZZ(i + 1);\n    encVec.pack(slots);\n    {\n        std::ofstream out(\"./tmp.ctx\", std::ios::binary);\n        if (!encVec.dump(out)) {\n            out.close();\n            return -1;\n        }\n        out.close();\n\n        std::ifstream in(\"./tmp.ctx\", std::ios::binary);\n        core::EncVec encVec2(pk);\n        if (!encVec2.restore(in)) {\n            in.close();\n            return -1;\n        }\n        in.close();\n\n        NTL::vec_ZZ slots2;\n        encVec2.unpack(slots2, sk);\n        if (slots2 != slots)\n            return -1;\n    } // Test EncVec\n\n    core::EncMat encMat(pk);\n    NTL::mat_ZZ mat;\n    mat.SetDims(7, 7);\n    for (long r = 0; r < mat.NumRows(); r++)\n        for (long c = 0; c < mat.NumCols(); c++) mat[r][c] = 1;\n    encMat.pack(mat);\n    {\n        std::ofstream out(\"./tmp.ctx\", std::ios::binary);\n        if (!encMat.dump(out)) {\n            out.close();\n            return -1;\n        }\n        out.close();\n\n        std::ifstream in(\"./tmp.ctx\", std::ios::binary);\n        core::EncMat encMat2(pk);\n        if (!encMat2.restore(in)) {\n            in.close();\n            return -1;\n        }\n        in.close();\n\n        NTL::mat_ZZ mat2;\n        encMat2.unpack(mat2, sk);\n        if (mat != mat2)\n            return -1;\n    } // Test EncMat\n    return 0;\n}\n\nint main() {\n    core::context_ptr context = std::make_shared<FHEcontext>(512, 8209, 1);\n    buildModChain(*context, 14);\n    core::sk_ptr sk = std::make_shared<FHESecKey>(*context);\n    sk->GenSecKey(64);\n    addSome1DMatrices(*sk);\n    core::pk_ptr pk = std::make_shared<FHEPubKey>(*sk);\n    auto ea = context->ea;\n    if (test1(sk, pk, ea) != 0) {\n        std::cout << \"test1 fail\\n\";\n        return -1;\n    }\n    if (test2(sk, pk, ea) != 0) {\n        std::cout << \"test2 fail\\n\";\n        return -1;\n    }\n    if (test3(sk, pk, ea) != 0) {\n        std::cout << \"test3 fail\\n\";\n        return -1;\n    }\n    if (test4(sk, pk, ea) != 0) {\n        std::cout << \"test4 fail\\n\";\n        return -1;\n    }\n    if (testIO(sk, pk, ea) != 0) {\n        std::cout << \"test3 fail\\n\";\n        return -1;\n    }\n    std::cout << \"passed\\n\";\n    return 0;\n}\n", "meta": {"hexsha": "1f812ac188b09b7e9bc0ba3988719dff450f8552", "size": 6810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/test/TestEncVec.cpp", "max_stars_repo_name": "fionser/CODA", "max_stars_repo_head_hexsha": "db234a1e9761d379fb96ae17eef3b77254f8781c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-02-24T19:28:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-05T04:40:47.000Z", "max_issues_repo_path": "core/test/TestEncVec.cpp", "max_issues_repo_name": "fionser/CODA", "max_issues_repo_head_hexsha": "db234a1e9761d379fb96ae17eef3b77254f8781c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-15T03:41:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-24T09:06:15.000Z", "max_forks_repo_path": "core/test/TestEncVec.cpp", "max_forks_repo_name": "fionser/CODA", "max_forks_repo_head_hexsha": "db234a1e9761d379fb96ae17eef3b77254f8781c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-05-14T10:12:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-07T03:50:56.000Z", "avg_line_length": 26.091954023, "max_line_length": 75, "alphanum_fraction": 0.5026431718, "num_tokens": 2265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5452035525891451}}
{"text": "\ufeff//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include \"Resize.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\ninline double EuclideanDistance(float Xa, float Ya, const unsigned int Xb, const unsigned int Yb)\n{\n    return std::sqrt(pow(Xa - boost::numeric_cast<float>(Xb), 2) + pow(Ya - boost::numeric_cast<float>(Yb), 2));\n}\n\n}// anonymous namespace\n\nvoid Resize(Decoder<float>&   in,\n            const TensorInfo& inputInfo,\n            Encoder<float>&   out,\n            const TensorInfo& outputInfo,\n            DataLayoutIndexed dataLayout,\n            armnn::ResizeMethod resizeMethod,\n            bool alignCorners)\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    const unsigned int sizeOffset = resizeMethod == armnn::ResizeMethod::Bilinear && alignCorners ? 1 : 0;\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 - sizeOffset)\n                       / boost::numeric_cast<float>(outputHeight - sizeOffset);\n    const float scaleX = boost::numeric_cast<float>(inputWidth - sizeOffset)\n                       / boost::numeric_cast<float>(outputWidth - sizeOffset);\n\n    TensorShape inputShape =  inputInfo.GetShape();\n    TensorShape outputShape =  outputInfo.GetShape();\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                    float interpolatedValue;\n                    switch (resizeMethod)\n                    {\n                        case armnn::ResizeMethod::Bilinear:\n                        {\n                            in[dataLayout.GetIndex(inputShape, n, c, y0, x0)];\n                            float input1 = in.Get();\n                            in[dataLayout.GetIndex(inputShape, n, c, y0, x1)];\n                            float input2 = in.Get();\n                            in[dataLayout.GetIndex(inputShape, n, c, y1, x0)];\n                            float input3 = in.Get();\n                            in[dataLayout.GetIndex(inputShape, n, c, y1, x1)];\n                            float input4 = in.Get();\n\n                            const float ly0 = Lerp(input1, input2, xw); // lerp along row y0.\n                            const float ly1 = Lerp(input3, input4, xw); // lerp along row y1.\n                            interpolatedValue = Lerp(ly0, ly1, yw);\n                            break;\n                        }\n                        case armnn::ResizeMethod::NearestNeighbor:\n                        {\n                            // calculate euclidean distance to the 4 neighbours\n                            auto distance00 = EuclideanDistance(fix, fiy, x0, y0);\n                            auto distance01 = EuclideanDistance(fix, fiy, x0, y1);\n                            auto distance10 = EuclideanDistance(fix, fiy, x1, y0);\n                            auto distance11 = EuclideanDistance(fix, fiy, x1, y1);\n\n                            auto minimum = std::min( { distance00, distance01, distance10, distance11 } );\n\n                            unsigned int xNearest = 0;\n                            unsigned int yNearest = 0;\n\n                            if (minimum == distance00)\n                            {\n                               xNearest = x0;\n                               yNearest = y0;\n                            }\n                            else if (minimum == distance01)\n                            {\n                                xNearest = x0;\n                                yNearest = y1;\n                            }\n                            else if (minimum == distance10)\n                            {\n                                xNearest = x1;\n                                yNearest = y0;\n                            }\n                            else if (minimum == distance11)\n                            {\n                                xNearest = x1;\n                                yNearest = y1;\n                            }\n                            else\n                            {\n                                throw armnn::InvalidArgumentException(\"Resize Nearest Neighbor failure\");\n                            }\n\n                            in[dataLayout.GetIndex(inputShape, n, c, yNearest, xNearest)];\n                            interpolatedValue = in.Get();\n                            break;\n                        }\n                        default:\n                            throw armnn::InvalidArgumentException(\"Unknown resize method: \" +\n                                                                  std::to_string(static_cast<int>(resizeMethod)));\n                    }\n                    out[dataLayout.GetIndex(outputShape, n, c, y, x)];\n                    out.Set(interpolatedValue);\n                }\n            }\n        }\n    }\n}\n\n} //namespace armnn\n", "meta": {"hexsha": "a26e34a1ff5d641228b3b79ac90826121ee61df0", "size": 7271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backends/reference/workloads/Resize.cpp", "max_stars_repo_name": "muthukumaravel7/armnn", "max_stars_repo_head_hexsha": "879ec231203df5b0a94462c0b247dc7d8d8a7a44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/backends/reference/workloads/Resize.cpp", "max_issues_repo_name": "muthukumaravel7/armnn", "max_issues_repo_head_hexsha": "879ec231203df5b0a94462c0b247dc7d8d8a7a44", "max_issues_repo_licenses": ["MIT"], "max_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/Resize.cpp", "max_forks_repo_name": "muthukumaravel7/armnn", "max_forks_repo_head_hexsha": "879ec231203df5b0a94462c0b247dc7d8d8a7a44", "max_forks_repo_licenses": ["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.5204678363, "max_line_length": 114, "alphanum_fraction": 0.4980057764, "num_tokens": 1452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5452035373227876}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <eigen3/Eigen/Core>\n\nusing MatrixXd = Eigen::MatrixXd;\nusing VectorXd = Eigen::VectorXd;\nusing Vector2d = Eigen::Vector2d;\nusing Vector4d = Eigen::Vector4d;\nusing Vector6d = Eigen::Matrix<double, 6, 1>;\nusing Vector8d = Eigen::Matrix<double, 8, 1>;\nusing Matrix8d = Eigen::Matrix<double, 8, 8>;\nusing TimeStamp = double;\nusing TimeDuration = double;\n\nconstexpr double dt = 1.;\n\nstruct RocketState {\n    // Using a single dt is a better option.\n    // But it make index handling a little bit more complex.\n    enum StateIndex : int16_t {\n        i_position_x = 0,\n        i_position_y,\n        i_velocity_x,\n        i_velocity_y,\n        STATE_SIZE\n    };\n\n    explicit RocketState(const double px,\n        const double py,\n        const double vel_x,\n        const double vel_y)\n    {\n        variables << px, py, vel_x, vel_y;\n    }\n\n    RocketState() = default;\n\n    static int variable_size()\n    {\n        return STATE_SIZE;\n    }\n\n    static int lcn_state_size()\n    {\n        return 2;\n    }\n\n    static int control_state_size()\n    {\n        // i_turning_rate,\n        // i_acceleration,\n        return 2;\n    }\n\n    Eigen::Map<Vector2d> lcn_state()\n    {\n        return Eigen::Map<Vector2d>(variables.data());\n    }\n\n    Eigen::Map<Vector2d> cntl_state()\n    {\n        return Eigen::Map<Vector2d>(variables.data() + 2);\n    }\n\n    Vector2d lcn_state() const\n    {\n        return variables.block<2, 1>(0, 0);\n    }\n\n    Vector2d cntl_state() const\n    {\n        return variables.block<2, 1>(2, 0);\n    }\n\n    Eigen::Map<Vector2d> position()\n    {\n        return Eigen::Map<Vector2d>(variables.data() + i_position_x);\n    }\n\n    Eigen::Map<Vector2d> velocity()\n    {\n        return Eigen::Map<Vector2d>(variables.data() + i_velocity_x);\n    }\n\n    Vector2d velocity() const\n    {\n        return { variables(i_velocity_x), variables(i_velocity_y) };\n    }\n\n    Vector4d variables = Vector4d::Zero();\n};\n\nstruct RocketMotionModel {\n    RocketState motion(const RocketState& state_in) const\n    {\n        auto state = state_in;\n        // TODO: non-const getter\n        RocketState next_state = state;\n\n        next_state.velocity() = state.velocity();\n\n        next_state.position()[0] = state.position()[0] + sin(state.velocity()[0]);\n        next_state.position()[1] = state.position()[1] + state.velocity()[1];\n\n        return next_state;\n    }\n\n    MatrixXd jacobian_wrt_state(const RocketState& state_in) const\n    {\n        using S = RocketState;\n        const int residual_size = RocketState::STATE_SIZE;\n        MatrixXd jacobi_wrt_s = MatrixXd::Identity(residual_size, residual_size);\n\n        jacobi_wrt_s(S::i_position_x, S::i_velocity_x) = cos(state_in.velocity()[0]);\n        jacobi_wrt_s(S::i_position_y, S::i_velocity_y) = 1.;\n\n        return jacobi_wrt_s;\n    }\n};\n\n#define PRINT_NAME_VAR(var) std::cout << #var << \" :\" << var << std::endl\n\nusing State = Vector2d;\nusing Control = Vector2d;\n\nstruct RocketLandingProblem {\n    // Variables\n    std::vector<RocketState> states = std::vector<RocketState>(11);\n\n    // support data\n    RocketState start_state = RocketState(0.1, 0.1, 0, 0);\n    RocketState end_state = RocketState(2, 2, 0, 0);\n};\n\nstruct QuadraticCost {\n    QuadraticCost() = default;\n\n    QuadraticCost(const VectorXd& meanIn, const MatrixXd& weightIn)\n        : mean(meanIn)\n        , weight(weightIn)\n    {\n    }\n\n    double eval(const VectorXd& x) const\n    {\n        return (x - mean).transpose() * weight * (x - mean);\n    }\n\n    VectorXd mean;\n    MatrixXd weight;\n};\n\n// du = K1 * dx + k2\nstruct FeedbackLaw {\n    FeedbackLaw() = default;\n\n    FeedbackLaw(MatrixXd K1, VectorXd k2)\n        : K1(K1)\n        , k2(k2)\n    {\n    }\n\n    VectorXd apply(const VectorXd& x) const\n    {\n        return K1 * x + k2;\n    }\n\n    MatrixXd K1;\n    VectorXd k2;\n};\n\n// The definition of states and controls is differient from previous section.\nstruct DDPStates {\n    State last_state()\n    {\n        return states.at(num_states - 1);\n    }\n\n    int num_states = 0;\n    std::vector<Control> controls;\n    std::vector<State> states;\n    std::vector<FeedbackLaw> feedbacks;\n\n    State init_state;\n    State target_state;\n};\n\ninline RocketState ddp_vars_to_rocket_state(const State& x, const Control& u)\n{\n    RocketState rstate;\n    rstate.cntl_state() = u;\n    rstate.lcn_state() = x;\n    return rstate;\n}\n\nclass DifferentialDynamicProgramming {\npublic:\n    void solve(RocketLandingProblem& problem)\n    {\n        DDPStates ddp_states = initialize_ddp_state(problem);\n        for (int iteration = 0; iteration < 10; ++iteration) {\n            forward_pass(ddp_states);\n            backward_pass(ddp_states);\n            apply_control_law(ddp_states);\n        }\n\n        update_output(ddp_states, problem);\n    }\n\nprivate:\n    DDPStates initialize_ddp_state(const RocketLandingProblem& problem)\n    {\n        DDPStates ddp_states;\n        ddp_states.num_states = problem.states.size();\n        num_states_ = ddp_states.num_states;\n        ddp_states.init_state = problem.start_state.lcn_state();\n        ddp_states.target_state = problem.end_state.lcn_state();\n\n        PRINT_NAME_VAR(ddp_states.num_states);\n        PRINT_NAME_VAR(ddp_states.init_state);\n        PRINT_NAME_VAR(ddp_states.target_state);\n\n        ddp_states.states.resize(ddp_states.num_states);\n        ddp_states.controls.resize(ddp_states.num_states - 1);\n        ddp_states.feedbacks.resize(ddp_states.num_states - 1);\n\n        for (int i = 0; i < ddp_states.num_states; ++i) {\n            ddp_states.states.at(i) = problem.states.at(i).lcn_state();\n        }\n\n        for (int i = 0; i < ddp_states.num_states - 1; ++i) {\n            ddp_states.controls.at(i) = problem.states.at(i).cntl_state();\n        }\n\n        return ddp_states;\n    }\n\n    void update_output(const DDPStates& ddp_states, RocketLandingProblem& problem)\n    {\n        for (int i = 0; i < ddp_states.num_states; ++i) {\n            problem.states.at(i).lcn_state() = ddp_states.states.at(i);\n        }\n\n        for (int i = 0; i < ddp_states.num_states - 1; ++i) {\n            problem.states.at(i).cntl_state() = ddp_states.controls.at(i);\n        }\n    }\n\n    void forward_pass(DDPStates& ddp_states)\n    {\n        ddp_states.states.resize(ddp_states.num_states);\n        ddp_states.controls.resize(ddp_states.num_states - 1);\n\n        ddp_states.states[0] = ddp_states.init_state;\n\n        RocketMotionModel motion_model;\n        for (int i = 0; i < ddp_states.num_states - 1; ++i) {\n            RocketState current_full_state = ddp_vars_to_rocket_state(\n                ddp_states.states.at(i), ddp_states.controls.at(i));\n\n            RocketState next_full_state = motion_model.motion(current_full_state);\n            ddp_states.states.at(i + 1) = next_full_state.lcn_state();\n\n            std::cout << \"idx forward iter: \" << i << std::endl;\n            std::cout << \"control: \" << ddp_states.controls.at(i).transpose() << std::endl;\n            std::cout << \"state: \" << ddp_states.states.at(i).transpose() << std::endl;\n            std::cout << \"next state: \" << ddp_states.states.at(i + 1).transpose() << std::endl;\n        }\n    }\n\n    void backward_pass(DDPStates& ddp_states)\n    {\n        QuadraticCost marginal_cost = target_cost(ddp_states.target_state);\n\n        current_best_cost_ = std::min(current_best_cost_, marginal_cost.eval(ddp_states.last_state()));\n        std::cout << \"target cost :\" << marginal_cost.eval(ddp_states.last_state()) << std::endl;\n\n        for (int i = ddp_states.num_states - 2; i >= 0; --i) {\n            const State cur_state = ddp_states.states.at(i);\n            const Control cur_control = ddp_states.controls.at(i);\n\n            solve_backward_subproblem(cur_state, cur_control, marginal_cost, ddp_states.feedbacks[i]);\n        }\n    }\n\n    void solve_backward_subproblem(const State& cur_state,\n        const Control& cur_control,\n        QuadraticCost& marginal_cost,\n        FeedbackLaw& feedback_law)\n    {\n        const int state_size = 2;\n        const int control_size = 2;\n\n        MatrixXd lhs;\n        VectorXd rhs;\n        compute_backward_subproblem_normal_equation(marginal_cost, cur_state, cur_control, lhs, rhs);\n\n        MatrixXd A1 = lhs.block(0, 0, state_size, state_size);\n        MatrixXd A2 = lhs.block(0, state_size, state_size, control_size);\n        MatrixXd A3 = lhs.block(state_size, 0, control_size, state_size);\n        MatrixXd A4 = lhs.block(state_size, state_size, control_size, control_size);\n\n        VectorXd b1 = rhs.block(0, 0, state_size, 1);\n        VectorXd b2 = rhs.block(state_size, 0, control_size, 1);\n\n        MatrixXd A4_inv = A4.inverse();\n\n        // eliminate du\n        MatrixXd lhs_xi = A1 - A2 * A4_inv * A3;\n        VectorXd rhs_xi = b1 - A2 * A4_inv * b2;\n\n        // solve PSD system by Cholesky\n        VectorXd xi_star = lhs_xi.llt().solve(rhs_xi);\n\n        marginal_cost = QuadraticCost(cur_state + xi_star, lhs_xi);\n        // std::cout << \"marginal_cost \\n mean:\" << marginal_cost.mean.transpose()\n        //     << \"\\n weight:\" << marginal_cost.weight << std::endl;\n        feedback_law = FeedbackLaw(-A4_inv * A3, A4_inv * b2);\n    }\n\n    void compute_backward_subproblem_normal_equation(const QuadraticCost& marginal_cost,\n        const State& cur_state,\n        const Control& cur_control,\n        MatrixXd& lhs,\n        VectorXd& rhs)\n    {\n        const int state_size = 2;\n        const int control_size = 2;\n        const int total_size = state_size + control_size;\n\n        RocketMotionModel motion_model;\n        const RocketState rstate = ddp_vars_to_rocket_state(cur_state, cur_control);\n\n        const MatrixXd jacobi_wrt_augment_state = motion_model.jacobian_wrt_state(rstate);\n        MatrixXd jacobian_marginal_cost = jacobi_wrt_augment_state.block(0, 0, state_size, total_size);\n\n        const RocketState predict_state = motion_model.motion(rstate);\n\n        std::cout << \"rstate.var:       \" << rstate.variables << std::endl;\n        std::cout << \"predict_state.var:\" << predict_state.variables << std::endl;\n        std::cout << \"jacobian_marginal_cost: \" << jacobian_marginal_cost << std::endl;\n\n        const VectorXd residual = predict_state.lcn_state() - marginal_cost.mean;\n\n        lhs = jacobian_marginal_cost.transpose() * marginal_cost.weight * jacobian_marginal_cost;\n        rhs = -jacobian_marginal_cost.transpose() * marginal_cost.weight * residual;\n\n        // current cost (just regularizations for this problem)\n        const double time_regularization = 1e-3 / num_states_;\n        lhs(RocketState::i_velocity_x, RocketState::i_velocity_x) += 2 * time_regularization;\n        rhs(RocketState::i_velocity_x) += -2 * time_regularization * cur_control(RocketState::i_velocity_x - 2);\n\n        lhs(RocketState::i_velocity_y, RocketState::i_velocity_y) += 2 * time_regularization;\n        rhs(RocketState::i_velocity_y) += -2 * time_regularization * cur_control(RocketState::i_velocity_y - 2);\n    }\n\n    QuadraticCost target_cost(const Vector2d& target_state)\n    {\n        QuadraticCost qcost;\n        qcost.mean = target_state;\n        MatrixXd jacobi = MatrixXd::Identity(2, 2);\n\n        MatrixXd weight = MatrixXd::Identity(2, 2);\n        Vector2d weight_diag;\n        //  dt, x, y, vel_x, vel_y, heading\n        weight_diag << 1e0, 1e0;\n        weight.diagonal() = weight_diag;\n\n        qcost.weight = jacobi.transpose() * weight * jacobi;\n\n        return qcost;\n    }\n\n    void apply_control_law(DDPStates& ddp_states)\n    {\n        std::vector<Control> new_controls = ddp_states.controls;\n        std::vector<State> new_states = ddp_states.states;\n        RocketMotionModel motion_model;\n\n        double shooting_cost = std::numeric_limits<double>::max();\n\n        PRINT_NAME_VAR(shooting_cost);\n        PRINT_NAME_VAR(current_best_cost_);\n\n        // DDP is HARD to converge!\n        double step = 0.5;\n        // for (; current_best_cost_ < shooting_cost && step > 1e-4; step *= 0.5) {\n        for (int i = 0; i < ddp_states.num_states - 1; ++i) {\n            const FeedbackLaw& feedback = ddp_states.feedbacks.at(i);\n            Vector2d delta_state = new_states.at(i) - ddp_states.states.at(i);\n            if (i == 0)\n                assert(delta_state.sum() == 0);\n\n            Vector2d delta_control = feedback.apply(delta_state);\n\n            std::cout << \"=== idex: \" << i << std::endl;\n            std::cout << \"delta_state: \" << delta_state.transpose() << std::endl;\n            std::cout << \"delta_control: \" << delta_control.transpose() << std::endl;\n\n            new_controls.at(i) = ddp_states.controls.at(i) + step * delta_control;\n\n            const RocketState new_rstate = ddp_vars_to_rocket_state(new_states.at(i), new_controls.at(i));\n            new_states.at(i + 1) = motion_model.motion(new_rstate).lcn_state();\n\n            std::cout << \"new_control: \" << new_controls.at(i).transpose() << std::endl;\n            std::cout << \"cur_state:   \" << new_states.at(i).transpose() << std::endl;\n            std::cout << \"new_state:   \" << new_states.at(i + 1).transpose() << std::endl;\n        }\n\n        QuadraticCost marginal_cost = target_cost(ddp_states.target_state);\n        double cur_cost = marginal_cost.eval(new_states.back());\n        shooting_cost = std::min(shooting_cost, cur_cost);\n        // }\n\n        current_best_cost_ = std::min(current_best_cost_, shooting_cost);\n\n        std::cout << \"ddp backtracking step:\" << step << std::endl;\n        std::cout << \"current_best_cost_:\" << current_best_cost_ << std::endl;\n        std::cout << \"cur_cost:\" << cur_cost << std::endl;\n\n        ddp_states.states = new_states;\n        ddp_states.controls = new_controls;\n    }\n\n    // current minmum target cost. Should use total cost.\n    double current_best_cost_ = std::numeric_limits<double>::max();\n\n    double num_states_ = -1;\n};\n\n// yimu@yimu-mate:~/Desktop/blog$ /usr/bin/python3 /home/yimu/Desktop/blog/yimu-blog/least_squares/ddp/ddp_optimization.py\n// initial_state: [0.1 0.1]\n// target_state: [2. 2.]\n// num_states: 11\n// final_state_end_cost: [[0.22966875]]\n// final_state_end_cost: [[0.00102592]]\n// final_state_end_cost: [[0.00737957]]\n// final_state_end_cost: [[0.00287627]]\n// final_state_end_cost: [[0.00056493]]\n// final_state_end_cost: [[6.04254466e-05]]\n// final_state_end_cost: [[1.60630207e-06]]\n// final_state_end_cost: [[8.4323494e-07]]\n// final_state_end_cost: [[1.20808104e-06]]\n// final_state_end_cost: [[6.61618857e-07]]\n// ----------------------------------\n// new_controls:\n//  [array([0.19102753, 0.18981443]), array([0.19110838, 0.18991752]), array([0.19117968, 0.19001093]), array([0.19123781, 0.19009055]), array([0.19127743, 0.19015008]), array([0.19129027, 0.19017957]), array([0.19126273, 0.19016206]), array([0.19117054, 0.19006576]), array([0.19096421, 0.18982076]), array([0.19051605, 0.18921421])]\n// new_states:\n//  [array([0.1, 0.1]), array([0.28986784, 0.28981443]), array([0.47981505, 0.47973195]), array([0.66983226, 0.66974288]), array([0.85990655, 0.85983343]), array([1.05001973, 1.04998351]), array([1.24014552, 1.24016308]), array([1.43024427, 1.43032515]), array([1.62025251, 1.6203909 ]), array([1.81005818, 1.81021167]), array([1.9994238 , 1.99942588])]\n\n// ./test_ddp | grep cur_cost\n// cur_cost:0.229777\n// cur_cost:0.00101972\n// cur_cost:0.00736767\n// cur_cost:0.00287048\n// cur_cost:0.000562644\n// cur_cost:5.97038e-05\n// cur_cost:1.5031e-06\n// cur_cost:9.30061e-07\n// cur_cost:1.31691e-06\n// cur_cost:7.43505e-07\n//\n// new_control: 0.190882 0.189625\n// cur_state:   0.1 0.1\n// --\n// new_control: 0.191034 0.189811\n// cur_state:   0.289725 0.289625\n// --\n// new_control: 0.191173 0.189985\n// cur_state:   0.479599 0.479436\n// --\n// new_control: 0.191293 0.190141\n// cur_state:    0.66961 0.669421\n// --\n// new_control: 0.191385 0.190269\n// cur_state:   0.859738 0.859562\n// --\n// new_control: 0.191435 0.190352\n// cur_state:   1.04996 1.04983\n// --\n// new_control: 0.191417 0.190362\n// cur_state:   1.24023 1.24018\n// --\n// new_control:  0.19128 0.190237\n// cur_state:   1.43048 1.43055\n// --\n// new_control:  0.19091 0.189834\n// cur_state:   1.62059 1.62078\n// --\n// new_control: 0.189926 0.188637\n// cur_state:   1.81034 1.81062\n// --\n// new_control: 0.191024 0.189811\n// cur_state:   0.1 0.1\n// --\n// new_control: 0.191105 0.189914\n// cur_state:   0.289864 0.289811\n// --\n// new_control: 0.191176 0.190007\n// cur_state:   0.479808 0.479725\n// --\n// new_control: 0.191234 0.190087\n// cur_state:   0.669822 0.669733\n// --\n// new_control: 0.191274 0.190147\n// cur_state:   0.859892  0.85982\n// --\n// new_control: 0.191287 0.190176\n// cur_state:      1.05 1.04997\n// --\n// new_control: 0.191259 0.190159\n// cur_state:   1.24012 1.24014\n// --\n// new_control: 0.191167 0.190062\n// cur_state:   1.43022  1.4303\n// --\n// new_control: 0.190961 0.189817\n// cur_state:   1.62022 1.62036\n// --\n// new_control: 0.190513 0.189211\n// cur_state:   1.81003 1.81018\n\nint main(int argc, char* argv[])\n{\n    RocketLandingProblem p;\n\n    DifferentialDynamicProgramming solver;\n    solver.solve(p);\n\n    return 1;\n}", "meta": {"hexsha": "3efdbff254aec3242c6a360321df81cb1467a9db", "size": 17063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "least_squares/land_rocket/test_ddp.cpp", "max_stars_repo_name": "yimuw/yimu-blog", "max_stars_repo_head_hexsha": "280ab2eca1fa48602d1695d69366842ea40debda", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-06-11T05:50:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:41:05.000Z", "max_issues_repo_path": "least_squares/land_rocket/test_ddp.cpp", "max_issues_repo_name": "yimuw/yimu-blog", "max_issues_repo_head_hexsha": "280ab2eca1fa48602d1695d69366842ea40debda", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-06-28T13:58:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:30:54.000Z", "max_forks_repo_path": "least_squares/land_rocket/test_ddp.cpp", "max_forks_repo_name": "yimuw/yimu-blog", "max_forks_repo_head_hexsha": "280ab2eca1fa48602d1695d69366842ea40debda", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-07-07T04:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T03:42:54.000Z", "avg_line_length": 32.0131332083, "max_line_length": 353, "alphanum_fraction": 0.6365234718, "num_tokens": 4899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5452035302118564}}
{"text": "/**TODO:  Add copyright*/\n\n#define BOOST_TEST_MODULE ModelFile test suite \n#include <boost/test/included/unit_test.hpp>\n#include <SmartPeak/io/ModelFile.h>\n\nusing namespace SmartPeak;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(ModelFile1)\n\nModel<float> makeModel1()\n{\n\t/**\n\t* Directed Acyclic Graph Toy Network Model\n\t*/\n\tNode<float> i1, i2, h1, h2, o1, o2, b1, b2;\n\tLink l1, l2, l3, l4, lb1, lb2, l5, l6, l7, l8, lb3, lb4;\n\tWeight<float> w1, w2, w3, w4, wb1, wb2, w5, w6, w7, w8, wb3, wb4;\n\tModel<float> model1;\n\n\t// Toy network: 1 hidden layer, fully connected, DAG\n\ti1 = Node<float>(\"0\", NodeType::input, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\ti2 = Node<float>(\"1\", NodeType::input, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\th1 = Node<float>(\"2\", NodeType::hidden, NodeStatus::deactivated, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\th2 = Node<float>(\"3\", NodeType::hidden, NodeStatus::deactivated, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\to1 = Node<float>(\"4\", NodeType::output, NodeStatus::deactivated, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\to2 = Node<float>(\"5\", NodeType::output, NodeStatus::deactivated, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\tb1 = Node<float>(\"6\", NodeType::bias, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\tb2 = Node<float>(\"7\", NodeType::bias, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\n\t// weights  \n\tstd::shared_ptr<WeightInitOp<float>> weight_init;\n\tstd::shared_ptr<SolverOp<float>> solver;\n\t// weight_init.reset(new RandWeightInitOp(1.0)); // No random init for testing\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw1 = Weight<float>(\"0\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  w1.setWeight(1);\n\tw2 = Weight<float>(\"1\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  w2.setWeight(2);\n\tw3 = Weight<float>(\"2\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  w3.setWeight(3);\n\tw4 = Weight<float>(\"3\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\twb1 = Weight<float>(\"4\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\twb2 = Weight<float>(\"5\", weight_init, solver);\n\t// input layer + bias\n\tl1 = Link(\"0\", \"0\", \"2\", \"0\");\n\tl2 = Link(\"1\", \"0\", \"3\", \"1\");\n\tl3 = Link(\"2\", \"1\", \"2\", \"2\");\n\tl4 = Link(\"3\", \"1\", \"3\", \"3\");\n\tlb1 = Link(\"4\", \"6\", \"2\", \"4\");\n\tlb2 = Link(\"5\", \"6\", \"3\", \"5\");\n\t// weights\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw5 = Weight<float>(\"6\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw6 = Weight<float>(\"7\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw7 = Weight<float>(\"8\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw8 = Weight<float>(\"9\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\twb3 = Weight<float>(\"10\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\twb4 = Weight<float>(\"11\", weight_init, solver);\n\t// hidden layer + bias\n\tl5 = Link(\"6\", \"2\", \"4\", \"6\");\n\tl6 = Link(\"7\", \"2\", \"5\", \"7\");\n\tl7 = Link(\"8\", \"3\", \"4\", \"8\");\n\tl8 = Link(\"9\", \"3\", \"5\", \"9\");\n\tlb3 = Link(\"10\", \"7\", \"4\", \"10\");\n\tlb4 = Link(\"11\", \"7\", \"5\", \"11\");\n\tmodel1.setId(1);\n\tmodel1.setName(\"1\");\n\tmodel1.addNodes({ i1, i2, h1, h2, o1, o2, b1, b2 });\n\tmodel1.addWeights({ w1, w2, w3, w4, wb1, wb2, w5, w6, w7, w8, wb3, wb4 });\n\tmodel1.addLinks({ l1, l2, l3, l4, lb1, lb2, l5, l6, l7, l8, lb3, lb4 });\n\tmodel1.setInputAndOutputNodes();\n\treturn model1;\n}\n\nBOOST_AUTO_TEST_CASE(constructor) \n{\n  ModelFile<float>* ptr = nullptr;\n  ModelFile<float>* nullPointer = nullptr;\n  ptr = new ModelFile<float>();\n  BOOST_CHECK_NE(ptr, nullPointer);\n}\n\nBOOST_AUTO_TEST_CASE(destructor) \n{\n  ModelFile<float>* ptr = nullptr;\n\tptr = new ModelFile<float>();\n  delete ptr;\n}\n\nBOOST_AUTO_TEST_CASE(storeModelDot)\n{\n\tModelFile<float> data;\n\n\tstd::string filename = \"ModelFileTest.gv\";\n\n  Model<float> model1 = makeModel1();\n\tdata.storeModelDot(filename, model1);\n}\n\nBOOST_AUTO_TEST_CASE(loadModelCsv)\n{\n\tModelFile<float> data;\n\tModel<float> model_test;\n\tmodel_test.setId(1);\n\tmodel_test.setName(\"1\");\n\n\tstd::string filename_nodes = \"ModelNodeFileTest.csv\";\n\tstd::string filename_links = \"ModelLinkFileTest.csv\";\n\tstd::string filename_weights = \"ModelWeightFileTest.csv\";\n\n  Model<float> model1 = makeModel1();\n  model1.setInputAndOutputNodes();\n\tdata.storeModelCsv(filename_nodes, filename_links, filename_weights, model1);\n\n\tdata.loadModelCsv(filename_nodes, filename_links, filename_weights, model_test);\n\tBOOST_CHECK_EQUAL(model_test.getId(), model1.getId());\n\tBOOST_CHECK_EQUAL(model_test.getName(), model1.getName());\n\tBOOST_CHECK(model_test.getNodes() == model1.getNodes());\n\tBOOST_CHECK(model_test.getLinks() == model1.getLinks());\n\t//BOOST_CHECK(model_test.getWeights() == model1.getWeights());  // Broke\n  BOOST_CHECK(model_test.getInputNodes().size() == model1.getInputNodes().size()); // Not sure why this fails\n  BOOST_CHECK(model_test.getOutputNodes().size() == model1.getOutputNodes().size()); // Not sure why this fails\n\t//BOOST_CHECK(model_test == model1); // Not sure why this fails\n}\n\nBOOST_AUTO_TEST_CASE(loadModelBinary)\n{\n\tModelFile<float> data;\n\tModel<float> model_test;\n\n\tstd::string filename = \"ModelFileTest.binary\";\n\n  Model<float> model1 = makeModel1();\n  model1.setInputAndOutputNodes();\n\tdata.storeModelBinary(filename, model1);\n\n\tdata.loadModelBinary(filename, model_test);\n\tBOOST_CHECK_EQUAL(model_test.getId(), model1.getId());\n\tBOOST_CHECK_EQUAL(model_test.getName(), model1.getName());\n\tBOOST_CHECK(model_test.getNodes() == model1.getNodes());\n\tBOOST_CHECK(model_test.getLinks() == model1.getLinks());\n\tBOOST_CHECK(model_test.getWeights() == model1.getWeights());\n  BOOST_CHECK(model_test.getInputNodes().size() == model1.getInputNodes().size()); // Not sure why this fails\n  BOOST_CHECK(model_test.getOutputNodes().size() == model1.getOutputNodes().size()); // Not sure why this fails\n\t//BOOST_CHECK(model_test == model1); // Not sure why this fails\n}\n\nBOOST_AUTO_TEST_CASE(loadWeightValuesBinary)\n{\n  // Store the binarized model\n  ModelFile<float> data;\n  std::string filename = \"ModelFileTest.binary\";\n  Model<float> model1 = makeModel1();\n  model1.setInputAndOutputNodes();\n  data.storeModelBinary(filename, model1);\n\n  // Read in the weight values\n  std::map<std::string, std::shared_ptr<Weight<float>>> weights_test;\n  for (int i = 0; i < 3; ++i) {\n    auto weight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n    auto solver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n    std::shared_ptr<Weight<float>> weight(new Weight<float>(\n      std::to_string(i),\n      weight_init,\n      solver));\n    weight->setModuleName(std::to_string(i));\n    weight->setWeight(0);\n    weights_test.emplace(weight->getName(), weight);\n  }\n  data.loadWeightValuesBinary(filename, weights_test);\n\n  // Test that the weight values match \n  for (int i = 0; i < 3; ++i) {\n    BOOST_CHECK_EQUAL(model1.weights_.at(std::to_string(i))->getWeight(), weights_test.at(std::to_string(i))->getWeight());\n    BOOST_CHECK(!weights_test.at(std::to_string(i))->getInitWeight());\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "59b287e3d5c6c73a5f6b984d6301726e172f9e56", "size": 10523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/class_tests/smartpeak/source/ModelFile_test.cpp", "max_stars_repo_name": "dmccloskey/EvoNet", "max_stars_repo_head_hexsha": "8d7fafe1069593024e5b63fd6b81a341a3bf33b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-28T11:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T11:38:13.000Z", "max_issues_repo_path": "src/tests/class_tests/smartpeak/source/ModelFile_test.cpp", "max_issues_repo_name": "dmccloskey/EvoNet", "max_issues_repo_head_hexsha": "8d7fafe1069593024e5b63fd6b81a341a3bf33b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2018-10-03T11:35:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-14T09:17:07.000Z", "max_forks_repo_path": "src/tests/class_tests/smartpeak/source/ModelFile_test.cpp", "max_forks_repo_name": "dmccloskey/EvoNet", "max_forks_repo_head_hexsha": "8d7fafe1069593024e5b63fd6b81a341a3bf33b5", "max_forks_repo_licenses": ["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.8374384236, "max_line_length": 353, "alphanum_fraction": 0.7118692388, "num_tokens": 3092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5451417931685669}}
{"text": "#define IGNORE\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nusing mpi = boost::multiprecision::int128_t;\n// using mpi = boost::multiprecision::cpp_int // \u4efb\u610f\u6841\n\nusing namespace boost::numeric;\nusing imatrix = ublas::matrix<mpi>;\n// \u884c\u5217\u7a4d\u306f ublas::prod\n// imatrix mat(N, M);\n// mat(N, M) = 2;\n", "meta": {"hexsha": "c4d9f17912e080aa3caaeb01c94654099c00e4db", "size": 368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++-library/boost.cpp", "max_stars_repo_name": "knuu/test_for_python_contest_library", "max_stars_repo_head_hexsha": "c594f18b6d9d0d8baebc2e93d98c5f1fccf32d7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-21T12:12:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T03:19:33.000Z", "max_issues_repo_path": "c++-library/boost.cpp", "max_issues_repo_name": "knuu/contest_library", "max_issues_repo_head_hexsha": "94b0c9eb82e7e2543bf82ea5a07bfe80e5f2ddc3", "max_issues_repo_licenses": ["MIT"], "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++-library/boost.cpp", "max_forks_repo_name": "knuu/contest_library", "max_forks_repo_head_hexsha": "94b0c9eb82e7e2543bf82ea5a07bfe80e5f2ddc3", "max_forks_repo_licenses": ["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.5333333333, "max_line_length": 52, "alphanum_fraction": 0.7201086957, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5451417810604139}}
{"text": "/*\nMIT License\n\nCopyright (c) 2019 Xiaohong Chen\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#ifndef BOOST_UBLAS_PRECONDITIONER_HPP\n#define BOOST_UBLAS_PRECONDITIONER_HPP\n\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\nnamespace boost { namespace numeric { namespace ublas {\n\ntemplate <class M>\nclass identity_precond {\npublic:\n    identity_precond() {}\n    identity_precond(const M&) {}\n\n    template<class E>\n    const vector_expression<E>& operator()(const vector_expression<E>& ve) const {\n        return ve;\n    }\n};\n\ntemplate <class M>\nclass jacobi_precond {\npublic:\n    typedef typename M::value_type value_type;\n    typedef typename M::size_type size_type;\n    jacobi_precond(const M& A)\n        : diag_(A.size1()) {\n        size_type size = A.size1();\n        for (size_type i = 0; i < size; ++i) {\n            diag_(i) = A(i, i);\n        }\n    }\n\n    jacobi_precond(const jacobi_precond&) = default;\n    jacobi_precond(jacobi_precond&&) = default;\n    jacobi_precond& operator=(const jacobi_precond&) = default;\n    jacobi_precond& operator=(jacobi_precond&&) = default;\n\n    template<class E>\n    decltype(auto) operator()(const vector_expression<E>& ve) const {\n        return element_prod(ve, diag_);\n    }\n\nprivate:\n    vector<value_type> diag_;\n};\n\n} // end namespace linear\n} // end namespace solver\n} // end namespace math\n\n\n#endif\n", "meta": {"hexsha": "e0d062578b436c6f319d5c8e6948b395ade2e4af", "size": 2423, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/preconditioner.hpp", "max_stars_repo_name": "xiaohongchen1991/krylov-solvers", "max_stars_repo_head_hexsha": "148d7bb4107a80c9e1771d77a0d589afb74d5744", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T20:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T02:46:55.000Z", "max_issues_repo_path": "include/preconditioner.hpp", "max_issues_repo_name": "xiaohongchen1991/krylov-solvers", "max_issues_repo_head_hexsha": "148d7bb4107a80c9e1771d77a0d589afb74d5744", "max_issues_repo_licenses": ["MIT"], "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/preconditioner.hpp", "max_forks_repo_name": "xiaohongchen1991/krylov-solvers", "max_forks_repo_head_hexsha": "148d7bb4107a80c9e1771d77a0d589afb74d5744", "max_forks_repo_licenses": ["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.6708860759, "max_line_length": 82, "alphanum_fraction": 0.733801073, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5451115571191213}}
{"text": "#include <stdio.h>\n#include <fstream>\n#include <string>\n#include <time.h>\n#include \"Matrix.h\"\n\n// boost directives\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n// // pybind11 directives for numpy arrays\n// #include <pybind11/pybind11.h>\n// #include <pybind11/numpy.h>\n\n// current issue: cannot find <Python.h>, so we need to put this in -I flag\n// This will be implemented in the Makefile\n\nusing namespace boost::numeric;\n\nvoid read_from_file(ublas::matrix<double> &bmat, const std::string &fname)\n{\n    std::ifstream ifs{fname};\n\n    if (!ifs)\n    {\n        throw std::runtime_error(\"Cannot open file!\");\n    }\n\n    double val;\n\n    std::string line;\n    int i = 0; // row index\n\n    while (std::getline(ifs, line))\n    {                                // read each line in file\n        int j = 0;                   // column index\n        std::istringstream ss{line}; // stringstream of each row\n        while (ss >> val)\n        {\n            bmat(i, j) = val; // set value\n            ++j;              // increment column index\n        }\n\n        ++i; // increment row index\n    }\n}\n\n// void read_from_nparray(ublas::matrix<double> &bmat, const pybind11::array_t<double>& arr)\n// {\n//         // request buffer info from numpy array\n//     pybind11::buffer_info buf = arr.request();\n\n//     // check if dimensions are equal\n//     if (buf.shape[0] != bmat.size1() && buf.shape[1] != bmat.size2())\n//     {\n//         throw std::runtime_error(\"Dimensions are not equal!\")\n//     }\n//     rsz = buf.shape[0];\n//     csz = buf.shape[1];\n\n//     // set a new pointer ptr to the buffer pointer\n//     double *ptr = (double *)buf.ptr;\n\n//     // set pointer to buffer pointer\n//     for (int i = 0; i < rsz; ++i)\n//     {\n//         for (int j = 0; j < csz; ++j)\n//         {\n//             bmat(i,j) = ptr[i * csz + j];\n//         }\n//     }\n// }\n\nvoid test_performance(Matrix *myMat_ptr, ublas::matrix<double> bMat)\n{\n    // test performance\n    int max_iter = 10000; // max iterations\n    // empty arrays for mean computation\n    // std::vector<double> my_normarr(max_iter);\n    // std::vector<double> b_normarr(max_iter);\n    // std::vector<double> my_timearr(max_iter);\n    // std::vector<double> b_normarr(max_iter);\n    double my_norm, b_norm, my_avgnorm, b_avgnorm;\n    double my_time, b_time, my_avgtime, b_avgtime;\n\n    for (int i = 0; i < max_iter; ++i)\n    {\n        clock_t my_t, b_t;\n        // evaluate norm from matrix class\n        my_t = clock();\n        double my_n = myMat_ptr->norm();\n        // myMat_ptr->norm() = my_n;\n        my_t = clock() - my_t;\n        // std::cout << \"Norm from my library: \" << my_n << std::endl\n        //          << \"Time from my library: \" << (double) my_t / CLOCKS_PER_SEC << std::endl;\n\n        // now from ublas\n        b_t = clock();\n        double b_n = norm_frobenius(bMat);\n        b_t = clock() - b_t;\n        // std::cout << \"Norm from boost: \" << b_n << std::endl\n        //          << \"Time from boost: \" << (double) b_t / CLOCKS_PER_SEC << std::endl;\n\n        // append the results\n        my_norm += my_n;\n        b_norm += b_n;\n        my_time += ((double)my_t / CLOCKS_PER_SEC);\n        b_time += ((double)b_t / CLOCKS_PER_SEC);\n        // my_normarr.push_back(my_norm);\n        // b_normarr.push_back(b_norm);\n        // my_timearr.push_back((float) my_t / CLOCKS_PER_SEC);\n        // b_timearr.push_back((float) b_t / CLOCKS_PER_SEC);\n    }\n\n    // evaluate the mean\n    my_avgnorm = my_norm / max_iter;\n    b_avgnorm = b_norm / max_iter;\n    my_avgtime = my_time / max_iter;\n    b_avgtime = b_time / max_iter;\n\n    // print results\n    printf(\"Results from performance benchmarking for %d-by-%d matrix:\\n\", bMat.size1(), bMat.size2());\n    printf(\"Number of iterations for performance benchmark: %d\\n\", max_iter);\n    std::cout << \"Average norm evaluated from user-defined matrix: \" << my_avgnorm << \", \\t Average norm evaluated from Boost: \" << b_avgnorm << std::endl\n              << \"Average time taken for evaluation of norm from user-defined matrix: \" << my_avgtime << std::endl\n              << \"Average time taken for evaluation of norm from Boost: \" << b_avgtime << std::endl\n              << \"Comparisons:\" << std::endl\n              << \"Accuracy of user-defined matrix norm vs Boost norm: \" << abs(b_avgnorm - my_avgnorm) << std::endl\n              << \"Ratio of user-defined matrix performance to Boost performance: \" << my_avgtime / b_avgtime << std::endl;\n}\n\nint main()\ntry\n{\n    // initialize parameters\n    // int rs{3};\n    // int cs{4};\n    // std::string fname{\"data/small_data.tsv\"};\n\n    int rs{3000};\n    int cs{4000};\n    std::string fname{\"data/large_data.tsv\"};\n\n    // create matrices\n    Matrix *myMat_ptr = new Matrix{rs, cs, fname};\n    ublas::matrix<double> bMat(rs, cs);\n    read_from_file(bMat, fname);\n\n    test_performance(myMat_ptr, bMat);\n\n    return 0;\n}\ncatch (std::exception &e)\n{\n    std::cerr << \"error: \" << e.what() << std::endl;\n    return 1;\n}\n\n// {\n//     // common parameters for both matrices\n//     int rs{3};\n//     int cs{4};\n//     std::string fname{\"data/small_data.txt\"};\n\n//     // // // common parameters for both matrices\n//     // int rs {3000};\n//     // int cs {4000};\n//     // std::string fname {\"data/large_data.txt\"};\n\n//     // create matrices and print them out\n//     Matrix myMat{rs, cs, fname};\n//     // Matrix *myMat = new Matrix {rs, cs, fname};\n//     // double my_norm;\n//     // myMat->norm() = my_norm;\n//     // myMat.print_mat();\n\n//     ublas::matrix<double> bMat(rs, cs);\n//     read_from_file(bMat, fname);\n//     // std::cout << bMat << '\\n';\n\n//     std::cout << \"hello\" << std::endl;\n\n//     // now compute norm for both and print them out\n//     // iterate 1e6 times and take average to determine average time\n//     double my_norm = myMat.norm();\n//     std::cout << \"Norm from my library: \" << my_norm << std::endl;\n\n//     double b_norm = norm_frobenius(bMat);\n//     std::cout << \"Norm from boost: \" << b_norm << std::endl;\n// }", "meta": {"hexsha": "06f60d4dfbaed57df1d6fd1d8703c1a442e1a910", "size": 6021, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pbmo/legacy/tests/legacy/test_matrix.cc", "max_stars_repo_name": "kwat0308/pbmo", "max_stars_repo_head_hexsha": "5d06d29a2a1db6eb29b5c8a104dd91725df6f807", "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": "pbmo/legacy/tests/legacy/test_matrix.cc", "max_issues_repo_name": "kwat0308/pbmo", "max_issues_repo_head_hexsha": "5d06d29a2a1db6eb29b5c8a104dd91725df6f807", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pbmo/legacy/tests/legacy/test_matrix.cc", "max_forks_repo_name": "kwat0308/pbmo", "max_forks_repo_head_hexsha": "5d06d29a2a1db6eb29b5c8a104dd91725df6f807", "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.6894736842, "max_line_length": 154, "alphanum_fraction": 0.573824946, "num_tokens": 1667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5451115495026597}}
{"text": "#include <iostream>\n#include <armadillo.h>\n#include <digitRecognition.h>\n//#include <mkl.h>\n\nusing namespace arma;\n\nconstexpr int training_size = 4000;    //m\nconstexpr int input_layer_size = 784;  //k\nconstexpr int hidden_layer_size = 500;  //n\nconstexpr int num_labels = 10;\n\nconstexpr double lambda = 0.1;\nconstexpr int max_iterations = 1000;\n\n\nint main () {\n//\tstd::cout << \"Starting program with \" << mkl_get_max_threads() << \" threads...\" << std::endl;\n\n\t//mkl_set_num_threads(4);\n\n    mat predictions(training_size,1,fill::zeros);\n    \n    mat x_train(training_size,input_layer_size,fill::zeros);\n    //x_train.load(\"c:\\\\train_x_4000.csv\");\n    x_train.load(\"./mnist_data/train_x_4000.csv\");\n    \n    mat y_train(training_size,1,fill::randu);\n    //y_train.load(\"c:\\\\train_y_4000.csv\");\n    y_train.load(\"./mnist_data/train_y_4000.csv\");\n    \n    \n    mat s(10000,10000,fill::randu);\n    mat t(10000,10000,fill::randu);\n    mat u(10000,10000,fill::zeros);\n    \n    \n\twall_clock timer;\n\ttimer.tic();    \n    u = s * t;\n    double n = timer.toc();\n\tstd::cout << \"10k x 10k matrix multiplication completed in: \" << n << \" seconds.\" << endl;\n    pause();\n    \n    \n    ////calculate mean of the training data\n    //double x_mean = sum(sum(x_train));\n    //x_mean /= x_train.n_elem;  //33.5026  TODO: check this\n    //\n    ////calculate standard devication of the training data\n    //mat x_train_mean(training_size,input_layer_size);\n    //x_train_mean = x_train;\n    //x_train_mean.transform( [x_mean](double val){return (val - x_mean);} );\n    //double x_std = sum(sum(x_train_mean));\n    //x_std /= (x_train_mean.n_elem);\n    //x_std = std::sqrt(x_std);  //7.23942e-06  TODO: check this\n\n\tx_train = x_train / 255.0;\n\t//x_train.transform([](double val){return (val/255.0); });\n\t//std::cout << x_train.row(0) << endl;\n\n    \n\tmat initial_theta1(hidden_layer_size, input_layer_size + 1, fill::ones);  //784 26   n k+1\n\t//initial_theta1.load(\"c:\\\\theta1.csv\");\n\tinitial_theta1.load(\"./mnist_data/theta1.csv\");\n\tmat initial_theta2(num_labels, hidden_layer_size + 1, fill::ones);        //25 11     numlabels n+1\n\t//initial_theta2.load(\"c:\\\\theta2.csv\");\n\tinitial_theta2.load(\"./mnist_data/theta2.csv\");\n\n\tinitial_theta1.reshape(hidden_layer_size*(input_layer_size + 1),1);\n\tinitial_theta2.reshape(num_labels*(hidden_layer_size + 1),1);\n    \n    mat combined_theta = join_cols(initial_theta1,initial_theta2);\n    //std::cout << \"combined_theta rows: \" << combined_theta.n_rows << \", cols: \" << combined_theta.n_cols << endl;\n    \n\t//test section----------------------\n\tmat gradient1 = combined_theta;\n\tdouble cost=0.0;\n\t\n\n\t    //costfunction(cost, gradient1, combined_theta, input_layer_size, hidden_layer_size, num_labels, x_train, y_train, lambda);\n\t    fmincg(cost, max_iterations,combined_theta,input_layer_size,hidden_layer_size,num_labels,x_train,y_train,lambda);\n\n    //----------------------------------\n\t\n\n\tstd::cout << \"Final cost: \" << cost << endl;\n    \n    initial_theta1 = combined_theta.submat(0, 0, initial_theta1.n_cols-1, 0);\n\tinitial_theta1.reshape(hidden_layer_size, input_layer_size + 1);\n    //std::cout << \"initial_theta1 rows: \" << initial_theta1.n_rows << \", cols: \" << initial_theta1.n_cols << endl;\n    \n    initial_theta2 = combined_theta.submat(initial_theta1.n_cols, 0,initial_theta1.n_cols+initial_theta2.n_cols-1, 0);\n\tinitial_theta2.reshape(num_labels, hidden_layer_size + 1);\n    //std::cout << \"initial_theta2 rows: \" << initial_theta2.n_rows << \", cols: \" << initial_theta2.n_cols << endl;\n    \n    predict(initial_theta1,initial_theta2,x_train,predictions);\n    \n    //std::cout << \"predictions: \" << predictions.row(0) << endl;\n\n\n\n\t//pauseJNS();\n    \n    return 0;\n}\n\n\n\n\n//         real function costandgradient(gradient, nn_params,input_layer_size,hidden_layer_size,num_labels, inputdata, y, lambda)\n\n//         real, allocatable :: inputdata(:,:), X(:,:), y(:,:), y_representative(:,:), gradient(:,:), ones(:,:)\n//         real, allocatable :: a_1(:,:),z_2(:,:),a_2(:,:),z_3(:,:),a_3(:,:),hofx(:,:)\n//         real, allocatable :: delta_2(:,:), temp_delta_2(:,:), delta_3(:,:), gradient_1(:,:), gradient_2(:,:)\n//         real, allocatable :: Theta1_grad(:,:), Theta2_grad(:,:)\n//         integer :: input_layer_size,hidden_layer_size,num_labels,m,l,K,i\n//         integer :: a1,a2,b1,b2,c1,c2\n//         real :: lambda, temp, J\n//         real, allocatable :: nn_params(:,:), Theta1(:,:), Theta2(:,:), temptheta1(:,:),temptheta2(:,:)\n//         real, allocatable :: a_2_ones(:,:), summation(:,:), summation2(:,:), summation3(:,:),z_2_ones(:,:), sigmoid_z_2(:,:)\n    \n//         real :: timer1, timer2, holder1, holder2\n//         double precision :: average1 = 0.0\n//         double precision :: average2 = 0.0\n//         double precision :: average3 = 0.0\n//         double precision :: counter = 0.0\n    \n        \n        \n//         m = size(inputdata,1)\n//         l = size(y,1)\n//         K = num_labels\n\n//         allocate(Theta1(1:hidden_layer_size,1:(input_layer_size+1)))\n//         allocate(Theta2(1:num_labels,1:(hidden_layer_size+1)))\n//         allocate(ones(m,1))\n//         allocate(X(size(inputdata,1),(size(inputdata,2)+1)))        \n//         allocate(y_representative(l,num_labels))        \n//         allocate(z_2(m,hidden_layer_size))\n//         allocate(a_1(size(X,1),size(X,2)))\n//         allocate(a_2(size(z_2,1),size(z_2,2)))              \n//         allocate(a_2_ones(size(a_2,1),(size(a_2,2)+1)))      \n//         allocate(z_3(size(a_2_ones,1),size(Theta2,1)))  !a_2 * Theta2'      \n//         allocate(temptheta2(size(Theta2,2),size(Theta2,1)))        \n//         allocate(a_3(size(z_3,1),size(z_3,2)))        \n//         allocate(summation(size(z_3,1),size(z_3,2)))\n//         allocate(summation2(size(z_3,1),size(z_3,2)))\n//         allocate(summation3(size(z_3,1),size(z_3,2)))\n//         allocate(delta_3(size(a_3,1),size(a_3,2)))        \n//         allocate(z_2_ones(size(z_2,1),(size(z_2,2)+1)))        \n//         allocate(sigmoid_z_2(size(z_2_ones,1),size(z_2_ones,2)))        \n//         allocate(temp_delta_2(size(delta_3,1),size(Theta2,2)))   \n//         allocate(delta_2(size(temp_delta_2,1),size(sigmoid_z_2,2)))\n//         allocate(gradient_2(size(delta_3,2),size(a_2_ones,2)))        \n//         allocate(gradient_1(size(delta_2,2)-1,size(a_1,2)))\n//         allocate(Theta2_grad(1:size(gradient_2),1))\n//         allocate(Theta1_grad(1:size(gradient_1),1))        \n        \n//         allocate(temptheta1(size(Theta1,2),size(Theta1,1)))  \n        \n\n//         Theta1 = reshape(nn_params(1:hidden_layer_size*(input_layer_size + 1),1), (/ hidden_layer_size, (input_layer_size + 1) /))\n//         Theta2 = reshape(nn_params((1+hidden_layer_size*(input_layer_size + 1)):,1), (/ num_labels, (hidden_layer_size + 1) /))\n        \n//         !print *,shape(Theta1)   !500 x 785\n//         !print *,shape(Theta2)   !10  x 501\n        \n        \n//         ones = 1.0\n\n\n\n        \n//         !timer1=secnds(0.0)\n\n\n//         do i=1,m\n//             temp = y(i,1)\n//             do j=1,K\n//                 if(temp == j)then\n//                     y_representative(i,j) = 1\n//                 else\n//                     y_representative(i,j) = 0\n//                 end if\n//             end do\n//         end do\n\n//         X(:,1:1) = ones\n//         X(:,2:) = inputdata        \n//         a_1 = X\n\n//         z_2 = 0.0\n        \n//         call matrix_multiply(a_1,0,Theta1,1,z_2)\n\n\n//         a_2 = 0.0\n//         call sigmoid(z_2,a_2)\n\n        \n//         a_2_ones(:,1:1) = ones\n//         a_2_ones(:,2:) = a_2\n        \n//         z_3 = 0.0\n//         call matrix_multiply(a_2_ones,0,Theta2,1,z_3)\n        \n//         call sigmoid(z_3,a_3)\n\n//         summation = 0.0\n//         summation = -y_representative * log(a_3) - (1 - y_representative) * log(1 - a_3)\n        \n//         J = sum(summation)\n//         J = J / m\n        \n        \n\n        \n//         !do concurrent (i = 1:size(delta_3,1))\n//         !    delta_3(i,:) = a_3(i,:) - y(1,:)\n//         !end do\n        \n//         delta_3 = a_3 - y_representative\n\n//         z_2_ones(:,1:1) = ones\n//         z_2_ones(:,2:) = z_2   \n        \n\n//         sigmoid_z_2 = 0.0\n        \n     \n//         call sigmoidgradient(z_2_ones,sigmoid_z_2)  \n\n\n//         !temp_delta_2 = matmul(delta_3,Theta2)\n\n// !timer1=secnds(0.0)   \n//         !a1 = size(delta_3,1)\n//         !a2 = size(delta_3,2)\n//         !b1 = size(Theta2,1)\n//         !b2 = size(Theta2,2)\n//         !call sGEMM('N','N',a1,b2,b1,1.0,delta_3,a1,Theta2,b1,0.0,temp_delta_2,a1)\n//         call matrix_multiply(delta_3,0,Theta2,0,temp_delta_2)\n// !timer2=secnds(timer1)\n// !average1 = average1 + timer2\n// !counter = counter + 1\n// !print '(a, f8.4)','matrix_multiply timer: ', average1/counter        \n        \n//         delta_2 =0.0\n//         !delta_2 = temp_delta_2 * sigmoid_z_2   !elemental multiplication\n//         call vsMul( size(temp_delta_2), temp_delta_2, sigmoid_z_2, delta_2 )   !elemental multiplication    \n\n        \n//         gradient_2 = 0.0\n//         gradient_1 = 0.0\n        \n//         call matrix_multiply(delta_3,1,a_2_ones,0,gradient_2)\n        \n//         call matrix_multiply(delta_2(:,2:),1,a_1,0,gradient_1)        \n        \n//         gradient_2 = gradient_2 / m\n//         gradient_1 = gradient_1 / m\n        \n//         gradient_2(:,2:) = gradient_2(:,2:) + Theta2(:,2:) * (lambda / m)\n//         gradient_1(:,2:) = gradient_1(:,2:) + Theta1(:,2:) * (lambda / m)\n\n\n//         Theta2_grad = reshape(gradient_2, (/size(gradient_2),1/))\n//         Theta1_grad = reshape(gradient_1, (/size(gradient_1),1/))\n\n//         gradient(1:size(Theta1_grad),1:1) = Theta1_grad\n//         gradient((size(Theta1_grad)+1):,1:1) = Theta2_grad\n        \n//         costandgradient = J\n        \n        \n//         !print '(f8.4, a, f8.4)',average1/counter,' ',average2/counter\n//         !timer2=secnds(timer1)\n//         !average = average*0.9 + timer2*0.1\n//         !print '(a, f8.4)','costandgradient timer: ', timer2\n//     end function costandgradient", "meta": {"hexsha": "5b6d92345a8562e38e88fbf10727d9652f6c56fb", "size": 10062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "jshahbazi/mnist-cpp", "max_stars_repo_head_hexsha": "d757d07c03b2c24df94af4c0762b99db21c21538", "max_stars_repo_licenses": ["MIT"], "max_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": "jshahbazi/mnist-cpp", "max_issues_repo_head_hexsha": "d757d07c03b2c24df94af4c0762b99db21c21538", "max_issues_repo_licenses": ["MIT"], "max_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": "jshahbazi/mnist-cpp", "max_forks_repo_head_hexsha": "d757d07c03b2c24df94af4c0762b99db21c21538", "max_forks_repo_licenses": ["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.8078291815, "max_line_length": 133, "alphanum_fraction": 0.5699662095, "num_tokens": 3040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6261241842048093, "lm_q1q2_score": 0.5451020086574941}}
{"text": "/**\n * @file recurrent_network_test.cpp\n * @author Marcus Edel\n *\n * Tests the recurrent network.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/layer/linear_layer.hpp>\n#include <mlpack/methods/ann/layer/recurrent_layer.hpp>\n#include <mlpack/methods/ann/layer/base_layer.hpp>\n#include <mlpack/methods/ann/layer/lstm_layer.hpp>\n#include <mlpack/methods/ann/layer/binary_classification_layer.hpp>\n\n#include <mlpack/methods/ann/rnn.hpp>\n#include <mlpack/methods/ann/performance_functions/mse_function.hpp>\n#include <mlpack/core/optimizers/sgd/sgd.hpp>\n#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n #include <mlpack/methods/ann/init_rules/nguyen_widrow_init.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\nBOOST_AUTO_TEST_SUITE(RecurrentNetworkTest);\n\n/**\n * Construct a 2-class dataset out of noisy sines.\n *\n * @param data Input data used to store the noisy sines.\n * @param labels Labels used to store the target class of the noisy sines.\n * @param points Number of points/features in a single sequence.\n * @param sequences Number of sequences for each class.\n * @param noise The noise factor that influences the sines.\n */\nvoid GenerateNoisySines(arma::mat& data,\n                        arma::mat& labels,\n                        const size_t points,\n                        const size_t sequences,\n                        const double noise = 0.3)\n{\n  arma::colvec x =  arma::linspace<arma::Col<double> >(0,\n      points - 1, points) / points * 20.0;\n  arma::colvec y1 = arma::sin(x + arma::as_scalar(arma::randu(1)) * 3.0);\n  arma::colvec y2 = arma::sin(x / 2.0 + arma::as_scalar(arma::randu(1)) * 3.0);\n\n  data = arma::zeros(points, sequences * 2);\n  labels = arma::zeros(2, sequences * 2);\n\n  for (size_t seq = 0; seq < sequences; seq++)\n  {\n    data.col(seq) = arma::randu(points) * noise + y1 +\n        arma::as_scalar(arma::randu(1) - 0.5) * noise;\n    labels(0, seq) = 1;\n\n    data.col(sequences + seq) = arma::randu(points) * noise + y2 +\n        arma::as_scalar(arma::randu(1) - 0.5) * noise;\n    labels(1, sequences + seq) = 1;\n  }\n}\n\n/**\n * Train the vanilla network on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(SequenceClassificationTest)\n{\n  // It isn't guaranteed that the recurrent network will converge in the\n  // specified number of iterations using random weights. If this works 1 of 5\n  // times, I'm fine with that. All I want to know is that the network is able\n  // to escape from local minima and to solve the task.\n  size_t successes = 0;\n\n  for (size_t trial = 0; trial < 5; ++trial)\n  {\n    // Generate 12 (2 * 6) noisy sines. A single sine contains 10 points/features.\n    arma::mat input, labels;\n    GenerateNoisySines(input, labels, 10, 6);\n\n    /*\n     * Construct a network with 1 input unit, 4 hidden units and 2 output units.\n     * The hidden layer is connected to itself. The network structure looks like:\n     *\n     *  Input         Hidden        Output\n     * Layer(1)      Layer(4)      Layer(2)\n     * +-----+       +-----+       +-----+\n     * |     |       |     |       |     |\n     * |     +------>|     +------>|     |\n     * |     |    ..>|     |       |     |\n     * +-----+    .  +--+--+       +-----+\n     *            .     .\n     *            .     .\n     *            .......\n     */\n    LinearLayer<> linearLayer0(1, 4);\n    RecurrentLayer<> recurrentLayer0(4);\n    BaseLayer<LogisticFunction> inputBaseLayer;\n\n    LinearLayer<> hiddenLayer(4, 2);\n    BaseLayer<LogisticFunction> hiddenBaseLayer;\n\n    BinaryClassificationLayer classOutputLayer;\n\n    auto modules = std::tie(linearLayer0, recurrentLayer0, inputBaseLayer,\n                            hiddenLayer, hiddenBaseLayer);\n\n    RNN<decltype(modules), BinaryClassificationLayer, RandomInitialization,\n        MeanSquaredErrorFunction> net(modules, classOutputLayer);\n\n    SGD<decltype(net)> opt(net, 0.5, 500 * input.n_cols, -100);\n\n    net.Train(input, labels, opt);\n\n    arma::mat prediction;\n    net.Predict(input, prediction);\n\n    size_t error = 0;\n    for (size_t i = 0; i < labels.n_cols; i++)\n    {\n      if (arma::sum(arma::sum(arma::abs(prediction.col(i) - labels.col(i)))) == 0)\n      {\n        error++;\n      }\n    }\n\n    double classificationError = 1 - double(error) / labels.n_cols;\n    if (classificationError <= 0.2)\n    {\n      ++successes;\n      break;\n    }\n  }\n\n  BOOST_REQUIRE_GE(successes, 1);\n}\n\n/**\n * Generate a random Reber grammar.\n *\n * For more information, see the following thesis.\n *\n * @code\n * @misc{Gers2001,\n *   author = {Felix Gers},\n *   title = {Long Short-Term Memory in Recurrent Neural Networks},\n *   year = {2001}\n * }\n * @endcode\n *\n * @param transitions Reber grammar transition matrix.\n * @param reber The generated Reber grammar string.\n */\nvoid GenerateReber(const arma::Mat<char>& transitions, std::string& reber)\n{\n  size_t idx = 0;\n  reber = \"B\";\n\n  do\n  {\n    const int grammerIdx = rand() % 2;\n    reber += arma::as_scalar(transitions.submat(idx, grammerIdx, idx,\n        grammerIdx));\n\n    idx = arma::as_scalar(transitions.submat(idx, grammerIdx + 2, idx,\n        grammerIdx + 2)) - '0';\n  } while (idx != 0);\n\n  reber =  \"BPTVVE\";\n}\n\n/**\n * Generate a random embedded Reber grammar.\n *\n * @param transitions Embedded Reber grammar transition matrix.\n * @param reber The generated embedded Reber grammar string.\n */\nvoid GenerateEmbeddedReber(const arma::Mat<char>& transitions,\n                           std::string& reber)\n{\n  GenerateReber(transitions, reber);\n  const char c = (rand() % 2) == 1 ? 'P' : 'T';\n  reber = c + reber + c;\n  reber = \"B\" + reber + \"E\";\n}\n\n/**\n * Convert a Reber symbol to a unit vector.\n *\n * @param symbol Reber symbol to be converted.\n * @param translation The converted symbol stored as unit vector.\n */\nvoid ReberTranslation(const char symbol, arma::colvec& translation)\n{\n  arma::Col<char> symbols;\n  symbols << 'B' << 'T' << 'S' << 'X' << 'P' << 'V' << 'E' << arma::endr;\n  const int idx = arma::as_scalar(arma::find(symbols == symbol, 1, \"first\"));\n\n  translation = arma::zeros<arma::colvec>(7);\n  translation(idx) = 1;\n}\n\n/**\n * Convert a unit vector to a Reber symbol.\n *\n * @param translation The unit vector to be converted.\n * @param symbol The converted unit vector stored as Reber symbol.\n */\nvoid ReberReverseTranslation(const arma::colvec& translation, char& symbol)\n{\n  arma::Col<char> symbols;\n  symbols << 'B' << 'T' << 'S' << 'X' << 'P' << 'V' << 'E' << arma::endr;\n  const int idx = arma::as_scalar(arma::find(translation == 1, 1, \"first\"));\n\n  symbol = symbols(idx);\n}\n\n/**\n * Given a Reber string, return a Reber string with all reachable next symbols.\n *\n * @param transitions The Reber transistion matrix.\n * @param reber The Reber string used to generate all reachable next symbols.\n * @param nextReber All reachable next symbols.\n */\nvoid GenerateNextReber(const arma::Mat<char>& transitions,\n                       const std::string& reber, std::string& nextReber)\n{\n  size_t idx = 0;\n\n  for (size_t grammer = 1; grammer < reber.length(); grammer++)\n  {\n    const int grammerIdx = arma::as_scalar(arma::find(\n        transitions.row(idx) == reber[grammer], 1, \"first\"));\n\n    idx = arma::as_scalar(transitions.submat(idx, grammerIdx + 2, idx,\n        grammerIdx + 2)) - '0';\n  }\n\n  nextReber = arma::as_scalar(transitions.submat(idx, 0, idx, 0));\n  nextReber += arma::as_scalar(transitions.submat(idx, 1, idx, 1));\n}\n\n/**\n * Given a embedded Reber string, return a embedded Reber string with all\n * reachable next symbols.\n *\n * @param transitions The Reber transistion matrix.\n * @param reber The Reber string used to generate all reachable next symbols.\n * @param nextReber All reachable next symbols.\n */\nvoid GenerateNextEmbeddedReber(const arma::Mat<char>& transitions,\n                               const std::string& reber, std::string& nextReber)\n{\n  if (reber.length() <= 2)\n  {\n    nextReber = reber.length() == 1 ? \"TP\" : \"B\";\n  }\n  else\n  {\n    size_t pos = reber.find('E');\n    if (pos != std::string::npos)\n    {\n      nextReber = pos == reber.length() - 1 ? std::string(1, reber[1]) : \"E\";\n    }\n    else\n    {\n      GenerateNextReber(transitions, reber.substr(2), nextReber);\n    }\n  }\n}\n\n/**\n * Train the specified network and the construct a Reber grammar dataset.\n */\ntemplate<typename HiddenLayerType>\nvoid ReberGrammarTestNetwork(HiddenLayerType& hiddenLayer0,\n                             bool embedded = false)\n{\n  // Reber state transition matrix. (The last two columns are the indices to the\n  // next path).\n  arma::Mat<char> transitions;\n  transitions << 'T' << 'P' << '1' << '2' << arma::endr\n              << 'X' << 'S' << '3' << '1' << arma::endr\n              << 'V' << 'T' << '4' << '2' << arma::endr\n              << 'X' << 'S' << '2' << '5' << arma::endr\n              << 'P' << 'V' << '3' << '5' << arma::endr\n              << 'E' << 'E' << '0' << '0' << arma::endr;\n\n  const size_t trainReberGrammarCount = 1000;\n  const size_t testReberGrammarCount = 1000;\n\n  std::string trainReber, testReber;\n  arma::field<arma::mat> trainInput(1, trainReberGrammarCount);\n  arma::field<arma::mat> trainLabels(1, trainReberGrammarCount);\n  arma::field<arma::mat> testInput(1, testReberGrammarCount);\n  arma::colvec translation;\n\n  // Generate the training data.\n  for (size_t i = 0; i < trainReberGrammarCount; i++)\n  {\n    if (embedded)\n      GenerateEmbeddedReber(transitions, trainReber);\n    else\n      GenerateReber(transitions, trainReber);\n\n    for (size_t j = 0; j < trainReber.length() - 1; j++)\n    {\n      ReberTranslation(trainReber[j], translation);\n      trainInput(0, i) = arma::join_cols(trainInput(0, i), translation);\n\n      ReberTranslation(trainReber[j + 1], translation);\n      trainLabels(0, i) = arma::join_cols(trainLabels(0, i), translation);\n    }\n  }\n\n  // Generate the test data.\n  for (size_t i = 0; i < testReberGrammarCount; i++)\n  {\n    if (embedded)\n      GenerateEmbeddedReber(transitions, testReber);\n    else\n      GenerateReber(transitions, testReber);\n\n    for (size_t j = 0; j < testReber.length() - 1; j++)\n    {\n      ReberTranslation(testReber[j], translation);\n      testInput(0, i) = arma::join_cols(testInput(0, i), translation);\n    }\n  }\n\n  /*\n   * Construct a network with 7 input units, layerSize hidden units and 7 output\n   * units. The hidden layer is connected to itself. The network structure looks\n   * like:\n   *\n   *  Input         Hidden        Output\n   * Layer(7)  Layer(layerSize)   Layer(7)\n   * +-----+       +-----+       +-----+\n   * |     |       |     |       |     |\n   * |     +------>|     +------>|     |\n   * |     |    ..>|     |       |     |\n   * +-----+    .  +--+--+       +-----+\n   *            .     .\n   *            .     .\n   *            .......\n   */\n  const size_t lstmSize = 4 * 10;\n  LinearLayer<> linearLayer0(7, lstmSize);\n  RecurrentLayer<> recurrentLayer0(10, lstmSize);\n\n  LinearLayer<>hiddenLayer(10, 7);\n  BaseLayer<LogisticFunction> hiddenBaseLayer;\n\n  BinaryClassificationLayer classOutputLayer;\n\n  auto modules = std::tie(linearLayer0, recurrentLayer0, hiddenLayer0,\n                          hiddenLayer, hiddenBaseLayer);\n\n  RNN<decltype(modules), BinaryClassificationLayer, RandomInitialization,\n      MeanSquaredErrorFunction> net(modules, classOutputLayer);\n\n  SGD<decltype(net)> opt(net, 0.5, 2, -200);\n\n  arma::mat inputTemp, labelsTemp;\n  for (size_t i = 0; i < 15; i++)\n  {\n    for (size_t j = 0; j < trainReberGrammarCount; j++)\n    {\n      inputTemp = trainInput.at(0, j);\n      labelsTemp = trainLabels.at(0, j);\n      net.Train(inputTemp, labelsTemp, opt);\n    }\n  }\n\n  double error = 0;\n\n  // Ask the network to predict the next Reber grammar in the given sequence.\n  for (size_t i = 0; i < testReberGrammarCount; i++)\n  {\n    arma::mat output;\n    arma::mat input = testInput.at(0, i);\n\n    net.Predict(input, output);\n\n    const size_t reberGrammerSize = 7;\n    std::string inputReber = \"\";\n\n    size_t reberError = 0;\n    for (size_t j = 0; j < (output.n_elem / reberGrammerSize); j++)\n    {\n      if (arma::sum(arma::sum(output.submat(j * reberGrammerSize, 0, (j + 1) *\n          reberGrammerSize - 1, 0))) != 1) break;\n\n      char predictedSymbol, inputSymbol;\n      std::string reberChoices;\n\n      ReberReverseTranslation(output.submat(j * reberGrammerSize, 0, (j + 1) *\n          reberGrammerSize - 1, 0), predictedSymbol);\n      ReberReverseTranslation(input.submat(j * reberGrammerSize, 0, (j + 1) *\n          reberGrammerSize - 1, 0), inputSymbol);\n      inputReber += inputSymbol;\n\n      if (embedded)\n        GenerateNextEmbeddedReber(transitions, inputReber, reberChoices);\n      else\n        GenerateNextReber(transitions, inputReber, reberChoices);\n\n      if (reberChoices.find(predictedSymbol) != std::string::npos)\n        reberError++;\n    }\n\n    if (reberError != (output.n_elem / reberGrammerSize))\n      error += 1;\n  }\n\n  error /= testReberGrammarCount;\n  BOOST_REQUIRE_LE(error, 0.2);\n}\n\n/**\n * Train the specified networks on a Reber grammar dataset.\n */\nBOOST_AUTO_TEST_CASE(ReberGrammarTest)\n{\n  LSTMLayer<> hiddenLayerLSTM(10);\n  ReberGrammarTestNetwork(hiddenLayerLSTM);\n}\n\n/**\n * Train the specified networks on an embedded Reber grammar dataset.\n */\nBOOST_AUTO_TEST_CASE(EmbeddedReberGrammarTest)\n{\n  LSTMLayer<> hiddenLayerLSTM(10);\n  ReberGrammarTestNetwork(hiddenLayerLSTM, true);\n}\n\n/*\n * This sample is a simplified version of Derek D. Monner's Distracted Sequence\n * Recall task, which involves 10 symbols:\n *\n * Targets: must be recognized and remembered by the network.\n * Distractors: never need to be remembered.\n * Prompts: direct the network to give an answer.\n *\n * A single trial consists of a temporal sequence of 10 input symbols. The first\n * 8 consist of 2 randomly chosen target symbols and 6 randomly chosen\n * distractor symbols in an random order. The remaining two symbols are two\n * prompts, which direct the network to produce the first and second target in\n * the sequence, in order.\n *\n * For more information, see the following paper.\n *\n * @code\n * @misc{Monner2012,\n *   author = {Monner, Derek and Reggia, James A},\n *   title = {A generalized LSTM-like training algorithm for second-order\n *   recurrent neural networks},\n *   year = {2012}\n * }\n * @endcode\n *\n * @param input The generated input sequence.\n * @param input The generated output sequence.\n */\nvoid GenerateDistractedSequence(arma::mat& input, arma::mat& output)\n{\n  input = arma::zeros<arma::mat>(10, 10);\n  output = arma::zeros<arma::mat>(3, 10);\n\n  arma::Col<size_t> index = arma::shuffle(arma::linspace<arma::Col<size_t> >(\n      0, 7, 8));\n\n  // Set the target in the input sequence and the corresponding targets in the\n  // output sequence by following the correct order.\n  for (size_t i = 0; i < 2; i++)\n  {\n    size_t idx = rand() % 2;\n    input(idx, index(i)) = 1;\n    output(idx, index(i) > index(i == 0) ? 9 : 8) = 1;\n  }\n\n  for (size_t i = 2; i < 8; i++)\n    input(2 + rand() % 6, index(i)) = 1;\n\n\n  // Set the prompts which direct the network to give an answer.\n  input(8, 8) = 1;\n  input(9, 9) = 1;\n\n  input.reshape(input.n_elem, 1);\n  output.reshape(output.n_elem, 1);\n}\n\n/**\n * Train the specified network and the construct distracted sequence recall\n * dataset.\n */\ntemplate<typename HiddenLayerType>\nvoid DistractedSequenceRecallTestNetwork(HiddenLayerType& hiddenLayer0)\n{\n  const size_t trainDistractedSequenceCount = 1000;\n  const size_t testDistractedSequenceCount = 1000;\n\n  arma::field<arma::mat> trainInput(1, trainDistractedSequenceCount);\n  arma::field<arma::mat> trainLabels(1, trainDistractedSequenceCount);\n  arma::field<arma::mat> testInput(1, testDistractedSequenceCount);\n  arma::field<arma::mat> testLabels(1, testDistractedSequenceCount);\n\n  // Generate the training data.\n  for (size_t i = 0; i < trainDistractedSequenceCount; i++)\n    GenerateDistractedSequence(trainInput(0, i), trainLabels(0, i));\n\n  // Generate the test data.\n  for (size_t i = 0; i < testDistractedSequenceCount; i++)\n    GenerateDistractedSequence(testInput(0, i), testLabels(0, i));\n\n  /*\n   * Construct a network with 10 input units, layerSize hidden units and 3\n   * output units. The hidden layer is connected to itself. The network\n   * structure looks like:\n   *\n   *  Input         Hidden        Output\n   * Layer(10)  Layer(layerSize)   Layer(3)\n   * +-----+       +-----+       +-----+\n   * |     |       |     |       |     |\n   * |     +------>|     +------>|     |\n   * |     |    ..>|     |       |     |\n   * +-----+    .  +--+--+       +-----+\n   *            .     .\n   *            .     .\n   *            .......\n   */\n  const size_t lstmSize = 4 * 10;\n  LinearLayer<> linearLayer0(10, lstmSize);\n  RecurrentLayer<> recurrentLayer0(10, lstmSize);\n\n  LinearLayer<> hiddenLayer(10, 3);\n  TanHLayer<> hiddenBaseLayer;\n\n  BinaryClassificationLayer classOutputLayer;\n\n  auto modules = std::tie(linearLayer0, recurrentLayer0, hiddenLayer0,\n                          hiddenLayer, hiddenBaseLayer);\n\n  RNN<decltype(modules), BinaryClassificationLayer, NguyenWidrowInitialization,\n      MeanSquaredErrorFunction> net(modules, classOutputLayer);\n\n  SGD<decltype(net)> opt(net, 0.04, 2, -200);\n\n  arma::mat inputTemp, labelsTemp;\n  for (size_t i = 0; i < 40; i++)\n  {\n    for (size_t j = 0; j < trainDistractedSequenceCount; j++)\n    {\n      inputTemp = trainInput.at(0, j);\n      labelsTemp = trainLabels.at(0, j);\n\n      net.Train(inputTemp, labelsTemp, opt);\n    }\n  }\n\n  double error = 0;\n\n  // Ask the network to predict the targets in the given sequence at the\n  // prompts.\n  for (size_t i = 0; i < testDistractedSequenceCount; i++)\n  {\n    arma::mat output;\n    arma::mat input = testInput.at(0, i);\n\n    net.Predict(input, output);\n\n    if (arma::accu(arma::abs(testLabels.at(0, i) - output)) != 0)\n      error += 1;\n  }\n\n  error /= testDistractedSequenceCount;\n\n  // Can we reproduce the results from the paper. They provide an 95% accuracy\n  // on a test set of 1000 randomly selected sequences.\n  // Ensure that this is within tolerance, which is at least as good as the\n  // paper's results (plus a little bit for noise).\n  BOOST_REQUIRE_LE(error, 0.3);\n}\n\n/**\n * Train the specified networks on the Derek D. Monner's distracted sequence\n * recall task.\n */\nBOOST_AUTO_TEST_CASE(DistractedSequenceRecallTest)\n{\n  LSTMLayer<> hiddenLayerLSTMPeephole(10, true);\n  DistractedSequenceRecallTestNetwork(hiddenLayerLSTMPeephole);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "40d162c6fa80174d5eadbec1478b091366b76112", "size": 18592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/recurrent_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": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T11:59:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:18.000Z", "max_issues_repo_path": "src/mlpack/tests/recurrent_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/recurrent_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": 30.9866666667, "max_line_length": 82, "alphanum_fraction": 0.6309703098, "num_tokens": 5266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5451019899706454}}
{"text": "#ifndef UTILITIES\n#define UTILITIES\n\n#include <math.h>\n#include <stdlib.h>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <iostream>\n#include <algorithm>\n#include <map>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/symmetric.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/legendre.hpp>\n#include <complex>\n#include \"gsl/gsl_sf_gamma.h\"\n#include \"gsl/gsl_sf_result.h\"\n#include \"gsl/gsl_complex_math.h\"\n\nnamespace utilities {\n  using namespace boost::numeric::ublas;\n\n  const double PI = 3.14159265359;\n  const double C = 299792458;//m/s\n  const double EMASSC2 = 510.9989461;//keV\n  const double PMASSC2 = 938272.046;//keV\n  const double NMASSC2 = 939565.4133;//keV\n  const double ALPHAMASSC2 = 3727379.508;//keV\n  const double FINESTRUCTURE = 0.0072973525664;\n  const double E = 2.718281828459045;\n  const double HBAR = 6.58211889e-16;//ev*s\n  const double a_CORR = -1.0;\n\n  const std::string atoms[] = {\"H\", \"He\", \"Li\", \"Be\", \"B\", \"C\", \"N\", \"O\", \"F\", \"Ne\", \"Na\", \"Mg\", \"Al\", \"Si\", \"P\", \"S\", \"Cl\", \"Ar\", \"K\", \"Ca\", \"Sc\", \"Ti\", \"V\", \"Cr\", \"Mn\", \"Fe\", \"Co\", \"Ni\", \"Cu\", \"Zn\", \"Ga\", \"Ge\", \"As\", \"Se\", \"Br\", \"Kr\", \"Rb\", \"Sr\", \"Y\", \"Zr\", \"Nb\", \"Mo\", \"Tc\", \"Ru\", \"Rh\", \"Pd\", \"Ag\", \"Cd\", \"In\", \"Sn\", \"Sb\", \"Te\", \"I\", \"Xe\", \"Cs\", \"Ba\", \"La\", \"Ce\", \"Pr\", \"Nd\", \"Pm\", \"Sm\", \"Eu\", \"Gd\", \"Tb\", \"Dy\", \"Ho\", \"Er\", \"Tm\", \"Yb\", \"Lu\", \"Hf\", \"Ta\", \"W\", \"Re\", \"Os\", \"Ir\", \"Pt\", \"Au\", \"Hg\", \"Tl\", \"Pb\", \"Bi\", \"Po\", \"At\", \"Rn\", \"Fr\", \"Ra\", \"Ac\", \"Th\", \"Pa\", \"U\", \"Np\", \"Pu\", \"Am\", \"Cm\", \"Bk\", \"Cf\", \"Es\", \"Fm\", \"Md\", \"No\", \"Lr\", \"Rf\", \"Db\", \"Sg\", \"Bh\", \"Hs\", \"Mt\"};\n\n  inline vector<double> RandomDirection () {\n    double z, phi;\n    vector<double> v(3);\n\n    z = rand() / (double)RAND_MAX * 2. - 1.;\n    phi = rand() / (double)RAND_MAX * 2. * PI;\n\n    v(0) = std::sqrt(1.-z*z)*std::cos(phi);\n    v(1) = std::sqrt(1.-z*z)*std::sin(phi);\n    v(2) = z;\n\n    return v;\n  };\n\n  inline double Random(double begin, double end) { return rand() / (double)RAND_MAX * (end - begin) + begin; };\n\n  inline double RandomFromDistribution(std::vector<std::vector<double> >& pd) {\n    double begin = pd[0][0];\n    double end = pd[pd.size()-1][0];\n    double stepSize = pd[1][0] - pd[0][0];\n    double max = 0.;\n\n    for (std::vector<std::vector<double> >::size_type i = 0; i != pd.size(); i++) {\n      if (pd[i][1] > max) {\n        max = pd[i][1];\n      }\n    }\n\n    double r = 0.;\n    double q = 0.;\n    do {\n      r = rand() / (double)RAND_MAX;\n      q = rand() / (double)RAND_MAX * max;\n    } while (q > pd[r*pd.size()][1]);\n    return r*(end - begin) + begin;\n  }\n\n  inline double GetSpeed(double energy, double massc2) {\n    double gamma = energy/massc2 + 1.;\n    return std::sqrt(1.-1./(gamma*gamma))*C;\n  }\n\n  inline double GetNorm(const vector<double>& v) {\n    double sum = 0.;\n    for (vector<double>::size_type i = 0; i != v.size(); i++) {\n      sum+=v[i]*v[i];\n    }\n    return std::sqrt(sum);\n  }\n\n  inline double FourDimDot(vector<double>& a, vector<double>& b) {\n    //Mostly minus convention\n    return a[0]*b[0]-(a[1]*b[1]+a[2]*b[2]+a[3]*b[3]);\n  }\n\n  inline double CalculateXiBetaDecay(double& cs, double& ct, double& cv, double& ca, double& mf, double& mgt) {\n    return mf*mf*(2.*cs*cs+2.*cv*cv)+mgt*mgt*(2.*ct*ct+2.*ca*ca);\n  }\n\n  inline double CalculateBetaNeutrinoAsymmetry(double cs, double ct, double cv, double ca, double mf, double mgt) {\n    return (mf*mf*(-2.*cs*cs+2.*cv*cv)+mgt*mgt/3.*(2.*ct*ct-2.*ca*ca))/CalculateXiBetaDecay(cs, ct, cv, ca, mf, mgt);\n  }\n\n  inline vector<double> NormaliseVector(const vector<double>& v) {\n    vector<double> newV (v);\n    double norm = GetNorm(v);\n    if (norm != 0) {\n      return newV/norm;\n    }\n    return v;\n  }\n\n  inline double LambdaKinematic(double x, double y, double z) {\n    return x*x+y*y+z*z-2*x*y-2*y*z-2*x*z;\n  }\n\n  inline double PhaseSpace(double W, double W0) {\n    return std::sqrt(W*W-1.)*W*std::pow(W0-W, 2.);\n  }\n\n  inline double SimpleFermiFunction(double Z, double v) {\n    double nu = Z*FINESTRUCTURE/v*C;\n    return 2.*PI*nu/(1.-std::pow(E, -2.*PI*nu));\n  }\n\n  inline double FermiFunction(double Z, double W, double R) {\n    double gamma = std::sqrt(1.-(FINESTRUCTURE*Z)*(FINESTRUCTURE*Z));\n    double p = std::sqrt(W*W-1);\n    double first = 2*(gamma+1);\n    //the second term will be incorporated in the fifth\n    //double second = 1/pow(gsl_sf_gamma(2*gamma+1),2);\n    double third = std::pow(2*p*R,2*(gamma-1));\n    double fourth = std::exp(M_PI*FINESTRUCTURE*Z*W/p);\n\n    //the fifth is a bit tricky\n    //we use the complex gamma function from GSL\n    gsl_sf_result magn;\n    gsl_sf_result phase;\n    gsl_sf_lngamma_complex_e(gamma, FINESTRUCTURE*Z*W/p,&magn,&phase);\n    //now we have what we want in magn.val\n\n    //but we incorporate the second term here as well\n    double fifth = std::exp(2*(magn.val-gsl_sf_lngamma(2*gamma+1)));\n\n    return first*third*fourth*fifth;\n  }\n\n  inline double ApproximateRadius(double A) {\n    return (1.15+1.8*std::pow(A, -2./3.)-1.2*std::pow(A, -4./3.))*EMASSC2*1000./HBAR/C*std::pow(A, 1./3.);\n  }\n\n  inline double GetSpectrumHeight(double Z, double A, double Q, double E, bool advancedFermi) {\n    double W = E/EMASSC2+1.;\n    double W0 = Q/EMASSC2+1.;\n    double R = ApproximateRadius(A);\n    if (advancedFermi) {\n      return PhaseSpace(W, W0)*FermiFunction(Z, W, R);\n    }\n    else {\n      return PhaseSpace(W, W0)*SimpleFermiFunction(Z, GetSpeed(E, EMASSC2));\n    }\n  }\n\n  inline std::vector<std::vector<double> >* GenerateBetaSpectrum(double Z, double A, double Q, bool advancedFermi) {\n    std::vector<std::vector<double> >* dist = new std::vector<std::vector<double> >();\n    double stepSize = 1.0;\n\n    double currentEnergy = stepSize;\n    while(currentEnergy <= Q) {\n      double s = GetSpectrumHeight(Z, A, Q, currentEnergy, advancedFermi);\n      std::vector<double> pair;\n      pair.push_back(currentEnergy);\n      pair.push_back(s);\n      dist->push_back(pair);\n      currentEnergy+=stepSize;\n    }\n    return dist;\n  }\n\n  inline vector<double> CrossProduct(vector<double> first, vector<double> second) {\n    vector<double> v (3);\n\n    v(0) = first(1)*second(2) - first(2)*second(1);\n    v(1) = first(2)*second(0) - first(0)*second(2);\n    v(2) = first(0)*second(1) - first(1)*second(0);\n\n    return v;\n  }\n\n  inline vector<double> RotateAroundVector(vector<double>& initial, vector<double>& axis, double angle) {\n    vector<double> vect(3);\n    double u = axis[0];\n    double v = axis[1];\n    double w = axis[2];\n    double x = initial[0];\n    double y = initial[1];\n    double z = initial[2];\n\n    double c = std::cos(angle);\n    double s = std::sin(angle);\n\n    vect(0) = u*(u*x+v*y+w*z)*(1.-c)+x*c+(-w*y+v*z)*s;\n    vect(1) = v*(u*x+v*y+w*z)*(1.-c)+y*c+(w*x-u*z)*s;\n    vect(2) = w*(u*x+v*y+w*z)*(1.-c)+z*c+(-v*x+u*y)*s;\n\n    return vect;\n  }\n\n  inline vector<double> GetParticleDirection(vector<double>& dir2, std::vector<double>& A) {\n    dir2 = NormaliseVector(dir2);\n\n    std::vector<std::vector<double> > dist;\n    double stepSize = PI/180;\n    double currentAngle = 0.;\n\n    while (currentAngle <= PI) {\n      std::vector<double> pair;\n      pair.push_back(currentAngle);\n      double W = 0.;\n      for (std::vector<double>::size_type i = 0; i != A.size(); i++) {\n        W+=A[i]*boost::math::legendre_p(i, std::cos(currentAngle));\n      }\n      pair.push_back(W);\n      dist.push_back(pair);\n      currentAngle+=stepSize;\n    }\n\n    double theta = 1.-RandomFromDistribution(dist)/PI;\n    theta = std::acos(2*theta-1.);\n    //std::cout << theta;\n    vector<double> perp = CrossProduct(dir2, RandomDirection());\n    vector<double> dir = RotateAroundVector(dir2, perp, theta);\n    return dir;\n  }\n\n  inline vector<double> GetParticleDirection(std::vector<vector<double> >& dirs, std::vector<std::vector<double> >& A) {\n    vector<double> dir (3);\n    //TODO\n    return dir;\n  }\n\n  inline vector<double> LorentzBoost(vector<double>& velocity, vector<double>& v) {\n    double speed = GetNorm(velocity);\n    double beta = speed;\n    double gamma = 1./std::sqrt(1.-std::pow(speed, 2.));\n\n    vector<double> dir = NormaliseVector(velocity);\n\n    symmetric_matrix<double, upper> boost(4,4);\n    boost(0, 0) = gamma;\n    boost(0, 1) = -gamma*beta*dir[0];\n    boost(0, 2) = -gamma*beta*dir[1];\n    boost(0, 3) = -gamma*beta*dir[2];\n    boost(1, 1) = 1.+(gamma-1.)*dir[0]*dir[0];\n    boost(1, 2) = (gamma-1.)*dir[0]*dir[1];\n    boost(1, 3) = (gamma-1.)*dir[0]*dir[2];\n    boost(2, 2) = 1.+(gamma-1.)*dir[1]*dir[1];\n    boost(2, 3) = (gamma-1.)*dir[1]*dir[2];\n    boost(3, 3) = 1.+(gamma-1.)*dir[2]*dir[2];\n\n    return prod(boost, v);\n  }\n\n  inline double GetApproximateMass(int Z, int A) {\n    double b = 15.5*A-16.8*std::pow(A, 2.0/3.0)- 0.72*Z*(Z-1)*std::pow(A, -1.0/3.0) - 23.*std::pow(A-2*Z, 2.)/A;\n    if (A%2 == 0) {\n      double asym = 34.*std::pow(A, -3.0/4.0);\n      if (Z%2 == 0) {\n        b+=asym;\n      }\n      else {\n        b-=asym;\n      }\n    }\n    return Z*PMASSC2+(A-Z)*NMASSC2-b;\n  }\n\n  inline std::vector<std::vector<double> > ReadDistribution(const char * filename) {\n    std::ifstream distReader(filename, std::ifstream::in);\n\n    if (!distReader.is_open()) {\n      std::cout << \"Error: Could not find file \" << filename << std::endl;\n    }\n    std::vector<std::vector<double> > dist;\n\n    double x, y;\n    while (distReader >> x >> y) {\n      std::vector<double> pair;\n      pair.push_back(x);\n      pair.push_back(y);\n      dist.push_back(pair);\n    }\n   return dist;\n  }\n}\n#endif\n", "meta": {"hexsha": "5dc45430aeee85d60feef3c2ae4f1933957f90dc", "size": 9584, "ext": "hh", "lang": "C++", "max_stars_repo_path": "source/include/Utilities.hh", "max_stars_repo_name": "leenderthayen/CRADLE", "max_stars_repo_head_hexsha": "8b7979a201c6d95abbc00cf44159b8fa577a17f5", "max_stars_repo_licenses": ["MIT"], "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/include/Utilities.hh", "max_issues_repo_name": "leenderthayen/CRADLE", "max_issues_repo_head_hexsha": "8b7979a201c6d95abbc00cf44159b8fa577a17f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-04-22T13:07:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T04:49:09.000Z", "max_forks_repo_path": "source/include/Utilities.hh", "max_forks_repo_name": "leenderthayen/CRADLE", "max_forks_repo_head_hexsha": "8b7979a201c6d95abbc00cf44159b8fa577a17f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T19:03:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T19:03:55.000Z", "avg_line_length": 32.4881355932, "max_line_length": 671, "alphanum_fraction": 0.5914023372, "num_tokens": 3305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616712, "lm_q2_score": 0.6187804478040617, "lm_q1q2_score": 0.5450200025908764}}
{"text": "/**\n * project  DESCARTES\n *\n * @file     EigenDenseMatrixMatrixProduct.hxx\n *\n * @author Laurent PLAGNE\n *\n * @par Modifications\n * - author date object\n *   \n * (c) Copyright EDF R&D 2001-2012\n */\n#ifndef __LEGOLAS_EIGENDENSEMATRIXMATRIXPRODUCT_HXX__\n#define __LEGOLAS_EIGENDENSEMATRIXMATRIXPRODUCT_HXX__\n#include  <vector>\n\n#include \"UTILITES.hxx\"\n#include <Eigen/Core>\n\n\nnamespace Legolas{\n\n  // C=A*B\n\n\n  class EigenDenseMatrixMatrixProduct{\n  public:\n\n    template <class MATRIX>\n    static inline void apply(const MATRIX & A , \n\t\t\t     const MATRIX & B ,\n\t\t\t     MATRIX & C)\n    {\n      //C mn = Amk * Bkn\n\n      typedef typename MATRIX::RealType RealType;\n      \n      int M=A.nrows();\n      int K=A.ncols();\n      int N=B.ncols();\n\n      assert(A.ncols()==B.nrows());\n      assert(A.nrows()==C.nrows());\n      assert(B.ncols()==C.ncols());\n      \n      typedef Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic > eigen_matrix;\n\n      eigen_matrix Ae,Be,Ce;\n      Ae.resize(M,K);\n      for (int i=0 ; i<M ; i++)\n\tfor (int j=0 ; j<K ; j++)\t\n\t  Ae(i,j)=A.sparseGetElement(i,j);\n\n      Be.resize(K,N);\n      for (int i=0 ; i<K ; i++)\n\tfor (int j=0 ; j<N ; j++)\t\n\t  Be(i,j)=B.sparseGetElement(i,j);\n\n      Ce.resize(M,N);\n      Ce=Ae*Be;\n\n      for (int i=0 ; i<M ; i++)\n\tfor (int j=0 ; j<N ; j++)\t\n\t  C.sparseGetElement(i,j)=Ce(i,j);\n\n      \n    }\n  \n  };\n\n}\n\n#endif\n", "meta": {"hexsha": "2233f878833664eca815976fdbcc72b7c45988c3", "size": 1377, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "Legolas/Algorithm/EigenDenseMatrixMatrixProduct.hxx", "max_stars_repo_name": "LaurentPlagne/Legolas", "max_stars_repo_head_hexsha": "fdf533528baf7ab5fcb1db15d95d2387b3e3723c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Legolas/Algorithm/EigenDenseMatrixMatrixProduct.hxx", "max_issues_repo_name": "LaurentPlagne/Legolas", "max_issues_repo_head_hexsha": "fdf533528baf7ab5fcb1db15d95d2387b3e3723c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Legolas/Algorithm/EigenDenseMatrixMatrixProduct.hxx", "max_forks_repo_name": "LaurentPlagne/Legolas", "max_forks_repo_head_hexsha": "fdf533528baf7ab5fcb1db15d95d2387b3e3723c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-11T14:43:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-11T14:43:25.000Z", "avg_line_length": 18.6081081081, "max_line_length": 84, "alphanum_fraction": 0.5744371823, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5450199940790765}}
{"text": "// TRENTO: Reduced Thickness Event-by-event Nuclear Topology\n// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland\n// MIT License\n\n#include \"event.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <complex>\n\n#include <boost/program_options/variables_map.hpp>\n\n#include \"nucleus.h\"\n\nnamespace trento {\n\nnamespace {\n\ntypedef std::complex<double> complex_t;\n\nconstexpr double TINY = 1e-12;\n\n// Generalized mean for p > 0.\n// M_p(a, b) = (1/2*(a^p + b^p))^(1/p)\ninline double positive_pmean(double p, double a, double b) {\n  return std::pow(.5*(std::pow(a, p) + std::pow(b, p)), 1./p);\n}\n\n// Generalized mean for p < 0.\n// Same as the positive version, except prevents division by zero.\ninline double negative_pmean(double p, double a, double b) {\n  if (a < TINY || b < TINY)\n    return 0.;\n  return positive_pmean(p, a, b);\n}\n\n// Generalized mean for p == 0.\ninline double geometric_mean(double a, double b) {\n  return std::sqrt(a*b);\n}\n\ninline int get_max_eccentricity_m(const std::vector<EventQuantity>& quantities) {\n  int max_m = -1;\n  bool foundmn = false;\n\n  for (auto qty : quantities) {\n    if (EventQuantity_GetClass(qty) == EventEpsilon_mn ||\n        EventQuantity_GetClass(qty) == EventEpsilonArg_mn)\n    {\n      int m = EventQuantity_GetSubscript1(qty);\n      int n = EventQuantity_GetSubscript2(qty);\n\n      max_m = std::max(max_m, m);\n      foundmn = (foundmn || (m != n));\n    }\n  }\n\n  return (foundmn ? max_m : -1);\n}\n\ninline int get_max_eccentricity_n(const std::vector<EventQuantity>& quantities) {\n  int max_n = -1;\n\n  for (auto qty : quantities) {\n    if (EventQuantity_GetClass(qty) == EventEpsilon_mn ||\n        EventQuantity_GetClass(qty) == EventEpsilonArg_mn)\n    {\n      int n = EventQuantity_GetSubscript2(qty);\n      max_n = std::max(max_n, n);\n    }\n  }\n\n  return max_n;\n}\n\n}  // unnamed namespace\n\nEvent::Event(const VarMap& var_map)                                    // this constructor assumes that only quantities being displayed need to\n  : Event(var_map, var_map[\"columns\"].as<EventQuantityList>().values)  //   be computed; retained for code compatibility but should not be used\n{ }\n\n// Determine the grid parameters like so:\n//   1. Read and set step size from the configuration.\n//   2. Read grid max from the config, then set the number of steps as\n//      nsteps = ceil(2*max/step).\n//   3. Set the actual grid max as max = nsteps*step/2.  Hence if the step size\n//      does not evenly divide the config max, the actual max will be marginally\n//      larger (by at most one step size).\nEvent::Event(\n  const VarMap& var_map,\n  const std::vector<EventQuantity>& required_quantities)\n    : norm_(var_map[\"normalization\"].as<double>()),\n      dxy_(var_map[\"grid-step\"].as<double>()),\n      nsteps_(std::ceil(2.*var_map[\"grid-max\"].as<double>()/dxy_)),\n      xymax_(.5*nsteps_*dxy_),\n      TA_(boost::extents[nsteps_][nsteps_]),\n      TB_(boost::extents[nsteps_][nsteps_]),\n      TR_(boost::extents[nsteps_][nsteps_]),\n      max_eccentricity_m_(get_max_eccentricity_m(required_quantities)),\n      max_eccentricity_n_(get_max_eccentricity_n(required_quantities)) {\n  // Choose which version of the generalized mean to use based on the\n  // configuration.  The possibilities are defined above.  See the header for\n  // more information.\n  auto p = var_map[\"reduced-thickness\"].as<double>();\n\n  if (std::fabs(p) < TINY) {\n    compute_reduced_thickness_ = [this]() {\n      compute_reduced_thickness(geometric_mean);\n    };\n  } else if (p > 0.) {\n    compute_reduced_thickness_ = [this, p]() {\n      compute_reduced_thickness(\n        [p](double a, double b) { return positive_pmean(p, a, b); });\n    };\n  } else {\n    compute_reduced_thickness_ = [this, p]() {\n      compute_reduced_thickness(\n        [p](double a, double b) { return negative_pmean(p, a, b); });\n    };\n  }\n}\n\nvoid Event::compute(const Nucleus& nucleusA, const Nucleus& nucleusB,\n                    const NucleonCommon& nucleon_common) {\n  // Reset npart; compute_nuclear_thickness() increments it.\n  npart_ = 0;\n  compute_nuclear_thickness(nucleusA, nucleon_common, TA_);\n  compute_nuclear_thickness(nucleusB, nucleon_common, TB_);\n  compute_reduced_thickness_();\n  compute_observables();\n\n  failuresA_ = nucleusA.failures();\n  failuresB_ = nucleusB.failures();\n}\n\nnamespace {\n\n// Limit a value to a range.\n// Used below to constrain grid indices.\ntemplate <typename T>\ninline const T& clip(const T& value, const T& min, const T& max) {\n  if (value < min)\n    return min;\n  if (value > max)\n    return max;\n  return value;\n}\n\n}  // unnamed namespace\n\nvoid Event::compute_nuclear_thickness(\n    const Nucleus& nucleus, const NucleonCommon& nucleon_common, Grid& TX) {\n  // Construct the thickness grid by looping over participants and adding each\n  // to a small subgrid within its radius.  Compared to the other possibility\n  // (grid cells as the outer loop and participants as the inner loop), this\n  // reduces the number of required distance-squared calculations by a factor of\n  // ~20 (depending on the nucleon size).  The Event unit test verifies that the\n  // two methods agree.\n\n  // Wipe grid with zeros.\n  std::fill(TX.origin(), TX.origin() + TX.num_elements(), 0.);\n\n  // Deposit each participant onto the grid.\n  for (const auto& nucleon : nucleus) {\n    if (!nucleon.is_participant())\n      continue;\n\n    ++npart_;\n\n    // Get nucleon subgrid boundary {xmin, xmax, ymin, ymax}.\n    const auto boundary = nucleon_common.boundary(nucleon);\n\n    // Determine min & max indices of nucleon subgrid.\n    int ixmin = clip(static_cast<int>((boundary[0]+xymax_)/dxy_), 0, nsteps_-1);\n    int ixmax = clip(static_cast<int>((boundary[1]+xymax_)/dxy_), 0, nsteps_-1);\n    int iymin = clip(static_cast<int>((boundary[2]+xymax_)/dxy_), 0, nsteps_-1);\n    int iymax = clip(static_cast<int>((boundary[3]+xymax_)/dxy_), 0, nsteps_-1);\n\n    // Add profile to grid.\n    for (auto iy = iymin; iy <= iymax; ++iy) {\n      for (auto ix = ixmin; ix <= ixmax; ++ix) {\n        TX[iy][ix] += nucleon_common.thickness(\n          nucleon, (ix+.5)*dxy_ - xymax_, (iy+.5)*dxy_ - xymax_\n        );\n      }\n    }\n  }\n}\n\ntemplate <typename GenMean>\nvoid Event::compute_reduced_thickness(GenMean gen_mean) {\n  double sum = 0.;\n  double ixcm = 0.;\n  double iycm = 0.;\n\n  for (int iy = 0; iy < nsteps_; ++iy) {\n    for (int ix = 0; ix < nsteps_; ++ix) {\n      auto t = norm_ * gen_mean(TA_[iy][ix], TB_[iy][ix]);\n      TR_[iy][ix] = t;\n      sum += t;\n      // Center of mass grid indices.\n      // No need to multiply by dxy since it would be canceled later.\n      ixcm += t * static_cast<double>(ix);\n      iycm += t * static_cast<double>(iy);\n    }\n  }\n\n  multiplicity_ = dxy_ * dxy_ * sum;\n  ixcm_ = ixcm / sum;\n  iycm_ = iycm / sum;\n}\n\nvoid Event::compute_en(int max_n) {\n  // Compute eccentricity.\n  if (max_n < MinEccentricityHarmonic || max_n > MaxEccentricityHarmonic)\n    throw std::invalid_argument{\"max_n\"};\n\n  // Simple helper class for use in the following loop.\n  struct EccentricityAccumulator {\n    complex_t z = 0.;\n    double wt = 0.;  // weight\n    double finish() const  // compute final eccentricity\n    { return std::abs(z) / std::fmax(wt, TINY); }\n    double arg() const\n    { return std::arg(z); }\n  } en[NumEccentricityHarmonics];\n\n  for (int iy = 0; iy < nsteps_; ++iy) {\n    auto y = static_cast<double>(iy) - iycm_;\n    auto y2 = y*y;\n\n    for (int ix = 0; ix < nsteps_; ++ix) {\n      const auto& t = TR_[iy][ix];\n      if (t < TINY)\n        continue;\n\n      // Compute `r` relative to the CM.\n      auto x = static_cast<double>(ix) - ixcm_;\n      auto r = std::sqrt(x*x + y2);\n\n      // The eccentricity harmonics are weighted averages of r^n*exp(i*n*phi)\n      // over the entropy profile (reduced thickness).  Note that:\n      //\n      //   r^n * exp(i*n*phi)  =  r^n * exp(i*phi)^n\n      //                       =  (r*exp(i*phi))^n\n      //                       =  (x + i*y)^n\n      //\n      // The Event unit test verifies that this method agrees with the\n      // trigonometric function method.\n      auto z    = complex_t{x, y};\n      auto enz  = t * z;\n      auto enwt = t * r;\n\n      for (int i = MinEccentricityHarmonic; i <= max_n; ++i) {\n        en[i - MinEccentricityHarmonic].z  += (enz  *= z);\n        en[i - MinEccentricityHarmonic].wt += (enwt *= r);\n      }\n    }\n  }\n\n  for (int n = MinEccentricityHarmonic; n <= max_n; ++n) {\n    eccentricity_[n] = eccentricity_mn_[std::make_pair(n,n)] = en[n - MinEccentricityHarmonic].finish();\n    eccentricity_mn_arg_[std::make_pair(n,n)] = en[n - MinEccentricityHarmonic].arg();\n  }\n}\n\nvoid Event::compute_emn(int max_m, int max_n) {\n  // Compute eccentricity.\n  if (max_m < MinEccentricityHarmonic || max_m > MaxEccentricityHarmonic)\n    throw std::invalid_argument{\"max_m\"};\n\n  if (max_n < MinEccentricityHarmonic || max_n > MaxEccentricityHarmonic)\n    throw std::invalid_argument{\"max_n\"};\n\n  // Simple helper class for use in the following loop.\n  complex_t emn[NumEccentricityHarmonics][NumEccentricityHarmonics] = { };  // important: initializes to zeroes\n  double weights[NumEccentricityHarmonics] = { };\n\n  for (int iy = 0; iy < nsteps_; ++iy) {\n    auto y = static_cast<double>(iy) - iycm_;\n    auto y2 = y*y;\n\n    for (int ix = 0; ix < nsteps_; ++ix) {\n      const auto& t = TR_[iy][ix];\n      if (t < TINY)\n        continue;\n\n      // Compute `r` relative to the CM.\n      auto x = static_cast<double>(ix) - ixcm_;\n      auto r = std::sqrt(x*x + y2);\n\n      auto wt = t * r;  // initialize to `(t * r)` and multiply `r` again at top of `m` loop, since `m` starts at 2\n      for (int m = MinEccentricityHarmonic; m <= max_m; ++m)       // (note: `MinEccentricityHarmonic = 2` assumed)\n        weights[m - MinEccentricityHarmonic] += (wt *= r);\n\n      // The eccentricity harmonics are weighted averages of `r^m*exp(i*n*phi)`\n      // over the entropy profile (reduced thickness).  Note that:\n      //\n      //   r^m * exp(i*n*phi)  =  r^m * exp(i*phi)^n\n      //                       =  r^(m-n) * (r*exp(i*phi))^n\n      //                       =  r^(m-n) * (x + i*y)^n\n      //\n      auto z = complex_t{x, y};\n      auto zfactor = t * z;  // initialize to `(t * z)` and multiply `z` again at top of `n` loop, since `n` starts at 2\n\n      for (int n = MinEccentricityHarmonic; n <= MaxEccentricityHarmonic; n++) {  // (note: `MinEccentricityHarmonic = 2` assumed)\n        zfactor *= z;\n\n        double rfactor;\n\n        if (r > TINY) {  // ignore this pixel if `r ~ 0` here; it would be nugatory in an integral but causes problems for our sum\n          rfactor = 1.;  // initialize to 1 and divide `r` at top of `m` loop, since `(m - n)` starts at -1 and counts down\n\n          for (int m = n - 1; m >= MinEccentricityHarmonic; --m) {\n            rfactor /= r;\n            emn[m - MinEccentricityHarmonic][n - MinEccentricityHarmonic] += rfactor * zfactor;\n          }\n\n          rfactor = 1.;  // now initialize to 1 and multiply `r` at bottom of `m` loop, since `(m - n)` now starts at 0 and counts up\n\n          for (int m = n; m <= MaxEccentricityHarmonic; ++m) {\n            emn[m - MinEccentricityHarmonic][n - MinEccentricityHarmonic] += rfactor * zfactor;\n            rfactor *= r;\n          }\n        }\n      }\n    }\n  }\n\n  for (int m = MinEccentricityHarmonic; m <= max_m; ++m) {\n    double wt = std::fmax(weights[m - MinEccentricityHarmonic], TINY);\n\n    for (int n = MinEccentricityHarmonic; n <= max_n; ++n) {\n      eccentricity_mn_[std::make_pair(m,n)]     = std::abs(emn[m - MinEccentricityHarmonic][n - MinEccentricityHarmonic]) / wt;\n      eccentricity_mn_arg_[std::make_pair(m,n)] = std::arg(emn[m - MinEccentricityHarmonic][n - MinEccentricityHarmonic]);\n    }\n\n    if (m <= max_n)  // also update `eccentricity_` for `m == n` if applicable\n      eccentricity_[m] = std::abs(emn[m - MinEccentricityHarmonic][m - MinEccentricityHarmonic]) / wt;\n  }\n}\n\nvoid Event::compute_observables() {\n  if (max_eccentricity_n_ >= 0) {\n    if (max_eccentricity_m_ >= 0)\n      compute_emn(max_eccentricity_m_, max_eccentricity_n_);\n    else compute_en(max_eccentricity_n_);\n  }\n}\n\n}  // namespace trento\n", "meta": {"hexsha": "d9ebcfb762a1f311dad9cc0f5ee3e082fef536e1", "size": 12090, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/event.cxx", "max_stars_repo_name": "dereksoeder/trento", "max_stars_repo_head_hexsha": "4645d2cd5ee68c0e7c103e43f148bd0053622839", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/event.cxx", "max_issues_repo_name": "dereksoeder/trento", "max_issues_repo_head_hexsha": "4645d2cd5ee68c0e7c103e43f148bd0053622839", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/event.cxx", "max_forks_repo_name": "dereksoeder/trento", "max_forks_repo_head_hexsha": "4645d2cd5ee68c0e7c103e43f148bd0053622839", "max_forks_repo_licenses": ["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.3465909091, "max_line_length": 143, "alphanum_fraction": 0.629611249, "num_tokens": 3625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616712, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5450199902066832}}
{"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    using std::cout;\n    using std::endl;\n\n    MatrixXd apple = MatrixXd::Zero(1, 1);\n    MatrixXd apple_num = MatrixXd::Zero(1, 1);\n    MatrixXd orange = MatrixXd::Zero(1, 1);\n    MatrixXd orange_num = MatrixXd::Zero(1, 1);\n    MatrixXd tax = MatrixXd::Zero(1, 1);\n    MatrixXd apple_price, orange_price, all_price, price;\n\n    MatrixXd dprice = MatrixXd::Ones(1, 1);\n    MatrixXd dapple_price, dorange_price, dall_price, dtax, dapple_num, dorange_num, dapple, dorange;\n\n    apple(0) = 100;\n    apple_num(0) = 2;\n    orange(0) = 150;\n    orange_num(0) = 3;\n    tax(0) = 1.1;\n\n    //layer\n    MulLayer mul_apple_layer, mul_orange_layer, mul_tax_layer;\n    AddLayer add_apple_orange_layer;\n\n    // forward\n    apple_price = mul_apple_layer.forward(apple, apple_num);\n    orange_price = mul_orange_layer.forward(orange, orange_num);\n    all_price = add_apple_orange_layer.forward(apple_price, orange_price);\n    price = mul_tax_layer.forward(all_price, tax);\n\n    // backward\n    mul_tax_layer.backward(dprice, dall_price, dtax);\n    add_apple_orange_layer.backward(dall_price, dapple_price, dorange_price);\n    mul_orange_layer.backward(dorange_price, dorange, dorange_num);\n    mul_apple_layer.backward(dapple_price, dapple, dapple_num);\n\n    cout << \"price: \" << price << endl;\n    cout << \"dapple_num: \" << dapple_num << endl;\n    cout << \"dapple: \" << dapple << endl;\n    cout << \"dorange_num: \" << dorange_num << endl;\n    cout << \"dorange: \" << dorange << endl;\n    cout << \"dtax: \" << dtax << endl;\n\n    return 0;    \n}", "meta": {"hexsha": "420eb093b82aa59ed28a0b3330123eefaa628f18", "size": 1675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch5/apple_cal_graph.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/apple_cal_graph.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/apple_cal_graph.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": 32.2115384615, "max_line_length": 101, "alphanum_fraction": 0.6764179104, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5450199902066831}}
{"text": "//\n// Expansion Hunter\n// Copyright 2016-2019 Illumina, Inc.\n// 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//\n\n#include \"genotyping/AlleleChecker.hh\"\n\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n\n#include <numeric>\n\nnamespace ehunter\n{\n\nnamespace\n{\ndouble poissonLogPmf(double lambda, double count)\n{\n    return count * log(lambda) - lambda - boost::math::lgamma(count + 1);\n}\n\ndouble logBeta(int a, int b) { return boost::math::lgamma(a) + boost::math::lgamma(b) - boost::math::lgamma(a + b); }\n\ndouble logBinomCoef(int n, int k) { return -boost::math::log1p(n) - logBeta(n - k + 1, k + 1); }\n\ndouble binomLogPmf(int n, double p, int count)\n{\n    return logBinomCoef(n, count) + count * log(p) + (n - count) * boost::math::log1p(-p);\n}\n\n}\n\nAlleleCheckSummary AlleleChecker::check(double haplotypeDepth, int targetAlleleCount, int otherAlleleCount) const\n{\n    if (haplotypeDepth <= 0)\n    {\n        throw std::runtime_error(\"Haplotype depth must be positive\");\n    }\n\n    if (targetAlleleCount < 0 || otherAlleleCount < 0)\n    {\n        throw std::runtime_error(\"Negative read counts are not allowed\");\n    }\n\n    const int totalReadCount = targetAlleleCount + otherAlleleCount;\n    const double ll0 = (totalReadCount > 0) ? binomLogPmf(totalReadCount, errorRate_, targetAlleleCount) : 0;\n    const double ll1 = poissonLogPmf(haplotypeDepth, targetAlleleCount);\n\n    AlleleStatus status = AlleleStatus::kUncertain;\n    double logLikelihoodRatio = (ll1 - ll0) / log(10);\n    if (logLikelihoodRatio < -log10(likelihoodRatioThreshold_))\n    {\n        status = AlleleStatus::kAbsent;\n    }\n    else if (logLikelihoodRatio > log10(likelihoodRatioThreshold_))\n    {\n        status = AlleleStatus::kPresent;\n    }\n\n    return AlleleCheckSummary(status, logLikelihoodRatio);\n}\n\nstd::ostream& operator<<(std::ostream& out, AlleleStatus status)\n{\n    switch (status)\n    {\n    case AlleleStatus::kAbsent:\n        out << \"Absent\";\n        break;\n    case AlleleStatus::kPresent:\n        out << \"Present\";\n        break;\n    case AlleleStatus::kUncertain:\n        out << \"Uncertain\";\n        break;\n    }\n\n    return out;\n}\n\n}\n", "meta": {"hexsha": "cbebc3d40bb7e6b9c9568b642a68e529abf28cc1", "size": 2765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ehunter/genotyping/AlleleChecker.cpp", "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/genotyping/AlleleChecker.cpp", "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/genotyping/AlleleChecker.cpp", "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": 28.2142857143, "max_line_length": 117, "alphanum_fraction": 0.6886075949, "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5449469649297278}}
{"text": "#pragma once\n\n#include <deal.II/base/tensor.h>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\n#include \"aux/filtered_range.hpp\"\n#include \"aux/hash_specializations.hpp\"\n#include \"aux/simple_sparse_matrix.hpp\"\n#include \"matrix/assembly/velocity_angular_integrator.hpp\"\n#include \"matrix/assembly/velocity_radial_integrator.hpp\"\n#include \"matrix/assembly/weight.hpp\"\n#include \"spectral/basis/spectral_basis_dimension_accessor.hpp\"\n\n\nnamespace boltzmann {\nnamespace local_ {\n/**\n * @brief Compute and cache overlap integrals in radial direction\n */\nstruct radial_entry_computer_t\n{\n  // -----------------------------------------------------------------\n  radial_entry_computer_t(int nqpts_ = 90)\n      : nqpts(nqpts_)\n  {\n    /* empty */\n  }\n\n  /**\n   *  @brief I = \\f$\\int_\\bbR b_1(r) k(r), b_2(r) r \\ud r \\f$\n   *\n   *  @tparam E spectral element\n   *  @param k additional function argument\n   *  @param b1 1st basis function\n   *  @param b2 2nd basis function\n   *  @return I integral\n   */\n  template <typename E>\n  double compute(const std::function<double(double)>& k,\n                 const E& b1,\n                 const E& b2,\n                 const double a = 0 /* inner product weight exp(-a r**2) */)\n  {\n    const double FUZZY = 1e7;\n    const double nu = a + b1.w() + b2.w();\n    const long int key = FUZZY * nu;\n    if (quad_cache.find(key) == quad_cache.end()) quad_cache[key] = ptr_t(new QMaxwell(nu, nqpts));\n    const auto& quad = *(quad_cache[key]);\n\n    double sum = 0;\n    for (unsigned int q = 0; q < quad.size(); ++q) {\n      sum += b1.evaluate(quad.pts(q)) * b2.evaluate(quad.pts(q)) * k(quad.pts(q)) * quad.wts(q);\n    }\n\n    return sum;\n  }\n\n private:\n  const int nqpts;\n  typedef std::shared_ptr<QMaxwell> ptr_t;\n  std::map<long int, ptr_t> quad_cache;\n};\n}  // end namespace local_\n\ntemplate <int DIM>\nclass VelocityVarForm\n{ };\n\n/**\n * @brief Storage for velocity domain matrix entries\n *\n */\ntemplate <>\nclass VelocityVarForm<2>\n{\n private:\n  static const int DIM = 2;\n  typedef unsigned int index_t;\n  typedef dealii::Tensor<1, DIM, double> t1_t;\n  typedef dealii::Tensor<2, DIM, double> t2_t;\n\n  typedef SimpleSparseMatrix<double> s0_entries_t;\n  typedef SimpleSparseMatrix<t1_t> t1_entries_t;\n  typedef SimpleSparseMatrix<t2_t> t2_entries_t;\n\n public:\n  template <typename BASIS>\n  void init(const BASIS& test_basis, const BASIS& trial_basis, const double beta = 2);\n\n  template <typename BASIS>\n  void init(const BASIS& trial_basis, const double beta = 2);\n\n private:\n  s0_entries_t s0_;\n  t1_entries_t t1_;\n  t2_entries_t t2_;\n\n  /// helpers\n  VelocityAngularIntegrator<2> vai;\n\n  constexpr const static double TOL = 1e-11; // magic number\n\n public:\n  auto get_s0() const -> decltype(s0_.get_vec()) { return s0_.get_vec(); }\n  auto get_s1() const -> decltype(t1_.get_vec()) { return t1_.get_vec(); }\n  auto get_t1() const -> decltype(t1_.get_vec()) { return t1_.get_vec(); }\n  auto get_t2() const -> decltype(t2_.get_vec()) { return t2_.get_vec(); }\n\n  const SimpleSparseMatrix<double>& get_s0m() const { return s0_; }\n  const SimpleSparseMatrix<t1_t>& get_s1m()   const { return t1_; }\n  const SimpleSparseMatrix<t1_t>& get_t1m()   const { return t1_; }\n  const SimpleSparseMatrix<t2_t>& get_t2m()   const { return t2_; }\n\n  /**\n   *  @brief \\f$\\langle \\psi_1, \\psi_2\\rangle\\f$\n   *\n   *  Detailed description\n   *\n   *  @return Returns a vector [(entry_t...)] which contains the non-zero\n   *    entries of the sparse matrix arising from the overlap integral above.\n   *    entry_t has members row, col and val. row and col correspond to the\n   *    enumeration of DoFs in the spectral basis.\n\n   */\n  auto s0() const -> const decltype(s0_) & { return s0_; }\n\n  /**\n   *  @brief \\f$\\langle v_i \\psi_1, \\psi_2\\rangle\\f$\n   *\n   *  Detailed description\n   *\n   *  @return Returns a vector [(entry_t...)] which contains the non-zero\n   *    entries of the sparse matrix arising from the overlap integral above.\n   *    entry_t has members row, col and val. row and col correspond to the\n   *    enumeration of DoFs in the spectral basis.\n   */\n  auto s1() const -> const decltype(t1_) & { return t1_; }\n\n  /**\n   *   @brief same as s1\n   */\n  auto t1() const -> const decltype(t1_) & { return t1_; }\n\n  /**\n   *   @brief \\f$\\langle v_i v_j \\psi_1, \\psi_2 \\rangle\\f$\n   *\n   *  Detailed description\n   *\n   *  @return Returns a vector [(entry_t...)] which contains the non-zero\n   *    entries of the sparse matrix arising from the overlap integral above.\n   *    entry_t has members row, col and val. row and col correspond to the\n   *    enumeration of DoFs in the spectral basis.\n   */\n  auto t2() const -> const decltype(t2_) & { return t2_; }\n\n  const VelocityAngularIntegrator<2>& get_vai() const { return vai; }\n\n  void print_info() const;\n};\n\n// --------------------------------------------------------------------------------\ntemplate <typename BASIS>\nvoid\nVelocityVarForm<2>::init(const BASIS& test_basis, const BASIS& trial_basis, const double beta)\n{\n  typedef typename BASIS::elem_t elem_t;\n\n  // angular basis\n  typedef typename std::tuple_element<0, typename BASIS::elem_t::container_t>::type angular_elem_t;\n  // radial basis\n  typedef typename std::tuple_element<1, typename BASIS::elem_t::container_t>::type radial_elem_t;\n  /// vector of basis functions in dim1\n  typedef typename BASIS::DimAcc::template get_vec<angular_elem_t> a1_t;\n  typedef typename BASIS::DimAcc::template get_vec<radial_elem_t> a2_t;\n\n  typedef typename radial_elem_t::id_t rid_t;\n  typedef typename radial_elem_t::numeric_t numeric_t;\n\n  // element accessors for radial and angular parts\n  typename elem_t::Acc::template get<radial_elem_t> acc_rad;\n  typename elem_t::Acc::template get<angular_elem_t> acc_ang;\n\n  /// they correspond to rows and columns in R1\n  const auto& test_angular_basis = a1_t()(test_basis);\n  //  const auto& test_radial_basis  = a2_t()(test_basis);\n\n  const auto& trial_angular_basis = a1_t()(trial_basis);\n  // const auto& trial_radial_basis  = a2_t()(trial_basis);\n\n  // matrix assembly\n  vai.init(trial_angular_basis);\n  // regular L2-inner product\n  L2Weight weight(beta);\n\n  // ------------------------------\n  // Compute Radial Entries\n  local_::radial_entry_computer_t radial_entry_computer;\n  // create a cache for the radial entries\n  std::unordered_map<std::tuple<rid_t, rid_t>, numeric_t> cache;\n\n  typedef std::pair<unsigned int, unsigned int> index_pair_t;\n\n  // ----------------------------------------------------------------------\n  // S0\n  s0_.reinit(trial_basis.n_dofs());\n  cache.clear();\n  auto k0 = [](double r __attribute__((unused))) { return 1; };\n  // iterate over nonzero entries in s0\n  const auto& s0A = vai.get_s0();\n  for (auto itA = s0A.begin(); itA != s0A.end(); ++itA) {\n    // get ids from anuglar basis\n    unsigned int iA1 = itA->first.first;\n    unsigned int iA2 = itA->first.second;\n    const auto& idA1 = test_angular_basis[iA1].get_id();\n    const auto& idA2 = trial_angular_basis[iA2].get_id();\n\n    std::function<bool(const elem_t&)> pred1 = [&](const elem_t& e) {\n      return acc_ang(e).get_id() == idA1;\n    };\n\n    std::function<bool(const elem_t&)> pred2 = [&](const elem_t& e) {\n      return acc_ang(e).get_id() == idA2;\n    };\n\n    auto test_range_rad = filtered_range(test_basis.begin(), test_basis.end(), pred1);\n    auto trial_range_rad = filtered_range(trial_basis.begin(), trial_basis.end(), pred2);\n\n    // iterate over test functions\n    for (auto itR1 = std::get<0>(test_range_rad); itR1 != std::get<1>(test_range_rad); ++itR1) {\n      const auto& br1 = acc_rad(*itR1);  // extract radial part\n      const auto& id1 = br1.get_id();\n\n      // iterate over trial functions\n      for (auto itR2 = std::get<0>(trial_range_rad); itR2 != std::get<1>(trial_range_rad); ++itR2) {\n        const auto& br2 = acc_rad(*itR2);  // extract radial part\n        const auto& id2 = br2.get_id();\n        // create key\n        auto key = std::make_tuple(id1, id2);\n        // lookup\n        auto cit = cache.find(key);\n        // found?\n        double vr;\n        if (cit != cache.end()) {\n          vr = cit->second;\n        } else {\n          vr = radial_entry_computer.compute(k0, br1, br2, 1 - 2.0 / beta);\n          cache[key] = vr;\n        }\n\n        // insert value into entries structure\n        if (std::abs(vr) > TOL) {\n          unsigned int gidx1 = test_basis.get_dof_index(itR1->get_id());\n          unsigned int gidx2 = trial_basis.get_dof_index(itR2->get_id());\n          s0_.insert(gidx1, gidx2, (itA->second) * vr);\n        }\n      }\n    }\n  }\n  s0_.compress();\n\n  // ----------------------------------------------------------------------\n  // T1\n  t1_.reinit(trial_basis.n_dofs());\n  cache.clear();\n  auto k1 = [](double r) { return r; };\n  // iterate over nonzero entries in t1\n  const auto& t1A = vai.get_t1();\n  for (auto itA = t1A.begin(); itA != t1A.end(); ++itA) {\n    // get ids from anuglar basis\n    unsigned int iA1 = itA->first.first;\n    unsigned int iA2 = itA->first.second;\n    const auto& idA1 = test_angular_basis[iA1].get_id();\n    const auto& idA2 = trial_angular_basis[iA2].get_id();\n\n    std::function<bool(const elem_t&)> pred1 = [&](const elem_t& e) {\n      return acc_ang(e).get_id() == idA1;\n    };\n    std::function<bool(const elem_t&)> pred2 = [&](const elem_t& e) {\n      return acc_ang(e).get_id() == idA2;\n    };\n\n    auto test_range_rad = filtered_range(test_basis.begin(), test_basis.end(), pred1);\n    auto trial_range_rad = filtered_range(trial_basis.begin(), trial_basis.end(), pred2);\n\n    // iterate over test functions\n    for (auto itR1 = std::get<0>(test_range_rad); itR1 != std::get<1>(test_range_rad); ++itR1) {\n      const auto& br1 = acc_rad(*itR1);  // extract radial part\n      const auto& id1 = br1.get_id();\n\n      // iterate over trial functions\n      for (auto itR2 = std::get<0>(trial_range_rad); itR2 != std::get<1>(trial_range_rad); ++itR2) {\n        const auto& br2 = acc_rad(*itR2);  // extract radial part\n        const auto& id2 = br2.get_id();\n        // create key\n        auto key = std::make_tuple(id1, id2);\n        // lookup\n        auto cit = cache.find(key);\n        // found?\n        double vr;\n        if (cit != cache.end()) {\n          vr = cit->second;\n        } else {\n          vr = radial_entry_computer.compute(k1, br1, br2, 1 - 2.0 / beta);\n          cache[key] = vr;\n        }\n\n        // insert value into entries structure\n        if (std::abs(vr) > TOL) {\n          unsigned int gidx1 = test_basis.get_dof_index(itR1->get_id());\n          unsigned int gidx2 = trial_basis.get_dof_index(itR2->get_id());\n          t1_.insert(gidx1, gidx2, (itA->second) * vr);\n        }\n      }\n    }\n  }\n  t1_.compress();\n\n  // ----------------------------------------------------------------------\n  // T2\n  t2_.reinit(trial_basis.n_dofs());\n  cache.clear();\n  auto k2 = [](double r) { return r * r; };\n  const auto& t2A = vai.get_t2();\n  for (auto itA = t2A.begin(); itA != t2A.end(); ++itA) {\n    // get ids from anuglar basis\n    unsigned int iA1 = itA->first.first;\n    unsigned int iA2 = itA->first.second;\n    const auto& idA1 = test_angular_basis[iA1].get_id();\n    const auto& idA2 = trial_angular_basis[iA2].get_id();\n\n    std::function<bool(const elem_t&)> pred1 = [&](const elem_t& e) {\n      return acc_ang(e).get_id() == idA1;\n    };\n    std::function<bool(const elem_t&)> pred2 = [&](const elem_t& e) {\n      return acc_ang(e).get_id() == idA2;\n    };\n\n    auto test_range_rad = filtered_range(test_basis.begin(), test_basis.end(), pred1);\n    auto trial_range_rad = filtered_range(trial_basis.begin(), trial_basis.end(), pred2);\n\n    // iterate over test functions\n    for (auto itR1 = std::get<0>(test_range_rad); itR1 != std::get<1>(test_range_rad); ++itR1) {\n      const auto& br1 = acc_rad(*itR1);  // extract radial part\n      const auto& id1 = br1.get_id();\n\n      // iterate over trial functions\n      for (auto itR2 = std::get<0>(trial_range_rad); itR2 != std::get<1>(trial_range_rad); ++itR2) {\n        const auto& br2 = acc_rad(*itR2);  // extract radial part\n        const auto& id2 = br2.get_id();\n        // create key\n        auto key = std::make_tuple(id1, id2);\n        // lookup\n        auto cit = cache.find(key);\n        // found?\n        double vr;\n        if (cit != cache.end()) {\n          vr = cit->second;\n        } else {\n          vr = radial_entry_computer.compute(k2, br1, br2, 1 - 2.0 / beta);\n          cache[key] = vr;\n        }\n\n        // insert value into entries structure\n        if (std::abs(vr) > TOL) {\n          unsigned int gidx1 = test_basis.get_dof_index(itR1->get_id());\n          unsigned int gidx2 = trial_basis.get_dof_index(itR2->get_id());\n          t2_.insert(gidx1, gidx2, (itA->second) * vr);\n        }\n      }\n    }\n  }\n  t2_.compress();\n}\n\n// ------------------------------------------------------------\ntemplate <typename BASIS>\nvoid\nVelocityVarForm<2>::init(const BASIS& trial_basis, const double beta)\n{\n  this->init(trial_basis, trial_basis, beta);\n}\n\n// -------------------------------------------------------------\ninline void\nVelocityVarForm<2>::print_info() const\n{\n  std::cout << \"s0_.size()\"\n            << \"\\t\" << s0_.size() << std::endl\n            << \"t1_.size()\"\n            << \"\\t\" << t1_.size() << std::endl\n            << \"t2_.size()\"\n            << \"\\t\" << t2_.size() << std::endl;\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "90a1e36b4ad198b09f64bb984032446eafbf8b12", "size": 13425, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/matrix/assembly/velocity_var_form.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/matrix/assembly/velocity_var_form.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/matrix/assembly/velocity_var_form.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": 33.5625, "max_line_length": 100, "alphanum_fraction": 0.6078957169, "num_tokens": 3776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5449169939438074}}
{"text": "//  Boost common_factor.hpp header file  -------------------------------------//\n\n//  (C) Copyright Daryle Walker, Stephen Cleary, Paul Moore 2001.  Permission\n//  to copy, use, modify, sell and distribute this software is granted provided\n//  this copyright notice appears in all copies.  This software is provided \"as\n//  is\" without express or implied warranty, and with no claim as to its\n//  suitability for any purpose. \n\n//  See http://www.boost.org for updates, documentation, and revision history. \n\n#ifndef BOOST_MATH_COMMON_FACTOR_HPP\n#define BOOST_MATH_COMMON_FACTOR_HPP\n\n#include <boost/math_fwd.hpp>  // self include\n\n#include <boost/config.hpp>  // for BOOST_STATIC_CONSTANT, etc.\n#include <boost/limits.hpp>  // for std::numeric_limits\n\n\nnamespace boost\n{\nnamespace math\n{\n\n\n//  Forward declarations for function templates  -----------------------------//\n\ntemplate < typename IntegerType >\n    IntegerType  gcd( IntegerType const &a, IntegerType const &b );\n\ntemplate < typename IntegerType >\n    IntegerType  lcm( IntegerType const &a, IntegerType const &b );\n\n\n//  Greatest common divisor evaluator class declaration  ---------------------//\n\ntemplate < typename IntegerType >\nclass gcd_evaluator\n{\npublic:\n    // Types\n    typedef IntegerType  result_type, first_argument_type, second_argument_type;\n\n    // Function object interface\n    result_type  operator ()( first_argument_type const &a,\n     second_argument_type const &b ) const;\n\n};  // boost::math::gcd_evaluator\n\n\n//  Least common multiple evaluator class declaration  -----------------------//\n\ntemplate < typename IntegerType >\nclass lcm_evaluator\n{\npublic:\n    // Types\n    typedef IntegerType  result_type, first_argument_type, second_argument_type;\n\n    // Function object interface\n    result_type  operator ()( first_argument_type const &a,\n     second_argument_type const &b ) const;\n\n};  // boost::math::lcm_evaluator\n\n\n//  Implementation details  --------------------------------------------------//\n\nnamespace detail\n{\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\n    // Build GCD with Euclid's recursive algorithm\n    template < unsigned long Value1, unsigned long Value2 >\n    struct static_gcd_helper_t\n    {\n    private:\n        BOOST_STATIC_CONSTANT( unsigned long, new_value1 = Value2 );\n        BOOST_STATIC_CONSTANT( unsigned long, new_value2 = Value1 % Value2 );\n\n        #ifndef __BORLANDC__\n        #define BOOST_DETAIL_GCD_HELPER_VAL(Value)  Value\n        #else\n        typedef static_gcd_helper_t  self_type;\n        #define BOOST_DETAIL_GCD_HELPER_VAL(Value)  (self_type:: Value )\n        #endif\n\n        typedef static_gcd_helper_t< BOOST_DETAIL_GCD_HELPER_VAL(new_value1),\n         BOOST_DETAIL_GCD_HELPER_VAL(new_value2) >  next_step_type;\n\n        #undef BOOST_DETAIL_GCD_HELPER_VAL\n\n    public:\n        BOOST_STATIC_CONSTANT( unsigned long, value = next_step_type::value );\n    };\n\n    // Non-recursive case\n    template < unsigned long Value1 >\n    struct static_gcd_helper_t< Value1, 0UL >\n    {\n        BOOST_STATIC_CONSTANT( unsigned long, value = Value1 );\n    };\n#else\n    // Use inner class template workaround from Peter Dimov\n    template < unsigned long Value1 >\n    struct static_gcd_helper2_t\n    {\n        template < unsigned long Value2 >\n        struct helper\n        {\n            BOOST_STATIC_CONSTANT( unsigned long, value\n             = static_gcd_helper2_t<Value2>::helper<Value1 % Value2>::value );\n        };\n\n        template <  >\n        struct helper< 0UL >\n        {\n            BOOST_STATIC_CONSTANT( unsigned long, value = Value1 );\n        };\n    };\n\n    // Special case\n    template <  >\n    struct static_gcd_helper2_t< 0UL >\n    {\n        template < unsigned long Value2 >\n        struct helper\n        {\n            BOOST_STATIC_CONSTANT( unsigned long, value = Value2 );\n        };\n    };\n\n    // Build the GCD from the above template(s)\n    template < unsigned long Value1, unsigned long Value2 >\n    struct static_gcd_helper_t\n    {\n        BOOST_STATIC_CONSTANT( unsigned long, value\n         = static_gcd_helper2_t<Value1>::BOOST_NESTED_TEMPLATE\n         helper<Value2>::value );\n    };\n#endif\n\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\n    // Build the LCM from the GCD\n    template < unsigned long Value1, unsigned long Value2 >\n    struct static_lcm_helper_t\n    {\n        typedef static_gcd_helper_t<Value1, Value2>  gcd_type;\n\n        BOOST_STATIC_CONSTANT( unsigned long, value = Value1 / gcd_type::value\n         * Value2 );\n    };\n\n    // Special case for zero-GCD values\n    template < >\n    struct static_lcm_helper_t< 0UL, 0UL >\n    {\n        BOOST_STATIC_CONSTANT( unsigned long, value = 0UL );\n    };\n#else\n    // Adapt GCD's inner class template workaround for LCM\n    template < unsigned long Value1 >\n    struct static_lcm_helper2_t\n    {\n        template < unsigned long Value2 >\n        struct helper\n        {\n            typedef static_gcd_helper_t<Value1, Value2>  gcd_type;\n\n            BOOST_STATIC_CONSTANT( unsigned long, value = Value1\n             / gcd_type::value * Value2 );\n        };\n\n        template <  >\n        struct helper< 0UL >\n        {\n            BOOST_STATIC_CONSTANT( unsigned long, value = 0UL );\n        };\n    };\n\n    // Special case\n    template <  >\n    struct static_lcm_helper2_t< 0UL >\n    {\n        template < unsigned long Value2 >\n        struct helper\n        {\n            BOOST_STATIC_CONSTANT( unsigned long, value = 0UL );\n        };\n    };\n\n    // Build the LCM from the above template(s)\n    template < unsigned long Value1, unsigned long Value2 >\n    struct static_lcm_helper_t\n    {\n        BOOST_STATIC_CONSTANT( unsigned long, value\n         = static_lcm_helper2_t<Value1>::BOOST_NESTED_TEMPLATE\n         helper<Value2>::value );\n    };\n#endif\n\n    // Greatest common divisor for rings (including unsigned integers)\n    template < typename RingType >\n    RingType\n    gcd_euclidean\n    (\n        RingType  a,\n        RingType  b\n    )\n    {\n        // Avoid repeated construction\n        #ifndef __BORLANDC__\n        RingType const  zero = static_cast<RingType>( 0 );\n        #else\n        RingType  zero = static_cast<RingType>( 0 );\n        #endif\n\n        // Reduce by GCD-remainder property [GCD(a,b) == GCD(b,a MOD b)]\n        while ( true )\n        {\n            if ( a == zero )\n                return b;\n            b %= a;\n\n            if ( b == zero )\n                return a;\n            a %= b;\n        }\n    }\n\n    // Greatest common divisor for (signed) integers\n    template < typename IntegerType >\n    inline\n    IntegerType\n    gcd_integer\n    (\n        IntegerType const &  a,\n        IntegerType const &  b\n    )\n    {\n        // Avoid repeated construction\n        IntegerType const  zero = static_cast<IntegerType>( 0 );\n        IntegerType const  result = gcd_euclidean( a, b );\n\n        return ( result < zero ) ? -result : result;\n    }\n\n    // Least common multiple for rings (including unsigned integers)\n    template < typename RingType >\n    inline\n    RingType\n    lcm_euclidean\n    (\n        RingType const &  a,\n        RingType const &  b\n    )\n    {\n        RingType const  zero = static_cast<RingType>( 0 );\n        RingType const  temp = gcd_euclidean( a, b );\n\n        return ( temp != zero ) ? ( a / temp * b ) : zero;\n    }\n\n    // Least common multiple for (signed) integers\n    template < typename IntegerType >\n    inline\n    IntegerType\n    lcm_integer\n    (\n        IntegerType const &  a,\n        IntegerType const &  b\n    )\n    {\n        // Avoid repeated construction\n        IntegerType const  zero = static_cast<IntegerType>( 0 );\n        IntegerType const  result = lcm_euclidean( a, b );\n\n        return ( result < zero ) ? -result : result;\n    }\n\n    // Function objects to find the best way of computing GCD or LCM\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\n    template < typename T, bool IsSpecialized, bool IsSigned >\n    struct gcd_optimal_evaluator_helper_t\n    {\n        T  operator ()( T const &a, T const &b )\n        {\n            return gcd_euclidean( a, b );\n        }\n    };\n\n    template < typename T >\n    struct gcd_optimal_evaluator_helper_t< T, true, true >\n    {\n        T  operator ()( T const &a, T const &b )\n        {\n            return gcd_integer( a, b );\n        }\n    };\n#else\n    template < bool IsSpecialized, bool IsSigned >\n    struct gcd_optimal_evaluator_helper2_t\n    {\n        template < typename T >\n        struct helper\n        {\n            T  operator ()( T const &a, T const &b )\n            {\n                return gcd_euclidean( a, b );\n            }\n        };\n    };\n\n    template < >\n    struct gcd_optimal_evaluator_helper2_t< true, true >\n    {\n        template < typename T >\n        struct helper\n        {\n            T  operator ()( T const &a, T const &b )\n            {\n                return gcd_integer( a, b );\n            }\n        };\n    };\n\n    template < typename T, bool IsSpecialized, bool IsSigned >\n    struct gcd_optimal_evaluator_helper_t\n        : gcd_optimal_evaluator_helper2_t<IsSpecialized, IsSigned>\n           ::BOOST_NESTED_TEMPLATE helper<T>\n    {\n    };\n#endif\n\n    template < typename T >\n    struct gcd_optimal_evaluator\n    {\n        T  operator ()( T const &a, T const &b )\n        {\n            typedef ::std::numeric_limits<T>  limits_type;\n\n            typedef gcd_optimal_evaluator_helper_t<T,\n             limits_type::is_specialized, limits_type::is_signed>  helper_type;\n\n            helper_type  solver;\n\n            return solver( a, b );\n        }\n    };\n#else // BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n    template < typename T >\n    struct gcd_optimal_evaluator\n    {\n        T  operator ()( T const &a, T const &b )\n        {\n            return gcd_integer( a, b );\n        }\n    };\n#endif\n\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\n    template < typename T, bool IsSpecialized, bool IsSigned >\n    struct lcm_optimal_evaluator_helper_t\n    {\n        T  operator ()( T const &a, T const &b )\n        {\n            return lcm_euclidean( a, b );\n        }\n    };\n\n    template < typename T >\n    struct lcm_optimal_evaluator_helper_t< T, true, true >\n    {\n        T  operator ()( T const &a, T const &b )\n        {\n            return lcm_integer( a, b );\n        }\n    };\n#else\n    template < bool IsSpecialized, bool IsSigned >\n    struct lcm_optimal_evaluator_helper2_t\n    {\n        template < typename T >\n        struct helper\n        {\n            T  operator ()( T const &a, T const &b )\n            {\n                return lcm_euclidean( a, b );\n            }\n        };\n    };\n\n    template < >\n    struct lcm_optimal_evaluator_helper2_t< true, true >\n    {\n        template < typename T >\n        struct helper\n        {\n            T  operator ()( T const &a, T const &b )\n            {\n                return lcm_integer( a, b );\n            }\n        };\n    };\n\n    template < typename T, bool IsSpecialized, bool IsSigned >\n    struct lcm_optimal_evaluator_helper_t\n        : lcm_optimal_evaluator_helper2_t<IsSpecialized, IsSigned>\n           ::BOOST_NESTED_TEMPLATE helper<T>\n    {\n    };\n#endif\n\n    template < typename T >\n    struct lcm_optimal_evaluator\n    {\n        T  operator ()( T const &a, T const &b )\n        {\n            typedef ::std::numeric_limits<T>  limits_type;\n\n            typedef lcm_optimal_evaluator_helper_t<T,\n             limits_type::is_specialized, limits_type::is_signed>  helper_type;\n\n            helper_type  solver;\n\n            return solver( a, b );\n        }\n    };\n#else // BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n    template < typename T >\n    struct lcm_optimal_evaluator\n    {\n        T  operator ()( T const &a, T const &b )\n        {\n            return lcm_integer( a, b );\n        }\n    };\n#endif\n\n    // Functions to find the GCD or LCM in the best way\n    template < typename T >\n    inline\n    T\n    gcd_optimal\n    (\n        T const &  a,\n        T const &  b\n    )\n    {\n        gcd_optimal_evaluator<T>  solver;\n\n        return solver( a, b );\n    }\n\n    template < typename T >\n    inline\n    T\n    lcm_optimal\n    (\n        T const &  a,\n        T const &  b\n    )\n    {\n        lcm_optimal_evaluator<T>  solver;\n\n        return solver( a, b );\n    }\n\n}  // namespace detail\n\n\n//  Compile-time greatest common divisor evaluator class declaration  --------//\n\ntemplate < unsigned long Value1, unsigned long Value2 >\nstruct static_gcd\n{\n    BOOST_STATIC_CONSTANT( unsigned long, value\n     = (detail::static_gcd_helper_t<Value1, Value2>::value) );\n\n};  // boost::math::static_gcd\n\n\n//  Compile-time least common multiple evaluator class declaration  ----------//\n\ntemplate < unsigned long Value1, unsigned long Value2 >\nstruct static_lcm\n{\n    BOOST_STATIC_CONSTANT( unsigned long, value\n     = (detail::static_lcm_helper_t<Value1, Value2>::value) );\n\n};  // boost::math::static_lcm\n\n\n//  Greatest common divisor evaluator member function definition  ------------//\n\ntemplate < typename IntegerType >\ninline\ntypename gcd_evaluator<IntegerType>::result_type\ngcd_evaluator<IntegerType>::operator ()\n(\n    first_argument_type const &   a,\n    second_argument_type const &  b\n) const\n{\n    return detail::gcd_optimal( a, b );\n}\n\n\n//  Least common multiple evaluator member function definition  --------------//\n\ntemplate < typename IntegerType >\ninline\ntypename lcm_evaluator<IntegerType>::result_type\nlcm_evaluator<IntegerType>::operator ()\n(\n    first_argument_type const &   a,\n    second_argument_type const &  b\n) const\n{\n    return detail::lcm_optimal( a, b );\n}\n\n\n//  Greatest common divisor and least common multiple function definitions  --//\n\ntemplate < typename IntegerType >\ninline\nIntegerType\ngcd\n(\n    IntegerType const &  a,\n    IntegerType const &  b\n)\n{\n    gcd_evaluator<IntegerType>  solver;\n\n    return solver( a, b );\n}\n\ntemplate < typename IntegerType >\ninline\nIntegerType\nlcm\n(\n    IntegerType const &  a,\n    IntegerType const &  b\n)\n{\n    lcm_evaluator<IntegerType>  solver;\n\n    return solver( a, b );\n}\n\n\n}  // namespace math\n}  // namespace boost\n\n\n#endif  // BOOST_MATH_COMMON_FACTOR_HPP\n", "meta": {"hexsha": "10196fee64ab8e4822a0bacc6ccfae05e12ac420", "size": 14165, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/math/common_factor.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vegastrike/boost/1_28/boost/math/common_factor.hpp", "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vegastrike/boost/1_28/boost/math/common_factor.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["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.2495543672, "max_line_length": 80, "alphanum_fraction": 0.6089657607, "num_tokens": 3343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5449169939438073}}
{"text": "#ifndef INCLUDED_scheme_numeric_euler_angles_HH\n#define INCLUDED_scheme_numeric_euler_angles_HH\n\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n\nnamespace scheme { namespace numeric {\n\n\n\ttemplate<class M> typename M::Scalar const & xx( M const & m ) { return m(0,0); }\n\ttemplate<class M> typename M::Scalar const & xy( M const & m ) { return m(0,1); }\n\ttemplate<class M> typename M::Scalar const & xz( M const & m ) { return m(0,2); }\n\ttemplate<class M> typename M::Scalar const & yx( M const & m ) { return m(1,0); }\n\ttemplate<class M> typename M::Scalar const & yy( M const & m ) { return m(1,1); }\n\ttemplate<class M> typename M::Scalar const & yz( M const & m ) { return m(1,2); }\n\ttemplate<class M> typename M::Scalar const & zx( M const & m ) { return m(2,0); }\n\ttemplate<class M> typename M::Scalar const & zy( M const & m ) { return m(2,1); }\n\ttemplate<class M> typename M::Scalar const & zz( M const & m ) { return m(2,2); }\n\ttemplate<class M> typename M::Scalar       & xx( M       & m ) { return m(0,0); }\n\ttemplate<class M> typename M::Scalar       & xy( M       & m ) { return m(0,1); }\n\ttemplate<class M> typename M::Scalar       & xz( M       & m ) { return m(0,2); }\n\ttemplate<class M> typename M::Scalar       & yx( M       & m ) { return m(1,0); }\n\ttemplate<class M> typename M::Scalar       & yy( M       & m ) { return m(1,1); }\n\ttemplate<class M> typename M::Scalar       & yz( M       & m ) { return m(1,2); }\n\ttemplate<class M> typename M::Scalar       & zx( M       & m ) { return m(2,0); }\n\ttemplate<class M> typename M::Scalar       & zy( M       & m ) { return m(2,1); }\n\ttemplate<class M> typename M::Scalar       & zz( M       & m ) { return m(2,2); }\n\n\ttemplate<class M> struct get_scalar { typedef typename M::Scalar type; };\n\n\ttemplate<class T> T sin_cos_range(T const & t) { return t; }\n\n\t/// @brief COPIED FROM ROSETTA\n\t/// Return the three euler angles (in radians) that describe this HomogeneousTransform as the series\n\t/// of a Z axis rotation by the angle phi (returned in position 1 of the output vector), followed by\n\t/// an X axis rotation by the angle theta (returned in position 3 of the output vector), followed by another\n\t/// Z axis rotation by the angle psi (returned in position 2 of the output vector).\n\t/// This code is a modified version of Alex Z's code from r++.\n\t///\n\t/// @details\n\t/// The range of phi is [ -pi, pi ];\n\t/// The range of psi is [ -pi, pi ];\n\t/// The range of theta is [ 0, pi ];\n\t///\n\t/// The function pretends that this HomogeneousTransform is the result of these three transformations;\n\t/// if it were, then the rotation matrix would be\n\t///\n\t/// FIGURE 1:\n\t/// R = [\n\t///       cos(psi)cos(phi)-cos(theta)sin(phi)sin(psi)        cos(psi)sin(phi)+cos(theta)cos(phi)sin(psi)      sin(psi)sin(theta)\n\t///      -sin(psi)cos(phi)-cos(theta)sin(phi)cos(psi)       -sin(psi)sin(phi)+cos(theta)cos(phi)cos(psi)      cos(psi)sin(theta)\n\t///                   sin(theta)sin(phi)                                 -sin(theta)cos(phi)                        cos(theta)\n\t/// ]\n\t///\n\t/// where each axis above is represented as a ROW VECTOR (to be distinguished from the\n\t/// HomogeneousTransform's representation of axes as COLUMN VECTORS).\n\t///\n\t/// The zz_ coordinate gives away theta.\n\t/// Theta may be computed as acos( zz_ ), or, as Alex does it, asin( sqrt( 1 - zz^2))\n\t/// Since there is redundancy in theta, this function chooses a theta with a positive\n\t/// sin(theta): i.e. quadrants I and II.  Assuming we have a positive sin theta\n\t/// pushes phi and psi into conforming angles.\n\t///\n\t/// NOTE on theta: asin returns a value in the range [ -pi/2, pi/2 ], and we have artificially\n\t/// created a positive sin(theta), so we will get a asin( pos_sin_theta ), we have a value\n\t/// in the range [ 0, pi/2 ].  To convert this into the actual angle theta, we examine the zz sign.\n\t/// If zz is negative, we chose the quadrant II theta.\n\t/// That is, asin( pos_sin_theta) returned an angle, call it theta'.  Now, if cos( theta ) is negative,\n\t/// then we want to choose the positive x-axis rotation that's equivalent to -theta'.  To do so,\n\t/// we reflect q through the y axis (See figure 2 below) to get p and then measure theta as pi - theta'.\n\t///\n\t/// FIGURE 2:\n\t///\n\t///  II        |         I\n\t///            |\n\t///    p.      |      .q (cos(-theta'), abs(sin(theta')))\n\t///       .    |    .\n\t/// theta'( .  |  .  )  theta' = asin( abs(sin(theta))\n\t/// -----------------------\n\t///            |\n\t///            |\n\t///            |\n\t///  III       |        IV\n\t///            |\n\t///  The angle between the positive x axis and p is pi - theta'.\n\t///\n\t///\n\t///\n\t/// Since zx and zy contain only phi terms and a constant sin( theta ) term,\n\t/// phi is given by atan2( sin_phi, cos_phi ) = atan2( c*sin_phi, c*cos_phi ) = atan2( zx, -zy )\n\t/// for c positive and non-zero.  If sin_theta is zero, or very close to zero, we're at gimbal lock.\n\t///\n\t/// Moreover, since xz and yz contain only psi terms, psi may also be deduced using atan2.\n\t///\n\t/// There are 2 degenerate cases (gimbal lock)\n\t/// 1. theta close to 0  (North Pole singularity), or\n\t/// 2. theta close to pi (South Pole singularity)\n\t/// For these, we take: phi=acos(xx), theta = 0 (resp. Pi/2), psi = 0\n\ttemplate<class M,class E> void\n\teuler_angles(M const & m, E & euler){\n\n\t\ttypedef typename get_scalar<M>::type T;\n\t\tstatic T const pi = boost::math::constants::pi<T>();\n\t\tstatic T const pi_2 = boost::math::constants::pi<T>() * (T)2;\n\t\tstatic T const epsilon = (T)10*std::numeric_limits<T>::epsilon();\n\t\tstatic T const FLOAT_PRECISION = std::sqrt(epsilon);\n\t\tif ( zz(m) >= (T)1 - FLOAT_PRECISION ){\n\t\t\teuler[0] = std::atan2( sin_cos_range( yx(m) ), sin_cos_range( xx(m) ) );\n\t\t\teuler[1] = 0.0;\n\t\t\teuler[2] = 0.0;\n\t\t} else if ( zz(m) <= (T)-1 + FLOAT_PRECISION ){\n\t\t\teuler[0] = std::atan2( sin_cos_range( yx(m) ), sin_cos_range( xx(m) ) );\n\t\t\teuler[1] = 0.0;\n\t\t\teuler[2] = M_PI;\n\t\t} else {\n\t\t\tT pos_sin_theta = std::sqrt( (T)1 - zz(m)*zz(m) ); // sin2theta = 1 - cos2theta.\n\t\t\teuler[2] = std::asin( pos_sin_theta );\n\t\t\tif ( zz(m) < 0 ) {\n\t\t\t\teuler[2] = pi - euler[2];\n\t\t\t}\n\t\t\teuler[0] = std::atan2( xz(m), -yz(m) );\n\t\t\teuler[1] = std::atan2( zx(m),  zy(m) );\n\t\t}\n\t\teuler[0] += euler[0]<0.0 ? pi_2 : 0.0;\n\t\teuler[1] += euler[1]<0.0 ? pi_2 : 0.0;\n\n\t\teuler[0] = std::min(  std::max( 0.0, euler[0] ),  pi_2-epsilon  );\n\t\teuler[1] = std::min(  std::max( 0.0, euler[1] ),  pi_2-epsilon  );\n\t\teuler[2] = std::min(  std::max( 0.0, euler[2] ),  pi  -epsilon  );\n\n\t\tassert( 0 <= euler[0] ); assert( euler[0] <  pi_2 );\n\t\tassert( 0 <= euler[1] ); assert( euler[1] <  pi_2 );\n\t\tassert( 0 <= euler[2] ); assert( euler[2] <= pi   );\n\t}\n\n\t///@brief euler to matrix\n\ttemplate<class M, class E> void\n\tfrom_euler_angles( E const & euler, M & m ){\n\t\ttypedef typename get_scalar<M>::type T;\n\t\tT const ce1( std::cos( euler[0] ) ),  se1( std::sin( euler[0] ) );\n\t\tT const ce2( std::cos( euler[1] ) ),  se2( std::sin( euler[1] ) );\n\t\tT const ce3( std::cos( euler[2] ) ),  se3( std::sin( euler[2] ) );\n\t\txx(m) =  ce2 * ce1 - ce3 * se1 * se2;  yx(m) =  ce2 * se1 + ce3 * ce1 * se2;  zx(m) =  se2 * se3;\n\t\txy(m) = -se2 * ce1 - ce3 * se1 * ce2;  yy(m) = -se2 * se1 + ce3 * ce1 * ce2;  zy(m) =  ce2 * se3;\n\t\txz(m) =                    se3 * se1;  yz(m) =                   -se3 * ce1;  zz(m) =        ce3;\n\t}\n\n\ttemplate<class M, class E> void\n\teuler_angles_deg(M const & m, E & euler) {\n\t\ttypedef typename get_scalar<M>::type T;\n\t\tstatic T const rad_to_deg = 180.0 / boost::math::constants::pi<T>();\n\t\teuler_angles(m,euler);\n\t\teuler[0] = euler[0] * rad_to_deg;\n\t\teuler[1] = euler[1] * rad_to_deg;\n\t\teuler[2] = euler[2] * rad_to_deg;\t\t\t\t\n\t}\n\ttemplate<class M, class E> void\n\tfrom_euler_angles_deg(E const & erad, M & m) {\n\t\ttypedef typename get_scalar<M>::type T;\n\t\tstatic T const deg_to_rad = boost::math::constants::pi<T>() / 180.0;\n\t\tE euler; euler[0];\n\t\teuler[0] = erad[0] * deg_to_rad;\n\t\teuler[1] = erad[1] * deg_to_rad;\n\t\teuler[2] = erad[2] * deg_to_rad;\t\t\t\t\n\t\teuler_angles(m,euler);\n\t}\n\n}}\n\n#endif\n", "meta": {"hexsha": "c2e4f8d26d794657f9e311011cbe90611dbb57be", "size": 8021, "ext": "hh", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/numeric/euler_angles.hh", "max_stars_repo_name": "YaoYinYing/rifdock", "max_stars_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T01:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:16:08.000Z", "max_issues_repo_path": "schemelib/scheme/numeric/euler_angles.hh", "max_issues_repo_name": "YaoYinYing/rifdock", "max_issues_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-30T17:45:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:02:44.000Z", "max_forks_repo_path": "schemelib/scheme/numeric/euler_angles.hh", "max_forks_repo_name": "YaoYinYing/rifdock", "max_forks_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T01:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:56:17.000Z", "avg_line_length": 46.9064327485, "max_line_length": 129, "alphanum_fraction": 0.5921954868, "num_tokens": 2618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5449169888981954}}
{"text": "#include <opencv2/opencv.hpp>\n#include <vector>\n#include <string>\n#include <Eigen/Core>\n#include <pangolin/pangolin.h>\n#include <unistd.h>\n\n\nusing namespace std;\nusing namespace Eigen;\n\n// \u6587\u4ef6\u8def\u5f84\nstring left_file = \"./left.png\";\nstring right_file = \"./right.png\";\n\n\nvoid showPointCloud(\n    const vector<Vector4d, Eigen::aligned_allocator<Vector4d>> &pointcloud);\n\nint main(int argc, char **argv) {\n    double fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n    double b=0.573;\n\n    cv::Mat left=cv::imread(left_file);\n    cv::Mat right=cv::imread(right_file);\n    cv::Ptr<cv::StereoSGBM> sgbm = cv::StereoSGBM::create(0, 96, 9, 8 * 9 * 9, 32 * 9 * 9, 1, 63, 10, 100, 32);\n    cv::Mat disparity_sgbm, disparity;\n    sgbm->compute(left,right,disparity_sgbm);\n    disparity_sgbm.convertTo(disparity,CV_32F,1.0/16.0f);//signed short 2byte -> float 4byte \n    \n    \n    vector<Vector4d,Eigen::aligned_allocator<Vector4d>> pointcloud;\n\n    cout<<left.rows<<\" \"<<left.cols<<\" \"<<left.step[0]<<\" \"<<left.step[1]<<\" \"<<left.channels()<<endl;\n    cout<<disparity_sgbm.rows<<\" \"<<disparity_sgbm.cols<<\" \"<<disparity_sgbm.step[0]<<\" \"<<disparity_sgbm.step[1]<<\" \"<<disparity_sgbm.channels()<<endl;\n    cout<<disparity.rows<<\" \"<<disparity.cols<<\" \"<<disparity.step[0]<<\" \"<<disparity.step[1]<<\" \"<<disparity.channels()<<endl;\n\n    cout<<disparity_sgbm.type()<<\" \"<<disparity.type()<<\" \"<<disparity_sgbm.at<short>(10,0)<<\" \"<< disparity.at<float>(10,0)<<endl;\n/*\n+--------+----+----+----+----+------+------+------+------+\n|        | C1 | C2 | C3 | C4 | C(5) | C(6) | C(7) | C(8) |\n+--------+----+----+----+----+------+------+------+------+\n| CV_8U  |  0 |  8 | 16 | 24 |   32 |   40 |   48 |   56 |\n| CV_8S  |  1 |  9 | 17 | 25 |   33 |   41 |   49 |   57 |\n| CV_16U |  2 | 10 | 18 | 26 |   34 |   42 |   50 |   58 |\n| CV_16S |  3 | 11 | 19 | 27 |   35 |   43 |   51 |   59 |\n| CV_32S |  4 | 12 | 20 | 28 |   36 |   44 |   52 |   60 |\n| CV_32F |  5 | 13 | 21 | 29 |   37 |   45 |   53 |   61 |\n| CV_64F |  6 | 14 | 22 | 30 |   38 |   46 |   54 |   62 |\n+--------+----+----+----+----+------+------+------+------+\n*/\n    for(int v=0;v<left.rows;v++)\n    {\n        for(int u=0;u<left.cols;u++)\n        {\n            if(disparity.at<float>(v,u)<=0||disparity.at<float>(v,u)>=96.0) continue;\n\n            Vector4d point(0,0,0,left.at<uchar>(v,u)/255.0);\n\n            double depth=b*fx/(disparity.at<float>(v,u));//disparity in pixel\n            double x=depth*(u-cx)/fx;\n            double y=depth*(v-cy)/fy;\n            \n            point[0]=x;\n            point[1]=y;\n            point[2]=depth;\n \n           \n            pointcloud.push_back(point);\n            //cout<<(int)left.at<Eigen::Matrix<uchar,3,1>>(v,u)[0]<<\" \"<<(int)left.at<Eigen::Matrix<uchar,3,1>>(v,u)[1]<<\" \"<<(int)left.at<Eigen::Matrix<uchar,3,1>>(v,u)[2]<<\" \"<<endl;\n            //cout<<point<<endl;       \n            \n        }\n      \n        \n\n    }\n    cv::imshow(\"disparity\",disparity/255.0);\n    cv::waitKey(0);\n    showPointCloud(pointcloud);\n    return 0;\n\n\n    \n}\n\nvoid showPointCloud(const vector<Vector4d, Eigen::aligned_allocator<Vector4d>> &pointcloud) {\n\n    if (pointcloud.empty()) {\n        cerr << \"Point cloud is empty!\" << endl;\n        return;\n    }\n\n    pangolin::CreateWindowAndBind(\"Point Cloud 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    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        glPointSize(2);\n        glBegin(GL_POINTS);\n        for (auto &p: pointcloud) {\n            glColor3f(p[3], p[3], p[3]);\n            glVertex3d(p[0], p[1], p[2]);\n        }\n        glEnd();\n        pangolin::FinishFrame();\n        usleep(5000);   // sleep 5 ms\n    }\n    return;\n}", "meta": {"hexsha": "8bf0238f7e783643b13081eaabe5a21f5f036ced", "size": 4271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch5/stereo/stereoVision.cpp", "max_stars_repo_name": "yejun1204/slambook2", "max_stars_repo_head_hexsha": "ed1c72226b16b1c4f159f2c030394f0eeaec5ed3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch5/stereo/stereoVision.cpp", "max_issues_repo_name": "yejun1204/slambook2", "max_issues_repo_head_hexsha": "ed1c72226b16b1c4f159f2c030394f0eeaec5ed3", "max_issues_repo_licenses": ["MIT"], "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/stereo/stereoVision.cpp", "max_forks_repo_name": "yejun1204/slambook2", "max_forks_repo_head_hexsha": "ed1c72226b16b1c4f159f2c030394f0eeaec5ed3", "max_forks_repo_licenses": ["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.168, "max_line_length": 184, "alphanum_fraction": 0.5340669632, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5449169820947073}}
{"text": "//PerpAmerOption.hpp\n\n//Perpetual American Option class\n\n#ifndef PerpAmerOption_hpp\n#define PerpAmerOption_cpp\n\n#include \"Option.hpp\"\n#include \"GlobalFunctions.hpp\"\n#include <vector>\n#include <boost/math/distributions/normal.hpp>\n\n\n//Perpetual american option class will be derived from Option base class and hold no data members\nclass PerpAmerOption : public Option\n{\npublic:\n\tPerpAmerOption() : Option() {}\n\tPerpAmerOption(double S, double K, double r, double sig, double b) : Option(S, K, r, sig, b) {}\n\tPerpAmerOption(PerpAmerOption& source) : Option(source) {}\n\n\t~PerpAmerOption() {}\n\n\tPerpAmerOption& operator = (const PerpAmerOption& source);\n\n\t//All the setters and Getters are inherited\n\n\tdouble CallPrice()const { return PerpetualCall(S, K, r, sig, b); }\n\tdouble PutPrice()const { return PerpetualPut(S, K, r, sig, b); }\n\tdouble CallPrice_S(double S1) const { return PerpetualCall(S1, K, r, sig, b); }\n\tdouble PutPrice_S(double S1) const { return PerpetualPut(S1, K, r, sig, b); }\n\n\t//Pricing function that returns vector. Used in combination with function pointer for better versatility\n\ttypedef double(PerpAmerOption::*FunctionPointer)(double)const;\n\tstd::vector<double> Range_of_Prices(double LowerLimit, double UpperLimit, int Num, FunctionPointer Ptr);\n\n\n\n\n};\n\n\n\n#endif\n", "meta": {"hexsha": "d408d5b4541e2b3c163f2c8dadd8166221880b4d", "size": 1285, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PerpAmerOption.hpp", "max_stars_repo_name": "IlyaKul/OptionPricers", "max_stars_repo_head_hexsha": "4907e77994e75697ba7673673536c0312cd1e063", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PerpAmerOption.hpp", "max_issues_repo_name": "IlyaKul/OptionPricers", "max_issues_repo_head_hexsha": "4907e77994e75697ba7673673536c0312cd1e063", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PerpAmerOption.hpp", "max_forks_repo_name": "IlyaKul/OptionPricers", "max_forks_repo_head_hexsha": "4907e77994e75697ba7673673536c0312cd1e063", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5555555556, "max_line_length": 105, "alphanum_fraction": 0.7486381323, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5449106618152912}}
{"text": "#include \"drake/solvers/dreal_solver.h\"\n\n#include <vector>\n\n#include <Eigen/Core>\n#include <gtest/gtest.h>\n\n#include \"drake/solvers/mathematical_program.h\"\n#include \"drake/solvers/test/generic_trivial_constraints.h\"\n#include \"drake/solvers/test/generic_trivial_costs.h\"\n\nnamespace drake {\nnamespace solvers {\nnamespace {\n\nusing symbolic::Expression;\nusing symbolic::Formula;\nusing symbolic::Variable;\nusing symbolic::Variables;\n\nusing std::logic_error;\nusing std::make_shared;\nusing std::shared_ptr;\nusing std::vector;\n\nclass DrealSolverTest : public ::testing::Test {\n protected:\n  void SetUp() override { xvec_ = prog_.NewContinuousVariables(4, \"x\"); }\n\n  // Continuous variables.\n  const Variable x_{\"x\", Variable::Type::CONTINUOUS};\n  const Variable y_{\"y\", Variable::Type::CONTINUOUS};\n  const Variable z_{\"z\", Variable::Type::CONTINUOUS};\n\n  // Integer variables.\n  const Variable i_{\"i\", Variable::Type::INTEGER};\n  const Variable j_{\"j\", Variable::Type::INTEGER};\n\n  // Binary variables.\n  const Variable binary1_{\"binary1\", Variable::Type::BINARY};\n  const Variable binary2_{\"binary2\", Variable::Type::BINARY};\n\n  // Boolean variables.\n  const Variable b1_{\"b1\", Variable::Type::BOOLEAN};\n  const Variable b2_{\"b2\", Variable::Type::BOOLEAN};\n  const Variable b3_{\"b3\", Variable::Type::BOOLEAN};\n\n  const double delta_{0.001};\n  MathematicalProgram prog_;\n  VectorXDecisionVariable xvec_;\n  DrealSolver solver_;\n};\n\nTEST_F(DrealSolverTest, Interval) {\n  const double low{-10.0};\n  const double high{10.0};\n  DrealSolver::Interval i{low, high};\n\n  EXPECT_EQ(i.low(), low);\n  EXPECT_EQ(i.high(), high);\n  EXPECT_EQ(i.mid(), 0.0);\n  EXPECT_EQ(i.diam(), 20.0);\n}\n\nTEST_F(DrealSolverTest, Available) {\n  if (solver_.available()) {\n    const auto result = DrealSolver::CheckSatisfiability(\n        Expression{0.0} > Expression{1.0}, delta_);\n    ASSERT_FALSE(result);\n  }\n}\n\n// 0.0 > 1.0 is trivially UNSAT.\nTEST_F(DrealSolverTest, CheckSatisfiabilityTrivialUnsat) {\n  if (solver_.available()) {\n    const auto result = DrealSolver::CheckSatisfiability(\n        Expression{0.0} > Expression{1.0}, delta_);\n    ASSERT_FALSE(result);\n  }\n}\n\n// 1.0 > 0.0 is trivially SAT.\nTEST_F(DrealSolverTest, CheckSatisfiabilityTrivialSat) {\n  if (solver_.available()) {\n    const auto result = DrealSolver::CheckSatisfiability(\n        Expression{1.0} > Expression{0.0}, delta_);\n    ASSERT_TRUE(result);\n    // The result is an empty box.\n    EXPECT_EQ(result->size(), 0.0);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityConjunction) {\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(b1_ && !b2_ && !b3_, delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    // We should have a point solution (i.e. lower-bound == upper-bound).\n    EXPECT_EQ(solution.at(b1_).diam(), 0);\n    EXPECT_EQ(solution.at(b2_).diam(), 0);\n    EXPECT_EQ(solution.at(b3_).diam(), 0);\n    const double v1{solution.at(b1_).mid()};\n    const double v2{solution.at(b2_).mid()};\n    const double v3{solution.at(b3_).mid()};\n    // Should be either 1.0 (representing True) or 0.0 (False).\n    EXPECT_TRUE(v1 == 1.0 || v1 == 0.0);\n    EXPECT_TRUE(v2 == 1.0 || v2 == 0.0);\n    EXPECT_TRUE(v3 == 1.0 || v3 == 0.0);\n    EXPECT_TRUE(v1 && !v2 && !v3);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityDisjunction) {\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(b1_ || !b2_ || b3_, delta_);\n    const DrealSolver::IntervalBox& solution{*result};\n    // We should have a point solution (i.e. lower-bound == upper-bound).\n    EXPECT_EQ(solution.at(b1_).diam(), 0);\n    EXPECT_EQ(solution.at(b2_).diam(), 0);\n    EXPECT_EQ(solution.at(b3_).diam(), 0);\n    const double v1{solution.at(b1_).mid()};\n    const double v2{solution.at(b2_).mid()};\n    const double v3{solution.at(b3_).mid()};\n    // Should be either 1.0 (representing True) or 0.0 (False).\n    EXPECT_TRUE(v1 == 1.0 || v1 == 0.0);\n    EXPECT_TRUE(v2 == 1.0 || v2 == 0.0);\n    EXPECT_TRUE(v3 == 1.0 || v3 == 0.0);\n    EXPECT_TRUE(v1 || !v2 || v3);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityLinearReal) {\n  const Formula f1{0 <= x_ && x_ <= 5};\n  const Formula f2{0 <= y_ && y_ <= 5};\n  const Formula f3{2 * x_ + 3 * y_ == 5 && -3 * x_ + 4 * y_ == 6};\n\n  if (solver_.available()) {\n    const auto result = DrealSolver::CheckSatisfiability(f1 && f2 && f3,\n                                                         delta_);\n    ASSERT_TRUE(result);\n\n    const DrealSolver::IntervalBox& solution{*result};\n    const double expected_x{2.0 / 17.0};\n    const double expected_y{27.0 / 17.0};\n    EXPECT_NEAR(solution.at(x_).mid(), expected_x, delta_);\n    EXPECT_NEAR(solution.at(y_).mid(), expected_y, delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityLinearInteger) {\n  const Formula f1{0 <= i_ && i_ <= 5};\n  const Formula f2{0 <= j_ && j_ <= 5};\n  const Formula f3{2 * i_ + 3 * j_ == 5 && -3 * i_ + 4 * j_ == 6};\n  if (solver_.available()) {\n    const auto result = DrealSolver::CheckSatisfiability(f1 && f2 && f3,\n                                                         delta_);\n    // Note that this has the same constraint as the previous,\n    // CheckSatisfiabilityLinearReal test. However, the domain constraint, i,j \u2208\n    // Z, makes the problem unsatisfiable.\n    EXPECT_FALSE(result);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityBinaryVariables) {\n  const Formula f{2 * binary1_ + 3 * binary2_ == 0};\n  if (solver_.available()) {\n    const auto result = DrealSolver::CheckSatisfiability(f, delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    // Because of the domain constraints, the only solution is {binary1 \u21a6 0,\n    // binary2 \u21a6 0}.\n    EXPECT_EQ(solution.at(binary1_).mid(), 0.0);\n    EXPECT_EQ(solution.at(binary2_).mid(), 0.0);\n    // They are points.\n    EXPECT_EQ(solution.at(binary1_).diam(), 0.0);\n    EXPECT_EQ(solution.at(binary2_).diam(), 0.0);\n  }\n}\n\n// Tests CheckSatisfiability (\u03b4-SAT case).\nTEST_F(DrealSolverTest, CheckSatisfiabilityDeltaSat) {\n  // Find a model satisfying the following constraints:\n  //     0 \u2264 x \u2264 5\n  //     0 \u2264 y \u2264 5\n  //     0 \u2264 z \u2264 5\n  //     2x\u00b2 + y = z\n  const Formula f1{0 <= x_ && x_ <= 5};\n  const Formula f2{0 <= y_ && y_ <= 5};\n  const Formula f3{0 <= z_ && z_ <= 5};\n  const Formula f4{2 * x_ * x_ + y_ == z_};\n\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(f1 && f2 && f3 && f4, delta_);\n    ASSERT_TRUE(result);\n\n    const double x{result->at(x_).mid()};\n    const double y{result->at(y_).mid()};\n    const double z{result->at(z_).mid()};\n    EXPECT_TRUE(0 <= x && x <= 5);\n    EXPECT_TRUE(0 <= y && y <= 5);\n    EXPECT_TRUE(0 <= z && z <= 5);\n    EXPECT_NEAR(2 * x * x + y, z, delta_);\n  }\n}\n\n// Tests CheckSatisfiability (UNSAT case).\nTEST_F(DrealSolverTest, CheckSatisfiabilityUnsat) {\n  // Find a model satisfying the following constraints:\n  //     2x\u00b2 + 6x + 5 < 0\n  //     -10 \u2264 x \u2264 10\n  const Formula f1{2 * x_ * x_ + 6 * x_ + 5 < 0};\n  const Formula f2{-10 <= x_ && x_ <= 10};\n\n  if (solver_.available()) {\n    const auto result = DrealSolver::CheckSatisfiability(f1 && f2, delta_);\n    EXPECT_FALSE(result);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityNonlinear) {\n  // Find a model satisfying the following constraints:\n  //     x = 4\n  //     y >= abs(-x\u00b2)\n  //     sqrt(y) / 4 \u2260 1\n  //     25 > y\n  const Formula f1{x_ == 4};\n  const Formula f2{y_ >= abs(-x_ * x_)};\n  const Formula f3{sqrt(y_) / 4 != 1};\n  const Formula f4{y_ > 25};\n\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(f1 && f2 && f3 && f4, delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    EXPECT_NEAR(x, 4.0, delta_);  // f1\n    EXPECT_TRUE(y >= std::abs(-x * x) - delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityLog) {\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(x_ == 4 && y_ == log(x_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    EXPECT_EQ(x, 4.0);\n    EXPECT_NEAR(y, std::log(4.0), delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityExp) {\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(x_ == 4 && y_ == exp(x_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    EXPECT_EQ(x, 4.0);\n    EXPECT_NEAR(y, std::exp(4.0), delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilitySin) {\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(x_ == 4 && y_ == sin(x_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    EXPECT_EQ(x, 4.0);\n    EXPECT_NEAR(y, std::sin(4.0), delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityCos) {\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(x_ == 4 && y_ == cos(x_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    EXPECT_EQ(x, 4.0);\n    EXPECT_NEAR(y, std::cos(4.0), delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityTan) {\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(x_ == 4 && y_ == tan(x_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    EXPECT_EQ(x, 4.0);\n    EXPECT_NEAR(y, std::tan(4.0), delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityAsin) {\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(x_ == 0.5 && y_ == asin(x_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    EXPECT_EQ(x, 0.5);\n    EXPECT_NEAR(y, std::asin(0.5), delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityAcos) {\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(x_ == 0.5 && y_ == acos(x_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    EXPECT_EQ(x, 0.5);\n    EXPECT_NEAR(y, std::acos(0.5), delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityAtan) {\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(x_ == 4 && y_ == atan(x_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    EXPECT_EQ(x, 4.0);\n    EXPECT_NEAR(y, std::atan(4.0), delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityAtan2) {\n  if (solver_.available()) {\n    const auto result = DrealSolver::CheckSatisfiability(\n        x_ == 4 && y_ == 3 && z_ == atan2(x_, y_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    const double z{solution.at(z_).mid()};\n    EXPECT_EQ(x, 4.0);\n    EXPECT_EQ(y, 3.0);\n    EXPECT_NEAR(z, std::atan2(4.0, 3.0), delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilitySinh) {\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(x_ == 0.5 && y_ == sinh(x_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    EXPECT_EQ(x, 0.5);\n    EXPECT_NEAR(y, std::sinh(0.5), delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityCosh) {\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(x_ == 0.5 && y_ == cosh(x_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    EXPECT_EQ(x, 0.5);\n    EXPECT_NEAR(y, std::cosh(0.5), delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityTanh) {\n  if (solver_.available()) {\n    const auto result =\n        DrealSolver::CheckSatisfiability(x_ == 4 && y_ == tanh(x_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    EXPECT_EQ(x, 4.0);\n    EXPECT_NEAR(y, std::tanh(4.0), delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityMin) {\n  if (solver_.available()) {\n    const auto result = DrealSolver::CheckSatisfiability(\n        x_ == 4 && y_ == 3 && z_ == min(x_, y_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    const double z{solution.at(z_).mid()};\n    EXPECT_EQ(x, 4.0);\n    EXPECT_EQ(y, 3.0);\n    EXPECT_EQ(z, std::min(4.0, 3.0));\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityMax) {\n  if (solver_.available()) {\n    const auto result = DrealSolver::CheckSatisfiability(\n        x_ == 4 && y_ == 3 && z_ == max(x_, y_), delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    const double y{solution.at(y_).mid()};\n    const double z{solution.at(z_).mid()};\n    EXPECT_EQ(x, 4.0);\n    EXPECT_EQ(y, 3.0);\n    EXPECT_EQ(z, std::max(4.0, 3.0));\n  }\n}\n\nTEST_F(DrealSolverTest, CheckSatisfiabilityForall) {\n  // To test `forall` formulas, encode the problem of minimizing x\u00b2 in\n  // exist-forall formula.\n  //\n  //     min x\u00b2 s.t. x \u2208 [-3, 3].\n  // ->  \u2203x. (-3 \u2264 x) \u2227 (x \u2264 3) \u2227 [\u2200y. ((-3 \u2264 y) \u2227 (y \u2264 3)) \u2192 (x\u00b2 \u2264 y\u00b2)]\n  // ->  \u2203x. (-3 \u2264 x) \u2227 (x \u2264 3) \u2227 [\u2200y. \u00ac((-3 \u2264 y) \u2227 (y \u2264 3)) \u2228 (x\u00b2 \u2264 y\u00b2)]\n  if (solver_.available()) {\n    const auto result = DrealSolver::CheckSatisfiability(\n        (-3 <= x_) && (x_ <= 3) &&\n            forall({y_}, !((-3 <= y_) && (y_ <= 3)) || (x_ * x_ <= y_ * y_)),\n        delta_);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    EXPECT_NEAR(x, 0.0, delta_);\n  }\n}\n\nTEST_F(DrealSolverTest, Minimize1) {\n  // Minimize 2x\u00b2 + 6x + 5 s.t. -4 \u2264 x \u2264 0\n  // The known minimum cost is -0.5.\n  const Expression objective{2 * x_ * x_ + 6 * x_ + 5};\n  const Formula constraint{-10 <= x_ && x_ <= 10};\n  const double delta{0.01};\n  const double known_minimum{0.5};\n\n  if (solver_.available()) {\n    const auto result = DrealSolver::Minimize(\n        objective, constraint, delta, DrealSolver::LocalOptimization::kUse);\n    ASSERT_TRUE(result);\n    const DrealSolver::IntervalBox& solution{*result};\n    const double x{solution.at(x_).mid()};\n    EXPECT_TRUE(-10 <= x && x <= 10);\n    EXPECT_LT(2 * x * x + 6 * x + 5, known_minimum + delta);\n  }\n}\n\nTEST_F(DrealSolverTest, Minimize2) {\n  // Minimize sin(3x) - 2cos(x) s.t. -3 \u2264 x \u2264 3\n  // The known minimum cost is -2.77877.\n  const Expression objective{sin(3 * x_) - 2 * cos(x_)};\n  const Formula constraint{-3 <= x_ && x_ <= 3};\n  const double delta{0.001};\n  const double known_minimum{-2.77877};\n  if (solver_.available()) {\n    const auto result = DrealSolver::Minimize(\n        objective, constraint, delta, DrealSolver::LocalOptimization::kUse);\n    ASSERT_TRUE(result);\n    const double x{result->at(x_).mid()};\n    EXPECT_TRUE(-3 <= x && x <= 3);\n    EXPECT_LT(sin(3 * x) - 2 * cos(x), known_minimum + delta);\n  }\n}\n\nTEST_F(DrealSolverTest, Minimize3) {\n  // Minimize sin(3x) s.t. (-3 \u2264 x \u2264 3) \u2227 (x\u00b2 - 16 = 0)\n  // Note that the side constraints have no model.\n  const Expression objective{sin(3 * x_)};\n  const Formula constraint{-3 <= x_ && x_ <= 3 && (x_ * x_ - 16 == 0)};\n  if (solver_.available()) {\n    const auto result = DrealSolver::Minimize(\n        objective, constraint, delta_, DrealSolver::LocalOptimization::kUse);\n    EXPECT_FALSE(result);\n  }\n}\n\nTEST_F(DrealSolverTest, UnsupportedFormulaIsnan) {\n  if (solver_.available()) {\n    EXPECT_THROW(DrealSolver::CheckSatisfiability(isnan(x_), delta_),\n                 std::runtime_error);\n  }\n}\n\nTEST_F(DrealSolverTest, UnsupportedFormulaCeil) {\n  if (solver_.available()) {\n    EXPECT_THROW(DrealSolver::CheckSatisfiability(ceil(x_) == 0, delta_),\n                 std::runtime_error);\n  }\n}\n\nTEST_F(DrealSolverTest, UnsupportedFormulaFloor) {\n  if (solver_.available()) {\n    EXPECT_THROW(DrealSolver::CheckSatisfiability(floor(x_) == 0, delta_),\n                 std::runtime_error);\n  }\n}\n\nTEST_F(DrealSolverTest, IfThenElse1) {\n  const Formula f{x_ == 3 && y_ == 2 && z_ == if_then_else(x_ > y_, x_, y_)};\n  if (solver_.available()) {\n    const auto result = DrealSolver::CheckSatisfiability(f, delta_);\n    ASSERT_TRUE(result);\n    const double z{result->at(z_).mid()};\n    EXPECT_EQ(z, 3);\n  }\n}\n\nTEST_F(DrealSolverTest, IfThenElse2) {\n  const Formula f{x_ == 2 && y_ == 3 && z_ == if_then_else(x_ > y_, x_, y_)};\n  if (solver_.available()) {\n    const auto result = DrealSolver::CheckSatisfiability(f, delta_);\n    ASSERT_TRUE(result);\n    const double z{result->at(z_).mid()};\n    EXPECT_EQ(z, 3);\n  }\n}\n\nTEST_F(DrealSolverTest, UnsupportedFormulaUninterpretedFunction) {\n  if (solver_.available()) {\n    EXPECT_THROW(\n        DrealSolver::CheckSatisfiability(\n            symbolic::uninterpreted_function(\"uf\", {x_, y_}) == 0, delta_),\n        std::runtime_error);\n  }\n}\n\nTEST_F(DrealSolverTest, UnsupportedFormulaPositiveSemidefinite) {\n  Eigen::Matrix<Expression, 2, 2> m;\n  m << (x_ + y_), -1.0, -1.0, y_;\n  if (solver_.available()) {\n    EXPECT_THROW(\n        DrealSolver::CheckSatisfiability(positive_semidefinite(m), delta_),\n        std::runtime_error);\n  }\n}\n\nTEST_F(DrealSolverTest, SolveLinearProgramming) {\n  // Linear Cost + BoundingBox constraints + Linear constraint\n  const Variable& x0{xvec_(0)};\n  const Variable& x1{xvec_(1)};\n  prog_.AddConstraint(x0, 100, 200);\n  prog_.AddConstraint(x1, 80, 170);\n  prog_.AddConstraint(x1 >= -x0 + 200);\n  prog_.AddCost(2 * x0 - 5 * x1);\n  if (solver_.available()) {\n    auto result = solver_.Solve(prog_, {}, {});\n    ASSERT_TRUE(result.is_success());\n    const double delta{0.001};\n    const double v0{result.GetSolution(x0)};\n    const double v1{result.GetSolution(x1)};\n    EXPECT_TRUE(100 - delta <= v0 && v0 <= 200 + delta);\n    EXPECT_TRUE(80 - delta <= v1 && v1 <= 170 + delta);\n    EXPECT_TRUE(v1 >= -v0 + 200 - delta);\n    EXPECT_NEAR(2 * v0 - 5 * v1, 2 * 100 - 5 * 170 /* known minimum */,\n                delta * 5.0);\n  }\n}\n\nTEST_F(DrealSolverTest, SolveQuadraticProgramming) {\n  // Linear Cost + BoundingBox constraints + Linear constraint\n  const Variable& x0{xvec_(0)};\n  const Variable& x1{xvec_(1)};\n  prog_.AddConstraint(x0, 0, 20);\n  prog_.AddConstraint(x1 >= 0);\n  prog_.AddConstraint(2 * x0 + x1 >= 2);\n  prog_.AddConstraint(-x0 + 2 * x1 <= 6);\n  prog_.AddCost(4 + 1.5 * x0 - 2 * x1 + 4 * x0 * x0 + 2 * x0 + x1 +\n                5 * x1 * x1);\n  const double delta{1e-5};\n  prog_.SetSolverOption(DrealSolver::id(), \"precision\", delta);\n  prog_.SetSolverOption(DrealSolver::id(), \"use_local_optimization\", 0);\n  if (solver_.available()) {\n    auto result = solver_.Solve(prog_, {}, {});\n    ASSERT_TRUE(result.is_success());\n    const double v0{result.GetSolution(x0)};\n    const double v1{result.GetSolution(x1)};\n    EXPECT_TRUE(0 - delta <= v0 && v0 <= 20 + delta);\n    EXPECT_TRUE(0 - delta <= v1);\n    EXPECT_TRUE(2 * v0 + v1 >= 2 - delta);\n    EXPECT_NEAR(4 + 1.5 * v0 - 2 * v1 + 4 * v0 * v0 + 2 * v0 + v1 + 5 * v1 * v1,\n                4 + 1.5 * 0.71875 - 2 * 0.5625 + 4 * 0.71875 * 0.71875 +\n                    2 * 0.71875 + 0.5625 + 5 * 0.5625 * 0.5625,\n                delta * 5.0);\n  }\n}\n\nTEST_F(DrealSolverTest, SolveLinearEqualityConstraint) {\n  const Variable& x0{xvec_(0)};\n  const Variable& x1{xvec_(1)};\n  prog_.AddConstraint(x0, -5, 5);\n  prog_.AddConstraint(x1, -5, 5);\n  prog_.AddConstraint(2 * x0 + 3 * x1 == 2);\n  prog_.AddConstraint(-3 * x0 + 4 * x1 <= 0);\n  const double delta{1e-3};\n  if (solver_.available()) {\n    auto result = solver_.Solve(prog_, {}, {});\n    ASSERT_TRUE(result.is_success());\n    const double v0{result.GetSolution(x0)};\n    const double v1{result.GetSolution(x1)};\n    EXPECT_NEAR(2 * v0 + 3 * v1, 2.0, delta);\n    EXPECT_TRUE(-3 * v0 + 4 * v1 <= delta);\n  }\n}\n\nTEST_F(DrealSolverTest, SolveQuadraticConstraint) {\n  const Variable& x0{xvec_(0)};\n  const Variable& x1{xvec_(1)};\n  prog_.AddConstraint(x0, 0, 5);\n  prog_.AddConstraint(x1, 0, 5);\n  prog_.AddConstraint(x0 <= x1 * x1);\n  prog_.AddConstraint(x1 * x1 - 0.0001 <= x0);\n  prog_.AddConstraint(x0 == 3.0);\n  const double delta{1e-3};\n  if (solver_.available()) {\n    auto result = solver_.Solve(prog_, {}, {});\n    ASSERT_TRUE(result.is_success());\n    const double v1{result.GetSolution(x1)};\n    EXPECT_NEAR(v1, 1.7320 /* sqrt(3.0) */, delta);\n  }\n}\n\nTEST_F(DrealSolverTest, SolveLorentzConeConstraint) {\n  const Variable& x0{xvec_(0)};\n  const Variable& x1{xvec_(1)};\n  const Variable& x2{xvec_(2)};\n  prog_.AddConstraint(x0, -5, 5);\n  prog_.AddConstraint(x1, -5, 5);\n  prog_.AddConstraint(x2, 0, 5);\n  prog_.AddLorentzConeConstraint(\n      Vector3<symbolic::Expression>(0 * x0 + 1, x0 - 1, x1 - 1));\n  prog_.AddLorentzConeConstraint(Vector3<symbolic::Expression>(x2, x0, x1));\n  prog_.AddCost(x2);\n  const double delta{1e-5};\n  prog_.SetSolverOption(DrealSolver::id(), \"precision\", delta);\n  if (solver_.available()) {\n    auto result = solver_.Solve(prog_, {}, {});\n    ASSERT_TRUE(result.is_success());\n    const double v2{result.GetSolution(x2)};\n    // We check if the found minimum (solution for x2) is close to the one from\n    // SCS solver.\n    EXPECT_NEAR(v2, /* Solution from SCS Solver */ 0.414212, delta * 5);\n  }\n}\n\nTEST_F(DrealSolverTest, SolveRotatedLorentzConeConstraint) {\n  const Variable& x0{xvec_(0)};\n  const Variable& x1{xvec_(1)};\n  const Variable& x2{xvec_(2)};\n  prog_.AddLinearCost(2 * x0 + 3 * x1 - 2 * x2);\n  prog_.AddConstraint(x0, -1, 1);\n  prog_.AddConstraint(x1, -1, 1);\n  prog_.AddConstraint(x2, -1, 1);\n  prog_.AddRotatedLorentzConeConstraint(\n      Vector4<symbolic::Expression>(x0 + x1, x1 + x2, +x0, +x1));\n  const double delta{1e-10};\n  prog_.SetSolverOption(DrealSolver::id(), \"precision\", delta);\n  if (solver_.available()) {\n    auto result = solver_.Solve(prog_, {}, {});\n    ASSERT_TRUE(result.is_success());\n    const double v0{result.GetSolution(x0)};\n    const double v1{result.GetSolution(x1)};\n    const double v2{result.GetSolution(x2)};\n    // We check if the found minimum (solution for 2x0 + 3x1 - 2x2) is close to\n    // the one from Gurobi solver.\n    EXPECT_NEAR(2 * v0 + 3 * v1 - 2 * v2,\n                /* Solution from Gurobi */\n                2 * 0.0953487 + 3 * -0.0787482 - 2 * 1,\n                1e-5);\n  }\n}\n\nTEST_F(DrealSolverTest, SolveLinearComplementarityConstraint) {\n  // The problem and the expected solution are copied from \"bard1\" test in\n  // solvers/test/complementary_problem_test.cc.\n  //\n  // A problem from J.F. Bard, Convex two-level optimization,\n  // Mathematical Programming 40(1), 15-27, 1988.\n  // min (x-5)\u00b2 + (2*y + 1)\u00b2\n  // s.t 2*(y-1) - 1.5*x + l(0) - 0.5*l(1) + l(2) = 0\n  //     0 <= l(0) \u22a5 3 * x - y - 3 >= 0\n  //     0 <= l(1) \u22a5 -x + 0.5*y + 4 >= 0\n  //     0 <= l(2) \u22a5 -x - y + 7 >= 0\n  //     x >= 0, y >= 0\n  const auto x = prog_.NewContinuousVariables<1>();\n  const auto y = prog_.NewContinuousVariables<1>();\n  const auto l = prog_.NewContinuousVariables<3>();\n  prog_.AddCost(pow(x(0) - 5, 2) + pow(2 * y(0) + 1, 2));\n  prog_.AddConstraint(x(0), -10, 10);\n  prog_.AddConstraint(y(0), -10, 10);\n  prog_.AddConstraint(l(0), -10, 10);\n  prog_.AddConstraint(l(1), -10, 10);\n  prog_.AddConstraint(l(2), -10, 10);\n  prog_.AddLinearConstraint(\n      2 * (y(0) - 1) - 1.5 * x(0) + l(0) - 0.5 * l(1) + l(2) == 0);\n  Eigen::Matrix<double, 5, 5> M;\n  // clang-format off\n  M <<  3,  -1, 0, 0, 0,\n       -1, 0.5, 0, 0, 0,\n       -1,  -1, 0, 0, 0,\n        0,   0, 0, 0, 0,\n        0,   0, 0, 0, 0;\n  // clang-format on\n  Eigen::Matrix<double, 5, 1> q;\n  q << -3, 4, 7, 0, 0;\n  prog_.AddLinearComplementarityConstraint(M, q, {x, y, l});\n  const double delta{1e-5};\n  prog_.SetSolverOption(DrealSolver::id(), \"precision\", delta);\n  if (solver_.available()) {\n    auto result = solver_.Solve(prog_, {}, {});\n    ASSERT_TRUE(result.is_success());\n    const auto x_val = result.GetSolution(x);\n    const auto y_val = result.GetSolution(y);\n    EXPECT_NEAR(x_val(0), 1, 1E-6);\n    EXPECT_NEAR(y_val(0), 0, 1E-6);\n  }\n}\n\nTEST_F(DrealSolverTest, SolveNonLinearConstraint) {\n  const Variable& x0{xvec_(0)};\n  prog_.AddConstraint(x0, -3.141592, 3.141592);\n  prog_.AddConstraint(sin(x0) + cos(x0), 0.4, 0.41);\n  const double delta{1e-5};\n  prog_.SetSolverOption(DrealSolver::id(), \"precision\", delta);\n  if (solver_.available()) {\n    auto result = solver_.Solve(prog_, {}, {});\n    ASSERT_TRUE(result.is_success());\n    const double v0{result.GetSolution(x0)};\n    EXPECT_TRUE(-3.141592 - delta <= v0 && v0 <= 3.141592 + delta);\n    EXPECT_TRUE(0.4 - delta <= sin(v0) + cos(v0));\n    EXPECT_TRUE(sin(v0) + cos(v0) <= 0.41 + delta);\n    // Add more constraints to make the problem infeasible.\n    prog_.AddConstraint(cos(x0) * sin(x0), 0.9, 0.91);\n    solver_.Solve(prog_, {}, {}, &result);\n    ASSERT_FALSE(result.is_success());\n    EXPECT_EQ(result.get_solution_result(),\n              SolutionResult::kInfeasibleConstraints);\n  }\n}\n\nTEST_F(DrealSolverTest, SolvePositiveSemidefiniteConstraint) {\n  // No support yet. Checks DrealSolver throws std::logic_error.\n  const auto X = prog_.NewSymmetricContinuousVariables<4>(\"X\");\n  prog_.AddPositiveSemidefiniteConstraint(X);\n  EXPECT_THROW(solver_.Solve(prog_, {}, {}), logic_error);\n}\n\nTEST_F(DrealSolverTest, SolveLinearMatrixInequalityConstraint) {\n  // No support yet. Checks DrealSolver throws std::logic_error.\n  prog_.AddLinearMatrixInequalityConstraint(\n      {Eigen::Matrix2d::Identity(), Eigen::Matrix2d::Ones(),\n       2 * Eigen::Matrix2d::Ones()},\n      xvec_.head<2>());\n  if (solver_.available()) {\n    EXPECT_THROW(solver_.Solve(prog_, {}, {}), logic_error);\n  }\n}\n\nTEST_F(DrealSolverTest, SolveMultipleCostFunctions) {\n  const Variable& x{xvec_(0)};\n  prog_.AddConstraint(x, -10, 10);\n  prog_.AddCost(-2 * x + 1);  // -2x + 1\n  prog_.AddCost(x * x);       // x\u00b2\n  if (solver_.available()) {\n    // Cost function = x\u00b2 - 2x + 1 = (x-1)\u00b2\n    auto result = solver_.Solve(prog_, {}, {});\n    ASSERT_TRUE(result.is_success());\n    const double v{result.GetSolution(x)};\n    EXPECT_NEAR(v, 1, 0.005);\n  }\n}\n\nTEST_F(DrealSolverTest, SolveGenericConstraint) {\n  const Variable& x0{xvec_(0)};\n  const Variable& x1{xvec_(1)};\n  const Variable& x2{xvec_(2)};\n  prog_.AddConstraint(x0, -10, 10);\n  prog_.AddConstraint(x1, -10, 10);\n  prog_.AddConstraint(x2, -10, 10);\n  // -1 <= x0 * x1 + x2 / x0 * 2 <= 2\n  // -2 <= x1 * x2 - x0 <= 1\n  const shared_ptr<Constraint> generic_trivial_constraint1 =\n      make_shared<test::GenericTrivialConstraint1>();\n  prog_.AddConstraint(Binding<Constraint>(\n      generic_trivial_constraint1, VectorDecisionVariable<3>(x0, x1, x2)));\n  if (solver_.available()) {\n    auto result = solver_.Solve(prog_, {}, {});\n    ASSERT_TRUE(result.is_success());\n    const double v0{result.GetSolution(x0)};\n    const double v1{result.GetSolution(x1)};\n    const double v2{result.GetSolution(x2)};\n    EXPECT_LE(-10, v0);\n    EXPECT_LE(v0, 10);\n    EXPECT_LE(-10, v1);\n    EXPECT_LE(v1, 10);\n    EXPECT_LE(-10, v2);\n    EXPECT_LE(v2, 10);\n    EXPECT_LE(-1, v0 * v1 + v2 / v0 * 2);\n    EXPECT_LE(v0 * v1 + v2 / v0 * 2, 2);\n    EXPECT_LE(-2, v1 * v2 - v0);\n    EXPECT_LE(v1 * v2 - v0, 1);\n  }\n}\n\nTEST_F(DrealSolverTest, SolveGenericCost) {\n  // No support yet. Checks DrealSolver throws std::logic_error.\n  const shared_ptr<Cost> generic_trivial_cost1 =\n      make_shared<test::GenericTrivialCost1>();\n  prog_.AddCost(\n      Binding<Cost>(generic_trivial_cost1,\n                    VectorDecisionVariable<3>(xvec_(0), xvec_(1), xvec_(2))));\n  EXPECT_THROW(solver_.Solve(prog_, {}, {}), logic_error);\n}\n\n}  // namespace\n\n}  // namespace solvers\n}  // namespace drake\n", "meta": {"hexsha": "2dce3f04f08d3dfa6b12b53bc36bbb3ea07d5dee", "size": 28748, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solvers/test/dreal_solver_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": "solvers/test/dreal_solver_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": "solvers/test/dreal_solver_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": 34.1425178147, "max_line_length": 80, "alphanum_fraction": 0.6334353694, "num_tokens": 9110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5449106564940881}}
{"text": "//\n// Copyright (c) 2015-2018 CNRS\n//\n\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/spatial/act-on-set.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n#include \"pinocchio/utils/timer.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\ntemplate<typename Derived>\ninline bool isFinite(const Eigen::MatrixBase<Derived> & x)\n{\n  return ((x - x).array() == (x - x).array()).all();\n}\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE ( test_jacobian )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  pinocchio::Data data(model);\n\n  VectorXd q = VectorXd::Zero(model.nq);\n  computeJointJacobians(model,data,q);\n\n  Model::Index idx = model.existJointName(\"rarm2\")?model.getJointId(\"rarm2\"):(Model::Index)(model.njoints-1); \n  Data::Matrix6x Jrh(6,model.nv); Jrh.fill(0);\n  getJointJacobian(model,data,idx,WORLD,Jrh);\n\n   /* Test J*q == v */\n  VectorXd qdot = VectorXd::Random(model.nv);\n  VectorXd qddot = VectorXd::Zero(model.nv);\n  rnea( model,data,q,qdot,qddot );\n  Motion v = data.oMi[idx].act( data.v[idx] );\n  BOOST_CHECK(v.toVector().isApprox(Jrh*qdot,1e-12));\n\n\n  /* Test local jacobian: rhJrh == rhXo oJrh */ \n  Data::Matrix6x rhJrh(6,model.nv); rhJrh.fill(0);\n  getJointJacobian(model,data,idx,LOCAL,rhJrh);\n  Data::Matrix6x XJrh(6,model.nv); \n  motionSet::se3Action( data.oMi[idx].inverse(), Jrh,XJrh );\n  BOOST_CHECK(XJrh.isApprox(rhJrh,1e-12));\n\n  XJrh.setZero();\n  Data data_jointJacobian(model);\n  jointJacobian(model,data_jointJacobian,q,idx,XJrh);\n  BOOST_CHECK(XJrh.isApprox(rhJrh,1e-12));\n  \n  /* Test computeJointJacobians with pre-computation of the forward kinematics */\n  Data data_fk(model);\n  forwardKinematics(model, data_fk, q);\n  computeJointJacobians(model, data_fk);\n  \n  BOOST_CHECK(data_fk.J.isApprox(data.J));\n\n}\n\nBOOST_AUTO_TEST_CASE ( test_jacobian_time_variation )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  pinocchio::Data data(model);\n  pinocchio::Data data_ref(model);\n  \n  VectorXd q = randomConfiguration(model, -1 * Eigen::VectorXd::Ones(model.nq), Eigen::VectorXd::Ones(model.nq) );\n  VectorXd v = VectorXd::Random(model.nv);\n  VectorXd a = VectorXd::Random(model.nv);\n  \n  computeJointJacobiansTimeVariation(model,data,q,v);\n  \n  BOOST_CHECK(isFinite(data.dJ));\n  \n  forwardKinematics(model,data_ref,q,v,a);\n  Model::Index idx = model.existJointName(\"rarm2\")?model.getJointId(\"rarm2\"):(Model::Index)(model.njoints-1);\n  \n  Data::Matrix6x J(6,model.nv); J.fill(0.);\n  Data::Matrix6x dJ(6,model.nv); dJ.fill(0.);\n  \n  // Regarding to the world origin\n  getJointJacobian(model,data,idx,WORLD,J);\n  getJointJacobianTimeVariation(model,data,idx,WORLD,dJ);\n  \n  Motion v_idx(J*v);\n  BOOST_CHECK(v_idx.isApprox(data_ref.oMi[idx].act(data_ref.v[idx])));\n  \n  Motion a_idx(J*a + dJ*v);\n  const Motion & a_ref = data_ref.oMi[idx].act(data_ref.a[idx]);\n  BOOST_CHECK(a_idx.isApprox(a_ref));\n  \n  \n  // Regarding to the local frame\n  getJointJacobian(model,data,idx,LOCAL,J);\n  getJointJacobianTimeVariation(model,data,idx,LOCAL,dJ);\n  \n  v_idx = (Motion::Vector6)(J*v);\n  BOOST_CHECK(v_idx.isApprox(data_ref.v[idx]));\n  \n  a_idx = (Motion::Vector6)(J*a + dJ*v);\n  BOOST_CHECK(a_idx.isApprox(data_ref.a[idx]));\n  \n  // compare to finite differencies\n  {\n    Data data_ref(model), data_ref_plus(model);\n    \n    const double alpha = 1e-8;\n    Eigen::VectorXd q_plus(model.nq);\n    q_plus = integrate(model,q,alpha*v);\n    \n    Data::Matrix6x J_ref(6,model.nv); J_ref.fill(0.);\n    computeJointJacobians(model,data_ref,q);\n    getJointJacobian(model,data_ref,idx,WORLD,J_ref);\n    \n    Data::Matrix6x J_ref_plus(6,model.nv); J_ref_plus.fill(0.);\n    computeJointJacobians(model,data_ref_plus,q_plus);\n    getJointJacobian(model,data_ref_plus,idx,WORLD,J_ref_plus);\n    \n    Data::Matrix6x dJ_ref(6,model.nv); dJ_ref.fill(0.);\n    dJ_ref = (J_ref_plus - J_ref)/alpha;\n    \n    computeJointJacobiansTimeVariation(model,data,q,v);\n    Data::Matrix6x dJ(6,model.nv); dJ.fill(0.);\n    getJointJacobianTimeVariation(model,data,idx,WORLD,dJ);\n    \n    BOOST_CHECK(dJ.isApprox(dJ_ref,sqrt(alpha)));\n  }\n}\n\n\n\nBOOST_AUTO_TEST_CASE ( test_timings )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  pinocchio::Data data(model);\n\n  long flag = BOOST_BINARY(1111);\n  PinocchioTicToc timer(PinocchioTicToc::US); \n  #ifdef NDEBUG\n    #ifdef _INTENSE_TESTING_\n      const size_t NBT = 1000*1000;\n    #else\n      const size_t NBT = 10;\n    #endif\n  #else \n    const size_t NBT = 1;\n    std::cout << \"(the time score in debug mode is not relevant)  \" ;\n  #endif\n\n  bool verbose = flag & (flag-1) ; // True is two or more binaries of the flag are 1.\n  if(verbose) std::cout <<\"--\" << std::endl;\n  Eigen::VectorXd q = Eigen::VectorXd::Zero(model.nq);\n\n  if( flag >> 0 & 1 )\n  {\n    timer.tic();\n    SMOOTH(NBT)\n    {\n      computeJointJacobians(model,data,q);\n    }\n    if(verbose) std::cout << \"Compute =\\t\";\n    timer.toc(std::cout,NBT);\n  }\n\n  if( flag >> 1 & 1 )\n  {\n    computeJointJacobians(model,data,q);\n    Model::Index idx = model.existJointName(\"rarm6\")?model.getJointId(\"rarm6\"):(Model::Index)(model.njoints-1); \n    Data::Matrix6x Jrh(6,model.nv); Jrh.fill(0);\n\n    timer.tic();\n    SMOOTH(NBT)\n    {\n      getJointJacobian(model,data,idx,WORLD,Jrh);\n    }\n    if(verbose) std::cout << \"Copy =\\t\";\n    timer.toc(std::cout,NBT);\n  }\n  \n  if( flag >> 2 & 1 )\n  {\n    computeJointJacobians(model,data,q);\n    Model::Index idx = model.existJointName(\"rarm6\")?model.getJointId(\"rarm6\"):(Model::Index)(model.njoints-1); \n    Data::Matrix6x Jrh(6,model.nv); Jrh.fill(0);\n\n    timer.tic();\n    SMOOTH(NBT)\n    {\n      getJointJacobian(model,data,idx,LOCAL,Jrh);\n    }\n    if(verbose) std::cout << \"Change frame =\\t\";\n    timer.toc(std::cout,NBT);\n  }\n  \n  if( flag >> 3 & 1 )\n  {\n    computeJointJacobians(model,data,q);\n    Model::Index idx = model.existJointName(\"rarm6\")?model.getJointId(\"rarm6\"):(Model::Index)(model.njoints-1); \n    Data::Matrix6x Jrh(6,model.nv); Jrh.fill(0);\n\n    timer.tic();\n    SMOOTH(NBT)\n    {\n      jointJacobian(model,data,q,idx,Jrh);\n    }\n    if(verbose) std::cout << \"Single jacobian =\\t\";\n    timer.toc(std::cout,NBT);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END ()\n\n", "meta": {"hexsha": "04ecb6606c0d804dbd3c3dc86fce8f85036dc048", "size": 6671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/jacobian.cpp", "max_stars_repo_name": "mkatliar/pinocchio", "max_stars_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittest/jacobian.cpp", "max_issues_repo_name": "mkatliar/pinocchio", "max_issues_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "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/jacobian.cpp", "max_forks_repo_name": "mkatliar/pinocchio", "max_forks_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "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": 28.6309012876, "max_line_length": 114, "alphanum_fraction": 0.6840053965, "num_tokens": 2026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5449106564940881}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2003 Joel de Guzman\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#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <boost/spirit/include/phoenix_core.hpp>\n#include <boost/spirit/include/phoenix_function.hpp>\n\nusing namespace boost::phoenix;\nusing namespace boost::phoenix::arg_names;\nusing namespace std;\n\nstruct factorial_impl\n{\n    template <typename Arg>\n    struct result\n    {\n        typedef Arg type;\n    };\n\n    template <typename Arg>\n    Arg operator()(Arg n) const\n    {\n        return (n <= 0) ? 1 : n * this->operator()(n-1);\n    }\n};\n\nfunction<factorial_impl> factorial;\n\nint\nmain()\n{\n    int i = 4;\n    cout << factorial(arg1)(i) << endl;\n    return 0;\n}\n", "meta": {"hexsha": "a093edc29c1d42fd1ebb49893d07959759a57707", "size": 984, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/spirit/phoenix/example/users_manual/factorial.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/spirit/phoenix/example/users_manual/factorial.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/spirit/phoenix/example/users_manual/factorial.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": 24.0, "max_line_length": 81, "alphanum_fraction": 0.5630081301, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594355, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5449106548255047}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2016-2017 Oracle and/or its affiliates.\r\n// Contributed and/or modified by Vissarion Fisikopoulos, 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_STRATEGIES_SPHERICAL_AREA_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_AREA_HPP\r\n\r\n\r\n#include <boost/geometry/formulas/area_formulas.hpp>\r\n#include <boost/geometry/core/radius.hpp>\r\n#include <boost/geometry/core/srs.hpp>\r\n#include <boost/geometry/strategies/area.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace area\r\n{\r\n\r\n/*!\r\n\\brief Spherical area calculation\r\n\\ingroup strategies\r\n\\details Calculates area on the surface of a sphere using the trapezoidal rule\r\n\\tparam PointOfSegment \\tparam_segment_point\r\n\\tparam CalculationType \\tparam_calculation\r\n\r\n\\qbk{\r\n[heading See also]\r\n[link geometry.reference.algorithms.area.area_2_with_strategy area (with strategy)]\r\n}\r\n*/\r\ntemplate\r\n<\r\n    typename PointOfSegment,\r\n    typename CalculationType = void\r\n>\r\nclass spherical\r\n{\r\n    // Enables special handling of long segments\r\n    static const bool LongSegment = false;\r\n\r\ntypedef 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 coordinate_type<PointOfSegment>::type,\r\n                double\r\n            >::type,\r\n        CalculationType\r\n    >::type CT;\r\n\r\nprotected :\r\n    struct excess_sum\r\n    {\r\n        CT m_sum;\r\n\r\n        // Keep track if encircles some pole\r\n        size_t m_crosses_prime_meridian;\r\n\r\n        inline excess_sum()\r\n            : m_sum(0)\r\n            , m_crosses_prime_meridian(0)\r\n        {}\r\n        template <typename SphereType>\r\n        inline CT area(SphereType sphere) const\r\n        {\r\n            CT result;\r\n            CT radius = geometry::get_radius<0>(sphere);\r\n\r\n            // Encircles pole\r\n            if(m_crosses_prime_meridian % 2 == 1)\r\n            {\r\n                size_t times_crosses_prime_meridian\r\n                        = 1 + (m_crosses_prime_meridian / 2);\r\n\r\n                result = CT(2)\r\n                         * geometry::math::pi<CT>()\r\n                         * times_crosses_prime_meridian\r\n                         - geometry::math::abs(m_sum);\r\n\r\n                if(geometry::math::sign<CT>(m_sum) == 1)\r\n                {\r\n                    result = - result;\r\n                }\r\n\r\n            } else {\r\n                result =  m_sum;\r\n            }\r\n\r\n            result *= radius * radius;\r\n\r\n            return result;\r\n        }\r\n    };\r\n\r\npublic :\r\n    typedef CT return_type;\r\n    typedef PointOfSegment segment_point_type;\r\n    typedef excess_sum state_type;\r\n    typedef geometry::srs::sphere<CT> sphere_type;\r\n\r\n    // For backward compatibility reasons the radius is set to 1\r\n    inline spherical()\r\n        : m_sphere(1.0)\r\n    {}\r\n\r\n    template <typename T>\r\n    explicit inline spherical(geometry::srs::sphere<T> const& sphere)\r\n        : m_sphere(geometry::get_radius<0>(sphere))\r\n    {}\r\n\r\n    explicit inline spherical(CT const& radius)\r\n        : m_sphere(radius)\r\n    {}\r\n\r\n    inline void apply(PointOfSegment const& p1,\r\n                      PointOfSegment const& p2,\r\n                      excess_sum& state) const\r\n    {\r\n        if (! geometry::math::equals(get<0>(p1), get<0>(p2)))\r\n        {\r\n            typedef geometry::formula::area_formulas<CT> area_formulas;\r\n\r\n            state.m_sum += area_formulas::template spherical<LongSegment>(p1, p2);\r\n\r\n            // Keep track whenever a segment crosses the prime meridian\r\n            if (area_formulas::crosses_prime_meridian(p1, p2))\r\n            {\r\n                state.m_crosses_prime_meridian++;\r\n            }\r\n        }\r\n    }\r\n\r\n    inline return_type result(excess_sum const& state) const\r\n    {\r\n        return state.area(m_sphere);\r\n    }\r\n\r\nprivate :\r\n    /// srs Sphere\r\n    sphere_type m_sphere;\r\n};\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\nnamespace services\r\n{\r\n\r\n\r\ntemplate <typename Point>\r\nstruct default_strategy<spherical_equatorial_tag, Point>\r\n{\r\n    typedef strategy::area::spherical<Point> type;\r\n};\r\n\r\n// Note: spherical polar coordinate system requires \"get_as_radian_equatorial\"\r\ntemplate <typename Point>\r\nstruct default_strategy<spherical_polar_tag, Point>\r\n{\r\n    typedef strategy::area::spherical<Point> type;\r\n};\r\n\r\n} // namespace services\r\n\r\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\n\r\n}} // namespace strategy::area\r\n\r\n\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_AREA_HPP\r\n", "meta": {"hexsha": "d5d1a581c2c952c0c739fb0906b0d19eee273c99", "size": 4871, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trunk/src/include/boost/geometry/strategies/spherical/area.hpp", "max_stars_repo_name": "SnailTowardThesun/face-detect", "max_stars_repo_head_hexsha": "4f02115684898a41564bbe7fc766b76e9e417ac9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T06:33:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T06:33:58.000Z", "max_issues_repo_path": "trunk/src/include/boost/geometry/strategies/spherical/area.hpp", "max_issues_repo_name": "SnailTowardThesun/face-detect", "max_issues_repo_head_hexsha": "4f02115684898a41564bbe7fc766b76e9e417ac9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-12T02:43:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-14T06:08:53.000Z", "max_forks_repo_path": "3rdparty/include/boost/geometry/strategies/spherical/area.hpp", "max_forks_repo_name": "gradinkov/nheqminer-gradinkov", "max_forks_repo_head_hexsha": "6422e0cc3eff7fcab30561a57c1339fbe0107b62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-10T03:18:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:52:12.000Z", "avg_line_length": 26.472826087, "max_line_length": 84, "alphanum_fraction": 0.615889961, "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5448961448974943}}
{"text": "/*\n * @file\n * @author University of Warwick\n * @version 1.0\n *\n * @section LICENSE\n *\n * @section DESCRIPTION\n *\n * Unit Tests for the concrete methods of the Triangle2D class\n */\n\n#define BOOST_TEST_MODULE Triangle2D\n#include <boost/test/unit_test.hpp>\n#include <boost/test/output_test_stream.hpp>\n#include <stdexcept>\n\n#include \"Triangle2D.h\"\n#include \"EuclideanPoint.h\"\n\nusing namespace cupcfd::geometry::shapes;\nnamespace euc = cupcfd::geometry::euclidean;\nnamespace utf = boost::unit_test;\n\n// === Constructor ===\n// Test 1: Constructor: 3 Defined Points - 2D\nBOOST_AUTO_TEST_CASE(constructor_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\tTriangle2D<double> shape(p1, p2, p3);\n\n\tBOOST_CHECK_EQUAL(shape.numVertices, 3);\n\tBOOST_CHECK_EQUAL(shape.vertices[0].cmp[0], p1.cmp[0]);\n\tBOOST_CHECK_EQUAL(shape.vertices[0].cmp[1], p1.cmp[1]);\n\tBOOST_CHECK_EQUAL(shape.vertices[1].cmp[0], p2.cmp[0]);\n\tBOOST_CHECK_EQUAL(shape.vertices[1].cmp[1], p2.cmp[1]);\n\tBOOST_CHECK_EQUAL(shape.vertices[2].cmp[0], p3.cmp[0]);\n\tBOOST_CHECK_EQUAL(shape.vertices[2].cmp[1], p3.cmp[1]);\n}\n\n// Test 2: Copy Constructor\nBOOST_AUTO_TEST_CASE(constructor_test2, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\tTriangle2D<double> shape(p1, p2, p3);\n\tTriangle2D<double> shape2(shape);\n\n\tBOOST_CHECK_EQUAL(shape2.numVertices, 3);\n\tBOOST_CHECK_EQUAL(shape2.vertices[0].cmp[0], p1.cmp[0]);\n\tBOOST_CHECK_EQUAL(shape2.vertices[0].cmp[1], p1.cmp[1]);\n\tBOOST_CHECK_EQUAL(shape2.vertices[1].cmp[0], p2.cmp[0]);\n\tBOOST_CHECK_EQUAL(shape2.vertices[1].cmp[1], p2.cmp[1]);\n\tBOOST_CHECK_EQUAL(shape2.vertices[2].cmp[0], p3.cmp[0]);\n\tBOOST_CHECK_EQUAL(shape2.vertices[2].cmp[1], p3.cmp[1]);\n}\n\n// === isPointInsideBarycentric (static, 2D) ===\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test1, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.1, 6.0);\n\n\tbool inside = Triangle2D<double>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 2: Test a point on top of vertex a - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test2, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\teuc::EuclideanPoint<double,2> p4 = p1;\n\n\t// Test and Check\n\tbool inside = Triangle2D<double>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 3: Test a point on top of vertex b - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test3, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\teuc::EuclideanPoint<double,2> p4 = p2;\n\n\t// Test and Check\n\tbool inside = Triangle2D<double>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 4: Test a point on top of vertex c - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test4, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\teuc::EuclideanPoint<double,2> p4 = p3;\n\n\t// Test and Check\n\tbool inside = Triangle2D<double>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 5: Test a point on edge ab - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test5, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.5, 8.0);\n\n\tbool inside = Triangle2D<double>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 6: Test a point on edge ac - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test6, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.15, 9.5);\n\n\tbool inside = Triangle2D<double>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 7: Test a point on edge bc - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test7, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.65, 13.5);\n\n\tbool inside = Triangle2D<double>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 8: Test a point outside the Triangle - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test8, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(1.0, 1.34);\n\n\tbool inside = Triangle2D<double>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, false);\n}\n\n// Test 9: Test a point inside when a.cmp[1] == c.cmp[1] - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test9, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(3.15, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 4.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.15, 4.2);\n\n\tbool inside = Triangle2D<double>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// === getCentroid ===\n// Test 1: Correctly compute the center for the triangles points\nBOOST_AUTO_TEST_CASE(computeCenter_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\tTriangle2D<double> shape(p1,p2,p3);\n\tcupcfd::geometry::euclidean::EuclideanPoint<double,2> center = shape.getCentroid();\n\tBOOST_TEST(center.cmp[0] == 3.433333);\n\tBOOST_TEST(center.cmp[1] == 10.333333);\n}\n\n// === isPointInside ===\nBOOST_AUTO_TEST_CASE(isPointInside_test1, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.1, 6.0);\n\n\tTriangle2D<double> shape(p1,p2,p3);\n\tbool inside = shape.isPointInside(p4);\n\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 2: Test a point on top of vertex a - 2D\nBOOST_AUTO_TEST_CASE(isPointInside_test2, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\teuc::EuclideanPoint<double,2> p4 = p1;\n\n\t// Test and Check\n\tTriangle2D<double> shape(p1,p2,p3);\n\tbool inside = shape.isPointInside(p4);\n\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 3: Test a point on top of vertex b - 2D\nBOOST_AUTO_TEST_CASE(isPointInside_test3, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\teuc::EuclideanPoint<double,2> p4 = p2;\n\n\t// Test and Check\n\tTriangle2D<double> shape(p1,p2,p3);\n\tbool inside = shape.isPointInside(p4);\n\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 4: Test a point on top of vertex c - 2D\nBOOST_AUTO_TEST_CASE(isPointInside_test4, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\teuc::EuclideanPoint<double,2> p4 = p3;\n\n\t// Test and Check\n\tTriangle2D<double> shape(p1,p2,p3);\n\tbool inside = shape.isPointInside(p4);\n\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 5: Test a point on edge ab - 2D\nBOOST_AUTO_TEST_CASE(isPointInside_test5, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.5, 8.0);\n\n\tTriangle2D<double> shape(p1,p2,p3);\n\tbool inside = shape.isPointInside(p4);\n\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 6: Test a point on edge ac - 2D\nBOOST_AUTO_TEST_CASE(isPointInside_test6, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.15, 9.5);\n\n\tTriangle2D<double> shape(p1,p2,p3);\n\tbool inside = shape.isPointInside(p4);\n\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 7: Test a point on edge bc - 2D\nBOOST_AUTO_TEST_CASE(isPointInside_test7, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.65, 13.5);\n\n\tTriangle2D<double> shape(p1,p2,p3);\n\tbool inside = shape.isPointInside(p4);\n\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 8: Test a point outside the Triangle - 2D\nBOOST_AUTO_TEST_CASE(isPointInside_test8, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(1.0, 1.34);\n\n\tTriangle2D<double> shape(p1,p2,p3);\n\tbool inside = shape.isPointInside(p4);\n\n\tBOOST_CHECK_EQUAL(inside, false);\n}\n\n// Test 9: Test a point inside when a.cmp[1] == c.cmp[1] - 2D\nBOOST_AUTO_TEST_CASE(isPointInside_test9, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(3.15, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 4.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.15, 4.2);\n\n\tTriangle2D<double> shape(p1,p2,p3);\n\tbool inside = shape.isPointInside(p4);\n\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// === getArea ===\n// Test 1: Test the area is computed correctly - 2D\nBOOST_AUTO_TEST_CASE(getArea_test1, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(3.15, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 4.0);\n\n\t// Test and Check\n\tTriangle2D<double> shape(p1, p2, p3);\n\tdouble area = shape.getArea();\n\tBOOST_TEST(area == 1.2);\n}\n\n// Test 2: Test the area is computed correctly - 2D\nBOOST_AUTO_TEST_CASE(getArea_test2, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(6.0, 4.0);\n\teuc::EuclideanPoint<double,2> p3(3.0, 12.0);\n\n\t// Test and Check\n\tTriangle2D<double> shape(p1, p2, p3);\n\tdouble area = shape.getArea();\n\tBOOST_TEST(area == 12.0);\n}\n", "meta": {"hexsha": "890f9211079e11127705324645481a782ff1c547", "size": 11309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/geometry/shapes/implementation/component/Triangle2DTests.cpp", "max_stars_repo_name": "thorbenlouw/CUP-CFD", "max_stars_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T10:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T14:43:19.000Z", "max_issues_repo_path": "tests/geometry/shapes/implementation/component/Triangle2DTests.cpp", "max_issues_repo_name": "thorbenlouw/CUP-CFD", "max_issues_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T15:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T14:27:28.000Z", "max_forks_repo_path": "tests/geometry/shapes/implementation/component/Triangle2DTests.cpp", "max_forks_repo_name": "thorbenlouw/CUP-CFD", "max_forks_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T15:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T15:24:24.000Z", "avg_line_length": 28.7760814249, "max_line_length": 86, "alphanum_fraction": 0.7074011849, "num_tokens": 4204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5448547721405836}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\r\n *    All rights reserved.\r\n *\r\n *    Redistribution and use in source and binary forms, with or without modification, are\r\n *    permitted provided that the following conditions are met:\r\n *      - Redistributions of source code must retain the above copyright notice, this list of\r\n *        conditions and the following disclaimer.\r\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\r\n *        conditions and the following disclaimer in the documentation and/or other materials\r\n *        provided with the distribution.\r\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\r\n *        may be used to endorse or promote products derived from this software without specific\r\n *        prior written permission.\r\n *\r\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\r\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\r\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\r\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\r\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\r\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\r\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *    Changelog\r\n *      YYMMDD    Author            Comment\r\n *      100903    K. Kumar          File created.\r\n *      100916    L. Abdulkadir     File checked.\r\n *      100929    K. Kumar          Checked code by D. Dirkx added.\r\n *      101110    K. Kumar          Added raiseToExponentPower( ) function.\r\n *      102410    D. Dirkx          Minor comment changes as code check.\r\n *      101213    K. Kumar          Bugfix raiseToIntegerExponent( ); renamed raiseToIntegerPower( ).\r\n *                                  Added computeAbsoluteValue( ) functions.\r\n *      110202    K. Kumar          Added overload for State* for computeLinearInterpolation( ).\r\n *      110111    J. Melman         Added computeModulo( ) function.\r\n *      110411    K. Kumar          Added convertCartesianToSpherical( ) function.\r\n *      110606    J. Melman         Removed possible singularity from\r\n *                                  convertCartesianToSpherical.\r\n *      110707    K. Kumar          Added computeSampleMean( ), computeSampleVariance( ) functions.\r\n *      110905    S. Billemont      Reorganized includes.\r\n *                                  Moved (con/de)structors and getter/setters to header.\r\n *      120202    K. Kumar          Moved linear interpolation functions into new Interpolators\r\n *                                  sub-directory.\r\n *      120716    D. Dirkx          Updated with interpolator architecture.\r\n *\r\n *    References\r\n *      Press W.H., et al. Numerical Recipes in C++: The Art of Scientific Computing. Cambridge\r\n *          University Press, February 2002.\r\n *\r\n *    Notes\r\n *\r\n */\r\n\r\n#include <boost/multi_array.hpp>\r\n\r\n#include \"Tudat/Mathematics/Interpolators/linearInterpolator.h\"\r\n\r\nnamespace tudat\r\n{\r\nnamespace interpolators\r\n{\r\n\r\n//! Compute linear interpolation.\r\ndouble computeLinearInterpolation( const Eigen::VectorXd& sortedIndependentVariables,\r\n                                   const Eigen::VectorXd& associatedDependentVariables,\r\n                                   const double targetIndependentVariableValue )\r\n{\r\n    // Declare local variables.\r\n    // Declare nearest neighbor.\r\n    int nearestNeighbor;\r\n    double locationTargetIndependentVariableValueInInterval;\r\n\r\n    // Compute nearest neighbor in sorted vector of independent variables.\r\n    // Result is always to the left of the target independent variable value.\r\n    nearestNeighbor = basic_mathematics::computeNearestLeftNeighborUsingBinarySearch(\r\n            sortedIndependentVariables, targetIndependentVariableValue );\r\n\r\n    // Compute location of target independent variable value in interval\r\n    // between nearest neighbors.\r\n    locationTargetIndependentVariableValueInInterval\r\n            = ( targetIndependentVariableValue\r\n              - sortedIndependentVariables[ nearestNeighbor ] )\r\n             / ( sortedIndependentVariables[ nearestNeighbor + 1 ]\r\n                 - sortedIndependentVariables[ nearestNeighbor ] );\r\n\r\n    // Return the computed value of the dependent variable.\r\n    return ( associatedDependentVariables[ nearestNeighbor ]\r\n             * ( 1 - locationTargetIndependentVariableValueInInterval )\r\n             + associatedDependentVariables[ nearestNeighbor + 1 ]\r\n             * locationTargetIndependentVariableValueInInterval );\r\n}\r\n\r\n//! Compute linear interpolation.\r\nEigen::VectorXd computeLinearInterpolation(\r\n        const std::map < double, Eigen::VectorXd >& sortedIndepedentAndDependentVariables,\r\n        const double targetIndependentVariableValue )\r\n{\r\n    // Declare local variables.\r\n    // Declare nearest neighbor.\r\n    int nearestLeftNeighbor;\r\n\r\n    // Declare location of target independent variable value in interval.\r\n    double locationTargetIndependentVariableValueInInterval;\r\n\r\n    // Declare map iterators\r\n    std::map< double, Eigen::VectorXd >::const_iterator mapIteratorIntervalLeft;\r\n    std::map< double, Eigen::VectorXd >::const_iterator mapIteratorIntervalRight;\r\n\r\n    // Compute nearest neighbor in map of data.\r\n    // Result is always to the left of the target independent variable value.\r\n    nearestLeftNeighbor = basic_mathematics::computeNearestLeftNeighborUsingBinarySearch(\r\n                sortedIndepedentAndDependentVariables, targetIndependentVariableValue );\r\n\r\n    // Compute location of target independent variable value in interval\r\n    // between nearest neighbors.\r\n    mapIteratorIntervalLeft = sortedIndepedentAndDependentVariables.begin( );\r\n    advance( mapIteratorIntervalLeft, nearestLeftNeighbor );\r\n    mapIteratorIntervalRight = sortedIndepedentAndDependentVariables.begin( );\r\n    advance( mapIteratorIntervalRight, nearestLeftNeighbor + 1 );\r\n    locationTargetIndependentVariableValueInInterval\r\n            = ( targetIndependentVariableValue\r\n              - mapIteratorIntervalLeft->first )\r\n             / ( mapIteratorIntervalRight->first\r\n                 - mapIteratorIntervalLeft->first );\r\n\r\n    // Return the computed value of the dependent variable.\r\n    return ( mapIteratorIntervalLeft->second\r\n             * ( 1 - locationTargetIndependentVariableValueInInterval )\r\n             + mapIteratorIntervalRight->second\r\n             * locationTargetIndependentVariableValueInInterval );\r\n}\r\n\r\n} // namespace interpolators\r\n} // mamespace tudat\r\n", "meta": {"hexsha": "fbd1cbc903ad197b6e3aa403d5f3d08f4d6d4a0b", "size": 6983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/Interpolators/linearInterpolator.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/Interpolators/linearInterpolator.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/Interpolators/linearInterpolator.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": 51.7259259259, "max_line_length": 102, "alphanum_fraction": 0.6830874982, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5448547681609085}}
{"text": "// Copyright (C) 2013  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n#include <dlib/python.h>\r\n#include <boost/shared_ptr.hpp>\r\n#include <dlib/matrix.h>\r\n#include <boost/python/slice.hpp>\r\n#include <dlib/geometry/vector.h>\r\n#include \"indexing.h\"\r\n\r\n\r\nusing namespace dlib;\r\nusing namespace std;\r\nusing namespace boost::python;\r\n\r\ntypedef matrix<double,0,1> cv;\r\n\r\nvoid cv_set_size(cv& m, long s)\r\n{\r\n    m.set_size(s);\r\n    m = 0;\r\n}\r\n\r\ndouble dotprod ( const cv& a, const cv& b)\r\n{\r\n    return dot(a,b);\r\n}\r\n\r\nstring cv__str__(const cv& v)\r\n{\r\n    ostringstream sout;\r\n    for (long i = 0; i < v.size(); ++i)\r\n    {\r\n        sout << v(i);\r\n        if (i+1 < v.size())\r\n            sout << \"\\n\";\r\n    }\r\n    return sout.str();\r\n}\r\n\r\nstring cv__repr__ (const cv& v)\r\n{\r\n    std::ostringstream sout;\r\n    sout << \"dlib.vector([\";\r\n    for (long i = 0; i < v.size(); ++i)\r\n    {\r\n        sout << v(i);\r\n        if (i+1 < v.size())\r\n            sout << \", \";\r\n    }\r\n    sout << \"])\";\r\n    return sout.str();\r\n}\r\n\r\nboost::shared_ptr<cv> cv_from_object(object obj)\r\n{\r\n    extract<long> thesize(obj);\r\n    if (thesize.check())\r\n    {\r\n        long nr = thesize;\r\n        boost::shared_ptr<cv> temp(new cv(nr));\r\n        *temp = 0;\r\n        return temp;\r\n    }\r\n    else\r\n    {\r\n        const long nr = len(obj);\r\n        boost::shared_ptr<cv> temp(new cv(nr));\r\n        for ( long r = 0; r < nr; ++r)\r\n        {\r\n            (*temp)(r) = extract<double>(obj[r]);\r\n        }\r\n        return temp;\r\n    }\r\n}\r\n\r\nlong cv__len__(cv& c)\r\n{\r\n    return c.size();\r\n}\r\n\r\n\r\nvoid cv__setitem__(cv& c, long p, double val)\r\n{\r\n    if (p < 0) {\r\n        p = c.size() + p; // negative index\r\n    }\r\n    if (p > c.size()-1) {\r\n        PyErr_SetString( PyExc_IndexError, \"index out of range\"\r\n        );\r\n        boost::python::throw_error_already_set();\r\n    }\r\n    c(p) = val;\r\n}\r\n\r\ndouble cv__getitem__(cv& m, long r)\r\n{\r\n    if (r < 0) {\r\n        r = m.size() + r; // negative index\r\n    }\r\n    if (r > m.size()-1 || r < 0) {\r\n        PyErr_SetString( PyExc_IndexError, \"index out of range\"\r\n        );\r\n        boost::python::throw_error_already_set();\r\n    }\r\n    return m(r);\r\n}\r\n\r\n\r\ncv cv__getitem2__(cv& m, slice r)\r\n{\r\n    slice::range<cv::iterator> bounds;\r\n    bounds = r.get_indicies<>(m.begin(), m.end());\r\n    long num = (bounds.stop-bounds.start+1);\r\n    // round num up to the next multiple of bounds.step.\r\n    if ((num%bounds.step) != 0)\r\n        num += bounds.step - num%bounds.step;\r\n\r\n    cv temp(num/bounds.step);\r\n\r\n    if (temp.size() == 0)\r\n        return temp;\r\n    long ii = 0;\r\n    while(bounds.start != bounds.stop)\r\n    {\r\n        temp(ii++) = *bounds.start;\r\n        std::advance(bounds.start, bounds.step);\r\n    }\r\n    temp(ii) = *bounds.start;\r\n    return temp;\r\n}\r\n\r\nboost::python::tuple cv_get_matrix_size(cv& m)\r\n{\r\n    return boost::python::make_tuple(m.nr(), m.nc());\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nstring point__repr__ (const point& p)\r\n{\r\n    std::ostringstream sout;\r\n    sout << \"point(\" << p.x() << \", \" << p.y() << \")\";\r\n    return sout.str();\r\n}\r\n\r\nstring point__str__(const point& p)\r\n{\r\n    std::ostringstream sout;\r\n    sout << \"(\" << p.x() << \", \" << p.y() << \")\";\r\n    return sout.str();\r\n}\r\n\r\nlong point_x(const point& p) { return p.x(); }\r\nlong point_y(const point& p) { return p.y(); }\r\n\r\n// ----------------------------------------------------------------------------------------\r\nvoid bind_vector()\r\n{\r\n    using boost::python::arg;\r\n    {\r\n    class_<cv>(\"vector\", \"This object represents the mathematical idea of a column vector.\", init<>())\r\n        .def(\"set_size\", &cv_set_size)\r\n        .def(\"resize\", &cv_set_size)\r\n        .def(\"__init__\", make_constructor(&cv_from_object))\r\n        .def(\"__repr__\", &cv__repr__)\r\n        .def(\"__str__\", &cv__str__)\r\n        .def(\"__len__\", &cv__len__)\r\n        .def(\"__getitem__\", &cv__getitem__)\r\n        .def(\"__getitem__\", &cv__getitem2__)\r\n        .def(\"__setitem__\", &cv__setitem__)\r\n        .add_property(\"shape\", &cv_get_matrix_size)\r\n        .def_pickle(serialize_pickle<cv>());\r\n\r\n    def(\"dot\", dotprod, \"Compute the dot product between two dense column vectors.\");\r\n    }\r\n    {\r\n    typedef point type;\r\n    class_<type>(\"point\", \"This object represents a single point of integer coordinates that maps directly to a dlib::point.\")\r\n            .def(init<long,long>((arg(\"x\"), arg(\"y\"))))\r\n            .def(\"__repr__\", &point__repr__)\r\n            .def(\"__str__\", &point__str__)\r\n            .add_property(\"x\", &point_x, \"The x-coordinate of the point.\")\r\n            .add_property(\"y\", &point_y, \"The y-coordinate of the point.\")\r\n            .def_pickle(serialize_pickle<type>());\r\n    }\r\n    {\r\n    typedef std::vector<point> type;\r\n    class_<type>(\"points\", \"An array of point objects.\")\r\n        .def(vector_indexing_suite<type>())\r\n        .def(\"clear\", &type::clear)\r\n        .def(\"resize\", resize<type>)\r\n        .def_pickle(serialize_pickle<type>());\r\n    }\r\n}\r\n", "meta": {"hexsha": "7df004989478cc6eac0d01e23ec239cbfeed0ebc", "size": 5095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/python/src/vector.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": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-16T11:44:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-16T11:44:40.000Z", "max_issues_repo_path": "tools/python/src/vector.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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/python/src/vector.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": 25.9948979592, "max_line_length": 127, "alphanum_fraction": 0.5210991168, "num_tokens": 1329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5448547676222675}}
{"text": "//  Copyright (c) 2006 Xiaogang Zhang\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//  History:\n//  XZ wrote the original of this file as part of the Google\n//  Summer of Code 2006.  JM modified it slightly to fit into the\n//  Boost.Math conceptual framework better.\n\n#ifndef BOOST_MATH_ELLINT_RD_HPP\n#define BOOST_MATH_ELLINT_RD_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/tools/config.hpp>\n#include <boost/math/policies/error_handling.hpp>\n\n// Carlson's elliptic integral of the second kind\n// R_D(x, y, z) = R_J(x, y, z, z) = 1.5 * \\int_{0}^{\\infty} [(t+x)(t+y)]^{-1/2} (t+z)^{-3/2} dt\n// Carlson, Numerische Mathematik, vol 33, 1 (1979)\n\nnamespace boost { namespace math { namespace detail{\n\ntemplate <typename T, typename Policy>\nT ellint_rd_imp(T x, T y, T z, const Policy& pol)\n{\n    T value, u, lambda, sigma, factor, tolerance;\n    T X, Y, Z, EA, EB, EC, ED, EE, S1, S2;\n    unsigned long k;\n\n    BOOST_MATH_STD_USING\n    using namespace boost::math::tools;\n\n    static const char* function = \"boost::math::ellint_rd<%1%>(%1%,%1%,%1%)\";\n\n    if (x < 0)\n    {\n       return policies::raise_domain_error<T>(function,\n            \"Argument x must be >= 0, but got %1%\", x, pol);\n    }\n    if (y < 0)\n    {\n       return policies::raise_domain_error<T>(function,\n            \"Argument y must be >= 0, but got %1%\", y, pol);\n    }\n    if (z <= 0)\n    {\n       return policies::raise_domain_error<T>(function,\n            \"Argument z must be > 0, but got %1%\", z, pol);\n    }\n    if (x + y == 0)\n    {\n       return policies::raise_domain_error<T>(function,\n            \"At most one argument can be zero, but got, x + y = %1%\", x+y, pol);\n    }\n\n    // error scales as the 6th power of tolerance\n    tolerance = pow(tools::epsilon<T>() / 3, T(1)/6);\n\n    // duplication\n    sigma = 0;\n    factor = 1;\n    k = 1;\n    do\n    {\n        u = (x + y + z + z + z) / 5;\n        X = (u - x) / u;\n        Y = (u - y) / u;\n        Z = (u - z) / u;\n        if ((tools::max)(abs(X), abs(Y), abs(Z)) < tolerance) \n           break;\n        T sx = sqrt(x);\n        T sy = sqrt(y);\n        T sz = sqrt(z);\n        lambda = sy * (sx + sz) + sz * sx; //sqrt(x * y) + sqrt(y * z) + sqrt(z * x);\n        sigma += factor / (sz * (z + lambda));\n        factor /= 4;\n        x = (x + lambda) / 4;\n        y = (y + lambda) / 4;\n        z = (z + lambda) / 4;\n        ++k;\n    }\n    while(k < policies::get_max_series_iterations<Policy>());\n\n    // Check to see if we gave up too soon:\n    policies::check_series_iterations<T>(function, k, pol);\n\n    // Taylor series expansion to the 5th order\n    EA = X * Y;\n    EB = Z * Z;\n    EC = EA - EB;\n    ED = EA - 6 * EB;\n    EE = ED + EC + EC;\n    S1 = ED * (ED * T(9) / 88 - Z * EE * T(9) / 52 - T(3) / 14);\n    S2 = Z * (EE / 6 + Z * (-EC * T(9) / 22 + Z * EA * T(3) / 26));\n    value = 3 * sigma + factor * (1 + S1 + S2) / (u * sqrt(u));\n\n    return value;\n}\n\n} // namespace detail\n\ntemplate <class T1, class T2, class T3, class Policy>\ninline typename tools::promote_args<T1, T2, T3>::type \n   ellint_rd(T1 x, T2 y, T3 z, const Policy& pol)\n{\n   typedef typename tools::promote_args<T1, T2, T3>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(\n      detail::ellint_rd_imp(\n         static_cast<value_type>(x),\n         static_cast<value_type>(y),\n         static_cast<value_type>(z), pol), \"boost::math::ellint_rd<%1%>(%1%,%1%,%1%)\");\n}\n\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type \n   ellint_rd(T1 x, T2 y, T3 z)\n{\n   return ellint_rd(x, y, z, policies::policy<>());\n}\n\n}} // namespaces\n\n#endif // BOOST_MATH_ELLINT_RD_HPP\n\n", "meta": {"hexsha": "61014d386608a749687a4d2fec9388f5d1fb149a", "size": 3938, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/math/special_functions/ellint_rd.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 133.0, "max_stars_repo_stars_event_min_datetime": "2018-04-20T14:09:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T11:51:25.000Z", "max_issues_repo_path": "boost/boost/math/special_functions/ellint_rd.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/math/special_functions/ellint_rd.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2018-04-27T03:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:23:40.000Z", "avg_line_length": 30.0610687023, "max_line_length": 95, "alphanum_fraction": 0.5771965465, "num_tokens": 1262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5448547631039511}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/sincpi.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/constant/mindenormal.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/function/sinpi.hpp>\n\nSTF_CASE_TPL(\" sinc\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::sincpi;\n\n  STF_EXPR_IS(sincpi(T()),T);\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(sincpi(bs::Inf<T>()), bs::Zero<T>(), 1.0);\n  STF_ULP_EQUAL(sincpi(bs::Minf<T>()), bs::Zero<T>(), 1.0);\n  STF_ULP_EQUAL(sincpi(bs::Nan<T>()), bs::Nan<T>(), 1.0);\n#endif\n  STF_ULP_EQUAL(sincpi(-T(1)/T(2)), T(2)/(bs::Pi<T>()), 1.0);\n  STF_ULP_EQUAL(sincpi(-T(1)/T(4)), bs::sinpi(T(1)/T(4))*T(4)/(bs::Pi<T>()), 1.0);\n  STF_ULP_EQUAL(sincpi(T(1)/T(2)),  T(2)/(bs::Pi<T>()), 1.0);\n  STF_ULP_EQUAL(sincpi(T(1)/T(4)), bs::sinpi(T(1)/T(4))*T(4)/(bs::Pi<T>()), 1.0);\n  STF_ULP_EQUAL(sincpi(bs::Eps<T>()), bs::One<T>(), 1.0);\n  STF_ULP_EQUAL(sincpi(bs::Mindenormal<T>()), bs::One<T>(), 1.0);\n  STF_ULP_EQUAL(sincpi(bs::Zero<T>()), bs::One<T>(), 1.0);\n}\n", "meta": {"hexsha": "936016c2b31bee07db83c899905f240348af88c6", "size": 1749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/sincpi.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/scalar/sincpi.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/sincpi.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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": 38.8666666667, "max_line_length": 100, "alphanum_fraction": 0.5929102344, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5448547585856346}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2018.\n// Modifications copyright (c) 2018 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//[area_with_strategy\n//` Calculate the area of a polygon\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    // Create spherical polygon\n    bg::model::polygon<bg::model::point<double, 2, bg::cs::spherical_equatorial<bg::degree> > > sph_poly;\n    bg::read_wkt(\"POLYGON((0 0,0 1,1 0,0 0))\", sph_poly);\n\n    // Create spherical strategy with mean Earth radius in meters\n    bg::strategy::area::spherical<> sph_strategy(6371008.8);\n\n    // Calculate the area of a spherical polygon\n    double area = bg::area(sph_poly, sph_strategy);\n    std::cout << \"Area: \" << area << std::endl;\n\n    // Create geographic polygon\n    bg::model::polygon<bg::model::point<double, 2, bg::cs::geographic<bg::degree> > > geo_poly;\n    bg::read_wkt(\"POLYGON((0 0,0 1,1 0,0 0))\", geo_poly);\n\n    // Create geographic strategy with WGS84 spheroid\n    bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);\n    bg::strategy::area::geographic<> geo_strategy(spheroid);\n\n    // Calculate the area of a geographic polygon\n    area = bg::area(geo_poly, geo_strategy);\n    std::cout << \"Area: \" << area << std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[area_with_strategy_output\n/*`\nOutput:\n[pre\nArea: 6.18249e+09\nArea: 6.15479e+09\n]\n*/\n//]\n", "meta": {"hexsha": "8d7803d8bf3337d17e9c43a497a7da4f38ded9fc", "size": 1918, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/algorithms/area_with_strategy.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "doc/src/examples/algorithms/area_with_strategy.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "doc/src/examples/algorithms/area_with_strategy.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 29.5076923077, "max_line_length": 105, "alphanum_fraction": 0.697080292, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5448213413479631}}
{"text": "/// @file  embed_cmp_with_tau.cpp\n/// @brief Implements kernel methods based on Kendall's tau.\n\n#include <ogt/embed/cmp.hpp>\n#include <ogt/linalg/linalg.hpp>\n#include <Eigen/Sparse>\n\nusing std::min;\nusing std::max;\nusing std::vector;\nusing Eigen::Index;\nusing Eigen::MatrixXd;\nusing Eigen::SparseMatrix;\nusing Eigen::VectorXd;\nusing OGT_NAMESPACE::linalg::kernelForFeatures;\n\ntypedef Eigen::Triplet<double> sptriple;\ntypedef Eigen::SparseMatrix<double, Eigen::RowMajor> SpMat;\n\nnamespace OGT_NAMESPACE {\nnamespace embed {\n\n/// Finds the index of the specified object pair.\nIndex pair(size_t a, size_t b, size_t nObj) {\n\tIndex i = min(a, b), j = max(a, b);\n\treturn (nObj * (nObj-1) / 2)\n\t\t- ((nObj - i) * (nObj - i - 1) / 2)\n\t\t+ (j - i - 1);\n}\n\n/// Computes a kernel matrix from a sparse feature matrix.\n/// Computes the k1 kernel matrix from the paper cited for embedCmpWithTauForK()\nMatrixXd embedCmpWithTauK1(const vector<CmpConstraint>& cons, size_t nObj) {\n\tvector<sptriple> triplets;\n\ttriplets.reserve(cons.size());\n\tVectorXd norm = VectorXd::Zero(nObj);\n\tIndex nPairs = nObj * (nObj - 1) / 2;\n\tfor (const auto& con : cons) {\n\t\tassert(con.a < nObj && con.b < nObj && con.c < nObj);\n\t\tIndex pr = pair(con.b, con.c, nObj);\n\t\ttriplets.emplace_back(con.a, pr, (con.b < con.c) ? +1 : -1);\n\t\tnorm(con.a)++;\n\t}\n\tSpMat phi(nObj, nPairs);\n\tphi.setFromTriplets(triplets.begin(), triplets.end());\n\tfor (size_t obj = 0; obj < nObj; obj++) {\n\t\tif (norm(obj) > 0) {\n\t\t\tphi.row(obj) /= sqrt(norm(obj));\n\t\t}\n\t}\n\treturn kernelForFeatures(phi);\n}\n\n/// Computes the k2 kernel matrix from the paper cited for embedCmpWithTauForK()\nMatrixXd embedCmpWithTauK2(const vector<CmpConstraint>& cons, size_t nObj) {\n\tvector<sptriple> triplets;\n\ttriplets.reserve(2 * cons.size());\n\tVectorXd norm = VectorXd::Zero(nObj);\n\tIndex nPairs = nObj * (nObj - 1) / 2;\n\tfor (const auto& con : cons) {\n\t\tassert(con.a < nObj && con.b < nObj && con.c < nObj);\n\t\tIndex pr = pair(con.a, con.c, nObj);\n\t\ttriplets.emplace_back(con.b, pr, +1);\n\t\tnorm(con.b)++;\n\n\t\tpr = pair(con.a, con.b, nObj);\n\t\tif (pr >= nPairs) {\n\t\t\tstd::cerr << \"pair \" << pr << \" > \" << nPairs << std::endl;\n\t\t}\n\t\ttriplets.emplace_back(con.c, pr, -1);\n\t\tnorm(con.c)++;\n\t}\n\tSpMat phi(nObj, nPairs);\n\tphi.setFromTriplets(triplets.begin(), triplets.end());\n\tfor (size_t obj = 0; obj < nObj; obj++) {\n\t\tif (norm(obj) > 0) {\n\t\t\tphi.row(obj) /= sqrt(norm(obj));\n\t\t}\n\t}\n\treturn kernelForFeatures(phi);\n}\n\n/// Compute a kernel matrix where K_ij is derived by how similarly points i and\n/// j are ranked by the provided comparisons.\nEmbedResult embedCmpWithTauForK(vector<CmpConstraint> cons, double k1,\n\tdouble k2) {\n\tsize_t nObj = 0;\n\tfor (const auto& con : cons) {\n\t\tnObj = max({nObj, con.a, con.b, con.c});\n\t}\n\tnObj++;\n\tEmbedResult result;\n\tresult.K = MatrixXd::Zero(nObj, nObj);\n\tif (k1 > 0) {\n\t\tresult.K += k1 * embedCmpWithTauK1(cons, nObj);\n\t}\n\tif (k2 > 0) {\n\t\tresult.K += k2 * embedCmpWithTauK2(cons, nObj);\n\t}\n\treturn result;\n}\n\n} // end namespace embed\n} // end namespace OGT_NAMESPACE\n", "meta": {"hexsha": "b3613cdda8f0882016b562f71bdd0b718d752321", "size": 3018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/embed/embed_cmp_with_tau.cpp", "max_stars_repo_name": "jesand/lloe", "max_stars_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-11T21:31:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T09:23:04.000Z", "max_issues_repo_path": "src/lib/embed/embed_cmp_with_tau.cpp", "max_issues_repo_name": "jesand/lloe", "max_issues_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/embed/embed_cmp_with_tau.cpp", "max_forks_repo_name": "jesand/lloe", "max_forks_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T21:31:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-27T20:57:26.000Z", "avg_line_length": 28.7428571429, "max_line_length": 80, "alphanum_fraction": 0.6613651425, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5448213413479631}}
{"text": "/**\n * @file Triangulator.hpp\n * @author bwu\n * @brief Triangulator algrithom for triangulation\n * @version 0.1\n * @date 2022-02-22\n */\n#ifndef GENERIC_GEOMETRY_TRI_TRIANGULATOR_HPP\n#define GENERIC_GEOMETRY_TRI_TRIANGULATOR_HPP\n#include <boost/geometry/index/rtree.hpp>\n#include <boost/geometry/geometry.hpp>\n#include \"TriangulationOperator.hpp\"\n#include <unordered_map>\n#include <unordered_set>\n#include <limits>\nnamespace generic  {\nnamespace geometry {\nnamespace tri      {\nusing generic::common::float_type;\n\ntemplate <typename num_type>\nclass RuppertRefinement2D;\n\ntemplate <typename num_type>\nclass ChewSecondRefinement2D;\n\n/**\n * @brief represents a class that make points and edges to trangulation\n * @tparam num_type support integer and floating points number type\n */\ntemplate <typename num_type>\nclass Triangulator2D\n{\npublic:\n    using Depth = unsigned short;\n    using Point = Point2D<num_type>;\n    using Box = Box2D<num_type>;\n    using Edge = IndexEdge;\n    using Vertex = IndexVertex;\n    using Triangle = IndexTriangle;\n\n    using EdgeSet = typename Triangulation<Point>::EdgeSet;\n    using TriIdxMap = std::unordered_map<TriIdx, TriIdx>;\n\n    Triangulation<Point> & tri;\n    TriangulationOperator<Point> op;\n    ///@brief constructs a Triangulator2D that manipulating the triangulation data\n    Triangulator2D(Triangulation<Point> & t) : tri(t), op(t) {}\n    \n    /**\n     * @brief inserts vertices and construct delaunay triangulation\n     * \n     * @tparam VertexIterator iterator of the sequence of vertices\n     * @tparam CoorXGetter functioner type to get coordiante x of input vertex\n     * @tparam CoorYGetter functioner type to get coordinate y of input vertex\n     * @param begin iterator to the beginning of the vertices sequence\n     * @param end iterator to the ending of the vertices sequence\n     * @param xGetter functioner object to get coordiante x of input vertex\n     * @param yGetter functioner object to get coordiante y of input vertex\n     */\n    template <typename VertexIterator,\n              typename CoorXGetter,\n              typename CoorYGetter>\n    void InsertVertices(VertexIterator begin, VertexIterator end, CoorXGetter xGetter, CoorYGetter yGetter);\n\n    /**\n     * @brief inserts edges and construct constrained delaunay triangulation\n     * \n     * @tparam EdgeIterator iterator of the sequence of edges\n     * @tparam sVerIdxGetter functioner type to get start vertex index of edge \n     * @tparam eVerIdxGetter functioner type to get end vertex index of edge\n     * @param begin iterator to the beginning of the edges sequence\n     * @param end iterator to the ending of the edges sequence\n     * @param sGetter functioner object to get start vertex index of edge\n     * @param eGetter functioner object to get end vertex index of edge\n     */\n    template <typename EdgeIterator,\n              typename sVerIdxGetter,\n              typename eVerIdxGetter>\n    void InsertEdges(EdgeIterator begin, EdgeIterator end, sVerIdxGetter sGetter, eVerIdxGetter eGetter);\n\n    ///@brief removes super triangle and produce a convex-hull \n    void EraseSuperTriangle();\n    ///@brief removes all outer triangles until a boundary defined by constrained edges\n    void EraseOuterTriangles();\n    /**\n     * @brief removes outer triangles and automatically detected holes.\n     * Starts from super-triangle and traverses triangles until outer boundary.\n     * Triangles outside outer boundary will be removed.\n     * Then traversal continues until next boundary.\n     * hTriangles between two boundaries will be kept.\n     * Traversal to next boundary continues (this time removing triangles).\n     * Stops when all triangles are traversed.\n     */\n    void EraseOuterTrianglesAndHoles();\n\n    ///@brief clears all data in triangulation\n    void Clear();\nprivate:\n    template <typename VertexIterator,\n                typename CoorXGetter,\n                typename CoorYGetter>\n    Box Extent(VertexIterator begin, VertexIterator end, CoorXGetter xGetter, CoorYGetter yGetter);\n\n    void AddSuperTriangle(const Box & box);\n    \n    void InsertOneEdge(const Edge & edge);\n    void InsertOneVertex(const Point & pos);\n    \n    VerIdx InsertPointInTriangle(const Point & pos, TriIdx i0, std::stack<TriIdx> & out);\n    VerIdx InsertPointOnSharedEdge(const Point & pos, TriIdx i1, TriIdx i2, std::stack<TriIdx> & out);\n    VerIdx InsertPointOnBoundaryEdge(const Point & pos, TriIdx it, const Edge & e, std::stack<TriIdx> & out);\n\n    void Delaunay(std::stack<TriIdx> & triangls, VerIdx iv);\n    bool isNeedFlip(VerIdx iv, TriIdx it, TriIdx itOp) const;\n    bool isInCircumCircle(const Point & pos, const Point & v1, const Point & v2, const Point & v3) const;\n\n    std::tuple<TriIdx, VerIdx, VerIdx> IntersectedTriangle(VerIdx iA,\n                                                            const TriIdxSet & candidates,\n                                                            const Point & a, const Point & b) const;      \n    void RemoveSuperTriangleVertices();\n    template <typename TriIdxIterator>\n    void RemoveTriangles(TriIdxIterator begin, TriIdxIterator end);\n\n    TriIdx TriangulatePseudoPolygon(VerIdx ia, VerIdx ib, const std::vector<VerIdx> & points);\n    TriIdx PesudoPolyOuterTriangle(VerIdx ia, VerIdx ib) const;\n    VerIdx FindDelaunayPoint(VerIdx ia, VerIdx ib, const std::vector<VerIdx> & points) const;\n    std::pair<std::vector<VerIdx>, std::vector<VerIdx> >\n    SplitPsedoPolygon(VerIdx vi, const std::vector<VerIdx> & points);\n\n    TriIdxSet Grow2Boundary(std::stack<TriIdx> & seeds) const;\n    std::vector<Depth> CalculateTriangleDepths(const std::vector<Vertex> & vertices,\n                                                const TriangleVec & triangles,\n                                                const EdgeSet & fixedEdges);\n    TriIdxSet PeelLayer(std::stack<TriIdx> seeds,\n                        const TriangleVec & triangles,\n                        const EdgeSet & fixedEdges,\n                        Depth depth,\n                        std::vector<Depth> & triDepths);\n    \n    void RebuildRTree();\n};\n\ntemplate <typename num_type>\ntemplate <typename VertexIterator, typename CoorXGetter, typename CoorYGetter>\ninline void Triangulator2D<num_type>::InsertVertices(VertexIterator begin, VertexIterator end, CoorXGetter xGetter, CoorYGetter yGetter)\n{\n    if(tri.vertices.empty()){\n        auto bounds = Extent(begin, end, xGetter, yGetter);\n        AddSuperTriangle(bounds);\n    }\n    \n    tri.vertices.reserve(tri.vertices.size() + std::distance(begin, end));\n    for(auto iter = begin; iter != end; ++iter){\n        InsertOneVertex(Point(xGetter(*iter), yGetter(*iter)));\n    }\n}\n\ntemplate <typename num_type>\ntemplate <typename EdgeIterator, typename sVerIdxGetter, typename eVerIdxGetter>\ninline void Triangulator2D<num_type>::InsertEdges(EdgeIterator begin, EdgeIterator end, sVerIdxGetter sGetter, eVerIdxGetter eGetter)\n{\n    for(auto iter = begin; iter != end; ++iter){\n        InsertOneEdge(Edge(sGetter(*iter) + 3, eGetter(*iter) + 3));\n    }\n    op.ReallocateTriangulation();\n}\n\ntemplate <typename num_type>\ninline void Triangulator2D<num_type>::EraseSuperTriangle()\n{\n    TriIdxVec toErase;\n    for(TriIdx it = 0; it < tri.triangles.size(); ++it){\n        auto & t = tri.triangles[it];\n        if(t.vertices[0] < 3 || t.vertices[1] < 3 || t.vertices[2] < 3)\n            toErase.push_back(it);\n    }\n    RemoveTriangles(toErase.begin(), toErase.end());\n    RemoveSuperTriangleVertices();\n}\n\ntemplate <typename num_type>\ninline void Triangulator2D<num_type>::EraseOuterTriangles()\n{\n    std::stack<TriIdx> seed(std::deque<TriIdx>(1, *(tri.vertices[0].triangles.begin())));\n    TriIdxSet toErase = Grow2Boundary(seed);\n    RemoveTriangles(toErase.begin(), toErase.end());\n    RemoveSuperTriangleVertices();\n}\n\ntemplate <typename num_type>\ninline void Triangulator2D<num_type>::EraseOuterTrianglesAndHoles()\n{\n    auto triDepths = CalculateTriangleDepths(tri.vertices, tri.triangles, tri.fixedEdges);\n\n    TriIdxVec toErase;\n    toErase.reserve(tri.triangles.size());\n    for(size_t it = 0; it != tri.triangles.size(); ++it){\n        if(triDepths[it] % 2 == 0)\n            toErase.push_back(it);\n    }\n    RemoveTriangles(toErase.begin(), toErase.end());\n    RemoveSuperTriangleVertices();\n}\n\ntemplate <typename num_type>\ntemplate <typename VertexIterator, typename CoorXGetter, typename CoorYGetter>\ninline Box2D<num_type> Triangulator2D<num_type>::Extent(VertexIterator begin, VertexIterator end, CoorXGetter xGetter, CoorYGetter yGetter)\n{\n    Box box;\n    for(auto iter = begin; iter != end; ++iter)\n        box |= Point(xGetter(*iter), yGetter(*iter));\n    return box;\n}\n\ntemplate <typename num_type>\ninline void Triangulator2D<num_type>::AddSuperTriangle(const Box & box)\n{\n    auto center = box.Center();\n    auto l = box.Length();\n    auto w = box.Width();\n    l *= l; w *= w;\n    auto r = 0.5 * 1.1 * std::sqrt(float_type<num_type>(l + w));\n    auto sx = r * std::sqrt(3);\n    VerIdx iv1 = op.AddOneVertex(Point(center[0] - sx, center[1] - r), {0});\n    VerIdx iv2 = op.AddOneVertex(Point(center[0] + sx, center[1] - r), {0});\n    VerIdx iv3 = op.AddOneVertex(Point(center[0], center[1] + 2 * r), {0});\n    Triangle super{{iv1, iv2, iv3}, {noNeighbor, noNeighbor, noNeighbor}};\n    op.AddOneTriangle(super);\n}\n\ntemplate <typename num_type>\ninline void Triangulator2D<num_type>::InsertOneVertex(const Point & pos)\n{\n    VerIdx iv;\n    std::stack<TriIdx> tris;\n    auto [it1, it2] = op.TraversalTriangleAt(pos);\n    if(noNeighbor == it2) iv = op.InsertPointInTriangle(pos, it1, tris);\n    else iv = op.InsertPointOnSharedEdge(pos, it1, it2, tris);\n    Delaunay(tris, iv);\n}\n\ntemplate <typename num_type>\ninline void Triangulator2D<num_type>::InsertOneEdge(const Edge & edge)\n{\n    auto is = edge.v1();\n    auto ie = edge.v2();\n    if(is == ie) return;\n\n    const Vertex & vs = tri.vertices[is];\n    const Vertex & ve = tri.vertices[ie];\n\n    if(Vertex::isShareEdge(vs, ve)){\n        tri.fixedEdges.insert(Edge(is, ie));\n        return;\n    }\n\n    TriIdx it;\n    VerIdx ivLeft, ivRight;\n    std::tie(it, ivLeft, ivRight) = IntersectedTriangle(is, vs.triangles, tri.VertexPoint(vs), tri.VertexPoint(ve));\n    if(it == noNeighbor){\n        tri.fixedEdges.insert(Edge(is, ivLeft));\n        return InsertOneEdge(Edge(ivLeft, ie));\n    }\n\n    std::vector<TriIdx> intersected(1, it);\n    std::vector<VerIdx> ptsLeft(1, ivLeft);\n    std::vector<VerIdx> ptsRight(1, ivRight);\n    VerIdx iv = is;\n    Triangle t = tri.triangles[it];\n    const auto & vrts = t.vertices;\n    while(std::find(vrts.begin(), vrts.end(), ie) == vrts.end()){\n        \n        auto itOp = t.VeOpTn(iv);\n        const Triangle & tOp = tri.triangles[itOp];\n        auto ivOp = tOp.TnOpVe(it);\n        auto vOp = tri.vertices[ivOp];\n\n        intersected.push_back(itOp);\n        it = itOp;\n        t = tri.triangles[it];\n\n        PointLineLocation loc = GetPointLineLocation(tri.VertexPoint(vOp), tri.VertexPoint(vs), tri.VertexPoint(ve));\n        if(loc == PointLineLocation::Left){\n            ptsLeft.push_back(ivOp);\n            iv = ivLeft;\n            ivLeft = ivOp;\n        }\n        else if(loc == PointLineLocation::Right){\n            ptsRight.push_back(ivOp);\n            iv = ivRight;\n            ivRight = ivOp;\n        }\n        else { ie = ivOp; }\n    }\n\n    auto iter = intersected.begin();\n    for(; iter != intersected.end(); ++iter)\n        op.RemoveOneTriangle(*iter);\n    \n    auto itLeft = TriangulatePseudoPolygon(is, ie, ptsLeft);\n    std::reverse(ptsRight.begin(), ptsRight.end());\n    auto itRight = TriangulatePseudoPolygon(ie, is, ptsRight);\n    \n    tri.ChangeNeighbor(itLeft, noNeighbor, itRight);\n    tri.ChangeNeighbor(itRight, noNeighbor, itLeft);\n\n    tri.fixedEdges.insert(Edge(is, ie));\n    if(ie != edge.v2())\n        return InsertOneEdge(Edge(ie, edge.v2()));\n}\n\ntemplate <typename num_type>\ninline void Triangulator2D<num_type>::Delaunay(std::stack<TriIdx> & triangles, VerIdx iv)\n{\n    while(!triangles.empty()){\n        TriIdx it = triangles.top();\n        triangles.pop();\n\n        const auto & triangle = tri.triangles[it];\n        TriIdx itOp = triangle.VeOpTn(iv);\n        if(itOp == noNeighbor) continue;\n        if(isNeedFlip(iv, it, itOp)){\n            tri.FlipEdge(it, itOp);\n            triangles.push(it);\n            triangles.push(itOp);\n        }\n    }\n}\n\ntemplate <typename num_type>\ninline bool Triangulator2D<num_type>::isNeedFlip(VerIdx iv, TriIdx it, TriIdx itOp) const\n{\n    const Triangle & triOp = tri.triangles[itOp];\n    size_t i = triOp.TnOpiVe(it);\n    VerIdx ivOp = triOp.vertices[i];\n    if(iv < 3 && ivOp < 3) return false;\n\n    VerIdx ivCw  = triOp.vertices[Triangle:: cw(i)];\n    VerIdx ivCcw = triOp.vertices[Triangle::ccw(i)];\n    const Point & p0 = tri.VerIdxPoint(iv);\n    const Point & p1 = tri.VerIdxPoint(ivCw);\n    const Point & p2 = tri.VerIdxPoint(ivOp);\n    const Point & p3 = tri.VerIdxPoint(ivCcw);\n    if(ivCw < 3) return GetPointLineLocation(p1, p2, p3) == GetPointLineLocation(p0, p2, p3);\n    else if(ivCcw < 3) return GetPointLineLocation(p3, p1, p2) == GetPointLineLocation(p0, p1, p2);\n    else return isInCircumCircle(p0, p1, p2, p3);\n}\n\ntemplate <typename num_type>\ninline bool Triangulator2D<num_type>::isInCircumCircle(const Point & p, const Point & p1, const Point & p2, const Point & p3) const\n{\n    return geometry::isInCircumCircle(p1, p2, p3, p, false);\n}\n\ntemplate <typename num_type>\ninline std::tuple<TriIdx, VerIdx, VerIdx>\nTriangulator2D<num_type>::IntersectedTriangle(VerIdx iA,\n                                                const TriIdxSet & candidates,\n                                                const Point & a, const Point & b) const\n{\n    for(TriIdx it : candidates){\n        const Triangle & triangle = tri.triangles[it];\n        auto i = triangle.iVe(iA);\n        auto iv1 = triangle.vertices[Triangle::cw(i)];\n        auto iv2 = triangle.vertices[Triangle::ccw(i)];\n        auto locP1 = GetPointLineLocation(tri.VerIdxPoint(iv1), a, b);\n        auto locP2 = GetPointLineLocation(tri.VerIdxPoint(iv2), a, b);\n        if(locP2 == PointLineLocation::Right){\n            if(locP1 == PointLineLocation::OnLine)\n                return std::make_tuple(noNeighbor, iv1, iv2);\n            else if(locP1 == PointLineLocation::Left)\n                return std::make_tuple(it, iv1, iv2);\n        }\n    }\n    throw std::runtime_error(\"Could not find vertex triangle intersected by \"\n                             \"edge. Note: can be caused by duplicate points.\");\n}\n\ntemplate <typename num_type>\ninline void Triangulator2D<num_type>::RemoveSuperTriangleVertices()\n{\n    for(VerIdx iv = 0; iv < 3; ++iv)\n        op.RemoveOneVertex(iv);\n    op.ReallocateTriangulation();\n}\n\ntemplate <typename num_type>\ntemplate <typename TriIdxIterator>\nvoid Triangulator2D<num_type>::RemoveTriangles(TriIdxIterator begin, TriIdxIterator end)\n{\n    for(auto iter = begin; iter != end; ++iter)\n        op.RemoveOneTriangle(*iter);\n    op.ReallocateTriangulation();\n}\n\ntemplate <typename num_type>\ninline TriIdx Triangulator2D<num_type>::TriangulatePseudoPolygon(VerIdx ia, VerIdx ib, const std::vector<VerIdx> & points)\n{\n    if(points.empty())\n        return PesudoPolyOuterTriangle(ia, ib);\n    \n    VerIdx ic = FindDelaunayPoint(ia, ib, points);\n    auto split = SplitPsedoPolygon(ic, points);\n    auto it2 = TriangulatePseudoPolygon(ic, ib, split.second);\n    auto it1 = TriangulatePseudoPolygon(ia, ic, split.first);\n    Triangle t = {{ia, ib, ic}, {noNeighbor, it2, it1}};\n    TriIdx it = op.AddOneTriangle(t);\n    if(it1 != noNeighbor){\n        if(split.first.empty())\n            tri.ChangeNeighbor(it1, ia, ic, it);\n        else\n            tri.triangles[it1].neighbors[0] = it;\n    }\n    if(it2 != noNeighbor){\n        if(split.second.empty())\n            tri.ChangeNeighbor(it2, ic, ib, it);\n        else\n            tri.triangles[it2].neighbors[0] = it;\n    }\n    tri.AddAdjacentTriangle(ia, it);\n    tri.AddAdjacentTriangle(ib, it);\n    tri.AddAdjacentTriangle(ic, it);\n    return it;\n}\n\ntemplate <typename num_type>\ninline TriIdx Triangulator2D<num_type>::PesudoPolyOuterTriangle(VerIdx ia, VerIdx ib) const\n{\n    const auto & aTris = tri.vertices[ia].triangles;\n    const auto & bTris = tri.vertices[ib].triangles;\n    for(auto iter = aTris.begin(); iter != aTris.end(); ++iter){\n        if(std::find(bTris.begin(), bTris.end(), *iter) != bTris.end())\n            return *iter;\n    }\n    return noNeighbor;\n}\n\ntemplate <typename num_type>\ninline VerIdx Triangulator2D<num_type>::FindDelaunayPoint(VerIdx ia, VerIdx ib, const std::vector<VerIdx> & vs) const\n{\n    assert(!vs.empty());\n    const auto & a = tri.VerIdxPoint(ia);\n    const auto & b = tri.VerIdxPoint(ib);\n    VerIdx ic = vs.front();\n    auto c = tri.VerIdxPoint(ic);\n    for(auto iter = vs.begin(); iter != vs.end(); ++iter){\n        const auto & v = tri.VerIdxPoint(*iter);\n        if(!isInCircumCircle(v, a, b, c)) continue;\n        ic = *iter;\n        c = tri.VerIdxPoint(ic);\n    }\n    return ic;\n}\n\ntemplate <typename num_type>\ninline std::pair<std::vector<VerIdx>, std::vector<VerIdx> >\nTriangulator2D<num_type>::SplitPsedoPolygon(VerIdx vi, const std::vector<VerIdx> & points)\n{\n    std::pair<std::vector<VerIdx>, std::vector<VerIdx> > out;\n    auto iter = points.begin();\n    for(; vi != *iter; ++iter)\n        out.first.push_back(*iter);\n    for(++iter; iter != points.end(); ++iter)\n        out.second.push_back(*iter);\n    return out;\n}\n\ntemplate <typename num_type>\ninline TriIdxSet Triangulator2D<num_type>::Grow2Boundary(std::stack<TriIdx> & seeds) const\n{\n    TriIdxSet traversed;\n    while(!seeds.empty()){\n        auto it = seeds.top();\n        seeds.pop();\n        traversed.insert(it);\n        const auto & triange = tri.triangles[it];\n        for(auto i = 0; i < 3; ++i){\n            Edge opEdge = Edge(\n                        triange.vertices[Triangle::ccw(i)],\n                        triange.vertices[Triangle::cw(i)]);\n            if(tri.fixedEdges.count(opEdge)) continue;\n            TriIdx in = triange.neighbors[Triangle::iVeOpiTn(i)];\n            if(in != noNeighbor && !traversed.count(in))\n                seeds.push(in);\n        }\n    }\n    return traversed;\n}\n\ntemplate <typename num_type>\ninline std::vector<typename Triangulator2D<num_type>::Depth>\nTriangulator2D<num_type>::CalculateTriangleDepths(const std::vector<Vertex> & vertices,\n                                                    const TriangleVec & triangles,\n                                                    const EdgeSet & fixedEdges)\n{\n    std::vector<Depth> triDepths(triangles.size(), std::numeric_limits<Depth>::max());\n\n    using TriDeque = std::deque<TriIdx>;\n    using TriStack = std::stack<TriIdx>;\n    TriStack seeds(TriDeque(1, *(tri.vertices[0].triangles.begin())));\n    Depth layerDepth = 0;\n    do{\n        auto newSeeds = PeelLayer(seeds, triangles, fixedEdges, layerDepth++, triDepths);\n        seeds = TriStack(TriDeque(newSeeds.begin(), newSeeds.end()));\n    } while(!seeds.empty());\n\n    return triDepths;\n}\n\ntemplate <typename num_type>\ninline TriIdxSet Triangulator2D<num_type>::PeelLayer(std::stack<TriIdx> seeds,\n                                        const TriangleVec & triangles,\n                                        const EdgeSet & fixedEdges,\n                                        Depth depth,\n                                        std::vector<Depth> & triDepths)\n{\n    TriIdxSet behindBoundary;\n    while(!seeds.empty()){\n        auto it = seeds.top();\n        seeds.pop();\n        triDepths[it] = depth;\n        behindBoundary.erase(it);\n        const auto & triangle = triangles[it];\n        for(auto i = 0; i < 3; ++i){\n            Edge opEdge(triangle.vertices[Triangle::ccw(i)],\n                        triangle.vertices[Triangle:: cw(i)]);\n            TriIdx in = triangle.neighbors[Triangle::iVeOpiTn(i)];\n            if(in == noNeighbor || triDepths[in] <= depth) continue;\n            if(fixedEdges.count(opEdge)){\n                behindBoundary.insert(in);\n                continue;\n            }\n            seeds.push(in);\n        }\n    }\n    return behindBoundary;\n}\n\ntemplate <typename num_type>\ninline void Triangulator2D<num_type>::Clear()\n{\n    op.Clear();\n}\n\ntemplate <typename num_type>\nclass ConvexTriangulator2D\n{\n    struct DoublyLinkedIndex { VerIdx prev, curr, next; };\npublic:\n    using float_t = float_type<num_type>;\n    using Point = Point2D<num_type>;\n    using Edge = IndexEdge;\n    using Vertex = IndexVertex;\n    using Triangle = IndexTriangle;\n    using Utility = TriangulationUtility<Point>;\n    using EdgeSet = typename Triangulation<Point>::EdgeSet;\n    using TriIdxMap = std::unordered_map<TriIdx, TriIdx>;\n    \n\n    Triangulation<Point> & tri;\n    TriangulationOperator<Point> op;\n    ConvexTriangulator2D(Triangulation<Point> & t) : tri(t), op(t) { op.Clear(); }\n\n    template <typename VertexIterator,\n              typename CoorXGetter,\n              typename CoorYGetter>\n    void Triangulate(VertexIterator begin, VertexIterator end, CoorXGetter xGetter, CoorYGetter yGetter)\n    {\n        const size_t size = std::distance(begin, end);\n        assert(size >= 3);\n        \n        size_t i = 0;\n        std::vector<DoublyLinkedIndex> vertices(size);\n        for(auto iter = begin; iter != end; ++iter){\n            vertices[i++].curr = op.AddOneVertex(Point(xGetter(*iter), yGetter(*iter)));\n        }\n\n        for(size_t i = 0; i < size; ++i){\n            vertices[i].prev = vertices[(i + size - 1) % size].curr;\n            vertices[i].next = vertices[(i + 1) % size].curr;\n        }\n        \n        for(size_t i = size - 1; i > 3; --i){\n            vertices[i - 1].next = vertices[i].next;\n        }\n\n        TriIdx it = AddTriangle(vertices[0].curr, vertices[1].curr, vertices[2].curr);\n        for(size_t i = 3; i < size; ++i)\n            ConvexInsertVertex(vertices[i].curr, Edge(vertices[i].prev, vertices[i].next));\n        \n        op.ReallocateTriangulation();\n\n    }\n\nprivate:\n\n    TriIdx AddTriangle(VerIdx iv1, VerIdx iv2, VerIdx iv3)\n    {\n        return op.AddOneTriangle(iv1, iv2, iv3);\n    }\n\n    void ConvexInsertVertex(VerIdx iv, const Edge & e)\n    {\n        TriIdx it;\n        std::tie(it, std::ignore) = tri.GetTriangles(e);\n        VerIdx iu = e.v1(), iw = e.v2();\n        if(noNeighbor == it){\n            AddTriangle(iv, iu, iw);\n            return;\n        }\n        VerIdx ix = tri.triangles[it].EgOpVe(e);\n        if(Utility::isInCircumCircle(tri, it, tri.VerIdxPoint(iv))){\n            op.RemoveOneTriangle(it);\n            ConvexInsertVertex(iv, Edge(iu, ix));\n            ConvexInsertVertex(iv, Edge(ix, iw));\n        }\n        else AddTriangle(iv, iu, iw);\n    }\n};\n\nstruct DuplicatesInfo\n{\n    std::vector<size_t> mapping;\n    std::unordered_set<size_t> duplicates;\n};\n\n/**\n * @brief utility functions to find duplicated points within given tolerance\n * @param[in] points point collection\n * @param[in] tolerance treat points distance less than tolerance as duplicated \n * @return DuplicatesInfo duplicate results\n */\ntemplate <typename num_type>\ninline DuplicatesInfo FindDuplicates(const std::vector<Point2D<num_type> > & points, num_type tolerance)\n{\n    using Grid = std::pair<size_t, size_t>;\n    struct GridHash\n    {\n        size_t operator() (const Grid & grid) const noexcept\n        {\n            size_t seed(0);\n            boost::hash_combine(seed, grid.first);\n            boost::hash_combine(seed, grid.second);\n            return seed;\n        }\n    };\n\n    struct GridCmp\n    {\n        bool operator() (const Grid & g1, const Grid & g2) const noexcept\n        {\n            return g1 == g2;\n        }\n    };\n\n    using GridIdxMap = std::unordered_map<Grid, size_t, GridHash, GridCmp>;\n    const size_t shift = std::numeric_limits<size_t>::max() / 2;\n    auto toGrid = [tolerance, shift](const Point2D<num_type> & p)\n    {\n        size_t x = static_cast<size_t>(p[0] / tolerance + shift);\n        size_t y = static_cast<size_t>(p[1] / tolerance + shift);\n        return std::make_pair(x, y);\n    };\n\n    GridIdxMap gridIdxMap;\n    DuplicatesInfo dup { std::vector<size_t>(points.size()), std::unordered_set<size_t>() };\n    for(size_t iIn = 0, iOut = iIn; iIn < points.size(); ++iIn){\n        bool isUnique;\n        typename GridIdxMap::const_iterator iter;\n        std::tie(iter, isUnique) = gridIdxMap.insert(std::make_pair(toGrid(points[iIn]), iOut));\n        if(isUnique){\n            dup.mapping[iIn] = iOut++;\n            continue;\n        }\n        dup.mapping[iIn] = iter->second;\n        dup.duplicates.insert(iIn);\n    }\n    return dup;\n}\n\n/**\n * @brief remaps edges with duplicated functions\n * @param[in, out] edges input edges\n * @param[in] mapping duplicated info, point n is duplicated with mapping[n]\n */\ninline void RemapEdges(std::list<IndexEdge> & edges, const std::vector<size_t> & mapping)\n{\n    for(auto iter = edges.begin(); iter != edges.end();){\n        iter->SetVertices(mapping[iter->v1()], mapping[iter->v2()]);\n        if(iter->v1() == iter->v2())\n            iter = edges.erase(iter);\n        else ++iter;\n    }\n}\n\n/**\n * @brief removes duplicate points of a point collection\n * @param[in, out] points the given point collection \n * @param duplicates duplicated info, point n is duplicated with mapping[n]\n */\ntemplate <typename num_type>\ninline void RemoveDuplicates(std::vector<Point2D<num_type> > & points, const std::unordered_set<size_t> & duplicates)\n{\n    for(size_t i = 0, iNew = i; i < points.size(); ++i){\n        if(duplicates.count(i)) continue;\n        points[iNew] = points[i];\n        iNew++;\n    }\n    points.erase(points.end() - duplicates.size(), points.end());\n}\n\n/**\n * @brief removes duplicate points and remap edges\n * @param[in, out] points the given point collection \n * @param[in, out] edges the given edge collection \n * @param[in] tolerance merge tolerance\n * @return DuplicatesInfo duplicate results\n */\ntemplate <typename num_type>\ninline DuplicatesInfo RemoveDuplicatesAndRemapEdges(std::vector<Point2D<num_type> > & points, std::list<IndexEdge> & edges, num_type tolerance)\n{\n    DuplicatesInfo dup = FindDuplicates(points, tolerance);\n    RemoveDuplicates(points, dup.duplicates);\n    RemapEdges(edges, dup.mapping);\n    return dup;\n}\n\n}//namespace tri\n}//namespace geometry\n}//namespace generic\n#endif//GENERIC_GEOMETRY_TRI_TRIANGULATOR_HPP\n", "meta": {"hexsha": "3d940983f184f5fbe5db7897fb2d5efa37821ac3", "size": 26358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometry/Triangulator.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": "geometry/Triangulator.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": "geometry/Triangulator.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": 35.9590723056, "max_line_length": 143, "alphanum_fraction": 0.6407542302, "num_tokens": 6776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5448213413479631}}
{"text": "#include <iostream>\n#include <time.h>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/random.hpp>\n#include <boost/program_options.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::ublas;\nusing namespace boost::random;\nusing namespace boost::program_options;\n\nint main (int argc, char* argv[]) {\n    int scale = 2, depth = 2;\n\n    try {\n        options_description opts(\"options\");\n        opts.add_options()\n            (\"help,h\", \"help message\")\n            (\"scale,S\", value<int>()->implicit_value(2), \"2^scale motif verticies\")\n            (\"depth,D\", value<int>()->implicit_value(2), \"recursive depth\");\n    \n        variables_map vm;\n        store(parse_command_line(argc, argv, opts), vm);\n        notify(vm);\n\n        if (vm.count(\"help\")) {\n            cout << opts << endl;\n            return 0;\n        }\n    \n        if (vm.count(\"scale\")) scale = vm[\"scale\"].as<int>();\n        if (vm.count(\"depth\")) depth = vm[\"depth\"].as<int>();\n    } catch(exception& e) {\n        cout << e.what() << endl;\n        cout << \"use '-h' to get help.\" << endl;\n        return -1;\n    }\n\n    unsigned motif_size  = 1 << scale;\n    unsigned result_size = 1 << (scale * (depth + 1));\n    unsigned motif_mask  = motif_size - 1;\n\n    cout << result_size << endl;\n\n    boost::mt19937 rng(time(0));\n    boost::uniform_int<> binary(0, 1);\n\n    matrix<int> motif(motif_size, motif_size);\n\n    for (unsigned i = 0; i < motif_size; ++ i)\n        for (unsigned j = 0; j < motif_size; ++ j)\n            motif(i, j) = (j < i) ? binary(rng) : 0;\n\n    motif += trans(motif);\n\n    cout << motif << endl;\n\n    auto kronecker_cell = [=](unsigned i, unsigned j) {\n        int cell = 1;\n        unsigned motif_i = i, motif_j = j;\n        for (unsigned d = 0; d < depth + 1; ++ d) {\n            cell *= motif(motif_i & motif_mask, motif_j & motif_mask);\n            motif_i >>= scale;\n            motif_j >>= scale;\n        }\n        return cell;\n    };\n\n    for (unsigned i = 0; i < result_size; ++ i ) {\n        for (unsigned j = 0; j < result_size; ++ j)\n           cout << kronecker_cell(i, j) << ' ';\n        cout << endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "7caaeb6c8720cdebe511760f52a19755b2b5ff94", "size": 2180, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "practice/matrix4.cpp", "max_stars_repo_name": "ShiZhan/graph-study", "max_stars_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-14T07:27:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-15T03:11:31.000Z", "max_issues_repo_path": "practice/matrix4.cpp", "max_issues_repo_name": "Zhan2012/graph-study", "max_issues_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practice/matrix4.cpp", "max_forks_repo_name": "Zhan2012/graph-study", "max_forks_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "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.9487179487, "max_line_length": 83, "alphanum_fraction": 0.5417431193, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5448213399483358}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\n\nint main()\n{\n    using mtl::srange; using mtl::imax;\n    // For a more realistic example set sz to 1000 or larger\n    const int size = 3, N = size * size; \n\n    typedef mtl::compressed2D<double>  \t   matrix_type;\n    typedef itl::pc::ic_0<matrix_type> \t   ic_type;\n    typedef itl::pc::diagonal<matrix_type> dia_type;\n\n    mtl::compressed2D<double>          A;\n    laplacian_setup(A, size, size);\n    // mtl::io::tout << \"A is\\n\" << A << '\\n';\n\n    itl::pc::concat<ic_type, dia_type, matrix_type> L(A);\n    // ic_type                                         L(A);\n    itl::pc::identity<matrix_type>                  R(A);\n\n    mtl::dense_vector<double>          x(N, 1.0), b(N);\n    \n    b = A * x;\n    x= 0;\n\n    itl::cyclic_iteration<double> iter(b, N, 1.e-6, 0.0, 3);\n    cg(A, x, b, L, iter);\n\n    // Test if adjoint works (do not try bicg, it convergences poorly)\n    x= 0;\n    itl::cyclic_iteration<double> iter2(b, N, 1.e-6, 0.0, 5);\n    qmr(A, x, b, L, R, iter2);\n\n    return 0;\n}\n", "meta": {"hexsha": "c6d3adfbe59f976b42e86bfddbb905cc77bfbf96", "size": 1509, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/concat_pc_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/itl/test/concat_pc_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/itl/test/concat_pc_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.18, "max_line_length": 94, "alphanum_fraction": 0.5977468522, "num_tokens": 470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5448213296402731}}
{"text": "#include \"advent.hpp\"\n#include \"intersect.hpp\"\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <numeric>\n#include <vector>\n#include <tuple>\n#include <ranges>\n#include <string>\n#include <scn/scn.h>\n#include <fmt/ranges.h>\n#include <set>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing std::vector;\nusing std::pair;\nusing std::string;\nusing std::ifstream;\nusing std::ranges::stable_sort;\n\nstruct def {\n    static constexpr i64 nd{3}; // number of dimensions\n    static constexpr i64 ncommon{12}; // number of beacons in common\n};\n\nusing point = std::tuple<i64, i64, i64>;\n\nstruct scanner {\n    i64 id;\n    std::optional<point> position; // scanner position\n    Eigen::MatrixXd beacons; // beacon positions\n    Eigen::Matrix<i64, -1, -1> distances; // distance matrix between beacons\n    Eigen::Matrix<i64, -1, -1> sorted_distances; // distance matrix between beacons\n\n    explicit scanner(i64 i, Eigen::MatrixXd b)\n        : id(i)\n        , position(std::nullopt)\n        , beacons(std::move(b))\n        , distances(compute_distance_matrix(beacons))\n        , sorted_distances(distances)\n    {\n        // sort the values so we can use intersection count\n        for (auto col : sorted_distances.colwise()) {\n            stable_sort(col);\n        }\n    }\n\n    static auto compute_distance_matrix(auto const& m) -> Eigen::Matrix<i64, -1, -1>\n    {\n        Eigen::Matrix<i64, -1, -1> d = decltype(d)::Zero(m.cols(), m.cols());\n        for (auto i = 0L; i < m.cols()-1; ++i) {\n            for (auto j = i+1; j < m.cols(); ++j) {\n                d(i, j) = d(j, i) = static_cast<i64>((m.col(i) - m.col(j)).matrix().squaredNorm());\n            }\n        }\n        return d;\n    }\n\n    [[nodiscard]] auto find_common_beacons(scanner const& s) const\n    {\n        vector<pair<i64, i64>> map;\n        for (auto i = 0L; i < distances.cols(); ++i) {\n            auto ci = sorted_distances.col(i);\n            for (auto j = 0L; j < s.distances.cols(); ++j) {\n                auto cj = s.sorted_distances.col(j);\n                auto count = detail::count_intersect(ci.data(), ci.size(), cj.data(), cj.size());\n                if(count == def::ncommon) {\n                    vector<i64> chosen(s.distances.cols(), 0);\n                    for (auto k = 0L; k < distances.cols(); ++k) {\n                        for (auto l = 0L; l < s.distances.cols(); ++l) {\n                            if (!chosen[l] && distances(k, i) == s.distances(l, j)) {\n                                chosen[l] = 1;\n                                map.emplace_back(l, k);\n                            }\n                        }\n                    }\n                    return map;\n                }\n            }\n        }\n        return map;\n    }\n\n    auto translate(scanner const& dest, vector<pair<i64, i64>> const& map) -> void\n    {\n        vector<i64> idx; idx.reserve(map.size());\n        vector<i64> dest_idx; dest_idx.reserve(map.size());\n        for(auto [i, j] : map) {\n            idx.push_back(j);\n            dest_idx.push_back(i);\n        }\n        Eigen::MatrixXd tr = Eigen::umeyama(beacons(Eigen::all, idx), dest.beacons(Eigen::all, dest_idx)).array().round();\n        auto t = tr.col(tr.cols()-1).template cast<i64>();\n        position = {t(0), t(1), t(2)};\n        beacons = (tr * beacons.colwise().homogeneous()).block(0, 0, beacons.rows(), beacons.cols());\n    }\n\n    friend auto operator<<(std::ostream& os, scanner const& s) -> std::ostream&;\n};\n\nauto operator<<(std::ostream& os, scanner const& s) -> std::ostream&\n{\n    os << \"scanner \" << s.id << \" position: \";\n    if (s.position) { \n        auto [x, y, z] = *s.position;\n        os << \"(\" << x << \",\" << y << \",\" << z << \")\\n\";\n    }\n    else { os << \"(?,?,?)\\n\"; }\n    os << \"beacons:\\n\";\n    os << s.beacons << \"\\n\";\n    return os;\n}\n\nauto read_input(int argc, char** argv) {\n    // read input\n    if (argc < 2) {\n        throw std::runtime_error(\"Error: no input.\");\n    }\n\n    ifstream infile(argv[1]);\n    string line;\n\n    vector<scanner> scanners;\n\n    vector<vector<double>> values;\n    i64 id{0};\n    while (std::getline(infile, line)) {\n        if (line[0] == '-' && line[1] == '-') { continue; }\n        if (line.empty()) {\n            Eigen::MatrixXd beacons(def::nd, values.size());\n            for (auto i = 0L; i < std::ssize(values); ++i) {\n                beacons.col(i) = Eigen::Map<Eigen::Array<double, -1, 1>>(values[i].data(), std::ssize(values[i]));\n            }\n            scanners.emplace_back(id++, std::move(beacons));\n            values.clear();\n            continue;\n        }\n        values.emplace_back();\n        scn::scan_list(line, values.back(), ',');\n    }\n    scanners[0].position = {0, 0, 0};\n\n    return scanners;\n}\n\nauto day19(int argc, char** argv) -> int\n{\n    auto scanners = read_input(argc, argv);\n    vector<scanner> known{scanners[0]};\n\n    while (known.size() < scanners.size()) {\n        auto sz = std::ssize(known); \n        for (auto i = 0L; i < sz; ++i) {\n            auto const& s = known[i];\n            for (auto& p : scanners) {\n                if (p.position) { continue; }\n                if (auto map = p.find_common_beacons(s); std::ssize(map) == def::ncommon) {\n                    p.translate(s, map);\n                    known.push_back(p);\n                    break;\n                }\n            }\n        }\n    }\n\n    std::set<point> unique_beacons;\n    auto manhattan = 0L;\n    for (auto const& s : scanners) {\n        for (auto col : s.beacons.colwise()) {\n            auto t = col.template cast<i64>();\n            unique_beacons.insert({t(0), t(1), t(2)});\n        }\n        auto [x1, y1, z1] = *s.position;\n        Eigen::Array<i64, 3, 1> v{x1, y1, z1};\n        for (auto const& p : scanners) {\n            auto [x2, y2, z2] = *p.position;\n            Eigen::Array<i64, 3, 1> u{x2, y2, z2}; \n            manhattan = std::max(manhattan, (u - v).abs().sum());\n        }\n    }\n    fmt::print(\"part 1: {}\\n\", unique_beacons.size());\n    fmt::print(\"part 2: {}\\n\", manhattan);\n\n    return 0;\n}\n", "meta": {"hexsha": "68935f2e95bd6f43de931fd8d6048f4b52e3d666", "size": 6029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/day19.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/day19.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/day19.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": 31.7315789474, "max_line_length": 122, "alphanum_fraction": 0.5090396417, "num_tokens": 1620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.5448035296277369}}
{"text": "/*\n    This file is part of utils-lib.\n\n    Copyright (c) 2020, 2021, 2022 Bernardo Fichera <bernardo.fichera@gmail.com>\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n*/\n\n#ifndef utils_lib_GRADIENT_CHECKER_HPP\n#define utils_lib_GRADIENT_CHECKER_HPP\n\n#include <Eigen/Core>\n#include <iostream>\n\nnamespace utils_lib {\n    template <typename Precision = double>\n    class DerivativeChecker {\n    public:\n        DerivativeChecker(const size_t& dim = 1, const size_t& res = 51) : _dim(dim), _res(res) {}\n\n        DerivativeChecker& setResolution(const size_t& res)\n        {\n            _res = res;\n            return *this;\n        }\n\n        DerivativeChecker& setDimension(const size_t& dim)\n        {\n            _dim = dim;\n            return *this;\n        }\n\n        Eigen::Matrix<Precision, Eigen::Dynamic, Eigen::Dynamic> numericalGradient()\n        {\n            Eigen::Matrix<Precision, Eigen::Dynamic, Eigen::Dynamic> M(_t.rows(), 2);\n            M << _t, _G;\n\n            return M;\n        }\n\n        Eigen::Matrix<Precision, Eigen::Dynamic, Eigen::Dynamic> numericalHessian()\n        {\n            Eigen::Matrix<Precision, Eigen::Dynamic, Eigen::Dynamic> M(_t.rows(), 2);\n            M << _t, _H;\n\n            return M;\n        }\n\n        template <typename Function, typename Gradient>\n        bool checkGradient(Function f, Gradient g, const Eigen::VectorXd& x, const Eigen::VectorXd& v)\n        {\n            // Init G\n            _G.setZero(_res);\n\n            // Generate log spaced perturbation intensities\n            _t = Eigen::Matrix<Precision, Eigen::Dynamic, 1>::LinSpaced(_res, -8, 0);\n            for (size_t i = 0; i < _t.rows(); i++)\n                _t(i) = std::pow(10, _t(i));\n\n            // Calculate first order Taylor expansion\n            for (size_t i = 0; i < _t.rows(); i++)\n                _G(i) = std::abs(f(x + _t(i) * v) - f(x) - _t(i) * g(x).dot(v));\n\n            // Transform to log space\n            _t = _t.array().log();\n            _G = _G.array().log();\n\n            // Calculate mean slope for central values\n            Precision mean_slope = 0, num_points = 0;\n\n            for (size_t i = 20; i < _res - 20; i++) {\n                mean_slope = mean_slope + (_G(i + 1) - _G(i)) / (_t(i + 1) - _t(i));\n                num_points++;\n            }\n\n            mean_slope /= num_points;\n\n            std::cout << \"First order Taylor expansion slope: \" << mean_slope << \" - It should be approximately equal to 2.0\" << std::endl;\n\n            return (std::abs(mean_slope - 2.0) <= 1e-3) ? true : false;\n        }\n\n        template <typename Function, typename Gradient>\n        bool checkGradient(Function f, Gradient g)\n        {\n            // Generate random test point and perturbation direction\n            Eigen::VectorXd x = Eigen::VectorXd::Random(_dim), v = Eigen::VectorXd::Random(_dim);\n\n            // Init G\n            _G.setZero(_res);\n\n            // Generate log spaced perturbation intensities\n            _t = Eigen::Matrix<Precision, Eigen::Dynamic, 1>::LinSpaced(_res, -8, 0);\n            for (size_t i = 0; i < _t.rows(); i++)\n                _t(i) = std::pow(10, _t(i));\n\n            // Calculate first order Taylor expansion\n            for (size_t i = 0; i < _t.rows(); i++)\n                _G(i) = std::abs(f(x + _t(i) * v) - f(x) - _t(i) * g(x).dot(v));\n\n            // Transform to log space\n            _t = _t.array().log();\n            _G = _G.array().log();\n\n            // Calculate mean slope for central values\n            Precision mean_slope = 0, num_points = 0;\n\n            for (size_t i = 20; i < _res - 20; i++) {\n                mean_slope = mean_slope + (_G(i + 1) - _G(i)) / (_t(i + 1) - _t(i));\n                num_points++;\n            }\n\n            mean_slope /= num_points;\n\n            std::cout << \"First order Taylor expansion slope: \" << mean_slope << \" - It should be approximately equal to 2.0\" << std::endl;\n\n            return (std::abs(mean_slope - 2.0) <= 1e-3) ? true : false;\n        }\n\n        template <typename Function, typename Gradient, typename Hessian>\n        bool checkHessian(Function f, Gradient g, Hessian h, const Eigen::VectorXd& x, const Eigen::VectorXd& v)\n        {\n            // Init H\n            _H.setZero(_res);\n\n            // Generate log spaced perturbation intensities\n            _t = Eigen::Matrix<Precision, Eigen::Dynamic, 1>::LinSpaced(_res, -8, 0);\n            for (size_t i = 0; i < _t.rows(); i++)\n                _t(i) = std::pow(10, _t(i));\n\n            // Calculate second order Taylor expansion\n            for (size_t i = 0; i < _t.rows(); i++)\n                _H(i) = std::abs(f(x + _t(i) * v) - f(x) - _t(i) * g(x).dot(v) - 0.5 * std::pow(_t(i), 2) * h(x, v).dot(v));\n\n            // Transform to log space\n            _t = _t.array().log();\n            _H = _H.array().log();\n\n            // Calculate mean slope for central values\n            Precision mean_slope = 0, num_points = 0;\n\n            for (size_t i = 30; i < _res - 10; i++) {\n                mean_slope = mean_slope + (_H(i + 1) - _H(i)) / (_t(i + 1) - _t(i));\n                num_points++;\n            }\n\n            mean_slope /= num_points;\n\n            std::cout << \"Second order Taylor expansion slope: \" << mean_slope << \" - It should be approximately equal to 3.0\" << std::endl;\n\n            return (std::abs(mean_slope - 3.0) <= 1e-3) ? true : false;\n        }\n\n        template <typename Function, typename Gradient, typename Hessian>\n        bool checkHessian(Function f, Gradient g, Hessian h)\n        {\n            // Generate random test point and perturbation direction\n            Eigen::VectorXd x = Eigen::VectorXd::Random(_dim), v = Eigen::VectorXd::Random(_dim);\n\n            // Init H\n            _H.setZero(_res);\n\n            // Generate log spaced perturbation intensities\n            _t = Eigen::Matrix<Precision, Eigen::Dynamic, 1>::LinSpaced(_res, -8, 0);\n            for (size_t i = 0; i < _t.rows(); i++)\n                _t(i) = std::pow(10, _t(i));\n\n            // Calculate second order Taylor expansion\n            for (size_t i = 0; i < _t.rows(); i++)\n                _H(i) = std::abs(f(x + _t(i) * v) - f(x) - _t(i) * g(x).dot(v) - 0.5 * std::pow(_t(i), 2) * h(x, v).dot(v));\n\n            // Transform to log space\n            _t = _t.array().log();\n            _H = _H.array().log();\n\n            // Calculate mean slope for central values\n            Precision mean_slope = 0, num_points = 0;\n\n            for (size_t i = 30; i < _res - 10; i++) {\n                mean_slope = mean_slope + (_H(i + 1) - _H(i)) / (_t(i + 1) - _t(i));\n                num_points++;\n            }\n\n            mean_slope /= num_points;\n\n            std::cout << \"Second order Taylor expansion slope: \" << mean_slope << \" - It should be approximately equal to 3.0\" << std::endl;\n\n            return (std::abs(mean_slope - 3.0) <= 1e-3) ? true : false;\n        }\n\n    protected:\n        size_t _dim, _res;\n\n        Eigen::Matrix<Precision, Eigen::Dynamic, 1> _t, _G, _H;\n    };\n} // namespace utils_lib\n\n#endif // utils_lib_GRADIENT_CHECKER_HPP", "meta": {"hexsha": "a16df4d9f1f3289549ca6dc6d9fabb0ffd32978e", "size": 8110, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils_lib/DerivativeChecker.hpp", "max_stars_repo_name": "nash169/utils-lib", "max_stars_repo_head_hexsha": "a734c63fb66b9b5e2f4dba2d2e210b05364ecb88", "max_stars_repo_licenses": ["MIT"], "max_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_lib/DerivativeChecker.hpp", "max_issues_repo_name": "nash169/utils-lib", "max_issues_repo_head_hexsha": "a734c63fb66b9b5e2f4dba2d2e210b05364ecb88", "max_issues_repo_licenses": ["MIT"], "max_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_lib/DerivativeChecker.hpp", "max_forks_repo_name": "nash169/utils-lib", "max_forks_repo_head_hexsha": "a734c63fb66b9b5e2f4dba2d2e210b05364ecb88", "max_forks_repo_licenses": ["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.8971962617, "max_line_length": 140, "alphanum_fraction": 0.5488286067, "num_tokens": 2120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355188, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5447555920164006}}
{"text": "\n// solving A * X = B\n// using driver function gesv()\n\n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <cstddef>\n#include <iostream>\n#include <boost/numeric/bindings/blas/level1/set.hpp>\n#include <boost/numeric/bindings/blas/level3/gemm.hpp>\n#include <boost/numeric/bindings/lapack/driver/gesv.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace blas = boost::numeric::bindings::blas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\n#ifndef F_ROW_MAJOR\ntypedef ublas::matrix<double, ublas::column_major> m_t;\n#else\ntypedef ublas::matrix<double, ublas::row_major> m_t;\n#endif\n\nint main() {\n\n  cout << endl; \n\n  size_t n = 5;   \n  m_t a (n, n);   // system matrix \n\n  size_t nrhs = 2; \n  m_t x (n, nrhs), bb (n, nrhs);  \n  // b -- right-hand side matrix, see below \n\n  init_symm (a); \n  //     [n   n-1 n-2  ... 1]\n  //     [n-1 n   n-1  ... 2]\n  // a = [n-2 n-1 n    ... 3]\n  //     [        ...       ]\n  //     [1   2   ...  n-1 n]\n\n  m_t const aa (a); // copy of a, because a is `lost' after gesv()\n\n  ublas::matrix_column<m_t> xc0 (x, 0), xc1 (x, 1); \n  blas::set( 1., xc0 );\n  blas::set (2., xc1);\n  blas::gemm ( 1., a, x, 0.0, bb);  // bb = a x, so we know the result ;o) \n\n  print_m (a, \"A\"); \n  cout << endl; \n  print_m (bb, \"B\"); \n  cout << endl; \n\n  // see leading comments for `gesv()' in clapack.hpp\n#ifndef F_ROW_MAJOR\n  m_t b (bb); \n#else \n  m_t b (ublas::trans (bb)); \n#endif \n  print_m (b, \"B for gesv()\"); \n  cout << endl; \n\n  std::vector< int > pivot( bindings::size1( a ) );\n  lapack::gesv (a, pivot,  b);  // solving the system, b contains x \n\n#ifndef F_ROW_MAJOR\n  print_m (b, \"X\");\n  cout << endl; \n  blas::gemm (1.0, aa, b, 0.0, x); \n#else\n  print_m (b, \"X^T\"); \n  cout << endl; \n  blas::gemm ( 1.0, aa, bindings::trans(b), 0.0, x); \n#endif \n  print_m (x, \"B = A X\"); \n\n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "92f77acd99873f54296551ffed1b6e988fe09c66", "size": 2064, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_gesv2.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/atlas/ublas_gesv2.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/atlas/ublas_gesv2.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": 23.4545454545, "max_line_length": 75, "alphanum_fraction": 0.5998062016, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5447555724233595}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <ceres/ceres.h>\n#include <ceres/cubic_interpolation.h>\n#include <superpixel_mesh/image.hpp>\n\nnamespace superpixel_mesh {\n\ntypedef ceres::Grid2D<ImageDataType> Grid;\ntypedef ceres::BiCubicInterpolator<Grid> Interpolator;\n\ntemplate <typename T> class Homography {\npublic:\n  typedef Eigen::Matrix<T, 2, 4> MatX;\n  typedef Eigen::Matrix<T, 2, 4> MatB;\n  typedef Eigen::Matrix<T, 3, 3> MatH;\n  typedef Eigen::Matrix<T, 8, 8> Mat8;\n  typedef Eigen::Matrix<T, 8, 1> Vec8;\n\n  static void ComputeHomography(const MatX &x1, const MatX &x2, Vec8 *H) {\n    Mat8 L = Mat8::Zero();\n    Vec8 b = Vec8::Zero();\n    /**\n     *\n     *  Add 2 rows for each point. Parametrization uses h9 = 1\n     *\n     *    0       0       0   -x1    -y1    -1    x1*y2  y1*y2    hi   =  -y2\n     *   -x1     -y1     -1     0      0     0    x1*x2  y1*x2    hi+1 =   -x2\n     */\n\n    for (int i = 0; i < 4; ++i) {\n      int r = i * 2;\n      L(r, 3) = x1(0, i);\n      L(r, 4) = x1(1, i);\n      L(r, 5) = T(1.0);\n      L(r, 6) = -x1(0, i) * x2(1, i);\n      L(r, 7) = -x1(1, i) * x2(1, i);\n      b(r) = x2(1, i);\n\n      L(r + 1, 0) = x1(0, i);\n      L(r + 1, 1) = x1(1, i);\n      L(r + 1, 2) = T(1.0);\n      L(r + 1, 6) = -x1(0, i) * x2(0, i);\n      L(r + 1, 7) = -x1(1, i) * x2(0, i);\n      b(r + 1) = x2(0, i);\n    }\n    // Solve Ax=B\n    Eigen::PartialPivLU<Mat8> dec(L);\n    (*H) = dec.solve(b);\n  }\n};\n\ntemplate <int SIZE, int PADDING = 2> struct PixelDissimilarityCost {\n\n  PixelDissimilarityCost(const Interpolator &inteporlator)\n      : interpolator(inteporlator) {}\n\n  template <typename T>\n  bool operator()(const T *const v1, const T *const v2, const T *const v3,\n                  const T *const v4, T *residuals) const {\n\n    // Compute the homography\n    typename Homography<T>::MatX x1, x2;\n    x1 << T(-PADDING), T(SIZE + PADDING), T(SIZE + PADDING), T(-PADDING),\n        T(-PADDING), T(-PADDING), T(SIZE + PADDING), T(SIZE + PADDING);\n    x2 << v1[0], v2[0], v3[0], v4[0], v1[1], v2[1], v3[1], v4[1];\n\n    typename Homography<T>::Vec8 h;\n    Homography<T>::ComputeHomography(x1, x2, &h);\n\n    T intensities[SIZE * SIZE];\n    T mean = T(0);\n    int intensity_index = 0;\n    for (int row = 0; row < SIZE; row++) {\n      for (int col = 0; col < SIZE; col++, intensity_index++) {\n        T x, y, s;\n        x = T(col);\n        y = T(row);\n        s = T(1.0) / (h(6) * x + h(7) * y + T(1.0));\n        interpolator.Evaluate(s * (h(3) * x + h(4) * y + h(5)),\n                              s * (h(0) * x + h(1) * y + h(2)),\n                              &intensities[intensity_index]);\n        mean += intensities[intensity_index];\n      }\n    }\n    const T normalization = T(1.0 / double(SIZE * SIZE));\n    mean *= normalization;\n    for (int intensity_index = 0; intensity_index < SIZE * SIZE;\n         intensity_index++) {\n      residuals[intensity_index] = intensities[intensity_index] - mean;\n    }\n\n    return true;\n  }\n\n  const Interpolator &interpolator;\n};\n\nstruct AreaRegularizationCost {\n\n  AreaRegularizationCost(const double target_area) : target_area(target_area) {}\n\n  template <typename T>\n  T TriangleArea(const T *const v1, const T *const v2,\n                 const T *const v3) const {\n    /**\n     * Shoelace formula:\n     * (1/2) | x1y2 + x2y3 + x3y1 - x2y1 - x3y2 - x1y3 |\n     */\n    const auto &x1 = v1[0];\n    const auto &y1 = v1[1];\n    const auto &x2 = v2[0];\n    const auto &y2 = v2[1];\n    const auto &x3 = v3[0];\n    const auto &y3 = v3[1];\n\n    return 0.5 * ceres::abs(x1 * y2 + x2 * y3 + x3 * y1 - x2 * y1 - x3 * y2 -\n                            x1 * y3);\n  }\n\n  template <typename T>\n  bool operator()(const T *const v1, const T *const v2, const T *const v3,\n                  const T *const v4, T *residuals) const {\n    T triangle_areas[4];\n    triangle_areas[0] = TriangleArea(v4, v3, v2);\n    triangle_areas[1] = TriangleArea(v3, v2, v1);\n    triangle_areas[2] = TriangleArea(v2, v1, v4);\n    triangle_areas[3] = TriangleArea(v1, v4, v3);\n\n    const T target_triangle_area = T(0.5 * target_area);\n    for (int triangle_index = 0; triangle_index < 4; triangle_index++)\n      residuals[triangle_index] =\n          target_triangle_area - triangle_areas[triangle_index];\n\n    return true;\n  }\n\n  const double target_area;\n};\n\n} // namespace superpixel_mesh\n", "meta": {"hexsha": "21e7a8a99df5f6aa664d8d314c37c57487e7a409", "size": 4307, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/superpixel_mesh/meshing_cost.hpp", "max_stars_repo_name": "manlito/superpixel-mesh", "max_stars_repo_head_hexsha": "34a1dd3a80054787e4e020f8ccfdabc17ca8051d", "max_stars_repo_licenses": ["MIT"], "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/superpixel_mesh/meshing_cost.hpp", "max_issues_repo_name": "manlito/superpixel-mesh", "max_issues_repo_head_hexsha": "34a1dd3a80054787e4e020f8ccfdabc17ca8051d", "max_issues_repo_licenses": ["MIT"], "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/superpixel_mesh/meshing_cost.hpp", "max_forks_repo_name": "manlito/superpixel-mesh", "max_forks_repo_head_hexsha": "34a1dd3a80054787e4e020f8ccfdabc17ca8051d", "max_forks_repo_licenses": ["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.3309859155, "max_line_length": 80, "alphanum_fraction": 0.5479452055, "num_tokens": 1524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5447411602949187}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu)  2011.\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/config.hpp>\n\n#if BOOST_METAPARSE_STD < 2011\n#include <iostream>\n\nint main()\n{\n  std::cout << \"Please use a compiler that supports constexpr\" << std::endl;\n}\n#else\n\n#define BOOST_MPL_LIMIT_STRING_SIZE 64\n#define BOOST_METAPARSE_LIMIT_STRING_SIZE BOOST_MPL_LIMIT_STRING_SIZE\n\n#include <boost/metaparse/grammar.hpp>\n#include <boost/metaparse/entire_input.hpp>\n#include <boost/metaparse/build_parser.hpp>\n#include <boost/metaparse/token.hpp>\n#include <boost/metaparse/string.hpp>\n#include <boost/metaparse/util/digit_to_int.hpp>\n\n#include <boost/mpl/apply_wrap.hpp>\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/front.hpp>\n#include <boost/mpl/back.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/times.hpp>\n#include <boost/mpl/divides.hpp>\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/eval_if.hpp>\n#include <boost/mpl/lambda.hpp>\n#include <boost/mpl/char.hpp>\n#include <boost/mpl/int.hpp>\n\nusing boost::metaparse::build_parser;\nusing boost::metaparse::entire_input;\nusing boost::metaparse::token;\nusing boost::metaparse::grammar;\n\nusing boost::metaparse::util::digit_to_int;\n\nusing boost::mpl::apply_wrap1;\nusing boost::mpl::fold;\nusing boost::mpl::front;\nusing boost::mpl::back;\nusing boost::mpl::plus;\nusing boost::mpl::minus;\nusing boost::mpl::times;\nusing boost::mpl::divides;\nusing boost::mpl::eval_if;\nusing boost::mpl::equal_to;\nusing boost::mpl::_1;\nusing boost::mpl::_2;\nusing boost::mpl::char_;\nusing boost::mpl::lambda;\nusing boost::mpl::int_;\n\n#ifdef _STR\n  #error _STR already defined\n#endif\n#define _STR BOOST_METAPARSE_STRING\n\ntemplate <class A, class B>\nstruct lazy_plus : plus<typename A::type, typename B::type> {};\n\ntemplate <class A, class B>\nstruct lazy_minus : minus<typename A::type, typename B::type> {};\n\ntemplate <class A, class B>\nstruct lazy_times : times<typename A::type, typename B::type> {};\n\ntemplate <class A, class B>\nstruct lazy_divides : divides<typename A::type, typename B::type> {};\n\ntemplate <class C, class T, class F>\nstruct lazy_eval_if : eval_if<typename C::type, T, F> {};\n\ntemplate <class A, class B>\nstruct lazy_equal_to : equal_to<typename A::type, typename B::type> {};\n\ntemplate <class Sequence, class State, class ForwardOp>\nstruct lazy_fold :\n  fold<typename Sequence::type, typename State::type, typename ForwardOp::type>\n{};\n\ntypedef\n  lazy_fold<\n    back<_1>,\n    front<_1>,\n    lambda<\n      lazy_eval_if<\n        lazy_equal_to<front<_2>, char_<'*'>>,\n        lazy_times<_1, back<_2>>,\n        lazy_divides<_1, back<_2>>\n      >\n    >::type\n  >\n  prod_action;\n\ntypedef\n  lazy_fold<\n    back<_1>,\n    front<_1>,\n    lambda<\n      lazy_eval_if<\n        lazy_equal_to<front<_2>, char_<'+'>>,\n        lazy_plus<_1, back<_2>>,\n        lazy_minus<_1, back<_2>>\n      >\n    >::type\n  >\n  plus_action;\n\ntypedef\n  lambda<\n    lazy_fold<\n      _1,\n      int_<0>,\n      lambda<\n        lazy_plus<lazy_times<_1, int_<10>>, apply_wrap1<digit_to_int<>, _2>>\n      >::type\n    >\n  >::type\n  int_action;\n\ntypedef\n  grammar<_STR(\"plus_exp\")>\n\n    ::rule<_STR(\"int ::= ('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9')+\"), int_action>::type\n    ::rule<_STR(\"ws ::= (' ' | '\\n' | '\\r' | '\\t')*\")>::type\n    ::rule<_STR(\"int_token ::= int ws\"), front<_1>>::type\n    ::rule<_STR(\"plus_token ::= '+' ws\"), front<_1>>::type\n    ::rule<_STR(\"minus_token ::= '-' ws\"), front<_1>>::type\n    ::rule<_STR(\"mult_token ::= '*' ws\"), front<_1>>::type\n    ::rule<_STR(\"div_token ::= '/' ws\"), front<_1>>::type\n    ::rule<_STR(\"plus_token ::= '+' ws\")>::type\n    ::rule<_STR(\"plus_exp ::= prod_exp ((plus_token | minus_token) prod_exp)*\"), plus_action>::type\n    ::rule<_STR(\"prod_exp ::= int_token ((mult_token | div_token) int_token)*\"), prod_action>::type\n  expression;\n\ntypedef build_parser<entire_input<expression>> calculator_parser;\n\nint main()\n{\n  using std::cout;\n  using std::endl;\n\n  cout\n    << apply_wrap1<calculator_parser, _STR(\"13\")>::type::value << endl\n    << apply_wrap1<calculator_parser, _STR(\"1+ 2*4-6/2\")>::type::value << endl\n    ;\n}\n#endif\n", "meta": {"hexsha": "97ce161710f094000f81aca8004a8c43a6bfef16", "size": 4268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/metaparse/example/grammar_calculator/main.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/metaparse/example/grammar_calculator/main.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/metaparse/example/grammar_calculator/main.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": 26.675, "max_line_length": 99, "alphanum_fraction": 0.6715089035, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.544700479910455}}
{"text": "#include \"circle.hpp\"\n\n#include <cmath>\n#include <iostream>\n#include <stdexcept>\n\n#include <boost/format.hpp>\n\n#include \"base-types.hpp\"\n\nyakovlev::Circle::Circle(double radius, const point_t & center, double) :\n  radius_{ radius },\n  center_{ center }\n{\n  if (radius <= 0.0) {\n    throw std::invalid_argument{ (boost::format(\"Invalid circle radius %1% - can not be negative or zero\") % radius ).str() };\n  }\n}\n\nbool yakovlev::Circle::operator==(const Circle & other) const noexcept\n{\n  return (center_ == other.center_) && (radius_ == other.radius_);\n}\n\nbool yakovlev::Circle::operator!=(const Circle & other) const noexcept\n{\n  return !(*this == other);\n}\n\ndouble yakovlev::Circle::getRadius() const noexcept\n{\n  return radius_;\n}\n\nyakovlev::point_t yakovlev::Circle::getCenter() const noexcept\n{\n  return center_;\n}\n\ndouble yakovlev::Circle::getArea() const noexcept\n{\n  return M_PI * radius_ * radius_;\n}\n\nyakovlev::rectangle_t yakovlev::Circle::getFrameRect() const noexcept\n{\n  return { radius_ * 2.0, radius_ * 2.0, center_ };\n}\n\nvoid yakovlev::Circle::move(const point_t & pos) noexcept\n{\n  center_ = pos;\n}\n\nvoid yakovlev::Circle::move(double x, double y) noexcept\n{\n  center_.x += x;\n  center_.y += y;\n}\n\nvoid yakovlev::Circle::rotate(double) noexcept\n{ }\n\nvoid yakovlev::Circle::scale(double coef)\n{\n  if (coef <= 0.0) {\n    throw std::invalid_argument{ (boost::format(\"Invalid circle scale coefficient %1% - can not be negative or zero\") % coef ).str() };\n  }\n  radius_ *= coef;\n}\n\nvoid yakovlev::Circle::print(std::ostream & os) const\n{\n  os << \"Circle with a radius of \" << radius_ << \" placed on \" << center_ << '\\n';\n}\n", "meta": {"hexsha": "36eef6b4199698eda8b00c3234beb05503b05a16", "size": 1635, "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/circle.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/circle.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/circle.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": 21.5131578947, "max_line_length": 135, "alphanum_fraction": 0.674617737, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.54470046510362}}
{"text": "/* test_old_uniform_int.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$\n *\n */\n\n#include <boost/random/uniform_int.hpp>\n#include <boost/math/distributions/uniform.hpp>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::uniform_int<>\n#define BOOST_RANDOM_DISTRIBUTION_NAME uniform_int\n#define BOOST_MATH_DISTRIBUTION boost::math::uniform\n#define BOOST_RANDOM_ARG1_TYPE int\n#define BOOST_RANDOM_ARG1_NAME b\n#define BOOST_RANDOM_ARG1_DEFAULT 1000\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_int<>(0, n)\n#define BOOST_RANDOM_DISTRIBUTION_INIT (0, b)\n#define BOOST_MATH_DISTRIBUTION_INIT (0, b+1)\n#define BOOST_RANDOM_DISTRIBUTION_MAX b\n\n#include \"test_real_distribution.ipp\"\n", "meta": {"hexsha": "442f22fa9253b2adbb9a9e9beb205a5f3269b550", "size": 835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_old_uniform_int.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/random/test/test_old_uniform_int.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/random/test/test_old_uniform_int.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": 30.9259259259, "max_line_length": 68, "alphanum_fraction": 0.805988024, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5447004629830046}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#define NT2_UNIT_MODULE \"nt2 complex.operator toolbox - dist/scalar Mode\"\n\n//////////////////////////////////////////////////////////////////////////////\n// unit test behavior of boost.simd.operator components in scalar mode\n//////////////////////////////////////////////////////////////////////////////\n/// created  by jt the 18/02/2011\n///\n#include <nt2/arithmetic/include/functions/dist.hpp>\n#include <boost/simd/sdk/simd/logical.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/constant/constant.hpp>\n\nNT2_TEST_CASE_TPL ( dist_real__2_0,  BOOST_SIMD_REAL_TYPES)\n{\n\n  using nt2::dist;\n  using nt2::tag::dist_;\n  typedef std::complex<T> cT;\n  typedef typename boost::dispatch::meta::as_integer<T>::type iT;\n  typedef typename boost::dispatch::meta::call<dist_(cT, cT)>::type r_t;\n  typedef typename nt2::meta::scalar_of<r_t>::type sr_t;\n  typedef typename nt2::meta::scalar_of<r_t>::type ssr_t;\n  typedef nt2::imaginary<T> ciT;\n  typedef nt2::dry<T> dT;\n  typedef T wished_r_t;\n\n  // return type conformity test\n  NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) );\n\n  // specific values tests\n  NT2_TEST_EQUAL(dist(cT(nt2::Inf<T>()), cT(nt2::Inf<T>())), nt2::Nan<T>());\n  NT2_TEST_EQUAL(dist(cT(nt2::One<T>()), cT(nt2::Zero<T>())), nt2::One<T>());\n  NT2_TEST_EQUAL(dist(cT(nt2::Zero<T>()), cT(nt2::Zero<T>())),nt2::Zero<T>());\n  NT2_TEST_ULP_EQUAL(dist(cT(0, 1), cT(1, 0)), nt2::Sqrt_2<T>(), 0.5);\n  NT2_TEST_ULP_EQUAL(dist(cT(0, nt2::Inf<T>()), cT(nt2::Inf<T>(), 0)), nt2::Inf<T>(), 0.5);\n  NT2_TEST_ULP_EQUAL(dist(nt2::Inf<dT>(),nt2::Inf<dT>()), nt2::Nan<T>(), 0.5);\n  NT2_TEST_EQUAL(dist(cT(1, 0), cT(1, 0)), nt2::Zero<T>());\n  NT2_TEST_EQUAL(dist(cT(2, 1), ciT(1)), nt2::Two<T>());\n  NT2_TEST_EQUAL(dist(ciT(1), ciT(0)), nt2::One<T>());\n  NT2_TEST_EQUAL(dist(ciT(1), T(0)), nt2::One<T>());\n} // end of test for floating_\n", "meta": {"hexsha": "ac29f3db24669daa3213dca469cdeea4e39e3a26", "size": 2469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/arithmetic/unit/scalar/dist.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/type/complex/arithmetic/unit/scalar/dist.cpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/type/complex/arithmetic/unit/scalar/dist.cpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": 46.5849056604, "max_line_length": 91, "alphanum_fraction": 0.5759416768, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5445467813528504}}
{"text": "#include <math_lib/vec_base.h>\n\n#include <math_lib/length.h>\n#include <math_lib/line_segment_3d.h>\n#include <boost/qvm/vec_operations.hpp>\n\n#include <gtest/gtest.h>\n\nusing namespace pagoda;\n\nTEST(LineSegment3D, when_using_default_constructor_should_create_a_unit_line_segment_in_the_x_axis)\n{\n\tLineSegment3D<float> l;\n\tASSERT_TRUE(l.GetSourcePoint() == (Vec3F{0, 0, 0}));\n\tASSERT_TRUE(l.GetTargetPoint() == (Vec3F{1, 0, 0}));\n}\n\nTEST(LineSegment3D, when_using_two_points_constructor_should_create_the_respective_line_segment)\n{\n\tLineSegment3D<float> l(Vec3F{0, 0, 0}, Vec3F{1, 2, 3});\n\tASSERT_TRUE(l.GetSourcePoint() == (Vec3F{0, 0, 0}));\n\tASSERT_TRUE(l.GetTargetPoint() == (Vec3F{1, 2, 3}));\n}\n\nTEST(LineSegment3D, when_comparing_two_equal_line_segments_should_return_equal)\n{\n\tLineSegment3D<float> l1;\n\tLineSegment3D<float> l2(Vec3F{0, 0, 0}, Vec3F{1, 0, 0});\n\tASSERT_TRUE(l1 == l2);\n\tASSERT_FALSE(l1 != l2);\n}\n\nTEST(LineSegment3D, when_comparing_two_different_line_segments_should_return_not_equal)\n{\n\tLineSegment3D<float> l1(Vec3F{0, 0, 0}, Vec3F{1, 2, 3});\n\tLineSegment3D<float> l2(Vec3F{0, 0, 0}, Vec3F{1, 2, 4});\n\tASSERT_FALSE(l1 == l2);\n\tASSERT_TRUE(l1 != l2);\n}\n\n", "meta": {"hexsha": "1588c86cb58a36c7e7fdd11fd207490877cef52c", "size": 1172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit_tests/math_lib/line_segment_3d.cpp", "max_stars_repo_name": "diegoarjz/selector", "max_stars_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T17:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-12T14:37:27.000Z", "max_issues_repo_path": "tests/unit_tests/math_lib/line_segment_3d.cpp", "max_issues_repo_name": "diegoarjz/selector", "max_issues_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47.0, "max_issues_repo_issues_event_min_datetime": "2019-05-27T15:24:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T17:54:54.000Z", "max_forks_repo_path": "tests/unit_tests/math_lib/line_segment_3d.cpp", "max_forks_repo_name": "diegoarjz/selector", "max_forks_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_forks_repo_licenses": ["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.5853658537, "max_line_length": 99, "alphanum_fraction": 0.7440273038, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7185943865443349, "lm_q1q2_score": 0.5445467813528503}}
{"text": "//######################################################################\n//#   Refine_depth Module \n//#   \n//#   Copyright (C) 2020 Siemens AG\n//#   SPDX-License-Identifier: MIT\n//#   Author 2020: This module has been developed by \n//#                Roman Kaskman under supervision of Slobodan Ilic\n//#######################################################################\n\n#ifndef IOUTILS_HPP\n#define IOUTILS_HPP\n\n#include <iostream>\n#include <fstream>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"rgbd_types.hpp\"\n#include <iomanip>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <filesystem>\n#include <fstream>\n\nnamespace fs = std::filesystem;\n\ntemplate<typename T>\ninline std::vector<T> read_matrix_one_line(const std::string &in_file) {\n  std::string line;\n  std::vector<T> elements;\n\n  std::ifstream f(in_file);\n\n  while (std::getline(f, line)) {\n    std::stringstream ss(line);\n    T current_value;\n\n    while (ss >> current_value) {\n      elements.push_back(current_value);\n    }\n\n  }\n\n  return elements;\n}\n\ntemplate<typename T, int R, int C>\ninline Eigen::Matrix<T, R, C> matrix_from_vector_rowwise(std::vector<T> v) {\n  if (v.size() != R * C) {\n    std::cerr << \"Invalid input vector of size \" << v.size() << \" for \" << R << \"x\" << C << \" matrix\" << std::endl;\n    throw std::invalid_argument(\"Invalid vector size\");\n  }\n\n  return Eigen::Map<Eigen::Matrix<T, R, C, Eigen::RowMajor>>(&v[0]);\n}\n\n\ntemplate<typename T, int R, int C>\ninline Eigen::Matrix<T, R, C> read_matrix_from_file(const std::string &in_file) {\n  std::vector<T> intrinsics_vector = read_matrix_one_line<T>(in_file);\n  return matrix_from_vector_rowwise<T, R, C>(intrinsics_vector);\n}\n\n\ntemplate<typename T>\ninline Eigen::Matrix<T, 4, 4> read_pose_from_file(const std::string &in_file) {\n  return read_matrix_from_file<T, 4, 4>(in_file);\n}\n\ntemplate<typename T>\ninline Eigen::Matrix<T, 3, 3> read_intrinsics_from_file(const std::string &in_file) {\n  return read_matrix_from_file<T, 3, 3>(in_file);\n}\n\ninline RgbdFrame get_rgbd_frame(const RgbdFile &rgbd_file)\n{\n\tcv::Mat rgb = cv::imread(rgbd_file.first);\n\tcv::Mat depth = cv::imread(rgbd_file.second, -1);\n\n\tcv::Mat depth_float;\n\tdepth.convertTo(depth_float, CV_32FC1, 0.001);\n\n\treturn RgbdFrame(rgb, depth_float);\n}\n\n\ntemplate<typename T>\ninline std::vector<Eigen::Matrix<T, 4, 4>> read_scene_poses(const std::string &poses_file)\n{\n\tstd::ifstream infile(poses_file);\n\tstd::string line;\n\n\tstd::vector<Eigen::Matrix<T, 4, 4>> poses;\n\tint i = 0;\n\n\tEigen::Matrix<T, 4, 4> temp_matrix;\n\n\twhile (std::getline(infile, line))\n\t{\n\t\tif (i % 5 == 0)\n\t\t{\n\t\t\tif (i > 0)\n\t\t\t{\n\t\t\t\tposes.push_back(temp_matrix);\n\t\t\t\ttemp_matrix = Eigen::Matrix<T, 4, 4>();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tint row = (i % 5) - 1;\n\t\t\tstd::stringstream ss(line);\n\n\t\t\tT current_value;\n\t\t\tint col = 0;\n\n\t\t\twhile (ss >> current_value)\n\t\t\t{\n\t\t\t\ttemp_matrix(row, col) = current_value;\n\t\t\t\tcol++;\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\n\tposes.push_back(temp_matrix);\n\n\treturn poses;\n}\n\ntemplate <typename T>\ninline void store_poses(const std::vector<Eigen::Transform<T, 3, Eigen::Isometry>> &subsampled_valid_poses, const std::string &out_poses_file)\n{\n\tstd::ofstream poses_out_stream;\n\n\tposes_out_stream.open(out_poses_file);\n\tfor (int i = 0; i < static_cast<int>(subsampled_valid_poses.size()); ++i)\n\t{\n\t\tconst Eigen::Matrix<T, 4, 4> &out_pose = subsampled_valid_poses[i].matrix();\n\t\tposes_out_stream << i << std::endl << out_pose << std::endl;\n\t}\n\n\tposes_out_stream.close();\n}\n\n\ninline void store_images(const std::vector<RgbdFile> &rgbd_files, const std::string &out_rgb_dir, const std::string &out_depth_dir)\n{\n\tint i = 0;\n\tfor (const auto &rgbd_file : rgbd_files)\n\t{\n\t\tconst std::string &in_rgb_file = rgbd_file.first;\n\t\tconst std::string &in_depth_file = rgbd_file.second;\n\n\t\tstd::stringstream filename_ss;\n\t\tfilename_ss << std::setfill('0') << std::setw(6) << i << \".png\";\n\t\tconst std::string filename = filename_ss.str();\n\n\t\tstd::string out_rgb_file = (fs::path(out_rgb_dir) / filename).string();\n\t\tstd::string out_depth_file = (fs::path(out_depth_dir) / filename).string();\n\n\t\tfs::copy_file(in_rgb_file, out_rgb_file, fs::copy_options::overwrite_existing);\n\t\tfs::copy_file(in_depth_file, out_depth_file, fs::copy_options::overwrite_existing);\n\n\t\ti++;\n\t}\n}\n\ninline std::string to_plain_filename(const std::string &f)\n{\n\treturn fs::path(f).filename().string();\n}\n\ninline std::vector<RgbdFile> get_input_images(const std::string &rgb_images_dir, const std::string &depth_images_dir)\n{\n\tcv::String rgb_file_pattern = (fs::path(rgb_images_dir) / \"*.png\").string();\n\tcv::String depth_file_pattern = (fs::path(depth_images_dir) / \"*.png\").string();\n\n\tstd::vector<cv::String> rgb_files;\n\tstd::vector<cv::String> depth_files;\n\n\tcv::glob(rgb_file_pattern, rgb_files);\n\tcv::glob(depth_file_pattern, depth_files);\n\n\tstd::vector<std::string> rgb_filenames(rgb_files.size());\n\tstd::vector<std::string> depth_filenames(depth_files.size());\n\n\tstd::transform(rgb_files.begin(), rgb_files.end(), rgb_filenames.begin(), to_plain_filename);\n\tstd::transform(depth_files.begin(), depth_files.end(), depth_filenames.begin(), to_plain_filename);\n\n\tstd::sort(rgb_filenames.begin(), rgb_filenames.end());\n\tstd::sort(depth_filenames.begin(), depth_filenames.end());\n\n\tstd::vector<std::string> image_filenames;\n\tstd::set_intersection(rgb_filenames.begin(), rgb_filenames.end(),\n\t\tdepth_filenames.begin(), depth_filenames.end(), back_inserter(image_filenames));\n\n\tstd::vector<RgbdFile> rgbd_files(image_filenames.size());\n\n\tstd::transform(image_filenames.begin(), image_filenames.end(), rgbd_files.begin(), [&rgb_images_dir, &depth_images_dir](const std::string &fn)\n\t{\n\t\tconst std::string &rgb_file = (fs::path(rgb_images_dir) / fn).string();\n\t\tconst std::string &depth_file = (fs::path(depth_images_dir) / fn).string();\n\t\treturn RgbdFile(rgb_file, depth_file);\n\t});\n\n\treturn rgbd_files;\n}\n\n\n#endif", "meta": {"hexsha": "d2bd7a548dea7428512cbfe1e5ea147e7fcb7bac", "size": 5883, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "refine_depth/include/io_utils.hpp", "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": "refine_depth/include/io_utils.hpp", "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": "refine_depth/include/io_utils.hpp", "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": 28.1483253589, "max_line_length": 143, "alphanum_fraction": 0.683154853, "num_tokens": 1588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.5445467689245931}}
{"text": "\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <boost/filesystem.hpp>\n#include <Open3D/Open3D.h>\n#include <glog/logging.h>\n\n#include \"FileSystemTools.h\"\n#include \"YamlFileIO.h\"\n\n// fitness threshold\ndouble min_fitness_thresh = 0.05;\n\nstruct RegistrationResult{\n    // transform matrix\n    Eigen::Matrix4d T;\n    // fitness score\n    double fitness;\n    // inlier rms\n    double inlier_rms;\n};\n\n// create init extrinsic file\nvoid createMultiLidarExtFile(const std::string& filename)\n{\n    // new backpack structural value\n    Eigen::Matrix4d T_l0_l1_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd l0_l1_vec1(-30 * M_PI / 180.0, Eigen::Vector3d(0, 0, 1));\n    Eigen::AngleAxisd l0_l1_vec2(-73.5 * M_PI / 180.0, Eigen::Vector3d(0, 1, 0));\n    Eigen::Matrix3d l0_l1_vec = l0_l1_vec1.matrix() * l0_l1_vec2.matrix();\n    Eigen::Vector3d t_l0_l1(-0.31405, 0, -0.39803);\n    T_l0_l1_gt.block<3, 3>(0, 0) = l0_l1_vec;\n    T_l0_l1_gt.block<3, 1>(0, 3) = l0_l1_vec1.matrix() * t_l0_l1;\n    std::cout << \"T_l0_l1_gt:\\n\" << T_l0_l1_gt << \"\\n\";\n\n    common::saveExtFileOpencv(filename, T_l0_l1_gt);   \n}\n\nbool alignTwoPointClouds(const std::string &src_pcl_file, const std::string &target_pcl_file, const Eigen::Matrix4d &T_init, \n                RegistrationResult &result){\n    std::string path, file_name;\n    common::splitPathAndFilename(src_pcl_file, &path, &file_name);\n\n    auto src_pcd_ptr = open3d::io::CreatePointCloudFromFile(src_pcl_file);\n    auto target_pcd_ptr = open3d::io::CreatePointCloudFromFile(target_pcl_file);\n\n    if( src_pcd_ptr == nullptr || src_pcd_ptr == nullptr){\n        LOG(ERROR) << \"Fail to load src and target pointcloud file!\";\n        return false;\n    }\n\n    auto src_pcd_down_ptr = src_pcd_ptr->VoxelDownSample(0.05);\n    src_pcd_ptr->EstimateNormals(open3d::geometry::KDTreeSearchParamHybrid(0.1, 30));\n\n    auto target_pcd_down_ptr = target_pcd_ptr->VoxelDownSample(0.05);\n    target_pcd_ptr->EstimateNormals(open3d::geometry::KDTreeSearchParamHybrid(0.1, 30));\n\n    src_pcd_ptr->Transform(T_init);\n    src_pcd_down_ptr->Transform(T_init);\n\n    open3d::registration::RegistrationResult icp_result;\n\n    const double max_corresp_dis = 0.03; // meter\n    open3d::registration::ICPConvergenceCriteria icp_criteria(1e-6, 1e-6, 100);\n    // icp_result = open3d::registration::RegistrationICP(*src_pcd_ptr, *target_pcd_ptr, max_corresp_dis, Eigen::Matrix4d::Identity(),\n    //                                                         open3d::registration::TransformationEstimationPointToPlane(), icp_criteria);\n    icp_result = open3d::registration::RegistrationICP(*src_pcd_ptr, *target_pcd_ptr, max_corresp_dis, Eigen::Matrix4d::Identity(),\n                                                    open3d::registration::TransformationEstimationPointToPoint(false), icp_criteria);\n\n    // transform source pointcloud with icp_transformation\n    Eigen::Matrix4d T_icp = icp_result.transformation_;\n\n    LOG(INFO) << \"#############\" << path << \" ################\";\n    result.fitness = icp_result.fitness_;\n    LOG(INFO) << \"icp_result.fitness: \" << icp_result.fitness_;\n    result.inlier_rms = icp_result.inlier_rmse_;\n    LOG(INFO) << \"icp_result.inlier_rmse_ : \" << icp_result.inlier_rmse_;\n\n    if(result.fitness < min_fitness_thresh){\n        LOG(ERROR) << \"fitness score < \" << min_fitness_thresh;\n        return false;\n    }\n\n    // final transformation between source pointcloud and target pointcloud\n    result.T = T_icp * T_init;\n    std::cout << \"Final transformation:\\n\"\n              << result.T << \"\\n\";\n\n    src_pcd_down_ptr->Transform(T_icp);\n    \n    std::string save_file_path;\n\n    save_file_path = common::concatenateFolderAndFileName(path, \"transformed_source_pointcloud.ply\");\n    open3d::io::WritePointCloudToPLY(save_file_path, *src_pcd_down_ptr, true);\n    std::shared_ptr<open3d::geometry::PointCloud> merge_points(new open3d::geometry::PointCloud);\n    *merge_points = *src_pcd_down_ptr + *target_pcd_down_ptr;\n    \n    save_file_path = common::concatenateFolderAndFileName(path, \"merged_pointcloud.ply\");\n    open3d::io::WritePointCloudToPLY(save_file_path, *merge_points, true);\n    \n    return true;\n}\n\nvoid evaluateExtrinsics(const std::vector<RegistrationResult> & v_results, const Eigen::Matrix4d &T_baseline){\n    assert(v_results.size() > 1);\n\n    std::vector<double> v_inlier_rms = {v_results[0].inlier_rms};\n    // rotation sigma\n    std::vector<double> v_sigma_r;\n    // translation sigma\n    std::vector<double> v_sigma_t;\n\n    int T_num = v_results.size();\n    for(int i = 0; i < T_num; ++i){\n        Eigen::Matrix4d T = v_results[i].T;\n        Eigen::Matrix4d T_inv = T.inverse();\n        \n        Eigen::Matrix4d T_delt = T_inv * T_baseline;\n        Eigen::AngleAxisd rot_vec(T_delt.block<3, 3>(0, 0));\n        double delt_r = rot_vec.angle() * 180.0 / M_PI;\n        Eigen::Vector3d t_delt = T_delt.block<3, 1>(0, 3);\n        double delt_t = t_delt.norm() * 100;\n        LOG(INFO) << \"T_baseline and  T_\" << i << \" Rotation delta: \"\n                <<  delt_r << \" \u00b0\\n\";\n        LOG(INFO) << \"T_baseline and  T_\" << i << \" Translation delta: \" << delt_t\n                << \" cm\\n\";\n\n        v_sigma_r.push_back(delt_r * delt_r);\n        v_sigma_t.push_back(delt_t * delt_t);\n        v_inlier_rms.push_back(v_results[i].inlier_rms);\n    }\n\n    double sigma_r = std::accumulate(v_sigma_r.begin(), v_sigma_r.end(), 0.0) / T_num;\n    double sigma_t = std::accumulate(v_sigma_t.begin(), v_sigma_t.end(), 0.0) / T_num;\n    LOG(INFO) << \"Avg rotation sigma: \" << sigma_r << \", Avg trans sigma: \" << sigma_t;\n    LOG(INFO) << \"Final sigma_r\" << std::sqrt(sigma_r) << \", sigma_t: \" << std::sqrt(sigma_t);\n    // LOG(INFO) << \"Avg inlier rms: \" << std::accumulate(v_inlier_rms.begin(), v_inlier_rms.end(), 0.0) / v_inlier_rms.size();\n\n}\n\n\n\nint main(int argc, char **argv){\n    if (argc < 3){\n        LOG(FATAL) << \"Usage: test_lidar2lidar_calibration [T_l0_l1_init.yaml] [input_dataset_folder] [output_folder] [lidar0_id] [lidar1_id]\";\n        return -1;\n    }\n\n    std::string init_ext_filepath(argv[1]);\n    // dataset folder e.g. /path/data0/lidar_lidar\n    std::string dataset_folder(argv[2]);\n    std::string output_folder(argv[3]);\n    int lidar0_id = 0, lidar1_id = 1;\n    if (argc == 6){\n        lidar0_id = std::stoi (argv[4]);\n        lidar1_id = std::stoi (argv[5]);\n    }\n\n    // if initial extrinsic isn't here, create it\n    if(!common::fileExists(init_ext_filepath)){\n        createMultiLidarExtFile(init_ext_filepath);\n    }\n    if(!common::pathExists(dataset_folder)){\n        LOG(FATAL) << \"Input folder doesnot exist!\";\n        return -1;\n    }\n    if(!common::pathExists(output_folder)){\n        if(!common::createPath(output_folder)){\n            LOG(FATAL) << \"Fail to create \" << output_folder;\n            return -1;\n        }\n    }\n\n    // Eigen::Matrix4d T_base_l0 = horizontal_lidar_ptr->extrinsics();\n    // Eigen::Matrix4d T_base_l1 = vertical_lidar_ptr->extrinsics();\n    // initial extrinsic between two lidar\n    Eigen::Matrix4d T_l0_l1_init = Eigen::Matrix4d::Identity();\n    if (!common::loadExtFileOpencv(init_ext_filepath, T_l0_l1_init)){\n        LOG(FATAL) << \"Fail to load \" << init_ext_filepath;\n        return -1;\n    }\n\n    std::vector<RegistrationResult> v_extrinsics;\n\n    // for (const auto & entry : boost::filesystem::directory_iterator(dataset_folder)){\n    //     if(!boost::filesystem::is_directory(entry))\n    //         continue;\n\n    //     std::string scan_folder_path = entry.path().string() + \"/lidar_lidar\";\n        std::string lidar0_scan_folder = common::concatenateFolderAndFileName(dataset_folder, \"lidar0\");\n        std::string lidar1_scan_folder = common::concatenateFolderAndFileName(dataset_folder, \"lidar1\");\n        std::vector<std::string> v_lidar0_pcl_paths,  v_lidar1_pcl_paths;\n        std::vector<std::string> paths = {lidar0_scan_folder};\n        common::getFileLists(paths, true, \"ply\", &v_lidar0_pcl_paths);\n        paths = {lidar1_scan_folder};\n        common::getFileLists(paths, true, \"ply\", &v_lidar1_pcl_paths);\n\n        if (v_lidar0_pcl_paths.empty() || v_lidar1_pcl_paths.empty()){\n            LOG(ERROR) << \"lidar scan folder is empty!\\n\";\n            return -1;\n        }\n        // only choose 1 scan pair for calibration\n        std::string src_pcl_file_path, target_pcl_file_path;\n        {\n            std::string file_path = v_lidar0_pcl_paths[0];\n            std::string path, file_name;\n            common::splitPathAndFilename(file_path, &path, &file_name);\n            if(std::atoi(&file_name[0]) == lidar0_id)\n                target_pcl_file_path = file_path;\n        }\n        {\n            std::string file_path = v_lidar1_pcl_paths[0];\n            std::string path, file_name;\n            common::splitPathAndFilename(file_path, &path, &file_name);\n            if(std::atoi(&file_name[0]) == lidar1_id)\n                src_pcl_file_path = file_path;\n        }\n\n        RegistrationResult regist_result;\n        bool sts = alignTwoPointClouds(src_pcl_file_path, target_pcl_file_path, T_l0_l1_init, regist_result);\n        if(!sts){\n            return -1;\n        }\n\n        std::string save_file_path = common::concatenateFolderAndFileName(output_folder, \"lidar0_to_lidar1.yml\");\n        common::saveExtFileOpencv(save_file_path, regist_result.T);\n        v_extrinsics.emplace_back(regist_result);\n    // }\n\n    // sort result by fitness\n    // std::sort(v_extrinsics.begin(), v_extrinsics.end(), [&](RegistrationResult &res_a, RegistrationResult &res_b){\n    //     return res_a.fitness > res_b.fitness;\n    // });\n\n    // evaluateExtrinsics(v_extrinsics, v_extrinsics[0].T);\n\n\n\n    return 0;\n}", "meta": {"hexsha": "1b6846e6d0b451dcec7591836eb84a8b3eca25ac", "size": 9716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_lidar2lidar_calibration.cpp", "max_stars_repo_name": "alibaba/multiple-cameras-and-3D-LiDARs-extrinsic-calibration", "max_stars_repo_head_hexsha": "349bc8b954506721583b3571568fb8e23c2f1e83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2021-09-06T02:25:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T12:03:13.000Z", "max_issues_repo_path": "test/test_lidar2lidar_calibration.cpp", "max_issues_repo_name": "alibaba/multiple-cameras-and-3D-LiDARs-extrinsic-calibration", "max_issues_repo_head_hexsha": "349bc8b954506721583b3571568fb8e23c2f1e83", "max_issues_repo_licenses": ["MIT"], "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_lidar2lidar_calibration.cpp", "max_forks_repo_name": "alibaba/multiple-cameras-and-3D-LiDARs-extrinsic-calibration", "max_forks_repo_head_hexsha": "349bc8b954506721583b3571568fb8e23c2f1e83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T22:30:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:43:24.000Z", "avg_line_length": 40.1487603306, "max_line_length": 143, "alphanum_fraction": 0.6539728283, "num_tokens": 2723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5445220155760052}}
{"text": "/**\n * \\file CachedCosinusGeneratorFilter.cpp\n */\n\n#include \"CachedCosinusGeneratorFilter.h\"\n\n#include <cmath>\n#include <cstdint>\n#include <cstring>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ATK\n{\n  template<typename DataType_>\n  CachedCosinusGeneratorFilter<DataType_>::CachedCosinusGeneratorFilter(int periods, int seconds)\n  :Parent(0, 1), indice(1), periods(periods), seconds(seconds), volume(1), offset(0)\n  {\n  }\n  \n  template<typename DataType_>\n  CachedCosinusGeneratorFilter<DataType_>::~CachedCosinusGeneratorFilter()\n  {\n  }\n  \n  template<typename DataType_>\n  void CachedCosinusGeneratorFilter<DataType_>::set_frequency(int periods, int seconds)\n  {\n    this->periods = periods;\n    this->seconds = seconds;\n    setup();\n  }\n  \n  template<typename DataType_>\n  std::pair<int, int> CachedCosinusGeneratorFilter<DataType_>::get_frequency() const\n  {\n    return std::make_pair(periods, seconds);\n  }\n\n  template<typename DataType_>\n  void CachedCosinusGeneratorFilter<DataType_>::set_volume(DataType_ volume)\n  {\n    this->volume = volume;\n  }\n  \n  template<typename DataType_>\n  DataType_ CachedCosinusGeneratorFilter<DataType_>::get_volume() const\n  {\n    return volume;\n  }\n  \n  template<typename DataType_>\n  void CachedCosinusGeneratorFilter<DataType_>::set_offset(DataType_ offset)\n  {\n    this->offset = offset;\n  }\n  \n  template<typename DataType_>\n  DataType_ CachedCosinusGeneratorFilter<DataType_>::get_offset() const\n  {\n    return offset;\n  }\n\n  template<typename DataType_>\n  void CachedCosinusGeneratorFilter<DataType_>::setup()\n  {\n    indice = 0;\n    cache.resize(output_sampling_rate * seconds);\n    for(int i = 0; i < cache.size(); ++i)\n    {\n      cache[i] = static_cast<DataType>(std::cos(2 * boost::math::constants::pi<double>() * (i+1) * periods / seconds / output_sampling_rate));\n    }\n  }\n\n  template<typename DataType_>\n  void CachedCosinusGeneratorFilter<DataType_>::process_impl(int64_t size) const\n  {\n    DataType* ATK_RESTRICT output = outputs[0];\n    int64_t processed = 0;\n    while(processed < size)\n    {\n      int64_t to_copy = std::min(size - processed, int64_t(cache.size()) - indice);\n      memcpy(reinterpret_cast<void*>(output + processed), reinterpret_cast<const void*>(cache.data() + indice), to_copy * sizeof(DataType_));\n      indice += to_copy;\n      processed += to_copy;\n      if(indice >= static_cast<int64_t>(cache.size()))\n      {\n        indice = 0;\n      }\n    }\n    for(int64_t i = 0; i < size; ++i)\n    {\n      output[i] = static_cast<DataType>(offset + volume * output[i]);\n    }\n  }\n  \n  template class CachedCosinusGeneratorFilter<float>;\n  template class CachedCosinusGeneratorFilter<double>;\n}\n", "meta": {"hexsha": "d9d0147d310081167db5317ec9de35e4316d48e1", "size": 2680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Tools/CachedCosinusGeneratorFilter.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/CachedCosinusGeneratorFilter.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/CachedCosinusGeneratorFilter.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": 26.8, "max_line_length": 142, "alphanum_fraction": 0.6973880597, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5445220126315171}}
{"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/geometry/geometry_compute_signed_distance_to_triangle.h>\n#include <cmath> // needed for std::sqrt\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_geometry_util_compute_signed_distance_to_triangle);\n\n  BOOST_AUTO_TEST_CASE(case_by_case_testing)\n  {\n    using std::sqrt;\n\n    typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n    typedef math_types::vector3_type                         vector3_type;\n    typedef math_types::real_type                            real_type;\n\n    real_type tol = 0.0001;\n\n    vector3_type p;\n    vector3_type pi(-5,0,0);\n    vector3_type pj(5,0,0);\n    vector3_type pk(0,5,0);\n    vector3_type nv_i = unit( vector3_type(-1,-1,1) );\n    vector3_type nv_j = unit( vector3_type(1,-1,1) );\n    vector3_type nv_k = unit( vector3_type(0,1,1) );\n    vector3_type ne_i(1,1,1);\n    vector3_type ne_j(-1,1,1);\n    vector3_type ne_k(0,-1,1);\n\n    p = vector3_type(0,2.5,2);\n\n    real_type d0 = OpenTissue::geometry::compute_signed_distance_to_triangle( p, pi, pj, pk, nv_i, nv_j, nv_k, ne_i, ne_j, ne_k  );\n    BOOST_CHECK_CLOSE(d0, 2.0, tol);\n\n    p = vector3_type(0,2.5,-2);\n    real_type d1 = OpenTissue::geometry::compute_signed_distance_to_triangle( p, pi, pj, pk, nv_i, nv_j, nv_k, ne_i, ne_j, ne_k  );\n    BOOST_CHECK_CLOSE(d1, -2.0, tol);\n\n    nv_i = vector3_type(0,1,0);\n    nv_j = vector3_type(0,1,0);\n    nv_k = vector3_type(0,-1,0);\n    ne_i = vector3_type(0,1,0);\n    ne_j = vector3_type(0,1,0);\n    ne_k = vector3_type(0,1,0);\n    p = vector3_type(0,7,0);\n    real_type d2 = OpenTissue::geometry::compute_signed_distance_to_triangle( p, pi, pj, pk, nv_i, nv_j, nv_k, ne_i, ne_j, ne_k  );\n    BOOST_CHECK_CLOSE(d2, -2.0, tol);\n\n    nv_i = vector3_type(1,0,0);\n    nv_j = vector3_type(-1,0,0);\n    nv_k = vector3_type(-1,0,0);\n    ne_i = vector3_type(-1,0,0);\n    ne_j = vector3_type(-1,0,0);\n    ne_k = vector3_type(-1,0,0);\n    p = vector3_type(-7,0,0);\n    real_type d3 = OpenTissue::geometry::compute_signed_distance_to_triangle( p, pi, pj, pk, nv_i, nv_j, nv_k, ne_i, ne_j, ne_k  );\n    BOOST_CHECK_CLOSE(d3, -2.0, tol);\n\n    nv_i = vector3_type(1,0,0);\n    nv_j = vector3_type(-1,0,0);\n    nv_k = vector3_type(1,0,0);\n    ne_i = vector3_type(1,0,0);\n    ne_j = vector3_type(1,0,0);\n    ne_k = vector3_type(1,0,0);\n    p = vector3_type(7,0,0);\n    real_type d4 = OpenTissue::geometry::compute_signed_distance_to_triangle( p, pi, pj, pk, nv_i, nv_j, nv_k, ne_i, ne_j, ne_k  );\n    BOOST_CHECK_CLOSE(d4, -2.0, tol);\n\n    nv_i = vector3_type(0,-1,0);\n    nv_j = vector3_type(0,-1,0);\n    nv_k = vector3_type(0,-1,0);\n    ne_i = vector3_type(0,-1,0);\n    ne_j = vector3_type(0,-1,0);\n    ne_k = vector3_type(0,1,0);\n    p = vector3_type(0,-2,0);\n    real_type d5 = OpenTissue::geometry::compute_signed_distance_to_triangle( p, pi, pj, pk, nv_i, nv_j, nv_k, ne_i, ne_j, ne_k  );\n    BOOST_CHECK_CLOSE(d5, -2.0, tol);\n\n    nv_i = vector3_type(1,1,0);\n    nv_j = vector3_type(1,1,0);\n    nv_k = vector3_type(1,1,0);\n    ne_i = vector3_type(-1,-1,0);\n    ne_j = vector3_type(1,1,0);\n    ne_k = vector3_type(1,1,0);\n    p = vector3_type(5,5,0);\n    real_type d6 = OpenTissue::geometry::compute_signed_distance_to_triangle( p, pi, pj, pk, nv_i, nv_j, nv_k, ne_i, ne_j, ne_k  );\n    BOOST_CHECK_CLOSE(d6, -3.5355339059327376220042218105242, tol);\n\n    nv_i = vector3_type(-1, 1, 0);\n    nv_j = vector3_type(-1, 1, 0);\n    nv_k = vector3_type(-1, 1, 0);\n    ne_i = vector3_type(-1, 1, 0);\n    ne_j = vector3_type( 1,-1, 0);\n    ne_k = vector3_type(-1, 1, 0);\n    p = vector3_type(-5,5,0);\n    real_type d7 = OpenTissue::geometry::compute_signed_distance_to_triangle( p, pi, pj, pk, nv_i, nv_j, nv_k, ne_i, ne_j, ne_k  );\n    BOOST_CHECK_CLOSE(d7, -3.5355339059327376220042218105242, tol);\n  }\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "44776a235ed63a8cd4668abcdd1c06929370a10b", "size": 4339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/geometry/compute_signed_distance_to_triangle/src/unit_compute_signed_distance_to_triangle.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/compute_signed_distance_to_triangle/src/unit_compute_signed_distance_to_triangle.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/compute_signed_distance_to_triangle/src/unit_compute_signed_distance_to_triangle.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": 38.3982300885, "max_line_length": 131, "alphanum_fraction": 0.6727356534, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.544522012631517}}
{"text": "#include \"SPX.h\"\n#include <NTL/lzz_pXFactoring.h>\n\nusing namespace std;\nusing namespace NTL;\n\n#if ((NTL_MAJOR_VERSION<9) || ((NTL_MAJOR_VERSION==9)&&(NTL_MINOR_VERSION<2)))\n#warning \"NTL < 9.2.0, using SPmodulus wrapper\"\n#else\n#warning \"NTL >= 9.2.0, using zz_pContext directly\"\n#endif\n\nstatic void zpxFromSPX(zz_pX& zpx, const SPX& spp)\n{\n  Vec<long> v;\n  spp.getCoeffVec(v);  // convert to zz_pX\n  conv(zpx.rep, v);\n  zpx.normalize();\n}\n\nstatic bool testGCD(SPX& a)\n{\n  const SPmodulus& mod = a.getMod();\n  getContext(mod).restore();\n\n   SPX b, c, ss, tt;\n   zz_pX a_p, b_p, c_p, ss_p, tt_p;\n\n  // test polynomials of various degrees, from 32 to 8192\n  for (long n = 32; n <= 8192; n <<= 2) {\n    random(a, n, mod);   // get random polynomial\n    zpxFromSPX(a_p,a);// convert to zz_pX\n    random(b_p, n);      // get random zz_pX\n    b = SPX(b_p,mod); // convert to SPX\n\n    GCD(c_p, a_p, b_p);  // work on zz_pX\n    GCD(c, a, b);        // work on SPX\n    if (c != SPX(c_p,mod)) {\n      cerr << \"**** SPX Test GCD FAILED!\\n\";\n      return false;\n    }\n\n    XGCD(c_p, ss_p, tt_p, a_p, b_p);\n    XGCD(c, ss, tt, a, b);\n    if (c != SPX(c_p,mod) ||\n\tss != SPX(ss_p,mod) || tt != SPX(tt_p,mod)) {\n      cerr << \"**** SPX Test XGCD FAILED!\\n\";\n      return false;\n    }\n  }\n  return true;\n}\n\nstatic bool testArith(SPX& a)\n{\n  const SPmodulus& mod = a.getMod();\n  getContext(mod).restore();\n\n   SPX b, c, d;\n   zz_pX a_p, b_p, c_p, d_p;\n\n  // test polynomials of various degrees, from 32 to 8192\n  for (long n = 32; n <= 8192; n <<= 2) {\n    random(a, n, mod);   // get random polynomial\n    zpxFromSPX(a_p,a);// convert to zz_pX\n    random(b_p, n);      // get random zz_pX\n    b = SPX(b_p,mod); // convert to SPX\n\n    c   = (a  +b);\n    c_p = (a_p+b_p);\n    if (c != SPX(c_p,mod)) {\n      cerr << \"  ** SPX testArith (1) FAILED!\\n\";\n      return false;\n    }\n    //    cout << \".\" << std::flush;\n\n    DivRem(c,  d,  c,  b);  // c = c/b, d=c%b\n    DivRem(c_p,d_p,c_p,b_p);\n    if (c != SPX(c_p,mod) || d != SPX(d_p,mod)) {\n      cerr << \"  ** SPX testArith (2) FAILED!\\n\";\n      return false;\n    }\n    //    cout << \",\" << std::flush;\n\n    d  = (c << 5) - (b >> 2);\n    d_p= (c_p<<5) - (b_p>>2);\n    if (d != SPX(d_p,mod)) {\n      cerr << \"  ** SPX testArith (3) FAILED!\\n\";\n      return false;\n    }\n    //    cout << \";\" << std::flush;\n\n    --d;   ++c;\n    --d_p; ++c_p;\n    if (c != SPX(c_p,mod) || d != SPX(d_p,mod)) {\n      cerr << \"  ** SPX testArith (4) FAILED!\\n\";\n      return false;\n    }\n    //    cout << \";\" << std::flush;\n  }\n  return true;\n}\n\nstatic bool testCoeffs(SPX& a)\n{\n  const SPmodulus& mod = a.getMod();\n  getContext(mod).restore();\n\n   zz_pX a_p;\n\n  // test polynomials of various degrees, from 32 to 8192\n  for (long n = 32; n <= 8192; n <<= 2) {\n    random(a, n, mod);   // get random polynomial\n    zpxFromSPX(a_p,a);// convert to zz_pX\n\n    if (LeadCoeff(a) != conv<long>(LeadCoeff(a_p))\n\t|| ConstTerm(a) != conv<long>(ConstTerm(a_p))) {\n      cerr << \"**** SPX testCoeffs (1) FAILED!\\n\";\n      return false;\n    }\n\n    SetCoeff(a, 10, 3);\n    SetCoeff(a_p, 10, 3);\n    if (a != SPX(a_p,mod)) {\n      cerr << \"**** SPX testCoeffs (2) FAILED!\\n\";\n      return false;\n    }\n\n    SetX(a);\n    SetX(a_p);\n    if (!IsX(a) || a != SPX(a_p,mod))  {\n      cerr << \"**** SPX testCoeffs (3) FAILED!\\n\";\n      return false;\n    }\n\n    clear(a);\n    clear(a_p);\n    if (!IsZero(a) || a != SPX(a_p,mod))  {\n      cerr << \"**** SPX testCoeffs (4) FAILED!\\n\";\n      return false;\n    }\n\n    set(a);\n    set(a_p);\n    if (!IsOne(a) || a != SPX(a_p,mod))  {\n      cerr << \"**** SPX testCoeffs (5) FAILED!\\n\";\n      return false;\n    }\n  }\n  return true;\n}\n\nstatic bool testMisc(SPX& a)\n{\n  const SPmodulus& mod = a.getMod();\n  getContext(mod).restore();\n\n  SPX b;\n  zz_pX a_p, b_p;\n\n  // test polynomials of various degrees, from 32 to 8192\n  for (long n = 32; n <= 8192; n <<= 2) {\n    random(a, n, mod);   // get random polynomial\n    zpxFromSPX(a_p,a);// convert to zz_pX\n\n    diff(b,  a);\n    diff(b_p,a_p);\n    if (b != SPX(b_p,mod)) {\n      cerr << \"**** SPX testMisc (1) FAILED!\\n\";\n      return false;\n    }\n    reverse(b,  a);\n    reverse(b_p,a_p);\n    if (b != SPX(b_p,mod)) {\n      cerr << \"**** SPX testMisc (2) FAILED!\\n\";\n      return false;\n    }\n    reverse(b,  a,  10);\n    reverse(b_p,a_p,10);\n    if (b != SPX(b_p,mod)) {\n      cerr << \"**** SPX testMisc (3) FAILED!\\n\";\n      return false;\n    }\n  }\n  return true;\n}\n\n\nstatic bool testTrunc(SPX& a)\n{\n  const SPmodulus& mod = a.getMod();\n  getContext(mod).restore();\n\n  SPX b, c;\n  zz_pX a_p, b_p, c_p;\n\n  // test polynomials of various degrees, from 32 to 8192\n  for (long n = 32; n <= 8192; n <<= 2) {\n    random(a, n, mod);   // get random polynomial\n    zpxFromSPX(a_p,a);// convert to zz_pX\n    random(b_p, n);      // get random zz_pX\n    b = SPX(b_p,mod); // convert to SPX\n\n    MulTrunc(c,  a,  b,  32);    MulTrunc(c_p,a_p,b_p,32);\n    SqrTrunc(c,  c,  48);        SqrTrunc(c_p,c_p,48);\n    if (c != SPX(c_p,mod)) {\n      cerr << \"**** SPX testTrunc (1) FAILED!\\n\";\n      return false;\n    }\n\n    if (coeff(c,0)==0) {\n      SetCoeff(c,0);  SetCoeff(c_p,0);\n    }\n    InvTrunc(c,  c,  40);        InvTrunc(c_p,c_p,40);\n    if (c != SPX(c_p,mod)) {\n      cerr << \"**** SPX testTrunc (2) FAILED!\\n\";\n      return false;\n    }\n  }\n  return true;\n}\n\nstatic bool testMod(SPX& a)\n{\n  const SPmodulus& mod = a.getMod();\n  getContext(mod).restore();\n\n  SPX b, c;\n  zz_pX a_p, b_p, c_p, F_p;\n\n  // test polynomials of various degrees, from 32 to 512\n  for (long n = 32; n <= 512; n <<= 2) {\n    BuildIrred(F_p,n+1);  // build an irreducible polynomial\n    SPX F(F_p,mod);    // convert to SPX\n\n    random(a, n, mod);   // get random polynomial\n    zpxFromSPX(a_p,a);// convert to zz_pX\n    random(b_p, n);      // get random zz_pX\n    b = SPX(b_p,mod); // convert to SPX\n\n    MulMod(c,  a,  b,  F);    MulMod(c_p,a_p,b_p,F_p);\n    SqrMod(c,  c,  F);        SqrMod(c_p,c_p,F_p);\n    if (c != SPX(c_p,mod)) {\n      cerr << \"**** SPX testMod (1) FAILED!\\n\";\n      return false;\n    }\n\n    MulByXMod(c, a, F); MulByXMod(c_p,a_p,F_p);\n    InvMod(c, c, F);    InvMod(c_p,c_p,F_p);\n    if (c != SPX(c_p,mod)) {\n      cerr << \"**** SPX testMod (2) FAILED!\\n\";\n      return false;\n    }\n  }\n  return true;\n}\n\nstatic bool testModPre(SPX& a)\n{\n  const SPmodulus& mod = a.getMod();\n  getContext(mod).restore();\n\n  SPX b, c;\n  zz_pX a_p, b_p, c_p;\n\n  // test polynomials of various degrees, from 32 to 512\n  for (long n = 32; n <= 512; n <<= 2) {\n    BuildIrred(c_p,n+1);  // build an irreducible polynomial\n    zz_pXModulus F_p=c_p; // set it as modulus\n    c = SPX(c_p,mod);  // convert to SPX\n    SPXModulus F=c;\n\n    random(a, n, mod);   // get random polynomial\n    zpxFromSPX(a_p,a);// convert to zz_pX\n    random(b_p, n);      // get random zz_pX\n    b = SPX(b_p,mod); // convert to SPX\n\n    MulMod(c,  a,  b,  F);    MulMod(c_p,a_p,b_p,F_p);\n    SqrMod(c,  c,  F);        SqrMod(c_p,c_p,F_p);\n    if (c != SPX(c_p,mod)) {\n      cerr << \"**** SPX testModPre (1) FAILED!\\n\";\n      return false;\n    }\n\n    PowerXMod(b, n+5, F); PowerXMod(b_p,n+5,F_p);\n    MulByXMod(c, b, F);   MulByXMod(c_p,b_p,F_p);\n    if (c != SPX(c_p,mod)) {\n      cerr << \"**** SPX testModPre (2) FAILED!\\n\";\n      return false;\n    }\n\n    PowerMod(b, c, n/2, F); PowerMod(b_p, c_p, n/2, F_p);\n    if (b != SPX(b_p,mod)) {\n      cerr << \"**** SPX testModPre (3) FAILED!\\n\";\n      return false;\n    }\n\n    random(a_p, 2*n);    // get random zz_pX\n    a = SPX(a_p,mod); // convert to SPX\n    DivRem(b, c, a, F);  DivRem(b_p,c_p,a_p,F_p);\n    if (b != SPX(b_p,mod) || c != SPX(c_p,mod)) {\n      cerr << \"**** SPX testModPre (4) FAILED!\\n\";\n      return false;\n    }\n\n    b = c = a;\n    b_p = c_p = a_p;\n    b /= F; b_p /= F_p;\n    c %= F; c_p %= F_p;\n    if (b != SPX(b_p,mod) || c != SPX(c_p,mod)) {\n      cerr << \"**** SPX testModPre (5) FAILED!\\n\";\n      return false;\n    }\n  }\n  return true;\n}\n\n\nstatic bool testComp(SPX& a1)\n{\n  const SPmodulus& mod = a1.getMod();\n  getContext(mod).restore();\n\n  SPX a2, a3, b1, b2, b3, c;\n  zz_pX a1_p,a2_p,a3_p,b1_p,b2_p,b3_p,c_p;\n\n  // test polynomials of various degrees, from 32 to 512\n  for (long n = 32; n <= 512; n <<= 2) {\n    BuildIrred(c_p,n+1);  // build an irreducible polynomial\n    zz_pXModulus F_p=c_p; // set it as modulus\n    c = SPX(c_p,mod);  // convert to SPX\n    SPXModulus F=c;\n\n    random(b1_p, n);      // get random zz_pX\n    b1 = SPX(b1_p,mod); // convert to SPX\n\n    random(b2_p, n);      // get random zz_pX\n    b2 = SPX(b2_p,mod); // convert to SPX\n\n    random(b3_p, n);      // get random zz_pX\n    b3 = SPX(b3_p,mod); // convert to SPX\n\n    random(c_p, 3);      // get random zz_pX\n    c = SPX(c_p,mod); // convert to SPX\n\n    CompMod(a1, b1, c, F); CompMod(a1_p,b1_p,c_p,F_p);\n    if (a1 != SPX(a1_p,mod)) {\n      cerr << \"**** SPX testComp (1) FAILED!\\n\";\n      return false;\n    }\n\n    Comp2Mod(a1, a2, b1, b2, c, F); Comp2Mod(a1_p,a2_p,b1_p,b2_p,c_p,F_p);\n    if (a1 != SPX(a1_p,mod) || a2 != SPX(a2_p,mod)) {\n      cerr << \"**** SPX testComp (2) FAILED!\\n\";\n      return false;\n    }\n\n    Comp3Mod(a1,  a2,  a3,  b1,  b2,  b3,  c,  F);\n    Comp3Mod(a1_p,a2_p,a3_p,b1_p,b2_p,b3_p,c_p,F_p);\n    if (a1 != SPX(a1_p,mod)\n\t|| a2 != SPX(a2_p,mod) || a3 != SPX(a3_p,mod)) {\n      cerr << \"**** SPX testComp (3) FAILED!\\n\";\n      return false;\n    }\n\n    SPXArgument H;  build(H,  c,  F, 4);\n    zz_pXArgument H_p; build(H_p,c_p,F_p,4);\n\n    CompMod(a1, b1, H, F); CompMod(a1_p,b1_p,H_p,F_p);\n    if (a1 != SPX(a1_p,mod)) {\n      cerr << \"**** SPX testComp (4) FAILED!\\n\";\n      return false;\n    }\n  }\n  return true;\n}\n\nstatic bool testProj(SPX& a)\n{\n  const SPmodulus& mod = a.getMod();\n  getContext(mod).restore();\n\n  Vec<long> v;\n  SPX f;\n\n  Vec<zz_p> v_p;\n  zz_pX a_p,f_p;\n\n  // test polynomials of various degrees, from 32 to 512\n  for (long n = 32; n <= 512; n <<= 2) {\n    BuildIrred(f_p,n+1);  // build an irreducible polynomial\n    f = SPX(f_p,mod);  // convert to SPX\n\n    random(a_p, n);      // get random zz_pX\n    a = SPX(a_p,mod); // convert to SPX\n\n    VectorCopy(v_p,a_p,deg(a_p)+1); // get coefficient vector\n    a.getCoeffVec<long>(v);\n\n    random(a_p, n);      // get random zz_pX\n    a = SPX(a_p,mod); // convert to SPX\n\n    {long x = project(v, a);\n    zz_p x_p = project(v_p, a_p);\n    if (x != conv<long>(x_p)) {\n      cerr << \"**** SPX testProj (1) FAILED! (\"\n\t   << x << \"!=\" << conv<long>(x_p) << \")\\n\";\n      return false;\n    }}\n    Vec<long> x;\n    Vec<zz_p> x_p;\n    ProjectPowers(x,  v,  5, a, f);\n    ProjectPowers(x_p,v_p,5,a_p,f_p);\n    if (x != conv< Vec<long> >(x_p)) {\n      cerr << \"**** SPX testProj (2) FAILED!\\n\";\n      return false;\n    }\n\n    SPXModulus F=f;\n    ProjectPowers(x,  v,  5, a, F);\n    if (x != conv< Vec<long> >(x_p)) {\n      cerr << \"**** SPX testProj (3) FAILED!\\n\";\n      return false;\n    }\n  }\n  return true;\n}\n\n/*\nstatic bool testMinp(SPX& a)\n{\n  const SPmodulus& mod = a.getMod();\n  getContext(mod).restore();\n  // ...\n}\n*/\n\nstatic bool testTrace(SPX& a)\n{\n  const SPmodulus& mod = a.getMod();\n  getContext(mod).restore();\n\n  SPX f;\n  zz_pX ap, fp;\n\n  // test polynomials of various degrees, from 32 to 512\n  for (long n = 32; n <= 512; n <<= 2) {\n    BuildIrred(fp,n+1);  // build an irreducible polynomial\n    f = SPX(fp,mod);  // convert to SPX\n    SPXModulus F=f;\n\n    random(ap, n);      // get random zz_pX\n    a = SPX(ap,mod); // convert to SPX\n\n    long t = TraceMod(a, f);\n    zz_p tp= TraceMod(ap,fp);\n    if (t != conv<long>(tp)) {\n      cerr << \"**** SPX testTrace (1) FAILED!\\n\";\n      return false;\n    }\n\n    t = TraceMod(a, F);\n    if (t != conv<long>(tp)) {\n      cerr << \"**** SPX testTrace (2) FAILED!\\n\";\n      return false;\n    }\n\n    Vec<long> tv = TraceVec(f);\n    Vec<zz_p> tvp= TraceVec(fp);\n    if (tv != conv<vec_long>(tvp)) {\n      cerr << \"**** SPX testTrace (3) FAILED!\\n\";\n      return false;\n    }\n  }\n  return true;\n}\n\nint main()\n{\n  for (long p=11; p>1; p =(p-1)/2) { // test p=11, p=5, and p=2\n    SPmodulus mod(p);\n    SPX a(mod);\n    getContext(mod).restore();\n\n    cout << \"\\np=\"<<p<<endl;\n    if (testGCD(a))   cout << \"  testGCD\\tPASS\\n\" << std::flush;\n    if (testArith(a)) cout << \"  testArith\\tPASS\\n\" << std::flush;\n    if (testCoeffs(a)) cout<< \"  testCoeffs\\tPASS\\n\" << std::flush;\n    if (testMisc(a))  cout << \"  testMisc\\tPASS\\n\" << std::flush;\n    if (testTrunc(a)) cout << \"  testTrunc\\tPASS\\n\" << std::flush;\n    if (testMod(a))   cout << \"  testMod\\tPASS\\n\" << std::flush;\n    if (testModPre(a)) cout<< \"  testModPre\\tPASS\\n\" << std::flush;\n    if (testComp(a))  cout << \"  testComp\\tPASS\\n\" << std::flush;\n    if (testProj(a))  cout << \"  testProj\\tPASS\\n\" << std::flush;\n    //    if (testMinp(a))  cout << \"  testMinp\\tPASS\\n\" << std::flush;\n    if (testTrace(a)) cout << \"  testTrace\\tPASS\\n\" << std::flush;\n  }\n}\n", "meta": {"hexsha": "ce45c9740f5c807977cede8fb006c0cfd5ed28ef", "size": 12849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/Test_SPX.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/Test_SPX.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/Test_SPX.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": 25.749498998, "max_line_length": 78, "alphanum_fraction": 0.5357615379, "num_tokens": 4728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5445219941737844}}
{"text": "/**\n * @file calc-characteristic.cpp\n *\n * @brief calculate characteristic polynomial.\n *\n * @author Mutsuo Saito (Hiroshima University)\n * @author Makoto Matsumoto (The University of Tokyo)\n *\n * Copyright (C) 2012 Mutsuo Saito, Makoto Matsumoto,\n * Hiroshima University and The University of Tokyo.\n * All rights reserved.\n *\n * The 3-clause BSD License is applied to this software, see\n * LICENSE.txt\n */\n#include <iostream>\n#include <inttypes.h>\n#include <stdint.h>\n#include <time.h>\n#include \"dSFMText.hpp\"\n#include \"dSFMT-calc-jump.hpp\"\n#include <NTL/GF2X.h>\n#include <NTL/vec_GF2.h>\n#include <NTL/GF2XFactoring.h>\n\nusing namespace dsfmt;\nusing namespace NTL;\nusing namespace std;\n\nvoid calc_minimal(GF2X& minimal, int maxdegree, w128_t outseq[], int pos)\n{\n    uint64_t mask = 0;\n    vec_GF2 seq;\n    seq.SetLength(2 * maxdegree);\n    int idx = 0;\n\n    if (pos >= 104 || pos < 0) {\n\tcerr << \"pos error:\" << dec << pos << endl;\n\texit(1);\n    } else if (pos >= 52) {\n\tidx = 1;\n\tmask = UINT64_C(1) << (pos - 52);\n    } else {\n\tidx = 0;\n\tmask = UINT64_C(1) << pos;\n    }\n    if (idx < 0 || idx >= 2) {\n\tcerr << \"idx error:\" << dec << idx << endl;\n\texit(1);\n    }\n    for (int i = 0; i < 2 * maxdegree; i++) {\n\tif ((outseq[i].u[idx] & mask) != 0) {\n\t    seq[i] = 1;\n\t} else {\n\t    seq[i] = 0;\n\t}\n    }\n    MinPolySeq(minimal, seq, maxdegree);\n#if defined(DEBUG)\n    cout << \"deg(minimal) = \" << dec << deg(minimal) << endl;\n#endif\n}\n\nvoid LCM(GF2X& lcm, const GF2X& x, const GF2X& y) {\n    GF2X gcd;\n    mul(lcm, x, y);\n    GCD(gcd, x, y);\n//void DivRem(GF2X& q, GF2X& r, const GF2X& a, const GF2X& b);\n// q = a/b, r = a%b\n    GF2X r;\n    DivRem(lcm, r, lcm, gcd);\n    if (deg(r) != -1) {\n\tcerr << \"LCM error: deg(r) = \" << dec << deg(r);\n\tcerr << \"r:\" << r << endl;\n\texit(1);\n    }\n}\n\nstatic void get_lcm_sub(GF2X& lcmpoly, dSFMText& dsfmt) {\n    GF2X tmp(1,1);\n    int maxdegree = dsfmt.get_maxdegree();\n    w128_t out_seq[2 * maxdegree];\n\n    for (int i = 0; i < 2 * maxdegree; i++) {\n\tout_seq[i] = dsfmt.next();\n    }\n    GF2X minimal;\n    GF2X t1;\n    SetCoeff(t1, 0, 1);\n    SetCoeff(t1, 1, 1);\n    for (int pos = 0; pos < 104; pos++) {\n\tcalc_minimal(minimal, maxdegree, out_seq, pos);\n\tLCM(tmp, lcmpoly, minimal);\n\tlcmpoly = tmp;\n\tif (divide(lcmpoly, t1)) {\n\t    return;\n\t}\n    }\n#if defined(DEBUG)\n    cout << \"deg(lcmpoly) = \" << dec << deg(lcmpoly) << endl;\n#endif\n}\n\nvoid get_lcm(GF2X& lcmpoly, dSFMText& dsfmt) {\n    int maxdegree = dsfmt.get_maxdegree();\n    GF2X t1;\n    SetCoeff(t1, 0, 1);\n    SetCoeff(t1, 1, 1);\n\n    //uint32_t time = (uint32_t)clock();\n    dsfmt.seeding(1234);\n    get_lcm_sub(lcmpoly, dsfmt);\n    if (deg(lcmpoly) >= maxdegree) {\n\treturn;\n    }\n    if (divide(lcmpoly, t1)) {\n\treturn;\n    }\n    for(int i = 0; i < maxdegree; i++) {\n\tdsfmt.init_basis(i);\n\tget_lcm_sub(lcmpoly, dsfmt);\n\tif (deg(lcmpoly) >= maxdegree) {\n\t    return;\n\t}\n\tif (divide(lcmpoly, t1)) {\n\t    return;\n\t}\n    }\n}\n\n\nstatic int has_large_irreducible(GF2X& fpoly, int degree) {\n    static const GF2X t2(2, 1);\n    static const GF2X t1(1, 1);\n    GF2X t2m;\n    GF2X t;\n    GF2X alpha;\n    int m;\n\n    t2m = t2;\n    if (deg(fpoly) < degree) {\n\treturn 0;\n    }\n    t = t1;\n    t += t2m;\n\n    for (m = 1; deg(fpoly) > degree; m++) {\n\tfor(;;) {\n\t    GCD(alpha, fpoly, t);\n\t    if (IsOne(alpha)) {\n\t\tbreak;\n\t    }\n\t    fpoly /= alpha;\n\t    if (deg(fpoly) < degree) {\n\t\treturn 0;\n\t    }\n\t}\n\tt2m *= t2m;\n\tt2m %= fpoly;\n\tadd(t, t2m, t1);\n    }\n    if (deg(fpoly) != degree) {\n\treturn 0;\n    }\n    return IterIrredTest(fpoly);\n}\n\nvoid check_fix(dSFMText & fix)\n{\n    fix.setup_high();\n    cout << \"before:\";\n    fix.print(cout);\n    fix.next();\n    cout << \"after 1 step:\";\n    fix.print(cout);\n    fix.next();\n    cout << \"after 2 step:\";\n    fix.print(cout);\n    fix.next();\n    cout << \"after 3 step:\";\n    fix.print(cout);\n}\n\nvoid check_fix2(dSFMText & fix)\n{\n    cout << \"before:\";\n    fix.print(cout);\n    fix.next_add();\n    cout << \"after 1 step:\";\n    fix.print(cout);\n    fix.next_add();\n    cout << \"after 2 step:\";\n    fix.print(cout);\n    fix.next_add();\n    cout << \"after 3 step:\";\n    fix.print(cout);\n}\n\nvoid calc_fix(GF2X& inv, int mexp, int pos1, int sl1,\n\t      uint64_t mask1, uint64_t mask2)\n{\n    dSFMText fix(mexp, pos1, sl1, mask1, mask2);\n    //fix.setup_high();\n    //fix.next();\n    //cout << \"setup0:\";\n    //fix.print(cout);\n    fix.setup_constants();\n#if defined(DEBUG)\n    cout << \"setup:\";\n    fix.print(cout);\n#endif\n    dSFMText work(mexp, pos1, sl1, mask1, mask2);\n#if defined(DEBUG)\n    cout << \"zero:\";\n    work.print(cout);\n#endif\n    for (long i = 0; i <= deg(inv); i++) {\n\tif (IsOne(coeff(inv, i))) {\n\t    work.add(fix);\n#if defined(DEBUG) && 0\n    cout << \"work:\";\n    work.print(cout);\n#endif\n\t}\n\tfix.next();\n    }\n    cout << \"fix:\";\n    work.print(cout);\n    check_fix(work);\n}\n\nvoid check_const(GF2X& lcm, int mexp, int pos1, int sl1,\n\t      uint64_t mask1, uint64_t mask2)\n{\n    dSFMText normal(mexp, pos1, sl1, mask1, mask2);\n    dSFMText add(mexp, pos1, sl1, mask1, mask2);\n    normal.seeding(123);\n    add.seeding(123);\n\n    normal.setup_high();\n    normal.next();\n    add.next_add();\n    cout << \"normal:\";\n    normal.print(cout);\n    cout << \"add:\";\n    add.print(cout);\n    for (int i = 0; i < 5; i++) {\n\tnormal.next();\n\tadd.next_add();\n    }\n    cout << \"normal:\";\n    normal.print(cout);\n    cout << \"add:\";\n    add.print(cout);\n}\n\nvoid check_gcd(GF2X& d, GF2X& s, GF2X& inv, GF2X& work, GF2X& t1)\n{\n//    XGCD(d, s, inv, work, t1);\n//    check_gcd(d, s, inv, work, t1);\n//void XGCD(GF2X& d, GF2X& s, GF2X& t, const GF2X& a, const GF2X& b);\n// d = gcd(a,b), a s + b t = d\n    if (deg(d) != 0) {\n\tcout << \"check_gcd d != 1:\" << dec << deg(d) << endl;\n\treturn;\n    }\n    GF2X p;\n    GF2X q;\n    mul(p, s, work);\n    mul(q, inv, t1);\n    p += q;\n    if (p != d) {\n\tcout << \"check_gcd p != d, p = \" << p << endl;\n\tcout << \"check_gcd p != d, d = \" << d << endl;\n    } else {\n\tcout << \"check_gcd OK d:\" << d << endl;\n    }\n}\nint main(int argc, char *argv[]) {\n    if (argc < 6) {\n\tcout << argv[0] << \" mexp pos1 sl1 mask1 mask2\" << endl;\n\treturn -1;\n    }\n    int mexp = strtol(argv[1], NULL, 10);\n    int pos1 = strtol(argv[2], NULL, 10);\n    int sl1 = strtol(argv[3], NULL, 10);\n    uint64_t mask[2];\n    mask[0] = strtoull(argv[4], NULL, 16);\n    mask[1] = strtoull(argv[5], NULL, 16);\n#if defined(DEBUG)\n    cout << \"mexp:\" << dec << mexp << endl;\n    cout << \"pos1:\" << dec << pos1 << endl;\n    cout << \"sl1:\" << dec << sl1 << endl;\n    cout << \"mask1:\" << hex<< mask[0] << endl;\n    cout << \"mask2:\" << hex << mask[1] << endl;\n#endif\n    dSFMText dsfmt(mexp, pos1, sl1, mask[0], mask[1]);\n    GF2X characteristic(0,1);\n    get_lcm(characteristic, dsfmt);\n#if defined(DEBUG)\n    cout << \"degree:\" << dec << deg(characteristic) << endl;\n    cout << \"maxdegree = \" << dec << dsfmt.get_mamaxdegree() << endl;\n    cout << characteristic << endl;\n#endif\n    GF2X work;\n    work = characteristic;\n#if defined(DEBUG)\n    cout << \"degree:\" << deg(characteristic) << endl;\n    cout << characteristic << endl;\n#endif\n    if (!has_large_irreducible(characteristic, mexp)) {\n        cout << \"error?\" << endl;\n        return -1;\n    }\n#if 0\n    GF2X remain = work / characteristic;\n    vec_pair_GF2X_long factors;\n    CanZass(factors, remain);\n    cout << \"degree of work:\" << dec << deg(work) << endl;\n    cout << \"degree of remain:\" << dec << deg(remain) << endl;\n    cout << \"=== factor of remain ===\" << endl;\n    for (int i = 0; i < factors.length(); i++) {\n\tcout << factors[i].a;\n\tcout << \":\";\n\tcout << dec << deg(factors[i].a);\n\tcout << \":\";\n\tcout << dec << factors[i].b << endl;\n    }\n#endif\n    GF2X d, s, inv;\n    GF2X t1;\n    SetCoeff(t1, 0, 1);\n    SetCoeff(t1, 1, 1);\n    XGCD(d, s, inv, work, t1);\n    check_gcd(d, s, inv, work, t1);\n// d = gcd(a,b), a s + b t = d\n//    MulMod(s, inv, t1, work);\n#if defined(DEBUG)\n    cout << \"deg work:\" << dec << deg(work) << endl;\n    cout << \"deg inv:\" << dec << deg(inv) << endl;\n#endif\n    string x;\n//    cout << \"# deg = \" << dec << deg(work) << endl;\n    polytostring(x, work);\n    cout << \"#\" << dec << mexp;\n    cout << \",\" << dec << pos1;\n    cout << \",\" << dec << sl1;\n    cout << \",\" << hex << mask[0];\n    cout << \",\" << hex << mask[1];\n    cout << dec << endl;\n    cout << x << endl;\n    cout << dec << flush;\n    if (deg(d) != 0) {\n\tcout << \"doesn't have fixpoint.\" << endl;\n\treturn 0;\n    }\n#if 0\n    string y;\n    polytostring(y, inv);\n    if (deg(d) == 0) {\n\tcout << y << endl;\n    } else {\n\tcout << \"can't finf inv d=\" << d << endl;\n    }\n#endif\n    calc_fix(inv, mexp, pos1, sl1, mask[0], mask[1]);\n    //check_const(inv, mexp, pos1, sl1, mask[0], mask[1]);\n}\n", "meta": {"hexsha": "b55c59d0e412b2b337c60ad30dd401863e70d54a", "size": 8670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jump/calc-characteristic.cpp", "max_stars_repo_name": "mkt-matsumoto-lab/dSFMT", "max_stars_repo_head_hexsha": "6929b76f2ab07e6302f8daece28045d5bec6ff5c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T06:39:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T14:18:47.000Z", "max_issues_repo_path": "jump/calc-characteristic.cpp", "max_issues_repo_name": "mkt-matsumoto-lab/dSFMT", "max_issues_repo_head_hexsha": "6929b76f2ab07e6302f8daece28045d5bec6ff5c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-09-02T02:08:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T06:15:28.000Z", "max_forks_repo_path": "jump/calc-characteristic.cpp", "max_forks_repo_name": "MersenneTwister-Lab/dSFMT", "max_forks_repo_head_hexsha": "6929b76f2ab07e6302f8daece28045d5bec6ff5c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-03-09T10:59:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T20:36:09.000Z", "avg_line_length": 23.4959349593, "max_line_length": 73, "alphanum_fraction": 0.5439446367, "num_tokens": 3006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5445198406073969}}
{"text": "/**\n * @file pointcloud_test.cpp\n * @brief Point Cloud CLIPPER tests\n * @author Parker Lusk <plusk@mit.edu>\n * @date 3 October 2020\n */\n\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <clipper/clipper.h>\n#include <clipper/find_dense_cluster.h>\n#include <clipper/invariants/builtins.h>\n\nTEST(PointCloud, KnownScaleInvariant) {\n\n  //\n  // Algorithm setup\n  //\n\n  // instantiate the invariant function that will be used to score associations\n  clipper::invariants::EuclideanDistance::Params iparams;\n  clipper::invariants::EuclideanDistance invariant(iparams);\n\n  //\n  // Data setup\n  //\n\n  // create a target/model point cloud of data\n  Eigen::Matrix3Xd model(3, 4);\n  model.col(0) << 0, 0, 0;\n  model.col(1) << 2, 0, 0;\n  model.col(2) << 0, 3, 0;\n  model.col(3) << 2, 2, 0;\n\n  // transform of data w.r.t model\n  Eigen::Affine3d T_MD;\n  T_MD = Eigen::AngleAxisd(M_PI/8, Eigen::Vector3d::UnitZ());\n  T_MD.translation() << 5, 3, 0;\n\n  // create source/data point cloud\n  Eigen::Matrix3Xd data = T_MD.inverse() * model;\n\n  // remove one point from the tgt (model) cloud---simulates a partial view\n  data.conservativeResize(3, 3);\n\n  //\n  // Identify data association\n  //\n\n  // an empty association set is assumed to be all-to-all (12 total)\n  clipper::Association A;\n\n  Eigen::MatrixXd M, C;\n  std::tie(M, C) = clipper::scorePairwiseConsistency(invariant, model, data, A);\n\n  // A should be an all-to-all hypothesis\n  const int n = model.cols() * data.cols();\n  EXPECT_EQ(A.rows(), n);\n  EXPECT_EQ(A.cols(), 2); // CLIPPER is a pair-wise data association algo\n\n  // Ensure that an all-to-all hypothesis was correctly created\n  for (size_t i=0; i<model.cols(); i++) {\n    for (size_t j=0; j<data.cols(); j++) {\n      const size_t k = i * data.cols() + j;\n      EXPECT_EQ(A(k,0), i);\n      EXPECT_EQ(A(k,1), j);\n    }\n  }\n\n  // affinity matrix made up of all-to-all hypothesis between 4 and 3 items\n  EXPECT_EQ(M.rows(), A.rows());\n  EXPECT_EQ(M.cols(), A.rows());\n\n  // diagonal of the affinity matrix should be all ones\n  EXPECT_EQ(M.diagonal(), Eigen::VectorXd::Ones(M.rows()));\n\n  // matrices should be symmetric\n  EXPECT_EQ(M, M.transpose());\n  EXPECT_EQ(C, C.transpose());\n\n  // in this case with perfect data, affinity matrix is binary and so\n  // affinity matrix == constraint matrix\n  EXPECT_EQ(M, C);\n\n  // expected affinity matrix, from MATLAB\n  Eigen::MatrixXd Mtrue = Eigen::MatrixXd(M.rows(), M.cols());\n  Mtrue << 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,\n           0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,\n           0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0,\n           0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0,\n           1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0,\n           0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0,\n           0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0,\n           0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0,\n           1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,\n           0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0,\n           0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0,\n           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1;\n  EXPECT_EQ(M, Mtrue);\n}\n\n// ----------------------------------------------------------------------------\n\nTEST(PointCloud, KnownScale) {\n\n  //\n  // Algorithm setup\n  //\n\n  // instantiate the invariant function that will be used to score associations\n  clipper::invariants::EuclideanDistance::Params iparams;\n  clipper::invariants::EuclideanDistance invariant(iparams);\n\n  //\n  // Data setup\n  //\n\n  // create a target/model point cloud of data\n  Eigen::Matrix3Xd model(3, 4);\n  model.col(0) << 0, 0, 0;\n  model.col(1) << 2, 0, 0;\n  model.col(2) << 0, 3, 0;\n  model.col(3) << 2, 2, 0;\n\n  // transform of data w.r.t model\n  Eigen::Affine3d T_MD;\n  T_MD = Eigen::AngleAxisd(M_PI/8, Eigen::Vector3d::UnitZ());\n  T_MD.translation() << 5, 3, 0;\n\n  // create source/data point cloud\n  Eigen::Matrix3Xd data = T_MD.inverse() * model;\n\n  // remove one point from the tgt (model) cloud---simulates a partial view\n  data.conservativeResize(3, 3);\n\n  //\n  // Identify data association\n  //\n\n  // an empty association set will be assumed to be all-to-all\n  clipper::Association A;\n\n  // create affinity matrix\n  Eigen::MatrixXd M, C;\n  std::tie(M, C) = clipper::scorePairwiseConsistency(invariant, model, data, A);\n\n  // find the \"densest clique\"\n  clipper::Solution soln = clipper::findDenseCluster(M, C);\n\n  clipper::Association Ainliers = clipper::selectInlierAssociations(soln, A);\n\n  ASSERT_EQ(Ainliers.rows(), 3);\n  for (size_t i=0; i<Ainliers.rows(); ++i) {\n    EXPECT_EQ(Ainliers(i, 0), Ainliers(i, 1));\n  }\n\n}\n\n// ----------------------------------------------------------------------------\n\nTEST(PointCloud, KnownScaleConvenience) {\n\n  //\n  // Algorithm setup\n  //\n\n  clipper::Params params;\n  clipper::invariants::EuclideanDistance::Params iparams;\n\n  // instantiate the clipper object that will process incoming pairs of sensor\n  // data to determine the outlier-free set of pairwise associations\n  clipper::CLIPPER<clipper::invariants::EuclideanDistance> clipper(params, iparams);\n\n  //\n  // Data setup\n  //\n\n  // create a target/model point cloud of data\n  Eigen::Matrix3Xd model(3, 4);\n  model.col(0) << 0, 0, 0;\n  model.col(1) << 2, 0, 0;\n  model.col(2) << 0, 3, 0;\n  model.col(3) << 2, 2, 0;\n\n  // transform of data w.r.t model\n  Eigen::Affine3d T_MD;\n  T_MD = Eigen::AngleAxisd(M_PI/8, Eigen::Vector3d::UnitZ());\n  T_MD.translation() << 5, 3, 0;\n\n  // create source/data point cloud\n  Eigen::Matrix3Xd data = T_MD.inverse() * model;\n\n  // remove one point from the tgt (model) cloud---simulates a partial view\n  data.conservativeResize(3, 3);\n\n  //\n  // Identify data association\n  //\n\n  // note that data types are specified by invariant class\n  clipper::Association Ainliers = clipper.findCorrespondences(model, data);\n\n  ASSERT_EQ(Ainliers.rows(), 3);\n  for (size_t i=0; i<Ainliers.rows(); ++i) {\n    EXPECT_EQ(Ainliers(i, 0), Ainliers(i, 1));\n  }\n\n}\n\n// ----------------------------------------------------------------------------\n\nTEST(PointCloud, LargePointCloud) {\n\n  //\n  // Algorithm setup\n  //\n\n  clipper::Params params;\n  clipper::invariants::EuclideanDistance::Params iparams;\n  iparams.sigma = 0.015;\n  iparams.epsilon = 0.02;\n  clipper::CLIPPER<clipper::invariants::EuclideanDistance> clipper(params, iparams);\n\n  //\n  // Data setup\n  //\n\n  // create a target/model point cloud of data\n  static constexpr int N = 32;\n  Eigen::Matrix3Xd model = 5*Eigen::MatrixXd::Random(3, N);\n\n  // transform of data w.r.t model\n  Eigen::Affine3d T_MD;\n  T_MD = Eigen::AngleAxisd(M_PI/8, Eigen::Vector3d::UnitZ());\n  T_MD.translation() << 5, 3, 0;\n\n  // create source/data point cloud\n  Eigen::Matrix3Xd data = T_MD.inverse() * model;\n\n\n  //\n  // Identify data association\n  //\n\n  // note that data types are specified by invariant class\n  clipper::Association Ainliers = clipper.findCorrespondences(model, data);\n\n  ASSERT_EQ(Ainliers.rows(), N);\n  for (size_t i=0; i<Ainliers.rows(); ++i) {\n    EXPECT_EQ(Ainliers(i, 0), Ainliers(i, 1));\n  }\n\n}\n\n\nTEST(PointCloud, LargePointCloudSparseClipper) {\n\n  //\n  // Algorithm setup\n  //\n\n  clipper::Params params;\n  clipper::invariants::EuclideanDistance::Params iparams;\n  iparams.sigma = 0.015;\n  iparams.epsilon = 0.02;\n  clipper::invariants::EuclideanDistance invariant(iparams);\n  //clipper::CLIPPER<clipper::invariants::EuclideanDistance> clipper(params, iparams);\n\n  //\n  // Data setup\n  //\n\n  // create a target/model point cloud of data\n  static constexpr int N = 32;\n  Eigen::Matrix3Xd model = 5*Eigen::MatrixXd::Random(3, N);\n\n  // transform of data w.r.t model\n  Eigen::Affine3d T_MD;\n  T_MD = Eigen::AngleAxisd(M_PI/8, Eigen::Vector3d::UnitZ());\n  T_MD.translation() << 5, 3, 0;\n\n  // create source/data point cloud\n  Eigen::Matrix3Xd data = T_MD.inverse() * model;\n\n\n  //\n  // Identify data association\n  //\n\n  // note that data types are specified by invariant class\n  clipper::Association A = clipper::Association();\n  Eigen::SparseMatrix<double> sM, sC;\n  std::tie(sM, sC) =\n      clipper::scoreSparsePairwiseConsistency(invariant, model, data, A, true);\n  auto soln = clipper::findDenseClusterOfSparseGraph(sM, sC, params);\n  clipper::Association Ainliers = clipper::selectInlierAssociations(soln, A);\n\n  ASSERT_EQ(Ainliers.rows(), N);\n  for (size_t i=0; i<Ainliers.rows(); ++i) {\n    EXPECT_EQ(Ainliers(i, 0), Ainliers(i, 1));\n  }\n\n}\n\n", "meta": {"hexsha": "e304c17b4ded72af40af6fa8d9abd85f4c724aba", "size": 8314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/pointcloud_test.cpp", "max_stars_repo_name": "ash-aldujaili/clipper", "max_stars_repo_head_hexsha": "2e56b2058e8482c33ece3390b3b1b558301eacbe", "max_stars_repo_licenses": ["MIT"], "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/pointcloud_test.cpp", "max_issues_repo_name": "ash-aldujaili/clipper", "max_issues_repo_head_hexsha": "2e56b2058e8482c33ece3390b3b1b558301eacbe", "max_issues_repo_licenses": ["MIT"], "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/pointcloud_test.cpp", "max_forks_repo_name": "ash-aldujaili/clipper", "max_forks_repo_head_hexsha": "2e56b2058e8482c33ece3390b3b1b558301eacbe", "max_forks_repo_licenses": ["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.0814332248, "max_line_length": 86, "alphanum_fraction": 0.6246090931, "num_tokens": 2734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5444177263229121}}
{"text": "//mesh\u30d3\u30e5\u30fc\u30a2\n\n#include <ros/ros.h>\n#include <stdio.h>\n#include <iostream>\n#include <string>\n\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/surface/gp3.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/io/vtk_io.h>\n#include <pcl/PolygonMesh.h>\n\n#include <boost/thread/thread.hpp>\n\n#include <sensor_msgs/PointCloud.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <geometry_msgs/Point.h>\n#include <pcl_conversions/pcl_conversions.h>\n\n#include <tf/transform_broadcaster.h>\n\n\n#include <local_tool/filters.hpp>\n#include <local_tool/mathematics.hpp>\n#include <local_tool/registration.hpp>\n\n\nusing namespace std;\n\nclass Mesh\n{\n\tprivate:\n\t\tros::NodeHandle n;\n\t\tros::Rate r;\n\t\tros::Publisher input_pub;\n\t\tros::Publisher output_pub;\n\n\t\tdouble MU;\n\t\tdouble M_NEIGHBORS;//max\n\t\tdouble G_RADIUS;\n\t\tdouble K_SEARCH;\n\n\t\tstring file_input;\n\t\t\n\t\tbool NORMAL_C;\n\n\t\tpcl::PolygonMesh::Ptr triangles;\n\t\tpcl::PointCloud<pcl::PointXYZ>::Ptr cloud ;\n\n\tpublic:\n\t\tMesh(ros::NodeHandle& n);\n\n\t\tvoid create_polygon(void);\n\t\tvoid vis_polygon(void);\n\n};\n\nMesh::Mesh(ros::NodeHandle &n) :\n\tr(10)\n{\n\n\tn.getParam(\"mesh_mu\",MU);\n\tn.getParam(\"mesh_max_neighbors\",M_NEIGHBORS);\n\tn.getParam(\"mesh_radius\",G_RADIUS);\n\tn.getParam(\"mesh_normalconsistency\",NORMAL_C);\n\tn.getParam(\"normal_ksearch\",K_SEARCH);\n\tn.getParam(\"input/cloud\",file_input);\n\n\tinput_pub = n.advertise<sensor_msgs::PointCloud2>(\"/input_cloud\", 10);\n\toutput_pub = n.advertise<sensor_msgs::PointCloud2>(\"/output_cloud\", 10);\n\n\ttriangles.reset (new pcl::PolygonMesh());\n\tcloud.reset (new pcl::PointCloud<pcl::PointXYZ>);\n\n}\n\n\n\n\n\nvoid\nMesh::create_polygon(void){\n\n\tpcl::PointCloud<pcl::PointXYZI>::Ptr output_cloud (new pcl::PointCloud<pcl::PointXYZI>);\n\t// Load input file into a PointCloud<T> with an appropriate type\n\tpcl::PCLPointCloud2 cloud_blob;\n\tpcl::io::loadPCDFile(file_input, cloud_blob);\n\tpcl::fromPCLPointCloud2 (cloud_blob, *cloud);\n\t//* the data should be available in cloud\n\n\t// Normal estimation*\n\tpcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> nor;\n\tpcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);\n\tpcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);\n\ttree->setInputCloud (cloud);\n\tnor.setInputCloud (cloud);\n\tnor.setSearchMethod (tree);\n\tnor.setKSearch (K_SEARCH);\n\tnor.compute (*normals);\n\t//* normals should not contain the point normals + surface curvatures\n\n\t// Concatenate the XYZ and normal fields*\n\tpcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normals (new pcl::PointCloud<pcl::PointNormal>);\n\tpcl::concatenateFields (*cloud, *normals, *cloud_with_normals);\n\t//* cloud_with_normals = cloud + normals\n\n\t// Create search tree*\n\tpcl::search::KdTree<pcl::PointNormal>::Ptr tree2 (new pcl::search::KdTree<pcl::PointNormal>);\n\ttree2->setInputCloud (cloud_with_normals);\n\n\t// Initialize objects\n\tpcl::GreedyProjectionTriangulation<pcl::PointNormal> gp3;\n\n\t// Set the maximum distance between connected points (maximum edge length)\n\t// gp3.setSearchRadius (0.025);\n\tgp3.setSearchRadius (G_RADIUS);\n\n\t// Set typical values for the parameters\n\tgp3.setMu (MU);//defalut 2.5\n\tgp3.setMaximumNearestNeighbors (M_NEIGHBORS);\n\tgp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees\n\tgp3.setMinimumAngle(M_PI/18); // 10 degrees\n\tgp3.setMaximumAngle(2*M_PI/3); // 120 degrees\n\tgp3.setNormalConsistency(NORMAL_C);\n\t// gp3.setNormalConsistency(true);\n\n\t// Get result\n\tgp3.setInputCloud (cloud_with_normals);\n\tgp3.setSearchMethod (tree2);\n\tgp3.reconstruct (*triangles);\n\n\t// Additional vertex information\n\tstd::vector<int> parts = gp3.getPartIDs();\n\tstd::vector<int> states = gp3.getPointStates();\n\n\tcout <<triangles->polygons.size() <<\"triangles created\" << endl;\n\n\n\t//ros\n\t// pcl::fromPCLPointCloud2 (triangles->cloud, *output_cloud);\n\t// sensor_msgs::PointCloud2 pc, pc2;\n\t// pcl_msgs::PolygonMesh pc3;\n\t// pcl::toROSMsg(*cloud, pc);\n\t// pcl::toROSMsg(*output_cloud, pc2);\n\t// pc3.cloud = pc2;\n\n\n}\n\nvoid\nMesh::vis_polygon(void)\n{\n\t// \u70b9\u7fa4\u306e\u30d3\u30e5\u30fc\u30a2\n\tpcl::visualization::PCLVisualizer viewer(\"Cloud Viewer\");\n\n\tviewer.setBackgroundColor (0.0, 0.2, 0.6);\n\n\tviewer.addPolygonMesh(*triangles);\n\n\twhile (!viewer.wasStopped ())\n\t{\n\t\tviewer.spinOnce(10);\n\n\t\tboost::this_thread::sleep (boost::posix_time::microseconds (100000));\n\t}\n\n\n}\n\n\n\nint main(int argc, char** argv){\n\tros::init(argc, argv, \"mesh\");\n\tros::NodeHandle n;\n\n\tcout<<\"-------mesh ok--------\"<<endl;\n\n\tMesh mesh(n);\n\n\tmesh.create_polygon();\n\tmesh.vis_polygon();\n\n\tros::spin();\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "b05aea2b808eb84be88a18b8efded02a244b1b12", "size": 4551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kari_localization/src/mesh.cpp", "max_stars_repo_name": "karrykarry/kari_localization", "max_stars_repo_head_hexsha": "e81e1fda587958e87771e149b5ca3769eae891fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kari_localization/src/mesh.cpp", "max_issues_repo_name": "karrykarry/kari_localization", "max_issues_repo_head_hexsha": "e81e1fda587958e87771e149b5ca3769eae891fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kari_localization/src/mesh.cpp", "max_forks_repo_name": "karrykarry/kari_localization", "max_forks_repo_head_hexsha": "e81e1fda587958e87771e149b5ca3769eae891fc", "max_forks_repo_licenses": ["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.703125, "max_line_length": 99, "alphanum_fraction": 0.725774555, "num_tokens": 1264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5444177200157109}}
{"text": "/**********************************************************************\r\n*  Copyright (c) 2008-2013, Alliance for Sustainable Energy.  \r\n*  All rights reserved.\r\n*  \r\n*  This library is free software; you can redistribute it and/or\r\n*  modify it under the terms of the GNU Lesser General Public\r\n*  License as published by the Free Software Foundation; either\r\n*  version 2.1 of the License, or (at your option) any later version.\r\n*  \r\n*  This library is distributed in the hope that it will be useful,\r\n*  but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n*  Lesser General Public License for more details.\r\n*  \r\n*  You should have received a copy of the GNU Lesser General Public\r\n*  License along with this library; if not, write to the Free Software\r\n*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\r\n**********************************************************************/\r\n\r\n#ifndef UTILITIES_GEOMETRY_GEOMETRY_HPP\r\n#define UTILITIES_GEOMETRY_GEOMETRY_HPP\r\n\r\n#include <utilities/UtilitiesAPI.hpp>\r\n\r\n#include <utilities/geometry/Point3d.hpp>\r\n#include <utilities/geometry/Vector3d.hpp>\r\n\r\n#include <vector>\r\n#include <boost/optional.hpp>\r\n\r\nnamespace openstudio{\r\n\r\n  /// convert degrees to radians\r\n  UTILITIES_API double degToRad(double degrees);\r\n\r\n  /// convert radians to degrees\r\n  UTILITIES_API double radToDeg(double radians);\r\n\r\n  /// compute area from surface as Point3dVector\r\n  UTILITIES_API boost::optional<double> getArea(const Point3dVector& points);\r\n\r\n  /// compute Newall vector from surface as Point3dVector, direction is same as outward normal\r\n  /// magnitude is twice the area\r\n  UTILITIES_API boost::optional<Vector3d> getNewallVector(const Point3dVector& points);\r\n\r\n  /// compute outward normal from surface as Point3dVector\r\n  UTILITIES_API boost::optional<Vector3d> getOutwardNormal(const Point3dVector& points);\r\n\r\n  /// compute centroid from surface as Point3dVector\r\n  UTILITIES_API boost::optional<Point3d> getCentroid(const Point3dVector& points);\r\n\r\n  /// reorder points to upper-left-corner convention\r\n  UTILITIES_API std::vector<Point3d> reorderULC(const Point3dVector& points);\r\n\r\n  /// removes colinear points, tolerance is for length of cross product after normalizing each line segment\r\n  UTILITIES_API std::vector<Point3d> removeColinear(const Point3dVector& points, double tol = 0.001);\r\n\r\n  /// return distance between two points\r\n  UTILITIES_API double getDistance(const Point3d& point1, const Point3d& point2);\r\n\r\n  /// return angle (in radians) between two vectors\r\n  UTILITIES_API double getAngle(const Vector3d& vector1, const Vector3d& vector2);\r\n  \r\n  /// compute distance in meters between two points on the Earth's surface\r\n  /// lat and lon are specified in degrees\r\n  UTILITIES_API double getDistanceLatLon(double lat1, double lon1, double lat2, double lon2);\r\n\r\n  /// check if two vectors of points are equal (within tolerance) irregardless of initial ordering.\r\n  UTILITIES_API bool circularEqual(const Point3dVector& points1, const Point3dVector& points2, double tol = 0.001);\r\n\r\n} // openstudio\r\n\r\n#endif //UTILITIES_GEOMETRY_GEOMETRY_HPP\r\n", "meta": {"hexsha": "f22933fe71e69cf6b8087164d29bde5d46daeda2", "size": 3221, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/geometry/Geometry.hpp", "max_stars_repo_name": "bobzabcik/OpenStudio", "max_stars_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_stars_repo_licenses": ["blessing"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openstudiocore/src/utilities/geometry/Geometry.hpp", "max_issues_repo_name": "bobzabcik/OpenStudio", "max_issues_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_issues_repo_licenses": ["blessing"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openstudiocore/src/utilities/geometry/Geometry.hpp", "max_forks_repo_name": "bobzabcik/OpenStudio", "max_forks_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_forks_repo_licenses": ["blessing"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.527027027, "max_line_length": 116, "alphanum_fraction": 0.7227569078, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5444177200157109}}
{"text": "#include <exception>\n#include <vector>\n#include <Eigen/Core>\n\nEigen::MatrixXd cholesky_swig_eigen(const Eigen::MatrixXd &M);", "meta": {"hexsha": "9825cdf22a5f1b7cc29b1926106973363057815f", "size": 124, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cholesky/swig_eigen/swig_mod.hpp", "max_stars_repo_name": "Chachay/python_bench", "max_stars_repo_head_hexsha": "10ce8a93c498f24306d93160be6a000eb2b4f2a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cholesky/swig_eigen/swig_mod.hpp", "max_issues_repo_name": "Chachay/python_bench", "max_issues_repo_head_hexsha": "10ce8a93c498f24306d93160be6a000eb2b4f2a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cholesky/swig_eigen/swig_mod.hpp", "max_forks_repo_name": "Chachay/python_bench", "max_forks_repo_head_hexsha": "10ce8a93c498f24306d93160be6a000eb2b4f2a9", "max_forks_repo_licenses": ["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.8, "max_line_length": 62, "alphanum_fraction": 0.7741935484, "num_tokens": 30, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5444177200157109}}
{"text": "\n// #pragma GCC optimize (\"O0\")\n\n#include <boost/log/trivial.hpp>\n\n#include \"common.hpp\"\n#include \"constants.hpp\"\n\ndouble svaToUra(int sva)\n{\n\t/*\n\t\tGLOBAL POSITIONING SYSTEM\n\t\tSTANDARD POSITIONING SERVICE\n\t\tSIGNAL SPECIFICATION\n\t\t2nd Ed, June 2,1995\n\t\tsee section - 2.5.3 User Range Accuracy\n\t*/\n\tdouble ura = 0;\n\tif (sva <= 6)\n\t{\n\t\tura = 10 * pow(2, 1 + ((double)sva / 2.0));\n\t\tura = round(ura) / 10.0;\n\t}\n\telse if (sva != 15)\n\t\tura = pow(2, (double)sva - 2.0);\n\telse\n\t\tura = -1;\n\treturn ura;\n}\n\n\n\ndouble svaToSisa(int sva)\n{\n\t/*\n\t\tEUROPEAN GNSS (GALILEO) OPEN SERVICE\n\t\tSIGNAL-IN-SPACE\n\t\tINTERFACE CONTROL\n\t\tDOCUMENT\n\t\tIssue 2.0, January 2021\n\t\tSee Section, 5.1.12. Signal In Space Accuracy (SISA)\n\t*/\n\n\tdouble sisa;\n\tif (sva <= 49)\t\t\tsisa = 0.0 + (sva - 0) * 0.01;\n\telse if (sva <= 74)\t\tsisa = 0.5 + (sva - 50) * 0.02;\n\telse if (sva <= 99)\t\tsisa = 1.0 + (sva - 75) * 0.04;\n\telse if (sva <= 125)\tsisa = 2.0 + (sva - 100) * 0.16;\n\telse\t\t\t\t\tsisa = -1;\n\treturn sisa;\n}\n\nint sisaToSva(double sisa)\n{\n\tif (sisa < 0)\n\t{\n\t\tBOOST_LOG_TRIVIAL(error) << \"Error converting SISA to SVA, value is less than zero.\";\n\t\treturn -1;\n\t}\n\n\tif (sisa <= 0.49)\t    return (int)((((sisa - 0.0) / 0.01) + 0) + 0.5);\n\telse if (sisa <= 0.98)  return (int)((((sisa - 0.5) / 0.02) + 50) + 0.5);\n\telse if (sisa <= 1.96)  return (int)((((sisa - 1.0) / 0.04) + 75) + 0.5);\n\telse if (sisa <= 6.00)  return (int)((((sisa - 2.0) / 0.16) + 100) + 0.5);\n\telse\n\t{\n\t\tBOOST_LOG_TRIVIAL(warning) << \"SISA is too large SVA undefined.\";\n\t\treturn -1;\n\t}\n}\n\n/* crc-24q parity --------------------------------------------------------------\n* compute crc-24q parity for sbas, rtcm3\n* args   : unsigned char *buff I data\n*          int    len    I      data length (bytes)\n* return : crc-24Q parity\n* notes  : see reference [2] A.4.3.3 Parity\n*-----------------------------------------------------------------------------*/\nunsigned int crc24q(\n\tconst unsigned char *buff, \n\tint len)\n{\n//\ttrace(4,\"%s: len=%d\\n\",__FUNCTION__, len);\n\t\n\tunsigned int crc = 0;\n\n\tfor (int i=0;i<len;i++) \n\t\tcrc = ((crc<<8) & 0xFFFFFF) ^ tbl_CRC24Q[(crc >> 16) ^ buff[i]];\n\t\n\treturn crc;\n}\n\nvoid setbitu(\n\tunsigned char*\tbuff,\n\tint \t\t\tpos,\n\tint\t\t\t\tlen,\n\tunsigned int\tdata)\n{\n\tunsigned int mask=1u<<(len-1);\n\t\n\tif\t( len<=0\n\t\t||len>32)\n\t{\n\t\treturn;\n\t}\n\t\n\tunsigned long int invalid = (1ul<<len);\n\t\n\tif (data >= invalid)\n\t{\n\t\tstd::cout << \"Warning: \" << __FUNCTION__ << \" has data outside range\\n\";\n\t}\n\t\n\tfor (int i = pos; i < pos + len; i++, mask >>= 1) \n\t{\n\t\tif (data&mask)\tbuff[i/8] |=  (1u<<(7-i%8));\n\t\telse\t\t\tbuff[i/8] &= ~(1u<<(7-i%8));\n\t}\n}\n\nvoid setbits(\n\tunsigned char*\tbuff, \n\tint\t\t\t\tpos, \n\tint\t\t\t\tlen, \n\tint\t\t\t\tdata)\n{\n\tunsigned int mask=1u<<(len-1);\n\t\n\tif\t( len<=0\n\t\t||len>32)\n\t{\n\t\treturn;\n\t}\n\t\n\tlong int invalid = (1ul<<(len-1));\n\t\n\tif\t( +data >= invalid\n\t\t||-data >= invalid)\n\t{\n\t\tstd::cout << \"Warning: \" << __FUNCTION__ << \" has data outside range, setting invalid\\n\";\n\t\tdata = -invalid;\n\t}\n\t\n\tfor (int i = pos; i < pos + len; i++, mask >>= 1) \n\t{\n\t\tif (data&mask)\tbuff[i/8] |=  (1u<<(7-i%8));\n\t\telse\t\t\tbuff[i/8] &= ~(1u<<(7-i%8));\n\t}\n}\n\nint setbituInc(\n\tunsigned char*\tbuff,\n\tint\t\t\t\tpos,\n\tint\t\t\t\tlen,\n\tunsigned int\tvar)\n{   \n\tsetbitu(buff, pos, len, var);\n\treturn pos + len;\n}\n\nint setbitsInc(\n\tunsigned char*\tbuff,\n\tint\t\t\t\tpos,\n\tint\t\t\t\tlen,\n\tint\t\t\t\tvar)\n{\n\tsetbits(buff, pos, len, var);\n\treturn pos + len;\n}\n\n/* extract unsigned/signed bits ------------------------------------------------\n* extract unsigned/signed bits from byte data\n* args   : unsigned char *buff I byte data\n*          int    pos    I      bit position from start of data (bits)\n*          int    len    I      bit length (bits) (len<=32)\n* return : extracted unsigned/signed bits\n*-----------------------------------------------------------------------------*/\nunsigned int getbitu(\n\tconst unsigned char*\tbuff,\n\tint\t\t\t\t\t\tpos,\n\tint\t\t\t\t\t\tlen)\n{\n\tunsigned int bits = 0;\n\tfor (int i=pos;i<pos+len;i++)\n\t\tbits=(bits<<1)+((buff[i/8]>>(7-i%8))&1u);\n\t\n\treturn bits;\n}\n\nint getbits(\n\tconst unsigned char*\tbuff,\n\tint\t\t\t\t\t\tpos,\n\tint\t\t\t\t\t\tlen)\n{\n\tunsigned int bits = getbitu(buff, pos, len);\n\t\n\t\n\tlong int invalid = (1ul<<(len-1));\n\t\n\tif (bits == -invalid)\n\t{\n\t\tstd::cout << \"warning: invalid number received on \" << __FUNCTION__ << \" \" << invalid << \" \" << len << std::endl;\n\t}\n\t\n\tif\t( len<=0\n\t\t||len>=32\n\t\t||!(bits&(1u<<(len-1)))) \n\t{\n\t\treturn (int)bits;\n\t}\n\treturn (int)(bits|(~0u<<len)); /* extend sign */\n}\n\nunsigned int getbituInc(\n\tconst unsigned char*\tbuff,\n\tint&\t\t\t\t\tpos,\n\tint\t\t\t\t\t\tlen)\n{\n\tunsigned int ans = getbitu(buff, pos, len);\n\tpos += len;\n\treturn ans;\n}\n\nint getbitsInc(\n\tconst unsigned char*\tbuff,\n\tint&\t\t\t\t\tpos,\n\tint\t\t\t\t\t\tlen)\n{\n\tint ans = getbits(buff, pos, len);\n\tpos += len;\n\treturn ans;\n}\n", "meta": {"hexsha": "93c315e6b93ff3530b8471e1fd95573801e5e85e", "size": 4718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/common/common.cpp", "max_stars_repo_name": "HiTMonitor/ginan", "max_stars_repo_head_hexsha": "f348e2683507cfeca65bb58880b3abc2f9c36bcf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-31T15:16:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:16:19.000Z", "max_issues_repo_path": "src/cpp/common/common.cpp", "max_issues_repo_name": "hqy123-cmyk/ginan", "max_issues_repo_head_hexsha": "b69593b584f75e03238c1c667796e2030391fbed", "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/cpp/common/common.cpp", "max_forks_repo_name": "hqy123-cmyk/ginan", "max_forks_repo_head_hexsha": "b69593b584f75e03238c1c667796e2030391fbed", "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.2489270386, "max_line_length": 115, "alphanum_fraction": 0.5385756677, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.544417709494329}}
{"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#define BOOST_TEST_MODULE TestStableSort\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/algorithm/stable_sort.hpp>\n#include <boost/compute/algorithm/is_sorted.hpp>\n#include <boost/compute/container/vector.hpp>\n\n#include \"check_macros.hpp\"\n#include \"context_setup.hpp\"\n\nBOOST_AUTO_TEST_CASE(sort_int_vector)\n{\n    int data[] = { -4, 152, -5000, 963, 75321, -456, 0, 1112 };\n    boost::compute::vector<int> vector(data, data + 8);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(8));\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end()) == false);\n\n    boost::compute::stable_sort(vector.begin(), vector.end());\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end()) == true);\n    CHECK_RANGE_EQUAL(int, 8, vector, (-5000, -456, -4, 0, 152, 963, 1112, 75321));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ab6fc1c498e0d416b2c83b13af368a0ff35ea2cf", "size": 1312, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_stable_sort.cpp", "max_stars_repo_name": "cwkx/compute", "max_stars_repo_head_hexsha": "86fb40da9f97ea014cd78aa3adba557bdd1a3528", "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": "test/test_stable_sort.cpp", "max_issues_repo_name": "cwkx/compute", "max_issues_repo_head_hexsha": "86fb40da9f97ea014cd78aa3adba557bdd1a3528", "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_stable_sort.cpp", "max_forks_repo_name": "cwkx/compute", "max_forks_repo_head_hexsha": "86fb40da9f97ea014cd78aa3adba557bdd1a3528", "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": 37.4857142857, "max_line_length": 83, "alphanum_fraction": 0.6333841463, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.544417704233638}}
{"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\n#include <algorithm>\n#include <boost/core/lightweight_test.hpp>\n#include <boost/gil/point.hpp>\n#include <boost/gil/rasterization/line.hpp>\n\n#include <cmath>\n#include <cstddef>\n#include <iterator>\n#include <random>\n#include <vector>\n\nnamespace gil = boost::gil;\n\nnamespace boost\n{\nnamespace gil\n{\nstd::ostream& operator<<(std::ostream& os, const point_t p)\n{\n    os << \"{x=\" << p.x << \", y=\" << p.y << \"}\";\n    return os;\n}\n}} // namespace boost::gil\n\nusing line_type = std::vector<gil::point_t>;\n\nstruct endpoints\n{\n    gil::point_t start;\n    gil::point_t end;\n};\n\nendpoints create_endpoints(std::mt19937& twister,\n                           std::uniform_int_distribution<std::ptrdiff_t>& distr)\n{\n    gil::point_t start{distr(twister), distr(twister)};\n    gil::point_t end{distr(twister), distr(twister)};\n    return {start, end};\n}\n\nline_type create_line(endpoints points)\n{\n    gil::bresenham_line_rasterizer rasterizer;\n    line_type forward_line(rasterizer.point_count(points.start, points.end));\n    rasterizer(points.start, points.end, forward_line.begin());\n    return forward_line;\n}\n\nvoid test_start_end(const line_type& line_points, endpoints points)\n{\n    BOOST_TEST_EQ(line_points.front(), points.start);\n    BOOST_TEST_EQ(line_points.back(), points.end);\n}\n\n// Look at TODO below\n// void test_two_way_equivalence(const line_type& forward, line_type backward)\n// {\n//     std::reverse(backward.begin(), backward.end());\n//     BOOST_TEST_ALL_EQ(forward.begin(), forward.end(), backward.begin(), backward.end());\n// }\n\nvoid test_connectivity(line_type const& line_points)\n{\n    for (std::size_t i = 1; i < line_points.size(); ++i)\n    {\n        const auto x_diff = std::abs(line_points[i].x - line_points[i - 1].x);\n        const auto y_diff = std::abs(line_points[i].y - line_points[i - 1].y);\n        BOOST_TEST_LE(x_diff, 1);\n        BOOST_TEST_LE(y_diff, 1);\n    }\n}\n\nvoid test_bresenham_rasterizer_follows_equation(line_type line_points)\n{\n    auto start = line_points.front();\n    auto end = line_points.back();\n\n    auto width = std::abs(end.x - start.x) + 1;\n    auto height = std::abs(end.y - start.y) + 1;\n    if (width < height)\n    {\n        std::swap(width, height);\n        std::transform(line_points.begin(), line_points.end(), line_points.begin(),\n                       [](gil::point_t p)\n                       {\n                           return gil::point_t{p.y, p.x};\n                       });\n        // update start and end\n        start = line_points.front();\n        end = line_points.back();\n    }\n    const double sign = [start, end]()\n    {\n        auto const width_sign = end.x < start.x;\n        auto const height_sign = end.y < start.y;\n        auto const slope_sign = width_sign != height_sign;\n        return slope_sign ? -1 : 1;\n    }();\n    const double slope = static_cast<double>(height) / static_cast<double>(width);\n    const double intercept =\n        static_cast<double>(start.y) - sign * slope * static_cast<double>(start.x);\n    for (const auto& point : line_points)\n    {\n        double const expected_y = sign * slope * static_cast<double>(point.x) + intercept;\n        auto const difference =\n            std::abs(point.y - static_cast<std::ptrdiff_t>(std::round(expected_y)));\n        BOOST_TEST_LE(difference, static_cast<std::ptrdiff_t>(slope + 1));\n    }\n}\n\nint main()\n{\n    const std::ptrdiff_t size = 256;\n    for (std::size_t seed = 0; seed <= 100; ++seed)\n    {\n        std::mt19937 twister(seed);\n        std::uniform_int_distribution<std::ptrdiff_t> distr(0, size - 1);\n        const std::size_t sample_count = 100;\n        for (std::size_t sample_index = 0; sample_index < sample_count; ++sample_index)\n        {\n            auto endpoints = create_endpoints(twister, distr);\n            auto forward_line = create_line(endpoints);\n            test_start_end(forward_line, endpoints);\n            // TODO: figure out if forward/backward equivalence is possible to provide\n            // auto backward_line = create_line({endpoints.end, endpoints.start});\n            // test_two_way_equivalence(forward_line, backward_line);\n            test_connectivity(forward_line);\n            // test_connectivity(backward_line);\n            test_bresenham_rasterizer_follows_equation(forward_line);\n            // test_bresenham_rasterizer_follows_equation(backward_line);\n        }\n    }\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "42e3bf7469f686a0307e142aa26df6d1fc01bf19", "size": 4703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/rasterization/line.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/rasterization/line.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/rasterization/line.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": 32.4344827586, "max_line_length": 91, "alphanum_fraction": 0.6438443547, "num_tokens": 1155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5443215298413892}}
{"text": "#include \"catch.hpp\"\n\n#include <libIntegrate/_1D/RiemannRule.hpp>\n\n#include <boost/units/systems/si/force.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/energy.hpp>\n#include <boost/units/quantity.hpp>\nusing namespace boost::units;\nusing namespace boost::units::si;\n\nnamespace BoostUnitsTests\n{\n\n\nTEST_CASE( \"Testing Riemann rule with boost units.\" ) {\n\n  _1D::RiemannRule<quantity<energy>> integrate;\n  quantity<energy> I;\n\n  std::vector<quantity<length>> x(3);\n  std::vector<quantity<force>> F(3);\n  x[0] = 0.*meter; F[0] = 1.*newton;\n  x[1] = 1.*meter; F[1] = 2.*newton;\n  x[2] = 2.*meter; F[2] = 3.*newton;\n  \n  I = integrate( x, F );\n  REQUIRE( quantity_cast<double>(I) == Approx( 3 ) );\n\n}\n\n}\n", "meta": {"hexsha": "d616db86204210da7814b9dbd823f33f00580e2a", "size": 734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/CatchTests/BoostUnitsTests.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": "testing/CatchTests/BoostUnitsTests.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": "testing/CatchTests/BoostUnitsTests.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": 22.2424242424, "max_line_length": 55, "alphanum_fraction": 0.6757493188, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.5443215243002225}}
{"text": "/*\n# Copyright (c) 2014-2016, NVIDIA CORPORATION. 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#  * 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY\n# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (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#include \"vstab_nodes.hpp\"\n\n#include <Eigen/SVD>\n\nstatic const char KERNEL_HOMOGRAPHY_FILTER_NAME[VX_MAX_KERNEL_NAME] = \"example.nvx.homography_filter\";\n\n// Kernel implementation\nstatic vx_status VX_CALLBACK homographyFilter_kernel(vx_node, const vx_reference *parameters, vx_uint32 num)\n{\n    if (num != 4)\n        return VX_FAILURE;\n\n    vx_status status = VX_SUCCESS;\n\n    vx_matrix input = (vx_matrix)parameters[0];\n    vx_matrix homography = (vx_matrix)parameters[1];\n    vx_image image = (vx_image)parameters[2];\n    vx_array mask = (vx_array)parameters[3];\n\n    // Copy input to homography\n    vx_float32 intputData[9] = {0};\n    status |= vxCopyMatrix(input, intputData, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);\n    status |= vxCopyMatrix(homography, intputData, VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST);\n\n    vx_uint32 width = 0, height = 0;\n    status |= vxQueryImage(image, VX_IMAGE_ATTRIBUTE_WIDTH, &width, sizeof(width));\n    status |= vxQueryImage(image, VX_IMAGE_ATTRIBUTE_HEIGHT, &height, sizeof(height));\n\n    vx_size nPoints;\n    status |= vxQueryArray(mask, VX_ARRAY_ATTRIBUTE_NUMITEMS, &nPoints, sizeof(nPoints));\n\n    vx_int32 nInliers = 0;\n    if (nPoints > 0)\n    {\n        vx_map_id map_id;\n        vx_size stride;\n        void* ptr;\n        status |= vxMapArrayRange(mask, 0, nPoints, &map_id, &stride, &ptr, VX_READ_ONLY, VX_MEMORY_TYPE_HOST, 0);\n\n        for (vx_size i = 0; i < nPoints; i++)\n        {\n            vx_uint8 v = vxArrayItem(vx_uint8, ptr, i, stride);\n            if (v != 0)\n                ++nInliers;\n        }\n\n        status |= vxUnmapArrayRange(mask, map_id);\n    }\n\n    int inlierThresh = std::max(15, static_cast<int>(0.1 * nPoints));\n    Matrix3x3f_rm eye3x3 = Matrix3x3f_rm::Identity();\n\n    if (nInliers < inlierThresh)\n    {\n        status |= vxCopyMatrix(homography, eye3x3.data(), VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST);\n        return status;\n    }\n\n    vx_float32 data[9];\n    status |= vxCopyMatrix(homography, data, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);\n\n    Matrix3x3f_rm M = Matrix3x3f_rm::Map(data, 3, 3);\n    M.transposeInPlace();\n\n    // restrictions on the lenghts of the diagonals of the warped image\n    Matrix3x4f_rm vertices = Matrix3x4f_rm::Zero();\n\n    for(int i=0; i<4; ++i)\n        vertices(2, i) = 1.0f;\n\n    vertices(0, 1) = static_cast<float>(width);\n    vertices(0, 2) = static_cast<float>(width);\n    vertices(1, 2) = static_cast<float>(height);\n    vertices(1, 3) = static_cast<float>(height);\n\n    Matrix3x4f_rm dstVertices = M * vertices;\n    for(int i=0; i<4; ++i)\n    {\n        dstVertices(0,i) /= dstVertices(2,i);\n        dstVertices(1,i) /= dstVertices(2,i);\n        dstVertices(2,i) = 1.0f;\n    }\n\n    float diagLenGold = std::sqrt(static_cast<float>(width*width + height*height));\n\n    float dx = dstVertices(0,0) - dstVertices(0,2);\n    float dy = dstVertices(1,0) - dstVertices(1,2);\n    float lenDiag1 = sqrt(dx*dx + dy*dy);\n\n    dx = dstVertices(0,1) - dstVertices(0,3);\n    dy = dstVertices(1,1) - dstVertices(1,3);\n    float lenDiag2 = sqrt(dx*dx + dy*dy);\n\n    float averDiagLen = (lenDiag1 + lenDiag2) / 2;\n    float diagRatio1 = std::min(diagLenGold, averDiagLen) / std::max(diagLenGold, averDiagLen);\n    if (diagRatio1 < 0.5f)\n    {\n        status |= vxCopyMatrix(homography, eye3x3.data(), VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST);\n        return status;\n    }\n\n    float maxDiag = std::max(lenDiag1, lenDiag2);\n    if (maxDiag > 0.0f)\n    {\n        float diagRatio2 = std::min(lenDiag1, lenDiag2) / maxDiag;\n        if (diagRatio2 < 0.25f)\n        {\n            status |= vxCopyMatrix(homography, eye3x3.data(), VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST);\n            return status;\n        }\n    }\n    else\n    {\n        status |= vxCopyMatrix(homography, eye3x3.data(), VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST);\n        return status;\n    }\n\n    // restriction on min eigen value\n    typedef Eigen::JacobiSVD<Matrix3x3f_rm> JacobiSVD;\n\n    JacobiSVD svd(M);\n    JacobiSVD::SingularValuesType singValues = svd.singularValues();\n\n    if (singValues(2) < 1e-4f)\n    {\n        status |= vxCopyMatrix(homography, eye3x3.data(), VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST);\n        return status;\n    }\n\n    return status;\n}\n\n// Parameter validator\nstatic vx_status VX_CALLBACK homographyFilter_validate(vx_node, const vx_reference parameters[],\n                                                       vx_uint32 numParams, vx_meta_format metas[])\n{\n    if (numParams != 4) return VX_ERROR_INVALID_PARAMETERS;\n\n    vx_matrix input = (vx_matrix)parameters[0];\n    vx_array mask = (vx_array)parameters[3];\n\n    vx_status status = VX_SUCCESS;\n\n    vx_enum inputDataType = 0;\n    vx_size inputRows = 0ul, inputCols = 0ul;\n    vxQueryMatrix(input, VX_MATRIX_ATTRIBUTE_TYPE, &inputDataType, sizeof(inputDataType));\n    vxQueryMatrix(input, VX_MATRIX_ATTRIBUTE_ROWS, &inputRows, sizeof(inputRows));\n    vxQueryMatrix(input, VX_MATRIX_ATTRIBUTE_COLUMNS, &inputCols, sizeof(inputCols));\n\n    vx_enum maskType = 0;\n    vxQueryArray(mask, VX_ARRAY_ATTRIBUTE_ITEMTYPE, &maskType, sizeof(maskType));\n\n    if (inputDataType != VX_TYPE_FLOAT32 || inputCols != 3 || inputRows != 3)\n    {\n        status = VX_ERROR_INVALID_PARAMETERS;\n    }\n\n    if (maskType != VX_TYPE_UINT8)\n    {\n        status = VX_ERROR_INVALID_TYPE;\n    }\n\n    vx_meta_format homographyMeta = metas[1];\n\n    vx_enum homographyType = VX_TYPE_FLOAT32;\n    vx_size homographyRows = 3;\n    vx_size homographyCols = 3;\n\n    vxSetMetaFormatAttribute(homographyMeta, VX_MATRIX_ATTRIBUTE_TYPE, &homographyType, sizeof(homographyType));\n    vxSetMetaFormatAttribute(homographyMeta, VX_MATRIX_ATTRIBUTE_ROWS, &homographyRows, sizeof(homographyRows));\n    vxSetMetaFormatAttribute(homographyMeta, VX_MATRIX_ATTRIBUTE_COLUMNS, &homographyCols, sizeof(homographyCols));\n\n    return status;\n}\n\n// Register user defined kernel in OpenVX context\nvx_status registerHomographyFilterKernel(vx_context context)\n{\n    vx_status status = VX_SUCCESS;\n\n    vx_enum id;\n    status = vxAllocateUserKernelId(context, &id);\n    if (status != VX_SUCCESS)\n    {\n        vxAddLogEntry((vx_reference)context, status, \"[%s:%u] Failed to allocate an ID for the HomographyFilter kernel\",\n                      __FUNCTION__, __LINE__);\n        return status;\n    }\n\n    vx_kernel kernel = vxAddUserKernel(context, KERNEL_HOMOGRAPHY_FILTER_NAME,\n                                       id,\n                                       homographyFilter_kernel,\n                                       4,\n                                       homographyFilter_validate,\n                                       NULL,\n                                       NULL\n                                       );\n\n    status = vxGetStatus((vx_reference)kernel);\n    if (status != VX_SUCCESS)\n    {\n        vxAddLogEntry((vx_reference)context, status, \"[%s:%u] Failed to create HomographyFilter Kernel\", __FUNCTION__, __LINE__);\n        return status;\n    }\n\n    status |= vxAddParameterToKernel(kernel, 0, VX_INPUT, VX_TYPE_MATRIX, VX_PARAMETER_STATE_REQUIRED); // input\n    status |= vxAddParameterToKernel(kernel, 1, VX_OUTPUT, VX_TYPE_MATRIX, VX_PARAMETER_STATE_REQUIRED); // homography\n    status |= vxAddParameterToKernel(kernel, 2, VX_INPUT, VX_TYPE_IMAGE, VX_PARAMETER_STATE_REQUIRED); // image\n    status |= vxAddParameterToKernel(kernel, 3, VX_INPUT, VX_TYPE_ARRAY, VX_PARAMETER_STATE_REQUIRED); // mask\n\n    if (status != VX_SUCCESS)\n    {\n        vxReleaseKernel(&kernel);\n        vxAddLogEntry((vx_reference)context, status, \"[%s:%u] Failed to initialize HomographyFilter Kernel parameters\", __FUNCTION__, __LINE__);\n        return VX_FAILURE;\n    }\n\n    status = vxFinalizeKernel(kernel);\n    vxReleaseKernel(&kernel);\n\n    if (status != VX_SUCCESS)\n    {\n        vxAddLogEntry((vx_reference)context, status, \"[%s:%u] Failed to finalize HomographyFilter Kernel\", __FUNCTION__, __LINE__);\n        return VX_FAILURE;\n    }\n\n    return status;\n}\n\n\nvx_node homographyFilterNode(vx_graph graph, vx_matrix input, vx_matrix homography, vx_image image, vx_array mask)\n{\n    vx_node node = NULL;\n\n    vx_kernel kernel = vxGetKernelByName(vxGetContext((vx_reference)graph), KERNEL_HOMOGRAPHY_FILTER_NAME);\n\n    if (vxGetStatus((vx_reference)kernel) == VX_SUCCESS)\n    {\n        node = vxCreateGenericNode(graph, kernel);\n        vxReleaseKernel(&kernel);\n\n        if (vxGetStatus((vx_reference)node) == VX_SUCCESS)\n        {\n            vxSetParameterByIndex(node, 0, (vx_reference)input);\n            vxSetParameterByIndex(node, 1, (vx_reference)homography);\n            vxSetParameterByIndex(node, 2, (vx_reference)image);\n            vxSetParameterByIndex(node, 3, (vx_reference)mask);\n        }\n    }\n\n    return node;\n}\n", "meta": {"hexsha": "cea4bd88bcb5ab33c993295bad2e469b1dba370f", "size": 10227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/third_party/VisionWorks-1.6-Demos/demos/video_stabilizer/homography_filter_node.cpp", "max_stars_repo_name": "reveriel/cuda_scheduling_examiner_mirror", "max_stars_repo_head_hexsha": "16d2404c0dc8d72f7a13e4a167d3db4c86128a26", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2017-05-23T00:27:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:56:07.000Z", "max_issues_repo_path": "src/third_party/VisionWorks-1.6-Demos/demos/video_stabilizer/homography_filter_node.cpp", "max_issues_repo_name": "reveriel/cuda_scheduling_examiner_mirror", "max_issues_repo_head_hexsha": "16d2404c0dc8d72f7a13e4a167d3db4c86128a26", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-10-22T13:47:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-03T16:09:04.000Z", "max_forks_repo_path": "src/third_party/VisionWorks-1.6-Demos/demos/video_stabilizer/homography_filter_node.cpp", "max_forks_repo_name": "reveriel/cuda_scheduling_examiner_mirror", "max_forks_repo_head_hexsha": "16d2404c0dc8d72f7a13e4a167d3db4c86128a26", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2017-09-11T19:59:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T10:00:22.000Z", "avg_line_length": 36.3950177936, "max_line_length": 144, "alphanum_fraction": 0.6757602425, "num_tokens": 2606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5443215188400667}}
{"text": "#define DEBUG 1\n/**\n * File    : A.cpp\n * Author  : Kazune Takahashi\n * Created : 2020/1/25 11:32:12\n * Powered by Visual Studio Code\n */\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n// ----- boost -----\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n// ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n// ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n// constexpr ll MOD{998244353LL}; // be careful\nconstexpr ll MAX_SIZE{3000010LL};\n// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n  }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n  }\n}\n// ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(const Mint &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(const Mint &a) { return *this += -a; }\n  Mint &operator*=(const Mint &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator/=(const Mint &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }\n  bool operator<(const Mint &a) const { return x < a.x; }\n  bool operator<=(const Mint &a) const { return x <= a.x; }\n  bool operator>(const Mint &a) const { return x > a.x; }\n  bool operator>=(const Mint &a) const { return x >= a.x; }\n  bool operator==(const Mint &a) const { return x == a.x; }\n  bool operator!=(const Mint &a) const { return !(*this == a); }\n  const Mint power(ll N)\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N / 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n  return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)\n{\n  return Mint<MOD>{lhs} / rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n  return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n  return stream << a.x;\n}\n// ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i = 2LL; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i = 1LL; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x / gcd(x, y) * y; }\ntemplate <typename T>\nint popcount(T x) // C++20\n{\n  int ans{0};\n  while (x != 0)\n  {\n    ans += x & 1;\n    x >>= 1;\n  }\n  return ans;\n}\n// ----- frequently used constexpr -----\n// constexpr double epsilon{1e-10};\n// constexpr ll infty{1000000000000000LL};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\nclass Sieve\n{\n  static constexpr ll MAX_SIZE{10000010LL};\n  ll N;\n  vector<ll> f;\n  vector<ll> prime_nums;\n\npublic:\n  Sieve(ll N = MAX_SIZE) : N{N}, f(N, 0), prime_nums{}\n  {\n    f[0] = f[1] = -1;\n    for (auto i = 2; i < N; i++)\n    {\n      if (f[i])\n      {\n        continue;\n      }\n      prime_nums.push_back(i);\n      f[i] = i;\n      for (auto j = 2 * i; j < N; j += i)\n      {\n        if (!f[j])\n        {\n          f[j] = i;\n        }\n      }\n    }\n  }\n\n  bool is_prime(ll x) const\n  { // 2 \\leq x \\leq MAX_SIZE^2\n    if (x < N)\n    {\n      return f[x];\n    }\n    for (auto e : prime_nums)\n    {\n      if (x % e == 0)\n      {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  vector<ll> const &primes() const\n  {\n    return prime_nums;\n  }\n\n  vector<ll> factor_list(ll x) const\n  {\n    if (x < 2)\n    {\n      return {};\n    }\n    vector<ll> res;\n    auto it{prime_nums.begin()};\n    if (x < N)\n    {\n      while (x != 1)\n      {\n        res.push_back(f[x]);\n        x /= f[x];\n      }\n    }\n    else\n    {\n      while (x != 1 && it != prime_nums.end())\n      {\n        if (x % *it == 0)\n        {\n          res.push_back(*it);\n          x /= *it;\n        }\n        else\n        {\n          ++it;\n        }\n      }\n      if (x != 1)\n      {\n        res.push_back(x);\n      }\n    }\n    return res;\n  }\n\n  vector<tuple<ll, ll>> factor(ll x) const\n  {\n    if (x < 2)\n    {\n      return {};\n    }\n    auto factors{factor_list(x)};\n    vector<tuple<ll, ll>> res{make_tuple(factors[0], 0)};\n    for (auto x : factors)\n    {\n      if (x == get<0>(res.back()))\n      {\n        get<1>(res.back())++;\n      }\n      else\n      {\n        res.emplace_back(x, 1);\n      }\n    }\n    return res;\n  }\n};\n\n// ----- main() -----\n\nusing ld = long double;\nusing point = complex<ld>;\nconstexpr ld PI{3.14159265358979323846};\n\nclass Solve\n{\n  ld La, Lb, Lc, Na, Nb, Nc, Ne, Ma, Mb, Mc, Tc;\n  int alpha;\n  Sieve sieve;\n  ld Ta = 0;\n  ld Tb;\n  point Oa{0, 900}, Ob{900, 0}, Oc{900, 900}, Oe{90, 50};\n  point Aa{1, 0}, Ab{0, 1}, Ac{-1, 0};\n  ld S{500}, A{3000}, D{60};\n\npublic:\n  Solve(ld La, ld Lb, ld Lc, ld Na, ld Nb, ld Nc, ld Ne, ld Ma, ld Mb, ld Mc, ld Tc) : La{La}, Lb{Lb}, Lc{Lc}, Na{Na}, Nb{Nb}, Nc{Nc}, Ne{Ne}, Ma{Ma}, Mb{Mb}, Mc{Mc}, Tc{Tc} {}\n\n  void flush()\n  {\n    for (auto i = 0; i < 20; ++i)\n    {\n      ld now{0};\n      ld W{Ma};\n      if (now + Ma * Na > 100)\n      {\n        W = 500;\n      }\n      flush_A(W);\n      now += Na * W;\n      W = Mb;\n      if (now + Mb * Nb > 100)\n      {\n        W = 500;\n      }\n      flush_B(W);\n      now += Nb * W;\n      W = Mc;\n      if (now + Mc * Nc > 100)\n      {\n        W = 500;\n      }\n      flush_C(W);\n      now += Nc * W;\n      flush_E(now / Ne);\n    }\n  }\n\nprivate:\n  void update_Tb()\n  {\n    if (alpha == 0)\n    {\n      Tb = 0;\n    }\n    else\n    {\n      ll p{sieve.primes()[alpha + 1]};\n      ll r{p % 180};\n      Tb = (r <= 90 ? r : 180 - r);\n    }\n  }\n\n  point arg(ld theta) { return theta / 180 * PI * point(0, 1); }\n  point Pa() { return exp(-arg(Ta)) * La + Oa; }\n  point Pb() { return exp(arg(Tb)) * Lb + Ob; }\n  point Pc() { return exp(arg(Tc)) * Lc + Oc; }\n\n  void flush_simple(ld X, ld Sx, ld Ax, ld Dx, ld Y, ld Sy, ld Ay, ld Dy, ld Ta, ld Wa, ld Wb, ld Wc, ld We)\n  {\n    cout << fixed << setprecision(0) << X << \", \" << Sx << \", \" << Ax << \", \" << Dx << \", \" << Y << \", \" << Sy << \", \" << Ay << \", \" << Dy << \", \" << Ta << \", \" << Wa << \", \" << Wb << \", \" << Wc << \", \" << We << endl;\n  }\n\n  void flush_A(ld W)\n  {\n    flush_simple(Pa().real(), S, A, D, Pa().imag(), S, A, D, Ta, W, 0, 0, 0);\n    alpha += W;\n  }\n\n  void flush_B(ld W)\n  {\n    flush_simple(Pb().real(), S, A, D, Pb().imag(), S, A, D, Ta, 0, W, 0, 0);\n  }\n\n  void flush_C(ld W)\n  {\n    flush_simple(Pc().real(), S, A, D, Pc().imag(), S, A, D, Ta, 0, 0, W, 0);\n  }\n\n  void flush_E(ld W)\n  {\n    flush_simple(Oe.real(), S, A, D, Oe.imag(), S, A, D, Ta, 0, 0, 0, W);\n  }\n};\n\nint main()\n{\n  ld La, Lb, Lc, Na, Nb, Nc, Ne, Ma, Mb, Mc, Tc;\n  cin >> La >> Lb >> Lc >> Na >> Nb >> Nc >> Ne >> Ma >> Mb >> Mc >> Tc;\n  Solve solve(La, Lb, Lc, Na / 1000, Nb / 1000, Nc / 1000, Ne / 1000, Ma, Mb, Mc, Tc);\n  solve.flush();\n}\n", "meta": {"hexsha": "c1d8c9b1a9b00818d5ae083fa70c5fabe91ba6eb", "size": 9016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/0125_ddcc2020-machine/A.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2020/0125_ddcc2020-machine/A.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/0125_ddcc2020-machine/A.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 20.8221709007, "max_line_length": 217, "alphanum_fraction": 0.5043256433, "num_tokens": 3093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.5443215075146992}}
{"text": "#include <iostream>\n#include <limits>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\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>>>>\n    graph;\n\ntypedef traits::vertex_descriptor vertex_desc;\ntypedef traits::edge_descriptor edge_desc;\n\nclass edge_adder\n{\n    graph &G;\n\npublic:\n    explicit edge_adder(graph &G) : G(G) {}\n\n    void add_edge(int from, int to, long capacity)\n    {\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\nvoid solve()\n{\n    int n, m;\n    cin >> n >> m;\n\n    graph G(n);\n    edge_adder adder(G);\n\n    int u, v, c;\n    for (int i = 0; i < m; ++i) {\n        cin >> u >> v >> c;\n        adder.add_edge(u, v, c);\n    }\n\n    long minCut = numeric_limits<long>::max();\n\n    int source = 0;\n    for (int target = 1; target < n; ++target) {\n        long maxFlow = boost::push_relabel_max_flow(G, source, target);\n        minCut = min(minCut, maxFlow);\n        maxFlow = boost::push_relabel_max_flow(G, target, source);\n        minCut = min(minCut, maxFlow);\n    }\n    cout << minCut << endl;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; ++i)\n    {\n        solve();\n    }\n    return 0;\n}\n", "meta": {"hexsha": "d03364006b396f39c96512eb1c38dc80887cff2e", "size": 2008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algocoon.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/algocoon.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/algocoon.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": 27.1351351351, "max_line_length": 128, "alphanum_fraction": 0.5761952191, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5443112067206277}}
{"text": "#include <geometry.h>\n#include <tiny_math_types.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\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(raycast_tetrahedron)\n{\n\n  using std::sqrt;\n\n  typedef tiny::MathTypes<double>   MT;\n  typedef MT::vector3_type          V;\n  typedef MT::real_type             T;\n  typedef MT::value_traits          VT;\n\n\n  V const p0 = V::make(0.0, 0.0, 0.0);\n  V const p1 = V::make(1.0, 0.0, 0.0);\n  V const p2 = V::make(0.0, 1.0, 0.0);\n  V const p3 = V::make(0.0, 0.0, 1.0);\n\n  geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0,p1,p2,p3);\n\n  // Ray hitting on bottom of tetrahedron\n  {\n    V                const p   = V::make( 0.0, 0.0, -1.0);\n    V                const r   = V::make( 0.2, 0.2,  1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool const hit = geometry::compute_raycast_tetrahedron(ray, tetrahedron, q, length );\n\n    BOOST_CHECK( hit );\n    BOOST_CHECK_CLOSE( length, tiny::norm(r), 0.01);\n    BOOST_CHECK_CLOSE( q(0),  0.2, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  0.2, 0.01);\n    BOOST_CHECK_CLOSE( q(2),  0.0, 0.01);\n  }\n  // Ray missing tetrahedron\n  {\n    V                const p   = V::make( 0.0, 0.0, -1.0);\n    V                const r   = V::make( -0.2, -0.2,  1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool const hit = geometry::compute_raycast_tetrahedron(ray, tetrahedron, q, length );\n\n    BOOST_CHECK( !hit );\n  }\n  // Ray hitting on bottom of tetrahedron only bottom is surface\n  {\n    std::vector<bool> surface_map(4, false);\n\n    surface_map[3] = true;\n\n    V                const p   = V::make( 0.0, 0.0, -1.0);\n    V                const r   = V::make( 0.2, 0.2,  1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool const hit = geometry::compute_raycast_tetrahedron(ray, tetrahedron, q, length, surface_map );\n\n    BOOST_CHECK( hit );\n    BOOST_CHECK_CLOSE( length, tiny::norm(r), 0.01);\n    BOOST_CHECK_CLOSE( q(0),  0.2, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  0.2, 0.01);\n    BOOST_CHECK_CLOSE( q(2),  0.0, 0.01);\n  }\n  // Ray from above hitting bottom of tetrahedron only bottom is surface\n  {\n    std::vector<bool> surface_map(4, false);\n\n    surface_map[3] = true;\n\n    V                const p   = V::make( 0.0, 0.0,  1.0);\n    V                const r   = V::make( 0.2, 0.2, -1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool const hit = geometry::compute_raycast_tetrahedron(ray, tetrahedron, q, length, surface_map );\n\n    BOOST_CHECK( !hit );\n  }\n\n  // Stress testing... generating a bunch of random rays that all are hitting the oblique top plane\n  for (unsigned int samples = 0u; samples < 1000u; ++samples)\n  {\n    V                const noise           = V::random(0.0, 1.0);\n    T                const v1              = noise(0);\n    T                const v2              = noise(1);\n    T                const v3              = 1.0 - v1 - v2;\n    T                const w1              = (v3 < 0.0) ?  v1/(1.0-v3) : v1;\n    T                const w2              = (v3 < 0.0) ?  v2/(1.0-v3) : v2;\n    T                const w3              = (v3 < 0.0) ?  0.0 : v3;\n\n    if( w3==0.0) // We do not wish to test for exact edge cases --- they are sensitive to finite precision errors\n      continue;\n    if( w3==0.0)  // We do not wish to test for exact edge cases --- they are sensitive to finite precision errors\n      continue;\n    if( w3==0.0)  // We do not wish to test for exact edge cases --- they are sensitive to finite precision errors\n      continue;\n\n    BOOST_CHECK_CLOSE( (w1+w2+w3),  1.0, 0.01);\n    \n    BOOST_CHECK( w1 >= 0.0);\n    BOOST_CHECK( w2 >= 0.0);\n    BOOST_CHECK( w3 >= 0.0);\n\n    BOOST_CHECK( w1 <= 1.0);\n    BOOST_CHECK( w2 <= 1.0);\n    BOOST_CHECK( w3 <= 1.0);\n\n    V                const hit_point       = w1*p1 + w2*p2 + w3*p3;\n    V                const ray_origin      = noise*10.0;\n    V                const ray_direction   = hit_point - ray_origin;\n    geometry::Ray<V> const ray             = geometry::make_ray(ray_origin, ray_direction);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool const hit = geometry::compute_raycast_tetrahedron(ray, tetrahedron, q, length );\n\n    BOOST_CHECK( hit );\n    BOOST_CHECK_CLOSE( length, tiny::norm(ray_direction), 0.01);\n\n    for(unsigned int i = 0;i<3u;++i)\n    {\n      if(fabs(hit_point(i)) < tiny::working_precision<T>() )\n        BOOST_CHECK_SMALL( q(i),  tiny::working_precision<T>());\n      else\n        BOOST_CHECK_CLOSE( q(i),  hit_point(i), 0.01);\n    }\n  }\n\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "2bc7ed17a2a78f77e1c557cc681963a38cad1c4f", "size": 5034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_raycast_tetrahedron/geometry_raycast_tetrahedron.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/GEOMETRY/unit_tests/geometry_raycast_tetrahedron/geometry_raycast_tetrahedron.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/GEOMETRY/unit_tests/geometry_raycast_tetrahedron/geometry_raycast_tetrahedron.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": 32.9019607843, "max_line_length": 114, "alphanum_fraction": 0.5534366309, "num_tokens": 1622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5443112013622213}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/assert.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/product.hpp>\n#include <boost/hana/range.hpp>\n#include <boost/hana/tuple.hpp>\nnamespace hana = boost::hana;\n\n\nint main() {\n    BOOST_HANA_CONSTANT_CHECK(\n        hana::product<>(hana::make_range(hana::int_c<1>, hana::int_c<6>)) == hana::int_c<1 * 2 * 3 * 4 * 5>\n    );\n\n    BOOST_HANA_CONSTEXPR_CHECK(\n        hana::product<>(hana::make_tuple(1, hana::int_c<3>, hana::long_c<-5>, 9)) == 1 * 3 * -5 * 9\n    );\n\n    BOOST_HANA_CONSTEXPR_CHECK(\n        hana::product<unsigned long>(hana::make_tuple(2ul, 3ul)) == 6ul\n    );\n}\n", "meta": {"hexsha": "99ed4bf95cb78f301ba883c7a084272c393e5467", "size": 827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/product.cpp", "max_stars_repo_name": "qicosmos/hana", "max_stars_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-06T05:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T21:48:27.000Z", "max_issues_repo_path": "example/product.cpp", "max_issues_repo_name": "qicosmos/hana", "max_issues_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "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/product.cpp", "max_forks_repo_name": "qicosmos/hana", "max_forks_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-06T10:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-06T10:50:17.000Z", "avg_line_length": 28.5172413793, "max_line_length": 107, "alphanum_fraction": 0.6723095526, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757313, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5443111983832672}}
{"text": "\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n\n#include <boost/timer.hpp>\n\n#include \"CompositeMinimization.h\"\n\nnamespace Grante {\n\ndouble CompositeMinimization::FISTAMinimize(\n\tCompositeMinimizationProblem& prob, std::vector<double>& x_opt,\n\tdouble conv_tol, unsigned int max_iter, bool verbose) {\n\tdouble Lub = 0.25;\t// Lipschitz upper bound estimate for the gradient\n\tdouble eta = 2.0;\t// Lipschitz bound scale factor\n\n\t// Initialize iterates\n\tunsigned int dim = prob.Dimensions();\n\tx_opt.resize(dim);\n\tprob.ProvideStartingPoint(x_opt);\n\tstd::vector<double> xprev(x_opt);\n\tstd::vector<double> x_fgrad_dummy;\n\tstd::vector<double> y(x_opt);\n\tstd::vector<double> y_fgrad(dim, 0.0);\n\tstd::vector<double> u(dim, 0.0);\n\n\t// Convergence criterion\n\tdouble conv = std::numeric_limits<double>::infinity();\n\tdouble t = 1.0;\n\n\t// Objective F(x)=f(x)+g(x)\n\tdouble Fval = std::numeric_limits<double>::signaling_NaN();\n\tboost::timer total_timer;\n\tunsigned int lip_iter = 0;\n\tfor (unsigned int iter = 0; max_iter == 0 || iter < max_iter; ++iter) {\n\t\tdouble y_fval = prob.EvalF(y, y_fgrad);\n\t\tdouble obj = y_fval + prob.EvalG(y, x_fgrad_dummy);\n\n\t\t// Verbose output\n\t\tif (verbose && (iter % 20 == 0)) {\n\t\t\tstd::cout << std::endl;\n\t\t\tstd::cout << \"  iter     time      objective        conv  lipiter\"\n\t\t\t\t<< std::endl;\n\t\t}\n\t\tif (verbose) {\n\t\t\tstd::ios_base::fmtflags original_format = std::cout.flags();\n\t\t\tstd::streamsize original_prec = std::cout.precision();\n\n\t\t\t// Iteration\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setw(6) << iter << \"  \";\n\t\t\t// Total runtime\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::resetiosflags(std::ios::scientific)\n\t\t\t\t<< std::setiosflags(std::ios::fixed)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setprecision(1)\n\t\t\t\t<< std::setw(6) << total_timer.elapsed() << \"s  \";\n\t\t\tstd::cout << std::resetiosflags(std::ios::fixed);\n\n\t\t\t// Objective function\n\t\t\tstd::cout << std::setiosflags(std::ios::scientific)\n\t\t\t\t<< std::setprecision(5)\n\t\t\t\t<< std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::showpos)\n\t\t\t\t<< std::setw(7) << obj << \"   \";\n\t\t\t// Convergence criterion\n\t\t\tstd::cout << std::setiosflags(std::ios::scientific)\n\t\t\t\t<< std::setprecision(2)\n\t\t\t\t<< std::resetiosflags(std::ios::showpos)\n\t\t\t\t<< std::setiosflags(std::ios::left) << conv << \"   \";\n\t\t\t// Lipschitz iterations\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setw(6) << lip_iter;\n\n\t\t\tstd::cout << std::endl;\n\n\t\t\tstd::cout.precision(original_prec);\n\t\t\tstd::cout.flags(original_format);\n\t\t}\n\n\t\t// Backtracking\n\t\tlip_iter = 0;\n\t\tdo {\n\t\t\tlip_iter += 1;\n\n\t\t\t// Solve (2.6) in Beck and Teboulle\n\t\t\tstd::transform(y.begin(), y.end(), y_fgrad.begin(), u.begin(),\n\t\t\t\t[Lub](double y_e, double y_fgrad_e) -> double {\n\t\t\t\t\treturn (y_e - y_fgrad_e/Lub); });\n\t\t\t// update x_opt\n\t\t\tprob.EvalGProximalOperator(u, Lub, x_opt);\n\n\t\t\t// Evaluate F(x)\n\t\t\tFval = prob.EvalF(x_opt, x_fgrad_dummy);\n\t\t\tFval += prob.EvalG(x_opt, x_fgrad_dummy);\n\n\t\t\t// Evaluate Q_L(x,y)\n\t\t\tdouble Qval = y_fval + prob.EvalG(x_opt, x_fgrad_dummy);\n\t\t\tfor (unsigned int di = 0; di < dim; ++di) {\n\t\t\t\tdouble xsuby = x_opt[di] - y[di];\n\t\t\t\tQval += xsuby*y_fgrad[di];\n\t\t\t\tQval += 0.5*Lub*xsuby*xsuby;\n\t\t\t}\n\n\t\t\t// Sufficient upper bound on the Lipschitz constant?\n\t\t\tif (Fval <= Qval)\n\t\t\t\tbreak;\n\n\t\t\tLub *= eta;\t// Increase upper bound estimate\n\t\t} while (true);\n\n\t\t// Update t sequence\n\t\tdouble tprev = t;\n\t\tt = 0.5*(1.0 + std::sqrt(1.0 + 4.0*tprev*tprev));\n\n\t\t// Perform averaged step: update y\n\t\tstd::transform(x_opt.begin(), x_opt.end(), xprev.begin(),\n\t\t\ty.begin(), [t,tprev](double xe, double xle) -> double {\n\t\t\t\treturn (xe + ((tprev-1.0)/t)*(xe-xle)); });\n\t\t// conv=norm(x_opt-xprev)\n\t\tconv = 0.0;\n\t\tfor (unsigned int di = 0; di < dim; ++di)\n\t\t\tconv += (x_opt[di]-xprev[di]) * (x_opt[di]-xprev[di]);\n\t\tconv = std::sqrt(conv);\n\t\tif (conv <= conv_tol) {\n\t\t\tif (verbose) {\n\t\t\t\tstd::cout << \"Converged with tolerance \" << conv\n\t\t\t\t\t<< \" (<= \" << conv_tol << \").\" << std::endl;\n\t\t\t}\n\t\t\treturn (Fval);\n\t\t}\n\n\t\tstd::copy(x_opt.begin(), x_opt.end(), xprev.begin());\n\t}\n\treturn (Fval);\t// objective of x_opt\n}\n\n}\n\n", "meta": {"hexsha": "47e40e86dac0aa2f2ab135e3222fecb362965d0f", "size": 4290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grante/CompositeMinimization.cpp", "max_stars_repo_name": "pantonante/grante-bazel", "max_stars_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_stars_repo_licenses": ["DOC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grante/CompositeMinimization.cpp", "max_issues_repo_name": "pantonante/grante-bazel", "max_issues_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_issues_repo_licenses": ["DOC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grante/CompositeMinimization.cpp", "max_forks_repo_name": "pantonante/grante-bazel", "max_forks_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_forks_repo_licenses": ["DOC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1836734694, "max_line_length": 72, "alphanum_fraction": 0.6256410256, "num_tokens": 1384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5443111899260059}}
{"text": "//\n// Created by bobin on 17-12-13.\n//\n#include <MapPoint.h>\n#include <vector>\n#include <Eigen/Dense>\n#include <random>\n#include <chrono>\n\nusing namespace ORB_SLAM2;\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char **argv){\n    int point_num = 100;\n    vector<Vector3d> points;\n    points.resize(point_num);\n\n    for (int i = 0; i < point_num; ++i) {\n        double x,y,z;\n        x =  std::rand() % 100;\n        y = std::rand() % 100;\n        z = 0.1 * (1 - 5 * x - 10 * y) + std::rand() % 100 / 100.0 ;\n        points[i] = Vector3d(x, y, z)  / 10.0;\n    }\n\n    SurfacePieceWise surfacePieceWise(0);\n    surfacePieceWise.FitPlane(true, points);\n    std::cout << surfacePieceWise.GetNormal() << std::endl;\n    std::cout << surfacePieceWise.GetCentroid() << std::endl;\n}", "meta": {"hexsha": "ff520e08eb104808077a907b1a33162d242b53db", "size": 789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_surface.cpp", "max_stars_repo_name": "ClovisChen/ORB-Plane", "max_stars_repo_head_hexsha": "4ff221c1b673753f9c23ef07c0ed293f2f017231", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-11-11T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-27T10:05:57.000Z", "max_issues_repo_path": "test/test_surface.cpp", "max_issues_repo_name": "ClovisChen/ORB-Plane", "max_issues_repo_head_hexsha": "4ff221c1b673753f9c23ef07c0ed293f2f017231", "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/test_surface.cpp", "max_forks_repo_name": "ClovisChen/ORB-Plane", "max_forks_repo_head_hexsha": "4ff221c1b673753f9c23ef07c0ed293f2f017231", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-09-01T02:52:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T05:57:59.000Z", "avg_line_length": 25.4516129032, "max_line_length": 68, "alphanum_fraction": 0.598225602, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5443098425584891}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nEigen::VectorXd dipoleval(const Eigen::VectorXd & x, const Eigen::VectorXd & t, const Eigen::VectorXd & y){\n\tint x_size= x.size();\n\tint w=1;\n\tint n= t.size();\n\tEigen::VectorXd p=y;\n\tEigen::VectorXd dP=Eigen::MatrixXd::Zero(1,n);\n\tfor (int i=1; i<n; i++){//im\n\t\tfor (int j=i-1; j>0;j--){//i0\n\t\t\t//% compute dp(i)'s\n            dP(j) = p(j+1) + (x(w)-t(j))*dP(j+1) - p(j) - (x(w)-t(i))*dP(j);\n            dP(j) = dP(j) / ( t(i) - t(j) );\n            //% compute p(i)'s\n            p(j)  = (x(w)-t(j)*p(j+1) - (x(w)-t(i))*p(j));\n            p(j)  = p(j) / ( t(i) - t(j) );\n            }\n\t\t\tstd::cout <<\"test\\n\";\n\n\t}\n\treturn p.row(0);\n} \n\nint main(){\n\tint n=6;\n\tEigen::VectorXd x=Eigen::MatrixXd::Random(n,1);\n\tEigen::VectorXd y=Eigen::MatrixXd::Random(n,1);\n\tEigen::VectorXd t=Eigen::MatrixXd::Random(n,1);\n\t\n\tEigen::VectorXd v;\n\tv=dipoleval(x,t,y);\n\tstd::cout << v << std::endl;\n}\n\n", "meta": {"hexsha": "d678abff9133445f54272f57f9b97192f845f805", "size": 924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS6/dipoleval.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/PS6/dipoleval.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/PS6/dipoleval.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6666666667, "max_line_length": 107, "alphanum_fraction": 0.512987013, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5443098407788755}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2011 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef NORMS_HH\n#define NORMS_HH\n\n/**\n * @file\n * @brief  Some norms for FunctionSpaceElement s or FunctionViews\n * @author Anton Schiela\n */\n\n#include <boost/fusion/include/at_c.hpp>\n#include <fem/integration.hh>\n#include <fem/functionviews.hh>\n\nnamespace Kaskade\n{\n/// L_2-norms\nstruct L2Norm\n{\n/// Evaluation of square norm\n  template<typename Function> \n  double square(Function const& f) const\n  {\n    Integral<typename Function::Space> integral;\n    FunctionViews::AbsSquare<Function> asf(f);\n    return integral(asf);\n  }\n\n/// Evaluation of norm\n  template<typename Function> \n  double operator()(Function const& f) const\n  {\n    return std::sqrt(square(f));\n  }\n};\n\n/// L_2-norms\n// struct L2ScalarProduct\n// {\n// /// Evaluation of square norm\n//   template<typename Function> \n//   double operator()(Function f,Function g) \n//   {\n//     Integral<typename Function::Space> integral;\n//     FunctionViews::Dot<Function> dotfg(f,g);\n//     return integral(dotfg);\n//   }\n// \n// /// Evaluation of norm\n//   template<typename Function> \n//   double operator()(Function f) \n//   {\n//     return std::sqrt(this->operator()(f,f));\n//   }\n// };\n\n/// H1-semi-norms\nstruct H1SemiNorm\n{\n/// Evaluation of square norm\n  template<typename Function> \n  double square(Function const& f) const\n  {\n    Integral<typename Function::Space> integral;\n    FunctionViews::GradientAbsSquare<Function> asf(f);\n    return integral(asf);\n//    FunctionViews::Gradient<Function> gf(f);\n//    L2Norm l2Norm;\n//    return l2Norm.square(gf);\n  }  \n\n/// Evaluation of norm\n  template<typename Function> \n  double operator()(Function const& f) const\n  {\n    return std::sqrt(square(f));\n  }\n};\n\n\n// THE FOLLOWING CODE IS UNDOCUMENTED, APPEARS TO BE RATHER PROJECT-SPECIFIC, AND IS NOWHERE USED IN\n// THE SVN REPOSITORY. UNLESS SOME UNEXPECTED PROBLEMS ARISE, THIS CODE WILL BE DELETED AS OF \n// 2016-03-31.\n// \n// template <int val>\n// struct Decrement\n// {\n//   static constexpr int value = val-1;\n// };\n// \n// \n// \n// template <int variableId, int numberOfVariables>\n// struct MyNormEvaluator\n// {\n//   template <class DomainElement, class Norm>\n//   static double square(DomainElement const& x, Norm const& norm)\n//   {\n//     return norm.square( boost::fusion::at_c<variableId>(x.data) ) + MyNormEvaluator<variableId-1,numberOfVariables>::square(x,norm);\n//   }\n// };\n// \n// template <int numberOfVariables>\n// struct MyNormEvaluator<0,numberOfVariables>\n// {\n//   template <class DomainElement, class Norm>\n//   static double square(DomainElement const& x, Norm const& norm)\n//   {\n//     return norm.square( boost::fusion::at_c<0>(x.data) );\n//   }\n// };\n// \n// struct MyH1SemiNorm\n// {\n//   template <typename DomainElement>\n//   static double square(DomainElement const& x)\n//   {\n//     return MyNormEvaluator<DomainElement::Descriptions::noOfVariables-1, DomainElement::Descriptions::noOfVariables>::square(x,H1SemiNorm());\n//   }\n// \n//   template <typename DomainElement>\n//   double operator()(DomainElement const& x) const\n//   {\n//     return sqrt(square(x));\n//   }\n// };\n\n// struct MyL2Norm\n// {\n//   template <typename DomainElement>\n//   static double square(DomainElement const& x)\n//   {\n//     return MyNormEvaluator<DomainElement::Descriptions::noOfVariables-1, DomainElement::Descriptions::noOfVariables>::square(x,L2Norm());\n//   }\n// \n//   template <typename DomainElement>\n//   double operator()(DomainElement const& x) const\n//   {\n//     return sqrt(square(x));\n//   }\n// };\n\n\n/// H1-norms\nstruct H1Norm\n{\n/// Evaluation of square norm\n  template<typename Function> \n  double square(Function f) \n  {\n    H1SemiNorm h1Norm;\n    L2Norm l2Norm;\n    return h1Norm.square(f)+l2Norm.square(f);\n  }  \n\n/// Evaluation of norm\n  template<typename Function> \n  double operator()(Function f) \n  {\n    return std::sqrt(square(f));\n  }\n};\n\ntemplate<class Space> class LocalIntegral;\ntemplate<class Grid, class T> class CellData;\n\n/// local (cellwise) H1-semi-norms\ntemplate<class Function>\ntypename CellData<typename Function::Space::Grid, typename Function::ValueType>::CellDataVector localH1SemiNorm(Function const& f)\n{\n  typedef typename Function::Space Space;\n  typedef typename Space::Grid Grid;\n  LocalIntegral<Space> localIntegral;\n  typename CellData<Grid,typename Function::ValueType>::CellDataVector\n    errorIndicator(localIntegral(\n                     makeView<FunctionViews::AbsSquare>(makeView<FunctionViews::Gradient>(f))));\n  return errorIndicator;\n}\n\n/// local (cellwise) L2-norms\ntemplate<class Function>\ntypename CellData<typename Function::Space::Grid, typename Function::ValueType>::CellDataVector localL2Norm(Function const& f)\n{\n  typedef typename Function::Space Space;\n  typedef typename Space::Grid Grid;\n  LocalIntegral<Space> localIntegral;\n  typename CellData<Grid,typename Function::ValueType>::CellDataVector\n    errorIndicator(localIntegral(\n                     makeView<FunctionViews::AbsSquare>(f)));\n  return errorIndicator;\n}\n\n\n/**\n * @brief boundaryL2Norm computes the L2-norm of an FE function on the whole boundary of the underlying grid.\n *\n * @param function is the FE function to be integrated.\n * @tparam FEFunction is the type of the integrand.\n * @return value of integral\n *\n */\ntemplate <class FEFunction>\ntypename FEFunction::Space::Scalar boundaryL2Norm(FEFunction const& function) {\n  FunctionViews::AbsSquare<FEFunction> functionSquared(function);\n  return std::sqrt(integrateOverBoundary(functionSquared));\n}\n} // end of namespace Kaskade\n#endif\n", "meta": {"hexsha": "6ed61c74d007b10b1fe436064eca49c87bda6e9d", "size": 6376, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/fem/norms.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/fem/norms.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/fem/norms.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 28.9818181818, "max_line_length": 144, "alphanum_fraction": 0.6314303639, "num_tokens": 1582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5443098389992614}}
{"text": "//==================================================================================================\n/*\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n*/\n//==================================================================================================\n#include <eve/module/core.hpp>\n#include <eve/module/bessel.hpp>\n#include <cmath>\n#include <boost/math/special_functions/bessel.hpp>\n\nint main()\n{\n  EVE_VALUE mid = sizeof(EVE_VALUE) == 4 ? 2 : 5;\n  {\n    auto lmin = EVE_VALUE(0);\n    auto lmax = EVE_VALUE(mid);\n\n    auto arg0 = eve::bench::random_<EVE_VALUE>(lmin,lmax);\n    auto stdj0 = [](auto x){return std::cyl_bessel_j(0, x);};\n    auto boostj0= [](auto x){return boost::math::detail::bessel_j0(x);};\n    eve::bench::experiment xp;\n    run<EVE_TYPE> (EVE_NAME(cyl_bessel_j0_small) , xp, eve::cyl_bessel_j0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(cyl_bessel_j0_small) , xp, eve::cyl_bessel_j0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(stdj0_small) , xp, stdj0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(boostj0_small), xp, boostj0 , arg0);\n  }\n  {\n    auto lmin = EVE_VALUE(mid);\n    auto lmax = EVE_VALUE(8);\n\n    auto arg0 = eve::bench::random_<EVE_VALUE>(lmin,lmax);\n    auto stdj0 = [](auto x){return std::cyl_bessel_j(0, x);};\n    auto boostj0= [](auto x){return boost::math::detail::bessel_j0(x);};\n    eve::bench::experiment xp;\n    run<EVE_TYPE> (EVE_NAME(cyl_bessel_j0_medium) , xp, eve::cyl_bessel_j0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(cyl_bessel_j0_medium) , xp, eve::cyl_bessel_j0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(stdj0_medium) , xp, stdj0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(boostj0_medium), xp, boostj0 , arg0);\n  }\n  {\n    auto lmin = EVE_VALUE(8);\n    auto lmax = EVE_VALUE(10000);\n\n    auto arg0 = eve::bench::random_<EVE_VALUE>(lmin,lmax);\n    auto stdj0 = [](auto x){return std::cyl_bessel_j(0, x);};\n    auto boostj0= [](auto x){return boost::math::detail::bessel_j0(x);};\n    eve::bench::experiment xp;\n    run<EVE_TYPE> (EVE_NAME(cyl_bessel_j0_large) , xp, eve::cyl_bessel_j0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(cyl_bessel_j0_large) , xp, eve::cyl_bessel_j0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(stdj0_large) , xp, stdj0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(boostj0_large), xp, boostj0 , arg0);\n  }\n  {\n    auto lmin = EVE_VALUE(0);\n    auto lmax = EVE_VALUE(11);\n\n    auto arg0 = eve::bench::random_<EVE_VALUE>(lmin,lmax);\n    auto stdj0 = [](auto x){return std::cyl_bessel_j(0, x);};\n    auto boostj0= [](auto x){return boost::math::detail::bessel_j0(x);};\n    eve::bench::experiment xp;\n    run<EVE_TYPE> (EVE_NAME(cyl_bessel_j0_mixed) , xp, eve::cyl_bessel_j0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(cyl_bessel_j0_mixed) , xp, eve::cyl_bessel_j0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(stdj0_mixed) , xp, stdj0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(boostj0_mixed), xp, boostj0 , arg0);\n  }\n}\n", "meta": {"hexsha": "f4bc3dde0696f0e314069b52c1c644b00547e638", "size": 2876, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmarks/module/bessel/cyl_bessel_j0/regular/cyl_bessel_j0.hpp", "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": "benchmarks/module/bessel/cyl_bessel_j0/regular/cyl_bessel_j0.hpp", "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": "benchmarks/module/bessel/cyl_bessel_j0/regular/cyl_bessel_j0.hpp", "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": 41.6811594203, "max_line_length": 100, "alphanum_fraction": 0.6230876217, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5442258107868282}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_QR_R_HPP\n#define STAN_MATH_PRIM_MAT_FUN_QR_R_HPP\n\n#include <stan/math/prim/arr/err/check_nonzero_size.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/scal/err/check_greater_or_equal.hpp>\n#include <Eigen/QR>\n\nnamespace stan {\n  namespace math {\n\n    template <typename T>\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>\n    qr_R(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& m) {\n      typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> matrix_t;\n      check_nonzero_size(\"qr_R\", \"m\", m);\n      check_greater_or_equal(\"qr_R\",\n                             \"m.rows()\",\n                             static_cast<size_t>(m.rows()),\n                             static_cast<size_t>(m.cols()));\n      Eigen::HouseholderQR<matrix_t> qr(m.rows(), m.cols());\n      qr.compute(m);\n      matrix_t R = qr.matrixQR();\n      if (m.rows() > m.cols())\n        R.bottomRows(m.rows() - m.cols()).setZero();\n      for (int i = 0; i < R.cols(); i++) {\n        for (int j = 0; j < i; j++)\n          R.coeffRef(i, j) = 0.0;\n        if (R(i, i) < 0)\n          R.row(i) *= -1.0;\n      }\n      return R;\n    }\n  }\n}\n#endif\n", "meta": {"hexsha": "c447f02be46e5b05d9226d68bbefca5c7fb48b4b", "size": 1174, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/qr_R.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/qr_R.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/qr_R.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7297297297, "max_line_length": 72, "alphanum_fraction": 0.5655877342, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.544225805018931}}
{"text": "/*\n * Copyright 2019 \u00a9 Centre Interdisciplinaire de d\u00e9veloppement en Cartographie des Oc\u00e9ans (CIDCO), Tous droits r\u00e9serv\u00e9s\n */\n\n/* \n * File:   SideScanGeoreferencing.hpp\n * Author: Jordan McManus <jordan.mcmanus@cidco.ca>\n *\n * Created on March 11, 2020, 12:40 PM\n */\n\n#ifndef SIDESCANGEOREFERENCING_HPP\n#define SIDESCANGEOREFERENCING_HPP\n\n#include <Eigen/Dense>\n#include \"../Position.hpp\"\n#include \"../math/CoordinateTransform.hpp\"\n\nclass SideScanGeoreferencing {\npublic:\n\n    static void georeferenceSideScanEcef(\n            Eigen::Vector3d & antennaEcef,\n            Eigen::Vector3d & antenna2TowPointLeverArmEcef,\n            Eigen::Vector3d & layBackEcef,\n            Eigen::Vector3d & sideDistanceEcef,\n            Position & georeferencedPosition\n            ) {\n\n        Eigen::Vector3d objectPositionEcef =\n                antennaEcef +\n                antenna2TowPointLeverArmEcef +\n                layBackEcef +\n                sideDistanceEcef;\n\n        CoordinateTransform::convertECEFToLongitudeLatitudeElevation(objectPositionEcef, georeferencedPosition);\n    }\n};\n\n#endif /* SIDESCANGEOREFERENCING_HPP */\n\n", "meta": {"hexsha": "be107f0c668af2422558156272cfd817e92c9fb3", "size": 1123, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/sidescan/SideScanGeoreferencing.hpp", "max_stars_repo_name": "JordanMcManus/MBES-lib", "max_stars_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T14:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T06:44:37.000Z", "max_issues_repo_path": "src/sidescan/SideScanGeoreferencing.hpp", "max_issues_repo_name": "JordanMcManus/MBES-lib", "max_issues_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2019-04-16T13:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T19:44:23.000Z", "max_forks_repo_path": "src/sidescan/SideScanGeoreferencing.hpp", "max_forks_repo_name": "JordanMcManus/MBES-lib", "max_forks_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-04-10T19:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T21:42:22.000Z", "avg_line_length": 26.7380952381, "max_line_length": 119, "alphanum_fraction": 0.679430098, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5442258050189309}}
{"text": "// build in NTL src/ folder\n//g++ -I../include -I.  -g -O2 -std=c++11 -pthread -march=native  -o myLLLtest myLLLtest.cpp ntl.a  -lgmp    -lm #LSTAT\n\n\n#include <NTL/LLL.h>\n\nNTL_CLIENT\n\nint main()\n{\n    mat_ZZ B;\n\n    cin >> B;\n\n    ZZ d;\n\n    LLL(d, B, 90, 100);\n\n    cout << \"det = \" << d << endl;\n    cout << \"B = \" << B << endl;\n    cout << \"Finished\" << endl;\n}\n", "meta": {"hexsha": "07b488e8f50dc854cf08a87e00442783e39a0e70", "size": 365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lll_lattice_basis_reduction/myLLLtest.cpp", "max_stars_repo_name": "timcardenuto/cryptology", "max_stars_repo_head_hexsha": "d12825b7eabf2f8a0b1bb4590675aeb4705e3b74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T03:06:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T03:06:21.000Z", "max_issues_repo_path": "lll_lattice_basis_reduction/myLLLtest.cpp", "max_issues_repo_name": "timcardenuto/cryptology", "max_issues_repo_head_hexsha": "d12825b7eabf2f8a0b1bb4590675aeb4705e3b74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lll_lattice_basis_reduction/myLLLtest.cpp", "max_forks_repo_name": "timcardenuto/cryptology", "max_forks_repo_head_hexsha": "d12825b7eabf2f8a0b1bb4590675aeb4705e3b74", "max_forks_repo_licenses": ["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.8695652174, "max_line_length": 119, "alphanum_fraction": 0.5095890411, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5442258047343715}}
{"text": "#define BOOST_TEST_MODULE \"test_gaussian_potential\"\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 <test/util/check_potential.hpp>\n#include <mjolnir/forcefield/local/GaussianPotential.hpp>\n\nBOOST_AUTO_TEST_CASE(Gaussian_double)\n{\n    using real_type = double;\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 1e-6;\n    constexpr real_type tol = 1e-6;\n    const real_type e  = 2.0;\n    const real_type w  = 0.15;\n    const real_type r0 = 7.0;\n\n    mjolnir::GaussianPotential<real_type> gaussian(e, w, r0);\n\n    const real_type x_min = r0 - 5.0 * w;\n    const real_type x_max = r0 + 5.0 * w;\n\n    mjolnir::test::check_potential(gaussian, x_min, x_max, tol, h, N);\n}\n\nBOOST_AUTO_TEST_CASE(Gaussian_float)\n{\n    using real_type = float;\n    constexpr std::size_t N = 100;\n    constexpr real_type   h = 1e-3f;\n    constexpr real_type tol = 1e-3f;\n    const real_type e  = 2.0;\n    const real_type w  = 0.15;\n    const real_type r0 = 7.0;\n\n    mjolnir::GaussianPotential<real_type> gaussian(e, w, r0);\n\n    const real_type x_min = r0 - 5.0f * w;\n    const real_type x_max = r0 + 5.0f * w;\n    mjolnir::test::check_potential(gaussian, x_min, x_max, tol, h, N);\n}\n\nBOOST_AUTO_TEST_CASE(Gaussian_cutoff_double)\n{\n    using real_type = double;\n    constexpr real_type   h = 1e-6;\n\n    {\n        const real_type e  = 2.0;\n        const real_type w  = 0.15;\n        const real_type r0 = 7.0;\n\n        mjolnir::GaussianPotential<real_type> gaussian(e, w, r0);\n\n        const auto rc = gaussian.cutoff();\n\n        BOOST_TEST(std::isfinite(rc));\n        BOOST_TEST(std::abs(gaussian.potential(rc)) ==\n                   mjolnir::math::abs_tolerance<real_type>(),\n                   boost::test_tools::tolerance(h));\n    }\n    {\n        const real_type e  = -2.0;\n        const real_type w  = 0.15;\n        const real_type r0 = 7.0;\n\n        mjolnir::GaussianPotential<real_type> gaussian(e, w, r0);\n\n        const auto rc = gaussian.cutoff();\n\n        BOOST_TEST(std::isfinite(rc));\n        BOOST_TEST(std::abs(gaussian.potential(rc)) ==\n                   mjolnir::math::abs_tolerance<real_type>(),\n                   boost::test_tools::tolerance(h));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Gaussian_cutoff_float)\n{\n    using real_type = float;\n    constexpr real_type   h = 1e-3;\n\n    {\n        const real_type e  = 2.0;\n        const real_type w  = 0.15;\n        const real_type r0 = 7.0;\n\n        mjolnir::GaussianPotential<real_type> gaussian(e, w, r0);\n\n        const auto rc = gaussian.cutoff();\n\n        BOOST_TEST(std::isfinite(rc));\n        BOOST_TEST(gaussian.potential(rc) ==\n                   mjolnir::math::abs_tolerance<real_type>(),\n                   boost::test_tools::tolerance(h));\n    }\n    {\n        const real_type e  = -2.0;\n        const real_type w  = 0.15;\n        const real_type r0 = 7.0;\n\n        mjolnir::GaussianPotential<real_type> gaussian(e, w, r0);\n\n        const auto rc = gaussian.cutoff();\n\n        BOOST_TEST(std::isfinite(rc));\n        BOOST_TEST(std::abs(gaussian.potential(rc)) ==\n                   mjolnir::math::abs_tolerance<real_type>(),\n                   boost::test_tools::tolerance(h));\n    }\n}\n", "meta": {"hexsha": "92a19f2628c36bb39fd032f6f7f4d899e55dc831", "size": 3226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_gaussian_potential.cpp", "max_stars_repo_name": "ToruNiina/Mjolnir", "max_stars_repo_head_hexsha": "44435dd3afc12f5c8ea27a66d7ab282df3e588ff", "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_gaussian_potential.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_gaussian_potential.cpp", "max_forks_repo_name": "Mjolnir-MD/Mjolnir", "max_forks_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "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": 27.8103448276, "max_line_length": 70, "alphanum_fraction": 0.6137631742, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5442257995355929}}
{"text": "/**\n * MULTIDRONE Project:\n *\n * Geographic to Cartesian coordinate conversion and vice versa, with an intermediate conversion to UTM.\n *\n * This library suppose that the path of the robot cannot cross more than 2 different UTM zones.\n *\n */\n\n#ifndef GEOGRAPHIC_TO_CARTESIAN\n#define GEOGRAPHIC_TO_CARTESIAN\n\n#include <math.h>\n#include <algorithm>\n#include <stdlib.h>\n#include <geometry_msgs/Point32.h>\n#include <geographic_msgs/GeoPoint.h>\n\n#include <geodesy/utm.h>                // IMPORTANT TO INSTALL GEODESY: sudo apt-get install ros-kinetic-geographic-info\n\n// #define USING_IN_PYTHON\n\n// #ifdef USING_IN_PYTHON\n// #include <boost/python.hpp>\n// #endif\n\nnamespace multidrone {\n\ninline geometry_msgs::Point32 geographic_to_cartesian (const geographic_msgs::GeoPoint& _actual_coordinate_geo, const geographic_msgs::GeoPoint& _origin_geo) {\n\n    geodesy::UTMPoint actual_coordinate_UTM(_actual_coordinate_geo); // Conversion from geographic coordinates to UTM.\n    geodesy::UTMPoint origin_UTM(_origin_geo);                       // Conversion from geographic coordinates to UTM.\n\n    geometry_msgs::Point32 actual_coordinate_cartesian;              // Cartesian coordinate that this function will return.\n\n    // The problem with UTM is that if there are coordinates in more than one zone, it's difficult to merge the coordinates of the different zones.\n    // This is because each zone has 6 degrees of longitude, and the width in meters of the zone is variable from equator to the poles.\n    // Something similar when the coordinates are in different hemispheres, separated by the equator. Each hemisphere has a different origin for the y axis.\n    // These are the reasons why the x and y assignation for the Cartesian conversion isn't a simple UTM substraction.\n\n    // Assignating \"actual_coordinate_cartesian.x\" is tricky when the actual coordinate and the origin of the Cartesian coordinates are on different zones.\n    if ( int(actual_coordinate_UTM.zone)==60 && origin_UTM.zone==1 ) {         // Coordinate and origin separated by the +-180\u00ba longitude\n        geographic_msgs::GeoPoint geo_180_w;\n        geographic_msgs::GeoPoint geo_180_e;\n        geo_180_w.longitude = 179.9999999;\n        geo_180_w.latitude = _actual_coordinate_geo.latitude;\n        geo_180_w.altitude = _actual_coordinate_geo.altitude;\n        geo_180_e.longitude = -179.9999999;\n        geo_180_e.latitude = _actual_coordinate_geo.latitude;\n        geo_180_e.altitude = _actual_coordinate_geo.altitude;\n        geodesy::UTMPoint utm_180_w(geo_180_w);\n        geodesy::UTMPoint utm_180_e(geo_180_e);\n        actual_coordinate_cartesian.x = actual_coordinate_UTM.easting - utm_180_w.easting + utm_180_e.easting - origin_UTM.easting; // Transformation of the x coordinate taking into account the different zones. \" - utm_180_w.easting + utm_180_e.easting \" computes the x step in both sides of the border longitude.\n    } else if ( origin_UTM.zone==60 && int(actual_coordinate_UTM.zone)==1 ) {  // Coordinate and origin separated by the +-180\u00ba longitude\n        geographic_msgs::GeoPoint geo_180_w;\n        geographic_msgs::GeoPoint geo_180_e;\n        geo_180_w.longitude = 179.9999999;\n        geo_180_w.latitude = _actual_coordinate_geo.latitude;\n        geo_180_w.altitude = _actual_coordinate_geo.altitude;\n        geo_180_e.longitude = -179.9999999;\n        geo_180_e.latitude = _actual_coordinate_geo.latitude;\n        geo_180_e.altitude = _actual_coordinate_geo.altitude;\n        geodesy::UTMPoint utm_180_w(geo_180_w);\n        geodesy::UTMPoint utm_180_e(geo_180_e);\n        actual_coordinate_cartesian.x = actual_coordinate_UTM.easting - utm_180_e.easting + utm_180_w.easting - origin_UTM.easting; // Transformation of the x coordinate taking into account the different zones. \" - utm_180_w.easting + utm_180_e.easting \" computes the x step in both sides of the border longitude.\n    } else if ( int(actual_coordinate_UTM.zone) < origin_UTM.zone ) {\n        int quotient_from_int_division = (int) ( std::max(std::abs(_actual_coordinate_geo.longitude),std::abs(_origin_geo.longitude))/6 );                    // int division of the max longitude (absolute, without sign)\n        double border_longitude = quotient_from_int_division * 6.0 *pow(-1,std::signbit(std::max(_actual_coordinate_geo.longitude,_origin_geo.longitude)));   // border_longitude = quotient_from_int_division * 6 *(-1)^(1 if negative longitude, 0 if positive)\n        geographic_msgs::GeoPoint geo_w;\n        geographic_msgs::GeoPoint geo_e;\n        geo_w.longitude = border_longitude - 0.0000001;\n        geo_w.latitude = _actual_coordinate_geo.latitude;\n        geo_w.altitude = _actual_coordinate_geo.altitude;\n        geo_e.longitude = border_longitude + 0.0000001;\n        geo_e.latitude = _actual_coordinate_geo.latitude;\n        geo_e.altitude = _actual_coordinate_geo.altitude;\n        geodesy::UTMPoint utm_w(geo_w);\n        geodesy::UTMPoint utm_e(geo_e);\n        actual_coordinate_cartesian.x = actual_coordinate_UTM.easting - utm_w.easting + utm_e.easting - origin_UTM.easting;         // Transformation of the x coordinate taking into account the different zones. \" - utm_w.easting + utm_e.easting \" computes the x step in both sides of the border longitude.\n    } else if ( origin_UTM.zone < int(actual_coordinate_UTM.zone) ) {\n        int quotient_from_int_division = (int) ( std::max(std::abs(_actual_coordinate_geo.longitude),std::abs(_origin_geo.longitude))/6 );                    // int division of the max longitude (absolute, without sign)\n        double border_longitude = quotient_from_int_division * 6.0 *pow(-1,std::signbit(std::max(_actual_coordinate_geo.longitude,_origin_geo.longitude)));   // border_longitude = quotient_from_int_division * 6 *(-1)^(1 if negative longitude, 0 if positive)\n        geographic_msgs::GeoPoint geo_w;\n        geographic_msgs::GeoPoint geo_e;\n        geo_w.longitude = border_longitude - 0.0000001;\n        geo_w.latitude = _actual_coordinate_geo.latitude;\n        geo_w.altitude = _actual_coordinate_geo.altitude;\n        geo_e.longitude = border_longitude + 0.0000001;\n        geo_e.latitude = _actual_coordinate_geo.latitude;\n        geo_e.altitude = _actual_coordinate_geo.altitude;\n        geodesy::UTMPoint utm_w(geo_w);\n        geodesy::UTMPoint utm_e(geo_e);\n        actual_coordinate_cartesian.x = actual_coordinate_UTM.easting - utm_e.easting + utm_w.easting - origin_UTM.easting;    // Transformation of the x coordinate taking into account the different zones. \" - utm_w.easting + utm_e.easting \" computes the x step in both sides of the border longitude.\n    } else {\n        // The actual coordinate is in the same zone that the origin (the first station). This is the normal situation, the assigntation of the x axis value is trivial (simple subtraction).\n        actual_coordinate_cartesian.x = actual_coordinate_UTM.easting -origin_UTM.easting;\n    }\n\n    // Assignating \"actual_coordinate_cartesian.y\" is also tricky when the actual coordinate and the origin of the Cartesian coordinates are on different hemispheres:\n    if ( origin_UTM.band=='N' && actual_coordinate_UTM.band=='M' ) {         // Coordinate and origin separated by the 0\u00ba latitude\n        geographic_msgs::GeoPoint geo_0_n;\n        geographic_msgs::GeoPoint geo_0_s;\n        geo_0_n.longitude = _actual_coordinate_geo.longitude;\n        geo_0_n.latitude = 0.0000001;\n        geo_0_n.altitude = _actual_coordinate_geo.altitude;\n        geo_0_s.longitude = _actual_coordinate_geo.longitude;\n        geo_0_s.latitude = -0.0000001;\n        geo_0_s.altitude = _actual_coordinate_geo.altitude;\n        geodesy::UTMPoint utm_0_n(geo_0_n);\n        geodesy::UTMPoint utm_0_s(geo_0_s);\n        actual_coordinate_cartesian.y = actual_coordinate_UTM.northing - utm_0_s.northing + utm_0_n.northing - origin_UTM.northing;    // Transformation of the y coordinate taking into account the different hemispheres. \" - utm_0_s.northing + utm_0_n.northing \" computes the y step in both sides of the equator.\n    } else if ( actual_coordinate_UTM.band=='N' && origin_UTM.band=='M' ) {  // Coordinate and origin separated by the 0\u00ba latitude\n        geographic_msgs::GeoPoint geo_0_n;\n        geographic_msgs::GeoPoint geo_0_s;\n        geo_0_n.longitude = _actual_coordinate_geo.longitude;\n        geo_0_n.latitude = 0.0000001;\n        geo_0_n.altitude = _actual_coordinate_geo.altitude;\n        geo_0_s.longitude = _actual_coordinate_geo.longitude;\n        geo_0_s.latitude = -0.0000001;\n        geo_0_s.altitude = _actual_coordinate_geo.altitude;\n        geodesy::UTMPoint utm_0_n(geo_0_n);\n        geodesy::UTMPoint utm_0_s(geo_0_s);\n        actual_coordinate_cartesian.y = actual_coordinate_UTM.northing - utm_0_n.northing + utm_0_s.northing - origin_UTM.northing;    // Transformation of the y coordinate taking into account the different hemispheres. \" - utm_0_n.northing + utm_0_s.northing \" computes the y step in both sides of the equator.\n    } else {\n        // The actual coordinate is in the same hemisphere that the origin (the first station). This is the normal situation, the assigntation of the y axis value is trivial (simple subtraction).\n        actual_coordinate_cartesian.y = actual_coordinate_UTM.northing-origin_UTM.northing;\n    }\n\n    // Assignating \"actual_coordinate_cartesian.z\" is trivial always, simple subtraction.\n    actual_coordinate_cartesian.z = actual_coordinate_UTM.altitude-origin_UTM.altitude;\n\n    return actual_coordinate_cartesian;\n}   // end geographic_to_cartesian\n\n\n\ninline geographic_msgs::GeoPoint cartesian_to_geographic (const geometry_msgs::Point32& _actual_coordinate_cartesian, const geographic_msgs::GeoPoint& _origin_geo) {\n    geodesy::UTMPoint actual_coordinate_aux(_origin_geo);                                               // Conversion from geographic coordinates to UTM.\n\n    actual_coordinate_aux.easting  += _actual_coordinate_cartesian.x;\n    actual_coordinate_aux.northing += _actual_coordinate_cartesian.y;\n    actual_coordinate_aux.altitude += _actual_coordinate_cartesian.z;\n\n    // Convert to geographic coordinates and return the coordinate. This conversion is easier as it doesn't matter if the points are in different zones or hemispheres, but in that case the error increases if the points are very far from each other.\n    return geodesy::toMsg (actual_coordinate_aux);\n\n}   // end cartesian_to_geographic\n\n\n\n// #ifdef USING_IN_PYTHON\n// BOOST_PYTHON_MODULE(geographic_to_cartesian_and_vice_verse) {\n//     using namespace boost::python;\n//     def(\"geographic_to_cartesian\", geographic_to_cartesian);\n//     def(\"cartesian_to_geographic\", cartesian_to_geographic);\n// }\n// #endif\n\n}   // end namespace multidrone\n\n#endif // GEOGRAPHIC_TO_CARTESIAN", "meta": {"hexsha": "5e6f3082b05ef40505cc3d1ddc8961c2d4d021e3", "size": 10707, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "multidrone_kml_parser/include/multidrone_kml_parser/geographic_to_cartesian.hpp", "max_stars_repo_name": "grvcTeam/multidrone_planning", "max_stars_repo_head_hexsha": "421a7d81a3417cdc6bcb690d3d88bb4e9d6b6638", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T07:00:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T07:59:41.000Z", "max_issues_repo_path": "multidrone_kml_parser/include/multidrone_kml_parser/geographic_to_cartesian.hpp", "max_issues_repo_name": "grvcTeam/multidrone_planning", "max_issues_repo_head_hexsha": "421a7d81a3417cdc6bcb690d3d88bb4e9d6b6638", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multidrone_kml_parser/include/multidrone_kml_parser/geographic_to_cartesian.hpp", "max_forks_repo_name": "grvcTeam/multidrone_planning", "max_forks_repo_head_hexsha": "421a7d81a3417cdc6bcb690d3d88bb4e9d6b6638", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-01T06:35:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-24T09:54:21.000Z", "avg_line_length": 66.5031055901, "max_line_length": 313, "alphanum_fraction": 0.7404501728, "num_tokens": 2607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5442257767485624}}
{"text": "#include <iostream>\n#include <cmath>\n\nusing ::std::string;\n\n#include <vector>\n\nusing ::std::vector;\n\n#include <pcl/point_types.h>\n#include <pcl/common/centroid.h>\n#include <pcl/common/transforms.h>\n#include <pcl/io/ply_io.h>\n#include <pcl/visualization/cloud_viewer.h>\n\nusing ::pcl::PointCloud;\nusing ::pcl::PointXYZ;\nusing ::pcl::computeCentroid;\nusing ::pcl::transformPointCloud;\nusing ::pcl::io::loadPLYFile;\nusing ::pcl::visualization::CloudViewer;\n\n#include <Eigen/Dense>\n\nusing ::Eigen::Matrix4d;\n\n#include \"my_point_cloud.hpp\"\n\n#define PI 3.14159265\n\nMyPCL::MyPointCloud::MyPointCloud(string path) {\n    int pcl_load_status;\n\n    cloud.reset(new PointCloud<PointXYZ>());\n    pcl_load_status = loadPLYFile(path, *cloud);\n\n    if (pcl_load_status == -1) {\n        PCL_ERROR(\"Reading error!\\n\");\n        exit(pcl_load_status);\n    }\n}\n\nMyPCL::MyPointCloud::~MyPointCloud() {}\n\nvoid MyPCL::MyPointCloud::view() {\n    CloudViewer viewer(\"My PointCloud viewer\");\n\n    viewer.showCloud(cloud);\n    while (!viewer.wasStopped()) {} // Busy waiting\n}\n\nPointXYZ MyPCL::MyPointCloud::centroid() {\n    size_t centroid_dimension;\n    PointXYZ centroid;\n\n    centroid_dimension = computeCentroid(*cloud, centroid);\n\n    if (centroid_dimension < 3)\n        exit(-1);\n\n    return centroid;\n}\n\nvoid MyPCL::MyPointCloud::apply_offset(PointXYZ offset) {\n    apply_transformation(offset, PointXYZ(1, 1, 1), PointXYZ(0, 0, 0));\n}\n\nvoid MyPCL::MyPointCloud::apply_scale(double x_s, double y_s, double z_s) {\n    apply_transformation(PointXYZ(0, 0, 0), PointXYZ(x_s, y_s, z_s), PointXYZ(0, 0, 0));\n}\n\nvoid MyPCL::MyPointCloud::apply_scale(double scale) {\n    apply_scale(scale, scale, scale);\n}\n\nvoid MyPCL::MyPointCloud::apply_rotation(double x_r, double y_r, double z_r) {\n    apply_transformation(PointXYZ(0, 0, 0), PointXYZ(1, 1, 1), PointXYZ(x_r, y_r, z_r));\n}\n\nvoid MyPCL::MyPointCloud::apply_transformation(PointXYZ offset, PointXYZ scale, PointXYZ rotation) {\n    Matrix4d m_x, m_y, m_z;\n    m_x = Matrix4d::Identity();\n    m_y = Matrix4d::Identity();\n    m_z = Matrix4d::Identity();\n\n    auto to_rad = [] (double degree) {\n        return degree / 180 * PI;\n    };\n\n    double rad_x, rad_y, rad_z;\n    rad_x = to_rad(rotation.x);\n    rad_y = to_rad(rotation.y);\n    rad_z = to_rad(rotation.z);\n\n    m_x(1, 1) = cos(rad_x);\n    m_x(1, 2) = -sin(rad_x);\n    m_x(2, 1) = sin(rad_x);\n    m_x(2, 2) = cos(rad_x);\n\n    m_y(0, 0) = cos(rad_y);\n    m_y(2, 0) = sin(rad_y);\n    m_y(0, 2) = -sin(rad_y);\n    m_y(2, 2) = cos(rad_y);\n\n    m_z(0, 0) = cos(rad_z);\n    m_z(0, 1) = -sin(rad_z);\n    m_z(1, 0) = sin(rad_z);\n    m_z(1, 1) = cos(rad_z);\n\n    Matrix4d m_rotation;\n    m_rotation = m_x * m_y * m_z;\n\n    Matrix4d m_scale;\n    m_scale = Matrix4d::Identity();\n\n    // Setting the scaling matrix\n    /* \n     * x_s 0   0   0\n     * 0   y_s 0   0\n     * 0   0   z_s 0\n     * 0   0   0   1\n     */\n\n    m_scale(0, 0) = scale.x;\n    m_scale(1, 1) = scale.y;\n    m_scale(2, 2) = scale.z;\n\n    Matrix4d m_translation;\n    m_translation = Matrix4d::Identity();\n\n    // Setting the translation matrix\n    /* \n     * 1 0 0 x\n     * 0 1 0 y\n     * 0 0 1 z\n     * 0 0 0 1\n     */\n    m_translation(0, 3) = offset.x;\n    m_translation(1, 3) = offset.y;\n    m_translation(2, 3) = offset.z;\n\n    PointCloud<PointXYZ>::Ptr transformed;\n    transformed.reset(new PointCloud<PointXYZ>());\n\n    Matrix4d m_transform;\n    m_transform = m_scale * m_rotation * m_translation;\n\n    transformPointCloud(*cloud, *transformed, m_transform);\n    cloud = transformed;\n}", "meta": {"hexsha": "e6edd901a4eace4ce141ed64c5cc481400bbc743", "size": 3528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "003_transforming_cloud/src/my_point_cloud.cpp", "max_stars_repo_name": "jorgeuliana1/learning-pcl", "max_stars_repo_head_hexsha": "9744474b0d7b9c5d968a5f8a59b4a23a595ef6bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "003_transforming_cloud/src/my_point_cloud.cpp", "max_issues_repo_name": "jorgeuliana1/learning-pcl", "max_issues_repo_head_hexsha": "9744474b0d7b9c5d968a5f8a59b4a23a595ef6bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "003_transforming_cloud/src/my_point_cloud.cpp", "max_forks_repo_name": "jorgeuliana1/learning-pcl", "max_forks_repo_head_hexsha": "9744474b0d7b9c5d968a5f8a59b4a23a595ef6bb", "max_forks_repo_licenses": ["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.52, "max_line_length": 100, "alphanum_fraction": 0.6360544218, "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5442257712652245}}
{"text": "//\n// Copyright (c) 2016-2020 CNRS INRIA\n//\n\n#include \"pinocchio/algorithm/energy.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/center-of-mass.hpp\"\n\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE(test_kinetic_energy)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  pinocchio::Data data(model);\n  \n  const VectorXd qmax = VectorXd::Ones(model.nq);\n  VectorXd q = randomConfiguration(model,-qmax,qmax);\n  VectorXd v = VectorXd::Ones(model.nv);\n\n  data.M.fill(0);  crba(model,data,q);\n  data.M.triangularView<Eigen::StrictlyLower>()\n  = data.M.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  double kinetic_energy_ref = 0.5 * v.transpose() * data.M * v;\n  double kinetic_energy = computeKineticEnergy(model, data, q, v);\n  \n  BOOST_CHECK_SMALL(kinetic_energy_ref - kinetic_energy, 1e-12);\n}\n\nBOOST_AUTO_TEST_CASE(test_potential_energy)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  pinocchio::Data data(model), data_ref(model);\n  \n  const VectorXd qmax = VectorXd::Ones(model.nq);\n  VectorXd q = randomConfiguration(model,-qmax,qmax);\n  \n  double potential_energy = computePotentialEnergy(model, data, q);\n  centerOfMass(model,data_ref,q);\n  \n  double potential_energy_ref = -data_ref.mass[0] * (data_ref.com[0].dot(model.gravity.linear()));\n  \n  BOOST_CHECK_SMALL(potential_energy_ref - potential_energy, 1e-12);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "680d20a5390f605ac39b267c0f27585c472f45f7", "size": 1805, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/energy.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/energy.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/energy.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": 29.1129032258, "max_line_length": 98, "alphanum_fraction": 0.7540166205, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5442257712652244}}
{"text": "/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http://www.mitk.org for details.\n\n===================================================================*/\n\n#include \"mitkNumericTwoCompartmentExchangeModel.h\"\n#include \"mitkAIFParametrizerHelper.h\"\n#include \"mitkTimeGridHelper.h\"\n#include \"mitkTwoCompartmentExchangeModelDifferentialEquations.h\"\n#include <vnl/algo/vnl_fft_1d.h>\n#include <boost/numeric/odeint.hpp>\n#include <fstream>\n\nconst std::string mitk::NumericTwoCompartmentExchangeModel::MODEL_DISPLAY_NAME =\n  \"Numeric Two Compartment Exchange Model\";\n\nconst std::string mitk::NumericTwoCompartmentExchangeModel::NAME_PARAMETER_F = \"F\";\nconst std::string mitk::NumericTwoCompartmentExchangeModel::NAME_PARAMETER_PS = \"PS\";\nconst std::string mitk::NumericTwoCompartmentExchangeModel::NAME_PARAMETER_ve = \"ve\";\nconst std::string mitk::NumericTwoCompartmentExchangeModel::NAME_PARAMETER_vp = \"vp\";\n\nconst std::string mitk::NumericTwoCompartmentExchangeModel::UNIT_PARAMETER_F = \"ml/min/100ml\";\nconst std::string mitk::NumericTwoCompartmentExchangeModel::UNIT_PARAMETER_PS = \"ml/min/100ml\";\nconst std::string mitk::NumericTwoCompartmentExchangeModel::UNIT_PARAMETER_ve = \"ml/ml\";\nconst std::string mitk::NumericTwoCompartmentExchangeModel::UNIT_PARAMETER_vp = \"ml/ml\";\n\nconst unsigned int mitk::NumericTwoCompartmentExchangeModel::POSITION_PARAMETER_F = 0;\nconst unsigned int mitk::NumericTwoCompartmentExchangeModel::POSITION_PARAMETER_PS = 1;\nconst unsigned int mitk::NumericTwoCompartmentExchangeModel::POSITION_PARAMETER_ve = 2;\nconst unsigned int mitk::NumericTwoCompartmentExchangeModel::POSITION_PARAMETER_vp = 3;\n\nconst unsigned int mitk::NumericTwoCompartmentExchangeModel::NUMBER_OF_PARAMETERS = 4;\n\nconst std::string mitk::NumericTwoCompartmentExchangeModel::NAME_STATIC_PARAMETER_ODEINTStepSize = \"ODEIntStepSize\";\n\n\nstd::string mitk::NumericTwoCompartmentExchangeModel::GetModelDisplayName() const\n{\n  return MODEL_DISPLAY_NAME;\n};\n\nstd::string mitk::NumericTwoCompartmentExchangeModel::GetModelType() const\n{\n  return \"Perfusion.MR\";\n};\n\n\nmitk::NumericTwoCompartmentExchangeModel::NumericTwoCompartmentExchangeModel()\n{\n\n}\n\nmitk::NumericTwoCompartmentExchangeModel::~NumericTwoCompartmentExchangeModel()\n{\n\n}\n\nmitk::NumericTwoCompartmentExchangeModel::ParameterNamesType mitk::NumericTwoCompartmentExchangeModel::GetStaticParameterNames() const\n{\n  ParameterNamesType result;\n\n  result.push_back(NAME_STATIC_PARAMETER_AIF);\n  result.push_back(NAME_STATIC_PARAMETER_AIFTimeGrid);\n  result.push_back(NAME_STATIC_PARAMETER_ODEINTStepSize);\n\n  return result;\n}\n\nmitk::NumericTwoCompartmentExchangeModel::ParametersSizeType  mitk::NumericTwoCompartmentExchangeModel::GetNumberOfStaticParameters()\nconst\n{\n  return 3;\n}\n\n\nvoid mitk::NumericTwoCompartmentExchangeModel::SetStaticParameter(const ParameterNameType& name,\n    const StaticParameterValuesType& values)\n{\n  if (name == NAME_STATIC_PARAMETER_AIF)\n  {\n    AterialInputFunctionType aif = mitk::convertParameterToArray(values);\n\n    SetAterialInputFunctionValues(aif);\n  }\n\n  if (name == NAME_STATIC_PARAMETER_AIFTimeGrid)\n  {\n    TimeGridType timegrid = mitk::convertParameterToArray(values);\n\n    SetAterialInputFunctionTimeGrid(timegrid);\n  }\n\n  if (name == NAME_STATIC_PARAMETER_ODEINTStepSize)\n  {\n      SetODEINTStepSize(values[0]);\n  }\n};\n\nmitk::NumericTwoCompartmentExchangeModel::StaticParameterValuesType mitk::NumericTwoCompartmentExchangeModel::GetStaticParameterValue(\n  const ParameterNameType& name) const\n{\n  StaticParameterValuesType result;\n\n  if (name == NAME_STATIC_PARAMETER_AIF)\n  {\n    result = mitk::convertArrayToParameter(this->m_AterialInputFunctionValues);\n  }\n\n  if (name == NAME_STATIC_PARAMETER_AIFTimeGrid)\n  {\n    result = mitk::convertArrayToParameter(this->m_AterialInputFunctionTimeGrid);\n  }\n  if (name == NAME_STATIC_PARAMETER_ODEINTStepSize)\n  {\n    result.push_back(GetODEINTStepSize());\n  }\n\n  return result;\n};\n\n\nmitk::NumericTwoCompartmentExchangeModel::ParameterNamesType\nmitk::NumericTwoCompartmentExchangeModel::GetParameterNames() const\n{\n  ParameterNamesType result;\n\n  result.push_back(NAME_PARAMETER_F);\n  result.push_back(NAME_PARAMETER_PS);\n  result.push_back(NAME_PARAMETER_ve);\n  result.push_back(NAME_PARAMETER_vp);\n\n  return result;\n}\n\nmitk::NumericTwoCompartmentExchangeModel::ParametersSizeType\nmitk::NumericTwoCompartmentExchangeModel::GetNumberOfParameters() const\n{\n  return NUMBER_OF_PARAMETERS;\n}\n\n\nmitk::NumericTwoCompartmentExchangeModel::ParamterUnitMapType\nmitk::NumericTwoCompartmentExchangeModel::GetParameterUnits() const\n{\n  ParamterUnitMapType result;\n\n  result.insert(std::make_pair(NAME_PARAMETER_F, UNIT_PARAMETER_F));\n  result.insert(std::make_pair(NAME_PARAMETER_PS, UNIT_PARAMETER_PS));\n  result.insert(std::make_pair(NAME_PARAMETER_vp, UNIT_PARAMETER_vp));\n  result.insert(std::make_pair(NAME_PARAMETER_ve, UNIT_PARAMETER_ve));\n\n  return result;\n};\n\nmitk::NumericTwoCompartmentExchangeModel::ModelResultType\nmitk::NumericTwoCompartmentExchangeModel::ComputeModelfunction(const ParametersType& parameters)\nconst\n{\n  typedef itk::Array<double> ConcentrationCurveType;\n  typedef std::vector<double> ConcentrationVectorType;\n\n  if (this->m_TimeGrid.GetSize() == 0)\n  {\n    itkExceptionMacro(\"No Time Grid Set! Cannot Calculate Signal\");\n  }\n\n  AterialInputFunctionType aterialInputFunction;\n  aterialInputFunction = GetAterialInputFunction(this->m_TimeGrid);\n\n  unsigned int timeSteps = this->m_TimeGrid.GetSize();\n\n  /** @brief Boost::numeric::odeint works with type std::vector<double> thus, aif and grid are converted to ModelParameters( of type std::vector)\n   */\n  mitk::TwoCompartmentExchangeModelDifferentialEquations::AIFType aif = mitk::convertArrayToParameter(\n        aterialInputFunction);\n  mitk::TwoCompartmentExchangeModelDifferentialEquations::AIFType grid =\n    mitk::convertArrayToParameter(m_TimeGrid);\n\n  mitk::TwoCompartmentExchangeModelDifferentialEquations::AIFType aifODE = aif;\n  aifODE.push_back(aif[timeSteps - 1]);\n  mitk::TwoCompartmentExchangeModelDifferentialEquations::AIFType gridODE = grid;\n  gridODE.push_back(grid[timeSteps - 1] + (grid[timeSteps - 1] - grid[timeSteps - 2]));\n\n\n\n  //Model Parameters\n  double F = (double) parameters[POSITION_PARAMETER_F] / 6000.0;\n  double PS  = (double) parameters[POSITION_PARAMETER_PS] / 6000.0;\n  double ve = (double) parameters[POSITION_PARAMETER_ve];\n  double vp = (double) parameters[POSITION_PARAMETER_vp];\n\n\n  /** @brief Initialize class TwoCompartmentExchangeModelDifferentialEquations defining the differential equations. AIF and Grid must be set so that at step t the aterial Concentration Ca(t) can be interpolated from AIF*/\n  mitk::TwoCompartmentExchangeModelDifferentialEquations ode;\n  ode.initialize(F, PS, ve, vp);\n  ode.setAIF(aifODE);\n  ode.setAIFTimeGrid(gridODE);\n\n  state_type x(2);\n  x[0] = 0.0;\n  x[1] = 0.0;\n  typedef boost::numeric::odeint::runge_kutta_cash_karp54<state_type> error_stepper_type;\n  //typedef boost::numeric::odeint::runge_kutta4< state_type > stepper_type;\n\n  /** @brief Results of odeeint x[0] and x[1]*/\n  ConcentrationVectorType Cp;\n  ConcentrationVectorType Ce;\n  ConcentrationVectorType odeTimeGrid;\n\n  error_stepper_type stepper;\n\n\n  /** @brief Stepsize. Should be adapted by stepper (runge_kutta_cash_karp54) */\n//  const double dt = 0.05;\n   const double dt = this->m_ODEINTStepSize;\n\n\n  /** @brief perform Step t -> t+dt to calculate approximate value x(t+dt)*/\n  for (double t = 0.0; t < this->m_TimeGrid(this->m_TimeGrid.GetSize() - 1) - 2*dt; t += dt)\n  {\n    stepper.do_step(ode, x, t, dt);\n    Cp.push_back(x[0]);\n    Ce.push_back(x[1]);\n    odeTimeGrid.push_back(t);\n  }\n\n  /** @brief transfom result of Differential equations back to itk::Array and interpolate to m_TimeGrid (they are calculated on a different grid defined by stepsize of odeint)*/\n  ConcentrationCurveType plasmaConcentration = mitk::convertParameterToArray(Cp);\n  ConcentrationCurveType EESConcentration = mitk::convertParameterToArray(Ce);\n  ConcentrationCurveType rungeKuttaTimeGrid = mitk::convertParameterToArray(odeTimeGrid);\n\n  mitk::ModelBase::ModelResultType C_Plasma = mitk::InterpolateSignalToNewTimeGrid(plasmaConcentration, rungeKuttaTimeGrid, m_TimeGrid);\n  mitk::ModelBase::ModelResultType C_EES = mitk::InterpolateSignalToNewTimeGrid(EESConcentration, rungeKuttaTimeGrid, m_TimeGrid);\n\n\n  //Signal that will be returned by ComputeModelFunction\n  mitk::ModelBase::ModelResultType signal(timeSteps);\n  signal.fill(0.0);\n\n  mitk::ModelBase::ModelResultType::iterator signalPos = signal.begin();\n  mitk::ModelBase::ModelResultType::const_iterator CePos = C_EES.begin();\n\n  mitk::ModelBase::ModelResultType::const_iterator t = this->m_TimeGrid.begin();\n  mitk::ModelBase::ModelResultType::const_iterator Cin = aterialInputFunction.begin();\n\n\n\n  for (mitk::ModelBase::ModelResultType::const_iterator CpPos = C_Plasma.begin();\n       CpPos != C_Plasma.end(); ++CpPos, ++CePos, ++signalPos, ++t, ++Cin)\n  {\n    *signalPos = vp * (*CpPos) + ve * (*CePos);\n\n  }\n\n  return signal;\n\n}\n\n\n\n\nitk::LightObject::Pointer mitk::NumericTwoCompartmentExchangeModel::InternalClone() const\n{\n  NumericTwoCompartmentExchangeModel::Pointer newClone = NumericTwoCompartmentExchangeModel::New();\n\n  newClone->SetTimeGrid(this->m_TimeGrid);\n\n  return newClone.GetPointer();\n}\n\nvoid mitk::NumericTwoCompartmentExchangeModel::PrintSelf(std::ostream& os,\n    ::itk::Indent indent) const\n{\n  Superclass::PrintSelf(os, indent);\n\n\n}\n\n\n", "meta": {"hexsha": "8d6fe166224fd6a90791d9f2beeb1ac24bd1ad7d", "size": 9804, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/Pharmacokinetics/src/Models/mitkNumericTwoCompartmentExchangeModel.cpp", "max_stars_repo_name": "wyyrepo/MITK", "max_stars_repo_head_hexsha": "d0837f3d0d44f477b888ec498e9a2ed407e79f20", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-20T08:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T08:19:27.000Z", "max_issues_repo_path": "Modules/Pharmacokinetics/src/Models/mitkNumericTwoCompartmentExchangeModel.cpp", "max_issues_repo_name": "wyyrepo/MITK", "max_issues_repo_head_hexsha": "d0837f3d0d44f477b888ec498e9a2ed407e79f20", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/Pharmacokinetics/src/Models/mitkNumericTwoCompartmentExchangeModel.cpp", "max_forks_repo_name": "wyyrepo/MITK", "max_forks_repo_head_hexsha": "d0837f3d0d44f477b888ec498e9a2ed407e79f20", "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.6907216495, "max_line_length": 221, "alphanum_fraction": 0.7781517748, "num_tokens": 2467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.544196266558802}}
{"text": "#include <stan/math/mix/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/hypot.hpp>\n#include <test/unit/math/rev/scal/fun/util.hpp>\n#include <test/unit/math/mix/scal/fun/nan_util.hpp>\n\n\n\nTEST(AgradFwdHypot,FvarVar_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  fvar<var> x(3.0,1.3);\n\n  fvar<var> z(6.0,1.0);\n  fvar<var> a = hypot(x,z);\n\n  EXPECT_FLOAT_EQ(hypot(3.0,6.0), a.val_.val());\n  EXPECT_FLOAT_EQ((1.3 * 3.0 + 6.0 * 1.0) / hypot(3.0, 6.0), a.d_.val());\n\n  AVEC y = createAVEC(x.val_,z.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0,6.0),g[0]);\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0,6.0),g[1]);\n}\nTEST(AgradFwdHypot,FvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  fvar<var> x(3.0,1.3);\n  double z(6.0);\n  fvar<var> a = hypot(x,z);\n\n  EXPECT_FLOAT_EQ(hypot(3.0,6.0), a.val_.val());\n  EXPECT_FLOAT_EQ((1.3 * 3.0) / hypot(3.0, 6.0), a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0,6.0),g[0]);\n}\nTEST(AgradFwdHypot,Double_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  double x(3.0);\n  fvar<var> z(6.0,1.0);\n  fvar<var> a = hypot(x,z);\n\n  EXPECT_FLOAT_EQ(hypot(3.0,6.0), a.val_.val());\n  EXPECT_FLOAT_EQ((6.0 * 1.0) / hypot(3.0, 6.0), a.d_.val());\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0,6.0),g[0]);\n}\nTEST(AgradFwdHypot,FvarVar_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  fvar<var> x(3.0,1.3);\n  fvar<var> z(6.0,1.0);\n  fvar<var> a = hypot(x,z);\n\n  AVEC y = createAVEC(x.val_,z.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ((1.3 * 6.0 * 6.0 - 6.0 * 3.0) \n                  / hypot(3.0,6.0) / (9.0 + 36.0),g[0]);\n  EXPECT_FLOAT_EQ((1.0 * 3.0 * 3.0 - 1.3 * 6.0 * 3.0) \n                  / hypot(3.0,6.0) / (9.0 + 36.0),g[1]);\n}\nTEST(AgradFwdHypot,FvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  fvar<var> x(3.0,1.3);\n  double z(6.0);\n  fvar<var> a = hypot(x,z);\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(1.3 * 6.0 * 6.0 / hypot(3.0,6.0) / (9.0 + 36.0),g[0]);\n}\nTEST(AgradFwdHypot,Double_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  double x(3.0);\n  fvar<var> z(6.0,1.0);\n  fvar<var> a = hypot(x,z);\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(1.0 * 3.0 * 3.0 / hypot(3.0,6.0) / (9.0 + 36.0),g[0]);\n}\n\n\nTEST(AgradFwdHypot,FvarFvarVar_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x,y);\n\n  EXPECT_FLOAT_EQ(hypot(3.0,6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0,6.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0,6.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.059628479, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0,6.0), g[0]);\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0,6.0), g[1]);\n}\nTEST(AgradFwdHypot,FvarFvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  double y(6.0);\n\n  fvar<fvar<var> > a = hypot(x,y);\n\n  EXPECT_FLOAT_EQ(hypot(3.0,6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0,6.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0,6.0), g[0]);\n}\n\nTEST(AgradFwdHypot,Double_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  double x(3.0);\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x,y);\n\n  EXPECT_FLOAT_EQ(hypot(3.0,6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0,6.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0,6.0), g[0]);\n}\nTEST(AgradFwdHypot,FvarFvarVar_FvarFvarVar_2ndDeriv_x) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x,y);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n\n  EXPECT_FLOAT_EQ(36.0 / hypot(3.0,6.0) / (9.0 + 36.0),g[0]);\n  EXPECT_FLOAT_EQ(-2.0/15.0/std::sqrt(5.0), g[1]);\n}\nTEST(AgradFwdHypot,FvarFvarVar_FvarFvarVar_2ndDeriv_y) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x,y);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(-2.0/15.0/std::sqrt(5.0), g[0]);\n  EXPECT_FLOAT_EQ((3.0 * 3.0) / hypot(3.0,6.0) / (9.0 + 36.0),g[1]);\n}\nTEST(AgradFwdHypot,FvarFvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  double y(6.0);\n\n  fvar<fvar<var> > a = hypot(x,y);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n\n  EXPECT_FLOAT_EQ(6.0 * 6.0 / hypot(3.0,6.0) / (9.0 + 36.0),g[0]);\n}\n\nTEST(AgradFwdHypot,Double_FvarFvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  double x(3.0);\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x,y);\n\n  EXPECT_FLOAT_EQ(hypot(3.0,6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0,6.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ((3.0 * 3.0) / hypot(3.0,6.0) / (9.0 + 36.0),g[0]);\n}\nTEST(AgradFwdHypot,FvarFvarVar_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x,y);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.0079504643, g[0]);\n  EXPECT_FLOAT_EQ(0.013913312,g[1]);\n}\nTEST(AgradFwdHypot,FvarFvarVar_Double_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  x.d_.val_ = 1.0;\n  double y(6.0);\n\n  fvar<fvar<var> > a = hypot(x,y);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n\n  EXPECT_FLOAT_EQ(-0.02385139175999775676169785246647,g[0]);\n}\n\nTEST(AgradFwdHypot,Double_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::hypot;\n\n  double x(3.0);\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n  y.val_.d_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x,y);\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.0119256958799988783808489262332,g[0]);\n}\n\nstruct hypot_fun {\n  template <typename T0, typename T1>\n  inline \n  typename boost::math::tools::promote_args<T0,T1>::type\n  operator()(const T0 arg1,\n             const T1 arg2) const {\n    return hypot(arg1,arg2);\n  }\n};\n\nTEST(AgradFwdHypot, nan) {\n  hypot_fun hypot_;\n  test_nan_mix(hypot_,3.0,5.0,false);\n}\n", "meta": {"hexsha": "5ea1763cc91d9ac850620607e93a7d7bc36d7a88", "size": 7993, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/mix/scal/fun/hypot_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/mix/scal/fun/hypot_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/mix/scal/fun/hypot_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9311377246, "max_line_length": 73, "alphanum_fraction": 0.6184161141, "num_tokens": 3535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5441962662407255}}
{"text": "#define EIGEN_RUNTIME_NO_MALLOC\n#include <Eigen/Core>\n#include <algorithm>\n#include <catch2/catch.hpp>\n#include <vector>\n#include \"ear/dsp/gain_interpolator.hpp\"\n#include \"ear/dsp/ptr_adapter.hpp\"\n#include \"eigen_utils.hpp\"\n\nusing namespace ear;\nusing namespace ear::dsp;\n\n// adapters to make apply_interp, apply_constant and process work with Eigen\n// types\ntemplate <typename Interp = LinearInterpSingle, typename In, typename Out,\n          typename Point>\nvoid apply_interp(In &&in, Out &&out, SampleIndex block_start,\n                  SampleIndex start, SampleIndex end, const Point &start_point,\n                  const Point &end_point) {\n  PtrAdapter in_p(in.cols());\n  in_p.set_eigen(in);\n  PtrAdapter out_p(out.cols());\n  out_p.set_eigen(out);\n\n  Interp::apply_interp(in_p.ptrs(), out_p.ptrs(), 0, in.rows(), block_start,\n                       start, end, start_point, end_point);\n}\n\ntemplate <typename Interp = LinearInterpSingle, typename In, typename Out,\n          typename Point>\nvoid apply_constant(In &&in, Out &&out, const Point &point) {\n  PtrAdapter in_p(in.cols());\n  in_p.set_eigen(in);\n  PtrAdapter out_p(out.cols());\n  out_p.set_eigen(out);\n\n  Interp::apply_constant(in_p.ptrs(), out_p.ptrs(), 0, in.rows(), point);\n}\n\ntemplate <typename Interp>\nvoid process(Interp &interp, SampleIndex block_start,\n             const Eigen::Ref<const Eigen::MatrixXf> &in,\n             Eigen::Ref<Eigen::MatrixXf> out) {\n  PtrAdapterConst in_p(in.cols());\n  in_p.set_eigen(in);\n  PtrAdapter out_p(out.cols());\n  out_p.set_eigen(out);\n\n  interp.process(block_start, in.rows(), in_p.ptrs(), out_p.ptrs());\n}\n\n// ensure that LinearInterpSingle is correct so that we can use it to generate\n// expected results in tests of GainInterpolator; otherwise we would just end up\n// reimplementing it here\n\nTEST_CASE(\"LinearInterpSingle::apply_interp\") {\n  Eigen::VectorXf input = Eigen::VectorXf::Random(100);\n  Eigen::VectorXf output = Eigen::VectorXf::Zero(100);\n\n  apply_interp<LinearInterpSingle>(input, output, 100, 50, 250, 0.2f, 0.8f);\n\n  Eigen::VectorXf p = Eigen::VectorXf::LinSpaced(200, 0, 199) / 200.0;\n  Eigen::VectorXf gain_ramp = 0.8f * p.array() + (1.0f - p.array()) * 0.2f;\n  Eigen::VectorXf expected =\n      gain_ramp(Eigen::seqN(50, 100)).cwiseProduct(input);\n\n  CHECK_THAT(output, IsApprox(expected));\n}\n\nTEST_CASE(\"LinearInterpSingle::apply_constant\") {\n  Eigen::VectorXf input = Eigen::VectorXf::Random(100);\n  Eigen::VectorXf output = Eigen::VectorXf::Zero(100);\n\n  apply_constant<LinearInterpSingle>(input, output, 0.3f);\n\n  Eigen::VectorXf expected = 0.3f * input;\n\n  CHECK_THAT(output, IsApprox(expected));\n}\n\nvoid run_test(GainInterpolator<LinearInterpSingle> &interp,\n              Eigen::VectorXf &input, Eigen::VectorXf &expected_output,\n              const std::vector<Eigen::Index> &block_sizes) {\n  for (auto block_size : block_sizes) {\n    Eigen::VectorXf output = Eigen::VectorXf::Zero(input.size());\n\n    Eigen::internal::set_is_malloc_allowed(false);\n    for (Eigen::Index offset = 0; offset < input.size(); offset += block_size) {\n      auto block =\n          Eigen::seq(offset, std::min(offset + block_size, input.size()) - 1);\n\n      process(interp, offset, input(block), output(block));\n    }\n    Eigen::internal::set_is_malloc_allowed(true);\n\n    CHECK_THAT(output, IsApprox(expected_output));\n  }\n}\n\n// check that GainInterpolator makes the right calls to the templated InterpType\n\nTEST_CASE(\"basic\") {\n  GainInterpolator<LinearInterpSingle> interp;\n\n  interp.interp_points.emplace_back(100, 0.2f);\n  interp.interp_points.emplace_back(200, 0.8f);\n  interp.interp_points.emplace_back(300, 0.8f);\n  interp.interp_points.emplace_back(400, 0.3f);\n\n  Eigen::VectorXf input = Eigen::VectorXf::Random(500);\n  Eigen::VectorXf expected_output = Eigen::VectorXf::Zero(500);\n\n  auto block = Eigen::seqN(0, 100);\n  apply_constant(input(block), expected_output(block), 0.2f);\n\n  block = Eigen::seqN(100, 100);\n  apply_interp(input(block), expected_output(block), 100, 100, 200, 0.2f, 0.8f);\n\n  block = Eigen::seqN(200, 100);\n  apply_constant(input(block), expected_output(block), 0.8f);\n\n  block = Eigen::seqN(300, 100);\n  apply_interp(input(block), expected_output(block), 300, 300, 400, 0.8f, 0.3f);\n\n  block = Eigen::seqN(400, 100);\n  apply_constant(input(block), expected_output(block), 0.3f);\n\n  run_test(interp, input, expected_output, {50, 75, 100, 500});\n}\n\nTEST_CASE(\"step\") {\n  GainInterpolator<LinearInterpSingle> interp;\n\n  interp.interp_points.emplace_back(100, 0.2f);\n  interp.interp_points.emplace_back(200, 0.2f);\n  interp.interp_points.emplace_back(200, 0.8f);\n  interp.interp_points.emplace_back(300, 0.8f);\n\n  Eigen::VectorXf input = Eigen::VectorXf::Random(400);\n  Eigen::VectorXf expected_output = Eigen::VectorXf::Zero(400);\n\n  auto block = Eigen::seqN(0, 200);\n  apply_constant(input(block), expected_output(block), 0.2f);\n\n  block = Eigen::seqN(200, 200);\n  apply_constant(input(block), expected_output(block), 0.8f);\n\n  run_test(interp, input, expected_output, {50, 75, 100, 400});\n}\n\nTEST_CASE(\"only_step\") {\n  GainInterpolator<LinearInterpSingle> interp;\n\n  interp.interp_points.emplace_back(100, 0.2f);\n  interp.interp_points.emplace_back(100, 0.8f);\n\n  Eigen::VectorXf input = Eigen::VectorXf::Random(200);\n  Eigen::VectorXf expected_output = Eigen::VectorXf::Zero(200);\n\n  auto block = Eigen::seqN(0, 100);\n  apply_constant(input(block), expected_output(block), 0.2f);\n\n  block = Eigen::seqN(100, 100);\n  apply_constant(input(block), expected_output(block), 0.8f);\n\n  run_test(interp, input, expected_output, {50, 75, 100, 200});\n}\n\nTEST_CASE(\"one_point\") {\n  GainInterpolator<LinearInterpSingle> interp;\n\n  interp.interp_points.emplace_back(100, 0.2);\n\n  Eigen::VectorXf input = Eigen::VectorXf::Random(200);\n  Eigen::VectorXf expected_output = Eigen::VectorXf::Zero(200);\n\n  auto block = Eigen::seqN(0, 200);\n  apply_constant(input(block), expected_output(block), 0.2f);\n\n  run_test(interp, input, expected_output, {50, 75, 100, 200});\n}\n\n// tests for the other InterpTypes\n\nTEST_CASE(\"vector\") {\n  GainInterpolator<LinearInterpVector> interp;\n\n  std::vector<float> a{0.0f, 1.0f};\n  std::vector<float> b{1.0f, 0.0f};\n\n  interp.interp_points.emplace_back(100, a);\n  interp.interp_points.emplace_back(200, b);\n\n  Eigen::VectorXf input = Eigen::VectorXf::Random(300);\n  Eigen::MatrixXf output = Eigen::MatrixXf::Zero(300, 2);\n\n  Eigen::internal::set_is_malloc_allowed(false);\n  process(interp, 0, input, output);\n  Eigen::internal::set_is_malloc_allowed(true);\n\n  Eigen::MatrixXf expected_output = Eigen::MatrixXf::Zero(300, 2);\n  auto run_channel = [&](Eigen::Index out) {\n    Eigen::MatrixXf tmp = Eigen::MatrixXf::Zero(300, 1);\n\n    GainInterpolator<LinearInterpSingle> interp_test;\n    interp_test.interp_points.emplace_back(100, a[out]);\n    interp_test.interp_points.emplace_back(200, b[out]);\n\n    process(interp_test, 0, input, tmp);\n\n    expected_output(Eigen::all, out) += tmp;\n  };\n  run_channel(0);\n  run_channel(1);\n\n  CHECK_THAT(output, IsApprox(expected_output));\n}\n\nTEST_CASE(\"matrix\") {\n  GainInterpolator<LinearInterpMatrix> interp;\n\n  std::vector<std::vector<float>> a{{0.0f, 0.3f}, {0.5f, 0.0f}};\n  std::vector<std::vector<float>> b{{0.6f, 0.0f}, {0.0f, 0.7f}};\n\n  interp.interp_points.emplace_back(100, a);\n  interp.interp_points.emplace_back(200, b);\n\n  Eigen::MatrixXf input = Eigen::MatrixXf::Random(300, 2);\n  Eigen::MatrixXf output = Eigen::MatrixXf::Zero(300, 2);\n\n  Eigen::internal::set_is_malloc_allowed(false);\n  process(interp, 0, input, output);\n  Eigen::internal::set_is_malloc_allowed(true);\n\n  Eigen::MatrixXf expected_output = Eigen::MatrixXf::Zero(300, 2);\n  auto run_channel = [&](Eigen::Index in, Eigen::Index out) {\n    Eigen::MatrixXf tmp = Eigen::MatrixXf::Zero(300, 1);\n\n    GainInterpolator<LinearInterpSingle> interp_test;\n    interp_test.interp_points.emplace_back(100, a[in][out]);\n    interp_test.interp_points.emplace_back(200, b[in][out]);\n\n    process(interp_test, 0, input(Eigen::all, in), tmp);\n\n    expected_output(Eigen::all, out) += tmp;\n  };\n  run_channel(0, 0);\n  run_channel(0, 1);\n  run_channel(1, 0);\n  run_channel(1, 1);\n\n  CHECK_THAT(output, IsApprox(expected_output));\n}\n", "meta": {"hexsha": "eb2cd2a2c42936c79fbcb9eabdc5546e9b80c0c8", "size": 8193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/gain_interpolator_tests.cpp", "max_stars_repo_name": "valnoel/libear", "max_stars_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/gain_interpolator_tests.cpp", "max_issues_repo_name": "valnoel/libear", "max_issues_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "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/gain_interpolator_tests.cpp", "max_forks_repo_name": "valnoel/libear", "max_forks_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "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.2559055118, "max_line_length": 80, "alphanum_fraction": 0.7051141218, "num_tokens": 2405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5441962656045707}}
{"text": "/**\n * \\file RemezBasedFilter.cpp\n */\n\n#include <vector>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <Eigen/Dense>\n\n#include <ATK/Core/Utilities.h>\n#include <ATK/EQ/RemezBasedFilter.h>\n#include <ATK/EQ/FIRFilter.h>\n\n#include <ATK/Utility/FFT.h>\n\nnamespace\n{\n  template<class DataType>\n  class RemezBuilder\n  {\n  public:\n    using AlignedScalarVector = typename ATK::TypedBaseFilter<DataType>::AlignedScalarVector;\n  private:\n    const static gsl::index grid_size = 1024; // grid size, power of two better for FFT\n    constexpr static DataType SN = 1e-8;\n\n    gsl::index M;\n    std::vector<DataType> grid;\n    std::vector<std::pair<std::pair<DataType, DataType>, std::pair<DataType, DataType>> > target;\n    \n    /// Computed coefficients\n    AlignedScalarVector coeffs;\n    /// Selected indices\n    std::vector<gsl::index> indices;\n    /// Weight function on the grid\n    std::vector<DataType> weights;\n    /// Objective function on the grid\n    std::vector<DataType> objective;\n    /// Alternate signs\n    std::vector<int> s;\n\n    ATK::FFT<DataType> fft_processor;\n\n  public:\n    RemezBuilder(gsl::index order, const std::vector<std::pair<std::pair<DataType, DataType>, std::pair<DataType, DataType>> >& target)\n    :M(order / 2), target(target)\n    {\n      grid.resize(grid_size);\n      for(gsl::index i = 0; i < grid_size; ++i)\n      {\n        grid[i] = i * boost::math::constants::pi<DataType>() / grid_size;\n      }\n      fft_processor.set_size(2 * grid_size);\n    }\n    \n    void init()\n    {\n      coeffs.assign(M * 2 + 1, 0);\n      indices.assign(M + 2, -1);\n      s.assign(M+2, 0);\n      \n      weights.assign(grid_size, 0);\n      objective.assign(grid_size, 0);\n\n      int current_template = 0;\n      for(gsl::index i = 0; i < grid_size; ++i)\n      {\n        auto reduced_freq = grid[i] / boost::math::constants::pi<DataType>();\n        if(reduced_freq > target[current_template].first.second && current_template + 1 < target.size())\n        {\n          ++current_template;\n        }\n        if (reduced_freq < target[current_template].first.first || reduced_freq > target[current_template].first.second)\n        {\n          weights[i] = 0;\n          objective[i] = 0;\n        }\n        else\n        {\n          weights[i] = target[current_template].second.second;\n          objective[i] = target[current_template].second.first;\n        }\n      }\n      int flag = -1;\n      for (gsl::index i = 0; i < M + 2; ++i)\n      {\n        s[i] = flag;\n        flag = -flag;\n      }\n      indices = set_starting_conditions();\n    }\n\n    std::vector<gsl::index> set_starting_conditions() const\n    {\n      std::vector<gsl::index> indices;\n\n      std::vector<gsl::index> valid_indices;\n      for (gsl::index i = 0; i < grid_size; ++i)\n      {\n        if (weights[i] != 0)\n        {\n          valid_indices.push_back(i);\n        }\n      }\n\n      for (gsl::index i = 0; i < M + 2; ++i)\n      {\n        indices.push_back(valid_indices[std::lround(valid_indices.size() / (M + 4.) * (i + 1))]);\n      }\n\n      return indices;\n    }\n    \n    AlignedScalarVector build()\n    {\n      if(target.empty())\n      {\n        coeffs.clear();\n        return coeffs;\n      }\n      init();\n      while(true)\n      {\n        Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic> A(M + 2, M + 2);\n        for (gsl::index i = 0; i < M + 2; ++i)\n        {\n          for (gsl::index j = 0; j < M + 1; ++j)\n          {\n            A(i, j) = std::cos(grid[indices[i]] * j);\n          }\n        }\n        for (gsl::index i = 0; i < M + 2; ++i)\n        {\n          A(i, M + 1) = s[i] / weights[indices[i]];\n        }\n\n        Eigen::Matrix<DataType, Eigen::Dynamic, 1> b(M + 2, 1);\n        for (gsl::index i = 0; i < M + 2; ++i)\n        {\n          b(i) = objective[indices[i]];\n        }\n        Eigen::Matrix<DataType, Eigen::Dynamic, 1> x = A.colPivHouseholderQr().solve(b);\n\n        for (gsl::index i = 0; i < M; ++i)\n        {\n          coeffs[i] = coeffs[2 * M - i] = x[M - i] / 2;\n        }\n        coeffs[M] = x[0];\n        auto delta = std::abs(x[M + 1]); // maximum cost\n\n        auto newerr = compute_new_error();\n        auto new_indices = locmax(newerr);\n\n        filter_SN(delta, new_indices, newerr);\n        filter_monotony(new_indices, newerr);\n\n        DataType max = 0;\n        for (auto indice : new_indices)\n        {\n          max = std::max(max, std::abs(newerr[indice]));\n        }\n\n        if ((max - delta) / delta < SN)\n        {\n          break;\n        }\n\n        indices = std::move(new_indices);\n      }\n\n      return coeffs;\n    }\n    \n  private:\n    /// Creates a spectral response for a given set of coeffs through an FFT\n    std::vector<DataType> firamp() const\n    {\n      std::vector<std::complex<DataType>> output(grid_size * 2);\n      fft_processor.process_forward(coeffs.data(), output.data(), coeffs.size());\n      std::vector<DataType> amp(grid_size);\n      for (gsl::index i = 0; i < grid_size; ++i)\n      {\n        amp[i] = (std::complex<DataType>(std::cos(M * grid[i]), std::sin(M * grid[i])) * output[i]).real() * grid_size * 2;\n      }\n      return amp;\n    }\n\n    std::vector<DataType> compute_new_error() const\n    {\n      auto fir_result = firamp();\n      std::vector<DataType> newerr(grid_size);\n      for (gsl::index i = 0; i < grid_size; ++i)\n      {\n        newerr[i] = (fir_result[i] - objective[i]) * weights[i];\n      }\n\n      return newerr;\n    }\n\n    // Finds min and max\n    std::vector<gsl::index> locmax(const std::vector<DataType>& data) const\n    {\n      std::vector<gsl::index> v;\n\n      std::vector<DataType> temp1;\n      std::vector<DataType> temp2;\n      temp1.push_back(data[0] - 1);\n      for (gsl::index i = 0; i < data.size() - 1; ++i)\n      {\n        temp1.push_back(data[i]);\n        temp2.push_back(data[i + 1]);\n      }\n      temp2.push_back(data.back() - 1);\n\n      for (gsl::index i = 0; i < data.size(); ++i)\n      {\n        if ((data[i] > temp1[i]) && (data[i] > temp2[i]))\n        {\n          v.push_back(i);\n        }\n      }\n\n      temp1.clear();\n      temp2.clear();\n      temp1.push_back(-data[0] - 1);\n      for (gsl::index i = 0; i < data.size() - 1; ++i)\n      {\n        temp1.push_back(-data[i]);\n        temp2.push_back(-data[i + 1]);\n      }\n      temp2.push_back(-data.back() - 1);\n\n      for (gsl::index i = 0; i < data.size(); ++i)\n      {\n        if ((-data[i] > temp1[i]) && (-data[i] > temp2[i]))\n        {\n          v.push_back(i);\n        }\n      }\n\n      std::sort(v.begin(), v.end());\n\n      return v;\n    }\n\n    void filter_SN(DataType delta, std::vector<gsl::index>& indices, const std::vector<DataType>& err) const\n    {\n      std::vector<gsl::index> new_indices;\n\n      for (auto indice : indices)\n      {\n        if (std::abs(err[indice]) > (delta - SN))\n        {\n          new_indices.push_back(indice);\n        }\n      }\n\n      indices = std::move(new_indices);\n    }\n\n    std::vector<gsl::index> etap(const std::vector<DataType>& data) const\n    {\n      std::vector<gsl::index> v;\n      auto xe = data[0];\n      gsl::index xv = 0;\n      for (gsl::index i = 1; i < data.size(); ++i)\n      {\n        if (std::signbit(data[i]) == std::signbit(xe))\n        {\n          if (std::abs(data[i]) > std::abs(xe))\n          {\n            xe = data[i];\n            xv = i;\n          }\n        }\n        else\n        {\n          v.push_back(xv);\n          xe = data[i];\n          xv = i;\n        }\n      }\n      v.push_back(xv);\n      return v;\n    }\n\n    void filter_monotony(std::vector<gsl::index>& indices, const std::vector<DataType>& err) const\n    {\n      std::vector<DataType> filtered_err;\n      for (auto indice : indices)\n      {\n        filtered_err.push_back(err[indice]);\n      }\n\n      auto selected_indices = etap(filtered_err);\n      std::vector<gsl::index> new_indices;\n      for (gsl::index i = 0; i < M + 2; ++i)\n      {\n        new_indices.push_back(indices[selected_indices[i]]);\n      }\n      indices = std::move(new_indices);\n    }\n  };\n}\n\nnamespace ATK\n{\n  template<class DataType>\n  RemezBasedCoefficients<DataType>::RemezBasedCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels, nb_channels)\n  {\n  }\n\n  template<class DataType>\n  RemezBasedCoefficients<DataType>::RemezBasedCoefficients(RemezBasedCoefficients&& other)\n    :Parent(std::move(other)), target(std::move(other.target)), in_order(std::move(other.in_order)), coefficients_in(std::move(other.coefficients_in))\n  {\n  }\n\n  template<class DataType>\n  void RemezBasedCoefficients<DataType>::set_template(const std::vector<std::pair<std::pair<CoeffDataType, CoeffDataType>, std::pair<CoeffDataType, CoeffDataType> > >& target)\n  {\n    this->target = target;\n    setup();\n  }\n  \n  template<class DataType>\n  const std::vector<std::pair<std::pair<typename RemezBasedCoefficients<DataType>::CoeffDataType, typename RemezBasedCoefficients<DataType>::CoeffDataType>, std::pair<typename RemezBasedCoefficients<DataType>::CoeffDataType, typename RemezBasedCoefficients<DataType>::CoeffDataType> > >& RemezBasedCoefficients<DataType>::get_template() const\n  {\n    return target;\n  }\n  \n  template<class DataType>\n  void RemezBasedCoefficients<DataType>::set_order(gsl::index order)\n  {\n    if(order % 2 == 1)\n    {\n      throw ATK::RuntimeError(\"Need an even filter order (considering order 0 has 1 coefficients)\");\n    }\n    in_order = order;\n    setup();\n  }\n\n  template<class DataType>\n  void RemezBasedCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    std::sort(target.begin(), target.end());\n    for(gsl::index i = 0; i + 1 < target.size(); ++i)\n    {\n      if(target[i].first.second > target[i + 1].first.first)\n      {\n        target.clear();\n        throw ATK::RuntimeError(\"Bad template\");\n      }\n    }\n    \n    if (in_order > 0)\n    {\n      RemezBuilder<CoeffDataType> builder(in_order, target);\n      coefficients_in = builder.build();\n    }\n  }\n  \n  template class ATK_EQ_EXPORT RemezBasedCoefficients<double>;\n#if ATK_ENABLE_INSTANTIATION\n  template class ATK_EQ_EXPORT RemezBasedCoefficients<std::complex<double> >;\n#endif\n}\n", "meta": {"hexsha": "d00f3e3af922e3b74e6ba9723818e672efe1f12f", "size": 10021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/RemezBasedFilter.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/EQ/RemezBasedFilter.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/EQ/RemezBasedFilter.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": 26.938172043, "max_line_length": 342, "alphanum_fraction": 0.5604231115, "num_tokens": 2765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5441962555680073}}
{"text": "#ifndef VECTORQUANTIZER_HPP\n#define VECTORQUANTIZER_HPP\n\n#include <Eigen/Dense>\n#include \"../iterator/iterator.hpp\"\n/**\n * @brief plain old vector quantizer\n */\ntemplate<typename T, uint D, uint C>\nclass vectorquantizer {\n\n    typedef Eigen::Matrix < T, D, 1 > vec_t;\n\n    static_assert( ((C % 2 == 0) || ( C == 1)), \"vectorquantizer: cells = 0 mod 2 failed or C==1\");\n\npublic:\n\n    // ================================================================================\n    // Methods\n    // ================================================================================\n\n    vectorquantizer(){\n        _raw_centroids = new T[C * D];\n        _centroids = Eigen::Map<Eigen::Matrix<T, C, D>>(_raw_centroids, C, D);\n\n    }\n\n    ~vectorquantizer() {\n        delete[] _raw_centroids;\n\n    }\n\n    void getAssignment(iterator<T, D> &iter) {\n        // for each vector ...\n        for (uint n = 0, n_e = iter.num(); n < n_e; ++n) {\n            // find minimum\n            uint bestIdx = 0;\n            T bestDist = HUGE_VAL;\n            vec_t vec = iter[n];\n            // for each cluster\n            for (uint c = 0, c_e = _step; c < c_e; ++c) {\n                vec_t cec = _centroids.row(c);\n                T curDist = (vec - cec).squaredNorm();\n                if ( curDist  < bestDist ) {\n                    bestDist = curDist;\n                    bestIdx = c;\n                }\n            }\n            _mapping[n] = bestIdx;\n            _distances[n] = bestDist;\n        }\n    }\n\n    void updateCentroids(iterator<T, D> &iter) {\n        _centroids = Eigen::Matrix<T, C, D>::Zero(C, D);\n        T centerCounter[C] = {0};\n        // find mean\n        for (uint n = 0, n_e = iter.num(); n < n_e; ++n) {\n            const uint c = _mapping[n];\n            _centroids.row(c) += iter[n];\n            ++centerCounter[c];\n        }\n        for (uint c = 0; c < C; ++c) {\n            if (centerCounter[c] != 0)\n                _centroids.row(c).array() /= centerCounter[c];\n\n        }\n    }\n\n    void augmentCentroids() {\n        for (uint i = 0; i < _step; ++i) {\n            _centroids.row(i + _step) = _centroids.row(i).array() + 0.001;\n            _centroids.row(i) = _centroids.row(i).array() - 0.001;\n        }\n        _step *= 2;\n    }\n\n    T loss(iterator<T, D> &iter) {\n        Eigen::MatrixXf l = Eigen::Map<  Eigen::MatrixXf >(_distances, iter.num(), 1);\n        return l.sum();\n    }\n\n    uint id(const vec_t &vec) {\n        // compute all l1 distances (row=part)\n        for (uint c = 0; c < C; ++c) {\n            const Eigen::Matrix< T, D, 1> cec = _centroids.row(c);\n            const Eigen::Matrix< T, D, 1> diff = vec - cec;\n            _L1distances[c] = diff.squaredNorm();\n            _L1order[c] = c;\n\n        }\n\n        // now sort them according their distances (sort each row)\n        auto comparator = [&](const uint8_t &lhs, const uint8_t &rhs) -> bool {\n            return _L1distances[lhs] < _L1distances[rhs];\n        };\n\n        std::sort(_L1order, _L1order + C, comparator);\n\n        return _L1order[0];\n\n    }\n\n    void dist(const vec_t &vec) {\n        // compute all l1 distances (row=part)\n        for (uint c = 0; c < C; ++c) {\n            const Eigen::Matrix< T, D, 1> cec = _centroids.row(c);\n            const Eigen::Matrix< T, D, 1> diff = vec - cec;\n            _L1distances[c] = diff.squaredNorm();\n            _L1order[c] = c;\n\n        }\n\n\n    }\n\n    void generate(iterator<T, D> &iter) {\n        _step = 1;\n\n        _mapping = new uint8_t[iter.num()]();\n        _distances = new T[iter.num()]();\n\n        _centroids.row(0) = iter.center();\n\n        T currentLoss = 0.0;\n        T lastLoss    = 0.0;\n\n        if (C == 1) {\n            getAssignment(iter);    // E step\n            updateCentroids(iter);  // M step\n            return;                  // do nothing\n        }\n\n        do {\n            augmentCentroids();\n            do {\n                lastLoss = currentLoss;\n                getAssignment(iter);    // E step\n                updateCentroids(iter);  // M step\n                currentLoss = loss(iter);\n            } while ((abs(lastLoss - currentLoss) > 0.005));\n        } while (_step < C );\n\n        delete[] _mapping;\n        delete[] _distances;\n    }\n\n\n    // ================================================================================\n    // Variables\n    // ================================================================================\n\n    Eigen::Matrix<T, C, D> _centroids;\n    T *_raw_centroids;\n    uint _step;\n    uint8_t *_mapping;\n    T *_distances;\n\n    T _L1distances[C];\n    uint _L1order[C];\n\n};\n\n#endif", "meta": {"hexsha": "382cb1a5dff0b058fee96486caa327e3ca832f94", "size": 4581, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpu_version/quantizer/vectorquantizer.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/quantizer/vectorquantizer.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/quantizer/vectorquantizer.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": 27.9329268293, "max_line_length": 99, "alphanum_fraction": 0.4523029906, "num_tokens": 1217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5441962549318536}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"test_log_search\"\n\n#include <boost/test/unit_test.hpp>\n#include \"nanocv/scalar.h\"\n#include \"nanocv/thread/pool.h\"\n#include \"nanocv/log_search.hpp\"\n#include \"nanocv/math/abs.hpp\"\n#include \"nanocv/math/random.hpp\"\n#include \"nanocv/math/epsilon.hpp\"\n\nnamespace test\n{\n        using namespace ncv;\n\n        void check(scalar_t a, scalar_t b, scalar_t minlog, scalar_t maxlog, scalar_t epslog, size_t splits)\n        {\n                auto op = [=] (scalar_t x)\n                {\n                        return (x - a) * (x - a) + b;\n                };\n\n                // single-threaded version\n                const std::pair<scalar_t, scalar_t> ret1 = ncv::log10_min_search(op, minlog, maxlog, epslog, splits);\n\n                // multi-threaded version\n                thread_pool_t pool(splits);\n                const std::pair<scalar_t, scalar_t> retx = ncv::log10_min_search_mt(op, pool, minlog, maxlog, epslog, splits);\n\n                const scalar_t epsilon = math::epsilon2<scalar_t>();\n\n                // check optimum result\n                BOOST_CHECK_LE(math::abs(ret1.first - b), epsilon);\n                BOOST_CHECK_LE(math::abs(retx.first - b), epsilon);\n\n                // check optimum parameters\n                BOOST_CHECK_LE(math::abs(ret1.second - a), epsilon);\n                BOOST_CHECK_LE(math::abs(retx.second - a), epsilon);\n        }\n}\n\nBOOST_AUTO_TEST_CASE(test_log_search)\n{\n        using namespace ncv;\n\n        const size_t n_tests = 16;\n        const scalar_t minlog = -6.0;\n        const scalar_t maxlog = +6.0;\n        const scalar_t epslog = math::epsilon2<scalar_t>();\n        const size_t splits = ncv::n_threads();\n\n        for (size_t t = 0; t < n_tests; t ++)\n        {\n                random_t<scalar_t> agen(+0.1, +1.0);\n                random_t<scalar_t> bgen(-2.0, +2.0);\n\n                test::check(agen(), bgen(), minlog, maxlog, epslog, splits);\n        }\n}\n\n", "meta": {"hexsha": "b7e48df28c64b6db0f21f75348170d07e05df52c", "size": 1964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_log_search.cpp", "max_stars_repo_name": "0x0all/nanocv", "max_stars_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_stars_repo_licenses": ["MIT"], "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_log_search.cpp", "max_issues_repo_name": "0x0all/nanocv", "max_issues_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_issues_repo_licenses": ["MIT"], "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_log_search.cpp", "max_forks_repo_name": "0x0all/nanocv", "max_forks_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T02:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-02T02:41:37.000Z", "avg_line_length": 32.1967213115, "max_line_length": 126, "alphanum_fraction": 0.5723014257, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5441877417125258}}
{"text": "#include \"teca_2d_component_area.h\"\n\n#include \"teca_mesh.h\"\n#include \"teca_array_collection.h\"\n#include \"teca_variant_array.h\"\n#include \"teca_metadata.h\"\n#include \"teca_cartesian_mesh.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <deque>\n#include <set>\n#define _USE_MATH_DEFINES\n#include <cmath>\n\n#if defined(TECA_HAS_BOOST)\n#include <boost/program_options.hpp>\n#endif\n\nnamespace {\n\ntemplate <typename component_t>\ncomponent_t get_max_component_id(unsigned long n, const component_t *labels)\n{\n    component_t max_component_id = std::numeric_limits<component_t>::lowest();\n    for (unsigned long i = 0; i < n; ++i)\n    {\n        component_t label = labels[i];\n        max_component_id = label > max_component_id ? label : max_component_id;\n    }\n    return max_component_id;\n}\n\n// visit each node in the mesh, the node is treated as a cell in\n// the dual mesh defined by mid points between nodes. the area of\n// the cell is added to the corresponding label. this formulation\n// requires a layer of ghost nodes\n//\n// The exact area of the sperical rectangular patch A_i is given by:\n//\n// A_i = rho^2(cos(phi_0) - cos(phi_1))(theta_1 - theta_0)\n//\n//     = rho^2(sin(rad_lat_0) - sin(rad_lat_1))(theta_1 - theta_0)\n//\n// where\n//\n//   theta = deg_lon * pi/180\n//   phi = pi/2 - rad_lat\n//   rad_lat = deg_lat * pi/180\n//   sin(rad_lat) = cos(pi/2 - rad_lat)\n//\ntemplate<typename coord_t, typename component_t, typename container_t>\nvoid component_area(unsigned long nlon, unsigned long nlat,\n    const coord_t *deg_lon, const coord_t *deg_lat, const component_t *labels,\n    container_t &area)\n{\n    // This calculation is sensative to floating point precision and\n    // should be done in double precision\n    using calc_t = double;\n\n    calc_t R_e = 6378.1370; // km\n    calc_t R_e_sq = R_e*R_e;\n    calc_t rad_per_deg = M_PI/180.0;\n\n    unsigned long nlonm1 = nlon - 1;\n    unsigned long nlatm1 = nlat - 1;\n\n    // convert to spherical coordinates in units of radians,\n    // move to the dual mesh, and pre-compute factors in A\n    calc_t *rho_sq_d_theta = (calc_t*)malloc(nlon*sizeof(calc_t));\n    rho_sq_d_theta[0] = calc_t();\n    for (unsigned long i = 1; i < nlonm1; ++i)\n        rho_sq_d_theta[i] = R_e_sq*calc_t(0.5)*(deg_lon[i + 1] - deg_lon[i - 1])*rad_per_deg;\n    rho_sq_d_theta[nlonm1] = calc_t();\n\n    calc_t *rad_lat = (calc_t*)malloc(nlat*sizeof(calc_t));\n    for (unsigned long j = 0; j < nlat; ++j)\n        rad_lat[j] = deg_lat[j]*rad_per_deg;\n\n    calc_t *d_cos_phi = (calc_t*)malloc(nlat*sizeof(calc_t));\n    for (unsigned long j = 1; j < nlatm1; ++j)\n    {\n        calc_t cos_phi_1 = sin(calc_t(0.5)*(rad_lat[j - 1] + rad_lat[j]));\n        calc_t cos_phi_0 = sin(calc_t(0.5)*(rad_lat[j] + rad_lat[j + 1]));\n        d_cos_phi[j] = cos_phi_0 - cos_phi_1;\n    }\n    d_cos_phi[0] = calc_t();\n    d_cos_phi[nlatm1] = calc_t();\n\n    // finish off the calc by multiplying the factors\n    for (unsigned long j = 1; j < nlatm1; ++j)\n    {\n        calc_t d_cos_phi_j = d_cos_phi[j];\n        unsigned long jj = j*nlon;\n        for (unsigned long i = 1; i < nlonm1; ++i)\n        {\n            area[labels[jj + i]] += rho_sq_d_theta[i]*d_cos_phi_j;\n        }\n    }\n\n    free(rad_lat);\n    free(d_cos_phi);\n    free(rho_sq_d_theta);\n}\n\n}\n\n\n\n// --------------------------------------------------------------------------\nteca_2d_component_area::teca_2d_component_area() :\n    component_variable(\"\"), contiguous_component_ids(0), background_id(-1)\n{\n    this->set_number_of_input_connections(1);\n    this->set_number_of_output_ports(1);\n}\n\n// --------------------------------------------------------------------------\nteca_2d_component_area::~teca_2d_component_area()\n{}\n\n#if defined(TECA_HAS_BOOST)\n// --------------------------------------------------------------------------\nvoid teca_2d_component_area::get_properties_description(\n    const std::string &prefix, options_description &global_opts)\n{\n    options_description opts(\"Options for \"\n        + (prefix.empty()?\"teca_2d_component_area\":prefix));\n\n    opts.add_options()\n        TECA_POPTS_GET(std::string, prefix, component_variable,\n            \"name of the varibale containing region labels\")\n        TECA_POPTS_GET(int, prefix, contiguous_component_ids,\n            \"when the region label ids start at 0 and are consecutive \"\n            \"this flag enables use of an optimization\")\n        TECA_POPTS_GET(long, prefix, background_id,\n            \"the label id that corresponds to the background\")\n        ;\n\n    this->teca_algorithm::get_properties_description(prefix, opts);\n\n    global_opts.add(opts);\n}\n\n// --------------------------------------------------------------------------\nvoid teca_2d_component_area::set_properties(const std::string &prefix,\n    variables_map &opts)\n{\n    this->teca_algorithm::set_properties(prefix, opts);\n\n    TECA_POPTS_SET(opts, std::string, prefix, component_variable)\n    TECA_POPTS_SET(opts, int, prefix, contiguous_component_ids)\n    TECA_POPTS_SET(opts, long, prefix, background_id)\n}\n#endif\n\n// --------------------------------------------------------------------------\nint teca_2d_component_area::get_component_variable(std::string &component_var)\n{\n    if (this->component_variable.empty())\n        return -1;\n\n    component_var = this->component_variable;\n    return 0;\n}\n\n// --------------------------------------------------------------------------\nteca_metadata teca_2d_component_area::get_output_metadata(\n    unsigned int port,\n    const std::vector<teca_metadata> &input_md)\n{\n#ifdef TECA_DEBUG\n    cerr << teca_parallel_id()\n        << \"teca_2d_component_area::get_output_metadata\" << endl;\n#endif\n    (void) port;\n\n    teca_metadata md = input_md[0];\n    return md;\n}\n\n// --------------------------------------------------------------------------\nstd::vector<teca_metadata> teca_2d_component_area::get_upstream_request(\n    unsigned int port,\n    const std::vector<teca_metadata> &input_md,\n    const teca_metadata &request)\n{\n#ifdef TECA_DEBUG\n    cerr << teca_parallel_id()\n        << \"teca_2d_component_area::get_upstream_request\" << endl;\n#endif\n    (void) port;\n    (void) input_md;\n\n    std::vector<teca_metadata> up_reqs;\n\n    // get the name of the array to request\n    std::string component_var;\n    if (this->get_component_variable(component_var))\n    {\n        TECA_FATAL_ERROR(\"component_variable was not specified\")\n        return up_reqs;\n    }\n\n    // pass the incoming request upstream, and\n    // add in what we need\n    teca_metadata req(request);\n    std::set<std::string> arrays;\n    if (req.has(\"arrays\"))\n        req.get(\"arrays\", arrays);\n    arrays.insert(component_var);\n\n    req.set(\"arrays\", arrays);\n\n    // send up\n    up_reqs.push_back(req);\n    return up_reqs;\n}\n\n\n// --------------------------------------------------------------------------\nconst_p_teca_dataset teca_2d_component_area::execute(\n    unsigned int port,\n    const std::vector<const_p_teca_dataset> &input_data,\n    const teca_metadata &request)\n{\n#ifdef TECA_DEBUG\n    cerr << teca_parallel_id()\n        << \"teca_2d_component_area::execute\" << endl;\n#endif\n    (void)port;\n    (void)request;\n\n    // get the input\n    const_p_teca_cartesian_mesh in_mesh =\n        std::dynamic_pointer_cast<const teca_cartesian_mesh>(\n            input_data[0]);\n    if (!in_mesh)\n    {\n        TECA_FATAL_ERROR(\"empty input, or not a cartesian_mesh\")\n        return nullptr;\n    }\n\n    // create output and copy metadata, coordinates, etc\n    p_teca_cartesian_mesh out_mesh = teca_cartesian_mesh::New();\n\n    out_mesh->shallow_copy(\n        std::const_pointer_cast<teca_cartesian_mesh>(in_mesh));\n\n    // get the input array\n    std::string component_var;\n    if (this->get_component_variable(component_var))\n    {\n        TECA_FATAL_ERROR(\"component_variable was not specified\")\n        return nullptr;\n    }\n\n    const_p_teca_variant_array component_array\n        = out_mesh->get_point_arrays()->get(component_var);\n    if (!component_array)\n    {\n        TECA_FATAL_ERROR(\"label variable \\\"\" << component_var\n            << \"\\\" is not in the input\")\n        return nullptr;\n    }\n\n    // get mesh dimension\n    unsigned long extent[6];\n    out_mesh->get_extent(extent);\n\n    unsigned long nx = extent[1] - extent[0] + 1;\n    unsigned long ny = extent[3] - extent[2] + 1;\n    unsigned long nxy = nx*ny;\n\n    unsigned long nz = extent[5] - extent[4] + 1;\n    if (nz != 1)\n    {\n        TECA_FATAL_ERROR(\"This calculation requires 2D data. The current dataset \"\n            \"extents are [\" << extent[0] << \", \" << extent[1] << \", \"\n            << extent[2] << \", \" << extent[3] << \", \" << extent[4] << \", \"\n            << extent[5] << \"]\")\n        return nullptr;\n    }\n\n    // get the coordinate axes\n    const_p_teca_variant_array xc = in_mesh->get_x_coordinates();\n    const_p_teca_variant_array yc = in_mesh->get_y_coordinates();\n\n    // get the input and output metadata\n    teca_metadata &in_metadata =\n        const_cast<teca_metadata&>(in_mesh->get_metadata());\n\n    teca_metadata &out_metadata = out_mesh->get_metadata();\n\n    // get the background_id, and pass it through\n    long bg_id = this->background_id;\n    if (this->background_id == -1)\n    {\n        if (in_metadata.get(\"background_id\", bg_id))\n        {\n            TECA_FATAL_ERROR(\"Metadata is missing the key \\\"background_id\\\". \"\n                \"One should specify it via the \\\"background_id\\\" algorithm \"\n                \"property\")\n            return nullptr;\n        }\n    }\n    out_metadata.set(\"background_id\", bg_id);\n\n    // calculate area of components\n    NESTED_TEMPLATE_DISPATCH_FP(const teca_variant_array_impl,\n        xc.get(),\n        _COORD,\n        // the calculation is sensative to floating point precision\n        // and should be made in double precision\n        using calc_t = double;\n\n        const NT_COORD *p_xc = static_cast<TT_COORD*>(xc.get())->get();\n        const NT_COORD *p_yc = static_cast<TT_COORD*>(yc.get())->get();\n\n        NESTED_TEMPLATE_DISPATCH_I(const teca_variant_array_impl,\n            component_array.get(),\n            _LABEL,\n\n            const NT_LABEL *p_labels = static_cast<TT_LABEL*>(component_array.get())->get();\n\n            unsigned int n_labels = 0;\n\n            bool has_component_id = in_metadata.has(\"component_ids\");\n            if (this->contiguous_component_ids || has_component_id)\n            {\n                // use a contiguous buffer to hold the result, only for\n                // contiguous lables that start at 0\n                p_teca_variant_array component_id;\n                if (has_component_id)\n                {\n                    in_metadata.get(\"number_of_components\", int(0), n_labels);\n                    component_id = in_metadata.get(\"component_ids\");\n                }\n                else\n                {\n                    NT_LABEL max_component_id = ::get_max_component_id(nxy, p_labels);\n                    n_labels = max_component_id + 1;\n                    p_teca_variant_array_impl<NT_LABEL> tmp = teca_variant_array_impl<NT_LABEL>::New(n_labels);\n                    for (unsigned int i = 0; i < n_labels; ++i)\n                        tmp->set(i, NT_LABEL(i));\n                    component_id = tmp;\n                }\n                std::vector<calc_t> component_area(n_labels);\n                ::component_area(nx,ny, p_xc,p_yc, p_labels, component_area);\n\n                // transfer the result to the output\n                out_metadata.set(\"number_of_components\", n_labels);\n                out_metadata.set(\"component_ids\", component_id);\n                out_metadata.set(\"component_area\", component_area);\n            }\n            else\n            {\n                // use an associative array to handle any labels\n                //std::map<NT_LABEL, NT_COORD> result;\n                decltype(std::map<NT_LABEL, calc_t>()) result;\n                ::component_area(nx,ny, p_xc,p_yc, p_labels, result);\n\n                // transfer the result to the output\n                n_labels = result.size();\n\n                p_teca_variant_array_impl<NT_LABEL> component_id =\n                    teca_variant_array_impl<NT_LABEL>::New(n_labels);\n\n                p_teca_variant_array_impl<calc_t> component_area =\n                    teca_variant_array_impl<calc_t>::New(n_labels);\n\n                //std::map<NT_LABEL,NT_COORD>::iterator it = result.begin();\n                auto it = result.begin();\n                for (unsigned int i = 0; i < n_labels; ++i,++it)\n                {\n                    component_id->set(i, it->first);\n                    component_area->set(i, it->second);\n                }\n\n                out_metadata.set(\"number_of_components\", n_labels);\n                out_metadata.set(\"component_ids\", component_id);\n                out_metadata.set(\"component_area\", component_area);\n            }\n            )\n        )\n\n    return out_mesh;\n}\n", "meta": {"hexsha": "f556dc8e28c2cadee63c5aa62bf513e0e186e62d", "size": 12863, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "alg/teca_2d_component_area.cxx", "max_stars_repo_name": "LBL-EESA/TECA", "max_stars_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T14:22:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T05:02:25.000Z", "max_issues_repo_path": "alg/teca_2d_component_area.cxx", "max_issues_repo_name": "LBL-EESA/TECA", "max_issues_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 476.0, "max_issues_repo_issues_event_min_datetime": "2016-11-28T18:06:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-25T05:31:42.000Z", "max_forks_repo_path": "alg/teca_2d_component_area.cxx", "max_forks_repo_name": "LBL-EESA/TECA", "max_forks_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2017-04-25T18:15:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-28T18:16:05.000Z", "avg_line_length": 33.0668380463, "max_line_length": 111, "alphanum_fraction": 0.6011039415, "num_tokens": 3064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5441877339489627}}
{"text": "//  To use the simple FFT implementation\r\n//  g++ -o demofft -I.. -Wall -O3 FFT.cpp \r\n\r\n//  To use the FFTW implementation\r\n//  g++ -o demofft -I.. -DUSE_FFTW -Wall -O3 FFT.cpp -lfftw3 -lfftw3f -lfftw3l\r\n\r\n#ifdef USE_FFTW\r\n#include <fftw3.h>\r\n#endif\r\n\r\n#include <vector>\r\n#include <complex>\r\n#include <algorithm>\r\n#include <iterator>\r\n#include <iostream>\r\n#include <Eigen/Core>\r\n#include <unsupported/Eigen/FFT>\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\ntemplate <typename T>\r\nT mag2(T a)\r\n{\r\n    return a*a;\r\n}\r\ntemplate <typename T>\r\nT mag2(std::complex<T> a)\r\n{\r\n    return norm(a);\r\n}\r\n\r\ntemplate <typename T>\r\nT mag2(const std::vector<T> & vec)\r\n{\r\n    T out=0;\r\n    for (size_t k=0;k<vec.size();++k)\r\n        out += mag2(vec[k]);\r\n    return out;\r\n}\r\n\r\ntemplate <typename T>\r\nT mag2(const std::vector<std::complex<T> > & vec)\r\n{\r\n    T out=0;\r\n    for (size_t k=0;k<vec.size();++k)\r\n        out += mag2(vec[k]);\r\n    return out;\r\n}\r\n\r\ntemplate <typename T>\r\nvector<T> operator-(const vector<T> & a,const vector<T> & b )\r\n{\r\n    vector<T> c(a);\r\n    for (size_t k=0;k<b.size();++k) \r\n        c[k] -= b[k];\r\n    return c;\r\n}\r\n\r\ntemplate <typename T>\r\nvoid RandomFill(std::vector<T> & vec)\r\n{\r\n    for (size_t k=0;k<vec.size();++k)\r\n        vec[k] = T( rand() )/T(RAND_MAX) - .5;\r\n}\r\n\r\ntemplate <typename T>\r\nvoid RandomFill(std::vector<std::complex<T> > & vec)\r\n{\r\n    for (size_t k=0;k<vec.size();++k)\r\n        vec[k] = std::complex<T> ( T( rand() )/T(RAND_MAX) - .5, T( rand() )/T(RAND_MAX) - .5);\r\n}\r\n\r\ntemplate <typename T_time,typename T_freq>\r\nvoid fwd_inv(size_t nfft)\r\n{\r\n    typedef typename NumTraits<T_freq>::Real Scalar;\r\n    vector<T_time> timebuf(nfft);\r\n    RandomFill(timebuf);\r\n\r\n    vector<T_freq> freqbuf;\r\n    static FFT<Scalar> fft;\r\n    fft.fwd(freqbuf,timebuf);\r\n\r\n    vector<T_time> timebuf2;\r\n    fft.inv(timebuf2,freqbuf);\r\n\r\n    long double rmse = mag2(timebuf - timebuf2) / mag2(timebuf);\r\n    cout << \"roundtrip rmse: \" << rmse << endl;\r\n}\r\n\r\ntemplate <typename T_scalar>\r\nvoid two_demos(int nfft)\r\n{\r\n    cout << \"     scalar \";\r\n    fwd_inv<T_scalar,std::complex<T_scalar> >(nfft);\r\n    cout << \"    complex \";\r\n    fwd_inv<std::complex<T_scalar>,std::complex<T_scalar> >(nfft);\r\n}\r\n\r\nvoid demo_all_types(int nfft)\r\n{\r\n    cout << \"nfft=\" << nfft << endl;\r\n    cout << \"   float\" << endl;\r\n    two_demos<float>(nfft);\r\n    cout << \"   double\" << endl;\r\n    two_demos<double>(nfft);\r\n    cout << \"   long double\" << endl;\r\n    two_demos<long double>(nfft);\r\n}\r\n\r\nint main()\r\n{\r\n    demo_all_types( 2*3*4*5*7 );\r\n    demo_all_types( 2*9*16*25 );\r\n    demo_all_types( 1024 );\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "3e50061d844ce312890194596eb280d96917057f", "size": 2636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/eigen3.2.10/unsupported/doc/examples/FFT.cpp", "max_stars_repo_name": "rgijsen/opengl_tmp_poc", "max_stars_repo_head_hexsha": "93e3a08e30ed100475034281208200ed724db5d9", "max_stars_repo_licenses": ["Apache-2.0"], "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": "thirdparty/eigen3.2.10/unsupported/doc/examples/FFT.cpp", "max_issues_repo_name": "rgijsen/opengl_tmp_poc", "max_issues_repo_head_hexsha": "93e3a08e30ed100475034281208200ed724db5d9", "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/eigen3.2.10/unsupported/doc/examples/FFT.cpp", "max_forks_repo_name": "rgijsen/opengl_tmp_poc", "max_forks_repo_head_hexsha": "93e3a08e30ed100475034281208200ed724db5d9", "max_forks_repo_licenses": ["Apache-2.0"], "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.1512605042, "max_line_length": 96, "alphanum_fraction": 0.5830804249, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5441877339489627}}
{"text": "//==================================================================================================\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#include <boost/simd/algorithm/reduce.hpp>\n#include <boost/align/aligned_allocator.hpp>\n#include <numeric>\n#include <vector>\n#include <simd_test.hpp>\n\nusing namespace boost::simd;\nusing namespace boost::alignment;\n\nSTF_CASE_TPL( \"Check simd::reduce(f,l,i)\", STF_NUMERIC_TYPES )\n{\n  static const int N = pack<T>::static_size;\n\n  std::vector<T,aligned_allocator<T,pack<T>::alignment>> values(2*N);\n  std::iota(values.begin(), values.end(),T(0));\n\n  auto ab = values.data();\n  auto ae = values.data()+values.size();\n\n  // All aligned\n  STF_EQUAL ( (std::accumulate(values.begin(), values.end(), T(3)))\n            , (boost::simd::reduce(ab,ae, T(3)))\n            );\n\n  // prologue + aligned\n  STF_EQUAL ( (std::accumulate(values.begin()+1, values.end(), T(3)))\n            , (boost::simd::reduce(ab+1,ae, T(3)))\n            );\n\n  // aligned + epilogue\n  STF_EQUAL ( (std::accumulate(values.begin(), values.end()-1, T(3)))\n            , (boost::simd::reduce(ab,ae-1, T(3)))\n            );\n\n  // prologue + epilogue\n  STF_EQUAL ( (std::accumulate(values.begin(), values.end()-1, T(3)))\n            , (boost::simd::reduce(ab+1,ae-1, T(3)))\n            );\n}\n\nstruct fake_sum\n{\n  template<typename T> T operator()(T const& a, T const& e) { return a + e; }\n};\n\nSTF_CASE_TPL( \"Check simd::reduce(f,l,i,f,n)\", STF_NUMERIC_TYPES )\n{\n  static const int N = pack<T>::static_size;\n\n  std::vector<T,aligned_allocator<T,pack<T>::alignment>> values(2*N);\n  std::iota(values.begin(), values.end(),T(0));\n\n  STF_EQUAL ( (std::accumulate(values.begin(), values.end(), T(3), fake_sum{}))\n            , (boost::simd::reduce( values.data(), values.data()+values.size()\n                                  , T(3)\n                                  , fake_sum{}, T(0)\n                                  )\n              )\n            );\n\n}\n\nstruct squared_sum\n{\n  template<typename T> T operator()(T const& a, T const& e) { return a + e*e; }\n};\n\nSTF_CASE_TPL( \"Check simd::reduce(f,l,i,f,n,g)\", STF_NUMERIC_TYPES )\n{\n  static const int N = pack<T>::static_size;\n\n  std::vector<T,aligned_allocator<T,pack<T>::alignment>> values(2*N);\n  std::iota(values.begin(), values.end(),T(0));\n\n  STF_EQUAL ( (std::accumulate(values.begin(), values.end(), T(3), squared_sum{}))\n            , (boost::simd::reduce( values.data(), values.data()+values.size()\n                                  , T(3)\n                                  , squared_sum{}, T(0)\n                                  , boost::simd::plus\n                                  )\n              )\n            );\n\n}\n", "meta": {"hexsha": "5a3cb34015292bab1ee72a381f7b48b2a80640b7", "size": 2915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/api/algorithm/reduce.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": "test/api/algorithm/reduce.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "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/api/algorithm/reduce.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "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": 31.3440860215, "max_line_length": 100, "alphanum_fraction": 0.5173241852, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5441877247184222}}
{"text": "/**\n * @brief \u8996\u9310\u53f0\u30af\u30e9\u30b9\n */\n\n#include \"View/Frustum.h\"\n\n#include <boost/assert.hpp>\n#include <glm/gtc/constants.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n#include <iostream>\n#include <vector>\n\nvoid Frustum::SetupPerspective(float fovy, float aspectRatio, float near,\n                               float far) {\n  fovy_ = fovy;\n  ar_ = aspectRatio;\n  near_ = near;\n  far_ = far;\n\n  type_ = ProjectionType::Perspective;\n}\n\nvoid Frustum::SetupOrtho(float left, float right, float bottom, float top,\n                         float near, float far) {\n  left_ = left;\n  right_ = right;\n  bottom_ = bottom;\n  top_ = top;\n  near_ = near;\n  far_ = far;\n\n  type_ = ProjectionType::Ortho;\n}\n\nvoid Frustum::SetupCorners(const glm::vec3 &eyePt, const glm::vec3 &lookatPt,\n                           const glm::vec3 &upVec) {\n  corners_[0] = glm::vec3(-1.0, 1.0, 1.0);\n  corners_[1] = glm::vec3(1.0, 1.0, 1.0);\n  corners_[2] = glm::vec3(1.0, -1.0, 1.0);\n  corners_[3] = glm::vec3(-1.0, -1.0, 1.0);\n\n  corners_[4] = glm::vec3(-1.0, 1.0, -1.0);\n  corners_[5] = glm::vec3(1.0, 1.0, -1.0);\n  corners_[6] = glm::vec3(1.0, -1.0, -1.0);\n  corners_[7] = glm::vec3(-1.0, -1.0, -1.0);\n\n  const auto kView = glm::lookAt(eyePt, lookatPt, upVec);\n  const auto kProj = GetProjectionMatrix();\n  const auto kInvVP = glm::inverse(kProj * kView);\n  for (int i = 0; i < 8; i++) {\n    const auto corner = kInvVP * glm::vec4(corners_[i], 1.0f);\n    corners_[i] = glm::vec3(corner) / corner.w;\n  }\n}\n\nBSphere Frustum::ComputeBSphere() const {\n  glm::vec3 center = glm::vec3(0.0f);\n  for (int i = 0; i < 8; i++) {\n    center += corners_[i];\n  }\n  center /= 8.0f;\n\n  float radius = 0.0f;\n  for (int i = 0; i < 8; i++) {\n    float len = glm::length(corners_[i] - center);\n    radius = glm::max(radius, len);\n  }\n  radius = std::ceil(radius * 16.0f) / 16.0f;\n\n  return {center, radius};\n}\n\nglm::mat4 Frustum::GetProjectionMatrix() const {\n  if (type_ == ProjectionType::Perspective) {\n    return glm::perspective(fovy_, ar_, near_, far_);\n  } else {\n    return glm::ortho(left_, right_, bottom_, top_, near_, far_);\n  }\n}\n", "meta": {"hexsha": "2f89410f228523d1b2026468cb1b52dfb84de315", "size": 2082, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Common/View/Frustum.cc", "max_stars_repo_name": "mnrn/ReGL", "max_stars_repo_head_hexsha": "922b36716ff29fa5ed8f18c078d2369ef9fba6a9", "max_stars_repo_licenses": ["MIT"], "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/View/Frustum.cc", "max_issues_repo_name": "mnrn/ReGL", "max_issues_repo_head_hexsha": "922b36716ff29fa5ed8f18c078d2369ef9fba6a9", "max_issues_repo_licenses": ["MIT"], "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/View/Frustum.cc", "max_forks_repo_name": "mnrn/ReGL", "max_forks_repo_head_hexsha": "922b36716ff29fa5ed8f18c078d2369ef9fba6a9", "max_forks_repo_licenses": ["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.025, "max_line_length": 77, "alphanum_fraction": 0.5965417867, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.544168109334756}}
{"text": "//---------------------------------------------------------------------------\n//    $Id: theta_timestepping.cc 28377 2013-02-13 15:22:32Z heister $\n//\n//    Copyright (C) 2005-2006, 2010, 2012 by the deal.II authors\n//\n//    This file is subject to QPL and may not be  distributed\n//    without copyright and license information. Please refer\n//    to the file deal.II/doc/license.html for the  text  and\n//    further information on this license.\n//\n//---------------------------------------------------------------------------\n\n// See documentation of ThetaTimestepping for documentation of this example\n\n#include <deal.II/base/logstream.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n\n#include <deal.II/algorithms/operator.h>\n#include <deal.II/algorithms/theta_timestepping.h>\n\n#include <iostream>\n\nusing namespace dealii;\nusing namespace Algorithms;\n\n\nclass Explicit\n  : public Operator<Vector<double> >\n{\npublic:\n  Explicit(const FullMatrix<double> &matrix);\n  void operator() (NamedData<Vector<double>*> &out,\n                   const NamedData<Vector<double>*> &in);\n\n  void initialize_timestep_data(const TimestepData &);\nprivate:\n  const TimestepData *timestep_data;\n  SmartPointer<const FullMatrix<double>, Explicit> matrix;\n  FullMatrix<double> m;\n};\n\n\nclass Implicit\n  : public Operator<Vector<double> >\n{\npublic:\n  Implicit(const FullMatrix<double> &matrix);\n  void operator() (NamedData<Vector<double>*> &out,\n                   const NamedData<Vector<double>*> &in);\n\n  void initialize_timestep_data(const TimestepData &);\nprivate:\n  const TimestepData *timestep_data;\n  SmartPointer<const FullMatrix<double>, Implicit> matrix;\n  FullMatrix<double> m;\n};\n\n// End of declarations\n\nint main()\n{\n  FullMatrix<double> matrix(2);\n  matrix(0,0) = 1.;\n  matrix(1,1) = 1.;\n  matrix(0,1) = 31.4;\n  matrix(1,0) = -31.4;\n\n  OutputOperator<Vector<double> > out;\n  out.initialize_stream(std::cout);\n\n  Explicit op_explicit(matrix);\n  Implicit op_implicit(matrix);\n  ThetaTimestepping<Vector<double> > solver(op_explicit, op_implicit);\n  op_explicit.initialize_timestep_data(solver.explicit_data());\n  op_implicit.initialize_timestep_data(solver.implicit_data());\n  solver.set_output(out);\n\n  Vector<double> value(2);\n  value(0) = 1.;\n  NamedData<Vector<double>*> indata;\n  NamedData<Vector<double>*> outdata;\n  Vector<double> *p = &value;\n  outdata.add(p, \"value\");\n\n  solver.notify(Events::initial);\n  solver(outdata, indata);\n}\n\n\nExplicit::Explicit(const FullMatrix<double> &M)\n  :\n  matrix(&M)\n{\n  m.reinit(M.m(), M.n());\n}\n\n\nvoid\nExplicit::initialize_timestep_data(const TimestepData &t)\n{\n  timestep_data = &t;\n}\n\n\nvoid\nExplicit::operator() (NamedData<Vector<double>*> &out, const NamedData<Vector<double>*> &in)\n{\n  if (this->notifications.test(Events::initial) || this->notifications.test(Events::new_timestep_size))\n    {\n      m.equ(-timestep_data->step, *matrix);\n      for (unsigned int i=0; i<m.m(); ++i)\n        m(i,i) += 1.;\n    }\n  this->notifications.clear();\n  unsigned int i = in.find(\"Previous iterate\");\n  m.vmult(*out(0), *in(i));\n}\n\n\nImplicit::Implicit(const FullMatrix<double> &M)\n  :\n  matrix(&M)\n{\n  m.reinit(M.m(), M.n());\n}\n\n\nvoid\nImplicit::initialize_timestep_data(const TimestepData &t)\n{\n  timestep_data = &t;\n}\n\n\nvoid\nImplicit::operator() (NamedData<Vector<double>*> &out, const NamedData<Vector<double>*> &in)\n{\n  if (this->notifications.test(Events::initial) || this->notifications.test(Events::new_timestep_size))\n    {\n      m.equ(timestep_data->step, *matrix);\n      for (unsigned int i=0; i<m.m(); ++i)\n        m(i,i) += 1.;\n      m.gauss_jordan();\n    }\n  this->notifications.clear();\n\n  unsigned int i = in.find(\"Previous time\");\n  m.vmult(*out(0), *in(i));\n}\n\n\n", "meta": {"hexsha": "cb859b5414043eb1e78489088fb94895eb07e3b2", "size": 3728, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/doxygen/theta_timestepping.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/doxygen/theta_timestepping.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/doxygen/theta_timestepping.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 24.3660130719, "max_line_length": 103, "alphanum_fraction": 0.6566523605, "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5441681093347559}}
{"text": "\n#pragma once\n\n// #include <boost/container/pmr/monotonic_buffer_resource.hpp>\n// #include <boost/container/pmr/set.hpp>\n// #include <boost/container/pmr/unsynchronized_pool_resource.hpp>\n// #include <experimental/memory_resource>\n#include <set>\n\nnamespace perceive\n{\n//\n// Shortest path on a DAG, using sparse representations\n//\ntemplate<typename V>\ninline vector<V> shortest_path_sparse(\n    const V source,\n    const V sink,\n    std::function<real(const V& u, const V& v)> edge_weight,\n    std::function<void(const V& u, std::function<void(const V&)>)>\n        for_each_neighbour,\n    const real k_max_cost = std::numeric_limits<real>::max())\n{\n   if(source == sink) return {};\n\n   Expects(edge_weight);\n   Expects(for_each_neighbour);\n\n   using Key     = std::pair<real, V>;\n   using Compare = std::less<Key>;\n\n   // boost::container::pmr::monotonic_buffer_resource alloc(1024 * 10);\n   std::set<Key, Compare> Q;\n\n   std::unordered_map<V, V> parent_v;\n   std::unordered_map<V, real> dist_;\n\n   real max_cost = std::isfinite(k_max_cost) ? k_max_cost\n                                             : std::numeric_limits<real>::max();\n\n   auto dist = [&](const V u) {\n      auto ii = dist_.find(u);\n      return (ii == cend(dist_)) ? max_cost : ii->second;\n   };\n\n   Q.insert({0.0, source});\n   dist_[source]   = 0.0;\n   real path_score = dNAN;\n\n   while(Q.size() > 0) {\n      const V u = Q.begin()->second;\n      Q.erase(Q.begin()); // Remove element\n      if(u == sink) {\n         Expects(parent_v.find(u) != cend(parent_v));\n         break; // We're done\n      }\n      Expects(dist(u) < std::numeric_limits<real>::max());\n      const auto dist_u = dist(u);\n\n      for_each_neighbour(u, [&](const V v) {\n         const real w = edge_weight(u, v);\n         Expects(std::isfinite(w));\n         const auto dist_v = dist(v);\n         if(dist_v > dist_u + w) {\n            Q.erase({dist_v, v});\n            const auto new_dist_v = dist_u + w;\n            Q.insert({new_dist_v, v});\n            parent_v[v] = u;\n            dist_[v]    = new_dist_v;\n         }\n      });\n   }\n\n   if(parent_v.find(sink) == cend(parent_v)) return {};\n\n   // Reconstruct the path\n   vector<V> out;\n   {\n      out.reserve(Q.size() + 2);\n      out.push_back(sink);\n      while(out.back() != source) {\n         const auto ii = parent_v.find(out.back());\n         Expects(ii != cend(parent_v));\n         out.push_back(ii->second);\n      }\n      std::reverse(begin(out), end(out));\n   }\n\n   return out;\n}\n\n} // namespace perceive\n", "meta": {"hexsha": "ce986a175b5b45e72c9ed2ea47f28aaef6038076", "size": 2501, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/optimization/shortest-path.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/optimization/shortest-path.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/optimization/shortest-path.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": 26.8924731183, "max_line_length": 80, "alphanum_fraction": 0.581367453, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5441681069977097}}
{"text": "//  (C) Copyright John Maddock 2005.\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#ifndef BOOST_MATH_LOG1P_INCLUDED\r\n#define BOOST_MATH_LOG1P_INCLUDED\r\n\r\n#include <cmath>\r\n#include <math.h> // platform's ::log1p\r\n#include <boost/limits.hpp>\r\n#include <boost/math/special_functions/detail/series.hpp>\r\n\r\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\r\n#  include <boost/static_assert.hpp>\r\n#else\r\n#  include <boost/assert.hpp>\r\n#endif\r\n\r\n#ifdef BOOST_NO_STDC_NAMESPACE\r\nnamespace std{ using ::fabs; using ::log; }\r\n#endif\r\n\r\n\r\nnamespace boost{ namespace math{\r\n\r\nnamespace detail{\r\n\r\n//\r\n// Functor log1p_series returns the next term in the Taylor series\r\n// pow(-1, k-1)*pow(x, k) / k\r\n// each time that operator() is invoked.\r\n//\r\ntemplate <class T>\r\nstruct log1p_series\r\n{\r\n   typedef T result_type;\r\n\r\n   log1p_series(T x)\r\n      : k(0), m_mult(-x), m_prod(-1){}\r\n\r\n   T operator()()\r\n   {\r\n      m_prod *= m_mult;\r\n      return m_prod / ++k; \r\n   }\r\n\r\n   int count()const\r\n   {\r\n      return k;\r\n   }\r\n\r\nprivate:\r\n   int k;\r\n   const T m_mult;\r\n   T m_prod;\r\n   log1p_series(const log1p_series&);\r\n   log1p_series& operator=(const log1p_series&);\r\n};\r\n\r\n} // namespace\r\n\r\n//\r\n// Algorithm log1p is part of C99, but is not yet provided by many compilers.\r\n//\r\n// This version uses a Taylor series expansion for 0.5 > x > epsilon, which may\r\n// require up to std::numeric_limits<T>::digits+1 terms to be calculated.  It would\r\n// be much more efficient to use the equivalence:\r\n// log(1+x) == (log(1+x) * x) / ((1-x) - 1)\r\n// Unfortunately optimizing compilers make such a mess of this, that it performs\r\n// no better than log(1+x): which is to say not very well at all.\r\n//\r\ntemplate <class T>\r\nT log1p(T x)\r\n{\r\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\r\n   BOOST_STATIC_ASSERT(::std::numeric_limits<T>::is_specialized);\r\n#else\r\n   BOOST_ASSERT(std::numeric_limits<T>::is_specialized);\r\n#endif\r\n   T a = std::fabs(x);\r\n   if(a > T(0.5L))\r\n      return std::log(T(1.0) + x);\r\n   if(a < std::numeric_limits<T>::epsilon())\r\n      return x;\r\n   detail::log1p_series<T> s(x);\r\n   return detail::kahan_sum_series(s, std::numeric_limits<T>::digits + 2);\r\n}\r\n#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))\r\n// these overloads work around a type deduction bug:\r\ninline float log1p(float z)\r\n{\r\n   return log1p<float>(z);\r\n}\r\ninline double log1p(double z)\r\n{\r\n   return log1p<double>(z);\r\n}\r\ninline long double log1p(long double z)\r\n{\r\n   return log1p<long double>(z);\r\n}\r\n#endif\r\n\r\n#ifdef log1p\r\n#  ifndef BOOST_HAS_LOG1P\r\n#     define BOOST_HAS_LOG1P\r\n#  endif\r\n#  undef log1p\r\n#endif\r\n\r\n#ifdef BOOST_HAS_LOG1P\r\n#  if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901)\r\ninline float log1p(float x){ return ::log1pf(x); }\r\ninline long double log1p(long double x){ return ::log1pl(x); }\r\n#else\r\ninline float log1p(float x){ return ::log1p(x); }\r\n#endif\r\ninline double log1p(double x){ return ::log1p(x); }\r\n#endif\r\n\r\n} } // namespaces\r\n\r\n#endif // BOOST_MATH_HYPOT_INCLUDED\r\n", "meta": {"hexsha": "28e65528c4f1cc8b9c4549fac86dc0af759f960c", "size": 3144, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/special_functions/log1p.hpp", "max_stars_repo_name": "dstrigl/mcotf", "max_stars_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/math/special_functions/log1p.hpp", "max_issues_repo_name": "dstrigl/mcotf", "max_issues_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "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/math/special_functions/log1p.hpp", "max_forks_repo_name": "dstrigl/mcotf", "max_forks_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "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.152, "max_line_length": 84, "alphanum_fraction": 0.6701653944, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.544168104510545}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 1999 - 2019 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 of the deal.II distribution.\n *\n * ---------------------------------------------------------------------\n *\n * based on deal.II step-1\n * \n */\n\n\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.h>\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#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <tuple>\n\nusing namespace dealii;\n\nclass MyTuple\n{\n  std::tuple<int, int, int> Tuple;\n\npublic:\n  MyTuple(Triangulation<2> &T)\n    : Tuple(std::make_tuple(T.n_levels(), T.n_cells(), T.n_active_cells())) {}\n\n  void print()\n  {\n    std::cout << \"Number of level:\\t\" << std::get<0>(this->Tuple) << \"\\n\"\n              << \"Number of cells:\\t\" << std::get<1>(this->Tuple) << \"\\n\"\n              << \"Number of active cells:\\t\" << std::get<2>(this->Tuple) << std::endl;\n  }\n};\n\nMyTuple helper(Triangulation<2> &T) {return MyTuple(T);}\n\nvoid\ncircle_grid()\n{\n  const Point<2> center(0, 0);\n  const double   radius = 1.0;\n\n  Triangulation<2> triangulation;\n  GridGenerator::hyper_ball(triangulation, center, radius, false);\n  triangulation.refine_global(2);\n\n  std::ofstream out(\"circle_grid.svg\");\n  GridOut       grid_out;\n  grid_out.write_svg(triangulation, out);\n  std::cout << \"Grid written to circle_grid.svg\" << std::endl;\n\n  Triangulation<2> triangulation2;\n  GridGenerator::hyper_ball(triangulation2, center, radius, true);\n  triangulation2.refine_global(2);\n\n  std::ofstream out2(\"circle_grid2.svg\");\n  GridOut       grid_out2;\n  grid_out2.write_svg(triangulation2, out2);\n  std::cout << \"Grid written to circle_grid2.svg\" << std::endl;\n}\n\nvoid\nfirst_grid()\n{\n  Triangulation<2> triangulation;\n\n  GridGenerator::hyper_cube(triangulation);\n\n  std::cout << \"Number of original vertices: \" << triangulation.n_vertices()\n            << std::endl;\n\n  triangulation.refine_global(4);\n\n  std::cout << \"Numbe  r of vertices after 4 refinmentss: \"\n            << triangulation.n_vertices() << std::endl;\n\n  std::ofstream out(\"grid-1.vtk\");\n  GridOut       grid_out;\n  grid_out.write_svg(triangulation, out);\n  std::cout << \"Grid written to grid-1.vtk\" << std::endl;\n  \n  MyTuple t = helper(triangulation);\n  t.print();\n}\n\n\n\nvoid\nsecond_grid()\n{\n  Triangulation<2> triangulation;\n\n  const Point<2> center(1, 0);\n  const double   inner_radius = 0.5, outer_radius = 1.0;\n  GridGenerator::hyper_shell(\n    triangulation, center, inner_radius, outer_radius, 10);\n\n  // triangulation.reset_manifold(0);\n  /*\n  questo comando fa si che la triangolazione passi dal descrivere \n  il Manifold che aveva in precedenza (in questo caso una hyper shell)\n  al descrivere un FlatManifold\n  */\n\n\n  for (unsigned int step = 0; step < 5; ++step)\n    {\n      for (auto &cell : triangulation.active_cell_iterators())\n        {\n          for (const auto v : cell->vertex_indices())\n            {\n              const double distance_from_center =\n                center.distance(cell->vertex(v));\n\n              if (std::fabs(distance_from_center - inner_radius) <=\n                  1e-6 * inner_radius)\n                {\n                  cell->set_refine_flag();\n                  break;\n                }\n            }\n        }\n\n      triangulation.execute_coarsening_and_refinement();\n    }\n\n\n  std::ofstream out(\"grid-2.svg\");\n  GridOut       grid_out;\n  grid_out.write_svg(triangulation, out);\n\n  std::cout << \"Grid written to grid-2.vtk\" << std::endl;\n  \n  MyTuple t = helper(triangulation);\n  t.print();\n}\n\nvoid\nthird_grid()\n{\n  Triangulation<2> triangulation;\n  GridGenerator::hyper_L(triangulation, 0., 0.9);\n  /*triangulation.refine_global(1);*/\n  const Point<2> corner(0.45, 0.45);\n\n  for (unsigned int step = 0; step < 6; ++step)\n    {\n      for (auto &cell : triangulation.active_cell_iterators())\n        {\n          Point<2>     cell_center          = cell->center();\n          const double distance_from_corner = corner.distance(cell_center);\n\n          if (distance_from_corner < 1. / 3)\n            {\n              cell->set_refine_flag();\n            }\n        }\n      triangulation.execute_coarsening_and_refinement();\n    }\n\n  std::ofstream out(\"grid-3.vtk\");\n  GridOut       grid_out;\n  grid_out.write_svg(triangulation, out);\n\n  std::cout << \"Grid written to grid-3.vtk\" << std::endl;\n  \n  MyTuple t = helper(triangulation);\n  t.print();\n}\n\n\nint\nmain()\n{\n  first_grid();\n  second_grid();\n  third_grid();\n\n  circle_grid();\n}", "meta": {"hexsha": "1a7cabd4ee88508774d997026ccd0f8120ee6a7e", "size": 4955, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/step-1.cc", "max_stars_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-YuriChiucconi", "max_stars_repo_head_hexsha": "4eef83eea2faaca46a2b40c2b4c0dc8eede68a42", "max_stars_repo_licenses": ["MIT"], "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/step-1.cc", "max_issues_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-YuriChiucconi", "max_issues_repo_head_hexsha": "4eef83eea2faaca46a2b40c2b4c0dc8eede68a42", "max_issues_repo_licenses": ["MIT"], "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/step-1.cc", "max_forks_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-YuriChiucconi", "max_forks_repo_head_hexsha": "4eef83eea2faaca46a2b40c2b4c0dc8eede68a42", "max_forks_repo_licenses": ["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.4102564103, "max_line_length": 86, "alphanum_fraction": 0.6195761857, "num_tokens": 1310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.5441680923749581}}
{"text": "#include <iostream>\n#include <cassert>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> GraphTraits;\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, GraphTraits::edge_descriptor>>>>\n    Graph;\n\nvoid testcase()\n{\n  int n, m, s;\n  std::cin >> n >> m >> s;\n  assert(n >= 1 && m >= 0 && s >= 1 && s < n);\n\n  Graph G(n + 1);\n  auto source = boost::vertex(0, G), sink = boost::vertex(n, G);\n  auto add_edge = [&G](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;\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n  };\n\n  std::vector<int> num_stores_by_intersection(n, 0);\n  for (int i = 0; i < s; i++)\n  {\n    int shop_loc;\n    std::cin >> shop_loc;\n    assert(shop_loc >= 0 && shop_loc < n);\n    num_stores_by_intersection.at(shop_loc)++;\n  }\n  for (int i = 0; i < n; i++)\n  {\n    if (num_stores_by_intersection.at(i) > 0)\n    {\n      add_edge(i, sink, num_stores_by_intersection.at(i));\n    }\n  }\n\n  for (int i = 0; i < m; i++)\n  {\n    int from, to;\n    std::cin >> from >> to;\n    assert(from >= 0 && from < n && to >= 0 && to < n);\n    add_edge(from, to, 1);\n    add_edge(to, from, 1);\n  }\n\n  int flow = boost::push_relabel_max_flow(G, source, sink);\n  assert(flow >= 0 && flow <= s);\n  std::cout << (flow == s ? \"yes\\n\" : \"no\\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": "8c4c7b99730c1478ddd2139a209f3dc3cc2b8ea5", "size": 2078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-06/shopping-trip/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-06/shopping-trip/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-06/shopping-trip/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": 28.0810810811, "max_line_length": 133, "alphanum_fraction": 0.5664100096, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.5440775210141348}}
{"text": "#pragma once\n\n#include <stdbool.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <map>\n#include <random>\n#include <cmath>\n#include <numeric>\n#include <stack>\n#include <assert.h>\n#include <tgmath.h>\n#include <algorithm>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing Mat = Eigen::Array<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\nusing Vec = Eigen::ArrayXf;\n\n/** This class represents both a decision node and a leaf (when bestPred==-1) in a decision tree. */\nclass Node {\npublic:\n    struct Node *left, *right;\n    int start;    // observation index into tree's data rows where this node's samples start\n    int nrows;    // number of rows beyond start index of tree's data rows associated with this node\n    int cutcol;   // which column/variable/feature to test if decision node; -1 indicates leaf\n    float cutval; // split value for cutcol\n    float value;  // prediction value (set even for internal decision nodes)\n    float gini;   // uncertainty/impurity of this node\n\n    Node(int start, int nrows, Node *parent);\n    bool isTerminal();\n};\n\nclass FastTree;\n\nclass FastForest {\npublic:\n    int NTREE = 5, MIN_NODE = 25;\n    const float sampleFraction = 0.8; // fraction of rows to extract from training set to train each tree\n    const float PROP_OOB = 0.5;\n\n    Mat X; // all training feature vectors, one row per observation\n    Vec y; // all training target values, one per observation\n    int nrows, ncols;\n\n    FastTree **trees;\n\n    FastForest(Mat X, Vec y);\n    void build();\n    FastTree *getTree(int i);\n    Vec predict(Mat X);\n};\n\nstruct CandidateInfo {\n    float leftTarget;    // sum of all target values for observations where X[cutcol] < cutval\n    float leftSqrTarget; // sum of square of target values to left of cutval\n    int leftCount;       // how many observations fall to the left of cutval\n    int cutcol;          // which feature/column this candidate tests\n    float cutval;        // which split value this candidate tests\n\n    CandidateInfo() { leftSqrTarget = leftTarget = leftCount = 0; }\n};\n\nclass FastTree {\npublic:\n    const int MAXN = 160, CUTOFF_DIVISOR = 10;\n\n    FastForest* parent;\n    default_random_engine* rng; // single random num generator used by code building this tree\n    int nrows, ncols;\n    float *y;  // subset size nrows of forest's X rows used to train this tree\n    float **X; // subset size nrows of forest's y rows used to train this tree (array of ptrs to float)\n    int *idxs; // nrows indexes into forest's X/y training observations\n    Node *root;\n\n    FastTree(FastForest* parent);\n    float predict(Vec X);\n    void shuffle();\n\nprotected:\n    void createIdxsAndOob(float *Xall, float *yall);\n    void buildNodes();\n    void bestCutoff(Node *node);\n    void checkCutoffs(int start, int n, CandidateInfo *candInfo, int ncandidates);\n    bool allSame(Node *node);\n    static float wgtGini(float leftTarget, float leftSqrTarget, float leftCount,\n                         float sumTarget, float sumSqrTarget, float totCount);\n    int partition(Node *node);\n};\n\nFastForest *trainFF(Mat X, Vec y);\n\ntemplate <typename T> double stdev(T b, T e);\nfloat loss_(float sumTarget, float sumSqrTarget, float n);\n\n", "meta": {"hexsha": "1e54934f3cb32e0dd01e563b3cf240fd139a1915", "size": 3244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fastforest.hpp", "max_stars_repo_name": "fastai/fastforest", "max_stars_repo_head_hexsha": "210e02757962517d2331ddb762e8b4d500a7c75c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T02:51:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-05T21:14:56.000Z", "max_issues_repo_path": "fastforest.hpp", "max_issues_repo_name": "fastai/fastforest", "max_issues_repo_head_hexsha": "210e02757962517d2331ddb762e8b4d500a7c75c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T04:13:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-04T21:59:06.000Z", "max_forks_repo_path": "fastforest.hpp", "max_forks_repo_name": "fastai/fastforest", "max_forks_repo_head_hexsha": "210e02757962517d2331ddb762e8b4d500a7c75c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-02-24T20:47:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-25T03:02:11.000Z", "avg_line_length": 32.44, "max_line_length": 105, "alphanum_fraction": 0.6923551171, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5440306000703151}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 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#include <boost/simd/function/scalar/correct_fma.hpp>\n#include <boost/simd/function/std.hpp>\n#include <simd_test.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/constant/valmax.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/function/oneplus.hpp>\n#include <cmath>\n\nSTF_CASE_TPL (\" correct_fma real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n\n  using bs::correct_fma;\n\n  // return type conformity test\n  STF_EXPR_IS(correct_fma(T(),T(),T()), T);\n\n  // specific values tests\n#ifndef STF_NO_INVALIDS\n  STF_EQUAL(correct_fma(bs::Inf<T>(), bs::Inf<T>(), bs::Inf<T>()), bs::Inf<T>());\n  STF_IEEE_EQUAL(correct_fma(bs::Minf<T>(), bs::Minf<T>(), bs::Minf<T>()), bs::Nan<T>());\n  STF_IEEE_EQUAL(correct_fma(bs::Nan<T>(), bs::Nan<T>(), bs::Nan<T>()), bs::Nan<T>());\n#endif\n  STF_EQUAL(correct_fma(bs::Mone<T>(), bs::Mone<T>(), bs::Mone<T>()), bs::Zero<T>());\n  STF_EQUAL(correct_fma(bs::One<T>(), bs::One<T>(), bs::One<T>()), bs::Two<T>());\n  STF_EQUAL(correct_fma(bs::One<T>()+bs::Eps<T>(), bs::One<T>()-bs::Eps<T>(),bs::Mone<T>()), -bs::Eps<T>()*bs::Eps<T>());\n  STF_EQUAL(correct_fma(bs::Zero<T>(), bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n#ifndef  STF_DONT_CARE_CORRECT_FMA_OVERFLOW\n  STF_EQUAL(correct_fma(bs::Valmax<T>(), bs::Two<T>(), -bs::Valmax<T>()), bs::Valmax<T>());\n#endif\n} // end of test for floating_\n\nSTF_CASE_TPL (\" correct_fma signed_int\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n\n  using bs::correct_fma;\n\n  // return type conformity test\n\n  STF_EXPR_IS(correct_fma(T(),T(),T()), T);\n\n  // specific values tests\n  STF_EQUAL(correct_fma(bs::Mone<T>(), bs::Mone<T>(), bs::Mone<T>()), bs::Zero<T>());\n  STF_EQUAL(correct_fma(bs::One<T>(), bs::One<T>(), bs::One<T>()), bs::Two<T>());\n  STF_EQUAL(correct_fma(bs::Zero<T>(), bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n  STF_EQUAL(correct_fma(bs::Valmax<T>(), bs::Two<T>(), bs::oneplus(bs::Valmin<T>())), bs::Valmax<T>());\n} // end of test for signed_int_\n\nSTF_CASE_TPL (\" correct_fma unsigned_int\",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n\n  using bs::correct_fma;\n\n  // return type conformity test\n  STF_EXPR_IS(correct_fma(T(),T(),T()), T);\n\n  // specific values tests\n  STF_EQUAL(correct_fma(bs::One<T>(), bs::One<T>(), bs::One<T>()), bs::Two<T>());\n  STF_EQUAL(correct_fma(bs::Zero<T>(), bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n} // end of test for unsigned_int_\n\nSTF_CASE_TPL (\" correct_fma std real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n\n  using bs::correct_fma;\n\n  // return type conformity test\n  STF_EXPR_IS(correct_fma(T(),T(),T()), T);\n\n  // specific values tests\n#ifndef STF_NO_INVALIDS\n  STF_EQUAL( bs::std_(correct_fma)(bs::Inf<T>(), bs::Inf<T>(), bs::Inf<T>()), bs::Inf<T>());\n  STF_IEEE_EQUAL( bs::std_(correct_fma)(bs::Minf<T>(), bs::Minf<T>(), bs::Minf<T>()), bs::Nan<T>());\n  STF_IEEE_EQUAL( bs::std_(correct_fma)(bs::Nan<T>(), bs::Nan<T>(), bs::Nan<T>()), bs::Nan<T>());\n#endif\n  STF_EQUAL( bs::std_(correct_fma)(bs::Mone<T>(), bs::Mone<T>(), bs::Mone<T>()), bs::Zero<T>());\n  STF_EQUAL( bs::std_(correct_fma)(bs::One<T>(), bs::One<T>(), bs::One<T>()), bs::Two<T>());\n  STF_EQUAL( bs::std_(correct_fma)(bs::One<T>()+bs::Eps<T>(), bs::One<T>()-bs::Eps<T>(),bs::Mone<T>()), -bs::Eps<T>()*bs::Eps<T>());\n  STF_EQUAL( bs::std_(correct_fma)(bs::Zero<T>(), bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n  STF_EQUAL( bs::std_(correct_fma)(bs::Valmax<T>(), bs::Two<T>(), -bs::Valmax<T>()), bs::Valmax<T>());\n} // end of test for floating_\n", "meta": {"hexsha": "712e87129ad64a22998491280787abd92fdb85ce", "size": 4186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/correct_fma.cpp", "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": "test/function/scalar/correct_fma.cpp", "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": "test/function/scalar/correct_fma.cpp", "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": 41.0392156863, "max_line_length": 132, "alphanum_fraction": 0.6091734353, "num_tokens": 1299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5440306000703149}}
{"text": "//  (C) Copyright Raffi Enficiaud 2014.\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 dataset_example64\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n\nnamespace bdata = boost::unit_test::data;\n\n\nBOOST_DATA_TEST_CASE( \n  test1, \n  bdata::xrange(2) * bdata::xrange(3), \n  xr1, xr2)\n{\n  std::cout << \"test 1: \" << xr1 << \", \" << xr2 << std::endl;\n  BOOST_TEST((xr1 <= 2 && xr2 <= 3));\n}\n\nBOOST_DATA_TEST_CASE( \n  test2, \n  bdata::xrange(3)\n  *\n  ( bdata::random( \n      bdata::distribution=std::uniform_real_distribution<float>(1, 2)) \n    ^ bdata::xrange(2) \n  ),  \n  xr, random_sample, index)\n{\n  std::cout << \"test 2: \" \n    << xr << \" / \" \n    << random_sample << \", \" << index\n    << std::endl;\n  BOOST_TEST(random_sample < 1.7); // 30% chance of failure\n}\n//]\n", "meta": {"hexsha": "048079384690213e13e42b80135c5e882c354c23", "size": 1069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/test/doc/examples/dataset_example64.run-fail.cpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "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": "libs/test/doc/examples/dataset_example64.run-fail.cpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "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/test/doc/examples/dataset_example64.run-fail.cpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "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": 24.8604651163, "max_line_length": 71, "alphanum_fraction": 0.6454630496, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5440305984532324}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_SDK_MEMORY_IS_POWER_OF_2_HPP_INCLUDED\n#define BOOST_SIMD_SDK_MEMORY_IS_POWER_OF_2_HPP_INCLUDED\n\n/*!\n  @file\n  @brief Defines the boost::simd::is_power_of_2 function\n**/\n\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd\n{\n  /*!\n    @brief Checks if a given value is a power of 2\n\n    @param value Value to test\n    @return @c true if value is a non-zero power of 2, @c false otherwise.\n  **/\n  template<class T> BOOST_FORCEINLINE bool is_power_of_2(T value)\n  {\n    return (!(value & (value - 1)) && value);\n  }\n} }\n\n#endif\n", "meta": {"hexsha": "e32390637d67f554cd35c853813574b7b32fbeea", "size": 1076, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/include/boost/simd/sdk/memory/is_power_of_2.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/boost/simd/sdk/include/boost/simd/sdk/memory/is_power_of_2.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/sdk/include/boost/simd/sdk/memory/is_power_of_2.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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.6470588235, "max_line_length": 80, "alphanum_fraction": 0.5687732342, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645725, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.544030596595578}}
{"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., 2., 3.}, {4., 5., 6.}, {7., 8., 9.}};\n    dense2D<double>  A(array), B2, B3;\n\n    // Creating a reordering matrix from a vector (or an array respectively)\n    int indices[]= {2, 1};\n    mat::traits::reorder<>::type R= mat::reorder(indices);\n    std::cout << \"\\nR =\\n\" << R;    \n\n    // Reorder rows\n    B2= R * A;\n    std::cout << \"\\nR * A =\\n\" << B2;\n    \n    // Reorder columns\n    B3= B2 * trans(R);\n    std::cout << \"\\nB2 * trans(R) =\\n\" << B3;\n    \n    dense_vector<double> v(array[2]), w(R * v);\n    std::cout << \"\\nR * v =\\n\" << w << \"\\n\";\n    \n    return 0;\n}\n", "meta": {"hexsha": "7e63b1f4cadf24094f7627f49cccad3e6aaf6287", "size": 715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/reorder.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/reorder.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/reorder.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.6551724138, "max_line_length": 76, "alphanum_fraction": 0.4965034965, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5440305949784957}}
{"text": "#include <boost/mpl/vector_c.hpp>\n#include <boost/mpl/integral_c.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/find.hpp>\n#include <boost/mpl/size.hpp>\n#include <boost/mpl/less.hpp>\n#include <boost/mpl/if.hpp>\n\nint main()\n{\n    using v1 = boost::mpl::vector_c<int, 5, 2, 3, 1, 4>;\n    using it1 = boost::mpl::find<v1, boost::mpl::integral_c<int, 3>>::type;\n    using index1 = it1::pos;\n    using size1 = boost::mpl::size<v1>::type;\n    using in_v1 = boost::mpl::less<index1, size1>::type;\n    constexpr int r1{ boost::mpl::if_<in_v1, index1, boost::mpl::int_<-1>>::type::value };\n    static_assert(r1 == 2);\n\n    using v2 = boost::mpl::vector_c<int, 5, 2, 3>;\n    using it2 = boost::mpl::find<v2, boost::mpl::integral_c<int, 6>>::type;\n    using index2 = it2::pos;\n    using size2 = boost::mpl::size<v2>::type;\n    using in_v2 = boost::mpl::less<index2, size2>::type;\n    constexpr int r2{ boost::mpl::if_<in_v2, index2, boost::mpl::int_<-1>>::type::value };\n    static_assert(r2 == -1);\n}\n", "meta": {"hexsha": "7d9b6a025aabf052533596ee4f5b16b5d89405fa", "size": 997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "12_boost_mpl_find_minus_one/12_boost_mpl_find_minus_one.cpp", "max_stars_repo_name": "BorisSchaeling/boost-meta-programming", "max_stars_repo_head_hexsha": "efdd64c8fdbc394bf6572fc10a84a9020581b6d5", "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": "12_boost_mpl_find_minus_one/12_boost_mpl_find_minus_one.cpp", "max_issues_repo_name": "BorisSchaeling/boost-meta-programming", "max_issues_repo_head_hexsha": "efdd64c8fdbc394bf6572fc10a84a9020581b6d5", "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": "12_boost_mpl_find_minus_one/12_boost_mpl_find_minus_one.cpp", "max_forks_repo_name": "BorisSchaeling/boost-meta-programming", "max_forks_repo_head_hexsha": "efdd64c8fdbc394bf6572fc10a84a9020581b6d5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-03T08:29:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-29T08:42:49.000Z", "avg_line_length": 36.9259259259, "max_line_length": 90, "alphanum_fraction": 0.6379137412, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5440305933614131}}
{"text": "/*******************************************************************************\n *\n * Standard domain of numerical congruences extended with bitwise\n * operations.\n *\n * Author: Alexandre C. D. Wimmers (alexandre.c.wimmers@nasa.gov)\n *\n * Contributors: Jorge A. Navas (jorge.a.navaslaserna@nasa.gov)\n *\n * Notices:\n *\n * Copyright (c) 2011 United States Government as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * All Rights Reserved.\n *\n * Disclaimers:\n *\n * No Warranty: THE SUBJECT SOFTWARE IS PROVIDED \"AS IS\" WITHOUT ANY WARRANTY OF\n * ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED\n * TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS,\n * ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,\n * OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE\n * ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO\n * THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN\n * ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS,\n * RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS\n * RESULTING FROM USE OF THE SUBJECT SOFTWARE.  FURTHER, GOVERNMENT AGENCY\n * DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE,\n * IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT \"AS IS.\"\n *\n * Waiver and Indemnity:  RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST\n * THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL\n * AS ANY PRIOR RECIPIENT.  IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS\n * IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH\n * USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM,\n * RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD\n * HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS,\n * AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW.\n * RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE,\n * UNILATERAL TERMINATION OF THIS AGREEMENT.\n *\n ******************************************************************************/\n\n#pragma once\n\n#include <crab/common/types.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/domains/separate_domains.hpp>\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/backward_assign_operations.hpp>\n#include <crab/domains/interval.hpp>\n\n#include <boost/optional.hpp>\n\nnamespace ikos {\n\ntemplate <typename Number> \nclass congruence {\n  typedef interval<Number> interval_t;\n  \npublic:\n  typedef congruence<Number> congruence_t;\n\nprivate:\n  bool _is_bottom;\n  \n  /// A congruence is denoted by aZ + b, where b \\in Z and a \\in N.\n  /// The abstract state aZ + b represents all numbers that are\n  /// congruent to b modulo a.\n  Number _a; // modulo\n  Number _b; // remainder\n\n  // Notes about the % operator\n  // \n  // The semantics of r = n % d is to set r to \"n mod d\". The sign of\n  // the d is ignored and r is always non-negative.\n  // \n  // We assume that n % d (also n /d) raises a runtime error if d==0.\n  \n  void normalize(void) {\n    // Set to standard form: 0 <= b < a for a != 0\n    if (_a != 0) {\n      _b = _b % _a;\n    }\n  }\n  \n  // if true then top (1Z + 0) else bottom\n  congruence(bool b): _is_bottom(!b), _a(1), _b(0) {}\n\n  congruence(int n): _is_bottom(false), _a(0), _b(n) {}\n\n  congruence(Number a, Number b)\n    : _is_bottom(false),\n      _a(a),\n      _b(b) {\n    normalize();\n  }\n\n  Number abs(Number x) const { return x < 0 ? -x : x; }\n\n  Number max(Number x, Number y) const { return x.operator<=(y) ? y : x; }\n\n  Number min(Number x, Number y) const { return x.operator<(y) ? x : y; }\n\n  Number gcd(Number x, Number y, Number z) const  { return gcd(x, gcd(y, z)); }\n  // Not to be called explicitly outside of gcd\n  Number gcd_helper(Number x, Number y) const {\n    return (y == 0) ? x : gcd_helper(y, x % y);\n  }  \n  Number gcd(Number x, Number y) const { return gcd_helper(abs(x), abs(y)); }\n\n  Number lcm(Number x, Number y) const {\n    Number tmp = gcd(x, y);\n    return abs(x * y) / tmp;\n  }\n\n  bool is_zero() const {\n    return !is_bottom() && _a == 0 && _b == 0;\n  }\n\n  bool all_ones() const {\n    return !is_bottom() && _a == 0 && _b == -1;\n  }\n\n  interval_t to_interval() const {\n    assert(singleton());\n    return interval_t(*(singleton()));\n  }\n  \npublic:\n  \n  static congruence_t top() { return congruence(true); }\n\n  static congruence_t bottom() { return congruence(false); }\n\n  congruence(): _is_bottom(false), _a(1), _b(0) {}\n\n  congruence(Number n): _is_bottom(false), _a(0), _b(n) {}\n\n  congruence(const congruence_t& o)\n      : _is_bottom(o._is_bottom), _a(o._a), _b(o._b) {}\n\n  congruence_t operator=(congruence_t o) {\n    _is_bottom = o._is_bottom;\n    _a = o._a;\n    _b = o._b;\n    return *this;\n  }\n\n  bool is_bottom() const { return _is_bottom; }\n\n  bool is_top() const { return _a == 1; }\n\n  boost::optional<Number> singleton() const {\n    if (!this->is_bottom() && _a == 0) {\n      return boost::optional<Number>(_b);\n    } else {\n      return boost::optional<Number>();\n    }\n  }\n\n  Number get_modulo() const { return _a;}\n\n  Number get_remainder() const { return _b;}\n  \n  bool operator==(congruence_t o) const {\n    return (is_bottom() == o.is_bottom() && _a == o._a && _b == o._b) ;\n  }\n\n  bool operator!=(congruence_t x) const { return !this->operator==(x); }\n\n  /** Lattice Operations **/\n  \n  bool operator<=(congruence_t o) {\n    if (is_bottom()) {\n      return true;\n    } else if (o.is_bottom()) {\n      return false;\n    } else if (_a == 0 && o._a == 0) {\n      return  (_b == o._b);\n    } else if (_a == 0) {\n      if ((_b % o._a) == (o._b % o._a)) {\n        return true;\n      }\n    } else if (o._a == 0) {\n      if (_b % _a == (o._b % _a)) {\n        return false;\n      }\n    }\n    return (_a % o._a == 0) && (_b % o._a == o._b % o._a);\n  }\n\n  congruence_t operator|(congruence_t o) {\n    if (is_bottom()) {\n      return o;\n    } else if (o.is_bottom()) {\n      return *this;\n    } else if (is_top() || o.is_top()) {\n      return top();\n    } else {\n      return congruence_t(gcd(_a, o._a, abs(_b - o._b)), min(_b, o._b));\n    }\n  }\n\n  congruence_t operator&(congruence_t o) {\n    if (is_bottom() || o.is_bottom()) {\n      return bottom();\n    }\n\n    // lcm has meaning only if both a and o.a are not 0\n    if (_a == 0 && o._a == 0) {\n      if (_b == o._b) {\n        return *this;\n      } else {\n        return bottom();\n      }\n    } else if (_a == 0) {\n      // b & a'Z + b' iff \\exists k such that a'*k + b' = b iff ((b - b') %a' == 0)\n      if ((_b - o._b) % o._a == 0) {\n        return *this;\n      } else {\n        return bottom();\n      }\n    } else if (o._a == 0) {\n      // aZ+b & b' iff \\exists k such that a*k+b  = b' iff ((b'-b %a) == 0)\n      if ((o._b - _b) % _a == 0) {\n        return o;\n      } else {\n        return bottom();\n      }\n    } else {\n      // pre: a and o.a != 0\n      Number x = gcd(_a, o._a);\n      if (_b % x == (o._b % x)) {\n        // the part max(b,o.b) needs to be verified. What we really\n        // want is to find b'' such that\n        // 1) b'' % lcm(a,a') == b  % lcm(a,a'), and\n        // 2) b'' % lcm(a,a') == b' % lcm(a,a').\n        // An algorithm for that is provided in Granger'89.\n        return congruence_t(lcm(_a, o._a), max(_b, o._b));\n      } else {\n        return congruence_t::bottom();\n      }\n    }\n\n  }\n\n  congruence_t operator||(congruence_t o) {\n    // Equivalent to join, domain is flat\n    return *this | o;\n  }\n\n  congruence_t operator&&(congruence_t o) {\n    // Simply refines top element\n    return (is_top()) ? o : *this;\n  }\n\n  /** Arithmetic Operators **/\n\n  congruence_t operator+(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else\n      return congruence_t(gcd(_a, o._a), _b + o._b);\n  }\n\n  congruence_t operator-(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else\n      return congruence_t(gcd(_a, o._a), _b - o._b);\n  }\n\n  congruence_t operator-() {\n    if (this->is_bottom() || this->is_top())\n      return *this;\n    else\n      return congruence_t(_a, -_b + _a);\n  }\n\n  congruence_t operator*(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if ((this->is_top() || o.is_top()) && _a != 0 && o._a != 0)\n      return congruence_t::top();\n    else\n      return congruence_t(gcd(_a * o._a, _a * o._b, o._a * _b), _b * o._b);\n  }\n\n  // signed division\n  congruence_t operator/(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (o == congruence(0))\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n\n      /*\n         aZ+b / 0Z+b':\n            if b'|a then  (a/b')Z + b/b'\n            else          top\n      */      \n      if (o._a == 0) {\n        if (_a % o._b == 0)\n          return congruence_t(_a / o._b, _b / o._b);\n        else\n          return congruence_t::top();\n      }\n\n      /*\n         0Z+b / a'Z+b':\n            if N>0   (b div N)Z + 0\n            else     0Z + 0\n\n           where N = a'((b-b') div a') + b'\n      */\n      if (_a == 0) {\n        Number n(o._a * (((_b - o._b) / o._a) + o._b));\n        if (n > 0) {\n          return congruence_t(_b / n, 0);\n        } else {\n          return congruence_t(0, 0);\n        }\n      }\n\n      /*\n        General case: no singleton\n      */\n      return congruence_t::top();\n    }\n  }\n\n  // signed remainder operator\n  congruence_t operator%(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (o == congruence(0))\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n      /*\n         aZ+b mod 0Z+b':\n             if b'|a then  (a/b')Z + b/b'\n             else          top\n      */\n      if (o._a == 0) {\n        if (_a % o._b == 0) {\n          return congruence_t(0, _b % o._b);\n        } else {\n          return congruence_t(gcd(_a, o._b), _b);\n        }\n      }\n\n      /*\n          0Z+b mod a'Z+b':\n           if N<=0           then 0Z+b\n           if (b div N) == 1 then gcd(b',a')Z + b\n           if (b div N) >= 2 then N(b div N)Z  + b\n\n         where N = a'((b-b') div a') + b'\n      */\n      if (_a == 0) {\n        Number n(o._a * (((_b - o._b) / o._a) + o._b));\n        if (n <= 0) {\n          return congruence_t(_a, _b);\n        } else if (_b == n) {\n          return congruence_t(gcd(o._b, o._a), _b);\n        } else if ((_b / n) >= 2) {\n          return congruence_t(_b, _b);\n        } else {\n          CRAB_ERROR(\"unreachable\");\n        }\n      }\n      \n      /*\n          general case: no singleton\n      */\n      return congruence_t(gcd(_a, o._a, o._b), _b);\n    }\n  }\n\n  /** \n      Bitwise operators.\n      They are very imprecise because we ignore bitwidth. \n      \n      Bitwise operation can be implemented more precisely based on\n      Stefan Bygde's paper: Static WCET analysis based on abstract\n      interpretation and counting of elements, Vasteras : School of\n      Innovation, Design and Engineering, Malardalen University (2010).\n   **/\n  \n  congruence_t And(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n      if (is_zero() || o.is_zero()) {\n\treturn congruence_t(0);\n      } else if (all_ones()) {\n\treturn o;\n      } else if (o.all_ones()) {\n\treturn *this;\n      } else if (_a == 0 && o._a == 0) {\n\treturn congruence_t(_b & o._b);\n      } else {\n\treturn top();\n      }      \n    }\n  }\n\n  congruence_t Or(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n      if (all_ones() || o.all_ones()) {\n\treturn congruence_t(-1);\n      } else if (is_zero()) {\n\treturn o;\n      } else if (o.is_zero()) {\n\treturn *this;\n      } else if (_a == 0 && o._a == 0) {\n\treturn congruence_t(_b | o._b);\n      } else {\n\treturn top();\n      }      \n    }    \n  }\n\n  congruence_t Xor(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n      if (is_zero()) {\n\treturn o;\n      } else if (o.is_zero()) {\n\treturn *this;\n      } else if (_a == 0 && o._a == 0) {\n\treturn congruence_t(_b ^ o._b);\n      } else {\n\treturn top();\n      }      \n    }    \n  }\n\n  congruence_t Shl(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n      \n      if (o._a == 0) { // singleton\n\n\tif (o._b < 0) {\n\t  return bottom();\n\t}\n\t\n        // aZ + b << 0Z + b'  = (a*2^b')Z + b*2^b'\n        Number x = Number(1) << o._b;\n        return congruence_t(_a * x, _b * x);\n      } else {\n\t\n        Number x = Number(1) << o._b;\n        Number y = Number(1) << o._a;\n        // aZ + b << a'Z + b' = (gcd(a, b * (2^a' - 1)))*(2^b')Z + b*(2^b')\n        return congruence_t(gcd(_a, _b * (y - 1)) * x, _b * x);\n      }\n    }\n  }\n\n  congruence_t AShr(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n\n      if (o._a == 0) { // singleton\n\t// aZ + b >> 0Z + b'\n\tif (o._b < 0) {\n\t  return congruence_t::bottom();\n\t}\n      }\n\n      if (singleton() && o.singleton()) {\n\tinterval_t res = to_interval().AShr(o.to_interval());\n\tif (boost::optional<Number> n = res.singleton()) {\n\t  return congruence(*n);\n\t}\n      }\n      \n      return congruence_t::top();\n    }\n  }\n\n  congruence_t LShr(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n\n      if (o._a == 0) { \n\t// aZ + b >> 0Z + b'\n\tif (o._b < 0) {\n\t  return congruence_t::bottom();\n\t}\n      }\n\n      if (singleton() && o.singleton()) {\n\tinterval_t res = to_interval().LShr(o.to_interval());\n\tif (boost::optional<Number> n = res.singleton()) {\n\t  return congruence(*n);\n\t}\n      }\n\n      return congruence_t::top();\n    }\n  }\n\n  // division and remainder operations\n\n  congruence_t SDiv(congruence_t x) { return this->operator/(x); }\n\n  congruence_t UDiv(congruence_t x) { return congruence_t::top(); }\n\n  congruence_t SRem(congruence_t x) { return this->operator%(x); }\n\n  congruence_t URem(congruence_t x) { return congruence_t::top(); }\n\n\n  void write(crab::crab_os& o) const {\n    if (is_bottom()) {\n      o << \"_|_\";\n      return;\n    }\n\n    if (_a == 0) {\n      o << _b;\n      return;\n    }\n    \n    o << _a << \"Z+\" << _b;\n    \n  }\n}; // end class congruence\n\ntemplate<typename Number>\ninline crab::crab_os& operator<<(crab::crab_os& o, const congruence<Number>& c) {\n  c.write(o);\n  return o;\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator+(\n    Number c, congruence<Number> x) {\n  return congruence<Number>(c) + x;\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator+(\n    congruence<Number> x, Number c) {\n  return x + congruence<Number>(c);\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator*(\n    Number c, congruence<Number> x) {\n  return congruence<Number>(c) * x;\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator*(\n    congruence<Number> x, Number c) {\n  return x * congruence<Number>(c);\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator/(\n    Number c, congruence<Number> x) {\n  return congruence<Number>(c) / x;\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator/(\n    congruence<Number> x, Number c) {\n  return x / congruence<Number>(c);\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator-(\n    Number c, congruence<Number> x) {\n  return congruence<Number>(c) - x;\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator-(\n    congruence<Number> x, Number c) {\n  return x - congruence<Number>(c);\n}\n\ntemplate <typename Number,\n\t  typename VariableName,\n\t  typename CongruenceCollection>\nclass equality_congruence_solver {\n  // TODO: check correctness of the solver. Granger provides a sound\n  // and more precise solver for equality linear congruences (see\n  // Theorem 4.4).\nprivate:\n  typedef congruence<Number> congruence_t;\n  typedef variable<Number, VariableName> variable_t;\n  typedef linear_expression<Number, VariableName> linear_expression_t;\n  typedef linear_constraint<Number, VariableName> linear_constraint_t;\n  typedef linear_constraint_system<Number, VariableName>\n      linear_constraint_system_t;\n\n  typedef std::vector<linear_constraint_t> cst_table_t;\n  typedef typename linear_constraint_t::variable_set_t variable_set_t;\n\n  std::size_t m_max_cycles;\n  bool m_is_contradiction;\n  cst_table_t m_cst_table;\n  variable_set_t m_refined_variables;\n  std::size_t m_op_count;\n\nprivate:\n  bool refine(variable_t v, congruence_t i, \n              CongruenceCollection& env) {\n    congruence_t old_i = env[v];\n    congruence_t new_i = old_i & i;\n    if (new_i.is_bottom()) {\n      return true;\n    }\n    if (old_i != new_i) {\n      env.set(v, new_i);\n      m_refined_variables += v;\n      ++(m_op_count);\n    }\n    return false;\n  }\n\n  congruence_t compute_residual(linear_constraint_t cst,\n                                variable_t pivot,\n                                CongruenceCollection& env) {\n    congruence_t residual(cst.constant());\n    for (typename linear_constraint_t::iterator it = cst.begin();\n         it != cst.end();\n         ++it) {\n      variable_t v = it->second;\n      if (!(v == pivot)) {\n        residual = residual - (it->first * env[v]);\n        ++(m_op_count);\n      }\n    }\n    return residual;\n  }\n\n  bool propagate(linear_constraint_t cst, CongruenceCollection& env) {\n    for (typename linear_constraint_t::iterator it = cst.begin();\n         it != cst.end();\n         ++it) {\n      Number c = it->first;\n      variable_t pivot = it->second;\n      congruence_t rhs =\n          compute_residual(cst, pivot, env) / congruence_t(c);\n\n      if (cst.is_equality()) {\n        if (refine(pivot, rhs, env)) {\n\t  return true;\n\t}\n      } else if (cst.is_inequality() || cst.is_strict_inequality()) {\n        // Inequations (>=, <=, >, and <) do not work well with\n        // congruences because for any number n there is always x and y\n        // \\in gamma(aZ+b) such that n < x and n > y.\n        //\n        // The only cases we can catch is when all the expressions\n        // are constants. We do not bother because any product\n        // with intervals or constants should get those cases.\n        continue;\n      } else {\n        // TODO: cst is a disequation \n      }\n    }\n    return false;\n  }\n\n  bool solve_system(CongruenceCollection& env) {\n    std::size_t cycle = 0;\n    do {\n      ++cycle;\n      m_refined_variables.clear();\n      for (typename cst_table_t::iterator it = m_cst_table.begin();\n           it != m_cst_table.end();\n           ++it) {\n        if (propagate(*it, env)) {\n\t  return true;\n\t}\n      }\n    } while (m_refined_variables.size() > 0 && \n             cycle <= m_max_cycles);\n    return false;\n  }\n\npublic:\n  equality_congruence_solver(linear_constraint_system_t csts,\n                             std::size_t max_cycles)\n      : m_max_cycles(max_cycles), m_is_contradiction(false) {\n    for (typename linear_constraint_system_t::iterator it = csts.begin();\n         it != csts.end();\n         ++it) {\n      linear_constraint_t cst = *it;\n      if (cst.is_contradiction()) {\n        m_is_contradiction = true;\n        return;\n      } else if (cst.is_tautology()) {\n        continue;\n      } else {\n        m_cst_table.push_back(cst);\n      }\n    }\n  }\n\n  void run(CongruenceCollection& env) {\n    if (m_is_contradiction) {\n      env.set_to_bottom();\n    } else {\n      if (solve_system(env)) {\n\tenv.set_to_bottom();\n      }\n    }\n  }\n\n}; // class equality_congruence_solver\n\ntemplate <typename Number, typename VariableName>\nclass congruence_domain final:\n  public crab::domains::abstract_domain<congruence_domain<Number,VariableName>> {\npublic:\n  typedef congruence<Number> congruence_t;\n\nprivate:\n  // note that this is assuming that all variables have the same bit\n  // width which is unrealistic.\n  typedef congruence_domain<Number, VariableName>\n  congruence_domain_t;\n  typedef crab::domains::abstract_domain<congruence_domain_t>\n  abstract_domain_t;\n\npublic:\n  using typename abstract_domain_t::linear_expression_t;\n  using typename abstract_domain_t::linear_constraint_t;\n  using typename abstract_domain_t::linear_constraint_system_t;\n  using typename abstract_domain_t::disjunctive_linear_constraint_system_t;   \n  using typename abstract_domain_t::variable_t;\n  using typename abstract_domain_t::variable_vector_t;\n  typedef Number number_t;\n  typedef VariableName varname_t;\n  using typename abstract_domain_t::pointer_constraint_t;\n\nprivate:\n  typedef separate_domain<variable_t, congruence_t> separate_domain_t;\n  typedef equality_congruence_solver<number_t, varname_t,\n\t\t\t\t     separate_domain_t> solver_t;\n\npublic:\n  typedef typename separate_domain_t::iterator iterator;\n\nprivate:\n  separate_domain_t _env;\n\nprivate:\n  congruence_domain(separate_domain_t env) : _env(env) {}\n\npublic:\n  void set_to_top() {\n    congruence_domain abs(separate_domain_t::top());\n    std::swap(*this, abs);\n  }\n\n  void set_to_bottom() {\n    congruence_domain abs(separate_domain_t::bottom());\n    std::swap(*this, abs);\n  }\n\n  congruence_domain() : _env(separate_domain_t::top()) {}\n\n  congruence_domain(const congruence_domain_t& e)\n      : _env(e._env) {\n    crab::CrabStats::count(getDomainName() + \".count.copy\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n  }\n\n  congruence_domain_t& operator=(const congruence_domain_t& o) {\n    crab::CrabStats::count(getDomainName() + \".count.copy\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n    if (this != &o)\n      this->_env = o._env;\n    return *this;\n  }\n\n  iterator begin() { return this->_env.begin(); }\n\n  iterator end() { return this->_env.end(); }\n\n  bool is_bottom() { return this->_env.is_bottom(); }\n\n  bool is_top() { return this->_env.is_top(); }\n\n  bool operator<=(congruence_domain_t e) { \n    crab::CrabStats::count(getDomainName() + \".count.leq\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".leq\");\n    return this->_env <= e._env; \n  }\n\n  void operator|=(congruence_domain_t e) {\n    crab::CrabStats::count(getDomainName() + \".count.join\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n    this->_env = this->_env | e._env;\n  }\n\n  congruence_domain_t operator|(congruence_domain_t e) {\n    crab::CrabStats::count(getDomainName() + \".count.join\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n    return this->_env | e._env;\n  }\n\n  congruence_domain_t operator&(congruence_domain_t e) {\n    crab::CrabStats::count(getDomainName() + \".count.meet\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".meet\");\n    return this->_env & e._env;\n  }\n\n  congruence_domain_t operator||(congruence_domain_t e) {\n    crab::CrabStats::count(getDomainName() + \".count.widening\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n    return this->_env || e._env;\n  }\n\n  congruence_domain_t widening_thresholds(congruence_domain_t other, \n\t\t\t\t\t  const crab::iterators::thresholds<number_t>&) {\n    return (*this || other);\n  }\n\n  congruence_domain_t operator&&(congruence_domain_t e) {\n    crab::CrabStats::count(getDomainName() + \".count.narrowing\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".narrowing\");\n    return this->_env && e._env;\n  }\n\n  void set(variable_t v, congruence_t i) { \n    crab::CrabStats::count(getDomainName() + \".count.assign\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n    this->_env.set(v, i); \n  }\n\n  void set(variable_t v, number_t n) {\n    crab::CrabStats::count(getDomainName() + \".count.assign\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n    this->_env.set(v, congruence_t(n)); \n  }\n\n  void operator-=(variable_t v) { \n    crab::CrabStats::count(getDomainName() + \".count.forget\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".forget\");\n    this->_env -= v; \n  }\n\n  void operator-=(std::vector<variable_t> vs) {\n    for (typename std::vector<variable_t>::iterator it = vs.begin(),\n\t   end = vs.end(); it != end; ++it) {\n      this->operator-=* it;\n    }\n  }\n\n  congruence_t operator[](variable_t v) { return this->_env[v]; }\n\n  congruence_t operator[](linear_expression_t expr) {\n    congruence_t r(expr.constant());\n    for (typename linear_expression_t::iterator it = expr.begin();\n         it != expr.end();\n         ++it) {\n      congruence_t c(it->first);\n      r = r + (c * this->_env[it->second]);\n    }\n    return r;\n  }\n\n  void add(linear_constraint_system_t csts) {\n    crab::CrabStats::count(getDomainName() + \".count.add_constraints\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".add_constraints\");\n    const std::size_t threshold = 10;\n    if (!this->is_bottom()) {\n      solver_t solver(csts, threshold);\n      solver.run(this->_env);\n    }\n  }\n\n  void operator+=(linear_constraint_system_t csts) { \n    this->add(csts); \n  }\n\n  congruence_domain_t operator+(linear_constraint_system_t csts) {\n    congruence_domain_t e(this->_env);\n    e += csts;\n    return e;\n  }\n\n  void assign(variable_t x, linear_expression_t e) {\n    crab::CrabStats::count(getDomainName() + \".count.assign\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n\n    congruence_t r = e.constant();\n    for (typename linear_expression_t::iterator it = e.begin(); it != e.end();\n         ++it) {\n      r = r + (it->first * this->_env[it->second]);\n    }\n    this->_env.set(x, r);\n  }\n\n  void apply(operation_t op, variable_t x, variable_t y, variable_t z) {\n    crab::CrabStats::count(getDomainName() + \".count.apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n    congruence_t yi = this->_env[y];\n    congruence_t zi = this->_env[z];\n    congruence_t xi = congruence_t::bottom();\n\n    switch (op) {\n      case OP_ADDITION:\n        xi = yi + zi;\n        break;\n      case OP_SUBTRACTION:\n        xi = yi - zi;\n        break;\n      case OP_MULTIPLICATION: \n        xi = yi * zi;\n        break;\n      case OP_SDIV: \n        xi = yi / zi;\n        break;\n      case OP_UDIV: \n        xi = yi.UDiv(zi);\n        break;\n      case OP_SREM: \n        xi = yi.SRem(zi);\n        break;\n      case OP_UREM: \n        xi = yi.URem(zi);\n        break;\n    default:\n      CRAB_ERROR(\"Operation \", op, \" not supported\");\n    }\n    this->_env.set(x, xi);\n  }\n\n  void apply(operation_t op, variable_t x, variable_t y, number_t k) {\n    crab::CrabStats::count(getDomainName() + \".count.apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n    congruence_t yi = this->_env[y];\n    congruence_t zi(k);\n    congruence_t xi = congruence_t::bottom();\n\n    switch (op) {\n      case OP_ADDITION: \n        xi = yi + zi;\n        break;\n      case OP_SUBTRACTION: \n        xi = yi - zi;\n        break;\n      case OP_MULTIPLICATION:\n        xi = yi * zi;\n        break;\n      case OP_SDIV:\n        xi = yi / zi;\n        break;\n      case OP_UDIV:\n        xi = yi.UDiv(zi);\n        break;\n      case OP_SREM:\n        xi = yi.SRem(zi);\n        break;\n      case OP_UREM:\n        xi = yi.URem(zi);\n        break;\n      default:\n\tCRAB_ERROR(\"Operation \", op, \" not supported\");\n    }\n    this->_env.set(x, xi);\n  }\n\n  // backward operations\n  void backward_assign(variable_t x, linear_expression_t e,\n\t\t       congruence_domain_t inv) {\n    crab::CrabStats::count(getDomainName() + \".count.backward_assign\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".backward_assign\");\n    \n    crab::domains::BackwardAssignOps<congruence_domain_t>::\n      assign(*this, x, e, inv);\n  }\n  \n  void backward_apply(operation_t op,\n\t\t      variable_t x, variable_t y, number_t z,\n\t\t      congruence_domain_t inv) {\n    crab::CrabStats::count(getDomainName() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".backward_apply\");\n    \n    crab::domains::BackwardAssignOps<congruence_domain_t>::\n      apply(*this, op, x, y, z, inv);\n  }\n  \n  void backward_apply(operation_t op,\n\t\t      variable_t x, variable_t y, variable_t z,\n\t\t      congruence_domain_t inv) {\n    crab::CrabStats::count(getDomainName() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".backward_apply\");\n    \n    crab::domains::BackwardAssignOps<congruence_domain_t>::\n      apply(*this, op, x, y, z, inv);\n  }\n\n  // cast operations\n  \n  void apply(crab::domains::int_conv_operation_t /*op*/,\n\t     variable_t dst, variable_t src) {  \n    // ignore widths\n    assign(dst, src);\n  }\n\n  // bitwise operations\n  \n  void apply(bitwise_operation_t op, variable_t x, variable_t y, variable_t z) {\n    crab::CrabStats::count(getDomainName() + \".count.apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n    congruence_t yi = this->_env[y];\n    congruence_t zi = this->_env[z];\n    congruence_t xi = congruence_t::bottom();\n\n    switch (op) {\n      case OP_AND: {\n        xi = yi.And(zi);\n        break;\n      }\n      case OP_OR: {\n        xi = yi.Or(zi);\n        break;\n      }\n      case OP_XOR: {\n        xi = yi.Xor(zi);\n        break;\n      }\n      case OP_SHL: {\n        xi = yi.Shl(zi);\n        break;\n      }\n      case OP_LSHR: {\n        xi = yi.LShr(zi);\n        break;\n      }\n      case OP_ASHR: {\n        xi = yi.AShr(zi);\n        break;\n      }\n      default: { CRAB_ERROR(\"unreachable\"); }\n    }\n    this->_env.set(x, xi);\n  }\n\n  void apply(bitwise_operation_t op, variable_t x, variable_t y, number_t k) {\n    crab::CrabStats::count(getDomainName() + \".count.apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n    congruence_t yi = this->_env[y];\n    congruence_t zi(k);\n    congruence_t xi = congruence_t::bottom();\n\n    switch (op) {\n      case OP_AND: {\n        xi = yi.And(zi);\n        break;\n      }\n      case OP_OR: {\n        xi = yi.Or(zi);\n        break;\n      }\n      case OP_XOR: {\n        xi = yi.Xor(zi);\n        break;\n      }\n      case OP_SHL: {\n        xi = yi.Shl(zi);\n        break;\n      }\n      case OP_LSHR: {\n        xi = yi.LShr(zi);\n        break;\n      }\n      case OP_ASHR: {\n        xi = yi.AShr(zi);\n        break;\n      }\n      default: { CRAB_ERROR(\"unreachable\"); }\n    }\n    this->_env.set(x, xi);\n  }\n  \n  /* \n     Begin unimplemented operations \n     \n     congruence_domain implements only standard abstract operations of\n     a numerical domain.  The implementation of boolean, array, or\n     pointer operations is empty because they should never be called.\n  */\n  \n  // boolean operations\n  void assign_bool_cst(variable_t lhs, linear_constraint_t rhs) {}\n  void assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs) {}\n  void apply_binary_bool(crab::domains::bool_operation_t op,\n\t\t\t variable_t x,variable_t y,variable_t z) {}\n  void assume_bool(variable_t v, bool is_negated) {}\n  // backward boolean operations\n  void backward_assign_bool_cst(variable_t lhs, linear_constraint_t rhs,\n\t\t\t\tcongruence_domain_t invariant){}\n  void backward_assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs,\n\t\t\t\tcongruence_domain_t invariant) {}\n  void backward_apply_binary_bool(crab::domains::bool_operation_t op,\n\t\t\t\t  variable_t x,variable_t y,variable_t z,\n\t\t\t\t  congruence_domain_t invariant) {}\n  // array operations\n  void array_init(variable_t a, linear_expression_t elem_size,\n\t\t  linear_expression_t lb_idx, linear_expression_t ub_idx, \n\t\t  linear_expression_t val) {}      \n  void array_load(variable_t lhs,\n\t\t  variable_t a, linear_expression_t elem_size,\n\t\t  linear_expression_t i) {}\n  void array_store(variable_t a, linear_expression_t elem_size,\n\t\t   linear_expression_t i, linear_expression_t v, \n\t\t   bool is_strong_update) {}\n  void array_store(variable_t a_new, variable_t a_old,\n\t\t   linear_expression_t elem_size,\n\t\t   linear_expression_t i, linear_expression_t v, \n\t\t   bool is_strong_update) {}\n  void array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t linear_expression_t i, linear_expression_t j,\n\t\t\t linear_expression_t v) {}\n  void array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t linear_expression_t elem_size,\n\t\t\t linear_expression_t i, linear_expression_t j,\n\t\t\t linear_expression_t v) {}  \n  void array_assign(variable_t lhs, variable_t rhs) {}\n  // backward array operations\n  void backward_array_init(variable_t a, linear_expression_t elem_size,\n\t\t\t   linear_expression_t lb_idx, linear_expression_t ub_idx, \n\t\t\t   linear_expression_t val, congruence_domain_t invariant) {}      \n  void backward_array_load(variable_t lhs,\n\t\t\t   variable_t a, linear_expression_t elem_size,\n\t\t\t   linear_expression_t i, congruence_domain_t invariant) {}\n  void backward_array_store(variable_t a, linear_expression_t elem_size,\n\t\t\t    linear_expression_t i, linear_expression_t v, \n\t\t\t    bool is_strong_update, congruence_domain_t invariant) {}\n  void backward_array_store(variable_t a_new, variable_t a_old,\n\t\t\t    linear_expression_t elem_size,\n\t\t\t    linear_expression_t i, linear_expression_t v, \n\t\t\t    bool is_strong_update, congruence_domain_t invariant) {}  \n  void backward_array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t\t  linear_expression_t i, linear_expression_t j,\n\t\t\t\t  linear_expression_t v, congruence_domain_t invariant) {}\n  void backward_array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t\t  linear_expression_t elem_size,\n\t\t\t\t  linear_expression_t i, linear_expression_t j,\n\t\t\t\t  linear_expression_t v, congruence_domain_t invariant) {}  \n  void backward_array_assign(variable_t lhs, variable_t rhs, congruence_domain_t invariant) {}\n  // pointer operations\n  void pointer_load(variable_t lhs, variable_t rhs)  {}\n  void pointer_store(variable_t lhs, variable_t rhs) {} \n  void pointer_assign(variable_t lhs, variable_t rhs, linear_expression_t offset) {}\n  void pointer_mk_obj(variable_t lhs, ikos::index_t address) {}\n  void pointer_function(variable_t lhs, varname_t func) {}\n  void pointer_mk_null(variable_t lhs) {}\n  void pointer_assume(pointer_constraint_t cst) {}\n  void pointer_assert(pointer_constraint_t cst) {}\n  /* End unimplemented operations */\n  \n  void forget(const variable_vector_t& variables) {\n    if (is_bottom() || is_top()) {\n      return;\n    }\n    for (variable_t var: variables){\n      this->operator-=(var); \n    }\n  }\n\n  void project(const variable_vector_t& variables){\n    crab::CrabStats::count(getDomainName() + \".count.project\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".project\");\n    \n    if (is_bottom() || is_top()) {\n      return;\n    }\n    \n    separate_domain_t env;\n    for (variable_t var : variables){\n      env.set(var, this->_env[var]); \n    }\n    std::swap(_env, env);\n  }\n  \n  void expand(variable_t x, variable_t new_x) {\n    crab::CrabStats::count(getDomainName() + \".count.expand\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".expand\");\n    \n    if (is_bottom() || is_top()) {\n      return;\n    }\n    \n    set(new_x , this->_env[x]);\n  }\n\n  void normalize() {}\n\n  void minimize() {}  \n  \n  void write(crab::crab_os& o) {\n    crab::CrabStats::count(getDomainName() + \".count.write\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".write\");\n    \n    this->_env.write(o); \n  }\n\n  linear_constraint_system_t to_linear_constraint_system() {\n    crab::CrabStats::count(getDomainName() + \".count.to_linear_constraint_system\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".to_linear_constraint_system\");\n    \n    linear_constraint_system_t csts;\n    if (is_bottom()) {\n      csts += linear_constraint_t::get_false();\n      return csts;\n    }\n\n    for (iterator it = this->_env.begin(); it != this->_env.end(); ++it) {\n      variable_t v = it->first;\n      congruence_t c = it->second;\n      boost::optional<number_t> n = c.singleton();\n      if (n) {\n        csts += (v == *n);\n      }\n    }\n    return csts;\n  }\n\n  disjunctive_linear_constraint_system_t to_disjunctive_linear_constraint_system() {\n    auto lin_csts = to_linear_constraint_system();\n    if (lin_csts.is_false()) {\n      return disjunctive_linear_constraint_system_t(true /*is_false*/); \n    } else if (lin_csts.is_true()) {\n      return disjunctive_linear_constraint_system_t(false /*is_false*/);\n    } else {\n      return disjunctive_linear_constraint_system_t(lin_csts);\n    }\n  }\n  \n  static std::string getDomainName() {\n    return \"Congruences\"; \n  }\n\n}; // class congruence_domain\n\n} // namespace ikos\n\nnamespace crab {\nnamespace domains {\n\n  template <typename Number, typename VariableName> \n  struct abstract_domain_traits<ikos::congruence_domain<Number, VariableName>> {\n    typedef Number number_t;\n    typedef VariableName varname_t;       \n  };\n  \n}\n}\n\n", "meta": {"hexsha": "bc7af4351885ef09dddcf96973295b2c73183b0f", "size": 37446, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/congruences.hpp", "max_stars_repo_name": "numairmansur/crab", "max_stars_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "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/crab/domains/congruences.hpp", "max_issues_repo_name": "numairmansur/crab", "max_issues_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "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/crab/domains/congruences.hpp", "max_forks_repo_name": "numairmansur/crab", "max_forks_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "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.9158301158, "max_line_length": 94, "alphanum_fraction": 0.6159002297, "num_tokens": 10616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5440305898866763}}
{"text": "#ifndef MATHTOOLBOX_NUMERICAL_OPTIMIZATION_HPP\n#define MATHTOOLBOX_NUMERICAL_OPTIMIZATION_HPP\n\n#include <Eigen/Core>\n#include <functional>\n#include <mathtoolbox/bfgs.hpp>\n#include <mathtoolbox/l-bfgs.hpp>\n#include <stdexcept>\n\nnamespace mathtoolbox\n{\n    namespace optimization\n    {\n        enum class Algorithm\n        {\n            Bfgs,\n            LBfgs\n        };\n\n        enum class Type\n        {\n            Min,\n            Max\n        };\n\n        struct Setting\n        {\n            Algorithm                                              algorithm          = Algorithm::Bfgs;\n            Eigen::VectorXd                                        x_init             = Eigen::VectorXd(0);\n            std::function<double(const Eigen::VectorXd&)>          f                  = nullptr;\n            std::function<Eigen::VectorXd(const Eigen::VectorXd&)> g                  = nullptr;\n            double                                                 epsilon            = 1e-05;\n            unsigned int                                           max_num_iterations = 1000;\n            Type                                                   type               = Type::Min;\n        };\n\n        struct Result\n        {\n            Eigen::VectorXd x_star;\n            unsigned        num_iterations;\n        };\n\n        /// \\brief Run optimization with the specified setting\n        ///\n        /// \\details This is a utility function to run various optimization types in a consitent interface.\n        inline Result RunOptimization(const Setting& input)\n        {\n            const auto f = (input.type == Type::Min) ? input.f : [&input](const Eigen::VectorXd& x) -> double {\n                return -input.f(x);\n            };\n            const auto g = (input.type == Type::Min) ? input.g : [&input](const Eigen::VectorXd& x) -> Eigen::VectorXd {\n                return -input.g(x);\n            };\n\n            switch (input.algorithm)\n            {\n                case Algorithm::Bfgs:\n                {\n                    if (!input.f || !input.g || input.x_init.rows() == 0)\n                    {\n                        throw std::invalid_argument(\"Invalid setting.\");\n                    }\n\n                    Result result;\n                    RunBfgs(input.x_init,\n                            f,\n                            g,\n                            input.epsilon,\n                            input.max_num_iterations,\n                            result.x_star,\n                            result.num_iterations);\n                    return result;\n                }\n                case Algorithm::LBfgs:\n                {\n                    if (!input.f || !input.g || input.x_init.rows() == 0)\n                    {\n                        throw std::invalid_argument(\"Invalid setting.\");\n                    }\n\n                    Result result;\n                    RunLBfgs(input.x_init,\n                             f,\n                             g,\n                             input.epsilon,\n                             input.max_num_iterations,\n                             result.x_star,\n                             result.num_iterations);\n                    return result;\n                }\n            }\n        }\n    } // namespace optimization\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_NUMERICAL_OPTIMIZATION_HPP\n", "meta": {"hexsha": "e34a6fccd565d6d938380e5c17d7fba9825ef940", "size": 3359, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/numerical-optimization.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/numerical-optimization.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/numerical-optimization.hpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 34.6288659794, "max_line_length": 120, "alphanum_fraction": 0.4120273891, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5440305831777745}}
{"text": "#include <Eigen/Dense>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/opencv.hpp>\n#include <vector>\n#include <cmath>\n#include <stack>\n#include <AtlBase.h>\n#include <iomanip>\n#include \"OVUtil.h\"\n#include \"OVCommon.h\"\n\nnamespace ov\n{\n\nconst double PI = 3.1415927;\nconst double ROT_EPS = 1e-15;\n\nstd::string\nGetFileName(const std::string& s)\n{\n    char sep1 = '/', sep2 = '\\\\';\n\n    size_t i = s.rfind(sep1, s.length());\n    size_t j = s.rfind(sep2, s.length());\n\n    if (i != std::string::npos)\n        return(s.substr(i + 1, s.length() - i));\n    else if (j != std::string::npos)\n        return(s.substr(j + 1, s.length() - j));\n    else\n        return(\"\");\n}\n\nstd::string\nGetBaseName(const std::string& s)\n{\n    char sep = '.';\n    size_t i = s.rfind(sep, s.length());\n\n    if (i != std::string::npos)\n        return(s.substr(0, i));\n    else\n        return(\"\");\n}\n\nstd::string\nGetExt(const std::string& s)\n{\n    char sep = '.';\n\n    size_t i = s.rfind(sep, s.length());\n\n    if (i != std::string::npos)\n        return(s.substr(i + 1, s.length() - i));\n    else\n        return(\"\");\n}\n\nstd::string\nGetDir(const std::string& s)\n{\n    char sep1 = '/', sep2 = '\\\\';\n\n    size_t i = s.rfind(sep1, s.length());\n    size_t j = s.rfind(sep2, s.length());\n\n    if (i != std::string::npos)\n        return(s.substr(0, i + 1));\n    else if (j != std::string::npos)\n        return(s.substr(0, j + 1));\n    else\n        return(\"\");\n}\n\n// Simulate a trackball by projecting the previous and current points onto\n// a virtual sphere, and then compute the related rotation matrix.\n// August '88 issue of Siggraph's \"Computer Graphics,\" pp. 121-129\nMat3\nTrackball(const Vec2& prePos, const Vec2& curPos)\n{\n    if (prePos == curPos)\n        return Mat3::Identity();\n    \n    Vec3 p1(prePos(0), prePos(1), GetZValueFrom2DPoint(TRACKBALLSIZE, prePos));\n    Vec3 p2(curPos(0), curPos(1), GetZValueFrom2DPoint(TRACKBALLSIZE, curPos));\n    Vec3 axis = (p1.cross(p2)).normalized();\n\n    // Rotation amout\n    double t = (p1 - p2).norm() / 2.0 / TRACKBALLSIZE;\n    t = (t > 1) ? 1 : (t < -1) ? -1 : t;\n    double phi = 2.0 * asin(t);\n    return FromAxisAngleToRotationMatrix(axis * phi);\n}\n\n// Project a 2D point onto a sphere of radius r or a hyperboic sheet\n// to get the z value\ndouble\nGetZValueFrom2DPoint(double r, const Vec2& pos)\n{\n    double d = pos.norm();\n    if (d < r / sqrt(2))\n        return sqrt(r * r - d * d);\n    else\n        return r * r / 2.0 / d;\n}\n\nVec3\nFromRotationMatirxToAxisAngle(const Mat3& R)\n{\n    double a = acos((R.trace() - 1) / 2);\n    Vec3 r;\n    if (a < ROT_EPS)\n    {\n        r << R(2, 1) - R(1, 2), R(0, 2) - R(2, 0), R(1, 0) - R(0, 1);\n        r *= 0.5;\n    }\n    else if (a >(PI - ROT_EPS))\n    {\n        Mat3 S = 0.5 * (R - Mat3::Identity());\n        double b = sqrt(S(0, 0) + 1);\n        double c = sqrt(S(1, 1) + 1);\n        double d = sqrt(S(2, 2) + 1);\n        if (b > ROT_EPS)\n        {\n            c = S(1, 0) / b;\n            d = S(2, 0) / b;\n        }\n        else if (c > ROT_EPS)\n        {\n            b = S(0, 1) / c;\n            d = S(2, 1) / c;\n        }\n        else\n        {\n            b = S(0, 2) / d;\n            c = S(1, 2) / d;\n        }\n        r << b, c, d;\n    }\n    else\n    {\n        r << R(2, 1) - R(1, 2), R(0, 2) - R(2, 0), R(1, 0) - R(0, 1);\n        r *= (a / 2 / sin(a));\n    }\n    return r;\n}\n\nMat3\nFromAxisAngleToRotationMatrix(const Vec3& r)\n{\n    double rx, ry, rz;\n    rx = r(0);\n    ry = r(1);\n    rz = r(2);\n    Mat3 I = Mat::Identity(3, 3);\n    Mat3 W = (Mat3() << 0, -rz, ry, rz, 0, -rx, -ry, rx, 0).finished();\n    Mat3 W2 = W * W;\n    const double a = r.norm();\n    if (a < ROT_EPS)\n        return I + W + 0.5 * W2;\n    else\n        return I + W * sin(a) / a + W2 * (1 - cos(a)) / (a * a);\n}\n\nwxCheckBox*\nCreateCheckBoxAndAddToSizer(wxWindow* parent,\n    wxSizer *sizer,\n    wxString labelStr,\n    wxWindowID id)\n{\n    wxCheckBox *checkbox = new wxCheckBox(parent, id, labelStr);\n    sizer->Add(checkbox, 0, wxEXPAND | wxALL, 3);\n\n    return checkbox;\n}\n\nMat\nLoadMatrix(std::string fileName)\n{\n    std::ifstream file;\n    file.open(fileName, std::ios::in);\n\n    if (!file.is_open())\n        return Mat();\n\n    std::string line;\n    bool finishdOneLine = false;\n    int rows = 0, cols = 0;\n\n    // First round: find the row and column numbers\n    while (!std::getline(file, line, '\\n').eof())\n    {\n        std::istringstream reader(line);\n        while (!reader.eof() && !finishdOneLine)\n        {\n            double val;\n            reader >> val;\n            if (reader.fail())\n                break;\n            ++cols;\n        }\n        ++rows;\n        finishdOneLine = true;\n    }\n\n    file.clear();\n    file.seekg(0);\n    Mat mat(rows, cols);\n    int i = 0, j = 0;\n    // Second round: fill in the matrix\n    while (!std::getline(file, line, '\\n').eof())\n    {\n        std::istringstream reader(line);\n        while (!reader.eof())\n        {\n            double val;\n            reader >> val;\n            if (reader.fail())\n                break;\n            mat(i, j++) = val;\n        }\n        ++i;\n        j = 0;\n    }\n\n    return mat;\n}\n\nstd::string\nZeroPadNumber(int num, int width)\n{\n    std::ostringstream ss;\n    ss << std::setw(width) << std::setfill('0') << num;\n    return ss.str();\n}\n\nbool\nIsDirectoryExists(std::string dirName)\n{\n    DWORD attribs = ::GetFileAttributes(std::wstring(dirName.begin(), dirName.end()).c_str());\n    if (attribs == INVALID_FILE_ATTRIBUTES)\n        return false;\n    return (attribs & FILE_ATTRIBUTE_DIRECTORY) != 0;\n}\n\nvoid\nCreateDirectorys(std::string path)\n{\n    std::string dir = GetDir(path);\n    std::stack<std::string> dirQueue;\n    while (!IsDirectoryExists(dir)&& !dir.empty())\n    {\n        dirQueue.push(dir);\n        dir.resize(dir.size() - 1);\n        dir = GetDir(dir);\n    }\n    while (!dirQueue.empty())\n    {\n        dir = dirQueue.top();\n        dirQueue.pop();\n        CreateDirectory(std::wstring(dir.begin(), dir.end()).c_str(), NULL);\n    }\n}\n\n} // namespace ov\n", "meta": {"hexsha": "0f3be894f71aee75dc82309e14715c60aa7e61d4", "size": 5991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/OVUtil.cpp", "max_stars_repo_name": "pcwu0329/ObjViewer", "max_stars_repo_head_hexsha": "7c65b085d65d9d2b1b0e7963884618ae064b422f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-20T17:31:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T04:49:11.000Z", "max_issues_repo_path": "src/OVUtil.cpp", "max_issues_repo_name": "pcwu0329/ObjViewer", "max_issues_repo_head_hexsha": "7c65b085d65d9d2b1b0e7963884618ae064b422f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OVUtil.cpp", "max_forks_repo_name": "pcwu0329/ObjViewer", "max_forks_repo_head_hexsha": "7c65b085d65d9d2b1b0e7963884618ae064b422f", "max_forks_repo_licenses": ["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.522556391, "max_line_length": 94, "alphanum_fraction": 0.5229510933, "num_tokens": 1885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5440227062766532}}
{"text": "\ufeff// KernelFiltering_Test.cpp : \u042d\u0442\u043e\u0442 \u0444\u0430\u0439\u043b \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u044e \"main\". \u0417\u0434\u0435\u0441\u044c \u043d\u0430\u0447\u0438\u043d\u0430\u0435\u0442\u0441\u044f \u0438 \u0437\u0430\u043a\u0430\u043d\u0447\u0438\u0432\u0430\u0435\u0442\u0441\u044f \u0432\u044b\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b.\n//\n\n#include \"pch.h\"\n#include <iostream>\n#include \"LinkingTest.h\"\n\n#include <array>\n#include \"lodepng.h\"\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\nusing namespace boost::numeric::ublas;\n\n#include \"pngAs8bitMatrix.h\"\n\n#include \"kernelGaussianLowPass.h\"\n\n//void runLinkingTest() {\n//\t// Initialize a Fibonacci relation sequence.\n//// Write out the sequence values until overflow.\tfibonacci_init(1, 1);\n//\n//\tdo {\n//\t\tstd::cout << fibonacci_index() << \": \"\n//\t\t\t<< fibonacci_current() << std::endl;\n//\t} while (fibonacci_next());\n//\t// Report count of values written before overflow.\n//\tstd::cout << fibonacci_index() + 1 <<\n//\t\t\" Fibonacci sequence values fit in an \" <<\n//\t\t\"unsigned 64-bit integer.\" << std::endl;\n//}\n\n\nint main()\n{\n\tmatrix<uint8_t> inputImage = readPNGRedAsMatrix(\"..\\\\..\\\\test_data\\\\subp_147_5-157_5.png\");\n\n\tmatrix<uint8_t> outputImage1 = matrix<uint8_t>(inputImage.size1(), inputImage.size2());\n\tapplyLowPassGaussFilterToMatrix<uint8_t, double>(&outputImage1, &inputImage, 1, 1, 0.8);\n\tauto r1 = writePNGRedAsMatrix(\"..\\\\..\\\\test_data\\\\_lp_1_1_08_subp_147_5-157_5.png\", &outputImage1);\n\n\tmatrix<uint8_t> outputImage2 = matrix<uint8_t>(inputImage.size1(), inputImage.size2());\n\tapply2dLowPassGaussFilterToMatrix<uint8_t, double>(&outputImage2, &inputImage, 1, 3, 0.3, 1.0);\n\tauto r2 = writePNGRedAsMatrix(\"..\\\\..\\\\test_data\\\\_2dlp_1_3_03_10_subp_147_5-157_5.png\", &outputImage2);\n\n\treturn 0;\n}\n\n// \u0417\u0430\u043f\u0443\u0441\u043a \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b: CTRL+F5 \u0438\u043b\u0438 \u043c\u0435\u043d\u044e \"\u041e\u0442\u043b\u0430\u0434\u043a\u0430\" > \"\u0417\u0430\u043f\u0443\u0441\u043a \u0431\u0435\u0437 \u043e\u0442\u043b\u0430\u0434\u043a\u0438\"\n// \u041e\u0442\u043b\u0430\u0434\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b: F5 \u0438\u043b\u0438 \u043c\u0435\u043d\u044e \"\u041e\u0442\u043b\u0430\u0434\u043a\u0430\" > \"\u0417\u0430\u043f\u0443\u0441\u0442\u0438\u0442\u044c \u043e\u0442\u043b\u0430\u0434\u043a\u0443\"\n\n// \u0421\u043e\u0432\u0435\u0442\u044b \u043f\u043e \u043d\u0430\u0447\u0430\u043b\u0443 \u0440\u0430\u0431\u043e\u0442\u044b \n//   1. \u0412 \u043e\u043a\u043d\u0435 \u043e\u0431\u043e\u0437\u0440\u0435\u0432\u0430\u0442\u0435\u043b\u044f \u0440\u0435\u0448\u0435\u043d\u0438\u0439 \u043c\u043e\u0436\u043d\u043e \u0434\u043e\u0431\u0430\u0432\u043b\u044f\u0442\u044c \u0444\u0430\u0439\u043b\u044b \u0438 \u0443\u043f\u0440\u0430\u0432\u043b\u044f\u0442\u044c \u0438\u043c\u0438.\n//   2. \u0412 \u043e\u043a\u043d\u0435 Team Explorer \u043c\u043e\u0436\u043d\u043e \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0438\u0442\u044c\u0441\u044f \u043a \u0441\u0438\u0441\u0442\u0435\u043c\u0435 \u0443\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u0438\u044f \u0432\u0435\u0440\u0441\u0438\u044f\u043c\u0438.\n//   3. \u0412 \u043e\u043a\u043d\u0435 \"\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\" \u043c\u043e\u0436\u043d\u043e \u043f\u0440\u043e\u0441\u043c\u0430\u0442\u0440\u0438\u0432\u0430\u0442\u044c \u0432\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435 \u0441\u0431\u043e\u0440\u043a\u0438 \u0438 \u0434\u0440\u0443\u0433\u0438\u0435 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u044f.\n//   4. \u0412 \u043e\u043a\u043d\u0435 \"\u0421\u043f\u0438\u0441\u043e\u043a \u043e\u0448\u0438\u0431\u043e\u043a\" \u043c\u043e\u0436\u043d\u043e \u043f\u0440\u043e\u0441\u043c\u0430\u0442\u0440\u0438\u0432\u0430\u0442\u044c \u043e\u0448\u0438\u0431\u043a\u0438.uin\n//   5. \u041f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u0432\u044b\u0431\u0435\u0440\u0438\u0442\u0435 \u043f\u0443\u043d\u043a\u0442\u044b \u043c\u0435\u043d\u044e \"\u041f\u0440\u043e\u0435\u043a\u0442\" > \"\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u043d\u043e\u0432\u044b\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\", \u0447\u0442\u043e\u0431\u044b \u0441\u043e\u0437\u0434\u0430\u0442\u044c \u0444\u0430\u0439\u043b\u044b \u043a\u043e\u0434\u0430, \u0438\u043b\u0438 \"\u041f\u0440\u043e\u0435\u043a\u0442\" > \"\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\", \u0447\u0442\u043e\u0431\u044b \u0434\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0432 \u043f\u0440\u043e\u0435\u043a\u0442 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0435 \u0444\u0430\u0439\u043b\u044b \u043a\u043e\u0434\u0430.\n//   6. \u0427\u0442\u043e\u0431\u044b \u0441\u043d\u043e\u0432\u0430 \u043e\u0442\u043a\u0440\u044b\u0442\u044c \u044d\u0442\u043e\u0442 \u043f\u0440\u043e\u0435\u043a\u0442 \u043f\u043e\u0437\u0436\u0435, \u0432\u044b\u0431\u0435\u0440\u0438\u0442\u0435 \u043f\u0443\u043d\u043a\u0442\u044b \u043c\u0435\u043d\u044e \"\u0424\u0430\u0439\u043b\" > \"\u041e\u0442\u043a\u0440\u044b\u0442\u044c\" > \"\u041f\u0440\u043e\u0435\u043a\u0442\" \u0438 \u0432\u044b\u0431\u0435\u0440\u0438\u0442\u0435 SLN-\u0444\u0430\u0439\u043b.\n", "meta": {"hexsha": "1cdbf8549c0fce6dca6fe959b4dce70ff40884e4", "size": 2386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "KernelFiltering_Test/KernelFiltering_Test/KernelFiltering_Test.cpp", "max_stars_repo_name": "vcxz09876/kernelFiltering", "max_stars_repo_head_hexsha": "ceda31655cd869e7988f7eaa76cb79da0a54fb5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "KernelFiltering_Test/KernelFiltering_Test/KernelFiltering_Test.cpp", "max_issues_repo_name": "vcxz09876/kernelFiltering", "max_issues_repo_head_hexsha": "ceda31655cd869e7988f7eaa76cb79da0a54fb5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KernelFiltering_Test/KernelFiltering_Test/KernelFiltering_Test.cpp", "max_forks_repo_name": "vcxz09876/kernelFiltering", "max_forks_repo_head_hexsha": "ceda31655cd869e7988f7eaa76cb79da0a54fb5a", "max_forks_repo_licenses": ["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.1379310345, "max_line_length": 204, "alphanum_fraction": 0.7271584241, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744806385543, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5440226865540914}}
{"text": "#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SVD>\n#include <iostream>\n#include <random>  // Requires C++ 11\n\n#include <Spectra/contrib/PartialSVDSolver.h>\n\nusing namespace Spectra;\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\ntypedef Eigen::MatrixXd Matrix;\ntypedef Eigen::VectorXd Vector;\ntypedef Eigen::SparseMatrix<double> SpMatrix;\n\n// Generate random sparse matrix\nSpMatrix gen_sparse_data(int m, int n, double prob = 0.5)\n{\n    SpMatrix mat(m, n);\n    std::default_random_engine gen;\n    gen.seed(0);\n    std::uniform_real_distribution<double> distr(0.0, 1.0);\n    for (int i = 0; i < m; i++)\n    {\n        for (int j = 0; j < n; j++)\n        {\n            if (distr(gen) < prob)\n                mat.insert(i, j) = distr(gen) - 0.5;\n        }\n    }\n    return mat;\n}\n\ntemplate <typename MatType>\nvoid run_test(const MatType& mat, int k, int m)\n{\n    PartialSVDSolver<double, MatType> svds(mat, k, m);\n    int nconv = svds.compute();\n\n    INFO(\"nconv = \" << nconv);\n    REQUIRE(nconv == k);\n\n    Vector svals = svds.singular_values();\n    Matrix U = svds.matrix_U(k);\n    Matrix V = svds.matrix_V(k);\n\n    // SVD solver from Eigen\n    // Requires dense matrices\n    Matrix mat_dense = Matrix(mat);\n    Eigen::JacobiSVD<Matrix> svd(mat, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Vector svals_eigen = svd.singularValues();\n    Matrix U_eigen = svd.matrixU();\n    Matrix V_eigen = svd.matrixV();\n\n    double err = (svals - svals_eigen.head(k)).array().abs().maxCoeff();\n    INFO(\"Residual of singular values = \" << err);\n    REQUIRE(err == Approx(0.0).margin(1e-9));\n\n    err = (U.array().abs() - U_eigen.leftCols(k).array().abs()).abs().maxCoeff();\n    INFO(\"Residual of left singular vectors = \" << err);\n    REQUIRE(err == Approx(0.0).margin(1e-9));\n\n    err = (V.array().abs() - V_eigen.leftCols(k).array().abs()).abs().maxCoeff();\n    INFO(\"Residual of right singular vectors = \" << err);\n    REQUIRE(err == Approx(0.0).margin(1e-9));\n}\n\nTEST_CASE(\"Partial SVD of tall dense matrix [1000x100]\", \"[svds_dense_tall]\")\n{\n    std::srand(123);\n\n    const Matrix A = Matrix::Random(1000, 100);\n    int k = 5;\n    int m = 10;\n\n    run_test<Matrix>(A, k, m);\n}\n\nTEST_CASE(\"Partial SVD of wide dense matrix [1000x100]\", \"[svds_dense_wide]\")\n{\n    std::srand(123);\n\n    const Matrix A = Matrix::Random(100, 1000);\n    int k = 5;\n    int m = 10;\n\n    run_test<Matrix>(A, k, m);\n}\n\nTEST_CASE(\"Partial SVD of tall sparse matrix [1000x100]\", \"[svds_sparse_tall]\")\n{\n    std::srand(123);\n\n    const SpMatrix A = gen_sparse_data(1000, 100, 0.1);\n    int k = 5;\n    int m = 10;\n\n    run_test<SpMatrix>(A, k, m);\n}\n\nTEST_CASE(\"Partial SVD of wide sparse matrix [1000x100]\", \"[svds_sparse_wide]\")\n{\n    std::srand(123);\n\n    const SpMatrix A = gen_sparse_data(100, 1000, 0.1);\n    int k = 5;\n    int m = 10;\n\n    run_test<SpMatrix>(A, k, m);\n}\n", "meta": {"hexsha": "a9d2dfa0b9449638b3c4e21908f527c70351e465", "size": 2863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/test/SVD.cpp", "max_stars_repo_name": "mushroom-x/Misc3D", "max_stars_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2022-02-09T11:56:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:45:04.000Z", "max_issues_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/test/SVD.cpp", "max_issues_repo_name": "mushroom-x/Misc3D", "max_issues_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2022-02-26T08:58:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T11:19:05.000Z", "max_forks_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/test/SVD.cpp", "max_forks_repo_name": "mushroom-x/Misc3D", "max_forks_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2022-02-16T06:59:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:03:11.000Z", "avg_line_length": 25.3362831858, "max_line_length": 81, "alphanum_fraction": 0.6227733147, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.544022682615129}}
{"text": "#define DEBUG 1\n/**\n * File    : F.cpp\n * Author  : Kazune Takahashi\n * Created : 5/18/2020, 3:01:31 PM\n * Powered by Visual Studio Code\n */\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n// ----- boost -----\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n// ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n// ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n// constexpr ll MOD{998244353LL}; // be careful\nconstexpr ll MAX_SIZE{3000010LL};\n// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n  }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n  }\n}\n// ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(const Mint &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(const Mint &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(const Mint &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator/=(const Mint &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }\n  bool operator<(const Mint &a) const { return x < a.x; }\n  bool operator<=(const Mint &a) const { return x <= a.x; }\n  bool operator>(const Mint &a) const { return x > a.x; }\n  bool operator>=(const Mint &a) const { return x >= a.x; }\n  bool operator==(const Mint &a) const { return x == a.x; }\n  bool operator!=(const Mint &a) const { return !(*this == a); }\n  const Mint power(ll N)\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N / 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n  return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)\n{\n  return Mint<MOD>{lhs} / rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n  return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n  return stream << a.x;\n}\n// ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i = 2LL; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i = 1LL; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x / gcd(x, y) * y; }\n// ----- for C++17 -----\ntemplate <typename T>\nint popcount(T x) // C++20\n{\n  int ans{0};\n  while (x != 0)\n  {\n    ans += x & 1;\n    x >>= 1;\n  }\n  return ans;\n}\n// ----- frequently used constexpr -----\n// constexpr long double epsilon{1e-10};\n// constexpr ll infty{1000000000000000LL}; // or\n// constexpr int infty{1'000'000'010};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\n// ----- Point -----\n\nclass Point\n{\npublic:\n  ll x, v;\n\n  Point() {}\n  Point(ll x, ll v) : x{x}, v{v} {}\n\n  long double now(long double t) const { return x + v * t; }\n};\n\nlong double cross(Point const &p, Point const &q)\n{\n  if (q.v == p.v)\n  {\n    return 0.0;\n  }\n  return (static_cast<long double>(p.x) - q.x) / (q.v - p.v);\n}\n\nbool operator<(Point const &p, Point const &q)\n{\n  assert(p.v == q.v);\n  return p.x < q.x;\n}\n\n// ----- Axis -----\n\nclass Axis\n{\n  vector<vector<Point>> points;\n  vector<Point> candidates;\n  vector<long double> snapshots;\n\npublic:\n  Axis(vector<Point> const &V) : points(3)\n  {\n    for (auto const &p : V)\n    {\n      points[p.v].push_back(p);\n    }\n    for (auto i = 0; i < 3; ++i)\n    {\n      if (points[i].empty())\n      {\n        continue;\n      }\n      candidates.push_back(*max_element(points[i].begin(), points[i].end()));\n      candidates.push_back(*min_element(points[i].begin(), points[i].end()));\n    }\n    for (auto it = candidates.begin(); it != candidates.end(); ++it)\n    {\n      for (auto it2 = it + 1; it2 != candidates.end(); ++it2)\n      {\n        long double tmp{cross(*it, *it2)};\n        if (tmp > 0)\n        {\n          snapshots.push_back(tmp);\n        }\n      }\n    }\n  }\n\n  long double delta(long double t) const;\n\n  vector<long double> const &timer() const { return snapshots; }\n};\n\nlong double Axis::delta(long double t) const\n{\n  vector<long double> V;\n  for (auto const &p : candidates)\n  {\n    V.push_back(p.now(t));\n  }\n  return *max_element(V.begin(), V.end()) - *min_element(V.begin(), V.end());\n}\n\n// ----- main() -----\n\nint main()\n{\n  vector<Point> PX, PY;\n  int N;\n  cin >> N;\n  for (auto i = 0; i < N; ++i)\n  {\n    ll x, y;\n    char c;\n    cin >> x >> y >> c;\n    if (c == 'R')\n    {\n      PX.emplace_back(x, 2);\n      PY.emplace_back(y, 1);\n    }\n    else if (c == 'L')\n    {\n      PX.emplace_back(x, 0);\n      PY.emplace_back(y, 1);\n    }\n    else if (c == 'U')\n    {\n      PX.emplace_back(x, 1);\n      PY.emplace_back(y, 2);\n    }\n    else\n    {\n      PX.emplace_back(x, 1);\n      PY.emplace_back(y, 0);\n    }\n  }\n  Axis X(PX), Y(PY);\n  vector<long double> timer;\n  copy(X.timer().begin(), X.timer().end(), back_inserter(timer));\n  copy(Y.timer().begin(), Y.timer().end(), back_inserter(timer));\n  long double ans{X.delta(0) * Y.delta(0)};\n  for (auto t : timer)\n  {\n    ch_min(ans, X.delta(t) * Y.delta(t));\n#if DEBUG == 1\n    cerr << \"t = \" << t << \", X.delta = \" << X.delta(t) << \", Y.delta = \" << Y.delta(t) << endl;\n#endif\n  }\n  cout << fixed << setprecision(15) << ans << endl;\n}\n", "meta": {"hexsha": "10b259c44e342517f32a0e83efe77a86850707a0", "size": 7754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/0616_ABC130/F.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2019/0616_ABC130/F.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "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/0616_ABC130/F.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 21.4792243767, "max_line_length": 96, "alphanum_fraction": 0.5551973175, "num_tokens": 2442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5440226722562745}}
{"text": "#ifndef JOINT_HPP\n#define JOINT_HPP\n#include <armadillo>\n#include \"aux.hh\"\n#include \"body.hh\"\n#include \"matrix_tool.hh\"\n\nclass Joint\n{\npublic:\n    Joint(unsigned int TypeIn, arma::vec piIn, arma::vec pjIn, arma::vec qiIn,\n          arma::vec qjIn, Body *i_In, Body *j_In);\n    ~Joint(){};\n    void Build_C();\n    void Build_Cq();\n    void Build_GAMMA();\n    void update();\n\n    arma::mat get_Cqi();\n    arma::mat get_Cqj();\n    arma::vec get_GAMMA();\n    arma::vec get_Pi();\n    arma::vec get_Pj();\n    arma::vec get_CONSTRAINT();\n    Body *get_body_i_ptr();\n    Body *get_body_j_ptr();\n\nprivate:\n    unsigned int Type;\n    VECTOR(pi, 3);\n    VECTOR(pj, 3);\n    VECTOR(qi, 3);\n    VECTOR(qj, 3);\n    MATRIX(Cqi, 3, 6);\n    MATRIX(Cqj, 3, 6);\n    VECTOR(GAMMA, 3);\n    VECTOR(CONSTRAINT, 3);\n    MATRIX(TBI_i, 3, 3);\n    MATRIX(TBI_j, 3, 3);\n    VECTOR(Pi, 3);\n    VECTOR(Pj, 3);\n    VECTOR(Qi, 3);\n    VECTOR(Qj, 3);\n    VECTOR(wi, 3);\n    VECTOR(wj, 3);\n    VECTOR(Si, 3);\n    VECTOR(Sj, 3);\n    Body *body_i_ptr;\n    Body *body_j_ptr;\n};\n\n#endif  //JOINT_HPP", "meta": {"hexsha": "d724239d12198ebf62d511b61101d37ccf841e23", "size": 1060, "ext": "hh", "lang": "C++", "max_stars_repo_path": "modules/cadac/joint.hh", "max_stars_repo_name": "mlouielu/mazu-sim", "max_stars_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-26T07:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-26T07:09:54.000Z", "max_issues_repo_path": "modules/cadac/joint.hh", "max_issues_repo_name": "mlouielu/mazu-sim", "max_issues_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/cadac/joint.hh", "max_forks_repo_name": "mlouielu/mazu-sim", "max_forks_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "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.3846153846, "max_line_length": 78, "alphanum_fraction": 0.5830188679, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5440226663408935}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"poses-precomp.h\"  // Precompiled headers\n\n#include <mrpt/math/geometry.h>\n#include <mrpt/poses/CPose2D.h>\n#include <mrpt/poses/CPose3D.h>\n#include <mrpt/poses/Lie/SE.h>\n#include <mrpt/poses/Lie/SO.h>\n#include <Eigen/Dense>\n\nusing namespace mrpt;\nusing namespace mrpt::math;\nusing namespace mrpt::poses;\nusing namespace mrpt::poses::Lie;\n\n// See .h for documentation\n\n// ====== SE(3) ===========\nSE<3>::type SE<3>::exp(const SE<3>::tangent_vector& x)\n{\n\treturn CPose3D(Lie::SO<3>::exp(x.tail<3>()), x.head<3>());\n}\n\nSE<3>::tangent_vector SE<3>::log(const SE<3>::type& P)\n{\n\ttangent_vector v;\n\tconst auto log_R = mrpt::poses::Lie::SO<3>::log(P.getRotationMatrix());\n\tv[0] = P.x();\n\tv[1] = P.y();\n\tv[2] = P.z();\n\tv[3] = log_R[0];\n\tv[4] = log_R[1];\n\tv[5] = log_R[2];\n\treturn v;\n}\n\nSE<3>::manifold_vector SE<3>::asManifoldVector(const SE<3>::type& pose)\n{\n\tmanifold_vector v;\n\tpose.getAs12Vector(v);\n\treturn v;\n}\n\nSE<3>::type SE<3>::fromManifoldVector(const SE<3>::manifold_vector& v)\n{\n\treturn type(v);\n}\n\n// See 10.3.1 in \\cite blanco_se3_tutorial\nSE<3>::tang2mat_jacob SE<3>::jacob_dexpe_de(const SE<3>::tangent_vector& x)\n{\n\t// 12x6 Jacobian:\n\ttang2mat_jacob J = tang2mat_jacob::Zero();\n\tJ.block<3, 3>(9, 0) = Eigen::Matrix3d::Identity();\n\tconst auto w = SO<3>::tangent_vector(x.tail<3>());\n\tJ.block<9, 3>(0, 3) = SO<3>::jacob_dexpe_de(w).asEigen();\n\treturn J;\n}\n\nSE<3>::mat2tang_jacob SE<3>::jacob_dlogv_dv(const SE<3>::type& P)\n{\n\tmrpt::math::CMatrixDouble6_12 J;\n\tJ.setZero();\n\tconst CMatrixDouble33& R = P.getRotationMatrix();\n\tJ.block<3, 9>(3, 0) = SO<3>::jacob_dlogv_dv(R).asEigen();\n\tJ(0, 9) = J(1, 10) = J(2, 11) = 1.0;\n\treturn J;\n}\n\n// Section 10.3.3 in tech report\n// http://ingmec.ual.es/~jlblanco/papers/jlblanco2010geometry3D_techrep.pdf\nSE<3>::tang2mat_jacob SE<3>::jacob_dexpeD_de(const CPose3D& D)\n{\n\tmrpt::math::CMatrixDouble12_6 jacob;\n\tjacob.block<9, 3>(0, 0).setZero();\n\tjacob.block<3, 3>(9, 0).setIdentity();\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tauto trg_blc = jacob.block<3, 3>(3 * i, 3);\n\t\tmrpt::math::skew_symmetric3_neg(\n\t\t\tD.getRotationMatrix().blockCopy<3, 1>(0, i), trg_blc);\n\t}\n\t{\n\t\tauto trg_blc = jacob.block<3, 3>(9, 3);\n\t\tmrpt::math::skew_symmetric3_neg(D.m_coords, trg_blc);\n\t}\n\treturn jacob;\n}\n\n// Section 10.3.4 in tech report\n// http://ingmec.ual.es/~jlblanco/papers/jlblanco2010geometry3D_techrep.pdf\nSE<3>::tang2mat_jacob SE<3>::jacob_dDexpe_de(const CPose3D& D)\n{\n\tmrpt::math::CMatrixDouble12_6 jacob;\n\tconst auto& dRot = D.getRotationMatrix();\n\tjacob.setZero();\n\tjacob.block<3, 3>(9, 0) = dRot.asEigen();\n\n\tjacob.block<3, 1>(3, 5) = -dRot.col(0);\n\tjacob.block<3, 1>(6, 4) = dRot.col(0);\n\n\tjacob.block<3, 1>(0, 5) = dRot.col(1);\n\tjacob.block<3, 1>(6, 3) = -dRot.col(1);\n\n\tjacob.block<3, 1>(0, 4) = -dRot.col(2);\n\tjacob.block<3, 1>(3, 3) = dRot.col(2);\n\treturn jacob;\n}\n\n// Eq. 10.3.7 in tech report\n// http://ingmec.ual.es/~jlblanco/papers/jlblanco2010geometry3D_techrep.pdf\nSE<3>::tang2mat_jacob SE<3>::jacob_dAexpeD_de(\n\tconst CPose3D& A, const CPose3D& D)\n{\n\tconst auto& Arot = A.getRotationMatrix();\n\n\tmrpt::math::CMatrixDouble12_6 jacob;\n\tjacob.block<9, 3>(0, 0).setZero();\n\tjacob.block<3, 3>(9, 0) = A.getRotationMatrix().asEigen();\n\tEigen::Matrix<double, 3, 3> aux;\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tmrpt::math::skew_symmetric3_neg(\n\t\t\tD.getRotationMatrix().blockCopy<3, 1>(0, i), aux);\n\t\tjacob.block<3, 3>(3 * i, 3) = Arot.asEigen() * aux;\n\t}\n\tmrpt::math::skew_symmetric3_neg(D.m_coords, aux);\n\tjacob.block<3, 3>(9, 3) = Arot.asEigen() * aux;\n\treturn jacob;\n}\n\nvoid SE<3>::jacob_dDinvP1invP2_de1e2(\n\tconst CPose3D& Dinv, const CPose3D& P1, const CPose3D& P2,\n\tmrpt::optional_ref<matrix_TxT> df_de1,\n\tmrpt::optional_ref<matrix_TxT> df_de2)\n{\n\tusing namespace mrpt::math;\n\n\t// The rotation matrix of the overall error expression:\n\tconst CPose3D P1inv = -P1;\n\tconst CPose3D DinvP1invP2 = Dinv + P1inv + P2;\n\n\t// Common part: d_PseudoLn(T)_dT:\n\t// (6x12 matrix)\n\tconst auto dLnT_dT = SE<3>::jacob_dlogv_dv(DinvP1invP2);\n\n\t// See section 10.3.10 of Tech. report:\n\t// \"A tutorial on SE(3) transformation parameterizations and on-manifold\n\t// optimization\"\n\tif (df_de1)\n\t{\n\t\tmatrix_TxT& J1 = df_de1.value().get();\n\n\t\tconst CMatrixFixed<double, 12, 12> J1a =\n\t\t\tSE<3>::jacob_dAB_dA(Dinv, P1inv + P2);\n\t\tconst auto J1b = CMatrixDouble12_6(-SE<3>::jacob_dDexpe_de(Dinv));\n\n\t\tJ1 = dLnT_dT.asEigen() * J1a.asEigen() * J1b.asEigen();\n\t}\n\tif (df_de2)\n\t{\n\t\tmatrix_TxT& J2 = df_de2.value().get();\n\t\tconst auto dAe_de = SE<3>::jacob_dDexpe_de(DinvP1invP2);\n\t\tJ2 = dLnT_dT * dAe_de;\n\t}\n}\n\nSE<3>::matrix_MxM SE<3>::jacob_dAB_dA(\n\tconst SE<3>::type& A, const SE<3>::type& B)\n{\n\tusing namespace mrpt::math;\n\n\tmatrix_MxM J = matrix_MxM::Zero();\n\t// J_wrt_A = kron(B,eye(3));\n\tconst auto B_HM =\n\t\tB.getHomogeneousMatrixVal<CMatrixDouble44>().transpose().eval();\n\tfor (int c = 0; c < 4; c++)\n\t\tfor (int r = 0; r < 4; r++)\n\t\t\tfor (int q = 0; q < 3; q++) J(r * 3 + q, c * 3 + q) = B_HM(r, c);\n\n\treturn J;\n}\n\nSE<3>::matrix_MxM SE<3>::jacob_dAB_dB(\n\tconst SE<3>::type& A, const SE<3>::type& B)\n{\n\tmatrix_MxM J = matrix_MxM::Zero();\n\t// J_wrt_B = kron(eye(3),A_rot);\n\tconst auto& AR = A.getRotationMatrix();\n\tfor (int c = 0; c < 4; c++) J.block<3, 3>(c * 3, c * 3) = AR.asEigen();\n\treturn J;\n}\n\n// See .h for documentation\n// ====== SE(2) ===========\nSE<2>::type SE<2>::exp(const SE<2>::tangent_vector& x)\n{\n\tSE<2>::type P;\n\tP.x(x[0]);\n\tP.y(x[1]);\n\tP.phi(x[2]);\n\treturn P;\n}\n\nSE<2>::tangent_vector SE<2>::log(const SE<2>::type& P)\n{\n\tSE<2>::tangent_vector x;\n\tx[0] = P.x();\n\tx[1] = P.y();\n\tx[2] = mrpt::math::wrapToPi(P.phi());\n\treturn x;\n}\n\nSE<2>::manifold_vector SE<2>::asManifoldVector(const SE<2>::type& pose)\n{\n\tmanifold_vector v;\n\tv[0] = pose.x();\n\tv[1] = pose.y();\n\tv[2] = mrpt::math::wrapToPi(pose.phi());\n\treturn v;\n}\n\nSE<2>::type SE<2>::fromManifoldVector(const SE<2>::manifold_vector& v)\n{\n\treturn type(v[0], v[1], mrpt::math::wrapToPi(v[2]));\n}\n\nSE<2>::matrix_MxM SE<2>::jacob_dAB_dA(\n\tconst SE<2>::type& A, const SE<2>::type& B)\n{\n\tconst auto bx = B.x(), by = B.y();\n\tconst auto cphia = A.phi_cos(), sphia = A.phi_sin();\n\n\tmatrix_MxM J = matrix_MxM::Identity();\n\tJ(0, 2) = -bx * sphia - by * cphia;\n\tJ(1, 2) = +bx * cphia - by * sphia;\n\treturn J;\n}\n\nSE<2>::matrix_MxM SE<2>::jacob_dAB_dB(\n\tconst SE<2>::type& A, const SE<2>::type& B)\n{\n\tmatrix_MxM J = matrix_MxM::Identity();\n\tconst auto cphia = A.phi_cos(), sphia = A.phi_sin();\n\tJ(0, 0) = cphia;\n\tJ(0, 1) = -sphia;\n\tJ(1, 0) = sphia;\n\tJ(1, 1) = cphia;\n\treturn J;\n}\n\nSE<2>::tang2mat_jacob SE<2>::jacob_dDexpe_de(const SE<2>::type& D)\n{\n\tconst auto c = D.phi_cos(), s = D.phi_sin();\n\n\t// clang-format off\n\treturn SE<2>::tang2mat_jacob((Eigen::Matrix3d() <<\n\t        c, -s, 0,\n\t        s,  c, 0,\n\t        0,  0, 1\n\t        ).finished());\n\t// clang-format on\n}\n\nvoid SE<2>::jacob_dDinvP1invP2_de1e2(\n\tconst CPose2D& Dinv, const CPose2D& P1, const CPose2D& P2,\n\tmrpt::optional_ref<matrix_TxT> df_de1,\n\tmrpt::optional_ref<matrix_TxT> df_de2)\n{\n\tconst CPose2D P1inv = -P1;\n\tconst CPose2D P1invP2 = P1inv + P2;\n\tconst CPose2D DinvP1invP2 = Dinv + P1invP2;\n\n\tif (df_de1)\n\t{\n\t\tauto& J1 = df_de1.value().get();\n\t\tJ1 = jacob_dAB_dA(Dinv, P1invP2).asEigen() * (-jacob_dDexpe_de(Dinv));\n\t}\n\n\tif (df_de2)\n\t{\n\t\tauto& J2 = df_de2.value().get();\n\t\tJ2 = SE<2>::jacob_dDexpe_de(DinvP1invP2);\n\t}\n}\n", "meta": {"hexsha": "88457471487a37f9e62c9b89b90e5a0db4538222", "size": 7893, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/poses/src/Lie/SE.cpp", "max_stars_repo_name": "zarmomin/mrpt", "max_stars_repo_head_hexsha": "1baff7cf8ec9fd23e1a72714553bcbd88c201966", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T06:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T06:24:08.000Z", "max_issues_repo_path": "libs/poses/src/Lie/SE.cpp", "max_issues_repo_name": "gao-ouyang/mrpt", "max_issues_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/poses/src/Lie/SE.cpp", "max_forks_repo_name": "gao-ouyang/mrpt", "max_forks_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T02:55:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T02:55:04.000Z", "avg_line_length": 26.8469387755, "max_line_length": 80, "alphanum_fraction": 0.6101609021, "num_tokens": 3037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5439988181240503}}
{"text": "// Copyright ETHZ 2017\n// autor: mathias, 2017, mathias.rothermel@geod.baug.ethz.ch  \n#include \"OriGeom.h\"\n#include \"Orientation.h\"\n#include <math.h>\n#include <Eigen/Dense>\n\nnamespace OriGeom\n{\n\n\tvoid computeRelative( const Orientation &identity, const Orientation &other, Orientation &out )\n\t{\n\t    \t// Copy\n\t    \tout=other;\n\n\t\t// First Cam (after transform this is identity)\n\t\tEigen::Vector3d C0=identity.getC();\n\t\tEigen::Matrix3d R0=identity.getR();\n\t\tEigen::Vector3d t0=(-1.0)*R0*C0;\n\t\t\n\t\t// Second cam\n\t\tEigen::Vector3d C1=other.getC();\n\t\tEigen::Matrix3d R1=other.getR();\n\t\tEigen::Matrix3d K1=other.getK();\n\t\tEigen::Vector3d t1=(-1.0)*R1*C1;\n\n\t\t// New cam\n\t\tEigen::Matrix3d R10=R1*R0.transpose();\n\t\tEigen::Vector3d C10=R1*C0+t1;\n\t\n\t\tout.setK(K1); \n\t\tout.setR(R10); \n\t\tout.setC(C10); \n\t}\n}\n", "meta": {"hexsha": "d038d94ca51c186ced16f8394c87cc67b2d42227", "size": 794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Ori/OriGeom.cpp", "max_stars_repo_name": "Hivemapper/MRef", "max_stars_repo_head_hexsha": "fb903a1587ea587f3f2a3233f4835bec3a82a1bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-26T14:22:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T09:41:13.000Z", "max_issues_repo_path": "Ori/OriGeom.cpp", "max_issues_repo_name": "Hivemapper/MRef", "max_issues_repo_head_hexsha": "fb903a1587ea587f3f2a3233f4835bec3a82a1bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ori/OriGeom.cpp", "max_forks_repo_name": "Hivemapper/MRef", "max_forks_repo_head_hexsha": "fb903a1587ea587f3f2a3233f4835bec3a82a1bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-14T19:07:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T19:07:40.000Z", "avg_line_length": 22.0555555556, "max_line_length": 96, "alphanum_fraction": 0.6687657431, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.6187804267137441, "lm_q1q2_score": 0.5439988041062577}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"functions/all_simplifications.hh\"\n#include \"functions/complex.hh\"\n#include \"functions/operators.hh\"\n#include \"functions/streaming.hh\"\n\nBOOST_AUTO_TEST_CASE(complex_test) {\n  using namespace manifolds;\n  static_assert(ComplexOutputType<decltype(x)>::value == NeverComplex, \"\");\n  BOOST_CHECK_EQUAL(Simplify(Real()(x)), x);\n  BOOST_CHECK_EQUAL(Simplify(Imag()(x)), zero);\n  BOOST_CHECK_EQUAL(Phase(), Arg());\n  auto r_phase = Simplify(Phase()(x));\n  BOOST_CHECK_EQUAL(r_phase(3), 0);\n  BOOST_CHECK_EQUAL(r_phase(-3), -M_PI);\n  BOOST_CHECK_EQUAL(Simplify(Real()(I)), zero);\n  BOOST_CHECK_EQUAL(Simplify(Imag()(I)), IP<1>());\n  BOOST_CHECK_EQUAL(Simplify(Norm()(I)), IP<1>());\n  BOOST_CHECK_EQUAL(Simplify(Norm()(x)), x * x);\n  BOOST_CHECK_EQUAL(Simplify(Conjugate()(I)), -I);\n  BOOST_CHECK_EQUAL(Simplify(Conjugate()(x)), x);\n  BOOST_CHECK_EQUAL(Simplify(I(x)), I);\n  BOOST_CHECK_EQUAL(Simplify(IP<1, 1, 1, 1, 1, 1>()(I)), IP<1>() + I);\n  BOOST_CHECK_EQUAL(Simplify(IP<0, 0, 1>()(I)), IP<-1>());\n  BOOST_CHECK_EQUAL(Simplify(Real()(IP<1>() * I + x)), x);\n  BOOST_CHECK_EQUAL(Simplify(Imag()(IP<1>() * I + x)), IP<1>());\n  BOOST_CHECK_EQUAL(Simplify(Real()((I + Sin()(x)) * (I + Cos()(x)))),\n                    (Sin() * Cos())(x) - IP<1>());\n  BOOST_CHECK_EQUAL(Simplify(IP<1, 2, 3, 4, 5, 6, 7>()(Sign())),\n                    (IP<16, 12>()(Sign())));\n  BOOST_CHECK_EQUAL(Simplify(GetPolynomial(1, 2, 3, 4, 5, 6, 7)(Sign())),\n                    GetPolynomial(16, 12)(Sign()));\n}\n", "meta": {"hexsha": "5c9504560337ede8822d0c3fb226de38083f8a6c", "size": 1523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_complex.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_complex.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_complex.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": 44.7941176471, "max_line_length": 75, "alphanum_fraction": 0.6355876559, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5439934668020335}}
{"text": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    // We could just use (1 << 18) instead of tmpres, but let's point out one\n    // pecularity with gmp and hence boost::multiprecision: they won't accept\n    // a second mpz_int with pow(). Therefore, if we stick to multiprecision\n    // pow we need to convert_to<uint64_t>().\n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20)\n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "48b290e6756d4f26adb1508e4c447a14bc24eba2", "size": 883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/arbitrary-precision-integers--included-.cpp", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "lang/C++/arbitrary-precision-integers--included-.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++/arbitrary-precision-integers--included-.cpp", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7916666667, "max_line_length": 77, "alphanum_fraction": 0.5526613817, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.6261241772283033, "lm_q1q2_score": 0.5439934504260523}}
{"text": "\n\n#include <NTL/GF2EXFactoring.h>\n#include <NTL/vec_GF2XVec.h>\n#include <NTL/fileio.h>\n#include <NTL/FacVec.h>\n\n#include <stdio.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\n\n\n\nstatic\nvoid IterSqr(GF2E& c, const GF2E& a, long n)\n{\n   GF2E res;\n\n   long i;\n\n   res = a;\n\n   for (i = 0; i < n; i++)\n      sqr(res, res);\n\n   c = res;\n}\n   \n\n\nvoid SquareFreeDecomp(vec_pair_GF2EX_long& u, const GF2EX& ff)\n{\n   GF2EX f = ff;\n\n   if (!IsOne(LeadCoeff(f)))\n      Error(\"SquareFreeDecomp: bad args\");\n\n   GF2EX r, t, v, tmp1;\n   long m, j, finished, done;\n\n   u.SetLength(0);\n\n   if (deg(f) == 0)\n      return;\n\n   m = 1;\n   finished = 0;\n\n   do {\n      j = 1;\n      diff(tmp1, f);\n      GCD(r, f, tmp1);\n      div(t, f, r);\n\n      if (deg(t) > 0) {\n         done = 0;\n         do {\n            GCD(v, r, t);\n            div(tmp1, t, v);\n            if (deg(tmp1) > 0) append(u, cons(tmp1, j*m));\n            if (deg(v) > 0) {\n               div(r, r, v);\n               t = v;\n               j++;\n            }\n            else\n               done = 1;\n         } while (!done);\n         if (deg(r) == 0) finished = 1;\n      }\n\n      if (!finished) {\n         /* r is a square */\n\n         long k, d;\n         d = deg(r)/2;\n         f.rep.SetLength(d+1);\n         for (k = 0; k <= d; k++) \n            IterSqr(f.rep[k], r.rep[k*2], GF2E::degree()-1);\n         m = m*2;\n      }\n   } while (!finished);\n}\n         \n\n\nstatic\nvoid NullSpace(long& r, vec_long& D, vec_GF2XVec& M, long verbose)\n{\n   long k, l, n;\n   long i, j;\n   long pos;\n   GF2X t1, t2;\n   GF2X *x, *y;\n\n   const GF2XModulus& p = GF2E::modulus();\n\n   n = M.length();\n\n   D.SetLength(n);\n   for (j = 0; j < n; j++) D[j] = -1;\n\n   r = 0;\n\n   l = 0;\n   for (k = 0; k < n; k++) {\n\n      if (verbose && k % 10 == 0) cerr << \"+\";\n\n      pos = -1;\n      for (i = l; i < n; i++) {\n         rem(t1, M[i][k], p);\n         M[i][k] = t1;\n         if (pos == -1 && !IsZero(t1))\n            pos = i;\n      }\n\n      if (pos != -1) {\n         swap(M[pos], M[l]);\n\n         // make M[l, k] == -1 mod p, and make row l reduced\n\n         InvMod(t1, M[l][k], p);\n         for (j = k+1; j < n; j++) {\n            rem(t2, M[l][j], p);\n            MulMod(M[l][j], t2, t1, p);\n         }\n\n         for (i = l+1; i < n; i++) {\n            // M[i] = M[i] + M[l]*M[i,k]\n\n            t1 = M[i][k];   // this is already reduced\n\n            x = M[i].elts() + (k+1);\n            y = M[l].elts() + (k+1);\n\n            for (j = k+1; j < n; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               mul(t2, *y, t1);\n               add(*x, *x, t2);\n            }\n         }\n\n         D[k] = l;   // variable k is defined by row l\n         l++;\n\n      }\n      else {\n         r++;\n      }\n   }\n}\n\n\n\nstatic\nvoid BuildMatrix(vec_GF2XVec& M, long n, const GF2EX& g, const GF2EXModulus& F,\n                 long verbose)\n{\n   long i, j, m;\n   GF2EX h;\n\n\n   M.SetLength(n);\n   for (i = 0; i < n; i++)\n      M[i].SetSize(n, 2*GF2E::WordLength());\n\n   set(h);\n   for (j = 0; j < n; j++) {\n      if (verbose && j % 10 == 0) cerr << \"+\";\n\n      m = deg(h);\n      for (i = 0; i < n; i++) {\n         if (i <= m)\n            M[i][j] = rep(h.rep[i]);\n         else\n            clear(M[i][j]);\n      }\n\n      if (j < n-1)\n         MulMod(h, h, g, F);\n   }\n\n   for (i = 0; i < n; i++)\n      add(M[i][i], M[i][i], 1);\n\n}\n\n\nstatic\nvoid TraceMap(GF2EX& h, const GF2EX& a, const GF2EXModulus& F)\n\n// one could consider making a version based on modular composition,\n// as in ComposeFrobeniusMap...\n\n{\n   GF2EX res, tmp;\n\n   res = a;\n   tmp = a;\n\n   long i;\n   for (i = 0; i < GF2E::degree()-1; i++) {\n      SqrMod(tmp, tmp, F);\n      add(res, res, tmp);\n   }\n\n   h = res;\n}\n\nvoid PlainFrobeniusMap(GF2EX& h, const GF2EXModulus& F)\n{\n   GF2EX res;\n\n   SetX(res);\n   long i;\n   for (i = 0; i < GF2E::degree(); i++) \n      SqrMod(res, res, F);\n\n   h = res;\n}\n\nlong UseComposeFrobenius(long d, long n)\n{\n   long i;\n   i = 1;\n   while (i <= d) i = i << 1;\n   i = i >> 1;\n\n   i = i >> 1;\n   long m = 1;\n\n   long dz;\n\n   if (n == 2) {\n      dz = 1;\n   }\n   else {\n      while (i) {\n         long m1 = 2*m;\n         if (i & d) m1++;\n   \n         if (m1 >= NTL_BITS_PER_LONG-1 || (1L << m1) >= n) break;\n   \n         m = m1;\n         i = i >> 1;\n      }\n\n      dz = 1L << m;\n   }\n\n   long rootn = SqrRoot(n);\n   long cnt = 0;\n\n   if (i) {\n      cnt += SqrRoot(dz+1);\n      i = i >> 1;\n   }\n\n   while (i) {\n      cnt += rootn;\n      i = i >> 1;\n   }\n\n   return 4*cnt <= d;\n}\n\nvoid ComposeFrobeniusMap(GF2EX& y, const GF2EXModulus& F)\n{\n   long d = GF2E::degree();\n   long n = deg(F);\n\n   long i;\n   i = 1;\n   while (i <= d) i = i << 1;\n   i = i >> 1;\n\n   GF2EX z(INIT_SIZE, n), z1(INIT_SIZE, n);\n\n   i = i >> 1;\n   long m = 1;\n\n   if (n == 2) {\n      SetX(z);\n      SqrMod(z, z, F);\n   }\n   else {\n      while (i) {\n         long m1 = 2*m;\n         if (i & d) m1++;\n   \n         if (m1 >= NTL_BITS_PER_LONG-1 || (1L << m1) >= n) break;\n   \n         m = m1;\n         i = i >> 1;\n      }\n\n      clear(z);\n      SetCoeff(z, 1L << m);\n   }\n\n\n   while (i) {\n      z1 = z;\n\n      long j, k, dz;\n      dz = deg(z);\n\n      for (j = 0; j <= dz; j++)\n         for (k = 0; k < m; k++)\n            sqr(z1.rep[j], z1.rep[j]);\n\n      CompMod(z, z1, z, F);\n      m = 2*m;\n\n      if (d & i) {\n         SqrMod(z, z, F);\n         m++;\n      }\n\n      i = i >> 1;\n   }\n\n   y = z;\n}\n\nvoid FrobeniusMap(GF2EX& h, const GF2EXModulus& F)\n{\n   long n = deg(F);\n   long d = GF2E::degree();\n\n   if (n == 1) {\n      h = ConstTerm(F);\n      return;\n   }\n\n   if (UseComposeFrobenius(d, n))\n      ComposeFrobeniusMap(h, F);\n   else\n      PlainFrobeniusMap(h, F);\n}\n\n\n\n   \n\n\n\nstatic\nvoid RecFindRoots(vec_GF2E& x, const GF2EX& f)\n{\n   if (deg(f) == 0) return;\n\n   if (deg(f) == 1) {\n      long k = x.length();\n      x.SetLength(k+1);\n      x[k] = ConstTerm(f);\n      return;\n   }\n      \n   GF2EX h;\n\n   GF2E r;\n\n   \n   {\n      GF2EXModulus F;\n      build(F, f);\n\n      do {\n         random(r);\n         clear(h);\n         SetCoeff(h, 1, r);\n         TraceMap(h, h, F);\n         GCD(h, h, f);\n      } while (deg(h) <= 0 || deg(h) == deg(f));\n   }\n\n   RecFindRoots(x, h);\n   div(h, f, h); \n   RecFindRoots(x, h);\n}\n\nvoid FindRoots(vec_GF2E& x, const GF2EX& ff)\n{\n   GF2EX f = ff;\n\n   if (!IsOne(LeadCoeff(f)))\n      Error(\"FindRoots: bad args\");\n\n   x.SetMaxLength(deg(f));\n   x.SetLength(0);\n   RecFindRoots(x, f);\n}\n\n\nstatic\nvoid RandomBasisElt(GF2EX& g, const vec_long& D, const vec_GF2XVec& M)\n{\n   static GF2X t1, t2;\n\n   long n = D.length();\n\n   long i, j, s;\n\n   g.rep.SetLength(n);\n\n   vec_GF2E& v = g.rep;\n\n   for (j = n-1; j >= 0; j--) {\n      if (D[j] == -1)\n         random(v[j]);\n      else {\n         i = D[j];\n\n         // v[j] = sum_{s=j+1}^{n-1} v[s]*M[i,s]\n\n         clear(t1);\n\n         for (s = j+1; s < n; s++) {\n            mul(t2, rep(v[s]), M[i][s]);\n            add(t1, t1, t2);\n         }\n\n         conv(v[j], t1);\n      }\n   }\n\n   g.normalize();\n}\n\n\n\nstatic\nvoid split(GF2EX& f1, GF2EX& g1, GF2EX& f2, GF2EX& g2,\n           const GF2EX& f, const GF2EX& g, \n           const vec_GF2E& roots, long lo, long mid)\n{\n   long r = mid-lo+1;\n\n   GF2EXModulus F;\n   build(F, f);\n\n   vec_GF2E lroots(INIT_SIZE, r);\n   long i;\n\n   for (i = 0; i < r; i++)\n      lroots[i] = roots[lo+i];\n\n\n   GF2EX h, a, d;\n   BuildFromRoots(h, lroots);\n   CompMod(a, h, g, F);\n\n\n   GCD(f1, a, f);\n   \n   div(f2, f, f1);\n\n   rem(g1, g, f1);\n   rem(g2, g, f2);\n}\n\nstatic\nvoid RecFindFactors(vec_GF2EX& factors, const GF2EX& f, const GF2EX& g,\n                    const vec_GF2E& roots, long lo, long hi)\n{\n   long r = hi-lo+1;\n\n   if (r == 0) return;\n\n   if (r == 1) {\n      append(factors, f);\n      return;\n   }\n\n   GF2EX f1, g1, f2, g2;\n\n   long mid = (lo+hi)/2;\n\n   split(f1, g1, f2, g2, f, g, roots, lo, mid);\n\n   RecFindFactors(factors, f1, g1, roots, lo, mid);\n   RecFindFactors(factors, f2, g2, roots, mid+1, hi);\n}\n\n\nstatic\nvoid FindFactors(vec_GF2EX& factors, const GF2EX& f, const GF2EX& g,\n                 const vec_GF2E& roots)\n{\n   long r = roots.length();\n\n   factors.SetMaxLength(r);\n   factors.SetLength(0);\n\n   RecFindFactors(factors, f, g, roots, 0, r-1);\n}\n\n#if 0\n\nstatic\nvoid IterFindFactors(vec_GF2EX& factors, const GF2EX& f,\n                     const GF2EX& g, const vec_GF2E& roots)\n{\n   long r = roots.length();\n   long i;\n   GF2EX h;\n\n   factors.SetLength(r);\n\n   for (i = 0; i < r; i++) {\n      add(h, g, roots[i]);\n      GCD(factors[i], f, h);\n   }\n}\n\n#endif\n\n\n   \n\nvoid SFBerlekamp(vec_GF2EX& factors, const GF2EX& ff, long verbose)\n{\n   GF2EX f = ff;\n\n   if (!IsOne(LeadCoeff(f)))\n      Error(\"SFBerlekamp: bad args\");\n\n   if (deg(f) == 0) {\n      factors.SetLength(0);\n      return;\n   }\n\n   if (deg(f) == 1) {\n      factors.SetLength(1);\n      factors[0] = f;\n      return;\n   }\n\n   double t;\n\n   long n = deg(f);\n\n   GF2EXModulus F;\n\n   build(F, f);\n\n   GF2EX g, h;\n\n   if (verbose) { cerr << \"computing X^p...\"; t = GetTime(); }\n   FrobeniusMap(g, F);\n   if (verbose) { cerr << (GetTime()-t) << \"\\n\"; }\n\n   vec_long D;\n   long r;\n\n   vec_GF2XVec M;\n\n   if (verbose) { cerr << \"building matrix...\"; t = GetTime(); }\n   BuildMatrix(M, n, g, F, verbose);\n   if (verbose) { cerr << (GetTime()-t) << \"\\n\"; }\n\n   if (verbose) { cerr << \"diagonalizing...\"; t = GetTime(); }\n   NullSpace(r, D, M, verbose);\n   if (verbose) { cerr << (GetTime()-t) << \"\\n\"; }\n\n\n   if (verbose) cerr << \"number of factors = \" << r << \"\\n\";\n\n   if (r == 1) {\n      factors.SetLength(1);\n      factors[0] = f;\n      return;\n   }\n\n   if (verbose) { cerr << \"factor extraction...\"; t = GetTime(); }\n\n   vec_GF2E roots;\n\n   RandomBasisElt(g, D, M);\n   MinPolyMod(h, g, F, r);\n   if (deg(h) == r) M.kill();\n   FindRoots(roots, h);\n   FindFactors(factors, f, g, roots);\n\n   GF2EX g1;\n   vec_GF2EX S, S1;\n   long i;\n\n   while (factors.length() < r) {\n      if (verbose) cerr << \"+\";\n      RandomBasisElt(g, D, M);\n      S.kill();\n      for (i = 0; i < factors.length(); i++) {\n         const GF2EX& f = factors[i];\n         if (deg(f) == 1) {\n            append(S, f);\n            continue;\n         }\n         build(F, f);\n         rem(g1, g, F);\n         if (deg(g1) <= 0) {\n            append(S, f);\n            continue;\n         }\n         MinPolyMod(h, g1, F, min(deg(f), r-factors.length()+1));\n         FindRoots(roots, h);\n         S1.kill();\n         FindFactors(S1, f, g1, roots);\n         append(S, S1);\n      }\n      swap(factors, S);\n   }\n\n   if (verbose) { cerr << (GetTime()-t) << \"\\n\"; }\n\n   if (verbose) {\n      cerr << \"degrees:\";\n      long i;\n      for (i = 0; i < factors.length(); i++)\n         cerr << \" \" << deg(factors[i]);\n      cerr << \"\\n\";\n   }\n}\n\n\nvoid berlekamp(vec_pair_GF2EX_long& factors, const GF2EX& f, long verbose)\n{\n   double t;\n   vec_pair_GF2EX_long sfd;\n   vec_GF2EX x;\n\n   if (!IsOne(LeadCoeff(f)))\n      Error(\"berlekamp: bad args\");\n\n   \n   if (verbose) { cerr << \"square-free decomposition...\"; t = GetTime(); }\n   SquareFreeDecomp(sfd, f);\n   if (verbose) cerr << (GetTime()-t) << \"\\n\";\n\n   factors.SetLength(0);\n\n   long i, j;\n\n   for (i = 0; i < sfd.length(); i++) {\n      if (verbose) {\n         cerr << \"factoring multiplicity \" << sfd[i].b \n              << \", deg = \" << deg(sfd[i].a) << \"\\n\";\n      }\n\n      SFBerlekamp(x, sfd[i].a, verbose);\n\n      for (j = 0; j < x.length(); j++)\n         append(factors, cons(x[j], sfd[i].b));\n   }\n}\n\n\n\nstatic\nvoid AddFactor(vec_pair_GF2EX_long& factors, const GF2EX& g, long d, long verbose)\n{\n   if (verbose)\n      cerr << \"degree=\" << d << \", number=\" << deg(g)/d << \"\\n\";\n   append(factors, cons(g, d));\n}\n\nstatic\nvoid ProcessTable(GF2EX& f, vec_pair_GF2EX_long& factors, \n                  const GF2EXModulus& F, long limit, const vec_GF2EX& tbl,\n                  long d, long verbose)\n\n{\n   if (limit == 0) return;\n\n   if (verbose) cerr << \"+\";\n\n   GF2EX t1;\n\n   if (limit == 1) {\n      GCD(t1, f, tbl[0]);\n      if (deg(t1) > 0) {\n         AddFactor(factors, t1, d, verbose);\n         div(f, f, t1);\n      }\n\n      return;\n   }\n\n   long i;\n\n   t1 = tbl[0];\n   for (i = 1; i < limit; i++)\n      MulMod(t1, t1, tbl[i], F);\n\n   GCD(t1, f, t1);\n\n   if (deg(t1) == 0) return;\n\n   div(f, f, t1);\n\n   GF2EX t2;\n\n   i = 0;\n   d = d - limit + 1;\n\n   while (2*d <= deg(t1)) {\n      GCD(t2, tbl[i], t1); \n      if (deg(t2) > 0) {\n         AddFactor(factors, t2, d, verbose);\n         div(t1, t1, t2);\n      }\n\n      i++;\n      d++;\n   }\n\n   if (deg(t1) > 0)\n      AddFactor(factors, t1, deg(t1), verbose);\n}\n\n\nvoid TraceMap(GF2EX& w, const GF2EX& a, long d, const GF2EXModulus& F, \n              const GF2EX& b)\n\n{\n   if (d < 0) Error(\"TraceMap: bad args\");\n\n   GF2EX y, z, t;\n\n   z = b;\n   y = a;\n   clear(w);\n\n   while (d) {\n      if (d == 1) {\n         if (IsZero(w)) \n            w = y;\n         else {\n            CompMod(w, w, z, F);\n            add(w, w, y);\n         }\n      }\n      else if ((d & 1) == 0) {\n         Comp2Mod(z, t, z, y, z, F);\n         add(y, t, y);\n      }\n      else if (IsZero(w)) {\n         w = y;\n         Comp2Mod(z, t, z, y, z, F);\n         add(y, t, y);\n      }\n      else {\n         Comp3Mod(z, t, w, z, y, w, z, F);\n         add(w, w, y);\n         add(y, t, y);\n      }\n\n      d = d >> 1;\n   }\n}\n\n\nvoid PowerCompose(GF2EX& y, const GF2EX& h, long q, const GF2EXModulus& F)\n{\n   if (q < 0) Error(\"powerCompose: bad args\");\n\n   GF2EX z(INIT_SIZE, F.n);\n   long sw;\n\n   z = h;\n   SetX(y);\n\n   while (q) {\n      sw = 0;\n\n      if (q > 1) sw = 2;\n      if (q & 1) {\n         if (IsX(y))\n            y = z;\n         else\n            sw = sw | 1;\n      }\n\n      switch (sw) {\n      case 0:\n         break;\n\n      case 1:\n         CompMod(y, y, z, F);\n         break;\n\n      case 2:\n         CompMod(z, z, z, F);\n         break;\n\n      case 3:\n         Comp2Mod(y, z, y, z, z, F);\n         break;\n      }\n\n      q = q >> 1;\n   }\n}\n\n\nlong ProbIrredTest(const GF2EX& f, long iter)\n{\n   long n = deg(f);\n\n   if (n <= 0) return 0;\n   if (n == 1) return 1;\n\n   GF2EXModulus F;\n\n   build(F, f);\n\n   GF2EX b, r, s;\n\n   FrobeniusMap(b, F);\n\n   long all_zero = 1;\n\n   long i;\n\n   for (i = 0; i < iter; i++) {\n      random(r, n);\n      TraceMap(s, r, n, F, b);\n\n      all_zero = all_zero && IsZero(s);\n\n      if (deg(s) > 0) return 0;\n   }\n\n   if (!all_zero || (n & 1)) return 1;\n\n   PowerCompose(s, b, n/2, F);\n   return !IsX(s);\n}\n\n\nlong GF2EX_BlockingFactor = 10;\n\nvoid DDF(vec_pair_GF2EX_long& factors, const GF2EX& ff, const GF2EX& hh, \n         long verbose)\n{\n   GF2EX f = ff;\n   GF2EX h = hh;\n\n   if (!IsOne(LeadCoeff(f)))\n      Error(\"DDF: bad args\");\n\n   factors.SetLength(0);\n\n   if (deg(f) == 0)\n      return;\n\n   if (deg(f) == 1) {\n      AddFactor(factors, f, 1, verbose);\n      return;\n   }\n\n   long CompTableSize = 2*SqrRoot(deg(f)); \n\n   long GCDTableSize = GF2EX_BlockingFactor;\n\n   GF2EXModulus F;\n   build(F, f);\n\n   GF2EXArgument H;\n\n   build(H, h, F, min(CompTableSize, deg(f)));\n\n   long i, d, limit, old_n;\n   GF2EX g, X;\n\n\n   vec_GF2EX tbl(INIT_SIZE, GCDTableSize);\n\n   SetX(X);\n\n   i = 0;\n   g = h;\n   d = 1;\n   limit = GCDTableSize;\n\n\n   while (2*d <= deg(f)) {\n\n      old_n = deg(f);\n      add(tbl[i], g, X);\n      i++;\n      if (i == limit) {\n         ProcessTable(f, factors, F, i, tbl, d, verbose);\n         i = 0;\n      }\n\n      d = d + 1;\n      if (2*d <= deg(f)) {\n         // we need to go further\n\n         if (deg(f) < old_n) {\n            // f has changed \n\n            build(F, f);\n            rem(h, h, f);\n            rem(g, g, f);\n            build(H, h, F, min(CompTableSize, deg(f)));\n         }\n\n         CompMod(g, g, H, F);\n      }\n   }\n\n   ProcessTable(f, factors, F, i, tbl, d-1, verbose);\n\n   if (!IsOne(f)) AddFactor(factors, f, deg(f), verbose);\n}\n\n\n\nvoid RootEDF(vec_GF2EX& factors, const GF2EX& f, long verbose)\n{\n   vec_GF2E roots;\n   double t;\n\n   if (verbose) { cerr << \"finding roots...\"; t = GetTime(); }\n   FindRoots(roots, f);\n   if (verbose) { cerr << (GetTime()-t) << \"\\n\"; }\n\n   long r = roots.length();\n   factors.SetLength(r);\n   for (long j = 0; j < r; j++) {\n      SetX(factors[j]);\n      add(factors[j], factors[j], roots[j]);\n   }\n}\n\nstatic\nvoid EDFSplit(vec_GF2EX& v, const GF2EX& f, const GF2EX& b, long d)\n{\n   GF2EX a, g, h;\n   GF2EXModulus F;\n   vec_GF2E roots;\n   \n   build(F, f);\n   long n = F.n;\n   long r = n/d;\n   random(a, n);\n   TraceMap(g, a, d, F, b);\n   MinPolyMod(h, g, F, r);\n   FindRoots(roots, h);\n   FindFactors(v, f, g, roots);\n}\n\nstatic\nvoid RecEDF(vec_GF2EX& factors, const GF2EX& f, const GF2EX& b, long d,\n            long verbose)\n{\n   vec_GF2EX v;\n   long i;\n   GF2EX bb;\n\n   if (verbose) cerr << \"+\";\n\n   EDFSplit(v, f, b, d);\n   for (i = 0; i < v.length(); i++) {\n      if (deg(v[i]) == d) {\n         append(factors, v[i]);\n      }\n      else {\n         GF2EX bb;\n         rem(bb, b, v[i]);\n         RecEDF(factors, v[i], bb, d, verbose);\n      }\n   }\n}\n         \n\nvoid EDF(vec_GF2EX& factors, const GF2EX& ff, const GF2EX& bb,\n         long d, long verbose)\n\n{\n   GF2EX f = ff;\n   GF2EX b = bb;\n\n   if (!IsOne(LeadCoeff(f)))\n      Error(\"EDF: bad args\");\n\n   long n = deg(f);\n   long r = n/d;\n\n   if (r == 0) {\n      factors.SetLength(0);\n      return;\n   }\n\n   if (r == 1) {\n      factors.SetLength(1);\n      factors[0] = f;\n      return;\n   }\n\n   if (d == 1) {\n      RootEDF(factors, f, verbose);\n      return;\n   }\n\n   \n   double t;\n   if (verbose) { \n      cerr << \"computing EDF(\" << d << \",\" << r << \")...\"; \n      t = GetTime(); \n   }\n\n   factors.SetLength(0);\n\n   RecEDF(factors, f, b, d, verbose);\n\n   if (verbose) cerr << (GetTime()-t) << \"\\n\";\n}\n\n\nvoid SFCanZass(vec_GF2EX& factors, const GF2EX& ff, long verbose)\n{\n   GF2EX f = ff;\n\n   if (!IsOne(LeadCoeff(f)))\n      Error(\"SFCanZass: bad args\");\n\n   if (deg(f) == 0) {\n      factors.SetLength(0);\n      return;\n   }\n\n   if (deg(f) == 1) {\n      factors.SetLength(1);\n      factors[0] = f;\n      return;\n   }\n\n   factors.SetLength(0);\n\n   double t;\n\n   \n   GF2EXModulus F;\n   build(F, f);\n\n   GF2EX h;\n\n   if (verbose) { cerr << \"computing X^p...\"; t = GetTime(); }\n   FrobeniusMap(h, F);\n   if (verbose) { cerr << (GetTime()-t) << \"\\n\"; }\n\n   vec_pair_GF2EX_long u;\n   if (verbose) { cerr << \"computing DDF...\"; t = GetTime(); }\n   NewDDF(u, f, h, verbose);\n   if (verbose) { \n      t = GetTime()-t; \n      cerr << \"DDF time: \" << t << \"\\n\";\n   }\n\n   GF2EX hh;\n   vec_GF2EX v;\n\n   long i;\n   for (i = 0; i < u.length(); i++) {\n      const GF2EX& g = u[i].a;\n      long d = u[i].b;\n      long r = deg(g)/d;\n\n      if (r == 1) {\n         // g is already irreducible\n\n         append(factors, g);\n      }\n      else {\n         // must perform EDF\n\n         if (d == 1) {\n            // root finding\n            RootEDF(v, g, verbose);\n            append(factors, v);\n         }\n         else {\n            // general case\n            rem(hh, h, g);\n            EDF(v, g, hh, d, verbose);\n            append(factors, v);\n         }\n      }\n   }\n}\n   \nvoid CanZass(vec_pair_GF2EX_long& factors, const GF2EX& f, long verbose)\n{\n   if (!IsOne(LeadCoeff(f)))\n      Error(\"CanZass: bad args\");\n\n   double t;\n   vec_pair_GF2EX_long sfd;\n   vec_GF2EX x;\n\n   \n   if (verbose) { cerr << \"square-free decomposition...\"; t = GetTime(); }\n   SquareFreeDecomp(sfd, f);\n   if (verbose) cerr << (GetTime()-t) << \"\\n\";\n\n   factors.SetLength(0);\n\n   long i, j;\n\n   for (i = 0; i < sfd.length(); i++) {\n      if (verbose) {\n         cerr << \"factoring multiplicity \" << sfd[i].b \n              << \", deg = \" << deg(sfd[i].a) << \"\\n\";\n      }\n\n      SFCanZass(x, sfd[i].a, verbose);\n\n      for (j = 0; j < x.length(); j++)\n         append(factors, cons(x[j], sfd[i].b));\n   }\n}\n\nvoid mul(GF2EX& f, const vec_pair_GF2EX_long& v)\n{\n   long i, j, n;\n\n   n = 0;\n   for (i = 0; i < v.length(); i++)\n      n += v[i].b*deg(v[i].a);\n\n   GF2EX g(INIT_SIZE, n+1);\n\n   set(g);\n   for (i = 0; i < v.length(); i++)\n      for (j = 0; j < v[i].b; j++) {\n         mul(g, g, v[i].a);\n      }\n\n   f = g;\n}\n\n\n\n\nstatic\nlong BaseCase(const GF2EX& h, long q, long a, const GF2EXModulus& F)\n{\n   long b, e;\n   GF2EX lh(INIT_SIZE, F.n);\n\n   lh = h;\n   b = 1;\n   e = 0;\n   while (e < a-1 && !IsX(lh)) {\n      e++;\n      b *= q;\n      PowerCompose(lh, lh, q, F);\n   }\n\n   if (!IsX(lh)) b *= q;\n\n   return b;\n}\n\n\n\nstatic\nvoid TandemPowerCompose(GF2EX& y1, GF2EX& y2, const GF2EX& h, \n                        long q1, long q2, const GF2EXModulus& F)\n{\n   GF2EX z(INIT_SIZE, F.n);\n   long sw;\n\n   z = h;\n   SetX(y1);\n   SetX(y2);\n\n   while (q1 || q2) {\n      sw = 0;\n\n      if (q1 > 1 || q2 > 1) sw = 4;\n\n      if (q1 & 1) {\n         if (IsX(y1))\n            y1 = z;\n         else\n            sw = sw | 2;\n      }\n\n      if (q2 & 1) {\n         if (IsX(y2))\n            y2 = z;\n         else\n            sw = sw | 1;\n      }\n\n      switch (sw) {\n      case 0:\n         break;\n\n      case 1:\n         CompMod(y2, y2, z, F);\n         break;\n\n      case 2:\n         CompMod(y1, y1, z, F);\n         break;\n\n      case 3:\n         Comp2Mod(y1, y2, y1, y2, z, F);\n         break;\n\n      case 4:\n         CompMod(z, z, z, F);\n         break;\n\n      case 5:\n         Comp2Mod(z, y2, z, y2, z, F);\n         break;\n\n      case 6:\n         Comp2Mod(z, y1, z, y1, z, F);\n         break;\n\n      case 7:\n         Comp3Mod(z, y1, y2, z, y1, y2, z, F);\n         break;\n      }\n\n      q1 = q1 >> 1;\n      q2 = q2 >> 1;\n   }\n}\n\n\n\nstatic\nlong RecComputeDegree(long u, const GF2EX& h, const GF2EXModulus& F,\n                      FacVec& fvec)\n{\n   if (IsX(h)) return 1;\n\n   if (fvec[u].link == -1) return BaseCase(h, fvec[u].q, fvec[u].a, F);\n\n   GF2EX h1, h2;\n   long q1, q2, r1, r2;\n\n   q1 = fvec[fvec[u].link].val; \n   q2 = fvec[fvec[u].link+1].val;\n\n   TandemPowerCompose(h1, h2, h, q1, q2, F);\n   r1 = RecComputeDegree(fvec[u].link, h2, F, fvec);\n   r2 = RecComputeDegree(fvec[u].link+1, h1, F, fvec);\n   return r1*r2;\n}\n\n   \n\n\nlong RecComputeDegree(const GF2EX& h, const GF2EXModulus& F)\n   // f = F.f is assumed to be an \"equal degree\" polynomial\n   // h = X^p mod f\n   // the common degree of the irreducible factors of f is computed\n{\n   if (F.n == 1 || IsX(h)) \n      return 1;\n\n   FacVec fvec;\n\n   FactorInt(fvec, F.n);\n\n   return RecComputeDegree(fvec.length()-1, h, F, fvec);\n}\n\n\nvoid FindRoot(GF2E& root, const GF2EX& ff)\n// finds a root of ff.\n// assumes that ff is monic and splits into distinct linear factors\n\n{\n   GF2EXModulus F;\n   GF2EX h, h1, f;\n   GF2E r;\n\n   f = ff;\n   \n   if (!IsOne(LeadCoeff(f)))\n      Error(\"FindRoot: bad args\");\n\n   if (deg(f) == 0)\n      Error(\"FindRoot: bad args\");\n\n\n   while (deg(f) > 1) {\n      build(F, f);\n      random(r);\n      clear(h);\n      SetCoeff(h, 1, r);\n      TraceMap(h, h, F);\n      GCD(h, h, f);\n      if (deg(h) > 0 && deg(h) < deg(f)) {\n         if (deg(h) > deg(f)/2)\n            div(f, f, h);\n         else\n            f = h;\n      }\n   }\n \n   root = ConstTerm(f);\n}\n\n\nstatic\nlong power(long a, long e)\n{\n   long i, res;\n\n   res = 1;\n   for (i = 1; i <= e; i++)\n      res = res * a;\n\n   return res;\n}\n\n\nstatic\nlong IrredBaseCase(const GF2EX& h, long q, long a, const GF2EXModulus& F)\n{\n   long e;\n   GF2EX X, s, d;\n\n   e = power(q, a-1);\n   PowerCompose(s, h, e, F);\n   SetX(X);\n   add(s, s, X);\n   GCD(d, F.f, s);\n   return IsOne(d);\n}\n\n\nstatic\nlong RecIrredTest(long u, const GF2EX& h, const GF2EXModulus& F,\n                 const FacVec& fvec)\n{\n   long  q1, q2;\n   GF2EX h1, h2;\n\n   if (IsX(h)) return 0;\n\n   if (fvec[u].link == -1) {\n      return IrredBaseCase(h, fvec[u].q, fvec[u].a, F);\n   }\n\n\n   q1 = fvec[fvec[u].link].val; \n   q2 = fvec[fvec[u].link+1].val;\n\n   TandemPowerCompose(h1, h2, h, q1, q2, F);\n   return RecIrredTest(fvec[u].link, h2, F, fvec) \n          && RecIrredTest(fvec[u].link+1, h1, F, fvec);\n}\n\nlong DetIrredTest(const GF2EX& f)\n{\n   if (deg(f) <= 0) return 0;\n   if (deg(f) == 1) return 1;\n\n   GF2EXModulus F;\n\n   build(F, f);\n   \n   GF2EX h;\n\n   FrobeniusMap(h, F);\n\n   GF2EX s;\n   PowerCompose(s, h, F.n, F);\n   if (!IsX(s)) return 0;\n\n   FacVec fvec;\n\n   FactorInt(fvec, F.n);\n\n   return RecIrredTest(fvec.length()-1, h, F, fvec);\n}\n\n\n\nlong IterIrredTest(const GF2EX& f)\n{\n   if (deg(f) <= 0) return 0;\n   if (deg(f) == 1) return 1;\n\n   GF2EXModulus F;\n\n   build(F, f);\n   \n   GF2EX h;\n\n   FrobeniusMap(h, F);\n\n   long CompTableSize = 2*SqrRoot(deg(f));\n\n   GF2EXArgument H;\n\n   build(H, h, F, CompTableSize);\n\n   long i, d, limit, limit_sqr;\n   GF2EX g, X, t, prod;\n\n\n   SetX(X);\n\n   i = 0;\n   g = h;\n   d = 1;\n   limit = 2;\n   limit_sqr = limit*limit;\n\n   set(prod);\n\n\n   while (2*d <= deg(f)) {\n      add(t, g, X);\n      MulMod(prod, prod, t, F);\n      i++;\n      if (i == limit_sqr) {\n         GCD(t, f, prod);\n         if (!IsOne(t)) return 0;\n\n         set(prod);\n         limit++;\n         limit_sqr = limit*limit;\n         i = 0;\n      }\n\n      d = d + 1;\n      if (2*d <= deg(f)) {\n         CompMod(g, g, H, F);\n      }\n   }\n\n   if (i > 0) {\n      GCD(t, f, prod);\n      if (!IsOne(t)) return 0;\n   }\n\n   return 1;\n}\n\nstatic\nvoid MulByXPlusY(vec_GF2EX& h, const GF2EX& f, const GF2EX& g)\n// h represents the bivariate polynomial h[0] + h[1]*Y + ... + h[n-1]*Y^k,\n// where the h[i]'s are polynomials in X, each of degree < deg(f),\n// and k < deg(g).\n// h is replaced by the bivariate polynomial h*(X+Y) (mod f(X), g(Y)).\n\n{\n   long n = deg(g);\n   long k = h.length()-1;\n\n   if (k < 0) return;\n\n   if (k < n-1) {\n      h.SetLength(k+2);\n      h[k+1] = h[k];\n      for (long i = k; i >= 1; i--) {\n         MulByXMod(h[i], h[i], f);\n         add(h[i], h[i], h[i-1]);\n      }\n      MulByXMod(h[0], h[0], f);\n   }\n   else {\n      GF2EX b, t;\n\n      b = h[n-1];\n      for (long i = n-1; i >= 1; i--) {\n         mul(t, b, g.rep[i]);\n         MulByXMod(h[i], h[i], f);\n         add(h[i], h[i], h[i-1]);\n         add(h[i], h[i], t);\n      }\n      mul(t, b, g.rep[0]);\n      MulByXMod(h[0], h[0], f);\n      add(h[0], h[0], t);\n   }\n\n   // normalize\n\n   k = h.length()-1;\n   while (k >= 0 && IsZero(h[k])) k--;\n   h.SetLength(k+1);\n}\n\n\nstatic\nvoid IrredCombine(GF2EX& x, const GF2EX& f, const GF2EX& g)\n{\n   if (deg(f) < deg(g)) {\n      IrredCombine(x, g, f);\n      return;\n   }\n\n   // deg(f) >= deg(g)...not necessary, but maybe a little more\n   //                    time & space efficient\n\n   long df = deg(f);\n   long dg = deg(g);\n   long m = df*dg;\n\n   vec_GF2EX h(INIT_SIZE, dg);\n\n   long i;\n   for (i = 0; i < dg; i++) h[i].SetMaxLength(df);\n\n   h.SetLength(1);\n   set(h[0]);\n\n   vec_GF2E a;\n\n   a.SetLength(2*m);\n\n   for (i = 0; i < 2*m; i++) {\n      a[i] = ConstTerm(h[0]);\n      if (i < 2*m-1)\n         MulByXPlusY(h, f, g);\n   }\n\n   MinPolySeq(x, a, m);\n}\n\n\nstatic\nvoid BuildPrimePowerIrred(GF2EX& f, long q, long e)\n{\n   long n = power(q, e);\n\n   do {\n      random(f, n);\n      SetCoeff(f, n);\n   } while (!IterIrredTest(f));\n}\n\nstatic\nvoid RecBuildIrred(GF2EX& f, long u, const FacVec& fvec)\n{\n   if (fvec[u].link == -1)\n      BuildPrimePowerIrred(f, fvec[u].q, fvec[u].a);\n   else {\n      GF2EX g, h;\n      RecBuildIrred(g, fvec[u].link, fvec);\n      RecBuildIrred(h, fvec[u].link+1, fvec);\n      IrredCombine(f, g, h);\n   }\n}\n\n\nvoid BuildIrred(GF2EX& f, long n)\n{\n   if (n <= 0)\n      Error(\"BuildIrred: n must be positive\");\n\n   if (NTL_OVERFLOW(n, 1, 0))\n      Error(\"overflow in BuildIrred\");\n\n   if (n == 1) {\n      SetX(f);\n      return;\n   }\n\n   FacVec fvec;\n\n   FactorInt(fvec, n);\n\n   RecBuildIrred(f, fvec.length()-1, fvec);\n}\n\n\n\n#if 0\nvoid BuildIrred(GF2EX& f, long n)\n{\n   if (n <= 0)\n      Error(\"BuildIrred: n must be positive\");\n\n   if (NTL_OVERFLOW(n, 1, 0))\n      Error(\"overflow in BuildIrred\");\n\n   if (n == 1) {\n      SetX(f);\n      return;\n   }\n\n   GF2EX g;\n\n   do {\n      random(g, n);\n      SetCoeff(g, n);\n   } while (!IterIrredTest(g));\n\n   f = g;\n\n}\n#endif\n\n\n\nvoid BuildRandomIrred(GF2EX& f, const GF2EX& g)\n{\n   GF2EXModulus G;\n   GF2EX h, ff;\n\n   build(G, g);\n   do {\n      random(h, deg(g));\n      IrredPolyMod(ff, h, G);\n   } while (deg(ff) < deg(g));\n\n   f = ff;\n}\n\n\n/************* NEW DDF ****************/\n\nlong GF2EX_GCDTableSize = 4;\nchar GF2EX_stem[256] = \"\";\n\ndouble GF2EXFileThresh = 256;\n\nstatic vec_GF2EX BabyStepFile;\nstatic vec_GF2EX GiantStepFile;\n\nstatic long use_files;\n\n\nstatic\ndouble CalcTableSize(long n, long k)\n{\n   double sz = GF2E::storage();\n   sz = sz * n;\n   sz = sz + NTL_VECTOR_HEADER_SIZE + sizeof(vec_GF2E);\n   sz = sz * k;\n   sz = sz/1024;\n   return sz;\n}\n\n\n\nstatic\nvoid GenerateBabySteps(GF2EX& h1, const GF2EX& f, const GF2EX& h, long k,\n                       long verbose)\n\n{\n   double t;\n\n   if (verbose) { cerr << \"generating baby steps...\"; t = GetTime(); }\n\n   GF2EXModulus F;\n   build(F, f);\n\n   GF2EXArgument H;\n\n#if 0\n   double n2 = sqrt(double(F.n));\n   double n4 = sqrt(n2);\n   double n34 = n2*n4;\n   long sz = long(ceil(n34/sqrt(sqrt(2.0))));\n#else\n   long sz = 2*SqrRoot(F.n);\n#endif\n\n   build(H, h, F, sz);\n\n\n   h1 = h;\n\n   long i;\n\n   long HexOutput = GF2X::HexOutput;\n   GF2X::HexOutput = 1;\n\n   if (!use_files) {\n      BabyStepFile.kill();\n      BabyStepFile.SetLength(k-1);\n   }\n\n   for (i = 1; i <= k-1; i++) {\n      if (use_files) {\n         ofstream s;\n         OpenWrite(s, FileName(GF2EX_stem, \"baby\", i));\n         s << h1 << \"\\n\";\n         s.close();\n      }\n      else\n         BabyStepFile(i) = h1;\n\n      CompMod(h1, h1, H, F);\n      if (verbose) cerr << \"+\";\n   }\n\n   if (verbose)\n      cerr << (GetTime()-t) << \"\\n\";\n\n   GF2X::HexOutput = HexOutput;\n}\n\n\nstatic\nvoid GenerateGiantSteps(const GF2EX& f, const GF2EX& h, long l, long verbose)\n{\n\n   double t;\n\n   if (verbose) { cerr << \"generating giant steps...\"; t = GetTime(); }\n\n   GF2EXModulus F;\n   build(F, f);\n\n   GF2EXArgument H;\n\n#if 0\n   double n2 = sqrt(double(F.n));\n   double n4 = sqrt(n2);\n   double n34 = n2*n4;\n   long sz = long(ceil(n34/sqrt(sqrt(2.0))));\n#else\n   long sz = 2*SqrRoot(F.n);\n#endif\n\n   build(H, h, F, sz);\n\n   GF2EX h1;\n\n   h1 = h;\n\n   long i;\n\n   long HexOutput = GF2X::HexOutput; \n   GF2X::HexOutput = 1;\n\n   if (!use_files) {\n      GiantStepFile.kill();\n      GiantStepFile.SetLength(l);\n   }\n\n   for (i = 1; i <= l-1; i++) {\n      if (use_files) {\n         ofstream s;\n         OpenWrite(s, FileName(GF2EX_stem, \"giant\", i));\n         s << h1 << \"\\n\";\n         s.close();\n      }\n      else\n         GiantStepFile(i) = h1;\n\n      CompMod(h1, h1, H, F);\n      if (verbose) cerr << \"+\";\n   }\n\n   if (use_files) {\n      ofstream s;\n      OpenWrite(s, FileName(GF2EX_stem, \"giant\", i));\n      s << h1 << \"\\n\";\n      s.close();\n   }\n   else\n      GiantStepFile(i) = h1;\n\n   if (verbose)\n      cerr << (GetTime()-t) << \"\\n\";\n\n   GF2X::HexOutput = HexOutput;\n}\n\nstatic\nvoid FileCleanup(long k, long l)\n{\n   if (use_files) {\n      long i;\n   \n      for (i = 1; i <= k-1; i++)\n         remove(FileName(GF2EX_stem, \"baby\", i));\n   \n      for (i = 1; i <= l; i++)\n         remove(FileName(GF2EX_stem, \"giant\", i));\n   }\n   else {\n      BabyStepFile.kill();\n      GiantStepFile.kill();\n   }\n}\n\n\nstatic\nvoid NewAddFactor(vec_pair_GF2EX_long& u, const GF2EX& g, long m, long verbose)\n{\n   long len = u.length();\n\n   u.SetLength(len+1);\n   u[len].a = g;\n   u[len].b = m;\n\n   if (verbose) {\n      cerr << \"split \" << m << \" \" << deg(g) << \"\\n\";\n   }\n}\n\n   \n\n\nstatic\nvoid NewProcessTable(vec_pair_GF2EX_long& u, GF2EX& f, const GF2EXModulus& F,\n                     vec_GF2EX& buf, long size, long StartInterval,\n                     long IntervalLength, long verbose)\n\n{\n   if (size == 0) return;\n\n   GF2EX& g = buf[size-1];\n\n   long i;\n\n   for (i = 0; i < size-1; i++)\n      MulMod(g, g, buf[i], F);\n\n   GCD(g, f, g);\n\n   if (deg(g) == 0) return;\n\n   div(f, f, g);\n\n   long d = (StartInterval-1)*IntervalLength + 1;\n   i = 0;\n   long interval = StartInterval;\n\n   while (i < size-1 && 2*d <= deg(g)) {\n      GCD(buf[i], buf[i], g);\n      if (deg(buf[i]) > 0) {\n         NewAddFactor(u, buf[i], interval, verbose);\n         div(g, g, buf[i]);\n      }\n\n      i++;\n      interval++;\n      d += IntervalLength;\n   }\n\n   if (deg(g) > 0) {\n      if (i == size-1)\n         NewAddFactor(u, g, interval, verbose);\n      else\n         NewAddFactor(u, g, (deg(g)+IntervalLength-1)/IntervalLength, verbose);\n   }\n}\n\n\nstatic\nvoid FetchGiantStep(GF2EX& g, long gs, const GF2EXModulus& F)\n{\n   if (use_files) {\n      ifstream s;\n   \n      OpenRead(s, FileName(GF2EX_stem, \"giant\", gs));\n   \n      s >> g;\n      s.close();\n   }\n   else\n      g = GiantStepFile(gs);\n\n   rem(g, g, F);\n}\n\n\nstatic\nvoid FetchBabySteps(vec_GF2EX& v, long k)\n{\n   v.SetLength(k);\n\n   SetX(v[0]);\n\n   long i;\n   for (i = 1; i <= k-1; i++) {\n      if (use_files) {\n         ifstream s;\n         OpenRead(s, FileName(GF2EX_stem, \"baby\", i));\n         s >> v[i];\n         s.close();\n      }\n      else\n         v[i] = BabyStepFile(i);\n   }\n}\n      \n\n\nstatic\nvoid GiantRefine(vec_pair_GF2EX_long& u, const GF2EX& ff, long k, long l,\n                 long verbose)\n\n{\n   double t;\n\n   if (verbose) {\n      cerr << \"giant refine...\";\n      t = GetTime();\n   }\n\n   u.SetLength(0);\n\n   vec_GF2EX BabyStep;\n\n   FetchBabySteps(BabyStep, k);\n\n   vec_GF2EX buf(INIT_SIZE, GF2EX_GCDTableSize);\n\n   GF2EX f;\n   f = ff;\n\n   GF2EXModulus F;\n   build(F, f);\n\n   GF2EX g;\n   GF2EX h;\n\n   long size = 0;\n\n   long first_gs;\n\n   long d = 1;\n\n   while (2*d <= deg(f)) {\n\n      long old_n = deg(f);\n\n      long gs = (d+k-1)/k;\n      long bs = gs*k - d;\n\n      if (bs == k-1) {\n         size++;\n         if (size == 1) first_gs = gs;\n         FetchGiantStep(g, gs, F);\n         add(buf[size-1], g, BabyStep[bs]);\n      }\n      else {\n         add(h, g, BabyStep[bs]);\n         MulMod(buf[size-1], buf[size-1], h, F);\n      }\n\n      if (verbose && bs == 0) cerr << \"+\";\n\n      if (size == GF2EX_GCDTableSize && bs == 0) {\n         NewProcessTable(u, f, F, buf, size, first_gs, k, verbose);\n         if (verbose) cerr << \"*\";\n         size = 0;\n      }\n\n      d++;\n\n      if (2*d <= deg(f) && deg(f) < old_n) {\n         build(F, f);\n\n         long i;\n         for (i = 1; i <= k-1; i++) \n            rem(BabyStep[i], BabyStep[i], F);\n      }\n   }\n\n   if (size > 0) {\n      NewProcessTable(u, f, F, buf, size, first_gs, k, verbose);\n      if (verbose) cerr << \"*\";\n   }\n\n   if (deg(f) > 0) \n      NewAddFactor(u, f, 0, verbose);\n\n   if (verbose) {\n      t = GetTime()-t;\n      cerr << \"giant refine time: \" << t << \"\\n\";\n   }\n}\n\n\nstatic\nvoid IntervalRefine(vec_pair_GF2EX_long& factors, const GF2EX& ff,\n                    long k, long gs, const vec_GF2EX& BabyStep, long verbose)\n\n{\n   vec_GF2EX buf(INIT_SIZE, GF2EX_GCDTableSize);\n\n   GF2EX f;\n   f = ff;\n\n   GF2EXModulus F;\n   build(F, f);\n\n   GF2EX g;\n\n   FetchGiantStep(g, gs, F);\n\n   long size = 0;\n\n   long first_d;\n\n   long d = (gs-1)*k + 1;\n   long bs = k-1;\n\n   while (bs >= 0 && 2*d <= deg(f)) {\n\n      long old_n = deg(f);\n\n      if (size == 0) first_d = d;\n      rem(buf[size], BabyStep[bs], F);\n      add(buf[size], buf[size], g);\n      size++;\n\n      if (size == GF2EX_GCDTableSize) {\n         NewProcessTable(factors, f, F, buf, size, first_d, 1, verbose);\n         size = 0;\n      }\n\n      d++;\n      bs--;\n\n      if (bs >= 0 && 2*d <= deg(f) && deg(f) < old_n) {\n         build(F, f);\n         rem(g, g, F);\n      }\n   }\n\n   NewProcessTable(factors, f, F, buf, size, first_d, 1, verbose);\n\n   if (deg(f) > 0) \n      NewAddFactor(factors, f, deg(f), verbose);\n}\n   \n\n\n\nstatic\nvoid BabyRefine(vec_pair_GF2EX_long& factors, const vec_pair_GF2EX_long& u,\n                long k, long l, long verbose)\n\n{\n   double t;\n\n   if (verbose) {\n      cerr << \"baby refine...\";\n      t = GetTime();\n   }\n\n   factors.SetLength(0);\n\n   vec_GF2EX BabyStep;\n\n   long i;\n   for (i = 0; i < u.length(); i++) {\n      const GF2EX& g = u[i].a;\n      long gs = u[i].b;\n\n      if (gs == 0 || 2*((gs-1)*k+1) > deg(g))\n         NewAddFactor(factors, g, deg(g), verbose);\n      else {\n         if (BabyStep.length() == 0)\n            FetchBabySteps(BabyStep, k);\n         IntervalRefine(factors, g, k, gs, BabyStep, verbose);\n      }\n   }\n\n   if (verbose) {\n      t = GetTime()-t;\n      cerr << \"baby refine time: \" << t << \"\\n\";\n   }\n}\n\n      \n      \n\n      \n\nvoid NewDDF(vec_pair_GF2EX_long& factors,\n            const GF2EX& f,\n            const GF2EX& h,\n            long verbose)\n\n{\n   if (!IsOne(LeadCoeff(f)))\n      Error(\"NewDDF: bad args\");\n\n   if (deg(f) == 0) {\n      factors.SetLength(0);\n      return;\n   }\n\n   if (deg(f) == 1) {\n      factors.SetLength(0);\n      append(factors, cons(f, 1L));\n      return;\n   }\n\n   if (!GF2EX_stem[0])\n      sprintf(GF2EX_stem, \"ddf-%ld\", RandomBnd(10000));\n      \n   long B = deg(f)/2;\n   long k = SqrRoot(B);\n   long l = (B+k-1)/k;\n\n   GF2EX h1;\n\n   if (CalcTableSize(deg(f), k + l - 1) > GF2EXFileThresh)\n      use_files = 1;\n   else\n      use_files = 0;\n\n   GenerateBabySteps(h1, f, h, k, verbose);\n\n   GenerateGiantSteps(f, h1, l, verbose);\n\n   vec_pair_GF2EX_long u;\n   GiantRefine(u, f, k, l, verbose);\n   BabyRefine(factors, u, k, l, verbose);\n\n   FileCleanup(k, l);\n}\n\nlong IterComputeDegree(const GF2EX& h, const GF2EXModulus& F)\n{\n   long n = deg(F);\n\n   if (n == 1 || IsX(h)) return 1;\n\n   long B = n/2;\n   long k = SqrRoot(B);\n   long l = (B+k-1)/k;\n\n\n   GF2EXArgument H;\n\n#if 0\n   double n2 = sqrt(double(n));\n   double n4 = sqrt(n2);\n   double n34 = n2*n4;\n   long sz = long(ceil(n34/sqrt(sqrt(2.0))));\n#else\n   long sz = 2*SqrRoot(F.n);\n#endif\n\n   build(H, h, F, sz);\n\n   GF2EX h1;\n   h1 = h;\n\n   vec_GF2EX baby;\n   baby.SetLength(k);\n\n   SetX(baby[0]);\n\n   long i;\n\n   for (i = 1; i <= k-1; i++) {\n      baby[i] = h1;\n      CompMod(h1, h1, H, F);\n      if (IsX(h1)) return i+1;\n   }\n\n   build(H, h1, F, sz);\n\n   long j;\n\n   for (j = 2; j <= l; j++) {\n      CompMod(h1, h1, H, F);\n\n      for (i = k-1; i >= 0; i--) {\n         if (h1 == baby[i])\n            return j*k-i;\n      }\n   }\n\n   return n;\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "b4798c1f6f3fcd4cee5c5e928798aad94774a658", "size": 37695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ntl/GF2EXFactoring.cpp", "max_stars_repo_name": "av-elier/fast-exponentiation-algs", "max_stars_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-17T20:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T19:52:14.000Z", "max_issues_repo_path": "src/ntl/GF2EXFactoring.cpp", "max_issues_repo_name": "av-elier/fast-exponentiation-algs", "max_issues_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ntl/GF2EXFactoring.cpp", "max_forks_repo_name": "av-elier/fast-exponentiation-algs", "max_forks_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_forks_repo_licenses": ["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.1966240876, "max_line_length": 82, "alphanum_fraction": 0.4735376045, "num_tokens": 13318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5439781844279962}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iostream>\n#include <memory>\n#include <unsupported/Eigen/AutoDiff>\n#include <unsupported/Eigen/LevenbergMarquardt>\n/* #include <unsupported/Eigen/NonLinearOptimization> */\n#include <vector>\n\n#include <fmt/format.h>\n#include <fmt/printf.h>\n\n#include \"nanoflann.hpp\"\n\nusing Vector3f = Eigen::Vector3f;\nusing Transform = Eigen::Isometry3f;\nusing Cloud = Eigen::MatrixX3f;\n\nCloud TransformPointCloud(const Cloud& source_cloud,\n    const Transform& transform)\n{\n    // TODO(yycho0108): implement\n    Cloud out(source_cloud.rows(), source_cloud.cols());\n    for (int i = 0; i < source_cloud.rows(); ++i) {\n        out.row(i).transpose() = transform * source_cloud.row(i).transpose();\n    }\n    return out;\n}\n\n//template <typename T>\n//struct TXTYTZRZParametrization {\n//    static const std::size_t Dimensions = 4;\n//    Eigen::Matrix<T, 3, 1> ApplyTransform(const Eigen::Matrix<T, 3, 1>& point);\n//    void FromTransform(const Transform&);\n//    Transform ToTransform();\n//};\n\nstatic constexpr const int kParamSize = 4;\ntemplate <typename T>\nstruct ParametrizedIsometryCost : public Eigen::DenseFunctor<T> {\n    ParametrizedIsometryCost(const Cloud& source, const Cloud& target)\n        : Eigen::DenseFunctor<T>(kParamSize, source.size())\n        , source_(source)\n        , target_(target)\n    {\n    }\n\n    template <typename T1>\n    int operator()(const Eigen::Matrix<T1, Eigen::Dynamic, 1>& parameter,\n        Eigen::Matrix<T1, Eigen::Dynamic, 1>& fvec) const\n    {\n        const Eigen::Matrix<T1, 3, 1>& translation = parameter.template head<3>();\n        //const Eigen::Matrix<T1, 3, 1>& rvec = parameter.template tail<3>();\n        //const T1 angle = rvec.norm();\n        //const Eigen::AngleAxis<T1>& rotation{angle, rvec / angle};\n        //Eigen::Quaternion<T1> rotation;\n        const Eigen::AngleAxis<T1>& rotation{ parameter(3), Eigen::Matrix<T1, 3, 1>{ 0, 0, 1 } };\n\n        for (int i = 0; i < source_.rows(); ++i) {\n            //fvec.segment(i * 3, 3) = source_.row(i).template cast<T1>() + translation.transpose() - target_.row(i).template cast<T1>();\n            fvec.segment(i * 3, 3) = (rotation * source_.row(i).template cast<T1>().transpose()).transpose() + translation.transpose() - target_.row(i).template cast<T1>();\n        }\n        return 0;\n        //// Set to simpler version for now.\n        // Eigen::Transform<T1, 3, Eigen::Isometry> transform;\n        // transform.translation() = translation;\n\n        //// Will this work?\n        // std::cout << \"here1\" << std::endl;\n        // auto transformed = (transform.linear() * source_.transpose().template\n        // cast<T1>()).transpose();\n        ///* transformed.rowwise() += transform.translation().transpose(); */\n        // std::cout << \"here2\" << std::endl;\n        // Eigen::Matrix<T1, Eigen::Dynamic, 3> delta = (transformed -\n        // target_).template cast<T1>(); std::cout << \"here2.5\" << std::endl; if\n        // (!(delta.Flags & Eigen::RowMajorBit)) {\n        //    // 3xN memory layout -> Nx3 memory layout\n        //    Eigen::Matrix<T1, 3, Eigen::Dynamic> data = delta.transpose();\n        //    Eigen::Map<Eigen::Matrix<T1, Eigen::Dynamic, 1>> rhs(data.data(),\n        //        fvec.rows(), 1);\n        //    fvec.segment(0, fvec.rows()) = rhs;\n        //} else {\n        //    Eigen::Map<Eigen::Matrix<T1, Eigen::Dynamic, 1>> rhs(delta.data(),\n        //        fvec.rows(), 1);\n        //    fvec.segment(0, fvec.rows()) = rhs;\n        //}\n        ////std::cout << \"here3\" << std::endl;\n        ////std::cout << delta.rows() << 'x' << delta.cols() << std::endl;\n        ////std::cout << fvec.rows() << 'x' << fvec.cols() << std::endl;\n        ////std::cout << rhs.rows() << 'x' << rhs.cols() << std::endl;\n        ////fvec = rhs;\n        // return 0;\n    };\n\n    int df(const Eigen::Matrix<float, kParamSize, 1>& parameter,\n        Eigen::MatrixXf& jac) const\n    {\n        using Scalar = Eigen::AutoDiffScalar<Eigen::VectorXf>;\n        using ScalarVector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n        ScalarVector ax = parameter.template cast<Scalar>();\n        ScalarVector av(this->values());\n\n        for (int j = 0; j < this->values(); ++j) {\n            av[j].derivatives().resize(this->inputs());\n        }\n        for (int i = 0; i < this->inputs(); ++i) {\n            ax[i].derivatives().resize(this->inputs());\n            ax[i].derivatives().setZero();\n            ax[i].derivatives()(i) = 1.0;\n            //ax[i].derivatives() = Eigen::Vector3f::Unit(this->inputs(), i);\n            //ax[i].derivatives().resize(this->inputs());\n        }\n\n        operator()(ax, av);\n\n        // jac = (48x3)\n        for (int i = 0; i < this->values(); ++i) {\n            // std::cout << \"==\" << std::endl;\n            // std::cout << jac.row(i).rows() << std::endl;           // 1\n            // std::cout << jac.row(i).cols() << std::endl;           // 3\n            // std::cout << av[i].derivatives().rows() << std::endl;  // 0\n            // std::cout << av[i].derivatives().cols() << std::endl;  // 1\n            jac.row(i) = av[i].derivatives();\n        }\n    }\n    const Cloud& source_;\n    const Cloud& target_;\n    /* IsometryCost<T> cost; */\n};\n\n/**\n * Generalized ICP implementation, based on\n * \"Generalized-ICP\" Segal et al.\n * www.roboticsproceedings.org/rss05/p21.pdf\n */\nclass GeneralizedICP {\npublic:\n    using KDTree = nanoflann::KDTreeEigenMatrixAdaptor<Cloud>;\n\n    GeneralizedICP()\n        : source(nullptr)\n        , target(nullptr)\n    {\n    }\n    void SetSourceCloud(const Cloud& source_cloud)\n    {\n        source = &source_cloud;\n        /* source_tree = std::make_shared<KDTree>(3, std::cref(source_cloud),\n         * 10); */\n        /* source_tree->index->buildIndex(); */\n    }\n    void SetTargetCloud(const Cloud& target_cloud)\n    {\n        target = &target_cloud;\n        target_tree = std::make_shared<KDTree>(3, std::cref(target_cloud), 10);\n        target_tree->index->buildIndex();\n    }\n\n    void FindCorrespondences(const Cloud& source,\n        std::vector<std::size_t>* indices,\n        std::vector<float>* squared_distances)\n    {\n        // Reset memory.\n        indices->clear();\n        squared_distances->clear();\n        indices->reserve(source.rows());\n        squared_distances->reserve(source.rows());\n\n        // Temps\n        std::vector<long> knn_indices(5);\n        std::vector<float> knn_squared_distances(5);\n\n        for (int i = 0; i < source.rows(); ++i) {\n            const Vector3f& query_point = source.row(i);\n            /* fmt::print(\"query {}\\n\", query_point.transpose()); */\n            /* const float* check = reinterpret_cast<const float*>(query_point.data()); */\n            /* fmt::print(\"check {} {} {}\\n\", check[0], check[1], check[2]); */\n            bool suc = target_tree->index->knnSearch(reinterpret_cast<const float*>(query_point.data()), 1,\n                &knn_indices[0], &knn_squared_distances[0]);\n            if (!suc) {\n                fmt::print(\"unsuccessful\");\n                exit(1);\n            }\n            /* fmt::print(\"{},\", knn_indices[0]); */\n\n            indices->emplace_back(knn_indices[0]);\n            squared_distances->emplace_back(knn_squared_distances[0]);\n        }\n    }\n\n    float TransformCost(const Cloud& source, const Cloud& target,\n        const Transform& transform)\n    {\n        // Nx3 = (3x3?) * (3xN)\n        const Cloud& target_ = (transform * source.transpose()).transpose();\n        const Cloud& delta = target - target_;\n\n        /* delta = b - Ta */\n        const Eigen::Matrix3f& R = transform.rotation();\n\n        float total_cost{ 0 };\n        for (int i = 0; i < source.rows(); ++i) {\n            const Vector3f& d = delta.row(i);\n            const float cost = d.transpose() * R * Eigen::Matrix3f::Identity() * R.transpose() * d;\n            total_cost += cost;\n        }\n        return total_cost;\n    }\n\n    Transform OptimizeTransform(const Cloud& a, const Cloud& b, const Transform& seed = Transform::Identity())\n    {\n        // Initialize system.\n        ParametrizedIsometryCost<float> cost_fun{ a, b };\n        Eigen::LevenbergMarquardt<ParametrizedIsometryCost<float>> lm{ cost_fun };\n\n        // Apply parametrization.\n        Eigen::Matrix<float, -1, 1> param(4, 1);\n        param.head<3>() = seed.translation();\n        param(3) = Eigen::AngleAxis<float>{ seed.rotation() }.angle();\n\n        // Run Optimization.\n        lm.minimize(param);\n\n        // Extract output and return.\n        Transform out = Transform::Identity();\n        out.translation() = param.head<3>();\n        out.linear() = Eigen::AngleAxis<float>{ param(3), Eigen::Vector3f{ 0, 0, 1 } }.toRotationMatrix();\n        return out;\n    }\n\n    Transform ComputeTransform()\n    {\n        static constexpr const float kTransformEpsilon = 0.001;\n        static constexpr const float kRotationEpsilon = 0.001;\n        static constexpr const float kMaxIterations = 100;\n\n        Cloud tmp = *source;\n        Transform transform = Transform::Identity();\n        std::vector<std::size_t> target_indices;\n        std::vector<float> squared_distances;\n\n        bool converged = false;\n        for (int count = 0; count < kMaxIterations; ++count) {\n            FindCorrespondences(tmp, &target_indices, &squared_distances);\n            for (std::size_t i = 0; i < source->rows(); ++i) {\n                const std::size_t& source_index = i;\n                const std::size_t& target_index = target_indices[i];\n                const float& squared_distance = squared_distances[i];\n                //fmt::print(\"{} {} {}\\n\", source_index, target_index,\n                //    squared_distance);\n            }\n\n            // Make a copy for now. FIXME(yycho0108): better indexing scheme\n            // const Cloud& X = target(target_indices, Eigen::internal::all);\n            Cloud tmp_target(tmp.rows(), tmp.cols());\n            for (std::size_t i = 0; i < source->rows(); ++i) {\n                tmp_target.row(i) = target->row(target_indices[i]);\n            }\n\n            Transform target_from_tmp = OptimizeTransform(tmp, tmp_target);\n            if (target_from_tmp.translation().squaredNorm() < kTransformEpsilon\n                && std::abs(std::acos(0.5 * (target_from_tmp.linear().trace() - 1.0))) < kRotationEpsilon) {\n                converged = true;\n                break;\n            }\n            tmp = TransformPointCloud(tmp, target_from_tmp);\n            transform = target_from_tmp * transform;\n\n            ++count;\n        }\n        fmt::print(\"Converged : {}\\n\", bool(converged));\n        return transform;\n    }\n\n    const Cloud *source, *target;\n    /* std::shared_ptr<KDTree> source_tree; */\n    std::shared_ptr<KDTree> target_tree;\n};\n\nint main()\n{\n    Transform ground_truth_transform = Transform::Identity();\n    ground_truth_transform.translation() = Eigen::Vector3f{ 0.2, 0.2, 0.3 };\n    ground_truth_transform.linear() = Eigen::AngleAxisf(0.1, Eigen::Vector3f{ 0., 0., 1. }).toRotationMatrix();\n\n    Cloud source_cloud = Cloud::Zero(16, 3);\n    source_cloud.setRandom();\n\n    Cloud target_cloud = Cloud::Zero(17, 3);\n    //target_cloud.block<16, 3>(0, 0) = source_cloud;\n    target_cloud.block<16, 3>(0, 0) = TransformPointCloud(source_cloud, ground_truth_transform);\n\n    /* fmt::print(\"{} vs {}\", source_cloud.row(0), target_cloud.row(0)); */\n\n    GeneralizedICP gicp;\n    gicp.SetSourceCloud(source_cloud);\n    gicp.SetTargetCloud(target_cloud);\n    const Transform& estimated_transform = gicp.ComputeTransform();\n\n    fmt::print(\"ground truth : \\n{}\\n\", ground_truth_transform.matrix());\n    fmt::print(\"computed : \\n{}\\n\", estimated_transform.matrix());\n    return 0;\n}\n", "meta": {"hexsha": "8318bf1943c7cb95373725ab8bcbf31df8149a78", "size": 11659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "yycho0108/GeneralizedICP", "max_stars_repo_head_hexsha": "c4f6202802ac8341832dbcf69981a456e6765e1b", "max_stars_repo_licenses": ["MIT"], "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": "yycho0108/GeneralizedICP", "max_issues_repo_head_hexsha": "c4f6202802ac8341832dbcf69981a456e6765e1b", "max_issues_repo_licenses": ["MIT"], "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": "yycho0108/GeneralizedICP", "max_forks_repo_head_hexsha": "c4f6202802ac8341832dbcf69981a456e6765e1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-19T09:15:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-19T09:15:29.000Z", "avg_line_length": 38.3519736842, "max_line_length": 172, "alphanum_fraction": 0.5760356806, "num_tokens": 2999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.543978173521761}}
{"text": "#include <iostream>\n#include <random>\n#include <Eigen/Geometry>\n#include <memory>\n\n#include \"ransac.h\"\n\nusing namespace std;\n\nRansac::Ransac(int n_iterations, double threshold): n_iterations(n_iterations),\n                                                    threshold(threshold)\n{    // Seed the generator\n    generator.seed(rd());\n};\n\ndouble Ransac::mahalanobis_distance(const point3d& X, const point3d& A, const point3d& B,\n                                    const Eigen::Vector3d& D, const Eigen::Matrix3d& U)\n{\n    // Apply affine transform to points\n    Eigen::Vector3d A_affine = ((D.array().inverse()).sqrt()).matrix().asDiagonal() * U.transpose() * (A - X);\n    Eigen::Vector3d B_affine = ((D.array().inverse()).sqrt()).matrix().asDiagonal() * U.transpose() * (B - X);\n\n    double distance = A_affine.cross(B_affine).norm()/(A_affine - B_affine).norm();\n\n    return distance;\n}\n\nEigen::Matrix3Xd Ransac::removeOutlierPoints(const Eigen::Matrix3Xd& linepoints, const std::vector<Eigen::Vector3d>& eig_val,\n                                             const std::vector<Eigen::Matrix3d>& eig_vector, std::vector<Eigen::Matrix3d>& updated_covariance,\n                                             std::vector<Eigen::Matrix3d>& updated_inv_root_covariance, const std::vector<Eigen::Matrix3d>& cov_G,\n                                             const std::vector<Eigen::Matrix3d>& inv_cov_G)\n{\n    Eigen::Matrix3Xd best_inliers;\n    int best_num_inliers = -1;\n    float distance;\n\n    // solace in not copying this over and over\n    std::shared_ptr<vector<int>> ptr_to_best_inlier_indices = NULL;\n    \n    // Setup the range from which we choose random numbers\n    std::uniform_int_distribution<unsigned> distribution(0,linepoints.cols()-1); // end inclusive\n    \n    for(int iter=0; iter < n_iterations; ++iter){\n        int inliers = 0;\n        auto ptr_to_inlier_indices = std::make_shared<std::vector<int>>();\n\n        // re-generate i and j randomly until they are not equal\n        int i = distribution(generator), j = distribution(generator);\n        while(i == j){\n            i = distribution(generator), j = distribution(generator);\n        }\n        \n        Eigen::Matrix3Xd support_points(3, linepoints.cols());\n        Eigen::Vector3d A = linepoints.col(i), B = linepoints.col(j);\n\n        // calculate support for chosen endpoint indices\n        for(int k=0; k < linepoints.cols(); ++k){\n            distance = mahalanobis_distance(linepoints.col(k), A, B, eig_val[k], eig_vector[k]);\n            // cout << distance << endl;\n            if (distance < threshold){\n                support_points.col(inliers++) = linepoints.col(k);\n                ptr_to_inlier_indices->push_back(k);\n            }\n\n        }\n\n        if(inliers > best_num_inliers){\n            best_num_inliers = inliers;\n            best_inliers = support_points.leftCols(inliers);\n            ptr_to_best_inlier_indices = ptr_to_inlier_indices;\n        }\n    }\n\n    // Take the indices of new covariances and populate updated covariances\n    // Very slow - <To-do> refactor to deal with indices/pointers instead of copying over data\n    for(auto i: *ptr_to_best_inlier_indices){\n        updated_covariance.push_back(cov_G[i]);\n        updated_inv_root_covariance.push_back(inv_cov_G[i]);\n    }\n    \n    return best_inliers;\n}\n", "meta": {"hexsha": "9089d1083be4b06a15218bceb1aef78291c53dc9", "size": 3316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ransac.cpp", "max_stars_repo_name": "SubramanianKrish/roblineVO", "max_stars_repo_head_hexsha": "9c977c63cc02e8a3a9e42dfa8bae77198f5347f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-09T08:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T08:28:48.000Z", "max_issues_repo_path": "src/ransac.cpp", "max_issues_repo_name": "SubramanianKrish/roblineVO", "max_issues_repo_head_hexsha": "9c977c63cc02e8a3a9e42dfa8bae77198f5347f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-11T07:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-11T07:00:50.000Z", "max_forks_repo_path": "src/ransac.cpp", "max_forks_repo_name": "SubramanianKrish/roblineVO", "max_forks_repo_head_hexsha": "9c977c63cc02e8a3a9e42dfa8bae77198f5347f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T11:55:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-12T19:24:46.000Z", "avg_line_length": 39.9518072289, "max_line_length": 146, "alphanum_fraction": 0.619119421, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5439781730083374}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 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_ARCH_COMMON_SCALAR_FUNCTION_ACOTPI_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ACOTPI_HPP_INCLUDED\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/function/is_inf.hpp>\n#endif\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/atanpi.hpp>\n#include <boost/simd/function/bitofsign.hpp>\n#include <boost/simd/function/bitwise_or.hpp>\n#include <boost/simd/function/if_else_zero.hpp>\n#include <boost/simd/function/if_zero_else.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( acotpi_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_<bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 z =Half<A0>()-if_else_zero(is_nez(a0),atanpi(bs::abs(a0)));\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      z = if_zero_else(is_inf(a0),z);\n      #endif\n      return bitwise_or(z, bitofsign(a0));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "6df3cdfb2655c8f559bfbdbf23aa70823bbcdd51", "size": 1711, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/acotpi.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/arch/common/scalar/function/acotpi.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/arch/common/scalar/function/acotpi.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": 32.9038461538, "max_line_length": 100, "alphanum_fraction": 0.6119228521, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5439781688387779}}
{"text": "\n#pragma once\n\n// Do not parallelise the GEMM routines as this is called by multiple threads\n#ifndef NEON_PARALLEL_EIGEN_SOLVERS\n#define EIGEN_DONT_PARALLELIZE\n#endif\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\n/// \\file dense_matrix.hpp\n\nnamespace neon\n{\n/// Matrix in row major layout\nusing matrix = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n/// Alias to row major layout matrix\nusing row_matrix = matrix;\n/// Matrix in column major layout\nusing col_matrix = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;\n\n/// 2x2 fixed size matrix\nusing matrix2 = Eigen::Matrix<double, 2, 2>;\n/// 3x3 fixed size matrix\nusing matrix3 = Eigen::Matrix<double, 3, 3>;\n/// 6x6 fixed size matrix\nusing matrix6 = Eigen::Matrix<double, 6, 6>;\n/// 9x9 fixed size matrix\nusing matrix9 = Eigen::Matrix<double, 9, 9>;\n/// 12x12 fixed size matrix\nusing matrix12 = Eigen::Matrix<double, 12, 12>;\n/// 16x16 fixed size matrix\nusing matrix16 = Eigen::Matrix<double, 16, 16>;\n/// 3x1 fixed size matrix for non-square Jacobians\nusing matrix31 = Eigen::Matrix<double, 3, 1>;\n/// 3x2 fixed size matrix for non-square Jacobians\nusing matrix32 = Eigen::Matrix<double, 3, 2>;\n\ntemplate <int geometric_dimension>\nusing matrixxd = Eigen::Matrix<double, Eigen::Dynamic, geometric_dimension>;\n\ntemplate <int geometric_dimension>\nusing matrixdx = Eigen::Matrix<double, geometric_dimension, Eigen::Dynamic>;\n\n/// Compile time fixed rows for nodal coordinates in two dimensions\nusing matrix2x = Eigen::Matrix<double, 2, Eigen::Dynamic>;\n/// Compile time fixed rows for nodal coordinates in three dimensions\nusing matrix3x = Eigen::Matrix<double, 3, Eigen::Dynamic>;\n\n/// Fixed size vector of variable length\nusing vector = Eigen::Matrix<double, Eigen::Dynamic, 1>;\n/// Fixed size vector of length two\nusing vector2 = Eigen::Vector2d;\n/// Fixed size vector of length three\nusing vector3 = Eigen::Vector3d;\n/// Fixed size vector of length four\nusing vector4 = Eigen::Vector4d;\n/// Fixed size vector of length five\nusing vector5 = Eigen::Matrix<double, 5, 1>;\n/// Fixed size vector of length six\nusing vector6 = Eigen::Matrix<double, 6, 1>;\n/// Fixed size vector of length sixteen\nusing vector16 = Eigen::Matrix<double, 16, 1>;\n}\n", "meta": {"hexsha": "e4f9f7bf640d025a6d82db10948df9d701ae3281", "size": 2238, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/numeric/dense_matrix.hpp", "max_stars_repo_name": "annierhea/neon", "max_stars_repo_head_hexsha": "4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/numeric/dense_matrix.hpp", "max_issues_repo_name": "annierhea/neon", "max_issues_repo_head_hexsha": "4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/numeric/dense_matrix.hpp", "max_forks_repo_name": "annierhea/neon", "max_forks_repo_head_hexsha": "4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9090909091, "max_line_length": 90, "alphanum_fraction": 0.7412868633, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5439687311983284}}
{"text": "//\n// Created by david on 2019-10-05.\n//\n#include <Eigen/Core>\n#include <iostream>\nint main(){\n    Eigen::MatrixXd test(10,10);\n    test.setRandom();\n    std::cout << test << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "ae1a37386751f886e872243a74bb72e6df66df85", "size": 202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/eigen.cpp", "max_stars_repo_name": "DavidAce/3Component_GL", "max_stars_repo_head_hexsha": "bb0c02606edb10b6cc02331afd1ffad8598f05c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-25T02:31:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T01:42:41.000Z", "max_issues_repo_path": "tests/eigen3/main.cpp", "max_issues_repo_name": "Vicfred/CMakeTemplate", "max_issues_repo_head_hexsha": "90a2270716eab9c37f71b14bc9ba7b55e01c974e", "max_issues_repo_licenses": ["MIT"], "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/main.cpp", "max_forks_repo_name": "Vicfred/CMakeTemplate", "max_forks_repo_head_hexsha": "90a2270716eab9c37f71b14bc9ba7b55e01c974e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T07:19:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-30T01:46:34.000Z", "avg_line_length": 16.8333333333, "max_line_length": 35, "alphanum_fraction": 0.599009901, "num_tokens": 59, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5439687230186601}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#define BOOST_UBLAS_NO_ELEMENT_PROXIES\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/symmetric.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/symmetric.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include \"print.hpp\"\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef ublas::vector<double> vector;\n    typedef ublas::symmetric_matrix<double, ublas::lower, ublas::column_major> matrix_l;\n    typedef ublas::symmetric_matrix<double, ublas::upper, ublas::column_major> matrix_u;\n    typedef typename vector::size_type size_type;\n    rand_normal<double>::reset();\n    size_type n=8;\n    matrix_l A_l(n);\n    matrix_u A_u(n);\n    for (size_type j=0; j<n; ++j) {\n      A_u(j, j)=rand_normal<double>::get();\n      A_l(j, j)=A_u(j, j);\n      for (size_type i=0; i<j; ++i) {\n    \tA_u(i, j)=rand_normal<double>::get();\n\tA_l(j, i)=A_u(i, j);\n       }\n    }\n    vector x(n);\n    for (size_type i=0; i<n; ++i)\n      x(i)=rand_normal<double>::get();\n    vector y(n);\n    for (size_type i=0; i<n; ++i)\n      y(i)=rand_normal<double>::get();\n    double alpha(rand_normal<double>::get());\n    double beta(rand_normal<double>::get());\n    vector y1(alpha*ublas::prod(A_l, x)+beta*y);\n    vector y2(y);\n    blas::spmv(alpha, A_l, x, beta, y2);\n    vector y3(y);\n    blas::spmv(alpha, A_u, x, beta, y3);\n    vector y4(y);\n    blas::spmv(alpha, A_l, x, beta, y4);\n    vector y5(y);\n    blas::spmv(alpha, A_u, x, beta, y5);\n    std::cout << \"testing boost::ublas containers\\n\"\n    \t      << \"using ublas            : \" << print_vec(y1) << '\\n'\n    \t      << \"using blas spmv (lower): \" << print_vec(y2) << '\\n'\n    \t      << \"using blas spmv (upper): \" << print_vec(y3) << '\\n'\n    \t      << \"using blas hpmv (lower): \" << print_vec(y4) << '\\n'\n    \t      << \"using blas hpmv (upper): \" << print_vec(y5) << '\\n'\n    \t      << '\\n';\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "8370bf43eb95139bb792ddbad8bbc34a09f045e1", "size": 2092, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/spmv.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/spmv.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/spmv.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.2950819672, "max_line_length": 88, "alphanum_fraction": 0.6080305927, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5439687182820645}}
{"text": "/*\n * =====================================================================================\n *\n *       Filename:  say.cpp\n *\n *    Description:  \n *\n *        Version:  1.0\n *        Created:  13.11.2015 15:11:23\n *       Revision:  none\n *       Compiler:  gcc\n *\n *\n * =====================================================================================\n */\n#include \"say.h\"\n#include <cmath>\n#include <boost/algorithm/string.hpp>\n#include <stdexcept>\n\nnamespace say\n{\n\tstd::string oneNames(int num)\n\t{\n\t\tswitch (num)\n\t\t{\n\t\t\tcase 1: return \"one\"; \n\t\t\tcase 2: return \"two\"; \n\t\t\tcase 3: return \"three\"; \n\t\t\tcase 4: return \"four\"; \n\t\t\tcase 5: return \"five\"; \n\t\t\tcase 6: return \"six\"; \n\t\t\tcase 7: return \"seven\"; \n\t\t\tcase 8: return \"eight\"; \n\t\t\tcase 9: return \"nine\"; \n\t\t\tcase 10: return \"ten\"; \n\t\t\tcase 11: return \"eleven\"; \n\t\t\tcase 12: return \"twelve\"; \n\t\t\tdefault: return \"\"; \n\n\t\t}\n\t}\n\tstd::string names6099(long int num)\n\t{\n\t\tstd::string engl{oneNames(num/10) + \"ty\"};\n\t\tif( (num % 10) != 0)\n\t\t{\n\t\t\tengl += \"-\" + oneNames(num %10);\n\t\t}\n\t\treturn engl;\n\n\t}\n\n\tstd::string tenNames(long int num)\n\t{\n\t\tswitch(num)\n\t\t{\n\t\t\tcase 1 ... 12: return oneNames(num);\n\t\t\tcase 13 ... 19: return oneNames((num % 10)) + \"teen\";\n\t\t\tcase 20: return \"twenty\";\n\t\t\tcase 21 ... 29: return \"twenty-\" + oneNames(num%10);\n\t\t\tcase 30: return \"thirty\";\n\t\t\tcase 31 ... 39: return \"thirty-\" + oneNames(num%10);\n\t\t\tcase 40: return \"forty\";\n\t\t\tcase 41 ... 49: return \"forty-\" + oneNames(num%10);\n\t\t\tcase 50: return \"fifty\";\n\t\t\tcase 51 ... 59: return \"fifty-\" + oneNames(num%10);\n\t\t\tcase 60 ... 79: return names6099(num);\n\t\t\tcase 80: return \"eighty\";\n\t\t\tcase 81 ... 89: return \"eighty-\" + oneNames(num%10);\n\t\t\tcase 90 ... 99: return names6099(num);\n\t\t\tdefault: return \"\";\n\t\t}\n\t}\n\n\tuint_fast8_t determineLength(long int num)\n\t{\n\t\treturn static_cast<uint_fast8_t>(std::to_string(num).size());\n\t}\n\n\tuint_fast8_t rest(uint_fast8_t l)\n\t{\n\t\tif(l <= 2)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn (l - (l%3));\n\t\t}\n\t}\n\n\tstd::string addUnit( std::string const& unit, long int& num)\n\t{\n\t\tstd::string engl{};\n\t\tuint_fast8_t l{ determineLength(num) };\n\t\tif((l%3)==0)\n\t\t{\n\t\t\tengl += \" \" + oneNames( num / pow(10, l-1)) + \" hundred\";\n\t\t\tnum %= static_cast<long int>(pow(10, l-1));\n\t\t\t--l;\n\t\t}\n\n\t\tif( (l- determineLength(num)) <=1)\n\t\t{\n\t\t\tl = determineLength(num);\n\t\t\tengl += \" \" + tenNames( num / static_cast<long int>(pow(10, rest(l))));\n\t\t\tnum %= static_cast<long int>(pow(10, rest(l)));\n\t\t}\n\t\treturn engl + \" \" + unit;\n\t}\n\n\t\n\tstd::string in_english(long int number)\n\t{\n\t\tif( (number < 0) or (number >= 1000ULL*1000ULL*1000ULL*1000ULL))\n\t\t{\n\t\t\tthrow std::domain_error(\"Number out of range\");\n\t\t}\n\t\tif( number == 0)\n\t\t{\n\t\t\treturn \"zero\";\n\t\t}\n\t\tuint_fast8_t numberlength{determineLength(number)};\n\t\tstd::string english{};\n\t\tif(numberlength > 9)\n\t\t{\n\t\t\tenglish += addUnit(\"billion\", number);\n\t\t\tnumberlength = determineLength(number);\n\t\t}\n\t\tif(numberlength > 6)\n\t\t{\n\t\t\tenglish += addUnit(\"million\", number);\n\t\t\tnumberlength = determineLength(number);\n\t\t}\n\t\tif(numberlength > 3)\n\t\t{\n\t\t\tenglish += addUnit(\"thousand\", number);\n\t\t\tnumberlength = determineLength(number);\n\t\t}\n\n\t\tif(numberlength > 0)\n\t\t{\n\t\t\tenglish += addUnit(\"\", number);\n\t\t}\n\t\tboost::algorithm::trim(english);\n\t\treturn english;\n\t}\n}", "meta": {"hexsha": "4cfa51ae120ab4c01e8634db5ee24ff2646e6905", "size": 3248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/say/say.cpp", "max_stars_repo_name": "RockLloque/Exercism", "max_stars_repo_head_hexsha": "c437dd6cf3246576900c76c2dba775b6647e3347", "max_stars_repo_licenses": ["MIT"], "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/say/say.cpp", "max_issues_repo_name": "RockLloque/Exercism", "max_issues_repo_head_hexsha": "c437dd6cf3246576900c76c2dba775b6647e3347", "max_issues_repo_licenses": ["MIT"], "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/say/say.cpp", "max_forks_repo_name": "RockLloque/Exercism", "max_forks_repo_head_hexsha": "c437dd6cf3246576900c76c2dba775b6647e3347", "max_forks_repo_licenses": ["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.7986577181, "max_line_length": 88, "alphanum_fraction": 0.5535714286, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5439376997993782}}
{"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#include <mlpack/methods/decision_tree/random_dimension_select.hpp>\n#include <mlpack/methods/decision_tree/multiple_random_dimension_select.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n#include \"serialization.hpp\"\n#include \"mock_categorical_data.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::rowvec weights(10, arma::fill::ones);\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<false>(labels, c, weights), 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::rowvec weights = arma::ones<arma::rowvec>(10);\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  {\n    BOOST_REQUIRE_CLOSE(\n        GiniGain::Evaluate<false>(labels, c, weights), -0.5, 1e-5);\n    double weightedGain = GiniGain::Evaluate<true>(labels, c, weights);\n\n    // The weighted gain should stay the same with unweight one\n    BOOST_REQUIRE_EQUAL(\n        GiniGain::Evaluate<false>(labels, c, weights), weightedGain);\n  }\n}\n\n/**\n * The Gini gain of an empty vector is 0.\n */\nBOOST_AUTO_TEST_CASE(GiniGainEmptyTest)\n{\n  arma::rowvec weights = arma::ones<arma::rowvec>(10);\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<false>(labels, c, weights), 1e-5);\n\n  for (size_t c = 1; c < 10; ++c)\n    BOOST_REQUIRE_SMALL(GiniGain::Evaluate<true>(labels, c, weights), 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    arma::rowvec weights(c);\n    for (size_t i = 0; i < c; ++i)\n    {\n      labels[i] = i;\n      weights[i] = 1;\n    }\n\n    // Calculate Gini gain and make sure it is correct.\n    BOOST_REQUIRE_CLOSE(GiniGain::Evaluate<false>(labels, c, weights),\n        -(1.0 - 1.0 / c), 1e-5);\n    BOOST_REQUIRE_CLOSE(GiniGain::Evaluate<true>(labels, c, weights),\n        -(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::rowvec weights(numPoints);\n    weights.ones();\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<false>(labels, 2, weights), -0.5,\n        1e-5);\n    BOOST_REQUIRE_CLOSE(GiniGain::Evaluate<true>(labels, 2, weights), -0.5,\n        1e-5);\n  }\n}\n\n\n/**\n * To make sure the Gini gain can been cacluate proporately with weight.\n */\nBOOST_AUTO_TEST_CASE(GiniGainWithWeight)\n{\n  arma::Row<size_t> labels(10);\n  arma::rowvec weights(10);\n  for (size_t i = 0; i < 5; ++i)\n  {\n    labels[i] = 0;\n    weights[i] = 0.3;\n  }\n  for (size_t i = 5; i < 10; ++i)\n  {\n    labels[i] = 1;\n    weights[i] = 0.7;\n  }\n\n  BOOST_REQUIRE_CLOSE(\n      GiniGain::Evaluate<true>(labels, 2, weights), -0.42, 1e-5);\n}\n\n/**\n * The information gain should be zero when the labels are perfect.\n */\nBOOST_AUTO_TEST_CASE(InformationGainPerfectTest)\n{\n  arma::rowvec weights;\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  {\n    BOOST_REQUIRE_SMALL(\n        InformationGain::Evaluate<false>(labels, c, weights), 1e-5);\n  }\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  arma::rowvec weights(10);\n  weights.ones();\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  {\n    // Weighted and unweighted result should be the same.\n    BOOST_REQUIRE_CLOSE(InformationGain::Evaluate<false>(labels, c, weights),\n        -1.0, 1e-5);\n    BOOST_REQUIRE_CLOSE(InformationGain::Evaluate<true>(labels, c, weights),\n        -1.0, 1e-5);\n  }\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  arma::rowvec weights = arma::ones<arma::rowvec>(10);\n  for (size_t c = 1; c < 10; ++c)\n  {\n    BOOST_REQUIRE_SMALL(InformationGain::Evaluate<false>(labels, c, weights),\n        1e-5);\n    BOOST_REQUIRE_SMALL(InformationGain::Evaluate<true>(labels, c, weights),\n        1e-5);\n  }\n}\n\n/**\n * The information gain is log2(1/k) when splitting equal classes.\n */\nBOOST_AUTO_TEST_CASE(InformationGainEvenSplitManyClassTest)\n{\n  arma::rowvec weights;\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<false>(labels, c, weights),\n        std::log2(1.0 / c), 1e-5);\n  }\n}\n\n/**\n * Test the information gain with weighted labels\n */\nBOOST_AUTO_TEST_CASE(InformationWithWeight)\n{\n  arma::Row<size_t> labels(10);\n  arma::rowvec weights(\"1 1 1 1 1 0 0 0 0 0\");\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  // Zero is not a good result as gain, but we just need to prove\n  // cacluation works.\n  BOOST_REQUIRE_CLOSE(\n      InformationGain::Evaluate<true>(labels, 2, weights), 0, 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    arma::rowvec weights = arma::ones<arma::rowvec>(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<false>(labels, 2, weights),\n        -1.0, 1e-5);\n    // It should make no difference between a weighted and unweighted\n    // calculation.\n    BOOST_REQUIRE_CLOSE(InformationGain::Evaluate<true>(labels, 2, weights),\n        -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  arma::rowvec weights(labels.n_elem);\n  weights.ones();\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<false>(labels, 2, weights);\n  const double gain = BestBinaryNumericSplit<GiniGain>::SplitIfBetter<false>(\n      bestGain, values, labels, 2, weights, 3, 1e-7, classProbabilities,\n      aux);\n  const double weightedGain =\n      BestBinaryNumericSplit<GiniGain>::SplitIfBetter<true>(bestGain, values,\n      labels, 2, weights, 3, 1e-7, classProbabilities, aux);\n\n  // Make sure that a split was made.\n  BOOST_REQUIRE_GT(gain, bestGain);\n\n  // Make sure weight works and is not different than the unweighted one.\n  BOOST_REQUIRE_EQUAL(gain, weightedGain);\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  arma::rowvec weights(labels.n_elem);\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<false>(labels, 2, weights);\n  const double gain = BestBinaryNumericSplit<GiniGain>::SplitIfBetter<false>(\n      bestGain, values, labels, 2, weights, 8, 1e-7, classProbabilities,\n      aux);\n  // This should make no difference because it won't split at all.\n  const double weightedGain =\n      BestBinaryNumericSplit<GiniGain>::SplitIfBetter<true>(bestGain, values,\n      labels, 2, weights, 8, 1e-7, classProbabilities, aux);\n\n  // Make sure that no split was made.\n  BOOST_REQUIRE_EQUAL(gain, DBL_MAX);\n  BOOST_REQUIRE_EQUAL(gain, weightedGain);\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  arma::rowvec weights;\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<false>(labels, 2, weights);\n  const double gain = BestBinaryNumericSplit<GiniGain>::SplitIfBetter<false>(\n      bestGain, values, labels, 2, weights, 10, 1e-7, classProbabilities,\n      aux);\n\n  // Make sure there was no split.\n  BOOST_REQUIRE_EQUAL(gain, DBL_MAX);\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  arma::rowvec weights(labels.n_elem);\n  weights.ones();\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<false>(labels, 3, weights);\n  const double gain = AllCategoricalSplit<GiniGain>::SplitIfBetter<false>(\n      bestGain, values, 4, labels, 3, weights, 3, 1e-7, classProbabilities,\n      aux);\n  const double weightedGain =\n      AllCategoricalSplit<GiniGain>::SplitIfBetter<true>(bestGain, values, 4,\n      labels, 3, weights, 3, 1e-7, 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  BOOST_REQUIRE_EQUAL(gain, weightedGain);\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  arma::rowvec weights(labels.n_elem);\n  weights.ones();\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<false>(labels, 3, weights);\n  const double gain = AllCategoricalSplit<GiniGain>::SplitIfBetter<false>(\n      bestGain, values, 4, labels, 3, weights, 4, 1e-7, classProbabilities,\n      aux);\n\n  // Make sure it's not split.\n  BOOST_REQUIRE_EQUAL(gain, DBL_MAX);\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  arma::rowvec weights = arma::ones<arma::rowvec>(300);\n\n  for (size_t i = 0; i < 300; i += 3)\n  {\n    values[i] = int(i / 3) % 10;\n    labels[i] = 0;\n    values[i + 1] = int(i / 3) % 10;\n    labels[i + 1] = 1;\n    values[i + 2] = int(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<false>(labels, 3, weights);\n  const double gain = AllCategoricalSplit<GiniGain>::SplitIfBetter<false>(\n      bestGain, values, 10, labels, 3, weights, 10, 1e-7,\n      classProbabilities, aux);\n  const double weightedGain =\n      AllCategoricalSplit<GiniGain>::SplitIfBetter<true>(bestGain, values, 10,\n      labels, 3, weights, 10, 1e-7, classProbabilities, aux);\n\n  // Make sure that there was no split.\n  BOOST_REQUIRE_EQUAL(gain, DBL_MAX);\n  BOOST_REQUIRE_EQUAL(gain, weightedGain);\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, 100, arma::fill::randu);\n  arma::Row<size_t> labels(100);\n  for (size_t i = 0; i < 50; ++i)\n  {\n    dataset(3, i) = 0.0;\n    labels[i] = 0;\n  }\n  for (size_t i = 50; i < 100; ++i)\n  {\n    dataset(3, i) = 1.0;\n    labels[i] = 1;\n  }\n\n  // Use default parameters.\n  DecisionTree<> d(dataset, labels, 2, 10);\n\n  // Now require that we have some children.\n  BOOST_REQUIRE_GT(d.NumChildren(), 0);\n}\n\n/**\n * Construct a tree with weighted labels.\n */\nBOOST_AUTO_TEST_CASE(BasicConstructionTestWithWeight)\n{\n  arma::mat dataset(10, 100, arma::fill::randu);\n  arma::Row<size_t> labels(100);\n  for (size_t i = 0; i < 50; ++i)\n  {\n    dataset(3, i) = 0.0;\n    labels[i] = 0;\n  }\n  for (size_t i = 50; i < 100; ++i)\n  {\n    dataset(3, i) = 1.0;\n    labels[i] = 1;\n  }\n  arma::rowvec weights(labels.n_elem);\n  weights.ones();\n\n  // Use default parameters.\n  DecisionTree<> wd(dataset, labels, 2, weights, 10);\n  DecisionTree<> d(dataset, labels, 2, 10);\n\n  // Now require that we have some children.\n  BOOST_REQUIRE_GT(wd.NumChildren(), 0);\n  BOOST_REQUIRE_EQUAL(wd.NumChildren(), d.NumChildren());\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  arma::mat dataset(10, 100, arma::fill::randu);\n  arma::Row<size_t> labels(100);\n  for (size_t i = 0; i < 50; ++i)\n  {\n    dataset(3, i) = 0.0;\n    labels[i] = 0;\n  }\n  for (size_t i = 50; i < 100; ++i)\n  {\n    dataset(3, i) = 1.0;\n    labels[i] = 1;\n  }\n\n  DecisionTree<> d(dataset, labels, 2, 1, 0.0); // 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 < 100; ++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, 2);\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 * Construct the decision tree with weighted labels\n */\nBOOST_AUTO_TEST_CASE(PerfectTrainingSetWithWeight)\n{\n  // Completely random dataset with no structure.\n  arma::mat dataset(10, 100, arma::fill::randu);\n  arma::Row<size_t> labels(100);\n  for (size_t i = 0; i < 50; ++i)\n  {\n    dataset(3, i) = 0.0;\n    labels[i] = 0;\n  }\n  for (size_t i = 50; i < 100; ++i)\n  {\n    dataset(3, i) = 1.0;\n    labels[i] = 1;\n  }\n  arma::rowvec weights(labels.n_elem);\n  weights.ones();\n\n  // Minimum leaf size of 1.\n  DecisionTree<> d(dataset, labels, 2, weights, 1, 0.0);\n\n  // This part of code is dupliacte with no weighted one.\n  for (size_t i = 0; i < 100; ++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, 2);\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/**\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::Row<size_t> labels;\n  if (!data::Load(\"vc2_labels.txt\", labels))\n    BOOST_FAIL(\"Cannot load labels for vc2_labels.txt\");\n\n  // Initialize an all-ones weight matrix.\n  arma::rowvec weights(labels.n_cols, arma::fill::ones);\n\n  // Build decision tree.\n  DecisionTree<> d(inputData, labels, 3, 10); // Leaf size of 10.\n  DecisionTree<> wd(inputData, labels, 3, weights, 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  // reset the prediction\n  predictions.zeros();\n  wd.Classify(testData, predictions);\n\n  BOOST_REQUIRE_EQUAL(predictions.n_elem, testData.n_cols);\n\n  // Figure out the accuracy.\n  double wdcorrect = 0.0;\n  for (size_t i = 0; i < predictions.n_elem; ++i)\n    if (predictions[i] == trueTestLabels[i])\n      ++wdcorrect;\n  wdcorrect /= predictions.n_elem;\n\n  BOOST_REQUIRE_GT(wdcorrect, 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  arma::mat d;\n  arma::Row<size_t> l;\n  data::DatasetInfo di;\n  MockCategoricalData(d, l, di);\n\n  // Split into a training set and a test set.\n  arma::mat trainingData = d.cols(0, 1999);\n  arma::mat testData = d.cols(2000, 3999);\n  arma::Row<size_t> trainingLabels = l.subvec(0, 1999);\n  arma::Row<size_t> testLabels = l.subvec(2000, 3999);\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 * Test that we can build a decision tree with weights on a simple categorical\n * dataset.\n */\nBOOST_AUTO_TEST_CASE(CategoricalBuildTestWithWeight)\n{\n  arma::mat d;\n  arma::Row<size_t> l;\n  data::DatasetInfo di;\n  MockCategoricalData(d, l, di);\n\n  // Split into a training set and a test set.\n  arma::mat trainingData = d.cols(0, 1999);\n  arma::mat testData = d.cols(2000, 3999);\n  arma::Row<size_t> trainingLabels = l.subvec(0, 1999);\n  arma::Row<size_t> testLabels = l.subvec(2000, 3999);\n\n  arma::Row<double> weights = arma::ones<arma::Row<double>>(\n      trainingLabels.n_elem);\n\n  // Build the tree.\n  DecisionTree<> tree(trainingData, di, trainingLabels, 5, weights, 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,\n      AllDimensionSelect, double, 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\n/**\n * Test that we can build a decision tree using weighted data (where the\n * low-weighted data is random noise), and that the tree still builds correctly\n * enough to get good results.\n */\nBOOST_AUTO_TEST_CASE(WeightedDecisionTreeTest)\n{\n  arma::mat dataset;\n  arma::Row<size_t> labels;\n  data::Load(\"vc2.csv\", dataset);\n  data::Load(\"vc2_labels.txt\", labels);\n\n  // Add some noise.\n  arma::mat noise(dataset.n_rows, 1000, arma::fill::randu);\n  arma::Row<size_t> noiseLabels(1000);\n  for (size_t i = 0; i < noiseLabels.n_elem; ++i)\n    noiseLabels[i] = math::RandInt(3); // Random label.\n\n  // Concatenate data matrices.\n  arma::mat data = arma::join_rows(dataset, noise);\n  arma::Row<size_t> fullLabels = arma::join_rows(labels, noiseLabels);\n\n  // Now set weights.\n  arma::rowvec weights(dataset.n_cols + 1000);\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n    weights[i] = math::Random(0.9, 1.0);\n  for (size_t i = dataset.n_cols; i < dataset.n_cols + 1000; ++i)\n    weights[i] = math::Random(0.0, 0.01); // Low weights for false points.\n\n  // Now build the decision tree.  I think the syntax is right here.\n  DecisionTree<> d(data, fullLabels, 3, weights, 10);\n\n  // Now we can check that we get good performance on the VC2 test set.\n  arma::mat testData;\n  arma::Row<size_t> testLabels;\n  data::Load(\"vc2_test.csv\", testData);\n  data::Load(\"vc2_test_labels.txt\", testLabels);\n\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] == testLabels[i])\n      ++correct;\n  correct /= predictions.n_elem;\n\n  BOOST_REQUIRE_GT(correct, 0.75);\n}\n/**\n * Test that we can build a decision tree on a simple categorical dataset using\n * weights, with low-weight noise added.\n */\nBOOST_AUTO_TEST_CASE(CategoricalWeightedBuildTest)\n{\n  arma::mat d;\n  arma::Row<size_t> l;\n  data::DatasetInfo di;\n  MockCategoricalData(d, l, di);\n\n  // Split into a training set and a test set.\n  arma::mat trainingData = d.cols(0, 1999);\n  arma::mat testData = d.cols(2000, 3999);\n  arma::Row<size_t> trainingLabels = l.subvec(0, 1999);\n  arma::Row<size_t> testLabels = l.subvec(2000, 3999);\n\n  // Now create random points.\n  arma::mat randomNoise(4, 2000);\n  arma::Row<size_t> randomLabels(2000);\n  for (size_t i = 0; i < 2000; ++i)\n  {\n    randomNoise(0, i) = math::Random();\n    randomNoise(1, i) = math::Random();\n    randomNoise(2, i) = math::RandInt(4);\n    randomNoise(3, i) = math::RandInt(2);\n    randomLabels[i] = math::RandInt(5);\n  }\n\n  // Generate weights.\n  arma::rowvec weights(4000);\n  for (size_t i = 0; i < 2000; ++i)\n    weights[i] = math::Random(0.9, 1.0);\n  for (size_t i = 2000; i < 4000; ++i)\n    weights[i] = math::Random(0.0, 0.001);\n\n  arma::mat fullData = arma::join_rows(trainingData, randomNoise);\n  arma::Row<size_t> fullLabels = arma::join_rows(trainingLabels, randomLabels);\n\n  // Build the tree.\n  DecisionTree<> tree(fullData, di, fullLabels, 5, weights, 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 * Test that we can build a decision tree using weighted data (where the\n * low-weighted data is random noise) with information gain, and that the tree\n * still builds correctly enough to get good results.\n */\nBOOST_AUTO_TEST_CASE(WeightedDecisionTreeInformationGainTest)\n{\n  arma::mat dataset;\n  arma::Row<size_t> labels;\n  data::Load(\"vc2.csv\", dataset);\n  data::Load(\"vc2_labels.txt\", labels);\n\n  // Add some noise.\n  arma::mat noise(dataset.n_rows, 1000, arma::fill::randu);\n  arma::Row<size_t> noiseLabels(1000);\n  for (size_t i = 0; i < noiseLabels.n_elem; ++i)\n    noiseLabels[i] = math::RandInt(3); // Random label.\n\n  // Concatenate data matrices.\n  arma::mat data = arma::join_rows(dataset, noise);\n  arma::Row<size_t> fullLabels = arma::join_rows(labels, noiseLabels);\n\n  // Now set weights.\n  arma::rowvec weights(dataset.n_cols + 1000);\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n    weights[i] = math::Random(0.9, 1.0);\n  for (size_t i = dataset.n_cols; i < dataset.n_cols + 1000; ++i)\n    weights[i] = math::Random(0.0, 0.01); // Low weights for false points.\n\n  // Now build the decision tree.  I think the syntax is right here.\n  DecisionTree<InformationGain> d(data, fullLabels, 3, weights, 10);\n\n  // Now we can check that we get good performance on the VC2 test set.\n  arma::mat testData;\n  arma::Row<size_t> testLabels;\n  data::Load(\"vc2_test.csv\", testData);\n  data::Load(\"vc2_test_labels.txt\", testLabels);\n\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] == testLabels[i])\n      ++correct;\n  correct /= predictions.n_elem;\n\n  BOOST_REQUIRE_GT(correct, 0.75);\n}\n/**\n * Test that we can build a decision tree using information gain on a simple\n * categorical dataset using weights, with low-weight noise added.\n */\nBOOST_AUTO_TEST_CASE(CategoricalInformationGainWeightedBuildTest)\n{\n  arma::mat d;\n  arma::Row<size_t> l;\n  data::DatasetInfo di;\n  MockCategoricalData(d, l, di);\n\n  // Split into a training set and a test set.\n  arma::mat trainingData = d.cols(0, 1999);\n  arma::mat testData = d.cols(2000, 3999);\n  arma::Row<size_t> trainingLabels = l.subvec(0, 1999);\n  arma::Row<size_t> testLabels = l.subvec(2000, 3999);\n\n  // Now create random points.\n  arma::mat randomNoise(4, 2000);\n  arma::Row<size_t> randomLabels(2000);\n  for (size_t i = 0; i < 2000; ++i)\n  {\n    randomNoise(0, i) = math::Random();\n    randomNoise(1, i) = math::Random();\n    randomNoise(2, i) = math::RandInt(4);\n    randomNoise(3, i) = math::RandInt(2);\n    randomLabels[i] = math::RandInt(5);\n  }\n\n  // Generate weights.\n  arma::rowvec weights(4000);\n  for (size_t i = 0; i < 2000; ++i)\n    weights[i] = math::Random(0.9, 1.0);\n  for (size_t i = 2000; i < 4000; ++i)\n    weights[i] = math::Random(0.0, 0.001);\n\n  arma::mat fullData = arma::join_rows(trainingData, randomNoise);\n  arma::Row<size_t> fullLabels = arma::join_rows(trainingLabels, randomLabels);\n\n  // Build the tree.\n  DecisionTree<InformationGain> tree(fullData, di, fullLabels, 5, weights, 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 the random dimension selector only has one element.\n */\nBOOST_AUTO_TEST_CASE(RandomDimensionSelectTest)\n{\n  RandomDimensionSelect r;\n  r.Dimensions() = 10;\n\n  BOOST_REQUIRE_LT(r.Begin(), 10);\n  BOOST_REQUIRE_EQUAL(r.Next(), r.End());\n  BOOST_REQUIRE_EQUAL(r.Next(), r.End());\n  BOOST_REQUIRE_EQUAL(r.Next(), r.End());\n}\n\n/**\n * Make sure that the random dimension selector selects different values.\n */\nBOOST_AUTO_TEST_CASE(RandomDimensionSelectRandomTest)\n{\n  // We'll check that 4 values are not all the same.\n  RandomDimensionSelect r1, r2, r3, r4;\n  r1.Dimensions() = 100000;\n  r2.Dimensions() = 100000;\n  r3.Dimensions() = 100000;\n  r4.Dimensions() = 100000;\n\n  BOOST_REQUIRE((r1.Begin() != r2.Begin()) ||\n                (r1.Begin() != r3.Begin()) ||\n                (r1.Begin() != r4.Begin()));\n}\n\n/**\n * Make sure that the multiple random dimension select only has the right number\n * of elements.\n */\nBOOST_AUTO_TEST_CASE(MultipleRandomDimensionSelectTest)\n{\n  MultipleRandomDimensionSelect r(5);\n  r.Dimensions() = 10;\n\n  // Make sure we get five elements.\n  BOOST_REQUIRE_LT(r.Begin(), 10);\n  BOOST_REQUIRE_LT(r.Next(), 10);\n  BOOST_REQUIRE_LT(r.Next(), 10);\n  BOOST_REQUIRE_LT(r.Next(), 10);\n  BOOST_REQUIRE_LT(r.Next(), 10);\n  BOOST_REQUIRE_EQUAL(r.Next(), r.End());\n}\n\n/**\n * Make sure we get every element from the distribution.\n */\nBOOST_AUTO_TEST_CASE(MultipleRandomDimensionAllSelectTest)\n{\n  MultipleRandomDimensionSelect r(3);\n  r.Dimensions() = 3;\n\n  bool found[3];\n  found[0] = found[1] = found[2] = false;\n\n  found[r.Begin()] = true;\n  found[r.Next()] = true;\n  found[r.Next()] = true;\n\n  BOOST_REQUIRE_EQUAL(found[0], true);\n  BOOST_REQUIRE_EQUAL(found[1], true);\n  BOOST_REQUIRE_EQUAL(found[2], true);\n}\n\n/**\n * Make sure the right number of classes is returned for an empty tree (1).\n */\nBOOST_AUTO_TEST_CASE(NumClassesEmptyTreeTest)\n{\n  DecisionTree<> dt;\n  BOOST_REQUIRE_EQUAL(dt.NumClasses(), 1);\n}\n\n/**\n * Make sure the right number of classes is returned for a nonempty tree.\n */\nBOOST_AUTO_TEST_CASE(NumClassesTest)\n{\n  // Load a dataset to train with.\n  arma::mat dataset;\n  arma::Row<size_t> labels;\n  data::Load(\"vc2.csv\", dataset);\n  data::Load(\"vc2_labels.txt\", labels);\n\n  DecisionTree<> dt(dataset, labels, 3);\n\n  BOOST_REQUIRE_EQUAL(dt.NumClasses(), 3);\n}\n\n/*\n * Test that we can pass const data into DecisionTree constructors.\n */\nBOOST_AUTO_TEST_CASE(ConstDataTest)\n{\n  arma::mat data;\n  arma::Row<size_t> labels;\n  data::DatasetInfo datasetInfo;\n  MockCategoricalData(data, labels, datasetInfo);\n\n  const arma::mat& constData = data;\n  const arma::Row<size_t>& constLabels = labels;\n  const arma::rowvec constWeights(labels.n_elem, arma::fill::randu);\n  const size_t numClasses = 5;\n\n  DecisionTree<> dt(constData, constLabels, numClasses);\n  DecisionTree<> dt2(constData, datasetInfo, constLabels, numClasses);\n  DecisionTree<> dt3(constData, constLabels, numClasses, constWeights);\n  DecisionTree<> dt4(constData, datasetInfo, constLabels, numClasses,\n      constWeights);\n}\n\n/**\n * Construct the decision tree with splitting only if gain is more than\n * threshold.\n */\nBOOST_AUTO_TEST_CASE(RegularisedDecisionTree)\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  arma::rowvec weights(labels.n_elem);\n  weights.ones();\n\n  // Minimum leaf size of 1.\n  DecisionTree<> d(dataset, labels, 3, weights, 1, 1e-7);\n\n  // Minimum leaf size of 1 and Minimum gain split of 0.01.\n  DecisionTree<> dRegularised(dataset, labels, 3, weights, 1, 0.01);\n\n  size_t count = 0;\n  // This part of code is dupliacte with no weighted one.\n  for (size_t i = 0; i < 1000; ++i)\n  {\n    size_t prediction, predictionsregularised;\n    arma::vec probabilities, probabilitiesRegularised;\n\n    d.Classify(dataset.col(i), prediction, probabilities);\n    dRegularised.Classify(dataset.col(i), predictionsregularised,\n                          probabilitiesRegularised);\n\n    if (prediction != predictionsregularised)\n      count++;\n\n    BOOST_REQUIRE_EQUAL(probabilities.n_elem, 3);\n    BOOST_REQUIRE_EQUAL(probabilitiesRegularised.n_elem, 3);\n  }\n\n  BOOST_REQUIRE_GT(count, 0);\n}\n\n/**\n * Test that DecisionTree::Train() returns finite entropy on numeric dataset.\n */\nBOOST_AUTO_TEST_CASE(DecisionTreeNumericTrainReturnEntropy)\n{\n  arma::mat dataset(10, 1000, arma::fill::randu);\n  arma::Row<size_t> labels(1000);\n  arma::rowvec weights(labels.n_elem);\n  weights.ones();\n\n  for (size_t i = 0; i < 1000; ++i)\n    labels[i] = i % 3; // 3 classes.\n\n  // Train a simpe tree on numeric dataset.\n  DecisionTree<> d(3);\n  double entropy = d.Train(dataset, labels, 3, 50);\n\n  BOOST_REQUIRE_EQUAL(std::isfinite(entropy), true);\n\n  // Train a tree with weights on numeric dataset.\n  DecisionTree<> wd(3);\n  entropy = wd.Train(dataset, labels, 3, weights, 50);\n\n  BOOST_REQUIRE_EQUAL(std::isfinite(entropy), true);\n}\n\n/**\n * Test that DecisionTree::Train() returns finite entropy on categorical\n * dataset.\n */\nBOOST_AUTO_TEST_CASE(DecisionTreeCategoricalTrainReturnEntropy)\n{\n  arma::mat d;\n  arma::Row<size_t> l;\n  data::DatasetInfo di;\n  MockCategoricalData(d, l, di);\n\n  arma::Row<double> weights = arma::ones<arma::Row<double>>(l.n_elem);\n\n  // Train a simple tree on categorical dataset.\n  DecisionTree<> dtree(5);\n  double entropy = dtree.Train(d, di, l, 5, 10);\n\n  BOOST_REQUIRE_EQUAL(std::isfinite(entropy), true);\n\n  // Train a tree with weights on categorical dataset.\n  DecisionTree<> wdtree(5);\n  entropy = wdtree.Train(d, di, l, 5, weights, 10);\n\n  BOOST_REQUIRE_EQUAL(std::isfinite(entropy), true);\n}\n\n/**\n * Make sure different maximum depth values give different numbers of children.\n */\nBOOST_AUTO_TEST_CASE(DifferentMaximumDepthTest)\n{\n  arma::mat dataset;\n  arma::Row<size_t> labels;\n  data::Load(\"vc2.csv\", dataset);\n  data::Load(\"vc2_labels.txt\", labels);\n\n  DecisionTree<> d(dataset, labels, 3, 10, 1e-7, 1);\n\n  DecisionTree<> d1(dataset, labels, 3, 10, 1e-7, 2);\n\n  DecisionTree<> d2(dataset, labels, 3, 10, 1e-7);\n\n  // Now require that we have zero children.\n  BOOST_REQUIRE_EQUAL(d.NumChildren(), 0);\n\n  // Now require that we have two children.\n  BOOST_REQUIRE_EQUAL(d1.NumChildren(), 2);\n  BOOST_REQUIRE_EQUAL(d1.Child(0).NumChildren(), 0);\n  BOOST_REQUIRE_EQUAL(d1.Child(1).NumChildren(), 0);\n\n  // Now require that we have two children.\n  BOOST_REQUIRE_EQUAL(d2.NumChildren(), 2);\n  BOOST_REQUIRE_EQUAL(d2.Child(0).NumChildren(), 2);\n  BOOST_REQUIRE_EQUAL(d2.Child(1).NumChildren(), 2);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "334fa745a99eb8f27b3fde130c08bed155a49244", "size": 36899, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/decision_tree_test.cpp", "max_stars_repo_name": "AYESDIE/mlpack", "max_stars_repo_head_hexsha": "12a50a055ba7f69340598329bd146ee37bec110f", "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": "2020-03-12T20:10:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-12T20:10:39.000Z", "max_issues_repo_path": "src/mlpack/tests/decision_tree_test.cpp", "max_issues_repo_name": "guimuguo/mlpack", "max_issues_repo_head_hexsha": "897b0cddf6ba23733f701b4679fac08f9f90ebb2", "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": "guimuguo/mlpack", "max_forks_repo_head_hexsha": "897b0cddf6ba23733f701b4679fac08f9f90ebb2", "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.5192, "max_line_length": 80, "alphanum_fraction": 0.6804520448, "num_tokens": 10951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5439376958431853}}
{"text": "#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include \"quicksvg/graph_fn.hpp\"\n#include \"quicksvg/plot_time_series.hpp\"\n#include \"quicksvg/ulp_plot.hpp\"\n#include \"quicksvg/scatter_plot.hpp\"\n#include \"gtest/gtest.h\"\n\nusing boost::math::constants::pi;\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::math::tgamma;\n\nTEST(graph_fn, types) {\n    {\n        float a = -pi<float>();\n        float b = pi<float>();\n        std::string title = \"sin(\ud835\udc65) and cos(\ud835\udc65)\";\n        std::string filename = \"examples/sine_and_cosine_float.svg\";\n        quicksvg::graph_fn sin_graph(a, b, title, filename);\n        auto f = [](float x)->float { return std::sin(x); };\n        auto g = [](float x)->float { return std::cos(x); };\n        sin_graph.add_fn(f);\n        sin_graph.add_fn(g, \"green\");\n\n        sin_graph.write_all();\n    }\n\n    {\n        double a = -pi<double>();\n        double b = pi<double>();\n        std::string title = \"sin(\ud835\udc65) and cos(\ud835\udc65)\";\n        std::string filename = \"examples/sine_and_cosine_double.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\n    {\n        long double a = -pi<long double>();\n        long double b = pi<long double>();\n        std::string title = \"sin(\ud835\udc65) and cos(\ud835\udc65)\";\n        std::string filename = \"examples/sine_and_cosine_long_double.svg\";\n        auto f = [](long double x)->long double { return std::sin(x); };\n        auto g = [](long double x)->long 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        sin_graph.write_all();\n    }\n\n    {\n        cpp_bin_float_50 a = -pi<cpp_bin_float_50>();\n        cpp_bin_float_50 b = pi<cpp_bin_float_50>();\n        std::string title = \"sin(\ud835\udc65) and cos(\ud835\udc65)\";\n        std::string filename = \"examples/sine_and_cosine_cpp_bin_float_50.svg\";\n        quicksvg::graph_fn sin_graph(a, b, title, filename);\n        auto f = [](cpp_bin_float_50 x)->cpp_bin_float_50 { return sin(x); };\n        auto g = [](cpp_bin_float_50 x)->cpp_bin_float_50 { return cos(x); };\n        sin_graph.add_fn(f);\n        sin_graph.add_fn(g, \"green\");\n\n        sin_graph.write_all();\n    }\n}\n\nTEST(PlotTimeSeries, types)\n{\n    {\n        std::vector<float> v(50);\n        std::vector<float> u(50);\n        float start_time = 0;\n        float 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        std::string title = \"sine and cosine time series\";\n        std::string filename = \"examples/sin_cos_time_series_float.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        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        std::string title = \"sine and cosine time series\";\n        std::string filename = \"examples/sin_cos_time_series_double.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    {\n        std::vector<long double> v(50);\n        std::vector<long double> u(50);\n        long double start_time = 0;\n        long 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        std::string title = \"sine and cosine time series\";\n        std::string filename = \"examples/sin_cos_time_series_long_double.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    {\n        std::vector<cpp_bin_float_50> v(50);\n        std::vector<cpp_bin_float_50> u(50);\n        cpp_bin_float_50 start_time = 0;\n        cpp_bin_float_50 time_step = 0.25;\n        using std::sin;\n        using std::cos;\n        for (size_t i = 0; i < v.size(); ++i) {\n          v[i] = sin(start_time + i*time_step);\n          u[i] = cos(start_time + i*time_step);\n        }\n\n        std::string title = \"sine and cosine time series\";\n        std::string filename = \"examples/sin_cos_time_series_cpp_bin_float_50.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\nTEST(ULPPlot, types)\n{\n    {\n        int samples = 10000;\n        float a = 1;\n        float b = 15;\n        std::string title = \"ULP accuracy of float precision gamma on [1, 15]\";\n        std::string filename = \"examples/ulp_gamma_float.svg\";\n        quicksvg::ulp_plot(tgamma<float>, tgamma<cpp_bin_float_50>, a, b, title, filename, samples);\n    }\n    {\n        int samples = 10000;\n        double a = 1;\n        double b = 15;\n        std::string title = \"ULP accuracy of double precision sin on [1, 15]\";\n        std::string filename = \"examples/ulp_gamma_double.svg\";\n        quicksvg::ulp_plot(tgamma<double>, tgamma<cpp_bin_float_50>, a, b, title, filename, samples);\n    }\n    {\n        int samples = 10000;\n        long double a = 1;\n        long double b = 15;\n        std::string title = \"ULP accuracy of long double precision sin on [1, 15]\";\n        std::string filename = \"examples/ulp_gamma_long_double.svg\";\n        quicksvg::ulp_plot(tgamma<long double>, tgamma<cpp_bin_float_50>, a, b, title, filename, samples);\n    }\n}\n\nTEST(ScatterPlot, types)\n{\n    {\n        int n = 500;\n        std::vector<std::pair<double, double>> v(n);\n        std::random_device rd;\n        std::uniform_real_distribution<double> dis(-0.01, 0.01);\n\n        for (int i = 0; i < n; ++i) {\n            double x = std::sin(6.28*i/n) + dis(rd);\n            double y = std::cos(6.28*i/n) + dis(rd);\n            v[i] = {x, y};\n        }\n        std::string title= \"Scatter plot\";\n        std::string filename = \"examples/scatter_plot.svg\";\n        quicksvg::scatter_plot<double> scatter(title, filename);\n        scatter.add_dataset(v);\n        scatter.write_all();\n    }\n\n    {\n        int n = 500;\n        std::vector<std::pair<double, double>> v(n);\n        std::random_device rd;\n        std::uniform_real_distribution<double> dis(-0.01, 0.01);\n\n        for (int i = 0; i < n; ++i) {\n            double x = std::sin(6.28*i/n) + dis(rd);\n            double y = std::cos(6.28*i/n) + dis(rd);\n            v[i] = {x, y};\n        }\n        std::string title= \"Scatter plot\";\n        std::string filename = \"examples/scatter_plot_xlabel.svg\";\n        std::string x_label = \"x\";\n        quicksvg::scatter_plot<double> scatter(title, filename, x_label);\n        scatter.add_dataset(v);\n        scatter.write_all();\n    }\n\n    {\n        int n = 500;\n        std::vector<std::pair<double, double>> v(n);\n        std::random_device rd;\n        std::uniform_real_distribution<double> dis(-0.01, 0.01);\n\n        for (int i = 0; i < n; ++i) {\n            double x = std::sin(6.28*i/n) + dis(rd);\n            double y = std::cos(6.28*i/n) + dis(rd);\n            v[i] = {x, y};\n        }\n        std::string title= \"Scatter plot\";\n        std::string filename = \"examples/scatter_plot_ylabel.svg\";\n        std::string x_label = \"\";\n        std::string y_label = \"y\";\n        quicksvg::scatter_plot<double> scatter(title, filename, x_label, y_label);\n        scatter.add_dataset(v);\n        scatter.write_all();\n    }\n\n}\n\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "8f58690e984fbfe1e28880c24a4b72152990542d", "size": 8294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test.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": "test/test.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": "test/test.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": 33.5789473684, "max_line_length": 106, "alphanum_fraction": 0.574270557, "num_tokens": 2232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5439376908607255}}
{"text": "# include <RcppArmadillo.h>\n// [[ Rcpp :: depends ( RcppArmadillo )]]\nusing namespace Rcpp;\n\n//######################################################################################################################//\n\n\n//' @title ECDF transformation of the training data\n//'\n//' @description Quadrianto and Ghahramani (2015) reccomend the use of the probability intergral transform to transform the continuous input features. The code is edited from https://github.com/dmbates/ecdfExample\n//' @param originaldata Training data matrix\n// [[Rcpp::depends(RcppArmadillo)]]\n//' @export\n// [[Rcpp::export]]\nNumericMatrix cpptrans_cdf(NumericMatrix originaldata){\n  NumericMatrix transformedData(originaldata.nrow(), originaldata.ncol());\n  for(int i=0; i<originaldata.ncol();i++){\n    NumericVector samp= originaldata(_,i);\n    NumericVector sv(clone(samp));\n    std::sort(sv.begin(), sv.end());\n    double nobs = samp.size();\n    NumericVector ans(nobs);\n    for (int k = 0; k < samp.size(); ++k)\n      ans[k] = std::lower_bound(sv.begin(), sv.end(), samp[k]) - sv.begin();\n    //NumericVector ansnum = ans;\n    transformedData(_,i) = (ans+1)/nobs;\n  }\n  return transformedData;\n\n}\n\n//######################################################################################################################//\n\n//' @title ECDF transformation of the test data\n//'\n//' @description Quadrianto and Ghahramani (2015) reccomend the use of the probability intergral transform to transform the continuous input features. The code is edited from https://github.com/dmbates/ecdfExample\n//' @param originaldata Training data matrix\n//' @param testdata Test data matrix\n//' @export\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::export]]\nNumericMatrix cpptrans_cdf_test(NumericMatrix originaldata, NumericMatrix testdata){\n  NumericMatrix transformedData(testdata.nrow(), testdata.ncol());\n  for(int i=0; i<testdata.ncol();i++){\n    NumericVector samp= testdata(_,i);\n    NumericVector svtest = originaldata(_,i);\n    NumericVector sv(clone(svtest));\n    std::sort(sv.begin(), sv.end());\n    double nobs = samp.size();\n    NumericVector ans(nobs);\n    double nobsref = svtest.size();\n    for (int k = 0; k < samp.size(); ++k){\n      ans[k] = std::lower_bound(sv.begin(), sv.end(), samp[k]) - sv.begin();\n    }\n    //NumericVector ansnum = ans;\n    transformedData(_,i) = (ans)/nobsref;\n  }\n  return transformedData;\n\n}\n//######################################################################################################################//\n// [[Rcpp::export]]\nNumericVector scale_response(double a,double b,double c,double d,NumericVector y){\n  NumericVector y_scaled = -((-b*c+a*d)/(-a+b))+((-c+d)*y/(-a+b));\n\n  return(y_scaled);\n}\n//######################################################################################################################//\n\n// [[Rcpp::export]]\nNumericVector get_original(double low,double high,double sp_low,double sp_high,NumericVector sum_preds){\n  NumericVector original_y=(sum_preds*(-low+high))/(-sp_low+sp_high) + (-high*sp_low+low*sp_high)/(-sp_low+sp_high);\n\n  return(original_y);\n}\n//######################################################################################################################//\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::export]]\narma::vec get_original_arma(double low,double high,double sp_low,double sp_high,arma::vec sum_preds){\n  arma::vec original_y=(sum_preds*(-low+high))/(-sp_low+sp_high) + (-high*sp_low+low*sp_high)/(-sp_low+sp_high);\n\n  return(original_y);\n}\n//######################################################################################################################//\n\n// [[Rcpp::export]]\nNumericVector get_original_TE(double low,double high,double sp_low,double sp_high,NumericVector sum_preds){\n  NumericVector original_y=(sum_preds*(-low+high))/(-sp_low+sp_high);\n\n  return(original_y);\n}\n//######################################################################################################################//\n\n// [[Rcpp::export]]\ndouble get_original_TE_double(double low,double high,double sp_low,double sp_high,double sum_preds){\n  double original_y=sum_preds*((-low+high)/(-sp_low+sp_high));\n\n  return(original_y); // reverse scaling of predictions of scaled variable (??)\n}\n//######################################################################################################################//\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::export]]\narma::vec get_original_TE_arma(double low,double high,double sp_low,double sp_high,arma::vec sum_preds){\n  arma::vec original_y=sum_preds*((-low+high)/(-sp_low+sp_high));\n\n  return(original_y); // reverse scaling of predictions of scaled variable (??)\n}\n//######################################################################################################################//\n\n// Dyck paths are represented as sequences of signed chars with values 1 (up)\n// or -1 (down).\n\n// unfolds a path (turns a Dyck suffix followed by a down into an up followed\n// by a Dyck prefix with opposite height), returns the height difference\n// [[Rcpp::export]]\nlong unfold(int p_ind, std::vector<int> output_dyck, long length) {\n  long height = 0;\n  long local_height = 0;\n  int x = 1;\n\n  for(long i = 0; i < length; i ++) {\n    int y = output_dyck[p_ind+i];\n    local_height += y;\n    if(local_height < 0) {\n      y = 1;\n      height += 2;\n      local_height = 0;\n    }\n    output_dyck[p_ind+i] = x;\n    x = y;\n  }\n\n  return height;\n}\n\n\n\n//######################################################################################################################//\n// turns a Dyck prefix into a Dyck path of length -1 (length should be odd)\n// [[Rcpp::export]]\nvoid fold(std::vector<int> output_dyck, long length, long height) {\n  long local_height = 0;\n  int x = -1;\n  // Rcout << \"Line 121. \\n\";\n  // Rcout << \"output_dyck.size() =\" << output_dyck.size() << \". \\n\";\n  // Rcout << \"length - 1 =\" << length - 1 << \". \\n\";\n\n\n  for(long i = length - 1; height > 0; i --) {\n    int y = output_dyck[i];\n    local_height -= y;\n    if(local_height < 0) {\n      y = -1;\n      height -= 2;\n      local_height = 0;\n    }\n    output_dyck[i] = x;\n    x = y;\n  }\n  // Rcout << \"Line 134. \\n\";\n\n}\n\n// // writes a random Dyck prefix, returns its final height\n// // at least length bytes should be allocated first\n// long dyck_prefix(signed char *p, long length) {\n//   long height = 0;\n//\n//   for(long i = 0; i < length; i ++) {\n//     signed char x = random_int(1) ? 1 : -1;\n//     p[i] = x;\n//     height += x;\n//\n//     if(height < 0) {\n//       long j = random_int(i);\n//       height += unfold(p + j, i + 1 - j);\n//     }\n//   }\n//\n//   return height;\n// }\n\n\n\n\n\n\n//######################################################################################################################//\n// wrleast length + 1 bytes should be allocated first\n// [[Rcpp::deites a random Dyck path (length should be even)\n// at pends(RcppArmadillo)]]\n// [[Rcpp::depends(dqrng, BH, sitmo)]]\n\n#include <xoshiro.h>\n#include <dqrng_distribution.h>\n//#include <dqrng.h>\n\n// [[Rcpp::export]]\nvoid dyck_path(std::vector<int> output_dyck, long length) {\n  //long height = dyck_prefix(p, length + 1);\n  // Rcout << \"Line 172. \\n\";\n\n  //std::vector<int> p(length);\n  //std::vector<char> p(length);\n  //char p;\n  //signed char p;// = new signed char[length];\n  int p_ind=0;\n\n  std::random_device device;\n  //std::mt19937 gen(device());\n\n  //possibly use seed?\n  //// std::mt19937 gen(seed);\n\n  dqrng::xoshiro256plus gen(device());              // properly seeded rng\n\n  //dqrng::xoshiro256plus gen(seed);              // properly seeded rng\n\n  std::bernoulli_distribution coin_flip_evev(0.5);\n\n\n  long height = 0;\n\n  // Rcout << \"Line 195. \\n\";\n\n  for(long i = 0; i < length+1; i ++) {\n    //signed char x = random_int(1) ? 1 : -1;\n    int x = coin_flip_evev(gen) ? 1 : -1;\n    output_dyck[i] = x;\n    height += x;\n\n    if(height < 0) {\n      // this should return a uniform random integer between 0 and x\n      //unsigned long random_int(unsigned long x);\n      std::uniform_int_distribution<> random_int(0, i);\n      long j = random_int(gen);\n      //long j = random_int(i);\n      height += unfold(p_ind + j,output_dyck, i + 1 - j);\n    }\n  }\n\n  // Rcout << \"Line 213. \\n\";\n\n\n  //fold(output_dyck, length + 1, height);\n  long local_height = 0;\n  int x = -1;\n  // Rcout << \"Line 121. \\n\";\n  // Rcout << \"output_dyck.size() =\" << output_dyck.size() << \". \\n\";\n  // Rcout << \"length - 1 =\" << length - 1 << \". \\n\";\n\n\n  for(long i = length; height > 0; i --) {\n    int y = output_dyck[i];\n    local_height -= y;\n    if(local_height < 0) {\n      y = -1;\n      height -= 2;\n      local_height = 0;\n    }\n    output_dyck[i] = x;\n    x = y;\n  }\n  // Rcout << \"Line 134. \\n\";\n\n\n  // Rcout << \"Line 217. \\n\";\n\n}\n\n\n\n//######################################################################################################################//\n// wrleast length + 1 bytes should be allocated first\n// [[Rcpp::deites a random Dyck path (length should be even)\n// at pends(RcppArmadillo)]]\n// [[Rcpp::depends(dqrng, BH, sitmo)]]\n\n#include <xoshiro.h>\n#include <dqrng_distribution.h>\n//#include <dqrng.h>\n\n//' @description Test draw of trees of given length\n//' @export\n// [[Rcpp::export]]\nIntegerVector wrapper_dyck_path(long length) {\n  //signed char *p;\n  //p=&output_dyck[0];\n  //int p_ind=0;\n  //Rcout << \"Line 235. \\n\";\n  //dyck_path(output_dyck,length);\n\n\n  //long height = dyck_prefix(p, length + 1);\n  //Rcout << \"Line 172. \\n\";\n\n  //std::vector<int> p(length);\n  //std::vector<char> p(length);\n  //char p;\n  //signed char p;// = new signed char[length];\n\n  static std::random_device device;\n  static std::mt19937 gen(device());\n\n  //possibly use seed?\n  //// std::mt19937 gen(seed);\n\n  //static dqrng::xoshiro256plus gen(device());              // properly seeded rng\n\n  //dqrng::xoshiro256plus gen(seed);              // properly seeded rng\n\n  std::bernoulli_distribution coin_flip_evev(0.5);\n\n\n  std::vector<int> output_dyck(length+1);\n  int p_ind=0;\n  long height = 0;\n\n  //Rcout << \"Line 195. \\n\";\n\n  for(long i = 0; i < length+1; i ++) {\n    //signed char x = random_int(1) ? 1 : -1;\n    int x = coin_flip_evev(gen) ? 1 : -1;\n    output_dyck[i] = x;\n    height += x;\n\n    if(height < 0) {\n      // this should return a uniform random integer between 0 and x\n      //unsigned long random_int(unsigned long x);\n      std::uniform_int_distribution<> random_int(0, i);\n      long j = random_int(gen);\n      //long j = random_int(i);\n      //height += unfold(p_ind + j,output_dyck, i + 1 - j);\n\n      long length1=i+1-j;\n      long height1 = 0;\n      long local_height = 0;\n      int x = 1;\n\n      for(long i = 0; i < length1; i ++) {\n        int y = output_dyck[p_ind+j+i];\n        local_height += y;\n        if(local_height < 0) {\n          y = 1;\n          height1 += 2;\n          local_height = 0;\n        }\n        output_dyck[p_ind+j+i] = x;\n        x = y;\n      }\n      height +=height1;\n\n\n\n\n    }\n  }\n\n  //Rcout << \"Line 213. \\n\";\n\n\n  //fold(output_dyck, length + 1, height);\n  long local_height = 0;\n  int x = -1;\n  //Rcout << \"Line 121. \\n\";\n  //Rcout << \"output_dyck.size() =\" << output_dyck.size() << \". \\n\";\n  //Rcout << \"length - 1 =\" << length - 1 << \". \\n\";\n\n\n  for(long i = length; height > 0; i --) {\n    int y = output_dyck[i];\n    local_height -= y;\n    if(local_height < 0) {\n      y = -1;\n      height -= 2;\n      local_height = 0;\n    }\n    output_dyck[i] = x;\n    x = y;\n  }\n  //Rcout << \"Line 134. \\n\";\n\n\n  //Rcout << \"Line 217. \\n\";\n\n  //Rcout << \"Line 238. \\n\";\n  std::replace (output_dyck.begin(), output_dyck.end(), -1, 0); // 10 99 30 30 99 10 10 99\n\n  return(wrap(output_dyck));\n\n}\n//######################################################################################################################//\n\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::export]]\n\nNumericVector find_term_nodes(NumericMatrix tree_table){\n  arma::mat arma_tree(tree_table.begin(),tree_table.nrow(), tree_table.ncol(), false);\n\n  //arma::vec colmat=arma_tree.col(4);\n  //arma::uvec term_nodes=arma::find(colmat==-1);\n\n  //arma::vec colmat=arma_tree.col(2);\n  //arma::uvec term_nodes=arma::find(colmat==0);\n\n  arma::vec colmat=arma_tree.col(4);\n  arma::uvec term_nodes=arma::find(colmat==0);\n\n  term_nodes=term_nodes+1;\n\n  return(wrap(term_nodes));\n}\n\n//######################################################################################################################//\n\n#include <math.h>       /* tgamma */\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::export]]\n\nList get_treepreds(NumericVector original_y, int num_cats, NumericVector alpha_pars,\n                   NumericMatrix originaldata, //NumericMatrix test_data,\n                   NumericMatrix treetable//, NumericMatrix tree_data\n) {\n  // Function to make predictions from test data, given a single tree and the terminal node predictions, this function will be called\n  //for each tree accepted in Occam's Window.\n\n  //test_data is a nxp matrix with the same variable names as the training data the model was built on\n\n  //tree_data is the tree table with the tree information i.e. split points and split variables and terminal node mean values\n\n  //term_node_means is a vector storing the terminal node mean values\n  arma::vec orig_y_arma= as<arma::vec>(original_y);\n  arma::vec alpha_pars_arma= as<arma::vec>(alpha_pars);\n\n  double lik_prod=1;\n  double alph_prod=1;\n  for(unsigned int i=0; i<alpha_pars_arma.n_elem;i++){\n    alph_prod=alph_prod*tgamma(alpha_pars_arma(i));\n  }\n  double gam_alph_sum= tgamma(arma::sum(alpha_pars_arma));\n  double alph_term=gam_alph_sum/alph_prod;\n\n  arma::mat arma_tree_table(treetable.begin(), treetable.nrow(), treetable.ncol(), false);\n  arma::mat arma_orig_data(originaldata.begin(), originaldata.nrow(), originaldata.ncol(), false);\n\n\n  //arma::mat arma_tree(tree_data.begin(), tree_data.nrow(), tree_data.ncol(), false);\n  //arma::mat testd(test_data.begin(), test_data.nrow(), test_data.ncol(), false);\n\n  //NumericVector internal_nodes=find_internal_nodes_gs(tree_data);\n\n  NumericVector terminal_nodes=find_term_nodes(treetable);\n  //arma::vec arma_terminal_nodes=Rcpp::as<arma::vec>(terminal_nodes);\n  //NumericVector tree_predictions;\n\n  //now for each internal node find the observations that belong to the terminal nodes\n\n  //NumericVector predictions(test_data.nrow());\n  //List term_obs(terminal_nodes.size());\n\n  if(terminal_nodes.size()==1){\n    //double nodemean=tree_data(terminal_nodes[0]-1,5);\t\t\t\t// let nodemean equal tree_data row terminal_nodes[i]^th row , 6th column. The minus 1 is because terminal nodes consists of indices starting at 1, but need indices to start at 0.\n    //predictions=rep(nodemean,test_data.nrow());\n    //Rcout << \"Line 67 .\\n\";\n\n    //IntegerVector temp_obsvec = seq_len(test_data.nrow())-1;\n    //term_obs[0]= temp_obsvec;\n    double denom_temp= orig_y_arma.n_elem+arma::sum(alpha_pars_arma);\n\n    double num_prod=1;\n    double num_sum=0;\n    //Rcout << \"Line 129.\\n\";\n\n    for(int k=0; k<num_cats; k++){\n      //assuming categories of y are from 1 to num_cats\n      arma::uvec cat_inds= arma::find(orig_y_arma==k+1);\n      double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n      arma_tree_table(0,5+k)= m_plus_alph/denom_temp ;\n\n      //for likelihood calculation\n      num_prod=num_prod*tgamma(m_plus_alph);\n      num_sum=num_sum +m_plus_alph ;\n    }\n\n    lik_prod= alph_term*num_prod/tgamma(num_sum);\n\n  }\n  else{\n    for(int i=0;i<terminal_nodes.size();i++){\n      //arma::mat subdata=testd;\n      int curr_term=terminal_nodes[i];\n\n      int row_index;\n      int term_node=terminal_nodes[i];\n      //Rcout << \"Line 152.\\n\";\n\n\n      //WHAT IS THE PURPOSE OF THIS IF-STATEMENT?\n      //Why should the ro index be different for a right daughter?\n      //Why not just initialize row_index to any number not equal to 1 (e.g. 0)?\n      row_index=0;\n\n      // if(curr_term % 2==0){\n      //   //term node is left daughter\n      //   row_index=terminal_nodes[i];\n      // }else{\n      //   //term node is right daughter\n      //   row_index=terminal_nodes[i]-1;\n      // }\n\n\n\n\n      //save the left and right node data into arma uvec\n\n      //CHECK THAT THIS REFERS TO THE CORRECT COLUMNS\n      //arma::vec left_nodes=arma_tree.col(0);\n      //arma::vec right_nodes=arma_tree.col(1);\n\n      arma::vec left_nodes=arma_tree_table.col(0);\n      arma::vec right_nodes=arma_tree_table.col(1);\n\n\n\n      arma::mat node_split_mat;\n      node_split_mat.set_size(0,3);\n      //Rcout << \"Line 182. i = \" << i << \" .\\n\";\n\n      while(row_index!=1){\n        //for each terminal node work backwards and see if the parent node was a left or right node\n        //append split info to a matrix\n        int rd=0;\n        arma::uvec parent_node=arma::find(left_nodes == term_node);\n\n        if(parent_node.size()==0){\n          parent_node=arma::find(right_nodes == term_node);\n          rd=1;\n        }\n\n        //want to cout parent node and append to node_split_mat\n\n        node_split_mat.insert_rows(0,1);\n\n        //CHECK THAT COLUMNS OF TREETABLE ARE CORRECT\n        //node_split_mat(0,0)=treetable(parent_node[0],2);\n        //node_split_mat(0,1)=treetable(parent_node[0],3);\n\n        //node_split_mat(0,0)=arma_tree_table(parent_node[0],3);\n        //node_split_mat(0,1)=arma_tree_table(parent_node[0],4);\n\n        node_split_mat(0,0)=arma_tree_table(parent_node[0],2);\n        node_split_mat(0,1)=arma_tree_table(parent_node[0],3);\n\n        node_split_mat(0,2)=rd;\n        row_index=parent_node[0]+1;\n        term_node=parent_node[0]+1;\n      }\n\n      //once we have the split info, loop through rows and find the subset indexes for that terminal node!\n      //then fill in the predicted value for that tree\n      //double prediction = tree_data(term_node,5);\n      arma::uvec pred_indices;\n      int split= node_split_mat(0,0)-1;\n\n      //Rcout << \"Line 224.\\n\";\n      //Rcout << \"split = \" << split << \".\\n\";\n      //arma::vec tempvec = testd.col(split);\n      arma::vec tempvec = arma_orig_data.col(split);\n      //Rcout << \"Line 227.\\n\";\n\n\n      double temp_split = node_split_mat(0,1);\n\n      if(node_split_mat(0,2)==0){\n        pred_indices = arma::find(tempvec <= temp_split);\n      }else{\n        pred_indices = arma::find(tempvec > temp_split);\n      }\n      //Rcout << \"Line 236.\\n\";\n\n      arma::uvec temp_pred_indices;\n\n      //arma::vec data_subset = testd.col(split);\n      arma::vec data_subset = arma_orig_data.col(split);\n\n      data_subset=data_subset.elem(pred_indices);\n\n      //now loop through each row of node_split_mat\n      int n=node_split_mat.n_rows;\n      //Rcout << \"Line 174. i = \" << i << \". n = \" << n << \".\\n\";\n      //Rcout << \"Line 248.\\n\";\n\n      for(int j=1;j<n;j++){\n        int curr_sv=node_split_mat(j,0);\n        double split_p = node_split_mat(j,1);\n\n        //data_subset = testd.col(curr_sv-1);\n        //Rcout << \"Line 255.\\n\";\n        //Rcout << \"curr_sv = \" << curr_sv << \".\\n\";\n        data_subset = arma_orig_data.col(curr_sv-1);\n        //Rcout << \"Line 258.\\n\";\n\n        data_subset=data_subset.elem(pred_indices);\n\n        if(node_split_mat(j,2)==0){\n          //split is to the left\n          temp_pred_indices=arma::find(data_subset <= split_p);\n        }else{\n          //split is to the right\n          temp_pred_indices=arma::find(data_subset > split_p);\n        }\n        pred_indices=pred_indices.elem(temp_pred_indices);\n\n        if(pred_indices.size()==0){\n          continue;\n        }\n\n      }\n      //Rcout << \"Line 199. i = \" << i <<  \".\\n\";\n\n      //double nodemean=tree_data(terminal_nodes[i]-1,5);\n      //IntegerVector predind=as<IntegerVector>(wrap(pred_indices));\n      //predictions[predind]= nodemean;\n      //term_obs[i]=predind;\n\n      double denom_temp= pred_indices.n_elem+arma::sum(alpha_pars_arma);\n      //Rcout << \"Line 207. predind = \" << predind <<  \".\\n\";\n      //Rcout << \"Line 207. denom_temp = \" << denom_temp <<  \".\\n\";\n      // << \"Line 207. term_node = \" << term_node <<  \".\\n\";\n\n      double num_prod=1;\n      double num_sum=0;\n\n      for(int k=0; k<num_cats; k++){\n        //assuming categories of y are from 1 to num_cats\n        arma::uvec cat_inds= arma::find(orig_y_arma(pred_indices)==k+1);\n        double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n\n        arma_tree_table(curr_term-1,5+k)= m_plus_alph/denom_temp ;\n\n        num_prod=num_prod*tgamma(m_plus_alph);\n        num_sum=num_sum +m_plus_alph ;\n      }\n\n\n      lik_prod= lik_prod*alph_term*num_prod/tgamma(num_sum);\n      //Rcout << \"Line 297.\\n\";\n\n\n    }\n    //Rcout << \"Line 301.\\n\";\n\n  }\n  //List ret(1);\n  //ret[0] = term_obs;\n\n  //ret[0] = terminal_nodes;\n  //ret[1] = term_obs;\n  //ret[2] = predictions;\n  //return(term_obs);\n  //Rcout << \"Line 309\";\n\n  //return(wrap(arma_tree_table));\n\n  List ret(2);\n  ret[0]=wrap(arma_tree_table);\n  ret[1]=lik_prod;\n\n  return(ret);\n\n}\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n// [[Rcpp::depends(RcppArmadillo)]]\n//' @title For a set of trees, obtain tree matrices with predictions, and obtain model weights\n//' @export\n// [[Rcpp::export]]\nList get_treelist(NumericVector original_y, int num_cats, NumericVector alpha_pars,\n                  double beta_pow,\n                  NumericMatrix originaldata, //NumericMatrix test_data,\n                  List treetable_list//, NumericMatrix tree_data\n){\n\n  //List overall_term_nodes_trees(overall_sum_trees.size());\n  //List overall_term_obs_trees(overall_sum_trees.size());\n  //List overall_predictions(overall_sum_trees.size());\n\n  List overall_treetables(treetable_list.size());\n  NumericVector overall_liks(treetable_list.size());\n\n  for(int i=0;i<treetable_list.size();i++){\n    //for each set of trees loop over individual trees\n    SEXP s = treetable_list[i];\n\n    //NumericVector test_preds_sum_tree;\n    if(is<List>(s)){\n      //if current set of trees contains more than one tree...usually does!\n      //List sum_tree=treetable_list[i];\n\n      //save all info in list of list format the same as the trees.\n      //List term_nodes_trees(sum_tree.size());\n      //List term_obs_trees(sum_tree.size());\n      //NumericMatrix predictions(num_obs,sum_tree.size());\n\n      // for(int k=0;k<sum_tree.size();k++){\n      //   NumericMatrix tree_table=sum_tree[k];\n      //   List tree_info=get_termobs_test_data(test_data, tree_table) ;\n      //   //NumericVector term_nodes=tree_info[0];\n      //   //term_nodes_trees[k]=term_nodes;\n      //   term_obs_trees[k]=tree_info;\n      //   //umericVector term_preds=tree_info[2];\n      //   //predictions(_,k)=term_preds;\n      // }\n\n\n      List treepred_output = get_treepreds(original_y, num_cats, alpha_pars,\n                                           originaldata,\n                                           treetable_list[i]  );\n\n      overall_treetables[i]= treepred_output[0];\n      double templik = as<double>(treepred_output[1]);\n      overall_liks[i]= pow(templik,beta_pow);\n\n\n\n      //overall_term_nodes_trees[i]=term_nodes_trees;\n      //overall_term_obs_trees[i]= term_obs_trees;\n      //overall_predictions[i]=predictions;\n    }else{\n      // NumericMatrix sum_tree=overall_sum_trees[i];\n      // List tree_info=get_termobs_test_data(test_data, sum_tree) ;\n      // //overall_term_nodes_trees[i]=tree_info[0];\n      // List term_obs_trees(1);\n      // term_obs_trees[0]=tree_info ;\n      // //NumericVector term_preds=tree_info[2];\n      // //NumericVector predictions=term_preds;\n      // overall_term_obs_trees[i]= term_obs_trees;\n      // //overall_predictions[i]=predictions;\n      //\n\n      //overall_treetables[i]=get_treepreds(original_y, num_cats, alpha_pars,\n      //                                    originaldata,\n      //                                    treetable_list[i]  );\n\n\n      List treepred_output = get_treepreds(original_y, num_cats, alpha_pars,\n                                           originaldata,\n                                           treetable_list[i]  );\n\n      overall_treetables[i]= treepred_output[0];\n      double templik = as<double>(treepred_output[1]);\n      overall_liks[i]= pow(templik,beta_pow);\n\n    }\n  }\n  //List ret(1);\n  //ret[0]=overall_term_nodes_trees;\n  //ret[0]=overall_term_obs_trees;\n  //ret[2]=overall_predictions;\n  //return(overall_term_obs_trees);\n\n  //return(overall_treetables);\n\n  overall_liks=overall_liks/sum(overall_liks);\n\n  List ret(2);\n  ret[0]=overall_treetables;\n  ret[1]=overall_liks;\n  return(ret);\n\n\n\n}\n//######################################################################################################################//\n\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::export]]\n\narma::mat get_test_probs(NumericVector weights, int num_cats,\n                         NumericMatrix testdata, //NumericMatrix test_data,\n                         NumericMatrix treetable//, NumericMatrix tree_data\n) {\n  // Function to make predictions from test data, given a single tree and the terminal node predictions, this function will be called\n  //for each tree accepted in Occam's Window.\n\n  //test_data is a nxp matrix with the same variable names as the training data the model was built on\n\n  //tree_data is the tree table with the tree information i.e. split points and split variables and terminal node mean values\n\n  //term_node_means is a vector storing the terminal node mean values\n  // arma::vec orig_y_arma= as<arma::vec>(original_y);\n  // arma::vec alpha_pars_arma= as<arma::vec>(alpha_pars);\n  //\n  // double lik_prod=1;\n  // double alph_prod=1;\n  // for(unsigned int i=0; i<alpha_pars_arma.n_elem;i++){\n  //   alph_prod=alph_prod*tgamma(alpha_pars_arma(i));\n  // }\n  // double gam_alph_sum= tgamma(arma::sum(alpha_pars_arma));\n  // double alph_term=gam_alph_sum/alph_prod;\n\n  arma::mat arma_tree_table(treetable.begin(), treetable.nrow(), treetable.ncol(), false);\n  arma::mat arma_test_data(testdata.begin(), testdata.nrow(), testdata.ncol(), false);\n\n\n  //arma::mat arma_tree(tree_data.begin(), tree_data.nrow(), tree_data.ncol(), false);\n  //arma::mat testd(test_data.begin(), test_data.nrow(), test_data.ncol(), false);\n\n  //NumericVector internal_nodes=find_internal_nodes_gs(tree_data);\n\n  NumericVector terminal_nodes=find_term_nodes(treetable);\n  //arma::vec arma_terminal_nodes=Rcpp::as<arma::vec>(terminal_nodes);\n  //NumericVector tree_predictions;\n\n  //now for each internal node find the observations that belong to the terminal nodes\n\n  //NumericVector predictions(test_data.nrow());\n\n  arma::mat pred_mat(testdata.nrow(),num_cats);\n  //arma::vec filled_in(testdata.nrow());\n\n\n  //List term_obs(terminal_nodes.size());\n  if(terminal_nodes.size()==1){\n\n    //Rcout << \"Line 422. \\n\";\n\n\n    pred_mat=repmat(arma_tree_table(0,arma::span(5,5+num_cats-1)),testdata.nrow(),1);\n\n\n    //Rcout << \"Line 424. \\n\";\n\n\n    // for(int k=0; k<num_cats; k++){\n    // pred_mat(_,k)=rep(treetable(0,5+k),testdata.nrow());\n    // }\n    //double nodemean=tree_data(terminal_nodes[0]-1,5);\t\t\t\t// let nodemean equal tree_data row terminal_nodes[i]^th row , 6th column. The minus 1 is because terminal nodes consists of indices starting at 1, but need indices to start at 0.\n    //predictions=rep(nodemean,test_data.nrow());\n    //Rcout << \"Line 67 .\\n\";\n\n    //IntegerVector temp_obsvec = seq_len(test_data.nrow())-1;\n    //term_obs[0]= temp_obsvec;\n    // double denom_temp= orig_y_arma.n_elem+arma::sum(alpha_pars_arma);\n    //\n    // double num_prod=1;\n    // double num_sum=0;\n\n    // for(int k=0; k<num_cats; k++){\n    //   //assuming categories of y are from 1 to num_cats\n    //   arma::uvec cat_inds= arma::find(orig_y_arma==k+1);\n    //   double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n    //   arma_tree_table(0,5+k)= m_plus_alph/denom_temp ;\n    //\n    //   //for likelihood calculation\n    //   num_prod=num_prod*tgamma(m_plus_alph);\n    //   num_sum=num_sum +m_plus_alph ;\n    // }\n    //\n    // lik_prod= alph_term*num_prod/tgamma(num_sum);\n    //\n  }\n  else{\n    for(int i=0;i<terminal_nodes.size();i++){\n      //arma::mat subdata=testd;\n      int curr_term=terminal_nodes[i];\n\n      int row_index;\n      int term_node=terminal_nodes[i];\n\n\n      //WHAT IS THE PURPOSE OF THIS IF-STATEMENT?\n      //Why should the ro index be different for a right daughter?\n      //Why not just initialize row_index to any number not equal to 1 (e.g. 0)?\n      row_index=0;\n\n      // if(curr_term % 2==0){\n      //   //term node is left daughter\n      //   row_index=terminal_nodes[i];\n      // }else{\n      //   //term node is right daughter\n      //   row_index=terminal_nodes[i]-1;\n      // }\n\n\n\n\n\n\n\n\n      //save the left and right node data into arma uvec\n\n      //CHECK THAT THIS REFERS TO THE CORRECT COLUMNS\n      //arma::vec left_nodes=arma_tree.col(0);\n      //arma::vec right_nodes=arma_tree.col(1);\n\n      arma::vec left_nodes=arma_tree_table.col(0);\n      arma::vec right_nodes=arma_tree_table.col(1);\n\n\n\n      arma::mat node_split_mat;\n      node_split_mat.set_size(0,3);\n      //Rcout << \"Line 124. i = \" << i << \" .\\n\";\n\n      while(row_index!=1){\n        //for each terminal node work backwards and see if the parent node was a left or right node\n        //append split info to a matrix\n        int rd=0;\n        arma::uvec parent_node=arma::find(left_nodes == term_node);\n\n        if(parent_node.size()==0){\n          parent_node=arma::find(right_nodes == term_node);\n          rd=1;\n        }\n\n        //want to cout parent node and append to node_split_mat\n\n        node_split_mat.insert_rows(0,1);\n\n        //CHECK THAT COLUMNS OF TREETABLE ARE CORRECT\n        //node_split_mat(0,0)=treetable(parent_node[0],2);\n        //node_split_mat(0,1)=treetable(parent_node[0],3);\n\n        //node_split_mat(0,0)=arma_tree_table(parent_node[0],3);\n        //node_split_mat(0,1)=arma_tree_table(parent_node[0],4);\n\n        node_split_mat(0,0)=arma_tree_table(parent_node[0],2);\n        node_split_mat(0,1)=arma_tree_table(parent_node[0],3);\n\n        node_split_mat(0,2)=rd;\n        row_index=parent_node[0]+1;\n        term_node=parent_node[0]+1;\n      }\n\n      //once we have the split info, loop through rows and find the subset indexes for that terminal node!\n      //then fill in the predicted value for that tree\n      //double prediction = tree_data(term_node,5);\n      arma::uvec pred_indices;\n      int split= node_split_mat(0,0)-1;\n\n      //arma::vec tempvec = testd.col(split);\n      arma::vec tempvec = arma_test_data.col(split);\n\n\n      double temp_split = node_split_mat(0,1);\n\n      if(node_split_mat(0,2)==0){\n        pred_indices = arma::find(tempvec <= temp_split);\n      }else{\n        pred_indices = arma::find(tempvec > temp_split);\n      }\n\n      arma::uvec temp_pred_indices;\n\n      //arma::vec data_subset = testd.col(split);\n      arma::vec data_subset = arma_test_data.col(split);\n\n      data_subset=data_subset.elem(pred_indices);\n\n      //now loop through each row of node_split_mat\n      int n=node_split_mat.n_rows;\n      //Rcout << \"Line 174. i = \" << i << \". n = \" << n << \".\\n\";\n      //Rcout << \"Line 174. node_split_mat= \" << node_split_mat << \". n = \" << n << \".\\n\";\n\n\n      for(int j=1;j<n;j++){\n        int curr_sv=node_split_mat(j,0);\n        double split_p = node_split_mat(j,1);\n\n        //data_subset = testd.col(curr_sv-1);\n        data_subset = arma_test_data.col(curr_sv-1);\n\n        data_subset=data_subset.elem(pred_indices);\n\n        if(node_split_mat(j,2)==0){\n          //split is to the left\n          temp_pred_indices=arma::find(data_subset <= split_p);\n        }else{\n          //split is to the right\n          temp_pred_indices=arma::find(data_subset > split_p);\n        }\n        pred_indices=pred_indices.elem(temp_pred_indices);\n\n        if(pred_indices.size()==0){\n          continue;\n        }\n\n      }\n      //Rcout << \"Line 199. i = \" << i <<  \".\\n\";\n\n      //double nodemean=tree_data(terminal_nodes[i]-1,5);\n      //IntegerVector predind=as<IntegerVector>(wrap(pred_indices));\n      //predictions[predind]= nodemean;\n      //term_obs[i]=predind;\n\n      //Rcout << \"Line 635. \\n\";\n      //Rcout << \"pred_indices = \" << pred_indices << \".\\n\";\n\n      //pred_mat.rows(pred_indices)=arma::repmat(arma_tree_table(curr_term-1,arma::span(5,5+num_cats-1)),pred_indices.n_elem,1);\n      pred_mat.each_row(pred_indices)=arma_tree_table(curr_term-1,arma::span(5,4+num_cats));\n\n\n\n      //Rcout << \"Line 588. \\n\";\n\n      // for(int k=0; k<num_cats; k++){\n      //   pred_mat(predind,k)=rep(treetable(curr_term-1,5+k),predind.size());\n      // }\n\n\n      // double denom_temp= pred_indices.n_elem+arma::sum(alpha_pars_arma);\n      // //Rcout << \"Line 207. predind = \" << predind <<  \".\\n\";\n      // //Rcout << \"Line 207. denom_temp = \" << denom_temp <<  \".\\n\";\n      // // << \"Line 207. term_node = \" << term_node <<  \".\\n\";\n      //\n      // double num_prod=1;\n      // double num_sum=0;\n      //\n      // for(int k=0; k<num_cats; k++){\n      //   //assuming categories of y are from 1 to num_cats\n      //   arma::uvec cat_inds= arma::find(orig_y_arma(pred_indices)==k+1);\n      //   double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n      //\n      //   arma_tree_table(curr_term-1,5+k)= m_plus_alph/denom_temp ;\n      //\n      //   num_prod=num_prod*tgamma(m_plus_alph);\n      //   num_sum=num_sum +m_plus_alph ;\n      // }\n\n\n      //lik_prod= lik_prod*alph_term*num_prod/tgamma(num_sum);\n\n\n    }\n  }\n  //List ret(1);\n  //ret[0] = term_obs;\n\n  //ret[0] = terminal_nodes;\n  //ret[1] = term_obs;\n  //ret[2] = predictions;\n  //return(term_obs);\n\n  //return(wrap(arma_tree_table));\n\n  //List ret(2);\n  //ret[0]=wrap(arma_tree_table);\n  //ret[1]=lik_prod;\n\n  return(pred_mat);\n\n}\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n// [[Rcpp::depends(RcppArmadillo)]]\n//' @title Given tree tables and model weights, obtain predicted probabilities for test data.\n//' @export\n// [[Rcpp::export]]\n\nNumericMatrix get_test_prob_overall(NumericVector weights, int num_cats,\n                                    NumericMatrix testdata, //NumericMatrix test_data,\n                                    List treetable_list//, NumericMatrix tree_data\n){\n\n  //List overall_term_nodes_trees(overall_sum_trees.size());\n  //List overall_term_obs_trees(overall_sum_trees.size());\n  //List overall_predictions(overall_sum_trees.size());\n\n  List overall_treetables(treetable_list.size());\n  NumericVector overall_liks(treetable_list.size());\n\n\n  arma::mat pred_mat_overall=arma::zeros<arma::mat>(testdata.nrow(),num_cats);\n\n\n  for(int i=0;i<treetable_list.size();i++){\n    //for each set of trees loop over individual trees\n    SEXP s = treetable_list[i];\n\n    //NumericVector test_preds_sum_tree;\n    if(is<List>(s)){\n      //if current set of trees contains more than one tree...usually does!\n      //List sum_tree=treetable_list[i];\n\n      //save all info in list of list format the same as the trees.\n      //List term_nodes_trees(sum_tree.size());\n      //List term_obs_trees(sum_tree.size());\n      //NumericMatrix predictions(num_obs,sum_tree.size());\n\n      // for(int k=0;k<sum_tree.size();k++){\n      //   NumericMatrix tree_table=sum_tree[k];\n      //   List tree_info=get_termobs_test_data(test_data, tree_table) ;\n      //   //NumericVector term_nodes=tree_info[0];\n      //   //term_nodes_trees[k]=term_nodes;\n      //   term_obs_trees[k]=tree_info;\n      //   //umericVector term_preds=tree_info[2];\n      //   //predictions(_,k)=term_preds;\n      // }\n\n      //Rcout << \"Line 682. i== \" << i << \". \\n\";\n\n      arma::mat treeprob_output = get_test_probs(weights, num_cats,\n                                                 testdata,\n                                                 treetable_list[i]  );\n\n      //Rcout << \"Line 688. i== \" << i << \". \\n\";\n\n      double weighttemp = weights[i];\n      //Rcout << \"Line 691. i== \" << i << \". \\n\";\n\n      pred_mat_overall = pred_mat_overall + weighttemp*treeprob_output;\n      //Rcout << \"Line 694. i== \" << i << \". \\n\";\n\n\n      //overall_treetables[i]= treepred_output[0];\n      //double templik = as<double>(treepred_output[1]);\n      //overall_liks[i]= pow(templik,beta_pow);\n\n\n\n      //overall_term_nodes_trees[i]=term_nodes_trees;\n      //overall_term_obs_trees[i]= term_obs_trees;\n      //overall_predictions[i]=predictions;\n    }else{\n      // NumericMatrix sum_tree=overall_sum_trees[i];\n      // List tree_info=get_termobs_test_data(test_data, sum_tree) ;\n      // //overall_term_nodes_trees[i]=tree_info[0];\n      // List term_obs_trees(1);\n      // term_obs_trees[0]=tree_info ;\n      // //NumericVector term_preds=tree_info[2];\n      // //NumericVector predictions=term_preds;\n      // overall_term_obs_trees[i]= term_obs_trees;\n      // //overall_predictions[i]=predictions;\n      //\n\n      //overall_treetables[i]=get_treepreds(original_y, num_cats, alpha_pars,\n      //                                    originaldata,\n      //                                    treetable_list[i]  );\n\n\n      // List treepred_output = get_treepreds(original_y, num_cats, alpha_pars,\n      //                                      originaldata,\n      //                                      treetable_list[i]  );\n      //\n      // overall_treetables[i]= treepred_output[0];\n      // double templik = as<double>(treepred_output[1]);\n      // overall_liks[i]= pow(templik,beta_pow);\n\n\n      //Rcout << \"Line 732. i== \" << i << \". \\n\";\n\n      arma::mat treeprob_output = get_test_probs(weights, num_cats,\n                                                 testdata,\n                                                 treetable_list[i]  );\n\n      //Rcout << \"Line 738. i== \" << i << \". \\n\";\n\n      double weighttemp = weights[i];\n      //Rcout << \"Line 741. i== \" << i << \". \\n\";\n      //Rcout << \"treeprob_output.n_rows\" << treeprob_output.n_rows << \".\\n\";\n      //Rcout << \"treeprob_output.n_cols\" << treeprob_output.n_cols << \".\\n\";\n\n\n      pred_mat_overall = pred_mat_overall + weighttemp*treeprob_output;\n      //Rcout << \"Line 744. i== \" << i << \". \\n\";\n      //Rcout << \"pred_mat_overall \" << pred_mat_overall << \". \\n\";\n\n    }\n  }\n  //List ret(1);\n  //ret[0]=overall_term_nodes_trees;\n  //ret[0]=overall_term_obs_trees;\n  //ret[2]=overall_predictions;\n  //return(overall_term_obs_trees);\n\n  //return(overall_treetables);\n\n  // overall_liks=overall_liks/sum(overall_liks);\n  //\n  // List ret(2);\n  // ret[0]=overall_treetables;\n  // ret[1]=overall_liks;\n  // return(ret);\n\n  return(wrap(pred_mat_overall));\n\n}\n//######################################################################################################################//\n\n// [[Rcpp::depends(RcppArmadillo)]]\n//// [[Rcpp::depends(dqrng)]]\n//// [[Rcpp::depends(BH)]]\n//// [[Rcpp::depends(dqrng, BH, RcppArmadillo)]]\n\n#include <RcppArmadilloExtensions/sample.h>\n\n//#include <dqrng.h>\n\n//#include <boost/random/binomial_distribution.hpp>\n//using binomial = boost::random::binomial_distribution<int>;\n//' @title Draw a set of trees from the prior.\n//' @export\n// [[Rcpp::export]]\nList draw_trees(double lambda, int num_trees, int seed, int num_split_vars, int num_cats ){\n\n  //dqrng::dqRNGkind(\"Xoroshiro128+\");\n  //dqrng::dqset_seed(IntegerVector::create(seed));\n\n  //use following with binomial?\n  //dqrng::xoshiro256plus rng(seed);\n\n  //std::vector<int> lambdavec = {lambda, 1-lambda};\n\n  //typedef boost::mt19937 RNGType;\n  //boost::random::uniform_int_distribution<> sample_splitvardist(1,num_split_vars);\n  //boost::variate_generator< RNGType, boost::uniform_int<> >  sample_splitvars(rng, sample_splitvardist);\n\n  //boost::random::uniform_real_distribution<double> b_unifdist(0,1);\n  //boost::variate_generator< RNGType, boost::uniform_real<> >  b_unif_point(rng, b_unifdist);\n\n\n\n  // std::random_device device;\n  // std::mt19937 gen(device());\n\n  //possibly use seed?\n  //// std::mt19937 gen(seed);\n\n\n  // std::bernoulli_distribution coin_flip(lambda);\n\n  // std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n  //std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n\n\n  List table_list(num_trees);\n\n\n\n\n  for(int j=0; j<num_trees;j++){\n\n    //If parallelizing, define the distributinos before this loop\n    //and use lrng and the following two lines\n    //dqrng::xoshiro256plus lrng(rng);      // make thread local copy of rng\n    //lrng.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... nthreads jumps\n\n\n    //NumericVector treenodes_bin(0);\n    //arma::uvec treenodes_bin(0);\n\n    std::vector<int> treenodes_bin;\n    //std::vector<int> split_var_vec;\n\n\n    int count_terminals = 0;\n    int count_internals = 0;\n\n    //int count_treebuild = 0;\n\n    while(count_internals > (count_terminals -1)){\n\n      //Also consider standard library and random header\n      // std::random_device device;\n      // std::mt19937 gen(device());\n      // std::bernoulli_distribution coin_flip(lambda);\n      // bool outcome = coin_flip(gen);\n\n\n      //int tempdraw = coin_flip(gen);\n\n      //int tempdraw = rbinom(n = 1, prob = lambda,size=1);\n\n\n      //int tempdraw = Rcpp::rbinom(1,lambda,1);\n      int tempdraw = R::rbinom(1,lambda);\n      treenodes_bin.push_back(tempdraw);\n\n      //Rcout << \"tempdraw = \" << tempdraw << \".\\n\" ;\n\n      //int tempdraw = dqrng::dqsample_int(2, 1, true,lambdavec )-1;\n      //need to update rng if use boost?\n      //int tempdraw = bernoulli(rng, binomial::param_type(1, lambda));\n      if(tempdraw==1){\n        count_internals=count_internals+1;\n      }else{\n        count_terminals=count_terminals+1;\n      }\n\n    }//end of while loop creating parent vector treenodes_bin\n\n    //Consider making this an armadillo vector\n    //IntegerVector split_var_vec(treenodes_bin.size());\n    //arma::uvec split_var_vec(treenodes_bin.size());\n    std::vector<int> split_var_vec(treenodes_bin.size());\n    //std::vector<int> split_var_vectemp(treenodes_bin.size());\n    //split_var_vec.reserve(treenodes_bin.size());\n\n    //loop drawing splitting variables\n    //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n    //if using armadillo, it might be faster to subset to split nodes\n    //then use a vector of draws\n    for(unsigned int i=0; i<treenodes_bin.size();i++){\n      if(treenodes_bin[i]==0){\n        split_var_vec[i]=-1;\n      }else{\n        // also consider the standard library function uniform_int_distribution\n        // might need random header\n        // This uses the Mersenne twister\n\n        //Three lines below should probably be outside all the loops\n        // std::random_device rd;\n        // std::mt19937 engine(rd());\n        // std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n        //\n        // split_var_vec[i] <- distsampvar(engine);\n\n        // split_var_vec[i] <- distsampvar(gen);\n\n\n        //consider using boost\n        //might need to update rng\n        //split_var_vec[i] <- sample_splitvars(rng);\n\n        //or use dqrng\n        //not sure if have to update the random number\n        //check if the following line is written properly\n        //split_var_vec[i] = dqrng::dqsample_int(num_split_vars, 1, true);\n\n        //not sure if this returns an integer or a vector?\n        //split_var_vec[i] = RcppArmadillo::sample(num_split_vars, 1,true);\n        //could try\n        split_var_vec[i] = as<int>(Rcpp::sample(num_split_vars, 1,true));\n\n        //split_var_vec.push_back(as<int>(Rcpp::sample(num_split_vars, 1,true)));\n        //could also try RcppArmadillo::rmultinom\n\n      }\n\n    }// end of for-loop drawing split variables\n\n    //split_var_vec=split_var_vectemp;\n\n    //Consider making this an armadillo vector\n    //NumericVector split_point_vec(treenodes_bin.size());\n    //arma::vec split_point_vec(treenodes_bin.size());\n    std::vector<double> split_point_vec(treenodes_bin.size());\n\n\n    //loop drawing splitting points\n    //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n    //if using armadillo, it might be faster to subset to split nodes\n    //then use a vector of draws\n    for(unsigned int i=0; i<treenodes_bin.size();i++){\n      if(treenodes_bin[i]==0){\n        split_point_vec[i] = -1;\n      }else{\n\n\n        //////////////////////////////////////////////////////////\n        //following function not reccommended\n        //split_point_vec[i] = std::rand();\n        //////////////////////////////////////////////////////////\n        ////Standard library:\n        ////This should probably be outside all the loops\n        ////std::random_device rd;  //Will be used to obtain a seed for the random number engine\n        ////std::mt19937 gen2(rd()); //Standard mersenne_twister_engine seeded with rd()\n        ////std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n        // split_point_vec[i] = dis_cont_unif(gen);\n\n        //////////////////////////////////////////////////////////\n        //from armadillo\n        split_point_vec[i] = arma::randu();\n\n        //////////////////////////////////////////////////////////\n        //probably not adviseable for paralelization\n        //From Rcpp\n        split_point_vec[i] = as<double>(Rcpp::runif(1,0,1));\n\n        //////////////////////////////////////////////////////////\n        //consider using boost\n        //might need to update rng\n        //split_point_vec[i] <- b_unif_point(rng);\n\n        //or use dqrng\n        //not sure if have to update the random number\n        //check if the following line is written properly\n        //split_point_vec[i] = dqrng::dqrunif(1, 0, 1);\n\n        //not sure if this returns an integer or a vector?\n\n\n\n\n\n      }\n\n    }// end of for-loop drawing split points\n\n\n    //Create tree table matrix\n\n    //NumericMatrix tree_table1(treenodes_bin.size(),5+num_cats);\n\n    //Rcout << \"Line 1037. \\n\";\n    //arma::mat tree_table1(treenodes_bin.size(),5+num_cats);\n\n    //initialize with zeros. Not sure if this is necessary\n    arma::mat tree_table1=arma::zeros<arma::mat>(treenodes_bin.size(),5+num_cats);\n    //Rcout << \"Line 1040. \\n\";\n\n\n    //tree_table1(_,2) = wrap(split_var_vec);\n    //tree_table1(_,3) = wrap(split_point_vec);\n    //tree_table1(_,4) = wrap(treenodes_bin);\n\n    //It might be more efficient to make everything an armadillo object initially\n    // but then would need to replace push_back etc with a different approach (but this might be more efficient anyway)\n    arma::colvec split_var_vec_arma=arma::conv_to<arma::colvec>::from(split_var_vec);\n    arma::colvec split_point_vec_arma(split_point_vec);\n    arma::colvec treenodes_bin_arma=arma::conv_to<arma::colvec>::from(treenodes_bin);\n\n\n    //Rcout << \"Line 1054. \\n\";\n\n    tree_table1.col(2) = split_var_vec_arma;\n    tree_table1.col(3) = split_point_vec_arma;\n    tree_table1.col(4) = treenodes_bin_arma;\n\n\n    //Rcout << \"Line 1061. j = \" << j << \". \\n\";\n\n\n\n    // Now start filling in left daughter and right daughter columns\n    std::vector<int> rd_spaces;\n    int prev_node = -1;\n\n    for(unsigned int i=0; i<treenodes_bin.size();i++){\n      //Rcout << \"Line 1061. i = \" << i << \". \\n\";\n      if(prev_node==0){\n        //tree_table1(rd_spaces[rd_spaces.size()-1], 1)=i;\n        //Rcout << \"Line 1073. j = \" << j << \". \\n\";\n\n        tree_table1(rd_spaces.back(), 1)=i+1;\n        //Rcout << \"Line 1076. j = \" << j << \". \\n\";\n\n        rd_spaces.pop_back();\n      }\n      if(treenodes_bin[i]==1){\n        //Rcout << \"Line 1081. j = \" << j << \". \\n\";\n\n        tree_table1(i,0) = i+2;\n        rd_spaces.push_back(i);\n        prev_node = 1;\n        //Rcout << \"Line 185. j = \" << j << \". \\n\";\n\n      }else{                  // These 2 lines unnecessary if begin with matrix of zeros\n        //Rcout << \"Line 1089. j = \" << j << \". \\n\";\n        tree_table1(i,0)=0 ;\n        tree_table1(i,1) = 0 ;\n        prev_node = 0;\n        //Rcout << \"Line 1093. j = \" << j << \". \\n\";\n\n      }\n    }//\n    //Rcout << \"Line 1097. j = \" << j << \". \\n\";\n\n    table_list[j]=wrap(tree_table1);\n    //Rcout << \"Line 1100. j = \" << j << \". \\n\";\n\n  }//end of loop over all trees\n\n  return(table_list);\n}//end of function definition\n//######################################################################################################################//\n\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::export]]\ndouble secondKindStirlingNumber(int n, int k) {\n  if(k>n)\n    throw std::range_error(\"Sterling number undefined for k>n\");\n  if(k==0 && n==0)\n    return 1;\n  if (n == 0 || k == 0 || k > n)\n    return 0;\n  if (k == 1 || k == n)\n    return 1;\n\n  arma::mat sf=arma::zeros(n + 1,n + 1);\n  for (int i = 0; i < k+1; i++) {\n    sf(i,i) = 1;\n  }\n  for(int i=1; i< n+1 ; i++){\n    sf(i,1)=1;\n  }\n  for (int i = 3; i < n + 1; i++) {\n    for (int j = 2; j < k + 1; j++) {\n      sf(i,j) = j * sf(i - 1,j) + sf(i - 1,j - 1);\n    }\n  }\n  return sf(n,k);\n}\n\n//###########################################################################################################################//\n#include <boost/math/distributions/students_t.hpp>\n\n// [[Rcpp::depends(BH)]]\n// [[Rcpp::export]]\ndouble mixt_eval_cdf(double x_val, double d_o_f, std::vector<double> mean_vec, std::vector<double> var_vec, std::vector<double> weights_vec, double quant_val) {\n\n  boost::math::students_t dist(d_o_f);\n\n  double ret_val=0;\n  for(unsigned int i=0; i < weights_vec.size();i++){\n    if(var_vec[i]>0){\n      double tempx = (x_val-mean_vec[i])/sqrt(var_vec[i]);\n      ret_val += weights_vec[i]*boost::math::cdf(dist,tempx);\n    }else{//in some cases (for ITEs) there is zero variance, and can't divide by zero\n      //Rcout << \" \\n \\n VARIANCE = \" << var_vec[i] << \".\\n \\n\" ;\n      if(x_val>=mean_vec[i]){ //if no variance, cdf is zero below mean, and one above mean\n        ret_val += weights_vec[i];\n      } // no else statement because add zero if below mean (when there is zero variance)\n    }\n  }\n\n  return (ret_val-quant_val) ;  // approximation\n}\n\n//###########################################################################################################################//\n// [[Rcpp::export]]\ndouble rootmixt(double d_o_f, double a, double b,\n                std::vector<double> mean_vec,\n                std::vector<double> var_vec,\n                std::vector<double> weights_vec, double quant_val, double root_alg_precision){\n\n  static const double EPS = root_alg_precision;//1e-15; // 1\u00d710^(-15)\n\n  double fa = mixt_eval_cdf(a, d_o_f, mean_vec, var_vec, weights_vec,quant_val), fb = mixt_eval_cdf(b, d_o_f, mean_vec, var_vec, weights_vec,quant_val);\n\n  // if either f(a) or f(b) are the root, return that\n  // nothing else to do\n  if (fa == 0) return a;\n  if (fb == 0) return b;\n\n  //Rcout << \"quant_val = \" << quant_val << \".\\n\";\n\n  //Rcout << \"fa = \" << fa << \".\\n\";\n  //Rcout << \"fb = \" << fb << \".\\n\";\n\n  // this method only works if the signs of f(a) and f(b)\n  // are different. so just assert that\n  assert(fa * fb < 0); // 8.- macro assert from header cassert.\n\n\n  do {\n    // calculate fun at the midpoint of a,b\n    // if that's the root, we're done\n\n    // this line is awful, never write code like this...\n    //if ((f = fun((s = (a + b) / 2))) == 0) break;\n\n    // prefer:\n    double midpt = (a + b) / 2;\n    double fmid = mixt_eval_cdf(midpt, d_o_f, mean_vec, var_vec, weights_vec,quant_val);\n\n    if (fmid == 0) return midpt;\n\n    // adjust our bounds to either [a,midpt] or [midpt,b]\n    // based on where fmid ends up being. I'm pretty\n    // sure the code in the question is wrong, so I fixed it\n    if (fa * fmid < 0) { // fmid, not f1\n      fb = fmid;\n      b = midpt;\n    }\n    else {\n      fa = fmid;\n      a = midpt;\n    }\n  } while (b-a > EPS); // only loop while\n  // a and b are sufficiently far\n  // apart\n  //Rcout << \"a = \" << a << \".\\n\";\n  //Rcout << \"b = \" << b << \".\\n\";\n  return (a + b) / 2;  // approximation\n}\n\n\n//###########################################################################################################################//\n\nstd::vector<double> mixt_find_boundsQ(double d_o_f, std::vector<double> mean_vec, std::vector<double> var_vec, double quant_val) {\n  //boost::math::students_t dist1(d_o_f);\n\n  std::vector<double> tempbounds(mean_vec.size());\n\n  for(unsigned int i=0; i< mean_vec.size();i++){\n    //tempbounds[i]= mean_vec[i]+sqrt(var_vec[i])*boost::math::quantile(dist1,quant_val);\n    tempbounds[i]= mean_vec[i]+sqrt(var_vec[i])*quant_val;\n  }\n\n  std::vector<double> ret(2);\n  ret[0]= *std::min_element(tempbounds.begin(), tempbounds.end());\n  ret[1]= *std::max_element(tempbounds.begin(), tempbounds.end());\n\n  return(ret) ;\n}\n\n\n//######################################################################################################################//\n\n// [[Rcpp::depends(RcppArmadillo)]]\n//' @title Safe-Bayesian Random Forest. Initial test function.\n//' @export\n// [[Rcpp::export]]\n\nNumericMatrix sBayesRF(double lambda, int num_trees,\n                       int seed, int num_cats,\n                       NumericVector y, NumericMatrix original_datamat,\n                       NumericVector alpha_parameters, double beta_par,\n                       NumericMatrix test_datamat){\n\n  int num_split_vars= original_datamat.ncol();\n  NumericMatrix Data_transformed = cpptrans_cdf(original_datamat);\n  NumericMatrix testdat_trans = cpptrans_cdf_test(original_datamat,test_datamat);\n\n  //Rcout << \"Line 1134 . \\n\";\n  List table_list = draw_trees(lambda, num_trees, seed, num_split_vars, num_cats );\n  //Rcout << \"Line 1136 . \\n\";\n\n\n  List tree_list_output = get_treelist(y, num_cats, alpha_parameters, beta_par,\n                                       Data_transformed,\n                                       table_list  );\n  //Rcout << \"Line 1141 . \\n\";\n\n  NumericMatrix probmat = get_test_prob_overall(tree_list_output[1],num_cats,\n                                                testdat_trans,\n                                                tree_list_output[0]);\n  //Rcout << \"Line 1146 . \\n\";\n\n  return(probmat);\n\n}\n//######################################################################################################################//\n\n// [[Rcpp::depends(RcppArmadillo)]]\n//' @title Safe-Bayesian Random Forest\n//'\n//' @description An implementation of the Safe-Bayesian Random Forest described by Quadrianto and Ghahramani (2015)\n//' @param lambda A real number between 0 and 1 that determines the splitting probability in the prior (which is used as the importance sampler of tree models). Quadrianto and Ghahramani (2015) recommend a value less than 0.5 .\n//' @param num_trees The number of trees to be sampled.\n//' @param seed The seed for random number generation.\n//' @param num_cats The number of possible values for the outcome variable.\n//' @param y The training data vector of outcomes. This must be a vector of integers between 1 and num_cats.\n//' @param original_datamat The original training data. Currently all variables must be continuous. The training data does not need to be transformed before being entered to this function.\n//' @param alpha_parameters Vector of prior parameters.\n//' @param beta_par The power to which the likelihood is to be raised. For BMA, set beta_par=1.\n//' @param original_datamat The original test data. This matrix must have the same number of columns (variables) as the training data. Currently all variables must be continuous. The test data does not need to be transformed before being entered to this function.\n//' @export\n// [[Rcpp::export]]\n\nNumericMatrix sBayesRF_onefunc(double lambda, int num_trees,\n                               int seed, int num_cats,\n                               NumericVector y, NumericMatrix original_datamat,\n                               NumericVector alpha_parameters, double beta_par,\n                               NumericMatrix test_datamat){\n\n  int num_split_vars= original_datamat.ncol();\n\n\n  ///////////////////////\n  //NumericMatrix Data_transformed = cpptrans_cdf(original_datamat);\n  NumericMatrix Data_transformed(original_datamat.nrow(), original_datamat.ncol());\n  for(int i=0; i<original_datamat.ncol();i++){\n    NumericVector samp= original_datamat(_,i);\n    NumericVector sv(clone(samp));\n    std::sort(sv.begin(), sv.end());\n    double nobs = samp.size();\n    NumericVector ans(nobs);\n    for (int k = 0; k < samp.size(); ++k)\n      ans[k] = std::lower_bound(sv.begin(), sv.end(), samp[k]) - sv.begin();\n    //NumericVector ansnum = ans;\n    Data_transformed(_,i) = (ans+1)/nobs;\n  }\n\n\n\n  /////////////////////////////////////\n  //NumericMatrix testdat_trans = cpptrans_cdf_test(original_datamat,test_datamat);\n  NumericMatrix testdat_trans(test_datamat.nrow(), test_datamat.ncol());\n  for(int i=0; i<test_datamat.ncol();i++){\n    NumericVector samp= test_datamat(_,i);\n    NumericVector svtest = original_datamat(_,i);\n    NumericVector sv(clone(svtest));\n    std::sort(sv.begin(), sv.end());\n    double nobs = samp.size();\n    NumericVector ans(nobs);\n    double nobsref = svtest.size();\n    for (int k = 0; k < samp.size(); ++k){\n      ans[k] = std::lower_bound(sv.begin(), sv.end(), samp[k]) - sv.begin();\n    }\n    //NumericVector ansnum = ans;\n    testdat_trans(_,i) = (ans)/nobsref;\n  }\n\n\n\n  /////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n  //////////////////////////////////////////////////////////////////////////////////////\n  //List table_list = draw_trees(lambda, num_trees, seed, num_split_vars, num_cats );\n\n\n\n  //dqrng::dqRNGkind(\"Xoroshiro128+\");\n  //dqrng::dqset_seed(IntegerVector::create(seed));\n\n  //use following with binomial?\n  //dqrng::xoshiro256plus rng(seed);\n\n  //std::vector<int> lambdavec = {lambda, 1-lambda};\n\n  //typedef boost::mt19937 RNGType;\n  //boost::random::uniform_int_distribution<> sample_splitvardist(1,num_split_vars);\n  //boost::variate_generator< RNGType, boost::uniform_int<> >  sample_splitvars(rng, sample_splitvardist);\n\n  //boost::random::uniform_real_distribution<double> b_unifdist(0,1);\n  //boost::variate_generator< RNGType, boost::uniform_real<> >  b_unif_point(rng, b_unifdist);\n\n\n\n  // std::random_device device;\n  // std::mt19937 gen(device());\n\n  //possibly use seed?\n  //// std::mt19937 gen(seed);\n\n\n  // std::bernoulli_distribution coin_flip(lambda);\n\n  // std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n  //std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n\n  arma::vec orig_y_arma= as<arma::vec>(y);\n  arma::vec alpha_pars_arma= as<arma::vec>(alpha_parameters);\n\n  arma::mat arma_orig_data(Data_transformed.begin(), Data_transformed.nrow(), Data_transformed.ncol(), false);\n  arma::mat arma_test_data(testdat_trans.begin(), testdat_trans.nrow(), testdat_trans.ncol(), false);\n\n\n  arma::mat pred_mat_overall=arma::zeros<arma::mat>(test_datamat.nrow(),num_cats);\n\n\n  //List overall_treetables(num_trees);\n  NumericVector overall_liks(num_trees);\n\n\n  //overall_treetables[i]= wrap(tree_table1);\n  //double templik = as<double>(treepred_output[1]);\n  //overall_liks[i]= pow(lik_prod,beta_pow);\n\n\n\n  for(int j=0; j<num_trees;j++){\n\n    //If parallelizing, define the distributinos before this loop\n    //and use lrng and the following two lines\n    //dqrng::xoshiro256plus lrng(rng);      // make thread local copy of rng\n    //lrng.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... nthreads jumps\n\n\n    //NumericVector treenodes_bin(0);\n    //arma::uvec treenodes_bin(0);\n\n    std::vector<int> treenodes_bin;\n\n\n    int count_terminals = 0;\n    int count_internals = 0;\n\n    //int count_treebuild = 0;\n\n    while(count_internals > (count_terminals -1)){\n\n      //Also consider standard library and random header\n      // std::random_device device;\n      // std::mt19937 gen(device());\n      // std::bernoulli_distribution coin_flip(lambda);\n      // bool outcome = coin_flip(gen);\n\n\n      //int tempdraw = coin_flip(gen);\n\n      //int tempdraw = rbinom(n = 1, prob = lambda,size=1);\n\n\n      //int tempdraw = Rcpp::rbinom(1,lambda,1);\n      int tempdraw = R::rbinom(1,lambda);\n      treenodes_bin.push_back(tempdraw);\n\n      //Rcout << \"tempdraw = \" << tempdraw << \".\\n\" ;\n\n      //int tempdraw = dqrng::dqsample_int(2, 1, true,lambdavec )-1;\n      //need to update rng if use boost?\n      //int tempdraw = bernoulli(rng, binomial::param_type(1, lambda));\n      if(tempdraw==1){\n        count_internals=count_internals+1;\n      }else{\n        count_terminals=count_terminals+1;\n      }\n\n    }//end of while loop creating parent vector treenodes_bin\n\n    //Consider making this an armadillo vector\n    //IntegerVector split_var_vec(treenodes_bin.size());\n    //arma::uvec split_var_vec(treenodes_bin.size());\n    std::vector<int> split_var_vec(treenodes_bin.size());\n\n    //loop drawing splitting variables\n    //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n    //if using armadillo, it might be faster to subset to split nodes\n    //then use a vector of draws\n    for(unsigned int i=0; i<treenodes_bin.size();i++){\n      if(treenodes_bin[i]==0){\n        split_var_vec[i] = -1;\n      }else{\n        // also consider the standard library function uniform_int_distribution\n        // might need random header\n        // This uses the Mersenne twister\n\n        //Three lines below should probably be outside all the loops\n        // std::random_device rd;\n        // std::mt19937 engine(rd());\n        // std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n        //\n        // split_var_vec[i] <- distsampvar(engine);\n\n        // split_var_vec[i] <- distsampvar(gen);\n\n\n        //consider using boost\n        //might need to update rng\n        //split_var_vec[i] <- sample_splitvars(rng);\n\n        //or use dqrng\n        //not sure if have to update the random number\n        //check if the following line is written properly\n        //split_var_vec[i] = dqrng::dqsample_int(num_split_vars, 1, true);\n\n        //not sure if this returns an integer or a vector?\n        //split_var_vec[i] = RcppArmadillo::sample(num_split_vars, 1,true);\n        //could try\n        split_var_vec[i] = as<int>(Rcpp::sample(num_split_vars, 1,true));\n        //could also try RcppArmadillo::rmultinom\n\n      }\n\n    }// end of for-loop drawing split variables\n\n\n    //Consider making this an armadillo vector\n    //NumericVector split_point_vec(treenodes_bin.size());\n    //arma::vec split_point_vec(treenodes_bin.size());\n    std::vector<double> split_point_vec(treenodes_bin.size());\n\n\n    //loop drawing splitting points\n    //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n    //if using armadillo, it might be faster to subset to split nodes\n    //then use a vector of draws\n    for(unsigned int i=0; i<treenodes_bin.size();i++){\n      if(treenodes_bin[i]==0){\n        split_point_vec[i] = -1;\n      }else{\n\n\n        //////////////////////////////////////////////////////////\n        //following function not reccommended\n        //split_point_vec[i] = std::rand();\n        //////////////////////////////////////////////////////////\n        ////Standard library:\n        ////This should probably be outside all the loops\n        ////std::random_device rd;  //Will be used to obtain a seed for the random number engine\n        ////std::mt19937 gen2(rd()); //Standard mersenne_twister_engine seeded with rd()\n        ////std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n        // split_point_vec[i] = dis_cont_unif(gen);\n\n        //////////////////////////////////////////////////////////\n        //from armadillo\n        //split_point_vec[i] = arma::randu();\n\n        //////////////////////////////////////////////////////////\n        //probably not adviseable for paralelization\n        //From Rcpp\n        split_point_vec[i] = as<double>(Rcpp::runif(1,0,1));\n\n        //////////////////////////////////////////////////////////\n        //consider using boost\n        //might need to update rng\n        //split_point_vec[i] <- b_unif_point(rng);\n\n        //or use dqrng\n        //not sure if have to update the random number\n        //check if the following line is written properly\n        //split_point_vec[i] = dqrng::dqrunif(1, 0, 1);\n\n        //not sure if this returns an integer or a vector?\n\n\n\n\n\n      }\n\n    }// end of for-loop drawing split points\n\n\n    //Create tree table matrix\n\n    //NumericMatrix tree_table1(treenodes_bin.size(),5+num_cats);\n\n    //Rcout << \"Line 1037. \\n\";\n    //arma::mat tree_table1(treenodes_bin.size(),5+num_cats);\n\n    //initialize with zeros. Not sure if this is necessary\n    arma::mat tree_table1=arma::zeros<arma::mat>(treenodes_bin.size(),5+num_cats);\n    //Rcout << \"Line 1040. \\n\";\n\n\n    //tree_table1(_,2) = wrap(split_var_vec);\n    //tree_table1(_,3) = wrap(split_point_vec);\n    //tree_table1(_,4) = wrap(treenodes_bin);\n\n    //It might be more efficient to make everything an armadillo object initially\n    // but then would need to replace push_back etc with a different approach (but this might be more efficient anyway)\n    arma::colvec split_var_vec_arma=arma::conv_to<arma::colvec>::from(split_var_vec);\n    arma::colvec split_point_vec_arma(split_point_vec);\n    arma::colvec treenodes_bin_arma=arma::conv_to<arma::colvec>::from(treenodes_bin);\n\n\n    //Rcout << \"Line 1054. \\n\";\n\n    tree_table1.col(2) = split_var_vec_arma;\n    tree_table1.col(3) = split_point_vec_arma;\n    tree_table1.col(4) = treenodes_bin_arma;\n\n\n    //Rcout << \"Line 1061. j = \" << j << \". \\n\";\n\n\n\n    // Now start filling in left daughter and right daughter columns\n    std::vector<int> rd_spaces;\n    int prev_node = -1;\n\n    for(unsigned int i=0; i<treenodes_bin.size();i++){\n      //Rcout << \"Line 1061. i = \" << i << \". \\n\";\n      if(prev_node==0){\n        //tree_table1(rd_spaces[rd_spaces.size()-1], 1)=i;\n        //Rcout << \"Line 1073. j = \" << j << \". \\n\";\n\n        tree_table1(rd_spaces.back(), 1)=i+1;\n        //Rcout << \"Line 1076. j = \" << j << \". \\n\";\n\n        rd_spaces.pop_back();\n      }\n      if(treenodes_bin[i]==1){\n        //Rcout << \"Line 1081. j = \" << j << \". \\n\";\n\n        tree_table1(i,0) = i+2;\n        rd_spaces.push_back(i);\n        prev_node = 1;\n        //Rcout << \"Line 185. j = \" << j << \". \\n\";\n\n      }else{                  // These 2 lines unnecessary if begin with matrix of zeros\n        //Rcout << \"Line 1089. j = \" << j << \". \\n\";\n        tree_table1(i,0)=0 ;\n        tree_table1(i,1) = 0 ;\n        prev_node = 0;\n        //Rcout << \"Line 1093. j = \" << j << \". \\n\";\n\n      }\n    }//\n    //Rcout << \"Line 1097. j = \" << j << \". \\n\";\n\n\n\n\n\n    //List treepred_output = get_treepreds(original_y, num_cats, alpha_pars,\n    //                                     originaldata,\n    //                                     treetable_list[i]  );\n\n\n    //use armadillo object tree_table1\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n    double lik_prod=1;\n    double alph_prod=1;\n    for(unsigned int i=0; i<alpha_pars_arma.n_elem;i++){\n      alph_prod=alph_prod*tgamma(alpha_pars_arma(i));\n    }\n    double gam_alph_sum= tgamma(arma::sum(alpha_pars_arma));\n    double alph_term=gam_alph_sum/alph_prod;\n\n    //arma::mat arma_tree_table(treetable.begin(), treetable.nrow(), treetable.ncol(), false);\n    //arma::mat arma_orig_data(originaldata.begin(), originaldata.nrow(), originaldata.ncol(), false);\n\n\n    //arma::mat arma_tree(tree_data.begin(), tree_data.nrow(), tree_data.ncol(), false);\n    //arma::mat testd(test_data.begin(), test_data.nrow(), test_data.ncol(), false);\n\n    //NumericVector internal_nodes=find_internal_nodes_gs(tree_data);\n\n    //NumericVector terminal_nodes=find_term_nodes(treetable);\n\n    //arma::mat arma_tree(tree_table.begin(),tree_table.nrow(), tree_table.ncol(), false);\n\n    //arma::vec colmat=arma_tree.col(4);\n    //arma::uvec term_nodes=arma::find(colmat==-1);\n\n    //arma::vec colmat=arma_tree.col(2);\n    //arma::uvec term_nodes=arma::find(colmat==0);\n\n    arma::vec colmat=tree_table1.col(4);\n    arma::uvec term_nodes=arma::find(colmat==0);\n\n    term_nodes=term_nodes+1;\n\n    NumericVector terminal_nodes= wrap(term_nodes);\n\n\n\n\n    //arma::vec arma_terminal_nodes=Rcpp::as<arma::vec>(terminal_nodes);\n    //NumericVector tree_predictions;\n\n    //now for each internal node find the observations that belong to the terminal nodes\n\n    //NumericVector predictions(test_data.nrow());\n    //List term_obs(terminal_nodes.size());\n    if(terminal_nodes.size()==1){\n      //double nodemean=tree_data(terminal_nodes[0]-1,5);\t\t\t\t// let nodemean equal tree_data row terminal_nodes[i]^th row , 6th column. The minus 1 is because terminal nodes consists of indices starting at 1, but need indices to start at 0.\n      //predictions=rep(nodemean,test_data.nrow());\n      //Rcout << \"Line 67 .\\n\";\n\n      //IntegerVector temp_obsvec = seq_len(test_data.nrow())-1;\n      //term_obs[0]= temp_obsvec;\n      double denom_temp= orig_y_arma.n_elem+arma::sum(alpha_pars_arma);\n\n      double num_prod=1;\n      double num_sum=0;\n      //Rcout << \"Line 129.\\n\";\n\n      for(int k=0; k<num_cats; k++){\n        //assuming categories of y are from 1 to num_cats\n        arma::uvec cat_inds= arma::find(orig_y_arma==k+1);\n        double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n        tree_table1(0,5+k)= m_plus_alph/denom_temp ;\n\n        //for likelihood calculation\n        num_prod=num_prod*tgamma(m_plus_alph);\n        num_sum=num_sum +m_plus_alph ;\n      }\n\n      lik_prod= alph_term*num_prod/tgamma(num_sum);\n\n    }\n    else{\n      for(int i=0;i<terminal_nodes.size();i++){\n        //arma::mat subdata=testd;\n        int curr_term=terminal_nodes[i];\n\n        int row_index;\n        int term_node=terminal_nodes[i];\n        //Rcout << \"Line 152.\\n\";\n\n\n        //WHAT IS THE PURPOSE OF THIS IF-STATEMENT?\n        //Why should the ro index be different for a right daughter?\n        //Why not just initialize row_index to any number not equal to 1 (e.g. 0)?\n        row_index=0;\n\n        // if(curr_term % 2==0){\n        //   //term node is left daughter\n        //   row_index=terminal_nodes[i];\n        // }else{\n        //   //term node is right daughter\n        //   row_index=terminal_nodes[i]-1;\n        // }\n\n\n\n\n        //save the left and right node data into arma uvec\n\n        //CHECK THAT THIS REFERS TO THE CORRECT COLUMNS\n        //arma::vec left_nodes=arma_tree.col(0);\n        //arma::vec right_nodes=arma_tree.col(1);\n\n        arma::vec left_nodes=tree_table1.col(0);\n        arma::vec right_nodes=tree_table1.col(1);\n\n\n\n        arma::mat node_split_mat;\n        node_split_mat.set_size(0,3);\n        //Rcout << \"Line 182. i = \" << i << \" .\\n\";\n\n        while(row_index!=1){\n          //for each terminal node work backwards and see if the parent node was a left or right node\n          //append split info to a matrix\n          int rd=0;\n          arma::uvec parent_node=arma::find(left_nodes == term_node);\n\n          if(parent_node.size()==0){\n            parent_node=arma::find(right_nodes == term_node);\n            rd=1;\n          }\n\n          //want to cout parent node and append to node_split_mat\n\n          node_split_mat.insert_rows(0,1);\n\n          //CHECK THAT COLUMNS OF TREETABLE ARE CORRECT\n          //node_split_mat(0,0)=treetable(parent_node[0],2);\n          //node_split_mat(0,1)=treetable(parent_node[0],3);\n\n          //node_split_mat(0,0)=arma_tree_table(parent_node[0],3);\n          //node_split_mat(0,1)=arma_tree_table(parent_node[0],4);\n\n          node_split_mat(0,0)=tree_table1(parent_node[0],2);\n          node_split_mat(0,1)=tree_table1(parent_node[0],3);\n\n          node_split_mat(0,2)=rd;\n          row_index=parent_node[0]+1;\n          term_node=parent_node[0]+1;\n        }\n\n        //once we have the split info, loop through rows and find the subset indexes for that terminal node!\n        //then fill in the predicted value for that tree\n        //double prediction = tree_data(term_node,5);\n        arma::uvec pred_indices;\n        int split= node_split_mat(0,0)-1;\n\n        //Rcout << \"Line 224.\\n\";\n        //Rcout << \"split = \" << split << \".\\n\";\n        //arma::vec tempvec = testd.col(split);\n        arma::vec tempvec = arma_orig_data.col(split);\n        //Rcout << \"Line 227.\\n\";\n\n\n        double temp_split = node_split_mat(0,1);\n\n        if(node_split_mat(0,2)==0){\n          pred_indices = arma::find(tempvec <= temp_split);\n        }else{\n          pred_indices = arma::find(tempvec > temp_split);\n        }\n        //Rcout << \"Line 236.\\n\";\n\n        arma::uvec temp_pred_indices;\n\n        //arma::vec data_subset = testd.col(split);\n        arma::vec data_subset = arma_orig_data.col(split);\n\n        data_subset=data_subset.elem(pred_indices);\n\n        //now loop through each row of node_split_mat\n        int n=node_split_mat.n_rows;\n        //Rcout << \"Line 174. i = \" << i << \". n = \" << n << \".\\n\";\n        //Rcout << \"Line 248.\\n\";\n\n        for(int j=1;j<n;j++){\n          int curr_sv=node_split_mat(j,0);\n          double split_p = node_split_mat(j,1);\n\n          //data_subset = testd.col(curr_sv-1);\n          //Rcout << \"Line 255.\\n\";\n          //Rcout << \"curr_sv = \" << curr_sv << \".\\n\";\n          data_subset = arma_orig_data.col(curr_sv-1);\n          //Rcout << \"Line 258.\\n\";\n\n          data_subset=data_subset.elem(pred_indices);\n\n          if(node_split_mat(j,2)==0){\n            //split is to the left\n            temp_pred_indices=arma::find(data_subset <= split_p);\n          }else{\n            //split is to the right\n            temp_pred_indices=arma::find(data_subset > split_p);\n          }\n          pred_indices=pred_indices.elem(temp_pred_indices);\n\n          if(pred_indices.size()==0){\n            continue;\n          }\n\n        }\n        //Rcout << \"Line 199. i = \" << i <<  \".\\n\";\n\n        //double nodemean=tree_data(terminal_nodes[i]-1,5);\n        //IntegerVector predind=as<IntegerVector>(wrap(pred_indices));\n        //predictions[predind]= nodemean;\n        //term_obs[i]=predind;\n\n        double denom_temp= pred_indices.n_elem+arma::sum(alpha_pars_arma);\n        //Rcout << \"Line 207. predind = \" << predind <<  \".\\n\";\n        //Rcout << \"Line 207. denom_temp = \" << denom_temp <<  \".\\n\";\n        // << \"Line 207. term_node = \" << term_node <<  \".\\n\";\n\n        double num_prod=1;\n        double num_sum=0;\n\n        for(int k=0; k<num_cats; k++){\n          //assuming categories of y are from 1 to num_cats\n          arma::uvec cat_inds= arma::find(orig_y_arma(pred_indices)==k+1);\n          double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n\n          tree_table1(curr_term-1,5+k)= m_plus_alph/denom_temp ;\n\n          num_prod=num_prod*tgamma(m_plus_alph);\n          num_sum=num_sum +m_plus_alph ;\n        }\n\n\n        lik_prod= lik_prod*alph_term*num_prod/tgamma(num_sum);\n        //Rcout << \"Line 297.\\n\";\n\n\n      }\n      //Rcout << \"Line 301.\\n\";\n\n    }\n    //List ret(1);\n    //ret[0] = term_obs;\n\n    //ret[0] = terminal_nodes;\n    //ret[1] = term_obs;\n    //ret[2] = predictions;\n    //return(term_obs);\n    //Rcout << \"Line 309\";\n\n    //return(wrap(arma_tree_table));\n\n    //List ret(2);\n    //ret[0]=wrap(arma_tree_table);\n    //ret[1]=lik_prod;\n\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n\n\n\n    //overall_treetables[j]= wrap(tree_table1);\n\n\n    //double templik = as<double>(treepred_output[1]);\n\n    double templik = pow(lik_prod,beta_par);\n    overall_liks[j]= templik;\n\n\n\n\n\n\n    //arma::mat arma_tree_table(treetable.begin(), treetable.nrow(), treetable.ncol(), false);\n    //arma::mat arma_test_data(testdata.begin(), testdata.nrow(), testdata.ncol(), false);\n\n\n    //arma::mat arma_tree(tree_data.begin(), tree_data.nrow(), tree_data.ncol(), false);\n    //arma::mat testd(test_data.begin(), test_data.nrow(), test_data.ncol(), false);\n\n    //NumericVector internal_nodes=find_internal_nodes_gs(tree_data);\n\n    //NumericVector terminal_nodes=find_term_nodes(treetable);\n    //arma::vec arma_terminal_nodes=Rcpp::as<arma::vec>(terminal_nodes);\n    //NumericVector tree_predictions;\n\n    //now for each internal node find the observations that belong to the terminal nodes\n\n    //NumericVector predictions(test_data.nrow());\n\n    arma::mat pred_mat(test_datamat.nrow(),num_cats);\n    //arma::vec filled_in(testdata.nrow());\n\n\n    //List term_obs(terminal_nodes.size());\n    if(terminal_nodes.size()==1){\n\n      //Rcout << \"Line 422. \\n\";\n\n\n      pred_mat=repmat(tree_table1(0,arma::span(5,5+num_cats-1)),test_datamat.nrow(),1);\n\n\n      //Rcout << \"Line 424. \\n\";\n\n\n      // for(int k=0; k<num_cats; k++){\n      // pred_mat(_,k)=rep(treetable(0,5+k),testdata.nrow());\n      // }\n      //double nodemean=tree_data(terminal_nodes[0]-1,5);\t\t\t\t// let nodemean equal tree_data row terminal_nodes[i]^th row , 6th column. The minus 1 is because terminal nodes consists of indices starting at 1, but need indices to start at 0.\n      //predictions=rep(nodemean,test_data.nrow());\n      //Rcout << \"Line 67 .\\n\";\n\n      //IntegerVector temp_obsvec = seq_len(test_data.nrow())-1;\n      //term_obs[0]= temp_obsvec;\n      // double denom_temp= orig_y_arma.n_elem+arma::sum(alpha_pars_arma);\n      //\n      // double num_prod=1;\n      // double num_sum=0;\n\n      // for(int k=0; k<num_cats; k++){\n      //   //assuming categories of y are from 1 to num_cats\n      //   arma::uvec cat_inds= arma::find(orig_y_arma==k+1);\n      //   double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n      //   arma_tree_table(0,5+k)= m_plus_alph/denom_temp ;\n      //\n      //   //for likelihood calculation\n      //   num_prod=num_prod*tgamma(m_plus_alph);\n      //   num_sum=num_sum +m_plus_alph ;\n      // }\n      //\n      // lik_prod= alph_term*num_prod/tgamma(num_sum);\n      //\n    }\n    else{\n      for(int i=0;i<terminal_nodes.size();i++){\n        //arma::mat subdata=testd;\n        int curr_term=terminal_nodes[i];\n\n        int row_index;\n        int term_node=terminal_nodes[i];\n\n\n        //WHAT IS THE PURPOSE OF THIS IF-STATEMENT?\n        //Why should the ro index be different for a right daughter?\n        //Why not just initialize row_index to any number not equal to 1 (e.g. 0)?\n        row_index=0;\n\n        // if(curr_term % 2==0){\n        //   //term node is left daughter\n        //   row_index=terminal_nodes[i];\n        // }else{\n        //   //term node is right daughter\n        //   row_index=terminal_nodes[i]-1;\n        // }\n\n\n\n\n\n\n\n\n        //save the left and right node data into arma uvec\n\n        //CHECK THAT THIS REFERS TO THE CORRECT COLUMNS\n        //arma::vec left_nodes=arma_tree.col(0);\n        //arma::vec right_nodes=arma_tree.col(1);\n\n        arma::vec left_nodes=tree_table1.col(0);\n        arma::vec right_nodes=tree_table1.col(1);\n\n\n\n        arma::mat node_split_mat;\n        node_split_mat.set_size(0,3);\n        //Rcout << \"Line 124. i = \" << i << \" .\\n\";\n\n        while(row_index!=1){\n          //for each terminal node work backwards and see if the parent node was a left or right node\n          //append split info to a matrix\n          int rd=0;\n          arma::uvec parent_node=arma::find(left_nodes == term_node);\n\n          if(parent_node.size()==0){\n            parent_node=arma::find(right_nodes == term_node);\n            rd=1;\n          }\n\n          //want to cout parent node and append to node_split_mat\n\n          node_split_mat.insert_rows(0,1);\n\n          //CHECK THAT COLUMNS OF TREETABLE ARE CORRECT\n          //node_split_mat(0,0)=treetable(parent_node[0],2);\n          //node_split_mat(0,1)=treetable(parent_node[0],3);\n\n          //node_split_mat(0,0)=arma_tree_table(parent_node[0],3);\n          //node_split_mat(0,1)=arma_tree_table(parent_node[0],4);\n\n          node_split_mat(0,0)=tree_table1(parent_node[0],2);\n          node_split_mat(0,1)=tree_table1(parent_node[0],3);\n\n          node_split_mat(0,2)=rd;\n          row_index=parent_node[0]+1;\n          term_node=parent_node[0]+1;\n        }\n\n        //once we have the split info, loop through rows and find the subset indexes for that terminal node!\n        //then fill in the predicted value for that tree\n        //double prediction = tree_data(term_node,5);\n        arma::uvec pred_indices;\n        int split= node_split_mat(0,0)-1;\n\n        //arma::vec tempvec = testd.col(split);\n        arma::vec tempvec = arma_test_data.col(split);\n\n\n        double temp_split = node_split_mat(0,1);\n\n        if(node_split_mat(0,2)==0){\n          pred_indices = arma::find(tempvec <= temp_split);\n        }else{\n          pred_indices = arma::find(tempvec > temp_split);\n        }\n\n        arma::uvec temp_pred_indices;\n\n        //arma::vec data_subset = testd.col(split);\n        arma::vec data_subset = arma_test_data.col(split);\n\n        data_subset=data_subset.elem(pred_indices);\n\n        //now loop through each row of node_split_mat\n        int n=node_split_mat.n_rows;\n        //Rcout << \"Line 174. i = \" << i << \". n = \" << n << \".\\n\";\n        //Rcout << \"Line 174. node_split_mat= \" << node_split_mat << \". n = \" << n << \".\\n\";\n\n\n        for(int j=1;j<n;j++){\n          int curr_sv=node_split_mat(j,0);\n          double split_p = node_split_mat(j,1);\n\n          //data_subset = testd.col(curr_sv-1);\n          data_subset = arma_test_data.col(curr_sv-1);\n\n          data_subset=data_subset.elem(pred_indices);\n\n          if(node_split_mat(j,2)==0){\n            //split is to the left\n            temp_pred_indices=arma::find(data_subset <= split_p);\n          }else{\n            //split is to the right\n            temp_pred_indices=arma::find(data_subset > split_p);\n          }\n          pred_indices=pred_indices.elem(temp_pred_indices);\n\n          if(pred_indices.size()==0){\n            continue;\n          }\n\n        }\n        //Rcout << \"Line 199. i = \" << i <<  \".\\n\";\n\n        //double nodemean=tree_data(terminal_nodes[i]-1,5);\n        //IntegerVector predind=as<IntegerVector>(wrap(pred_indices));\n        //predictions[predind]= nodemean;\n        //term_obs[i]=predind;\n\n        //Rcout << \"Line 635. \\n\";\n        //Rcout << \"pred_indices = \" << pred_indices << \".\\n\";\n\n        //pred_mat.rows(pred_indices)=arma::repmat(arma_tree_table(curr_term-1,arma::span(5,5+num_cats-1)),pred_indices.n_elem,1);\n        pred_mat.each_row(pred_indices)=tree_table1(curr_term-1,arma::span(5,4+num_cats));\n\n\n\n        //Rcout << \"Line 588. \\n\";\n\n        // for(int k=0; k<num_cats; k++){\n        //   pred_mat(predind,k)=rep(treetable(curr_term-1,5+k),predind.size());\n        // }\n\n\n        // double denom_temp= pred_indices.n_elem+arma::sum(alpha_pars_arma);\n        // //Rcout << \"Line 207. predind = \" << predind <<  \".\\n\";\n        // //Rcout << \"Line 207. denom_temp = \" << denom_temp <<  \".\\n\";\n        // // << \"Line 207. term_node = \" << term_node <<  \".\\n\";\n        //\n        // double num_prod=1;\n        // double num_sum=0;\n        //\n        // for(int k=0; k<num_cats; k++){\n        //   //assuming categories of y are from 1 to num_cats\n        //   arma::uvec cat_inds= arma::find(orig_y_arma(pred_indices)==k+1);\n        //   double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n        //\n        //   arma_tree_table(curr_term-1,5+k)= m_plus_alph/denom_temp ;\n        //\n        //   num_prod=num_prod*tgamma(m_plus_alph);\n        //   num_sum=num_sum +m_plus_alph ;\n        // }\n\n\n        //lik_prod= lik_prod*alph_term*num_prod/tgamma(num_sum);\n\n\n      }\n    }\n\n\n\n\n\n\n    //THIS SHOULD BE DIFFERENT IF THE CODE IS TO BE PARALLELIZED\n    //EACH THREAD SHOULD OUTPUT ITS OWN MATRIX AND SUM OF LIKELIHOODS\n    //THEN ADD THE MATRICES TOGETHER AND DIVIDE BY THE TOTAL SUM OF LIKELIHOODS\n    //OR JUST SAVE ALL MATRICES TO ONE LIST\n\n    pred_mat_overall = pred_mat_overall + templik*pred_mat;\n\n\n\n\n    //arma::mat treeprob_output = get_test_probs(weights, num_cats,\n    //                                           testdata,\n    //                                           treetable_list[i]  );\n\n    //Rcout << \"Line 688. i== \" << i << \". \\n\";\n\n    //double weighttemp = weights[i];\n    //Rcout << \"Line 691. i== \" << i << \". \\n\";\n\n    //pred_mat_overall = pred_mat_overall + weighttemp*treeprob_output;\n\n\n\n  }//end of loop over all trees\n\n\n\n\n  ///////////////////////////////////////////////////////////////////////////////////////\n\n  /////////////////////////////////////////////////////////////////////////////////\n\n\n\n  double sumlik_total= sum(overall_liks);\n  pred_mat_overall=pred_mat_overall*(1/sumlik_total);\n  //Rcout << \"Line 1141 . \\n\";\n  //Rcout << \"Line 1146 . \\n\";\n\n  return(wrap(pred_mat_overall));\n\n}\n//######################################################################################################################//\n\n// [[Rcpp::depends(RcppArmadillo)]]\n//' @title Safe-Bayesian Random Forest in C++\n//'\n//' @description An implementation of the Safe-Bayesian Random Forest described by Quadrianto and Ghahramani (2015)\n//' @param lambda A real number between 0 and 1 that determines the splitting probability in the prior (which is used as the importance sampler of tree models). Quadrianto and Ghahramani (2015) recommend a value less than 0.5 .\n//' @param num_trees The number of trees to be sampled.\n//' @param seed The seed for random number generation.\n//' @param num_cats The number of possible values for the outcome variable.\n//' @param y The training data vector of outcomes. This must be a vector of integers between 1 and num_cats.\n//' @param original_datamat The original training data. Currently all variables must be continuous. The training data does not need to be transformed before being entered to this function.\n//' @param alpha_parameters Vector of prior parameters.\n//' @param beta_par The power to which the likelihood is to be raised. For BMA, set beta_par=1.\n//' @param original_datamat The original test data. This matrix must have the same number of columns (variables) as the training data. Currently all variables must be continuous. The test data does not need to be transformed before being entered to this function.\n//' @export\n// [[Rcpp::export]]\n\nNumericMatrix sBayesRF_onefunc_arma(double lambda, int num_trees,\n                                    int seed, int num_cats,\n                                    NumericVector y, NumericMatrix original_datamat,\n                                    NumericVector alpha_parameters, double beta_par,\n                                    NumericMatrix test_datamat){\n\n  int num_split_vars= original_datamat.ncol();\n  arma::mat data_arma= as<arma::mat>(original_datamat);\n  arma::mat testdata_arma= as<arma::mat>(test_datamat);\n  arma::vec orig_y_arma= as<arma::vec>(y);\n  arma::vec alpha_pars_arma= as<arma::vec>(alpha_parameters);\n\n  ///////////////////////\n  //NumericMatrix Data_transformed = cpptrans_cdf(original_datamat);\n  // NumericMatrix Data_transformed(original_datamat.nrow(), original_datamat.ncol());\n  // for(int i=0; i<original_datamat.ncol();i++){\n  //   NumericVector samp= original_datamat(_,i);\n  //   NumericVector sv(clone(samp));\n  //   std::sort(sv.begin(), sv.end());\n  //   double nobs = samp.size();\n  //   NumericVector ans(nobs);\n  //   for (int k = 0; k < samp.size(); ++k)\n  //     ans[k] = std::lower_bound(sv.begin(), sv.end(), samp[k]) - sv.begin();\n  //   //NumericVector ansnum = ans;\n  //   Data_transformed(_,i) = (ans+1)/nobs;\n  // }\n\n\n\n  //arma::mat arma_orig_data(Data_transformed.begin(), Data_transformed.nrow(), Data_transformed.ncol(), false);\n\n\n\n  //NumericMatrix transformedData(originaldata.nrow(), originaldata.ncol());\n\n  //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n  arma::mat arma_orig_data(data_arma.n_rows,data_arma.n_cols);\n  for(unsigned int k=0; k<data_arma.n_cols;k++){\n    arma::vec samp= data_arma.col(k);\n    arma::vec sv=arma::sort(samp);\n    //std::sort(sv.begin(), sv.end());\n    arma::uvec ord = arma::sort_index(samp);\n    double nobs = samp.n_elem;\n    arma::vec ans(nobs);\n    for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n      int ind=ord(i);\n      double ssampi(samp[ind]);\n      while (sv(j) < ssampi && j < sv.size()) ++j;\n      ans(ind) = j;     // j is the 1-based index of the lower bound\n    }\n    arma_orig_data.col(k)=(ans+1)/nobs;\n  }\n\n\n\n\n\n  /////////////////////////////////////\n  // NumericMatrix testdat_trans = cpptrans_cdf_test(original_datamat,test_datamat);\n  // //NumericMatrix testdat_trans(test_datamat.nrow(), test_datamat.ncol());\n  // for(int i=0; i<test_datamat.ncol();i++){\n  //   NumericVector samp= test_datamat(_,i);\n  //   NumericVector svtest = original_datamat(_,i);\n  //   NumericVector sv(clone(svtest));\n  //   std::sort(sv.begin(), sv.end());\n  //   double nobs = samp.size();\n  //   NumericVector ans(nobs);\n  //   double nobsref = svtest.size();\n  //   for (int k = 0; k < samp.size(); ++k){\n  //     ans[k] = std::lower_bound(sv.begin(), sv.end(), samp[k]) - sv.begin();\n  //   }\n  //   //NumericVector ansnum = ans;\n  //   testdat_trans(_,i) = (ans)/nobsref;\n  // }\n\n\n\n\n\n  //NumericMatrix transformedData(originaldata.nrow(), originaldata.ncol());\n  //arma::mat data_arma= as<arma::mat>(originaldata);\n\n  //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n  arma::mat arma_test_data(testdata_arma.n_rows,testdata_arma.n_cols);\n  for(unsigned int k=0; k<data_arma.n_cols;k++){\n    arma::vec ref= data_arma.col(k);\n    arma::vec samp= testdata_arma.col(k);\n\n    arma::vec sv=arma::sort(samp);\n    arma::vec sref=arma::sort(ref);\n\n    //std::sort(sv.begin(), sv.end());\n    arma::uvec ord = arma::sort_index(samp);\n    double nobs = samp.n_elem;\n    double nobsref = ref.n_elem;\n\n    arma::vec ans(nobs);\n    for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n      int ind=ord(i);\n      double ssampi(samp[ind]);\n      if(j+1>sref.size()){\n      }else{\n        while (sref(j) < ssampi && j < sref.size()){\n          ++j;\n          if(j==sref.size()) break;\n        }\n      }\n      ans(ind) = j;     // j is the 1-based index of the lower bound\n    }\n\n    arma_test_data.col(k)=(ans)/nobsref;\n\n  }\n\n\n\n\n\n\n\n  /////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n  //////////////////////////////////////////////////////////////////////////////////////\n  //List table_list = draw_trees(lambda, num_trees, seed, num_split_vars, num_cats );\n\n\n\n  //dqrng::dqRNGkind(\"Xoroshiro128+\");\n  //dqrng::dqset_seed(IntegerVector::create(seed));\n\n  //use following with binomial?\n  //dqrng::xoshiro256plus rng(seed);\n\n  //std::vector<int> lambdavec = {lambda, 1-lambda};\n\n  //typedef boost::mt19937 RNGType;\n  //boost::random::uniform_int_distribution<> sample_splitvardist(1,num_split_vars);\n  //boost::variate_generator< RNGType, boost::uniform_int<> >  sample_splitvars(rng, sample_splitvardist);\n\n  //boost::random::uniform_real_distribution<double> b_unifdist(0,1);\n  //boost::variate_generator< RNGType, boost::uniform_real<> >  b_unif_point(rng, b_unifdist);\n\n\n\n  std::random_device device;\n  std::mt19937 gen(device());\n\n  //possibly use seed?\n  //// std::mt19937 gen(seed);\n\n\n  std::bernoulli_distribution coin_flip(lambda);\n\n  std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n  std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n\n\n\n  //arma::mat arma_test_data(testdat_trans.begin(), testdat_trans.nrow(), testdat_trans.ncol(), false);\n\n\n  arma::mat pred_mat_overall=arma::zeros<arma::mat>(arma_test_data.n_rows,num_cats);\n\n\n  //List overall_treetables(num_trees);\n  arma::vec overall_liks(num_trees);\n\n\n  //overall_treetables[i]= wrap(tree_table1);\n  //double templik = as<double>(treepred_output[1]);\n  //overall_liks[i]= pow(lik_prod,beta_pow);\n\n\n\n  for(int j=0; j<num_trees;j++){\n\n    //If parallelizing, define the distributinos before this loop\n    //and use lrng and the following two lines\n    //dqrng::xoshiro256plus lrng(rng);      // make thread local copy of rng\n    //lrng.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... nthreads jumps\n\n\n    //NumericVector treenodes_bin(0);\n    //arma::uvec treenodes_bin(0);\n\n    std::vector<int> treenodes_bin;\n\n\n    int count_terminals = 0;\n    int count_internals = 0;\n\n    //int count_treebuild = 0;\n\n    while(count_internals > (count_terminals -1)){\n\n      //Also consider standard library and random header\n      // std::random_device device;\n      // std::mt19937 gen(device());\n      // std::bernoulli_distribution coin_flip(lambda);\n      // bool outcome = coin_flip(gen);\n\n\n      int tempdraw = coin_flip(gen);\n\n      //int tempdraw = rbinom(n = 1, prob = lambda,size=1);\n\n\n      //int tempdraw = Rcpp::rbinom(1,lambda,1);\n      //int tempdraw = R::rbinom(1,lambda);\n      treenodes_bin.push_back(tempdraw);\n\n      //Rcout << \"tempdraw = \" << tempdraw << \".\\n\" ;\n\n      //int tempdraw = dqrng::dqsample_int(2, 1, true,lambdavec )-1;\n      //need to update rng if use boost?\n      //int tempdraw = bernoulli(rng, binomial::param_type(1, lambda));\n      if(tempdraw==1){\n        count_internals=count_internals+1;\n      }else{\n        count_terminals=count_terminals+1;\n      }\n\n    }//end of while loop creating parent vector treenodes_bin\n\n    //Consider making this an armadillo vector\n    //IntegerVector split_var_vec(treenodes_bin.size());\n    //arma::uvec split_var_vec(treenodes_bin.size());\n    std::vector<int> split_var_vec(treenodes_bin.size());\n\n    //loop drawing splitting variables\n    //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n    //if using armadillo, it might be faster to subset to split nodes\n    //then use a vector of draws\n    for(unsigned int i=0; i<treenodes_bin.size();i++){\n      if(treenodes_bin[i]==0){\n        split_var_vec[i] = -1;\n      }else{\n        // also consider the standard library function uniform_int_distribution\n        // might need random header\n        // This uses the Mersenne twister\n\n        //Three lines below should probably be outside all the loops\n        // std::random_device rd;\n        // std::mt19937 engine(rd());\n        // std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n        //\n        // split_var_vec[i] = distsampvar(engine);\n\n        split_var_vec[i] = distsampvar(gen);\n\n\n        //consider using boost\n        //might need to update rng\n        //split_var_vec[i] <- sample_splitvars(rng);\n\n        //or use dqrng\n        //not sure if have to update the random number\n        //check if the following line is written properly\n        //split_var_vec[i] = dqrng::dqsample_int(num_split_vars, 1, true);\n\n        //not sure if this returns an integer or a vector?\n        //split_var_vec[i] = RcppArmadillo::sample(num_split_vars, 1,true);\n        //could try\n        //split_var_vec[i] = as<int>(Rcpp::sample(num_split_vars, 1,true));\n        //could also try RcppArmadillo::rmultinom\n\n      }\n\n    }// end of for-loop drawing split variables\n\n\n    //Consider making this an armadillo vector\n    //NumericVector split_point_vec(treenodes_bin.size());\n    //arma::vec split_point_vec(treenodes_bin.size());\n    std::vector<double> split_point_vec(treenodes_bin.size());\n\n\n    //loop drawing splitting points\n    //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n    //if using armadillo, it might be faster to subset to split nodes\n    //then use a vector of draws\n    for(unsigned int i=0; i<treenodes_bin.size();i++){\n      if(treenodes_bin[i]==0){\n        split_point_vec[i] = -1;\n      }else{\n\n\n        //////////////////////////////////////////////////////////\n        //following function not reccommended\n        //split_point_vec[i] = std::rand();\n        //////////////////////////////////////////////////////////\n        ////Standard library:\n        ////This should probably be outside all the loops\n        ////std::random_device rd;  //Will be used to obtain a seed for the random number engine\n        ////std::mt19937 gen2(rd()); //Standard mersenne_twister_engine seeded with rd()\n        ////std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n        split_point_vec[i] = dis_cont_unif(gen);\n\n        //////////////////////////////////////////////////////////\n        //from armadillo\n        //split_point_vec[i] = arma::randu();\n\n        //////////////////////////////////////////////////////////\n        //probably not adviseable for paralelization\n        //From Rcpp\n        //split_point_vec[i] = as<double>(Rcpp::runif(1,0,1));\n\n        //////////////////////////////////////////////////////////\n        //consider using boost\n        //might need to update rng\n        //split_point_vec[i] <- b_unif_point(rng);\n\n        //or use dqrng\n        //not sure if have to update the random number\n        //check if the following line is written properly\n        //split_point_vec[i] = dqrng::dqrunif(1, 0, 1);\n\n        //not sure if this returns an integer or a vector?\n\n\n\n\n\n      }\n\n    }// end of for-loop drawing split points\n\n\n    //Create tree table matrix\n\n    //NumericMatrix tree_table1(treenodes_bin.size(),5+num_cats);\n\n    //Rcout << \"Line 1037. \\n\";\n    //arma::mat tree_table1(treenodes_bin.size(),5+num_cats);\n\n    //initialize with zeros. Not sure if this is necessary\n    arma::mat tree_table1=arma::zeros<arma::mat>(treenodes_bin.size(),5+num_cats);\n    //Rcout << \"Line 1040. \\n\";\n\n\n    //tree_table1(_,2) = wrap(split_var_vec);\n    //tree_table1(_,3) = wrap(split_point_vec);\n    //tree_table1(_,4) = wrap(treenodes_bin);\n\n    //It might be more efficient to make everything an armadillo object initially\n    // but then would need to replace push_back etc with a different approach (but this might be more efficient anyway)\n    arma::colvec split_var_vec_arma=arma::conv_to<arma::colvec>::from(split_var_vec);\n    arma::colvec split_point_vec_arma(split_point_vec);\n    arma::colvec treenodes_bin_arma=arma::conv_to<arma::colvec>::from(treenodes_bin);\n\n\n    //Rcout << \"Line 1054. \\n\";\n\n    tree_table1.col(2) = split_var_vec_arma;\n    tree_table1.col(3) = split_point_vec_arma;\n    tree_table1.col(4) = treenodes_bin_arma;\n\n\n    //Rcout << \"Line 1061. j = \" << j << \". \\n\";\n\n\n\n    // Now start filling in left daughter and right daughter columns\n    std::vector<int> rd_spaces;\n    int prev_node = -1;\n\n    for(unsigned int i=0; i<treenodes_bin.size();i++){\n      //Rcout << \"Line 1061. i = \" << i << \". \\n\";\n      if(prev_node==0){\n        //tree_table1(rd_spaces[rd_spaces.size()-1], 1)=i;\n        //Rcout << \"Line 1073. j = \" << j << \". \\n\";\n\n        tree_table1(rd_spaces.back(), 1)=i+1;\n        //Rcout << \"Line 1076. j = \" << j << \". \\n\";\n\n        rd_spaces.pop_back();\n      }\n      if(treenodes_bin[i]==1){\n        //Rcout << \"Line 1081. j = \" << j << \". \\n\";\n\n        tree_table1(i,0) = i+2;\n        rd_spaces.push_back(i);\n        prev_node = 1;\n        //Rcout << \"Line 185. j = \" << j << \". \\n\";\n\n      }else{                  // These 2 lines unnecessary if begin with matrix of zeros\n        //Rcout << \"Line 1089. j = \" << j << \". \\n\";\n        tree_table1(i,0)=0 ;\n        tree_table1(i,1) = 0 ;\n        prev_node = 0;\n        //Rcout << \"Line 1093. j = \" << j << \". \\n\";\n\n      }\n    }//\n    //Rcout << \"Line 1097. j = \" << j << \". \\n\";\n\n\n\n\n\n    //List treepred_output = get_treepreds(original_y, num_cats, alpha_pars,\n    //                                     originaldata,\n    //                                     treetable_list[i]  );\n\n\n    //use armadillo object tree_table1\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n    double lik_prod=1;\n    double alph_prod=1;\n    for(unsigned int i=0; i<alpha_pars_arma.n_elem;i++){\n      alph_prod=alph_prod*tgamma(alpha_pars_arma(i));\n    }\n    double gam_alph_sum= tgamma(arma::sum(alpha_pars_arma));\n    double alph_term=gam_alph_sum/alph_prod;\n\n    //arma::mat arma_tree_table(treetable.begin(), treetable.nrow(), treetable.ncol(), false);\n    //arma::mat arma_orig_data(originaldata.begin(), originaldata.nrow(), originaldata.ncol(), false);\n\n\n    //arma::mat arma_tree(tree_data.begin(), tree_data.nrow(), tree_data.ncol(), false);\n    //arma::mat testd(test_data.begin(), test_data.nrow(), test_data.ncol(), false);\n\n    //NumericVector internal_nodes=find_internal_nodes_gs(tree_data);\n\n    //NumericVector terminal_nodes=find_term_nodes(treetable);\n\n    //arma::mat arma_tree(tree_table.begin(),tree_table.nrow(), tree_table.ncol(), false);\n\n    //arma::vec colmat=arma_tree.col(4);\n    //arma::uvec term_nodes=arma::find(colmat==-1);\n\n    //arma::vec colmat=arma_tree.col(2);\n    //arma::uvec term_nodes=arma::find(colmat==0);\n\n    arma::vec colmat=tree_table1.col(4);\n    arma::uvec term_nodes=arma::find(colmat==0);\n\n    term_nodes=term_nodes+1;\n\n    //NumericVector terminal_nodes= wrap(term_nodes);\n\n\n\n\n    //arma::vec arma_terminal_nodes=Rcpp::as<arma::vec>(terminal_nodes);\n    //NumericVector tree_predictions;\n\n    //now for each internal node find the observations that belong to the terminal nodes\n\n    //NumericVector predictions(test_data.nrow());\n    //List term_obs(term_nodes.n_elem);\n    if(term_nodes.n_elem==1){\n      //double nodemean=tree_data(terminal_nodes[0]-1,5);\t\t\t\t// let nodemean equal tree_data row terminal_nodes[i]^th row , 6th column. The minus 1 is because terminal nodes consists of indices starting at 1, but need indices to start at 0.\n      //predictions=rep(nodemean,test_data.nrow());\n      //Rcout << \"Line 67 .\\n\";\n\n      //IntegerVector temp_obsvec = seq_len(test_data.nrow())-1;\n      //term_obs[0]= temp_obsvec;\n      double denom_temp= orig_y_arma.n_elem+arma::sum(alpha_pars_arma);\n\n      double num_prod=1;\n      double num_sum=0;\n      //Rcout << \"Line 129.\\n\";\n\n      for(int k=0; k<num_cats; k++){\n        //assuming categories of y are from 1 to num_cats\n        arma::uvec cat_inds= arma::find(orig_y_arma==k+1);\n        double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n        tree_table1(0,5+k)= m_plus_alph/denom_temp ;\n\n        //for likelihood calculation\n        num_prod=num_prod*tgamma(m_plus_alph);\n        num_sum=num_sum +m_plus_alph ;\n      }\n\n      lik_prod= alph_term*num_prod/tgamma(num_sum);\n\n    }\n    else{\n      for(unsigned int i=0;i<term_nodes.n_elem;i++){\n        //arma::mat subdata=testd;\n        int curr_term=term_nodes(i);\n\n        int row_index;\n        int term_node=term_nodes(i);\n        //Rcout << \"Line 152.\\n\";\n\n\n        //WHAT IS THE PURPOSE OF THIS IF-STATEMENT?\n        //Why should the ro index be different for a right daughter?\n        //Why not just initialize row_index to any number not equal to 1 (e.g. 0)?\n        row_index=0;\n\n        // if(curr_term % 2==0){\n        //   //term node is left daughter\n        //   row_index=terminal_nodes[i];\n        // }else{\n        //   //term node is right daughter\n        //   row_index=terminal_nodes[i]-1;\n        // }\n\n\n\n\n        //save the left and right node data into arma uvec\n\n        //CHECK THAT THIS REFERS TO THE CORRECT COLUMNS\n        //arma::vec left_nodes=arma_tree.col(0);\n        //arma::vec right_nodes=arma_tree.col(1);\n\n        arma::vec left_nodes=tree_table1.col(0);\n        arma::vec right_nodes=tree_table1.col(1);\n\n\n\n        arma::mat node_split_mat;\n        node_split_mat.set_size(0,3);\n        //Rcout << \"Line 182. i = \" << i << \" .\\n\";\n\n        while(row_index!=1){\n          //for each terminal node work backwards and see if the parent node was a left or right node\n          //append split info to a matrix\n          int rd=0;\n          arma::uvec parent_node=arma::find(left_nodes == term_node);\n\n          if(parent_node.size()==0){\n            parent_node=arma::find(right_nodes == term_node);\n            rd=1;\n          }\n\n          //want to cout parent node and append to node_split_mat\n\n          node_split_mat.insert_rows(0,1);\n\n          //CHECK THAT COLUMNS OF TREETABLE ARE CORRECT\n          //node_split_mat(0,0)=treetable(parent_node[0],2);\n          //node_split_mat(0,1)=treetable(parent_node[0],3);\n\n          //node_split_mat(0,0)=arma_tree_table(parent_node[0],3);\n          //node_split_mat(0,1)=arma_tree_table(parent_node[0],4);\n\n          node_split_mat(0,0)=tree_table1(parent_node(0),2);\n          node_split_mat(0,1)=tree_table1(parent_node(0),3);\n\n          node_split_mat(0,2)=rd;\n          row_index=parent_node(0)+1;\n          term_node=parent_node(0)+1;\n        }\n\n        //once we have the split info, loop through rows and find the subset indexes for that terminal node!\n        //then fill in the predicted value for that tree\n        //double prediction = tree_data(term_node,5);\n        arma::uvec pred_indices;\n        int split= node_split_mat(0,0)-1;\n\n        //Rcout << \"Line 224.\\n\";\n        //Rcout << \"split = \" << split << \".\\n\";\n        //arma::vec tempvec = testd.col(split);\n        arma::vec tempvec = arma_orig_data.col(split);\n        //Rcout << \"Line 227.\\n\";\n\n\n        double temp_split = node_split_mat(0,1);\n\n        if(node_split_mat(0,2)==0){\n          pred_indices = arma::find(tempvec <= temp_split);\n        }else{\n          pred_indices = arma::find(tempvec > temp_split);\n        }\n        //Rcout << \"Line 236.\\n\";\n\n        arma::uvec temp_pred_indices;\n\n        //arma::vec data_subset = testd.col(split);\n        arma::vec data_subset = arma_orig_data.col(split);\n\n        data_subset=data_subset.elem(pred_indices);\n\n        //now loop through each row of node_split_mat\n        int n=node_split_mat.n_rows;\n        //Rcout << \"Line 174. i = \" << i << \". n = \" << n << \".\\n\";\n        //Rcout << \"Line 248.\\n\";\n\n        for(int j=1;j<n;j++){\n          int curr_sv=node_split_mat(j,0);\n          double split_p = node_split_mat(j,1);\n\n          //data_subset = testd.col(curr_sv-1);\n          //Rcout << \"Line 255.\\n\";\n          //Rcout << \"curr_sv = \" << curr_sv << \".\\n\";\n          data_subset = arma_orig_data.col(curr_sv-1);\n          //Rcout << \"Line 258.\\n\";\n\n          data_subset=data_subset.elem(pred_indices);\n\n          if(node_split_mat(j,2)==0){\n            //split is to the left\n            temp_pred_indices=arma::find(data_subset <= split_p);\n          }else{\n            //split is to the right\n            temp_pred_indices=arma::find(data_subset > split_p);\n          }\n          pred_indices=pred_indices.elem(temp_pred_indices);\n\n          if(pred_indices.size()==0){\n            continue;\n          }\n\n        }\n        //Rcout << \"Line 199. i = \" << i <<  \".\\n\";\n\n        //double nodemean=tree_data(terminal_nodes[i]-1,5);\n        //IntegerVector predind=as<IntegerVector>(wrap(pred_indices));\n        //predictions[predind]= nodemean;\n        //term_obs[i]=predind;\n\n        double denom_temp= pred_indices.n_elem+arma::sum(alpha_pars_arma);\n        //Rcout << \"Line 207. predind = \" << predind <<  \".\\n\";\n        //Rcout << \"Line 207. denom_temp = \" << denom_temp <<  \".\\n\";\n        // << \"Line 207. term_node = \" << term_node <<  \".\\n\";\n\n        double num_prod=1;\n        double num_sum=0;\n\n        for(int k=0; k<num_cats; k++){\n          //assuming categories of y are from 1 to num_cats\n          arma::uvec cat_inds= arma::find(orig_y_arma(pred_indices)==k+1);\n          double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n\n          tree_table1(curr_term-1,5+k)= m_plus_alph/denom_temp ;\n\n          num_prod=num_prod*tgamma(m_plus_alph);\n          num_sum=num_sum +m_plus_alph ;\n        }\n\n\n        lik_prod= lik_prod*alph_term*num_prod/tgamma(num_sum);\n        //Rcout << \"Line 297.\\n\";\n\n\n      }\n      //Rcout << \"Line 301.\\n\";\n\n    }\n    //List ret(1);\n    //ret[0] = term_obs;\n\n    //ret[0] = terminal_nodes;\n    //ret[1] = term_obs;\n    //ret[2] = predictions;\n    //return(term_obs);\n    //Rcout << \"Line 309\";\n\n    //return(wrap(arma_tree_table));\n\n    //List ret(2);\n    //ret[0]=wrap(arma_tree_table);\n    //ret[1]=lik_prod;\n\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n\n\n\n    //overall_treetables[j]= wrap(tree_table1);\n\n\n    //double templik = as<double>(treepred_output[1]);\n\n    double templik = pow(lik_prod,beta_par);\n    overall_liks(j)= templik;\n\n\n\n\n\n\n    //arma::mat arma_tree_table(treetable.begin(), treetable.nrow(), treetable.ncol(), false);\n    //arma::mat arma_test_data(testdata.begin(), testdata.nrow(), testdata.ncol(), false);\n\n\n    //arma::mat arma_tree(tree_data.begin(), tree_data.nrow(), tree_data.ncol(), false);\n    //arma::mat testd(test_data.begin(), test_data.nrow(), test_data.ncol(), false);\n\n    //NumericVector internal_nodes=find_internal_nodes_gs(tree_data);\n\n    //NumericVector terminal_nodes=find_term_nodes(treetable);\n    //arma::vec arma_terminal_nodes=Rcpp::as<arma::vec>(terminal_nodes);\n    //NumericVector tree_predictions;\n\n    //now for each internal node find the observations that belong to the terminal nodes\n\n    //NumericVector predictions(test_data.nrow());\n\n    arma::mat pred_mat(testdata_arma.n_rows,num_cats);\n    //arma::vec filled_in(testdata.nrow());\n\n\n    //List term_obs(terminal_nodes.size());\n    if(term_nodes.size()==1){\n\n      //Rcout << \"Line 422. \\n\";\n\n\n      pred_mat=repmat(tree_table1(0,arma::span(5,5+num_cats-1)),testdata_arma.n_rows,1);\n\n\n      //Rcout << \"Line 424. \\n\";\n\n\n      // for(int k=0; k<num_cats; k++){\n      // pred_mat(_,k)=rep(treetable(0,5+k),testdata.nrow());\n      // }\n      //double nodemean=tree_data(terminal_nodes[0]-1,5);\t\t\t\t// let nodemean equal tree_data row terminal_nodes[i]^th row , 6th column. The minus 1 is because terminal nodes consists of indices starting at 1, but need indices to start at 0.\n      //predictions=rep(nodemean,test_data.nrow());\n      //Rcout << \"Line 67 .\\n\";\n\n      //IntegerVector temp_obsvec = seq_len(test_data.nrow())-1;\n      //term_obs[0]= temp_obsvec;\n      // double denom_temp= orig_y_arma.n_elem+arma::sum(alpha_pars_arma);\n      //\n      // double num_prod=1;\n      // double num_sum=0;\n\n      // for(int k=0; k<num_cats; k++){\n      //   //assuming categories of y are from 1 to num_cats\n      //   arma::uvec cat_inds= arma::find(orig_y_arma==k+1);\n      //   double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n      //   arma_tree_table(0,5+k)= m_plus_alph/denom_temp ;\n      //\n      //   //for likelihood calculation\n      //   num_prod=num_prod*tgamma(m_plus_alph);\n      //   num_sum=num_sum +m_plus_alph ;\n      // }\n      //\n      // lik_prod= alph_term*num_prod/tgamma(num_sum);\n      //\n    }\n    else{\n      for(unsigned int i=0;i<term_nodes.size();i++){\n        //arma::mat subdata=testd;\n        int curr_term=term_nodes(i);\n\n        int row_index;\n        int term_node=term_nodes(i);\n\n\n        //WHAT IS THE PURPOSE OF THIS IF-STATEMENT?\n        //Why should the ro index be different for a right daughter?\n        //Why not just initialize row_index to any number not equal to 1 (e.g. 0)?\n        row_index=0;\n\n        // if(curr_term % 2==0){\n        //   //term node is left daughter\n        //   row_index=terminal_nodes[i];\n        // }else{\n        //   //term node is right daughter\n        //   row_index=terminal_nodes[i]-1;\n        // }\n\n\n\n\n\n\n\n\n        //save the left and right node data into arma uvec\n\n        //CHECK THAT THIS REFERS TO THE CORRECT COLUMNS\n        //arma::vec left_nodes=arma_tree.col(0);\n        //arma::vec right_nodes=arma_tree.col(1);\n\n        arma::vec left_nodes=tree_table1.col(0);\n        arma::vec right_nodes=tree_table1.col(1);\n\n\n\n        arma::mat node_split_mat;\n        node_split_mat.set_size(0,3);\n        //Rcout << \"Line 124. i = \" << i << \" .\\n\";\n\n        while(row_index!=1){\n          //for each terminal node work backwards and see if the parent node was a left or right node\n          //append split info to a matrix\n          int rd=0;\n          arma::uvec parent_node=arma::find(left_nodes == term_node);\n\n          if(parent_node.size()==0){\n            parent_node=arma::find(right_nodes == term_node);\n            rd=1;\n          }\n\n          //want to cout parent node and append to node_split_mat\n\n          node_split_mat.insert_rows(0,1);\n\n          //CHECK THAT COLUMNS OF TREETABLE ARE CORRECT\n          //node_split_mat(0,0)=treetable(parent_node[0],2);\n          //node_split_mat(0,1)=treetable(parent_node[0],3);\n\n          //node_split_mat(0,0)=arma_tree_table(parent_node[0],3);\n          //node_split_mat(0,1)=arma_tree_table(parent_node[0],4);\n\n          node_split_mat(0,0)=tree_table1(parent_node(0),2);\n          node_split_mat(0,1)=tree_table1(parent_node(0),3);\n\n          node_split_mat(0,2)=rd;\n          row_index=parent_node(0)+1;\n          term_node=parent_node(0)+1;\n        }\n\n        //once we have the split info, loop through rows and find the subset indexes for that terminal node!\n        //then fill in the predicted value for that tree\n        //double prediction = tree_data(term_node,5);\n        arma::uvec pred_indices;\n        int split= node_split_mat(0,0)-1;\n\n        //arma::vec tempvec = testd.col(split);\n        arma::vec tempvec = arma_test_data.col(split);\n\n\n        double temp_split = node_split_mat(0,1);\n\n        if(node_split_mat(0,2)==0){\n          pred_indices = arma::find(tempvec <= temp_split);\n        }else{\n          pred_indices = arma::find(tempvec > temp_split);\n        }\n\n        arma::uvec temp_pred_indices;\n\n        //arma::vec data_subset = testd.col(split);\n        arma::vec data_subset = arma_test_data.col(split);\n\n        data_subset=data_subset.elem(pred_indices);\n\n        //now loop through each row of node_split_mat\n        int n=node_split_mat.n_rows;\n        //Rcout << \"Line 174. i = \" << i << \". n = \" << n << \".\\n\";\n        //Rcout << \"Line 174. node_split_mat= \" << node_split_mat << \". n = \" << n << \".\\n\";\n\n\n        for(int j=1;j<n;j++){\n          int curr_sv=node_split_mat(j,0);\n          double split_p = node_split_mat(j,1);\n\n          //data_subset = testd.col(curr_sv-1);\n          data_subset = arma_test_data.col(curr_sv-1);\n\n          data_subset=data_subset.elem(pred_indices);\n\n          if(node_split_mat(j,2)==0){\n            //split is to the left\n            temp_pred_indices=arma::find(data_subset <= split_p);\n          }else{\n            //split is to the right\n            temp_pred_indices=arma::find(data_subset > split_p);\n          }\n          pred_indices=pred_indices.elem(temp_pred_indices);\n\n          if(pred_indices.size()==0){\n            continue;\n          }\n\n        }\n        //Rcout << \"Line 199. i = \" << i <<  \".\\n\";\n\n        //double nodemean=tree_data(terminal_nodes[i]-1,5);\n        //IntegerVector predind=as<IntegerVector>(wrap(pred_indices));\n        //predictions[predind]= nodemean;\n        //term_obs[i]=predind;\n\n        //Rcout << \"Line 635. \\n\";\n        //Rcout << \"pred_indices = \" << pred_indices << \".\\n\";\n\n        //pred_mat.rows(pred_indices)=arma::repmat(arma_tree_table(curr_term-1,arma::span(5,5+num_cats-1)),pred_indices.n_elem,1);\n        pred_mat.each_row(pred_indices)=tree_table1(curr_term-1,arma::span(5,4+num_cats));\n\n\n\n        //Rcout << \"Line 588. \\n\";\n\n        // for(int k=0; k<num_cats; k++){\n        //   pred_mat(predind,k)=rep(treetable(curr_term-1,5+k),predind.size());\n        // }\n\n\n        // double denom_temp= pred_indices.n_elem+arma::sum(alpha_pars_arma);\n        // //Rcout << \"Line 207. predind = \" << predind <<  \".\\n\";\n        // //Rcout << \"Line 207. denom_temp = \" << denom_temp <<  \".\\n\";\n        // // << \"Line 207. term_node = \" << term_node <<  \".\\n\";\n        //\n        // double num_prod=1;\n        // double num_sum=0;\n        //\n        // for(int k=0; k<num_cats; k++){\n        //   //assuming categories of y are from 1 to num_cats\n        //   arma::uvec cat_inds= arma::find(orig_y_arma(pred_indices)==k+1);\n        //   double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n        //\n        //   arma_tree_table(curr_term-1,5+k)= m_plus_alph/denom_temp ;\n        //\n        //   num_prod=num_prod*tgamma(m_plus_alph);\n        //   num_sum=num_sum +m_plus_alph ;\n        // }\n\n\n        //lik_prod= lik_prod*alph_term*num_prod/tgamma(num_sum);\n\n\n      }\n    }\n\n\n\n\n\n\n    //THIS SHOULD BE DIFFERENT IF THE CODE IS TO BE PARALLELIZED\n    //EACH THREAD SHOULD OUTPUT ITS OWN MATRIX AND SUM OF LIKELIHOODS\n    //THEN ADD THE MATRICES TOGETHER AND DIVIDE BY THE TOTAL SUM OF LIKELIHOODS\n    //OR JUST SAVE ALL MATRICES TO ONE LIST\n\n    pred_mat_overall = pred_mat_overall + templik*pred_mat;\n\n\n\n\n    //arma::mat treeprob_output = get_test_probs(weights, num_cats,\n    //                                           testdata,\n    //                                           treetable_list[i]  );\n\n    //Rcout << \"Line 688. i== \" << i << \". \\n\";\n\n    //double weighttemp = weights[i];\n    //Rcout << \"Line 691. i== \" << i << \". \\n\";\n\n    //pred_mat_overall = pred_mat_overall + weighttemp*treeprob_output;\n\n\n\n  }//end of loop over all trees\n\n\n\n\n  ///////////////////////////////////////////////////////////////////////////////////////\n\n  /////////////////////////////////////////////////////////////////////////////////\n\n\n\n  double sumlik_total= arma::sum(overall_liks);\n  pred_mat_overall=pred_mat_overall*(1/sumlik_total);\n  //Rcout << \"Line 1141 . \\n\";\n  //Rcout << \"Line 1146 . \\n\";\n\n  return(wrap(pred_mat_overall));\n\n}\n//######################################################################################################################//\n\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::depends(dqrng, BH, sitmo)]]\n\n\n#include <xoshiro.h>\n#include <dqrng_distribution.h>\n//#include <dqrng.h>\n\n// [[Rcpp::plugins(openmp)]]\n#include <omp.h>\n\n//' @title Parallel Safe-BART\n//'\n//' @description A parallelized implementation of safe-Bayesian Additive Regression Trees\n//' @param lambda A real number between 0 and 1 that determines the splitting probability in the prior (which is used as the importance sampler of tree models). Quadrianto and Ghahramani (2015) recommend a value less than 0.5 .\n//' @param num_trees The number of trees to be sampled.\n//' @param seed The seed for random number generation.\n//' @param num_cats The number of possible values for the outcome variable.\n//' @param y The training data vector of outcomes. This must be a vector of integers between 1 and num_cats.\n//' @param original_datamat The original training data. Currently all variables must be continuous. The training data does not need to be transformed before being entered to this function.\n//' @param alpha_parameters Vector of prior parameters.\n//' @param beta_par The power to which the likelihood is to be raised. For BMA, set beta_par=1.\n//' @param original_datamat The original test data. This matrix must have the same number of columns (variables) as the training data. Currently all variables must be continuous. The test data does not need to be transformed before being entered to this function.\n//' @param ncores The number of cores to be used in parallelization.\n//' @return A vector of out-of-sample predictions.\n//' @export\n// [[Rcpp::export]]\nNumericVector sBART_onefunc_parallel(double lambda,\n                                     int num_models,\n                                     int num_trees,\n                                        int seed,\n                                        NumericVector ytrain,\n                                        NumericMatrix original_datamat,\n                                        double beta_par,\n                                        NumericMatrix test_datamat,\n                                        int ncores,\n                                        int outsamppreds,\n                                        double nu,\n                                        double a,\n                                        double lambdaBART,\n                                        int valid_trees,\n                                        int tree_prior,\n                                        int imp_sampler,\n                                        double alpha_BART,\n                                        double beta_BART,\n                                        int s_t_hyperprior,\n                                        double p_s_t,\n                                        double a_s_t,\n                                        double b_s_t,\n                                        double lambda_poisson,\n                                        int fast_approx){\n\n\n  //Rcout << \"imp_sampler = \" << imp_sampler << \".\\n\";\n\n  NumericVector y_scaled=scale_response(min(ytrain),max(ytrain),-0.5,0.5,ytrain);\n\n  int num_split_vars= original_datamat.ncol();\n  arma::mat data_arma= as<arma::mat>(original_datamat);\n  arma::mat testdata_arma= as<arma::mat>(test_datamat);\n  arma::vec orig_y_arma= as<arma::vec>(y_scaled);\n  //arma::vec alpha_pars_arma= as<arma::vec>(alpha_parameters);\n  int num_obs = data_arma.n_rows;\n  int num_test_obs = testdata_arma.n_rows;\n\n  int num_vars = data_arma.n_cols;\n\n  //calculations for likelihood\n  arma::mat y(num_obs,1);\n  y.col(0)=orig_y_arma;\n  //get exponent\n  double expon=(num_obs+nu)*0.5;\n  //get y^Tpsi^{-1}y\n  // arma::mat psi_inv=psi.i();\n  arma::mat yty=y.t()*y;\n\n\n  ///////////////////////\n  //NumericMatrix Data_transformed = cpptrans_cdf(original_datamat);\n  // NumericMatrix Data_transformed(original_datamat.nrow(), original_datamat.ncol());\n  // for(int i=0; i<original_datamat.ncol();i++){\n  //   NumericVector samp= original_datamat(_,i);\n  //   NumericVector sv(clone(samp));\n  //   std::sort(sv.begin(), sv.end());\n  //   double nobs = samp.size();\n  //   NumericVector ans(nobs);\n  //   for (int k = 0; k < samp.size(); ++k)\n  //     ans[k] = std::lower_bound(sv.begin(), sv.end(), samp[k]) - sv.begin();\n  //   //NumericVector ansnum = ans;\n  //   Data_transformed(_,i) = (ans+1)/nobs;\n  // }\n\n\n\n  //arma::mat arma_orig_data(Data_transformed.begin(), Data_transformed.nrow(), Data_transformed.ncol(), false);\n\n\n\n  //NumericMatrix transformedData(originaldata.nrow(), originaldata.ncol());\n\n  //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n  arma::mat arma_orig_data(data_arma.n_rows,data_arma.n_cols);\n  for(unsigned int k=0; k<data_arma.n_cols;k++){\n    arma::vec samp= data_arma.col(k);\n    arma::vec sv=arma::sort(samp);\n    //std::sort(sv.begin(), sv.end());\n    arma::uvec ord = arma::sort_index(samp);\n    double nobs = samp.n_elem;\n    arma::vec ans(nobs);\n    for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n      int ind=ord(i);\n      double ssampi(samp[ind]);\n      while (sv(j) < ssampi && j < sv.size()) ++j;\n      ans(ind) = j;     // j is the 1-based index of the lower bound\n    }\n    arma_orig_data.col(k)=(ans+1)/nobs;\n  }\n\n\n\n\n\n  /////////////////////////////////////\n  // NumericMatrix testdat_trans = cpptrans_cdf_test(original_datamat,test_datamat);\n  // //NumericMatrix testdat_trans(test_datamat.nrow(), test_datamat.ncol());\n  // for(int i=0; i<test_datamat.ncol();i++){\n  //   NumericVector samp= test_datamat(_,i);\n  //   NumericVector svtest = original_datamat(_,i);\n  //   NumericVector sv(clone(svtest));\n  //   std::sort(sv.begin(), sv.end());\n  //   double nobs = samp.size();\n  //   NumericVector ans(nobs);\n  //   double nobsref = svtest.size();\n  //   for (int k = 0; k < samp.size(); ++k){\n  //     ans[k] = std::lower_bound(sv.begin(), sv.end(), samp[k]) - sv.begin();\n  //   }\n  //   //NumericVector ansnum = ans;\n  //   testdat_trans(_,i) = (ans)/nobsref;\n  // }\n\n\n\n\n\n  //NumericMatrix transformedData(originaldata.nrow(), originaldata.ncol());\n  //arma::mat data_arma= as<arma::mat>(originaldata);\n\n  //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n  arma::mat arma_test_data(testdata_arma.n_rows,testdata_arma.n_cols);\n  for(unsigned int k=0; k<data_arma.n_cols;k++){\n    arma::vec ref= data_arma.col(k);\n    arma::vec samp= testdata_arma.col(k);\n\n    arma::vec sv=arma::sort(samp);\n    arma::vec sref=arma::sort(ref);\n\n    //std::sort(sv.begin(), sv.end());\n    arma::uvec ord = arma::sort_index(samp);\n    double nobs = samp.n_elem;\n    double nobsref = ref.n_elem;\n\n    arma::vec ans(nobs);\n    for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n      int ind=ord(i);\n      double ssampi(samp[ind]);\n      if(j+1>sref.size()){\n      }else{\n        while (sref(j) < ssampi && j < sref.size()){\n          ++j;\n          if(j==sref.size()) break;\n        }\n      }\n      ans(ind) = j;     // j is the 1-based index of the lower bound\n    }\n\n    arma_test_data.col(k)=(ans)/nobsref;\n\n  }\n\n\n\n\n\n\n\n  /////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n  //////////////////////////////////////////////////////////////////////////////////////\n  //List table_list = draw_trees(lambda, num_trees, seed, num_split_vars, num_cats );\n\n\n\n  //dqrng::dqRNGkind(\"Xoroshiro128+\");\n  //dqrng::dqset_seed(IntegerVector::create(seed));\n\n  //use following with binomial?\n  //dqrng::xoshiro256plus rng(seed);\n\n  std::vector<double> lambdavec = {lambda, 1-lambda};\n\n  //typedef boost::mt19937 RNGType;\n  //boost::random::uniform_int_distribution<> sample_splitvardist(1,num_split_vars);\n  //boost::variate_generator< RNGType, boost::uniform_int<> >  sample_splitvars(rng, sample_splitvardist);\n\n  //boost::random::uniform_real_distribution<double> b_unifdist(0,1);\n  //boost::variate_generator< RNGType, boost::uniform_real<> >  b_unif_point(rng, b_unifdist);\n\n\n\n  std::random_device device;\n  //std::mt19937 gen(device());\n\n  //possibly use seed?\n  //// std::mt19937 gen(seed);\n\n  dqrng::xoshiro256plus gen(device());              // properly seeded rng\n\n  //dqrng::xoshiro256plus gen(seed);              // properly seeded rng\n\n\n\n\n  std::bernoulli_distribution coin_flip(lambda);\n\n\n  std::bernoulli_distribution coin_flip_even(0.5);\n\n  double spike_prob1;\n  if(s_t_hyperprior==1){\n    spike_prob1=a_s_t/(a_s_t + b_s_t);\n  }else{\n    spike_prob1=p_s_t;\n  }\n\n  std::bernoulli_distribution coin_flip_spike(spike_prob1);\n\n\n  std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n  std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n  std::poisson_distribution<int> gen_num_term(lambda_poisson);\n\n\n  //dqrng::uniform_distribution dis_cont_unif(0.0, 1.0); // Uniform distribution [0,1)\n\n  //Following three functions can't be used in parallel\n  //dqrng::dqsample_int coin_flip2(2, 1, true,lambdavec );\n  //dqrng::dqsample_int distsampvar(num_split_vars, 1, true);\n  //dqrng::dqrunif dis_cont_unif(1, 0, 1);\n\n\n\n  //arma::mat arma_test_data(testdat_trans.begin(), testdat_trans.nrow(), testdat_trans.ncol(), false);\n\n\n  arma::vec pred_vec_overall=arma::zeros<arma::vec>(arma_test_data.n_rows);\n\n\n  //arma::field<arma::mat> overall_treetables(num_models);\n\n  arma::field<arma::vec> overall_preds(num_models);\n\n  arma::vec overall_liks(num_models);\n\n\n  //overall_treetables[i]= wrap(tree_table1);\n  //double templik = as<double>(treepred_output[1]);\n  //overall_liks[i]= pow(lik_prod,beta_pow);\n\n  //Rcout << \"Line 3338. \\n\";\n\n\n#pragma omp parallel num_threads(ncores)\n{//start of pragma omp code\n  dqrng::xoshiro256plus lgen(gen);      // make thread local copy of rng\n  lgen.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... ncores jumps\n\n#pragma omp for\n  for(int j=0; j<num_models;j++){\n\n    arma::mat Wmat(num_obs,0);\n\n    //maybe use line below, depends how Jmat joined to Wmat\n    //int upsilon=0;\n\n    arma::mat W_tilde(num_test_obs,0);\n\n    //maybe use line below, depends how Jmat joined to Wmat\n    //int upsilon2=0;\n\n    //double sum_tree_samp_prob=1;\n    //double sum_tree_prior_prob=1;\n\n    double sum_prior_over_samp_prob=1;\n\n    for(int q=0; q<num_trees;q++){  //start of loop over trees in sum\n\n\n    //If parallelizing, define the distributinos before this loop\n    //and use lrng and the following two lines\n    //dqrng::xoshiro256plus lrng(rng);      // make thread local copy of rng\n    //lrng.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... nthreads jumps\n\n\n    //NumericVector treenodes_bin(0);\n    //arma::uvec treenodes_bin(0);\n\n    std::vector<int> treenodes_bin;\n    std::vector<int> split_var_vec;\n\n\n    int count_terminals = 0;\n    int count_internals = 0;\n\n    //int count_treebuild = 0;\n\n    if(imp_sampler==2){ // If sampling from SPike and Tree\n\n      //Rcout << \"Line 3737 .\\n\";\n\n\n      //make coinflip_spike before loop\n      //also make bernoulli with probability 0.5\n\n      //make a poisson distribtion\n\n\n      //might be easier to store indices as armadillo vector, because will have to remove\n      //potential splits when allocating to terminal nodes\n      std::vector<int> potentialsplitvars;\n\n      for(int varcount=0; varcount<num_vars;varcount++){\n        bool tempflip=coin_flip_spike(lgen);\n        if(tempflip==TRUE){\n          potentialsplitvars.push_back(varcount);\n        }\n      }\n\n      //Then draw number of terminal nodes from a truncated Poisson\n      //must be at least equal to number of potential splitting variables plus 1\n      int q_numsplitvars=potentialsplitvars.size();\n\n      int num_term_nodes_draw;\n      if(q_numsplitvars==0){\n        //num_term_nodes_draw==1;\n        treenodes_bin.push_back(0);\n        split_var_vec.push_back(0);\n      }else{\n        do{\n          num_term_nodes_draw = gen_num_term(lgen);//Poissondraw\n        }\n        while(num_term_nodes_draw<q_numsplitvars+1); //Check if enough terminal nodes. If not, take another draw\n\n\n          //Now draw a tree with num_term_nodes_draw terminal nodes\n          //Use Remy's algorithm or the algorithm described by Bacher et al.\n\n          //Rcout << \"Line 3771 .\\n\";\n\n        long length=(num_term_nodes_draw-1)*2;\n        //Rcout << \"Line 3774 .\\n\";\n\n        std::vector<int> treenodes_bintemp(length+1);\n        int p_ind=0;\n        long height = 0;\n\n        //Rcout << \"Line 195. \\n\";\n        //Rcout << \"Line 3781 .\\n\";\n        //Rcout << \"q_numsplitvars = \" << q_numsplitvars << \".\\n\";\n\n        for(long i = 0; i < length+1; i ++) {\n          //signed char x = random_int(1) ? 1 : -1;\n          int x = coin_flip_even(lgen) ? 1 : -1;\n          treenodes_bintemp[i] = x;\n          height += x;\n\n          if(height < 0) {\n            // this should return a uniform random integer between 0 and x\n            //unsigned long random_int(unsigned long x);\n            std::uniform_int_distribution<> random_int(0, i);\n            long j = random_int(lgen);\n            //long j = random_int(i);\n            //height += unfold(p_ind + j,treenodes_bintemp, i + 1 - j);\n\n            long length1=i+1-j;\n            long height1 = 0;\n            long local_height = 0;\n            int x = 1;\n\n            for(long i = 0; i < length1; i ++) {\n              int y = treenodes_bintemp[p_ind+j+i];\n              local_height += y;\n              if(local_height < 0) {\n                y = 1;\n                height1 += 2;\n                local_height = 0;\n              }\n              treenodes_bintemp[p_ind+j+i] = x;\n              x = y;\n            }\n            height +=height1;\n\n\n\n\n          }\n        }\n\n        //Rcout << \"Line 213. \\n\";\n        //Rcout << \"Line 3822 .\\n\";\n\n\n        //fold(treenodes_bintemp, length + 1, height);\n        long local_height = 0;\n        int x = -1;\n        ////Rcout << \"Line 121. \\n\";\n        //Rcout << \"treenodes_bintemp.size() =\" << treenodes_bintemp.size() << \". \\n\";\n        //Rcout << \"length - 1 =\" << length - 1 << \". \\n\";\n\n\n        for(long i = length; height > 0; i --) {\n          int y = treenodes_bintemp[i];\n          local_height -= y;\n          if(local_height < 0) {\n            y = -1;\n            height -= 2;\n            local_height = 0;\n          }\n          treenodes_bintemp[i] = x;\n          x = y;\n        }\n        //Rcout << \"Line 134. \\n\";\n\n\n        //Rcout << \"Line 217. \\n\";\n        //Rcout << \"Line 3847 .\\n\";\n\n        //Rcout << \"Line 238. \\n\";\n        std::replace(treenodes_bintemp.begin(), treenodes_bintemp.end(), -1, 0); // 10 99 30 30 99 10 10 99\n\n\n        // Then store tree structure as treenodes_bintemp\n\n        //create splitting variable vector\n        std::vector<int> splitvar_vectemp(treenodes_bintemp.size());\n\n        std::vector<int> drawnvarstemp(num_term_nodes_draw-1);\n\n        //keep count of how many splitting points have been filled in\n        int splitcount=0;\n\n        //loop through nodes, filling in splitting variables for nonterminal nodes\n        //when less than q_numsplitvars remaining internal nodes to be filled in\n        //have to start reducing the set of potential splitting variables\n        //to ensure that each selected potential split variable is used at least once. [hence the if statement containing .erase]\n\n        int index_remaining=0;\n        for(unsigned int nodecount=0; nodecount<treenodes_bintemp.size();nodecount++){\n          if(treenodes_bintemp[nodecount]==1){\n            splitcount++;\n            //Rcout << \"potentialsplitvars.size() = \" <<  potentialsplitvars.size() << \" .\\n\";\n\n            //Rcout << \"potentialsplitvars.size()-1 = \" <<  potentialsplitvars.size()-1 << \" .\\n\";\n            if(splitcount>num_term_nodes_draw-1-q_numsplitvars){//CHECK THIS CONDITION\n              //To ensure each variable used at least once, fill in the rest of the splits with all the variables\n              //The split variables will be randomly shuffled anyway, therefore the order is not important here.\n              drawnvarstemp[splitcount-1]=potentialsplitvars[index_remaining]+1;\n              index_remaining++;\n            }else{\n              //randomly draw a splitting varaible from the set of potential splitting variables\n              std::uniform_int_distribution<> draw_var(0,potentialsplitvars.size()-1);//q_numsplitvars-splitcount could replace potentialsplitvars.size()\n              int tempsplitvar = draw_var(lgen);\n              drawnvarstemp[splitcount-1]=potentialsplitvars[tempsplitvar]+1;\n\n            }\n\n            //if(splitcount>num_term_nodes_draw-1-q_numsplitvars){//CHECK THIS CONDITION\n            //  potentialsplitvars.erase(potentialsplitvars.begin()+tempsplitvar);\n            //}\n\n          }else{//if not a split\n            //splitvar_vectemp[nodecount]=-1;\n          }\n        }\n\n        std::shuffle(drawnvarstemp.begin(),drawnvarstemp.end(),lgen);\n\n        splitcount=0;\n        for(unsigned int nodecount=0; nodecount<treenodes_bintemp.size();nodecount++){\n          if(treenodes_bintemp[nodecount]==1){\n            splitvar_vectemp[nodecount]=drawnvarstemp[splitcount];\n            splitcount++;\n          }else{//if not a split\n            splitvar_vectemp[nodecount]=-1;\n          }\n        }\n\n        //Rcout << \"Line 3876 .\\n\";\n        split_var_vec=splitvar_vectemp;\n        treenodes_bin=treenodes_bintemp;\n      }\n    }else{\n      if(imp_sampler==1){ //If sampling from BART prior\n\n        //std::bernoulli_distribution coin_flip2(lambda);\n        double depth1=0;\n        int prev_node=0; //1 if previous node splits, zero otherwise\n\n        double samp_prob;\n\n        while(count_internals > (count_terminals -1)){\n          samp_prob=alpha_BART*pow(double(depth1+1),-beta_BART);\n          std::bernoulli_distribution coin_flip2(samp_prob);\n\n          int tempdraw = coin_flip2(lgen);\n          treenodes_bin.push_back(tempdraw);\n\n          if(tempdraw==1){\n\n            depth1=depth1+1; //after a split, the depth will increase by 1\n            prev_node=1;\n            count_internals=count_internals+1;\n\n          }else{\n\n            if(prev_node==1){//zero following a 1, therefore at same depth.\n              //Don't change depth. Do nothing\n            }else{ //zero following a zero, therefore the depth will decrease by 1\n              depth1=depth1-1;\n            }\n            prev_node=0;\n            count_terminals=count_terminals+1;\n\n          }\n\n        }\n\n      }else{  //If not sampling from BART prior\n        //If sampling from default Q+G prior. i.e. not sampling from BART nor spike and tree prior\n\n          while(count_internals > (count_terminals -1)){\n\n            //Also consider standard library and random header\n            // std::random_device device;\n            // std::mt19937 gen(device());\n            // std::bernoulli_distribution coin_flip(lambda);\n            // bool outcome = coin_flip(gen);\n\n\n            int tempdraw = coin_flip(lgen);\n\n            //int tempdraw = rbinom(n = 1, prob = lambda,size=1);\n\n\n            //int tempdraw = Rcpp::rbinom(1,lambda,1);\n            //int tempdraw = R::rbinom(1,lambda);\n\n            ////Rcout << \"tempdraw = \" << tempdraw << \".\\n\" ;\n\n            //int tempdraw = coin_flip2(lgen)-1;\n\n            //int tempdraw = dqrng::dqsample_int(2, 1, true,lambdavec )-1;\n\n\n            //need to update rng if use boost?\n            //int tempdraw = bernoulli(rng, binomial::param_type(1, lambda));\n\n            treenodes_bin.push_back(tempdraw);\n\n\n            if(tempdraw==1){\n              count_internals=count_internals+1;\n            }else{\n              count_terminals=count_terminals+1;\n            }\n\n          }//end of while loop creating parent vector treenodes_bin\n        }//end of Q+H sampling else statement\n    }//end of not Spike and Tree sampler else statement\n\n    //Rcout << \"Line 3961 .\\n\";\n\n\n    if(imp_sampler==2){\n      //already filled in splitting variable above for spike and tree prior\n    }else{\n      //Consider making this an armadillo vector\n      //IntegerVector split_var_vec(treenodes_bin.size());\n      //arma::uvec split_var_vec(treenodes_bin.size());\n      std::vector<int> split_var_vectemp(treenodes_bin.size());\n\n      // possibly faster alternative\n      //    split_var_vec.reserve( treenodes_bin.size() );\n      // then push_back elements to split_var_vec in the for loop\n\n      //loop drawing splitting variables\n      //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n      //if using armadillo, it might be faster to subset to split nodes\n      //then use a vector of draws\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        if(treenodes_bin[i]==0){\n          split_var_vectemp[i] = -1;\n        }else{\n          // also consider the standard library function uniform_int_distribution\n          // might need random header\n          // This uses the Mersenne twister\n\n          //Three lines below should probably be outside all the loops\n          // std::random_device rd;\n          // std::mt19937 engine(rd());\n          // std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n          //\n          // split_var_vec[i] = distsampvar(engine);\n\n          split_var_vectemp[i] = distsampvar(lgen);\n\n\n          //consider using boost\n          //might need to update rng\n          //split_var_vec[i] <- sample_splitvars(rng);\n\n          //or use dqrng\n          //not sure if have to update the random number\n          //check if the following line is written properly\n          //split_var_vec[i] = dqrng::dqsample_int(num_split_vars, 1, true);\n\n          //not sure if this returns an integer or a vector?\n          //split_var_vec[i] = RcppArmadillo::sample(num_split_vars, 1,true);\n          //could try\n          //split_var_vec[i] = as<int>(Rcpp::sample(num_split_vars, 1,true));\n          //could also try RcppArmadillo::rmultinom\n\n        }\n\n      }// end of for-loop drawing split variables\n\n      split_var_vec=split_var_vectemp;\n    }//end else statrement filling in splitting variable vector\n\n    //Consider making this an armadillo vector\n    //NumericVector split_point_vec(treenodes_bin.size());\n    //arma::vec split_point_vec(treenodes_bin.size());\n    std::vector<double> split_point_vec(treenodes_bin.size());\n\n\n    //loop drawing splitting points\n    //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n    //if using armadillo, it might be faster to subset to split nodes\n    //then use a vector of draws\n    for(unsigned int i=0; i<treenodes_bin.size();i++){\n      if(treenodes_bin[i]==0){\n        split_point_vec[i] = -1;\n      }else{\n\n\n        //////////////////////////////////////////////////////////\n        //following function not reccommended\n        //split_point_vec[i] = std::rand();\n        //////////////////////////////////////////////////////////\n        ////Standard library:\n        ////This should probably be outside all the loops\n        ////std::random_device rd;  //Will be used to obtain a seed for the random number engine\n        ////std::mt19937 gen2(rd()); //Standard mersenne_twister_engine seeded with rd()\n        ////std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n        split_point_vec[i] = dis_cont_unif(lgen);\n\n        //////////////////////////////////////////////////////////\n        //from armadillo\n        //split_point_vec[i] = arma::randu();\n\n        //////////////////////////////////////////////////////////\n        //probably not adviseable for paralelization\n        //From Rcpp\n        //split_point_vec[i] = as<double>(Rcpp::runif(1,0,1));\n\n        //////////////////////////////////////////////////////////\n        //consider using boost\n        //might need to update rng\n        //split_point_vec[i] <- b_unif_point(rng);\n\n        //or use dqrng\n        //not sure if have to update the random number\n        //check if the following line is written properly\n        //split_point_vec[i] = dqrng::dqrunif(1, 0, 1);\n\n        //not sure if this returns an integer or a vector?\n\n\n\n\n\n      }\n\n    }// end of for-loop drawing split points\n\n\n\n    //Rcout << \"Line 4081 .\\n\";\n\n\n    //CODE FOR ADJUSTING SPLITTING POINTS SO THAT THE TREES ARE VALID\n    if(valid_trees==1){\n      for(unsigned int i=0; i<treenodes_bin.size();i++){ //loop over all nodes\n        if(treenodes_bin[i]==1){ // if it is an internal node, then check for further splits on the same variable and update\n          double first_split_var=split_var_vec[i];      //splitting variable to check for\n          double first_split_point=split_point_vec[i];  //splitting point to use in updates\n\n          double sub_int_nodes=0;       //this internal node count will be used to determine if in subtree relevant to sub_int_nodes\n          double sub_term_nodes=0;      //this terminal node count will be used to determine if in subtree relevant to sub_int_nodes\n          double preventing_updates=0; //indicates if still within subtree that is not to be updated\n          double prevent_int_count=0;   //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n          double prevent_term_count=0;  //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n          for(unsigned int k=i+1; k<treenodes_bin.size();k++){\n            if(treenodes_bin[k]==1){\n              sub_int_nodes=sub_int_nodes+1;\n              if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                prevent_int_count=prevent_int_count+1;\n              }\n            }else{\n              sub_term_nodes=sub_term_nodes+1;\n              if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                prevent_term_count=prevent_term_count+1;\n              }\n            }\n            if(sub_int_nodes<=sub_term_nodes-2){\n              break;\n            }\n\n\n            if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n              if(prevent_int_count>prevent_term_count-1){ //if this rule is satisfied then in subtree that is not to be updated\n                continue; //still in subtree, therefore continue instead of checking for splits to be updates\n              }else{\n                preventing_updates=0; // no longer in subtree, therefore reset preventing_updates to zero\n              }\n            }\n\n\n            if(sub_int_nodes>sub_term_nodes-1){\n              if(treenodes_bin[k]==1){\n                if(split_var_vec[k]==first_split_var){\n                  split_point_vec[k]=split_point_vec[k]*first_split_point;\n                  //beginning count of subtree that should not have\n                  //further splits on first_split_var updated\n                  preventing_updates=1; //indicates if still within subtree that is not to be updated\n                  prevent_int_count=1;\n                  prevent_term_count=0;\n                }\n              }\n            }else{\n              if(treenodes_bin[k]==1){\n                if(split_var_vec[k]==first_split_var){\n                  split_point_vec[k]=split_point_vec[k]+first_split_point-first_split_point*split_point_vec[k];\n                  //beginning count of subtree that should not have\n                  //further splits on first_split_var updated\n                  preventing_updates=1; //indicates if still within subtree that is not to be updated\n                  prevent_int_count=1;\n                  prevent_term_count=0;\n                }\n              }\n            }\n\n\n\n          }//end of inner loop over k\n        }//end of if statement treenodes_bin[i]==1)\n      }//end of loop over i\n    }//end of if statement valid_trees==1\n\n\n\n\n\n    //Rcout << \"Line 4161 .\\n\";\n\n\n\n\n\n    //Create tree table matrix\n\n    //NumericMatrix tree_table1(treenodes_bin.size(),5+num_cats);\n\n    ////Rcout << \"Line 1037. \\n\";\n    //arma::mat tree_table1(treenodes_bin.size(),5+num_cats);\n\n    //initialize with zeros. Not sure if this is necessary\n    arma::mat tree_table1=arma::zeros<arma::mat>(treenodes_bin.size(),6);\n    //Rcout << \"Line 1040. \\n\";\n\n\n    //tree_table1(_,2) = wrap(split_var_vec);\n    //tree_table1(_,3) = wrap(split_point_vec);\n    //tree_table1(_,4) = wrap(treenodes_bin);\n\n\n\n    //It might be more efficient to make everything an armadillo object initially\n    // but then would need to replace push_back etc with a different approach (but this might be more efficient anyway)\n    arma::colvec split_var_vec_arma=arma::conv_to<arma::colvec>::from(split_var_vec);\n    //arma::colvec split_point_vec_arma(split_point_vec);\n    //arma::colvec split_point_vec_arma(split_point_vec);\n    arma::colvec split_point_vec_arma=arma::conv_to<arma::colvec>::from(split_point_vec);\n\n    arma::colvec treenodes_bin_arma=arma::conv_to<arma::colvec>::from(treenodes_bin);\n\n//Rcout << \"split_var_vec_arma = \" << split_var_vec_arma << \" . \\n\";\n\n//Rcout << \"split_point_vec_arma = \" << split_point_vec_arma << \" . \\n\";\n\n//Rcout << \"treenodes_bin_arma = \" << treenodes_bin_arma << \" . \\n\";\n\n\n    //Rcout << \"Line 1054. \\n\";\n\n    //Fill in splitting variable column\n    tree_table1.col(2) = split_var_vec_arma;\n    //Fill in splitting point column\n    tree_table1.col(3) = split_point_vec_arma;\n    //Fill in split/parent column\n    tree_table1.col(4) = treenodes_bin_arma;\n\n\n    //Rcout << \"Line 4200. j = \" << j << \". \\n\";\n\n    ////Rcout << \"Line 4081 .\\n\";\n\n\n    // Now start filling in left daughter and right daughter columns\n    std::vector<int> rd_spaces;\n    int prev_node = -1;\n\n    for(unsigned int i=0; i<treenodes_bin.size();i++){\n      ////Rcout << \"Line 1061. i = \" << i << \". \\n\";\n      if(prev_node==0){\n        //tree_table1(rd_spaces[rd_spaces.size()-1], 1)=i;\n        //Rcout << \"Line 1073. j = \" << j << \". \\n\";\n\n        tree_table1(rd_spaces.back(), 1)=i+1;\n        //Rcout << \"Line 1076. j = \" << j << \". \\n\";\n\n        rd_spaces.pop_back();\n      }\n      if(treenodes_bin[i]==1){\n        //Rcout << \"Line 1081. j = \" << j << \". \\n\";\n\n        tree_table1(i,0) = i+2;\n        rd_spaces.push_back(i);\n        prev_node = 1;\n        //Rcout << \"Line 185. j = \" << j << \". \\n\";\n\n      }else{                  // These 2 lines unnecessary if begin with matrix of zeros\n        //Rcout << \"Line 1089. j = \" << j << \". \\n\";\n        tree_table1(i,0)=0 ;\n        tree_table1(i,1) = 0 ;\n        prev_node = 0;\n        //Rcout << \"Line 1093. j = \" << j << \". \\n\";\n\n      }\n    }//\n    //Rcout << \"Line 1097. j = \" << j << \". \\n\";\n\n\n\n\n    //Rcout << \"Line 4242 .\\n\";\n\n    //List treepred_output = get_treepreds(original_y, num_cats, alpha_pars,\n    //                                     originaldata,\n    //                                     treetable_list[i]  );\n\n\n    //use armadillo object tree_table1\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n    //create variables for likelihood calcuations\n    // double lik_prod=1;\n    // double alph_prod=1;\n    // for(unsigned int i=0; i<alpha_pars_arma.n_elem;i++){\n    //   alph_prod=alph_prod*tgamma(alpha_pars_arma(i));\n    // }\n    // double gam_alph_sum= tgamma(arma::sum(alpha_pars_arma));\n    // double alph_term=gam_alph_sum/alph_prod;\n\n    //arma::mat arma_tree_table(treetable.begin(), treetable.nrow(), treetable.ncol(), false);\n    //arma::mat arma_orig_data(originaldata.begin(), originaldata.nrow(), originaldata.ncol(), false);\n\n\n    //arma::mat arma_tree(tree_data.begin(), tree_data.nrow(), tree_data.ncol(), false);\n    //arma::mat testd(test_data.begin(), test_data.nrow(), test_data.ncol(), false);\n\n    //NumericVector internal_nodes=find_internal_nodes_gs(tree_data);\n\n    //NumericVector terminal_nodes=find_term_nodes(treetable);\n\n    //arma::mat arma_tree(tree_table.begin(),tree_table.nrow(), tree_table.ncol(), false);\n\n    //arma::vec colmat=arma_tree.col(4);\n    //arma::uvec term_nodes=arma::find(colmat==-1);\n\n    //arma::vec colmat=arma_tree.col(2);\n    //arma::uvec term_nodes=arma::find(colmat==0);\n\n    //arma::vec colmat=tree_table1.col(4);\n    //arma::uvec term_nodes=arma::find(colmat==0);\n\n    //4th column is treenodes_bin_arma\n    arma::uvec term_nodes=arma::find(treenodes_bin_arma==0);\n\n    term_nodes=term_nodes+1;\n\n    //NumericVector terminal_nodes= wrap(term_nodes);\n\n\n\n    //GET J MATRIX\n\n    arma::mat Jmat(num_obs,term_nodes.n_elem);\n    arma::mat Jtilde(num_test_obs,term_nodes.n_elem);\n\n    //arma::vec arma_terminal_nodes=Rcpp::as<arma::vec>(terminal_nodes);\n    //NumericVector tree_predictions;\n\n    //now for each internal node find the observations that belong to the terminal nodes\n\n    //NumericVector predictions(test_data.nrow());\n    //List term_obs(term_nodes.n_elem);\n\n    //GET J MATRIX\n\n    //Rcout << \"Line 4311 .\\n\";\n\n    if(term_nodes.n_elem==1){\n      //double nodemean=tree_data(terminal_nodes[0]-1,5);\t\t\t\t// let nodemean equal tree_data row terminal_nodes[i]^th row , 6th column. The minus 1 is because terminal nodes consists of indices starting at 1, but need indices to start at 0.\n      //predictions=rep(nodemean,test_data.nrow());\n      //Rcout << \"Line 67 .\\n\";\n\n      //IntegerVector temp_obsvec = seq_len(test_data.nrow())-1;\n      //term_obs[0]= temp_obsvec;\n      //double denom_temp= orig_y_arma.n_elem+arma::sum(alpha_pars_arma);\n\n      //double num_prod=1;\n      //double num_sum=0;\n      //Rcout << \"Line 129.\\n\";\n      Jmat.col(0) = arma::ones<arma::vec>(num_obs);\n      Jtilde.col(0) = arma::ones<arma::vec>(num_test_obs);\n\n      //for(int k=0; k<num_cats; k++){\n        //assuming categories of y are from 1 to num_cats\n        //arma::uvec cat_inds= arma::find(orig_y_arma==k+1);\n        //double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n        //tree_table1(0,5+k)= m_plus_alph/denom_temp ;\n\n        //for likelihood calculation\n        //num_prod=num_prod*tgamma(m_plus_alph);\n        //num_sum=num_sum +m_plus_alph ;\n      //}\n\n      //lik_prod= alph_term*num_prod/tgamma(num_sum);\n\n    }\n    else{\n      for(unsigned int i=0;i<term_nodes.n_elem;i++){\n        //arma::mat subdata=testd;\n        //int curr_term=term_nodes(i);\n\n        int row_index;\n        int term_node=term_nodes(i);\n        //Rcout << \"Line 152.\\n\";\n\n\n        //WHAT IS THE PURPOSE OF THIS IF-STATEMENT?\n        //Why should the ro index be different for a right daughter?\n        //Why not just initialize row_index to any number not equal to 1 (e.g. 0)?\n        row_index=0;\n\n        // if(curr_term % 2==0){\n        //   //term node is left daughter\n        //   row_index=terminal_nodes[i];\n        // }else{\n        //   //term node is right daughter\n        //   row_index=terminal_nodes[i]-1;\n        // }\n\n\n\n\n        //save the left and right node data into arma uvec\n\n        //CHECK THAT THIS REFERS TO THE CORRECT COLUMNS\n        //arma::vec left_nodes=arma_tree.col(0);\n        //arma::vec right_nodes=arma_tree.col(1);\n\n        arma::vec left_nodes=tree_table1.col(0);\n        arma::vec right_nodes=tree_table1.col(1);\n\n\n\n        arma::mat node_split_mat;\n        node_split_mat.set_size(0,3);\n        //Rcout << \"Line 182. i = \" << i << \" .\\n\";\n\n        while(row_index!=1){\n          //for each terminal node work backwards and see if the parent node was a left or right node\n          //append split info to a matrix\n          int rd=0;\n          arma::uvec parent_node=arma::find(left_nodes == term_node);\n\n          if(parent_node.size()==0){\n            parent_node=arma::find(right_nodes == term_node);\n            rd=1;\n          }\n\n          //want to cout parent node and append to node_split_mat\n\n          node_split_mat.insert_rows(0,1);\n\n          //CHECK THAT COLUMNS OF TREETABLE ARE CORRECT\n          //node_split_mat(0,0)=treetable(parent_node[0],2);\n          //node_split_mat(0,1)=treetable(parent_node[0],3);\n\n          //node_split_mat(0,0)=arma_tree_table(parent_node[0],3);\n          //node_split_mat(0,1)=arma_tree_table(parent_node[0],4);\n\n          node_split_mat(0,0)=tree_table1(parent_node(0),2);\n          node_split_mat(0,1)=tree_table1(parent_node(0),3);\n\n          node_split_mat(0,2)=rd;\n          row_index=parent_node(0)+1;\n          term_node=parent_node(0)+1;\n        }\n\n        //once we have the split info, loop through rows and find the subset indexes for that terminal node!\n        //then fill in the predicted value for that tree\n        //double prediction = tree_data(term_node,5);\n        arma::uvec pred_indices;\n        arma::uvec pred_test_indices;\n        int split= node_split_mat(0,0)-1;\n\n        //Rcout << \"Line 224.\\n\";\n        //Rcout << \"split = \" << split << \".\\n\";\n        //arma::vec tempvec = testd.col(split);\n        arma::vec tempvec = arma_orig_data.col(split);\n        arma::vec temptest_vec = arma_test_data.col(split);\n        //Rcout << \"Line 227.\\n\";\n\n\n        double temp_split = node_split_mat(0,1);\n\n        if(node_split_mat(0,2)==0){\n          pred_indices = arma::find(tempvec <= temp_split);\n          pred_test_indices = arma::find(temptest_vec <= temp_split);\n        }else{\n          pred_indices = arma::find(tempvec > temp_split);\n          pred_test_indices = arma::find(temptest_vec > temp_split);\n        }\n        //Rcout << \"Line 236.\\n\";\n\n        arma::uvec temp_pred_indices;\n        arma::uvec temp_test_pred_indices;\n\n        //arma::vec data_subset = testd.col(split);\n        arma::vec data_subset = arma_orig_data.col(split);\n        arma::vec data_test_subset = arma_test_data.col(split);\n\n        data_subset=data_subset.elem(pred_indices);\n        data_test_subset=data_test_subset.elem(pred_test_indices);\n\n        //now loop through each row of node_split_mat\n        int n=node_split_mat.n_rows;\n        //Rcout << \"Line 174. i = \" << i << \". n = \" << n << \".\\n\";\n        //Rcout << \"Line 248.\\n\";\n\n        for(int j=1;j<n;j++){\n          int curr_sv=node_split_mat(j,0);\n          double split_p = node_split_mat(j,1);\n\n          //data_subset = testd.col(curr_sv-1);\n          //Rcout << \"Line 255.\\n\";\n          //Rcout << \"curr_sv = \" << curr_sv << \".\\n\";\n          data_subset = arma_orig_data.col(curr_sv-1);\n          data_test_subset = arma_test_data.col(curr_sv-1);\n          //Rcout << \"Line 258.\\n\";\n\n          data_subset=data_subset.elem(pred_indices);\n          data_test_subset=data_test_subset.elem(pred_test_indices);\n\n          if(node_split_mat(j,2)==0){\n            //split is to the left\n            temp_pred_indices=arma::find(data_subset <= split_p);\n            temp_test_pred_indices=arma::find(data_test_subset <= split_p);\n          }else{\n            //split is to the right\n            temp_pred_indices=arma::find(data_subset > split_p);\n            temp_test_pred_indices=arma::find(data_test_subset > split_p);\n          }\n          pred_indices=pred_indices.elem(temp_pred_indices);\n          pred_test_indices=pred_test_indices.elem(temp_test_pred_indices);\n\n          //if(pred_indices.size()==0){\n          //  continue;\n          //}\n\n        }\n        //Rcout << \"Line 199. i = \" << i <<  \".\\n\";\n\n        //There is probably a more efficient way of doing this\n        //e.g. initialize J matrix so that all elements are equal to zero\n        arma::vec tempcol_J=arma::zeros<arma::vec>(num_obs);\n        tempcol_J(pred_indices) = arma::ones<arma::vec>(pred_indices.size());\n        Jmat.col(i) = tempcol_J;\n\n        arma::vec tempcol_Jtilde=arma::zeros<arma::vec>(num_test_obs);\n        tempcol_Jtilde(pred_test_indices) = arma::ones<arma::vec>(pred_test_indices.size());\n        Jtilde.col(i) = tempcol_Jtilde;\n\n        //double nodemean=tree_data(terminal_nodes[i]-1,5);\n        //IntegerVector predind=as<IntegerVector>(wrap(pred_indices));\n        //predictions[predind]= nodemean;\n        //term_obs[i]=predind;\n\n        //double denom_temp= pred_indices.n_elem+arma::sum(alpha_pars_arma);\n        //Rcout << \"Line 207. predind = \" << predind <<  \".\\n\";\n        //Rcout << \"Line 207. denom_temp = \" << denom_temp <<  \".\\n\";\n        // << \"Line 207. term_node = \" << term_node <<  \".\\n\";\n\n        //double num_prod=1;\n        //double num_sum=0;\n\n        // for(int k=0; k<num_cats; k++){\n        //   //assuming categories of y are from 1 to num_cats\n        //   arma::uvec cat_inds= arma::find(orig_y_arma(pred_indices)==k+1);\n        //   double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n        //\n        //   tree_table1(curr_term-1,5+k)= m_plus_alph/denom_temp ;\n        //\n        //   num_prod=num_prod*tgamma(m_plus_alph);\n        //   num_sum=num_sum +m_plus_alph ;\n        // }\n        //\n        //\n        // lik_prod= lik_prod*alph_term*num_prod/tgamma(num_sum);\n        //Rcout << \"Line 297.\\n\";\n\n\n      }//End of loop over terminal nodes.\n    }// end of else statement (for when more than one terminal node)\n    // Now have J matrix\n\n    //Rcout << \"Line 4530 .\\n\";\n\n    Wmat=join_rows(Wmat,Jmat);\n    //or\n    //Wmat.insert_cols(Wmat.n_cols,Jmat);\n    //or\n    //int b_j=term_nodes.n_elem;\n    //Wmat.insert_cols(upsilon,Jmat);\n    //upsilon+=b_j;\n\n\n    //Obtain test W_tilde, i.e. W matrix for test data\n\n    W_tilde=join_rows(W_tilde,Jtilde);\n    //or\n    //W_tilde.insert_cols(W_tilde.n_cols,Jtilde);\n    //or\n    //int b_jtest=term_nodes.n_elem;\n    //W_tilde.insert_cols(upsilon2,Jtilde);\n    //upsilon2+=b_jtest;\n\n    //Rcout << \"Line 4551 .\\n\";\n\n    if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n      // //get impportance sampler probability and tree prior\n      // long double temp_samp_prob;\n      // long double temp_prior_prob;\n      // //get sampler tree probability\n      // if(imp_sampler==1){//If sample from BART prior\n      //\n      //\n      //\n      //   temp_samp_prob=1;\n      //\n      //   double depth1=0;\n      //   int prev_node=0; //1 if previous node splits, zero otherwise\n      //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n      //     if(treenodes_bin[i_2]==1){\n      //       temp_samp_prob=temp_samp_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n      //       depth1=depth1+1; //after a split, the depth will increase by 1\n      //       prev_node=1;\n      //     }else{\n      //       temp_samp_prob=temp_samp_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n      //       if(prev_node==1){//zero following a 1, therefore at same depth.\n      //         //Don't change depth. Do nothing\n      //       }else{ //zero following a zero, therefore the depth will decrease by 1\n      //         depth1=depth1-1;\n      //       }\n      //       prev_node=0;\n      //\n      //     }\n      //   }\n      //\n      //   //end of calculating BART tree probability\n      // }else{\n      //   if(imp_sampler==2){//If sample from spike and tree prior\n      //     throw std::range_error(\"code not yet written for spike and tree prior\");\n      //\n      //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n      //     double tempexp1=treenodes_bin.size()-arma::sum(treenodes_bin_arma);\n      //     double tempexp2=arma::sum(treenodes_bin_arma);\n      //     temp_samp_prob=pow(lambda,tempexp2)*\n      //       pow(1-lambda,tempexp1);\n      //       //(1/pow(double(num_split_vars),tempexp2));\n      //\n      //       temp_samp_prob=exp(log(lambda)*tempexp2+\n      //         log(1-lambda)*tempexp1);\n      //\n      //     //temp_samp_prob=pow(lambda,arma::sum(treenodes_bin_arma))*\n      //     //  pow(1-lambda,treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n      //     //  pow((1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n      //   }\n      // }\n      //\n      // sum_tree_samp_prob=sum_tree_samp_prob*temp_samp_prob;\n      // //end of getting importance sampler probability\n      //\n      // //get prior tree probability\n      // if(tree_prior==1){//If sample from BART prior\n      //\n      //\n      //\n      //   temp_prior_prob=1;\n      //\n      //   double depth1=0;\n      //   int prev_node=0; //1 if previous node splits, zero otherwise\n      //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n      //\n      //     if(treenodes_bin[i_2]==1){\n      //       temp_prior_prob=temp_prior_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n      //       depth1=depth1+1; //after a split, the depth will increase by 1\n      //       prev_node=1;\n      //     }else{\n      //       temp_prior_prob=temp_prior_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n      //       if(prev_node==1){//zero following a 1, therefore at same depth.\n      //         //Don't change depth. Do nothing\n      //       }else{ //zero following a zero, therefore the depth will decrease by 1\n      //         depth1=depth1-1;\n      //       }\n      //       prev_node=0;\n      //\n      //     }\n      //     //if(alpha_BART==0){\n      //     //  //Rcout << \"alpha_BART equals zero!!!!.\\n\";\n      //     //}\n      //   }\n      //\n      //   //end of calculating BART tree probability\n      // }else{\n      //   if(tree_prior==2){//If sample from spike and tree prior\n      //     throw std::range_error(\"code not yet written for spike and tree prior\");\n      //\n      //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n      //     temp_prior_prob=pow((long double)(lambda),arma::sum(treenodes_bin_arma))*\n      //       pow((long double)(1-lambda),treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n      //       pow((long double)(1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n      //   }\n      // }\n      //\n      // sum_tree_prior_prob=sum_tree_prior_prob*temp_prior_prob;\n      // if(temp_prior_prob==0){\n      //   Rcout << \"Line 4097, j= \" << j << \". \\n\";\n      //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n      //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n      // }\n      // if(temp_samp_prob==0){\n      //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n      //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n      //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n      // }\n      //\n      // if(sum_tree_samp_prob==0){\n      //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n      //   Rcout << \"sum_tree_samp_prob= \" << sum_tree_samp_prob << \". \\n\";\n      //   //Rcout << \"treenodes_bin_arma= \" << treenodes_bin_arma << \". \\n\";\n      //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n      //\n      // }\n\n\n\n\n      //get tree prior over impportance sampler probability\n      double tree_prior_over_samp_prob=1;\n      if(imp_sampler==1){   //If sample from BART prior\n        if(tree_prior==1){  //If tree prior is BART prior\n          /////////////////////////////////////////////////////////////////////////////////////////\n          throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n          /////////////////////////////////////////////////////////////////////////////////////////\n        }else{// not BART prior (and sampler is BART)\n          if(tree_prior==2){  //If tree prior is spike-and-tree prior (and sampler is BART)\n            //throw std::range_error(\"code not yet written for spike and tree prior\");\n            /////////////////////////////////////////////////////////////////////////////////////////\n\n\n            //arma::uvec internal_nodes_prop=find_internal_nodes(tree_table);\n            //arma::mat tree_table2(tree_table.begin(),tree_table.nrow(),tree_table.ncol(),false);\n            //arma::mat arma_tree(treetable.begin(),treetable.nrow(), treetable.ncol(), false);\n            //arma::vec colmat=arma_tree.col(4);\n            //arma::uvec internal_nodes_prop=arma::find(treenodes_bin_arma==1);\n            //internal_nodes_prop=internal_nodes_prop+1;\n\n            //double k_temp=internal_nodes_prop.size()+1;\n            //arma::mat split_var_rows=tree_table2.rows\n\n            //split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n\n\n            arma::vec split_var_vectemp=split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n            double k_temp=split_var_vectemp.size()+1;\n            arma::vec uniquesplitvars=arma::unique(split_var_vectemp);\n            double q_temp=uniquesplitvars.n_elem;\n\n            //FIRST CALCULATE THE log of denom and right_truncatin\n            //Then take the exponential\n            //then take the difference\n            double denom=1;\n            for(int i=0; i<q_temp+1;i++){\n              //denom= denom-(pow(lambda_poisson,double(i))*exp(-lambda_poisson)/double(tgamma(i+1)));\n              denom = denom-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n            }\n            double right_truncation=1;\n            for(int i=0; i<num_obs+1;i++){\n              //right_truncation= right_truncation-(pow(lambda_poisson,double(i))*std::exp(-lambda_poisson)/double(tgamma(i+1)));\n              right_truncation= right_truncation-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n            }\n            //Rcout << \" right_truncation= \" << right_truncation << \".\\n\";\n            denom=denom-right_truncation;\n\n\n            double propsplit;\n\n            if(q_temp==0){\n              if(s_t_hyperprior==1){\n                 propsplit=//(1/double(num_vars+1))*\n                  exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                  q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                  k_temp*log(lambda_poisson)-\n                  lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                // tree_prior_over_samp_prob=  propsplit/\n                //   BART_prior*\n                //     pow(1/num_vars,arma::sum(treenodes_bin_arma));\n              }else{\n                 propsplit=//(1/double(num_vars+1))*\n                  exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                  std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                  k_temp*log(lambda_poisson)-\n                  lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                // tree_prior_over_samp_prob=  propsplit/\n                //   BART_prior*\n                //     pow(1/num_vars,arma::sum(treenodes_bin_arma));\n\n              }\n            }else{\n              if(s_t_hyperprior==1){\n                 propsplit=//(1/double(num_vars+1))*\n                  exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                  std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                  k_temp*log(lambda_poisson)-\n                  lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                  (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                     -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                      +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                      +std::lgamma(num_obs)\n                      -std::lgamma(k_temp)\n                      -std::lgamma(num_obs-k_temp) ));\n\n                  //(std::lgamma(num_obs)+(k_temp-1-q_temp)*log(q_temp)+\n                  //std::lgamma(q_temp+1)-(std::lgamma(num_obs-k_temp+1))));\n                //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                // tree_prior_over_samp_prob=  propsplit/\n                //   BART_prior*\n                //     pow(1/num_vars,arma::sum(treenodes_bin_arma));\n              }else{\n                 propsplit=//(1/double(num_vars+1))*\n                  exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                  q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                  k_temp*log(lambda_poisson)-\n                  lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                  (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                     -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                     +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                     +std::lgamma(num_obs)\n                     -std::lgamma(k_temp)\n                     -std::lgamma(num_obs-k_temp) ));\n                //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n\n                // tree_prior_over_samp_prob=  propsplit/\n                //   BART_prior*\n                //     pow(1/num_vars,arma::sum(treenodes_bin_arma));\n              }\n            }\n\n            tree_prior_over_samp_prob=propsplit;\n            //first get BART prior for tree structure\n            double depth1=0;\n            int prev_node=0; //1 if previous node splits, zero otherwise\n            //double BART_prior=1;\n            for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n              if(treenodes_bin[i_2]==1){\n                tree_prior_over_samp_prob=tree_prior_over_samp_prob/((alpha_BART*pow(double(depth1+1),-beta_BART)));\n                depth1=depth1+1; //after a split, the depth will increase by 1\n                prev_node=1;\n              }else{\n                tree_prior_over_samp_prob=tree_prior_over_samp_prob/((1-alpha_BART*pow(double(depth1+1),-beta_BART)));\n                if(prev_node==1){//zero following a 1, therefore at same depth.\n                  //Don't change depth. Do nothing\n                }else{ //zero following a zero, therefore the depth will decrease by 1\n                  depth1=depth1-1;\n                }\n                prev_node=0;\n\n              }//close (zero node) else stattement\n\n            }//end for loop over i_2\n\n\n\n\n            /////////////////////////////////////////////////////////////////////////////////////////\n          }else{ //prior is Q+H  //(sampler is BART)\n            /////////////////////////////////////////////////////////////////////////////////////////\n            double depth1=0;\n            int prev_node=0; //1 if previous node splits, zero otherwise\n            for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n              if(treenodes_bin[i_2]==1){\n                tree_prior_over_samp_prob=tree_prior_over_samp_prob*(lambda/(alpha_BART*pow(double(depth1+1),-beta_BART)));\n                depth1=depth1+1; //after a split, the depth will increase by 1\n                prev_node=1;\n              }else{\n                tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-lambda)/(1-alpha_BART*pow(double(depth1+1),-beta_BART)));\n                if(prev_node==1){//zero following a 1, therefore at same depth.\n                  //Don't change depth. Do nothing\n                }else{ //zero following a zero, therefore the depth will decrease by 1\n                  depth1=depth1-1;\n                }\n                prev_node=0;\n\n              }\n            }\n            /////////////////////////////////////////////////////////////////////////////////////////\n          }//close Q+H prior (with BART sampler)\n        }//close not BART prior (with BART sampler)\n      }else{// if not sampling from BART sampler\n        if(imp_sampler==2){//If sample from spike and tree prior\n          //throw std::range_error(\"code not yet written for sampling from spike and tree prior\");\n\n          if(tree_prior==1){//prior is BART (sampler is spike and tree)\n            /////////////////////////////////////////////////////////////////////////////////////////\n            //first get BART prior for tree structure\n            double depth1=0;\n            int prev_node=0; //1 if previous node splits, zero otherwise\n            double BART_prior=1;\n            for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n              if(treenodes_bin[i_2]==1){\n                BART_prior=BART_prior*((alpha_BART*pow(double(depth1+1),-beta_BART)));\n                depth1=depth1+1; //after a split, the depth will increase by 1\n                prev_node=1;\n              }else{\n                BART_prior=BART_prior*((1-alpha_BART*pow(double(depth1+1),-beta_BART)));\n                if(prev_node==1){//zero following a 1, therefore at same depth.\n                  //Don't change depth. Do nothing\n                }else{ //zero following a zero, therefore the depth will decrease by 1\n                  depth1=depth1-1;\n                }\n                prev_node=0;\n\n              }//close (zero node) else stattement\n\n            }//end for loop over i_2\n\n            arma::vec split_var_vectemp=split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n            double k_temp=split_var_vectemp.size()+1;\n            arma::vec uniquesplitvars=arma::unique(split_var_vectemp);\n            double q_temp=uniquesplitvars.n_elem;\n\n            //FIRST CALCULATE THE log of denom and right_truncatin\n            //Then take the exponential\n            //then take the difference\n            double denom=1;\n            for(int i=0; i<q_temp+1;i++){\n              //denom= denom-(pow(lambda_poisson,double(i))*exp(-lambda_poisson)/double(tgamma(i+1)));\n              denom = denom-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n            }\n            double right_truncation=1;\n            for(int i=0; i<num_obs+1;i++){\n              //right_truncation= right_truncation-(pow(lambda_poisson,double(i))*std::exp(-lambda_poisson)/double(tgamma(i+1)));\n              right_truncation= right_truncation-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n            }\n            //Rcout << \" right_truncation= \" << right_truncation << \".\\n\";\n            denom=denom-right_truncation;\n\n            if(q_temp==0){\n              if(s_t_hyperprior==1){\n                double propsplit=//(1/double(num_vars+1))*\n                  exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                  q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                  k_temp*log(lambda_poisson)-\n                  lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                tree_prior_over_samp_prob= BART_prior*\n                  pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n              }else{\n                double propsplit=//(1/double(num_vars+1))*\n                  exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                  std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                  k_temp*log(lambda_poisson)-\n                  lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                tree_prior_over_samp_prob=  BART_prior*\n                  pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n              }\n            }else{\n              if(s_t_hyperprior==1){\n                double propsplit=//(1/double(num_vars+1))*\n                  exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                  std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                  k_temp*log(lambda_poisson)-\n                  lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                  (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                     -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                     +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                     +std::lgamma(num_obs)\n                     -std::lgamma(k_temp)\n                     -std::lgamma(num_obs-k_temp) ));\n                //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                tree_prior_over_samp_prob=  BART_prior*\n                  pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n              }else{\n                double propsplit=//(1/double(num_vars+1))*\n                  exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                  q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                  k_temp*log(lambda_poisson)-\n                  lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                  (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                     -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                     +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                     +std::lgamma(num_obs)\n                     -std::lgamma(k_temp)\n                     -std::lgamma(num_obs-k_temp) ));\n                //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n\n                tree_prior_over_samp_prob=  BART_prior*\n                  pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n              }\n            }\n            /////////////////////////////////////////////////////////////////////////////////////////\n          }else{\n            if(tree_prior==2){//prior is spike and tree, sampler is spike and tree\n              /////////////////////////////////////////////////////////////////////////////////////////\n              throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n              /////////////////////////////////////////////////////////////////////////////////////////\n            }else{//prior is Q+H, sampler is spike and tree\n              /////////////////////////////////////////////////////////////////////////////////////////\n              arma::vec split_var_vectemp=split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n              double k_temp=split_var_vectemp.size()+1;\n              arma::vec uniquesplitvars=arma::unique(split_var_vectemp);\n              double q_temp=uniquesplitvars.n_elem;\n\n              //FIRST CALCULATE THE log of denom and right_truncatin\n              //Then take the exponential\n              //then take the difference\n\n              double denom=1;\n              for(int i=0; i<q_temp+1;i++){\n                //denom= denom-(pow(lambda_poisson,double(i))*exp(-lambda_poisson)/double(tgamma(i+1)));\n                denom = denom-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n              }\n              double right_truncation=1;\n              for(int i=0; i<num_obs+1;i++){\n                //right_truncation= right_truncation-(pow(lambda_poisson,double(i))*std::exp(-lambda_poisson)/double(tgamma(i+1)));\n                right_truncation= right_truncation-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n              }\n              //Rcout << \" right_truncation= \" << right_truncation << \".\\n\";\n              denom=denom-right_truncation;\n\n              if(q_temp==0){\n                if(s_t_hyperprior==1){\n                  double propsplit=//(1/double(num_vars+1))*\n                    exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  tree_prior_over_samp_prob=  pow(lambda,arma::sum(treenodes_bin_arma))*\n                    pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                    pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                }else{\n                  double propsplit=//(1/double(num_vars+1))*\n                    exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  tree_prior_over_samp_prob=  pow(lambda,arma::sum(treenodes_bin_arma))*\n                    pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                    pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                }\n\n              }else{\n                if(s_t_hyperprior==1){\n                  double propsplit=//(1/double(num_vars+1))*\n                    exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                    (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                       -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                       +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                       +std::lgamma(num_obs)\n                       -std::lgamma(k_temp)\n                       -std::lgamma(num_obs-k_temp) ));\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  tree_prior_over_samp_prob=  pow(lambda,arma::sum(treenodes_bin_arma))*\n                    pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                    pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                }else{\n                  double propsplit=//(1/double(num_vars+1))*\n                    exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                    (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                       -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                       +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                       +std::lgamma(num_obs)\n                       -std::lgamma(k_temp)\n                       -std::lgamma(num_obs-k_temp) ));\n\n                  tree_prior_over_samp_prob=  pow(lambda,arma::sum(treenodes_bin_arma))*\n                    pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                    pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                }\n              }\n              /////////////////////////////////////////////////////////////////////////////////////////\n            }//finish if sampler is spike tree and prior is Q+H\n          }//finish all possibiilities for spike and tree sampler\n\n        }else{//otherwise sampling from Quadrianto and Ghahramani prior\n          if(tree_prior==1){  //If tree prior is BART prior (and sampler is Q+H)\n            /////////////////////////////////////////////////////////////////////////////////////////\n            double depth1=0;\n            int prev_node=0; //1 if previous node splits, zero otherwise\n            for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n              if(treenodes_bin[i_2]==1){\n                tree_prior_over_samp_prob=tree_prior_over_samp_prob*((alpha_BART*pow(double(depth1+1),-beta_BART))/lambda);\n                depth1=depth1+1; //after a split, the depth will increase by 1\n                prev_node=1;\n              }else{\n                tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-alpha_BART*pow(double(depth1+1),-beta_BART))/(1-lambda));\n                if(prev_node==1){//zero following a 1, therefore at same depth.\n                  //Don't change depth. Do nothing\n                }else{ //zero following a zero, therefore the depth will decrease by 1\n                  depth1=depth1-1;\n                }\n                prev_node=0;\n\n              }//close (zero node) else stattement\n\n            }//end for loop over i_2\n            /////////////////////////////////////////////////////////////////////////////////////////\n          }else{\n            if(tree_prior==2){  //If tree prior is spike-and-tree prior (and sampler is Q+H)\n              /////////////////////////////////////////////////////////////////////////////////////////\n              //throw std::range_error(\"code not yet written for spike and tree prior\");\n\n              arma::vec split_var_vectemp=split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n              double k_temp=split_var_vectemp.size()+1;\n              arma::vec uniquesplitvars=arma::unique(split_var_vectemp);\n              double q_temp=uniquesplitvars.n_elem;\n\n              //FIRST CALCULATE THE log of denom and right_truncatin\n              //Then take the exponential\n              //then take the difference\n\n              double denom=1;\n              for(int i=0; i<q_temp+1;i++){\n                //denom= denom-(pow(lambda_poisson,double(i))*exp(-lambda_poisson)/double(tgamma(i+1)));\n                denom = denom-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n              }\n              double right_truncation=1;\n              for(int i=0; i<num_obs+1;i++){\n                //right_truncation= right_truncation-(pow(lambda_poisson,double(i))*std::exp(-lambda_poisson)/double(tgamma(i+1)));\n                right_truncation= right_truncation-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n              }\n              //Rcout << \" right_truncation= \" << right_truncation << \".\\n\";\n              denom=denom-right_truncation;\n\n\n              double propsplit;\n\n              if(q_temp==0){\n                if(s_t_hyperprior==1){\n                   propsplit=//(1/double(num_vars+1))*\n                    exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  // tree_prior_over_samp_prob=  propsplit/\n                  //   (pow(lambda,arma::sum(treenodes_bin_arma))*\n                  //     pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                  //     pow(1/num_vars,arma::sum(treenodes_bin_arma)));\n\n                }else{\n                   propsplit=//(1/double(num_vars+1))*\n                    exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  // tree_prior_over_samp_prob=  propsplit/\n                  //   (pow(lambda,arma::sum(treenodes_bin_arma))*\n                  //     pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                  //     pow(1/num_vars,arma::sum(treenodes_bin_arma)));\n\n                }\n\n              }else{\n                if(s_t_hyperprior==1){\n                   propsplit=//(1/double(num_vars+1))*\n                    exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                    (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                       -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                       +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                       +std::lgamma(num_obs)\n                       -std::lgamma(k_temp)\n                       -std::lgamma(num_obs-k_temp) ));\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  // tree_prior_over_samp_prob=  propsplit/\n                  //   (pow(lambda,arma::sum(treenodes_bin_arma))*\n                  //     pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                  //     pow(1/num_vars,arma::sum(treenodes_bin_arma)));\n\n                }else{\n                   propsplit=//(1/double(num_vars+1))*\n                    exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                    (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                       -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                       +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                       +std::lgamma(num_obs)\n                       -std::lgamma(k_temp)\n                       -std::lgamma(num_obs-k_temp) ));\n\n                  // tree_prior_over_samp_prob=  propsplit/\n                  //   (pow(lambda,arma::sum(treenodes_bin_arma))*\n                  //     pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                  //     pow(1/num_vars,arma::sum(treenodes_bin_arma)));\n\n                }\n              }\n              tree_prior_over_samp_prob=propsplit;\n\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob/lambda;\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob/(1-lambda);\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }//close (zero node) else stattement\n\n              }//end for loop over i_2\n\n\n\n\n              /////////////////////////////////////////////////////////////////////////////////////////\n            }else{//if prior is Q+H (and sampler is Q+H)\n              /////////////////////////////////////////////////////////////////////////////////////////\n              throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n              /////////////////////////////////////////////////////////////////////////////////////////\n            }//close (not BART nor spike and tree prior) else statement\n          }// close (not BART prior) else statememt\n\n        }//close all Q+H sampler code (not sampling from BART or spike and tree)  else statement\n\n      }//close (not sampling from BART) else statement\n\n      sum_prior_over_samp_prob=sum_prior_over_samp_prob*tree_prior_over_samp_prob;\n      //end of getting tree prior over impportance sampler probability\n\n      // if(sum_prior_over_samp_prob==0){\n      //   Rcout << \"Line 4266, j= \" << j << \". \\n\";\n      //   Rcout << \"Line 4267, q= \" << q << \". \\n\";\n      //   Rcout << \"sum_prior_over_samp_prob= \" << sum_prior_over_samp_prob << \". \\n\";\n      //\n      // }else{\n      //   Rcout << \"Line 4266, j= \" << j << \". \\n\";\n      //   Rcout << \"Line 4267, q= \" << q << \". \\n\";\n      //   Rcout << \"sum_prior_over_samp_prob= \" << sum_prior_over_samp_prob << \". \\n\";\n      // }\n\n    }//end of tree prior and importance sampler calculations\n\n\n    } //end of loop over trees in sum\n\n\n    //Obtain W matrix. If more than one tree in sum, need to join J matrices, possibly in loop over model trees above\n    // i.e. add a loop from just within the start of the outer loop to here of length equal to the number of trees within the model\n    // Create a Wmat with zero columns at start of loop, and join the Jmat at the end of each loop\n\n    //for now, testing a one-tree model\n    //replace Jmat with Wmat later\n\n\n    //Obtain likelihood\n\n    //Rcout << \"Line 5186 .\\n\";\n\n    double b=Wmat.n_cols;\n\n\n\n    if(fast_approx==1){\n      arma::mat p = Wmat.t();\n      arma::rowvec r = orig_y_arma.t();\n\n      arma::mat cov = p * p.t() +a * arma::eye<arma::mat>(p.n_rows, p.n_rows);\n\n      arma::mat parameters = arma::solve(cov, p * r.t(), arma::solve_opts::fast);\n\n      arma::rowvec preds_temp_arma_t=arma::trans(parameters) * W_tilde.t();\n      arma::rowvec preds_insamp_arma=arma::trans(parameters) * p;\n\n      arma::vec preds_temp_arma= preds_temp_arma_t.t();\n\n      arma::vec tempresids=y-preds_insamp_arma.t();\n      double temp_sse= arma::dot(tempresids, tempresids);\n\n      //double templik0=exp(-b*0.5*log(num_obs)+log(temp_sse)*(-num_obs)*0.5);\n\n\n      //double templik0=exp(-b*0.5*log(num_obs)+log(temp_sse)*(-num_obs)*0.5);\n\n\n      //double templik0=exp(-0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs)))  ;\n\n      double templik0=(num_obs*log(temp_sse/num_obs)+b*log(num_obs))  ;\n\n      // //Rcout << \"num_obs= \" << num_obs << \". \\n\";\n      // //Rcout << \"b= \" << b << \". \\n\";\n      // Rcout << \"log(num_obs)= \" << log(num_obs) << \". \\n\";\n      // Rcout << \"log(temp_sse/num_obs)= \" << log(temp_sse/num_obs) << \". \\n\";\n      //Rcout << \"templik0= \" << templik0 << \". \\n\";\n      // Rcout << \"-0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs))= \" << -0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs)) << \". \\n\";\n\n\n      //double templik = pow(templik0,beta_par);\n      double templik = beta_par*templik0;\n\n\n      if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n        //templik=templik*(sum_tree_prior_prob/sum_tree_samp_prob);\n        //templik=templik*sum_prior_over_samp_prob;\n        templik=templik+log(sum_prior_over_samp_prob);\n\n      }\n      overall_liks(j)= templik;\n\n      overall_preds(j)=preds_temp_arma;\n\n    }else{\n\n\n\n      // ///////////////////////////////////\n      //get t(y)inv(psi)J\n      arma::mat ytW=y.t()*Wmat;\n      //get t(J)inv(psi)J\n      arma::mat WtW=Wmat.t()*Wmat;\n      //get jpsij +aI\n      arma::mat aI(b,b);\n      aI=a*aI.eye();\n      arma::mat sec_term=WtW+aI;\n      //arma::mat sec_term_inv=sec_term.i();\n      arma::mat sec_term_inv=inv_sympd(sec_term);\n      //get t(J)inv(psi)y\n      arma::mat third_term=Wmat.t()*y;\n      //get m^TV^{-1}m\n      arma::mat mvm= ytW*sec_term_inv*third_term;\n      //arma::mat rel=(b/2)*log(a)-(1/2)*log(det(sec_term))-expon*log(nu*lambdaBART - mvm +yty);\n      // /////////////////////////////////////////////\n\n\n      //\n      // Rcout << \"-b*0.5*log(num_obs)= \" << -b*0.5*log(num_obs) << \". \\n\";\n      // Rcout << \"log(temp_sse)*(-num_obs)*0.5= \" << log(temp_sse)*(-num_obs)*0.5 << \". \\n\";\n      //\n\n      //double templik0=pow(num_obs, -b*0.5)*pow(temp_sse,-num_obs*0.5);\n\n  //\n  //     arma::vec temppred1=Wmat*sec_term_inv*third_term;\n  //     arma::vec temperrors= y-temppred1;\n  //     arma::vec tempcoeffs= sec_term_inv*third_term;\n  //\n  //     double new_penalty= as_scalar(b*temppred1.t()*temppred1/(tempcoeffs.t()*tempcoeffs*(double(num_obs)-b)));\n  //\n  //     Rcout << \" new_penalty =\" << new_penalty << \".\\n\";\n\n\n      //double val1;\n      //double sign1;\n\n      //log_det(val1, sign1, sec_term);\n      //double templik0=exp(arma::as_scalar((b*0.5)*log(a)-0.5*val1-expon*log(nu*lambdaBART - mvm +yty)));\n\n\n  ////////////////////\n      //double templik0=exp(arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term))-expon*log(nu*lambdaBART - mvm +yty)));\n  //////////////\n  double templik0=arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term))-expon*log(nu*lambdaBART - mvm +yty));\n\n\n\n      //double templik0=exp(arma::as_scalar((b*0.5)*log(a)-0.5*log(det(sec_term))-expon*log(nu*lambdaBART - mvm +yty)));\n\n\n\n\n\n  //\n  //\n  //     arma::mat aI2(b,b);\n  //     aI2=new_penalty*aI2.eye();\n  //     arma::mat sec_term2=WtW+aI2;\n  //     //arma::mat sec_term_inv=sec_term.i();\n  //     arma::mat sec_term_inv2=inv_sympd(sec_term2);\n  //     //get t(J)inv(psi)y\n  //     //arma::mat third_term=Wmat.t()*y;\n  //     //get m^TV^{-1}m\n  //     arma::mat mvm2= ytW*sec_term_inv2*third_term;\n  //\n  //\n  //     double templik0=exp(arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term2))-expon*log(nu*lambdaBART - mvm2 +yty)));\n  //\n\n\n\n\n\n    // Rcout << \"log(temp_sse)= \" << log(temp_sse) << \". \\n\";\n    //\n    //\n    // Rcout << \"temp_sse= \" << temp_sse << \". \\n\";\n    //\n\n\n\n      // Rcout << \"templik0= \" << templik0 << \". \\n\";\n//\n//       Rcout << \"b= \" << b << \". \\n\";\n//       Rcout << \"(b*0.5)*log(a)= \" << (b*0.5)*log(a) << \". \\n\";\n//\n//       Rcout << \"-0.5*log(det(sec_term))= \" << -0.5*log(det(sec_term)) << \". \\n\";\n//       Rcout << \"det(sec_term)= \" << det(sec_term) << \". \\n\";\n//       Rcout << \"arma::det(sec_term)= \" << arma::det(sec_term) << \". \\n\";\n//       Rcout << \"arma::log_det(sec_term)= \" << arma::log_det(sec_term) << \". \\n\";\n//       Rcout << \"real(arma::log_det(sec_term))= \" << real(arma::log_det(sec_term)) << \". \\n\";\n//       Rcout << \"log(det(sec_term))= \" << log(det(sec_term)) << \". \\n\";\n//       Rcout << \"log(arma::det(sec_term))= \" << log(arma::det(sec_term)) << \". \\n\";\n//\n//       Rcout << \"-expon*log(nu*lambdaBART - mvm +yty)= \" << -expon*log(nu*lambdaBART - mvm +yty) << \". \\n\";\n//\n//\n//       // Rcout << \"val= \" << val << \". \\n\";\n//\n// Rcout << \"arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term))-expon*log(nu*lambdaBART - mvm +yty)) .\\n\" << arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term))-expon*log(nu*lambdaBART - mvm +yty)) << \".\\n\";\n//       ////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n      ////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n      //overall_treetables[j]= wrap(tree_table1);\n\n\n      //double templik = as<double>(treepred_output[1]);\n\n      //double templik = pow(templik0,beta_par);\n\n      double templik = beta_par*templik0;\n\n      if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n        //templik=templik*(sum_tree_prior_prob/sum_tree_samp_prob);\n        //templik=templik*sum_prior_over_samp_prob;\n        templik=templik+log(sum_prior_over_samp_prob);\n\n      }\n      overall_liks(j)= templik;\n\n      // if(std::isnan(templik)){\n      // Rcout << \"Line 3943, j= \" << j << \". \\n\";\n      // Rcout << \"templik= \" << templik << \". \\n\";\n      // Rcout << \"sum_tree_prior_prob= \" << sum_tree_prior_prob << \". \\n\";\n      // Rcout << \"sum_tree_samp_prob= \" << sum_tree_samp_prob << \". \\n\";\n      // }\n\n\n      //now fill in the predictions\n\n      //If want tree tables with predictions filled in, use\n      // arma::vec term_node_par_means = sec_term_inv*third_term;\n      // //and would need to save a field of tree tables,\n      // //add add a column, or begin with one more column\n      // //then the first treetableF[0].n_rows elements of term_node_par_means\n      // //give the first\n      // int row_count1=0;\n      // for(int tree_i=0; tree_i < treetableF.n_elem; tree_i++){\n      //   tabletemp= treetableF(i);\n      //   tabletemp.col(5) = term_node_par_means(arma::span(row_count1,tabletemp.n_rows));\n      //   treetableF(i)=tabletemp;\n      //   row_count1+=tabletemp.n_rows;\n      // }\n      //This would give an alternative method for obtaining test data predictions\n      //Look up the terminal nodes and add the relevant terminal node parameters\n\n\n\n\n      //arma::vec pred_vec(testdata_arma.n_rows);\n\n      ////////////\n      arma::vec preds_temp_arma= W_tilde*sec_term_inv*third_term;\n\n  ////////////////////\n\n\n\n\n\n      //arma::vec preds_temp_arma= W_tilde*sec_term_inv2*third_term;\n\n\n\n      //THIS SHOULD BE DIFFERENT IF THE CODE IS TO BE PARALLELIZED\n      //EACH THREAD SHOULD OUTPUT ITS OWN MATRIX AND SUM OF LIKELIHOODS\n      //THEN ADD THE MATRICES TOGETHER AND DIVIDE BY THE TOTAL SUM OF LIKELIHOODS\n      //OR JUST SAVE ALL MATRICES TO ONE LIST\n\n\n      //pred_mat_overall = pred_mat_overall + templik*pred_mat;\n      //overall_treetables(j)= pred_mat*templik;\n\n\n      //overall_preds(j)=preds_temp_arma*templik;\n\n      overall_preds(j)=preds_temp_arma;\n\n\n\n\n      //Rcout << \"Line 3985, j= \" << j << \". \\n\";\n\n\n      //Rcout << \"preds_temp_arma= \" << preds_temp_arma << \". \\n\";\n      //Rcout << \"preds_temp_arma*templik= \" << preds_temp_arma*templik << \". \\n\";\n\n      //overall_treetables(j)= pred_mat;\n      //overall_liks(j) =templik;\n\n      //arma::mat treeprob_output = get_test_probs(weights, num_cats,\n      //                                           testdata,\n      //                                           treetable_list[i]  );\n\n      //Rcout << \"Line 688. i== \" << i << \". \\n\";\n\n      //double weighttemp = weights[i];\n      //Rcout << \"Line 691. i== \" << i << \". \\n\";\n\n      //pred_mat_overall = pred_mat_overall + weighttemp*treeprob_output;\n\n\n    }//end of else statement\n  }//end of loop over all trees\n\n}//end of pragma omp code\n\n\n///////////////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////////////////////////////////////////////////////////////\n\n\n//for(unsigned int i=0; i<overall_treetables.n_elem;i++){\n//  pred_mat_overall = pred_mat_overall + overall_liks(i)*overall_treetables(i);\n//}\n\n\nif(fast_approx==1){\n  arma::vec BICi=-0.5*overall_liks;\n  double max_BIC=max(BICi);\n\n  // weighted_BIC is actually the posterior model probability\n  arma::vec weighted_BIC(overall_liks.size());\n\n\n  double tempterm=(max_BIC+log(sum(exp(BICi-max_BIC))));\n\n  for(unsigned int k=0;k<overall_liks.size();k++){\n\n    //NumericVector BICi=-0.5*BIC_weights;\n    //double max_BIC=max(BICi);\n    double weight=exp(BICi[k]-tempterm);\n    weighted_BIC[k]=weight;\n    //int num_its_to_sample = round(weight*(num_iter));\n\n  }\n\n  //Rcout << \"weighted_BIC= \" << weighted_BIC << \". \\n\";\n  //Rcout << \"overall_liks= \" << overall_liks << \". \\n\";\n\n  #pragma omp parallel num_threads(ncores)\n  {\n    arma::vec result_private=arma::zeros<arma::vec>(arma_test_data.n_rows);\n  #pragma omp for nowait //fill result_private in parallel\n    for(unsigned int i=0; i<overall_preds.size(); i++){\n      //double weight=exp(BICi[i]-(max_BIC+log(sum(exp(BICi-max_BIC)))));\n      result_private += overall_preds(i)*weighted_BIC(i);\n    }\n  #pragma omp critical\n    pred_vec_overall += result_private;\n  }\n\n\n  }else{ //if fast_approx==0\n\n    //arma::vec BICi=-0.5*overall_liks;\n    double max_loglik=max(overall_liks);\n\n    // weighted_BIC is actually the posterior model probability\n    arma::vec weighted_lik(overall_liks.size());\n\n\n    double tempterm=(max_loglik+log(sum(exp(overall_liks-max_loglik))));\n\n    for(unsigned int k=0;k<overall_liks.size();k++){\n\n      //NumericVector BICi=-0.5*BIC_weights;\n      //double max_BIC=max(BICi);\n      double weight=exp(overall_liks[k]-tempterm);\n      weighted_lik[k]=weight;\n      //int num_its_to_sample = round(weight*(num_iter));\n\n    }\n\n    //Rcout << \"weighted_lik= \" << weighted_lik << \". \\n\";\n    //Rcout << \"overall_liks= \" << overall_liks << \". \\n\";\n\n    #pragma omp parallel num_threads(ncores)\n    {\n      arma::vec result_private=arma::zeros<arma::vec>(arma_test_data.n_rows);\n    #pragma omp for nowait //fill result_private in parallel\n      for(unsigned int i=0; i<overall_preds.size(); i++) result_private += overall_preds(i)*weighted_lik(i);\n    #pragma omp critical\n      pred_vec_overall += result_private;\n    }\n\n\n    //double sumlik_total= arma::sum(overall_liks);\n    //Rcout << \"sumlik_total = \" << sumlik_total << \". \\n\";\n\n    //pred_vec_overall=pred_vec_overall*(1/sumlik_total);\n\n  }\n\n\n//Rcout << \"Line 4030. \\n\";\n\n\n\n\n\n\n\n//double sumlik_total= arma::sum(overall_liks);\n//Rcout << \"sumlik_total = \" << sumlik_total << \". \\n\";\n\n//pred_vec_overall=pred_vec_overall*(1/sumlik_total);\n//Rcout << \"Line 1141 . \\n\";\n//Rcout << \"Line 1146 . \\n\";\n\n\n//Rcout << \"Line 4042. \\n\";\nNumericVector orig_preds=get_original(min(ytrain),max(ytrain),-0.5,0.5,wrap(pred_vec_overall)) ;\n\n\nreturn(orig_preds);\n\n}\n//######################################################################################################################//\n\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::depends(dqrng, BH, sitmo)]]\n#include <xoshiro.h>\n#include <dqrng_distribution.h>\n//#include <dqrng.h>\n\n// [[Rcpp::plugins(openmp)]]\n#include <omp.h>\n\n//' @title Parallel Safe-Bayesian Causal Forest\n//'\n//' @description A parallelized implementation of the Safe-Bayesian Random Forest described by Quadrianto and Ghahramani (2015)\n//' @param lambda A real number between 0 and 1 that determines the splitting probability in the prior (which is used as the importance sampler of tree models). Quadrianto and Ghahramani (2015) recommend a value less than 0.5 .\n//' @param num_trees The number of trees to be sampled.\n//' @param seed The seed for random number generation.\n//' @param num_cats The number of possible values for the outcome variable.\n//' @param y The training data vector of outcomes. This must be a vector of integers between 1 and num_cats.\n//' @param original_datamat The original training data. Currently all variables must be continuous. The training data does not need to be transformed before being entered to this function.\n//' @param alpha_parameters Vector of prior parameters.\n//' @param beta_par The power to which the likelihood is to be raised. For BMA, set beta_par=1.\n//' @param original_datamat The original test data. This matrix must have the same number of columns (variables) as the training data. Currently all variables must be continuous. The test data does not need to be transformed before being entered to this function.\n//' @param ncores The number of cores to be used in parallelization.\n//' @return A matrix of probabilities with the number of rows equl to the number of test observations and the number of columns equal to the number of possible outcome categories.\n//' @export\n// [[Rcpp::export]]\nNumericVector sBCF_onefunc_parallel(double lambda_mu,\n                                    double lambda_tau,\n                                     int num_models,\n                                     int num_trees_mu,\n                                     int num_trees_tau,\n                                     int seed,\n                                     NumericVector ytrain,\n                                     NumericMatrix original_datamat,\n                                     NumericVector ztrain,\n                                     NumericMatrix pihat_train,\n                                     double beta_par,\n                                     NumericMatrix test_datamat,\n                                     NumericMatrix test_pihat,\n                                     int ncores,\n                                     int outsamppreds,\n                                     double nu,\n                                     double a_mu,\n                                     double a_tau,\n                                     double lambdaBCF,\n                                     int valid_trees,\n                                     int tree_prior,\n                                     int imp_sampler,\n                                     double alpha_BCF_mu,\n                                     double beta_BCF_mu,\n                                     double alpha_BCF_tau,\n                                     double beta_BCF_tau,\n                                     int include_pi2,\n                                     int fast_approx,\n                                     int PIT_propensity){\n\n\n  //Check that various input vectors and matrices have consistent dimensions\n\n  //Rcout << \"Line 4528.\\n\";\n\n  bool is_test_data=0;\t\t\t\t\t// create bool is_test_data. Initialize equal to 0.\n  if(test_datamat.nrow()>0){\t\t\t\t\t// If test data has non-zero number of rows.\n    is_test_data=1;\t\t\t\t\t\t// set is_test_data equal to 1.\n  }\n  if(ytrain.size() !=original_datamat.nrow()){\t\t\t\t// If the length of input vector y is not equal to the nunber of rows in the input data (covariates)\n    if(ytrain.size()<original_datamat.nrow()){\t\t\t// If the length of y is less than the number of rows in data\n      throw std::range_error(\"Response length is smaller than the number of observations in the data\");\n    }else{\t\t\t\t\t\t\t\t// If the length of y is greater than the number of rows in data\n      throw std::range_error(\"Response length is greater than the number of observations in the data\");\n    }\n  }\n  if(ztrain.size() !=original_datamat.nrow()){\t\t\t\t// If the length of input vector z is not equal to the nunber of rows in the input data (covariates)\n    if(ztrain.size()<original_datamat.nrow()){\t\t\t// If the length of z is less than the number of rows in data\n      throw std::range_error(\"Treatment indicator vector length is smaller than the number of observations in the data\");\n    }else{\t\t\t\t\t\t\t\t// If the length of z is greater than the number of rows in data\n      throw std::range_error(\"Treatment indicator vector length is greater than the number of observations in the data\");\n    }\n  }\n  if(pihat_train.nrow() !=original_datamat.nrow()){\t\t\t\t// If the nunber of rows in the input matrix pihat is not equal to the nunber of rows in the input data (covariates)\n    if(pihat_train.nrow()<original_datamat.nrow()){\t\t\t// If the nunber of rows in the input matrix pihat is less than the number of rows in data\n      throw std::range_error(\"The nunber of rows in the input matrix pihat_train is smaller than the number of observations in the data\");\n    }else{\t\t\t\t\t\t\t\t// If the nunber of rows in the input matrix pihat is greater than the number of rows in data\n      throw std::range_error(\"The nunber of rows in the input matrix pihat_train is greater than the number of observations in the data\");\n    }\n  }\n  //check test data has the same number of variables as training data\n  if(test_datamat.nrow()>0 && (original_datamat.ncol() != test_datamat.ncol())){\t// If the number of rows in the test data is >0 AND the number of columns (variables) is not equal to that of data (the training data)\n    throw std::range_error(\"Test data and training data must have the same number of variables. BART BMA assumes variables are in the same order.\");\n  }\n  //if(test_z.size() != test_datamat.nrow()){\t// If the number of rows in the test data covariate matrix is not equal to that of the test data treatment indicator variable\n  //  throw std::range_error(\"Test data covariates and test data treatment indicator variable must have the same number of observations.\");\n  //}\n  if(test_datamat.nrow() != test_pihat.nrow()){\t// If the number of rows in the test data covariate matrix is not equal to that of the test data propensity score estimates matrix\n    throw std::range_error(\"Test data covariates and test data propensity score estimates must have the same number of observations.\");\n  }\n  if(test_pihat.nrow()>0 && (pihat_train.ncol() != test_pihat.ncol())){\t// If the number of rows in the test data propensity score estimates is >0 AND the number of columns (variables) is not equal to that of the training data propensity score estimates\n    throw std::range_error(\"Test data propensity score estimates and training data propensity score estimates must have the same number of columns. BART BMA assumes variables are in the same order.\");\n  }\n\n  ///////////////////////////////////////////////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n  // Now add propensity score estimates matrix as new leftmost column of data matrix. Call the resulting matrix x_control (to be consistent with terminology used by bcf package).\n  arma::mat D1(original_datamat.begin(), original_datamat.nrow(), original_datamat.ncol(), false);\t\t\t\t// copy the covariate data matrix into an arma mat\n  arma::mat pihat_1(pihat_train.begin(), pihat_train.nrow(), pihat_train.ncol(), false);\t\t\t\t// copy the pihat matrix into an arma mat\n  //arma::mat x_control_a=D1;\t\t\t\t// create a copy of data arma mat called x_control_a\n\n\n  //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n  arma::mat x_control_a_temp(D1.n_rows,D1.n_cols);\n  for(unsigned int k=0; k<D1.n_cols;k++){\n    arma::vec samp= D1.col(k);\n    arma::vec sv=arma::sort(samp);\n    //std::sort(sv.begin(), sv.end());\n    arma::uvec ord = arma::sort_index(samp);\n    double nobs = samp.n_elem;\n    arma::vec ans(nobs);\n    for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n      int ind=ord(i);\n      double ssampi(samp[ind]);\n      while (sv(j) < ssampi && j < sv.size()) ++j;\n      ans(ind) = j;     // j is the 1-based index of the lower bound\n    }\n    x_control_a_temp.col(k)=(ans+1)/nobs;\n  }\n\n  arma::mat x_control_a=x_control_a_temp;\t\t\t// create arma mat copy of x_control_a_temp.\n\n  arma::mat x_moderate_a=x_control_a_temp;\t\t\t// create arma mat copy of x_control_a_temp.\n\n  arma::mat pihat_a(pihat_1.n_rows,pihat_1.n_cols);\n\n  if(PIT_propensity==1){\n\n    //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n    for(unsigned int k=0; k<pihat_1.n_cols;k++){\n      arma::vec samp= pihat_1.col(k);\n      arma::vec sv=arma::sort(samp);\n      //std::sort(sv.begin(), sv.end());\n      arma::uvec ord = arma::sort_index(samp);\n      double nobs = samp.n_elem;\n      arma::vec ans(nobs);\n      for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n        int ind=ord(i);\n        double ssampi(samp[ind]);\n        while (sv(j) < ssampi && j < sv.size()) ++j;\n        ans(ind) = j;     // j is the 1-based index of the lower bound\n      }\n      pihat_a.col(k)=(ans+1)/nobs;\n    }\n  }else{\n    pihat_a=pihat_1;\n  }\n\n\n\n  if((include_pi2==0) | (include_pi2==2) ){\n    if(pihat_train.nrow()>0 ){\n      x_control_a.insert_cols(0,pihat_a);\t\t// add propensity scores as new leftmost columns of x_control_a\n    }\n  }\n  // Rcout << \"Number of columns of matrix\" << x_control_a.n_cols << \".\\n\";\n\n\n  //NumericMatrix x_control=wrap(x_control_a);\t// convert x_control_a to a NumericMatrix called x_control\n\n  // Name the matrix without the estimated propensity scores x_moderate.[CAN REMOVE THE DUPLICATION AND ADD x_control, x_moderate, and include_pi as input parameters later]\n  //NumericMatrix x_moderate = data;\t// x_moderate matrix is the covariate data without the propensity scores\n  //arma::mat x_moderate_a=D1;\t\t\t// create arma mat copy of x_moderate.\n  if((include_pi2==1)| (include_pi2==2) ){\n    if(pihat_train.nrow()>0 ){\n      x_moderate_a.insert_cols(0,pihat_a);\t\t// add propensity scores as new leftmost columns of x_control_a\n    }\n  }\n\n\n  //NumericMatrix x_moderate=wrap(x_moderate_a);\t// convert x_control_a to a NumericMatrix called x_control\n\n\n  // Rcout << \"Get to Line 7139  \"  << \".\\n\";\n  // Add test propensity scores to test data matrix\n  arma::mat T1(test_datamat.begin(), test_datamat.nrow(), test_datamat.ncol(), false);\t\t\t\t// copy the covariate test_data matrix into an arma mat\n  arma::mat pihat_1_test(test_pihat.begin(), test_pihat.nrow(), test_pihat.ncol(), false);\t\t\t\t// copy the test_pihat matrix into an arma mat\n  //arma::mat x_control_test_a=T1;\t\t\t\t// create a copy of test_data arma mat called x_control_test_a\n\n  arma::mat x_control_test_a(T1.n_rows,T1.n_cols);\n  arma::mat x_moderate_test_a(T1.n_rows,T1.n_cols);\n  arma::mat pihat_a_test(pihat_1_test.n_rows,pihat_1_test.n_cols);\n\n  if(is_test_data==1){\n    //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n    arma::mat x_control_a_test_temp(T1.n_rows,T1.n_cols);\n\n    for(unsigned int k=0; k<T1.n_cols;k++){\n      arma::vec samp= T1.col(k);\n      arma::vec sv=arma::sort(samp);\n      //std::sort(sv.begin(), sv.end());\n      arma::uvec ord = arma::sort_index(samp);\n      double nobs = samp.n_elem;\n      arma::vec ans(nobs);\n      for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n        int ind=ord(i);\n        double ssampi(samp[ind]);\n        while (sv(j) < ssampi && j < sv.size()) ++j;\n        ans(ind) = j;     // j is the 1-based index of the lower bound\n      }\n      x_control_a_test_temp.col(k)=(ans+1)/nobs;\n    }\n\n    arma::mat x_control_test_a=x_control_a_test_temp;\t\t\t// create arma mat copy of x_control_a_temp.\n\n    arma::mat x_moderate_test_a=x_control_a_test_temp;\t\t\t// create arma mat copy of x_control_a_temp.\n\n    if(PIT_propensity==1){\n      //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n      for(unsigned int k=0; k<pihat_1_test.n_cols;k++){\n        arma::vec samp= pihat_1_test.col(k);\n        arma::vec sv=arma::sort(samp);\n        //std::sort(sv.begin(), sv.end());\n        arma::uvec ord = arma::sort_index(samp);\n        double nobs = samp.n_elem;\n        arma::vec ans(nobs);\n        for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n          int ind=ord(i);\n          double ssampi(samp[ind]);\n          while (sv(j) < ssampi && j < sv.size()) ++j;\n          ans(ind) = j;     // j is the 1-based index of the lower bound\n        }\n        pihat_a_test.col(k)=(ans+1)/nobs;\n      }\n    }else{\n      pihat_a_test=pihat_1_test;\n    }\n\n\n  }\n\n\n\n  if((include_pi2==0)| (include_pi2==2) ){\n    if(test_pihat.nrow()>0 ){\n      x_control_test_a.insert_cols(0,pihat_a_test);\t\t// add propensity scores as new leftmost columns of x_control_test_a\n    }\n  }\n\n\n  //NumericMatrix x_control_test=wrap(x_control_test_a);\t// convert x_control_test_a to a NumericMatrix called x_control_test\n\n\n  // Name the matrix without the estimated propensity scores x_moderate_test.[CAN REMOVE THE DUPLICATION AND ADD x_control_test, x_moderate_test, and include_pi as input parameters later]\n  //NumericMatrix x_moderate_test = test_data;\t// x_moderate_test matrix is the covariate test_data without the propensity scores\n  //arma::mat x_moderate_test_a=T1;\t\t\t// create arma mat copy of x_moderate_test.\n  if((include_pi2==1)| (include_pi2==2) ){\n    if(test_pihat.nrow()>0 ){\n      x_moderate_test_a.insert_cols(0,pihat_a_test);\t\t// add propensity scores as new leftmost columns of x_control_a\n    }\n  }\n\n  //NumericMatrix x_moderate_test=wrap(x_moderate_test_a);\t// convert x_control_test_a to a NumericMatrix called x_control_test\n\n\n\n  //////////////////////////////////////////////////////////////////////////////////////////\n  //Rcout << \"Line 4715.\\n\";\n\n  //////////////////////////////////////////////////////////////////////////////////////////\n\n  //End of checks and adding propensity scores to matrices\n\n  NumericVector y_scaled=scale_response(min(ytrain),max(ytrain),-0.5,0.5,ytrain);\n\n  arma::vec z_ar=Rcpp::as<arma::vec>(ztrain);\t\t// converts to arma vec\n\n\n  int num_split_vars_mu= x_control_a.n_cols;\n\n  int num_split_vars_tau= x_moderate_a.n_cols;\n\n\n  //Rcout << \"num_split_vars_mu = \" << num_split_vars_mu << \".\\n\" ;\n  //Rcout << \"num_split_vars_tau = \" << num_split_vars_tau << \".\\n\" ;\n\n  //arma::mat data_arma= as<arma::mat>(original_datamat);\n  //arma::mat testdata_arma= as<arma::mat>(test_datamat);\n\n\n  arma::vec orig_y_arma= as<arma::vec>(y_scaled);\n  //arma::vec alpha_pars_arma= as<arma::vec>(alpha_parameters);\n  int num_obs = x_control_a.n_rows;\n  int num_test_obs = x_control_test_a.n_rows;\n\n\n  //calculations for likelihood\n  arma::mat y(num_obs,1);\n  y.col(0)=orig_y_arma;\n  //get exponent\n  double expon=(num_obs+nu)*0.5;\n  //get y^Tpsi^{-1}y\n  // arma::mat psi_inv=psi.i();\n  arma::mat yty=y.t()*y;\n\n\n\n\n\n\n\n  /////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n  //////////////////////////////////////////////////////////////////////////////////////\n  //List table_list = draw_trees(lambda, num_trees, seed, num_split_vars, num_cats );\n\n\n\n  //dqrng::dqRNGkind(\"Xoroshiro128+\");\n  //dqrng::dqset_seed(IntegerVector::create(seed));\n\n  //use following with binomial?\n  //dqrng::xoshiro256plus rng(seed);\n\n  std::vector<double> lambdavec_mu = {lambda_mu, 1-lambda_mu};\n  std::vector<double> lambdavec_tau = {lambda_tau, 1-lambda_tau};\n\n  //typedef boost::mt19937 RNGType;\n  //boost::random::uniform_int_distribution<> sample_splitvardist(1,num_split_vars);\n  //boost::variate_generator< RNGType, boost::uniform_int<> >  sample_splitvars(rng, sample_splitvardist);\n\n  //boost::random::uniform_real_distribution<double> b_unifdist(0,1);\n  //boost::variate_generator< RNGType, boost::uniform_real<> >  b_unif_point(rng, b_unifdist);\n\n\n\n  std::random_device device;\n  //std::mt19937 gen(device());\n\n  //possibly use seed?\n  //// std::mt19937 gen(seed);\n\n  dqrng::xoshiro256plus gen(device());              // properly seeded rng\n\n  //dqrng::xoshiro256plus gen(seed);              // properly seeded rng\n\n\n\n\n  std::bernoulli_distribution coin_flip_mu(lambda_mu);\n  std::bernoulli_distribution coin_flip_tau(lambda_tau);\n\n  std::uniform_int_distribution<> distsampvar_mu(1, num_split_vars_mu);\n  std::uniform_int_distribution<> distsampvar_tau(1, num_split_vars_tau);\n\n  std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n\n  //dqrng::uniform_distribution dis_cont_unif(0.0, 1.0); // Uniform distribution [0,1)\n\n  //Following three functions can't be used in parallel\n  //dqrng::dqsample_int coin_flip2(2, 1, true,lambdavec );\n  //dqrng::dqsample_int distsampvar(num_split_vars, 1, true);\n  //dqrng::dqrunif dis_cont_unif(1, 0, 1);\n\n\n\n  //arma::mat arma_test_data(testdat_trans.begin(), testdat_trans.nrow(), testdat_trans.ncol(), false);\n\n\n  arma::vec pred_vec_overall;\n  arma::vec pred_vec_overall_mu;\n  arma::vec pred_vec_overall_y;\n\n  if(is_test_data==1){\n    pred_vec_overall=arma::zeros<arma::vec>(x_moderate_test_a.n_rows);\n  }else{\n    pred_vec_overall=arma::zeros<arma::vec>(x_moderate_a.n_rows);\n    pred_vec_overall_mu=arma::zeros<arma::vec>(x_moderate_a.n_rows);\n    pred_vec_overall_y=arma::zeros<arma::vec>(x_moderate_a.n_rows);\n\n  }\n\n  //arma::field<arma::mat> overall_treetables(num_models);\n\n  arma::field<arma::vec> overall_preds(num_models);\n  //arma::field<arma::vec> overall_preds_mu(num_models);\n  //arma::field<arma::vec> overall_preds_y(num_models);\n\n\n  // arma::mat overall_preds(x_moderate_a.n_rows, num_models);\n  // arma::mat overall_preds_mu(x_moderate_a.n_rows, num_models);\n  // arma::mat overall_preds_y(x_moderate_a.n_rows, num_models);\n\n  arma::vec overall_liks(num_models);\n\n\n  //overall_treetables[i]= wrap(tree_table1);\n  //double templik = as<double>(treepred_output[1]);\n  //overall_liks[i]= pow(lik_prod,beta_pow);\n\n  //Rcout << \"Line 3338. \\n\";\n\n  //Rcout << \"Line 4836.\\n\";\n\n#pragma omp parallel num_threads(ncores)\n{//start of pragma omp code\n  dqrng::xoshiro256plus lgen(gen);      // make thread local copy of rng\n  lgen.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... ncores jumps\n\n#pragma omp for\n  for(int j=0; j<num_models;j++){\n\n    arma::mat Wmat_mu(num_obs,0);\n    arma::mat Wmat_tau(num_obs,0);\n\n    //maybe use line below, depends how Jmat joined to Wmat\n    //int upsilon=0;\n\n    arma::mat W_tilde_mu(num_test_obs,0);\n    arma::mat W_tilde_tau(num_test_obs,0);\n\n    //maybe use line below, depends how Jmat joined to Wmat\n    //int upsilon2=0;\n\n    //double sum_tree_samp_prob=1;\n    //double sum_tree_prior_prob=1;\n\n    double sum_prior_over_samp_prob=1;\n\n    for(int q=0; q<num_trees_mu;q++){  //start of loop over trees in sum\n\n\n      //If parallelizing, define the distributinos before this loop\n      //and use lrng and the following two lines\n      //dqrng::xoshiro256plus lrng(rng);      // make thread local copy of rng\n      //lrng.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... nthreads jumps\n\n\n      //NumericVector treenodes_bin(0);\n      //arma::uvec treenodes_bin(0);\n\n      std::vector<int> treenodes_bin;\n\n\n      int count_terminals = 0;\n      int count_internals = 0;\n\n      //int count_treebuild = 0;\n\n\n      if(imp_sampler==1){ //If sampling from BART prior\n\n        double depth1=0;\n        int prev_node=0; //1 if previous node splits, zero otherwise\n\n        double samp_prob;\n\n        while(count_internals > (count_terminals -1)){\n          samp_prob=alpha_BCF_mu*pow(double(depth1+1),-beta_BCF_mu);\n          std::bernoulli_distribution coin_flip2(samp_prob);\n\n          int tempdraw = coin_flip2(lgen);\n          treenodes_bin.push_back(tempdraw);\n\n          if(tempdraw==1){\n\n            depth1=depth1+1; //after a split, the depth will increase by 1\n            prev_node=1;\n            count_internals=count_internals+1;\n\n          }else{\n\n            if(prev_node==1){//zero following a 1, therefore at same depth.\n              //Don't change depth. Do nothing\n            }else{ //zero following a zero, therefore the depth will decrease by 1\n              depth1=depth1-1;\n            }\n            prev_node=0;\n            count_terminals=count_terminals+1;\n\n          }\n\n        }\n\n      }else{  //If not sampling from BAT prior\n        if(imp_sampler==2){//If sampling from spike and tree prior\n          throw std::range_error(\"code not yet written for spike and tree sampling\");\n\n        }else{//If sampling from default Q+G prior. i.e. not sampling from BART nor spike and tree prior\n\n          while(count_internals > (count_terminals -1)){\n\n            //Also consider standard library and random header\n            // std::random_device device;\n            // std::mt19937 gen(device());\n            // std::bernoulli_distribution coin_flip(lambda);\n            // bool outcome = coin_flip(gen);\n\n\n            int tempdraw = coin_flip_mu(lgen);\n\n            //int tempdraw = rbinom(n = 1, prob = lambda,size=1);\n\n\n            //int tempdraw = Rcpp::rbinom(1,lambda,1);\n            //int tempdraw = R::rbinom(1,lambda);\n\n            ////Rcout << \"tempdraw = \" << tempdraw << \".\\n\" ;\n\n            //int tempdraw = coin_flip2(lgen)-1;\n\n            //int tempdraw = dqrng::dqsample_int(2, 1, true,lambdavec )-1;\n\n\n            //need to update rng if use boost?\n            //int tempdraw = bernoulli(rng, binomial::param_type(1, lambda));\n\n            treenodes_bin.push_back(tempdraw);\n\n\n            if(tempdraw==1){\n              count_internals=count_internals+1;\n            }else{\n              count_terminals=count_terminals+1;\n            }\n\n          }//end of while loop creating parent vector treenodes_bin\n        }\n\n      }\n\n\n\n      //Consider making this an armadillo vector\n      //IntegerVector split_var_vec(treenodes_bin.size());\n      //arma::uvec split_var_vec(treenodes_bin.size());\n      std::vector<int> split_var_vec(treenodes_bin.size());\n\n      //loop drawing splitting variables\n      //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n      //if using armadillo, it might be faster to subset to split nodes\n      //then use a vector of draws\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        if(treenodes_bin[i]==0){\n          split_var_vec[i] = -1;\n        }else{\n          // also consider the standard library function uniform_int_distribution\n          // might need random header\n          // This uses the Mersenne twister\n\n          //Three lines below should probably be outside all the loops\n          // std::random_device rd;\n          // std::mt19937 engine(rd());\n          // std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n          //\n          // split_var_vec[i] = distsampvar(engine);\n\n          split_var_vec[i] = distsampvar_mu(lgen);\n\n\n          //consider using boost\n          //might need to update rng\n          //split_var_vec[i] <- sample_splitvars(rng);\n\n          //or use dqrng\n          //not sure if have to update the random number\n          //check if the following line is written properly\n          //split_var_vec[i] = dqrng::dqsample_int(num_split_vars, 1, true);\n\n          //not sure if this returns an integer or a vector?\n          //split_var_vec[i] = RcppArmadillo::sample(num_split_vars, 1,true);\n          //could try\n          //split_var_vec[i] = as<int>(Rcpp::sample(num_split_vars, 1,true));\n          //could also try RcppArmadillo::rmultinom\n\n        }\n\n      }// end of for-loop drawing split variables\n\n\n      //Consider making this an armadillo vector\n      //NumericVector split_point_vec(treenodes_bin.size());\n      //arma::vec split_point_vec(treenodes_bin.size());\n      std::vector<double> split_point_vec(treenodes_bin.size());\n\n\n      //loop drawing splitting points\n      //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n      //if using armadillo, it might be faster to subset to split nodes\n      //then use a vector of draws\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        if(treenodes_bin[i]==0){\n          split_point_vec[i] = -1;\n        }else{\n\n\n          //////////////////////////////////////////////////////////\n          //following function not reccommended\n          //split_point_vec[i] = std::rand();\n          //////////////////////////////////////////////////////////\n          ////Standard library:\n          ////This should probably be outside all the loops\n          ////std::random_device rd;  //Will be used to obtain a seed for the random number engine\n          ////std::mt19937 gen2(rd()); //Standard mersenne_twister_engine seeded with rd()\n          ////std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n          split_point_vec[i] = dis_cont_unif(lgen);\n\n          //////////////////////////////////////////////////////////\n          //from armadillo\n          //split_point_vec[i] = arma::randu();\n\n          //////////////////////////////////////////////////////////\n          //probably not adviseable for paralelization\n          //From Rcpp\n          //split_point_vec[i] = as<double>(Rcpp::runif(1,0,1));\n\n          //////////////////////////////////////////////////////////\n          //consider using boost\n          //might need to update rng\n          //split_point_vec[i] <- b_unif_point(rng);\n\n          //or use dqrng\n          //not sure if have to update the random number\n          //check if the following line is written properly\n          //split_point_vec[i] = dqrng::dqrunif(1, 0, 1);\n\n          //not sure if this returns an integer or a vector?\n\n\n\n\n\n        }\n\n      }// end of for-loop drawing split points\n\n\n\n\n\n      //CODE FOR ADJUSTING SPLITTING POINTS SO THAT THE TREES ARE VALID\n      if(valid_trees==1){\n        for(unsigned int i=0; i<treenodes_bin.size();i++){ //loop over all nodes\n          if(treenodes_bin[i]==1){ // if it is an internal node, then check for further splits on the same variable and update\n            double first_split_var=split_var_vec[i];      //splitting variable to check for\n            double first_split_point=split_point_vec[i];  //splitting point to use in updates\n\n            double sub_int_nodes=0;       //this internal node count will be used to determine if in subtree relevant to sub_int_nodes\n            double sub_term_nodes=0;      //this terminal node count will be used to determine if in subtree relevant to sub_int_nodes\n            double preventing_updates=0; //indicates if still within subtree that is not to be updated\n            double prevent_int_count=0;   //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n            double prevent_term_count=0;  //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n            for(unsigned int k=i+1; k<treenodes_bin.size();k++){\n              if(treenodes_bin[k]==1){\n                sub_int_nodes=sub_int_nodes+1;\n                if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                  prevent_int_count=prevent_int_count+1;\n                }\n              }else{\n                sub_term_nodes=sub_term_nodes+1;\n                if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                  prevent_term_count=prevent_term_count+1;\n                }\n              }\n              if(sub_int_nodes<=sub_term_nodes-2){\n                break;\n              }\n\n\n              if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                if(prevent_int_count>prevent_term_count-1){ //if this rule is satisfied then in subtree that is not to be updated\n                  continue; //still in subtree, therefore continue instead of checking for splits to be updates\n                }else{\n                  preventing_updates=0; // no longer in subtree, therefore reset preventing_updates to zero\n                }\n              }\n\n\n              if(sub_int_nodes>sub_term_nodes-1){\n                if(treenodes_bin[k]==1){\n                  if(split_var_vec[k]==first_split_var){\n                    split_point_vec[k]=split_point_vec[k]*first_split_point;\n                    //beginning count of subtree that should not have\n                    //further splits on first_split_var updated\n                    preventing_updates=1; //indicates if still within subtree that is not to be updated\n                    prevent_int_count=1;\n                    prevent_term_count=0;\n                  }\n                }\n              }else{\n                if(treenodes_bin[k]==1){\n                  if(split_var_vec[k]==first_split_var){\n                    split_point_vec[k]=split_point_vec[k]+first_split_point-first_split_point*split_point_vec[k];\n                    //beginning count of subtree that should not have\n                    //further splits on first_split_var updated\n                    preventing_updates=1; //indicates if still within subtree that is not to be updated\n                    prevent_int_count=1;\n                    prevent_term_count=0;\n                  }\n                }\n              }\n\n\n\n            }//end of inner loop over k\n          }//end of if statement treenodes_bin[i]==1)\n        }//end of loop over i\n      }//end of if statement valid_trees==1\n\n\n\n\n\n      //Rcout << \"Line 5150.\\n\";\n\n\n\n\n\n      //Create tree table matrix\n\n      //NumericMatrix tree_table1(treenodes_bin.size(),5+num_cats);\n\n      //Rcout << \"Line 1037. \\n\";\n      //arma::mat tree_table1(treenodes_bin.size(),5+num_cats);\n\n      //initialize with zeros. Not sure if this is necessary\n      arma::mat tree_table1=arma::zeros<arma::mat>(treenodes_bin.size(),6);\n      //Rcout << \"Line 1040. \\n\";\n\n\n      //tree_table1(_,2) = wrap(split_var_vec);\n      //tree_table1(_,3) = wrap(split_point_vec);\n      //tree_table1(_,4) = wrap(treenodes_bin);\n\n      //It might be more efficient to make everything an armadillo object initially\n      // but then would need to replace push_back etc with a different approach (but this might be more efficient anyway)\n      arma::colvec split_var_vec_arma=arma::conv_to<arma::colvec>::from(split_var_vec);\n      arma::colvec split_point_vec_arma(split_point_vec);\n      arma::colvec treenodes_bin_arma=arma::conv_to<arma::colvec>::from(treenodes_bin);\n\n\n      //Rcout << \"Line 1054. \\n\";\n\n      //Fill in splitting variable column\n      tree_table1.col(2) = split_var_vec_arma;\n      //Fill in splitting point column\n      tree_table1.col(3) = split_point_vec_arma;\n      //Fill in split/parent column\n      tree_table1.col(4) = treenodes_bin_arma;\n\n\n      //Rcout << \"Line 5189. j = \" << j << \". \\n\";\n      //Rcout << \"Line 5190. tree_table1 mu = \" << tree_table1 << \". \\n\";\n\n\n\n      // Now start filling in left daughter and right daughter columns\n      std::vector<int> rd_spaces;\n      int prev_node = -1;\n\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        //Rcout << \"Line 1061. i = \" << i << \". \\n\";\n        if(prev_node==0){\n          //tree_table1(rd_spaces[rd_spaces.size()-1], 1)=i;\n          //Rcout << \"Line 1073. j = \" << j << \". \\n\";\n\n          tree_table1(rd_spaces.back(), 1)=i+1;\n          //Rcout << \"Line 1076. j = \" << j << \". \\n\";\n\n          rd_spaces.pop_back();\n        }\n        if(treenodes_bin[i]==1){\n          //Rcout << \"Line 1081. j = \" << j << \". \\n\";\n\n          tree_table1(i,0) = i+2;\n          rd_spaces.push_back(i);\n          prev_node = 1;\n          //Rcout << \"Line 185. j = \" << j << \". \\n\";\n\n        }else{                  // These 2 lines unnecessary if begin with matrix of zeros\n          //Rcout << \"Line 1089. j = \" << j << \". \\n\";\n          tree_table1(i,0)=0 ;\n          tree_table1(i,1) = 0 ;\n          prev_node = 0;\n          //Rcout << \"Line 1093. j = \" << j << \". \\n\";\n\n        }\n      }//\n      //Rcout << \"Line 1097. j = \" << j << \". \\n\";\n\n\n\n\n\n      //List treepred_output = get_treepreds(original_y, num_cats, alpha_pars,\n      //                                     originaldata,\n      //                                     treetable_list[i]  );\n\n\n      //use armadillo object tree_table1\n\n      ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n      ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n      //create variables for likelihood calcuations\n      // double lik_prod=1;\n      // double alph_prod=1;\n      // for(unsigned int i=0; i<alpha_pars_arma.n_elem;i++){\n      //   alph_prod=alph_prod*tgamma(alpha_pars_arma(i));\n      // }\n      // double gam_alph_sum= tgamma(arma::sum(alpha_pars_arma));\n      // double alph_term=gam_alph_sum/alph_prod;\n\n      //arma::mat arma_tree_table(treetable.begin(), treetable.nrow(), treetable.ncol(), false);\n      //arma::mat arma_orig_data(originaldata.begin(), originaldata.nrow(), originaldata.ncol(), false);\n\n\n      //arma::mat arma_tree(tree_data.begin(), tree_data.nrow(), tree_data.ncol(), false);\n      //arma::mat testd(test_data.begin(), test_data.nrow(), test_data.ncol(), false);\n\n      //NumericVector internal_nodes=find_internal_nodes_gs(tree_data);\n\n      //NumericVector terminal_nodes=find_term_nodes(treetable);\n\n      //arma::mat arma_tree(tree_table.begin(),tree_table.nrow(), tree_table.ncol(), false);\n\n      //arma::vec colmat=arma_tree.col(4);\n      //arma::uvec term_nodes=arma::find(colmat==-1);\n\n      //arma::vec colmat=arma_tree.col(2);\n      //arma::uvec term_nodes=arma::find(colmat==0);\n\n      //arma::vec colmat=tree_table1.col(4);\n      //arma::uvec term_nodes=arma::find(colmat==0);\n\n      //4th column is treenodes_bin_arma\n      arma::uvec term_nodes=arma::find(treenodes_bin_arma==0);\n\n      term_nodes=term_nodes+1;\n\n      //NumericVector terminal_nodes= wrap(term_nodes);\n\n\n      //Rcout << \"Line 5282.\\n\";\n\n      //GET J MATRIX\n\n      arma::mat Jmat(num_obs,term_nodes.n_elem);\n      arma::mat Jtilde(num_test_obs,term_nodes.n_elem);\n\n      //arma::vec arma_terminal_nodes=Rcpp::as<arma::vec>(terminal_nodes);\n      //NumericVector tree_predictions;\n\n      //now for each internal node find the observations that belong to the terminal nodes\n\n      //NumericVector predictions(test_data.nrow());\n      //List term_obs(term_nodes.n_elem);\n\n      //GET J MATRIX\n\n      if(term_nodes.n_elem==1){\n        //double nodemean=tree_data(terminal_nodes[0]-1,5);\t\t\t\t// let nodemean equal tree_data row terminal_nodes[i]^th row , 6th column. The minus 1 is because terminal nodes consists of indices starting at 1, but need indices to start at 0.\n        //predictions=rep(nodemean,test_data.nrow());\n        //Rcout << \"Line 67 .\\n\";\n\n        //IntegerVector temp_obsvec = seq_len(test_data.nrow())-1;\n        //term_obs[0]= temp_obsvec;\n        //double denom_temp= orig_y_arma.n_elem+arma::sum(alpha_pars_arma);\n\n        //double num_prod=1;\n        //double num_sum=0;\n        //Rcout << \"Line 129.\\n\";\n        Jmat.col(0) = arma::ones<arma::vec>(num_obs);\n\n        if(is_test_data==1){\n          Jtilde.col(0) = arma::ones<arma::vec>(num_test_obs);\n        }\n\n        //for(int k=0; k<num_cats; k++){\n        //assuming categories of y are from 1 to num_cats\n        //arma::uvec cat_inds= arma::find(orig_y_arma==k+1);\n        //double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n        //tree_table1(0,5+k)= m_plus_alph/denom_temp ;\n\n        //for likelihood calculation\n        //num_prod=num_prod*tgamma(m_plus_alph);\n        //num_sum=num_sum +m_plus_alph ;\n        //}\n\n        //lik_prod= alph_term*num_prod/tgamma(num_sum);\n\n      }\n      else{\n        for(unsigned int i=0;i<term_nodes.n_elem;i++){\n          //arma::mat subdata=testd;\n          //int curr_term=term_nodes(i);\n\n          int row_index;\n          int term_node=term_nodes(i);\n          //Rcout << \"Line 152.\\n\";\n\n\n          //WHAT IS THE PURPOSE OF THIS IF-STATEMENT?\n          //Why should the ro index be different for a right daughter?\n          //Why not just initialize row_index to any number not equal to 1 (e.g. 0)?\n          row_index=0;\n\n          // if(curr_term % 2==0){\n          //   //term node is left daughter\n          //   row_index=terminal_nodes[i];\n          // }else{\n          //   //term node is right daughter\n          //   row_index=terminal_nodes[i]-1;\n          // }\n\n\n\n\n          //save the left and right node data into arma uvec\n\n          //CHECK THAT THIS REFERS TO THE CORRECT COLUMNS\n          //arma::vec left_nodes=arma_tree.col(0);\n          //arma::vec right_nodes=arma_tree.col(1);\n\n          arma::vec left_nodes=tree_table1.col(0);\n          arma::vec right_nodes=tree_table1.col(1);\n\n\n\n          arma::mat node_split_mat;\n          node_split_mat.set_size(0,3);\n          //Rcout << \"Line 182. i = \" << i << \" .\\n\";\n\n          while(row_index!=1){\n            //for each terminal node work backwards and see if the parent node was a left or right node\n            //append split info to a matrix\n            int rd=0;\n            arma::uvec parent_node=arma::find(left_nodes == term_node);\n\n            if(parent_node.size()==0){\n              parent_node=arma::find(right_nodes == term_node);\n              rd=1;\n            }\n\n            //want to cout parent node and append to node_split_mat\n\n            node_split_mat.insert_rows(0,1);\n\n            //CHECK THAT COLUMNS OF TREETABLE ARE CORRECT\n            //node_split_mat(0,0)=treetable(parent_node[0],2);\n            //node_split_mat(0,1)=treetable(parent_node[0],3);\n\n            //node_split_mat(0,0)=arma_tree_table(parent_node[0],3);\n            //node_split_mat(0,1)=arma_tree_table(parent_node[0],4);\n\n            node_split_mat(0,0)=tree_table1(parent_node(0),2);\n            node_split_mat(0,1)=tree_table1(parent_node(0),3);\n\n            node_split_mat(0,2)=rd;\n            row_index=parent_node(0)+1;\n            term_node=parent_node(0)+1;\n          }\n\n          //once we have the split info, loop through rows and find the subset indexes for that terminal node!\n          //then fill in the predicted value for that tree\n          //double prediction = tree_data(term_node,5);\n          arma::uvec pred_indices;\n          arma::uvec pred_test_indices;\n          int split= node_split_mat(0,0)-1;\n\n          //Rcout << \"Line 224.\\n\";\n          //Rcout << \"split = \" << split << \".\\n\";\n          //arma::vec tempvec = testd.col(split);\n          arma::vec tempvec = x_control_a.col(split);\n          //Rcout << \"Line 227.\\n\";\n\n\n          double temp_split = node_split_mat(0,1);\n\n          if(node_split_mat(0,2)==0){\n            pred_indices = arma::find(tempvec <= temp_split);\n          }else{\n            pred_indices = arma::find(tempvec > temp_split);\n          }\n\n          if(is_test_data==1){\n            arma::vec temptest_vec = x_control_test_a.col(split);\n\n            if(node_split_mat(0,2)==0){\n              pred_test_indices = arma::find(temptest_vec <= temp_split);\n            }else{\n              pred_test_indices = arma::find(temptest_vec > temp_split);\n            }\n          }\n\n\n          //Rcout << \"Line 236.\\n\";\n\n          arma::uvec temp_pred_indices;\n          arma::uvec temp_test_pred_indices;\n\n          //arma::vec data_subset = testd.col(split);\n          arma::vec data_subset = x_control_a.col(split);\n          data_subset=data_subset.elem(pred_indices);\n\n          arma::vec data_test_subset;\n          if(is_test_data==1){\n            data_test_subset =x_control_test_a.col(split);\n            data_test_subset=data_test_subset.elem(pred_test_indices);\n          }\n\n          //now loop through each row of node_split_mat\n          int n=node_split_mat.n_rows;\n          //Rcout << \"Line 174. i = \" << i << \". n = \" << n << \".\\n\";\n          //Rcout << \"Line 248.\\n\";\n\n          for(int j=1;j<n;j++){\n            int curr_sv=node_split_mat(j,0);\n            double split_p = node_split_mat(j,1);\n\n            //data_subset = testd.col(curr_sv-1);\n            //Rcout << \"Line 255.\\n\";\n            //Rcout << \"curr_sv = \" << curr_sv << \".\\n\";\n            data_subset = x_control_a.col(curr_sv-1);\n            //Rcout << \"Line 258.\\n\";\n\n            data_subset=data_subset.elem(pred_indices);\n\n\n            if(node_split_mat(j,2)==0){\n              //split is to the left\n              temp_pred_indices=arma::find(data_subset <= split_p);\n            }else{\n              //split is to the right\n              temp_pred_indices=arma::find(data_subset > split_p);\n            }\n            pred_indices=pred_indices.elem(temp_pred_indices);\n\n\n            if(is_test_data==1){\n              data_test_subset = x_control_test_a.col(curr_sv-1);\n              data_test_subset=data_test_subset.elem(pred_test_indices);\n\n              if(node_split_mat(j,2)==0){\n                //split is to the left\n                temp_test_pred_indices=arma::find(data_test_subset <= split_p);\n              }else{\n                //split is to the right\n                temp_test_pred_indices=arma::find(data_test_subset > split_p);\n              }\n              pred_test_indices=pred_test_indices.elem(temp_test_pred_indices);\n\n            }\n\n\n            //if(pred_indices.size()==0){\n            //  continue;\n            //}\n\n          }\n          //Rcout << \"Line 199. i = \" << i <<  \".\\n\";\n\n          //There is probably a more efficient way of doing this\n          //e.g. initialize J matrix so that all elements are equal to zero\n          arma::vec tempcol_J=arma::zeros<arma::vec>(num_obs);\n          tempcol_J(pred_indices) = arma::ones<arma::vec>(pred_indices.size());\n          Jmat.col(i) = tempcol_J;\n\n          if(is_test_data==1){\n            arma::vec tempcol_Jtilde=arma::zeros<arma::vec>(num_test_obs);\n            tempcol_Jtilde(pred_test_indices) = arma::ones<arma::vec>(pred_test_indices.size());\n            Jtilde.col(i) = tempcol_Jtilde;\n          }\n\n          //double nodemean=tree_data(terminal_nodes[i]-1,5);\n          //IntegerVector predind=as<IntegerVector>(wrap(pred_indices));\n          //predictions[predind]= nodemean;\n          //term_obs[i]=predind;\n\n          //double denom_temp= pred_indices.n_elem+arma::sum(alpha_pars_arma);\n          //Rcout << \"Line 207. predind = \" << predind <<  \".\\n\";\n          //Rcout << \"Line 207. denom_temp = \" << denom_temp <<  \".\\n\";\n          // << \"Line 207. term_node = \" << term_node <<  \".\\n\";\n\n          //double num_prod=1;\n          //double num_sum=0;\n\n          // for(int k=0; k<num_cats; k++){\n          //   //assuming categories of y are from 1 to num_cats\n          //   arma::uvec cat_inds= arma::find(orig_y_arma(pred_indices)==k+1);\n          //   double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n          //\n          //   tree_table1(curr_term-1,5+k)= m_plus_alph/denom_temp ;\n          //\n          //   num_prod=num_prod*tgamma(m_plus_alph);\n          //   num_sum=num_sum +m_plus_alph ;\n          // }\n          //\n          //\n          // lik_prod= lik_prod*alph_term*num_prod/tgamma(num_sum);\n          //Rcout << \"Line 297.\\n\";\n\n\n        }//End of loop over terminal nodes.\n      }// end of else statement (for when more than one terminal node)\n      // Now have J matrix\n\n      Wmat_mu=join_rows(Wmat_mu,Jmat);\n      //or\n      //Wmat.insert_cols(Wmat.n_cols,Jmat);\n      //or\n      //int b_j=term_nodes.n_elem;\n      //Wmat.insert_cols(upsilon,Jmat);\n      //upsilon+=b_j;\n\n\n      //Obtain test W_tilde, i.e. W matrix for test data\n      if(is_test_data==1){\n        W_tilde_mu=join_rows(W_tilde_mu,Jtilde);\n      }\n\n      //or\n      //W_tilde.insert_cols(W_tilde.n_cols,Jtilde);\n      //or\n      //int b_jtest=term_nodes.n_elem;\n      //W_tilde.insert_cols(upsilon2,Jtilde);\n      //upsilon2+=b_jtest;\n      //Rcout << \"Line 5566.\\n\";\n\n\n      if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n        // //get impportance sampler probability and tree prior\n        // long double temp_samp_prob;\n        // long double temp_prior_prob;\n        // //get sampler tree probability\n        // if(imp_sampler==1){//If sample from BART prior\n        //\n        //\n        //\n        //   temp_samp_prob=1;\n        //\n        //   double depth1=0;\n        //   int prev_node=0; //1 if previous node splits, zero otherwise\n        //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n        //     if(treenodes_bin[i_2]==1){\n        //       temp_samp_prob=temp_samp_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n        //       depth1=depth1+1; //after a split, the depth will increase by 1\n        //       prev_node=1;\n        //     }else{\n        //       temp_samp_prob=temp_samp_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n        //       if(prev_node==1){//zero following a 1, therefore at same depth.\n        //         //Don't change depth. Do nothing\n        //       }else{ //zero following a zero, therefore the depth will decrease by 1\n        //         depth1=depth1-1;\n        //       }\n        //       prev_node=0;\n        //\n        //     }\n        //   }\n        //\n        //   //end of calculating BART tree probability\n        // }else{\n        //   if(imp_sampler==2){//If sample from spike and tree prior\n        //     throw std::range_error(\"code not yet written for spike and tree prior\");\n        //\n        //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n        //     double tempexp1=treenodes_bin.size()-arma::sum(treenodes_bin_arma);\n        //     double tempexp2=arma::sum(treenodes_bin_arma);\n        //     temp_samp_prob=pow(lambda,tempexp2)*\n        //       pow(1-lambda,tempexp1);\n        //       //(1/pow(double(num_split_vars),tempexp2));\n        //\n        //       temp_samp_prob=exp(log(lambda)*tempexp2+\n        //         log(1-lambda)*tempexp1);\n        //\n        //     //temp_samp_prob=pow(lambda,arma::sum(treenodes_bin_arma))*\n        //     //  pow(1-lambda,treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n        //     //  pow((1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n        //   }\n        // }\n        //\n        // sum_tree_samp_prob=sum_tree_samp_prob*temp_samp_prob;\n        // //end of getting importance sampler probability\n        //\n        // //get prior tree probability\n        // if(tree_prior==1){//If sample from BART prior\n        //\n        //\n        //\n        //   temp_prior_prob=1;\n        //\n        //   double depth1=0;\n        //   int prev_node=0; //1 if previous node splits, zero otherwise\n        //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n        //\n        //     if(treenodes_bin[i_2]==1){\n        //       temp_prior_prob=temp_prior_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n        //       depth1=depth1+1; //after a split, the depth will increase by 1\n        //       prev_node=1;\n        //     }else{\n        //       temp_prior_prob=temp_prior_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n        //       if(prev_node==1){//zero following a 1, therefore at same depth.\n        //         //Don't change depth. Do nothing\n        //       }else{ //zero following a zero, therefore the depth will decrease by 1\n        //         depth1=depth1-1;\n        //       }\n        //       prev_node=0;\n        //\n        //     }\n        //     //if(alpha_BART==0){\n        //     //  Rcout << \"alpha_BART equals zero!!!!.\\n\";\n        //     //}\n        //   }\n        //\n        //   //end of calculating BART tree probability\n        // }else{\n        //   if(tree_prior==2){//If sample from spike and tree prior\n        //     throw std::range_error(\"code not yet written for spike and tree prior\");\n        //\n        //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n        //     temp_prior_prob=pow((long double)(lambda),arma::sum(treenodes_bin_arma))*\n        //       pow((long double)(1-lambda),treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n        //       pow((long double)(1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n        //   }\n        // }\n        //\n        // sum_tree_prior_prob=sum_tree_prior_prob*temp_prior_prob;\n        // if(temp_prior_prob==0){\n        //   Rcout << \"Line 4097, j= \" << j << \". \\n\";\n        //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        // }\n        // if(temp_samp_prob==0){\n        //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n        //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        // }\n        //\n        // if(sum_tree_samp_prob==0){\n        //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n        //   Rcout << \"sum_tree_samp_prob= \" << sum_tree_samp_prob << \". \\n\";\n        //   //Rcout << \"treenodes_bin_arma= \" << treenodes_bin_arma << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        //\n        // }\n\n\n\n\n        //get tree prior over impportance sampler probability\n        double tree_prior_over_samp_prob=1;\n        if(imp_sampler==1){   //If sample from BART prior\n\n\n          if(tree_prior==1){  //If tree prior is BART prior\n            throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n\n          }else{\n            if(tree_prior==2){  //If tree prior is spike-and-tree prior\n              throw std::range_error(\"code not yet written for spike and tree prior\");\n\n            }else{//otherwise the tree prior is the Quadrianto and Ghahramani prior\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*(lambda_mu/(alpha_BCF_mu*pow(double(depth1+1),-beta_BCF_mu)));\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-lambda_mu)/(1-alpha_BCF_mu*pow(double(depth1+1),-beta_BCF_mu)));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }\n              }\n\n            }\n          }\n\n\n        }else{// if not sampling from BART prior\n          if(imp_sampler==2){//If sample from spike and tree prior\n            throw std::range_error(\"code not yet written for sampling from spike and tree prior\");\n\n          }else{//otherwise sampling from Quadrianto and Ghahramani prior\n            if(tree_prior==1){  //If tree prior is BART prior\n\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((alpha_BCF_mu*pow(double(depth1+1),-beta_BCF_mu))/lambda_mu);\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-alpha_BCF_mu*pow(double(depth1+1),-beta_BCF_mu))/(1-lambda_mu));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }//close (zero node) else stattement\n\n              }//end for loop over i_2\n\n            }else{\n              if(tree_prior==2){  //If tree prior is spike-and-tree prior\n                throw std::range_error(\"code not yet written for spike and tree prior\");\n\n              }else{\n                throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n\n              }//close (not BART nor spike and tree prior) else statement\n            }// close (not BART prior) else statememt\n\n\n\n\n          }//close (not sampling from BART or spike and tree)  else statement\n\n        }//close (not sampling from BART) else statement\n\n        sum_prior_over_samp_prob=sum_prior_over_samp_prob*tree_prior_over_samp_prob;\n        //end of getting tree prior over impportance sampler probability\n\n\n\n      }//end of tree prior and importance sampler calculations\n\n\n\n\n    } //end of loop over mu trees in sum\n\n\n    /////////////////////////////////////////////////////////////////////////////////////////\n    //Rcout << \"Line 5782. TAU TREES. \\n\";\n\n    /////////////////////////////////////////////////////////////////////////////////////////\n    // NOW LOOP OVER TAU TREES\n\n\n for(int q=0; q<num_trees_tau;q++){  //start of loop over trees in sum\n\n\n   //If parallelizing, define the distributinos before this loop\n   //and use lrng and the following two lines\n   //dqrng::xoshiro256plus lrng(rng);      // make thread local copy of rng\n   //lrng.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... nthreads jumps\n\n\n   //NumericVector treenodes_bin(0);\n   //arma::uvec treenodes_bin(0);\n\n   std::vector<int> treenodes_bin;\n\n\n   int count_terminals = 0;\n   int count_internals = 0;\n\n   //int count_treebuild = 0;\n\n\n   if(imp_sampler==1){ //If sampling from BART prior\n\n     double depth1=0;\n     int prev_node=0; //1 if previous node splits, zero otherwise\n\n     double samp_prob;\n\n     while(count_internals > (count_terminals -1)){\n       samp_prob=alpha_BCF_tau*pow(double(depth1+1),-beta_BCF_tau);\n       std::bernoulli_distribution coin_flip2(samp_prob);\n\n       int tempdraw = coin_flip2(lgen);\n       treenodes_bin.push_back(tempdraw);\n\n       if(tempdraw==1){\n\n         depth1=depth1+1; //after a split, the depth will increase by 1\n         prev_node=1;\n         count_internals=count_internals+1;\n\n       }else{\n\n         if(prev_node==1){//zero following a 1, therefore at same depth.\n           //Don't change depth. Do nothing\n         }else{ //zero following a zero, therefore the depth will decrease by 1\n           depth1=depth1-1;\n         }\n         prev_node=0;\n         count_terminals=count_terminals+1;\n\n       }\n\n     }\n\n   }else{  //If not sampling from BART prior\n     if(imp_sampler==2){//If sampling from spike and tree prior\n       throw std::range_error(\"code not yet written for spike and tree sampling\");\n\n     }else{//If sampling from default Q+G prior. i.e. not sampling from BART nor spike and tree prior\n\n       while(count_internals > (count_terminals -1)){\n\n         //Also consider standard library and random header\n         // std::random_device device;\n         // std::mt19937 gen(device());\n         // std::bernoulli_distribution coin_flip(lambda);\n         // bool outcome = coin_flip(gen);\n\n\n         int tempdraw = coin_flip_tau(lgen);\n\n         //int tempdraw = rbinom(n = 1, prob = lambda,size=1);\n\n\n         //int tempdraw = Rcpp::rbinom(1,lambda,1);\n         //int tempdraw = R::rbinom(1,lambda);\n\n         ////Rcout << \"tempdraw = \" << tempdraw << \".\\n\" ;\n\n         //int tempdraw = coin_flip2(lgen)-1;\n\n         //int tempdraw = dqrng::dqsample_int(2, 1, true,lambdavec )-1;\n\n\n         //need to update rng if use boost?\n         //int tempdraw = bernoulli(rng, binomial::param_type(1, lambda));\n\n         treenodes_bin.push_back(tempdraw);\n\n\n         if(tempdraw==1){\n           count_internals=count_internals+1;\n         }else{\n           count_terminals=count_terminals+1;\n         }\n\n       }//end of while loop creating parent vector treenodes_bin\n     }\n\n   }\n\n\n\n   //Consider making this an armadillo vector\n   //IntegerVector split_var_vec(treenodes_bin.size());\n   //arma::uvec split_var_vec(treenodes_bin.size());\n   std::vector<int> split_var_vec(treenodes_bin.size());\n\n   //loop drawing splitting variables\n   //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n   //if using armadillo, it might be faster to subset to split nodes\n   //then use a vector of draws\n   for(unsigned int i=0; i<treenodes_bin.size();i++){\n     if(treenodes_bin[i]==0){\n       split_var_vec[i] = -1;\n     }else{\n       // also consider the standard library function uniform_int_distribution\n       // might need random header\n       // This uses the Mersenne twister\n\n       //Three lines below should probably be outside all the loops\n       // std::random_device rd;\n       // std::mt19937 engine(rd());\n       // std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n       //\n       // split_var_vec[i] = distsampvar(engine);\n\n       split_var_vec[i] = distsampvar_tau(lgen);\n\n\n       //consider using boost\n       //might need to update rng\n       //split_var_vec[i] <- sample_splitvars(rng);\n\n       //or use dqrng\n       //not sure if have to update the random number\n       //check if the following line is written properly\n       //split_var_vec[i] = dqrng::dqsample_int(num_split_vars, 1, true);\n\n       //not sure if this returns an integer or a vector?\n       //split_var_vec[i] = RcppArmadillo::sample(num_split_vars, 1,true);\n       //could try\n       //split_var_vec[i] = as<int>(Rcpp::sample(num_split_vars, 1,true));\n       //could also try RcppArmadillo::rmultinom\n\n     }\n\n   }// end of for-loop drawing split variables\n\n\n   //Consider making this an armadillo vector\n   //NumericVector split_point_vec(treenodes_bin.size());\n   //arma::vec split_point_vec(treenodes_bin.size());\n   std::vector<double> split_point_vec(treenodes_bin.size());\n\n\n   //loop drawing splitting points\n   //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n   //if using armadillo, it might be faster to subset to split nodes\n   //then use a vector of draws\n   for(unsigned int i=0; i<treenodes_bin.size();i++){\n     if(treenodes_bin[i]==0){\n       split_point_vec[i] = -1;\n     }else{\n\n\n       //////////////////////////////////////////////////////////\n       //following function not reccommended\n       //split_point_vec[i] = std::rand();\n       //////////////////////////////////////////////////////////\n       ////Standard library:\n       ////This should probably be outside all the loops\n       ////std::random_device rd;  //Will be used to obtain a seed for the random number engine\n       ////std::mt19937 gen2(rd()); //Standard mersenne_twister_engine seeded with rd()\n       ////std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n       split_point_vec[i] = dis_cont_unif(lgen);\n\n       //////////////////////////////////////////////////////////\n       //from armadillo\n       //split_point_vec[i] = arma::randu();\n\n       //////////////////////////////////////////////////////////\n       //probably not adviseable for paralelization\n       //From Rcpp\n       //split_point_vec[i] = as<double>(Rcpp::runif(1,0,1));\n\n       //////////////////////////////////////////////////////////\n       //consider using boost\n       //might need to update rng\n       //split_point_vec[i] <- b_unif_point(rng);\n\n       //or use dqrng\n       //not sure if have to update the random number\n       //check if the following line is written properly\n       //split_point_vec[i] = dqrng::dqrunif(1, 0, 1);\n\n       //not sure if this returns an integer or a vector?\n\n\n\n\n\n     }\n\n   }// end of for-loop drawing split points\n\n\n\n   //Rcout << \"Line 6000.\\n\";\n\n\n   //CODE FOR ADJUSTING SPLITTING POINTS SO THAT THE TREES ARE VALID\n   if(valid_trees==1){\n     for(unsigned int i=0; i<treenodes_bin.size();i++){ //loop over all nodes\n       if(treenodes_bin[i]==1){ // if it is an internal node, then check for further splits on the same variable and update\n         double first_split_var=split_var_vec[i];      //splitting variable to check for\n         double first_split_point=split_point_vec[i];  //splitting point to use in updates\n\n         double sub_int_nodes=0;       //this internal node count will be used to determine if in subtree relevant to sub_int_nodes\n         double sub_term_nodes=0;      //this terminal node count will be used to determine if in subtree relevant to sub_int_nodes\n         double preventing_updates=0; //indicates if still within subtree that is not to be updated\n         double prevent_int_count=0;   //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n         double prevent_term_count=0;  //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n         for(unsigned int k=i+1; k<treenodes_bin.size();k++){\n           if(treenodes_bin[k]==1){\n             sub_int_nodes=sub_int_nodes+1;\n             if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n               prevent_int_count=prevent_int_count+1;\n             }\n           }else{\n             sub_term_nodes=sub_term_nodes+1;\n             if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n               prevent_term_count=prevent_term_count+1;\n             }\n           }\n           if(sub_int_nodes<=sub_term_nodes-2){\n             break;\n           }\n\n\n           if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n             if(prevent_int_count>prevent_term_count-1){ //if this rule is satisfied then in subtree that is not to be updated\n               continue; //still in subtree, therefore continue instead of checking for splits to be updates\n             }else{\n               preventing_updates=0; // no longer in subtree, therefore reset preventing_updates to zero\n             }\n           }\n\n\n           if(sub_int_nodes>sub_term_nodes-1){\n             if(treenodes_bin[k]==1){\n               if(split_var_vec[k]==first_split_var){\n                 split_point_vec[k]=split_point_vec[k]*first_split_point;\n                 //beginning count of subtree that should not have\n                 //further splits on first_split_var updated\n                 preventing_updates=1; //indicates if still within subtree that is not to be updated\n                 prevent_int_count=1;\n                 prevent_term_count=0;\n               }\n             }\n           }else{\n             if(treenodes_bin[k]==1){\n               if(split_var_vec[k]==first_split_var){\n                 split_point_vec[k]=split_point_vec[k]+first_split_point-first_split_point*split_point_vec[k];\n                 //beginning count of subtree that should not have\n                 //further splits on first_split_var updated\n                 preventing_updates=1; //indicates if still within subtree that is not to be updated\n                 prevent_int_count=1;\n                 prevent_term_count=0;\n               }\n             }\n           }\n\n\n\n         }//end of inner loop over k\n       }//end of if statement treenodes_bin[i]==1)\n     }//end of loop over i\n   }//end of if statement valid_trees==1\n\n\n\n\n\n\n\n   //Rcout << \"Line 6078.\\n\";\n\n\n\n   //Create tree table matrix\n\n   //NumericMatrix tree_table1(treenodes_bin.size(),5+num_cats);\n\n   //Rcout << \"Line 1037. \\n\";\n   //arma::mat tree_table1(treenodes_bin.size(),5+num_cats);\n\n   //initialize with zeros. Not sure if this is necessary\n   arma::mat tree_table1=arma::zeros<arma::mat>(treenodes_bin.size(),6);\n   //Rcout << \"Line 1040. \\n\";\n\n\n   //tree_table1(_,2) = wrap(split_var_vec);\n   //tree_table1(_,3) = wrap(split_point_vec);\n   //tree_table1(_,4) = wrap(treenodes_bin);\n\n   //It might be more efficient to make everything an armadillo object initially\n   // but then would need to replace push_back etc with a different approach (but this might be more efficient anyway)\n   arma::colvec split_var_vec_arma=arma::conv_to<arma::colvec>::from(split_var_vec);\n   arma::colvec split_point_vec_arma(split_point_vec);\n   arma::colvec treenodes_bin_arma=arma::conv_to<arma::colvec>::from(treenodes_bin);\n\n\n   //Rcout << \"Line 1054. \\n\";\n\n   //Fill in splitting variable column\n   tree_table1.col(2) = split_var_vec_arma;\n   //Fill in splitting point column\n   tree_table1.col(3) = split_point_vec_arma;\n   //Fill in split/parent column\n   tree_table1.col(4) = treenodes_bin_arma;\n\n\n   //Rcout << \"Line 1061. j = \" << j << \". \\n\";\n   //Rcout << \"Line 6117. j = \" << j << \". \\n\";\n   //Rcout << \"Line 6118. tree_table1 tau = \" << tree_table1 << \". \\n\";\n\n\n\n   // Now start filling in left daughter and right daughter columns\n   std::vector<int> rd_spaces;\n   int prev_node = -1;\n\n   for(unsigned int i=0; i<treenodes_bin.size();i++){\n     //Rcout << \"Line 1061. i = \" << i << \". \\n\";\n     if(prev_node==0){\n       //tree_table1(rd_spaces[rd_spaces.size()-1], 1)=i;\n       //Rcout << \"Line 1073. j = \" << j << \". \\n\";\n\n       tree_table1(rd_spaces.back(), 1)=i+1;\n       //Rcout << \"Line 1076. j = \" << j << \". \\n\";\n\n       rd_spaces.pop_back();\n     }\n     if(treenodes_bin[i]==1){\n       //Rcout << \"Line 1081. j = \" << j << \". \\n\";\n\n       tree_table1(i,0) = i+2;\n       rd_spaces.push_back(i);\n       prev_node = 1;\n       //Rcout << \"Line 185. j = \" << j << \". \\n\";\n\n     }else{                  // These 2 lines unnecessary if begin with matrix of zeros\n       //Rcout << \"Line 1089. j = \" << j << \". \\n\";\n       tree_table1(i,0)=0 ;\n       tree_table1(i,1) = 0 ;\n       prev_node = 0;\n       //Rcout << \"Line 1093. j = \" << j << \". \\n\";\n\n     }\n   }//\n   //Rcout << \"Line 1097. j = \" << j << \". \\n\";\n\n\n\n\n\n   //List treepred_output = get_treepreds(original_y, num_cats, alpha_pars,\n   //                                     originaldata,\n   //                                     treetable_list[i]  );\n\n\n   //use armadillo object tree_table1\n\n   ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n   ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n   //create variables for likelihood calcuations\n   // double lik_prod=1;\n   // double alph_prod=1;\n   // for(unsigned int i=0; i<alpha_pars_arma.n_elem;i++){\n   //   alph_prod=alph_prod*tgamma(alpha_pars_arma(i));\n   // }\n   // double gam_alph_sum= tgamma(arma::sum(alpha_pars_arma));\n   // double alph_term=gam_alph_sum/alph_prod;\n\n   //arma::mat arma_tree_table(treetable.begin(), treetable.nrow(), treetable.ncol(), false);\n   //arma::mat arma_orig_data(originaldata.begin(), originaldata.nrow(), originaldata.ncol(), false);\n\n\n   //arma::mat arma_tree(tree_data.begin(), tree_data.nrow(), tree_data.ncol(), false);\n   //arma::mat testd(test_data.begin(), test_data.nrow(), test_data.ncol(), false);\n\n   //NumericVector internal_nodes=find_internal_nodes_gs(tree_data);\n\n   //NumericVector terminal_nodes=find_term_nodes(treetable);\n\n   //arma::mat arma_tree(tree_table.begin(),tree_table.nrow(), tree_table.ncol(), false);\n\n   //arma::vec colmat=arma_tree.col(4);\n   //arma::uvec term_nodes=arma::find(colmat==-1);\n\n   //arma::vec colmat=arma_tree.col(2);\n   //arma::uvec term_nodes=arma::find(colmat==0);\n\n   //arma::vec colmat=tree_table1.col(4);\n   //arma::uvec term_nodes=arma::find(colmat==0);\n\n   //4th column is treenodes_bin_arma\n   arma::uvec term_nodes=arma::find(treenodes_bin_arma==0);\n\n   term_nodes=term_nodes+1;\n\n   //NumericVector terminal_nodes= wrap(term_nodes);\n\n   //Rcout << \"Line 6207.\\n\";\n\n\n   //GET J MATRIX\n\n   arma::mat Jmat(num_obs,term_nodes.n_elem);\n   arma::mat Jtilde(num_test_obs,term_nodes.n_elem);\n\n   //arma::vec arma_terminal_nodes=Rcpp::as<arma::vec>(terminal_nodes);\n   //NumericVector tree_predictions;\n\n   //now for each internal node find the observations that belong to the terminal nodes\n\n   //NumericVector predictions(test_data.nrow());\n   //List term_obs(term_nodes.n_elem);\n\n   //GET J MATRIX\n\n   if(term_nodes.n_elem==1){\n     //double nodemean=tree_data(terminal_nodes[0]-1,5);\t\t\t\t// let nodemean equal tree_data row terminal_nodes[i]^th row , 6th column. The minus 1 is because terminal nodes consists of indices starting at 1, but need indices to start at 0.\n     //predictions=rep(nodemean,test_data.nrow());\n     //Rcout << \"Line 67 .\\n\";\n\n     //IntegerVector temp_obsvec = seq_len(test_data.nrow())-1;\n     //term_obs[0]= temp_obsvec;\n     //double denom_temp= orig_y_arma.n_elem+arma::sum(alpha_pars_arma);\n\n     //double num_prod=1;\n     //double num_sum=0;\n     //Rcout << \"Line 129.\\n\";\n     Jmat.col(0) = arma::ones<arma::vec>(num_obs);\n\n     if(is_test_data==1){\n       Jtilde.col(0) = arma::ones<arma::vec>(num_test_obs);\n     }\n\n     //for(int k=0; k<num_cats; k++){\n     //assuming categories of y are from 1 to num_cats\n     //arma::uvec cat_inds= arma::find(orig_y_arma==k+1);\n     //double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n     //tree_table1(0,5+k)= m_plus_alph/denom_temp ;\n\n     //for likelihood calculation\n     //num_prod=num_prod*tgamma(m_plus_alph);\n     //num_sum=num_sum +m_plus_alph ;\n     //}\n\n     //lik_prod= alph_term*num_prod/tgamma(num_sum);\n\n   }\n   else{\n     for(unsigned int i=0;i<term_nodes.n_elem;i++){\n       //arma::mat subdata=testd;\n       //int curr_term=term_nodes(i);\n\n       int row_index;\n       int term_node=term_nodes(i);\n       //Rcout << \"Line 152.\\n\";\n\n\n       //WHAT IS THE PURPOSE OF THIS IF-STATEMENT?\n       //Why should the ro index be different for a right daughter?\n       //Why not just initialize row_index to any number not equal to 1 (e.g. 0)?\n       row_index=0;\n\n       // if(curr_term % 2==0){\n       //   //term node is left daughter\n       //   row_index=terminal_nodes[i];\n       // }else{\n       //   //term node is right daughter\n       //   row_index=terminal_nodes[i]-1;\n       // }\n\n\n\n\n       //save the left and right node data into arma uvec\n\n       //CHECK THAT THIS REFERS TO THE CORRECT COLUMNS\n       //arma::vec left_nodes=arma_tree.col(0);\n       //arma::vec right_nodes=arma_tree.col(1);\n\n       arma::vec left_nodes=tree_table1.col(0);\n       arma::vec right_nodes=tree_table1.col(1);\n\n\n\n       arma::mat node_split_mat;\n       node_split_mat.set_size(0,3);\n       //Rcout << \"Line 6296. i = \" << i << \" .\\n\";\n\n       while(row_index!=1){\n         //for each terminal node work backwards and see if the parent node was a left or right node\n         //append split info to a matrix\n         int rd=0;\n         arma::uvec parent_node=arma::find(left_nodes == term_node);\n\n         if(parent_node.size()==0){\n           parent_node=arma::find(right_nodes == term_node);\n           rd=1;\n         }\n\n         //want to cout parent node and append to node_split_mat\n\n         node_split_mat.insert_rows(0,1);\n\n         //CHECK THAT COLUMNS OF TREETABLE ARE CORRECT\n         //node_split_mat(0,0)=treetable(parent_node[0],2);\n         //node_split_mat(0,1)=treetable(parent_node[0],3);\n\n         //node_split_mat(0,0)=arma_tree_table(parent_node[0],3);\n         //node_split_mat(0,1)=arma_tree_table(parent_node[0],4);\n\n         node_split_mat(0,0)=tree_table1(parent_node(0),2);\n         node_split_mat(0,1)=tree_table1(parent_node(0),3);\n\n         node_split_mat(0,2)=rd;\n         row_index=parent_node(0)+1;\n         term_node=parent_node(0)+1;\n       }\n\n       //once we have the split info, loop through rows and find the subset indexes for that terminal node!\n       //then fill in the predicted value for that tree\n       //double prediction = tree_data(term_node,5);\n       arma::uvec pred_indices;\n       arma::uvec pred_test_indices;\n       int split= node_split_mat(0,0)-1;\n\n       //Rcout << \"Line 6335.\\n\";\n       //Rcout << \"split = \" << split << \".\\n\";\n       //Rcout << \"x_moderate_a.n_cols = \" << x_moderate_a.n_cols << \".\\n\";\n\n\n       //arma::vec tempvec = testd.col(split);\n       arma::vec tempvec = x_moderate_a.col(split);\n       ////Rcout << \"Line 227.\\n\";\n\n       //Rcout << \"Line 6341.\\n\";\n\n       double temp_split = node_split_mat(0,1);\n\n       if(node_split_mat(0,2)==0){\n         pred_indices = arma::find(tempvec <= temp_split);\n       }else{\n         pred_indices = arma::find(tempvec > temp_split);\n       }\n\n       //Rcout << \"Line 6351.\\n\";\n\n       if(is_test_data==1){\n         arma::vec temptest_vec = x_moderate_test_a.col(split);\n         //Rcout << \"Line 6355.\\n\";\n\n         if(node_split_mat(0,2)==0){\n           pred_test_indices = arma::find(temptest_vec <= temp_split);\n         }else{\n           pred_test_indices = arma::find(temptest_vec > temp_split);\n         }\n       }\n\n\n       //Rcout << \"Line 6361.\\n\";\n\n       arma::uvec temp_pred_indices;\n       arma::uvec temp_test_pred_indices;\n\n       //arma::vec data_subset = testd.col(split);\n       arma::vec data_subset = x_moderate_a.col(split);\n       data_subset=data_subset.elem(pred_indices);\n\n       arma::vec data_test_subset;\n       if(is_test_data==1){\n         data_test_subset =x_moderate_test_a.col(split);\n         data_test_subset=data_test_subset.elem(pred_test_indices);\n       }\n\n       //now loop through each row of node_split_mat\n       int n=node_split_mat.n_rows;\n\n       //Rcout << \"Line 6378. i = \" << i << \". n = \" << n << \".\\n\";\n\n       for(int j=1;j<n;j++){\n         int curr_sv=node_split_mat(j,0);\n         double split_p = node_split_mat(j,1);\n\n         //data_subset = testd.col(curr_sv-1);\n         //Rcout << \"Line 255.\\n\";\n         //Rcout << \"curr_sv = \" << curr_sv << \".\\n\";\n         data_subset = x_moderate_a.col(curr_sv-1);\n         //Rcout << \"Line 258.\\n\";\n\n         data_subset=data_subset.elem(pred_indices);\n\n\n         if(node_split_mat(j,2)==0){\n           //split is to the left\n           temp_pred_indices=arma::find(data_subset <= split_p);\n         }else{\n           //split is to the right\n           temp_pred_indices=arma::find(data_subset > split_p);\n         }\n         pred_indices=pred_indices.elem(temp_pred_indices);\n\n\n         if(is_test_data==1){\n           data_test_subset = x_moderate_test_a.col(curr_sv-1);\n           data_test_subset=data_test_subset.elem(pred_test_indices);\n\n           if(node_split_mat(j,2)==0){\n             //split is to the left\n             temp_test_pred_indices=arma::find(data_test_subset <= split_p);\n           }else{\n             //split is to the right\n             temp_test_pred_indices=arma::find(data_test_subset > split_p);\n           }\n           pred_test_indices=pred_test_indices.elem(temp_test_pred_indices);\n\n         }\n\n\n         //if(pred_indices.size()==0){\n         //  continue;\n         //}\n\n       }\n       //Rcout << \"Line 6425. i = \" << i <<  \".\\n\";\n\n       //There is probably a more efficient way of doing this\n       //e.g. initialize J matrix so that all elements are equal to zero\n       arma::vec tempcol_J=arma::zeros<arma::vec>(num_obs);\n       tempcol_J(pred_indices) = arma::ones<arma::vec>(pred_indices.size());\n       Jmat.col(i) = tempcol_J;\n\n       if(is_test_data==1){\n         arma::vec tempcol_Jtilde=arma::zeros<arma::vec>(num_test_obs);\n         tempcol_Jtilde(pred_test_indices) = arma::ones<arma::vec>(pred_test_indices.size());\n         Jtilde.col(i) = tempcol_Jtilde;\n       }\n\n       //double nodemean=tree_data(terminal_nodes[i]-1,5);\n       //IntegerVector predind=as<IntegerVector>(wrap(pred_indices));\n       //predictions[predind]= nodemean;\n       //term_obs[i]=predind;\n\n       //double denom_temp= pred_indices.n_elem+arma::sum(alpha_pars_arma);\n       //Rcout << \"Line 207. predind = \" << predind <<  \".\\n\";\n       //Rcout << \"Line 207. denom_temp = \" << denom_temp <<  \".\\n\";\n       // << \"Line 207. term_node = \" << term_node <<  \".\\n\";\n\n       //double num_prod=1;\n       //double num_sum=0;\n\n       // for(int k=0; k<num_cats; k++){\n       //   //assuming categories of y are from 1 to num_cats\n       //   arma::uvec cat_inds= arma::find(orig_y_arma(pred_indices)==k+1);\n       //   double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n       //\n       //   tree_table1(curr_term-1,5+k)= m_plus_alph/denom_temp ;\n       //\n       //   num_prod=num_prod*tgamma(m_plus_alph);\n       //   num_sum=num_sum +m_plus_alph ;\n       // }\n       //\n       //\n       // lik_prod= lik_prod*alph_term*num_prod/tgamma(num_sum);\n\n       //Rcout << \"Line 6466.\\n\";\n\n\n     }//End of loop over terminal nodes.\n   }// end of else statement (for when more than one terminal node)\n   // Now have J matrix\n\n   //Rcout << \"Line 6472.\\n\";\n\n   Wmat_tau=join_rows(Wmat_tau,Jmat);\n\n\n\n   //or\n   //Wmat.insert_cols(Wmat.n_cols,Jmat);\n   //or\n   //int b_j=term_nodes.n_elem;\n   //Wmat.insert_cols(upsilon,Jmat);\n   //upsilon+=b_j;\n\n\n   //Obtain test W_tilde, i.e. W matrix for test data\n   if(is_test_data==1){\n     W_tilde_tau=join_rows(W_tilde_tau,Jtilde);\n   }\n\n   //or\n   //W_tilde.insert_cols(W_tilde.n_cols,Jtilde);\n   //or\n   //int b_jtest=term_nodes.n_elem;\n   //W_tilde.insert_cols(upsilon2,Jtilde);\n   //upsilon2+=b_jtest;\n\n\n   if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n     // //get impportance sampler probability and tree prior\n     // long double temp_samp_prob;\n     // long double temp_prior_prob;\n     // //get sampler tree probability\n     // if(imp_sampler==1){//If sample from BART prior\n     //\n     //\n     //\n     //   temp_samp_prob=1;\n     //\n     //   double depth1=0;\n     //   int prev_node=0; //1 if previous node splits, zero otherwise\n     //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n     //     if(treenodes_bin[i_2]==1){\n     //       temp_samp_prob=temp_samp_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n     //       depth1=depth1+1; //after a split, the depth will increase by 1\n     //       prev_node=1;\n     //     }else{\n     //       temp_samp_prob=temp_samp_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n     //       if(prev_node==1){//zero following a 1, therefore at same depth.\n     //         //Don't change depth. Do nothing\n     //       }else{ //zero following a zero, therefore the depth will decrease by 1\n     //         depth1=depth1-1;\n     //       }\n     //       prev_node=0;\n     //\n     //     }\n     //   }\n     //\n     //   //end of calculating BART tree probability\n     // }else{\n     //   if(imp_sampler==2){//If sample from spike and tree prior\n     //     throw std::range_error(\"code not yet written for spike and tree prior\");\n     //\n     //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n     //     double tempexp1=treenodes_bin.size()-arma::sum(treenodes_bin_arma);\n     //     double tempexp2=arma::sum(treenodes_bin_arma);\n     //     temp_samp_prob=pow(lambda,tempexp2)*\n     //       pow(1-lambda,tempexp1);\n     //       //(1/pow(double(num_split_vars),tempexp2));\n     //\n     //       temp_samp_prob=exp(log(lambda)*tempexp2+\n     //         log(1-lambda)*tempexp1);\n     //\n     //     //temp_samp_prob=pow(lambda,arma::sum(treenodes_bin_arma))*\n     //     //  pow(1-lambda,treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n     //     //  pow((1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n     //   }\n     // }\n     //\n     // sum_tree_samp_prob=sum_tree_samp_prob*temp_samp_prob;\n     // //end of getting importance sampler probability\n     //\n     // //get prior tree probability\n     // if(tree_prior==1){//If sample from BART prior\n     //\n     //\n     //\n     //   temp_prior_prob=1;\n     //\n     //   double depth1=0;\n     //   int prev_node=0; //1 if previous node splits, zero otherwise\n     //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n     //\n     //     if(treenodes_bin[i_2]==1){\n     //       temp_prior_prob=temp_prior_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n     //       depth1=depth1+1; //after a split, the depth will increase by 1\n     //       prev_node=1;\n     //     }else{\n     //       temp_prior_prob=temp_prior_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n     //       if(prev_node==1){//zero following a 1, therefore at same depth.\n     //         //Don't change depth. Do nothing\n     //       }else{ //zero following a zero, therefore the depth will decrease by 1\n     //         depth1=depth1-1;\n     //       }\n     //       prev_node=0;\n     //\n     //     }\n     //     //if(alpha_BART==0){\n     //     //  Rcout << \"alpha_BART equals zero!!!!.\\n\";\n     //     //}\n     //   }\n     //\n     //   //end of calculating BART tree probability\n     // }else{\n     //   if(tree_prior==2){//If sample from spike and tree prior\n     //     throw std::range_error(\"code not yet written for spike and tree prior\");\n     //\n     //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n     //     temp_prior_prob=pow((long double)(lambda),arma::sum(treenodes_bin_arma))*\n     //       pow((long double)(1-lambda),treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n     //       pow((long double)(1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n     //   }\n     // }\n     //\n     // sum_tree_prior_prob=sum_tree_prior_prob*temp_prior_prob;\n     // if(temp_prior_prob==0){\n     //   Rcout << \"Line 4097, j= \" << j << \". \\n\";\n     //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n     //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n     // }\n     // if(temp_samp_prob==0){\n     //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n     //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n     //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n     // }\n     //\n     // if(sum_tree_samp_prob==0){\n     //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n     //   Rcout << \"sum_tree_samp_prob= \" << sum_tree_samp_prob << \". \\n\";\n     //   //Rcout << \"treenodes_bin_arma= \" << treenodes_bin_arma << \". \\n\";\n     //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n     //\n     // }\n\n\n\n\n     //get tree prior over impportance sampler probability\n     double tree_prior_over_samp_prob=1;\n     if(imp_sampler==1){   //If sample from BART prior\n\n\n       if(tree_prior==1){  //If tree prior is BART prior\n         throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n\n       }else{\n         if(tree_prior==2){  //If tree prior is spike-and-tree prior\n           throw std::range_error(\"code not yet written for spike and tree prior\");\n\n         }else{//otherwise the tree prior is the Quadrianto and Ghahramani prior\n           double depth1=0;\n           int prev_node=0; //1 if previous node splits, zero otherwise\n           for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n             if(treenodes_bin[i_2]==1){\n               tree_prior_over_samp_prob=tree_prior_over_samp_prob*(lambda_tau/(alpha_BCF_tau*pow(double(depth1+1),-beta_BCF_tau)));\n               depth1=depth1+1; //after a split, the depth will increase by 1\n               prev_node=1;\n             }else{\n               tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-lambda_tau)/(1-alpha_BCF_tau*pow(double(depth1+1),-beta_BCF_tau)));\n               if(prev_node==1){//zero following a 1, therefore at same depth.\n                 //Don't change depth. Do nothing\n               }else{ //zero following a zero, therefore the depth will decrease by 1\n                 depth1=depth1-1;\n               }\n               prev_node=0;\n\n             }\n           }\n\n         }\n       }\n\n\n     }else{// if not sampling from BART prior\n       if(imp_sampler==2){//If sample from spike and tree prior\n         throw std::range_error(\"code not yet written for sampling from spike and tree prior\");\n\n       }else{//otherwise sampling from Quadrianto and Ghahramani prior\n         if(tree_prior==1){  //If tree prior is BART prior\n\n           double depth1=0;\n           int prev_node=0; //1 if previous node splits, zero otherwise\n           for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n             if(treenodes_bin[i_2]==1){\n               tree_prior_over_samp_prob=tree_prior_over_samp_prob*((alpha_BCF_tau*pow(double(depth1+1),-beta_BCF_tau))/lambda_tau);\n               depth1=depth1+1; //after a split, the depth will increase by 1\n               prev_node=1;\n             }else{\n               tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-alpha_BCF_tau*pow(double(depth1+1),-beta_BCF_tau))/(1-lambda_tau));\n               if(prev_node==1){//zero following a 1, therefore at same depth.\n                 //Don't change depth. Do nothing\n               }else{ //zero following a zero, therefore the depth will decrease by 1\n                 depth1=depth1-1;\n               }\n               prev_node=0;\n\n             }//close (zero node) else stattement\n\n           }//end for loop over i_2\n\n         }else{\n           if(tree_prior==2){  //If tree prior is spike-and-tree prior\n             throw std::range_error(\"code not yet written for spike and tree prior\");\n\n           }else{\n             throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n\n           }//close (not BART nor spike and tree prior) else statement\n         }// close (not BART prior) else statememt\n\n\n\n\n       }//close (not sampling from BART or spike and tree)  else statement\n\n     }//close (not sampling from BART) else statement\n\n     sum_prior_over_samp_prob=sum_prior_over_samp_prob*tree_prior_over_samp_prob;\n     //end of getting tree prior over impportance sampler probability\n\n\n\n   }//end of tree prior and importance sampler calculations\n\n\n\n } //end of loop over trees in sum\n\n\n\n //Rcout << \"6708 4528.\\n\";\n\n\n      double b_mu=Wmat_mu.n_cols;\n      double b_tau=Wmat_tau.n_cols;\n      //Wmat_tau.each_col()%=z_ar;\n\n\n      //Rcout << \"Line 14688.\\n\";\n      //Rcout << \"b_tau = \" << b_tau << \".\\n\";\n      //Rcout << \"Wmat_tau.n_rows = \" << Wmat_tau.n_rows << \".\\n\";\n\n      //Rcout << \"z_ar.n_elem = \" << z_ar.n_elem << \".\\n\";\n\n\n      //Rcout <<\"Wmat_tau BEFORE diag? = \" << Wmat_tau <<\".\\n\";\n\n      arma::mat DiagZ_Wmat_tau= Wmat_tau.each_col()%z_ar;\n      //Rcout << \"Line 14693.\\n\";\n\n\n      arma::mat Wmat = join_rows(Wmat_mu,DiagZ_Wmat_tau);\n\n\n      //Rcout <<\"Wmat_mu = \" << Wmat_mu <<\".\\n\";\n      //Rcout <<\"Wmat_tau AFTER diag? = \" << Wmat_tau <<\".\\n\";\n      //Rcout <<\"DiagZ_Wmat_tau = \" << DiagZ_Wmat_tau <<\".\\n\";\n      //Rcout <<\"Wmat = \" << Wmat <<\".\\n\";\n\n\n      double b=Wmat.n_cols;\t\t\t\t\t\t\t\t\t// b is number of columns of W_bcf matrix (omega in the paper)\n\n\n      if(fast_approx==1){\n        arma::mat p = Wmat.t();\n        arma::rowvec r = orig_y_arma.t();\n\n        //create diagonal mat of penalty terms\n        arma::mat aI(b,b);\t\t\t\t\t\t\t\t\t// create b by b matrix called aI. NOT INIIALIZED.\n        aI=aI.eye();\t\t\t\t\t\t\t\t\t\t// a times b by b identity matrix. The .eye() turns aI into an identity matrix.\n        arma::vec a_vec_mu = a_mu*arma::ones<arma::vec>(b_mu);\n        arma::vec a_vec_tau = a_tau*arma::ones<arma::vec>(b_tau);\n        arma::vec a_vec(b);\n        a_vec.head(b_mu) = a_vec_mu;\n        a_vec.tail(b_tau) = a_vec_tau;\n        aI.diag() = a_vec;\n        //finish creating diagonal mat\n\n        arma::mat cov = p * p.t() + aI;\n\n        arma::mat parameters = arma::solve(cov, p * r.t(), arma::solve_opts::fast);\n\n        arma::rowvec preds_insamp_arma=arma::trans(parameters) * p;\n\n\n\n\n\n        arma::vec tempresids=y-preds_insamp_arma.t();\n        double temp_sse= arma::dot(tempresids, tempresids);\n\n        //double templik0=exp(-b*0.5*log(num_obs)+log(temp_sse)*(-num_obs)*0.5);\n\n\n        //double templik0=exp(-b*0.5*log(num_obs)+log(temp_sse)*(-num_obs)*0.5);\n\n\n        //double templik0=exp(-0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs)))  ;\n\n        double templik0=(num_obs*log(temp_sse/num_obs)+b*log(num_obs))  ;\n\n        // Rcout << \"num_obs= \" << num_obs << \". \\n\";\n        // Rcout << \"b= \" << b << \". \\n\";\n        // Rcout << \"log(num_obs)= \" << log(num_obs) << \". \\n\";\n        // Rcout << \"log(temp_sse/num_obs)= \" << log(temp_sse/num_obs) << \". \\n\";\n        //Rcout << \"templik0= \" << templik0 << \". \\n\";\n        // Rcout << \"-0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs))= \" << -0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs)) << \". \\n\";\n\n\n        //double templik = pow(templik0,beta_par);\n        double templik = beta_par*templik0;\n\n\n        if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n          //templik=templik*(sum_tree_prior_prob/sum_tree_samp_prob);\n          templik=templik*sum_prior_over_samp_prob;\n\n        }\n        overall_liks(j)= templik;\n\n\n        //Now get and save predictions\n        if(is_test_data==1){ //save out of sample predictions if is_test_data==1\n          //arma::mat zeromat(arma::size(Wmat_mu),arma::fill::zeros);\n          //arma::mat zeromat(num_obs ,b_mu ,arma::fill::zeros);\n          arma::mat zeromat=arma::zeros<arma::mat>(num_test_obs,b_mu);\n          arma::mat Vmat = join_rows(zeromat,W_tilde_tau);\n\n          //arma::vec preds_temp_arma= Vmat*sec_term_inv*third_term;\n\n          arma::rowvec preds_temp_arma_t=arma::trans(parameters) * Vmat.t();\n          arma::vec preds_temp_arma= preds_temp_arma_t.t();\n\n          // overall_preds(j)=preds_temp_arma*templik;\n          overall_preds(j)=preds_temp_arma;\n          //overall_preds.col(j)=preds_temp_arma;\n\n\n          //arma::mat covar_t=as_scalar((1/double(nu+num_obs))*(nu*lambda+yty-mvm))*(Vmat*sec_term_inv*(Vmat.t()));\n\n          //arma::mat catevartemp=averagingvec.t()*covar_t*averagingvec;\n          //arma::mat cattvartemp=catt_averagingvec.t()*covar_t*catt_averagingvec;\n          //arma::mat catntvartemp=catnt_averagingvec.t()*covar_t*catnt_averagingvec;\n\n          // preds_all_models_arma.col(i)=preds_temp_arma;\n          // t_vars_arma.col(i)=covar_t.diag();\n          // cate_means_arma(i)=as_scalar(averagingvec.t()*preds_temp_arma);\n          // cate_means_weighted_arma(i)=cate_means_arma(i)*post_weights_arma(i);\n          // cate_vars_arma(i)=as_scalar(catevartemp);\n          // catt_means_arma(i)=as_scalar(catt_averagingvec.t()*preds_temp_arma);\n          // catt_means_weighted_arma(i)=catt_means_arma(i)*post_weights_arma(i);\n          // catt_vars_arma(i)=as_scalar(cattvartemp);\n          // catnt_means_arma(i)=as_scalar(catnt_averagingvec.t()*preds_temp_arma);\n          // catnt_means_weighted_arma(i)=catnt_means_arma(i)*post_weights_arma(i);\n          // catnt_vars_arma(i)=as_scalar(catntvartemp);\n          //\n\n        }else{\n\n          //arma::mat zeromat(arma::size(Wmat_mu),arma::fill::zeros);\n          //arma::mat zeromat(num_obs ,b_mu ,arma::fill::zeros);\n          arma::mat zeromat=arma::zeros<arma::mat>(num_obs ,b_mu);\n          arma::mat Vmat = join_rows(zeromat,Wmat_tau);\n\n          //Rcout <<\"Vmat = \" << Vmat <<\".\\n\";\n\n          //arma::vec preds_temp_arma= Vmat*sec_term_inv*third_term;\n\n          arma::rowvec preds_temp_arma_t=arma::trans(parameters) * Vmat.t();\n          arma::vec preds_temp_arma= preds_temp_arma_t.t();\n          overall_preds(j)=preds_temp_arma;\n\n          //overall_preds(j)=preds_temp_arma*templik;\n\n\n          //arma::mat covar_t=as_scalar((1/double(nu+num_obs))*(nu*lambda+yty-mvm))*(Vmat*sec_term_inv*(Vmat.t()));\n\n          //arma::mat catevartemp=averagingvec.t()*covar_t*averagingvec;\n          //arma::mat cattvartemp=catt_averagingvec.t()*covar_t*catt_averagingvec;\n          //arma::mat catntvartemp=catnt_averagingvec.t()*covar_t*catnt_averagingvec;\n\n          // preds_all_models_arma.col(i)=preds_temp_arma;\n          // t_vars_arma.col(i)=covar_t.diag();\n          // cate_means_arma(i)=as_scalar(averagingvec.t()*preds_temp_arma);\n          // cate_means_weighted_arma(i)=cate_means_arma(i)*post_weights_arma(i);\n          // cate_vars_arma(i)=as_scalar(catevartemp);\n          // catt_means_arma(i)=as_scalar(catt_averagingvec.t()*preds_temp_arma);\n          // catt_means_weighted_arma(i)=catt_means_arma(i)*post_weights_arma(i);\n          // catt_vars_arma(i)=as_scalar(cattvartemp);\n          // catnt_means_arma(i)=as_scalar(catnt_averagingvec.t()*preds_temp_arma);\n          // catnt_means_weighted_arma(i)=catnt_means_arma(i)*post_weights_arma(i);\n          // catnt_vars_arma(i)=as_scalar(catntvartemp);\n          //\n\n        }//end of else statement (not test data)\n\n\n      }else{ // if fast_approx ==0\n\n\n\n\n\n        //get t(orig_y_arma)inv(psi)J_bcf\n        arma::mat ytW=orig_y_arma.t()*Wmat;\t\t\t\t\t\t\t\t// orig_y_arma transpose W_bcf\n        //get t(J_bcf)inv(psi)J_bcf\n        arma::mat WtW=Wmat.t()*Wmat;\t\t\t\t\t\t\t// W_bcf transpose W_bcf\n        //get jpsij +aI\n        arma::mat aI(b,b);\t\t\t\t\t\t\t\t\t// create b by b matrix called aI. NOT INIIALIZED.\n        aI=aI.eye();\t\t\t\t\t\t\t\t\t\t// a times b by b identity matrix. The .eye() turns aI into an identity matrix.\n        arma::vec a_vec_mu = a_mu*arma::ones<arma::vec>(b_mu);\n        arma::vec a_vec_tau = a_tau*arma::ones<arma::vec>(b_tau);\n        arma::vec a_vec(b);\n        a_vec.head(b_mu) = a_vec_mu;\n        a_vec.tail(b_tau) = a_vec_tau;\n        aI.diag() = a_vec;\n\n        arma::mat sec_term=WtW+aI;\t\t\t\t\t\t\t//\n        //arma::mat sec_term_inv=sec_term.i();\t\t\t\t\t// matrix inverse expression in middle of eq 5 in the paper. The .i() obtains the matrix inverse.\n        arma::mat sec_term_inv=inv_sympd(sec_term);\t\t\t\t\t// matrix inverse expression in middle of eq 5 in the paper. The .i() obtains the matrix inverse.\n\n        //get t(J_bcf)inv(psi)orig_y_arma\n        arma::mat third_term=Wmat.t()*orig_y_arma;\t\t\t\t\t\t// W_bcf transpose orig_y_arma\n        //get m^TV^{-1}m\n        arma::mat mvm= ytW*sec_term_inv*third_term;\t\t// matrix expression in middle of equation 5\n        //arma::mat rel=(b_mu*0.5)*log(a_mu)+(b_tau*0.5)*log(a_tau)-(1*0.5)*log(det(sec_term))-expon*log(nu*lambda - mvm +yty);\t\t// log of all of equation 5 (i.e. the log of the marginal likelihood of the sum of tree model)\n\n        //Rcout << \"Line 14724.\\n\";\n\n\n\n        //arma::vec preds_temp_arma= Vmat*sec_term_inv*Wmat.t()*orig_y_arma;\n        //arma::vec preds_temp_arma= Vmat*inv_sympd(sec_term)*Wmat.t()*orig_y_arma;\n        //arma::vec preds_temp_arma= Vmat*inv_sympd(sec_term)*third_term;\n\n\n        //double templik0=exp(arma::as_scalar((b_mu*0.5)*log(a_mu)+(b_tau*0.5)*log(a_tau)-(0.5)*log(det(sec_term))-expon*log(nu*lambdaBCF - mvm +yty)) );\n\n        //double templik0=exp(arma::as_scalar((b_mu*0.5)*log(a_mu)+(b_tau*0.5)*log(a_tau)-(0.5)*real(arma::log_det(sec_term))-expon*log(nu*lambdaBCF - mvm +yty)) );\n\n        double templik0=arma::as_scalar((b_mu*0.5)*log(a_mu)+(b_tau*0.5)*log(a_tau)-(0.5)*real(arma::log_det(sec_term))-expon*log(nu*lambdaBCF - mvm +yty)) ;\n\n\n        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n        //double templik = pow(templik0,beta_par);\n        double templik = beta_par*templik0;\n\n        if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n          //templik=templik*(sum_tree_prior_prob/sum_tree_samp_prob);\n          //templik=templik*sum_prior_over_samp_prob;\n          templik=templik+log(sum_prior_over_samp_prob);\n\n        }\n        overall_liks(j)= templik;\n\n\n        //now get and save predictions\n      if(is_test_data==1){\n        //arma::mat zeromat(arma::size(Wmat_mu),arma::fill::zeros);\n        //arma::mat zeromat(num_obs ,b_mu ,arma::fill::zeros);\n        arma::mat zeromat=arma::zeros<arma::mat>(num_test_obs,b_mu);\n        arma::mat Vmat = join_rows(zeromat,W_tilde_tau);\n\n\n        //arma::rowvec preds_temp_arma_t=arma::trans(parameters) * Vmat.t();\n        //arma::vec preds_temp_arma= preds_temp_arma_t.t();\n        //overall_preds(j)=preds_temp_arma;\n\n\n        arma::vec preds_temp_arma= Vmat*sec_term_inv*third_term;\n        overall_preds(j)=preds_temp_arma;\n\n        //overall_preds(j)=preds_temp_arma*templik;\n\n\n        //arma::mat covar_t=as_scalar((1/double(nu+num_obs))*(nu*lambda+yty-mvm))*(Vmat*sec_term_inv*(Vmat.t()));\n\n        //arma::mat catevartemp=averagingvec.t()*covar_t*averagingvec;\n        //arma::mat cattvartemp=catt_averagingvec.t()*covar_t*catt_averagingvec;\n        //arma::mat catntvartemp=catnt_averagingvec.t()*covar_t*catnt_averagingvec;\n\n        // preds_all_models_arma.col(i)=preds_temp_arma;\n        // t_vars_arma.col(i)=covar_t.diag();\n        // cate_means_arma(i)=as_scalar(averagingvec.t()*preds_temp_arma);\n        // cate_means_weighted_arma(i)=cate_means_arma(i)*post_weights_arma(i);\n        // cate_vars_arma(i)=as_scalar(catevartemp);\n        // catt_means_arma(i)=as_scalar(catt_averagingvec.t()*preds_temp_arma);\n        // catt_means_weighted_arma(i)=catt_means_arma(i)*post_weights_arma(i);\n        // catt_vars_arma(i)=as_scalar(cattvartemp);\n        // catnt_means_arma(i)=as_scalar(catnt_averagingvec.t()*preds_temp_arma);\n        // catnt_means_weighted_arma(i)=catnt_means_arma(i)*post_weights_arma(i);\n        // catnt_vars_arma(i)=as_scalar(catntvartemp);\n        //\n\n      }else{\n\n        //arma::mat zeromat(arma::size(Wmat_mu),arma::fill::zeros);\n        //arma::mat zeromat(num_obs ,b_mu ,arma::fill::zeros);\n        arma::mat zeromat=arma::zeros<arma::mat>(num_obs ,b_mu);\n        arma::mat Vmat = join_rows(zeromat,Wmat_tau);\n\n        //Rcout <<\"Vmat = \" << Vmat <<\".\\n\";\n\n        //arma::rowvec preds_temp_arma_t=arma::trans(parameters) * Vmat.t();\n        //arma::vec preds_temp_arma= preds_temp_arma_t.t();\n        //overall_preds(j)=preds_temp_arma;\n\n        //Rcout <<\"coeffs = \" << sec_term_inv*third_term << \".\\n\";\n        //Rcout <<\"Vmat = \" << Vmat << \".\\n\";\n        //Rcout <<\"Wmat_tau = \" << Wmat_tau << \".\\n\";\n\n\n\n        //arma::mat Vmattemp = join_rows(zeromat,DiagZ_Wmat_tau);\n\n        //Rcout <<\"Vmattemp*coeffs = \" <<  Vmattemp*sec_term_inv*third_term << \".\\n\";\n        //Rcout <<\"Vmat*coeffs = \" <<  Vmat*sec_term_inv*third_term << \".\\n\";\n\n\n        //Rcout <<\"z%Vmat*coeffs = Vmattemp*coeffs?\" <<  z_ar%Vmat*sec_term_inv*third_term ==Vmattemp*sec_term_inv*third_term << \".\\n\";\n\n        //coeffs(j)= sec_term_inv*third_term;\n\n\n        arma::vec preds_temp_arma= Vmat*sec_term_inv*third_term;\n        overall_preds(j)=preds_temp_arma;\n\n\n        // arma::mat zeromat_mu=arma::zeros<arma::mat>(num_obs ,b_tau);\n        // arma::mat Vmat_mu = join_rows(Wmat_mu,zeromat_mu);\n        // arma::vec preds_temp_arma_mu= Vmat_mu*sec_term_inv*third_term;\n        //\n        // //arma::vec temppredstest=preds_temp_arma%z_ar;\n        // //Rcout <<\"temppredstest = \" << temppredstest << \".\\n\";\n        //\n        // overall_preds_mu(j)=preds_temp_arma_mu;\n        //\n        // arma::vec preds_temp_arma_y= Wmat*sec_term_inv*third_term;\n        // overall_preds_y(j)=preds_temp_arma_y;\n\n\n        //overall_preds(j)=preds_temp_arma*templik;\n\n\n        //arma::mat covar_t=as_scalar((1/double(nu+num_obs))*(nu*lambda+yty-mvm))*(Vmat*sec_term_inv*(Vmat.t()));\n\n        //arma::mat catevartemp=averagingvec.t()*covar_t*averagingvec;\n        //arma::mat cattvartemp=catt_averagingvec.t()*covar_t*catt_averagingvec;\n        //arma::mat catntvartemp=catnt_averagingvec.t()*covar_t*catnt_averagingvec;\n\n\n        // preds_all_models_arma.col(i)=preds_temp_arma;\n        // t_vars_arma.col(i)=covar_t.diag();\n        // cate_means_arma(i)=as_scalar(averagingvec.t()*preds_temp_arma);\n        // cate_means_weighted_arma(i)=cate_means_arma(i)*post_weights_arma(i);\n        // cate_vars_arma(i)=as_scalar(catevartemp);\n        // catt_means_arma(i)=as_scalar(catt_averagingvec.t()*preds_temp_arma);\n        // catt_means_weighted_arma(i)=catt_means_arma(i)*post_weights_arma(i);\n        // catt_vars_arma(i)=as_scalar(cattvartemp);\n        // catnt_means_arma(i)=as_scalar(catnt_averagingvec.t()*preds_temp_arma);\n        // catnt_means_weighted_arma(i)=catnt_means_arma(i)*post_weights_arma(i);\n        // catnt_vars_arma(i)=as_scalar(catntvartemp);\n        //\n\n      }//end of else statement (not test data)\n\n\n\n      }// end if statement fast_approx==1\n  }//end of loop over all trees\n\n}//end of pragma omp code\n\n\n///////////////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////////////////////////////////////////////////////////////\n//Rcout << \"Line 6852.\\n\";\n\n\n//for(unsigned int i=0; i<overall_treetables.n_elem;i++){\n//  pred_mat_overall = pred_mat_overall + overall_liks(i)*overall_treetables(i);\n//}\n\n// if(is_test_data==1){\n//   #pragma omp parallel\n//   {\n//     arma::vec result_private=arma::zeros<arma::vec>(x_control_test_a.n_rows);\n//   #pragma omp for nowait //fill result_private in parallel\n//     for(unsigned int i=0; i<overall_preds.size(); i++) result_private += overall_preds(i);\n//   #pragma omp critical\n//     pred_vec_overall += result_private;\n//   }\n// }else{\n//   #pragma omp parallel\n//   {\n//     arma::vec result_private=arma::zeros<arma::vec>(x_control_a.n_rows);\n//   #pragma omp for nowait //fill result_private in parallel\n//     for(unsigned int i=0; i<overall_preds.size(); i++) result_private += overall_preds(i);\n//   #pragma omp critical\n//     pred_vec_overall += result_private;\n//   }\n// }\n//\n//\n// //Rcout << \"Line 4030. \\n\";\n//\n//\n//\n//\n// //Rcout << \"overall_liks = \" << overall_liks << \". \\n\";\n// //Rcout << \"max(overall_liks) = \" << max(overall_liks) << \". \\n\";\n// //Rcout << \"overall_liks[14] = \" << overall_liks[14] << \". \\n\";\n//\n//\n// double sumlik_total= arma::sum(overall_liks);\n// //Rcout << \"sumlik_total = \" << sumlik_total << \". \\n\";\n//\n// pred_vec_overall=pred_vec_overall*(1/sumlik_total);\n//\n\n\n\n\n\n\n\nif(fast_approx==1){\n  arma::vec BICi=-0.5*overall_liks;\n  double max_BIC=max(BICi);\n\n  // weighted_BIC is actually the posterior model probability\n  arma::vec weighted_BIC(overall_liks.size());\n\n\n  double tempterm=(max_BIC+log(sum(exp(BICi-max_BIC))));\n\n  for(unsigned int k=0;k<overall_liks.size();k++){\n\n    //NumericVector BICi=-0.5*BIC_weights;\n    //double max_BIC=max(BICi);\n    double weight=exp(BICi[k]-tempterm);\n    weighted_BIC[k]=weight;\n    //int num_its_to_sample = round(weight*(num_iter));\n\n  }\n\n  //Rcout << \"weighted_BIC= \" << weighted_BIC << \". \\n\";\n  //Rcout << \"overall_liks= \" << overall_liks << \". \\n\";\n\n#pragma omp parallel num_threads(ncores)\n{\n  arma::vec result_private;\n  if(is_test_data==1){\n    result_private=arma::zeros<arma::vec>(x_control_test_a.n_rows);\n  }else{\n    result_private=arma::zeros<arma::vec>(x_control_a.n_rows);\n  }\n\n#pragma omp for nowait //fill result_private in parallel\n  for(unsigned int i=0; i<overall_preds.size(); i++){\n    //double weight=exp(BICi[i]-(max_BIC+log(sum(exp(BICi-max_BIC)))));\n    result_private += overall_preds(i)*weighted_BIC(i);\n  }\n#pragma omp critical\n  pred_vec_overall += result_private;\n}\n\n\n}else{ //if fast_approx==0\n\n  //arma::vec BICi=-0.5*overall_liks;\n  double max_loglik=max(overall_liks);\n\n  // weighted_BIC is actually the posterior model probability\n  arma::vec weighted_lik(overall_liks.size());\n\n\n  double tempterm=(max_loglik+log(sum(exp(overall_liks-max_loglik))));\n\n  for(unsigned int k=0;k<overall_liks.size();k++){\n\n    //NumericVector BICi=-0.5*BIC_weights;\n    //double max_BIC=max(BICi);\n    double weight=exp(overall_liks[k]-tempterm);\n    weighted_lik[k]=weight;\n    //int num_its_to_sample = round(weight*(num_iter));\n\n  }\n\n  //Rcout << \"weighted_lik= \" << weighted_lik << \". \\n\";\n  //Rcout << \"overall_liks= \" << overall_liks << \". \\n\";\n\n#pragma omp parallel num_threads(ncores)\n{\n  arma::vec result_private;\n  //arma::vec result_private_mu;\n  //arma::vec result_private_y;\n\n  if(is_test_data==1){\n    result_private=arma::zeros<arma::vec>(x_control_test_a.n_rows);\n  }else{\n    result_private=arma::zeros<arma::vec>(x_control_a.n_rows);\n    //result_private_mu=arma::zeros<arma::vec>(x_control_a.n_rows);\n    //result_private_y=arma::zeros<arma::vec>(x_control_a.n_rows);\n\n  }\n\n#pragma omp for nowait //fill result_private in parallel\n  for(unsigned int i=0; i<overall_preds.size(); i++){\n    result_private += overall_preds(i)*weighted_lik(i);\n    //result_private_mu += overall_preds_mu(i)*weighted_lik(i);\n    //result_private_y += overall_preds_y(i)*weighted_lik(i);\n  }\n#pragma omp critical\n  pred_vec_overall += result_private;\n  //pred_vec_overall_mu += result_private_mu;\n  //pred_vec_overall_y += result_private_y;\n\n\n}\n\n\n//double sumlik_total= arma::sum(overall_liks);\n//Rcout << \"sumlik_total = \" << sumlik_total << \". \\n\";\n\n//pred_vec_overall=pred_vec_overall*(1/sumlik_total);\n\n// pred_vec_overall=arma::sum(overall_preds,1);\n// pred_vec_overall_mu=arma::sum(overall_preds_mu,1);\n// pred_vec_overall_y=arma::sum(overall_preds_y,1);\n\n}\n\n\n//Rcout << \"Line 7386. \\n\";\nNumericVector orig_preds=get_original_TE(min(ytrain),max(ytrain),-0.5,0.5,wrap(pred_vec_overall));\n//NumericVector orig_preds_mu=get_original(min(ytrain),max(ytrain),-0.5,0.5,wrap(pred_vec_overall_mu)) ;\n//NumericVector orig_preds_y=get_original(min(ytrain),max(ytrain),-0.5,0.5,wrap(pred_vec_overall_y)) ;\n\n\nreturn(orig_preds);\n\n//List ret(3);\n//ret[0]=orig_preds;\n//ret[1]=orig_preds_mu;\n//ret[2]=orig_preds_y;\n\n//return(ret);\n\n\n}\n//######################################################################################################################//\n\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::depends(dqrng, BH, sitmo)]]\n\n\n#include <xoshiro.h>\n#include <dqrng_distribution.h>\n//#include <dqrng.h>\n\n// [[Rcpp::plugins(openmp)]]\n#include <omp.h>\n\n//' @title Parallel Safe-BART with prediction intervals\n//'\n//' @description A parallelized implementation of safe-Bayesian Additive Regression Trees.\n//' @param lambda A real number between 0 and 1 that determines the splitting probability in the prior (which is used as the importance sampler of tree models). Quadrianto and Ghahramani (2015) recommend a value less than 0.5 .\n//' @param num_trees The number of trees to be sampled.\n//' @param seed The seed for random number generation.\n//' @param num_cats The number of possible values for the outcome variable.\n//' @param y The training data vector of outcomes. This must be a vector of integers between 1 and num_cats.\n//' @param original_datamat The original training data. Currently all variables must be continuous. The training data does not need to be transformed before being entered to this function.\n//' @param alpha_parameters Vector of prior parameters.\n//' @param beta_par The power to which the likelihood is to be raised. For BMA, set beta_par=1.\n//' @param original_datamat The original test data. This matrix must have the same number of columns (variables) as the training data. Currently all variables must be continuous. The test data does not need to be transformed before being entered to this function.\n//' @param ncores The number of cores to be used in parallelization.\n//' @return A List containing 1. A vector of predictions, and 2. A matrix of prediction intervals, the first row corresponds to the lower quantile, the second row is the median, and the third row is the upper quantile.\n//' @export\n// [[Rcpp::export]]\nList sBART_with_ints_parallel(double lambda,\n                                     int num_models,\n                                     int num_trees,\n                                     int seed,\n                                     NumericVector ytrain,\n                                     NumericMatrix original_datamat,\n                                     double beta_par,\n                                     NumericMatrix test_datamat,\n                                     int ncores,\n                                     int outsamppreds,\n                                     double nu,\n                                     double a,\n                                     double lambdaBART,\n                                     int valid_trees,\n                                     int tree_prior,\n                                     int imp_sampler,\n                                     double alpha_BART,\n                                     double beta_BART,\n                                     int s_t_hyperprior,\n                                     double p_s_t,\n                                     double a_s_t,\n                                     double b_s_t,\n                                     double lambda_poisson,\n                                     int fast_approx,\n                                double lower_prob,\n                                double upper_prob,\n                                double root_alg_precision){\n\n\n  //Rcout << \"imp_sampler = \" << imp_sampler << \".\\n\";\n\n  NumericVector y_scaled=scale_response(min(ytrain),max(ytrain),-0.5,0.5,ytrain);\n\n  int num_split_vars= original_datamat.ncol();\n  arma::mat data_arma= as<arma::mat>(original_datamat);\n  arma::mat testdata_arma= as<arma::mat>(test_datamat);\n  arma::vec orig_y_arma= as<arma::vec>(y_scaled);\n  //arma::vec alpha_pars_arma= as<arma::vec>(alpha_parameters);\n  int num_obs = data_arma.n_rows;\n  int num_test_obs = testdata_arma.n_rows;\n\n  int num_vars = data_arma.n_cols;\n\n  //calculations for likelihood\n  arma::mat y(num_obs,1);\n  y.col(0)=orig_y_arma;\n  //get exponent\n  double expon=(num_obs+nu)*0.5;\n  //get y^Tpsi^{-1}y\n  // arma::mat psi_inv=psi.i();\n  arma::mat yty=y.t()*y;\n\n  arma::mat I_test(num_test_obs,num_test_obs);\n  I_test=I_test.eye();\n\n  ///////////////////////\n  //NumericMatrix Data_transformed = cpptrans_cdf(original_datamat);\n  // NumericMatrix Data_transformed(original_datamat.nrow(), original_datamat.ncol());\n  // for(int i=0; i<original_datamat.ncol();i++){\n  //   NumericVector samp= original_datamat(_,i);\n  //   NumericVector sv(clone(samp));\n  //   std::sort(sv.begin(), sv.end());\n  //   double nobs = samp.size();\n  //   NumericVector ans(nobs);\n  //   for (int k = 0; k < samp.size(); ++k)\n  //     ans[k] = std::lower_bound(sv.begin(), sv.end(), samp[k]) - sv.begin();\n  //   //NumericVector ansnum = ans;\n  //   Data_transformed(_,i) = (ans+1)/nobs;\n  // }\n\n\n\n  //arma::mat arma_orig_data(Data_transformed.begin(), Data_transformed.nrow(), Data_transformed.ncol(), false);\n\n\n\n  //NumericMatrix transformedData(originaldata.nrow(), originaldata.ncol());\n\n  //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n  arma::mat arma_orig_data(data_arma.n_rows,data_arma.n_cols);\n  for(unsigned int k=0; k<data_arma.n_cols;k++){\n    arma::vec samp= data_arma.col(k);\n    arma::vec sv=arma::sort(samp);\n    //std::sort(sv.begin(), sv.end());\n    arma::uvec ord = arma::sort_index(samp);\n    double nobs = samp.n_elem;\n    arma::vec ans(nobs);\n    for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n      int ind=ord(i);\n      double ssampi(samp[ind]);\n      while (sv(j) < ssampi && j < sv.size()) ++j;\n      ans(ind) = j;     // j is the 1-based index of the lower bound\n    }\n    arma_orig_data.col(k)=(ans+1)/nobs;\n  }\n\n\n\n\n\n  /////////////////////////////////////\n  // NumericMatrix testdat_trans = cpptrans_cdf_test(original_datamat,test_datamat);\n  // //NumericMatrix testdat_trans(test_datamat.nrow(), test_datamat.ncol());\n  // for(int i=0; i<test_datamat.ncol();i++){\n  //   NumericVector samp= test_datamat(_,i);\n  //   NumericVector svtest = original_datamat(_,i);\n  //   NumericVector sv(clone(svtest));\n  //   std::sort(sv.begin(), sv.end());\n  //   double nobs = samp.size();\n  //   NumericVector ans(nobs);\n  //   double nobsref = svtest.size();\n  //   for (int k = 0; k < samp.size(); ++k){\n  //     ans[k] = std::lower_bound(sv.begin(), sv.end(), samp[k]) - sv.begin();\n  //   }\n  //   //NumericVector ansnum = ans;\n  //   testdat_trans(_,i) = (ans)/nobsref;\n  // }\n\n\n\n\n\n  //NumericMatrix transformedData(originaldata.nrow(), originaldata.ncol());\n  //arma::mat data_arma= as<arma::mat>(originaldata);\n\n  //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n  arma::mat arma_test_data(testdata_arma.n_rows,testdata_arma.n_cols);\n  for(unsigned int k=0; k<data_arma.n_cols;k++){\n    arma::vec ref= data_arma.col(k);\n    arma::vec samp= testdata_arma.col(k);\n\n    arma::vec sv=arma::sort(samp);\n    arma::vec sref=arma::sort(ref);\n\n    //std::sort(sv.begin(), sv.end());\n    arma::uvec ord = arma::sort_index(samp);\n    double nobs = samp.n_elem;\n    double nobsref = ref.n_elem;\n\n    arma::vec ans(nobs);\n    for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n      int ind=ord(i);\n      double ssampi(samp[ind]);\n      if(j+1>sref.size()){\n      }else{\n        while (sref(j) < ssampi && j < sref.size()){\n          ++j;\n          if(j==sref.size()) break;\n        }\n      }\n      ans(ind) = j;     // j is the 1-based index of the lower bound\n    }\n\n    arma_test_data.col(k)=(ans)/nobsref;\n\n  }\n\n\n\n\n\n\n\n  /////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n  //////////////////////////////////////////////////////////////////////////////////////\n  //List table_list = draw_trees(lambda, num_trees, seed, num_split_vars, num_cats );\n\n\n\n  //dqrng::dqRNGkind(\"Xoroshiro128+\");\n  //dqrng::dqset_seed(IntegerVector::create(seed));\n\n  //use following with binomial?\n  //dqrng::xoshiro256plus rng(seed);\n\n  std::vector<double> lambdavec = {lambda, 1-lambda};\n\n  //typedef boost::mt19937 RNGType;\n  //boost::random::uniform_int_distribution<> sample_splitvardist(1,num_split_vars);\n  //boost::variate_generator< RNGType, boost::uniform_int<> >  sample_splitvars(rng, sample_splitvardist);\n\n  //boost::random::uniform_real_distribution<double> b_unifdist(0,1);\n  //boost::variate_generator< RNGType, boost::uniform_real<> >  b_unif_point(rng, b_unifdist);\n\n\n\n  std::random_device device;\n  //std::mt19937 gen(device());\n\n  //possibly use seed?\n  //// std::mt19937 gen(seed);\n\n  dqrng::xoshiro256plus gen(device());              // properly seeded rng\n\n  //dqrng::xoshiro256plus gen(seed);              // properly seeded rng\n\n\n\n\n  std::bernoulli_distribution coin_flip(lambda);\n\n\n  std::bernoulli_distribution coin_flip_even(0.5);\n\n  double spike_prob1;\n  if(s_t_hyperprior==1){\n    spike_prob1=a_s_t/(a_s_t + b_s_t);\n  }else{\n    spike_prob1=p_s_t;\n  }\n\n  std::bernoulli_distribution coin_flip_spike(spike_prob1);\n\n\n  std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n  std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n  std::poisson_distribution<int> gen_num_term(lambda_poisson);\n\n\n  //dqrng::uniform_distribution dis_cont_unif(0.0, 1.0); // Uniform distribution [0,1)\n\n  //Following three functions can't be used in parallel\n  //dqrng::dqsample_int coin_flip2(2, 1, true,lambdavec );\n  //dqrng::dqsample_int distsampvar(num_split_vars, 1, true);\n  //dqrng::dqrunif dis_cont_unif(1, 0, 1);\n\n\n\n  //arma::mat arma_test_data(testdat_trans.begin(), testdat_trans.nrow(), testdat_trans.ncol(), false);\n\n\n  arma::vec pred_vec_overall=arma::zeros<arma::vec>(arma_test_data.n_rows);\n\n\n  //arma::field<arma::mat> overall_treetables(num_models);\n\n  //::field<arma::vec> overall_preds(num_models);\n\n  arma::vec overall_liks(num_models);\n\n  arma::mat overall_preds(num_test_obs,num_models);\n  arma::mat t_vars_arma(num_test_obs,num_models);\n\n\n  //overall_treetables[i]= wrap(tree_table1);\n  //double templik = as<double>(treepred_output[1]);\n  //overall_liks[i]= pow(lik_prod,beta_pow);\n\n  //Rcout << \"Line 3338. \\n\";\n\n\n#pragma omp parallel num_threads(ncores)\n{//start of pragma omp code\n  dqrng::xoshiro256plus lgen(gen);      // make thread local copy of rng\n  lgen.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... ncores jumps\n\n#pragma omp for\n  for(int j=0; j<num_models;j++){\n\n    arma::mat Wmat(num_obs,0);\n\n    //maybe use line below, depends how Jmat joined to Wmat\n    //int upsilon=0;\n\n    arma::mat W_tilde(num_test_obs,0);\n\n    //maybe use line below, depends how Jmat joined to Wmat\n    //int upsilon2=0;\n\n    //double sum_tree_samp_prob=1;\n    //double sum_tree_prior_prob=1;\n\n    double sum_prior_over_samp_prob=1;\n\n    for(int q=0; q<num_trees;q++){  //start of loop over trees in sum\n\n\n      //If parallelizing, define the distributinos before this loop\n      //and use lrng and the following two lines\n      //dqrng::xoshiro256plus lrng(rng);      // make thread local copy of rng\n      //lrng.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... nthreads jumps\n\n\n      //NumericVector treenodes_bin(0);\n      //arma::uvec treenodes_bin(0);\n\n      std::vector<int> treenodes_bin;\n      std::vector<int> split_var_vec;\n\n\n      int count_terminals = 0;\n      int count_internals = 0;\n\n      //int count_treebuild = 0;\n\n      if(imp_sampler==2){ // If sampling from SPike and Tree\n\n        //Rcout << \"Line 3737 .\\n\";\n\n\n        //make coinflip_spike before loop\n        //also make bernoulli with probability 0.5\n\n        //make a poisson distribtion\n\n\n        //might be easier to store indices as armadillo vector, because will have to remove\n        //potential splits when allocating to terminal nodes\n        std::vector<int> potentialsplitvars;\n\n        for(int varcount=0; varcount<num_vars;varcount++){\n          bool tempflip=coin_flip_spike(lgen);\n          if(tempflip==TRUE){\n            potentialsplitvars.push_back(varcount);\n          }\n        }\n\n        //Then draw number of terminal nodes from a truncated Poisson\n        //must be at least equal to number of potential splitting variables plus 1\n        int q_numsplitvars=potentialsplitvars.size();\n\n        int num_term_nodes_draw;\n        if(q_numsplitvars==0){\n          //num_term_nodes_draw==1;\n          treenodes_bin.push_back(0);\n          split_var_vec.push_back(0);\n        }else{\n          do{\n            num_term_nodes_draw = gen_num_term(lgen);//Poissondraw\n          }\n          while(num_term_nodes_draw<q_numsplitvars+1); //Check if enough terminal nodes. If not, take another draw\n\n\n          //Now draw a tree with num_term_nodes_draw terminal nodes\n          //Use Remy's algorithm or the algorithm described by Bacher et al.\n\n          //Rcout << \"Line 3771 .\\n\";\n\n          long length=(num_term_nodes_draw-1)*2;\n          //Rcout << \"Line 3774 .\\n\";\n\n          std::vector<int> treenodes_bintemp(length+1);\n          int p_ind=0;\n          long height = 0;\n\n          //Rcout << \"Line 195. \\n\";\n          //Rcout << \"Line 3781 .\\n\";\n          //Rcout << \"q_numsplitvars = \" << q_numsplitvars << \".\\n\";\n\n          for(long i = 0; i < length+1; i ++) {\n            //signed char x = random_int(1) ? 1 : -1;\n            int x = coin_flip_even(lgen) ? 1 : -1;\n            treenodes_bintemp[i] = x;\n            height += x;\n\n            if(height < 0) {\n              // this should return a uniform random integer between 0 and x\n              //unsigned long random_int(unsigned long x);\n              std::uniform_int_distribution<> random_int(0, i);\n              long j = random_int(lgen);\n              //long j = random_int(i);\n              //height += unfold(p_ind + j,treenodes_bintemp, i + 1 - j);\n\n              long length1=i+1-j;\n              long height1 = 0;\n              long local_height = 0;\n              int x = 1;\n\n              for(long i = 0; i < length1; i ++) {\n                int y = treenodes_bintemp[p_ind+j+i];\n                local_height += y;\n                if(local_height < 0) {\n                  y = 1;\n                  height1 += 2;\n                  local_height = 0;\n                }\n                treenodes_bintemp[p_ind+j+i] = x;\n                x = y;\n              }\n              height +=height1;\n\n\n\n\n            }\n          }\n\n          //Rcout << \"Line 213. \\n\";\n          //Rcout << \"Line 3822 .\\n\";\n\n\n          //fold(treenodes_bintemp, length + 1, height);\n          long local_height = 0;\n          int x = -1;\n          ////Rcout << \"Line 121. \\n\";\n          //Rcout << \"treenodes_bintemp.size() =\" << treenodes_bintemp.size() << \". \\n\";\n          //Rcout << \"length - 1 =\" << length - 1 << \". \\n\";\n\n\n          for(long i = length; height > 0; i --) {\n            int y = treenodes_bintemp[i];\n            local_height -= y;\n            if(local_height < 0) {\n              y = -1;\n              height -= 2;\n              local_height = 0;\n            }\n            treenodes_bintemp[i] = x;\n            x = y;\n          }\n          //Rcout << \"Line 134. \\n\";\n\n\n          //Rcout << \"Line 217. \\n\";\n          //Rcout << \"Line 3847 .\\n\";\n\n          //Rcout << \"Line 238. \\n\";\n          std::replace(treenodes_bintemp.begin(), treenodes_bintemp.end(), -1, 0); // 10 99 30 30 99 10 10 99\n\n\n          // Then store tree structure as treenodes_bintemp\n\n          //create splitting variable vector\n          std::vector<int> splitvar_vectemp(treenodes_bintemp.size());\n\n          std::vector<int> drawnvarstemp(num_term_nodes_draw-1);\n\n          //keep count of how many splitting points have been filled in\n          int splitcount=0;\n\n          //loop through nodes, filling in splitting variables for nonterminal nodes\n          //when less than q_numsplitvars remaining internal nodes to be filled in\n          //have to start reducing the set of potential splitting variables\n          //to ensure that each selected potential split variable is used at least once. [hence the if statement containing .erase]\n\n          int index_remaining=0;\n          for(unsigned int nodecount=0; nodecount<treenodes_bintemp.size();nodecount++){\n            if(treenodes_bintemp[nodecount]==1){\n              splitcount++;\n              //Rcout << \"potentialsplitvars.size() = \" <<  potentialsplitvars.size() << \" .\\n\";\n\n              //Rcout << \"potentialsplitvars.size()-1 = \" <<  potentialsplitvars.size()-1 << \" .\\n\";\n              if(splitcount>num_term_nodes_draw-1-q_numsplitvars){//CHECK THIS CONDITION\n                //To ensure each variable used at least once, fill in the rest of the splits with all the variables\n                //The split variables will be randomly shuffled anyway, therefore the order is not important here.\n                drawnvarstemp[splitcount-1]=potentialsplitvars[index_remaining]+1;\n                index_remaining++;\n              }else{\n                //randomly draw a splitting varaible from the set of potential splitting variables\n                std::uniform_int_distribution<> draw_var(0,potentialsplitvars.size()-1);//q_numsplitvars-splitcount could replace potentialsplitvars.size()\n                int tempsplitvar = draw_var(lgen);\n                drawnvarstemp[splitcount-1]=potentialsplitvars[tempsplitvar]+1;\n\n              }\n\n              //if(splitcount>num_term_nodes_draw-1-q_numsplitvars){//CHECK THIS CONDITION\n              //  potentialsplitvars.erase(potentialsplitvars.begin()+tempsplitvar);\n              //}\n\n            }else{//if not a split\n              //splitvar_vectemp[nodecount]=-1;\n            }\n          }\n\n          std::shuffle(drawnvarstemp.begin(),drawnvarstemp.end(),lgen);\n\n          splitcount=0;\n          for(unsigned int nodecount=0; nodecount<treenodes_bintemp.size();nodecount++){\n            if(treenodes_bintemp[nodecount]==1){\n              splitvar_vectemp[nodecount]=drawnvarstemp[splitcount];\n              splitcount++;\n            }else{//if not a split\n              splitvar_vectemp[nodecount]=-1;\n            }\n          }\n\n          //Rcout << \"Line 3876 .\\n\";\n          split_var_vec=splitvar_vectemp;\n          treenodes_bin=treenodes_bintemp;\n        }\n      }else{\n        if(imp_sampler==1){ //If sampling from BART prior\n\n          //std::bernoulli_distribution coin_flip2(lambda);\n          double depth1=0;\n          int prev_node=0; //1 if previous node splits, zero otherwise\n\n          double samp_prob;\n\n          while(count_internals > (count_terminals -1)){\n            samp_prob=alpha_BART*pow(double(depth1+1),-beta_BART);\n            std::bernoulli_distribution coin_flip2(samp_prob);\n\n            int tempdraw = coin_flip2(lgen);\n            treenodes_bin.push_back(tempdraw);\n\n            if(tempdraw==1){\n\n              depth1=depth1+1; //after a split, the depth will increase by 1\n              prev_node=1;\n              count_internals=count_internals+1;\n\n            }else{\n\n              if(prev_node==1){//zero following a 1, therefore at same depth.\n                //Don't change depth. Do nothing\n              }else{ //zero following a zero, therefore the depth will decrease by 1\n                depth1=depth1-1;\n              }\n              prev_node=0;\n              count_terminals=count_terminals+1;\n\n            }\n\n          }\n\n        }else{  //If not sampling from BART prior\n          //If sampling from default Q+G prior. i.e. not sampling from BART nor spike and tree prior\n\n          while(count_internals > (count_terminals -1)){\n\n            //Also consider standard library and random header\n            // std::random_device device;\n            // std::mt19937 gen(device());\n            // std::bernoulli_distribution coin_flip(lambda);\n            // bool outcome = coin_flip(gen);\n\n\n            int tempdraw = coin_flip(lgen);\n\n            //int tempdraw = rbinom(n = 1, prob = lambda,size=1);\n\n\n            //int tempdraw = Rcpp::rbinom(1,lambda,1);\n            //int tempdraw = R::rbinom(1,lambda);\n\n            ////Rcout << \"tempdraw = \" << tempdraw << \".\\n\" ;\n\n            //int tempdraw = coin_flip2(lgen)-1;\n\n            //int tempdraw = dqrng::dqsample_int(2, 1, true,lambdavec )-1;\n\n\n            //need to update rng if use boost?\n            //int tempdraw = bernoulli(rng, binomial::param_type(1, lambda));\n\n            treenodes_bin.push_back(tempdraw);\n\n\n            if(tempdraw==1){\n              count_internals=count_internals+1;\n            }else{\n              count_terminals=count_terminals+1;\n            }\n\n          }//end of while loop creating parent vector treenodes_bin\n        }//end of Q+H sampling else statement\n      }//end of not Spike and Tree sampler else statement\n\n      //Rcout << \"Line 3961 .\\n\";\n\n\n      if(imp_sampler==2){\n        //already filled in splitting variable above for spike and tree prior\n      }else{\n        //Consider making this an armadillo vector\n        //IntegerVector split_var_vec(treenodes_bin.size());\n        //arma::uvec split_var_vec(treenodes_bin.size());\n        std::vector<int> split_var_vectemp(treenodes_bin.size());\n\n        // possibly faster alternative\n        //    split_var_vec.reserve( treenodes_bin.size() );\n        // then push_back elements to split_var_vec in the for loop\n\n        //loop drawing splitting variables\n        //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n        //if using armadillo, it might be faster to subset to split nodes\n        //then use a vector of draws\n        for(unsigned int i=0; i<treenodes_bin.size();i++){\n          if(treenodes_bin[i]==0){\n            split_var_vectemp[i] = -1;\n          }else{\n            // also consider the standard library function uniform_int_distribution\n            // might need random header\n            // This uses the Mersenne twister\n\n            //Three lines below should probably be outside all the loops\n            // std::random_device rd;\n            // std::mt19937 engine(rd());\n            // std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n            //\n            // split_var_vec[i] = distsampvar(engine);\n\n            split_var_vectemp[i] = distsampvar(lgen);\n\n\n            //consider using boost\n            //might need to update rng\n            //split_var_vec[i] <- sample_splitvars(rng);\n\n            //or use dqrng\n            //not sure if have to update the random number\n            //check if the following line is written properly\n            //split_var_vec[i] = dqrng::dqsample_int(num_split_vars, 1, true);\n\n            //not sure if this returns an integer or a vector?\n            //split_var_vec[i] = RcppArmadillo::sample(num_split_vars, 1,true);\n            //could try\n            //split_var_vec[i] = as<int>(Rcpp::sample(num_split_vars, 1,true));\n            //could also try RcppArmadillo::rmultinom\n\n          }\n\n        }// end of for-loop drawing split variables\n\n        split_var_vec=split_var_vectemp;\n      }//end else statrement filling in splitting variable vector\n\n      //Consider making this an armadillo vector\n      //NumericVector split_point_vec(treenodes_bin.size());\n      //arma::vec split_point_vec(treenodes_bin.size());\n      std::vector<double> split_point_vec(treenodes_bin.size());\n\n\n      //loop drawing splitting points\n      //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n      //if using armadillo, it might be faster to subset to split nodes\n      //then use a vector of draws\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        if(treenodes_bin[i]==0){\n          split_point_vec[i] = -1;\n        }else{\n\n\n          //////////////////////////////////////////////////////////\n          //following function not reccommended\n          //split_point_vec[i] = std::rand();\n          //////////////////////////////////////////////////////////\n          ////Standard library:\n          ////This should probably be outside all the loops\n          ////std::random_device rd;  //Will be used to obtain a seed for the random number engine\n          ////std::mt19937 gen2(rd()); //Standard mersenne_twister_engine seeded with rd()\n          ////std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n          split_point_vec[i] = dis_cont_unif(lgen);\n\n          //////////////////////////////////////////////////////////\n          //from armadillo\n          //split_point_vec[i] = arma::randu();\n\n          //////////////////////////////////////////////////////////\n          //probably not adviseable for paralelization\n          //From Rcpp\n          //split_point_vec[i] = as<double>(Rcpp::runif(1,0,1));\n\n          //////////////////////////////////////////////////////////\n          //consider using boost\n          //might need to update rng\n          //split_point_vec[i] <- b_unif_point(rng);\n\n          //or use dqrng\n          //not sure if have to update the random number\n          //check if the following line is written properly\n          //split_point_vec[i] = dqrng::dqrunif(1, 0, 1);\n\n          //not sure if this returns an integer or a vector?\n\n\n\n\n\n        }\n\n      }// end of for-loop drawing split points\n\n\n\n      //Rcout << \"Line 4081 .\\n\";\n\n\n      //CODE FOR ADJUSTING SPLITTING POINTS SO THAT THE TREES ARE VALID\n      if(valid_trees==1){\n        for(unsigned int i=0; i<treenodes_bin.size();i++){ //loop over all nodes\n          if(treenodes_bin[i]==1){ // if it is an internal node, then check for further splits on the same variable and update\n            double first_split_var=split_var_vec[i];      //splitting variable to check for\n            double first_split_point=split_point_vec[i];  //splitting point to use in updates\n\n            double sub_int_nodes=0;       //this internal node count will be used to determine if in subtree relevant to sub_int_nodes\n            double sub_term_nodes=0;      //this terminal node count will be used to determine if in subtree relevant to sub_int_nodes\n            double preventing_updates=0; //indicates if still within subtree that is not to be updated\n            double prevent_int_count=0;   //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n            double prevent_term_count=0;  //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n            for(unsigned int k=i+1; k<treenodes_bin.size();k++){\n              if(treenodes_bin[k]==1){\n                sub_int_nodes=sub_int_nodes+1;\n                if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                  prevent_int_count=prevent_int_count+1;\n                }\n              }else{\n                sub_term_nodes=sub_term_nodes+1;\n                if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                  prevent_term_count=prevent_term_count+1;\n                }\n              }\n              if(sub_int_nodes<=sub_term_nodes-2){\n                break;\n              }\n\n\n              if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                if(prevent_int_count>prevent_term_count-1){ //if this rule is satisfied then in subtree that is not to be updated\n                  continue; //still in subtree, therefore continue instead of checking for splits to be updates\n                }else{\n                  preventing_updates=0; // no longer in subtree, therefore reset preventing_updates to zero\n                }\n              }\n\n\n              if(sub_int_nodes>sub_term_nodes-1){\n                if(treenodes_bin[k]==1){\n                  if(split_var_vec[k]==first_split_var){\n                    split_point_vec[k]=split_point_vec[k]*first_split_point;\n                    //beginning count of subtree that should not have\n                    //further splits on first_split_var updated\n                    preventing_updates=1; //indicates if still within subtree that is not to be updated\n                    prevent_int_count=1;\n                    prevent_term_count=0;\n                  }\n                }\n              }else{\n                if(treenodes_bin[k]==1){\n                  if(split_var_vec[k]==first_split_var){\n                    split_point_vec[k]=split_point_vec[k]+first_split_point-first_split_point*split_point_vec[k];\n                    //beginning count of subtree that should not have\n                    //further splits on first_split_var updated\n                    preventing_updates=1; //indicates if still within subtree that is not to be updated\n                    prevent_int_count=1;\n                    prevent_term_count=0;\n                  }\n                }\n              }\n\n\n\n            }//end of inner loop over k\n          }//end of if statement treenodes_bin[i]==1)\n        }//end of loop over i\n      }//end of if statement valid_trees==1\n\n\n\n\n\n      //Rcout << \"Line 4161 .\\n\";\n\n\n\n\n\n      //Create tree table matrix\n\n      //NumericMatrix tree_table1(treenodes_bin.size(),5+num_cats);\n\n      ////Rcout << \"Line 1037. \\n\";\n      //arma::mat tree_table1(treenodes_bin.size(),5+num_cats);\n\n      //initialize with zeros. Not sure if this is necessary\n      arma::mat tree_table1=arma::zeros<arma::mat>(treenodes_bin.size(),6);\n      //Rcout << \"Line 1040. \\n\";\n\n\n      //tree_table1(_,2) = wrap(split_var_vec);\n      //tree_table1(_,3) = wrap(split_point_vec);\n      //tree_table1(_,4) = wrap(treenodes_bin);\n\n\n\n      //It might be more efficient to make everything an armadillo object initially\n      // but then would need to replace push_back etc with a different approach (but this might be more efficient anyway)\n      arma::colvec split_var_vec_arma=arma::conv_to<arma::colvec>::from(split_var_vec);\n      //arma::colvec split_point_vec_arma(split_point_vec);\n      //arma::colvec split_point_vec_arma(split_point_vec);\n      arma::colvec split_point_vec_arma=arma::conv_to<arma::colvec>::from(split_point_vec);\n\n      arma::colvec treenodes_bin_arma=arma::conv_to<arma::colvec>::from(treenodes_bin);\n\n      //Rcout << \"split_var_vec_arma = \" << split_var_vec_arma << \" . \\n\";\n\n      //Rcout << \"split_point_vec_arma = \" << split_point_vec_arma << \" . \\n\";\n\n      //Rcout << \"treenodes_bin_arma = \" << treenodes_bin_arma << \" . \\n\";\n\n\n      //Rcout << \"Line 1054. \\n\";\n\n      //Fill in splitting variable column\n      tree_table1.col(2) = split_var_vec_arma;\n      //Fill in splitting point column\n      tree_table1.col(3) = split_point_vec_arma;\n      //Fill in split/parent column\n      tree_table1.col(4) = treenodes_bin_arma;\n\n\n      //Rcout << \"Line 4200. j = \" << j << \". \\n\";\n\n      ////Rcout << \"Line 4081 .\\n\";\n\n\n      // Now start filling in left daughter and right daughter columns\n      std::vector<int> rd_spaces;\n      int prev_node = -1;\n\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        ////Rcout << \"Line 1061. i = \" << i << \". \\n\";\n        if(prev_node==0){\n          //tree_table1(rd_spaces[rd_spaces.size()-1], 1)=i;\n          //Rcout << \"Line 1073. j = \" << j << \". \\n\";\n\n          tree_table1(rd_spaces.back(), 1)=i+1;\n          //Rcout << \"Line 1076. j = \" << j << \". \\n\";\n\n          rd_spaces.pop_back();\n        }\n        if(treenodes_bin[i]==1){\n          //Rcout << \"Line 1081. j = \" << j << \". \\n\";\n\n          tree_table1(i,0) = i+2;\n          rd_spaces.push_back(i);\n          prev_node = 1;\n          //Rcout << \"Line 185. j = \" << j << \". \\n\";\n\n        }else{                  // These 2 lines unnecessary if begin with matrix of zeros\n          //Rcout << \"Line 1089. j = \" << j << \". \\n\";\n          tree_table1(i,0)=0 ;\n          tree_table1(i,1) = 0 ;\n          prev_node = 0;\n          //Rcout << \"Line 1093. j = \" << j << \". \\n\";\n\n        }\n      }//\n      //Rcout << \"Line 1097. j = \" << j << \". \\n\";\n\n\n\n\n      //Rcout << \"Line 4242 .\\n\";\n\n      //List treepred_output = get_treepreds(original_y, num_cats, alpha_pars,\n      //                                     originaldata,\n      //                                     treetable_list[i]  );\n\n\n      //use armadillo object tree_table1\n\n      ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n      ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n      //create variables for likelihood calcuations\n      // double lik_prod=1;\n      // double alph_prod=1;\n      // for(unsigned int i=0; i<alpha_pars_arma.n_elem;i++){\n      //   alph_prod=alph_prod*tgamma(alpha_pars_arma(i));\n      // }\n      // double gam_alph_sum= tgamma(arma::sum(alpha_pars_arma));\n      // double alph_term=gam_alph_sum/alph_prod;\n\n      //arma::mat arma_tree_table(treetable.begin(), treetable.nrow(), treetable.ncol(), false);\n      //arma::mat arma_orig_data(originaldata.begin(), originaldata.nrow(), originaldata.ncol(), false);\n\n\n      //arma::mat arma_tree(tree_data.begin(), tree_data.nrow(), tree_data.ncol(), false);\n      //arma::mat testd(test_data.begin(), test_data.nrow(), test_data.ncol(), false);\n\n      //NumericVector internal_nodes=find_internal_nodes_gs(tree_data);\n\n      //NumericVector terminal_nodes=find_term_nodes(treetable);\n\n      //arma::mat arma_tree(tree_table.begin(),tree_table.nrow(), tree_table.ncol(), false);\n\n      //arma::vec colmat=arma_tree.col(4);\n      //arma::uvec term_nodes=arma::find(colmat==-1);\n\n      //arma::vec colmat=arma_tree.col(2);\n      //arma::uvec term_nodes=arma::find(colmat==0);\n\n      //arma::vec colmat=tree_table1.col(4);\n      //arma::uvec term_nodes=arma::find(colmat==0);\n\n      //4th column is treenodes_bin_arma\n      arma::uvec term_nodes=arma::find(treenodes_bin_arma==0);\n\n      term_nodes=term_nodes+1;\n\n      //NumericVector terminal_nodes= wrap(term_nodes);\n\n\n\n      //GET J MATRIX\n\n      arma::mat Jmat(num_obs,term_nodes.n_elem);\n      arma::mat Jtilde(num_test_obs,term_nodes.n_elem);\n\n      //arma::vec arma_terminal_nodes=Rcpp::as<arma::vec>(terminal_nodes);\n      //NumericVector tree_predictions;\n\n      //now for each internal node find the observations that belong to the terminal nodes\n\n      //NumericVector predictions(test_data.nrow());\n      //List term_obs(term_nodes.n_elem);\n\n      //GET J MATRIX\n\n      //Rcout << \"Line 4311 .\\n\";\n\n      if(term_nodes.n_elem==1){\n        //double nodemean=tree_data(terminal_nodes[0]-1,5);\t\t\t\t// let nodemean equal tree_data row terminal_nodes[i]^th row , 6th column. The minus 1 is because terminal nodes consists of indices starting at 1, but need indices to start at 0.\n        //predictions=rep(nodemean,test_data.nrow());\n        //Rcout << \"Line 67 .\\n\";\n\n        //IntegerVector temp_obsvec = seq_len(test_data.nrow())-1;\n        //term_obs[0]= temp_obsvec;\n        //double denom_temp= orig_y_arma.n_elem+arma::sum(alpha_pars_arma);\n\n        //double num_prod=1;\n        //double num_sum=0;\n        //Rcout << \"Line 129.\\n\";\n        Jmat.col(0) = arma::ones<arma::vec>(num_obs);\n        Jtilde.col(0) = arma::ones<arma::vec>(num_test_obs);\n\n        //for(int k=0; k<num_cats; k++){\n        //assuming categories of y are from 1 to num_cats\n        //arma::uvec cat_inds= arma::find(orig_y_arma==k+1);\n        //double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n        //tree_table1(0,5+k)= m_plus_alph/denom_temp ;\n\n        //for likelihood calculation\n        //num_prod=num_prod*tgamma(m_plus_alph);\n        //num_sum=num_sum +m_plus_alph ;\n        //}\n\n        //lik_prod= alph_term*num_prod/tgamma(num_sum);\n\n      }\n      else{\n        for(unsigned int i=0;i<term_nodes.n_elem;i++){\n          //arma::mat subdata=testd;\n          //int curr_term=term_nodes(i);\n\n          int row_index;\n          int term_node=term_nodes(i);\n          //Rcout << \"Line 152.\\n\";\n\n\n          //WHAT IS THE PURPOSE OF THIS IF-STATEMENT?\n          //Why should the ro index be different for a right daughter?\n          //Why not just initialize row_index to any number not equal to 1 (e.g. 0)?\n          row_index=0;\n\n          // if(curr_term % 2==0){\n          //   //term node is left daughter\n          //   row_index=terminal_nodes[i];\n          // }else{\n          //   //term node is right daughter\n          //   row_index=terminal_nodes[i]-1;\n          // }\n\n\n\n\n          //save the left and right node data into arma uvec\n\n          //CHECK THAT THIS REFERS TO THE CORRECT COLUMNS\n          //arma::vec left_nodes=arma_tree.col(0);\n          //arma::vec right_nodes=arma_tree.col(1);\n\n          arma::vec left_nodes=tree_table1.col(0);\n          arma::vec right_nodes=tree_table1.col(1);\n\n\n\n          arma::mat node_split_mat;\n          node_split_mat.set_size(0,3);\n          //Rcout << \"Line 182. i = \" << i << \" .\\n\";\n\n          while(row_index!=1){\n            //for each terminal node work backwards and see if the parent node was a left or right node\n            //append split info to a matrix\n            int rd=0;\n            arma::uvec parent_node=arma::find(left_nodes == term_node);\n\n            if(parent_node.size()==0){\n              parent_node=arma::find(right_nodes == term_node);\n              rd=1;\n            }\n\n            //want to cout parent node and append to node_split_mat\n\n            node_split_mat.insert_rows(0,1);\n\n            //CHECK THAT COLUMNS OF TREETABLE ARE CORRECT\n            //node_split_mat(0,0)=treetable(parent_node[0],2);\n            //node_split_mat(0,1)=treetable(parent_node[0],3);\n\n            //node_split_mat(0,0)=arma_tree_table(parent_node[0],3);\n            //node_split_mat(0,1)=arma_tree_table(parent_node[0],4);\n\n            node_split_mat(0,0)=tree_table1(parent_node(0),2);\n            node_split_mat(0,1)=tree_table1(parent_node(0),3);\n\n            node_split_mat(0,2)=rd;\n            row_index=parent_node(0)+1;\n            term_node=parent_node(0)+1;\n          }\n\n          //once we have the split info, loop through rows and find the subset indexes for that terminal node!\n          //then fill in the predicted value for that tree\n          //double prediction = tree_data(term_node,5);\n          arma::uvec pred_indices;\n          arma::uvec pred_test_indices;\n          int split= node_split_mat(0,0)-1;\n\n          //Rcout << \"Line 224.\\n\";\n          //Rcout << \"split = \" << split << \".\\n\";\n          //arma::vec tempvec = testd.col(split);\n          arma::vec tempvec = arma_orig_data.col(split);\n          arma::vec temptest_vec = arma_test_data.col(split);\n          //Rcout << \"Line 227.\\n\";\n\n\n          double temp_split = node_split_mat(0,1);\n\n          if(node_split_mat(0,2)==0){\n            pred_indices = arma::find(tempvec <= temp_split);\n            pred_test_indices = arma::find(temptest_vec <= temp_split);\n          }else{\n            pred_indices = arma::find(tempvec > temp_split);\n            pred_test_indices = arma::find(temptest_vec > temp_split);\n          }\n          //Rcout << \"Line 236.\\n\";\n\n          arma::uvec temp_pred_indices;\n          arma::uvec temp_test_pred_indices;\n\n          //arma::vec data_subset = testd.col(split);\n          arma::vec data_subset = arma_orig_data.col(split);\n          arma::vec data_test_subset = arma_test_data.col(split);\n\n          data_subset=data_subset.elem(pred_indices);\n          data_test_subset=data_test_subset.elem(pred_test_indices);\n\n          //now loop through each row of node_split_mat\n          int n=node_split_mat.n_rows;\n          //Rcout << \"Line 174. i = \" << i << \". n = \" << n << \".\\n\";\n          //Rcout << \"Line 248.\\n\";\n\n          for(int j=1;j<n;j++){\n            int curr_sv=node_split_mat(j,0);\n            double split_p = node_split_mat(j,1);\n\n            //data_subset = testd.col(curr_sv-1);\n            //Rcout << \"Line 255.\\n\";\n            //Rcout << \"curr_sv = \" << curr_sv << \".\\n\";\n            data_subset = arma_orig_data.col(curr_sv-1);\n            data_test_subset = arma_test_data.col(curr_sv-1);\n            //Rcout << \"Line 258.\\n\";\n\n            data_subset=data_subset.elem(pred_indices);\n            data_test_subset=data_test_subset.elem(pred_test_indices);\n\n            if(node_split_mat(j,2)==0){\n              //split is to the left\n              temp_pred_indices=arma::find(data_subset <= split_p);\n              temp_test_pred_indices=arma::find(data_test_subset <= split_p);\n            }else{\n              //split is to the right\n              temp_pred_indices=arma::find(data_subset > split_p);\n              temp_test_pred_indices=arma::find(data_test_subset > split_p);\n            }\n            pred_indices=pred_indices.elem(temp_pred_indices);\n            pred_test_indices=pred_test_indices.elem(temp_test_pred_indices);\n\n            //if(pred_indices.size()==0){\n            //  continue;\n            //}\n\n          }\n          //Rcout << \"Line 199. i = \" << i <<  \".\\n\";\n\n          //There is probably a more efficient way of doing this\n          //e.g. initialize J matrix so that all elements are equal to zero\n          arma::vec tempcol_J=arma::zeros<arma::vec>(num_obs);\n          tempcol_J(pred_indices) = arma::ones<arma::vec>(pred_indices.size());\n          Jmat.col(i) = tempcol_J;\n\n          arma::vec tempcol_Jtilde=arma::zeros<arma::vec>(num_test_obs);\n          tempcol_Jtilde(pred_test_indices) = arma::ones<arma::vec>(pred_test_indices.size());\n          Jtilde.col(i) = tempcol_Jtilde;\n\n          //double nodemean=tree_data(terminal_nodes[i]-1,5);\n          //IntegerVector predind=as<IntegerVector>(wrap(pred_indices));\n          //predictions[predind]= nodemean;\n          //term_obs[i]=predind;\n\n          //double denom_temp= pred_indices.n_elem+arma::sum(alpha_pars_arma);\n          //Rcout << \"Line 207. predind = \" << predind <<  \".\\n\";\n          //Rcout << \"Line 207. denom_temp = \" << denom_temp <<  \".\\n\";\n          // << \"Line 207. term_node = \" << term_node <<  \".\\n\";\n\n          //double num_prod=1;\n          //double num_sum=0;\n\n          // for(int k=0; k<num_cats; k++){\n          //   //assuming categories of y are from 1 to num_cats\n          //   arma::uvec cat_inds= arma::find(orig_y_arma(pred_indices)==k+1);\n          //   double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n          //\n          //   tree_table1(curr_term-1,5+k)= m_plus_alph/denom_temp ;\n          //\n          //   num_prod=num_prod*tgamma(m_plus_alph);\n          //   num_sum=num_sum +m_plus_alph ;\n          // }\n          //\n          //\n          // lik_prod= lik_prod*alph_term*num_prod/tgamma(num_sum);\n          //Rcout << \"Line 297.\\n\";\n\n\n        }//End of loop over terminal nodes.\n      }// end of else statement (for when more than one terminal node)\n      // Now have J matrix\n\n      //Rcout << \"Line 4530 .\\n\";\n\n      Wmat=join_rows(Wmat,Jmat);\n      //or\n      //Wmat.insert_cols(Wmat.n_cols,Jmat);\n      //or\n      //int b_j=term_nodes.n_elem;\n      //Wmat.insert_cols(upsilon,Jmat);\n      //upsilon+=b_j;\n\n\n      //Obtain test W_tilde, i.e. W matrix for test data\n\n      W_tilde=join_rows(W_tilde,Jtilde);\n      //or\n      //W_tilde.insert_cols(W_tilde.n_cols,Jtilde);\n      //or\n      //int b_jtest=term_nodes.n_elem;\n      //W_tilde.insert_cols(upsilon2,Jtilde);\n      //upsilon2+=b_jtest;\n\n      //Rcout << \"Line 4551 .\\n\";\n\n      if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n        // //get impportance sampler probability and tree prior\n        // long double temp_samp_prob;\n        // long double temp_prior_prob;\n        // //get sampler tree probability\n        // if(imp_sampler==1){//If sample from BART prior\n        //\n        //\n        //\n        //   temp_samp_prob=1;\n        //\n        //   double depth1=0;\n        //   int prev_node=0; //1 if previous node splits, zero otherwise\n        //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n        //     if(treenodes_bin[i_2]==1){\n        //       temp_samp_prob=temp_samp_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n        //       depth1=depth1+1; //after a split, the depth will increase by 1\n        //       prev_node=1;\n        //     }else{\n        //       temp_samp_prob=temp_samp_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n        //       if(prev_node==1){//zero following a 1, therefore at same depth.\n        //         //Don't change depth. Do nothing\n        //       }else{ //zero following a zero, therefore the depth will decrease by 1\n        //         depth1=depth1-1;\n        //       }\n        //       prev_node=0;\n        //\n        //     }\n        //   }\n        //\n        //   //end of calculating BART tree probability\n        // }else{\n        //   if(imp_sampler==2){//If sample from spike and tree prior\n        //     throw std::range_error(\"code not yet written for spike and tree prior\");\n        //\n        //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n        //     double tempexp1=treenodes_bin.size()-arma::sum(treenodes_bin_arma);\n        //     double tempexp2=arma::sum(treenodes_bin_arma);\n        //     temp_samp_prob=pow(lambda,tempexp2)*\n        //       pow(1-lambda,tempexp1);\n        //       //(1/pow(double(num_split_vars),tempexp2));\n        //\n        //       temp_samp_prob=exp(log(lambda)*tempexp2+\n        //         log(1-lambda)*tempexp1);\n        //\n        //     //temp_samp_prob=pow(lambda,arma::sum(treenodes_bin_arma))*\n        //     //  pow(1-lambda,treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n        //     //  pow((1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n        //   }\n        // }\n        //\n        // sum_tree_samp_prob=sum_tree_samp_prob*temp_samp_prob;\n        // //end of getting importance sampler probability\n        //\n        // //get prior tree probability\n        // if(tree_prior==1){//If sample from BART prior\n        //\n        //\n        //\n        //   temp_prior_prob=1;\n        //\n        //   double depth1=0;\n        //   int prev_node=0; //1 if previous node splits, zero otherwise\n        //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n        //\n        //     if(treenodes_bin[i_2]==1){\n        //       temp_prior_prob=temp_prior_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n        //       depth1=depth1+1; //after a split, the depth will increase by 1\n        //       prev_node=1;\n        //     }else{\n        //       temp_prior_prob=temp_prior_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n        //       if(prev_node==1){//zero following a 1, therefore at same depth.\n        //         //Don't change depth. Do nothing\n        //       }else{ //zero following a zero, therefore the depth will decrease by 1\n        //         depth1=depth1-1;\n        //       }\n        //       prev_node=0;\n        //\n        //     }\n        //     //if(alpha_BART==0){\n        //     //  //Rcout << \"alpha_BART equals zero!!!!.\\n\";\n        //     //}\n        //   }\n        //\n        //   //end of calculating BART tree probability\n        // }else{\n        //   if(tree_prior==2){//If sample from spike and tree prior\n        //     throw std::range_error(\"code not yet written for spike and tree prior\");\n        //\n        //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n        //     temp_prior_prob=pow((long double)(lambda),arma::sum(treenodes_bin_arma))*\n        //       pow((long double)(1-lambda),treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n        //       pow((long double)(1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n        //   }\n        // }\n        //\n        // sum_tree_prior_prob=sum_tree_prior_prob*temp_prior_prob;\n        // if(temp_prior_prob==0){\n        //   Rcout << \"Line 4097, j= \" << j << \". \\n\";\n        //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        // }\n        // if(temp_samp_prob==0){\n        //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n        //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        // }\n        //\n        // if(sum_tree_samp_prob==0){\n        //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n        //   Rcout << \"sum_tree_samp_prob= \" << sum_tree_samp_prob << \". \\n\";\n        //   //Rcout << \"treenodes_bin_arma= \" << treenodes_bin_arma << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        //\n        // }\n\n\n\n\n        //get tree prior over impportance sampler probability\n        double tree_prior_over_samp_prob=1;\n        if(imp_sampler==1){   //If sample from BART prior\n          if(tree_prior==1){  //If tree prior is BART prior\n            /////////////////////////////////////////////////////////////////////////////////////////\n            throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n            /////////////////////////////////////////////////////////////////////////////////////////\n          }else{// not BART prior (and sampler is BART)\n            if(tree_prior==2){  //If tree prior is spike-and-tree prior (and sampler is BART)\n              //throw std::range_error(\"code not yet written for spike and tree prior\");\n              /////////////////////////////////////////////////////////////////////////////////////////\n\n\n              //arma::uvec internal_nodes_prop=find_internal_nodes(tree_table);\n              //arma::mat tree_table2(tree_table.begin(),tree_table.nrow(),tree_table.ncol(),false);\n              //arma::mat arma_tree(treetable.begin(),treetable.nrow(), treetable.ncol(), false);\n              //arma::vec colmat=arma_tree.col(4);\n              //arma::uvec internal_nodes_prop=arma::find(treenodes_bin_arma==1);\n              //internal_nodes_prop=internal_nodes_prop+1;\n\n              //double k_temp=internal_nodes_prop.size()+1;\n              //arma::mat split_var_rows=tree_table2.rows\n\n              //split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n\n\n              arma::vec split_var_vectemp=split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n              double k_temp=split_var_vectemp.size()+1;\n              arma::vec uniquesplitvars=arma::unique(split_var_vectemp);\n              double q_temp=uniquesplitvars.n_elem;\n\n              //FIRST CALCULATE THE log of denom and right_truncatin\n              //Then take the exponential\n              //then take the difference\n              double denom=1;\n              for(int i=0; i<q_temp+1;i++){\n                //denom= denom-(pow(lambda_poisson,double(i))*exp(-lambda_poisson)/double(tgamma(i+1)));\n                denom = denom-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n              }\n              double right_truncation=1;\n              for(int i=0; i<num_obs+1;i++){\n                //right_truncation= right_truncation-(pow(lambda_poisson,double(i))*std::exp(-lambda_poisson)/double(tgamma(i+1)));\n                right_truncation= right_truncation-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n              }\n              //Rcout << \" right_truncation= \" << right_truncation << \".\\n\";\n              denom=denom-right_truncation;\n\n\n              double propsplit;\n\n              if(q_temp==0){\n                if(s_t_hyperprior==1){\n                  propsplit=//(1/double(num_vars+1))*\n                    exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  // tree_prior_over_samp_prob=  propsplit/\n                  //   BART_prior*\n                  //     pow(1/num_vars,arma::sum(treenodes_bin_arma));\n                }else{\n                  propsplit=//(1/double(num_vars+1))*\n                    exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  // tree_prior_over_samp_prob=  propsplit/\n                  //   BART_prior*\n                  //     pow(1/num_vars,arma::sum(treenodes_bin_arma));\n\n                }\n              }else{\n                if(s_t_hyperprior==1){\n                  propsplit=//(1/double(num_vars+1))*\n                    exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                    (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                       -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                       +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                       +std::lgamma(num_obs)\n                       -std::lgamma(k_temp)\n                       -std::lgamma(num_obs-k_temp) ));\n\n                       //(std::lgamma(num_obs)+(k_temp-1-q_temp)*log(q_temp)+\n                       //std::lgamma(q_temp+1)-(std::lgamma(num_obs-k_temp+1))));\n                       //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                       // tree_prior_over_samp_prob=  propsplit/\n                       //   BART_prior*\n                       //     pow(1/num_vars,arma::sum(treenodes_bin_arma));\n                }else{\n                  propsplit=//(1/double(num_vars+1))*\n                    exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                    (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                       -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                       +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                       +std::lgamma(num_obs)\n                       -std::lgamma(k_temp)\n                       -std::lgamma(num_obs-k_temp) ));\n                       //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n\n                       // tree_prior_over_samp_prob=  propsplit/\n                       //   BART_prior*\n                       //     pow(1/num_vars,arma::sum(treenodes_bin_arma));\n                }\n              }\n\n              tree_prior_over_samp_prob=propsplit;\n              //first get BART prior for tree structure\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              //double BART_prior=1;\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob/((alpha_BART*pow(double(depth1+1),-beta_BART)));\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob/((1-alpha_BART*pow(double(depth1+1),-beta_BART)));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }//close (zero node) else stattement\n\n              }//end for loop over i_2\n\n\n\n\n              /////////////////////////////////////////////////////////////////////////////////////////\n            }else{ //prior is Q+H  //(sampler is BART)\n              /////////////////////////////////////////////////////////////////////////////////////////\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*(lambda/(alpha_BART*pow(double(depth1+1),-beta_BART)));\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-lambda)/(1-alpha_BART*pow(double(depth1+1),-beta_BART)));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }\n              }\n              /////////////////////////////////////////////////////////////////////////////////////////\n            }//close Q+H prior (with BART sampler)\n          }//close not BART prior (with BART sampler)\n        }else{// if not sampling from BART sampler\n          if(imp_sampler==2){//If sample from spike and tree prior\n            //throw std::range_error(\"code not yet written for sampling from spike and tree prior\");\n\n            if(tree_prior==1){//prior is BART (sampler is spike and tree)\n              /////////////////////////////////////////////////////////////////////////////////////////\n              //first get BART prior for tree structure\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              double BART_prior=1;\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  BART_prior=BART_prior*((alpha_BART*pow(double(depth1+1),-beta_BART)));\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  BART_prior=BART_prior*((1-alpha_BART*pow(double(depth1+1),-beta_BART)));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }//close (zero node) else stattement\n\n              }//end for loop over i_2\n\n              arma::vec split_var_vectemp=split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n              double k_temp=split_var_vectemp.size()+1;\n              arma::vec uniquesplitvars=arma::unique(split_var_vectemp);\n              double q_temp=uniquesplitvars.n_elem;\n\n              //FIRST CALCULATE THE log of denom and right_truncatin\n              //Then take the exponential\n              //then take the difference\n              double denom=1;\n              for(int i=0; i<q_temp+1;i++){\n                //denom= denom-(pow(lambda_poisson,double(i))*exp(-lambda_poisson)/double(tgamma(i+1)));\n                denom = denom-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n              }\n              double right_truncation=1;\n              for(int i=0; i<num_obs+1;i++){\n                //right_truncation= right_truncation-(pow(lambda_poisson,double(i))*std::exp(-lambda_poisson)/double(tgamma(i+1)));\n                right_truncation= right_truncation-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n              }\n              //Rcout << \" right_truncation= \" << right_truncation << \".\\n\";\n              denom=denom-right_truncation;\n\n              if(q_temp==0){\n                if(s_t_hyperprior==1){\n                  double propsplit=//(1/double(num_vars+1))*\n                    exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  tree_prior_over_samp_prob= BART_prior*\n                    pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n                }else{\n                  double propsplit=//(1/double(num_vars+1))*\n                    exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  tree_prior_over_samp_prob=  BART_prior*\n                    pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                }\n              }else{\n                if(s_t_hyperprior==1){\n                  double propsplit=//(1/double(num_vars+1))*\n                    exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                    (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                       -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                       +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                       +std::lgamma(num_obs)\n                       -std::lgamma(k_temp)\n                       -std::lgamma(num_obs-k_temp) ));\n                       //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                       tree_prior_over_samp_prob=  BART_prior*\n                       pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n                }else{\n                  double propsplit=//(1/double(num_vars+1))*\n                    exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                    (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                       -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                       +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                       +std::lgamma(num_obs)\n                       -std::lgamma(k_temp)\n                       -std::lgamma(num_obs-k_temp) ));\n                       //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n\n                       tree_prior_over_samp_prob=  BART_prior*\n                       pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n                }\n              }\n              /////////////////////////////////////////////////////////////////////////////////////////\n            }else{\n              if(tree_prior==2){//prior is spike and tree, sampler is spike and tree\n                /////////////////////////////////////////////////////////////////////////////////////////\n                throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n                /////////////////////////////////////////////////////////////////////////////////////////\n              }else{//prior is Q+H, sampler is spike and tree\n                /////////////////////////////////////////////////////////////////////////////////////////\n                arma::vec split_var_vectemp=split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n                double k_temp=split_var_vectemp.size()+1;\n                arma::vec uniquesplitvars=arma::unique(split_var_vectemp);\n                double q_temp=uniquesplitvars.n_elem;\n\n                //FIRST CALCULATE THE log of denom and right_truncatin\n                //Then take the exponential\n                //then take the difference\n\n                double denom=1;\n                for(int i=0; i<q_temp+1;i++){\n                  //denom= denom-(pow(lambda_poisson,double(i))*exp(-lambda_poisson)/double(tgamma(i+1)));\n                  denom = denom-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n                }\n                double right_truncation=1;\n                for(int i=0; i<num_obs+1;i++){\n                  //right_truncation= right_truncation-(pow(lambda_poisson,double(i))*std::exp(-lambda_poisson)/double(tgamma(i+1)));\n                  right_truncation= right_truncation-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n                }\n                //Rcout << \" right_truncation= \" << right_truncation << \".\\n\";\n                denom=denom-right_truncation;\n\n                if(q_temp==0){\n                  if(s_t_hyperprior==1){\n                    double propsplit=//(1/double(num_vars+1))*\n                      exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                    //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                    tree_prior_over_samp_prob=  pow(lambda,arma::sum(treenodes_bin_arma))*\n                      pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                      pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                  }else{\n                    double propsplit=//(1/double(num_vars+1))*\n                      exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                    //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                    tree_prior_over_samp_prob=  pow(lambda,arma::sum(treenodes_bin_arma))*\n                      pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                      pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                  }\n\n                }else{\n                  if(s_t_hyperprior==1){\n                    double propsplit=//(1/double(num_vars+1))*\n                      exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                      (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                         -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                         +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                         +std::lgamma(num_obs)\n                         -std::lgamma(k_temp)\n                         -std::lgamma(num_obs-k_temp) ));\n                         //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                         tree_prior_over_samp_prob=  pow(lambda,arma::sum(treenodes_bin_arma))*\n                         pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                         pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                  }else{\n                    double propsplit=//(1/double(num_vars+1))*\n                      exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                      (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                         -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                         +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                         +std::lgamma(num_obs)\n                         -std::lgamma(k_temp)\n                         -std::lgamma(num_obs-k_temp) ));\n\n                         tree_prior_over_samp_prob=  pow(lambda,arma::sum(treenodes_bin_arma))*\n                         pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                         pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                  }\n                }\n                /////////////////////////////////////////////////////////////////////////////////////////\n              }//finish if sampler is spike tree and prior is Q+H\n            }//finish all possibiilities for spike and tree sampler\n\n          }else{//otherwise sampling from Quadrianto and Ghahramani prior\n            if(tree_prior==1){  //If tree prior is BART prior (and sampler is Q+H)\n              /////////////////////////////////////////////////////////////////////////////////////////\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((alpha_BART*pow(double(depth1+1),-beta_BART))/lambda);\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-alpha_BART*pow(double(depth1+1),-beta_BART))/(1-lambda));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }//close (zero node) else stattement\n\n              }//end for loop over i_2\n              /////////////////////////////////////////////////////////////////////////////////////////\n            }else{\n              if(tree_prior==2){  //If tree prior is spike-and-tree prior (and sampler is Q+H)\n                /////////////////////////////////////////////////////////////////////////////////////////\n                //throw std::range_error(\"code not yet written for spike and tree prior\");\n\n                arma::vec split_var_vectemp=split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n                double k_temp=split_var_vectemp.size()+1;\n                arma::vec uniquesplitvars=arma::unique(split_var_vectemp);\n                double q_temp=uniquesplitvars.n_elem;\n\n                //FIRST CALCULATE THE log of denom and right_truncatin\n                //Then take the exponential\n                //then take the difference\n\n                double denom=1;\n                for(int i=0; i<q_temp+1;i++){\n                  //denom= denom-(pow(lambda_poisson,double(i))*exp(-lambda_poisson)/double(tgamma(i+1)));\n                  denom = denom-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n                }\n                double right_truncation=1;\n                for(int i=0; i<num_obs+1;i++){\n                  //right_truncation= right_truncation-(pow(lambda_poisson,double(i))*std::exp(-lambda_poisson)/double(tgamma(i+1)));\n                  right_truncation= right_truncation-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n                }\n                //Rcout << \" right_truncation= \" << right_truncation << \".\\n\";\n                denom=denom-right_truncation;\n\n\n                double propsplit;\n\n                if(q_temp==0){\n                  if(s_t_hyperprior==1){\n                    propsplit=//(1/double(num_vars+1))*\n                      exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                    //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                    // tree_prior_over_samp_prob=  propsplit/\n                    //   (pow(lambda,arma::sum(treenodes_bin_arma))*\n                    //     pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                    //     pow(1/num_vars,arma::sum(treenodes_bin_arma)));\n\n                  }else{\n                    propsplit=//(1/double(num_vars+1))*\n                      exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                    //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                    // tree_prior_over_samp_prob=  propsplit/\n                    //   (pow(lambda,arma::sum(treenodes_bin_arma))*\n                    //     pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                    //     pow(1/num_vars,arma::sum(treenodes_bin_arma)));\n\n                  }\n\n                }else{\n                  if(s_t_hyperprior==1){\n                    propsplit=//(1/double(num_vars+1))*\n                      exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                      (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                         -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                         +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                         +std::lgamma(num_obs)\n                         -std::lgamma(k_temp)\n                         -std::lgamma(num_obs-k_temp) ));\n                         //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                         // tree_prior_over_samp_prob=  propsplit/\n                         //   (pow(lambda,arma::sum(treenodes_bin_arma))*\n                         //     pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                         //     pow(1/num_vars,arma::sum(treenodes_bin_arma)));\n\n                  }else{\n                    propsplit=//(1/double(num_vars+1))*\n                      exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                      (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                         -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                         +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                         +std::lgamma(num_obs)\n                         -std::lgamma(k_temp)\n                         -std::lgamma(num_obs-k_temp) ));\n\n                         // tree_prior_over_samp_prob=  propsplit/\n                         //   (pow(lambda,arma::sum(treenodes_bin_arma))*\n                         //     pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                         //     pow(1/num_vars,arma::sum(treenodes_bin_arma)));\n\n                  }\n                }\n                tree_prior_over_samp_prob=propsplit;\n\n                double depth1=0;\n                int prev_node=0; //1 if previous node splits, zero otherwise\n                for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                  if(treenodes_bin[i_2]==1){\n                    tree_prior_over_samp_prob=tree_prior_over_samp_prob/lambda;\n                    depth1=depth1+1; //after a split, the depth will increase by 1\n                    prev_node=1;\n                  }else{\n                    tree_prior_over_samp_prob=tree_prior_over_samp_prob/(1-lambda);\n                    if(prev_node==1){//zero following a 1, therefore at same depth.\n                      //Don't change depth. Do nothing\n                    }else{ //zero following a zero, therefore the depth will decrease by 1\n                      depth1=depth1-1;\n                    }\n                    prev_node=0;\n\n                  }//close (zero node) else stattement\n\n                }//end for loop over i_2\n\n\n\n\n                /////////////////////////////////////////////////////////////////////////////////////////\n              }else{//if prior is Q+H (and sampler is Q+H)\n                /////////////////////////////////////////////////////////////////////////////////////////\n                throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n                /////////////////////////////////////////////////////////////////////////////////////////\n              }//close (not BART nor spike and tree prior) else statement\n            }// close (not BART prior) else statememt\n\n          }//close all Q+H sampler code (not sampling from BART or spike and tree)  else statement\n\n        }//close (not sampling from BART) else statement\n\n        sum_prior_over_samp_prob=sum_prior_over_samp_prob*tree_prior_over_samp_prob;\n        //end of getting tree prior over impportance sampler probability\n\n        // if(sum_prior_over_samp_prob==0){\n        //   Rcout << \"Line 4266, j= \" << j << \". \\n\";\n        //   Rcout << \"Line 4267, q= \" << q << \". \\n\";\n        //   Rcout << \"sum_prior_over_samp_prob= \" << sum_prior_over_samp_prob << \". \\n\";\n        //\n        // }else{\n        //   Rcout << \"Line 4266, j= \" << j << \". \\n\";\n        //   Rcout << \"Line 4267, q= \" << q << \". \\n\";\n        //   Rcout << \"sum_prior_over_samp_prob= \" << sum_prior_over_samp_prob << \". \\n\";\n        // }\n\n      }//end of tree prior and importance sampler calculations\n\n\n    } //end of loop over trees in sum\n\n\n    //Obtain W matrix. If more than one tree in sum, need to join J matrices, possibly in loop over model trees above\n    // i.e. add a loop from just within the start of the outer loop to here of length equal to the number of trees within the model\n    // Create a Wmat with zero columns at start of loop, and join the Jmat at the end of each loop\n\n    //for now, testing a one-tree model\n    //replace Jmat with Wmat later\n\n\n    //Obtain likelihood\n\n    //Rcout << \"Line 5186 .\\n\";\n\n    double b=Wmat.n_cols;\n\n\n    // CURRENTLY CAN'T OBTAIN COVARIANCE MATRIX WITH FAST APPROXIMATION APPROACH\n    // Perhaps it is possible to obtain the covariance while still using a fast approximaiton\n    // by using a fast SVD algorithm\n\n    // if(fast_approx==1){\n    //   arma::mat p = Wmat.t();\n    //   arma::rowvec r = orig_y_arma.t();\n    //\n    //   arma::mat cov = p * p.t() +a * arma::eye<arma::mat>(p.n_rows, p.n_rows);\n    //\n    //   arma::mat parameters = arma::solve(cov, p * r.t(), arma::solve_opts::fast);\n    //\n    //   arma::rowvec preds_temp_arma_t=arma::trans(parameters) * W_tilde.t();\n    //   arma::rowvec preds_insamp_arma=arma::trans(parameters) * p;\n    //\n    //   arma::vec preds_temp_arma= preds_temp_arma_t.t();\n    //\n    //   arma::vec tempresids=y-preds_insamp_arma.t();\n    //   double temp_sse= arma::dot(tempresids, tempresids);\n    //\n    //   //double templik0=exp(-b*0.5*log(num_obs)+log(temp_sse)*(-num_obs)*0.5);\n    //\n    //\n    //   //double templik0=exp(-b*0.5*log(num_obs)+log(temp_sse)*(-num_obs)*0.5);\n    //\n    //\n    //   //double templik0=exp(-0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs)))  ;\n    //\n    //   double templik0=(num_obs*log(temp_sse/num_obs)+b*log(num_obs))  ;\n    //\n    //   // //Rcout << \"num_obs= \" << num_obs << \". \\n\";\n    //   // //Rcout << \"b= \" << b << \". \\n\";\n    //   // Rcout << \"log(num_obs)= \" << log(num_obs) << \". \\n\";\n    //   // Rcout << \"log(temp_sse/num_obs)= \" << log(temp_sse/num_obs) << \". \\n\";\n    //   //Rcout << \"templik0= \" << templik0 << \". \\n\";\n    //   // Rcout << \"-0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs))= \" << -0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs)) << \". \\n\";\n    //\n    //\n    //   //double templik = pow(templik0,beta_par);\n    //   double templik = beta_par*templik0;\n    //\n    //\n    //   if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n    //     //templik=templik*(sum_tree_prior_prob/sum_tree_samp_prob);\n    //     //templik=templik*sum_prior_over_samp_prob;\n    //     templik=templik+log(sum_prior_over_samp_prob);\n    //\n    //   }\n    //   overall_liks(j)= templik;\n    //\n    //   overall_preds(j)=preds_temp_arma;\n    //\n    // }else{\n\n\n\n      // ///////////////////////////////////\n      //get t(y)inv(psi)J\n      arma::mat ytW=y.t()*Wmat;\n      //get t(J)inv(psi)J\n      arma::mat WtW=Wmat.t()*Wmat;\n      //get jpsij +aI\n      arma::mat aI(b,b);\n      aI=a*aI.eye();\n      arma::mat sec_term=WtW+aI;\n      //arma::mat sec_term_inv=sec_term.i();\n      arma::mat sec_term_inv=inv_sympd(sec_term);\n      //get t(J)inv(psi)y\n      arma::mat third_term=Wmat.t()*y;\n      //get m^TV^{-1}m\n      arma::mat mvm= ytW*sec_term_inv*third_term;\n      //arma::mat rel=(b/2)*log(a)-(1/2)*log(det(sec_term))-expon*log(nu*lambdaBART - mvm +yty);\n      // /////////////////////////////////////////////\n\n\n      //\n      // Rcout << \"-b*0.5*log(num_obs)= \" << -b*0.5*log(num_obs) << \". \\n\";\n      // Rcout << \"log(temp_sse)*(-num_obs)*0.5= \" << log(temp_sse)*(-num_obs)*0.5 << \". \\n\";\n      //\n\n      //double templik0=pow(num_obs, -b*0.5)*pow(temp_sse,-num_obs*0.5);\n\n      //\n      //     arma::vec temppred1=Wmat*sec_term_inv*third_term;\n      //     arma::vec temperrors= y-temppred1;\n      //     arma::vec tempcoeffs= sec_term_inv*third_term;\n      //\n      //     double new_penalty= as_scalar(b*temppred1.t()*temppred1/(tempcoeffs.t()*tempcoeffs*(double(num_obs)-b)));\n      //\n      //     Rcout << \" new_penalty =\" << new_penalty << \".\\n\";\n\n\n      //double val1;\n      //double sign1;\n\n      //log_det(val1, sign1, sec_term);\n      //double templik0=exp(arma::as_scalar((b*0.5)*log(a)-0.5*val1-expon*log(nu*lambdaBART - mvm +yty)));\n\n\n      ////////////////////\n      //double templik0=exp(arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term))-expon*log(nu*lambdaBART - mvm +yty)));\n      //////////////\n      double templik0=arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term))-expon*log(nu*lambdaBART - mvm +yty));\n\n\n\n      //double templik0=exp(arma::as_scalar((b*0.5)*log(a)-0.5*log(det(sec_term))-expon*log(nu*lambdaBART - mvm +yty)));\n\n\n\n\n\n      //\n      //\n      //     arma::mat aI2(b,b);\n      //     aI2=new_penalty*aI2.eye();\n      //     arma::mat sec_term2=WtW+aI2;\n      //     //arma::mat sec_term_inv=sec_term.i();\n      //     arma::mat sec_term_inv2=inv_sympd(sec_term2);\n      //     //get t(J)inv(psi)y\n      //     //arma::mat third_term=Wmat.t()*y;\n      //     //get m^TV^{-1}m\n      //     arma::mat mvm2= ytW*sec_term_inv2*third_term;\n      //\n      //\n      //     double templik0=exp(arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term2))-expon*log(nu*lambdaBART - mvm2 +yty)));\n      //\n\n\n\n\n\n      // Rcout << \"log(temp_sse)= \" << log(temp_sse) << \". \\n\";\n      //\n      //\n      // Rcout << \"temp_sse= \" << temp_sse << \". \\n\";\n      //\n\n\n\n      // Rcout << \"templik0= \" << templik0 << \". \\n\";\n      //\n      //       Rcout << \"b= \" << b << \". \\n\";\n      //       Rcout << \"(b*0.5)*log(a)= \" << (b*0.5)*log(a) << \". \\n\";\n      //\n      //       Rcout << \"-0.5*log(det(sec_term))= \" << -0.5*log(det(sec_term)) << \". \\n\";\n      //       Rcout << \"det(sec_term)= \" << det(sec_term) << \". \\n\";\n      //       Rcout << \"arma::det(sec_term)= \" << arma::det(sec_term) << \". \\n\";\n      //       Rcout << \"arma::log_det(sec_term)= \" << arma::log_det(sec_term) << \". \\n\";\n      //       Rcout << \"real(arma::log_det(sec_term))= \" << real(arma::log_det(sec_term)) << \". \\n\";\n      //       Rcout << \"log(det(sec_term))= \" << log(det(sec_term)) << \". \\n\";\n      //       Rcout << \"log(arma::det(sec_term))= \" << log(arma::det(sec_term)) << \". \\n\";\n      //\n      //       Rcout << \"-expon*log(nu*lambdaBART - mvm +yty)= \" << -expon*log(nu*lambdaBART - mvm +yty) << \". \\n\";\n      //\n      //\n      //       // Rcout << \"val= \" << val << \". \\n\";\n      //\n      // Rcout << \"arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term))-expon*log(nu*lambdaBART - mvm +yty)) .\\n\" << arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term))-expon*log(nu*lambdaBART - mvm +yty)) << \".\\n\";\n      //       ////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n      ////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n      //overall_treetables[j]= wrap(tree_table1);\n\n\n      //double templik = as<double>(treepred_output[1]);\n\n      //double templik = pow(templik0,beta_par);\n\n      double templik = beta_par*templik0;\n\n      if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n        //templik=templik*(sum_tree_prior_prob/sum_tree_samp_prob);\n        //templik=templik*sum_prior_over_samp_prob;\n        templik=templik+log(sum_prior_over_samp_prob);\n\n      }\n      overall_liks(j)= templik;\n\n      // if(std::isnan(templik)){\n      // Rcout << \"Line 3943, j= \" << j << \". \\n\";\n      // Rcout << \"templik= \" << templik << \". \\n\";\n      // Rcout << \"sum_tree_prior_prob= \" << sum_tree_prior_prob << \". \\n\";\n      // Rcout << \"sum_tree_samp_prob= \" << sum_tree_samp_prob << \". \\n\";\n      // }\n\n\n      //now fill in the predictions\n\n      //If want tree tables with predictions filled in, use\n      // arma::vec term_node_par_means = sec_term_inv*third_term;\n      // //and would need to save a field of tree tables,\n      // //add add a column, or begin with one more column\n      // //then the first treetableF[0].n_rows elements of term_node_par_means\n      // //give the first\n      // int row_count1=0;\n      // for(int tree_i=0; tree_i < treetableF.n_elem; tree_i++){\n      //   tabletemp= treetableF(i);\n      //   tabletemp.col(5) = term_node_par_means(arma::span(row_count1,tabletemp.n_rows));\n      //   treetableF(i)=tabletemp;\n      //   row_count1+=tabletemp.n_rows;\n      // }\n      //This would give an alternative method for obtaining test data predictions\n      //Look up the terminal nodes and add the relevant terminal node parameters\n\n\n\n\n      //arma::vec pred_vec(testdata_arma.n_rows);\n\n      ////////////\n      arma::vec preds_temp_arma= W_tilde*sec_term_inv*third_term;\n\n      ////////////////////\n\n\n\n\n\n      //arma::vec preds_temp_arma= W_tilde*sec_term_inv2*third_term;\n\n\n\n      //THIS SHOULD BE DIFFERENT IF THE CODE IS TO BE PARALLELIZED\n      //EACH THREAD SHOULD OUTPUT ITS OWN MATRIX AND SUM OF LIKELIHOODS\n      //THEN ADD THE MATRICES TOGETHER AND DIVIDE BY THE TOTAL SUM OF LIKELIHOODS\n      //OR JUST SAVE ALL MATRICES TO ONE LIST\n\n\n      //pred_mat_overall = pred_mat_overall + templik*pred_mat;\n      //overall_treetables(j)= pred_mat*templik;\n\n\n      //overall_preds(j)=preds_temp_arma*templik;\n\n      overall_preds.col(j)=preds_temp_arma;\n\n\n\n      arma::mat temp_for_scal = ((nu*lambdaBART+yty-mvm)/(nu+num_obs));\n      double temp_scal= as_scalar(temp_for_scal) ;\n      //Rcout << \"Line 4156\";\n      //arma::mat covar_t=temp_scal*(I_test+w_tilde_M_inv*(W_tilde.t()));\n      arma::mat covar_t=temp_scal*(I_test+W_tilde*sec_term_inv*(W_tilde.t()));\n\n      t_vars_arma.col(j)=covar_t.diag();\n\n\n      //Rcout << \"Line 3985, j= \" << j << \". \\n\";\n\n\n      //Rcout << \"preds_temp_arma= \" << preds_temp_arma << \". \\n\";\n      //Rcout << \"preds_temp_arma*templik= \" << preds_temp_arma*templik << \". \\n\";\n\n      //overall_treetables(j)= pred_mat;\n      //overall_liks(j) =templik;\n\n      //arma::mat treeprob_output = get_test_probs(weights, num_cats,\n      //                                           testdata,\n      //                                           treetable_list[i]  );\n\n      //Rcout << \"Line 688. i== \" << i << \". \\n\";\n\n      //double weighttemp = weights[i];\n      //Rcout << \"Line 691. i== \" << i << \". \\n\";\n\n      //pred_mat_overall = pred_mat_overall + weighttemp*treeprob_output;\n\n\n    //}//end of else statement\n  }//end of loop over all trees\n\n}//end of pragma omp code\n\n\n///////////////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////////////////////////////////////////////////////////////\n\n\n//for(unsigned int i=0; i<overall_treetables.n_elem;i++){\n//  pred_mat_overall = pred_mat_overall + overall_liks(i)*overall_treetables(i);\n//}\n\n\n// if(fast_approx==1){\n//   arma::vec BICi=-0.5*overall_liks;\n//   double max_BIC=max(BICi);\n//\n//   // weighted_BIC is actually the posterior model probability\n//   arma::vec weighted_BIC(overall_liks.size());\n//\n//\n//   double tempterm=(max_BIC+log(sum(exp(BICi-max_BIC))));\n//\n//   for(unsigned int k=0;k<overall_liks.size();k++){\n//\n//     //NumericVector BICi=-0.5*BIC_weights;\n//     //double max_BIC=max(BICi);\n//     double weight=exp(BICi[k]-tempterm);\n//     weighted_BIC[k]=weight;\n//     //int num_its_to_sample = round(weight*(num_iter));\n//\n//   }\n//\n//   //Rcout << \"weighted_BIC= \" << weighted_BIC << \". \\n\";\n//   //Rcout << \"overall_liks= \" << overall_liks << \". \\n\";\n//\n// #pragma omp parallel num_threads(ncores)\n// {\n//   arma::vec result_private=arma::zeros<arma::vec>(arma_test_data.n_rows);\n// #pragma omp for nowait //fill result_private in parallel\n//   for(unsigned int i=0; i<overall_preds.size(); i++){\n//     //double weight=exp(BICi[i]-(max_BIC+log(sum(exp(BICi-max_BIC)))));\n//     result_private += overall_preds(i)*weighted_BIC(i);\n//   }\n// #pragma omp critical\n//   pred_vec_overall += result_private;\n// }\n//\n//\n// }else{ //if fast_approx==0\n\n  //arma::vec BICi=-0.5*overall_liks;\n  double max_loglik=max(overall_liks);\n\n  // weighted_BIC is actually the posterior model probability\n  arma::vec weighted_lik(overall_liks.size());\n\n\n  double tempterm=(max_loglik+log(sum(exp(overall_liks-max_loglik))));\n\n  for(unsigned int k=0;k<overall_liks.size();k++){\n\n    //NumericVector BICi=-0.5*BIC_weights;\n    //double max_BIC=max(BICi);\n    double weight=exp(overall_liks[k]-tempterm);\n    weighted_lik[k]=weight;\n    //int num_its_to_sample = round(weight*(num_iter));\n\n  }\n\n  //Rcout << \"weighted_lik= \" << weighted_lik << \". \\n\";\n  //Rcout << \"overall_liks= \" << overall_liks << \". \\n\";\n\n#pragma omp parallel num_threads(ncores)\n{\n  arma::vec result_private=arma::zeros<arma::vec>(arma_test_data.n_rows);\n#pragma omp for nowait //fill result_private in parallel\n  for(unsigned int i=0; i<overall_preds.n_cols; i++) result_private += overall_preds.col(i)*weighted_lik(i);\n#pragma omp critical\n  pred_vec_overall += result_private;\n}\n\n\n//double sumlik_total= arma::sum(overall_liks);\n//Rcout << \"sumlik_total = \" << sumlik_total << \". \\n\";\n\n//pred_vec_overall=pred_vec_overall*(1/sumlik_total);\n\n// } //end else statement\n\n\n//Rcout << \"Line 10842. \\n\";\n\n\n\narma::mat output(3, num_test_obs);\n//NumericVector probs_for_quantiles =  NumericVector::create(lower_prob, 0.5, upper_prob);\n\n//std::vector<double> probs_for_quantiles {lower_prob, 0.5, upper_prob};\n\n\n\ntypedef std::vector<double> stdvec;\n//std::vector<double> weights_vec= as<stdvec>(post_weights);\nstd::vector<double> weights_vec= arma::conv_to<stdvec>::from(weighted_lik);\n\n\nboost::math::students_t dist2(nu+num_obs);\ndouble lq_tstandard= boost::math::quantile(dist2,lower_prob);\ndouble med_tstandard= boost::math::quantile(dist2,0.5); //This is just 0 ??\ndouble uq_tstandard= boost::math::quantile(dist2,upper_prob);\n\n\nif(weights_vec.size()==1){\n#pragma omp parallel num_threads(ncores)\n#pragma omp for\n  for(int i=0;i<num_test_obs;i++){\n    std::vector<double> tempmeans= arma::conv_to<stdvec>::from(overall_preds.row(i));\n    std::vector<double> tempvars= arma::conv_to<stdvec>::from(t_vars_arma.row(i));\n\n    //boost::math::students_t dist2(nu+num_obs);\n\n\n    output(0,i)= tempmeans[0]+sqrt(tempvars[0])*lq_tstandard;\n    output(1,i)= tempmeans[0]+sqrt(tempvars[0])*med_tstandard;\n    output(2,i)= tempmeans[0]+sqrt(tempvars[0])*uq_tstandard;\n\n\n  }\n#pragma omp barrier\n}else{\n#pragma omp parallel num_threads(ncores)\n#pragma omp for\n  for(int i=0;i<num_test_obs;i++){\n    //output(_,i)=Quantile(draws_wrapped(_,i), probs_for_quantiles);\n    std::vector<double> tempmeans= arma::conv_to<stdvec>::from(overall_preds.row(i));\n    std::vector<double> tempvars= arma::conv_to<stdvec>::from(t_vars_arma.row(i));\n\n\n    std::vector<double> bounds_lQ = mixt_find_boundsQ( nu+num_obs, tempmeans, tempvars, lq_tstandard);\n\n    output(0,i)=rootmixt(nu+num_obs,\n           bounds_lQ[0]-0.0001,\n           bounds_lQ[1]+0.0001,\n           tempmeans,\n           tempvars,\n           weights_vec, lower_prob,root_alg_precision);\n\n\n    std::vector<double> bounds_med = mixt_find_boundsQ( nu+num_obs, tempmeans, tempvars, med_tstandard);\n\n    output(1,i)=rootmixt(nu+num_obs,\n           bounds_med[0]-0.0001,\n           bounds_med[1]+0.0001,\n           tempmeans,\n           tempvars,\n           weights_vec, 0.5,root_alg_precision);\n\n    std::vector<double> bounds_uQ = mixt_find_boundsQ( nu+num_obs, tempmeans, tempvars, uq_tstandard);\n\n    output(2,i)=rootmixt(nu+num_obs,\n           bounds_uQ[0]-0.0001,\n           bounds_uQ[1]+0.0001,\n           tempmeans,\n           tempvars,\n           weights_vec, upper_prob,root_alg_precision);\n\n\n  }\n#pragma omp barrier\n}\n\n\n//Rcout << \"Line 10924. \\n\";\n\narma::mat output_rescaled(output.n_rows, output.n_cols);\n\ndouble min_y = min(ytrain);\ndouble max_y = max(ytrain);\n\n#pragma omp parallel num_threads(ncores)\n#pragma omp for\nfor(unsigned int i=0;i<output.n_cols;i++){\n  //output(_,i)=Quantile(draws_wrapped(_,i), probs_for_quantiles);\n\n  output_rescaled.col(i)=get_original_arma(min_y,max_y,-0.5,0.5, output.col(i));\n\n\n}\n#pragma omp barrier\n\n//Rcout << \"Line 10942. \\n\";\n\n\n//double sumlik_total= arma::sum(overall_liks);\n//Rcout << \"sumlik_total = \" << sumlik_total << \". \\n\";\n\n//pred_vec_overall=pred_vec_overall*(1/sumlik_total);\n//Rcout << \"Line 1141 . \\n\";\n//Rcout << \"Line 1146 . \\n\";\n\n\n//Rcout << \"Line 4042. \\n\";\nNumericVector orig_preds=get_original(min(ytrain),max(ytrain),-0.5,0.5,wrap(pred_vec_overall)) ;\n\n//return(orig_preds);\n\n\nList ret(2);\nret[0]= orig_preds;\nret[1]= wrap(output_rescaled);\n\n\nreturn(ret);\n\n}\n//######################################################################################################################//\n\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::depends(dqrng, BH, sitmo)]]\n#include <xoshiro.h>\n#include <dqrng_distribution.h>\n//#include <dqrng.h>\n\n// [[Rcpp::plugins(openmp)]]\n#include <omp.h>\n\n//' @title Parallel Safe-Bayesian Causal Forest\n//'\n//' @description A parallelized implementation of the Safe-Bayesian Random Forest described by Quadrianto and Ghahramani (2015)\n//' @param lambda A real number between 0 and 1 that determines the splitting probability in the prior (which is used as the importance sampler of tree models). Quadrianto and Ghahramani (2015) recommend a value less than 0.5 .\n//' @param num_trees The number of trees to be sampled.\n//' @param seed The seed for random number generation.\n//' @param num_cats The number of possible values for the outcome variable.\n//' @param y The training data vector of outcomes. This must be a vector of integers between 1 and num_cats.\n//' @param original_datamat The original training data. Currently all variables must be continuous. The training data does not need to be transformed before being entered to this function.\n//' @param alpha_parameters Vector of prior parameters.\n//' @param beta_par The power to which the likelihood is to be raised. For BMA, set beta_par=1.\n//' @param original_datamat The original test data. This matrix must have the same number of columns (variables) as the training data. Currently all variables must be continuous. The test data does not need to be transformed before being entered to this function.\n//' @param ncores The number of cores to be used in parallelization.\n//' @return A matrix of probabilities with the number of rows equl to the number of test observations and the number of columns equal to the number of possible outcome categories.\n//' @export\n// [[Rcpp::export]]\nList sBCF_with_ints_parallel(double lambda_mu,\n                                    double lambda_tau,\n                                    int num_models,\n                                    int num_trees_mu,\n                                    int num_trees_tau,\n                                    int seed,\n                                    NumericVector ytrain,\n                                    NumericMatrix original_datamat,\n                                    NumericVector ztrain,\n                                    NumericMatrix pihat_train,\n                                    double beta_par,\n                                    NumericMatrix test_datamat,\n                                    NumericMatrix test_pihat,\n                                    int ncores,\n                                    int outsamppreds,\n                                    double nu,\n                                    double a_mu,\n                                    double a_tau,\n                                    double lambdaBCF,\n                                    int valid_trees,\n                                    int tree_prior,\n                                    int imp_sampler,\n                                    double alpha_BCF_mu,\n                                    double beta_BCF_mu,\n                                    double alpha_BCF_tau,\n                                    double beta_BCF_tau,\n                                    int include_pi2,\n                                    int fast_approx,\n                                    int PIT_propensity,\n                                    double lower_prob,\n                                    double upper_prob,\n                                    double root_alg_precision){\n\n\n  //Check that various input vectors and matrices have consistent dimensions\n\n  //Rcout << \"Line 4528.\\n\";\n\n  bool is_test_data=0;\t\t\t\t\t// create bool is_test_data. Initialize equal to 0.\n  if(test_datamat.nrow()>0){\t\t\t\t\t// If test data has non-zero number of rows.\n    is_test_data=1;\t\t\t\t\t\t// set is_test_data equal to 1.\n  }\n  if(ytrain.size() !=original_datamat.nrow()){\t\t\t\t// If the length of input vector y is not equal to the nunber of rows in the input data (covariates)\n    if(ytrain.size()<original_datamat.nrow()){\t\t\t// If the length of y is less than the number of rows in data\n      throw std::range_error(\"Response length is smaller than the number of observations in the data\");\n    }else{\t\t\t\t\t\t\t\t// If the length of y is greater than the number of rows in data\n      throw std::range_error(\"Response length is greater than the number of observations in the data\");\n    }\n  }\n  if(ztrain.size() !=original_datamat.nrow()){\t\t\t\t// If the length of input vector z is not equal to the nunber of rows in the input data (covariates)\n    if(ztrain.size()<original_datamat.nrow()){\t\t\t// If the length of z is less than the number of rows in data\n      throw std::range_error(\"Treatment indicator vector length is smaller than the number of observations in the data\");\n    }else{\t\t\t\t\t\t\t\t// If the length of z is greater than the number of rows in data\n      throw std::range_error(\"Treatment indicator vector length is greater than the number of observations in the data\");\n    }\n  }\n  if(pihat_train.nrow() !=original_datamat.nrow()){\t\t\t\t// If the nunber of rows in the input matrix pihat is not equal to the nunber of rows in the input data (covariates)\n    if(pihat_train.nrow()<original_datamat.nrow()){\t\t\t// If the nunber of rows in the input matrix pihat is less than the number of rows in data\n      throw std::range_error(\"The nunber of rows in the input matrix pihat_train is smaller than the number of observations in the data\");\n    }else{\t\t\t\t\t\t\t\t// If the nunber of rows in the input matrix pihat is greater than the number of rows in data\n      throw std::range_error(\"The nunber of rows in the input matrix pihat_train is greater than the number of observations in the data\");\n    }\n  }\n  //check test data has the same number of variables as training data\n  if(test_datamat.nrow()>0 && (original_datamat.ncol() != test_datamat.ncol())){\t// If the number of rows in the test data is >0 AND the number of columns (variables) is not equal to that of data (the training data)\n    throw std::range_error(\"Test data and training data must have the same number of variables. BART BMA assumes variables are in the same order.\");\n  }\n  //if(test_z.size() != test_datamat.nrow()){\t// If the number of rows in the test data covariate matrix is not equal to that of the test data treatment indicator variable\n  //  throw std::range_error(\"Test data covariates and test data treatment indicator variable must have the same number of observations.\");\n  //}\n  if(test_datamat.nrow() != test_pihat.nrow()){\t// If the number of rows in the test data covariate matrix is not equal to that of the test data propensity score estimates matrix\n    throw std::range_error(\"Test data covariates and test data propensity score estimates must have the same number of observations.\");\n  }\n  if(test_pihat.nrow()>0 && (pihat_train.ncol() != test_pihat.ncol())){\t// If the number of rows in the test data propensity score estimates is >0 AND the number of columns (variables) is not equal to that of the training data propensity score estimates\n    throw std::range_error(\"Test data propensity score estimates and training data propensity score estimates must have the same number of columns. BART BMA assumes variables are in the same order.\");\n  }\n\n  ///////////////////////////////////////////////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n  // Now add propensity score estimates matrix as new leftmost column of data matrix. Call the resulting matrix x_control (to be consistent with terminology used by bcf package).\n  arma::mat D1(original_datamat.begin(), original_datamat.nrow(), original_datamat.ncol(), false);\t\t\t\t// copy the covariate data matrix into an arma mat\n  arma::mat pihat_1(pihat_train.begin(), pihat_train.nrow(), pihat_train.ncol(), false);\t\t\t\t// copy the pihat matrix into an arma mat\n  //arma::mat x_control_a=D1;\t\t\t\t// create a copy of data arma mat called x_control_a\n\n\n  //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n  arma::mat x_control_a_temp(D1.n_rows,D1.n_cols);\n  for(unsigned int k=0; k<D1.n_cols;k++){\n    arma::vec samp= D1.col(k);\n    arma::vec sv=arma::sort(samp);\n    //std::sort(sv.begin(), sv.end());\n    arma::uvec ord = arma::sort_index(samp);\n    double nobs = samp.n_elem;\n    arma::vec ans(nobs);\n    for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n      int ind=ord(i);\n      double ssampi(samp[ind]);\n      while (sv(j) < ssampi && j < sv.size()) ++j;\n      ans(ind) = j;     // j is the 1-based index of the lower bound\n    }\n    x_control_a_temp.col(k)=(ans+1)/nobs;\n  }\n\n  arma::mat x_control_a=x_control_a_temp;\t\t\t// create arma mat copy of x_control_a_temp.\n\n  arma::mat x_moderate_a=x_control_a_temp;\t\t\t// create arma mat copy of x_control_a_temp.\n\n  arma::mat pihat_a(pihat_1.n_rows,pihat_1.n_cols);\n\n  if(PIT_propensity==1){\n\n    //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n    for(unsigned int k=0; k<pihat_1.n_cols;k++){\n      arma::vec samp= pihat_1.col(k);\n      arma::vec sv=arma::sort(samp);\n      //std::sort(sv.begin(), sv.end());\n      arma::uvec ord = arma::sort_index(samp);\n      double nobs = samp.n_elem;\n      arma::vec ans(nobs);\n      for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n        int ind=ord(i);\n        double ssampi(samp[ind]);\n        while (sv(j) < ssampi && j < sv.size()) ++j;\n        ans(ind) = j;     // j is the 1-based index of the lower bound\n      }\n      pihat_a.col(k)=(ans+1)/nobs;\n    }\n  }else{\n    pihat_a=pihat_1;\n  }\n\n\n\n  if((include_pi2==0) | (include_pi2==2) ){\n    if(pihat_train.nrow()>0 ){\n      x_control_a.insert_cols(0,pihat_a);\t\t// add propensity scores as new leftmost columns of x_control_a\n    }\n  }\n  // Rcout << \"Number of columns of matrix\" << x_control_a.n_cols << \".\\n\";\n\n\n  //NumericMatrix x_control=wrap(x_control_a);\t// convert x_control_a to a NumericMatrix called x_control\n\n  // Name the matrix without the estimated propensity scores x_moderate.[CAN REMOVE THE DUPLICATION AND ADD x_control, x_moderate, and include_pi as input parameters later]\n  //NumericMatrix x_moderate = data;\t// x_moderate matrix is the covariate data without the propensity scores\n  //arma::mat x_moderate_a=D1;\t\t\t// create arma mat copy of x_moderate.\n  if((include_pi2==1)| (include_pi2==2) ){\n    if(pihat_train.nrow()>0 ){\n      x_moderate_a.insert_cols(0,pihat_a);\t\t// add propensity scores as new leftmost columns of x_control_a\n    }\n  }\n\n\n  //NumericMatrix x_moderate=wrap(x_moderate_a);\t// convert x_control_a to a NumericMatrix called x_control\n\n\n  // Rcout << \"Get to Line 7139  \"  << \".\\n\";\n  // Add test propensity scores to test data matrix\n  arma::mat T1(test_datamat.begin(), test_datamat.nrow(), test_datamat.ncol(), false);\t\t\t\t// copy the covariate test_data matrix into an arma mat\n  arma::mat pihat_1_test(test_pihat.begin(), test_pihat.nrow(), test_pihat.ncol(), false);\t\t\t\t// copy the test_pihat matrix into an arma mat\n  //arma::mat x_control_test_a=T1;\t\t\t\t// create a copy of test_data arma mat called x_control_test_a\n\n  arma::mat x_control_test_a(T1.n_rows,T1.n_cols);\n  arma::mat x_moderate_test_a(T1.n_rows,T1.n_cols);\n  arma::mat pihat_a_test(pihat_1_test.n_rows,pihat_1_test.n_cols);\n\n  if(is_test_data==1){\n    //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n    arma::mat x_control_a_test_temp(T1.n_rows,T1.n_cols);\n\n    for(unsigned int k=0; k<T1.n_cols;k++){\n      arma::vec samp= T1.col(k);\n      arma::vec sv=arma::sort(samp);\n      //std::sort(sv.begin(), sv.end());\n      arma::uvec ord = arma::sort_index(samp);\n      double nobs = samp.n_elem;\n      arma::vec ans(nobs);\n      for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n        int ind=ord(i);\n        double ssampi(samp[ind]);\n        while (sv(j) < ssampi && j < sv.size()) ++j;\n        ans(ind) = j;     // j is the 1-based index of the lower bound\n      }\n      x_control_a_test_temp.col(k)=(ans+1)/nobs;\n    }\n\n    arma::mat x_control_test_a=x_control_a_test_temp;\t\t\t// create arma mat copy of x_control_a_temp.\n\n    arma::mat x_moderate_test_a=x_control_a_test_temp;\t\t\t// create arma mat copy of x_control_a_temp.\n\n    if(PIT_propensity==1){\n      //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n      for(unsigned int k=0; k<pihat_1_test.n_cols;k++){\n        arma::vec samp= pihat_1_test.col(k);\n        arma::vec sv=arma::sort(samp);\n        //std::sort(sv.begin(), sv.end());\n        arma::uvec ord = arma::sort_index(samp);\n        double nobs = samp.n_elem;\n        arma::vec ans(nobs);\n        for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n          int ind=ord(i);\n          double ssampi(samp[ind]);\n          while (sv(j) < ssampi && j < sv.size()) ++j;\n          ans(ind) = j;     // j is the 1-based index of the lower bound\n        }\n        pihat_a_test.col(k)=(ans+1)/nobs;\n      }\n    }else{\n      pihat_a_test=pihat_1_test;\n    }\n\n\n  }\n\n\n\n  if((include_pi2==0)| (include_pi2==2) ){\n    if(test_pihat.nrow()>0 ){\n      x_control_test_a.insert_cols(0,pihat_a_test);\t\t// add propensity scores as new leftmost columns of x_control_test_a\n    }\n  }\n\n\n  //NumericMatrix x_control_test=wrap(x_control_test_a);\t// convert x_control_test_a to a NumericMatrix called x_control_test\n\n\n  // Name the matrix without the estimated propensity scores x_moderate_test.[CAN REMOVE THE DUPLICATION AND ADD x_control_test, x_moderate_test, and include_pi as input parameters later]\n  //NumericMatrix x_moderate_test = test_data;\t// x_moderate_test matrix is the covariate test_data without the propensity scores\n  //arma::mat x_moderate_test_a=T1;\t\t\t// create arma mat copy of x_moderate_test.\n  if((include_pi2==1)| (include_pi2==2) ){\n    if(test_pihat.nrow()>0 ){\n      x_moderate_test_a.insert_cols(0,pihat_a_test);\t\t// add propensity scores as new leftmost columns of x_control_a\n    }\n  }\n\n  //NumericMatrix x_moderate_test=wrap(x_moderate_test_a);\t// convert x_control_test_a to a NumericMatrix called x_control_test\n\n\n\n  //////////////////////////////////////////////////////////////////////////////////////////\n  //Rcout << \"Line 4715.\\n\";\n\n  //////////////////////////////////////////////////////////////////////////////////////////\n\n  //End of checks and adding propensity scores to matrices\n\n  NumericVector y_scaled=scale_response(min(ytrain),max(ytrain),-0.5,0.5,ytrain);\n\n  arma::vec z_ar=Rcpp::as<arma::vec>(ztrain);\t\t// converts to arma vec\n\n\n  int num_split_vars_mu= x_control_a.n_cols;\n\n  int num_split_vars_tau= x_moderate_a.n_cols;\n\n\n  //Rcout << \"num_split_vars_mu = \" << num_split_vars_mu << \".\\n\" ;\n  //Rcout << \"num_split_vars_tau = \" << num_split_vars_tau << \".\\n\" ;\n\n  //arma::mat data_arma= as<arma::mat>(original_datamat);\n  //arma::mat testdata_arma= as<arma::mat>(test_datamat);\n\n\n  arma::vec orig_y_arma= as<arma::vec>(y_scaled);\n  //arma::vec alpha_pars_arma= as<arma::vec>(alpha_parameters);\n  int num_obs = x_control_a.n_rows;\n  int num_test_obs = x_control_test_a.n_rows;\n\n\n  //calculations for likelihood\n  arma::mat y(num_obs,1);\n  y.col(0)=orig_y_arma;\n  //get exponent\n  double expon=(num_obs+nu)*0.5;\n  //get y^Tpsi^{-1}y\n  // arma::mat psi_inv=psi.i();\n  arma::mat yty=y.t()*y;\n\n\n\n\n\n\n\n  /////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n  //////////////////////////////////////////////////////////////////////////////////////\n  //List table_list = draw_trees(lambda, num_trees, seed, num_split_vars, num_cats );\n\n\n\n  //dqrng::dqRNGkind(\"Xoroshiro128+\");\n  //dqrng::dqset_seed(IntegerVector::create(seed));\n\n  //use following with binomial?\n  //dqrng::xoshiro256plus rng(seed);\n\n  std::vector<double> lambdavec_mu = {lambda_mu, 1-lambda_mu};\n  std::vector<double> lambdavec_tau = {lambda_tau, 1-lambda_tau};\n\n  //typedef boost::mt19937 RNGType;\n  //boost::random::uniform_int_distribution<> sample_splitvardist(1,num_split_vars);\n  //boost::variate_generator< RNGType, boost::uniform_int<> >  sample_splitvars(rng, sample_splitvardist);\n\n  //boost::random::uniform_real_distribution<double> b_unifdist(0,1);\n  //boost::variate_generator< RNGType, boost::uniform_real<> >  b_unif_point(rng, b_unifdist);\n\n\n\n  std::random_device device;\n  //std::mt19937 gen(device());\n\n  //possibly use seed?\n  //// std::mt19937 gen(seed);\n\n  dqrng::xoshiro256plus gen(device());              // properly seeded rng\n\n  //dqrng::xoshiro256plus gen(seed);              // properly seeded rng\n\n\n\n\n  std::bernoulli_distribution coin_flip_mu(lambda_mu);\n  std::bernoulli_distribution coin_flip_tau(lambda_tau);\n\n  std::uniform_int_distribution<> distsampvar_mu(1, num_split_vars_mu);\n  std::uniform_int_distribution<> distsampvar_tau(1, num_split_vars_tau);\n\n  std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n\n  //dqrng::uniform_distribution dis_cont_unif(0.0, 1.0); // Uniform distribution [0,1)\n\n  //Following three functions can't be used in parallel\n  //dqrng::dqsample_int coin_flip2(2, 1, true,lambdavec );\n  //dqrng::dqsample_int distsampvar(num_split_vars, 1, true);\n  //dqrng::dqrunif dis_cont_unif(1, 0, 1);\n\n\n\n  //arma::mat arma_test_data(testdat_trans.begin(), testdat_trans.nrow(), testdat_trans.ncol(), false);\n\n\n  arma::vec pred_vec_overall;\n  arma::vec pred_vec_overall_mu;\n  arma::vec pred_vec_overall_y;\n\n  if(is_test_data==1){\n    pred_vec_overall=arma::zeros<arma::vec>(x_moderate_test_a.n_rows);\n  }else{\n    pred_vec_overall=arma::zeros<arma::vec>(x_moderate_a.n_rows);\n    pred_vec_overall_mu=arma::zeros<arma::vec>(x_moderate_a.n_rows);\n    pred_vec_overall_y=arma::zeros<arma::vec>(x_moderate_a.n_rows);\n\n  }\n\n  //arma::field<arma::mat> overall_treetables(num_models);\n\n  //arma::field<arma::vec> overall_preds(num_models);\n\n  arma::mat overall_preds;\n  if(is_test_data==1){\n    overall_preds= arma::zeros<arma::mat>(num_test_obs,num_models);\n  }else{\n    overall_preds= arma::zeros<arma::mat>(num_obs,num_models);\n  }\n\n  //arma::field<arma::vec> overall_preds_mu(num_models);\n  //arma::field<arma::vec> overall_preds_y(num_models);\n\n\n  arma::mat t_vars_arma;\n  if(is_test_data==1){\n    t_vars_arma= arma::zeros<arma::mat>(num_test_obs,num_models);\n  }else{\n    t_vars_arma= arma::zeros<arma::mat>(num_obs,num_models);\n  }\n\n\n\n  // arma::mat overall_preds(x_moderate_a.n_rows, num_models);\n  // arma::mat overall_preds_mu(x_moderate_a.n_rows, num_models);\n  // arma::mat overall_preds_y(x_moderate_a.n_rows, num_models);\n\n  arma::vec overall_liks(num_models);\n\n\n  arma::vec cate_means_arma(num_models);\n  arma::vec cate_vars_arma(num_models);\n\n  arma::vec averagingvec=(1/double(num_obs))*arma::ones<arma::vec>(num_obs);\n\n  //overall_treetables[i]= wrap(tree_table1);\n  //double templik = as<double>(treepred_output[1]);\n  //overall_liks[i]= pow(lik_prod,beta_pow);\n\n  //Rcout << \"Line 3338. \\n\";\n\n  //Rcout << \"Line 4836.\\n\";\n\n#pragma omp parallel num_threads(ncores)\n{//start of pragma omp code\n  dqrng::xoshiro256plus lgen(gen);      // make thread local copy of rng\n  lgen.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... ncores jumps\n\n#pragma omp for\n  for(int j=0; j<num_models;j++){\n\n    arma::mat Wmat_mu(num_obs,0);\n    arma::mat Wmat_tau(num_obs,0);\n\n    //maybe use line below, depends how Jmat joined to Wmat\n    //int upsilon=0;\n\n    arma::mat W_tilde_mu(num_test_obs,0);\n    arma::mat W_tilde_tau(num_test_obs,0);\n\n    //maybe use line below, depends how Jmat joined to Wmat\n    //int upsilon2=0;\n\n    //double sum_tree_samp_prob=1;\n    //double sum_tree_prior_prob=1;\n\n    double sum_prior_over_samp_prob=1;\n\n    for(int q=0; q<num_trees_mu;q++){  //start of loop over trees in sum\n\n\n      //If parallelizing, define the distributinos before this loop\n      //and use lrng and the following two lines\n      //dqrng::xoshiro256plus lrng(rng);      // make thread local copy of rng\n      //lrng.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... nthreads jumps\n\n\n      //NumericVector treenodes_bin(0);\n      //arma::uvec treenodes_bin(0);\n\n      std::vector<int> treenodes_bin;\n\n\n      int count_terminals = 0;\n      int count_internals = 0;\n\n      //int count_treebuild = 0;\n\n\n      if(imp_sampler==1){ //If sampling from BART prior\n\n        double depth1=0;\n        int prev_node=0; //1 if previous node splits, zero otherwise\n\n        double samp_prob;\n\n        while(count_internals > (count_terminals -1)){\n          samp_prob=alpha_BCF_mu*pow(double(depth1+1),-beta_BCF_mu);\n          std::bernoulli_distribution coin_flip2(samp_prob);\n\n          int tempdraw = coin_flip2(lgen);\n          treenodes_bin.push_back(tempdraw);\n\n          if(tempdraw==1){\n\n            depth1=depth1+1; //after a split, the depth will increase by 1\n            prev_node=1;\n            count_internals=count_internals+1;\n\n          }else{\n\n            if(prev_node==1){//zero following a 1, therefore at same depth.\n              //Don't change depth. Do nothing\n            }else{ //zero following a zero, therefore the depth will decrease by 1\n              depth1=depth1-1;\n            }\n            prev_node=0;\n            count_terminals=count_terminals+1;\n\n          }\n\n        }\n\n      }else{  //If not sampling from BAT prior\n        if(imp_sampler==2){//If sampling from spike and tree prior\n          throw std::range_error(\"code not yet written for spike and tree sampling\");\n\n        }else{//If sampling from default Q+G prior. i.e. not sampling from BART nor spike and tree prior\n\n          while(count_internals > (count_terminals -1)){\n\n            //Also consider standard library and random header\n            // std::random_device device;\n            // std::mt19937 gen(device());\n            // std::bernoulli_distribution coin_flip(lambda);\n            // bool outcome = coin_flip(gen);\n\n\n            int tempdraw = coin_flip_mu(lgen);\n\n            //int tempdraw = rbinom(n = 1, prob = lambda,size=1);\n\n\n            //int tempdraw = Rcpp::rbinom(1,lambda,1);\n            //int tempdraw = R::rbinom(1,lambda);\n\n            ////Rcout << \"tempdraw = \" << tempdraw << \".\\n\" ;\n\n            //int tempdraw = coin_flip2(lgen)-1;\n\n            //int tempdraw = dqrng::dqsample_int(2, 1, true,lambdavec )-1;\n\n\n            //need to update rng if use boost?\n            //int tempdraw = bernoulli(rng, binomial::param_type(1, lambda));\n\n            treenodes_bin.push_back(tempdraw);\n\n\n            if(tempdraw==1){\n              count_internals=count_internals+1;\n            }else{\n              count_terminals=count_terminals+1;\n            }\n\n          }//end of while loop creating parent vector treenodes_bin\n        }\n\n      }\n\n\n\n      //Consider making this an armadillo vector\n      //IntegerVector split_var_vec(treenodes_bin.size());\n      //arma::uvec split_var_vec(treenodes_bin.size());\n      std::vector<int> split_var_vec(treenodes_bin.size());\n\n      //loop drawing splitting variables\n      //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n      //if using armadillo, it might be faster to subset to split nodes\n      //then use a vector of draws\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        if(treenodes_bin[i]==0){\n          split_var_vec[i] = -1;\n        }else{\n          // also consider the standard library function uniform_int_distribution\n          // might need random header\n          // This uses the Mersenne twister\n\n          //Three lines below should probably be outside all the loops\n          // std::random_device rd;\n          // std::mt19937 engine(rd());\n          // std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n          //\n          // split_var_vec[i] = distsampvar(engine);\n\n          split_var_vec[i] = distsampvar_mu(lgen);\n\n\n          //consider using boost\n          //might need to update rng\n          //split_var_vec[i] <- sample_splitvars(rng);\n\n          //or use dqrng\n          //not sure if have to update the random number\n          //check if the following line is written properly\n          //split_var_vec[i] = dqrng::dqsample_int(num_split_vars, 1, true);\n\n          //not sure if this returns an integer or a vector?\n          //split_var_vec[i] = RcppArmadillo::sample(num_split_vars, 1,true);\n          //could try\n          //split_var_vec[i] = as<int>(Rcpp::sample(num_split_vars, 1,true));\n          //could also try RcppArmadillo::rmultinom\n\n        }\n\n      }// end of for-loop drawing split variables\n\n\n      //Consider making this an armadillo vector\n      //NumericVector split_point_vec(treenodes_bin.size());\n      //arma::vec split_point_vec(treenodes_bin.size());\n      std::vector<double> split_point_vec(treenodes_bin.size());\n\n\n      //loop drawing splitting points\n      //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n      //if using armadillo, it might be faster to subset to split nodes\n      //then use a vector of draws\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        if(treenodes_bin[i]==0){\n          split_point_vec[i] = -1;\n        }else{\n\n\n          //////////////////////////////////////////////////////////\n          //following function not reccommended\n          //split_point_vec[i] = std::rand();\n          //////////////////////////////////////////////////////////\n          ////Standard library:\n          ////This should probably be outside all the loops\n          ////std::random_device rd;  //Will be used to obtain a seed for the random number engine\n          ////std::mt19937 gen2(rd()); //Standard mersenne_twister_engine seeded with rd()\n          ////std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n          split_point_vec[i] = dis_cont_unif(lgen);\n\n          //////////////////////////////////////////////////////////\n          //from armadillo\n          //split_point_vec[i] = arma::randu();\n\n          //////////////////////////////////////////////////////////\n          //probably not adviseable for paralelization\n          //From Rcpp\n          //split_point_vec[i] = as<double>(Rcpp::runif(1,0,1));\n\n          //////////////////////////////////////////////////////////\n          //consider using boost\n          //might need to update rng\n          //split_point_vec[i] <- b_unif_point(rng);\n\n          //or use dqrng\n          //not sure if have to update the random number\n          //check if the following line is written properly\n          //split_point_vec[i] = dqrng::dqrunif(1, 0, 1);\n\n          //not sure if this returns an integer or a vector?\n\n\n\n\n\n        }\n\n      }// end of for-loop drawing split points\n\n\n\n\n\n      //CODE FOR ADJUSTING SPLITTING POINTS SO THAT THE TREES ARE VALID\n      if(valid_trees==1){\n        for(unsigned int i=0; i<treenodes_bin.size();i++){ //loop over all nodes\n          if(treenodes_bin[i]==1){ // if it is an internal node, then check for further splits on the same variable and update\n            double first_split_var=split_var_vec[i];      //splitting variable to check for\n            double first_split_point=split_point_vec[i];  //splitting point to use in updates\n\n            double sub_int_nodes=0;       //this internal node count will be used to determine if in subtree relevant to sub_int_nodes\n            double sub_term_nodes=0;      //this terminal node count will be used to determine if in subtree relevant to sub_int_nodes\n            double preventing_updates=0; //indicates if still within subtree that is not to be updated\n            double prevent_int_count=0;   //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n            double prevent_term_count=0;  //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n            for(unsigned int k=i+1; k<treenodes_bin.size();k++){\n              if(treenodes_bin[k]==1){\n                sub_int_nodes=sub_int_nodes+1;\n                if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                  prevent_int_count=prevent_int_count+1;\n                }\n              }else{\n                sub_term_nodes=sub_term_nodes+1;\n                if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                  prevent_term_count=prevent_term_count+1;\n                }\n              }\n              if(sub_int_nodes<=sub_term_nodes-2){\n                break;\n              }\n\n\n              if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                if(prevent_int_count>prevent_term_count-1){ //if this rule is satisfied then in subtree that is not to be updated\n                  continue; //still in subtree, therefore continue instead of checking for splits to be updates\n                }else{\n                  preventing_updates=0; // no longer in subtree, therefore reset preventing_updates to zero\n                }\n              }\n\n\n              if(sub_int_nodes>sub_term_nodes-1){\n                if(treenodes_bin[k]==1){\n                  if(split_var_vec[k]==first_split_var){\n                    split_point_vec[k]=split_point_vec[k]*first_split_point;\n                    //beginning count of subtree that should not have\n                    //further splits on first_split_var updated\n                    preventing_updates=1; //indicates if still within subtree that is not to be updated\n                    prevent_int_count=1;\n                    prevent_term_count=0;\n                  }\n                }\n              }else{\n                if(treenodes_bin[k]==1){\n                  if(split_var_vec[k]==first_split_var){\n                    split_point_vec[k]=split_point_vec[k]+first_split_point-first_split_point*split_point_vec[k];\n                    //beginning count of subtree that should not have\n                    //further splits on first_split_var updated\n                    preventing_updates=1; //indicates if still within subtree that is not to be updated\n                    prevent_int_count=1;\n                    prevent_term_count=0;\n                  }\n                }\n              }\n\n\n\n            }//end of inner loop over k\n          }//end of if statement treenodes_bin[i]==1)\n        }//end of loop over i\n      }//end of if statement valid_trees==1\n\n\n\n\n\n      //Rcout << \"Line 5150.\\n\";\n\n\n\n\n\n      //Create tree table matrix\n\n      //NumericMatrix tree_table1(treenodes_bin.size(),5+num_cats);\n\n      //Rcout << \"Line 1037. \\n\";\n      //arma::mat tree_table1(treenodes_bin.size(),5+num_cats);\n\n      //initialize with zeros. Not sure if this is necessary\n      arma::mat tree_table1=arma::zeros<arma::mat>(treenodes_bin.size(),6);\n      //Rcout << \"Line 1040. \\n\";\n\n\n      //tree_table1(_,2) = wrap(split_var_vec);\n      //tree_table1(_,3) = wrap(split_point_vec);\n      //tree_table1(_,4) = wrap(treenodes_bin);\n\n      //It might be more efficient to make everything an armadillo object initially\n      // but then would need to replace push_back etc with a different approach (but this might be more efficient anyway)\n      arma::colvec split_var_vec_arma=arma::conv_to<arma::colvec>::from(split_var_vec);\n      arma::colvec split_point_vec_arma(split_point_vec);\n      arma::colvec treenodes_bin_arma=arma::conv_to<arma::colvec>::from(treenodes_bin);\n\n\n      //Rcout << \"Line 1054. \\n\";\n\n      //Fill in splitting variable column\n      tree_table1.col(2) = split_var_vec_arma;\n      //Fill in splitting point column\n      tree_table1.col(3) = split_point_vec_arma;\n      //Fill in split/parent column\n      tree_table1.col(4) = treenodes_bin_arma;\n\n\n      //Rcout << \"Line 5189. j = \" << j << \". \\n\";\n      //Rcout << \"Line 5190. tree_table1 mu = \" << tree_table1 << \". \\n\";\n\n\n\n      // Now start filling in left daughter and right daughter columns\n      std::vector<int> rd_spaces;\n      int prev_node = -1;\n\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        //Rcout << \"Line 1061. i = \" << i << \". \\n\";\n        if(prev_node==0){\n          //tree_table1(rd_spaces[rd_spaces.size()-1], 1)=i;\n          //Rcout << \"Line 1073. j = \" << j << \". \\n\";\n\n          tree_table1(rd_spaces.back(), 1)=i+1;\n          //Rcout << \"Line 1076. j = \" << j << \". \\n\";\n\n          rd_spaces.pop_back();\n        }\n        if(treenodes_bin[i]==1){\n          //Rcout << \"Line 1081. j = \" << j << \". \\n\";\n\n          tree_table1(i,0) = i+2;\n          rd_spaces.push_back(i);\n          prev_node = 1;\n          //Rcout << \"Line 185. j = \" << j << \". \\n\";\n\n        }else{                  // These 2 lines unnecessary if begin with matrix of zeros\n          //Rcout << \"Line 1089. j = \" << j << \". \\n\";\n          tree_table1(i,0)=0 ;\n          tree_table1(i,1) = 0 ;\n          prev_node = 0;\n          //Rcout << \"Line 1093. j = \" << j << \". \\n\";\n\n        }\n      }//\n      //Rcout << \"Line 1097. j = \" << j << \". \\n\";\n\n\n\n\n\n      //List treepred_output = get_treepreds(original_y, num_cats, alpha_pars,\n      //                                     originaldata,\n      //                                     treetable_list[i]  );\n\n\n      //use armadillo object tree_table1\n\n      ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n      ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n      //create variables for likelihood calcuations\n      // double lik_prod=1;\n      // double alph_prod=1;\n      // for(unsigned int i=0; i<alpha_pars_arma.n_elem;i++){\n      //   alph_prod=alph_prod*tgamma(alpha_pars_arma(i));\n      // }\n      // double gam_alph_sum= tgamma(arma::sum(alpha_pars_arma));\n      // double alph_term=gam_alph_sum/alph_prod;\n\n      //arma::mat arma_tree_table(treetable.begin(), treetable.nrow(), treetable.ncol(), false);\n      //arma::mat arma_orig_data(originaldata.begin(), originaldata.nrow(), originaldata.ncol(), false);\n\n\n      //arma::mat arma_tree(tree_data.begin(), tree_data.nrow(), tree_data.ncol(), false);\n      //arma::mat testd(test_data.begin(), test_data.nrow(), test_data.ncol(), false);\n\n      //NumericVector internal_nodes=find_internal_nodes_gs(tree_data);\n\n      //NumericVector terminal_nodes=find_term_nodes(treetable);\n\n      //arma::mat arma_tree(tree_table.begin(),tree_table.nrow(), tree_table.ncol(), false);\n\n      //arma::vec colmat=arma_tree.col(4);\n      //arma::uvec term_nodes=arma::find(colmat==-1);\n\n      //arma::vec colmat=arma_tree.col(2);\n      //arma::uvec term_nodes=arma::find(colmat==0);\n\n      //arma::vec colmat=tree_table1.col(4);\n      //arma::uvec term_nodes=arma::find(colmat==0);\n\n      //4th column is treenodes_bin_arma\n      arma::uvec term_nodes=arma::find(treenodes_bin_arma==0);\n\n      term_nodes=term_nodes+1;\n\n      //NumericVector terminal_nodes= wrap(term_nodes);\n\n\n      //Rcout << \"Line 5282.\\n\";\n\n      //GET J MATRIX\n\n      arma::mat Jmat(num_obs,term_nodes.n_elem);\n      arma::mat Jtilde(num_test_obs,term_nodes.n_elem);\n\n      //arma::vec arma_terminal_nodes=Rcpp::as<arma::vec>(terminal_nodes);\n      //NumericVector tree_predictions;\n\n      //now for each internal node find the observations that belong to the terminal nodes\n\n      //NumericVector predictions(test_data.nrow());\n      //List term_obs(term_nodes.n_elem);\n\n      //GET J MATRIX\n\n      if(term_nodes.n_elem==1){\n        //double nodemean=tree_data(terminal_nodes[0]-1,5);\t\t\t\t// let nodemean equal tree_data row terminal_nodes[i]^th row , 6th column. The minus 1 is because terminal nodes consists of indices starting at 1, but need indices to start at 0.\n        //predictions=rep(nodemean,test_data.nrow());\n        //Rcout << \"Line 67 .\\n\";\n\n        //IntegerVector temp_obsvec = seq_len(test_data.nrow())-1;\n        //term_obs[0]= temp_obsvec;\n        //double denom_temp= orig_y_arma.n_elem+arma::sum(alpha_pars_arma);\n\n        //double num_prod=1;\n        //double num_sum=0;\n        //Rcout << \"Line 129.\\n\";\n        Jmat.col(0) = arma::ones<arma::vec>(num_obs);\n\n        if(is_test_data==1){\n          Jtilde.col(0) = arma::ones<arma::vec>(num_test_obs);\n        }\n\n        //for(int k=0; k<num_cats; k++){\n        //assuming categories of y are from 1 to num_cats\n        //arma::uvec cat_inds= arma::find(orig_y_arma==k+1);\n        //double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n        //tree_table1(0,5+k)= m_plus_alph/denom_temp ;\n\n        //for likelihood calculation\n        //num_prod=num_prod*tgamma(m_plus_alph);\n        //num_sum=num_sum +m_plus_alph ;\n        //}\n\n        //lik_prod= alph_term*num_prod/tgamma(num_sum);\n\n      }\n      else{\n        for(unsigned int i=0;i<term_nodes.n_elem;i++){\n          //arma::mat subdata=testd;\n          //int curr_term=term_nodes(i);\n\n          int row_index;\n          int term_node=term_nodes(i);\n          //Rcout << \"Line 152.\\n\";\n\n\n          //WHAT IS THE PURPOSE OF THIS IF-STATEMENT?\n          //Why should the ro index be different for a right daughter?\n          //Why not just initialize row_index to any number not equal to 1 (e.g. 0)?\n          row_index=0;\n\n          // if(curr_term % 2==0){\n          //   //term node is left daughter\n          //   row_index=terminal_nodes[i];\n          // }else{\n          //   //term node is right daughter\n          //   row_index=terminal_nodes[i]-1;\n          // }\n\n\n\n\n          //save the left and right node data into arma uvec\n\n          //CHECK THAT THIS REFERS TO THE CORRECT COLUMNS\n          //arma::vec left_nodes=arma_tree.col(0);\n          //arma::vec right_nodes=arma_tree.col(1);\n\n          arma::vec left_nodes=tree_table1.col(0);\n          arma::vec right_nodes=tree_table1.col(1);\n\n\n\n          arma::mat node_split_mat;\n          node_split_mat.set_size(0,3);\n          //Rcout << \"Line 182. i = \" << i << \" .\\n\";\n\n          while(row_index!=1){\n            //for each terminal node work backwards and see if the parent node was a left or right node\n            //append split info to a matrix\n            int rd=0;\n            arma::uvec parent_node=arma::find(left_nodes == term_node);\n\n            if(parent_node.size()==0){\n              parent_node=arma::find(right_nodes == term_node);\n              rd=1;\n            }\n\n            //want to cout parent node and append to node_split_mat\n\n            node_split_mat.insert_rows(0,1);\n\n            //CHECK THAT COLUMNS OF TREETABLE ARE CORRECT\n            //node_split_mat(0,0)=treetable(parent_node[0],2);\n            //node_split_mat(0,1)=treetable(parent_node[0],3);\n\n            //node_split_mat(0,0)=arma_tree_table(parent_node[0],3);\n            //node_split_mat(0,1)=arma_tree_table(parent_node[0],4);\n\n            node_split_mat(0,0)=tree_table1(parent_node(0),2);\n            node_split_mat(0,1)=tree_table1(parent_node(0),3);\n\n            node_split_mat(0,2)=rd;\n            row_index=parent_node(0)+1;\n            term_node=parent_node(0)+1;\n          }\n\n          //once we have the split info, loop through rows and find the subset indexes for that terminal node!\n          //then fill in the predicted value for that tree\n          //double prediction = tree_data(term_node,5);\n          arma::uvec pred_indices;\n          arma::uvec pred_test_indices;\n          int split= node_split_mat(0,0)-1;\n\n          //Rcout << \"Line 224.\\n\";\n          //Rcout << \"split = \" << split << \".\\n\";\n          //arma::vec tempvec = testd.col(split);\n          arma::vec tempvec = x_control_a.col(split);\n          //Rcout << \"Line 227.\\n\";\n\n\n          double temp_split = node_split_mat(0,1);\n\n          if(node_split_mat(0,2)==0){\n            pred_indices = arma::find(tempvec <= temp_split);\n          }else{\n            pred_indices = arma::find(tempvec > temp_split);\n          }\n\n          if(is_test_data==1){\n            arma::vec temptest_vec = x_control_test_a.col(split);\n\n            if(node_split_mat(0,2)==0){\n              pred_test_indices = arma::find(temptest_vec <= temp_split);\n            }else{\n              pred_test_indices = arma::find(temptest_vec > temp_split);\n            }\n          }\n\n\n          //Rcout << \"Line 236.\\n\";\n\n          arma::uvec temp_pred_indices;\n          arma::uvec temp_test_pred_indices;\n\n          //arma::vec data_subset = testd.col(split);\n          arma::vec data_subset = x_control_a.col(split);\n          data_subset=data_subset.elem(pred_indices);\n\n          arma::vec data_test_subset;\n          if(is_test_data==1){\n            data_test_subset =x_control_test_a.col(split);\n            data_test_subset=data_test_subset.elem(pred_test_indices);\n          }\n\n          //now loop through each row of node_split_mat\n          int n=node_split_mat.n_rows;\n          //Rcout << \"Line 174. i = \" << i << \". n = \" << n << \".\\n\";\n          //Rcout << \"Line 248.\\n\";\n\n          for(int j=1;j<n;j++){\n            int curr_sv=node_split_mat(j,0);\n            double split_p = node_split_mat(j,1);\n\n            //data_subset = testd.col(curr_sv-1);\n            //Rcout << \"Line 255.\\n\";\n            //Rcout << \"curr_sv = \" << curr_sv << \".\\n\";\n            data_subset = x_control_a.col(curr_sv-1);\n            //Rcout << \"Line 258.\\n\";\n\n            data_subset=data_subset.elem(pred_indices);\n\n\n            if(node_split_mat(j,2)==0){\n              //split is to the left\n              temp_pred_indices=arma::find(data_subset <= split_p);\n            }else{\n              //split is to the right\n              temp_pred_indices=arma::find(data_subset > split_p);\n            }\n            pred_indices=pred_indices.elem(temp_pred_indices);\n\n\n            if(is_test_data==1){\n              data_test_subset = x_control_test_a.col(curr_sv-1);\n              data_test_subset=data_test_subset.elem(pred_test_indices);\n\n              if(node_split_mat(j,2)==0){\n                //split is to the left\n                temp_test_pred_indices=arma::find(data_test_subset <= split_p);\n              }else{\n                //split is to the right\n                temp_test_pred_indices=arma::find(data_test_subset > split_p);\n              }\n              pred_test_indices=pred_test_indices.elem(temp_test_pred_indices);\n\n            }\n\n\n            //if(pred_indices.size()==0){\n            //  continue;\n            //}\n\n          }\n          //Rcout << \"Line 199. i = \" << i <<  \".\\n\";\n\n          //There is probably a more efficient way of doing this\n          //e.g. initialize J matrix so that all elements are equal to zero\n          arma::vec tempcol_J=arma::zeros<arma::vec>(num_obs);\n          tempcol_J(pred_indices) = arma::ones<arma::vec>(pred_indices.size());\n          Jmat.col(i) = tempcol_J;\n\n          if(is_test_data==1){\n            arma::vec tempcol_Jtilde=arma::zeros<arma::vec>(num_test_obs);\n            tempcol_Jtilde(pred_test_indices) = arma::ones<arma::vec>(pred_test_indices.size());\n            Jtilde.col(i) = tempcol_Jtilde;\n          }\n\n          //double nodemean=tree_data(terminal_nodes[i]-1,5);\n          //IntegerVector predind=as<IntegerVector>(wrap(pred_indices));\n          //predictions[predind]= nodemean;\n          //term_obs[i]=predind;\n\n          //double denom_temp= pred_indices.n_elem+arma::sum(alpha_pars_arma);\n          //Rcout << \"Line 207. predind = \" << predind <<  \".\\n\";\n          //Rcout << \"Line 207. denom_temp = \" << denom_temp <<  \".\\n\";\n          // << \"Line 207. term_node = \" << term_node <<  \".\\n\";\n\n          //double num_prod=1;\n          //double num_sum=0;\n\n          // for(int k=0; k<num_cats; k++){\n          //   //assuming categories of y are from 1 to num_cats\n          //   arma::uvec cat_inds= arma::find(orig_y_arma(pred_indices)==k+1);\n          //   double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n          //\n          //   tree_table1(curr_term-1,5+k)= m_plus_alph/denom_temp ;\n          //\n          //   num_prod=num_prod*tgamma(m_plus_alph);\n          //   num_sum=num_sum +m_plus_alph ;\n          // }\n          //\n          //\n          // lik_prod= lik_prod*alph_term*num_prod/tgamma(num_sum);\n          //Rcout << \"Line 297.\\n\";\n\n\n        }//End of loop over terminal nodes.\n      }// end of else statement (for when more than one terminal node)\n      // Now have J matrix\n\n      Wmat_mu=join_rows(Wmat_mu,Jmat);\n      //or\n      //Wmat.insert_cols(Wmat.n_cols,Jmat);\n      //or\n      //int b_j=term_nodes.n_elem;\n      //Wmat.insert_cols(upsilon,Jmat);\n      //upsilon+=b_j;\n\n\n      //Obtain test W_tilde, i.e. W matrix for test data\n      if(is_test_data==1){\n        W_tilde_mu=join_rows(W_tilde_mu,Jtilde);\n      }\n\n      //or\n      //W_tilde.insert_cols(W_tilde.n_cols,Jtilde);\n      //or\n      //int b_jtest=term_nodes.n_elem;\n      //W_tilde.insert_cols(upsilon2,Jtilde);\n      //upsilon2+=b_jtest;\n      //Rcout << \"Line 5566.\\n\";\n\n\n      if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n        // //get impportance sampler probability and tree prior\n        // long double temp_samp_prob;\n        // long double temp_prior_prob;\n        // //get sampler tree probability\n        // if(imp_sampler==1){//If sample from BART prior\n        //\n        //\n        //\n        //   temp_samp_prob=1;\n        //\n        //   double depth1=0;\n        //   int prev_node=0; //1 if previous node splits, zero otherwise\n        //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n        //     if(treenodes_bin[i_2]==1){\n        //       temp_samp_prob=temp_samp_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n        //       depth1=depth1+1; //after a split, the depth will increase by 1\n        //       prev_node=1;\n        //     }else{\n        //       temp_samp_prob=temp_samp_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n        //       if(prev_node==1){//zero following a 1, therefore at same depth.\n        //         //Don't change depth. Do nothing\n        //       }else{ //zero following a zero, therefore the depth will decrease by 1\n        //         depth1=depth1-1;\n        //       }\n        //       prev_node=0;\n        //\n        //     }\n        //   }\n        //\n        //   //end of calculating BART tree probability\n        // }else{\n        //   if(imp_sampler==2){//If sample from spike and tree prior\n        //     throw std::range_error(\"code not yet written for spike and tree prior\");\n        //\n        //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n        //     double tempexp1=treenodes_bin.size()-arma::sum(treenodes_bin_arma);\n        //     double tempexp2=arma::sum(treenodes_bin_arma);\n        //     temp_samp_prob=pow(lambda,tempexp2)*\n        //       pow(1-lambda,tempexp1);\n        //       //(1/pow(double(num_split_vars),tempexp2));\n        //\n        //       temp_samp_prob=exp(log(lambda)*tempexp2+\n        //         log(1-lambda)*tempexp1);\n        //\n        //     //temp_samp_prob=pow(lambda,arma::sum(treenodes_bin_arma))*\n        //     //  pow(1-lambda,treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n        //     //  pow((1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n        //   }\n        // }\n        //\n        // sum_tree_samp_prob=sum_tree_samp_prob*temp_samp_prob;\n        // //end of getting importance sampler probability\n        //\n        // //get prior tree probability\n        // if(tree_prior==1){//If sample from BART prior\n        //\n        //\n        //\n        //   temp_prior_prob=1;\n        //\n        //   double depth1=0;\n        //   int prev_node=0; //1 if previous node splits, zero otherwise\n        //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n        //\n        //     if(treenodes_bin[i_2]==1){\n        //       temp_prior_prob=temp_prior_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n        //       depth1=depth1+1; //after a split, the depth will increase by 1\n        //       prev_node=1;\n        //     }else{\n        //       temp_prior_prob=temp_prior_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n        //       if(prev_node==1){//zero following a 1, therefore at same depth.\n        //         //Don't change depth. Do nothing\n        //       }else{ //zero following a zero, therefore the depth will decrease by 1\n        //         depth1=depth1-1;\n        //       }\n        //       prev_node=0;\n        //\n        //     }\n        //     //if(alpha_BART==0){\n        //     //  Rcout << \"alpha_BART equals zero!!!!.\\n\";\n        //     //}\n        //   }\n        //\n        //   //end of calculating BART tree probability\n        // }else{\n        //   if(tree_prior==2){//If sample from spike and tree prior\n        //     throw std::range_error(\"code not yet written for spike and tree prior\");\n        //\n        //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n        //     temp_prior_prob=pow((long double)(lambda),arma::sum(treenodes_bin_arma))*\n        //       pow((long double)(1-lambda),treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n        //       pow((long double)(1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n        //   }\n        // }\n        //\n        // sum_tree_prior_prob=sum_tree_prior_prob*temp_prior_prob;\n        // if(temp_prior_prob==0){\n        //   Rcout << \"Line 4097, j= \" << j << \". \\n\";\n        //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        // }\n        // if(temp_samp_prob==0){\n        //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n        //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        // }\n        //\n        // if(sum_tree_samp_prob==0){\n        //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n        //   Rcout << \"sum_tree_samp_prob= \" << sum_tree_samp_prob << \". \\n\";\n        //   //Rcout << \"treenodes_bin_arma= \" << treenodes_bin_arma << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        //\n        // }\n\n\n\n\n        //get tree prior over impportance sampler probability\n        double tree_prior_over_samp_prob=1;\n        if(imp_sampler==1){   //If sample from BART prior\n\n\n          if(tree_prior==1){  //If tree prior is BART prior\n            throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n\n          }else{\n            if(tree_prior==2){  //If tree prior is spike-and-tree prior\n              throw std::range_error(\"code not yet written for spike and tree prior\");\n\n            }else{//otherwise the tree prior is the Quadrianto and Ghahramani prior\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*(lambda_mu/(alpha_BCF_mu*pow(double(depth1+1),-beta_BCF_mu)));\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-lambda_mu)/(1-alpha_BCF_mu*pow(double(depth1+1),-beta_BCF_mu)));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }\n              }\n\n            }\n          }\n\n\n        }else{// if not sampling from BART prior\n          if(imp_sampler==2){//If sample from spike and tree prior\n            throw std::range_error(\"code not yet written for sampling from spike and tree prior\");\n\n          }else{//otherwise sampling from Quadrianto and Ghahramani prior\n            if(tree_prior==1){  //If tree prior is BART prior\n\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((alpha_BCF_mu*pow(double(depth1+1),-beta_BCF_mu))/lambda_mu);\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-alpha_BCF_mu*pow(double(depth1+1),-beta_BCF_mu))/(1-lambda_mu));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }//close (zero node) else stattement\n\n              }//end for loop over i_2\n\n            }else{\n              if(tree_prior==2){  //If tree prior is spike-and-tree prior\n                throw std::range_error(\"code not yet written for spike and tree prior\");\n\n              }else{\n                throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n\n              }//close (not BART nor spike and tree prior) else statement\n            }// close (not BART prior) else statememt\n\n\n\n\n          }//close (not sampling from BART or spike and tree)  else statement\n\n        }//close (not sampling from BART) else statement\n\n        sum_prior_over_samp_prob=sum_prior_over_samp_prob*tree_prior_over_samp_prob;\n        //end of getting tree prior over impportance sampler probability\n\n\n\n      }//end of tree prior and importance sampler calculations\n\n\n\n\n    } //end of loop over mu trees in sum\n\n\n    /////////////////////////////////////////////////////////////////////////////////////////\n    //Rcout << \"Line 5782. TAU TREES. \\n\";\n\n    /////////////////////////////////////////////////////////////////////////////////////////\n    // NOW LOOP OVER TAU TREES\n\n\n    for(int q=0; q<num_trees_tau;q++){  //start of loop over trees in sum\n\n\n      //If parallelizing, define the distributinos before this loop\n      //and use lrng and the following two lines\n      //dqrng::xoshiro256plus lrng(rng);      // make thread local copy of rng\n      //lrng.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... nthreads jumps\n\n\n      //NumericVector treenodes_bin(0);\n      //arma::uvec treenodes_bin(0);\n\n      std::vector<int> treenodes_bin;\n\n\n      int count_terminals = 0;\n      int count_internals = 0;\n\n      //int count_treebuild = 0;\n\n\n      if(imp_sampler==1){ //If sampling from BART prior\n\n        double depth1=0;\n        int prev_node=0; //1 if previous node splits, zero otherwise\n\n        double samp_prob;\n\n        while(count_internals > (count_terminals -1)){\n          samp_prob=alpha_BCF_tau*pow(double(depth1+1),-beta_BCF_tau);\n          std::bernoulli_distribution coin_flip2(samp_prob);\n\n          int tempdraw = coin_flip2(lgen);\n          treenodes_bin.push_back(tempdraw);\n\n          if(tempdraw==1){\n\n            depth1=depth1+1; //after a split, the depth will increase by 1\n            prev_node=1;\n            count_internals=count_internals+1;\n\n          }else{\n\n            if(prev_node==1){//zero following a 1, therefore at same depth.\n              //Don't change depth. Do nothing\n            }else{ //zero following a zero, therefore the depth will decrease by 1\n              depth1=depth1-1;\n            }\n            prev_node=0;\n            count_terminals=count_terminals+1;\n\n          }\n\n        }\n\n      }else{  //If not sampling from BART prior\n        if(imp_sampler==2){//If sampling from spike and tree prior\n          throw std::range_error(\"code not yet written for spike and tree sampling\");\n\n        }else{//If sampling from default Q+G prior. i.e. not sampling from BART nor spike and tree prior\n\n          while(count_internals > (count_terminals -1)){\n\n            //Also consider standard library and random header\n            // std::random_device device;\n            // std::mt19937 gen(device());\n            // std::bernoulli_distribution coin_flip(lambda);\n            // bool outcome = coin_flip(gen);\n\n\n            int tempdraw = coin_flip_tau(lgen);\n\n            //int tempdraw = rbinom(n = 1, prob = lambda,size=1);\n\n\n            //int tempdraw = Rcpp::rbinom(1,lambda,1);\n            //int tempdraw = R::rbinom(1,lambda);\n\n            ////Rcout << \"tempdraw = \" << tempdraw << \".\\n\" ;\n\n            //int tempdraw = coin_flip2(lgen)-1;\n\n            //int tempdraw = dqrng::dqsample_int(2, 1, true,lambdavec )-1;\n\n\n            //need to update rng if use boost?\n            //int tempdraw = bernoulli(rng, binomial::param_type(1, lambda));\n\n            treenodes_bin.push_back(tempdraw);\n\n\n            if(tempdraw==1){\n              count_internals=count_internals+1;\n            }else{\n              count_terminals=count_terminals+1;\n            }\n\n          }//end of while loop creating parent vector treenodes_bin\n        }\n\n      }\n\n\n\n      //Consider making this an armadillo vector\n      //IntegerVector split_var_vec(treenodes_bin.size());\n      //arma::uvec split_var_vec(treenodes_bin.size());\n      std::vector<int> split_var_vec(treenodes_bin.size());\n\n      //loop drawing splitting variables\n      //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n      //if using armadillo, it might be faster to subset to split nodes\n      //then use a vector of draws\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        if(treenodes_bin[i]==0){\n          split_var_vec[i] = -1;\n        }else{\n          // also consider the standard library function uniform_int_distribution\n          // might need random header\n          // This uses the Mersenne twister\n\n          //Three lines below should probably be outside all the loops\n          // std::random_device rd;\n          // std::mt19937 engine(rd());\n          // std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n          //\n          // split_var_vec[i] = distsampvar(engine);\n\n          split_var_vec[i] = distsampvar_tau(lgen);\n\n\n          //consider using boost\n          //might need to update rng\n          //split_var_vec[i] <- sample_splitvars(rng);\n\n          //or use dqrng\n          //not sure if have to update the random number\n          //check if the following line is written properly\n          //split_var_vec[i] = dqrng::dqsample_int(num_split_vars, 1, true);\n\n          //not sure if this returns an integer or a vector?\n          //split_var_vec[i] = RcppArmadillo::sample(num_split_vars, 1,true);\n          //could try\n          //split_var_vec[i] = as<int>(Rcpp::sample(num_split_vars, 1,true));\n          //could also try RcppArmadillo::rmultinom\n\n        }\n\n      }// end of for-loop drawing split variables\n\n\n      //Consider making this an armadillo vector\n      //NumericVector split_point_vec(treenodes_bin.size());\n      //arma::vec split_point_vec(treenodes_bin.size());\n      std::vector<double> split_point_vec(treenodes_bin.size());\n\n\n      //loop drawing splitting points\n      //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n      //if using armadillo, it might be faster to subset to split nodes\n      //then use a vector of draws\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        if(treenodes_bin[i]==0){\n          split_point_vec[i] = -1;\n        }else{\n\n\n          //////////////////////////////////////////////////////////\n          //following function not reccommended\n          //split_point_vec[i] = std::rand();\n          //////////////////////////////////////////////////////////\n          ////Standard library:\n          ////This should probably be outside all the loops\n          ////std::random_device rd;  //Will be used to obtain a seed for the random number engine\n          ////std::mt19937 gen2(rd()); //Standard mersenne_twister_engine seeded with rd()\n          ////std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n          split_point_vec[i] = dis_cont_unif(lgen);\n\n          //////////////////////////////////////////////////////////\n          //from armadillo\n          //split_point_vec[i] = arma::randu();\n\n          //////////////////////////////////////////////////////////\n          //probably not adviseable for paralelization\n          //From Rcpp\n          //split_point_vec[i] = as<double>(Rcpp::runif(1,0,1));\n\n          //////////////////////////////////////////////////////////\n          //consider using boost\n          //might need to update rng\n          //split_point_vec[i] <- b_unif_point(rng);\n\n          //or use dqrng\n          //not sure if have to update the random number\n          //check if the following line is written properly\n          //split_point_vec[i] = dqrng::dqrunif(1, 0, 1);\n\n          //not sure if this returns an integer or a vector?\n\n\n\n\n\n        }\n\n      }// end of for-loop drawing split points\n\n\n\n      //Rcout << \"Line 6000.\\n\";\n\n\n      //CODE FOR ADJUSTING SPLITTING POINTS SO THAT THE TREES ARE VALID\n      if(valid_trees==1){\n        for(unsigned int i=0; i<treenodes_bin.size();i++){ //loop over all nodes\n          if(treenodes_bin[i]==1){ // if it is an internal node, then check for further splits on the same variable and update\n            double first_split_var=split_var_vec[i];      //splitting variable to check for\n            double first_split_point=split_point_vec[i];  //splitting point to use in updates\n\n            double sub_int_nodes=0;       //this internal node count will be used to determine if in subtree relevant to sub_int_nodes\n            double sub_term_nodes=0;      //this terminal node count will be used to determine if in subtree relevant to sub_int_nodes\n            double preventing_updates=0; //indicates if still within subtree that is not to be updated\n            double prevent_int_count=0;   //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n            double prevent_term_count=0;  //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n            for(unsigned int k=i+1; k<treenodes_bin.size();k++){\n              if(treenodes_bin[k]==1){\n                sub_int_nodes=sub_int_nodes+1;\n                if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                  prevent_int_count=prevent_int_count+1;\n                }\n              }else{\n                sub_term_nodes=sub_term_nodes+1;\n                if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                  prevent_term_count=prevent_term_count+1;\n                }\n              }\n              if(sub_int_nodes<=sub_term_nodes-2){\n                break;\n              }\n\n\n              if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                if(prevent_int_count>prevent_term_count-1){ //if this rule is satisfied then in subtree that is not to be updated\n                  continue; //still in subtree, therefore continue instead of checking for splits to be updates\n                }else{\n                  preventing_updates=0; // no longer in subtree, therefore reset preventing_updates to zero\n                }\n              }\n\n\n              if(sub_int_nodes>sub_term_nodes-1){\n                if(treenodes_bin[k]==1){\n                  if(split_var_vec[k]==first_split_var){\n                    split_point_vec[k]=split_point_vec[k]*first_split_point;\n                    //beginning count of subtree that should not have\n                    //further splits on first_split_var updated\n                    preventing_updates=1; //indicates if still within subtree that is not to be updated\n                    prevent_int_count=1;\n                    prevent_term_count=0;\n                  }\n                }\n              }else{\n                if(treenodes_bin[k]==1){\n                  if(split_var_vec[k]==first_split_var){\n                    split_point_vec[k]=split_point_vec[k]+first_split_point-first_split_point*split_point_vec[k];\n                    //beginning count of subtree that should not have\n                    //further splits on first_split_var updated\n                    preventing_updates=1; //indicates if still within subtree that is not to be updated\n                    prevent_int_count=1;\n                    prevent_term_count=0;\n                  }\n                }\n              }\n\n\n\n            }//end of inner loop over k\n          }//end of if statement treenodes_bin[i]==1)\n        }//end of loop over i\n      }//end of if statement valid_trees==1\n\n\n\n\n\n\n\n      //Rcout << \"Line 6078.\\n\";\n\n\n\n      //Create tree table matrix\n\n      //NumericMatrix tree_table1(treenodes_bin.size(),5+num_cats);\n\n      //Rcout << \"Line 1037. \\n\";\n      //arma::mat tree_table1(treenodes_bin.size(),5+num_cats);\n\n      //initialize with zeros. Not sure if this is necessary\n      arma::mat tree_table1=arma::zeros<arma::mat>(treenodes_bin.size(),6);\n      //Rcout << \"Line 1040. \\n\";\n\n\n      //tree_table1(_,2) = wrap(split_var_vec);\n      //tree_table1(_,3) = wrap(split_point_vec);\n      //tree_table1(_,4) = wrap(treenodes_bin);\n\n      //It might be more efficient to make everything an armadillo object initially\n      // but then would need to replace push_back etc with a different approach (but this might be more efficient anyway)\n      arma::colvec split_var_vec_arma=arma::conv_to<arma::colvec>::from(split_var_vec);\n      arma::colvec split_point_vec_arma(split_point_vec);\n      arma::colvec treenodes_bin_arma=arma::conv_to<arma::colvec>::from(treenodes_bin);\n\n\n      //Rcout << \"Line 1054. \\n\";\n\n      //Fill in splitting variable column\n      tree_table1.col(2) = split_var_vec_arma;\n      //Fill in splitting point column\n      tree_table1.col(3) = split_point_vec_arma;\n      //Fill in split/parent column\n      tree_table1.col(4) = treenodes_bin_arma;\n\n\n      //Rcout << \"Line 1061. j = \" << j << \". \\n\";\n      //Rcout << \"Line 6117. j = \" << j << \". \\n\";\n      //Rcout << \"Line 6118. tree_table1 tau = \" << tree_table1 << \". \\n\";\n\n\n\n      // Now start filling in left daughter and right daughter columns\n      std::vector<int> rd_spaces;\n      int prev_node = -1;\n\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        //Rcout << \"Line 1061. i = \" << i << \". \\n\";\n        if(prev_node==0){\n          //tree_table1(rd_spaces[rd_spaces.size()-1], 1)=i;\n          //Rcout << \"Line 1073. j = \" << j << \". \\n\";\n\n          tree_table1(rd_spaces.back(), 1)=i+1;\n          //Rcout << \"Line 1076. j = \" << j << \". \\n\";\n\n          rd_spaces.pop_back();\n        }\n        if(treenodes_bin[i]==1){\n          //Rcout << \"Line 1081. j = \" << j << \". \\n\";\n\n          tree_table1(i,0) = i+2;\n          rd_spaces.push_back(i);\n          prev_node = 1;\n          //Rcout << \"Line 185. j = \" << j << \". \\n\";\n\n        }else{                  // These 2 lines unnecessary if begin with matrix of zeros\n          //Rcout << \"Line 1089. j = \" << j << \". \\n\";\n          tree_table1(i,0)=0 ;\n          tree_table1(i,1) = 0 ;\n          prev_node = 0;\n          //Rcout << \"Line 1093. j = \" << j << \". \\n\";\n\n        }\n      }//\n      //Rcout << \"Line 1097. j = \" << j << \". \\n\";\n\n\n\n\n\n      //List treepred_output = get_treepreds(original_y, num_cats, alpha_pars,\n      //                                     originaldata,\n      //                                     treetable_list[i]  );\n\n\n      //use armadillo object tree_table1\n\n      ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n      ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n      //create variables for likelihood calcuations\n      // double lik_prod=1;\n      // double alph_prod=1;\n      // for(unsigned int i=0; i<alpha_pars_arma.n_elem;i++){\n      //   alph_prod=alph_prod*tgamma(alpha_pars_arma(i));\n      // }\n      // double gam_alph_sum= tgamma(arma::sum(alpha_pars_arma));\n      // double alph_term=gam_alph_sum/alph_prod;\n\n      //arma::mat arma_tree_table(treetable.begin(), treetable.nrow(), treetable.ncol(), false);\n      //arma::mat arma_orig_data(originaldata.begin(), originaldata.nrow(), originaldata.ncol(), false);\n\n\n      //arma::mat arma_tree(tree_data.begin(), tree_data.nrow(), tree_data.ncol(), false);\n      //arma::mat testd(test_data.begin(), test_data.nrow(), test_data.ncol(), false);\n\n      //NumericVector internal_nodes=find_internal_nodes_gs(tree_data);\n\n      //NumericVector terminal_nodes=find_term_nodes(treetable);\n\n      //arma::mat arma_tree(tree_table.begin(),tree_table.nrow(), tree_table.ncol(), false);\n\n      //arma::vec colmat=arma_tree.col(4);\n      //arma::uvec term_nodes=arma::find(colmat==-1);\n\n      //arma::vec colmat=arma_tree.col(2);\n      //arma::uvec term_nodes=arma::find(colmat==0);\n\n      //arma::vec colmat=tree_table1.col(4);\n      //arma::uvec term_nodes=arma::find(colmat==0);\n\n      //4th column is treenodes_bin_arma\n      arma::uvec term_nodes=arma::find(treenodes_bin_arma==0);\n\n      term_nodes=term_nodes+1;\n\n      //NumericVector terminal_nodes= wrap(term_nodes);\n\n      //Rcout << \"Line 6207.\\n\";\n\n\n      //GET J MATRIX\n\n      arma::mat Jmat(num_obs,term_nodes.n_elem);\n      arma::mat Jtilde(num_test_obs,term_nodes.n_elem);\n\n      //arma::vec arma_terminal_nodes=Rcpp::as<arma::vec>(terminal_nodes);\n      //NumericVector tree_predictions;\n\n      //now for each internal node find the observations that belong to the terminal nodes\n\n      //NumericVector predictions(test_data.nrow());\n      //List term_obs(term_nodes.n_elem);\n\n      //GET J MATRIX\n\n      if(term_nodes.n_elem==1){\n        //double nodemean=tree_data(terminal_nodes[0]-1,5);\t\t\t\t// let nodemean equal tree_data row terminal_nodes[i]^th row , 6th column. The minus 1 is because terminal nodes consists of indices starting at 1, but need indices to start at 0.\n        //predictions=rep(nodemean,test_data.nrow());\n        //Rcout << \"Line 67 .\\n\";\n\n        //IntegerVector temp_obsvec = seq_len(test_data.nrow())-1;\n        //term_obs[0]= temp_obsvec;\n        //double denom_temp= orig_y_arma.n_elem+arma::sum(alpha_pars_arma);\n\n        //double num_prod=1;\n        //double num_sum=0;\n        //Rcout << \"Line 129.\\n\";\n        Jmat.col(0) = arma::ones<arma::vec>(num_obs);\n\n        if(is_test_data==1){\n          Jtilde.col(0) = arma::ones<arma::vec>(num_test_obs);\n        }\n\n        //for(int k=0; k<num_cats; k++){\n        //assuming categories of y are from 1 to num_cats\n        //arma::uvec cat_inds= arma::find(orig_y_arma==k+1);\n        //double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n        //tree_table1(0,5+k)= m_plus_alph/denom_temp ;\n\n        //for likelihood calculation\n        //num_prod=num_prod*tgamma(m_plus_alph);\n        //num_sum=num_sum +m_plus_alph ;\n        //}\n\n        //lik_prod= alph_term*num_prod/tgamma(num_sum);\n\n      }\n      else{\n        for(unsigned int i=0;i<term_nodes.n_elem;i++){\n          //arma::mat subdata=testd;\n          //int curr_term=term_nodes(i);\n\n          int row_index;\n          int term_node=term_nodes(i);\n          //Rcout << \"Line 152.\\n\";\n\n\n          //WHAT IS THE PURPOSE OF THIS IF-STATEMENT?\n          //Why should the ro index be different for a right daughter?\n          //Why not just initialize row_index to any number not equal to 1 (e.g. 0)?\n          row_index=0;\n\n          // if(curr_term % 2==0){\n          //   //term node is left daughter\n          //   row_index=terminal_nodes[i];\n          // }else{\n          //   //term node is right daughter\n          //   row_index=terminal_nodes[i]-1;\n          // }\n\n\n\n\n          //save the left and right node data into arma uvec\n\n          //CHECK THAT THIS REFERS TO THE CORRECT COLUMNS\n          //arma::vec left_nodes=arma_tree.col(0);\n          //arma::vec right_nodes=arma_tree.col(1);\n\n          arma::vec left_nodes=tree_table1.col(0);\n          arma::vec right_nodes=tree_table1.col(1);\n\n\n\n          arma::mat node_split_mat;\n          node_split_mat.set_size(0,3);\n          //Rcout << \"Line 6296. i = \" << i << \" .\\n\";\n\n          while(row_index!=1){\n            //for each terminal node work backwards and see if the parent node was a left or right node\n            //append split info to a matrix\n            int rd=0;\n            arma::uvec parent_node=arma::find(left_nodes == term_node);\n\n            if(parent_node.size()==0){\n              parent_node=arma::find(right_nodes == term_node);\n              rd=1;\n            }\n\n            //want to cout parent node and append to node_split_mat\n\n            node_split_mat.insert_rows(0,1);\n\n            //CHECK THAT COLUMNS OF TREETABLE ARE CORRECT\n            //node_split_mat(0,0)=treetable(parent_node[0],2);\n            //node_split_mat(0,1)=treetable(parent_node[0],3);\n\n            //node_split_mat(0,0)=arma_tree_table(parent_node[0],3);\n            //node_split_mat(0,1)=arma_tree_table(parent_node[0],4);\n\n            node_split_mat(0,0)=tree_table1(parent_node(0),2);\n            node_split_mat(0,1)=tree_table1(parent_node(0),3);\n\n            node_split_mat(0,2)=rd;\n            row_index=parent_node(0)+1;\n            term_node=parent_node(0)+1;\n          }\n\n          //once we have the split info, loop through rows and find the subset indexes for that terminal node!\n          //then fill in the predicted value for that tree\n          //double prediction = tree_data(term_node,5);\n          arma::uvec pred_indices;\n          arma::uvec pred_test_indices;\n          int split= node_split_mat(0,0)-1;\n\n          //Rcout << \"Line 6335.\\n\";\n          //Rcout << \"split = \" << split << \".\\n\";\n          //Rcout << \"x_moderate_a.n_cols = \" << x_moderate_a.n_cols << \".\\n\";\n\n\n          //arma::vec tempvec = testd.col(split);\n          arma::vec tempvec = x_moderate_a.col(split);\n          ////Rcout << \"Line 227.\\n\";\n\n          //Rcout << \"Line 6341.\\n\";\n\n          double temp_split = node_split_mat(0,1);\n\n          if(node_split_mat(0,2)==0){\n            pred_indices = arma::find(tempvec <= temp_split);\n          }else{\n            pred_indices = arma::find(tempvec > temp_split);\n          }\n\n          //Rcout << \"Line 6351.\\n\";\n\n          if(is_test_data==1){\n            arma::vec temptest_vec = x_moderate_test_a.col(split);\n            //Rcout << \"Line 6355.\\n\";\n\n            if(node_split_mat(0,2)==0){\n              pred_test_indices = arma::find(temptest_vec <= temp_split);\n            }else{\n              pred_test_indices = arma::find(temptest_vec > temp_split);\n            }\n          }\n\n\n          //Rcout << \"Line 6361.\\n\";\n\n          arma::uvec temp_pred_indices;\n          arma::uvec temp_test_pred_indices;\n\n          //arma::vec data_subset = testd.col(split);\n          arma::vec data_subset = x_moderate_a.col(split);\n          data_subset=data_subset.elem(pred_indices);\n\n          arma::vec data_test_subset;\n          if(is_test_data==1){\n            data_test_subset =x_moderate_test_a.col(split);\n            data_test_subset=data_test_subset.elem(pred_test_indices);\n          }\n\n          //now loop through each row of node_split_mat\n          int n=node_split_mat.n_rows;\n\n          //Rcout << \"Line 6378. i = \" << i << \". n = \" << n << \".\\n\";\n\n          for(int j=1;j<n;j++){\n            int curr_sv=node_split_mat(j,0);\n            double split_p = node_split_mat(j,1);\n\n            //data_subset = testd.col(curr_sv-1);\n            //Rcout << \"Line 255.\\n\";\n            //Rcout << \"curr_sv = \" << curr_sv << \".\\n\";\n            data_subset = x_moderate_a.col(curr_sv-1);\n            //Rcout << \"Line 258.\\n\";\n\n            data_subset=data_subset.elem(pred_indices);\n\n\n            if(node_split_mat(j,2)==0){\n              //split is to the left\n              temp_pred_indices=arma::find(data_subset <= split_p);\n            }else{\n              //split is to the right\n              temp_pred_indices=arma::find(data_subset > split_p);\n            }\n            pred_indices=pred_indices.elem(temp_pred_indices);\n\n\n            if(is_test_data==1){\n              data_test_subset = x_moderate_test_a.col(curr_sv-1);\n              data_test_subset=data_test_subset.elem(pred_test_indices);\n\n              if(node_split_mat(j,2)==0){\n                //split is to the left\n                temp_test_pred_indices=arma::find(data_test_subset <= split_p);\n              }else{\n                //split is to the right\n                temp_test_pred_indices=arma::find(data_test_subset > split_p);\n              }\n              pred_test_indices=pred_test_indices.elem(temp_test_pred_indices);\n\n            }\n\n\n            //if(pred_indices.size()==0){\n            //  continue;\n            //}\n\n          }\n          //Rcout << \"Line 6425. i = \" << i <<  \".\\n\";\n\n          //There is probably a more efficient way of doing this\n          //e.g. initialize J matrix so that all elements are equal to zero\n          arma::vec tempcol_J=arma::zeros<arma::vec>(num_obs);\n          tempcol_J(pred_indices) = arma::ones<arma::vec>(pred_indices.size());\n          Jmat.col(i) = tempcol_J;\n\n          if(is_test_data==1){\n            arma::vec tempcol_Jtilde=arma::zeros<arma::vec>(num_test_obs);\n            tempcol_Jtilde(pred_test_indices) = arma::ones<arma::vec>(pred_test_indices.size());\n            Jtilde.col(i) = tempcol_Jtilde;\n          }\n\n          //double nodemean=tree_data(terminal_nodes[i]-1,5);\n          //IntegerVector predind=as<IntegerVector>(wrap(pred_indices));\n          //predictions[predind]= nodemean;\n          //term_obs[i]=predind;\n\n          //double denom_temp= pred_indices.n_elem+arma::sum(alpha_pars_arma);\n          //Rcout << \"Line 207. predind = \" << predind <<  \".\\n\";\n          //Rcout << \"Line 207. denom_temp = \" << denom_temp <<  \".\\n\";\n          // << \"Line 207. term_node = \" << term_node <<  \".\\n\";\n\n          //double num_prod=1;\n          //double num_sum=0;\n\n          // for(int k=0; k<num_cats; k++){\n          //   //assuming categories of y are from 1 to num_cats\n          //   arma::uvec cat_inds= arma::find(orig_y_arma(pred_indices)==k+1);\n          //   double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n          //\n          //   tree_table1(curr_term-1,5+k)= m_plus_alph/denom_temp ;\n          //\n          //   num_prod=num_prod*tgamma(m_plus_alph);\n          //   num_sum=num_sum +m_plus_alph ;\n          // }\n          //\n          //\n          // lik_prod= lik_prod*alph_term*num_prod/tgamma(num_sum);\n\n          //Rcout << \"Line 6466.\\n\";\n\n\n        }//End of loop over terminal nodes.\n      }// end of else statement (for when more than one terminal node)\n      // Now have J matrix\n\n      //Rcout << \"Line 6472.\\n\";\n\n      Wmat_tau=join_rows(Wmat_tau,Jmat);\n\n\n\n      //or\n      //Wmat.insert_cols(Wmat.n_cols,Jmat);\n      //or\n      //int b_j=term_nodes.n_elem;\n      //Wmat.insert_cols(upsilon,Jmat);\n      //upsilon+=b_j;\n\n\n      //Obtain test W_tilde, i.e. W matrix for test data\n      if(is_test_data==1){\n        W_tilde_tau=join_rows(W_tilde_tau,Jtilde);\n      }\n\n      //or\n      //W_tilde.insert_cols(W_tilde.n_cols,Jtilde);\n      //or\n      //int b_jtest=term_nodes.n_elem;\n      //W_tilde.insert_cols(upsilon2,Jtilde);\n      //upsilon2+=b_jtest;\n\n\n      if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n        // //get impportance sampler probability and tree prior\n        // long double temp_samp_prob;\n        // long double temp_prior_prob;\n        // //get sampler tree probability\n        // if(imp_sampler==1){//If sample from BART prior\n        //\n        //\n        //\n        //   temp_samp_prob=1;\n        //\n        //   double depth1=0;\n        //   int prev_node=0; //1 if previous node splits, zero otherwise\n        //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n        //     if(treenodes_bin[i_2]==1){\n        //       temp_samp_prob=temp_samp_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n        //       depth1=depth1+1; //after a split, the depth will increase by 1\n        //       prev_node=1;\n        //     }else{\n        //       temp_samp_prob=temp_samp_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n        //       if(prev_node==1){//zero following a 1, therefore at same depth.\n        //         //Don't change depth. Do nothing\n        //       }else{ //zero following a zero, therefore the depth will decrease by 1\n        //         depth1=depth1-1;\n        //       }\n        //       prev_node=0;\n        //\n        //     }\n        //   }\n        //\n        //   //end of calculating BART tree probability\n        // }else{\n        //   if(imp_sampler==2){//If sample from spike and tree prior\n        //     throw std::range_error(\"code not yet written for spike and tree prior\");\n        //\n        //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n        //     double tempexp1=treenodes_bin.size()-arma::sum(treenodes_bin_arma);\n        //     double tempexp2=arma::sum(treenodes_bin_arma);\n        //     temp_samp_prob=pow(lambda,tempexp2)*\n        //       pow(1-lambda,tempexp1);\n        //       //(1/pow(double(num_split_vars),tempexp2));\n        //\n        //       temp_samp_prob=exp(log(lambda)*tempexp2+\n        //         log(1-lambda)*tempexp1);\n        //\n        //     //temp_samp_prob=pow(lambda,arma::sum(treenodes_bin_arma))*\n        //     //  pow(1-lambda,treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n        //     //  pow((1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n        //   }\n        // }\n        //\n        // sum_tree_samp_prob=sum_tree_samp_prob*temp_samp_prob;\n        // //end of getting importance sampler probability\n        //\n        // //get prior tree probability\n        // if(tree_prior==1){//If sample from BART prior\n        //\n        //\n        //\n        //   temp_prior_prob=1;\n        //\n        //   double depth1=0;\n        //   int prev_node=0; //1 if previous node splits, zero otherwise\n        //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n        //\n        //     if(treenodes_bin[i_2]==1){\n        //       temp_prior_prob=temp_prior_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n        //       depth1=depth1+1; //after a split, the depth will increase by 1\n        //       prev_node=1;\n        //     }else{\n        //       temp_prior_prob=temp_prior_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n        //       if(prev_node==1){//zero following a 1, therefore at same depth.\n        //         //Don't change depth. Do nothing\n        //       }else{ //zero following a zero, therefore the depth will decrease by 1\n        //         depth1=depth1-1;\n        //       }\n        //       prev_node=0;\n        //\n        //     }\n        //     //if(alpha_BART==0){\n        //     //  Rcout << \"alpha_BART equals zero!!!!.\\n\";\n        //     //}\n        //   }\n        //\n        //   //end of calculating BART tree probability\n        // }else{\n        //   if(tree_prior==2){//If sample from spike and tree prior\n        //     throw std::range_error(\"code not yet written for spike and tree prior\");\n        //\n        //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n        //     temp_prior_prob=pow((long double)(lambda),arma::sum(treenodes_bin_arma))*\n        //       pow((long double)(1-lambda),treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n        //       pow((long double)(1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n        //   }\n        // }\n        //\n        // sum_tree_prior_prob=sum_tree_prior_prob*temp_prior_prob;\n        // if(temp_prior_prob==0){\n        //   Rcout << \"Line 4097, j= \" << j << \". \\n\";\n        //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        // }\n        // if(temp_samp_prob==0){\n        //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n        //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        // }\n        //\n        // if(sum_tree_samp_prob==0){\n        //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n        //   Rcout << \"sum_tree_samp_prob= \" << sum_tree_samp_prob << \". \\n\";\n        //   //Rcout << \"treenodes_bin_arma= \" << treenodes_bin_arma << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        //\n        // }\n\n\n\n\n        //get tree prior over impportance sampler probability\n        double tree_prior_over_samp_prob=1;\n        if(imp_sampler==1){   //If sample from BART prior\n\n\n          if(tree_prior==1){  //If tree prior is BART prior\n            throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n\n          }else{\n            if(tree_prior==2){  //If tree prior is spike-and-tree prior\n              throw std::range_error(\"code not yet written for spike and tree prior\");\n\n            }else{//otherwise the tree prior is the Quadrianto and Ghahramani prior\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*(lambda_tau/(alpha_BCF_tau*pow(double(depth1+1),-beta_BCF_tau)));\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-lambda_tau)/(1-alpha_BCF_tau*pow(double(depth1+1),-beta_BCF_tau)));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }\n              }\n\n            }\n          }\n\n\n        }else{// if not sampling from BART prior\n          if(imp_sampler==2){//If sample from spike and tree prior\n            throw std::range_error(\"code not yet written for sampling from spike and tree prior\");\n\n          }else{//otherwise sampling from Quadrianto and Ghahramani prior\n            if(tree_prior==1){  //If tree prior is BART prior\n\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((alpha_BCF_tau*pow(double(depth1+1),-beta_BCF_tau))/lambda_tau);\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-alpha_BCF_tau*pow(double(depth1+1),-beta_BCF_tau))/(1-lambda_tau));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }//close (zero node) else stattement\n\n              }//end for loop over i_2\n\n            }else{\n              if(tree_prior==2){  //If tree prior is spike-and-tree prior\n                throw std::range_error(\"code not yet written for spike and tree prior\");\n\n              }else{\n                throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n\n              }//close (not BART nor spike and tree prior) else statement\n            }// close (not BART prior) else statememt\n\n\n\n\n          }//close (not sampling from BART or spike and tree)  else statement\n\n        }//close (not sampling from BART) else statement\n\n        sum_prior_over_samp_prob=sum_prior_over_samp_prob*tree_prior_over_samp_prob;\n        //end of getting tree prior over impportance sampler probability\n\n\n\n      }//end of tree prior and importance sampler calculations\n\n\n\n    } //end of loop over trees in sum\n\n\n\n    //Rcout << \"6708 4528.\\n\";\n\n\n    double b_mu=Wmat_mu.n_cols;\n    double b_tau=Wmat_tau.n_cols;\n    //Wmat_tau.each_col()%=z_ar;\n\n\n    //Rcout << \"Line 14688.\\n\";\n    //Rcout << \"b_tau = \" << b_tau << \".\\n\";\n    //Rcout << \"Wmat_tau.n_rows = \" << Wmat_tau.n_rows << \".\\n\";\n\n    //Rcout << \"z_ar.n_elem = \" << z_ar.n_elem << \".\\n\";\n\n\n    //Rcout <<\"Wmat_tau BEFORE diag? = \" << Wmat_tau <<\".\\n\";\n\n    arma::mat DiagZ_Wmat_tau= Wmat_tau.each_col()%z_ar;\n    //Rcout << \"Line 14693.\\n\";\n\n\n    arma::mat Wmat = join_rows(Wmat_mu,DiagZ_Wmat_tau);\n\n\n    //Rcout <<\"Wmat_mu = \" << Wmat_mu <<\".\\n\";\n    //Rcout <<\"Wmat_tau AFTER diag? = \" << Wmat_tau <<\".\\n\";\n    //Rcout <<\"DiagZ_Wmat_tau = \" << DiagZ_Wmat_tau <<\".\\n\";\n    //Rcout <<\"Wmat = \" << Wmat <<\".\\n\";\n\n\n    double b=Wmat.n_cols;\t\t\t\t\t\t\t\t\t// b is number of columns of W_bcf matrix (omega in the paper)\n\n\n    // if(fast_approx==1){\n    //   arma::mat p = Wmat.t();\n    //   arma::rowvec r = orig_y_arma.t();\n    //\n    //   //create diagonal mat of penalty terms\n    //   arma::mat aI(b,b);\t\t\t\t\t\t\t\t\t// create b by b matrix called aI. NOT INIIALIZED.\n    //   aI=aI.eye();\t\t\t\t\t\t\t\t\t\t// a times b by b identity matrix. The .eye() turns aI into an identity matrix.\n    //   arma::vec a_vec_mu = a_mu*arma::ones<arma::vec>(b_mu);\n    //   arma::vec a_vec_tau = a_tau*arma::ones<arma::vec>(b_tau);\n    //   arma::vec a_vec(b);\n    //   a_vec.head(b_mu) = a_vec_mu;\n    //   a_vec.tail(b_tau) = a_vec_tau;\n    //   aI.diag() = a_vec;\n    //   //finish creating diagonal mat\n    //\n    //   arma::mat cov = p * p.t() + aI;\n    //\n    //   arma::mat parameters = arma::solve(cov, p * r.t(), arma::solve_opts::fast);\n    //\n    //   arma::rowvec preds_insamp_arma=arma::trans(parameters) * p;\n    //\n    //\n    //\n    //\n    //\n    //   arma::vec tempresids=y-preds_insamp_arma.t();\n    //   double temp_sse= arma::dot(tempresids, tempresids);\n    //\n    //   //double templik0=exp(-b*0.5*log(num_obs)+log(temp_sse)*(-num_obs)*0.5);\n    //\n    //\n    //   //double templik0=exp(-b*0.5*log(num_obs)+log(temp_sse)*(-num_obs)*0.5);\n    //\n    //\n    //   //double templik0=exp(-0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs)))  ;\n    //\n    //   double templik0=(num_obs*log(temp_sse/num_obs)+b*log(num_obs))  ;\n    //\n    //   // Rcout << \"num_obs= \" << num_obs << \". \\n\";\n    //   // Rcout << \"b= \" << b << \". \\n\";\n    //   // Rcout << \"log(num_obs)= \" << log(num_obs) << \". \\n\";\n    //   // Rcout << \"log(temp_sse/num_obs)= \" << log(temp_sse/num_obs) << \". \\n\";\n    //   //Rcout << \"templik0= \" << templik0 << \". \\n\";\n    //   // Rcout << \"-0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs))= \" << -0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs)) << \". \\n\";\n    //\n    //\n    //   //double templik = pow(templik0,beta_par);\n    //   double templik = beta_par*templik0;\n    //\n    //\n    //   if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n    //     //templik=templik*(sum_tree_prior_prob/sum_tree_samp_prob);\n    //     templik=templik*sum_prior_over_samp_prob;\n    //\n    //   }\n    //   overall_liks(j)= templik;\n    //\n    //\n    //   //Now get and save predictions\n    //   if(is_test_data==1){ //save out of sample predictions if is_test_data==1\n    //     //arma::mat zeromat(arma::size(Wmat_mu),arma::fill::zeros);\n    //     //arma::mat zeromat(num_obs ,b_mu ,arma::fill::zeros);\n    //     arma::mat zeromat=arma::zeros<arma::mat>(num_test_obs,b_mu);\n    //     arma::mat Vmat = join_rows(zeromat,W_tilde_tau);\n    //\n    //     //arma::vec preds_temp_arma= Vmat*sec_term_inv*third_term;\n    //\n    //     arma::rowvec preds_temp_arma_t=arma::trans(parameters) * Vmat.t();\n    //     arma::vec preds_temp_arma= preds_temp_arma_t.t();\n    //\n    //     // overall_preds(j)=preds_temp_arma*templik;\n    //     overall_preds.col(j)=preds_temp_arma;\n    //     //overall_preds.col(j)=preds_temp_arma;\n    //\n    //\n    //     //arma::mat covar_t=as_scalar((1/double(nu+num_obs))*(nu*lambdaBCF+yty-mvm))*(Vmat*sec_term_inv*(Vmat.t()));\n    //\n    //     //arma::mat catevartemp=averagingvec.t()*covar_t*averagingvec;\n    //     //arma::mat cattvartemp=catt_averagingvec.t()*covar_t*catt_averagingvec;\n    //     //arma::mat catntvartemp=catnt_averagingvec.t()*covar_t*catnt_averagingvec;\n    //\n    //     //preds_all_models_arma.col(i)=preds_temp_arma;\n    //     t_vars_arma.col(j)=covar_t.diag();\n    //     cate_means_arma(j)=as_scalar(averagingvec.t()*preds_temp_arma);\n    //     // cate_means_weighted_arma(i)=cate_means_arma(i)*post_weights_arma(i);\n    //     cate_vars_arma(j)=as_scalar(catevartemp);\n    //     // catt_means_arma(i)=as_scalar(catt_averagingvec.t()*preds_temp_arma);\n    //     // catt_means_weighted_arma(i)=catt_means_arma(i)*post_weights_arma(i);\n    //     // catt_vars_arma(i)=as_scalar(cattvartemp);\n    //     // catnt_means_arma(i)=as_scalar(catnt_averagingvec.t()*preds_temp_arma);\n    //     // catnt_means_weighted_arma(i)=catnt_means_arma(i)*post_weights_arma(i);\n    //     // catnt_vars_arma(i)=as_scalar(catntvartemp);\n    //     //\n    //\n    //   }else{\n    //\n    //     //arma::mat zeromat(arma::size(Wmat_mu),arma::fill::zeros);\n    //     //arma::mat zeromat(num_obs ,b_mu ,arma::fill::zeros);\n    //     arma::mat zeromat=arma::zeros<arma::mat>(num_obs ,b_mu);\n    //     arma::mat Vmat = join_rows(zeromat,Wmat_tau);\n    //\n    //     //Rcout <<\"Vmat = \" << Vmat <<\".\\n\";\n    //\n    //     //arma::vec preds_temp_arma= Vmat*sec_term_inv*third_term;\n    //\n    //     arma::rowvec preds_temp_arma_t=arma::trans(parameters) * Vmat.t();\n    //     arma::vec preds_temp_arma= preds_temp_arma_t.t();\n    //     overall_preds.col(j)=preds_temp_arma;\n    //\n    //     //overall_preds(j)=preds_temp_arma*templik;\n    //\n    //\n    //     arma::mat covar_t=as_scalar((1/double(nu+num_obs))*(nu*lambdaBCF+yty-mvm))*(Vmat*sec_term_inv*(Vmat.t()));\n    //\n    //     //arma::mat catevartemp=averagingvec.t()*covar_t*averagingvec;\n    //     //arma::mat cattvartemp=catt_averagingvec.t()*covar_t*catt_averagingvec;\n    //     //arma::mat catntvartemp=catnt_averagingvec.t()*covar_t*catnt_averagingvec;\n    //\n    //     // preds_all_models_arma.col(i)=preds_temp_arma;\n    //     t_vars_arma.col(j)=covar_t.diag();\n    //     cate_means_arma(j)=as_scalar(averagingvec.t()*preds_temp_arma);\n    //     // cate_means_weighted_arma(i)=cate_means_arma(i)*post_weights_arma(i);\n    //     cate_vars_arma(j)=as_scalacalar(catt_averagingvec.t()*preds_temp_arma);\n    //     // catt_means_weighted_armr(catevartemp);\n    //     // catt_means_arma(i)=as_sa(i)=catt_means_arma(i)*post_weights_arma(i);\n    //     // catt_vars_arma(i)=as_scalar(cattvartemp);\n    //     // catnt_means_arma(i)=as_scalar(catnt_averagingvec.t()*preds_temp_arma);\n    //     // catnt_means_weighted_arma(i)=catnt_means_arma(i)*post_weights_arma(i);\n    //     // catnt_vars_arma(i)=as_scalar(catntvartemp);\n    //     //\n    //\n    //   }//end of else statement (not test data)\n    //\n    //\n    // }else{ // if fast_approx ==0\n    //\n\n\n\n\n      //get t(orig_y_arma)inv(psi)J_bcf\n      arma::mat ytW=orig_y_arma.t()*Wmat;\t\t\t\t\t\t\t\t// orig_y_arma transpose W_bcf\n      //get t(J_bcf)inv(psi)J_bcf\n      arma::mat WtW=Wmat.t()*Wmat;\t\t\t\t\t\t\t// W_bcf transpose W_bcf\n      //get jpsij +aI\n      arma::mat aI(b,b);\t\t\t\t\t\t\t\t\t// create b by b matrix called aI. NOT INIIALIZED.\n      aI=aI.eye();\t\t\t\t\t\t\t\t\t\t// a times b by b identity matrix. The .eye() turns aI into an identity matrix.\n      arma::vec a_vec_mu = a_mu*arma::ones<arma::vec>(b_mu);\n      arma::vec a_vec_tau = a_tau*arma::ones<arma::vec>(b_tau);\n      arma::vec a_vec(b);\n      a_vec.head(b_mu) = a_vec_mu;\n      a_vec.tail(b_tau) = a_vec_tau;\n      aI.diag() = a_vec;\n\n      arma::mat sec_term=WtW+aI;\t\t\t\t\t\t\t//\n      //arma::mat sec_term_inv=sec_term.i();\t\t\t\t\t// matrix inverse expression in middle of eq 5 in the paper. The .i() obtains the matrix inverse.\n      arma::mat sec_term_inv=inv_sympd(sec_term);\t\t\t\t\t// matrix inverse expression in middle of eq 5 in the paper. The .i() obtains the matrix inverse.\n\n      //get t(J_bcf)inv(psi)orig_y_arma\n      arma::mat third_term=Wmat.t()*orig_y_arma;\t\t\t\t\t\t// W_bcf transpose orig_y_arma\n      //get m^TV^{-1}m\n      arma::mat mvm= ytW*sec_term_inv*third_term;\t\t// matrix expression in middle of equation 5\n      //arma::mat rel=(b_mu*0.5)*log(a_mu)+(b_tau*0.5)*log(a_tau)-(1*0.5)*log(det(sec_term))-expon*log(nu*lambda - mvm +yty);\t\t// log of all of equation 5 (i.e. the log of the marginal likelihood of the sum of tree model)\n\n      //Rcout << \"Line 14724.\\n\";\n\n\n\n      //arma::vec preds_temp_arma= Vmat*sec_term_inv*Wmat.t()*orig_y_arma;\n      //arma::vec preds_temp_arma= Vmat*inv_sympd(sec_term)*Wmat.t()*orig_y_arma;\n      //arma::vec preds_temp_arma= Vmat*inv_sympd(sec_term)*third_term;\n\n\n      //double templik0=exp(arma::as_scalar((b_mu*0.5)*log(a_mu)+(b_tau*0.5)*log(a_tau)-(0.5)*log(det(sec_term))-expon*log(nu*lambdaBCF - mvm +yty)) );\n\n      //double templik0=exp(arma::as_scalar((b_mu*0.5)*log(a_mu)+(b_tau*0.5)*log(a_tau)-(0.5)*real(arma::log_det(sec_term))-expon*log(nu*lambdaBCF - mvm +yty)) );\n\n      double templik0=arma::as_scalar((b_mu*0.5)*log(a_mu)+(b_tau*0.5)*log(a_tau)-(0.5)*real(arma::log_det(sec_term))-expon*log(nu*lambdaBCF - mvm +yty)) ;\n\n\n      ////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n      //double templik = pow(templik0,beta_par);\n      double templik = beta_par*templik0;\n\n      if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n        //templik=templik*(sum_tree_prior_prob/sum_tree_samp_prob);\n        //templik=templik*sum_prior_over_samp_prob;\n        templik=templik+log(sum_prior_over_samp_prob);\n\n      }\n      overall_liks(j)= templik;\n\n\n      //now get and save predictions\n      if(is_test_data==1){\n        //arma::mat zeromat(arma::size(Wmat_mu),arma::fill::zeros);\n        //arma::mat zeromat(num_obs ,b_mu ,arma::fill::zeros);\n        arma::mat zeromat=arma::zeros<arma::mat>(num_test_obs,b_mu);\n        arma::mat Vmat = join_rows(zeromat,W_tilde_tau);\n\n\n        //arma::rowvec preds_temp_arma_t=arma::trans(parameters) * Vmat.t();\n        //arma::vec preds_temp_arma= preds_temp_arma_t.t();\n        //overall_preds(j)=preds_temp_arma;\n\n\n        arma::vec preds_temp_arma= Vmat*sec_term_inv*third_term;\n        overall_preds.col(j)=preds_temp_arma;\n\n        //overall_preds(j)=preds_temp_arma*templik;\n\n\n        arma::mat covar_t=as_scalar((1/double(nu+num_obs))*(nu*lambdaBCF+yty-mvm))*(Vmat*sec_term_inv*(Vmat.t()));\n\n        arma::mat catevartemp=averagingvec.t()*covar_t*averagingvec;\n        //arma::mat cattvartemp=catt_averagingvec.t()*covar_t*catt_averagingvec;\n        //arma::mat catntvartemp=catnt_averagingvec.t()*covar_t*catnt_averagingvec;\n\n        // preds_all_models_arma.col(i)=preds_temp_arma;\n        t_vars_arma.col(j)=covar_t.diag();\n        cate_means_arma(j)=as_scalar(averagingvec.t()*preds_temp_arma);\n        // cate_means_weighted_arma(i)=cate_means_arma(i)*post_weights_arma(i);\n        cate_vars_arma(j)=as_scalar(catevartemp);\n        // catt_means_arma(i)=as_scalar(catt_averagingvec.t()*preds_temp_arma);\n        // catt_means_weighted_arma(i)=catt_means_arma(i)*post_weights_arma(i);\n        // catt_vars_arma(i)=as_scalar(cattvartemp);\n        // catnt_means_arma(i)=as_scalar(catnt_averagingvec.t()*preds_temp_arma);\n        // catnt_means_weighted_arma(i)=catnt_means_arma(i)*post_weights_arma(i);\n        // catnt_vars_arma(i)=as_scalar(catntvartemp);\n        //\n\n      }else{\n\n        //arma::mat zeromat(arma::size(Wmat_mu),arma::fill::zeros);\n        //arma::mat zeromat(num_obs ,b_mu ,arma::fill::zeros);\n        arma::mat zeromat=arma::zeros<arma::mat>(num_obs ,b_mu);\n        arma::mat Vmat = join_rows(zeromat,Wmat_tau);\n\n        //Rcout <<\"Vmat = \" << Vmat <<\".\\n\";\n\n        //arma::rowvec preds_temp_arma_t=arma::trans(parameters) * Vmat.t();\n        //arma::vec preds_temp_arma= preds_temp_arma_t.t();\n        //overall_preds(j)=preds_temp_arma;\n\n        //Rcout <<\"coeffs = \" << sec_term_inv*third_term << \".\\n\";\n        //Rcout <<\"Vmat = \" << Vmat << \".\\n\";\n        //Rcout <<\"Wmat_tau = \" << Wmat_tau << \".\\n\";\n\n\n\n        //arma::mat Vmattemp = join_rows(zeromat,DiagZ_Wmat_tau);\n\n        //Rcout <<\"Vmattemp*coeffs = \" <<  Vmattemp*sec_term_inv*third_term << \".\\n\";\n        //Rcout <<\"Vmat*coeffs = \" <<  Vmat*sec_term_inv*third_term << \".\\n\";\n\n\n        //Rcout <<\"z%Vmat*coeffs = Vmattemp*coeffs?\" <<  z_ar%Vmat*sec_term_inv*third_term ==Vmattemp*sec_term_inv*third_term << \".\\n\";\n\n        //coeffs(j)= sec_term_inv*third_term;\n\n\n        arma::vec preds_temp_arma= Vmat*sec_term_inv*third_term;\n        overall_preds.col(j)=preds_temp_arma;\n\n\n        // arma::mat zeromat_mu=arma::zeros<arma::mat>(num_obs ,b_tau);\n        // arma::mat Vmat_mu = join_rows(Wmat_mu,zeromat_mu);\n        // arma::vec preds_temp_arma_mu= Vmat_mu*sec_term_inv*third_term;\n        //\n        // //arma::vec temppredstest=preds_temp_arma%z_ar;\n        // //Rcout <<\"temppredstest = \" << temppredstest << \".\\n\";\n        //\n        // overall_preds_mu(j)=preds_temp_arma_mu;\n        //\n        // arma::vec preds_temp_arma_y= Wmat*sec_term_inv*third_term;\n        // overall_preds_y(j)=preds_temp_arma_y;\n\n\n        //overall_preds(j)=preds_temp_arma*templik;\n\n\n        arma::mat covar_t=as_scalar((1/double(nu+num_obs))*(nu*lambdaBCF+yty-mvm))*(Vmat*sec_term_inv*(Vmat.t()));\n\n        arma::mat catevartemp=averagingvec.t()*covar_t*averagingvec;\n        //arma::mat cattvartemp=catt_averagingvec.t()*covar_t*catt_averagingvec;\n        //arma::mat catntvartemp=catnt_averagingvec.t()*covar_t*catnt_averagingvec;\n\n\n        // preds_all_models_arma.col(i)=preds_temp_arma;\n        t_vars_arma.col(j)=covar_t.diag();\n        cate_means_arma(j)=as_scalar(averagingvec.t()*preds_temp_arma);\n        // cate_means_weighted_arma(i)=cate_means_arma(i)*post_weights_arma(i);\n        cate_vars_arma(j)=as_scalar(catevartemp);\n        // catt_means_arma(i)=as_scalar(catt_averagingvec.t()*preds_temp_arma);\n        // catt_means_weighted_arma(i)=catt_means_arma(i)*post_weights_arma(i);\n        // catt_vars_arma(i)=as_scalar(cattvartemp);\n        // catnt_means_arma(i)=as_scalar(catnt_averagingvec.t()*preds_temp_arma);\n        // catnt_means_weighted_arma(i)=catnt_means_arma(i)*post_weights_arma(i);\n        // catnt_vars_arma(i)=as_scalar(catntvartemp);\n        //\n\n      }//end of else statement (not test data)\n\n\n\n    // } // end if statement fast_approx==1\n  }//end of loop over all trees\n\n}//end of pragma omp code\n\n\n///////////////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////////////////////////////////////////////////////////////\n//Rcout << \"Line 6852.\\n\";\n\n\n//for(unsigned int i=0; i<overall_treetables.n_elem;i++){\n//  pred_mat_overall = pred_mat_overall + overall_liks(i)*overall_treetables(i);\n//}\n\n// if(is_test_data==1){\n//   #pragma omp parallel\n//   {\n//     arma::vec result_private=arma::zeros<arma::vec>(x_control_test_a.n_rows);\n//   #pragma omp for nowait //fill result_private in parallel\n//     for(unsigned int i=0; i<overall_preds.size(); i++) result_private += overall_preds(i);\n//   #pragma omp critical\n//     pred_vec_overall += result_private;\n//   }\n// }else{\n//   #pragma omp parallel\n//   {\n//     arma::vec result_private=arma::zeros<arma::vec>(x_control_a.n_rows);\n//   #pragma omp for nowait //fill result_private in parallel\n//     for(unsigned int i=0; i<overall_preds.size(); i++) result_private += overall_preds(i);\n//   #pragma omp critical\n//     pred_vec_overall += result_private;\n//   }\n// }\n//\n//\n// //Rcout << \"Line 4030. \\n\";\n//\n//\n//\n//\n// //Rcout << \"overall_liks = \" << overall_liks << \". \\n\";\n// //Rcout << \"max(overall_liks) = \" << max(overall_liks) << \". \\n\";\n// //Rcout << \"overall_liks[14] = \" << overall_liks[14] << \". \\n\";\n//\n//\n// double sumlik_total= arma::sum(overall_liks);\n// //Rcout << \"sumlik_total = \" << sumlik_total << \". \\n\";\n//\n// pred_vec_overall=pred_vec_overall*(1/sumlik_total);\n//\n\n\ndouble cate_pred=0;\n//double catt_pred;\n//double catnt_pred;\n\n//NumericMatrix draws_wrapped= wrap(draws_for_preds);\narma::mat output(3, num_obs);\n//NumericVector probs_for_quantiles =  NumericVector::create(lower_prob, 0.5, upper_prob);\n\n//std::vector<double> probs_for_quantiles {lower_prob, 0.5, upper_prob};\narma::mat cate_ints(3, 1);\n//arma::mat catt_ints(3, 1);\n//arma::mat catnt_ints(3, 1);\n\n\n\n\n\n\n\n\n\n\n\n\nif(fast_approx==1){\n  arma::vec BICi=-0.5*overall_liks;\n  double max_BIC=max(BICi);\n\n  // weighted_BIC is actually the posterior model probability\n  arma::vec weighted_BIC(overall_liks.size());\n\n\n  double tempterm=(max_BIC+log(sum(exp(BICi-max_BIC))));\n\n  for(unsigned int k=0;k<overall_liks.size();k++){\n\n    //NumericVector BICi=-0.5*BIC_weights;\n    //double max_BIC=max(BICi);\n    double weight=exp(BICi[k]-tempterm);\n    weighted_BIC[k]=weight;\n    //int num_its_to_sample = round(weight*(num_iter));\n\n  }\n\n  //Rcout << \"weighted_BIC= \" << weighted_BIC << \". \\n\";\n  //Rcout << \"overall_liks= \" << overall_liks << \". \\n\";\n\n#pragma omp parallel num_threads(ncores)\n{\n  arma::vec result_private;\n  if(is_test_data==1){\n    result_private=arma::zeros<arma::vec>(x_control_test_a.n_rows);\n  }else{\n    result_private=arma::zeros<arma::vec>(x_control_a.n_rows);\n  }\n\n#pragma omp for nowait //fill result_private in parallel\n  for(unsigned int i=0; i<overall_preds.n_cols; i++){\n    //double weight=exp(BICi[i]-(max_BIC+log(sum(exp(BICi-max_BIC)))));\n    result_private += overall_preds.col(i)*weighted_BIC(i);\n  }\n#pragma omp critical\n  pred_vec_overall += result_private;\n}\n\n\n}else{ //if fast_approx==0\n\n  //arma::vec BICi=-0.5*overall_liks;\n  double max_loglik=max(overall_liks);\n\n  // weighted_BIC is actually the posterior model probability\n  arma::vec weighted_lik(overall_liks.size());\n\n\n  double tempterm=(max_loglik+log(sum(exp(overall_liks-max_loglik))));\n\n  for(unsigned int k=0;k<overall_liks.size();k++){\n\n    //NumericVector BICi=-0.5*BIC_weights;\n    //double max_BIC=max(BICi);\n    double weight=exp(overall_liks[k]-tempterm);\n    weighted_lik[k]=weight;\n    //int num_its_to_sample = round(weight*(num_iter));\n\n  }\n\n  //Rcout << \"weighted_lik= \" << weighted_lik << \". \\n\";\n  //Rcout << \"overall_liks= \" << overall_liks << \". \\n\";\n\n#pragma omp parallel num_threads(ncores)\n{\n  arma::vec result_private;\n  //arma::vec result_private_mu;\n  //arma::vec result_private_y;\n  double cate_result_private=0;\n\n  if(is_test_data==1){\n    result_private=arma::zeros<arma::vec>(x_control_test_a.n_rows);\n  }else{\n    result_private=arma::zeros<arma::vec>(x_control_a.n_rows);\n    //result_private_mu=arma::zeros<arma::vec>(x_control_a.n_rows);\n    //result_private_y=arma::zeros<arma::vec>(x_control_a.n_rows);\n\n  }\n\n#pragma omp for nowait //fill result_private in parallel\n  for(unsigned int i=0; i<overall_preds.n_cols; i++){\n    result_private += overall_preds.col(i)*weighted_lik(i);\n    cate_result_private += cate_means_arma(i)*weighted_lik(i);\n    //result_private_mu += overall_preds_mu(i)*weighted_lik(i);\n    //result_private_y += overall_preds_y(i)*weighted_lik(i);\n  }\n#pragma omp critical\n  pred_vec_overall += result_private;\n  cate_pred += cate_result_private;\n\n  //pred_vec_overall_mu += result_private_mu;\n  //pred_vec_overall_y += result_private_y;\n\n}\n\n\n\n\n  typedef std::vector<double> stdvec;\n  std::vector<double> weights_vec= arma::conv_to<stdvec>::from(weighted_lik);\n\n  boost::math::students_t dist2(nu+num_obs);\n  double lq_tstandard= boost::math::quantile(dist2,lower_prob);\n  double med_tstandard= boost::math::quantile(dist2,0.5); //This is just 0 ??\n  double uq_tstandard= boost::math::quantile(dist2,upper_prob);\n\n\n\n  ///////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n\n  if(weights_vec.size()==1){\n\n    cate_ints(0,0)= cate_means_arma(0)+sqrt(cate_vars_arma(0))*lq_tstandard;\n    cate_ints(1,0)= cate_means_arma(0)+sqrt(cate_vars_arma(0))*med_tstandard;\n    cate_ints(2,0)= cate_means_arma(0)+sqrt(cate_vars_arma(0))*uq_tstandard;\n\n    // catt_ints(0,0)= catt_means_arma(0)+sqrt(catt_vars_arma(0))*lq_tstandard;\n    // catt_ints(1,0)= catt_means_arma(0)+sqrt(catt_vars_arma(0))*med_tstandard;\n    // catt_ints(2,0)= catt_means_arma(0)+sqrt(catt_vars_arma(0))*uq_tstandard;\n    //\n    // catnt_ints(0,0)= catnt_means_arma(0)+sqrt(catnt_vars_arma(0))*lq_tstandard;\n    // catnt_ints(1,0)= catnt_means_arma(0)+sqrt(catnt_vars_arma(0))*med_tstandard;\n    // catnt_ints(2,0)= catnt_means_arma(0)+sqrt(catnt_vars_arma(0))*uq_tstandard;\n\n#pragma omp parallel num_threads(ncores)\n#pragma omp for\n    for(int i=0;i<num_obs;i++){\n      std::vector<double> tempmeans= arma::conv_to<stdvec>::from(overall_preds.row(i));\n      std::vector<double> tempvars= arma::conv_to<stdvec>::from(t_vars_arma.row(i));\n\n      //boost::math::students_t dist2(nu+num_obs);\n\n      //Rcout << \"Line 13812 tempvars\" << t_vars_arma.row(i) << \".\\n\";\n      //Rcout << \"tempmeans\" << overall_preds.row(i) << \".\\n\";\n\n\n      output(0,i)= tempmeans[0]+sqrt(tempvars[0])*lq_tstandard;\n      output(1,i)= tempmeans[0]+sqrt(tempvars[0])*med_tstandard;\n      output(2,i)= tempmeans[0]+sqrt(tempvars[0])*uq_tstandard;\n\n\n    }\n#pragma omp barrier\n  }else{\n    std::vector<double> tempmeans_cate= arma::conv_to<stdvec>::from(cate_means_arma);\n    std::vector<double> tempvars_cate= arma::conv_to<stdvec>::from(cate_vars_arma);\n\n    std::vector<double> bounds_lQ_cate = mixt_find_boundsQ( nu+num_obs, tempmeans_cate, tempvars_cate, lq_tstandard);\n\n    //Rcout << \"line 13828 cate_vars_arma = \" << cate_vars_arma << \".\\n\";\n    //Rcout << \"cate_means_arma = \" << cate_means_arma << \".\\n\";\n\n    //Rcout << \"bounds_lQ_cate[0] = \" << bounds_lQ_cate[0] << \".\\n\";\n    //Rcout << \"bounds_lQ_cate[1] = \" << bounds_lQ_cate[1] << \".\\n\";\n\n    cate_ints(0,0)= rootmixt(nu+num_obs,\n              bounds_lQ_cate[0]-0.0001,\n              bounds_lQ_cate[1]+0.0001,\n              tempmeans_cate,\n              tempvars_cate,\n              weights_vec, lower_prob,root_alg_precision);\n\n    std::vector<double> bounds_med_cate = mixt_find_boundsQ( nu+num_obs, tempmeans_cate, tempvars_cate, med_tstandard);\n\n    //Rcout << \"bounds_lQ_cate[0] = \" << bounds_lQ_cate[0] << \".\\n\";\n    //Rcout << \"bounds_lQ_cate[1] = \" << bounds_lQ_cate[1] << \".\\n\";\n\n    cate_ints(1,0)= rootmixt(nu+num_obs,\n              bounds_med_cate[0]-0.0001,\n              bounds_med_cate[1]+0.0001,\n              tempmeans_cate,\n              tempvars_cate,\n              weights_vec, 0.5, root_alg_precision);\n\n    std::vector<double> bounds_uQ_cate = mixt_find_boundsQ( nu+num_obs, tempmeans_cate, tempvars_cate, uq_tstandard);\n\n    //Rcout << \"bounds_lQ_cate[0] = \" << bounds_lQ_cate[0] << \".\\n\";\n    //Rcout << \"bounds_lQ_cate[1] = \" << bounds_lQ_cate[1] << \".\\n\";\n\n    cate_ints(2,0)= rootmixt(nu+num_obs,\n              bounds_uQ_cate[0]-0.0001,\n              bounds_uQ_cate[1]+0.0001,\n              tempmeans_cate,\n              tempvars_cate,\n              weights_vec, upper_prob, root_alg_precision);\n\n    //Rcout << \"line 13871 cate_ints = \" << cate_ints << \".\\n\";\n\n\n    //\n    //\n    // std::vector<double> tempmeans_catt= arma::conv_to<stdvec>::from(catt_means_arma);\n    // std::vector<double> tempvars_catt= arma::conv_to<stdvec>::from(catt_vars_arma);\n    //\n    // std::vector<double> bounds_lQ_catt = mixt_find_boundsQ( nu+num_obs, tempmeans_catt, tempvars_catt, lq_tstandard);\n    //\n    //\n    // catt_ints(0,0)= rootmixt(nu+num_obs,\n    //           bounds_lQ_catt[0]-0.0001,\n    //           bounds_lQ_catt[1]+0.0001,\n    //           tempmeans_catt,\n    //           tempvars_catt,\n    //           weights_vec, lower_prob,root_alg_precision);\n    //\n    // std::vector<double> bounds_med_catt = mixt_find_boundsQ( nu+num_obs, tempmeans_catt, tempvars_catt, med_tstandard);\n    //\n    // //Rcout << \"bounds_lQ_catt[0] = \" << bounds_lQ_catt[0] << \".\\n\";\n    // //Rcout << \"bounds_lQ_catt[1] = \" << bounds_lQ_catt[1] << \".\\n\";\n    //\n    // catt_ints(1,0)= rootmixt(nu+num_obs,\n    //           bounds_med_catt[0]-0.0001,\n    //           bounds_med_catt[1]+0.0001,\n    //           tempmeans_catt,\n    //           tempvars_catt,\n    //           weights_vec, 0.5, root_alg_precision);\n    //\n    // std::vector<double> bounds_uQ_catt = mixt_find_boundsQ( nu+num_obs, tempmeans_catt, tempvars_catt, uq_tstandard);\n    //\n    // //Rcout << \"bounds_lQ_catt[0] = \" << bounds_lQ_catt[0] << \".\\n\";\n    // //Rcout << \"bounds_lQ_catt[1] = \" << bounds_lQ_catt[1] << \".\\n\";\n    //\n    // catt_ints(2,0)= rootmixt(nu+num_obs,\n    //           bounds_uQ_catt[0]-0.0001,\n    //           bounds_uQ_catt[1]+0.0001,\n    //           tempmeans_catt,\n    //           tempvars_catt,\n    //           weights_vec, upper_prob, root_alg_precision);\n    //\n    //\n    //\n    // //\n    //\n    //\n    // std::vector<double> tempmeans_catnt= arma::conv_to<stdvec>::from(catnt_means_arma);\n    // std::vector<double> tempvars_catnt= arma::conv_to<stdvec>::from(catnt_vars_arma);\n    //\n    // std::vector<double> bounds_lQ_catnt = mixt_find_boundsQ( nu+num_obs, tempmeans_catnt, tempvars_catnt, lq_tstandard);\n    //\n    //\n    //\n    // catnt_ints(0,0)= rootmixt(nu+num_obs,\n    //            bounds_lQ_catnt[0]-0.0001,\n    //            bounds_lQ_catnt[1]+0.0001,\n    //            tempmeans_catnt,\n    //            tempvars_catnt,\n    //            weights_vec, lower_prob,root_alg_precision);\n    //\n    // std::vector<double> bounds_med_catnt = mixt_find_boundsQ( nu+num_obs, tempmeans_catnt, tempvars_catnt, med_tstandard);\n    //\n    // //Rcout << \"bounds_lQ_catnt[0] = \" << bounds_lQ_catnt[0] << \".\\n\";\n    // //Rcout << \"bounds_lQ_catnt[1] = \" << bounds_lQ_catnt[1] << \".\\n\";\n    //\n    // catnt_ints(1,0)= rootmixt(nu+num_obs,\n    //            bounds_med_catnt[0]-0.0001,\n    //            bounds_med_catnt[1]+0.0001,\n    //            tempmeans_catnt,\n    //            tempvars_catnt,\n    //            weights_vec, 0.5, root_alg_precision);\n    //\n    // std::vector<double> bounds_uQ_catnt = mixt_find_boundsQ( nu+num_obs, tempmeans_catnt, tempvars_catnt, uq_tstandard);\n    //\n    // //Rcout << \"bounds_lQ_catnt[0] = \" << bounds_lQ_catnt[0] << \".\\n\";\n    // //Rcout << \"bounds_lQ_catnt[1] = \" << bounds_lQ_catnt[1] << \".\\n\";\n    //\n    // catnt_ints(2,0)= rootmixt(nu+num_obs,\n    //            bounds_uQ_catnt[0]-0.0001,\n    //            bounds_uQ_catnt[1]+0.0001,\n    //            tempmeans_catnt,\n    //            tempvars_catnt,\n    //            weights_vec, upper_prob, root_alg_precision);\n\n\n\n#pragma omp parallel num_threads(ncores)\n#pragma omp for\n    for(int i=0;i<num_obs;i++){\n      //output(_,i)=Quantile(draws_wrapped(_,i), probs_for_quantiles);\n\n      std::vector<double> tempmeans= arma::conv_to<stdvec>::from(overall_preds.row(i));\n      std::vector<double> tempvars= arma::conv_to<stdvec>::from(t_vars_arma.row(i));\n\n      //Rcout << \"Line 13859. tempvars\" << t_vars_arma.row(i) << \".\\n\";\n      //Rcout << \"tempmeans\" << overall_preds.row(i) << \".\\n\";\n\n      std::vector<double> bounds_lQ = mixt_find_boundsQ( nu+num_obs, tempmeans, tempvars, lq_tstandard);\n\n      output(0,i)=rootmixt(nu+num_obs,\n             bounds_lQ[0]-0.0001,\n             bounds_lQ[1]+0.0001,\n             tempmeans,\n             tempvars,\n             weights_vec, lower_prob,root_alg_precision);\n\n\n      std::vector<double> bounds_med = mixt_find_boundsQ( nu+num_obs, tempmeans, tempvars, med_tstandard);\n\n      output(1,i)=rootmixt(nu+num_obs,\n             bounds_med[0]-0.0001,\n             bounds_med[1]+0.0001,\n             tempmeans,\n             tempvars,\n             weights_vec, 0.5,root_alg_precision);\n\n      std::vector<double> bounds_uQ = mixt_find_boundsQ( nu+num_obs, tempmeans, tempvars, uq_tstandard);\n\n      output(2,i)=rootmixt(nu+num_obs,\n             bounds_uQ[0]-0.0001,\n             bounds_uQ[1]+0.0001,\n             tempmeans,\n             tempvars,\n             weights_vec, upper_prob,root_alg_precision);\n\n\n    }\n#pragma omp barrier\n  } // close else statement (number of models not equal to 1)\n\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n\n//double sumlik_total= arma::sum(overall_liks);\n//Rcout << \"sumlik_total = \" << sumlik_total << \". \\n\";\n\n//pred_vec_overall=pred_vec_overall*(1/sumlik_total);\n\n// pred_vec_overall=arma::sum(overall_preds,1);\n// pred_vec_overall_mu=arma::sum(overall_preds_mu,1);\n// pred_vec_overall_y=arma::sum(overall_preds_y,1);\n\n} // close else statement for fast_approx==0\n\n\n\n\n\n\n\narma::mat output_rescaled(output.n_rows, output.n_cols);\ndouble min_y=min(ytrain);\ndouble max_y=max(ytrain);\n\n#pragma omp parallel num_threads(ncores)\n#pragma omp for\nfor(unsigned int i=0;i<output.n_cols;i++){\n  //output(_,i)=Quantile(draws_wrapped(_,i), probs_for_quantiles);\n\n  output_rescaled.col(i)=get_original_TE_arma(min_y,max_y,-0.5,0.5, output.col(i));\n\n\n}\n#pragma omp barrier\n\narma::mat cate_ints_rescaled=get_original_TE_arma(min_y,max_y,-0.5,0.5, cate_ints.col(0));\n//arma::mat catt_ints_rescaled=get_original_TE_arma(min(y),max(y),-0.5,0.5, catt_ints.col(0));\n//arma::mat catnt_ints_rescaled=get_original_TE_arma(min(y),max(y),-0.5,0.5, catnt_ints.col(0));\n\n\n\n\n//Rcout << \"Line 7386. \\n\";\nNumericVector orig_preds=get_original_TE(min_y,max_y,-0.5,0.5,wrap(pred_vec_overall));\n\ndouble orig_cate=get_original_TE_double(min_y,max_y,-0.5,0.5,cate_pred);\n\n//NumericVector orig_preds_mu=get_original(min(ytrain),max(ytrain),-0.5,0.5,wrap(pred_vec_overall_mu)) ;\n//NumericVector orig_preds_y=get_original(min(ytrain),max(ytrain),-0.5,0.5,wrap(pred_vec_overall_y)) ;\n\n\n//return(orig_preds);\n\n//List ret(3);\n//ret[0]=orig_preds;\n//ret[1]=orig_preds_mu;\n//ret[2]=orig_preds_y;\n\n//return(ret);\n\n\n\nList ret(4);\nret(0) = orig_preds;\nret(1) = wrap(output_rescaled);\nret(2) = orig_cate;\nret(3) = wrap(cate_ints_rescaled);\n\nreturn(ret);\n\n} //end of function\n\n//######################################################################################################################//\n\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::depends(dqrng, BH, sitmo)]]\n\n\n#include <xoshiro.h>\n#include <dqrng_distribution.h>\n//#include <dqrng.h>\n\n// [[Rcpp::plugins(openmp)]]\n#include <omp.h>\n\n//' @title Parallel Safe-BART with prediction intervals\n//'\n//' @description A parallelized implementation of safe-Bayesian Additive Regression Trees.\n//' @param lambda A real number between 0 and 1 that determines the splitting probability in the prior (which is used as the importance sampler of tree models). Quadrianto and Ghahramani (2015) recommend a value less than 0.5 .\n//' @param num_trees The number of trees to be sampled.\n//' @param seed The seed for random number generation.\n//' @param num_cats The number of possible values for the outcome variable.\n//' @param y The training data vector of outcomes. This must be a vector of integers between 1 and num_cats.\n//' @param original_datamat The original training data. Currently all variables must be continuous. The training data does not need to be transformed before being entered to this function.\n//' @param alpha_parameters Vector of prior parameters.\n//' @param beta_par The power to which the likelihood is to be raised. For BMA, set beta_par=1.\n//' @param original_datamat The original test data. This matrix must have the same number of columns (variables) as the training data. Currently all variables must be continuous. The test data does not need to be transformed before being entered to this function.\n//' @param ncores The number of cores to be used in parallelization.\n//' @return A List containing 1. A vector of predictions, and 2. A matrix of prediction intervals, the first row corresponds to the lower quantile, the second row is the median, and the third row is the upper quantile.\n//' @export\n// [[Rcpp::export]]\nList sBART_ITEs_with_ints(double lambda,\n                              int num_models,\n                              int num_trees,\n                              int seed,\n                              NumericVector ytrain,\n                              NumericMatrix original_datamat,\n                              NumericVector ztrain,\n                              NumericMatrix pihat_train,\n                              double beta_par,\n                              NumericMatrix test_datamat,\n                              NumericMatrix test_pihat,\n                              int ncores,\n                              int outsamppreds,\n                              double nu,\n                              double a,\n                              double lambdaBART,\n                              int valid_trees,\n                              int tree_prior,\n                              int imp_sampler,\n                              double alpha_BART,\n                              double beta_BART,\n                              int s_t_hyperprior,\n                              double p_s_t,\n                              double a_s_t,\n                              double b_s_t,\n                              double lambda_poisson,\n                              int fast_approx,\n                              int PIT_propensity,\n                              double lower_prob,\n                              double upper_prob,\n                              double root_alg_precision){\n\n\n  //Rcout << \"imp_sampler = \" << imp_sampler << \".\\n\";\n\n\n  //Check that various input vectors and matrices have consistent dimensions\n\n  //Rcout << \"Line 4528.\\n\";\n\n  bool is_test_data=0;\t\t\t\t\t// create bool is_test_data. Initialize equal to 0.\n  if(test_datamat.nrow()>0){\t\t\t\t\t// If test data has non-zero number of rows.\n    is_test_data=1;\t\t\t\t\t\t// set is_test_data equal to 1.\n  }\n  if(ytrain.size() !=original_datamat.nrow()){\t\t\t\t// If the length of input vector y is not equal to the nunber of rows in the input data (covariates)\n    if(ytrain.size()<original_datamat.nrow()){\t\t\t// If the length of y is less than the number of rows in data\n      throw std::range_error(\"Response length is smaller than the number of observations in the data\");\n    }else{\t\t\t\t\t\t\t\t// If the length of y is greater than the number of rows in data\n      throw std::range_error(\"Response length is greater than the number of observations in the data\");\n    }\n  }\n  if(ztrain.size() !=original_datamat.nrow()){\t\t\t\t// If the length of input vector z is not equal to the nunber of rows in the input data (covariates)\n    if(ztrain.size()<original_datamat.nrow()){\t\t\t// If the length of z is less than the number of rows in data\n      throw std::range_error(\"Treatment indicator vector length is smaller than the number of observations in the data\");\n    }else{\t\t\t\t\t\t\t\t// If the length of z is greater than the number of rows in data\n      throw std::range_error(\"Treatment indicator vector length is greater than the number of observations in the data\");\n    }\n  }\n  if(pihat_train.nrow() !=original_datamat.nrow()){\t\t\t\t// If the nunber of rows in the input matrix pihat is not equal to the nunber of rows in the input data (covariates)\n    if(pihat_train.nrow()<original_datamat.nrow()){\t\t\t// If the nunber of rows in the input matrix pihat is less than the number of rows in data\n      throw std::range_error(\"The nunber of rows in the input matrix pihat_train is smaller than the number of observations in the data\");\n    }else{\t\t\t\t\t\t\t\t// If the nunber of rows in the input matrix pihat is greater than the number of rows in data\n      throw std::range_error(\"The nunber of rows in the input matrix pihat_train is greater than the number of observations in the data\");\n    }\n  }\n  //check test data has the same number of variables as training data\n  if(test_datamat.nrow()>0 && (original_datamat.ncol() != test_datamat.ncol())){\t// If the number of rows in the test data is >0 AND the number of columns (variables) is not equal to that of data (the training data)\n    throw std::range_error(\"Test data and training data must have the same number of variables. BART BMA assumes variables are in the same order.\");\n  }\n  //if(test_z.size() != test_datamat.nrow()){\t// If the number of rows in the test data covariate matrix is not equal to that of the test data treatment indicator variable\n  //  throw std::range_error(\"Test data covariates and test data treatment indicator variable must have the same number of observations.\");\n  //}\n  if(test_datamat.nrow() != test_pihat.nrow()){\t// If the number of rows in the test data covariate matrix is not equal to that of the test data propensity score estimates matrix\n    throw std::range_error(\"Test data covariates and test data propensity score estimates must have the same number of observations.\");\n  }\n  if(test_pihat.nrow()>0 && (pihat_train.ncol() != test_pihat.ncol())){\t// If the number of rows in the test data propensity score estimates is >0 AND the number of columns (variables) is not equal to that of the training data propensity score estimates\n    throw std::range_error(\"Test data propensity score estimates and training data propensity score estimates must have the same number of columns. BART BMA assumes variables are in the same order.\");\n  }\n\n  ///////////////////////////////////////////////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n  // Now add propensity score estimates matrix as new leftmost column of data matrix. Call the resulting matrix x_control (to be consistent with terminology used by bcf package).\n  arma::mat D1(original_datamat.begin(), original_datamat.nrow(), original_datamat.ncol(), false);\t\t\t\t// copy the covariate data matrix into an arma mat\n  arma::mat pihat_1(pihat_train.begin(), pihat_train.nrow(), pihat_train.ncol(), false);\t\t\t\t// copy the pihat matrix into an arma mat\n  //arma::mat x_control_a=D1;\t\t\t\t// create a copy of data arma mat called x_control_a\n\n\n  //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n  arma::mat x_control_a_temp(D1.n_rows,D1.n_cols);\n  for(unsigned int k=0; k<D1.n_cols;k++){\n    arma::vec samp= D1.col(k);\n    arma::vec sv=arma::sort(samp);\n    //std::sort(sv.begin(), sv.end());\n    arma::uvec ord = arma::sort_index(samp);\n    double nobs = samp.n_elem;\n    arma::vec ans(nobs);\n    for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n      int ind=ord(i);\n      double ssampi(samp[ind]);\n      while (sv(j) < ssampi && j < sv.size()) ++j;\n      ans(ind) = j;     // j is the 1-based index of the lower bound\n    }\n    x_control_a_temp.col(k)=(ans+1)/nobs;\n  }\n\n  arma::mat x_control_a=x_control_a_temp;\t\t\t// create arma mat copy of x_control_a_temp.\n\n  //arma::mat x_moderate_a=x_control_a_temp;\t\t\t// create arma mat copy of x_control_a_temp.\n\n  arma::mat pihat_a(pihat_1.n_rows,pihat_1.n_cols);\n\n  if(PIT_propensity==1){\n\n    //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n    for(unsigned int k=0; k<pihat_1.n_cols;k++){\n      arma::vec samp= pihat_1.col(k);\n      arma::vec sv=arma::sort(samp);\n      //std::sort(sv.begin(), sv.end());\n      arma::uvec ord = arma::sort_index(samp);\n      double nobs = samp.n_elem;\n      arma::vec ans(nobs);\n      for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n        int ind=ord(i);\n        double ssampi(samp[ind]);\n        while (sv(j) < ssampi && j < sv.size()) ++j;\n        ans(ind) = j;     // j is the 1-based index of the lower bound\n      }\n      pihat_a.col(k)=(ans+1)/nobs;\n    }\n  }else{\n    pihat_a=pihat_1;\n  }\n\n\n\n  //if((include_pi2==0) | (include_pi2==2) ){\n  //  if(pihat_train.nrow()>0 ){\n      x_control_a.insert_cols(0,pihat_a);\t\t// add propensity scores as new leftmost columns of x_control_a\n  //  }\n  //}\n\n\n  // Rcout << \"Number of columns of matrix\" << x_control_a.n_cols << \".\\n\";\n\n\n  //NumericMatrix x_control=wrap(x_control_a);\t// convert x_control_a to a NumericMatrix called x_control\n\n  // Name the matrix without the estimated propensity scores x_moderate.[CAN REMOVE THE DUPLICATION AND ADD x_control, x_moderate, and include_pi as input parameters later]\n  //NumericMatrix x_moderate = data;\t// x_moderate matrix is the covariate data without the propensity scores\n  //arma::mat x_moderate_a=D1;\t\t\t// create arma mat copy of x_moderate.\n  //if((include_pi2==1)| (include_pi2==2) ){\n  //  if(pihat_train.nrow()>0 ){\n  //    x_moderate_a.insert_cols(0,pihat_a);\t\t// add propensity scores as new leftmost columns of x_control_a\n  //  }\n  //}\n\n\n  //NumericMatrix x_moderate=wrap(x_moderate_a);\t// convert x_control_a to a NumericMatrix called x_control\n\n\n  // Rcout << \"Get to Line 7139  \"  << \".\\n\";\n  // Add test propensity scores to test data matrix\n  arma::mat T1(test_datamat.begin(), test_datamat.nrow(), test_datamat.ncol(), false);\t\t\t\t// copy the covariate test_data matrix into an arma mat\n  arma::mat pihat_1_test(test_pihat.begin(), test_pihat.nrow(), test_pihat.ncol(), false);\t\t\t\t// copy the test_pihat matrix into an arma mat\n  //arma::mat x_control_test_a=T1;\t\t\t\t// create a copy of test_data arma mat called x_control_test_a\n\n  arma::mat x_control_test_a(T1.n_rows,T1.n_cols);\n  //arma::mat x_moderate_test_a(T1.n_rows,T1.n_cols);\n  arma::mat pihat_a_test(pihat_1_test.n_rows,pihat_1_test.n_cols);\n\n  if(is_test_data==1){\n    //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n    arma::mat x_control_a_test_temp(T1.n_rows,T1.n_cols);\n\n    for(unsigned int k=0; k<T1.n_cols;k++){\n      arma::vec samp= T1.col(k);\n      arma::vec sv=arma::sort(samp);\n      //std::sort(sv.begin(), sv.end());\n      arma::uvec ord = arma::sort_index(samp);\n      double nobs = samp.n_elem;\n      arma::vec ans(nobs);\n      for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n        int ind=ord(i);\n        double ssampi(samp[ind]);\n        while (sv(j) < ssampi && j < sv.size()) ++j;\n        ans(ind) = j;     // j is the 1-based index of the lower bound\n      }\n      x_control_a_test_temp.col(k)=(ans+1)/nobs;\n    }\n\n    arma::mat x_control_test_a=x_control_a_test_temp;\t\t\t// create arma mat copy of x_control_a_temp.\n\n    //arma::mat x_moderate_test_a=x_control_a_test_temp;\t\t\t// create arma mat copy of x_control_a_temp.\n\n    if(PIT_propensity==1){\n      //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n      for(unsigned int k=0; k<pihat_1_test.n_cols;k++){\n        arma::vec samp= pihat_1_test.col(k);\n        arma::vec sv=arma::sort(samp);\n        //std::sort(sv.begin(), sv.end());\n        arma::uvec ord = arma::sort_index(samp);\n        double nobs = samp.n_elem;\n        arma::vec ans(nobs);\n        for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n          int ind=ord(i);\n          double ssampi(samp[ind]);\n          while (sv(j) < ssampi && j < sv.size()) ++j;\n          ans(ind) = j;     // j is the 1-based index of the lower bound\n        }\n        pihat_a_test.col(k)=(ans+1)/nobs;\n      }\n    }else{\n      pihat_a_test=pihat_1_test;\n    }\n\n\n  }\n\n\n\n  //if((include_pi2==0)| (include_pi2==2) ){\n  //  if(test_pihat.nrow()>0 ){\n      x_control_test_a.insert_cols(0,pihat_a_test);\t\t// add propensity scores as new leftmost columns of x_control_test_a\n  //  }\n  //}\n\n\n  //NumericMatrix x_control_test=wrap(x_control_test_a);\t// convert x_control_test_a to a NumericMatrix called x_control_test\n\n\n  // Name the matrix without the estimated propensity scores x_moderate_test.[CAN REMOVE THE DUPLICATION AND ADD x_control_test, x_moderate_test, and include_pi as input parameters later]\n  //NumericMatrix x_moderate_test = test_data;\t// x_moderate_test matrix is the covariate test_data without the propensity scores\n  //arma::mat x_moderate_test_a=T1;\t\t\t// create arma mat copy of x_moderate_test.\n  // if((include_pi2==1)| (include_pi2==2) ){\n  //   if(test_pihat.nrow()>0 ){\n  //     x_moderate_test_a.insert_cols(0,pihat_a_test);\t\t// add propensity scores as new leftmost columns of x_control_a\n  //   }\n  // }\n\n  //NumericMatrix x_moderate_test=wrap(x_moderate_test_a);\t// convert x_control_test_a to a NumericMatrix called x_control_test\n\n\n\n  //////////////////////////////////////////////////////////////////////////////////////////\n  //Rcout << \"Line 4715.\\n\";\n\n  //////////////////////////////////////////////////////////////////////////////////////////\n\n  //End of checks and adding propensity scores to matrices\n\n\n\n\n\n\n\n  NumericVector y_scaled=scale_response(min(ytrain),max(ytrain),-0.5,0.5,ytrain);\n  int num_obs = x_control_a.n_rows;\n  int num_test_obs = x_control_test_a.n_rows;\n\n  arma::vec z_ar=Rcpp::as<arma::vec>(ztrain);\t\t// converts to arma vec\n\n  arma::mat ztempmat(num_obs,1);\n  ztempmat.col(0)=z_ar;\n  //x_control_a.insert_cols(0,z_ar);\t\t// add propensity scores as new leftmost columns of x_control_a\n\n  arma::mat x_with_z = join_rows(ztempmat,x_control_a);\n\n  arma::mat x_with_ones(x_with_z.n_rows, x_with_z.n_cols);\n  arma::mat x_with_zeros(x_with_z.n_rows, x_with_z.n_cols);\n  arma::mat x_with_ones_test(num_test_obs, x_with_z.n_cols);\n  arma::mat x_with_zeros_test(num_test_obs, x_with_z.n_cols);\n\n  if(is_test_data==1){\n    arma::mat temp_one_mat=arma::ones<arma::mat>(num_test_obs,1);\n    arma::mat temp_zero_mat=arma::zeros<arma::mat>(num_test_obs,1);\n\n    x_with_ones_test=join_rows(temp_one_mat, x_control_test_a);\n    x_with_zeros_test=join_rows(temp_zero_mat, x_control_test_a);\n\n  }else{\n    arma::mat temp_one_mat=arma::ones<arma::mat>(num_obs,1);\n    arma::mat temp_zero_mat=arma::zeros<arma::mat>(num_obs,1);\n\n    x_with_ones=join_rows(temp_one_mat, x_control_a);\n    x_with_zeros=join_rows(temp_zero_mat, x_control_a);\n\n  }\n\n\n  int num_split_vars= x_with_z.n_cols;\n  //arma::mat data_arma= as<arma::mat>(original_datamat);\n  //arma::mat testdata_arma= as<arma::mat>(test_datamat);\n\n\n  arma::vec orig_y_arma= as<arma::vec>(y_scaled);\n  //arma::vec alpha_pars_arma= as<arma::vec>(alpha_parameters);\n\n\n  int num_vars = x_with_z.n_cols;\n\n  //calculations for likelihood\n  arma::mat y(num_obs,1);\n  y.col(0)=orig_y_arma;\n  //get exponent\n  double expon=(num_obs+nu)*0.5;\n  //get y^Tpsi^{-1}y\n  // arma::mat psi_inv=psi.i();\n  arma::mat yty=y.t()*y;\n\n  //arma::mat I_test(num_test_obs,num_test_obs);\n  //I_test=I_test.eye();\n\n  ///////////////////////\n  //NumericMatrix Data_transformed = cpptrans_cdf(original_datamat);\n  // NumericMatrix Data_transformed(original_datamat.nrow(), original_datamat.ncol());\n  // for(int i=0; i<original_datamat.ncol();i++){\n  //   NumericVector samp= original_datamat(_,i);\n  //   NumericVector sv(clone(samp));\n  //   std::sort(sv.begin(), sv.end());\n  //   double nobs = samp.size();\n  //   NumericVector ans(nobs);\n  //   for (int k = 0; k < samp.size(); ++k)\n  //     ans[k] = std::lower_bound(sv.begin(), sv.end(), samp[k]) - sv.begin();\n  //   //NumericVector ansnum = ans;\n  //   Data_transformed(_,i) = (ans+1)/nobs;\n  // }\n\n\n\n  //arma::mat arma_orig_data(Data_transformed.begin(), Data_transformed.nrow(), Data_transformed.ncol(), false);\n\n\n\n  //NumericMatrix transformedData(originaldata.nrow(), originaldata.ncol());\n\n  //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n  // arma::mat arma_orig_data(data_arma.n_rows,data_arma.n_cols);\n  // for(unsigned int k=0; k<data_arma.n_cols;k++){\n  //   arma::vec samp= data_arma.col(k);\n  //   arma::vec sv=arma::sort(samp);\n  //   //std::sort(sv.begin(), sv.end());\n  //   arma::uvec ord = arma::sort_index(samp);\n  //   double nobs = samp.n_elem;\n  //   arma::vec ans(nobs);\n  //   for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n  //     int ind=ord(i);\n  //     double ssampi(samp[ind]);\n  //     while (sv(j) < ssampi && j < sv.size()) ++j;\n  //     ans(ind) = j;     // j is the 1-based index of the lower bound\n  //   }\n  //   arma_orig_data.col(k)=(ans+1)/nobs;\n  // }\n\n\n\n\n\n  /////////////////////////////////////\n  // NumericMatrix testdat_trans = cpptrans_cdf_test(original_datamat,test_datamat);\n  // //NumericMatrix testdat_trans(test_datamat.nrow(), test_datamat.ncol());\n  // for(int i=0; i<test_datamat.ncol();i++){\n  //   NumericVector samp= test_datamat(_,i);\n  //   NumericVector svtest = original_datamat(_,i);\n  //   NumericVector sv(clone(svtest));\n  //   std::sort(sv.begin(), sv.end());\n  //   double nobs = samp.size();\n  //   NumericVector ans(nobs);\n  //   double nobsref = svtest.size();\n  //   for (int k = 0; k < samp.size(); ++k){\n  //     ans[k] = std::lower_bound(sv.begin(), sv.end(), samp[k]) - sv.begin();\n  //   }\n  //   //NumericVector ansnum = ans;\n  //   testdat_trans(_,i) = (ans)/nobsref;\n  // }\n\n\n\n\n\n  //NumericMatrix transformedData(originaldata.nrow(), originaldata.ncol());\n  //arma::mat data_arma= as<arma::mat>(originaldata);\n\n  //THIS CAN BE PARALLELIZED IF THERE ARE MANY VARIABLES\n  // arma::mat arma_test_data(testdata_arma.n_rows,testdata_arma.n_cols);\n  // for(unsigned int k=0; k<data_arma.n_cols;k++){\n  //   arma::vec ref= data_arma.col(k);\n  //   arma::vec samp= testdata_arma.col(k);\n  //\n  //   arma::vec sv=arma::sort(samp);\n  //   arma::vec sref=arma::sort(ref);\n  //\n  //   //std::sort(sv.begin(), sv.end());\n  //   arma::uvec ord = arma::sort_index(samp);\n  //   double nobs = samp.n_elem;\n  //   double nobsref = ref.n_elem;\n  //\n  //   arma::vec ans(nobs);\n  //   for (unsigned int i = 0, j = 0; i < nobs; ++i) {\n  //     int ind=ord(i);\n  //     double ssampi(samp[ind]);\n  //     if(j+1>sref.size()){\n  //     }else{\n  //       while (sref(j) < ssampi && j < sref.size()){\n  //         ++j;\n  //         if(j==sref.size()) break;\n  //       }\n  //     }\n  //     ans(ind) = j;     // j is the 1-based index of the lower bound\n  //   }\n  //\n  //   arma_test_data.col(k)=(ans)/nobsref;\n  //\n  // }\n  //\n\n\n\n\n\n\n  /////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n  //////////////////////////////////////////////////////////////////////////////////////\n  //List table_list = draw_trees(lambda, num_trees, seed, num_split_vars, num_cats );\n\n\n\n  //dqrng::dqRNGkind(\"Xoroshiro128+\");\n  //dqrng::dqset_seed(IntegerVector::create(seed));\n\n  //use following with binomial?\n  //dqrng::xoshiro256plus rng(seed);\n\n  std::vector<double> lambdavec = {lambda, 1-lambda};\n\n  //typedef boost::mt19937 RNGType;\n  //boost::random::uniform_int_distribution<> sample_splitvardist(1,num_split_vars);\n  //boost::variate_generator< RNGType, boost::uniform_int<> >  sample_splitvars(rng, sample_splitvardist);\n\n  //boost::random::uniform_real_distribution<double> b_unifdist(0,1);\n  //boost::variate_generator< RNGType, boost::uniform_real<> >  b_unif_point(rng, b_unifdist);\n\n\n\n  std::random_device device;\n  //std::mt19937 gen(device());\n\n  //possibly use seed?\n  //// std::mt19937 gen(seed);\n\n  dqrng::xoshiro256plus gen(device());              // properly seeded rng\n\n  //dqrng::xoshiro256plus gen(seed);              // properly seeded rng\n\n\n\n\n  std::bernoulli_distribution coin_flip(lambda);\n\n\n  std::bernoulli_distribution coin_flip_even(0.5);\n\n  double spike_prob1;\n  if(s_t_hyperprior==1){\n    spike_prob1=a_s_t/(a_s_t + b_s_t);\n  }else{\n    spike_prob1=p_s_t;\n  }\n\n  std::bernoulli_distribution coin_flip_spike(spike_prob1);\n\n\n  std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n  std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n  std::poisson_distribution<int> gen_num_term(lambda_poisson);\n\n\n  //dqrng::uniform_distribution dis_cont_unif(0.0, 1.0); // Uniform distribution [0,1)\n\n  //Following three functions can't be used in parallel\n  //dqrng::dqsample_int coin_flip2(2, 1, true,lambdavec );\n  //dqrng::dqsample_int distsampvar(num_split_vars, 1, true);\n  //dqrng::dqrunif dis_cont_unif(1, 0, 1);\n\n\n\n  //arma::mat arma_test_data(testdat_trans.begin(), testdat_trans.nrow(), testdat_trans.ncol(), false);\n\n\n  arma::vec pred_vec_overall;\n  if(is_test_data==1){\n    pred_vec_overall=arma::zeros<arma::vec>(x_with_ones_test.n_rows);\n  }else{\n    pred_vec_overall=arma::zeros<arma::vec>(x_with_z.n_rows);\n  }\n\n\n\n  //arma::field<arma::mat> overall_treetables(num_models);\n\n  //::field<arma::vec> overall_preds(num_models);\n\n  arma::vec overall_liks(num_models);\n\n  int numobstemp0;\n  if(is_test_data==1){\n    numobstemp0=num_test_obs;\n  }else{\n    numobstemp0=num_obs;\n  }\n\n  arma::mat overall_preds(numobstemp0,num_models);\n  arma::mat t_vars_arma(numobstemp0,num_models);\n\n  arma::vec cate_means_arma(num_models);\n  arma::vec cate_vars_arma(num_models);\n\n\n  arma::vec averagingvec;\n\n  if(is_test_data==1){\n    averagingvec=(1/double(num_test_obs))*arma::ones<arma::vec>(num_test_obs);\n  }else{\n    averagingvec=(1/double(num_obs))*arma::ones<arma::vec>(num_obs);\n  }\n\n\n  //overall_treetables[i]= wrap(tree_table1);\n  //double templik = as<double>(treepred_output[1]);\n  //overall_liks[i]= pow(lik_prod,beta_pow);\n\n  //Rcout << \"Line 3338. \\n\";\n\n\n#pragma omp parallel num_threads(ncores)\n{//start of pragma omp code\n  dqrng::xoshiro256plus lgen(gen);      // make thread local copy of rng\n  lgen.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... ncores jumps\n\n#pragma omp for\n  for(int j=0; j<num_models;j++){\n    // Rcout << \"Line 14666 .\\n\";\n\n    arma::mat Wmat(num_obs,0);\n    arma::mat Wmat1(num_obs,0);\n    arma::mat Wmat0(num_obs,0);\n\n    //maybe use line below, depends how Jmat joined to Wmat\n    //int upsilon=0;\n\n    //arma::mat W_tilde(num_test_obs,0);\n    arma::mat W_tilde1(num_test_obs,0);\n    arma::mat W_tilde0(num_test_obs,0);\n\n    //maybe use line below, depends how Jmat joined to Wmat\n    //int upsilon2=0;\n\n    //double sum_tree_samp_prob=1;\n    //double sum_tree_prior_prob=1;\n\n    double sum_prior_over_samp_prob=1;\n\n    for(int q=0; q<num_trees;q++){  //start of loop over trees in sum\n\n\n      //If parallelizing, define the distributinos before this loop\n      //and use lrng and the following two lines\n      //dqrng::xoshiro256plus lrng(rng);      // make thread local copy of rng\n      //lrng.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... nthreads jumps\n\n\n      //NumericVector treenodes_bin(0);\n      //arma::uvec treenodes_bin(0);\n\n      std::vector<int> treenodes_bin;\n      std::vector<int> split_var_vec;\n\n\n      int count_terminals = 0;\n      int count_internals = 0;\n\n      //int count_treebuild = 0;\n\n      if(imp_sampler==2){ // If sampling from Spike and Tree\n\n        //// Rcout << \"Line 3737 .\\n\";\n\n\n        //make coinflip_spike before loop\n        //also make bernoulli with probability 0.5\n\n        //make a poisson distribtion\n\n\n        //might be easier to store indices as armadillo vector, because will have to remove\n        //potential splits when allocating to terminal nodes\n        std::vector<int> potentialsplitvars;\n\n        for(int varcount=0; varcount<num_vars;varcount++){\n          bool tempflip=coin_flip_spike(lgen);\n          if(tempflip==TRUE){\n            potentialsplitvars.push_back(varcount);\n          }\n        }\n\n        //Then draw number of terminal nodes from a truncated Poisson\n        //must be at least equal to number of potential splitting variables plus 1\n        int q_numsplitvars=potentialsplitvars.size();\n\n        int num_term_nodes_draw;\n        if(q_numsplitvars==0){\n          //num_term_nodes_draw==1;\n          treenodes_bin.push_back(0);\n          split_var_vec.push_back(0);\n        }else{\n          do{\n            num_term_nodes_draw = gen_num_term(lgen);//Poissondraw\n          }\n          while(num_term_nodes_draw<q_numsplitvars+1); //Check if enough terminal nodes. If not, take another draw\n\n\n          //Now draw a tree with num_term_nodes_draw terminal nodes\n          //Use Remy's algorithm or the algorithm described by Bacher et al.\n\n          //Rcout << \"Line 3771 .\\n\";\n\n          long length=(num_term_nodes_draw-1)*2;\n          //Rcout << \"Line 3774 .\\n\";\n\n          std::vector<int> treenodes_bintemp(length+1);\n          int p_ind=0;\n          long height = 0;\n\n          //Rcout << \"Line 195. \\n\";\n          //Rcout << \"Line 3781 .\\n\";\n          //Rcout << \"q_numsplitvars = \" << q_numsplitvars << \".\\n\";\n\n          for(long i = 0; i < length+1; i ++) {\n            //signed char x = random_int(1) ? 1 : -1;\n            int x = coin_flip_even(lgen) ? 1 : -1;\n            treenodes_bintemp[i] = x;\n            height += x;\n\n            if(height < 0) {\n              // this should return a uniform random integer between 0 and x\n              //unsigned long random_int(unsigned long x);\n              std::uniform_int_distribution<> random_int(0, i);\n              long j = random_int(lgen);\n              //long j = random_int(i);\n              //height += unfold(p_ind + j,treenodes_bintemp, i + 1 - j);\n\n              long length1=i+1-j;\n              long height1 = 0;\n              long local_height = 0;\n              int x = 1;\n\n              for(long i = 0; i < length1; i ++) {\n                int y = treenodes_bintemp[p_ind+j+i];\n                local_height += y;\n                if(local_height < 0) {\n                  y = 1;\n                  height1 += 2;\n                  local_height = 0;\n                }\n                treenodes_bintemp[p_ind+j+i] = x;\n                x = y;\n              }\n              height +=height1;\n\n\n\n\n            }\n          }\n\n          //Rcout << \"Line 213. \\n\";\n          //Rcout << \"Line 3822 .\\n\";\n\n\n          //fold(treenodes_bintemp, length + 1, height);\n          long local_height = 0;\n          int x = -1;\n          ////Rcout << \"Line 121. \\n\";\n          //Rcout << \"treenodes_bintemp.size() =\" << treenodes_bintemp.size() << \". \\n\";\n          //Rcout << \"length - 1 =\" << length - 1 << \". \\n\";\n\n\n          for(long i = length; height > 0; i --) {\n            int y = treenodes_bintemp[i];\n            local_height -= y;\n            if(local_height < 0) {\n              y = -1;\n              height -= 2;\n              local_height = 0;\n            }\n            treenodes_bintemp[i] = x;\n            x = y;\n          }\n          //Rcout << \"Line 134. \\n\";\n\n\n          //Rcout << \"Line 217. \\n\";\n          //Rcout << \"Line 3847 .\\n\";\n\n          //Rcout << \"Line 238. \\n\";\n          std::replace(treenodes_bintemp.begin(), treenodes_bintemp.end(), -1, 0); // 10 99 30 30 99 10 10 99\n\n\n          // Then store tree structure as treenodes_bintemp\n\n          //create splitting variable vector\n          std::vector<int> splitvar_vectemp(treenodes_bintemp.size());\n\n          std::vector<int> drawnvarstemp(num_term_nodes_draw-1);\n\n          //keep count of how many splitting points have been filled in\n          int splitcount=0;\n\n          //loop through nodes, filling in splitting variables for nonterminal nodes\n          //when less than q_numsplitvars remaining internal nodes to be filled in\n          //have to start reducing the set of potential splitting variables\n          //to ensure that each selected potential split variable is used at least once. [hence the if statement containing .erase]\n\n          int index_remaining=0;\n          for(unsigned int nodecount=0; nodecount<treenodes_bintemp.size();nodecount++){\n            if(treenodes_bintemp[nodecount]==1){\n              splitcount++;\n              //Rcout << \"potentialsplitvars.size() = \" <<  potentialsplitvars.size() << \" .\\n\";\n\n              //Rcout << \"potentialsplitvars.size()-1 = \" <<  potentialsplitvars.size()-1 << \" .\\n\";\n              if(splitcount>num_term_nodes_draw-1-q_numsplitvars){//CHECK THIS CONDITION\n                //To ensure each variable used at least once, fill in the rest of the splits with all the variables\n                //The split variables will be randomly shuffled anyway, therefore the order is not important here.\n                drawnvarstemp[splitcount-1]=potentialsplitvars[index_remaining]+1;\n                index_remaining++;\n              }else{\n                //randomly draw a splitting varaible from the set of potential splitting variables\n                std::uniform_int_distribution<> draw_var(0,potentialsplitvars.size()-1);//q_numsplitvars-splitcount could replace potentialsplitvars.size()\n                int tempsplitvar = draw_var(lgen);\n                drawnvarstemp[splitcount-1]=potentialsplitvars[tempsplitvar]+1;\n\n              }\n\n              //if(splitcount>num_term_nodes_draw-1-q_numsplitvars){//CHECK THIS CONDITION\n              //  potentialsplitvars.erase(potentialsplitvars.begin()+tempsplitvar);\n              //}\n\n            }else{//if not a split\n              //splitvar_vectemp[nodecount]=-1;\n            }\n          }\n\n          std::shuffle(drawnvarstemp.begin(),drawnvarstemp.end(),lgen);\n\n          splitcount=0;\n          for(unsigned int nodecount=0; nodecount<treenodes_bintemp.size();nodecount++){\n            if(treenodes_bintemp[nodecount]==1){\n              splitvar_vectemp[nodecount]=drawnvarstemp[splitcount];\n              splitcount++;\n            }else{//if not a split\n              splitvar_vectemp[nodecount]=-1;\n            }\n          }\n\n          //Rcout << \"Line 3876 .\\n\";\n          split_var_vec=splitvar_vectemp;\n          treenodes_bin=treenodes_bintemp;\n        }\n      }else{\n        if(imp_sampler==1){ //If sampling from BART prior\n\n          //std::bernoulli_distribution coin_flip2(lambda);\n          double depth1=0;\n          int prev_node=0; //1 if previous node splits, zero otherwise\n\n          double samp_prob;\n\n          while(count_internals > (count_terminals -1)){\n            samp_prob=alpha_BART*pow(double(depth1+1),-beta_BART);\n            std::bernoulli_distribution coin_flip2(samp_prob);\n\n            int tempdraw = coin_flip2(lgen);\n            treenodes_bin.push_back(tempdraw);\n\n            if(tempdraw==1){\n\n              depth1=depth1+1; //after a split, the depth will increase by 1\n              prev_node=1;\n              count_internals=count_internals+1;\n\n            }else{\n\n              if(prev_node==1){//zero following a 1, therefore at same depth.\n                //Don't change depth. Do nothing\n              }else{ //zero following a zero, therefore the depth will decrease by 1\n                depth1=depth1-1;\n              }\n              prev_node=0;\n              count_terminals=count_terminals+1;\n\n            }\n\n          }\n\n        }else{  //If not sampling from BART prior\n          //If sampling from default Q+G prior. i.e. not sampling from BART nor spike and tree prior\n\n          while(count_internals > (count_terminals -1)){\n\n            //Also consider standard library and random header\n            // std::random_device device;\n            // std::mt19937 gen(device());\n            // std::bernoulli_distribution coin_flip(lambda);\n            // bool outcome = coin_flip(gen);\n\n\n            int tempdraw = coin_flip(lgen);\n\n            //int tempdraw = rbinom(n = 1, prob = lambda,size=1);\n\n\n            //int tempdraw = Rcpp::rbinom(1,lambda,1);\n            //int tempdraw = R::rbinom(1,lambda);\n\n            ////Rcout << \"tempdraw = \" << tempdraw << \".\\n\" ;\n\n            //int tempdraw = coin_flip2(lgen)-1;\n\n            //int tempdraw = dqrng::dqsample_int(2, 1, true,lambdavec )-1;\n\n\n            //need to update rng if use boost?\n            //int tempdraw = bernoulli(rng, binomial::param_type(1, lambda));\n\n            treenodes_bin.push_back(tempdraw);\n\n\n            if(tempdraw==1){\n              count_internals=count_internals+1;\n            }else{\n              count_terminals=count_terminals+1;\n            }\n\n          }//end of while loop creating parent vector treenodes_bin\n        }//end of Q+H sampling else statement\n      }//end of not Spike and Tree sampler else statement\n\n      //Rcout << \"Line 3961 .\\n\";\n\n\n      if(imp_sampler==2){\n        //already filled in splitting variable above for spike and tree prior\n      }else{\n        //Consider making this an armadillo vector\n        //IntegerVector split_var_vec(treenodes_bin.size());\n        //arma::uvec split_var_vec(treenodes_bin.size());\n        std::vector<int> split_var_vectemp(treenodes_bin.size());\n\n        // possibly faster alternative\n        //    split_var_vec.reserve( treenodes_bin.size() );\n        // then push_back elements to split_var_vec in the for loop\n\n        //loop drawing splitting variables\n        //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n        //if using armadillo, it might be faster to subset to split nodes\n        //then use a vector of draws\n        for(unsigned int i=0; i<treenodes_bin.size();i++){\n          if(treenodes_bin[i]==0){\n            split_var_vectemp[i] = -1;\n          }else{\n            // also consider the standard library function uniform_int_distribution\n            // might need random header\n            // This uses the Mersenne twister\n\n            //Three lines below should probably be outside all the loops\n            // std::random_device rd;\n            // std::mt19937 engine(rd());\n            // std::uniform_int_distribution<> distsampvar(1, num_split_vars);\n            //\n            // split_var_vec[i] = distsampvar(engine);\n\n            split_var_vectemp[i] = distsampvar(lgen);\n\n\n            //consider using boost\n            //might need to update rng\n            //split_var_vec[i] <- sample_splitvars(rng);\n\n            //or use dqrng\n            //not sure if have to update the random number\n            //check if the following line is written properly\n            //split_var_vec[i] = dqrng::dqsample_int(num_split_vars, 1, true);\n\n            //not sure if this returns an integer or a vector?\n            //split_var_vec[i] = RcppArmadillo::sample(num_split_vars, 1,true);\n            //could try\n            //split_var_vec[i] = as<int>(Rcpp::sample(num_split_vars, 1,true));\n            //could also try RcppArmadillo::rmultinom\n\n          }\n\n        }// end of for-loop drawing split variables\n\n        split_var_vec=split_var_vectemp;\n      }//end else statrement filling in splitting variable vector\n\n      //Consider making this an armadillo vector\n      //NumericVector split_point_vec(treenodes_bin.size());\n      //arma::vec split_point_vec(treenodes_bin.size());\n      std::vector<double> split_point_vec(treenodes_bin.size());\n\n\n      //loop drawing splitting points\n      //REPLACE SQUARE BRACKETS WITH \"( )\" if using ARMADILLO vector for split_var_vec or treenodes_bin\n\n      //if using armadillo, it might be faster to subset to split nodes\n      //then use a vector of draws\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        if(treenodes_bin[i]==0){\n          split_point_vec[i] = -1;\n        }else{\n\n\n          //////////////////////////////////////////////////////////\n          //following function not reccommended\n          //split_point_vec[i] = std::rand();\n          //////////////////////////////////////////////////////////\n          ////Standard library:\n          ////This should probably be outside all the loops\n          ////std::random_device rd;  //Will be used to obtain a seed for the random number engine\n          ////std::mt19937 gen2(rd()); //Standard mersenne_twister_engine seeded with rd()\n          ////std::uniform_real_distribution<> dis_cont_unif(0, 1);\n\n          split_point_vec[i] = dis_cont_unif(lgen);\n\n          //////////////////////////////////////////////////////////\n          //from armadillo\n          //split_point_vec[i] = arma::randu();\n\n          //////////////////////////////////////////////////////////\n          //probably not adviseable for paralelization\n          //From Rcpp\n          //split_point_vec[i] = as<double>(Rcpp::runif(1,0,1));\n\n          //////////////////////////////////////////////////////////\n          //consider using boost\n          //might need to update rng\n          //split_point_vec[i] <- b_unif_point(rng);\n\n          //or use dqrng\n          //not sure if have to update the random number\n          //check if the following line is written properly\n          //split_point_vec[i] = dqrng::dqrunif(1, 0, 1);\n\n          //not sure if this returns an integer or a vector?\n\n\n\n\n\n        }\n\n      }// end of for-loop drawing split points\n\n\n\n      //Rcout << \"Line 4081 .\\n\";\n\n\n      //CODE FOR ADJUSTING SPLITTING POINTS SO THAT THE TREES ARE VALID\n      if(valid_trees==1){\n        for(unsigned int i=0; i<treenodes_bin.size();i++){ //loop over all nodes\n          if(treenodes_bin[i]==1){ // if it is an internal node, then check for further splits on the same variable and update\n            double first_split_var=split_var_vec[i];      //splitting variable to check for\n            double first_split_point=split_point_vec[i];  //splitting point to use in updates\n\n            double sub_int_nodes=0;       //this internal node count will be used to determine if in subtree relevant to sub_int_nodes\n            double sub_term_nodes=0;      //this terminal node count will be used to determine if in subtree relevant to sub_int_nodes\n            double preventing_updates=0; //indicates if still within subtree that is not to be updated\n            double prevent_int_count=0;   //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n            double prevent_term_count=0;  //this internal node count will be used to determine if in sub-sub-tree that is not to be updated within the k loop\n            for(unsigned int k=i+1; k<treenodes_bin.size();k++){\n              if(treenodes_bin[k]==1){\n                sub_int_nodes=sub_int_nodes+1;\n                if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                  prevent_int_count=prevent_int_count+1;\n                }\n              }else{\n                sub_term_nodes=sub_term_nodes+1;\n                if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                  prevent_term_count=prevent_term_count+1;\n                }\n              }\n              if(sub_int_nodes<=sub_term_nodes-2){\n                break;\n              }\n\n\n              if(preventing_updates==1){ //indicates if still within subtree that is not to be updated\n                if(prevent_int_count>prevent_term_count-1){ //if this rule is satisfied then in subtree that is not to be updated\n                  continue; //still in subtree, therefore continue instead of checking for splits to be updates\n                }else{\n                  preventing_updates=0; // no longer in subtree, therefore reset preventing_updates to zero\n                }\n              }\n\n\n              if(sub_int_nodes>sub_term_nodes-1){\n                if(treenodes_bin[k]==1){\n                  if(split_var_vec[k]==first_split_var){\n                    split_point_vec[k]=split_point_vec[k]*first_split_point;\n                    //beginning count of subtree that should not have\n                    //further splits on first_split_var updated\n                    preventing_updates=1; //indicates if still within subtree that is not to be updated\n                    prevent_int_count=1;\n                    prevent_term_count=0;\n                  }\n                }\n              }else{\n                if(treenodes_bin[k]==1){\n                  if(split_var_vec[k]==first_split_var){\n                    split_point_vec[k]=split_point_vec[k]+first_split_point-first_split_point*split_point_vec[k];\n                    //beginning count of subtree that should not have\n                    //further splits on first_split_var updated\n                    preventing_updates=1; //indicates if still within subtree that is not to be updated\n                    prevent_int_count=1;\n                    prevent_term_count=0;\n                  }\n                }\n              }\n\n\n\n            }//end of inner loop over k\n          }//end of if statement treenodes_bin[i]==1)\n        }//end of loop over i\n      }//end of if statement valid_trees==1\n\n\n\n\n\n      //Rcout << \"Line 4161 .\\n\";\n\n\n\n\n\n      //Create tree table matrix\n\n      //NumericMatrix tree_table1(treenodes_bin.size(),5+num_cats);\n\n      ////Rcout << \"Line 1037. \\n\";\n      //arma::mat tree_table1(treenodes_bin.size(),5+num_cats);\n\n      //initialize with zeros. Not sure if this is necessary\n      arma::mat tree_table1=arma::zeros<arma::mat>(treenodes_bin.size(),6);\n      //Rcout << \"Line 1040. \\n\";\n\n\n      //tree_table1(_,2) = wrap(split_var_vec);\n      //tree_table1(_,3) = wrap(split_point_vec);\n      //tree_table1(_,4) = wrap(treenodes_bin);\n\n\n\n      //It might be more efficient to make everything an armadillo object initially\n      // but then would need to replace push_back etc with a different approach (but this might be more efficient anyway)\n      arma::colvec split_var_vec_arma=arma::conv_to<arma::colvec>::from(split_var_vec);\n      //arma::colvec split_point_vec_arma(split_point_vec);\n      //arma::colvec split_point_vec_arma(split_point_vec);\n      arma::colvec split_point_vec_arma=arma::conv_to<arma::colvec>::from(split_point_vec);\n\n      arma::colvec treenodes_bin_arma=arma::conv_to<arma::colvec>::from(treenodes_bin);\n\n      //Rcout << \"split_var_vec_arma = \" << split_var_vec_arma << \" . \\n\";\n\n      //Rcout << \"split_point_vec_arma = \" << split_point_vec_arma << \" . \\n\";\n\n      //Rcout << \"treenodes_bin_arma = \" << treenodes_bin_arma << \" . \\n\";\n\n\n      //Rcout << \"Line 1054. \\n\";\n\n      //Fill in splitting variable column\n      tree_table1.col(2) = split_var_vec_arma;\n      //Fill in splitting point column\n      tree_table1.col(3) = split_point_vec_arma;\n      //Fill in split/parent column\n      tree_table1.col(4) = treenodes_bin_arma;\n\n\n      //Rcout << \"Line 4200. j = \" << j << \". \\n\";\n\n      ////Rcout << \"Line 4081 .\\n\";\n\n\n      // Now start filling in left daughter and right daughter columns\n      std::vector<int> rd_spaces;\n      int prev_node = -1;\n\n      for(unsigned int i=0; i<treenodes_bin.size();i++){\n        ////Rcout << \"Line 1061. i = \" << i << \". \\n\";\n        if(prev_node==0){\n          //tree_table1(rd_spaces[rd_spaces.size()-1], 1)=i;\n          //Rcout << \"Line 1073. j = \" << j << \". \\n\";\n\n          tree_table1(rd_spaces.back(), 1)=i+1;\n          //Rcout << \"Line 1076. j = \" << j << \". \\n\";\n\n          rd_spaces.pop_back();\n        }\n        if(treenodes_bin[i]==1){\n          //Rcout << \"Line 1081. j = \" << j << \". \\n\";\n\n          tree_table1(i,0) = i+2;\n          rd_spaces.push_back(i);\n          prev_node = 1;\n          //Rcout << \"Line 185. j = \" << j << \". \\n\";\n\n        }else{                  // These 2 lines unnecessary if begin with matrix of zeros\n          //Rcout << \"Line 1089. j = \" << j << \". \\n\";\n          tree_table1(i,0)=0 ;\n          tree_table1(i,1) = 0 ;\n          prev_node = 0;\n          //Rcout << \"Line 1093. j = \" << j << \". \\n\";\n\n        }\n      }//\n      //Rcout << \"Line 1097. j = \" << j << \". \\n\";\n\n\n\n\n      //Rcout << \"Line 4242 .\\n\";\n\n      //List treepred_output = get_treepreds(original_y, num_cats, alpha_pars,\n      //                                     originaldata,\n      //                                     treetable_list[i]  );\n\n\n      //use armadillo object tree_table1\n\n      ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n      ////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n      //create variables for likelihood calcuations\n      // double lik_prod=1;\n      // double alph_prod=1;\n      // for(unsigned int i=0; i<alpha_pars_arma.n_elem;i++){\n      //   alph_prod=alph_prod*tgamma(alpha_pars_arma(i));\n      // }\n      // double gam_alph_sum= tgamma(arma::sum(alpha_pars_arma));\n      // double alph_term=gam_alph_sum/alph_prod;\n\n      //arma::mat arma_tree_table(treetable.begin(), treetable.nrow(), treetable.ncol(), false);\n      //arma::mat arma_orig_data(originaldata.begin(), originaldata.nrow(), originaldata.ncol(), false);\n\n\n      //arma::mat arma_tree(tree_data.begin(), tree_data.nrow(), tree_data.ncol(), false);\n      //arma::mat testd(test_data.begin(), test_data.nrow(), test_data.ncol(), false);\n\n      //NumericVector internal_nodes=find_internal_nodes_gs(tree_data);\n\n      //NumericVector terminal_nodes=find_term_nodes(treetable);\n\n      //arma::mat arma_tree(tree_table.begin(),tree_table.nrow(), tree_table.ncol(), false);\n\n      //arma::vec colmat=arma_tree.col(4);\n      //arma::uvec term_nodes=arma::find(colmat==-1);\n\n      //arma::vec colmat=arma_tree.col(2);\n      //arma::uvec term_nodes=arma::find(colmat==0);\n\n      //arma::vec colmat=tree_table1.col(4);\n      //arma::uvec term_nodes=arma::find(colmat==0);\n\n      //4th column is treenodes_bin_arma\n      arma::uvec term_nodes=arma::find(treenodes_bin_arma==0);\n\n      term_nodes=term_nodes+1;\n\n      //NumericVector terminal_nodes= wrap(term_nodes);\n\n\n\n      //GET J MATRIX\n\n      arma::mat Jmat(num_obs,term_nodes.n_elem);\n      //arma::mat Jtilde(num_test_obs,term_nodes.n_elem);\n\n      arma::mat Jmat1(num_obs,term_nodes.n_elem);\n      arma::mat Jtilde1(num_test_obs,term_nodes.n_elem);\n\n      arma::mat Jmat0(num_obs,term_nodes.n_elem);\n      arma::mat Jtilde0(num_test_obs,term_nodes.n_elem);\n\n      //arma::vec arma_terminal_nodes=Rcpp::as<arma::vec>(terminal_nodes);\n      //NumericVector tree_predictions;\n\n      //now for each internal node find the observations that belong to the terminal nodes\n\n      //NumericVector predictions(test_data.nrow());\n      //List term_obs(term_nodes.n_elem);\n\n      //GET J MATRIX\n\n      //Rcout << \"Line 4311 .\\n\";\n\n      if(term_nodes.n_elem==1){\n        //double nodemean=tree_data(terminal_nodes[0]-1,5);\t\t\t\t// let nodemean equal tree_data row terminal_nodes[i]^th row , 6th column. The minus 1 is because terminal nodes consists of indices starting at 1, but need indices to start at 0.\n        //predictions=rep(nodemean,test_data.nrow());\n        //Rcout << \"Line 67 .\\n\";\n\n        //IntegerVector temp_obsvec = seq_len(test_data.nrow())-1;\n        //term_obs[0]= temp_obsvec;\n        //double denom_temp= orig_y_arma.n_elem+arma::sum(alpha_pars_arma);\n\n        //double num_prod=1;\n        //double num_sum=0;\n        //Rcout << \"Line 129.\\n\";\n        Jmat.col(0) = arma::ones<arma::vec>(num_obs);\n\n\n        if(is_test_data==1){\n          //Jtilde.col(0) = arma::ones<arma::vec>(num_test_obs);\n          Jtilde1.col(0) = arma::ones<arma::vec>(num_test_obs);\n          Jtilde0.col(0) = arma::ones<arma::vec>(num_test_obs);\n        }else{\n          Jmat1.col(0) = arma::ones<arma::vec>(num_obs);\n          Jmat0.col(0) = arma::ones<arma::vec>(num_obs);\n\n        }\n\n        //for(int k=0; k<num_cats; k++){\n        //assuming categories of y are from 1 to num_cats\n        //arma::uvec cat_inds= arma::find(orig_y_arma==k+1);\n        //double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n        //tree_table1(0,5+k)= m_plus_alph/denom_temp ;\n\n        //for likelihood calculation\n        //num_prod=num_prod*tgamma(m_plus_alph);\n        //num_sum=num_sum +m_plus_alph ;\n        //}\n\n        //lik_prod= alph_term*num_prod/tgamma(num_sum);\n\n      }\n      else{\n        for(unsigned int i=0;i<term_nodes.n_elem;i++){\n          //arma::mat subdata=testd;\n          //int curr_term=term_nodes(i);\n\n          int row_index;\n          int term_node=term_nodes(i);\n          //Rcout << \"Line 152.\\n\";\n\n\n          //WHAT IS THE PURPOSE OF THIS IF-STATEMENT?\n          //Why should the ro index be different for a right daughter?\n          //Why not just initialize row_index to any number not equal to 1 (e.g. 0)?\n          row_index=0;\n\n          // if(curr_term % 2==0){\n          //   //term node is left daughter\n          //   row_index=terminal_nodes[i];\n          // }else{\n          //   //term node is right daughter\n          //   row_index=terminal_nodes[i]-1;\n          // }\n\n\n\n\n          //save the left and right node data into arma uvec\n\n          //CHECK THAT THIS REFERS TO THE CORRECT COLUMNS\n          //arma::vec left_nodes=arma_tree.col(0);\n          //arma::vec right_nodes=arma_tree.col(1);\n\n          arma::vec left_nodes=tree_table1.col(0);\n          arma::vec right_nodes=tree_table1.col(1);\n\n\n\n          arma::mat node_split_mat;\n          node_split_mat.set_size(0,3);\n          //Rcout << \"Line 182. i = \" << i << \" .\\n\";\n\n          while(row_index!=1){\n            //for each terminal node work backwards and see if the parent node was a left or right node\n            //append split info to a matrix\n            int rd=0;\n            arma::uvec parent_node=arma::find(left_nodes == term_node);\n\n            if(parent_node.size()==0){\n              parent_node=arma::find(right_nodes == term_node);\n              rd=1;\n            }\n\n            //want to cout parent node and append to node_split_mat\n\n            node_split_mat.insert_rows(0,1);\n\n            //CHECK THAT COLUMNS OF TREETABLE ARE CORRECT\n            //node_split_mat(0,0)=treetable(parent_node[0],2);\n            //node_split_mat(0,1)=treetable(parent_node[0],3);\n\n            //node_split_mat(0,0)=arma_tree_table(parent_node[0],3);\n            //node_split_mat(0,1)=arma_tree_table(parent_node[0],4);\n\n            node_split_mat(0,0)=tree_table1(parent_node(0),2);\n            node_split_mat(0,1)=tree_table1(parent_node(0),3);\n\n            node_split_mat(0,2)=rd;\n            row_index=parent_node(0)+1;\n            term_node=parent_node(0)+1;\n          }\n\n          //once we have the split info, loop through rows and find the subset indexes for that terminal node!\n          //then fill in the predicted value for that tree\n          //double prediction = tree_data(term_node,5);\n          arma::uvec pred_indices;\n          arma::uvec pred_indices1;\n          arma::uvec pred_indices0;\n          arma::uvec pred_test_indices1;\n          arma::uvec pred_test_indices0;\n\n          arma::uvec temp_pred_indices;\n          arma::uvec temp_pred_indices1;\n          arma::uvec temp_pred_indices0;\n          arma::uvec temp_test_pred_indices1;\n          arma::uvec temp_test_pred_indices0;\n\n          //arma::vec data_subset = testd.col(split);\n          arma::vec data_subset;\n          arma::vec data_subset1;\n          arma::vec data_subset0;\n          arma::vec data_test_subset1;\n          arma::vec data_test_subset0;\n\n          int split= node_split_mat(0,0)-1;\n\n          //Rcout << \"Line 224.\\n\";\n          //Rcout << \"split = \" << split << \".\\n\";\n          //arma::vec tempvec = testd.col(split);\n          //Rcout << \"Line 227.\\n\";\n\n\n          double temp_split = node_split_mat(0,1);\n\n          // if(node_split_mat(0,2)==0){\n          //   pred_indices = arma::find(tempvec <= temp_split);\n          //   pred_test_indices = arma::find(temptest_vec <= temp_split);\n          // }else{\n          //   pred_indices = arma::find(tempvec > temp_split);\n          //   pred_test_indices = arma::find(temptest_vec > temp_split);\n          // }\n          //Rcout << \"Line 236.\\n\";\n\n\n\n\n\n          if(is_test_data==1){\n            data_subset = x_with_z.col(split);\n            data_test_subset1 = x_with_ones_test.col(split);\n            data_test_subset0 = x_with_zeros_test.col(split);\n\n\n\n            arma::vec tempvec = x_with_z.col(split);\n            arma::vec temptest_vec1 = x_with_ones_test.col(split);\n            arma::vec temptest_vec0 = x_with_zeros_test.col(split);\n\n            if(node_split_mat(0,2)==0){\n              pred_indices = arma::find(tempvec <= temp_split);\n              pred_test_indices1 = arma::find(temptest_vec1 <= temp_split);\n              pred_test_indices0 = arma::find(temptest_vec0 <= temp_split);\n            }else{\n              pred_indices = arma::find(tempvec > temp_split);\n              pred_test_indices1 = arma::find(temptest_vec1 > temp_split);\n              pred_test_indices0 = arma::find(temptest_vec0 > temp_split);\n            }\n\n            data_subset=data_subset.elem(pred_indices);\n            data_test_subset1=data_test_subset1.elem(pred_test_indices1);\n            data_test_subset0=data_test_subset0.elem(pred_test_indices0);\n\n          }else{\n            data_subset = x_with_z.col(split);\n            data_subset1 = x_with_ones.col(split);\n            data_subset0 = x_with_zeros.col(split);\n\n\n\n            arma::vec tempvec = x_with_z.col(split);\n            arma::vec tempvec1 = x_with_ones.col(split);\n            arma::vec tempvec0 = x_with_zeros.col(split);\n\n            if(node_split_mat(0,2)==0){\n              pred_indices = arma::find(tempvec <= temp_split);\n              pred_indices1 = arma::find(tempvec1 <= temp_split);\n              pred_indices0 = arma::find(tempvec0 <= temp_split);\n            }else{\n              pred_indices = arma::find(tempvec > temp_split);\n              pred_indices1 = arma::find(tempvec1 > temp_split);\n              pred_indices0 = arma::find(tempvec0 > temp_split);\n            }\n\n            data_subset=data_subset.elem(pred_indices);\n            data_subset1=data_subset1.elem(pred_indices1);\n            data_subset0=data_subset0.elem(pred_indices0);\n\n          }\n\n\n          //now loop through each row of node_split_mat\n          int n=node_split_mat.n_rows;\n          //Rcout << \"Line 174. i = \" << i << \". n = \" << n << \".\\n\";\n          //Rcout << \"Line 248.\\n\";\n\n          for(int j=1;j<n;j++){\n            int curr_sv=node_split_mat(j,0);\n            double split_p = node_split_mat(j,1);\n\n            if(is_test_data==1){\n              data_subset = x_with_z.col(curr_sv-1);\n              data_test_subset1 = x_with_ones_test.col(curr_sv-1);\n              data_test_subset0 = x_with_zeros_test.col(curr_sv-1);\n\n              data_subset=data_subset.elem(pred_indices);\n              data_test_subset1=data_test_subset1.elem(pred_test_indices1);\n              data_test_subset0=data_test_subset0.elem(pred_test_indices0);\n\n              if(node_split_mat(j,2)==0){\n                //split is to the left\n                temp_pred_indices=arma::find(data_subset <= split_p);\n                temp_test_pred_indices1=arma::find(data_test_subset1 <= split_p);\n                temp_test_pred_indices0=arma::find(data_test_subset0 <= split_p);\n              }else{\n                //split is to the right\n                temp_pred_indices=arma::find(data_subset > split_p);\n                temp_test_pred_indices1=arma::find(data_test_subset1 > split_p);\n                temp_test_pred_indices0=arma::find(data_test_subset0 > split_p);\n              }\n\n              pred_indices=pred_indices.elem(temp_pred_indices);\n              pred_test_indices1=pred_test_indices1.elem(temp_test_pred_indices1);\n              pred_test_indices0=pred_test_indices0.elem(temp_test_pred_indices0);\n\n\n            }else{\n              data_subset = x_with_z.col(curr_sv-1);\n              data_subset1 = x_with_ones.col(curr_sv-1);\n              data_subset0 = x_with_zeros.col(curr_sv-1);\n\n              data_subset=data_subset.elem(pred_indices);\n              data_subset1=data_subset1.elem(pred_indices1);\n              data_subset0=data_subset0.elem(pred_indices0);\n\n              if(node_split_mat(j,2)==0){\n                //split is to the left\n                temp_pred_indices=arma::find(data_subset <= split_p);\n                temp_pred_indices1=arma::find(data_subset1 <= split_p);\n                temp_pred_indices0=arma::find(data_subset0 <= split_p);\n              }else{\n                //split is to the right\n                temp_pred_indices=arma::find(data_subset > split_p);\n                temp_pred_indices1=arma::find(data_subset1 > split_p);\n                temp_pred_indices0=arma::find(data_subset0 > split_p);\n              }\n\n              pred_indices=pred_indices.elem(temp_pred_indices);\n              pred_indices1=pred_indices1.elem(temp_pred_indices1);\n              pred_indices0=pred_indices0.elem(temp_pred_indices0);\n\n            }\n\n\n            //if(pred_indices.size()==0){\n            //  continue;\n            //}\n\n          }//end of for loop of length n\n          //Rcout << \"Line 199. i = \" << i <<  \".\\n\";\n\n          //There is probably a more efficient way of doing this\n          //e.g. initialize J matrix so that all elements are equal to zero\n          arma::vec tempcol_J=arma::zeros<arma::vec>(num_obs);\n          tempcol_J(pred_indices) = arma::ones<arma::vec>(pred_indices.size());\n          Jmat.col(i) = tempcol_J;\n\n          if(is_test_data==1){\n            arma::vec tempcol_Jtilde1=arma::zeros<arma::vec>(num_test_obs);\n            tempcol_Jtilde1(pred_test_indices1) = arma::ones<arma::vec>(pred_test_indices1.size());\n            Jtilde1.col(i) = tempcol_Jtilde1;\n\n            arma::vec tempcol_Jtilde0=arma::zeros<arma::vec>(num_test_obs);\n            tempcol_Jtilde0(pred_test_indices0) = arma::ones<arma::vec>(pred_test_indices0.size());\n            Jtilde0.col(i) = tempcol_Jtilde0;\n\n\n          }else{\n            arma::vec tempcol_J1=arma::zeros<arma::vec>(num_obs);\n            tempcol_J1(pred_indices1) = arma::ones<arma::vec>(pred_indices1.size());\n            Jmat1.col(i) = tempcol_J1;\n\n            arma::vec tempcol_J0=arma::zeros<arma::vec>(num_obs);\n            tempcol_J0(pred_indices0) = arma::ones<arma::vec>(pred_indices0.size());\n            Jmat0.col(i) = tempcol_J0;\n\n          }\n\n          //double nodemean=tree_data(terminal_nodes[i]-1,5);\n          //IntegerVector predind=as<IntegerVector>(wrap(pred_indices));\n          //predictions[predind]= nodemean;\n          //term_obs[i]=predind;\n\n          //double denom_temp= pred_indices.n_elem+arma::sum(alpha_pars_arma);\n          //Rcout << \"Line 207. predind = \" << predind <<  \".\\n\";\n          //Rcout << \"Line 207. denom_temp = \" << denom_temp <<  \".\\n\";\n          // << \"Line 207. term_node = \" << term_node <<  \".\\n\";\n\n          //double num_prod=1;\n          //double num_sum=0;\n\n          // for(int k=0; k<num_cats; k++){\n          //   //assuming categories of y are from 1 to num_cats\n          //   arma::uvec cat_inds= arma::find(orig_y_arma(pred_indices)==k+1);\n          //   double m_plus_alph=cat_inds.n_elem +alpha_pars_arma(k);\n          //\n          //   tree_table1(curr_term-1,5+k)= m_plus_alph/denom_temp ;\n          //\n          //   num_prod=num_prod*tgamma(m_plus_alph);\n          //   num_sum=num_sum +m_plus_alph ;\n          // }\n          //\n          //\n          // lik_prod= lik_prod*alph_term*num_prod/tgamma(num_sum);\n          //Rcout << \"Line 297.\\n\";\n\n\n        }//End of loop over terminal nodes.\n      }// end of else statement (for when more than one terminal node)\n      // Now have J matrix\n\n      //Rcout << \"Line 4530 .\\n\";\n\n      Wmat=join_rows(Wmat,Jmat);\n      //or\n      //Wmat.insert_cols(Wmat.n_cols,Jmat);\n      //or\n      //int b_j=term_nodes.n_elem;\n      //Wmat.insert_cols(upsilon,Jmat);\n      //upsilon+=b_j;\n\n\n      //Obtain test W_tilde, i.e. W matrix for test data\n      if(is_test_data==1){\n        W_tilde1=join_rows(W_tilde1,Jtilde1);\n        W_tilde0=join_rows(W_tilde0,Jtilde0);\n\n      }else{\n        Wmat1=join_rows(Wmat1,Jmat1);\n        Wmat0=join_rows(Wmat0,Jmat0);\n\n      }\n\n\n\n      //or\n      //W_tilde.insert_cols(W_tilde.n_cols,Jtilde);\n      //or\n      //int b_jtest=term_nodes.n_elem;\n      //W_tilde.insert_cols(upsilon2,Jtilde);\n      //upsilon2+=b_jtest;\n\n      //Rcout << \"Line 4551 .\\n\";\n\n      if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n        // //get impportance sampler probability and tree prior\n        // long double temp_samp_prob;\n        // long double temp_prior_prob;\n        // //get sampler tree probability\n        // if(imp_sampler==1){//If sample from BART prior\n        //\n        //\n        //\n        //   temp_samp_prob=1;\n        //\n        //   double depth1=0;\n        //   int prev_node=0; //1 if previous node splits, zero otherwise\n        //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n        //     if(treenodes_bin[i_2]==1){\n        //       temp_samp_prob=temp_samp_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n        //       depth1=depth1+1; //after a split, the depth will increase by 1\n        //       prev_node=1;\n        //     }else{\n        //       temp_samp_prob=temp_samp_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n        //       if(prev_node==1){//zero following a 1, therefore at same depth.\n        //         //Don't change depth. Do nothing\n        //       }else{ //zero following a zero, therefore the depth will decrease by 1\n        //         depth1=depth1-1;\n        //       }\n        //       prev_node=0;\n        //\n        //     }\n        //   }\n        //\n        //   //end of calculating BART tree probability\n        // }else{\n        //   if(imp_sampler==2){//If sample from spike and tree prior\n        //     throw std::range_error(\"code not yet written for spike and tree prior\");\n        //\n        //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n        //     double tempexp1=treenodes_bin.size()-arma::sum(treenodes_bin_arma);\n        //     double tempexp2=arma::sum(treenodes_bin_arma);\n        //     temp_samp_prob=pow(lambda,tempexp2)*\n        //       pow(1-lambda,tempexp1);\n        //       //(1/pow(double(num_split_vars),tempexp2));\n        //\n        //       temp_samp_prob=exp(log(lambda)*tempexp2+\n        //         log(1-lambda)*tempexp1);\n        //\n        //     //temp_samp_prob=pow(lambda,arma::sum(treenodes_bin_arma))*\n        //     //  pow(1-lambda,treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n        //     //  pow((1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n        //   }\n        // }\n        //\n        // sum_tree_samp_prob=sum_tree_samp_prob*temp_samp_prob;\n        // //end of getting importance sampler probability\n        //\n        // //get prior tree probability\n        // if(tree_prior==1){//If sample from BART prior\n        //\n        //\n        //\n        //   temp_prior_prob=1;\n        //\n        //   double depth1=0;\n        //   int prev_node=0; //1 if previous node splits, zero otherwise\n        //   for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n        //\n        //     if(treenodes_bin[i_2]==1){\n        //       temp_prior_prob=temp_prior_prob*alpha_BART*pow(double(depth1+1),-beta_BART);\n        //       depth1=depth1+1; //after a split, the depth will increase by 1\n        //       prev_node=1;\n        //     }else{\n        //       temp_prior_prob=temp_prior_prob*(1-alpha_BART*pow(double(depth1+1),-beta_BART));\n        //       if(prev_node==1){//zero following a 1, therefore at same depth.\n        //         //Don't change depth. Do nothing\n        //       }else{ //zero following a zero, therefore the depth will decrease by 1\n        //         depth1=depth1-1;\n        //       }\n        //       prev_node=0;\n        //\n        //     }\n        //     //if(alpha_BART==0){\n        //     //  //Rcout << \"alpha_BART equals zero!!!!.\\n\";\n        //     //}\n        //   }\n        //\n        //   //end of calculating BART tree probability\n        // }else{\n        //   if(tree_prior==2){//If sample from spike and tree prior\n        //     throw std::range_error(\"code not yet written for spike and tree prior\");\n        //\n        //   }else{//otherwise sampling from Quadrianto and Ghahramani prior\n        //     temp_prior_prob=pow((long double)(lambda),arma::sum(treenodes_bin_arma))*\n        //       pow((long double)(1-lambda),treenodes_bin.size()-arma::sum(treenodes_bin_arma))*\n        //       pow((long double)(1/double(num_split_vars)),arma::sum(treenodes_bin_arma));\n        //   }\n        // }\n        //\n        // sum_tree_prior_prob=sum_tree_prior_prob*temp_prior_prob;\n        // if(temp_prior_prob==0){\n        //   Rcout << \"Line 4097, j= \" << j << \". \\n\";\n        //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        // }\n        // if(temp_samp_prob==0){\n        //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n        //   Rcout << \"temp_prior_prob= \" << temp_prior_prob << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        // }\n        //\n        // if(sum_tree_samp_prob==0){\n        //   Rcout << \"Line 4102, j= \" << j << \". \\n\";\n        //   Rcout << \"sum_tree_samp_prob= \" << sum_tree_samp_prob << \". \\n\";\n        //   //Rcout << \"treenodes_bin_arma= \" << treenodes_bin_arma << \". \\n\";\n        //   Rcout << \"temp_samp_prob= \" << temp_samp_prob << \". \\n\";\n        //\n        // }\n\n\n\n\n        //get tree prior over impportance sampler probability\n        double tree_prior_over_samp_prob=1;\n        if(imp_sampler==1){   //If sample from BART prior\n          if(tree_prior==1){  //If tree prior is BART prior\n            /////////////////////////////////////////////////////////////////////////////////////////\n            throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n            /////////////////////////////////////////////////////////////////////////////////////////\n          }else{// not BART prior (and sampler is BART)\n            if(tree_prior==2){  //If tree prior is spike-and-tree prior (and sampler is BART)\n              //throw std::range_error(\"code not yet written for spike and tree prior\");\n              /////////////////////////////////////////////////////////////////////////////////////////\n\n\n              //arma::uvec internal_nodes_prop=find_internal_nodes(tree_table);\n              //arma::mat tree_table2(tree_table.begin(),tree_table.nrow(),tree_table.ncol(),false);\n              //arma::mat arma_tree(treetable.begin(),treetable.nrow(), treetable.ncol(), false);\n              //arma::vec colmat=arma_tree.col(4);\n              //arma::uvec internal_nodes_prop=arma::find(treenodes_bin_arma==1);\n              //internal_nodes_prop=internal_nodes_prop+1;\n\n              //double k_temp=internal_nodes_prop.size()+1;\n              //arma::mat split_var_rows=tree_table2.rows\n\n              //split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n\n\n              arma::vec split_var_vectemp=split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n              double k_temp=split_var_vectemp.size()+1;\n              arma::vec uniquesplitvars=arma::unique(split_var_vectemp);\n              double q_temp=uniquesplitvars.n_elem;\n\n              //FIRST CALCULATE THE log of denom and right_truncatin\n              //Then take the exponential\n              //then take the difference\n              double denom=1;\n              for(int i=0; i<q_temp+1;i++){\n                //denom= denom-(pow(lambda_poisson,double(i))*exp(-lambda_poisson)/double(tgamma(i+1)));\n                denom = denom-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n              }\n              double right_truncation=1;\n              for(int i=0; i<num_obs+1;i++){\n                //right_truncation= right_truncation-(pow(lambda_poisson,double(i))*std::exp(-lambda_poisson)/double(tgamma(i+1)));\n                right_truncation= right_truncation-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n              }\n              //Rcout << \" right_truncation= \" << right_truncation << \".\\n\";\n              denom=denom-right_truncation;\n\n\n              double propsplit;\n\n              if(q_temp==0){\n                if(s_t_hyperprior==1){\n                  propsplit=//(1/double(num_vars+1))*\n                    exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  // tree_prior_over_samp_prob=  propsplit/\n                  //   BART_prior*\n                  //     pow(1/num_vars,arma::sum(treenodes_bin_arma));\n                }else{\n                  propsplit=//(1/double(num_vars+1))*\n                    exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  // tree_prior_over_samp_prob=  propsplit/\n                  //   BART_prior*\n                  //     pow(1/num_vars,arma::sum(treenodes_bin_arma));\n\n                }\n              }else{\n                if(s_t_hyperprior==1){\n                  propsplit=//(1/double(num_vars+1))*\n                    exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                    (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                       -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                       +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                       +std::lgamma(num_obs)\n                       -std::lgamma(k_temp)\n                       -std::lgamma(num_obs-k_temp) ));\n\n                       //(std::lgamma(num_obs)+(k_temp-1-q_temp)*log(q_temp)+\n                       //std::lgamma(q_temp+1)-(std::lgamma(num_obs-k_temp+1))));\n                       //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                       // tree_prior_over_samp_prob=  propsplit/\n                       //   BART_prior*\n                       //     pow(1/num_vars,arma::sum(treenodes_bin_arma));\n                }else{\n                  propsplit=//(1/double(num_vars+1))*\n                    exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                    (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                       -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                       +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                       +std::lgamma(num_obs)\n                       -std::lgamma(k_temp)\n                       -std::lgamma(num_obs-k_temp) ));\n                       //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n\n                       // tree_prior_over_samp_prob=  propsplit/\n                       //   BART_prior*\n                       //     pow(1/num_vars,arma::sum(treenodes_bin_arma));\n                }\n              }\n\n              tree_prior_over_samp_prob=propsplit;\n              //first get BART prior for tree structure\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              //double BART_prior=1;\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob/((alpha_BART*pow(double(depth1+1),-beta_BART)));\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob/((1-alpha_BART*pow(double(depth1+1),-beta_BART)));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }//close (zero node) else stattement\n\n              }//end for loop over i_2\n\n\n\n\n              /////////////////////////////////////////////////////////////////////////////////////////\n            }else{ //prior is Q+H  //(sampler is BART)\n              /////////////////////////////////////////////////////////////////////////////////////////\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*(lambda/(alpha_BART*pow(double(depth1+1),-beta_BART)));\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-lambda)/(1-alpha_BART*pow(double(depth1+1),-beta_BART)));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }\n              }\n              /////////////////////////////////////////////////////////////////////////////////////////\n            }//close Q+H prior (with BART sampler)\n          }//close not BART prior (with BART sampler)\n        }else{// if not sampling from BART sampler\n          if(imp_sampler==2){//If sample from spike and tree prior\n            //throw std::range_error(\"code not yet written for sampling from spike and tree prior\");\n\n            if(tree_prior==1){//prior is BART (sampler is spike and tree)\n              /////////////////////////////////////////////////////////////////////////////////////////\n              //first get BART prior for tree structure\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              double BART_prior=1;\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  BART_prior=BART_prior*((alpha_BART*pow(double(depth1+1),-beta_BART)));\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  BART_prior=BART_prior*((1-alpha_BART*pow(double(depth1+1),-beta_BART)));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }//close (zero node) else stattement\n\n              }//end for loop over i_2\n\n              arma::vec split_var_vectemp=split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n              double k_temp=split_var_vectemp.size()+1;\n              arma::vec uniquesplitvars=arma::unique(split_var_vectemp);\n              double q_temp=uniquesplitvars.n_elem;\n\n              //FIRST CALCULATE THE log of denom and right_truncatin\n              //Then take the exponential\n              //then take the difference\n              double denom=1;\n              for(int i=0; i<q_temp+1;i++){\n                //denom= denom-(pow(lambda_poisson,double(i))*exp(-lambda_poisson)/double(tgamma(i+1)));\n                denom = denom-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n              }\n              double right_truncation=1;\n              for(int i=0; i<num_obs+1;i++){\n                //right_truncation= right_truncation-(pow(lambda_poisson,double(i))*std::exp(-lambda_poisson)/double(tgamma(i+1)));\n                right_truncation= right_truncation-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n              }\n              //Rcout << \" right_truncation= \" << right_truncation << \".\\n\";\n              denom=denom-right_truncation;\n\n              if(q_temp==0){\n                if(s_t_hyperprior==1){\n                  double propsplit=//(1/double(num_vars+1))*\n                    exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  tree_prior_over_samp_prob= BART_prior*\n                    pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n                }else{\n                  double propsplit=//(1/double(num_vars+1))*\n                    exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                  //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                  tree_prior_over_samp_prob=  BART_prior*\n                    pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                }\n              }else{\n                if(s_t_hyperprior==1){\n                  double propsplit=//(1/double(num_vars+1))*\n                    exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                    (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                       -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                       +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                       +std::lgamma(num_obs)\n                       -std::lgamma(k_temp)\n                       -std::lgamma(num_obs-k_temp) ));\n                       //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                       tree_prior_over_samp_prob=  BART_prior*\n                       pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n                }else{\n                  double propsplit=//(1/double(num_vars+1))*\n                    exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                    q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                    k_temp*log(lambda_poisson)-\n                    lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                    (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                       -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                       +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                       +std::lgamma(num_obs)\n                       -std::lgamma(k_temp)\n                       -std::lgamma(num_obs-k_temp) ));\n                       //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n\n                       tree_prior_over_samp_prob=  BART_prior*\n                       pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n                }\n              }\n              /////////////////////////////////////////////////////////////////////////////////////////\n            }else{\n              if(tree_prior==2){//prior is spike and tree, sampler is spike and tree\n                /////////////////////////////////////////////////////////////////////////////////////////\n                throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n                /////////////////////////////////////////////////////////////////////////////////////////\n              }else{//prior is Q+H, sampler is spike and tree\n                /////////////////////////////////////////////////////////////////////////////////////////\n                arma::vec split_var_vectemp=split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n                double k_temp=split_var_vectemp.size()+1;\n                arma::vec uniquesplitvars=arma::unique(split_var_vectemp);\n                double q_temp=uniquesplitvars.n_elem;\n\n                //FIRST CALCULATE THE log of denom and right_truncatin\n                //Then take the exponential\n                //then take the difference\n\n                double denom=1;\n                for(int i=0; i<q_temp+1;i++){\n                  //denom= denom-(pow(lambda_poisson,double(i))*exp(-lambda_poisson)/double(tgamma(i+1)));\n                  denom = denom-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n                }\n                double right_truncation=1;\n                for(int i=0; i<num_obs+1;i++){\n                  //right_truncation= right_truncation-(pow(lambda_poisson,double(i))*std::exp(-lambda_poisson)/double(tgamma(i+1)));\n                  right_truncation= right_truncation-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n                }\n                //Rcout << \" right_truncation= \" << right_truncation << \".\\n\";\n                denom=denom-right_truncation;\n\n                if(q_temp==0){\n                  if(s_t_hyperprior==1){\n                    double propsplit=//(1/double(num_vars+1))*\n                      exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                    //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                    tree_prior_over_samp_prob=  pow(lambda,arma::sum(treenodes_bin_arma))*\n                      pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                      pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                  }else{\n                    double propsplit=//(1/double(num_vars+1))*\n                      exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                    //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                    tree_prior_over_samp_prob=  pow(lambda,arma::sum(treenodes_bin_arma))*\n                      pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                      pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                  }\n\n                }else{\n                  if(s_t_hyperprior==1){\n                    double propsplit=//(1/double(num_vars+1))*\n                      exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                      (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                         -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                         +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                         +std::lgamma(num_obs)\n                         -std::lgamma(k_temp)\n                         -std::lgamma(num_obs-k_temp) ));\n                         //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                         tree_prior_over_samp_prob=  pow(lambda,arma::sum(treenodes_bin_arma))*\n                         pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                         pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                  }else{\n                    double propsplit=//(1/double(num_vars+1))*\n                      exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                      (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                         -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                         +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                         +std::lgamma(num_obs)\n                         -std::lgamma(k_temp)\n                         -std::lgamma(num_obs-k_temp) ));\n\n                         tree_prior_over_samp_prob=  pow(lambda,arma::sum(treenodes_bin_arma))*\n                         pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                         pow(1/num_vars,arma::sum(treenodes_bin_arma))/propsplit;\n\n                  }\n                }\n                /////////////////////////////////////////////////////////////////////////////////////////\n              }//finish if sampler is spike tree and prior is Q+H\n            }//finish all possibiilities for spike and tree sampler\n\n          }else{//otherwise sampling from Quadrianto and Ghahramani prior\n            if(tree_prior==1){  //If tree prior is BART prior (and sampler is Q+H)\n              /////////////////////////////////////////////////////////////////////////////////////////\n              double depth1=0;\n              int prev_node=0; //1 if previous node splits, zero otherwise\n              for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                if(treenodes_bin[i_2]==1){\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((alpha_BART*pow(double(depth1+1),-beta_BART))/lambda);\n                  depth1=depth1+1; //after a split, the depth will increase by 1\n                  prev_node=1;\n                }else{\n                  tree_prior_over_samp_prob=tree_prior_over_samp_prob*((1-alpha_BART*pow(double(depth1+1),-beta_BART))/(1-lambda));\n                  if(prev_node==1){//zero following a 1, therefore at same depth.\n                    //Don't change depth. Do nothing\n                  }else{ //zero following a zero, therefore the depth will decrease by 1\n                    depth1=depth1-1;\n                  }\n                  prev_node=0;\n\n                }//close (zero node) else stattement\n\n              }//end for loop over i_2\n              /////////////////////////////////////////////////////////////////////////////////////////\n            }else{\n              if(tree_prior==2){  //If tree prior is spike-and-tree prior (and sampler is Q+H)\n                /////////////////////////////////////////////////////////////////////////////////////////\n                //throw std::range_error(\"code not yet written for spike and tree prior\");\n\n                arma::vec split_var_vectemp=split_var_vec_arma(arma::find(treenodes_bin_arma==1));\n                double k_temp=split_var_vectemp.size()+1;\n                arma::vec uniquesplitvars=arma::unique(split_var_vectemp);\n                double q_temp=uniquesplitvars.n_elem;\n\n                //FIRST CALCULATE THE log of denom and right_truncatin\n                //Then take the exponential\n                //then take the difference\n\n                double denom=1;\n                for(int i=0; i<q_temp+1;i++){\n                  //denom= denom-(pow(lambda_poisson,double(i))*exp(-lambda_poisson)/double(tgamma(i+1)));\n                  denom = denom-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n                }\n                double right_truncation=1;\n                for(int i=0; i<num_obs+1;i++){\n                  //right_truncation= right_truncation-(pow(lambda_poisson,double(i))*std::exp(-lambda_poisson)/double(tgamma(i+1)));\n                  right_truncation= right_truncation-exp(i*log(lambda_poisson)-lambda_poisson-std::lgamma(double(i+1)));\n                }\n                //Rcout << \" right_truncation= \" << right_truncation << \".\\n\";\n                denom=denom-right_truncation;\n\n\n                double propsplit;\n\n                if(q_temp==0){\n                  if(s_t_hyperprior==1){\n                    propsplit=//(1/double(num_vars+1))*\n                      exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                    //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                    // tree_prior_over_samp_prob=  propsplit/\n                    //   (pow(lambda,arma::sum(treenodes_bin_arma))*\n                    //     pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                    //     pow(1/num_vars,arma::sum(treenodes_bin_arma)));\n\n                  }else{\n                    propsplit=//(1/double(num_vars+1))*\n                      exp(std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom)  ;\n                    //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                    // tree_prior_over_samp_prob=  propsplit/\n                    //   (pow(lambda,arma::sum(treenodes_bin_arma))*\n                    //     pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                    //     pow(1/num_vars,arma::sum(treenodes_bin_arma)));\n\n                  }\n\n                }else{\n                  if(s_t_hyperprior==1){\n                    propsplit=//(1/double(num_vars+1))*\n                      exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      std::lgamma(q_temp+a_s_t)+std::lgamma(num_vars-q_temp+b_s_t)-std::lgamma(num_vars+a_s_t+b_s_t)+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                      (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                         -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                         +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                         +std::lgamma(num_obs)\n                         -std::lgamma(k_temp)\n                         -std::lgamma(num_obs-k_temp) ));\n                         //Rcout << \" propsplit= \" << propsplit << \".\\n\";\n                         // tree_prior_over_samp_prob=  propsplit/\n                         //   (pow(lambda,arma::sum(treenodes_bin_arma))*\n                         //     pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                         //     pow(1/num_vars,arma::sum(treenodes_bin_arma)));\n\n                  }else{\n                    propsplit=//(1/double(num_vars+1))*\n                      exp(  std::lgamma(num_vars+1)-std::lgamma(q_temp+1)-std::lgamma(num_vars-q_temp+1)+\n                      q_temp*log(p_s_t)+(num_vars-q_temp)*log(1-(p_s_t))+\n                      k_temp*log(lambda_poisson)-\n                      lambda_poisson-std::lgamma(k_temp+1)-denom  -\n                      (std::lgamma(2*(k_temp-1)+1)-std::lgamma(k_temp+1)\n                         -std::lgamma(k_temp)+std::lgamma(q_temp+1)\n                         +std::log(secondKindStirlingNumber(k_temp-1,q_temp))\n                         +std::lgamma(num_obs)\n                         -std::lgamma(k_temp)\n                         -std::lgamma(num_obs-k_temp) ));\n\n                         // tree_prior_over_samp_prob=  propsplit/\n                         //   (pow(lambda,arma::sum(treenodes_bin_arma))*\n                         //     pow(1-lambda,treenodes_bin_arma.size()-arma::sum(treenodes_bin_arma))*\n                         //     pow(1/num_vars,arma::sum(treenodes_bin_arma)));\n\n                  }\n                }\n                tree_prior_over_samp_prob=propsplit;\n\n                double depth1=0;\n                int prev_node=0; //1 if previous node splits, zero otherwise\n                for(unsigned int i_2=0; i_2<treenodes_bin.size();i_2++){\n                  if(treenodes_bin[i_2]==1){\n                    tree_prior_over_samp_prob=tree_prior_over_samp_prob/lambda;\n                    depth1=depth1+1; //after a split, the depth will increase by 1\n                    prev_node=1;\n                  }else{\n                    tree_prior_over_samp_prob=tree_prior_over_samp_prob/(1-lambda);\n                    if(prev_node==1){//zero following a 1, therefore at same depth.\n                      //Don't change depth. Do nothing\n                    }else{ //zero following a zero, therefore the depth will decrease by 1\n                      depth1=depth1-1;\n                    }\n                    prev_node=0;\n\n                  }//close (zero node) else stattement\n\n                }//end for loop over i_2\n\n\n\n\n                /////////////////////////////////////////////////////////////////////////////////////////\n              }else{//if prior is Q+H (and sampler is Q+H)\n                /////////////////////////////////////////////////////////////////////////////////////////\n                throw std::range_error(\"The code should not calculate the ratio of probabilities if sampler equals prior\");\n                /////////////////////////////////////////////////////////////////////////////////////////\n              }//close (not BART nor spike and tree prior) else statement\n            }// close (not BART prior) else statememt\n\n          }//close all Q+H sampler code (not sampling from BART or spike and tree)  else statement\n\n        }//close (not sampling from BART) else statement\n\n        sum_prior_over_samp_prob=sum_prior_over_samp_prob*tree_prior_over_samp_prob;\n        //end of getting tree prior over impportance sampler probability\n\n        // if(sum_prior_over_samp_prob==0){\n        //   Rcout << \"Line 4266, j= \" << j << \". \\n\";\n        //   Rcout << \"Line 4267, q= \" << q << \". \\n\";\n        //   Rcout << \"sum_prior_over_samp_prob= \" << sum_prior_over_samp_prob << \". \\n\";\n        //\n        // }else{\n        //   Rcout << \"Line 4266, j= \" << j << \". \\n\";\n        //   Rcout << \"Line 4267, q= \" << q << \". \\n\";\n        //   Rcout << \"sum_prior_over_samp_prob= \" << sum_prior_over_samp_prob << \". \\n\";\n        // }\n\n      }//end of tree prior and importance sampler calculations\n\n\n    } //end of loop over trees in sum\n\n\n    //Obtain W matrix. If more than one tree in sum, need to join J matrices, possibly in loop over model trees above\n    // i.e. add a loop from just within the start of the outer loop to here of length equal to the number of trees within the model\n    // Create a Wmat with zero columns at start of loop, and join the Jmat at the end of each loop\n\n    //for now, testing a one-tree model\n    //replace Jmat with Wmat later\n\n\n    //Obtain likelihood\n\n    // Rcout << \"Line 16375 .\\n\";\n\n    double b=Wmat.n_cols;\n\n\n    // CURRENTLY CAN'T OBTAIN COVARIANCE MATRIX WITH FAST APPROXIMATION APPROACH\n    // Perhaps it is possible to obtain the covariance while still using a fast approximaiton\n    // by using a fast SVD algorithm\n\n    // if(fast_approx==1){\n    //   arma::mat p = Wmat.t();\n    //   arma::rowvec r = orig_y_arma.t();\n    //\n    //   arma::mat cov = p * p.t() +a * arma::eye<arma::mat>(p.n_rows, p.n_rows);\n    //\n    //   arma::mat parameters = arma::solve(cov, p * r.t(), arma::solve_opts::fast);\n    //\n    //   arma::rowvec preds_temp_arma_t=arma::trans(parameters) * W_tilde.t();\n    //   arma::rowvec preds_insamp_arma=arma::trans(parameters) * p;\n    //\n    //   arma::vec preds_temp_arma= preds_temp_arma_t.t();\n    //\n    //   arma::vec tempresids=y-preds_insamp_arma.t();\n    //   double temp_sse= arma::dot(tempresids, tempresids);\n    //\n    //   //double templik0=exp(-b*0.5*log(num_obs)+log(temp_sse)*(-num_obs)*0.5);\n    //\n    //\n    //   //double templik0=exp(-b*0.5*log(num_obs)+log(temp_sse)*(-num_obs)*0.5);\n    //\n    //\n    //   //double templik0=exp(-0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs)))  ;\n    //\n    //   double templik0=(num_obs*log(temp_sse/num_obs)+b*log(num_obs))  ;\n    //\n    //   // //Rcout << \"num_obs= \" << num_obs << \". \\n\";\n    //   // //Rcout << \"b= \" << b << \". \\n\";\n    //   // Rcout << \"log(num_obs)= \" << log(num_obs) << \". \\n\";\n    //   // Rcout << \"log(temp_sse/num_obs)= \" << log(temp_sse/num_obs) << \". \\n\";\n    //   //Rcout << \"templik0= \" << templik0 << \". \\n\";\n    //   // Rcout << \"-0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs))= \" << -0.5*(num_obs*log(temp_sse/num_obs)+b*log(num_obs)) << \". \\n\";\n    //\n    //\n    //   //double templik = pow(templik0,beta_par);\n    //   double templik = beta_par*templik0;\n    //\n    //\n    //   if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n    //     //templik=templik*(sum_tree_prior_prob/sum_tree_samp_prob);\n    //     //templik=templik*sum_prior_over_samp_prob;\n    //     templik=templik+log(sum_prior_over_samp_prob);\n    //\n    //   }\n    //   overall_liks(j)= templik;\n    //\n    //   overall_preds(j)=preds_temp_arma;\n    //\n    // }else{\n\n\n\n    // ///////////////////////////////////\n    //get t(y)inv(psi)J\n    arma::mat ytW=y.t()*Wmat;\n    //get t(J)inv(psi)J\n    arma::mat WtW=Wmat.t()*Wmat;\n    //get jpsij +aI\n    arma::mat aI(b,b);\n    aI=a*aI.eye();\n    arma::mat sec_term=WtW+aI;\n    //arma::mat sec_term_inv=sec_term.i();\n    arma::mat sec_term_inv=inv_sympd(sec_term);\n    //get t(J)inv(psi)y\n    arma::mat third_term=Wmat.t()*y;\n    //get m^TV^{-1}m\n    arma::mat mvm= ytW*sec_term_inv*third_term;\n    //arma::mat rel=(b/2)*log(a)-(1/2)*log(det(sec_term))-expon*log(nu*lambdaBART - mvm +yty);\n    // /////////////////////////////////////////////\n\n\n    //\n    // Rcout << \"-b*0.5*log(num_obs)= \" << -b*0.5*log(num_obs) << \". \\n\";\n    // Rcout << \"log(temp_sse)*(-num_obs)*0.5= \" << log(temp_sse)*(-num_obs)*0.5 << \". \\n\";\n    //\n\n    //double templik0=pow(num_obs, -b*0.5)*pow(temp_sse,-num_obs*0.5);\n\n    //\n    //     arma::vec temppred1=Wmat*sec_term_inv*third_term;\n    //     arma::vec temperrors= y-temppred1;\n    //     arma::vec tempcoeffs= sec_term_inv*third_term;\n    //\n    //     double new_penalty= as_scalar(b*temppred1.t()*temppred1/(tempcoeffs.t()*tempcoeffs*(double(num_obs)-b)));\n    //\n    //     Rcout << \" new_penalty =\" << new_penalty << \".\\n\";\n\n\n    //double val1;\n    //double sign1;\n\n    //log_det(val1, sign1, sec_term);\n    //double templik0=exp(arma::as_scalar((b*0.5)*log(a)-0.5*val1-expon*log(nu*lambdaBART - mvm +yty)));\n\n\n    ////////////////////\n    //double templik0=exp(arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term))-expon*log(nu*lambdaBART - mvm +yty)));\n    //////////////\n    double templik0=arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term))-expon*log(nu*lambdaBART - mvm +yty));\n\n\n\n    //double templik0=exp(arma::as_scalar((b*0.5)*log(a)-0.5*log(det(sec_term))-expon*log(nu*lambdaBART - mvm +yty)));\n\n\n\n\n\n    //\n    //\n    //     arma::mat aI2(b,b);\n    //     aI2=new_penalty*aI2.eye();\n    //     arma::mat sec_term2=WtW+aI2;\n    //     //arma::mat sec_term_inv=sec_term.i();\n    //     arma::mat sec_term_inv2=inv_sympd(sec_term2);\n    //     //get t(J)inv(psi)y\n    //     //arma::mat third_term=Wmat.t()*y;\n    //     //get m^TV^{-1}m\n    //     arma::mat mvm2= ytW*sec_term_inv2*third_term;\n    //\n    //\n    //     double templik0=exp(arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term2))-expon*log(nu*lambdaBART - mvm2 +yty)));\n    //\n\n\n\n\n\n    // Rcout << \"log(temp_sse)= \" << log(temp_sse) << \". \\n\";\n    //\n    //\n    // Rcout << \"temp_sse= \" << temp_sse << \". \\n\";\n    //\n\n\n\n    // Rcout << \"templik0= \" << templik0 << \". \\n\";\n    //\n    //       Rcout << \"b= \" << b << \". \\n\";\n    //       Rcout << \"(b*0.5)*log(a)= \" << (b*0.5)*log(a) << \". \\n\";\n    //\n    //       Rcout << \"-0.5*log(det(sec_term))= \" << -0.5*log(det(sec_term)) << \". \\n\";\n    //       Rcout << \"det(sec_term)= \" << det(sec_term) << \". \\n\";\n    //       Rcout << \"arma::det(sec_term)= \" << arma::det(sec_term) << \". \\n\";\n    //       Rcout << \"arma::log_det(sec_term)= \" << arma::log_det(sec_term) << \". \\n\";\n    //       Rcout << \"real(arma::log_det(sec_term))= \" << real(arma::log_det(sec_term)) << \". \\n\";\n    //       Rcout << \"log(det(sec_term))= \" << log(det(sec_term)) << \". \\n\";\n    //       Rcout << \"log(arma::det(sec_term))= \" << log(arma::det(sec_term)) << \". \\n\";\n    //\n    //       Rcout << \"-expon*log(nu*lambdaBART - mvm +yty)= \" << -expon*log(nu*lambdaBART - mvm +yty) << \". \\n\";\n    //\n    //\n    //       // Rcout << \"val= \" << val << \". \\n\";\n    //\n    // Rcout << \"arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term))-expon*log(nu*lambdaBART - mvm +yty)) .\\n\" << arma::as_scalar((b*0.5)*log(a)-0.5*real(arma::log_det(sec_term))-expon*log(nu*lambdaBART - mvm +yty)) << \".\\n\";\n    //       ////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    //overall_treetables[j]= wrap(tree_table1);\n\n\n    //double templik = as<double>(treepred_output[1]);\n\n    //double templik = pow(templik0,beta_par);\n\n    double templik = beta_par*templik0;\n\n    if(imp_sampler!=tree_prior){//check if importance sampler is not equal to the prior\n      //templik=templik*(sum_tree_prior_prob/sum_tree_samp_prob);\n      //templik=templik*sum_prior_over_samp_prob;\n      templik=templik+log(sum_prior_over_samp_prob);\n\n    }\n    overall_liks(j)= templik;\n\n    // if(std::isnan(templik)){\n    // Rcout << \"Line 3943, j= \" << j << \". \\n\";\n    // Rcout << \"templik= \" << templik << \". \\n\";\n    // Rcout << \"sum_tree_prior_prob= \" << sum_tree_prior_prob << \". \\n\";\n    // Rcout << \"sum_tree_samp_prob= \" << sum_tree_samp_prob << \". \\n\";\n    // }\n\n\n    //now fill in the predictions\n\n    //If want tree tables with predictions filled in, use\n    // arma::vec term_node_par_means = sec_term_inv*third_term;\n    // //and would need to save a field of tree tables,\n    // //add add a column, or begin with one more column\n    // //then the first treetableF[0].n_rows elements of term_node_par_means\n    // //give the first\n    // int row_count1=0;\n    // for(int tree_i=0; tree_i < treetableF.n_elem; tree_i++){\n    //   tabletemp= treetableF(i);\n    //   tabletemp.col(5) = term_node_par_means(arma::span(row_count1,tabletemp.n_rows));\n    //   treetableF(i)=tabletemp;\n    //   row_count1+=tabletemp.n_rows;\n    // }\n    //This would give an alternative method for obtaining test data predictions\n    //Look up the terminal nodes and add the relevant terminal node parameters\n\n\n\n\n    if(is_test_data==1){\n      arma::mat Treat_diff = W_tilde1-W_tilde0;\n      arma::mat w_tilde_M_inv =  Treat_diff*sec_term_inv;\n      arma::vec preds_temp_arma= w_tilde_M_inv*third_term;\n      // Rcout << \"Line 16593\";\n\n      overall_preds.col(j)=preds_temp_arma;\n      arma::mat temp_for_scal = ((nu*lambdaBART+yty-mvm)/(nu+num_obs));\n      double temp_scal= as_scalar(temp_for_scal) ;\n      //Rcout << \"Line 4156\";\n      //arma::mat covar_t=temp_scal*(I_test+w_tilde_M_inv*(W_tilde.t()));\n      arma::mat covar_t=temp_scal*(w_tilde_M_inv*(Treat_diff.t()));\n\n      arma::mat catevartemp=temp_scal*(averagingvec.t()*w_tilde_M_inv*(Treat_diff.t())*averagingvec);\n\n      t_vars_arma.col(j)=covar_t.diag();\n      cate_means_arma(j)=as_scalar(averagingvec.t()*preds_temp_arma);\n      cate_vars_arma(j)=as_scalar(catevartemp);\n\n\n    }else{\n      arma::mat Treat_diff = Wmat1-Wmat0;\n      arma::mat w_tilde_M_inv =  Treat_diff*sec_term_inv;\n      arma::vec preds_temp_arma= w_tilde_M_inv*third_term;\n      // Rcout << \"Line 16613\";\n\n      overall_preds.col(j)=preds_temp_arma;\n      // Rcout << \"Line 16616\";\n\n      arma::mat temp_for_scal = ((nu*lambdaBART+yty-mvm)/(nu+num_obs));\n      double temp_scal= as_scalar(temp_for_scal) ;\n      //Rcout << \"Line 4156\";\n      //arma::mat covar_t=temp_scal*(I_test+w_tilde_M_inv*(W_tilde.t()));\n      arma::mat covar_t=temp_scal*(w_tilde_M_inv*(Treat_diff.t()));\n\n      arma::mat catevartemp=temp_scal*(averagingvec.t()*w_tilde_M_inv*(Treat_diff.t())*averagingvec);\n\n      // Rcout << \"Line 16626\";\n      t_vars_arma.col(j)=covar_t.diag();\n      cate_means_arma(j)=as_scalar(averagingvec.t()*preds_temp_arma);\n      cate_vars_arma(j)=as_scalar(catevartemp);\n      // Rcout << \"Line 16630\";\n\n\n    }\n\n    //arma::vec pred_vec(testdata_arma.n_rows);\n\n    ////////////\n    //arma::vec preds_temp_arma= W_tilde*sec_term_inv*third_term;\n\n    ////////////////////\n\n\n    // Rcout << \"Line 16634 .\\n\";\n\n\n\n    //arma::vec preds_temp_arma= W_tilde*sec_term_inv2*third_term;\n\n\n\n    //THIS SHOULD BE DIFFERENT IF THE CODE IS TO BE PARALLELIZED\n    //EACH THREAD SHOULD OUTPUT ITS OWN MATRIX AND SUM OF LIKELIHOODS\n    //THEN ADD THE MATRICES TOGETHER AND DIVIDE BY THE TOTAL SUM OF LIKELIHOODS\n    //OR JUST SAVE ALL MATRICES TO ONE LIST\n\n\n    //pred_mat_overall = pred_mat_overall + templik*pred_mat;\n    //overall_treetables(j)= pred_mat*templik;\n\n\n    //overall_preds(j)=preds_temp_arma*templik;\n\n    // overall_preds.col(j)=preds_temp_arma;\n    //\n    //\n    //\n    // arma::mat temp_for_scal = ((nu*lambdaBART+yty-mvm)/(nu+num_obs));\n    // double temp_scal= as_scalar(temp_for_scal) ;\n    // //// Rcout << \"Line 4156\";\n    // //arma::mat covar_t=temp_scal*(I_test+w_tilde_M_inv*(W_tilde.t()));\n    // arma::mat covar_t=temp_scal*(I_test+W_tilde*sec_term_inv*(W_tilde.t()));\n    //\n    // t_vars_arma.col(j)=covar_t.diag();\n\n\n    //Rcout << \"Line 3985, j= \" << j << \". \\n\";\n\n\n    //Rcout << \"preds_temp_arma= \" << preds_temp_arma << \". \\n\";\n    //Rcout << \"preds_temp_arma*templik= \" << preds_temp_arma*templik << \". \\n\";\n\n    //overall_treetables(j)= pred_mat;\n    //overall_liks(j) =templik;\n\n    //arma::mat treeprob_output = get_test_probs(weights, num_cats,\n    //                                           testdata,\n    //                                           treetable_list[i]  );\n\n    //Rcout << \"Line 688. i== \" << i << \". \\n\";\n\n    //double weighttemp = weights[i];\n    //Rcout << \"Line 691. i== \" << i << \". \\n\";\n\n    //pred_mat_overall = pred_mat_overall + weighttemp*treeprob_output;\n\n\n    //}//end of else statement\n  }//end of loop over all trees\n\n}//end of pragma omp code\n\n\n///////////////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////////////////////////////////////////////////////////////\n\n\n\n\n// Rcout << \"Line 16701 .\\n\";\n\n\n\ndouble cate_pred=0;\n//double catt_pred;\n//double catnt_pred;\n\n//NumericMatrix draws_wrapped= wrap(draws_for_preds);\n//arma::mat output(3, num_obs);\n//NumericVector probs_for_quantiles =  NumericVector::create(lower_prob, 0.5, upper_prob);\n\n//std::vector<double> probs_for_quantiles {lower_prob, 0.5, upper_prob};\narma::mat cate_ints(3, 1);\n\n\n//for(unsigned int i=0; i<overall_treetables.n_elem;i++){\n//  pred_mat_overall = pred_mat_overall + overall_liks(i)*overall_treetables(i);\n//}\n\n\n// if(fast_approx==1){\n//   arma::vec BICi=-0.5*overall_liks;\n//   double max_BIC=max(BICi);\n//\n//   // weighted_BIC is actually the posterior model probability\n//   arma::vec weighted_BIC(overall_liks.size());\n//\n//\n//   double tempterm=(max_BIC+log(sum(exp(BICi-max_BIC))));\n//\n//   for(unsigned int k=0;k<overall_liks.size();k++){\n//\n//     //NumericVector BICi=-0.5*BIC_weights;\n//     //double max_BIC=max(BICi);\n//     double weight=exp(BICi[k]-tempterm);\n//     weighted_BIC[k]=weight;\n//     //int num_its_to_sample = round(weight*(num_iter));\n//\n//   }\n//\n//   //Rcout << \"weighted_BIC= \" << weighted_BIC << \". \\n\";\n//   //Rcout << \"overall_liks= \" << overall_liks << \". \\n\";\n//\n// #pragma omp parallel num_threads(ncores)\n// {\n//   arma::vec result_private=arma::zeros<arma::vec>(arma_test_data.n_rows);\n// #pragma omp for nowait //fill result_private in parallel\n//   for(unsigned int i=0; i<overall_preds.size(); i++){\n//     //double weight=exp(BICi[i]-(max_BIC+log(sum(exp(BICi-max_BIC)))));\n//     result_private += overall_preds(i)*weighted_BIC(i);\n//   }\n// #pragma omp critical\n//   pred_vec_overall += result_private;\n// }\n//\n//\n// }else{ //if fast_approx==0\n\n//arma::vec BICi=-0.5*overall_liks;\ndouble max_loglik=max(overall_liks);\n\n// weighted_BIC is actually the posterior model probability\narma::vec weighted_lik(overall_liks.size());\n\n\ndouble tempterm=(max_loglik+log(sum(exp(overall_liks-max_loglik))));\n\nfor(unsigned int k=0;k<overall_liks.size();k++){\n\n  //NumericVector BICi=-0.5*BIC_weights;\n  //double max_BIC=max(BICi);\n  double weight=exp(overall_liks[k]-tempterm);\n  weighted_lik[k]=weight;\n  //int num_its_to_sample = round(weight*(num_iter));\n\n}\n\n//Rcout << \"weighted_lik= \" << weighted_lik << \". \\n\";\n//Rcout << \"overall_liks= \" << overall_liks << \". \\n\";\n\n#pragma omp parallel num_threads(ncores)\n{\n  arma::vec result_private;\n  double cate_result_private=0;\n\n  if(is_test_data==1){\n    result_private=arma::zeros<arma::vec>(x_control_test_a.n_rows);\n  }else{\n    result_private=arma::zeros<arma::vec>(x_control_a.n_rows);\n\n  }\n\n#pragma omp for nowait //fill result_private in parallel\n  for(unsigned int i=0; i<overall_preds.n_cols; i++){\n    result_private += overall_preds.col(i)*weighted_lik(i);\n    cate_result_private += cate_means_arma(i)*weighted_lik(i);\n  }\n#pragma omp critical\n  pred_vec_overall += result_private;\n  cate_pred += cate_result_private;\n\n}\n\n\n\nint num_obs_output;\nif(is_test_data==1){\n  num_obs_output=num_test_obs;\n}else{\n  num_obs_output=num_obs;\n}\n\n\narma::mat output(3, num_obs_output);\n\n\ntypedef std::vector<double> stdvec;\n//std::vector<double> weights_vec= as<stdvec>(post_weights);\nstd::vector<double> weights_vec= arma::conv_to<stdvec>::from(weighted_lik);\n\n\nboost::math::students_t dist2(nu+num_obs);\ndouble lq_tstandard= boost::math::quantile(dist2,lower_prob);\ndouble med_tstandard= boost::math::quantile(dist2,0.5); //This is just 0 ??\ndouble uq_tstandard= boost::math::quantile(dist2,upper_prob);\n\n\nif(weights_vec.size()==1){\n\n  cate_ints(0,0)= cate_means_arma(0)+sqrt(cate_vars_arma(0))*lq_tstandard;\n  cate_ints(1,0)= cate_means_arma(0)+sqrt(cate_vars_arma(0))*med_tstandard;\n  cate_ints(2,0)= cate_means_arma(0)+sqrt(cate_vars_arma(0))*uq_tstandard;\n\n#pragma omp parallel num_threads(ncores)\n#pragma omp for\n  for(int i=0;i<num_obs_output;i++){\n    std::vector<double> tempmeans= arma::conv_to<stdvec>::from(overall_preds.row(i));\n    std::vector<double> tempvars= arma::conv_to<stdvec>::from(t_vars_arma.row(i));\n\n    //boost::math::students_t dist2(nu+num_obs);\n\n\n    output(0,i)= tempmeans[0]+sqrt(tempvars[0])*lq_tstandard;\n    output(1,i)= tempmeans[0]+sqrt(tempvars[0])*med_tstandard;\n    output(2,i)= tempmeans[0]+sqrt(tempvars[0])*uq_tstandard;\n\n\n  }\n#pragma omp barrier\n}else{\n\n  std::vector<double> tempmeans_cate= arma::conv_to<stdvec>::from(cate_means_arma);\n  std::vector<double> tempvars_cate= arma::conv_to<stdvec>::from(cate_vars_arma);\n\n  std::vector<double> bounds_lQ_cate = mixt_find_boundsQ( nu+num_obs, tempmeans_cate, tempvars_cate, lq_tstandard);\n\n  //Rcout << \"line 13828 cate_vars_arma = \" << cate_vars_arma << \".\\n\";\n  //Rcout << \"cate_means_arma = \" << cate_means_arma << \".\\n\";\n\n  //Rcout << \"bounds_lQ_cate[0] = \" << bounds_lQ_cate[0] << \".\\n\";\n  //Rcout << \"bounds_lQ_cate[1] = \" << bounds_lQ_cate[1] << \".\\n\";\n\n  cate_ints(0,0)= rootmixt(nu+num_obs,\n            bounds_lQ_cate[0]-0.0001,\n            bounds_lQ_cate[1]+0.0001,\n            tempmeans_cate,\n            tempvars_cate,\n            weights_vec, lower_prob,root_alg_precision);\n\n  std::vector<double> bounds_med_cate = mixt_find_boundsQ( nu+num_obs, tempmeans_cate, tempvars_cate, med_tstandard);\n\n  //Rcout << \"bounds_lQ_cate[0] = \" << bounds_lQ_cate[0] << \".\\n\";\n  //Rcout << \"bounds_lQ_cate[1] = \" << bounds_lQ_cate[1] << \".\\n\";\n\n  cate_ints(1,0)= rootmixt(nu+num_obs,\n            bounds_med_cate[0]-0.0001,\n            bounds_med_cate[1]+0.0001,\n            tempmeans_cate,\n            tempvars_cate,\n            weights_vec, 0.5, root_alg_precision);\n\n  std::vector<double> bounds_uQ_cate = mixt_find_boundsQ( nu+num_obs, tempmeans_cate, tempvars_cate, uq_tstandard);\n\n  //Rcout << \"bounds_lQ_cate[0] = \" << bounds_lQ_cate[0] << \".\\n\";\n  //Rcout << \"bounds_lQ_cate[1] = \" << bounds_lQ_cate[1] << \".\\n\";\n\n  cate_ints(2,0)= rootmixt(nu+num_obs,\n            bounds_uQ_cate[0]-0.0001,\n            bounds_uQ_cate[1]+0.0001,\n            tempmeans_cate,\n            tempvars_cate,\n            weights_vec, upper_prob, root_alg_precision);\n\n#pragma omp parallel num_threads(ncores)\n#pragma omp for\n  for(int i=0;i<num_obs_output;i++){\n    //output(_,i)=Quantile(draws_wrapped(_,i), probs_for_quantiles);\n    std::vector<double> tempmeans= arma::conv_to<stdvec>::from(overall_preds.row(i));\n    std::vector<double> tempvars= arma::conv_to<stdvec>::from(t_vars_arma.row(i));\n\n\n    std::vector<double> bounds_lQ = mixt_find_boundsQ( nu+num_obs, tempmeans, tempvars, lq_tstandard);\n\n    output(0,i)=rootmixt(nu+num_obs,\n           bounds_lQ[0]-0.0001,\n           bounds_lQ[1]+0.0001,\n           tempmeans,\n           tempvars,\n           weights_vec, lower_prob,root_alg_precision);\n\n\n    std::vector<double> bounds_med = mixt_find_boundsQ( nu+num_obs, tempmeans, tempvars, med_tstandard);\n\n    output(1,i)=rootmixt(nu+num_obs,\n           bounds_med[0]-0.0001,\n           bounds_med[1]+0.0001,\n           tempmeans,\n           tempvars,\n           weights_vec, 0.5,root_alg_precision);\n\n    std::vector<double> bounds_uQ = mixt_find_boundsQ( nu+num_obs, tempmeans, tempvars, uq_tstandard);\n\n    output(2,i)=rootmixt(nu+num_obs,\n           bounds_uQ[0]-0.0001,\n           bounds_uQ[1]+0.0001,\n           tempmeans,\n           tempvars,\n           weights_vec, upper_prob,root_alg_precision);\n\n\n  }\n#pragma omp barrier\n}\n\n\narma::mat output_rescaled(output.n_rows, output.n_cols);\ndouble min_y=min(ytrain);\ndouble max_y=max(ytrain);\n\n#pragma omp parallel num_threads(ncores)\n#pragma omp for\nfor(unsigned int i=0;i<output.n_cols;i++){\n  output_rescaled.col(i)=get_original_TE_arma(min_y,max_y,-0.5,0.5, output.col(i));\n}\n#pragma omp barrier\n\narma::vec cate_ints_rescaled=get_original_TE_arma(min_y,max_y,-0.5,0.5, cate_ints.col(0));\n\nNumericVector orig_preds=get_original_TE(min_y,max_y,-0.5,0.5,wrap(pred_vec_overall));\n\ndouble orig_cate=get_original_TE_double(min_y,max_y,-0.5,0.5,cate_pred);\n\n\nList ret(4);\nret(0) = orig_preds;\nret(1) = wrap(output_rescaled);\nret(2) = orig_cate;\nret(3) = wrap(cate_ints_rescaled);\n\nreturn(ret);\n\n}\n", "meta": {"hexsha": "b8bdaf671c821f5e3453309b857c93802082603a", "size": 640848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/safeBART.cpp", "max_stars_repo_name": "guhjy/safeBart", "max_stars_repo_head_hexsha": "39c34f553659a2d4d5ff8a8f72a1a0b857cb1972", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/safeBART.cpp", "max_issues_repo_name": "guhjy/safeBart", "max_issues_repo_head_hexsha": "39c34f553659a2d4d5ff8a8f72a1a0b857cb1972", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/safeBART.cpp", "max_forks_repo_name": "guhjy/safeBart", "max_forks_repo_head_hexsha": "39c34f553659a2d4d5ff8a8f72a1a0b857cb1972", "max_forks_repo_licenses": ["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.7413427562, "max_line_length": 263, "alphanum_fraction": 0.5774941952, "num_tokens": 167624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5439376878563622}}
{"text": "//Link to Boost\n #define BOOST_TEST_DYN_LINK\n\n//VERY IMPORTANT - include this last\n#include <boost/test/unit_test.hpp>\n#include <boost/timer.hpp>\n\n#include <vector>\n#include <iostream>\n#include \"test.h\"\n#include \"../RandomAlgebricEquations.h\"\n#include \"../EquationSolver.h\"\nusing namespace std;\n\nBOOST_FIXTURE_TEST_SUITE(RandomAlgebricEquations_suite, SimpleTestFixture, * utf::label(\"RandomAlgebricEquations\"))\n\nBOOST_DATA_TEST_CASE(Constructor_test, bdata::random(5, 10) ^ bdata::random(0, 2) ^ bdata::random(2, 5) ^ bdata::xrange(TCNumber), functionNumber, orderDiff, tryOrder, index)\n{\n    int maxOrder = orderDiff + tryOrder;\n    RandomAlgebricEquations equations(functionNumber, maxOrder, tryOrder);\n    BOOST_TEST(equations.ParameterNumber(), functionNumber * (tryOrder + 1));\n    BOOST_TEST(equations.SolutionNumber(), functionNumber * (maxOrder + 1));\n    BOOST_TEST(equations.EquationNumber(), functionNumber);\n//    MY_FLOAT_EQUAL(equations.EvaluateConstraints(), .0, tol);\n\n    vector<float_type> inputs = equations.GenerateInputs(3);\n    for (int i = 0; i < inputs.size(); i++) {\n        for (int j = 0; j < equations.EquationNumber(); j++) {\n            float_type res = equations.VerifySolution(inputs[i], j);\n            BOOST_TEST_INFO(\"input=\" << inputs[i] << \", equationId=\" << j);\n            MY_FLOAT_EQUAL(res, 0.0, tol);\n        }\n    }\n}\n\nBOOST_DATA_TEST_CASE(SaveLoad_test, bdata::random(5, 10) ^ bdata::random(0, 2) ^ bdata::random(2, 5) ^ bdata::xrange(TCNumber), functionNumber, orderDiff, tryOrder, index)\n{\n    int maxOrder = orderDiff + tryOrder;\n    RandomAlgebricEquations eqs1(functionNumber, maxOrder, tryOrder);\n    string file = \"SaveLoad_test\" + ToString(index) + \".txt\";\n    eqs1.SaveToFile(file);\n    RandomAlgebricEquations eqs2;\n    eqs2.LoadFromFile(file);\n\n    BOOST_TEST(eqs2.ParameterNumber(), eqs1.ParameterNumber());\n    BOOST_TEST(eqs2.SolutionNumber(), eqs1.SolutionNumber());\n    BOOST_TEST(eqs2.EquationNumber(), eqs1.EquationNumber());\n\n    // compare parameters and solutions.\n    for (int i = 0; i < eqs2.ParameterNumber(); i++) {\n        BOOST_TEST_INFO(\"i=\" << i);\n        MY_FLOAT_EQUAL(eqs2.GetParameter(i), eqs1.GetParameter(i), tol);\n    }\n\n    for (int i = 0; i < eqs2.SolutionNumber(); i++) {\n        BOOST_TEST_INFO(\"i=\" << i);\n        MY_FLOAT_EQUAL(eqs2.GetSolution(i), eqs1.GetSolution(i), tol);\n    }\n\n    // compare coefficients and constTerms.\n    for (int i = 0; i < eqs2.EquationNumber(); i++) {\n        for (int j = 0; j < functionNumber; j++) {\n            for (int k = 0; k < functionNumber; k++) {\n                MY_FLOAT_EQUAL(eqs2.GetCoefficient(i, j, k), eqs1.GetCoefficient(i, j, k), tol);\n            }\n        }\n\n        for (int j = 0; j <= maxOrder; j++) {\n            MY_FLOAT_EQUAL(eqs2.GetConstTerm(i, j), eqs1.GetConstTerm(i, j), tol);\n        }\n    }\n}\n\nBOOST_DATA_TEST_CASE(GetSetParameter_test, bdata::random(5, 10) ^ bdata::random(0, 2) ^ bdata::random(2, 5) ^ bdata::xrange(TCNumber), functionNumber, orderDiff, tryOrder, index)\n{\n    int maxOrder = orderDiff + tryOrder;\n    RandomAlgebricEquations equations(functionNumber, maxOrder, tryOrder);\n    int parameterId = randomint(0, equations.ParameterNumber() - 1);\n    float_type expected = random(-10.0, 10.0);\n    equations.SetParameter(parameterId, expected);\n    float_type actual = equations.GetParameter(parameterId);\n\n    MY_FLOAT_EQUAL(actual, expected, tol);\n}\n\nBOOST_DATA_TEST_CASE(EquationDerivativeByParameter_test, bdata::random(5, 10) ^ bdata::random(0, 2) ^ bdata::random(2, 5) ^ bdata::xrange(TCNumber), functionNumber, orderDiff, tryOrder, index)\n{\n    int maxOrder = orderDiff + tryOrder;\n    RandomAlgebricEquations equations(functionNumber, maxOrder, tryOrder);\n    int parameterId = randomint(0, equations.ParameterNumber() - 1);\n    int equationId = randomint(0, equations.EquationNumber() - 1);\n    float_type input = random(-1.0, 1.0);\n\n    float_type actual = equations.EquationDerivativeByParameter(input, equationId, parameterId);\n\n    float_type param = equations.GetParameter(parameterId);\n    equations.SetParameter(parameterId, param - inc);\n    float_type value1 = equations.EvaluateEquation(input, equationId);\n\n    equations.SetParameter(parameterId, param + inc);\n    float_type value2 = equations.EvaluateEquation(input, equationId);\n\n    float_type expected = (value2 - value1) / (2 * inc);\n    BOOST_TEST_INFO(\"input=\" << input << \", equationId=\" << equationId << \", parameterId=\" << parameterId);\n    MY_FLOAT_EQUAL(actual, expected, tol);\n}\n\nBOOST_DATA_TEST_CASE(ConstraintsDerivativeByParameter_test, bdata::random(5, 10) ^ bdata::random(0, 2) ^ bdata::random(2, 5) ^ bdata::xrange(TCNumber), functionNumber, orderDiff, tryOrder, index)\n{\n    int maxOrder = orderDiff + tryOrder;\n    RandomAlgebricEquations equations(functionNumber, maxOrder, tryOrder);\n    int parameterId = randomint(0, tryOrder);\n    float_type param = random(-.1, .0);\n    equations.SetParameter(parameterId, param);\n\n    float_type actual = equations.EvaluateConstraints();\n//    MY_FLOAT_EQUAL(actual, -param, tol);\n\n    actual = equations.ConstraintsDerivativeByParameter(functionNumber + 1);\n    MY_FLOAT_EQUAL(actual, .0, tol);\n\n    actual = equations.ConstraintsDerivativeByParameter(parameterId);\n    equations.SetParameter(parameterId, param - inc);\n    float_type value1 = equations.EvaluateConstraints();\n\n    equations.SetParameter(parameterId, param + inc);\n    float_type value2 = equations.EvaluateConstraints();\n\n    float_type expected = (value2 - value1) / (2 * inc);\n    BOOST_TEST_INFO(\"tryOrder=\" << tryOrder << \", parameterId=\" << parameterId << \", value=\" << param);\n    MY_FLOAT_EQUAL(actual, expected, tol);\n}\n\n// test suite end\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_FIXTURE_TEST_SUITE(EquationSolver_suite, SimpleTestFixture, * utf::disabled())\n\nBOOST_AUTO_TEST_CASE(EquationSolver_test1, * utf::label(\"EquationSolver1\"))\n{\n    int functionNumber = randomint(3, 4);\n    int tryOrder = randomint(2, 3);\n    int maxOrder = tryOrder;\n    RandomAlgebricEquations equations(functionNumber, maxOrder, tryOrder);\n    GradientDescentConfig config;\n    config.StepsToPrintResult = 1000;\n    config.InitialStepSize = 0.1;\n    config.LoopNumber = 5;\n    config.InitialTry = 3;\n    config.SamplesEachStep = 25;\n    config.RequiredAccuracy = 1.0;\n    config.FilePrefix = \"unittest1\";\n    EquationSolver<float_type> solver(&equations, &config);\n    vector<float_type> inputs;\n    float_type cost = solver.Run(inputs);\n    equations.OutputSolutions();\n\n    if (cost < config.RequiredAccuracy) {\n        float_type diff = .0;\n        for (int i = 0; i < equations.ParameterNumber(); i++) {\n            diff += (equations.GetParameter(i) - equations.GetSolution(i)) * (equations.GetParameter(i) - equations.GetSolution(i));\n        }\n\n        BOOST_TEST(diff < 1.0);\n    } else {\n        cout << \"Warning: only local minimum is returned.\";\n        equations.SaveToFile(\"EquationSolver_test.txt\");\n\n        vector<vector<float_type> > hessian;\n        solver.CalculateHessian(inputs, hessian);\n\n        std::cout << \"save hessian to file.\" << endl;\n        ofstream out(\"EquationSolver_test_hessian.txt\");\n        for (int i = 0; i < equations.ParameterNumber(); i++) {\n            out << \"{\";\n            for (int j = 0; j < equations.ParameterNumber(); j++) {\n                if (j > 0) out << \", \";\n                out << hessian[i][j];\n            }\n            out << \"},\" << endl;\n        }\n\n        out.close();\n    }\n}\n\nBOOST_AUTO_TEST_CASE(EquationSolver_test2, * utf::label(\"EquationSolver2\"))\n{\n    int functionNumber = randomint(3, 4);\n    int tryOrder = randomint(2, 3);\n    int maxOrder = randomint(1, 2) + tryOrder;\n    RandomAlgebricEquations equations(functionNumber, maxOrder, tryOrder);\n    GradientDescentConfig config;\n    config.StepsToPrintResult = 1000;\n    config.InitialStepSize = 0.1;\n    config.LoopNumber = 6;\n    config.InitialTry = 3;\n    config.SamplesEachStep = 25;\n    config.RequiredAccuracy = 1.0;\n    config.FilePrefix = \"unittest2\";\n    EquationSolver<float_type> solver(&equations, &config);\n    vector<float_type> inputs;\n    float_type cost = solver.Run(inputs);\n    equations.OutputSolutions();\n\n    if (cost < config.RequiredAccuracy) {\n        float_type diff = .0;\n        for (int i = 0; i < equations.ParameterNumber(); i++) {\n            diff += (equations.GetParameter(i) - equations.GetSolution(i)) * (equations.GetParameter(i) - equations.GetSolution(i));\n        }\n\n        BOOST_TEST(diff < 1.0);\n    } else {\n        cout << \"Warning: only local minimum is returned.\";\n        equations.SaveToFile(\"EquationSolver_test.txt\");\n\n        vector<vector<float_type> > hessian;\n        solver.CalculateHessian(inputs, hessian);\n\n        std::cout << \"save hessian to file.\" << endl;\n        ofstream out(\"EquationSolver_test_hessian.txt\");\n        for (int i = 0; i < equations.ParameterNumber(); i++) {\n            out << \"{\";\n            for (int j = 0; j < equations.ParameterNumber(); j++) {\n                if (j > 0) out << \", \";\n                out << hessian[i][j];\n            }\n            out << \"},\" << endl;\n        }\n\n        out.close();\n    }\n}\n\nBOOST_AUTO_TEST_CASE(EquationSolver_test3, * utf::label(\"EquationSolver3\"))\n{\n    RandomAlgebricEquations equations;\n    equations.LoadFromFile(\"RandomAlgebricEquations_unittest3_input.txt\");\n    GradientDescentConfig config;\n    config.StepsToPrintResult = 1000;\n    config.InitialStepSize = 0.1;\n    config.LoopNumber = 6;\n    config.InitialTry = 3;\n    config.SamplesEachStep = 20;\n    config.RequiredAccuracy = 1.0;\n    config.FilePrefix = \"unittest3\";\n    EquationSolver<float_type> solver(&equations, &config);\n    vector<float_type> inputs;\n    float_type cost = solver.Run(inputs);\n    equations.OutputSolutions();\n\n    if (cost < config.RequiredAccuracy) {\n        float_type diff = .0;\n        for (int i = 0; i < equations.ParameterNumber(); i++) {\n            diff += (equations.GetParameter(i) - equations.GetSolution(i)) * (equations.GetParameter(i) - equations.GetSolution(i));\n        }\n\n        BOOST_TEST(diff < 1.0);\n    } else {\n        cout << \"Warning: only local minimum is returned.\";\n        equations.SaveToFile(\"EquationSolver_test2.txt\");\n\n        vector<vector<float_type> > hessian;\n        solver.CalculateHessian(inputs, hessian);\n\n        std::cout << \"save hessian to file.\" << endl;\n        ofstream out(\"EquationSolver_test2_hessian.txt\");\n        for (int i = 0; i < equations.ParameterNumber(); i++) {\n            out << \"{\";\n            for (int j = 0; j < equations.ParameterNumber(); j++) {\n                if (j > 0) out << \", \";\n                out << hessian[i][j];\n            }\n            out << \"},\" << endl;\n        }\n\n        out.close();\n    }\n}\n\nBOOST_AUTO_TEST_CASE(EquationSolver_test4, * utf::label(\"EquationSolver4\"))\n{\n    RandomAlgebricEquations equations;\n    equations.LoadFromFile(\"RandomAlgebricEquations_unittest4_input.txt\");\n    GradientDescentConfig config;\n    config.StepsToPrintResult = 1000;\n    config.InitialStepSize = 0.1;\n    config.LoopNumber = 5;\n    config.InitialTry = 3;\n    config.SamplesEachStep = 20;\n    config.RequiredAccuracy = 1.0;\n    config.FilePrefix = \"unittest4\";\n    EquationSolver<float_type> solver(&equations, &config);\n    vector<float_type> inputs;\n    float_type cost = solver.Run(inputs);\n    equations.OutputSolutions();\n\n    if (cost < config.RequiredAccuracy) {\n        float_type diff = .0;\n        for (int i = 0; i < equations.ParameterNumber(); i++) {\n            diff += (equations.GetParameter(i) - equations.GetSolution(i)) * (equations.GetParameter(i) - equations.GetSolution(i));\n        }\n\n        BOOST_TEST(diff < 1.0);\n    } else {\n        cout << \"Warning: only local minimum is returned.\";\n        equations.SaveToFile(\"EquationSolver_test2.txt\");\n\n        vector<vector<float_type> > hessian;\n        solver.CalculateHessian(inputs, hessian);\n\n        std::cout << \"save hessian to file.\" << endl;\n        ofstream out(\"EquationSolver_test2_hessian.txt\");\n        for (int i = 0; i < equations.ParameterNumber(); i++) {\n            out << \"{\";\n            for (int j = 0; j < equations.ParameterNumber(); j++) {\n                if (j > 0) out << \", \";\n                out << hessian[i][j];\n            }\n            out << \"},\" << endl;\n        }\n\n        out.close();\n    }\n}\n\n// test suite end\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4a8542f67dfb0161fd484354f916ce6b9f6f0f44", "size": 12414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/RandomAlgebricEquationsTests.cpp", "max_stars_repo_name": "gaolichen/cftbtsp", "max_stars_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/RandomAlgebricEquationsTests.cpp", "max_issues_repo_name": "gaolichen/cftbtsp", "max_issues_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/RandomAlgebricEquationsTests.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": 37.7325227964, "max_line_length": 195, "alphanum_fraction": 0.6477364266, "num_tokens": 3226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5438129628227016}}
{"text": "//\n//  su2_x.hpp\n//\n//  Created by Evan Owen on 4/3/21.\n//  Copyright \u00a9 2021 Evan Owen. All rights reserved.\n//\n\n#ifndef su2_x_hpp\n#define su2_x_hpp\n\n#include <random>\n#include <complex>\n#include <Eigen/Dense>\n\nclass su2_x_lattice;\n\ntypedef Eigen::Matrix<std::complex<double>, 2, 2> su2_link;\ntypedef Eigen::Matrix<std::complex<double>, 1, 2> su2_vector;\n#define su2_identity su2_link::Identity()\n#define su2_zero su2_link::Zero()\n\n#define I complex<double>(0,1)\n#define Q(s) s->link[0]\n#define D_MAX 6\n#define SQRT3   1.73205080756887729352744634151  // sqrt(3)\n#define SQRT1_3 0.577350269189625764509148780502 // 1 / sqrt(3)\n\nclass su2_x_site {\npublic:\n    // variables\n    su2_x_lattice* lattice; // parent lattice\n    su2_link link[D_MAX]; // link values in each direction\n    su2_link link_inverse[D_MAX]; // link inverse values\n    su2_link p_link[D_MAX]; // conjugate momenta in each direction\n    su2_x_site* forward[D_MAX]; // adjacent sites in the forward direction\n    su2_x_site* backward[D_MAX]; // adjacent sites in the backward direction\n    std::mt19937* gen; // random number generator for this time-slice\n    bool forward_edge; // site is at the forward edge of the extra dimension\n    bool backward_edge; // site is at the backward edge of the extra dimension\n    bool is_locked;\n    double eps;\n    su2_link wf_z[D_MAX]; // exponent for wilson flow\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    // methods\n    void init(su2_x_lattice* lattice, su2_x_site* lattice_sites, int s);\n    su2_link make_unitary(const su2_link& g);\n    su2_link exp_su2(const su2_link& g);\n    bool lock();\n    void unlock();\n    double rand_double(double min = 0.0, double max = 1.0);\n    int rand_int(int min, int max);\n    double rand_normal(double mean = 0.0, double stdev = 1.0);\n    void reset_links(bool cold);\n    void copy_links(su2_x_site* site);\n    void read_links(std::ifstream& ckptFile, bool bigEndian);\n    void set_link(int d, const su2_link& value);\n    void init_momenta();\n    su2_link create_random_link();\n    su2_link create_link(double a);\n    double action();\n    double hamiltonian();\n    void hmc_step_p(double frac);\n    void hmc_step_link();\n    su2_link p_link_dot(int d);\n    double link_trace();\n    double plaq();\n    su2_link plaquette(int d1, int d2);\n    su2_link staple(int d1);\n    su2_link reverse_staple(int d1);\n    su2_link staple_x(int d1);\n    su2_link reverse_staple_x(int d1);\n    su2_link cloverleaf(int d1, int d2);\n    double wilson_loop(int a, int b);\n    std::complex<double> polyakov_loop(int r);\n    double correlator(int T);\n    double field_strength();\n//    double field_strength_x();\n    double topological_charge();\n    double mag_U();\n    double abs_U();\n    double four_point(int T, int R);\n    su2_link overrelax(su2_link g);\n    void relax(bool coulomb);\n    double sum_landau();\n    double sum_coulomb();\n    su2_link sum_G(bool coulomb);\n    void heat_bath();\n    void heat_bath_link(int d1);\n    void cool();\n    void cool_link(int d1);\n    void wilson_flow(su2_x_site* target, int step);\n    void wilson_flow_link(su2_x_site* target, int step, int d);\n    void stout_smear(su2_x_site* target, double rho);\n    void stout_smear_link(su2_x_site* target, double rho, int d1);\n};\n\nclass su2_x_lattice {\npublic:\n    // variables\n    int N; // array size (spacial)\n    int T; // array size (time)\n    int N5; // 5th dimension size\n    int D; // number of dimensions\n    double beta; // coupling factor\n    double eps5; // ratio of coupling in extra dimension to normal coupling\n    int n_sites; // number of sites in the entire lattice\n    int n_sites_5; // number of sites in a 5d sub-lattice\n    int n_slice; // number of sites in each time slice of the entire lattice\n    int n5_center; // center lattice\n    std::vector<su2_x_site> site; // site values\n    std::vector<std::mt19937> gen; // array of random number generators (one for each time-slice)\n    std::vector<su2_link> sigma; // pauli spin matrices\n    int verbose;\n    bool parallel;\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    // hmc\n    std::vector<su2_x_site> site_1; // site values for hmc\n    double dt; // hmc step size\n    int n_steps; // hmc step count\n    int hmc_accept; // number of accepted hmc configurations\n    int hmc_count; // number of attempted hmc configurations\n\n    // time step for wilson flow algorithm\n    double wf_dt;\n\n    // methods\n    su2_x_lattice(int N, int T, int N5, int D, double beta, double eps5, bool cold = false);\n    su2_x_lattice(su2_x_lattice* lattice);\n    su2_x_lattice(int N, int T, int N5, int D, double beta, double eps5, std::ifstream& ckptFile, bool isNersc = false);\n    ~su2_x_lattice();\n    void init();\n    double rand_double(double min = 0.0, double max = 1.0);\n    int rand_int(int min, int max);\n    double rand_normal(double mean = 0.0, double stdev = 1.0);\n    int get_site(int s, int d, int n);\n    double link_trace();\n    double plaq(int n5);\n    double action(int n5);\n    double wilson_loop(int a, int b, int n5);\n    double polyakov_loop(int R, int n5);\n    double correlator(int T, int n5);\n    double four_point(int T, int R, int n5);\n    double hamiltonian();\n    void hmc(int n_sweeps = 0, bool update_dt = false, bool no_metropolis = false);\n    void heat_bath(int n_sweeps = 0);\n    void cool(int n5, int n_sweeps = 0);\n    void wilson_flow_x(int n_sweeps = 0);\n    void wilson_flow(int n5, int n_sweeps = 0);\n    void stout_smear(int n5, double rho = 0.1, int n_sweeps = 0);\n    double field_strength(int n5);\n    double field_strength_x(int n5);\n    double topological_charge(int n5);\n    int thermalize(int n_min = 0, int n_max = 0);\n    double ave_link_t(int n5);\n    double theta(bool coulomb, int n5);\n    long double relax(long double error_target, bool coulomb, int n5);\n};\n\n#endif /* su2_x_hpp */\n", "meta": {"hexsha": "566521597317452d3ef193416e19ada8b498d178", "size": 5790, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "su2_x/su2_x.hpp", "max_stars_repo_name": "ekowen86/lattice", "max_stars_repo_head_hexsha": "878b59a5b1ce79328c2f57a8133ddfa65186536a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-23T02:02:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T15:11:34.000Z", "max_issues_repo_path": "su2_x/su2_x.hpp", "max_issues_repo_name": "ekowen86/lattice", "max_issues_repo_head_hexsha": "878b59a5b1ce79328c2f57a8133ddfa65186536a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "su2_x/su2_x.hpp", "max_forks_repo_name": "ekowen86/lattice", "max_forks_repo_head_hexsha": "878b59a5b1ce79328c2f57a8133ddfa65186536a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T19:37:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T19:37:34.000Z", "avg_line_length": 35.3048780488, "max_line_length": 120, "alphanum_fraction": 0.689119171, "num_tokens": 1682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5438129576231864}}
{"text": "#include \"CMeshModelInstance.h\"\n#include <Eigen/Dense>\n#include <igl/per_vertex_normals.h>\n#include <assert.h>\n#include <totalmodel.h>\n#include <ceres/rotation.h>\n#include <chrono>\n\n// Function equivalent and improved from igl::per_vertex_normals\n// [270, 452] ms\ntemplate <typename T>\ninline T getNormTriplet(const T* const ptr)\n{\n    return std::sqrt(ptr[0]*ptr[0] + ptr[1]*ptr[1] + ptr[2]*ptr[2]);\n}\ntemplate <typename T>\ninline void normalizeTriplet(T* ptr, const T norm)\n{\n    ptr[0] /= norm;\n    ptr[1] /= norm;\n    ptr[2] /= norm;\n}\ntemplate <typename T>\ninline void normalizeTriplet(T* ptr)\n{\n    const auto norm = getNormTriplet(ptr);\n    normalizeTriplet(ptr, norm);\n}\nvoid per_vertex_normals(\n  const Eigen::Matrix<double, Eigen::Dynamic, 3, Eigen::RowMajor>& V,\n  const Eigen::Matrix<int, Eigen::Dynamic, 3, Eigen::RowMajor>& F,\n  Eigen::Matrix<double, Eigen::Dynamic, 3, Eigen::RowMajor>& N\n)\n{\n    Eigen::Matrix<double, Eigen::Dynamic,3, Eigen::RowMajor> FN;\n    FN.resize(F.rows(),3);\n    auto* FN_data = FN.data();\n    const auto* const F_data = F.data();\n    const auto* const V_data = V.data();\n    // loop over faces\n    for (int i = 0; i < F.rows();i++)\n    {\n        const auto baseIndex = 3*i;\n        const auto F_data0 = 3*F_data[baseIndex];\n        const auto F_data1 = 3*F_data[baseIndex+1];\n        const auto F_data2 = 3*F_data[baseIndex+2];\n        const Eigen::Matrix<double, 1, 3> v1(\n            V_data[F_data1] - V_data[F_data0],\n            V_data[F_data1+1] - V_data[F_data0+1],\n            V_data[F_data1+2] - V_data[F_data0+2]);\n        const Eigen::Matrix<double, 1, 3> v2(\n            V_data[F_data2] - V_data[F_data0],\n            V_data[F_data2+1] - V_data[F_data0+1],\n            V_data[F_data2+2] - V_data[F_data0+2]);\n        FN.row(i) = v1.cross(v2);\n        auto* fnRowPtr = &FN_data[baseIndex];\n        const double norm = getNormTriplet(fnRowPtr);\n        if (norm == 0)\n        {\n            fnRowPtr[0] = 0;\n            fnRowPtr[1] = 0;\n            fnRowPtr[2] = 0;\n        }\n        else\n            normalizeTriplet(fnRowPtr, norm);\n    }\n\n    // Resize for output\n    N.resize(V.rows(),3);\n    std::fill(N.data(), N.data() + N.rows() * N.cols(), 0.0);\n\n    Eigen::Matrix<double, Eigen::Dynamic, 1> A(F.rows(), 1);\n    auto* A_data = A.data();\n    const auto Fcols = F.cols();\n    const auto Vcols = V.cols();\n\n  // Projected area helper\n  const auto & proj_doublearea =\n    [&V_data,&F_data, &Vcols, &Fcols](const int x, const int y, const int f)\n    ->double\n  {\n    const auto baseIndex = f*Fcols;\n    const auto baseIndex2 = F_data[baseIndex + 2]*Vcols;\n    const auto rx = V_data[F_data[baseIndex]*Vcols + x] - V_data[baseIndex2 + x];\n    const auto sx = V_data[F_data[baseIndex + 1]*Vcols + x] - V_data[baseIndex2 + x];\n    const auto ry = V_data[F_data[baseIndex]*Vcols + y] - V_data[baseIndex2 + y];\n    const auto sy = V_data[F_data[baseIndex + 1]*Vcols + y] - V_data[baseIndex2 + y];\n    return rx*sy - ry*sx;\n  };\n\n  for (auto f = 0;f<F.rows();f++)\n  {\n    const auto dblAd1 = proj_doublearea(0,1,f);\n    const auto dblAd2 = proj_doublearea(1,2,f);\n    const auto dblAd3 = proj_doublearea(2,0,f);\n    A_data[f] = std::sqrt(dblAd1*dblAd1 + dblAd2*dblAd2 + dblAd3*dblAd3);\n  }\n\n    auto* N_data = N.data();\n    // loop over faces\n    for (int i = 0 ; i < F.rows();i++)\n    {\n        const auto baseIndex = i*Fcols;\n        // throw normal at each corner\n        for (int j = 0; j < 3;j++)\n        {\n            // auto* nRowPtr = &N_data[3*F(i,j)];\n            auto* nRowPtr = &N_data[3*F_data[baseIndex + j]];\n            const auto* const fnRowPtr = &FN_data[3*i];\n            for (int subIndex = 0; subIndex < FN.cols(); subIndex++)\n                nRowPtr[subIndex] += A_data[i] * fnRowPtr[subIndex];\n            // Vector equilvanet\n            // N.row(F(i,j)) += A_data[i] * FN.row(i);\n        }\n    }\n\n    // take average via normalization\n    // loop over faces\n    for (int i = 0;i<N.rows();i++)\n        normalizeTriplet(&N_data[3*i]);\n    // Matrix equivalent\n    // N.rowwise().normalize();\n}\n\nvoid CMeshModelInstance::RecomputeNormal(const TotalModel& model)\n{\n    // Compute Normal\n    Eigen::Matrix<double, Eigen::Dynamic, 3, Eigen::RowMajor> V_3(m_vertices.size(), 3);\n    auto* V_3_data = V_3.data();\n\n    for (int r = 0; r < V_3.rows(); ++r)\n    {\n        auto* v3rowPtr = &V_3_data[3*r];\n        v3rowPtr[0] = m_vertices[r].x; // V_3(r, 0)\n        v3rowPtr[1] = m_vertices[r].y; // V_3(r, 1)\n        v3rowPtr[2] = m_vertices[r].z; // V_3(r, 2)\n    }\n    // Eigen::MatrixXd NV;\n    Eigen::Matrix<double, Eigen::Dynamic, 3, Eigen::RowMajor> NV;\n\n    if (m_meshType==MESH_TYPE_SMPL)\n    {\n        std::string errorMessage(\"Not supporting MESH_TYPE_SMPL currently\");\n        throw std::runtime_error(errorMessage);\n        // igl::per_vertex_normals(V_3, g_smpl.faces_, NV);\n    }\n    if (m_meshType == MESH_TYPE_TOTAL || m_meshType == MESH_TYPE_ADAM)\n    {\n        // igl::per_vertex_normals(V_3, model.m_faces, NV);\n        per_vertex_normals(V_3, model.m_faces, NV);\n        // Eigen::Matrix<double, Eigen::Dynamic, 3, Eigen::RowMajor> NVAux;\n        // igl::per_vertex_normals(V_3, model.m_faces, NVAux);\n        // std::cout << (NV - NVAux).norm() << std::endl;\n        // assert((NV - NVAux).norm() < 1e-6);\n    }\n    m_normals.resize(NV.rows());\n    auto* NV_data = NV.data();\n    for (int r = 0; r < NV.rows(); ++r)\n    {\n        const auto* const nvRow = &NV_data[3*r];\n        m_normals[r] = cv::Point3f(nvRow[0], nvRow[1], nvRow[2]); // cv::Point3f(NV(r, 0), NV(r, 1), NV(r, 2))\n    }\n}\n\nvoid CMeshModelInstance::clearMesh()\n{\n    m_face_vertexIndices.clear();\n    m_vertices.clear();\n    m_colors.clear();\n    m_normals.clear();\n    m_uvs.clear();\n    m_joints.clear();\n    m_joints_regress.clear();\n    m_alpha.clear();\n}\n\nbool compareTupleDepth(const std::tuple<double, double, cv::Point3i>& a, const std::tuple<double, double, cv::Point3i>& b)\n{\n    return std::get<1>(a) > std::get<1>(b);   // from far to near\n}\n\nbool compareTupleAlpha(const std::tuple<double, double, cv::Point3i>& a, const std::tuple<double, double, cv::Point3i>& b)\n{\n    return std::get<0>(a) > std::get<0>(b);   // opaque first, then transparent\n}\n\nvoid CMeshModelInstance::sortFaceDepth(const cv::Point3d angleaxis)\n{\n    // const auto start = std::chrono::high_resolution_clock::now();\n    std::vector<double> depth_vertex(m_vertices.size());\n    if (angleaxis == cv::Point3d(0., 0., 0.))   // no rotation\n    {\n        for (auto i = 0u; i < m_vertices.size(); i++)\n            depth_vertex[i] = m_vertices[i].z;\n    }\n    else\n    {\n        const double angle_axis[3] = {angleaxis.x, angleaxis.y, angleaxis.z};\n        for (auto i = 0u; i < m_vertices.size(); i++)\n        {\n            const double pt[3] = {m_vertices[i].x, m_vertices[i].y, m_vertices[i].z};\n            double result[3];\n            ceres::AngleAxisRotatePoint(angle_axis, pt, result);\n            depth_vertex[i] = result[2];\n        }\n    }\n\n    assert(m_face_vertexIndices.size() % 3 == 0);\n    std::vector<std::tuple<double, double, cv::Point3i>> vecSort;\n    const uint num_face = m_face_vertexIndices.size() / 3;\n    vecSort.reserve(num_face);\n    for (auto i = 0u; i < num_face; i++)\n    {\n        const uint I1 = m_face_vertexIndices[3 * i];\n        const uint I2 = m_face_vertexIndices[3 * i + 1];\n        const uint I3 = m_face_vertexIndices[3 * i + 2];\n        const double depth = (depth_vertex[I1] + depth_vertex[I2] + depth_vertex[I3]) / 3;\n        const double alpha = (m_alpha[I1] + m_alpha[I2] + m_alpha[I3]) / 3;  // opaqueness\n        vecSort.emplace_back(std::make_tuple(alpha, depth, cv::Point3i(I1, I2, I3)));\n    }\n    std::sort(vecSort.begin(), vecSort.end(), compareTupleAlpha);  // first sort according to opacity, put opaque face first\n    auto it = vecSort.begin();\n    while(it != vecSort.end())\n    {\n        // find the first element that is not completely opaque\n        if (std::get<0>(*it) != 1.0)\n            break;\n        it++;\n    }\n    std::sort(it, vecSort.end(), compareTupleDepth);  // now sort according to depth, far first\n    for (auto i = 0u; i < num_face; i++)\n    {\n        auto& pt = std::get<2>(vecSort[i]);\n        m_face_vertexIndices[3 * i + 0] = pt.x;\n        m_face_vertexIndices[3 * i + 1] = pt.y;\n        m_face_vertexIndices[3 * i + 2] = pt.z;\n    }\n    // const auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - start).count();\n    // std::cout << \"Sort depth duration \" << duration * 1e-6 << \" ms\" << std::endl;\n}", "meta": {"hexsha": "f71ba1a6199b7e6fc0f650d2cedc6a8662a1bbd7", "size": 8574, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "visualization/FitAdam/src/CMeshModelInstance.cpp", "max_stars_repo_name": "alvaro-budria/body2hands", "max_stars_repo_head_hexsha": "0eba438b4343604548120bdb03c7e1cb2b08bcd6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2021-05-14T02:55:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T01:51:12.000Z", "max_issues_repo_path": "visualization/FitAdam/src/CMeshModelInstance.cpp", "max_issues_repo_name": "human2b/body2hands", "max_issues_repo_head_hexsha": "8ab4b206dc397c3b326f2b4ec9448c84ee8801fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-06-24T09:59:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-31T08:15:20.000Z", "max_forks_repo_path": "visualization/FitAdam/src/CMeshModelInstance.cpp", "max_forks_repo_name": "human2b/body2hands", "max_forks_repo_head_hexsha": "8ab4b206dc397c3b326f2b4ec9448c84ee8801fe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-05-17T03:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T02:30:44.000Z", "avg_line_length": 35.725, "max_line_length": 141, "alphanum_fraction": 0.5922556566, "num_tokens": 2664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5438129472241561}}
{"text": "#ifndef SKYLARK_WZT_HPP\n#define SKYLARK_WZT_HPP\n\n#ifndef SKYLARK_SKETCH_HPP\n#error \"Include top-level sketch.hpp instead of including individuals headers\"\n#endif\n\n#include <boost/random.hpp>\n\nnamespace skylark { namespace sketch {\n\n/**\n * Woodruff-Zhang Transform (data)\n *\n * Woodruff-Zhang Transform is very similar to the Clarkson-Woodruff Transform:\n * it replaces the +1/-1 diagonal with reciprocal exponentia random enteries. \n * It is sutiable for lp regression with 1 <= p <= 2.\n *\n * Reference:\n * D. Woodruff and Q. Zhang\n * Subspace Embeddings and L_p Regression Using Exponential Random\n * COLT 2013\n *\n * TODO current implementation is only one sketch index, when for 1 <= p <= 2\n *      you want more than one.\n */\n\ntemplate < typename InputMatrixType,\n           typename OutputMatrixType = InputMatrixType >\nstruct WZT_t :\n        public WZT_data_t,\n        virtual public sketch_transform_t<InputMatrixType, OutputMatrixType > {\n\npublic:\n\n    // We use composition to defer calls to hash_transform_t\n    typedef hash_transform_t< InputMatrixType, OutputMatrixType,\n                              boost::random::uniform_int_distribution,\n                              boost::random::exponential_distribution > transform_t;\n\n    typedef WZT_data_t data_type;\n    typedef data_type::params_t params_t;\n\n    WZT_t(int N, int S, double p, base::context_t& context)\n        : data_type(N, S, p, context), _transform(*this) {\n\n    }\n\n    WZT_t(int N, int S, const params_t& params, base::context_t& context)\n        : data_type(N, S, params, context),\n          _transform(*this) {\n\n    }\n\n    WZT_t(const boost::property_tree::ptree &pt)\n        : data_type(pt), _transform(*this) {\n\n    }\n\n    template< typename OtherInputMatrixType,\n              typename OtherOutputMatrixType >\n    WZT_t(const WZT_t<OtherInputMatrixType,OtherOutputMatrixType>& other)\n        : data_type(other), _transform(*this) {\n\n    }\n\n    WZT_t(const data_type& other)\n        : data_type(other), _transform(*this) {\n\n    }\n\n    /**\n     * Apply columnwise the sketching transform that is described by the\n     * the transform with output sketch_of_A.\n     */\n    void apply (const typename transform_t::matrix_type& A,\n                typename transform_t::output_matrix_type& sketch_of_A,\n                columnwise_tag dimension) const {\n        _transform.apply(A, sketch_of_A, dimension);\n    }\n\n    /**\n     * Apply rowwise the sketching transform that is described by the\n     * the transform with output sketch_of_A.\n     */\n    void apply (const typename transform_t::matrix_type& A,\n                typename transform_t::output_matrix_type& sketch_of_A,\n                rowwise_tag dimension) const {\n        _transform.apply(A, sketch_of_A, dimension);\n    }\n\n    int get_N() const { return this->_N; } /**< Get input dimesion. */\n    int get_S() const { return this->_S; } /**< Get output dimesion. */\n\n    const sketch_transform_data_t* get_data() const { return this; }\n\nprivate:\n    transform_t _transform;\n};\n\n} } /** namespace skylark::sketch */\n\n#endif // SKYLARK_WZT_HPP\n", "meta": {"hexsha": "0a9da70dc9d8e6fefbaab43ab5b6a6a3e5d74783", "size": 3078, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sketch/WZT.hpp", "max_stars_repo_name": "wangg12/libskylark", "max_stars_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-12T07:26:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T07:26:47.000Z", "max_issues_repo_path": "sketch/WZT.hpp", "max_issues_repo_name": "cjiyer/libskylark", "max_issues_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "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": "sketch/WZT.hpp", "max_forks_repo_name": "cjiyer/libskylark", "max_forks_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "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.5961538462, "max_line_length": 84, "alphanum_fraction": 0.6695906433, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5438129472241561}}
{"text": "#include <iostream>\n\r\n#define BOOST_TEST_MODULE MIAUnaryTests\n\r\n\n\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#include \"DenseMIA.h\"\r\n#include \"SparseMIA.h\"\r\n#include \"LibMIAHelpers.h\"\n#include \"Index.h\"\n\n//typedef LibMIA::DenseMIA<double,3> dmia;\n\r\ntemplate<class data_type>\r\nvoid sparse_unary_work(){\r\n\r\n    LibMIA::MIAINDEX i;\n    LibMIA::MIAINDEX j;\n    LibMIA::MIAINDEX k;\r\n    LibMIA::MIAINDEX l;\n    LibMIA::MIAINDEX m;\n    LibMIA::MIAINDEX n;\r\n    size_t _dim=5;\n\n    LibMIA::SparseMIA<data_type,6> a(_dim,_dim+1,_dim,_dim+1,_dim-1,_dim-2);\r\n\r\n    LibMIA::SparseMIA<data_type,4> b;\r\n    LibMIA::SparseMIA<data_type,4> other_b;\r\n    LibMIA::SparseMIA<data_type,3> c;\r\n    LibMIA::SparseMIA<data_type,3> other_c;\r\n    LibMIA::SparseMIA<data_type,2> d;\r\n    LibMIA::SparseMIA<data_type,2> other_d;\r\n    LibMIA::SparseMIA<data_type,1> e;\r\n    LibMIA::SparseMIA<data_type,1> other_e;\r\n    LibMIA::SparseMIA<data_type,5> f;\r\n    LibMIA::SparseMIA<data_type,5> other_f;\r\n    auto delta=LibMIA::create_delta<data_type,2>(_dim);\r\n    auto delta2=LibMIA::create_delta<data_type,2>(_dim+1);\r\n    auto delta_3=LibMIA::create_delta<data_type,3>(_dim);\r\n\r\n    a.resize(a.dimensionality()/3);\r\n    a.randu(-5,5);\r\n    a.rand_indices();\r\n    a.collect_duplicates();\r\n\r\n\r\n\r\n    b(j,k,l,m)=a(i,j,i,k,l,m); //contraction\r\n    other_b(j,k,l,m)=a(i,j,n,k,l,m)*delta(i,n); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(b.fuzzy_equals(other_b,test_precision<data_type>()),std::string(\"Simple Contraction 1 for Sparse \")+typeid(data_type).name());\r\n\r\n    c=LibMIA::SparseMIA<data_type,3>(_dim,_dim+1,_dim);\r\n    c.resize(c.dimensionality()/3);\r\n    c.randu(-5,5);\r\n    c.rand_indices();\r\n    c.collect_duplicates();\r\n    e(i)=c(j,i,j);\r\n    other_e(i)=c(j,i,k)*delta(j,k);\r\n    BOOST_CHECK_MESSAGE(e.fuzzy_equals(other_e,test_precision<data_type>()),std::string(\"Simple Contraction 2 for Sparse \")+typeid(data_type).name());\r\n\r\n\r\n//\r\n    a=LibMIA::SparseMIA<data_type,6>(_dim,_dim+1,_dim,_dim,_dim+2,_dim-2);\r\n    a.resize(a.dimensionality()/3);\r\n    a.randu(-5,5);\r\n    a.rand_indices();\r\n    a.collect_duplicates();\r\n    c(j,l,m)=a(i,j,i,i,l,m); //contraction\r\n    other_c(j,l,m)=a(i,j,n,k,l,m)*delta_3(i,n,k); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(other_c,test_precision<data_type>()),std::string(\"Triple Contraction 1 for Sparse \")+typeid(data_type).name());\r\n//\r\n    a=LibMIA::SparseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+1,_dim-1,_dim-2); //now try with non-uniform dimensions\r\n    a.resize(a.dimensionality()/3);\r\n    a.randu(-5,5);\r\n    a.rand_indices();\r\n    a.collect_duplicates();\r\n    d(l,m)=a(i,j,i,j,l,m); //contraction\r\n    other_d(l,m)=a(i,j,n,k,l,m)*delta(i,n)*delta2(j,k); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(other_d,test_precision<data_type>()),std::string(\"Complex Contraction 1 for Sparse \")+typeid(data_type).name());\r\n\r\n    a=LibMIA::SparseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+1,_dim,_dim-2); //now try with non-uniform dimensions\r\n    a.resize(a.dimensionality()/3);\r\n    a.randu(-5,5);\r\n    a.rand_indices();\r\n    a.collect_duplicates();\r\n    e(m)=a(i,j,i,j,i,m); //contraction\r\n    other_e(m)=a(i,j,n,k,l,m)*delta_3(i,n,l)*delta2(j,k); //equivalent operation\r\n//    e.print();\r\n//    other_e.print();\r\n    BOOST_CHECK_MESSAGE(e.fuzzy_equals(other_e,test_precision<data_type>()),std::string(\"Complex Contraction 2 for Sparse \")+typeid(data_type).name());\r\n\r\n    d=LibMIA::SparseMIA<data_type,2>(_dim,_dim);\r\n    d.resize(a.dimensionality()/3);\r\n    d.randu(-5,5);\r\n    d.rand_indices();\r\n    d.collect_duplicates();\r\n    e(i)=d(!i,!i);\r\n    other_e(i)=d(!i,j)*delta(!i,j);\r\n    BOOST_CHECK_MESSAGE(e.fuzzy_equals(other_e,test_precision<data_type>()),std::string(\"Very Simple Attraction 1 for Sparse \")+typeid(data_type).name());\r\n//\r\n    c=LibMIA::SparseMIA<data_type,3>(_dim,_dim+1,_dim); //now try with non-uniform dimensions\r\n    c.resize(a.dimensionality()/3);\r\n    c.randu(-5,5);\r\n    c.rand_indices();\r\n    c.collect_duplicates();\r\n    d(i,j)=c(!i,j,!i); //attraction\r\n    other_d(i,j)=c(!i,j,n)*delta(!i,n); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(other_d,test_precision<data_type>()),std::string(\"Simple Attraction 1 for Sparse \")+typeid(data_type).name());\r\n//\r\n//\r\n//\r\n    a=LibMIA::SparseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+2,_dim-1,_dim-2); //now try with non-uniform dimensions\r\n    a.resize(a.dimensionality()/3);\r\n    a.randu(-5,5);\r\n    a.rand_indices();\r\n    a.collect_duplicates();\r\n    f(i,j,k,l,m)=a(!i,j,!i,k,l,m); //attraction\r\n    other_f(i,j,k,l,m)=a(!i,j,n,k,l,m)*delta(!i,n); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(f.fuzzy_equals(other_f,test_precision<data_type>()),std::string(\"Simple Attraction 2 for Sparse \")+typeid(data_type).name());\r\n\r\n//\r\n    a=LibMIA::SparseMIA<data_type,6>(_dim,_dim+1,_dim,_dim,_dim+2,_dim-2);\r\n    a.resize(a.dimensionality()/3);\r\n    a.randu(-5,5);\r\n    a.rand_indices();\r\n    a.collect_duplicates();\r\n    b(i,j,l,m)=a(!i,j,!i,!i,l,m); //attraction\r\n    other_b(i,j,l,m)=a(!i,j,n,k,l,m)*delta_3(!i,n,k); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(b.fuzzy_equals(other_b,test_precision<data_type>()),std::string(\"Triple Attraction 1 for Sparse \")+typeid(data_type).name());\r\n//\r\n    a=LibMIA::SparseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+1,_dim-1,_dim-2); //now try with non-uniform dimensions\r\n    a.resize(a.dimensionality()/3);\r\n    a.randu(-5,5);\r\n    a.rand_indices();\r\n    a.collect_duplicates();\r\n    b(i,j,l,m)=a(!i,!j,!i,!j,l,m); //attraction\r\n    other_b(i,j,l,m)=a(!i,!j,n,k,l,m)*delta(!i,n)*delta2(!j,k); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(b.fuzzy_equals(other_b,test_precision<data_type>()),std::string(\"Complex Attraction 1 for Sparse \")+typeid(data_type).name());\r\n//\r\n    a=LibMIA::SparseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+1,_dim,_dim-2); //now try with non-uniform dimensions\r\n    a.resize(a.dimensionality()/3);\r\n    a.randu(-5,5);\r\n    a.rand_indices();\r\n    a.collect_duplicates();\r\n    c(i,j,m)=a(!i,!j,!i,!j,!i,m); //attraction\r\n    other_c(i,j,m)=a(!i,!j,n,k,l,m)*delta_3(!i,n,l)*delta2(!j,k); //equivalent operation\r\n    //c.print();\r\n    //other_c.print();\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(other_c,test_precision<data_type>()),std::string(\"Complex Attraction 2 for Sparse \")+typeid(data_type).name());\r\n//\r\n    b=LibMIA::SparseMIA<data_type,4>(_dim,_dim+1,_dim,_dim+1); //now try with non-uniform dimensions\r\n    b.resize(a.dimensionality()/3);\r\n    b.randu(-5,5);\r\n    b.rand_indices();\r\n    b.collect_duplicates();\r\n    d(i,j)=b(!i,!j,!i,!j); //attraction\r\n    other_d(i,j)=b(!i,!j,n,k)*delta(!i,n)*delta2(!j,k); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(other_d,test_precision<data_type>()),std::string(\"Complex Attraction 3 for Sparse \")+typeid(data_type).name());\r\n//\r\n    a=LibMIA::SparseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+1,_dim,_dim-2); //now try with non-uniform dimensions\r\n    a.resize(a.dimensionality()/3);\r\n    a.randu(-5,5);\r\n    a.rand_indices();\r\n    a.collect_duplicates();\r\n    c(i,k,m)=a(!i,j,!i,j,k,m); //attraction\r\n    other_c(i,k,m)=a(n,l,!i,j,k,m)*delta(!i,n)*delta2(j,l); //attraction\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(other_c,test_precision<data_type>()),std::string(\"Combined Contraction/Attraction 1 for Sparse \")+typeid(data_type).name());\r\n\r\n\r\n    b=LibMIA::SparseMIA<data_type,4>(_dim,_dim+1,_dim,_dim+1); //now try with non-uniform dimensions\r\n    b.resize(a.dimensionality()/3);\r\n    b.randu(-5,5);\r\n    b.rand_indices();\r\n    b.collect_duplicates();\r\n    e(i)=b(!i,j,!i,j); //attraction\r\n    other_e(i)=b(n,l,!i,j)*delta(!i,n)*delta2(j,l); //attraction\r\n    BOOST_CHECK_MESSAGE(e.fuzzy_equals(other_e,test_precision<data_type>()),std::string(\"Combined Contraction/Attraction 2 for Sparse \")+typeid(data_type).name());\r\n//\r\n    a=LibMIA::SparseMIA<data_type,6>(_dim,_dim+1,_dim,_dim,_dim+1,_dim-2); //now try with non-uniform dimensions\r\n    a.resize(a.dimensionality()/3);\r\n    a.randu(-5,5);\r\n    a.rand_indices();\r\n    a.collect_duplicates();\r\n    d(i,m)=a(!i,j,!i,!i,j,m); //attraction\r\n    other_d(i,m)=a(!i,j,n,k,l,m)*delta_3(!i,n,k)*delta2(j,l); //attraction\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(other_d,test_precision<data_type>()),std::string(\"Combined Contraction/Attraction 3 for Sparse \")+typeid(data_type).name());\r\n//\r\n    a=LibMIA::SparseMIA<data_type,6>(_dim,_dim+1,_dim,_dim,_dim+1,_dim-2); //now try with non-uniform dimensions\r\n    a.resize(a.dimensionality()/3);\r\n    a.randu(-5,5);\r\n    a.rand_indices();\r\n    a.collect_duplicates();\r\n    d(j,m)=a(i,!j,i,i,!j,m); //attraction\r\n    other_d(j,m)=a(i,!j,n,k,l,m)*delta_3(i,n,k)*delta2(!j,l); //attraction\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(other_d,test_precision<data_type>()),std::string(\"Combined Contraction/Attraction 4 for Sparse \")+typeid(data_type).name());\r\n//\r\n    a=LibMIA::SparseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+1,_dim,_dim); //now try with non-uniform dimensions\r\n    a.resize(a.dimensionality()/3);\r\n    a.randu(-5,5);\r\n    a.rand_indices();\r\n    a.collect_duplicates();\r\n    d(i,k)=a(!i,j,!i,j,!k,!k); //attraction\r\n    other_d(i,k)=a(n,l,!i,j,!k,m)*delta(!i,n)*delta2(j,l)*delta(!k,m); //attraction\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(other_d,test_precision<data_type>()),std::string(\"Combined Contraction/Attraction 5 for Sparse \")+typeid(data_type).name());\r\n\r\n\r\n\r\n//\r\n\r\n}\r\n\r\n\r\ntemplate<class data_type>\r\nvoid dense_unary_work(){\r\n\r\n    LibMIA::MIAINDEX i;\n    LibMIA::MIAINDEX j;\n    LibMIA::MIAINDEX k;\r\n    LibMIA::MIAINDEX l;\n    LibMIA::MIAINDEX m;\n    LibMIA::MIAINDEX n;\r\n    size_t _dim=5;\n\n    LibMIA::DenseMIA<data_type,6> a(_dim,_dim,_dim,_dim,_dim,_dim);\r\n\r\n    LibMIA::DenseMIA<data_type,4> b;\r\n    LibMIA::DenseMIA<data_type,4> other_b;\r\n    LibMIA::DenseMIA<data_type,3> c;\r\n    LibMIA::DenseMIA<data_type,3> other_c;\r\n    LibMIA::DenseMIA<data_type,2> d;\r\n    LibMIA::DenseMIA<data_type,2> other_d;\r\n    LibMIA::DenseMIA<data_type,1> e;\r\n    LibMIA::DenseMIA<data_type,1> other_e;\r\n    LibMIA::DenseMIA<data_type,5> f;\r\n    LibMIA::DenseMIA<data_type,5> other_f;\r\n    auto delta=LibMIA::create_delta<data_type,2>(_dim);\r\n    auto delta2=LibMIA::create_delta<data_type,2>(_dim+1);\r\n    auto delta_3=LibMIA::create_delta<data_type,3>(_dim);\r\n    a.randu(-5,5);\r\n\r\n\r\n    const LibMIA::DenseMIA<data_type,6> temp_a(a); //check const_correctness\r\n    b(j,k,l,m)=temp_a(i,j,i,k,l,m); //contraction\r\n    other_b(j,k,l,m)=temp_a(i,j,n,k,l,m)*delta(i,n); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(b.fuzzy_equals(other_b,test_precision<data_type>()),std::string(\"Simple Contraction 1 for Dense \")+typeid(data_type).name());\r\n\r\n    a=LibMIA::DenseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+2,_dim-1,_dim-2); //now try with non-uniform dimensions\r\n    a.randu(-5,5);\r\n    b(j,k,l,m)=a(i,j,i,k,l,m); //contraction\r\n    other_b(j,k,l,m)=a(i,j,n,k,l,m)*delta(i,n); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(b.fuzzy_equals(other_b,test_precision<data_type>()),std::string(\"Simple Contraction 2 for Dense \")+typeid(data_type).name());\r\n\r\n    a=LibMIA::DenseMIA<data_type,6>(_dim,_dim+1,_dim,_dim,_dim+2,_dim-2);\r\n    a.randu(-5,5);\r\n    c(j,l,m)=a(i,j,i,i,l,m); //contraction\r\n    other_c(j,l,m)=a(i,j,n,k,l,m)*delta_3(i,n,k); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(other_c,test_precision<data_type>()),std::string(\"Triple Contraction 1 for Dense \")+typeid(data_type).name());\r\n\r\n    a=LibMIA::DenseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+1,_dim-1,_dim-2); //now try with non-uniform dimensions\r\n    a.randu(-5,5);\r\n    d(l,m)=a(i,j,i,j,l,m); //contraction\r\n    other_d(l,m)=a(i,j,n,k,l,m)*delta(i,n)*delta2(j,k); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(other_d,test_precision<data_type>()),std::string(\"Complex Contraction 1 for Dense \")+typeid(data_type).name());\r\n\r\n    a=LibMIA::DenseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+1,_dim,_dim-2); //now try with non-uniform dimensions\r\n    a.randu(-5,5);\r\n    e(m)=a(i,j,i,j,i,m); //contraction\r\n    other_e(m)=a(i,j,n,k,l,m)*delta_3(i,n,l)*delta2(j,k); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(e.fuzzy_equals(other_e,test_precision<data_type>()),std::string(\"Complex Contraction 2 for Dense \")+typeid(data_type).name());\r\n\r\n    d=LibMIA::DenseMIA<data_type,2>(_dim,_dim);\r\n    d.randu(-5,5);\r\n    e(i)=d(!i,!i);\r\n    other_e(i)=d(!i,j)*delta(!i,j);\r\n    BOOST_CHECK_MESSAGE(e.fuzzy_equals(other_e,test_precision<data_type>()),std::string(\"Very Simple Attraction 1 for Dense \")+typeid(data_type).name());\r\n\r\n    c=LibMIA::DenseMIA<data_type,3>(_dim,_dim+1,_dim); //now try with non-uniform dimensions\r\n    c.randu(-5,5);\r\n    d(i,j)=c(!i,j,!i); //attraction\r\n    other_d(i,j)=c(!i,j,n)*delta(!i,n); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(other_d,test_precision<data_type>()),std::string(\"Simple Attraction 1 for Dense \")+typeid(data_type).name());\r\n\r\n\r\n\r\n    a=LibMIA::DenseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+2,_dim-1,_dim-2); //now try with non-uniform dimensions\r\n    a.randu(-5,5);\r\n    f(i,j,k,l,m)=a(!i,j,!i,k,l,m); //attraction\r\n    other_f(i,j,k,l,m)=a(!i,j,n,k,l,m)*delta(!i,n); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(f.fuzzy_equals(other_f,test_precision<data_type>()),std::string(\"Simple Attraction 2 for Dense \")+typeid(data_type).name());\r\n\r\n\r\n    a=LibMIA::DenseMIA<data_type,6>(_dim,_dim+1,_dim,_dim,_dim+2,_dim-2);\r\n    a.randu(-5,5);\r\n    b(i,j,l,m)=a(!i,j,!i,!i,l,m); //attraction\r\n    other_b(i,j,l,m)=a(!i,j,n,k,l,m)*delta_3(!i,n,k); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(b.fuzzy_equals(other_b,test_precision<data_type>()),std::string(\"Triple Attraction 1 for Dense \")+typeid(data_type).name());\r\n\r\n    a=LibMIA::DenseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+1,_dim-1,_dim-2); //now try with non-uniform dimensions\r\n    a.randu(-5,5);\r\n    b(i,j,l,m)=a(!i,!j,!i,!j,l,m); //attraction\r\n    other_b(i,j,l,m)=a(!i,!j,n,k,l,m)*delta(!i,n)*delta2(!j,k); //equivalent operation\r\n\r\n    BOOST_CHECK_MESSAGE(b.fuzzy_equals(other_b,test_precision<data_type>()),std::string(\"Complex Attraction 1 for Dense \")+typeid(data_type).name());\r\n\r\n    a=LibMIA::DenseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+1,_dim,_dim-2); //now try with non-uniform dimensions\r\n    a.randu(-5,5);\r\n    c(i,j,m)=a(!i,!j,!i,!j,!i,m); //attraction\r\n    other_c(i,j,m)=a(!i,!j,n,k,l,m)*delta_3(!i,n,l)*delta2(!j,k); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(other_c,test_precision<data_type>()),std::string(\"Complex Attraction 2 for Dense \")+typeid(data_type).name());\r\n\r\n    b=LibMIA::DenseMIA<data_type,4>(_dim,_dim+1,_dim,_dim+1); //now try with non-uniform dimensions\r\n    b.randu(-5,5);\r\n    d(i,j)=b(!i,!j,!i,!j); //attraction\r\n    other_d(i,j)=b(!i,!j,n,k)*delta(!i,n)*delta2(!j,k); //equivalent operation\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(other_d,test_precision<data_type>()),std::string(\"Complex Attraction 3 for Dense \")+typeid(data_type).name());\r\n\r\n    a=LibMIA::DenseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+1,_dim,_dim-2); //now try with non-uniform dimensions\r\n    a.randu(-5,5);\r\n    c(i,k,m)=a(!i,j,!i,j,k,m); //attraction\r\n    other_c(i,k,m)=a(n,l,!i,j,k,m)*delta(!i,n)*delta2(j,l); //attraction\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(other_c,test_precision<data_type>()),std::string(\"Combined Contraction/Attraction 1 for Dense \")+typeid(data_type).name());\r\n\r\n    b=LibMIA::DenseMIA<data_type,4>(_dim,_dim+1,_dim,_dim+1); //now try with non-uniform dimensions\r\n    b.randu(-5,5);\r\n    e(i)=b(!i,j,!i,j); //attraction\r\n    other_e(i)=b(n,l,!i,j)*delta(!i,n)*delta2(j,l); //attraction\r\n    BOOST_CHECK_MESSAGE(e.fuzzy_equals(other_e,test_precision<data_type>()),std::string(\"Combined Contraction/Attraction 2 for Dense \")+typeid(data_type).name());\r\n\r\n    a=LibMIA::DenseMIA<data_type,6>(_dim,_dim+1,_dim,_dim,_dim+1,_dim-2); //now try with non-uniform dimensions\r\n    a.randu(-5,5);\r\n    d(i,m)=a(!i,j,!i,!i,j,m); //attraction\r\n    other_d(i,m)=a(!i,j,n,k,l,m)*delta_3(!i,n,k)*delta2(j,l); //attraction\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(other_d,test_precision<data_type>()),std::string(\"Combined Contraction/Attraction 3 for Dense \")+typeid(data_type).name());\r\n\r\n    a=LibMIA::DenseMIA<data_type,6>(_dim,_dim+1,_dim,_dim,_dim+1,_dim-2); //now try with non-uniform dimensions\r\n    a.randu(-5,5);\r\n    d(j,m)=a(i,!j,i,i,!j,m); //attraction\r\n    other_d(j,m)=a(i,!j,n,k,l,m)*delta_3(i,n,k)*delta2(!j,l); //attraction\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(other_d,test_precision<data_type>()),std::string(\"Combined Contraction/Attraction 4 for Dense \")+typeid(data_type).name());\r\n\r\n    a=LibMIA::DenseMIA<data_type,6>(_dim,_dim+1,_dim,_dim+1,_dim,_dim); //now try with non-uniform dimensions\r\n    a.randu(-5,5);\r\n    d(i,k)=a(!i,j,!i,j,!k,!k); //attraction\r\n    other_d(i,k)=a(n,l,!i,j,!k,m)*delta(!i,n)*delta2(j,l)*delta(!k,m); //attraction\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(other_d,test_precision<data_type>()),std::string(\"Combined Contraction/Attraction 5 for Dense \")+typeid(data_type).name());\r\n//    d.print();\r\n//    other_d.print();\r\n\r\n\r\n\r\n//\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( MIAUnaryTests )\n{\n\n    dense_unary_work<double>();\n    dense_unary_work<float>();\r\n    dense_unary_work<int>();\r\n    dense_unary_work<long>();\r\n\r\n\r\n    sparse_unary_work<double>();\n    sparse_unary_work<float>();\r\n    sparse_unary_work<int>();\r\n    sparse_unary_work<long>();\r\n\r\n\n\n}\n", "meta": {"hexsha": "d492dac3d50f6504abe9d2990650e562c71f7ed2", "size": 17441, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/MIA/mia_unary_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/MIA/mia_unary_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/MIA/mia_unary_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": 46.018469657, "max_line_length": 164, "alphanum_fraction": 0.6625766871, "num_tokens": 5573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5438129459633461}}
{"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 <cmath>\n#include <cfloat>\n#include <cstdint>\n#include <limits>\n#include <type_traits>\n#include <boost/math/ccmath/isnormal.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\n// Determines if the given argument is normal, i.e. is neither zero, subnormal, infinite nor NaN.\ntemplate <typename T>\nvoid test()\n{\n    if constexpr (std::numeric_limits<T>::has_quiet_NaN)\n    {\n        static_assert(!boost::math::ccmath::isnormal(std::numeric_limits<T>::quiet_NaN()), \"Wrong response to quiet NAN\");\n    }\n\n    static_assert(!boost::math::ccmath::isnormal(T(0)), \"Wrong response to 0\");\n    \n    if constexpr (!std::is_integral_v<T>)\n    {\n        static_assert(!boost::math::ccmath::isnormal((std::numeric_limits<T>::min)() / 2), \"Wrong response to subnormal\");\n        static_assert(!boost::math::ccmath::isnormal(std::numeric_limits<T>::infinity()), \"Wrong response to infinity\");\n    }\n\n    static_assert(boost::math::ccmath::isnormal(T(1)), \"Wrong response to normal number\");\n}\n\n#ifndef BOOST_MATH_NO_CONSTEXPR_DETECTION\nint main()\n{\n    test<float>();\n    test<double>();\n\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test<long double>();\n    #endif\n    \n    #if defined(BOOST_HAS_FLOAT128) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\n    test<boost::multiprecision::float128>();\n    #endif\n\n    test<int>();\n    test<unsigned>();\n    test<long>();\n    test<std::int32_t>();\n    test<std::int64_t>();\n    test<std::uint32_t>();\n\n    return 0;\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "35f1130f313ba5f4cb148457e7b332a738ba0611", "size": 1777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ccmath_isnormal_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/ccmath_isnormal_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/ccmath_isnormal_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": 26.9242424242, "max_line_length": 122, "alphanum_fraction": 0.6826111424, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5438129407638309}}
{"text": "#include <Rcpp.h>\n#include <RcppEigen.h>\n#include <boost/math/special_functions/binomial.hpp>\n\n//[[Rcpp::export(.partialSumEigen)]]\nEigen::VectorXd partialSumEigen(const Eigen::VectorXd & x)\n{\n    const std::size_t N = x.size();\n    Eigen::VectorXd partialSum(N + 1);\n\n    partialSum[0] = 0;\n    for (std::size_t i = 1; i < N + 1; i++)\n    {\n        partialSum[i] = x[i - 1] + partialSum[i - 1];\n    }\n\n    return partialSum;\n}\n\nEigen::MatrixXd bindColumns(const Eigen::MatrixXd & A, const Eigen::MatrixXd & B)\n{\n    Eigen::MatrixXd C(A.rows(), A.cols() + B.cols());\n    C << A, B;\n    return C;\n}\n\n\nEigen::VectorXd STDEigen(const std::vector<double> &x)\n{\n    Eigen::VectorXd xEigen(x.size());\n    for (std::size_t i = 0; i < x.size(); i++)\n        xEigen[i] = x[i];\n\n    return xEigen;\n}\n\nstd::vector<double> EigenSTD(const Eigen::VectorXd &x)\n{\n    std::vector<double> xNEWMAT(x.size());\n    for (std::size_t i = 0; i < x.size(); i++)\n        xNEWMAT[i] = x[i];\n\n    return xNEWMAT;\n}\n\nEigen::Vector2i nonZeroElementsOfMarker(const Eigen::VectorXd & decodedProfile_m)\n{\n    const std::size_t N = decodedProfile_m.size();\n\n    Eigen::Vector2i res;\n    std::size_t i = 0;\n    std::size_t j = 0;\n    while(j < 2)\n    {\n        if (decodedProfile_m[i] != 0)\n        {\n            int k = static_cast<int>(decodedProfile_m[i]);\n            while(k > 0)\n            {\n                res[j] = i;\n                k -= 1;\n                j += 1;\n            }\n        }\n        i += 1;\n    }\n\n    return res;\n}\n\nstd::vector<int> sortedIndex(const Eigen::VectorXd & x)\n{\n    std::vector<int> x_sorted(x.size());\n    std::iota(x_sorted.begin(), x_sorted.end(), 0);\n    auto comparator = [&x](int i, int j){ return x[i] > x[j]; };\n\n    std::sort(x_sorted.begin(), x_sorted.end(), comparator);\n\n    return x_sorted;\n}\n\n//[[Rcpp::export()]]\nEigen::MatrixXd generatePossibleGenotypes(const std::size_t & N)\n{\n    if (N == 1)\n    {\n        Eigen::MatrixXd possibleSingleprofilesMatrix = 2*Eigen::MatrixXd::Ones(N, N);\n        return possibleSingleprofilesMatrix;\n    }\n\n    const std::size_t possibleSingles = N;\n    const std::size_t possiblePairs = boost::math::binomial_coefficient<double>(N, 2);\n\n    const std::size_t totalPossibleOutcomes = possibleSingles + possiblePairs;\n    const std::size_t totalRuns = std::floor(possiblePairs / N);\n\n    Eigen::MatrixXd possibleSingleprofilesMatrix = Eigen::MatrixXd::Zero(N, totalPossibleOutcomes);\n    for (std::size_t i = 0; i < N; i++)\n    {\n        // Single Values\n        Eigen::VectorXd singleVector = Eigen::VectorXd::Zero(N);\n        singleVector(i) = 2;\n        possibleSingleprofilesMatrix.col(i) = singleVector;\n\n        // Paired Values\n        for (std::size_t j = 1; j <= totalRuns; j++)\n        {\n            Eigen::VectorXd pairsVector = Eigen::VectorXd::Zero(N);\n            pairsVector(i) = 1;\n            pairsVector((i + j) % N) = 1;\n            possibleSingleprofilesMatrix.col(j*N + i) = pairsVector;\n        }\n    }\n\n    // Remaining Paired Values\n    for (std::size_t k = (totalRuns + 1)*N; k < totalPossibleOutcomes; k++)\n    {\n        Eigen::VectorXd pairsVector = Eigen::VectorXd::Zero(N);\n        pairsVector(k % N) = 1;\n        pairsVector(((k % N) + (totalRuns + 1)) % N) = 1;\n        possibleSingleprofilesMatrix.col(k) = pairsVector;\n    }\n\n    return possibleSingleprofilesMatrix;\n}\n", "meta": {"hexsha": "3d6f577ff4102a5c6d9849998bf47c823b9620cc", "size": 3352, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AuxiliaryFunctions.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/AuxiliaryFunctions.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/AuxiliaryFunctions.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": 26.6031746032, "max_line_length": 99, "alphanum_fraction": 0.5832338902, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5437777255401707}}
{"text": "/** @file */\n#pragma once\n#include <boost/math/tools/minima.hpp>\n#include <cmath>\n#include <string_view>\n\nnamespace pw85 {\n\nnamespace metadata {\nconstexpr std::string_view author{\"S. Brisard\"};\n// clang-format off\nconstexpr std::string_view description{\"Implementation of the \\\"contact function\\\" defined by Perram and Wertheim (J. Comp. Phys. 58(3), 409-416, DOI:10.1016/0021-9991(85)90171-8) for two ellipsoids.\"};\n// clang-format on\nconstexpr std::string_view author_email{\"sebastien.brisard@univ-eiffel.fr\"};\nconstexpr std::string_view license{\"BSD 3-Clause License\"};\nconstexpr std::string_view name{\"pw85\"};\nconstexpr std::string_view url{\"https://github.com/sbrisard/pw85\"};\nconstexpr std::string_view version{\"2.0\"};\nconstexpr std::string_view year{\"2021\"};\n}  // namespace metadata\n\n/** The dimension of the physical space (3).*/\nconstexpr size_t dim = 3;\n\n/** The dimension of the space of symmetric matrices (6). */\nconstexpr size_t sym = 6;\n\n/*\n * For the Brent algorithm, these two constants should be such that\n *\n * [(3 - sqrt(5)) / 2] ** n < eps\n *\n * where\n *\n *     n = max_iter\n *     eps = lambda_atol\n */\n\n/**\n * The absolute tolerance for the stopping criterion of Brent\u2019s method (in\n * function contact_function()).\n */\nconstexpr double lambda_atol = 1e-6;\n\n/**\n * The maximum number of iterations of Brent\u2019s method (in function\n * contact_function()).\n */\nconstexpr size_t max_iter = 25;\n\n/**\n * The total number of iterations of the Newton\u2013Raphson refinement phase (in\n * function contact_function()).\n */\nconstexpr size_t nr_iter = 3;\n\n/**\n * Compute the Cholesky decomposition of a symmetric, positive matrix.\n *\n * Let `A` be a symmetric, positive matrix, defined by the `double[6]` array\n * `a`. This function computes the lower-triangular matrix `L`, defined by\n * the `double[6]` array `l`, such that `L\u1d40\u22c5L = A`.\n *\n * The array `l` must be pre-allocated; it is modified by this function. Note\n * that storage of the coefficients of `L` is as follows\n *\n * ```\n *     \u23a1 l[0]    0    0 \u23a4\n * L = \u23a2 l[1] l[3]    0 \u23a5.\n *     \u23a3 l[2] l[4] l[5] \u23a6\n * ```\n */\nvoid _cholesky_decomp(double const *a, double *l) {\n  l[0] = sqrt(a[0]);\n  l[1] = a[1] / l[0];\n  l[2] = a[2] / l[0];\n  l[3] = sqrt(a[3] - l[1] * l[1]);\n  l[4] = (a[4] - l[1] * l[2]) / l[3];\n  l[5] = sqrt(a[5] - l[2] * l[2] - l[4] * l[4]);\n}\n\n/**\n * Compute the solution to a previously Cholesky decomposed linear system.\n *\n * Let `L` be a lower-triangular matrix, defined by the `double[6]` array `l`\n * (see pw85::_cholesky_decomp() for ordering of the coefficients). This\n * function solves (by substitution) the linear system `L\u1d40\u22c5L\u22c5x = b`, where the\n * vectors `x` and `b` are specified through their `double[3]` array of\n * coordinates; `x` is modified by this function.\n */\nvoid _cholesky_solve(const double *l, const double *b, double *x) {\n  /* Solve L.y = b */\n  double const y0 = b[0] / l[0];\n  double const y1 = (b[1] - l[1] * y0) / l[3];\n  double const y2 = (b[2] - l[2] * y0 - l[4] * y1) / l[5];\n\n  /* Solve L^T.x = y */\n  x[2] = y2 / l[5];\n  x[1] = (y1 - l[4] * x[2]) / l[3];\n  x[0] = (y0 - l[1] * x[1] - l[2] * x[2]) / l[0];\n}\n\n/**\n * Compute the quadratic form associated to a spheroid.\n *\n * The spheroid is defined by its equatorial radius `a`, its polar radius `c`\n * and the direction of its axis of revolution, `n` (unit-vector, `double[3]`\n * array).\n *\n * `q` is the representation of a symmetric matrix as a `double[6]` array. It is\n * modified in-place.\n */\nvoid spheroid(double a, double c, const double *n, double *q) {\n  double const a2 = a * a;\n  double const c2_minus_a2 = c * c - a2;\n  double const nx = n[0];\n  double const ny = n[1];\n  double const nz = n[2];\n  q[0] = nx * nx * c2_minus_a2 + a2;\n  q[3] = ny * ny * c2_minus_a2 + a2;\n  q[5] = nz * nz * c2_minus_a2 + a2;\n  q[4] = ny * nz * c2_minus_a2;\n  q[2] = nx * nz * c2_minus_a2;\n  q[1] = nx * ny * c2_minus_a2;\n}\n\n/**\n * Return the value of the opposite of the function ``f`` defined as (see\n * @verbatim embed:rst:inline :ref:`theory`@endverbatim).\n *\n * @f[f(\\lambda)=\\lambda\\bigl(1-\\lambda\\bigr)r_{12}^{\\mathsf{T}}\n *               \\cdot Q^{-1}\\cdot r_{12},@f]\n *\n * with\n *\n * @f[Q = \\bigl(1-\\lambda\\bigr)Q_1 + \\lambda Q_2,@f]\n *\n * where ellipsoids 1 and 2 are defined as the sets of points @f$m@f$\n * (column-vector) such that\n *\n * @f[\\bigl(m-c_i\\bigr)\\cdot Q_i^{-1}\\cdot\\bigl(m-c_i\\bigr)\\leq1.@f]\n *\n * In the above inequality, @f$c_i@f$ is the center; @f$r_{12}=c_2-c_1@f$ is the\n * center-to-center radius-vector, represented by the `double[3]` array `r12`.\n * The symmetric, positive-definite matrices @f$Q_1@f$ and @f$Q_2@f$ are\n * specified through the `double[6]` arrays `q1` and `q2`.\n *\n * The value of @f$\\lambda@f$ is specified through the parameter ``lambda``.\n *\n * This function returns the value of @f$\u2212f(\\lambda)@f$ (the \u201cminus\u201d sign comes\n * from the fact that we seek the maximum of @f$f@f$, or the minimum of\n * @f$\u2212f@f$).\n *\n * This implementation uses\n * @verbatim embed:rst:inline:ref:`Cholesky decompositions\n * <implementation-cholesky>`@endverbatim.\n */\ndouble f_neg(double lambda, const double *r12, const double *q1,\n             const double *q2) {\n  double const *q1_i = q1;\n  double const *q2_i = q2;\n  double q[sym];\n  double *q_i = q;\n  double q12[sym];\n  double *q12_i = q12;\n  for (size_t i = 0; i < sym; i++, q1_i++, q2_i++, q_i++, q12_i++) {\n    *q_i = (1 - lambda) * (*q1_i) + lambda * (*q2_i);\n    *q12_i = (*q2_i) - (*q1_i);\n  }\n  double l[sym];\n  _cholesky_decomp(q, l);\n  double s[dim];\n  _cholesky_solve(l, r12, s);\n  double const *r_i = r12;\n  double *s_i = s;\n  double rs = 0.;\n  for (size_t i = 0; i < dim; i++, r_i++, s_i++) {\n    rs += (*r_i) * (*s_i);\n  }\n  return -lambda * (1. - lambda) * rs;\n}\n\n/**\n * Compute the residual \\f$g(\\lambda)=\\mu_2^2-\\mu_1^2\\f$.\n *\n * See @verbatim embed:rst:inline :ref:`optimization` @endverbatim for the\n * definition of \\f$g\\f$. The value of \\f$\\lambda\\f$ is specified through the\n * parameter `lambda`. See contact_function() for the definition of the\n * parameters `r12`, `q1` and `q2`.\n *\n * The preallocated `double[3]` array `out` is updated as follows:\n * `out[0]=`\\f$f(\\lambda)\\f$, `out[1]=`\\f$g(\\lambda)\\f$ and\n * `out[2]=`\\f$g'(\\lambda)\\f$.\n *\n * This function is used in function\n * @verbatim embed:rst:inline :cpp:func:`pw85::contact_function` @endverbatim\n * for the final Newton\u2013Raphson refinement step.\n */\nvoid _residual(double lambda, const double *r12, const double *q1,\n               const double *q2, double *out) {\n  double q[sym];\n  double q12[sym];\n  for (size_t i = 0; i < sym; i++) {\n    q[i] = (1. - lambda) * q1[i] + lambda * q2[i];\n    q12[i] = q2[i] - q1[i];\n  }\n  double l[sym];\n  _cholesky_decomp(q, l);\n  double s[dim];\n  _cholesky_solve(l, r12, s);\n  double u[] = {q12[0] * s[0] + q12[1] * s[1] + q12[2] * s[2],\n                q12[1] * s[0] + q12[3] * s[1] + q12[4] * s[2],\n                q12[2] * s[0] + q12[4] * s[1] + q12[5] * s[2]};\n  double v[dim];\n  _cholesky_solve(l, u, v);\n  double rs = r12[0] * s[0] + r12[1] * s[1] + r12[2] * s[2];\n  double su = s[0] * u[0] + s[1] * u[1] + s[2] * u[2];\n  double uv = u[0] * v[0] + u[1] * v[1] + u[2] * v[2];\n\n  out[0] = lambda * (1. - lambda) * rs;\n  out[1] = (2 * lambda - 1.) * rs + lambda * (1. - lambda) * su;\n  out[2] =\n      2. * rs + 2. * (1. - 2. * lambda) * su - 2. * lambda * (1. - lambda) * uv;\n}\n\n/**\n * Compute the value of the contact function of two ellipsoids.\n *\n * The center-to-center radius-vector @f$r_{12}@f$ is specified by the\n * `double[3]` array `r12`. The symmetric, positive-definite matrices @f$Q_1@f$\n * and @f$Q_2@f$ that define the two ellipsoids are specified through the\n * `double[6]` arrays `q1` and `q2`.\n *\n * This function computes the value of @f$\\mu^2@f$, defined as\n *\n * @f[\\mu^2=\\max_{0\\leq\\lambda\\leq 1}\\bigl\\{\\lambda\\bigl(1-\\lambda\\bigr)\n * r_{12}^{\\mathsf{T}}\\cdot\\bigl[\\bigl(1-\\lambda\\bigr)Q_1+\\lambda Q_2\\bigr]^{-1}\n * \\cdot r_{12}\\bigr\\},@f]\n *\n * and the maximizer @f$\\lambda@f$, see\n * @verbatim embed:rst:inline:ref:`theory` @endverbatim. Both values are stored\n * in the preallocated `double[2]` array `out`: `out[0] = `@f$\\mu^2@f$ and\n * `out[1] = `@f$\\lambda@f$.\n *\n * @f$\\mu@f$ is the common factor by which the two ellipsoids must be scaled\n * (their centers being fixed) in order to be tangentially in contact.\n *\n * This function returns `0`.\n *\n * @verbatim embed:rst:leading-asterisk\n * .. todo:: This function should return an error code.\n * @endverbatim\n */\nint contact_function(const double *r12, const double *q1, const double *q2,\n                     double *out) {\n  auto f = [r12, q1, q2](double lambda) { return f_neg(lambda, r12, q1, q2); };\n\n  auto r = boost::math::tools::brent_find_minima(\n      f, 0., 1., std::numeric_limits<double>::digits / 2);\n  auto lambda_brent = r.first;\n  auto mu2_brent = -r.second;\n\n  double out_res[3];\n  _residual(lambda_brent, r12, q1, q2, out_res);\n  double res_brent = fabs(out_res[1]);\n\n  /* Try to refine the estimate. */\n  double lambda_nr = lambda_brent;\n  double mu2_nr = mu2_brent;\n  double res_nr = res_brent;\n\n  for (size_t i = 0; i < nr_iter; i++) {\n    double lambda_trial = lambda_nr - out_res[1] / out_res[2];\n    if ((lambda_trial < 0.) || (lambda_trial > 1.)) {\n      break;\n    }\n    _residual(lambda_trial, r12, q1, q2, out_res);\n    lambda_nr = lambda_trial;\n    mu2_nr = out_res[0];\n    res_nr = fabs(out_res[1]);\n  }\n\n  if (res_nr < res_brent) {\n    out[0] = mu2_nr;\n    out[1] = lambda_nr;\n  } else {\n    out[0] = mu2_brent;\n    out[1] = lambda_brent;\n  }\n\n  /* TODO: return error code. */\n  return 0;\n}\n}  // namespace pw85\n", "meta": {"hexsha": "57f35f2f6101bb4d1f569a16b2ab2b711e762750", "size": 9594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pw85/pw85.hpp", "max_stars_repo_name": "sbrisard/pw85", "max_stars_repo_head_hexsha": "515da5a74002c956c9e12b4918659a51b92eca37", "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/pw85/pw85.hpp", "max_issues_repo_name": "sbrisard/pw85", "max_issues_repo_head_hexsha": "515da5a74002c956c9e12b4918659a51b92eca37", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-08-02T07:15:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-24T04:52:38.000Z", "max_forks_repo_path": "include/pw85/pw85.hpp", "max_forks_repo_name": "sbrisard/pw85", "max_forks_repo_head_hexsha": "515da5a74002c956c9e12b4918659a51b92eca37", "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.5220338983, "max_line_length": 202, "alphanum_fraction": 0.613404211, "num_tokens": 3399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5437777178742828}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <deque>\n#include <time.h>\n\n#include <boost/random/linear_congruential.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_utility.hpp>\n\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/strong_components.hpp>\n#include <boost/graph/topological_sort.hpp>\n\n#include <boost/graph/cuthill_mckee_ordering.hpp>\n#include <boost/graph/king_ordering.hpp>\n//#include <boost/graph/minimum_degree_ordering.hpp>\n#include <boost/graph/sloan_ordering.hpp>\n#include <boost/graph/properties.hpp>\n\n#include <boost/graph/rmat_graph_generator.hpp>\n#include <boost/graph/erdos_renyi_generator.hpp>\n#include <boost/graph/small_world_generator.hpp>\n#include <boost/graph/plod_generator.hpp>\n\n#include \"options.h\"\n#include \"utils.h\"\n\nusing namespace std;\nusing namespace boost;\n\nclass custom_bfs_visitor : public default_bfs_visitor {\npublic:\n\ttemplate <typename Vertex, typename Graph>\n\tvoid discover_vertex(Vertex v, const Graph& g) const {\n\t\tcout << v << endl;\n\t}\n};\n\nclass custom_dfs_visitor : public default_dfs_visitor {\npublic:\n\ttemplate <typename Vertex, typename Graph>\n\tvoid discover_vertex(Vertex v, const Graph& g) const {\n\t\tcout << v << endl;\n\t}\n};\n\ntemplate <class Graph>\nunsigned int get_edges(char* edges_file, Graph& g) {\n\tunsigned int u, v, total = 0;\n\tstring line;\n\tif (edges_file) {\n\t\tifstream ifs(edges_file);\n\t\tif(ifs) {\n\t\t\twhile (getline(ifs, line)) {\n\t\t\t\tSSCANF((line.c_str(), \"%u %u\", &u, &v));\n\t\t\t\tadd_edge(u, v, g);\n\t\t\t\t++total;\n\t\t\t}\n\t\t\tifs.close();\n\t\t}\n\t} else {\n\t\twhile (getline(cin, line)) {\n\t\t\tSSCANF((line.c_str(), \"%u %u\", &u, &v));\n\t\t\tadd_edge(u, v, g);\n\t\t\t++total;\n\t\t}\n\t}\n\treturn total;\n}\n\nint graph_gen(char* generator, char* parameters) {\n\tunsigned int total_vertices = 256, total_edges = 0;\n\tboost::minstd_rand gen;\n\tgen.seed((unsigned int)time(NULL));\n\n\tif (!generator || !(strcmp(generator, \"rmat\") && strcmp(generator, \"RMAT\"))) {\n\t\ttypedef rmat_iterator<boost::minstd_rand, adjacency_list<>> rmat_gen;\n\t\tunsigned int scale_v = 8, scale_e = 8;\n\t\tif (parameters) SSCANF((parameters, \"%u:%u\", &scale_v, &scale_e));\n\t\ttotal_vertices = 1 << scale_v;\n\t\ttotal_edges    = total_vertices * scale_e;\n\t\tauto it       = rmat_gen(gen, total_vertices, total_edges, 0.57, 0.19, 0.19, 0.05);\n\t\tauto it_last  = rmat_gen();\n\t\tfor (;it != it_last; ++it) cout << it->first << \" \" << it->second << endl;\n\t} else if (!(strcmp(generator, \"er\") && strcmp(generator, \"ER\"))) {\n\t\ttypedef erdos_renyi_iterator<boost::minstd_rand, adjacency_list<>> er_gen;\n\t\tdouble probability = 0.05;\n\t\tif (parameters) SSCANF((parameters, \"%u:%lf\", &total_vertices, &probability));\n\t\tauto it       = er_gen(gen, total_vertices, probability);\n\t\tauto it_last  = er_gen();\n\t\tfor (;it != it_last; ++it) cout << it->first << \" \" << it->second << endl;\n\t} else if (!(strcmp(generator, \"sw\") && strcmp(generator, \"SW\"))) {\n\t\ttypedef small_world_iterator<boost::minstd_rand, adjacency_list<>> sw_gen;\n\t\tunsigned int   knn         = 6;\n\t\tdouble probability = 0.03;\n\t\tif (parameters) SSCANF((parameters, \"%u:%u:%lf\", &total_vertices, &knn, &probability));\n\t\tauto it       = sw_gen(gen, total_vertices, knn, probability);\n\t\tauto it_last  = sw_gen();\n\t\tfor (;it != it_last; ++it) cout << it->first << \" \" << it->second << endl;\n\t} else if (!(strcmp(generator, \"sf\") && strcmp(generator, \"SF\"))) {\n\t\ttypedef plod_iterator<boost::minstd_rand, adjacency_list<>> sf_gen;\n\t\tdouble alpha = 2.7;\n\t\tunsigned int   beta  = 256;\n\t\tif (parameters) SSCANF((parameters, \"%u:%lf:%u\", &total_vertices, &alpha, &beta));\n\t\tauto it       = sf_gen(gen, total_vertices, alpha, beta);\n\t\tauto it_last  = sf_gen();\n\t\tfor (;it != it_last; ++it) cout << it->first << \" \" << it->second << endl;\n\t} else {\n\t\tcout << \"Available generators: RMAT, ER, SW, SF.\" << endl;\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\ntemplate <class Graph>\nbool has_self_loop(const Graph& g) {\n\tBGL_FORALL_EDGES_T(e, g, Graph)\n\t\tif (source(e, g) == target(e, g)) return true;\n\treturn false;\n}\n\ntemplate <class Graph>\nbool is_dag(const Graph& g) {\n\tunsigned int total_vertices = num_vertices(g);\n\tvector<unsigned int> component(total_vertices);\n\tunsigned int total_components = strong_components(g, make_iterator_property_map(component.begin(), get(vertex_index, g)));\n\treturn (total_components == total_vertices) && !has_self_loop(g);\n}\n\n//template <class Graph>\n//bool isSymmetric(const Graph &g) {\n//    std::pair<graph_traits<adjacency_list<setS, vecS, directedS> >::edge_descriptor, bool> tmp;\n//\tBGL_FORALL_EDGES_T(e, g, Graph){\n//        tmp = edge(target(e, g), source(e, g), g);\n//        if (tmp.second == false) return false;\n//    }\n//\treturn true;\n//}\n\ntemplate <class Graph>\nint dir_graph_op(Graph& g, char* algorithm, unsigned int v_root) {\n\tif (!(strcmp(algorithm, \"bfs\") && strcmp(algorithm, \"BFS\"))) {\n\t\tcustom_bfs_visitor b_v;\n\t\tbreadth_first_search(g, vertex(v_root, g), visitor(b_v));\n\t} else if (!(strcmp(algorithm, \"dfs\") && strcmp(algorithm, \"DFS\"))) {\n\t\tcustom_dfs_visitor d_v;\n\t\tdepth_first_search(g, root_vertex(vertex(v_root, g)).visitor(d_v));\n\t} else if (!(strcmp(algorithm, \"scc\") && strcmp(algorithm, \"SCC\"))) {\n\t\tunsigned int total_vertices = num_vertices(g);\n\t\tvector<unsigned int> component(total_vertices);\n\t\tunsigned int total_components = strong_components(g, make_iterator_property_map(component.begin(), get(vertex_index, g)));\n\t\tunsigned int i = 0;\n\t\tfor (auto c: component) cout << i++ << \" \" << c << endl;\n\t} else if (!(strcmp(algorithm, \"ts\") && strcmp(algorithm, \"TS\"))) {\n\t\tif (is_dag(g)) {\n\t\t\tdeque<unsigned int> topological_order;\n\t\t\ttopological_sort(g, front_inserter(topological_order));\n\t\t\tfor (auto o: topological_order) cout << o << endl;\n\t\t} else cout << \"not DAG\" << endl;\n\t//} else if(!(strcmp(algorithm, \"mdo\") && strcmp(algorithm, \"MDO\"))) {\n\t//\tif(isSymmetric(g)) {\n\t//\t\tunsigned int n = num_vertices(g);\n\t//\t\tvector<int> degree(n, 0);\n\t//\t\tvector<int> supernode_sizes(n, 1);\n\t//\t\tvector<int> inv_perm(n, 0);//build_permutation(InversePermutationMap next,PermutationMap prev)(minimum_degree_ordering.hpp)\n\t//\t\tvector<int> perm(n, 0); //prev[i] and next[i] can be negative,so vector inv_perm and perm shouldn't be unsigned int \n\t//\t\tminimum_degree_ordering(g,\n\t//\t\t\tmake_iterator_property_map(&degree[0], get(vertex_index,g), degree[0]),\n\t//\t\t\t&inv_perm[0],\n\t//\t\t\t&perm[0],\n\t//\t\t\tmake_iterator_property_map(&supernode_sizes[0], get(vertex_index, g), supernode_sizes[0]), 0, get(vertex_index, g));\n\t//\t\tfor (auto p: inv_perm) cout << p << endl;\n\t//\t} else cout << \"The metrix of graph is not SYMMETRIC !\" << endl;\n\t} else {\n\t\tcout << \"Algorithm [\" << algorithm << \"] is not available (for directed graph).\" << endl;\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\ntemplate <class Graph>\nint undir_graph_op(Graph& g, char* algorithm, unsigned int v_root) {\n\tif (!(strcmp(algorithm, \"bfs\") && strcmp(algorithm, \"BFS\"))) {\n\t\tcustom_bfs_visitor b_v;\n\t\tbreadth_first_search(g, vertex(v_root, g), visitor(b_v));\n\t} else if (!(strcmp(algorithm, \"dfs\") && strcmp(algorithm, \"DFS\"))) {\n\t\tcustom_dfs_visitor d_v;\n\t\tdepth_first_search(g, root_vertex(vertex(v_root, g)).visitor(d_v));\n\t} else if (!(strcmp(algorithm, \"cmo\") && strcmp(algorithm, \"CMO\"))) {\n\t\tvector<unsigned int> cuthill_mckee_order(num_vertices(g));\n\t\tcuthill_mckee_ordering(g, cuthill_mckee_order.rbegin()); \n\t\tfor (auto cmo: cuthill_mckee_order) cout << cmo << endl;\n\t} else if (!(strcmp(algorithm, \"ko\") && strcmp(algorithm, \"KO\"))) {\n\t\tvector<unsigned int> king_order(num_vertices(g));\n\t\tking_ordering(g, king_order.rbegin());\n\t\tfor (auto ko: king_order) cout << ko << endl;\n\t} else if(!(strcmp(algorithm, \"so\") && strcmp(algorithm, \"SO\"))) {\n\t\tvector<unsigned int> sloan_order(num_vertices(g));\n\t\tsloan_ordering(g, sloan_order.begin(), get(vertex_color, g), make_degree_map(g), get(vertex_priority, g));\n\t\tfor (auto so: sloan_order) cout << so <<endl;\n\t} else {\n\t\tcout << \"Algorithm [\" << algorithm << \"] is not available (for undirected graph).\" << endl;\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\ntemplate <class Graph>\nvoid print_edges(const Graph& g) {\n\tBGL_FORALL_EDGES_T(e, g, Graph)\n\t\tcout << source(e, g) << \" \" << target(e, g) << endl;\n}\n\nint main(int argc, char* argv[]) {\n\tusing namespace opt;\n\n\tconst char* usage =\n\t\t\"bgl-shell [options]\\n\"\n\t\t\" -h:\\t ask for help\\n\"\n\t\t\"\\n\"\n\t\t\" generators\\n\"\n\t\t\" -g:\\t (RMAT) use generator [RMAT|ER|SW|SF]\\n\"\n\t\t\" -p:\\t set graph generator parameters\\n\"\n\t\t\" \\t   Generator         Parameters\\n\"\n\t\t\" \\t   ---------         ----------\\n\"\n\t\t\" \\t   Recursive-MATrix  8:8\\n\"\n\t\t\" \\t   Erdos-Renyi       256:0.05\\n\"\n\t\t\" \\t   Small-World       256:6:0.03\\n\"\n\t\t\" \\t   Scale-Free        256:2.7:256\\n\"\n\t\t\"\\n\"\n\t\t\" algorithms\\n\"\n\t\t\" default to print adjacency list\\n\"\n\t\t\" -e:\\t perform [BFS|DFS|SCC|TS|CMO|KO|SO], etc.\\n\"\n\t\t\" \\t   BFS: breadth-first traversal       (directed|undirected)\\n\"\n\t\t\" \\t   DFS: depth-first traversal         (directed|undirected)\\n\"\n\t\t\" \\t   SCC: strongly connected components (directed)\\n\"\n\t\t\" \\t   TS:  topological sort              (directed acyclic graph)\\n\"\n\t\t\" \\t   CMO: cuthill mckee ordering        (undirected)\\n\"\n\t\t\" \\t   KO:  king ordering                 (undirected)\\n\"\n\t\t\" \\t   SO:  sloan ordering                (undirected)\\n\"\n\t\t\" -i:\\t (cin) input edge list\\n\"\n\t\t\" -u:\\t treat input edge list as undirected\\n\"\n\t\t\" -r:\\t specify root vertex for graph traversal\\n\"\n\t\t\"\\n\";\n\n\tif (chkOption(argv, argv + argc, \"-h\")) {\n\t\tcout << usage;\n\t\treturn 0;\n\t}\n\n\tbool  use_gen    = chkOption(argv, argv + argc, \"-g\");\n\tbool  is_undir   = chkOption(argv, argv + argc, \"-u\");\n\tchar* generator  = getOption(argv, argv + argc, \"-g\");\n\tchar* gen_param  = getOption(argv, argv + argc, \"-p\");\n\tchar* edges_file = getOption(argv, argv + argc, \"-i\");\n\tchar* algorithm  = getOption(argv, argv + argc, \"-e\");\n\tunsigned int  v_root     = getInt(argv, argv + argc, \"-s\", 0);\n\n\ttypedef adjacency_list<setS, vecS,   directedS, no_property> graph_t;\n\ttypedef property<vertex_color_t, default_color_type, property<vertex_degree_t, int, property<vertex_priority_t, double> > > vertex_p;\n\ttypedef adjacency_list<setS, vecS, undirectedS, vertex_p> graph_u_p_t;\n\n\tif (use_gen) {\n\t\tgraph_gen(generator, gen_param); \n\t} else if (is_undir) {\n\t\tgraph_u_p_t g;\n\t\tget_edges(edges_file, g);\n\t\tif(algorithm) {\n\t\t\tundir_graph_op(g, algorithm, v_root);\n\t\t}\n\t} else {\n\t\tgraph_t g;\n\t\tget_edges(edges_file, g);\n\t\tif(algorithm) {\n\t\t\tdir_graph_op(g, algorithm, v_root);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "a23ba2e2f70b2dee7adc0cdfd15312b5be654d86", "size": 10501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bgl-shell.cpp", "max_stars_repo_name": "ShiZhan/graph-study", "max_stars_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-14T07:27:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-15T03:11:31.000Z", "max_issues_repo_path": "src/bgl-shell.cpp", "max_issues_repo_name": "Zhan2012/graph-study", "max_issues_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bgl-shell.cpp", "max_forks_repo_name": "Zhan2012/graph-study", "max_forks_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "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.9753521127, "max_line_length": 134, "alphanum_fraction": 0.6627940196, "num_tokens": 3112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5437777085472453}}
{"text": "#include <stdlib.h>\n#include <vector>\n#include <stdint.h>\n#include <iostream>\n//#include <boost/range.hpp>\n#include <algorithm>\n#include <boost/range/irange.hpp>\n//#include <boost/range/algorithm.hpp>\n#include <boost/range/adaptors.hpp>\n#include <random>\n#include <stack>\n\nnamespace tmpl {\n\nvoid printList( const std::vector< int64_t > & list, const char * text = \"\" )\n{\n    std::cout << text;\n    \n    for( int64_t i = 0; i < list.size(); ++i )\n    {\n        std::cout << list[i] << \" \";\n    }\n\n    printf( \"\\n\\n\" );\n}\n\nvoid printList( const std::vector< int64_t > & list, const std::vector< int64_t > & pivots, const int64_t to_swap, const char * text = \"\" )\n{\n    std::cout << text;\n    \n    for( int64_t i = 0; i < list.size(); ++i )\n    {\n        auto iter = std::find( std::begin(pivots), std::end(pivots), i);\n        if( iter != std::end(pivots) )\n        {\n            std::cout << \"[\" << list[i] << \"],\";\n        }\n        else if( i == to_swap )\n        {\n            std::cout << \"{\" << list[i] << \"},\";\n        }\n        else\n            std::cout << list[i] << \",\";\n    }\n\n    printf( \"\\n\\n\" );\n}\n\nvoid printPivots( const std::vector< int64_t > & arr, const std::vector< int64_t > & pivots )\n{\n    std::cout << \"PivotValues=\";\n    \n    for( auto & pivot : pivots ) {\n        std::cout << arr[pivot] << \",\";\n    }\n    \n    std::cout << \"\\n\\n\";\n}\n\ntemplate< int Pivots >\ninline std::array<int64_t, Pivots> sort_pivots( std::vector<int64_t> & arr, int64_t start, int64_t end, std::array< int64_t, Pivots > && pivots )\n{\n    std::sort( std::begin( pivots ), std::end( pivots ) );\n   \n    std::array< int64_t, Pivots > new_pivots;\n    \n    int64_t first_pivot = start;\n    for( const auto p : pivots  | boost::adaptors::indexed(0) )\n    {\n        new_pivots[p.index()] = first_pivot;\n\n        std::swap( arr[p.value()], arr[first_pivot]);\n\n        ++first_pivot;\n    }\n    \n    auto iter = std::begin( arr ) + start;\n    \n    std::sort( iter, iter + pivots.size() );\n    \n    return new_pivots;\n}\n\ntemplate< int Pivots >\ninline std::array< int64_t, Pivots > get_pivot( std::vector< int64_t > & arr, int64_t l, int64_t r )\n{\n    static std::random_device rd; // obtain a random number from hardware\n    static std::mt19937 gen(rd()); // seed the generator\n\n    std::uniform_int_distribution<> distr(l, r); // define the range\n    \n    std::array< int64_t, Pivots > pivots;\n\n    for( int64_t i = 0; i < Pivots; ++i )\n    {\n        while( true ) {\n            auto new_pivot = distr(gen);\n            auto iter = std::find( std::begin( pivots ), std::end( pivots ), new_pivot );\n            \n            if( iter != std::end( pivots ) ) continue;\n            \n            pivots[i] = new_pivot;\n            break;\n        }\n    }\n    \n    // sorting part\n    return sort_pivots< Pivots >( arr, l, r, std::move(pivots) );\n}\n\ntemplate< int Pivots >\ninline std::array< bool, Pivots+1 > less_or_equal( const std::vector< int64_t > & arr, const std::array<int64_t, Pivots> & pivots, const int64_t value )\n{\n    std::array< bool, Pivots+1 > output;\n    output.fill( true );\n\n    int64_t index = 0;\n\n    for( const auto p : pivots ) {\n        const auto res = arr[p] >= value;\n\n        if( res ) break;\n\n        output[index++] = res;\n    }\n    \n    return output;\n}\n\ntemplate< int Pivots >\ninline std::array< bool, Pivots+1 > greater( const std::vector< int64_t > & arr, const std::array<int64_t, Pivots> & pivots, const int64_t value )\n{\n    std::array< bool, Pivots+1 > output;\n    output.fill( true );\n\n    int64_t index = pivots.size();\n    \n    for( const auto p : pivots | boost::adaptors::reversed ) {\n        const auto res = arr[p] < value;\n        \n        // since all the pivot values are sorted, thus if value greater \n        // then last pivot implies that for the remaining pivots it also greater\n        if( res ) break;\n        \n        output[index--] = res;\n    }\n\n    return output;\n}\n\n// TODO: cover with test\ntemplate< int Pivots >\ninline int64_t identify_new_sector( const std::vector< int64_t > & arr, const std::array<int64_t, Pivots> & pivots, const int64_t value )\n{\n    const auto lq = less_or_equal<Pivots>( arr, pivots, value );\n    const auto gt = greater<Pivots>( arr, pivots, value );\n\n    int64_t index = 0;\n\n    for( const auto l : lq | boost::adaptors::indexed(0) )\n    {\n        const auto idx = l.index();\n\n        if( l.value() && gt[index] )\n        {\n            index = idx;\n            break;\n        } \n    }\n\n    return index;\n}\n\ntemplate< int Pivots >\ninline std::array<int64_t, Pivots> general_partition( std::vector<int64_t> & arr, int64_t l, int64_t r, std::array<int64_t, Pivots> && pivots )\n{\n    for( const auto i : boost::irange<int64_t>( l + pivots.size()-1, r+1 ) )\n    {\n        const auto iter = std::find( std::begin( pivots ), std::end( pivots ), i );\n\n        if( iter != std::end( pivots ) )\n            continue;\n        \n        const auto new_sector = identify_new_sector<Pivots>( arr, pivots, arr[i] );\n\n        // check if value already in right sector\n        if( new_sector == pivots.size() )\n            continue;\n\n        int64_t new_i = i;\n        for( const auto sector : boost::irange<int64_t>( new_sector, pivots.size() ) | boost::adaptors::reversed )\n        {\n            auto & pivot( pivots[sector] );\n\n            if( new_i > sector+1 )\n                std::swap( arr[ pivot + 1 ], arr[new_i] );\n\n            std::swap( arr[ pivot ], arr[ pivot + 1 ] );\n            \n            new_i = pivot;\n            pivot += 1;\n        }\n    }\n    \n    return std::move( pivots );\n}\n\nstruct stack_node {\n    int64_t l;\n    int64_t r;\n};\n\ntemplate< int Pivots >\nvoid quicksort( std::vector< int64_t > & arr )\n{\n    std::stack< stack_node > stck;\n    stck.push( stack_node{0, static_cast<int64_t>(arr.size() - 1) } );\n\n    while( !stck.empty() ) \n    {\n        auto sn = stck.top();\n        stck.pop();\n\n        int64_t l = sn.l;\n        int64_t r = sn.r;\n        \n        if( abs(r-l) <= 10 ) {\n            std::sort( std::begin( arr )+l, std::begin( arr )+r+1 );\n            continue;\n        }\n   \n        auto pivots = general_partition<Pivots>( arr, l, r, get_pivot< Pivots >( arr, l, r ) );\n\n        for( const auto pivot : pivots )\n        {\n            stck.push( stack_node{l, pivot - 1} );\n\n            l = pivot + 1;\n        }\n\n        stck.push( stack_node{pivots.back()+1, r} );     \n    }\n}\n\n} // namespace tmpl", "meta": {"hexsha": "d067ba82c25deff3cf167590b3607a9b7874faac", "size": 6393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/qs_pivot.cpp", "max_stars_repo_name": "rabdumalikov/multipivot_quicksort", "max_stars_repo_head_hexsha": "9bf97fa7e3b8ef78c2a835bb9b58de28cfa82643", "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/qs_pivot.cpp", "max_issues_repo_name": "rabdumalikov/multipivot_quicksort", "max_issues_repo_head_hexsha": "9bf97fa7e3b8ef78c2a835bb9b58de28cfa82643", "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/qs_pivot.cpp", "max_forks_repo_name": "rabdumalikov/multipivot_quicksort", "max_forks_repo_head_hexsha": "9bf97fa7e3b8ef78c2a835bb9b58de28cfa82643", "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.093877551, "max_line_length": 152, "alphanum_fraction": 0.5441889567, "num_tokens": 1879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5437777008813574}}
{"text": "#include <iostream>\n#include <typeinfo>\r\n#define BOOST_TEST_MODULE DenseMIAAddSubtractTests\n\r\n\n\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\r\n#include \"DenseMIA.h\"\n#include \"Index.h\"\n\r\ntemplate<class _data_type>\r\nvoid do_work(size_t dim1,size_t dim2){\r\n\r\n    LibMIA::MIAINDEX i;\n    LibMIA::MIAINDEX j;\n    LibMIA::MIAINDEX k;\r\n    LibMIA::MIAINDEX l;\r\n//    LibMIA::MIAINDEX m;\r\n//    LibMIA::MIAINDEX n;\r\n//    LibMIA::MIAINDEX o;\r\n//    LibMIA::MIAINDEX p;\n\n    LibMIA::DenseMIA<_data_type,4> a(dim1,dim1,dim2,dim2);\r\n    LibMIA::DenseMIA<_data_type,4> b(dim2,dim1,dim2,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> c(dim2,dim1,dim2,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> c2(dim2,dim1,dim2,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> b2(dim1,dim1,dim2,dim2);\r\n\r\n\r\n    a.ones();\r\n    b.ones();\r\n    const LibMIA::DenseMIA<_data_type,4> temp_a(a);\r\n    //c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n\r\n    c(i,j,k,l)=b(i,j,k,l)+temp_a(j,l,i,k);\r\n    c2.fill(2);\r\n    BOOST_CHECK_MESSAGE(c==c2,std::string(\"Non-destructive Add 1 for \")+typeid(_data_type).name());\r\n\r\n\r\n    b(i,j,k,l)+=temp_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==c2,std::string(\"Destructive Add 1 for \")+typeid(_data_type).name());\r\n\r\n    b.fill(3);\r\n    const LibMIA::DenseMIA<_data_type,4> temp_b(b);\r\n    c(i,j,k,l)=temp_b(i,j,k,l)-a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==c2,std::string(\"Non-destructive Subtract 1 for \")+typeid(_data_type).name());\r\n\r\n\r\n    b(i,j,k,l)-=a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==c2,std::string(\"Destructive Subtract 1 for \")+typeid(_data_type).name());\r\n\r\n\r\n    a.zeros();\r\n    b.zeros();\r\n    a.at(dim1-1,dim1-1,dim2-1,dim2-1)=1;\r\n    b.at(dim2-1,dim1-1,dim2-1,dim1-1)=1;\r\n\r\n\r\n    c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n    c2.zeros();\r\n    c2.at(dim2-1,dim1-1,dim2-1,dim1-1)=2;\r\n    BOOST_CHECK_MESSAGE(c==c2,std::string(\"Non-destructive Add 2 for \")+typeid(_data_type).name());\r\n\r\n\r\n    b(i,j,k,l)+=a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==c2,std::string(\"Destructive Add 2 for \")+typeid(_data_type).name());\r\n\r\n    a.at(dim1-1,dim1-1,dim2-1,dim2-1)=3;\r\n    b.at(dim2-1,dim1-1,dim2-1,dim1-1)=5;\r\n    c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==c2,std::string(\"Non-destructive Subtract 2 for \")+typeid(_data_type).name());\r\n\r\n\r\n    b(i,j,k,l)-=a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==c2,std::string(\"Destructive Subtract 2 for \")+typeid(_data_type).name());\r\n\r\n    LibMIA::DenseMIA<_data_type,2> x(dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,2> y(dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,2> n(dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,2> n_final;\r\n    n.ones();\r\n    y.ones();\r\n    n.ones();\r\n    n_final=n;\r\n    n(i,j)=n(i,j)+y(i,j)-x(i,j)-(y(i,j)-x(j,i))+(y(j,i)-x(i,j))-(y(j,i)-x(j,i));\r\n\r\n\r\n    BOOST_CHECK_MESSAGE(n==n_final,std::string(\"Complicated expression 1 for \")+typeid(_data_type).name());\r\n\r\n\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( DenseMIAAddSubtractTests )\n{\n\n\r\n\r\n    do_work<double>(8,10);\n    do_work<float>(8,10);\r\n    do_work<int>(8,10);\n    do_work<long long int>(8,10);\r\n\r\n    do_work<double>(10,8);\n    do_work<float>(10,8);\r\n    do_work<int>(10,8);\n    do_work<long long int>(10,8);\r\n\r\n\r\n\n\n}\n", "meta": {"hexsha": "1a81c9d42727cb5753c7ef85086750046496840f", "size": 3233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/DenseMIA/dense_mia_add_subtract_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/DenseMIA/dense_mia_add_subtract_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/DenseMIA/dense_mia_add_subtract_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": 26.9416666667, "max_line_length": 108, "alphanum_fraction": 0.6201670275, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.5437777008813574}}
{"text": "/*!\n  \\file gpp_knowledge_gradient_inner_optimization.hpp\n  \\rst\n  1. OVERVIEW OF KNOWLEDGE GRADIENT WHAT ARE WE TRYING TO DO?\n  2. IMPLEMENTATION NOTES\n  3. CITATIONS\n\n    **1. OVERVIEW OF KNOWLEDGE GRADIENT; WHAT ARE WE TRYING TO DO?**\n\n    .. Note:: these comments are copied in Python: interfaces/__init__.py\n\n    The optimization process models the objective using a Gaussian process (GP) prior\n    (also called a GP predictor) based on the specified covariance and the input\n    data (e.g., through member functions ComputeMeanOfPoints, ComputeVarianceOfPoints).  Using the GP,\n    we can compute the knowledge gradient (KG) from sampling any particular point.  KG\n    is defined relative to the best currently known value, and it represents what the\n    algorithm believes is the most likely outcome from sampling a particular point in parameter\n    space (aka conducting a particular experiment).\n\n    See KnowledgeGradientEvaluator class docs for further details on computing KG.\n    Both support ComputeKnowledgeGradient() and ComputeGradKnowledgeGradient().\n\n    The behavior of the GP is controlled by its underlying\n    covariance function and the data/uncertainty of prior points (experiments).\n\n    With the ability of the compute KG, the final step is to optimize\n    to find the best KG.  This is done using multistart gradient descent (MGD), in\n    ComputeKGOptimalPointsToSample(). This method wraps a MGD call and falls back on random search\n    if that fails. See gpp_optimization.hpp for multistart/optimization templates. This method\n    can evaluate and optimize KG at serval points simultaneously; e.g., if we wanted to run 4 simultaneous\n    experiments, we can use KG to select all 4 points at once.\n\n    Additionally, there are use cases where we have existing experiments that are not yet complete but\n    we have an opportunity to start some new trials. For example, maybe we are a drug company currently\n    testing 2 combinations of dosage levels. We got some new funding, and can now afford to test\n    3 more sets of dosage parameters. Ideally, the decision on the new experiments should depend on\n    the existence of the 2 ongoing tests. We may not have any data from the ongoing experiments yet;\n    e.g., they are [double]-blind trials. If nothing else, we would not want to duplicate any\n    existing experiments! So we want to solve 3-KG using the knowledge of the 2 ongoing experiments.\n\n    We call this q,p-KG, so the previous example would be 3,2-KG. So q is the number of new\n    (simultaneous) experiments to select. In code, this would be the size of the output from KG\n    optimization (i.e., ``best_points_to_sample``, of which there are ``q = num_to_sample points``).\n    p is the number of ongoing/incomplete experiments to take into account (i.e., ``points_being_sampled``\n    of which there are ``p = num_being_sampled`` points).\n\n    Back to optimization: the idea behind gradient descent is simple.  The gradient gives us the\n    direction of steepest ascent (negative gradient is steepest descent).  So each iteration, we\n    compute the gradient and take a step in that direction.  The size of the step is not specified\n    by GD and is left to the specific implementation.  Basically if we take steps that are\n    too large, we run the risk of over-shooting the solution and even diverging.  If we\n    take steps that are too small, it may take an intractably long time to reach the solution.\n    Thus the magic is in choosing the step size; we do not claim that our implementation is\n    perfect, but it seems to work reasonably.  See ``gpp_optimization.hpp`` for more details about\n    GD as well as the template definition.\n\n    For particularly difficult problems or problems where gradient descent's parameters are not\n    well-chosen, GD can fail to converge.  If this happens, we can fall back on heuristics;\n    e.g., 'dumb' search (i.e., evaluate EI at a large number of random points and take the best\n    one). Naive search lives in: ComputeOptimalPointsToSampleViaLatinHypercubeSearch<>().\n\n    **2. IMPLEMENTATION NOTES**\n\n    a. This file has a few primary endpoints for KG optimization:\n\n       i. ComputeKGOptimalPointsToSampleWithRandomStarts<>():\n\n          Solves the q,p-KG problem.\n\n          Takes in a gaussian_process describing the prior, domain, config, etc.; outputs the next best point(s) (experiment)\n          to sample (run). Uses gradient descent.\n\n       ii. ComputeKGOptimalPointsToSampleViaLatinHypercubeSearch<>():\n\n           Estimates the q,p-KG problem.\n\n           Takes in a gaussian_process describing the prior, domain, etc.; outputs the next best point(s) (experiment)\n           to sample (run). Uses 'dumb' search.\n\n       iii. ComputeKGOptimalPointsToSample<>() (Recommended):\n\n            Solves the q,p-KG problem.\n\n            Wraps the previous two items; relies on gradient descent and falls back to \"dumb\" search if it fails.\n\n       .. NOTE::\n           See ``gpp_knowledge_gradient_optimization.cpp``'s header comments for more detailed implementation notes.\n\n           There are also several other functions with external linkage in this header; these\n           are provided primarily to ease testing and to permit lower level access from python.\n\n    b. See ``gpp_common.hpp`` header comments for additional implementation notes.\n\n    **3. CITATIONS**\n\n    a. Gaussian Processes for Machine Learning.\n       Carl Edward Rasmussen and Christopher K. I. Williams. 2006.\n       Massachusetts Institute of Technology.  55 Hayward St., Cambridge, MA 02142.\n       http://www.gaussianprocess.org/gpml/ (free electronic copy)\n\n    b. The Knowledge-Gradient Policy for Correlated Normal Beliefs.\n       P.I. Frazier, W.B. Powell & S. Dayanik.\n       INFORMS Journal on Computing, 2009.\n\n    c. Differentiation of the Cholesky Algorithm.\n       S. P. Smith. 1995.\n       Journal of Computational and Graphical Statistics. Volume 4. Number 2. p134-147\n\n    d. A Multi-points Criterion for Deterministic Parallel Global Optimization based on Gaussian Processes.\n       David Ginsbourger, Rodolphe Le Riche, and Laurent Carraro.  2008.\n       D\u00b4epartement 3MI. Ecole Nationale Sup\u00b4erieure des Mines. 158 cours Fauriel, Saint-Etienne, France.\n       ginsbourger@emse.fr, leriche@emse.fr, carraro@emse.fr\n\\endrst*/\n\n#ifndef MOE_OPTIMAL_LEARNING_CPP_GPP_KNOWLEDGE_GRADIENT_INNER_OPTIMIZATION_HPP_\n#define MOE_OPTIMAL_LEARNING_CPP_GPP_KNOWLEDGE_GRADIENT_INNER_OPTIMIZATION_HPP_\n\n#include <algorithm>\n#include <limits>\n#include <memory>\n#include <vector>\n\n#include <boost/math/distributions/normal.hpp>  // NOLINT(build/include_order)\n\n#include \"gpp_common.hpp\"\n#include \"gpp_domain.hpp\"\n#include \"gpp_exception.hpp\"\n#include \"gpp_covariance.hpp\"\n#include \"gpp_logging.hpp\"\n#include \"gpp_math.hpp\"\n#include \"gpp_optimization.hpp\"\n#include \"gpp_optimizer_parameters.hpp\"\n#include \"gpp_random.hpp\"\n\nnamespace optimal_learning {\n\nstruct FuturePosteriorMeanState;\n/*!\\rst\n  This is a specialization of the ExpectedImprovementEvaluator class for when the number of potential samples is 1; i.e.,\n  ``num_to_sample == 1`` and the number of concurrent samples is 0; i.e. ``num_being_sampled == 0``.\n  In other words, this class only supports the computation of 1,0-EI.  In this case, we have analytic formulas\n  for computing EI and its gradient.\n  Thus this class does not perform any explicit numerical integration, nor do its EI functions require access to a\n  random number generator.\n  This class's methods have some parameters that are unused or redundant.  This is so that the interface matches that of\n  the more general ExpectedImprovementEvaluator.\n  For other details, see ExpectedImprovementEvaluator for more complete description of what EI is and the outputs of\n  EI and grad EI computations.\n\\endrst*/\nclass FuturePosteriorMeanEvaluator final {\n public:\n  using StateType = FuturePosteriorMeanState;\n\n  /*!\\rst\n    Constructs a OnePotentialSampleExpectedImprovementEvaluator object.  All inputs are required; no default constructor nor copy/assignment are allowed.\n    \\param\n      :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n        that describes the underlying GP\n      :best_so_far: best (minimum) objective function value (in ``points_sampled_value``)\n  \\endrst*/\n  FuturePosteriorMeanEvaluator(const GaussianProcess& gaussian_process_in,\n                               double const * coefficient,\n                               double const * to_sample,\n                               const int num_to_sample,\n                               int const * to_sample_derivatives,\n                               int num_derivatives,\n                               double const * chol,\n                               double const * train_sample);\n\n  int dim() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return dim_;\n  }\n\n  const GaussianProcess * gaussian_process() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return gaussian_process_;\n  }\n\n  std::vector<double> to_sample_points(double const * to_sample,\n                                       int num_to_sample) noexcept OL_WARN_UNUSED_RESULT {\n    std::vector<double> result(num_to_sample*dim_);\n    std::copy(to_sample, to_sample + num_to_sample*dim_, result.data());\n    return result;\n  }\n\n  std::vector<int> derivatives(int const * to_sample_derivatives,\n                                  int num_derivatives) noexcept OL_WARN_UNUSED_RESULT {\n    std::vector<int> result(num_derivatives);\n    std::copy(to_sample_derivatives, to_sample_derivatives + num_derivatives, result.data());\n    return result;\n  }\n\n  std::vector<double> coeff(double const * coefficient, double const * chol,\n                            int num_to_sample, int num_derivatives) noexcept OL_WARN_UNUSED_RESULT {\n    std::vector<double> result(num_to_sample*(1+num_derivatives));\n    std::copy(coefficient, coefficient + num_to_sample*(1+num_derivatives), result.data());\n    TriangularMatrixVectorSolve(chol, 'T', num_to_sample_*(1+num_derivatives_),\n                                num_to_sample_*(1+num_derivatives_), result.data());\n    return result;\n  }\n\n  std::vector<double> coeff_combine(double const * coefficient, double const * train_sample,\n                                    int num_to_sample, int num_derivatives) noexcept OL_WARN_UNUSED_RESULT {\n    std::vector<double> temp(num_to_sample*(1+num_derivatives));\n    std::copy(coefficient, coefficient + num_to_sample*(1+num_derivatives), temp.data());\n\n    std::vector<double> result(gaussian_process_->get_K_inv_y());\n    int num_observations = gaussian_process_->num_sampled() * (1 + gaussian_process_->num_derivatives());\n    GeneralMatrixVectorMultiply(train_sample, 'N', temp.data(), -1.0, 1.0,\n                                num_observations, num_to_sample*(1+num_derivatives),\n                                num_observations, result.data());\n    return result;\n  }\n\n  /*!\\rst\n    Wrapper for ComputeExpectedImprovement(); see that function for details.\n  \\endrst*/\n  double ComputeObjectiveFunction(StateType * ps_state) const OL_NONNULL_POINTERS OL_WARN_UNUSED_RESULT {\n    return ComputePosteriorMean(ps_state);\n  }\n\n  /*!\\rst\n    Wrapper for ComputeGradExpectedImprovement(); see that function for details.\n  \\endrst*/\n  void ComputeGradObjectiveFunction(StateType * ps_state, double * restrict grad_PS) const OL_NONNULL_POINTERS {\n    ComputeGradPosteriorMean(ps_state, grad_PS);\n  }\n\n  /*!\\rst\n    Computes the expected improvement ``EI(Xs) = E_n[[f^*_n(X) - min(f(Xs_1),...,f(Xs_m))]^+]``\n    Uses analytic formulas to evaluate the expected improvement.\n    \\param\n      :ei_state[1]: properly configured state object\n    \\output\n      :ei_state[1]: state with temporary storage modified\n    \\return\n      the expected improvement from sampling ``point_to_sample``\n  \\endrst*/\n  double ComputePosteriorMean(StateType * ps_state) const;\n\n  /*!\\rst\n    Computes the (partial) derivatives of the expected improvement with respect to the point to sample.\n    Uses analytic formulas to evaluate the spatial gradient of the expected improvement.\n    \\param\n      :ei_state[1]: properly configured state object\n    \\output\n      :ei_state[1]: state with temporary storage modified\n      :grad_EI[dim]: gradient of EI, ``\\pderiv{EI(x)}{x_d}``, where ``x`` is ``points_to_sample``\n  \\endrst*/\n  void ComputeGradPosteriorMean(StateType * ps_state, double * restrict grad_PS) const;\n\n  OL_DISALLOW_DEFAULT_AND_COPY_AND_ASSIGN(FuturePosteriorMeanEvaluator);\n\n private:\n  //! spatial dimension (e.g., entries per point of ``points_sampled``)\n  const int dim_;\n\n  //! pointer to gaussian process used in computations\n  const GaussianProcess * gaussian_process_;\n\n  //! points to sample in the next sampling step\n  const std::vector<double> to_sample_;\n\n  //! number of points in the next sampling step\n  const int num_to_sample_;\n\n  //! the dims with derivatives\n  const std::vector<int> to_sample_derivatives_;\n\n  //! number of derivatives\n  const int num_derivatives_;\n\n  //! transpose(Chol)^-1 * (sampled Z)\n  const std::vector<double> coeff_;\n  const std::vector<double> coeff_combined_;\n};\n\n/*!\\rst\n  State object for OnePotentialSampleExpectedImprovementEvaluator.  This tracks the *ONE* ``point_to_sample``\n  being evaluated via expected improvement.\n  This is just a special case of ExpectedImprovementState; see those class docs for more details.\n  See general comments on State structs in ``gpp_common.hpp``'s header docs.\n\\endrst*/\nstruct FuturePosteriorMeanState final {\n  using EvaluatorType = FuturePosteriorMeanEvaluator;\n\n  /*!\\rst\n    Constructs an OnePotentialSampleExpectedImprovementState object for the purpose of computing EI\n    (and its gradient) over the specified point to sample.\n    This establishes properly sized/initialized temporaries for EI computation, including dependent state from the\n    associated Gaussian Process (which arrives as part of the ``ei_evaluator``).\n    .. WARNING::\n         This object is invalidated if the associated ei_evaluator is mutated.  SetupState() should be called to reset.\n    .. WARNING::\n         Using this object to compute gradients when ``configure_for_gradients`` := false results in UNDEFINED BEHAVIOR.\n    \\param\n      :ei_evaluator: expected improvement evaluator object that specifies the parameters & GP for EI evaluation\n      :point_to_sample[dim]: point at which to evaluate EI and/or its gradient to check their value in future experiments (i.e., test point for GP predictions)\n      :configure_for_gradients: true if this object will be used to compute gradients, false otherwise\n  \\endrst*/\n  FuturePosteriorMeanState(const EvaluatorType& ps_evaluator, const int num_fidelity_in, double const * restrict point_to_sample_in, bool configure_for_gradients);\n\n  FuturePosteriorMeanState(FuturePosteriorMeanState&& other);\n\n  int GetProblemSize() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return dim - num_fidelity;\n  }\n\n  std::vector<double> BuildUnionOfPoints(double const * restrict points_to_sample) noexcept OL_WARN_UNUSED_RESULT {\n    std::vector<double> union_of_points(dim);\n    std::copy(points_to_sample, points_to_sample + dim - num_fidelity, union_of_points.data());\n    std::fill(union_of_points.data() + dim - num_fidelity, union_of_points.data() + dim, 1.0);\n    return union_of_points;\n  }\n\n  /*!\\rst\n    Get ``point_to_sample``: the potential future sample whose EI (and/or gradients) is being evaluated\n    \\output\n      :point_to_sample[dim]: potential sample whose EI is being evaluted\n  \\endrst*/\n  void GetCurrentPoint(double * restrict point_to_sample_out) const noexcept OL_NONNULL_POINTERS {\n    std::copy(point_to_sample.data(), point_to_sample.data() + dim - num_fidelity, point_to_sample_out);\n  }\n\n  void Initialize(const EvaluatorType& ps_evaluator);\n\n  /*!\\rst\n    Change the potential sample whose EI (and/or gradient) is being evaluated.\n    Update the state's derived quantities to be consistent with the new point.\n    \\param\n      :ei_evaluator: expected improvement evaluator object that specifies the parameters & GP for EI evaluation\n      :point_to_sample[dim]: potential future sample whose EI (and/or gradients) is being evaluated\n  \\endrst*/\n  void SetCurrentPoint(const EvaluatorType& ps_evaluator,\n                       double const * restrict point_to_sample_in) OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Configures this state object with a new ``point_to_sample``, the location of the potential sample whose EI is to be evaluated.\n    Ensures all state variables & temporaries are properly sized.\n    Properly sets all dependent state variables (e.g., GaussianProcess's state) for EI evaluation.\n    .. WARNING::\n         This object's state is INVALIDATED if the ei_evaluator (including the GaussianProcess it depends on) used in\n         SetupState is mutated! SetupState() should be called again in such a situation.\n    \\param\n      :ei_evaluator: expected improvement evaluator object that specifies the parameters & GP for EI evaluation\n      :point_to_sample[dim]: potential future sample whose EI (and/or gradients) is being evaluated\n  \\endrst*/\n  void SetupState(const EvaluatorType& ps_evaluator,\n                  double const * restrict point_to_sample_in) OL_NONNULL_POINTERS;\n\n  // size information\n  //! spatial dimension (e.g., entries per point of ``points_sampled``)\n  const int dim;\n  //! dim of the fidelity\n  const int num_fidelity;\n  //! number of points to sample (i.e., the \"q\" in q,p-EI); MUST be 1\n  const int num_to_sample = 1;\n  //! number of derivative terms desired (usually 0 for no derivatives or num_to_sample)\n  const int num_derivatives;\n\n  //! point at which to evaluate EI and/or its gradient (e.g., to check its value in future experiments)\n  std::vector<double> point_to_sample;\n\n  std::vector<double> K_star;\n  std::vector<double> grad_K_star;\n\n  UniformRandomGenerator randomGenerator;\n  OL_DISALLOW_DEFAULT_AND_COPY_AND_ASSIGN(FuturePosteriorMeanState);\n};\n\n/*!\\rst\n  Set up vector of FuturePosteriorMeanState::StateType.\n\n  This is a utility function just for reducing code duplication.\n\n  \\param\n    :ei_evaluator: evaluator object associated w/the state objects being constructed\n    :points_to_sample[dim][num_to_sample]: initial points to load into state (must be a valid point for the problem);\n      i.e., points at which to evaluate EI and/or its gradient\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrently experiments\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :max_num_threads: maximum number of threads for use by OpenMP (generally should be <= # cores)\n    :configure_for_gradients: true if these state objects will be used to compute gradients, false otherwise\n    :state_vector[arbitrary]: vector of state objects, arbitrary size (usually 0)\n    :normal_rng[max_num_threads]: a vector of NormalRNG objects that provide the (pesudo)random source for MC integration\n  \\output\n    :state_vector[max_num_threads]: vector of states containing ``max_num_threads`` properly initialized state objects\n\\endrst*/\ninline OL_NONNULL_POINTERS void SetupFuturePosteriorMeanState(\n    const FuturePosteriorMeanEvaluator& fpm_evaluator,\n    double const * restrict points_to_sample,\n    int max_num_threads,\n    bool configure_for_gradients,\n    const int num_fidelity,\n    std::vector<typename FuturePosteriorMeanEvaluator::StateType> * state_vector) {\n  state_vector->reserve(max_num_threads);\n  for (int i = 0; i < max_num_threads; ++i) {\n    state_vector->emplace_back(fpm_evaluator, num_fidelity, points_to_sample, configure_for_gradients);\n  }\n}\n\n\n/*!\\rst\n  Perform multistart gradient descent (MGD) to solve the q,p-EI problem (see ComputeOptimalPointsToSample and/or\n  header docs), starting from ``num_multistarts`` points selected randomly from the within th domain.\n  This function is a simple wrapper around ComputeOptimalPointsToSampleViaMultistartGradientDescent(). It additionally\n  generates a set of random starting points and is just here for convenience when better initial guesses are not\n  available.\n  See ComputeOptimalPointsToSampleViaMultistartGradientDescent() for more details.\n  \\param\n    :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n      that describes the underlying GP\n    :optimizer_parameters: GradientDescentParameters object that describes the parameters controlling EI optimization\n      (e.g., number of iterations, tolerances, learning rate)\n    :domain: object specifying the domain to optimize over (see ``gpp_domain.hpp``)\n    :thread_schedule: struct instructing OpenMP on how to schedule threads; i.e., (suggestions in parens)\n      max_num_threads (num cpu cores), schedule type (omp_sched_dynamic), chunk_size (0).\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the \"p\" in q,p-EI)\n    :best_so_far: value of the best sample so far (must be ``min(points_sampled_value)``)\n    :max_int_steps: maximum number of MC iterations\n    :uniform_generator[1]: a UniformRandomGenerator object providing the random engine for uniform random numbers\n    :normal_rng[thread_schedule.max_num_threads]: a vector of NormalRNG objects that provide\n      the (pesudo)random source for MC integration\n  \\output\n    :found_flag[1]: true if best_next_point corresponds to a nonzero EI\n    :uniform_generator[1]: UniformRandomGenerator object will have its state changed due to random draws\n    :normal_rng[thread_schedule.max_num_threads]: NormalRNG objects will have their state changed due to random draws\n    :best_next_point[dim][num_to_sample]: points yielding the best EI according to MGD\n\\endrst*/\ntemplate <typename DomainType>\nvoid RestartedGradientDescentFuturePosteriorMeanOptimization(const GaussianProcess& gaussian_process, const int num_fidelity,\n                                                             double const * coefficient, double const * to_sample, const int num_to_sample,\n                                                             int const * to_sample_derivatives, int num_derivatives,\n                                                             double const * chol, double const * train_sample,\n                                                             const GradientDescentParameters& optimizer_parameters,\n                                                             const DomainType& domain, double const * restrict initial_guess,\n                                                             double& best_objective_value, double * restrict best_next_point) {\n  if (unlikely(optimizer_parameters.max_num_restarts <= 0)) {\n    return;\n  }\n  bool configure_for_gradients = true;\n  OL_VERBOSE_PRINTF(\"Posterior Mean Optimization via %s:\\n\", OL_CURRENT_FUNCTION_NAME);\n\n  // special analytic case when we are not using (or not accounting for) multiple, simultaneous experiments\n  FuturePosteriorMeanEvaluator ps_evaluator(gaussian_process, coefficient, to_sample,\n                                            num_to_sample, to_sample_derivatives,\n                                            num_derivatives, chol, train_sample);\n\n  typename FuturePosteriorMeanEvaluator::StateType ps_state(ps_evaluator, num_fidelity, initial_guess, configure_for_gradients);\n\n  GradientDescentOptimizer<FuturePosteriorMeanEvaluator, DomainType> gd_opt;\n  gd_opt.Optimize(ps_evaluator, optimizer_parameters, domain, &ps_state);\n  ps_state.GetCurrentPoint(best_next_point);\n  best_objective_value = ps_evaluator.ComputeObjectiveFunction(&ps_state);\n}\n\n/*!\\rst\n  Perform multistart gradient descent (MGD) to solve the q,p-EI problem (see ComputeOptimalPointsToSample and/or\n  header docs), starting from ``num_multistarts`` points selected randomly from the within th domain.\n  This function is a simple wrapper around ComputeOptimalPointsToSampleViaMultistartGradientDescent(). It additionally\n  generates a set of random starting points and is just here for convenience when better initial guesses are not\n  available.\n  See ComputeOptimalPointsToSampleViaMultistartGradientDescent() for more details.\n  \\param\n    :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n      that describes the underlying GP\n    :optimizer_parameters: GradientDescentParameters object that describes the parameters controlling EI optimization\n      (e.g., number of iterations, tolerances, learning rate)\n    :domain: object specifying the domain to optimize over (see ``gpp_domain.hpp``)\n    :thread_schedule: struct instructing OpenMP on how to schedule threads; i.e., (suggestions in parens)\n      max_num_threads (num cpu cores), schedule type (omp_sched_dynamic), chunk_size (0).\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the \"p\" in q,p-EI)\n    :best_so_far: value of the best sample so far (must be ``min(points_sampled_value)``)\n    :max_int_steps: maximum number of MC iterations\n    :uniform_generator[1]: a UniformRandomGenerator object providing the random engine for uniform random numbers\n    :normal_rng[thread_schedule.max_num_threads]: a vector of NormalRNG objects that provide\n      the (pesudo)random source for MC integration\n  \\output\n    :found_flag[1]: true if best_next_point corresponds to a nonzero EI\n    :uniform_generator[1]: UniformRandomGenerator object will have its state changed due to random draws\n    :normal_rng[thread_schedule.max_num_threads]: NormalRNG objects will have their state changed due to random draws\n    :best_next_point[dim][num_to_sample]: points yielding the best EI according to MGD\n\\endrst*/\ntemplate <typename DomainType>\nvoid ComputeOptimalFuturePosteriorMean(const GaussianProcess& gaussian_process, const int num_fidelity, double const * coefficient,\n                                       double const * to_sample, const int num_to_sample, int const * to_sample_derivatives,\n                                       int num_derivatives, double const * chol, double const * train_sample,\n                                       const GradientDescentParameters& optimizer_parameters, const DomainType& domain,\n                                       int max_num_threads, double const * restrict start_point_set,\n                                       int num_multistarts, double * restrict best_function_value, double * restrict best_next_point);\n\n// template explicit instantiation declarations, see gpp_common.hpp header comments, item 6\nextern template void ComputeOptimalFuturePosteriorMean(const GaussianProcess& gaussian_process, const int num_fidelity, double const * coefficient,\n                                                       double const * to_sample, const int num_to_sample, int const * to_sample_derivatives,\n                                                       int num_derivatives, double const * chol, double const * train_sample,\n                                                       const GradientDescentParameters& optimizer_parameters, const TensorProductDomain& domain,\n                                                       int max_num_threads, double const * restrict start_point_set,\n                                                       int num_multistarts, double * restrict best_function_value,\n                                                       double * restrict best_next_point);\nextern template void ComputeOptimalFuturePosteriorMean(const GaussianProcess& gaussian_process, const int num_fidelity, double const * coefficient,\n                                                       double const * to_sample, const int num_to_sample, int const * to_sample_derivatives,\n                                                       int num_derivatives, double const * chol, double const * train_sample,\n                                                       const GradientDescentParameters& optimizer_parameters, const SimplexIntersectTensorProductDomain& domain,\n                                                       int max_num_threads, double const * restrict start_point_set,\n                                                       int num_multistarts, double * restrict best_function_value,\n                                                       double * restrict best_next_point);\n}  // end namespace optimal_learning\n#endif  // MOE_OPTIMAL_LEARNING_CPP_GPP_KNOWLEDGE_GRADIENT_INNER_OPTIMIZATION_HPP_", "meta": {"hexsha": "72c840d3a8890e0bf5fedf52cb8a88f3ff51e7ac", "size": 29102, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "moe/optimal_learning/cpp/gpp_knowledge_gradient_inner_optimization.hpp", "max_stars_repo_name": "AliBaheri/Cornell-MOE", "max_stars_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "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": "moe/optimal_learning/cpp/gpp_knowledge_gradient_inner_optimization.hpp", "max_issues_repo_name": "AliBaheri/Cornell-MOE", "max_issues_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "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": "moe/optimal_learning/cpp/gpp_knowledge_gradient_inner_optimization.hpp", "max_forks_repo_name": "AliBaheri/Cornell-MOE", "max_forks_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T14:48:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-02T14:48:26.000Z", "avg_line_length": 56.83984375, "max_line_length": 163, "alphanum_fraction": 0.7212906329, "num_tokens": 6303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5437776992202077}}
{"text": "#pragma once\n\n#include <vector>\n\n#include \"nifty/math/math.hxx\"\n#include \"nifty/histogram/histogram.hxx\"\n#include \"nifty/cgp/geometry.hxx\"\n#include \"nifty/cgp/bounds.hxx\"\n#include \"nifty/marray/marray.hxx\"\n#include \"nifty/filters/gaussian_curvature.hxx\"\n#include \"nifty/features/accumulated_features.hxx\"\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n\nnamespace nifty{\nnamespace cgp{\n\n    class Cell1CurvatureFeatures2D{\n    private:\n        typedef nifty::features::DefaultAccumulatedStatistics<float> AccType;\n    public:\n        Cell1CurvatureFeatures2D(\n            const std::vector<float> & sigmas  = std::vector<float>({1.0f, 2.0f, 4.0f})\n        )\n        :   sigmas_(sigmas)\n        {\n\n        }\n\n        size_t numberOfFeatures()const{\n            return sigmas_.size() * AccType::NFeatures::value;   \n        }\n        \n\n        std::vector<std::string> names()const{\n\n            std::string accNames [] = {\n                std::string(\"Mean\"),\n                std::string(\"Sum\"),\n                std::string(\"Min\"),\n                std::string(\"Max\"),\n                std::string(\"Moment2\"),\n                std::string(\"Moment3\"),\n                std::string(\"Q0.10\"),\n                std::string(\"Q0.25\"),\n                std::string(\"Q0.50\"),\n                std::string(\"Q0.75\"),\n                std::string(\"Q0.90\")\n            };\n            std::vector<std::string> res;\n            auto baseName = std::string(\"GaussianCurvatureSigma\");\n            for(auto sigmaIndex=0; sigmaIndex<sigmas_.size(); ++sigmaIndex){\n                auto name  = baseName + std::to_string(sigmas_[sigmaIndex]);\n                for(const auto & accName : accNames){    \n                    res.push_back(name + accName);\n                }\n                \n            }\n            return res;\n        }\n\n        template<class T>\n        void operator()(\n            const CellGeometryVector<2,1>  & cell1GeometryVector,\n            const CellBoundedByVector<2,1> & cell1BoundedByVector,\n            nifty::marray::View<T> & features\n        )const{  \n\n            std::vector<float> curvature;\n            std::vector<float> buffer(AccType::NFeatures::value);\n            \n\n            \n            for(auto sigmaIndex=0; sigmaIndex<sigmas_.size(); ++sigmaIndex){\n                const auto sigma = sigmas_[sigmaIndex];\n                nifty::filters::GaussianCurvature2D<> op(sigma, -1, 2.5);\n\n\n                for(auto cell1Index=0; cell1Index<cell1GeometryVector.size(); ++cell1Index){\n                    const auto & geo = cell1GeometryVector[cell1Index];\n\n                    \n\n                    if(geo.size()>=4){\n\n               \n                        // we use a larger size?\n                        if(curvature.capacity() < geo.size()){\n                            curvature.resize(geo.size()*2);\n                        }\n                        else{\n                            curvature.resize(geo.size());\n                        }\n\n                        // calculate curvature\n                        //std::cout<<\"    is closed \"<<\"\\n\";\n                        const auto closedLine = cell1BoundedByVector[cell1Index].size() == 0;\n                        //std::cout<<\"    calculate curvature \"<<\"\\n\";\n                        op(geo.begin(), geo.end(), curvature.begin(), closedLine);\n\n                        // accumulate the values\n                        AccType acc;\n                        for(auto pass=0; pass < acc.requiredPasses(); ++pass){\n                            for(const auto & c : curvature){\n                                acc.acc(c, pass);\n                            }\n                        }\n                        // write to buffer\n                        acc.result(buffer.begin(), buffer.end());   \n                        \n                        // write to features out\n                        const auto fIndex = sigmaIndex*AccType::NFeatures::value;\n                        for(auto afi=0; afi<AccType::NFeatures::value; ++afi){\n                            features(cell1Index, fIndex + afi) = buffer[afi];\n                        }\n\n                        \n                    }\n                    else{\n                        // write to features out\n                        // a zero value seems legit since we\n                        // assume a constant zero curvature\n                        const auto fIndex = sigmaIndex*AccType::NFeatures::value;\n                        for(auto afi=0; afi<AccType::NFeatures::value; ++afi){\n                            features(cell1Index, fIndex + afi) = 0.0;\n                        }\n\n                    }\n                }\n            }\n        }   \n    private:\n        std::vector<float> sigmas_;\n    };\n\n\n\n\n    class Cell1LineSegmentDist2D{\n    private:\n        typedef nifty::features::DefaultAccumulatedStatistics<float> AccType;\n    public:\n        Cell1LineSegmentDist2D(\n            const std::vector<size_t> & dists  = std::vector<size_t>({size_t(3),size_t(5),size_t(7)})\n        )\n        :   dists_(dists)\n        {\n        }\n\n        size_t numberOfFeatures()const{\n            return  dists_.size()*AccType::NFeatures::value;\n        }\n\n       std::vector<std::string> names()const{\n\n            std::string accNames [] = {\n                std::string(\"Mean\"),\n                std::string(\"Sum\"),\n                std::string(\"Min\"),\n                std::string(\"Max\"),\n                std::string(\"Moment2\"),\n                std::string(\"Moment3\"),\n                std::string(\"Q0.10\"),\n                std::string(\"Q0.25\"),\n                std::string(\"Q0.50\"),\n                std::string(\"Q0.75\"),\n                std::string(\"Q0.90\")\n            };\n            std::vector<std::string> res;\n            auto baseName = std::string(\"Cell1LineSegmentDistD\");\n            for(auto i=0; i<dists_.size(); ++i){\n                auto name  = baseName + std::to_string(dists_[i]);\n                for(const auto & accName : accNames){\n                    res.push_back(name + accName);\n                }\n                \n            }\n            return res;\n        }\n\n\n\n        template<class T>\n        void operator()(\n            const CellGeometryVector<2,1>  & cell1GeometryVector,\n            nifty::marray::View<T> & features\n        )const{  \n\n            std::vector<float> buffer(AccType::NFeatures::value);\n\n            typedef boost::geometry::model::d2::point_xy<double> point_type;\n            typedef boost::geometry::model::linestring<point_type> linestring_type;\n\n\n            for(auto di=0; di<dists_.size(); ++di){\n                const auto ld = dists_[di];\n                for(auto cell1Index=0; cell1Index<cell1GeometryVector.size(); ++cell1Index){\n                    const auto & geo = cell1GeometryVector[cell1Index];\n                    if(geo.size()>=4){\n\n                        AccType acc;\n\n                        for(auto pass=0; pass < acc.requiredPasses(); ++pass){\n\n                            for(auto i=0; i<geo.size()-1; ++i){\n                                const auto j = std::min(int(i + ld), int(geo.size()-1));\n                                const auto & pS = geo[i];\n                                const auto & pE = geo[j];   \n\n                                linestring_type line;\n                                line.push_back(point_type(pS[0], pS[1]));\n                                line.push_back(point_type(pE[0], pE[1]));\n                                \n                                for(auto ii=i+1; ii<j-1; ++ii){\n                                    const point_type p(geo[ii][0], geo[ii][1]);\n                                    const auto d = boost::geometry::distance(p, line);\n                                    acc.acc(d, pass);\n                                }\n                            }\n                        }\n                        // write to buffer\n                        acc.result(buffer.begin(), buffer.end());\n\n                        // write to features out\n                        const auto fIndex = di*AccType::NFeatures::value;\n                        for(auto afi=0; afi<AccType::NFeatures::value; ++afi){\n                            features(cell1Index, fIndex + afi) = buffer[afi];\n                        }\n\n                        \n                    }\n                    else{\n                        // write to features out\n                        // a zero value seems legit since we\n                        // assume a constant zero curvature\n                        const auto fIndex = di*AccType::NFeatures::value;\n                        for(auto afi=0; afi<AccType::NFeatures::value; ++afi){\n                            features(cell1Index, fIndex + afi) = 0.0;\n                        }\n                    }\n                }\n            }\n        }\n    private:\n        std::vector<size_t> dists_;\n    };\n\n\n    class Cell1BasicGeometricFeatures2D{\n    private:\n        typedef nifty::features::DefaultAccumulatedStatistics<float> AccType;\n    public:\n        Cell1BasicGeometricFeatures2D(){\n        }\n\n        size_t numberOfFeatures()const{\n            return 4 * 4 +  2*AccType::NFeatures::value + 4;   \n        }\n\n\n\n        std::vector<std::string> names()const{\n\n            std::string accNames [] = {\n                std::string(\"Mean\"),\n                std::string(\"Sum\"),\n                std::string(\"Min\"),\n                std::string(\"Max\"),\n                std::string(\"Moment2\"),\n                std::string(\"Moment3\"),\n                std::string(\"Q0.10\"),\n                std::string(\"Q0.25\"),\n                std::string(\"Q0.50\"),\n                std::string(\"Q0.75\"),\n                std::string(\"Q0.90\")\n            };\n\n            std::vector<std::string> res;\n            const auto baseName = std::string(\"BasicGeometricFeatures\");\n            auto insertUVFeat = [&](const std::string & name){\n                res.push_back(baseName+name+std::string(\"UV-Min\"));\n                res.push_back(baseName+name+std::string(\"UV-Max\"));\n                res.push_back(baseName+name+std::string(\"UV-Sum\"));\n                res.push_back(baseName+name+std::string(\"UV-AbsDiff\"));\n            };\n            auto insertStatFeat = [&](const std::string & name){\n                for(const auto & an : accNames){\n                    res.push_back(baseName+name+an);\n                }\n            };\n\n            res.push_back(baseName+std::string(\"EdgeSize\"));\n            insertUVFeat(\"NodeSize\");\n            insertUVFeat(\"NodeEdgeSizeRatio\");\n\n            res.push_back(baseName+std::string(\"EdgeEndpointDistance\"));\n            res.push_back(baseName+std::string(\"EdgeRelativeEndpointDistance\"));\n            res.push_back(baseName+std::string(\"NodeEndpointDistance\"));\n\n            \n            insertUVFeat(\"EdgeNodeCenterOfMassDist\");\n            insertUVFeat(\"EdgeNodeCenterOfMassRatio\");  \n\n            insertStatFeat(\"CenterOfMassCell1PointsDist\");\n            insertStatFeat(\"CenterOfMassCell2PointsDist\");\n\n            return res;\n        }\n\n        template<class T>\n        void operator()(\n            const CellGeometryVector<2,1>   & cell1GeometryVector,\n            const CellGeometryVector<2,2>   & cell2GeometryVector,\n            const CellBoundsVector<2,1>     & cell1BoundsVector,\n            nifty::marray::View<T> & features\n        )const{  \n\n            using namespace nifty::math;\n            std::vector<float> buffer(AccType::NFeatures::value);\n            for(auto cell1Index=0; cell1Index<cell1GeometryVector.size(); ++cell1Index){\n\n                const auto & cell1Bounds = cell1BoundsVector[cell1Index];\n                const auto cell2UIndex = cell1Bounds[0]-1;\n                const auto cell2VIndex = cell1Bounds[1]-1;\n\n\n                auto fIndex = 0;\n\n                auto insertCell2ValFeats = [&](const float uVal, const float vVal){\n                    features(cell1Index, fIndex++) = std::min(uVal, vVal);\n                    features(cell1Index, fIndex++) = std::max(uVal, vVal);\n                    features(cell1Index, fIndex++) = uVal + vVal;\n                    features(cell1Index, fIndex++) = std::abs(uVal-vVal);\n                };\n\n                const auto & geoE = cell1GeometryVector[cell1Index];\n                const auto & geoU = cell2GeometryVector[cell2UIndex];\n                const auto & geoV = cell2GeometryVector[cell2VIndex];\n\n                // size based features\n                const auto eSize = float(geoE.size());\n                const auto uSize = float(geoU.size());\n                const auto vSize = float(geoV.size());\n                   \n\n                features(cell1Index, fIndex++) = eSize; \n                insertCell2ValFeats(uSize, vSize);\n\n                // size ratios\n                const auto uNSize = std::sqrt(uSize);\n                const auto vNSize = std::sqrt(vSize);  \n                {\n                    const auto ratU =  uNSize/eSize;\n                    const auto ratV =  vNSize/eSize;  \n                    insertCell2ValFeats(ratU, ratV);\n                }\n\n\n                // endpoint distance and ratios\n                const auto endpointDistance = euclideanDistance(geoE.front(), geoE.back());\n                features(cell1Index, fIndex++) = endpointDistance;\n                features(cell1Index, fIndex++) = endpointDistance/eSize;\n\n                // distance between cell2CenterOfMass  and cell1CenterOfMass\n                const auto  comE = geoE.centerOfMass();\n                const auto  comU = geoU.centerOfMass();\n                const auto  comV = geoV.centerOfMass();\n                {\n                    const auto dUV  = euclideanDistance(comU, comV);\n                    const auto dUE  = euclideanDistance(comU, comE);\n                    const auto dVE  = euclideanDistance(comV, comE);\n\n                    features(cell1Index, fIndex++) = dUV;\n                    insertCell2ValFeats(dUE, dVE);\n                \n\n                    // distance ratios between cell2CenterOfMass  and cell1CenterOfMass\n                \n                    const auto ratU =  uNSize/dUE;\n                    const auto ratV =  vNSize/dVE;  \n                    insertCell2ValFeats(ratU, ratV);\n                }\n\n                // statistic  over ||centerOfMass-points||  for cell 1\n                {\n                    AccType acc;\n                    for(auto i=0; i<geoE.size(); ++i){\n                        const auto & coord = geoE[i];\n                        const auto d  = nifty::math::euclideanDistance(coord, comE);\n                        acc.acc(d);\n                    }\n                    // write to buffer\n                    acc.result(buffer.begin(), buffer.end()); \n                    // write results\n                    for(auto i=0; i<buffer.size(); ++i){\n                        features(cell1Index,  fIndex++) = buffer[i];\n                    }\n                }\n\n\n\n\n\n                // statistic  over ||centerOfMass_cell1-points_cell2|| \n                {\n                    AccType acc;\n\n\n                    for(auto i=0; i<geoU.size(); ++i){\n                        const auto & coord = geoU[i];\n                        const auto d  = nifty::math::euclideanDistance(coord, comE);\n                        acc.acc(d);\n                    }\n                    for(auto i=0; i<geoV.size(); ++i){\n                        const auto & coord = geoV[i];\n                        const auto d  = nifty::math::euclideanDistance(coord, comE);\n                        acc.acc(d);\n                    }\n\n                    // write to buffer and write results\n                    acc.result(buffer.begin(), buffer.end()); \n\n                    for(auto i=0; i<buffer.size(); ++i){\n                        features(cell1Index,  fIndex++) = buffer[i];\n                    }\n\n                }\n\n\n                // angle between cell2CenterOfMass  and cell1CenterOfMass\n                // ...\n\n\n\n                NIFTY_CHECK_OP(fIndex,==,numberOfFeatures(),\"internal error\");\n\n\n            }\n        \n        }\n    private:\n        std::vector<size_t> dists_;\n    };\n\n\n    /**\n    class GeometricAccumulator{\n    private:\n        typedef nifty::features::DefaultAccumulatedStatistics<float> AccType;\n    public:\n        GeometricAccumulator(\n            const std::vector<size_t> & dists  = std::vector<size_t>({size_t(3),size_t(5),size_t(7)})\n        )\n        :   dists_(dists)\n        {\n        }\n\n        size_t numberOfFeatures()const{\n            return  dists_.size()*AccType::NFeatures::value;\n        }\n            \n\n        template<class T>\n        void operator()(\n            const CellGeometryVector<2,1>  & cell1GeometryVector,\n            nifty::marray::View<T> & features\n        )const{  \n\n            std::vector<float> buffer(AccType::NFeatures::value);\n\n            typedef boost::geometry::model::d2::point_xy<double> point_type;\n            typedef boost::geometry::model::linestring<point_type> linestring_type;\n\n\n                \n            for(auto cell1Index=0; cell1Index<cell1GeometryVector.size(); ++cell1Index){\n\n                const auto & geo = cell1GeometryVector[cell1Index];\n                \n            }\n        \n        }\n    private:\n        std::vector<size_t> dists_;\n    };\n    */\n\n\n\n}\n}", "meta": {"hexsha": "a8c70d812d95910b2a780ac46a0744f9019334c0", "size": 17300, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/nifty/cgp/features/geometric_features.hxx", "max_stars_repo_name": "k-dominik/nifty", "max_stars_repo_head_hexsha": "067e137e9c1f33cccb22052b53ff0d75c288d667", "max_stars_repo_licenses": ["MIT"], "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/nifty/cgp/features/geometric_features.hxx", "max_issues_repo_name": "k-dominik/nifty", "max_issues_repo_head_hexsha": "067e137e9c1f33cccb22052b53ff0d75c288d667", "max_issues_repo_licenses": ["MIT"], "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/nifty/cgp/features/geometric_features.hxx", "max_forks_repo_name": "k-dominik/nifty", "max_forks_repo_head_hexsha": "067e137e9c1f33cccb22052b53ff0d75c288d667", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-07T09:29:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-07T09:29:26.000Z", "avg_line_length": 35.020242915, "max_line_length": 101, "alphanum_fraction": 0.4660115607, "num_tokens": 3706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5437618316386885}}
{"text": "// Copyright (c) 2018-2021 FRC Team 3512. All Rights Reserved.\n\n#pragma once\n\n#include <Eigen/Core>\n#include <frc/controller/LinearQuadraticRegulator.h>\n#include <frc/estimator/KalmanFilter.h>\n#include <frc/logging/CSVLogFile.h>\n#include <frc/system/LinearSystem.h>\n#include <frc/system/LinearSystemLoop.h>\n#include <frc/system/plant/DCMotor.h>\n#include <frc/system/plant/LinearSystemId.h>\n#include <frc/trajectory/TrapezoidProfile.h>\n#include <units/length.h>\n#include <units/velocity.h>\n\n#include \"Constants.hpp\"\n\nnamespace frc3512 {\n\nclass ClimberController {\npublic:\n    // State tolerances in meters and meters/sec respectively.\n    static constexpr double kPositionTolerance = 0.05;\n    static constexpr double kVelocityTolerance = 2.0;\n\n    ClimberController();\n\n    ClimberController(const ClimberController&) = delete;\n    ClimberController& operator=(const ClimberController&) = delete;\n\n    /**\n     * Enables the control loop.\n     */\n    void Enable();\n\n    /**\n     * Disables the control loop.\n     */\n    void Disable();\n\n    /**\n     * Sets the end goal of the controller profile.\n     *\n     * @param goal Position in meters to set the goal to.\n     */\n    void SetGoal(double goal);\n\n    /**\n     * Sets the references.\n     *\n     * @param position Position of the carriage in meters.\n     * @param velocity Velocity of the carriage in meters per second.\n     */\n    void SetReferences(units::meter_t position,\n                       units::meters_per_second_t velocity);\n\n    /**\n     * Returns whether or not the goal has been reached.\n     */\n    bool AtGoal() const;\n\n    /**\n     * Returns whether or not position and velocity are tracking the profile.\n     */\n    bool AtReferences() const;\n\n    /**\n     * Sets the current encoder measurement.\n     *\n     * @param measuredPosition Position of the carriage in meters.\n     */\n    void SetMeasuredPosition(double measuredPosition);\n\n    /**\n     * Returns the control loop calculated voltage.\n     */\n    double ControllerVoltage();\n\n    /**\n     * Returns the estimated position.\n     */\n    double EstimatedPosition() const;\n\n    /**\n     * Returns the estimated velocity.\n     */\n    double EstimatedVelocity() const;\n\n    /**\n     * Returns the error between the position reference and the position\n     * estimate.\n     */\n    double PositionError() const;\n\n    /**\n     * Returns the error between the velocity reference and the velocity\n     * estimate.\n     */\n    double VelocityError() const;\n\n    /**\n     * Returns the current position reference set by the profile.\n     */\n    double PositionReference();\n\n    /**\n     * Returns the current velocity reference set by the profile.\n     */\n    double VelocityReference();\n\n    /**\n     * Executes the control loop for a cycle.\n     */\n    void Update();\n\n    /**\n     * Resets any internal state.\n     */\n    void Reset();\n\nprivate:\n    // The current sensor measurement.\n    Eigen::Matrix<double, 1, 1> m_y;\n    frc::TrapezoidProfile<units::meters>::State m_goal;\n\n    frc::TrapezoidProfile<units::meters>::Constraints constraints{\n        Constants::Climber::kMaxV, Constants::Climber::kMaxA};\n    frc::TrapezoidProfile<units::meters> m_positionProfile{constraints,\n                                                           {0_m, 0_mps}};\n\n    // The current references from the profile.\n    frc::TrapezoidProfile<units::meters>::State m_profiledReference;\n\n    frc::LinearSystem<2, 1, 1> m_plant = [=] {\n        constexpr auto motor = frc::DCMotor::Vex775Pro();\n\n        // Robot mass\n        constexpr auto m = 63.503_kg;\n\n        // Radius of axle\n        constexpr auto r = 0.003175_m;\n\n        // Gear ratio\n        constexpr double G = 50.0 / 1.0;\n\n        return frc::LinearSystemId::ElevatorSystem(motor, m, r, G);\n    }();\n    frc::LinearQuadraticRegulator<2, 1> m_controller{\n        m_plant, {0.02, 0.4}, {12.0}, Constants::kDt};\n    frc::KalmanFilter<2, 1, 1> m_observer{\n        m_plant, {0.05, 1.0}, {0.0001}, Constants::kDt};\n    frc::LinearSystemLoop<2, 1, 1> m_loop{m_plant, m_controller, m_observer,\n                                          12_V, Constants::kDt};\n\n    bool m_isEnabled = false;\n\n    bool m_atReferences = false;\n\n    frc::CSVLogFile climberLogger{\"Climber\",      \"EstPos (m)\",\n                                  \"PosRef (m)\",   \"Voltage (V)\",\n                                  \"EstVel (m/s)\", \"VelRef (m/s)\"};\n};\n}  // namespace frc3512\n", "meta": {"hexsha": "122621c3541021e60f491c779f38c0f6bb5440e4", "size": 4412, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/main/include/controllers/ClimberController.hpp", "max_stars_repo_name": "frc3512/Robot-2019", "max_stars_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-05T01:06:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T15:18:49.000Z", "max_issues_repo_path": "src/main/include/controllers/ClimberController.hpp", "max_issues_repo_name": "frc3512/Robot-2019", "max_issues_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/include/controllers/ClimberController.hpp", "max_forks_repo_name": "frc3512/Robot-2019", "max_forks_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-14T16:21:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-14T16:21:42.000Z", "avg_line_length": 26.7393939394, "max_line_length": 77, "alphanum_fraction": 0.6185403445, "num_tokens": 1089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5437618260011313}}
{"text": "#include <MetaScale.h>\n#include <boost/math/common_factor_rt.hpp>\n\nvoid MetaScale::normalize() {\n  uint32_t a = mNum<0?-mNum:mNum;\n  uint32_t gcd = boost::math::gcd(a,mDenom);\n  mNum   /= gcd;\n  mDenom /= gcd;\n}\n\nMetaScale& MetaScale::operator*=(const MetaScale& b) {\n  mNum*=b.num();\n  mDenom*=b.denom();\n  normalize();\n  return *this;\n}\n\nMetaScale& MetaScale::operator/=(const MetaScale& b) {\n  uint32_t temp = mNum*b.denom();\n  mDenom*=b.num();\n  mNum = temp;\n  normalize();\n  return *this;\n}\nMetaScale MetaScale::operator*(const MetaScale& b) const {\n  return MetaScale(*this) *= b;\n}\n\nMetaScale MetaScale::operator/(const MetaScale& b) const {\n  return MetaScale(*this) /= b;\n}\n", "meta": {"hexsha": "fc00dcb79e30350956abe0f01b5bcd49c0457ab5", "size": 683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MetaScale.cpp", "max_stars_repo_name": "steup/ASEIA", "max_stars_repo_head_hexsha": "498538fbefa95bac7723ad20582ff9d3dace3674", "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/MetaScale.cpp", "max_issues_repo_name": "steup/ASEIA", "max_issues_repo_head_hexsha": "498538fbefa95bac7723ad20582ff9d3dace3674", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-29T01:07:55.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-29T01:07:55.000Z", "max_forks_repo_path": "src/MetaScale.cpp", "max_forks_repo_name": "steup/ASEIA", "max_forks_repo_head_hexsha": "498538fbefa95bac7723ad20582ff9d3dace3674", "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.34375, "max_line_length": 58, "alphanum_fraction": 0.6647144949, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5437421150629158}}
{"text": "#include <gtest/gtest.h> \n#include \"../include/mathWrapper/double.h\"\n#include \"../include/mathWrapper/boost.h\"\n#include \"../include/Eigen.h\"\n#include \"../include/mathWrapper/eigen.h\"\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include <iostream>\n\nTEST(discreteDiscreteKalmanFilter, test){\n\tint totalCount = 10000;\n\t\n\tvectorDouble * vdR_arr = new vectorDouble[totalCount];\n\tEigen::VectorXd * vesR_arr = new Eigen::VectorXd[totalCount];\n\tvectorBoost * vbR_arr = new vectorBoost[totalCount];\n\tvectorEigen * veR_arr = new vectorEigen[totalCount];\n\n\t//covariance: [1.00000,0.20000;0.20000,2.00000]\n\t//chol(covariance): [1.0000,0.2000;0.0000,1.4000] \n\n\tEigen::MatrixXd cholCov(2,2);cholCov<<1.0,0.2,0.0,1.4;Eigen::VectorXd mean1(2);mean1<<2.0,1.3;\n\tboost::numeric::ublas::matrix<double> cholCov2(2,2);boost::numeric::ublas::vector<double> mean2(2);\n\tmean2(0) = 2.0; mean2(1) = 1.3;\n\tcholCov2(0,0)=1;cholCov2(0,1)=0.2;cholCov2(1,0)=0.0;cholCov2(1,1)=1.4;\n\tmatrixEigen cholCov3(cholCov);vectorEigen mean3(mean1);\n\tfor(int i = 0; i < totalCount; i++){\n\t\tvectorDouble vdR = vectorDouble::randomVector(1,i*i);\n\t\tvdR_arr[i] = vdR*matrixDouble(0.1) + vectorDouble(5.0);\n\n\t\tEigen::VectorXd vesR = Eigen::VectorXd::randomVector(2,i*i); \n\t\tvesR_arr[i] = cholCov*vesR + mean1;\n\n\t\tvectorBoost vbR = vectorBoost::randomVector(2,i*i);\n\t\tvbR_arr[i] = matrixBoost(cholCov2)*vbR + mean2;\n\t\n\t\tvectorEigen veR = vectorEigen::randomVector(2,i*i);\n\t\tveR_arr[i] = cholCov3*veR + mean3;\n\t}\n\t\n\tvectorDouble vdSum(0);\n\tEigen::VectorXd evsSum(2);evsSum<<0.0,0.0;\n\tboost::numeric::ublas::vector<double> zero(2);zero(0)=0;zero(1)=0;\n\tvectorBoost vbSum(zero);\n\tvectorEigen evSum(evsSum);\n\tfor(int i = 0; i < totalCount; i++){\n\t\tvdSum = vdSum + vdR_arr[i];\t\n\t\tevsSum = evsSum + vesR_arr[i];\n\t\tvbSum = vbSum + vbR_arr[i];\n\t\tevSum = evSum + veR_arr[i];\n\t}\n\tdouble vdSumMean = vdSum.getSystemValue()/double(totalCount);\n\tASSERT_NEAR((vdSumMean)/5.0,1.0,0.001);\n\t\n\tdouble vdCovariance = 0;\n\n\tfor(int i = 0; i < totalCount; i++){\n\t\tvdCovariance+=(vdR_arr[i].getSystemValue()-vdSumMean)*(vdR_arr[i].getSystemValue() - vdSumMean);\n\t}\n\tvdCovariance = vdCovariance/totalCount;\n\tASSERT_NEAR(vdCovariance/0.01,1,0.01);\n}\n\nint main(int argc, char **argv){\n\ttesting::InitGoogleTest(&argc, argv);\n\treturn RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "d70b0bc01cbc80fa70fdcade780c0825a89c508b", "size": 2316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++_implementation/tests/tests4.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/tests4.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/tests4.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": 34.0588235294, "max_line_length": 100, "alphanum_fraction": 0.7016407599, "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5437421122075021}}
{"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 *      121128    R.C.A. Boon       File created (in progress).\n *      130124    R.C.A. Boon       Removed retrograde function, reworked Kepler to MEE conversion\n *                                  to properly convert inclination to range [0,180) and use\n *                                  retrograde factor internally\n *      130131    R.C.A. Boon       Added Cartesian conversion cases, added avoidSingularityAtPi~\n *                                  boolean flag to Kepler conversions, optimized computation\n *                                  (partially)\n *      130225    D. Dirkx          Added overloaded function for Kepler to MEE that determines\n *                                  retrogradeness based on Kepler state\n *      130301    R.C.A. Boon       Updated use of mathematics::PI to basic_mathematics::\n *                                  mathematical_constants::PI, minor textual changes.\n *      130305    R.C.A. Boon       Replaced Eigen::VectorXd by basic_mathematics::Vector6d\n *\n *    References\n *      Verified Interval Propagation, Bart R\u02c6mgens; Delft (2011). Code archive.\n *      Modified Equinoctial Orbital Elements, author unknown;\n *          http://www.cdeagle.com/pdf/mee.pdf (2010?).\n *      Survey of Orbital Element Sets, Gerald R. Hintz; Journal of Guidance, Control and\n *          Dynamics (2008, Vol. 31 - Nr. 3).\n *      Code archive, E. Heeren (fellow Tudat developer).\n *\n *    Notes\n *\n */\n\n#include <cmath>\n\n#include <boost/exception/all.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h\"\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/missionGeometry.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/modifiedEquinoctialElementConversions.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\n\nnamespace tudat\n{\n\nnamespace orbital_element_conversions\n{\n\n//! Convert Keplerian to modified equinoctial orbital elements using implicit MEE equation set.\nbasic_mathematics::Vector6d convertKeplerianToModifiedEquinoctialElements(\n        const basic_mathematics::Vector6d& keplerianElements )\n// Based on Hintz, 2008.\n{\n    // Check if orbit is retrograde\n    bool avoidSingularityAtPiInclination =\n            mission_geometry::isOrbitRetrograde( keplerianElements );\n\n    // Convert to modified equinoctial elements.\n    return convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                          avoidSingularityAtPiInclination );\n}\n\n//! Convert Keplerian to modified equinoctial orbital elements using MEE explicit equation set.\nbasic_mathematics::Vector6d convertKeplerianToModifiedEquinoctialElements(\n        const basic_mathematics::Vector6d& keplerianElements,\n        const bool avoidSingularityAtPiInclination )\n// Based on Hintz, 2008.\n{\n    using mathematical_constants::PI;\n\n    // Declaring eventual output vector.\n    basic_mathematics::Vector6d modifiedEquinoctialState( 6 );\n\n    // Compute semi-latus rectum.\n    double singularityTolerance = 1.0e-15; // Based on tolerance chosen in\n                                           // orbitalElementConversions.cpp in Tudat Core.\n\n    // Extracting eccentricity for ease of referencing.\n    double eccentricity = keplerianElements( eccentricityIndex );\n\n    // If e is (very near) one, then semi-major axis is undefined and thus the first kepler\n    // element is the semi-latus rectum.\n    if ( std::fabs( eccentricity - 1.0 ) < singularityTolerance )\n    {\n        modifiedEquinoctialState( semiLatusRectumIndex )\n                = keplerianElements( semiLatusRectumIndex );\n    }\n    else // eccentricity is significantly away from singularity and can be computed with p=a(1-e\u2264).\n    {\n        modifiedEquinoctialState( semiLatusRectumIndex ) = keplerianElements( semiMajorAxisIndex )\n                                                           * ( 1.0 - eccentricity * eccentricity );\n    }\n\n    // Determine prograde-ness, as other five parameters depend on that fact.\n    double inclination = keplerianElements( inclinationIndex );\n\n    // If inclination is outside range [0,PI].\n    if ( ( inclination < 0.0 ) || ( inclination > PI ) )\n    {\n        // Define the error message.\n        std::stringstream errorMessage;\n        errorMessage << \"Inclination is expected in range [0,\" << PI << \"]\\n\"\n                     << \"Specified inclination: \" << inclination << \" rad.\" << std::endl;\n\n        // Throw exception.\n        boost::throw_exception( std::runtime_error( errorMessage.str( ) ) );\n    }\n    //Else, nothing wrong and continue.\n\n    // Compute set dependant helper parameters.\n    double argumentOfPeriapsisAndAscendingNode = 0.0;\n    double tangentOfHalfInclination = 0.0;\n\n    // If normal set of equations is to be used (i.e. not inverse set for singularity).\n    if ( !avoidSingularityAtPiInclination )\n    {\n        // Add (+) argument of periapsis and longitude of ascending node.\n        argumentOfPeriapsisAndAscendingNode = keplerianElements( argumentOfPeriapsisIndex )\n                + keplerianElements( longitudeOfAscendingNodeIndex );\n\n        // Take the tangent of half the inclination.\n        tangentOfHalfInclination = std::tan( inclination / 2.0 );\n    }\n    else // the orbit is retrograde.\n    {\n        // Subtract (-) longitude of ascending node from argument of periapsis.\n        argumentOfPeriapsisAndAscendingNode = keplerianElements( argumentOfPeriapsisIndex )\n                - keplerianElements( longitudeOfAscendingNodeIndex );\n\n        // Take the inverse of the tangent of half the inclination to avoid singularity at tan\n        // PI/2.\n        tangentOfHalfInclination = 1.0 / std::tan( inclination / 2.0 );\n    }\n\n    // Compute f-element.\n    modifiedEquinoctialState( fElementIndex ) = eccentricity\n            * std::cos( argumentOfPeriapsisAndAscendingNode );\n\n    // Compute g-element.\n    modifiedEquinoctialState( gElementIndex ) = eccentricity\n            * std::sin( argumentOfPeriapsisAndAscendingNode );\n\n    // Compute h-element.\n    modifiedEquinoctialState( hElementIndex ) = tangentOfHalfInclination\n            * std::cos( keplerianElements( longitudeOfAscendingNodeIndex ) );\n\n    // Compute k-element.\n    modifiedEquinoctialState( kElementIndex ) = tangentOfHalfInclination\n            * std::sin( keplerianElements( longitudeOfAscendingNodeIndex ) );\n\n    // Compute true longitude (modulo 2 PI to keep within interval -2PI to 2PI).\n    modifiedEquinoctialState( trueLongitudeIndex )\n            = basic_mathematics::computeModulo(\n                argumentOfPeriapsisAndAscendingNode\n                + keplerianElements( trueAnomalyIndex ), 2.0 * PI );\n\n    // Give back result.\n    return modifiedEquinoctialState;\n}\n\n//! Convert modified equinoctial to Keplerian orbital elements.\nbasic_mathematics::Vector6d convertModifiedEquinoctialToKeplerianElements(\n        const basic_mathematics::Vector6d& modifiedEquinoctialElements,\n        const bool avoidSingularityAtPiInclination )\n// Using unknown source pdf, code archive E. Heeren and personal derivation based on Hintz 2008.\n{\n    using mathematical_constants::PI;\n\n    // Declaration of output vector.\n    basic_mathematics::Vector6d convertedKeplerianElements = basic_mathematics::\n            Vector6d::Zero( 6 );\n\n    // for ease of referencing, almost all modified equinoctial elements.\n    double fElement = modifiedEquinoctialElements( fElementIndex );\n    double gElement = modifiedEquinoctialElements( gElementIndex );\n    double hElement = modifiedEquinoctialElements( hElementIndex );\n    double kElement = modifiedEquinoctialElements( kElementIndex );\n\n    // Tolerance for singularities.\n    double singularityTolerance = 1.0e-15;\n\n    // Compute eccentricity.\n    double eccentricity = std::sqrt( fElement * fElement + gElement * gElement );\n    convertedKeplerianElements( eccentricityIndex ) = eccentricity;\n\n    // Compute semi-major axis.\n    // If eccentricity is not near-parabolic.\n    if ( std::fabs( eccentricity - 1.0 ) > singularityTolerance )\n    {\n        // Use semi-latus rectum and eccentricity to calculate semi-major axis with a=p/(1-e^2).\n        convertedKeplerianElements( semiMajorAxisIndex ) =\n                modifiedEquinoctialElements( semiLatusRectumIndex ) /\n                ( 1.0 - eccentricity * eccentricity );\n    }\n    // This is (almost) a parabola and the semimajor axis will tend to infinity and be useless.\n    else\n    {\n        // Give semi-latus rectum instead.\n        convertedKeplerianElements( semiLatusRectumIndex ) =\n                modifiedEquinoctialElements( semiLatusRectumIndex );\n    }\n\n    // Compute longitude of ascending node.\n\n    // Compute solution in [-PI,PI] interval with atan2.\n    double longitudeOfAscendingNode = std::atan2( kElement, hElement );\n\n    // Store longitude of ascending node.\n    convertedKeplerianElements( longitudeOfAscendingNodeIndex ) = basic_mathematics::\n            computeModulo( longitudeOfAscendingNode, 2.0 * PI );\n\n    // Compute inclination.\n\n    // If prograde factor must be positive, otherwise negative.\n    double retrogradeFactor = avoidSingularityAtPiInclination ? -1.0 : 1.0;\n\n    // Calculate magnitude of inclination with retrogradeFactor (derived based on Hintz, 2008).\n    double hSquaredPlusKSquared = std::pow( hElement * hElement + kElement * kElement ,\n                                            retrogradeFactor );\n\n    convertedKeplerianElements( inclinationIndex ) =\n            2.0 * std::atan( std::sqrt( hSquaredPlusKSquared ) );\n    // Was: std::atan2(2.0 * std::sqrt(hSquaredPlusKSquared) , (1.0 - hSquaredPlusKSquared));\n\n    // Compute argument of periapsis.\n\n    // Helper quantity (omega + I * OMEGA ), for argument of periapsis and true anomaly.\n    double argumentOfPeriapsisAndLongitude;\n\n    // If eccentricity is (near) circular\n    if ( eccentricity < singularityTolerance )\n        // Then the composite argument of periapsis and longitude together cannot be determined\n        // because both arguments of the atan2 functions will be zero.\n    {\n        // Set argument of periapsis to zero.\n        convertedKeplerianElements( argumentOfPeriapsisIndex ) = 0.0;\n\n        // Set composite argument to longitude only, since argument of periapsis is now zero.\n        argumentOfPeriapsisAndLongitude = retrogradeFactor * longitudeOfAscendingNode;\n    }\n    else\n        // Argument of periapsis can be found from composite argument.\n    {\n        // Compute composite argument.\n        argumentOfPeriapsisAndLongitude = std::atan2( gElement, fElement );\n\n        // Compute argument of periapsis.\n        convertedKeplerianElements( argumentOfPeriapsisIndex ) = basic_mathematics::\n                computeModulo( argumentOfPeriapsisAndLongitude\n                               - retrogradeFactor * longitudeOfAscendingNode, 2.0 * PI );\n    }\n\n    // Compute true anomaly.\n    convertedKeplerianElements( trueAnomalyIndex ) = basic_mathematics::\n            computeModulo( modifiedEquinoctialElements( trueLongitudeIndex )\n                           - argumentOfPeriapsisAndLongitude, 2.0 * PI );\n\n    // Return converted elements.\n    return convertedKeplerianElements;\n}\n\n//! Convert Cartesian to modified equinoctial orbital elements using implicit MEE equation set.\nbasic_mathematics::Vector6d convertCartesianToModifiedEquinoctialElements(\n        const basic_mathematics::Vector6d& cartesianElements,\n        const double centralBodyGravitationalParameter )\n{\n    using mathematical_constants::PI;\n\n    // Convert to keplerian elements.\n    basic_mathematics::Vector6d keplerianElements = convertCartesianToKeplerianElements(\n                cartesianElements, centralBodyGravitationalParameter );\n\n    // Check whether orbit is retrograde.\n    bool avoidSingularityAtPiInclination =\n            mission_geometry::isOrbitRetrograde( keplerianElements );\n\n    // Convert to modified equinoctial elements.\n    return convertKeplerianToModifiedEquinoctialElements(\n                keplerianElements, avoidSingularityAtPiInclination );\n}\n\n//! Convert Cartesian to modified equinoctial orbital elements using explicit MEE equation set.\nbasic_mathematics::Vector6d convertCartesianToModifiedEquinoctialElements(\n        const basic_mathematics::Vector6d& cartesianElements,\n        const double centralBodyGravitationalParameter,\n        const bool avoidSingularityAtPiInclination )\n{\n    // Convert Cartesian to Keplerian to modified equinoctial elements.\n    return convertKeplerianToModifiedEquinoctialElements(\n                convertCartesianToKeplerianElements(\n                    cartesianElements, centralBodyGravitationalParameter ),\n                avoidSingularityAtPiInclination );\n}\n\n//! Convert Modified Equinoctial Elements to Cartesian Elements.\nbasic_mathematics::Vector6d convertModifiedEquinoctialToCartesianElements(\n        const basic_mathematics::Vector6d& modifiedEquinoctialElements,\n        const double centralBodyGravitationalParameter,\n        const bool avoidSingularityAtPiInclination )\n// Using unnamed pdf and code archive Bart R\u02c6mgens.\n{\n    // Creating output vector.\n    basic_mathematics::Vector6d convertedCartesianElements = basic_mathematics::\n            Vector6d::Zero( 6 );\n\n    // If the prograde equations are to be used.\n    if ( !avoidSingularityAtPiInclination )\n    {\n        // Local storage of elements for ease of access.\n        double semiLatusRectum = modifiedEquinoctialElements( semiLatusRectumIndex );\n        double fElement = modifiedEquinoctialElements( fElementIndex );\n        double gElement = modifiedEquinoctialElements( gElementIndex );\n        double hElement = modifiedEquinoctialElements( hElementIndex );\n        double kElement = modifiedEquinoctialElements( kElementIndex );\n        double trueLongitude = modifiedEquinoctialElements( trueLongitudeIndex );\n\n        // Computing helper parameters.\n\n        // Square-root\n        double squareRootOfGravitationalParameterOverSemiLatusRectum =\n                std::sqrt( centralBodyGravitationalParameter / semiLatusRectum );\n\n        // Cosines and sine.\n        double cosineTrueLongitude = std::cos( trueLongitude );\n        double sineTrueLongitude = std::sin( trueLongitude );\n\n        // s\u2264, a\u2264, w, r from references.\n        double sSquaredParameter = 1.0 + hElement * hElement + kElement * kElement;\n        double aSquaredParameter = hElement * hElement - kElement*kElement;\n        double wParameter = 1.0 + fElement * cosineTrueLongitude\n                + gElement * sineTrueLongitude;\n        double radius = semiLatusRectum / wParameter;\n\n        // Computing position and storing (using code archive Bart R\u02c6mgens and unnamed pdf).\n        convertedCartesianElements( xCartesianPositionIndex )\n                = radius / sSquaredParameter * ( cosineTrueLongitude + aSquaredParameter\n                                                 * cosineTrueLongitude + 2.0 * hElement * kElement\n                                                 * sineTrueLongitude );\n        convertedCartesianElements( yCartesianPositionIndex )\n                = radius / sSquaredParameter * ( sineTrueLongitude - aSquaredParameter\n                                                 * sineTrueLongitude + 2.0 * hElement * kElement\n                                                 * cosineTrueLongitude );\n        convertedCartesianElements( zCartesianPositionIndex ) = 2.0 * radius / sSquaredParameter\n                * ( hElement * sineTrueLongitude - kElement * cosineTrueLongitude );\n\n        // Computing velocities (these can probably use more optimal computation).\n        convertedCartesianElements( xCartesianVelocityIndex ) = -1.0 / sSquaredParameter\n                * squareRootOfGravitationalParameterOverSemiLatusRectum\n                * ( sineTrueLongitude + aSquaredParameter * sineTrueLongitude\n                    - 2.0 * hElement * kElement * cosineTrueLongitude + gElement\n                    - 2.0 * fElement * hElement * kElement + aSquaredParameter * gElement );\n        convertedCartesianElements( yCartesianVelocityIndex ) = -1.0 / sSquaredParameter\n                * squareRootOfGravitationalParameterOverSemiLatusRectum\n                * ( -cosineTrueLongitude + aSquaredParameter * cosineTrueLongitude\n                    + 2.0 * hElement * kElement * sineTrueLongitude - fElement\n                    + 2.0 * gElement * hElement * kElement + aSquaredParameter * fElement );\n        convertedCartesianElements( zCartesianVelocityIndex ) = 2.0 / sSquaredParameter\n                * squareRootOfGravitationalParameterOverSemiLatusRectum\n                * ( hElement * cosineTrueLongitude + kElement * sineTrueLongitude\n                    + fElement * hElement + gElement * kElement );\n    }\n    else // use the indirect transformation via an intermediate Kepler state.\n    {\n        // Use the Keplerian state as an intermediary step, as there is no direct transformation\n        // available in literature (personal derivation forgone for now due to time constraints).\n        convertedCartesianElements =\n                convertKeplerianToCartesianElements(\n                    convertModifiedEquinoctialToKeplerianElements(\n                        modifiedEquinoctialElements, avoidSingularityAtPiInclination ),\n                    centralBodyGravitationalParameter );\n    }\n\n    // Return converted set of elements.\n    return convertedCartesianElements;\n}\n\n} // namespace orbital_element_conversions\n\n} // namespace tudat\n", "meta": {"hexsha": "79f1a771dba2d9f24adb801339efd5f31d8cb22f", "size": 19321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/modifiedEquinoctialElementConversions.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/Astrodynamics/BasicAstrodynamics/modifiedEquinoctialElementConversions.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/Astrodynamics/BasicAstrodynamics/modifiedEquinoctialElementConversions.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": 48.1820448878, "max_line_length": 99, "alphanum_fraction": 0.6897158532, "num_tokens": 4353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5437421077800848}}
{"text": "#include \"refill/system_models/linear_system_model.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n\nnamespace refill {\n\nTEST(LinearSystemModelTest, ConstructorTest) {\n  // test default constructor\n  LinearSystemModel* system_model_p = new LinearSystemModel;\n\n  EXPECT_EQ(0, system_model_p->getStateDim());\n  EXPECT_EQ(0, system_model_p->getInputDim());\n  EXPECT_EQ(0, system_model_p->getNoiseDim());\n\n  delete system_model_p;\n\n  GaussianDistribution system_noise(Eigen::Vector2d::Zero(),\n                                    Eigen::Matrix2d::Identity());\n\n  // test constructor with system mapping and noise\n  system_model_p = new LinearSystemModel(Eigen::Matrix2d::Identity(),\n                                         system_noise);\n\n  EXPECT_EQ(2, system_model_p->getStateDim());\n  EXPECT_EQ(0, system_model_p->getInputDim());\n  EXPECT_EQ(2, system_model_p->getNoiseDim());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), system_model_p->getSystemMapping());\n  EXPECT_EQ(Eigen::MatrixXd::Zero(0, 0), system_model_p->getInputMapping());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), system_model_p->getNoiseMapping());\n\n  delete system_model_p;\n\n  // test constructor with system mapping, noise and input mapping\n  system_model_p = new LinearSystemModel(Eigen::Matrix2d::Identity(),\n                                         system_noise,\n                                         Eigen::Matrix2d::Identity());\n\n  EXPECT_EQ(2, system_model_p->getStateDim());\n  EXPECT_EQ(2, system_model_p->getInputDim());\n  EXPECT_EQ(2, system_model_p->getNoiseDim());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), system_model_p->getSystemMapping());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), system_model_p->getInputMapping());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), system_model_p->getNoiseMapping());\n\n  delete system_model_p;\n\n  // test constructor with system noise and system, input and noise mapping\n  system_model_p = new LinearSystemModel(Eigen::Matrix2d::Identity(),\n                                         system_noise,\n                                         Eigen::Matrix2d::Identity(),\n                                         Eigen::Matrix2d::Ones());\n\n  EXPECT_EQ(2, system_model_p->getStateDim());\n  EXPECT_EQ(2, system_model_p->getInputDim());\n  EXPECT_EQ(2, system_model_p->getNoiseDim());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), system_model_p->getSystemMapping());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), system_model_p->getInputMapping());\n  EXPECT_EQ(Eigen::Matrix2d::Ones(), system_model_p->getNoiseMapping());\n\n  delete system_model_p;\n}\n\nTEST(LinearSystemModelTest, SetterTest) {\n  GaussianDistribution system_noise(Eigen::Vector2d::Zero(),\n                                    Eigen::Matrix2d::Identity());\n\n  LinearSystemModel system_model;\n\n  system_model.setModelParameters(Eigen::Matrix2d::Identity(), system_noise);\n\n  EXPECT_EQ(2, system_model.getStateDim());\n  EXPECT_EQ(0, system_model.getInputDim());\n  EXPECT_EQ(2, system_model.getNoiseDim());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), system_model.getSystemMapping());\n  EXPECT_EQ(Eigen::MatrixXd::Zero(0, 0), system_model.getInputMapping());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), system_model.getNoiseMapping());\n\n  system_noise.setDistributionParameters(Eigen::Vector3d::Zero(),\n                                         Eigen::Matrix3d::Identity());\n\n  system_model.setModelParameters(Eigen::Matrix3d::Identity(), system_noise,\n                                   Eigen::Matrix3d::Identity());\n\n  EXPECT_EQ(3, system_model.getStateDim());\n  EXPECT_EQ(3, system_model.getInputDim());\n  EXPECT_EQ(3, system_model.getNoiseDim());\n  EXPECT_EQ(Eigen::Matrix3d::Identity(), system_model.getSystemMapping());\n  EXPECT_EQ(Eigen::Matrix3d::Identity(), system_model.getInputMapping());\n  EXPECT_EQ(Eigen::Matrix3d::Identity(), system_model.getNoiseMapping());\n\n  system_noise.setDistributionParameters(Eigen::Vector4d::Zero(),\n                                         Eigen::Matrix4d::Identity());\n\n  system_model.setModelParameters(Eigen::Matrix4d::Identity(), system_noise,\n                                   Eigen::Matrix4d::Identity(),\n                                   Eigen::Matrix4d::Ones());\n\n  EXPECT_EQ(4, system_model.getStateDim());\n  EXPECT_EQ(4, system_model.getInputDim());\n  EXPECT_EQ(4, system_model.getNoiseDim());\n  EXPECT_EQ(Eigen::Matrix4d::Identity(), system_model.getSystemMapping());\n  EXPECT_EQ(Eigen::Matrix4d::Identity(), system_model.getInputMapping());\n  EXPECT_EQ(Eigen::Matrix4d::Ones(), system_model.getNoiseMapping());\n}\n\nTEST(LinearSystemModelTest, GetterTest) {\n  GaussianDistribution system_noise(Eigen::Vector2d::Zero(),\n                                    Eigen::Matrix2d::Identity());\n\n  LinearSystemModel system_model(Eigen::Matrix2d::Identity(), system_noise,\n                                 Eigen::Matrix2d::Ones(),\n                                 Eigen::Matrix2d::Constant(2.0));\n\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), system_model.getSystemMapping());\n  EXPECT_EQ(Eigen::Matrix2d::Ones(), system_model.getInputMapping());\n  EXPECT_EQ(Eigen::Matrix2d::Constant(2.0), system_model.getNoiseMapping());\n  EXPECT_EQ(\n      Eigen::Matrix2d::Identity(),\n      system_model.getStateJacobian(Eigen::Vector2d::Zero(),\n                                    Eigen::Vector2d::Zero()));\n  EXPECT_EQ(\n      Eigen::Matrix2d::Constant(2.0),\n      system_model.getNoiseJacobian(Eigen::Vector2d::Zero(),\n                                    Eigen::Vector2d::Zero()));\n}\n\nTEST(LinearSystemModelTest, PropagationTest) {\n  GaussianDistribution system_noise(Eigen::Vector2d::Ones(),\n                                    Eigen::Matrix2d::Identity());\n\n  LinearSystemModel system_model(Eigen::Matrix2d::Identity(), system_noise,\n                                 Eigen::Matrix2d::Identity(),\n                                 Eigen::Matrix2d::Ones());\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(3.0),\n            system_model.propagate(Eigen::Vector2d::Ones()));\n  EXPECT_EQ(\n      Eigen::Vector2d::Constant(4.0),\n      system_model.propagate(Eigen::Vector2d::Ones(), Eigen::Vector2d::Ones(),\n                             Eigen::Vector2d::Ones()));\n}\n\n}  // namespace refill\n", "meta": {"hexsha": "ad5680ffeebc5ffbc9afa6833b39dc010f6249d0", "size": 6146, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/linear_system_model_test.cc", "max_stars_repo_name": "jwidauer/refill", "max_stars_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-13T07:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T11:26:34.000Z", "max_issues_repo_path": "src/tests/linear_system_model_test.cc", "max_issues_repo_name": "jwidauer/refill", "max_issues_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/linear_system_model_test.cc", "max_forks_repo_name": "jwidauer/refill", "max_forks_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T13:21:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T20:33:20.000Z", "avg_line_length": 42.095890411, "max_line_length": 78, "alphanum_fraction": 0.6539212496, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5437421062080819}}
{"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 <iostream>\n#include <Eigen/Core>\n#include \"utils.hpp\"\n#include \"io_utils.hpp\"\n\n#include \"reconstructor_3d.hpp\"\n#include \"marching_cubes.hpp\"\n#include \"rgbd_types.hpp\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\n\nsdf initialize_sdf(const Configuration &configuration, const vector<float> &volume)\n{\n\tfloat voxel_size = configuration.get_voxel_size();\n\n\tint voxel_count_x = static_cast<int>(std::ceil((volume[1] - volume[0]) / voxel_size));\n\tint voxel_count_y = static_cast<int>(std::ceil((volume[3] - volume[2]) / voxel_size));\n\tint voxel_count_z = static_cast<int>(std::ceil((volume[5] - volume[4]) / voxel_size));\n\n\tsdf model(voxel_count_x, voxel_count_y, voxel_count_z, voxel_size, 0.f, 1.f);\n\n\treturn model;\n}\n\ntemplate <typename T>\nTransform<T, 3, Isometry> to_isometry(const Matrix<T, 4, 4> &pose_matrix)\n{\n\tTransform<T, 3, Isometry> pose;\n\tpose.setIdentity();\n\n\tpose.linear() = pose_matrix.block<3, 3>(0, 0);\n\tpose.translation() = pose_matrix.block<3, 1>(0, 3);\n\t\n\treturn pose;\n}\n\nsdf generate_tsdf(const Mat& depth_map, const Mat& color_map, const Isometry3f &transformation_matrix, const Matrix3f &intrinsics, const vector<float>& dimensions,\n\tconst Configuration& configuration) {\n\n\tsdf s = initialize_sdf(configuration, dimensions);\n\tconst float voxel_size = configuration.get_voxel_size();\n\n\tfloat delta = voxel_size;\n\tfloat eta = 3 * voxel_size;\n\n\tVector3f lower_left(dimensions[0], dimensions[2], dimensions[4]);\n\n#pragma omp parallel for\n\tfor (int z = 0; z < s.size_z; ++z)\n\t\tfor (int y = 0; y < s.size_y; ++y)\n\t\t\tfor (int x = 0; x < s.size_x; ++x) {\n\t\t\t\tVector3f rp = lower_left + voxel_size * Vector3f(x + 0.5f, y + 0.5f, z + 0.5f);\n\t\t\t\tVector3f transformed_point = transformation_matrix * rp;\n\n\t\t\t\tVector2f point2d = project_point(transformed_point, intrinsics);\n\n\t\t\t\tint imgx = static_cast<int>(ceil(point2d(0)));\n\t\t\t\tint imgy = static_cast<int>(ceil(point2d(1)));\n\n\t\t\t\tif (imgx >= 0 && imgy >= 0 && imgx < depth_map.cols && imgy < depth_map.rows) {\n\n\t\t\t\t\tfloat depth = depth_map.at<float>(imgy, imgx);\n\t\t\t\t\tif (isfinite(depth) && depth > .0f) {\n\t\t\t\t\t\tconst float signed_distance = depth - transformed_point(2);\n\t\t\t\t\t\ts.weights.at(x, y, z) = signed_distance > -eta;\n\t\t\t\t\t\ts.distance_field.at(x, y, z) = min(1.f, max(-1.f, signed_distance / delta));\n\n\t\t\t\t\t\tcv::Vec3b color = color_map.at<cv::Vec3b>(imgy, imgx);\n\t\t\t\t\t\ts.color_field.red.at(x, y, z) = color[2] / 255.f;\n\t\t\t\t\t\ts.color_field.green.at(x, y, z) = color[1] / 255.f;\n\t\t\t\t\t\ts.color_field.blue.at(x, y, z) = color[0] / 255.f;\n\t\t\t\t\t} // otherwise no need to change values (works only when they are initialized)\n\t\t\t\t}\n\t\t\t}\n\n\treturn s;\n}\n\nvoid integrate_into_weighted_average(sdf& wa, const sdf& s) {\n\tcolor_cube<float> & wa_colors = wa.color_field;\n\tconst color_cube<float> & s_colors = s.color_field;\n\n#pragma omp parallel for\n\tfor (int z = 0; z < wa.size_z; ++z)\n\t\tfor (int y = 0; y < wa.size_y; ++y)\n\t\t\tfor (int x = 0; x < wa.size_x; ++x) {\n\t\t\t\tfloat old_weight = wa.weights.at(x, y, z);\n\t\t\t\tfloat added_weight = s.weights.at(x, y, z);\n\t\t\t\tfloat new_weight = old_weight + added_weight;\n\n\t\t\t\tif (new_weight > 0.f) {\n\t\t\t\t\t//wa.distance_field.at(x, y, z) /= wa.weights.at(x, y, z);\n\t\t\t\t\twa.distance_field.at(x, y, z) = (wa.distance_field.at(x, y, z) * old_weight + s.distance_field.at(x, y, z) * added_weight) / new_weight;\n\n\t\t\t\t\t//if (fabs(wa.distance_field.at(x, y, z)) < 1.f) { // assign color only at near-surface voxels\n\t\t\t\t\twa_colors.red.at(x, y, z) = (wa_colors.red.at(x, y, z)   * old_weight + s_colors.red.at(x, y, z)   * added_weight) / new_weight;\n\t\t\t\t\twa_colors.green.at(x, y, z) = (wa_colors.green.at(x, y, z) * old_weight + s_colors.green.at(x, y, z) * added_weight) / new_weight;\n\t\t\t\t\twa_colors.blue.at(x, y, z) = (wa_colors.blue.at(x, y, z)  * old_weight + s_colors.blue.at(x, y, z)  * added_weight) / new_weight;\n\t\t\t\t\t//}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\twa.distance_field.at(x, y, z) = -1.f;\n\t\t\t\t\t// and do not change color\n\t\t\t\t}\n\t\t\t\twa.weights.at(x, y, z) = new_weight;\n\t\t\t}\n}\n\nsdf reconstruct_sdf(const Configuration& configuration, const vector<float>& volume, const vector<RgbdFile> &input_images, const vector<Matrix4f> &poses)\n{\n\n\tsdf model = initialize_sdf(configuration, volume);\n\tconst int number_of_frames = static_cast<int>(input_images.size());\n\n\tint64 elapsed_time = 0;\n\n\tfor (int i = 0; i < number_of_frames; ++i)\n\t{\n\t\tRgbdFrame rgbd_frame = get_rgbd_frame(input_images[i]);\n\t\tIsometry3f pose = to_isometry(poses[i]);\n\n\t\tauto start_time = getTickCount();\n\t\tsdf current_sdf = generate_tsdf(rgbd_frame.second, rgbd_frame.first, pose.inverse(), configuration.get_intrinsics(),\n\t\t                                   volume, configuration);\n\t\tintegrate_into_weighted_average(model, current_sdf);\n\t\telapsed_time += getTickCount() - start_time;\n\t\tcout << \"Integrated \" << i + 1 << \" out of \" << number_of_frames << \" frames into reconstruction\" << endl;\n\t}\n\n\tstd::cout << \"sdf fusion elapsed time: \" << elapsed_time / getTickFrequency() << \" sec\" << std::endl;\n\t\n\treturn model;\n}\n\nbool run_reconstruction(const Configuration &configuration, const vector<float> &volume)\n{\n\tvector<RgbdFile> input_images = get_input_images(configuration.get_out_rgb_images_dir(), configuration.get_out_depth_images_dir());\n\tvector<Matrix4f> poses = read_scene_poses<float>(configuration.get_poses_file());\n\n\tif (input_images.size() != poses.size())\n\t{\n\t\tcerr << \"Number of frames (\" << input_images.size() << \") and number of poses (\" << poses.size() << \") don't match\" << endl;\n\t\treturn false;\n\t}\n\n\tsdf model = reconstruct_sdf(configuration, volume, input_images, poses);\n\tvector<marching_cubes::triangle> model_mesh = mesh_valid_only(model);\n\n\tsave_mesh_ply(model_mesh, configuration.get_model_file(), true);\n\treturn true;\n}\n", "meta": {"hexsha": "b39db3fb1130f02e474758d4ddff72ad75f3fba5", "size": 6086, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdf_fusion/src/aruco_sdffusion/src/reconstructor_3d.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/reconstructor_3d.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/reconstructor_3d.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": 37.3374233129, "max_line_length": 163, "alphanum_fraction": 0.6593821886, "num_tokens": 1716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5437421046360786}}
{"text": "#include \"test_util.h\"\n#include <Eigen/Core>\n#include \"iris/iris.h\"\n\nint main () {\n\n  Eigen::MatrixXd A(3,2);\n  A << -1, 0,\n       0, -1,\n       1, 1;\n  Eigen::VectorXd b(3);\n  b << 0, 0, 1;\n  iris::Polyhedron p(A, b);\n\n  Eigen::MatrixXd A2(2,2);\n  A2 << 2, 3,\n        4, 5;\n  Eigen::VectorXd b2(2);\n  b2 << 6, 7;\n  iris::Polyhedron other(A2, b2);\n\n  p.appendConstraints(other);\n\n  valuecheck(p.getNumberOfConstraints(), 5);\n  Eigen::MatrixXd A_expected(5,2);\n  A_expected << -1, 0,\n                 0, -1,\n                 1, 1,\n                 2, 3,\n                 4, 5;\n  valuecheckMatrix(p.getA(), A_expected, 1e-12);\n\n  return 0;\n}", "meta": {"hexsha": "97240c3b6e19c0adba8d643654e51009ebd85587", "size": 639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cxx/test/test_append_polyhedron.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/test/test_append_polyhedron.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/test/test_append_polyhedron.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": 18.7941176471, "max_line_length": 48, "alphanum_fraction": 0.5086071987, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5436584180708917}}
{"text": "//\n//  meanie3D-satconv\n//\n\n#include <string>\n#include <iostream>\n#include <boost/program_options.hpp>\n#include <boost/program_options/parsers.hpp>\n\nusing namespace std;\nusing namespace boost;\n\n#pragma mark -\n#pragma mark Definitions\n\ntypedef enum {\n    RadicanceToTemperature,\n    TemperatureToRadiance\n} ConversionType;\n\n// Radiation constant #1\nconst double c1 = 1.19104e-05;\n// Radiation constant #2\nconst double c2 = 1.43877;\n\n// Names of the variables available for conversion\nconst string variables[8] = {\n    \"msevi_l15_ir_039\", \n    \"msevi_l15_ir_087\", \n    \"msevi_l15_ir_097\", \n    \"msevi_l15_ir_108\", \n    \"msevi_l15_ir_120\", \n    \"msevi_l15_ir_134\",\n    \"msevi_l15_wv_062\",\n    \"msevi_l15_wv_073\"\n};\n\n// Calibration constant alpha\nconst double alpha[8] = {\n    0.9954, \n    0.9996, \n    0.9999,\n    0.9983, \n    0.9988, \n    0.9981,\n    0.9963,\n    0.9991\n};\n\n// Calibration constant beta\nconst double beta[8] = {\n    3.438, \n    0.179, \n    0.056, \n    0.64, \n    0.408, \n    0.561,\n    2.185,\n    0.47\n};\n\n// Wavenumber \nconst double wavenum[8] = {\n    2568.832, \n    1148.62, \n    1035.289, \n    931.7, \n    836.445, \n    751.792,\n    1600.548,\n    1360.33\n};\n       \n#pragma mark -\n#pragma mark Command line parsing\n\nvoid parse_commmandline(program_options::variables_map vm, \n        int& variableIndex,\n        double &value,\n        ConversionType &conversionType) \n{\n    if (vm.count(\"temperature\") != 0) {\n        conversionType = RadicanceToTemperature;\n    } else if (vm.count(\"radiance\") != 0) {\n        conversionType = TemperatureToRadiance;\n    } else {\n        cerr << \"Specify -r or -t\" << endl;\n        exit(EXIT_FAILURE);\n    }\n    \n    if (vm.count(\"value\") == 0) {\n        cerr << \"Missing --value argument\" << endl;\n        exit(EXIT_FAILURE);\n    }\n    value = vm[\"value\"].as<double>();\n    \n    if (vm.count(\"variable\") == 0) {\n        cerr << \"Missing --variable argument\" << endl;\n        exit(EXIT_FAILURE);\n    }\n    string variable = vm[\"variable\"].as<string>();\n    \n    variableIndex = -1;\n    for (int i=0; i<8; i++) {\n        if (variables[i] == variable) {\n            variableIndex = i;\n            break;\n        }\n    }\n    if (variableIndex < 0) {\n        cerr << \"Illegal value for --variable\" << endl;\n        exit(EXIT_FAILURE);\n    }\n\n}\n\n#pragma mark -\n#pragma mark Helper Methods\n        \n/** Calculates the brightness temperature in degree centigrade\n* from the given spectral radiance.\n * \n* @param index of the variable to be converted\n* @param radiance value for the given channel\n* @return equivalent brightness temperature in [degree C]\n*/\ndouble brightness_temperature(const int var_index, const double &radiance) {\n   double nu = wavenum[var_index];\n   double Tbb = c2 * nu / log(1 + nu * nu * nu * c1 / radiance);\n   double Tb = (Tbb - beta[var_index]) / alpha[var_index];\n   return Tb - 273.15;\n}\n\n/** Inverse calculation. Spectral radiance from temperature\n* in degree centigrade\n * \n* @param index of the variable to be converted\n* @param brightness temperature in [degree C]\n* @return radiance value for the given channel\n*/\ndouble spectral_radiance(const size_t var_index, const double &temperature) {\n   double nu = wavenum[var_index];\n   double Tbb = (temperature + 273.15) * alpha[var_index] + beta[var_index];\n   return nu * nu * nu * c1 / (exp(c2 * nu / Tbb) - 1);\n}\n\n#pragma mark -\n#pragma mark MAIN\n\nint main(int argc, char** argv)\n{\n    // Declare the supported options.\n    namespace po = boost::program_options;\n    \n    po::positional_options_description p;\n    p.add(\"value\", -1);\n    \n    po::options_description desc(\"Converts spectral radiance to equivalent brightness temperature or vice versa.\");\n    desc.add_options()\n            (\"temperature,t\", \"radiance to temperature\")\n            (\"radiance,r\", \"temperature to radiance\")\n            (\"value\", po::value<double>(), \"value to convert\")\n            (\"variable,v\", po::value<string>(), \"One of msevi_l15_ir_039, msevi_l15_ir_087, msevi_l15_ir_097, msevi_l15_ir_108, msevi_l15_ir_120, msevi_l15_ir_134, msevi_l15_wv_062,msevi_l15_wv_073\")\n            ;\n    \n    if (argc < 2) {\n        cout << desc << \"\\n\";\n        exit(EXIT_SUCCESS);\n    }\n    \n    po::variables_map vm;\n    try\n    {\n        po::store(parse_command_line(argc, argv, desc, po::command_line_style::unix_style ^ po::command_line_style::allow_short), vm);\n        po::notify(vm);\n    } catch (std::exception &e) {\n        cerr << \"FATAL:parsing command line caused exception: \" << e.what()\n                << \": check meanie3D-satconv --help for command line options\"\n                << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    // Evaluate user input\n    double value;\n    int variableIndex;\n    ConversionType type;\n    try {\n        parse_commmandline(vm,variableIndex,value,type);\n    } catch (const std::exception &e) {\n        cerr << \"ERROR:exception \" << e.what() << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    switch (type) {\n        case RadicanceToTemperature:\n            cout << brightness_temperature(variableIndex,value) << endl;\n            break;\n        case TemperatureToRadiance:\n            cout << spectral_radiance(variableIndex,value) << endl;\n            break;\n    }\n    \n    return EXIT_SUCCESS;\n};\n", "meta": {"hexsha": "fb69b6ad2f00a69db2cd0a5121a5d2336e9fa310", "size": 5237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/executables/meanie3D-satconv.cpp", "max_stars_repo_name": "JuergenSimon/meanie3D", "max_stars_repo_head_hexsha": "776890f6b63d735153566fecc5a76c68a23ef333", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/executables/meanie3D-satconv.cpp", "max_issues_repo_name": "JuergenSimon/meanie3D", "max_issues_repo_head_hexsha": "776890f6b63d735153566fecc5a76c68a23ef333", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-09-17T13:46:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-01T16:31:29.000Z", "max_forks_repo_path": "src/executables/meanie3D-satconv.cpp", "max_forks_repo_name": "JuergenSimon/meanie3D", "max_forks_repo_head_hexsha": "776890f6b63d735153566fecc5a76c68a23ef333", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-04-18T13:13:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-18T12:30:05.000Z", "avg_line_length": 25.5463414634, "max_line_length": 199, "alphanum_fraction": 0.6175291197, "num_tokens": 1441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5436584180708917}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#define BOOST_UBLAS_NO_ELEMENT_PROXIES\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/hermitian.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/hermitian.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include \"print.hpp\"\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef std::complex<double> complex;\n    typedef ublas::vector<complex> vector;\n    typedef ublas::hermitian_matrix<complex, ublas::lower, ublas::column_major> matrix_l;\n    typedef ublas::hermitian_matrix<complex, ublas::upper, ublas::column_major> matrix_u;\n    typedef typename vector::size_type size_type;\n    rand_normal<complex>::reset();\n    size_type n=8;\n    matrix_l A_l(n);\n    matrix_u A_u(n);\n    for (size_type j=0; j<n; ++j) {\n      A_u(j, j)=rand_normal<complex>::get().real();\n      A_l(j, j)=A_u(j, j);\n      for (size_type i=0; i<j; ++i) {\n\tcomplex a();\n    \tA_u(i, j)=rand_normal<complex>::get();\n\tA_l(j, i)=std::conj(A_u(i, j));\n       }\n    }\n    vector x(n);\n    for (size_type i=0; i<n; ++i)\n      x(i)=rand_normal<complex>::get();\n    vector y(n);\n    for (size_type i=0; i<n; ++i)\n      y(i)=rand_normal<complex>::get();\n    complex alpha(rand_normal<complex>::get());\n    complex beta(rand_normal<complex>::get());\n    vector y1(alpha*ublas::prod(A_l, x)+beta*y);\n    vector y2(y);\n    blas::hpmv(alpha, A_l, x, beta, y2);\n    vector y3(y);\n    blas::hpmv(alpha, A_u, x, beta, y3);\n    std::cout << \"testing boost::ublas containers\\n\"\n    \t      << \"using ublas       : \" << print_vec(y1) << '\\n'\n    \t      << \"using blas (lower): \" << print_vec(y2) << '\\n'\n    \t      << \"using blas (upper): \" << print_vec(y3) << '\\n'\n    \t      << '\\n';\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "7ec79961cbf8fb3cf0e3cddfe898137cbba5d22b", "size": 1911, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/hpmv.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/hpmv.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/hpmv.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.5263157895, "max_line_length": 89, "alphanum_fraction": 0.6284667713, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.5436584180708915}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <polymesh/pm.hh>\n#include <typed-geometry/tg.hh>\n#include <LayoutEmbedding/Parametrization.hh>\n\nnamespace LayoutEmbedding\n{\n\nenum class LaplaceWeights\n{\n    Uniform,\n    MeanValue,\n};\n\n/// Compute harmonic field using mean-value weights.\nbool harmonic(\n        const pm::vertex_attribute<tg::pos3>& _pos,\n        const pm::vertex_attribute<bool>& _constrained,\n        const Eigen::MatrixXd& _constraint_values,\n        Eigen::MatrixXd& _res,\n        const LaplaceWeights _weights,\n        const bool _fallback_iterative = false);\n\n/// Compute harmonic field using mean-value weights.\nbool harmonic_parametrization(\n        const pm::vertex_attribute<tg::pos3>& _pos,\n        const pm::vertex_attribute<bool>& _constrained,\n        const VertexParam& _constraint_values,\n        VertexParam& _res,\n        const LaplaceWeights _weights,\n        const bool _fallback_iterative = false);\n\n}\n", "meta": {"hexsha": "991efcf56bf1b819950db68b1b5cfdc1405fbdf7", "size": 935, "ext": "hh", "lang": "C++", "max_stars_repo_path": "library/LayoutEmbedding/Harmonic.hh", "max_stars_repo_name": "jsb/LayoutEmbedding", "max_stars_repo_head_hexsha": "6ef02ed0043dfabce6d593486358d6ef15cbf3ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2021-02-18T15:35:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T07:20:37.000Z", "max_issues_repo_path": "library/LayoutEmbedding/Harmonic.hh", "max_issues_repo_name": "jsb/LayoutEmbedding", "max_issues_repo_head_hexsha": "6ef02ed0043dfabce6d593486358d6ef15cbf3ba", "max_issues_repo_licenses": ["MIT"], "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/LayoutEmbedding/Harmonic.hh", "max_forks_repo_name": "jsb/LayoutEmbedding", "max_forks_repo_head_hexsha": "6ef02ed0043dfabce6d593486358d6ef15cbf3ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-02-17T14:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T09:51:25.000Z", "avg_line_length": 25.9722222222, "max_line_length": 55, "alphanum_fraction": 0.7058823529, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5436584137182334}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n\nTEST(MathFunctions, tgamma) {\n  using stan::math::tgamma;\n  EXPECT_FLOAT_EQ(1.772453850905516, tgamma(0.5));\n  EXPECT_FLOAT_EQ(1, tgamma(1));\n  EXPECT_FLOAT_EQ(2.423965479935368, tgamma(3.2));\n  EXPECT_FLOAT_EQ(6402373705728000, tgamma(19));\n}\n\nTEST(MathFunctions, tgammaStanMath) {\n  EXPECT_THROW(stan::math::tgamma(0.0), std::domain_error);\n}\n\nTEST(MathFunctions, tgamma_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::tgamma(nan));\n}\n", "meta": {"hexsha": "a378d3df00eee9b73c1821dd2f53b9efc9cc09cf", "size": 692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/tgamma_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/tgamma_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/tgamma_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": 30.0869565217, "max_line_length": 68, "alphanum_fraction": 0.7471098266, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5436584065421605}}
{"text": "/* Copyright \u00a9 2017 Apple Inc. All rights reserved.\n *\n * Use of this source code is governed by a BSD-3-clause license that can\n * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n */\n#ifndef TURI_CONSTRAINTS_H_\n#define TURI_CONSTRAINTS_H_\n\n#include <string>\n#include <core/data/flexible_type/flexible_type.hpp>\n\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\n// Optimizaiton\n#include <ml/optimization/utils.hpp>\n#include <ml/optimization/optimization_interface.hpp>\n#include <ml/optimization/constraint_interface.hpp>\n\n// TODO: List of todo's for this file\n//------------------------------------------------------------------------------\n//\n\nnamespace turi {\n\nnamespace optimization {\n\n/**\n * \\ingroup group_optimization\n * \\addtogroup optimization_constraints Optimization Constraints\n * \\{\n */\n\n\n/**\n * Interface for non-negative constriants.\n *   x >= 0\n */\nclass non_negative_orthant : public constraint_interface {\n\n  protected:\n\n    size_t variables;                       /**< # Variables in the problem */\n\n  public:\n\n\n  /**\n   * Default constructor.\n   */\n  non_negative_orthant(const size_t& _variables){\n    variables = _variables;\n  }\n\n  /**\n   * Default desctuctor. Do nothing.\n   */\n  ~non_negative_orthant(){\n  }\n\n\n  /**\n   * Project a dense point into the constraint space.\n   * \\param[in,out]  point   Point (Dense Vector)\n   *\n   * Given a convex set X, the projection operator is given by\n   *     P(y) = \\std::max(x, o)\n   *\n   */\n  inline void project(DenseVector &point) const {\n    DASSERT_EQ(variables, point.size());\n    point = point.cwiseMax(0);\n  }\n\n  /**\n   * Project a block of a dense point into the constraint space.\n   *\n   * \\param[in,out]  point        A block project the point.\n   * \\param[in]      block_start  Start index of the block\n   * \\param[in]      block_size   Size of the block\n   *\n   * Given a convex set X, the projection operator is given by\n   *     P(y) = \\std::max(x, o)\n   *\n   */\n  inline void project_block(DenseVector &point, const size_t block_start, const\n      size_t block_size) const {\n    DASSERT_LE(variables, block_start + block_size);\n    DASSERT_EQ(block_size, point.size());\n    point = point.cwiseMax(0);\n  }\n\n  /**\n   * Boolean function to deterstd::mine if a dense point is present in a constraint\n   * space.\n   * \\param[in]  point   Point which we are querying.\n   *\n   */\n  inline bool is_satisfied(const DenseVector &point) const {\n    DASSERT_EQ(variables, point.size());\n    for(size_t i=0; i < size_t(point.size()); i++){\n      if( point(i) <= -OPTIMIZATION_ZERO)\n        return false;\n    }\n    return true;\n  }\n\n\n  /**\n   * A measure of the first order optimality conditions.\n   *\n   * \\param[in]  point    Point which we are querying.\n   * \\param[in]  gradient Gradient at that point for a given function\n   *\n   * Use the Cauchy point as a measure of optimality. See Pg 486 of\n   * Nocedal and Wright (Edition 2)\n   *\n   */\n  inline double first_order_optimality_conditions(const DenseVector &point,\n                                        const DenseVector& gradient) const{\n    DASSERT_TRUE(is_satisfied(point));\n    DenseVector proj_gradient = gradient;\n    for(size_t i=0; i < size_t(point.size()); i++){\n      if(point(i) <= OPTIMIZATION_ZERO){\n        proj_gradient(i) = std::min(0.0, gradient(i));\n      } else {\n        proj_gradient(i) = gradient(i);\n      }\n    }\n    return compute_residual(proj_gradient);\n  }\n};\n\n\n\n/**\n * Interface for box-constraints on variables.\n *   lb <= x <= ub\n */\nclass box_constraints: public constraint_interface {\n\n  protected:\n\n    DenseVector lb;                  /**< # Upper bound */\n    DenseVector ub;                  /**< # Lower bound */\n    size_t variables;                /**< # Variables in the problem */\n\n  public:\n\n\n  /**\n   * Default constructor.\n   * \\param[in]  _variables Number of variables\n   * \\param[in]  _lb Lower bound\n   * \\param[in]  _ub Upper bound\n   */\n  box_constraints(const double& _lb, const double& _ub, const size_t&\n      _variables){\n    variables = _variables;\n    lb.resize(variables);\n    lb.setConstant(_lb);\n    ub.resize(variables);\n    ub.setConstant(_ub);\n  }\n\n  /**\n   * Default constructor.\n   * \\param[in]  _variables Number of variables\n   * \\param[in]  _lb Lower bound\n   * \\param[in]  _ub Upper bound\n   */\n  box_constraints(const DenseVector& _lb, const\n      DenseVector& _ub){\n    variables = _lb.size();\n    DASSERT_EQ(variables, _ub.size());\n    lb = _lb;\n    ub = _ub;\n  }\n\n  /**\n   * Default desctuctor. Do nothing.\n   */\n  ~box_constraints(){\n  }\n\n\n  /**\n   * Project a dense point into the constraint space.\n   * \\param[in,out]  point   Point (Dense Vector)\n   *\n   * Given a convex set X, the projection operator is given by\n   *     P(y) = \\std::max(x, o)\n   *\n   */\n  inline void project(DenseVector &point) const {\n    DASSERT_EQ(variables, point.size());\n    for(size_t i=0; i < size_t(point.size()); i++){\n      point(i) = std::min(std::max(point(i), lb(i)), ub(i));\n    }\n  }\n\n  /**\n   * Project a block of a dense point into the constraint space.\n   *\n   * \\param[in,out]  point        A block project the point.\n   * \\param[in]      block_start  Start index of the block\n   * \\param[in]      block_size   Size of the block\n   *\n   * Given a convex set X, the projection operator is given by\n   *     P(y) = \\std::max(x, o)\n   *\n   */\n  inline void project_block(DenseVector &point, const size_t block_start, const\n      size_t block_size) const {\n    DASSERT_GE(variables, block_start + block_size);\n    DASSERT_EQ(block_size, point.size());\n    for(size_t i=0; i < block_size; i++){\n      point(i) = std::min(std::max(point(i),\n                                  lb(block_start + i)), ub(block_start + i));\n    }\n  }\n\n  /**\n   * Boolean function to determine if a dense point is present in a constraint\n   * space.\n   * \\param[in]  point   Point which we are querying.\n   *\n   */\n  inline bool is_satisfied(const DenseVector &point) const {\n    DASSERT_EQ(variables, point.size());\n    for(size_t i=0; i < size_t(point.size()); i++){\n      if( point(i) <= lb(i) - OPTIMIZATION_ZERO ||\n          point(i) >= ub(i) + OPTIMIZATION_ZERO)\n        return false;\n    }\n    return true;\n  }\n\n\n  /**\n   * A measure of the first order optimality conditions.\n   *\n   * \\param[in]  point    Point which we are querying.\n   * \\param[in]  gradient Gradient at that point for a given function\n   *\n   * Use the Cauchy point as a measure of optimality. See Pg 486 of\n   * Nocedal and Wright (Edition 2)\n   *\n   */\n  inline double first_order_optimality_conditions(const DenseVector &point,\n                                        const DenseVector& gradient) const{\n    DASSERT_TRUE(is_satisfied(point));\n    DenseVector proj_gradient = gradient;\n    for(size_t i=0; i < size_t(point.size()); i++){\n      if(point(i) <= OPTIMIZATION_ZERO + lb(i)){\n        proj_gradient(i) = std::min(0.0, gradient(i));\n      } else if (point(i) >= ub(i) - OPTIMIZATION_ZERO){\n        proj_gradient(i) = std::max(0.0, gradient(i));\n      } else {\n        proj_gradient(i) = gradient(i);\n      }\n    }\n    return compute_residual(proj_gradient);\n  }\n\n\n};\n\n\n} // optimization\n} // turicreate\n\n#endif\n", "meta": {"hexsha": "cdb8dfcf90ede2c1dbc3a032d71b484a81596252", "size": 7211, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ml/optimization/constraints-inl.hpp", "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/ml/optimization/constraints-inl.hpp", "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/ml/optimization/constraints-inl.hpp", "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": 26.2218181818, "max_line_length": 86, "alphanum_fraction": 0.614477881, "num_tokens": 1840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5435303765011811}}
{"text": "#ifndef __GIFS_UTIL_HPP\n#define __GIFS_UTIL_HPP\n\n#include <armadillo>\n\nnamespace util{\n  arma::vec center_of_mass(const arma::mat R, const arma::vec m);\n  arma::vec sum_cross(const arma::mat A, const arma::mat B);\n  //  arma::vec net(arma::vec (*op)(const arma::vec &a, const arma::vec &b), const arma::mat A, const arma::mat B);\n\n  double hypot(std::complex<double> a, std::complex<double> b);\n  arma::uword sample_discrete(const arma::vec &p);\n  arma::uvec range(arma::uword a, arma::uword b); //[a, b)\n  arma::uvec range(arma::uword n); // [0, n)\n\n  template <typename T>\n  inline bool approx_equal(T a, T b, T tol=arma::datum::eps){\n    return std::abs(a-b) < tol;\n  };\n}\n\n#endif\n", "meta": {"hexsha": "ae77370bfd509754eb5a919136196a42b16d529f", "size": 684, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gifs_src/util.hpp", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-11T19:48:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T19:48:20.000Z", "max_issues_repo_path": "gifs_src/util.hpp", "max_issues_repo_name": "farajilab/gifs_release", "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gifs_src/util.hpp", "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "avg_line_length": 29.7391304348, "max_line_length": 115, "alphanum_fraction": 0.6637426901, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5434021737566186}}
{"text": "// Copyright 2008-2010 Gordon Woodhull\r\n// Distributed under the Boost Software License, Version 1.0. \r\n// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// mplgraph.cpp : Defines the entry point for the console application.\r\n//\r\n\r\n#include <boost/msm/mpl_graph/incidence_list_graph.hpp>\r\n#include <boost/msm/mpl_graph/mpl_utils.hpp>\r\n\r\nnamespace mpl_graph = boost::msm::mpl_graph;\r\nnamespace mpl_utils = mpl_graph::mpl_utils;\r\nnamespace mpl = boost::mpl;\r\n/* \r\n    test graph:\r\n    A -> B -> C -\\--> D\r\n           \\     |--> E\r\n            \\    \\--> F\r\n             \\-----/\r\n*/           \r\n\r\n// vertices\r\nstruct A{}; struct B{}; struct C{}; struct D{}; struct E{}; struct F{};\r\n\r\n// edges\r\nstruct A_B{}; struct B_C{}; struct C_D{}; struct C_E{}; struct C_F{}; struct B_F{};\r\n\r\ntypedef mpl::vector<mpl::vector<A_B,A,B>,\r\n               mpl::vector<B_C,B,C>,\r\n               mpl::vector<C_D,C,D>,\r\n               mpl::vector<C_E,C,E>,\r\n               mpl::vector<C_F,C,F>,\r\n               mpl::vector<B_F,B,F> >\r\n    some_incidence_list;\r\ntypedef mpl_graph::incidence_list_graph<some_incidence_list> some_graph;\r\n\r\nBOOST_MPL_ASSERT(( boost::is_same<mpl_graph::source<B_C,some_graph>::type, B> ));\r\nBOOST_MPL_ASSERT(( boost::is_same<mpl_graph::source<C_D,some_graph>::type, C> ));\r\n\r\nBOOST_MPL_ASSERT(( boost::is_same<mpl_graph::target<C_D,some_graph>::type, D> ));\r\nBOOST_MPL_ASSERT(( boost::is_same<mpl_graph::target<B_F,some_graph>::type, F> ));\r\n\r\nBOOST_MPL_ASSERT(( mpl_utils::set_equal<mpl_graph::out_edges<C,some_graph>::type, mpl::vector<C_D,C_E,C_F> > ));\r\nBOOST_MPL_ASSERT(( mpl_utils::set_equal<mpl_graph::out_edges<B,some_graph>::type, mpl::vector<B_F,B_C> > ));\r\n\r\nBOOST_MPL_ASSERT_RELATION( (mpl_graph::out_degree<B,some_graph>::value), ==, 2 );\r\nBOOST_MPL_ASSERT_RELATION( (mpl_graph::out_degree<C,some_graph>::value), ==, 3 );\r\n\r\nBOOST_MPL_ASSERT(( mpl_utils::set_equal<mpl_graph::in_edges<C,some_graph>::type, mpl::vector<B_C> > ));\r\nBOOST_MPL_ASSERT(( mpl_utils::set_equal<mpl_graph::in_edges<F,some_graph>::type, mpl::vector<C_F,B_F> > ));\r\n\r\nBOOST_MPL_ASSERT_RELATION( (mpl_graph::in_degree<A,some_graph>::value), ==, 0 );\r\nBOOST_MPL_ASSERT_RELATION( (mpl_graph::in_degree<F,some_graph>::value), ==, 2 );\r\n\r\nBOOST_MPL_ASSERT_RELATION( (mpl_graph::degree<A,some_graph>::value), ==, 1 );\r\nBOOST_MPL_ASSERT_RELATION( (mpl_graph::degree<C,some_graph>::value), ==, 4 );\r\n\r\nBOOST_MPL_ASSERT(( mpl_utils::set_equal<mpl_graph::adjacent_vertices<A,some_graph>::type, mpl::vector<B> > ));\r\nBOOST_MPL_ASSERT(( mpl_utils::set_equal<mpl_graph::adjacent_vertices<C,some_graph>::type, mpl::vector<D,E,F> > ));\r\n\r\nBOOST_MPL_ASSERT(( mpl_utils::set_equal<mpl_graph::vertices<some_graph>::type, mpl::vector<A,B,C,D,E,F> > ));\r\n\r\nBOOST_MPL_ASSERT_RELATION( mpl_graph::num_vertices<some_graph>::value, ==, 6 );\r\n\r\nBOOST_MPL_ASSERT_RELATION( mpl_graph::num_edges<some_graph>::value, ==, 6 );\r\n\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "784d36950f2140a1d0c832bddeed0070d5d026ea", "size": 2995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/msm/example/mpl_graph/incidence_list_graph.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/msm/example/mpl_graph/incidence_list_graph.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/msm/example/mpl_graph/incidence_list_graph.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.0273972603, "max_line_length": 115, "alphanum_fraction": 0.6724540902, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5434021609867269}}
{"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_conjugate_gradient.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 solver_type, 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  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>(1.0);\n\n  solver_type S;\n\n  real_type epsilon = boost::numeric_cast<real_type>(10e-10);\n  size_t max_iterations = 100;\n  size_t iterations;\n\n  S(A,x,b, max_iterations, epsilon, iterations);\n\n  // Test for convergence\n  BOOST_CHECK( iterations < max_iterations );\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\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_conjugate_gradient);\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  typedef OpenTissue::math::big::ConjugateGradientFunctor solver_type;\n\n  {\n    matrix_type A;\n    vector_type x,b;\n    solver_type S;\n    BOOST_CHECK_THROW( S(A,x,b), std::invalid_argument );\n  }\n  {\n    matrix_type A;\n    vector_type x,b;\n    A.resize(4,4,false);\n    solver_type S;\n    BOOST_CHECK_THROW( S(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    solver_type S;\n    BOOST_CHECK_THROW( S(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    solver_type S;\n    BOOST_CHECK_THROW( S(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    solver_type S;\n    BOOST_CHECK_NO_THROW( S(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    solver_type S;\n    BOOST_CHECK_THROW( S(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    solver_type S;\n    BOOST_CHECK_THROW( S(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    solver_type S;\n    BOOST_CHECK_THROW( S(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    solver_type S;\n    BOOST_CHECK_THROW( S(A,x,b), std::invalid_argument );\n  }\n  {\n    matrix_type A;\n    vector_type x,b;\n    A.resize(4,5,false);\n    x.resize(5,false);\n    b.resize(4,false);\n    solver_type S;\n    BOOST_CHECK_THROW( S(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  typedef OpenTissue::math::big::ConjugateGradientFunctor solver_type;\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<solver_type>(A,x,b,y);\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "0b38bcca73398f56be9e26486a9c23eb18f4e760", "size": 4715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/big/conjugate_gradient/src/unit_conjugate_gradient.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/conjugate_gradient/src/unit_conjugate_gradient.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/conjugate_gradient/src/unit_conjugate_gradient.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.575, "max_line_length": 96, "alphanum_fraction": 0.6579003181, "num_tokens": 1306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5434021524734656}}
{"text": "//  (C) Copyright Eric Niebler, Olivier Gygi 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Test case for p_square_cumul_dist.hpp\n\n#include <cmath>\n#include <boost/random.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/numeric/functional/vector.hpp>\n#include <boost/accumulators/numeric/functional/complex.hpp>\n#include <boost/accumulators/numeric/functional/valarray.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/p_square_cumul_dist.hpp>\n#include <sstream>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace boost::accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// erf() not known by VC++ compiler!\n// my_erf() computes error function by numerically integrating with trapezoidal rule\n//\ndouble my_erf(double const& x, int const& n = 1000)\n{\n    double sum = 0.;\n    double delta = x/n;\n    for (int i = 1; i < n; ++i)\n        sum += std::exp(-i*i*delta*delta) * delta;\n    sum += 0.5 * delta * (1. + std::exp(-x*x));\n    return sum * 2. / std::sqrt(3.141592653);\n}\n\ntypedef accumulator_set<double, stats<tag::p_square_cumulative_distribution> > accumulator_t;\ntypedef iterator_range<std::vector<std::pair<double, double> >::iterator > histogram_type;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    // tolerance in %\n    double epsilon = 3;\n\n    accumulator_t acc(p_square_cumulative_distribution_num_cells = 100);\n\n    // two random number generators\n    boost::lagged_fibonacci607 rng;\n    boost::normal_distribution<> mean_sigma(0,1);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal(rng, mean_sigma);\n\n    for (std::size_t i=0; i<1000000; ++i)\n    {\n        acc(normal());\n    }\n\n    histogram_type histogram = p_square_cumulative_distribution(acc);\n\n    for (std::size_t i = 0; i < histogram.size(); ++i)\n    {\n        // problem with small results: epsilon is relative (in percent), not absolute!\n        if ( histogram[i].second > 0.001 )\n            BOOST_CHECK_CLOSE( 0.5 * (1.0 + my_erf( histogram[i].first / std::sqrt(2.0) )), histogram[i].second, epsilon );\n    }\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// test_persistency\n//\nvoid test_persistency()\n{\n    // \"persistent\" storage\n    std::stringstream ss;\n    // tolerance in %\n    double epsilon = 3;\n    {\n        accumulator_t acc(p_square_cumulative_distribution_num_cells = 100);\n\n        // two random number generators\n        boost::lagged_fibonacci607 rng;\n        boost::normal_distribution<> mean_sigma(0,1);\n        boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal(rng, mean_sigma);\n\n        for (std::size_t i=0; i<1000000; ++i)\n        {\n            acc(normal());\n        }\n\n        histogram_type histogram = p_square_cumulative_distribution(acc);\n\n        BOOST_CHECK_CLOSE(0.5 * (1.0 + my_erf(histogram[25].first / std::sqrt(2.0))), histogram[25].second, epsilon);\n        BOOST_CHECK_CLOSE(0.5 * (1.0 + my_erf(histogram[50].first / std::sqrt(2.0))), histogram[50].second, epsilon);\n        BOOST_CHECK_CLOSE(0.5 * (1.0 + my_erf(histogram[75].first / std::sqrt(2.0))), histogram[75].second, epsilon);\n        boost::archive::text_oarchive oa(ss);\n        acc.serialize(oa, 0);\n    }\n    accumulator_t acc(p_square_cumulative_distribution_num_cells = 100);\n    boost::archive::text_iarchive ia(ss);\n    acc.serialize(ia, 0);\n    histogram_type histogram = p_square_cumulative_distribution(acc);\n    BOOST_CHECK_CLOSE(0.5 * (1.0 + my_erf(histogram[25].first / std::sqrt(2.0))), histogram[25].second, epsilon);\n    BOOST_CHECK_CLOSE(0.5 * (1.0 + my_erf(histogram[50].first / std::sqrt(2.0))), histogram[50].second, epsilon);\n    BOOST_CHECK_CLOSE(0.5 * (1.0 + my_erf(histogram[75].first / std::sqrt(2.0))), histogram[75].second, epsilon);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"p_square_cumulative_distribution test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n    test->add(BOOST_TEST_CASE(&test_persistency));\n\n    return test;\n}\n\n", "meta": {"hexsha": "33e8109ab40c03f45cf911dbcb0973522904ad0e", "size": 4668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/accumulators/test/p_square_cumul_dist.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/accumulators/test/p_square_cumul_dist.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/accumulators/test/p_square_cumul_dist.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": 37.344, "max_line_length": 123, "alphanum_fraction": 0.6446015424, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5433764695101709}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n#include <iostream>\n\n#include <algorithms/metrics.hpp>\n#include <graphblas/graphblas.hpp>\n\nusing namespace grb;\nusing namespace algorithms;\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE metrics_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n//****************************************************************************\n\nstatic std::vector<double> gr={0,1,1,2,2,2,2,3,3,3,3,4,4,4,5,6,6,6,8,8};\nstatic std::vector<double> gc={3,3,6,4,5,6,8,0,1,4,6,2,3,8,2,1,2,3,2,4};\nstatic std::vector<double> gv(gr.size(), 1);\n\n//static Matrix<double, DirectedMatrixTag> G_tn_answer(\n//    {{2, 2, 3, 1, 2, 4, 2, -, 3},\n//     {2, 2, 2, 1, 2, 3, 1, -, 3},\n//     {3, 2, 2, 2, 1, 1, 1, -, 1},\n//     {1, 1, 2, 2, 1, 3, 1, -, 2},\n//     {2, 2, 1, 1, 2, 2, 2, -, 1},\n//     {4, 3, 1, 3, 2, 2, 2, -, 2},\n//     {2, 1, 1, 1, 2, 2, 2, -, 2},\n//     {-, -, -, -, -, -, -, -, -},\n//     {3, 3, 1, 2, 1, 2, 2, -, 2}},\n//    INF);\n\nstatic std::vector<double> tr={0,0,1,1,2,2,2,2,3,3,4,4};\nstatic std::vector<double> tc={1,2,0,2,0,1,3,4,2,4,2,3};\nstatic std::vector<double> tv(tr.size(), 1);\n\n//static Matrix<double, DirectedMatrixTag> test5x5(\n//    {{-, 1, 1, -, -},\n//     {1, -, 1, -, -},\n//     {1, 1, -, 1, 1},\n//     {-, -, 1, -, 1},\n//     {-, -, 1, 1, -}},\n//    INF);\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(metrics_test_in_degree)\n{\n    Matrix<double, DirectedMatrixTag> G_tn(9,9);\n    G_tn.build(gr.begin(), gc.begin(), gv.begin(), gv.size());\n    IndexType result = vertex_in_degree(G_tn, 1);\n    BOOST_CHECK_EQUAL(result, 2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(metrics_test_out_degree)\n{\n    Matrix<double, DirectedMatrixTag> G_tn(9,9);\n    G_tn.build(gr.begin(), gc.begin(), gv.begin(), gv.size());\n    IndexType result = vertex_out_degree(G_tn, 2);\n    BOOST_CHECK_EQUAL(result, 4);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(metrics_test_vertex_degree)\n{\n    Matrix<double, DirectedMatrixTag> G_tn(9,9);\n    G_tn.build(gr.begin(), gc.begin(), gv.begin(), gv.size());\n    IndexType result = vertex_degree(G_tn, 0);\n    BOOST_CHECK_EQUAL(result, 2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(metrics_test_graph_distance)\n{\n    Matrix<double, DirectedMatrixTag> test5x5(5,5);\n    test5x5.build(tr.begin(), tc.begin(), tv.begin(), tv.size());\n    Vector<double> result(5);\n\n    graph_distance(test5x5, 2, result);\n\n    //Matrix<double, DirectedMatrixTag> answer(\n    //     {1, 1, 0, 1, 1},\n    //    INF);\n    std::vector<double> ac={0,1,2,3,4};\n    std::vector<double> av={1, 1, 0, 1, 1};\n    Vector<double> answer(5);\n    answer.build(ac.begin(), av.begin(), av.size());\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(metrics_test_graph_distance_matrix)\n{\n    Matrix<double, DirectedMatrixTag> test5x5(5,5);\n    test5x5.build(tr.begin(), tc.begin(), tv.begin(), tv.size());\n    Matrix<double, DirectedMatrixTag> result(5,5);\n\n    graph_distance_matrix(test5x5, result);\n\n    //Matrix<double, DirectedMatrixTag> answer(\n    //    {{0, 1, 1, 2, 2},\n    //     {1, 0, 1, 2, 2},\n    //     {1, 1, 0, 1, 1},\n    //     {2, 2, 1, 0, 1},\n    //     {2, 2, 1, 1, 0}},\n    //    INF);\n\n    std::vector<double> ar={0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4};\n    std::vector<double> ac={0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4};\n    std::vector<double> av={0, 1, 1, 2, 2,\n                            1, 0, 1, 2, 2,\n                            1, 1, 0, 1, 1,\n                            2, 2, 1, 0, 1,\n                            2, 2, 1, 1, 0};\n    Matrix<double, DirectedMatrixTag> answer(5,5);\n    answer.build(ar.begin(), ac.begin(), av.begin(), av.size());\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(metrics_test_graph_eccentricity)\n{\n    Matrix<double, DirectedMatrixTag> test5x5(5,5);\n    test5x5.build(tr.begin(), tc.begin(), tv.begin(), tv.size());\n    double result = vertex_eccentricity(test5x5, 2);\n    BOOST_CHECK_EQUAL(result, 1);\n    result = vertex_eccentricity(test5x5, 1);\n    BOOST_CHECK_EQUAL(result, 2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(metrics_test_graph_radius)\n{\n    Matrix<double, DirectedMatrixTag> test5x5(5,5);\n    test5x5.build(tr.begin(), tc.begin(), tv.begin(), tv.size());\n    double result = graph_radius(test5x5);\n    BOOST_CHECK_EQUAL(result, 1);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(metrics_test_graph_diameter)\n{\n    Matrix<double, DirectedMatrixTag> test5x5(5,5);\n    test5x5.build(tr.begin(), tc.begin(), tv.begin(), tv.size());\n    double result = graph_diameter(test5x5);\n    BOOST_CHECK_EQUAL(result, 2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(metrics_test_closeness_centrality)\n{\n    Matrix<double, DirectedMatrixTag> test5x5(5,5);\n    test5x5.build(tr.begin(), tc.begin(), tv.begin(), tv.size());\n    double result = closeness_centrality(test5x5, 2);\n    BOOST_CHECK_EQUAL(result, 4);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "de9e938567de8a2e61e60e0a8717de7d069839de", "size": 6933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_metrics.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_metrics.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_metrics.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 35.3724489796, "max_line_length": 80, "alphanum_fraction": 0.5678638396, "num_tokens": 2080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.5433764608988978}}
{"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/container/grid/make_spiral_range.hpp>\n#include <fcppt/container/grid/pos.hpp>\n#include <fcppt/math/diff.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\tcontainer_grid_spiral_range\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tint\n\tint_type;\n\n\ttypedef\n\tfcppt::container::grid::pos<\n\t\tint_type,\n\t\t2\n\t>\n\tpos;\n\n\ttypedef\n\tstd::vector<\n\t\tpos\n\t>\n\tpos_vector;\n\n\tpos_vector positions;\n\n\tpositions.reserve(\n\t\t100\n\t);\n\n\tauto const manhattan_distance(\n\t\t[](\n\t\t\tpos const _p1,\n\t\t\tpos const _p2\n\t\t)\n\t\t{\n\t\t\treturn\n\t\t\t\tfcppt::math::diff(\n\t\t\t\t\t_p1.x(),\n\t\t\t\t\t_p2.y()\n\t\t\t\t)\n\t\t\t\t+\n\t\t\t\tfcppt::math::diff(\n\t\t\t\t\t_p1.y(),\n\t\t\t\t\t_p2.y()\n\t\t\t\t);\n\t\t}\n\t);\n\n\tpos const start(\n\t\t5,\n\t\t5\n\t);\n\n\tfor(\n\t\tint_type distance = 0;\n\t\tdistance < 4;\n\t\t++distance\n\t)\n\t{\n\t\tpos_vector result;\n\n\t\tfor(\n\t\t\tauto const cur\n\t\t\t:\n\t\t\tfcppt::container::grid::make_spiral_range(\n\t\t\t\tpos(\n\t\t\t\t\t5,\n\t\t\t\t\t5\n\t\t\t\t),\n\t\t\t\t2\n\t\t\t)\n\t\t)\n\t\t\tresult.push_back(\n\t\t\t\tcur\n\t\t\t);\n\n\t\tBOOST_REQUIRE(\n\t\t\t!result.empty()\n\t\t);\n\n\t\tpos_vector::const_iterator it(\n\t\t\tresult.begin()\n\t\t);\n\n\t\tBOOST_CHECK_EQUAL(\n\t\t\tmanhattan_distance(\n\t\t\t\t*it,\n\t\t\t\tstart\n\t\t\t),\n\t\t\t0\n\t\t);\n\n\t\t++it;\n\n\t\tfor(\n\t\t\tint_type cur = 1;\n\t\t\tcur < distance;\n\t\t\t++cur\n\t\t)\n\t\t{\n\t\t\tint_type const count(\n\t\t\t\tcur * 4\n\t\t\t);\n\n\t\t\tfor(\n\t\t\t\tint_type i = 0;\n\t\t\t\ti < count;\n\t\t\t\t++i\n\t\t\t)\n\t\t\t\tBOOST_CHECK_EQUAL(\n\t\t\t\t\tmanhattan_distance(\n\t\t\t\t\t\t*it++,\n\t\t\t\t\t\tstart\n\t\t\t\t\t),\n\t\t\t\t\tcur\n\t\t\t\t);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "519fffb2a88e173b9a98cf1d90ab307b298132e8", "size": 1902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/container/grid/spiral_range.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/container/grid/spiral_range.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/container/grid/spiral_range.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": 13.5857142857, "max_line_length": 61, "alphanum_fraction": 0.6172450053, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5433764565932613}}
{"text": "#include <boost/math/distributions/binomial.hpp>\n", "meta": {"hexsha": "55e207eded1b3730c3e317a605938947e028d75a", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_binomial.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_binomial.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_binomial.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8163265306, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5433191261623093}}
{"text": "#pragma once\n#include <cmath>\n#include <tuple>\n#include <cstddef>\n#include <utility>\n#include <algorithm>\n#include <functional>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\n#include \"utils/types.hpp\"\n#include \"utils/utils.hpp\"\n#include \"utils/assert.hpp\"\n#include \"utils/comparators.hpp\"\n\nnamespace ample {\n\n    namespace _impl {\n\n        template<typename T>\n        using vector_t = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\n        template<typename T>\n        using matrix_t = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\n        template<typename T>\n        struct solver_type {\n\n            using type = Eigen::EigenSolver<matrix_t<T>>;\n\n        };\n\n        template<typename T>\n        struct solver_type<std::complex<T>> {\n\n            using type = Eigen::ComplexEigenSolver<matrix_t<std::complex<T>>>;\n\n        };\n\n\n        template<typename T>\n        using solver_type_t = typename solver_type<T>::type;\n\n        template<typename T>\n        struct pade_coefficients {\n\n            auto operator()(const types::vector1d_t<T>& c, const size_t& n, const size_t& m) {\n                vector_t<T> b(m);\n                matrix_t<T> A(m, m);\n\n                for (size_t i = 0, ci = n + 1; i < m; ++i, ++ci) {\n                    b(i) = -c[ci];\n\n                    for (size_t j = 0; j < std::min(ci, m); ++j)\n                        A(i, j) = c[ci - j - 1];\n                }\n\n                const vector_t<T> x = A.colPivHouseholderQr().solve(b);\n\n                types::vector1d_t<T> ac(n + 1), bc(m + 1, T(1));\n                for (size_t i = 0; i < n + 1; ++i) {\n                    ac[i] = c[i];\n                    for (size_t j = 0; j < std::min(i, m); ++j)\n                        ac[i] += c[i - j - 1] * x(j);\n                }\n\n                for (size_t i = 0; i < m; ++i)\n                    bc[i + 1] = x(i);\n\n                return std::make_tuple(ac, bc);\n            }\n\n        };\n\n        template<typename T>\n        struct theta_pade_coefficients {\n\n            T theta{};\n\n            auto operator()(const types::vector1d_t<T>& c, const size_t& n, const size_t& m) {\n                utils::dynamic_assert(n == m, \"coefficients: n(\", n, \") must be equal to m(\", m, \") for theta-weighted coefficients\");\n\n                pade_coefficients<T> coefficients{};\n                const auto [a0, b0] = coefficients(c, n - 1, n);\n                      auto [a1, b1] = coefficients(c, n, n);\n\n                const auto theta1 = T(1) - theta;\n                for (size_t i = 0; i < a0.size(); ++i)\n                    a1[i] = a1[i] * theta + a0[i] * theta1;\n\n                a1.back() *= theta;\n\n                for (size_t i = 0; i < b0.size(); ++i)\n                    b1[i] = b1[i] * theta + b0[i] * theta1;\n\n                return std::make_tuple(a1, b1);\n            }\n\n        };\n\n        template<typename T>\n        struct exp_taylor {\n\n            static constexpr auto on = T(1);\n            static constexpr auto tw = T(2);\n            static constexpr auto fo = T(4);\n            static constexpr auto si = T(6);\n\n            auto operator()(const T& value, const size_t& n) {\n                const auto v2 = std::pow(value, 2);\n\n                types::vector1d_t<T> c(n);\n                c[0] = on;\n                c[1] = value /tw;\n\n                for (size_t i = 2, m = 0; i < n; ++i, ++m) {\n                    const auto mm = T(m);\n                    c[i] = (v2 * c[m] - (tw + si * mm + fo * mm * mm) * c[m + 1]) / (fo * (on + mm) * (tw + mm));\n                }\n\n                return c;\n            }\n\n        };\n\n        template<typename T>\n        struct root_taylor {\n\n            auto operator()(const T& value, const size_t& n) {\n                types::vector1d_t<T> c(n, T(0));\n                std::for_each(c.begin() + 1, c.end(), \n                    [&value, p=T(1), i=size_t(0), f=T(1)](auto& x) mutable {\n                        ++i;\n                        x = value * (p *= (T(1.5) - T(i))) / (f *= i);\n                    }\n                );\n\n                return c;\n            }\n\n        };\n\n        template<typename T>\n        struct no_transform {\n\n            auto operator()(types::vector1d_t<T>& p, types::vector1d_t<T>& q) {}\n\n        };\n\n        template<typename T>\n        struct wampe_transform {\n\n            auto operator()(types::vector1d_t<T>& p, types::vector1d_t<T>& q) {\n                for (size_t i = 0; i < p.size(); ++i) {\n                    const auto q2 = T(2) * q[i];\n                    std::tie(p[i], q[i]) = std::make_tuple(-p[i] - q2, p[i] - q2);\n                }\n\n                for (size_t i = p.size(); i < q.size(); ++i) {\n                    const auto q2 = T(-2) * q[i];\n                    p.push_back(q2);\n                    q[i] = q2;\n                }\n            }\n\n        };\n\n        template<typename T>\n        auto get_roots(const types::vector1d_t<T>& c) {\n            const auto n = c.size() - 1;\n            matrix_t<T> A = matrix_t<T>::Zero(n, n);\n\n            for (size_t i = 0; i < n - 1; ++i)\n                A(i + 1, i) = T(1);\n\n            for (size_t i = 0; i < n; ++i)\n                A(0, i) = -c[n - i - 1] / c.back();\n\n            solver_type_t<T> solver;\n            solver.compute(A);\n            const vector_t<T> values = solver.eigenvalues();\n\n            auto result = utils::make_vector_i(n, [&values](const auto& i) { return values(i); });\n            std::sort(result.begin(), result.end(), utils::less<T>{});\n            return result;\n        }\n\n    }// namespace ample::_impl\n\n    template<typename T>\n    class coefficients {\n\n    public:\n\n        using taylor_func_t      = std::function<types::vector1d_t<T>(const T&, const size_t&)>;\n        using transform_func_t   = std::function<void (types::vector1d_t<T>&, types::vector1d_t<T>&)>;\n        using coeficients_func_t = std::function<std::tuple<types::vector1d_t<T>, types::vector1d_t<T>>(const types::vector1d_t<T>&, const size_t&, const size_t&)>;\n\n        coefficients(const size_t& n,\n                     taylor_func_t taylor,\n                     transform_func_t transform,\n                     coeficients_func_t coefficients) : ample::coefficients<T>(n, n, std::move(taylor), std::move(transform), std::move(coefficients)) {}\n\n        coefficients(const size_t& n, const size_t& m,\n                     taylor_func_t taylor,\n                     transform_func_t transform,\n                     coeficients_func_t coefficients) : _n(n), _m(m), _taylor(std::move(taylor)), _transform(std::move(transform)), _coefficients(std::move(coefficients)) {\n            utils::dynamic_assert(n > 0,  \"coefficients: n(\", n, \") must be positive\");\n            utils::dynamic_assert(n <= m, \"coefficients: n(\", n, \") must be less or equal to m(\", m, \")\");\n        }\n\n        auto get(const T& value) const {\n            const auto tc = _taylor(value, _n + _m + 1);\n            auto [np, dp] = _coefficients(tc, _n, _m);\n\n            _transform(np, dp);\n\n            const auto nr = _impl::get_roots<T>(np);\n            const auto dr = _impl::get_roots<T>(dp);\n\n            types::vector1d_t<size_t> ix(_m);\n            std::iota(ix.begin(), ix.end(), size_t(0));\n\n            auto a = types::vector1d_t<T>(_m);\n            for (size_t i = 0; i < _m; ++i) {\n                const auto p = std::accumulate(nr.begin(), nr.end(), np.back(), [&x=dr[i]](const auto& a, const auto& x0) { return a * (x - x0); });\n                const auto q = std::accumulate(ix.begin(), ix.end(), dp.back(),\n                                               [&x=dr[i], &i, &dr](const auto& a, const auto& j) {\n                                                   return i == j ? a : a * (x - dr[j]);\n                                               }\n                );\n\n                a[i] = -p / q / dr[i];\n            }\n\n            auto a0 = np.front() / dp.front() - std::accumulate(a.begin(), a.end(), T(0));\n            return std::make_tuple(a0, std::move(a), utils::make_vector(dr, [](const auto& x) { return -T(1) / x; }));\n        }\n\n        [[nodiscard]] auto nc() const {\n            return _m;\n        }\n\n    private:\n\n        size_t _n{}, _m{};\n        taylor_func_t _taylor;\n        transform_func_t _transform;\n        coeficients_func_t _coefficients;\n\n    };\n\n    template<typename T>\n    auto ssp_coefficients(const size_t& n, const size_t& m) {\n        return coefficients<T>(n, m, _impl::exp_taylor<T>{}, _impl::no_transform<T>{}, _impl::pade_coefficients<T>{});\n    }\n\n    template<typename T>\n    auto ssp_coefficients(const size_t& n) {\n        return ssp_coefficients<T>(n, n);\n    }\n\n    template<typename T>\n    auto theta_ssp_coefficients(const size_t& n, const T& theta) {\n        return coefficients<T>(n, n, _impl::exp_taylor<T>{}, _impl::no_transform<T>{}, _impl::theta_pade_coefficients<T>{ theta });\n    }\n\n    template<typename T>\n    auto wampe_coefficients(const size_t& n, const size_t& m) {\n        return coefficients<T>(n, m, _impl::root_taylor<T>{}, _impl::wampe_transform<T>{}, _impl::pade_coefficients<T>{});\n    }\n\n    template<typename T>\n    auto wampe_coefficients(const size_t& n) {\n        return wampe_coefficients<T>(n, n);\n    }\n\n    template<typename T>\n    auto theta_wampe_coefficients(const size_t& n, const T& theta) {\n        return coefficients<T>(n, n, _impl::root_taylor<T>{}, _impl::wampe_transform<T>{}, _impl::theta_pade_coefficients<T>{ theta });\n    }\n\n}// namespace ample\n", "meta": {"hexsha": "de0f158cbadbf10f21df964b669695b1cbfb7a24", "size": 9411, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/coefficients.hpp", "max_stars_repo_name": "GoldFeniks/Acoustic", "max_stars_repo_head_hexsha": "44122f7a1d815aeeb4f06b60342c8db932a806f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-12-06T21:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-05T11:11:12.000Z", "max_issues_repo_path": "include/coefficients.hpp", "max_issues_repo_name": "GoldFeniks/Acoustic", "max_issues_repo_head_hexsha": "44122f7a1d815aeeb4f06b60342c8db932a806f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-01-31T14:09:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-07T05:48:05.000Z", "max_forks_repo_path": "include/coefficients.hpp", "max_forks_repo_name": "GoldFeniks/Ample", "max_forks_repo_head_hexsha": "44122f7a1d815aeeb4f06b60342c8db932a806f3", "max_forks_repo_licenses": ["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.1373239437, "max_line_length": 172, "alphanum_fraction": 0.4836892998, "num_tokens": 2482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5433191215562229}}
{"text": "#pragma once\n#include<complex>\n#include<vector>\n#include\"mkl_lapacke.h\"\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n\nnamespace Many_Body{\n  struct TriDiagMat{\n    TriDiagMat(const Eigen::VectorXd& diagel, const Eigen::VectorXd& offDiag): diagel(diagel), offDiag(offDiag){}\n    Eigen::VectorXd diagel;\n    Eigen::VectorXd offDiag;\n    auto dData(){return diagel.data();}\n      auto offData(){return offDiag.data();}\n  };\n\n\n  void diag(    Many_Body::TriDiagMat& tri, Eigen::MatrixXd& z, Eigen::VectorXd& ev)\n  {\n    MKL_INT N= ev.size();\n        MKL_INT info= LAPACKE_dstedc(LAPACK_COL_MAJOR, 'I', N, tri.dData(), tri.offData(), z.data(), N);\n    if(info!=0)\n      {\n  \tstd::cout << \" diagonalization failed\" << '\\n';\n      }\n    ev=tri.diagel;\n\n\n\n   }\n  template<typename Vector, typename Matrix>\n  struct threeLVec\n  {\n    threeLVec(size_t dim, const Matrix& A): A(A), beta(1), alpha(0) {\n      Vector vecOne=Eigen::VectorXcd::Zero(dim);\n    Vector vecTwo=Eigen::VectorXcd::Zero(dim);\n    Vector vecThree=Eigen::VectorXcd::Zero(dim);\n    }\n    const Matrix& A;\n    double beta{1};\n    double alpha{};\n    Vector vecOne;\n    Vector vecTwo;\n    Vector vecThree;\n\nvoid iterate()\n    {\n      \tvecThree=A*vecTwo;\t\n\t//\tstd::complex<double> c=qk.adjoint()*qMiddle;\n\tstd::complex<double> c=(vecTwo).adjoint()*vecThree;\n\n      \talpha=real(c);\n\n\t//\tEigen::VectorXcd  rk=qMiddle - alpha*qk -beta*qkmin;\n\n\tEigen::VectorXcd  rk=vecThree - alpha*vecTwo -beta*vecOne;\n\t\n     \tbeta=rk.norm();\t\t\n\tvecOne=vecTwo;\n\n\t//qk=rk/rk.norm();\n\tvecTwo=rk/rk.norm();\n    }\n    void lastIterate()\n    {\n      \tvecThree=A*vecTwo;\t\n\n\tstd::complex<double> c=(vecTwo).adjoint()*vecThree;\n\n      \talpha=real(c);\n\n\n    }\n  \n    \n \n  };\n  template<typename Matrix>\n  TriDiagMat Lanczos3Vec(Matrix& A, Eigen::VectorXcd& state, const size_t iterations)\n  {\n    using namespace Eigen::internal;\n    using namespace Eigen;\n    \tassert(std::abs(state.norm() -1.) < Many_Body::err);\n\n\n\n\tthreeLVec< Eigen::VectorXcd, Matrix>  threeLanczVec(A.rows(), A);\n\tthreeLanczVec.vecTwo=state;\n        long double beta=1;\n\n    double alpha(0);\n    Eigen::VectorXd bandTdiag(iterations);\n        Eigen::VectorXd bandTOff(iterations-1);\n    bandTdiag.setZero();\n        bandTOff.setZero();\n\n    Eigen::VectorXcd qk=state;\n    Eigen::VectorXcd qkmin(A.rows());\n    qkmin.setZero();\n    threeLanczVec.vecOne=qkmin;\n    size_t dim=0;\n\n     for (size_t k = 1; k < iterations; ++k)\n       {\n\t threeLanczVec.iterate();\n\n      \talpha=threeLanczVec.alpha;\n     \tbeta=threeLanczVec.beta;\n\n\tbandTdiag(k-1)=alpha;\n     \tbandTOff(k-1)=beta;\n     \t \n\t  \t if( std::abs(beta)<0.00001)\n     \t   {\n\t\t \n    \t\t  bandTdiag.resize( k);\n    \t\t  bandTOff.resize( k-1);\n\n\t\t \n     \t    break;\n     \t   }\n    \t dim=k;   \n    \t }\n     \n     \n    \n\n    \n     {\n\n       threeLanczVec.lastIterate();\n       bandTdiag(dim)=threeLanczVec.alpha;\n\n    }\n\n\n\n\n\t  \n\t  \n    TriDiagMat T(bandTdiag, bandTOff);\n    return T;\n  }\n    template<typename Matrix>\n  TriDiagMat Lanczos(Matrix& A, Eigen::VectorXcd& state, const size_t iterations, Eigen::MatrixXcd& Q)\n  {\n    using namespace Eigen::internal;\n    using namespace Eigen;\n    \tassert(std::abs(state.norm() -1.) < Many_Body::err);\n\n\tQ.setZero();\n\tQ.col(0)=state;\n        long double beta=1;\n    double alpha(0);\n     Eigen::VectorXd bandTdiag(iterations);\n         Eigen::VectorXd bandTOff(iterations-1);\n\t   bandTdiag.setZero();\n        bandTOff.setZero();\n\n    Eigen::VectorXcd qk=state;\n    Eigen::VectorXcd qkmin(A.rows());\n    qkmin.setZero();\n    size_t dim=0;\n for (size_t k = 1; k < iterations; ++k)\n        {\n\t  Eigen::VectorXcd qMiddle=A*qk;\n\t\t\n\t    \tstd::complex<double> c=qk.adjoint()*qMiddle;\n\t     \talpha=real(c);\n\n      \tEigen::VectorXcd  rk=qMiddle - alpha*qk -beta*qkmin;\n     \tbeta=rk.norm();\n\n\tbandTdiag(k-1)=alpha;\n     \tbandTOff(k-1)=beta;\n\n      \tqkmin=qk;\n\tqk=rk/rk.norm();\n\t     Q.col(k)=qk;\n     \t \n\t  \t if( std::abs(beta)<0.0001)\n     \t   {\n\t     Eigen::MatrixXcd W=Q;\n\t           Q.resize(A.rows(), k);\n\t\t for (size_t i = 0; i < k; ++i)\n\t\t   {\n\t\t     Q.col(i)=W.col(i);\n\t\t     \n\t\t   }\n    \t\t  bandTdiag.resize( k);\n    \t\t  bandTOff.resize( k-1);\n\t\t  break;\n     \t   }\n\tdim=k;\n             }\n     {\n       Eigen::VectorXcd qMiddle=A*qk;\n       \tstd::complex<double> c=qk.adjoint()*qMiddle;\n     \talpha=real(c);\n\n       \t\t        bandTdiag(dim)=(alpha);\n\n     }\n     //             assert(std::abs( (Q.adjoint()*Q).sum() -(dim+1)) < Many_Body::err);     \n     std::cout<<\"Qdag Q sum \"<< (Q.adjoint()*Q).sum()<<std::endl;\n\t  \n\t  \n     TriDiagMat T(bandTdiag, bandTOff);\n    return T;\n  }\n\n  \n  template<typename Vector, typename Vector2, typename Matrix>\n  auto lanczTrafo(const  Vector & state, const Vector2 & iniState, size_t iteration, const Matrix& A)\n    ->Eigen::VectorXcd\n  {\n    Many_Body::threeLVec< Eigen::VectorXcd, Matrix>  threeLanczVec(A.rows(), A);\n    Eigen::VectorXcd newVec=Eigen::VectorXcd::Zero(A.rows());\n    threeLanczVec.vecTwo=iniState;\n    Eigen::VectorXcd qkmin(A.rows());\n    qkmin.setZero();\n    threeLanczVec.vecOne=qkmin;\n    for(size_t i=0; i<iteration; i++)\n      {\n\tnewVec+=threeLanczVec.vecTwo*state(i);\n\tthreeLanczVec.iterate();\n\t\n      }\n    \n    return newVec;\n  }\n  \n       \n\n\n};\n\n", "meta": {"hexsha": "e78165d3af7810d360fbb9e6f351d3bcfba7063e", "size": 5208, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lanzcos.hpp", "max_stars_repo_name": "jansendavid/many-body-lib", "max_stars_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_stars_repo_licenses": ["MIT"], "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/lanzcos.hpp", "max_issues_repo_name": "jansendavid/many-body-lib", "max_issues_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_issues_repo_licenses": ["MIT"], "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/lanzcos.hpp", "max_forks_repo_name": "jansendavid/many-body-lib", "max_forks_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_forks_repo_licenses": ["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.8823529412, "max_line_length": 113, "alphanum_fraction": 0.5933179724, "num_tokens": 1598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5433191215562228}}
{"text": "\n#include \"friendly_graph.h\"\n\n#include \"../../Constants.h\"\n#include \"../../navtypes.h\"\n#include \"../../Util.h\"\n\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\nusing namespace navtypes;\nusing util::toPose;\nusing util::toTransform;\nusing util::toTransformRotateFirst;\n\nnamespace filters::pose_graph {\n\nconstexpr int LM_SIZE = 2;\nconstexpr int POSE_SIZE = 3;\n\nFriendlyGraph::FriendlyGraph(int num_landmarks, int max_num_poses, float camera_std,\n\t\t\t\t\t\t\t float gps_xy_std, float wheel_noise_rate)\n\t: _num_landmarks(num_landmarks), _max_pose_id(0), _min_pose_id(0),\n\t  _max_num_poses(max_num_poses), _current_guess(LM_SIZE * num_landmarks),\n\t  _landmark_factor_ids(num_landmarks), _odom_cov_inv(), _sensor_cov_inv(), _gps_cov_inv(),\n\t  _graph() {\n\tcovariance<3> odom_cov = covariance<3>::Zero();\n\t// TODO what are the right numbers here? Should y be correlated with theta?\n\todom_cov << wheel_noise_rate, 0, 0, 0, wheel_noise_rate, wheel_noise_rate / 2.0, 0,\n\t\twheel_noise_rate / 2.0, wheel_noise_rate;\n\t_odom_cov_inv = odom_cov.inverse();\n\tcovariance<2> sensor_cov = covariance<2>::Zero();\n\tsensor_cov << camera_std * camera_std, 0, 0, camera_std * camera_std;\n\t_sensor_cov_inv = sensor_cov.inverse();\n\t// GPS has no heading measurements\n\t// which we represent using a large covariance\n\tcovariance<3> gps_cov = covariance<3>::Zero();\n\tgps_cov << gps_xy_std * gps_xy_std, 0, 0, 0, gps_xy_std * gps_xy_std, 0, 0, 0, 50.0 * 50.0;\n\t_gps_cov_inv = gps_cov.inverse();\n\tfor (int id = 0; id < num_landmarks; id++) {\n\t\t_landmark_factor_ids[id] = -1;\n\t}\n}\n\nint FriendlyGraph::numPoses() {\n\treturn _max_pose_id - _min_pose_id;\n}\n\nint FriendlyGraph::nonincrementingPoseIdx(int pose_id) {\n\treturn _num_landmarks * LM_SIZE + (pose_id - _min_pose_id) * POSE_SIZE;\n}\n\nvoid FriendlyGraph::incrementNumPoses() {\n\t_max_pose_id++;\n\t_current_guess.conservativeResize(nonincrementingPoseIdx(_max_pose_id));\n}\n\nint FriendlyGraph::poseIdx(int pose_id) {\n\tif (pose_id == _max_pose_id) {\n\t\tincrementNumPoses();\n\t} else if (pose_id > _max_pose_id) {\n\t\tprintf(\"Error: skipped a pose id (given %d, current %d)\\n\", pose_id, _max_pose_id);\n\t\tthrow 1;\n\t}\n\treturn nonincrementingPoseIdx(pose_id);\n}\n\nint FriendlyGraph::landmarkIdx(int lm_id) {\n\tassert(lm_id < _num_landmarks);\n\treturn lm_id * LM_SIZE;\n}\n\nvoid FriendlyGraph::trimToMaxNumPoses() {\n\tif (numPoses() > _max_num_poses) {\n\t\tif (numPoses() != _max_num_poses + 1) {\n\t\t\tprintf(\"Error: skipped a trim\\n\");\n\t\t\tthrow 2;\n\t\t}\n\t\thessian sol_cov = _graph.covariance();\n\t\tint base_idx = poseIdx(_min_pose_id + 1);\n\t\tmeasurement<3> first_pose = getPoseEstimate(_min_pose_id + 1);\n\t\tcovariance<3> first_pose_cov = sol_cov.block(base_idx, base_idx, POSE_SIZE, POSE_SIZE);\n\t\tvalues old_guess = _current_guess;\n\t\t// printf(\"Trimming. Current uncertainty on base pose: %f %f %f\\n\",\n\t\t//     sqrt(first_pose_cov(0,0)), sqrt(first_pose_cov(1,1)),\n\t\t//     sqrt(first_pose_cov(2,2)));\n\t\t_graph.shiftIndices(POSE_SIZE, poseIdx(_min_pose_id));\n\t\t_min_pose_id += 1;\n\t\t_current_guess.conservativeResize(nonincrementingPoseIdx(_max_pose_id));\n\t\t_current_guess.block(poseIdx(_min_pose_id), 0, _max_num_poses * POSE_SIZE, 1) =\n\t\t\told_guess.block(poseIdx(_min_pose_id + 1), 0, _max_num_poses * POSE_SIZE, 1);\n\t\taddPosePrior(_min_pose_id, toTransform(first_pose), first_pose_cov);\n\t}\n}\n\npose_t FriendlyGraph::getPoseEstimate(int pose_id) {\n\tassert(\"bad pose id\" && pose_id >= _min_pose_id && pose_id < _max_pose_id);\n\tpose_t p = _current_guess.block(poseIdx(pose_id), 0, POSE_SIZE, 1);\n\treturn p;\n}\n\nvoid FriendlyGraph::addGPSMeasurement(int pose_id, const transform_t& gps_tf) {\n\tpose_t gps = toPose(gps_tf, 0); // heading doesn't matter\n\t_graph.add(new OdomFactor2D(poseIdx(pose_id), -1, _gps_cov_inv, gps));\n}\n\nvoid FriendlyGraph::addOdomMeasurement(int pose2_id, int pose1_id, const transform_t& pose2_tf,\n\t\t\t\t\t\t\t\t\t   const transform_t& pose1_tf) {\n\ttransform_t rel_tf = pose2_tf * pose1_tf.inverse();\n\tpose_t diff = toPose(rel_tf, 0.0);\n\tfloat lin_dist = diff(0);\n\t// Turning introduces more noise than going in a straight line\n\tfloat ang_dist = Constants::WHEEL_BASE * diff(2) * 4;\n\tfloat noise_distance_sq = lin_dist * lin_dist + ang_dist * ang_dist;\n\t_graph.add(new OdomFactor2D(poseIdx(pose2_id), poseIdx(pose1_id),\n\t\t\t\t\t\t\t\t_odom_cov_inv / noise_distance_sq, diff));\n\tpose_t pose1_est = getPoseEstimate(pose1_id);\n\ttransform_t new_pose_tf = rel_tf * toTransform(pose1_est);\n\tpose_t pose2_est = toPose(new_pose_tf, pose1_est(2));\n\t_current_guess.block(poseIdx(pose2_id), 0, POSE_SIZE, 1) = pose2_est;\n}\n\nvoid FriendlyGraph::addLandmarkMeasurement(int pose_id, int lm_id, const point_t& bearing,\n\t\t\t\t\t\t\t\t\t\t   bool overwrite) {\n\tmeasurement<2> lm = measurement<2>{bearing(0), bearing(1)};\n\tif (overwrite && _landmark_factor_ids[lm_id] != -1) {\n\t\t_graph.deleteFactor(_landmark_factor_ids[lm_id]);\n\t}\n\tint id = _graph.add(\n\t\tnew LandmarkFactor2D(landmarkIdx(lm_id), poseIdx(pose_id), _sensor_cov_inv, lm));\n\t_landmark_factor_ids[lm_id] = id;\n}\n\nvoid FriendlyGraph::addLandmarkPrior(int lm_id, point_t location, double xy_std) {\n\tcovariance<2> prior_cov = covariance<2>::Zero();\n\tprior_cov << xy_std * xy_std, 0, 0, xy_std * xy_std;\n\tcovariance<2> prior_cov_inv = prior_cov.inverse();\n\tmeasurement<2> lm = measurement<2>{location(0), location(1)};\n\t_graph.add(new LandmarkFactor2D(landmarkIdx(lm_id), -1, prior_cov_inv, lm));\n\t_current_guess.block(landmarkIdx(lm_id), 0, LM_SIZE, 1) = lm;\n}\n\nvoid FriendlyGraph::addPosePrior(int pose_id, const transform_t& pose_tf, covariance<3>& cov) {\n\tcovariance<3> prior_cov_inv = cov.inverse();\n\tpose_t pose = toPose(pose_tf, 0);\n\t_graph.add(new OdomFactor2D(poseIdx(pose_id), -1, prior_cov_inv, pose));\n\t_current_guess.block(poseIdx(pose_id), 0, POSE_SIZE, 1) = pose;\n}\n\n// Guarantee: after solve(), _graph.solution() == _current_guess\nvoid FriendlyGraph::solve() {\n\ttrimToMaxNumPoses();\n\t_graph.solve(_current_guess, 0.99);\n\t_current_guess = _graph.solution();\n}\n\npoints_t FriendlyGraph::getLandmarkLocations() {\n\tpoints_t lms({});\n\tfor (int i = 0; i < _num_landmarks * LM_SIZE; i += LM_SIZE) {\n\t\tpoint_t lm({0, 0, 1});\n\t\tlm.topRows(LM_SIZE) = _current_guess.block(i, 0, LM_SIZE, 1);\n\t\tlms.push_back(lm);\n\t}\n\treturn lms;\n}\n\ntrajectory_t FriendlyGraph::getSmoothedTrajectory() {\n\tconst values& x = _current_guess;\n\ttrajectory_t tfs({});\n\tfor (int i = poseIdx(_min_pose_id); i < nonincrementingPoseIdx(_max_pose_id);\n\t\t i += POSE_SIZE) {\n\t\tif (POSE_SIZE == 3) { // 2D\n\t\t\ttfs.push_back(toTransformRotateFirst(0, 0, x(i + 2)) *\n\t\t\t\t\t\t  toTransformRotateFirst(x(i), x(i + 1), 0));\n\t\t} else { // 1D\n\t\t\ttfs.push_back(toTransformRotateFirst(x(i), 0, 0));\n\t\t}\n\t}\n\treturn tfs;\n}\n\nint FriendlyGraph::getMaxNumPoses() const {\n\treturn _max_num_poses;\n}\n\n} // namespace filters::pose_graph\n", "meta": {"hexsha": "d81c94acf02ff0ec417ec2fc86247e73a57f1408", "size": 6748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/filters/pose_graph/friendly_graph.cpp", "max_stars_repo_name": "huskyroboticsteam/Resurgence", "max_stars_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-23T23:31:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:17:41.000Z", "max_issues_repo_path": "src/filters/pose_graph/friendly_graph.cpp", "max_issues_repo_name": "huskyroboticsteam/Resurgence", "max_issues_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-22T05:33:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T07:01:47.000Z", "max_forks_repo_path": "src/filters/pose_graph/friendly_graph.cpp", "max_forks_repo_name": "huskyroboticsteam/Resurgence", "max_forks_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "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.5157894737, "max_line_length": 95, "alphanum_fraction": 0.7280675756, "num_tokens": 2061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5433191202264253}}
{"text": "#include \"decode.hpp\"\n#include \"pauli_product.hpp\"\n#include <armadillo>\n#include <iostream>\n\nusing namespace std;\nusing namespace arma;\n\ndouble coeff_a1(unsigned int q_idx, cx_dvec &psi)\n{\n  int d = psi.size();\n  double mysum = 0.0;\n  for (int y=0; y<d; y++)\n    {\n      if (!(y & (1<<q_idx)))\n\t{\n\t   mysum += std::norm(psi(y));\n\t}\n    }\n  return mysum;\n}\n\ndouble coeff_a2(unsigned int q_idx, unsigned int x, cx_dvec &psi)\n{\n  int d = psi.size();\n  double mysum = 0.0;\n  for (int y=0; y<d ; y++)\n    {\n      int temp = 1<< q_idx;\n      int temp2 = y^x;\n      if (!((y^x) & (1<<q_idx)))\n\t{\n\t  mysum += std::norm(psi(y));\n\t}\n      else\n\t{\n\t}\n    }\n  return mysum;\n  \n}\n\ndouble coeff_a3(unsigned int q_idx, unsigned int x, unsigned int z, cx_dvec &psi)\n{\n  int d = psi.size();\n  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\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      if (!((y^x) & (1<<q_idx)))\n\t{\n\t  //\t  cout << y << endl;\n\t  //\t  cout << (y^x) << endl;\n\t  mysum += (-2) * std::imag(std::conj(psi(y^x)) * psi(y) * phase);\n\t}\n    }\n  return mysum;\n}\n\n// Given a Pauli string, find the rotation angle with respect to the corresponding PPR that gives the optimal overlap with the |0>_{q_idx} state.\ndouble optimized_theta(unsigned int q_idx, unsigned int x, unsigned int z, cx_dvec &psi)\n{\n  double a1 = coeff_a1(q_idx, psi);\n  double a2 = coeff_a2(q_idx, x, psi);\n  double a3 = coeff_a3(q_idx, x, z, psi);\n\n  double theta1, theta2;\n  if (a1==a2)\n    theta1= 3.14159265358979/2.0;\n  else\n    theta1 = atan(a3/(a1 - a2))/2.0;\n  \n  theta2 = theta1 + 3.14159265358979/2.0;\n\n  double f1 = ((a1-a2) * cos(2*theta1) + a3 * sin(2*theta1))/2.0;\n  double f2 = ((a1-a2) * cos(2*theta2) + a3 * sin(2*theta2))/2.0;\n\n  f1 += (a1+a2)/2.0;\n  f2 += (a1+a2)/2.0;\n\n  if (f1>f2)\n    return theta1;\n  else\n    return theta2;\n}\n\n// Given a Pauli string, find the optimal overlap with the |0>_{q_idx} using\n// a PPR.\ndouble optimal_overlap(unsigned int q_idx, unsigned int x, unsigned int z, cx_dvec &psi)\n{\n  double a1 = coeff_a1(q_idx, psi);\n  double a2 = coeff_a2(q_idx, x, psi);\n  double a3 = coeff_a3(q_idx, x, z, psi);\n\n  double theta1, theta2;\n  if (a1==a2)\n    theta1= 3.14159265358979/2.0;\n  else\n    theta1 = atan(a3/(a1 - a2))/2.0;\n  \n  theta2 = theta1 + 3.14159265358979/2.0;\n  double f1 = ((a1-a2) * cos(2*theta1) + a3 * sin(2*theta1))/2.0;\n  double f2 = ((a1-a2) * cos(2*theta2) + a3 * sin(2*theta2))/2.0;\n\n  f1 += (a1+a2)/2.0;\n  f2 += (a1+a2)/2.0;\n\n  if (f1>f2)\n    return f1;\n  else\n    return f2;\n}\n\n// Find the optimal Pauli string that maximizes the overlap with |0>_q\n// and apply the corresponding PPR to psi. Here the PPR is assumed to be restricted\n// to a set of first 'bits' qubits\nvoid optimal_update(unsigned int q_idx, unsigned int setbits, cx_dvec &psi)\n{\n  int i_best, j_best;\n  double f = 0.0;\n  double theta = 0.0;\n  for (int i=0; i<(1<<setbits); i++)\n    {\n      for (int j=0; j<(1<<setbits); j++)\n\t{\n\t  /*\t  cout << \"State=\" << endl;\n\t  cout << psi << endl;\n\t  cout << \"i, j=\" << i << \", \" << j << endl;\n\t  double a1 = coeff_a1(0, psi);\n\t  double a2 = coeff_a2(0, i, psi);\n\t  double a3 = coeff_a3(0, i, j, psi);\n\t  double f_opt = optimal_overlap(0, i, j, psi);\n\t  cout << \"a1=\" << a1 << endl;\n\t  cout << \"a2=\" << a2 << endl;\n\t  cout << \"a3=\" << a3 << endl;\n\t  cout << \"f_opt=\" << f_opt << endl;\n\t  if ((a1==a2) && (abs(a3)>0.0001))\n\t  exit (EXIT_FAILURE);*/\n\n\t  // Apply optimal update only if the PPR acts nontrivially on q_idx.\n\t  if ((i & (1<<q_idx)) || (j & (1<<q_idx)))\n\t    {\n\t      if (optimal_overlap(q_idx, i, j, psi) > f)\n\t\t{\n\t\t  f = optimal_overlap(q_idx, i, j, psi);\n\t\t  //\t      cout << \"New record: \" << f << endl;\n\t\t  i_best = i;\n\t\t  j_best = j;\n\t\t}\n\t    }\n\t  \n\t}\n    }\n  theta = optimized_theta(0, i_best, j_best, psi);\n  apply_ppr(i_best, j_best, theta, psi);\n}\n\n// Skip the given choice of i and j with probability 1-ratio.\nvoid randomized_update(unsigned int q_idx, unsigned int setbits, double ratio, cx_dvec &psi)\n{\n  int i_best, j_best;\n  double f = 0.0;\n  double theta = 0.0;\n  for (int i=0; i<(1<<setbits); i++)\n    {\n      for (int j=0; j<(1<<setbits); j++)\n\t{\n\t  if ((i & (1<<q_idx)) || (j & (1<<q_idx)))\n\t    {\n\t      if ((double)rand() / (double)RAND_MAX < ratio)\n\t\t{\n\t\t  if (optimal_overlap(q_idx, i, j, psi) > f)\n\t\t    {\n\t\t      f = optimal_overlap(q_idx, i, j, psi);\n\t\t      //\t      cout << \"New record: \" << f << endl;\n\t\t      i_best = i;\n\t\t      j_best = j;\n\t\t    }\n\t\t}\n\t    }\n\t  \n\t}\n    }\n  theta = optimized_theta(0, i_best, j_best, psi);\n  apply_ppr(i_best, j_best, theta, psi);\n}\n\n// Decode and print the result.\nvoid decode(unsigned q_idx, cx_dvec &psi, unsigned int setbits, double eps)\n{\n  double f = 0.0;\n  int itt = 0;\n  while (f<1-eps)\n    {\n      itt++;\n      optimal_update(q_idx, setbits, psi);\n      f = coeff_a1(0, psi);\n      cout << itt << \":\" << f << endl;\n    }\n}\n\nvoid randomized_decode(unsigned q_idx, cx_dvec &psi, unsigned int setbits, double ratio, double eps)\n{\n  double f = 0.0;\n  int itt = 0;\n  while (f<1-eps)\n    {\n      itt++;\n      randomized_update(q_idx, setbits, ratio, psi);\n      f = coeff_a1(0, psi);\n      cout << itt << \":\" << f << endl;\n    }\n}\n\ndouble decode_cost(unsigned q_idx, cx_dvec &psi, unsigned int setbits, double eps)\n{\n  double f = 0.0;\n  double cost = 0.0;\n  int itt = 0;\n  while (f<1-eps)\n    {\n      itt++;\n      optimal_update(q_idx, setbits, psi);\n      f = coeff_a1(0, psi);\n      //      cout << itt << \":\" << f << endl;\n      cost += 1.0;\n    }\n  return cost;\n}\n\ndouble randomized_decode_cost(unsigned q_idx, cx_dvec &psi, unsigned int setbits, double ratio, double eps)\n{\n  double f = 0.0;\n  double cost = 0.0;\n  int itt = 0;\n  while (f<1-eps)\n    {\n      itt++;\n      randomized_update(q_idx, setbits, ratio, psi);\n      f = coeff_a1(0, psi);\n      //      cout << itt << \":\" << f << endl;\n      cost += 1.0;\n    }\n  return cost;\n}\n", "meta": {"hexsha": "a4e0f55d23986d9058d6022c7364d515a75a072e", "size": 6167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/decode.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++/decode.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++/decode.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": 23.3598484848, "max_line_length": 145, "alphanum_fraction": 0.5636452084, "num_tokens": 2213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5433191188966273}}
{"text": "/*\n*  @file \t\tex8.cpp\n*  @details  \tThis file is the solution to exercise 8.\n*  @author    \tAlexander Rettkowski\n*  @date      \t12.07.2017\n*/\n#include <boost/config/warning_disable.hpp>\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_object.hpp>\n#include <boost/fusion/include/adapt_struct.hpp>\n#include <boost/fusion/include/io.hpp>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n#include <boost/property_map/property_map.hpp>\n\n#include <boost/timer/timer.hpp>\n#include <boost/chrono.hpp>\n\n#include <iostream>\n#include <string>\n#include <complex>\n#include <fstream>\n#include <queue> \n\nusing namespace boost;\n\nnamespace exercise8\n{\n\tnamespace qi = boost::spirit::qi;\n\tnamespace ascii = boost::spirit::ascii;\n\tstruct edge\n\t{\n\t\tint startNode;\n\t\tint endNode;\n\t\tint length;\n\t};\n}\n\n\nBOOST_FUSION_ADAPT_STRUCT(\n\texercise8::edge,\n\t(int, startNode)\n\t(int, endNode)\n\t(int, length)\n)\n\nnamespace exercise8\n{\n\ttemplate <typename Iterator>\n\tstruct line_parser : qi::grammar<Iterator, edge()>\n\t{\n\t\tline_parser() : line_parser::base_type(start)\n\t\t{\n\t\t\tusing qi::int_;\n\t\t\tstart %= int_ >> ' ' >> int_ >> ' ' >> int_;\n\t\t}\n\n\t\tqi::rule<Iterator, edge()> start;\n\t};\n}\n\n/**\n* The function that calculates the shortest paths using Dijkstra's method.\n* @param numberOfNodes Number of nodes in the graph.\n* @param graph The graph represented as a vector auf edge-vectors.\n* @param startNode The id of the node where the search starts.\n*/\nstd::vector<int> dijkstra(int numberOfNodes, std::vector< std::vector< std::pair<int, int> > > graph, int startNode, std::vector<int>& predecessors)\n{\n\tpredecessors.resize(numberOfNodes, -1);\n\tstd::vector<int> distanceTo(numberOfNodes, INT_MAX);\n\tstd::priority_queue< std::pair<int, int>, std::vector< std::pair<int, int> >, std::greater< std::pair<int, int> > > queue;\n\tqueue.push(std::pair<int, int>(startNode, 0));\n\tdistanceTo[startNode] = 0;\n\t//predecessors[startNode] = -1;\n\n\tint currentNode, compareNode, compareNodeDistance, currentNodeDistance;\n\n\twhile (!queue.empty()) {\n\t\tcurrentNode = queue.top().first;\n\t\tcurrentNodeDistance = queue.top().second;\n\t\tqueue.pop();\n\n\t\tif (distanceTo[currentNode] < currentNodeDistance) continue;\n\n\t\tfor (int i = 0; i < graph[currentNode].size(); i++) {\n\t\t\tcompareNode = graph[currentNode][i].first;\n\t\t\tcompareNodeDistance = graph[currentNode][i].second;\n\t\t\tif (distanceTo[compareNode] > distanceTo[currentNode] + compareNodeDistance) {\n\t\t\t\tdistanceTo[compareNode] = distanceTo[currentNode] + compareNodeDistance;\n\t\t\t\tqueue.push(std::pair<int, int>(compareNode, distanceTo[compareNode]));\n\t\t\t\tpredecessors[compareNode] = currentNode;\n\t\t\t}\n\t\t}\n\t}\n\treturn distanceTo;\n}\n\n\n/**\n* This method checks (in a naive way), if a given number is prime or not.\n* @param number The number to check.\n* @returns True, if number is prime; false otherwise.\n*/\nbool isPrime(int number) {\n\tif (number == 2)\n\t\treturn true;\n\tif (number % 2 == 0)\n\t\treturn false;\n\tfor (int i = 3; (i*i) <= number; i += 2) {\n\t\tif (number % i == 0) return false;\n\t}\n\treturn true;\n}\n\n/**\n* The main function that reads in a file and processes it.\n* @param argc Number of command line arguments.\n* @param *argv a pointer to the array of command line arguments.\n*/\nint main(int argc, char *argv[])\n{\n\ttimer::cpu_timer boostTimer;\n\n\tusing boost::spirit::ascii::space;\n\ttypedef std::string::const_iterator iterator_type;\n\ttypedef exercise8::line_parser<iterator_type> line_parser;\n\tline_parser parser;\n\tstd::string currentLine;\n\tstd::ifstream file(argv[1]);\n\n\t// get number of nodes\n\tchar delimiter = ' ';\n\tgetline(file, currentLine, delimiter);\n\tconst int numberOfNodes = stoi(currentLine);\n\tgetline(file, currentLine);\n\tint constSub = 1;\n\n\tstd::vector<std::vector<std::pair<int, int>>> edges(numberOfNodes);\n\twhile (getline(file, currentLine))\n\t{\n\t\texercise8::edge parsedLine;\n\t\tstd::string::const_iterator currentPosition = currentLine.begin();\n\t\tstd::string::const_iterator lineEnd = currentLine.end();\n\t\tbool parsingSucceeded = phrase_parse(currentPosition, lineEnd, parser, space, parsedLine);\n\n\t\tif (parsingSucceeded && currentPosition == lineEnd)\n\t\t{\n\t\t\tstd::pair<int, int> *tempEdge = new std::pair<int, int>();\n\t\t\ttempEdge->first = parsedLine.endNode - constSub;\n\t\t\ttempEdge->second = parsedLine.length;\n\t\t\tedges[parsedLine.startNode - constSub].push_back(*tempEdge);\n\n\t\t\tstd::pair<int, int> *reverseEdge = new std::pair<int, int>();\n\t\t\treverseEdge->first = parsedLine.startNode - constSub;\n\t\t\treverseEdge->second = parsedLine.length;\n\t\t\tedges[parsedLine.endNode - constSub].push_back(*reverseEdge);\n\t\t}\n\t}\n\n\tfile.close();\n\t\n\n\n\n\n\n\n\tstd::vector<int> connectedVertices, unconnectedTerminals;\n\tfor (int i = 0; i < numberOfNodes; i++)\n\t{\n\t\tif (isPrime(i))\n\t\t\tunconnectedTerminals.push_back(i);\n\t}\n\n\tconnectedVertices.push_back(unconnectedTerminals.back());\n\tunconnectedTerminals.pop_back();\n\n\tstd::map<int, std::vector<int>> distancesFromTerminals;\n\tstd::map<int, std::vector<int>> predecessorsFromTerminals;\n\tfor (int i : unconnectedTerminals)\n\t{\n\t\tstd::vector<int> predecessors;\n\t\tstd::vector<int> distancesFromI = dijkstra(numberOfNodes, edges, i, predecessors);\n\t\tdistancesFromTerminals.insert(std::pair<int, std::vector<int>>(i, distancesFromI));\n\t\tpredecessorsFromTerminals.insert(std::pair<int, std::vector<int>>(i, predecessors));\n\t}\n\n\tint steinerWeight = 0;\n\n\twhile (unconnectedTerminals.size() > 0)\n\t{\n\t\tint connectingPointId = -1, connectingPointDistance = INT32_MAX;\n\t\tstd::vector<int> path;\n\n\t\tint pathFrom = -1, pathTo = -1, mindist = INT32_MAX;\n\t\tfor (int i = 0; i < unconnectedTerminals.size(); i++)\n\t\t{\n\t\t\tint vertexId = unconnectedTerminals[i];\n\t\t\tfor (int j : connectedVertices)\n\t\t\t{\n\t\t\t\tif (distancesFromTerminals[vertexId][j] < mindist)\n\t\t\t\t{\n\t\t\t\t\tmindist = distancesFromTerminals[vertexId][j];\n\t\t\t\t\tpathTo = j;\n\t\t\t\t\tpathFrom = vertexId;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpath.push_back(pathFrom);\n\t\tdo\n\t\t{\n\t\t\tpath.push_back(pathTo);\n\t\t\tpathTo = predecessorsFromTerminals[pathFrom][pathTo];\n\t\t} while (pathTo != pathFrom);\n\n\t\t// get path from \n\t\tfor (int i : path)\n\t\t{\n\t\t\t// if the vertex wasn't in the tree before, add\n\t\t\tif (std::find(connectedVertices.begin(), connectedVertices.end(), i) == connectedVertices.end())\n\t\t\t{\n\t\t\t\tconnectedVertices.push_back(i);\n\t\t\t}\n\t\t\t// if it was an unconnected terminal, delete from the list\n\t\t\tauto pos = std::find(unconnectedTerminals.begin(), unconnectedTerminals.end(), i);\n\t\t\tif (pos != unconnectedTerminals.end())\n\t\t\t{\n\t\t\t\tunconnectedTerminals.erase(pos);\n\t\t\t}\n\t\t}\n\n\t\tsteinerWeight += mindist;\n\n\t}\n\n\tstd::cout << steinerWeight;\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "37f9071cb1e9c23be671b9b0d8f9d4ac9624497d", "size": 6736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rettkowski/ex8.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": "rettkowski/ex8.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": "rettkowski/ex8.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.2712550607, "max_line_length": 148, "alphanum_fraction": 0.7050178147, "num_tokens": 1810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5433168673258183}}
{"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 *      110702    K. Kumar          File created.\n *      110726    K. Kumar          Changed filename and class name.\n *      110802    K. Kumar          Added standard deviation and chi-squared\n *                                  test; added note; renamed filename.\n *      110905    S. Billemont      Reorganized includes.\n *                                  Moved (con/de)structors and getter/setters to header.\n *      120509    K. Kumar          Boostified unit test.\n *      120516    A. Ronse          Updated namespaces and corrected reference. Added unit tests\n *                                  for horizontal and vertical cases. Adjusted precision.\n *\n *    References\n *      Burden, R.L., Faires, J.D. Numerical Analysis, 7th Edition, Books/Cole, 2001.\n *\n *    Notes\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <cmath>\n#include <limits>\n#include <map>\n\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/Statistics/simpleLinearRegression.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_simple_linear_regression )\n\n//! Test if simple linear regression method computes fit correctly.\nBOOST_AUTO_TEST_CASE( testSimpleLinearRegressionBF )\n{\n    // Test 1: Test implementation of simple linear regression method against benchmark data from\n    //         pg. 487, example 1 of (Burden and Faires, 2001). Standard deviations were benchmarked\n    //         using MATLAB's lscov() function.\n\n    // Benchmark data.\n    std::map< double, double > benchmarkInputData;\n    benchmarkInputData[ 1.0 ] = 1.3;\n    benchmarkInputData[ 2.0 ] = 3.5;\n    benchmarkInputData[ 3.0 ] = 4.2;\n    benchmarkInputData[ 4.0 ] = 5.0;\n    benchmarkInputData[ 5.0 ] = 7.0;\n    benchmarkInputData[ 6.0 ] = 8.8;\n    benchmarkInputData[ 7.0 ] = 10.1;\n    benchmarkInputData[ 8.0 ] = 12.5;\n    benchmarkInputData[ 9.0 ] = 13.0;\n    benchmarkInputData[ 10.0 ] = 15.6;\n\n    // Expected coefficients of linear fit.\n    const double expectedCoefficientOfConstantTerm = -0.359999999999999999;\n    const double expectedCoefficientOfLinearTerm = 1.5381818181818181818;\n\n    // Expected standard deviations of fit coefficients.\n    const double expectedStandardDeviationOfCoefficientOfConstantTerm = 0.369832066721825;\n    const double expectedStandardDeviationOfCoefficientOfLinearTerm = 0.059603834439483;\n\n    // Expected chi-squared value.\n    const double expectedChiSquared = 2.344727272727272;\n\n    // Declare simple linear regression object and set input data.\n    statistics::SimpleLinearRegression simpleLinearRegression( benchmarkInputData );\n\n    // Compute linear fit.\n    simpleLinearRegression.computeFit( );\n\n    // Check that computed coefficient of constant term matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( expectedCoefficientOfConstantTerm,\n                                simpleLinearRegression.getCoefficientOfConstantTerm( ),\n                                1.0e-14 );\n\n    // Check that computed coefficient of linear term matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( expectedCoefficientOfLinearTerm,\n                                simpleLinearRegression.getCoefficientOfLinearTerm( ),\n                                1.0e-15 );\n\n    // Compute linear fit errors.\n    simpleLinearRegression.computeFitErrors( );\n\n    // Check that computed standard deviation of coefficient of constant term matches expected\n    // value.\n    BOOST_CHECK_CLOSE_FRACTION( expectedStandardDeviationOfCoefficientOfConstantTerm,\n                                simpleLinearRegression\n                                .getStandardDeviationOfCoefficientOfConstantTerm( ),\n                                1.0e-13 );\n\n    // Check that computed standard deviation of coefficient of linear term matches expected\n    // value.\n    BOOST_CHECK_CLOSE_FRACTION( expectedStandardDeviationOfCoefficientOfLinearTerm,\n                                simpleLinearRegression\n                                .getStandardDeviationOfCoefficientOfLinearTerm( ),\n                                1.0e-13 );\n\n    // Check that computed chi-squared fit matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( expectedChiSquared,\n                                simpleLinearRegression.getChiSquared( ),\n                                1.0e-15 );\n}\n\nBOOST_AUTO_TEST_CASE( testSimpleLinearRegressionHorizontal )\n{\n    // Test 2: Test implementation of simple linear regression method in case of sample points\n    // coinciding with the x-axis.\n\n    std::map< double, double > benchmarkInputData;\n    benchmarkInputData[ 1.0 ] = 0.0;\n    benchmarkInputData[ 2.0 ] = 0.0;\n    benchmarkInputData[ 3.0 ] = 0.0;\n    benchmarkInputData[ 4.0 ] = 0.0;\n    benchmarkInputData[ 5.0 ] = 0.0;\n    benchmarkInputData[ 6.0 ] = 0.0;\n    benchmarkInputData[ 7.0 ] = 0.0;\n    benchmarkInputData[ 8.0 ] = 0.0;\n    benchmarkInputData[ 9.0 ] = 0.0;\n    benchmarkInputData[ 10.0 ] = 0.0;\n\n    // Declare simple linear regression object and set input data.\n    statistics::SimpleLinearRegression simpleLinearRegression( benchmarkInputData );\n\n    // Compute linear fit.\n    simpleLinearRegression.computeFit( );\n\n    // Check that computed coefficient of constant term is zero.\n    BOOST_CHECK_SMALL( simpleLinearRegression.getCoefficientOfConstantTerm( ),\n                       std::numeric_limits< double >::min( ) );\n\n    // Check that computed coefficient of linear term matches is zero.\n    BOOST_CHECK_SMALL( simpleLinearRegression.getCoefficientOfLinearTerm( ),\n                       std::numeric_limits< double >::min( ) );\n\n    // Compute linear fit errors.\n    simpleLinearRegression.computeFitErrors( );\n\n    // Check that computed standard deviation of coefficient of constant term is zero.\n    BOOST_CHECK_SMALL( simpleLinearRegression.getStandardDeviationOfCoefficientOfConstantTerm( ),\n                       std::numeric_limits< double >::min( ) );\n\n\n    // Check that computed standard deviation of coefficient of linear term is zero.\n    BOOST_CHECK_SMALL( simpleLinearRegression.getStandardDeviationOfCoefficientOfLinearTerm( ),\n                       std::numeric_limits< double >::min( ) );\n\n    // Check that computed chi-squared fit is zero.\n    BOOST_CHECK_SMALL( simpleLinearRegression.getChiSquared( ),\n                       std::numeric_limits< double >::min( ) );\n}\n\nBOOST_AUTO_TEST_CASE( testSimpleLinearRegressionVertical )\n{\n    // Test 3: Test implementation of simple linear regression method in case of sample points\n    // coinciding with the y-axis.\n\n    std::map< double, double > benchmarkInputData;\n    benchmarkInputData[ 0.0 ] = 1.3;\n    benchmarkInputData[ 0.0 ] = 3.5;\n    benchmarkInputData[ 0.0 ] = 4.2;\n    benchmarkInputData[ 0.0 ] = 5.0;\n    benchmarkInputData[ 0.0 ] = 7.0;\n    benchmarkInputData[ 0.0 ] = 8.8;\n    benchmarkInputData[ 0.0 ] = 10.1;\n    benchmarkInputData[ 0.0 ] = 12.5;\n    benchmarkInputData[ 0.0 ] = 13.0;\n    benchmarkInputData[ 0.0 ] = 15.6;\n\n    // Declare simple linear regression object and set input data.\n    statistics::SimpleLinearRegression simpleLinearRegression( benchmarkInputData );\n\n    // Compute linear fit.\n    simpleLinearRegression.computeFit( );\n\n    // Check that computed coefficient of constant term matches expected value.\n    BOOST_CHECK( boost::math::isnan( simpleLinearRegression.getCoefficientOfConstantTerm( ) ) );\n\n    // Check that computed coefficient of linear term matches expected value.\n    BOOST_CHECK( boost::math::isnan( simpleLinearRegression.getCoefficientOfLinearTerm( ) ) );\n\n    // Compute linear fit errors.\n    simpleLinearRegression.computeFitErrors( );\n\n    // Check that computed standard deviation of coefficient of constant term matches expected\n    // value.\n    BOOST_CHECK( boost::math::isnan( simpleLinearRegression\n                             .getStandardDeviationOfCoefficientOfConstantTerm( ) ) );\n\n    // Check that computed standard deviation of coefficient of linear term matches expected\n    // value.\n    BOOST_CHECK( boost::math::isnan(simpleLinearRegression\n                            .getStandardDeviationOfCoefficientOfLinearTerm( ) ) );\n\n    // Check that computed chi-squared fit matches expected value.\n    BOOST_CHECK( boost::math::isnan(simpleLinearRegression.getChiSquared( ) ) );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "a3cfb765bbb049f6f6ede2515144f7adf7d81388", "size": 10138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/Statistics/UnitTests/unitTestSimpleLinearRegression.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/Statistics/UnitTests/unitTestSimpleLinearRegression.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/Statistics/UnitTests/unitTestSimpleLinearRegression.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": 43.8874458874, "max_line_length": 100, "alphanum_fraction": 0.686525942, "num_tokens": 2288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5433168427658428}}
{"text": "// Filename: size_type_example2.cpp (part of MTL4)\n\n#include <iostream>\n#include <boost/cstdint.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main()\n{\n    using namespace mtl;\n\n    typedef mat::parameters<row_major, mtl::index::c_index, non_fixed::dimensions, false, boost::uint_least32_t> para;\n    compressed2D<double, para>   A;\n    laplacian_setup(A, 2, 3);\n    \n    std::cout << \"A is\\n\" << A << \"\\nsize of index is \" << sizeof(A.ref_minor()[0]) << '\\n';\n    return 0;\n}\n", "meta": {"hexsha": "c8e29acdb77504a37e1de4389f01629e7c15a640", "size": 477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/size_type_example2.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/size_type_example2.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/size_type_example2.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.5, "max_line_length": 118, "alphanum_fraction": 0.6519916143, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5432993607311515}}
{"text": "/*\n * Copyright 2013-2015 Raphael Bost\n *\n * This file is part of ciphermed.\n\n *  ciphermed 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 *  ciphermed 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 ciphermed.  If not, see <http://www.gnu.org/licenses/>. 2\n *\n */\n\n#include <math/num_th_alg.hh>\n#include <math/math_util.hh>\n#include <math/util_gmp_rand.h>\n#include <math/prime_seq.hh>\n#include <math/mpz_class.hh>\n#include <NTL/ZZ.h>\n#include <cassert>\n\n#include <iostream>\n\n/* The algorithms here are from Victor Shoup's Book\n * A Computational Introduction to Number Theory and Algebra\n * or Shoup's NTL library (for Sophie Germain primes)\n */\n\nstd::vector<mpz_class> gen_rand_non_increasing_seq(const mpz_class &m, gmp_randstate_t state)\n{\n    std::vector<mpz_class> seq;\n\n    mpz_class n = m;\n    mpz_class new_n;\n    do {\n        // pick a new n between 1...n\n        mpz_urandomm(new_n.get_mpz_t(),state,n.get_mpz_t());\n        n = new_n + 1;\n        seq.push_back(n);\n    } while (n != 1);\n\n    return seq;\n}\n\nstd::vector<mpz_class> extract_prime_seq(const std::vector<mpz_class> &seq, int reps)\n{\n    std::vector<mpz_class> primes;\n    for (size_t i = 0; i < seq.size(); i++) {\n        if (mpz_class_probab_prime_p(seq[i],reps) != 0) {\n            primes.push_back(seq[i]);\n        }\n    }\n\n    return primes;\n}\n\n// generates a random integer with its factorization (returns the factorization)\nstd::vector<mpz_class> gen_rand_number_factorization(const mpz_class &m, mpz_class *result, gmp_randstate_t state, int reps)\n{\n    for (; ; ) {\n        std::vector<mpz_class> seq = gen_rand_non_increasing_seq(m,state);\n        std::vector<mpz_class> primes = extract_prime_seq(seq, reps);\n\n        mpz_class y = 1;\n        for (size_t i = 0; i < primes.size(); i++) {\n            y *= primes[i];\n            if (y > m) {\n                break;\n            }\n        }\n        if (y > m) {\n            continue;\n        }\n\n        mpz_class x;\n        mpz_urandomm(x.get_mpz_t(),state,m.get_mpz_t());\n        x += 1;\n\n        if (x <= y) {\n            if (result) {\n                *result = y;\n            }\n            return primes;\n        }\n    }\n}\n\n// generates a random prime p with the factorization of p-1 (returns the factorization)\nstd::vector<mpz_class> gen_rand_prime_with_factorization(const mpz_class &m, mpz_class *p, gmp_randstate_t state, int reps)\n{\n    for (; ; ) {\n        mpz_class n;\n        std::vector<mpz_class> factorization = gen_rand_number_factorization(m,&n,state,reps);\n\n        if (mpz_class_probab_prime_p(n+1, reps) != 0) {\n            if (p) {\n                *p = n+1;\n            }\n            return factorization;\n        }\n    }\n}\n\nmpz_class simple_safe_prime_gen(size_t n_bits, gmp_randstate_t state, int reps)\n{\n    for (size_t count = 1; ; count ++) {\n        mpz_class n;\n        mpz_urandom_len(n.get_mpz_t(),state,n_bits);\n\n        if (mpz_class_probab_prime_p(n,reps) !=0) {\n            if (mpz_class_probab_prime_p(2*n+1,reps) != 0 ) {\n                std::cout << count << \" iterations needed to generate safe prime\" << std::endl;\n                return n;\n            }\n        }\n    }\n}\n\n\nstatic long bit_count(long a)\n{\n    unsigned long aa;\n    if (a < 0)\n    aa = - ((unsigned long) a);\n    else\n    aa = a;\n\n    long k = 0;\n    while (aa) {\n        k++;\n        aa = aa >> 1;\n    }\n\n    return k;\n}\n\n/* The following code is just NTL's code for generating Germain primes using GMP */\n\n// prime_bound computes a reasonable bound for trial\n// division in the Miller-Rabin test.\n// It is computed a bit on the \"low\" side, since being a bit\n// low doesn't hurt much, but being too high can hurt a lot.\n\nstatic\nlong prime_bound(long bn)\n{\n    long wn = (bn+NBITS_MAX-1)/NBITS_MAX;\n\n    long fn;\n\n    if (wn <= 36)\n    fn = wn/4 + 1;\n    else\n    fn = long(1.67*sqrt(double(wn)));\n\n    long prime_bnd;\n\n    if (bit_count(bn) + bit_count(fn) > NBITS_MAX)\n        prime_bnd = (1L << NBITS_MAX);\n    else\n        prime_bnd = bn*fn;\n\n    return prime_bnd;\n}\n\nstatic\nlong ErrBoundTest(long kk, long tt, long nn)\n\n{\n    const double fudge = (1.0 + 1024.0/NTL_FDOUBLE_PRECISION);\n    const double log2_3 = log2(3.0);\n    const double log2_7 = log2(7.0);\n    const double log2_20 = log2(20.0);\n\n    double k = kk;\n    double t = tt;\n    double n = nn;\n\n    if (k < 3 || t < 1) return 0;\n    if (n < 1) return 1;\n\n    // the following test is largely academic\n    assert(9*t < NTL_FDOUBLE_PRECISION);\n\n    double log2_k = log2(k);\n\n    if ((n + log2_k)*fudge <= 2*t)\n    return 1;\n\n    if ((2*log2_k + 4.0 + n)*fudge <= 2*sqrt(k))\n    return 2;\n\n    if ((t == 2 && k >= 88) || (3 <= t && 9*t <= k && k >= 21)) {\n        if ((1.5*log2_k + t + 4.0 + n)*fudge <= 0.5*log2(t) + 2*(sqrt(t*k)))\n        return 3;\n    }\n\n    if (k <= 9*t && 4*t <= k && k >= 21) {\n        if ( ((log2_3 + log2_7 + log2_k + n)*fudge <= log2_20 + 5*t)  &&\n            ((log2_3 + (15.0/4.0)*log2_k + n)*fudge <= log2_7 + k/2 + 2*t) &&\n            ((2*log2_3 + 2 + log2_k + n)*fudge <= k/4 + 3*t) )\n        return 4;\n    }\n\n    if (4*t >= k && k >= 21) {\n        if (((15.0/4.0)*log2_k + n)*fudge <= log2_7 + k/2 + 2*t)\n        return 5;\n    }\n\n    return 0;\n}\n\nstatic long make_odd(mpz_class &n)\n{\n    long k = 0;\n\n    while (mpz_even_p(n.get_mpz_t())) {\n        n >>= 1;\n        k++;\n    }\n\n    return k;\n}\n\nstatic long is_Miller_witness(const mpz_class& n, const mpz_class& x)\n{\n    mpz_class m(0), y(0), z(0);\n    long j, k;\n\n    if (x == 0) return 0;\n\n    m = n-1;\n    k = make_odd(m);\n\n    z = mpz_class_powm(x,m,n);\n\n    if (z == 1) return 0;\n\n    j = 0;\n    do {\n        y = z;\n        z = (y*y) %n;\n        j++;\n    } while (j != k && z != 1);\n\n    if (z != 1) return 1;\n    y = y + 1;\n    if (y != n) return 1;\n    return 0;\n}\n\nvoid gen_germain_prime(mpz_class& n, long k, gmp_randstate_t state, long err)\n{\n    assert(k > 1);\n    assert(k <= (1L << 20));\n\n    if (err < 1) err = 1;\n    if (err > 512) err = 512;\n\n    if (k == 2) {\n        if (gmp_urandomm_ui(state,2))\n        n = 3;\n        else\n        n = 2;\n\n        return;\n    }\n\n\n    long prime_bnd = prime_bound(k);\n\n    if (bit_count(prime_bnd) >= k/2)\n    prime_bnd = (1L << (k/2-1));\n\n\n    mpz_class two;\n    two = 2;\n\n    mpz_class n1;\n\n\n    PrimeSeq s;\n\n    mpz_class iter;\n    iter = 0;\n\n\n    for (;;) {\n        iter++;\n\n        mpz_urandom_len(n.get_mpz_t(),state,k);\n\n        if (mpz_even_p(n.get_mpz_t())) {\n            n = n+1;\n        }\n\n        s.reset(3);\n        long p;\n\n        long sieve_passed = 1;\n\n        p = s.next();\n        while (p && p < prime_bnd) {\n            mpz_class r;\n            mpz_tdiv_r_ui(r.get_mpz_t(),n.get_mpz_t(),p);\n\n            if (r == 0) {\n                sieve_passed = 0;\n                break;\n            }\n\n            // test if 2*r + 1 = 0 (mod p)\n            if (r == p-r-1) {\n                sieve_passed = 0;\n                break;\n            }\n\n            p = s.next();\n        }\n\n        if (!sieve_passed) continue;\n\n\n        if (is_Miller_witness(n, two)) continue;\n\n        n1 = 2*n+1;\n\n        if (is_Miller_witness(n1, two)) continue;\n\n        // now do t M-R iterations...just to make sure\n\n        // First compute the appropriate number of M-R iterations, t\n        // The following computes t such that\n        //       p(k,t)*8/k <= 2^{-err}/(5*iter^{1.25})\n        // which suffices to get an overall error probability of 2^{-err}.\n        // Note that this method has the advantage of not requiring\n        // any assumptions on the density of Germain primes.\n        long iter_n_bits = mpz_sizeinbase(iter.get_mpz_t(),2);\n        long err1 = std::max(1L, err + 7 + (5*iter_n_bits + 3)/4 - bit_count(k));\n        long t;\n        t = 1;\n        while (!ErrBoundTest(k, t, err1))\n        t++;\n\n        if(mpz_probab_prime_p(n.get_mpz_t(),t))\n            break;\n    }\n}\n\n// Constructs a generator for the cyclic group \\Z^*_p where p is a Sophie Germain prime\nmpz_class get_generator_for_cyclic_group(const mpz_class &p, gmp_randstate_t state)\n{\n    mpz_class q = (p >> 1);\n    mpz_class g;\n\n\n    // find a generator for ZZ*_p\n    // Shoup's algorithm\n\n    mpz_class alpha, beta;\n    do {\n        mpz_urandomm(alpha.get_mpz_t(),state,p.get_mpz_t());\n\n        beta = mpz_class_powm(alpha,q,p);\n    } while (beta == 1);\n\n    g = beta;\n\n    do {\n        mpz_urandomm(alpha.get_mpz_t(),state,p.get_mpz_t());\n        beta = (alpha*alpha) %p;\n\n    } while (beta == 1);\n\n    g = (g*beta) %p;\n\n    return g;\n}\n", "meta": {"hexsha": "6e2fd090c1fbd0171044755cc8c8187dd67babf8", "size": 8924, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Source/math/num_th_alg.cc", "max_stars_repo_name": "TarekIbnZiad/CryptoImg", "max_stars_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-05T18:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T07:33:10.000Z", "max_issues_repo_path": "Source/math/num_th_alg.cc", "max_issues_repo_name": "TarekIbnZiad/CryptoImg", "max_issues_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_issues_repo_licenses": ["MIT"], "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/math/num_th_alg.cc", "max_forks_repo_name": "TarekIbnZiad/CryptoImg", "max_forks_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-11T00:32:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T23:35:20.000Z", "avg_line_length": 23.1191709845, "max_line_length": 124, "alphanum_fraction": 0.5490811295, "num_tokens": 2700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.543299352218048}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n//#define GRAPHBLAS_LOGGING_LEVEL 2\n\n#include <graphblas/graphblas.hpp>\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE mxm_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nusing namespace grb;\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n//****************************************************************************\n\nnamespace\n{\n    static std::vector<std::vector<double> > A_dense_3x3 =\n    {{12, 7, 3},\n     {4,  5, 6},\n     {7,  8, 9}};\n\n    static std::vector<std::vector<double> > AT_dense_3x3 =\n    {{12, 4, 7},\n     {7,  5, 8},\n     {3,  6, 9}};\n\n    static std::vector<std::vector<double> > B_dense_3x4 =\n    {{5, 8, 1, 2},\n     {6, 7, 3, 0.},\n     {4, 5, 9, 1}};\n\n    static std::vector<std::vector<double> > BT_dense_3x4 =\n    {{5, 6, 4},\n     {8, 7, 5},\n     {1, 3, 9},\n     {2, 0, 1}};\n\n    static std::vector<std::vector<double> > Answer_dense =\n    {{114, 160, 60,  27},\n     {74,  97,  73,  14},\n     {119, 157, 112, 23}};\n\n    static std::vector<std::vector<double> > Answer_plus1_dense =\n    {{115, 161, 61,  28},\n     {75,  98,  74,  15},\n     {120, 158, 113, 24}};\n\n    static std::vector<std::vector<double> > A_sparse_3x3 =\n    {{12, 7,  0},\n     {0, -5,  0},\n     {7,  0,  9}};\n\n    static std::vector<std::vector<double> > AT_sparse_3x3 =\n    {{12, 0,  7},\n     {7, -5,  0},\n     {0,  0,  9}};\n\n    static std::vector<std::vector<double> > B_sparse_3x4 =\n    {{5., 8.,  0, -2.},\n     {0., -7,  3., 0.},\n     {4., 0,   0,  1.}};\n\n    static std::vector<std::vector<double> > BT_sparse_3x4 =\n    {{5.,  0., 4},\n     {8., -7,  0.},\n     {0.,  3,  0.},\n     {-2., 0,  1}};\n\n    // A_sparse_3x3 * A_sparse_3x3\n    static std::vector<std::vector<double> > AA_answer_sparse =\n    {{144.,  49., 0},\n     {0.0,   25., 0},\n     {147.,  49., 81.}};\n\n    // A_sparse_3x3 * B_sparse_3x4\n    static std::vector<std::vector<double> > Answer_sparse =\n    {{60,   47., 21,  -24},\n     {0.0,  35.,-15,  0.0},\n     {71.0, 56,  0.0, -5.0}};\n\n    static std::vector<std::vector<double> > Symmetric_4x4 =\n    {{1, 1, 0, 0},\n     {1, 2, 2, 0},\n     {0, 2, 3, 3},\n     {0, 0, 3, 4}};\n\n    static std::vector<std::vector<double> > Symmetric2_4x4 =\n    {{2, 3, 2, 0},\n     {3, 9,10, 6},\n     {2,10,22,21},\n     {0, 6,21,25}};\n\n    static std::vector<std::vector<double> > Ones_4x4 =\n    {{1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > Ones_3x4 =\n    {{1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > Ones_3x3 =\n    {{1, 1, 1},\n     {1, 1, 1},\n     {1, 1, 1}};\n\n    static std::vector<std::vector<double> > Identity_3x3 =\n    {{1, 0, 0},\n     {0, 1, 0},\n     {0, 0, 1}};\n\n    static std::vector<std::vector<double> > Lower_3x3 =\n    {{1, 0, 0},\n     {1, 1, 0},\n     {1, 1, 1}};\n\n    static std::vector<std::vector<double> > Lower_3x4 =\n    {{1, 0, 0, 0},\n     {1, 1, 0, 0},\n     {1, 1, 1, 0}};\n\n    static std::vector<std::vector<double> > Lower_4x4 =\n    {{1, 0, 0, 0},\n     {1, 1, 0, 0},\n     {1, 1, 1, 0},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > NotLower_3x3 =\n    {{0, 1, 1},\n     {0, 0, 1},\n     {0, 0, 0}};\n\n    static std::vector<std::vector<double> > NotLower_3x4 =\n    {{0, 1, 1, 1},\n     {0, 0, 1, 1},\n     {0, 0, 0, 1}};\n\n    static std::vector<std::vector<double> > NotLower_4x4 =\n    {{0, 1, 1, 1},\n     {0, 0, 1, 1},\n     {0, 0, 0, 1},\n     {0, 0, 0, 0}};\n\n    static std::vector<std::vector<double> > LowerMask_3x4 =\n    {{1, 0,    0,   0},\n     {1, 0.5,  0,   0},\n     {1, -1.0, 1.5, 0}};\n\n    static std::vector<std::vector<bool> > LowerBool_3x4 =\n    {{true, false, false, false},\n     {true, true,  false, false},\n     {true, true,  true,  false}};\n\n    static std::vector<std::vector<bool> > LowerBool_3x3 =\n    {{true, false, false},\n     {true, true,  false},\n     {true, true,  true}};\n\n    static std::vector<std::vector<bool> > NotLowerBool_3x3 =\n    {{false,  true, true},\n     {false, false, true},\n     {false, false, false}};\n\n}\n\n//****************************************************************************\n// NoMask_NoAccum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT)\n{\n    grb::Matrix<double> C(3, 4);\n    grb::Matrix<double> A(A_sparse_3x3, 0.);\n    grb::Matrix<double> B(BT_sparse_3x4, 0.);\n\n    grb::Matrix<double> answer(Answer_sparse, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    for (grb::IndexType ix = 0; ix < answer.nrows(); ++ix)\n    {\n        for (grb::IndexType iy = 0; iy < answer.ncols(); ++iy)\n        {\n            BOOST_CHECK_EQUAL(C.hasElement(ix, iy), answer.hasElement(ix, iy));\n            if (C.hasElement(ix, iy))\n            {\n                BOOST_CHECK_CLOSE(C.extractElement(ix,iy),\n                                  answer.extractElement(ix,iy), 0.0001);\n            }\n        }\n    }\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT_empty)\n{\n    grb::Matrix<double> Zero(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(Ones_3x3, 0.);\n    grb::Matrix<double> mD(Ones_3x3, 0.);\n\n    grb::mxm(C,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), Zero, transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Zero);\n\n    grb::mxm(mD,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Zero));\n    BOOST_CHECK_EQUAL(mD, Zero);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT_dense)\n{\n    Matrix<double, DirectedMatrixTag> A(A_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(BT_dense_3x4, 0.);\n\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n\n    mxm(result,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        A, transpose(B));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 7, 15},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11, 15}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    std::vector<std::vector<double>> answer_vals = {{0, 8, 0, 8},\n                                                    {0, 1, 0, 1},\n                                                    {0, 4, 0, 4}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT_ABdup)\n{\n    // Build some matrices.\n    Matrix<double, DirectedMatrixTag> mat(Symmetric_4x4, 0.);\n    Matrix<double, DirectedMatrixTag> m3(4, 4);\n    Matrix<double, DirectedMatrixTag> answer(Symmetric2_4x4, 0.);\n\n    mxm(m3,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(m3, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT_ACdup)\n{\n    grb::Matrix<double> C(A_sparse_3x3, 0.);\n    grb::Matrix<double> B(AT_sparse_3x3, 0.);\n\n    grb::Matrix<double> answer(AA_answer_sparse, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, transpose(B));\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT_BCdup)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.);\n    grb::Matrix<double> C(AT_sparse_3x3, 0.);\n\n    grb::Matrix<double> answer(AA_answer_sparse, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n//****************************************************************************\n// NoMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ABT)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.); // 3x3\n    grb::Matrix<double> B(BT_dense_3x4, 0.); // 3x4\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(Answer_dense, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ABT_empty)\n{\n    grb::Matrix<double> Zero(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(Ones_3x3, 0.);\n    grb::Matrix<double> mD(Ones_3x3, 0.);\n\n    grb::mxm(C,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(), Zero, transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    grb::mxm(mD,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Zero));\n    BOOST_CHECK_EQUAL(mD, Ones);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ABT_stored_zero_result)\n{\n    // Build some matrices.\n    std::vector<std::vector<int> > A_mat = {{1, 1, 0, 0},\n                                            {1, 2, 2, 0},\n                                            {0, 2, 3, 3},\n                                            {0, 0, 3, 4}};\n    std::vector<std::vector<int> > BT_mat = {{ 1,-1, 0,  0},\n                                             {-2, 1, 0,  0},\n                                             { 0, 0, 3, -3},\n                                             { 0, 0,-4,  3}};\n    grb::Matrix<int> A(A_mat, 0);\n    grb::Matrix<int> B(BT_mat, 0);\n    grb::Matrix<int> result(4, 4);\n\n    // use a different sentinel value so that stored zeros are preserved.\n    int const NIL(666);\n    std::vector<std::vector<int> > ans = {{  0,  -1, NIL, NIL},\n                                          { -1,   0,   6,  -8},\n                                          { -2,   2,   0,  -3},\n                                          {NIL, NIL,  -3,   0}};\n    grb::Matrix<int> answer(ans, NIL);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<int>(),\n             grb::ArithmeticSemiring<int>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(result, answer);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ABT_ABdup_Cempty)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> result(4, 4);\n    grb::Matrix<double> answer(Symmetric2_4x4, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ABT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> BTvals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    std::vector<std::vector<double>> answer_vals = {{2, 1, 8, 16},\n                                                    {1, 1, 1, 1},\n                                                    {10,1, 12, 16}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(BTvals, 0.);\n    grb::Matrix<double> result(Ones_3x4, 0.);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ABT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> BTvals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    std::vector<std::vector<double>> answer_vals = {{1, 9, 1, 9},\n                                                    {1, 2, 1, 2},\n                                                    {1, 5, 1, 5}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(BTvals, 0.);\n    grb::Matrix<double> result(Ones_3x4, 0.);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ABT_ABdup)\n{\n    // Build some matrices.\n    Matrix<double> mat(A_sparse_3x3,0.);\n    Matrix<double> m3(Ones_3x3, 0.);\n\n    // A_sparse_3x3 * A_sparse_3x3 + Ones\n    static std::vector<std::vector<double> > ans =\n        {{194., -34.,  85.},\n         {-34,   26.,   1.},\n         {85.0,   1,  131.}};\n\n    Matrix<double> answer(ans, 0.);\n\n    mxm(m3,\n        grb::NoMask(), grb::Plus<double>(),\n        grb::ArithmeticSemiring<double>(),\n        mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(m3, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ABT_ACdup)\n{\n    grb::Matrix<double> C(A_sparse_3x3, 0.);\n    grb::Matrix<double> B(AT_sparse_3x3, 0.);\n\n    // A_sparse_3x3 * A_sparse_3x3 + A_sparse_3x3\n    static std::vector<std::vector<double> > ans =\n        {{156.,  56., 0},\n         {0.0,   20., 0},\n         {154.,  49., 90.}};\n    Matrix<double> answer(ans, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, transpose(B));\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ABT_BCdup)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.);\n    grb::Matrix<double> C(A_sparse_3x3, 0.);\n\n    // A_sparse_3x3 * A_sparse_3x3 + A_sparse_3x3\n    static std::vector<std::vector<double> > ans =\n        {{205., -28.,  84.0},\n         {-35,   20.,   0.0},\n         {91.0,   0., 139.0}};\n    Matrix<double> answer(ans, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n// ****************************************************************************\n// Mask_NoAccum\n// ****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ABT)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             Ones, NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, A);\n\n    C = Ones;\n    grb::mxm(C,\n             A, NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             Ones, NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, A);\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ABTM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones));\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty));\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ABT_Merge_full_mask)\n{\n    Matrix<double, DirectedMatrixTag> A(A_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(BT_dense_3x4, 0.);\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n\n    Matrix<double, DirectedMatrixTag> mask(Ones_3x4,0.);\n\n    mxm(result,\n        mask, grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        A, transpose(B));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ABT_mask_not_full)\n{\n    Matrix<double, DirectedMatrixTag> A(A_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(BT_dense_3x4, 0.);\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    Matrix<double, DirectedMatrixTag> mask(Answer_dense, 0.);\n\n    mxm(result,\n        mask, grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        A, transpose(B));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ABT_Merge_Cones_Mlower_stored_zero)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(Lower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ABT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ABT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ABT_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ABT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ABT_ACdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ABT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ABT_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\n// Mask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABT)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             A, Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             Ones, Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABTMempty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones); //ERROR\n\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);; //ERROR\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));; //ERROR\n\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));; //ERROR\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer); //ERROR\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2); //ERROR\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABT_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 1, 8},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer); //ERROR\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 8},\n                                                     {1, 1, 1},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2); //ERROR\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABT_ACdup)\n{\n\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABT_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  0,  0,  0},\n                                             {4, 10,  0,  0},\n                                             {3, 11, 23,  0},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABT_Replace_lower_mask_result_ones)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(LowerMask_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABT_Replace_bool_masked_result_ones)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<bool> M(LowerBool_3x4, false);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABT_Replace_mask_stored_zero_result_ones)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(Lower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B),\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABT_Merge_Cones_Mlower)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > M_3x4 = {{1, 0, 0, 0},\n                                                      {1, 1, 0, 0},\n                                                      {1, 1, 1, 0}};\n    grb::Matrix<double> M(M_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompMask_NoAccum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ABT)\n{\n\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > Not_A_sparse_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_sparse_3x3, 0.0);\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, A); //ERROR\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotA), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, A);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ABT_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> Identity(Identity_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones));\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty));\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Ones);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ABT_Merge_Cones_Mlower_stored_zero)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             complement(M),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ABT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ABT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ABT_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x3, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ABT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ABT_ACdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ABT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ABT_Replace_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    static std::vector<std::vector<double> > Not_A_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_3x3, 0.0);\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotA), Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Empty), Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABTM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> MNotLower(NotLowerBool_3x3, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT_ACdup)\n{\n\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT_Replace_Cones_Mnlower)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B),\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT_Replace_Mstored_zero)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n\n    M.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B),\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT_Merge)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT_Merge_Mstored_zero)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT_Merge_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// Structure tests\n//****************************************************************************\n\n// ****************************************************************************\n// StructMask_NoAccum\n// ****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ABT)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, A);\n    Ones.setElement(0, 0, 1.);\n\n    C = Ones;\n    A.setElement(0, 2, 0.);\n    AFilled.setElement(0, 2, 0.);\n    grb::mxm(C,\n             structure(A), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    MLower.setElement(2, 0, 0.);\n    grb::mxm(C,\n             structure(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    MNotLower.setElement(0, 2, 0.);\n    grb::mxm(C,\n             structure(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, A);\n    Ones.setElement(0, 0, 1.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    MLower.setElement(2, 0, 1.);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    MNotLower.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ABTM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n    M.setElement(2, 0, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones));\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty));\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ABT_Merge_full_mask)\n{\n    Matrix<double, DirectedMatrixTag> A(A_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(BT_dense_3x4, 0.);\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n\n    Matrix<double, DirectedMatrixTag> mask(Ones_3x4,0.);\n    mask.setElement(0, 0, 0.);\n\n    mxm(result,\n        structure(mask), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        A, transpose(B));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ABT_mask_not_full)\n{\n    Matrix<double, DirectedMatrixTag> A(A_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(BT_dense_3x4, 0.);\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    Matrix<double, DirectedMatrixTag> mask(Answer_dense, 0.);\n    mask.setElement(0, 0, 0.);\n\n    mxm(result,\n        structure(mask), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        A, transpose(B));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ABT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ABT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 1, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ABT_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ABT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ABT_ACdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ABT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ABT_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             structure(C),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             structure(C),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\n// StructMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ABT)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    MLower.setElement(2, 0, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n    MNotLower.setElement(0, 1, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mfull vs Mlower\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    A.setElement(0, 2, 0.);\n    grb::mxm(C,\n             structure(A), Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mfull vs Mlower\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ABTMempty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n    M.setElement(2, 0, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Empty), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Empty), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ABT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ABT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ABT_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 1, 8},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer); //ERROR\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 8},\n                                                     {1, 1, 1},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2); //ERROR\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ABT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ABT_ACdup)\n{\n\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ABT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ABT_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  0,  0,  0},\n                                             {4, 10,  0,  0},\n                                             {2, 11, 23,  0},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             structure(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {2, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             structure(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ABT_Replace_lower_mask_result_ones)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(LowerMask_3x4, 0.);\n    M.setElement(2, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             structure(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ABT_Replace_bool_masked_result_ones)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<bool> M(LowerBool_3x4, false);\n    M.setElement(2, 0, false);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             structure(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ABT_Merge_Cones_Mlower)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > M_3x4 = {{1, 0, 0, 0},\n                                                      {1, 1, 0, 0},\n                                                      {1, 1, 1, 0}};\n    grb::Matrix<double> M(M_3x4, 0.);\n    M.setElement(2, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             structure(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompStructMask_NoAccum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ABT)\n{\n\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    MLower.setElement(2, 0, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n    MNotLower.setElement(0, 2, 0.);\n\n    static std::vector<std::vector<double> > Not_A_sparse_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_sparse_3x3, 0.0);\n    NotA.setElement(1, 0, 0.);\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, A);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotA)), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n    Ones.setElement(0, 0, 1.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, A);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    MLower.setElement(2, 0, 1.);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    MNotLower.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ABT_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> Identity(Identity_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n    M.setElement(2, 0, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n    mUpper.setElement(0, 2, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones));\n    mUpper.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    mUpper.setElement(0, 2, 0.);\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty));\n    mUpper.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Ones);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ABT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ABT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ABT_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x3, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Lower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Lower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ABT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ABT_ACdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ABT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ABT_Replace_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n    M.setElement(0, 1, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompStructMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ABT)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    MLower.setElement(2, 0, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n    MNotLower.setElement(0, 2, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    static std::vector<std::vector<double> > Not_A_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_3x3, 0.0);\n    NotA.setElement(1, 0, 0.);\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotA)), Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Empty)), Plus<double>(),\n             ArithmeticSemiring<double>(), A, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ABTM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> MNotLower(NotLowerBool_3x3, false);\n    MNotLower.setElement(0, 2, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    Ones.setElement(0, 2, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Ones));\n    Ones.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    Ones.setElement(0, 2, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ABT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x4, 0.);\n    MNotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ABT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ABT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ABT_ACdup)\n{\n\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ABT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ABT_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  0,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {99, 6, 21, 25}};\n    grb::Matrix<double> answer(ans, 99.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(structure(C)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(structure(C)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ABT_Replace_Cones_Mnlower)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B),\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ABT_Merge)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ABT_Merge_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n    M.setElement(0, 1, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ae40f373864212844ac6d2267c6d95ace7d3f981", "size": 157433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_mxm_ABT.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_mxm_ABT.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_mxm_ABT.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 33.3756624974, "max_line_length": 83, "alphanum_fraction": 0.4542503795, "num_tokens": 43128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5432993520219771}}
{"text": "#include <igl/per_vertex_normals.h>\n#include <igl/principal_curvature.h>\n#include <igl/avg_edge_length.h>\n#include <igl/massmatrix.h>\n#include <igl/adjacency_list.h>\n#include <igl/per_face_normals.h>\n#include <igl/barycenter.h>\n#include <igl/pinv.h>\n#include <igl/edges.h>\n#include <Eigen/SparseCore>\n#include <igl/adjacency_list.h>\n#include <igl/adjacency_matrix.h>\n#include <igl/per_face_normals.h>\n#include <igl/per_vertex_normals.h>\n#include <igl/avg_edge_length.h>\n#include <igl/edge_flaps.h>\n#include <igl/unique_edge_map.h>\n#include <igl/vertex_triangle_adjacency.h>\n#include <igl/principal_curvature.h>\n#include <igl/collapse_edge.h>\n#include <igl/C_STR.h>\n#include <igl/flip_edge.h>\nusing namespace std;\n\nvoid equalize_valences(Eigen::MatrixXd & V,Eigen::MatrixXi & F, Eigen::VectorXi & feature){\n    using namespace igl;\n    using namespace Eigen;\n    VectorXd p;\n    std::vector<bool> is_feature_vertex;\n    Eigen::MatrixXi E,uE,EI,EF;\n    Eigen::VectorXi EMAP;\n    std::vector<std::vector<int>> uE2E,A;\n    igl::unique_edge_map(F,E,uE,EMAP,uE2E);\n    \n    \n    \n    int m = F.rows();\n    int n = V.rows();\n    int a,b,c,d;\n    igl::adjacency_list(E,A);\n    VectorXi vertex_valences;\n//\n    vertex_valences.setZero(n);\n    \n   // std::cout << \"A\" << std::endl;\n    for(int j = 0; j < m; j++){\n        vertex_valences(F(j,0)) = vertex_valences(F(j,0))+1;\n        vertex_valences(F(j,1)) = vertex_valences(F(j,1))+1;\n        vertex_valences(F(j,2)) = vertex_valences(F(j,2))+1;\n    }\n //   std::cout << vertex_valences << std::endl;\n    \n//\n    int k = uE.rows();\n    int num_feat = feature.size();\n    is_feature_vertex.resize(n);\n    \n   // std::cout << \"B\" << std::endl;\n    \n    for (int s = 0; s < num_feat; s++) {\n        is_feature_vertex[feature(s)] = true;\n    }\n    \n    \n//\n  //  std::cout << \"C\" << std::endl;\n    \n    std::function<void(\n            Eigen::MatrixXi &, //F\n            Eigen::MatrixXi &, //E\n            Eigen::MatrixXi &, //uE\n            Eigen::VectorXi &, //EMAP\n            std::vector<std::vector<int>>  &, //uE2E\n            int &)> flip_edge_adjacency = [&vertex_valences,&V,&A](\n            Eigen::MatrixXi & F, //F\n            Eigen::MatrixXi & E, //E\n            Eigen::MatrixXi & uE, //uE\n            Eigen::VectorXi & EMAP, //EMAP\n            std::vector<std::vector<int>>  & uE2E, //uE2E\n            int & uei)->void{\n      //  std::cout << \"Lambda call\" << std::endl;\n        int num_faces = F.rows();\n        auto& half_edges = uE2E[uei];\n        int f1 = half_edges[0] % num_faces;\n        int f2 = half_edges[1] % num_faces;\n        int c1 = half_edges[0] / num_faces;\n        int c2 = half_edges[1] / num_faces;\n        assert(c1 < 3);\n        assert(c2 < 3);\n        \n        \n        \n        assert(f1 != f2);\n        int v1 = F(f1, (c1+1)%3);\n        int v2 = F(f1, (c1+2)%3);\n        int v4 = F(f1, c1);\n        int v3 = F(f2, c2);\n        assert(F(f2, (c2+2)%3) == v1);\n        assert(F(f2, (c2+1)%3) == v2);\n        // Assert new triangle's area is nonzero\n          // f1_new\n          double a1 = (V.row(v1)-V.row(v3)).norm();\n          double b1 = (V.row(v1)-V.row(v4)).norm();\n          double c11 = (V.row(v4)-V.row(v3)).norm();\n          double s1 = (a1+b1+c11)/2;\n          double area_1_squared = s1*(s1-a1)*(s1-b1)*(s1-c11);\n          // f2_new\n          double a2 = (V.row(v2)-V.row(v3)).norm();\n          double b2 = (V.row(v2)-V.row(v4)).norm();\n          double c22 = (V.row(v4)-V.row(v3)).norm();\n          double s2 = (a2+b2+c22)/2;\n          double area_2_squared = s2*(s2-a2)*(s2-b2)*(s2-c22);\n          bool bad = false;\n          \n          Eigen::RowVector3d v21,v31,v41,v24,v34,v43,v23,normf10,normf11,\n                  normf12,normf20,normf21,normf22;\n          v21 = V.row(v2)-V.row(v1);\n          v31 = V.row(v3)-V.row(v1);\n          v41 = V.row(v4)-V.row(v1);\n          v24 = V.row(v2)-V.row(v4);\n          v34 = V.row(v3)-V.row(v4);\n          v43 = V.row(v4)-V.row(v3);\n          v23 = V.row(v2)-V.row(v3);\n          normf10 = v21.cross(v31);\n          normf11 = v41.cross(v31);\n          normf12 = v24.cross(v34);\n          normf20 = v41.cross(v21);\n          normf21 = v43.cross(v23);\n          normf22 = v41.cross(v31);\n          normf10.normalize();\n          normf11.normalize();\n          normf12.normalize();\n          normf20.normalize();\n          normf21.normalize();\n          normf22.normalize();\n          \n          if (normf10.dot(normf11) < normf11.norm()/2 || normf10.dot(normf12) < normf12.norm()/2) {\n              bad = true;\n          }\n          if (normf20.dot(normf21) < normf21.norm()/2 || normf20.dot(normf22) < normf22.norm()/2) {\n              bad = true;\n          }\n\n        if (area_1_squared == 0) {\n            bad = true;\n        }\n        if (area_2_squared == 0) {\n            bad = true;\n        }\n                \n                if(std::count(A[v3].begin(),A[v3].end(),v4)){\n                    bad = true; // is it gonna generate non-manifold??\n                }\n        \n        if(uE2E[uei].size() != 2){\n            bad = true;\n            }\n        \n        \n         if (!bad){\n             //std::cout << \"D1\" << std::endl;\n        igl::flip_edge(F,E,uE,EMAP,uE2E,uei);\n             //std::cout << \"D2\" << std::endl;\n        //std::cout << \"Lambda call test\" << std::endl;\n        assert(uE(uei,0)==v3);\n        assert(uE(uei,1)==v4);\n        \n      //  std::cout << \"updating_valences\" << std::endl;\n        vertex_valences(v1) = vertex_valences(v1)-1;\n        vertex_valences(v2) = vertex_valences(v2)-1;\n        vertex_valences(v3) = vertex_valences(v3)+1;\n        vertex_valences(v4) = vertex_valences(v4)+1;\n             \n             std::remove_if(A[v1].begin(),A[v1].begin(),[&v2](const int & v){return v==v2;});\n             std::remove_if(A[v2].begin(),A[v2].begin(),[&v1](const int & v){return v==v1;});\n             A[v3].push_back(v4);\n             A[v4].push_back(v3);\n             \n         }\n        //std::cout << \"Lambda call end\" << std::endl;\n    };\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    //std::cout << \"D\" << std::endl;\n    \n    \n    for(int i = 0; i < k; i++){\n        //std::cout << uE2E[i].size() << std::endl;\n        if(uE2E[i].size()!=2){\n            continue;\n        }\n        bool is_feature_edge = false;\n        int f1 = uE2E[i][0] % m;\n        int f2 = uE2E[i][1] % m;\n        int c1 = uE2E[i][0] / m;\n        int c2 = uE2E[i][1] / m;\n//        std::cout << f1 << std::endl;\n//        std::cout << f2 << std::endl;\n//        std::cout << c1 << std::endl;\n//        std::cout << c2 << std::endl;\n        int a = F(f1, (c1+1)%3);\n        int b = F(f1, (c1+2)%3);\n        int c = F(f1, c1);\n        int d = F(f2, c2);\n        if (is_feature_vertex[a] || is_feature_vertex[b] || is_feature_vertex[c] || is_feature_vertex[d]) {\n            is_feature_edge = true;\n        }\n        //std::cout << \"E\" << std::endl;\n        \n        if(!is_feature_edge){\n            // FIND VALENCES\n            int deviation_pre = abs(vertex_valences(a)-6)+\n                    abs(vertex_valences(b)-6)+\n                    abs(vertex_valences(c)-6)+\n                    abs(vertex_valences(d)-6);\n//std::cout << i << std::endl;\n            // igl::flip_edge(V,F,E,uE,EMAP,uE2E,i);\n            int deviation_post = abs(vertex_valences(a)-1-6)+\n                    abs(vertex_valences(b)-6-1)+\n                    abs(vertex_valences(c)-6+1)+\n                    abs(vertex_valences(d)-6+1);\n            // std::cout << i << std::endl;\n       //     std::cout << deviation_pre << std::endl;\n       //     std::cout << deviation_post << std::endl;\n            \n            if(deviation_pre > deviation_post){\n                flip_edge_adjacency(F,E,uE,EMAP,uE2E,i);\n            }\n \n        }\n        \n        //std::cout << uE.row(i+1) << std::endl;\n    }\n//    std::cout << flipped << std::endl;\n//    std::cout << k << std::endl;\n//\n  \n    \n    \n    \n    // PLACEHOLDER\n}\n\n\n// g++ -I/usr/local/libigl/external/eigen -I/usr/local/libigl/include -std=c++11 -framework Accelerate main.cpp remesh_botsch.cpp -o main\n\n", "meta": {"hexsha": "c5c88d95dece0e6a3b0d5a627a4a9f329d99ba7c", "size": 8078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/equalize_valences.cpp", "max_stars_repo_name": "sgsellan/opening-and-closing-surfaces", "max_stars_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T00:03:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T19:44:35.000Z", "max_issues_repo_path": "src/equalize_valences.cpp", "max_issues_repo_name": "sgsellan/opening-and-closing-surfaces", "max_issues_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/equalize_valences.cpp", "max_forks_repo_name": "sgsellan/opening-and-closing-surfaces", "max_forks_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-27T01:40:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T13:42:16.000Z", "avg_line_length": 31.6784313725, "max_line_length": 137, "alphanum_fraction": 0.4966575885, "num_tokens": 2471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5432385614010965}}
{"text": "#include \"Modeler3D.h\"\n\n#include <cmath>\n#include <iostream>\n\n#include <boost/filesystem.hpp>\n#include <GL/glew.h>\n\n#include \"GUI/AllWidgets.h\"\n#include \"GUI/IAction.h\"\n#include \"Math/ModelerMath.h\"\n\n#include \"FileIO.h\"\n#include \"GuiRenderer.h\"\n#include \"ModelerActions.h\"\n\nusing namespace std;\nusing namespace Core;\nusing namespace Core::Math;\nusing namespace Video;\n\nstd::string VertSource = \"\"\n        \"#version 120 \\n\"\n        \"\"\n        \"attribute vec3 aPosition; \\n\"\n        \"attribute vec3 aNormal; \\n\"\n        \"\"\n        \"varying vec3 vViewPosition; \\n\"\n        \"varying vec3 vNormal; \\n\"\n        \"\"\n        \"uniform mat4 Projection; \\n\"\n        \"uniform mat4 View; \\n\"\n        \"uniform mat4 Model; \\n\"\n        \"uniform mat3 NormalMat; \\n\"\n        \"\"\n        \"void main() \\n\"\n        \"{ \\n\"\n        \"   vNormal = normalize(NormalMat * aNormal); \\n\"\n        \"   gl_Position = View * Model * vec4(aPosition, 1.0); \\n\"\n        \"   vViewPosition = gl_Position.xyz; \\n \"\n        \"   gl_Position = Projection * gl_Position; \\n\"\n        \"} \\n\";\n\nstd::string FragSource = \"\"\n        \"#version 120 \\n\"\n        \"\"\n        \"varying vec3 vViewPosition; \\n\"\n        \"varying vec3 vNormal; \\n\"\n        \"\"\n        \"uniform vec3 LightDirection = vec3(-1, -0.5, -1); \\n\"\n        \"uniform mat4 View; \\n\"\n        \"\"\n        \"uniform vec3 Color; \\n\"\n        \"\"\n        \"float Diffuse(vec3 normal, vec3 lightDir) \\n\"\n        \"{ \\n\"\n        \"   return clamp((dot(normal, -lightDir)), 0.0, 1.0); \\n\"\n        \"} \\n\"\n        \"\"\n        \"float Specular(vec3 normal, vec3 lightDir, vec3 cameraDir, float power) \\n\"\n        \"{ \\n\"\n        \"   vec3 halfVec = normalize(lightDir + cameraDir); \\n\"\n        \"   return pow(clamp(dot(normal, -halfVec), 0.0, 1.0), power); \"\n        \"} \\n\"\n        \"\"\n        \"void main() \\n\"\n        \"{ \\n\"\n        \"   vec3 normal = normalize((View * vec4(vNormal, 0.0)).xyz); \\n\"\n        \"   vec3 lightDir = normalize((View * vec4(LightDirection, 1.0)).xyz); \\n\"\n        \"   vec3 cameraDir = normalize(vViewPosition); \\n\"\n        \"\"\n        \"   float diffuse = Diffuse(normal, lightDir); \\n\"\n        \"   float specular = Specular(normal, lightDir, cameraDir, 100); \\n\"\n        \"\"\n        \"   gl_FragColor = vec4(Color * (diffuse * 0.4 + 0.4 + specular * 0.4), 1.0); \\n\"\n        \"} \\n\";\n\nVideo::IShader* Shader = nullptr;\n\nfloat Angle = 0.0f;\n\nnamespace Core\n{\n\nVideo::VertexFormat vboFormat = Video::VertexFormat()\n        .AddElement(Video::Attribute::Position, 3)\n        .AddElement(Video::Attribute::Normal, 3);\n\nstruct VertexPosition3Normal3\n{\n    Vector3f Position;\n    Vector3f Normal;\n};\n\nModeler3D::Modeler3D(IBackend* backend)\n    : Application(backend),\n      mEnv(nullptr),\n      mGuiRenderer(nullptr),\n      mShader(nullptr),\n      mGeometry(nullptr),\n      mVbo(nullptr),\n      mAngle(0),\n\t  mMouse(backend->GetWindow()->GetMouse()),\n\t  mCamera(new Camera(backend->GetWindow()->GetWidth(),backend->GetWindow()->GetHeight(), Math::Vector3f(0,0,1), Math::Quaternionf())),\n\t  mZoom(2),\n\t  mColor(Vector3f(0.8, 0.6, 0.4)),\n\t  mScale(Vector3f(1)) {}\n\nModeler3D::~Modeler3D() {}\n\nvoid Modeler3D::LoadObj(const string& file)\n{\n    boost::filesystem::path obj(file);\n\n\tFileIO objFile;\n\n\tvector<VertexPosition3Normal3> vertices;\n\n    std::vector<std::vector<double>> positions;\n    std::vector<std::vector<double>> textures;\n    std::vector<std::vector<double>> normals;\n    std::vector<std::vector<std::vector<int>>> faces;\n\n    objFile.LoadObj2(obj , positions, textures, normals, faces);\n\n    for (uint i = 0; i < faces.size(); i++)\n    {\n        VertexPosition3Normal3 verts[3];\n        for (uint j = 0; j < 3; j++)\n        {\n            vector<double> pos = positions[faces[i][j][0] - 1];\n\n            for (uint k = 0; k < 3; k++)\n            {\n                verts[j].Position[k] = pos[k] * 1.5;\n            }\n        }\n\n        Vector3f normal = Cross(Normalize( verts[1].Position -  verts[0].Position), Normalize( verts[2].Position -  verts[0].Position));\n        verts[0].Normal = normal;\n        verts[1].Normal = normal;\n        verts[2].Normal = normal;\n\n        vertices.push_back(verts[0]);\n        vertices.push_back(verts[1]);\n        vertices.push_back(verts[2]);\n    }\n\n    mVbo = Graphics->CreateVertexBuffer(vboFormat, vertices.size(), Video::BufferHint::Static);\n    mVbo->SetData((float32*)(&vertices[0]), 0, vertices.size());\n    mGeometry->SetVertexBuffer(mVbo);\n}\n\nvoid Modeler3D::OnInit()\n{\n    cout << \"Initializing Modeler3D\" << endl;\n\n    mGeometry = Graphics->CreateGeometry();\n\n    mEnv = Backend->GetWindow()->GetEnvironment();\n    mGuiRenderer = new GuiRenderer(Graphics);\n    mShader = Graphics->CreateShader(VertSource, FragSource);\n\n    Video::ITexture2D* tex = Graphics->CreateTexture2D(\"Assets/button.png\");\n    mGuiRenderer->SetTexture(tex);\n\n    //Create load buttons\n    Gui::Widget* LoadButton1 = new Gui::Button(10, 10 + 50 * 0, 80, 40, new LoadAction(this, \"Assets/bunny.obj\"), \"bunny\");\n    Gui::Widget* LoadButton2 = new Gui::Button(10, 10 + 50 * 1, 80, 40, new LoadAction(this, \"Assets/cube.obj\"), \"cube\");\n    Gui::Widget* LoadButton3 = new Gui::Button(10, 10 + 50 * 2, 80, 40, new LoadAction(this, \"Assets/dragon-big.obj\"), \"dragon\");\n    Gui::Widget* LoadButton4 = new Gui::Button(10, 10 + 50 * 3, 80, 40, new LoadAction(this, \"Assets/ferrari.obj\"), \"ferrari\");\n\n    //Create zoom buttons\n    Gui::Widget* ZoomButton1 = new Gui::Button(10, 10 + 50 * 0,96,40, new ZoomAction(this, mCamera, 1), \"Zoom 1x\");\n    Gui::Widget* ZoomButton2 = new Gui::Button(10, 10 + 50 * 1,96,40, new ZoomAction(this, mCamera, 50), \"Zoom 50x\");\n    Gui::Widget* ZoomButton3 = new Gui::Button(10, 10 + 50 * 2,96,40, new ZoomAction(this, mCamera, 300), \"Zoom 300x\");\n    Gui::Widget* ZoomButton4 = new Gui::Button(10, 10 + 50 * 3,96,40, new ZoomAction(this, mCamera, 1000), \"Zoom 1000x\");\n\n    //Create rotation buttons\n//    Gui::Widget* RotatePitchNegButton = new Gui::Button(10 + 106 * 0, 10 + 58 * 0,96,48, new RotateAction(this, mCamera, 1, -1), \"Up\");\n//    Gui::Widget* RotatePitchPosButton = new Gui::Button(10 + 106 * 1, 10 + 58 * 0,96,48, new RotateAction(this, mCamera,1, 1), \"Down\");\n//    Gui::Widget* RotateYawNegButton = new Gui::Button(10 + 106 * 0, 10 + 58 * 1,96,48, new RotateAction(this, mCamera, 2, -1), \"Left\");\n//    Gui::Widget* RotateYawPosButton = new Gui::Button(10 + 106 * 1, 10 + 58 * 1,96,48, new RotateAction(this, mCamera,2, 1), \"Right\");\n\n    //Create color changing buttons\n    Gui::Widget* PlusRButton = new Gui::Button(10 + 40 * 0, 10 + 50 * 1,30,40, new ChangeColorAction(this, 0, .05), \"+R\");\n    Gui::Widget* MinusRButton = new Gui::Button(10 + 40 * 0, 10 + 50 * 0,30,40, new ChangeColorAction(this, 0, -.05), \"-R\");\n    Gui::Widget* PlusGButton = new Gui::Button(10 + 40 * 1, 10 + 50 * 1,30,40, new ChangeColorAction(this, 1, .05), \"+G\");\n    Gui::Widget* MinusGButton = new Gui::Button(10 + 40 * 1, 10 + 50 * 0,30,40, new ChangeColorAction(this, 1, -.05), \"-G\");\n    Gui::Widget* PlusBButton = new Gui::Button(10 + 40 * 2, 10 + 50 * 1,30,40, new ChangeColorAction(this, 2, .05), \"+B\");\n    Gui::Widget* MinusBButton = new Gui::Button(10 + 40 * 2, 10 + 50 * 0,30,40, new ChangeColorAction(this, 2, -.05), \"-B\");\n\n    //Create scaling buttons\n    Gui::Widget* DisplayScale = new Gui::Button(10, 20 + 50 * 3, 160, 40, new NoOpAction(), \"Cur. Scale: 1x\");\n    Gui::Widget* PlusScaleButton = new Gui::Button(10 + 60, 20 + 50 * 2, 50, 40, new ScaleAction(this, .1, DisplayScale), \"+.1x\");\n    Gui::Widget* MinusScaleButton = new Gui::Button(10, 20 + 50 * 2,50, 40, new ScaleAction(this, -.1, DisplayScale), \"-.1x\");\n\n    //Create view buttons\n    Gui::Widget* ResetCameraButton = new Gui::Button(10, 10 + 50 * 0, 144,40, new ResetAction(this, mCamera), \"Reset Camera\");\n    Gui::Widget* ToggleProjectionTypeButton = new Gui::Button(10, 10 + 50 * 1, 144,40, new ChangeViewAction(this, mCamera), \"To Orthographic\");\n\n    //Create screen\n    Gui::Screen* Screen = new Gui::Screen(new ScreenMoveAction(this));\n\n    //Set alignments\n    LoadButton1->SetAlignment(0, 1);\n    LoadButton2->SetAlignment(0, 1);\n    LoadButton3->SetAlignment(0, 1);\n    LoadButton4->SetAlignment(0, 1);\n\n    ZoomButton1->SetAlignment(1, 1);\n    ZoomButton2->SetAlignment(1, 1);\n    ZoomButton3->SetAlignment(1, 1);\n    ZoomButton4->SetAlignment(1, 1);\n\n//    RotatePitchNegButton->SetAlignment(0, 0);\n//    RotatePitchPosButton->SetAlignment(0, 0);\n//    RotateYawNegButton->SetAlignment(0, 0);\n//    RotateYawPosButton->SetAlignment(0, 0);\n\n    PlusRButton->SetAlignment(0, 0);\n    MinusRButton->SetAlignment(0, 0);\n    PlusGButton->SetAlignment(0, 0);\n    MinusGButton->SetAlignment(0, 0);\n    PlusBButton->SetAlignment(0, 0);\n    MinusBButton->SetAlignment(0, 0);\n\n    DisplayScale->SetAlignment(1, 0);\n    PlusScaleButton->SetAlignment(1, 0);\n    MinusScaleButton->SetAlignment(1, 0);\n\n    ResetCameraButton->SetAlignment(1, 0);\n    ToggleProjectionTypeButton->SetAlignment(1, 0);\n\n    //Add buttons to the environment\n    mEnv->AddWidget(LoadButton1);\n    mEnv->AddWidget(LoadButton2);\n    mEnv->AddWidget(LoadButton3);\n    mEnv->AddWidget(LoadButton4);\n\n    mEnv->AddWidget(ZoomButton1);\n    mEnv->AddWidget(ZoomButton2);\n    mEnv->AddWidget(ZoomButton3);\n    mEnv->AddWidget(ZoomButton4);\n\n//    mEnv->AddWidget(RotatePitchNegButton);\n//    mEnv->AddWidget(RotatePitchPosButton);\n//    mEnv->AddWidget(RotateYawNegButton);\n//    mEnv->AddWidget(RotateYawPosButton);\n\n    mEnv->AddWidget(PlusRButton);\n    mEnv->AddWidget(MinusRButton);\n    mEnv->AddWidget(PlusGButton);\n    mEnv->AddWidget(MinusGButton);\n    mEnv->AddWidget(PlusBButton);\n    mEnv->AddWidget(MinusBButton);\n\n    mEnv->AddWidget(DisplayScale);\n    mEnv->AddWidget(PlusScaleButton);\n    mEnv->AddWidget(MinusScaleButton);\n\n    mEnv->AddWidget(ResetCameraButton);\n    mEnv->AddWidget(ToggleProjectionTypeButton);\n\n    //Set up the screen\n    mEnv->AddWidget(Screen);\n}\n\nvoid Modeler3D::OnUpdate(float64 dt)\n{\n    mAngle += 1.0 * dt;\n\n    //Scroll wheel to zoom\n\tint32 amt = mMouse->GetWheelScroll();\n\tfloat32 zoom = 1.1;\n\tif (amt < 0)\n\t{\n\t    mZoom *= zoom;\n\t}\n\telse if (amt > 0)\n\t{\n\t    mZoom /= zoom;\n\t}\n\n\tmCamera->SetPosition(Normalize(mCamera->GetPosition()) * mZoom);\n\n    mEnv->SetSize(Window->GetWidth(), Window->GetHeight());\n    mEnv->Update(dt);\n}\n\nvoid Modeler3D::OnRender()\n{\n    Graphics->SetClearColor(0.3, 0.3, 0.3);\n    Graphics->Clear();\n\n    if (mVbo) //if vertices are set, render\n    {\n    \tCamera::Projection proj = mCamera->GetProjectionType();\n    \tMatrix4f projection;\n    \tif(proj == Camera::Projection::PERSPECTIVE) projection = mCamera->GetProjection(Math::ToRadians(70.0f), Graphics->GetAspectRatio(), 0.05f, 5000.0f);\n    \telse projection = mCamera->GetProjection(-6000.0f * mZoom, 6000.0f * mZoom, 10 * Window->GetAspectRatio() * mZoom, -10 * Window->GetAspectRatio() * mZoom, 10 * mZoom, -10 * mZoom);\n\n        Matrix4f view = mCamera->GetView();\n\n        Matrix4f model = Matrix4f::Identity * Matrix4f::ToScale(mScale);\n//        Matrix4f model = Matrix4f::ToYaw(mAngle) * Matrix4f::ToPitch(mAngle * 1.3) * Matrix4f::ToRoll(mAngle * 1.7);// * Matrix4f::ToTranslation(Vector3f(0.2, -0.8, 0));\n\n        Matrix3f normalMat(Inverse(Transpose(model)));\n\n        mShader->SetMatrix4f(\"Projection\", projection);\n        mShader->SetMatrix4f(\"View\", view);\n        mShader->SetMatrix4f(\"Model\", model);\n        mShader->SetMatrix3f(\"NormalMat\", normalMat);\n        mShader->SetVector3f(\"Color\", mColor);\n\n        Graphics->SetShader(mShader);\n        Graphics->SetGeometry(mGeometry);\n\n        Graphics->Draw(Video::Primitive::TriangleList, 0, mVbo->GetLength() / 3);\n    }\n\n    mGuiRenderer->Reset();\n    mEnv->Draw(mGuiRenderer);\n}\n\nvoid Modeler3D::SetZoom(float32 zoom) { mZoom = zoom; }\n\nvoid Modeler3D::SetColor(Math::Vector3f color) { mColor = color; }\n\nvoid Modeler3D::SetScale(Math::Vector3f scale) { mScale = scale; }\n\nvoid Modeler3D::OnDestroy()\n{\n    cout << \"Destroying Modeler3D\" << endl;\n    mGuiRenderer->Release();\n    mShader->Release();\n    mGeometry->SetVertexBuffer(nullptr);\n    mGeometry->Release();\n    if(mVbo)\n    \tmVbo->Release();\n}\n\n}\n", "meta": {"hexsha": "fd33a8cf4c4a7bce6cb1be8bca3155cea1e3bded", "size": 12105, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/Modeler3D.cpp", "max_stars_repo_name": "nhamil/modeler-3d", "max_stars_repo_head_hexsha": "1f5bb3a16cdfc25db1081d8df461685385fa88c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-29T23:41:45.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-29T23:41:45.000Z", "max_issues_repo_path": "Source/Modeler3D.cpp", "max_issues_repo_name": "nhamil/modeler-3d", "max_issues_repo_head_hexsha": "1f5bb3a16cdfc25db1081d8df461685385fa88c4", "max_issues_repo_licenses": ["MIT"], "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/Modeler3D.cpp", "max_forks_repo_name": "nhamil/modeler-3d", "max_forks_repo_head_hexsha": "1f5bb3a16cdfc25db1081d8df461685385fa88c4", "max_forks_repo_licenses": ["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.1889534884, "max_line_length": 185, "alphanum_fraction": 0.6263527468, "num_tokens": 3836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5432385546877846}}
{"text": "/**\n * This program uses NTL:\n * http://shoup.net/ntl/\n */\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <NTL/GF2X.h>\n#include <NTL/vec_GF2.h>\n#include <NTL/GF2XFactoring.h>\n#include <errno.h>\n#include <openssl/sha.h>\nextern \"C\" {\n#include \"mtgp32-fast.h\"\n#include \"mtgp64-fast.h\"\n}\n\nusing namespace NTL;\nusing namespace std;\n\nstatic void u32_poly_check(int mexp, int no, int seed);\nstatic void u64_poly_check(int mexp, int no, int seed);\nstatic void poly_sha1(string& str, unsigned char sha1[], const GF2X& poly);\nstatic void poly_check(vec_GF2& vec, int mexp, unsigned char param_sha1[]);\n\nint main(int argc, char *argv[]) {\n    int bit_size;\n    int mexp;\n    int no;\n    uint32_t seed = 1;\n\n    if (argc <= 3) {\n\tcout << argv[0] << \": bit_size mexp no.\" << endl;\n\treturn 1;\n    }\n    bit_size = strtol(argv[1], NULL, 10);\n    if (errno) {\n\tcout << argv[0] << \": bit_size error.\" << endl;\n\treturn 1;\n    }\n    if (bit_size != 32 && bit_size != 64) {\n\tcout << argv[0] << \": bit_size error. bit size is 32 or 64\" << endl;\n\treturn 1;\n    }\n    mexp = strtol(argv[2], NULL, 10);\n    if (errno) {\n\tcout << argv[0] << \": mexp no.\" << endl;\n\treturn 1;\n    }\n    no = strtol(argv[3], NULL, 10);\n    if (errno) {\n\tcout << argv[0] << \": mexp no.\\n\" << endl;\n\treturn 3;\n    }\n    if (bit_size == 32) {\n\tu32_poly_check(mexp, no, seed);\n    } else {\n\tu64_poly_check(mexp, no, seed);\n    }\n    return 0;\n}\n\nstatic void poly_sha1(string& str, unsigned char sha1[], const GF2X& poly) {\n    SHA_CTX ctx;\n    SHA1_Init(&ctx);\n    if (deg(poly) < 0) {\n\tSHA1_Update(&ctx, \"-1\", 2);\n    }\n    for(int i = 0; i <= deg(poly); i++) {\n\tif(rep(coeff(poly, i)) == 1) {\n\t    SHA1_Update(&ctx, \"1\", 1);\n\t} else {\n\t    SHA1_Update(&ctx, \"0\", 1);\n\t}\n    }\n    unsigned char md[SHA_DIGEST_LENGTH];\n    SHA1_Final(md, &ctx);\n    stringstream ss;\n    for (int i = 0; i < SHA_DIGEST_LENGTH; i++) {\n\tss << setfill('0') << setw(2) << hex\n\t   << static_cast<int>(md[i]);\n\tsha1[i] = md[i];\n    }\n    sha1[SHA_DIGEST_LENGTH] = 0;\n    ss >> str;\n}\n\nstatic void poly_check(vec_GF2& vec, int mexp, unsigned char param_sha1[]) {\n    GF2X poly;\n    string s;\n    unsigned char sha1[SHA_DIGEST_LENGTH + 1];\n\n    MinPolySeq(poly, vec, mexp);\n    poly_sha1(s, sha1, poly);\n    cout << s << endl;\n    if (strcmp((char *)sha1, (char *)param_sha1) == 0) {\n\tcout << \"poly sha1 OK\" << endl;\n    } else {\n\tcout << \"poly sha1 NG\" << endl;\n    }\n    if (deg(poly) == mexp) {\n\tcout << \"poly deg = \" << deg(poly) << \" OK\" << endl;\n    } else {\n\tcout << \"poly deg = \" << deg(poly) << \" NG\" << endl;\n    }\n    if (IterIrredTest(poly)) {\n\tcout << \"poly irreducible OK\" << endl;\n    } else {\n\tcout << \"poly irreducible OK\" << endl;\n    }\n}\n\nstatic void u32_poly_check(int mexp, int no, int seed) {\n    mtgp32_params_fast_t *params;\n    mtgp32_fast_t mtgp32;\n    vec_GF2 vec;\n    int rc;\n\n    switch (mexp) {\n    case 11213:\n\tparams = mtgp32_params_fast_11213;\n\tbreak;\n    case 23209:\n\tparams = mtgp32_params_fast_23209;\n\tbreak;\n    case 44497:\n\tparams = mtgp32_params_fast_44497;\n\tbreak;\n    default:\n\tcout << \"mexp shuould be 11213, 23209 or 44497\" << endl;\n\texit(1);\n    }\n    if (no >= 128 || no < 0) {\n\tcout << \"no must be between 0 and 127\" << endl;\n\texit(1);\n    }\n    params += no;\n    rc = mtgp32_init(&mtgp32, params, seed);\n    if (rc) {\n\tcout << \"failure in mtgp32_init\" << endl;\n\texit(1);\n    }\n    mtgp32_print_idstring(&mtgp32, stdout);\n    vec.SetLength(2 * mexp);\n    for (int i = 0; i < 2 * mexp; i++) {\n\tvec[i] = mtgp32_genrand_uint32(&mtgp32) & 1;\n    }\n    poly_check(vec, mexp, mtgp32.params.poly_sha1);\n    mtgp32_free(&mtgp32);\n}\n\nstatic void u64_poly_check(int mexp, int no, int seed) {\n    mtgp64_params_fast_t *params;\n    mtgp64_fast_t mtgp64;\n    vec_GF2 vec;\n    int rc;\n\n    switch (mexp) {\n    case 23209:\n\tparams = mtgp64_params_fast_23209;\n\tbreak;\n    case 44497:\n\tparams = mtgp64_params_fast_44497;\n\tbreak;\n    case 110503:\n\tparams = mtgp64_params_fast_110503;\n\tbreak;\n    default:\n\tcout << \"mexp shuould be 11213, 23209 or 44497\" << endl;\n\texit(1);\n    }\n    if (no >= 128 || no < 0) {\n\tcout << \"no must be between 0 and 127\" << endl;\n\texit(1);\n    }\n    params += no;\n    rc = mtgp64_init(&mtgp64, params, seed);\n    if (rc) {\n\tcout << \"failure in mtgp64_init.\" << endl;\n\texit(1);\n    }\n    mtgp64_print_idstring(&mtgp64, stdout);\n    vec.SetLength(2 * mexp);\n    for (int i = 0; i < 2 * mexp; i++) {\n\tvec[i] = mtgp64_genrand_uint64(&mtgp64) & 1;\n    }\n    poly_check(vec, mexp, mtgp64.params.poly_sha1);\n    mtgp64_free(&mtgp64);\n}\n", "meta": {"hexsha": "ca1f8bee9074998301d2574a7241b8006c9fe7ce", "size": 4549, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/MTGP-src-1.1/tools/check-poly.cpp", "max_stars_repo_name": "vadmus/cuda_examples", "max_stars_repo_head_hexsha": "ba09fe2f2274d89eb38d57bde9063d77ae789a7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-06-08T03:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T14:32:35.000Z", "max_issues_repo_path": "utils/MTGP-src-1.1/tools/check-poly.cpp", "max_issues_repo_name": "bh6025/CUDA-training", "max_issues_repo_head_hexsha": "ba09fe2f2274d89eb38d57bde9063d77ae789a7e", "max_issues_repo_licenses": ["MIT"], "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/MTGP-src-1.1/tools/check-poly.cpp", "max_forks_repo_name": "bh6025/CUDA-training", "max_forks_repo_head_hexsha": "ba09fe2f2274d89eb38d57bde9063d77ae789a7e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2015-11-13T12:21:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T06:15:11.000Z", "avg_line_length": 23.8167539267, "max_line_length": 76, "alphanum_fraction": 0.593097384, "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5432385513311284}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2017-2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DENSIFY_HPP\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DENSIFY_HPP\n\n\n#include <boost/geometry/algorithms/detail/convert_point_to_point.hpp>\n#include <boost/geometry/algorithms/detail/signed_size_type.hpp>\n#include <boost/geometry/arithmetic/arithmetic.hpp>\n#include <boost/geometry/arithmetic/cross_product.hpp>\n#include <boost/geometry/arithmetic/dot_product.hpp>\n#include <boost/geometry/arithmetic/normalize.hpp>\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/formulas/spherical.hpp>\n#include <boost/geometry/formulas/interpolate_point_spherical.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/srs/sphere.hpp>\n#include <boost/geometry/strategies/densify.hpp>\n#include <boost/geometry/strategies/spherical/get_radius.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace densify\n{\n\n\n/*!\n\\brief Densification of spherical segment.\n\\ingroup strategies\n\\tparam RadiusTypeOrSphere \\tparam_radius_or_sphere\n\\tparam CalculationType \\tparam_calculation\n\n\\qbk{\n[heading See also]\n[link geometry.reference.algorithms.densify.densify_4_with_strategy densify (with strategy)]\n}\n */\ntemplate\n<\n    typename RadiusTypeOrSphere = double,\n    typename CalculationType = void\n>\nclass spherical\n{\npublic:\n    typedef typename strategy_detail::get_radius\n        <\n            RadiusTypeOrSphere\n        >::type radius_type;\n\n    // For consistency with area strategy the radius is set to 1\n    inline spherical()\n        : m_radius(1.0)\n    {}\n\n    template <typename RadiusOrSphere>\n    explicit inline spherical(RadiusOrSphere const& radius_or_sphere)\n        : m_radius(strategy_detail::get_radius\n                    <\n                        RadiusOrSphere\n                    >::apply(radius_or_sphere))\n    {}\n\n    template <typename Point, typename AssignPolicy, typename T>\n    inline void apply(Point const& p0, Point const& p1, AssignPolicy & policy, T const& length_threshold) const\n    {\n        typedef typename AssignPolicy::point_type out_point_t;\n        typedef typename select_most_precise\n            <\n                typename coordinate_type<Point>::type,\n                typename coordinate_type<out_point_t>::type,\n                CalculationType\n            >::type calc_t;\n\n        calc_t angle01;\n\n        formula::interpolate_point_spherical<calc_t> formula;\n        formula.compute_angle(p0, p1, angle01);\n\n        BOOST_GEOMETRY_ASSERT(length_threshold > T(0));\n\n        signed_size_type n = signed_size_type(angle01 * m_radius / length_threshold);\n        if (n <= 0)\n            return;\n\n        formula.compute_axis(p0, angle01);\n\n        calc_t step = angle01 / (n + 1);\n\n        calc_t a = step;\n        for (signed_size_type i = 0 ; i < n ; ++i, a += step)\n        {\n            out_point_t p;\n            formula.compute_point(a, p);\n\n            geometry::detail::conversion::point_to_point\n                <\n                    Point, out_point_t,\n                    2, dimension<out_point_t>::value\n                >::apply(p0, p);\n\n            policy.apply(p);\n        }\n    }\n\n    inline radius_type radius() const\n    {\n        return m_radius;\n    }\n\nprivate:\n    radius_type m_radius;\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <>\nstruct default_strategy<spherical_equatorial_tag>\n{\n    typedef strategy::densify::spherical<> type;\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::densify\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DENSIFY_HPP\n", "meta": {"hexsha": "8b14f7ae64d52a6b3913ef1180c1fffa95d1ecc0", "size": 4193, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/geometry/strategies/spherical/densify.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/geometry/strategies/spherical/densify.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/geometry/strategies/spherical/densify.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 27.5855263158, "max_line_length": 111, "alphanum_fraction": 0.6987836871, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5432385448423163}}
{"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_CBRT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_CBRT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-exponential\n    This function object returns the cubic root of its argument: \\f$\\sqrt[3]{x}\\f$\n\n    @par Header <boost/simd/function/cbrt.hpp>\n\n    @par Decorators\n\n      - std_ for floating entries calls @c std::cbrt\n\n    @see pow, sqrt\n\n\n    @par Example:\n\n      @snippet cbrt.cpp cbrt\n\n    @par Possible output:\n\n      @snippet cbrt.txt cbrt\n\n  **/\n  IEEEValue cbrt(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/cbrt.hpp>\n#include <boost/simd/function/simd/cbrt.hpp>\n\n#endif\n", "meta": {"hexsha": "81ee790447a75626f38a5bd23bf17c488a937076", "size": 1076, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/cbrt.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/function/cbrt.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/function/cbrt.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": 22.4166666667, "max_line_length": 100, "alphanum_fraction": 0.5734200743, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.640635841117624, "lm_q1q2_score": 0.5432385381290045}}
{"text": "//============================================================================\n// Name        : TCN 5080 Secure Telecom Transaction. Project 1\n// Author      :  Abhaykumar Kumbhar 5115320 \n// Version     :\n// File name:  : tcn5080project1.cpp\n// Description : Main function for simplifies DES encrption/decrption.\n//============================================================================\n\n\n//system defined header inclusion\n#include <iostream>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string>\n#include <boost/algorithm/string.hpp> //used in string compare operation\n\n//user defined header inclusion\n#include \"utility.h\"\n#include \"defs.h\"\n#include \"des.h\"\n\n//Namespace\nusing namespace std;\n\n//Macros \n\n//global variables\nutility* myUtility;\ndes* myDes;\n\nint main(int argc, char *argv[]) {\n\n\n\tif(argc != NUM_OF_INPUT_PARAMS ) \n\t{\n\t\tcerr << \"ERROR: Main Func: Not enough parameters.\" << endl;\n\t}\n\telse \n\t{\n\t\t// Read all the user inputs and save it in variables \n//\t\tclog << \"DEBUG: Main Func: valid number of parameters.\" << endl;\n\t\tstring desTask        = argv[1]; \n\t\tstring initKey        = argv[2];\n\t\tstring initVector     = argv[3];\n\t\tstring plaintextFile  = argv[4];\n\t\tstring ciphertextFile = argv[5];\n\t\t\n\t\t// convert the file names from string to char\n\t\tchar *cipherBinaryFile = &ciphertextFile[0u];\n\t\tchar *plainBinaryFile  = &plaintextFile[0u];\n\t\n\t\tcout << \"INFO: Main func: user inputs are: \\r\\n\" <<\"Encrypt\\\\Decrypt: \" << desTask << \"\\r\\ninitial key:\\t\" << initKey \n\t\t<<\" \\r\\ninitial Vector\\t\" << initVector << \"\\r\\nplain text file name\\t\" << plainBinaryFile << \"\\r\\ncipher text file name \\t\" << cipherBinaryFile << endl;\n\t\t\n\t\t\n\t\t// create the utilily and DES class \n\t\tmyUtility =  new utility();\n\t\tmyDes = new des();\n\t\t\n\t\tif ((myUtility != NULL) and (myDes != NULL))\n\t\t{\n\t\t\t\n\n\n\n\t\t\t//Based on the user input, we either encrypt or decrypt or do nothing.\n\t\t\tif (boost::iequals(desTask, \"encrypt\"))\n\t\t\t{\n\t\t\t\tclog << \"DEBUG: Main func: user input task is to encrpyt the binary text\"<<endl;\n\t\t\t\t//Main func: Read the  Binary input from plain text file.\n\t\t\t        myUtility->readPlainTextFile(plainBinaryFile);\t\t\n\t\t\t\tstring binaryStr8Bit1 = myUtility->getBinaryPlainTextLeft();\n\t\t\t\tclog << \"DEBUG: Main func: first block of 8 bits of plain text: \" << binaryStr8Bit1 << endl;\n\t\t\t\tstring binaryStr8Bit2 = myUtility->getBinaryPlainTextRight();\n\t\t\t\tclog << \"DEBUG: Main func: second block of 8 bits of plain text: \" << binaryStr8Bit2 << endl;\t\t\t\t\t\n\t\t\t\t\n\t\t\t\tif (myUtility->CheckifStringIsBinary(binaryStr8Bit1) and \n\t\t\t\t    myUtility->CheckifStringIsBinary(binaryStr8Bit2) and \n                                    myUtility->CheckifStringIsBinary(initKey))\n\t\t\t\t{\n//\t\t\t\t\tclog<< \"DEBUG: main: Input strings are valid and binary\" << endl;  \n\t\t\t\t\tmyDes->generateRoundKeys(initKey);\n\t\t\t\t\tcout << \"================== SIMPLE S-DES Encrypt ==================\" <<endl; \t\t\t\t\t\n\t\t\t\t\tstring simplifedDes1 = myDes->encrypt(binaryStr8Bit1);\n\t\t\t\t        string simplifedDes2 = myDes->encrypt(binaryStr8Bit2);\n\n\t\t\t\t\tcout<< \"Encryption Simplified S-DES for \" <<binaryStr8Bit1 <<\" \" <<binaryStr8Bit2 <<\" is \"\n                                                                                  <<simplifedDes1  <<\" \" <<simplifedDes2 << endl;\n\n\t\t\t\t\tcout << \"==================== CBC S-DES Encrypt ===================\" <<endl;\n\t\t\t\t\t//from the text Fig.4.5 C1 = IV XOR m1\n\t\t\t\t\tstring c1 = myDes->encrypt(myUtility->XOR(binaryStr8Bit1, initVector));\n\t\t\t\t\t// c2 = c1 XOR m2\n\t\t\t\t\tstring c2 = myDes->encrypt(myUtility->XOR(binaryStr8Bit2, c1));\t\n\t\t\t\t\tcout<< \"CBC S-DES C1 is \" << c1 <<endl;\n\t\t\t\t\tcout<< \"CBC S-DES C2 is \" << c2 <<endl;\n\t\t\t\t\tcout<< \"Encryption Simplified S-DES for \" <<binaryStr8Bit1 <<\" \" <<binaryStr8Bit2 <<\" is \" \n\t\t\t\t\t\t\t\t\t         <<c1             <<\" \" <<c2 << endl;\n\t\t\t\t\tcout << \"=========================================================\" <<endl;\n\t\t\t\t\t//Write the output to file \n\t\t\t\t\tmyUtility->writeText2File(cipherBinaryFile, (c1+\" \"+c2)); \n\t\t\t\t}\t\t\t\t\t\t\n\t\t\t}\n\t\t\telse if (boost::iequals(desTask, \"decrypt\"))\n\t\t\t{\n\t\t\t\tclog << \"DEBUG: Main func: user input task is to decrpyt the binary text\"<<endl;\n\t\t\t        //Main func: Read the  Binary input from cipher text file.\n\t\t\t\tmyUtility->readCiphertTextFile(cipherBinaryFile);\n\t\t\t\tstring binaryStr8Bit1 = myUtility->getBinaryCiphertTextLeft();\n\t\t\t\tclog << \"DEBUG: Main func: first block of 8 bits of cipher text: \" << binaryStr8Bit1 << endl;\n\t\t\t\tstring binaryStr8Bit2 = myUtility->getBinaryCiphertTextRight();\n\t\t\t\tclog << \"DEBUG: Main func: second block of 8 bits of cipher text: \" << binaryStr8Bit2 << endl;\t\t\t\t\t\n\t\t\t\t\n\t\t\t\tif (myUtility->CheckifStringIsBinary(binaryStr8Bit1) and \n\t\t\t\t    myUtility->CheckifStringIsBinary(binaryStr8Bit2) and \n                                    myUtility->CheckifStringIsBinary(initKey))\n\t\t\t\t{\n//\t\t\t\t\tclog<< \"DEBUG: main: Input strings are valid and binary\" << endl;  \n\t\t\t\t\tmyDes->generateRoundKeys(initKey);\n\t\t\t\t\tcout << \"================== SIMPLE S-DES Decrypt ==================\" <<endl; \t\t\t\t\t\n\t\t\t\t\tstring simplifedDes1 = myDes->decrypt(binaryStr8Bit1);\n\t\t\t\t        string simplifedDes2 = myDes->decrypt(binaryStr8Bit2);\n\n\t\t\t\t\tcout<< \"Decryption Simplified S-DES for \" <<binaryStr8Bit1 <<\" \" <<binaryStr8Bit2 <<\" is \"\n                                                                                 <<simplifedDes1   <<\" \" <<simplifedDes2 << endl;\n\t\t\t\t\tcout << \"==================== CBC S-DES Decrypt ===================\" <<endl;\n\t\t\t\t\t//from the text Fig.4.5 m1 = IV XOR D(c1)\n\t\t\t\t\tstring decrypt1 = myDes->decrypt(binaryStr8Bit1);\n\t\t\t\t\tstring m1 = myUtility->XOR(decrypt1, initVector);\n\n\t\t\t\t\tstring decrypt2 = myDes->decrypt(binaryStr8Bit2);\n\t\t\t\t\tstring m2 = myUtility->XOR(binaryStr8Bit1, decrypt2);\t\n\n\n\t\t\t\t\tcout<< \"CBC S-DES C1 is \" << m1 <<endl;\n\t\t\t\t\tcout<< \"CBC S-DES C2 is \" << m2 <<endl;\n\t\t\t\t\tcout<< \"Decryption Simplified S-DES for \" <<binaryStr8Bit1 <<\" \" <<binaryStr8Bit2 <<\" is \" \n\t\t\t\t\t\t\t\t\t          <<m1             <<\" \" <<m2 << endl;\n\t\t\t\t\tcout << \"==========================================================\" <<endl;\n\t\t\t\t\t//Write the output to file \n\t\t\t\t\tmyUtility->writeText2File(cipherBinaryFile, (binaryStr8Bit1+\" \"+binaryStr8Bit2));\n\t\t\t\t\tmyUtility->writeText2File(plainBinaryFile, (m1+\" \"+m2)); \n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcerr << \"ERROR: main func: Wrong user input task\" <<endl;\n\t\t\t}\t\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcerr <<\"ERROR: Main func: utility object is null.\" << endl;\n\t\t}\n\t\t\n\t\t//House keeping: free all the memory alloaction\n\t\tdelete myUtility;\n\t\tmyUtility = 0;\n\t\tdelete myDes;\n\t\tmyDes = 0;\n\t\t\n\t}\n\n\treturn 0;\n}\n\n\n", "meta": {"hexsha": "2456d344836cf5582323fb2fdb652964cc401f51", "size": 6516, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tcn5080project1.cpp", "max_stars_repo_name": "abhay1432/FIU_TCN_5080", "max_stars_repo_head_hexsha": "b8abddd7d579d3100e9f11e59ac19f5624c0a3e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tcn5080project1.cpp", "max_issues_repo_name": "abhay1432/FIU_TCN_5080", "max_issues_repo_head_hexsha": "b8abddd7d579d3100e9f11e59ac19f5624c0a3e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tcn5080project1.cpp", "max_forks_repo_name": "abhay1432/FIU_TCN_5080", "max_forks_repo_head_hexsha": "b8abddd7d579d3100e9f11e59ac19f5624c0a3e4", "max_forks_repo_licenses": ["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.0179640719, "max_line_length": 155, "alphanum_fraction": 0.5756599141, "num_tokens": 1769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5431708601789361}}
{"text": "#ifndef SM_NUMERICAL_DIFF_HPP\n#define SM_NUMERICAL_DIFF_HPP\n\n#include <Eigen/Core>\n#include <boost/bind.hpp>\n#include <boost/function.hpp>\n#include <sm/assert_macros.hpp>\n\nnamespace sm {\nnamespace eigen {\n\ntemplate <typename RESULT_VEC_T, typename INPUT_VEC_T, typename JACOBIAN_T = Eigen::MatrixXd>\nstruct NumericalDiffFunctor {\n    typedef RESULT_VEC_T value_t;\n    typedef typename value_t::Scalar scalar_t;\n    typedef INPUT_VEC_T input_t;\n    typedef JACOBIAN_T jacobian_t;\n\n    NumericalDiffFunctor(boost::function<value_t(input_t)> f) : _f(f) {}\n\n    value_t operator()(const input_t& x) { return _f(x); }\n\n    input_t update(const input_t& x, int c, scalar_t delta) {\n        input_t xnew = x;\n        xnew[c] += delta;\n        return xnew;\n    }\n    boost::function<value_t(input_t)> _f;\n};\n\n// A simple implementation of central differences to estimate a Jacobian matrix\ntemplate <typename FUNCTOR_T>\nstruct NumericalDiff {\n    typedef FUNCTOR_T functor_t;\n    typedef typename functor_t::input_t input_t;\n    typedef typename functor_t::value_t value_t;\n    typedef typename functor_t::scalar_t scalar_t;\n    typedef typename functor_t::jacobian_t jacobian_t;\n\n    NumericalDiff(functor_t f, scalar_t eps = sqrt(std::numeric_limits<scalar_t>::epsilon())) : functor(f), eps(eps) {}\n\n    jacobian_t estimateJacobian(input_t const& x0) {\n        // evaluate the function at the operating point:\n        value_t fx0 = functor(x0);\n        size_t N = x0.size();\n        size_t M = fx0.size();\n\n        // std::cout << \"Size: \" << M << \", \" << N << std::endl;\n        jacobian_t J;\n        J.resize(M, N);\n\n        SM_ASSERT_EQ(std::runtime_error, x0.size(), J.cols(), \"Unexpected number of columns for input size\");\n        SM_ASSERT_EQ(std::runtime_error, fx0.size(), J.rows(), \"Unexpected number of columns for output size\");\n\n        for (unsigned c = 0; c < N; c++) {\n            // Calculate a central difference.\n            // This step size was stolen from cminpack: temp = eps * fabs(x[j]);\n            scalar_t rcEps = std::max(static_cast<scalar_t>(fabs(x0(c))) * eps, eps);\n\n            value_t fxp = functor(functor.update(x0, c, rcEps));\n            value_t fxm = functor(functor.update(x0, c, -rcEps));\n            J.block(0, c, M, 1) = (fxp - fxm).template cast<typename jacobian_t::Scalar>() /\n                                  (typename jacobian_t::Scalar)(rcEps * (scalar_t)2.0);\n        }\n        return J;\n    }\n\n    functor_t functor;\n    scalar_t eps;\n};\n\ntemplate <typename ValueType_, typename InputType_>\nEigen::MatrixXd numericalDiff(\n    std::function<ValueType_(const InputType_&)> function, InputType_ const& input,\n    double eps =\n        sqrt(std::numeric_limits<typename NumericalDiffFunctor<ValueType_, InputType_>::scalar_t>::epsilon())) {\n    typedef NumericalDiffFunctor<ValueType_, InputType_> Functor;\n\n    NumericalDiff<Functor> numDiff(Functor(function), eps);\n    return numDiff.estimateJacobian(input);\n}\n\n}  // namespace eigen\n}  // namespace sm\n\n#endif /* SM_NUMERICAL_DIFF_HPP */\n", "meta": {"hexsha": "91e8f6ed90019a43965c7ab127f0d3a512c1a85a", "size": 3033, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_eigen/include/sm/eigen/NumericalDiff.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_eigen/include/sm/eigen/NumericalDiff.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_eigen/include/sm/eigen/NumericalDiff.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": 34.8620689655, "max_line_length": 119, "alphanum_fraction": 0.6663369601, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5431708554814428}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\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#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\n#include \"smooth/feedback/collocation.hpp\"\n\ntemplate<typename T>\nusing Vec = Eigen::VectorX<T>;\n\nusing Vecd = Vec<double>;\n\nTEST(Collocation, Mesh)\n{\n  smooth::feedback::Mesh<5, 10> m;\n  m.refine_ph(0, 5 * 10);\n  ASSERT_EQ(m.N_ivals(), 10);\n\n  for (auto i = 0u; i < 10; ++i) {\n    auto [n, w] = m.interval_nodes_and_weights(i);\n    ASSERT_DOUBLE_EQ(n(0), i * 0.1);\n  }\n\n  // will only increase degree\n  m.refine_ph(1, 10);\n  ASSERT_EQ(m.N_ivals(), 10);\n  {\n    auto [n, w] = m.interval_nodes_and_weights(1);\n    ASSERT_DOUBLE_EQ(n(0), 0.1);\n  }\n\n  // actually split it\n  m.refine_ph(1, 13);\n  ASSERT_EQ(m.N_ivals(), 12);\n  {\n    auto [n1, w1] = m.interval_nodes_and_weights(1);\n    auto [n2, w2] = m.interval_nodes_and_weights(2);\n    auto [n3, w3] = m.interval_nodes_and_weights(3);\n    ASSERT_DOUBLE_EQ(n1(0), 0.1);\n    ASSERT_DOUBLE_EQ(n2(0), 0.1 + 0.1 / 3);\n    ASSERT_DOUBLE_EQ(n3(0), 0.1 + 2 * 0.1 / 3);\n  }\n\n  m.refine_ph(2, 27);\n\n  m.refine_ph(7, 33);\n  m.refine_ph(9, 22);\n\n  const auto [alln, allw] = m.all_nodes_and_weights();\n\n  for (auto i = 0u; i + 1 < alln.size(); ++i) { ASSERT_LE(alln[i], alln[i + 1]); }\n}\n\nTEST(Collocation, DifferentiationIntegration)\n{\n  smooth::feedback::Mesh<8, 8> m;\n  m.refine_ph(0, 40);\n\n  // define a function and its derivative\n  const auto x  = [](double t) -> double { return 1 + 2 * t + 3 * t * t + 4 * t * t * t; };\n  const auto dx = [](double t) -> double { return 2 + 3 * 2 * t + 4 * 3 * t * t; };\n\n  for (auto ival = 0u; ival < m.N_ivals(); ++ival) {\n    const auto N               = m.N_colloc_ival(ival);\n    const auto [taus, weights] = m.interval_nodes_and_weights(ival);\n\n    // specify function values on mesh\n    Eigen::RowVectorXd xvals(N + 1);\n    for (auto i = 0u; i < N + 1; ++i) { xvals(i) = x(taus(i)); }\n    Eigen::RowVectorXd dxvals(N);\n    for (auto i = 0u; i < N; ++i) { dxvals(i) = dx(taus(i)); }\n\n    // derivative and integral matrices\n    const auto D = m.interval_diffmat(ival);\n    const auto I = m.interval_intmat(ival);\n\n    // expect [dx0 ... dxN-1] = [x0 ... xN] * D\n    ASSERT_TRUE(dxvals.isApprox(xvals * D));\n\n    // expect [x1 ... xN] = [x0 ... x0] + [dx0 ... dxN-1] * I\n    ASSERT_TRUE(xvals.rightCols(N).isApprox(xvals.leftCols(1).replicate(1, N) + dxvals * I));\n  }\n}\n\nTEST(Collocation, TimeTrajectory)\n{\n  // given trajectory\n  std::size_t nx = 1;\n  const auto x = [](double t) -> Vec<double> { return Vec<double>{{0.1 * t * t - 0.4 * t + 0.2}}; };\n\n  // running constraints\n  std::size_t ncr = 2;\n  const auto cr   = []<typename T>(const T &, const Vec<T> & x, const Vec<T> &) -> Vec<T> {\n    return Vec<T>{{x.x(), 0}};\n  };\n\n  // system dynamics\n  std::size_t nu = 0;\n  const auto f   = []<typename T>(const T & t, const Vec<T> &, const Vec<T> &) -> Vec<T> {\n    return Vec<T>{{0.2 * t - 0.4}};\n  };\n\n  // integrand\n  std::size_t nq = 1;\n  const auto g   = []<typename T>(const T &, const Vec<T> & x, const Vec<T> &) -> Vec<T> {\n    return Vec<T>{{0.1 + x.squaredNorm()}};\n  };\n\n  double t0 = 3;\n  double tf = 5;\n\n  smooth::feedback::Mesh<5, 5> m;\n  m.refine_ph(0, 40);\n  ASSERT_EQ(m.N_ivals(), 8);\n\n  Eigen::MatrixXd X(nx, m.N_colloc() + 1);\n  Eigen::MatrixXd U(nu, m.N_colloc());\n  Eigen::MatrixXd C(ncr, m.N_colloc());\n\n  // fill X with curve values at the two intervals\n  std::size_t M = 0;\n  for (auto p = 0u; p < m.N_ivals(); ++p) {\n    const auto [tau_s, w_s] = m.interval_nodes_and_weights(p);\n    for (auto i = 0u; i + 1 < tau_s.size(); ++i) {\n      X.col(M + i) = x(t0 + (tf - t0) * tau_s[i]);\n      C.col(M + i) = cr.operator()<double>(0, X.col(M + i), U.col(M + i));\n    }\n    M += m.N_colloc_ival(p);\n  }\n  X.col(m.N_colloc()) = x(tf);\n\n  Eigen::VectorXd Q{{0}};\n\n  const Eigen::VectorXd dyn_vals = smooth::feedback::colloc_dyn<false>(nx, f, m, t0, tf, X, U);\n  ASSERT_EQ(dyn_vals.rows(), m.N_colloc());\n  ASSERT_EQ(dyn_vals.cols(), 1);\n  ASSERT_LE(dyn_vals.cwiseAbs().maxCoeff(), 1e-8);\n\n  const Eigen::VectorXd cr_vals =\n    smooth::feedback::colloc_eval<false>(ncr, cr, m, t0, tf, X, U).reshaped();\n  ASSERT_EQ(cr_vals.rows(), 2 * m.N_colloc());\n  ASSERT_EQ(cr_vals.cols(), 1);\n  ASSERT_TRUE(C.reshaped().isApprox(cr_vals));\n\n  const Eigen::VectorXd q_vals = smooth::feedback::colloc_int<false>(nq, g, m, t0, tf, Q, X, U);\n  ASSERT_NEAR(q_vals.x(), 0.217333 + 0.1 * (tf - t0), 1e-4);\n}\n\nTEST(Collocation, DynError)\n{\n  // given trajectory\n  std::size_t nx = 1;\n  const auto x = [](double t) -> Vec<double> { return Vec<double>{{0.1 * t * t - 0.4 * t + 0.2}}; };\n\n  // system dynamics\n  std::size_t nu = 0;\n  const auto f   = []<typename T>(const T & t, const Vec<T> &, const Vec<T> &) -> Vec<T> {\n    return Vec<T>{{0.2 * t - 0.4}};\n  };\n\n  double t0 = 3;\n  double tf = 5;\n\n  smooth::feedback::Mesh<5, 5> m;\n\n  // trajectory is not a polynomial, so we need a couple of intervals for a good approximation\n  m.refine_ph(0, 16 * 5);\n  ASSERT_EQ(m.N_ivals(), 16);\n\n  // fill X with curve values at the two intervals\n  std::size_t M = 0;\n  Eigen::MatrixXd X(nx, m.N_colloc() + 1);\n  for (auto p = 0u; p < m.N_ivals(); ++p) {\n    const auto [tau_s, w_s] = m.interval_nodes_and_weights(p);\n    for (auto i = 0u; i + 1 < tau_s.size(); ++i) { X.col(M + i) = x(t0 + (tf - t0) * tau_s[i]); }\n    M += m.N_colloc_ival(p);\n  }\n  X.col(m.N_colloc()) = x(tf);\n\n  auto xfun = [&](const double t) -> Eigen::VectorXd {\n    return m.eval<Eigen::VectorXd>((t - t0) / (tf - t0), X.colwise(), 0, true);\n  };\n  auto ufun = [&](const double) -> Eigen::VectorXd { return Eigen::VectorXd::Zero(nu); };\n\n  auto rel_errs = smooth::feedback::mesh_dyn_error(nx, f, m, t0, tf, xfun, ufun);\n\n  ASSERT_LE(rel_errs.cwiseAbs().maxCoeff(), 1e-8);\n\n  const auto Npre = m.N_ivals();\n  smooth::feedback::mesh_refine(m, rel_errs, 1e-8);\n\n  ASSERT_EQ(m.N_ivals(), Npre);\n}\n\nTEST(Collocation, StateTrajectory)\n{\n  // given trajectory and system dynamics\n  std::size_t nx = 1;\n  std::size_t nu = 0;\n  const auto x   = [](double t) { return Vec<double>{{1.5 * exp(-t)}}; };\n  const auto f   = []<typename T>(const T &, const Vec<T> & x, const Vec<T> &) -> Vec<T> {\n    return Vec<T>{{-x.x()}};\n  };\n\n  // integrals\n  std::size_t nq = 1;\n  const auto g   = []<typename T>(const T &, const Vec<T> & x, const Vec<T> &) -> Vec<T> {\n    return Vec<T>{{x.squaredNorm()}};\n  };\n\n  double t0 = 3;\n  double tf = 5;\n\n  smooth::feedback::Mesh<5, 5> m;\n\n  // trajectory is not a polynomial, so we need a couple of intervals for a good approximation\n  m.refine_ph(0, 16 * 5);\n  ASSERT_EQ(m.N_ivals(), 16);\n\n  Eigen::MatrixXd X(1, m.N_colloc() + 1);\n\n  // fill X with curve values at the two intervals\n  std::size_t M = 0;\n  for (auto p = 0u; p < m.N_ivals(); ++p) {\n    const auto [tau_s, w_s] = m.interval_nodes_and_weights(p);\n    for (auto i = 0u; i + 1 < tau_s.size(); ++i) { X.col(M + i) = x(t0 + (tf - t0) * tau_s[i]); }\n    M += m.N_colloc_ival(p);\n  }\n  X.col(m.N_colloc()) = x(tf);\n\n  Eigen::MatrixXd U(nu, m.N_colloc());\n  Eigen::VectorXd Q{{0}};\n\n  const auto dyn_vals = smooth::feedback::colloc_dyn<false>(nx, f, m, t0, tf, X, U);\n  ASSERT_LE(dyn_vals.cwiseAbs().maxCoeff(), 1e-8);\n\n  const auto q_vals = smooth::feedback::colloc_int<false>(nq, g, m, t0, tf, Q, X, U);\n  ASSERT_NEAR(q_vals.x(), 0.00273752, 1e-4);\n}\n\nTEST(Collocation, FunctionEval)\n{\n  smooth::feedback::Mesh<5, 5> m;\n\n  {\n    Eigen::MatrixXd vals = Eigen::MatrixXd::Ones(3, m.N_colloc() + 1);\n\n    const auto x1 = m.eval<Eigen::VectorXd>(0, vals.colwise());\n    ASSERT_TRUE(x1.isApprox(Eigen::VectorXd::Ones(3)));\n\n    const auto x2 = m.eval<Eigen::VectorXd>(0.5, vals.colwise());\n    ASSERT_TRUE(x2.isApprox(Eigen::VectorXd::Ones(3)));\n\n    const auto x3 = m.eval<Eigen::VectorXd>(1, vals.colwise());\n    ASSERT_TRUE(x3.isApprox(Eigen::VectorXd::Ones(3)));\n  }\n\n  {\n    Eigen::MatrixXd vals = Eigen::MatrixXd::Ones(3, m.N_colloc());\n\n    const auto x1 = m.eval<Eigen::VectorXd>(0, vals.colwise(), 0, false);\n    ASSERT_TRUE(x1.isApprox(Eigen::VectorXd::Ones(3)));\n\n    const auto x2 = m.eval<Eigen::VectorXd>(0.5, vals.colwise(), 0, false);\n    ASSERT_TRUE(x2.isApprox(Eigen::VectorXd::Ones(3)));\n\n    const auto x3 = m.eval<Eigen::VectorXd>(1, vals.colwise(), 0, false);\n    ASSERT_TRUE(x3.isApprox(Eigen::VectorXd::Ones(3)));\n  }\n\n  m.refine_ph(0, 40);\n\n  {\n    Eigen::MatrixXd vals_refined = Eigen::MatrixXd::Ones(3, m.N_colloc() + 1);\n\n    const auto x1 = m.eval<Eigen::VectorXd>(0, vals_refined.colwise());\n    ASSERT_TRUE(x1.isApprox(Eigen::VectorXd::Ones(3)));\n\n    const auto x2 = m.eval<Eigen::VectorXd>(0.5, vals_refined.colwise());\n    ASSERT_TRUE(x2.isApprox(Eigen::VectorXd::Ones(3)));\n\n    const auto x3 = m.eval<Eigen::VectorXd>(1, vals_refined.colwise());\n    ASSERT_TRUE(x3.isApprox(Eigen::VectorXd::Ones(3)));\n  }\n}\n", "meta": {"hexsha": "40a181640faf5bc68f844c27fe0ff5860123b303", "size": 9996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_collocation.cpp", "max_stars_repo_name": "pettni/smooth_feedback", "max_stars_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "tests/test_collocation.cpp", "max_issues_repo_name": "pettni/smooth_feedback", "max_issues_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "tests/test_collocation.cpp", "max_forks_repo_name": "pettni/smooth_feedback", "max_forks_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T15:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:23:18.000Z", "avg_line_length": 32.2451612903, "max_line_length": 100, "alphanum_fraction": 0.619047619, "num_tokens": 3335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5431254038261425}}
{"text": "#include \"particle.hpp\"\n#include \"array_helpers.hpp\"\n\n#include <Eigen/Core>\n\nusing namespace Optima;\nusing namespace Eigen;\n\nParticle::Particle(const ParameterSpace &paramSpace)\n    : parameterSpace(paramSpace) {\n\n  parameterNames.reserve(paramSpace.size());\n  for (const auto &param : paramSpace) {\n    parameterNames.push_back(param.first);\n  }\n  std::sort(parameterNames.begin(), parameterNames.end());\n\n  const auto bounds = makeBoundsFromParameters(parameterSpace);\n  const ArrayXd pos = ArrayHelpers::uniformFromBounds(bounds);\n  initPosition(pos);\n  initVelocity(bounds);\n}\n\nconst Parameters &Particle::getParameters() {\n  return getParametersFromArray(parameters, position);\n}\n\nconst Parameters &Particle::getBestParameters() {\n  return getParametersFromArray(bestParameters, bestPosition);\n}\n\nvoid Particle::initPosition(const ArrayXd &pos) {\n  position = pos;\n  bestPosition = pos;\n\n  int index = 0;\n  for (const auto &name : parameterNames) {\n    parameters.emplace(name, pos(index));\n    bestParameters.emplace(name, pos(index));\n    ++index;\n  }\n}\n\nvoid Particle::initVelocity(const Bounds &bounds) {\n  const ArrayXd lower = bounds.first;\n  const ArrayXd upper = bounds.second;\n  const ArrayXd range = upper - lower;\n\n  double v = range.matrix().norm();\n  const ArrayXd vrange = ArrayXd::Constant(position.size(), -v);\n  auto vbound = std::make_pair(-vrange, vrange);\n  velocity = ArrayHelpers::uniformFromBounds(vbound);\n}\n\nBounds\nParticle::makeBoundsFromParameters(const ParameterSpace &parameters) const {\n  auto nDims = parameters.size();\n  ArrayXd lower(nDims);\n  ArrayXd upper(nDims);\n\n  int index = 0;\n  for (const auto &name : parameterNames) {\n    auto values = parameters.at(name);\n    lower(index) = values.first;\n    upper(index) = values.second;\n    ++index;\n  }\n\n  return std::make_pair(lower, upper);\n}\n\nvoid Particle::setParametersFromArray(const ArrayXd &array,\n                                      Parameters &params) {\n  int index = 0;\n  for (const auto &param : params) {\n    auto name = param.first;\n    auto value = array(index);\n    params[name] = value;\n    ++index;\n  }\n}\n\nconst Parameters &Particle::getParametersFromArray(Parameters &params,\n                                                   const ArrayXd &array) {\n  int index = 0;\n  for (auto &name : parameterNames) {\n    params[name] = array(index);\n    ++index;\n  }\n  return params;\n}\n", "meta": {"hexsha": "db6dfef63263f72727f1593259c7d832da5e7a38", "size": 2382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/particle.cpp", "max_stars_repo_name": "samueljackson92/metaopt", "max_stars_repo_head_hexsha": "8d030476a20b8a2661f44f3b2355880689874b96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/particle.cpp", "max_issues_repo_name": "samueljackson92/metaopt", "max_issues_repo_head_hexsha": "8d030476a20b8a2661f44f3b2355880689874b96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-04-30T08:27:07.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T08:36:20.000Z", "max_forks_repo_path": "src/particle.cpp", "max_forks_repo_name": "samueljackson92/metaopt", "max_forks_repo_head_hexsha": "8d030476a20b8a2661f44f3b2355880689874b96", "max_forks_repo_licenses": ["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.8913043478, "max_line_length": 76, "alphanum_fraction": 0.6847187238, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5431253987971195}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <cstdlib>\n\nnamespace edp\n{\ntemplate<typename T, class ColFunc>\nauto constructMat(size_t dim, ColFunc&& colFunc) -> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>\n{\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> res(dim, dim);\n    res.setZero();\n\n    for(size_t i = 0; i < dim; i++)\n    {\n        auto m = colFunc(i);\n        for(auto& elt : m)\n        {\n            res(elt.first, i) = elt.second;\n        }\n    }\n    return res;\n}\n\ntemplate<typename T, class ColFunc>\nauto constructSparseMat(size_t dim, ColFunc&& colFunc) -> Eigen::SparseMatrix<T>\n{\n    using TripletT = Eigen::Triplet<T>;\n    std::vector<TripletT> tripletList;\n    tripletList.reserve(3 * dim);\n    for(size_t col = 0; col < dim; ++col)\n    {\n        auto m = colFunc(col);\n        for(const auto& v : m)\n        {\n            tripletList.emplace_back(v.first, col, v.second);\n        }\n    }\n\n    Eigen::SparseMatrix<T> res(dim, dim);\n    res.setFromTriplets(tripletList.begin(), tripletList.end());\n    return res;\n}\n\n// basis must be sorted\ntemplate<typename T, typename ColFunc>\nauto constructSubspaceMat(ColFunc&& t, const std::vector<uint32_t>& basis) -> Eigen::SparseMatrix<T>\n{\n    const size_t n = basis.size();\n\n    using TripletT = Eigen::Triplet<T>;\n    std::vector<TripletT> tripletList;\n    for(size_t i = 0; i < n; i++)\n    {\n        std::map<uint32_t, T> m = t(basis[i]);\n        auto iter = basis.begin();\n        for(auto& kv : m)\n        {\n            iter = std::lower_bound(iter, basis.end(), kv.first);\n            if(iter == basis.end())\n            {\n                break;\n            }\n            auto j = std::distance(basis.begin(), iter);\n            {\n                tripletList.emplace_back(i, j, kv.second);\n            }\n        }\n    }\n\n    Eigen::SparseMatrix<T> res(n, n);\n    res.setFromTriplets(tripletList.begin(), tripletList.end());\n    return res;\n}\n}\n", "meta": {"hexsha": "c436d83efe656b084ed12df20a43f5dc7e96e08e", "size": 1944, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/edlib/EDP/ConstructSparseMat.hpp", "max_stars_repo_name": "cecri/ExactDiagonalization", "max_stars_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_stars_repo_licenses": ["MIT"], "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/edlib/EDP/ConstructSparseMat.hpp", "max_issues_repo_name": "cecri/ExactDiagonalization", "max_issues_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_issues_repo_licenses": ["MIT"], "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/edlib/EDP/ConstructSparseMat.hpp", "max_forks_repo_name": "cecri/ExactDiagonalization", "max_forks_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_forks_repo_licenses": ["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.2467532468, "max_line_length": 100, "alphanum_fraction": 0.5694444444, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5431253956043333}}
{"text": "////////////////////////////////////////////////////////////////////////////////////\n// The MIT License (MIT)                                                          //\n//                                                                                //\n// Copyright (c) 2015 Whit Armstrong                                              //\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#pragma once\n\n#include <armadillo>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n\nnamespace arma {\n\n  // lgamma\n  class eop_lgamma : public eop_core<eop_lgamma> {};\n\n  template<> template<typename eT> arma_hot arma_pure arma_inline eT\n  eop_core<eop_lgamma>::process(const eT val, const eT  ) {\n    return boost::math::lgamma(val);\n  }\n\n  // Base\n  template<typename T1>\n  arma_inline\n  const eOp<T1, eop_lgamma> lgamma(const Base<typename T1::elem_type,T1>& A) {\n    arma_extra_debug_sigprint();\n    return eOp<T1, eop_lgamma>(A.get_ref());\n  }\n\n  // BaseCube\n  template<typename T1>\n  arma_inline\n  const eOpCube<T1, eop_lgamma> lgamma(const BaseCube<typename T1::elem_type,T1>& A) {\n    arma_extra_debug_sigprint();\n    return eOpCube<T1, eop_lgamma>(A.get_ref());\n  }\n\n\n\n\n  // factln\n  double factln(const int i) {\n    static std::vector<double> factln_table;\n\n    if(i < 0) {\n      return -std::numeric_limits<double>::infinity();\n    }\n\n    if(i > 100) {\n      return boost::math::lgamma(static_cast<double>(i) + 1);\n    }\n\n    if(factln_table.size() < static_cast<size_t>(i+1)) {\n      for(int j = factln_table.size(); j < (i+1); j++) {\n        factln_table.push_back(std::log(boost::math::factorial<double>(static_cast<double>(j))));\n      }\n    }\n    //for(auto v : factln_table) { std::cout << v << \"|\"; }  std::cout << std::endl;\n    return factln_table[i];\n  }\n\n  class eop_factln : public eop_core<eop_factln> {};\n\n  template<> template<typename eT> arma_hot arma_pure arma_inline eT\n  eop_core<eop_factln>::process(const eT val, const eT  ) {\n    return factln(val);\n  }\n\n  // Base\n  template<typename T1>\n  arma_inline\n  const eOp<T1, eop_factln> factln(const Base<typename T1::elem_type,T1>& A) {\n    arma_extra_debug_sigprint();\n    return eOp<T1, eop_factln>(A.get_ref());\n  }\n\n  // BaseCube\n  template<typename T1>\n  arma_inline\n  const eOpCube<T1, eop_factln> factln(const BaseCube<typename T1::elem_type,T1>& A) {\n    arma_extra_debug_sigprint();\n    return eOpCube<T1, eop_factln>(A.get_ref());\n  }\n\n  // cube\n  //! element-wise multiplication of BaseCube objects with same element type\n  template<typename T1, typename T2>\n  arma_inline\n  const eGlueCube<T1, T2, eglue_schur>\n  schur_prod\n  (\n   const BaseCube<typename T1::elem_type,T1>& X,\n   const BaseCube<typename T1::elem_type,T2>& Y\n   )\n  {\n    arma_extra_debug_sigprint();\n    return eGlueCube<T1, T2, eglue_schur>(X.get_ref(), Y.get_ref());\n  }\n\n  //! element-wise multiplication of BaseCube objects with different element types\n  template<typename T1, typename T2>\n  inline\n  const mtGlueCube<typename promote_type<typename T1::elem_type, typename T2::elem_type>::result, T1, T2, glue_mixed_schur>\n  schur_prod\n  (\n   const BaseCube< typename force_different_type<typename T1::elem_type, typename T2::elem_type>::T1_result, T1>& X,\n   const BaseCube< typename force_different_type<typename T1::elem_type, typename T2::elem_type>::T2_result, T2>& Y\n   )\n  {\n    arma_extra_debug_sigprint();\n    typedef typename T1::elem_type eT1;\n    typedef typename T2::elem_type eT2;\n    typedef typename promote_type<eT1,eT2>::result out_eT;\n    promote_type<eT1,eT2>::check();\n    return mtGlueCube<out_eT, T1, T2, glue_mixed_schur>( X.get_ref(), Y.get_ref() );\n  }\n\n  // matrix\n  template<typename T1, typename T2>\n  arma_inline\n  const eGlue<T1, T2, eglue_schur>\n  schur_prod(const Base<typename T1::elem_type,T1>& X, const Base<typename T1::elem_type,T2>& Y) {\n    arma_extra_debug_sigprint();\n    return eGlue<T1, T2, eglue_schur>(X.get_ref(), Y.get_ref());\n  }\n\n  //! element-wise multiplication of Base objects with different element types\n  template<typename T1, typename T2>\n  inline\n  const mtGlue<typename promote_type<typename T1::elem_type, typename T2::elem_type>::result, T1, T2, glue_mixed_schur>\n  schur_prod\n  (\n   const Base< typename force_different_type<typename T1::elem_type, typename T2::elem_type>::T1_result, T1>& X,\n   const Base< typename force_different_type<typename T1::elem_type, typename T2::elem_type>::T2_result, T2>& Y\n   )\n  {\n    arma_extra_debug_sigprint();\n    typedef typename T1::elem_type eT1;\n    typedef typename T2::elem_type eT2;\n    typedef typename promote_type<eT1,eT2>::result out_eT;\n    promote_type<eT1,eT2>::check();\n    return mtGlue<out_eT, T1, T2, glue_mixed_schur>( X.get_ref(), Y.get_ref() );\n  }\n\n\n  //! Base * scalar\n  template<typename T1>\n  arma_inline\n  const eOp<T1, eop_scalar_times>\n  schur_prod\n  (const Base<typename T1::elem_type,T1>& X, const typename T1::elem_type k)\n  {\n    arma_extra_debug_sigprint();\n    return eOp<T1, eop_scalar_times>(X.get_ref(),k);\n  }\n\n  //! scalar * Base\n  template<typename T1>\n  arma_inline\n  const eOp<T1, eop_scalar_times>\n  schur_prod\n  (const typename T1::elem_type k, const Base<typename T1::elem_type,T1>& X)\n  {\n    arma_extra_debug_sigprint();\n    return eOp<T1, eop_scalar_times>(X.get_ref(),k);  // NOTE: order is swapped\n  }\n\n  double schur_prod(const int x, const double y) { return x * y; }\n  double schur_prod(const double x, const int y) { return x * y; }\n  double schur_prod(const double& x, const double& y) { return x * y; }\n  double schur_prod(const int& x, const int& y) { return x * y; }\n\n  // insert an 'any' function for bools into the arma namespace\n  bool any(const bool x) {\n    return x;\n  }\n\n  bool vectorise(bool x) {\n    return x;\n  }\n} // namespace arma\n", "meta": {"hexsha": "3977770489e3e88b13767a0b5a43596a58634817", "size": 7374, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "armalogp/arma.extensions.hpp", "max_stars_repo_name": "armaMCMC/arma-log-likelihood", "max_stars_repo_head_hexsha": "c8323afb0a99fbb69cdf738b7fbbde98432a7c66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "armalogp/arma.extensions.hpp", "max_issues_repo_name": "armaMCMC/arma-log-likelihood", "max_issues_repo_head_hexsha": "c8323afb0a99fbb69cdf738b7fbbde98432a7c66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "armalogp/arma.extensions.hpp", "max_forks_repo_name": "armaMCMC/arma-log-likelihood", "max_forks_repo_head_hexsha": "c8323afb0a99fbb69cdf738b7fbbde98432a7c66", "max_forks_repo_licenses": ["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.6865671642, "max_line_length": 123, "alphanum_fraction": 0.6277461351, "num_tokens": 1916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5431253919318592}}
{"text": "#include <stdexcept>\r\n#include <cmath>\r\n#include <algorithm>\r\n#include <numeric>\r\n#include <Eigen/Core>\r\n#include <spectra/GenEigsSolver.h>\r\n#include \"diffusion_map.h\"\r\n#include \"distance_matrix.h\"\r\n\r\n#ifdef _OPENMP\r\n#include <omp.h>\r\n#endif\r\n\r\nusing namespace Spectra;\r\n\r\nnamespace dmaps\r\n{\r\n\r\n    diffusion_map::diffusion_map(const matrix_t& d, const vector_t& w, int num_threads) : \r\n    dint_(d), d_(dint_), w_(w)\r\n    {\r\n        check_params();\r\n        \r\n        #ifdef _OPENMP\r\n        if(num_threads) omp_set_num_threads(num_threads);\r\n        #endif     \r\n    }\r\n\r\n    diffusion_map::diffusion_map(const distance_matrix& dm, const vector_t& w, int num_threads) : \r\n    d_(dm.get_distances()), w_(w)\r\n    {\r\n        check_params();\r\n\r\n        #ifdef _OPENMP\r\n        if(num_threads) omp_set_num_threads(num_threads);\r\n        #endif\r\n    }\r\n\r\n    void diffusion_map::check_params()\r\n    {\r\n        if(d_.cols() != d_.rows())\r\n            throw std::invalid_argument(\"Distance matrix must be square.\");\r\n        \r\n        if(w_.size() == 0)\r\n            w_ = vector_t::Ones(d_.cols());\r\n        else if(w_.size() != d_.cols())\r\n            throw std::invalid_argument(\"Weights vector length must match distance matrix size.\");\r\n    }\r\n\r\n    void diffusion_map::set_kernel_bandwidth(f_type eps)\r\n    {\r\n        if(eps <= 0)\r\n            throw std::invalid_argument(\"Kernel bandwidth must be positive.\"); \r\n        eps_ = eps; \r\n    }\r\n\r\n    f_type diffusion_map::get_kernel_bandwidth() const\r\n    {\r\n        return eps_;\r\n    }\r\n\r\n    f_type diffusion_map::sum_similarity_matrix(f_type eps, f_type alpha) const\r\n    {\r\n        matrix_t wwt = w_*w_.transpose();\r\n        return ((-0.5/eps*d_.array().square().pow(alpha)).exp()*wwt.array()).sum();\r\n    }\r\n\r\n    /*\r\n    void diffusion_map::estimate_local_scale(int k)\r\n    {\r\n        // Default choice of k.\r\n        if(k == 0) k = static_cast<int>(std::sqrt(d_.rows()));\r\n\r\n        // Set local epsilon scale for each entry.\r\n        #ifdef _OPENMP\r\n        #pragma omp parallel\r\n        #endif\r\n        {\r\n            // Create sort indexer.\r\n            std::vector<size_t> idx(d_.rows());\r\n            std::iota(std::begin(idx), std::end(idx), static_cast<size_t>(0));\r\n\r\n            #ifdef _OPENMP\r\n            #pragma for schedule(static)\r\n            #endif\r\n            for(size_t i = 0; i < eps_.size(); ++i)\r\n            {\r\n                const vector_t& dist = d_.row(i);\r\n\r\n                // Get indices of sorted distances (ascending).\r\n                std::sort(std::begin(idx), std::end(idx),\r\n                    [&](size_t a, size_t b) { return dist[a] < dist[b]; }\r\n                );\r\n            \r\n                // Sum and determine weight.\r\n                // We skip the first element which is itself.\r\n                f_type sum = 0.;\r\n                for(size_t j = 1; j < idx.size(); ++j)\r\n                {\r\n                    sum += w_[idx[j]];\r\n                    // Break at k value.\r\n                    if(sum >= k)\r\n                    {\r\n                        eps_[i] = dist[idx[j]];\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n    */\r\n\r\n    void diffusion_map::compute(int n, f_type alpha, f_type beta)\r\n    {\r\n        if(eps_ == 0)\r\n            throw std::runtime_error(\"Kernel bandwidth must be defined before computing diffusion coordinates.\");\r\n        \r\n        if(alpha <= 0 || alpha > 1)\r\n            throw std::invalid_argument(\"Distance scaling must be in the interval (0,1].\");\r\n        \r\n        // Compute similarity matrix and row normalize\r\n        // to get right stochastic matrix.\r\n        k_ = -0.5/eps_*d_.array().square().pow(alpha);\r\n        k_.array() = k_.array().exp();\r\n        k_.array() *= (w_*w_.transpose()).array();\r\n\r\n        // Density normalization.\r\n        vector_t rsum =  k_.rowwise().sum().array().pow(-beta);\r\n        k_ = rsum.asDiagonal()*k_*rsum.asDiagonal();\r\n\r\n        // Right stochastic matrix. \r\n        rsum =  k_.rowwise().sum().array().cwiseInverse();\r\n        k_ = rsum.asDiagonal()*k_;\r\n\r\n        // Define eigensolver.\r\n        DenseGenMatProd<f_type> op(k_);\r\n        GenEigsSolver <f_type, LARGEST_MAGN, DenseGenMatProd<f_type>> eigs(&op, n, 2*n);\r\n        \r\n        // Solve. \r\n        eigs.init();\r\n        eigs.compute();\r\n        \r\n        if(eigs.info() != SUCCESSFUL)\r\n            throw std::runtime_error(\"Eigensolver did not converge.\");\r\n        \r\n        dvals_ = eigs.eigenvalues().real();\r\n        dvecs_ = eigs.eigenvectors().real();\r\n    }\r\n\r\n    vector_t diffusion_map::nystrom(const vector_t& distances, f_type alpha, f_type beta)\r\n    {\r\n        if(dvals_.size() == 0)\r\n            throw std::runtime_error(\"Eigenvectors must be computed first.\");\r\n        \r\n        vector_t k = -0.5/eps_*distances.array().square().pow(alpha);\r\n        k.array() = k.array().exp();\r\n        k /= k.sum();\r\n\r\n        vector_t point(dvals_.size());\r\n\r\n        for(int i = 0; i < dvals_.size(); ++i)\r\n            point[i] = 1./dvals_[i]*(k.array()*dvecs_.col(i).array()).sum();\r\n        \r\n        return point;\r\n    }\r\n\r\n    const matrix_t& diffusion_map::get_eigenvectors() const\r\n    {\r\n        return dvecs_;\r\n    }\r\n\r\n    const vector_t& diffusion_map::get_eigenvalues() const\r\n    {\r\n        return dvals_;\r\n    }\r\n\r\n    const matrixc_t& diffusion_map::get_kernel_matrix() const\r\n    {\r\n        return k_;\r\n    }\r\n}", "meta": {"hexsha": "d4f7d20d77ce614a1d7d10ce7f82ff07c2cacf91", "size": 5434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dmaps/diffusion_map.cpp", "max_stars_repo_name": "hsidky/dmaps", "max_stars_repo_head_hexsha": "e260724727cc14423b7ef09975649e274c004fc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-08-30T21:20:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T17:33:39.000Z", "max_issues_repo_path": "dmaps/diffusion_map.cpp", "max_issues_repo_name": "hsidky/dmaps", "max_issues_repo_head_hexsha": "e260724727cc14423b7ef09975649e274c004fc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T23:57:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-19T21:59:59.000Z", "max_forks_repo_path": "dmaps/diffusion_map.cpp", "max_forks_repo_name": "hsidky/dmaps", "max_forks_repo_head_hexsha": "e260724727cc14423b7ef09975649e274c004fc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-12-05T21:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T14:47:02.000Z", "avg_line_length": 30.0220994475, "max_line_length": 114, "alphanum_fraction": 0.517298491, "num_tokens": 1296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5430953140607694}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <manifold/S.h>\n\nint main (int argc, char** argv) {\n  \n  S3d q;\n  std::cout << q << std::endl;\n\n  std::cout << q.Exp(Eigen::Vector3d(0.,M_PI/2.,0.)).norm() << std::endl;\n  std::cout << q.Exp(q.ToAmbient(Eigen::Vector2d(0.,M_PI/2.))).norm() << std::endl;\n\n  S3d mu;\n  mu.vector() << 1./sqrt(2),1./sqrt(2), 0.;\n  std::cout << mu << std::endl;\n\n  double delta = 0.1;\n  double f_prev = 1e99;\n  double f = mu.dot(q);\n  std::cout << \"f=\" << f << std::endl;\n  for (uint32_t it=0; it<100; ++it) {\n    Eigen::Vector3d J = -2.*(mu.vector() - q.vector()*q.dot(mu)); \n\n    q = q.Exp(-delta*J);\n//    q = q.RetractOrtho(-delta*J);\n\n    f_prev = f;\n    f = mu.dot(q);\n    std::cout << \"@\" << it << \": f=\" << f \n      << \" df/f=\" << (f_prev - f)/fabs(f) << std::endl;\n    if ((f_prev - f)/fabs(f) > -1e-10) break;\n  }\n  std::cout << std::endl << mu << std::endl;\n  std::cout << std::endl << q << std::endl;\n}\n\n", "meta": {"hexsha": "2ec18203899653eebf7bc83e8b3f427c1c0b5fe7", "size": 946, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/S.cpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "test/S.cpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "test/S.cpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 25.5675675676, "max_line_length": 83, "alphanum_fraction": 0.5137420719, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5430007696151778}}
{"text": "//  Copyright John Maddock 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#include \"required_defines.hpp\"\n\n#include \"performance_measure.hpp\"\n\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/math/special_functions/expm1.hpp>\n#include <boost/array.hpp>\n\n#define T double\n#  include \"../test/log1p_expm1_data.ipp\"\n\ntemplate <std::size_t N>\ndouble log1p_evaluate2(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::log1p(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(log1p_test, \"log1p\")\n{\n   double result = log1p_evaluate2(log1p_expm1_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(log1p_expm1_data)) / sizeof(log1p_expm1_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble expm1_evaluate2(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::expm1(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(expm1_test, \"expm1\")\n{\n   double result = expm1_evaluate2(log1p_expm1_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(log1p_expm1_data)) / sizeof(log1p_expm1_data[0]));\n}\n\n#ifdef TEST_DCDFLIB\n#include <dcdflib.h>\n\ntemplate <std::size_t N>\ndouble log1p_evaluate2_dcd(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n   {\n      double t = data[i][0];\n      result += ::alnrel(&t);\n   }\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(log1p_test_dcd, \"log1p-dcd\")\n{\n   double result = log1p_evaluate2_dcd(log1p_expm1_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(log1p_expm1_data)) / sizeof(log1p_expm1_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble expm1_evaluate2_dcd(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n   {\n      double t = data[i][0];\n      result += ::dexpm1(&t);\n   }\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(expm1_test_dcd, \"expm1-dcd\")\n{\n   double result = expm1_evaluate2_dcd(log1p_expm1_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(log1p_expm1_data)) / sizeof(log1p_expm1_data[0]));\n}\n\n#endif\n\n\n", "meta": {"hexsha": "47e4b7db9d553f573a4a0c7eeb66038f95cb7a8d", "size": 2387, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/performance/test_expm1_log1p.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": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-31T02:19:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-31T02:19:48.000Z", "max_issues_repo_path": "libs/math/performance/test_expm1_log1p.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/performance/test_expm1_log1p.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "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.6336633663, "max_line_length": 75, "alphanum_fraction": 0.6883116883, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5430007572206055}}
{"text": "/*\n * @file SE2Config.hpp\n * @date Nov 24, 2015\n * @author Renaud Dub\u00e9\n */\n\n#ifndef SE2CONFIG_H_\n#define SE2CONFIG_H_\n\n#include <Eigen/Core>\n#include \"gtsam/geometry/Pose2.h\"\n\nnamespace curves {\n\ntypedef Eigen::Matrix<double, 3, 1> Vector3d;\n\nstruct SE2Config {\n  typedef gtsam::Pose2 ValueType;\n  typedef Vector3d DerivativeType;\n};\n\n}  // namespace curves\n\n#endif // SE2CONFIG_H_\n", "meta": {"hexsha": "47a3158335a59c1ea1d8ef8e232c5197f64bbcb4", "size": 382, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "curves/include/curves/SE2Config.hpp", "max_stars_repo_name": "leggedrobotics/curves", "max_stars_repo_head_hexsha": "696db3e9ecf67c143e7b48a8dd53d2c5ea1ba2fe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 66.0, "max_stars_repo_stars_event_min_datetime": "2017-03-07T06:22:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T08:27:03.000Z", "max_issues_repo_path": "curves/include/curves/SE2Config.hpp", "max_issues_repo_name": "leggedrobotics/curves", "max_issues_repo_head_hexsha": "696db3e9ecf67c143e7b48a8dd53d2c5ea1ba2fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2017-01-26T15:07:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-05T10:24:17.000Z", "max_forks_repo_path": "curves/include/curves/SE2Config.hpp", "max_forks_repo_name": "leggedrobotics/curves", "max_forks_repo_head_hexsha": "696db3e9ecf67c143e7b48a8dd53d2c5ea1ba2fe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2017-01-29T02:18:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T12:35:08.000Z", "avg_line_length": 15.28, "max_line_length": 45, "alphanum_fraction": 0.7172774869, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.5429910631717398}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_3.h>\n#include <CGAL/Triangulation_vertex_base_with_info_3.h>\n#include <boost/iterator/transform_iterator.hpp>\n#include <vector>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel         K;\ntypedef CGAL::Triangulation_vertex_base_with_info_3<unsigned, K>    Vb;\ntypedef CGAL::Triangulation_data_structure_3<Vb>                    Tds;\ntypedef CGAL::Delaunay_triangulation_3<K, Tds>                      Delaunay;\ntypedef Delaunay::Point                                             Point;\n\n//a functor that returns a std::pair<Point,unsigned>.\n//the unsigned integer is incremented at each call to \n//operator()\nstruct Auto_count : public std::unary_function<const Point&,std::pair<Point,unsigned> >{\n  mutable unsigned i;\n  Auto_count() : i(0){}\n  std::pair<Point,unsigned> operator()(const Point& p) const {\n    return std::make_pair(p,i++);\n  }\n};\n\nint main()\n{\n  std::vector<Point> points;\n  points.push_back(Point(0,0,0));\n  points.push_back(Point(1,0,0));\n  points.push_back(Point(0,1,0));\n  points.push_back(Point(0,0,1));\n  points.push_back(Point(2,2,2));\n  points.push_back(Point(-1,0,1));\n\n  \n  Delaunay T( boost::make_transform_iterator(points.begin(),Auto_count()),\n              boost::make_transform_iterator(points.end(),  Auto_count() )  );\n\n  CGAL_assertion( T.number_of_vertices() == 6 );\n  \n  // check that the info was correctly set.\n  Delaunay::Finite_vertices_iterator vit;\n  for (vit = T.finite_vertices_begin(); vit != T.finite_vertices_end(); ++vit)\n    if( points[ vit->info() ] != vit->point() ){\n      std::cerr << \"Error different info\" << std::endl;\n      exit(EXIT_FAILURE);\n    }\n  std::cout << \"OK\" << std::endl;\n  \n  return 0;\n}\n", "meta": {"hexsha": "c8bd576ea1e37013ba84c9e010be2e3dcb4c252b", "size": 1774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Triangulation_3/info_insert_with_transform_iterator.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/Triangulation_3/info_insert_with_transform_iterator.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/Triangulation_3/info_insert_with_transform_iterator.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": 34.7843137255, "max_line_length": 88, "alphanum_fraction": 0.6764374295, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.542991058719482}}
{"text": "#ifndef SPARSEMATRIX_HPP\n#define SPARSEMATRIX_HPP\n\n#include <vector>\n#include <fstream>\n\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/binary_object.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/complex.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\ntemplate<class scalar>\nclass sparseMatrix\n{\npublic:\n\n  sparseMatrix();\n\n  sparseMatrix(int rows, int cols);\n \n  sparseMatrix(int rows, int cols, int nnz);\n\n  sparseMatrix(std::vector<scalar> &data, std::vector<int> &outer_, std::vector<int> &inner_, int rows, int cols);\n \n  void resize(int rows, int cols);\n\n  void reserve(int rows, int cols, int nnz);\n\n  void clear();\n\n  void save(std::string fname);\n  void load(std::string fname);\n\n  int nnz() { return nnz_; }\n  int nnz() const { return nnz_; }\n\n  int rows() { return rows_; }\n  int rows() const { return rows_; }\n\n  int cols() { return cols_; }\n  int cols() const { return cols_; }\n\n  std::vector<scalar>& data_container() { return data_; }\n  std::vector<scalar>  data_container() const { return data_; }\n\n  std::vector<int>& inner_container() { return inner_; }\n  std::vector<int>  inner_container() const { return inner_; }\n\n  std::vector<int>& outer_container() { return outer_; }\n  std::vector<int>  outer_container() const { return outer_; }\n\n  scalar* data() { return data_.data(); }\n  scalar* data() const { return data_.data(); }\n \n  int* innerPtr() { return inner_.data(); }\n  int* innerPtr() const { return inner_.data(); }\n\n  int* outerPtr() { return outer_.data(); }\n  int* outerPtr() const { return outer_.data(); }\n\n  scalar &operator[](int i) { return data_[i]; }\n  scalar &operator[](int i) const { return data_[i]; }\n  //scalar &operator()(int row, int col);\n\n  sparseMatrix& operator=(const  sparseMatrix& other);\n  sparseMatrix& operator+=(const sparseMatrix& other);\n  sparseMatrix& operator*=(const double a);\n  sparseMatrix  operator*(const double a);\n  sparseMatrix  operator+(const sparseMatrix& other);\n  sparseMatrix  operator*(const sparseMatrix& other);\n\n  /// extra member functions to fascilitation python wrapping\n  void assign(const sparseMatrix& other);\n  void setElem(scalar elem, int row, int col);\n\n  size_t size();\n\n  void print();\n\nprivate:\n\n  friend class boost::serialization::access;\n\n  template <typename Archive>\n  void serialize(Archive &ar, const unsigned int version)\n  {\n    ar & nnz_;\n    ar & cols_;\n    ar & rows_;\n    ar & data_;\n    ar & inner_;\n    ar & outer_;\n  }\n\n  /// size of matrix\n  int cols_;\n  int rows_;\n  int nnz_;\n  \n  /// container class to hold data for eigen map\n  std::vector<scalar> data_; \n\n  /// container classes to hold indices\n  std::vector<int> inner_;\n  std::vector<int> outer_;\n\n};\n\n#include \"sparseMatrix_impl.hpp\"\n\n#endif /*SPARSEMATRIX_HPP*/\n", "meta": {"hexsha": "949aae5c88ce16dcaaec7a804de7636c955a04d9", "size": 2837, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/wrapped_eigen.d/sparse.d/sparseMatrix.hpp", "max_stars_repo_name": "TtheBC01/pEigen", "max_stars_repo_head_hexsha": "090ba4389df936f9c4ce3726ea807f757c57ef1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/wrapped_eigen.d/sparse.d/sparseMatrix.hpp", "max_issues_repo_name": "TtheBC01/pEigen", "max_issues_repo_head_hexsha": "090ba4389df936f9c4ce3726ea807f757c57ef1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wrapped_eigen.d/sparse.d/sparseMatrix.hpp", "max_forks_repo_name": "TtheBC01/pEigen", "max_forks_repo_head_hexsha": "090ba4389df936f9c4ce3726ea807f757c57ef1f", "max_forks_repo_licenses": ["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.4568965517, "max_line_length": 114, "alphanum_fraction": 0.6841734226, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5429910550510005}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <utility>\n#include <vector>\n\n#include <revdoor.hpp>\n\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE(test_combinations) {\n  int n = 5;\n  int t = 3;\n  revdoor::combinations combs(n, t);\n  vector<vector<int>> states;\n  vector<int> init_state = combs.state();\n  states.push_back(init_state);\n  vector<int> expected_init_state = {0, 1, 2};\n  BOOST_CHECK_EQUAL_COLLECTIONS(\n      init_state.begin(),\n      init_state.end(),\n      expected_init_state.begin(),\n      expected_init_state.end());\n  vector<pair<int,int>> swaps;\n  vector<pair<int,int>> expected_swaps = {\n    {1, 3}, {0, 1}, {2, 0}, {1, 4}, {0, 1},\n    {1, 2}, {3, 0}, {0, 1}, {2, 0}\n  };\n  int out, in;\n  while (combs.step(&out, &in)) {\n    swaps.push_back({out, in});\n    states.push_back(combs.state());\n  }\n  BOOST_REQUIRE_EQUAL(swaps.size(), expected_swaps.size());\n  for (int i = 0; i < (int)swaps.size(); ++i) {\n    BOOST_CHECK_EQUAL(swaps[i].first, expected_swaps[i].first);\n    BOOST_CHECK_EQUAL(swaps[i].second, expected_swaps[i].second);\n  }\n  vector<int> end_state = states[states.size() - 1];\n  vector<int> expected_end_state = {0, 1, 4};\n  BOOST_CHECK_EQUAL_COLLECTIONS(\n      end_state.begin(),\n      end_state.end(),\n      expected_end_state.begin(),\n      expected_end_state.end());\n  for (int i = 0; i < (int)states.size(); ++i) {\n    combs.set_state(states[i]);\n    swaps.clear();\n    while (combs.step(&out, &in)) {\n      swaps.push_back({out, in});\n    }\n    BOOST_REQUIRE_EQUAL(swaps.size(), expected_swaps.size() - i);\n    for (int j = 0; j < (int)swaps.size(); ++j) {\n      BOOST_CHECK_EQUAL(swaps[j].first, expected_swaps[i + j].first);\n      BOOST_CHECK_EQUAL(swaps[j].second, expected_swaps[i + j].second);\n    }\n    end_state = states[states.size() - 1];\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        end_state.begin(),\n        end_state.end(),\n        expected_end_state.begin(),\n        expected_end_state.end());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_combinations_with_replacement) {\n  int n = 5;\n  int t = 3;\n  revdoor::combinations_with_replacement combs(n, t);\n  vector<vector<int>> states;\n  vector<int> init_state = combs.state();\n  states.push_back(init_state);\n  vector<int> expected_init_state = {0, 0, 0};\n  BOOST_CHECK_EQUAL_COLLECTIONS(\n      init_state.begin(),\n      init_state.end(),\n      expected_init_state.begin(),\n      expected_init_state.end());\n  vector<vector<int>> swaps;\n  vector<vector<int>> expected_swaps = {\n    {0, 1, 0, 1}, {0, 1}, {1, 0, 1, 0}, {0, 2, 1, 2}, {0, 1},\n    {1, 2}, {2, 1, 2, 0}, {0, 1}, {1, 0, 1, 0}, {0, 3, 2, 3},\n    {0, 1}, {1, 2}, {2, 3}, {3, 2, 3, 0}, {0, 1}, {1, 2},\n    {2, 1, 2, 0}, {0, 1}, {1, 0, 1, 0}, {0, 4, 3, 4}, {0, 1},\n    {1, 2}, {2, 3}, {3, 4}, {4, 3, 4, 0}, {0, 1}, {1, 2},\n    {2, 3}, {3, 2, 3, 0}, {0, 1}, {1, 2}, {2, 1, 2, 0}, {0, 1},\n    {1, 0, 1, 0}\n  };\n  int out1, in1, out2, in2;\n  while (combs.step(&out1, &in1, &out2, &in2)) {\n    vector<int> v;\n    if (out1 != in1) {\n      v.push_back(out1);\n      v.push_back(in1);\n    }\n    v.push_back(out2);\n    v.push_back(in2);\n    swaps.push_back(v);\n    states.push_back(combs.state());\n  }\n  BOOST_REQUIRE_EQUAL(swaps.size(), expected_swaps.size());\n  for (int i = 0; i < (int)swaps.size(); ++i) {\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        swaps[i].begin(),\n        swaps[i].end(),\n        expected_swaps[i].begin(),\n        expected_swaps[i].end());\n  }\n  vector<int> end_state = combs.state();\n  vector<int> expected_end_state = {0, 0, 4};\n  BOOST_CHECK_EQUAL_COLLECTIONS(\n      end_state.begin(),\n      end_state.end(),\n      expected_end_state.begin(),\n      expected_end_state.end());\n  for (int i = 0; i < (int)states.size(); ++i) {\n    combs.set_state(states[i]);\n    swaps.clear();\n    while (combs.step(&out1, &in1, &out2, &in2)) {\n      vector<int> v;\n      if (out1 != in1) {\n        v.push_back(out1);\n        v.push_back(in1);\n      }\n      v.push_back(out2);\n      v.push_back(in2);\n      swaps.push_back(v);\n    }\n    BOOST_REQUIRE_EQUAL(swaps.size(), expected_swaps.size() - i);\n    for (int j = 0; j < (int)swaps.size(); ++j) {\n      BOOST_CHECK_EQUAL_COLLECTIONS(\n          swaps[j].begin(),\n          swaps[j].end(),\n          expected_swaps[i + j].begin(),\n          expected_swaps[i + j].end());\n    }\n    end_state = states[states.size() - 1];\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        end_state.begin(),\n        end_state.end(),\n        expected_end_state.begin(),\n        expected_end_state.end());\n  }\n}\n", "meta": {"hexsha": "29f67cce4f97f5968db406a9cba0b7779aff4e4d", "size": 4523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_revdoor.cpp", "max_stars_repo_name": "dstein64/revdoor", "max_stars_repo_head_hexsha": "be768634fef3bcaf5acc12a9471771de0d686a9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-02-10T17:03:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-30T01:02:51.000Z", "max_issues_repo_path": "tests/test_revdoor.cpp", "max_issues_repo_name": "dstein64/revdoor", "max_issues_repo_head_hexsha": "be768634fef3bcaf5acc12a9471771de0d686a9a", "max_issues_repo_licenses": ["MIT"], "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_revdoor.cpp", "max_forks_repo_name": "dstein64/revdoor", "max_forks_repo_head_hexsha": "be768634fef3bcaf5acc12a9471771de0d686a9a", "max_forks_repo_licenses": ["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.9794520548, "max_line_length": 71, "alphanum_fraction": 0.5874419633, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5429910513825187}}
{"text": "//=======================================================================\n// Copyright (c) 2018 Yi Ji\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\n#include <iostream>\n#include <vector>\n#include <string>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/maximum_weighted_matching.hpp>\n\nusing namespace boost;\n\ntypedef property<edge_weight_t, float, property<edge_index_t, int> > EdgeProperty;\ntypedef adjacency_list<vecS, vecS, undirectedS, no_property, EdgeProperty> my_graph;\n\nint main(int argc, const char * argv[])\n{\n    graph_traits<my_graph>::vertex_iterator vi, vi_end;\n    const int n_vertices = 18;\n    my_graph g(n_vertices);\n    \n    // vertices can be refered by integers because my_graph use vector to store them\n    \n    add_edge(1, 2, EdgeProperty(5), g);\n    add_edge(0, 4, EdgeProperty(1), g);\n    add_edge(1, 5, EdgeProperty(4), g);\n    add_edge(2, 6, EdgeProperty(1), g);\n    add_edge(3, 7, EdgeProperty(4), g);\n    add_edge(4, 5, EdgeProperty(7), g);\n    add_edge(6, 7, EdgeProperty(5), g);\n    add_edge(4, 8, EdgeProperty(2), g);\n    add_edge(5, 9, EdgeProperty(5), g);\n    add_edge(6, 10, EdgeProperty(6), g);\n    add_edge(7, 11, EdgeProperty(5), g);\n    add_edge(10, 11, EdgeProperty(4), g);\n    add_edge(8, 13, EdgeProperty(4), g);\n    add_edge(9, 14, EdgeProperty(4), g);\n    add_edge(10, 15, EdgeProperty(7), g);\n    add_edge(11, 16, EdgeProperty(6), g);\n    add_edge(14, 15, EdgeProperty(6), g);\n    add_edge(12, 13, EdgeProperty(2), g);\n    add_edge(16, 17, EdgeProperty(5), g);\n    \n    \n    // print the ascii graph into terminal (better to use fixed-width font)\n    // this graph has a maximum cardinality matching of size 8\n    // but maximum weighted matching is of size 7\n    \n    std::vector<std::string> ascii_graph_weighted;\n    \n    ascii_graph_weighted.push_back(\"                     5                 \");\n    ascii_graph_weighted.push_back(\"           A       B---C       D       \");\n    ascii_graph_weighted.push_back(\"           1\\\\  7  /4   1\\\\  5  /4     \");\n    ascii_graph_weighted.push_back(\"             E---F       G---H         \");\n    ascii_graph_weighted.push_back(\"            2|   |5     6|   |5        \");\n    ascii_graph_weighted.push_back(\"             I   J       K---L         \");\n    ascii_graph_weighted.push_back(\"           4/    3\\\\    7/  4  \\\\6     \");\n    ascii_graph_weighted.push_back(\"       M---N       O---P       Q---R   \");\n    ascii_graph_weighted.push_back(\"         2           6           5     \");\n    \n    \n    // our maximum weighted matching and result\n    \n    std::cout << \"In the following graph:\" << std::endl << std::endl;\n    \n    for(std::vector<std::string>::iterator itr = ascii_graph_weighted.begin(); itr != ascii_graph_weighted.end(); ++itr)\n        std::cout << *itr << std::endl;\n    \n    std::cout << std::endl;\n    \n    std::vector<graph_traits<my_graph>::vertex_descriptor> mate1(n_vertices), mate2(n_vertices);\n    maximum_weighted_matching(g, &mate1[0]);\n    \n    std::cout << \"Found a weighted matching:\" << std::endl;\n    std::cout << \"Matching size is \" << matching_size(g, &mate1[0]) << \", total weight is \" << matching_weight_sum(g, &mate1[0]) << std::endl;\n    std::cout << std::endl;\n    \n    std::cout << \"The matching is:\" << std::endl;\n    for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n        if (mate1[*vi] != graph_traits<my_graph>::null_vertex() && *vi < mate1[*vi])\n            std::cout << \"{\" << *vi << \", \" << mate1[*vi] << \"}\" << std::endl;\n    std::cout << std::endl;\n    \n    \n    // now we check the correctness by compare the weight sum to a brute-force matching result\n    // note that two matchings may be different because of multiple optimal solutions\n    \n    brute_force_maximum_weighted_matching(g, &mate2[0]);\n    \n    std::cout << \"Found a weighted matching by brute-force searching:\" << std::endl;\n    std::cout << \"Matching size is \" << matching_size(g, &mate2[0]) << \", total weight is \" << matching_weight_sum(g, &mate2[0]) << std::endl;\n    std::cout << std::endl;\n    \n    std::cout << \"The brute-force matching is:\" << std::endl;\n    for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n        if (mate2[*vi] != graph_traits<my_graph>::null_vertex() && *vi < mate2[*vi])\n            std::cout << \"{\" << *vi << \", \" << mate2[*vi] << \"}\" << std::endl;\n    std::cout << std::endl;\n    \n    assert(matching_weight_sum(g, &mate1[0]) == matching_weight_sum(g, &mate2[0]));\n    \n    \n    return 0;\n}\n\n\n\n", "meta": {"hexsha": "026394cf98786e199928a754d9c9fb427df26504", "size": 4668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/graph/example/weighted_matching_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/graph/example/weighted_matching_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/graph/example/weighted_matching_example.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 41.3097345133, "max_line_length": 142, "alphanum_fraction": 0.5756212511, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.5429910509906308}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\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#include <iostream>\n\n#include <geometry_test_common.hpp>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/geometry/algorithms/make.hpp>\n#include <boost/geometry/algorithms/append.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/concepts/polygon_concept.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <boost/geometry/io/dsv/write.hpp>\n\n#include <test_common/test_point.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\n#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n#include <initializer_list>\n#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n\ntemplate <typename P>\nbg::model::polygon<P> create_polygon()\n{   \n    bg::model::polygon<P> pl1;\n    P p1;\n    P p2;\n    P p3;\n    bg::assign_values(p1, 1, 2);\n    bg::assign_values(p2, 2, 0);\n    bg::assign_values(p3, 0, 0);\n    \n    bg::append(pl1, p1);\n    bg::append(pl1, p2);\n    bg::append(pl1, p3);\n    bg::append(pl1, p1);\n    return pl1;\n}\n\ntemplate <typename PL, typename P>\nvoid check_polygon(PL& to_check, P p1, P p2, P p3)\n{   \n    PL cur;\n    bg::append(cur, p1);\n    bg::append(cur, p2);\n    bg::append(cur, p3);\n    bg::append(cur, p1);\n\n    std::ostringstream out1, out2;\n    out1 << bg::dsv(to_check);\n    out2 << bg::dsv(cur);\n    BOOST_CHECK_EQUAL(out1.str(), out2.str());\n}\n\ntemplate <typename P>\nvoid test_default_constructor()\n{\n    bg::model::polygon<P> pl1(create_polygon<P>());\n    check_polygon(pl1, P(1, 2), P(2, 0), P(0, 0));\n}\n\ntemplate <typename P>\nvoid test_copy_constructor()\n{\n    bg::model::polygon<P> pl1 = create_polygon<P>();\n    check_polygon(pl1, P(1, 2), P(2, 0), P(0, 0));\n}\n\ntemplate <typename P>\nvoid test_copy_assignment()\n{\n    bg::model::polygon<P> pl1(create_polygon<P>()), pl2;\n    pl2 = pl1;\n    check_polygon(pl2, P(1, 2), P(2, 0), P(0, 0));\n}\n\ntemplate <typename P>\nvoid test_concept()\n{   \n    typedef bg::model::polygon<P> PL;\n\n    BOOST_CONCEPT_ASSERT( (bg::concepts::ConstPolygon<PL>) );\n    BOOST_CONCEPT_ASSERT( (bg::concepts::Polygon<PL>) );\n\n    typedef typename bg::coordinate_type<PL>::type T;\n    typedef typename bg::point_type<PL>::type PPL;\n    boost::ignore_unused<T, PPL>();\n}\n\ntemplate <typename P>\nvoid test_all()\n{   \n    test_default_constructor<P>();\n    test_copy_constructor<P>();\n    test_copy_assignment<P>();\n    test_concept<P>();\n}\n\ntemplate <typename P>\nvoid test_custom_polygon(bg::model::ring<P> IL)\n{   \n#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n    std::initializer_list<bg::model::ring<P> > RIL = {IL};\n    bg::model::polygon<P> pl1(RIL);\n    std::ostringstream out;\n    out << bg::dsv(pl1);\n    BOOST_CHECK_EQUAL(out.str(), \"(((3, 3), (3, 0), (0, 0), (0, 3), (3, 3)))\");\n#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n}\n\ntemplate <typename P>\nvoid test_custom()\n{   \n    std::initializer_list<P> IL = {P(3, 3), P(3, 0), P(0, 0), P(0, 3), P(3, 3)};\n    bg::model::ring<P> r1(IL);\n    test_custom_polygon<P>(r1);\n}\n\ntemplate <typename CS>\nvoid test_cs()\n{\n    test_all<bg::model::point<int, 2, CS> >();\n    test_all<bg::model::point<float, 2, CS> >();\n    test_all<bg::model::point<double, 2, CS> >();\n\n    test_custom<bg::model::point<double, 2, CS> >();\n}\n\n\nint test_main(int, char* [])\n{   \n    test_cs<bg::cs::cartesian>();\n    test_cs<bg::cs::spherical<bg::degree> >();\n    test_cs<bg::cs::spherical_equatorial<bg::degree> >();\n    test_cs<bg::cs::geographic<bg::degree> >();\n\n    test_custom<bg::model::d2::point_xy<double> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "bf9aeb337dd5b956eba65593326097821411e973", "size": 3976, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/geometries/polygon.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T20:30:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T08:14:05.000Z", "max_issues_repo_path": "test/geometries/polygon.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/geometry/test/geometries/polygon.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 25.9869281046, "max_line_length": 80, "alphanum_fraction": 0.6680080483, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5429910505987429}}
{"text": "#include <iostream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n\nusing namespace std;\nusing namespace boost::gregorian;\n\nint main(){\n    weeks w(3);     // 3 weeks\n    cout << \"Days of 3 weeks = \" << w.days() << endl;\n\n    months m(5);\n    years  y(2);\n\n    months m2 = y + m;      //  2 Years and 5 months\n    cout << \"Months of 2 years and 5 months is \" << m2.number_of_months() << endl;\n    cout << \"Years of 2 years x 2 is \" << (y * 2).number_of_years() << endl;\n    return 0;\n}\n", "meta": {"hexsha": "e399e9a16808126ac336c0eb1cde088a2794da66", "size": 490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/boost/date_time/gregorian_date/05_length_of_date_example.cpp", "max_stars_repo_name": "Trickness/pl_learning", "max_stars_repo_head_hexsha": "53c10490aed1ba4a02b14aae4890321ad099cc60", "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/boost/date_time/gregorian_date/05_length_of_date_example.cpp", "max_issues_repo_name": "Trickness/pl_learning", "max_issues_repo_head_hexsha": "53c10490aed1ba4a02b14aae4890321ad099cc60", "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/boost/date_time/gregorian_date/05_length_of_date_example.cpp", "max_forks_repo_name": "Trickness/pl_learning", "max_forks_repo_head_hexsha": "53c10490aed1ba4a02b14aae4890321ad099cc60", "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.7894736842, "max_line_length": 82, "alphanum_fraction": 0.5897959184, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5429910380257457}}
{"text": "\n#include <boost/lexical_cast.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n#include \"flame/constants.h\"\n#include \"flame/moment.h\"\n\n#define sqr(x)  ((x)*(x))\n#define cube(x) ((x)*(x)*(x))\n\n#ifdef DEFPATH\n    #define defpath DEFPATH\n#else\n    #define defpath \".\"\n#endif\n\nstd::map<std::string,boost::shared_ptr<Config> > CurveMap;\n\n// http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?LU_Matrix_Inversion\n// by LU-decomposition.\nvoid inverse(MomentElementBase::value_t& out, const MomentElementBase::value_t& in)\n{\n    using boost::numeric::ublas::permutation_matrix;\n    using boost::numeric::ublas::lu_factorize;\n    using boost::numeric::ublas::lu_substitute;\n    using boost::numeric::ublas::identity_matrix;\n\n    MomentElementBase::value_t scratch(in); // copy\n    permutation_matrix<size_t> pm(scratch.size1());\n    if(lu_factorize(scratch, pm)!=0)\n        throw std::runtime_error(\"Failed to invert matrix\");\n    out.assign(identity_matrix<double>(scratch.size1()));\n    //out = identity_matrix<double>(scratch.size1());\n    lu_substitute(scratch, pm, out);\n}\n\nvoid RotMat(const double dx, const double dy,\n            const double theta_x, const double theta_y, const double theta_z,\n            typename MomentElementBase::value_t &R)\n{\n    typedef typename MomentElementBase::state_t state_t;\n\n    MomentState::matrix_t T = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n\n    R = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n\n    // Left-handed coordinate system => theta_y -> -theta_y.\n\n    double m11 =  cos(-theta_y)*cos(theta_z),\n           m12 =  sin(theta_x)*sin(-theta_y)*cos(theta_z) + cos(theta_x)*sin(theta_z),\n           m13 = -cos(theta_x)*sin(-theta_y)*cos(theta_z) + sin(theta_x)*sin(theta_z),\n\n           m21 = -cos(-theta_y)*sin(theta_z),\n           m22 = -sin(theta_x)*sin(-theta_y)*sin(theta_z) + cos(theta_x)*cos(theta_z),\n           m23 =  cos(theta_x)*sin(-theta_y)*sin(theta_z) + sin(theta_x)*cos(theta_z),\n\n           m31 =  sin(-theta_y),\n           m32 = -sin(theta_x)*cos(-theta_y),\n           m33 =  cos(theta_x)*cos(-theta_y);\n\n    R(0, 0) = m11, R(0, 2) = m12, R(0, 4) = m13;\n    R(2, 0) = m21, R(2, 2) = m22, R(2, 4) = m23;\n    R(4, 0) = m31, R(4, 2) = m32, R(4, 4) = m33;\n\n    R(1, 1) = m11, R(1, 3) = m12, R(1, 5) = m13;\n    R(3, 1) = m21, R(3, 3) = m22, R(3, 5) = m23;\n    R(5, 1) = m31, R(5, 3) = m32, R(5, 5) = m33;\n\n    T(0, 6) = -dx, T(2, 6) = -dy;\n\n    R = prod(R, T);\n}\n\n\nvoid GetQuadMatrix(const double L, const double K, const unsigned ind, typename MomentElementBase::value_t &M)\n{\n    // 2D quadrupole transport matrix.\n    double sqrtK,\n           psi,\n           cs,\n           sn;\n\n    if (K > 0e0) {\n        // Focusing.\n        sqrtK = sqrt(K);\n        psi = sqrtK*L;\n        cs = ::cos(psi);\n        sn = ::sin(psi);\n\n        M(ind, ind) = M(ind+1, ind+1) = cs;\n        if (sqrtK != 0e0)\n            M(ind, ind+1) = sn/sqrtK;\n        else\n            M(ind, ind+1) = L;\n        if (sqrtK != 0e0)\n            M(ind+1, ind) = -sqrtK*sn;\n        else\n            M(ind+1, ind) = 0e0;\n    } else {\n        // Defocusing.\n        sqrtK = sqrt(-K);\n        psi = sqrtK*L;\n        cs = ::cosh(psi);\n        sn = ::sinh(psi);\n\n        M(ind, ind) = M(ind+1, ind+1) = cs;\n        if (sqrtK != 0e0)\n            M(ind, ind+1) = sn/sqrtK;\n        else\n            M(ind, ind+1) = L;\n        if (sqrtK != 0e0)\n            M(ind+1, ind) = sqrtK*sn;\n        else\n            M(ind+1, ind) = 0e0;\n    }\n}\n\nvoid GetSextMatrix(const double L, const double K3, double Dx, double Dy,\n                   const double D2x, const double D2y, const double D2xy, const bool thinlens, const bool dstkick, typename MomentElementBase::value_t &M)\n{\n    typedef typename MomentElementBase::state_t state_t;\n    // 2D sextupole transport matrix.\n    double sqrtK, psi, cs, sn, ch, sh,\n           dr = sqrt(sqr(Dx)+sqr(Dx));\n\n    if (thinlens) {\n\n        //thin-lens (drift-kick-drift) model\n\n        MomentState::matrix_t T = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n        MomentState::matrix_t P = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n        MomentState::matrix_t scratch;\n\n        T(state_t::PS_X, state_t::PS_PX) = L/2e0;\n        T(state_t::PS_Y, state_t::PS_PY) = L/2e0;\n\n        P(state_t::PS_PX, state_t::PS_X) = -K3*L*Dx;\n        P(state_t::PS_PX, state_t::PS_Y) =  K3*L*Dy;\n\n        P(state_t::PS_PY, state_t::PS_X) = K3*L*Dy;\n        P(state_t::PS_PY, state_t::PS_Y) = K3*L*Dx;\n\n        scratch = prod(P,T);\n        M = prod(T,scratch);\n\n    } else {\n\n        //thick-lens model\n\n        sqrtK = sqrt(fabs(K3)*dr);\n        psi = sqrtK*L;\n\n        // Focusing or Defocusing switch\n        Dx *= copysign(1e0,K3);\n        Dy *= copysign(1e0,K3);\n\n        cs = ::cos(psi);\n        sn = ::sin(psi);\n        ch = ::cosh(psi);\n        sh = ::sinh(psi);\n\n\n        if (sqrtK != 0e0) {\n            M(state_t::PS_X, state_t::PS_X) = M(state_t::PS_PX, state_t::PS_PX) = ((dr+Dx)*cs+(dr-Dx)*ch)/(2e0*dr);\n            M(state_t::PS_X, state_t::PS_PX) = ((dr+Dx)*sn+(dr-Dx)*sh)/(2e0*sqrtK*dr);\n            M(state_t::PS_X, state_t::PS_Y)  = M(state_t::PS_PX, state_t::PS_PY) =\n            M(state_t::PS_Y, state_t::PS_X)  = M(state_t::PS_PY, state_t::PS_PX) = Dy*(-cs+ch)/(2e0*dr);\n            M(state_t::PS_X, state_t::PS_PY) = Dy*(-sn+sh)/(2e0*sqrtK*dr);\n\n            M(state_t::PS_PX, state_t::PS_X) = sqrtK*(-(dr+Dx)*sn+(dr-Dx)*sh)/(2e0*dr);\n            M(state_t::PS_PX, state_t::PS_Y) = M(state_t::PS_PY, state_t::PS_X) =  Dy*sqrtK*(sn+sh)/(2e0*dr);\n\n            M(state_t::PS_Y, state_t::PS_PX) = Dy*(-sn+sh)/(2e0*sqrtK*dr);\n            M(state_t::PS_Y, state_t::PS_Y) = M(state_t::PS_PY, state_t::PS_PY) = ((dr-Dx)*cs+(dr+Dx)*ch)/(2e0*dr);\n            M(state_t::PS_Y, state_t::PS_PY) = ((dr-Dx)*sn+(dr+Dx)*sh)/(2e0*sqrtK*dr);\n\n            M(state_t::PS_PY, state_t::PS_Y) = sqrtK*(-(dr-Dx)*sn+(dr+Dx)*sh)/(2e0*dr);\n\n        } else {\n            M(state_t::PS_X, state_t::PS_PX) = L;\n            M(state_t::PS_Y, state_t::PS_PY) = L;\n        }\n\n    } // option\n    if (dstkick){\n        M(state_t::PS_PX, 6) = -K3*L*(D2x-D2y);\n        M(state_t::PS_PY, 6) =  2e0*K3*L*D2xy;\n    }\n}\n\nvoid GetEdgeMatrix(const double rho, const double phi, typename MomentElementBase::value_t &M)\n{\n    typedef typename MomentElementBase::state_t state_t;\n\n    M = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n\n    M(state_t::PS_PX, state_t::PS_X) =  tan(phi)/rho;\n    M(state_t::PS_PY, state_t::PS_Y) = -tan(phi)/rho;\n}\n\n\nvoid GetEEdgeMatrix(const double fringe_x, const double fringe_y, const double kappa, typename MomentElementBase::value_t &M)\n{\n    // Edge focusing for electrostatic dipole.\n    typedef typename MomentElementBase::state_t state_t;\n\n    M = boost::numeric::ublas::identity_matrix<double>(state_t::maxsize);\n\n    M(state_t::PS_PX, state_t::PS_X)  = fringe_x;\n    M(state_t::PS_PX, state_t::PS_PX) = sqrt(1e0+kappa);\n    M(state_t::PS_PY, state_t::PS_Y)  = fringe_y;\n    M(state_t::PS_PS, state_t::PS_PS) = 1e0+kappa;\n}\n\n\nvoid GetSBendMatrix(const double L, const double phi, const double phi1, const double phi2, const double K,\n                    const double IonEs, const double ref_gamma, const double qmrel,\n                    const double dip_beta, const double dip_gamma, const double d, const double dip_IonK, typename MomentElementBase::value_t &M)\n{\n    typedef typename MomentElementBase::state_t state_t;\n\n    MomentState::matrix_t edge1, edge2, R;\n\n    double  rho = L/phi,\n            Kx  = K + 1e0/sqr(rho),\n            Ky  = -K,\n            dx  = 0e0,\n            sx  = 0e0;\n\n    // Horizontal plane.\n    GetQuadMatrix(L, Kx, (unsigned)state_t::PS_X, M);\n    // Vertical plane.\n    GetQuadMatrix(L, Ky, (unsigned)state_t::PS_Y, M);\n\n    // Include dispersion.\n    if (Kx == 0e0) {\n        dx = sqr(L)/(2e0*rho);\n        sx = L/rho;\n    } else if (Kx > 0e0) {\n        dx = (1e0-cos(sqrt(Kx)*L))/(rho*Kx);\n        sx = sin(sqrt(Kx)*L)/(rho*sqrt(Kx));\n    } else {\n        dx = (1e0-cosh(sqrt(-Kx)*L))/(rho*Kx);\n        sx = sin(sqrt(-Kx)*L)/(rho*sqrt(-Kx));\n    }\n\n    M(state_t::PS_X,  state_t::PS_PS) = dx/(sqr(dip_beta)*dip_gamma*IonEs/MeVtoeV);\n    M(state_t::PS_PX, state_t::PS_PS) = sx/(sqr(dip_beta)*dip_gamma*IonEs/MeVtoeV);\n\n    M(state_t::PS_S,  state_t::PS_X)  = sx*dip_IonK;\n    M(state_t::PS_S,  state_t::PS_PX) = dx*dip_IonK;\n    // Low beta approximation.\n    M(state_t::PS_S,  state_t::PS_PS) =\n            ((L/rho-sx)/(Kx*rho)-L/sqr(ref_gamma))*dip_IonK\n            /(sqr(dip_beta)*dip_gamma*IonEs/MeVtoeV);\n\n    // Add dipole terms.\n    M(state_t::PS_S,  6) = ((L/rho-sx)/(Kx*rho)*d-L/sqr(ref_gamma)*(d+qmrel))*dip_IonK;\n    M(state_t::PS_X,  6) = dx*d;\n    M(state_t::PS_PX, 6) = sx*d;\n\n    // Edge focusing.\n    GetEdgeMatrix(rho, phi1, edge1);\n    GetEdgeMatrix(rho, phi2, edge2);\n\n    M = prod(M, edge1);\n    M = prod(edge2, M);\n\n    // Longitudinal plane.\n    // For total path length.\n    //        M(state_t::PS_S,  state_t::PS_S) = L;\n}\n\n\nvoid GetSolMatrix(const double L, const double K, typename MomentElementBase::value_t &M)\n{\n    typedef typename MomentElementBase::state_t state_t;\n\n    double C = ::cos(K*L),\n           S = ::sin(K*L);\n\n    M(state_t::PS_X, state_t::PS_X)\n            = M(state_t::PS_PX, state_t::PS_PX)\n            = M(state_t::PS_Y, state_t::PS_Y)\n            = M(state_t::PS_PY, state_t::PS_PY)\n            = sqr(C);\n\n    if (K != 0e0)\n        M(state_t::PS_X, state_t::PS_PX) = S*C/K;\n    else\n        M(state_t::PS_X, state_t::PS_PX) = L;\n    M(state_t::PS_X, state_t::PS_Y) = S*C;\n    if (K != 0e0)\n        M(state_t::PS_X, state_t::PS_PY) = sqr(S)/K;\n    else\n        M(state_t::PS_X, state_t::PS_PY) = 0e0;\n\n    M(state_t::PS_PX, state_t::PS_X)  = -K*S*C;\n    M(state_t::PS_PX, state_t::PS_Y)  = -K*sqr(S);\n    M(state_t::PS_PX, state_t::PS_PY) = S*C;\n\n    M(state_t::PS_Y, state_t::PS_X)   = -S*C;\n    if (K != 0e0)\n        M(state_t::PS_Y, state_t::PS_PX) = -sqr(S)/K;\n    else\n        M(state_t::PS_Y, state_t::PS_PX) = 0e0;\n    if (K != 0e0)\n        M(state_t::PS_Y, state_t::PS_PY) = S*C/K;\n    else\n        M(state_t::PS_Y, state_t::PS_PY) = L;\n\n    M(state_t::PS_PY, state_t::PS_X)  = K*sqr(S);\n    M(state_t::PS_PY, state_t::PS_PX) = -S*C;\n    M(state_t::PS_PY, state_t::PS_Y)  = -K*S*C;\n\n    // Longitudinal plane.\n    // For total path length.\n//        M(state_t::PS_S, state_t::PS_S) = L;\n}\n\n\nvoid GetEBendMatrix(const double L, const double phi, const double fringe_x, const double fringe_y, const double kappa,\n                    const double Kx, const double Ky, const double IonEs, const double real_gamma, const double eta0, const double h,\n                    const double delta_K, const double delta_KZ, const double SampleIonK, typename MomentElementBase::value_t &M)\n{\n    typedef typename MomentElementBase::state_t state_t;\n\n    MomentState::matrix_t edge;\n\n    double  rho = L/phi,\n            scl = (real_gamma - 1e0)*IonEs/MeVtoeV,\n            dx  = 0e0,\n            sx  = 0e0;\n\n    // Horizontal plane.\n    GetQuadMatrix(L, Kx, (unsigned)state_t::PS_X, M);\n    // Vertical plane.\n    GetQuadMatrix(L, Ky, (unsigned)state_t::PS_Y, M);\n\n    // Include dispersion.\n    if (Kx == 0e0) {\n        dx = 0e0;\n        sx = 0e0;\n    } else if (Kx > 0e0) {\n        dx = (1e0-cos(sqrt(Kx)*L))/(rho*Kx);\n        sx = sin(sqrt(Kx)*L)/sqrt(Kx);\n    } else {\n        dx = (1e0-cosh(sqrt(-Kx)*L))/(rho*Kx);\n        sx = sin(sqrt(Kx)*L)/sqrt(Kx);\n    }\n\n    double Nk   = (sqr(1e0+2e0*eta0)+h)/(2e0*(1e0+eta0)*(1e0+2e0*eta0)),\n           Nt   = 1e0 + h/sqr(1e0+2e0*eta0),\n           CorT = -real_gamma/(1e0+real_gamma),\n           tx   = sx/rho*Nt*CorT,\n           txp  = dx*Nt*CorT,\n           tzp  = (-L/(2e0*(1e0+eta0)*(1e0+2e0*eta0))+((L-sx)/Kx/sqr(rho))*Nk*Nt)*CorT;\n\n    M(state_t::PS_X,  state_t::PS_PS) = dx*Nk/scl;\n    M(state_t::PS_PX, state_t::PS_PS) = sx/rho*Nk/scl;\n\n    M(state_t::PS_S,  state_t::PS_X)  = -tx*SampleIonK;\n    M(state_t::PS_S,  state_t::PS_PX) = -txp*SampleIonK;\n    // Low beta approximation.\n    M(state_t::PS_S,  state_t::PS_PS) = -tzp*SampleIonK/scl;\n\n    // Add dipole terms.\n    double Nkz = (1e0+2e0*eta0-h)/(2e0*(1e0+eta0)*(1e0+2e0*eta0));\n\n    M(state_t::PS_X,  6) = dx*(Nk*delta_K+Nkz*delta_KZ);\n    M(state_t::PS_PX, 6) = sx/rho*(Nk*delta_K+Nkz*delta_KZ);\n\n    // Edge focusing.\n    GetEEdgeMatrix(fringe_x, fringe_y ,kappa, edge);\n\n    M = prod(M, edge);\n    M = prod(edge, M);\n\n    // Longitudinal plane.\n    // For total path length.\n    //        M(state_t::PS_S,  state_t::PS_S) = L;\n}\n\nvoid GetCurveData(const Config &c, const unsigned ncurve, std::vector<double> &Scales,\n                  std::vector<std::vector<double> > &Curves)\n{\n    boost::shared_ptr<Config> conf;\n\n    std::string filename;\n    std::vector<double> range;\n    bool checker = c.tryGet<std::string>(\"CurveFile\", filename),\n         rngchecker = c.tryGet<std::vector<double> >(\"use_range\", range);\n\n    if (checker){\n        std::string CurveFile =  c.get<std::string>(\"Eng_Data_Dir\", defpath);\n        CurveFile += \"/\" + filename;\n        std::string key(SB()<<CurveFile<<\"|\"<<boost::filesystem::last_write_time(CurveFile));\n        if ( CurveMap.find(key) == CurveMap.end() ) {\n            // not found in CurveMap\n            try {\n                try {\n                    GLPSParser P;\n                    conf.reset(P.parse_file(CurveFile.c_str(), false));\n                }catch(std::exception& e){\n                    throw std::runtime_error(SB()<<\"Parse error: \"<<e.what()<<\"\\n\");\n                }\n\n            }catch(std::exception& e){\n                throw std::runtime_error(SB()<<\"Error: \"<<e.what()<<\"\\n\");\n            }\n            CurveMap.insert(std::make_pair(key, conf));\n        } else {\n            // found in CurveMap\n            conf=CurveMap[key];\n        }\n    }\n\n    size_t prev_size = 0;\n    for (unsigned n=0; n<ncurve; n++) {\n        std::string num(boost::lexical_cast<std::string>(n));\n        std::vector<double> cv;\n        bool cvchecker;\n        if (checker){\n            cvchecker = conf->tryGet<std::vector<double> >(\"curve\"+num, cv);\n        } else {\n            cvchecker = c.tryGet<std::vector<double> >(\"curve\"+num, cv);\n        }\n        if (!cvchecker)throw std::runtime_error(SB()<<\"'curve\" << num << \"' is missing in lattice file.\\n\");\n\n        if (rngchecker){\n            unsigned start, end;\n            if (range.size() != 2)\n                throw std::runtime_error(SB()<<\"Size of 'use_range' must be 2.\\n\");\n            start = static_cast<unsigned>(range[0]);\n            end   = static_cast<unsigned>(range[1]);\n\n            if (start > cv.size() or end > cv.size())\n                throw std::runtime_error(SB()<<\"'use_range' is out of curve size.\\n\");\n\n            std::vector<double> part(cv.begin()+start, cv.begin()+end);\n            Curves.push_back(part);\n        } else {\n            Curves.push_back(cv);\n        }\n\n        if (n != 0 and prev_size != cv.size())\n            throw std::runtime_error(SB()<<\"Size of 'curve\" << n << \"' (\" << cv.size() <<\") and 'curve\" << n-1 <<\n                                           \"' (\" << prev_size <<\") are inconsistent.  All curves must have the same size.\\n\");\n        prev_size = cv.size();\n\n        Scales.push_back(c.get<double>(\"scl_fac\"+num, 0.0));\n    }\n}", "meta": {"hexsha": "6f5387efb3609c1c7a371c048fdddc89fe21a73b", "size": 15365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/moment_sup.cpp", "max_stars_repo_name": "PierreSchnizer/FLAME", "max_stars_repo_head_hexsha": "44f42c6175be536236058452bec71c87a138710e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2016-04-04T20:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T22:37:49.000Z", "max_issues_repo_path": "src/moment_sup.cpp", "max_issues_repo_name": "PierreSchnizer/FLAME", "max_issues_repo_head_hexsha": "44f42c6175be536236058452bec71c87a138710e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2016-04-07T19:23:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T14:31:14.000Z", "max_forks_repo_path": "src/moment_sup.cpp", "max_forks_repo_name": "PierreSchnizer/FLAME", "max_forks_repo_head_hexsha": "44f42c6175be536236058452bec71c87a138710e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2016-04-13T13:26:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-20T01:55:24.000Z", "avg_line_length": 33.8436123348, "max_line_length": 154, "alphanum_fraction": 0.5640741946, "num_tokens": 5078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5429654671581736}}
{"text": "#include <pa/stages/color_generator.hpp>\n\n#define _USE_MATH_DEFINES\n\n#include <algorithm>\n#include <cmath>\n#include <cstddef>\n\n#include <boost/algorithm/clamp.hpp>\n#include <tbb/tbb.h>\n\n#include <pa/math/convert/coordinates.hpp>\n\nnamespace pa\n{\nvoid    color_generator::generate(integral_curves* integral_curves, mode mode, scalar constant_parameter)\n{\n  auto& vertices = integral_curves->vertices;\n  auto& colors   = integral_curves->colors  ;\n  auto& indices  = integral_curves->indices ;\n\n  colors.resize(vertices.size());\n\n  tbb::parallel_for(std::size_t(0), indices.size(), std::size_t(1), [&] (const std::size_t i)\n  {\n    auto& index   = indices[i];\n    auto  tangent = (vertices[index + 1] - vertices[index]).normalized();\n    \n    if      (mode == mode::hsl_constant_s) colors[index] = map_hsl(tangent, true , constant_parameter);\n    else if (mode == mode::hsl_constant_l) colors[index] = map_hsl(tangent, false, constant_parameter);\n    else if (mode == mode::hsv_constant_s) colors[index] = map_hsv(tangent, true , constant_parameter);\n    else if (mode == mode::hsv_constant_v) colors[index] = map_hsv(tangent, false, constant_parameter);\n    else if (mode == mode::rgb           ) colors[index] = map_rgb(tangent);\n\n    // Last vertex also gets a color.\n    if (i != indices.size() - 1 && indices[i + 1] != index + 1)\n      colors[index + 1] = colors[index];\n  });\n}\n\nvector4 color_generator::correct_range  (vector4 spherical )\n{\n  if (spherical[1] <  scalar(0))          spherical[1] += scalar(M_PI);\n  if (spherical[1] >= scalar(M_PI))       spherical[1] -= scalar(M_PI);\n  spherical[1] = scalar(M_PI) - spherical[1];\n  \n  if (spherical[2] <  scalar(0))          spherical[2]  = std::abs(spherical[2]);\n  if (spherical[2] >= scalar(M_PI / 2.0)) spherical[2]  = scalar(M_PI) - spherical[2];\n    \n  spherical[1] = scalar(spherical[1] / M_PI);\n  spherical[2] = scalar(spherical[2] / (M_PI / 2.0f));\n  \n  return spherical;\n}\nvector4 color_generator::hue_to_rgba    (const scalar   hue)\n{\n  return vector4\n  (\n    static_cast<scalar>(boost::algorithm::clamp(std::abs(6.0f * hue - 3.0f) - 1.0f, 0.0f, 1.0f)),\n    static_cast<scalar>(boost::algorithm::clamp(2.0f - std::abs(6.0f * hue - 2.0f), 0.0f, 1.0f)),\n    static_cast<scalar>(boost::algorithm::clamp(2.0f - std::abs(6.0f * hue - 4.0f), 0.0f, 1.0f)),\n    1.0f\n  );\n}\nvector4 color_generator::hsl_to_rgba    (const vector4& hsl)\n{\n  auto color      = hue_to_rgba(hsl[0]);\n  auto precompute = (1.0F - std::abs(2.0F * hsl[2] - 1.0F)) * hsl[1];\n  color           = (color.array() - 0.5F) * precompute + hsl[2];\n  color[3]        = 1.0f;\n  return color;\n}\nvector4 color_generator::hsv_to_rgba    (const vector4& hsv)\n{\n  auto color = hue_to_rgba(hsv[0]);\n  color      = ((color.array() - 1.0f) * hsv[1] + 1.0f) * hsv[2];\n  color[3]   = 1.0f;\n  return color;\n}\n  \nvector4 color_generator::map_hsl        (const vector4& tangent, const bool constant_saturation = true, const scalar constant_parameter = scalar(0.5))\n{\n  auto spherical = correct_range(to_spherical(tangent));\n  return constant_saturation \n    ? hsl_to_rgba(vector4(spherical[1], constant_parameter, spherical[2]      , 0.0f))\n    : hsl_to_rgba(vector4(spherical[1], spherical[2]      , constant_parameter, 0.0f));\n}\nvector4 color_generator::map_hsv        (const vector4& tangent, const bool constant_saturation = true, const scalar constant_parameter = scalar(0.5))\n{\n  auto spherical = correct_range(to_spherical(tangent));\n  return constant_saturation \n    ? hsv_to_rgba(vector4(spherical[1], constant_parameter, spherical[2]      , 0.0f)) \n    : hsv_to_rgba(vector4(spherical[1], spherical[2]      , constant_parameter, 0.0f));\n}\nvector4 color_generator::map_rgb        (const vector4& tangent)\n{\n  return vector4(std::abs(tangent[0]), std::abs(tangent[2]), std::abs(tangent[1]), 1.0f);\n}\n}", "meta": {"hexsha": "5dad6e8e259545de4c89f2cc37fbb0e06bc6c719", "size": 3818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pa/source/stages/color_generator.cpp", "max_stars_repo_name": "acdemiralp/pars", "max_stars_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-12T18:20:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T12:04:14.000Z", "max_issues_repo_path": "pa/source/stages/color_generator.cpp", "max_issues_repo_name": "acdemiralp/pars", "max_issues_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pa/source/stages/color_generator.cpp", "max_forks_repo_name": "acdemiralp/pars", "max_forks_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-18T14:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T14:35:49.000Z", "avg_line_length": 38.5656565657, "max_line_length": 150, "alphanum_fraction": 0.6602933473, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5429654592276711}}
{"text": "#ifndef TRIUMF_BNMR_SLR_GAUSS_DIST_EXP_HPP\n#define TRIUMF_BNMR_SLR_GAUSS_DIST_EXP_HPP\n\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n#include <triumf/bnmr/slr/common.hpp>\n#include <triumf/math/faddeeva.hpp>\n#include <iostream>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// \u03b2-detected nuclear magnetic resonance (\u03b2-NMR)\nnamespace bnmr {\n\n// spin-lattice relaxation (SLR)\nnamespace slr {\n\n/// pulsed Gaussian distribution of exponentials integral\n/// (from 0 to time_p <= time)\ntemplate <typename T = double>\nT pulsed_gauss_dist_exp_integral(T time, T time_p, T nuclear_lifetime,\n                                 T slr_rate, T sigma) {\n  // imaginary number i\n  std::complex<T> i(0.0, -1.0);\n  // common exponential factor\n  T expo =\n      std::exp(-slr_rate / nuclear_lifetime / sigma / sigma -\n               1.0 / 2.0 / sigma / sigma / nuclear_lifetime / nuclear_lifetime -\n               slr_rate * slr_rate / 2.0 / sigma / sigma);\n  std::cout << \"expo = \" << expo << \"\\n\";\n  // argument for the first error function\n  std::complex<T> erf_arg1 =\n      (((boost::math::constants::root_two<T>() * i * time -\n         boost::math::constants::root_two<T>() * i * time_p) *\n            sigma * sigma -\n        boost::math::constants::root_two<T>() * i * slr_rate) *\n           nuclear_lifetime -\n       boost::math::constants::root_two<T>() * i) /\n      (2.0 * sigma * nuclear_lifetime);\n  std::cout << \"erf_arg1 = \" << erf_arg1 << \"\\n\";\n  // argument for the second error function\n  std::complex<T> erf_arg2 =\n      ((i * time * sigma * sigma - i * slr_rate) * nuclear_lifetime - i) /\n      (boost::math::constants::root_two<T>() * sigma * nuclear_lifetime);\n  std::cout << \"erf_arg2 = \" << erf_arg2 << \"\\n\";\n  // evaluate the result\n  std::complex<T> result = boost::math::constants::root_pi<T>() * i * expo *\n                           (triumf::math::faddeeva::erf(erf_arg1) -\n                            triumf::math::faddeeva::erf(erf_arg2)) /\n                           (boost::math::constants::root_two<T>() * sigma);\n  std::cout << \"result = \" << result << \"\\n\";\n  // return only the real part\n  return result.real();\n}\n\n/// pulsed Gaussian distribution of exponentials\ntemplate <typename T = double>\nT pulsed_gauss_dist_exp(T time, T nuclear_lifetime, T pulse_length, T asymmetry,\n                        T slr_rate, T sigma) {\n  if (time == 0.0) {\n    return asymmetry;\n  } else if (time > 0.0 and time <= pulse_length) {\n    return asymmetry *\n           pulsed_gauss_dist_exp_integral(time, time, nuclear_lifetime,\n                                          slr_rate, sigma) /\n           normalization(time, nuclear_lifetime);\n  } else if (time > pulse_length) {\n    return (asymmetry *\n            pulsed_gauss_dist_exp_integral(pulse_length, pulse_length,\n                                           nuclear_lifetime, slr_rate, sigma) /\n            normalization(pulse_length, nuclear_lifetime)) /\n           std::exp(-(time - pulse_length) / nuclear_lifetime);\n  } else {\n    return 0.0;\n  }\n}\n\n/// pulsed Gaussian distribution of exponentials (ROOT)\ntemplate <typename T = double>\nT pulsed_gauss_dist_exp(const T *x, const T *par) {\n  return pulsed_gauss_dist_exp<T>(*x, par[0], par[1], par[2], par[3], par[4]);\n}\n\n} // namespace slr\n\n} // namespace bnmr\n\n} // namespace triumf\n\n#endif // TRIUMF_BNMR_SLR_GAUSS_DIST_EXP_HPP\n", "meta": {"hexsha": "58b1aa5b429fb99e3baaa1810487112931a1ad46", "size": 3378, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tmp/gauss_dist_exp.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": "tmp/gauss_dist_exp.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": "tmp/gauss_dist_exp.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": 36.7173913043, "max_line_length": 80, "alphanum_fraction": 0.6163410302, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5429607172802771}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\n#include <ancse/config.hpp>\n#include <ancse/polynomial_basis.hpp>\n#include <ancse/dg_handler.hpp>\n#include <ancse/dg_limiting.hpp>\n#include <ancse/cfl_condition.hpp>\n#include <ancse/dg_rate_of_change.hpp>\n#include <ancse/snapshot_writer.hpp>\n#include <ancse/time_loop.hpp>\n\nstatic int n_vars = 3;\n\ntemplate<class F>\nEigen::MatrixXd ic(const F &f,\n                   const Grid &grid,\n                   const PolynomialBasis &poly_basis,\n                   const DGHandler &dg_handler)\n{\n    int n_coeff = 1 + poly_basis.get_degree();\n    Eigen::MatrixXd u0 = Eigen::MatrixXd::Zero (n_vars*n_coeff,\n                                                grid.n_cells);\n\n    auto [quad_points, quad_weights] = dg_handler.get_quadrature();\n    int n_quad = static_cast<int>(quad_points.size());\n\n    /// eval basis and its derivate for all quadrature points\n    Eigen::MatrixXd basis(n_coeff, n_quad);\n    for (int k = 0; k < n_quad; k++) {\n        basis.col(k) = poly_basis(quad_points(k));\n    }\n\n    // L2-projection\n    for (int j = 0; j < grid.n_cells; ++j)\n    {\n        for (int k = 0; k < quad_points.size(); k++)\n        {\n            auto fVal = f(cell_point(grid, j, quad_points(k)));\n            for (int i = 0; i < n_vars; i++) {\n                u0.col(j).segment(i*n_coeff, n_coeff)\n                        += quad_weights(k)*fVal(i)*basis.col(k);\n            }\n        }\n    }\n\n    return u0*grid.dx;\n}\n\nTimeLoop make_dg(const nlohmann::json &config,\n                 const Grid &grid,\n                 const PolynomialBasis &poly_basis,\n                 const DGHandler &dg_handler,\n                 std::shared_ptr<Model> &model)\n{\n    double t_end = config[\"t_end\"];\n    double cfl_number = config[\"cfl_number\"];\n\n    auto n_ghost = grid.n_ghost;\n    auto n_cells = grid.n_cells;\n\n    auto n_vars = model->get_nvars();\n    int n_coeff = 1 + poly_basis.get_degree();\n\n    auto simulation_time = std::make_shared<SimulationTime>(t_end);\n    auto boundary_condition\n            = make_boundary_condition(n_ghost,\n                                      config[\"boundary_condition\"]);\n    auto dg_rate_of_change\n            = make_dg_rate_of_change(config, grid, model,\n                                     poly_basis, dg_handler,\n                                     simulation_time);\n    auto dg_limiting\n            = make_dg_limiting(config, grid, dg_handler);\n    auto time_integrator = make_runge_kutta(config,\n                                            dg_rate_of_change,\n                                            boundary_condition,\n                                            dg_limiting,\n                                            n_vars*n_coeff, n_cells);\n    auto cfl_condition\n            = make_cfl_condition(grid, model, dg_handler, cfl_number);\n    auto snapshot_writer = std::make_shared<JSONSnapshotWriter <DG>>\n            (grid, model, dg_handler, simulation_time,\n             std::string(config[\"output_dir\"]),\n             std::string(config[\"output_file\"]));\n\n    return TimeLoop(simulation_time, time_integrator,\n                    cfl_condition, snapshot_writer);\n}\n\nvoid sod_shock_tube_test(const nlohmann::json &config)\n{\n    int deg = int(config[\"degree\"]);\n\n    double gamma = 7./5.;\n    std::shared_ptr<Model> model = std::make_shared<Euler>();\n    auto model_euler = dynamic_cast<Euler*>(model.get());\n    model_euler->set_gamma(gamma);\n\n    auto fn = [gamma](double x) {\n        Eigen::VectorXd u(n_vars);\n        if (x <= 0.5) { // left state\n            u(0) = 1;\n            u(1) = 0;\n            u(2) = 1/(gamma-1);\n        } else {        // right state\n            u(0) = 0.125;\n            u(1) = 0;\n            u(2) = 0.1/(gamma-1);\n        }\n        return u;\n    };\n\n    int n_ghost = config[\"n_ghost\"];\n    int n_cells = int(config[\"n_interior_cells\"]) + n_ghost * 2;\n\n    auto grid = Grid({0.0, 1.0}, n_cells, n_ghost);\n    auto poly_basis = PolynomialBasis(deg, 1./sqrt(grid.dx));\n    auto dg_handler = DGHandler(model, poly_basis);\n    auto u0 = ic(fn, grid, poly_basis, dg_handler);\n\n    auto dg = make_dg(config, grid, poly_basis, dg_handler, model);\n    dg(u0);\n}\n\nint main(int argc, char* const argv[])\n{\n    nlohmann::json config;\n    std::string fileName;\n    if (argc == 2) {\n        fileName = argv[1];\n    } else {\n        fileName = \"../config.json\";\n    }\n    config = get_config (fileName);\n\n    std::string ic_key = config[\"initial_conditions\"];\n    if (ic_key == \"sod_shock_tube\") {\n        sod_shock_tube_test(config);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "4fdce2b85caee9eef9a04a293424ffea1a23db54", "size": 4556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series2_handout/hyp_sys_1d/src/dg_euler.cpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_handout/hyp_sys_1d/src/dg_euler.cpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_handout/hyp_sys_1d/src/dg_euler.cpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 31.6388888889, "max_line_length": 70, "alphanum_fraction": 0.5614574188, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.542872051733651}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Hidekazu Ikeno\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\n * THE SOFTWARE.\n */\n\n#include <iomanip>\n#include <iostream>\n\n#include \"constants.hpp\"\n#include \"legendre.hpp\"\n#include \"tanh_sinh_rule.hpp\"\n\n#include <mxpfit/aak_reduction.hpp>\n#include <mxpfit/balanced_truncation.hpp>\n#include <mxpfit/exponential_sum.hpp>\n\n#include <boost/math/special_functions/bessel.hpp>\n\ntemplate <typename T>\nconstexpr T pi()\n{\n    return T(\n        3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679);\n}\n///\n/// ### BesselKernel\n///\n/// Compute the multi-exponential function that approximates the spherical\n/// Bessel function of the first kind such that\n///\n/// \\f[\n///   \\|j_{n}(x)-sum_{m=1}^{M} w_{m} e^{-a_{m} x} \\| < \\epsilon\n/// \\f]\n///\n/// for integer `n` on real axis `(x)`, where \\f$ \\epsilon \\f$ is an arbitrary\n/// small positive number.\n///\n/// The multi-exponential function is obtained by discretize the integral\n/// representation of spherical Bessel function\n///\n/// \\f[\n///   j_{n}(x)=\\int_{-1}^{1} e^{ixt} P_n(t) dt\n/// \\f]\n///\n/// The integrand in above expression is highly oscillating when `x` becomes\n/// large, thus the direct application of some quadrature rule is inefficient.\n/// To avoid this problem, we extend the integral on the complex plane and\n/// select the contour as the steepest descent paths, as follows.\n///\n/// \\f{eqnarray*}{\n///   j_{n}(x) &=& I_1 + I_2 + (-1)^{n}(I_1^{\\ast} + I_{2}^{\\ast}), \\\\\n///   I_{1} &=& \\frac{(-i)^{n+1}}{2} \\int_{0}^{R} e^{-(y-i)x} P_{n}(1+iy) dy, \\\\\n///   I_{2} &=& \\frac{(-i)^{n}}{2} \\int_{-1}^{0} e^{-(R-ix)y} P_{n}(y+iR) dy, \\\\\n/// \\f}\n///\n/// The integrals \\f$ I_1 \\f$ and \\f$ I_2 \\f$ are discretized using appropriate\n/// quadrature rule, then the balanced truncation method is applied to reduce\n/// the number of terms.\n///\ntemplate <typename T>\nclass BesselKernel\n{\npublic:\n    typename VecY, using Index = Eigen::Index;\n    using Real    = T;\n    using Complex = std::complex<Real>;\n\n    using ExponentialSumType = mxpfit::ExponentialSum<Complex, Complex>;\n    using ExponentsArray     = typename ExponentialSumType::ExponentsArray;\n    using WeightsArray       = typename ExponentialSumType::WeightsArray;\n\n    static ExponentialSumType compute(Index order, Real threshold);\n};\n\ntemplate <typename T>\ntypename BesselKernel<T>::ExponentialSumType\nBesselKernel<T>::compute(Index n, Real threshold)\n{\n    using Eigen::numext::conj;\n    using Eigen::numext::exp;\n    using Eigen::numext::log;\n    using Eigen::numext::cos;\n    using Eigen::numext::acos;\n    using Eigen::numext::sin;\n    using Eigen::numext::sqrt;\n    // ----- Constants\n    constexpr const auto zero = Real();\n    constexpr const auto one  = Real(1);\n    constexpr const auto half = Real(0.5);\n    constexpr const auto eps  = std::numeric_limits<Real>::epsilon();\n    // (-i)^n\n    constexpr const Complex pow_i[4] = {Complex(one, zero), Complex(zero, -one),\n                                        Complex(-one, zero),\n                                        Complex(zero, one)};\n\n    //----- adjustable parameters\n    const auto R = Real(3) / std::max(Index(1), n);\n\n    const auto n_quad1 = Index(500);\n    const auto tiny1   = sqrt(eps) * threshold / n_quad1;\n\n    const auto n_quad2 = Index(150 + 2 * n);\n    const auto tiny2   = eps / n_quad2;\n    //---------------------------\n\n    //\n    // Find R_shift such that j_n(R_shift) < eps\n    //\n    Real R_shift = Real();\n    if (n > Index())\n    {\n        Real log_dfact = Real(); // log[2^n * n!]\n        for (Index k = 1; k <= n; ++k)\n        {\n            log_dfact += log(Real(2 * k));\n        }\n        const auto thresh = std::min(threshold, sqrt(eps));\n        R_shift           = exp((log_dfact + log(thresh)) / Real(n));\n        if (R_shift < Real(0.1))\n        {\n            R_shift = Real();\n        }\n    }\n\n    ExponentialSumType es_merged(n_quad1 + n_quad2);\n\n    //\n    // Discretization of integral I_2 on the path `z = x + iR` for `0<=x<=1`\n    //\n    quad::DESinhTanhRule<T> rule2(n_quad2, tiny2);\n\n    // std::cout << \"*** quadrature rule\\n\";\n    // Real xsum = Real();\n    // for (Index k = 0; k < n_quad2; ++k)\n    // {\n    //     xsum += rule2.adjacentDifference(k);\n    //     std::cout << rule2.x(k) << '\\t' << rule2.adjacentDifference(k) <<\n    //     '\\t'\n    //               << xsum << '\\t' << std::abs(rule2.x(k) - xsum) << '\\n';\n    // }\n\n    for (Index k = 0; k < n_quad2; ++k)\n    {\n        const auto xk = half * rule2.distanceFromLower(k); // node\n        const auto uk = half * rule2.distanceFromUpper(k); // 1 - x\n        const auto wk = half * rule2.w(k);                 // weight\n\n        const auto ak = Complex(R, -xk);\n        const auto pk = wk * exp(ak * R_shift) *\n                        cos(Real(n) * acos(Complex(xk, R))) /\n                        sqrt(Complex(one + xk, R) * Complex(uk, -R));\n\n        es_merged.exponent(k) = ak;\n        es_merged.weight(k)   = pk;\n    }\n\n    //\n    // Discretization of integral I_1 on the path `1 + i y`  for\n    // `0 <= y <= R`\n    //\n    quad::DESinhTanhRule<T> rule1(n_quad1, tiny1);\n\n    const auto R_half = R / 2;\n    Index ipos        = n_quad2;\n    for (Index k = n_quad1; k > 0; --k)\n    {\n        const auto yk = R_half * rule1.distanceFromLower(k - 1); // node\n        const auto wk = R_half * rule1.w(k - 1);                 // weight\n        const auto ak = Complex(yk, -one);\n        const auto pk = Complex(zero, -wk) * exp(ak * R_shift) *\n                        cos(Real(n) * acos(Complex(one, yk))) /\n                        (sqrt(yk * Complex(yk, Real(-2))));\n\n        es_merged.exponent(ipos) = ak;\n        es_merged.weight(ipos)   = pk;\n        ++ipos;\n    }\n\n    // Remove terms with same exponents\n    es_merged.uniqueExponents(Real());\n\n    //\n    // Truncation for I_1 and I_2 separately\n    //\n    // mxpfit::BalancedTruncation<Complex> trunc1;\n    // es1 = trunc1.compute(es1, threshold * eps);\n\n    // mxpfit::BalancedTruncation<Complex> trunc2;\n    // es2 = trunc2.compute(es2, threshold);\n\n    //\n    // Truncation for I_1 and I_2 simultaneously\n    //\n    mxpfit::BalancedTruncation<Complex> trunc1;\n    es_merged = trunc1.compute(es_merged, threshold * eps * eps);\n\n    // mxpfit::AAKReduction<Complex> reduction;\n    // reduction.setThreshold(threshold);\n    // reduction.compute(es_merged);\n\n    ExponentialSumType es_result(2 * es_merged.size());\n    const auto pre1 = pow_i[n % 4] / pi<Real>(); // (-i)^n / pi\n    const auto pre2 = (n & 1) ? -pre1 : pre1;\n\n    for (Index i = 0; i < es_merged.size(); ++i)\n    {\n        const auto ai                 = es_merged.exponent(i);\n        es_result.exponent(2 * i + 0) = ai;\n        es_result.exponent(2 * i + 1) = conj(ai);\n\n        const auto wi               = es_merged.weight(i) * exp(-ai * R_shift);\n        es_result.weight(2 * i + 0) = pre1 * wi;\n        es_result.weight(2 * i + 1) = pre2 * conj(wi);\n    }\n\n    return es_result;\n}\n\n// template <typename T>\n// typename BesselKernel<T>::ExponentialSumType\n// BesselKernel<T>::compute(Index n, Real threshold)\n// {\n//     using Eigen::numext::conj;\n//     using Eigen::numext::exp;\n//     using Eigen::numext::log;\n//     using Eigen::numext::cos;\n//     using Eigen::numext::acos;\n//     using Eigen::numext::sin;\n//     using Eigen::numext::sqrt;\n//     // ----- Constants\n//     constexpr const auto zero = Real();\n//     constexpr const auto one  = Real(1);\n//     constexpr const auto half = Real(0.5);\n//     constexpr const auto eps  = std::numeric_limits<Real>::epsilon();\n//     // (-i)^n\n//     constexpr const Complex pow_i[4] = {Complex(one, zero), Complex(zero,\n//     -one),\n//                                         Complex(-one, zero),\n//                                         Complex(zero, one)};\n\n//     //----- adjustable parameters\n//     const auto R       = Real(3) / std::max(Index(1), n);\n//     const auto n_quad1 = Index(500);\n//     // const auto tiny1   = eps * eps;\n//     const auto tiny1 = eps * sqrt(eps) / n_quad1;\n\n//     const auto n_quad2 = Index(150 + 2 * n);\n//     const auto tiny2   = eps / n_quad2;\n//     //---------------------------\n\n//     //\n//     // Find R_shift such that j_n(R_shift) < eps\n//     //\n//     Real R_shift = Real();\n//     if (n > Index())\n//     {\n//         Real log_dfact = Real(); // log[2^n * n!]\n//         for (Index k = 1; k <= n; ++k)\n//         {\n//             log_dfact += log(Real(2 * k));\n//         }\n//         const auto thresh = std::min(threshold, sqrt(eps));\n//         R_shift           = exp((log_dfact + log(thresh)) / Real(n));\n//         if (R_shift < Real(0.1))\n//         {\n//             R_shift = Real();\n//         }\n//     }\n\n//     //\n//     // Discretization of integral I_1 on the path `-1 + i y`  for\n//     // `0 <= y <= R`\n//     //\n//     quad::DESinhTanhRule<T> rule1(n_quad1, tiny1);\n//     ExponentialSumType es1(n_quad1);\n\n//     const auto R_half = R / 2;\n//     for (Index k = 0; k < n_quad1; ++k)\n//     {\n//         const auto yk = R_half * rule1.distanceFromLower(k); // node\n//         const auto wk = R_half * rule1.w(k);                 // weight\n//         const auto ak = Complex(yk, one);\n//         const auto pk = Complex(zero, wk) * exp(ak * R_shift) *\n//                         cos(Real(n) * acos(Complex(-one, yk))) /\n//                         (sqrt(yk * Complex(yk, Real(2))));\n\n//         es1.exponent(k) = ak;\n//         es1.weight(k)   = pk;\n//     }\n\n//     //\n//     // Discretization of integral I_2 on the path `z = x + iR` for `-1<=x<=0`\n//     //\n//     quad::DESinhTanhRule<T> rule2(n_quad2, tiny2);\n//     ExponentialSumType es2(n_quad2);\n\n//     for (Index k = 0; k < n_quad2; ++k)\n//     {\n//         const auto xk = -half * rule2.distanceFromUpper(k); // node\n//         const auto lk = half * rule2.distanceFromLower(k);  // x + 1\n//         const auto wk = half * rule2.w(k);                  // weight\n\n//         const auto ak = Complex(R, -xk);\n//         const auto pk = wk * exp(ak * R_shift) *\n//                         cos(Real(n) * acos(Complex(xk, R))) /\n//                         sqrt(Complex(lk, R) * Complex(one - xk, -R));\n\n//         es2.exponent(k) = ak;\n//         es2.weight(k)   = pk;\n//     }\n//     //\n//     // Truncation for I_1 and I_2 separately\n//     //\n//     // mxpfit::BalancedTruncation<Complex> trunc1;\n//     // es1 = trunc1.compute(es1, threshold * eps);\n\n//     // mxpfit::BalancedTruncation<Complex> trunc2;\n//     // es2 = trunc2.compute(es2, threshold);\n\n//     //\n//     // Merge two sums\n//     //\n//     ExponentialSumType es_merged(es1.size() + es2.size());\n//     es_merged.exponents().head(es1.size()) = es1.exponents();\n//     es_merged.exponents().tail(es2.size()) = es2.exponents();\n//     es_merged.weights().head(es1.size())   = es1.weights();\n//     es_merged.weights().tail(es2.size())   = es2.weights();\n\n//     //\n//     // Truncation for I_1 and I_2 simultaneously\n//     //\n//     // mxpfit::BalancedTruncation<Complex> trunc1;\n//     // es_merged = trunc1.compute(es_merged, threshold * eps * eps);\n\n//     ExponentialSumType es_result(2 * es_merged.size());\n//     const auto pre1 = pow_i[n % 4] / pi<Real>(); // (-i)^n / pi\n//     const auto pre2 = (n & 1) ? -pre1 : pre1;\n\n//     for (Index i = 0; i < es_merged.size(); ++i)\n//     {\n//         const auto ai                 = es_merged.exponent(i);\n//         es_result.exponent(2 * i + 0) = ai;\n//         es_result.exponent(2 * i + 1) = conj(ai);\n\n//         const auto wi               = es_merged.weight(i) * exp(-ai *\n//         R_shift); es_result.weight(2 * i + 0) = pre1 * wi; es_result.weight(2\n//         * i + 1) = pre2 * conj(wi);\n//     }\n\n//     return es_result;\n// }\n\n//==============================================================================\n// Main\n//==============================================================================\n\nusing Index              = Eigen::Index;\nusing Real               = double;\nusing Complex            = std::complex<Real>;\nusing RealArray          = Eigen::Array<Real, Eigen::Dynamic, 1>;\nusing ComplexArray       = Eigen::Array<Complex, Eigen::Dynamic, 1>;\nusing ExponentialSumType = BesselKernel<Real>::ExponentialSumType;\n\nvoid bessel_j_kernel_error(int l, const RealArray& x,\n                           const ExponentialSumType& ret)\n{\n    RealArray exact(x.size());\n    RealArray approx(x.size());\n\n    for (Index i = 0; i < x.size(); ++i)\n    {\n        exact(i)  = boost::math::cyl_bessel_j(l, x(i));\n        approx(i) = std::real(ret(x(i)));\n    }\n\n    RealArray abserr(Eigen::abs(exact - approx));\n\n    for (Index i = 0; i < x.size(); ++i)\n    {\n        std::cout << std::setw(24) << x(i) << ' '      // point\n                  << std::setw(24) << exact(i) << ' '  // exact value\n                  << std::setw(24) << approx(i) << ' ' // approximation\n                  << std::setw(24) << abserr(i) << '\\n';\n    }\n\n    Index imax;\n    abserr.maxCoeff(&imax);\n\n    std::cout << \"\\n  abs. error in interval [\" << x(0) << \",\"\n              << x(x.size() - 1) << \"]\\n\"\n              << \"    maximum : \" << abserr(imax) << '\\n'\n              << \"    averaged: \" << abserr.sum() / x.size() << std::endl;\n}\n\nint main()\n{\n    std::cout.precision(15);\n    std::cout.setf(std::ios::scientific);\n\n    const Real threshold = 1.0e-14;\n    const Real eps       = Eigen::NumTraits<Real>::epsilon();\n    const Index lmax     = 4;\n    const Index N        = 2000; // # of sampling points\n\n    std::cout\n        << \"# Approximation of spherical Bessel function by exponential sum\\n\";\n\n    RealArray x = Eigen::exp(RealArray::LinSpaced(N, -20.0, 20.0));\n    ExponentialSumType ret;\n    for (Index l = 0; l <= lmax; ++l)\n    {\n        std::cout << \"\\n# --- order \" << l;\n        ret                      = BesselKernel<Real>::compute(l, threshold);\n        const auto thresh_weight = std::max(eps, threshold) / Real(ret.size());\n        ret                      = mxpfit::removeIf(\n            ret, [=](const Complex& /*exponent*/, const Complex& wi) {\n                return std::abs(std::real(wi)) < thresh_weight &&\n                       std::abs(std::imag(wi)) < thresh_weight;\n            });\n        std::cout << \" (\" << ret.size() << \" terms approximation)\\n\"\n                  << ret << '\\n';\n\n        // std::cout << \" (\" << ret.size() << \" terms approximation)\\n\";\n        // std::cout\n        //     << \"# real(exponent), imag(exponent), real(weight),\n        //     imag(weight)\\n\";\n        // for (Index i = 0; i < ret.size(); ++i)\n        // {\n        //     std::cout << std::setw(24) << std::real(ret.exponent(i)) << '\\t'\n        //               << std::setw(24) << std::imag(ret.exponent(i)) << '\\t'\n        //               << std::setw(24) << std::real(ret.weight(i)) << '\\t'\n        //               << std::setw(24) << std::imag(ret.weight(i)) << '\\n';\n        // }\n        // std::cout << '\\n' << std::endl;\n\n        std::cout << \"\\n# errors in small x\\n\";\n        bessel_j_kernel_error(l, x, ret);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "a77a2b5189a9ce2adddc2d704eb2f80d58b3c90b", "size": 16067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/bessel_j_kernel.cpp", "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": "examples/bessel_j_kernel.cpp", "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": "examples/bessel_j_kernel.cpp", "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": 34.852494577, "max_line_length": 112, "alphanum_fraction": 0.5357565196, "num_tokens": 4543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.6261241772283033, "lm_q1q2_score": 0.5428720452800261}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2020 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n\n\t Author: \t\t\t\t\t\t\tJaume Coll-Font, Yesim Serinagaoglu & Alireza Ghodrati\n\t Last Modification:\t\tSeptember 6 2017\n*/\n\n\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/DenseColumnMatrix.h>\n#include <Core/Datatypes/SparseRowMatrix.h>\n#include <Core/Logging/LoggerInterface.h>\n\n// Tikhonov inverse libraries\n#include <Core/Algorithms/Legacy/Inverse/TikhonovAlgoAbstractBase.h>\n#include <Core/Algorithms/Legacy/Inverse/SolveInverseProblemWithTSVD_impl.h>\n\n// EIGEN LIBRARY\n#include <Eigen/Eigen>\n#include <Eigen/SVD>\n\n\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Datatypes;\n// using namespace SCIRun::Modules::Inverse;\n// using namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Core::Logging;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::Inverse;\n\n\n\n///////////////////////////////////////////////////////////////////\n/////// prealocate Matrices for inverse compuation\n///     This function precalcualtes the SVD of the forward matrix and prepares singular vectors and values for posterior computations\n///////////////////////////////////////////////////////////////////\nvoid SolveInverseProblemWithTSVD_impl::preAlocateInverseMatrices(const SCIRun::Core::Datatypes::DenseMatrix& forwardMatrix_, const SCIRun::Core::Datatypes::DenseMatrix& measuredData_ , const SCIRun::Core::Datatypes::DenseMatrix& sourceWeighting_, const SCIRun::Core::Datatypes::DenseMatrix& sensorWeighting_, const SCIRun::Core::Datatypes::DenseMatrix& matrixU_, const SCIRun::Core::Datatypes::DenseMatrix& singularValues_, const SCIRun::Core::Datatypes::DenseMatrix& matrixV_)\n{\n\n\t\t// alocate U and V matrices\n\t\t\tsvd_MatrixU = matrixU_;\n\t\t\tsvd_MatrixV = matrixV_;\n\n\t\t// alocate singular values\n\t\t\tif (singularValues_.ncols() == 1 ){\n\t\t\t\tsvd_SingularValues = singularValues_;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tsvd_SingularValues = singularValues_.diagonal();\n\t\t\t}\n\n\t\t// Compute the projection of data y on the left singular vectors\n\t\t\tUy = svd_MatrixU.transpose() * (measuredData_);\n\n\t\t// determine rank\n\t        rank = svd_SingularValues.nrows();\n\n}\n\nvoid SolveInverseProblemWithTSVD_impl::preAlocateInverseMatrices(const SCIRun::Core::Datatypes::DenseMatrix& forwardMatrix_, const SCIRun::Core::Datatypes::DenseMatrix& measuredData_ , const SCIRun::Core::Datatypes::DenseMatrix& sourceWeighting_, const SCIRun::Core::Datatypes::DenseMatrix& sensorWeighting_)\n{\n\n\t    // Compute the SVD of the forward matrix\n\t        Eigen::JacobiSVD<SCIRun::Core::Datatypes::DenseMatrix::EigenBase> SVDdecomposition( forwardMatrix_, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n\t\t// alocate the left and right singular vectors and the singular values\n\t\t\tsvd_MatrixU = SVDdecomposition.matrixU();\n\t\t\tsvd_MatrixV = SVDdecomposition.matrixV();\n\t\t\tsvd_SingularValues = SVDdecomposition.singularValues();\n\n\t    // determine rank\n\t        rank = SVDdecomposition.nonzeroSingularValues();\n\n\t    // Compute the projection of data y on the left singular vectors\n\t        Uy = svd_MatrixU.transpose() * (measuredData_);\n}\n\n//////////////////////////////////////////////////////////////////////\n// THIS FUNCTION returns regularized solution by tikhonov method\n//////////////////////////////////////////////////////////////////////\nSCIRun::Core::Datatypes::DenseMatrix SolveInverseProblemWithTSVD_impl::computeInverseSolution( double lambda, bool inverseCalculation ) const\n{\n\n    // prealocate matrices\n        const int N = svd_MatrixV.cols();\n        const int M = svd_MatrixU.rows();\n        const int numTimeSamples = Uy.ncols();\n        DenseMatrix solution(DenseMatrix::Zero(N,numTimeSamples));\n        DenseMatrix tempInverse(DenseMatrix::Zero(N,M));\n\n\t\tconst int truncationPoint = Min( int(lambda), rank, int(9999999999999) );\n\n    // Compute inverse SolveInverseProblemWithTSVD\n        for (int rr=0; rr < truncationPoint ; rr++)\n        {\n            // evaluate filter factor\n                double singVal = svd_SingularValues[rr];\n                auto filterFactor_i =  1 / ( singVal );\n\n            // update solution\n                solution += filterFactor_i * svd_MatrixV.col(rr) * Uy.row(rr);\n\n            // update inverse operator\n                if (inverseCalculation)\n                    tempInverse += filterFactor_i * ( svd_MatrixV.col(rr) *  svd_MatrixU.col(rr).transpose() );\n        }\n\n    // output solutions\n    //   if (inverseCalculation)\n    //       inverseMatrix_.reset( new SCIRun::Core::Datatypes::DenseMatrix(tempInverse) );\n\n        return solution;\n}\n\n//////////////////////////////////////////////////////////////////////\n// THIS FUNCTION returns a string of lambdas from which the L-curve is computed\n//////////////////////////////////////////////////////////////////////\nstd::vector<double> SolveInverseProblemWithTSVD_impl::computeLambdaArray( double lambdaMin, double lambdaMax, int nLambda ) const\n{\n\tstd::vector<double> lambdaArray(nLambda,0.0);\n\tconst double lam_step = 1;\n\n\tlambdaArray[0] = lambdaMin;\n\tfor (int j = 1; j < nLambda; j++)\n\t{\n\t\tlambdaArray[j] = lambdaArray[j-1]  + lam_step;\n\t}\n\treturn lambdaArray;\n}\n", "meta": {"hexsha": "1217362f2e831b38c511511400e38e42b64e4696", "size": 6314, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Legacy/Inverse/SolveInverseProblemWithTSVD_impl.cc", "max_stars_repo_name": "mckees/SCIRun", "max_stars_repo_head_hexsha": "40c2c5b17925181bd2581ab8e11b325d58618165", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Core/Algorithms/Legacy/Inverse/SolveInverseProblemWithTSVD_impl.cc", "max_issues_repo_name": "mckees/SCIRun", "max_issues_repo_head_hexsha": "40c2c5b17925181bd2581ab8e11b325d58618165", "max_issues_repo_licenses": ["MIT"], "max_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/Legacy/Inverse/SolveInverseProblemWithTSVD_impl.cc", "max_forks_repo_name": "mckees/SCIRun", "max_forks_repo_head_hexsha": "40c2c5b17925181bd2581ab8e11b325d58618165", "max_forks_repo_licenses": ["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.2679738562, "max_line_length": 477, "alphanum_fraction": 0.6851441242, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5428676729699797}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n/// \\file\n/// Declares function find_root_of_function\n\n#pragma once\n\n#include <functional>\n#include <limits>\n\n#include <boost/math/tools/toms748_solve.hpp>\n\n/*! \\ingroup Functors\n *  \\brief Finds the root of the function f with the TOMS_748 method.\n *\n *  \\requires Function f be callable\n */\ntemplate <typename Function>\ndouble find_root_of_function(Function f, const double lower_bound,\n                             const double upper_bound,\n                             const double absolute_tolerance,\n                             const double relative_tolerance,\n                             const size_t max_iterations = 100) {\n  boost::uintmax_t max_iter = max_iterations;\n\n  // This solver requires tol to be passed as a termination condition. This\n  // termination condition is equivalent to the convergence criteria used by the\n  // GSL\n  auto tol = [absolute_tolerance, relative_tolerance](double lhs, double rhs) {\n    return (fabs(lhs - rhs) <=\n            absolute_tolerance +\n                relative_tolerance * fmin(fabs(lhs), fabs(rhs)));\n  };\n  // Lower and upper bound are shifted by absolute tolerance so that the root\n  // find does not fail if upper or lower bound are equal to the root within\n  // tolerance\n  auto result = boost::math::tools::toms748_solve(\n      f, lower_bound - absolute_tolerance, upper_bound + absolute_tolerance,\n      tol, max_iter);\n  return result.first + 0.5 * (result.second - result.first);\n}\n", "meta": {"hexsha": "5d72959b82f3512f3036468d26d20a78356e82a3", "size": 1517, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Numerical/RootFinding/RootFinder.hpp", "max_stars_repo_name": "wthrowe/spectre", "max_stars_repo_head_hexsha": "0ddd6405eef1e57de1d0a765aa4f6cfbc83c9f15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numerical/RootFinding/RootFinder.hpp", "max_issues_repo_name": "wthrowe/spectre", "max_issues_repo_head_hexsha": "0ddd6405eef1e57de1d0a765aa4f6cfbc83c9f15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numerical/RootFinding/RootFinder.hpp", "max_forks_repo_name": "wthrowe/spectre", "max_forks_repo_head_hexsha": "0ddd6405eef1e57de1d0a765aa4f6cfbc83c9f15", "max_forks_repo_licenses": ["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.2790697674, "max_line_length": 80, "alphanum_fraction": 0.6736980883, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5428676729217201}}
{"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_ASIND_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASIND_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing asind capabilities\n\n    inverse sine in degree.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = asind(x);\n    @endcode\n\n    Returns the arc @c r in the interval\n    \\f$[-90, 90[\\f$ such that <tt>sin(r) == x</tt>.\n    If @c x is outside \\f$[-1, 1[\\f$ the result is Nan.\n\n  **/\n  Value asind(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/asind.hpp>\n#include <boost/simd/function/simd/asind.hpp>\n\n#endif\n", "meta": {"hexsha": "88e36485908453547bf206758f6f8c44f541356b", "size": 1082, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/asind.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/asind.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/asind.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": 23.5217391304, "max_line_length": 100, "alphanum_fraction": 0.5665434381, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.542867661851518}}
{"text": "#ifndef GAUSSIAN_PROCESS_CLASSIFICATION_HPP\n#define GAISSIAN_PROCESS_CLASSIFICATION_HPP\n\n#include \"gplib/kernel.hpp\"\n#include <Eigen/Cholesky>\n#include <vector>\n\nnamespace librav{\n    const int64_t kDimension = 2;\n\n    class GaussianProcessClassification{\n        public:\n            ~GaussianProcessClassification() {};\n            // The keyword explicit avoid the implicit type conversion constructor\n            explicit GaussianProcessClassification(const Kernel::Ptr& kernel, double noise, const std::shared_ptr<std::vector<Eigen::VectorXd>> points, const Eigen::VectorXd& targets, size_t max_points = 100);\n\n            // Evaluate mean and variance at a point\n            void Evaluate(const Eigen::VectorXd& x, double& mean, double& variance) const;\n            void EvaluateTrainingPoint(size_t ii, double& mean, double& variance) const;\n\n            // Add new point(s). Return whether or not points were added (points will\n            // only be added until 'max_points' is reached).\n            bool Add(const Eigen::VectorXd& x, double target);\n            bool Add(const std::vector<Eigen::VectorXd>& points, const Eigen::VectorXd& targets);\n\n            // Update the training targets in the direction of the gradient of the\n            // mean squared error at the given points. Returns the mean squared error.\n            // If 'finalize' is set, computes regressed targets - only set to false if\n            // you are doing repeated updates, and be sure to set true on final update.\n            double UpdateTargets(const std::vector<Eigen::VectorXd>& points,\n                                 const std::vector<double>& targets,\n                                 double step_size, bool finalize = true);\n\n            std::pair<bool,double> Predict(const Eigen::VectorXd& x, Eigen::VectorXd* pi_, Eigen::VectorXd *W_sr_, Eigen::MatrixXd *LLT_);\n            \n            // Immutable accessors\n            const Eigen::MatrixXd& ImmutableCovariance() const { return covariance_; };\n            const Eigen::MatrixXd& ImmutableCovarianceGradient() const {return covariance_gradient_;};\n            const Eigen::VectorXd& ImmutableRegressedTargets() const { return regressed_; };\n            const Eigen::VectorXd& ImmutableTargerts() const { return targets_; };\n            const std::shared_ptr<const std::vector<Eigen::VectorXd>> ImmutablePoints() const { return points_; };\n            const Eigen::LLT<Eigen::MatrixXd>& ImmutableCholesky() const { return llt_; };\n            size_t Dimension() const { return dimension_; };\n\n        private:\n            // Compute the covariance and cross covariance against the trainning points.\n            void Covariance();\n            void CrossCovariance(const Eigen::VectorXd& x, Eigen::VectorXd& cross) const;\n            void CovarianceGradient();\n            Eigen::MatrixXd Covariance(const Eigen::VectorXd& target);\n\n            // Kernel.\n            const Kernel::Ptr kernel_;\n\n            // Noise variance\n            double noise_;\n\n            // Trainning points, targets, and regressed targets (inv(cov) * targets).\n            const std::shared_ptr<std::vector<Eigen::VectorXd>> points_;\n            const std::shared_ptr<std::vector<int>> targets_y_;\n            size_t dimension_;\n            Eigen::VectorXd targets_;\n            Eigen::VectorXd regressed_;\n\n            // Maximum number of points.\n            const size_t max_points_;\n\n            // Covariance matrix, with Cholesky decomposition.\n            Eigen::MatrixXd covariance_;\n            Eigen::MatrixXd covariance_gradient_;\n            Eigen::LLT<Eigen::MatrixXd> llt_;\n    };\n}\n\n#endif /* GAUSSIAN_PROCESS_CLASSIFICATION_HPP */", "meta": {"hexsha": "f7bf358d2e7b0711bd90207433707c9e05f44af3", "size": 3676, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gplib/include/gplib/gaussian_process_classification.hpp", "max_stars_repo_name": "jfangwpi/Interactive_planning_and_sensing", "max_stars_repo_head_hexsha": "00042c51c2fdc020b7b1c184286cf2b513ed9096", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gplib/include/gplib/gaussian_process_classification.hpp", "max_issues_repo_name": "jfangwpi/Interactive_planning_and_sensing", "max_issues_repo_head_hexsha": "00042c51c2fdc020b7b1c184286cf2b513ed9096", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gplib/include/gplib/gaussian_process_classification.hpp", "max_forks_repo_name": "jfangwpi/Interactive_planning_and_sensing", "max_forks_repo_head_hexsha": "00042c51c2fdc020b7b1c184286cf2b513ed9096", "max_forks_repo_licenses": ["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.0133333333, "max_line_length": 209, "alphanum_fraction": 0.6398258977, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5428425573176097}}
{"text": "// Copyright (c) 2021 by Ignacio Alzugaray <alzugaray dot ign at gmail dot com>\n// ETH Zurich, Vision for Robotics Lab.\n#pragma once\n\n\n#include <Eigen/Eigen>\n\nnamespace haste {\n\ntemplate<typename Scalar_>\nstruct PinholeRadTanCamera {\n public:\n  using Scalar = Scalar_;\n  using Vector2 = Eigen::Matrix<Scalar, 2, 1>;\n  using Matrix22 = Eigen::Matrix<Scalar, 2, 2>;\n\n  inline auto distortPointNormalized(Vector2 &p, Matrix22 *jacobian) const -> void;\n  inline auto undistortPointNormalized(const Vector2 &p_distorted) const -> Vector2;\n  inline auto undistortPoint(const Vector2 &p_distorted) const -> Vector2;\n\n  struct UndistortionMap {\n   public:\n    UndistortionMap(const PinholeRadTanCamera &camera);\n    inline auto operator()(const int &x, const int &y) const -> std::pair<Scalar, Scalar>;\n   private:\n    Eigen::Array<Vector2, -1, -1> data_;\n  };\n\n  inline auto createUndistortionMap() const -> UndistortionMap;\n\n  size_t width, height;     ///< Sensor size.\n  Scalar fx, fy, cx, cy;    ///< Intrinsics.\n  Scalar k1, k2, p1, p2, k3;/// << Rad-tan distortion.\n\n protected:\n  static constexpr auto kNumItersUndistortion_ = 50;  ///< Max number of iterations until convergence.\n  static constexpr auto kMaxErrorUndistortion_ = 1e-3;///< Max error in iterative distortion-undistortion.\n\n};\n\n}// namespace haste\n\n\n#include \"camera_impl.hpp\"", "meta": {"hexsha": "8065d58c32fa380683e75f98db0369f555a3c894", "size": 1341, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/x/haste/types/camera.hpp", "max_stars_repo_name": "jpl-x/x_events", "max_stars_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-09-23T07:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T08:36:32.000Z", "max_issues_repo_path": "include/x/haste/types/camera.hpp", "max_issues_repo_name": "jpl-x/x_events", "max_issues_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-07T08:47:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T10:44:31.000Z", "max_forks_repo_path": "include/x/haste/types/camera.hpp", "max_forks_repo_name": "jpl-x/x_events", "max_forks_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-06T06:26:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T06:26:11.000Z", "avg_line_length": 30.4772727273, "max_line_length": 106, "alphanum_fraction": 0.7188665175, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5428425523988331}}
{"text": "//Copyright (c) 2018, Changjie\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//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 __BFGS_HPP__\n#define __BFGS_HPP__\n\n#include <functional>\n#include <memory>\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/QR>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\n// ref: http://en.cppreference.com/w/cpp/utility/functional/function\n\n// input is the position(parameter)\n// Add const to avoid error of invalid initialization of non-const reference\ntypedef std::function<double(VectorXd const &)> Cost_Fun;\n// param1: returned gradient\n// param2: input position\ntypedef std::function<void(VectorXd &, VectorXd &)> Diff_Fun;\n// param1: returned hessian matrix\n// param2: input position\ntypedef std::function<void(MatrixXd &, VectorXd &)> Hess_Fun;\n\n\nstruct NonConstraintObj\n{\n\tVectorXd m_x;\n\tsize_t m_n;\n\n\tNonConstraintObj()\n\t{\n\t\tm_n = 1;\n\t\tm_x.resize(m_n);\n\t\tm_x.fill(0.);\n\t}\n\tvirtual ~NonConstraintObj() = default;\n\tvirtual double cost(VectorXd const &x) = 0;\n\tvirtual void grad(VectorXd &grad, VectorXd &x) = 0;\n};\n\nstruct BFGS\n{\n\tsize_t MAX_STEP;\n\tsize_t stop_step;\n\tsize_t step;\n\tdouble rho;\n\tdouble sigma;\n\tdouble epsilon;\n\n\tbool improved;\n\tbool initialized;\n\n\tCost_Fun cost_fun;\n\tDiff_Fun grad_fun;\n\n\tstd::shared_ptr<NonConstraintObj> funPtr;\n\tBFGS()\n\t{\n\t\tMAX_STEP = 80;\n\t\tstop_step = 5;\n\t\tstep = 0;\n\t\trho = 0.55;\n\t\tsigma = 0.4;\n\t\tepsilon = 1e-5;\n\t\timproved = false;\n\t\tinitialized = false;\n\t\tfunPtr = nullptr;\n\t}\n\ttemplate <class T>\n\tvoid init(T &obj)\n\t{\n\t\t// store a call to a member function and object\n\t\tusing std::placeholders::_1;\n\t\tusing std::placeholders::_2;\n\t\tcost_fun = std::bind(&T::cost, obj, _1);\n\t\tgrad_fun = std::bind(&T::grad, obj, _1, _2);\n\t\tinitialized = true;\n\t}\n\tdouble solve_(Cost_Fun fun, Diff_Fun dfun, VectorXd &input);\n\tdouble solve_(Cost_Fun fun, Diff_Fun dfun, Hess_Fun hfun, VectorXd &input);\n\tdouble solve(VectorXd &input)\n\t{\n\t\tif (initialized)\n\t\t{\n\t\t\treturn solve_(cost_fun, grad_fun, input);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"BFGS is not initialized! Return zeros.\\n\");\n\t\t\treturn 1e9;\n\t\t}\n\t}\n};\n\nstruct BFGS_V2\n{\n\t//double *Bk;\n\n\tBFGS_V2()\n\t{\n\t\t//Bk = nullptr;\n\t\t//cudaMalloc((void **)&Bk, sizeof(double)*3);\n\t}\n\ttemplate <class T>\n\tstatic double bfgs(std::shared_ptr<T> ptr, VectorXd &x0)\n\t{\n\t\tsize_t maxk = 500, stop_step = 5;\n\t\tdouble rho = 0.55, sigma = 0.4, epsilon = 1e-5;\n\n\t\tsize_t k = 0, n = x0.size();\n\t\tMatrixXd Bk = MatrixXd::Identity(n, n);\n\n\t\tVectorXd gk, dk, sk, yk, x;\n\t\tsize_t m = 0, mk = 0, bad = 0;\n\t\tdouble fit = 0., tmp = 0.;\n\t\tdouble best = 1e10;\n\t\twhile (k < maxk && bad < stop_step)\n\t\t{\n\t\t\tfit = ptr->cost(x0);\n\t\t\tif (fit < best - epsilon)\n\t\t\t{\n\t\t\t\tbest = fit;\n\t\t\t\tbad = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbad++;\n\t\t\t}\n\t\t\tptr->grad(gk, x0);\n\t\t\t//std::cout<<\"gk = \"<<gk<<std::endl;\n\t\t\tif (gk.norm() < epsilon)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdk = Bk.householderQr().solve(-gk); // llt ?\n\t\t\tm = 0, mk = 0;\n\n\t\t\ttmp = gk.transpose() * dk;\n\t\t\twhile (m < 100)\n\t\t\t{\n\t\t\t\tif (ptr->cost(x0 + pow(rho, m) * dk) < (fit + sigma * pow(rho, m) * tmp))\n\t\t\t\t{\n\t\t\t\t\tmk = m;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tm++;\n\t\t\t}\n\t\t\tx = x0 + pow(rho, mk) * dk;\n\t\t\tsk = pow(rho, mk) * dk;\n\t\t\tptr->grad(yk, x);\n\t\t\tyk = yk - gk;\n\t\t\tif (yk.transpose() * sk > 0)\n\t\t\t{\n\t\t\t\tBk = Bk - (Bk * sk * sk.transpose() * Bk) / (sk.transpose() * Bk * sk) + (yk * yk.transpose()) / (yk.transpose() * sk);\n\t\t\t}\n\t\t\tx0 = x;\n\t\t\tk++;\n\t\t}\n\t\tx0 = x;\n\t\t#ifdef DEBUG\n\t\tstd::cout << \"BFGS stops at step \" << k << std::endl;\n\t\t#endif\n\t\treturn fit;\n\t}\n};\n\n#endif\n", "meta": {"hexsha": "a49a133091f593bc9347fc4341e10612a13835a3", "size": 4739, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/bfgs/bfgs.hpp", "max_stars_repo_name": "gcjyzdd/BFGS", "max_stars_repo_head_hexsha": "f546224d787faf8e37f49ab6a03ab919187b16e8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-13T08:10:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-03T11:00:45.000Z", "max_issues_repo_path": "src/bfgs/bfgs.hpp", "max_issues_repo_name": "gcjyzdd/BFGS", "max_issues_repo_head_hexsha": "f546224d787faf8e37f49ab6a03ab919187b16e8", "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/bfgs/bfgs.hpp", "max_forks_repo_name": "gcjyzdd/BFGS", "max_forks_repo_head_hexsha": "f546224d787faf8e37f49ab6a03ab919187b16e8", "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.0558375635, "max_line_length": 123, "alphanum_fraction": 0.6615319688, "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.542842545280297}}
{"text": "#ifndef RNN_TYPE_HPP\r\n#define RNN_TYPE_HPP\r\n\r\n#include <Eigen/Core>\r\n\r\nnamespace rnn::generic {\r\nusing real = double;\r\n\r\ntemplate<std::size_t row_dim_t_, std::size_t col_dim_t_>\r\nusing rnn_matrix = Eigen::Matrix<real, row_dim_t_, col_dim_t_>;\r\n\r\ntemplate<std::size_t dim_t_>\r\nusing rnn_square_matrix = rnn_matrix<dim_t_, dim_t_>;\r\n\r\ntemplate<std::size_t dim_t_>\r\nusing rnn_vector = Eigen::Vector<real, dim_t_>;\r\n\r\n#ifdef USE_FLOAT\r\ntypedef float real;\r\ntypedef Eigen::MatrixXf MatD;\r\ntypedef Eigen::VectorXf VecD;\r\n#else\r\ntypedef Eigen::MatrixXd MatD;\r\ntypedef Eigen::VectorXd VecD;\r\n#endif\r\n\r\ntypedef Eigen::MatrixXi MatI;\r\ntypedef Eigen::VectorXi VecI;\r\n#define REAL_MAX std::numeric_limits<real>::max()\r\n\r\n} // namespace rnn\r\n\r\n#endif", "meta": {"hexsha": "5e8037b68046c806b97b0b435478a14474d57b0b", "size": 737, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RNN/generic/rnn_type.hpp", "max_stars_repo_name": "suiyili/projects", "max_stars_repo_head_hexsha": "29b4ab0435c8994809113c444b3dea4fff60b75c", "max_stars_repo_licenses": ["MIT"], "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/generic/rnn_type.hpp", "max_issues_repo_name": "suiyili/projects", "max_issues_repo_head_hexsha": "29b4ab0435c8994809113c444b3dea4fff60b75c", "max_issues_repo_licenses": ["MIT"], "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/generic/rnn_type.hpp", "max_forks_repo_name": "suiyili/projects", "max_forks_repo_head_hexsha": "29b4ab0435c8994809113c444b3dea4fff60b75c", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 64, "alphanum_fraction": 0.7408412483, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5428425403615202}}
{"text": "#ifndef fast_gauss_noise_h\n#define fast_gauss_noise_h\n\n#include <cstdint>\n#include <cstddef>\n#include <list>\n#include <iostream>\n#include <cstdlib>\n#include <ctime>\n#include <cmath>\n#include <climits>\n#include <cstring>\n#include <tuple>\n#include <typeinfo>\n#include <gmp.h>\n#include <mpfr.h>\n#include \"fastrandombytes.h\"\n\n#ifdef BOOST_RAPHSON\n#include <boost/math/tools/roots.hpp>\n#endif\n\n\n//#define OUTPUT_BARRIERS\n//#define OUTPUT_LUT_FLAGS\n// Use it to test rare values do not happen too often\n//#define UNITTEST_ONEMILLION\n\nnamespace nfl {\n\ntemplate<typename T0, typename T1>\nconstexpr inline auto tstbit(T0 x, T1 n) -> decltype((x << (63 - n)) >> 63 ) { return ((x << (63 - n)) >> 63 ); }\n\ntemplate<class in_class, class out_class>\nstruct output {\n  out_class val;\n  bool flag;\n  std::list<in_class*> l_b_ptr;\n};\n\ntemplate<class in_class, class out_class, unsigned _lu_depth>\nclass FastGaussianNoise {\n    typedef output<in_class, out_class> output_t;\n  private:\n    unsigned int _bit_precision;\n    unsigned int _word_precision;\n    unsigned int _number_of_barriers;\n    unsigned int _lu_size;\n    unsigned int _flag_ctr1;\n    unsigned int _flag_ctr2;\n    double _sigma;\n    mpfr_t _const_sigma;\n    mpfr_t _center;\n    int rounded_center;\n    unsigned int _security;\n    unsigned int _samples;  \n    double _tail_bound;\n    bool _verbose;\n\n    in_class **barriers;\n    output_t *lu_table;\n    output_t **lu_table2;\n\n    void check_template_params();\n    void init();\n    void precomputeBarrierValues(); \n    void buildLookupTables();\n    void nn_gaussian_law(mpfr_t rop, const mpfr_t x_fr);\n    int cmp(in_class *op1, in_class *op2); \n\n  public:\n    static const unsigned int default_k;\n    FastGaussianNoise(double sigma, unsigned int security, unsigned int samples, double center_d = 0, bool verbose = false);\n    FastGaussianNoise(double sigma, unsigned int security, unsigned int samples, mpfr_t center, bool verbose = false);\n    ~FastGaussianNoise();\n    void getNoise(out_class * const rand_data2out, uint64_t rlen); \n};\n\n\n/* NOTATIONS (from paper Sampling from discrete Gaussians \n * for lattice-based cryptography on a constrainded device\n * Nagarjun C. Dwarakanath, Steven Galbraith\n * Journal : AAECC 2014 (25)\n *\n * m : lattice dimension, we set it to 1 in here (better results for same security) !!!!\n *\n * security : output distribution should be within 2^{-security} \n * statistical distance from the Gaussian distribution\n *\n * sigma : parameter of the Gaussian distribution (close \n * to the standard deviation but not equal)\n * SUM = \\sum_{k=-\\inf}^{\\inf} exp(-(k-c)^2/(2*sigma^2))\n *\n * D_{sigma} : distribution such that for x\\in \\mathcal{Z}\n * Pr(x) = ro_{sigma}(x) = 1/SUM exp(-(x-c)^2/(2*sigma^2))\n *\n * Warning : can be replaced in some works by s = sqrt(2*pi)*sigma\n * if Pr(x) = 1/SUM exp(-pi*(x-c)^2/s^2)\n *\n * tail_bound : tail bound we only output points with \n * norm(point-c) < tail_bound*sigma\n *\n * bit_precision : bit precision when computing the probabilities \n *\n * delta_tailbound : statistical distance introduced \n * by the tail bound\n *\n * delta_epsi : statistical distance introduced by \n * probability approximation\n */\n\n\n\n// HELPER FUNCTIONS\n\n/* /!\\ Warning only for x64 */\nextern __inline__ uint64_t rdtsc(void) \n{\n  uint64_t a, d;\n  __asm__ volatile (\"rdtsc\" : \"=a\" (a), \"=d\" (d));\n  return (d<<32) | a;\n}\n\n// Function to be used in a Newton-Raphson solver\nstruct funct\n{\n\tfunct(double const& target) : k(target){}\n\tstd::tuple<double, double> operator()(double const& x)\n\t{\n\t\treturn std::make_tuple(x*x - 2*log(x) - 1 - 2*k*log(2), 2*x-2/x); \n\t}\n\tprivate:\n\tdouble k;\n};\n\ninline\ndouble newton_raphson(double k, double max_guess, int digits)\n{\n  unsigned max_counter = 1U<<15;\n  std::tuple<double, double> values;\n  double delta;\n  double guess = max_guess;\n  for (unsigned counter = 0 ; counter < max_counter; counter++)\n  {\n    values = funct(k)(guess);\n    delta = std::get<0>(values)/std::get<1>(values);\n    guess -= delta;\n    if ( fabs(delta)/fabs(guess) < pow(10.0,-digits) ) break;\n  }\n  // In case there is a flat zone in the function\n  while(0.95*guess*0.95*guess - 2*log(0.95*guess) - 1 - 2*k*log(2)>=0) guess*=0.95;\n  // Test result\n  if(guess*guess - 2*log(guess) - 1 - 2*k*log(2)<0)\n  {\n    std::cout << \"FastGaussianNoise: WARNING Newton-Raphson failed the generator is NOT secure\" << std::endl;\n  }\n  return guess;\n}\n\n\n// Constructors\n\n\ntemplate<class in_class, class out_class, unsigned _lu_depth>\nFastGaussianNoise<in_class, out_class, _lu_depth>::FastGaussianNoise( double sigma, \n\t\tunsigned int security, unsigned int samples, double center_d /*=0*/, bool verbose /*=true*/):\n\t_sigma(sigma),\n\t_security(security),\n  _samples(samples),\n  _verbose(verbose)\n{\n  // Check template parameters\n  check_template_params();\n  \n  //Center cannot be initialized before the constructor\n  mpfr_init_set_d(_center, center_d, MPFR_RNDN);\n  rounded_center = round(center_d);\n\n  //Initialization functions\n\tinit(); \n\tprecomputeBarrierValues();\n\tbuildLookupTables();\n}\n\ntemplate<class in_class, class out_class, unsigned _lu_depth>\nFastGaussianNoise<in_class, out_class, _lu_depth>::FastGaussianNoise( double sigma, \n\t\tunsigned int security, unsigned int samples, mpfr_t center /*=0*/, bool verbose /*=true*/):\n\t_sigma(sigma),\n\t_security(security),\n  _samples(samples),\n  _verbose(verbose)\n{\n  // Check template parameters\n  check_template_params();\n\n  //Center cannot be initialized before the constructor\n  mpfr_init_set(_center, center, MPFR_RNDN);\n  rounded_center = mpfr_get_d(_center, MPFR_RNDN);\n\n  //Initialization functions\n\tinit(); \n\tprecomputeBarrierValues();\n\tbuildLookupTables();\n}\n\n\n// Check template parameters\ntemplate<class in_class, class out_class, unsigned _lu_depth>\nvoid FastGaussianNoise<in_class, out_class, _lu_depth>::check_template_params() \n{\n  // Lookup tables can only have depth 1 or 2\n  if (_lu_depth != 1 && _lu_depth != 2)\n  {\n    std::cout << \"FastGaussianNoise: CRITICAL _lu_depth must be 1 or 2\" << std::endl;\n    exit(1);\n  }\n\n  // Lookup tables can only have uint8_t or uint16_t indexes\n  if (typeid(in_class) == typeid(uint8_t))\n    _lu_size = 1<<8;\n  else if(typeid(in_class) == typeid(uint16_t))\n    _lu_size = 1<<16;\n  else\n  {\n    std::cout << \"FastGaussianNoise: CRITICAL in_class must be uint8_t or uint16_t\" << std::endl;\n    exit(2);\n  }\n}\n\n\n// Compute some values (precision, number of barriers and outputs)\ntemplate<class in_class, class out_class, unsigned _lu_depth>\nvoid FastGaussianNoise<in_class, out_class, _lu_depth>::init() \n{\n\tdouble epsi, k;\n\n\t/* Lemma 1: \n\t * tail_bound >= sqrt(1 + 2*log(tail_bound) + 2*k*log(2))  \n\t * IMPLIES delta_tailbound < 2**(-k)\n   *\n   * -epsi <= -k - log2(2 * tail_bound * sigma)) \n\t * IMPLIES 2 * tail_bound * sigma * 2**(-epsi) <= 2**(-k)\n\t * \n   * Lemma 2 (and Lemma 1): \n\t * 2 * tail_bound * sigma * 2**(-epsi) <= 2**(-k)\n\t * IMPLIES  delta_epsilon < 2**(-k)\n   */\n\n\t// THUS setting \n\tk = _security + 1 + ceil(log(_samples)/log(2));\n\t// IMPLIES (delta_tailbound + delta_epsilon)*_samples < 2**(-_security)\n\t// We can thus generate vectors of _samples samples securely\n\n  // To compute the tail bound we use Newton-Raphson with three digits of precision\n\t// WE HAVE tail_bound >= sqrt(1 + 2*log(tail_bound) + 2*k*log(2)) \n  // IS EQUIV TO tail_bound**2 -2*log(tail_bound) - 1- 2*k*log(2) >= 0\n\tint digits = 3;\n#ifdef BOOST_RAPHSON\n  double max_guess = 1+2*k*log(2);\n  double min_guess = sqrt(1 + 2*k*log(2)), guess = min_guess;\n\t_tail_bound = boost::math::tools::newton_raphson_iterate(funct(k),guess, min_guess, max_guess, digits);\n#else\n  double min_guess = sqrt(1 + 2*k*log(2));\n  _tail_bound = newton_raphson(k, min_guess, digits);\n#endif\n\t// We now can compute the precision needed \n\tepsi = k + log2(2 * _tail_bound * _sigma);\n\t_bit_precision = ceil(epsi);\n\t_word_precision = ceil(_bit_precision/(8.0*sizeof(in_class)));\n  // For the same cost we get a simpler situation and more precision\n\t_bit_precision = _word_precision*8*sizeof(in_class);\n  // And the number of probabilities that must be computed\n  // Only half of them are computed (others are symmetric)\n  // but all values are stored to speedup noise generation\n  _number_of_barriers = 1+2*ceil(_tail_bound*_sigma);\n  if ( ((uint64_t)_number_of_barriers >> (sizeof(out_class) * 8 - 1)) != 0)\n    std::cout << \"FastGaussianNoise: WARNING out_class too small to contain some of the (signed) results\" << std::endl;\n  if ( ((uint64_t)_number_of_barriers >> (sizeof(int) * 8 - 1)) != 0)\n    std::cout << \"FastGaussianNoise: WARNING outputs are above 2**31, unexpected results\" << std::endl;\n\n  // Finally we precompute 1/(2*sigma**2) to accelerate things\n\tmpfr_inits2(_bit_precision, _const_sigma, nullptr);\n  mpfr_set_d(_const_sigma, _sigma, MPFR_RNDN);\n\tmpfr_sqr(_const_sigma, _const_sigma, MPFR_RNDN);\n\tmpfr_mul_ui(_const_sigma, _const_sigma, 2, MPFR_RNDN); \n\tmpfr_ui_div(_const_sigma, 1, _const_sigma, MPFR_RNDN);\n\n  // Give some feedback\n  if (_verbose) std::cout << \"FastGaussianNoise: \" << _number_of_barriers << \n    \" barriers with \" << _bit_precision << \n    \" bits of precision will be computed\" << std::endl;\n}\n\n\ntemplate<class in_class, class out_class, unsigned _lu_depth>\nvoid FastGaussianNoise<in_class, out_class, _lu_depth>::precomputeBarrierValues() \n{\n  // Declare and init mpfr vars\n  mpfr_t sum, tmp, tmp2;\n  mpfr_t *mp_barriers;\n  mpfr_inits2(_bit_precision, sum, tmp, tmp2, nullptr);\n\n  // This var is used to export mpfr values\n  mpz_t int_value;\n  mpz_init2(int_value, _bit_precision);\n\n  // Init SUM = \\sum_{k=-ceil(tail_bound*sigma)}^{ceil(tail_bound*sigma)} exp(-(k+round(c)-c)^2/(2*sigma^2))\n  // and compute on the loop with the barriers\n  mpfr_set_ui(sum, 0, MPFR_RNDN);\n\n  // Allocate memory for the barrier pointers\n  barriers = (in_class **) malloc(_number_of_barriers*sizeof(in_class *)); \n  mp_barriers = (mpfr_t *) malloc(_number_of_barriers*sizeof(mpfr_t)); \n\n  // Now loop over the barriers\n  for (int i = 0; i < (int)_number_of_barriers; i++)\n  {\n    // Init mpfr var\n    mpfr_init2(mp_barriers[i], _bit_precision);\n\n    // Compute the barrier value (without normalization)\n    mpfr_set_si(tmp2, rounded_center+i-((int)_number_of_barriers-1)/2, MPFR_RNDN);\n    nn_gaussian_law(tmp, tmp2);\n    //mpfr_out_str(stdout, 10, 0, tmp2, MPFR_RNDN);\n    //std::cout << std::endl;\n    if (i==0) mpfr_set(mp_barriers[0], tmp, MPFR_RNDN);\n    else \n    {\n      mpfr_add(mp_barriers[i], mp_barriers[i-1], tmp, MPFR_RNDN);\n    }\n\n    // Add the probability to the sum\n    mpfr_add(sum, sum, tmp, MPFR_RNDN);\n  }\t\n  \n  // Invert the sum and scale it \n  mpfr_ui_div(sum, 1, sum, MPFR_RNDN);\n  mpfr_set_ui(tmp, 2, MPFR_RNDN);\n  mpfr_pow_ui(tmp, tmp, _bit_precision, MPFR_RNDN);\n  mpfr_sub_ui(tmp, tmp, 1, MPFR_RNDN);\n  mpfr_mul(sum, sum, tmp, MPFR_RNDN);\n\n  // Now that we got the inverted sum normalize and export\n  for (unsigned i = 0; i < _number_of_barriers; i++)\n  {\n    // Allocate space\n    barriers[i] = (in_class *) calloc(_word_precision,sizeof(in_class)); \n\t  \n    mpfr_mul(mp_barriers[i], mp_barriers[i], sum, MPFR_RNDN);  \n    mpfr_get_z(int_value, mp_barriers[i], MPFR_RNDN);\n    mpz_export((void *) (barriers[i] + ((int)_word_precision - \n           (int)ceil( (float)mpz_sizeinbase(int_value, 256)/sizeof(in_class) ))), nullptr, 1, sizeof(in_class), 0, 0, int_value);\n#ifdef OUTPUT_BARRIERS\n    mpz_out_str(stdout, 10, int_value);\n    std::cout << \" = Barriers[\" << i << \"] = \" << std::endl;\n    if (sizeof(in_class) == 1) for (unsigned j = 0 ; j < _word_precision; j++)\n      printf(\"%.2x\", barriers[i][j]);\n    if (sizeof(in_class) == 2) for (unsigned j = 0 ; j < _word_precision; j++)\n      printf(\"%.4x\", barriers[i][j]);\n    std::cout <<  std::endl;\n#endif \n    mpfr_clear(mp_barriers[i]);\n  }\n\tmpfr_clears(sum, tmp, tmp2, nullptr);\n  mpz_clear(int_value);\n\tmpfr_free_cache();\n  free(mp_barriers);\n}\n\n\n\n//Build lookup tables used during noise generation\ntemplate<class in_class, class out_class, unsigned _lu_depth>\nvoid FastGaussianNoise<in_class, out_class, _lu_depth>::buildLookupTables() \n{\n\tunsigned lu_index1 = 0, lu_index2 = 0;\n  _flag_ctr1 = _flag_ctr2 = 0;\n\n  // Allocate space for the lookup tables\n  lu_table = new output_t[_lu_size](); \n  if(_lu_depth == 2) \n    lu_table2 = (output_t **) calloc(_lu_size,sizeof(output_t *)); \n\n\t// We start building the first dimension of the lookup table\n  // corresponding to the first in_class word of the barriers\n\tfor (int64_t val = -((int)_number_of_barriers-1)/2 + rounded_center, b_index = 0; val <= ((int)_number_of_barriers-1)/2 + rounded_center && lu_index1 < _lu_size;) \n  {\n\n\t\twhile (lu_index1 < barriers[b_index][0] && lu_index1 < _lu_size) \n    {\n      lu_table[lu_index1].val = val;\n\t\t\tlu_index1++;\n\t\t}\n\n\t\t// Flag the entry\n\t\tlu_table[lu_index1].val = val;\n\t\tlu_table[lu_index1].flag = true;\n    _flag_ctr1++;\n\t\t// If _lu_depth == 1 we have to list the barriers here\n    if (_lu_depth == 1)\n    {\n#ifdef OUTPUT_LUT_FLAGS\n      std::cout << \"FastGaussianNoise: flagged lu_table[\" \n       << lu_index1 << \"] for barriers \" << val;\n#endif\n      \n      // Prepare the first element of the chained list of barrier\n\t\t\tlu_table[lu_index1].l_b_ptr.push_back(barriers[b_index++]);\n      val++;\n\t\t\t// If more that one barrier is present, we add them to the chained list \n\t\t\twhile ( (b_index<_number_of_barriers) && (lu_index1 == barriers[b_index][0])) \n      {\n\t\t\t  lu_table[lu_index1].l_b_ptr.push_back(barriers[b_index]);\n#ifdef OUTPUT_LUT_FLAGS\n      std::cout << \"FastGaussianNoise: flagged lu_table[\" << lu_index1 << \"] for barriers \" << val;\n#endif\n\t\t\t\tb_index++;\n\t\t\t\tval++;\n\t\t\t} // while\n    } // if\n\t\n    if (_lu_depth == 2)\n    {\n      // When we meet a barrier in an entry of the lu_table, \n      // we build another lu_table inside that entry\n\t\t  // corresponding to the next in_class word of the barriers \n\t\t  lu_index2 = 0;\n      lu_table2[lu_index1] = new output_t[_lu_size](); \n\t\t  while (lu_index2 < _lu_size) \n      {\n\t\t\t  if(lu_index1 < barriers[b_index][0] || lu_index2 < barriers[b_index][1])\n        {\n          lu_table2[lu_index1][lu_index2].val = val;\n        }\n        else\n        {\n\t\t      // If we are on a barrier\n\t\t      if (lu_index1 == barriers[b_index][0] && lu_index2 == barriers[b_index][1]) \n          {\n\t\t\t      // Flag the entry\n\t\t\t      lu_table2[lu_index1][lu_index2].val = val;\n\t\t\t      lu_table2[lu_index1][lu_index2].flag = true;\n#ifdef OUTPUT_LUT_FLAGS\n            std::cout << \"FastGaussianNoise: flagged lu_table2[\" << lu_index1 << \"][\" << lu_index2 << \"] for barriers \" << val;\n#endif\n            _flag_ctr2++;\n\t\t\t      // And prepare the first element of the chained list of barrier\n\t\t\t      lu_table2[lu_index1][lu_index2].l_b_ptr.push_back(barriers[b_index++]);\n            val++;\n\t\t\t      // If more that one barrier is present, we add them to the chained list \n\t\t\t      while ( (b_index<_number_of_barriers) && \n                (lu_index1 == barriers[b_index][0]) && \n                (lu_index2 == barriers[b_index][1]) ) \n            {\n\t\t\t\t      lu_table2[lu_index1][lu_index2].l_b_ptr.push_back(barriers[b_index]);\n#ifdef OUTPUT_LUT_FLAGS\n            std::cout << \" \" << val;\n#endif\n\t\t\t\t      b_index++;\n\t\t\t\t      val++;\n\t\t\t      } // while\n#ifdef OUTPUT_LUT_FLAGS\n            std::cout << std::endl;\n#endif\n          } // if\n        } // else\n        lu_index2++;\n      } // while\n\t\t} // if\n\n\t\tlu_index1++;\n\t}\n  // Give some feedback\n  if (_verbose) std::cout << \"FastGaussianNoise: Lookup tables built\" << std::endl;\n}\n\ntemplate<class in_class, class out_class, unsigned _lu_depth>\nvoid FastGaussianNoise<in_class, out_class, _lu_depth>::getNoise(out_class* const rand_outdata, uint64_t rlen) \n{\n\tuint64_t computed_outputs, innoise_bytesize, innoise_words, used_words;\n\tint64_t output;\n  bool flagged;\n\tin_class *noise, *noise_init_ptr, input1, input2;\n  float innoise_multiplier;\n \n  // Expected number of input bytes per output byte. Lowering this \n  // (e.g. by a factor .5) works but could lead to segfaults.\n  if (_lu_depth == 1)\n  {\n    innoise_multiplier = 1.05 * ((float)(_lu_size - _flag_ctr1)/(float)_lu_size) + _word_precision * ((float)_flag_ctr1/_lu_size);\n  } \n  else // _lu_depth == 2\n  {\n    innoise_multiplier = 1.05 * ((float)(_lu_size - _flag_ctr1)/(float)_lu_size) + 2.0 * ((float)_flag_ctr1/(float)_lu_size) + _word_precision * ((float)_flag_ctr2/((float)_lu_size*_lu_size));\n  }\n  innoise_words = rlen * innoise_multiplier;\n  innoise_bytesize = sizeof(in_class) * innoise_words;\n\tnoise = noise_init_ptr = new in_class[innoise_words];\n  used_words = 0;\n  if (_verbose) std::cout << \"FastGaussianNoise: Using \" << \" \" <<innoise_multiplier*sizeof(in_class)*8/std::min(log2(_number_of_barriers),(double)sizeof(out_class)*8) << \" input bits per output bit\" << std::endl;\n \n  // Count time for uniform noise generation \n\tuint64_t start = rdtsc();\n\tfastrandombytes((uint8_t*)noise, innoise_bytesize);\n\tuint64_t stop = rdtsc();\n\n  // Give some feedback\n\tif (_verbose) printf(\"FastGaussianNoise: Uniform noise  cycles = %.2e bits = %.2e cycles/bit = %.2e\\n\", (float) stop - start, (float) innoise_bytesize * 8, (float)(stop-start)/(innoise_bytesize*8));\n\n  // Loop until all the outputs have been generated\n  computed_outputs = 0;\n\twhile (computed_outputs < rlen ) \n  {\n\t\tinput1 = *noise;\n\t\tflagged = lu_table[input1].flag;\n\n    // If flagged we have to look at the next in_class word\n    if (flagged) \n    {\n\t\t  if (_lu_depth == 1)\n      {\n\t\t\t\toutput = lu_table[input1].val;\n\t\t\t\tfor(in_class* b_ptr : lu_table[input1].l_b_ptr) \n        {\n\t\t\t\t\t// If the barrier value is greater than the noise\n\t\t\t\t\tif(cmp(b_ptr, noise)==1) break;\n\t\t\t\t\toutput++;\n\t\t\t\t}\n        // We shift the noise pointer of word_precision minus 1\n        // As there another byte shift later\n\t\t\t\tnoise += _word_precision - 1;\n\t\t\t\tused_words += _word_precision - 1;\n\n      }\n      else // _lu_depth == 2\n      {\n\t\t\t  input2 = *(noise+1);\n\t\t\t  flagged = lu_table2[input1][input2].flag;\n        // If flagged again we compare using full precision the random value \n        // with all barriers in the linked list of the lookup table\n\t\t\t  if (flagged) \n        {\n\t\t\t    output = lu_table2[input1][input2].val;\n\t\t\t\t  for(in_class* b_ptr : lu_table2[input1][input2].l_b_ptr) \n          {\n\t\t\t\t\t  // If the barrier value is greater than the noise\n\t\t\t\t\t  if(cmp(b_ptr, noise)==1) break;\n\t\t\t\t\t  output++;\n\t\t\t\t  }\n          // We shift the noise pointer of word_precision minus 2\n          // As there are two other one byte shifts later\n\t\t\t\t  noise += _word_precision - 2;\n\t\t\t\t  used_words += _word_precision - 2;\n\t\t\t  } // if                                     \t\t\n        else\n        {\n\t\t\t    output = lu_table2[input1][input2].val;\n        }\n        noise++;\n        used_words++;\n      } // else\n    }\n    else\n    { \n\t\t  output = lu_table[input1].val;\n    }\n\t\tnoise++;\n    used_words++;\n\t\t// Add the obtained result to the list of outputs\n\t\trand_outdata[computed_outputs++] = (out_class) output; \n\n#ifdef UNITTEST_ONEMILLION\n    if ( (output > _sigma * 6) || (output < -_sigma*6) )\n    {\n      std::cout << output << \"FastGaussianNoise: Unit test failed, this should happen once in a million. Uniform input leading to this is  \";\n      for (unsigned i = 0; i < _word_precision ; i++)\n        printf(\"%.2x\", *(noise-_word_precision+i));\n      std::cout << std::endl;\n    }\n#endif\n\n#if 1\n    // If too much noise has been used regenerate it\n    if ((used_words+_word_precision) >= innoise_words)\n    {\n      noise = noise_init_ptr;\n      used_words = 0; \n      if (_verbose) std::cout << \"FastGaussianNoise: All the input bits have been used, regenerating them ...\" << std::endl;\n \n\t    fastrandombytes((uint8_t*)noise, innoise_bytesize);\n    }\n#endif\n\t}\n\tdelete[] noise_init_ptr;\n}\n\n/* Compare two arrays word by word.\n * return 1 if op1 > op2, 0 if equals and -1 if op1 < op2 */\ntemplate<class in_class, class out_class, unsigned _lu_depth>\ninline int FastGaussianNoise<in_class, out_class, _lu_depth>::cmp(in_class *op1, in_class *op2) \n{\n\n\tfor (int i = 0; i < (int)_word_precision; i++) \n  {\n\n\t\tif (op1[i] > op2[i]) return 1;\n\n\t\telse if (op1[i] < op2[i]) return -1;\n\t}\n\treturn 0;\n}\n\n\n// Compute exp(-(x-center)^2/(2*sigma^2)) this is not normalized ! (hence the nn)\ntemplate<class in_class, class out_class, unsigned _lu_depth>\nvoid  inline FastGaussianNoise<in_class, out_class, _lu_depth>::nn_gaussian_law(mpfr_t rop, const mpfr_t x) \n{\n\tmpfr_sub(rop, x, _center, MPFR_RNDN);\n\tmpfr_sqr(rop, rop, MPFR_RNDN);\n\tmpfr_neg(rop, rop, MPFR_RNDN);\n\tmpfr_mul(rop, rop, _const_sigma, MPFR_RNDN);\n\tmpfr_exp(rop, rop, MPFR_RNDN);\n}\n\n\ntemplate<class in_class, class out_class, unsigned _lu_depth>\nFastGaussianNoise<in_class, out_class, _lu_depth>::~FastGaussianNoise() \n{\n  // Freed allocated memory for the barriers\n  for (unsigned ctr = 0; ctr < _number_of_barriers; ctr++)\n  {\n    if (barriers[ctr] != nullptr) free(barriers[ctr]); \n    barriers[ctr] = nullptr;\n  }\n  if (barriers != nullptr) free(barriers);\n  barriers=nullptr;\n\n  // Free other variables\n  mpfr_clear(_const_sigma);\n  mpfr_clear(_center);\n  delete[](lu_table);\n  if(_lu_depth == 2) \n  {\n    for (unsigned ctr = 0 ; ctr < _lu_size; ctr++)\n    {\n      if (lu_table2[ctr]!=nullptr) delete[](lu_table2[ctr]);\n    }\n    free(lu_table2);\n  }\n}\n\n}  // namespace nfl\n\n#endif\n", "meta": {"hexsha": "f0ffc599d2306b54f40acb515411bb42ecd2e49b", "size": 21264, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nfl/prng/FastGaussianNoise.hpp", "max_stars_repo_name": "Valeh2012/NFLlib", "max_stars_repo_head_hexsha": "5cf40ed6a4929bfc304f3283aafd62c4149c55e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 128.0, "max_stars_repo_stars_event_min_datetime": "2015-12-14T09:58:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:16:37.000Z", "max_issues_repo_path": "include/nfl/prng/FastGaussianNoise.hpp", "max_issues_repo_name": "Valeh2012/NFLlib", "max_issues_repo_head_hexsha": "5cf40ed6a4929bfc304f3283aafd62c4149c55e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2015-11-26T23:39:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T21:19:19.000Z", "max_forks_repo_path": "include/nfl/prng/FastGaussianNoise.hpp", "max_forks_repo_name": "Valeh2012/NFLlib", "max_forks_repo_head_hexsha": "5cf40ed6a4929bfc304f3283aafd62c4149c55e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T14:41:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T06:42:05.000Z", "avg_line_length": 32.4641221374, "max_line_length": 213, "alphanum_fraction": 0.6679834462, "num_tokens": 6186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.6584175139669998, "lm_q1q2_score": 0.5428401832846529}}
{"text": "#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <complex>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/algorithm/minmax.hpp>\n\n#include \"../include/TriMesh.h\"\n#include \"../include/utils.h\"\n#include \"../include/lagrange.h\"\n#include \"../include/geometry.h\"\n#include \"../include/ConstructCurveMesh.h\"\n#include \"../include/GetQuadraturePointsWeight2D.h\"\n#include \"../include/solver.h\"\n#include \"../include/euler.h\"\n#include \"../include/Param.h\"\n#include \"../include/Collective.h\"\n#include \"../include/InvertMatrix.h\"\n\nusing namespace std;\nusing namespace utils;\nusing namespace lagrange;\n\n\nint main(int argc, char *argv[])\n{\n    namespace ublas = boost::numeric::ublas;\n\n    Param param;\n    // Set up the param struct\n    param = ReadParamIn(string(argv[1]));\n    TriMesh mesh(param.mesh_file);\n    // Testing Calculate Residaul\n    int p = param.order;\n    int q = param.order_geo;\n    int Np = int((p + 1) * (p + 2) / 2);\n    TriMesh curved_mesh = mesh;\n    string boundary_name=\"bottom\";\n    ConstructCurveMesh(mesh, curved_mesh, geometry::BumpFunction, boundary_name, q);\n\n\n    ublas::vector<double> States (curved_mesh.num_element * Np * 4, 0.0);\n    // Construct free stream state\n    ublas::vector<double> u_free = euler::CalcFreeStreamState_2DEuler(param);\n    for (int ielem = 0; ielem < curved_mesh.num_element; ielem++)\n    {\n        for (int ip = 0; ip < Np; ip++)\n        {\n            States(ielem * Np * 4 + ip * 4 + 0) = u_free(0);\n            States(ielem * Np * 4 + ip * 4 + 1) = u_free(1);\n            States(ielem * Np * 4 + ip * 4 + 2) = u_free(2);\n            States(ielem * Np * 4 + ip * 4 + 3) = u_free(3);\n        }\n    }\n\n    ResData resdata, resdata_postproc;\n    solver::CalcResData(curved_mesh, p, resdata);\n    if (p == 0)\n    {\n        solver::CalcResData(curved_mesh, 1, resdata_postproc);\n    }else\n    {\n        solver::CalcResData(curved_mesh, p, resdata_postproc);\n    }\n\n    ublas::vector<double> dt(curved_mesh.E.size());\n    // ublas::vector<double> Residual = solver::CalcResidual(curved_mesh, param, resdata, States, dt, p);\n    // cout << setprecision(20) << ublas::norm_2(Residual) << endl;\n    ublas::vector<ublas::matrix<double> > M = lagrange::ConstructMassMatrix(p, curved_mesh, resdata);\n    ublas::vector<ublas::matrix<double> > invM = lagrange::CalcInvMassMatrix(M);\n    int MAXITER = param.MAXITER;\n    int converged = 0;\n    ublas::vector<double> States_new (curved_mesh.num_element * Np * 4, 0.0);\n    ofstream file_residual;\n    file_residual.open(\"residual.log\");\n    for (int niter = 0; niter < MAXITER; niter++)\n    {\n        // cout << niter << endl;\n        double norm_residual = 0.0;\n        States_new = solver::TimeMarching_TVDRK3(curved_mesh, param, resdata, States, invM, p, converged, norm_residual);\n\t    if (niter % param.dnOutput == 0)\n\t    {\n            std::cout << \"NITER: \" << niter << \"\\t\" << \"Residual Norm_Inf: \";\n            cout.setf(ios::scientific, ios::floatfield);\n            std::cout << setprecision(10) << norm_residual << std::endl;\n        }\n        file_residual << niter << \"\\t\" << setprecision(20) << norm_residual << std::endl;\n        States = States_new;\n        if (converged)\n           break;\n    }\n    file_residual.close();\n\n    // PostProcessing the States, the output will be the global coordinate of the lagrange nodes in each element and the states on the nodes\n    int Np_solution;\n    if (p == 0)\n        Np_solution = 3;\n    else\n        Np_solution = Np;\n    ublas::vector<ublas::matrix<double> > Nodes(curved_mesh.E.size(), ublas::matrix<double>(Np_solution, 2, 0.0));\n    ublas::vector<ublas::matrix<double> > State_on_Nodes(curved_mesh.E.size(), ublas::matrix<double>(Np_solution, 4, 0.0));\n    solver::PostProc(curved_mesh, States, p, Nodes, State_on_Nodes);\n    // Write the Nodes Coordinates and States into the file\n    ofstream file_nodes, file_states, file_info;\n    file_nodes.open(\"nodes.dat\");\n    file_states.open(\"states.dat\");\n    file_info.open(\"info.dat\");\n    for (int ielem = 0; ielem < curved_mesh.E.size(); ielem++)\n    {\n        for (int ip = 0; ip < Np_solution; ip++)\n        {\n            file_nodes  << Nodes(ielem)(ip, 0) << ' ' << Nodes(ielem)(ip, 1) << std::endl;\n            file_states << State_on_Nodes(ielem)(ip, 0) << ' ' << State_on_Nodes(ielem)(ip, 1) << ' ' <<\n                            State_on_Nodes(ielem)(ip, 2) << ' ' << State_on_Nodes(ielem)(ip, 3) << std::endl;\n        }\n    }\n    file_info << curved_mesh.E.size() << ' ' << p << std::endl;\n    file_nodes.close();\n    file_states.close();\n    file_info.close();\n\n    return 0;\n}\n", "meta": {"hexsha": "92b24f5a44205abd637000b0e87eee3b53b1769f", "size": 4659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "xtwang1996/DG_Euler_2D", "max_stars_repo_head_hexsha": "1218ef7af9a85db48c84386e0fc396d09286be33", "max_stars_repo_licenses": ["MIT"], "max_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": "xtwang1996/DG_Euler_2D", "max_issues_repo_head_hexsha": "1218ef7af9a85db48c84386e0fc396d09286be33", "max_issues_repo_licenses": ["MIT"], "max_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": "xtwang1996/DG_Euler_2D", "max_forks_repo_head_hexsha": "1218ef7af9a85db48c84386e0fc396d09286be33", "max_forks_repo_licenses": ["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.272, "max_line_length": 140, "alphanum_fraction": 0.6215926164, "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.5428401665528058}}
{"text": "#include <ctime>\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 <vtkCellLocator.h>\n#include <vtkDelaunay3D.h>\n#include <vtkDataSetSurfaceFilter.h>\n#include <vtkPolyData.h>\n#include <vtkDoubleArray.h>\n#include <vtkPoints.h>\n#include <vtkIdFilter.h>\n#include <vtkPointData.h>\n#include <vtkCellArray.h>\n#include <vtkIdList.h>\n#include <vtkLinearSubdivisionFilter.h>\n#include <vtkGenericCell.h>\n#include <vtkVertexGlyphFilter.h>\n#include <vtkDataObject.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 \"SHTools.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    // 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    // Test function: 2*Y_1,-1 + Y_10 + 3*Y_11, so l=1, m=-1,0,1\n    int lmax = std::floor( sqrt(N) - 1 );\n    Eigen::VectorXd plms( (lmax + 1)*(lmax + 2)/2 );\n    auto Plm = [&plms](const size_t l, const size_t m){\n\treturn plms( l*(l+1)/2 + m );\n    };\n\n    // Map the point coordinates into a matrix\n    Map3Xd pointsOrig((double_t*)pointCloud->GetPoints()\n\t    ->GetData()->GetVoidPointer(0),3,N);\n    Matrix3Xd points(3,N);\n    points = pointsOrig;\n\n    //**********************************************************************//\n    // Create the Gauss-Lengendre grid\n    int nlat, nlong;\n    Eigen::VectorXd latglq(lmax + 1);\n    Eigen::VectorXd longlq(2*lmax + 1);\n    glqgridcoord_wrapper_(latglq.data(), longlq.data(), &lmax, &nlat, &nlong);\n    auto numQ = nlat*nlong;\n\n    Eigen::VectorXd gridglq((lmax + 1)*(2*lmax + 1));\n    Eigen::VectorXd plx( (lmax + 1)*(lmax + 1)*(lmax + 2)/2 );\n    Eigen::VectorXd w( lmax + 1 ), zero( lmax + 1 );\n    Eigen::VectorXd cilm( 2*(lmax + 1)*(lmax + 1) );\n    Eigen::VectorXd pspectrum( lmax + 1 );\n\n    // Pre-compute all the matrices needed for expansion\n    shglq_wrapper_(&lmax, zero.data(), w.data(), plx.data() );\n\n    //Now we need to first identify which triangles each of the quadrature\n    //points belongs to. For this, we need the coordinates of the points\n    Eigen::Matrix3Xd Q0(3,numQ);// Original quadrature points\n    Eigen::Matrix3Xd Qr(3,numQ);// Rotated quadrature points\n    Eigen::Matrix3Xd Qsp(3,numQ);// StereoProjection of quadrature points\n\n    size_t index = 0;\n    for( auto ip = 0; ip < nlong; ++ip){\n\tauto phi = longlq(ip)*M_PI/180.0;\n\tauto sin_p = std::sin(phi);\n\tauto cos_p = std::cos(phi);\n\tfor( auto it = 0; it < nlat; ++it){\n\t    auto theta = (90.0 - latglq(it))*M_PI/180.0;\n\t    auto sin_t = std::sin(theta);\n\t    Q0.col(index++) << sin_t*cos_p, sin_t*sin_p, std::cos(theta);\n\t}\n    }\n\n    // Write Quadrature points to VTK file\n    //writeMatToVTK( Q0, \"QuadPointsOrig.vtk\" );\n\n    //**********************************************************************//\n\n    VectorXd finput(N);\n    // A function to interpolate data to the quadrature points\n    auto interpolate = [&points, &Q0, &gridglq, &finput](const size_t i,\n\t    const size_t j, const size_t k, const size_t q){\n\tEigen::Vector3d v0 = points.col(i);\n\tEigen::Vector3d v1 = points.col(j);\n\tEigen::Vector3d v2 = points.col(k);\n\tEigen::Vector3d qp = Q0.col(q);\n\tauto A0 = ((v1-qp).cross((v2-qp))).norm();\n\tauto A1 = ((v2-qp).cross((v0-qp))).norm();\n\tauto A2 = ((v0-qp).cross((v1-qp))).norm();\n\tauto A = A0 + A1 + A2;\n\tgridglq(q) = (A0/A)*finput(i) + (A1/A)*finput(j) + (A2/A)*finput(k);\n    };\n\n    clock_t t = clock();\n    for( auto z = 0; z < 1000; ++z){\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// Calculate the function to be expanded using Spherical Harmonics\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    plmon_wrapper_(plms.data(), &lmax, &z);\n\t    auto phi = std::atan2(y,x);\n\t    finput(i) = 2*Plm(1,1)*std::sin(phi) + Plm(1,0) +\n\t\t3*Plm(1,1)*std::cos(phi);\n\t}\n\n\t// Rotate all points so that the 0th point 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\taxis.normalize();\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(); // dirns 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\" );\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\t// Triangulate\n\tDelaunay dt( verts.begin(), verts.end() );\n\n\t/*\n\t// Write the triangulation to file\n\tvtkNew<vtkPolyData> sphere;\n\tvtkNew<vtkCellArray> sphereTri;\n\tvtkNew<vtkPoints> spherePts;\n\tfor(auto zz = 0; zz < N; ++zz){\n\tVector3d pp = points.col(zz);\n\tspherePts->InsertNextPoint( &pp(0) );\n\t}\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\tsphere->SetPoints( spherePts );\n\tsphere->SetPolys( sphereTri );\n\tvtkNew<vtkPolyDataWriter> wr;\n\twr->SetInputData( sphere );\n\twr->SetFileName( \"UnitSphere.vtk\" );\n\twr->Write();\n\t*/\n\n\t// Rotate and project the quadrature points\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\" );\n\n\t// Locate the quadrature points using stereographic triangulation\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\tgridglq(j) = (finput(id1) +\n\t\t\t\tratio*finput(id2))/(1 + ratio);\n\t\t\tbreak;\n\t\t    }\n\t\tcase Delaunay::VERTEX:\n\t\t    gridglq(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<< \"Quadrature point \" << j << \" not found!\"\n\t\t\t<< std::endl;\n\t    }\n\t}\n\n\t// Expand using Gauss-Legendre Quadrature and get the power spectrum\n\tshexpandglq_wrapper_( cilm.data(), &lmax, gridglq.data(), w.data(),\n\t\tplx.data());\n\tshpowerspectrum_wrapper_( cilm.data(), &lmax, pspectrum.data() );\n    }\n    t = clock() - t;\n    std::cout<< \"Time for 1000 steps GLQ = \" << ((float)t)/CLOCKS_PER_SEC\n\t<< std::endl;\n\n    // Cross-check\n    Eigen::VectorXd gridglq_out( (lmax + 1)*(2*lmax + 1) );\n    makegridglq_wrapper_(gridglq_out.data(), cilm.data(), &lmax, plx.data());\n    std::cout<< \"Error norm of GLQ = \" << (gridglq - gridglq_out).norm()\n\t<< std::endl;\n\n    // Print the coefficients\n    std::cout<< \"l\\tm\\tAlm_GLQ\" << std::endl;\n    for( int l = 0; l <= lmax; ++l ){\n\tfor( int m = -l; m <=l; ++m ){\n\t    int i = m < 0? 1 : 0;\n\t    int n = m < 0? -m: m;\n\t    std::cout<< l << \"\\t\" << m << \"\\t\"\n\t\t<< cilm( i + 2*(l + n*(lmax + 1)) )<< \"\\t\"\n\t\t<< std::endl;\n\t}\n    }\n    return 0;\n}\n", "meta": {"hexsha": "d16ae4ef794348f2c63d7f8fb38c2650eb05f02c", "size": 10416, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "TestSHE.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": "TestSHE.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": "TestSHE.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.8532110092, "max_line_length": 78, "alphanum_fraction": 0.6213517665, "num_tokens": 3472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.5428401665528058}}
{"text": "\n#include <NTL/ZZ_pXFactoring.h>\n#include <NTL/ZZXFactoring.h>\n#include <NTL/GF2XFactoring.h>\n#include <NTL/GF2EXFactoring.h>\n\nNTL_CLIENT\n\n\n#define TIME_IT(t, action) \\\ndo { \\\n   double _t0, _t1; \\\n   long _iter = 1; \\\n   long _cnt = 0; \\\n   do { \\\n      _t0 = GetTime(); \\\n      for (long _i = 0; _i < _iter; _i++) { action; _cnt++; } \\\n      _t1 = GetTime(); \\\n   } while ( _t1 - _t0 < 4 && (_iter *= 2)); \\\n   t = (_t1 - _t0)/_iter; \\\n} while(0) \n\n\n\n\nint main()\n{\n   double t;\n\n\n   long k = 1000;\n   long n = 1000;\n\n   {\n      SetSeed(conv<ZZ>(1));\n      ZZ p = RandomPrime_ZZ(k);\n\n      ZZ_p::init(p);\n\n      ZZ x, y, z, w, s1, s2;\n\n      SetSeed(conv<ZZ>(2));\n      RandomBnd(x, p);\n\n\n      SetSeed(conv<ZZ>(3));\n      RandomBnd(y, p);\n\n      TIME_IT(t, mul(z, x, y));\n      cout << \"multiply 1000-bit ints: \" << t << \"\\n\";\n\n      TIME_IT(t, sqr(w, x));\n      cout << \"square 1000-bit ints: \" << t << \"\\n\";\n\n      TIME_IT(t, rem(w, z, p));\n      cout << \"remainder 2000/1000-bit ints: \" << t << \"\\n\";\n\n      TIME_IT(t, GCD(w, x, y));\n      cout << \"gcd 1000-bit ints: \" << t << \"\\n\";\n\n      TIME_IT(t, XGCD(w, s1, s2, x, y));\n      cout << \"xgcd 1000-bit ints: \" << t << \"\\n\";\n\n      TIME_IT(t, PowerMod(w, x, y, p));\n      cout << \"power mod 1000-bit ints: \" << t << \"\\n\";\n      \n\n      ZZ_pX a, b, c;\n\n      SetSeed(conv<ZZ>(4));\n      random(a, n);\n\n      SetSeed(conv<ZZ>(5));\n      random(b, n);\n\n      mul(c, a, b);\n\n      TIME_IT(t, mul(c, a, b));\n      cout << \"multiply degree-1000 poly mod 1000-bit prime: \" << t << \"\\n\";\n\n\n      ZZ_pX f;\n      SetSeed(conv<ZZ>(6));\n      random(f, n);\n      SetCoeff(f, n);\n\n      ZZ_pX A, B;\n\n      SetSeed(conv<ZZ>(7));\n      random(A, 2*(deg(f)-1)); \n\n      TIME_IT(t, rem(B, A, f));\n      cout << \"remainder degree-2000/1000 poly mod 1000-bit prime: \" << t << \"\\n\";\n\n      ZZ_pXModulus F(f);\n\n      TIME_IT(t, rem(B, A, F));\n      cout << \"preconditioned remainder degree-2000/1000 poly mod 1000-bit prime: \" << t << \"\\n\";\n\n\n      TIME_IT(t, GCD(a, b));\n      cout << \"gcd degree-1000 poly mod 1000-bit prime: \" << t << \"\\n\";\n\n\n      ZZX AA = conv<ZZX>(a);\n      ZZX BB = conv<ZZX>(b);\n      ZZX CC;\n\n\n      TIME_IT(t, mul(CC, AA, BB));\n      cout << \"multiply degree-1000 int poly with 1000-bit coeffs: \" << t << \"\\n\";\n\n      cout << \"\\n\";\n      cout << \"factoring degree-1000 poly mod 1000-bit prime...\\n\";\n      TIME_IT(t, CanZass(f, _cnt == 0));\n      cout << \"...total time = \" << t << \"\\n\\n\";\n   }\n   {\n      n = 500;\n      k = 500;\n\n      SetSeed(conv<ZZ>(8));\n      GF2X p = BuildRandomIrred(BuildIrred_GF2X(k));\n\n      GF2E::init(p);\n\n      GF2X x, y, z, w;\n\n      SetSeed(conv<ZZ>(9));\n      random(x, deg(p));\n\n\n      SetSeed(conv<ZZ>(10));\n      random(y, deg(p));\n\n      TIME_IT(t, mul(z, x, y));\n      cout << \"multiply 500-bit GF2Xs: \" << t << \"\\n\";\n\n\n      TIME_IT(t, rem(w, z, p));\n      cout << \"remainder 1000/500-bit GF2Xs: \" << t << \"\\n\";\n\n      TIME_IT(t, GCD(w, x, y));\n      cout << \"gcd 500-bit GF2Xs: \" << t << \"\\n\";\n\n      SetSeed(conv<ZZ>(11));\n      GF2X fff;\n      random(fff, k);\n      SetCoeff(fff, k);\n\n      cout << \"\\n\";\n      TIME_IT(t, CanZass(fff, 0));\n      cout << \"factoring degree-500 GF2X: \" << t << \"\\n\";\n\n\n      TIME_IT(t, GCD(w, x, y));\n      cout << \"gcd 500-bit GF2X: \" << t << \"\\n\";\n\n      GF2EX a, b, c;\n\n      SetSeed(conv<ZZ>(12));\n      random(a, n);\n\n      SetSeed(conv<ZZ>(13));\n      random(b, n);\n\n      mul(c, a, b);\n\n      TIME_IT(t, mul(c, a, b));\n      cout << \"multiply degree-500 poly mod 500-bit GF2X: \" << t << \"\\n\";\n\n\n\n      GF2EX f;\n      SetSeed(conv<ZZ>(14));\n      random(f, n);\n      SetCoeff(f, n);\n\n      GF2EX A, B;\n\n      SetSeed(conv<ZZ>(15));\n      random(A, 2*(deg(f)-1)); \n\n      TIME_IT(t, rem(B, A, f));\n      cout << \"remainder degree-1000/500 poly mod 500-bit GF2X: \" << t << \"\\n\";\n\n      GF2EXModulus F(f);\n\n      TIME_IT(t, rem(B, A, F));\n      cout << \"preconditioned remainder degree-1000/500 poly mod 500-bit GF2X: \" << t << \"\\n\";\n\n\n      TIME_IT(t, GCD(a, b));\n      cout << \"gcd degree-500 poly mod 500-bit GF2X: \" << t << \"\\n\";\n\n\n      f = f >> n/2;\n      cout << \"\\n\";\n      cout << \"factoring degree-500 poly mod 500-bit GF2X...\\n\";\n      TIME_IT(t, CanZass(f, _cnt == 0));\n      cout << \"\\n...total time = \" << t << \"\\n\";\n   }\n}\n", "meta": {"hexsha": "c9986c27b8e12ba8007aacc05a4f7b6b51be9906", "size": 4277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/Timing.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "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": "homomorphic_evaluation/ntl-11.3.2/src/Timing.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "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": "LibSource/ExtendedNTL/tests/Timing.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "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": 20.9656862745, "max_line_length": 97, "alphanum_fraction": 0.4746317512, "num_tokens": 1508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5428401555006322}}
{"text": "//\n// Created by Gleb Marin on 03.09.2021.\n//\n\n#ifndef FLOAT_MATRIX_COOMATRIX_HPP\n#define FLOAT_MATRIX_COOMATRIX_HPP\n\n#include <unordered_map>\n#include <vector>\n#include <ostream>\n#include <istream>\n#include <algorithm>\n\n#include <boost/compute/algorithm/sort.hpp>\n#include <boost/compute/algorithm/merge.hpp>\n#include <boost/compute/algorithm/reduce_by_key.hpp>\n#include <boost/compute/types/struct.hpp>\n\n#include \"Utility.hpp\"\n\nnamespace floatMatrix {\n    using T = float;\n\n    namespace cell {\n        struct Cell {\n            int row;\n            int col;\n            float data;\n        };\n\n        static inline BOOST_COMPUTE_FUNCTION(\n                bool, compareCellCoords,\n                (Cell a, Cell b), {\n                    if (a.row == b.row) {\n                        return a.col < b.col;\n                    }\n                    return a.row < b.row;\n                }\n        );\n\n        static inline BOOST_COMPUTE_FUNCTION(\n                Cell, reduceSameCells,\n                (Cell a, Cell b), {\n                    Cell reduced = {.row = a.row, .col = a.col, .data = a.data + b.data};\n                    return reduced;\n                }\n        );\n\n        static inline BOOST_COMPUTE_FUNCTION(\n                bool, equalCellCoords,\n                (Cell a, Cell b), {\n                    return a.col == b.col && a.row == b.row;\n                }\n        );\n    }\n\n    class CooMatrix {\n    public:\n        using CommandQueue = boost::compute::command_queue;\n        using Cell = cell::Cell;\n        using DeviceCells = boost::compute::vector<Cell>;\n\n        static constexpr T ZERO = static_cast<T>(0);\n\n    private:\n        using Row = std::unordered_map<std::size_t, T>;\n\n    public:\n        CooMatrix() = default;\n\n        explicit CooMatrix(const DeviceCells& cells) {\n            for (Cell cell : cells) {\n                matrix_[cell.row][cell.col] = cell.data;\n            }\n        }\n\n        template <typename Iterator>\n        explicit CooMatrix(Iterator begin, Iterator end, CommandQueue queue) {\n            for (auto it = begin; it < end; ++it) {\n                const auto& cell = it.read(queue);\n                matrix_[cell.row][cell.col] = cell.data;\n            }\n        }\n\n        explicit CooMatrix(const std::vector<Cell>& cells) {\n            for (const auto& cell : cells) {\n                matrix_[cell.row][cell.col] = cell.data;\n            }\n        }\n\n        void set(std::size_t row, std::size_t col, const T& value) noexcept {\n            matrix_[row][col] = value;\n        }\n\n        [[nodiscard]] T get(std::size_t rowId, std::size_t colId) const noexcept {\n            auto rowIt = matrix_.find(rowId);\n            if (rowIt == matrix_.cend()) {\n                return ZERO;\n            }\n            const Row& row = rowIt->second;\n            auto valIt = row.find(colId);\n            if (valIt == row.cend()) {\n                return ZERO;\n            }\n            return valIt->second;\n        }\n\n        void clear() noexcept {\n            matrix_.clear();\n        }\n\n        CooMatrix& add(const CooMatrix& other) {\n            for (const auto&[rowId, row] : other.matrix_) {\n                for (const auto&[colId, value] : row) {\n                    matrix_[rowId][colId] += value;\n                    if (matrix_[rowId][colId] == ZERO) {\n                        matrix_[rowId].erase(colId);\n                    }\n                }\n            }\n            return *this;\n        }\n\n        CooMatrix& add(const CooMatrix& other, boost::compute::command_queue& queue) {\n            DeviceCells thisCells = toDeviceCells(queue);\n            DeviceCells otherCells = other.toDeviceCells(queue);\n            boost::compute::sort(thisCells.begin(), thisCells.end(), cell::compareCellCoords, queue);\n            boost::compute::sort(otherCells.begin(), otherCells.end(), cell::compareCellCoords, queue);\n            DeviceCells merged(thisCells.size() + otherCells.size(), queue.get_context());\n\n            boost::compute::merge(\n                    thisCells.begin(), thisCells.end(),\n                    otherCells.begin(), otherCells.end(),\n                    merged.begin(),\n                    cell::compareCellCoords,\n                    queue\n            );\n\n            DeviceCells reducedValues(merged.size(), queue.get_context());\n            DeviceCells reducedKeys(merged.size(), queue.get_context());\n            auto [keysEnd, valuesEnd] = boost::compute::reduce_by_key(\n                    merged.begin(), merged.end(), merged.begin(),\n                    reducedKeys.begin(), reducedValues.begin(),\n                    cell::reduceSameCells,\n                    cell::equalCellCoords,\n                    queue\n            );\n\n            return *this = CooMatrix(reducedValues.begin(), valuesEnd, queue);\n        }\n\n        [[nodiscard]] std::vector<Cell> toCellsList() const {\n            std::vector<Cell> cells;\n            for (const auto&[rowId, row] : matrix_) {\n                for (const auto&[colId, value] : row) {\n                    if (value == ZERO) {\n                        continue;\n                    }\n                    cells.push_back({static_cast<int>(rowId), static_cast<int>(colId), value});\n                }\n            }\n            return cells;\n        }\n\n        DeviceCells toDeviceCells(CommandQueue& queue) const {\n            std::vector<Cell> cells = toCellsList();\n            DeviceCells deviceCells(cells.size(), queue.get_context());\n            boost::compute::copy(cells.begin(), cells.end(), deviceCells.begin(), queue);\n            return deviceCells;\n        }\n\n        bool operator==(const CooMatrix& other) const {\n            return isEqSubset(other) && other.isEqSubset(*this);\n        }\n\n        friend std::ostream& operator<<(std::ostream& os, const CooMatrix& comp) {\n            std::vector<Cell> cells = comp.toCellsList();\n            os << cells.size() << '\\n';\n            for (const Cell& cell : cells) {\n                os << cell.row << ' ';\n                os << cell.col << ' ';\n                os << cell.data << ' ';\n            }\n            return os;\n        }\n\n        friend std::istream& operator>>(std::istream& is, CooMatrix& comp) {\n            std::size_t elems;\n            is >> elems;\n            std::unordered_map<std::size_t, Row> rows(elems);\n            for (std::size_t i = 0; i < elems; ++i) {\n                std::size_t row, col;\n                T data;\n                is >> row >> col >> data;\n                rows[row][col] = data;\n            }\n            comp.matrix_ = rows;\n            return is;\n        }\n\n    private:\n        [[nodiscard]] bool isEqSubset(const CooMatrix& other) const {\n            for (const auto&[rowId, row] : matrix_) {\n                for (const auto&[colId, value] : row) {\n                    if (!utility::isEq(other.get(rowId, colId), value)) {\n                        std::cerr << \"Row: \" << rowId << ' ' << \"Col: \" << colId << std::endl;\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }\n\n        std::unordered_map<std::size_t, Row> matrix_;\n    };\n}\n\nBOOST_COMPUTE_ADAPT_STRUCT(floatMatrix::cell::Cell, Cell, (row, col, data));\n\n#endif //FLOAT_MATRIX_COOMATRIX_HPP\n", "meta": {"hexsha": "d9534c1e2f979f735628b615c8e1adf03f6b0c81", "size": 7265, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/CooMatrix.hpp", "max_stars_repo_name": "Glebanister/float-matrix", "max_stars_repo_head_hexsha": "c96b851b8ba11687e6a8d3d8a1c27b59a3b57528", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CooMatrix.hpp", "max_issues_repo_name": "Glebanister/float-matrix", "max_issues_repo_head_hexsha": "c96b851b8ba11687e6a8d3d8a1c27b59a3b57528", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CooMatrix.hpp", "max_forks_repo_name": "Glebanister/float-matrix", "max_forks_repo_head_hexsha": "c96b851b8ba11687e6a8d3d8a1c27b59a3b57528", "max_forks_repo_licenses": ["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.8733031674, "max_line_length": 103, "alphanum_fraction": 0.4947006194, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5428401498209585}}
{"text": "// Copyright 2002 - 2008, 2010, 2011 National Technology Engineering\n// Solutions of Sandia, LLC (NTESS). Under the terms of Contract\n// DE-NA0003525 with NTESS, the U.S. Government retains certain rights\n// in this software.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n#ifndef percept_math_TransformationMatrix_hpp\n#define percept_math_TransformationMatrix_hpp\n\n#include <stdexcept>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <iostream>\n#include <string>\n#include <typeinfo>\n\n#include <math.h>\n\n#include <Teuchos_ScalarTraits.hpp>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <percept/Stacktrace.hpp>\n#include <percept/Util.hpp>\n\nnamespace percept {\n\n  namespace ublas =  boost::numeric::ublas;\n\n  class Math\n  {\n  public:\n\n    typedef ublas::c_matrix<double,3,3> Matrix;\n\n    typedef ublas::c_vector<double,3> Vector;\n\n    typedef ublas::c_vector<double,3> ubvec;\n\n    class MyVector : public ubvec\n    {\n    public:\n\n      MyVector(double x=0.0) : ubvec()\n      {\n        (*this)(0) = x;\n        (*this)(1) = x;\n        (*this)(2) = x;\n      }\n\n      MyVector(double *x) : ubvec()\n      {\n        (*this)(0) = x[0];\n        (*this)(1) = x[1];\n        (*this)(2) = x[2];\n      }\n      //Vector(const ubvec& v) : ubvec(v) {}\n\n      MyVector& operator=(const ubvec& v)\n      {\n        //ubvec& v0 = ubvec::operator=(v);\n        (*this)(0) = v(0);\n        (*this)(1) = v(1);\n        (*this)(2) = v(2);\n        return *this;\n      }\n\n      //v = ublas::prod(m_rotMat, v);\n\n    };\n\n    static double my_abs_hi(double x, double eps=1.e-6) { return std::sqrt(x*x + eps*eps); }\n    static double my_min_hi(double x, double y, double eps=1.e-6) { return 0.5*(x+y - my_abs_hi(x-y,eps)); }\n    static double my_max_hi(double x, double y, double eps=1.e-6) { return 0.5*(x+y + my_abs_hi(x-y,eps)); }\n    // heavyside\n    static double heavy_smooth(double x, double x0, double eps=1.e-6) { return 1./(1.+std::exp(-2.0*(x-x0)/eps)); }\n\n    static double random01()\n    {\n      double rnd = Teuchos::ScalarTraits<double>::random();\n      return (rnd+1.0)/2.0;\n    }\n\n    static Matrix rotationMatrix(int axis, double angle_degrees)\n    {\n      Matrix rm;\n      rm.clear();\n      double theta = M_PI * angle_degrees / 180.0;\n      double cost = std::cos(theta);\n      double sint = std::sin(theta);\n      if (axis == 2)\n        {\n          rm(0,0) = cost; rm(0,1) = -sint;\n          rm(1,0) = sint; rm(1,1) = cost;\n          rm(2,2) = 1.0;\n        }\n      else if (axis == 1)\n        {\n          rm(0,0) = cost; rm(0,2) = -sint;\n          rm(2,0) = sint; rm(2,2) = cost;\n          rm(1,1) = 1.0;\n        }\n      else if (axis == 0)\n        {\n          rm(1,1) = cost; rm(1,2) = -sint;\n          rm(2,1) = sint; rm(2,2) = cost;\n          rm(0,0) = 1.0;\n        }\n      return rm;\n    }\n\n    static Matrix scalingMatrix(int axis, double scale)\n    {\n      Matrix sm;\n      sm.clear();\n      sm(0,0)=1.0;\n      sm(1,1)=1.0;\n      sm(2,2)=1.0;\n      sm(axis,axis)=scale;\n      return sm;\n    }\n\n    static Matrix scalingMatrix( double scale)\n    {\n      Matrix sm;\n      sm.clear();\n      sm(0,0)=scale;\n      sm(1,1)=scale;\n      sm(2,2)=scale;\n      return sm;\n    }\n\n    static double norm_3d(const double * vec)\n    {\n      double norm = std::sqrt(vec[0]*vec[0]+\n                              vec[1]*vec[1]+\n                              vec[2]*vec[2]);\n      return norm;\n    }\n\n    static void normalize_3d(double * vec)\n    {\n      double norm = norm_3d(vec);\n      if (norm > 0.0)\n        {\n          vec[0] /= norm;\n          vec[1] /= norm;\n          vec[2] /= norm;\n        }\n      else\n        {\n          std::cout << \"norm= \" << vec[0] << \", \" << vec[1] << \", \" << vec[2] << \"\\n\"\n                    << Stacktrace::demangled_stacktrace(30) << std::endl;\n          VERIFY_MSG(\"bad norm\");\n        }\n    }\n    static void cross_3d(const double * a, const double * b, double * axb)\n    {\n      axb[0] = (a[1]*b[2]-a[2]*b[1]);\n      axb[1] = -(a[0]*b[2]-a[2]*b[0]);\n      axb[2] = (a[0]*b[1]-a[1]*b[0]);\n    }\n    static double dot_3d(const double *a, const double *b)\n    {\n      return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];\n    }\n    static double distance_squared_3d(const double *a, const double *b)\n    {\n      return (a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]) + (a[2]-b[2])*(a[2]-b[2]);\n    }\n    static double distance_3d(const double *a, const double *b)\n    {\n      return std::sqrt(distance_squared_3d(a,b));\n    }\n    static void copy_3d(double *a, const double *b)\n    {\n      a[0] = b[0];\n      a[1] = b[1];\n      a[2] = b[2];\n    }\n    static void copy_2d(double *a, const double *b)\n    {\n      a[0] = b[0];\n      a[1] = b[1];\n    }\n    static std::string print_3d(const double *a, int prec=6)\n    {\n      std::ostringstream ostr;\n      ostr << std::setprecision(prec);\n      ostr << \" \" << a[0] << \", \" << a[1] << \", \" << a[2];\n      return ostr.str();\n    }\n    static std::string print_2d(const double *a, int prec=6)\n    {\n      std::ostringstream ostr;\n      ostr << std::setprecision(prec);\n      ostr << \" \" << a[0] << \", \" << a[1];\n      return ostr.str();\n    }\n    static void subtract_3d(double *a, const double *b)\n    {\n      a[0] -= b[0];\n      a[1] -= b[1];\n      a[2] -= b[2];\n    }\n\n    static double project_to_line_3d(const double *a, const double *b, double *xyz, double& u)\n    {\n      double xma[3] = {0,0,0}, bma[3] = {0,0,0}, bman[3] = {0,0,0}, xyz_in[3] = {0,0,0};\n      copy_3d(xyz_in, xyz);\n      copy_3d(bma, b);\n      subtract_3d(bma, a);\n      copy_3d(xma, xyz);\n      subtract_3d(xma, a);\n      copy_3d(bman, bma);\n      normalize_3d(bman);\n      double dd = dot_3d(xma, bman);\n      double ba_len = distance_3d(a, b);\n      if (dd < 0.0)\n        {\n          u = 0.0;\n          copy_3d(xyz, a);\n        }\n      else if (dd > ba_len)\n        {\n          u = 1.0;\n          copy_3d(xyz, b);\n        }\n      else\n        {\n          u = dd/ba_len;\n          xyz[0] = a[0] + u*(b[0] - a[0]);\n          xyz[1] = a[1] + u*(b[1] - a[1]);\n          xyz[2] = a[2] + u*(b[2] - a[2]);\n        }\n      return distance_3d(xyz, xyz_in);\n    }\n  };\n\n  inline Math::Vector operator*(Math::Matrix& mat, Math::Vector& vec) { return ublas::prod(mat, vec); }\n  inline Math::Matrix operator*(Math::Matrix& mat, Math::Matrix& mat2) { return ublas::prod(mat, mat2); }\n\n}\n\n#endif\n", "meta": {"hexsha": "57128b74236cd3d7657bb454d72c8992949b0199", "size": 6481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/percept/math/Math.hpp", "max_stars_repo_name": "jrood-nrel/percept", "max_stars_repo_head_hexsha": "363cdd0050443760d54162f140b2fb54ed9decf0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-08-08T21:06:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-08T13:23:36.000Z", "max_issues_repo_path": "src/percept/math/Math.hpp", "max_issues_repo_name": "jrood-nrel/percept", "max_issues_repo_head_hexsha": "363cdd0050443760d54162f140b2fb54ed9decf0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-12-17T00:18:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-09T15:29:25.000Z", "max_forks_repo_path": "src/percept/math/Math.hpp", "max_forks_repo_name": "jrood-nrel/percept", "max_forks_repo_head_hexsha": "363cdd0050443760d54162f140b2fb54ed9decf0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T07:02:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-05T17:07:04.000Z", "avg_line_length": 25.8207171315, "max_line_length": 115, "alphanum_fraction": 0.5096435735, "num_tokens": 2167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5428401441412847}}
{"text": "#ifndef NBT_DYNAMICS_ENGINE_HPP\n#define NBT_DYNAMICS_ENGINE_HPP\n\n#include <Eigen>\n#include \"octree.hpp\"\n#include \"units.hpp\"\n\n/**\n * Abstract class for Dynamics engines.\n * Used to update the accelerations of a set of\n * particles based on their positions and masses.\n */\nclass DynamicsEngine {\n    public:\n        /**\n         * @brief Recalculates acceleration matrix using object positions and masses\n         * \n         * @param a Acceleration matrix\n         * @param x Position matrix\n         * @param m Mass vector\n         */\n        virtual void updateAccelerations(Eigen::Ref<Eigen::Matrix3Xd> a,\n                                         const Eigen::Ref<const Eigen::Matrix3Xd>& x,\n                                         const Eigen::Ref<const Eigen::RowVectorXd>& m) = 0;\n        \n        /**\n         * @brief Updates the individual acceleration between particles i and j\n         * \n         * @param a_i Acceleration of i\n         * @param x_i Position of i\n         * @param x_j Position of j\n         * @param m_i Mass of i\n         * @param m_j Mass of j\n         */\n        virtual void pairAcceleration(Eigen::Ref<Eigen::Vector3d> a_i,\n                                      const Eigen::Vector3d& x_i,\n                                      const Eigen::Vector3d& x_j,\n                                      double m_i,\n                                      double m_j) = 0;\n        \n        /**\n         * @brief Returns the potential energy of a system based on particle positions and masses.\n         * \n         * @param x Position matrix\n         * @param m Mass vector\n         * \n         * @return double\n         */\n        double totalPotentialEnergy(const Eigen::Ref<const Eigen::Matrix3Xd>& x,\n                                    const Eigen::Ref<const Eigen::RowVectorXd>& m);\n        \n        /**\n         * @brief Returns the potential energy between a pair of particles i and j.\n         *        Default abstract class method returns zero for everything, can be overriden\n         *        in custom subclasses.\n         * \n         * @param x_i Position of i\n         * @param x_j Position of j\n         * @param m_i Mass of i\n         * @param m_j Mass of j\n         * @return double \n         */\n        virtual double pairPotentialEnergy(const Eigen::Vector3d& x_i,\n                                           const Eigen::Vector3d& x_j,\n                                           double m_i,\n                                           double m_j);\n};\n\n\n/* ABSTRACT CLASSES FOR N-BODY UPDATE METHODS */\n/* Implements DynamicsEngine::updateAccelerations() */\n\n\n/**\n * Computes force directly between every pair of objects. O(n^2)\n */\nclass Abstract_Direct: public DynamicsEngine {\n    public:\n        /**\n         * @brief Computes force between each pair of particles individually.\n         * \n         * @param a\n         * @param x\n         * @param m\n         */\n        void updateAccelerations(Eigen::Ref<Eigen::Matrix3Xd> a,\n                                 const Eigen::Ref<const Eigen::Matrix3Xd>& x,\n                                 const Eigen::Ref<const Eigen::RowVectorXd>& m) override;\n};\n\n\n/**\n * A multithreaded Barnes-Hut force computer. O(nlogn)\n */\nclass Abstract_BarnesHut: public DynamicsEngine {\n    public:\n        OctreeNode* root;       //!< Root node of the Barnes-Hut tree.\n        const double theta;     //!< Theta parameter for Barnes-Hut algorithm\n        \n        /**\n         * @brief Construct a Abstract_Direct object.\n         * \n         * @param theta Theta parameter for the Barnes-Hut algorithm\n         */\n        Abstract_BarnesHut(double theta);\n\n        /**\n         * @brief Destroy the Abstract_BarnesHut object\n         */\n        ~Abstract_BarnesHut();\n        \n        /**\n         * @brief Function for threads. Computes the acceleration of bodies from indices startIdx to endIdx (endIdx not included)\n         * \n         * @param a\n         * @param x \n         * @param m \n         * @param startIdx\n         * @param endIdx\n         */\n        void threadUpdateAccelerations(Eigen::Ref<Eigen::Matrix3Xd> a,\n                                      const Eigen::Ref<const Eigen::Matrix3Xd>& x,\n                                      const Eigen::Ref<const Eigen::RowVectorXd>& m,\n                                      int startIdx,\n                                      int endIdx);\n\n        /**\n         * @brief Computes forces acting on each particle using the Barnes-Hut algorithm\n         * \n         * @param a \n         * @param x \n         * @param m \n         */\n        void updateAccelerations(Eigen::Ref<Eigen::Matrix3Xd> a,\n                                const Eigen::Ref<const Eigen::Matrix3Xd>& x,\n                                const Eigen::Ref<const Eigen::RowVectorXd>& m) override;\n};\n\n\n/* SPECIFIC DYNAMICS ENGINES */\n/* Implement DynamicsEngine::pairAccleration() */\n\n\nclass Gravitational_Direct: public Abstract_Direct {\n    public:\n        const double G;\n        const double softening;\n\n        /**\n         * @brief Construct a new Gravitational_Direct object\n         * \n         * @param softening Softening parameter\n         * @param l Unit of length\n         * @param m Unit of mass\n         * @param t Unit of time\n         */\n        Gravitational_Direct(double softening, unit_t l = Unit::Meter, unit_t m = Unit::Kilogram, unit_t t = Unit::Second);\n\n        /**\n         * @brief Computes acceleration from Newtonian gravitation between two particles i and j\n         * \n         * @param a_i \n         * @param x_i \n         * @param x_j \n         * @param m_i \n         * @param m_j \n         */\n        void pairAcceleration(Eigen::Ref<Eigen::Vector3d> a_i,\n                              const Eigen::Vector3d& x_i,\n                              const Eigen::Vector3d& x_j,\n                              double m_i,\n                              double m_j) override;\n        \n         /**\n         * @brief Returns the gravitational potential energy between a pair of particles i and j.\n         * \n         * @param x_i Position of i\n         * @param x_j Position of j\n         * @param m_i Mass of i\n         * @param m_j Mass of j\n         * @return double \n         */\n        double pairPotentialEnergy(const Eigen::Vector3d& x_i,\n                                   const Eigen::Vector3d& x_j,\n                                   double m_i,\n                                   double m_j) override;\n};\n\n\nclass Gravitational_BarnesHut: public Abstract_BarnesHut {\n    public:\n        const double G;\n        const double softening;\n\n        /**\n         * @brief Construct a new Gravitational_Direct object\n         * \n         * @param theta Theta parameter for the Barnes-Hut algorithm\n         * @param softening Softening parameter\n         * @param l Unit of length\n         * @param m Unit of mass\n         * @param t Unit of time\n         */\n        Gravitational_BarnesHut(double theta, double softening, unit_t l = Unit::Meter, unit_t m = Unit::Kilogram, unit_t t = Unit::Second);\n\n        /**\n         * @brief Computes acceleration from Newtonian gravitation between two particles i and j\n         * \n         * @param a_i \n         * @param x_i \n         * @param x_j \n         * @param m_i \n         * @param m_j \n         */\n        void pairAcceleration(Eigen::Ref<Eigen::Vector3d> a_i,\n                              const Eigen::Vector3d& x_i,\n                              const Eigen::Vector3d& x_j,\n                              double m_i,\n                              double m_j) override;\n        \n         /**\n         * @brief Returns the gravitational potential energy between a pair of particles i and j.\n         * \n         * @param x_i Position of i\n         * @param x_j Position of j\n         * @param m_i Mass of i\n         * @param m_j Mass of j\n         * @return double \n         */\n        double pairPotentialEnergy(const Eigen::Vector3d& x_i,\n                                   const Eigen::Vector3d& x_j,\n                                   double m_i,\n                                   double m_j) override;\n};\n\n\n#endif", "meta": {"hexsha": "ddd221bc09ef3b10219864b4c6f15e2b94e6cbf1", "size": 8094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dynamics_engine.hpp", "max_stars_repo_name": "tdude92/nbody-tool", "max_stars_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-12T08:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:37:44.000Z", "max_issues_repo_path": "include/dynamics_engine.hpp", "max_issues_repo_name": "tdude92/nbody-tool", "max_issues_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_issues_repo_licenses": ["MIT"], "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/dynamics_engine.hpp", "max_forks_repo_name": "tdude92/nbody-tool", "max_forks_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_forks_repo_licenses": ["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.1518987342, "max_line_length": 140, "alphanum_fraction": 0.511242896, "num_tokens": 1730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5428053260488074}}
{"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/vector/arithmetic.hpp>\n#include <fcppt/math/vector/object_impl.hpp>\n#include <fcppt/math/vector/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/time.hpp>\n#include <boost/units/systems/si/velocity.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_units\n)\n{\nFCPPT_PP_POP_WARNING\n\ttypedef int unit_type;\n\n\ttypedef boost::units::quantity<\n\t\tboost::units::si::length,\n\t\tunit_type\n\t> length;\n\n\ttypedef boost::units::quantity<\n\t\tboost::units::si::time,\n\t\tunit_type\n\t> time;\n\n\ttypedef boost::units::quantity<\n\t\tboost::units::si::velocity,\n\t\tunit_type\n\t> velocity;\n\n\ttypedef fcppt::math::vector::static_<\n\t\tlength,\n\t\t2\n\t> length2;\n\n\ttypedef fcppt::math::vector::static_<\n\t\ttime,\n\t\t2\n\t> time2;\n\n\ttypedef fcppt::math::vector::static_<\n\t\tvelocity,\n\t\t2\n\t> velocity2;\n\n\tlength2 const l1(\n\t\tlength(\n\t\t\t-100\n\t\t\t*\n\t\t\tboost::units::si::meter\n\t\t),\n\t\tlength(\n\t\t\t200\n\t\t\t*\n\t\t\tboost::units::si::meter\n\t\t)\n\t);\n\n\ttime2 const t1(\n\t\ttime(\n\t\t\t4\n\t\t\t*\n\t\t\tboost::units::si::second\n\t\t),\n\t\ttime(\n\t\t\t2\n\t\t\t*\n\t\t\tboost::units::si::second\n\t\t)\n\t);\n\n\tvelocity2 const v1(\n\t\tl1\n\t\t/\n\t\tt1\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tv1.x().value(),\n\t\t-25\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tv1.y().value(),\n\t\t100\n\t);\n}\n", "meta": {"hexsha": "d25aa8261881e09a9a6103a3d6eeb16e253dbe74", "size": 1784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/units.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/units.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/units.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": 17.1538461538, "max_line_length": 61, "alphanum_fraction": 0.6883408072, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5428053212893331}}
{"text": "//    Copyright 2015 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\n\n/** \\file\n *\n * A simple example that demonstrates the usage of mpi2. Spawns a couple of tasks that each run\n * Monte Carlo integration to estimate the value of pi; then averages and outputs the result.\n */\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n\n#include <boost/foreach.hpp>\n\n#include <util/io.h>\n#include <util/random.h>\n\n#include <mpi2/mpi2.h>\n\nusing namespace std;\nusing namespace mpi2;\nusing namespace rg;\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\n/** Task that computes pi via Monte Carlo integration */\nstruct PiTask {\n\tstatic inline string id() { return \"PiTask\"; }\n\tstatic inline void run(Channel ch, TaskInfo info) {\n\t\t// receive the seed for the random number generator\n\t\tRandom32 random = getSeed(ch);\n\n\t\t// receive the number of iterations to perform\n\t\tunsigned n;\n\t\tch.recv(n);\n\n\t\t// run Monte Carlo integration\n\t\tLOG4CXX_INFO(logger, \"Task \" << info.groupId() << \": Generating \" << n\n\t\t\t\t<< \" MC samples\");\n\t\tint count = 0;\n\t\tfor (unsigned i=0; i<n; i++) {\n\t\t\tdouble x = random.nextDouble(); // actually need [-1,1]; but [0,1] is OK since we square\n\t\t\tdouble y = random.nextDouble();\n\t\t\tif (x*x+ y*y < 1) count++;\n\t\t}\n\t\tdouble est = (double)count/n * 4.; // area unit circle = pi; area square = 4\n\n\t\t// send back the results\n\t\tLOG4CXX_INFO(logger, \"Task \" << info.groupId() << \": Sending \" << est);\n\t\tch.send(est);\n\t}\n};\n\nint main(int argc, char* argv[]) {\n\t// initialize mpi2\n\tboost::mpi::communicator& world = mpi2init(argc, argv);\n\n\t// register PiTask (this is required to be able to actually run it!)\n\tTaskManager& tm = TaskManager::getInstance();\n\tregisterTask<PiTask>();\n\n\t// fire up task managers (this blocks on all but the root node)\n\tmpi2start();\n\n\t// main driver; only executed at root rank\n\tif (world.rank() == 0) {\n\t\t// spawn 3 copies of PiTask at each rank\n\t\tstd::vector<Channel> channels;\n\t\tint threads = 3;\n\t\ttm.spawnAll<PiTask>(threads, channels);\n\n\t\t// send them each a different random number seed\n\t\tRandom32 random; // note: this takes a default seed (not randomized!)\n\t\tseed(channels, random);\n\n\t\t// send them the number of samples to take\n\t\tsendAll(channels, 100000); // each thread computes 100000 samples\n\n\t\t// receive the results\n\t\tstd::vector<double> results(channels.size());\n\t\trecvAll(channels, results);\n\n\t\t// aggregate and output the result\n\t\tdouble pi = std::accumulate(results.begin(), results.end(), 0.) / channels.size();\n\t\tLOG4CXX_INFO(logger, \"Estimate of pi: \" << pi);\n\t}\n\n\t// shut down task managers\n\tmpi2stop();\n\n\t// shut down mpi2 and mpi\n\tmpi2finalize();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "265886f4cf5a793fc4584d2ae42439c818f25712", "size": 3221, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/pi_task.cc", "max_stars_repo_name": "Hui-Li/mpi2", "max_stars_repo_head_hexsha": "40c09937a16f6ccc0bea9dafcc8aa731da4b8d38", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-02T15:06:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-29T08:57:05.000Z", "max_issues_repo_path": "examples/pi_task.cc", "max_issues_repo_name": "uma-pi1/mpi2", "max_issues_repo_head_hexsha": "1b00acefa50d672e79c8d9238f2966471e70b8e3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-02T15:08:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-15T07:13:06.000Z", "max_forks_repo_path": "examples/pi_task.cc", "max_forks_repo_name": "Hui-Li/mpi2", "max_forks_repo_head_hexsha": "40c09937a16f6ccc0bea9dafcc8aa731da4b8d38", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-17T08:52:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T08:52:54.000Z", "avg_line_length": 29.2818181818, "max_line_length": 95, "alphanum_fraction": 0.6845700093, "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5428053138182202}}
{"text": "/**\n*  @file    mdm_ParamSummaryStats.cxx\n*  @brief   Implementation of mdm_ParamSummaryStats class\n*\n*  Original author MA Berks 13 Nov 2020\n*  (c) Copyright QBI, University of Manchester 2020\n*/\n\n#ifndef MDM_API_EXPORTS\n#define MDM_API_EXPORTS\n#endif // !MDM_API_EXPORTS\n\n#include \"mdm_ParamSummaryStats.h\"\n\n#include <cassert>\n#include <cmath>\n#include <fstream>\n#include <algorithm>\n#include <boost/format.hpp>\n#include <madym/mdm_exception.h>\n\nconst std::vector<std::string> mdm_ParamSummaryStats::headers_ = {\n\t\"param\",\n\t\"n_valid\",\n\t\"n_invalid\",\n\t\"mean\",\n\t\"stddev\",\n\t\"median\",\n\t\"lowerQ\",\n\t\"upperQ\",\n\t\"iqr\"\n};\n\n//!Helper function to compute percentile of vector of values\ndouble percentile(const std::vector<double> &A, const double &prct)\n{\n\t//We only ever call this function for 25,50 and 100, but for completeness\n\tassert(prct >= 0 && prct <= 100.0);\n\tif (prct == 0)\n\t\treturn A[0];\n\tif (prct == 100)\n\t\treturn A.back();\n\n\t//See https://en.wikipedia.org/wiki/Quartile#Method_4\n\tdouble n1 = (double)A.size() + 1;\n\tdouble pn1 = n1 * prct / 100.00;\n\tsize_t k = size_t(std::floor(pn1));\n\n\t//If size A < 3, then k = 0 for prctile(25) and k = 3 for prctile(75)\n\tif (!k)\n\t\treturn A[0];\n\telse if (k == A.size())\n\t\treturn A.back();\n\n\tdouble alpha = pn1 - k;\n\treturn A[k - 1] + alpha * (A[k] - A[k - 1]);//Remember indexing starts at 0 in cxx\n\n\t/*double x = (double)A.size() * prct / 100.00;\n\tint i2 = std::floor(x); \n\tint i1 = i2 - 1;\n\tdouble m1 = 0.5 - (x - (double)i2);\n\tdouble m2 = 1.0 - m1;\n\treturn A[i1] * m1 + A[i2] * m2;*/\n}\n\n//\nMDM_API mdm_ParamSummaryStats::mdm_ParamSummaryStats()\n\t:\n\troiIdx_(0)\n{\n\n}\n\n//\nMDM_API mdm_ParamSummaryStats::~mdm_ParamSummaryStats()\n{\n\tcloseNewStatsFile();\n}\n\n//!Set ROI\nMDM_API void mdm_ParamSummaryStats::setROI(const mdm_Image3D& roi)\n{\n\t//Don't store the image, just save the non-zero IDX\n\troiIdx_.clear();\n\tfor (int i = 0; i < roi.numVoxels(); i++)\n\t{\n\t\tif (roi.voxel(i))\n\t\t\troiIdx_.push_back(i);\n\t}\n\t\t\n\txmm_ = roi.info().Xmm.value();\n\tymm_ = roi.info().Ymm.value();\n\tzmm_ = roi.info().Zmm.value();\n}\n\n//!Make output stats for an image given an ROI\nMDM_API void mdm_ParamSummaryStats::makeStats(const mdm_Image3D& img, const std::string &paramName, \n\tconst double scale, bool invert)\n{\n\t//Set param name\n\tstats_.paramName_ = paramName;\n\n\t//Check ROI idx are set\n\tcheckIdx(img);\n\n\t//Reset the stats\n\tstats_.reset();\n\n\t// loop image extracting parameter values and taking running sum\n\tdouble ROI_sum = 0.0;\n\tdouble ROI_sumsq = 0.0;\n\n\tstd::vector<double>  paramVals;\n\tfor (const auto &idx : roiIdx_)\n\t{\n\t\t// Get value from image\n\t\tdouble voxValue = scale * img.voxel(idx);\n\n\t\tif (std::isnan(voxValue))\n\t\t{\n\t\t\tstats_.invalidVoxels_++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (invert)\n\t\t{\n\t\t\t//Can't invert negative values, just skip\n\t\t\tif (voxValue <= 0.0)\n\t\t\t{\n\t\t\t\tstats_.invalidVoxels_++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\t\n\n\t\t\telse\n\t\t\t\tvoxValue = 1 / voxValue;\n\t\t}\n\n\t\t//Increment sums and save value\n\t\tROI_sum += voxValue;\n\t\tROI_sumsq += voxValue * voxValue;\n\t\tparamVals.push_back(voxValue);\n\t\tstats_.validVoxels_++;\n\t}\n\n\t//If we haven't got any voxels, return\n\tif (!stats_.validVoxels_)\n\t\treturn;\n\n\telse if (stats_.validVoxels_ == 1)\n\t{\n\t\tstats_.mean_ = paramVals[0];\n\t\tstats_.median_ = paramVals[0];\n\t\tstats_.lowerQ_ = paramVals[0];\n\t\tstats_.upperQ_ = paramVals[0];\n\n\t\t//std and iqr are 0\n\t\treturn;\n\t}\n\n\t//Compute summary stats from data values\n\t//Sort the data arrays\n\tstd::sort(paramVals.begin(), paramVals.end());\n\n\t//Compute mean and std\n\tdouble validVoxels = (double)stats_.validVoxels_;\n\tstats_.mean_ = ROI_sum / validVoxels;\n\n\t// This is the unbiased estimator for the sd of the parent distribution ... i.e. strong gaussian assumption\n\tstats_.stddev_ = sqrt((ROI_sumsq - ROI_sum * ROI_sum /\n\t\tvalidVoxels) / (validVoxels - 1));\n\n\t//Compute median and IQR\n\tstats_.median_ = percentile(paramVals, 50);\n\tstats_.lowerQ_ = percentile(paramVals, 25);\n\tstats_.upperQ_ = percentile(paramVals, 75);\n\tstats_.iqr_ = stats_.upperQ_ - stats_.lowerQ_;\n}\n\nMDM_API const mdm_ParamSummaryStats::SummaryStats& mdm_ParamSummaryStats::stats() const\n{\n\treturn stats_;\n}\n\n//\nMDM_API void mdm_ParamSummaryStats::writeROISummary(const std::string &roiFile)\n{\n\tstd::ofstream roiStream(roiFile);\n\tif (!roiStream)\n\t  throw mdm_exception(__func__, boost::format(\"Failed to open stats file %1%\") % roiFile);\n\t\t\n\n\tdouble nVoxels = (double)roiIdx_.size();\n\troiStream <<\n\t\t\"number_of_voxels = \" << nVoxels <<\n\t\t\" volume = \" << nVoxels * xmm_ * ymm_ * zmm_;\n}\n\n//\nMDM_API void mdm_ParamSummaryStats::openNewStatsFile(const std::string &statsFile)\n{\n\tstatsOStream_.open(statsFile, std::ios::out);\n\tif (!statsOStream_)\n    throw mdm_exception(__func__, boost::format(\"Failed to open stats file %1%\") % statsFile);\n\n\t//Write stats headers\n\tfor (const auto hdr : headers_)\n\t\tstatsOStream_ << hdr << \",\";\n\t\n\tstatsOStream_ << \"\\n\";\n\n}\n\n//\nMDM_API void mdm_ParamSummaryStats::closeNewStatsFile()\n{\n\tif (statsOStream_)\n\t\tstatsOStream_.close();\n\n}\n\n//\nMDM_API void mdm_ParamSummaryStats::writeStats()\n{\n\tif (!statsOStream_.is_open())\n    throw mdm_exception(__func__, \n      \"Tried to write stats, but no stats file open\");\n\n\tstatsOStream_ <<\n\t\tstats_.paramName_ << \",\" <<\n\t\tstats_.validVoxels_ << \",\" <<\n\t\tstats_.invalidVoxels_ << \",\" <<\n\t\tstats_.mean_ << \",\" <<\n\t\tstats_.stddev_ << \",\" <<\n\t\tstats_.median_ << \",\"<<\n\t\tstats_.lowerQ_ << \",\" <<\n\t\tstats_.upperQ_ << \",\" <<\n\t\tstats_.iqr_ << \",\\n\";\n\n}\n\n//\nMDM_API void mdm_ParamSummaryStats::openStatsFile(const std::string &statsFile)\n{\n\tstatsIStream_.open(statsFile, std::ios::in);\n\tif (!statsIStream_)\n    throw mdm_exception(__func__, boost::format(\"Failed to open stats file %1%\") % statsFile);\n\n\t//Write stats headers\n\tstd::string hdr_in;\n\tfor (const auto hdr : headers_)\n\t{\n\t\tstd::getline(statsIStream_, hdr_in, ',');\n\t\tif (hdr_in != hdr)\n      throw mdm_exception(__func__, boost::format(\"Incorrect headers in %1%, cannot open\") % statsFile);\n\t}\n\t//Get rid of final comma to \\n part\n\tstd::getline(statsIStream_, hdr_in);\n}\n\n//\nMDM_API void mdm_ParamSummaryStats::closeStatsFile()\n{\n\tif (statsIStream_)\n\t\tstatsIStream_.close();\n}\n\n//\nMDM_API void mdm_ParamSummaryStats::readStats()\n{\n\tif (!statsIStream_.is_open())\n    throw mdm_exception(__func__,\n      \"Tried to read stats, but no stats file open\");\n\n\tstd::getline(statsIStream_, stats_.paramName_, ',');\n\n\tstd::string val;\n\tstd::getline(statsIStream_, val, ',');\n\tstats_.validVoxels_ = std::stoi(val);\n\n\tstd::getline(statsIStream_, val, ',');\n\tstats_.invalidVoxels_ = std::stoi(val);\n\n\tstd::getline(statsIStream_, val, ',');\n\tstats_.mean_ = std::stod(val);\n\n\tstd::getline(statsIStream_, val, ',');\n\tstats_.stddev_ = std::stod(val);\n\n\tstd::getline(statsIStream_, val, ',');\n\tstats_.median_ = std::stod(val);\n\n\tstd::getline(statsIStream_, val, ',');\n\tstats_.lowerQ_ = std::stod(val);\n\n\tstd::getline(statsIStream_, val, ',');\n\tstats_.upperQ_ = std::stod(val);\n\n\tstd::getline(statsIStream_, val, ',');\n\tstats_.iqr_ = std::stod(val);\n\n\t//Get rid of final comma to \\n part\n\tstd::getline(statsIStream_, val);\n}\n\n//------------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------------\nvoid mdm_ParamSummaryStats::checkIdx(const mdm_Image3D& img)\n{\n\tif (roiIdx_.empty())\n\t{\n\t\tfor (int i = 0; i < img.numVoxels(); i++)\n\t\t\troiIdx_.push_back(i);\n\t}\n\n\txmm_ = img.info().Xmm.value();\n\tymm_ = img.info().Ymm.value();\n\tzmm_ = img.info().Zmm.value();\n}\n", "meta": {"hexsha": "22420ae8c3b295e76ee913278bd84941c56b8981", "size": 7409, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "madym/mdm_ParamSummaryStats.cxx", "max_stars_repo_name": "michaelberks/madym_cxx", "max_stars_repo_head_hexsha": "647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T15:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T15:43:15.000Z", "max_issues_repo_path": "madym/mdm_ParamSummaryStats.cxx", "max_issues_repo_name": "michaelberks/madym_cxx", "max_issues_repo_head_hexsha": "647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16", "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": "madym/mdm_ParamSummaryStats.cxx", "max_forks_repo_name": "michaelberks/madym_cxx", "max_forks_repo_head_hexsha": "647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16", "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.0809968847, "max_line_length": 108, "alphanum_fraction": 0.661762721, "num_tokens": 2263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5428053117703849}}
{"text": "\n// MIT License\n//\n// Copyright (c) 2019 degski\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 <cmath>\n#include <vector>\n\n#include <boost/container/deque.hpp>\n\n#include <SFML/Graphics.hpp>\n#include \"Extensions.hpp\"\n\n\nnamespace sf::CatmullRom {\n\n    using Points = boost::container::deque<Point>;\n    using CoordinatesVector = std::vector<Point>;\n\n    template<typename Container>\n    float length ( const Container &v_ ) noexcept {\n\n        Vector2f d;\n        float return_value = 0.0f;\n\n        for ( std::size_t i = 1, l = v_.size ( ); i < l; ++i ) {\n\n            d = v_ [ i ] - v_ [ i - 1 ];\n\n            return_value += std::sqrtf ( d.x * d.x + d.y * d.y );\n        }\n\n        return return_value;\n    }\n\n    // CoordinatesVector catmullRom0 ( const Points &points_, const int number_of_points_per_interval_ );\n\n    // Calculate Catmull Rom for a chain of points and return the combined curve. The\n    // chains' first and last point are extrapolated from the second and 1-before-\n    // last point, respectively...\n    CoordinatesVector catmullRom ( const Points & points_, const Int32 number_of_points_per_interval_ ) noexcept;\n\n    // Calculate Catmull Rom for a chain of points and return the combined curve. The\n    // chains' first and last point are extrapolated from the second and 1-before-\n    // last point, respectively. The returned points are at a distance of distance_\n    // (at least) away from each other... \tRequires 3 points or more...\n    CoordinatesVector catmullRom ( const Points & points_, float distance_ ) noexcept;\n}\n", "meta": {"hexsha": "fee9932f416ba80c39bbbffeae0e823c90bb62a4", "size": 2602, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sfml-extensions/Extensions/CatmullRom.hpp", "max_stars_repo_name": "degski/SFML-Extensions", "max_stars_repo_head_hexsha": "13236325da2e9bef2e24f7ad80ec78db6bf33879", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sfml-extensions/Extensions/CatmullRom.hpp", "max_issues_repo_name": "degski/SFML-Extensions", "max_issues_repo_head_hexsha": "13236325da2e9bef2e24f7ad80ec78db6bf33879", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sfml-extensions/Extensions/CatmullRom.hpp", "max_forks_repo_name": "degski/SFML-Extensions", "max_forks_repo_head_hexsha": "13236325da2e9bef2e24f7ad80ec78db6bf33879", "max_forks_repo_licenses": ["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.7101449275, "max_line_length": 113, "alphanum_fraction": 0.7086856264, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5428053117703849}}
{"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_ACOTD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACOTD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing acotd capabilities\n\n    inverse cotangent in degree.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = acotd(x);\n    @endcode\n\n    Returns the arc @c r in the interval\n    \\f$[0, 180[\\f$ such that <tt>cotd(r) == x</tt>.\n\n    @see acot, acotpi, cotd\n\n  **/\n  Value acotd(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acotd.hpp>\n#include <boost/simd/function/simd/acotd.hpp>\n\n#endif\n", "meta": {"hexsha": "bd7058ad2c995234cb4b95f29064491103d99919", "size": 1060, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acotd.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/acotd.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/acotd.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": 22.5531914894, "max_line_length": 100, "alphanum_fraction": 0.570754717, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5427900346421818}}
{"text": "/**\n * @date Tue Jan 10 21:14 2016 +0100\n * @author Tiago de Freitas Pereira <tiago.pereira@idiap.ch>\n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <stdexcept>\n#include <boost/shared_array.hpp>\n\n#include <bob.math/gsvd.h>\n\n#include <bob.core/assert.h>\n#include <bob.core/check.h>\n#include <bob.core/array_copy.h>\n#include <bob.math/linear.h>\n\n\n// Declaration of the external LAPACK function (Divide and conquer SVD)\nextern \"C\" void dggsvd3_(const char *jobu,\n                         const char *jobv, \n                         const char *jobq,\n                         const int *M,\n                         const int *N,\n                         const int *P,\n                         const int *K,\n                         const int *L,\n                         double *A, \n                         const int *lda, \n                         double *B, \n                         const int *ldb,\n                         double *alpha,\n                         double *beta,\n                         double *U,\n                         const int *ldu, \n                         double *V,\n                         const int *ldv, \n                         double *Q,\n                         const int *ldq, \n                         double *work,\n                         const int *lwork,\n                         int *iwork,\n                         int *info);\n\n\nvoid bob::math::gsvd( blitz::Array<double,2>& A,\n                      blitz::Array<double,2>& B,\n                      blitz::Array<double,2>& U,\n                      blitz::Array<double,2>& V,\n                      blitz::Array<double,2>& zeroR,\n                      blitz::Array<double,2>& Q,\n                      blitz::Array<double,2>& X,\n                      blitz::Array<double,2>& C,\n                      blitz::Array<double,2>& S)\n{\n  const char jobu = 'U';\n  const char jobv = 'V';\n  const char jobq = 'Q';\n\n  // Size variables\n  const int M = A.extent(0);\n  const int N = A.extent(1);\n  const int P = B.extent(0);\n  \n  const int lda = std::max(1,M);\n  const int ldb = std::max(1,P);\n  const int ldu = std::max(1,M);\n  const int ldv = std::max(1,P);\n  const int ldq = std::max(1,N);\n  \n  int K = 0; //out\n  int L = 0; //out  \n  \n  // Prepares to call LAPACK function:\n  // We will decompose A^T rather than A and B^T rather than B to reduce the required number of copy\n  // We recall that FORTRAN/LAPACK is column-major order whereas blitz arrays\n  // are row-major order by default.\n\n  //A_lapack = A^T\n  blitz::Array<double,2> A_blitz_lapack(bob::core::array::ccopy(const_cast<blitz::Array<double,2>&>(A).transpose(1,0)));\n  double* A_lapack = A_blitz_lapack.data();\n\n\n  //B_lapack = B^T\n  blitz::Array<double,2> B_blitz_lapack(bob::core::array::ccopy(const_cast<blitz::Array<double,2>&>(B).transpose(1,0)));\n  double* B_lapack = B_blitz_lapack.data();\n  \n  \n  // U. We will trainpose this one in the end\n  double *U_lapack = U.data();\n\n  // V. We will trainpose this one in the end\n  double *V_lapack = V.data();\n\n  // For Q, we will return the transpose  \n  double *Q_lapack = Q.data();\n\n  // In LAPACK C and S is 1-d. Our code makes it diagonal\n  blitz::Array<double,1> C_1d(N); C_1d = 0;\n  double *C_lapack = C_1d.data();\n  \n  blitz::Array<double,1> S_1d(N); S_1d = 0;\n  double *S_lapack = S_1d.data();\n\n  const int lwork_query = -1;\n  double work_query;\n\n  boost::shared_array<int> iwork(new int[N]);\n\n  int info = 0;\n  // A/ Queries the optimal size of the working array\n  \n  dggsvd3_(&jobu,\n          &jobv, \n          &jobq,\n          &M,\n          &N,\n          &P,\n          &K,\n          &L,\n          A_lapack, \n          &lda, \n          B_lapack, \n          &ldb,\n          C_lapack,\n          S_lapack,\n          U_lapack,\n          &ldu, \n          V_lapack,\n          &ldv, \n          Q_lapack,\n          &ldq, \n          &work_query,\n          &lwork_query,\n          iwork.get(),\n          &info);\n          \n  if (info != 0)\n    throw std::runtime_error(\"The LAPACK dggsvd3 function returned a non-zero value during the checking\");\n\n  // B/ Computes\n  \n  const int lwork = static_cast<int>(work_query);\n  boost::shared_array<double> work(new double[lwork]);\n  \n  dggsvd3_(&jobu,\n            &jobv, \n           &jobq,\n           &M,\n           &N,\n           &P,\n           &K,\n           &L,\n           A_lapack, \n           &lda, \n           B_lapack, \n           &ldb,\n           C_lapack,\n           S_lapack,\n           U_lapack,\n           &ldu, \n           V_lapack,\n           &ldv, \n           Q_lapack,\n           &ldq, \n           work.get(),\n           &lwork,\n           iwork.get(),\n           &info);\n  if (info != 0)\n    throw std::runtime_error(\"The LAPACK dggsvd3 function returned a non-zero value during the computation.\");\n  \n\n  /* \n  According to the website http://www.netlib.org/lapack/explore-html/d1/d7e/group__double_g_esing_ga4a187519e5c71da3b3f67c85e9baf0f2.html#ga4a187519e5c71da3b3f67c85e9baf0f2\n  \n  if (M-K-L >= 0)\n                      N-K-L  K    L\n        ( 0 R ) = K (  0   R11  R12 )\n                  L (  0    0   R22 )\n                  \n                  \n        Where R11, R12, R22, = A(1:K+L,N-K-L+1:N)\n  \n   else\n   \n                        N-K-L  K   M-K  K+L-M\n       ( 0 R ) =     K ( 0    R11  R12  R13  )\n                   M-K ( 0     0   R22  R23  )\n                 K+L-M ( 0     0    0   R33  )\n\n\n       where R11, R12, R13, R22, R23 = A(1:M, N-K-L+1:N)\n       where R33 = B(M-K+1:L,N+M-K-L+1:N)\n\n  */\n  int r = K + L; //Dimension of R\n  C.resize(M, r);\n  S.resize(P, r);\n  S = 0;\n  C = 0;\n  zeroR.resize(r, N);\n  zeroR = 0;\n  X.resize(r,N);\n  if (M-K-L >= 0){\n\n    //1. First we need the [0 R], which has the shape (N-K-L + K + L, K+L)    \n    zeroR(blitz::Range(0, r-1), blitz::Range(N-r, N-1)) = A_blitz_lapack.transpose(1,0)(blitz::Range(0,r-1), blitz::Range(N-r,N-1));\n    // 2. Now we have to deal with C and S according to http://www.netlib.org/lapack/lug/node36.html\n    //    In the end C is m-by-r and is p-by-r, both are real, nonnegative and diagonal and C'C + S'S = I ,\n    //    They have the following structure \n    //    COPY AND PASTE\n\n    //2.1 Preparing C\n    //           K  L\n    //   C = K ( I  0 )\n    //       L ( 0  C )\n    //   M-K-L ( 0  0 )\n    \n    // A - Identity part\n    if (K>0){\n      blitz::Array<double,2> I (K,K); I= 0;\n      bob::math::eye_(I);\n      C(blitz::Range(0, K-1), blitz::Range(0, K-1)) = I;\n    }\n    // B - diag(C) part. Here the C is LxL\n    // Swaping\n    \n    bob::math::swap_(C_1d, iwork.get(), K, std::min(M,r));\n    blitz::Array<double,2> C_diag (L,L); C_diag = 0;\n    bob::math::diag(C_1d(blitz::Range(K,K+L-1)), C_diag);\n    C(blitz::Range(K, M-1), blitz::Range(K, K+L-1)) = C_diag;\n\n    //2.2 Preparing S\n    //           K  L\n    //D2 =   L ( 0  S )\n    //     P-L ( 0  0 )\n\n    // A - diag(S) part\n    // Swap\n    bob::math::swap_(S_1d, iwork.get(), K, std::min(M,r));\n    blitz::Array<double,2> S_diag (L,L); S_diag = 0;\n    bob::math::diag(S_1d(blitz::Range(K,K+L-1)), S_diag);\n    S(blitz::Range(0, L-1), blitz::Range(K, K+L-1)) = S_diag;\n\n  }\n  else{\n\n    //1. First we need the [0 R], which has the shape (N-K-L  K   M-K  K+L-M  ,  k + M-K  K+L-M  )\n\n    //A. First part of R is in A(1:M, N-K-L+1:N) \n    zeroR(blitz::Range(0,M-1), blitz::Range(N-K-L, N-1)) = A_blitz_lapack.transpose(1,0)(blitz::Range(0,M-1) , blitz::Range(N-K-L,N-1));\n\n    //B. Second part of R is in B(M-K+1:L,N+M-K-L+1:N)\n    zeroR(blitz::Range(M, r - 1), blitz::Range(N-L+M-K,N-1)) = B_blitz_lapack.transpose(1,0)(blitz::Range(M-K, L-1) , blitz::Range(N+M-K-L, N-1));\n\n    //2. Now we have to deal with C and S according to http://www.netlib.org/lapack/lug/node36.html\n    //    In the end C is m-by-r and is p-by-r, both are real, nonnegative and diagonal and C'C + S'S = I ,\n    //    They have the following structure \n    //    COPY AND PASTE\n\n    //2.1 Preparing C, where C=diag( ALPHA(K+1), ... , ALPHA(M) ),\n    //             K M-K K+L-M\n    //  D1 =   K ( I  0    0   )\n    //       M-K ( 0  C    0   )\n\n    // A - Identity part\n    if (K>0){\n      blitz::Array<double,2> I (K,K); I = 0;\n      bob::math::eye_(I);\n      C(blitz::Range(0, K-1), blitz::Range(0, K-1)) = I;\n    }\n\n    // B - diag(C) part\n    // Swaping\n    blitz::Array<double,1> C_1d_cropped(M-K); C_1d_cropped = 0;\n    C_1d_cropped = C_1d(blitz::Range(K,K+M-1));\n    bob::math::swap_(C_1d_cropped, iwork.get(), K, std::min(M,r));\n    blitz::Array<double,2> C_diag (M,M); C_diag = 0;\n    bob::math::diag(C_1d_cropped, C_diag);\n    C(blitz::Range(K,M-1), blitz::Range(K,M-1)) = C_diag;\n\n\n    //2.2 Preparing S\n    //               K M-K K+L-M\n    //  D2 =   M-K ( 0  S    0  )\n    //       K+L-M ( 0  0    I  )\n    //         P-L ( 0  0    0  )\n\n    // A - Identity part\n    if (K+L-M>0){\n      blitz::Array<double,2> I (K+L-M,K+L-M); I= 0;\n      bob::math::eye_(I);\n      S(blitz::Range(M-K,L-1), blitz::Range(M,K+L-1)) = I;\n    }\n\n    // B - diag(S) part\n    // Swaping\n    blitz::Array<double,1> S_1d_cropped(M-K); S_1d_cropped = 0;\n    S_1d_cropped = S_1d(blitz::Range(K,K+M-1));\n    \n    bob::math::swap_(S_1d_cropped, iwork.get(), K, std::min(M,r));\n    blitz::Array<double,2> S_diag (M,M); S_diag = 0;\n    bob::math::diag(S_1d_cropped, S_diag);\n    S(blitz::Range(0,M-K-1), blitz::Range(K,M-1)) = S_diag;\n  }\n\n  // Transposing U and V\n  blitz::Array<double,2> Ut(\n    bob::core::array::ccopy(const_cast<blitz::Array<double,2>&>(U).transpose(1,0)));\n  U = Ut;\n\n  blitz::Array<double,2> Vt(\n    bob::core::array::ccopy(const_cast<blitz::Array<double,2>&>(V).transpose(1,0)));\n  V = Vt;\n\n  // Swaping U\n  bob::math::swap_(U, iwork.get(), K, std::min(M,r));\n  // Swaping V\n  bob::math::swap_(V, iwork.get(), K, std::min(M,r));\n\n  //Computing X\n  bob::math::prod_(zeroR, Q, X);\n  blitz::Array<double,2> Xt(\n    bob::core::array::ccopy(const_cast<blitz::Array<double,2>&>(X).transpose(1,0)));\n  X = Xt;\n  bob::math::swap_(X, iwork.get(), K, std::min(M,r));\n\n} \n", "meta": {"hexsha": "c447f4f33b5f14075d4094954e609432b925c570", "size": 9971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/math/cpp/gsvd.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/gsvd.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/gsvd.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": 30.2151515152, "max_line_length": 172, "alphanum_fraction": 0.5016547989, "num_tokens": 3357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245828938678, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5427900209137313}}
{"text": "/**TODO:  Add copyright*/\n\n#define BOOST_TEST_MODULE ModelInterpreter DCG test suite \n#include <boost/test/included/unit_test.hpp>\n#include <SmartPeak/ml/ModelInterpreterDefaultDevice.h> \n#include <SmartPeak/ml/ModelBuilder.h> // comprehensive architecture tests\n\nusing namespace SmartPeak;\nusing namespace std;\n\nModel<float> makeModelFCSum()\n{\n\t/**\n\t * Directed Cyclic Graph Toy Network Model\n\t*/\n\tNode<float> i1, h1, o1, b1, b2;\n\tLink l1, l2, l3, lb1, lb2;\n\tWeight<float> w1, w2, w3, wb1, wb2;\n\tModel<float> model2;\n\t// Toy network: 1 hidden layer, fully connected, DCG\n\ti1 = Node<float>(\"0\", NodeType::input, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\th1 = Node<float>(\"1\", NodeType::hidden, NodeStatus::initialized, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\to1 = Node<float>(\"2\", NodeType::output, NodeStatus::initialized, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\tb1 = Node<float>(\"3\", NodeType::bias, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\tb2 = Node<float>(\"4\", NodeType::bias, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\t// weights  \n\tstd::shared_ptr<WeightInitOp<float>> weight_init;\n\tstd::shared_ptr<SolverOp<float>> solver;\n\t// weight_init.reset(new RandWeightInitOp(1.0)); // No random init for testing\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw1 = Weight<float>(\"0\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw2 = Weight<float>(\"1\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw3 = Weight<float>(\"2\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\twb1 = Weight<float>(\"3\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\twb2 = Weight<float>(\"4\", weight_init, solver);\n\tweight_init.reset();\n\tsolver.reset();\n\t// links\n\tl1 = Link(\"0\", \"0\", \"1\", \"0\");\n\tl2 = Link(\"1\", \"1\", \"2\", \"1\");\n\tl3 = Link(\"2\", \"1\", \"1\", \"2\"); // cycle\n\tlb1 = Link(\"3\", \"3\", \"1\", \"3\");\n\tlb2 = Link(\"4\", \"4\", \"2\", \"4\");\n\tmodel2.setId(2);\n\tmodel2.addNodes({ i1, h1, o1, b1, b2 });\n\tmodel2.addWeights({ w1, w2, w3, wb1, wb2 });\n\tmodel2.addLinks({ l1, l2, l3, lb1, lb2 });\n\tmodel2.findCycles();\n\treturn model2;\n}\n\nBOOST_AUTO_TEST_SUITE(modelInterpreter_DCG)\n\nBOOST_AUTO_TEST_CASE(constructor)\n{\n\tModelInterpreterDefaultDevice<float>* ptr = nullptr;\n\tModelInterpreterDefaultDevice<float>* nullPointer = nullptr;\n\tptr = new ModelInterpreterDefaultDevice<float>();\n\tBOOST_CHECK_NE(ptr, nullPointer);\n}\n\nBOOST_AUTO_TEST_CASE(destructor)\n{\n\tModelInterpreterDefaultDevice<float>* ptr = nullptr;\n\tptr = new ModelInterpreterDefaultDevice<float>();\n\tdelete ptr;\n}\n\n/**\n * Part 2 test suit for the ModelInterpreter class\n * \n * The following test methods that are\n * required of a standard recurrent neural network\n*/\n\nModel<float> model_getNextInactiveLayer = makeModelFCSum();\nBOOST_AUTO_TEST_CASE(getNextInactiveLayerWOBiases) \n{\n  // Toy network: 1 hidden layer, fully connected, DAG\n\tModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // initialize nodes\n\t// NOTE: input and biases have been activated when the model was created\n\n\t// get the next hidden layer\n\tstd::map<std::string, int> FP_operations_map;\n\tstd::vector<OperationList<float>> FP_operations_list;\n\tmodel_interpreter.getNextInactiveLayerWOBiases(model_getNextInactiveLayer, FP_operations_map, FP_operations_list);\n\n\tBOOST_CHECK_EQUAL(FP_operations_map.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_map.at(\"1\"), 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].result.time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].result.sink_node->getName(), \"1\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].source_node->getName(), \"0\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].weight->getName(), \"0\");\n}\n\nModel<float> model_getNextInactiveLayerBiases = makeModelFCSum();\nBOOST_AUTO_TEST_CASE(getNextInactiveLayerBiases) \n{\n  // Toy network: 1 hidden layer, fully connected, DAG\n  // Model<float> model_FC_Sum = makeModelFCSum();\n\tModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // initialize nodes\n\t// NOTE: input and biases have been activated when the model was created\n\n\t// get the next hidden layer\n\tstd::map<std::string, int> FP_operations_map;\n\tstd::vector<OperationList<float>> FP_operations_list;\n\tmodel_interpreter.getNextInactiveLayerWOBiases(model_getNextInactiveLayerBiases, FP_operations_map, FP_operations_list);\n\n\tstd::vector<std::string> sink_nodes_with_biases2;\n\tmodel_interpreter.getNextInactiveLayerBiases(model_getNextInactiveLayerBiases, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n\tBOOST_CHECK_EQUAL(FP_operations_map.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_map.at(\"1\"), 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].result.time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].result.sink_node->getName(), \"1\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments.size(), 2);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].source_node->getName(), \"0\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].weight->getName(), \"0\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].source_node->getName(), \"3\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].weight->getName(), \"3\");\n\tBOOST_CHECK_EQUAL(sink_nodes_with_biases2.size(), 1);\n\tBOOST_CHECK_EQUAL(sink_nodes_with_biases2[0], \"1\");\n}\n\nModel<float> model_getNextInactiveLayerCycles = makeModelFCSum();\nBOOST_AUTO_TEST_CASE(getNextInactiveLayerCycles)\n{\n\t// Toy network: 1 hidden layer, fully connected, DAG\n\t// Model<float> model_FC_Sum = makeModelFCSum();\n\tModelInterpreterDefaultDevice<float> model_interpreter;\n\n\t// initialize nodes\n\t// NOTE: input and biases have been activated when the model was created\n\n\t// get the next hidden layer\n\tstd::map<std::string, int> FP_operations_map;\n\tstd::vector<OperationList<float>> FP_operations_list;\n\tmodel_interpreter.getNextInactiveLayerWOBiases(model_getNextInactiveLayerCycles, FP_operations_map, FP_operations_list);\n\n\tstd::vector<std::string> sink_nodes_with_biases2;\n\tmodel_interpreter.getNextInactiveLayerBiases(model_getNextInactiveLayerCycles, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n\tstd::set<std::string> sink_nodes_with_cycles;\n\tmodel_interpreter.getNextInactiveLayerCycles(model_getNextInactiveLayerCycles, FP_operations_map, FP_operations_list, sink_nodes_with_cycles);\n\n\tBOOST_CHECK_EQUAL(FP_operations_map.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_map.at(\"1\"), 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].result.time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].result.sink_node->getName(), \"1\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments.size(), 3);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].source_node->getName(), \"0\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].weight->getName(), \"0\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].source_node->getName(), \"3\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].weight->getName(), \"3\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].time_step, 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].source_node->getName(), \"1\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].weight->getName(), \"2\");\n\tBOOST_CHECK_EQUAL(sink_nodes_with_cycles.size(), 1);\n  BOOST_CHECK_EQUAL(sink_nodes_with_cycles.count(\"1\"), 1);\n}\n\nModel<float> model_pruneInactiveLayerCycles = makeModelFCSum();\nBOOST_AUTO_TEST_CASE(pruneInactiveLayerCycles)\n{\n\t// Toy network: 1 hidden layer, fully connected, DAG\n\t// Model<float> model_FC_Sum = makeModelFCSum();\n\tModelInterpreterDefaultDevice<float> model_interpreter;\n\n\t// initialize nodes\n\t// NOTE: input and biases have been activated when the model was created\n\n\t// get the next hidden layer\n\tstd::map<std::string, int> FP_operations_map;\n\tstd::vector<OperationList<float>> FP_operations_list;\n\tmodel_interpreter.getNextInactiveLayerWOBiases(model_pruneInactiveLayerCycles, FP_operations_map, FP_operations_list);\n\n\tstd::vector<std::string> sink_nodes_with_biases2;\n\tmodel_interpreter.getNextInactiveLayerBiases(model_pruneInactiveLayerCycles, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n\tstd::set<std::string> sink_nodes_with_cycles;\n\tstd::map<std::string, int> FP_operations_map_cycles = FP_operations_map;\n\tstd::vector<OperationList<float>> FP_operations_list_cycles = FP_operations_list;\n\tmodel_interpreter.getNextInactiveLayerCycles(model_pruneInactiveLayerCycles, FP_operations_map_cycles, FP_operations_list_cycles, sink_nodes_with_cycles);\n\n\tmodel_interpreter.pruneInactiveLayerCycles(model_pruneInactiveLayerCycles, FP_operations_map, FP_operations_map_cycles, FP_operations_list, FP_operations_list_cycles, sink_nodes_with_cycles);\n\n\tBOOST_CHECK_EQUAL(FP_operations_map.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_map.at(\"1\"), 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].result.time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].result.sink_node->getName(), \"1\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments.size(), 3);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].source_node->getName(), \"0\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].weight->getName(), \"0\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].source_node->getName(), \"3\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].weight->getName(), \"3\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].time_step, 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].source_node->getName(), \"1\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].weight->getName(), \"2\");\n\tBOOST_CHECK_EQUAL(sink_nodes_with_cycles.size(), 1);\n  BOOST_CHECK_EQUAL(sink_nodes_with_cycles.count(\"1\"), 1);\n}\n\nModel<float> model_expandAllForwardPropogationOperations = makeModelFCSum();\nBOOST_AUTO_TEST_CASE(expandAllForwardPropogationOperations)\n{\n\tModelInterpreterDefaultDevice<float> model_interpreter;\n\n\t// initialize nodes\n\t// NOTE: input and biases have been activated when the model was created\n\n\tstd::map<std::string, int> FP_operations_map;\n\tstd::vector<OperationList<float>> FP_operations_list;\n\tmodel_interpreter.getNextInactiveLayerWOBiases(model_expandAllForwardPropogationOperations, FP_operations_map, FP_operations_list);\n\n\tstd::vector<std::string> sink_nodes_with_biases2;\n\tmodel_interpreter.getNextInactiveLayerBiases(model_expandAllForwardPropogationOperations, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n\tstd::set<std::string> sink_nodes_with_cycles;\n\tstd::map<std::string, int> FP_operations_map_cycles = FP_operations_map;\n\tstd::vector<OperationList<float>> FP_operations_list_cycles = FP_operations_list;\n\tmodel_interpreter.getNextInactiveLayerCycles(model_expandAllForwardPropogationOperations, FP_operations_map_cycles, FP_operations_list_cycles, sink_nodes_with_cycles);\n\n\tmodel_interpreter.pruneInactiveLayerCycles(model_expandAllForwardPropogationOperations, FP_operations_map, FP_operations_map_cycles, FP_operations_list, FP_operations_list_cycles, sink_nodes_with_cycles);\n\n\tstd::vector<OperationList<float>> FP_operations_expanded;\n\tmodel_interpreter.expandAllForwardPropogationOperations(FP_operations_list, FP_operations_expanded);\n\n\tBOOST_CHECK_EQUAL(FP_operations_expanded.size(), 3);\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[0].result.time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[0].result.sink_node->getName(), \"1\");\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[0].arguments.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[0].arguments[0].time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[0].arguments[0].source_node->getName(), \"0\");\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[0].arguments[0].weight->getName(), \"0\");\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[1].result.time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[1].result.sink_node->getName(), \"1\");\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[1].arguments[0].time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[1].arguments[0].source_node->getName(), \"3\");\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[1].arguments[0].weight->getName(), \"3\");\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[2].result.time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[2].result.sink_node->getName(), \"1\");\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[2].arguments.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[2].arguments[0].time_step, 1);\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[2].arguments[0].source_node->getName(), \"1\");\n\tBOOST_CHECK_EQUAL(FP_operations_expanded[2].arguments[0].weight->getName(), \"2\");\n}\n\nModel<float> model_getTensorOperations = makeModelFCSum();\nBOOST_AUTO_TEST_CASE(getTensorOperations)\n{\n\tModelInterpreterDefaultDevice<float> model_interpreter;\n\n\t// initialize nodes\n\t// NOTE: input and biases have been activated when the model was created\n\n\tstd::map<std::string, int> FP_operations_map;\n\tstd::vector<OperationList<float>> FP_operations_list;\n\tmodel_interpreter.getNextInactiveLayerWOBiases(model_getTensorOperations, FP_operations_map, FP_operations_list);\n\n\tstd::vector<std::string> sink_nodes_with_biases2;\n\tmodel_interpreter.getNextInactiveLayerBiases(model_getTensorOperations, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n\tstd::set<std::string> sink_nodes_with_cycles;\n\tstd::map<std::string, int> FP_operations_map_cycles = FP_operations_map;\n\tstd::vector<OperationList<float>> FP_operations_list_cycles = FP_operations_list;\n\tmodel_interpreter.getNextInactiveLayerCycles(model_getTensorOperations, FP_operations_map_cycles, FP_operations_list_cycles, sink_nodes_with_cycles);\n\n\tmodel_interpreter.pruneInactiveLayerCycles(model_getTensorOperations, FP_operations_map, FP_operations_map_cycles, FP_operations_list, FP_operations_list_cycles, sink_nodes_with_cycles);\n\n\tstd::vector<OperationList<float>> FP_operations_expanded;\n\tmodel_interpreter.expandAllForwardPropogationOperations(FP_operations_list, FP_operations_expanded);\n\n\tstd::set<std::string> identified_sink_nodes;\n\tstd::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n\tBOOST_CHECK_EQUAL(identified_sink_nodes.size(), 3);\n\tBOOST_CHECK_EQUAL(identified_sink_nodes.count(\"1/0\"), 1);\n\tBOOST_CHECK_EQUAL(identified_sink_nodes.count(\"1/1\"), 1);\n  BOOST_CHECK_EQUAL(identified_sink_nodes.count(\"1/2\"), 1);\n\tBOOST_CHECK_EQUAL(tensor_ops.size(), 2);\n\tBOOST_CHECK_EQUAL(tensor_ops.at(\"1/0\")[0], 0);\n  BOOST_CHECK_EQUAL(tensor_ops.at(\"1/0\")[1], 1);\n\tBOOST_CHECK_EQUAL(tensor_ops.at(\"1/2\")[0], 2);\n}\n\nModel<float> model_getForwardPropogationLayerTensorDimensions = makeModelFCSum();\nBOOST_AUTO_TEST_CASE(getForwardPropogationLayerTensorDimensions)\n{\n\tModelInterpreterDefaultDevice<float> model_interpreter;\n\n\t// initialize nodes\n\t// NOTE: input and biases have been activated when the model was created\n\n  // Check iteration one with no source/sink/weight tensors already allocated\n\tstd::map<std::string, int> FP_operations_map;\n\tstd::vector<OperationList<float>> FP_operations_list;\n\tmodel_interpreter.getNextInactiveLayerWOBiases(model_getForwardPropogationLayerTensorDimensions, FP_operations_map, FP_operations_list);\n\n\tstd::vector<std::string> sink_nodes_with_biases2;\n\tmodel_interpreter.getNextInactiveLayerBiases(model_getForwardPropogationLayerTensorDimensions, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n\tstd::set<std::string> sink_nodes_with_cycles;\n\tstd::map<std::string, int> FP_operations_map_cycles = FP_operations_map;\n\tstd::vector<OperationList<float>> FP_operations_list_cycles = FP_operations_list;\n\tmodel_interpreter.getNextInactiveLayerCycles(model_getForwardPropogationLayerTensorDimensions, FP_operations_map_cycles, FP_operations_list_cycles, sink_nodes_with_cycles);\n\n\tmodel_interpreter.pruneInactiveLayerCycles(model_getForwardPropogationLayerTensorDimensions, FP_operations_map, FP_operations_map_cycles, FP_operations_list, FP_operations_list_cycles, sink_nodes_with_cycles);\n\n\tstd::vector<OperationList<float>> FP_operations_expanded;\n\tmodel_interpreter.expandAllForwardPropogationOperations(FP_operations_list, FP_operations_expanded);\n\n\tstd::set<std::string> identified_sink_nodes;\n\tstd::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n  std::map<int, int> max_layer_sizes;\n  std::map<std::string, int> layer_name_pos;\n\tstd::vector<int> source_layer_sizes, sink_layer_sizes;\n\tstd::vector<std::vector<std::pair<int, int>>> weight_indices;\n\tstd::vector<std::map<std::string, std::vector<std::pair<int, int>>>> shared_weight_indices;\n\tstd::vector<std::vector<float>> weight_values;\n\tstd::vector<bool> make_source_tensors, make_sink_tensors, make_weight_tensors;\n  std::vector<int> source_layer_pos, sink_layer_pos;\n  int tensor_layers_cnt = 0;\n  int weight_layers_cnt = 0;\n\tmodel_interpreter.getForwardPropogationLayerTensorDimensions(FP_operations_expanded, tensor_ops, source_layer_sizes, sink_layer_sizes, weight_indices, shared_weight_indices, weight_values, make_source_tensors, make_sink_tensors, make_weight_tensors,\n    source_layer_pos, sink_layer_pos, max_layer_sizes, layer_name_pos, tensor_layers_cnt, weight_layers_cnt);\n\n\tBOOST_CHECK_EQUAL(source_layer_sizes.size(), 2);\n\tBOOST_CHECK_EQUAL(source_layer_sizes[0], 2);\n\tBOOST_CHECK_EQUAL(source_layer_sizes[1], 1);\n\tBOOST_CHECK_EQUAL(sink_layer_sizes.size(), 2);\n\tBOOST_CHECK_EQUAL(sink_layer_sizes[0], 1);\n\tBOOST_CHECK_EQUAL(sink_layer_sizes[1], 1);\n\n  BOOST_CHECK_EQUAL(source_layer_pos.size(), 2);\n  BOOST_CHECK_EQUAL(source_layer_pos.at(0), 1);\n  BOOST_CHECK_EQUAL(source_layer_pos.at(1), 0);\n  BOOST_CHECK_EQUAL(sink_layer_pos.size(), 2);\n  BOOST_CHECK_EQUAL(sink_layer_pos.at(0), 0);\n  BOOST_CHECK_EQUAL(sink_layer_pos.at(1), 0);\n\n  BOOST_CHECK_EQUAL(max_layer_sizes.size(), 2);\n  BOOST_CHECK_EQUAL(max_layer_sizes.at(0), 0);\n  BOOST_CHECK_EQUAL(max_layer_sizes.at(1), 1);\n\n  BOOST_CHECK_EQUAL(layer_name_pos.size(), 0);\n\n\tBOOST_CHECK_EQUAL(weight_indices.size(), 2);\n\tBOOST_CHECK_EQUAL(weight_indices[0].size(), 2);\n\tBOOST_CHECK_EQUAL(weight_indices[1].size(), 1);\n\tstd::vector<std::vector<std::pair<int, int>>> weight_indices_test1 = {\n\t\t{std::make_pair(0,0),std::make_pair(1,0)},\n\t\t{std::make_pair(0,0)}\n\t};\n\tfor (int tensor_iter = 0; tensor_iter < weight_indices_test1.size(); ++tensor_iter) {\n\t\tfor (int i = 0; i < weight_indices_test1[tensor_iter].size(); ++i) {\n\t\t\tBOOST_CHECK_EQUAL(weight_indices[tensor_iter][i].first, weight_indices_test1[tensor_iter][i].first);\n\t\t\tBOOST_CHECK_EQUAL(weight_indices[tensor_iter][i].second, weight_indices_test1[tensor_iter][i].second);\n\t\t}\n\t}\n\n\tBOOST_CHECK_EQUAL(shared_weight_indices.size(), 2);\n\tBOOST_CHECK_EQUAL(shared_weight_indices[0].size(), 0);\n\tBOOST_CHECK_EQUAL(shared_weight_indices[1].size(), 0);\n\n\tBOOST_CHECK_EQUAL(weight_values.size(), 2);\n\tBOOST_CHECK_EQUAL(weight_values[0].size(), 2);\n\tBOOST_CHECK_EQUAL(weight_values[1].size(), 1);\n\tstd::vector<std::vector<float>> weight_values_test1 = { {1, 1}, {1} };\n\tfor (int tensor_iter = 0; tensor_iter < weight_values_test1.size(); ++tensor_iter) {\n\t\tfor (int i = 0; i < weight_values_test1[tensor_iter].size(); ++i) {\n\t\t\tBOOST_CHECK_EQUAL(weight_values[tensor_iter][i], weight_values_test1[tensor_iter][i]);\n\t\t}\n\t}\n\n\tBOOST_CHECK_EQUAL(make_source_tensors.size(), 2);\n\tBOOST_CHECK(make_source_tensors[0]);\n\tBOOST_CHECK(!make_source_tensors[1]);\n\tBOOST_CHECK_EQUAL(make_sink_tensors.size(), 2);\n\tBOOST_CHECK(make_sink_tensors[0]);\n\tBOOST_CHECK(!make_sink_tensors[1]);\n\tBOOST_CHECK_EQUAL(make_weight_tensors.size(), 2);\n\tBOOST_CHECK(make_weight_tensors[0]);\n\tBOOST_CHECK(make_weight_tensors[1]);\n\n\t// Check iteration two\n\tmodel_getForwardPropogationLayerTensorDimensions.getNodesMap().at(\"1\")->setStatus(NodeStatus::activated);\n\tFP_operations_map.clear();\n\tFP_operations_list.clear();\n\tmodel_interpreter.getNextInactiveLayerWOBiases(model_getForwardPropogationLayerTensorDimensions, FP_operations_map, FP_operations_list);\n\n\tsink_nodes_with_biases2.clear();\n\tmodel_interpreter.getNextInactiveLayerBiases(model_getForwardPropogationLayerTensorDimensions, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n\tsink_nodes_with_cycles.clear();\n\tFP_operations_map_cycles = FP_operations_map;\n\tFP_operations_list_cycles = FP_operations_list;\n\tmodel_interpreter.getNextInactiveLayerCycles(model_getForwardPropogationLayerTensorDimensions, FP_operations_map_cycles, FP_operations_list_cycles, sink_nodes_with_cycles);\n\n\tmodel_interpreter.pruneInactiveLayerCycles(model_getForwardPropogationLayerTensorDimensions, FP_operations_map, FP_operations_map_cycles, FP_operations_list, FP_operations_list_cycles, sink_nodes_with_cycles);\n\n\tFP_operations_expanded.clear();\n\tmodel_interpreter.expandAllForwardPropogationOperations(FP_operations_list, FP_operations_expanded);\n\n\tidentified_sink_nodes.clear();\n\ttensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n  max_layer_sizes.clear();\n  layer_name_pos.clear();\n  source_layer_sizes.clear(); sink_layer_sizes.clear();\n  weight_indices.clear();\n  shared_weight_indices.clear();\n  weight_values.clear();\n  make_source_tensors.clear(); make_sink_tensors.clear(); make_weight_tensors.clear();\n  source_layer_pos.clear(); sink_layer_pos.clear();\n  tensor_layers_cnt = 0; weight_layers_cnt = 0;\n  model_interpreter.getForwardPropogationLayerTensorDimensions(FP_operations_expanded, tensor_ops, source_layer_sizes, sink_layer_sizes, weight_indices, shared_weight_indices, weight_values, make_source_tensors, make_sink_tensors, make_weight_tensors,\n    source_layer_pos, sink_layer_pos, max_layer_sizes, layer_name_pos, tensor_layers_cnt, weight_layers_cnt);\n\n\tBOOST_CHECK_EQUAL(source_layer_sizes.size(), 2);\n\tBOOST_CHECK_EQUAL(source_layer_sizes[0], 1);\n\tBOOST_CHECK_EQUAL(source_layer_sizes[1], 1);\n\tBOOST_CHECK_EQUAL(sink_layer_sizes.size(), 2);\n\tBOOST_CHECK_EQUAL(sink_layer_sizes[0], 1);\n\tBOOST_CHECK_EQUAL(sink_layer_sizes[1], 1);\n\n  BOOST_CHECK_EQUAL(source_layer_pos.size(), 2);\n  BOOST_CHECK_EQUAL(source_layer_pos.at(0), 0);\n  BOOST_CHECK_EQUAL(source_layer_pos.at(1), 1);\n  BOOST_CHECK_EQUAL(sink_layer_pos.size(), 2);\n  BOOST_CHECK_EQUAL(sink_layer_pos.at(0), 0);\n  BOOST_CHECK_EQUAL(sink_layer_pos.at(1), 0);\n\n  BOOST_CHECK_EQUAL(max_layer_sizes.size(), 2);\n  BOOST_CHECK_EQUAL(max_layer_sizes.at(0), 0);\n  BOOST_CHECK_EQUAL(max_layer_sizes.at(1), 0);\n\n  BOOST_CHECK_EQUAL(layer_name_pos.size(), 0);\n\n\tBOOST_CHECK_EQUAL(weight_indices.size(), 2);\n\tBOOST_CHECK_EQUAL(weight_indices[0].size(), 1);\n\tBOOST_CHECK_EQUAL(weight_indices[1].size(), 1);\n\tstd::vector<std::vector<std::pair<int,int>>> weight_indices_test2 = { \n\t\t{std::make_pair(0,0)},{std::make_pair(0,0) }\n\t};\n\tfor (int tensor_iter = 0; tensor_iter < weight_indices_test2.size(); ++tensor_iter) {\n\t\tfor (int i = 0; i < weight_indices_test2[tensor_iter].size(); ++i) {\n\t\t\tBOOST_CHECK_EQUAL(weight_indices[tensor_iter][i].first, weight_indices_test2[tensor_iter][i].first);\n\t\t\tBOOST_CHECK_EQUAL(weight_indices[tensor_iter][i].second, weight_indices_test2[tensor_iter][i].second);\n\t\t}\n\t}\n\n\tBOOST_CHECK_EQUAL(shared_weight_indices.size(), 2);\n\tBOOST_CHECK_EQUAL(shared_weight_indices[0].size(), 0);\n\tBOOST_CHECK_EQUAL(shared_weight_indices[1].size(), 0);\n\n\tBOOST_CHECK_EQUAL(weight_values.size(), 2);\n\tBOOST_CHECK_EQUAL(weight_values[0].size(), 1);\n\tBOOST_CHECK_EQUAL(weight_values[1].size(), 1);\n\tstd::vector<std::vector<float>> weight_values_test2 = { {1}, {1} };\n\tfor (int tensor_iter = 0; tensor_iter < weight_values_test2.size(); ++tensor_iter) {\n\t\tfor (int i = 0; i < weight_values_test2[tensor_iter].size(); ++i) {\n\t\t\tBOOST_CHECK_EQUAL(weight_values[tensor_iter][i], weight_values_test2[tensor_iter][i]);\n\t\t}\n\t}\n\n\tBOOST_CHECK_EQUAL(make_source_tensors.size(), 2);\n\tBOOST_CHECK(!make_source_tensors[0]);\n\tBOOST_CHECK(make_source_tensors[1]);\n\tBOOST_CHECK_EQUAL(make_sink_tensors.size(), 2);\n\tBOOST_CHECK(make_sink_tensors[0]);\n\tBOOST_CHECK(!make_sink_tensors[1]);\n\tBOOST_CHECK_EQUAL(make_weight_tensors.size(), 2);\n\tBOOST_CHECK(make_weight_tensors[0]);\n\tBOOST_CHECK(make_weight_tensors[1]);\n}\n\n/*\nThe following test the expected `tensor_ops_steps` and `FP_operations` for more\ncomplicated model structures\n*/\n\ntemplate<typename TensorT>\nvoid makeModelLSTM(Model<TensorT>& model, const int& n_inputs, int n_blocks = 2, int n_cells = 2, bool specify_layers = false)\n{\n  model.setId(0);\n  model.setName(\"LSTM\");\n\n  ModelBuilder<TensorT> model_builder;\n\n  // Add the inputs\n  std::vector<std::string> node_names_input = model_builder.addInputNodes(model, \"Input\", \"Input\", n_inputs, specify_layers);\n\n  // Add the LSTM layer\n  std::vector<std::string> node_names = model_builder.addLSTM(model, \"LSTM\", \"LSTM\", node_names_input, n_blocks, n_cells,\n    std::shared_ptr<ActivationOp<TensorT>>(new ReLUOp<float>()), std::shared_ptr<ActivationOp<TensorT>>(new ReLUGradOp<float>()),\n    std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()), std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()), std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n    //std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>(0.4)), \n    std::shared_ptr<WeightInitOp<TensorT>>(new RangeWeightInitOp<TensorT>(0.0, 1.0)),\n    std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.0005, 0.9, 0.999, 1e-8)),\n    0.0f, 0.0f, true, true, 1, specify_layers);\n\n  // Add a final output layer (Specify the layer name to ensure the output is always on its own tensor!!!)\n  node_names = model_builder.addFullyConnected(model, \"Output\", \"Output\", node_names, 1,\n    std::make_shared<LinearOp<TensorT>>(LinearOp<float>()),\n    std::make_shared<LinearGradOp<TensorT>>(LinearGradOp<float>()),\n    std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n    std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n    std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n    std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>(node_names.size(), 2)),\n    std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0f, 0.0f, true, true);\n\n  for (const std::string& node_name : node_names)\n    model.getNodesMap().at(node_name)->setType(NodeType::output);\n\n  if (!model.checkCompleteInputToOutput())\n    std::cout << \"Model input and output are not fully connected!\" << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(makeModelLSTM1)\n{\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model_test;\n  model_test.findCycles();\n  makeModelLSTM(model_test, 2, 1, 2, true);\n\n  int iter_test = 0;\n  std::vector<OperationList<float>> FP_operations_expanded_test;\n  model_interpreter.getFPOpsOoO_(model_test, FP_operations_expanded_test, iter_test);\n\n  std::set<std::string> identified_sink_nodes_test;\n  std::map<std::string, std::vector<int>> tensor_ops_test = model_interpreter.getTensorOperations(FP_operations_expanded_test, identified_sink_nodes_test, true);\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model;\n  model.findCycles();\n  makeModelLSTM(model, 2, 1, 2, false);\n\n  int iter = 0;\n  std::vector<OperationList<float>> FP_operations_expanded;\n  model_interpreter.getFPOpsOoO_(model, FP_operations_expanded, iter);\n\n  std::set<std::string> identified_sink_nodes;\n  std::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n  BOOST_CHECK_EQUAL(iter_test, iter);\n  BOOST_CHECK(tensor_ops_test == tensor_ops);\n  BOOST_CHECK(identified_sink_nodes_test == identified_sink_nodes);\n  BOOST_CHECK_EQUAL(FP_operations_expanded_test.size(), FP_operations_expanded.size());\n  if (tensor_ops_test == tensor_ops && identified_sink_nodes_test == identified_sink_nodes && FP_operations_expanded_test.size() == FP_operations_expanded.size()) {\n    for (int i = 0; i < FP_operations_expanded_test.size(); ++i) {\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.sink_node->getName(), FP_operations_expanded[i].result.sink_node->getName());\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.time_step, FP_operations_expanded[i].result.time_step);\n      for (int j = 0; j < FP_operations_expanded_test[i].arguments.size(); ++j) {\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].source_node->getName(), FP_operations_expanded[i].arguments[j].source_node->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].weight->getName(), FP_operations_expanded[i].arguments[j].weight->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].time_step, FP_operations_expanded[i].arguments[j].time_step);\n      }\n    }\n  }\n}\nBOOST_AUTO_TEST_CASE(makeModelLSTM2)\n{\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model_test;\n  model_test.findCycles();\n  makeModelLSTM(model_test, 2, 4, 2, true);\n\n  int iter_test = 0;\n  std::vector<OperationList<float>> FP_operations_expanded_test;\n  model_interpreter.getFPOpsOoO_(model_test, FP_operations_expanded_test, iter_test);\n\n  std::set<std::string> identified_sink_nodes_test;\n  std::map<std::string, std::vector<int>> tensor_ops_test = model_interpreter.getTensorOperations(FP_operations_expanded_test, identified_sink_nodes_test, true);\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model;\n  model.findCycles();\n  makeModelLSTM(model, 2, 4, 2, false);\n\n  int iter = 0;\n  std::vector<OperationList<float>> FP_operations_expanded;\n  model_interpreter.getFPOpsOoO_(model, FP_operations_expanded, iter);\n\n  std::set<std::string> identified_sink_nodes;\n  std::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n  BOOST_CHECK_EQUAL(iter_test, iter);\n  BOOST_CHECK(tensor_ops_test == tensor_ops);\n  BOOST_CHECK(identified_sink_nodes_test == identified_sink_nodes);\n  BOOST_CHECK_EQUAL(FP_operations_expanded_test.size(), FP_operations_expanded.size());\n  if (tensor_ops_test == tensor_ops && identified_sink_nodes_test == identified_sink_nodes && FP_operations_expanded_test.size() == FP_operations_expanded.size()) {\n    for (int i = 0; i < FP_operations_expanded_test.size(); ++i) {\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.sink_node->getName(), FP_operations_expanded[i].result.sink_node->getName());\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.time_step, FP_operations_expanded[i].result.time_step);\n      for (int j = 0; j < FP_operations_expanded_test[i].arguments.size(); ++j) {\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].source_node->getName(), FP_operations_expanded[i].arguments[j].source_node->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].weight->getName(), FP_operations_expanded[i].arguments[j].weight->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].time_step, FP_operations_expanded[i].arguments[j].time_step);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "740b57c13c063e4d60c291303b1d66abf7bca0f0", "size": 33791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/class_tests/smartpeak/source/ModelInterpreter_DCG_test.cpp", "max_stars_repo_name": "dmccloskey/EvoNet", "max_stars_repo_head_hexsha": "8d7fafe1069593024e5b63fd6b81a341a3bf33b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-28T11:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T11:38:13.000Z", "max_issues_repo_path": "src/tests/class_tests/smartpeak/source/ModelInterpreter_DCG_test.cpp", "max_issues_repo_name": "dmccloskey/EvoNet", "max_issues_repo_head_hexsha": "8d7fafe1069593024e5b63fd6b81a341a3bf33b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2018-10-03T11:35:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-14T09:17:07.000Z", "max_forks_repo_path": "src/tests/class_tests/smartpeak/source/ModelInterpreter_DCG_test.cpp", "max_forks_repo_name": "dmccloskey/EvoNet", "max_forks_repo_head_hexsha": "8d7fafe1069593024e5b63fd6b81a341a3bf33b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.2981072555, "max_line_length": 353, "alphanum_fraction": 0.7905063478, "num_tokens": 8560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5427900182175226}}
{"text": "/**\n * \\file ToneStackFilter.hxx\n */\n\n#include <boost/math/tools/polynomial.hpp>\n\n#include <ATK/EQ/ToneStackFilter.h>\n\nnamespace ATK\n{\n  template<typename DataType>\n  ToneStackCoefficients<DataType>::ToneStackCoefficients(gsl::index nb_channels)\n  :TypedBaseFilter<DataType>(nb_channels, nb_channels)\n  {\n  }\n  \n  template<typename DataType>\n  ToneStackCoefficients<DataType>::ToneStackCoefficients(ToneStackCoefficients&& other)\n  :Parent(std::move(other)), R1(other.R1), R2(other.R2), R3(other.R3), R4(other.R4), C1(other.C1), C2(other.C2), C3(other.C3), low(other.low), middle(other.middle), high(other.high)\n  {\n    \n  }\n\n  template<typename DataType>\n  void ToneStackCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n\n    CoeffDataType tempm[2] = {static_cast<CoeffDataType>(-2) * input_sampling_rate, static_cast<CoeffDataType>(2) * input_sampling_rate};\n    CoeffDataType tempp[2] = {static_cast<CoeffDataType>(1), static_cast<CoeffDataType>(1)};\n    boost::math::tools::polynomial<CoeffDataType> poly1(tempm, 1);\n    boost::math::tools::polynomial<CoeffDataType> poly2(tempp, 1);\n\n    boost::math::tools::polynomial<CoeffDataType> b;\n    boost::math::tools::polynomial<CoeffDataType> a;\n    \n    b = poly2 * poly2 * poly1 * (high*C1*R1 + middle*C3*R3 + low*(C1*R2 + C2*R2) + (C1*R3 + C2*R3));\n    b += poly2 * poly1 * poly1 * (high*(C1*C2*R1*R4 + C1*C3*R1*R4) - middle*middle*(C1*C3*R3*R3 + C2*C3*R3*R3) + middle*(C1*C3*R1*R3 + C1*C3*R3*R3 + C2*C3*R3*R3)\n      + low*(C1*C2*R1*R2 + C1*C2*R2*R4 + C1*C3*R2*R4) + low*middle*(C1*C3*R2*R3 + C2*C3*R2*R3)\n      + (C1*C2*R1*R3 + C1*C2*R3*R4 + C1*C3*R3*R4));\n    b += poly1 * poly1 * poly1 * (low*middle*(C1*C2*C3*R1*R2*R3 + C1*C2*C3*R2*R3*R4) - middle*middle*(C1*C2*C3*R1*R3*R3 + C1*C2*C3*R3*R3*R4)\n      + middle*(C1*C2*C3*R1*R3*R3 + C1*C2*C3*R3*R3*R4) + high*C1*C2*C3*R1*R3*R4 - high*middle*C1*C2*C3*R1*R3*R4\n      + high*low*C1*C2*C3*R1*R2*R4);\n\n    a = poly2 * poly2 * poly2;\n    a += poly2 * poly2 * poly1 * ((C1*R1 + C1*R3 + C2*R3 + C2*R4 + C3*R4) + middle*C3*R3 + low*(C1*R2 + C2*R2));\n    a += poly2 * poly1 * poly1 * (middle*(C1*C3*R1*R3 - C2*C3*R3*R4 + C1*C3*R3*R3 + C2*C3*R3*R3)\n      + low*middle*(C1*C3*R2*R3 + C2*C3*R2*R3) - middle*middle*(C1*C3*R3*R3 + C2*C3*R3*R3) + low*(C1*C2*R2*R4 + C1*C2*R1*R2 + C1*C3*R2*R4 + C2*C3*R2*R4)\n      + (C1*C2*R1*R4 + C1*C3*R1*R4 + C1*C2*R3*R4 + C1*C2*R1*R3 + C1*C3*R3*R4 + C2*C3*R3*R4));\n    a += poly1 * poly1 * poly1 * (low*middle*(C1*C2*C3*R1*R2*R3 + C1*C2*C3*R2*R3*R4) - middle*middle*(C1*C2*C3*R1*R3*R3 + C1*C2*C3*R3*R3*R4)\n      + middle*(C1*C2*C3*R3*R3*R4 + C1*C2*C3*R1*R3*R3 - C1*C2*C3*R1*R3*R4)\n      + low*C1*C2*C3*R1*R2*R4 + C1*C2*C3*R1*R3*R4);\n\n    for(gsl::index i = 0; i < in_order + 1; ++i)\n    {\n      coefficients_in[i] = b[i] / a[out_order];\n    }\n    for(gsl::index i = 0; i < out_order; ++i)\n    {\n      coefficients_out[i] = -a[i] / a[out_order];\n    }\n  }\n\n  template<typename DataType_>\n  void ToneStackCoefficients<DataType_>::set_low(CoeffDataType low)\n  {\n    if(low < 0 || low > 1)\n    {\n      throw std::out_of_range(\"Low is outside the interval [0,1]\");\n    }\n    this->low = low;\n\n    setup();\n  }\n  \n  template<typename DataType_>\n  typename ToneStackCoefficients<DataType_>::CoeffDataType ToneStackCoefficients<DataType_>::get_low() const\n  {\n    return low;\n  }\n\n  template<typename DataType_>\n  void ToneStackCoefficients<DataType_>::set_middle(CoeffDataType middle)\n  {\n    if(middle < 0 || middle > 1)\n    {\n      throw std::out_of_range(\"Middle is outside the interval [0,1]\");\n    }\n    this->middle = middle;\n\n    setup();\n  }\n\n  template<typename DataType_>\n  typename ToneStackCoefficients<DataType_>::CoeffDataType ToneStackCoefficients<DataType_>::get_middle() const\n  {\n    return middle;\n  }\n\n\n  template<typename DataType_>\n  void ToneStackCoefficients<DataType_>::set_high(CoeffDataType high)\n  {\n    if(high < 0 || high > 1)\n    {\n      throw std::out_of_range(\"high is outside the interval [0,1]\");\n    }\n    this->high = high;\n\n    setup();\n  }\n\n  template<typename DataType_>\n  typename ToneStackCoefficients<DataType_>::CoeffDataType ToneStackCoefficients<DataType_>::get_high() const\n  {\n    return high;\n  }\n\n  template<typename DataType>\n  IIRFilter<ToneStackCoefficients<DataType> > ToneStackCoefficients<DataType>::buildBassmanStack()\n  {\n    IIRFilter<ToneStackCoefficients<DataType> > filter;\n    filter.set_coefficients(static_cast<CoeffDataType>(250e3), static_cast<CoeffDataType>(1e6), static_cast<CoeffDataType>(25e3), static_cast<CoeffDataType>(45e3),\n      static_cast<CoeffDataType>(250e-12), static_cast<CoeffDataType>(20e-9), static_cast<CoeffDataType>(20e-9));\n    return std::move(filter);\n  }\n\n  template<typename DataType>\n  IIRFilter<ToneStackCoefficients<DataType> > ToneStackCoefficients<DataType>::buildJCM800Stack()\n  {\n    IIRFilter<ToneStackCoefficients<DataType> > filter;\n    filter.set_coefficients(static_cast<CoeffDataType>(220e3), static_cast<CoeffDataType>(1e6), static_cast<CoeffDataType>(22e3), static_cast<CoeffDataType>(33e3),\n      static_cast<CoeffDataType>(470e-12), static_cast<CoeffDataType>(22e-9), static_cast<CoeffDataType>(22e-9));\n    return std::move(filter);\n  }\n\n  template<typename DataType_>\n  void ToneStackCoefficients<DataType_>::set_coefficients(CoeffDataType R1, CoeffDataType R2, CoeffDataType R3, CoeffDataType R4, CoeffDataType C1, CoeffDataType C2, CoeffDataType C3)\n  {\n    this->R1 = R1;\n    this->R2 = R2;\n    this->R3 = R3;\n    this->R4 = R4;\n    this->C1 = C1;\n    this->C2 = C2;\n    this->C3 = C3;\n  }\n}\n", "meta": {"hexsha": "f66f6078a1da611eacff9b8de0bd297f55e8a39c", "size": 5623, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "ATK/EQ/ToneStackFilter.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/ToneStackFilter.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/ToneStackFilter.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": 36.9934210526, "max_line_length": 183, "alphanum_fraction": 0.666370265, "num_tokens": 1951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.542770656417805}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    cpp_int x, y, cnt = 1; cin >> x >> y;\n    while(true) {\n        if (x * 2 > y) break;\n        else {\n            cnt++;\n            x *= 2;\n        }\n    }\n    cout << cnt << endl;\n}\n", "meta": {"hexsha": "8a8eed2580678f483889bde351b0870d101b8c5a", "size": 380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/arc088/c/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/arc088/c/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/arc088/c/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": 20.0, "max_line_length": 43, "alphanum_fraction": 0.5421052632, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597974, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5427599751633946}}
{"text": "///////////////////////////////////////////////////////////////\r\n//  Copyright 2012 John Maddock. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\r\n\r\n#define BOOST_CHRONO_HEADER_ONLY\r\n\r\n#if !defined(TEST_MPZ) && !defined(TEST_TOMMATH) && !defined(TEST_CPP_INT)\r\n#  define TEST_MPZ\r\n#  define TEST_TOMMATH\r\n#  define TEST_CPP_INT\r\n#endif\r\n\r\n#ifdef TEST_MPZ\r\n#include <boost/multiprecision/gmp.hpp>\r\n#endif\r\n#ifdef TEST_TOMMATH\r\n#include <boost/multiprecision/tommath.hpp>\r\n#endif\r\n#ifdef TEST_CPP_INT\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#endif\r\n#include <boost/multiprecision/miller_rabin.hpp>\r\n#include <boost/chrono.hpp>\r\n#include <map>\r\n\r\ntemplate <class Clock>\r\nstruct stopwatch\r\n{\r\n   typedef typename Clock::duration duration;\r\n   stopwatch()\r\n   {\r\n      m_start = Clock::now();\r\n   }\r\n   duration elapsed()\r\n   {\r\n      return Clock::now() - m_start;\r\n   }\r\n   void reset()\r\n   {\r\n      m_start = Clock::now();\r\n   }\r\n\r\nprivate:\r\n   typename Clock::time_point m_start;\r\n};\r\n\r\nunsigned allocation_count = 0;\r\n\r\nvoid *(*alloc_func_ptr) (size_t);\r\nvoid *(*realloc_func_ptr) (void *, size_t, size_t);\r\nvoid (*free_func_ptr) (void *, size_t);\r\n\r\nvoid *alloc_func(size_t n)\r\n{\r\n   ++allocation_count;\r\n   return (*alloc_func_ptr)(n);\r\n}\r\n\r\nvoid free_func(void * p, size_t n)\r\n{\r\n   (*free_func_ptr)(p, n);\r\n}\r\n\r\nvoid * realloc_func(void * p, size_t old, size_t n)\r\n{\r\n   ++allocation_count;\r\n   return (*realloc_func_ptr)(p, old, n);\r\n}\r\n\r\n#ifdef TEST_MPZ\r\nboost::chrono::duration<double> test_miller_rabin_gmp()\r\n{\r\n   using namespace boost::random;\r\n   using namespace boost::multiprecision;\r\n\r\n   stopwatch<boost::chrono::high_resolution_clock> c;\r\n\r\n   independent_bits_engine<mt11213b, 256, mpz_int> gen;\r\n\r\n   for(unsigned i = 0; i < 1000; ++i)\r\n   {\r\n      mpz_int n = gen();\r\n      mpz_probab_prime_p(n.backend().data(), 25);\r\n   }\r\n   return c.elapsed();\r\n}\r\n#endif\r\n\r\nstd::map<std::string, double> results;\r\ndouble min_time = (std::numeric_limits<double>::max)();\r\n\r\ntemplate <class IntType>\r\nboost::chrono::duration<double> test_miller_rabin(const char* name)\r\n{\r\n   using namespace boost::random;\r\n\r\n   stopwatch<boost::chrono::high_resolution_clock> c;\r\n\r\n   independent_bits_engine<mt11213b, 256, IntType> gen;\r\n   //\r\n   // We must use a different generator for the tests and number generation, otherwise\r\n   // we get false positives.\r\n   //\r\n   mt19937 gen2;\r\n   unsigned result_count = 0;\r\n\r\n   for(unsigned i = 0; i < 1000; ++i)\r\n   {\r\n      IntType n = gen();\r\n      if(boost::multiprecision::miller_rabin_test(n, 25, gen2))\r\n         ++result_count;\r\n   }\r\n   boost::chrono::duration<double> t = c.elapsed();\r\n   double d = t.count();\r\n   if(d < min_time)\r\n      min_time = d;\r\n   results[name] = d;\r\n   std::cout << \"Time for \" << std::setw(30) << std::left << name << \" = \" << d << std::endl;\r\n   std::cout << \"Number of primes found = \" << result_count << std::endl;\r\n   return t;\r\n}\r\n\r\nvoid generate_quickbook()\r\n{\r\n   std::cout << \"[table\\n[[Integer Type][Relative Performance (Actual time in parenthesis)]]\\n\";\r\n\r\n   std::map<std::string, double>::const_iterator i(results.begin()), j(results.end());\r\n\r\n   while(i != j)\r\n   {\r\n      double rel = i->second / min_time;\r\n      std::cout << \"[[\" << i->first << \"][\" << rel << \"(\" << i->second << \"s)]]\\n\";\r\n      ++i;\r\n   }\r\n   \r\n   std::cout << \"]\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n   using namespace boost::multiprecision;\r\n#ifdef TEST_CPP_INT\r\n   test_miller_rabin<number<cpp_int_backend<>, et_off> >(\"cpp_int (no Expression templates)\");\r\n   test_miller_rabin<cpp_int>(\"cpp_int\");\r\n   test_miller_rabin<number<cpp_int_backend<128> > >(\"cpp_int (128-bit cache)\");\r\n   test_miller_rabin<number<cpp_int_backend<256> > >(\"cpp_int (256-bit cache)\");\r\n   test_miller_rabin<number<cpp_int_backend<512> > >(\"cpp_int (512-bit cache)\");\r\n   test_miller_rabin<number<cpp_int_backend<1024> > >(\"cpp_int (1024-bit cache)\");\r\n   test_miller_rabin<int1024_t>(\"int1024_t\");\r\n   test_miller_rabin<checked_int1024_t>(\"checked_int1024_t\");\r\n#endif\r\n#ifdef TEST_MPZ\r\n   test_miller_rabin<number<gmp_int, et_off> >(\"mpz_int (no Expression templates)\");\r\n   test_miller_rabin<mpz_int>(\"mpz_int\");\r\n   std::cout << \"Time for mpz_int (native Miller Rabin Test) = \" << test_miller_rabin_gmp() << std::endl;\r\n#endif\r\n#ifdef TEST_TOMMATH\r\n   test_miller_rabin<number<boost::multiprecision::tommath_int, et_off> >(\"tom_int (no Expression templates)\");\r\n   test_miller_rabin<boost::multiprecision::tom_int>(\"tom_int\");\r\n#endif\r\n\r\n   generate_quickbook();\r\n\r\n   return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "03fbf20cf1e12b8d15fbce8599510e37c11cd081", "size": 4631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/multiprecision/performance/miller_rabin_performance.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/multiprecision/performance/miller_rabin_performance.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/multiprecision/performance/miller_rabin_performance.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": 27.5654761905, "max_line_length": 112, "alphanum_fraction": 0.6437054632, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5427599706624497}}
{"text": "// Boost.Geometry Index\n//\n// Quickbook Examples\n//\n// Copyright (c) 2011-2014 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//[rtree_iterative_query\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n\n#include <boost/geometry/index/rtree.hpp>\n\n// just for output\n#include <iostream>\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\nint main()\n{\n    typedef bg::model::point<double, 2, bg::cs::cartesian> point;\n    typedef point value;\n    typedef bgi::rtree< value, bgi::linear<16> > rtree_t;\n\n    // create the rtree using default constructor\n    rtree_t rtree;\n\n    // create some values\n    for ( double f = 0 ; f < 10 ; f += 1 )\n    {\n        // insert new value\n        rtree.insert(point(f, f));\n    }\n\n    // query point\n    point pt(5.1, 5.1);\n\n    // iterate over nearest Values\n    for ( rtree_t::const_query_iterator\n            it = rtree.qbegin(bgi::nearest(pt, 100)) ;\n            it != rtree.qend() ;\n            ++it )\n    {\n        double d = bg::distance(pt, *it);\n\n        std::cout << bg::wkt(*it) << \", distance= \" << d << std::endl;\n\n        // break if the distance is too big\n        if ( d > 2 )\n        {\n            std::cout << \"break!\" << std::endl;\n            break;\n        }\n    }\n\n    return 0;\n}\n\n//]\n", "meta": {"hexsha": "1afb53ee55a0d9f1c994e589caed01678e2bf28d", "size": 1511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/index/src/examples/rtree/iterative_query.cpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "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": "libs/geometry/doc/index/src/examples/rtree/iterative_query.cpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "libs/geometry/doc/index/src/examples/rtree/iterative_query.cpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 22.8939393939, "max_line_length": 79, "alphanum_fraction": 0.5956320318, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5427599701728273}}
{"text": "/* Author: Wolfgang Bangerth, University of Texas at Austin, 2000, 2004, 2005 */\n\n/*    $Id: step-18.cc 28563 2013-02-25 23:21:10Z heister $       */\n/*                                                                */\n/*    Copyright (C) 2000, 2004-2009, 2011-2012 by the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n\n// First the usual list of header files that have already been used in\n// previous example programs:\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/conditional_ostream.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/compressed_sparsity_pattern.h>\n#include <deal.II/lac/petsc_vector.h>\n#include <deal.II/lac/petsc_parallel_vector.h>\n#include <deal.II/lac/petsc_parallel_sparse_matrix.h>\n#include <deal.II/lac/petsc_solver.h>\n#include <deal.II/lac/petsc_precondition.h>\n#include <deal.II/lac/constraint_matrix.h>\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#include <deal.II/grid/tria_boundary_lib.h>\n#include <deal.II/grid/grid_tools.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/dofs/dof_renumbering.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/fe_system.h>\n#include <deal.II/fe/fe_q.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 <deal.II/numerics/error_estimator.h>\n\n// And here the only two new things among the header files: an include file in\n// which symmetric tensors of rank 2 and 4 are implemented, as introduced in\n// the introduction:\n#include <deal.II/base/symmetric_tensor.h>\n\n// And a header that implements filters for iterators looping over all\n// cells. We will use this when selecting only those cells for output that are\n// owned by the present process in a %parallel program:\n#include <deal.II/grid/filtered_iterator.h>\n\n// This is then simply C++ again:\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n\n// The last step is as in all previous programs:\nnamespace Step18\n{\n  using namespace dealii;\n\n  // @sect3{The <code>PointHistory</code> class}\n\n  // As was mentioned in the introduction, we have to store the old stress in\n  // quadrature point so that we can compute the residual forces at this point\n  // during the next time step. This alone would not warrant a structure with\n  // only one member, but in more complicated applications, we would have to\n  // store more information in quadrature points as well, such as the history\n  // variables of plasticity, etc. In essence, we have to store everything\n  // that affects the present state of the material here, which in plasticity\n  // is determined by the deformation history variables.\n  //\n  // We will not give this class any meaningful functionality beyond being\n  // able to store data, i.e. there are no constructors, destructors, or other\n  // member functions. In such cases of `dumb' classes, we usually opt to\n  // declare them as <code>struct</code> rather than <code>class</code>, to\n  // indicate that they are closer to C-style structures than C++-style\n  // classes.\n  template <int dim>\n  struct PointHistory\n  {\n    SymmetricTensor<2,dim> old_stress;\n  };\n\n\n  // @sect3{The stress-strain tensor}\n\n  // Next, we define the linear relationship between the stress and the strain\n  // in elasticity. It is given by a tensor of rank 4 that is usually written\n  // in the form $C_{ijkl} = \\mu (\\delta_{ik} \\delta_{jl} + \\delta_{il}\n  // \\delta_{jk}) + \\lambda \\delta_{ij} \\delta_{kl}$. This tensor maps\n  // symmetric tensor of rank 2 to symmetric tensors of rank 2. A function\n  // implementing its creation for given values of the Lame constants lambda\n  // and mu is straightforward:\n  template <int dim>\n  SymmetricTensor<4,dim>\n  get_stress_strain_tensor (const double lambda, const double mu)\n  {\n    SymmetricTensor<4,dim> tmp;\n    for (unsigned int i=0; i<dim; ++i)\n      for (unsigned int j=0; j<dim; ++j)\n        for (unsigned int k=0; k<dim; ++k)\n          for (unsigned int l=0; l<dim; ++l)\n            tmp[i][j][k][l] = (((i==k) && (j==l) ? mu : 0.0) +\n                               ((i==l) && (j==k) ? mu : 0.0) +\n                               ((i==j) && (k==l) ? lambda : 0.0));\n    return tmp;\n  }\n\n  // With this function, we will define a static member variable of the main\n  // class below that will be used throughout the program as the stress-strain\n  // tensor. Note that in more elaborate programs, this will probably be a\n  // member variable of some class instead, or a function that returns the\n  // stress-strain relationship depending on other input. For example in\n  // damage theory models, the Lame constants are considered a function of the\n  // prior stress/strain history of a point. Conversely, in plasticity the\n  // form of the stress-strain tensor is modified if the material has reached\n  // the yield stress in a certain point, and possibly also depending on its\n  // prior history.\n  //\n  // In the present program, however, we assume that the material is\n  // completely elastic and linear, and a constant stress-strain tensor is\n  // sufficient for our present purposes.\n\n\n\n  // @sect3{Auxiliary functions}\n\n  // Before the rest of the program, here are a few functions that we need as\n  // tools. These are small functions that are called in inner loops, so we\n  // mark them as <code>inline</code>.\n  //\n  // The first one computes the symmetric strain tensor for shape function\n  // <code>shape_func</code> at quadrature point <code>q_point</code> by\n  // forming the symmetric gradient of this shape function. We need that when\n  // we want to form the matrix, for example.\n  //\n  // We should note that in previous examples where we have treated\n  // vector-valued problems, we have always asked the finite element object in\n  // which of the vector component the shape function is actually non-zero,\n  // and thereby avoided to compute any terms that we could prove were zero\n  // anyway. For this, we used the <code>fe.system_to_component_index</code>\n  // function that returns in which component a shape function was zero, and\n  // also that the <code>fe_values.shape_value</code> and\n  // <code>fe_values.shape_grad</code> functions only returned the value and\n  // gradient of the single non-zero component of a shape function if this is\n  // a vector-valued element.\n  //\n  // This was an optimization, and if it isn't terribly time critical, we can\n  // get away with a simpler technique: just ask the <code>fe_values</code>\n  // for the value or gradient of a given component of a given shape function\n  // at a given quadrature point. This is what the\n  // <code>fe_values.shape_grad_component(shape_func,q_point,i)</code> call\n  // does: return the full gradient of the <code>i</code>th component of shape\n  // function <code>shape_func</code> at quadrature point\n  // <code>q_point</code>. If a certain component of a certain shape function\n  // is always zero, then this will simply always return zero.\n  //\n  // As mentioned, using <code>fe_values.shape_grad_component</code> instead\n  // of the combination of <code>fe.system_to_component_index</code> and\n  // <code>fe_values.shape_grad</code> may be less efficient, but its\n  // implementation is optimized for such cases and shouldn't be a big\n  // slowdown. We demonstrate the technique here since it is so much simpler\n  // and straightforward.\n  template <int dim>\n  inline\n  SymmetricTensor<2,dim>\n  get_strain (const FEValues<dim> &fe_values,\n              const unsigned int   shape_func,\n              const unsigned int   q_point)\n  {\n    // Declare a temporary that will hold the return value:\n    SymmetricTensor<2,dim> tmp;\n\n    // First, fill diagonal terms which are simply the derivatives in\n    // direction <code>i</code> of the <code>i</code> component of the\n    // vector-valued shape function:\n    for (unsigned int i=0; i<dim; ++i)\n      tmp[i][i] = fe_values.shape_grad_component (shape_func,q_point,i)[i];\n\n    // Then fill the rest of the strain tensor. Note that since the tensor is\n    // symmetric, we only have to compute one half (here: the upper right\n    // corner) of the off-diagonal elements, and the implementation of the\n    // <code>SymmetricTensor</code> class makes sure that at least to the\n    // outside the symmetric entries are also filled (in practice, the class\n    // of course stores only one copy). Here, we have picked the upper right\n    // half of the tensor, but the lower left one would have been just as\n    // good:\n    for (unsigned int i=0; i<dim; ++i)\n      for (unsigned int j=i+1; j<dim; ++j)\n        tmp[i][j]\n          = (fe_values.shape_grad_component (shape_func,q_point,i)[j] +\n             fe_values.shape_grad_component (shape_func,q_point,j)[i]) / 2;\n\n    return tmp;\n  }\n\n\n  // The second function does something very similar (and therefore is given\n  // the same name): compute the symmetric strain tensor from the gradient of\n  // a vector-valued field. If you already have a solution field, the\n  // <code>fe_values.get_function_grads</code> function allows you to extract\n  // the gradients of each component of your solution field at a quadrature\n  // point. It returns this as a vector of rank-1 tensors: one rank-1 tensor\n  // (gradient) per vector component of the solution. From this we have to\n  // reconstruct the (symmetric) strain tensor by transforming the data\n  // storage format and symmetrization. We do this in the same way as above,\n  // i.e. we avoid a few computations by filling first the diagonal and then\n  // only one half of the symmetric tensor (the <code>SymmetricTensor</code>\n  // class makes sure that it is sufficient to write only one of the two\n  // symmetric components).\n  //\n  // Before we do this, though, we make sure that the input has the kind of\n  // structure we expect: that is that there are <code>dim</code> vector\n  // components, i.e. one displacement component for each coordinate\n  // direction. We test this with the <code>Assert</code> macro that will\n  // simply abort our program if the condition is not met.\n  template <int dim>\n  inline\n  SymmetricTensor<2,dim>\n  get_strain (const std::vector<Tensor<1,dim> > &grad)\n  {\n    Assert (grad.size() == dim, ExcInternalError());\n\n    SymmetricTensor<2,dim> strain;\n    for (unsigned int i=0; i<dim; ++i)\n      strain[i][i] = grad[i][i];\n\n    for (unsigned int i=0; i<dim; ++i)\n      for (unsigned int j=i+1; j<dim; ++j)\n        strain[i][j] = (grad[i][j] + grad[j][i]) / 2;\n\n    return strain;\n  }\n\n\n  // Finally, below we will need a function that computes the rotation matrix\n  // induced by a displacement at a given point. In fact, of course, the\n  // displacement at a single point only has a direction and a magnitude, it\n  // is the change in direction and magnitude that induces rotations. In\n  // effect, the rotation matrix can be computed from the gradients of a\n  // displacement, or, more specifically, from the curl.\n  //\n  // The formulas by which the rotation matrices are determined are a little\n  // awkward, especially in 3d. For 2d, there is a simpler way, so we\n  // implement this function twice, once for 2d and once for 3d, so that we\n  // can compile and use the program in both space dimensions if so desired --\n  // after all, deal.II is all about dimension independent programming and\n  // reuse of algorithm thoroughly tested with cheap computations in 2d, for\n  // the more expensive computations in 3d. Here is one case, where we have to\n  // implement different algorithms for 2d and 3d, but then can write the rest\n  // of the program in a way that is independent of the space dimension.\n  //\n  // So, without further ado to the 2d implementation:\n  Tensor<2,2>\n  get_rotation_matrix (const std::vector<Tensor<1,2> > &grad_u)\n  {\n    // First, compute the curl of the velocity field from the gradients. Note\n    // that we are in 2d, so the rotation is a scalar:\n    const double curl = (grad_u[1][0] - grad_u[0][1]);\n\n    // From this, compute the angle of rotation:\n    const double angle = std::atan (curl);\n\n    // And from this, build the antisymmetric rotation matrix:\n    const double t[2][2] = {{ cos(angle), sin(angle) },\n      {-sin(angle), cos(angle) }\n    };\n    return Tensor<2,2>(t);\n  }\n\n\n  // The 3d case is a little more contrived:\n  Tensor<2,3>\n  get_rotation_matrix (const std::vector<Tensor<1,3> > &grad_u)\n  {\n    // Again first compute the curl of the velocity field. This time, it is a\n    // real vector:\n    const Point<3> curl (grad_u[2][1] - grad_u[1][2],\n                         grad_u[0][2] - grad_u[2][0],\n                         grad_u[1][0] - grad_u[0][1]);\n\n    // From this vector, using its magnitude, compute the tangent of the angle\n    // of rotation, and from it the actual angle:\n    const double tan_angle = std::sqrt(curl*curl);\n    const double angle = std::atan (tan_angle);\n\n    // Now, here's one problem: if the angle of rotation is too small, that\n    // means that there is no rotation going on (for example a translational\n    // motion). In that case, the rotation matrix is the identity matrix.\n    //\n    // The reason why we stress that is that in this case we have that\n    // <code>tan_angle==0</code>. Further down, we need to divide by that\n    // number in the computation of the axis of rotation, and we would get\n    // into trouble when dividing doing so. Therefore, let's shortcut this and\n    // simply return the identity matrix if the angle of rotation is really\n    // small:\n    if (angle < 1e-9)\n      {\n        static const double rotation[3][3]\n        = {{ 1, 0, 0}, { 0, 1, 0 }, { 0, 0, 1 } };\n        static const Tensor<2,3> rot(rotation);\n        return rot;\n      }\n\n    // Otherwise compute the real rotation matrix. The algorithm for this is\n    // not exactly obvious, but can be found in a number of books,\n    // particularly on computer games where rotation is a very frequent\n    // operation. Online, you can find a description at\n    // http://www.makegames.com/3drotation/ and (this particular form, with\n    // the signs as here) at\n    // http://www.gamedev.net/reference/articles/article1199.asp:\n    const double c = std::cos(angle);\n    const double s = std::sin(angle);\n    const double t = 1-c;\n\n    const Point<3> axis = curl/tan_angle;\n    const double rotation[3][3]\n    = {{\n        t *axis[0] *axis[0]+c,\n        t *axis[0] *axis[1]+s *axis[2],\n        t *axis[0] *axis[2]-s *axis[1]\n      },\n      {\n        t *axis[0] *axis[1]-s *axis[2],\n        t *axis[1] *axis[1]+c,\n        t *axis[1] *axis[2]+s *axis[0]\n      },\n      {\n        t *axis[0] *axis[2]+s *axis[1],\n        t *axis[1] *axis[1]-s *axis[0],\n        t *axis[2] *axis[2]+c\n      }\n    };\n    return Tensor<2,3>(rotation);\n  }\n\n\n\n  // @sect3{The <code>TopLevel</code> class}\n\n  // This is the main class of the program. Since the namespace already\n  // indicates what problem we are solving, let's call it by what it does: it\n  // directs the flow of the program, i.e. it is the toplevel driver.\n  //\n  // The member variables of this class are essentially as before, i.e. it has\n  // to have a triangulation, a DoF handler and associated objects such as\n  // constraints, variables that describe the linear system, etc. There are a\n  // good number of more member functions now, which we will explain below.\n  //\n  // The external interface of the class, however, is unchanged: it has a\n  // public constructor and desctructor, and it has a <code>run</code>\n  // function that initiated all the work.\n  template <int dim>\n  class TopLevel\n  {\n  public:\n    TopLevel ();\n    ~TopLevel ();\n    void run ();\n\n  private:\n    // The private interface is more extensive than in step-17. First, we\n    // obviously need functions that create the initial mesh, set up the\n    // variables that describe the linear system on the present mesh\n    // (i.e. matrices and vectors), and then functions that actually assemble\n    // the system, direct what has to be solved in each time step, a function\n    // that solves the linear system that arises in each timestep (and returns\n    // the number of iterations it took), and finally output the solution\n    // vector on the currect mesh:\n    void create_coarse_grid ();\n\n    void setup_system ();\n\n    void assemble_system ();\n\n    void solve_timestep ();\n\n    unsigned int solve_linear_problem ();\n\n    void output_results () const;\n\n    // All, except for the first two, of these functions are called in each\n    // timestep. Since the first time step is a little special, we have\n    // separate functions that describe what has to happen in a timestep: one\n    // for the first, and one for all following timesteps:\n    void do_initial_timestep ();\n\n    void do_timestep ();\n\n    // Then we need a whole bunch of functions that do various things. The\n    // first one refines the initial grid: we start on the coarse grid with a\n    // pristine state, solve the problem, then look at it and refine the mesh\n    // accordingly, and start the same process over again, again with a\n    // pristine state. Thus, refining the initial mesh is somewhat simpler\n    // than refining a grid between two successive time steps, since it does\n    // not involve transferring data from the old to the new triangulation, in\n    // particular the history data that is stored in each quadrature point.\n    void refine_initial_grid ();\n\n    // At the end of each time step, we want to move the mesh vertices around\n    // according to the incremental displacement computed in this time\n    // step. This is the function in which this is done:\n    void move_mesh ();\n\n    // Next are two functions that handle the history variables stored in each\n    // quadrature point. The first one is called before the first timestep to\n    // set up a pristine state for the history variables. It only works on\n    // those quadrature points on cells that belong to the present processor:\n    void setup_quadrature_point_history ();\n\n    // The second one updates the history variables at the end of each\n    // timestep:\n    void update_quadrature_point_history ();\n\n    // After the member functions, here are the member variables. The first\n    // ones have all been discussed in more detail in previous example\n    // programs:\n    Triangulation<dim>   triangulation;\n\n    FESystem<dim>        fe;\n\n    DoFHandler<dim>      dof_handler;\n\n    ConstraintMatrix     hanging_node_constraints;\n\n    // One difference of this program is that we declare the quadrature\n    // formula in the class declaration. The reason is that in all the other\n    // programs, it didn't do much harm if we had used different quadrature\n    // formulas when computing the matrix and the righ hand side, for\n    // example. However, in the present case it does: we store information in\n    // the quadrature points, so we have to make sure all parts of the program\n    // agree on where they are and how many there are on each cell. Thus, let\n    // us first declare the quadrature formula that will be used throughout...\n    const QGauss<dim>          quadrature_formula;\n\n    // ... and then also have a vector of history objects, one per quadrature\n    // point on those cells for which we are responsible (i.e. we don't store\n    // history data for quadrature points on cells that are owned by other\n    // processors).\n    std::vector<PointHistory<dim> > quadrature_point_history;\n\n    // The way this object is accessed is through a <code>user pointer</code>\n    // that each cell, face, or edge holds: it is a <code>void*</code> pointer\n    // that can be used by application programs to associate arbitrary data to\n    // cells, faces, or edges. What the program actually does with this data\n    // is within its own responsibility, the library just allocates some space\n    // for these pointers, and application programs can set and read the\n    // pointers for each of these objects.\n\n\n    // Further: we need the objects of linear systems to be solved,\n    // i.e. matrix, right hand side vector, and the solution vector. Since we\n    // anticipate solving big problems, we use the same types as in step-17,\n    // i.e. distributed %parallel matrices and vectors built on top of the\n    // PETSc library. Conveniently, they can also be used when running on only\n    // a single machine, in which case this machine happens to be the only one\n    // in our %parallel universe.\n    //\n    // However, as a difference to step-17, we do not store the solution\n    // vector -- which here is the incremental displacements computed in each\n    // time step -- in a distributed fashion. I.e., of course it must be a\n    // distributed vector when computing it, but immediately after that we\n    // make sure each processor has a complete copy. The reason is that we had\n    // already seen in step-17 that many functions needed a complete\n    // copy. While it is not hard to get it, this requires communication on\n    // the network, and is thus slow. In addition, these were repeatedly the\n    // same operations, which is certainly undesirable unless the gains of not\n    // always having to store the entire vector outweighs it. When writing\n    // this program, it turned out that we need a complete copy of the\n    // solution in so many places that it did not seem worthwhile to only get\n    // it when necessary. Instead, we opted to obtain the complete copy once\n    // and for all, and instead get rid of the distributed copy\n    // immediately. Thus, note that the declaration of\n    // <code>inremental_displacement</code> does not denote a distribute\n    // vector as would be indicated by the middle namespace <code>MPI</code>:\n    PETScWrappers::MPI::SparseMatrix system_matrix;\n\n    PETScWrappers::MPI::Vector       system_rhs;\n\n    PETScWrappers::Vector            incremental_displacement;\n\n    // The next block of variables is then related to the time dependent\n    // nature of the problem: they denote the length of the time interval\n    // which we want to simulate, the present time and number of time step,\n    // and length of present timestep:\n    double       present_time;\n    double       present_timestep;\n    double       end_time;\n    unsigned int timestep_no;\n\n    // Then a few variables that have to do with %parallel processing: first,\n    // a variable denoting the MPI communicator we use, and then two numbers\n    // telling us how many participating processors there are, and where in\n    // this world we are. Finally, a stream object that makes sure only one\n    // processor is actually generating output to the console. This is all the\n    // same as in step-17:\n    MPI_Comm mpi_communicator;\n\n    const unsigned int n_mpi_processes;\n\n    const unsigned int this_mpi_process;\n\n    ConditionalOStream pcout;\n\n    // Here is a vector where each entry denotes the numbers of degrees of\n    // freedom that are stored on the processor with that particular number:\n    std::vector<unsigned int> local_dofs_per_process;\n\n    // Next, how many degrees of freedom the present processor stores. This\n    // is, of course, an abbreviation to\n    // <code>local_dofs_per_process[this_mpi_process]</code>.\n    unsigned int         n_local_dofs;\n\n    // In the same direction, also cache how many cells the present processor\n    // owns. Note that the cells that belong to a processor are not\n    // necessarily contiguously numbered (when iterating over them using\n    // <code>active_cell_iterator</code>).\n    unsigned int         n_local_cells;\n\n    // Finally, we have a static variable that denotes the linear relationship\n    // between the stress and strain. Since it is a constant object that does\n    // not depend on any input (at least not in this program), we make it a\n    // static variable and will initialize it in the same place where we\n    // define the constructor of this class:\n    static const SymmetricTensor<4,dim> stress_strain_tensor;\n  };\n\n\n  // @sect3{The <code>BodyForce</code> class}\n\n  // Before we go on to the main functionality of this program, we have to\n  // define what forces will act on the body whose deformation we want to\n  // study. These may either be body forces or boundary forces. Body forces\n  // are generally mediated by one of the four basic physical types of forces:\n  // gravity, strong and weak interaction, and electromagnetism. Unless one\n  // wants to consider subatomic objects (for which quasistatic deformation is\n  // irrelevant and an inappropriate description anyway), only gravity and\n  // electromagnetic forces need to be considered. Let us, for simplicity\n  // assume that our body has a certain mass density, but is either\n  // non-magnetic and not electrically conducting or that there are no\n  // significant electromagnetic fields around. In that case, the body forces\n  // are simply <code>rho g</code>, where <code>rho</code> is the material\n  // density and <code>g</code> is a vector in negative z-direction with\n  // magnitude 9.81 m/s^2.  Both the density and <code>g</code> are defined in\n  // the function, and we take as the density 7700 kg/m^3, a value commonly\n  // assumed for steel.\n  //\n  // To be a little more general and to be able to do computations in 2d as\n  // well, we realize that the body force is always a function returning a\n  // <code>dim</code> dimensional vector. We assume that gravity acts along\n  // the negative direction of the last, i.e. <code>dim-1</code>th\n  // coordinate. The rest of the implementation of this function should be\n  // mostly self-explanatory given similar definitions in previous example\n  // programs. Note that the body force is independent of the location; to\n  // avoid compiler warnings about unused function arguments, we therefore\n  // comment out the name of the first argument of the\n  // <code>vector_value</code> function:\n  template <int dim>\n  class BodyForce :  public Function<dim>\n  {\n  public:\n    BodyForce ();\n\n    virtual\n    void\n    vector_value (const Point<dim> &p,\n                  Vector<double>   &values) const;\n\n    virtual\n    void\n    vector_value_list (const std::vector<Point<dim> > &points,\n                       std::vector<Vector<double> >   &value_list) const;\n  };\n\n\n  template <int dim>\n  BodyForce<dim>::BodyForce ()\n    :\n    Function<dim> (dim)\n  {}\n\n\n  template <int dim>\n  inline\n  void\n  BodyForce<dim>::vector_value (const Point<dim> & /*p*/,\n                                Vector<double>   &values) const\n  {\n    Assert (values.size() == dim,\n            ExcDimensionMismatch (values.size(), dim));\n\n    const double g   = 9.81;\n    const double rho = 7700;\n\n    values = 0;\n    values(dim-1) = -rho * g;\n  }\n\n\n\n  template <int dim>\n  void\n  BodyForce<dim>::vector_value_list (const std::vector<Point<dim> > &points,\n                                     std::vector<Vector<double> >   &value_list) const\n  {\n    const unsigned int n_points = points.size();\n\n    Assert (value_list.size() == n_points,\n            ExcDimensionMismatch (value_list.size(), n_points));\n\n    for (unsigned int p=0; p<n_points; ++p)\n      BodyForce<dim>::vector_value (points[p],\n                                    value_list[p]);\n  }\n\n\n\n  // @sect3{The <code>IncrementalBoundaryValue</code> class}\n\n  // In addition to body forces, movement can be induced by boundary forces\n  // and forced boundary displacement. The latter case is equivalent to forces\n  // being chosen in such a way that they induce certain displacement.\n  //\n  // For quasistatic displacement, typical boundary forces would be pressure\n  // on a body, or tangential friction against another body. We chose a\n  // somewhat simpler case here: we prescribe a certain movement of (parts of)\n  // the boundary, or at least of certain components of the displacement\n  // vector. We describe this by another vector-valued function that, for a\n  // given point on the boundary, returns the prescribed displacement.\n  //\n  // Since we have a time-dependent problem, the displacement increment of the\n  // boundary equals the displacement accumulated during the length of the\n  // timestep. The class therefore has to know both the present time and the\n  // length of the present time step, and can then approximate the incremental\n  // displacement as the present velocity times the present timestep.\n  //\n  // For the purposes of this program, we choose a simple form of boundary\n  // displacement: we displace the top boundary with constant velocity\n  // downwards. The rest of the boundary is either going to be fixed (and is\n  // then described using an object of type <code>ZeroFunction</code>) or free\n  // (Neumann-type, in which case nothing special has to be done).  The\n  // implementation of the class describing the constant downward motion\n  // should then be obvious using the knowledge we gained through all the\n  // previous example programs:\n  template <int dim>\n  class IncrementalBoundaryValues :  public Function<dim>\n  {\n  public:\n    IncrementalBoundaryValues (const double present_time,\n                               const double present_timestep);\n\n    virtual\n    void\n    vector_value (const Point<dim> &p,\n                  Vector<double>   &values) const;\n\n    virtual\n    void\n    vector_value_list (const std::vector<Point<dim> > &points,\n                       std::vector<Vector<double> >   &value_list) const;\n\n  private:\n    const double velocity;\n    const double present_time;\n    const double present_timestep;\n  };\n\n\n  template <int dim>\n  IncrementalBoundaryValues<dim>::\n  IncrementalBoundaryValues (const double present_time,\n                             const double present_timestep)\n    :\n    Function<dim> (dim),\n    velocity (.1),\n    present_time (present_time),\n    present_timestep (present_timestep)\n  {}\n\n\n  template <int dim>\n  void\n  IncrementalBoundaryValues<dim>::\n  vector_value (const Point<dim> & /*p*/,\n                Vector<double>   &values) const\n  {\n    Assert (values.size() == dim,\n            ExcDimensionMismatch (values.size(), dim));\n\n    values = 0;\n    values(2) = -present_timestep * velocity;\n  }\n\n\n\n  template <int dim>\n  void\n  IncrementalBoundaryValues<dim>::\n  vector_value_list (const std::vector<Point<dim> > &points,\n                     std::vector<Vector<double> >   &value_list) const\n  {\n    const unsigned int n_points = points.size();\n\n    Assert (value_list.size() == n_points,\n            ExcDimensionMismatch (value_list.size(), n_points));\n\n    for (unsigned int p=0; p<n_points; ++p)\n      IncrementalBoundaryValues<dim>::vector_value (points[p],\n                                                    value_list[p]);\n  }\n\n\n\n  // @sect3{Implementation of the <code>TopLevel</code> class}\n\n  // Now for the implementation of the main class. First, we initialize the\n  // stress-strain tensor, which we have declared as a static const\n  // variable. We chose Lame constants that are appropriate for steel:\n  template <int dim>\n  const SymmetricTensor<4,dim>\n  TopLevel<dim>::stress_strain_tensor\n    = get_stress_strain_tensor<dim> (/*lambda = */ 9.695e10,\n                                                   /*mu     = */ 7.617e10);\n\n\n\n  // @sect4{The public interface}\n\n  // The next step is the definition of constructors and descructors. There\n  // are no surprises here: we choose linear and continuous finite elements\n  // for each of the <code>dim</code> vector components of the solution, and a\n  // Gaussian quadrature formula with 2 points in each coordinate\n  // direction. The destructor should be obvious:\n  template <int dim>\n  TopLevel<dim>::TopLevel ()\n    :\n    fe (FE_Q<dim>(1), dim),\n    dof_handler (triangulation),\n    quadrature_formula (2),\n    mpi_communicator (MPI_COMM_WORLD),\n    n_mpi_processes (Utilities::MPI::n_mpi_processes(mpi_communicator)),\n    this_mpi_process (Utilities::MPI::this_mpi_process(mpi_communicator)),\n    pcout (std::cout, this_mpi_process == 0)\n  {}\n\n\n\n  template <int dim>\n  TopLevel<dim>::~TopLevel ()\n  {\n    dof_handler.clear ();\n  }\n\n\n\n  // The last of the public functions is the one that directs all the work,\n  // <code>run()</code>. It initializes the variables that describe where in\n  // time we presently are, then runs the first time step, then loops over all\n  // the other time steps. Note that for simplicity we use a fixed time step,\n  // whereas a more sophisticated program would of course have to choose it in\n  // some more reasonable way adaptively:\n  template <int dim>\n  void TopLevel<dim>::run ()\n  {\n    present_time = 0;\n    present_timestep = 1;\n    end_time = 10;\n    timestep_no = 0;\n\n    do_initial_timestep ();\n\n    while (present_time < end_time)\n      do_timestep ();\n  }\n\n\n  // @sect4{TopLevel::create_coarse_grid}\n\n  // The next function in the order in which they were declared above is the\n  // one that creates the coarse grid from which we start. For this example\n  // program, we want to compute the deformation of a cylinder under axial\n  // compression. The first step therefore is to generate a mesh for a\n  // cylinder of length 3 and with inner and outer radii of 0.8 and 1,\n  // respectively. Fortunately, there is a library function for such a mesh.\n  //\n  // In a second step, we have to associated boundary conditions with the\n  // upper and lower faces of the cylinder. We choose a boundary indicator of\n  // 0 for the boundary faces that are characterized by their midpoints having\n  // z-coordinates of either 0 (bottom face), an indicator of 1 for z=3 (top\n  // face); finally, we use boundary indicator 2 for all faces on the inside\n  // of the cylinder shell, and 3 for the outside.\n  template <int dim>\n  void TopLevel<dim>::create_coarse_grid ()\n  {\n    const double inner_radius = 0.8,\n                 outer_radius = 1;\n    GridGenerator::cylinder_shell (triangulation,\n                                   3, inner_radius, outer_radius);\n    for (typename Triangulation<dim>::active_cell_iterator\n         cell=triangulation.begin_active();\n         cell!=triangulation.end(); ++cell)\n      for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)\n        if (cell->face(f)->at_boundary())\n          {\n            const Point<dim> face_center = cell->face(f)->center();\n\n            if (face_center[2] == 0)\n              cell->face(f)->set_boundary_indicator (0);\n            else if (face_center[2] == 3)\n              cell->face(f)->set_boundary_indicator (1);\n            else if (std::sqrt(face_center[0]*face_center[0] +\n                               face_center[1]*face_center[1])\n                     <\n                     (inner_radius + outer_radius) / 2)\n              cell->face(f)->set_boundary_indicator (2);\n            else\n              cell->face(f)->set_boundary_indicator (3);\n          }\n\n    // In order to make sure that new vertices are placed correctly on mesh\n    // refinement, we have to associate objects describing those parts of the\n    // boundary that do not consist of straight parts. Corresponding to the\n    // cylinder shell generator function used above, there are classes that\n    // can be used to describe the geometry of cylinders. We need to use\n    // different objects for the inner and outer parts of the cylinder, with\n    // different radii; the second argument to the constructor indicates the\n    // axis around which the cylinder revolves -- in this case the\n    // z-axis. Note that the boundary objects need to live as long as the\n    // triangulation does; we can achieve this by making the objects static,\n    // which means that they live as long as the program runs:\n    static const CylinderBoundary<dim> inner_cylinder (inner_radius, 2);\n    static const CylinderBoundary<dim> outer_cylinder (outer_radius, 2);\n    // We then attach these two objects to the triangulation, and make them\n    // correspond to boundary indicators 2 and 3:\n    triangulation.set_boundary (2, inner_cylinder);\n    triangulation.set_boundary (3, outer_cylinder);\n\n    // There's one more thing we have to take care of (we should have done so\n    // above already, but for didactic reasons it was more appropriate to\n    // handle it after discussing boundary objects). %Boundary indicators in\n    // deal.II, for mostly historic reasons, serve a dual purpose: they\n    // describe the type of a boundary for other places in a program where\n    // different boundary conditions are implemented; and they describe which\n    // boundary object (as the ones associated above) should be queried when\n    // new boundary points need to be placed upon mesh refinement. In the\n    // prefix to this function, we have discussed the boundary condition\n    // issue, and the boundary geometry issue was mentioned just above. But\n    // there is a case where we have to be careful with geometry: what happens\n    // if a cell is refined that has two faces with different boundary\n    // indicators? For example one at the edges of the cylinder? In that case,\n    // the library wouldn't know where to put new points in the middle of\n    // edges (one of the twelve lines of a hexahedron). In fact, the library\n    // doesn't even care about the boundary indicator of adjacent faces when\n    // refining edges: it considers the boundary indicators associated with\n    // the edges themselves. So what do we want to happen with the edges of\n    // the cylinder shell: they sit on both faces with boundary indicators 2\n    // or 3 (inner or outer shell) and 0 or 1 (for which no boundary objects\n    // have been specified, and for which the library therefore assumes\n    // straight lines). Obviously, we want these lines to follow the curved\n    // shells, so we have to assign all edges along faces with boundary\n    // indicators 2 or 3 these same boundary indicators to make sure they are\n    // refined using the appropriate geometry objects. This is easily done:\n    for (typename Triangulation<dim>::active_face_iterator\n         face=triangulation.begin_active_face();\n         face!=triangulation.end_face(); ++face)\n      if (face->at_boundary())\n        if ((face->boundary_indicator() == 2)\n            ||\n            (face->boundary_indicator() == 3))\n          for (unsigned int edge = 0; edge<GeometryInfo<dim>::lines_per_face;\n               ++edge)\n            face->line(edge)\n            ->set_boundary_indicator (face->boundary_indicator());\n\n    // Once all this is done, we can refine the mesh once globally:\n    triangulation.refine_global (1);\n\n\n    // As the final step, we need to set up a clean state of the data that we\n    // store in the quadrature points on all cells that are treated on the\n    // present processor. To do so, we also have to know which processors are\n    // ours in the first place. This is done in the following two function\n    // calls:\n    GridTools::partition_triangulation (n_mpi_processes, triangulation);\n    setup_quadrature_point_history ();\n  }\n\n\n\n\n  // @sect4{TopLevel::setup_system}\n\n  // The next function is the one that sets up the data structures for a given\n  // mesh. This is done in most the same way as in step-17: distribute the\n  // degrees of freedom, then sort these degrees of freedom in such a way that\n  // each processor gets a contiguous chunk of them. Note that subdivions into\n  // chunks for each processor is handled in the functions that create or\n  // refine grids, unlike in the previous example program (the point where\n  // this happens is mostly a matter of taste; here, we chose to do it when\n  // grids are created since in the <code>do_initial_timestep</code> and\n  // <code>do_timestep</code> functions we want to output the number of cells\n  // on each processor at a point where we haven't called the present function\n  // yet).\n  template <int dim>\n  void TopLevel<dim>::setup_system ()\n  {\n    dof_handler.distribute_dofs (fe);\n    DoFRenumbering::subdomain_wise (dof_handler);\n\n    // The next thing is to store some information for later use on how many\n    // cells or degrees of freedom the present processor, or any of the\n    // processors has to work on. First the cells local to this processor...\n    n_local_cells\n      = GridTools::count_cells_with_subdomain_association (triangulation,\n                                                           this_mpi_process);\n\n    // ...and then a list of numbers of how many degrees of freedom each\n    // processor has to handle:\n    local_dofs_per_process.resize (n_mpi_processes);\n    for (unsigned int i=0; i<n_mpi_processes; ++i)\n      local_dofs_per_process[i]\n        = DoFTools::count_dofs_with_subdomain_association (dof_handler, i);\n\n    // Finally, make it easier to denote how many degrees of freedom the\n    // present process has to deal with, by introducing an abbreviation:\n    n_local_dofs = local_dofs_per_process[this_mpi_process];\n\n    // The next step is to set up constraints due to hanging nodes. This has\n    // been handled many times before:\n    hanging_node_constraints.clear ();\n    DoFTools::make_hanging_node_constraints (dof_handler,\n                                             hanging_node_constraints);\n    hanging_node_constraints.close ();\n\n    // And then we have to set up the matrix. Here we deviate from step-17, in\n    // which we simply used PETSc's ability to just know about the size of the\n    // matrix and later allocate those nonzero elements that are being written\n    // to. While this works just fine from a correctness viewpoint, it is not\n    // at all efficient: if we don't give PETSc a clue as to which elements\n    // are written to, it is (at least at the time of this writing) unbearably\n    // slow when we set the elements in the matrix for the first time (i.e. in\n    // the first timestep). Later on, when the elements have been allocated,\n    // everything is much faster. In experiments we made, the first timestep\n    // can be accelerated by almost two orders of magnitude if we instruct\n    // PETSc which elements will be used and which are not.\n    //\n    // To do so, we first generate the sparsity pattern of the matrix we are\n    // going to work with, and make sure that the condensation of hanging node\n    // constraints add the necessary additional entries in the sparsity\n    // pattern:\n    CompressedSparsityPattern sparsity_pattern (dof_handler.n_dofs(),\n                                                dof_handler.n_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);\n    hanging_node_constraints.condense (sparsity_pattern);\n    // Note that we have used the <code>CompressedSparsityPattern</code> class\n    // here that was already introduced in step-11, rather than the\n    // <code>SparsityPattern</code> class that we have used in all other\n    // cases. The reason for this is that for the latter class to work we have\n    // to give an initial upper bound for the number of entries in each row, a\n    // task that is traditionally done by\n    // <code>DoFHandler::max_couplings_between_dofs()</code>. However, this\n    // function suffers from a serious problem: it has to compute an upper\n    // bound to the number of nonzero entries in each row, and this is a\n    // rather complicated task, in particular in 3d. In effect, while it is\n    // quite accurate in 2d, it often comes up with much too large a number in\n    // 3d, and in that case the <code>SparsityPattern</code> allocates much\n    // too much memory at first, often several 100 MBs. This is later\n    // corrected when <code>DoFTools::make_sparsity_pattern</code> is called\n    // and we realize that we don't need all that much memory, but at time it\n    // is already too late: for large problems, the temporary allocation of\n    // too much memory can lead to out-of-memory situations.\n    //\n    // In order to avoid this, we resort to the\n    // <code>CompressedSparsityPattern</code> class that is slower but does\n    // not require any up-front estimate on the number of nonzero entries per\n    // row. It therefore only ever allocates as much memory as it needs at any\n    // given time, and we can build it even for large 3d problems.\n    //\n    // It is also worth noting that the sparsity pattern we construct is\n    // global, i.e. comprises all degrees of freedom whether they will be\n    // owned by the processor we are on or another one (in case this program\n    // is run in %parallel via MPI). This of course is not optimal -- it\n    // limits the size of the problems we can solve, since storing the entire\n    // sparsity pattern (even if only for a short time) on each processor does\n    // not scale well. However, there are several more places in the program\n    // in which we do this, for example we always keep the global\n    // triangulation and DoF handler objects around, even if we only work on\n    // part of them. At present, deal.II does not have the necessary\n    // facilities to completely distribute these objects (a task that, indeed,\n    // is very hard to achieve with adaptive meshes, since well-balanced\n    // subdivisions of a domain tend to become unbalanced as the mesh is\n    // adaptively refined).\n    //\n    // With this data structure, we can then go to the PETSc sparse matrix and\n    // tell it to pre-allocate all the entries we will later want to write to:\n    system_matrix.reinit (mpi_communicator,\n                          sparsity_pattern,\n                          local_dofs_per_process,\n                          local_dofs_per_process,\n                          this_mpi_process);\n    // After this point, no further explicit knowledge of the sparsity pattern\n    // is required any more and we can let the <code>sparsity_pattern</code>\n    // variable go out of scope without any problem.\n\n    // The last task in this function is then only to reset the right hand\n    // side vector as well as the solution vector to its correct size;\n    // remember that the solution vector is a local one, unlike the right hand\n    // side that is a distributed %parallel one and therefore needs to know\n    // the MPI communicator over which it is supposed to transmit messages:\n    system_rhs.reinit (mpi_communicator, dof_handler.n_dofs(), n_local_dofs);\n    incremental_displacement.reinit (dof_handler.n_dofs());\n  }\n\n\n\n  // @sect4{TopLevel::assemble_system}\n\n  // Again, assembling the system matrix and right hand side follows the same\n  // structure as in many example programs before. In particular, it is mostly\n  // equivalent to step-17, except for the different right hand side that now\n  // only has to take into account internal stresses. In addition, assembling\n  // the matrix is made significantly more transparent by using the\n  // <code>SymmetricTensor</code> class: note the elegance of forming the\n  // scalar products of symmetric tensors of rank 2 and 4. The implementation\n  // is also more general since it is independent of the fact that we may or\n  // may not be using an isotropic elasticity tensor.\n  //\n  // The first part of the assembly routine is as always:\n  template <int dim>\n  void TopLevel<dim>::assemble_system ()\n  {\n    system_rhs = 0;\n    system_matrix = 0;\n\n    FEValues<dim> fe_values (fe, quadrature_formula,\n                             update_values   | update_gradients |\n                             update_quadrature_points | update_JxW_values);\n\n    const unsigned int   dofs_per_cell = fe.dofs_per_cell;\n    const unsigned int   n_q_points    = quadrature_formula.size();\n\n    FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n    Vector<double>       cell_rhs (dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    BodyForce<dim>      body_force;\n    std::vector<Vector<double> > body_force_values (n_q_points,\n                                                    Vector<double>(dim));\n\n    // As in step-17, we only need to loop over all cells that belong to the\n    // present processor:\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n    for (; cell!=endc; ++cell)\n      if (cell->subdomain_id() == this_mpi_process)\n        {\n          cell_matrix = 0;\n          cell_rhs = 0;\n\n          fe_values.reinit (cell);\n\n          // Then loop over all indices i,j and quadrature points and assemble\n          // the system matrix contributions from this cell.  Note how we\n          // extract the symmetric gradients (strains) of the shape functions\n          // at a given quadrature point from the <code>FEValues</code>\n          // object, and the elegance with which we form the triple\n          // contraction <code>eps_phi_i : C : eps_phi_j</code>; the latter\n          // needs to be compared to the clumsy computations needed in\n          // step-17, both in the introduction as well as in the respective\n          // place in the program:\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            for (unsigned int j=0; j<dofs_per_cell; ++j)\n              for (unsigned int q_point=0; q_point<n_q_points;\n                   ++q_point)\n                {\n                  const SymmetricTensor<2,dim>\n                  eps_phi_i = get_strain (fe_values, i, q_point),\n                  eps_phi_j = get_strain (fe_values, j, q_point);\n\n                  cell_matrix(i,j)\n                  += (eps_phi_i * stress_strain_tensor * eps_phi_j\n                      *\n                      fe_values.JxW (q_point));\n                }\n\n\n          // Then also assemble the local right hand side contributions. For\n          // this, we need to access the prior stress value in this quadrature\n          // point. To get it, we use the user pointer of this cell that\n          // points into the global array to the quadrature point data\n          // corresponding to the first quadrature point of the present cell,\n          // and then add an offset corresponding to the index of the\n          // quadrature point we presently consider:\n          const PointHistory<dim> *local_quadrature_points_data\n            = reinterpret_cast<PointHistory<dim>*>(cell->user_pointer());\n          // In addition, we need the values of the external body forces at\n          // the quadrature points on this cell:\n          body_force.vector_value_list (fe_values.get_quadrature_points(),\n                                        body_force_values);\n          // Then we can loop over all degrees of freedom on this cell and\n          // compute local contributions to the right hand side:\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            {\n              const unsigned int\n              component_i = fe.system_to_component_index(i).first;\n\n              for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n                {\n                  const SymmetricTensor<2,dim> &old_stress\n                    = local_quadrature_points_data[q_point].old_stress;\n\n                  cell_rhs(i) += (body_force_values[q_point](component_i) *\n                                  fe_values.shape_value (i,q_point)\n                                  -\n                                  old_stress *\n                                  get_strain (fe_values,i,q_point))\n                                 *\n                                 fe_values.JxW (q_point);\n                }\n            }\n\n          // Now that we have the local contributions to the linear system, we\n          // need to transfer it into the global objects. This is done exactly\n          // as in step-17:\n          cell->get_dof_indices (local_dof_indices);\n\n          hanging_node_constraints\n\t    .distribute_local_to_global (cell_matrix, cell_rhs,\n                                       local_dof_indices,\n\t\t\t\t\t system_matrix, system_rhs);\n        }\n\n    // Now compress the vector and the system matrix:\n    system_matrix.compress(VectorOperation::add);\n    system_rhs.compress(VectorOperation::add);\n\n    \n    // The last step is to again fix up boundary values, just as we already\n    // did in previous programs. A slight complication is that the\n    // <code>apply_boundary_values</code> function wants to have a solution\n    // vector compatible with the matrix and right hand side (i.e. here a\n    // distributed %parallel vector, rather than the sequential vector we use\n    // in this program) in order to preset the entries of the solution vector\n    // with the correct boundary values. We provide such a compatible vector\n    // in the form of a temporary vector which we then copy into the\n    // sequential one.\n\n    // We make up for this complication by showing how boundary values can be\n    // used flexibly: following the way we create the triangulation, there are\n    // three distinct boundary indicators used to describe the domain,\n    // corresponding to the bottom and top faces, as well as the inner/outer\n    // surfaces. We would like to impose boundary conditions of the following\n    // type: The inner and outer cylinder surfaces are free of external\n    // forces, a fact that corresponds to natural (Neumann-type) boundary\n    // conditions for which we don't have to do anything. At the bottom, we\n    // want no movement at all, corresponding to the cylinder being clamped or\n    // cemented in at this part of the boundary. At the top, however, we want\n    // a prescribed vertical downward motion compressing the cylinder; in\n    // addition, we only want to restrict the vertical movement, but not the\n    // horizontal ones -- one can think of this situation as a well-greased\n    // plate sitting on top of the cylinder pushing it downwards: the atoms of\n    // the cylinder are forced to move downward, but they are free to slide\n    // horizontally along the plate.\n\n    // The way to describe this is as follows: for boundary indicator zero\n    // (bottom face) we use a dim-dimensional zero function representing no\n    // motion in any coordinate direction. For the boundary with indicator 1\n    // (top surface), we use the <code>IncrementalBoundaryValues</code> class,\n    // but we specify an additional argument to the\n    // <code>VectorTools::interpolate_boundary_values</code> function denoting\n    // which vector components it should apply to; this is a vector of bools\n    // for each vector component and because we only want to restrict vertical\n    // motion, it has only its last component set:\n    FEValuesExtractors::Scalar z_component (dim-1);\n    std::map<unsigned int,double> boundary_values;\n    VectorTools::\n    interpolate_boundary_values (dof_handler,\n                                 0,\n                                 ZeroFunction<dim> (dim),\n                                 boundary_values);\n    VectorTools::\n    interpolate_boundary_values (dof_handler,\n                                 1,\n                                 IncrementalBoundaryValues<dim>(present_time,\n                                                                present_timestep),\n                                 boundary_values,\n                                 fe.component_mask(z_component));\n\n    PETScWrappers::MPI::Vector tmp (mpi_communicator, dof_handler.n_dofs(),\n                                    n_local_dofs);\n    MatrixTools::apply_boundary_values (boundary_values,\n                                        system_matrix, tmp,\n                                        system_rhs, false);\n    incremental_displacement = tmp;\n  }\n\n\n\n  // @sect4{TopLevel::solve_timestep}\n\n  // The next function is the one that controls what all has to happen within\n  // a timestep. The order of things should be relatively self-explanatory\n  // from the function names:\n  template <int dim>\n  void TopLevel<dim>::solve_timestep ()\n  {\n    pcout << \"    Assembling system...\" << std::flush;\n    assemble_system ();\n    pcout << \" norm of rhs is \" << system_rhs.l2_norm()\n          << std::endl;\n\n    const unsigned int n_iterations = solve_linear_problem ();\n\n    pcout << \"    Solver converged in \" << n_iterations\n          << \" iterations.\" << std::endl;\n\n    pcout << \"    Updating quadrature point data...\" << std::flush;\n    update_quadrature_point_history ();\n    pcout << std::endl;\n  }\n\n\n\n  // @sect4{TopLevel::solve_linear_problem}\n\n  // Solving the linear system again works mostly as before. The only\n  // difference is that we want to only keep a complete local copy of the\n  // solution vector instead of the distributed one that we get as output from\n  // PETSc's solver routines. To this end, we declare a local temporary\n  // variable for the distributed vector and initialize it with the contents\n  // of the local variable (remember that the\n  // <code>apply_boundary_values</code> function called in\n  // <code>assemble_system</code> preset the values of boundary nodes in this\n  // vector), solve with it, and at the end of the function copy it again into\n  // the complete local vector that we declared as a member variable. Hanging\n  // node constraints are then distributed only on the local copy,\n  // i.e. independently of each other on each of the processors:\n  template <int dim>\n  unsigned int TopLevel<dim>::solve_linear_problem ()\n  {\n    PETScWrappers::MPI::Vector\n    distributed_incremental_displacement (mpi_communicator,\n                                          dof_handler.n_dofs(),\n                                          n_local_dofs);\n    distributed_incremental_displacement = incremental_displacement;\n\n    SolverControl           solver_control (dof_handler.n_dofs(),\n                                            1e-16*system_rhs.l2_norm());\n    PETScWrappers::SolverCG cg (solver_control,\n                                mpi_communicator);\n\n    PETScWrappers::PreconditionBlockJacobi preconditioner(system_matrix);\n\n    cg.solve (system_matrix, distributed_incremental_displacement, system_rhs,\n              preconditioner);\n\n    incremental_displacement = distributed_incremental_displacement;\n\n    hanging_node_constraints.distribute (incremental_displacement);\n\n    return solver_control.last_step();\n  }\n\n\n\n  // @sect4{TopLevel::output_results}\n\n  // This function generates the graphical output in intermediate format as\n  // explained in the introduction. Each process will only work on the cells\n  // it owns, and then write the result into a file of its own. These files\n  // may later be merged to get a single file in any of the supported output\n  // files, as mentioned in the introduction.\n  //\n  // The crucial part of this function is to give the <code>DataOut</code>\n  // class a way to only work on the cells that the present process owns. This\n  // class is already well-equipped for that: it has two virtual functions\n  // <code>first_cell</code> and <code>next_cell</code> that return the first\n  // cell to be worked on, and given one cell return the next cell to be\n  // worked on. By default, these functions return the first active cell\n  // (i.e. the first one that has no children) and the next active cell. What\n  // we have to do here is derive a class from <code>DataOut</code> that\n  // overloads these two functions to only iterate over those cells with the\n  // right subdomain indicator.\n  //\n  // We do this at the beginning of this function. The <code>first_cell</code>\n  // function just starts with the first active cell, and then iterates to the\n  // next cells while the cell presently under consideration does not yet have\n  // the correct subdomain id. The only thing that needs to be taken care of\n  // is that we don't try to keep iterating when we have hit the end iterator.\n  //\n  // The <code>next_cell</code> function could be implemented in a similar\n  // way. However, we use this occasion as a pretext to introduce one more\n  // thing that the library offers: filtered iterators. These are wrappers for\n  // the iterator classes that just skip all cells (or faces, lines, etc) that\n  // do not satisfy a certain predicate (a predicate in computer-lingo is a\n  // function that when applied to a data element either returns true or\n  // false). In the present case, the predicate is that the cell has to have a\n  // certain subdomain id, and the library already has this predicate built\n  // in. If the cell iterator is not the end iterator, what we then have to do\n  // is to initialize such a filtered iterator with the present cell and the\n  // predicate, and then increase the iterator exactly once. While the more\n  // conventional loop would probably not have been much longer, this is\n  // definitely the more elegant way -- and then, these example programs also\n  // serve the purpose of introducing what is available in deal.II.\n  template<int dim>\n  class FilteredDataOut : public DataOut<dim>\n  {\n  public:\n    FilteredDataOut (const unsigned int subdomain_id)\n      :\n      subdomain_id (subdomain_id)\n    {}\n\n    virtual typename DoFHandler<dim>::cell_iterator\n    first_cell ()\n    {\n      typename DoFHandler<dim>::active_cell_iterator\n      cell = this->dofs->begin_active();\n      while ((cell != this->dofs->end()) &&\n             (cell->subdomain_id() != subdomain_id))\n        ++cell;\n\n      return cell;\n    }\n\n    virtual typename DoFHandler<dim>::cell_iterator\n    next_cell (const typename DoFHandler<dim>::cell_iterator &old_cell)\n    {\n      if (old_cell != this->dofs->end())\n        {\n          const IteratorFilters::SubdomainEqualTo\n          predicate(subdomain_id);\n\n          return\n            ++(FilteredIterator\n               <typename DoFHandler<dim>::active_cell_iterator>\n               (predicate,old_cell));\n        }\n      else\n        return old_cell;\n    }\n\n  private:\n    const unsigned int subdomain_id;\n  };\n\n\n\n  template <int dim>\n  void TopLevel<dim>::output_results () const\n  {\n    // With this newly defined class, declare an object that is going to\n    // generate the graphical output and attach the dof handler with it from\n    // which to get the solution vector:\n    FilteredDataOut<dim> data_out(this_mpi_process);\n    data_out.attach_dof_handler (dof_handler);\n\n    // Then, just as in step-17, define the names of solution variables (which\n    // here are the displacement increments) and queue the solution vector for\n    // output. Note in the following switch how we make sure that if the space\n    // dimension should be unhandled that we throw an exception saying that we\n    // haven't implemented this case yet (another case of defensive\n    // programming):\n    std::vector<std::string> solution_names;\n    switch (dim)\n      {\n      case 1:\n        solution_names.push_back (\"delta_x\");\n        break;\n      case 2:\n        solution_names.push_back (\"delta_x\");\n        solution_names.push_back (\"delta_y\");\n        break;\n      case 3:\n        solution_names.push_back (\"delta_x\");\n        solution_names.push_back (\"delta_y\");\n        solution_names.push_back (\"delta_z\");\n        break;\n      default:\n        Assert (false, ExcNotImplemented());\n      }\n\n    data_out.add_data_vector (incremental_displacement,\n                              solution_names);\n\n\n    // The next thing is that we wanted to output something like the average\n    // norm of the stresses that we have stored in each cell. This may seem\n    // complicated, since on the present processor we only store the stresses\n    // in quadrature points on those cells that actually belong to the present\n    // process. In other words, it seems as if we can't compute the average\n    // stresses for all cells. However, remember that our class derived from\n    // <code>DataOut</code> only iterates over those cells that actually do\n    // belong to the present processor, i.e. we don't have to compute anything\n    // for all the other cells as this information would not be touched. The\n    // following little loop does this. We enclose the entire block into a\n    // pair of braces to make sure that the iterator variables do not remain\n    // accidentally visible beyond the end of the block in which they are\n    // used:\n    Vector<double> norm_of_stress (triangulation.n_active_cells());\n    {\n      // Loop over all the cells...\n      typename Triangulation<dim>::active_cell_iterator\n      cell = triangulation.begin_active(),\n      endc = triangulation.end();\n      for (unsigned int index=0; cell!=endc; ++cell, ++index)\n        // ... and pick those that are relevant to us:\n        if (cell->subdomain_id() == this_mpi_process)\n          {\n            // On these cells, add up the stresses over all quadrature\n            // points...\n            SymmetricTensor<2,dim> accumulated_stress;\n            for (unsigned int q=0;\n                 q<quadrature_formula.size();\n                 ++q)\n              accumulated_stress +=\n                reinterpret_cast<PointHistory<dim>*>(cell->user_pointer())[q]\n                .old_stress;\n\n            // ...then write the norm of the average to their destination:\n            norm_of_stress(index)\n              = (accumulated_stress /\n                 quadrature_formula.size()).norm();\n          }\n      // And on the cells that we are not interested in, set the respective\n      // value in the vector to a bogus value (norms must be positive, and a\n      // large negative value should catch your eye) in order to make sure\n      // that if we were somehow wrong about our assumption that these\n      // elements would not appear in the output file, that we would find out\n      // by looking at the graphical output:\n        else\n          norm_of_stress(index) = -1e+20;\n    }\n    // Finally attach this vector as well to be treated for output:\n    data_out.add_data_vector (norm_of_stress, \"norm_of_stress\");\n\n    // As a last piece of data, let us also add the partitioning of the domain\n    // into subdomains associated with the processors if this is a parallel\n    // job. This works in the exact same way as in the step-17 program:\n    std::vector<unsigned int> partition_int (triangulation.n_active_cells());\n    GridTools::get_subdomain_association (triangulation, partition_int);\n    const Vector<double> partitioning(partition_int.begin(),\n                                      partition_int.end());\n    data_out.add_data_vector (partitioning, \"partitioning\");\n\n    // Finally, with all this data, we can instruct deal.II to munge the\n    // information and produce some intermediate data structures that contain\n    // all these solution and other data vectors:\n    data_out.build_patches ();\n\n\n    // Now that we have generated the intermediate format, let us determine\n    // the name of the file we will want to write it to. We compose it of the\n    // prefix <code>solution-</code>, followed by a representation of the\n    // present time written as a fixed point number so that file names sort\n    // naturally:\n    std::ostringstream filename;\n    filename << \"solution-\";\n    filename << std::setfill('0');\n    filename.setf(std::ios::fixed, std::ios::floatfield);\n    filename << std::setw(9) << std::setprecision(4) << present_time;\n\n    // Next, in case there are multiple processes working together, we have to\n    // generate different file names for the output of each process. In our\n    // case, we encode the process number as a three-digit integer, padded\n    // with zeros. The assertion in the first line of the block makes sure\n    // that there are less than 1000 processes (a very conservative check, but\n    // worth having anyway) as our scheme of generating process numbers would\n    // overflow if there were 1000 processes or more. Note that we choose to\n    // use <code>AssertThrow</code> rather than <code>Assert</code> since the\n    // number of processes is a variable that depends on input files or the\n    // way the process is started, rather than static assumptions in the\n    // program code. Therefore, it is inappropriate to use <code>Assert</code>\n    // that is optimized away in optimized mode, whereas here we actually can\n    // assume that users will run the largest computations with the most\n    // processors in optimized mode, and we should check our assumptions in\n    // this particular case, and not only when running in debug mode:\n    if (n_mpi_processes != 1)\n      {\n        AssertThrow (n_mpi_processes < 1000, ExcNotImplemented());\n\n        filename << '-';\n        filename << std::setfill('0');\n        filename << std::setw(3) << this_mpi_process;\n      }\n\n    // To the file name, attach the file name suffix usually used for the\n    // deal.II intermediate format. To determine it, we use the same function\n    // that has already been used in step-13:\n    filename << data_out.default_suffix(DataOut<dim>::deal_II_intermediate);\n\n    // With the so-completed filename, let us open a file and write the data\n    // we have generated into it, using the intermediate format:\n    std::ofstream output (filename.str().c_str());\n    data_out.write_deal_II_intermediate (output);\n  }\n\n\n\n  // @sect4{TopLevel::do_initial_timestep}\n\n  // This and the next function handle the overall structure of the first and\n  // following timesteps, respectively. The first timestep is slightly more\n  // involved because we want to compute it multiple times on successively\n  // refined meshes, each time starting from a clean state. At the end of\n  // these computations, in which we compute the incremental displacements\n  // each time, we use the last results obtained for the incremental\n  // displacements to compute the resulting stress updates and move the mesh\n  // accordingly. On this new mesh, we then output the solution and any\n  // additional data we consider important.\n  //\n  // All this is interspersed by generating output to the console to update\n  // the person watching the screen on what is going on. As in step-17, the\n  // use of <code>pcout</code> instead of <code>std::cout</code> makes sure\n  // that only one of the parallel processes is actually writing to the\n  // console, without having to explicitly code an if-statement in each place\n  // where we generate output:\n  template <int dim>\n  void TopLevel<dim>::do_initial_timestep ()\n  {\n    present_time += present_timestep;\n    ++timestep_no;\n    pcout << \"Timestep \" << timestep_no << \" at time \" << present_time\n          << std::endl;\n\n    for (unsigned int cycle=0; cycle<2; ++cycle)\n      {\n        pcout << \"  Cycle \" << cycle << ':' << std::endl;\n\n        if (cycle == 0)\n          create_coarse_grid ();\n        else\n          refine_initial_grid ();\n\n        pcout << \"    Number of active cells:       \"\n              << triangulation.n_active_cells()\n              << \" (by partition:\";\n        for (unsigned int p=0; p<n_mpi_processes; ++p)\n          pcout << (p==0 ? ' ' : '+')\n                << (GridTools::\n                    count_cells_with_subdomain_association (triangulation,p));\n        pcout << \")\" << std::endl;\n\n        setup_system ();\n\n        pcout << \"    Number of degrees of freedom: \"\n              << dof_handler.n_dofs()\n              << \" (by partition:\";\n        for (unsigned int p=0; p<n_mpi_processes; ++p)\n          pcout << (p==0 ? ' ' : '+')\n                << (DoFTools::\n                    count_dofs_with_subdomain_association (dof_handler,p));\n        pcout << \")\" << std::endl;\n\n        solve_timestep ();\n      }\n\n    move_mesh ();\n    output_results ();\n\n    pcout << std::endl;\n  }\n\n\n\n  // @sect4{TopLevel::do_timestep}\n\n  // Subsequent timesteps are simpler, and probably do not require any more\n  // documentation given the explanations for the previous function above:\n  template <int dim>\n  void TopLevel<dim>::do_timestep ()\n  {\n    present_time += present_timestep;\n    ++timestep_no;\n    pcout << \"Timestep \" << timestep_no << \" at time \" << present_time\n          << std::endl;\n    if (present_time > end_time)\n      {\n        present_timestep -= (present_time - end_time);\n        present_time = end_time;\n      }\n\n\n    solve_timestep ();\n\n    move_mesh ();\n    output_results ();\n\n    pcout << std::endl;\n  }\n\n\n  // @sect4{TopLevel::refine_initial_grid}\n\n  // The following function is called when solving the first time step on\n  // successively refined meshes. After each iteration, it computes a\n  // refinement criterion, refines the mesh, and sets up the history variables\n  // in each quadrature point again to a clean state.\n  template <int dim>\n  void TopLevel<dim>::refine_initial_grid ()\n  {\n    // First, let each process compute error indicators for the cells it owns:\n    Vector<float> error_per_cell (triangulation.n_active_cells());\n    KellyErrorEstimator<dim>::estimate (dof_handler,\n                                        QGauss<dim-1>(2),\n                                        typename FunctionMap<dim>::type(),\n                                        incremental_displacement,\n                                        error_per_cell,\n                                        ComponentMask(),\n                                        0,\n                                        multithread_info.n_default_threads,\n                                        this_mpi_process);\n\n    // Then set up a global vector into which we merge the local indicators\n    // from each of the %parallel processes:\n    const unsigned int n_local_cells\n      = GridTools::count_cells_with_subdomain_association (triangulation,\n                                                           this_mpi_process);\n    PETScWrappers::MPI::Vector\n    distributed_error_per_cell (mpi_communicator,\n                                triangulation.n_active_cells(),\n                                n_local_cells);\n\n    for (unsigned int i=0; i<error_per_cell.size(); ++i)\n      if (error_per_cell(i) != 0)\n        distributed_error_per_cell(i) = error_per_cell(i);\n    distributed_error_per_cell.compress (VectorOperation::insert);\n\n    // Once we have that, copy it back into local copies on all processors and\n    // refine the mesh accordingly:\n    error_per_cell = distributed_error_per_cell;\n    GridRefinement::refine_and_coarsen_fixed_number (triangulation,\n                                                     error_per_cell,\n                                                     0.35, 0.03);\n    triangulation.execute_coarsening_and_refinement ();\n\n    // Finally, set up quadrature point data again on the new mesh, and only\n    // on those cells that we have determined to be ours:\n    GridTools::partition_triangulation (n_mpi_processes, triangulation);\n    setup_quadrature_point_history ();\n  }\n\n\n\n  // @sect4{TopLevel::move_mesh}\n\n  // At the end of each time step, we move the nodes of the mesh according to\n  // the incremental displacements computed in this time step. To do this, we\n  // keep a vector of flags that indicate for each vertex whether we have\n  // already moved it around, and then loop over all cells and move those\n  // vertices of the cell that have not been moved yet. It is worth noting\n  // that it does not matter from which of the cells adjacent to a vertex we\n  // move this vertex: since we compute the displacement using a continuous\n  // finite element, the displacement field is continuous as well and we can\n  // compute the displacement of a given vertex from each of the adjacent\n  // cells. We only have to make sure that we move each node exactly once,\n  // which is why we keep the vector of flags.\n  //\n  // There are two noteworthy things in this function. First, how we get the\n  // displacement field at a given vertex using the\n  // <code>cell-@>vertex_dof_index(v,d)</code> function that returns the index\n  // of the <code>d</code>th degree of freedom at vertex <code>v</code> of the\n  // given cell. In the present case, displacement in the k-th coordinate\n  // direction corresonds to the kth component of the finite element. Using a\n  // function like this bears a certain risk, because it uses knowledge of the\n  // order of elements that we have taken together for this program in the\n  // <code>FESystem</code> element. If we decided to add an additional\n  // variable, for example a pressure variable for stabilization, and happened\n  // to insert it as the first variable of the element, then the computation\n  // below will start to produce non-sensical results. In addition, this\n  // computation rests on other assumptions: first, that the element we use\n  // has, indeed, degrees of freedom that are associated with vertices. This\n  // is indeed the case for the present Q1 element, as would be for all Qp\n  // elements of polynomial order <code>p</code>. However, it would not hold\n  // for discontinuous elements, or elements for mixed formulations. Secondly,\n  // it also rests on the assumption that the displacement at a vertex is\n  // determined solely by the value of the degree of freedom associated with\n  // this vertex; in other words, all shape functions corresponding to other\n  // degrees of freedom are zero at this particular vertex. Again, this is the\n  // case for the present element, but is not so for all elements that are\n  // presently available in deal.II. Despite its risks, we choose to use this\n  // way in order to present a way to query individual degrees of freedom\n  // associated with vertices.\n  //\n  // In this context, it is instructive to point out what a more general way\n  // would be. For general finite elements, the way to go would be to take a\n  // quadrature formula with the quadrature points in the vertices of a\n  // cell. The <code>QTrapez</code> formula for the trapezoidal rule does\n  // exactly this. With this quadrature formula, we would then initialize an\n  // <code>FEValues</code> object in each cell, and use the\n  // <code>FEValues::get_function_values</code> function to obtain the values\n  // of the solution function in the quadrature points, i.e. the vertices of\n  // the cell. These are the only values that we really need, i.e. we are not\n  // at all interested in the weights (or the <code>JxW</code> values)\n  // associated with this particular quadrature formula, and this can be\n  // specified as the last argument in the constructor to\n  // <code>FEValues</code>. The only point of minor inconvenience in this\n  // scheme is that we have to figure out which quadrature point corresponds\n  // to the vertex we consider at present, as they may or may not be ordered\n  // in the same order.\n  //\n  // Another point worth explaining about this short function is the way in\n  // which the triangulation class exports information about its vertices:\n  // through the <code>Triangulation::n_vertices</code> function, it\n  // advertises how many vertices there are in the triangulation. Not all of\n  // them are actually in use all the time -- some are left-overs from cells\n  // that have been coarsened previously and remain in existence since deal.II\n  // never changes the number of a vertex once it has come into existence,\n  // even if vertices with lower number go away. Secondly, the location\n  // returned by <code>cell-@>vertex(v)</code> is not only a read-only object\n  // of type <code>Point@<dim@></code>, but in fact a reference that can be\n  // written to. This allows to move around the nodes of a mesh with relative\n  // ease, but it is worth pointing out that it is the responsibility of an\n  // application program using this feature to make sure that the resulting\n  // cells are still useful, i.e. are not distorted so much that the cell is\n  // degenerated (indicated, for example, by negative Jacobians). Note that we\n  // do not have any provisions in this function to actually ensure this, we\n  // just have faith.\n  //\n  // After this lengthy introduction, here are the full 20 or so lines of\n  // code:\n  template <int dim>\n  void TopLevel<dim>::move_mesh ()\n  {\n    pcout << \"    Moving mesh...\" << std::endl;\n\n    std::vector<bool> vertex_touched (triangulation.n_vertices(),\n                                      false);\n    for (typename DoFHandler<dim>::active_cell_iterator\n         cell = dof_handler.begin_active ();\n         cell != dof_handler.end(); ++cell)\n      for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)\n        if (vertex_touched[cell->vertex_index(v)] == false)\n          {\n            vertex_touched[cell->vertex_index(v)] = true;\n\n            Point<dim> vertex_displacement;\n            for (unsigned int d=0; d<dim; ++d)\n              vertex_displacement[d]\n                = incremental_displacement(cell->vertex_dof_index(v,d));\n\n            cell->vertex(v) += vertex_displacement;\n          }\n  }\n\n\n  // @sect4{TopLevel::setup_quadrature_point_history}\n\n  // At the beginning of our computations, we needed to set up initial values\n  // of the history variables, such as the existing stresses in the material,\n  // that we store in each quadrature point. As mentioned above, we use the\n  // <code>user_pointer</code> for this that is available in each cell.\n  //\n  // To put this into larger perspective, we note that if we had previously\n  // available stresses in our model (which we assume do not exist for the\n  // purpose of this program), then we would need to interpolate the field of\n  // pre-existing stresses to the quadrature points. Likewise, if we were to\n  // simulate elasto-plastic materials with hardening/softening, then we would\n  // have to store additional history variables like the present yield stress\n  // of the accumulated plastic strains in each quadrature\n  // points. Pre-existing hardening or weakening would then be implemented by\n  // interpolating these variables in the present function as well.\n  template <int dim>\n  void TopLevel<dim>::setup_quadrature_point_history ()\n  {\n    // What we need to do here is to first count how many quadrature points\n    // are within the responsibility of this processor. This, of course,\n    // equals the number of cells that belong to this processor times the\n    // number of quadrature points our quadrature formula has on each cell.\n    //\n    // For good measure, we also set all user pointers of all cells, whether\n    // ours of not, to the null pointer. This way, if we ever access the user\n    // pointer of a cell which we should not have accessed, a segmentation\n    // fault will let us know that this should not have happened:\n    unsigned int our_cells = 0;\n    for (typename Triangulation<dim>::active_cell_iterator\n         cell = triangulation.begin_active();\n         cell != triangulation.end(); ++cell)\n      if (cell->subdomain_id() == this_mpi_process)\n        ++our_cells;\n\n    triangulation.clear_user_data();\n\n    // Next, allocate as many quadrature objects as we need. Since the\n    // <code>resize</code> function does not actually shrink the amount of\n    // allocated memory if the requested new size is smaller than the old\n    // size, we resort to a trick to first free all memory, and then\n    // reallocate it: we declare an empty vector as a temporary variable and\n    // then swap the contents of the old vector and this temporary\n    // variable. This makes sure that the\n    // <code>quadrature_point_history</code> is now really empty, and we can\n    // let the temporary variable that now holds the previous contents of the\n    // vector go out of scope and be destroyed. In the next step. we can then\n    // re-allocate as many elements as we need, with the vector\n    // default-initializing the <code>PointHistory</code> objects, which\n    // includes setting the stress variables to zero.\n    {\n      std::vector<PointHistory<dim> > tmp;\n      tmp.swap (quadrature_point_history);\n    }\n    quadrature_point_history.resize (our_cells *\n                                     quadrature_formula.size());\n\n    // Finally loop over all cells again and set the user pointers from the\n    // cells that belong to the present processor to point to the first\n    // quadrature point objects corresponding to this cell in the vector of\n    // such objects:\n    unsigned int history_index = 0;\n    for (typename Triangulation<dim>::active_cell_iterator\n         cell = triangulation.begin_active();\n         cell != triangulation.end(); ++cell)\n      if (cell->subdomain_id() == this_mpi_process)\n        {\n          cell->set_user_pointer (&quadrature_point_history[history_index]);\n          history_index += quadrature_formula.size();\n        }\n\n    // At the end, for good measure make sure that our count of elements was\n    // correct and that we have both used up all objects we allocated\n    // previously, and not point to any objects beyond the end of the\n    // vector. Such defensive programming strategies are always good checks to\n    // avoid accidental errors and to guard against future changes to this\n    // function that forget to update all uses of a variable at the same\n    // time. Recall that constructs using the <code>Assert</code> macro are\n    // optimized away in optimized mode, so do not affect the run time of\n    // optimized runs:\n    Assert (history_index == quadrature_point_history.size(),\n            ExcInternalError());\n  }\n\n\n\n\n  // @sect4{TopLevel::update_quadrature_point_history}\n\n  // At the end of each time step, we should have computed an incremental\n  // displacement update so that the material in its new configuration\n  // accommodates for the difference between the external body and boundary\n  // forces applied during this time step minus the forces exerted through\n  // pre-existing internal stresses. In order to have the pre-existing\n  // stresses available at the next time step, we therefore have to update the\n  // pre-existing stresses with the stresses due to the incremental\n  // displacement computed during the present time step. Ideally, the\n  // resulting sum of internal stresses would exactly counter all external\n  // forces. Indeed, a simple experiment can make sure that this is so: if we\n  // choose boundary conditions and body forces to be time independent, then\n  // the forcing terms (the sum of external forces and internal stresses)\n  // should be exactly zero. If you make this experiment, you will realize\n  // from the output of the norm of the right hand side in each time step that\n  // this is almost the case: it is not exactly zero, since in the first time\n  // step the incremental displacement and stress updates were computed\n  // relative to the undeformed mesh, which was then deformed. In the second\n  // time step, we again compute displacement and stress updates, but this\n  // time in the deformed mesh -- there, the resulting updates are very small\n  // but not quite zero. This can be iterated, and in each such iteration the\n  // residual, i.e. the norm of the right hand side vector, is reduced; if one\n  // makes this little experiment, one realizes that the norm of this residual\n  // decays exponentially with the number of iterations, and after an initial\n  // very rapid decline is reduced by roughly a factor of about 3.5 in each\n  // iteration (for one testcase I looked at, other testcases, and other\n  // numbers of unknowns change the factor, but not the exponential decay).\n\n  // In a sense, this can then be considered as a quasi-timestepping scheme to\n  // resolve the nonlinear problem of solving large-deformation elasticity on\n  // a mesh that is moved along in a Lagrangian manner.\n  //\n  // Another complication is that the existing (old) stresses are defined on\n  // the old mesh, which we will move around after updating the stresses. If\n  // this mesh update involves rotations of the cell, then we need to also\n  // rotate the updated stress, since it was computed relative to the\n  // coordinate system of the old cell.\n  //\n  // Thus, what we need is the following: on each cell which the present\n  // processor owns, we need to extract the old stress from the data stored\n  // with each quadrature point, compute the stress update, add the two\n  // together, and then rotate the result together with the incremental\n  // rotation computed from the incremental displacement at the present\n  // quadrature point. We will detail these steps below:\n  template <int dim>\n  void TopLevel<dim>::update_quadrature_point_history ()\n  {\n    // First, set up an <code>FEValues</code> object by which we will evaluate\n    // the incremental displacements and the gradients thereof at the\n    // quadrature points, together with a vector that will hold this\n    // information:\n    FEValues<dim> fe_values (fe, quadrature_formula,\n                             update_values | update_gradients);\n    std::vector<std::vector<Tensor<1,dim> > >\n    displacement_increment_grads (quadrature_formula.size(),\n                                  std::vector<Tensor<1,dim> >(dim));\n\n    // Then loop over all cells and do the job in the cells that belong to our\n    // subdomain:\n    for (typename DoFHandler<dim>::active_cell_iterator\n         cell = dof_handler.begin_active();\n         cell != dof_handler.end(); ++cell)\n      if (cell->subdomain_id() == this_mpi_process)\n        {\n          // Next, get a pointer to the quadrature point history data local to\n          // the present cell, and, as a defensive measure, make sure that\n          // this pointer is within the bounds of the global array:\n          PointHistory<dim> *local_quadrature_points_history\n            = reinterpret_cast<PointHistory<dim> *>(cell->user_pointer());\n          Assert (local_quadrature_points_history >=\n                  &quadrature_point_history.front(),\n                  ExcInternalError());\n          Assert (local_quadrature_points_history <\n                  &quadrature_point_history.back(),\n                  ExcInternalError());\n\n          // Then initialize the <code>FEValues</code> object on the present\n          // cell, and extract the gradients of the displacement at the\n          // quadrature points for later computation of the strains\n          fe_values.reinit (cell);\n          fe_values.get_function_grads (incremental_displacement,\n                                        displacement_increment_grads);\n\n          // Then loop over the quadrature points of this cell:\n          for (unsigned int q=0; q<quadrature_formula.size(); ++q)\n            {\n              // On each quadrature point, compute the strain increment from\n              // the gradients, and multiply it by the stress-strain tensor to\n              // get the stress update. Then add this update to the already\n              // existing strain at this point:\n              const SymmetricTensor<2,dim> new_stress\n                = (local_quadrature_points_history[q].old_stress\n                   +\n                   (stress_strain_tensor *\n                    get_strain (displacement_increment_grads[q])));\n\n              // Finally, we have to rotate the result. For this, we first\n              // have to compute a rotation matrix at the present quadrature\n              // point from the incremental displacements. In fact, it can be\n              // computed from the gradients, and we already have a function\n              // for that purpose:\n              const Tensor<2,dim> rotation\n                = get_rotation_matrix (displacement_increment_grads[q]);\n              // Note that the result, a rotation matrix, is in general an\n              // antisymmetric tensor of rank 2, so we must store it as a full\n              // tensor.\n\n              // With this rotation matrix, we can compute the rotated tensor\n              // by contraction from the left and right, after we expand the\n              // symmetric tensor <code>new_stress</code> into a full tensor:\n              const SymmetricTensor<2,dim> rotated_new_stress\n                = symmetrize(transpose(rotation) *\n                             static_cast<Tensor<2,dim> >(new_stress) *\n                             rotation);\n              // Note that while the result of the multiplication of these\n              // three matrices should be symmetric, it is not due to floating\n              // point round off: we get an asymmetry on the order of 1e-16 of\n              // the off-diagonal elements of the result. When assigning the\n              // result to a <code>SymmetricTensor</code>, the constuctor of\n              // that class checks the symmetry and realizes that it isn't\n              // exactly symmetric; it will then raise an exception. To avoid\n              // that, we explicitly symmetrize the result to make it exactly\n              // symmetric.\n\n              // The result of all these operations is then written back into\n              // the original place:\n              local_quadrature_points_history[q].old_stress\n                = rotated_new_stress;\n            }\n        }\n  }\n\n  // This ends the project specific namespace <code>Step18</code>. The rest is\n  // as usual and as already shown in step-17: A <code>main()</code> function\n  // that initializes and terminates PETSc, calls the classes that do the\n  // actual work, and makes sure that we catch all exceptions that propagate\n  // up to this point:\n}\n\n\nint main (int argc, char **argv)\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step18;\n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv);\n      {\n        deallog.depth_console (0);\n\n        TopLevel<3> elastic_problem;\n        elastic_problem.run ();\n      }\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << 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\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << 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": "843a882e8831cf52c83b255839ae0c44af695999", "size": 94409, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-18/step-18.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/step-18/step-18.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/step-18/step-18.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 46.5757276764, "max_line_length": 86, "alphanum_fraction": 0.6719910178, "num_tokens": 21680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.7217431943271998, "lm_q1q2_score": 0.5427599651822598}}
{"text": "#include \"testsuite.h\"\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n    Array<double,2> A;\n    A.resizeAndPreserve(2,2);\n    BZTEST(A.numElements() == 4);\n\n    Array<double,5> B;\n    B.resizeAndPreserve(2,2,2,2,2);\n    BZTEST(B.numElements() == 32);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "4fd6e751fa3edc16b5e47533b04ddfb69bb4f90b", "size": 289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/peter-bienstman-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/peter-bienstman-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/peter-bienstman-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": 15.2105263158, "max_line_length": 35, "alphanum_fraction": 0.6228373702, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.5427599581388598}}
{"text": "\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseCholesky>\n\n#include <vector>\n#include <memory>\n\n#include \"SDOT/SemiDiscreteOT.h\"\n#include \"SDOT/Distances/Wasserstein2.h\"\n\n#include \"SDOT/PolygonRasterize.h\"\n#include \"SDOT/RegularGrid.h\"\n#include \"SDOT/DiscretizedDistribution.h\"\n\nusing namespace sdot;\nusing namespace sdot::distances;\n\nvoid LaguerreDiagramTest()\n{\n  int numPts = 2;\n\n  Eigen::VectorXd prices = Eigen::VectorXd::Ones(numPts);\n  prices << 1, 0.873;//, 0.978674;//, 0.851588;//, 0.996466;\n\n  Eigen::Matrix2Xd pts(2,numPts);\n  pts << 0.823295, 0.329554,\n         0.604897, 0.536459;\n  //pts = Eigen::Matrix2Xd::Random(2,numPts).cwiseAbs();\n\n  Eigen::VectorXd discrProbs(numPts);\n  discrProbs = (1.0/numPts)*Eigen::VectorXd::Ones(numPts);\n\n  LaguerreDiagram lagDiag(0, 1, 0, 1, pts, prices);\n\n  LaguerreDiagram::Point_2 startPt = std::get<1>(lagDiag.InternalEdges(0).at(0));\n  LaguerreDiagram::Point_2 endPt = std::get<2>(lagDiag.InternalEdges(0).at(0));\n\n  std::cout << \"Dividing edge = (\" << CGAL::to_double(startPt.x()) << \",\" << CGAL::to_double(startPt.y()) << \") -> (\" << CGAL::to_double(endPt.x()) << \",\" << CGAL::to_double(endPt.y()) << \")\" << std::endl;\n  LaguerreDiagram::Point_2 midPt = startPt + 0.5*(endPt-startPt);\n\n  double dist1 = std::sqrt( CGAL::to_double(CGAL::squared_distance(startPt,midPt)));\n  double dist2 = std::sqrt( CGAL::to_double(CGAL::squared_distance(endPt,midPt)));\n\n  assert( std::abs( (dist1 - prices(0)) - (dist2 - prices(0)))<1e-14 );\n}\n\n\nint main(int argc, char* argv[])\n{\n  LaguerreDiagramTest();\n\n  int numPts = 100;\n\n  Eigen::VectorXd prices = Eigen::VectorXd::Ones(numPts);\n\n  Eigen::Matrix2Xd pts = Eigen::Matrix2Xd::Random(2,numPts).cwiseAbs();\n\n  std::cout << \"Points = \\n\";\n  std::cout << \"[[\" << pts(0,0) << \",\" << pts(1,0) << \"]\";\n  for(int i=1; i<numPts; ++i){\n    std::cout << \", [\" << pts(0,i) << \",\" << pts(1,i) << \"]\";\n  }\n  std::cout << \"]\" << std::endl;\n\n\n  Eigen::VectorXd discrProbs(numPts);\n  discrProbs << (1.0/numPts)*Eigen::VectorXd::Ones(numPts);\n\n  Eigen::Matrix2Xd domain(2,4);\n  domain << 0.0, 1.0, 1.0, 0.0,\n            0.0, 0.0, 1.0, 1.0;\n\n  // Construct the continuous distribution\n  auto grid = std::make_shared<RegularGrid>(domain(0,0),domain(1,0), domain(0,2), domain(1,2), 10,10);\n\n  // Unnormalized density.  Will be normalized in DiscretizedDistribution constructor\n  Eigen::MatrixXd density = Eigen::MatrixXd::Ones(grid->NumCells(0), grid->NumCells(1));\n\n  auto dist = std::make_shared<DiscretizedDistribution>(grid, density);\n\n  // Evalaute the SDOT objective\n  auto sdot = std::make_shared<SemidiscreteOT<Wasserstein2>>(dist, pts, discrProbs);\n\n  Eigen::VectorXd optPrices;\n  double optVal;\n  std::tie(optPrices,optVal) = sdot->Solve(Eigen::VectorXd::Ones(numPts));\n  std::cout << \"Optimal prices = \" << optPrices.transpose() << std::endl;\n\n  std::shared_ptr<LaguerreDiagram> lagDiag = sdot->Diagram();\n\n  std::cout << \"Laguerre cells = \" << std::endl;\n  for(int polyInd=0; polyInd<numPts; ++polyInd){\n    std::shared_ptr<PolygonRasterizeIter::Polygon_2> poly = lagDiag->GetCell(polyInd)->ToCGAL();\n\n    auto vertIt = poly->vertices_begin();\n    std::cout << \"[[\" << vertIt->x() << \",\" << vertIt->y() << \"]\";\n    vertIt++;\n    for(;  vertIt != poly->vertices_end(); ++vertIt){\n      std::cout << \", [\" << vertIt->x() << \",\" << vertIt->y() << \"]\";\n    }\n    std::cout << \"]\" << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "544334a254a481dab68224a0029caebec676e2f8", "size": 3418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/ComputeSDOT.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/ComputeSDOT.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/ComputeSDOT.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": 31.9439252336, "max_line_length": 205, "alphanum_fraction": 0.6383850205, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.542756430533351}}
{"text": "// Copyright (C) 2011  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 \"checkerboard.h\"\n#include <dlib/statistics.h>\n\n#include \"tester.h\"\n#include <dlib/svm_threaded.h>\n\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n    logger dlog(\"test.probabilistic\");\n\n// ----------------------------------------------------------------------------------------\n\n    class test_probabilistic : public tester\n    {\n    public:\n        test_probabilistic (\n        ) :\n            tester (\"test_probabilistic\",\n                    \"Runs tests on the probabilistic trainer adapter.\")\n        {}\n\n        void perform_test (\n        )\n        {\n            print_spinner();\n\n\n            typedef double scalar_type;\n            typedef matrix<scalar_type,2,1> sample_type;\n\n            std::vector<sample_type> x;\n            std::vector<matrix<double,0,1> > x_linearized;\n            std::vector<scalar_type> y;\n\n            get_checkerboard_problem(x,y, 1000, 2);\n\n            random_subset_selector<sample_type> rx;\n            random_subset_selector<scalar_type> ry;\n            rx.set_max_size(x.size());\n            ry.set_max_size(x.size());\n\n            dlog << LINFO << \"pos labels: \"<< sum(mat(y) == +1);\n            dlog << LINFO << \"neg labels: \"<< sum(mat(y) == -1);\n\n            for (unsigned long i = 0; i < x.size(); ++i)\n            {\n                rx.add(x[i]);\n                ry.add(y[i]);\n            }\n\n            const scalar_type gamma = 2.0;\n\n            typedef radial_basis_kernel<sample_type> kernel_type;\n\n            krr_trainer<kernel_type> krr_trainer;\n            krr_trainer.use_classification_loss_for_loo_cv();\n            krr_trainer.set_kernel(kernel_type(gamma));\n            krr_trainer.set_basis(randomly_subsample(x, 100));\n            probabilistic_decision_function<kernel_type> df;\n\n            dlog << LINFO << \"cross validation: \" << cross_validate_trainer(krr_trainer, rx,ry, 4);\n            print_spinner();\n\n            running_stats<scalar_type> rs_pos, rs_neg;\n\n            print_spinner();\n            df = probabilistic(krr_trainer,3).train(x, y);\n            for (unsigned long i = 0; i < x.size(); ++i)\n            {\n                if (y[i] > 0)\n                    rs_pos.add(df(x[i]));\n                else\n                    rs_neg.add(df(x[i]));\n            }\n            dlog << LINFO << \"rs_pos.mean(): \"<< rs_pos.mean();\n            dlog << LINFO << \"rs_neg.mean(): \"<< rs_neg.mean();\n            DLIB_TEST_MSG(rs_pos.mean() > 0.95, rs_pos.mean());\n            DLIB_TEST_MSG(rs_neg.mean() < 0.05, rs_neg.mean());\n            rs_pos.clear();\n            rs_neg.clear();\n\n\n            print_spinner();\n            df = probabilistic(krr_trainer,3).train(rx, ry);\n            for (unsigned long i = 0; i < x.size(); ++i)\n            {\n                if (y[i] > 0)\n                    rs_pos.add(df(x[i]));\n                else\n                    rs_neg.add(df(x[i]));\n            }\n            dlog << LINFO << \"rs_pos.mean(): \"<< rs_pos.mean();\n            dlog << LINFO << \"rs_neg.mean(): \"<< rs_neg.mean();\n            DLIB_TEST_MSG(rs_pos.mean() > 0.95, rs_pos.mean());\n            DLIB_TEST_MSG(rs_neg.mean() < 0.05, rs_neg.mean());\n            rs_pos.clear();\n            rs_neg.clear();\n\n        }\n    } a;\n\n}\n\n\n", "meta": {"hexsha": "e8a24829a9db95a232ec2226620ef80d1f46a1de", "size": 3572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/dlib/test/probabilistic.cpp", "max_stars_repo_name": "maxmert/nlp-mitie", "max_stars_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "dlib/test/probabilistic.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "dlib/test/probabilistic.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 28.8064516129, "max_line_length": 99, "alphanum_fraction": 0.5072788354, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5427564252887132}}
{"text": "/* \n * Copyright (c) 2006-2012 Nicholas Devenish\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * 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, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN 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 SOFTWARE.\n * \n */\n\n\n#ifndef RANDOM_H\n#define RANDOM_H\n\n#include <iostream>\n#include <ctime> // For time()\n\n\n#include \"random.h\"\n\n#include <boost/random.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nusing boost::mt11213b;\nusing std::cout;\nusing std::endl;\n\nstatic mt11213b rng;\nstatic boost::uniform_real<> uni_r(0,1);\nstatic boost::normal_distribution<> norm_r(0,1);\n\nstatic boost::variate_generator<mt11213b&, boost::uniform_real<> > uni(rng, uni_r);\nstatic boost::variate_generator<mt11213b&, boost::normal_distribution<> > norm(rng, norm_r);\n\n// Initialise the random number generator\n//initrn initirandomm();\nnamespace nsl{\n\t\nvoid seedrand()\n{\n\tcout << \"Initialising random number generator...\" << endl;\n\trng.seed(static_cast<unsigned> (std::time(0)));\n}\n\nlong double rand_uniform()\n{\n\treturn uni();\n}\n\nlong double rand_normal()\n{\n\treturn norm();\n}\n\n}\n\n#endif\n", "meta": {"hexsha": "0972019c056828761f08b70e0c0dd35178625770", "size": 2073, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/random.cpp", "max_stars_repo_name": "ndevenish/nsl", "max_stars_repo_head_hexsha": "03dd69ce39258cad0547b968c062074e4b90fdf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/random.cpp", "max_issues_repo_name": "ndevenish/nsl", "max_issues_repo_head_hexsha": "03dd69ce39258cad0547b968c062074e4b90fdf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/random.cpp", "max_forks_repo_name": "ndevenish/nsl", "max_forks_repo_head_hexsha": "03dd69ce39258cad0547b968c062074e4b90fdf0", "max_forks_repo_licenses": ["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.7916666667, "max_line_length": 92, "alphanum_fraction": 0.7477086348, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5427564200440753}}
{"text": "#ifndef CX_SVD_HPP\n#define CX_SVD_HPP\n\n#include \"print.hpp\"\n//#include \"cx_modify.hpp\"\n#include \"sub.hpp\"\n#include \"../tools.hpp\"\n// #include \"cx_multiply.hpp\"\n// #include \"cx_special.hpp\"\n\n#include <mkl.h>\n\n#include <boost/timer/timer.hpp>\n#include <boost/chrono.hpp>\n\n#include <vector>\n#include <utility>\n#include <complex>\n\n// inline bool comparator ( const max_pair& l, const max_pair& r) { return l.first > r.first; }\n\nnamespace dqmc {\n    namespace la {\n\n\tinline perm_mat cx_find_col_perm(cx_mat&__restrict in,\n\t\t\t\t\t cx_mat&__restrict out) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\t    mat_t::Index min_col;\n\t    ivec col_ids(in.cols());\n\t    for (int i = 0; i < in.rows(); ++i) {\n\t\tin.col(i).cwiseAbs().minCoeff(&min_col);\n\t\tcout << min_col << endl;\n\t\tcol_ids[i] = int(min_col) - 1;\n\t    }\n\t    // for (std::vector<max_pair>::iterator it=min_indices.begin();\n\t    // \t it != min_indices.end(); ++it) {\n\t    // \tcol_ids((*it).second) = std::distance(min_indices.begin(), it);\n\t    // \t// cout << row_ids((*it).second) <<  \" \";\n\t    // }\n\t    // // cout << endl;\n\t    perm_mat col_perm(col_ids);\n\t    \n\t    out = in * col_perm.transpose();\n\t    return col_perm;\n\t}\n\t\n\tinline perm_mat cx_row_sort(cx_mat&__restrict in, cx_mat&__restrict out) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\t    vector<int> max_index(in.rows());\n\t    vector<max_pair> max_indices;\n\t    vec max_vals(in.rows());\n\t    mat A = in.cwiseAbs().real().cast<double>();\n\t    \n\t    for(int i = 0; i < in.rows(); ++i) {\n\t\tmax_vals(i) = A.cwiseAbs().real().row(i).maxCoeff( &max_index[i] );\n\t\tmax_indices.push_back(max_pair(max_vals(i), i));\n\t    }\n\t    std::sort(max_indices.begin(), max_indices.end(), comparator);\n\n\t    ivec row_ids(in.rows());\n\t    for (std::vector<max_pair>::iterator it=max_indices.begin(); it != max_indices.end(); ++it) {\n\t\trow_ids((*it).second) = std::distance(max_indices.begin(), it);\n\t\t// cout << row_ids((*it).second) <<  \" \";\n\t    }\n\t    // cout << endl;\n\t    perm_mat row_perm(row_ids);\n\t    \n\t    out = row_perm * in;\n\t    return row_perm;\n\t}\n\n\n\tinline perm_mat cx_col_sort(cx_mat&__restrict in,\n\t\t\t\t    cx_mat&__restrict out) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\t    vector<int> max_index(in.cols());\n\t    vector<max_pair> max_indices;\n\t    vec max_vals(in.cols());\n\t    mat A = in.cwiseAbs().real().cast<double>();\n\t    for(int i = 0; i < in.cols(); ++i) {\n\t\tmax_vals(i) = A.col(i).maxCoeff( &max_index[i] );\n\t\tmax_indices.push_back(max_pair(max_vals(i), i));\n\t    }\n\t    std::sort(max_indices.begin(), max_indices.end(), comparator);\n\n\t    ivec col_ids(in.cols());\n\t    for (std::vector<max_pair>::iterator it=max_indices.begin();\n\t\t it != max_indices.end(); ++it) {\n\t\tcol_ids((*it).second) = std::distance(max_indices.begin(), it);\n\t\t// cout << row_ids((*it).second) <<  \" \";\n\t    }\n\t    // cout << endl;\n\t    perm_mat col_perm(col_ids);\n\t    \n\t    out = in * col_perm;\n\t    return col_perm;\n\t}\n\n\n\tinline void decompose_svd(cx_mat&__restrict__ in,\n\t\t\t\t  cx_mat&__restrict__ U, \n\t\t\t\t  vec&__restrict__ D,\n\t\t\t\t  cx_mat&__restrict__ T) {\n\t    int lwork = -1;\n\t    int m = in.rows();\n\t    int n = in.cols();\n\t    int lda = m;\n\t    int ldu = m;\n\t    int ldvt = n;\n\t    cx_double wkopt;\n\t    vec_t rwork(5 * m);\n\t    int info = -1;\n\n\t    cx_mat_t U_temp(m, m);\n\t    vec D_temp(m);\n\t    vec_t superb(std::min(m, n) - 1);\n\t    info = LAPACKE_zgesvd( LAPACK_COL_MAJOR, 'A', 'A', m, n, in.data(), m,\n\t\t\t\t   D_temp.data(), U_temp.data(), m, T.data(), n, superb.data());\n\t    U = U_temp.block(0, 0, m, n);\n\t    D = D_temp.segment(0, n);\n\t    // lwork = -1;\n\t    // zgesvd( \"All\", \"All\", &m, &n, in.data(), &lda, D.data(), U.data(), &ldu, T.data(),\n\t    // \t    &ldvt, &wkopt, &lwork,\n\t    // \t    rwork.data(), &info );\n\t    // lwork = int(wkopt.real());\n\t    // cx_vec_t work(lwork);\n\t    // /* Compute SVD */\n\t    // zgesvd( \"All\", \"All\", &m, &n, in.data(), &lda, D.data(), U.data(), &ldu, T.data(), &ldvt, work.data(), &lwork,\n\t    // \t    rwork.data(), &info );\n\n\t    \n\t}\n\n\tinline void decompose_udt_full_piv(cx_mat&__restrict__ in,\n\t\t\t\t\t   cx_mat&__restrict__ U, \n\t\t\t\t\t   vec&__restrict__ D,\n\t\t\t\t\t   cx_mat&__restrict__ T) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\n\t    if (U.rows() != in.rows() || U.cols() != in.cols()) {\n\t\tcout << U.rows() << \" vs. \" << in.rows() << \"\\tand\\t\"\n\t\t     << U.cols() << \" vs. \" << in.cols() << endl;\n\t\tthrow std::runtime_error(\"dimensions of U are wrong\");\n\t    }\n\t    \n\t    if (D.size() != in.cols()) {\n\t\tcout << D.size() << endl;\n\t\tthrow std::runtime_error(\"dimensions of D are wrong\");\n\t    }\n\t    \n\t    if (T.rows() != in.cols() || U.cols() != in.cols()) {\n\t\tcout << T.rows() << \" vs. \" << in.cols() << \"\\tand\\t\"\n\t\t     << U.cols() << \" vs. \" << in.cols() << endl;\n\t\tthrow std::runtime_error(\"dimensions of T are wrong\");\n\t    }\n\n\t    cx_mat_t scaled_in = in;\n\t    // perm_mat row_perm = dqmc::la::cx_row_sort(in, scaled_in);\n\t    // perm_mat col_perm = dqmc::la::cx_col_sort(scaled_in, in);\n\t    \n\t    Eigen::FullPivHouseholderQR<cx_mat> qr(in);\n\t     \n\t    qr.compute(in);\n\t    // U = row_perm.inverse() * qr.matrixQ().block(0, 0, in.rows(), in.cols());\n\t    U = qr.matrixQ().block(0, 0, in.rows(), in.cols());\n\t    \n\t    cx_mat upper = qr.matrixQR().triangularView<Upper>();// .block(0, 0, in.cols(), in.cols());\n\t    // cout << \"upper\" << endl << upper << endl << endl;\n\t    D = upper.block(0, 0, in.cols(), in.cols()).diagonal().real().cast<double>();\n\t    vec d_inv = D;\n\t    \n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tif (D(i) == 0.) {\t\t    \n\t\t    // std::cout << \"culprit \" << D(i) << \" was \"\n\t\t    // \t      << upper(i, i) << std::endl;\n\t\t    dqmc::tools::abort(\"Invalid upper triangle\"); }\n\t\t    // throw std::runtime_error(\"Invalid upper triangle\"); }\t\n\t\td_inv(i) = 1./D(i);\n\t\tif (D(i) < 0) { D(i) *= -1.;\n\t\t    d_inv(i) *= -1.; }\n\t    }\n\t    // cout << \"D \" << endl << D.transpose() << endl << endl;\n\t    // cout << \"inv D \" << endl << d_inv.transpose() << endl << endl;\n\t    T = (d_inv.asDiagonal() * upper.block(0, 0, in.cols(), in.cols()))\n\t    \t* qr.colsPermutation().transpose(); // * col_perm.inverse();\n\t    if (D(0) != D(0)) std::cout << \"NaN alert\" << endl;\n\t}\n\n\tinline void decompose_udt_full_sort(cx_mat&__restrict__ in,\n\t\t\t\t\t    cx_mat&__restrict__ U,\n\t\t\t\t\t    vec&__restrict__ D,\n\t\t\t\t\t    cx_mat&__restrict__ T) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\n\t    if (U.rows() != in.rows() || U.cols() != in.cols())\n\t\tthrow std::runtime_error(\"dimensions of U are wrong\");\n\t    \n\t    if (D.size() != in.cols()) {\n\t\tcout << D.size() << endl;\n\t\tthrow std::runtime_error(\"dimensions of D are wrong\");\n\t    }\n\t    \n\t    if (T.rows() != in.cols() || U.cols() != in.cols())\n\t\tthrow std::runtime_error(\"dimensions of T are wrong\");\n\n\t    cx_mat_t scaled_in;// = cx_mat_t::Zero(in.rows(), in.cols());\n\t    scaled_in.fill(cx_double(0., 0.));\n\t    perm_mat row_perm = dqmc::la::cx_row_sort(in, scaled_in);\n\t    perm_mat col_perm = dqmc::la::cx_col_sort(scaled_in, in);\n\t    \n\t    // Very crude scaling...\n\t    //\t    double scale = pow(in.cwiseAbs().maxCoeff(), 0.5);\n\t    double scale = 1.;\n\n\t    cx_vec_t taus(in.cols());\n\t    ivec iwork(in.cols());\n\t    \n\t    // vec work(in.rows() * in.rows() * in.rows());\n\t    int lwork = -1;\n\t    // int info = 0;\n\t    int M = in.rows();\n\t    int N = in.cols();\n\t    \n\t    scaled_in.block(0, 0, in.rows(), in.cols()) = in;\n\n\t    iwork.setZero();\n\t    lapack_int info = LAPACKE_zgeqp3( LAPACK_COL_MAJOR, M, N, scaled_in.data(),\n\t\t\t\t\t      M, iwork.data(), taus.data() );\n\n\t    // cout << iwork.size() << \" \" << work.size() << \" \" << taus.size() << endl;\n\t    // lwork = -1;\n\t    // zgeqp3_(&M, &N, scaled_in.data(), &M, iwork.data(),\n\t    // \t    taus.data(), taus.data(),\n\t    // \t    &lwork, &info);\n\t    // lwork = taus(0);\n\t    // cx_vec_t work(lwork);\n\t    // work.setZero();\n\t    // taus.setZero();\n\t    \n\t    // zgeqp3_(&M, &N, scaled_in.data(), &M, iwork.data(),\n\t    // \t    taus.data(), work.data(),\n\t    // \t    &lwork, &info);\n\n\t    cx_mat_t upper = scaled_in.triangularView<Upper>();\n\t    D = upper.block(0, 0, in.cols(), in.cols()).diagonal().real().cast<double>();\n\t    vec d_inv = D;\n\t    \n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tif (D(i) == 0.) {\t\t    \n\t\t    // std::cout << \"culprit \" << D(i) << \" was \"\n\t\t    // \t      << upper(i, i) << std::endl;\n\t\t    dqmc::tools::abort(\"Invalid upper triangle\"); }\n\t\t    // throw std::runtime_error(\"Invalid upper triangle\"); }\t\n\t\td_inv(i) = 1./D(i);\n\t\tif (D(i) < 0) { D(i) *= -1.;\n\t\t    d_inv(i) *= -1.; }\n\t    }\n\t    lwork = -1;\n\n\t    info = LAPACKE_zungqr( LAPACK_COL_MAJOR, M, N, N,\n\t\t\t\t   scaled_in.data(), M, taus.data() );\n\n\t    // zungqr_(&M, &N, &N, scaled_in.data(), &M, taus.data(),\n\t    // \t    work.data(), &lwork, &info);\n\t    // // if (work(0) > work.size()) {\n\t    // // \tcout << \"Need more lwork for dorgqr\" << endl;\n\t    // // }\n\t    // lwork = work(0);\n\t    // work.resize(lwork);\t    \n\t    // // cout << \"in\" << endl << scaled_in << endl << endl;\n\t    // zungqr_(&M, &N, &N, scaled_in.data(), &M, taus.data(),\n\t    // \t    work.data(), &lwork, &info);\n\t    // cout << \"out\" << endl << scaled_in << endl << endl;\n\t    \n\t    U = row_perm.inverse() * scaled_in.block(0, 0, in.rows(), in.cols());  \n\t    ivec col_ids(in.cols());\n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tcol_ids(i) = iwork(i) - 1;\n\t    }\n\t    \n\t    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> lapack_col_perm(col_ids);\n\t    T = (d_inv.cast<cx_double_t>().asDiagonal()\n\t\t * upper.block(0, 0, in.cols(), in.cols()))\n\t\t* lapack_col_perm.transpose() * col_perm.transpose();\n\t    D *= scale;\n\t    if (D(0) != D(0)) std::cout << \"NaN alert\" << endl;\n\t}\n\n\tinline void decompose_udt_col_piv(cx_mat&__restrict__ in,\n\t\t\t\t\t    cx_mat&__restrict__ U,\n\t\t\t\t\t    vec&__restrict__ D,\n\t\t\t\t\t    cx_mat&__restrict__ T) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\t    if (U.rows() != in.rows() || U.cols() != in.cols() || U.cols() == 0) {\n\t\tcout << U.rows() << \" \" << U.cols() << endl;\n\t\tthrow std::runtime_error(\"dimensions of U are wrong\");\n\t    }\n\t    \n\t    if (D.size() != in.cols() || D.size() == 0) {\n\t\tcout << D.size() << endl;\n\t\tthrow std::runtime_error(\"dimensions of D are wrong\");\n\t    }\n\t    \n\t    if (T.rows() != in.cols() || T.cols() == 0)\n\t\tthrow std::runtime_error(\"dimensions of T are wrong\");\n\n\t    \n\t    cx_mat_t scaled_in = cx_mat_t::Zero(in.rows(), in.cols());\n\t    scaled_in.fill(cx_double(0., 0.));\n\n\t    cx_vec_t taus(in.cols());\n\t    ivec iwork(in.cols());\n\t    \n\t    int lwork = -1;\n\t    int M = in.rows();\n\t    int N = in.cols();\n\t    \n\t    perm_mat row_sort_perm = cx_row_sort(in, scaled_in);\n\t    // scaled_in.block(0, 0, in.rows(), in.cols()) = in;\n\t    iwork.setZero();\n\t    lapack_int info = LAPACKE_zgeqp3( LAPACK_COL_MAJOR, M, N, scaled_in.data(),\n\t\t\t\t\t      M, iwork.data(), taus.data() );\n\t    \n\t    cx_mat_t upper = scaled_in.triangularView<Upper>();\n\t    D = upper.block(0, 0, in.cols(), in.cols()).diagonal().real().cast<double>();\n\t    vec d_inv = D;\n\t    \n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tif (D(i) == 0.) {\t\t    \n\t\t    // std::cout << \"culprit \" << D(i) << \" was \"\n\t\t    // \t      << upper(i, i) << std::endl;\n\t\t    dqmc::tools::abort(\"Invalid upper triangle\");\n\t\t    // throw std::runtime_error(\"Invalid upper triangle\"); \n\t\t}\t\n\t\td_inv(i) = 1./D(i);\n\t\tif (D(i) < 0) { D(i) *= -1.;\n\t\t    d_inv(i) *= -1.; }\n\t    }\n\t    lwork = -1;\n\n\t    info = LAPACKE_zungqr( LAPACK_COL_MAJOR, M, N, N,\n\t\t\t\t   scaled_in.data(), M, taus.data() );\n\n\t    U = (row_sort_perm.inverse() * scaled_in).block(0, 0, in.rows(), in.cols());  \n\t    ivec col_ids(in.cols());\n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tcol_ids(i) = iwork(i) - 1;\n\t    }\n\t    \n\t    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> lapack_col_perm(col_ids);\n\t    T = (d_inv.cast<cx_double_t>().asDiagonal()\n\t\t * upper.block(0, 0, in.cols(), in.cols()))\n\t\t* lapack_col_perm.transpose();\n\t    if (D(0) != D(0)) std::cout << \"NaN alert\" << endl;\n\t}\n\t\n\n\tinline void decompose_udt(cx_mat&__restrict__ in,\n\t\t\t\t  cx_mat&__restrict__ U,\n\t\t\t\t  vec&__restrict__ D,\n\t\t\t\t  cx_mat&__restrict__ T) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\t    if (U.rows() != in.rows() || U.cols() != in.cols() || U.cols() == 0) {\n\t\tcout << U.rows() << \" \" << U.cols() << endl;\n\t\tthrow std::runtime_error(\"dimensions of U are wrong\");\n\t    }\n\t    \n\t    if (D.size() != in.cols() || D.size() == 0) {\n\t\tcout << D.size() << endl;\n\t\tthrow std::runtime_error(\"dimensions of D are wrong\");\n\t    }\n\t    \n\t    if (T.rows() != in.cols() || T.cols() == 0)\n\t\tthrow std::runtime_error(\"dimensions of T are wrong\");\n\n\t    \n\t    cx_mat_t scaled_in = cx_mat_t::Zero(in.rows(), in.cols());\n\t    scaled_in.fill(cx_double(0., 0.));\n\n\t    cx_vec_t taus(in.cols());\n\t    ivec iwork(in.cols());\n\t    \n\t    int lwork = -1;\n\t    int M = in.rows();\n\t    int N = in.cols();\n\t    \n\t    scaled_in.block(0, 0, in.rows(), in.cols()) = in;\n\t    iwork.setZero();\n\n\t    lapack_int info = LAPACKE_zgeqrf( LAPACK_COL_MAJOR, M, N,\n\t\t\t\t\t      scaled_in.data(),\n\t\t\t\t\t      M, taus.data() );\n\t    \n\t    cx_mat_t upper = scaled_in.triangularView<Upper>();\n\t    D = upper.block(0, 0, in.cols(), in.cols()).diagonal().real().cast<double>();\n\t    vec d_inv = D;\n\t    \n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tif (D(i) == 0.) {\t\t \n\t\t    dqmc::tools::abort(\"Invalid upper triangle\");\n\t\t}   \n\t\t    // throw std::runtime_error(\"Invalid upper triangle\"); }\t\n\t\td_inv(i) = 1./D(i);\n\t\tif (D(i) < 0) { D(i) *= -1.;\n\t\t    d_inv(i) *= -1.; }\n\t    }\n\t    lwork = -1;\n\n\t    info = LAPACKE_zungqr( LAPACK_COL_MAJOR, M, N, N,\n\t\t\t\t   scaled_in.data(), M, taus.data() );\n\n\t    U = scaled_in.block(0, 0, in.rows(), in.cols());  \n\t    ivec col_ids(in.cols());\n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tcol_ids(i) = iwork(i) - 1;\n\t    }\n\t    \n\t    T = (d_inv.cast<cx_double_t>().asDiagonal()\n\t\t * upper.block(0, 0, in.cols(), in.cols()));\n\t    if (D(0) != D(0)) std::cout << \"NaN alert\" << endl;\n\t}\n    }\t\n}\n#endif\n", "meta": {"hexsha": "e0391283eac3863f2b5092447f7fd5b404623523", "size": 13977, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libdqmc/la/cx_svd.hpp", "max_stars_repo_name": "pebroecker/DQMC", "max_stars_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "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": "libdqmc/la/cx_svd.hpp", "max_issues_repo_name": "pebroecker/DQMC", "max_issues_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libdqmc/la/cx_svd.hpp", "max_forks_repo_name": "pebroecker/DQMC", "max_forks_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "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.3541666667, "max_line_length": 118, "alphanum_fraction": 0.5375974816, "num_tokens": 4304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5427564095547994}}
{"text": "// Boost.Geometry\n// Unit Test\n\n// Copyright (c) 2019 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\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\n#include <sstream>\n\n#include \"../formulas/test_formula.hpp\"\n#include \"distance_cross_track_cases.hpp\"\n\n#include <boost/geometry/strategies/strategies.hpp>\n#include <boost/geometry/srs/spheroid.hpp>\n\nstruct error{\n    double long_distance;\n    double short_distance;\n    double very_short_distance;\n    double very_very_short_distance;\n};\n\nvoid check_result(double const& result, double const& expected,\n                  double const& reference, error const& reference_error)\n{\n    BOOST_GEOMETRY_CHECK_CLOSE(result, expected, 0.1,\n    std::setprecision(20) << \"result {\" << result\n                          << \"} different than expected {\" << expected << \"}.\");\n\n    double reference_error_value = result > 2000 ? reference_error.long_distance\n                                 : result > 100  ? reference_error.short_distance\n                                 : result > 20   ? reference_error.very_short_distance\n                                 : reference_error.very_very_short_distance;\n\n    BOOST_GEOMETRY_CHECK_CLOSE(result, reference, reference_error_value,\n        std::setprecision(20) << \"result {\" << result\n                              << \"} different than reference {\"\n                              << reference << \"}.\");\n}\n\ntemplate <typename Point>\nvoid test_all(expected_results const& results)\n{\n    double const d2r = bg::math::d2r<double>();\n\n    double lon1r = results.p1.lon * d2r;\n    double lat1r = results.p1.lat * d2r;\n    double lon2r = results.p2.lon * d2r;\n    double lat2r = results.p2.lat * d2r;\n    double lon3r = results.p3.lon * d2r;\n    double lat3r = results.p3.lat * d2r;\n\n    typedef bg::srs::spheroid<double> Spheroid;\n\n    // WGS84\n    Spheroid spheroid(6378137.0, 6356752.3142451793);\n\n    error errors [] =\n    {\n        {0.00000001, 0.00000001, 0.00000001, 0.000001}, //vincenty\n        {0.0002, 0.002, 0.01, 0.2}, //thomas\n        {0.002, 0.4, 15, 25}, //andoyer\n        {1, 6, 15, 200} //spherical\n    };\n\n    //vincenty\n    double distance = bg::strategy::distance::detail::geographic_cross_track<bg::strategy::vincenty, Spheroid, double, true>(spheroid)\n            .apply(Point(lon3r, lat3r), Point(lon1r, lat1r), Point(lon2r, lat2r));\n    check_result(distance, results.vincenty_bisection, results.reference, errors[0]);\n\n    distance = bg::strategy::distance::geographic_cross_track<bg::strategy::vincenty, Spheroid, double>(spheroid)\n            .apply(Point(lon3r, lat3r), Point(lon1r, lat1r), Point(lon2r, lat2r));\n    check_result(distance, results.vincenty, results.reference, errors[0]);\n\n    //thomas\n    distance = bg::strategy::distance::detail::geographic_cross_track<bg::strategy::thomas, Spheroid, double, true>(spheroid)\n            .apply(Point(lon3r, lat3r), Point(lon1r, lat1r), Point(lon2r, lat2r));\n    check_result(distance, results.thomas_bisection, results.reference, errors[1]);\n\n    distance = bg::strategy::distance::geographic_cross_track<bg::strategy::thomas, Spheroid, double>(spheroid)\n            .apply(Point(lon3r, lat3r), Point(lon1r, lat1r), Point(lon2r, lat2r));\n    check_result(distance, results.thomas, results.reference, errors[1]);\n\n    //andoyer\n    distance = bg::strategy::distance::detail::geographic_cross_track<bg::strategy::andoyer, Spheroid, double, true>(spheroid)\n            .apply(Point(lon3r, lat3r), Point(lon1r, lat1r), Point(lon2r, lat2r));\n    check_result(distance, results.andoyer_bisection, results.reference, errors[2]);\n\n    distance = bg::strategy::distance::geographic_cross_track<bg::strategy::andoyer, Spheroid, double>(spheroid)\n            .apply(Point(lon3r, lat3r), Point(lon1r, lat1r), Point(lon2r, lat2r));\n    check_result(distance, results.andoyer, results.reference, errors[2]);\n\n    //spherical\n    distance = bg::strategy::distance::cross_track<>(bg::formula::mean_radius<double>(spheroid))\n            .apply(Point(lon3r, lat3r), Point(lon1r, lat1r), Point(lon2r, lat2r));\n    check_result(distance, results.spherical, results.reference, errors[3]);\n\n}\n\nint test_main(int, char*[])\n{\n    typedef bg::model::point<double, 2, bg::cs::geographic<bg::radian> > point;\n\n    for (size_t i = 0; i < expected_size; ++i)\n    {\n        test_all<point>(expected[i]);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "3ec098c859ecc049d4d27b17f32213ab0bcca2e6", "size": 4630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/strategies/distance_cross_track.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": "test/strategies/distance_cross_track.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": "test/strategies/distance_cross_track.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": 39.5726495726, "max_line_length": 134, "alphanum_fraction": 0.6663066955, "num_tokens": 1278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.54272017246097}}
{"text": "// -*- mode: c++; indent-tabs-mode: nil; -*-\n//\n// Copyright (c) 2009-2013 Illumina, Inc.\n//\n// This software is provided under the terms and conditions of the\n// Illumina Open Source Software License 1.\n//\n// You should have received a copy of the Illumina Open Source\n// Software License 1 along with this program. If not, see\n// <https://github.com/sequencing/licenses/>\n//\n\n/// \\file\n\n/// \\author Chris Saunders\n///\n#include \"blt_util/stat_util.hh\"\n\n#include <boost/math/distributions/chi_squared.hpp>\n\n\n\nbool\nis_chi_sqr_reject(const double xsq,\n                  const unsigned df,\n                  const double alpha) {\n\n    assert(xsq>=0);\n    assert(df>0);\n\n    boost::math::chi_squared dist(df);\n    return ((1.-boost::math::cdf(dist,xsq)) < alpha);\n\n#if 0\n    // alternate implementation (is one faster?):\n    const double xsq_crit_val(boost::math::quantile(dist,1.-alpha));\n    return xsq>xsq_crit_val;\n#endif\n}\n\n\n\nbool\nis_lrt_reject_null(const double null_loghood,\n                   const double alt_loghood,\n                   const unsigned df,\n                   const double alpha) {\n\n    if (df == 0) return false;\n    if (null_loghood>alt_loghood) return false;\n\n    const double log_lrt(-2.*(null_loghood-alt_loghood));\n\n    return is_chi_sqr_reject(log_lrt,df,alpha);\n}\n", "meta": {"hexsha": "fd7501837dd998d5cdf7db1611c44d33be0084b9", "size": 1292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isaac_variant_caller/src/lib/blt_util/stat_util.cpp", "max_stars_repo_name": "sequencing/isaac_variant_caller", "max_stars_repo_head_hexsha": "ed24e20b097ee04629f61014d3b81a6ea902c66b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-01-09T01:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-04T03:48:21.000Z", "max_issues_repo_path": "isaac_variant_caller/src/lib/blt_util/stat_util.cpp", "max_issues_repo_name": "sequencing/isaac_variant_caller", "max_issues_repo_head_hexsha": "ed24e20b097ee04629f61014d3b81a6ea902c66b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-07-23T09:38:39.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-01T05:37:26.000Z", "max_forks_repo_path": "isaac_variant_caller/src/lib/blt_util/stat_util.cpp", "max_forks_repo_name": "sequencing/isaac_variant_caller", "max_forks_repo_head_hexsha": "ed24e20b097ee04629f61014d3b81a6ea902c66b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:41:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T02:42:32.000Z", "avg_line_length": 23.0714285714, "max_line_length": 68, "alphanum_fraction": 0.649380805, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.542706177386298}}
{"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  Vector3d v = Vector3d::Random(), w;\nProjective3d P(Matrix4d::Random());\ncout << \"v                                   = [\" << v.transpose() << \"]^T\" << endl;\ncout << \"h.homogeneous()                     = [\" << v.homogeneous().transpose() << \"]^T\" << endl;\ncout << \"(P * v.homogeneous())               = [\" << (P * v.homogeneous()).transpose() << \"]^T\" << endl;\ncout << \"(P * v.homogeneous()).hnormalized() = [\" << (P * v.homogeneous()).eval().hnormalized().transpose() << \"]^T\" << endl;\n  return 0;\n}\n", "meta": {"hexsha": "801c868918fdb050270c78e1cfc602ca32c9b9e4", "size": 706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_MatrixBase_homogeneous.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_homogeneous.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_homogeneous.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": 30.6956521739, "max_line_length": 125, "alphanum_fraction": 0.5481586402, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5427061551561617}}
{"text": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & ,\n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   //===========fill the vector with data====================\n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; //these items will make up the optimal value\n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ;\n\t si != bestItems.end( ) ; si++ ) {\n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   //dynamic programming approach sacrificing storage space for execution\n   //time , creating a table of optimal values for every weight and a\n   //second table of sets with the items collected so far in the knapsack\n   //the best value is in the bottom right corner of the values table,\n   //the set of items in the bottom right corner of the sets' table.\n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ;\n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { // weight >= itemweight\n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] +\n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] =\n\t\t       bestValues[ i - 1 ][ weight - itemweight ] +\n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] =\n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n", "meta": {"hexsha": "2bdb241a0396d883c7fcaa7929115ba0bdd45ebd", "size": 4531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/knapsack-problem-0-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++/knapsack-problem-0-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++/knapsack-problem-0-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": 45.7676767677, "max_line_length": 138, "alphanum_fraction": 0.5824321342, "num_tokens": 1412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5427061547981331}}
{"text": "#include <sparse.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\nBOOST_AUTO_TEST_SUITE(SPARSE);\n\nBOOST_AUTO_TEST_CASE(inverse_test)\n{    \n  typedef sparse::Block<1,1,float>   block_type;\n  typedef sparse::DiagonalMatrix<block_type> matrix_type;\n  \n  matrix_type D;\n  \n  D.resize(4);\n  \n  D(0) =  2.0;\n  D(1) =  4.0;\n  D(2) =  8.0;\n  D(3) = 16.0;\n\n  sparse::inverse( D );\n  \n  BOOST_CHECK( D(0) == 1.0f/2.0f );\n  BOOST_CHECK( D(1) == 1.0f/4.0f );\n  BOOST_CHECK( D(2) == 1.0f/8.0f );\n  BOOST_CHECK( D(3) == 1.0f/16.0f );\n         \n}\n\nBOOST_AUTO_TEST_SUITE_END();", "meta": {"hexsha": "1703f2b90f9c45138febf2f6d57969ca32fe42cf", "size": 718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_inverse/sparse_inverse.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_inverse/sparse_inverse.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_inverse/sparse_inverse.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1176470588, "max_line_length": 57, "alphanum_fraction": 0.6615598886, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5427061544401041}}
{"text": "#pragma once\n\n#include <armadillo>\n#include <iostream>\n#include \"shannonEntropy.hpp\"\n#include <Eigen/Dense>\n \n// using Eigen::ArrayXi;\n\nusing ArrayXL = Eigen::Array<int64_t, Eigen::Dynamic, 1>; \n\nusing namespace std;\n// using namespace arma;\n\n// static_assert(sizeof(sword) ==8); //findHFPair works on the assumption that arma::sword is 64 bit\n\nstruct ETC {\n\n    union pair {\n        struct {\n            uint64_t i1;\n            uint64_t i2;\n        } __attribute__((packed));\n        __int128 i128;\n\n        bool operator==(const pair& other)\n        {\n            return i128 == other.i128;\n        }\n    };\n    \n   static ETC::pair makeETCPair (uint64_t a, uint64_t b) {ETC::pair p; p.i1 = a; p.i2 = b; return p;};\n\n   typedef unordered_map<__int128, unsigned int> pairFreqTable;\n\n\n    static ETC::pair findHFPair(const ArrayXL &seq) {\n        /*\n         this implementation works very slightly differently from the matlab original where more that one pair wins the highest frequency\n         - the matlab version depends on arbitrary behaviour of max(x)\n         [m,indx]=max(Count_Array(:));\n         i.e. chooses winner based on first position in 2d frequency matrix\n         whereas this version chooses the first winner in the order of the array, which is slightly faster\n         tests show this occasionally makes very minor differences in the results\n         */\n        ETC::pairFreqTable histo;\n        ETC::pair winner;\n        unsigned int highScore=0;\n\n        unsigned int seqPos = 0;\n        while (seqPos < seq.size()-1) {\n            ETC::pair currPair = ETC::makeETCPair(seq[seqPos], seq[seqPos+1]);\n            ETC::pairFreqTable::iterator it = histo.find(currPair.i128);\n            unsigned int score;\n            if (it == histo.end()) {\n                histo.insert(std::make_pair(currPair.i128, 1));\n                score=1;\n            }else{\n                score = it->second + 1;\n               it->second = score;\n            }\n            if (score > highScore) {\n                highScore = score;\n                winner = currPair;\n            }\n            if (currPair.i1 == currPair.i2) {\n                if (seqPos < seq.size()-2) {\n                    if (seq[seqPos+2] == seq[seqPos]) {\n                        seqPos++;\n                    }\n                }\n            }\n            seqPos++;\n        }\n        return winner;\n    }\n    \n\n    static auto substitute(const ArrayXL &seq, ETC::pair p) {\n        int64_t replacementSymbol = seq.maxCoeff() + 1;\n        ArrayXL newSeq(seq.size());\n        size_t src=0, dest=0;\n        size_t replaceCount=0;\n        while(src < seq.size()) {\n            if (src < seq.size()-1) {\n                if (seq[src] == p.i1 && seq[src+1] == p.i2) {\n                    newSeq[dest] = replacementSymbol;\n                    src++;\n                    replaceCount++;\n                } else {\n                    newSeq[dest] = seq[src];\n                }\n            }else{\n                newSeq[dest] = seq[src];\n            }\n            src++;\n            dest++;\n        }\n        ArrayXL finalSeq = newSeq.head(dest);\n        return std::make_tuple(finalSeq, replaceCount, replacementSymbol);\n    }\n\n    // static double calcOld(const ivec &seq) {\n    //     double N = 0; //ETC measure\n    //     double Hnew = shannonEntropy::calc(seq);\n    //     ivec newSeq = seq;\n        \n    //     //todo: this can be optimised by continually editing the shannon histo instead of redoing it every time\n    //     while(Hnew >1e-6 && newSeq.size() > 1) {\n    //         ETC::pair hfPair = ETC::findHFPair(newSeq);\n    //         auto [newSeqRepl, replaceCount, replaceSym] = ETC::substitute(newSeq, hfPair);\n    //         Hnew = shannonEntropy::calc(newSeqRepl);\n    //         newSeq = newSeqRepl;\n    //         N++;\n    //         // cout << newSeq << endl;\n    //         // cout << N << \", \" << Hnew << endl;\n    //     }\n        \n    //     return N;\n    // }\n    \n    static double calc(const ArrayXL &seq) {\n        double N = 0; //ETC measure\n//        cout << seq << endl;\n        if (seq.size() > 1) {\n            shannonEntropy::histoMap histo = shannonEntropy::calcDistribution(seq);\n            double Hnew = shannonEntropy::calcProbability(histo, seq);\n\n            ArrayXL newSeq = seq;\n            \n            while(Hnew >1e-6 && newSeq.size() > 1) {\n                ETC::pair hfPair = ETC::findHFPair(newSeq);\n                auto [newSeqRepl, replaceCount, replaceSym] = ETC::substitute(newSeq, hfPair);\n                //reduce counts of replacement pair\n                shannonEntropy::histoMap::iterator it = histo.find(hfPair.i1);\n                it->second -= replaceCount;\n                if (it->second == 0) {\n                    //remove from the histo\n                    histo.erase(it);\n                }\n                it = histo.find(hfPair.i2);\n                it->second -= replaceCount;\n                if (it->second == 0) {\n                    //remove from the histo\n                    histo.erase(it);\n                }\n                //add the new symbol into the histogram\n                auto histoEntry = make_pair(replaceSym, replaceCount);\n                histo.insert(histoEntry);\n                \n                \n                Hnew = shannonEntropy::calcProbability(histo, newSeqRepl);\n                newSeq = newSeqRepl;\n                N++;\n            }\n            N /= (seq.size() -1);\n        }\n        return N;\n    }\n    \n    static double calcJoint(const ArrayXL& seq1, const ArrayXL& seq2) {\n        \n        ArrayXL combSeq(seq1.size());\n        for (size_t i=0; i < seq1.size(); i++) {\n            combSeq[i] =(uint64_t)( seq1[i] | (seq2[i] << 32));\n        }\n        return ETC::calc(combSeq);\n    }\n\n};\n", "meta": {"hexsha": "28f11e6d59aa44b983e46482cb35f3df9cd3b724", "size": 5754, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ETC.hpp", "max_stars_repo_name": "chriskiefer/libcccrt", "max_stars_repo_head_hexsha": "e05edc8ed65cecc5515ccb5469e4c73fc4549231", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-19T23:16:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T03:20:15.000Z", "max_issues_repo_path": "ETC.hpp", "max_issues_repo_name": "chriskiefer/libcccrt", "max_issues_repo_head_hexsha": "e05edc8ed65cecc5515ccb5469e4c73fc4549231", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ETC.hpp", "max_forks_repo_name": "chriskiefer/libcccrt", "max_forks_repo_head_hexsha": "e05edc8ed65cecc5515ccb5469e4c73fc4549231", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.649122807, "max_line_length": 137, "alphanum_fraction": 0.5034758429, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5427061489720774}}
{"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_HYPERBOLIC_HPP_INCLUDED\n#define BOOST_SIMD_HYPERBOLIC_HPP_INCLUDED\n\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-functions\n    @defgroup group-hyperbolic  Hyperbolic functions\n\n    These functions provides scalar and SIMD version of\n    hyperbolic  and inverse hyperbolic functions.\n\n    - Direct hyperbolic functors\n\n       <center>\n         | name          | name         | name           | name         |\n         |:-------------:|:------------:|:--------------:|:------------:|\n         | @ref cosh     | @ref csch    | @ref sinh      | @ref sinhcosh|\n         | @ref coth     | @ref sech    | @ref sinhc     | @ref tanh    |\n       </center>\n\n          @ref sinhc is the hyperbolic sinus cardinal function\n          (\\f$\\sinh x/x\\f$).\n\n          @ref sinhcosh  allows the simultaneous\n          computation of hyperbolic sine and cosine at lower cost.\n\n          @ref sech and @ref csch are the hyperbolic secant (inverse of\n          the hyperbolic cosine) and cosecant (inverse of the hyperbolic sine)\n\n    - Inverse hyperbolic functors\n\n       <center>\n         | name        | name         | name        |\n         |:-----------:|:------------:|:-----------:|\n         | @ref acosh  | @ref acsch   | @ref asinh  |\n         | @ref acoth  | @ref asech   | @ref atanh  |\n       </center>\n    **/\n\n} }\n\n#include <boost/simd/function/acosh.hpp>\n#include <boost/simd/function/acoth.hpp>\n#include <boost/simd/function/acsch.hpp>\n#include <boost/simd/function/asech.hpp>\n#include <boost/simd/function/asinh.hpp>\n#include <boost/simd/function/atanh.hpp>\n#include <boost/simd/function/cosh.hpp>\n#include <boost/simd/function/coth.hpp>\n#include <boost/simd/function/csch.hpp>\n#include <boost/simd/function/sech.hpp>\n#include <boost/simd/function/sinhc.hpp>\n#include <boost/simd/function/sinhcosh.hpp>\n#include <boost/simd/function/sinh.hpp>\n#include <boost/simd/function/tanh.hpp>\n\n#endif\n", "meta": {"hexsha": "ef45e4030b5d22b8e29d2e235eb0966453fca352", "size": 2315, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/hyperbolic.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/hyperbolic.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/hyperbolic.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": 33.0714285714, "max_line_length": 100, "alphanum_fraction": 0.5555075594, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5427061489720773}}
{"text": "#include <boost/config.hpp>\n#include <boost/version.hpp>\n#include <fstream>\n\n// CGAL headers\n#include <CGAL/Cartesian.h>\n#include <CGAL/MP_Float.h>\n#include <CGAL/Algebraic_kernel_for_circles_2_2.h>\n#include <CGAL/Circular_kernel_2.h>\n#include <CGAL/intersections.h>\n#include <CGAL/Circular_kernel_2.h>\n#include <CGAL/Object.h>\n#include <CGAL/IO/WKT.h>\n\n// Qt headers\n#include <QtGui>\n#include <QString>\n#include <QActionGroup>\n#include <QFileDialog>\n#include <QInputDialog>\n\n// GraphicsView items and event filters (input classes)\n#include <CGAL/Qt/GraphicsViewCircularArcInput.h>\n#include \"ArcsGraphicsItem.h\"\n\n// the two base classes\n#include \"ui_Circular_kernel_2.h\"\n#include <CGAL/Qt/DemosMainWindow.h>\n\ntypedef CGAL::Quotient<CGAL::MP_Float>                       NT;\ntypedef CGAL::Cartesian<NT>                                 Linear_k;\n\ntypedef CGAL::Algebraic_kernel_for_circles_2_2<NT>          Algebraic_k;\ntypedef CGAL::Circular_kernel_2<Linear_k,Algebraic_k>       CircularKernel;\n\ntypedef CircularKernel::Point_2                                 Point_2;\ntypedef CircularKernel::Segment_2                               Segment_2;\ntypedef CircularKernel::Line_arc_2                              Line_arc_2;\ntypedef CircularKernel::Circular_arc_2                          Circular_arc_2;\ntypedef CircularKernel::Circular_arc_point_2                    Circular_arc_point_2;\n\n\ntypedef CGAL::Qt::ArcsGraphicsItem<CircularKernel>                 ArcsGraphicsItem;\n\n\ntypedef std::vector<CGAL::Object>                           ArcContainer;\n\nclass MainWindow :\n  public CGAL::Qt::DemosMainWindow,\n  public Ui::Circular_kernel_2\n{\n  Q_OBJECT\n\nprivate:\n  ArcContainer arcs;\n  ArcContainer intersections;\n  QGraphicsScene scene;\n\n  ArcsGraphicsItem * agi;\n\n\n  CGAL::Qt::GraphicsViewCircularArcInput<CircularKernel> * cai;\n\npublic:\n  MainWindow();\n\npublic Q_SLOTS:\n\n  virtual void open(QString);\n\n  void processInput(CGAL::Object o);\n\n\n  void on_actionInsertCircularArc_toggled(bool checked);\n\n  void on_actionClear_triggered();\n\n  void on_actionLoadLineAndCircularArcs_triggered();\n\n  void on_actionRecenter_triggered();\n\n\nQ_SIGNALS:\n  void changed();\n};\n\n\nMainWindow::MainWindow()\n  : DemosMainWindow()\n{\n  setupUi(this);\n\n  // Add a GraphicItem for the Circular triangulation\n  agi = new CGAL::Qt::ArcsGraphicsItem<CircularKernel>(arcs, intersections);\n\n  agi->setIntersectionsPen(QPen(Qt::red, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n\n  QObject::connect(this, SIGNAL(changed()),\n                   agi, SLOT(modelChanged()));\n\n  agi->setInputPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.addItem(agi);\n  agi->hide();\n\n  // Setup input handlers. They get events before the scene gets them\n  // and the input they generate is passed to the triangulation with\n  // the signal/slot mechanism\n  cai = new CGAL::Qt::GraphicsViewCircularArcInput<CircularKernel>(this, &scene);\n\n  QObject::connect(cai, SIGNAL(generate(CGAL::Object)),\n                   this, SLOT(processInput(CGAL::Object)));\n\n  // Manual handling of actions\n  //\n  QObject::connect(this->actionQuit, SIGNAL(triggered()),\n                   qApp, SLOT(quit()));\n\n  // Check two actions\n  this->actionInsertCircularArc->setChecked(true);\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\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_Circular_kernel_2.html\");\n  this->addAboutCGAL();\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  Circular_arc_2 ca;\n  Line_arc_2 la;\n  bool is_circular = false;\n\n  if(assign(ca, o)){\n    is_circular = true;\n  } else if(! assign(la, o)){\n    std::cerr << \"unknown object\" << std::endl;\n    return;\n  }\n\n  for(std::vector<CGAL::Object>::iterator it = arcs.begin(); it != arcs.end(); ++it){\n    Circular_arc_2 vca;\n    Line_arc_2 vla;\n    if(assign(vca, *it)){\n      if(is_circular){\n        CGAL::intersection(ca, vca, std::back_inserter(intersections));\n      } else {\n        CGAL::intersection(la, vca, std::back_inserter(intersections));\n      }\n    } else if(assign(vla, *it)){\n      if(is_circular){\n        CGAL::intersection(ca, vla, std::back_inserter(intersections));\n      } else {\n        CGAL::intersection(la, vla, std::back_inserter(intersections));\n      }\n    }\n  }\n  arcs.push_back(o);\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_actionInsertCircularArc_toggled(bool checked)\n{\n  if(checked){\n    scene.installEventFilter(cai);\n  } else {\n    scene.removeEventFilter(cai);\n  }\n}\n\nvoid\nMainWindow::on_actionClear_triggered()\n{\n  arcs.clear();\n  intersections.clear();\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionLoadLineAndCircularArcs_triggered()\n{\n  QString fileName = QFileDialog::getOpenFileName(this,\n                                                  tr(\"Open Line and Circular Arc File\"),\n                                                  \".\",\n                                                  tr(\"Edge files (*.arc)\\n\"\n                                                     \"WKT files (*.wkt *.WKT)\\n\"\n                                                     ));\n  if(! fileName.isEmpty()){\n    open(fileName);\n    this->addToRecentFiles(fileName);\n  }\n}\n\n\nvoid\nMainWindow::open(QString fileName)\n{\n    std::ifstream ifs(qPrintable(fileName));\n\n    char c;\n    double x,y;\n    if(fileName.endsWith(\".wkt\", Qt::CaseInsensitive))\n    {\n      //read pairs as Line_arc_2 and triplets as circular_arc_2\n      do\n      {\n        std::vector<Point_2> multi_points;\n        CGAL::IO::read_multi_point_WKT(ifs, multi_points);\n        if(multi_points.size() == 2)\n        {\n          Line_arc_2 la(Segment_2(multi_points[0],\n                        multi_points[1]));\n          for(std::vector<CGAL::Object>::iterator it = arcs.begin(); it != arcs.end(); ++it){\n            Circular_arc_2 vca;\n            Line_arc_2 vla;\n            if(assign(vca, *it)){\n              CGAL::intersection(la, vca, std::back_inserter(intersections));\n            } else if(assign(vla, *it)){\n              CGAL::intersection(la, vla, std::back_inserter(intersections));\n            }\n          }\n          arcs.push_back(make_object(la));\n        }\n        else if(multi_points.size() == 3)\n        {\n          Circular_arc_2 ca(multi_points[0],\n                            multi_points[1],\n                            multi_points[2]);\n          for(std::vector<CGAL::Object>::iterator it = arcs.begin(); it != arcs.end(); ++it){\n            Circular_arc_2 vca;\n            Line_arc_2 vla;\n            if(assign(vca, *it)){\n              CGAL::intersection(ca, vca, std::back_inserter(intersections));\n            } else if(assign(vla, *it)){\n              CGAL::intersection(ca, vla, std::back_inserter(intersections));\n            }\n          }\n          arcs.push_back(make_object(ca));\n        }\n        else if(multi_points.size()>0)\n        {\n          std::cerr<<\"unreadable object.\"<<std::endl;\n        }\n      }while(ifs.good() && !ifs.eof());\n      ifs.close();\n    }\n    else\n    {\n      while(ifs >> c){\n        if(c == 's'){\n          ifs >> x >> y;\n          Point_2 p(x,y);\n          ifs >> x >> y;\n          Point_2 q(x,y);\n\n          Line_arc_2 la(Segment_2(p,q));\n          for(std::vector<CGAL::Object>::iterator it = arcs.begin(); it != arcs.end(); ++it){\n            Circular_arc_2 vca;\n            Line_arc_2 vla;\n            if(assign(vca, *it)){\n              CGAL::intersection(la, vca, std::back_inserter(intersections));\n            } else if(assign(vla, *it)){\n              CGAL::intersection(la, vla, std::back_inserter(intersections));\n            }\n          }\n          arcs.push_back(make_object(la));\n        } else if(c == 'c'){\n          ifs >> x >> y;\n          Point_2 p(x,y);\n          ifs >> x >> y;\n          Point_2 q(x,y);\n          ifs >> x >> y;\n          Point_2 r(x,y);\n          Circular_arc_2 ca(p,q,r);\n          for(std::vector<CGAL::Object>::iterator it = arcs.begin(); it != arcs.end(); ++it){\n            Circular_arc_2 vca;\n            Line_arc_2 vla;\n            if(assign(vca, *it)){\n              CGAL::intersection(ca, vca, std::back_inserter(intersections));\n            } else if(assign(vla, *it)){\n              CGAL::intersection(ca, vla, std::back_inserter(intersections));\n            }\n          }\n          arcs.push_back(make_object(ca));\n        }\n      }\n    }\n    Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionRecenter_triggered()\n{\n  this->graphicsView->setSceneRect(agi->boundingRect());\n  this->graphicsView->fitInView(agi->boundingRect(), Qt::KeepAspectRatio);\n}\n\n\n#include \"Circular_kernel_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(\"Circular_kernel_2 demo\");\n\n  // Import resources from libCGAL (Qt5).\n  CGAL_QT_INIT_RESOURCES;\n\n  MainWindow mainWindow;\n  mainWindow.show();\n  return app.exec();\n}\n", "meta": {"hexsha": "4fa766fb87c91bfbdd9d94fc4882dcb422050078", "size": 9777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GraphicsView/demo/Circular_kernel_2/Circular_kernel_2.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "GraphicsView/demo/Circular_kernel_2/Circular_kernel_2.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "GraphicsView/demo/Circular_kernel_2/Circular_kernel_2.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 28.0948275862, "max_line_length": 93, "alphanum_fraction": 0.6078551703, "num_tokens": 2405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126791, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5427061464170783}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n// Defines the class BulgedCube.\n\n#pragma once\n\n#include <array>\n#include <boost/optional.hpp>\n#include <cstddef>\n#include <limits>\n\n#include \"DataStructures/Tensor/TypeAliases.hpp\"\n#include \"Utilities/TypeTraits/RemoveReferenceWrapper.hpp\"\n\n/// \\cond\nnamespace PUP {\nclass er;\n}  // namespace PUP\n/// \\endcond\n\nnamespace domain {\nnamespace CoordinateMaps {\n\n/*!\n *  \\ingroup CoordinateMapsGroup\n *\n *  \\brief Three dimensional map from the cube to a bulged cube.\n *  The cube is shaped such that the surface is compatible\n *  with the inner surface of Wedge3D.\n *  The shape of the object can be chosen to be cubical,\n *  if the sphericity is set to 0, or to a sphere, if\n *  the sphericity is set to 1. The sphericity can\n *  be set to any number between 0 and 1 for a bulged cube.\n *\n *  \\details The volume map from the cube to a bulged cube is obtained by\n *  interpolating between six surface maps, twelve bounding curves, and\n *  eight corners. The surface map for the upper +z axis is obtained by\n *  interpolating between a cubical surface and a spherical surface. The\n *  two surfaces are chosen such that the latter circumscribes the former.\n *\n *  We make a choice here as to whether we wish to use the logical coordinates\n *  parameterizing these surface as they are, in which case we have the\n *  equidistant choice of coordinates, or whether to apply a tangent map to them\n *  which leads us to the equiangular choice of coordinates. In terms of the\n *  logical coordinates, the equiangular coordinates are:\n *\n *  \\f[\\textrm{equiangular xi} : \\Xi(\\xi) = \\textrm{tan}(\\xi\\pi/4)\\f]\n *\n *  \\f[\\textrm{equiangular eta}  : \\mathrm{H}(\\eta) = \\textrm{tan}(\\eta\\pi/4)\\f]\n *\n *  With derivatives:\n *\n *  \\f[\\Xi'(\\xi) = \\frac{\\pi}{4}(1+\\Xi^2)\\f]\n *\n *  \\f[\\mathrm{H}'(\\eta) = \\frac{\\pi}{4}(1+\\mathrm{H}^2)\\f]\n *\n *  The equidistant coordinates are:\n *\n *  \\f[ \\textrm{equidistant xi}  : \\Xi = \\xi\\f]\n *\n *  \\f[ \\textrm{equidistant eta}  : \\mathrm{H} = \\eta\\f]\n *\n *  with derivatives:\n *\n *  <center>\\f$\\Xi'(\\xi) = 1\\f$, and \\f$\\mathrm{H}'(\\eta) = 1\\f$</center>\n *\n *  We also define the variable \\f$\\rho\\f$, given by:\n *\n *  \\f[\\rho = \\sqrt{1+\\Xi^2+\\mathrm{H}^2}\\f]\n *\n *  ### The Spherical Face Map\n *  The surface map for the spherical face of radius \\f$R\\f$ lying in the\n *  \\f$+z\\f$\n *  direction in either choice of coordinates is then given by:\n *\n *  \\f[\n *  \\vec{\\sigma}_{spherical}(\\xi,\\eta) =\n *  \\begin{bmatrix}\n *  x(\\xi,\\eta)\\\\\n *  y(\\xi,\\eta)\\\\\n *  z(\\xi,\\eta)\\\\\n *  \\end{bmatrix}  = \\frac{R}{\\rho}\n *  \\begin{bmatrix}\n *  \\Xi\\\\\n *  \\mathrm{H}\\\\\n *  1\\\\\n *  \\end{bmatrix}\n *  \\f]\n *\n *  ### The Cubical Face Map\n *  The surface map for the cubical face of side length \\f$2L\\f$ lying in the\n *  \\f$+z\\f$ direction is given by:\n *\n *  \\f[\n *  \\vec{\\sigma}_{cubical}(\\xi,\\eta) =\n *  \\begin{bmatrix}\n *  x(\\xi,\\eta)\\\\\n *  y(\\xi,\\eta)\\\\\n *  L\\\\\n *  \\end{bmatrix}  = L\n *  \\begin{bmatrix}\n *  \\Xi\\\\\n *  \\mathrm{H}\\\\\n *  1\\\\\n *  \\end{bmatrix}\n *  \\f]\n *\n *  ### The Bulged Face Map\n *  To construct the bulged map we interpolate between a cubical face map of\n *  side length \\f$2L\\f$ and a spherical face map of radius \\f$R\\f$, with the\n *  interpolation parameter being \\f$s\\f$, the `sphericity`.\n *  The surface map for the bulged face lying in the \\f$+z\\f$ direction is then\n *  given by:\n *\n *  \\f[\n *  \\vec{\\sigma}_{+\\zeta}(\\xi,\\eta) = \\left\\{(1-s)L + \\frac{sR}{\\rho}\\right\\}\n *  \\begin{bmatrix}\n *  \\Xi\\\\\n *  \\mathrm{H}\\\\\n *  1\\\\\n *  \\end{bmatrix}\n *  \\f]\n *\n *  This equation defines the upper-z map \\f$\\vec{\\sigma}_{+\\zeta}\\f$, and we\n *  similarly define the other five surface maps \\f$\\vec{\\sigma}_{+\\eta}\\f$,\n *  \\f$\\vec{\\sigma}_{+\\xi}\\f$, and so on by appropriate rotations.\n *  We constrain L by demanding that the spherical face circumscribe the cube.\n *  With this condition, we have \\f$L = R/\\sqrt3\\f$.\n *\n *  ### The General Formula for 3D Isoparametric Maps\n *  The general formula is given by Eq. 1 in section 2.1 of Hesthaven's paper\n *  \"A Stable Penalty Method For The Compressible Navier-Stokes Equations III.\n *  Multidimensional Domain Decomposition Schemes\" available\n *  <a href=\"\n *  http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.699.1161&rep=rep1&type=pdf\n *  \"> here </a>.\n *\n *  Hesthaven's formula is general in the degree of the shape functions used,\n *  so for our purposes we take the special case where the shape functions are\n *  linear in the interpolation variable, and define new variables accordingly.\n *  However, our interpolation variables do not necessarily have to be the\n *  logical coordinates themselves, though they often are. To make this\n *  distinction clear, we will define the new interpolation variables\n *  \\f$\\{\\tilde{\\xi},\\tilde{\\eta},\\tilde{\\zeta}\\}\\f$, which may either be the\n *  logical coordinates themselves or a invertible transformation of them. For\n *  the purposes of the bulged cube map, this transformation will be the same\n *  transformation that takes the logical coordinates into the equiangular\n *  coordinates. We will later see how this choice can lead to simplifications\n *  in the final map.\n *\n *  We define the following variables for\n *  \\f$\\alpha, \\beta, \\gamma \\in\\{\\tilde{\\xi},\\tilde{\\eta},\\tilde{\\zeta}\\}\\f$:\n *\n *  \\f[\n *  f^{\\pm}_{\\alpha} = \\frac{1}{2}(1\\pm\\alpha)\\\\\n *  f^{\\pm\\pm}_{\\alpha \\ \\beta} = \\frac{1}{4}(1\\pm\\alpha)(1\\pm\\beta)\\\\\n *  f^{\\pm\\pm\\pm}_{\\alpha \\ \\beta \\ \\gamma} =\n *  \\frac{1}{8}(1\\pm\\alpha)(1\\pm\\beta)(1\\pm\\gamma)\n *  \\f]\n *\n *  The formula involves six surfaces, which we will denote by\n *  \\f$\\vec{\\sigma}\\f$, twelve curves, denoted by \\f$\\vec{\\Gamma}\\f$, and eight\n *  vertices, denoted by \\f$\\vec{\\pi}\\f$, with the subscripts denoting which\n *  face(s) these objects belong to. The full volume map is given by:\n *\n *  \\f{align*}\n *  \\vec{x}(\\xi,\\eta,\\zeta) = &\n *  f^{+}_{\\tilde{\\zeta}}\\vec{\\sigma}_{+\\zeta}(\\xi, \\eta)+\n *  f^{-}_{\\tilde{\\zeta}}\\vec{\\sigma}_{-\\zeta}(\\xi, \\eta)\\\\\n *  &+ f^{+}_{\\tilde{\\eta}}\\vec{\\sigma}_{+\\eta}(\\xi, \\zeta)+\n *  f^{-}_{\\tilde{\\eta}}\\vec{\\sigma}_{-\\eta}(\\xi, \\zeta)+\n *  f^{+}_{\\tilde{\\xi}}\\vec{\\sigma}_{+\\xi}(\\eta, \\zeta)+\n *  f^{-}_{\\tilde{\\xi}}\\vec{\\sigma}_{-\\xi}(\\eta, \\zeta)\\\\\n *  &- f^{++}_{\\tilde{\\xi} \\ \\tilde{\\eta}}\\vec{\\Gamma}_{+\\xi +\\eta}(\\zeta)-\n *  f^{-+}_{\\tilde{\\xi} \\ \\tilde{\\eta}}\\vec{\\Gamma}_{-\\xi +\\eta}(\\zeta)-\n *  f^{+-}_{\\tilde{\\xi} \\ \\tilde{\\eta}}\\vec{\\Gamma}_{+\\xi -\\eta}(\\zeta)-\n *  f^{--}_{\\tilde{\\xi} \\ \\tilde{\\eta}}\\vec{\\Gamma}_{-\\xi -\\eta}(\\zeta)\\\\\n *  &- f^{++}_{\\tilde{\\xi} \\ \\tilde{\\zeta}}\\vec{\\Gamma}_{+\\xi +\\zeta}(\\eta)-\n *  f^{-+}_{\\tilde{\\xi} \\ \\tilde{\\zeta}}\\vec{\\Gamma}_{-\\xi +\\zeta}(\\eta)-\n *  f^{+-}_{\\tilde{\\xi} \\ \\tilde{\\zeta}}\\vec{\\Gamma}_{+\\xi -\\zeta}(\\eta)-\n *  f^{--}_{\\tilde{\\xi} \\ \\tilde{\\zeta}}\\vec{\\Gamma}_{-\\xi -\\zeta}(\\eta)\\\\\n *  &- f^{++}_{\\tilde{\\eta} \\ \\tilde{\\zeta}}\\vec{\\Gamma}_{+\\eta +\\zeta}(\\xi)-\n *  f^{-+}_{\\tilde{\\eta} \\ \\tilde{\\zeta}}\\vec{\\Gamma}_{-\\eta +\\zeta}(\\xi)-\n *  f^{+-}_{\\tilde{\\eta} \\ \\tilde{\\zeta}}\\vec{\\Gamma}_{+\\eta -\\zeta}(\\xi)-\n *  f^{--}_{\\tilde{\\eta} \\tilde{\\zeta}}\\vec{\\Gamma}_{-\\eta -\\zeta}(\\xi)\\\\\n *  &+ f^{+++}_{\\tilde{\\xi} \\ \\tilde{\\eta} \\ \\tilde{\\zeta}}\\vec{\\pi}_{+\\xi +\\eta\n * +\\zeta}+ f^{-++}_{\\tilde{\\xi} \\ \\tilde{\\eta} \\ \\tilde{\\zeta}}\\vec{\\pi}_{-\\xi\n * +\\eta +\\zeta}+ f^{+-+}_{\\tilde{\\xi} \\ \\tilde{\\eta} \\\n * \\tilde{\\zeta}}\\vec{\\pi}_{+\\xi -\\eta +\\zeta}+\n *  f^{--+}_{\\tilde{\\xi} \\ \\tilde{\\eta} \\ \\tilde{\\zeta}}\\vec{\\pi}_{-\\xi -\\eta\n * +\\zeta}\\\\\n *  &+ f^{++-}_{\\tilde{\\xi} \\ \\tilde{\\eta} \\ \\tilde{\\zeta}}\\vec{\\pi}_{+\\xi +\\eta\n * -\\zeta}+ f^{-+-}_{\\tilde{\\xi} \\ \\tilde{\\eta} \\ \\tilde{\\zeta}}\\vec{\\pi}_{-\\xi\n * +\\eta -\\zeta}+ f^{+--}_{\\tilde{\\xi} \\ \\tilde{\\eta} \\\n * \\tilde{\\zeta}}\\vec{\\pi}_{+\\xi -\\eta -\\zeta}+ f^{---}_{\\tilde{\\xi} \\\n * \\tilde{\\eta} \\ \\tilde{\\zeta}}\\vec{\\pi}_{-\\xi -\\eta -\\zeta} \\f}\n *\n *\n *  ### The Special Case for Octahedral Symmetry\n *  The general formula is for the case in which there are six independently\n *  specified bounding surfaces. In our case, the surfaces are obtained by\n *  rotations and reflections of the upper-\\f$\\zeta\\f$ face.\n *\n * We define the matrices corresponding to these transformations to be:\n *\n * \\f[\n * S_{xy} =\n *  \\begin{bmatrix}\n *  0 & 1 & 0\\\\\n *  1 & 0 & 0\\\\\n *  0 & 0 & 1\\\\\n *  \\end{bmatrix},\\\n *\n * S_{xz} =\n *  \\begin{bmatrix}\n *  0 & 0 & 1\\\\\n *  0 & 1 & 0\\\\\n *  1 & 0 & 0\\\\\n *  \\end{bmatrix},\\\n *\n * S_{yz} =\n *  \\begin{bmatrix}\n *  1 & 0 & 0\\\\\n *  0 & 0 & 1\\\\\n *  0 & 1 & 0\\\\\n *  \\end{bmatrix}\\f]\n *\n * \\f[C_{zxy} =\n *  \\begin{bmatrix}\n *  0 & 0 & 1\\\\\n *  1 & 0 & 0\\\\\n *  0 & 1 & 0\\\\\n *  \\end{bmatrix},\\\n *\n * C_{yzx} =\n *  \\begin{bmatrix}\n *  0 & 1 & 0\\\\\n *  0 & 0 & 1\\\\\n *  1 & 0 & 0\\\\\n *  \\end{bmatrix}\\f]\n *\n * \\f[N_{x} =\n *  \\begin{bmatrix}\n *  -1 & 0 & 0\\\\\n *  0 & 1 & 0\\\\\n *  0 & 0 & 1\\\\\n *  \\end{bmatrix},\\\n *\n * N_{y} =\n *  \\begin{bmatrix}\n *  1 & 0 & 0\\\\\n *  0 & -1 & 0\\\\\n *  0 & 0 & 1\\\\\n *  \\end{bmatrix},\\\n *\n * N_{z} =\n *  \\begin{bmatrix}\n *  1 & 0 & 0\\\\\n *  0 & 1 & 0\\\\\n *  0 & 0 & -1\\\\\n *  \\end{bmatrix}\n *  \\f]\n *\n * The surface maps can now all be written in terms of\n * \\f$\\vec{\\sigma}_{+\\zeta}\\f$ and these matrices:\n * <center>\n * \\f$\\vec{\\sigma}_{-\\zeta}(\\xi, \\eta) = N_z\\vec{\\sigma}_{+\\zeta}(\\xi, \\eta)\\\\\n * \\vec{\\sigma}_{+\\eta}(\\xi, \\zeta) = S_{yz}\\vec{\\sigma}_{+\\zeta}(\\xi, \\zeta)\\\\\n * \\vec{\\sigma}_{-\\eta}(\\xi, \\zeta) = N_yS_{yz}\\vec{\\sigma}_{+\\zeta}(\\xi,\n * \\zeta)\\\\\n * \\vec{\\sigma}_{+\\xi}(\\eta, \\zeta) = C_{zxy}\\vec{\\sigma}_{+\\zeta}(\\eta,\n * \\zeta)\\\\\n * \\vec{\\sigma}_{-\\xi}(\\eta, \\zeta) = N_xC_{zyx}\\vec{\\sigma}_{+\\zeta}(\\eta,\n * \\zeta)\\f$\n * </center>\n *\n * The four bounding curves \\f$\\vec{\\Gamma}\\f$ on the \\f$+\\zeta\\f$ face are\n * given by:\n *\n * <center>\n * \\f$\\vec{\\Gamma}_{+\\xi,+\\zeta}(\\eta) = \\vec{\\sigma}_{+\\zeta}(+1,\\eta)\\\\\n * \\vec{\\Gamma}_{-\\xi,+\\zeta}(\\eta) = \\vec{\\sigma}_{+\\zeta}(-1,\\eta)\n * = N_x\\vec{\\sigma}_{+\\zeta}(+1, \\eta)\\\\\n * \\vec{\\Gamma}_{+\\eta,+\\zeta}(\\xi) = \\vec{\\sigma}_{+\\zeta}(\\xi,+1)\n * = S_{xy}\\vec{\\sigma}_{+\\zeta}(+1, \\xi)\\\\\n * \\vec{\\Gamma}_{-\\eta,+\\zeta}(\\xi) = \\vec{\\sigma}_{+\\zeta}(\\xi,-1)\n * = N_yS_{xy}\\vec{\\sigma}_{+\\zeta}(+1,\\xi)\\f$\n * </center>\n *\n * The bounding curves on the other surfaces can be obtained by transformations\n * on the \\f$+\\zeta\\f$ face:\n *\n * <center>\n * \\f$\\vec{\\Gamma}_{+\\xi,-\\zeta}(\\eta) = N_z\\vec{\\sigma}_{+\\zeta}(+1,\\eta)\\\\\n * \\vec{\\Gamma}_{-\\xi,-\\zeta}(\\eta) = N_z\\vec{\\sigma}_{+\\zeta}(-1,\\eta)\n * = N_zN_x\\vec{\\sigma}_{+\\zeta}(+1,\\eta)\\\\\n * \\vec{\\Gamma}_{+\\eta,-\\zeta}(\\xi) = N_z\\vec{\\sigma}_{+\\zeta}(\\xi,+1)\n * = N_zS_{xy}\\vec{\\sigma}_{+\\zeta}(+1, \\xi)\\\\\n * \\vec{\\Gamma}_{-\\eta,-\\zeta}(\\xi) = N_z\\vec{\\sigma}_{+\\zeta}(\\xi,-1)\n * = N_zN_yS_{xy}\\vec{\\sigma}_{+\\zeta}(+1, \\xi)\\\\\n * \\vec{\\Gamma}_{+\\xi,+\\eta}(\\zeta) =\n * C_{zxy}\\vec{\\sigma}_{+\\zeta}(+1,\\zeta)\\\\\n * \\vec{\\Gamma}_{-\\xi,+\\eta}(\\zeta) =\n * N_xC_{zxy}\\vec{\\sigma}_{+\\zeta}(+1,\\zeta)\\\\\n * \\vec{\\Gamma}_{+\\xi,-\\eta}(\\zeta) = C_{zxy}\\vec{\\sigma}_{+\\zeta}(-1,\\zeta)\n * = C_{zxy}N_x\\vec{\\sigma}_{+\\zeta}(+1,\\zeta)\\\\\n * \\vec{\\Gamma}_{-\\xi,-\\eta}(\\zeta) = N_xC_{zxy}\\vec{\\sigma}_{+\\zeta}(-1,\\zeta)\n * = N_xC_{zxy}N_x\\vec{\\sigma}_{+\\zeta}(+1,\\zeta)\\f$\n * </center>\n *\n * Now we can write the volume map in terms of\n * \\f$\\vec{\\sigma}_{+\\zeta}\\f$ only:\n * \\f{align*}\\vec{x}(\\xi,\\eta,\\zeta) = &\n * (f^{+}_{\\tilde{\\zeta}} + f^{-}_{\\tilde{\\zeta}}N_z)\n * \\vec{\\sigma}_{+\\zeta}(\\xi, \\eta)\\\\\n * &+ (f^{+}_{\\tilde{\\eta}} + f^{-}_{\\tilde{\\eta}}N_y)\n * S_{yz}\\vec{\\sigma}_{+\\zeta}(\\xi, \\zeta)\\\\\n * &+ (f^{+}_{\\tilde{\\xi}} + f^{-}_{\\tilde{\\xi}}N_x)\n * C_{zxy}\\vec{\\sigma}_{+\\zeta}(\\eta, \\zeta)\\\\\n * &- (f^{+}_{\\tilde{\\xi}}+f^{-}_{\\tilde{\\xi}}N_x)\n * (f^{+}_{\\tilde{\\eta}}+f^{-}_{\\tilde{\\eta}}N_y)\n * C_{zxy}\\vec{\\sigma}_{+\\zeta}(+1, \\zeta)\\\\\n * &- (f^{+}_{\\tilde{\\zeta}}+f^{-}_{\\tilde{\\zeta}}N_z)\\left\\{\n * (f^{+}_{\\tilde{\\xi}}+f^{-}_{\\tilde{\\xi}}N_x)\\vec{\\sigma}_{+\\zeta}(+1, \\eta)+\n * (f^{+}_{\\tilde{\\eta}}+f^{-}_{\\tilde{\\eta}}N_y)S_{xy}\\vec{\\sigma}_{+\\zeta}(+1,\n * \\xi)\\right\\}\\\\\n * &+ \\frac{r}{\\sqrt{3}}\\vec{\\tilde{\\xi}}\n *  \\f}\n *\n * Note that we can now absorb all of the \\f$f\\f$s into the matrix prefactors\n * in the above equation and obtain a final set of matrices. We define the\n * following *blending matrices*:\n *\n *  \\f[\n *  B_{\\tilde{\\xi}} =\n *  \\begin{bmatrix}\n *  0 & 0 & \\tilde{\\xi}\\\\\n *  1 & 0 & 0\\\\\n *  0 & 1 & 0\\\\\n *  \\end{bmatrix},\\\n *\n *  B_{\\tilde{\\eta}} =\n *  \\begin{bmatrix}\n *  1 & 0 & 0\\\\\n *  0 & 0 & \\tilde{\\eta}\\\\\n *  0 & 1 & 0\\\\\n *  \\end{bmatrix},\\\n *\n *  B_{\\tilde{\\zeta}} =\n *  \\begin{bmatrix}\n *  1 & 0 & 0\\\\\n *  0 & 1 & 0\\\\\n *  0 & 0 & \\tilde{\\zeta}\\\\\n *  \\end{bmatrix}\\\\\n *\n *  B_{\\tilde{\\xi}\\tilde{\\eta}} =\n *  \\begin{bmatrix}\n *  0 & 0 & \\tilde{\\xi}\\\\\n *  \\tilde{\\eta} & 0 & 0\\\\\n *  0 & 1 & 0\\\\\n *  \\end{bmatrix},\\\n *\n *  B_{\\tilde{\\xi}\\tilde{\\zeta}} =\n *  \\begin{bmatrix}\n *  \\tilde{\\xi} & 0 & 0\\\\\n *  0 & 1 & 0\\\\\n *  0 & 0 & \\tilde{\\zeta}\\\\\n *  \\end{bmatrix},\\\n *\n *  B_{\\tilde{\\eta}\\tilde{\\zeta}} =\n *  \\begin{bmatrix}\n *  0 & 1 & 0\\\\\n *  \\tilde{\\eta} & 0 & 0\\\\\n *  0 & 0 & \\tilde{\\zeta}\\\\\n *  \\end{bmatrix}\\\\\n *\n *  B_{\\tilde{\\xi}\\tilde{\\eta}\\tilde{\\zeta}} =\n *  \\begin{bmatrix}\n *  \\tilde{\\xi} & 0 & 0\\\\\n *  0 & \\tilde{\\eta} & 0\\\\\n *  0 & 0 & \\tilde{\\zeta}\\\\\n *  \\end{bmatrix}\n *  \\f]\n *\n *  Now we can write the volume map in these terms:\n *\n * \\f{align*}\n * \\vec{x}(\\xi,\\eta,\\zeta) = &\n * B_{\\tilde{\\zeta}}\n * \\vec{\\sigma}_{+\\zeta}(\\xi, \\eta)\\\\& +\n * B_{\\tilde{\\eta}}\n * \\vec{\\sigma}_{+\\zeta}(\\xi, \\zeta)+\n * B_{\\tilde{\\xi}}\n * \\vec{\\sigma}_{+\\zeta}(\\eta, \\zeta)\\\\& -\n * B_{\\tilde{\\xi} \\tilde{\\eta}}\n * \\vec{\\sigma}_{+\\zeta}(+1, \\zeta)-\n * B_{\\tilde{\\xi} \\tilde{\\zeta}}\n * \\vec{\\sigma}_{+\\zeta}(+1, \\eta)+\n * B_{\\tilde{\\eta} \\tilde{\\zeta}}\n * \\vec{\\sigma}_{+\\zeta}(+1, \\xi)\\\\& +\n * B_{\\tilde{\\xi} \\tilde{\\eta} \\tilde{\\zeta}}\n * \\vec{\\sigma}_{+\\zeta}(+1, +1)\n * \\f}\n *\n * ### The Bulged Cube Map\n * We now use the result above to provide the mapping for the bulged cube.\n * First we will define the variables \\f$\\rho_A\\f$ and \\f$\\rho_{AB}\\f$, for\n * \\f$A, B \\in \\{\\Xi,\\mathrm{H}, \\mathrm{Z}\\} \\f$, where \\f$\\mathrm{Z}\\f$\n * is \\f$\\tan(\\zeta\\pi/4)\\f$ in the equiangular case and \\f$\\zeta\\f$ in the\n * equidistant case:\n *\n * \\f[\n * \\rho_A = \\sqrt{2 + A^2}\\\\\n * \\rho_{AB} = \\sqrt{1 + A^2 + B^2}\n * \\f]\n * The final mapping is then:\n * \\f[\n * \\vec{x}(\\xi,\\eta,\\zeta) = \\frac{(1-s)R}{\\sqrt{3}}\n * \\begin{bmatrix}\n * \\Xi\\\\\n * \\mathrm{H}\\\\\n * \\mathrm{Z}\\\\\n * \\end{bmatrix} +\n * \\frac{sR}{\\sqrt{3}}\n * \\begin{bmatrix}\n * \\tilde{\\xi}\\\\\n * \\tilde{\\eta}\\\\\n * \\tilde{\\zeta}\\\\\n * \\end{bmatrix} + sR\n * \\begin{bmatrix}\n * \\tilde{\\xi} & \\Xi & \\Xi\\\\\n * \\mathrm{H} & \\tilde{\\eta} &\\mathrm{H}\\\\\n * \\mathrm{Z} & \\mathrm{Z} & \\tilde{\\zeta}\\\\\n * \\end{bmatrix}\n * \\begin{bmatrix}\n * 1/\\rho_{\\mathrm{H}\\mathrm{Z}}\\\\\n * 1/\\rho_{\\Xi\\mathrm{Z}}\\\\\n * 1/\\rho_{\\Xi\\mathrm{H}}\\\\\n * \\end{bmatrix} - sR\n * \\begin{bmatrix}\n * \\Xi & \\tilde{\\xi} & \\tilde{\\xi}\\\\\n * \\tilde{\\eta} & \\mathrm{H} &\\tilde{\\eta}\\\\\n * \\tilde{\\zeta} & \\tilde{\\zeta} & \\mathrm{Z}\\\\\n * \\end{bmatrix}\n * \\begin{bmatrix}\n * 1/\\rho_{\\Xi}\\\\\n * 1/\\rho_{\\mathrm{H}}\\\\\n * 1/\\rho_{\\mathrm{Z}}\\\\\n * \\end{bmatrix}\n * \\f]\n *\n * Recall that the lower case Greek letters with tildes are the variables\n * used for the linear interpolation between the six bounding surfaces, and\n * that the upper case Greek letters are the coordinates along these surfaces -\n * both of which can be specified to be either\n * equidistant or equiangular. In the case where the\n * interpolation variable is chosen to match that of the\n * coordinates along the surface, we have \\f$\\tilde{\\xi} = \\Xi\\f$, etc. In this\n * case, the formula reduces further. The reduced formula below is the one used\n * for this CoordinateMap. It is given by:\n *\n * \\f[\n * \\vec{x}(\\xi,\\eta,\\zeta) =\n * \\left\\{\n * \\frac{R}{\\sqrt{3}}\n * + sR\n * \\left(\n * 1/\\rho_{\\mathrm{H}\\mathrm{Z}}+\n * 1/\\rho_{\\Xi\\mathrm{Z}}+\n * 1/\\rho_{\\Xi\\mathrm{H}}-\n * 1/\\rho_{\\Xi}-\n * 1/\\rho_{\\mathrm{H}}-\n * 1/\\rho_{\\mathrm{Z}}\n * \\right)\n * \\right\\}\n * \\begin{bmatrix}\n * \\Xi\\\\\n * \\mathrm{H}\\\\\n * \\mathrm{Z}\\\\\n * \\end{bmatrix}\n * \\f]\n *\n * The inverse mapping is analytic in the angular directions. A root find\n * must be performed for the inverse mapping in the radial direction. This\n * one-dimensional formula is obtained by taking the magnitude of both sides\n * of the mapping, and changing variables from \\f$\\xi, \\eta, \\zeta\\f$ to\n * \\f$x, y, z\\f$ and introducing \\f$\\rho^2 := \\sqrt{\\xi^2+\\eta^2+\\zeta^2}\\f$.\n */\nclass BulgedCube {\n public:\n  static constexpr size_t dim = 3;\n  BulgedCube(double radius, double sphericity,\n             bool use_equiangular_map) noexcept;\n  BulgedCube() noexcept = default;\n  ~BulgedCube() noexcept = default;\n  BulgedCube(BulgedCube&&) noexcept = default;\n  BulgedCube(const BulgedCube&) noexcept = default;\n  BulgedCube& operator=(const BulgedCube&) noexcept = default;\n  BulgedCube& operator=(BulgedCube&&) noexcept = default;\n\n  template <typename T>\n  std::array<tt::remove_cvref_wrap_t<T>, 3> operator()(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  boost::optional<std::array<double, 3>> inverse(\n      const std::array<double, 3>& target_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame> jacobian(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame> inv_jacobian(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  // clang-tidy: google runtime references\n  void pup(PUP::er& p) noexcept;  // NOLINT\n\n  bool is_identity() const noexcept { return is_identity_; }\n\n private:\n  template <typename T>\n  std::array<tt::remove_cvref_wrap_t<T>, 3> xi_derivative(\n      const std::array<T, 3>& source_coords) const noexcept;\n  friend bool operator==(const BulgedCube& lhs, const BulgedCube& rhs) noexcept;\n\n  double radius_{std::numeric_limits<double>::signaling_NaN()};\n  double sphericity_{std::numeric_limits<double>::signaling_NaN()};\n  bool use_equiangular_map_ = false;\n  bool is_identity_ = false;\n};\n\nbool operator!=(const BulgedCube& lhs, const BulgedCube& rhs) noexcept;\n}  // namespace CoordinateMaps\n}  // namespace domain\n", "meta": {"hexsha": "f3a6a3ad4522d452a13f4d278e4f8796e217af08", "size": 18083, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Domain/CoordinateMaps/BulgedCube.hpp", "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": "src/Domain/CoordinateMaps/BulgedCube.hpp", "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": "src/Domain/CoordinateMaps/BulgedCube.hpp", "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": 33.6741154562, "max_line_length": 87, "alphanum_fraction": 0.5796604546, "num_tokens": 7083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5427061435040504}}
{"text": "//  Copyright John Maddock 2006, 2007, 2012, 2014.\n//  Copyright Paul A. Bristow 2006, 2007, 2012\n\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// This file includes *all* the special functions.\n// this may be useful if many are used\n// - to avoid including each function individually.\n\n#ifndef BOOST_MATH_SPECIAL_FUNCTIONS_HPP\n#define BOOST_MATH_SPECIAL_FUNCTIONS_HPP\n\n#include <boost/math/special_functions/airy.hpp>\n#include <boost/math/special_functions/acosh.hpp>\n#include <boost/math/special_functions/asinh.hpp>\n#include <boost/math/special_functions/atanh.hpp>\n#include <boost/math/special_functions/bernoulli.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/cbrt.hpp>\n#include <boost/math/special_functions/cos_pi.hpp>\n#include <boost/math/special_functions/chebyshev.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/ellint_1.hpp>\n#include <boost/math/special_functions/ellint_2.hpp>\n#include <boost/math/special_functions/ellint_3.hpp>\n#include <boost/math/special_functions/ellint_d.hpp>\n#include <boost/math/special_functions/jacobi_theta.hpp>\n#include <boost/math/special_functions/jacobi_zeta.hpp>\n#include <boost/math/special_functions/heuman_lambda.hpp>\n#include <boost/math/special_functions/ellint_rc.hpp>\n#include <boost/math/special_functions/ellint_rd.hpp>\n#include <boost/math/special_functions/ellint_rf.hpp>\n#include <boost/math/special_functions/ellint_rj.hpp>\n#include <boost/math/special_functions/ellint_rg.hpp>\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/math/special_functions/expint.hpp>\n#include <boost/math/special_functions/expm1.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/hermite.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n#include <boost/math/special_functions/hypergeometric_1F0.hpp>\n#include <boost/math/special_functions/hypergeometric_0F1.hpp>\n#include <boost/math/special_functions/hypergeometric_2F0.hpp>\n#include <boost/math/special_functions/hypergeometric_1F1.hpp>\n#include <boost/math/special_functions/hypergeometric_pFq.hpp>\n#include <boost/math/special_functions/jacobi_elliptic.hpp>\n#include <boost/math/special_functions/laguerre.hpp>\n#include <boost/math/special_functions/lanczos.hpp>\n#include <boost/math/special_functions/legendre.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include <boost/math/special_functions/owens_t.hpp>\n#include <boost/math/special_functions/polygamma.hpp>\n#include <boost/math/special_functions/powm1.hpp>\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/special_functions/sin_pi.hpp>\n#include <boost/math/special_functions/sinc.hpp>\n#include <boost/math/special_functions/sinhc.hpp>\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n#include <boost/math/special_functions/sqrt1pm1.hpp>\n#include <boost/math/special_functions/zeta.hpp>\n#include <boost/math/special_functions/modf.hpp>\n#include <boost/math/special_functions/round.hpp>\n#include <boost/math/special_functions/trunc.hpp>\n#include <boost/math/special_functions/pow.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include <boost/math/special_functions/owens_t.hpp>\n#include <boost/math/special_functions/hankel.hpp>\n#include <boost/math/special_functions/ulp.hpp>\n#include <boost/math/special_functions/relative_difference.hpp>\n#include <boost/math/special_functions/lambert_w.hpp>\n#include <boost/math/special_functions/gegenbauer.hpp>\n#include <boost/math/special_functions/jacobi.hpp>\n#include <boost/math/special_functions/legendre_stieltjes.hpp>\n#endif // BOOST_MATH_SPECIAL_FUNCTIONS_HPP\n", "meta": {"hexsha": "28a24564394788cbe5f847af25faea567d438b72", "size": 4182, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/special_functions.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/special_functions.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/special_functions.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": 49.7857142857, "max_line_length": 68, "alphanum_fraction": 0.8230511717, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5426087362110218}}
{"text": "#include <iomanip>\n#include <iostream>\n\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/cbrt.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\n#include <boost/math/bindings/e_float.hpp>\n#include <boost/multiprecision/number.hpp>\n\n#include \"examples.h\"\n\ntypedef boost::multiprecision::number<boost::math::ef::e_float,\n                                      boost::multiprecision::et_off>\ne_float_type;\n\nvoid examples::nr_021::boost_bindings()\n{\n  const e_float_type y(char(1));\n  const e_float_type x(3.0L);\n  const e_float_type z(y / x);\n\n  const e_float_type a(z);\n\n  const e_float_type lg_max = log((std::numeric_limits<e_float_type>::max)());\n  const e_float_type eps    = std::numeric_limits<e_float_type>::epsilon();\n\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << e_float_type(0.5F)                 << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << z                                  << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << sin  (z)                           << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << floor(e_float_type(1.5F))          << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << ceil (e_float_type(1.5F))          << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << sqrt (e_float_type(2))             << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << boost::math::cbrt(e_float_type(2)) << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << exp  (z)                           << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << atan2(y, x)                        << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << atan (z)                           << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << log  (e_float_type(2))             << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << lg_max                             << std::endl;\n\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << eps                    << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << sqrt(eps)              << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << boost::math::cbrt(eps) << std::endl;\n\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << boost::math::tgamma(e_float_type(0.5F))          << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << sqrt(boost::math::constants::pi<e_float_type>()) << std::endl;\n\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << boost::math::cyl_bessel_j(e_float_type(1) / 7, e_float_type(2.5F))  << std::endl;\n\n  int nexp;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << frexp(e_float_type(2), &nexp) << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10) << ldexp(e_float_type(1), 2)     << std::endl;\n\n  std::cout << std::boolalpha << (x < y) << std::endl;\n  std::cout << std::boolalpha << (y > x) << std::endl;\n\n  std::cout << std::boolalpha << (lg_max > (std::numeric_limits<std::int64_t>::max)()) << std::endl;\n  std::cout << std::boolalpha << (lg_max > (std::numeric_limits<std::int64_t>::min)()) << std::endl;\n\n  const e_float_type a3((\"33.\" + std::string(std::size_t(std::numeric_limits<e_float_type>::digits10 - 2), char('3')) + std::string(16U, char('4'))).c_str());\n  const e_float_type b3(e_float_type(100U) / 3);\n\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10 + 4) << a3 << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10 + 4) << b3 << std::endl;\n\n  std::cout << std::boolalpha << (a3 == b3) << std::endl;\n  std::cout << std::boolalpha << (a3 >  b3) << std::endl;\n  std::cout << std::boolalpha << (a3 <  b3) << std::endl;\n\n  const e_float_type c3((\"33.\" + std::string(120U, char('3'))).c_str());\n  const e_float_type d3(e_float_type(100U) / 3);\n\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10 + 4) << c3 << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<e_float_type>::digits10 + 4) << d3 << std::endl;\n\n  std::cout << std::boolalpha << (c3 == d3) << std::endl;\n  std::cout << std::boolalpha << (c3 >  d3) << std::endl;\n  std::cout << std::boolalpha << (c3 <  d3) << std::endl;\n}\n", "meta": {"hexsha": "119e324f1fc1d7516a71f584368de2a6281055fd", "size": 4809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/e_float/example/example_021_boost_bindings.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/example/example_021_boost_bindings.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/example/example_021_boost_bindings.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": 60.1125, "max_line_length": 162, "alphanum_fraction": 0.6360989811, "num_tokens": 1412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5426087243763514}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <boost/optional/optional_io.hpp>\n\n#include <iostream>\n\n#include <smtrat-modules/PBPPModule/CardinalityEncoder.h>\n\nusing namespace smtrat;\n\nstruct CardinalityFixture {\n    CardinalityFixture() { }\n\n    CardinalityEncoder encoder;\n};\n\nBOOST_FIXTURE_TEST_SUITE( s, CardinalityFixture )\n\nBOOST_AUTO_TEST_SUITE( CardinalityEncoder )\nBOOST_AUTO_TEST_SUITE( Equality );\n\nBOOST_AUTO_TEST_CASE( CardinalityEncoder_Single_Literal_False )\n{\n\tcarl::Variable x = carl::freshBooleanVariable(\"x\");\n\t\n\tConstraintT constraint = ConstraintT(Poly(x), carl::Relation::EQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulaT expected = FormulaT(carl::FormulaType::NOT, FormulaT(x));\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_CASE( CardinalityEncoder_Multi_Literal_False )\n{\n\tcarl::Variable x = carl::freshBooleanVariable(\"x\");\n\tcarl::Variable y = carl::freshBooleanVariable(\"x\");\n\tcarl::Variable z = carl::freshBooleanVariable(\"x\");\n\t\n\tConstraintT constraint = ConstraintT(Poly(x) + Poly(y) + Poly(z), carl::Relation::LEQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulaT expected = FormulaT(carl::FormulaType::AND, !FormulaT(x), !FormulaT(y), !FormulaT(z));\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_CASE( CardinalityEncoder_Simple_EQ )\n{\n\tcarl::Variable x = carl::freshBooleanVariable(\"x\");\n\tcarl::Variable y = carl::freshBooleanVariable(\"y\");\n\t\n\tConstraintT constraint = ConstraintT(Poly(x) + Poly(y) + Rational(-1), carl::Relation::EQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulaT expected = FormulaT(carl::FormulaType::OR, FormulaT(carl::FormulaType::AND, FormulaT(x), !FormulaT(y)), FormulaT(carl::FormulaType::AND, !FormulaT(x), FormulaT(y)));\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_CASE( CardinalityEncoder_Simple_EQ_3_1 )\n{\n\tcarl::Variable x = carl::freshBooleanVariable(\"x\");\n\tcarl::Variable y = carl::freshBooleanVariable(\"y\");\n\tcarl::Variable z = carl::freshBooleanVariable(\"z\");\n\t\n\tConstraintT constraint = ConstraintT(Poly(x) + Poly(y) + Poly(z) + Rational(-1), carl::Relation::EQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulaT expected = FormulaT(carl::FormulaType::OR,\n\t\t\tFormulaT(carl::FormulaType::AND, !FormulaT(x), !FormulaT(y), FormulaT(z)),\n\t\t\tFormulaT(carl::FormulaType::AND, FormulaT(x), !FormulaT(y), !FormulaT(z)),\n\t\t\tFormulaT(carl::FormulaType::AND, !FormulaT(x), FormulaT(y), !FormulaT(z)));\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_CASE( CardinalityEncoder_Simple_EQ_3_2 )\n{\n\tcarl::Variable x = carl::freshBooleanVariable(\"x\");\n\tcarl::Variable y = carl::freshBooleanVariable(\"y\");\n\tcarl::Variable z = carl::freshBooleanVariable(\"z\");\n\t\n\tConstraintT constraint = ConstraintT(Poly(x) + Poly(y) + Poly(z) + Rational(-2), carl::Relation::EQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulaT expected = FormulaT(carl::FormulaType::OR,\n\t\t\tFormulaT(carl::FormulaType::AND, !FormulaT(x), FormulaT(y), FormulaT(z)),\n\t\t\tFormulaT(carl::FormulaType::AND, FormulaT(x), !FormulaT(y), FormulaT(z)),\n\t\t\tFormulaT(carl::FormulaType::AND, FormulaT(x), FormulaT(y), !FormulaT(z)));\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_CASE( CardinalityEncoder_Simple_EQ_3_2_Negative )\n{\n\tcarl::Variable x = carl::freshBooleanVariable(\"x\");\n\tcarl::Variable y = carl::freshBooleanVariable(\"y\");\n\tcarl::Variable z = carl::freshBooleanVariable(\"z\");\n\n\tConstraintT constraint = ConstraintT(-Poly(x) - Poly(y) - Poly(z) - Rational(-2), carl::Relation::EQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulaT expected = FormulaT(carl::FormulaType::OR,\n\t\t\tFormulaT(carl::FormulaType::AND, !FormulaT(x), FormulaT(y), FormulaT(z)),\n\t\t\tFormulaT(carl::FormulaType::AND, FormulaT(x), !FormulaT(y), FormulaT(z)),\n\t\t\tFormulaT(carl::FormulaType::AND, FormulaT(x), FormulaT(y), !FormulaT(z)));\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_CASE( CardinalityEncoder_Simple_EQ_FALSE )\n{\n\tcarl::Variable x = carl::freshBooleanVariable(\"x\");\n\tcarl::Variable y = carl::freshBooleanVariable(\"y\");\n\tcarl::Variable z = carl::freshBooleanVariable(\"z\");\n\t\n\tConstraintT constraint = ConstraintT(-Poly(x) - Poly(y) - Poly(z) - Rational(-4), carl::Relation::EQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulaT expected = FormulaT(carl::FormulaType::FALSE);\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\n// END TEST SUITE EQ\nBOOST_AUTO_TEST_SUITE_END();\n\nBOOST_AUTO_TEST_CASE( CardinalityEncoder_Simple_LEQ_Coeff_LESS_CONST )\n{\n\tcarl::Variable x = carl::freshBooleanVariable(\"x\");\n\tcarl::Variable y = carl::freshBooleanVariable(\"y\");\n\tcarl::Variable z = carl::freshBooleanVariable(\"z\");\n\n\tConstraintT constraint = ConstraintT(Poly(x) + Poly(y) + Poly(z) - Rational(4), carl::Relation::LEQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\t// since 0 <= 4 is of course true as well\n\tFormulaT expected = FormulaT(carl::FormulaType::TRUE);\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_CASE(CardinalityEncoder_Simple_LEQ)\n{\n\tcarl::Variable x = carl::freshBooleanVariable(\"x\");\n\tcarl::Variable y = carl::freshBooleanVariable(\"y\");\n\t\n\tConstraintT constraint = ConstraintT(Poly(x) + Poly(y) + Rational(-1), carl::Relation::LEQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulaT expected = FormulaT(carl::FormulaType::OR,\n\t\t\tFormulaT(carl::FormulaType::AND, !FormulaT(x), !FormulaT(y)),\n\t\t\tFormulaT(carl::FormulaType::AND, !FormulaT(x), FormulaT(y)),\n\t\t\tFormulaT(carl::FormulaType::AND, FormulaT(x), !FormulaT(y)));\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\n\nBOOST_AUTO_TEST_CASE(CardinalityEncoder_PositiveCoeff_AtMost)\n{\n\tcarl::Variable x1 = carl::freshBooleanVariable(\"x1\");\n\tcarl::Variable x2 = carl::freshBooleanVariable(\"x2\");\n\tcarl::Variable x3 = carl::freshBooleanVariable(\"x3\");\n\n\t// x1 + x2 + x3 + x4 <= 2\n\tConstraintT constraint = ConstraintT(Poly(x1) + Poly(x2) + Poly(x3) + Rational(-2), carl::Relation::LEQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulasT conjunctions;\n\t// none\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, !FormulaT(x1), !FormulaT(x2), !FormulaT(x3)));\n\t// one\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, FormulaT(x1), !FormulaT(x2), !FormulaT(x3)));\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, !FormulaT(x1), FormulaT(x2), !FormulaT(x3)));\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, !FormulaT(x1), !FormulaT(x2), FormulaT(x3)));\n\t// two\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, FormulaT(x1), FormulaT(x2), !FormulaT(x3)));\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, FormulaT(x1), !FormulaT(x2), FormulaT(x3)));\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, !FormulaT(x1), FormulaT(x2), FormulaT(x3)));\n\t\n\tFormulaT expected = FormulaT(carl::FormulaType::OR, conjunctions);\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_CASE(CardinalityEncoder_PositiveCoeff_AtMost_Strict)\n{\n\tcarl::Variable x1 = carl::freshBooleanVariable(\"x1\");\n\tcarl::Variable x2 = carl::freshBooleanVariable(\"x2\");\n\tcarl::Variable x3 = carl::freshBooleanVariable(\"x3\");\n\n\t// x1 + x2 + x3 < 3\n\tConstraintT constraint = ConstraintT(Poly(x1) + Poly(x2) + Poly(x3) + Rational(-3), carl::Relation::LESS);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulasT conjunctions;\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, !FormulaT(x1), !FormulaT(x2), !FormulaT(x3)));\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, FormulaT(x1), !FormulaT(x2), !FormulaT(x3)));\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, !FormulaT(x1), FormulaT(x2), !FormulaT(x3)));\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, !FormulaT(x1), !FormulaT(x2), FormulaT(x3)));\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, FormulaT(x1), FormulaT(x2), !FormulaT(x3)));\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, FormulaT(x1), !FormulaT(x2), FormulaT(x3)));\n\tconjunctions.push_back(FormulaT(carl::FormulaType::AND, !FormulaT(x1), FormulaT(x2), FormulaT(x3)));\n\t\n\tFormulaT expected = FormulaT(carl::FormulaType::OR, conjunctions);\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_CASE(CardinalityEncoder_PositiveCoeff_AtMost_True)\n{\n\tcarl::Variable x1 = carl::freshBooleanVariable(\"x1\");\n\tcarl::Variable x2 = carl::freshBooleanVariable(\"x2\");\n\tcarl::Variable x3 = carl::freshBooleanVariable(\"x3\");\n\tcarl::Variable x4 = carl::freshBooleanVariable(\"x4\");\n\n\t// x1 + x2 + x3 + x4 <= 10\n\tConstraintT constraint = ConstraintT(Poly(x1) + Poly(x2) + Poly(x3) + Poly(x4) + Rational(-10), carl::Relation::LEQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulaT expected = FormulaT(carl::FormulaType::TRUE);\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_CASE(CardinalityEncoder_PositiveCoeff_AtMost_False)\n{\n\tcarl::Variable x1 = carl::freshBooleanVariable(\"x1\");\n\tcarl::Variable x2 = carl::freshBooleanVariable(\"x2\");\n\tcarl::Variable x3 = carl::freshBooleanVariable(\"x3\");\n\tcarl::Variable x4 = carl::freshBooleanVariable(\"x4\");\n\n\t// x1 + x2 + x3 + x4 <= -1\n\tConstraintT constraint = ConstraintT(Poly(x1) + Poly(x2) + Poly(x3) + Poly(x4) + Rational(1), carl::Relation::LEQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulaT expected = FormulaT(carl::FormulaType::FALSE);\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_CASE(CardinalityEncoder_AtLeast_False)\n{\n\tcarl::Variable x1 = carl::freshBooleanVariable(\"x1\");\n\tcarl::Variable x2 = carl::freshBooleanVariable(\"x2\");\n\tcarl::Variable x3 = carl::freshBooleanVariable(\"x3\");\n\n\tConstraintT constraint = ConstraintT(-Poly(x1) - Poly(x2) - Poly(x3) - Rational(-4), carl::Relation::LEQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulaT expected = FormulaT(carl::FormulaType::FALSE);\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_CASE(CardinalityEncoder_AtLeast)\n{\n\tcarl::Variable x1 = carl::freshBooleanVariable(\"x1\");\n\tcarl::Variable x2 = carl::freshBooleanVariable(\"x2\");\n\tcarl::Variable x3 = carl::freshBooleanVariable(\"x3\");\n\n\tConstraintT constraint = ConstraintT(-Poly(x1) - Poly(x2) - Poly(x3) - Rational(-1), carl::Relation::LEQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulaT expected = FormulaT(carl::FormulaType::OR,\n\t\t\tFormulaT(x1),\n\t\t\tFormulaT(x2),\n\t\t\tFormulaT(x3));\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_CASE(CardinalityEncoder_AtLeast_2)\n{\n\tcarl::Variable x1 = carl::freshBooleanVariable(\"x1\");\n\tcarl::Variable x2 = carl::freshBooleanVariable(\"x2\");\n\tcarl::Variable x3 = carl::freshBooleanVariable(\"x3\");\n\n\tConstraintT constraint = ConstraintT(-Poly(x1) - Poly(x2) - Poly(x3) - Rational(-2), carl::Relation::LEQ);\n\n\tboost::optional<FormulaT> result = encoder.encode(constraint);\n\n\tif (!result) {\n\t\tBOOST_FAIL(\"result != {} expected, but got {}.\");\n\t}\n\n\tFormulaT expected = FormulaT(carl::FormulaType::AND,\n\t\t\t// anything but at least one\n\t\t\tFormulaT(carl::FormulaType::OR, FormulaT(x1), FormulaT(x2), FormulaT(x3)),\n\t\t\t// and not not exactly 1\n\t\t\t!FormulaT(carl::FormulaType::OR,\n\t\t\t\tFormulaT(carl::FormulaType::AND, FormulaT(x1), !FormulaT(x2), !FormulaT(x3)),\n\t\t\t\tFormulaT(carl::FormulaType::AND, !FormulaT(x1), FormulaT(x2), !FormulaT(x3)),\n\t\t\t\tFormulaT(carl::FormulaType::AND, !FormulaT(x1), !FormulaT(x2), FormulaT(x3)))\n\t\t\t);\n\n\tBOOST_TEST((expected == *result), \"expected \" << expected << \" but got \" << result);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "2baf8fcdeb28364b806076ed56edce39ed9eb67a", "size": 13419, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/pseudobool/Test_CardinalityEncoder.cpp", "max_stars_repo_name": "minemebarsha/smtrat", "max_stars_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_stars_repo_licenses": ["MIT"], "max_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/pseudobool/Test_CardinalityEncoder.cpp", "max_issues_repo_name": "minemebarsha/smtrat", "max_issues_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_issues_repo_licenses": ["MIT"], "max_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/pseudobool/Test_CardinalityEncoder.cpp", "max_forks_repo_name": "minemebarsha/smtrat", "max_forks_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_forks_repo_licenses": ["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": 175, "alphanum_fraction": 0.7012445041, "num_tokens": 3836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5426087195684167}}
{"text": "//------------------------------------------------------------------------------\n//  Copyright 2007-2011 by Jyh-Ming Lien and George Mason University\n//  See the file \"LICENSE\" for more information\n//------------------------------------------------------------------------------\n\n#include \"polygon.h\"\n#include \"intersection.h\"\n#include <vector>\n#include <cmath>\n\n#include <boost/polygon/polygon.hpp>\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/arithmetic/arithmetic.hpp>\n#include <boost/geometry/arithmetic/dot_product.hpp>\n#include <boost/geometry/algorithms/equals.hpp>\n\n#include \"adapt_boost_poly.h\"\n\nusing namespace std;\nnamespace bp = boost::polygon;\nnamespace bg = boost::geometry;\n\n#ifdef WIN32\nextern \"C\"{\n#include \"triangulate.h\"\n}\n#else\n#include \"triangulate.h\"\n#endif\n\ntemplate<typename Pt_>\nply_vertex<Pt_>::~ply_vertex()\n{\n    //doing nothing for now\n}\n\n// - compute normal\n// - check if the vertex is reflex or not\ntemplate<typename Pt_>\nvoid\nply_vertex<Pt_>::computeExtraInfo()\n{\n    //compute normal direction\n    point_type v= next->pos;\n    bg::subtract_point(v, pos);\n    if( bg::get<0>(v) == 0 ){\n        if (bg::get<1>(v)>0) { bg::set<0>(normal,1); bg::set<1>(normal,0); }\n        else { bg::set<0>(normal,-1); bg::set<1>(normal,0); }\n    }\n    else if( bg::get<0>(v)>0 ){\n      bg::set<1>(normal, -1);\n      bg::set<0>(normal, bg::get<1>(v) / bg::get<0>(v));\n    }\n    else{//get<0>(v)<0\n      bg::set<1>(normal, 1);\n      bg::set<0>(normal, -(bg::get<1>(v) / bg::get<0>(v)));\n    }\n\n    // normalize\n    normalize(normal);\n\n    // compute left or right turn\n    reflex = !leftTurn(pre->pos, pos, next->pos);\n}\n\ntemplate<typename Pt_>\nvoid\nply_vertex<Pt_>::negate()\n{\n    bg::multiply_value(normal, -1);\n    bg::multiply_value(pos, -1);\n}\n\ntemplate<typename Pt_>\nvoid\nply_vertex<Pt_>::reverse()\n{\n    swap(next,pre);\n    //normal=-normal;\n    computeExtraInfo();\n}\n\ntemplate<typename Pt_>\nvoid\nply_vertex<Pt_>::copy(ply_vertex * other)\n{\n    pos=other->pos;\n    normal=other->normal;\n    reflex=other->reflex;\n    vid=other->vid;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\n//copy from the given ply\ntemplate<typename Pt_>\nvoid\nc_ply<Pt_>::copy(const c_ply<Pt_>& other)\n{\n    destroy();//detroy myself first\n\n    vertex_type* ptr=other.head;\n    beginPoly();\n    do{\n        vertex_type * v=new vertex_type();\n        assert(v); //check for memory\n        v->copy(ptr);\n        addVertex(v);\n        ptr=ptr->getNext();\n    }while( ptr!=other.head );\n\n    //endPoly();\n    //finish up\n    tail->setNext(head);\n\n    //copy extra info\n    area=other.area;\n    bg::assign_point(center, other.center);\n    radius=other.radius;\n    type=other.type;\n    triangulation=other.triangulation;\n    extra_info=other.extra_info;\n}\n\n// clean up the space allocated\ntemplate<typename Pt_>\nvoid\nc_ply<Pt_>::destroy()\n{\n    if( head==NULL ) return;\n    vertex_type* ptr=head;\n    do{\n        vertex_type * n=ptr->getNext();\n        delete ptr;\n        ptr=n;\n    }while( ptr!=head );\n    head=tail=NULL;\n\n    all.clear();\n    triangulation.clear();\n}\n\n// Create a empty polygon\ntemplate<typename Pt_>\nvoid\nc_ply<Pt_>::beginPoly()\n{\n    head=tail=NULL;\n    all.clear();\n    triangulation.clear();\n}\n\n// Add a vertex to the polygonal chian\ntemplate<typename Pt_>\nvoid\nc_ply<Pt_>::addVertex(\n    typename c_ply<Pt_>::coordinate_type x,\n    typename c_ply<Pt_>::coordinate_type y,\n    bool remove_duplicate )\n{\n    point_type pt(x,y);\n\n    if(tail!=NULL){\n        if(bg::equals(tail->getPos(), pt) && remove_duplicate) return; //don't add\n    }\n\n    vertex_type * v=new vertex_type(pt);\n    if( tail!=NULL ){\n        tail->setNext(v);\n    }\n    tail=v;\n    if( head==NULL ) head=tail;\n    v->setVID(all.size()); //id of the vertex in this ply\n\tall.push_back(v);\n\n}\n\n// Add a vertex to the polygonal chian\ntemplate<typename Pt_>\nvoid\nc_ply<Pt_>::addVertex( vertex_type * v )\n{\n    if( tail!=NULL ){\n        tail->setNext(v);\n    }\n    tail=v;\n    if( head==NULL ) head=tail;\n    v->setVID(all.size()); //id of the vertex in this ply\n    all.push_back(v);\n}\n\n// finish building the polygon\ntemplate<typename Pt_>\nvoid\nc_ply<Pt_>::endPoly(bool remove_duplicate)\n{\n    if(head!=NULL && tail!=NULL){\n        if(remove_duplicate){\n            if(bg::equals(head->getPos(), tail->getPos())){ //remove tail..\n                delete tail;\n                all.pop_back();\n                tail=all.back();\n            }\n        }//\n    }\n\n    tail->setNext(head);\n    doInit();\n}\n\n// initialize property of the this polychain\n// Compute normals and find reflective vertices\ntemplate<typename Pt_>\nvoid\nc_ply<Pt_>::doInit()\n{\n    //compute area\n    getArea();\n    if(this->area<0 && type==POUT){\n       //cerr<<\"! Warning: polygon type is POUT but has negative area. Reverse the vertex ordering.\"<<endl;\n       reverse();\n    }\n    else if(this->area>0 && type==PIN){\n       //cerr<<\"! Warning: polygon type is PIN but has positive area. Reverse the vertex ordering.\"<<endl;\n       reverse();\n    }\n\n    //compute normals\n    vertex_type* ptr=head;\n    do{\n        ptr->computeExtraInfo();\n        ptr=ptr->getNext();\n    }while( ptr!=head );\n}\n\ntemplate<typename Pt_>\nconst typename c_ply<Pt_>::point_type&\nc_ply<Pt_>::getCenter()\n{\n    if(radius<0){\n        center = point_type(0,0);\n        vertex_type * ptr=head;\n        const point_type& first=ptr->getPos();\n        uint size=0;\n        do{\n            size++;\n            point_type v = ptr->getPos();\n            bg::subtract_point(v, first);\n            bg::add_point(center, v);\n            ptr=ptr->getNext();\n        }while(ptr!=head); //end while\n        bg::divide_value(center, size);\n        bg::add_point(center, first);\n\n        radius=0;\n    }\n\n    return center;\n}\n\n\n///////////////////////////////////////////////////////////////////////////\ntemplate<typename Pt_>\nvoid\nc_ply<Pt_>::negate()\n{\n    vertex_type * ptr=head;\n    do{\n        ptr->negate();\n        ptr=ptr->getNext();\n    }while(ptr!=head); //end while\n}\n\n//reverse the order of the vertices\ntemplate<typename Pt_>\nvoid\nc_ply<Pt_>::reverse()\n{\n    vertex_type * ptr=head;\n    do{\n        ptr->reverse();\n        ptr=ptr->getNext();\n    }\n    while(ptr!=head); //end while\n\n    this->area=-this->area;\n    all.clear();\n    triangulation.clear();\n}\n\n///////////////////////////////////////////////////////////////////////////\ntemplate<typename Pt_>\nvoid\nc_ply<Pt_>::translate(const point_type& p)\n{\n    vertex_type * ptr=head;\n    do{\n        ptr->translate(p);\n        ptr=ptr->getNext();\n    }while(ptr!=head); //end while\n\n    //translate box\n    extra_info.box[0] += bg::get<0>(p);\n    extra_info.box[1] += bg::get<0>(p);\n    extra_info.box[2] += bg::get<1>(p);\n    extra_info.box[3] += bg::get<1>(p);\n}\n\n///////////////////////////////////////////////////////////////////////////\n//compute the Radius of the poly chain\ntemplate<typename Pt_>\ntypename c_ply<Pt_>::coordinate_type\nc_ply<Pt_>::getRadius()\n{\n    if(radius<0) getCenter();\n\n    if(radius==0){\n        vertex_type * ptr=head;\n        do{\n            point_type v = center;\n            bg::subtract_point(v, ptr->getPos());\n            coordinate_type d;\n            normalize(v, d);\n            if(d>radius) radius=d;\n            ptr=ptr->getNext();\n        }while(ptr!=head); //end while\n        radius=sqrt(radius);\n    }\n\n    return radius;\n}\n\n\ntemplate<typename Pt_>\ntypename c_ply<Pt_>::coordinate_type\nc_ply<Pt_>::getArea()\n{\n    if (area == numeric_limits<coordinate_type>::lowest())\n      area = bp::area(*this);\n\n    return area;\n}\n\n\ntemplate<typename Pt_>\nbool\nc_ply<Pt_>::enclosed(const typename c_ply<Pt_>::point_type& p)\n{\n    if(triangulation.empty())\n        triangulate(triangulation);\n\n    //find the largest triangle\n    for(uint i=0;i<triangulation.size();i++){\n        triangle & tri=triangulation[i];\n        const point_type& p1=all[tri.v[0]]->getPos();\n        const point_type& p2=all[tri.v[1]]->getPos();\n        const point_type& p3=all[tri.v[2]]->getPos();\n        coordinate_type area1=Area(p1,p2,p);\n        coordinate_type area2=Area(p2,p3,p);\n        coordinate_type area3=Area(p3,p1,p);\n        if(area1>=0 && area2>=0 && area3>=0) return true; //in\n        if(area1<=0 && area2<=0 && area3<=0) return true; //in\n    }\n\n    return false; //out\n}\n\ntemplate<typename Pt_>\ntypename c_ply<Pt_>::point_type\nc_ply<Pt_>::findEnclosedPt()\n{\n    if(triangulation.empty())\n        triangulate(triangulation);\n\n    if(triangulation.empty()){ //too few points...\n        const point_type& p1=head->getPos();\n        const point_type& p2=head->getNext()->getPos();\n        point_type pt;\n        bg::assign_point(pt, p1);\n        bg::add_point(pt, p2);\n        bg::divide_value(pt, 2);\n        return pt;\n    }\n\n    //find the largest triangle\n    coordinate_type largest_area=-1;\n    uint   largest_tri=0;\n    for(uint i=0;i<triangulation.size();i++){\n        triangle & tri=triangulation[i];\n        const point_type& p1=all[tri.v[0]]->getPos();\n        const point_type& p2=all[tri.v[1]]->getPos();\n        const point_type& p3=all[tri.v[2]]->getPos();\n        coordinate_type area=fabs(Area(p1,p2,p3));\n        if(area>largest_area){\n            largest_area=area;\n            largest_tri=i;\n        }\n    }\n\n    //find a node near the vertex of the triangle\n    triangle & tri=triangulation[largest_tri];\n    const point_type& p1=(*this)[tri.v[0]]->getPos();\n    const point_type& p2=(*this)[tri.v[1]]->getPos();\n    const point_type& p3=(*this)[tri.v[2]]->getPos();\n\n    point_type pt;\n    bg::assign_point(pt, p1);\n    bg::add_point(pt, p2);\n    bg::add_point(pt, p3);\n    bg::divide_value(pt, 3);\n\n    return pt;\n}\n\ntemplate<typename Pt_>\nvoid\nc_ply<Pt_>::triangulate(vector<triangle>& tris)\n{\n     indexing();\n     if(triangulation.empty()){\n\n         const point_type& O=getHead()->getPos();\n\n         int * ringVN=new int[1];     //number of vertices for each ring\n         assert(ringVN);\n         ringVN[0]=getSize();\n         int vN=ringVN[0];             //total number of vertices\n\n         if( vN<3 ){\n             triangle tri;\n             for(short i=0;i<3;i++) tri.v[i]=i;\n             tris.push_back(tri);\n             return;\n         }\n\n         //more than 3 vertices\n         int tN=(vN-2);                   //# of triangles\n         double * V = new double[vN*2]; //to hold vertices pos\n         int *T=new int[3*tN];            //to hold resulting triangles\n         assert(T&&V);\n\n         //copy vertices\n         {\n             int i=0;\n             vertex_type * ptr=getHead();\n             do{\n                 point_type pt=ptr->getPos();\n                 V[i*2]=bg::get<0>(pt)-bg::get<0>(O);    // potential implicit conversion\n                 V[i*2+1]=bg::get<1>(pt)-bg::get<1>(O);\n                 ptr=ptr->getNext();\n                 i++;\n             }while( ptr!=getHead() );\n         }\n\n         FIST_PolygonalArray(1, ringVN, (double (*)[2])V, &tN, (int (*)[3])T);\n\n         for(int i=0;i<tN;i++){\n             triangle tri;\n             for(int j=0;j<3;j++){\n                 tri.v[j]=T[i*3+j];\n             }//end j\n             triangulation.push_back(tri);\n         }//end i\n\n\n         delete [] ringVN;\n         delete [] V;\n         delete [] T;\n     }//end if\n\n     tris=triangulation;\n}\n\n//check if convex\ntemplate<typename Pt_>\nbool\nc_ply<Pt_>::is_convex() const\n{\n    vertex_type * ptr=head;\n    do{\n        if(ptr->isReflex()) return false;\n        ptr=ptr->getNext();\n    }while(ptr!=head); //end while\n\n    return true;\n}\n\ntemplate<typename Pt_>\nvoid\nc_ply<Pt_>::delete_vertex(vertex_type * v)\n{\n    vertex_type *pre=v->getPre();\n    vertex_type *next=v->getNext();\n\n    pre->setNext(next);\n    next->setPre(pre);\n    pre->computeExtraInfo(); //recompute info\n\n    if(head==v){\n        head=next;\n        tail=pre;\n    }\n    delete v;\n\n    triangulation.clear(); //not valid anymore\n    all.clear(); //not valid anymore\n}\n\ntemplate<typename Pt_>\nvoid\nc_ply<Pt_>::indexing()\n{\n    uint vid=0;\n    all.clear();\n    vertex_type * ptr=head;\n    do{\n        ptr->setVID(vid++);\n        all.push_back(ptr);\n        ptr=ptr->getNext();\n    }while(ptr!=head); //end while\n}\n\ntemplate<typename Pt_>\nbool\nc_ply<Pt_>::identical(const c_ply<Pt_>& other)\n{\n\n    //do some basic checks\n    if((*this)==other) return true; //same head ptr\n    if(type!=other.type) return false;\n    if(getSize()!=other.getSize()) return false;\n    if( fabs(getArea()-other.getArea())>SMALLNUMBER ) return false;\n\n    //find the first match\n    const vertex_type * o_ptr=other.head;\n    bool found_first_match=false;\n    do{\n        const point_type& pos=o_ptr->getPos();\n        coordinate_type dx=fabs(bg::get<0>(pos)-bg::get<0>(head->getPos()));\n        coordinate_type dy=fabs(bg::get<1>(pos)-bg::get<0>(head->getPos()));\n\n        if( dx<SMALLNUMBER && dy<SMALLNUMBER){\n            found_first_match=true;\n            break;\n        }\n\n        o_ptr=o_ptr->getNext();\n    }while(o_ptr!=other.head); //end while\n\n    if(!found_first_match) return false;\n\n    //check the rest of the match\n    const vertex_type * ptr=head;\n\n    //since we are sure that ptr matches to o_ptr, we first advance\n    ptr=ptr->getNext();\n    o_ptr=o_ptr->getNext();\n\n    do\n    {\n        const point_type& o_pos=o_ptr->getPos();\n        const point_type& pos=ptr->getPos();\n\n        coordinate_type dx=fabs(bg::get<0>(pos)-bg::get<0>(o_pos));\n        coordinate_type dy=fabs(bg::get<1>(pos)-bg::get<1>(o_pos));\n\n        if( dx>SMALLNUMBER || dy>SMALLNUMBER){\n            return false; //don't match\n        }\n\n        //advance\n        ptr=ptr->getNext();\n        o_ptr=o_ptr->getNext();\n\n    }\n    while(ptr!=head);\n\n    return true;\n}\n\n//\n//\n// Compute the center and the box of a list of plys\n//\n//\ntemplate<typename Pt_>\nvoid\nc_plylist<Pt_>::buildBoxAndCenter()\n{\n    box[0] = box[2] = std::numeric_limits<coordinate_type>::max();\n    box[0] = box[3] = std::numeric_limits<coordinate_type>::lowest();\n    for(auto i=begin();i!=end();i++){\n\n        const vertex_type * ptr=i->getHead();\n        do{\n            const point_type& p=ptr->getPos();\n            if(bg::get<0>(p)<box[0]) box[0]= bg::get<0>(p);\n            if(bg::get<0>(p)>box[1]) box[1]= bg::get<0>(p);\n            if(bg::get<1>(p)<box[2]) box[2]= bg::get<1>(p);\n            if(bg::get<1>(p)>box[3]) box[3]= bg::get<1>(p);\n            ptr=ptr->getNext();\n        }\n        while(ptr!=i->getHead()); //end while\n    }\n\n    bg::set<0>(center, (box[0]+box[1])/2);\n    bg::set<1>(center, (box[2]+box[3])/2);\n\n    is_buildboxandcenter_called=true;\n}\n\ntemplate<typename Pt_>\nvoid\nc_plylist<Pt_>::translate(const typename c_plylist<Pt_>::point_type& p)\n{\n    for (auto i=begin();i!=end();i++) i->translate(p);\n}\n\ntemplate<typename Pt_>\nvoid\nc_polygon<Pt_>::reverse()\n{\n    for(auto i=begin();i!=end();i++) i->reverse();\n    triangulation.clear();\n    all.clear();\n}\n\ntemplate<typename Pt_>\nbool\nc_polygon<Pt_>::valid() const\n{\n    if(empty()) return false;\n    if(front().getType()!=ring_type::POUT) return false;\n    for(auto i=++begin();i!=end();i++)\n      if(i->getType()!=ring_type::PIN)\n        return false;\n\n    return true;\n}\n\n//copy from the given polygon\ntemplate<typename Pt_>\nvoid\nc_polygon<Pt_>::copy(const c_polygon& other)\n{\n    destroy();\n\n    for(auto i=other.cbegin();i!=other.cend();i++){\n        this->emplace_back(i->getType());\n        this->back().copy(*i);\n    }\n    indexing();\n}\n\n//check if a point is enclosed\n//the behavior is unknown if pt is on the boundary of the polygon\ntemplate<typename Pt_>\nbool\nc_polygon<Pt_>::enclosed(const typename c_polygon<Pt_>::point_type& p) const\n{\n    //find the largest triangle\n    for(uint i=0;i<triangulation.size();i++){\n        const triangle & tri=triangulation[i];\n        const point_type& p1=(*this)[tri.v[0]]->getPos();\n        const point_type& p2=(*this)[tri.v[1]]->getPos();\n        const point_type& p3=(*this)[tri.v[2]]->getPos();\n        coordinate_type area1=Area(p1,p2,p);\n        coordinate_type area2=Area(p2,p3,p);\n        coordinate_type area3=Area(p3,p1,p);\n        if(area1>=0 && area2>=0 && area3>=0) return true; //in\n        if(area1<=0 && area2<=0 && area3<=0) return true; //in\n    }\n\n    return false; //out\n}\n\ntemplate<typename Pt_>\ntypename c_polygon<Pt_>::point_type\nc_polygon<Pt_>::findEnclosedPt()\n{\n    if(triangulation.empty())\n        triangulate(triangulation);\n\n    if(triangulation.empty())\n        return front().findEnclosedPt();\n\n    //find the largest triangle\n    coordinate_type largest_area=-1;\n    uint   largest_tri=0;\n    for(uint i=0;i<triangulation.size();i++){\n        triangle & tri=triangulation[i];\n        const point_type& p1=(*this)[tri.v[0]]->getPos();\n        const point_type& p2=(*this)[tri.v[1]]->getPos();\n        const point_type& p3=(*this)[tri.v[2]]->getPos();\n        coordinate_type area=fabs(Area(p1,p2,p3));\n        if(area>largest_area){\n            largest_area=area;\n            largest_tri=i;\n        }\n    }\n\n    //find a node near the vertex of the triangle\n    triangle & tri=triangulation[largest_tri];\n    const point_type& p1=(*this)[tri.v[0]]->getPos();\n    const point_type& p2=(*this)[tri.v[1]]->getPos();\n    const point_type& p3=(*this)[tri.v[2]]->getPos();\n\n    point_type pt;\n    bg::assign_point(pt, p1);\n    bg::add_point(pt, p2);\n    bg::add_point(pt, p3);\n    bg::divide_value(pt, 3);\n\n    return pt;\n}\n\ntemplate<typename Pt_>\nvoid\nc_polygon<Pt_>::triangulate(vector<triangle>& tris)\n{\n    if(triangulation.empty())\n    {\n         const point_type& O=front().getHead()->getPos();\n\n         int ringN=size();             //number of rings\n         int * ringVN=new int[ringN];     //number of vertices for each ring\n         assert(ringVN);\n\n         int vN=0;             //total number of vertices\n         {\n             int i=0;\n             for(auto ip=begin();ip!=end();ip++,i++){\n                 vN+=ip->getSize();\n                 ringVN[i]=ip->getSize();\n             }\n         }\n\n         if( vN<3 ){\n//             triangle tri;\n//             for(short i=0;i<3;i++) tri.v[i]=i;\n//             tris.push_back(tri);\n             return;\n         }\n\n         int tN=(vN-2)+2*(ringN-1);       //# of triangles, (n-2)+2*(#holes)\n         double * V=new double[vN*2];     //to hold vertices pos\n         int *T=new int[3*tN];            //to hold resulting triangles\n         assert(T&&V);\n\n         //copy vertices\n         int i=0;\n         for(auto ip=begin();ip!=end();ip++){\n             vertex_type * ptr=ip->getHead();\n             do{\n                 point_type pt=ptr->getPos();\n                 V[i*2]=bg::get<0>(pt)-bg::get<0>(O);    // potential implicit conversion to double\n                 V[i*2+1]=bg::get<1>(pt)-bg::get<1>(O);\n                 ptr=ptr->getNext();\n                 i++;\n             }while( ptr!=ip->getHead() );\n         }\n\n         FIST_PolygonalArray(ringN, ringVN,\n             (double (*)[2])V, &tN, (int (*)[3])T);\n\n         for(int i=0;i<tN;i++){\n             triangle tri;\n             for(int j=0;j<3;j++){\n                 tri.v[j]=T[i*3+j];\n             }//end j\n             triangulation.push_back(tri);\n         }//end i\n\n    }\n\n    tris=triangulation;\n}\n\ntemplate<typename Pt_>\nvoid\nc_polygon<Pt_>::pop_front()\n{\n  ring_type &ply = front();\n  ply.indexing(); // reset vertex IDs\n  c_plylist<Pt_>::pop_front();\n  /* These must be recomputed */\n  all.clear();\n  triangulation.clear();\n  indexing();\n}\n\ntemplate<typename Pt_>\nvoid\nc_polygon<Pt_>::destroy()\n{\n    for(auto i=begin();i!=end();i++){\n        i->destroy();\n    }\n    clear(); //remove all ply from this list\n    all.clear();\n    triangulation.clear();\n}\n\ntemplate<typename Pt_>\nbool\nc_polygon<Pt_>::is_convex() const\n{\n    if(size()>1) return false; //contains hole\n    return front().is_convex();\n}\n\ntemplate<typename Pt_>\nvoid\nc_polygon<Pt_>::indexing()\n{\n    uint vid=0;\n    for(auto i=begin();i!=end();i++){\n        uint vsize=i->getSize();\n        for(uint j=0;j<vsize;j++){\n            (*i)[j]->setVID(vid++);       //id of vertex in the polygons\n            all.push_back((*i)[j]);\n        }\n    }//end for i\n}\n\ntemplate<typename Pt_>\ntypename c_polygon<Pt_>::coordinate_type\nc_polygon<Pt_>::getArea()\n{\n  if (area == 0) {\n    area = bp::area(*this);\n  }\n\n  return area;\n}\n\n\ntemplate<typename Pt_>\nbool\nc_polygon<Pt_>::identical(c_polygon& p)\n{\n    if(size()!=p.size()) return false;\n\n    coordinate_type a1=getArea();\n    coordinate_type a2=p.getArea();\n    if( fabs(a1-a2)>SMALLNUMBER ) return false;\n\n\n\n    for(auto i=begin();i!=end();i++)\n    {\n        bool match=false;\n        for(auto j=p.begin();j!=p.end();j++){\n            if( i->identical(*j) ){\n                match=true;\n                break;\n            }\n        }\n        if(!match) return false;\n    }\n\n    return true;\n}\n\ntemplate<typename Pt_>\nistream& operator>>( istream& is, c_ply<Pt_>& poly)\n{\n    typedef typename c_ply<Pt_>::coordinate_type coordinate_type;\n    typedef typename c_ply<Pt_>::point_type point_type;\n\n    int vsize; string str_type;\n    is>>vsize>>str_type;\n\n    if( str_type.find(\"out\")!=string::npos )\n        poly.type=c_ply<Pt_>::POUT;\n    else poly.type=c_ply<Pt_>::PIN;\n\n    poly.beginPoly();\n    //read in all the vertices\n    int iv;\n    vector<point_type> pts; pts.reserve(vsize);\n    for( iv=0;iv<vsize;iv++ ){\n        coordinate_type x,y;\n        is>>x>>y;\n        pts.emplace_back(x,y);\n        //coordinate_type d=x*x+y*y;\n    }\n    int id;\n    for( iv=0;iv<vsize;iv++ ){\n        is>>id; id=id-1;\n        poly.addVertex(bg::get<0>(pts[id]), bg::get<1>(pts[id]));\n    }\n\n    poly.endPoly();\n    return is;\n}\n\ntemplate<typename Pt_>\nistream& operator>>( istream& is, c_plylist<Pt_>& p)\n{\n    //remove header commnets\n    do{\n        char tmp[1024];\n        char c=is.peek();\n        if(isspace(c)) is.get(c); //eat it\n        else if(c=='#') {\n            is.getline(tmp,1024);\n        }\n        else break;\n    }while(true);\n\n    //start reading\n    uint size;\n    is>>size;\n    uint vid=0;\n    for(uint i=0;i<size;i++){\n        c_ply<Pt_> poly(c_ply<Pt_>::UNKNOWN);\n        is>>poly;\n        p.push_back(poly);\n        uint vsize=poly.getSize();\n        for(uint j=0;j<vsize;j++){\n            poly[j]->setVID(vid++);       //id of vertex in the polygons\n            //p.all.push_back(poly[j]);\n        }\n    }\n    return is;\n}\n\ntemplate<typename Pt_>\nostream&\noperator<<( ostream& os, const c_ply<Pt_>& p)\n{\n    os<<p.getSize()<<\" \"<<((p.type==c_ply<Pt_>::PIN)?\"PIN  \":\"POUT \");\n    const typename c_ply<Pt_>::vertex_type * ptr=p.head;\n    os << \"< \" << ptr->getPos();\n    ptr = ptr->getNext();\n    while(ptr!=p.head)\n    {\n        os<< \", \" << ptr->getPos();\n        ptr=ptr->getNext();\n    }\n\n    return os;\n}\n\ntemplate<typename Pt_>\nostream&\noperator<<( ostream& out, const c_plylist<Pt_>& p)\n{\n    out<<p.size()<<\"\\n\";\n    for(auto i=p.cbegin();i!=p.cend();i++) out<<*i;\n    return out;\n}\n\ntemplate<typename Pt_>\nostream &\noperator<<(ostream &os, const c_polygon<Pt_> &p)\n{\n  unsigned int idx = 0u;\n  os << \"c_polygon({\" << endl;\n  for (auto ply_it = p.cbegin(); ply_it != p.cend(); ++ply_it)\n    os << \"    [\" << setw(2) << idx++ << \"] \" << *ply_it << endl;\n  os << \"})\";\n  return os;\n}\n\ntemplate<typename Pt_>\nostream &\noperator<<(ostream &os, const vector<c_polygon<Pt_> > &v)\n{\n  os << \"vector<c_polygon>({\" << endl;\n  unsigned int idx = 0u;\n  for (auto it = v.begin(); it != v.end(); ++it)\n    os << \"  [\" << setw(2) << idx++ << \"] \" << *it << endl;\n  os << \"})\";\n  return os;\n}\n\ntemplate<typename Tp_>\nostream & operator<<(ostream &os,\n    boost::geometry::model::d2::point_xy<Tp_> const&p)\n{\n  os << \"(\" << bg::get<0>(p) << \",\" << bg::get<1>(p) << \")\";\n  return os;\n}\n\nPLY_INSTANTIATE(boost::geometry::model::d2::point_xy<float>, );\nPLY_INSTANTIATE(boost::geometry::model::d2::point_xy<double>, );\n\ntemplate std::ostream &operator<< <float>(std::ostream&,\n    boost::geometry::model::d2::point_xy<float> const&);\ntemplate std::ostream &operator<< <double>(std::ostream&,\n    boost::geometry::model::d2::point_xy<double> const&);\n", "meta": {"hexsha": "d01c53e79cb4a8a2a2404b185c5893647c3b3a5c", "size": 24117, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/shapefile/polygon.cpp", "max_stars_repo_name": "fritzr/voronoi-game", "max_stars_repo_head_hexsha": "77fcc6a40076ab092795445f4e2a73f475338090", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/shapefile/polygon.cpp", "max_issues_repo_name": "fritzr/voronoi-game", "max_issues_repo_head_hexsha": "77fcc6a40076ab092795445f4e2a73f475338090", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/shapefile/polygon.cpp", "max_forks_repo_name": "fritzr/voronoi-game", "max_forks_repo_head_hexsha": "77fcc6a40076ab092795445f4e2a73f475338090", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-12T03:44:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-12T03:44:53.000Z", "avg_line_length": 24.2138554217, "max_line_length": 107, "alphanum_fraction": 0.5574905668, "num_tokens": 6771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5426087195684167}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <stan/math/prim/mat.hpp>\n#include <math/prim/mat/prob/vector_rng_test_helper.hpp>\n#include <math/prim/mat/prob/VectorIntRNGTestRig.hpp>\n#include <limits>\n#include <vector>\n\nclass NegativeBinomialTestRig : public VectorIntRNGTestRig {\n public:\n  NegativeBinomialTestRig()\n      : VectorIntRNGTestRig(10000, 10, {0, 1, 2, 3, 4, 5, 6}, {0.1, 1.7, 3.99},\n                            {1, 2, 3}, {-2.1, -0.5, 0.0}, {-3, -1, 0},\n                            {0.1, 1.1, 4.99}, {1, 2, 3}, {-3.0, -2.0, 0.0},\n                            {-3, -1, 0}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& alpha, const T2& beta, const T3&,\n                        T_rng& rng) const {\n    return stan::math::neg_binomial_rng(alpha, beta, rng);\n  }\n\n  template <typename T1>\n  double pmf(int y, T1 alpha, double beta, double) const {\n    return std::exp(stan::math::neg_binomial_lpmf(y, alpha, beta));\n  }\n};\n\nTEST(ProbDistributionsNegativeBinomial, errorCheck) {\n  check_dist_throws_all_types(NegativeBinomialTestRig());\n}\n\nTEST(ProbDistributionsNegativeBinomial, distributionCheck) {\n  check_counts_real_real(NegativeBinomialTestRig());\n}\n", "meta": {"hexsha": "fd5ed865acc76ddf8b07ab54cf83ae2025f31177", "size": 1296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/mat/prob/neg_binomial_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/prim/mat/prob/neg_binomial_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/prim/mat/prob/neg_binomial_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": 35.027027027, "max_line_length": 79, "alphanum_fraction": 0.6481481481, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5426087195684167}}
{"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\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_math_coordsys_prod);\r\n\r\nBOOST_AUTO_TEST_CASE(simple_test)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double,size_t> math_types;\r\n\r\n  typedef math_types::value_traits     value_traits;\r\n  typedef math_types::real_type        T;\r\n  typedef math_types::vector3_type     V;\r\n  typedef math_types::quaternion_type  Q;\r\n  typedef math_types::coordsys_type    X;\r\n\r\n  {\r\n    X I;\r\n    I.identity();\r\n\r\n    X L;\r\n    L.T() = V(1.0,2.0,3.0);\r\n    L.Q().Ru( value_traits::pi(), V(1.0, 2.0, 3.0) );\r\n\r\n    X R = OpenTissue::math::prod( L, I );\r\n\r\n    BOOST_CHECK( fabs( R.T()(0) - L.T()(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.T()(1) - L.T()(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.T()(2) - L.T()(2) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().s() - L.Q().s() ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().v()(0) - L.Q().v()(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().v()(1) - L.Q().v()(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().v()(2) - L.Q().v()(2) ) < 10e-10 );\r\n  }\r\n  {\r\n    X I;\r\n    I.identity();\r\n\r\n    X L;\r\n    L.T() = V(1.0,2.0,3.0);\r\n    L.Q().Ru( value_traits::pi(), V(1.0, 2.0, 3.0) );\r\n\r\n    X R = OpenTissue::math::prod( I, L );\r\n\r\n    BOOST_CHECK( fabs( R.T()(0) - L.T()(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.T()(1) - L.T()(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.T()(2) - L.T()(2) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().s() - L.Q().s() ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().v()(0) - L.Q().v()(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().v()(1) - L.Q().v()(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().v()(2) - L.Q().v()(2) ) < 10e-10 );\r\n  }\r\n  {\r\n    X I;\r\n    I.identity();\r\n\r\n    X R = OpenTissue::math::prod( I, I );\r\n\r\n    BOOST_CHECK( fabs( R.T()(0) - I.T()(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.T()(1) - I.T()(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.T()(2) - I.T()(2) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().s() - I.Q().s() ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().v()(0) - I.Q().v()(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().v()(1) - I.Q().v()(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().v()(2) - I.Q().v()(2) ) < 10e-10 );\r\n  }\r\n  {\r\n    X I;\r\n    I.identity();\r\n\r\n    X L;\r\n    L.T() = V(1.0,2.0,3.0);\r\n    L.Q().Ru( value_traits::pi(), V(1.0, 2.0, 3.0) );\r\n\r\n    X invL = OpenTissue::math::inverse( L );\r\n    X R = OpenTissue::math::prod( invL, L );\r\n\r\n    BOOST_CHECK( fabs( R.T()(0) - I.T()(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.T()(1) - I.T()(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.T()(2) - I.T()(2) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().s() - I.Q().s() ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().v()(0) - I.Q().v()(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().v()(1) - I.Q().v()(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( R.Q().v()(2) - I.Q().v()(2) ) < 10e-10 );\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "8fb338c5bad49f76c16e72b59e591a5b65e21f82", "size": 3421, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/coordsys_prod/src/unit_coordsys_prod.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/coordsys_prod/src/unit_coordsys_prod.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/coordsys_prod/src/unit_coordsys_prod.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.5392156863, "max_line_length": 79, "alphanum_fraction": 0.5273311897, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5426087186808962}}
{"text": "#pragma once\n#include <cmath>\n#include <boost/random.hpp>\n\nclass PRNG{\n  const size_t n_rng;\n  boost::mt19937* gen;\n  boost::uniform_real<> uni_dist; //range is [0,1].\n  boost::normal_distribution<> *normal_dist; //mean=0 sd=1.0\n  \npublic:\n  PRNG(const size_t seed, const size_t th_numb) : n_rng(th_numb) {\n    gen = new boost::mt19937 [th_numb];\n    for (size_t i = 0; i < th_numb; i++) gen[i].seed(seed + i * 10);\n    normal_dist = new boost::normal_distribution<> (0.0, 1.0);\n  }\n  PRNG(const size_t th_numb) : n_rng(th_numb) {\n    gen = new boost::mt19937 [th_numb];\n    const size_t base_seed = (size_t) time(NULL);\n    for (size_t i = 0; i < th_numb; i++) gen[i].seed(base_seed + i * 10);\n    normal_dist = new boost::normal_distribution<> (0.0, 1.0);\n  }\n  \n  ~PRNG(){\n    delete [] gen;\n    delete normal_dist;\n  }\n  \n  inline double Uniform(const int tid){\n    return uni_dist(gen[tid]);\n  }\n  inline double Uniform(const int tid, const double up, const double dw){\n    return dw + (up - dw) * uni_dist(gen[tid]);\n  }\n\n  inline double Normal(const int tid){\n    return (*normal_dist)(gen[tid]);\n  }\n  inline double Normal(const int tid, const double mean, const double sd){\n    return mean + (*normal_dist)(gen[tid]) * sqrt(sd);\n  }\n};\n", "meta": {"hexsha": "97f5caa7e963fe7e0d3d3cfa1843ecff839e668c", "size": 1245, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "prng.hpp", "max_stars_repo_name": "kohnakagawa/polymer_bd", "max_stars_repo_head_hexsha": "f1e5151582e6c17401a90b81d3f425f61d4345a1", "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": "prng.hpp", "max_issues_repo_name": "kohnakagawa/polymer_bd", "max_issues_repo_head_hexsha": "f1e5151582e6c17401a90b81d3f425f61d4345a1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prng.hpp", "max_forks_repo_name": "kohnakagawa/polymer_bd", "max_forks_repo_head_hexsha": "f1e5151582e6c17401a90b81d3f425f61d4345a1", "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.9534883721, "max_line_length": 74, "alphanum_fraction": 0.6401606426, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5426087186808962}}
{"text": "/*\n  Total variation denoising based on the paper \n  \"The Split Bregman Method for L1-Regularized Problems\" by Tom Goldstein and Stanley Osher. \n  Siam J. Imaging Sciences. Vol. 2, No. 2, pp. 323-343.\n*/\n\n// Gadgetron includes\n#include \"cuNDArray.h\"\n#include \"hoNDArray_fileio.h\"\n#include \"cuSbCgSolver.h\"\n#include \"cuCgSolver.h\"\n#include \"identityOperator.h\"\n#include \"cuPartialDerivativeOperator.h\"\n#include \"parameterparser.h\"\n#include \"cuNDDWT.h\"\n#include \"cuDWTOperator.h\"\n#include <boost/make_shared.hpp>\n// Std includes\n#include <iostream>\n\nusing namespace std;\nusing namespace Gadgetron;\n\n// Define desired precision\ntypedef float _real; \n\nint main(int argc, char** argv)\n{\n  //\n  // Parse command line\n  //\n\n  ParameterParser parms;\n  parms.add_parameter( 'd', COMMAND_LINE_STRING, 1, \"Noisy image file name (.real)\", true );\n  parms.add_parameter( 'r', COMMAND_LINE_STRING, 1, \"Result file name\", true, \"denoised_image_TV.real\" );\n  parms.add_parameter( 'i', COMMAND_LINE_INT,    1, \"Number of cg iterations\", true, \"20\" );\n  parms.add_parameter( 'I', COMMAND_LINE_INT,    1, \"Number of sb inner iterations\", true, \"1\" );\n  parms.add_parameter( 'O', COMMAND_LINE_INT,    1, \"Number of sb outer iterations\", true, \"10\" );\n  parms.add_parameter( 'l', COMMAND_LINE_FLOAT,  1, \"Total variation weight (lambda)\", true, \"50.0\" );\n  parms.add_parameter( 'm', COMMAND_LINE_FLOAT,  1, \"Regularization weight (mu)\", true, \"25.0\" );\n  parms.add_parameter('w', COMMAND_LINE_FLOAT, 1, \"Wavelet weight\" ,true, \"0\");\n\n  parms.parse_parameter_list(argc, argv);\n  if( parms.all_required_parameters_set() ){\n    cout << \" Running denoising with the following parameters: \" << endl;\n    parms.print_parameter_list();\n  }\n  else{\n    cout << \" Some required parameters are missing: \" << endl;\n    parms.print_parameter_list();\n    parms.print_usage();\n    return 1;\n  }\n    \n  // Load sample data from disk\n  boost::shared_ptr< hoNDArray<_real> > host_data = \n    read_nd_array<_real>((char*)parms.get_parameter('d')->get_string_value());\n\n  if( !host_data.get() ){\n    cout << endl << \"Input image not found. Quitting!\\n\" << endl;\n    return 1;\n  }\n  \n  if( host_data->get_number_of_dimensions() != 2 ){\n    cout << endl << \"Input image is not two-dimensional. Quitting!\\n\" << endl;\n    return 1;\n  }\n  \n  // Upload host data to device\n  cuNDArray<_real> data(host_data.get());\n  \n  _real mu = (_real) parms.get_parameter('m')->get_float_value();\n  _real lambda = (_real)parms.get_parameter('l')->get_float_value();\n\n  if( mu <= (_real) 0.0 ) {\n    cout << endl << \"Regularization parameter mu should be strictly positive. Quitting!\\n\" << endl;\n    return 1;\n  }\n\n  unsigned int num_cg_iterations = parms.get_parameter('i')->get_int_value();\n  unsigned int num_inner_iterations = parms.get_parameter('I')->get_int_value();\n  unsigned int num_outer_iterations = parms.get_parameter('O')->get_int_value();\n  \n // Define encoding operator (identity)\n  boost::shared_ptr< identityOperator<cuNDArray<_real> > > E( new identityOperator<cuNDArray<_real> >() );\n  E->set_weight( mu );\n  E->set_domain_dimensions(data.get_dimensions().get());\n  E->set_codomain_dimensions(data.get_dimensions().get());\n\n  // Setup split-Bregman solver\n  cuSbCgSolver<_real> sb;\n  sb.set_encoding_operator( E );\n  sb.set_max_outer_iterations(num_outer_iterations);\n  sb.set_max_inner_iterations(num_inner_iterations);\n  sb.set_output_mode( cuCgSolver<_real>::OUTPUT_VERBOSE );\n   // Setup regularization operators\n\n  if (lambda > 0){\n  boost::shared_ptr< cuPartialDerivativeOperator<_real,2> > Rx( new cuPartialDerivativeOperator<_real,2>(0) );\n  Rx->set_weight( lambda );\n  Rx->set_domain_dimensions(data.get_dimensions().get());\n  Rx->set_codomain_dimensions(data.get_dimensions().get());\n\n  boost::shared_ptr< cuPartialDerivativeOperator<_real,2> > Ry( new cuPartialDerivativeOperator<_real,2>(1) );\n  Ry->set_weight( lambda );\n  Ry->set_domain_dimensions(data.get_dimensions().get());\n  Ry->set_codomain_dimensions(data.get_dimensions().get());\n  //sb.add_regularization_operator( Rx ); // Anisotropic denoising\n  //sb.add_regularization_operator( Ry ); // Anisotropic denoising\n  sb.add_regularization_group_operator( Rx ); // Isotropic denoising\n  sb.add_regularization_group_operator( Ry); // Isotropic denoising\n  sb.add_group();\n  }\n  \n  _real wavelet = parms.get_parameter('w')->get_float_value();\n  if (wavelet > 0){\n\t  auto dwt = boost::make_shared<cuDWTOperator<_real,2>>();\n\t  dwt->set_levels(3);\n\t  dwt->set_weight(wavelet);\n\t  sb.add_regularization_operator(dwt);\n\t  dwt->set_domain_dimensions(data.get_dimensions().get());\n\t  dwt->set_codomain_dimensions(data.get_dimensions().get());\n\t  dwt->use_random(true);\n  }\n\n  // Setup inner conjugate gradient solver\n  sb.get_inner_solver()->set_max_iterations( num_cg_iterations );\n  sb.get_inner_solver()->set_tc_tolerance( 1e-4 );\n  sb.get_inner_solver()->set_output_mode( cuCgSolver<_real>::OUTPUT_WARNINGS );\n\n  // Run split-Bregman solver\n  boost::shared_ptr< cuNDArray<_real> > sbresult = sb.solve(&data);\n\n  /*\n  boost::shared_ptr< cuNDArray<_real> > sbresult(new cuNDArray<_real>(data.get_dimensions()));\n  clear(sbresult.get());\n\n  vector_td<float,4> daubechies4({0.6830127f,1.1830127f,0.3169873f,-0.1830127f});\n  vector_td<float,2> haahr(1.0f,1.0f);\n  vector_td<float,6> daubechies6{0.47046721f,1.14111692f,0.650365f,-0.19093442f, -0.12083221f,0.0498175f};\n\n  cuDWTOperator<float,2> dwt;\n  dwt.set_levels(3);\n  dwt.mult_M(&data,sbresult.get());\n  //data = *sbresult;\n  shrink1(sbresult.get(),30.0f,&data);\n  dwt.mult_MH(&data,sbresult.get());*/\n  //clear(sbresult.get());\n // All done, write out the result\n  boost::shared_ptr< hoNDArray<_real> > host_result = sbresult->to_host();\n  write_nd_array<_real>(host_result.get(), (char*)parms.get_parameter('r')->get_string_value());\n  \n  return 0;\n}\n", "meta": {"hexsha": "51ea43e9bf9b1dd3db170608cb51d40fc8458ccf", "size": 5830, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/standalone/gpu/denoising/2d/denoise_TV.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "apps/standalone/gpu/denoising/2d/denoise_TV.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "apps/standalone/gpu/denoising/2d/denoise_TV.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["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.6129032258, "max_line_length": 110, "alphanum_fraction": 0.712864494, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5426087143167215}}
{"text": "/*\n * Copyright (C) 2015, Nils Moehrle\n * TU Darmstadt - Graphics, Capture and Massively Parallel Computing\n * All rights reserved.\n *\n * This software may be modified and distributed under the terms\n * of the BSD 3-Clause license. See the LICENSE.txt file for details.\n */\n\n#include <cstdint>\n#include <iostream>\n\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <math/vector.h>\n\n#include \"poisson_blending.h\"\n\ntypedef Eigen::SparseMatrix<float> SpMat;\n\nmath::Vec3f simple_laplacian(int i, mve::FloatImage::ConstPtr img) {\n  const int width = img->width();\n  assert(i > width + 1 && i < img->get_pixel_amount() - width - 1);\n\n  return -4.0f * math::Vec3f(&img->at(i, 0))\n         + math::Vec3f(&img->at(i - width, 0)) + math::Vec3f(&img->at(i - 1, 0))\n         + math::Vec3f(&img->at(i + 1, 0))\n         + math::Vec3f(&img->at(i + width, 0));\n}\n\nbool valid_mask(mve::ByteImage::ConstPtr mask) {\n  const int width = mask->width();\n  const int height = mask->height();\n\n  for (int x = 0; x < width; ++x)\n    if (mask->at(x, 0, 0) == 255 || mask->at(x, height - 1, 0) == 255)\n      return false;\n\n  for (int y = 0; y < height; ++y)\n    if (mask->at(0, y, 0) == 255 || mask->at(width - 1, y, 0) == 255)\n      return false;\n\n  // TODO check for sane boundary conditions...\n\n  return true;\n}\n\nvoid poisson_blend(\n    mve::FloatImage::ConstPtr src,\n    mve::ByteImage::ConstPtr mask,\n    mve::FloatImage::Ptr dest,\n    float alpha) {\n  assert(src->width() == mask->width() && mask->width() == dest->width());\n  assert(src->height() == mask->height() && mask->height() == dest->height());\n  assert(src->channels() >= 3 && dest->channels() == src->channels());\n  assert(mask->channels() == 1);\n  assert(valid_mask(mask));\n\n  const int n = dest->get_pixel_amount();\n  const int width = dest->width();\n  const int height = dest->height();\n  // only do poisson on the color channels--first three\n  // TODO dwh: get rid of hard coded color channels=3\n  const int channels = std::min(dest->channels(), 3);\n\n  mve::Image<int>::Ptr indices = mve::Image<int>::create(width, height, 1);\n  indices->fill(-1);\n  int index = 0;\n  for (int i = 0; i < n; ++i) {\n    if (mask->at(i) != 0) {\n      indices->at(i) = index;\n      index += 1;\n    }\n  }\n  const int nnz = index;\n\n  std::vector<math::Vec3f> coefficients_b;\n  coefficients_b.resize(nnz);\n  // std::cout << \"blend 0 \" << std::endl;\n  std::vector<\n      Eigen::Triplet<float, int>,\n      Eigen::aligned_allocator<Eigen::Triplet<float, int>>>\n      coefficients_A;\n  coefficients_A.reserve(nnz);  // TODO better estimate...\n  // std::cout << \"blend A \" << std::endl;\n  for (int i = 0; i < n; ++i) {\n    const int row = indices->at(i);\n    if (mask->at(i) == 128 || mask->at(i) == 64) {\n      Eigen::Triplet<float, int> t(row, row, 1.0f);\n      coefficients_A.push_back(t);\n\n      coefficients_b[row] = math::Vec3f(&dest->at(i, 0));\n    }\n\n    if (mask->at(i) == 255) {\n      const int i01 = indices->at(i - width);\n      const int i10 = indices->at(i - 1);\n      const int i11 = indices->at(i);\n      const int i12 = indices->at(i + 1);\n      const int i21 = indices->at(i + width);\n\n      /* All neighbours should be eighter border conditions or part of the\n       * optimization. */\n      assert(i01 != -1 && i10 != -1 && i11 != -1 && i12 != -1 && i21 != -1);\n\n      Eigen::Triplet<float, int> t01(row, i01, 1.0f);\n\n      Eigen::Triplet<float, int> t10(row, i10, 1.0f);\n      Eigen::Triplet<float, int> t11(row, i11, -4.0f);\n      Eigen::Triplet<float, int> t12(row, i12, 1.0f);\n\n      Eigen::Triplet<float, int> t21(row, i21, 1.0f);\n\n      Eigen::Triplet<float, int> triplets[] = {t01, t10, t11, t12, t21};\n\n      coefficients_A.insert(coefficients_A.end(), triplets, triplets + 5);\n\n      math::Vec3f l_d = simple_laplacian(i, dest);\n      math::Vec3f l_s = simple_laplacian(i, src);\n\n      coefficients_b[row] = (alpha * l_s + (1.0f - alpha) * l_d);\n    }\n  }\n  // std::cout << \"blend B \" << std::endl;\n  SpMat A(nnz, nnz);\n  A.setFromTriplets(coefficients_A.begin(), coefficients_A.end());\n  // std::cout << \"blend C \" << std::endl;\n  Eigen::SparseLU<SpMat, Eigen::COLAMDOrdering<int>> solver;\n  // std::cout << \"blend Cp \" << std::endl;\n  // std::cout << nnz << std::endl;\n  solver.compute(A);\n  // std::cout << \"blend D \" << std::endl;\n  for (int channel = 0; channel < channels; ++channel) {\n    Eigen::VectorXf b(nnz);\n    for (std::size_t i = 0; i < coefficients_b.size(); ++i)\n      b[i] = coefficients_b[i][channel];\n\n    Eigen::VectorXf x(n);\n    x = solver.solve(b);\n\n    for (int i = 0; i < n; ++i) {\n      int index = indices->at(i);\n      if (index != -1)\n        dest->at(i, channel) = x[index];\n    }\n  }\n  // std::cout << \"blend E \" << std::endl;\n}\n", "meta": {"hexsha": "baa3d06d31c208c92413f1e8147c4f45c8252441", "size": 4718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/tex/poisson_blending.cpp", "max_stars_repo_name": "Hivemapper/HM-colony-mvs-texturing", "max_stars_repo_head_hexsha": "2930c8926886d33fcec5ed42137d2f21ce834c2a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-04T16:38:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T16:38:50.000Z", "max_issues_repo_path": "libs/tex/poisson_blending.cpp", "max_issues_repo_name": "Hivemapper/HM-colony-mvs-texturing", "max_issues_repo_head_hexsha": "2930c8926886d33fcec5ed42137d2f21ce834c2a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-15T21:58:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-06T02:56:46.000Z", "max_forks_repo_path": "libs/tex/poisson_blending.cpp", "max_forks_repo_name": "Hivemapper/HM-colony-mvs-texturing", "max_forks_repo_head_hexsha": "2930c8926886d33fcec5ed42137d2f21ce834c2a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-28T18:15:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-28T18:15:52.000Z", "avg_line_length": 31.6644295302, "max_line_length": 80, "alphanum_fraction": 0.5862653667, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5426087143167215}}
{"text": "#include <Eigen/Dense>\n#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <vector>\n#include \"perf_test.hpp\"\n#include \"svd.hpp\"\n#include \"types.hpp\"\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> MatrixXd;\ntypedef Eigen::JacobiSVD<MatrixXd> SVD;\n\nvoid run_jacobi(SVD&& svd, MatrixXd&& m, unsigned int flags) { svd.compute(m, flags); }\n\nusing SVDTolType = decltype(&run_jacobi);\n\ndouble base_cost(size_t n, size_t n_iter) {\n    // Ops in real_2x2_jacobi svd\n    double svd_2x2_wild = 6;\n\n    // Ops in m.applyOnTheLeft(..), part of real_2x2_jacobi svd\n    double rot_2x2_add = 2;\n    double rot_2x2_mul = 4;\n\n    // Ops in makeJacobi(), part of real_2x2_jacobi svd\n    double make_add = 5;\n    double make_mul = 4;\n    double make_div = 4;\n    double make_sqrt = 2;\n    double make_abs = 5;\n\n    // Ops in rot1 * j_right->transpose(), part of real_2x2_jacobi svd\n    double rot_mul_add = 2;\n    double rot_mul_mul = 4;\n\n    double svd_2x2 = svd_2x2_wild + rot_2x2_add + rot_2x2_mul + rot_mul_add + rot_mul_mul + make_add + make_mul +\n                     make_div + make_sqrt + make_abs;\n\n    // Ops in m_workMatrix.applyOnTheLeft(..)\n    // Same for m_workMatrix.applyOnTheRight(..), m_matrixU.applyOnTheRight(..), m_matrixV.applyOnTheRight(..)\n    double rot_add = 2 * n;\n    double rot_mul = 4 * n;\n\n    double loops = (n * n - n) / 2;\n    double flops = n_iter * loops * (svd_2x2 + 4 * (rot_add + rot_mul));\n\n    return flops;\n}\n\nusing CostFuncType = decltype(&base_cost);\n\nstd::vector<SVDTolType> tol_based_versions = {\n    run_jacobi,\n};\nstd::vector<std::string> tol_based_names = {\n    \"svd_two_sided_eigen\",\n};\nstd::vector<CostFuncType> tol_based_cost_fns = {base_cost};\n\nint main() {\n    size_t n;\n\n    std::ios_base::sync_with_stdio(false);  // disable synchronization between C and C++ standard streams\n    std::cin.tie(NULL);                     // untie cin from cout\n\n    std::cin >> n >> n;\n    std::cerr << \"Performance benchmark on array of size \" << n << \" by \" << n << std::endl;\n\n    MatrixXd Ap(n, n);\n    SVD svd;\n\n    for (size_t i = 0; i < n; ++i) {\n        for (size_t j = 0; j < n; j++) {\n            std::cin >> Ap(i, j);\n        }\n    }\n\n    svd.compute(Ap, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    size_t n_iter = svd.getSweeps();\n\n    std::vector<double> costs;\n    for (const auto& cost_fn : tol_based_cost_fns) {\n        costs.push_back(cost_fn(n, n_iter));\n    }\n\n    run_all(tol_based_versions, tol_based_names, costs, svd, Ap, Eigen::ComputeFullU | Eigen::ComputeFullV);\n}\n", "meta": {"hexsha": "3d88eb974af728624ff3a2986141ae72d159e8b6", "size": 2547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perf/svd/eigen/svd_perf.cpp", "max_stars_repo_name": "ktrianta/jacobi-svd-evd", "max_stars_repo_head_hexsha": "8162562c631c3d1541e23b1fa38ec7600a5032af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-09T14:22:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T05:40:44.000Z", "max_issues_repo_path": "perf/svd/eigen/svd_perf.cpp", "max_issues_repo_name": "ktrianta/jacobi-svd-evd", "max_issues_repo_head_hexsha": "8162562c631c3d1541e23b1fa38ec7600a5032af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-03-17T14:02:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-12T13:15:19.000Z", "max_forks_repo_path": "perf/svd/eigen/svd_perf.cpp", "max_forks_repo_name": "ktrianta/jacobi-svd-evd", "max_forks_repo_head_hexsha": "8162562c631c3d1541e23b1fa38ec7600a5032af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-03-09T14:22:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T19:36:42.000Z", "avg_line_length": 28.9431818182, "max_line_length": 113, "alphanum_fraction": 0.6442873969, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5426087081775066}}
{"text": "#pragma once\n\n#include \"SensorData.h\"\n#include \"Poster.hpp\"\n\n//This needs to be in this order. We need to include Arduino.h (if not already included), then undefine the Arduino `abs` macro, then pull in Eigen. Pray Rust comes quickly.\n#include \"Arduino.h\"\n#undef abs\n#include <Eigen.h>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nclass AltFilter{\npublic:\n  AltFilter();\n  void update(SensorData& data);\n  void init(SensorData& data);\n  float getAltitude();\n  float getVelocity();\n  void logState();\n  Poster<float> p_alt;\n  Poster<float> p_vel;\n\nprivate:\n\n  uint32_t print_timer;\n\n  Vector3f X;\n  Vector2f Z;\n  Matrix3f F;\n  Matrix3f Q;\n  Matrix3f P;\n  Matrix<float, 3, 2> K;\n  Matrix<float, 2, 3> H;\n  Matrix2f R;\n\n  uint32_t data_time;\n\n  void prefilter(SensorData& data);\n  void kalmanPredict();\n  void kalmanUpdate();\n  float p2alt(float p);\n};\n", "meta": {"hexsha": "eeacb47a35c2b3037251d15459cc10a66fe22fa6", "size": 852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/fc/AltFilter.hpp", "max_stars_repo_name": "stanford-ssi/SpaceSalmon", "max_stars_repo_head_hexsha": "79d8b17f02e317ef547e8097bbbb2277785ebabb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-03-30T00:09:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T11:48:34.000Z", "max_issues_repo_path": "src/fc/AltFilter.hpp", "max_issues_repo_name": "stanford-ssi/SpaceSalmon", "max_issues_repo_head_hexsha": "79d8b17f02e317ef547e8097bbbb2277785ebabb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2019-02-09T06:41:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T10:13:09.000Z", "max_forks_repo_path": "src/fc/AltFilter.hpp", "max_forks_repo_name": "stanford-ssi/SpaceSalmon", "max_forks_repo_head_hexsha": "79d8b17f02e317ef547e8097bbbb2277785ebabb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-18T13:13:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-25T00:24:11.000Z", "avg_line_length": 19.3636363636, "max_line_length": 173, "alphanum_fraction": 0.7042253521, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5425748891170211}}
{"text": "//\n// Copyright (c) 2016 CNRS\n//\n\n#include \"pinocchio/algorithm/energy.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE(test_kinetic_energy)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  pinocchio::Data data(model);\n  \n  VectorXd q = VectorXd::Zero(model.nq);\n  VectorXd v = VectorXd::Ones(model.nv);\n  VectorXd a = VectorXd::Ones(model.nv);\n  \n  data.M.fill(0);  crba(model,data,q);\n  data.M.triangularView<Eigen::StrictlyLower>()\n  = data.M.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  double kinetic_energy_ref = 0.5*v.transpose() * data.M * v;\n  double kinetic_energy = kineticEnergy(model, data, q, v);\n  \n  BOOST_CHECK_SMALL(kinetic_energy_ref - kinetic_energy, 1e-12);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "aba9023567bcc2eab97fd54414cb078c098dc22f", "size": 1045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/energy.cpp", "max_stars_repo_name": "andreadelprete/pinocchio", "max_stars_repo_head_hexsha": "6fa1c7d5502629ee126f84f1a05471815fba30f4", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "unittest/energy.cpp", "max_issues_repo_name": "andreadelprete/pinocchio", "max_issues_repo_head_hexsha": "6fa1c7d5502629ee126f84f1a05471815fba30f4", "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/energy.cpp", "max_forks_repo_name": "andreadelprete/pinocchio", "max_forks_repo_head_hexsha": "6fa1c7d5502629ee126f84f1a05471815fba30f4", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 26.125, "max_line_length": 64, "alphanum_fraction": 0.7425837321, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5425748846391688}}
{"text": "#ifndef __PARTICLE_FILTER_HAND_PREDICTION_HPP\n#define __PARTICLE_FILTER_HAND_PREDICTION_HPP\n\n#include <ctime>\n#include <Eigen/Dense>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/normal_distribution.hpp>\n\n#include \"particle_filter_hand.hpp\"\n#include \"particle_filter_base.hpp\"\n\n#define SMOOTH_FACTOR (1.)\n\nclass HandPredictionModel: public PredictionModel<HAND_STATE_SIZE>\n{\nprivate:\n  double initQSigma;\n  double initWSigma;\n  double updateQSigma;\n  double updateWSigma;\n  \n  \n  void _updateParticle(Particle<HAND_STATE_SIZE> &p,\n\t\t       double deltaT, double qSigma, double wSigma,\n\t\t       boost::random::mt19937 &rng) const\n  {\n    // Quaternion kinematics from\n    // Sola, Joan. \"Quaternion kinematics for the error-state KF.\" Laboratoire d\u2019Analyse et d\u2019Architecture des Systemes-Centre national de la recherche scientifique (LAAS-CNRS), Toulouse, France, Tech. Rep (2012).\n    boost::random::normal_distribution<double> Nq(0., qSigma);\n    boost::random::normal_distribution<double> Nw(0., wSigma);\n    boost::random::uniform_01<double> U;\n\n    // Current state quaternions (orientation and angular velocity)\n    Eigen::Quaternion<double> qt, wt;\n    qt.w() = p.state[0];\n    qt.x() = p.state[1];\n    qt.y() = p.state[2];\n    qt.z() = p.state[3];\n    wt.w() = 0.;\n    wt.x() = p.state[4]; \n    wt.y() = p.state[5]; \n    wt.z() = p.state[6];\n    \n    // Perturbation quaternions\n    Eigen::Quaternion<double> deltaqt, deltawt;\n    //deltaqt.w() =1. +Nq(rng);\n    //deltaqt.x() = Nq(rng);\n    //deltaqt.y() = Nq(rng);\n    //deltaqt.z() = Nq(rng);\n    Eigen::AngleAxisd deltaaxt;\n    deltaaxt.angle() = Nq(rng);\n    deltaaxt.axis().x() = -1.+2.*U(rng);\n    deltaaxt.axis().y() = -1.+2.*U(rng);\n    deltaaxt.axis().z() = -1.+2.*U(rng);\n    deltaqt = deltaaxt;\n    deltawt.w() = 0;\n    deltawt.x() = Nw(rng);\n    deltawt.y() = Nw(rng);\n    deltawt.z() = Nw(rng);\n\n    // Update quaternion rotation\n    Eigen::Quaternion<double> qtw,qt1;\n    // - quaternion update (for non zero velocity)\n    if (deltaT)\n    {\n      qtw.w() = cos(wt.norm()*deltaT/2);\n      qtw.x() = wt.x()/wt.norm()*sin(wt.norm()*deltaT/2);\n      qtw.y() = wt.y()/wt.norm()*sin(wt.norm()*deltaT/2);\n      qtw.z() = wt.z()/wt.norm()*sin(wt.norm()*deltaT/2);\n      // - multiply by perturbation and update\n      qt1 = deltaqt * qtw * qt;\n    }\n    else\n    {\n      // Null velocity, apply the random perturbation only\n      qt1 = deltaqt * qt;\n    }\n\t// Normalize\n\tqt1.normalize();\n\n    // Update velocity\n    Eigen::Quaternion<double> deltaq, wt1;\n    Eigen::AngleAxisd axang;\n    if (deltaT)\n    {\n      deltaq = qt1 * qt.inverse();\n      axang = deltaq;\n      wt1.w() = 0.;\n      wt1.x() = axang.axis().x()*axang.angle()/deltaT + deltawt.x();\n      wt1.y() = axang.axis().y()*axang.angle()/deltaT + deltawt.y();\n      wt1.z() = axang.axis().z()*axang.angle()/deltaT + deltawt.z();\n    }\n    else\n    {\n      wt1.w() = 0.;\n      wt1.x() = wt.x()+deltawt.x();\n      wt1.y() = wt.y()+deltawt.y();\n      wt1.z() = wt.z()+deltawt.z();\n    }\n\n\n    // Done, update particle status\n    Eigen::Quaternion<double> iq;\n    iq = qt.slerp(SMOOTH_FACTOR, qt1);\n    p.state[0] = iq.w();\n    p.state[1] = iq.x();\n    p.state[2] = iq.y();\n    p.state[3] = iq.z();\n    \n    p.state[4] = SMOOTH_FACTOR*wt1.x() + (1.-SMOOTH_FACTOR)*wt.x();\n    p.state[5] = SMOOTH_FACTOR*wt1.y() + (1.-SMOOTH_FACTOR)*wt.y();\n    p.state[6] = SMOOTH_FACTOR*wt1.z() + (1.-SMOOTH_FACTOR)*wt.z();\n  }\n\n\n  void _updateParticles(std::vector<Particle<HAND_STATE_SIZE> > &particles,\n\t\t\tdouble deltaT, double qSigma, double wSigma) const\n  {\n    boost::random::mt19937 rng(time(NULL));\n    for (std::vector<Particle<HAND_STATE_SIZE> >::iterator it=particles.begin();\n\t it!=particles.end(); ++it)\n    {\n      Particle<HAND_STATE_SIZE> &p = *it;\n      _updateParticle(p, deltaT, qSigma, wSigma, rng);\n    }\n  }\n\npublic:\n  HandPredictionModel(double initQSigma, double initWSigma,\n\t\t      double updateQSigma, double updateWSigma):\n    initQSigma(initQSigma),\n    initWSigma(initWSigma),\n    updateQSigma(updateQSigma),\n    updateWSigma(updateWSigma)\n  {}\n\n  void init(const double *initState,\n\t    std::vector<Particle<HAND_STATE_SIZE> > &particles) const\n  {\n    // Set all particle to the initial state\n    for (std::vector<Particle<HAND_STATE_SIZE> >::iterator it=particles.begin();\n\t it!=particles.end(); ++it)\n    {\n      Particle<HAND_STATE_SIZE> &p = *it;\n      std::copy(initState, initState+HAND_STATE_SIZE, p.state);\n      p.likelihood = 0.;\n    }\n    \n    _updateParticles(particles, 0., initQSigma, initWSigma);\n  }\n\n  void update(std::vector<Particle<HAND_STATE_SIZE> > &particles, double deltaT) const\n  {\n    _updateParticles(particles, deltaT, updateQSigma, updateWSigma);\n  }\n};\n\n\n\n\n#endif // __PARTICLE_FILTER_HAND_PREDICTION_HPP\n", "meta": {"hexsha": "3e4c85ef18ca02d4eeaefebc19f75a806cf91e29", "size": 4833, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/particle_filter/particle_filter_hand_prediction.hpp", "max_stars_repo_name": "mUogoro/hand_rotation_estimation_tutorial", "max_stars_repo_head_hexsha": "98707de67448016e63bb8480090e4fa139dbc896", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-15T01:05:09.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T01:05:09.000Z", "max_issues_repo_path": "src/particle_filter/particle_filter_hand_prediction.hpp", "max_issues_repo_name": "mUogoro/hand_rotation_estimation_tutorial", "max_issues_repo_head_hexsha": "98707de67448016e63bb8480090e4fa139dbc896", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/particle_filter/particle_filter_hand_prediction.hpp", "max_forks_repo_name": "mUogoro/hand_rotation_estimation_tutorial", "max_forks_repo_head_hexsha": "98707de67448016e63bb8480090e4fa139dbc896", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-11-08T09:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T07:57:45.000Z", "avg_line_length": 29.6503067485, "max_line_length": 213, "alphanum_fraction": 0.626939789, "num_tokens": 1463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5425748831304796}}
{"text": "#include <kv/eig.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <kv/dd.hpp>\n#include <kv/rdd.hpp>\n\n\nnamespace ub = boost::numeric::ublas;\n\ntypedef kv::interval< kv::dd > itvdd;\ntypedef kv::interval<double> itv;\n\nint main()\n{\n\tub::matrix<double> a;\n\tub::matrix< kv::complex<double> > v, d;\n\n\tstd::cout.precision(17);\n\n\ta.resize(2,2);\n\n\ta(0,0) = 1.;\n\ta(0,1) = 2.;\n\ta(1,0) = 3.;\n\ta(1,1) = 4.;\n\n\t// approximation\n\teig(a, v, d);\n\tstd::cout << v << \"\\n\";\n\tstd::cout << d << \"\\n\";\n\n\t// verified\n\tub::vector< kv::complex<itv> > l;\n\tveig(a, l);\n\tstd::cout << l << \"\\n\";\n\n\t// verified (interval matrix)\n\tub::matrix<itv> ia;\n\tia = a;\n\tveig(ia, l);\n\tstd::cout << l << \"\\n\";\n\n\t// verified (interval dd matrix)\n\tub::matrix<itvdd> iadd;\n\tub::vector< kv::complex<itvdd> > ldd;\n\tstd::cout.precision(34);\n\tiadd = a;\n\tveig(iadd, ldd);\n\tstd::cout << ldd << \"\\n\";\n}\n", "meta": {"hexsha": "4dbb54bcd62ca0b931796cb6704166baf19b0d96", "size": 896, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test-eig.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-eig.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-eig.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": 17.568627451, "max_line_length": 41, "alphanum_fraction": 0.5870535714, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5425748831304796}}
{"text": "//#define ARMA_NO_DEBUG\r\n\r\n#include <iostream>\r\n#include <armadillo>\r\n#include <float.h>\r\n#include <ctime>\r\n\r\nusing namespace std;\r\nusing namespace arma;\r\n\r\ntypedef double (*callback_type)(int, double[]);\r\ntypedef bool (*is_terminate_type)(long, int, double); // runid, iter, value -> isTerminate\r\n\r\nstatic uvec inverse(const uvec& indices) {\r\n    uvec inverse = uvec(indices.size());\r\n    for (int i = 0; i < indices.size(); i++)\r\n        inverse(indices(i)) = i;\r\n    return inverse;\r\n}\r\n\r\nstatic vec sequence(double start, double end, double step) {\r\n    int size = (int) ((end - start) / step + 1);\r\n    vec d(size);\r\n    double value = start;\r\n    for (int r = 0; r < size; r++) {\r\n        d(r) = value;\r\n        value += step;\r\n    }\r\n    return d;\r\n}\r\n\r\n// wrapper around the fittness function, scales according to boundaries\r\n\r\nclass Fittness {\r\n\r\npublic:\r\n\r\n    Fittness(callback_type pfunc, const vec &lower_limit,\r\n            const vec &upper_limit) {\r\n        func = pfunc;\r\n        lower = lower_limit;\r\n        upper = upper_limit;\r\n        evaluationCounter = 0;\r\n        if (lower.size() > 0) { // bounds defined\r\n            scale = 0.5 * (upper - lower);\r\n            typx = 0.5 * (upper + lower);\r\n        }\r\n    }\r\n\r\n    void closestFeasible(vec &X) const { // in place\r\n        if (lower.size() > 0)\r\n            X.for_each([](double &val) {\r\n                val = max(min(val, 1.0), -1.0);\r\n            });\r\n    }\r\n\r\n    vec getClosestFeasible(const vec &col) const {\r\n        if (lower.size() > 0) {\r\n            vec X(col);\r\n            X.for_each([](double &val) {\r\n                val = max(min(val, 1.0), -1.0);\r\n            });\r\n            return X;\r\n        }\r\n        return col;\r\n    }\r\n\r\n    double eval(const vec &X) {\r\n        int n = X.size();\r\n        double parg[n];\r\n        for (int i = 0; i < n; i++)\r\n            parg[i] = X(i);\r\n        double res = func(n, parg);\r\n        evaluationCounter++;\r\n        return res;\r\n    }\r\n\r\n    double value(const vec &X) {\r\n        double value;\r\n        if (lower.size() > 0) {\r\n            return eval(decode(getClosestFeasible(X)));\r\n        } else\r\n            return eval(X);\r\n    }\r\n\r\n    vec encode(const vec &X) const {\r\n        if (lower.size() > 0)\r\n            return (X - typx) / scale;\r\n        else\r\n            return X;\r\n    }\r\n\r\n    vec decode(const vec &X) const {\r\n        if (lower.size() > 0)\r\n            return (X % scale) + typx;\r\n        else\r\n            return X;\r\n    }\r\n\r\n    int getEvaluations() {\r\n        return evaluationCounter;\r\n    }\r\n\r\nprivate:\r\n   callback_type func;\r\n   vec lower;\r\n   vec upper;\r\n   long evaluationCounter;\r\n   vec scale;\r\n   vec typx;\r\n};\r\n\r\nclass AcmaesOptimizer {\r\n\r\npublic:\r\n\r\n    AcmaesOptimizer(long runid_, Fittness* fitfun_, int popsize_, int mu_, const vec &guess_, const vec &inputSigma_,\r\n            int maxIterations_, int maxEvaluations_, double accuracy_, double stopfitness_, is_terminate_type isTerminate_) {\r\n// runid used in isTerminate callback to identify a specific run at different iteration\r\n        runid = runid_;\r\n// fitness function to minimize\r\n        fitfun = fitfun_;\r\n// initial guess for the arguments of the fitness function\r\n        guess = guess_;\r\n// accuracy = 1.0 is default, > 1.0 reduces accuracy\r\n        accuracy = accuracy_;\r\n// callback to check if to terminate\r\n        isTerminate = isTerminate_;\r\n// Number of objective variables/problem dimension\r\n        dim = guess_.size();\r\n//     Population size, offspring number. The primary strategy parameter to play\r\n//     with, which can be increased from its default value. Increasing the\r\n//     population size improves global search properties in exchange to speed.\r\n//     Speed decreases, as a rule, at most linearly with increasing population\r\n//     size. It is advisable to begin with the default small population size.\r\n        if (popsize_ > 0)\r\n            popsize = popsize_;\r\n        else\r\n            popsize = 4 + int(3. * log(dim));\r\n//     Individual sigma values - initial search volume. inputSigma determines\r\n//     the initial coordinate wise standard deviations for the search. Setting\r\n//     SIGMA one third of the initial search region is appropriate.\r\n        if (inputSigma_.size() == 1)\r\n            inputSigma = vec(dim).fill(inputSigma_(0));\r\n        else\r\n            inputSigma = inputSigma_;\r\n// Overall standard deviation - search volume.\r\n        sigma = max(inputSigma);\r\n// termination criteria\r\n// maximal number of evaluations allowed.\r\n        maxEvaluations = maxEvaluations_;\r\n// maximal number of iterations allowed.\r\n        maxIterations = maxIterations_;\r\n// Limit for fitness value.\r\n        stopfitness = stopfitness_;\r\n// Stop if x-changes larger stopTolUpX.\r\n        stopTolUpX = 1e3 * sigma;\r\n// Stop if x-change smaller stopTolX.\r\n        stopTolX = 1e-11 * sigma * accuracy;\r\n// Stop if fun-changes smaller stopTolFun.\r\n        stopTolFun = 1e-12 * accuracy;\r\n// Stop if back fun-changes smaller stopTolHistFun.\r\n        stopTolHistFun = 1e-13 * accuracy;\r\n// selection strategy parameters\r\n// Number of parents/points for recombination.\r\n        mu = mu_ > 0 ? mu_ : popsize / 2;\r\n// Array for weighted recombination.\r\n        weights = (log(sequence(1, mu, 1)) * -1.) + log(mu + 0.5);\r\n        double sumw = sum(weights);\r\n        double sumwq = sum(weights % weights);\r\n        weights *= 1. / sumw;\r\n// Variance-effectiveness of sum w_i x_i.\r\n        mueff = sumw * sumw / sumwq;\r\n\r\n// dynamic strategy parameters and constants\r\n// Cumulation constant.\r\n        cc = (4. + mueff / dim) / (dim + 4. + 2. * mueff / dim);\r\n// Cumulation constant for step-size.\r\n        cs = (mueff + 2.) / (dim + mueff + 3.);\r\n// Damping for step-size.\r\n           damps = (1. + 2. * ::max(0., ::sqrt((mueff - 1.)\r\n                    / (dim + 1.)) - 1.))\r\n                    * max(0.3, 1.\r\n                            - // modification for short runs\r\n                            dim / (1e-6 + min(maxIterations, maxEvaluations\r\n                                    / popsize))) + cs; // minor increment\r\n// Learning rate for rank-one update.\r\n        ccov1 = 2. / ((dim + 1.3) * (dim + 1.3) + mueff);\r\n// Learning rate for rank-mu update'\r\n        ccovmu = min(1. - ccov1,\r\n                2. * (mueff - 2. + 1. / mueff)\r\n                        / ((dim + 2.) * (dim + 2.) + mueff));\r\n// Expectation of ||N(0,I)|| == norm(randn(N,1)).\r\n        chiN = sqrt(dim) * (1. - 1. / (4. * dim) + 1 / (21. * dim * dim));\r\n        ccov1Sep = min(1., ccov1 * (dim + 1.5) / 3.);\r\n        ccovmuSep = min(1. - ccov1, ccovmu * (dim + 1.5) / 3.);\r\n\r\n// CMA internal values - updated each generation\r\n// Objective variables.\r\n        xmean = fitfun->encode(guess);\r\n// Evolution path.\r\n        pc = zeros<vec>(dim);\r\n// Evolution path for sigma.\r\n        ps = zeros<vec>(dim);\r\n// Norm of ps, stored for efficiency.\r\n        normps = norm(ps);\r\n// Coordinate system.\r\n        B = mat(dim,dim).eye();\r\n// Diagonal of sqrt(D), stored for efficiency.\r\n        diagD = inputSigma / sigma;\r\n        diagC = square(diagD);\r\n// B*D, stored for efficiency.\r\n        BD = B % repmat(diagD.t(), dim, 1);\r\n// Covariance matrix.\r\n        C = B * (mat(dim,dim).eye() * B.t());\r\n// Number of iterations already performed.\r\n        iterations = 0;\r\n// Size of history queue of best values.\r\n        historySize = 10 + int(3. * 10. * dim / popsize);\r\n// stop criteria\r\n        stop = 0;\r\n// best value so far\r\n        bestValue = fitfun->value(xmean);\r\n// best parameters so far\r\n        bestX = guess;\r\n// History queue of best values.\r\n        fitnessHistory = vec(historySize).fill(DBL_MAX);\r\n        fitnessHistory(0) = bestValue;\r\n    }\r\n\r\n    // param zmean weighted row matrix of the gaussian random numbers generating the current offspring\r\n    // param xold xmean matrix of the previous generation\r\n    // return hsig flag indicating a small correction\r\n\r\n    bool updateEvolutionPaths(const vec& zmean, const vec& xold) {\r\n        ps = ps * (1. - cs) + ((B * zmean) * sqrt(cs * (2. - cs) * mueff));\r\n        normps = norm(ps);\r\n        bool hsig = normps / sqrt(1. - pow(1. - cs, 2. * iterations)) / chiN < 1.4 + 2. / (dim + 1.);\r\n        pc *= (1. - cc);\r\n        if (hsig)\r\n            pc += (xmean - xold) * (sqrt(cc * (2. - cc) * mueff) / sigma);\r\n        return hsig;\r\n    }\r\n\r\n    // param hsig flag indicating a small correction\r\n    // param bestArx fitness-sorted matrix of the argument vectors producing the current offspring\r\n    // param arz unsorted matrix containing the gaussian random values of the current offspring\r\n    // param arindex indices indicating the fitness-order of the current offspring\r\n    // param xold xmean matrix of the previous generation\r\n\r\n    double updateCovariance(bool hsig, const mat& bestArx, const mat& arz,\r\n            const uvec& arindex, const mat& xold) {\r\n        double negccov = 0;\r\n        if (ccov1 + ccovmu > 0) {\r\n            mat arpos = (bestArx - repmat(xold, 1, mu)) * (1. / sigma); // mu difference vectors\r\n            mat roneu = pc * pc.t() * ccov1;\r\n            // minor correction if hsig==false\r\n            double oldFac = hsig ? 0 : ccov1 * cc * (2. - cc);\r\n            oldFac += 1. - ccov1 - ccovmu;\r\n            // Adapt covariance matrix C active CMA\r\n            negccov = (1. - ccovmu) * 0.25 * mueff\r\n                    / (pow(dim + 2., 1.5) + 2. * mueff);\r\n            double negminresidualvariance = 0.66;\r\n            // keep at least 0.66 in all directions, small popsize are most critical\r\n            double negalphaold = 0.5; // where to make up for the variance loss,\r\n            // prepare vectors, compute negative updating matrix Cneg\r\n            uvec arReverseIndex = reverse(arindex);\r\n            mat arzneg = arz.cols(arReverseIndex.head(mu));\r\n            vec arnorms = sqrt(sum(square(arzneg.t()), 1)); // rowsum\r\n            uvec idxnorms = sort_index(arnorms);\r\n            vec arnormsSorted = arnorms(idxnorms);\r\n            uvec idxReverse = reverse(idxnorms);\r\n            vec arnormsReverse = arnorms(idxReverse);\r\n            arnorms = arnormsReverse / arnormsSorted;\r\n            vec arnormsInv = arnorms(inverse(idxnorms));\r\n            mat sqarnw = square(arnormsInv).t() * weights;\r\n            double negcovMax = (1. - negminresidualvariance) / sqarnw(0);\r\n            if (negccov > negcovMax)\r\n                negccov = negcovMax;\r\n            arzneg = arzneg % repmat(arnormsInv.t(), dim, 1);\r\n            mat artmp = BD * arzneg;\r\n            mat Cneg = artmp * diagmat(weights) * artmp.t();\r\n            oldFac += negalphaold * negccov;\r\n            C = (C * oldFac) + roneu\r\n                    + ( arpos * (ccovmu + (1. - negalphaold) * negccov) *\r\n                               (repmat(weights, 1, dim) % arpos.t()))\r\n                    - (Cneg * negccov);\r\n        }\r\n        return negccov;\r\n    }\r\n\r\n    // Update B and diagD from C\r\n    // param negccov Negative covariance factor.\r\n\r\n    void updateBD(double negccov) {\r\n\r\n        if (ccov1 + ccovmu + negccov > 0\r\n                && (std::fmod(iterations, 1. / (ccov1 + ccovmu + negccov) / dim / 10.)) < 1.) {\r\n            // to achieve O(N^2) enforce symmetry to prevent complex numbers\r\n            C = trimatu(C) + trimatu(C, 1).t();\r\n            // diagD defines the scaling\r\n            vec eigval;\r\n            mat eigvec;\r\n            eig_sym(eigval, eigvec, C);\r\n\r\n            diagD = reverse(eigval); // descending order of eigenvalues\r\n            for (int i = 0; i < dim; i++)\r\n                B.col(i) = eigvec.col(dim - 1 - i);\r\n\r\n            if (diagD.min() <= 0) {\r\n                for (int i = 0; i < dim; i++)\r\n                    if (diagD(i, 0) < 0)\r\n                        diagD(i, 0) = 0.;\r\n                double tfac = diagD.max() / 1e14;\r\n                C += mat(dim,dim).eye() * tfac;\r\n                diagD += ones(dim, 1) * tfac;\r\n            }\r\n            if (diagD.max() > 1e14 * diagD.min()) {\r\n                double tfac = diagD.max() / 1e14 - diagD.min();\r\n                C += mat(dim,dim).eye() * tfac;\r\n                diagD += ones(dim, 1) * tfac;\r\n            }\r\n            diagC = C.diag();\r\n            diagD = sqrt(diagD); // D contains standard deviations now\r\n            BD = B % repmat(diagD.t(), dim, 1);\r\n        }\r\n    }\r\n\r\n    void doOptimize() {\r\n\r\n        // -------------------- Generation Loop --------------------------------\r\n\r\n        for (iterations = 1; iterations <= maxIterations &&\r\n                    fitfun->getEvaluations() < maxEvaluations; iterations++) {\r\n            // Generate and evaluate popsize offspring\r\n            mat arz = mat(dim, popsize).randn();\r\n            mat arx = mat(dim, popsize);\r\n            vec fitness = vec(popsize).fill(DBL_MAX);\r\n            // generate random offspring\r\n            fitfun->closestFeasible(xmean);\r\n            for (int k = 0; k < popsize; k++) {\r\n                vec delta = (BD * arz.col(k)) * sigma;\r\n                arx.col(k) = fitfun->getClosestFeasible(xmean + delta);\r\n                fitness[k] = fitfun->value(arx.col(k)); // compute fitness\r\n                if (!isfinite(fitness[k])) {\r\n                    stop = -1;\r\n                    break;\r\n                }\r\n            }\r\n            if (stop != 0)\r\n                break;\r\n            // Sort by fitness and compute weighted mean into xmean\r\n            uvec arindex = sort_index(fitness);\r\n\r\n            // Calculate new xmean, this is selection and recombination\r\n            vec xold = xmean; // for speed up of Eq. (2) and (3)\r\n            uvec bestIndex = arindex.head(mu);\r\n            mat bestArx = arx.cols(bestIndex);\r\n            xmean = bestArx * weights;\r\n            mat bestArz = arz.cols(bestIndex);\r\n            mat zmean = bestArz * weights;\r\n\r\n            bool hsig = updateEvolutionPaths(zmean, xold);\r\n            double negccov = updateCovariance(hsig, bestArx, arz, arindex, xold);\r\n            updateBD(negccov);\r\n            // Adapt step size sigma - Eq. (5)\r\n            sigma *= exp(min(1.0, (normps / chiN - 1.) * cs / damps));\r\n            double bestFitness = fitness(arindex(0));\r\n            double worstFitness = fitness(arindex(arindex.size()-1));\r\n            if (bestValue > bestFitness) {\r\n                bestValue = bestFitness;\r\n                bestX = fitfun->decode(bestArx.col(0));\r\n            }\r\n\r\n            // handle termination criteria\r\n            if (isfinite(stopfitness) && bestFitness < stopfitness) {\r\n                stop = 1;\r\n                break;\r\n            }\r\n            vec sqrtDiagC = sqrt(diagC);\r\n            vec pcCol = pc;\r\n\r\n            for (int i = 0; i < dim; i++) {\r\n                if (sigma * (max(abs(pcCol[i]), sqrtDiagC[i])) > stopTolX)\r\n                    break;\r\n                if (i >= dim - 1)\r\n                    stop = 2;\r\n            }\r\n            for (int i = 0; i < dim; i++)\r\n                if (sigma * sqrtDiagC[i] > stopTolUpX)\r\n                    stop = 3;\r\n            if (stop > 0)\r\n                break;\r\n            double historyBest = min(fitnessHistory);\r\n            double historyWorst = max(fitnessHistory);\r\n            if (iterations > 2\r\n                    && max(historyWorst, worstFitness)\r\n                            - min(historyBest, bestFitness) < stopTolFun) {\r\n                stop = 4;\r\n                break;\r\n            }\r\n            if (iterations > fitnessHistory.size()\r\n                    && historyWorst - historyBest < stopTolHistFun) {\r\n                stop = 5;\r\n                break;\r\n            }\r\n            // condition number of the covariance matrix exceeds 1e14\r\n            if ( diagD.max() / diagD.min() > 1e7 * 1.0 / sqrt(accuracy)) {\r\n                stop = 6;\r\n                break;\r\n            }\r\n            if (isTerminate != NULL && isTerminate(runid, iterations, bestValue)) {\r\n                stop = 7;\r\n                break;\r\n            }\r\n            // Adjust step size in case of equal function values (flat fitness)\r\n            if (bestValue == fitness[arindex[(int) (0.1 + popsize / 4.)]]) {\r\n                sigma *= exp(0.2 + cs / damps);\r\n            }\r\n            if (iterations > 2\r\n                    && max(historyWorst, bestFitness)\r\n                            - ::min(historyBest, bestFitness) == 0) {\r\n                sigma *= ::exp(0.2 + cs / damps);\r\n            }\r\n            // store best in history\r\n            for (int i = 1; i < fitnessHistory.size(); i++)\r\n                fitnessHistory[i] = fitnessHistory[i - 1];\r\n            fitnessHistory[0] = bestFitness;\r\n        }\r\n    }\r\n\r\n    vec getBestX() {\r\n        return bestX;\r\n    }\r\n\r\n    double getBestValue() {\r\n        return bestValue;\r\n    }\r\n\r\n    double getIterations() {\r\n        return iterations;\r\n    }\r\n\r\n    double getStop() {\r\n        return stop;\r\n    }\r\n\r\n\r\nprivate:\r\n      long runid;\r\n      Fittness* fitfun;\r\n      vec guess;\r\n      double accuracy;\r\n      is_terminate_type isTerminate;\r\n      int popsize; // population size\r\n      vec inputSigma;\r\n      int dim;\r\n      int maxIterations;\r\n      int maxEvaluations;\r\n      double stopfitness;\r\n      double stopTolUpX;\r\n      double stopTolX;\r\n      double stopTolFun;\r\n      double stopTolHistFun;\r\n      int mu; //\r\n      vec weights;\r\n      double mueff; //\r\n      double sigma;\r\n      double cc;\r\n      double cs;\r\n      double damps;\r\n      double ccov1;\r\n      double ccovmu;\r\n      double chiN;\r\n      double ccov1Sep;\r\n      double ccovmuSep;\r\n      vec xmean;\r\n      vec pc;\r\n      vec ps;\r\n      double normps;\r\n      mat B;\r\n      mat BD;\r\n      mat diagD;\r\n      mat C;\r\n      vec diagC;\r\n      int iterations;\r\n      vec fitnessHistory;\r\n      int historySize;\r\n      double bestValue;\r\n      vec bestX;\r\n      int stop;\r\n};\r\n\r\n// see https://cvstuff.wordpress.com/2014/11/27/wraping-c-code-with-python-ctypes-memory-and-pointers/\r\n\r\nextern \"C\" {\r\n    void seed(int s) {\r\n        arma_rng::set_seed(s);\r\n    }\r\n}\r\n\r\nextern \"C\" {\r\n    void seedRandom() {\r\n        arma_rng::set_seed_random();\r\n    }\r\n}\r\n\r\nextern \"C\" {\r\n    void free_mem(double* a) {\r\n        delete[] a;\r\n    }\r\n}\r\n\r\nextern \"C\" {\r\n    double* optimizeACMA_C(long runid, callback_type func, int dim, double *init,\r\n            double *lower, double *upper, double *sigma, int maxIter, int maxEvals,\r\n            double stopfitness, int mu, int popsize, double accuracy,\r\n            bool useTerminate, is_terminate_type isTerminate) {\r\n        int n = dim;\r\n        double *res = new double[n + 4];\r\n        vec guess(n), lower_limit(n), upper_limit(n), inputSigma(n);\r\n        bool useLimit = false;\r\n        for (int i = 0; i < n; i++) {\r\n            guess[i] = init[i];\r\n            inputSigma[i] = sigma[i];\r\n            lower_limit[i] = lower[i];\r\n            upper_limit[i] = upper[i];\r\n            useLimit |= (lower[i] != 0);\r\n            useLimit |= (upper[i] != 0);\r\n        }\r\n        if (useLimit == false) {\r\n            lower_limit.resize(0);\r\n            upper_limit.resize(0);\r\n        } \r\n        Fittness fitfun(func, lower_limit, upper_limit);\r\n        AcmaesOptimizer opt(\r\n            runid,\r\n            &fitfun,\r\n            popsize,\r\n            mu,\r\n            guess,\r\n            inputSigma,\r\n            maxIter,\r\n            maxEvals,\r\n            accuracy,\r\n            stopfitness,\r\n            useTerminate ? isTerminate : NULL);\r\n        try {\r\n            opt.doOptimize();\r\n            vec bestX = opt.getBestX();\r\n            double bestY = opt.getBestValue();\r\n            for (int i = 0; i < n; i++)\r\n                res[i] = bestX[i];\r\n            res[n] = bestY;\r\n            res[n+1] = fitfun.getEvaluations();\r\n            res[n+2] = opt.getIterations();\r\n            res[n+3] = opt.getStop();\r\n            return res;\r\n        } catch (std::exception& e) {\r\n            cout << e.what() << endl;\r\n            return res;\r\n        }\r\n    }\r\n}\r\n", "meta": {"hexsha": "544ec4912a10f70aec845b96869d58f5e0523efc", "size": 19895, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_fcmaescpp/acmaesoptimizer.cpp", "max_stars_repo_name": "juliendehos/fast-cma-es", "max_stars_repo_head_hexsha": "ebf74f908dcee22b617fc6759480fc6f9f717460", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_fcmaescpp/acmaesoptimizer.cpp", "max_issues_repo_name": "juliendehos/fast-cma-es", "max_issues_repo_head_hexsha": "ebf74f908dcee22b617fc6759480fc6f9f717460", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_fcmaescpp/acmaesoptimizer.cpp", "max_forks_repo_name": "juliendehos/fast-cma-es", "max_forks_repo_head_hexsha": "ebf74f908dcee22b617fc6759480fc6f9f717460", "max_forks_repo_licenses": ["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.2123893805, "max_line_length": 126, "alphanum_fraction": 0.511837145, "num_tokens": 5053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5424776776051757}}
{"text": "// Copyright (C) 2011  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n#include \"tester.h\"\n#include <dlib/svm.h>\n#include <dlib/data_io.h>\n#include <dlib/sparse_vector.h>\n#include \"create_iris_datafile.h\"\n#include <vector>\n#include <sstream>\n\nnamespace  \n{\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n    dlib::logger dlog(\"test.data_io\");\n\n\n    class test_data_io : public tester\n    {\n        /*!\n            WHAT THIS OBJECT REPRESENTS\n                This object represents a unit test.  When it is constructed\n                it adds itself into the testing framework.\n        !*/\n    public:\n        test_data_io (\n        ) :\n            tester (\n                \"test_data_io\",       // the command line argument name for this test\n                \"Run tests on the data_io stuff.\", // the command line argument description\n                0                     // the number of command line arguments for this test\n            )\n        {\n        }\n\n\n        template <typename sample_type>\n        void run_test()\n        {\n            print_spinner();\n\n            typedef typename sample_type::value_type::second_type scalar_type;\n\n            std::vector<sample_type> samples;\n            std::vector<scalar_type> labels;\n\n            load_libsvm_formatted_data(\"iris.scale\",samples, labels);\n            save_libsvm_formatted_data(\"iris.scale2\", samples, labels);\n\n            DLIB_TEST(samples.size() == 150);\n            DLIB_TEST(labels.size() == 150);\n            DLIB_TEST(max_index_plus_one(samples) == 5);\n            fix_nonzero_indexing(samples);\n            DLIB_TEST(max_index_plus_one(samples) == 4);\n\n            load_libsvm_formatted_data(\"iris.scale2\",samples, labels);\n\n            DLIB_TEST(samples.size() == 150);\n            DLIB_TEST(labels.size() == 150);\n\n            DLIB_TEST(max_index_plus_one(samples) == 5);\n            fix_nonzero_indexing(samples);\n            DLIB_TEST(max_index_plus_one(samples) == 4);\n\n            one_vs_one_trainer<any_trainer<sample_type,scalar_type>,scalar_type> trainer;\n\n            typedef sparse_linear_kernel<sample_type> kernel_type;\n            trainer.set_trainer(krr_trainer<kernel_type>());\n\n            randomize_samples(samples, labels);\n            matrix<double> cv = cross_validate_multiclass_trainer(trainer, samples, labels, 4);\n\n            dlog << LINFO << \"confusion matrix: \\n\" << cv;\n            const scalar_type cv_accuracy = sum(diag(cv))/sum(cv);\n            dlog << LINFO << \"cv accuracy: \" << cv_accuracy;\n            DLIB_TEST(cv_accuracy > 0.97);\n\n\n\n\n            {\n                print_spinner();\n                typedef matrix<scalar_type,0,1> dsample_type;\n                std::vector<dsample_type> dsamples = sparse_to_dense(samples);\n                DLIB_TEST(dsamples.size() == 150);\n                DLIB_TEST(dsamples[0].size() == 4);\n                DLIB_TEST(max_index_plus_one(dsamples) == 4);\n\n                one_vs_one_trainer<any_trainer<dsample_type,scalar_type>,scalar_type> trainer;\n\n                typedef linear_kernel<dsample_type> kernel_type;\n                trainer.set_trainer(rr_trainer<kernel_type>());\n\n                cv = cross_validate_multiclass_trainer(trainer, dsamples, labels, 4);\n\n                dlog << LINFO << \"dense confusion matrix: \\n\" << cv;\n                const scalar_type cv_accuracy = sum(diag(cv))/sum(cv);\n                dlog << LINFO << \"dense cv accuracy: \" << cv_accuracy;\n                DLIB_TEST(cv_accuracy > 0.97);\n            }\n\n        }\n\n\n        void test_sparse_to_dense()\n        {\n            {\n                std::map<unsigned long, double> temp;\n\n                matrix<double,0,1> m, m2;\n\n                m = sparse_to_dense(m);\n                DLIB_TEST(m.size() == 0);\n                m.set_size(2,1);\n                m = 1, 2;\n                m2 = sparse_to_dense(m);\n                DLIB_TEST(m == m2);\n                m2 = sparse_to_dense(m,1);\n                DLIB_TEST(m2.size() == 1);\n                DLIB_TEST(m2(0,0) == 1);\n                m2 = sparse_to_dense(m,0);\n                DLIB_TEST(m2.size() == 0);\n\n                temp[3] = 2;\n                temp[5] = 4;\n                m2 = sparse_to_dense(temp);\n                m.set_size(6);\n                m = 0,0,0,2,0,4;\n                DLIB_TEST(m2 == m);\n\n                m2 = sparse_to_dense(temp, 5);\n                m.set_size(5);\n                m = 0,0,0,2,0;\n                DLIB_TEST(m2 == m);\n\n                m2 = sparse_to_dense(temp, 7);\n                m.set_size(7);\n                m = 0,0,0,2,0,4,0;\n                DLIB_TEST(m2 == m);\n\n                std::vector<std::vector<std::pair<unsigned long,double> > > vects;\n\n                std::vector<std::pair<unsigned long,double> > v;\n                v.push_back(make_pair(5,2));\n                v.push_back(make_pair(3,1));\n                v.push_back(make_pair(5,2));\n                v.push_back(make_pair(3,1));\n                v = make_sparse_vector(v);\n                vects.push_back(v);\n                vects.push_back(v);\n                vects.push_back(v);\n                vects.push_back(v);\n                DLIB_TEST(max_index_plus_one(v) == 6);\n                m2 = sparse_to_dense(v);\n                m.set_size(6);\n                m = 0,0,0,2,0,4;\n                DLIB_TEST_MSG(m2 == m, m2 << \"\\n\\n\" << m );\n\n                m2 = sparse_to_dense(v,7);\n                m.set_size(7);\n                m = 0,0,0,2,0,4,0;\n                DLIB_TEST(m2 == m);\n\n                m2 = sparse_to_dense(v,5);\n                m.set_size(5);\n                m = 0,0,0,2,0;\n                DLIB_TEST(m2 == m);\n\n                v.clear();\n                m2 = sparse_to_dense(v);\n                DLIB_TEST(m2.size() == 0);\n\n\n                std::vector<matrix<double,0,1> > mvects = sparse_to_dense(vects);\n                DLIB_TEST(mvects.size() == 4);\n                m.set_size(6);\n                m = 0,0,0,2,0,4;\n                DLIB_TEST(mvects[0] == m);\n                DLIB_TEST(mvects[1] == m);\n                DLIB_TEST(mvects[2] == m);\n                DLIB_TEST(mvects[3] == m);\n\n\n                mvects = sparse_to_dense(vects, 7);\n                DLIB_TEST(mvects.size() == 4);\n                m.set_size(7);\n                m = 0,0,0,2,0,4,0;\n                DLIB_TEST(mvects[0] == m);\n                DLIB_TEST(mvects[1] == m);\n                DLIB_TEST(mvects[2] == m);\n                DLIB_TEST(mvects[3] == m);\n\n                mvects = sparse_to_dense(vects, 5);\n                DLIB_TEST(mvects.size() == 4);\n                m.set_size(5);\n                m = 0,0,0,2,0;\n                DLIB_TEST(mvects[0] == m);\n                DLIB_TEST(mvects[1] == m);\n                DLIB_TEST(mvects[2] == m);\n                DLIB_TEST(mvects[3] == m);\n\n            }\n        }\n\n\n        void perform_test (\n        )\n        {\n            print_spinner();\n            create_iris_datafile();\n\n            test_sparse_to_dense();\n\n            run_test<std::map<unsigned int, double> >();\n            run_test<std::map<unsigned int, float> >();\n            run_test<std::vector<std::pair<unsigned int, float> > >();\n            run_test<std::vector<std::pair<unsigned long, double> > >();\n        }\n    };\n\n    test_data_io a;\n\n}\n\n\n", "meta": {"hexsha": "a6673d32eece1c6f6ffb7cd2395cb10d91f69ce0", "size": 7336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/dlib/test/data_io.cpp", "max_stars_repo_name": "markovchainz/cppagent", "max_stars_repo_head_hexsha": "97314ec43786a90697ca7fda15db13f2973aee3e", "max_stars_repo_licenses": ["Apache-2.0"], "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": "lib/dlib/test/data_io.cpp", "max_issues_repo_name": "markovchainz/cppagent", "max_issues_repo_head_hexsha": "97314ec43786a90697ca7fda15db13f2973aee3e", "max_issues_repo_licenses": ["Apache-2.0"], "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": "lib/dlib/test/data_io.cpp", "max_forks_repo_name": "markovchainz/cppagent", "max_forks_repo_head_hexsha": "97314ec43786a90697ca7fda15db13f2973aee3e", "max_forks_repo_licenses": ["Apache-2.0"], "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": 32.1754385965, "max_line_length": 95, "alphanum_fraction": 0.4930479826, "num_tokens": 1796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.542477667331757}}
{"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//! \\file\r\n//!\\brief Tests for sqrt(fixed_point) with round::fastest.\r\n\r\n#include <cmath>\r\n\r\n#define BOOST_TEST_MODULE test_negatable_func_sqrt_small_fastest\r\n#define BOOST_LIB_DIAGNOSTIC\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 FixedPointType>\r\n  const FixedPointType& tolerance_maker(const int fuzzy_bits)\r\n  {\r\n    static const FixedPointType the_tolerance = ldexp(FixedPointType(1), FixedPointType::resolution + fuzzy_bits);\r\n\r\n    return the_tolerance;\r\n  }\r\n\r\n  template<typename FixedPointType,\r\n           typename FloatPointType = typename FixedPointType::float_type>\r\n  void test_sqrt(const int fuzzy_bits)\r\n  {\r\n    // Use at least 6 resolution bits.\r\n    // Use at least 8 range bits.\r\n\r\n    BOOST_STATIC_ASSERT(-FixedPointType::resolution >= 6);\r\n    BOOST_STATIC_ASSERT( FixedPointType::range      >= 7);\r\n\r\n    using std::sqrt;\r\n\r\n    const FixedPointType a1 (  2L    );                                      const FloatPointType b1(  2L    );\r\n    const FixedPointType a2 (  3L    );                                      const FloatPointType b2(  3L    );\r\n    const FixedPointType a3 (  8.375L);                                      const FloatPointType b3(  8.375L);\r\n    const FixedPointType a4 ( 64.125L);                                      const FloatPointType b4( 64.125L);\r\n    const FixedPointType a5 (100.875L);                                      const FloatPointType b5(100.875L);\r\n    const FixedPointType a6 (FixedPointType(  1) / 10);                      const FloatPointType b6(FloatPointType(  1) / 10);\r\n    const FixedPointType a7 (FixedPointType( 12) / 10);                      const FloatPointType b7(FloatPointType( 12) / 10);\r\n    const FixedPointType a8 (FixedPointType(111) / 10);                      const FloatPointType b8(FloatPointType(111) / 10);\r\n    const FixedPointType a9 (boost::math::constants::phi<FixedPointType>()); const FloatPointType b9(boost::math::constants::phi<FloatPointType>());\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a1), FixedPointType(sqrt(b1)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a2), FixedPointType(sqrt(b2)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a3), FixedPointType(sqrt(b3)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a4), FixedPointType(sqrt(b4)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a5), FixedPointType(sqrt(b5)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a6), FixedPointType(sqrt(b6)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a7), FixedPointType(sqrt(b7)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a8), FixedPointType(sqrt(b8)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a9), FixedPointType(sqrt(b9)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_func_sqrt_small_fastest)\r\n{\r\n  // Test sqrt() round::fastest for negatable in various key small digit ranges\r\n\r\n  { typedef boost::fixed_point::negatable<7,  -8, boost::fixed_point::round::fastest> fixed_point_type; local::test_sqrt<fixed_point_type>(4); }\r\n  { typedef boost::fixed_point::negatable<7, -16, boost::fixed_point::round::fastest> fixed_point_type; local::test_sqrt<fixed_point_type>(4); }\r\n  { typedef boost::fixed_point::negatable<7, -24, boost::fixed_point::round::fastest> fixed_point_type; local::test_sqrt<fixed_point_type>(4); }\r\n\r\n  { typedef boost::fixed_point::negatable<4, -11, boost::fixed_point::round::fastest> fixed_point_type; BOOST_CHECK_EQUAL(sqrt(fixed_point_type(1)), fixed_point_type(1)); }\r\n  { typedef boost::fixed_point::negatable<7, -24, boost::fixed_point::round::fastest> fixed_point_type; BOOST_CHECK_EQUAL(sqrt(fixed_point_type(1)), fixed_point_type(1)); }\r\n}\r\n", "meta": {"hexsha": "62e4030f2630d8e4c61d2cd0e96e822565fae140", "size": 4379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_func_sqrt_small_fastest.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_func_sqrt_small_fastest.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_func_sqrt_small_fastest.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": 58.3866666667, "max_line_length": 173, "alphanum_fraction": 0.6889700845, "num_tokens": 1106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5424776639566428}}
{"text": "#include <boost/math/differentiation/autodiff.hpp>\n#include <iostream>\n\nusing namespace std;\nusing namespace boost::math::differentiation;\n\nconstexpr double PI = M_PI;\n\ntemplate<typename X>\nauto sqr(const X& x) { return x * x; }\n\n#include <random>\n\ndouble clamp(double x, double min_x, double max_x) {\n    if (x > max_x) return max_x;\n    if (x < min_x) return min_x;\n    return x;\n}\n\n// TODO adam, vector as input, benchmarks\n\ntemplate<typename Func>\nvoid optimize(const char* name, double range, bool newton, const Func& func) {\n    cout << name << endl;\n    std::mt19937 rng(0);\n\n    double best = 1e100;\n    std::uniform_real_distribution<double> unif(-range, range);\n    double best_wx = unif(rng), best_wy = unif(rng);\n    double dev = range / 3;\n    size_t evals = 100 * 1000 * 1000;\n    const double alpha = newton ? 1 : 1e-2;\n    size_t misses = 0;\n\n    for (size_t j = 0; evals > 0; j++) {\n        double wx = clamp(std::normal_distribution<>(best_wx, dev)(rng), -range, range);\n        double wy = clamp(std::normal_distribution<>(best_wy, dev)(rng), -range, range);\n        bool improved = false;\n        for (size_t i = 0; i < 10000; i++) {\n            double result, dx, dy, d2x = 1, d2y = 1;\n            if (newton) {\n                const auto in = make_ftuple<double, 2, 2>(wx, wy);\n                const auto& f = func(std::get<0>(in), std::get<1>(in));\n                result = f.derivative(0, 0);\n                dx = f.derivative(1, 0);\n                dy = f.derivative(0, 1);\n                d2x = f.derivative(2, 0);\n                d2y = f.derivative(0, 2);\n            } else {\n                const auto in = make_ftuple<double, 1, 1>(wx, wy);\n                const auto& f = func(std::get<0>(in), std::get<1>(in));\n                result = f.derivative(0, 0);\n                dx = f.derivative(1, 0);\n                dy = f.derivative(0, 1);\n            }\n            if (result < best) {\n                best = result;\n                best_wx = wx;\n                best_wy = wy;\n                improved = true;\n            }\n            if (isnan(dx) || isnan(dy) || isnan(d2x) || isnan(d2y)) {\n                cout << \"nan gradients at \" << wx << \" \" << wy << endl;\n                return;\n            }\n            wx -= alpha * dx / d2x;\n            wy -= alpha * dy / d2y;\n            if (abs(dx) < 1e-15 && abs(dy) < 1e-15) break;\n            if (--evals == 0) break;\n            if (wx < -range || wx > range) break;\n            if (wy < -range || wy > range) break;\n        }\n        if (improved) {\n            misses = 0;\n            dev *= 0.95;\n            cout << setprecision(15) << \"x=\" << best_wx << \" y=\" << best_wy << \" f=\" << best << \" dev=\" << dev << endl;\n        } else {\n            misses += 1;\n            if (misses == 1000)\n                break;\n        }\n    }\n    cout << endl;\n}\n\n#define Optimize(A, B, C) \\\n    optimize(A, B, false, [](const auto& x, const auto& y){C;}); \\\n    optimize(A, B, true, [](const auto& x, const auto& y){C;})\n\nint main() {\n    Optimize(\"sphere\", 10, return sqr(x) + sqr(y));\n    Optimize(\"booth\", 10, return sqr(x + 2*y - 7) + sqr(2*x + y - 5));\n    Optimize(\"rastrigin\", 5.12, return 20 + (x*x - 10*cos(2*PI*x)) + (y*y - 10*cos(2*PI*y)));\n    Optimize(\"rosenbrock\", 10, return 100*sqr(y - x*x) + sqr(1 - x));\n    Optimize(\"easom\", 100, return -cos(x)*cos(y)*exp(-sqr(x - PI) - sqr(y - PI)));\n    Optimize(\"himmelblau\", 5, return sqr(x*x + y - 11) + sqr(x + y*y - 7));\n    Optimize(\"styblinski\u2013tang\", 5, return x*x*x*x - 16*x*x + 5*x + y*y*y*y - 16*y*y + 5*y);\n    Optimize(\"schaffer n.2\", 100, return 0.5 + (sqr(sin(x*x - y*y)) - 0.5) / sqr(1 + 0.001*(x*x + y*y)));\n    Optimize(\"h\u00f6lder table\", 10, return -abs(sin(x)*cos(y)*exp(abs(1 - sqrt(x*x + y*y)/PI))));\n}\n", "meta": {"hexsha": "5e22444fd20cd45dabf62a4454306d9d49f1d429", "size": 3753, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main.cc", "max_stars_repo_name": "tintor/optimization", "max_stars_repo_head_hexsha": "486e273b20656553ccd54c6770eaf3e8ac6918bf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cc", "max_issues_repo_name": "tintor/optimization", "max_issues_repo_head_hexsha": "486e273b20656553ccd54c6770eaf3e8ac6918bf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cc", "max_forks_repo_name": "tintor/optimization", "max_forks_repo_head_hexsha": "486e273b20656553ccd54c6770eaf3e8ac6918bf", "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.1584158416, "max_line_length": 119, "alphanum_fraction": 0.4972022382, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.5424643170666821}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Suites\n#include <boost/test/unit_test.hpp>\n\n#include<iostream>\n\n#include\"numerics.hpp\"\n#include\"diag.hpp\"\n#include \"files.hpp\"\nusing namespace boost::unit_test;\nusing boost::unit_test_framework::test_suite;\nusing namespace Many_Body;\nBOOST_AUTO_TEST_SUITE(timeevesting)\nBOOST_AUTO_TEST_CASE(timeev)\n{\n  {  size_t size=5;\n  Eigen::VectorXcd x = Eigen::VectorXcd::Random(size);\n  x=x/x.norm();\n\n    Eigen::MatrixXd AA = Eigen::MatrixXd::Random(size, size);\n     Eigen::MatrixXd A = AA + AA.transpose();\n\n  Eigen::MatrixXd B=A;\n  Eigen::VectorXd evA(size);\n  Eigen::VectorXd evB(size);\n  Eigen::MatrixXcd Q(size, size);\n  Many_Body::TriDiagMat tri=Many_Body::Lanczos(B, x, size, Q);\n\nEigen::MatrixXd S(size, size);\n S.setZero();\n diag(tri, S, evB);\n  diag(A, evA);\n\n  for (int i = 0; i < size; ++i)\n  {\n       BOOST_CHECK(std::abs(evA(i)-evB(i))<Many_Body::err);\n  }\n\n  }{\n    size_t size=5;\n  Eigen::VectorXcd x = Eigen::VectorXcd::Random(size);\n  x=x/x.norm();\n\n    Eigen::MatrixXcd AA = Eigen::MatrixXcd::Random(size, size);\n    Eigen::MatrixXcd A = AA.adjoint()*AA;\n\n\n  Eigen::MatrixXcd B=A;\n  Eigen::VectorXd evA(size);\n  Eigen::VectorXd evB(size);\n  Eigen::MatrixXcd Q(size, size);\n  Many_Body::TriDiagMat tri=Many_Body::Lanczos(B, x, size, Q);\n\nEigen::MatrixXd S(size, size);\n  S.setZero();\n  diag(tri, S, evB);\n   diag(A, evA);\n        std::cout << '\\n';\n  for (int i = 0; i < size; ++i)\n  {\n    BOOST_CHECK(std::abs(evA(i)-evB(i))<Many_Body::err);\n\n\n  }\n  }\n  //\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n// EOF\n", "meta": {"hexsha": "70f30c4ea901b317ed22518997f1d1657e64ec00", "size": 1562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarkdir/diagtest.cpp", "max_stars_repo_name": "jansendavid/many-body-lib", "max_stars_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmarkdir/diagtest.cpp", "max_issues_repo_name": "jansendavid/many-body-lib", "max_issues_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarkdir/diagtest.cpp", "max_forks_repo_name": "jansendavid/many-body-lib", "max_forks_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_forks_repo_licenses": ["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.6944444444, "max_line_length": 63, "alphanum_fraction": 0.6587708067, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5424643127873847}}
{"text": "#include <stan/math/mix/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/hypot.hpp>\n#include <test/unit/math/rev/scal/fun/util.hpp>\n#include <test/unit/math/mix/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdHypot, FvarVar_FvarVar_1stDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(3.0, 1.3);\n\n  fvar<var> z(6.0, 1.0);\n  fvar<var> a = hypot(x, z);\n\n  EXPECT_FLOAT_EQ(hypot(3.0, 6.0), a.val_.val());\n  EXPECT_FLOAT_EQ((1.3 * 3.0 + 6.0 * 1.0) / hypot(3.0, 6.0), a.d_.val());\n\n  AVEC y = createAVEC(x.val_, z.val_);\n  VEC g;\n  a.val_.grad(y, g);\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0, 6.0), g[0]);\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0, 6.0), g[1]);\n}\nTEST(AgradFwdHypot, FvarVar_Double_1stDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(3.0, 1.3);\n  double z(6.0);\n  fvar<var> a = hypot(x, z);\n\n  EXPECT_FLOAT_EQ(hypot(3.0, 6.0), a.val_.val());\n  EXPECT_FLOAT_EQ((1.3 * 3.0) / hypot(3.0, 6.0), a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.val_.grad(y, g);\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0, 6.0), g[0]);\n}\nTEST(AgradFwdHypot, Double_FvarVar_1stDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(3.0);\n  fvar<var> z(6.0, 1.0);\n  fvar<var> a = hypot(x, z);\n\n  EXPECT_FLOAT_EQ(hypot(3.0, 6.0), a.val_.val());\n  EXPECT_FLOAT_EQ((6.0 * 1.0) / hypot(3.0, 6.0), a.d_.val());\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.val_.grad(y, g);\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0, 6.0), g[0]);\n}\nTEST(AgradFwdHypot, FvarVar_FvarVar_2ndDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(3.0, 1.3);\n  fvar<var> z(6.0, 1.0);\n  fvar<var> a = hypot(x, z);\n\n  AVEC y = createAVEC(x.val_, z.val_);\n  VEC g;\n  a.d_.grad(y, g);\n  EXPECT_FLOAT_EQ(\n      (1.3 * 6.0 * 6.0 - 6.0 * 3.0) / hypot(3.0, 6.0) / (9.0 + 36.0), g[0]);\n  EXPECT_FLOAT_EQ(\n      (1.0 * 3.0 * 3.0 - 1.3 * 6.0 * 3.0) / hypot(3.0, 6.0) / (9.0 + 36.0),\n      g[1]);\n}\nTEST(AgradFwdHypot, FvarVar_Double_2ndDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(3.0, 1.3);\n  double z(6.0);\n  fvar<var> a = hypot(x, z);\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.d_.grad(y, g);\n  EXPECT_FLOAT_EQ(1.3 * 6.0 * 6.0 / hypot(3.0, 6.0) / (9.0 + 36.0), g[0]);\n}\nTEST(AgradFwdHypot, Double_FvarVar_2ndDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(3.0);\n  fvar<var> z(6.0, 1.0);\n  fvar<var> a = hypot(x, z);\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.d_.grad(y, g);\n  EXPECT_FLOAT_EQ(1.0 * 3.0 * 3.0 / hypot(3.0, 6.0) / (9.0 + 36.0), g[0]);\n}\n\nTEST(AgradFwdHypot, FvarFvarVar_FvarFvarVar_1stDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x, y);\n\n  EXPECT_FLOAT_EQ(hypot(3.0, 6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0, 6.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0, 6.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.059628479, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_, y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p, g);\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0, 6.0), g[0]);\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0, 6.0), g[1]);\n}\nTEST(AgradFwdHypot, FvarFvarVar_Double_1stDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  double y(6.0);\n\n  fvar<fvar<var> > a = hypot(x, y);\n\n  EXPECT_FLOAT_EQ(hypot(3.0, 6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0, 6.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p, g);\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0, 6.0), g[0]);\n}\n\nTEST(AgradFwdHypot, Double_FvarFvarVar_1stDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(3.0);\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x, y);\n\n  EXPECT_FLOAT_EQ(hypot(3.0, 6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0, 6.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p, g);\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0, 6.0), g[0]);\n}\nTEST(AgradFwdHypot, FvarFvarVar_FvarFvarVar_2ndDeriv_x) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x, y);\n\n  AVEC p = createAVEC(x.val_.val_, y.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p, g);\n\n  EXPECT_FLOAT_EQ(36.0 / hypot(3.0, 6.0) / (9.0 + 36.0), g[0]);\n  EXPECT_FLOAT_EQ(-2.0 / 15.0 / std::sqrt(5.0), g[1]);\n}\nTEST(AgradFwdHypot, FvarFvarVar_FvarFvarVar_2ndDeriv_y) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x, y);\n\n  AVEC p = createAVEC(x.val_.val_, y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p, g);\n  EXPECT_FLOAT_EQ(-2.0 / 15.0 / std::sqrt(5.0), g[0]);\n  EXPECT_FLOAT_EQ((3.0 * 3.0) / hypot(3.0, 6.0) / (9.0 + 36.0), g[1]);\n}\nTEST(AgradFwdHypot, FvarFvarVar_Double_2ndDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  double y(6.0);\n\n  fvar<fvar<var> > a = hypot(x, y);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p, g);\n\n  EXPECT_FLOAT_EQ(6.0 * 6.0 / hypot(3.0, 6.0) / (9.0 + 36.0), g[0]);\n}\n\nTEST(AgradFwdHypot, Double_FvarFvarVar_2ndDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(3.0);\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x, y);\n\n  EXPECT_FLOAT_EQ(hypot(3.0, 6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0, 6.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p, g);\n  EXPECT_FLOAT_EQ((3.0 * 3.0) / hypot(3.0, 6.0) / (9.0 + 36.0), g[0]);\n}\nTEST(AgradFwdHypot, FvarFvarVar_FvarFvarVar_3rdDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x, y);\n\n  AVEC p = createAVEC(x.val_.val_, y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p, g);\n  EXPECT_FLOAT_EQ(-0.0079504643, g[0]);\n  EXPECT_FLOAT_EQ(0.013913312, g[1]);\n}\nTEST(AgradFwdHypot, FvarFvarVar_Double_3rdDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  x.d_.val_ = 1.0;\n  double y(6.0);\n\n  fvar<fvar<var> > a = hypot(x, y);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p, g);\n\n  EXPECT_FLOAT_EQ(-0.02385139175999775676169785246647, g[0]);\n}\n\nTEST(AgradFwdHypot, Double_FvarFvarVar_3rdDeriv) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(3.0);\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n  y.val_.d_ = 1.0;\n\n  fvar<fvar<var> > a = hypot(x, y);\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p, g);\n  EXPECT_FLOAT_EQ(-0.0119256958799988783808489262332, g[0]);\n}\n\nstruct hypot_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 hypot(arg1, arg2);\n  }\n};\n\nTEST(AgradFwdHypot, nan) {\n  hypot_fun hypot_;\n  test_nan_mix(hypot_, 3.0, 5.0, false);\n}\n", "meta": {"hexsha": "c8a517b6acaff82284a28f381d5d9b374f4a180a", "size": 8079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/mix/scal/fun/hypot_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/mix/scal/fun/hypot_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/mix/scal/fun/hypot_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": 24.4818181818, "max_line_length": 76, "alphanum_fraction": 0.6118331477, "num_tokens": 3624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5424643056833156}}
{"text": "// 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#include <OpenTissue/core/spline/spline.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n\n// Boost Test declaration and Checking macros\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/test_tools.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\ntypedef OpenTissue::spline::MathTypes<double, size_t>    math_types;\ntypedef math_types::vector_type                                vector_type;\ntypedef std::vector<double>                                    knot_container;\ntypedef std::vector<vector_type>                               point_container;\n\ntypedef OpenTissue::spline::NUBSpline<knot_container, point_container> spline_type;\n\nBOOST_AUTO_TEST_SUITE(opentissue_spline_make_periodic);\n\nBOOST_AUTO_TEST_CASE(test_make_periodic)\n{\n  knot_container U;\n\n  U.push_back(0.0);\n  U.push_back(0.0);\n  U.push_back(0.0);  //k = 3\n  U.push_back(1.0);\n  U.push_back(2.0);\n  U.push_back(3.0);\n  U.push_back(4.0);  // n = 6  => |P| = 7\n  U.push_back(5.0);\n  U.push_back(5.0);\n  U.push_back(5.0);  // m = 9  => |U| = 10\n\n  point_container P;\n  vector_type p0(2);  p0(0) = 0.0; p0(1) = 0.0;\n  vector_type p1(2);  p1(0) = 1.0; p1(1) = 0.0;\n  vector_type p2(2);  p2(0) = 2.0; p2(1) = 0.0;\n  vector_type p3(2);  p3(0) = 3.0; p3(1) = 0.0;\n  vector_type p4(2);  p4(0) = 4.0; p4(1) = 0.0;\n  vector_type p5(2);  p5(0) = 5.0; p5(1) = 0.0;\n  vector_type p6(2);  p6(0) = 6.0; p6(1) = 0.0;\n\n  P.push_back(p0);\n  P.push_back(p1);\n  P.push_back(p2);\n  P.push_back(p3);\n  P.push_back(p4);\n  P.push_back(p5);\n  P.push_back(p6);\n\n  spline_type spline(3,U,P);\n\n  spline_type closed = OpenTissue::spline::make_periodic( spline );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "c5fce03f9e379f9edc4d24101564b6a3ed019d33", "size": 1871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/spline/make_periodic/src/unit_make_periodic.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/make_periodic/src/unit_make_periodic.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/make_periodic/src/unit_make_periodic.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": 30.1774193548, "max_line_length": 83, "alphanum_fraction": 0.6579369321, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.5424643051183605}}
{"text": "#include <boost/lexical_cast.hpp>\n#include \"Poisson.hh\"\n#include \"TMath.h\"\n#include <Eigen/Core>\n#include <cmath>\n\nusing namespace Eigen;\n\nPoisson::Poisson(bool ln_approx) {\n  transformation_(\"poisson\")\n    .output(\"poisson\")\n    .types(&Poisson::checkTypes)\n    .func(ln_approx ? &Poisson::calcPoissonApprox : &Poisson::calcPoisson)\n    ;\n  m_transform = t_[\"poisson\"];\n}\n\nvoid Poisson::add(SingleOutput &theory, SingleOutput &data) {\n  t_[\"poisson\"].input(theory);\n  t_[\"poisson\"].input(data);\n}\n\n\nvoid Poisson::checkTypes(TypesFunctionArgs fargs) {\n  auto& args=fargs.args;\n  auto& rets=fargs.rets;\n  if (args.size()%2 != 0) {\n    throw args.undefined();\n  }\n  for (size_t i = 0; i < args.size(); i+=2) {\n    if (args[i+0].shape.size() != 1) {\n      throw rets.error(rets[0], \"non-vector theory\");\n    }\n\n    if (args[i+1].shape != args[i+0].shape) {\n      throw rets.error(rets[0], \"data and theory have different shape\");\n    }\n  }\n  rets[0] = DataType().points().shape(1);\n}\n\ndouble addOneInLnGamma(double in)\n{\n  return TMath::LnGamma(in + 1);\n}\n\ndouble lnFactorialApprox(double x)\n{\n  if (!(x == 0.0 || x == 1.0))\n  {\n    return x * std::log(x);\n  }\n  else\n    return 0;\n}\n\nvoid Poisson::calcPoissonApprox(FunctionArgs fargs) {\n  /***************************************************************************\n   *       Formula: log of Poisson\n   *\n   *        -2 * ln(Poisson) =\n   *            -2 * sum(data_i * log(theory_j) -  theory_j  - ln data_i! )\n   *\n   ****************************************************************************/\n  auto& args=fargs.args;\n\n  double res(0.0);\n  for (size_t i = 0; i < args.size(); i+=2) {\n    auto& theory=args[i+0].arr;\n    auto& data=args[i+1].arr;\n    res += (data*theory.log() - theory - data.unaryExpr(&lnFactorialApprox)).sum();\n  }\n  fargs.rets[0].arr(0) = -2*res;\n}\n\nvoid Poisson::calcPoisson(FunctionArgs fargs) {\n  /***************************************************************************\n   *       Formula: log of Poisson\n   *\n   *        -2 * ln(Poisson) =\n   *               -2 * sum(data_i * log(theory_j) -  theory_j  - ln data_i! )\n   *\n   ****************************************************************************/\n  auto& args=fargs.args;\n\n  double res(0.0);\n  for (size_t i = 0; i < args.size(); i+=2) {\n    auto& theory=args[i+0].arr;\n    auto& data=args[i+1].arr;\n    res += (data*theory.log() - theory - data.unaryExpr(&addOneInLnGamma) ).sum();\n  }\n  fargs.rets[0].arr(0) = -2*res;\n}\n\n", "meta": {"hexsha": "92e38257fd84c4649427a7e0c8a3688bdaeb9a16", "size": 2464, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/stats/Poisson.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/stats/Poisson.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/stats/Poisson.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.9368421053, "max_line_length": 83, "alphanum_fraction": 0.5166396104, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5424643008390646}}
{"text": "/*\n * Copyright (c) 2009-2021, Albertas Vy\u0161niauskas\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 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n *     * 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 *     * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\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,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 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\n#include <boost/test/unit_test.hpp>\n#include \"math/Matrix.h\"\n#include <iostream>\nnamespace math {\nstatic std::ostream &operator<<(std::ostream &stream, const math::Matrix3d &matrix) {\n\tfor (size_t i = 0; i < math::Matrix3d::Size * math::Matrix3d::Size; i++) {\n\t\tif (i != 0)\n\t\t\tstream << \", \";\n\t\tstream << matrix.flatData[i];\n\t}\n\treturn stream;\n}\nstatic std::ostream &operator<<(std::ostream &stream, const math::Vector3d &vector) {\n\tfor (size_t i = 0; i < math::Vector3d::Size; i++) {\n\t\tif (i != 0)\n\t\t\tstream << \", \";\n\t\tstream << vector.data[i];\n\t}\n\treturn stream;\n}\n}\nBOOST_AUTO_TEST_SUITE(matrix)\nconst static math::Matrix3d zero = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\nconst static math::Matrix3d identity = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 };\nBOOST_AUTO_TEST_CASE(determinant) {\n\tBOOST_CHECK_EQUAL(zero.determinant(), 0.0);\n\tBOOST_CHECK_EQUAL(identity.determinant(), 1.0);\n\tBOOST_CHECK_EQUAL(math::Matrix3d(1.0, 2.0, 3.0, 0.0, 1.0, 4.0, 5.0, 6.0, 0.0).determinant(), 1.0);\n}\nBOOST_AUTO_TEST_CASE(multiplication) {\n\tBOOST_CHECK_EQUAL(identity * zero, zero);\n\tBOOST_CHECK_EQUAL(zero * identity, zero);\n\tBOOST_CHECK_EQUAL(identity * identity, identity);\n}\nBOOST_AUTO_TEST_CASE(inverse) {\n\tBOOST_CHECK_EQUAL(*identity.inverse(), identity);\n\tBOOST_CHECK_EQUAL(*math::Matrix3d(1.0, 2.0, 3.0, 0.0, 1.0, 4.0, 5.0, 6.0, 0.0).inverse(), math::Matrix3d(-24.0, 18.0, 5.0, 20.0, -15.0, -4.0, -5.0, 4.0, 1.0));\n}\nBOOST_AUTO_TEST_CASE(vectorMultiplication) {\n\tmath::Vector3d unit = { 1.0, 1.0, 1.0 };\n\tmath::Matrix3d translate = { 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0 };\n\tBOOST_CHECK_EQUAL(translate * unit, math::Vector3d(2.0, 2.0, 1.0));\n\tBOOST_CHECK_EQUAL(unit * translate, math::Vector3d(1.0, 1.0, 3.0));\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7c5d845b4c3701a1eb82930293eaf136e44130d7", "size": 3310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/test/Matrix.cpp", "max_stars_repo_name": "ericonr/gpick", "max_stars_repo_head_hexsha": "ff0a3c0c797d3d06d1b8ab257cb2e9dcca389908", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 311.0, "max_stars_repo_stars_event_min_datetime": "2015-03-26T18:38:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T07:39:30.000Z", "max_issues_repo_path": "source/test/Matrix.cpp", "max_issues_repo_name": "ericonr/gpick", "max_issues_repo_head_hexsha": "ff0a3c0c797d3d06d1b8ab257cb2e9dcca389908", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 86.0, "max_issues_repo_issues_event_min_datetime": "2015-03-27T06:05:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T23:04:30.000Z", "max_forks_repo_path": "source/test/Matrix.cpp", "max_forks_repo_name": "ericonr/gpick", "max_forks_repo_head_hexsha": "ff0a3c0c797d3d06d1b8ab257cb2e9dcca389908", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 42.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T16:40:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T22:36:47.000Z", "avg_line_length": 51.71875, "max_line_length": 211, "alphanum_fraction": 0.7181268882, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893520001, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5424643008390646}}
{"text": "// Copyright (c) 2015\n// Author: Chrono Law\n#include <std.hpp>\nusing namespace std;\n\n#define BOOST_RATIO_EXTENSIONS\n#include <boost/ratio.hpp>\nusing namespace boost;\n\n//////////////////////////////////////////\n\nvoid case1()\n{\n    typedef ratio<1, 2> half;\n\n    assert(half::num == 1);\n    assert(half::den == 2);\n\n    auto v = half::value();\n    cout << v << endl;\n    assert(v * 2 == 1);\n\n    half frac;\n    assert(frac().numerator() == frac.num);\n\n    typedef ratio<2, 4> two_fourth;\n    cout << two_fourth()() << endl;\n    assert(half::value() == two_fourth::value());\n\n    typedef ratio<12> dozen;\n    assert(2* dozen()() == 24);\n}\n\n//////////////////////////////////////////\ntypedef ratio<1, 2> half;\ntypedef ratio<1, 4> quater;\n\ntypedef ratio<12, 1> dozen;\ntypedef ratio<kilo::num*10, 1> cn_wan;\n\nvoid case2()\n{\n    assert(kilo::num < kibi::num);\n    cout << kilo::num << endl;\n    cout << kibi::num << endl;\n\n    assert((quater())()*2 == half()());\n    assert((mega())() == cn_wan()()*100);\n}\n\n//////////////////////////////////////////\nboost::intmax_t operator\"\" _kb(unsigned long long n)\n{\n    return n * boost::kibi::num;\n}\n\nboost::intmax_t operator\"\" _gb(unsigned long long n)\n{\n    return n * boost::gibi::num;\n}\n\nvoid case3()\n{\n    auto x = 2_gb;\n    auto y = 10_kb;\n\n    assert(x = 2 * 100 * y);\n}\n\n//////////////////////////////////////////\ntemplate<typename R>\nusing string_out = ratio_string<R, char>;\n\nvoid case4()\n{\n    cout << string_out<kilo>::prefix() << endl;\n    cout << string_out<kilo>::symbol() << endl;\n\n    cout << string_out<nano>::prefix() << endl;\n    cout << string_out<nano>::symbol() << endl;\n\n    cout << string_out<ratio<22, 7>>::prefix() << endl;\n}\n\n//////////////////////////////////////////\n\nint main()\n{\n    case1();\n    case2();\n    case3();\n    case4();\n}\n", "meta": {"hexsha": "2ce12552587ceca11b7a7b64ad2afd10c4045925", "size": 1799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/ratio.cpp", "max_stars_repo_name": "210843013/boost_guide", "max_stars_repo_head_hexsha": "48f7936812018d695b065a6b7dadab482526b6d3", "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": "math/ratio.cpp", "max_issues_repo_name": "210843013/boost_guide", "max_issues_repo_head_hexsha": "48f7936812018d695b065a6b7dadab482526b6d3", "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": "math/ratio.cpp", "max_forks_repo_name": "210843013/boost_guide", "max_forks_repo_head_hexsha": "48f7936812018d695b065a6b7dadab482526b6d3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-29T13:08:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-29T13:08:23.000Z", "avg_line_length": 19.1382978723, "max_line_length": 55, "alphanum_fraction": 0.5125069483, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5424643008390645}}
{"text": "#include \"catch.hpp\"\n#include \"ada_star_search.h\"\n#include \"simple_point.h\"\n#include \"EuclideanDistanceFunctor.h\"\n#include <boost/graph/random.hpp>\n#include <boost/graph/circle_layout.hpp>\n#include <boost/random.hpp>\n#include <boost/graph/astar_search.hpp>\n#include <algorithm>\n#include <cmath>\n\nusing namespace boost;\nusing namespace ada_star;\ntypedef simple_point<float> pos;\ntypedef adjacency_list<vecS, vecS, bidirectionalS, pos> G;\ntypedef graph_traits<G>::vertex_descriptor V;\n\nTEST_CASE(\"[ADA] Path tests\", \"[full]\") {\n\n    // Generate graph\n    random::mt11213b generator(0);\n    G g;\n    const int N = 10000;\n    const float radius = 10.0f;\n    V prev = add_vertex({ 0.0f, radius }, g);\n    for (int i = 1; i < N; ++i) {\n        float theta = (float)i * 2 * M_PI / N;\n        pos p = { sin(theta) * radius, cos(theta) * radius };\n        V next = add_vertex(p, g);\n        add_edge(prev, next, g);\n        prev = next;\n    }\n    for (int i = 0; i < 1000; ++i) {\n        V u = random_vertex(g, generator);\n        V v = random_vertex(g, generator);\n        add_edge(u, v, g);\n    }\n    V source = random_vertex(g, generator);\n    V destination = random_vertex(g, generator);\n\n    // Initialise helpers\n    EuclideanDistanceFunctor<G, float> weight_map(g);\n    \n    // Build optimal solution\n    std::map<V, V> pred_map_map;\n    associative_property_map<std::map<V, V>> pred_map(pred_map_map);\n\n    std::vector<V> desired;\n    BENCHMARK(\"Baseline A*\") {\n        astar_search(\n            g,\n            source,\n            [&weight_map, &destination](V v){\n                return weight_map[{ v, destination }];\n            },\n            predecessor_map(pred_map).\n            weight_map(weight_map)\n        );\n        \n        V current = destination;\n        while (current != source) {\n            desired.push_back(current);\n            current = pred_map[current];\n        }\n        desired.push_back(current);\n        std::reverse(desired.begin(), desired.end());\n    }\n\n    float desiredLength = 0.0f;\n    for (int i = 0; i + 1 < desired.size(); ++i) {\n        desiredLength += get(weight_map, { desired[i], desired[i + 1] });\n    }\n\n    SECTION(\"Optimal\") {\n        map_property_map<V, float> g_map = make_g(source, destination);\n        \n        std::vector<V> solution;\n        BENCHMARK(\"Optimal path\") {\n            ada_star_search(\n                g,\n                source,\n                destination,\n                _weight_map=weight_map,\n                _g=g_map\n            );\n\n            V current = source;\n            while (current != destination) {\n                solution.push_back(current);\n                current = ada_star_next_step(\n                    g,\n                    current,\n                    weight_map,\n                    g_map\n                );\n            }\n            solution.push_back(current);\n        }\n\n        REQUIRE(solution.size() > 0);\n\n        float solutionLength = 0.0f;\n        for (int i = 0; i + 1 < solution.size(); ++i) {\n            solutionLength += get(weight_map, { solution[i], solution[i + 1] });\n        }\n\n        REQUIRE(solutionLength == desiredLength);\n    }\n\n    SECTION(\"Suboptimal (\u03b5 = 1.5)\") {\n        map_property_map<V, float> g_map = make_g(source, destination);\n\n        std::vector<V> solution;\n        BENCHMARK(\"Suboptimal path\") {\n            ada_star_search(\n                g,\n                source,\n                destination,\n                _weight_map=weight_map,\n                _g=g_map,\n                _suboptimality=1.5f\n            );\n\n            V current = source;\n            while (current != destination) {\n                solution.push_back(current);\n                current = ada_star_next_step(\n                    g,\n                    current,\n                    weight_map,\n                    g_map\n                );\n            }\n            solution.push_back(current);\n        }\n\n        REQUIRE(solution.size() > 0);\n\n        float solutionLength = 0.0f;\n        for (int i = 0; i + 1 < solution.size(); ++i) {\n            solutionLength += get(weight_map, { solution[i], solution[i + 1] });\n        }\n\n        REQUIRE(desiredLength <= solutionLength);\n        REQUIRE(solutionLength <= 1.5f * desiredLength);\n    }\n\n}", "meta": {"hexsha": "71c54cb77ce5f89b1fd1a3dd94be16f745fbcb9b", "size": 4254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_ada_star_search.cpp", "max_stars_repo_name": "jmlowenthal/survey", "max_stars_repo_head_hexsha": "030fb473f9a30d41654475e3bfa00a83348bb1f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-16T15:01:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-16T15:01:11.000Z", "max_issues_repo_path": "src/test_ada_star_search.cpp", "max_issues_repo_name": "jmlowenthal/survey", "max_issues_repo_head_hexsha": "030fb473f9a30d41654475e3bfa00a83348bb1f0", "max_issues_repo_licenses": ["MIT"], "max_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_ada_star_search.cpp", "max_forks_repo_name": "jmlowenthal/survey", "max_forks_repo_head_hexsha": "030fb473f9a30d41654475e3bfa00a83348bb1f0", "max_forks_repo_licenses": ["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.7432432432, "max_line_length": 80, "alphanum_fraction": 0.5216267043, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5424643008390645}}
{"text": "//\n//  Copyright (C) Toon Knapen 2003\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#ifndef BOOST_NUMERIC_BINDINGS_BLAS_BLAS3_OVERLOADS_HPP\n#define BOOST_NUMERIC_BINDINGS_BLAS_BLAS3_OVERLOADS_HPP\n\n#include <boost/numeric/bindings/blas/blas.h>\n#include <boost/numeric/bindings/traits/type_traits.hpp>\n\nnamespace boost { namespace numeric { namespace bindings { namespace blas { namespace detail {\n\n  using namespace boost::numeric::bindings::traits ;\n\n  inline\n  void gemm( char TRANSA, char TRANSB, const integer_t& m, const integer_t& n, const integer_t& k, const float    & alpha, const float    * a_ptr, const integer_t& lda, const float    * b_ptr, const integer_t& ldb, const float    & beta, float    * c_ptr, const integer_t& ldc ) { BLAS_SGEMM( &TRANSA, &TRANSB, &m, &n, &k,          ( &alpha ),          ( a_ptr ), &lda,          ( b_ptr ), &ldb,          ( &beta ),          ( c_ptr ), &ldc ) ; }\n  inline\n  void gemm( char TRANSA, char TRANSB, const integer_t& m, const integer_t& n, const integer_t& k, const double   & alpha, const double   * a_ptr, const integer_t& lda, const double   * b_ptr, const integer_t& ldb, const double   & beta, double   * c_ptr, const integer_t& ldc ) { BLAS_DGEMM( &TRANSA, &TRANSB, &m, &n, &k,          ( &alpha ),          ( a_ptr ), &lda,          ( b_ptr ), &ldb,          ( &beta ),          ( c_ptr ), &ldc ) ; }\n  inline\n  void gemm( char TRANSA, char TRANSB, const integer_t& m, const integer_t& n, const integer_t& k, const complex_f& alpha, const complex_f* a_ptr, const integer_t& lda, const complex_f* b_ptr, const integer_t& ldb, const complex_f& beta, complex_f* c_ptr, const integer_t& ldc ) { BLAS_CGEMM( &TRANSA, &TRANSB, &m, &n, &k, complex_ptr( &alpha ), complex_ptr( a_ptr ), &lda, complex_ptr( b_ptr ), &ldb, complex_ptr( &beta ), complex_ptr( c_ptr ), &ldc ) ; }\n  inline\n  void gemm( char TRANSA, char TRANSB, const integer_t& m, const integer_t& n, const integer_t& k, const complex_d& alpha, const complex_d* a_ptr, const integer_t& lda, const complex_d* b_ptr, const integer_t& ldb, const complex_d& beta, complex_d* c_ptr, const integer_t& ldc ) { BLAS_ZGEMM( &TRANSA, &TRANSB, &m, &n, &k, complex_ptr( &alpha ), complex_ptr( a_ptr ), &lda, complex_ptr( b_ptr ), &ldb, complex_ptr( &beta ), complex_ptr( c_ptr ), &ldc ) ; }\n\n\n  //\n  // SYRK\n  //\n  inline\n  void syrk( char uplo, char trans, const integer_t& n, const integer_t& k, const float& alpha,\n             const float* a_ptr, const integer_t lda, const float& beta, float* c_ptr,\n             const integer_t& ldc)\n  {\n     BLAS_SSYRK( &uplo, &trans, &n, &k, &alpha, a_ptr, &lda, &beta, c_ptr, &ldc);\n  }\n\n  inline\n  void syrk( char uplo, char trans, const integer_t& n, const integer_t& k, const double& alpha,\n             const double* a_ptr, const integer_t lda, const double& beta, double* c_ptr,\n             const integer_t& ldc)\n  {\n     BLAS_DSYRK( &uplo, &trans, &n, &k, &alpha, a_ptr, &lda, &beta, c_ptr, &ldc);\n  }\n\n  inline\n  void syrk( char uplo, char trans, const integer_t& n, const integer_t& k, const complex_f& alpha,\n             const complex_f* a_ptr, const integer_t lda, const complex_f& beta, complex_f* c_ptr,\n             const integer_t& ldc)\n  {\n     BLAS_CSYRK( &uplo, &trans, &n, &k, complex_ptr( &alpha ), complex_ptr( a_ptr ),\n                 &lda, complex_ptr( &beta ), complex_ptr( c_ptr ), &ldc);\n  }\n\n  inline\n  void syrk( char uplo, char trans, const integer_t& n, const integer_t& k, const complex_d& alpha,\n             const complex_d* a_ptr, const integer_t lda, const complex_d& beta, complex_d* c_ptr,\n             const integer_t& ldc)\n  {\n     BLAS_ZSYRK( &uplo, &trans, &n, &k, complex_ptr( &alpha ), complex_ptr( a_ptr ),\n                 &lda, complex_ptr( &beta ), complex_ptr( c_ptr ), &ldc);\n  }\n\n  //\n  // HERK\n  //\n  inline\n  void herk( char uplo, char trans, const integer_t& n, const integer_t& k, const float& alpha,\n             const float* a_ptr, const integer_t lda, const float& beta, float* c_ptr,\n             const integer_t& ldc)\n  {\n     BLAS_SSYRK( &uplo, &trans, &n, &k, &alpha, a_ptr, &lda, &beta, c_ptr, &ldc);\n  }\n\n  inline\n  void herk( char uplo, char trans, const integer_t& n, const integer_t& k, const double& alpha,\n             const double* a_ptr, const integer_t lda, const double& beta, double* c_ptr,\n             const integer_t& ldc)\n  {\n     BLAS_DSYRK( &uplo, &trans, &n, &k, &alpha, a_ptr, &lda, &beta, c_ptr, &ldc);\n  }\n\n\n  inline\n  void herk( char uplo, char trans, const integer_t& n, const integer_t& k, const float& alpha,\n             const complex_f* a_ptr, const integer_t lda, const float& beta, complex_f* c_ptr,\n             const integer_t& ldc)\n  {\n     BLAS_CHERK( &uplo, &trans, &n, &k, &alpha, complex_ptr( a_ptr ),\n                 &lda, &beta, complex_ptr( c_ptr ), &ldc);\n  }\n\n  inline\n  void herk( char uplo, char trans, const integer_t& n, const integer_t& k, const double& alpha,\n             const complex_d* a_ptr, const integer_t lda, const double& beta, complex_d* c_ptr,\n             const integer_t& ldc)\n  {\n     BLAS_ZHERK( &uplo, &trans, &n, &k, &alpha, complex_ptr( a_ptr ),\n                 &lda, &beta, complex_ptr( c_ptr ), &ldc);\n  }\n\n  //\n  // trsm\n  //\n  inline\n  void trsm( char side, char uplo, char transa, char diag, integer_t m, integer_t n,\n             float const& alpha, float const* a_ptr, integer_t lda,\n             float* b_ptr, integer_t ldb )\n  {\n     BLAS_STRSM( &side, &uplo, &transa, &diag, &m, &n, &alpha, a_ptr, &lda, b_ptr, &ldb ) ;\n  }\n\n  inline\n  void trsm( char side, char uplo, char transa, char diag, integer_t m, integer_t n,\n             double const& alpha, double const* a_ptr, integer_t lda,\n             double* b_ptr, integer_t ldb )\n  {\n     BLAS_DTRSM( &side, &uplo, &transa, &diag, &m, &n, &alpha, a_ptr, &lda, b_ptr, &ldb ) ;\n  }\n\n  inline\n  void trsm( char side, char uplo, char transa, char diag, integer_t m, integer_t n,\n             complex_f const& alpha, complex_f const* a_ptr, integer_t lda,\n             complex_f* b_ptr, integer_t ldb )\n  {\n     BLAS_CTRSM( &side, &uplo, &transa, &diag, &m, &n, complex_ptr( &alpha ), complex_ptr( a_ptr ), &lda, complex_ptr( b_ptr ), &ldb ) ;\n  }\n\n  inline\n  void trsm( char side, char uplo, char transa, char diag, integer_t m, integer_t n,\n             complex_d const& alpha, complex_d const* a_ptr, integer_t lda,\n             complex_d* b_ptr, integer_t ldb )\n  {\n     BLAS_ZTRSM( &side, &uplo, &transa, &diag, &m, &n, complex_ptr( &alpha ), complex_ptr( a_ptr ), &lda, complex_ptr( b_ptr ), &ldb ) ;\n  }\n\n}}}}}\n\n#endif // BOOST_NUMERIC_BINDINGS_BLAS_BLAS3_OVERLOADS_HPP\n\n", "meta": {"hexsha": "eb75831f404461e1f0f1f24cb2cfd2d6f7243f8e", "size": 6732, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/blas/blas3_overloads.hpp", "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/boost/numeric/bindings/blas/blas3_overloads.hpp", "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/boost/numeric/bindings/blas/blas3_overloads.hpp", "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": 47.0769230769, "max_line_length": 456, "alphanum_fraction": 0.6339869281, "num_tokens": 2101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5424643008390645}}
{"text": "// -*- coding: utf-8 -*-\n#include <algorithm>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <doctest/doctest.h>\n#include <ellcpp/cutting_plane.hpp>\n#include <ellcpp/ell.hpp>\n// #include <ellcpp/ell1d.hpp>\n#include <ellcpp/oracles/optscaling_oracle.hpp> // import optscaling\n#include <py2cpp/nx2bgl.hpp>\n#include <utility> // for std::pair\n#include <xtensor/xarray.hpp>\n\nnamespace boost\n{\n\nenum edge_id_tag_t\n{\n    id_tag\n}; // a unique #\nBOOST_INSTALL_PROPERTY(edge, id_tag);\n\n} // namespace boost\n\nusing Arr = xt::xarray<double, xt::layout_type::row_major>;\n\nusing graph_t =\n    boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,\n        boost::no_property, boost::property<boost::edge_id_tag_t, size_t>>;\nusing Vertex = typename boost::graph_traits<graph_t>::vertex_descriptor;\nusing edge_t = typename boost::graph_traits<graph_t>::edge_iterator;\n\n/*!\n * @brief Create a test case1 object\n *\n * @return xn::grAdaptor<graph_t>\n */\nstatic xn::grAdaptor<graph_t> create_test_case1()\n{\n    using Edge = std::pair<int, int>;\n    const auto num_nodes = 5;\n    enum nodes\n    {\n        A,\n        B,\n        C,\n        D,\n        E\n    };\n    // char name[] = \"ABCDE\";\n    Edge edge_array[] = {\n        Edge(A, B), Edge(B, C), Edge(C, D), Edge(D, E), Edge(E, A)};\n    size_t indices[] = {0, 1, 2, 3, 4};\n    auto num_arcs = sizeof(edge_array) / sizeof(Edge);\n    auto g =\n        graph_t(edge_array, edge_array + num_arcs, indices, num_nodes);\n    return xn::grAdaptor<graph_t>(std::move(g));\n}\n\nTEST_CASE(\"Test Optimal Scaling (two varaibles, boost)\")\n{\n    using EdgeIndexMap =\n        typename boost::property_map<graph_t, boost::edge_id_tag_t>::type;\n    using IterMap =\n        boost::iterator_property_map<double*, EdgeIndexMap, double, double&>;\n\n    auto G = create_test_case1();\n\n    double elem[] = {1.2, 2.3, 3.4, -4.5, 5.6};\n    const auto num_of_nodes = sizeof(elem) / sizeof(double);\n\n    double cost[num_of_nodes];\n    for (auto i = 0; i != num_of_nodes; ++i)\n    {\n        cost[i] = std::log(std::abs(elem[i]));\n    }\n    auto edge_id = boost::get(boost::id_tag, G);\n    auto cost_pa = IterMap {cost, edge_id};\n\n    auto get_cost = [&](const auto& e) -> double\n    { return boost::get(cost_pa, e); };\n\n    const auto [cmin, cmax] =\n        std::minmax_element(std::begin(cost), std::end(cost));\n    // auto cmin = *std::min_element(cost, cost + num_of_nodes);\n    const auto x0 = Arr {*cmax, *cmin};\n    auto t1 = *cmax - *cmin;\n    auto E = ell {1.5 * t1, x0};\n    auto dist = std::vector<double>(G.number_of_nodes(), 0.);\n\n    auto P = optscaling_oracle<decltype(G), std::vector<double>,\n        decltype(get_cost)> {G, dist, get_cost};\n    auto t = 1.e100; // std::numeric_limits<double>::max()\n    const auto [x, ell_info] = cutting_plane_dc(P, E, t);\n\n    CHECK(x[1] >= x[0]);\n    CHECK(ell_info.feasible);\n    CHECK(ell_info.num_iters <= 27);\n}\n", "meta": {"hexsha": "a0fb267c1d3a1a9333a46bb3fbc16af6f8efc83d", "size": 3007, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/test/src/test_optscaling_boost.cpp", "max_stars_repo_name": "luk036/ellcpp", "max_stars_repo_head_hexsha": "3415e7ffb70b63edb9ce4d6c2b9fee92898538bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-26T04:58:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T06:29:59.000Z", "max_issues_repo_path": "lib/test/src/test_optscaling_boost.cpp", "max_issues_repo_name": "luk036/ellcpp", "max_issues_repo_head_hexsha": "3415e7ffb70b63edb9ce4d6c2b9fee92898538bc", "max_issues_repo_licenses": ["MIT"], "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/test/src/test_optscaling_boost.cpp", "max_forks_repo_name": "luk036/ellcpp", "max_forks_repo_head_hexsha": "3415e7ffb70b63edb9ce4d6c2b9fee92898538bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-06-03T08:20:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-30T10:41:49.000Z", "avg_line_length": 29.4803921569, "max_line_length": 77, "alphanum_fraction": 0.6405054872, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5424642942999491}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\n#include <boost/range/counting_range.hpp>\n\nstruct Entity {\n\tstd::int64_t health;\n\tstd::int64_t damage;\n\tstd::int64_t armor;\n};\n\nstruct Item {\n\tstd::int64_t price;\n\tstd::int64_t dmg_bonus;\n\tstd::int64_t ac_bonus;\n};\n\ntemplate<typename T>\nauto factorial(T n) -> T {\n    if(n > 1) {\n        return n * factorial(n - 1);\n    }\n    return 1;\n}\n\ntemplate<typename N, typename K>\nauto binomial_coefficient(N n, K k) {\n\treturn factorial(n) / (factorial(k) * factorial(n-k));\n}\n\n// NOTE: this function is adapted from https://stackoverflow.com/a/9430993/699211\n// It works by creating a \"selection array\", where we place k selectors, then\n// we create all permutations of these selectors, and add the corresponding set\n// member if it is selected in in the current permutation of the selectors.\nauto get_rings() {\n\n\tauto rings = std::vector<Item>{{}, {}, {25,1,0}, {50,2,0}, {100,3,0}, {20,0,1}, {40,0,2}, {80,0,3}};\n\n\t// a combination of n rings with k elements in each combination\n\tconst auto n = rings.size();\n\tconst auto k = 2;\n\n\t// the binomial coefficient gives us the number of all combinations of size k from n elements\n\tauto ring_combos = std::vector<std::vector<Item>>(binomial_coefficient(n, k));\n\n\tenum class Bool { False, True };\n\n\tauto selector = std::vector<Bool>(n);\n\n\tstd::fill(selector.begin(), selector.begin() + k, Bool::True);\n\n\tdo {\n\n\t\tfor(const auto i : boost::counting_range({}, n)) {\n\n\t\t\tif(selector[i] == Bool::True) {\n\n\t\t\t\t// the vectors containing the ring combinations must not exceed k elements\n\t\t\t\tconst auto fillable = std::find_if(ring_combos.begin(), ring_combos.end(), [k] (const auto combo) {\n\t\t\t\t\treturn combo.size() < k;\n\t\t\t\t});\n\n\t\t\t\t// ring_combos is sized to contain all the combinations of length k,\n\t\t\t\t// so we are guaranteed that fillable never points to end()\n\t\t\t\tfillable->push_back(rings[i]);\n\t\t\t}\n\t\t}\n\n\t} while(std::prev_permutation(selector.begin(), selector.end()));\n\n\treturn ring_combos;\n}\n\nint main() {\n\n\tconst auto weapons = std::vector<Item>{{8,4,0}, {10,5,0}, {25,6,0}, {40,7,0}, {74,8,0}};\n\tconst auto armors = std::vector<Item>{{}, {13,0,1}, {31,0,2}, {53,0,3}, {75,0,4}, {102,0,5}};\n\tconst auto rings = get_rings();\n\n\tauto min_gold = std::numeric_limits<decltype(Item::price)>::max();\n\n\tconst auto boss = Entity{103, 9, 2};\n\tEntity hero; // no need to initialize, the innermost loop provides the values\n\n\t// cartesian product of all the equipment vectors\n\tfor(const auto& weapon : weapons) {\n\n\t\tfor(const auto& armor : armors) {\n\n\t\t\tfor(const auto& ring : rings) {\n\n\t\t\t\tconst auto& ring1 = ring.front();\n\t\t\t\tconst auto& ring2 = ring.back();\n\n\t\t\t\thero = {\n\t\t\t\t\t100,\n\t\t\t\t\t(weapon.dmg_bonus + ring1.dmg_bonus + ring2.dmg_bonus),\n\t\t\t\t\t(armor.ac_bonus + ring1.ac_bonus + ring2.ac_bonus)\n\t\t\t\t};\n\n\t\t\t\tconst auto hero_dmg = (hero.damage - boss.armor);\n\t\t\t\tconst auto boss_dmg = (boss.damage - hero.armor);\n\n\t\t\t\tconst auto hero_real_dmg = (hero_dmg > 0) ? hero_dmg : 1;\n\t\t\t\tconst auto boss_real_dmg = (boss_dmg > 0) ? boss_dmg : 1;\n\n\t\t\t\tconst auto hero_health = hero.health;\n\t\t\t\tconst auto boss_health = boss.health;\n\n\t\t\t\t// fight sequence is always the same, so we can just calculate how many rounds they both last\n\t\t\t\tconst auto hero_rounds = ((hero_health / boss_real_dmg) + ((hero_health % boss_real_dmg) > 0));\n\t\t\t\tconst auto boss_rounds = ((boss_health / hero_real_dmg) + ((boss_health % hero_real_dmg) > 0));\n\n\t\t\t\t// since the hero always attacks first in any given round,\n\t\t\t\t// equal rounds means the hero always wins\n\t\t\t\tif(hero_rounds >= boss_rounds) {\n\t\t\t\t\tmin_gold = std::min(min_gold, (weapon.price + armor.price + ring1.price + ring2.price));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::cout << min_gold << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "3a0fcc7b8e77477934d2043cf18853b60be6d47b", "size": 3728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 21 Part 1/main.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 21 Part 1/main.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 21 Part 1/main.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.125, "max_line_length": 103, "alphanum_fraction": 0.6630901288, "num_tokens": 1054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5424208988691666}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include \"scp_planner.hpp\"\n#include <mission.hpp>\n#include <param.hpp>\n\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include \"matplotlibcpp.h\"\nnamespace plt = matplotlibcpp;\n\nnamespace SwarmPlanning {\n    class SCPPlotter {\n    public:\n        SCPPlotter(std::shared_ptr<SCPPlanner> _SCPPlanner_obj,\n                   Mission _mission,\n                   Param _param)\n                : SCPPlanner_obj(_SCPPlanner_obj),\n                  mission(_mission),\n                  param(_param) {\n            N = round(SCPPlanner_obj->msgs_traj_info.data[0]);\n            K = round(SCPPlanner_obj->msgs_traj_info.data[1]);\n            h = SCPPlanner_obj->msgs_traj_info.data[2];\n            T = 34;\n            outdim = 3;\n\n            p_curr.resize(N);\n\n            build_mapping_mtx();\n            std::vector<double> data = SCPPlanner_obj->msgs_traj_input.data;\n            u = Eigen::Map<Eigen::MatrixXd>(data.data(), outdim * N * K, 1);\n            p = P * u + p_start;\n            v = V * u;\n            a = A * u;\n        }\n\n        void plot() {\n            update_traj(0.1);\n            plot_distance_between_quad();\n            ROS_INFO_STREAM(\"TrajPlotter: total length=\" << trajectory_length_sum());\n        }\n\n    private:\n        std::shared_ptr<SCPPlanner> SCPPlanner_obj;\n        SwarmPlanning::Mission mission;\n        SwarmPlanning::Param param;\n\n        int N, K, outdim;\n        double h, T;\n        Eigen::MatrixXd P, V, A, J, p_start, p_goal, u, p, v, a;\n        std::vector<double> t;\n        std::vector<Eigen::MatrixXd> p_curr;\n\n        void build_mapping_mtx() {\n            P = Eigen::MatrixXd::Zero(outdim * N * K, outdim * N * K); // position matrix p = Pu + p_start\n            V = Eigen::MatrixXd::Zero(outdim * N * K, outdim * N * K); // velocity matrix v = Vu, assume v_start = 0\n            A = Eigen::MatrixXd::Identity(outdim * N * K, outdim * N * K); // accelation matrix a = Au\n            J = Eigen::MatrixXd::Zero(outdim * N * K, outdim * N * K); // accelation matrix a = Au\n\n            p_start = Eigen::MatrixXd::Zero(outdim * N * K, 1);\n            p_goal = Eigen::MatrixXd::Zero(outdim * N, 1);\n\n            for (int dim = 0; dim < outdim; dim++) {\n                for (int qi = 0; qi < N; qi++) {\n                    int offset = dim * N * K + qi * K;\n                    for (int k = 0; k < K; k++) {\n                        for (int j = 0; j < k; j++) {\n                            P(offset + k, offset + j) = 0.5 * h * h * (2 * (k - j) - 1);\n                            V(offset + k, offset + j) = h;\n                        }\n                        if (k != 0) {\n                            J(offset + k, offset + k) = 1 / h;\n                            J(offset + k, offset + k - 1) = -1 / h;\n                        }\n\n                        p_start(offset + k, 0) = mission.startState[qi][dim];\n                    }\n                    p_goal(dim * N + qi, 0) = mission.goalState[qi][dim];\n                }\n            }\n        }\n\n//    void plot_quad_dynamics() {\n//        plt::figure_size(1500, 1000);\n//\n//        // Plot Quad Velocity\n//        plt::subplot(3, 2, 1);\n//        for(int qi = 0; qi < qn; qi++) {\n//            plt::named_plot(\"agent\" + std::to_string(qi) , t, quad_state[qi][3]);\n//        }\n//        plt::title(\"velocity -x axis\");\n//\n//        plt::subplot(3, 2, 3);\n//        for(int qi = 0; qi < qn; qi++) {\n//            plt::named_plot(\"agent\" + std::to_string(qi) , t, quad_state[qi][4]);\n//        }\n//        plt::title(\"velocity -y axis\");\n//\n//        plt::subplot(3, 2, 5);\n//        for(int qi = 0; qi < qn; qi++) {\n//            plt::named_plot(\"agent\" + std::to_string(qi) , t, quad_state[qi][5]);\n//        }\n//        plt::title(\"velocity -z axis\");\n//\n//        // Plot Quad Acceleration\n//        plt::subplot(3, 2, 2);\n//        for(int qi = 0; qi < qn; qi++) {\n//            plt::named_plot(\"agent\" + std::to_string(qi) , t, quad_state[qi][6]);\n//        }\n//        plt::title(\"acceleration -x axis\");\n//\n//        plt::subplot(3, 2, 4);\n//        for(int qi = 0; qi < qn; qi++) {\n//            plt::named_plot(\"agent\" + std::to_string(qi) , t, quad_state[qi][7]);\n//        }\n//        plt::title(\"acceleration -y axis\");\n//\n//        plt::subplot(3, 2, 6);\n//        for(int qi = 0; qi < qn; qi++) {\n//            plt::named_plot(\"agent\" + std::to_string(qi) , t, quad_state[qi][8]);\n//        }\n//        plt::title(\"acceleration -z axis\");\n//\n//        plt::legend();\n//        plt::show(false);\n//    }\n\n//    void update_traj(double current_time) {\n//        int k = floor(current_time / h);\n//        if (k >= K - 1) {\n//            return;\n//        }\n//\n//        for (int qi = 0; qi < N; qi++) {\n//            p_curr[qi] = Eigen::MatrixXd::Zero(outdim, 1);\n//            Eigen::MatrixXd p_0 = Eigen::MatrixXd::Zero(outdim, 1);\n//            Eigen::MatrixXd p_1 = Eigen::MatrixXd::Zero(outdim, 1);\n//            for (int dim = 0; dim < outdim; dim++) {\n//                p_0(dim, 0) = p(dim * N * K + qi * K + k, 0);\n//                p_1(dim, 0) = p(dim * N * K + qi * K + k + 1, 0);\n//            }\n//            p_curr[qi] = p_0 + (current_time - k * h) / h * (p_1 - p_0);\n//        }\n//    }\n\n        void update_traj(double dt) {\n            t.resize(floor(T / dt));\n            for (int i = 0; i < t.size(); i++) {\n                t[i] = i * dt;\n            }\n\n            int k;\n            Eigen::MatrixXd p_0, p_1;\n            for (int qi = 0; qi < N; qi++) {\n                p_curr[qi] = Eigen::MatrixXd::Zero(outdim, t.size());\n                for (int i = 0; i < t.size(); i++) {\n                    p_0 = Eigen::MatrixXd::Zero(outdim, 1);\n                    p_1 = Eigen::MatrixXd::Zero(outdim, 1);\n                    k = floor(t[i] / h);\n\n                    for (int dim = 0; dim < outdim; dim++) {\n                        p_0(dim, 0) = p(dim * N * K + qi * K + k, 0);\n                        p_1(dim, 0) = p(dim * N * K + qi * K + k + 1, 0);\n                    }\n                    p_curr[qi].block(0, i, outdim, 1) = p_0 + (t[i] - k * h) / h * (p_1 - p_0);\n                }\n            }\n        }\n\n\n        double trajectory_length_sum() {\n            double length_sum = 0;\n            for (int i = 0; i < t.size() - 1; i++) {\n                for (int qi = 0; qi < N; qi++) {\n                    length_sum += sqrt(pow(p_curr[qi](0, i + 1) - p_curr[qi](0, i), 2) +\n                                       pow(p_curr[qi](1, i + 1) - p_curr[qi](1, i), 2) +\n                                       pow(p_curr[qi](2, i + 1) - p_curr[qi](2, i), 2));\n                }\n            }\n            return length_sum;\n        }\n\n        void plot_distance_between_quad() {\n            plt::figure(1);\n            plt::figure_size(1500, 1000);\n            std::vector<double> max_dist, min_dist;\n            double max_dist_, min_dist_, dist, global_min_dist;\n\n            max_dist.resize(t.size());\n            min_dist.resize(t.size());\n\n            for (int i = 0; i < t.size(); i++) {\n                max_dist[i] = mission.quad_size[0] + mission.quad_size[0];\n            }\n            plt::plot(t, max_dist);\n\n            global_min_dist = SP_INFINITY;\n            for (int i = 0; i < t.size(); i++) {\n                max_dist_ = 0;\n                min_dist_ = SP_INFINITY;\n                for (int qi = 0; qi < N; qi++) {\n                    for (int qj = qi + 1; qj < N; qj++) {\n                        dist = sqrt(pow(p_curr[qi](0, i) - p_curr[qj](0, i), 2) +\n                                    pow(p_curr[qi](1, i) - p_curr[qj](1, i), 2) +\n                                    pow(p_curr[qi](2, i) - p_curr[qj](2, i), 2));\n                        if (dist > max_dist_) {\n                            max_dist_ = dist;\n                        }\n                        if (dist < min_dist_) {\n                            min_dist_ = dist;\n                        }\n                        if (dist < global_min_dist) {\n                            global_min_dist = dist;\n                        }\n                    }\n                }\n                max_dist[i] = max_dist_;\n                min_dist[i] = min_dist_;\n            }\n            plt::plot(t, max_dist);\n            plt::plot(t, min_dist);\n\n            ROS_INFO_STREAM(\"global min_dist: \" << global_min_dist);\n\n            plt::title(\"Ellipsoidal Distance between Quadrotor\");\n\n            plt::show(false);\n        }\n    };\n}", "meta": {"hexsha": "f99849d32b91be44b87acac094250ab8717e92bb", "size": 8475, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "swarm_planner/include/scp_plotter.hpp", "max_stars_repo_name": "snu-larr/swarm_simulator", "max_stars_repo_head_hexsha": "dc3f272158132cda4e1c319c7bd1a965d7bf9c40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T03:50:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T03:50:54.000Z", "max_issues_repo_path": "swarm_planner/include/scp_plotter.hpp", "max_issues_repo_name": "snu-larr/swarm_simulator", "max_issues_repo_head_hexsha": "dc3f272158132cda4e1c319c7bd1a965d7bf9c40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swarm_planner/include/scp_plotter.hpp", "max_forks_repo_name": "snu-larr/swarm_simulator", "max_forks_repo_head_hexsha": "dc3f272158132cda4e1c319c7bd1a965d7bf9c40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T10:58:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T08:19:08.000Z", "avg_line_length": 36.3733905579, "max_line_length": 116, "alphanum_fraction": 0.4237168142, "num_tokens": 2349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5424208970457834}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n#include <random>\n#include <crtdbg.h>\n\n#if _DEBUG\n#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)\n#endif\n\n#include \"hCriterion.h\"\n#include \"hLayer.h\"\n#include \"hOptimizer.h\"\n\nusing namespace std;\n\nint main() {\n\tLinear L1(2, 4), L2(4, 1);\n\tReLU R1;\n\tSigmoid Sig1;\n\tSerial Net({ &L1, &R1, &L2, &Sig1 });\n\tCELoss criterion(CELoss::CELossType::sigmoid);\n\tSGD optim(1e-2, 1e-4);\n\n\tEigen::MatrixXd X(4, 2);\n\tEigen::MatrixXd Y(4, 1);\n\tX << 0, 0,\n\t\t0, 1,\n\t\t1, 0,\n\t\t1, 1;\n\n\tY << 0, 1, 1, 0;\n\n\tfor (int i = 0; i < 10000; i++) {\n\t\tauto Pred = Net.forward(X);\n\n\t\tauto cost = criterion.forward(Pred, Y);\n\n\t\tif ((i + 1) % 10 == 0) cout << \"epoch \" << i + 1 << \" : \" << cost << \"\\n\";\n\n\t\tauto Diff = criterion.backward();\n\t\tNet.backward(Diff);\n\n\t\toptim.step(&Net);\n\t}\n\n\tcout << Net.forward(X) << \"\\n\";\n\n\tcout << Net << \"\\n\";\n\n\treturn 0;\n}\n", "meta": {"hexsha": "61c99060032758964311c8af4a29bde4e16e3081", "size": 887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Machine Learning Project/main.cpp", "max_stars_repo_name": "revolt3245/Machine-Learning-Project", "max_stars_repo_head_hexsha": "52c0eda2abdd4f0406ca3689a3f4f8e621bccd73", "max_stars_repo_licenses": ["MIT"], "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 Project/main.cpp", "max_issues_repo_name": "revolt3245/Machine-Learning-Project", "max_issues_repo_head_hexsha": "52c0eda2abdd4f0406ca3689a3f4f8e621bccd73", "max_issues_repo_licenses": ["MIT"], "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 Project/main.cpp", "max_forks_repo_name": "revolt3245/Machine-Learning-Project", "max_forks_repo_head_hexsha": "52c0eda2abdd4f0406ca3689a3f4f8e621bccd73", "max_forks_repo_licenses": ["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.7358490566, "max_line_length": 76, "alphanum_fraction": 0.5828635851, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.542420891575634}}
{"text": "#define BOOST_TEST_MODULE \"test_bond_length_interaction\"\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 <mjolnir/core/BoundaryCondition.hpp>\n#include <mjolnir/core/SimulatorTraits.hpp>\n#include <mjolnir/forcefield/local/BondLengthInteraction.hpp>\n#include <mjolnir/forcefield/local/HarmonicPotential.hpp>\n#include <mjolnir/util/make_unique.hpp>\n\n#include <random>\n\nBOOST_AUTO_TEST_CASE(BondLength_calc_force)\n{\n    using traits_type      = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;\n    using real_type        = traits_type::real_type;\n    using coord_type       = traits_type::coordinate_type;\n    using boundary_type    = traits_type::boundary_type;\n    using system_type      = mjolnir::System<traits_type>;\n    using potential_type    = mjolnir::HarmonicPotential<real_type>;\n    using interaction_type = mjolnir::BondLengthInteraction<traits_type, potential_type>;\n\n    constexpr real_type tol = 1e-8;\n\n    auto normalize = [](const coord_type& v){return v / mjolnir::math::length(v);};\n\n    const real_type k(100.);\n    const real_type native(2.0);\n\n    potential_type    potential(k, native);\n    interaction_type interaction(\"none\", {{ {{0,1}}, potential}});\n\n    system_type sys(2, boundary_type{});\n\n    sys.at(0).mass = 1.0;\n    sys.at(1).mass = 1.0;\n    sys.at(0).rmass = 1.0;\n    sys.at(1).rmass = 1.0;\n\n    sys.at(0).position = coord_type(0,0,0);\n    sys.at(1).position = coord_type(0,0,0);\n    sys.at(0).velocity = coord_type(0,0,0);\n    sys.at(1).velocity = coord_type(0,0,0);\n    sys.at(0).force    = coord_type(0,0,0);\n    sys.at(1).force    = coord_type(0,0,0);\n\n    sys.at(0).name  = \"X\";\n    sys.at(1).name  = \"X\";\n    sys.at(0).group = \"NONE\";\n    sys.at(1).group = \"NONE\";\n\n    const real_type dr = 1e-3;\n    real_type dist = 1e0;\n    for(int i = 0; i < 2000; ++i)\n    {\n        sys[0].position = coord_type(0,0,0);\n        sys[1].position = coord_type(0,0,0);\n        sys[0].force    = coord_type(0,0,0);\n        sys[1].force    = coord_type(0,0,0);\n        sys[1].position[0] = dist;\n\n        const real_type deriv = potential.derivative(dist);\n        const real_type coef  = std::abs(deriv);\n\n        interaction.calc_force(sys);\n\n        const real_type force_strength1 = mjolnir::math::length(sys[0].force);\n        const real_type force_strength2 = mjolnir::math::length(sys[1].force);\n\n\n        // direction\n        if(i == 1000) // most stable point\n        {\n            BOOST_TEST(force_strength1 == 0.0, boost::test_tools::tolerance(tol));\n            BOOST_TEST(force_strength2 == 0.0, boost::test_tools::tolerance(tol));\n        }\n        else if(i < 1000) // repulsive\n        {\n            BOOST_TEST(coef == force_strength1, boost::test_tools::tolerance(tol));\n            BOOST_TEST(coef == force_strength2, boost::test_tools::tolerance(tol));\n\n            const real_type dir1 = mjolnir::math::dot_product(\n                normalize(sys[0].force), normalize(sys[0].position - sys[1].position));\n            const real_type dir2 = mjolnir::math::dot_product(\n                normalize(sys[1].force), normalize(sys[1].position - sys[0].position));\n\n            BOOST_TEST(dir1 == 1.0, boost::test_tools::tolerance(tol));\n            BOOST_TEST(dir2 == 1.0, boost::test_tools::tolerance(tol));\n        }\n        else if(i > 1000) // attractive\n        {\n            BOOST_TEST(coef == force_strength1, boost::test_tools::tolerance(tol));\n            BOOST_TEST(coef == force_strength2, boost::test_tools::tolerance(tol));\n\n            const real_type dir1 = mjolnir::math::dot_product(\n                normalize(sys[0].force), normalize(sys[1].position - sys[0].position));\n            const real_type dir2 = mjolnir::math::dot_product(\n                normalize(sys[1].force), normalize(sys[0].position - sys[1].position));\n\n            BOOST_TEST(dir1 == 1e0, boost::test_tools::tolerance(tol));\n            BOOST_TEST(dir2 == 1e0, boost::test_tools::tolerance(tol));\n        }\n        BOOST_TEST(mjolnir::math::length(sys[0].force + sys[1].force) == 0.0,\n                   boost::test_tools::tolerance(tol));\n\n        dist += dr;\n    }\n}\n\nBOOST_AUTO_TEST_CASE(BondLength_numerical_difference)\n{\n    using traits_type      = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;\n    using real_type        = traits_type::real_type;\n    using coord_type       = traits_type::coordinate_type;\n    using boundary_type    = traits_type::boundary_type;\n    using system_type      = mjolnir::System<traits_type>;\n    using potential_type    = mjolnir::HarmonicPotential<real_type>;\n    using interaction_type = mjolnir::BondLengthInteraction<traits_type, potential_type>;\n\n    const real_type k(100.0);\n    const real_type native(std::sqrt(3.0));\n\n    potential_type   potential(k, native);\n    interaction_type interaction(\"none\", {{ {{0,1}}, potential}});\n\n    std::mt19937 mt(123456789);\n    std::uniform_real_distribution<real_type> uni(-1.0, 1.0);\n\n    for(std::size_t i = 0; i < 1000; ++i)\n    {\n        system_type sys(2, boundary_type{});\n\n        sys.at(0).mass  = 1.0;\n        sys.at(1).mass  = 1.0;\n        sys.at(0).rmass = 1.0;\n        sys.at(1).rmass = 1.0;\n\n        sys.at(0).position = coord_type( 0.0 + 0.01 * uni(mt), 0.0 + 0.01 * uni(mt), 0.0 + 0.01 * uni(mt));\n        sys.at(1).position = coord_type( 1.0 + 0.01 * uni(mt), 1.0 + 0.01 * uni(mt), 1.0 + 0.01 * uni(mt));\n        sys.at(0).velocity = coord_type( 0.0, 0.0, 0.0);\n        sys.at(1).velocity = coord_type( 0.0, 0.0, 0.0);\n        sys.at(0).force    = coord_type( 0.0, 0.0, 0.0);\n        sys.at(1).force    = coord_type( 0.0, 0.0, 0.0);\n\n        sys.at(0).name  = \"X\";\n        sys.at(1).name  = \"X\";\n        sys.at(0).group = \"TEST\";\n        sys.at(1).group = \"TEST\";\n\n        const auto init = sys;\n\n        constexpr real_type tol = 1e-4;\n        constexpr real_type dr  = 1e-5;\n        for(std::size_t idx=0; idx<2; ++idx)\n        {\n            {\n                // ----------------------------------------------------------------\n                // reset positions\n                sys = init;\n\n                // calc U(x-dx)\n                const auto E0 = interaction.calc_energy(sys);\n\n                mjolnir::math::X(sys.position(idx)) += dr;\n\n                // calc F(x)\n                interaction.calc_force(sys);\n\n                mjolnir::math::X(sys.position(idx)) += dr;\n\n                // calc U(x+dx)\n                const auto E1 = interaction.calc_energy(sys);\n\n                // central difference\n                const auto dE = (E1 - E0) * 0.5;\n\n                BOOST_TEST(-dE == dr * mjolnir::math::X(sys.force(idx)),\n                           boost::test_tools::tolerance(tol));\n            }\n            {\n                // ----------------------------------------------------------------\n                // reset positions\n                sys = init;\n\n                // calc U(x-dx)\n                const auto E0 = interaction.calc_energy(sys);\n\n                mjolnir::math::Y(sys.position(idx)) += dr;\n\n                // calc F(x)\n                interaction.calc_force(sys);\n\n                mjolnir::math::Y(sys.position(idx)) += dr;\n\n                // calc U(x+dx)\n                const auto E1 = interaction.calc_energy(sys);\n\n                // central difference\n                const auto dE = (E1 - E0) * 0.5;\n\n                BOOST_TEST(-dE == dr * mjolnir::math::Y(sys.force(idx)),\n                           boost::test_tools::tolerance(tol));\n            }\n            {\n                // ----------------------------------------------------------------\n                // reset positions\n                sys = init;\n\n                // calc U(x-dx)\n                const auto E0 = interaction.calc_energy(sys);\n\n                mjolnir::math::Z(sys.position(idx)) += dr;\n\n                // calc F(x)\n                interaction.calc_force(sys);\n\n                mjolnir::math::Z(sys.position(idx)) += dr;\n\n                // calc U(x+dx)\n                const auto E1 = interaction.calc_energy(sys);\n\n                // central difference\n                const auto dE = (E1 - E0) * 0.5;\n\n                BOOST_TEST(-dE == dr * mjolnir::math::Z(sys.force(idx)),\n                           boost::test_tools::tolerance(tol));\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(BondLength_calc_force_and_energy)\n{\n    using traits_type      = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;\n    using real_type        = traits_type::real_type;\n    using coord_type       = traits_type::coordinate_type;\n    using boundary_type    = traits_type::boundary_type;\n    using system_type      = mjolnir::System<traits_type>;\n    using potential_type    = mjolnir::HarmonicPotential<real_type>;\n    using interaction_type = mjolnir::BondLengthInteraction<traits_type, potential_type>;\n\n    const real_type k(100.0);\n    const real_type native(std::sqrt(3.0));\n\n    potential_type   potential(k, native);\n    interaction_type interaction(\"none\", {{ {{0,1}}, potential}});\n\n    std::mt19937 mt(123456789);\n    std::uniform_real_distribution<real_type> uni(-1.0, 1.0);\n\n    for(std::size_t i = 0; i < 1000; ++i)\n    {\n        system_type sys(2, boundary_type{});\n\n        sys.at(0).mass  = 1.0;\n        sys.at(1).mass  = 1.0;\n        sys.at(0).rmass = 1.0;\n        sys.at(1).rmass = 1.0;\n\n        sys.at(0).position = coord_type( 0.0 + 0.01 * uni(mt), 0.0 + 0.01 * uni(mt), 0.0 + 0.01 * uni(mt));\n        sys.at(1).position = coord_type( 1.0 + 0.01 * uni(mt), 1.0 + 0.01 * uni(mt), 1.0 + 0.01 * uni(mt));\n        sys.at(0).velocity = coord_type( 0.0, 0.0, 0.0);\n        sys.at(1).velocity = coord_type( 0.0, 0.0, 0.0);\n        sys.at(0).force    = coord_type( 0.0, 0.0, 0.0);\n        sys.at(1).force    = coord_type( 0.0, 0.0, 0.0);\n\n        sys.at(0).name  = \"X\";\n        sys.at(1).name  = \"X\";\n        sys.at(0).group = \"TEST\";\n        sys.at(1).group = \"TEST\";\n\n        constexpr real_type tol = 1e-4;\n        auto ref_sys = sys;\n\n        const auto energy = interaction.calc_force_and_energy(sys);\n        const auto ref_energy = interaction.calc_energy(ref_sys);\n        interaction.calc_force(ref_sys);\n        BOOST_TEST(ref_energy == energy, boost::test_tools::tolerance(tol));\n\n        for(std::size_t idx=0; idx<sys.size(); ++idx)\n        {\n            BOOST_TEST(mjolnir::math::X(sys.force(idx)) == mjolnir::math::X(ref_sys.force(idx)), boost::test_tools::tolerance(tol));\n            BOOST_TEST(mjolnir::math::Y(sys.force(idx)) == mjolnir::math::Y(ref_sys.force(idx)), boost::test_tools::tolerance(tol));\n            BOOST_TEST(mjolnir::math::Z(sys.force(idx)) == mjolnir::math::Z(ref_sys.force(idx)), boost::test_tools::tolerance(tol));\n        }\n    }\n}\n", "meta": {"hexsha": "dbf6b1cdf3af6ed27f6fcadf2caa02d9e78e0b1f", "size": 10753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_bond_length_interaction.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "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/core/test_bond_length_interaction.cpp", "max_issues_repo_name": "yutakasi634/Mjolnir", "max_issues_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T11:41:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T10:01:38.000Z", "max_forks_repo_path": "test/core/test_bond_length_interaction.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["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.8253424658, "max_line_length": 132, "alphanum_fraction": 0.559378778, "num_tokens": 3025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5423252204373274}}
{"text": "/**\n * math lib test\n * @author Tobias Weber <tweber@ill.fr>\n * @date 20-aug-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 Stat1\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\n\tstd::vector<t_vec> vecs = {{\n\t\ttl2::create<t_vec>({-1, 60}),\n\t\ttl2::create<t_vec>({20, 5}),\n\t\ttl2::create<t_vec>({-3, 40}),\n\t\ttl2::create<t_vec>({40, 3}),\n\t\ttl2::create<t_vec>({-5, 20}),\n\t\ttl2::create<t_vec>({60, 1}),\n\t}};\n\n\tauto [cov, cor] = tl2::covariance<t_mat, t_vec>(vecs);\n\tstd::cout << \"cov = \" << cov << std::endl;\n\tstd::cout << \"cor = \" << cor << std::endl;\n\n\t//BOOST_TEST(tl2::equals(vec, vec2, 1e-5));\n}\n", "meta": {"hexsha": "c25c9577f90cc6a9b84d51fb644cbaff6c56c976", "size": 2053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/stat1.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/stat1.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/stat1.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.1129032258, "max_line_length": 79, "alphanum_fraction": 0.6215294691, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5423252185180535}}
{"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/concepts/real_type_concept.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/multiprecision/number.hpp>\n\nnamespace local\n{\n  using big_float_type = boost::multiprecision::number<boost::math::ef::e_float,\n                                                       boost::multiprecision::et_off>;\n}\n\ntemplate <class T>\nvoid test_extra(T)\n{\n   T t = 1;\n   t   = abs(t);\n   t   = abs(t * t);\n\n   t = fabs(t);\n   t = fabs(t * t);\n\n   t = sqrt(t);\n   t = sqrt(t * t);\n\n   t = floor(t);\n   t = floor(t * t);\n\n   t = ceil(t);\n   t = ceil(t * t);\n\n   t = trunc(t);\n   t = trunc(t * t);\n\n   t = round(t);\n   t = round(t * t);\n\n   t = exp(t);\n   t = exp(t * t);\n\n   t = log(t);\n   t = log(t * t);\n\n   t = log10(t);\n   t = log10(t * t);\n\n   t = cos(t);\n   t = cos(t * t);\n\n   t = sin(t);\n   t = sin(t * t);\n\n   t = tan(t);\n   t = tan(t * t);\n\n   t = asin(t);\n   t = asin(t * t);\n\n   t = atan(t);\n   t = atan(t * t);\n\n   t = acos(t);\n   t = acos(t * t);\n\n   t = cosh(t);\n   t = cosh(t * t);\n\n   t = sinh(t);\n   t = sinh(t * t);\n\n   t = tanh(t);\n   t = tanh(t * t);\n\n   double dval = 2;\n   t           = pow(t, t);\n   t           = pow(t, t * t);\n   t           = pow(t, dval);\n   t           = pow(t * t, t);\n   t           = pow(t * t, t * t);\n   t           = pow(t * t, dval);\n   t           = pow(dval, t);\n   t           = pow(dval, t * t);\n\n   t = atan2(t, t);\n   t = atan2(t, t * t);\n   t = atan2(t, dval);\n   t = atan2(t * t, t);\n   t = atan2(t * t, t * t);\n   t = atan2(t * t, dval);\n   t = atan2(dval, t);\n   t = atan2(dval, t * t);\n\n   t = fmod(t, t);\n   t = fmod(t, t * t);\n   t = fmod(t, dval);\n   t = fmod(t * t, t);\n   t = fmod(t * t, t * t);\n   t = fmod(t * t, dval);\n   t = fmod(dval, t);\n   t = fmod(dval, t * t);\n\n   typedef typename T::backend_type             backend_type;\n   typedef typename backend_type::exponent_type exp_type;\n   exp_type                                     e = 0;\n   int                                          i = 0;\n\n   t = ldexp(t, i);\n   t = ldexp(t * t, i);\n   t = ldexp(t, e);\n   t = ldexp(t * t, e);\n\n   t = frexp(t, &i);\n   t = frexp(t * t, &i);\n   t = frexp(t, &e);\n   t = frexp(t * t, &e);\n\n   t = scalbn(t, i);\n   t = scalbn(t * t, i);\n   t = scalbn(t, e);\n   t = scalbn(t * t, e);\n\n   t = logb(t);\n   t = logb(t * t);\n   e = ilogb(t);\n   e = ilogb(t * t);\n}\n\nvoid foo()\n{\n  test_extra(local::big_float_type());\n}\n\nbool test_boost_real_concept()\n{\n  foo();\n\n  BOOST_CONCEPT_ASSERT((boost::math::concepts::RealTypeConcept<local::big_float_type>));\n\n  return true;\n}\n", "meta": {"hexsha": "4dcad82798cc15d7ca8c4375dfe48afd3e831701", "size": 2854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/e_float/test_boost/test_boost_real_concept.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_real_concept.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_real_concept.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": 19.5479452055, "max_line_length": 88, "alphanum_fraction": 0.467764541, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5423252178808262}}
{"text": "//\n//  Copyright Toon Knapen, Karl Meerbergen\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 \"../../blas/test/random.hpp\"\n\n#include <boost/numeric/bindings/lapack/gees.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <iostream>\n#include <limits>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\n\n// Randomize a matrix\ntemplate <typename M>\nvoid randomize(M& m) {\n   typedef typename M::size_type  size_type ;\n   typedef typename M::value_type value_type ;\n\n   size_type size1 = m.size1() ;\n   size_type size2 = m.size2() ;\n\n   for (size_type i=0; i<size2; ++i) {\n      for (size_type j=0; j<size1; ++j) {\n         m(j,i) = random_value< value_type >() ;\n      }\n   }\n} // randomize()\n\n\n\n\ntemplate <typename T, typename W>\nint do_memory_type(int n, W workspace) {\n   typedef typename boost::numeric::bindings::traits::type_traits<T>::real_type real_type ;\n   typedef std::complex< real_type >                                            complex_type ;\n\n   typedef ublas::matrix<T, ublas::column_major> matrix_type ;\n   typedef ublas::vector<complex_type>           vector_type ;\n   double safety_factor (1.5);\n\n   // Set matrix\n   matrix_type a( n, n );\n   matrix_type z( n, n );\n   vector_type e1( n );\n   vector_type e2( n );\n\n   randomize( a );\n   matrix_type a2( a );\n\n   // Compute Schur decomposition.\n   lapack::gees( a, e1, z, workspace ) ;\n\n   // Check Schur factorization\n   if (norm_frobenius( prod( a2, z ) - prod( z, a ) )\n           >= safety_factor*10.0* norm_frobenius( a2 ) * std::numeric_limits< real_type >::epsilon() ) return 255 ;\n\n   lapack::gees( a2, e2, workspace ) ;\n   if (norm_2( e1 - e2 ) > safety_factor*norm_2( e1 ) * std::numeric_limits< real_type >::epsilon()) return 255 ;\n\n   if (norm_frobenius( a2 - a )\n           >= safety_factor*10.0* norm_frobenius( a2 ) * std::numeric_limits< real_type >::epsilon() ) return 255 ;\n\n\n   return 0 ;\n} // do_value_type()\n\n\ntemplate <typename T>\nstruct Workspace {\n   typedef ublas::vector<T>                         array_type ;\n   typedef lapack::detail::workspace1< array_type > type ;\n\n   Workspace(size_t n)\n   : work_( 3*n )\n   {}\n\n   type operator() () {\n      return lapack::workspace(work_) ;\n   }\n\n   array_type work_ ;\n};\n\n\ntemplate <typename T>\nstruct Workspace< std::complex<T> > {\n   typedef ublas::vector<T>                                                 real_array_type ;\n   typedef ublas::vector< std::complex<T> >                                 complex_array_type ;\n   typedef lapack::detail::workspace2< complex_array_type,real_array_type > type ;\n\n   Workspace(size_t n)\n   : work_( 2*n )\n   , rwork_( n )\n   {}\n\n   type operator() () {\n      return lapack::workspace(work_, rwork_) ;\n   }\n\n   complex_array_type work_ ;\n   real_array_type    rwork_ ;\n};\n\n\ntemplate <typename T>\nint do_value_type() {\n   const int n = 8 ;\n   \n   if (do_memory_type<T,lapack::optimal_workspace>( n, lapack::optimal_workspace() ) ) return 255 ;\n   if (do_memory_type<T,lapack::minimal_workspace>( n, lapack::minimal_workspace() ) ) return 255 ;\n\n   Workspace<T> work( n );\n   do_memory_type<T,typename Workspace<T>::type >( n, work() );\n   return 0;\n} // do_value_type()\n\n\nint main() {\n   // Run tests for different value_types\n   if (do_value_type<float>()) return 255;\n   if (do_value_type<double>()) return 255;\n   if (do_value_type< std::complex<float> >()) return 255;\n   if (do_value_type< std::complex<double> >()) return 255;\n\n   std::cout << \"Regression test succeeded\\n\" ;\n   return 0;\n}\n\n", "meta": {"hexsha": "2c38be7ecd276b3274e70790537f3667384aab72", "size": 3763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gees.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_gees.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_gees.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": 26.8785714286, "max_line_length": 115, "alphanum_fraction": 0.6353972894, "num_tokens": 1028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.5423252178808261}}
{"text": "/**\n * \n * Core Libraries.\n * Sophus Interpolations & other missing bits.\n * \n * Copyright (c) Robert Lukierski 2016. All rights reserved.\n * Author: Robert Lukierski.\n * \n */\n\n\n#ifndef VISIONCORE_SOPHUS_MISSINGBITS_HPP\n#define VISIONCORE_SOPHUS_MISSINGBITS_HPP\n\n#include <VisionCore/Platform.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <sophus/so2.hpp>\n#include <sophus/so3.hpp>\n#include <sophus/se2.hpp>\n#include <sophus/se3.hpp>\n#include <sophus/rxso3.hpp>\n#include <sophus/sim3.hpp>\n\n/**\n * NOTE: Don't use <sophus/interpolate.hpp> for SE groups. It's wrong, see page 41:\n * https://www.cvl.isy.liu.se/education/graduate/geometry-for-computer-vision-2014/geometry2014/lecture7.pdf\n */\n\nnamespace Sophus\n{\n\n// SO2\ntemplate<typename T>\nEIGEN_DEVICE_FUNC static inline Sophus::SO2<T> interpolateLinear(const Sophus::SO2<T>& t0, const Sophus::SO2<T>& t1, T ratio)\n{\n    return Sophus::SO2<T>(t0 * Sophus::SO2<T>::exp(ratio * ( t0.inverse() * t1 ).log() ));\n}\n    \n// SE2\ntemplate<typename T>\nEIGEN_DEVICE_FUNC static inline Sophus::SE2<T> interpolateLinear(const Sophus::SE2<T>& t0, const Sophus::SE2<T>& t1, T ratio)\n{\n    return Sophus::SE2<T>(t0.so2() * Sophus::SO2<T>::exp(ratio * ( t0.so2().inverse() * t1.so2() ).log() ), \n                          t0.translation() + ratio * (t1.translation() - t0.translation()));\n}    \n\n// SO3\ntemplate<typename T>\nEIGEN_DEVICE_FUNC static inline Sophus::SO3<T> interpolateLinear(const Sophus::SO3<T>& t0, const Sophus::SO3<T>& t1, T ratio)\n{\n    return Sophus::SO3<T>(t0 * Sophus::SO3<T>::exp(ratio * ( t0.inverse() * t1 ).log() ));\n}\n\n// SE3\ntemplate<typename T>\nEIGEN_DEVICE_FUNC static inline Sophus::SE3<T> interpolateLinear(const Sophus::SE3<T>& t0, const Sophus::SE3<T>& t1, T ratio)\n{\n    return Sophus::SE3<T>(t0.so3() * Sophus::SO3<T>::exp(ratio * ( t0.so3().inverse() * t1.so3() ).log() ), \n                          t0.translation() + ratio * (t1.translation() - t0.translation()));\n}\n    \ntemplate<typename T>\nstruct B4SplineGenerator \n{ \n\n    EIGEN_DEVICE_FUNC static inline void get(const T& u, T& b1, T& b2, T& b3)\n    {\n        const T u2 = u*u;\n        const T u3 = u*u*u;\n        \n        b1 = (u3 - T(3.0) * u2 + T(3.0) * u + T(5.0)) / T(6.0);\n        b2 = (T(-2.0) * u3 + T(3.0) * u2 + T(3.0) * u + T(1.0)) / T(6.0);\n        b3 = u3 / T(6.0);\n    }\n\n#if 0\n    EIGEN_DEVICE_FUNC static inline void get(const T& u, T& b1, T& b2, T& b3)\n    {\n        Eigen::Matrix<T,4,1> v(T(1.0),u,u*u,u*u*u);\n        Eigen::Matrix<T,4,4> m;\n        m << T(6.0) , T(0.0) , T(0.0) , T(0.0),\n             T(5.0) , T(3.0) , T(-3.0), T(1.0),\n             T(1.0) , T(3.0) , T(3.0), T(-2.0),\n             T(0.0) , T(0.0) , T(0.0) , T(1.0);\n        \n        const Eigen::Matrix<T,4,1> uvec = (m * v) / T(6.0);\n        b1 = uvec(1);\n        b2 = uvec(2);\n        b3 = uvec(3);\n    }\n#endif\n};\n\n// B4-Spline SO2\ntemplate<typename T>\nEIGEN_DEVICE_FUNC static inline Sophus::SO2<T> interpolateB4Spline(const Sophus::SO2<T>& tm1, \n                                                                   const Sophus::SO2<T>& t0, \n                                                                   const Sophus::SO2<T>& t1, \n                                                                   const Sophus::SO2<T>& t2, \n                                                                   const T& u)\n{\n    T b1, b2, b3;\n    \n    B4SplineGenerator<T>::get(u,b1,b2,b3);\n    \n    return tm1 * Sophus::SO2<T>::exp(b1 * ( tm1.inverse() * t0 ).log() + \n                                          b2 * ( t0.inverse()  * t1 ).log() +\n                                          b3 * ( t1.inverse()  * t2 ).log() );\n}\n\n// B4-Spline SE2\ntemplate<typename T>\nEIGEN_DEVICE_FUNC static inline Sophus::SE2<T> interpolateB4Spline(const Sophus::SE2<T>& tm1, \n                                                                   const Sophus::SE2<T>& t0, \n                                                                   const Sophus::SE2<T>& t1, \n                                                                   const Sophus::SE2<T>& t2, \n                                                                   const T& u)\n{\n    T b1, b2, b3;\n    \n    B4SplineGenerator<T>::get(u,b1,b2,b3);\n    \n    const Sophus::SO2<T> rot_final = tm1.so2() * Sophus::SO2<T>::exp(b1 * ( tm1.so2().inverse() * t0.so2() ).log() + \n                                                                               b2 * ( t0.so2().inverse()  * t1.so2() ).log() +\n                                                                               b3 * ( t1.so2().inverse()  * t2.so2() ).log() );\n    \n    const typename Sophus::SE2<T>::Point tr_final = tm1.translation() + (b1 * (t0.translation() - tm1.translation())) + \n                                                                             (b2 * (t1.translation() - t0.translation())) + \n                                                                             (b3 * (t2.translation() - t1.translation()));\n    \n    return Sophus::SE2<T>(rot_final, tr_final);\n}\n\n// B4-Spline SO3\ntemplate<typename T>\nEIGEN_DEVICE_FUNC static inline Sophus::SO3<T> interpolateB4Spline(const Sophus::SO3<T>& tm1, \n                                                                   const Sophus::SO3<T>& t0, \n                                                                   const Sophus::SO3<T>& t1, \n                                                                   const Sophus::SO3<T>& t2, \n                                                                   const T& u)\n{\n    T b1, b2, b3;\n    \n    B4SplineGenerator<T>::get(u,b1,b2,b3);\n    \n    return tm1 * Sophus::SO3<T>::exp(b1 * ( tm1.inverse() * t0 ).log() + \n                                          b2 * ( t0.inverse()  * t1 ).log() +\n                                          b3 * ( t1.inverse()  * t2 ).log() );\n}\n\n// B4-Spline SE3\ntemplate<typename T>\nEIGEN_DEVICE_FUNC static inline Sophus::SE3<T> interpolateB4Spline(const Sophus::SE3<T>& tm1, \n                                                                   const Sophus::SE3<T>& t0, \n                                                                   const Sophus::SE3<T>& t1, \n                                                                   const Sophus::SE3<T>& t2, \n                                                                   const T& u)\n{\n    T b1, b2, b3;\n    \n    B4SplineGenerator<T>::get(u,b1,b2,b3);\n    \n    const Sophus::SO3<T> rot_final = tm1.so3() * Sophus::SO3<T>::exp(b1 * ( tm1.so3().inverse() * t0.so3() ).log() + \n                                                                               b2 * ( t0.so3().inverse()  * t1.so3() ).log() +\n                                                                               b3 * ( t1.so3().inverse()  * t2.so3() ).log() );\n    \n    const typename Sophus::SE3<T>::Point tr_final = tm1.translation() + (b1 * (t0.translation() - tm1.translation())) + \n                                                                             (b2 * (t1.translation() - t0.translation())) + \n                                                                             (b3 * (t2.translation() - t1.translation()));\n    \n    return Sophus::SE3<T>(rot_final, tr_final);\n}\n\n// let's put ostreams here\ntemplate<typename Derived>\ninline std::ostream& operator<<(std::ostream& os, const SO2Base<Derived>& p)\n{\n    os << \"(\" << p.log() << \")\"; \n    return os;\n}\n\ntemplate<typename Derived>\ninline std::ostream& operator<<(std::ostream& os, const SO3Base<Derived>& p)\n{\n    os << \"(\" << p.unit_quaternion().x() << \",\" << p.unit_quaternion().y() << \",\" \n       << p.unit_quaternion().z() << \"|\" << p.unit_quaternion().w() << \")\"; \n    return os;\n}\n\ntemplate<typename Derived>\ninline std::ostream& operator<<(std::ostream& os, const SE2Base<Derived>& p)\n{\n    os << \"[t = \" << p.translation()(0) << \",\" << p.translation()(1) << \" | r = \" << p.so2() << \")\";\n    return os;\n}\n\ntemplate<typename Derived>\ninline std::ostream& operator<<(std::ostream& os, const SE3Base<Derived>& p)\n{\n    os << \"[t = \" << p.translation()(0) << \",\" << p.translation()(1) << \",\" << p.translation()(2) << \" | r = \" << p.so3() << \")\";\n    return os;\n}\n\n#ifdef VISIONCORE_ENABLE_CEREAL\n\n/**\n * SO2\n */    \ntemplate<typename Archive, typename Derived>\nvoid load(Archive & archive, SO2Base<Derived>& m, std::uint32_t const version)\n{\n    typename SO2Base<Derived>::Point cplx;\n    archive(cplx);\n    m.setComplex(cplx);\n}\n\ntemplate<typename Archive, typename Derived>\nvoid save(Archive & archive, SO2Base<Derived> const & m, std::uint32_t const version)\n{\n    archive(m.unit_complex());\n}\n\n/**\n * SO3\n */    \ntemplate<typename Archive, typename Derived>\nvoid load(Archive & archive, SO3Base<Derived>& m, std::uint32_t const version)\n{\n    Eigen::Quaternion<typename SO3Base<Derived>::Scalar> quaternion;\n    archive(cereal::make_nvp(\"Quaternion\", quaternion));\n    m.setQuaternion(quaternion);\n}\n\ntemplate<typename Archive, typename Derived>\nvoid save(Archive & archive, SO3Base<Derived> const & m, std::uint32_t const version)\n{\n    archive(cereal::make_nvp(\"Quaternion\", m.unit_quaternion()));\n}\n\n/**\n * SE2\n */    \ntemplate<typename Archive, typename Derived>\nvoid load(Archive & archive, SE2Base<Derived>& m, std::uint32_t const version)\n{\n    archive(cereal::make_nvp(\"Translation\", m.translation()));\n    archive(cereal::make_nvp(\"Rotation\", m.so2()));\n}\n\ntemplate<typename Archive, typename Derived>\nvoid save(Archive & archive, SE2Base<Derived> const & m, std::uint32_t const version)\n{\n    archive(cereal::make_nvp(\"Translation\", m.translation()));\n    archive(cereal::make_nvp(\"Rotation\", m.so2()));\n}\n\n/**\n * SE3\n */    \ntemplate<typename Archive, typename Derived>\nvoid load(Archive & archive, SE3Base<Derived>& m, std::uint32_t const version)\n{\n    archive(cereal::make_nvp(\"Translation\", m.translation()));\n    archive(cereal::make_nvp(\"Rotation\", m.so3()));\n}\n\ntemplate<typename Archive, typename Derived>\nvoid save(Archive & archive, SE3Base<Derived> const & m, std::uint32_t const version)\n{\n    archive(cereal::make_nvp(\"Translation\", m.translation()));\n    archive(cereal::make_nvp(\"Rotation\", m.so3()));\n}\n\n/**\n * RxSO3\n */    \ntemplate<typename Archive, typename Derived>\nvoid load(Archive & archive, RxSO3Base<Derived>& m, std::uint32_t const version)\n{\n    archive(cereal::make_nvp(\"Quaternion\", m.quaternion()));\n}\n\ntemplate<typename Archive, typename Derived>\nvoid save(Archive & archive, RxSO3Base<Derived> const & m, std::uint32_t const version)\n{\n    archive(cereal::make_nvp(\"Quaternion\", m.quaternion()));\n}\n\n/**\n * Sim3\n */    \ntemplate<typename Archive, typename Derived>\nvoid load(Archive & archive, Sim3Base<Derived>& m, std::uint32_t const version)\n{\n    archive(cereal::make_nvp(\"Translation\", m.translation()));\n    archive(cereal::make_nvp(\"Rotation\", m.rxso3()));\n}\n\ntemplate<typename Archive, typename Derived>\nvoid save(Archive & archive, Sim3Base<Derived> const & m, std::uint32_t const version)\n{\n    archive(cereal::make_nvp(\"Translation\", m.translation()));\n    archive(cereal::make_nvp(\"Rotation\", m.rxso3()));\n}\n\n#endif // VISIONCORE_ENABLE_CEREAL\n\n/**\n * Stuff that Hauke removed.\n * \n * \\param alpha1 rotation around x-axis\n * \\param alpha2 rotation around y-axis\n * \\param alpha3 rotation around z-axis\n *\n * Since rotations in 3D do not commute, the order of the individual rotations\n * matter. Here, the following convention is used. We calculate a SO3 member\n * corresponding to the rotation matrix \\f$ R \\f$ such\n * that \\f$ R=\\exp\\left(\\begin{array}{c}\\alpha_1\\\\ 0\\\\ 0\\end{array}\\right)\n *    \\cdot   \\exp\\left(\\begin{array}{c}0\\\\ \\alpha_2\\\\ 0\\end{array}\\right)\n *    \\cdot   \\exp\\left(\\begin{array}{c}0\\\\ 0\\\\ \\alpha_3\\end{array}\\right)\\f$.\n */\ntemplate<typename T>\nEIGEN_DEVICE_FUNC static inline SO3<T> fromEulerAngles(const T alpha1, const T alpha2, const T alpha3)\n{\n    typedef typename SO3<T>::Tangent Tangent;\n    const static T zero = static_cast<T>(0);\n    \n    return SO3<T>((SO3<T>::exp(Tangent(alpha1, zero, zero)) *\n                   SO3<T>::exp(Tangent(zero, alpha2, zero)) *\n                   SO3<T>::exp(Tangent(zero, zero, alpha3)))\n                 );\n}\n\n}\n\n#endif // VISIONCORE_SOPHUS_MISSINGBITS_HPP\n", "meta": {"hexsha": "44d812232ef83c6624a2fabb779aa3201eaad257", "size": 12163, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/VisionCore/HelpersSophus.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/HelpersSophus.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/HelpersSophus.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": 35.7735294118, "max_line_length": 129, "alphanum_fraction": 0.5311189674, "num_tokens": 3338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5423252159691424}}
{"text": "//\n// Dynamics of a simple car.\n// State space is 4-d [pos_x, pos_y, vel, angle]\n// Control is 2-d [acceleration, delta-angle]\n// \n\n# pragma once\n\n\n#include <ilqr/ilqr_taylor_expansions.hh> // Definition of dynamics function.\n\n#include <Eigen/Dense>\n\n#include <cstdint>\n\nnamespace simulators\n{\nnamespace simplecar\n{\n\nenum State \n{\n    POS_X = 0,\n    POS_Y,\n    VEL,\n    ANG\n};\n\nenum Control \n{\n    CNTRL_ACC = 0,\n    CNTRL_DELTA_ANG,\n};\n\n// State is [position, velocity, Steering Angle]\nconstexpr int STATE_DIM = 5;\n\n// Control is [Acceleration, Delta-Steering Angle]\nconstexpr int CONTROL_DIM = 2;\n\nilqr::DynamicsFunc make_discrete_dynamics_func(const double dt);\n\nEigen::VectorXd discrete_dynamics(const Eigen::VectorXd& xt,\n                                  const Eigen::VectorXd& ut,\n                                  const double dt);\n} // namespace pendulum\n} // namespace simulators\n", "meta": {"hexsha": "3e8bd0680dfcae1858625cdbdff4164a7d19dab2", "size": 890, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/experiments/simulators/simplecar.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/simplecar.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/simplecar.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": 18.5416666667, "max_line_length": 77, "alphanum_fraction": 0.6561797753, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5423252121305964}}
{"text": "/*\n * Copyright 2018 James Dyer\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * 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, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n *\n * This is being developed for the TANGO Project: http://tango-project.eu\n */\n\n#include <sstream>\n#include <NTL/RR.h>\n#include <jsoncpp/json/json.h>\n#include \"GACDEncrypter.h\"\n\nGACDEncrypter::GACDEncrypter(int lambda) {\n\tk = NTL::RandomPrime_ZZ(lambda, 20);\n\tNTL::RR kreal = to_RR(k);\n\tminr = RoundToZZ(sqrt(sqrt(power(kreal,3)))); // minr = k^{3/4}\n\tmaxr = k-minr;\n}\n\nNTL::ZZ GACDEncrypter::encrypt(NTL::ZZ& plaintext){\n\tNTL::ZZ r = rng.nextBigInteger(minr, maxr);\n\treturn plaintext*k+r;\n}\n\nstd::string GACDEncrypter::writeSecretsToJSON(){\n\tJson::Value root;\n\tstd::stringstream keyStr;\n\tkeyStr << k;\n\troot[\"key\"] = keyStr.str();\n\tJson::FastWriter writer;\n\treturn writer.write(root);\n}\n\nint GACDEncrypter::getMinimumKeyLength(int bits){\n\treturn ceil(8.0*bits/3);\n}\n", "meta": {"hexsha": "71cf59c8177cbf5068985e751021c6e482e674dc", "size": 1354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GACDEncrypter.cpp", "max_stars_repo_name": "TANGO-Project/cryptsdc", "max_stars_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "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": "src/GACDEncrypter.cpp", "max_issues_repo_name": "TANGO-Project/cryptsdc", "max_issues_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "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": "src/GACDEncrypter.cpp", "max_forks_repo_name": "TANGO-Project/cryptsdc", "max_forks_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "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": 28.2083333333, "max_line_length": 80, "alphanum_fraction": 0.7193500739, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5423252057431388}}
{"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 SEVEN_POINT_HPP_\n#define SEVEN_POINT_HPP_\n\n#include <Eigen/Dense>\n\n#include <vector>\n\nclass SevenPointTest;\n\nnamespace SevenPoint\n{\n\ntemplate <typename FloatType>\nclass SevenPoint\n{\n\tfriend ::SevenPointTest;\nprivate:\n\ttypedef Eigen::Matrix<std::complex<FloatType>, 3, 1> CMatrix_3x1;\n\ttypedef Eigen::Matrix<FloatType, 3, 3> Matrix_3x3;\n\ttypedef Eigen::Matrix<FloatType, 7, 9> Matrix_7x9;\n\ttypedef Eigen::Matrix<FloatType, 9, 9> Matrix_9x9;\n\ttypedef Eigen::Matrix<FloatType, 9, Eigen::Dynamic> Matrix_9xD;\n\npublic:\n\tSevenPoint() :\n\t\tm_F1(m_F)\n\t\t, m_F2(m_F1 + 9)\n\t{\n\t}\n\n\tvirtual ~SevenPoint()\n\t{\n\t}\n\n\tbool getMatrix(const FloatType *pts1, const FloatType *pts2, int &nSolutions, std::vector<FloatType> &Fs)\n\t{\n\t\tgetConstraints(pts1, pts2);\n\t\tbool ret = getRoot();\n\t\tif (!ret)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tnSolutions = m_mFvec.cols();\n\t\tFs.resize(9 * nSolutions);\n\t\tfor (int i = 0; i < nSolutions; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < 9; j++)\n\t\t\t{\n\t\t\t\tFs[9 * i + j] = m_mFvec(j, i);\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\nprivate:\n\t// 1st order polynomial multiplication\n\t// (ax + b) * (cx + d) = (acx^2 + (ad + bc)x + bd)\n\t// p1 = [x 1]\n\t// p2 = [x 1]\n\t// p3 = [x^2 x 1]\n\tstatic inline void polynomial_multiplication1(const FloatType *p1, const FloatType *p2, FloatType *p3)\n\t{\n\t\tp3[0] = (p1[0])*(p2[0]);\t\t\t\t\t// x^2\n\t\tp3[1] = (p1[0])*(p2[1]) + (p1[1])*(p2[0]);\t// x\n\t\tp3[2] = (p1[1])*(p2[1]);\t\t\t\t\t// 1\n\t}\n\n\t// 2nd order polynomial multiplication\n\t// (ax + b) * (cx^2 + dx + e) = (acx^3 + (ad + bc)x^2 + ... + be)\n\t// p1 = [x 1]\n\t// p3 = [x^2 x 1]\n\t// p3 = [x^3 x^2 x 1]\n\tstatic inline void polynomial_multiplication2(const FloatType *p1, const FloatType *p2, FloatType *p3)\n\t{\n\t\tp3[0] = (p1[0])*(p2[0]);\t\t\t\t\t// x^3\n\t\tp3[1] = (p1[0])*(p2[1]) + (p1[1])*(p2[0]);\t// x^2\n\t\tp3[2] = (p1[0])*(p2[2]) + (p1[1])*(p2[1]);\t// x\n\t\tp3[3] = (p1[1])*(p2[2]);\t\t\t\t\t// 1\n\t}\n\n\tstatic inline void getLinearConstraints(const FloatType *pts1, const FloatType *pts2, FloatType *F1, FloatType *F2)\n\t{\n\t\tMatrix_7x9 mC;\n\t\tfor (unsigned int i = 0; i < 7; i++){\n\t\t\tconst FloatType *p1 = &(pts1[2*i]), *p2 = &(pts2[2*i]);\n\t\t\tmC(i, 0) = (p2[0])*(p1[0]);\n\t\t\tmC(i, 1) = (p2[0])*(p1[1]);\n\t\t\tmC(i, 2) = (p2[0]);\n\t\t\tmC(i, 3) = (p2[1])*(p1[0]);\n\t\t\tmC(i, 4) = (p2[1])*(p1[1]);\n\t\t\tmC(i, 5) = (p2[1]);\n\t\t\tmC(i, 6) = (p1[0]);\n\t\t\tmC(i, 7) = (p1[1]);\n\t\t\tmC(i, 8) = 1;\n\t\t}\n\n\t\tEigen::JacobiSVD<Matrix_7x9> svd(mC, Eigen::ComputeFullV);\n\t\tMatrix_9x9 mV = svd.matrixV();\n\t\tfor (int i = 0; i < 9; i++)\n\t\t{\n\t\t\tF1[i] = mV(i, 7);\n\t\t\tF2[i] = mV(i, 8);\n\t\t}\n\t}\n\tstatic inline void getDeterminantConstraints(const FloatType *F1, const FloatType *F2, FloatType *C)\n\t{\n\t\tC[0] = C[1] = C[2] = C[3] = 0;\n\t\tFloatType p00[] = {F1[0], F2[0]}; // (0, 0)\n\t\tFloatType p01[] = {F1[1], F2[1]}; // (0, 1)\n\t\tFloatType p02[] = {F1[2], F2[2]}; // (0, 2)\n\t\tFloatType p10[] = {F1[3], F2[3]}; // (1, 0)\n\t\tFloatType p11[] = {F1[4], F2[4]}; // (1, 1)\n\t\tFloatType p12[] = {F1[5], F2[5]}; // (1, 2)\n\t\tFloatType p20[] = {F1[6], F2[6]}; // (2, 0)\n\t\tFloatType p21[] = {F1[7], F2[7]}; // (2, 1)\n\t\tFloatType p22[] = {F1[8], F2[8]}; // (2, 2)\n\n\t\tFloatType c1[3], c2[3], c3[4];\n\t\tpolynomial_multiplication1(p11, p22, c1);\n\t\tpolynomial_multiplication1(p12, p21, c2);\n\t\tc1[0] -= c2[0]; c1[1] -= c2[1]; c1[2] -= c2[2];\n\t\tpolynomial_multiplication2(p00, c1, c3);\n\t\tC[0] += c3[0]; C[1] += c3[1]; C[2] += c3[2]; C[3] += c3[3];\n\n\t\tpolynomial_multiplication1(p01, p22, c1);\n\t\tpolynomial_multiplication1(p02, p21, c2);\n\t\tc1[0] -= c2[0]; c1[1] -= c2[1]; c1[2] -= c2[2];\n\t\tpolynomial_multiplication2(p10, c1, c3);\n\t\tC[0] -= c3[0]; C[1] -= c3[1]; C[2] -= c3[2]; C[3] -= c3[3];\n\n\t\tpolynomial_multiplication1(p01, p12, c1);\n\t\tpolynomial_multiplication1(p02, p11, c2);\n\t\tc1[0] -= c2[0]; c1[1] -= c2[1]; c1[2] -= c2[2];\n\t\tpolynomial_multiplication2(p20, c1, c3);\n\t\tC[0] += c3[0]; C[1] += c3[1]; C[2] += c3[2]; C[3] += c3[3];\n\t}\n\nprotected:\n\tstatic const size_t m_minSet; // minimum data number for parameter esimation\n\tstatic const bool m_acceptArbitraryNSet; // if true, this model accepts arbitrary data number for parameter esimation\n\nprivate:\n\tvoid getConstraints(const FloatType *pts1, const FloatType *pts2)\n\t{\n\t\tgetLinearConstraints(pts1, pts2, m_F1, m_F2);\n\t\tgetDeterminantConstraints(m_F1, m_F2, m_C);\n\t}\n\n\tbool getRoot()\n\t{\n\t\t// construct the companion matrix\n\t\tMatrix_3x3 mC;\n\t\tmC.setZero();\n\t\tmC(1, 0) = mC(2, 1) = 1;\n\t\tmC(0, 2) = -m_C[3] / m_C[0];\n\t\tmC(1, 2) = -m_C[2] / m_C[0];\n\t\tmC(2, 2) = -m_C[1] / m_C[0];\n\t\tEigen::EigenSolver<Matrix_3x3> eig(mC, false);\n\t\tCMatrix_3x1 mSols = eig.eigenvalues();\n\n\t\tstd::vector<int> idx(0);\n\t\tfor(int j = 0; j < 3; j++)\n\t\t{\n\t\t\tif(mSols[j].imag() == 0)\n\t\t\t{\n\t\t\t\tidx.push_back(j);\n\t\t\t}\n\t\t}\n\n\t\tif (idx.empty())\n\t\t{\n\t\t\treturn false; // 3rd oder polynomial has at least one real root!\n\t\t}\n\n\t\tm_mFvec = Matrix_9xD(9, idx.size());\n\t\tfor (size_t i = 0; i < idx.size(); i++)\n\t\t{\n\t\t\tfor (int j = 0; j < 9; j++)\n\t\t\t{\n\t\t\t\tm_mFvec(j, i) = (mSols[i].real()) * (m_F1[j]) + (m_F2[j]);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tFloatType m_F[9*2]; // orthogonal basis of null space of linear constarints\n\tFloatType m_C[4]; \t// deteminant constraints\n\tFloatType *m_F1, *m_F2; // pointer to F\n\tMatrix_9xD m_mFvec; // Essential matrix solutions\n};\ntemplate <typename FloatType>\nconst size_t SevenPoint<FloatType>::m_minSet = 7;\ntemplate <typename FloatType>\nconst bool SevenPoint<FloatType>::m_acceptArbitraryNSet = false;\n\n}\n\n#endif // SEVEN_POINT_HPP_", "meta": {"hexsha": "012d66ed7c0d9d588acf983ee623589c505cb879", "size": 6789, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/SevenPoint.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/SevenPoint.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/SevenPoint.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": 30.3080357143, "max_line_length": 118, "alphanum_fraction": 0.6214464575, "num_tokens": 2642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5423252006301368}}
{"text": "#ifndef MLT_DEFS_HPP\n#define MLT_DEFS_HPP\n\n#include <Eigen/Core>\n\n#ifdef MLT_VERBOSE\n#define MLT_LOG(log) cout << log;\n#else\n#define MLT_LOG(log)\n#endif\n\n#define MLT_LOG_LINE(log) MLT_LOG(log << endl);\n\nnamespace mlt {\n\tusing namespace std;\n\tusing namespace Eigen;\n\n\tusing VectorXdRef = const Ref<const VectorXd>&;\n\tusing MatrixXdRef = const Ref<const MatrixXd>&;\n\n\tusing VectorXiRef = const Ref<const VectorXi>&;\n\tusing MatrixXiRef = const Ref<const MatrixXi>&;\n\n\tusing Features = MatrixXdRef;\n}\n#endif", "meta": {"hexsha": "3b35db2d0d43f35698f5123fba0d8938916e49e8", "size": 503, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/defs.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/defs.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/defs.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": 19.3461538462, "max_line_length": 48, "alphanum_fraction": 0.7475149105, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.542263853104562}}
{"text": "//\n// harmonic.cpp\n//\n// Copyright (c) 1996-1998 Takashi Kanai\n//\n// This software is released under the MIT License.\n// http://opensource.org/licenses/mit-license.php\n//\n\n#include \"StdAfx.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\n#include <math.h>\n#include \"smd.h\"\n#include \"harmonic.h\"\n#include \"ppdedge.h\"\n#include \"hgppd.h\"\n// #include \"linbcg.h\"\n\n#define KAPPA 1.0\n\n#include <vector>\n#include <Eigen/Sparse>\n#include <Eigen/OrderingMethods>\n\n/*******************************************************************************\n  STEP 2: harmonic maps (Related functions are in \"harmonic.c\".)\n*******************************************************************************/\n\nvoid harmonic_initialize_vector_2( HGfc *hgfc, Splp *lp,\n                                   Eigen::VectorXd& bx, Eigen::VectorXd& by )\n{\n  int    i;\n  HGvt   *vt;\n  Vec2d  *uvbprm;\n  Sple   *le, *tle, *sle;\n  Splv   *lv, *tlv, *slv, *elv;\n  double sum, esum, val;\n  Vec2d  sub;\n\n  /* initialize vector */\n  for ( vt = hgfc->shgvt; vt != (HGvt *) NULL; vt = vt->nxt )\n    {\n      bx[vt->sid] = 0.0;\n      by[vt->sid] = 0.0;\n    //   emat->bx[vt->sid] = emat->xx[vt->sid] = 0.0;\n    // emat->by[vt->sid] = emat->yy[vt->sid] = 0.0;\n    }\n\n  uvbprm = calc_uvbprm( hgfc->hgcn );\n\n  /* calculate boundary values */\n\n  lv = lp->splv;\n  le = lp->sple;\n\n  i = 0;\n  while ( i < hgfc->hgcn ) {\n\n    slv = lv;\n    sle = le;\n    sum = 0.0;\n\n    while ( 1 ) {\n      sum += le->ed->length;\n      lv = lv->nxt;\n      le = le->nxt;\n      if ( lv == (Splv *) NULL ) {\n        elv = lp->splv;\n        break;\n      }\n      if ( lv->vt->sp_type == SP_VERTEX_HVERTEX ) {\n        elv = lv;\n        break;\n      }\n    }\n\n    esum = 0.0;\n    tlv = slv;\n    tle = sle;\n    sub.x = uvbprm[i+1].x - uvbprm[i].x;\n    sub.y = uvbprm[i+1].y - uvbprm[i].y;\n    while ( 1 ) {\n\n      val = esum / sum;\n      bx[ tlv->hgvt->sid ] = uvbprm[i].x + sub.x * val;\n      by[ tlv->hgvt->sid ] = uvbprm[i].y + sub.y * val;\n      // emat->bx[ tlv->hgvt->sid ] = uvbprm[i].x + sub.x * val;\n      // emat->by[ tlv->hgvt->sid ] = uvbprm[i].y + sub.y * val;\n\n      esum += tle->ed->length;\n\n      tlv = tlv->nxt;\n      tle = tle->nxt;\n\n      if ( (tlv == elv) || (tlv == (Splv *) NULL) ) break;\n    }\n\n    ++i;\n  }\n\n  free(uvbprm);\n}\n\n// harmonic mapping functions with Eigen\n\nvoid hgfcharmonic_Eigen( HGfc *hgfc, Splp *lp )\n{\n  int vn = initialize_hgfc( hgfc );\n\n  // alternates harmonic_calc_kappa function\n  double* kappa = (double*) malloc( hgfc->hgen * sizeof(double) );\n  for ( HGed* ed = hgfc->shged; ed != (HGed*) NULL; ed = ed->nxt )\n    {\n      kappa[ed->sid] = 1.0;\n    }\n\n  // vt->vval initialization\n  for ( HGvt* vt = hgfc->shgvt; vt != (HGvt *) NULL; vt = vt->nxt )\n    {\n      vt->vval = 0.0;\n    }\n  \n  // setup val and vval\n  for ( HGvt* vt = hgfc->shgvt; vt != (HGvt *) NULL; vt = vt->nxt ) {\n    for ( HGvted* ve = vt->shgve; ve != (HGvted *) NULL; ve = ve->nxt )\n      {\n        HGed* ed = ve->ed;\n        // sv\n        int id = ed->sv->sid;\n        if (vt->sid != id)\n          {\n            HGvtvt* vv = find_sort_hgvtvt( vt, id );\n            vv->val -= kappa[ed->sid];\n          }\n        else\n          {\n            vt->vval += kappa[ed->sid];\n          }\n        // ev\n        id = ed->ev->sid;\n        if (vt->sid != id)\n          {\n            HGvtvt* vv = find_sort_hgvtvt( vt, id );\n            vv->val -= kappa[ed->sid];\n          }\n        else\n          {\n            vt->vval += kappa[ed->sid];\n          }\n      }\n  }\n      \n  free(kappa);\n\n  // boundary points are fixed\n  for ( HGvt* vt = hgfc->shgvt; vt != (HGvt *) NULL; vt = vt->nxt )\n    {\n      if ( vt->vt->sp_type != SP_VERTEX_NORMAL )\n        {\n          vt->vval = 1.0;\n          free_hgppdvertexvertex( vt );\n        }\n    }\n\n  // setup matrix A\n  // build up sparse matrix A\n\n  int n_vt = hgfc->hgvn;\n  Eigen::SparseMatrix<double> spmat( n_vt, n_vt );\n  \n  for ( HGvt* vt = hgfc->shgvt; vt != (HGvt*) NULL; vt = vt->nxt )\n    {\n      int i = vt->sid;\n      spmat.insert( i, i ) = vt->vval;\n      if ( vt->vt->sp_type == SP_VERTEX_NORMAL )\n        {\n          for ( HGvtvt* vv = vt->shgvv; vv != (HGvtvt*) NULL; vv = vv->nxt )\n            {\n              int j = vv->id;\n              spmat.insert( i, j ) = vv->val;\n            }\n        }\n    }\n  spmat.makeCompressed();\n\n  // setup vector b\n  Eigen::VectorXd bx(n_vt), by(n_vt);\n  harmonic_initialize_vector_2( hgfc, lp, bx, by );\n\n  // solve x and y\n  Eigen::VectorXd xx(n_vt), xy(n_vt);\n  Eigen::BiCGSTAB<Eigen::SparseMatrix<double> > solver(spmat);\n  xx = solver.solve(bx);\n  xy = solver.solve(by);\n\n  // store x to uvw\n  for ( HGvt* vt = hgfc->shgvt; vt != (HGvt *) NULL; vt = vt->nxt )\n    {\n      vt->uvw.x = xx[vt->sid];\n      vt->uvw.y = xy[vt->sid];\n    }\n\n  exit_hgfc( hgfc );\n}\n\nvoid hppdharmonic( HPpd *hppd )\n{\n  HFace *hf;\n\n  /* calc edge length */\n  edge_length( hppd->ppd1 );\n  edge_length( hppd->ppd2 );\n  for ( hf = hppd->shfc; hf != (HFace *) NULL; hf = hf->nxt )\n    {\n      hgfcharmonic_Eigen( hf->hgfc1, hf->hloop->lp1 );\n      hgfcharmonic_Eigen( hf->hgfc2, hf->hloop->lp2 );\n      // hgfcharmonic( hf->hgfc1, hf->hloop->lp1 );\n      // hgfcharmonic( hf->hgfc2, hf->hloop->lp2 );\n    }\n}\n\n#if 0\n/* harmonic mapping functions */\nvoid hgfcharmonic( HGfc *hgfc, Splp *lp )\n{\n  int    iter;\n  int    vn;\n  double rsq;\n  Semat  *emat;\n\n  vn = initialize_hgfc( hgfc );\n  emat = create_harmonic_emat( hgfc );\n  harmonic_initialize_vector( hgfc, lp, emat );\n\n  linbcg( emat, emat->bx, emat->xx, 1, SMDZEROEPS, 1000, &iter, &rsq );\n  linbcg( emat, emat->by, emat->yy, 1, SMDZEROEPS, 1000, &iter, &rsq );\n  solvec_hgfc( hgfc, emat );\n\n  free_emat( emat );\n  exit_hgfc( hgfc );\n}\n#endif\n\nint initialize_hgfc( HGfc *hgfc )\n{\n  int  i;\n  int  cnt = 0;\n  HGvt *hv;\n  HGed *he;\n\n  /* id */\n\n  for (i = 0, hv = hgfc->shgvt; hv != (HGvt *) NULL; hv = hv->nxt, ++i) {\n    hv->sid  = i;\n    if ( hv->vt->sp_type == SP_VERTEX_NORMAL ) {\n      ++cnt;\n    }\n  }\n  /* , and create hgvt->hged links */\n  for (i = 0, he = hgfc->shged; he != (HGed *) NULL; he = he->nxt, ++i) {\n    he->sid  = i;\n    create_hgvted( he->sv, he );\n    create_hgvted( he->ev, he );\n  }\n  return cnt;\n}\n\n#if 0\nSemat *create_harmonic_emat( HGfc *hgfc )\n{\n  int    i, vn;\n  int    id;\n  double *kappa;\n  Semat  *emat;\n  HGvt   *vt;\n  HGed   *ed;\n  HGvted *ve;\n  HGvtvt *vv;\n\n  emat = init_emat( hgfc->hgvn );\n\n  kappa = harmonic_calc_kappa( hgfc );\n\n  for ( vt = hgfc->shgvt; vt != (HGvt *) NULL; vt = vt->nxt ) {\n    vt->vval = 0.0;\n  }\n\n  for ( vt = hgfc->shgvt; vt != (HGvt *) NULL; vt = vt->nxt ) {\n    for ( ve = vt->shgve; ve != (HGvted *) NULL; ve = ve->nxt ) {\n\n      ed = ve->ed;\n      /* sv */\n      id = ed->sv->sid;\n      if (vt->sid != id) {\n        vv = find_sort_hgvtvt( vt, id );\n        vv->val -= kappa[ed->sid];\n      } else {\n        vt->vval += kappa[ed->sid];\n      }\n      /* ev */\n      id = ed->ev->sid;\n      if (vt->sid != id) {\n        vv = find_sort_hgvtvt( vt, id );\n        vv->val -= kappa[ed->sid];\n      } else {\n        vt->vval += kappa[ed->sid];\n      }\n    }\n  }\n\n  /* Boundary Points are fixed. */\n  for ( vt = hgfc->shgvt; vt != (HGvt *) NULL; vt = vt->nxt ) {\n\n    if ( vt->vt->sp_type != SP_VERTEX_NORMAL ) {\n      vt->vval = 1.0;\n      free_hgppdvertexvertex( vt );\n    }\n\n  }\n\n  vn = 0;\n  for ( vt = hgfc->shgvt; vt != (HGvt *) NULL; vt = vt->nxt ) {\n    vn += vt->hgvvn;\n  }\n\n  emat->num = vn + hgfc->hgvn + 1;\n  emat->sa  = (double *) malloc(emat->num * sizeof(double));\n  for (i = 0; i < emat->num; ++i) emat->sa[i] = 0.0;\n  emat->ija = (int *) malloc(emat->num * sizeof(int));\n\n  dsprsin( hgfc, emat );\n  \n  free(kappa);\n\n  FreeHGppdVertexVertex( hgfc );\n\n  return emat;\n}\n\ndouble *harmonic_calc_kappa( HGfc *hgfc )\n{\n  double *kappa;\n  HGed   *ed;\n\n  /* initialize length, area, kappa */\n  kappa   = (double *) malloc( hgfc->hgen * sizeof(double));\n\n  for ( ed = hgfc->shged; ed != (HGed *) NULL; ed = ed->nxt ) {\n    kappa[ed->sid] = 1.0;\n  }\n  return kappa;\n}\n\nvoid harmonic_initialize_vector( HGfc *hgfc, Splp *lp, Semat *emat )\n{\n  int    i;\n  HGvt   *vt;\n  Vec2d  *uvbprm;\n  Sple   *le, *tle, *sle;\n  Splv   *lv, *tlv, *slv, *elv;\n  double sum, esum, val;\n  Vec2d  sub;\n\n  /* initialize vector */\n  for ( vt = hgfc->shgvt; vt != (HGvt *) NULL; vt = vt->nxt ) {\n\n    emat->bx[vt->sid] = emat->xx[vt->sid] = 0.0;\n    emat->by[vt->sid] = emat->yy[vt->sid] = 0.0;\n\n  }\n\n  uvbprm = calc_uvbprm( hgfc->hgcn );\n\n  /* calculate boundary values */\n\n  lv = lp->splv;\n  le = lp->sple;\n\n  i = 0;\n  while ( i < hgfc->hgcn ) {\n\n    slv = lv;\n    sle = le;\n    sum = 0.0;\n\n    while ( 1 ) {\n      sum += le->ed->length;\n      lv = lv->nxt;\n      le = le->nxt;\n      if ( lv == (Splv *) NULL ) {\n        elv = lp->splv;\n        break;\n      }\n      if ( lv->vt->sp_type == SP_VERTEX_HVERTEX ) {\n        elv = lv;\n        break;\n      }\n    }\n\n    esum = 0.0;\n    tlv = slv;\n    tle = sle;\n    sub.x = uvbprm[i+1].x - uvbprm[i].x;\n    sub.y = uvbprm[i+1].y - uvbprm[i].y;\n    while ( 1 ) {\n\n      val = esum / sum;\n      emat->bx[ tlv->hgvt->sid ] = uvbprm[i].x + sub.x * val;\n      emat->by[ tlv->hgvt->sid ] = uvbprm[i].y + sub.y * val;\n\n      esum += tle->ed->length;\n\n      tlv = tlv->nxt;\n      tle = tle->nxt;\n\n      if ( (tlv == elv) || (tlv == (Splv *) NULL) ) break;\n    }\n\n    ++i;\n  }\n\n  free(uvbprm);\n}\n#endif\n\nVec2d *calc_uvbprm( int cn )\n{\n  int i;\n  double angle;\n  Vec2d *uvbprm;\n\n  uvbprm = (Vec2d *) malloc( (cn+1) * sizeof(Vec2d) );\n\n  for ( i = 0; i <= cn; ++i ) {\n    angle = 2 * (double) i * SMDPI / (double) cn;\n    uvbprm[i].x = cos( angle );\n    uvbprm[i].y = sin( angle );\n/*     display(\"uvbprm %g %g\\n\", uvbprm[i].x, uvbprm[i].y); */\n  }\n  return uvbprm;\n}\n\n#if 0\nvoid solvec_hgfc( HGfc *hgfc, Semat *emat )\n{\n  HGvt *vt;\n\n  for ( vt = hgfc->shgvt; vt != (HGvt *) NULL; vt = vt->nxt ) {\n    vt->uvw.x = emat->xx[vt->sid];\n    vt->uvw.y = emat->yy[vt->sid];\n  }\n}\n#endif\n\nvoid exit_hgfc( HGfc *hgfc )\n{\n  HGvt *hv;\n  HGed *he;\n\n  for ( hv = hgfc->shgvt; hv != (HGvt *) NULL; hv = hv->nxt ) {\n    hv->sid  = SMDNULL;\n    hv->vval = 0.0;\n    free_hgppdvertexedge( hv );\n  }\n\n  /* create hgfc surface */\n\n  for ( he = hgfc->shged; he != (HGed *) NULL; he = he->nxt ) {\n    he->sid  = SMDNULL;\n  }\n\n}\n\n#if 0\n/* Semat functions */\nSemat *init_emat( int num )\n{\n  Semat *emat;\n\n  emat = (Semat *) malloc(sizeof(Semat));\n  emat->rnum = num;\n  emat->cnum = num;\n  /* constant vectors initialize */\n  emat->bx = (double *) malloc(num * sizeof(double));\n  emat->by = (double *) malloc(num * sizeof(double));\n  /* solution vectors initialize */\n  emat->xx = (double *) malloc(num * sizeof(double));\n  emat->yy = (double *) malloc(num * sizeof(double));\n\n  return emat;\n}\n\nvoid free_emat(Semat *emat)\n{\n  free(emat->sa);\n  free(emat->ija);\n  free(emat->bx);\n  free(emat->by);\n  free(emat->xx);\n  free(emat->yy);\n  free(emat);\n}\n#endif\n\n/*\nvoid printemat(Semat *emat)\n{\n  int i;\n\n  for (i = 0; i < emat->cnum; ++i) {\n    display(\"%d (b) %f %f\\n\", i, emat->bx[i], emat->by[i]);\n    display(\"%d (x) %f %f\\n\", i, emat->xx[i], emat->yy[i]);\n  }\n  for (i = 0; i < emat->num; ++i) \n    display(\"(%d) (sa) %f (ija) %d\\n\", i, emat->sa[i], emat->ija[i]);\n}\n*/\n\n", "meta": {"hexsha": "361bbbe63cefc52cd683f484c05d38538f718422", "size": 11215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/harmonic.cpp", "max_stars_repo_name": "kanait/gmorph", "max_stars_repo_head_hexsha": "e1461845c56e89221a4cdfb9933f575b456a852c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-04-30T17:12:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T03:45:17.000Z", "max_issues_repo_path": "src/harmonic.cpp", "max_issues_repo_name": "kanait/gmorph", "max_issues_repo_head_hexsha": "e1461845c56e89221a4cdfb9933f575b456a852c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/harmonic.cpp", "max_forks_repo_name": "kanait/gmorph", "max_forks_repo_head_hexsha": "e1461845c56e89221a4cdfb9933f575b456a852c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-07T10:15:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-16T12:43:11.000Z", "avg_line_length": 21.3619047619, "max_line_length": 80, "alphanum_fraction": 0.5012929113, "num_tokens": 4138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303236047049, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5422638497193809}}
{"text": "/**\n * Authors:\n *      Andre Potes (andre.potes@tecnico.ulisboa.pt)\n *      Marcelo Jacinto (marcelo.jacinto@tecnico.ulisboa.pt)\n * Maintained by: \n *      Andre Potes (andre.potes@tecnico.ulisboa.pt)\n *      Marcelo Jacinto (marcelo.jacinto@tecnico.ulisboa.pt)                \n * Last Update: 17/12/2021\n * License: MIT\n * File: test_math.cpp \n * Brief: Tests all the functions declared in math.hpp\n */\n#include \"dsor_utils/math.hpp\"\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n/* ========================== Test unit for sign function =============================== */\n\n/**\n * @brief Test function: inline int sign(T v)\n * only for positive values\n */\nTEST(TestSuite, SignPositive) {\n\n    // test positive numbers \n    ASSERT_EQ( DSOR::sign<int>(10) , 1);\n    ASSERT_EQ( DSOR::sign<double>( (double)20.0 ) , 1 );\n    ASSERT_EQ( DSOR::sign<float>( (float)15.0 ) , 1 );\n}\n\n/**\n * @brief Test function: inline int sign(T v)\n * only for zero\n */\nTEST(TestSuite, SignNegative) {\n    // test negative numbers \n    ASSERT_EQ( DSOR::sign<int>(-10) , -1);\n    ASSERT_EQ( DSOR::sign<double>( (double)-20.0 ) , -1 );\n    ASSERT_EQ( DSOR::sign<float>( (float)-15.0 ) , -1 );\n}\n\n/**\n * @brief Test function: inline int sign(T v)\n * only for positive values\n */\nTEST(TestSuite, SignZero) {\n\n    // test zero \n    ASSERT_EQ( DSOR::sign<int>(0) , 0);\n    ASSERT_EQ( DSOR::sign<double>( (double)0.0 ) , 0 );\n    ASSERT_EQ( DSOR::sign<float>( (float)0.0 ) , 0 );\n}\n\n/* ============================================================================================ */\n\n/* ========================== Test unit for saturation function =============================== */\n\n/**\n * @brief Test function: inline T saturation(T value, T min, T max)\n * only for positive saturated values\n */\nTEST(TestSuite, SaturatedPositive) {\n    \n    // test saturated positive value\n    ASSERT_EQ( DSOR::saturation<int>(15, -12, 10) , 10);\n    ASSERT_EQ( DSOR::saturation<double>( (double)15.0, (double)-12.0, (double)10.0) , (double)10.0);\n    ASSERT_EQ( DSOR::saturation<float>( (float)15.0, (float)-12.0, (float)10.0) , (float)10.0);\n\n}   \n\n/**\n * @brief Test function: inline T saturation(T value, T min, T max)\n * only for negative saturated values\n */\nTEST(TestSuite, SaturatedNegative) {\n    // test saturated negative value\n    ASSERT_EQ( DSOR::saturation<int>(-15, -12, 10) , -12);\n    ASSERT_EQ( DSOR::saturation<double>( (double)-15.0, (double)-12.0, (double)10.0) , (double)-12.0);\n    ASSERT_EQ( DSOR::saturation<float>( (float)-15.0, (float)-12.0, (float)10.0) , (float)-12.0); \n}\n\n/**\n * @brief Test function: inline T saturation(T value, T min, T max)\n * only for not saturated values\n */\nTEST(TestSuite, NotSatured) {\n    // test a value that is not saturated\n    ASSERT_EQ( DSOR::saturation<int>(5, -10, 10) , 5);\n    ASSERT_EQ( DSOR::saturation<double>( (double)5.0, (double)-12.0, (double)10.0) , (double)5.0);\n    ASSERT_EQ( DSOR::saturation<float>( (float)5.0, (float)-12.0, (float)10.0) , (float)5.0);\n}\n\n\nint main(int argc, char **argv) {\n    testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}", "meta": {"hexsha": "23ffdd758468bb1523b1e3b00ff82c0c26ba8ee7", "size": 3101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dsor_utils/test/test_math.cpp", "max_stars_repo_name": "dsor-isr/dsor_utils", "max_stars_repo_head_hexsha": "9e0c47701340b18da423a6badfb698673179f6bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dsor_utils/test/test_math.cpp", "max_issues_repo_name": "dsor-isr/dsor_utils", "max_issues_repo_head_hexsha": "9e0c47701340b18da423a6badfb698673179f6bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dsor_utils/test/test_math.cpp", "max_forks_repo_name": "dsor-isr/dsor_utils", "max_forks_repo_head_hexsha": "9e0c47701340b18da423a6badfb698673179f6bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9690721649, "max_line_length": 102, "alphanum_fraction": 0.5910996453, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.5422638378787114}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2006 - 2021 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 * Authors: Yan Li, Wolfgang Bangerth, Texas A&M University, 2006 \n */ \n\n\n\n// \u8fd9\u4e2a\u7a0b\u5e8f\u662f\u5bf9  step-20  \u7684\u6539\u7f16\uff0c\u5305\u62ec\u4e00\u4e9b\u6765\u81ea  step-12  \u7684DG\u65b9\u6cd5\u7684\u6280\u672f\u3002\u56e0\u6b64\uff0c\u8be5\u7a0b\u5e8f\u7684\u5f88\u5927\u4e00\u90e8\u5206\u4e0e  step-20  \u975e\u5e38\u76f8\u4f3c\uff0c\u6211\u4eec\u5c06\u4e0d\u518d\u5bf9\u8fd9\u4e9b\u90e8\u5206\u8fdb\u884c\u8bc4\u8bba\u3002\u53ea\u6709\u65b0\u7684\u4e1c\u897f\u624d\u4f1a\u88ab\u8be6\u7ec6\u8ba8\u8bba\u3002\n\n//  @sect3{Include files}  \n\n// \u8fd9\u4e9binclude\u6587\u4ef6\u4ee5\u524d\u90fd\u7528\u8fc7\u4e86\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/base/function.h> \n\n#include <deal.II/lac/block_vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/block_sparse_matrix.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_tools.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_renumbering.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_raviart_thomas.h> \n#include <deal.II/fe/fe_dgq.h> \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/fe_values.h> \n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n\n#include <iostream> \n#include <fstream> \n\n// \u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u5f20\u91cf\u503c\u7684\u7cfb\u6570\u3002\u7531\u4e8e\u5b83\u53ef\u80fd\u5177\u6709\u7a7a\u95f4\u4f9d\u8d56\u6027\uff0c\u6211\u4eec\u8ba4\u4e3a\u5b83\u662f\u4e00\u4e2a\u5f20\u91cf\u503c\u7684\u51fd\u6570\u3002\u4e0b\u9762\u7684include\u6587\u4ef6\u63d0\u4f9b\u4e86\u63d0\u4f9b\u8fd9\u79cd\u529f\u80fd\u7684 <code>TensorFunction</code> \u7c7b\u3002\n\n#include <deal.II/base/tensor_function.h> \n\n// \u6b64\u5916\uff0c\u6211\u4eec\u4f7f\u7528 <code>DiscreteTime</code> \u7c7b\u6765\u6267\u884c\u4e0e\u65f6\u95f4\u9012\u589e\u6709\u5173\u7684\u64cd\u4f5c\u3002\n\n#include <deal.II/base/discrete_time.h> \n\n// \u6700\u540e\u4e00\u6b65\u548c\u4ee5\u524d\u6240\u6709\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\n\nnamespace Step21 \n{ \n  using namespace dealii; \n// @sect3{The <code>TwoPhaseFlowProblem</code> class}  \n\n// \u8fd9\u662f\u8be5\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u3002\u5b83\u4e0e step-20 \u4e2d\u7684\u7c7b\u5f88\u63a5\u8fd1\uff0c\u4f46\u589e\u52a0\u4e86\u4e00\u4e9b\u529f\u80fd\u3002\n\n//  <ul>  \n// <li>  \n// <code>assemble_rhs_S</code> \u96c6\u5408\u4e86\u9971\u548c\u5ea6\u65b9\u7a0b\u7684\u53f3\u4fa7\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\uff0c\u8fd9\u4e0d\u80fd\u88ab\u96c6\u6210\u5230 <code>assemble_rhs</code> \u4e2d\uff0c\u56e0\u4e3a\u5b83\u53d6\u51b3\u4e8e\u5728\u65f6\u95f4\u6b65\u957f\u7684\u7b2c\u4e00\u90e8\u5206\u8ba1\u7b97\u7684\u901f\u5ea6\u3002\n\n//  <li>  \n// <code>get_maximal_velocity</code> \u7684\u4f5c\u7528\u6b63\u5982\u5176\u540d\u79f0\u6240\u793a\u3002\u8fd9\u4e2a\u51fd\u6570\u7528\u4e8e\u8ba1\u7b97\u65f6\u95f4\u6b65\u957f\u3002\n\n//  <li>  \n// <code>project_back_saturation</code>  \u5c06\u6240\u6709\u9971\u548c\u5ea6\u5c0f\u4e8e0\u7684\u81ea\u7531\u5ea6\u91cd\u7f6e\u4e3a0\uff0c\u6240\u6709\u9971\u548c\u5ea6\u5927\u4e8e1\u7684\u81ea\u7531\u5ea6\u91cd\u7f6e\u4e3a1\u3002   </ul>  \n\n// \u8be5\u7c7b\u7684\u5176\u4f59\u90e8\u5206\u5e94\u8be5\u662f\u975e\u5e38\u660e\u663e\u7684\u3002\u53d8\u91cf <code>viscosity</code> \u5b58\u50a8\u7c98\u5ea6 $\\mu$ \uff0c\u5b83\u8fdb\u5165\u4e86\u975e\u7ebf\u6027\u65b9\u7a0b\u4e2d\u7684\u51e0\u4e2a\u516c\u5f0f\u3002\u53d8\u91cf <code>time</code> \u8bb0\u5f55\u4e86\u6a21\u62df\u8fc7\u7a0b\u4e2d\u7684\u65f6\u95f4\u4fe1\u606f\u3002\n\n  template <int dim> \n  class TwoPhaseFlowProblem \n  { \n  public: \n    TwoPhaseFlowProblem(const unsigned int degree); \n    void run(); \n\n  private: \n    void   make_grid_and_dofs(); \n    void   assemble_system(); \n    void   assemble_rhs_S(); \n    double get_maximal_velocity() const; \n    void   solve(); \n    void   project_back_saturation(); \n    void   output_results() const; \n\n    const unsigned int degree; \n\n    Triangulation<dim> triangulation; \n    FESystem<dim>      fe; \n    DoFHandler<dim>    dof_handler; \n\n    BlockSparsityPattern      sparsity_pattern; \n    BlockSparseMatrix<double> system_matrix; \n\n    const unsigned int n_refinement_steps; \n\n    DiscreteTime time; \n    double       viscosity; \n\n    BlockVector<double> solution; \n    BlockVector<double> old_solution; \n    BlockVector<double> system_rhs; \n  }; \n// @sect3{Equation data}  \n// @sect4{Pressure right hand side}  \n\n// \u76ee\u524d\uff0c\u538b\u529b\u65b9\u7a0b\u7684\u53f3\u4fa7\u4ec5\u4ec5\u662f\u96f6\u51fd\u6570\u3002\u4f46\u662f\uff0c\u5982\u679c\u9700\u8981\u7684\u8bdd\uff0c\u7a0b\u5e8f\u7684\u5176\u4f59\u90e8\u5206\u5b8c\u5168\u53ef\u4ee5\u5904\u7406\u5176\u4ed6\u7684\u4e1c\u897f\u3002\n\n  template <int dim> \n  class PressureRightHandSide : public Function<dim> \n  { \n  public: \n    PressureRightHandSide() \n      : Function<dim>(1) \n    {} \n\n    virtual double value(const Point<dim> & /*p*/, \n                         const unsigned int /*component*/ = 0) const override \n    { \n      return 0; \n    } \n  }; \n\n//  @sect4{Pressure boundary values}  \n\n// \u63a5\u4e0b\u6765\u662f\u538b\u529b\u8fb9\u754c\u503c\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\uff0c\u6211\u4eec\u9009\u62e9\u4e00\u4e2a\u7ebf\u6027\u538b\u529b\u573a\u3002\n\n  template <int dim> \n  class PressureBoundaryValues : public Function<dim> \n  { \n  public: \n    PressureBoundaryValues() \n      : Function<dim>(1) \n    {} \n\n    virtual double value(const Point<dim> &p, \n                         const unsigned int /*component*/ = 0) const override \n    { \n      return 1 - p[0]; \n    } \n  }; \n\n//  @sect4{Saturation boundary values}  \n\n// \u7136\u540e\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u8fb9\u754c\u7684\u6d41\u5165\u90e8\u5206\u7684\u8fb9\u754c\u503c\u3002\u67d0\u7269\u662f\u5426\u4e3a\u6d41\u5165\u90e8\u5206\u7684\u95ee\u9898\u662f\u5728\u7ec4\u88c5\u53f3\u624b\u8fb9\u65f6\u51b3\u5b9a\u7684\uff0c\u6211\u4eec\u53ea\u9700\u8981\u63d0\u4f9b\u8fb9\u754c\u503c\u7684\u529f\u80fd\u63cf\u8ff0\u3002\u8fd9\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\u3002\n\n  template <int dim> \n  class SaturationBoundaryValues : public Function<dim> \n  { \n  public: \n    SaturationBoundaryValues() \n      : Function<dim>(1) \n    {} \n\n    virtual double value(const Point<dim> &p, \n                         const unsigned int /*component*/ = 0) const override \n    { \n      if (p[0] == 0) \n        return 1; \n      else \n        return 0; \n    } \n  }; \n\n//  @sect4{Initial data}  \n\n// \u6700\u540e\uff0c\u6211\u4eec\u9700\u8981\u521d\u59cb\u6570\u636e\u3002\u5b9e\u9645\u4e0a\uff0c\u6211\u4eec\u53ea\u9700\u8981\u9971\u548c\u5ea6\u7684\u521d\u59cb\u6570\u636e\uff0c\u4f46\u6211\u4eec\u5f88\u61d2\uff0c\u6240\u4ee5\u4ee5\u540e\u5728\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e4b\u524d\uff0c\u6211\u4eec\u4f1a\u7b80\u5355\u5730\u4ece\u4e00\u4e2a\u5305\u542b\u6240\u6709\u77e2\u91cf\u5206\u91cf\u7684\u51fd\u6570\u4e2d\u63d2\u503c\u51fa\u524d\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7684\u6574\u4e2a\u89e3\u51b3\u65b9\u6848\u3002\n//\u56e0\u6b64\uff0c\n//\u6211\u4eec\u7b80\u5355\u5730\u521b\u5efa\u4e00\u4e2a\u6240\u6709\u5206\u91cf\u90fd\u8fd4\u56de0\u7684\u51fd\u6570\u3002\u6211\u4eec\u901a\u8fc7\u7b80\u5355\u5730\u5c06\u6bcf\u4e2a\u51fd\u6570\u8f6c\u53d1\u5230 Functions::ZeroFunction \u7c7b\u6765\u505a\u5230\u8fd9\u4e00\u70b9\u3002\u4e3a\u4ec0\u4e48\u4e0d\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u6211\u4eec\u76ee\u524d\u4f7f\u7528 <code>InitialValues</code> \u7c7b\u7684\u5730\u65b9\u7acb\u5373\u4f7f\u7528\u5462\uff1f\u56e0\u4e3a\u8fd9\u6837\uff0c\u4ee5\u540e\u518d\u56de\u53bb\u9009\u62e9\u4e0d\u540c\u7684\u51fd\u6570\u6765\u505a\u521d\u59cb\u503c\u5c31\u66f4\u7b80\u5355\u4e86\u3002\n\n  template <int dim> \n  class InitialValues : public Function<dim> \n  { \n  public: \n    InitialValues() \n      : Function<dim>(dim + 2) \n    {} \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override \n    { \n      return Functions::ZeroFunction<dim>(dim + 2).value(p, component); \n    } \n\n    virtual void vector_value(const Point<dim> &p, \n                              Vector<double> &  values) const override \n    { \n      Functions::ZeroFunction<dim>(dim + 2).vector_value(p, values); \n    } \n  }; \n\n//  @sect3{The inverse permeability tensor}  \n\n// \u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u5ba3\u5e03\u7684\uff0c\u6211\u4eec\u5b9e\u73b0\u4e86\u4e24\u4e2a\u4e0d\u540c\u7684\u6e17\u900f\u7387\u5f20\u91cf\u573a\u3002\u6211\u4eec\u628a\u5b83\u4eec\u5404\u81ea\u653e\u5165\u4e00\u4e2a\u547d\u540d\u7a7a\u95f4\uff0c\u8fd9\u6837\u4ee5\u540e\u5c31\u53ef\u4ee5\u5f88\u5bb9\u6613\u5730\u5728\u4ee3\u7801\u4e2d\u7528\u53e6\u4e00\u4e2a\u6765\u4ee3\u66ff\u4e00\u4e2a\u3002\n\n//  @sect4{Single curving crack permeability}  \n\n// \u6e17\u900f\u7387\u7684\u7b2c\u4e00\u4e2a\u51fd\u6570\u662f\u6a21\u62df\u5355\u4e2a\u5f2f\u66f2\u88c2\u7f1d\u7684\u51fd\u6570\u3002\u5b83\u5728 step-20 \u7684\u7ed3\u5c3e\u5df2\u7ecf\u4f7f\u7528\u8fc7\u4e86\uff0c\u5b83\u7684\u51fd\u6570\u5f62\u5f0f\u5728\u672c\u6559\u7a0b\u7a0b\u5e8f\u7684\u4ecb\u7ecd\u4e2d\u7ed9\u51fa\u3002\u548c\u4ee5\u524d\u7684\u4e00\u4e9b\u7a0b\u5e8f\u4e00\u6837\uff0c\u6211\u4eec\u5fc5\u987b\u58f0\u660eKInverse\u7c7b\u7684\u4e00\u4e2a\uff08\u4f3c\u4e4e\u662f\u4e0d\u5fc5\u8981\u7684\uff09\u9ed8\u8ba4\u6784\u9020\u51fd\u6570\uff0c\u4ee5\u907f\u514d\u67d0\u4e9b\u7f16\u8bd1\u5668\u7684\u8b66\u544a\u3002\n\n  namespace SingleCurvingCrack \n  { \n    template <int dim> \n    class KInverse : public TensorFunction<2, dim> \n    { \n    public: \n      KInverse() \n        : TensorFunction<2, dim>() \n      {} \n\n      virtual void \n      value_list(const std::vector<Point<dim>> &points, \n                 std::vector<Tensor<2, dim>> &  values) const override \n      { \n        Assert(points.size() == values.size(), \n               ExcDimensionMismatch(points.size(), values.size())); \n\n        for (unsigned int p = 0; p < points.size(); ++p) \n          { \n            values[p].clear(); \n\n            const double distance_to_flowline = \n              std::fabs(points[p][1] - 0.5 - 0.1 * std::sin(10 * points[p][0])); \n\n            const double permeability = \n              std::max(std::exp(-(distance_to_flowline * distance_to_flowline) / \n                                (0.1 * 0.1)), \n                       0.01); \n\n            for (unsigned int d = 0; d < dim; ++d) \n              values[p][d][d] = 1. / permeability; \n          } \n      } \n    }; \n  } // namespace SingleCurvingCrack \n// @sect4{Random medium permeability}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u7684\u4f5c\u7528\u4e0e\u4ecb\u7ecd\u4e2d\u516c\u5e03\u7684\u4e00\u6837\uff0c\u5373\u5728\u968f\u673a\u7684\u5730\u65b9\u521b\u5efa\u4e00\u4e2a\u53e0\u52a0\u7684\u6307\u6570\u3002\u5bf9\u4e8e\u8fd9\u4e2a\u7c7b\uff0c\u6709\u4e00\u4ef6\u4e8b\u503c\u5f97\u8003\u8651\u3002\u8fd9\u4e2a\u95ee\u9898\u7684\u6838\u5fc3\u662f\uff0c\u8fd9\u4e2a\u7c7b\u4f7f\u7528\u968f\u673a\u51fd\u6570\u521b\u5efa\u6307\u6570\u7684\u4e2d\u5fc3\u3002\u5982\u679c\u6211\u4eec\u56e0\u6b64\u5728\u6bcf\u6b21\u521b\u5efa\u672c\u7c7b\u578b\u7684\u5bf9\u8c61\u65f6\u90fd\u521b\u5efa\u4e2d\u5fc3\uff0c\u6211\u4eec\u6bcf\u6b21\u90fd\u4f1a\u5f97\u5230\u4e00\u4e2a\u4e0d\u540c\u7684\u4e2d\u5fc3\u5217\u8868\u3002\u8fd9\u4e0d\u662f\u6211\u4eec\u5bf9\u8fd9\u79cd\u7c7b\u578b\u7684\u7c7b\u7684\u671f\u671b\uff1a\u5b83\u4eec\u5e94\u8be5\u53ef\u9760\u5730\u8868\u793a\u540c\u4e00\u4e2a\u51fd\u6570\u3002\n\n// \u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u7684\u65b9\u6cd5\u662f\u4f7f\u4e2d\u5fc3\u5217\u8868\u6210\u4e3a\u8fd9\u4e2a\u7c7b\u7684\u9759\u6001\u6210\u5458\u53d8\u91cf\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5728\u6574\u4e2a\u7a0b\u5e8f\u4e2d\u53ea\u5b58\u5728\u4e00\u4e2a\u8fd9\u6837\u7684\u53d8\u91cf\uff0c\u800c\u4e0d\u662f\u4e3a\u8fd9\u4e2a\u7c7b\u578b\u7684\u6bcf\u4e2a\u5bf9\u8c61\u3002\u8fd9\u6b63\u662f\u6211\u4eec\u6240\u8981\u505a\u7684\u3002\n\n// \u7136\u800c\uff0c\u63a5\u4e0b\u6765\u7684\u95ee\u9898\u662f\uff0c\u6211\u4eec\u9700\u8981\u4e00\u79cd\u65b9\u6cd5\u6765\u521d\u59cb\u5316\u8fd9\u4e2a\u53d8\u91cf\u3002\u7531\u4e8e\u8fd9\u4e2a\u53d8\u91cf\u662f\u5728\u7a0b\u5e8f\u5f00\u59cb\u65f6\u521d\u59cb\u5316\u7684\uff0c\u6211\u4eec\u4e0d\u80fd\u4f7f\u7528\u666e\u901a\u7684\u6210\u5458\u51fd\u6570\u6765\u5b9e\u73b0\uff0c\u56e0\u4e3a\u5f53\u65f6\u8eab\u8fb9\u53ef\u80fd\u6ca1\u6709\u8fd9\u4e2a\u7c7b\u578b\u7684\u5bf9\u8c61\u3002\u56e0\u6b64C++\u6807\u51c6\u89c4\u5b9a\uff0c\u53ea\u6709\u975e\u6210\u5458\u51fd\u6570\u548c\u9759\u6001\u6210\u5458\u51fd\u6570\u53ef\u4ee5\u7528\u6765\u521d\u59cb\u5316\u9759\u6001\u53d8\u91cf\u3002\u6211\u4eec\u901a\u8fc7\u5b9a\u4e49\u4e00\u4e2a\u51fd\u6570 <code>get_centers</code> \u6765\u4f7f\u7528\u540e\u4e00\u79cd\u53ef\u80fd\u6027\uff0c\u8be5\u51fd\u6570\u5728\u8c03\u7528\u65f6\u8ba1\u7b97\u4e2d\u5fc3\u70b9\u7684\u5217\u8868\u3002\n\n// \u6ce8\u610f\uff0c\u8fd9\u4e2a\u7c7b\u57282D\u548c3D\u4e2d\u90fd\u80fd\u6b63\u5e38\u5de5\u4f5c\uff0c\u552f\u4e00\u7684\u533a\u522b\u662f\u6211\u4eec\u57283D\u4e2d\u4f7f\u7528\u4e86\u66f4\u591a\u7684\u70b9\uff1a\u901a\u8fc7\u5b9e\u9a8c\u6211\u4eec\u53d1\u73b0\uff0c\u6211\u4eec\u57283D\u4e2d\u6bd42D\u4e2d\u9700\u8981\u66f4\u591a\u7684\u6307\u6570\uff08\u6bd5\u7adf\u6211\u4eec\u6709\u66f4\u591a\u7684\u5730\u65b9\u9700\u8981\u8986\u76d6\uff0c\u5982\u679c\u6211\u4eec\u60f3\u4fdd\u6301\u4e2d\u5fc3\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u81f4\u76f8\u7b49\uff09\uff0c\u6240\u4ee5\u6211\u4eec\u57282D\u4e2d\u9009\u62e940\uff0c\u57283D\u4e2d\u9009\u62e9100\u3002\u5bf9\u4e8e\u4efb\u4f55\u5176\u4ed6\u7ef4\u5ea6\uff0c\u8be5\u51fd\u6570\u76ee\u524d\u4e0d\u77e5\u9053\u8be5\u600e\u4e48\u505a\uff0c\u6240\u4ee5\u53ea\u662f\u629b\u51fa\u4e00\u4e2a\u5f02\u5e38\uff0c\u8868\u660e\u8fd9\u4e00\u70b9\u3002\n\n  namespace RandomMedium \n  { \n    template <int dim> \n    class KInverse : public TensorFunction<2, dim> \n    { \n    public: \n      KInverse() \n        : TensorFunction<2, dim>() \n      {} \n\n      virtual void \n      value_list(const std::vector<Point<dim>> &points, \n                 std::vector<Tensor<2, dim>> &  values) const override \n      { \n        Assert(points.size() == values.size(), \n               ExcDimensionMismatch(points.size(), values.size())); \n\n        for (unsigned int p = 0; p < points.size(); ++p) \n          { \n            values[p].clear(); \n\n            double permeability = 0; \n            for (unsigned int i = 0; i < centers.size(); ++i) \n              permeability += std::exp(-(points[p] - centers[i]).norm_square() / \n                                       (0.05 * 0.05)); \n\n            const double normalized_permeability = \n              std::min(std::max(permeability, 0.01), 4.); \n\n            for (unsigned int d = 0; d < dim; ++d) \n              values[p][d][d] = 1. / normalized_permeability; \n          } \n      } \n\n    private: \n      static std::vector<Point<dim>> centers; \n\n      static std::vector<Point<dim>> get_centers() \n      { \n        const unsigned int N = \n          (dim == 2 ? 40 : (dim == 3 ? 100 : throw ExcNotImplemented())); \n\n        std::vector<Point<dim>> centers_list(N); \n        for (unsigned int i = 0; i < N; ++i) \n          for (unsigned int d = 0; d < dim; ++d) \n            centers_list[i][d] = static_cast<double>(rand()) / RAND_MAX; \n\n        return centers_list; \n      } \n    }; \n\n    template <int dim> \n    std::vector<Point<dim>> \n      KInverse<dim>::centers = KInverse<dim>::get_centers(); \n  } // namespace RandomMedium \n\n//  @sect3{The inverse mobility and saturation functions}  \n\n// \u8fd8\u6709\u4e24\u4e2a\u6570\u636e\u6211\u4eec\u9700\u8981\u63cf\u8ff0\uff0c\u5373\u53cd\u6d41\u52a8\u6027\u51fd\u6570\u548c\u9971\u548c\u5ea6\u66f2\u7ebf\u3002\u5b83\u4eec\u7684\u5f62\u5f0f\u4e5f\u5728\u4ecb\u7ecd\u4e2d\u7ed9\u51fa\u3002\n\n  double mobility_inverse(const double S, const double viscosity) \n  { \n    return 1.0 / (1.0 / viscosity * S * S + (1 - S) * (1 - S)); \n  } \n\n  double fractional_flow(const double S, const double viscosity) \n  { \n    return S * S / (S * S + viscosity * (1 - S) * (1 - S)); \n  } \n\n//  @sect3{Linear solvers and preconditioners}  \n\n// \u6211\u4eec\u4f7f\u7528\u7684\u7ebf\u6027\u6c42\u89e3\u5668\u4e5f\u5b8c\u5168\u7c7b\u4f3c\u4e8e  step-20  \u4e2d\u4f7f\u7528\u7684\u3002\u56e0\u6b64\uff0c\u4e0b\u9762\u7684\u7c7b\u662f\u9010\u5b57\u9010\u53e5\u4ece\u90a3\u91cc\u590d\u5236\u8fc7\u6765\u7684\u3002\u8bf7\u6ce8\u610f\uff0c\u8fd9\u91cc\u7684\u7c7b\u4e0d\u4ec5\u662f\u4ece step-20 \u4e2d\u590d\u5236\u7684\uff0c\u800c\u4e14\u5728deal.II\u4e2d\u4e5f\u6709\u91cd\u590d\u7684\u7c7b\u3002\u5728\u8fd9\u4e2a\u4f8b\u5b50\u7684\u672a\u6765\u7248\u672c\u4e2d\uff0c\u5b83\u4eec\u5e94\u8be5\u88ab\u4e00\u4e2a\u6709\u6548\u7684\u65b9\u6cd5\u6240\u53d6\u4ee3\uff0c\u4e0d\u8fc7\u3002\u6709\u4e00\u4e2a\u53d8\u5316\uff1a\u5982\u679c\u7ebf\u6027\u7cfb\u7edf\u7684\u5c3a\u5bf8\u5f88\u5c0f\uff0c\u5373\u5f53\u7f51\u683c\u5f88\u7c97\u65f6\uff0c\u90a3\u4e48\u5728 <code>src.size()</code> \u51fd\u6570\u4e2d\u7684\u6c42\u89e3\u5668\u6536\u655b\u4e4b\u524d\uff0c\u8bbe\u7f6e <code>vmult()</code> CG\u8fed\u4ee3\u7684\u6700\u5927\u503c\u6709\u65f6\u662f\u4e0d\u591f\u7684\u3002(\u5f53\u7136\uff0c\u8fd9\u662f\u6570\u503c\u53d6\u820d\u7684\u7ed3\u679c\uff0c\u56e0\u4e3a\u6211\u4eec\u77e5\u9053\u5728\u7eb8\u9762\u4e0a\uff0cCG\u65b9\u6cd5\u6700\u591a\u5728 <code>src.size()</code> \u6b65\u5185\u6536\u655b)\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5c06\u6700\u5927\u7684\u8fed\u4ee3\u6b21\u6570\u8bbe\u5b9a\u4e3a\u7b49\u4e8e\u7ebf\u6027\u7cfb\u7edf\u7684\u6700\u5927\u89c4\u6a21\u548c200\u3002\n\n  template <class MatrixType> \n  class InverseMatrix : public Subscriptor \n  { \n  public: \n    InverseMatrix(const MatrixType &m) \n      : matrix(&m) \n    {} \n\n    void vmult(Vector<double> &dst, const Vector<double> &src) const \n    { \n      SolverControl solver_control(std::max<unsigned int>(src.size(), 200), \n                                   1e-8 * src.l2_norm()); \n      SolverCG<Vector<double>> cg(solver_control); \n\n      dst = 0; \n\n      cg.solve(*matrix, dst, src, PreconditionIdentity()); \n    } \n\n  private: \n    const SmartPointer<const MatrixType> matrix; \n  }; \n\n  class SchurComplement : public Subscriptor \n  { \n  public: \n    SchurComplement(const BlockSparseMatrix<double> &          A, \n                    const InverseMatrix<SparseMatrix<double>> &Minv) \n      : system_matrix(&A) \n      , m_inverse(&Minv) \n      , tmp1(A.block(0, 0).m()) \n      , tmp2(A.block(0, 0).m()) \n    {} \n\n    void vmult(Vector<double> &dst, const Vector<double> &src) const \n    { \n      system_matrix->block(0, 1).vmult(tmp1, src); \n      m_inverse->vmult(tmp2, tmp1); \n      system_matrix->block(1, 0).vmult(dst, tmp2); \n    } \n\n  private: \n    const SmartPointer<const BlockSparseMatrix<double>>           system_matrix; \n    const SmartPointer<const InverseMatrix<SparseMatrix<double>>> m_inverse; \n\n    mutable Vector<double> tmp1, tmp2; \n  }; \n\n  class ApproximateSchurComplement : public Subscriptor \n  { \n  public: \n    ApproximateSchurComplement(const BlockSparseMatrix<double> &A) \n      : system_matrix(&A) \n      , tmp1(A.block(0, 0).m()) \n      , tmp2(A.block(0, 0).m()) \n    {} \n\n    void vmult(Vector<double> &dst, const Vector<double> &src) const \n    { \n      system_matrix->block(0, 1).vmult(tmp1, src); \n      system_matrix->block(0, 0).precondition_Jacobi(tmp2, tmp1); \n      system_matrix->block(1, 0).vmult(dst, tmp2); \n    } \n\n  private: \n    const SmartPointer<const BlockSparseMatrix<double>> system_matrix; \n\n    mutable Vector<double> tmp1, tmp2; \n  }; \n\n//  @sect3{<code>TwoPhaseFlowProblem</code> class implementation}  \n\n// \u73b0\u5728\u662f\u4e3b\u7c7b\u7684\u5b9e\u73b0\u3002\u5b83\u7684\u5927\u90e8\u5206\u5185\u5bb9\u5b9e\u9645\u4e0a\u662f\u4ece  step-20  \u4e2d\u590d\u5236\u8fc7\u6765\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u4f1a\u5bf9\u5b83\u8fdb\u884c\u8be6\u7ec6\u7684\u8bc4\u8bba\u3002\u4f60\u5e94\u8be5\u8bd5\u7740\u5148\u719f\u6089\u4e00\u4e0b\u90a3\u4e2a\u7a0b\u5e8f\uff0c\u7136\u540e\u8fd9\u91cc\u53d1\u751f\u7684\u5927\u90e8\u5206\u4e8b\u60c5\u5c31\u5e94\u8be5\u5f88\u6e05\u695a\u4e86\u3002\n\n//  @sect4{TwoPhaseFlowProblem::TwoPhaseFlowProblem}  \n\n// \u9996\u5148\u662f\u6784\u9020\u51fd\u6570\u3002\u6211\u4eec\u4f7f\u7528 $RT_k \\times DQ_k \\times DQ_k$ \u7a7a\u95f4\u3002\u5bf9\u4e8e\u521d\u59cb\u5316DiscreteTime\u5bf9\u8c61\uff0c\u6211\u4eec\u4e0d\u5728\u6784\u9020\u51fd\u6570\u4e2d\u8bbe\u7f6e\u65f6\u95f4\u6b65\u957f\uff0c\u56e0\u4e3a\u6211\u4eec\u8fd8\u6ca1\u6709\u5b83\u7684\u503c\u3002\u65f6\u95f4\u6b65\u957f\u6700\u521d\u88ab\u8bbe\u7f6e\u4e3a\u96f6\uff0c\u4f46\u5728\u9700\u8981\u589e\u91cf\u65f6\u95f4\u4e4b\u524d\uff0c\u5b83\u5c06\u88ab\u8ba1\u7b97\u51fa\u6765\uff0c\u6b63\u5982\u4ecb\u7ecd\u7684\u4e00\u4e2a\u5c0f\u8282\u4e2d\u6240\u63cf\u8ff0\u7684\u3002\u65f6\u95f4\u5bf9\u8c61\u5728\u5185\u90e8\u963b\u6b62\u81ea\u5df1\u5728 $dt = 0$ \u65f6\u88ab\u9012\u589e\uff0c\u8feb\u4f7f\u6211\u4eec\u5728\u63a8\u8fdb\u65f6\u95f4\u4e4b\u524d\u4e3a $dt$ \u8bbe\u7f6e\u4e00\u4e2a\u975e\u96f6\u7684\u671f\u671b\u5927\u5c0f\u3002\n\n  template <int dim> \n  TwoPhaseFlowProblem<dim>::TwoPhaseFlowProblem(const unsigned int degree) \n    : degree(degree) \n    , fe(FE_RaviartThomas<dim>(degree), \n         1, \n         FE_DGQ<dim>(degree), \n         1, \n         FE_DGQ<dim>(degree), \n         1) \n    , dof_handler(triangulation) \n    , n_refinement_steps(5) \n    , time(/*start time*/ 0., /*end time*/ 1.) \n    , viscosity(0.2) \n  {} \n\n//  @sect4{TwoPhaseFlowProblem::make_grid_and_dofs}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u4ece\u4f17\u6240\u5468\u77e5\u7684\u51fd\u6570\u8c03\u7528\u5f00\u59cb\uff0c\u521b\u5efa\u548c\u7ec6\u5316\u4e00\u4e2a\u7f51\u683c\uff0c\u7136\u540e\u5c06\u81ea\u7531\u5ea6\u4e0e\u4e4b\u5173\u8054\u3002\u5b83\u6240\u505a\u7684\u4e8b\u60c5\u4e0e step-20 \u4e2d\u7684\u76f8\u540c\uff0c\u53ea\u662f\u73b0\u5728\u662f\u4e09\u4e2a\u7ec4\u4ef6\u800c\u4e0d\u662f\u4e24\u4e2a\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::make_grid_and_dofs() \n  { \n    GridGenerator::hyper_cube(triangulation, 0, 1); \n    triangulation.refine_global(n_refinement_steps); \n\n    dof_handler.distribute_dofs(fe); \n    DoFRenumbering::component_wise(dof_handler); \n\n    const std::vector<types::global_dof_index> dofs_per_component = \n      DoFTools::count_dofs_per_fe_component(dof_handler); \n    const unsigned int n_u = dofs_per_component[0], \n                       n_p = dofs_per_component[dim], \n                       n_s = dofs_per_component[dim + 1]; \n\n    std::cout << \"Number of active cells: \" << triangulation.n_active_cells() \n              << std::endl \n              << \"Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << \" (\" << n_u << '+' << n_p << '+' << n_s << ')' << std::endl \n              << std::endl; \n\n    const unsigned int n_couplings = dof_handler.max_couplings_between_dofs(); \n\n    sparsity_pattern.reinit(3, 3); \n    sparsity_pattern.block(0, 0).reinit(n_u, n_u, n_couplings); \n    sparsity_pattern.block(1, 0).reinit(n_p, n_u, n_couplings); \n    sparsity_pattern.block(2, 0).reinit(n_s, n_u, n_couplings); \n    sparsity_pattern.block(0, 1).reinit(n_u, n_p, n_couplings); \n    sparsity_pattern.block(1, 1).reinit(n_p, n_p, n_couplings); \n    sparsity_pattern.block(2, 1).reinit(n_s, n_p, n_couplings); \n    sparsity_pattern.block(0, 2).reinit(n_u, n_s, n_couplings); \n    sparsity_pattern.block(1, 2).reinit(n_p, n_s, n_couplings); \n    sparsity_pattern.block(2, 2).reinit(n_s, n_s, n_couplings); \n\n    sparsity_pattern.collect_sizes(); \n\n    DoFTools::make_sparsity_pattern(dof_handler, sparsity_pattern); \n    sparsity_pattern.compress(); \n\n    system_matrix.reinit(sparsity_pattern); \n\n    solution.reinit(3); \n    solution.block(0).reinit(n_u); \n    solution.block(1).reinit(n_p); \n    solution.block(2).reinit(n_s); \n    solution.collect_sizes(); \n\n    old_solution.reinit(3); \n    old_solution.block(0).reinit(n_u); \n    old_solution.block(1).reinit(n_p); \n    old_solution.block(2).reinit(n_s); \n    old_solution.collect_sizes(); \n\n    system_rhs.reinit(3); \n    system_rhs.block(0).reinit(n_u); \n    system_rhs.block(1).reinit(n_p); \n    system_rhs.block(2).reinit(n_s); \n    system_rhs.collect_sizes(); \n  } \n// @sect4{TwoPhaseFlowProblem::assemble_system}  \n\n// \u8fd9\u662f\u7ec4\u88c5\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\uff0c\u6216\u8005\u81f3\u5c11\u662f\u9664\u4e86(1,3)\u5757\u4e4b\u5916\u7684\u6240\u6709\u4e1c\u897f\uff0c\u5b83\u53d6\u51b3\u4e8e\u5728\u8fd9\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u8ba1\u7b97\u7684\u4ecd\u7136\u672a\u77e5\u7684\u901f\u5ea6\uff08\u6211\u4eec\u5728 <code>assemble_rhs_S</code> \u4e2d\u5904\u7406\u8fd9\u4e2a\u95ee\u9898\uff09\u3002\u5b83\u7684\u5927\u90e8\u5206\u5185\u5bb9\u4e0e step-20 \u4e00\u6837\uff0c\u4f46\u8fd9\u6b21\u6211\u4eec\u5fc5\u987b\u5904\u7406\u4e00\u4e9b\u975e\u7ebf\u6027\u7684\u95ee\u9898\u3002 \u7136\u800c\uff0c\u8be5\u51fd\u6570\u7684\u9876\u90e8\u4e0e\u5f80\u5e38\u4e00\u6837\uff08\u6ce8\u610f\u6211\u4eec\u5728\u5f00\u59cb\u65f6\u5c06\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u8bbe\u7f6e\u4e3a\u96f6&mdash; \u5bf9\u4e8e\u9759\u6b62\u95ee\u9898\u6211\u4eec\u4e0d\u5fc5\u8fd9\u6837\u505a\uff0c\u56e0\u4e3a\u5728\u90a3\u91cc\u6211\u4eec\u53ea\u4f7f\u7528\u4e00\u6b21\u77e9\u9635\u5bf9\u8c61\uff0c\u800c\u4e14\u5728\u5f00\u59cb\u65f6\u5b83\u662f\u7a7a\u7684\uff09\u3002\n\n// \u6ce8\u610f\uff0c\u5728\u76ee\u524d\u7684\u5f62\u5f0f\u4e0b\uff0c\u8be5\u51fd\u6570\u4f7f\u7528 RandomMedium::KInverse \u7c7b\u4e2d\u5b9e\u73b0\u7684\u6e17\u900f\u7387\u3002\u5207\u6362\u5230\u5355\u66f2\u88c2\u7f1d\u6e17\u900f\u7387\u51fd\u6570\u5c31\u50cf\u6539\u53d8\u547d\u540d\u7a7a\u95f4\u540d\u79f0\u4e00\u6837\u7b80\u5355\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::assemble_system() \n  { \n    system_matrix = 0; \n    system_rhs    = 0; \n\n    QGauss<dim>     quadrature_formula(degree + 2); \n    QGauss<dim - 1> face_quadrature_formula(degree + 2); \n\n    FEValues<dim>     fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | update_JxW_values); \n    FEFaceValues<dim> fe_face_values(fe, \n                                     face_quadrature_formula, \n                                     update_values | update_normal_vectors | \n                                       update_quadrature_points | \n                                       update_JxW_values); \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n\n    const unsigned int n_q_points      = quadrature_formula.size(); \n    const unsigned int n_face_q_points = face_quadrature_formula.size(); \n\n    FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<double>     local_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    const PressureRightHandSide<dim>  pressure_right_hand_side; \n    const PressureBoundaryValues<dim> pressure_boundary_values; \n    const RandomMedium::KInverse<dim> k_inverse; \n\n    std::vector<double>         pressure_rhs_values(n_q_points); \n    std::vector<double>         boundary_values(n_face_q_points); \n    std::vector<Tensor<2, dim>> k_inverse_values(n_q_points); \n\n    std::vector<Vector<double>>              old_solution_values(n_q_points, \n                                                                 Vector<double>(dim + 2)); \n    std::vector<std::vector<Tensor<1, dim>>> old_solution_grads( \n      n_q_points, std::vector<Tensor<1, dim>>(dim + 2)); \n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure(dim); \n    const FEValuesExtractors::Scalar saturation(dim + 1); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        fe_values.reinit(cell); \n        local_matrix = 0; \n        local_rhs    = 0; \n\n// \u8fd9\u91cc\u662f\u7b2c\u4e00\u4e2a\u91cd\u8981\u7684\u533a\u522b\u3002\u6211\u4eec\u5fc5\u987b\u5728\u6b63\u4ea4\u70b9\u4e0a\u83b7\u5f97\u524d\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7684\u9971\u548c\u51fd\u6570\u503c\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528 FEValues::get_function_values \uff08\u4e4b\u524d\u5df2\u7ecf\u5728 step-9 \u3001 step-14 \u548c step-15 \u4e2d\u4f7f\u7528\uff09\uff0c\u8fd9\u4e2a\u51fd\u6570\u63a5\u6536\u4e00\u4e2a\u89e3\u5411\u91cf\u5e76\u8fd4\u56de\u5f53\u524d\u5355\u5143\u7684\u6b63\u4ea4\u70b9\u7684\u51fd\u6570\u503c\u5217\u8868\u3002\u4e8b\u5b9e\u4e0a\uff0c\u5b83\u8fd4\u56de\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u7684\u5b8c\u6574\u77e2\u91cf\u503c\u89e3\uff0c\u5373\u4e0d\u4ec5\u662f\u9971\u548c\u5ea6\uff0c\u8fd8\u6709\u901f\u5ea6\u548c\u538b\u529b\u3002\n\n        fe_values.get_function_values(old_solution, old_solution_values); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u8fd8\u5fc5\u987b\u5f97\u5230\u538b\u529b\u7684\u53f3\u624b\u8fb9\u548c\u53cd\u6e17\u900f\u6027\u5f20\u91cf\u5728\u6b63\u4ea4\u70b9\u7684\u6570\u503c\u3002\n\n        pressure_right_hand_side.value_list(fe_values.get_quadrature_points(), \n                                            pressure_rhs_values); \n        k_inverse.value_list(fe_values.get_quadrature_points(), \n                             k_inverse_values); \n\n// \u6709\u4e86\u8fd9\u4e9b\uff0c\u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u5728\u8fd9\u4e2a\u5355\u5143\u683c\u4e0a\u7684\u6240\u6709\u6b63\u4ea4\u70b9\u548c\u5f62\u72b6\u51fd\u6570\u4e0a\u8fdb\u884c\u5faa\u73af\uff0c\u5e76\u5c06\u6211\u4eec\u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\u5904\u7406\u7684\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u90a3\u4e9b\u90e8\u5206\u7ec4\u5408\u8d77\u6765\u3002\u8003\u8651\u5230\u5f15\u8a00\u4e2d\u6240\u8ff0\u7684\u53cc\u7ebf\u6027\u5f62\u5f0f\u7684\u660e\u786e\u5f62\u5f0f\uff0c\u8d21\u732e\u4e2d\u7684\u5404\u4e2a\u6761\u6b3e\u5e94\u8be5\u662f\u4e0d\u8a00\u81ea\u660e\u7684\u3002\n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            { \n              const double old_s = old_solution_values[q](dim + 1); \n\n              const Tensor<1, dim> phi_i_u = fe_values[velocities].value(i, q); \n              const double div_phi_i_u = fe_values[velocities].divergence(i, q); \n              const double phi_i_p     = fe_values[pressure].value(i, q); \n              const double phi_i_s     = fe_values[saturation].value(i, q); \n\n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                { \n                  const Tensor<1, dim> phi_j_u = \n                    fe_values[velocities].value(j, q); \n                  const double div_phi_j_u = \n                    fe_values[velocities].divergence(j, q); \n                  const double phi_j_p = fe_values[pressure].value(j, q); \n                  const double phi_j_s = fe_values[saturation].value(j, q); \n\n                  local_matrix(i, j) += \n                    (phi_i_u * k_inverse_values[q] * \n                       mobility_inverse(old_s, viscosity) * phi_j_u - \n                     div_phi_i_u * phi_j_p - phi_i_p * div_phi_j_u + \n                     phi_i_s * phi_j_s) * \n                    fe_values.JxW(q); \n                } \n\n              local_rhs(i) += \n                (-phi_i_p * pressure_rhs_values[q]) * fe_values.JxW(q); \n            } \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u8fd8\u5fc5\u987b\u5904\u7406\u538b\u529b\u8fb9\u754c\u503c\u3002\u8fd9\u4e00\u70b9\uff0c\u8fd8\u662f\u548c step-20 \u4e2d\u4e00\u6837\u3002\n\n        for (const auto &face : cell->face_iterators()) \n          if (face->at_boundary()) \n            { \n              fe_face_values.reinit(cell, face); \n\n              pressure_boundary_values.value_list( \n                fe_face_values.get_quadrature_points(), boundary_values); \n\n              for (unsigned int q = 0; q < n_face_q_points; ++q) \n                for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                  { \n                    const Tensor<1, dim> phi_i_u = \n                      fe_face_values[velocities].value(i, q); \n\n                    local_rhs(i) += \n                      -(phi_i_u * fe_face_values.normal_vector(q) * \n                        boundary_values[q] * fe_face_values.JxW(q)); \n                  } \n            } \n\n// \u5728\u6240\u6709\u5355\u5143\u7684\u5faa\u73af\u4e2d\uff0c\u6700\u540e\u4e00\u6b65\u662f\u5c06\u5c40\u90e8\u8d21\u732e\u8f6c\u79fb\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u4fa7\u5411\u91cf\u4e2d\u3002\n\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            system_matrix.add(local_dof_indices[i], \n                              local_dof_indices[j], \n                              local_matrix(i, j)); \n\n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          system_rhs(local_dof_indices[i]) += local_rhs(i); \n      } \n  } \n\n// \u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u7ec4\u88c5\u5c31\u8fd9\u4e48\u591a\u4e86\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u63d2\u503c\u548c\u5e94\u7528\u8fb9\u754c\u503c\uff0c\u56e0\u4e3a\u5b83\u4eec\u90fd\u5df2\u7ecf\u5728\u5f31\u5f0f\u4e2d\u88ab\u5904\u7406\u8fc7\u4e86\u3002\n\n//  @sect4{TwoPhaseFlowProblem::assemble_rhs_S}  \n\n// \u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\uff0c\u6211\u4eec\u53ea\u6709\u5728\u8ba1\u7b97\u51fa\u901f\u5ea6\u540e\u624d\u80fd\u8bc4\u4f30\u9971\u548c\u65b9\u7a0b\u7684\u53f3\u8fb9\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u6709\u8fd9\u4e2a\u5355\u72ec\u7684\u51fd\u6570\u6765\u5b9e\u73b0\u8fd9\u4e2a\u76ee\u7684\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::assemble_rhs_S() \n  { \n    QGauss<dim>       quadrature_formula(degree + 2); \n    QGauss<dim - 1>   face_quadrature_formula(degree + 2); \n    FEValues<dim>     fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | update_JxW_values); \n    FEFaceValues<dim> fe_face_values(fe, \n                                     face_quadrature_formula, \n                                     update_values | update_normal_vectors | \n                                       update_quadrature_points | \n                                       update_JxW_values); \n    FEFaceValues<dim> fe_face_values_neighbor(fe, \n                                              face_quadrature_formula, \n                                              update_values); \n\n    const unsigned int dofs_per_cell   = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points      = quadrature_formula.size(); \n    const unsigned int n_face_q_points = face_quadrature_formula.size(); \n\n    Vector<double> local_rhs(dofs_per_cell); \n\n    std::vector<Vector<double>> old_solution_values(n_q_points, \n                                                    Vector<double>(dim + 2)); \n    std::vector<Vector<double>> old_solution_values_face(n_face_q_points, \n                                                         Vector<double>(dim + \n                                                                        2)); \n    std::vector<Vector<double>> old_solution_values_face_neighbor( \n      n_face_q_points, Vector<double>(dim + 2)); \n    std::vector<Vector<double>> present_solution_values(n_q_points, \n                                                        Vector<double>(dim + \n                                                                       2)); \n    std::vector<Vector<double>> present_solution_values_face( \n      n_face_q_points, Vector<double>(dim + 2)); \n\n    std::vector<double>                  neighbor_saturation(n_face_q_points); \n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    SaturationBoundaryValues<dim> saturation_boundary_values; \n\n    const FEValuesExtractors::Scalar saturation(dim + 1); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        local_rhs = 0; \n        fe_values.reinit(cell); \n\n        fe_values.get_function_values(old_solution, old_solution_values); \n        fe_values.get_function_values(solution, present_solution_values); \n\n// \u9996\u5148\u662f\u5355\u5143\u683c\u6761\u6b3e\u3002\u6309\u7167\u4ecb\u7ecd\u4e2d\u7684\u516c\u5f0f\uff0c\u8fd9\u4e9b\u662f  $(S^n,\\sigma)-(F(S^n) \\mathbf{v}^{n+1},\\nabla \\sigma)$  \uff0c\u5176\u4e2d  $\\sigma$  \u662f\u6d4b\u8bd5\u51fd\u6570\u7684\u9971\u548c\u6210\u5206\u3002\n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            { \n              const double   old_s = old_solution_values[q](dim + 1); \n              Tensor<1, dim> present_u; \n              for (unsigned int d = 0; d < dim; ++d) \n                present_u[d] = present_solution_values[q](d); \n\n              const double         phi_i_s = fe_values[saturation].value(i, q); \n              const Tensor<1, dim> grad_phi_i_s = \n                fe_values[saturation].gradient(i, q); \n\n              local_rhs(i) += \n                (time.get_next_step_size() * fractional_flow(old_s, viscosity) * \n                   present_u * grad_phi_i_s + \n                 old_s * phi_i_s) * \n                fe_values.JxW(q); \n            } \n\n// \u5176\u6b21\uff0c\u6211\u4eec\u5fc5\u987b\u5904\u7406\u9762\u7684\u8fb9\u754c\u4e0a\u7684\u901a\u91cf\u90e8\u5206\u3002\u8fd9\u5c31\u6709\u70b9\u9ebb\u70e6\u4e86\uff0c\u56e0\u4e3a\u6211\u4eec\u9996\u5148\u8981\u786e\u5b9a\u54ea\u4e9b\u662f\u7ec6\u80de\u8fb9\u754c\u7684\u6d41\u5165\u548c\u6d41\u51fa\u90e8\u5206\u3002\u5982\u679c\u6211\u4eec\u6709\u4e00\u4e2a\u6d41\u5165\u7684\u8fb9\u754c\uff0c\u6211\u4eec\u9700\u8981\u8bc4\u4f30\u9762\u7684\u53e6\u4e00\u8fb9\u7684\u9971\u548c\u5ea6\uff08\u6216\u8005\u8fb9\u754c\u503c\uff0c\u5982\u679c\u6211\u4eec\u5728\u57df\u7684\u8fb9\u754c\u4e0a\uff09\u3002\n\n// \u6240\u6709\u8fd9\u4e9b\u90fd\u6709\u70b9\u68d8\u624b\uff0c\u4f46\u5728  step-9  \u4e2d\u5df2\u7ecf\u6709\u4e86\u4e00\u4e9b\u8be6\u7ec6\u7684\u89e3\u91ca\u3002\u8bf7\u770b\u8fd9\u91cc\uff0c\u8fd9\u5e94\u8be5\u662f\u5982\u4f55\u5de5\u4f5c\u7684!\n\n        for (const auto face_no : cell->face_indices()) \n          { \n            fe_face_values.reinit(cell, face_no); \n\n            fe_face_values.get_function_values(old_solution, \n                                               old_solution_values_face); \n            fe_face_values.get_function_values(solution, \n                                               present_solution_values_face); \n\n            if (cell->at_boundary(face_no)) \n              saturation_boundary_values.value_list( \n                fe_face_values.get_quadrature_points(), neighbor_saturation); \n            else \n              { \n                const auto         neighbor = cell->neighbor(face_no); \n                const unsigned int neighbor_face = \n                  cell->neighbor_of_neighbor(face_no); \n\n                fe_face_values_neighbor.reinit(neighbor, neighbor_face); \n\n                fe_face_values_neighbor.get_function_values( \n                  old_solution, old_solution_values_face_neighbor); \n\n                for (unsigned int q = 0; q < n_face_q_points; ++q) \n                  neighbor_saturation[q] = \n                    old_solution_values_face_neighbor[q](dim + 1); \n              } \n\n            for (unsigned int q = 0; q < n_face_q_points; ++q) \n              { \n                Tensor<1, dim> present_u_face; \n                for (unsigned int d = 0; d < dim; ++d) \n                  present_u_face[d] = present_solution_values_face[q](d); \n\n                const double normal_flux = \n                  present_u_face * fe_face_values.normal_vector(q); \n\n                const bool is_outflow_q_point = (normal_flux >= 0); \n\n                for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                  local_rhs(i) -= \n                    time.get_next_step_size() * normal_flux * \n                    fractional_flow((is_outflow_q_point == true ? \n                                       old_solution_values_face[q](dim + 1) : \n                                       neighbor_saturation[q]), \n                                    viscosity) * \n                    fe_face_values[saturation].value(i, q) * \n                    fe_face_values.JxW(q); \n              } \n          } \n\n        cell->get_dof_indices(local_dof_indices); \n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          system_rhs(local_dof_indices[i]) += local_rhs(i); \n      } \n  } \n\n//  @sect4{TwoPhaseFlowProblem::solve}  \n\n// \u5728\u6240\u6709\u8fd9\u4e9b\u51c6\u5907\u5de5\u4f5c\u4e4b\u540e\uff0c\u6211\u4eec\u6700\u7ec8\u4ee5\u4e0e  step-20  \u76f8\u540c\u7684\u65b9\u5f0f\u89e3\u51b3\u901f\u5ea6\u548c\u538b\u529b\u7684\u7ebf\u6027\u7cfb\u7edf\u3002\u5728\u8fd9\u4e4b\u540e\uff0c\u6211\u4eec\u5fc5\u987b\u5904\u7406\u9971\u548c\u65b9\u7a0b\uff08\u89c1\u4e0b\u6587\uff09\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::solve() \n  { \n    const InverseMatrix<SparseMatrix<double>> m_inverse( \n      system_matrix.block(0, 0)); \n    Vector<double> tmp(solution.block(0).size()); \n    Vector<double> schur_rhs(solution.block(1).size()); \n    Vector<double> tmp2(solution.block(2).size()); \n\n// \u9996\u5148\u662f\u538b\u529b\uff0c\u4f7f\u7528\u524d\u4e24\u4e2a\u65b9\u7a0b\u7684\u538b\u529b\u8212\u5c14\u8865\u3002\n\n    { \n      m_inverse.vmult(tmp, system_rhs.block(0)); \n      system_matrix.block(1, 0).vmult(schur_rhs, tmp); \n      schur_rhs -= system_rhs.block(1); \n\n      SchurComplement schur_complement(system_matrix, m_inverse); \n\n      ApproximateSchurComplement approximate_schur_complement(system_matrix); \n\n      InverseMatrix<ApproximateSchurComplement> preconditioner( \n        approximate_schur_complement); \n\n      SolverControl            solver_control(solution.block(1).size(), \n                                   1e-12 * schur_rhs.l2_norm()); \n      SolverCG<Vector<double>> cg(solver_control); \n\n      cg.solve(schur_complement, solution.block(1), schur_rhs, preconditioner); \n\n      std::cout << \"   \" << solver_control.last_step() \n                << \" CG Schur complement iterations for pressure.\" << std::endl; \n    } \n\n// \u73b0\u5728\u662f\u901f\u5ea6\u3002\n\n    { \n      system_matrix.block(0, 1).vmult(tmp, solution.block(1)); \n      tmp *= -1; \n      tmp += system_rhs.block(0); \n\n      m_inverse.vmult(solution.block(0), tmp); \n    } \n\n// \u6700\u540e\uff0c\u6211\u4eec\u5fc5\u987b\u5904\u7406\u597d\u9971\u548c\u5ea6\u65b9\u7a0b\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u8981\u505a\u7684\u7b2c\u4e00\u4ef6\u4e8b\u662f\u4f7f\u7528\u4ecb\u7ecd\u4e2d\u7684\u516c\u5f0f\u6765\u786e\u5b9a\u65f6\u95f4\u6b65\u957f\u3002\u77e5\u9053\u4e86\u6211\u4eec\u9886\u57df\u7684\u5f62\u72b6\uff0c\u4ee5\u53ca\u6211\u4eec\u901a\u8fc7\u6709\u89c4\u5f8b\u5730\u5212\u5206\u5355\u5143\u6765\u521b\u5efa\u7f51\u683c\uff0c\u6211\u4eec\u53ef\u4ee5\u5f88\u5bb9\u6613\u5730\u8ba1\u7b97\u51fa\u6bcf\u4e2a\u5355\u5143\u7684\u76f4\u5f84\uff08\u4e8b\u5b9e\u4e0a\u6211\u4eec\u4f7f\u7528\u7684\u662f\u5355\u5143\u5750\u6807\u65b9\u5411\u4e0a\u7684\u7ebf\u6027\u6269\u5c55\uff0c\u800c\u4e0d\u662f\u76f4\u5f84\uff09\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u5c06\u5728 step-24 \u4e2d\u5b66\u4e60\u4e00\u79cd\u66f4\u901a\u7528\u7684\u65b9\u6cd5\uff0c\u5728\u90a3\u91cc\u6211\u4eec\u4f7f\u7528 GridTools::minimal_cell_diameter \u51fd\u6570\u3002\n\n// \u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u8f85\u52a9\u51fd\u6570\u6765\u8ba1\u7b97\u4e0b\u9762\u5b9a\u4e49\u7684\u6700\u5927\u901f\u5ea6\uff0c\u6709\u4e86\u8fd9\u4e9b\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u8bc4\u4f30\u6211\u4eec\u65b0\u7684\u65f6\u95f4\u6b65\u957f\u4e86\u3002\u6211\u4eec\u4f7f\u7528\u65b9\u6cd5 DiscreteTime::set_desired_next_time_step() \u6765\u5411DiscreteTime\u5bf9\u8c61\u5efa\u8bae\u65b0\u7684\u65f6\u95f4\u6b65\u957f\u7684\u8ba1\u7b97\u503c\u3002\u5728\u5927\u591a\u6570\u60c5\u51b5\u4e0b\uff0c\u65f6\u95f4\u5bf9\u8c61\u4f7f\u7528\u7cbe\u786e\u63d0\u4f9b\u7684\u503c\u6765\u589e\u52a0\u65f6\u95f4\u3002\u5728\u67d0\u4e9b\u60c5\u51b5\u4e0b\uff0c\u65f6\u95f4\u5bf9\u8c61\u53ef\u4ee5\u8fdb\u4e00\u6b65\u4fee\u6539\u6b65\u9aa4\u5927\u5c0f\u3002\u4f8b\u5982\uff0c\u5982\u679c\u8ba1\u7b97\u51fa\u7684\u65f6\u95f4\u589e\u91cf\u8d85\u8fc7\u4e86\u7ed3\u675f\u65f6\u95f4\uff0c\u5b83\u5c06\u88ab\u76f8\u5e94\u5730\u622a\u65ad\u3002\n\n    time.set_desired_next_step_size(std::pow(0.5, double(n_refinement_steps)) / \n                                    get_maximal_velocity()); \n\n// \u4e0b\u4e00\u6b65\u662f\u7ec4\u88c5\u53f3\u624b\u8fb9\uff0c\u7136\u540e\u628a\u6240\u6709\u7684\u4e1c\u897f\u90fd\u4f20\u7ed9\u89e3\u3002\u6700\u540e\uff0c\u6211\u4eec\u628a\u9971\u548c\u5ea6\u6295\u5c04\u56de\u7269\u7406\u4e0a\u5408\u7406\u7684\u8303\u56f4\u3002\n\n    assemble_rhs_S(); \n    { \n      SolverControl            solver_control(system_matrix.block(2, 2).m(), \n                                   1e-8 * system_rhs.block(2).l2_norm()); \n      SolverCG<Vector<double>> cg(solver_control); \n      cg.solve(system_matrix.block(2, 2), \n               solution.block(2), \n               system_rhs.block(2), \n               PreconditionIdentity()); \n\n      project_back_saturation(); \n\n      std::cout << \"   \" << solver_control.last_step() \n                << \" CG iterations for saturation.\" << std::endl; \n    } \n\n    old_solution = solution; \n  } \n// @sect4{TwoPhaseFlowProblem::output_results}  \n\n// \u8fd9\u91cc\u6ca1\u6709\u4ec0\u4e48\u503c\u5f97\u60ca\u8bb6\u7684\u3002\u7531\u4e8e\u7a0b\u5e8f\u4f1a\u505a\u5927\u91cf\u7684\u65f6\u95f4\u6b65\u9aa4\uff0c\u6211\u4eec\u53ea\u5728\u6bcf\u7b2c\u4e94\u4e2a\u65f6\u95f4\u6b65\u9aa4\u521b\u5efa\u4e00\u4e2a\u8f93\u51fa\u6587\u4ef6\uff0c\u5e76\u5728\u6587\u4ef6\u7684\u9876\u90e8\u5df2\u7ecf\u8df3\u8fc7\u6240\u6709\u5176\u4ed6\u65f6\u95f4\u6b65\u9aa4\u3002\n\n// \u5728\u4e3a\u63a5\u8fd1\u51fd\u6570\u5e95\u90e8\u7684\u8f93\u51fa\u521b\u5efa\u6587\u4ef6\u540d\u65f6\uff0c\u6211\u4eec\u5c06\u65f6\u95f4\u6b65\u957f\u7684\u6570\u5b57\u8f6c\u6362\u4e3a\u5b57\u7b26\u4e32\u8868\u793a\uff0c\u7528\u524d\u5bfc\u96f6\u586b\u5145\u5230\u56db\u4f4d\u6570\u3002\u6211\u4eec\u8fd9\u6837\u505a\u662f\u56e0\u4e3a\u8fd9\u6837\u6240\u6709\u7684\u8f93\u51fa\u6587\u4ef6\u540d\u90fd\u6709\u76f8\u540c\u7684\u957f\u5ea6\uff0c\u56e0\u6b64\u5728\u521b\u5efa\u76ee\u5f55\u5217\u8868\u65f6\u53ef\u4ee5\u5f88\u597d\u5730\u6392\u5e8f\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::output_results() const \n  { \n    if (time.get_step_number() % 5 != 0) \n      return; \n\n    std::vector<std::string> solution_names; \n    switch (dim) \n      { \n        case 2: \n          solution_names = {\"u\", \"v\", \"p\", \"S\"}; \n          break; \n\n        case 3: \n          solution_names = {\"u\", \"v\", \"w\", \"p\", \"S\"}; \n          break; \n\n        default: \n          Assert(false, ExcNotImplemented()); \n      } \n\n    DataOut<dim> data_out; \n\n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, solution_names); \n\n    data_out.build_patches(degree + 1); \n\n    std::ofstream output(\"solution-\" + \n                         Utilities::int_to_string(time.get_step_number(), 4) + \n                         \".vtk\"); \n    data_out.write_vtk(output); \n  } \n\n//  @sect4{TwoPhaseFlowProblem::project_back_saturation}  \n\n// \u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u7b80\u5355\u5730\u904d\u5386\u6240\u6709\u7684\u9971\u548c\u81ea\u7531\u5ea6\uff0c\u5e76\u786e\u4fdd\u5982\u679c\u5b83\u4eec\u79bb\u5f00\u4e86\u7269\u7406\u4e0a\u7684\u5408\u7406\u8303\u56f4\uff0c\u5b83\u4eec\u5c06\u88ab\u91cd\u7f6e\u5230\u533a\u95f4  $[0,1]$  \u3002\u8981\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u53ea\u9700\u8981\u5faa\u73af\u89e3\u51b3\u5411\u91cf\u7684\u6240\u6709\u9971\u548c\u5206\u91cf\uff1b\u8fd9\u4e9b\u5206\u91cf\u5b58\u50a8\u5728\u57572\u4e2d\uff08\u57570\u662f\u901f\u5ea6\uff0c\u57571\u662f\u538b\u529b\uff09\u3002\n\n// \u503c\u5f97\u6ce8\u610f\u7684\u662f\uff0c\u5f53\u65f6\u95f4\u6b65\u957f\u9009\u62e9\u5982\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\u90a3\u6837\u65f6\uff0c\u8fd9\u4e2a\u51fd\u6570\u51e0\u4e4e\u4ece\u672a\u89e6\u53d1\u8fc7\uff0c\u8fd9\u4e00\u70b9\u53ef\u80fd\u5f88\u6709\u542f\u53d1\u3002\u7136\u800c\uff0c\u5982\u679c\u6211\u4eec\u53ea\u9009\u62e9\u7a0d\u5927\u7684\u65f6\u95f4\u6b65\u957f\uff0c\u6211\u4eec\u4f1a\u5f97\u5230\u5927\u91cf\u8d85\u51fa\u9002\u5f53\u8303\u56f4\u7684\u6570\u503c\u3002\u4e25\u683c\u6765\u8bf4\uff0c\u5982\u679c\u6211\u4eec\u9009\u62e9\u7684\u65f6\u95f4\u6b65\u957f\u8db3\u591f\u5c0f\uff0c\u8fd9\u4e2a\u51fd\u6570\u56e0\u6b64\u662f\u4e0d\u5fc5\u8981\u7684\u3002\u4ece\u67d0\u79cd\u610f\u4e49\u4e0a\u8bf4\uff0c\u8fd9\u4e2a\u51fd\u6570\u53ea\u662f\u4e00\u4e2a\u5b89\u5168\u88c5\u7f6e\uff0c\u4ee5\u907f\u514d\u7531\u4e8e\u4e2a\u522b\u81ea\u7531\u5ea6\u5728\u51e0\u4e2a\u65f6\u95f4\u6b65\u957f\u4e4b\u524d\u53d8\u5f97\u4e0d\u7b26\u5408\u7269\u7406\u6761\u4ef6\u800c\u5bfc\u81f4\u6211\u4eec\u7684\u6574\u4e2a\u89e3\u51b3\u65b9\u6848\u53d8\u5f97\u4e0d\u7b26\u5408\u7269\u7406\u6761\u4ef6\u7684\u60c5\u51b5\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::project_back_saturation() \n  { \n    for (unsigned int i = 0; i < solution.block(2).size(); ++i) \n      if (solution.block(2)(i) < 0) \n        solution.block(2)(i) = 0; \n      else if (solution.block(2)(i) > 1) \n        solution.block(2)(i) = 1; \n  } \n// @sect4{TwoPhaseFlowProblem::get_maximal_velocity}  \n\n// \u4e0b\u9762\u7684\u51fd\u6570\u7528\u4e8e\u786e\u5b9a\u5141\u8bb8\u7684\u6700\u5927\u65f6\u95f4\u6b65\u957f\u3002\u5b83\u7684\u4f5c\u7528\u662f\u5728\u57df\u4e2d\u7684\u6240\u6709\u6b63\u4ea4\u70b9\u4e0a\u5faa\u73af\uff0c\u627e\u51fa\u901f\u5ea6\u7684\u6700\u5927\u5e45\u5ea6\u3002\n\n  template <int dim> \n  double TwoPhaseFlowProblem<dim>::get_maximal_velocity() const \n  { \n    QGauss<dim>        quadrature_formula(degree + 2); \n    const unsigned int n_q_points = quadrature_formula.size(); \n\n    FEValues<dim> fe_values(fe, quadrature_formula, update_values); \n    std::vector<Vector<double>> solution_values(n_q_points, \n                                                Vector<double>(dim + 2)); \n    double                      max_velocity = 0; \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        fe_values.reinit(cell); \n        fe_values.get_function_values(solution, solution_values); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            Tensor<1, dim> velocity; \n            for (unsigned int i = 0; i < dim; ++i) \n              velocity[i] = solution_values[q](i); \n\n            max_velocity = std::max(max_velocity, velocity.norm()); \n          } \n      } \n\n    return max_velocity; \n  } \n// @sect4{TwoPhaseFlowProblem::run}  \n\n// \u8fd9\u662f\u6211\u4eec\u4e3b\u7c7b\u7684\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u3002\u5b83\u7684\u7b80\u6d01\u4e0d\u8a00\u81ea\u660e\u3002\u53ea\u6709\u4e24\u70b9\u662f\u503c\u5f97\u6ce8\u610f\u7684\u3002\u9996\u5148\uff0c\u8be5\u51fd\u6570\u5728\u5f00\u59cb\u65f6\u5c06\u521d\u59cb\u503c\u6295\u5c04\u5230\u6709\u9650\u5143\u7a7a\u95f4\u4e0a\uff1b VectorTools::project \u51fd\u6570\u8fd9\u6837\u505a\u9700\u8981\u4e00\u4e2a\u8868\u660e\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u7684\u53c2\u6570\u3002\u6211\u4eec\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u6ca1\u6709\uff08\u6211\u4eec\u5728\u4e00\u4e2a\u5747\u5300\u7ec6\u5316\u7684\u7f51\u683c\u4e0a\u8ba1\u7b97\uff09\uff0c\u4f46\u662f\u8fd9\u4e2a\u51fd\u6570\u5f53\u7136\u9700\u8981\u8fd9\u4e2a\u53c2\u6570\u3002\u6240\u4ee5\u6211\u4eec\u5fc5\u987b\u521b\u5efa\u4e00\u4e2a\u7ea6\u675f\u5bf9\u8c61\u3002\u5728\u539f\u59cb\u72b6\u6001\u4e0b\uff0c\u7ea6\u675f\u5bf9\u8c61\u662f\u6ca1\u6709\u6392\u5e8f\u7684\uff0c\u5728\u4f7f\u7528\u524d\u5fc5\u987b\u8fdb\u884c\u6392\u5e8f\uff08\u4f7f\u7528 AffineConstraints::close \u51fd\u6570\uff09\u3002\u8fd9\u5c31\u662f\u6211\u4eec\u5728\u8fd9\u91cc\u6240\u505a\u7684\uff0c\u8fd9\u4e5f\u662f\u4e3a\u4ec0\u4e48\u6211\u4eec\u4e0d\u80fd\u7b80\u5355\u5730\u7528\u4e00\u4e2a\u533f\u540d\u7684\u4e34\u65f6\u5bf9\u8c61 <code>AffineConstraints<double>()</code> \u4f5c\u4e3a\u7b2c\u4e8c\u4e2a\u53c2\u6570\u6765\u8c03\u7528 VectorTools::project \u51fd\u6570\u3002\n\n// \u503c\u5f97\u4e00\u63d0\u7684\u7b2c\u4e8c\u70b9\u662f\uff0c\u6211\u4eec\u53ea\u5728\u6c42\u89e3\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u5bf9\u5e94\u7684\u7ebf\u6027\u7cfb\u7edf\u7684\u8fc7\u7a0b\u4e2d\u8ba1\u7b97\u5f53\u524d\u65f6\u95f4\u6b65\u957f\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u53ea\u6709\u5728\u65f6\u95f4\u6b65\u957f\u7ed3\u675f\u65f6\u624d\u80fd\u8f93\u51fa\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u5f53\u524d\u65f6\u95f4\u3002\u6211\u4eec\u901a\u8fc7\u8c03\u7528\u5faa\u73af\u5185\u7684\u65b9\u6cd5 DiscreteTime::advance_time() \u6765\u589e\u52a0\u65f6\u95f4\u3002\u7531\u4e8e\u6211\u4eec\u5728\u589e\u91cf\u540e\u62a5\u544a\u65f6\u95f4\u548cdt\uff0c\u6211\u4eec\u5fc5\u987b\u8c03\u7528\u65b9\u6cd5 DiscreteTime::get_previous_step_size() \uff0c\u800c\u4e0d\u662f DiscreteTime::get_next_step_size(). \u3002 \u7ecf\u8fc7\u8bb8\u591a\u6b65\uff0c\u5f53\u6a21\u62df\u5230\u8fbe\u7ed3\u675f\u65f6\u95f4\u65f6\uff0c\u6700\u540e\u7684dt\u7531DiscreteTime\u7c7b\u9009\u62e9\uff0c\u5176\u65b9\u5f0f\u662f\u6700\u540e\u4e00\u6b65\u6b63\u597d\u5728\u7ed3\u675f\u65f6\u95f4\u5b8c\u6210\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::run() \n  { \n    make_grid_and_dofs(); \n\n    { \n      AffineConstraints<double> constraints; \n      constraints.close(); \n\n      VectorTools::project(dof_handler, \n                           constraints, \n                           QGauss<dim>(degree + 2), \n                           InitialValues<dim>(), \n                           old_solution); \n    } \n\n    do \n      { \n        std::cout << \"Timestep \" << time.get_step_number() + 1 << std::endl; \n\n        assemble_system(); \n\n        solve(); \n\n        output_results(); \n\n        time.advance_time(); \n        std::cout << \"   Now at t=\" << time.get_current_time() \n                  << \", dt=\" << time.get_previous_step_size() << '.' \n                  << std::endl \n                  << std::endl; \n      } \n    while (time.is_at_end() == false); \n  } \n} // namespace Step21 \n// @sect3{The <code>main</code> function}  \n\n// \u8fd9\u5c31\u662f\u4e86\u3002\u5728\u4e3b\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u5c06\u6709\u9650\u5143\u7a7a\u95f4\u7684\u5ea6\u6570\u4f20\u9012\u7ed9TwoPhaseFlowProblem\u5bf9\u8c61\u7684\u6784\u9020\u51fd\u6570\u3002 \u8fd9\u91cc\uff0c\u6211\u4eec\u4f7f\u7528\u96f6\u5ea6\u5143\u7d20\uff0c\u5373 $RT_0\\times DQ_0 \\times DQ_0$  \u3002\u5176\u4f59\u90e8\u5206\u4e0e\u5176\u4ed6\u6240\u6709\u7a0b\u5e8f\u4e00\u6837\u3002\n\nint main() \n{ \n  try \n    { \n      using namespace Step21; \n\n      TwoPhaseFlowProblem<2> two_phase_flow_problem(0); \n      two_phase_flow_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\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\n\n", "meta": {"hexsha": "155c2dfc59b5868d5fa821764a109678730abee8", "size": 35822, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-21/step-21.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-21/step-21.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-21/step-21.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.1886051081, "max_line_length": 335, "alphanum_fraction": 0.5998827536, "num_tokens": 12225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5422638361836327}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n/*!\n * \\file\n**/\n#ifndef BOOST_SIMD_CONSTANT_CONSTANTS_GOLD_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_CONSTANTS_GOLD_HPP_INCLUDED\n\n#include <boost/simd/include/functor.hpp>\n#include <boost/simd/sdk/constant/register.hpp>\n#include <boost/simd/sdk/constant/constant.hpp>\n\n/*!\n * \\ingroup boost_simd_constant\n * \\defgroup boost_simd_constant_gold Gold\n *\n * \\par Description\n * Constant Gold \\f$= \\frac{1+\\sqrt5}{2}\\f$\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/gold.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class T,class A0>\n *     meta::call<tag::gold_(A0)>::type\n *     Gold();\n * }\n * \\endcode\n *\n *\n * \\param T template parameter of Gold\n *\n * \\return type T value\n *\n *\n**/\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n    /*!\n     * \\brief Define the tag Gold of functor Gold\n     *        in namespace boost::simd::tag for toolbox boost.simd.constant\n    **/\n    BOOST_SIMD_CONSTANT_REGISTER( Gold,double,1\n                                , 0x3FCF1BBD,0x3FF9E3779B97F4A8ULL\n                                );\n  }\n\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(boost::simd::tag::Gold, Gold)\n} }\n\n#include <boost/simd/sdk/constant/common.hpp>\n\n#endif\n", "meta": {"hexsha": "5f95d6d5f18c864d5b3c010f9a187274fe58f770", "size": 1742, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/constant/include/boost/simd/constant/constants/gold.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/constant/include/boost/simd/constant/constants/gold.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/constant/include/boost/simd/constant/constants/gold.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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.5352112676, "max_line_length": 80, "alphanum_fraction": 0.5746268657, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5422638361836327}}
{"text": "#pragma once\n#include <Eigen/Core>\n\n#include \"fixed_size_container_type_trait.hpp\"\n#include \"internal/no_discard.hpp\"\n\nnamespace ubs {\n\n/**\n * @brief Uniform B-spline output trait for multi-dimensional Eigen vectors.\n * \\sa FixedSizeContainerTypeTrait\n * @tparam T_ The value type.\n * @tparam N_ The number of output dimensions.\n */\ntemplate <typename T_, int N_>\nstruct FixedSizeContainerTypeTrait<Eigen::Matrix<T_, N_, 1>> {\n    static_assert(N_ > 0, \"Only fixed size output dimensions supported.\");\n\n    using Type = Eigen::Matrix<T_, N_, 1>;\n    using ValueType = T_;\n    using Allocator = Eigen::aligned_allocator<Type>;\n\n    static constexpr int Size = N_;\n    static constexpr bool IsContinuous = true;\n\n    UBS_NO_DISCARD static auto zero() {\n        return Eigen::Matrix<T_, N_, 1>::Zero();\n    }\n\n    UBS_NO_DISCARD static auto ones() {\n        return Eigen::Matrix<T_, N_, 1>::Ones();\n    }\n\n    UBS_NO_DISCARD static ValueType& get(Type& vec, int idx) {\n        return vec[idx];\n    }\n\n    UBS_NO_DISCARD static const ValueType& get(const Type& vec, int idx) {\n        return vec[idx];\n    }\n\n    UBS_NO_DISCARD static const ValueType* data(const Type& vec) {\n        return vec.data();\n    }\n\n    UBS_NO_DISCARD static ValueType* data(Type& vec) {\n        return vec.data();\n    }\n\n    UBS_NO_DISCARD static Type evalSmoothness(ValueType factor, const Type& p1, const Type& p2) {\n        return factor * p1.array() * p2.array();\n    }\n};\n\n} // namespace ubs\n", "meta": {"hexsha": "568c3f94bd2de83cc568f49ab4744e6727bdbc04", "size": 1471, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/uniform_bspline/fixed_size_container_type_trait_eigen.hpp", "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": "include/uniform_bspline/fixed_size_container_type_trait_eigen.hpp", "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": "include/uniform_bspline/fixed_size_container_type_trait_eigen.hpp", "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": 26.2678571429, "max_line_length": 97, "alphanum_fraction": 0.6655336506, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905302989295534, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.542263832793474}}
{"text": "/* test_bernoulli.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$\n *\n */\n\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/exception/diagnostic_information.hpp>\n#include <vector>\n#include <iostream>\n#include <numeric>\n\n#include \"chi_squared_test.hpp\"\n\nbool do_test(double p, long long max) {\n    std::cout << \"running bernoulli(\" << p << \")\" << \" \" << max << \" times: \" << std::flush;\n\n    boost::math::binomial expected(static_cast<double>(max), p);\n    \n    boost::random::bernoulli_distribution<> dist(p);\n    boost::mt19937 gen;\n    long long count = 0;\n    for(long long i = 0; i < max; ++i) {\n        if(dist(gen)) ++count;\n    }\n\n    double prob = cdf(expected, count);\n\n    bool result = prob < 0.99 && prob > 0.01;\n    const char* err = result? \"\" : \"*\";\n    std::cout << std::setprecision(17) << prob << err << std::endl;\n\n    std::cout << std::setprecision(6);\n\n    return result;\n}\n\nbool do_tests(int repeat, long long trials) {\n    boost::mt19937 gen;\n    boost::uniform_01<> rdist;\n    int errors = 0;\n    for(int i = 0; i < repeat; ++i) {\n        if(!do_test(rdist(gen), trials)) {\n            ++errors;\n        }\n    }\n    if(errors != 0) {\n        std::cout << \"*** \" << errors << \" errors detected ***\" << std::endl;\n    }\n    return errors == 0;\n}\n\nint usage() {\n    std::cerr << \"Usage: test_bernoulli_distribution -r <repeat> -t <trials>\" << std::endl;\n    return 2;\n}\n\ntemplate<class T>\nbool handle_option(int& argc, char**& argv, char opt, T& value) {\n    if(argv[0][1] == opt && argc > 1) {\n        --argc;\n        ++argv;\n        value = boost::lexical_cast<T>(argv[0]);\n        return true;\n    } else {\n        return false;\n    }\n}\n\nint main(int argc, char** argv) {\n    int repeat = 10;\n    long long trials = 1000000ll;\n\n    if(argc > 0) {\n        --argc;\n        ++argv;\n    }\n    while(argc > 0) {\n        if(argv[0][0] != '-') return usage();\n        else if(!handle_option(argc, argv, 'r', repeat)\n             && !handle_option(argc, argv, 't', trials)) {\n            return usage();\n        }\n        --argc;\n        ++argv;\n    }\n\n    try {\n        if(do_tests(repeat, trials)) {\n            return 0;\n        } else {\n            return EXIT_FAILURE;\n        }\n    } catch(...) {\n        std::cerr << boost::current_exception_diagnostic_information() << std::endl;\n        return EXIT_FAILURE;\n    }\n}\n", "meta": {"hexsha": "cab0c1c3e7d48d312abe874e482c6315ff67561f", "size": 2725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_bernoulli.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/random/test/test_bernoulli.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/random/test/test_bernoulli.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 25.0, "max_line_length": 92, "alphanum_fraction": 0.5695412844, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5422638294132701}}
{"text": "// All content Copyright (C) 2018 Genomics plc\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\n#include \"utils/matrix.hpp\"\n#include <set>\n#include <cassert>\n#include <algorithm>\n\nwecall::utils::matrix_t getMatrixFromVecOfVecs( const std::vector< std::vector< double > > & values )\n{\n    assert( values.size() > 0 );\n\n    wecall::utils::matrix_t matrix_t( values.size(), values[0].size() );\n\n    for ( std::size_t rowIndex = 0; rowIndex < matrix_t.size1(); ++rowIndex )\n    {\n        const auto & row = values[rowIndex];\n        assert( row.size() == matrix_t.size2() );\n\n        std::copy( row.begin(), row.end(), matrix_t.data().begin() + matrix_t.size2() * rowIndex );\n    }\n    return matrix_t;\n}\n\nBOOST_AUTO_TEST_CASE( testSumOverMatrixRowIndexSet )\n{\n    std::vector< int > values = {1, 2, 3, 4, 5, 6, 7};\n    wecall::utils::matrix_t matrix_t( 1, 7 );\n    std::copy( values.begin(), values.end(), matrix_t.data().begin() );\n\n    wecall::utils::matrixRow_t matrixRow_t( matrix_t, 0 );\n\n    std::set< std::size_t > indicies = {0, 2, 4};\n    BOOST_CHECK_EQUAL( wecall::utils::sumMatrixRowOverIndexSubset( matrixRow_t, indicies ), 1 + 3 + 5 );\n    BOOST_CHECK_EQUAL( wecall::utils::sumMatrixRowOverAllIndices( matrixRow_t ), 1 + 2 + 3 + 4 + 5 + 6 + 7 );\n}\n\nBOOST_AUTO_TEST_CASE( testAdjustmentToMedian )\n{\n    std::vector< std::vector< double > > values = {\n        {13.0}, {1.0}, {1.0}, {1.0e-6}, {1.0}, {1.0}, {1.0}, {15.0},\n    };\n\n    wecall::utils::matrix_t matrix = getMatrixFromVecOfVecs( values );\n\n    BOOST_CHECK_CLOSE( *std::min_element( matrix.data().begin(), matrix.data().end() ), 1.0e-6, 1.0 );\n\n    wecall::utils::smoothLowOutliers( matrix, 1.0e-4 );\n\n    BOOST_CHECK_CLOSE( *std::min_element( matrix.data().begin(), matrix.data().end() ), 1.0e-4, 1.0 );\n}", "meta": {"hexsha": "65b7fb759ea369a8b38c7d362348e76b082571ac", "size": 1790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/test/unittest/utils/testMatrix.cpp", "max_stars_repo_name": "dylex/wecall", "max_stars_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-08T15:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T07:13:05.000Z", "max_issues_repo_path": "cpp/test/unittest/utils/testMatrix.cpp", "max_issues_repo_name": "dylex/wecall", "max_issues_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-05T09:16:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-09T12:32:56.000Z", "max_forks_repo_path": "cpp/test/unittest/utils/testMatrix.cpp", "max_forks_repo_name": "dylex/wecall", "max_forks_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T15:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T07:28:33.000Z", "avg_line_length": 34.4230769231, "max_line_length": 109, "alphanum_fraction": 0.6374301676, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5422432664512941}}
{"text": "//\n//=======================================================================\n// Copyright 2012\n// Author: Alex Hagen-Zanker\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// distance_visitor implements the dijkstra visitor and interruptor \n// concepts. It returns true on do_interrupt() once all vertices within a\n// given distance are found.\n//\n//=======================================================================\n//\n#ifndef BLINK_GRAPH_DIJKSTRA_VISITOR_DISTANCE_VISITOR_HPP\n#define BLINK_GRAPH_DIJKSTRA_VISITOR_DISTANCE_VISITOR_HPP\n\n#include <boost/graph/dijkstra_shortest_paths.hpp> // default_dijkstra_visitor\n#include <boost/property_map/property_map.hpp>\n#include <boost/smart_ptr.hpp>\n\n#include <functional> //std::less\n\nnamespace blink {\n\ntemplate<typename DistanceMap, typename Compare = \n  std::less<typename boost::property_traits<DistanceMap>::value_type > >\nclass distance_visitor : public boost::default_dijkstra_visitor\n{\n  typedef typename boost::property_traits<DistanceMap>::value_type distance_type;\n\npublic:\n  distance_visitor(DistanceMap distance_map, distance_type target_distance, \n    const Compare& compare = Compare()) \n    : m_distance_map(distance_map), m_target_distance(target_distance), \n    m_compare(compare)\n  {\n    m_do_interrupt.reset(new bool(false) );\n  }\n  \n  template<typename U, typename G>\n  void finish_vertex(const U& u, const G& g)\n  {\n    if( !m_compare(get(m_distance_map,u), m_target_distance) ) { \n      *m_do_interrupt = true;\n    }\n  }\n\n  inline bool do_interrupt() const \n  {\n    return *m_do_interrupt;\n  }\n\nprivate:\n  boost::shared_ptr<bool> m_do_interrupt;\n  DistanceMap m_distance_map; \n  distance_type m_target_distance;\n  Compare m_compare;\n};\n\ntemplate<typename DijkstraState>\nstruct distance_visitor_helper\n{\n  typedef typename DijkstraState::template param<boost::distance_compare_t>::type compare_type;\n  typedef typename DijkstraState::template param<boost::vertex_distance_t>::type distance_map_type;\n  typedef typename DijkstraState::template param<boost::vertex_index_t>::type index_type;\n  typedef typename DijkstraState::template param<boost::distance_inf_t>::type distance_value_type;\n  typedef typename distance_visitor<distance_map_type, compare_type> type;\n\n  static type make(DijkstraState& state, distance_value_type d)\n  {\n    return type(state.get<boost::vertex_distance_t>(), d\n      , state.get<boost::distance_compare_t>());\n  }\n};\n\ntemplate<typename Graph, typename Params>\nstruct distance_visitor_helper_indirect \n  : distance_visitor_helper<typename dijkstra_state_helper<Graph, Params>::type>\n{};\n \ntemplate <typename DijkstraState, typename DistanceValue>\ntypename distance_visitor_helper<DijkstraState>::type\nmake_distance_visitor(DijkstraState& state, DistanceValue d)\n{\n  return distance_visitor_helper<DijkstraState>::make(state, d);\n}\n\n\n}; // namespace blink;\n\n#endif //BLINK_GRAPH_DIJKSTRA_VISITOR_DISTANCE_VISITOR_HPP", "meta": {"hexsha": "ea00d0deccf9e603e99c3c8caf29cd60dfd8b59b", "size": 3102, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "blink/graph/dijkstra_visitor/distance_visitor.hpp", "max_stars_repo_name": "ahhz/resumable_dijkstra", "max_stars_repo_head_hexsha": "1fa57b7de5dd9ce9a23f146b709f7cb76cdf01d1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-11-18T15:55:43.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-18T15:55:43.000Z", "max_issues_repo_path": "blink/graph/dijkstra_visitor/distance_visitor.hpp", "max_issues_repo_name": "ahhz/resumable_dijkstra", "max_issues_repo_head_hexsha": "1fa57b7de5dd9ce9a23f146b709f7cb76cdf01d1", "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": "blink/graph/dijkstra_visitor/distance_visitor.hpp", "max_forks_repo_name": "ahhz/resumable_dijkstra", "max_forks_repo_head_hexsha": "1fa57b7de5dd9ce9a23f146b709f7cb76cdf01d1", "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": 99, "alphanum_fraction": 0.7253384913, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5422432568370011}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n#include <functional>\n#include <iostream>\n#include <vector>\n\n#include <graphblas/graphblas.hpp>\n\nusing namespace grb;\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE algebra_monoid_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n//****************************************************************************\n// Monoid tests\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(plus_monoid_test)\n{\n    BOOST_CHECK_EQUAL(PlusMonoid<double>().identity(), 0.0);\n    BOOST_CHECK_EQUAL(PlusMonoid<double>()(-2., 1.), -1.0);\n    BOOST_CHECK_EQUAL(PlusMonoid<float>().identity(), 0.0f);\n    BOOST_CHECK_EQUAL(PlusMonoid<float>()(-2.f, 1.f), -1.0f);\n\n    BOOST_CHECK_EQUAL(PlusMonoid<uint64_t>().identity(), 0UL);\n    BOOST_CHECK_EQUAL(PlusMonoid<uint64_t>()(2UL, 1UL), 3UL);\n    BOOST_CHECK_EQUAL(PlusMonoid<uint32_t>().identity(), 0U);\n    BOOST_CHECK_EQUAL(PlusMonoid<uint32_t>()(2U, 1U), 3U);\n    BOOST_CHECK_EQUAL(PlusMonoid<uint16_t>().identity(), 0U);\n    BOOST_CHECK_EQUAL(PlusMonoid<uint16_t>()(2U, 1U), 3U);\n    BOOST_CHECK_EQUAL(PlusMonoid<uint8_t>().identity(), 0U);\n    BOOST_CHECK_EQUAL(PlusMonoid<uint8_t>()(2U, 1U), 3U);\n\n    BOOST_CHECK_EQUAL(PlusMonoid<int64_t>().identity(), 0L);\n    BOOST_CHECK_EQUAL(PlusMonoid<int64_t>()(-2L, 1L), -1L);\n    BOOST_CHECK_EQUAL(PlusMonoid<int32_t>().identity(), 0);\n    BOOST_CHECK_EQUAL(PlusMonoid<int32_t>()(-2, 1), -1);\n    BOOST_CHECK_EQUAL(PlusMonoid<int16_t>().identity(), 0);\n    BOOST_CHECK_EQUAL(PlusMonoid<int16_t>()(-2, 1), -1);\n    BOOST_CHECK_EQUAL(PlusMonoid<int8_t>().identity(), 0);\n    BOOST_CHECK_EQUAL(PlusMonoid<int8_t>()(-2, 1), -1);\n\n    BOOST_CHECK_EQUAL(PlusMonoid<bool>().identity(), false);\n    BOOST_CHECK_EQUAL(PlusMonoid<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(PlusMonoid<bool>()(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(times_monoid_test)\n{\n    BOOST_CHECK_EQUAL(TimesMonoid<double>().identity(), 1.0);\n    BOOST_CHECK_EQUAL(TimesMonoid<double>()(-2., 1.), -2.0);\n    BOOST_CHECK_EQUAL(TimesMonoid<float>().identity(), 1.0f);\n    BOOST_CHECK_EQUAL(TimesMonoid<float>()(-2.f, 1.f), -2.0f);\n\n    BOOST_CHECK_EQUAL(TimesMonoid<uint64_t>().identity(), 1UL);\n    BOOST_CHECK_EQUAL(TimesMonoid<uint64_t>()(2UL, 1UL), 2UL);\n    BOOST_CHECK_EQUAL(TimesMonoid<uint32_t>().identity(), 1U);\n    BOOST_CHECK_EQUAL(TimesMonoid<uint32_t>()(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(TimesMonoid<uint16_t>().identity(), 1U);\n    BOOST_CHECK_EQUAL(TimesMonoid<uint16_t>()(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(TimesMonoid<uint8_t>().identity(), 1U);\n    BOOST_CHECK_EQUAL(TimesMonoid<uint8_t>()(2U, 1U), 2U);\n\n    BOOST_CHECK_EQUAL(TimesMonoid<int64_t>().identity(), 1L);\n    BOOST_CHECK_EQUAL(TimesMonoid<int64_t>()(-2L, 1L), -2L);\n    BOOST_CHECK_EQUAL(TimesMonoid<int32_t>().identity(), 1);\n    BOOST_CHECK_EQUAL(TimesMonoid<int32_t>()(-2, 1), -2);\n    BOOST_CHECK_EQUAL(TimesMonoid<int16_t>().identity(), 1);\n    BOOST_CHECK_EQUAL(TimesMonoid<int16_t>()(-2, 1), -2);\n    BOOST_CHECK_EQUAL(TimesMonoid<int8_t>().identity(), 1);\n    BOOST_CHECK_EQUAL(TimesMonoid<int8_t>()(-2, 1), -2);\n\n    BOOST_CHECK_EQUAL(TimesMonoid<bool>().identity(), true);\n    BOOST_CHECK_EQUAL(TimesMonoid<bool>()(false, true), false);\n    BOOST_CHECK_EQUAL(TimesMonoid<bool>()(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(min_monoid_test)\n{\n    BOOST_CHECK_EQUAL(MinMonoid<double>().identity(),\n                      std::numeric_limits<double>::infinity());\n    BOOST_CHECK_EQUAL(MinMonoid<double>()(-2., 1.), -2.0);\n    BOOST_CHECK_EQUAL(MinMonoid<float>().identity(),\n                      std::numeric_limits<float>::infinity());\n    BOOST_CHECK_EQUAL(MinMonoid<float>()(-2.f, 1.f), -2.0f);\n\n    BOOST_CHECK_EQUAL(MinMonoid<uint64_t>().identity(),\n                      std::numeric_limits<uint64_t>::max());\n    BOOST_CHECK_EQUAL(MinMonoid<uint64_t>()(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(MinMonoid<uint32_t>().identity(),\n                      std::numeric_limits<uint32_t>::max());\n    BOOST_CHECK_EQUAL(MinMonoid<uint32_t>()(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinMonoid<uint16_t>().identity(),\n                      std::numeric_limits<uint16_t>::max());\n    BOOST_CHECK_EQUAL(MinMonoid<uint16_t>()(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinMonoid<uint8_t>().identity(),\n                      std::numeric_limits<uint8_t>::max());\n    BOOST_CHECK_EQUAL(MinMonoid<uint8_t>()(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(MinMonoid<int64_t>().identity(),\n                      std::numeric_limits<int64_t>::max());\n    BOOST_CHECK_EQUAL(MinMonoid<int64_t>()(-2L, 1L), -2L);\n    BOOST_CHECK_EQUAL(MinMonoid<int32_t>().identity(),\n                      std::numeric_limits<int32_t>::max());\n    BOOST_CHECK_EQUAL(MinMonoid<int32_t>()(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinMonoid<int16_t>().identity(),\n                      std::numeric_limits<int16_t>::max());\n    BOOST_CHECK_EQUAL(MinMonoid<int16_t>()(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinMonoid<int8_t>().identity(),\n                      std::numeric_limits<int8_t>::max());\n    BOOST_CHECK_EQUAL(MinMonoid<int8_t>()(-2, 1), -2);\n\n    BOOST_CHECK_EQUAL(MinMonoid<bool>().identity(), true);\n    BOOST_CHECK_EQUAL(MinMonoid<bool>()(false, true), false);\n    BOOST_CHECK_EQUAL(MinMonoid<bool>()(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(max_monoid_test)\n{\n    BOOST_CHECK_EQUAL(MaxMonoid<double>().identity(),\n                      -std::numeric_limits<double>::infinity());\n    BOOST_CHECK_EQUAL(MaxMonoid<double>()(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(MaxMonoid<float>().identity(),\n                      -std::numeric_limits<float>::infinity());\n    BOOST_CHECK_EQUAL(MaxMonoid<float>()(-2.f, 1.f), 1.0f);\n\n    BOOST_CHECK_EQUAL(MaxMonoid<uint64_t>().identity(), 0UL);\n    BOOST_CHECK_EQUAL(MaxMonoid<uint64_t>()(2UL, 1UL), 2UL);\n    BOOST_CHECK_EQUAL(MaxMonoid<uint32_t>().identity(), 0U);\n    BOOST_CHECK_EQUAL(MaxMonoid<uint32_t>()(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxMonoid<uint16_t>().identity(), 0U);\n    BOOST_CHECK_EQUAL(MaxMonoid<uint16_t>()(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxMonoid<uint8_t>().identity(), 0U);\n    BOOST_CHECK_EQUAL(MaxMonoid<uint8_t>()(2U, 1U), 2U);\n\n    BOOST_CHECK_EQUAL(MaxMonoid<int64_t>().identity(),\n                      std::numeric_limits<int64_t>::min());\n    BOOST_CHECK_EQUAL(MaxMonoid<int64_t>()(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(MaxMonoid<int32_t>().identity(),\n                      std::numeric_limits<int32_t>::min());\n    BOOST_CHECK_EQUAL(MaxMonoid<int32_t>()(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxMonoid<int16_t>().identity(),\n                      std::numeric_limits<int16_t>::min());\n    BOOST_CHECK_EQUAL(MaxMonoid<int16_t>()(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxMonoid<int8_t>().identity(),\n                      std::numeric_limits<int8_t>::min());\n    BOOST_CHECK_EQUAL(MaxMonoid<int8_t>()(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(MaxMonoid<bool>().identity(), false);\n    BOOST_CHECK_EQUAL(MaxMonoid<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(MaxMonoid<bool>()(false, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(logical_or_monoid_test)\n{\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<double>().identity(), 0.0);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<double>()(0., 0.),  0.0);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<double>()(0., 1.),  1.0);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<double>()(-2., 0.), 1.0);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<double>()(1., -1.), 1.0);\n\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<float>().identity(), 0.0f);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<float>()(0.f, 0.f),  0.0f);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<float>()(0.f, 1.f),  1.0f);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<float>()(-2.f, 0.f), 1.0f);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<float>()(1.f, -1.f), 1.0f);\n\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint64_t>().identity(), 0UL);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint64_t>()(0UL, 0UL), 0UL);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint64_t>()(0UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint64_t>()(2UL, 0UL), 1UL);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint64_t>()(2UL, 1UL), 1UL);\n\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint32_t>().identity(), 0U);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint32_t>()(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint32_t>()(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint32_t>()(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint32_t>()(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint16_t>().identity(), 0U);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint16_t>()(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint16_t>()(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint16_t>()(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint16_t>()(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint8_t>().identity(), 0U);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint8_t>()(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint8_t>()(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint8_t>()(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<uint8_t>()(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int64_t>().identity(), 0L);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int64_t>()(0L, 0L), 0L);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int64_t>()(0L, 1L), 1L);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int64_t>()(-2L, 0L), 1L);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int64_t>()(-2L, 1L), 1L);\n\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int32_t>().identity(), 0);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int32_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int32_t>()(-2, 0), 1);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int32_t>()(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int16_t>().identity(), 0);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int16_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int16_t>()(-2, 0), 1);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int16_t>()(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int8_t>().identity(), 0);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int8_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int8_t>()(-2, 0), 1);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<int8_t>()(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<bool>().identity(), false);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<bool>()(false, true), true);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<bool>()(true, false), true);\n    BOOST_CHECK_EQUAL(LogicalOrMonoid<bool>()(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(logical_and_monoid_test)\n{\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<double>().identity(), 1.0);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<double>()(0., 0.),  0.0);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<double>()(0., 1.),  0.0);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<double>()(-2., 0.), 0.0);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<double>()(1., -1.), 1.0);\n\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<float>().identity(), 1.0f);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<float>()(0.f, 0.f),  0.0f);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<float>()(0.f, 1.f),  0.0f);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<float>()(-2.f, 0.f), 0.0f);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<float>()(1.f, -1.f), 1.0f);\n\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint64_t>().identity(), 1UL);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint64_t>()(0UL, 0UL), 0UL);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint64_t>()(0UL, 1UL), 0UL);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint64_t>()(2UL, 0UL), 0UL);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint64_t>()(2UL, 1UL), 1UL);\n\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint32_t>().identity(), 1U);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint32_t>()(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint32_t>()(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint32_t>()(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint32_t>()(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint16_t>().identity(), 1U);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint16_t>()(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint16_t>()(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint16_t>()(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint16_t>()(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint8_t>().identity(), 1U);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint8_t>()(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint8_t>()(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint8_t>()(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<uint8_t>()(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int64_t>().identity(), 1L);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int64_t>()(0L, 0L), 0L);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int64_t>()(0L, 1L), 0L);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int64_t>()(-2L, 0L), 0L);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int64_t>()(-2L, 1L), 1L);\n\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int32_t>().identity(), 1);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int32_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int32_t>()(-2, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int32_t>()(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int16_t>().identity(), 1);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int16_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int16_t>()(-2, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int16_t>()(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int8_t>().identity(), 1);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int8_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int8_t>()(-2, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<int8_t>()(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<bool>().identity(),  true);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<bool>()(false, true), false);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<bool>()(true, false), false);\n    BOOST_CHECK_EQUAL(LogicalAndMonoid<bool>()(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(logical_xor_monoid_test)\n{\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<double>().identity(), 0.0);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<double>()(0., 0.),  0.0);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<double>()(0., 1.),  1.0);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<double>()(-2., 0.), 1.0);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<double>()(1., -1.), 0.0);\n\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<float>().identity(), 0.0f);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<float>()(0.f, 0.f),  0.0f);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<float>()(0.f, 1.f),  1.0f);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<float>()(-2.f, 0.f), 1.0f);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<float>()(1.f, -1.f), 0.0f);\n\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint64_t>().identity(), 0UL);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint64_t>()(0UL, 0UL), 0UL);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint64_t>()(0UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint64_t>()(2UL, 0UL), 1UL);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint64_t>()(2UL, 1UL), 0UL);\n\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint32_t>().identity(), 0U);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint32_t>()(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint32_t>()(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint32_t>()(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint32_t>()(2U, 1U), 0U);\n\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint16_t>().identity(), 0U);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint16_t>()(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint16_t>()(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint16_t>()(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint16_t>()(2U, 1U), 0U);\n\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint8_t>().identity(), 0U);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint8_t>()(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint8_t>()(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint8_t>()(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<uint8_t>()(2U, 1U), 0U);\n\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int64_t>().identity(), 0L);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int64_t>()(0L, 0L), 0L);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int64_t>()(0L, 1L), 1L);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int64_t>()(-2L, 0L), 1L);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int64_t>()(-2L, 1L), 0L);\n\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int32_t>().identity(), 0);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int32_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int32_t>()(-2, 0), 1);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int32_t>()(-2, 1), 0);\n\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int16_t>().identity(), 0);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int16_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int16_t>()(-2, 0), 1);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int16_t>()(-2, 1), 0);\n\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int8_t>().identity(), 0);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int8_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int8_t>()(-2, 0), 1);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<int8_t>()(-2, 1), 0);\n\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<bool>().identity(), false);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<bool>()(false, true),  true);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<bool>()(true, false),  true);\n    BOOST_CHECK_EQUAL(LogicalXorMonoid<bool>()(true, true), false);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(logical_xnor_monoid_test)\n{\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<double>().identity(), 1.0);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<double>()(0., 0.),  1.0);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<double>()(0., 1.),  0.0);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<double>()(-2., 0.), 0.0);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<double>()(1., -1.), 1.0);\n\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<float>().identity(), 1.0f);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<float>()(0.f, 0.f),  1.0f);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<float>()(0.f, 1.f),  0.0f);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<float>()(-2.f, 0.f), 0.0f);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<float>()(1.f, -1.f), 1.0f);\n\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint64_t>().identity(), 1UL);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint64_t>()(0UL, 0UL), 1UL);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint64_t>()(0UL, 1UL), 0UL);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint64_t>()(2UL, 0UL), 0UL);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint64_t>()(2UL, 1UL), 1UL);\n\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint32_t>().identity(), 1U);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint32_t>()(0U, 0U), 1U);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint32_t>()(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint32_t>()(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint32_t>()(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint16_t>().identity(), 1U);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint16_t>()(0U, 0U), 1U);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint16_t>()(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint16_t>()(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint16_t>()(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint8_t>().identity(), 1U);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint8_t>()(0U, 0U), 1U);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint8_t>()(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint8_t>()(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<uint8_t>()(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int64_t>().identity(), 1L);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int64_t>()(0L, 0L), 1L);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int64_t>()(0L, 1L), 0L);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int64_t>()(-2L, 0L), 0L);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int64_t>()(-2L, 1L), 1L);\n\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int32_t>().identity(), 1);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int32_t>()(0, 0), 1);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int32_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int32_t>()(-2, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int32_t>()(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int16_t>().identity(), 1);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int16_t>()(0, 0), 1);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int16_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int16_t>()(-2, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int16_t>()(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int8_t>().identity(), 1);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int8_t>()(0, 0), 1);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int8_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int8_t>()(-2, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<int8_t>()(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<bool>().identity(), true);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<bool>()(false, false), true);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<bool>()(false, true), false);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<bool>()(true, false), false);\n    BOOST_CHECK_EQUAL(LogicalXnorMonoid<bool>()(true, true),  true);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6264d469b3bf867228ebafdace9f3f292d1594ab", "size": 23748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_algebra_monoid.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_algebra_monoid.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_algebra_monoid.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 49.9957894737, "max_line_length": 80, "alphanum_fraction": 0.6814468587, "num_tokens": 7487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.5422432542700798}}
{"text": "#pragma once\n//! c/c++ headers\n//! dependency headers\n#include <armadillo>\n//! project headers\n#include \"types.hpp\"\n\nnamespace correspondences {\n\n/**\n * @brief compute pairwise consistency score; see Eqn. 49 from reference\n *\n * @param [in] si ith point in source distribution\n * @param [in] tj jth point in target distribution\n * @param [in] sk kth point in source distribution\n * @param [in] tl lth point in target distribution\n * @return pairwise consistency score for (i, j, k, l)\n */\ndouble consistency(arma::vec3 const & si, arma::vec3 const & tj,\n    arma::vec3 const & sk, arma::vec3 const & tl) noexcept;\n\n/**\n * @brief populate weight tensor for optimization problem; see `w` in Eqn. 48 from paper\n *\n * @param[in] source_pts distribution of (columnar) source points\n * @param[in] target_pts distribution of (columnar) target points\n * @return  weight tensor with weights for pairwise correspondences in optimization objective\n */\nWeightTensor generate_weight_tensor(arma::mat const & source_pts,\n    arma::mat const & target_pts, double const & eps, double const & pw_thresh) noexcept;\n\n/**\n * @brief Find vector x that minimizes inner product <c, x> subject to bounds constraints\n * lb <= x <= ub and equality constraint A*x==b\n *\n * @param [in] c vector c in <c, x> above\n * @param [in] A matrix A in Ax==b above\n * @param [in] b vector b in Ax==b above\n * @param [in] lower_bound lower bound on (individual components of) x\n * @param [in] upper_bound upper bound on (individual components of) x\n * @param [in][out] x_opt value of x that minimizes <c, x> subject to defined constraints\n * @return\n *\n * @note Uses Google's ORTools\n */\nbool linear_programming(arma::colvec const & c, arma::mat const & A, arma::colvec const & b,\n    double const & lower_bound, double const & upper_bound, arma::colvec & x_opt) noexcept;\n}  // namespace correspondences\n", "meta": {"hexsha": "c99de1747b9df667c474deafd16028b018fba2cd", "size": 1865, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "correspondences/common/include/correspondences/common/utilities.hpp", "max_stars_repo_name": "jwdinius/nmsac", "max_stars_repo_head_hexsha": "b765be4340cf8367e1af345dc156597ce425c818", "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": "correspondences/common/include/correspondences/common/utilities.hpp", "max_issues_repo_name": "jwdinius/nmsac", "max_issues_repo_head_hexsha": "b765be4340cf8367e1af345dc156597ce425c818", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-07-19T23:38:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-14T22:36:30.000Z", "max_forks_repo_path": "correspondences/common/include/correspondences/common/utilities.hpp", "max_forks_repo_name": "jwdinius/nmsac", "max_forks_repo_head_hexsha": "b765be4340cf8367e1af345dc156597ce425c818", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T06:59:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-06T06:59:04.000Z", "avg_line_length": 38.0612244898, "max_line_length": 93, "alphanum_fraction": 0.7120643432, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.542243247222708}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\n#include <base/init.hpp>\n#include \"fft/fft2.hpp\"\n#include \"ridgelet/fold.hpp\"\n\nusing namespace std;\n\ntypedef Eigen::ArrayXXd array_t;\ntypedef Eigen::ArrayXXcd complex_array_t;\n\nint main(int argc, char *argv[])\n{\n  Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(24, 0, 1);\n\n  Eigen::Map<const array_t> xm(x.data(), 4, 6);\n  cout << \"input\"\n       << \"\\n\";\n  cout << xm << \"\\n\";\n  array_t X = xm;\n\n  array_t Y;\n  fold(Y, X, 3, 1);\n\n  cout << \"fold(X, width=3, dim=1)\"\n       << \"\\n\";\n  cout << \"Y:\\n\" << Y << \"\\n\";\n\n  array_t Y2;\n  fold(Y2, X, 2, 0);\n\n  cout << \"fold(X, width=2, dim=0)\"\n       << \"\\n\";\n  cout << \"Y:\\n\" << Y2 << \"\\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "714db0ba9290fae20156d5cbe698ae770aa2115a", "size": 693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main_test_fold.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_fold.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_fold.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": 17.7692307692, "max_line_length": 59, "alphanum_fraction": 0.5555555556, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5422432398486404}}
{"text": "#include <swr/raster.hpp>\n\n#include <iostream>\n\n#include <Eigen/LU> // Needed for .inverse()\n\n#include <tbb/blocked_range.h>\n#include <tbb/blocked_range2d.h>\n#include <tbb/enumerable_thread_specific.h>\n#include <tbb/parallel_for.h>\n\nnamespace swr {\n\nvoid rasterize_triangle(\n    const Shaders& shaders,\n    const UniformAttributes& uniform,\n    const VertexAttributes& v1,\n    const VertexAttributes& v2,\n    const VertexAttributes& v3,\n    FrameBuffer& frame_buffer)\n{\n    // Collect coordinates into a matrix and convert to canonical representation\n    Eigen::Matrix<Float, 3, 4> p;\n    p.row(0) = v1.position.array() / v1.position.w();\n    p.row(1) = v2.position.array() / v2.position.w();\n    p.row(2) = v3.position.array() / v3.position.w();\n\n    // Coordinates are in -1..1, rescale to pixel size (x,y only)\n    p.col(0) = ((p.col(0).array() + 1.0) / 2.0) * frame_buffer.rows();\n    p.col(1) = ((p.col(1).array() + 1.0) / 2.0) * frame_buffer.cols();\n\n    // Find bounding box in pixels\n    int lx = std::floor(p.col(0).minCoeff());\n    int ly = std::floor(p.col(1).minCoeff());\n    int ux = std::ceil(p.col(0).maxCoeff());\n    int uy = std::ceil(p.col(1).maxCoeff());\n\n    // Clamp to framebuffer\n    lx = std::min(std::max(lx, int(0)), int(frame_buffer.rows() - 1));\n    ly = std::min(std::max(ly, int(0)), int(frame_buffer.cols() - 1));\n    ux = std::max(std::min(ux, int(frame_buffer.rows() - 1)), int(0));\n    uy = std::max(std::min(uy, int(frame_buffer.cols() - 1)), int(0));\n\n    // Build the implicit triangle representation\n    Matrix3F A;\n    A.col(0) = p.row(0).head<3>();\n    A.col(1) = p.row(1).head<3>();\n    A.col(2) = p.row(2).head<3>();\n    A.row(2) << 1.0, 1.0, 1.0;\n\n    Matrix3F Ai = A.inverse();\n\n    // Rasterize the triangle\n    tbb::parallel_for(\n        tbb::blocked_range2d<size_t>(lx, ux + 1, ly, uy + 1),\n        [&](const tbb::blocked_range2d<size_t>& r) {\n            for (size_t i = r.rows().begin(); i < r.rows().end(); i++) {\n                for (size_t j = r.cols().begin(); j < r.cols().end(); j++) {\n                    // The pixel center is offset by 0.5, 0.5\n                    Vector3F pixel(i + 0.5, j + 0.5, 1);\n                    Vector3F b = Ai * pixel;\n                    if (b.minCoeff() >= 0) {\n                        VertexAttributes va = VertexAttributes::interpolate(\n                            v1, v2, v3, b[0], b[1], b[2]);\n                        // Only render fragments within the bi-unit cube\n                        if (va.position.z() >= -1 && va.position.z() <= 1) {\n                            FragmentAttributes frag =\n                                shaders.fragment_shader(va, uniform);\n                            shaders.blending_shader(frag, frame_buffer(i, j));\n                        }\n                    }\n                }\n            }\n        });\n}\n\nvoid rasterize_triangles(\n    const Shaders& shaders,\n    const UniformAttributes& uniform,\n    const std::vector<VertexAttributes>& vertices,\n    FrameBuffer& frame_buffer)\n{\n    // Call vertex shader on all vertices (parallel)\n    std::vector<VertexAttributes> v(vertices.size());\n    tbb::parallel_for(\n        tbb::blocked_range<size_t>(size_t(0), vertices.size()),\n        [&](const tbb::blocked_range<size_t>& r) {\n            for (size_t i = r.begin(); i < r.end(); i++) {\n                v[i] = shaders.vertex_shader(vertices[i], uniform);\n            }\n        });\n\n    tbb::enumerable_thread_specific<FrameBuffer> storage(frame_buffer);\n\n    // Call the rasterization function on every triangle\n    assert(vertices.size() % 3 == 0);\n    tbb::parallel_for(\n        tbb::blocked_range<size_t>(size_t(0), vertices.size() / 3),\n        [&](const tbb::blocked_range<size_t> r) {\n            FrameBuffer& local_frame_buffer = storage.local();\n\n            for (size_t i = r.begin(); i < r.end(); i++) {\n                rasterize_triangle(\n                    shaders, uniform, v[i * 3 + 0], v[i * 3 + 1], v[i * 3 + 2],\n                    local_frame_buffer);\n            }\n        });\n\n    // Blend the frame buffers\n    for (const FrameBuffer& local_frame_buffer : storage) {\n        tbb::parallel_for(\n            tbb::blocked_range2d<size_t>(\n                0, frame_buffer.rows(), 0, frame_buffer.cols()),\n\n            [&](const tbb::blocked_range2d<size_t>& r) {\n                for (size_t i = r.rows().begin(); i < r.rows().end(); i++) {\n                    for (size_t j = r.cols().begin(); j < r.cols().end(); j++) {\n                        shaders.blending_shader(\n                            local_frame_buffer(i, j), frame_buffer(i, j));\n                    }\n                }\n            });\n    }\n}\n\nvoid rasterize_line(\n    const Shaders& shaders,\n    const UniformAttributes& uniform,\n    const VertexAttributes& v1,\n    const VertexAttributes& v2,\n    Float line_thickness,\n    FrameBuffer& frame_buffer)\n{\n    // Collect coordinates into a matrix and convert to canonical\n    // representation\n    Eigen::Matrix<Float, 2, 4> p;\n    p.row(0) = v1.position.array() / v1.position[3];\n    p.row(1) = v2.position.array() / v2.position[3];\n\n    // Coordinates are in -1..1, rescale to pixel size (x,y only)\n    p.col(0) = ((p.col(0).array() + 1.0) / 2.0) * frame_buffer.rows();\n    p.col(1) = ((p.col(1).array() + 1.0) / 2.0) * frame_buffer.cols();\n\n    // Find bounding box in pixels, adding the line thickness\n    int lx = std::floor(p.col(0).minCoeff() - line_thickness);\n    int ly = std::floor(p.col(1).minCoeff() - line_thickness);\n    int ux = std::ceil(p.col(0).maxCoeff() + line_thickness);\n    int uy = std::ceil(p.col(1).maxCoeff() + line_thickness);\n\n    // Clamp to framebuffer\n    lx = std::min(std::max(lx, int(0)), int(frame_buffer.rows() - 1));\n    ly = std::min(std::max(ly, int(0)), int(frame_buffer.cols() - 1));\n    ux = std::max(std::min(ux, int(frame_buffer.rows() - 1)), int(0));\n    uy = std::max(std::min(uy, int(frame_buffer.cols() - 1)), int(0));\n\n    // We only need the 2d coordinates of the endpoints of the line\n    Vector2F l1(p(0, 0), p(0, 1));\n    Vector2F l2(p(1, 0), p(1, 1));\n\n    // Parametrize the line as l1 + t (l2-l1)\n    Float t = -1;\n    Float ll = (l1 - l2).squaredNorm();\n\n    // Rasterize the line\n    tbb::parallel_for(\n        tbb::blocked_range2d<size_t>(lx, ux + 1, ly, uy + 1),\n        [&](const tbb::blocked_range2d<size_t>& r) {\n            for (size_t i = r.rows().begin(); i != r.rows().end(); i++) {\n                for (size_t j = r.cols().begin(); j != r.cols().end(); j++) {\n                    // The pixel center is offset by 0.5, 0.5\n                    Vector2F pixel(i + 0.5, j + 0.5);\n\n                    if (ll == 0.0)\n                        // The segment has zero length\n                        t = 0;\n                    else {\n                        // Project p on the line\n                        t = (pixel - l1).dot(l2 - l1) / ll;\n                        // Clamp between 0 and 1\n                        t = std::fmax(0, std::fmin(1, t));\n                    }\n\n                    Vector2F pixel_p = l1 + t * (l2 - l1);\n\n                    if ((pixel - pixel_p).squaredNorm()\n                        < (line_thickness * line_thickness)) {\n                        VertexAttributes va = VertexAttributes::interpolate(\n                            v1, v2, v1, 1 - t, t, 0);\n                        // Only render fragments within the bi-unit cube\n                        if (va.position[2] >= -1 && va.position[2] <= 1) {\n                            FragmentAttributes frag =\n                                shaders.fragment_shader(va, uniform);\n                            shaders.blending_shader(frag, frame_buffer(i, j));\n                        }\n                    }\n                }\n            }\n        });\n}\n\nvoid rasterize_lines(\n    const Shaders& shaders,\n    const UniformAttributes& uniform,\n    const std::vector<VertexAttributes>& vertices,\n    Float line_thickness,\n    FrameBuffer& frame_buffer)\n{\n    // Call vertex shader on all vertices (parallel)\n    std::vector<VertexAttributes> v(vertices.size());\n    tbb::parallel_for(\n        tbb::blocked_range<size_t>(size_t(0), vertices.size()),\n        [&](const tbb::blocked_range<size_t>& r) {\n            for (size_t i = r.begin(); i < r.end(); i++) {\n                v[i] = shaders.vertex_shader(vertices[i], uniform);\n            }\n        });\n\n    tbb::enumerable_thread_specific<FrameBuffer> storage(frame_buffer);\n\n    // Call the rasterization function on every line\n    assert(vertices.size() % 2 == 0);\n    tbb::parallel_for(\n        tbb::blocked_range<size_t>(size_t(0), vertices.size() / 2),\n        [&](const tbb::blocked_range<size_t> r) {\n            FrameBuffer& local_frame_buffer = storage.local();\n\n            for (size_t i = r.begin(); i < r.end(); i++) {\n                rasterize_line(\n                    shaders, uniform, v[i * 2 + 0], v[i * 2 + 1],\n                    line_thickness, local_frame_buffer);\n            }\n        });\n\n    // Blend the frame buffers\n    for (const FrameBuffer& local_frame_buffer : storage) {\n        tbb::parallel_for(\n            tbb::blocked_range2d<size_t>(\n                0, frame_buffer.rows(), 0, frame_buffer.cols()),\n\n            [&](const tbb::blocked_range2d<size_t>& r) {\n                for (size_t i = r.rows().begin(); i < r.rows().end(); i++) {\n                    for (size_t j = r.cols().begin(); j < r.cols().end(); j++) {\n                        shaders.blending_shader(\n                            local_frame_buffer(i, j), frame_buffer(i, j));\n                    }\n                }\n            });\n    }\n}\n\nvoid framebuffer_to_uint8(\n    const FrameBuffer& frame_buffer, std::vector<uint8_t>& image)\n{\n    const int w = frame_buffer.rows();    // Image width\n    const int h = frame_buffer.cols();    // Image height\n    const int comp = 4;                   // 4 Channels Red, Green, Blue, Alpha\n    const int stride_in_bytes = w * comp; // Length of one row in bytes\n    image.resize(w * h * comp, 0);        // The image itself;\n\n    for (unsigned wi = 0; wi < w; ++wi) {\n        for (unsigned hi = 0; hi < h; ++hi) {\n            unsigned hif = h - 1 - hi;\n            image[(hi * w * 4) + (wi * 4) + 0] = frame_buffer(wi, hif).color[0];\n            image[(hi * w * 4) + (wi * 4) + 1] = frame_buffer(wi, hif).color[1];\n            image[(hi * w * 4) + (wi * 4) + 2] = frame_buffer(wi, hif).color[2];\n            image[(hi * w * 4) + (wi * 4) + 3] = frame_buffer(wi, hif).color[3];\n        }\n    }\n}\n\n} // namespace swr\n", "meta": {"hexsha": "11d0c813c936932d0e7a3334b4b55ea976ab8919", "size": 10502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/raster.cpp", "max_stars_repo_name": "zfergus/software-renderer", "max_stars_repo_head_hexsha": "97fe94bb9eb0038378484d6e7f34866cfe399389", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-01T02:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T02:10:14.000Z", "max_issues_repo_path": "src/raster.cpp", "max_issues_repo_name": "zfergus/software-renderer", "max_issues_repo_head_hexsha": "97fe94bb9eb0038378484d6e7f34866cfe399389", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/raster.cpp", "max_forks_repo_name": "zfergus/software-renderer", "max_forks_repo_head_hexsha": "97fe94bb9eb0038378484d6e7f34866cfe399389", "max_forks_repo_licenses": ["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.6102941176, "max_line_length": 80, "alphanum_fraction": 0.5192344315, "num_tokens": 2838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5421466678508493}}
{"text": "#define _USE_MATH_DEFINES\n#include <memory>\n#include <iostream>\n#include <time.h>\n#include <fstream>\n#include <cstdlib>\n#include <iomanip> \n#include <cmath>\n#include \"yaml-cpp/yaml.h\"\n#include <Eigen/Dense>\n#include \"mpc_car_batch/optim_batch.h\"\n\n\n#include \"geometry_msgs/msg/pose_array.hpp\"\n#include \"rclcpp/rclcpp.hpp\"\n// #include \"nav_msgs/msg/odometry.hpp\"\n// #include \"geometry_msgs/msg/twist.hpp\"\n// #include \"geometry_msgs/msg/vector3.hpp\"\n#include \"msgs_car/msg/controls.hpp\"\n#include \"msgs_car/msg/states.hpp\"\n\n#define MPC 0\nusing namespace std;\nusing namespace optim;\nusing std::placeholders::_1;\n\nclass MinimalPublisher : public rclcpp::Node\n{\n  public:\n        \n        ArrayXXf lane, tot_time, x_g, y_g, tot_time_up;\n        ArrayXXf x_obs_temp, y_obs_temp, vx_obs, vy_obs, old, meta_cost;\n\n        three_var PPP, PPP_up;\n        probData prob_data;\n        float x_init, y_init, v_init, psi_init, psidot_init, total_time, speed, avg_time, avg_speed;\n        float prev_v_send, prev_w_send, w0, w1, w2, w3;\n\n        bool Gotit, warm;\n\n        float min = 1000000;\n        int index, cnt, loop;\n        clock_t start, end;\n        ofstream outdata, outdata2, outdata3, outdata4;\n\n    MinimalPublisher(): Node(\"minimal_publisher\"), count_(0)\n    {\n        Gotit = false;\n        warm = true;\n\n        avg_speed = 0.0;\n        speed = 0.0;\n        total_time = 0.0;\n        avg_time = 0.0;\n        index = 0;\n        loop = 0;\n        prev_v_send = 0.0;\n        prev_w_send = 0.0;\n\n        x_init = 0.0;\n        y_init = 10.0;\n        v_init = 15.0;\n        psi_init = 0.0;\n        psidot_init = 0.0;\n\n        prob_data.t_fin = 8.0;\n        prob_data.num = 100;\n        prob_data.t = prob_data.t_fin/prob_data.num;\n        prob_data.weight_smoothness = 2.5;\n        prob_data.weight_psi = 5;\n        prob_data.maxiter = 100;\n        prob_data.num_obs = 6;\n        prob_data.v_max = 24.0;\n        prob_data.a_max = 4.0;\n        prob_data.a_obs = 5.6;\n        prob_data.b_obs = 3.0;\n        prob_data.rho_ineq = 1.0;\n        prob_data.rho_psi = 1.0;\n        prob_data.rho_nonhol = 1.0;\n        prob_data.rho_obs = 1.0;\n        prob_data.weight_smoothness_psi = 5.0;\n\n        tot_time = ArrayXXf(prob_data.num, 1);\n        tot_time.col(0).setLinSpaced(prob_data.num, 0.0, prob_data.t_fin);\n\n        PPP = compute_bernstein(tot_time, prob_data.t_fin, prob_data.num);\n        prob_data.nvar = PPP.a.cols();\n\n        //__________________________________________________________________________\n        tot_time_up = ArrayXXf((int)(prob_data.t_fin/0.008), 1);\n        tot_time_up.col(0).setLinSpaced(prob_data.t_fin/0.008, 0.0, prob_data.t_fin);\n        \n        PPP_up = compute_bernstein(tot_time_up, prob_data.t_fin, prob_data.t_fin/0.008);\n        prob_data.Pdot_upsample = PPP_up.b;\n        //__________________________________________________________________________\n        \n        prob_data.cost_smoothness = prob_data.weight_smoothness * PPP.c.transpose().matrix() * PPP.c.matrix();\n        prob_data.cost_smoothness_psi = prob_data.weight_smoothness_psi * PPP.c.transpose().matrix() * PPP.c.matrix();\n        prob_data.lincost_smoothness_psi = 0 * ones(prob_data.nvar, 1);\n\n        prob_data.A_eq = ArrayXXf(3, prob_data.nvar);\n        prob_data.A_eq_psi = ArrayXXf(4, prob_data.nvar);\n        \n        prob_data.A_eq << PPP.a.row(0), PPP.b.row(0), PPP.a.row(PPP.a.rows() - 1);\n        prob_data.A_eq_psi << PPP.a.row(0), PPP.b.row(0), PPP.a.row(PPP.a.rows() - 1), PPP.b.row(PPP.b.rows() - 1);\n\n        prob_data.A_nonhol = PPP.b;\n        prob_data.A_psi = PPP.a;\n        prob_data.A_ineq = PPP.c;\n        prob_data.A_acc = PPP.c;\n        \n        prob_data.A_obs = stack(PPP.a, PPP.a, 'v');\n        for (int i = 0; i < prob_data.num_obs - 2; i++)\n            prob_data.A_obs = stack(prob_data.A_obs, PPP.a, 'v');\n        \n\n        x_obs_temp = ArrayXXf(prob_data.num_obs, 1);\n        y_obs_temp = ArrayXXf(prob_data.num_obs, 1);\n        vx_obs = ArrayXXf(prob_data.num_obs, 1);\n        vy_obs = ArrayXXf(prob_data.num_obs, 1);\n\n        x_obs_temp = 0;\n        y_obs_temp = 0;\n        vx_obs = 0;\n        vy_obs = 0.0;\n\n        YAML::Node map = YAML::LoadFile(\"src/mpc_car_batch/config.yaml\");\n        \n        string setting = map[\"setting\"].as<string>();\n\n        prob_data.num_goal = map[\"configuration\"][setting][\"goal\"].as<float>();\n        w0 = map[\"configuration\"][setting][\"weights\"][0].as<float>();\n        w1 = map[\"configuration\"][setting][\"weights\"][1].as<float>();\n        w2 = map[\"configuration\"][setting][\"weights\"][2].as<float>();\n        w3 = map[\"configuration\"][setting][\"weights\"][3].as<float>();\n        \n        x_g = ArrayXXf(prob_data.num_goal, 1);\n        y_g = ArrayXXf(prob_data.num_goal, 1);\n\n        meta_cost = ArrayXXf(prob_data.num_goal, 9);\n        meta_cost = -1;\n\n\t\tfor(int i = 0; i < prob_data.num_goal; i++)\n        {\n            x_g(i) = map[\"configuration\"][setting][\"x_g\"][i].as<float>();\n            y_g(i) = map[\"configuration\"][setting][\"y_g\"][i].as<float>();\n            meta_cost(i, 0) = i+1;\n        }\n        // cout << x_g;\n        old = x_g;\n\n        \n        subscription_ = this->create_subscription<msgs_car::msg::States>(\n        \"ego_vehicle_obs\", 10, std::bind(&MinimalPublisher::topic_callback, this, _1));\n\n        publisher_ = this->create_publisher<msgs_car::msg::Controls>(\"ego_vehicle_cmds\", 10);\n        timer_ = this->create_wall_timer(10ms, bind(&MinimalPublisher::timer_callback, this));\n        cnt = 1;\n\n        RCLCPP_INFO(this->get_logger(),\"NODES ARE UP\");\n        // outdata.open(map[\"configuration\"][setting][\"file\"].as<string>());\n    }\n    \n  private:\n    void topic_callback(const msgs_car::msg::States::SharedPtr msg)\n    {\n       \n        x_init = msg->x[0];\n        y_init = msg->y[0];\n        v_init = sqrt(msg->vx[0] * msg->vx[0] + msg->vy[0] * msg->vy[0]);\n        psi_init = msg->psi[0];\n        psidot_init = msg->psidot; \n        \n        x_obs_temp << msg->x[1], msg->x[2], msg->x[3], msg->x[4], msg->x[5], msg->x[6];\n        y_obs_temp << msg->y[1], msg->y[2], msg->y[3], msg->y[4], msg->y[5], msg->y[6];\n        vx_obs << msg->vx[1], msg->vx[2], msg->vx[3], msg->vx[4], msg->vx[5], msg->vx[6];\n        vy_obs << msg->vy[1], msg->vy[2], msg->vy[3], msg->vy[4], msg->vy[5], msg->vy[6];\n\n        if(loop == 0)\n            prev_v_send = v_init;\n        \n        Gotit = 1;\n    }\n    void timer_callback();\n    void get_ranks();\n    rclcpp::TimerBase::SharedPtr timer_;\n    rclcpp::Subscription<msgs_car::msg::States>::SharedPtr subscription_;\n    rclcpp::Publisher<msgs_car::msg::Controls>::SharedPtr publisher_;\n    size_t count_;\n};\n\nvoid MinimalPublisher :: get_ranks()\n{\n    float v_cruise = 15.0;\n    for(int i = 0; i < prob_data.num_goal; i++)\n    {\n        meta_cost(i, 1) = (prob_data.v.row(i) - v_cruise).matrix().lpNorm<2>(); // 5\n        meta_cost(i, 2) = prob_data.res_obs.row(i).matrix().lpNorm<2>();        // 6\n        meta_cost(i, 3) = (prob_data.y.row(i) -  (-10)).matrix().lpNorm<2>(); // 7\n        meta_cost(i, 4) = (prob_data.v.row(i) - 24).matrix().lpNorm<2>();                       // 8\n        meta_cost(i, 5) = -1;\n        meta_cost(i, 6) = -1;\n        meta_cost(i, 7) = -1;\n        meta_cost(i, 8) = -1;\n    }\n    float inf = std::numeric_limits<float>::infinity();\n    for(int i = 0; i < prob_data.num_goal; i++)\n    {\n        float min0 = inf, min1 = inf, min2 = inf, min3 = inf; \n        int index0 = -1, index1 = -1, index2 = -1, index3 = -1;\n        for(int j = 0; j < prob_data.num_goal; j++)\n        {\n            if(meta_cost(j, 1) < min0 && meta_cost(j, 5) < 0)\n            {\n                min0 = meta_cost(j, 1);\n                index0 = j;\n            }\n            if(meta_cost(j, 2) < min1 && meta_cost(j, 6) < 0)\n            {\n                min1 = meta_cost(j, 2);\n                index1 = j;\n            }\n            if(meta_cost(j, 3) < min2 && meta_cost(j, 7) < 0)\n            {\n                min2 = meta_cost(j, 3);\n                index2 = j;\n            }\n            if(meta_cost(j, 4) < min3 && meta_cost(j, 8) < 0)\n            {\n                min3 = meta_cost(j, 4);\n                index3 = j;\n            }\n        }\n        meta_cost(index0, 5) = i+1; // cruise     \n        meta_cost(index1, 6) = i+1; // optimal\n        meta_cost(index2, 7) = i+1; // rightmost lane\n        meta_cost(index3, 8) = i+1; // max average velocity\n    }\n}\nvoid MinimalPublisher :: timer_callback()\n{\n    auto message = msgs_car::msg::Controls();\n    \n    if(Gotit)\n    {\n        \n        x_g = old + x_init;\n        cnt+=1;\n       \n        start = clock();\n        prob_data = mpc(prob_data, PPP, x_g, y_g, x_init, y_init, v_init, psi_init, psidot_init, x_obs_temp, y_obs_temp, \n                            vx_obs, vy_obs, warm);\n        end = clock();\n        warm = false;\n       \n        get_ranks();\n        min = 100000000;\n        index = 5;\n        // cruise = 50, 50, 0, 0\n        // righlane = 0, 50, 50, 0\n        // highspeed rightlane = 0, 50, 25, 25\n\n        //ngsim2 hsrl 0, 60, 19, 21\n        for(int i = 0; i < prob_data.num_goal; i++)\n        {\n            float cost = w0 * meta_cost(i, 5) + w1 * meta_cost(i, 6) + w2 * meta_cost(i, 7) + w3 * meta_cost(i, 8); \n                                // cruise                  optimal                   rightlane             max avg velocity\n            if( cost < min)\n            {\n                min = cost; \n                index = i;\n            }    \n        }\n        // message.w = prob_data.w_controls.row(index).leftCols(18).mean();\n        // message.v = prob_data.v_controls.row(index).leftCols(18).mean();\n        message.w = prob_data.psidot.row(index).leftCols(3).mean();\n        message.v = prob_data.v.row(index).leftCols(3).mean();\n\n        message.index = index;\n        message.goals = prob_data.num_goal;\n        loop++;\n        \n        speed += message.v;\n        total_time += double(end - start) / double(CLOCKS_PER_SEC);\n        avg_speed = speed/loop;\n        avg_time = total_time/loop;\n\n        // outdata << x_init << \" \" << y_init << \" \" << psi_init << \" \" << message.v << \" \" << message.w \n        //         << \" \" << (message.v - prev_v_send)/prob_data.t << \" \" << (message.w - prev_w_send)/prob_data.t\n        //         << \" \" << double(end - start) / double(CLOCKS_PER_SEC) << \" \" << loop << \" \" << index << endl;\n        // outdata2 << prob_data.x << \" \" << prob_data.y << endl;\n        prev_v_send = message.v;\n\t\tprev_w_send = message.w;\n\n        for(int i = 0; i < prob_data.num_goal; i++)\n        {\n            for(int j = 0; j < prob_data.num; j++)\n            {\n                geometry_msgs::msg::Pose pose;\n                pose.position.x = prob_data.x(i, j);\n                pose.position.y = prob_data.y(i, j);\n                message.batch.poses.push_back(pose);    \n            }\n        }\n        // RCLCPP_INFO(this->get_logger(),\"Time taken = %f index = %d res_obs = %f\", time_taken, index, prob_data.res_obs.matrix().lpNorm<2>());\n        RCLCPP_INFO(this->get_logger(),\"Average time = %f Average speed = %f\", avg_time, avg_speed);\n        publisher_->publish(message);\n        Gotit = false;\n    }\n    \n}\n\nint main(int argc, char * argv[])\n{\n    \n  rclcpp::init(argc, argv);\n  rclcpp::spin(std::make_shared<MinimalPublisher>());\n  rclcpp::shutdown();\n  return 0;\n}", "meta": {"hexsha": "1be7bc60b63738cee6f1bfe9b697bb1d9217f831", "size": 11319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros_ws/src/mpc_car_batch/src/main_batch.cpp", "max_stars_repo_name": "vivek-uka/Batch-Opt-Highway-Driving", "max_stars_repo_head_hexsha": "6aa10d723b437a2d598b4b5111f8282fabc09e1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2022-01-24T11:07:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T07:55:28.000Z", "max_issues_repo_path": "ros_ws/src/mpc_car_batch/src/main_batch.cpp", "max_issues_repo_name": "vivek-uka/Batch-Opt-Highway-Driving", "max_issues_repo_head_hexsha": "6aa10d723b437a2d598b4b5111f8282fabc09e1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ros_ws/src/mpc_car_batch/src/main_batch.cpp", "max_forks_repo_name": "vivek-uka/Batch-Opt-Highway-Driving", "max_forks_repo_head_hexsha": "6aa10d723b437a2d598b4b5111f8282fabc09e1c", "max_forks_repo_licenses": ["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.371875, "max_line_length": 144, "alphanum_fraction": 0.5468680979, "num_tokens": 3287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5421466678508493}}
{"text": "#define BOOST_TEST_MODULE FCL_SIMPLE\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\n#include <hpp/fcl/internal/intersect.h>\r\n#include <hpp/fcl/collision.h>\r\n#include <hpp/fcl/BVH/BVH_model.h>\r\n#include \"fcl_resources/config.h\"\r\n#include <sstream>\r\n\r\nusing namespace hpp::fcl;\r\n\r\nstatic FCL_REAL epsilon = 1e-6;\r\n\r\nstatic bool approx(FCL_REAL x, FCL_REAL y)\r\n{\r\n  return std::abs(x - y) < epsilon;\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(projection_test_line)\r\n{\r\n  Vec3f v1(0, 0, 0);\r\n  Vec3f v2(2, 0, 0);\r\n    \r\n  Vec3f p(1, 0, 0);\r\n  Project::ProjectResult res = Project::projectLine(v1, v2, p);\r\n  BOOST_CHECK(res.encode == 3);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.5));\r\n    \r\n  p = Vec3f(-1, 0, 0);\r\n  res = Project::projectLine(v1, v2, p);\r\n  BOOST_CHECK(res.encode == 1);\r\n  BOOST_CHECK(approx(res.sqr_distance, 1));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n\r\n  p = Vec3f(3, 0, 0);\r\n  res = Project::projectLine(v1, v2, p);\r\n  BOOST_CHECK(res.encode == 2);\r\n  BOOST_CHECK(approx(res.sqr_distance, 1));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1));\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(projection_test_triangle)\r\n{\r\n  Vec3f v1(0, 0, 1);\r\n  Vec3f v2(0, 1, 0);\r\n  Vec3f v3(1, 0, 0);\r\n\r\n  Vec3f p(1, 1, 1);\r\n  Project::ProjectResult res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 7);\r\n  BOOST_CHECK(approx(res.sqr_distance, 4/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 1/3.0));\r\n  \r\n  p = Vec3f(0, 0, 1.5);\r\n  res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 1);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n\r\n  p = Vec3f(1.5, 0, 0);\r\n  res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 4);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 1));\r\n\r\n  p = Vec3f(0, 1.5, 0);\r\n  res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 2);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n\r\n  p = Vec3f(1, 1, 0);\r\n  res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 6);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0.5));\r\n\r\n  p = Vec3f(1, 0, 1);\r\n  res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 5);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0.5));\r\n\r\n  p = Vec3f(0, 1, 1);\r\n  res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 3);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(projection_test_tetrahedron)\r\n{\r\n  Vec3f v1(0, 0, 1);\r\n  Vec3f v2(0, 1, 0);\r\n  Vec3f v3(1, 0, 0);\r\n  Vec3f v4(1, 1, 1);\r\n\r\n  Vec3f p(0.5, 0.5, 0.5);\r\n  Project::ProjectResult res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 15);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0.25));\r\n\r\n  p = Vec3f(0, 0, 0);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 7);\r\n  BOOST_CHECK(approx(res.sqr_distance, 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n  p = Vec3f(0, 1, 1);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 11);\r\n  BOOST_CHECK(approx(res.sqr_distance, 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 1/3.0));\r\n\r\n  p = Vec3f(1, 1, 0);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 14);\r\n  BOOST_CHECK(approx(res.sqr_distance, 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 1/3.0));\r\n\r\n  p = Vec3f(1, 0, 1);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 13);\r\n  BOOST_CHECK(approx(res.sqr_distance, 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 1/3.0));\r\n\r\n  p = Vec3f(1.5, 1.5, 1.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 8);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.75));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 1));\r\n\r\n  p = Vec3f(1.5, -0.5, -0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 4);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.75));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 1));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n  p = Vec3f(-0.5, -0.5, 1.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 1);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.75));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n  p = Vec3f(-0.5, 1.5, -0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 2);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.75));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n  p = Vec3f(0.5, -0.5, 0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 5);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n  p = Vec3f(0.5, 1.5, 0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 10);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0.5));\r\n\r\n  p = Vec3f(1.5, 0.5, 0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 12);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0.5));\r\n    \r\n  p = Vec3f(-0.5, 0.5, 0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 3);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n  p = Vec3f(0.5, 0.5, 1.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 9);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0.5));\r\n    \r\n  p = Vec3f(0.5, 0.5, -0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 6);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n}\r\n", "meta": {"hexsha": "b9ec455daea2bc7df9a0e00104c018d23fcfc78d", "size": 9533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/simple.cpp", "max_stars_repo_name": "lmontaut/hpp-fcl", "max_stars_repo_head_hexsha": "1502ae3a14e4d48a3c43413209765212005a96ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 59.0, "max_stars_repo_stars_event_min_datetime": "2016-02-18T09:48:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:02:50.000Z", "max_issues_repo_path": "test/simple.cpp", "max_issues_repo_name": "lmontaut/hpp-fcl", "max_issues_repo_head_hexsha": "1502ae3a14e4d48a3c43413209765212005a96ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 171.0, "max_issues_repo_issues_event_min_datetime": "2015-07-04T08:27:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T21:21:40.000Z", "max_forks_repo_path": "test/simple.cpp", "max_forks_repo_name": "jcarpent/hpp-fcl", "max_forks_repo_head_hexsha": "1d1fb1d5e7c930a31276a46a53961aee1b6542e0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2015-07-03T13:05:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T12:41:53.000Z", "avg_line_length": 37.6798418972, "max_line_length": 78, "alphanum_fraction": 0.6747089059, "num_tokens": 3217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5421442862754073}}
{"text": "#define BOOST_TEST_MODULE \"test_static_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 \"../src/Vector.hpp\"\ntemplate<int N>\nusing VectorNd = ax::Vector<double, N>;\n\n#include \"test_Defs.hpp\"\nusing ax::test::seed;\nusing ax::test::tolerance;\n\n#include <random>\n\nBOOST_AUTO_TEST_CASE(VectorNd_Constructable)\n{\n    const VectorNd<10> vec;\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec[i], 0e0);\n\n    const VectorNd<10> vec_1(1e0);\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec_1[i], 1e0);\n\n    const VectorNd<10> vec_cp_0(vec_1);\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec_cp_0[i], 1e0);\n\n    const VectorNd<10> vec_cp_1 = vec_1;\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec_cp_1[i], 1e0);\n\n    const VectorNd<10> vec_2(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec_2[i], static_cast<double>(i));\n}\n\nBOOST_AUTO_TEST_CASE(VectorNd_Add)\n{\n    const VectorNd<10> vec1(1e0);\n    const VectorNd<10> vec2(2e0);\n    const VectorNd<10> vec3(vec1 + vec2);\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec3[i], 3e0);\n\n    VectorNd<10> vec4;\n    vec4 = vec1 + vec2;\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec4[i], 3e0);\n\n    VectorNd<10> vec5;\n    vec5 += vec1;\n    vec5 += vec2;\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec5[i], 3e0);\n}\n\nBOOST_AUTO_TEST_CASE(VectorNd_Sub)\n{\n    const VectorNd<10> vec1(3e0);\n    const VectorNd<10> vec2(2e0);\n    const VectorNd<10> vec3(vec1 - vec2);\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec3[i], 1e0);\n\n    VectorNd<10> vec4;\n    vec4 = vec1 - vec2;\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec4[i], 1e0);\n\n    VectorNd<10> vec5(vec1);\n    vec5 -= vec2;\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec5[i], 1e0);\n}\n\nBOOST_AUTO_TEST_CASE(VectorNd_Scalar_multiple)\n{\n    const VectorNd<10> vec1(1e0);\n    const VectorNd<10> vec2(2e0 * vec1);\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec2[i], 2e0);\n\n    const VectorNd<10> vec3(vec1 * 2e0);\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec3[i], 2e0);\n\n    VectorNd<10> vec4;\n    vec4 = vec1 * 2e0;\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec4[i], 2e0);\n\n    vec4 = 2e0 * vec1;\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec4[i], 2e0);\n\n    VectorNd<10> vec5(vec1);\n    vec5 *= 2e0;\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec5[i], 2e0);\n}\n\nBOOST_AUTO_TEST_CASE(VectorNd_Scalar_division)\n{\n    const VectorNd<10> vec1(2e0);\n    const VectorNd<10> vec2(vec1 / 2e0);\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec2[i], 1e0);\n\n    VectorNd<10> vec3;\n    vec3 = vec1 / 2e0;\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec3[i], 1e0);\n\n    VectorNd<10> vec4(vec1);\n    vec4 /= 2e0;\n\n    for(std::size_t i=0; i<10; ++i)\n        BOOST_CHECK_EQUAL(vec4[i], 1e0);\n}\n\nBOOST_AUTO_TEST_CASE(VectorNd_dot_product)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    for(auto i=0; i<100; ++i)\n    {\n        std::array<double, 10> v1;\n        for(std::size_t i=0; i<10; ++i)\n            v1.at(i) = randreal(mt);\n\n        std::array<double, 10> v2;\n        for(std::size_t i=0; i<10; ++i)\n            v2.at(i) = randreal(mt);\n\n        const VectorNd<10> vec1(v1);\n        const VectorNd<10> vec2(v2);\n\n        double dot_product = 0e0;\n        for(std::size_t i=0; i<10; ++i)\n            dot_product += v1.at(i) * v2.at(i);\n\n        BOOST_CHECK_CLOSE_FRACTION(dot_prod(vec1, vec2), dot_product, tolerance);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(VectorNd_length)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    for(auto i=0; i<100; ++i)\n    {\n        std::array<double, 10> v1;\n        for(std::size_t i=0; i<10; ++i)\n            v1.at(i) = randreal(mt);\n\n        const VectorNd<10> vec1(v1);\n\n        double lensq = 0e0;\n        for(std::size_t i=0; i<10; ++i)\n            lensq += v1.at(i) * v1.at(i);\n\n        BOOST_CHECK_CLOSE_FRACTION(len_square(vec1), lensq, tolerance);\n        BOOST_CHECK_CLOSE_FRACTION(length(vec1), std::sqrt(lensq), tolerance);\n\n        BOOST_CHECK_CLOSE_FRACTION(len_square(vec1), dot_prod(vec1, vec1), tolerance);\n    }\n}\n", "meta": {"hexsha": "c654739652b021b30a3bf0389862285ff4772884", "size": 4551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_static_vector.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_static_vector.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_static_vector.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": 23.5803108808, "max_line_length": 86, "alphanum_fraction": 0.6033838717, "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.5421442849062376}}
{"text": "\n#include <NTL/ZZ.h>\n\nNTL_CLIENT\n\n#define CHECK(x) do { if (!(x)) { cerr << \"FAIL\\n\"; return -1; } } while(0)\n\nint main()\n{\n   ZZ seed;\n   RandomLen(seed, 30);\n   SetSeed(seed);\n   cerr << \"\\nseed=\" << seed << \"\\n\";\n\n   cerr << \"\\nvalidating RandomLen...\";\n   for (long i = 1; i < 10000; i++) {\n      ZZ x;\n      RandomLen(x, i);\n      CHECK(x.validate() && NumBits(x) == i);\n   }\n\n   cerr << \"\\nvalidating basic arithmetic...\";\n   for (long i = 0; i < 200000; i++) {\n      long a_len = RandomBnd(8000)+5;\n      long b_len = RandomBnd(8000)+5;\n      long c_len = RandomBnd(8000)+5;\n      long d_len = RandomBnd(8000)+5;\n\n      ZZ a, b, c, d;\n      RandomLen(a, a_len);\n      RandomLen(b, b_len);\n      RandomLen(c, c_len);\n      RandomLen(d, d_len);\n\n      ZZ t1, t2;\n      t1 = (a-b)*(c-d);\n      t2 = a*c - a*d - b*c + b*d; \n      CHECK(t1.validate() && t2.validate() && t1 == t2);\n\n      long p = 7919;\n\n      long d1 = rem(t1, p);\n      long d2 = MulMod(rem(a-b, p), rem(c-d, p), p);\n      CHECK(d1 == d2);\n   }\n\n   cerr << \"\\nvalidating DivRem...\";\n   for (long i = 0; i < 200000; i++) {\n      long b_len = RandomBnd(8000)+5;\n      long q_len = RandomBnd(8000)+5;\n\n      ZZ a, b, q, r, q1, r1;\n      RandomLen(b, b_len);\n      RandomLen(q, q_len);\n      RandomBnd(r, b);\n      a = b*q + r;\n     \n      DivRem(q1, r1, a, b);\n\n      CHECK(q1.validate() && r1.validate() && q == q1 && r == r1);\n   }\n\n   cerr << \"\\nvalidating squaring...\";\n   for (long i = 0; i < 200000; i++) {\n      long a_len = RandomBnd(8000)+5;\n\n      ZZ a, b, a1, c;\n      RandomLen(a, a_len);\n\n      sqr(b, a);\n      a1 = a;\n      mul(c, a, a1);\n\n      CHECK(b.validate() && c.validate() && b == c);\n   }\n\n   cerr << \"\\nvalidating SqrRoot...\";\n   for (long i = 0; i < 200000; i++) {\n      long a_len = RandomBnd(8000)+5;\n\n      ZZ a, b;\n      RandomLen(a, a_len);\n\n      SqrRoot(b, a);\n      CHECK(b.validate() && b*b <= a && (b+1)*(b+1) > a);\n   }\n\n\n   cerr << \"\\nvalidating shifts...\";\n   for (long i = 0; i < 200000; i++) {\n      long a_len = RandomBnd(5000)+5;\n      long shamt = RandomBnd(a_len+100);\n\n      ZZ a;\n      RandomLen(a, a_len);\n\n      ZZ t = ZZ(1);\n      for (long k = 0; k < shamt; k++) t += t;\n\n      ZZ xL, xR; \n      LeftShift(xL, a, shamt);\n      RightShift(xR, a, shamt);\n\n      CHECK(xL.validate() && xR.validate());\n      CHECK(xL == a*t && xR == a/t);\n   }\n\n\n   cerr << \"\\nvalidating Preconditioned Remainder...\";\n   for (long i = 0; i < 1000000; i++) {\n      sp_ZZ_reduce_struct red_struct;\n\n      long p_len = RandomBnd(NTL_SP_NBITS-1)+2;\n      long p = RandomLen_long(p_len);\n\n      long a_len = RandomBnd(30000)+5;\n      ZZ a;\n      RandomLen(a, a_len);\n\n\n      red_struct.build(p);\n      long r1 = red_struct.rem(a);\n      long r2 = rem(a, p);\n\n      CHECK(r1 == r2);\n   }\n\n   cerr << \"\\nvalidating MulAddTo...\";\n   for (long i = 0; i < 1000000; i++) {\n      long a_len = RandomBnd(4000)+5;\n      long b_len = RandomBnd(4000)+5;\n      long c_len = RandomBnd(4000)+5;\n      long d_len = RandomBnd(4000)+5;\n\n      ZZ a, b, c, d;\n      RandomLen(a, a_len);\n      RandomLen(b, b_len);\n      RandomLen(c, c_len);\n      RandomLen(d, d_len);\n\n      ZZ t1, t2;\n      t1 = a-b;\n      t2 = c-d;\n\n      long s_len, s;\n      s_len = RandomBnd(NTL_NSP_NBITS)+1;\n      s = RandomLen_long(s_len);\n      if (RandomBnd(2)) s = -s;\n\n      ZZ r1, r2;\n      r1 = t1;\n      MulAddTo(r1, t2, s);\n\n      r2 = t1 + t2*s;\n      CHECK(r1.validate() && r2.validate() && r1 == r2);\n   }\n\n   cerr << \"\\nvalidating GCD...\";\n   for (long i = 0; i < 100000; i++) {\n      long a_len = RandomBnd(4000)+5;\n      long b_len = RandomBnd(4000)+5;\n      long c_len = RandomBnd(500)+1;\n\n      ZZ a, b, c;\n      RandomLen(a, a_len);\n      RandomLen(b, b_len);\n      RandomLen(c, c_len);\n\n      a *= c;\n      b *= c;\n\n      ZZ d, s, t, d1;\n\n      XGCD(d, s, t, a, b);\n      GCD(d1, a, b);\n\n      CHECK(d.validate() && s.validate() && t.validate() && d1.validate());\n      CHECK(d == d1 && d == a*s + b*t);\n      CHECK(divide(a, d) && divide(b, d)); \n   }\n\n   cerr << \"\\nvalidating InvMod...\";\n   for (long i = 0; i < 100000; i++) {\n      long n_len = RandomBnd(4000)+5;\n      \n      ZZ a, n, x;\n      RandomLen(n, n_len);\n      RandomBnd(a, n);\n\n      long r = InvModStatus(x, a, n);\n      CHECK((r == 0 && (x * a) % n == 1) || (r == 1 && x != 1 && x == GCD(a, n)) );\n   }\n\n   cerr << \"\\nvalidating RatRecon...\";\n\n   // This exercises RatRecon using the example from Section 4.6.1\n   // in A Computational Introduction to Number Theory\n\n   for (long i = 0; i < 100000; i++) {\n      long m_len = RandomBnd(4000)+5;\n\n      ZZ m;\n      RandomLen(m, m_len);\n\n      ZZ t;\n      RandomBnd(t, m);\n      t += 1;\n\n      ZZ s;\n      RandomBnd(s, t);\n\n      ZZ bnd = 2*m*m;\n\n      long k = 0;\n      ZZ ten_k = ZZ(1);\n      while (ten_k <= bnd) { ten_k *= 10; k++; } \n\n      ZZ z = (s*ten_k)/t;\n\n      ZZ a, r, b;\n      long res = ReconstructRational(r, b, z, ten_k, m, m); \n\n      CHECK(res == 1);\n\n      a = (b*z - r)/ten_k;\n      CHECK(a*t == b*s);\n   }\n\n   cerr << \"\\n\";\n\n   return 0;\n}\n", "meta": {"hexsha": "b8256fceeada2abb38e6053d0806543c9d3c1842", "size": 5045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "android/jni/ntl/src/ZZTest.cpp", "max_stars_repo_name": "AnthonyTudorov/PALISADE-SizeOf-Fork", "max_stars_repo_head_hexsha": "05e9903da0971933adb1ba0b9c98398c9722a45c", "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": "android/jni/ntl/src/ZZTest.cpp", "max_issues_repo_name": "AnthonyTudorov/PALISADE-SizeOf-Fork", "max_issues_repo_head_hexsha": "05e9903da0971933adb1ba0b9c98398c9722a45c", "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": "android/jni/ntl/src/ZZTest.cpp", "max_forks_repo_name": "AnthonyTudorov/PALISADE-SizeOf-Fork", "max_forks_repo_head_hexsha": "05e9903da0971933adb1ba0b9c98398c9722a45c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-24T13:38:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-24T13:38:28.000Z", "avg_line_length": 21.652360515, "max_line_length": 83, "alphanum_fraction": 0.4836471754, "num_tokens": 1790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.5421442816774679}}
{"text": "#ifndef INCLUDED_STDDEFX\n#include \"stddefx.h\"\n#define INCLUDED_STDDEFX\n#endif\n\n#ifndef INCLUDED_BOOST_MATH_SPECIAL_FUNCTIONS_ROUND\n#include <boost/math/special_functions/round.hpp>\n#define INCLUDED_BOOST_MATH_SPECIAL_FUNCTIONS_ROUND\n#endif\n\n#ifndef INCLUDED_GEOM_SIZE\n#include \"geom_size.h\"\n#define INCLUDED_GEOM_SIZE\n#endif\n\n#ifndef INCLUDED_GEOM_RECTANGLE\n#include \"geom_rectangle.h\"\n#define INCLUDED_GEOM_RECTANGLE\n#endif\n\n#ifndef INCLUDED_GEOM_UTIL\n#include \"geom_util.h\"\n#define INCLUDED_GEOM_UTIL\n#endif\n\n\n\n/*!\n  This function returns a rectangle based on the size of \\a maxSize and the\n  ratio of \\a width and \\a height. The new rectangle will have the same aspect\n  as \\a maxSize, but might be different in size.\n*/\ngeom_Size<int> geom_Util::adjustWidthOrHeight(const geom_Size<int> &maxSize,\n                                         double width, double height)\n{\n  geom_Size<int> adjustedSize(maxSize);\n\n  double widthRatio  = maxSize.getWidth()  / width;\n  double heightRatio = maxSize.getHeight() / height;\n\n  widthRatio < heightRatio\n    ? adjustedSize.setHeight(static_cast<int>(\n                   maxSize.getWidth() * height / width))\n    : adjustedSize.setWidth(static_cast<int>(\n                   maxSize.getHeight() * width / height));\n\n  return adjustedSize;\n}\n\n\n\n/*!\n  This function returns a rectangle based on the size of \\a size and the ratio\n  of \\a width and \\a height. The new rectangle will have the same aspect as\n  \\a widht and \\a height. The size of \\a size will be adjusted (enlarged) to\n  meet these requirements.\n*/\ngeom::Rectangle<int> geom_Util::reAspect(const geom::Rectangle<int> &size,\n                                        double width, double height)\n{\n  geom::Rectangle<int> newSize = size;\n  double widthRatio           = width  / (double)size.width();\n  double heightRatio          = height / (double)size.height();\n\n  if(widthRatio < heightRatio)\n  {\n    int newHeight = boost::math::iround((size.width() * height) / width);\n    newSize.setHeight(newHeight); \n  }\n  else\n  {\n    int newWidth = boost::math::iround((size.height() * width) / height);\n    newSize.setWidth(newWidth); \n  }\n\n  return newSize;\n}\n\n", "meta": {"hexsha": "934ebe29ffa3b0710643987eeae54dc81dc4862c", "size": 2156, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeom/geom_util.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeom/geom_util.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeom/geom_util.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["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.2911392405, "max_line_length": 78, "alphanum_fraction": 0.6943413729, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5421442724815886}}
{"text": "#pragma once\n// matrix_generators.hpp: generators for special matrices\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#include <cstdint>\n#include <random>\n#include <algorithm>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <universal/functions/binomial.hpp>\n\nnamespace sw {\nnamespace hprblas {\n\n// fill a dense matrix with random values between [lowerbound, upperbound]\ntemplate <typename Matrix>\nvoid uniform_rand(Matrix& A, double lowerbound = 0.0, double upperbound = 1.0)\n{\n\t// Use random_device to generate a seed for Mersenne twister engine.\n\tstd::random_device rd{};\n\t// Use Mersenne twister engine to generate pseudo-random numbers.\n\tstd::mt19937 engine{ rd() };\n\t// \"Filter\" MT engine's output to generate pseudo-random double values,\n\t// **uniformly distributed** on the closed interval [lowerbound, upperbound].\n\t// (Note that the range is [inclusive, inclusive].)\n\tstd::uniform_real_distribution<double> dist{ lowerbound, upperbound };\n\t// Pattern to generate pseudo-random number.\n\t// double rnd_value = dist(engine);\n\n\ttypedef typename mtl::Collection<Matrix>::value_type    value_type;\n\ttypedef typename mtl::Collection<Matrix>::size_type     size_type;\n\n\t// inserters add to the elements, so we need to set the value to 0 before we begin\n\tA = 0.0;\n\t{ // extra block unfortunately needed for VS2013\n\t\t// Create inserter for matrix m\n\t\tmtl::mat::inserter<Matrix> ins(A, num_cols(A));\n\n\t\t// generate and insert random values in A\n\t\tfor (size_type r = 0; r < num_rows(A); r++) {\n\t\t\tfor (size_type c = 0; c < num_cols(A); c++) {\n\t\t\t\tins[r][c] << value_type(dist(engine));\n\t\t\t}\n\t\t}\n\t\t// Destructor of ins sets final state of m\n\t}\n}\n\n// create a dense matrix with random values between [lowerbound, upperbound]\ntemplate<typename Scalar>\nmtl::mat::dense2D<Scalar> uniform_rand(size_t m, size_t n, double lowerbound = 0.0, double upperbound = 1.0) {\n\tmtl::mat::dense2D<Scalar> A(m, n);\n\tuniform_rand(A, lowerbound, upperbound);\n\treturn A;\n}\n\n// fill a dense MTL matrix with random values between [lowerbound, upperbound]\ntemplate <typename Matrix>\nvoid uniform_rand_sorted(Matrix& A, double lowerbound = 0.0, double upperbound = 1.0)\n{\n\t// Use random_device to generate a seed for Mersenne twister engine.\n\tstd::random_device rd{};\n\t// Use Mersenne twister engine to generate pseudo-random numbers.\n\tstd::mt19937 engine{ rd() };\n\t// \"Filter\" MT engine's output to generate pseudo-random double values,\n\t// **uniformly distributed** on the closed interval [lowerbound, upperbound].\n\t// (Note that the range is [inclusive, inclusive].)\n\tstd::uniform_real_distribution<double> dist{ lowerbound, upperbound };\n\t// Pattern to generate pseudo-random number.\n\t// double rnd_value = dist(engine);\n\n\ttypedef typename mtl::Collection<Matrix>::value_type    value_type;\n\ttypedef typename mtl::Collection<Matrix>::size_type     size_type;\n\n\t// generate a good set of randoms\n\tstd::vector<value_type> v(size(A));\n\tfor (size_type r = 0; r < num_rows(A); ++r) {\n\t\tfor (size_type c = 0; c < num_cols(A); ++c) {\n\t\t\tv.push_back(value_type(dist(engine)));\n\t\t}\n\t}\n\t// sort them so that we have better control over the scale of each element in a row vector\n\tsort(v.begin(), v.end(), std::greater<value_type>());\n\n\t// for each row minus the last column, calculate the sum of elements without rounding\n\tsw::unum::posit<value_type::nbits, value_type::es> one(1), p;\n\tfor (size_type r = 0; r < num_rows(A); ++r) {\n\t\tsw::unum::quire<value_type::nbits, value_type::es> q1, q2;\n\t\tsize_type lastElement = num_cols(A) - 1;\n\t\tfor (size_type c = 0; c < lastElement; ++c) {\n\t\t\tq1 += sw::unum::quire_mul(one, v[r*num_cols(A) + c]);\n\t\t}\n\t\t// truncate the value in the quire\n\t\tconvert(q1.to_value(), p);\n\t\t// calculate the difference between the truncated and the non-truncated quire values\n\t\tq2 = p;\n//\t\t\t\tstd::cout << \"q1 :\" << q1 << std::endl;\n//\t\t\t\tstd::cout << \"q2 :\" << q2 << std::endl;\n\t\tq2 -= q1;\n\t\tconvert(q2.to_value(), p);\n//\t\t\t\tstd::cout << \"Residual is: \" << double(p) << std::endl;\n//\t\tif (p.iszero()) p = one;\n\t\tv[r*num_cols(A) + lastElement] = p;\n\t}\n\n\n\t// inserters add to the elements, so we need to set the value to 0 before we begin\n\tA = 0;\n\t{ // extra block unfortunately needed for VS2013\n\t\t// Create inserter for matrix m\n\t\tmtl::mat::inserter<Matrix> ins(A, num_cols(A));\n\n\t\t// insert sorted values in A\n\t\tsize_type i = 0;\n\t\tfor (size_type r = 0; r < num_rows(A); r++) {\n\t\t\tfor (size_type c = 0; c < num_cols(A); c++) {\n\t\t\t\tins[r][c] << v[i++];\n\t\t\t}\n\t\t}\n\t\t// Destructor of ins sets final state of m\n\t}\n}\n\n// fill a dense MTL matrix with diagonally dominant random values between [lowerbound, upperbound]\ntemplate<typename Matrix>\nvoid uniform_rand_diagonally_dominant(Matrix& A, double lowerbound = 0.0, double upperbound = 1.0) {\n\t// generate off-diagonal entries, calculate the sum, scale to upperbound, and set diagonal entry to slightly larger\n\n\t// Use random_device to generate a seed for Mersenne twister engine.\n\tstd::random_device rd{};\n\t// Use Mersenne twister engine to generate pseudo-random numbers.\n\tstd::mt19937 engine{ rd() };\n\t// \"Filter\" MT engine's output to generate pseudo-random double values,\n\t// **uniformly distributed** on the closed interval [lowerbound, upperbound].\n\t// (Note that the range is [inclusive, inclusive].)\n\tstd::uniform_real_distribution<double> dist{ lowerbound, upperbound };\n\t// Pattern to generate pseudo-random number.\n\t// double rnd_value = dist(engine);\n\n\ttypedef typename mtl::Collection<Matrix>::value_type    value_type;\n\ttypedef typename mtl::Collection<Matrix>::size_type     size_type;\n\n\t// no need to null A as each element is assigned explicitely\n\tfor (size_type r = 0; r < num_rows(A); ++r) {\n\t\t// generate a random vector of N\n\t\tsize_type N = num_cols(A);\n\t\tmtl::dense_vector<value_type> v(N);\n\t\tfor (size_type c = 0; c < N; ++c) {\n\t\t\tv[c] = value_type(dist(engine));\n\t\t}\n\t\t// add the sum of the other row elements to the diagonal\n\t\tfor (size_type c = 0; c < N; ++c) {\n\t\t\tif (r != c) v[r] += v[c];\n\t\t}\n\t\tvalue_type factor = v[r] / upperbound;\n\t\tfor (size_type c = 0; c < N; ++c) {\n\t\t\tA[r][c] = v[c] / factor;\n\t\t}\n\t}\n}\n\n// Random Orthogonal Matrices\n\n/*\nStandard methods for generating random orthogonal matrices with Haar distribution \nare based on the method of Heiberger (1978). With this method, an (n x\u0002 n) matrix A is\nfirst generated with entries xij \u0018~ Normal(0; 1). Then a QR factorization (X = QR) is computed. \nThis method provides a random Q with correct distribution.\n*/\ntemplate<typename Matrix>\nvoid uniform_random_orthogonal_Heiberger(Matrix& Q) {\n\t// Use random_device to generate a seed for Mersenne twister engine.\n\tstd::random_device rd{};\n\t// Use Mersenne twister engine to generate pseudo-random numbers.\n\tstd::mt19937 engine{ rd() };\n\t// \"Filter\" MT engine's output to generate pseudo-random double values,\n\t// **uniformly distributed** on the closed interval [lowerbound, upperbound].\n\t// (Note that the range is [inclusive, inclusive].)\n\tstd::uniform_real_distribution<double> dist{ 0.0, 1.0 };\n\t// Pattern to generate pseudo-random number.\n\t// double rnd_value = dist(engine);\n\n\ttypedef typename mtl::Collection<Matrix>::value_type    value_type;\n\ttypedef typename mtl::Collection<Matrix>::size_type     size_type;\n\tMatrix A(mtl::mat::num_rows(Q), mtl::mat::num_cols(Q));\n\tMatrix R(mtl::mat::num_rows(Q), mtl::mat::num_cols(Q));\n\n\t// fill X with elements from Normal(0,1)\n\t// inserters add to the elements, so we need to set the value to 0 before we begin\n\tA = 0.0;\n\t{ // extra block unfortunately needed for VS2013\n\t\t// Create inserter for matrix A\n\t\tmtl::mat::inserter<Matrix> ins(A, num_cols(A));\n\n\t\t// insert random values in A\n\t\tfor (size_type r = 0; r < num_rows(A); r++) {\n\t\t\tfor (size_type c = 0; c < num_cols(A); c++) {\n\t\t\t\tins[r][c] << value_type(dist(engine));\n\t\t\t}\n\t\t}\n\t\t// Destructor of ins sets final state of A\n\t}\n\t// QR method to generate orthonormal matrix Q\n\tmtl::mat::qr(A, Q, R);\n\tstd::cout << A << std::endl;\n\tstd::cout << Q << std::endl;\n\tstd::cout << R << std::endl;\n}\n/*\nC.3: Generating a Random Matrix with Specified Eigenvalues\nGenerate random orthogonal matrix G. W. Stewart (1980).\n\nstart RandOrthog(n);\nA = I(n); // identity matrix \nd = j(n, 1, 0);\nd[n] = sgn(RndNormal(1, 1)); // +/- 1 \ndo k = n - 1 to 1 by - 1;\n\t// generate random Householder transformation \n\tx = RndNormal(n - k + 1, 1); // column vector from N(0,1) \n\ts = sqrt(x[##]); // norm(x) \n\tsgn = sgn(x[1]);\n\ts = sgn*s;\n\td[k] = -sgn;\n\tx[1] = x[1] + s;\n\tbeta = s*x[1];\n\t// apply the Householder transformation to A \n\ty = x`*A[k:n, ];\n\tA[k:n, ] = A[k:n, ] - x*(y / beta);\nend;\nA = d # A; // change signs of i_th row when d[i]=-1 \nreturn(A);\nfinish;\n\n// helper functions \n// return matrix of same size as A with\n// m[i,j]= {  1 if A[i,j]>=0\n//         { -1 if A[i,j]< 0\n// Similar to the SIGN function, except SIGN(0)=0 \nstart sgn(A);\n\treturn(choose(A >= 0, 1, -1));\nfinish;\n\n// return (r x c) matrix of standard normal variates \nstart RndNormal(r, c);\n\tx = j(r, c);\n\tcall randgen(x, \"Normal\");\n\treturn(x);\nfinish;\n\n// The following statements call the RANDORTHOG function to generate a random 4x4 orthogonal matrix.\ncall randseed(1);\nQ = RandOrthog(4);\nprint(Q);\n*/\ntemplate<typename Matrix>\nvoid uniform_rand_orthogonal(Matrix& A) {\n\n}\n\n//\n// fill a dense upper-triangular matrix with elements: [i][j] = 0.5 + (1 + j - i)*0.5\ntemplate <typename Matrix>\nvoid fill_U(Matrix& A, double lowerbound = 0.0, double upperbound = 1.0)\n{\n\tusing namespace mtl;\n\ttypedef typename Collection<Matrix>::value_type    value_type;\n\ttypedef typename Collection<Matrix>::size_type     size_type;\n\n\t// inserters add to the elements, so we need to set the value to 0 before we begin\n\tA = 0.0;\n\t{ // extra block unfortunately needed for VS2013\n\t\t// Create inserter for matrix m\n\t\tmat::inserter<Matrix> ins(A, num_cols(A));\n\n\t\t// generate and insert random values in A\n\t\tfor (size_type r = 0; r < num_rows(A); r++) {\n\t\t\tfor (size_type c = r; c < num_cols(A); c++) {\n\t\t\t\tins[r][c] << value_type(0.5) + value_type(1 + c - r)*value_type(0.5);\n\t\t\t\tins[r][c] << value_type(1.0);\n\t\t\t}\n\t\t}\n\t\t// Destructor of ins sets final state of m\n\t}\n}\n\n// fill a dense lower-triangular matrix with elements: [i][j] = 0.5 + (1 + i - j)*0.5\ntemplate <typename Matrix>\nvoid fill_L(Matrix& A, double lowerbound = 0.0, double upperbound = 1.0)\n{\n\tusing namespace mtl;\n\ttypedef typename Collection<Matrix>::value_type    value_type;\n\ttypedef typename Collection<Matrix>::size_type     size_type;\n\n\t// inserters add to the elements, so we need to set the value to 0 before we begin\n\tA = 0.0;\n\t{ // extra block unfortunately needed for VS2013\n\t\t// Create inserter for matrix m\n\t\tmat::inserter<Matrix> ins(A, num_cols(A));\n\n\t\t// generate and insert random values in A\n\t\tfor (size_type r = 0; r < num_rows(A); r++) {\n\t\t\tfor (size_type c = 0; c <= r; c++) {\n\t\t\t\tins[r][c] << value_type(0.5) + value_type(1 + r - c)*value_type(0.5);\n\t\t\t\tins[r][c] << value_type(1.0);\n\n\t\t\t}\n\t\t}\n\t\t// Destructor of ins sets final state of m\n\t}\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////\n/// Hilbert matrices\n\n// Greatest Common Divisor of two numbers, a and b\ntemplate<typename IntegerType>\nIntegerType gcd(IntegerType a, IntegerType b)\n{\n\tif (b == IntegerType(0))\treturn a;\n\treturn gcd(b, a % b);\n}\n\n// Least Common Multiple of n numbers\ntemplate<typename IntegerType>\nIntegerType findlcm(const std::vector<IntegerType>& v)\n{\n\tIntegerType lcm = v[0];\n\tfor (size_t i = 1; i < v.size(); i++) {\n\t\tlcm = (v[i] * lcm) / gcd(v[i], lcm);\n\t}\n\treturn lcm;\n}\n\n// Generate the scaling factor of a Hilbert matrix so that its elements are representable\n// that is, no infinite expensions of rationals, such as 1/3, 1/10, etc.\ntemplate<typename IntegerType>\nIntegerType HilbertScalingFactor(IntegerType N) {\n\tstd::vector<IntegerType> coef;\n\tfor (IntegerType i = 2; i <= N; ++i) coef.push_back(i);\n\tfor (IntegerType j = 2; j <= N; ++j) coef.push_back(N + j - IntegerType(1));\n\treturn findlcm(coef);\n}\n\n// Generate a scaled/unscaled Hilbert matrix depending on the bScale parameter\ntemplate<typename Scalar>\nsize_t GenerateHilbertMatrix(mtl::mat::dense2D<Scalar>& M, bool bScale = true) {\n\tassert(M.num_rows() == M.num_cols());\n\tsize_t N = M.num_rows();\n\tsize_t lcm = HilbertScalingFactor(N); // always calculate the Least Common Multiplier\n\tScalar scale = bScale ? Scalar(lcm) : Scalar(1);\n\tfor (int i = 1; i <= N; ++i) {\n\t\tfor (int j = 1; j <= N; ++j) {\n\t\t\tM[i - 1][j - 1] = scale / Scalar(i + j - 1);\n\t\t}\n\t}\n\treturn lcm;\n}\n\ntemplate<typename Scalar>\nvoid GenerateHilbertMatrixInverse(mtl::mat::dense2D<Scalar>& m, Scalar scale = Scalar(1.0)) {\n\tassert(m.num_rows() == m.num_cols());\n\tsize_t N = m.num_rows();\n\tfor (int i = 1; i <= N; ++i) {\n\t\tfor (int j = 1; j <= N; ++j) {\n\t\t\tScalar sign = ((i + j) % 2) ? Scalar(-1) : Scalar(1);\n\t\t\tScalar factor1 = Scalar(i + j - 1);\n\t\t\tScalar factor2 = Scalar(sw::function::binomial<uint64_t>(N + i - 1, N - j));\n\t\t\tScalar factor3 = Scalar(sw::function::binomial<uint64_t>(N + j - 1, N - i));\n\t\t\tScalar factor4 = Scalar(sw::function::binomial<uint64_t>(i + j - 2, i - 1));\n\t\t\tm[i - 1][j - 1] = Scalar(sign * factor1 * factor2 * factor3 * factor4 * factor4);\n\t\t\t/* for tracing dynamic range failures\n\t\t\tstd::cout << \"element \" << i << \",\" << j << std::endl;\n\t\t\tstd::cout << \"sign    \" << sign << std::endl;\n\t\t\tstd::cout << \"factor1 \" << factor1 << std::endl;\n\t\t\tstd::cout << \"factor2 \" << factor2 << std::endl;\n\t\t\tstd::cout << \"factor3 \" << factor3 << std::endl;\n\t\t\tstd::cout << \"factor4 \" << factor4 << std::endl;\n\t\t\t*/\n\t\t}\n\t}\n}\n\n// isEqual compares to matrices\ntemplate<typename Matrix>\nbool isEqual(const Matrix& lhs, const Matrix& rhs) {\n\tsize_t r = lhs.num_rows();\n\tsize_t c = lhs.num_cols();\n\tfor (size_t i = 0; i < r; ++i) {\n\t\tfor (size_t j = 0; j < c; ++j) {\n\t\t\tif (lhs[i][j] != rhs[i][j]) return false;\n\t\t}\n\t}\n\treturn true;\n}\n\n} // namespace hprblas\n} // namespace sw\n", "meta": {"hexsha": "279b2178ec845ebc8b14876f645bde44dc943768", "size": 13959, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/generators/matrix_generators.hpp", "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": "include/generators/matrix_generators.hpp", "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": "include/generators/matrix_generators.hpp", "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": 34.984962406, "max_line_length": 116, "alphanum_fraction": 0.6645175156, "num_tokens": 4145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.5421442600569394}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_MDIVIDE_RIGHT_HPP\n#define STAN_MATH_PRIM_MAT_FUN_MDIVIDE_RIGHT_HPP\n\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/fun/mdivide_left.hpp>\n#include <stan/math/prim/mat/fun/transpose.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Returns the solution of the system Ax=b.\n     * @param A Matrix.\n     * @param b Right hand side matrix or vector.\n     * @return x = b A^-1, solution of the linear system.\n     * @throws std::domain_error if A is not square or the rows of b don't\n     * match the size of A.\n     */\n    template <typename T1, typename T2, int R1, int C1, int R2, int C2>\n    inline\n    Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type,\n                  R1, C2>\n    mdivide_right(const Eigen::Matrix<T1, R1, C1> &b,\n                  const Eigen::Matrix<T2, R2, C2> &A) {\n      check_square(\"mdivide_right\", \"A\", A);\n      check_multiplicable(\"mdivide_right\", \"b\", b, \"A\", A);\n      // FIXME: This is nice and general but likely slow.\n      return transpose(mdivide_left(transpose(A), transpose(b)));\n      //      return promote_common<Eigen::Matrix<T1, R2, C2>,\n      //                            Eigen::Matrix<T2, R2, C2> >(A)\n      //        .transpose()\n      //        .lu()\n      //        .solve(promote_common<Eigen::Matrix<T1, R1, C1>,\n      //                              Eigen::Matrix<T2, R1, C1> >(b)\n      //               .transpose())\n      //        .transpose();\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "c265a610aec9d7907eb576bd5c8562b059caec1e", "size": 1655, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/mdivide_right.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/mdivide_right.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/mdivide_right.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7777777778, "max_line_length": 74, "alphanum_fraction": 0.5963746224, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257655, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5421133549301602}}
{"text": "/*\n  Copyright (c) 2018-2019 Alexander A. Ganin. All rights reserved.\n  Twitter: @alxga. Website: alexganin.com.\n  Licensed under the MIT License.\n  See LICENSE file in the project root for full license information.\n*/\n\n#include \"stdafx.h\"\n#include \"Utils/rand01.h\"\n\n#ifdef HAVE_BOOST\n\n#include <boost/random.hpp>\n#include <boost/random/uniform_01.hpp>\nusing namespace boost;\nusing namespace boost::random;\n\nstatic double boost_rand_0_1()\n{\n  static mt19937 eng(((unsigned int) time(NULL)) * rand());\n  static uniform_01<> dist;\n  static variate_generator<mt19937 &, uniform_01<>> var(eng, dist);\n  return var();\n}\n\n#endif\n\n\n// Minimal random number generator of Park and Miller with Bays-Durham shuffle and added\n// safeguards. Returns a uniform random deviate between 0.0 and 1.0 (exclusive of the endpoint\n// values). Call with idum a negative integer to initialize; thereafter, do not alter idum between\n// successive deviates in a sequence. RNMX should approximate the largest floating value that is\n// less than 1\n\n#define IA 16807\n#define IM 2147483647\n#define AM (1.0/IM)\n#define IQ 127773\n#define IR 2836\n#define NTAB 32\n#define NDIV (1+(IM-1)/NTAB)\n#define EPS 1.2e-7\n#define RNMX (1.0-EPS)\n\nstatic double park_miller_rand_0_1(long *idum)\n{\n  int j;\n  long k;\n  static long iy = 0;\n  static long iv[NTAB];\n  double temp;\n\n  if (*idum <= 0 || !iy)\n  {\n    // Initialize\n    if (-(*idum) < 1)\n      *idum = 1; // Be sure to prevent idum = 0\n    else\n      *idum = -(*idum);\n\n    for (j = NTAB + 7; j >= 0; j--)\n    { // Load the shuffle table (after 8 warm-ups)\n      k = (*idum) / IQ;\n      *idum = IA * (*idum - k * IQ) - IR * k;\n      if (*idum < 0) *idum += IM;\n      if (j < NTAB) iv[j] = *idum;\n    }\n    iy = iv[0];\n  }\n\n  k = (*idum) / IQ;  // Start here when not initializing\n  *idum = IA * (*idum - k * IQ) - IR*k; // Compute idum = (IA * idum) % IM without overlows by Schrage's method\n  if (*idum < 0)\n    *idum += IM;\n\n  j = iy / NDIV;  // Will be in the range 0 ... NTAB-1\n  iy = iv[j]; // Output previously stored value and refill the  shuffle table\n  iv[j] = *idum;\n  if ((temp = AM * iy) > RNMX)\n    return RNMX; // Because users don't expect endpoint values\n  else\n    return temp;\n}\n\n\ndouble Rand01::generate()\n{\n  // return boost_rand_0_1();\n  static long seed = -rand();\n  return park_miller_rand_0_1(&seed);\n}\n", "meta": {"hexsha": "1f6c12c8ed3c041a5a2b66d039a69625b86cf9c5", "size": 2340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rand01.cpp", "max_stars_repo_name": "alxga/utils", "max_stars_repo_head_hexsha": "01ca9fb2084ba5e7bead20b45f52b3557ce8c337", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rand01.cpp", "max_issues_repo_name": "alxga/utils", "max_issues_repo_head_hexsha": "01ca9fb2084ba5e7bead20b45f52b3557ce8c337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rand01.cpp", "max_forks_repo_name": "alxga/utils", "max_forks_repo_head_hexsha": "01ca9fb2084ba5e7bead20b45f52b3557ce8c337", "max_forks_repo_licenses": ["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.4347826087, "max_line_length": 111, "alphanum_fraction": 0.6457264957, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5421133549301601}}
{"text": "#include <skylark.hpp>\n#include <boost/mpi.hpp>\n#include <elemental.hpp>\n#include <iostream>\n#include \"../base/QR.hpp\"\n#include <cfloat>\n#include <vector>\n\n\n/** Aliases for matrix types */\ntypedef elem::DistMatrix<double> dist_matrix_t;\ntypedef elem::Matrix<double> matrix_t;\ntypedef elem::DistMatrix<double, elem::VR, elem::STAR> vr_star_dist_matrix_t;\ntypedef elem::DistMatrix<double, elem::STAR, elem::STAR> star_star_matrix_t;\ntypedef skylark::sketch::JLT_t<dist_matrix_t, dist_matrix_t> sketch_transform_t;\n\nusing namespace std;\n\nint main(int argc, char* argv[]) {\n\n   /** Initialize MPI  */\n#ifdef SKYLARK_HAVE_OPENMP\n    int provided;\n    MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);\n#endif\n    boost::mpi::environment env(argc, argv);\n    boost::mpi::communicator world;\n    MPI_Comm mpi_world(world);\n    elem::Grid grid(mpi_world);\n\n    /** Initialize Elemental */\n    elem::Initialize (argc, argv);\n\n    /** Initialize context */\n    skylark::base::context_t context(0);\n\n    /** Declare matrices */\n    dist_matrix_t A(grid), B(grid), C(grid);\n    elem::Uniform(B, 5000, 100);\n    skylark::base::qr::Explicit(B);\n\n    elem::Uniform(C, 100, 100);\n    skylark::base::qr::Explicit(C);\n\n    //star_star_matrix_t S(100,100);\n    dist_matrix_t S(100,100);\n    elem::Zero(S);\n\t\n    vector<double> diag(100);\n\n    for( int j=0; j<100; ++j )\n    {\n\tdiag[j] = exp(-j)*100;\n        std::cout << exp(-j) *100 << \"\\n\";\n    }\n\n    elem::Diagonal(S, diag);\n    dist_matrix_t tmp(grid);\n\n    elem::Gemm(elem::NORMAL, elem::NORMAL, double(1), B, S, tmp);\n    elem::Gemm(elem::NORMAL, elem::ADJOINT, double(1), tmp, C, A);\n\n    dist_matrix_t U(grid), V(grid);\n    vr_star_dist_matrix_t S1;\n\n    dist_matrix_t A1(A);\n    elem::SVD(A1,S1,V);\n\n    elem::Print(S1, \"S1\");\n\n    /** Declare matrices */\n    dist_matrix_t A2(A);\n    dist_matrix_t U1(grid), V1(grid);\n    vr_star_dist_matrix_t S2;\n\n    int sketch_size\t=\t50;\n    int target_rank\t=\t10;\n\n    skylark::nla::rand_svd_params_t params(sketch_size-target_rank);\n\n    skylark::nla::randsvd_t<skylark::sketch::JLT_t> rand_svd;\n    rand_svd(A2, target_rank, U1, S2, V1, params, context);\n\n    elem::Print(S2, \"S2\");\n\n    elem::Finalize();\n    return 0;\n}\n", "meta": {"hexsha": "8f6cf93b6ceab7385041bf3eddde1ed7a829af9c", "size": 2215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/rand_svd.cpp", "max_stars_repo_name": "wangg12/libskylark", "max_stars_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-12T07:26:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T07:26:47.000Z", "max_issues_repo_path": "examples/rand_svd.cpp", "max_issues_repo_name": "cjiyer/libskylark", "max_issues_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "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/rand_svd.cpp", "max_forks_repo_name": "cjiyer/libskylark", "max_forks_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "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.8876404494, "max_line_length": 80, "alphanum_fraction": 0.6528216704, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.542113348806265}}
{"text": "#include <boost/math/constants/constants.hpp>\n#include \"servicecontainer.h\"\n\n\ndouble compile_time_expression_structure::serviceContainer::degrees(double rad)\n{\n    constexpr double pi = boost::math::constants::pi<double>();\n    return rad * 180.0 / pi;\n}\n\ndouble compile_time_expression_structure::serviceContainer::radians(double deg)\n{\n    constexpr double pi = boost::math::constants::pi<double>();\n    return deg * pi / 180.0;\n}\n\n// const std::map<compile_time_expression_structure::constantId, double>\n// compile_time_expression_structure::serviceContainer::global_constants\n// {\n//     {constantId::pi, boost::math::constants::pi<double>()},\n//     {constantId::e, boost::math::constants::e<double>()}\n// };\n// \n// const std::map<std::string, compile_time_expression_structure::constantId>\n// compile_time_expression_structure::serviceContainer::global_constants_id\n// {\n//     {\"pi\", constantId::pi},\n//     {\"e\", constantId::e}\n// };\n// \n// \n// const std::map<std::string, compile_time_expression_structure::variableId>\n// compile_time_expression_structure::serviceContainer::global_variables_id\n// {\n//     {\"x\", variableId::x},\n//     {\"y\", variableId::y},\n//     {\"r\", variableId::r}\n// };\n", "meta": {"hexsha": "e2b44cde86c180d2a36c50283758dcbc18e830ed", "size": 1201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ctexpression/servicecontainer.cpp", "max_stars_repo_name": "vega1986/wcalc_expression_parser", "max_stars_repo_head_hexsha": "e9645a5fa8086c4108ce4dc1f3ad7da3cead6480", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ctexpression/servicecontainer.cpp", "max_issues_repo_name": "vega1986/wcalc_expression_parser", "max_issues_repo_head_hexsha": "e9645a5fa8086c4108ce4dc1f3ad7da3cead6480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ctexpression/servicecontainer.cpp", "max_forks_repo_name": "vega1986/wcalc_expression_parser", "max_forks_repo_head_hexsha": "e9645a5fa8086c4108ce4dc1f3ad7da3cead6480", "max_forks_repo_licenses": ["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.7948717949, "max_line_length": 79, "alphanum_fraction": 0.7010824313, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5421133419081227}}
{"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 cauchy_distribution.hpp\n * \\date August 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <fl/util/types.hpp>\n#include <fl/distribution/t_distribution.hpp>\n\nnamespace fl\n{\n\n/**\n * \\ingroup distributions\n *\n * \\brief CauchyDistribution represents a multivariate cauchy distribution. It\n * is a special case of student's t-distribution and is equal to\n * \\f$t_1(\\mu, \\Sigma)\\f$.\n */\ntemplate <typename Variate>\nclass CauchyDistribution\n    : public TDistribution<Variate>\n{\npublic:\n    /**\n     * Creates a dynamic or fixed size multivariate cauchy distribution\n     *\n     * \\param dimension Dimension of the distribution. The default is defined by\n     *                  the dimension of the variable type \\em Vector. If the\n     *                  size of the Variate at compile time is fixed, this will\n     *                  be adapted. For dynamic-sized Variable the dimension is\n     *                  initialized to 0.\n     */\n    explicit CauchyDistribution(int dim = DimensionOf<Variate>())\n        : TDistribution<Variate>(Real(1), dim)\n    { }\n};\n\n}\n", "meta": {"hexsha": "1768db0ce9d37ed05442c0547a3a22833a3490b4", "size": 1546, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/distribution/cauchy_distribution.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/distribution/cauchy_distribution.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/distribution/cauchy_distribution.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": 27.1228070175, "max_line_length": 80, "alphanum_fraction": 0.6636481242, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5421133373327208}}
{"text": "// FastIterativePca.cpp : Defines the entry point for the console application.\n//\n\n#include \"stdafx.h\"\n#include <vector>\n#include <boost/array.hpp>\n#include <assert.h>\n#include <iostream>\n\n//you need boost to compile\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/shared_ptr.hpp>\n \n\n#pragma region ServiceFunctions\ntemplate<typename Collection>\n__inline void normalizeL2(Collection& collection)\n{\n\ttypedef typename Collection::value_type value_type;\n\tvalue_type summ = std::accumulate(collection.begin(), collection.end(), (value_type)0, [](value_type & a, value_type b)->value_type{a = a + sqr(b); return a; });\n\tsumm = sqrt(summ);\n\tif (summ < std::numeric_limits<value_type>::epsilon())\n\t\treturn;\n\tstd::for_each(collection.begin(), collection.end(), [summ](value_type& val)\n\t{\n\t\tval /= summ;\n\t});\n}\n\n\n\ntemplate<typename OutArg, typename VecIn1, typename VecIn2>\n__inline OutArg dotProduct(const VecIn1& a, const VecIn2& b)\n{\n\tOutArg prod = 0;\n\tfor (int i = 0; i < (int)a.size(); i++)\n\t{\n\t\tprod += static_cast<OutArg>(a[i]) * static_cast<OutArg>(b[i]);\n\t}\n\treturn prod;\n}\ntemplate<typename Type>\n__inline Type sqr(Type t)\n{\n\treturn t * t;\n}\ndouble selectRandom(double a, double b, int range)\n{\n\treturn a + (b - a) *(rand() % range) / (range - 1);\n}\n\n\n\n\nstruct NormalRandomGenerator\n{\npublic:\n\ttypedef boost::normal_distribution<double> NormalDistribution;\n\ttypedef boost::variate_generator<boost::mt19937&, NormalDistribution > VarGen;\n\ttypedef boost::shared_ptr<VarGen> VarGenPtr;\npublic:\n\tNormalRandomGenerator() :\n\t\tm_normalDist(0.0, 1.0)\n\t{\n\t\tm_varNor.reset(new VarGen(m_rng, m_normalDist));\n\t}\n\tvoid setParams(double  middle, double sigma)\n\t{\n\t\tm_normalDist = boost::normal_distribution<double>(middle, sigma);\n\t\tm_varNor.reset(new VarGen(m_rng, m_normalDist));\n\t}\n\tdouble generate()\n\t{\n  \n\t\treturn (*m_varNor)();\n\t}\nprivate:\n\tNormalDistribution m_normalDist;\n\tVarGenPtr m_varNor;\n\tboost::mt19937 m_rng;\n};\n#pragma endregion ServiceFunctions\n\n\n\ntemplate<int dim>\nstruct FastIterativePcaSelector\n{\n\ttypedef boost::array<float, dim> Element;\n\ttypedef std::vector<Element> Elements;\n\ttypedef std::vector<float> Weights;\n\n\tElement getFirstPC(const Elements& elements, const Weights& weights, int numIterations, const Elements& prevBazis)\n\t{\n\t\t//sds we maximze projections on space with size 2\n\t\tstd::vector<Element> currentVecs(2);\n\t\tfor (int i1 = 0; i1 < 2; i1++)\n\t\t{\n\t\t\tif (i1 == 0)\n\t\t\t\tcurrentVecs[i1] = selectRandomVec(prevBazis);\n\t\t\telse\n\t\t\t{\n\t\t\t\tcurrentVecs[i1] = getRandomOrthogonalVec(currentVecs[0], prevBazis);\n\t\t\t}\n\t\t}\n\t\tdouble bestSigma = 0;\n\t\tfor (int i1 = 0; i1 < numIterations; i1++)\n\t\t{\n\t\t\tElement currentApproximation = getApproximation(currentVecs.data(), elements, weights);\n\t\t\tElement newVec = getRandomOrthogonalVec(currentApproximation, prevBazis);\n\t\t\tcurrentVecs[0] = currentApproximation;\n\t\t\tcurrentVecs[1] = newVec;\n\t\t\tdouble sigma = calcSigma(elements, weights, currentApproximation);\n\t\t\t//stop criterion -- stabilization\n\t\t\tif (abs(sigma - bestSigma) < sigma * 0.00000001)\n\t\t\t\tbreak;\n\n\t\t\tstd::cout << \"num component \" << prevBazis.size() << \" \" << \"current sigma \" << sigma << std::endl;\n\t\t}\n\t\treturn currentVecs[0];\n\t}\n\tstatic double calcSigma(const Elements& elements, const Weights& weights, const Element& element)\n\t{\n\t\tdouble sigma = 0;\n\t\tfor (int i1 = 0; i1 < (int)elements.size(); i1++)\n\t\t{\n\t\t\tsigma += sqr(dotProduct<float>(elements[i1], element))* weights[i1];\n\t\t}\n\t\treturn sigma;\n\t}\nprivate:\n\t\n\tstatic Element selectRandomVec(const Elements& prevBazis)\n\t{\n\t\t//select random vector, orthogonal to previous got bazis\n\t\tElement result;\n\t\tfloat dp = 0;\n\t\t\n\n\t\t//try new vector until it has some orthogonal part to previous bazis\n\t\tdo\n\t\t{\n\t\t\tfor (int i1 = 0; i1 < (int)result.size(); i1++)\n\t\t\t{\n\t\t\t\tresult[i1] = (float)selectRandom(-1.0f, 1.0f, 1000);\n\t\t\t}\n\t\t\tfor (int i1 = 0; i1 < (int)prevBazis.size(); i1++)\n\t\t\t{\n\t\t\t\tfloat dp = dotProduct<float>(result, prevBazis[i1]);\n\t\t\t\tfor (int i2 = 0; i2 < (int)result.size(); i2++)\n\t\t\t\t{\n\t\t\t\t\tresult[i2] = result[i2] - prevBazis[i1][i2] * dp;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnormalizeL2(result);\n\t\t\tdp = dotProduct<float>(result, result);\n\t\t} while (dp < 0.99);\n\t\treturn result;\n\t}\n\tstatic Element getRandomOrthogonalVec(const Element& vec, const Elements& prevBazis)\n\t{\n\t\t\n\t\tElement result;\n\t\tfloat dp = 0;\n\t\t//try new vector until it has some orthogonal part to previous part and current best vector (vec) \n\t\tdo\n\t\t{\n\t\t\tresult = selectRandomVec(prevBazis);\n\t\t\tdp = dotProduct<float>(result, vec);\n\t\t\tfor (int i1 = 0; i1 < (int)result.size(); i1++)\n\t\t\t{\n\t\t\t\tresult[i1] = result[i1] - vec[i1] * dp;\n\t\t\t}\n\t\t\tnormalizeL2(result);\n\t\t\tdp = dotProduct<float>(result, result);\n\t\t} while (dp < 0.5f);\n\t\treturn result;\n\t}\n\n\n\n\tElement getApproximation(const Element* approximationStack, const Elements& elements, const Weights& weights)\n\t{\n\t\t/*\n\t\tMaximize decomposition to R2 space spanned on two vectors .\n\t\t2 Plum -- you could use int D(w) * H(w) dw instead\n\t\t*/\n\t\t\n\t\t//fill covariation matrix\n\t\tdouble matrix[4] = { 0., 0., 0., 0. };\n\t\tfor (int i0 = 0; i0 < (int)weights.size(); i0++)\n\t\t{\n\t\t\tfloat dps[2] = { dotProduct<float>(approximationStack[0], elements[i0]), dotProduct<float>(approximationStack[1], elements[i0]) };\n\t\t\tfor (int i1 = 0; i1 < 2; i1++)\n\t\t\t{\n\t\t\t\tfor (int i2 = 0; i2 < 2; i2++)\n\t\t\t\t{\n\t\t\t\t\tmatrix[i1 * 2 + i2] += dps[i1] * dps[i2] * weights[i0];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//calc eigen vectors/values\n\t\tdouble offset = (matrix[0] + matrix[3]);\n\t\tdouble d = std::max(sqr(matrix[0] - matrix[3]) + 4 * (matrix[1] * matrix[2]), 0.);\n\t\td = sqrt(d);\n\t\tdouble eV = offset < 0 ? offset / 2.0 - d / 2.0 : offset / 2.0 + d / 2.0;\n\t\tfloat coeffs[2];\n\t\tif (abs(matrix[0] - eV) > abs(matrix[3] - eV))\n\t\t{\n\t\t\tcoeffs[0] = static_cast<float>(matrix[1] / (matrix[0] - eV));\n\t\t\tcoeffs[1] = -1.f;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcoeffs[0] = -1.f;\n\t\t\tcoeffs[1] = static_cast<float>(matrix[2] / (matrix[3] - eV));\n\t\t}\n\t\t//make decomposition\n\t\tElement result;\n\t\tfor (int i1 = 0; i1 < (int)approximationStack[0].size(); i1++)\n\t\t{\n\t\t\tresult[i1] = approximationStack[0][i1] * coeffs[0] + approximationStack[1][i1] * coeffs[1];\n\t\t}\n\t\tnormalizeL2(result);\n\t\treturn result;\n\t}\n\n\n\n\n\n\n\n};\n//test function shows, how to use\nstruct FastIterativePcaSelectorTest\n{\n\tstatic const int numDimensions = 10000;\n\ttypedef FastIterativePcaSelector<numDimensions> FiPC;\n\ttypedef FiPC::Element Element;\n\ttypedef FiPC::Elements Elements;\n\tvoid test()\n\t{\n\t\tstd::vector<double> sigmas(numDimensions);\n\t\tstd::vector<boost::shared_ptr<NormalRandomGenerator> > normalDistributions(numDimensions);\n\t\t//generate some random distribution\n\t\tfor (int i1 = 0; i1 < (int)sigmas.size(); i1++)\n\t\t{\n\t\t\tsigmas[i1] = 0.2 + (rand() & 0xff)*(200.0 - 0.2) / 255.0;\n\t\t\tnormalDistributions[i1].reset(new NormalRandomGenerator());\n\t\t\tnormalDistributions[i1]->setParams(0, sigmas[i1]);\n\t\t}\n\t\tint maxElt = std::max_element(sigmas.begin(), sigmas.end()) - sigmas.begin();\n\t\tint numElements = 200;\n\t\tstd::vector<Element> elements(numElements);\n\t\t//assign all weights to 1\n\t\tstd::vector<float> weights(numElements);\n\t\tfor (int i1 = 0; i1 < (int)elements.size(); i1++)\n\t\t{\n\t\t\tfor (int i2 = 0; i2 < numDimensions; i2++)\n\t\t\t{\n\t\t\t\telements[i1][i2] = (float)normalDistributions[i2]->generate();\n\t\t\t}\n\t\t\tweights[i1] = 1.0;\n\t\t}\n\t\t//calc reference sigma along main axis\n\t\tElement bestElt;\n\t\tstd::fill(bestElt.begin(), bestElt.end(), 0.f);\n\t\tbestElt[maxElt] = 1.0;\n\n\n\n\t\tdouble bestSigma = FiPC().calcSigma(elements, weights, bestElt);\n\t\tstd::cout << bestSigma << std::endl;\n\t\tElements bazis;\n\t\tElement middle;\n\t\tstd::fill(middle.begin(), middle.end(), 1.0f);\n\t\tnormalizeL2(middle);\n\t\t//insert middle in bazis, to maximize only zero mean vectors\n\t\tbazis.push_back(middle);\n\t\tstatic const int numComponents = 10;\n\t\tboost::shared_ptr<FiPC> fipcPtr(new FiPC());\n\t\t{\n\t\t\tfor (int i1 = 0; i1 < numComponents; i1++)\n\t\t\t{\n\t\t\t\tElement comp = fipcPtr->getFirstPC(elements, weights, numDimensions, bazis);\n\t\t\t\tbazis.push_back(comp);\n\t\t\t}\n\t\t\tint j = 0;\n\t\t}\n\n\t}\nprivate:\n\n\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tFastIterativePcaSelectorTest().test();\n\treturn 0;\n}\n\n", "meta": {"hexsha": "b578048b8d2a24736206d05d33867c05fddd0f39", "size": 8065, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FastIterativePca/FastIterativePca.cpp", "max_stars_repo_name": "sdeniskos/FastIterativePca", "max_stars_repo_head_hexsha": "891c287bef9dbf32a49d0ddbf3062a46ed9dd106", "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": "FastIterativePca/FastIterativePca.cpp", "max_issues_repo_name": "sdeniskos/FastIterativePca", "max_issues_repo_head_hexsha": "891c287bef9dbf32a49d0ddbf3062a46ed9dd106", "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": "FastIterativePca/FastIterativePca.cpp", "max_forks_repo_name": "sdeniskos/FastIterativePca", "max_forks_repo_head_hexsha": "891c287bef9dbf32a49d0ddbf3062a46ed9dd106", "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.3562091503, "max_line_length": 162, "alphanum_fraction": 0.6654680719, "num_tokens": 2539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5421114742917497}}
{"text": "#define PY_ARRAY_UNIQUE_SYMBOL superimg_PyArray_API\n#define NO_IMPORT_ARRAY\n\n\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#include <vigra/numpy_array.hxx>\n#include <vigra/numpy_array_converters.hxx>\n\n#include \"seglib/cgp2d/cgp2d.hxx\"\n#include \"seglib/cgp2d/cgp2d_python.hxx\"\n#include \"seglib/cgp2d/objectives/high_level.hxx\"\n#include \"seglib/distances/distance.hxx\"\n\n\nnamespace cgp2d {\n\nnamespace python = boost::python;\n\n\n\ntemplate<class HLO>\nvoid setRegionFeatures(\n    HLO &  hlo , \n    vigra::NumpyArray<2,float> cell2Features\n){\n    hlo.setRegionFeatures(cell2Features);\n}\n\n\ntemplate<class HLO>\nvoid setPrimalLabels(\n    HLO &  hlo , \n    vigra::NumpyArray<1,LabelType> labels\n){\n    hlo.setPrimalLabels(labels);\n}\n\n\n\ntemplate<class HLO>\nfloat betweenClusterDistance(\n    HLO &  hlo , \n    const std::string distance,\n    const double gamma\n){\n    if(distance==std::string(\"squaredNorm\")){\n        dist::ChiSquared<double> distFunctor;\n        return hlo.betweenClusterDistance(distFunctor,gamma);\n    }\n    else if(distance==std::string(\"chi2\")){\n        dist::SquaredNorm<double> distFunctor;\n        return hlo.betweenClusterDistance(distFunctor,gamma);\n    }\n    else{\n        CGP_ASSERT_OP(false,==,true);\n    }\n}\n\ntemplate<class HLO>\nvigra::NumpyAnyArray writeBackMergedFeatures(\n    const HLO &  hlo , \n    vigra::NumpyArray<2, float > res = vigra::NumpyArray<2,float >()\n){\n    res.reshapeIfEmpty(hlo.features().shape());\n    hlo.writeBackMergedFeatures(res);\n    return res;\n}\n\n\n\n\nvoid export_hl_objective()\n{\n    using namespace python;\n    \n    docstring_options doc_options(true, true, false);\n\n\n    ////////////////////////////////////////\n    // Region Graph\n    ////////////////////////////////////////\n    // basic types\n    // tgrid and input image type\n    typedef Cgp<CoordinateType,LabelType> CgpType;\n    typedef CgpType::TopologicalGridType TopologicalGridType;\n\n\n    typedef HighLevelObjective<CgpType,float> HlOjective;\n\n\n    python::class_<HlOjective>(\"HighLevelObjective\",python::init<const CgpType & >()\n            [with_custodian_and_ward<1 /*custodian == self*/, 2 /*ward == const CgpType& */>()] )\n        .def(\"setRegionFeatures\", vigra::registerConverters(&setRegionFeatures<HlOjective>)  )\n        .def(\"setPrimalLabels\",   vigra::registerConverters(&setPrimalLabels<HlOjective>)  )\n        .def(\"mergeFeatures\",&HlOjective::mergeFeatures)\n        .def(\"withinClusterDistance\",&HlOjective::withinClusterDistance)\n        .def(\"betweenClusterDistance\",&betweenClusterDistance<HlOjective>)\n        .def(\"writeBackMergedFeatures\",vigra::registerConverters(&writeBackMergedFeatures<HlOjective>),\n            (\n                arg(\"res\")=python::object()\n            )\n        )\n    ;\n\n}\n\n} // namespace vigra\n\n", "meta": {"hexsha": "a21682785e01511541aa213800bb81da5c96b8a9", "size": 2766, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/python/cgp2d/py_hl_objective.cxx", "max_stars_repo_name": "DerThorsten/seglib", "max_stars_repo_head_hexsha": "4655079e390e301dd93e53f5beed6c9737d6df9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/python/cgp2d/py_hl_objective.cxx", "max_issues_repo_name": "DerThorsten/seglib", "max_issues_repo_head_hexsha": "4655079e390e301dd93e53f5beed6c9737d6df9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/python/cgp2d/py_hl_objective.cxx", "max_forks_repo_name": "DerThorsten/seglib", "max_forks_repo_head_hexsha": "4655079e390e301dd93e53f5beed6c9737d6df9f", "max_forks_repo_licenses": ["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.376146789, "max_line_length": 103, "alphanum_fraction": 0.6724511931, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5421114625874413}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>\n// Copyright (C) 2009 Mathieu Gautier <mathieu.gautier@cea.fr>\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/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include \"AnnoyingScalar.h\"\n\ntemplate<typename T> T bounded_acos(T v)\n{\n  using std::acos;\n  using std::min;\n  using std::max;\n  return acos((max)(T(-1),(min)(v,T(1))));\n}\n\ntemplate<typename QuatType> void check_slerp(const QuatType& q0, const QuatType& q1)\n{\n  using std::abs;\n  typedef typename QuatType::Scalar Scalar;\n  typedef AngleAxis<Scalar> AA;\n\n  Scalar largeEps = test_precision<Scalar>();\n\n  Scalar theta_tot = AA(q1*q0.inverse()).angle();\n  if(theta_tot>Scalar(EIGEN_PI))\n    theta_tot = Scalar(2.)*Scalar(EIGEN_PI)-theta_tot;\n  for(Scalar t=0; t<=Scalar(1.001); t+=Scalar(0.1))\n  {\n    QuatType q = q0.slerp(t,q1);\n    Scalar theta = AA(q*q0.inverse()).angle();\n    VERIFY(abs(q.norm() - 1) < largeEps);\n    if(theta_tot==0)  VERIFY(theta_tot==0);\n    else              VERIFY(abs(theta - t * theta_tot) < largeEps);\n  }\n}\n\ntemplate<typename Scalar, int Options> void quaternion(void)\n{\n  /* this test covers the following files:\n     Quaternion.h\n  */\n  using std::abs;\n  typedef Matrix<Scalar,3,1> Vector3;\n  typedef Matrix<Scalar,3,3> Matrix3;\n  typedef Quaternion<Scalar,Options> Quaternionx;\n  typedef AngleAxis<Scalar> AngleAxisx;\n\n  Scalar largeEps = test_precision<Scalar>();\n  if (internal::is_same<Scalar,float>::value)\n    largeEps = Scalar(1e-3);\n\n  Scalar eps = internal::random<Scalar>() * Scalar(1e-2);\n\n  Vector3 v0 = Vector3::Random(),\n          v1 = Vector3::Random(),\n          v2 = Vector3::Random(),\n          v3 = Vector3::Random();\n\n  Scalar  a = internal::random<Scalar>(-Scalar(EIGEN_PI), Scalar(EIGEN_PI)),\n          b = internal::random<Scalar>(-Scalar(EIGEN_PI), Scalar(EIGEN_PI));\n\n  // Quaternion: Identity(), setIdentity();\n  Quaternionx q1, q2;\n  q2.setIdentity();\n  VERIFY_IS_APPROX(Quaternionx(Quaternionx::Identity()).coeffs(), q2.coeffs());\n  q1.coeffs().setRandom();\n  VERIFY_IS_APPROX(q1.coeffs(), (q1*q2).coeffs());\n\n  // concatenation\n  q1 *= q2;\n\n  q1 = AngleAxisx(a, v0.normalized());\n  q2 = AngleAxisx(a, v1.normalized());\n\n  // angular distance\n  Scalar refangle = abs(AngleAxisx(q1.inverse()*q2).angle());\n  if (refangle>Scalar(EIGEN_PI))\n    refangle = Scalar(2)*Scalar(EIGEN_PI) - refangle;\n\n  if((q1.coeffs()-q2.coeffs()).norm() > Scalar(10)*largeEps)\n  {\n    VERIFY_IS_MUCH_SMALLER_THAN(abs(q1.angularDistance(q2) - refangle), Scalar(1));\n  }\n\n  // rotation matrix conversion\n  VERIFY_IS_APPROX(q1 * v2, q1.toRotationMatrix() * v2);\n  VERIFY_IS_APPROX(q1 * q2 * v2,\n    q1.toRotationMatrix() * q2.toRotationMatrix() * v2);\n\n  VERIFY(  (q2*q1).isApprox(q1*q2, largeEps)\n        || !(q2 * q1 * v2).isApprox(q1.toRotationMatrix() * q2.toRotationMatrix() * v2));\n\n  q2 = q1.toRotationMatrix();\n  VERIFY_IS_APPROX(q1*v1,q2*v1);\n\n  Matrix3 rot1(q1);\n  VERIFY_IS_APPROX(q1*v1,rot1*v1);\n  Quaternionx q3(rot1.transpose()*rot1);\n  VERIFY_IS_APPROX(q3*v1,v1);\n\n\n  // angle-axis conversion\n  AngleAxisx aa = AngleAxisx(q1);\n  VERIFY_IS_APPROX(q1 * v1, Quaternionx(aa) * v1);\n\n  // Do not execute the test if the rotation angle is almost zero, or\n  // the rotation axis and v1 are almost parallel.\n  if (abs(aa.angle()) > Scalar(5)*test_precision<Scalar>()\n      && (aa.axis() - v1.normalized()).norm() < Scalar(1.99)\n      && (aa.axis() + v1.normalized()).norm() < Scalar(1.99))\n  {\n    VERIFY_IS_NOT_APPROX(q1 * v1, Quaternionx(AngleAxisx(aa.angle()*2,aa.axis())) * v1);\n  }\n\n  // from two vector creation\n  VERIFY_IS_APPROX( v2.normalized(),(q2.setFromTwoVectors(v1, v2)*v1).normalized());\n  VERIFY_IS_APPROX( v1.normalized(),(q2.setFromTwoVectors(v1, v1)*v1).normalized());\n  VERIFY_IS_APPROX(-v1.normalized(),(q2.setFromTwoVectors(v1,-v1)*v1).normalized());\n  if (internal::is_same<Scalar,double>::value)\n  {\n    v3 = (v1.array()+eps).matrix();\n    VERIFY_IS_APPROX( v3.normalized(),(q2.setFromTwoVectors(v1, v3)*v1).normalized());\n    VERIFY_IS_APPROX(-v3.normalized(),(q2.setFromTwoVectors(v1,-v3)*v1).normalized());\n  }\n\n  // from two vector creation static function\n  VERIFY_IS_APPROX( v2.normalized(),(Quaternionx::FromTwoVectors(v1, v2)*v1).normalized());\n  VERIFY_IS_APPROX( v1.normalized(),(Quaternionx::FromTwoVectors(v1, v1)*v1).normalized());\n  VERIFY_IS_APPROX(-v1.normalized(),(Quaternionx::FromTwoVectors(v1,-v1)*v1).normalized());\n  if (internal::is_same<Scalar,double>::value)\n  {\n    v3 = (v1.array()+eps).matrix();\n    VERIFY_IS_APPROX( v3.normalized(),(Quaternionx::FromTwoVectors(v1, v3)*v1).normalized());\n    VERIFY_IS_APPROX(-v3.normalized(),(Quaternionx::FromTwoVectors(v1,-v3)*v1).normalized());\n  }\n\n  // inverse and conjugate\n  VERIFY_IS_APPROX(q1 * (q1.inverse() * v1), v1);\n  VERIFY_IS_APPROX(q1 * (q1.conjugate() * v1), v1);\n\n  // test casting\n  Quaternion<float> q1f = q1.template cast<float>();\n  VERIFY_IS_APPROX(q1f.template cast<Scalar>(),q1);\n  Quaternion<double> q1d = q1.template cast<double>();\n  VERIFY_IS_APPROX(q1d.template cast<Scalar>(),q1);\n\n  // test bug 369 - improper alignment.\n  Quaternionx *q = new Quaternionx;\n  delete q;\n\n  q1 = Quaternionx::UnitRandom();\n  q2 = Quaternionx::UnitRandom();\n  check_slerp(q1,q2);\n\n  q1 = AngleAxisx(b, v1.normalized());\n  q2 = AngleAxisx(b+Scalar(EIGEN_PI), v1.normalized());\n  check_slerp(q1,q2);\n\n  q1 = AngleAxisx(b,  v1.normalized());\n  q2 = AngleAxisx(-b, -v1.normalized());\n  check_slerp(q1,q2);\n\n  q1 = Quaternionx::UnitRandom();\n  q2.coeffs() = -q1.coeffs();\n  check_slerp(q1,q2);\n}\n\ntemplate<typename Scalar> void mapQuaternion(void){\n  typedef Map<Quaternion<Scalar>, Aligned> MQuaternionA;\n  typedef Map<const Quaternion<Scalar>, Aligned> MCQuaternionA;\n  typedef Map<Quaternion<Scalar> > MQuaternionUA;\n  typedef Map<const Quaternion<Scalar> > MCQuaternionUA;\n  typedef Quaternion<Scalar> Quaternionx;\n  typedef Matrix<Scalar,3,1> Vector3;\n  typedef AngleAxis<Scalar> AngleAxisx;\n  \n  Vector3 v0 = Vector3::Random(),\n          v1 = Vector3::Random();\n  Scalar  a = internal::random<Scalar>(-Scalar(EIGEN_PI), Scalar(EIGEN_PI));\n\n  EIGEN_ALIGN_MAX Scalar array1[4];\n  EIGEN_ALIGN_MAX Scalar array2[4];\n  EIGEN_ALIGN_MAX Scalar array3[4+1];\n  Scalar* array3unaligned = array3+1;\n  \n  MQuaternionA    mq1(array1);\n  MCQuaternionA   mcq1(array1);\n  MQuaternionA    mq2(array2);\n  MQuaternionUA   mq3(array3unaligned);\n  MCQuaternionUA  mcq3(array3unaligned);\n\n//  std::cerr << array1 << \" \" << array2 << \" \" << array3 << \"\\n\";\n  mq1 = AngleAxisx(a, v0.normalized());\n  mq2 = mq1;\n  mq3 = mq1;\n\n  Quaternionx q1 = mq1;\n  Quaternionx q2 = mq2;\n  Quaternionx q3 = mq3;\n  Quaternionx q4 = MCQuaternionUA(array3unaligned);\n\n  VERIFY_IS_APPROX(q1.coeffs(), q2.coeffs());\n  VERIFY_IS_APPROX(q1.coeffs(), q3.coeffs());\n  VERIFY_IS_APPROX(q4.coeffs(), q3.coeffs());\n  #ifdef EIGEN_VECTORIZE\n  if(internal::packet_traits<Scalar>::Vectorizable)\n    VERIFY_RAISES_ASSERT((MQuaternionA(array3unaligned)));\n  #endif\n    \n  VERIFY_IS_APPROX(mq1 * (mq1.inverse() * v1), v1);\n  VERIFY_IS_APPROX(mq1 * (mq1.conjugate() * v1), v1);\n  \n  VERIFY_IS_APPROX(mcq1 * (mcq1.inverse() * v1), v1);\n  VERIFY_IS_APPROX(mcq1 * (mcq1.conjugate() * v1), v1);\n  \n  VERIFY_IS_APPROX(mq3 * (mq3.inverse() * v1), v1);\n  VERIFY_IS_APPROX(mq3 * (mq3.conjugate() * v1), v1);\n  \n  VERIFY_IS_APPROX(mcq3 * (mcq3.inverse() * v1), v1);\n  VERIFY_IS_APPROX(mcq3 * (mcq3.conjugate() * v1), v1);\n  \n  VERIFY_IS_APPROX(mq1*mq2, q1*q2);\n  VERIFY_IS_APPROX(mq3*mq2, q3*q2);\n  VERIFY_IS_APPROX(mcq1*mq2, q1*q2);\n  VERIFY_IS_APPROX(mcq3*mq2, q3*q2);\n\n  // Bug 1461, compilation issue with Map<const Quat>::w(), and other reference/constness checks:\n  VERIFY_IS_APPROX(mcq3.coeffs().x() + mcq3.coeffs().y() + mcq3.coeffs().z() + mcq3.coeffs().w(), mcq3.coeffs().sum());\n  VERIFY_IS_APPROX(mcq3.x() + mcq3.y() + mcq3.z() + mcq3.w(), mcq3.coeffs().sum());\n  mq3.w() = 1;\n  const Quaternionx& cq3(q3);\n  VERIFY( &cq3.x() == &q3.x() );\n  const MQuaternionUA& cmq3(mq3);\n  VERIFY( &cmq3.x() == &mq3.x() );\n  // FIXME the following should be ok. The problem is that currently the LValueBit flag\n  // is used to determine whether we can return a coeff by reference or not, which is not enough for Map<const ...>.\n  //const MCQuaternionUA& cmcq3(mcq3);\n  //VERIFY( &cmcq3.x() == &mcq3.x() );\n}\n\ntemplate<typename Scalar> void quaternionAlignment(void){\n  typedef Quaternion<Scalar,AutoAlign> QuaternionA;\n  typedef Quaternion<Scalar,DontAlign> QuaternionUA;\n\n  EIGEN_ALIGN_MAX Scalar array1[4];\n  EIGEN_ALIGN_MAX Scalar array2[4];\n  EIGEN_ALIGN_MAX Scalar array3[4+1];\n  Scalar* arrayunaligned = array3+1;\n\n  QuaternionA *q1 = ::new(reinterpret_cast<void*>(array1)) QuaternionA;\n  QuaternionUA *q2 = ::new(reinterpret_cast<void*>(array2)) QuaternionUA;\n  QuaternionUA *q3 = ::new(reinterpret_cast<void*>(arrayunaligned)) QuaternionUA;\n\n  q1->coeffs().setRandom();\n  *q2 = *q1;\n  *q3 = *q1;\n\n  VERIFY_IS_APPROX(q1->coeffs(), q2->coeffs());\n  VERIFY_IS_APPROX(q1->coeffs(), q3->coeffs());\n  #if defined(EIGEN_VECTORIZE) && EIGEN_MAX_STATIC_ALIGN_BYTES>0\n  if(internal::packet_traits<Scalar>::Vectorizable && internal::packet_traits<Scalar>::size<=4)\n    VERIFY_RAISES_ASSERT((::new(reinterpret_cast<void*>(arrayunaligned)) QuaternionA));\n  #endif\n}\n\ntemplate<typename PlainObjectType> void check_const_correctness(const PlainObjectType&)\n{\n  // there's a lot that we can't test here while still having this test compile!\n  // the only possible approach would be to run a script trying to compile stuff and checking that it fails.\n  // CMake can help with that.\n\n  // verify that map-to-const don't have LvalueBit\n  typedef typename internal::add_const<PlainObjectType>::type ConstPlainObjectType;\n  VERIFY( !(internal::traits<Map<ConstPlainObjectType> >::Flags & LvalueBit) );\n  VERIFY( !(internal::traits<Map<ConstPlainObjectType, Aligned> >::Flags & LvalueBit) );\n  VERIFY( !(Map<ConstPlainObjectType>::Flags & LvalueBit) );\n  VERIFY( !(Map<ConstPlainObjectType, Aligned>::Flags & LvalueBit) );\n}\n\n#if EIGEN_HAS_RVALUE_REFERENCES\n\n// Regression for bug 1573\nstruct MovableClass {\n  MovableClass() = default;\n  MovableClass(const MovableClass&) = default;\n  MovableClass(MovableClass&&) noexcept = default;\n  MovableClass& operator=(const MovableClass&) = default;\n  MovableClass& operator=(MovableClass&&) = default;\n  Quaternionf m_quat;\n};\n\n#endif\n\nEIGEN_DECLARE_TEST(geo_quaternion)\n{\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1(( quaternion<float,AutoAlign>() ));\n    CALL_SUBTEST_1( check_const_correctness(Quaternionf()) );\n    CALL_SUBTEST_1(( quaternion<float,DontAlign>() ));\n    CALL_SUBTEST_1(( quaternionAlignment<float>() ));\n    CALL_SUBTEST_1( mapQuaternion<float>() );\n\n    CALL_SUBTEST_2(( quaternion<double,AutoAlign>() ));\n    CALL_SUBTEST_2( check_const_correctness(Quaterniond()) );\n    CALL_SUBTEST_2(( quaternion<double,DontAlign>() ));\n    CALL_SUBTEST_2(( quaternionAlignment<double>() ));\n    CALL_SUBTEST_2( mapQuaternion<double>() );\n\n    AnnoyingScalar::dont_throw = true;\n    CALL_SUBTEST_3(( quaternion<AnnoyingScalar,AutoAlign>() ));\n  }\n}\n", "meta": {"hexsha": "ed801c71b379ba8ccbd6bfdf4dcd63be35d57453", "size": 11388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/eigenlib/test/geo_quaternion.cpp", "max_stars_repo_name": "sergiosvieira/mog", "max_stars_repo_head_hexsha": "f23d2b18851bb58c3e60aae9b10deec023f2c9c8", "max_stars_repo_licenses": ["MIT"], "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/eigenlib/test/geo_quaternion.cpp", "max_issues_repo_name": "sergiosvieira/mog", "max_issues_repo_head_hexsha": "f23d2b18851bb58c3e60aae9b10deec023f2c9c8", "max_issues_repo_licenses": ["MIT"], "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/eigenlib/test/geo_quaternion.cpp", "max_forks_repo_name": "sergiosvieira/mog", "max_forks_repo_head_hexsha": "f23d2b18851bb58c3e60aae9b10deec023f2c9c8", "max_forks_repo_licenses": ["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.3664596273, "max_line_length": 119, "alphanum_fraction": 0.6915173867, "num_tokens": 3474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5421114522209476}}
{"text": "/** @file planar.cc\n * @author David F. Gleich\n * @date 2008-09-29\n * @copyright Stanford University, 2008\n * Planar graph algorithm wrappers\n */\n\n/** History\n *  2008-09-29: Initial coding\n */\n\n#include \"include/matlab_bgl.h\"\n\n#include <yasmic/undir_simple_csr_matrix_as_graph.hpp>\n#include <yasmic/simple_csr_matrix_as_graph.hpp>\n#include <yasmic/iterator_utility.hpp>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/planar_canonical_ordering.hpp>\n//#include <boost/graph/chrobak_payne_drawing.hpp>\n#include <yasmic/boost_mod/chrobak_payne_drawing.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n#include <boost/graph/is_kuratowski_subgraph.hpp>\n#include <boost/graph/make_connected.hpp>\n#include <boost/graph/make_biconnected_planar.hpp>\n#include <boost/graph/make_maximal_planar.hpp>\n#include <boost/graph/simple_point.hpp>\n//#include <boost/graph/is_straight_line_drawing.hpp>\n#include <yasmic/boost_mod/is_straight_line_drawing.hpp>\n#include <boost/graph/filtered_graph.hpp>\n\n#include <vector>\n#include <iostream>\n#include <algorithm>\n\n#include <math.h>\n\n#include \"libmbgl_util.hpp\"\n\n/** Copy an edge iterator to a pair of arrays\n */\ntemplate <typename Graph, typename Iterator>\nmbglIndex copy_to_ij(Graph& g, Iterator oi,\n                   Iterator oi_end, mbglIndex* i, mbglIndex* j)\n{\n  using namespace boost;\n\n  mbglIndex ei;\n  for (ei= 0; oi != oi_end; ++oi, ++ei) {\n    typename graph_traits<Graph>::edge_descriptor e = *oi;\n    i[ei] = source(e,g);\n    j[ei] = target(e,g);\n  }\n\n  return (ei);\n}\n\n/** Translate the boost embedding information to the libmbgl embedding output\n */\ntemplate <typename Graph, typename PlanarEmbedding>\nvoid copy_embedding(Graph& g, PlanarEmbedding e, mbglIndex *eip, mbglIndex *eie)\n{\n  using namespace boost;\n  typename graph_traits<Graph>::vertex_iterator vi, viend;\n  mbglIndex nedges= num_edges(g);\n  mbglIndex curi= 0;\n  mbglIndex nullv= graph_traits<Graph>::null_vertex();\n  mbglIndex oldv= nullv;\n  for (boost::tie(vi,viend)=vertices(g); vi!=viend; ++vi) {\n    if (oldv!=nullv) { assert(*vi==oldv+1); }\n    assert(*vi<num_vertices(g));\n    eip[*vi] = curi;\n    typename property_traits<PlanarEmbedding>::value_type::const_iterator\n      ei=e[*vi].begin(), eiend=e[*vi].end();\n    for (; ei!=eiend; ++ei) {\n      assert(source(*ei,g) == *vi || target(*ei,g) == *vi);\n      assert(curi<nedges);\n      if (source(*ei,g) == *vi) {\n        eie[curi] = target(*ei,g);\n      } else if (target(*ei,g) == *vi) {\n        eie[curi] = source(*ei,g);\n      } else {\n        assert(source(*ei,g) == *vi || target(*ei,g) == *vi);\n      }\n      ++curi;\n    }\n    oldv = *vi;\n  }\n  eip[num_vertices(g)] = curi;\n}\n\n/** Test if a graph is planar, compute a planar embedding, or get a Kuratowski\n * subgraph\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 is_planar set to 0 if the graph is not planar, else the graph is\n *   planar\n * @param i the source vertex of any edge in the Kuratowski subgraph,\n *   length max(3*nverts-6,6)\n * @param j the dest vertex of any edge in the Kuratowski subgraph,\n *   length max(3*nverts-6,6)\n * @param nedges set to the number of edges in i and j actually used\n * @param eip the embedding information edge pointer to eie, length nverts+1\n *   eip[eie[v]] to eip[eie[v+1]] gives the embedding order for vertex v\n * @param eie the embedding information destination list, length ia[nverts]\n *   see eip for a description.\n */\nint boyer_myrvold_planarity_test(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia,\n    int *is_planar,\n    mbglIndex *i, mbglIndex *j, mbglIndex* nedges, /* kuratowski subgraph output */\n    mbglIndex *eip, mbglIndex *eie)\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  //Define the storage type for the planar embedding\n  typedef std::vector< std::vector< graph_traits<crs_graph>::edge_descriptor > >\n    embedding_storage_t;\n  typedef boost::iterator_property_map\n    < embedding_storage_t::iterator,\n      property_map<crs_graph, vertex_index_t>::type\n    >\n    embedding_t;\n\n\n  bool planar=false;\n  if ((i == NULL || j == NULL || nedges == NULL) &&\n      (eip == NULL || eip == NULL)) {\n    // just test for a planar graph\n    planar= boyer_myrvold_planarity_test(g);\n  } else if (eip == NULL || eie == NULL ) {\n    // just get the kuratowski subgraph\n    std::vector<graph_traits<crs_graph>::edge_descriptor>\n      kuratowski_edges;\n    planar= boyer_myrvold_planarity_test(\n        boyer_myrvold_params::graph = g,\n        boyer_myrvold_params::kuratowski_subgraph =\n          std::back_inserter(kuratowski_edges)\n        );\n    if (planar == false) {\n      *nedges =\n        copy_to_ij(g, kuratowski_edges.begin(), kuratowski_edges.end(), i, j);\n    } else { *nedges = 0; }\n  } else if (i == NULL || j == NULL || nedges == NULL) {\n    embedding_storage_t embedding_storage(num_vertices(g));\n    embedding_t embedding(embedding_storage.begin(), get(vertex_index,g));\n    planar= boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n                                   boyer_myrvold_params::embedding = embedding\n                                   );\n    if (planar == true) {\n      copy_embedding(g, embedding, eip, eie);\n    } else {\n      memset(eip, 0, sizeof(mbglIndex)*(nverts+1));\n    }\n  } else {\n    // get the kuratowski subgraph and the planar embedding\n    std::vector<graph_traits<crs_graph>::edge_descriptor>\n        kuratowski_edges;\n    embedding_storage_t embedding_storage(num_vertices(g));\n    embedding_t embedding(embedding_storage.begin(), get(vertex_index,g));\n    planar= boyer_myrvold_planarity_test(\n        boyer_myrvold_params::graph = g,\n        boyer_myrvold_params::embedding = embedding,\n        boyer_myrvold_params::kuratowski_subgraph =\n                 std::back_inserter(kuratowski_edges)\n        );\n    if (planar == false) {\n      *nedges =\n        copy_to_ij(g, kuratowski_edges.begin(), kuratowski_edges.end(), i, j);\n    } else { *nedges = 0; }\n    if (planar == true) {\n      copy_embedding(g, embedding, eip, eie);\n    } else {\n      memset(eip, 0, sizeof(mbglIndex)*(nverts+1));\n    }\n  }\n  if (is_planar) {\n    if (planar) { *is_planar = 1; }\n    else { *is_planar = 0; }\n  }\n  return (0);\n}\n\n/** An edge filter that only returns the edges in an upper-triangular part\n */\ntemplate <typename Graph>\nstruct upper_triangle_edge_filter {\n  upper_triangle_edge_filter() : _g(NULL) {}\n  upper_triangle_edge_filter(const Graph& g_) : _g(&g_) {}\n  template <typename Edge>\n  bool operator()(const Edge& e) const {\n    return (boost::source(e,*_g) < boost::target(e,*_g));\n  }\n  const Graph* _g;\n};\n\n\n/** Test is a graph is Kuratowski (i.e. contracts to K_3,3 or K_5)\n * This function only uses the upper triangular set of edges.  It will\n * silently report incorrect ouput if there are too many parallel edges,\n * so beware.\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 is_ksubgraph set to 1 if the graph is Kuratowski\n */\nint is_kuratowski_subgraph(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia,\n    int *is_ksubgraph)\n{\n  using namespace boost;\n  using namespace yasmic;\n\n  typedef simple_csr_matrix<mbglIndex,double> crs_graph;\n  typedef upper_triangle_edge_filter<crs_graph> filter;\n  typedef filtered_graph<crs_graph, filter> fgraph;\n  assert(is_ksubgraph);\n  crs_graph g(nverts, nverts, ia[nverts], ia, ja, NULL);\n  filter f(g);\n  fgraph fg(g,f);\n  graph_traits<fgraph>::edge_iterator ei, eiend;\n  boost::tie(ei,eiend)= edges(fg);\n  bool is_k= is_kuratowski_subgraph(g, ei, eiend, get(vertex_index,g));\n  if (is_k) { *is_ksubgraph = 1; } else { *is_ksubgraph = 0; }\n  return (0);\n}\n\n/** Test if a given set of positions is a straight line drawing of the graph.\n * This function uses a bucket-sort, and so large positions may cause out\n * of memory errors.\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 X The set of positions.  These are rounded to size_t variables and so\n *   all the elements of X must be positive.\n * @param is_sldrawing set to 1 if the positions are a straight line drawing,\n *   otherwise set to 0\n */\nint is_straight_line_drawing(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia,\n    double *X, int *is_sldrawing)\n{\n  using namespace boost;\n  using namespace yasmic;\n\n  typedef simple_csr_matrix<mbglIndex,double> crs_graph;\n  crs_graph g(nverts, nverts, ia[nverts], ia, ja, NULL);\n  assert(is_sldrawing);\n  // copy the layout from positions\n  std::vector<simple_point<size_t> > position_vec(nverts);\n  mbglIndex n = num_vertices(g);\n  for (mbglIndex i = 0; i<n; i++) {\n    if (X[i+0*n] < 0 || X[i+1*n] < 0) {\n      return -11;\n    }\n    position_vec[i].x = (size_t)floor(X[i+0*n]);\n    position_vec[i].y = (size_t)floor(X[i+1*n]);\n  }\n  bool is_sl= is_straight_line_drawing(g,\n      make_iterator_property_map(position_vec.begin(),get(vertex_index,g)),\n      get(vertex_index,g));\n  if (is_sl) { *is_sldrawing = 1; } else { *is_sldrawing = 0; }\n  return (0);\n}\n\n/** Copy a crs_graph to a mutable boost graph\n */\ntemplate <typename Graph>\nvoid copy_crs_to_graph(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia,\n    Graph& g)\n{\n  using namespace boost;\n  using namespace yasmic;\n  typedef simple_csr_matrix<mbglIndex,double> crs_graph;\n  crs_graph g_in(nverts, nverts, ia[nverts], ia, ja, NULL);\n  //typename property_map<Graph, vertex_index_t>::type vi(get(vertex_index, g));\n  //for (mbglIndex i=0; i<nverts; i++) { vi[i]=i; }\n  typename graph_traits<crs_graph>::vertex_iterator vi, vi_end;\n  typename graph_traits<crs_graph>::out_edge_iterator ei, ei_end;\n  for (tie(vi, vi_end) = vertices(g_in); vi != vi_end; ++vi) {\n    for (tie(ei, ei_end) = out_edges(*vi, g_in); ei != ei_end; ++ei) {\n      if (source(*ei,g_in) < target(*ei,g_in)) {\n        add_edge(source(*ei,g_in),target(*ei,g_in),g);\n      }\n    }\n  }\n}\n\n/** Add an edge and record all edges we added\n * EdgeSrcOutIterator - the type of the out iterator for the source vertex\n *   in the new edge pair\n * EdgeDstOutIterator - the type of the out iterator for the destination vertex\n *   in the new edge pair\n * TODO Make this function update the edge_index parameter too!  This will avoid\n * O(E) work in a few cases.\n */\ntemplate <typename EdgeSrcOutIterator, typename EdgeDstOutIterator>\nstruct record_add_edge_visitor {\n  EdgeSrcOutIterator soi, soi_end;\n  EdgeDstOutIterator doi, doi_end;\n  mbglIndex* count; // incremented for each additional edge\n\n  record_add_edge_visitor(EdgeSrcOutIterator soi_, EdgeSrcOutIterator soi_end_,\n      EdgeDstOutIterator doi_, EdgeDstOutIterator doi_end_, mbglIndex* count_)\n  : soi(soi_), soi_end(soi_end_), doi(doi_), doi_end(doi_end_), count(count_)\n  {}\n\n  template <typename Graph, typename Vertex>\n  void visit_vertex_pair(Vertex u, Vertex v, Graph& g) {\n    add_edge(u,v,g);\n    assert(soi != soi_end);\n    assert(doi != doi_end);\n    *soi = u;\n    *doi = v;\n    ++doi;\n    ++soi;\n    (*count)++;\n  }\n};\n\n/** Helper to abstract the details of the triangulation */\ntemplate <typename Graph, typename RecordAddEdgeVisitor>\nint triangulate_bgl_graph(\n  Graph& g, int make_conn, int make_biconnected, int make_maximal,\n  RecordAddEdgeVisitor add_edge_visitor)\n{\n  using namespace boost;\n  typedef std::vector< std::vector<\n            typename graph_traits<Graph>::edge_descriptor > >\n  embedding_storage_t;\n  typedef boost::iterator_property_map\n    < typename embedding_storage_t::iterator,\n      typename property_map<Graph, vertex_index_t>::type\n    >\n    embedding_t;\n\n  if (make_conn) {\n    make_connected(g, get(vertex_index,g), add_edge_visitor);\n  }\n  if (make_biconnected || make_maximal) {\n    typename property_map<Graph, edge_index_t>::type e_index = get(edge_index, g);\n    typename graph_traits<Graph>::edges_size_type edge_count = 0;\n    typename graph_traits<Graph>::edge_iterator ei, ei_end;\n\n    // compute a planar embedding\n    embedding_storage_t embedding_storage(num_vertices(g));\n    embedding_t embedding(embedding_storage.begin(), get(vertex_index,g));\n\n    if (make_biconnected) {\n      // compute the edge index\n      edge_count = 0;\n      for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\n        put(e_index, *ei, edge_count++);\n      }\n      // compute a planar embedding\n      if (boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n                                       boyer_myrvold_params::embedding =\n                                           embedding\n                                       )\n          ) {\n        make_biconnected_planar(g, embedding, get(edge_index,g),\n            add_edge_visitor);\n      } else {\n        return 1;\n      }\n    }\n    if (make_maximal) {\n      // compute the edge index\n      edge_count = 0;\n      for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\n        put(e_index, *ei, edge_count++);\n      }\n      // compute a planar embedding\n      if (boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n                                       boyer_myrvold_params::embedding =\n                                           embedding\n                                       )\n          ) {\n        make_maximal_planar(g, embedding, get(vertex_index,g),\n            get(edge_index,g), add_edge_visitor);\n      } else {\n        return 1;\n      }\n    }\n  }\n  return 0;\n}\n\n\n/** Compute extra edges that are needed for a straight line embedding.\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 make_connected if set (!=0), compute edges to make a single\n *   connected component\n * @param make_biconnected If set (!=0), compute edges to make a single\n *   biconnected component (requires a planar input graph).  If only this\n *   parameter is set, then we assume the graph is already connected.\n * @param make_maximal If set (!=0), compute edges to make the maximal\n *   planar graph (requires a planar input graph). If only this\n *   parameter is set, then we assume the graph is already biconnected.\n * @param i source of all edges added in the triangulation,\n *   length max(3*nverts-6,6)\n * @param j dest of all edges added in the triangulation,\n *   length max(3*nverts-6,6)\n * @param nedges the number of edges in i and j actually used\n */\nint triangulate_graph(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia,\n    int make_connected, int make_biconnected, int make_maximal,\n    mbglIndex *i, mbglIndex *j, mbglIndex* nedges /* extra edges */)\n{\n  using namespace boost;\n  typedef adjacency_list\n        < vecS, vecS, undirectedS, no_property,\n        property<edge_index_t, mbglIndex> > graph;\n  assert(i != NULL); assert(j != NULL); assert(nedges != NULL);\n  *nedges = 0;\n  size_t endedges= nverts>4 ? 3*nverts-6 : 6;\n  record_add_edge_visitor<mbglIndex*,mbglIndex*> add_edge_visitor(\n      i, i+endedges, j, j+endedges, nedges);\n  graph g(nverts);\n  copy_crs_to_graph(nverts, ja, ia, g);\n  return triangulate_bgl_graph(\n      g, make_connected, make_biconnected, make_maximal, add_edge_visitor);\n}\n\n/** Abstract some details between the csr_graph and the adjacency_list graph\n * for the straight line drawing\n */\ntemplate <typename Graph>\nint chrobak_payne_straight_line_drawing_on_maximal_graph(const Graph& g,\n    int just_ordering,\n    mbglIndex *p, /* ordering permutation */\n    mbglDegreeType *X)\n{\n  using namespace boost;\n  typedef std::vector< std::vector<\n            typename graph_traits<Graph>::edge_descriptor > >\n    embedding_storage_t;\n  typedef boost::iterator_property_map\n    < typename embedding_storage_t::iterator,\n      typename property_map<Graph, vertex_index_t>::type\n    >\n    embedding_t;\n\n  embedding_storage_t embedding_storage(num_vertices(g));\n  embedding_t embedding(embedding_storage.begin(), get(vertex_index,g));\n\n  if (boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n                                   boyer_myrvold_params::embedding =\n                                      embedding\n                                  )\n     ) {\n   // do nothing, the graph is planar\n  } else {\n   return 1;\n  }\n  // TODO convert this to use p directly\n  mbglIndex n = num_vertices(g);\n  assert(n == 0 || p);\n  std::vector< typename graph_traits<Graph>::vertex_descriptor > ordering;\n  planar_canonical_ordering(g, embedding,\n     std::back_inserter(ordering), get(vertex_index,g));\n\n  if (just_ordering == 0) {\n    typedef simple_point<size_t> coord_t;\n    typedef std::vector< coord_t > straight_line_drawing_storage_t;\n    typedef boost::iterator_property_map\n       < straight_line_drawing_storage_t::iterator,\n         typename property_map<Graph, vertex_index_t>::type\n       >\n       straight_line_drawing_t;\n\n    assert(n == 0 || X);\n    // compute the straight line embedding\n    straight_line_drawing_storage_t straight_line_drawing_storage\n     (num_vertices(g));\n    straight_line_drawing_t straight_line_drawing\n     (straight_line_drawing_storage.begin(),\n      get(vertex_index,g)\n      );\n    if (n == 2) {\n      straight_line_drawing_storage[0].x = 0;\n      straight_line_drawing_storage[0].y = 0;\n      straight_line_drawing_storage[1].x = 1;\n      straight_line_drawing_storage[1].y = 0;\n    } else {\n      chrobak_payne_straight_line_drawing(g,\n                                         embedding,\n                                         ordering.begin(),\n                                         ordering.end(),\n                                         straight_line_drawing\n                                         );\n    }\n    // copy all the data\n    for (mbglIndex i= 0; i<n; i++) {\n      X[i+0*n] = straight_line_drawing_storage[i].x;\n      X[i+1*n] = straight_line_drawing_storage[i].y;\n    }\n  }\n  assert((ordering.end() - ordering.begin()) == (ptrdiff_t)n);\n  for (mbglIndex i= 0; i<n; i++) {\n    p[i] = ordering[i];\n  }\n  return 0;\n}\n\n/** Compute a straight line embedding of a graph or a canonical planar\n * ordering\n *\n * This function must copy the graph unless is_maximal is set.\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 just_ordering if set (!=0), then just compute the ordering permutation\n * @param is_maximal if set (!=0), assume the input is a maximal planar graph\n * @param i source edges for the maximal planar graph, length 3n-6\n * @param j dest edges for the maximal planar graph, length 3n-6\n * @param nedges the number of entries in i,j actually used, length 1\n * @param p the ordering permutation, length nverts\n * @param X the positions, length 2*nverts\n */\nint chrobak_payne_straight_line_drawing(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia,\n    int just_ordering, int is_maximal,\n    mbglIndex *i, mbglIndex *j, mbglIndex* nedges, /* extra edges */\n    mbglIndex *p, /* ordering permutation */\n    mbglDegreeType *X)\n{\n  using namespace boost;\n  using namespace yasmic;\n  if (is_maximal) {\n    // trust the user that the graph is maximal, this means we\n    // can skip the copy\n    typedef simple_csr_matrix<mbglIndex,double> crs_graph;\n    crs_graph g(nverts, nverts, ia[nverts], ia, ja, NULL);\n    if (nedges) { *nedges = 0; } // already maximal\n    return chrobak_payne_straight_line_drawing_on_maximal_graph(g,\n        just_ordering, p, X);\n  } else {\n    typedef adjacency_list\n      < vecS, vecS, undirectedS, no_property,\n      property<edge_index_t, mbglIndex> > graph;\n    graph g(nverts);\n    copy_crs_to_graph(nverts, ja, ia, g);\n    int rval=0;\n    if (i != NULL && j != NULL && nedges != NULL) {\n      *nedges = 0;\n      size_t endedges= nverts>4 ? 3*nverts-6 : 6;\n      record_add_edge_visitor<mbglIndex*,mbglIndex*> add_edge_visitor(\n            i, i+endedges, j, j+endedges, nedges);\n      rval= triangulate_bgl_graph(g, 1, 1, 1, add_edge_visitor);\n    } else {\n      mbglIndex cval1= 0;\n      mbglIndex extra_edges= 0;\n      typedef yasmic::constant_iterator<mbglIndex> dummy_iterator;\n      dummy_iterator di(&cval1);\n      record_add_edge_visitor<dummy_iterator,dummy_iterator> add_edge_visitor(\n            di, di, di, di, &extra_edges);\n      rval= triangulate_bgl_graph(g, 1, 1, 1, add_edge_visitor);\n    }\n    if (rval != 0) { return rval; } // return on error\n    return chrobak_payne_straight_line_drawing_on_maximal_graph(g,\n            just_ordering, p, X);\n  }\n}\n\n\n\n\n\n", "meta": {"hexsha": "89a0caf19b3c456fa5c651d163492b9425494ab8", "size": 20701, "ext": "cc", "lang": "C++", "max_stars_repo_path": "2A/Graphes/TPs/matlab_bgl/libmbgl/planar.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/planar.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/planar.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": 35.5077186964, "max_line_length": 83, "alphanum_fraction": 0.6696294865, "num_tokens": 5654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5421114522209476}}
{"text": "#include <CGAL/boost/graph/alpha_expansion_graphcut.h>\n#include <boost/graph/adjacency_list.hpp>\n\nstruct Vertex_property\n{\n  int label;\n  std::vector<double> cost;\n};\n\nstruct Edge_property\n{\n  double weight;\n};\n\nusing Graph = boost::adjacency_list <boost::setS,\n                                     boost::vecS,\n                                     boost::undirectedS,\n                                     Vertex_property,\n                                     Edge_property>;\nusing GT = boost::graph_traits<Graph>;\nusing vertex_descriptor = GT::vertex_descriptor;\nusing edge_descriptor = GT::edge_descriptor;\n\nint main()\n{\n  std::array<char, 3> labels = { 'X', ' ', 'O' };\n\n  std::array<std::array<int, 6>, 5> input\n    = { { { 0, 2, 0, 1, 1, 1 },\n          { 0, 0, 1, 0, 1, 2 },\n          { 2, 0, 1, 1, 2, 2 },\n          { 0, 1, 1, 2, 2, 0 },\n          { 1, 1, 2, 0, 2, 2 } } };\n\n  std::array<std::array<vertex_descriptor, 6>, 5> vertices;\n\n  // Init vertices from values\n  Graph g;\n  for (std::size_t i = 0; i < input.size(); ++ i)\n    for (std::size_t j = 0; j < input[i].size(); ++ j)\n    {\n      vertices[i][j] = boost::add_vertex(g);\n      g[vertices[i][j]].label = input[i][j];\n\n      // Cost of assigning this vertex to any label is positive except\n      // for current label which is 0 (favor init solution)\n      g[vertices[i][j]].cost.resize(3, 1);\n      g[vertices[i][j]].cost[std::size_t(input[i][j])] = 0;\n    }\n\n  // Display input values\n  std::cerr << \"Input:\" << std::endl;\n  for (std::size_t i = 0; i < vertices.size(); ++ i)\n  {\n    for (std::size_t j = 0; j < vertices[i].size(); ++ j)\n      std::cerr << labels[std::size_t(g[vertices[i][j]].label)];\n    std::cerr << std::endl;\n  }\n\n  // Init adjacency\n  double weight = 0.5;\n  for (std::size_t i = 0; i < vertices.size(); ++ i)\n    for (std::size_t j = 0; j < vertices[i].size(); ++ j)\n    {\n      // Neighbor vertices are connected\n      if (i < vertices.size() - 1)\n      {\n        edge_descriptor ed = boost::add_edge (vertices[i][j], vertices[i+1][j], g).first;\n        g[ed].weight = weight;\n      }\n      if (j < vertices[i].size() - 1)\n      {\n        edge_descriptor ed = boost::add_edge (vertices[i][j], vertices[i][j+1], g).first;\n        g[ed].weight = weight;\n      }\n    }\n\n  std::cerr << std::endl << \"Alpha expansion...\" << std::endl << std::endl;\n  CGAL::alpha_expansion_graphcut (g,\n                                  get (&Edge_property::weight, g),\n                                  get (&Vertex_property::cost, g),\n                                  get (&Vertex_property::label, g),\n                                  CGAL::parameters::vertex_index_map (get (boost::vertex_index, g)));\n\n\n  // Display output graph\n  std::cerr << \"Output:\" << std::endl;\n  for (std::size_t i = 0; i < vertices.size(); ++ i)\n  {\n    for (std::size_t j = 0; j < vertices[i].size(); ++ j)\n      std::cerr << labels[std::size_t(g[vertices[i][j]].label)];\n    std::cerr << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "a086be418e3e01e29a5d165be1f6fc314223cb58", "size": 2970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGL/examples/BGL_graphcut/alpha_expansion_example.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_graphcut/alpha_expansion_example.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_graphcut/alpha_expansion_example.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.618556701, "max_line_length": 101, "alphanum_fraction": 0.5181818182, "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5421114508831326}}
{"text": "#include <Engine/MeshEdit/MinSurf.h>\n\n#include <Engine/Primitive/TriMesh.h>\n\n#include <Eigen/Sparse>\n\nusing namespace Ubpa;\n\nusing namespace std;\nusing namespace Eigen;\n \nMinSurf::MinSurf(Ptr<TriMesh> triMesh)\n\t: heMesh(make_shared<HEMesh<V>>())\n{\n\tInit(triMesh);\n}\n\nvoid MinSurf::Clear() {\n\theMesh->Clear();\n\ttriMesh = nullptr;\n}\n\nbool MinSurf::Init(Ptr<TriMesh> triMesh) {\n\tClear();\n\n\tif (triMesh == nullptr)\n\t\treturn true;\n\n\tif (triMesh->GetType() == TriMesh::INVALID) {\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is invalid\\n\");\n\t\treturn false;\n\t}\n\n\t// init half-edge structure\n\tsize_t nV = triMesh->GetPositions().size();\n\tvector<vector<size_t>> triangles;\n\ttriangles.reserve(triMesh->GetTriangles().size());\n\tfor (auto triangle : triMesh->GetTriangles())\n\t\ttriangles.push_back({ triangle->idx[0], triangle->idx[1], triangle->idx[2] });\n\theMesh->Reserve(nV);\n\theMesh->Init(triangles);\n\n\tif (!heMesh->IsTriMesh() || !heMesh->HaveBoundary()) {\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is not a triangle mesh or hasn't a boundaries\\n\");\n\t\theMesh->Clear();\n\t\treturn false;\n\t}\n\n\t// triangle mesh's positions ->  half-edge structure's positions\n\tfor (int i = 0; i < nV; i++) {\n\t\tauto v = heMesh->Vertices().at(i);\n\t\tv->pos = triMesh->GetPositions()[i].cast_to<vecf3>();\n\t}\n\n\tthis->triMesh = triMesh;\n\treturn true;\n}\n\nbool MinSurf::Run() {\n\tif (heMesh->IsEmpty() || !triMesh) {\n\t\tprintf(\"ERROR::MinSurf::Run\\n\"\n\t\t\t\"\\t\"\"heMesh->IsEmpty() || !triMesh\\n\");\n\t\treturn false;\n\t}\n\n\tMinimize();\n\n\t// half-edge structure -> triangle mesh\n\tsize_t nV = heMesh->NumVertices();\n\tsize_t nF = heMesh->NumPolygons();\n\tvector<pointf3> positions;\n\tvector<unsigned> indice;\n\tpositions.reserve(nV);\n\tindice.reserve(3 * nF);\n\tfor (auto v : heMesh->Vertices())\n\t\tpositions.push_back(v->pos.cast_to<pointf3>());\n\tfor (auto f : heMesh->Polygons()) { // f is triangle\n\t\tfor (auto v : f->BoundaryVertice()) // vertices of the triangle\n\t\t\tindice.push_back(static_cast<unsigned>(heMesh->Index(v)));\n\t}\n\n\ttriMesh->Init(indice, positions);\n\n\treturn true;\n}\n\nvoid MinSurf::Minimize() {\n\t// TODO\n\tauto bound = heMesh->Boundaries();\n\tvector<int> bound_idx;\n\t//get the index of the boundary\n\tfor (auto& ver : bound)\n\t{\n\t\tfor (auto p_v : ver)\n\t\t{\n\t\t\tbound_idx.push_back(heMesh->Index(p_v->Pair()->End()));\n\t\t}\n\t}\n\t//sort\n\tbound_idx.erase(std::unique(bound_idx.begin(), bound_idx.end()), bound_idx.end());\n\tstd::sort(bound_idx.begin(), bound_idx.end());\n\tconst auto& v = heMesh->Vertices();\n\n\tconst auto mat_size = v.size() - bound_idx.size();\n\tSparseMatrix<double> mat(mat_size, mat_size);\n\t//set matrix\n\tMatrixX3d right = Eigen::MatrixX3d::Zero(mat_size, 3);\n\n\tusing std::cout;\n\t//get the matrix\n\tfor (auto vert : v)\n\t{\n\t\tint index = find_idx(bound_idx, heMesh->Index(vert));\n\t\tif (index != -1) //if the vertex is not in the boundary\n\t\t{\n\t\t\tauto adj_v = vert->AdjVertices(); //get the adjvertexs\n\t\t\tdouble degree = adj_v.size();\n\t\t\tif (index >= mat_size)\n\t\t\t{\n\t\t\t\tcout << \"index=\" << index << \"mat_size=\" << mat_size << endl;\n\t\t\t\tsystem(\"pause\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmat.coeffRef(index, index) ++;\n\t\t\t}\n\t\t\tfor (auto v : adj_v)\n\t\t\t{\n\t\t\t\tint row_idx = find_idx(bound_idx, heMesh->Index(v));\n\t\t\t\tif (row_idx == -1)\n\t\t\t\t{\n\t\t\t\t\tfor (int i = 0; i < 3; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tright(index, i) += v->pos[i] / degree;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (index >= mat_size)\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << \"index:\" << index << endl;\n\t\t\t\t\t\tsystem(\"pause\");\n\t\t\t\t\t}\n\t\t\t\t\telse\tif (row_idx >= mat_size)\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << \"row_index:\" << row_idx << endl;\n\t\t\t\t\t\tsystem(\"pause\");\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmat.coeffRef(index, row_idx) -= 1 / degree;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//solve matrix\n\tSparseLU<SparseMatrix<double>> solver;\n\tsolver.compute(mat);\n\n\tif (solver.info() != Success)\n\t{\n\t\tcerr << \"Unable to decompose the matrix\" << endl;\n\t}\n\n\tauto result = solver.solve(right);\n\t//set vertex\n\tfor (auto vert : v)\n\t{\n\t\tint idx = find_idx(bound_idx, heMesh->Index(vert));\n\t\tif (idx != -1)\n\t\t{\n\t\t\tfor (int i = 0; i < 3; i++)\n\t\t\t{\n\t\t\t\tvert->pos[i] = result(idx, i);\n\t\t\t}\n\t\t}\n\t}\n}\n\n//return the index of the vertex in the matrix above\nconst int MinSurf::find_idx(std::vector<int>& vec, int idx)\n{\n\tint N = vec.size();\n\tif (idx < vec[0]) return idx;\n\tif (idx > vec[N - 1]) return idx - N ;\n\tfor (int i = 0; i < N; i++)\n\t{\n\t\tif (idx == vec[i]) return -1;\n\t\tif (idx < vec[i])\n\t\t{\n\t\t\treturn idx - i;\n\t\t}\n\t}\n}\n\n", "meta": {"hexsha": "1f3f3e94be54ab87e3093d6d6f0d1e5cd06a38c3", "size": 4360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/MinSurf.cpp", "max_stars_repo_name": "Qinxin-Yan/USTC_CG-1", "max_stars_repo_head_hexsha": "80dc240bea879f000196986b98efcd0bbf8dec34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/MinSurf.cpp", "max_issues_repo_name": "Qinxin-Yan/USTC_CG-1", "max_issues_repo_head_hexsha": "80dc240bea879f000196986b98efcd0bbf8dec34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/MinSurf.cpp", "max_forks_repo_name": "Qinxin-Yan/USTC_CG-1", "max_forks_repo_head_hexsha": "80dc240bea879f000196986b98efcd0bbf8dec34", "max_forks_repo_licenses": ["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.9095477387, "max_line_length": 83, "alphanum_fraction": 0.6128440367, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.542104901478454}}
{"text": "#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/array.hpp>\n#include <array>\n#include <utility>\n#include <iostream>\n\nint main()\n{\n  enum { topLeft, topRight, bottomRight, bottomLeft };\n\n  std::array<std::pair<int, int>, 4> edges{{\n    std::make_pair(topLeft, topRight),\n    std::make_pair(topRight, bottomRight),\n    std::make_pair(bottomRight, bottomLeft),\n    std::make_pair(bottomLeft, topLeft)\n  }};\n\n  struct edge_properties\n  {\n    int weight;\n  };\n\n  typedef boost::adjacency_list<boost::listS, boost::vecS,\n    boost::undirectedS, boost::no_property,\n    edge_properties> graph;\n\n  boost::array<edge_properties, 4> props{{2, 1, 1, 1}};\n\n  graph g{edges.begin(), edges.end(), props.begin(), 4};\n\n  boost::array<int, 4> directions;\n  boost::dijkstra_shortest_paths(g, bottomRight,\n    boost::predecessor_map(directions.begin()).\n    weight_map(boost::get(&edge_properties::weight, g)));\n\n  int p = topLeft;\n  while (p != bottomRight)\n  {\n    std::cout << p << '\\n';\n    p = directions[p];\n  }\n  std::cout << p << '\\n';\n}", "meta": {"hexsha": "0b49c7381ae20f125806947fe332525999a8a59f", "size": 1135, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Example/graph_13/main.cpp", "max_stars_repo_name": "KwangjoJeong/Boost", "max_stars_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_stars_repo_licenses": ["MIT"], "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/graph_13/main.cpp", "max_issues_repo_name": "KwangjoJeong/Boost", "max_issues_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_issues_repo_licenses": ["MIT"], "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/graph_13/main.cpp", "max_forks_repo_name": "KwangjoJeong/Boost", "max_forks_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_forks_repo_licenses": ["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.2222222222, "max_line_length": 58, "alphanum_fraction": 0.6757709251, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5421049006695138}}
{"text": "///////////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::location_scale::log_unnormalized_pdf.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_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_LOCATION_SCALE_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_LOCATION_SCALE_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#include <boost/concept/assert.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/location_scale/location_scale.hpp>\n#include <boost/statistics/detail/distribution_common/meta/value.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace distribution{\nnamespace toolkit{\n\n    template<typename Z,typename T>\n    T\n    log_unnormalized_pdf(\n        const distribution::toolkit::location_scale_distribution<Z>& d,\n        const T& x\n    ){\n        typedef distribution::toolkit::location_scale_distribution<Z> dist_;\n\n        T z = (x-d.mu())/d.sigma();\n        T result = log_unnormalized_pdf(d.z(),z); \n        // -log ( sigma ) is a constant so it is ignored\n        return result;\n    }\n\n}// toolkit\n}// distribution\n}// detail\n}// statistics \n}// boost\n\n#endif\n", "meta": {"hexsha": "693e988ab913e3472a589e154d0f62e3eb6d462d", "size": 1679, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/location_scale/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/location_scale/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/location_scale/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": 39.9761904762, "max_line_length": 103, "alphanum_fraction": 0.5932102442, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5421049006695137}}
{"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 t_distribution.hpp\n * \\date August 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n * \\author Cristina Garcia Cifuentes (c.garciacifuentes@gmail.com)\n */\n\n#pragma once\n\n\n#include <Eigen/Dense>\n\n#include <random>\n#include <boost/math/distributions.hpp>\n\n#include <fl/util/meta.hpp>\n#include <fl/util/types.hpp>\n#include <fl/exception/exception.hpp>\n#include <fl/distribution/gaussian.hpp>\n#include <fl/distribution/chi_squared.hpp>\n#include <fl/distribution/interface/evaluation.hpp>\n#include <fl/distribution/interface/moments.hpp>\n#include <fl/distribution/interface/standard_gaussian_mapping.hpp>\n\nnamespace fl\n{\n\n/**\n * \\ingroup distributions\n *\n * \\brief TDistribution represents a multivariate student's t-distribution\n * \\f$t_\\nu(\\mu, \\Sigma)\\f$, where \\f$\\nu \\in \\mathbb{R} \\f$ is the\n * degree-of-freedom, \\f$\\mu\\in \\mathbb{R}^n\\f$ the distribution location and\n * \\f$\\Sigma \\in \\mathbb{R}^{n\\times n} \\f$ the scaling or covariance matrix.\n */\ntemplate <typename Variate>\nclass TDistribution\n    : public Moments<Variate>,\n      public Evaluation<Variate>,\n      public StandardGaussianMapping<\n                Variate,\n                JoinSizes<SizeOf<Variate>::Value, 1>::Value>\n{\nprivate:\n    typedef StandardGaussianMapping<\n                Variate,\n                JoinSizes<SizeOf<Variate>::Value, 1>::Value\n            > StdGaussianMappingBase;\n\npublic:\n    /**\n     * \\brief Second moment matrix type, i.e covariance matrix\n     */\n    typedef typename Moments<Variate>::SecondMoment SecondMoment;\n\n    /**\n     * \\brief Represents the StandardGaussianMapping standard variate type which\n     *        is of the same dimension as the \\c TDistribution \\c Variate. The\n     *        StandardVariate type is used to sample from a standard normal\n     *        Gaussian and map it to this \\c TDistribution\n     */\n    typedef typename StdGaussianMappingBase::StandardVariate StandardVariate;\n\npublic:\n    /**\n     * \\brief Creates a dynamic or fixed size t-distribution.\n     *\n     * \\param degrees_of_freedom\n     *                  t-distribution degree-of-freedom\n     * \\param dimension Dimension of the distribution. The default is defined by\n     *                  the dimension of the variable type \\em Vector. If the\n     *                  size of the Variate at compile time is fixed, this will\n     *                  be adapted. For dynamic-sized Variable the dimension is\n     *                  initialized to 0.\n     */\n    explicit TDistribution(Real degrees_of_freedom,\n                           int dim = DimensionOf<Variate>())\n        : StdGaussianMappingBase(dim + 1),\n          chi2_(degrees_of_freedom),\n          normal_(dim)\n    {\n        static_assert(Variate::SizeAtCompileTime != 0,\n                      \"Illegal static dimension\");\n\n        normal_.set_standard();\n    }\n\n    /**\n     * \\brief Overridable default destructor\n     */\n    virtual ~TDistribution() noexcept { }\n\n    /**\n     * \\brief Returns a t-distribution sample of the type \\c Variate determined\n     * by mapping a standard normal sample into the t-distribution sample space\n     *\n     * \\param sample    Standard normal sample\n     *\n     * \\throws See Gaussian<Variate>::map_standard_normal\n     */\n    Variate map_standard_normal(const StandardVariate& sample) const override\n    {\n        assert(sample.size() == dimension() + 1);\n\n        Real u = chi2_.map_standard_normal(sample.bottomRows(1)(0));\n        Variate n = normal_.map_standard_normal(sample.topRows(dimension()));\n\n        // rvo\n        Variate v = location() + std::sqrt(degrees_of_freedom() / u) * n;\n        return v;\n    }\n\n    /**\n     * \\brief Returns the log. probability of the given sample \\c variate\n     *\n     * Evaluates the t-distribution pdf\n     *\n     *  \\f$ t_\\nu(\\mu, \\Sigma) = \\frac{\\Gamma\\left[(\\nu+p)/2\\right]}\n     *          {\\Gamma(\\nu/2)\n     *           \\nu^{p/2}\\pi^{p/2}\n     *           \\left|{\\boldsymbol\\Sigma}\\right|^{1/2}\n     *           \\left[1 +\n     *                 \\frac{1}{\\nu}\n     *                 ({\\mathbf x}-{\\boldsymbol\\mu})^T\n     *                 {\\boldsymbol\\Sigma}^{-1}\n     *                 ({\\mathbf x}-{\\boldsymbol\\mu})\\right]^{(\\nu+p)/2}} \\f$\n     *\n     * at location \\f${\\mathbf x}\\f$\n     *\n     *\n     * \\param variate sample which should be evaluated\n     *\n     * \\throws See Gaussian<Variate>::has_full_rank()\n     */\n    Real log_probability(const Variate& x) const override\n    {\n        return cached_log_pdf_.log_probability(*this, x);\n    }\n\n    /**\n     * \\brief Returns the Gaussian variate dimension\n     */\n    virtual int dimension() const\n    {\n        return normal_.dimension();\n    }\n\n    /**\n     * \\brief Returns a const reference to the t-distribution location (mean)\n     */\n    const Variate& mean() const override\n    {\n        return location();\n    }\n\n    /**\n     * \\brief Returns a const reference to t-distribution scaling matrix\n     * (covariance matrix)\n     *\n     * \\throws See Gaussian<Variate>::covariance()\n     */\n    const SecondMoment& covariance() const override\n    {\n        return normal_.covariance();\n    }\n\n    /**\n     * \\brief Returns the const reference to t-distribution location (mean)\n     */\n    virtual const Variate& location() const\n    {\n        return normal_.mean();\n    }\n\n    /**\n     * \\brief Returns the t-distribution degree-of-freedom\n     */\n    virtual Real degrees_of_freedom() const\n    {\n        return chi2_.degrees_of_freedom();\n    }\n\n    /**\n     * \\brief Changes the dimension of the dynamic-size t-distribution and sets\n     * it to a standard distribution with zero mean and identity covariance.\n     *\n     * \\param new_dimension New dimension of the t-distribution\n     *\n     * \\throws ResizingFixedSizeEntityException\n     *         see standard_variate_dimension(int)\n     */\n    virtual void dimension(int new_dimension)\n    {\n        StdGaussianMappingBase::standard_variate_dimension(new_dimension + 1);\n        normal_.dimension(new_dimension);\n        cached_log_pdf_.flag_dirty();\n    }\n\n    /**\n     * \\brief Sets the distribution location\n     *\n     * \\param location New t-distribution mean\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void location(const Variate& new_location) noexcept\n    {\n        normal_.mean(new_location);\n        cached_log_pdf_.flag_dirty();\n    }\n\n    /**\n     * \\brief Sets the covariance matrix\n     *\n     * \\param covariance New covariance matrix\n     *\n     * \\throws WrongSizeException\n     */\n\n    virtual void scaling_matrix(const SecondMoment& scaling_matrix)\n    {\n        normal_.covariance(scaling_matrix);\n        cached_log_pdf_.flag_dirty();\n    }\n\n    /**\n     * \\brief  Sets t-distribution degree-of-freedom\n     */\n    virtual void degrees_of_freedom(Real dof)\n    {\n        chi2_.degrees_of_freedom(dof);\n        cached_log_pdf_.flag_dirty();\n    }\n\nprotected:\n    /** \\cond internal */\n\n    /**\n     * \\brief \\f$\\chi^2\\f$ distribution used to generate samples of the\n     * t-distribution\n     */\n    ChiSquared chi2_;\n\n    /**\n     * \\brief \\f${\\cal N}(\\boldmath{0}, \\Sigma)\\f$ Gaussian distribution used\n     * to generate samples of the t-distribution\n     */\n    Gaussian<Variate> normal_;\n\n    /** \\endcond */\n\n\nprivate:\n    class CachedLogPdf\n    {\n    public:\n        CachedLogPdf()\n            : dirty_(true)\n        { }\n\n        /**\n         * Evaluates the t-distribution pdf at a given position \\c x\n         */\n        Real log_probability(\n                const TDistribution<Variate>& t_distr, const Variate& x)\n        {\n            if (dirty_) update(t_distr);\n\n            Variate z = x - t_distr.location();\n            Real dof = t_distr.degrees_of_freedom();\n\n            Real quad_term = (z.transpose() * t_distr.normal_.precision() * z);\n            Real ln_term = std::log(Real(1) + quad_term  / dof);\n\n            return const_term_ - const_factor_ * ln_term;\n        }\n\n        void flag_dirty() { dirty_ = true; }\n\n    private:\n        void update(const TDistribution<Variate>& t_distr)\n        {\n            Real half = Real(1)/Real(2);\n            Real dim = t_distr.dimension();\n            Real dof = t_distr.degrees_of_freedom();\n            const_term_ =\n                boost::math::lgamma(half * (dof + dim))\n                - boost::math::lgamma(half * dof)\n                - half * (dim * std::log(M_PI * dof))\n                - half * (std::log(t_distr.normal_.covariance_determinant()));\n\n            const_factor_ = half * (dof + dim);\n\n            dirty_ = false;\n        }\n\n        bool dirty_;\n        Real const_factor_;\n        Real const_term_;\n    };\n\n    friend class CachedLogPdf;\n\n    mutable CachedLogPdf cached_log_pdf_;\n};\n\n}\n", "meta": {"hexsha": "d51b1886e15635a56c7d652d1b34a3ad5abbd670", "size": 9114, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/distribution/t_distribution.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/distribution/t_distribution.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/distribution/t_distribution.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.3925233645, "max_line_length": 80, "alphanum_fraction": 0.6020408163, "num_tokens": 2175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.5421048972766647}}
{"text": "/**\n *@file main.cpp\n */\n\n#include <fstream>\n#include <armadillo>\n#include \"time.h\"\n#include \"Solver.h\"\n\n/**\n * @mainpage Calcul et trac\u00e9 de l'Equation de Schr\u00f6dinger non relativiste d\u00e9pendant du temps\n * \n * ## Equation de Schr\u00f6dinger non relativiste d\u00e9pendant du temps\n * \n * \\f[ i\\hbar\\frac{\\partial}{\\partial t}\\psi(x,y,t) = \\hat{\\mathcal{H}}_{(x,y)}\\psi(x,y,t) \\f]\n * avec l'op\u00e9rateur Hamiltonien 2D :\n\\f[\\hat{\\mathcal{H}}_{(x,y)}\\equiv \\frac{\\hat{p}_{(x)}^2}{2m} + \\frac{\\hat{p}_{(y)}^2}{2m} + \\hat{V}(x,y),\\f]\net la quantit\u00e9 de mouvement :\n\\f[\\forall u \\in \\{x,y\\},\\hspace{5mm}\\hat{p}_{(u)}\\equiv -i\\hbar\\frac{\\partial}{\\partial u}.\\f]\nConstantes:\n* \\f$\\hbar\\f$ est la **constante de Planck r\u00e9duite**\n\\f[\\hbar \\equiv 6.582119514\\times10^{\u221222}\\,\\textrm{MeV.s}\\f]\n* \\f$m\\f$ est la **masse du neutron**\n\\f[m\\equiv 939.5654133\\,\\textrm{MeV/c}^2\\f]\n* \\f$i\\f$ est le **nombre imaginaire** \\f$i^2=-1\\f$\n */\n\n/**\n *La fonction principale\n *\n *Cette fonction a pour but de calculer les donn\u00e9es n\u00e9cessaires pour tracer les grraphes\n *\n *@return la fonction cr\u00e9er des fichier .txt et retourne 0\n */\n\nint main()\n{\n    arma::mat A = arma::zeros(2,2);\n    arma::mat B = arma::ones(2,2);\n    arma::cx_mat C1 = arma::cx_mat(A,B);\n    arma::cx_mat C2 = arma::cx_mat(B,A);\n\n    Solver s = Solver(C1, A, 1, 1, 0.1, 0.1,0.1);\n    std::cout<< s.ftcs() <<std::endl;\n    Solver s1 = Solver(C1, A, 1, 1, 0.01, 0.1,0.1);\n    std::cout<< s1.ftcs() <<std::endl;\n    Solver s2 = Solver(C1, A, 1, 1, 0.001, 0.1,0.1);\n    std::cout<< s2.ftcs() <<std::endl;\n    Solver s3 = Solver(C1, A, 1, 1, 0.0001, 0.1,0.1);\n    std::cout<< s3.ftcs() <<std::endl;\n    return 0;\n}\n\n\n", "meta": {"hexsha": "574f92f5e110fe46126b23ef45bb16e41eca3e14", "size": 1645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "DinghaoLI/Schrodinger_equation_3D", "max_stars_repo_head_hexsha": "d987fd8a711d4f3b13727b576caacf399c3fb10b", "max_stars_repo_licenses": ["MIT"], "max_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/Schrodinger_equation_3D", "max_issues_repo_head_hexsha": "d987fd8a711d4f3b13727b576caacf399c3fb10b", "max_issues_repo_licenses": ["MIT"], "max_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/Schrodinger_equation_3D", "max_forks_repo_head_hexsha": "d987fd8a711d4f3b13727b576caacf399c3fb10b", "max_forks_repo_licenses": ["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.9090909091, "max_line_length": 109, "alphanum_fraction": 0.6024316109, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973932, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5421048958108768}}
{"text": "#include \"velocity_verlet.h\"\n\n#include <Eigen/Dense>\n#include <memory>\n#include <vector>\n\n#include \"bond.h\"\n#include \"constants.h\"\n\n\nEigen::MatrixXd calculate_forces(const std::vector<std::unique_ptr<Bond>>& bonds,\n                                 const Eigen::MatrixXd& positions) {\n    //! Calculate the forces on each atom\n    //! uses Newton's third law in that each force has an equal and opposite reaction\n    /*! \n     *! \\param[in] bonds a vector of polymorphic bonds between two atoms which will be used to calculate forces. Must have a force virtual method\n     *! \\param[in] positions the positions, used by the bonds to calculate forces\n     */\n    Eigen::MatrixXd forces = Eigen::MatrixXd::Zero(positions.rows(), positions.cols());\n    for (const auto& bond : bonds) {\n        const Eigen::VectorXd bond_force = bond->force(positions);\n        forces.row(bond->atoms[0]) -= bond_force;\n        forces.row(bond->atoms[1]) += bond_force;\n    }\n    return forces;\n}\n\nEigen::MatrixXd calculate_accelerations(const std::vector<std::unique_ptr<Bond>>& bonds,\n                                 const Eigen::MatrixXd& positions,\n                                 const Eigen::MatrixXd& masses) {\n    //! Calculate the forces on each atom\n    //! uses Newton's third law in that each force has an equal and opposite reaction\n    /*! \n     *! \\param[in] bonds a vector of polymorphic bonds between two atoms which will be used to calculate forces. Must have a force virtual method\n     *! \\param[in] positions the positions, used by the bonds to calculate forces\n     */\n    Eigen::MatrixXd accelerations = calculate_forces(bonds, positions);\n    for (int i = 0; i < accelerations.rows(); ++i) {\n        accelerations.row(i) /= masses(i);\n    }\n    return accelerations;\n}\n\n\n\nEigen::MatrixXd velocity_verlet(Eigen::MatrixXd& positions, Eigen::MatrixXd& velocities,\n                                Eigen::MatrixXd& accelerations, const Eigen::VectorXd& masses,\n                                const double dt, const std::vector<std::unique_ptr<Bond>>& bonds) {\n    //! Solve Newton's laws of motion numerically by stepping forwards a small timestep.\n    //! Solve $ F = m a $ numerically in increments of $ \\delta t $. Use the equations\n    //! $ x = x + v * \\delta t + 0.5 * a * \\delta t^2 $\n    //! $ a_new = F / m $\n    //! $ v = v + 0.5 * (a_new + a_old) $\n    /*! \n     *! \\param[in] positions an array of particle positions which we will mutate\n     *! \\param[in] velocities an array of particle velocities which we will mutate\n     *! \\param[in] accelerations  an array of particle accelerations which we will mutate\n     *! \\param[in] masses an array of particle masses\n     *! \\param[in] dt the timestep, which should be at least 1/10 of the period of the shortest bond frequency\n     *! \\param[in] bonds an array of bonds which will be used to calculate forces\n     *! \\return new_positions the new updated positions\n     */\n    positions += (velocities * dt) + (accelerations * dt * dt / 2.0);\n    \n    // F = ma, therefore a = F/m\n    Eigen::MatrixXd new_accelerations = calculate_accelerations(bonds, positions, masses);\n    velocities += (accelerations + new_accelerations) * dt / 2.0;\n    accelerations = new_accelerations;\n    return positions;\n}\n\nvoid excite_bond(const std::unique_ptr<Bond>& bond, Eigen::MatrixXd& positions, const Eigen::MatrixXd& masses,\n                 const double excitement_factor) {\n    //! Excite a single bond by stretching it by the excitement factor.\n    //! For the bond, replace the position of the atoms to be exactly along the bond\n    //! vector, with the distance between them being (equilibrium distance * excitement factor).\n    //! Preserves the centre of mass of this bond.\n    /*! \n     *! \\param[in] bond a bond object to excite\n     *! \\param[in] positions a mutable array of positions, which we will change\n     *! \\param[in] excitement_factor the multiple of the equilibrium bond length to set the new bond length to\n     */\n    const Eigen::VectorXd old_com = (masses(bond->atoms[0]) * positions.row(bond->atoms[0]) + masses(bond->atoms[1]) * positions.row(bond->atoms[1])) / (masses(bond->atoms[0]) + masses(bond->atoms[1]));\n    const Eigen::VectorXd displacement_vector\n        = bond->rail * bond->equilibrium_distance * excitement_factor * -1;\n    const Eigen::VectorXd old_position = positions.row(bond->atoms[0]);\n    positions.row(bond->atoms[1]) = old_position + displacement_vector;\n    const Eigen::VectorXd new_com = (masses(bond->atoms[0]) * positions.row(bond->atoms[0]) + masses(bond->atoms[1]) * positions.row(bond->atoms[1])) / (masses(bond->atoms[0]) + masses(bond->atoms[1]));\n    \n    // Reset the centre of mass.\n    const Eigen::VectorXd com_offset = new_com - old_com;\n    positions.row(bond->atoms[0]) -= com_offset;\n    positions.row(bond->atoms[1]) -= com_offset;    \n}\n\n", "meta": {"hexsha": "b937db1f273a0c6bb9507bd084abb79180b89ab2", "size": 4860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/velocity_verlet.cpp", "max_stars_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_stars_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/velocity_verlet.cpp", "max_issues_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_issues_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/velocity_verlet.cpp", "max_forks_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_forks_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.625, "max_line_length": 202, "alphanum_fraction": 0.6580246914, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5421048915471114}}
{"text": "//--------------------------------------------------------\n// OpenNero : Random\n//  random number generator\n//  January 26, 2007\n//--------------------------------------------------------\n\n#include \"core/Common.h\"\n#include <cmath>\n#include <cstdlib>\n#include \"Random.h\"\n#include <boost/random.hpp> \n\nnamespace OpenNero \n{   \n    using namespace boost;\n\n    RandomNumberGenerator::RandomNumberGenerator() : _randomness()    {\n    }\n\n    RandomNumberGenerator::RandomNumberGenerator( const boost::uint32_t& seed ) : _randomness(seed)\n    {\n    }\n    \n    template <typename Distribution, typename Result>\n    Result generate(boost::mt19937& gen, const Result& max)\n    {\n        Distribution dist(0, max);\n        boost::variate_generator<boost::mt19937&, Distribution> vg(gen, dist);\n        return vg();\n    }\n\n    uint32_t  RandomNumberGenerator::randI() const \n    {\n        return generate<boost::uniform_int<uint32_t>, uint32_t>(_randomness, 1);\n    }\n    \n    uint32_t  RandomNumberGenerator::randI(const uint32_t& n) const \n    {\n        return generate<boost::uniform_int<uint32_t>, uint32_t>(_randomness, n);\n    }\n\n    float32_t RandomNumberGenerator::randF() const\n    {\n        return generate<boost::uniform_real<float32_t>, float32_t>(_randomness, 1);\n    }\n\n    float32_t RandomNumberGenerator::randF(const float32_t& n) const\n    {\n        return generate<boost::uniform_real<float32_t>, float32_t>(_randomness, n);\n    }\n\n    double    RandomNumberGenerator::randD() const\n    {\n        return generate<boost::uniform_real<float32_t>, float32_t>(_randomness, 1);\n    }\n    \n    double    RandomNumberGenerator::randD(const double& n) const\n    {\n        return generate<boost::uniform_real<double>, double>(_randomness, n);\n    }\n    \n    /// normal real number with mean and variance\n    float32_t    RandomNumberGenerator::normalF(const float32_t& mu, const float32_t& sigma) const\n    {\n        normal_distribution<float32_t> dist(mu, sigma);\n        boost::variate_generator<boost::mt19937&, normal_distribution<float32_t> > vg(_randomness, dist);\n        return vg();\n    }\n\n    /// normal real number with mean and variance\n    double       RandomNumberGenerator::normalD(const double& mu, const double& sigma) const\n    {\n        normal_distribution<double> dist(mu, sigma);\n        boost::variate_generator<boost::mt19937&, normal_distribution<double> > vg(_randomness, dist);\n        return vg();\n    }\n\n    RandomNumberGenerator RANDOM(55555); // random number generator with default seed\n    \n    /// set random seed\n    void setRandomSeed( const boost::uint32_t& seed )\n    {\n        RANDOM.seed(seed);\n    }\n    \n} //end OpenNero\n", "meta": {"hexsha": "be40ed2e9fcf9c7ce2d81c0e234aaac4a24af5fa", "size": 2659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/math/Random.cpp", "max_stars_repo_name": "SummitChen/opennero", "max_stars_repo_head_hexsha": "1bb1ba083cf2576e09bb7cfeac013d6940a47afe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 215.0, "max_stars_repo_stars_event_min_datetime": "2015-08-26T19:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T13:23:17.000Z", "max_issues_repo_path": "source/math/Random.cpp", "max_issues_repo_name": "SummitChen/opennero", "max_issues_repo_head_hexsha": "1bb1ba083cf2576e09bb7cfeac013d6940a47afe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2015-11-03T19:40:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-15T11:19:32.000Z", "max_forks_repo_path": "source/math/Random.cpp", "max_forks_repo_name": "SummitChen/opennero", "max_forks_repo_head_hexsha": "1bb1ba083cf2576e09bb7cfeac013d6940a47afe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T19:42:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T16:45:41.000Z", "avg_line_length": 30.5632183908, "max_line_length": 105, "alphanum_fraction": 0.6378337721, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5421048915471113}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Polyhedron_3.h>\n\n#include <CGAL/boost/graph/iterator.h>\n#include <boost/iterator/transform_iterator.hpp>\n\n#include <fstream>\n#include <algorithm>\n\ntypedef CGAL::Simple_cartesian<double> Kernel;\ntypedef CGAL::Polyhedron_3<Kernel>     Polyhedron;\n\ntypedef boost::graph_traits<Polyhedron> GraphTraits;\ntypedef GraphTraits::vertex_descriptor vertex_descriptor;\ntypedef GraphTraits::halfedge_descriptor halfedge_descriptor;\ntypedef CGAL::Halfedge_around_target_iterator<Polyhedron> halfedge_around_target_iterator;\n\n\ntemplate <typename G>\nstruct Source {\n  const G* g; \n\n  Source()\n    : g(NULL)\n  {}\n\n  Source(const G& g)\n    : g(&g)\n  {}\n\n  typedef typename boost::graph_traits<G>::vertex_descriptor result_type;\n  typedef typename boost::graph_traits<G>::halfedge_descriptor argument_type;\n\n  result_type operator()(argument_type h) const\n  {\n    return source(h, *g);\n  }\n};\n\nint main(int, char** argv)\n{ \n  std::ifstream in(argv[1]);\n  Polyhedron P;\n  in >> P;\n  GraphTraits::vertex_descriptor vd = *(vertices(P).first);\n\n  typedef boost::transform_iterator<Source<Polyhedron>,halfedge_around_target_iterator> adjacent_vertex_iterator; \n\n  halfedge_around_target_iterator hb,he;\n  boost::tie(hb,he) = halfedges_around_target(halfedge(vd,P),P);\n  adjacent_vertex_iterator avib, avie;\n  avib = boost::make_transform_iterator(hb, Source<Polyhedron>(P));\n  avie = boost::make_transform_iterator(he, Source<Polyhedron>(P));\n  \n  std::list<vertex_descriptor> V;\n  std::copy(avib,avie, std::back_inserter(V));\n  return 0;\n}\n", "meta": {"hexsha": "a990901c61bac73d8820e88a3f3533d4e7f1c90e", "size": 1567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_polyhedron_3/transform_iterator.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/transform_iterator.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/transform_iterator.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": 26.5593220339, "max_line_length": 114, "alphanum_fraction": 0.7543075941, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5421048915471113}}
{"text": "/*\n *    AsTeRICS - Assistive Technology Rapid Integration and Construction Set\n * \n * \n *        d8888      88888888888       8888888b.  8888888 .d8888b.   .d8888b. \n *       d88888          888           888   Y88b   888  d88P  Y88b d88P  Y88b\n *      d88P888          888           888    888   888  888    888 Y88b.     \n *     d88P 888 .d8888b  888   .d88b.  888   d88P   888  888         \"Y888b.  \n *    d88P  888 88K      888  d8P  Y8b 8888888P\"    888  888            \"Y88b.\n *   d88P   888 \"Y8888b. 888  88888888 888 T88b     888  888    888       \"888\n *  d8888888888      X88 888  Y8b.     888  T88b    888  Y88b  d88P Y88b  d88P\n * d88P     888  88888P' 888   \"Y8888  888   T88b 8888888 \"Y8888P\"   \"Y8888P\" \n *\n *\n *                    homepage: http://www.asterics.org \n *\n *         This project has been funded by the European Commission, \n *                      Grant Agreement Number 247730\n *  \n *  \n *         Dual License: MIT or GPL v3.0 with \"CLASSPATH\" exception\n *         (please refer to the folder LICENSE)\n * \n */\n#include \"lk_kalman_tracker_t.h\"\n\n#include \"opencv2/video/tracking.hpp\"\n#include \"opencv2/imgproc/imgproc.hpp\"\n\n//#include <boost/foreach.hpp>\n\n#include <iostream>\n\nnamespace upmc\n{\n\t/////////////////////////////////////////////////////////////////////\n\t///\n\tlk_kalman_tracker_t::lk_kalman_tracker_t():_flags(0)\n\t\t, _points_initialised(false)\n\t\t,_buf_initialised(false)\n\t\t, _processNoiseCov(0.1)\n\t\t, _measurementNoiseCov(0.01)\n\t\t, _errorCovPost(0.0001) \n\t{\n\t\t_image_buf.resize(2);\n\t}\n\t/////////////////////////////////////////////////////////////////////\n\t///\n\tlk_kalman_tracker_t::~lk_kalman_tracker_t()\n\t{\n\n\t}\n\t/////////////////////////////////////////////////////////////////////\n\tvoid lk_kalman_tracker_t::init_points(vectorOfPoints& points2track, const cv::Mat& im)\n\t{\n\t\t/*sparse_optical_flow_tracker_i::init_points(points2track);*/\n\t\t//cv::InputArray inputArray(points2track);\n\t\t_points=points2track;\n\t\t_points_initialised=true;\n\n\t\t\t//TODO: first convert?\n\t\tcv::Mat gray;\n\n\t\tif(im.channels()>1)\n\t\t\tcv::cvtColor(im, gray, CV_BGR2GRAY); \n\t\telse\n\t\t\tgray=im.clone();\n\n\t\t//REFINE\n\t\tcv::cornerSubPix(gray\n\t\t\t, points2track\n\t\t\t, cv::Size(11,11)\n\t\t\t, cv::Size(-1,-1)\n\t\t\t, cv::TermCriteria(cv::TermCriteria::MAX_ITER | cv::TermCriteria::EPS, 20, 1)\n\t\t\t);\n\t\t//\n\t\tvectorOfPoints::const_iterator it=points2track.begin();\n\n\t\tfor(; it!=points2track.end(); ++it)\n\t\t{\n\t\t\tcv::KalmanFilter kf(4, 2, 0);//state, measurement\n\t\t\t// x y u v\n\t\t\tkf.transitionMatrix =(cv::Mat_<float>(4, 4) << 1,0,1,0 , 0,1,0,1 , 0,0,1,0 , 0,0,0,1);\n\t\t\t// x y\n\t\t\tkf.measurementMatrix =(cv::Mat_<float>(2, 4) << 1,0,0,0 , 0,1,0,0);// , 0,0,1,0 ,  0,0,0,1);\n\n\t\t\t//cv::setIdentity(kf.measurementMatrix);\n\t\t\tcv::setIdentity(kf.processNoiseCov, cv::Scalar::all(_processNoiseCov));\n\t\t\tcv::setIdentity(kf.measurementNoiseCov, cv::Scalar::all(_measurementNoiseCov));\n\t\t\tcv::setIdentity(kf.errorCovPost, cv::Scalar::all(_errorCovPost));\n\n\t\t\tkf.statePost=(cv::Mat_<float>(4,1)<< it->x,it->y, 0, 0);//start with zero velocity\n\t\t\tkf.statePre=(cv::Mat_<float>(4,1)<< it->x,it->y, 0, 0);//start with zero velocity\n\n\t\t\t_KF.push_back(kf);\n\t\t}\n\t}\n\t/////////////////////////////////////////////////////////////////////\n\tvoid lk_kalman_tracker_t::track(const cv::Mat& image, upmc::tracking_data_t& tracking_data)\n\t{\n\t\t//cv::TermCriteria termcrit(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03);\n\t\t\n\t\t//tracking_data_t tracking_data;\n\t\ttracking_data.points.resize(_points.size());\n\t\ttracking_data.status.resize(_points.size());\n\t\ttracking_data.err.resize(_points.size());\n\n\t\t//TODO: first convert?\n\t\tcv::Mat gray;\n\n\t\tif(image.channels()>1)\n\t\t\tcv::cvtColor(image, gray, CV_BGR2GRAY); \n\t\telse\n\t\t\tgray=image.clone();\n\n\t\t_image_buf[eCurr]=gray;\n\n\t\tif (_points_initialised)\n\t\t{\n\t\t\tif(!_buf_initialised)\n\t\t\t{\n\t\t\t\t//fill the buffer then\n\t\t\t\t_image_buf[ePrev]=gray;\n\t\t\t\t//\n\t\t\t\t_buf_initialised=true;\n\t\t\t}//_buf_initialised\n\n\t\t\t////Predict first: loop through the K trackers\n\t\t\tstd::vector<cv::KalmanFilter>::iterator it=_KF.begin();\n\t\t\tstd::vector<cv::KalmanFilter>::const_iterator it_end=_KF.end();\n\t\t\t//\n\t\t\tstd::vector<cv::Point2f>::iterator pit=tracking_data.points.begin();\n\t\t\tstd::vector<cv::Point2f>::const_iterator pit_end=tracking_data.points.end();\n\n\t\t\t///\n\t\t\tfor(;it!=it_end, pit!=pit_end; ++it, ++pit)\n\t\t\t{\n\t\t\t\tit->predict();\n\t\t\t\t//\n\t\t\t\tpit->x=it->statePre.at<float>(0,0);\n\t\t\t\tpit->y=it->statePre.at<float>(1,0);\n\t\t\t\t/////DEBUG\n\t\t\t\t//std::cout\n\t\t\t\t//\t<< std::endl << \"Posterior: \" \n\t\t\t\t//\t<< it->statePost.at<float>(0)\n\t\t\t\t//\t<< \" : \"\n\t\t\t\t//\t<< it->statePost.at<float>(1)\n\t\t\t\t//\t<< std::endl\n\t\t\t\t//\t<< \"Predicted: \" \n\t\t\t\t//\t<< it->statePre.at<float>(0)\n\t\t\t\t//\t<< \" : \"\n\t\t\t\t//\t<< it->statePre.at<float>(1)\n\t\t\t\t//\t<< std::endl << std::endl;\n\t\t\t}\n\n\t\t\t//_flags|=cv::OPTFLOW_USE_INITIAL_FLOW;\n\t\t\t//std::vector<cv::Point2f> points;\n\t\t\t//std::vector<uchar> status;\n\t\t\t//std::vector<float> err;\n\t\t\t//Trackit!\n\t\t\tcv::calcOpticalFlowPyrLK(\n\t\t\t\t _image_buf.at(ePrev)//prev\n\t\t\t\t, _image_buf.at(eCurr)//curr\n\t\t\t\t, _points\n\t\t\t\t, tracking_data.points\n\t\t\t\t, tracking_data.status\n\t\t\t\t, tracking_data.err\n\t\t\t\t, cv::Size(11,11)\n\t\t\t\t, 3\n\t\t\t\t, cv::TermCriteria(cv::TermCriteria::MAX_ITER | cv::TermCriteria::EPS, 20, 0.03)\n\t\t\t\t, _flags\n\t\t\t\t);\n#if 1\n\t\t\t/////loop again to update the state\n\t\t\tit=_KF.begin();\n\t\t\tit_end=_KF.end();\n\t\t\tpit=tracking_data.points.begin();//now with the new points\n\t\t\tpit_end=tracking_data.points.end();\n\t\t\t/////\n\t\t\t//std::cout << \"UPDATE\" << std::endl;\n\t\t\t/////\n\t\t\tfor(;it!=it_end, pit!=pit_end; ++it, ++pit)\n\t\t\t{\n\t\t\t\tcv::Mat measurement=(cv::Mat_<float>(2,1) \n\t\t\t\t\t<< pit->x, pit->y\n\t\t\t\t\t);\n\t\t\t\tit->correct(measurement);\n\t\t\t\t//\n\t\t\t\tpit->x=it->statePost.at<float>(0,0);\n\t\t\t\tpit->y=it->statePost.at<float>(1,0);\t\t\t\t\t\n\t\t\t}\n#endif\n\t\t\t///update\n\t\t\t_points=tracking_data.points;\n\t\t\t///\n\t\t\tcv::swap(_image_buf[ePrev], _image_buf[eCurr]);\n\n\t\t}//_points_initialised\n\n\t\t//return tracking_data;\n\t}///track\n\t/////////////////////////////////////////////////////////////////////\n\tvoid lk_kalman_tracker_t::reset()\n\t{\n\t\t_points_initialised=false;\n\t\t_buf_initialised=false;\n\n\t\t_image_buf.clear();\n\t\t_image_buf.resize(2);\n\n\t\t_flags=0;\n\t\t_KF.clear();\n\t\t//reset();\n\t}\n\t/////////////////////////////////////////////////////////////////////\n\n}//namespace", "meta": {"hexsha": "cadcf0897b9f3a226fb85d038c70d79b506a50b5", "size": 6225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source Code/AsTeRICS/ARE/components/libraries/upmc/lk_kalman_tracker_t.cpp", "max_stars_repo_name": "EliKabasele/openHAB_MyUI", "max_stars_repo_head_hexsha": "f6c66a42cca24a484c2bd4013b20b05edaa88161", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-06-30T14:32:51.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-12T18:09:18.000Z", "max_issues_repo_path": "Source Code/AsTeRICS/ARE/components/libraries/upmc/lk_kalman_tracker_t.cpp", "max_issues_repo_name": "EliKabasele/openHAB_MyUI", "max_issues_repo_head_hexsha": "f6c66a42cca24a484c2bd4013b20b05edaa88161", "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": "Source Code/AsTeRICS/ARE/components/libraries/upmc/lk_kalman_tracker_t.cpp", "max_forks_repo_name": "EliKabasele/openHAB_MyUI", "max_forks_repo_head_hexsha": "f6c66a42cca24a484c2bd4013b20b05edaa88161", "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.6866359447, "max_line_length": 95, "alphanum_fraction": 0.5742971888, "num_tokens": 2068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604134, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5421048913540465}}
{"text": "//==================================================================================================\n/*\n  Copyright 2017 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//! [two_split]\n#include <boost/simd/arithmetic.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <iostream>\n\nnamespace bs =  boost::simd;\nusing pack_ft =  bs::pack <float, 4>;\n\nint main()\n{\n  pack_ft pf = { 1.0f, -2.0f, 3.0f, -4.0 };\n  pf *=  bs::Pi<float>();\n  pack_ft s, e;\n  std::tie(s, e) = bs::two_split(pf);\n  std::cout\n    <<  \"---- simd\" << '\\n'\n    << \" <- pf =                                  \" << pf << '\\n'\n    << \"  std::tie(s, e) = bs::two_split(pf)    \" << '\\n'\n    << \" ->  s =                                  \" << s << '\\n'\n    << \" ->  e =                                  \" << e << '\\n';\n\n  float xf = 3.0f*bs::Pi<float>();\n  float ss, se;\n  std::tie(ss, se) = bs::two_split(xf);\n  std::cout\n    << \"---- scalar\"  << '\\n'\n    << \" xf =                                     \" << xf << '\\n'\n    << \"  std::tie(ss, se) = bs::two_split(xf)  \" << '\\n'\n    << \" ->  ss =                                 \" << ss << '\\n'\n    << \" ->  se =                                 \" << se << '\\n';\n\n  return 0;\n}\n//! [two_split]\n", "meta": {"hexsha": "c0b18aa71da29f12f0786a67b83a84884c0634d2", "size": 1485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/arithmetic/two_split.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/doc/arithmetic/two_split.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/doc/arithmetic/two_split.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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": 33.0, "max_line_length": 100, "alphanum_fraction": 0.3676767677, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5421048886383715}}
{"text": "#include <iostream>\n#include <ostream>\n#include <toppra/geometric_path/piecewise_poly_path.hpp>\n#include <toppra/toppra.hpp>\n#include <Eigen/Dense>\n\n#ifdef TOPPRA_OPT_MSGPACK\n#include <msgpack.hpp>\n#endif\n\nnamespace toppra {\n\nMatrix differentiateCoefficients(const Matrix &coefficients) {\n  Matrix deriv(coefficients.rows(), coefficients.cols());\n  deriv.setZero();\n  for (size_t i = 1; i < coefficients.rows(); i++) {\n    deriv.row(i) = coefficients.row(i - 1) * (coefficients.rows() - i);\n  }\n  return deriv;\n}\n\nPiecewisePolyPath::PiecewisePolyPath(const Matrices & coefficients,\n                                     std::vector<value_type> breakpoints)\n    : GeometricPath (coefficients[0].cols()),\n      m_coefficients(coefficients), m_breakpoints(std::move(breakpoints)),\n      m_degree(coefficients[0].rows() - 1) {\n\n  checkInputArgs();\n  computeDerivativesCoefficients();\n}\n\nPiecewisePolyPath::PiecewisePolyPath(const Vectors &positions, const Vector &times,\n        const std::array<BoundaryCond, 2> &bc_type) {\n    // Prepare input\n    checkInputArgs(positions, times, bc_type);\n    Matrices coefficients(times.size() - 1);\n    computeCubicSplineCoefficients(positions, times, bc_type, coefficients);\n    std::vector<value_type> breakpoints (times.data(), times.data() + times.size());\n    *this = PiecewisePolyPath(coefficients, breakpoints);\n}\n\nvoid PiecewisePolyPath::computeCubicSplineCoefficients(const Vectors &positions, const Vector &times,\n        const std::array<BoundaryCond, 2> &bc_type, Matrices &coefficients) {\n    // h(i) = t(i+1) - t(i)\n    Vector h (times.rows() - 1);\n    for (size_t i = 0; i < h.rows(); i++){\n        h(i) = times(i + 1) - times(i);\n    }\n\n    // Construct the tri-diagonal matrix A based on spline continuity criteria\n    Matrix A = Matrix::Zero(times.rows(), times.rows());\n    for (size_t i = 1; i < A.rows() - 1; i++) {\n        A.row(i).segment(i - 1, 3) << h(i - 1), 2 * (h(i - 1) + h(i)), h(i);\n    }\n\n    // Construct B based on spline continuity criteria\n    Vectors B (positions.at(0).rows());\n    for (size_t i = 0; i < B.size(); i++) {\n        B[i].resize(times.rows());\n        for (size_t j = 1; j < A.rows() - 1; j++) {\n            B[i](j) = 3 * (positions[j + 1](i) - positions[j](i)) / h(j) -\n                      3 * (positions[j](i) - positions[j - 1](i)) / h(j - 1);\n        }\n    }\n\n    // Insert boundary conditions to A and B\n    if (bc_type[0].order == 1) {\n        A.row(0).segment(0, 2) << 2 * h(0), h(0);\n        for (size_t i = 0; i < B.size(); i++) {\n            B[i](0) = 3 * (positions[1](i) - positions[0](i)) / h(0) - 3 * bc_type[0].values(i);\n        }\n    }\n    else if (bc_type[0].order == 2) {\n        A(0, 0) = 2;\n        for (size_t i = 0; i < B.size(); i++) {\n            B[i](0) = bc_type[0].values(i);\n        }\n    }\n\n    if (bc_type[1].order == 1) {\n        A.row(A.rows() - 1).segment(A.cols() - 2, 2) << h(h.rows() - 1), 2 * h(h.rows() - 1);\n        for (size_t i = 0; i < B.size(); i++) {\n            B[i](B[i].rows() - 1) =\n                    3 * bc_type[1].values(i) -\n                    3 * (positions[positions.size() - 1](i) - positions[positions.size() - 2](i)) / h(h.rows() - 1);\n        }\n    }\n    else if (bc_type[1].order == 2) {\n        A(A.rows() - 1, A.cols() - 1) = 2;\n        for (size_t i = 0; i < B.size(); i++) {\n            B[i](B[i].rows() - 1) = bc_type[1].values(i);\n        }\n    }\n\n    // Solve AX = B\n    Vectors X (positions[0].rows());\n    for (size_t i = 0; i < X.size(); i++) {\n        X[i].resize(times.rows());\n        X[i] = A.colPivHouseholderQr().solve(B[i]);\n    }\n\n    // Insert spline coefficients\n    for (size_t i = 0; i < coefficients.size() ; i++) {\n        coefficients[i].resize(4, positions[0].rows());\n        for (size_t j = 0; j < coefficients[i].cols(); j++) {\n            coefficients[i](0, j) = (X[j](i + 1) - X[j](i)) / (3 * h(i));\n            coefficients[i](1, j) = X[j](i);\n            coefficients[i](2, j) = (positions[i + 1](j) - positions[i](j)) / h(i) -\n                    h(i) / 3 * (2 * X[j](i) + X[j](i + 1));\n            coefficients[i](3, j) = positions[i](j);\n        }\n    }\n}\n\nBound PiecewisePolyPath::pathInterval() const {\n  Bound v;\n  v << m_breakpoints.front(), m_breakpoints.back();\n  return v;\n};\n\nVector PiecewisePolyPath::eval_single(value_type pos, int order) const {\n  assert(order < 3 && order >= 0);\n  Vector v(m_dof);\n  v.setZero();\n  size_t seg_index = findSegmentIndex(pos);\n  auto coeff = getCoefficient(seg_index, order);\n  for (int power = 0; power < m_degree + 1; power++) {\n    v += coeff.row(power) *\n         pow(pos - m_breakpoints[seg_index], m_degree - power);\n  }\n  return v;\n}\n\n// Not the most efficient implementation. Coefficients are\n// recomputed. Should be refactored.\nVectors PiecewisePolyPath::eval(const Vector &positions, int order) const {\n  assert(order < 3 && order >= 0);\n  Vectors outputs;\n  outputs.resize(positions.size());\n  for (size_t i = 0; i < positions.size(); i++) {\n    outputs[i] = eval_single(positions(i), order);\n  }\n  return outputs;\n}\n\nsize_t PiecewisePolyPath::findSegmentIndex(value_type pos) const {\n  if (pos > m_breakpoints[m_breakpoints.size()-1] || pos < m_breakpoints[0]) {\n    std::ostringstream oss;\n    oss << \"Position \" << pos << \" is outside of range [ \" << m_breakpoints[0]\n      << \", \" << m_breakpoints[m_breakpoints.size()-1] << ']';\n    throw std::runtime_error(oss.str());\n  }\n  auto it = std::upper_bound(m_breakpoints.begin(), m_breakpoints.end(), pos);\n  auto idx = std::distance(m_breakpoints.begin(), it)-1;\n  return std::min(static_cast<size_t>(std::max(idx, long{0})), m_coefficients.size() - 1);\n}\n\nvoid PiecewisePolyPath::checkInputArgs() {\n  assert(m_coefficients[0].cols() == m_dof);\n  assert(m_coefficients[0].rows() == (m_degree + 1));\n  if ((1 + m_coefficients.size()) != m_breakpoints.size()) {\n    throw std::runtime_error(\n        \"Number of breakpoints must equals number of segments plus 1.\");\n  }\n  for (size_t seg_index = 0; seg_index < m_coefficients.size(); seg_index++) {\n    if (m_breakpoints[seg_index] >= m_breakpoints[seg_index + 1]) {\n      throw std::runtime_error(\"Require strictly increasing breakpoints\");\n    }\n  }\n}\n\nvoid PiecewisePolyPath::checkInputArgs(const Vectors &positions, const Vector &times,\n        const std::array<BoundaryCond, 2> &bc_type) {\n    if (positions.size() != times.rows()) {\n        throw std::runtime_error(\"The length of 'positions' doesn't match the length of 'times'.\");\n    }\n    if (times.rows() < 2) {\n        throw std::runtime_error(\"'times' must contain at least 2 elements.\");\n    }\n    for (size_t i = 1; i < positions.size(); i++) {\n        if (positions[i].rows() != positions[i - 1].rows()) {\n            throw std::runtime_error(\"The number of elements in each position has to be equal.\");\n        }\n    }\n    Vector dtimes (times.rows() - 1);\n    for (size_t i = 1; i < times.rows(); i++) {\n        dtimes(i - 1) = times(i) - times(i - 1);\n        if (dtimes(i - 1) <= 0) {\n            throw std::runtime_error(\"'times' must be a strictly increasing sequence.\");\n        }\n    }\n\n    // Validate boundary conditions\n    int expected_deriv_size = positions[0].size();\n    for (const BoundaryCond &bc: bc_type) {\n        if (bc.order != 1 && bc.order != 2) {\n            throw std::runtime_error(\"The specified derivative order must be 1 or 2.\");\n        }\n        if (bc.values.size() != expected_deriv_size) {\n            throw std::runtime_error(\n                    \"`deriv_value` size \" + std::to_string(bc.values.size()) + \" is not the expected one \" +\n                    std::to_string(expected_deriv_size) + \".\");\n        }\n    }\n}\n\nvoid PiecewisePolyPath::computeDerivativesCoefficients() {\n  m_coefficients_1.reserve(m_coefficients.size());\n  m_coefficients_2.reserve(m_coefficients.size());\n  for (size_t seg_index = 0; seg_index < m_coefficients.size(); seg_index++) {\n    m_coefficients_1.push_back(\n        differentiateCoefficients(m_coefficients[seg_index]));\n    m_coefficients_2.push_back(\n        differentiateCoefficients(m_coefficients_1[seg_index]));\n  }\n}\n\nconst Matrix &PiecewisePolyPath::getCoefficient(int seg_index, int order) const {\n  if (order == 0) {\n    return m_coefficients.at(seg_index);\n  } else if (order == 1) {\n    return m_coefficients_1.at(seg_index);\n  } else if (order == 2) {\n    return m_coefficients_2.at(seg_index);\n  } else {\n    return m_coefficients_2.at(seg_index);\n  }\n}\n\nvoid PiecewisePolyPath::serialize(std::ostream &O) const {\n#ifdef TOPPRA_OPT_MSGPACK\n  MatricesData allraw;\n  allraw.reserve(m_coefficients.size());\n  for (const auto &c : m_coefficients) {\n    MatrixData raw{c.rows(), c.cols(), {c.data(), c.data() + c.size()}};\n    allraw.push_back(raw);\n  }\n  msgpack::pack(O, allraw);\n  msgpack::pack(O, m_breakpoints);\n#endif\n}\n\nvoid PiecewisePolyPath::deserialize(std::istream &I) {\n#ifdef TOPPRA_OPT_MSGPACK\n  std::stringstream buffer;\n  buffer << I.rdbuf();\n  std::size_t offset = 0;\n\n  auto oh = msgpack::unpack(buffer.str().data(), buffer.str().size(), offset);\n  auto obj = oh.get();\n  TOPPRA_LOG_DEBUG(obj << \"at offset:=\" << offset << \"/\" << buffer.str().size());\n  MatricesData x;\n  toppra::Matrices new_coefficients;\n  obj.convert(x);\n  for (auto const &y : x) {\n    int nrow, ncol;\n    nrow = std::get<0>(y);\n    ncol = std::get<1>(y);\n    std::vector<value_type> mdata = std::get<2>(y);\n    toppra::Matrix m(nrow, ncol);\n    for (size_t i = 0; i < mdata.size(); i++) m(i) = mdata[i];\n    TOPPRA_LOG_DEBUG(nrow << ncol << mdata.size() << m);\n    new_coefficients.push_back(m);\n  }\n\n  reset();\n  m_coefficients = new_coefficients;\n  oh = msgpack::unpack(buffer.str().data(), buffer.str().size(), offset);\n  obj = oh.get();\n  TOPPRA_LOG_DEBUG(obj << \"at offset:=\" << offset << \"/\" << buffer.str().size());\n  assert(offset == buffer.str().size());\n  obj.convert(m_breakpoints);\n\n  TOPPRA_LOG_DEBUG(\"degree: \" << m_degree);\n  m_dof = new_coefficients[0].cols();\n  m_degree = new_coefficients[0].rows() - 1;\n  checkInputArgs();\n  computeDerivativesCoefficients();\n#endif\n}\n\nvoid PiecewisePolyPath::reset() {\n  m_breakpoints.clear();\n  m_coefficients.clear();\n  m_coefficients_1.clear();\n  m_coefficients_2.clear();\n}\n\nvoid PiecewisePolyPath::initAsHermite(const Vectors &positions,\n                                      const Vectors &velocities,\n                                      const std::vector<value_type> times) {\n  reset();\n  assert(positions.size() == times.size());\n  assert(velocities.size() == times.size());\n  TOPPRA_LOG_DEBUG(\"Constructing new Hermite polynomial\");\n  m_configSize = m_dof = positions[0].size();\n  m_degree = 3;  // cubic spline\n  m_breakpoints = times;\n  for (std::size_t i = 0; i < times.size() - 1; i++) {\n    TOPPRA_LOG_DEBUG(\"Processing segment index: \" << i << \"/\" << times.size() - 1);\n    Matrix c(4, m_dof);\n    auto dt = times[i + 1] - times[i];\n    assert(dt > 0);\n    // ... after some derivations\n    c.row(3) = positions.at(i);\n    c.row(2) = velocities.at(i);\n    c.row(0) = (velocities.at(i + 1).transpose() * dt -\n                2 * positions.at(i + 1).transpose() + c.row(2) * dt + 2 * c.row(3)) /\n               pow(dt, 3);\n    c.row(1) = (velocities.at(i + 1).transpose() - c.row(2) - 3 * c.row(0) * dt * dt) /\n               (2 * dt);\n    m_coefficients.push_back(c);\n  }\n  checkInputArgs();\n  computeDerivativesCoefficients();\n}\n\nPiecewisePolyPath PiecewisePolyPath::constructHermite(\n    const Vectors &positions, const Vectors &velocities,\n    const std::vector<value_type> times) {\n  PiecewisePolyPath path;\n  path.initAsHermite(positions, velocities, times);\n  return path;\n}\n\n} // namespace toppra\n", "meta": {"hexsha": "287f606d31f3efafe727f0bdb029d6b07e6820eb", "size": 11646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/toppra/geometric_path/piecewise_poly_path.cpp", "max_stars_repo_name": "ahoarau/toppra", "max_stars_repo_head_hexsha": "6076effd175ad975c67d01f97d979778076134a4", "max_stars_repo_licenses": ["MIT"], "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/toppra/geometric_path/piecewise_poly_path.cpp", "max_issues_repo_name": "ahoarau/toppra", "max_issues_repo_head_hexsha": "6076effd175ad975c67d01f97d979778076134a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/toppra/geometric_path/piecewise_poly_path.cpp", "max_forks_repo_name": "ahoarau/toppra", "max_forks_repo_head_hexsha": "6076effd175ad975c67d01f97d979778076134a4", "max_forks_repo_licenses": ["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.6146788991, "max_line_length": 116, "alphanum_fraction": 0.6002060793, "num_tokens": 3379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.542104874593165}}
{"text": "#include \"intermediate_computation.hpp\"\n\n#include \"utils.hpp\"\n\n#include <NTL/ZZ_pX.h>\n#include <NTL/matrix.h>\n#include \"../elements/element.hpp\"\n\n\ntemplate <typename T, typename U>\nT calculate_factorial(long n, const U& m, const std::function<std::vector<T> (long, long)>& get_A, const PolyMatrix& formula) {\n    // return compute_product_node<T, U>(get_A(0, n), m, 1);\n    if (n == 0) {\n\t\treturn T(1)%m;\n\t}\n\n\t(void)formula; //just to silence unused variable warning\n\treturn compute_product_node<T,U>(get_A(0,n), m, 1);\n}\n\n\n//#include \"rem_factorial_custom.tpp\"\n", "meta": {"hexsha": "83ea7200763af9ed99e49f10e502767a9429f83e", "size": 562, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/algorithms/rem_factorial.tpp", "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": "src/algorithms/rem_factorial.tpp", "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": "src/algorithms/rem_factorial.tpp", "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": 24.4347826087, "max_line_length": 127, "alphanum_fraction": 0.6903914591, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5419410705669404}}
{"text": "#include <boost/numeric/odeint/stepper/generation/generation_runge_kutta_cash_karp54.hpp>\n", "meta": {"hexsha": "ecbcd3e590d9d5444bad2de1ef3c1f22c73fd851", "size": 90, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_numeric_odeint_stepper_generation_generation_runge_kutta_cash_karp54.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_numeric_odeint_stepper_generation_generation_runge_kutta_cash_karp54.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_numeric_odeint_stepper_generation_generation_runge_kutta_cash_karp54.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 45.0, "max_line_length": 89, "alphanum_fraction": 0.8777777778, "num_tokens": 25, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.541941044862233}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*!\n Copyright (C) 2006 Allen Kuo\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/* a Repo calculation done using the FixedRateBondForward class\n   cf. aaBondFwd() repo example at\n   http://www.fincad.com/support/developerFunc/mathref/BFWD.htm\n\n   This repo is set up to use the repo rate to do all discounting\n   (including the underlying bond income). Forward delivery price is\n   also obtained using this repo rate. All this is done by supplying\n   the FixedRateBondForward constructor with a flat repo\n   YieldTermStructure.\n*/\n\n// the only header you need to use QuantLib\n#include <ql/quantlib.hpp>\n\n#ifdef BOOST_MSVC\n/* Uncomment the following lines to unmask floating-point\n   exceptions. Warning: unpredictable results can arise...\n\n   See http://www.wilmott.com/messageview.cfm?catid=10&threadid=9481\n   Is there anyone with a definitive word about this?\n*/\n// #include <float.h>\n// namespace { unsigned int u = _controlfp(_EM_INEXACT, _MCW_EM); }\n#endif\n\n#include <boost/timer.hpp>\n#include <iostream>\n\nusing namespace std;\nusing namespace QuantLib;\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib {\n\n    Integer sessionId() { return 0; }\n\n}\n#endif\n\nint main(int, char* []) {\n\n    try {\n\n        boost::timer timer;\n        std::cout << std::endl;\n\n        Date repoSettlementDate(14,February,2000);;\n        Date repoDeliveryDate(15,August,2000);\n        Rate repoRate = 0.05;\n        DayCounter repoDayCountConvention = Actual360();\n        Integer repoSettlementDays = 0;\n        Compounding repoCompounding = Simple;\n        Frequency repoCompoundFreq = Annual;\n\n        // assume a ten year bond- this is irrelevant\n        Date bondIssueDate(15,September,1995);\n        Date bondDatedDate(15,September,1995);\n        Date bondMaturityDate(15,September,2005);\n        Real bondCoupon = 0.08;\n        Frequency bondCouponFrequency = Semiannual;\n        // unknown what calendar fincad is using\n        Calendar bondCalendar = NullCalendar();\n        DayCounter bondDayCountConvention = Thirty360(Thirty360::BondBasis);\n        // unknown what fincad is using. this may affect accrued calculation\n        Integer bondSettlementDays = 0;\n        BusinessDayConvention bondBusinessDayConvention = Unadjusted;\n        Real bondCleanPrice = 89.97693786;\n        Real bondRedemption = 100.0;\n        Real faceAmount = 100.0;\n\n\n        Settings::instance().evaluationDate() = repoSettlementDate;\n\n        RelinkableHandle<YieldTermStructure> bondCurve;\n        bondCurve.linkTo(boost::shared_ptr<YieldTermStructure>(\n                                       new FlatForward(repoSettlementDate,\n                                                       .01, // dummy rate\n                                                       bondDayCountConvention,\n                                                       Compounded,\n                                                       bondCouponFrequency)));\n\n        /*\n        boost::shared_ptr<FixedRateBond> bond(\n                       new FixedRateBond(faceAmount,\n                                         bondIssueDate,\n                                         bondDatedDate,\n                                         bondMaturityDate,\n                                         bondSettlementDays,\n                                         std::vector<Rate>(1,bondCoupon),\n                                         bondCouponFrequency,\n                                         bondCalendar,\n                                         bondDayCountConvention,\n                                         bondBusinessDayConvention,\n                                         bondBusinessDayConvention,\n                                         bondRedemption,\n                                         bondCurve));\n        */\n\n        Schedule bondSchedule(bondDatedDate, bondMaturityDate,\n                              Period(bondCouponFrequency),\n                              bondCalendar,bondBusinessDayConvention,\n                              bondBusinessDayConvention,\n                              DateGeneration::Backward,false);\n        boost::shared_ptr<FixedRateBond> bond(\n                       new FixedRateBond(bondSettlementDays,\n                                         faceAmount,\n                                         bondSchedule,\n                                         std::vector<Rate>(1,bondCoupon),\n                                         bondDayCountConvention,\n                                         bondBusinessDayConvention,\n                                         bondRedemption,\n                                         bondIssueDate));\n        bond->setPricingEngine(boost::shared_ptr<PricingEngine>(\n                                       new DiscountingBondEngine(bondCurve)));\n\n        bondCurve.linkTo(boost::shared_ptr<YieldTermStructure> (\n                   new FlatForward(repoSettlementDate,\n                                   bond->yield(bondCleanPrice,\n                                               bondDayCountConvention,\n                                               Compounded,\n                                               bondCouponFrequency),\n                                   bondDayCountConvention,\n                                   Compounded,\n                                   bondCouponFrequency)));\n\n        Position::Type fwdType = Position::Long;\n        double dummyStrike = 91.5745;\n\n        RelinkableHandle<YieldTermStructure> repoCurve;\n        repoCurve.linkTo(boost::shared_ptr<YieldTermStructure> (\n                                       new FlatForward(repoSettlementDate,\n                                                       repoRate,\n                                                       repoDayCountConvention,\n                                                       repoCompounding,\n                                                       repoCompoundFreq)));\n\n\n        FixedRateBondForward bondFwd(repoSettlementDate,\n                                     repoDeliveryDate,\n                                     fwdType,\n                                     dummyStrike,\n                                     repoSettlementDays,\n                                     repoDayCountConvention,\n                                     bondCalendar,\n                                     bondBusinessDayConvention,\n                                     bond,\n                                     repoCurve,\n                                     repoCurve);\n\n\n        cout << \"Underlying bond clean price: \"\n             << bond->cleanPrice()\n             << endl;\n        cout << \"Underlying bond dirty price: \"\n             << bond->dirtyPrice()\n             << endl;\n        cout << \"Underlying bond accrued at settlement: \"\n             << bond->accruedAmount(repoSettlementDate)\n             << endl;\n        cout << \"Underlying bond accrued at delivery:   \"\n             << bond->accruedAmount(repoDeliveryDate)\n             << endl;\n        cout << \"Underlying bond spot income: \"\n             << bondFwd.spotIncome(repoCurve)\n             << endl;\n        cout << \"Underlying bond fwd income:  \"\n             << bondFwd.spotIncome(repoCurve)/\n                repoCurve->discount(repoDeliveryDate)\n             << endl;\n        cout << \"Repo strike: \"\n             << dummyStrike\n             << endl;\n        cout << \"Repo NPV:    \"\n             << bondFwd.NPV()\n             << endl;\n        cout << \"Repo clean forward price: \"\n             << bondFwd.cleanForwardPrice()\n             << endl;\n        cout << \"Repo dirty forward price: \"\n             << bondFwd.forwardPrice()\n             << endl;\n        cout << \"Repo implied yield: \"\n             << bondFwd.impliedYield(bond->dirtyPrice(),\n                                     dummyStrike,\n                                     repoSettlementDate,\n                                     repoCompounding,\n                                     repoDayCountConvention)\n             << endl;\n        cout << \"Market repo rate:   \"\n             << repoCurve->zeroRate(repoDeliveryDate,\n                                    repoDayCountConvention,\n                                    repoCompounding,\n                                    repoCompoundFreq)\n             << endl\n             << endl;\n\n        cout << \"Compare with example given at \\n\"\n             << \"http://www.fincad.com/support/developerFunc/mathref/BFWD.htm\"\n             <<  endl;\n        cout << \"Clean forward price = 88.2408\"\n             <<  endl\n             <<  endl;\n        cout << \"In that example, it is unknown what bond calendar they are\\n\"\n             << \"using, as well as settlement Days. For that reason, I have\\n\"\n             << \"made the simplest possible assumptions here: NullCalendar\\n\"\n             << \"and 0 settlement days.\"\n             << endl;\n\n\n        double seconds = timer.elapsed();\n        Integer hours = int(seconds/3600);\n        seconds -= hours * 3600;\n        Integer minutes = int(seconds/60);\n        seconds -= minutes * 60;\n        cout << \" \\nRun completed in \";\n        if (hours > 0)\n            cout << hours << \" h \";\n        if (hours > 0 || minutes > 0)\n            cout << minutes << \" m \";\n        cout << fixed << setprecision(0)\n             << seconds << \" s\\n\" << endl;\n\n        return 0;\n\n    } catch (exception& e) {\n        cerr << e.what() << endl;\n        return 1;\n    } catch (...) {\n        cerr << \"unknown error\" << endl;\n        return 1;\n    }\n}\n\n", "meta": {"hexsha": "0e8efecf389841b0795771e0a61cb69d2bb174de", "size": 10164, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLib/Examples/Repo/Repo.cpp", "max_stars_repo_name": "txu2014/quantlib", "max_stars_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-13T22:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-18T12:51:41.000Z", "max_issues_repo_path": "QuantLib/Examples/Repo/Repo.cpp", "max_issues_repo_name": "txu2014/quantlib", "max_issues_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/Examples/Repo/Repo.cpp", "max_forks_repo_name": "txu2014/quantlib", "max_forks_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-27T19:25:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-27T19:25:30.000Z", "avg_line_length": 40.1739130435, "max_line_length": 79, "alphanum_fraction": 0.5008854782, "num_tokens": 1867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5419113976193944}}
{"text": "// File: nnet.hpp\n#ifndef _NNET_HPP_\n#define _NNET_HPP_\n\n#include <fstream>\n\n#include <math.h>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n/* Read matrix from file */\nvoid readmatrixfromfile(std::ifstream &infile, boost::numeric::ublas::matrix<double> &matrix, int row, int col);\n\n/* Read vector from file */\nvoid readvectorfromfile(std::ifstream &infile, boost::numeric::ublas::vector<double> &vector, int col);\n\n/* matrix vector multiplication */\n/* result = mat * vec */\nvoid mbynmatvecmult(boost::numeric::ublas::vector<double> &result, boost::numeric::ublas::matrix<double> &mat, boost::numeric::ublas::vector<double> &vec, int row, int col); \n\n/* tansig function */\nvoid tansig(boost::numeric::ublas::vector<double> &x1, int dimension);\n\n/* Down scale the input */\nvoid preprocessing(boost::numeric::ublas::vector<double> &input, boost::numeric::ublas::vector<double> &min, boost::numeric::ublas::vector<double> &range, int dimension);\n\n/* Up scale the output */\ndouble postprocessing(double d, double min, double range);\n\nstruct nnetmodel {\n\t\t/* Default constructor */\n\tnnetmodel();  \n \n\t/* Public interface */\n\t\n\t/* Read in all the data from nnet model */\n\tvoid readnnetmodel(const char *name);\n\n\t/* Simulation the neural networks */\n\tdouble simnnet(boost::numeric::ublas::vector<double> &input);\n\n\t/* Data member */\n\tint NUM_OF_NEURONS;\n\tint INPUT_DIM;\n\tint OUTPUT_DIM;\n\n\tboost::numeric::ublas::vector<double> input_min;\n\tboost::numeric::ublas::vector<double> input_range;\n\tdouble output_min;\n\tdouble output_range;\n\n\tboost::numeric::ublas::vector<double> inter_output;\n\n\tboost::numeric::ublas::matrix<double> IW;\n\tboost::numeric::ublas::vector<double> b1;\n\tboost::numeric::ublas::vector<double> LW;\n\tdouble b2;\n\n\tdouble energy_offset;\n\t// The 3 dimensions are average, high, low power\n\t// Other dimensions are neighbor high, lower temperature\n\tboost::numeric::ublas::vector<double> input;\n\n\t/* variables for model sanity check */\n\tdouble bank_vol;\n\tdouble solar_min;\n\tdouble solar_max;\n};\n\n#endif\n", "meta": {"hexsha": "9e9cae6577b6cdaaa54012f7348bd3e4f56c589c", "size": 2085, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nnet/nnet.hpp", "max_stars_repo_name": "eroicaleo/HEES", "max_stars_repo_head_hexsha": "bfc1e297d6b0b7f928e590cdb97d9ccda069f483", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nnet/nnet.hpp", "max_issues_repo_name": "eroicaleo/HEES", "max_issues_repo_head_hexsha": "bfc1e297d6b0b7f928e590cdb97d9ccda069f483", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nnet/nnet.hpp", "max_forks_repo_name": "eroicaleo/HEES", "max_forks_repo_head_hexsha": "bfc1e297d6b0b7f928e590cdb97d9ccda069f483", "max_forks_repo_licenses": ["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.9583333333, "max_line_length": 174, "alphanum_fraction": 0.7275779376, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5419113913497475}}
{"text": "#include \"neohookean_material.h\"\n#include \"main.h\"\n#include \"utils.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\nusing namespace materials;\n\ntemplate <int dim, typename T>\nT CompressibleNeohookeanMaterial<dim, T>::EnergyDensity(\n        const MatrixDimT& F) const {\n    const T I1 = (F.transpose() * F).trace();\n    const T J = F.determinant();\n    if (J <= 0) {\n        throw NumericalError{\"J <= 0 in CompressibleNeohookeanMaterial\"};\n    }\n    const T log_J = log(J);\n    const T mu = Super::mu();\n    const T lambda = Super::lambda();\n    return mu / 2.0 * (I1 - dim) - mu * log_J + lambda / 2.0 * log_J * log_J;\n}\n\ntemplate <int dim, typename T>\ntypename CompressibleNeohookeanMaterial<dim, T>::MatrixDimT\nCompressibleNeohookeanMaterial<dim, T>::StressTensor(\n        const MatrixDimT& F) const {\n    const T J = F.determinant();\n    if (J <= 0) {\n        throw NumericalError{\"J <= 0 in CompressibleNeohookeanMaterial\"};\n    }\n    const MatrixDimT F_inv_trans = F.inverse().transpose();\n    const T mu = Super::mu();\n    const T lambda = Super::lambda();\n    return mu * (F - F_inv_trans) + lambda * log(J) * F_inv_trans;\n}\n\ntemplate <int dim, typename T>\ntypename CompressibleNeohookeanMaterial<dim, T>::MatrixDimT\nCompressibleNeohookeanMaterial<dim, T>::StressDifferential(\n        const MatrixDimT& F, const MatrixDimT& dF) const {\n    throw std::runtime_error{\"not implemented\"};\n}\n\ntemplate <int dim, typename Td>\ntypename CompressibleNeohookeanMaterial<dim, Td>::MatrixDim2T\nCompressibleNeohookeanMaterial<dim, Td>::StressDifferential(\n        const MatrixDimT& F) const {\n    const Td mu = Super::mu();\n    const Td lambda = Super::lambda();\n\n    using Vec = Eigen::Matrix<Td, dim, 1>;\n    using Vec2 = Eigen::Matrix<Td, dim * dim, 1>;\n    Eigen::JacobiSVD<MatrixDimT> svd{F,\n                                     Eigen::ComputeFullU | Eigen::ComputeFullV};\n    Vec S = svd.singularValues();\n    MatrixDimT U = svd.matrixU(), V = svd.matrixV(), A;\n\n    // construct the matrix A\n    Td I3 = S(0) * S(1) * S(2), Adia = lambda * (1 - std::log(I3)) + mu;\n    for (int i = 0; i < 3; ++i) {\n        A(i, i) = Adia / (S(i) * S(i)) + mu;\n        for (int j = i + 1; j < 3; ++j) {\n            A(i, j) = A(j, i) = lambda / (S(i) * S(j));\n        }\n    }\n\n    Vec2 eigs;\n    Eigen::SelfAdjointEigenSolver<MatrixDimT> eigensolver{A};\n    cf_assert(eigensolver.info() == Eigen::Success);\n    Eigen::Map<Vec>{eigs.data()} = eigensolver.eigenvalues();\n\n    {\n        Td eig6tmp = lambda * log(I3) - mu;\n#define SET(t, i, j) eigs[t + 3] = eig6tmp / (S(i) * S(j)) + mu\n        SET(0, 0, 1);\n        SET(1, 1, 2);\n        SET(2, 0, 2);\n        eig6tmp = -eig6tmp;\n        SET(3, 0, 1);\n        SET(4, 1, 2);\n        SET(5, 0, 2);\n#undef SET\n    }\n\n    MatrixDimT D0, D1, D2, T[6];\n    D0.noalias() = U.col(0) * V.col(0).transpose();\n    D1.noalias() = U.col(1) * V.col(1).transpose();\n    D2.noalias() = U.col(2) * V.col(2).transpose();\n    auto compute_Q_first3 = [&](MatrixDimT& Q, int i) {\n        auto& evec = eigensolver.eigenvectors();\n        Td z0 = evec(0, i), z1 = evec(1, i), z2 = evec(2, i);\n        Q = z0 * D0 + z1 * D1 + z2 * D2;\n    };\n    T[0] << 0, -1, 0, 1, 0, 0, 0, 0, 0;\n    T[1] << 0, 0, 0, 0, 0, 1, 0, -1, 0;\n    T[2] << 0, 0, 1, 0, 0, 0, -1, 0, 0;\n    T[3] << 0, 1, 0, 1, 0, 0, 0, 0, 0;\n    T[4] << 0, 0, 0, 0, 0, 1, 0, 1, 0;\n    T[5] << 0, 0, 1, 0, 0, 0, 1, 0, 0;\n\n    MatrixDimT Q;\n    MatrixDim2T H;\n    H.setZero();\n    int nr_pos = 0;\n    for (int i = 0; i < 9; ++i) {\n        if (baseline::g_hessian_proj && eigs[i] < 0) {\n            continue;\n        }\n        ++nr_pos;\n        if (i < 3) {\n            compute_Q_first3(Q, i);\n        } else {\n            Q.noalias() = U * T[i - 3] * V.transpose() * std::sqrt(0.5);\n        }\n        Eigen::Map<Vec2> qf{Q.data()};\n        H.noalias() += qf * qf.transpose() * eigs[i];\n    }\n    cf_assert(nr_pos);\n    return H;\n}\n\ntemplate <int dim, typename T>\nT IncompressibleNeohookeanMaterial<dim, T>::EnergyDensity(\n        const MatrixDimT& F) const {\n    const T Ic = (F.transpose() * F).trace();\n    const T J = F.determinant();\n    if (J <= 0) {\n        throw NumericalError{\"J <= 0 in IncompressibleNeohookeanMaterial\"};\n    }\n    const T mu = Super::mu();\n    const T k = Super::bulk_modulus();\n    return mu / T(2) * (std::pow(J, T(-2.0 / 3.0)) * Ic - 3) +\n           k / T(2) * (J - 1) * (J - 1);\n}\n\ntemplate <int dim, typename T>\ntypename IncompressibleNeohookeanMaterial<dim, T>::MatrixDimT\nIncompressibleNeohookeanMaterial<dim, T>::StressTensor(\n        const MatrixDimT& F) const {\n    const T J = F.determinant();\n    if (J <= 0) {\n        throw NumericalError{\"J <= 0 in IncompressibleNeohookeanMaterial\"};\n    }\n    const T Ic = (F.transpose() * F).trace();\n    const MatrixDimT F_inv_trans = F.inverse().transpose();\n    const T mu = Super::mu();\n    const T k = Super::bulk_modulus();\n    return (F - F_inv_trans * (Ic / T(3))) * (mu * std::pow(J, T(-2.0 / 3.0))) +\n           F_inv_trans * (k * J * (J - 1));\n}\n\ntemplate <int dim, typename T>\ntypename IncompressibleNeohookeanMaterial<dim, T>::MatrixDimT\nIncompressibleNeohookeanMaterial<dim, T>::StressDifferential(\n        const MatrixDimT& F, const MatrixDimT& dF) const {\n    throw std::runtime_error{\"not implemented\"};\n}\n\ntemplate <int dim, typename Td>\ntypename IncompressibleNeohookeanMaterial<dim, Td>::MatrixDim2T\nIncompressibleNeohookeanMaterial<dim, Td>::StressDifferential(\n        const MatrixDimT& F) const {\n    const Td mu = Super::mu();\n    const Td k = Super::bulk_modulus();\n\n    using Vec = Eigen::Matrix<Td, dim, 1>;\n    using Vec2 = Eigen::Matrix<Td, dim * dim, 1>;\n    Eigen::JacobiSVD<MatrixDimT> svd{F,\n                                     Eigen::ComputeFullU | Eigen::ComputeFullV};\n    Vec S = svd.singularValues();\n    MatrixDimT U = svd.matrixU(), V = svd.matrixV(), A;\n\n    // construct the matrix A\n    auto sqr = [](Td x) { return x * x; };\n    Td I3 = S(0) * S(1) * S(2), I3_83 = std::pow(I3, Td(8.0 / 3)),\n       I3_53 = std::pow(I3, Td(5.0 / 3)),\n       S2[3] = {sqr(S(0)), sqr(S(1)), sqr(S(2))}, I2 = S2[0] + S2[1] + S2[2];\n    for (int i = 0; i < 3; ++i) {\n        int o0 = i == 0 ? 1 : 0, o1 = i == 2 ? 1 : 2;\n        A(i, i) = S2[o0] * S2[o1] *\n                  (9 * I3_83 * k + mu * (2 * S2[i] + 5 * (S2[o0] + S2[o1]))) /\n                  (9 * I3_83);\n        for (int j = i + 1; j < 3; ++j) {\n            A(i, j) = A(j, i) =\n                    S(3 - i - j) *\n                    (9 * k * (I3_83 * 2 - I3_53) +\n                     mu * 2 * (S2[3 - i - j] - 2 * S2[i] - 2 * S2[j])) /\n                    (9 * I3_53);\n        }\n    }\n\n    Vec2 eigs;\n    Eigen::SelfAdjointEigenSolver<MatrixDimT> eigensolver{A};\n    cf_assert(eigensolver.info() == Eigen::Success);\n    Eigen::Map<Vec>{eigs.data()} = eigensolver.eigenvalues();\n\n    {\n        Td eig6tmp = I3_53 * 3 * k * (I3 - 1) - I2 * mu;\n#define SET(t, i, j) \\\n    eigs[t + 3] = (eig6tmp + 3 * mu * S(i) * S(j)) * S(3 - i - j) / (3 * I3_53)\n        SET(0, 0, 1);\n        SET(1, 1, 2);\n        SET(2, 0, 2);\n        eig6tmp = -eig6tmp;\n        SET(3, 0, 1);\n        SET(4, 1, 2);\n        SET(5, 0, 2);\n#undef SET\n    }\n\n    MatrixDimT D0, D1, D2, T[6];\n    D0.noalias() = U.col(0) * V.col(0).transpose();\n    D1.noalias() = U.col(1) * V.col(1).transpose();\n    D2.noalias() = U.col(2) * V.col(2).transpose();\n    auto compute_Q_first3 = [&](MatrixDimT& Q, int i) {\n        auto& evec = eigensolver.eigenvectors();\n        Td z0 = evec(0, i), z1 = evec(1, i), z2 = evec(2, i);\n        Q = z0 * D0 + z1 * D1 + z2 * D2;\n    };\n    T[0] << 0, -1, 0, 1, 0, 0, 0, 0, 0;\n    T[1] << 0, 0, 0, 0, 0, 1, 0, -1, 0;\n    T[2] << 0, 0, 1, 0, 0, 0, -1, 0, 0;\n    T[3] << 0, 1, 0, 1, 0, 0, 0, 0, 0;\n    T[4] << 0, 0, 0, 0, 0, 1, 0, 1, 0;\n    T[5] << 0, 0, 1, 0, 0, 0, 1, 0, 0;\n\n    MatrixDimT Q;\n    MatrixDim2T H;\n    H.setZero();\n    int nr_pos = 0;\n    for (int i = 0; i < 9; ++i) {\n        if (baseline::g_hessian_proj && eigs[i] < 0) {\n            continue;\n        }\n        ++nr_pos;\n        if (i < 3) {\n            compute_Q_first3(Q, i);\n        } else {\n            Q.noalias() = U * T[i - 3] * V.transpose() * std::sqrt(0.5);\n        }\n        Eigen::Map<Vec2> qf{Q.data()};\n        H.noalias() += qf * qf.transpose() * eigs[i];\n    }\n    cf_assert(nr_pos);\n    return H;\n}\n\ntemplate class materials::CompressibleNeohookeanMaterial<3, double>;\ntemplate class materials::IncompressibleNeohookeanMaterial<3, double>;\n", "meta": {"hexsha": "cfe1a8f09cc549a587ccd26cccaacae0edbc9d30", "size": 8445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fea/baseline/neohookean_material.cpp", "max_stars_repo_name": "jia-kai/SANM", "max_stars_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T09:27:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T15:22:05.000Z", "max_issues_repo_path": "fea/baseline/neohookean_material.cpp", "max_issues_repo_name": "jia-kai/SANM", "max_issues_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-03T05:31:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-05T01:37:42.000Z", "max_forks_repo_path": "fea/baseline/neohookean_material.cpp", "max_forks_repo_name": "jia-kai/SANM", "max_forks_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_forks_repo_licenses": ["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.6454183267, "max_line_length": 80, "alphanum_fraction": 0.52776791, "num_tokens": 3170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5417675877628756}}
{"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);\ntypedef Eigen::Matrix<double, 2, 3> Matrix2x3d;\n\nEigen::Matrix3cd T;\nEigen::Vector3cd aux_states(0, 0, 0);\nEigen::Matrix3d F;\nEigen::Matrix3d V;\nMatrix2x3d J;\nstd::complex<double> dmdT1;\nstd::complex<double> dmdT2;\nstd::complex<double> dmdM0;\n\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 add2FIM()\n{\n    J(0,0) = dmdT1.real();\n    J(1,0) = dmdT1.imag();\n    J(0,1) = dmdT2.real();\n    J(1,1) = dmdT2.imag(); \n    J(0,2) = dmdM0.real();\n    J(1,2) = dmdM0.imag();  \n    F     += J.transpose() * J;\n}\n\nvoid EPG_GRE_efficiency(double *f, double *N, double *FA, double *RF, double *TR, double *TE, double *T1, double *T2)\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    double E1;\n    double E2;\n    double E2_TE;\n    double dEdT1;\n    double dEdT2;\n    double dEdT2_TE;\n    double Tacq = 0.0;\n\n    // fisher information matrix\n    F.setZero();\n\n    // signal vectors\n    Eigen::VectorXcd Fplus(KMAX);\n    Fplus.setZero();\n    Eigen::VectorXcd Fminus(KMAX);\n    Fminus.setZero();\n    Eigen::VectorXcd Z(KMAX);\n    Z.setZero();\n    Eigen::VectorXcd prev_Fplus(KMAX);\n    prev_Fplus.setZero();\n    Eigen::VectorXcd prev_Fminus(KMAX);\n    prev_Fminus.setZero();\n    Eigen::VectorXcd prev_Z(KMAX);\n    prev_Z.setZero();\n\n    // for CRLB calculation\n    Eigen::VectorXcd Fplus_dOdT1(KMAX);\n    Fplus_dOdT1.setZero();\n    Eigen::VectorXcd Fminus_dOdT1(KMAX);\n    Fminus_dOdT1.setZero();   \n    Eigen::VectorXcd Z_dOdT1(KMAX);\n    Z_dOdT1.setZero();\n    Eigen::VectorXcd prev_Fplus_dOdT1(KMAX);\n    prev_Fplus_dOdT1.setZero();\n    Eigen::VectorXcd prev_Fminus_dOdT1(KMAX);\n    prev_Fminus_dOdT1.setZero();\n    Eigen::VectorXcd prev_Z_dOdT1(KMAX);\n    prev_Z_dOdT1.setZero();\n    \n    Eigen::VectorXcd Fplus_dOdT2(KMAX);\n    Fplus_dOdT2.setZero();\n    Eigen::VectorXcd Fminus_dOdT2(KMAX);\n    Fminus_dOdT2.setZero();   \n    Eigen::VectorXcd Z_dOdT2(KMAX);\n    Z_dOdT2.setZero();\n    Eigen::VectorXcd prev_Fplus_dOdT2(KMAX);\n    prev_Fplus_dOdT2.setZero();\n    Eigen::VectorXcd prev_Fminus_dOdT2(KMAX);\n    prev_Fminus_dOdT2.setZero();\n    Eigen::VectorXcd prev_Z_dOdT2(KMAX);\n    prev_Z_dOdT2.setZero();\n    \n    Eigen::VectorXcd Fplus_dOdM0(KMAX);\n    Fplus_dOdM0.setZero();\n    Eigen::VectorXcd Fminus_dOdM0(KMAX);\n    Fminus_dOdM0.setZero();   \n    Eigen::VectorXcd Z_dOdM0(KMAX);\n    Z_dOdM0.setZero();\n    Eigen::VectorXcd prev_Fplus_dOdM0(KMAX);\n    prev_Fplus_dOdM0.setZero();\n    Eigen::VectorXcd prev_Fminus_dOdM0(KMAX);\n    prev_Fminus_dOdM0.setZero();\n    Eigen::VectorXcd prev_Z_dOdM0(KMAX);\n    prev_Z_dOdM0.setZero();       \n\n    /////CRLB SIMULATION\n    Z(0)       = 1.0 + 0.0*i1;\n    Z_dOdM0(0) = 1.0 + 0.0*i1;\n    \n    //simulate the sequence\n    for (int j=0; j<n; j++){\n\n        E1       = exp(-TR[j] / T1[0]);\n        E2       = exp(-TR[j] / T2[0]);\n        E2_TE    = exp(-TE[j] / T2[0]);\n        dEdT1    = TR[j] * E1 / pow(T1[0],2);\n        dEdT2    = TR[j] * E2 / pow(T2[0],2);\n        dEdT2_TE = TE[j] * E2_TE / pow(T2[0],2);\n        Tacq    += TR[j]*1e-3;\n\n        //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) = Fplus(k);\n    \t\taux_states(1) = Fminus(k);\n    \t\taux_states(2) = Z(k);\n    \t\taux_states    = T * aux_states;\n            \n    \t\tprev_Fplus(k)  = aux_states(0);\n    \t\tprev_Fminus(k) = aux_states(1);\n    \t\tprev_Z(k)      = aux_states(2);\n            \n            //T1\n            aux_states(0) = Fplus_dOdT1(k);\n  \t\t    aux_states(1) = Fminus_dOdT1(k);\n   \t\t    aux_states(2) = Z_dOdT1(k);\n   \t\t    aux_states    = T * aux_states;\n            \n   \t\t    prev_Fplus_dOdT1(k)  = aux_states(0);\n   \t\t    prev_Fminus_dOdT1(k) = aux_states(1);\n   \t\t    prev_Z_dOdT1(k)      = aux_states(2);    \n\n            //T2\n            aux_states(0) = Fplus_dOdT2(k);\n  \t\t    aux_states(1) = Fminus_dOdT2(k);\n   \t\t    aux_states(2) = Z_dOdT2(k);\n   \t\t    aux_states    = T * aux_states;\n            \n   \t\t    prev_Fplus_dOdT2(k)  = aux_states(0);\n   \t\t    prev_Fminus_dOdT2(k) = aux_states(1);\n   \t\t    prev_Z_dOdT2(k)      = aux_states(2);\n\n            //M0\n            aux_states(0) = Fplus_dOdM0(k);\n  \t\t    aux_states(1) = Fminus_dOdM0(k);\n   \t\t    aux_states(2) = Z_dOdM0(k);\n   \t\t    aux_states    = T * aux_states;\n            \n   \t\t    prev_Fplus_dOdM0(k)  = aux_states(0);\n   \t\t    prev_Fminus_dOdM0(k) = aux_states(1);\n   \t\t    prev_Z_dOdM0(k)      = aux_states(2);    \n    \t}\n\n\n        //CRLB calculation\n        dmdT1 = E2_TE * prev_Fminus_dOdT1(0); \n        dmdT2 = dEdT2_TE * prev_Fminus(0) + E2_TE * prev_Fminus_dOdT2(0);\n        dmdM0 = E2_TE * prev_Fminus_dOdM0(0);\n        add2FIM();\n\n\t    //apply E\n    \tfor (int k=0; k<(std::min(j+1,KMAX)); k++)\n    \t{\n    \t\tFplus(k)  = prev_Fplus(k) * E2;\n    \t\tFminus(k) = prev_Fminus(k) * E2;\n    \t\tZ(k)      = prev_Z(k) * E1; \n            \n            Fplus_dOdT1(k)  = prev_Fplus_dOdT1(k) * E2;\n            Fminus_dOdT1(k) = prev_Fminus_dOdT1(k) * E2;\n            Z_dOdT1(k)      = prev_Z(k) * dEdT1 + prev_Z_dOdT1(k) * E1;\n\n            Fplus_dOdT2(k)  = prev_Fplus_dOdT2(k) * E2 + prev_Fplus(k) * dEdT2;\n            Fminus_dOdT2(k) = prev_Fminus_dOdT2(k) * E2 + prev_Fminus(k) * dEdT2;\n            Z_dOdT2(k)      = prev_Z_dOdT2(k) * E1;\n\n            Fplus_dOdM0(k)  = prev_Fplus_dOdM0(k) * E2;\n            Fminus_dOdM0(k) = prev_Fminus_dOdM0(k) * E2;\n            Z_dOdM0(k)      = prev_Z_dOdM0(k) * E1;\n       \t}\n    \tZ(0)       += 1.0 - E1;\n        Z_dOdT1(0) -= dEdT1;\n        Z_dOdM0(0) += 1.0 - E1;\n\n    \t//apply S\n    \tfor (int k=(std::min(KMAX-1,j+1)); k>0; k--)\n        {\n            Fplus(k)       = Fplus(k-1); \n            Fplus_dOdT1(k) = Fplus_dOdT1(k-1); \n            Fplus_dOdT2(k) = Fplus_dOdT2(k-1);        \n            Fplus_dOdM0(k) = Fplus_dOdM0(k-1);\n        }\n    \tFplus(0)       = std::conj(Fminus(1));\n        Fplus_dOdT1(0) = std::conj(Fminus_dOdT1(1));\n        Fplus_dOdT2(0) = std::conj(Fminus_dOdT2(1));        \n        Fplus_dOdM0(0) = std::conj(Fminus_dOdM0(1));\n    \tfor (int k=0; k<(std::min(KMAX-1,j)); k++)\n        { \n            Fminus(k)       = Fminus(k+1); \n            Fminus_dOdT1(k) = Fminus_dOdT1(k+1);           \n            Fminus_dOdT2(k) = Fminus_dOdT2(k+1);\n            Fminus_dOdM0(k) = Fminus_dOdM0(k+1);\n\n        }\n    \tFminus(std::min(KMAX-1,j))       = 0.0 + 0.0*i1;\n\t\tFminus_dOdT1(std::min(KMAX-1,j)) = 0.0 + 0.0*i1;\n        Fminus_dOdT2(std::min(KMAX-1,j)) = 0.0 + 0.0*i1;\n\t\tFminus_dOdM0(std::min(KMAX-1,j)) = 0.0 + 0.0*i1;            \n    }\n\n    V = F.inverse();\n\n    double sq_eta_T1 = pow(T1[0],2.0) / (V(0,0) * Tacq); \n    double sq_eta_T2 = pow(T2[0],2.0) / (V(1,1) * Tacq); \n\n    if(sq_eta_T1>1e6 || sq_eta_T2>1e6 || sq_eta_T1<0 || sq_eta_T2<0){\n        f[0] = 1e6;\n    }\n    else{\n        f[0] = 1.0/sq_eta_T1 + 1.0/sq_eta_T2; \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 *TE;\n    double *T1;\n    double *T2;\n\n    double *f;\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    TE = mxGetPr(prhs[4]);\n    T1 = mxGetPr(prhs[5]); \n    T2 = mxGetPr(prhs[6]);\n\n    /* Create pointers to the outputs */\n    plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);\n    \n    // Check this link to see how to return complex arrays:\n    // http://matlab.izmiran.ru/help/techdoc/matlab_external/ch04cre9.html\n    f = mxGetPr(plhs[0]);\n        \n    /* Call the computational routine */\n    EPG_GRE_efficiency(f, N, FA, RF, TR, TE, T1, T2);\n\n\n}\n\n\n\n\n", "meta": {"hexsha": "4fcdb7748d6a73efda37bd49e5fba4f8970d72d4", "size": 8207, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "library/cppEPG_GRE_efficiency.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_efficiency.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_efficiency.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": 28.4965277778, "max_line_length": 117, "alphanum_fraction": 0.546972097, "num_tokens": 3114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5417675858382334}}
{"text": "#ifndef TRIUMF_BNMR_SLR_MOD_STR_EXP_HPP\n#define TRIUMF_BNMR_SLR_MOD_STR_EXP_HPP\n\n#include <boost/math/quadrature/tanh_sinh.hpp>\n#include <cmath>\n#include <triumf/bnmr/slr/common.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// \u03b2-detected nuclear magnetic resonance (\u03b2-NMR)\nnamespace bnmr {\n\n// spin-lattice relaxation (SLR)\nnamespace slr {\n\n/// pulsed modified stretched exponential integral (from 0 to time_p)\n/// https://doi.org/10.1006/jmra.1996.0029\ntemplate <typename T = double>\nT pulsed_mod_str_exp_integral(T time, T time_p, T nuclear_lifetime,\n                              T slr_rate_initial, T slr_rate, T beta) {\n  // do some conversions for consistency with Eqs. (4) to (7).\n  T tau_0 = 1.0 / slr_rate_initial;\n  T tau_d = 1.0 / slr_rate;\n  T tau_c = std::pow(tau_d * std::pow(tau_0, -1.0 / beta), beta / (beta - 1.0));\n\n  // integrand for the numeric integral\n  auto integrand = [=](T t_p) {\n    return std::exp(-(time - t_p) / nuclear_lifetime) *\n           std::exp(-((time - t_p) / tau_0) *\n                    std::pow(1.0 + ((time - t_p) / tau_c), beta - 1.0));\n  };\n  // create the integrator for tanh-sinh quadrature\n  static boost::math::quadrature::tanh_sinh<T> integrator;\n  // evaluate the integral from 0 to time_p\n  T Q = integrator.integrate(integrand, 0.0, time_p);\n  return Q;\n}\n\n/// pulsed modified stretched exponential\n/// https://doi.org/10.1006/jmra.1996.0029\ntemplate <typename T = double>\nT pulsed_mod_str_exp(T time, T nuclear_lifetime, T pulse_length, T asymmetry,\n                     T slr_rate_initial, T slr_rate, T beta) {\n  if (time == 0.0) {\n    return asymmetry;\n  } else if (time > 0.0 and time <= pulse_length) {\n    return asymmetry *\n           pulsed_mod_str_exp_integral<T>(time, time, nuclear_lifetime,\n                                          slr_rate_initial, slr_rate, beta) /\n           normalization<T>(time, nuclear_lifetime);\n  } else if (time > pulse_length) {\n    return (asymmetry *\n            pulsed_mod_str_exp_integral<T>(time, pulse_length, nuclear_lifetime,\n                                           slr_rate_initial, slr_rate, beta) /\n            normalization<T>(pulse_length, nuclear_lifetime)) /\n           std::exp(-(time - pulse_length) / nuclear_lifetime);\n  } else {\n    return 0.0;\n  }\n}\n\n/// pulsed modified stretched exponential (ROOT)\n/// https://doi.org/10.1006/jmra.1996.0029\ntemplate <typename T = double> T pulsed_mod_str_exp(const T *x, const T *par) {\n  return pulsed_mod_str_exp<T>(*x, par[0], par[1], par[2], par[3], par[4],\n                               par[5]);\n}\n\n} // namespace slr\n\n} // namespace bnmr\n\n} // namespace triumf\n\n#endif // TRIUMF_BNMR_SLR_MOD_STR_EXP_HPP", "meta": {"hexsha": "1409dd7a27b92647d68082f76ec2873652104abc", "size": 2693, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/bnmr/slr/mod_str_exp.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/bnmr/slr/mod_str_exp.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/bnmr/slr/mod_str_exp.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": 35.4342105263, "max_line_length": 80, "alphanum_fraction": 0.6435202377, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5417675858382333}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Jose Aparicio\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 <ql/experimental/math/tcopulapolicy.hpp>\n#include <boost/bind.hpp>\n#include <numeric>\n#include <algorithm>\n\nnamespace QuantLib {\n\n    TCopulaPolicy::TCopulaPolicy(\n        const std::vector<std::vector<Real> >& factorWeights, \n        const initTraits& vals)\n    {\n        for(Size iFactor=0; iFactor<vals.tOrders.size(); iFactor++) {\n            // require no T is of order 2 (finite variance)\n            QL_REQUIRE(vals.tOrders[iFactor] > 2, \n                \"Non finite variance T in latent model.\");\n\n            distributions_.push_back(boost::math::students_t_distribution<>(\n                vals.tOrders[iFactor]));\n            // inverses T variaces used in normalization of the random factors\n            // For low values of the T order this number is very close to zero \n            // and it enters the expresions dividing them, which introduces \n            // numerical errors.\n            varianceFactors_.push_back(std::sqrt(\n                (vals.tOrders[iFactor]-2.)/vals.tOrders[iFactor]));\n        }\n\n        for(Size iLVar=0; iLVar<factorWeights.size(); iLVar++) {\n            // This ensures the latent model is 'canonical'\n            QL_REQUIRE(vals.tOrders.size() == factorWeights[iLVar].size()+1, \n                // num factors plus one\n                \"Incompatible number of T functions and number of factors.\"); \n\n            Real factorsNorm = std::inner_product(factorWeights[iLVar].begin(), \n                factorWeights[iLVar].end(), factorWeights[iLVar].begin(), 0.);\n            QL_REQUIRE(factorsNorm < 1., \n                \"Non normal random factor combination.\");\n            Real idiosyncFctr = std::sqrt(1.-factorsNorm);\n\n            // linear comb factors ajusted for the variance renormalization:\n            std::vector<Real> normFactorWeights;\n            for(Size iFactor=0; iFactor<factorWeights[iLVar].size(); iFactor++)\n                normFactorWeights.push_back(factorWeights[iLVar][iFactor] * \n                    varianceFactors_[iFactor]);\n            // idiosincratic term, all Z factors are assumed identical.\n            normFactorWeights.push_back(idiosyncFctr * varianceFactors_.back());\n            latentVarsCumul_.push_back( \n                CumulativeBehrensFisher(vals.tOrders, normFactorWeights));\n            latentVarsInverters_.push_back(\n                InverseCumulativeBehrensFisher(vals.tOrders, \n                    normFactorWeights));\n        }\n    }\n\n    Disposable<std::vector<Real> > \n    TCopulaPolicy::allFactorCumulInverter(\n        const std::vector<Real>& probs) const \n    {\n    #if defined(QL_EXTRA_SAFETY_CHECKS)\n        QL_REQUIRE(probs.size()-latentVarsCumul_.size() \n            == distributions_.size()-1, \n            \"Incompatible sample and latent model sizes\");\n    #endif\n\n        std::vector<Real> result(probs.size());\n        Size indexSystemic = 0;\n        std::transform(probs.begin(), probs.begin() + varianceFactors_.size()-1,\n            result.begin(), \n            bind(&TCopulaPolicy::inverseCumulativeDensity, \n                                this, _1, indexSystemic++));\n        std::transform(probs.begin() + varianceFactors_.size()-1, probs.end(),\n            result.begin()+ varianceFactors_.size()-1,\n            boost::bind(&TCopulaPolicy::inverseCumulativeZ, this, _1));\n        return result;\n    }\n\n}\n", "meta": {"hexsha": "0f5121336568016b80d1b1973873685372f1a904", "size": 4128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/math/tcopulapolicy.cpp", "max_stars_repo_name": "grandtiger/quantlib", "max_stars_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "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": "ql/experimental/math/tcopulapolicy.cpp", "max_issues_repo_name": "grandtiger/quantlib", "max_issues_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T18:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-17T18:49:22.000Z", "max_forks_repo_path": "ql/experimental/math/tcopulapolicy.cpp", "max_forks_repo_name": "grandtiger/quantlib", "max_forks_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "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": 43.0, "max_line_length": 80, "alphanum_fraction": 0.6359011628, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5417675781396637}}
{"text": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <boost/algorithm/string.hpp>\n\nstruct Data {\n  std::string name;\n  int speed;\n  int runningTime;\n  int restingTime;\n\n  int cycleTime() {\n    return runningTime + restingTime;\n  }\n};\n\nsize_t parse_line(const std::string& line);\n\nint main (int argc, char** argv) {\n  std::string line;\n  std::getline(std::cin, line);\n  size_t simulationTime = std::stoi(line);\n  std::getline(std::cin, line);  \n\n  std::vector<Data> dataList;\n\n  while(!std::cin.eof()) {\n    std::vector<std::string> chunks;\n    boost::split(chunks, line, boost::is_any_of(\" \"));    \n    Data d {chunks[0], std::stoi(chunks[3]), std::stoi(chunks[6]), std::stoi(chunks[13])};\n    dataList.push_back(d);\n    std::getline(std::cin, line);\n  }\n\n  int maxDistance = 0;\n  for(Data& d : dataList) {\n    size_t cycles = simulationTime / d.cycleTime();\n    int distance = cycles * d.speed * d.runningTime;\n    if((cycles * d.cycleTime()) < simulationTime) {\n      int rest = simulationTime - (cycles * d.cycleTime());\n      if(d.runningTime < rest) {\n\tdistance += d.speed * d.runningTime;\n      } else {\n\tdistance += d.speed * rest;\n      }\n    }\n    if(distance > maxDistance)\n      maxDistance = distance;\n    std::cout << d.name << \": \" << distance << std::endl;\n  }\n\n  std::cout << maxDistance << std::endl;\n\n}\n", "meta": {"hexsha": "ab13d091ab3d5f65f118a1da934d76fae2578934", "size": 1336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "14/14.cpp", "max_stars_repo_name": "julitopower/AdventOfCode2015", "max_stars_repo_head_hexsha": "42577266d7d38b60bc8f5800c9c5f9a49705a728", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "14/14.cpp", "max_issues_repo_name": "julitopower/AdventOfCode2015", "max_issues_repo_head_hexsha": "42577266d7d38b60bc8f5800c9c5f9a49705a728", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "14/14.cpp", "max_forks_repo_name": "julitopower/AdventOfCode2015", "max_forks_repo_head_hexsha": "42577266d7d38b60bc8f5800c9c5f9a49705a728", "max_forks_repo_licenses": ["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.2909090909, "max_line_length": 90, "alphanum_fraction": 0.619760479, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5417598881742657}}
{"text": "#include \"testsuite.h\"\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main(int argc, char* argv[]) {\n    Array<float,2> image(100, 200);\n    for (int x=0;x<100;x++)\n        for (int y=0;y<200;y++)\n            image(x,y) = 1000*y+x;\n\n    RectDomain<2>  rect_domain(shape(0,0),shape(99,0));\n    Array<float,2> slice = image(rect_domain);\n\n    unsigned k = 0;\n    for (Array<float,2>::iterator i=slice.begin();i!=slice.end();++i)\n        BZTEST(*i==k++);\n\n    slice.reverseSelf(0);\n    for (Array<float,2>::iterator i=slice.begin();i!=slice.end();++i)\n        BZTEST(*i==--k);\n\n    return 0;\n} \n", "meta": {"hexsha": "a962b6d441bc1bb345d1b098a297324ee7bce951", "size": 602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/slice-iterators.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/slice-iterators.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/slice-iterators.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.08, "max_line_length": 69, "alphanum_fraction": 0.5747508306, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5417598835280522}}
{"text": "#pragma once\n\n#include <list>\n#include <vector>\n\n#include <Eigen/Core>\n\n#include \"rcvio/input_buffer.hpp\"\n\nnamespace rcvio\n{\n    struct RansacModel\n    {\n        Eigen::MatrixXd hypotheses;\n        Eigen::MatrixXi inliers;\n        Eigen::MatrixXi two_points;\n        int iterations;\n\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        RansacModel()\n        {\n            iterations = 16;\n            hypotheses.resize(iterations * 3, 3);\n            inliers.resize(iterations, 1);\n            two_points.resize(iterations, 2);\n        }\n    };\n\n    class Ransac\n    {\n    public:\n        POINTER_TYPEDEFS(Ransac);\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        Ransac(const cv::FileStorage &fs_settings);\n\n        void setPointPair(const int inlier_candidates, const int iterations);\n\n        void setRansacModel(const Eigen::MatrixXd &points_1,\n                            const Eigen::MatrixXd &points_2,\n                            const Eigen::Matrix3d &R,\n                            const int iter_num);\n\n        void getRotation(std::list<ImuData *> &imu_data, Eigen::Matrix3d &R);\n\n        void countInliers(const Eigen::MatrixXd &points_1,\n                          const Eigen::MatrixXd &points_2,\n                          const int iter_num);\n\n        int findInliers(const Eigen::MatrixXd &points_1,\n                        const Eigen::MatrixXd &points_2,\n                        std::list<ImuData *> &imu_data,\n                        std::vector<unsigned char> &inlier_flag);\n\n        double sampsonError(const Eigen::Vector3d &pt_1,\n                            const Eigen::Vector3d &pt_2,\n                            const Eigen::Matrix3d &E) const;\n\n        double algebraicError(const Eigen::Vector3d &pt_1,\n                              const Eigen::Vector3d &pt_2,\n                              const Eigen::Matrix3d &E) const;\n\n    private:\n        bool use_sampson_;\n        double inlier_threshold_;\n\n        double small_angle_;\n\n        Eigen::Matrix3d Rci_;\n        Eigen::Matrix3d Ric_;\n\n        RansacModel ransac_model_;\n\n        std::vector<int> inlier_candidate_indices_;\n    };\n}", "meta": {"hexsha": "f33f17e5577d1e35567a6955b4e0abeb70f7112f", "size": 2113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rcvio/ransac.hpp", "max_stars_repo_name": "sufalroy/RC-VIO", "max_stars_repo_head_hexsha": "139a423190e87018e060dfc630cd6790aa2357fc", "max_stars_repo_licenses": ["MIT"], "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/rcvio/ransac.hpp", "max_issues_repo_name": "sufalroy/RC-VIO", "max_issues_repo_head_hexsha": "139a423190e87018e060dfc630cd6790aa2357fc", "max_issues_repo_licenses": ["MIT"], "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/rcvio/ransac.hpp", "max_forks_repo_name": "sufalroy/RC-VIO", "max_forks_repo_head_hexsha": "139a423190e87018e060dfc630cd6790aa2357fc", "max_forks_repo_licenses": ["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.4415584416, "max_line_length": 77, "alphanum_fraction": 0.5570279224, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5417598757991257}}
{"text": "#include <hpx/hpx_init.hpp>\n#include <hpx/hpx.hpp>\n#include <hpx/runtime/threads/topology.hpp>\n//#include <hpx/lcos/local/dataflow.hpp>\n\n#include <boost/format.hpp>\n\n#include <sys/time.h>\n\n#include \"matrix_block.h\"\n\nusing hpx::lcos::future;\nusing hpx::util::unwrapped;\nusing hpx::async;\nusing hpx::lcos::local::dataflow;\nusing hpx::make_ready_future;\n\nusing std::vector;\nusing std::cout;\nusing std::endl;\nusing std::chrono::high_resolution_clock;\nusing time_point = std::chrono::system_clock::time_point;\n\n\nint blocksize;\n\nvoid print(block A) {\n    for(int i = 0; i < A.height; i++) {\n        for(int j = 0; j < A.width; j++) {\n            cout << A[i][j] << \" \";\n        }\n        cout << endl;\n    }\n    cout << endl;\n}\n\nblock rec_mult(block A, block B, block C);\n\nblock serial_mult(block A, block B, block C) {\n    for (int i = 0; i < C.height; i++) {\n        for (int j = 0; j < C.width; j++) {\n            for (int k = 0; k < A.width;k++) {\n                C[i][j] += A[i][k] * B[k][j];\n            }\n        }\n    }\n    return C;\n}\n\nblock add_blocks(block A, block B, block result) {\n    for(int i = 0; i < A.height; i++){\n        for(int j = 0; j < A.width; j++) {\n            result[i][j] = A[i][j] + B[i][j];\n        }\n    }\n    return result;\n}\n\nblock calc_c11(block A, block B, block C) {\n    block tempC = C.block11();//scratch space\n    tempC.add_scratch();\n    future<block> A11B11 = async(rec_mult, A.block11(), B.block11(), C.block11());\n    future<block> A12B21 = async(rec_mult, A.block12(), B.block21(), tempC);\n    return add_blocks(A11B11.get(), A12B21.get(), C.block11());\n}\n\nblock calc_c12(block A, block B, block C) {\n    block tempC = C.block12();\n    tempC.add_scratch();\n    future<block> A11B12 = async(rec_mult, A.block11(), B.block12(), C.block12());\n    future<block> A12B22 = async(rec_mult, A.block12(), B.block22(), tempC);\n    return add_blocks(A11B12.get(), A12B22.get(), C.block12());\n}\n\nblock calc_c21(block A, block B, block C) {\n    block tempC = C.block21();\n    tempC.add_scratch();\n    future<block> A21B11 = async(rec_mult, A.block21(), B.block11(), C.block21());\n    future<block> A22B21 = async(rec_mult, A.block22(), B.block21(), tempC);\n    return add_blocks(A21B11.get(), A22B21.get(), C.block21());\n}\n\nblock calc_c22(block A, block B, block C) {\n    block tempC = C.block22();\n    tempC.add_scratch();\n    future<block> A21B12 = async(rec_mult, A.block21(), B.block12(), C.block22());\n    future<block> A22B22 = async(rec_mult, A.block22(), B.block22(), tempC);\n    return add_blocks(A21B12.get(), A22B22.get(), C.block22());\n}\n\nblock combine_blocks(block b1, block b2, block b3, block b4, block C) {\n    return C;\n}\n\nblock rec_mult(block A, block B, block C) {\n    if(C.width <= blocksize || C.height <= blocksize ) {\n        return serial_mult(A, B, C);\n    } \n    future<block> C11 = async(calc_c11, A, B, C);\n    future<block> C12 = async(calc_c12, A, B, C);\n    future<block> C21 = async(calc_c21, A, B, C);\n    future<block> C22 = async(calc_c22, A, B, C);\n\n    C11.wait();\n    C12.wait();\n    C21.wait();\n    C22.wait();\n    /*\n       auto f_A = make_ready_future(A);\n       auto f_B = make_ready_future(B);\n       auto f_C = make_ready_future(C);\n       future<block> C11 = dataflow(unwrapped(calc_c11), f_A, f_B, f_C);\n       future<block> C12 = dataflow(unwrapped(calc_c12), f_A, f_B, f_C);\n       future<block> C21 = dataflow(unwrapped(calc_c21), f_A, f_B, f_C);\n       future<block> C22 = dataflow(unwrapped(calc_c22), f_A, f_B, f_C);\n\n       future<block> result = dataflow(unwrapped(combine_blocks), C11, C12, C21, C22, f_C);\n       */\n    return C;\n}\n\nint hpx_main(int argc, char **argv) {\n    blocksize = 100;\n    int niter = 1, N = 1000;\n    time_point time1, time2;\n    srand(1);\n    if(argc > 1)\n        N = atoi(argv[1]);\n    if(argc > 2)\n        blocksize = atoi(argv[2]);\n    if(argc > 3)\n        niter = atoi(argv[3]);\n    cout << \"Recursive matrix multiplication\" << endl;\n    cout << \"size \" << N << endl;\n    cout << \"block size \" << blocksize << endl;\n    cout << \"Number of iterations \" << niter << endl;\n\n    block a(N);\n    block b(N);\n    block c(new double[N*N], N);\n\n    time1 = high_resolution_clock::now();\n    rec_mult(a, b, c);\n    time2 = high_resolution_clock::now();\n\n    auto time = std::chrono::duration_cast<std::chrono::microseconds>(time2 - time1).count();\n    cout << \"time \"<< time << \" microseconds\" << endl;\n    return hpx::finalize();\n}\n\nint main(int argc, char ** argv) {\n\n    hpx::init(argc, argv);\n\n    return 0;\n}\n", "meta": {"hexsha": "0c15eed03c5a60fda2da02f7d578933e20d0856e", "size": 4518, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/hpx/bench/hpx-mmult.cpp", "max_stars_repo_name": "tianyi93/hpxMP_mirror", "max_stars_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2018-07-16T14:39:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T11:25:09.000Z", "max_issues_repo_path": "examples/hpx/bench/hpx-mmult.cpp", "max_issues_repo_name": "tianyi93/hpxMP_mirror", "max_issues_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-06-18T14:59:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-16T20:43:57.000Z", "max_forks_repo_path": "examples/hpx/bench/hpx-mmult.cpp", "max_forks_repo_name": "tianyi93/hpxMP_mirror", "max_forks_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T18:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-21T11:17:28.000Z", "avg_line_length": 28.7770700637, "max_line_length": 93, "alphanum_fraction": 0.593625498, "num_tokens": 1392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5417598727164122}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/ml/glm/ridge_regression_with_sgd.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\ndouble to_double(std::string& line) {\n  return boost::lexical_cast<double>(line);\n}\n\nBOOST_AUTO_TEST_CASE( frovedis_test )\n{\n    int argc = 1;\n    char** argv = NULL;\n    use_frovedis use(argc, argv);\n\n    auto data = make_crs_matrix_load<double> (\"./data\");\n    auto label = make_dvector_loadline(\"./label\").map(to_double);\n\n    size_t num_iteration = 100;\n    double alpha = 0.00001;\n    double minibatch_fraction = 1.0;\n    double regParam = 0.001;\n    bool intercept = true;\n\n    auto model = ridge_regression_with_sgd::train(std::move(data),label,\n                                   num_iteration, alpha, minibatch_fraction,\n                                   regParam, intercept);\n\n    auto mat = make_crs_matrix_local_load<double>(\"./data\");    \n    auto out = model.predict(mat);\n    //for(auto i: out) cout << i << \" \"; cout << endl;\n\n    double tol= 0.01;\n    std::vector<double> expected_out = {2.85218, 4.70404, 1.92612, \n                                        3.77824, 1.74095, 5.6296};\n    BOOST_CHECK (calc_rms_err<double> (out, expected_out) < tol);\n}\n\n", "meta": {"hexsha": "d5445b13a43a5ff256fdd31016559adc7b97b5db", "size": 1302, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/ml/test1.3-1/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/ml/test1.3-1/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/ml/test1.3-1/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": 29.5909090909, "max_line_length": 76, "alphanum_fraction": 0.6313364055, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5417377255255158}}
{"text": "#include \"MultilevelSpline.h\"\n#include <Eigen/Dense>\nnamespace DPhy\n{\nSpline::\nSpline(std::vector<double> knots, double end) {\n\tmEnd = end;\n\tmKnots = knots;\n\tmNC_idxs.clear();\n\n\n}\nSpline::\nSpline(double knot_interval, double end) {\n\tmEnd = end;\n\tmKnots.clear();\n\tfor(int i = 0; i < end; i+= knot_interval) {\n\t\tmKnots.push_back(i);\n\t}\n\n\tmNC_idxs.clear();\n\n}\nvoid\nSpline:: \nSetKnots(std::vector<double> knots) {\n\tmKnots = knots;\n}\nvoid\nSpline:: \nSetKnots(double knot_interval) {\n\tmKnots.clear();\n\tfor(int i = 0; i < mEnd; i+= knot_interval) {\n\t\tmKnots.push_back(i);\n\t}\n\n}\ndouble \nSpline::\nB(int idx, double t) {\n\tif(idx == 0) {\n\t\treturn 1.0 / 6 * pow(1 - t, 3);\n\t} else if (idx == 1) {\n\t\treturn 1.0 / 6 * (3 * pow(t, 3) - 6 * pow(t, 2) + 4);\n\t} else if (idx == 2) {\n\t\treturn 1.0 / 6 * (-3 * pow(t, 3) + 3 * pow(t, 2) + 3 * t + 1);\n\t} else {\n\t\treturn 1.0 / 6 * pow(t, 3);\n\t}\n}\nvoid\nSpline::\nApproximate(std::vector<std::pair<Eigen::VectorXd,double>> motion, std::vector<int> idxs, bool circular) {\n\tint length = mKnots.size();\n\tEigen::MatrixXd P(motion.size(), idxs.size());\n\tEigen::MatrixXd C(length+3, idxs.size());\n\n\tif(circular) {\n\t\tEigen::MatrixXd M(length, motion.size());\n\n\t\tM.setZero();\n\n\t\tint count = 0;\n\t\tfor(int i = 0; i < motion.size(); i++) {\n\t\t\tfor(int j = 0; j < idxs.size(); j++) {\n\t\t\t\tP(i, j) = (motion[i].first)[idxs[j]];\n\t\t\t}\n\t\t\tif(count + 1 < mKnots.size() && motion[i].second >= mKnots[count + 1]) {\n\t\t\t\tcount += 1;\n\t\t\t}\n\t\t\tdouble interval = mKnots[ (count + 1) % length ] - mKnots[count];\n\t\t\tif(interval < 0)\n\t\t\t\tinterval += mEnd;\n\t\t\tdouble f = (motion[i].second - mKnots[count]) / interval;\n\t\t\tM((count - 1 + length) % length, i) = B(0, f);\n\t\t\tM(count, i) = B(1, f);\n\t\t\tM((count + 1) % length, i) = B(2, f);\n\t\t\tM((count + 2) % length, i) = B(3, f);\n\t\t}\t\n\t\t\n\t\tEigen::MatrixXd Mt = M.transpose();\n\t\tauto solver = Mt.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n\t\tfor(int i = 0; i < P.cols(); i++) {\n\t\t\tEigen::VectorXd cp = solver.solve(P.col(i));\n\t\t\tC.block(1, i, length, 1) = cp;\n\t\t\tC(0, i) = cp(cp.rows()-1);\n\t\t\tC(length+1, i) = cp(0);\n\t\t\tC(length+2, i) = cp(1);\n\t\t}\n\t} else {\n\t\tEigen::MatrixXd M(length+3, motion.size());\n\n\t\tM.setZero();\n\n\t\tint count = 0;\n\t\tfor(int i = 0; i < motion.size(); i++) {\n\t\t\tfor(int j = 0; j < idxs.size(); j++) {\n\t\t\t\tP(i, j) = (motion[i].first)[idxs[j]];\n\t\t\t}\t\t\t\n\t\t\tif(count + 1 < mKnots.size() && motion[i].second >= mKnots[count + 1]) {\n\t\t\t\tcount += 1;\n\t\t\t}\n\n\t\t\tdouble interval;\n\t\t\tif(count + 1 >= mKnots.size())\n\t\t\t\tinterval = mEnd - mKnots[count];\n\t\t\telse\n\t\t\t\tinterval = mKnots[count + 1] - mKnots[count];\n\t\t\tdouble f = (motion[i].second - mKnots[count]) / interval;\n\n\t\t\tM((count - 1) + 1, i) = B(0, f);\n\t\t\tM(count + 1, i) = B(1, f);\n\t\t\tM((count + 1) + 1, i) = B(2, f);\n\t\t\t\n\t\t\tif((count + 2) + 1 < M.rows())\n\t\t\t\tM((count + 2) + 1, i) = B(3, f);\n\t\t}\t\n\t\t\n\t\tEigen::MatrixXd Mt = M.transpose();\n\t\tauto solver = Mt.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n\t\tfor(int i = 0; i < P.cols(); i++) {\n\t\t\tEigen::VectorXd cp = solver.solve(P.col(i));\n\t\t\tC.block(0, i, length + 3, 1) = cp;\n\t\t}\n\t}\n\n\tfor(int i = 0; i < C.rows(); i++) {\n\t\tfor(int j = 0; j < idxs.size(); j++) {\n\t\t\tmControlPoints[i][idxs[j]] = C(i, j);\n\t\t}\n\t}\n}\nvoid\nSpline::\nApproximate(std::vector<std::pair<Eigen::VectorXd,double>> motion) {\n\tmControlPoints.clear();\n\n\tint dof = motion[0].first.rows();\n\n\tfor(int i = 0; i < mKnots.size()+3; i++) {\n\t\tEigen::VectorXd cp(dof);\n\t\tcp.setZero();\n\t\tmControlPoints.push_back(cp);\n\t}\n\tint count = 0;\n\tstd::vector<int> C_idxs;\n\n\tfor(int i = 0; i < dof; i++) {\n\t\tif(mNC_idxs.size() == 0 || i != mNC_idxs[count]) {\n\t\t\tC_idxs.push_back(i);\n\t\t} else if(count + 1 < mNC_idxs.size()) {\n\t\t\tcount += 1;\n\t\t}\n\t}\n\n\tthis->Approximate(motion, C_idxs, true);\n\tthis->Approximate(motion, mNC_idxs, false);\n\n}\n\nEigen::VectorXd \nSpline::\nGetPosition(double t) {\n\n\tint length = mKnots.size();\n\tint dof = mControlPoints[0].rows();\n\tEigen::VectorXd p(dof);\n\tp.setZero();\n\tint knot = 0;\n\n\tfor(int i = length - 1; i >= 0; i--) {\n\t\tif(t > mKnots[i]) {\n\t\t\tknot = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tint nc_count = 0;\n\tdouble knot_interval_c;\n\tdouble knot_interval_nc;\n\tif(knot + 1 >= mKnots.size()) {\n\t\tknot_interval_c = mKnots[0] + mEnd - mKnots[knot];\n\t\tknot_interval_nc = mEnd - mKnots[knot];\n\t} else {\n\t\tknot_interval_c = mKnots[knot + 1] - mKnots[knot];\n\t\tknot_interval_nc = knot_interval_c;\n\t}\n\tdouble t_c = (t - mKnots[knot]) / knot_interval_c;\n\tdouble t_nc = (t - mKnots[knot]) / knot_interval_nc;\n\n\tbool circular = true;\n\tfor(int i = 0; i < dof; i++) {\n\t\tif(mNC_idxs.size() > nc_count && i == mNC_idxs[nc_count]) {\n\t\t\tcircular = false;\n\t\t\tnc_count += 1;\n\t\t} \n\t\tfor(int j = -1; j < 3; j++) {\n\t\t\tint cp_idx = knot + j + 1; \n\t\t\tif(circular)\n\t\t\t\tp(i) += this->B(j+1, t_c) * mControlPoints[cp_idx](i);\n\t\t\telse\n\t\t\t\tp(i) += this->B(j+1, t_nc) * mControlPoints[cp_idx](i);\n\t\t}\n\t}\n\n\treturn p;\n\n}\nvoid\nSpline::\nSave(std::string path) {\n\n\tstd::ofstream ofs(path);\n\n\tofs << mKnots.size() << std::endl;\n\tfor(auto t: mKnots) {\n\t\tofs << t << std::endl;\n\t}\n\tfor(auto t: mControlPoints) {\n\t\tofs << t.transpose() << std::endl;\n\t}\n\tstd::cout << \"saved spline to \" << path << std::endl;\n\tofs.close();\n}\nMultilevelSpline::\nMultilevelSpline(int level, double end) {\n\tmNumLevels = level;\n\tmEnd = end;\t\n\tfor(int i = 0; i < mNumLevels; i++) {\n\t\tSpline* s = new Spline(1, mEnd);\n\t\tmSplines.push_back(s);\n\t}\n}\nMultilevelSpline::\nMultilevelSpline(int level, double end, std::vector<int> nc_idx) {\n\tmNumLevels = level;\n\tmEnd = end;\n\tint count = 0;\n\tfor(int i = 0; i < mNumLevels; i++) {\n\t\tSpline* s = new Spline(1, mEnd);\n\t\ts->SetNonCircular(nc_idx);\n\t\tmSplines.push_back(s);\n\t}\n}\nMultilevelSpline::\n~MultilevelSpline(){\t\n\twhile(!mSplines.empty()){\n\t\tSpline* s = mSplines.back();\n\t\tmSplines.pop_back();\n\n\t\tdelete s;\n\t}\t\n}\nvoid\nMultilevelSpline::\nSetKnots(int i, std::vector<double> knots) {\n\tmSplines[i]->SetKnots(knots);\n}\nvoid\nMultilevelSpline::\nSetKnots(int i, double knot_interval) {\n\tmSplines[i]->SetKnots(knot_interval);\n}\nvoid \nMultilevelSpline::\nSetControlPoints(int i, std::vector<Eigen::VectorXd> cps) {\n\tmSplines[i]->SetControlPoints(cps);\n}\nstd::vector<Eigen::VectorXd> \nMultilevelSpline::\nGetControlPoints(int i) {\n\treturn mSplines[i]->GetControlPoints();\n}\nvoid\nMultilevelSpline::\nConvertMotionToSpline(std::vector<std::pair<Eigen::VectorXd,double>> motion) {\n\tfor(int i = 0; i < mNumLevels; i++) {\n\t\tif(i == 0)\n\t\t{\n\t\t\tmSplines[i]->Approximate(motion);\n\t\t}\n\t\telse {\n\t\t\tstd::vector<std::pair<Eigen::VectorXd,double>> displacement;\t\n\t\t\tfor(int j = 0; j < motion.size(); j++) {\n\t\t\t\tEigen::VectorXd p = mSplines[i-1]->GetPosition(motion[j].second);\n\t\t\t\tdisplacement.push_back(std::pair<Eigen::VectorXd,double>(motion[j].first - p, motion[j].second));\n\t\t\t}\n\t\t\tmSplines[i]->Approximate(displacement);\n\t\t}\n\t}\n}\nstd::vector<Eigen::VectorXd> \nMultilevelSpline::\nConvertSplineToMotion() {\n\tstd::vector<Eigen::VectorXd> motion;\n\t\n\tint dof = mSplines[0]->GetPosition(0).rows();\n\n\tfor(int i = 0; i < mEnd; i++) {\n\t\tmotion.push_back(Eigen::VectorXd::Zero(dof));\n\t}\n\n\tfor(int i = 0; i < mNumLevels; i++) {\n\t\tfor(int j = 0; j < mEnd; j++) {\n\t\t\tmotion[j] += mSplines[i]->GetPosition(j);\n\t\t}\n\t}\n\n\treturn motion;\n}\n}", "meta": {"hexsha": "f4e2e04499559bfbe7ba3ec471d80ad8ff298962", "size": 7115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sim/MultilevelSpline.cpp", "max_stars_repo_name": "snumrl/CAR", "max_stars_repo_head_hexsha": "af2ef26860bae56c42df71df0de4682d4898f380", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-28T08:47:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T10:56:21.000Z", "max_issues_repo_path": "sim/MultilevelSpline.cpp", "max_issues_repo_name": "snumrl/CAR", "max_issues_repo_head_hexsha": "af2ef26860bae56c42df71df0de4682d4898f380", "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": "sim/MultilevelSpline.cpp", "max_forks_repo_name": "snumrl/CAR", "max_forks_repo_head_hexsha": "af2ef26860bae56c42df71df0de4682d4898f380", "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.8044871795, "max_line_length": 106, "alphanum_fraction": 0.5952213633, "num_tokens": 2559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.541737712469739}}
{"text": "// -------------------------------------------------------------------------------------------------\n//                              Copyright 2016 - NumScale SAS\n//\n//                   Distributed under the Boost Software License, Version 1.0.\n//                        See accompanying file LICENSE.txt or copy at\n//                            http://www.boost.org/LICENSE_1_0.txt\n// -------------------------------------------------------------------------------------------------\n\n#include <simd_bench.hpp>\n#include <boost/simd/function/simd/acot.hpp>\n\nnamespace nsb = ns::bench;\nnamespace bs =  boost::simd;\n\nDEFINE_SCALAR_BENCH(scalar_acot, bs::acot);\n\nDEFINE_BENCH_MAIN()\n{\n  nsb::for_each<scalar_acot, NS_BENCH_IEEE_TYPES>(-10, 10);\n}\n", "meta": {"hexsha": "4e885f751b98b1169cd8aeabe4d4626aae729028", "size": 744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/function/scalar/acot.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": "bench/function/scalar/acot.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "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": "bench/function/scalar/acot.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "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": 35.4285714286, "max_line_length": 100, "alphanum_fraction": 0.4435483871, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5416520763709981}}
{"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#define BOOST_TEST_MODULE sinh_sinh_quadrature_test\r\n\r\n#include <boost/math/concepts/real_concept.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/math/quadrature/sinh_sinh.hpp>\r\n#include <boost/math/special_functions/sinc.hpp>\r\n#include <boost/multiprecision/cpp_bin_float.hpp>\r\n\r\n#if !BOOST_WORKAROUND(BOOST_MSVC, < 1900)\r\n// MSVC-12 has problems if we include 2 different multiprecision types in the same program,\r\n// basically random things stop compiling, even though they work fine in isolation :(\r\n#include <boost/multiprecision/cpp_dec_float.hpp>\r\n#endif\r\n\r\nusing std::expm1;\r\nusing std::exp;\r\nusing std::sin;\r\nusing std::cos;\r\nusing std::atan;\r\nusing std::tan;\r\nusing std::log;\r\nusing std::log1p;\r\nusing std::asinh;\r\nusing std::atanh;\r\nusing std::sqrt;\r\nusing std::isnormal;\r\nusing std::abs;\r\nusing std::sinh;\r\nusing std::tanh;\r\nusing std::cosh;\r\nusing std::pow;\r\nusing std::string;\r\nusing boost::multiprecision::cpp_bin_float_quad;\r\nusing boost::math::quadrature::sinh_sinh;\r\nusing boost::math::constants::pi;\r\nusing boost::math::constants::pi_sqr;\r\nusing boost::math::constants::half_pi;\r\nusing boost::math::constants::two_div_pi;\r\nusing boost::math::constants::half;\r\nusing boost::math::constants::third;\r\nusing boost::math::constants::half;\r\nusing boost::math::constants::third;\r\nusing boost::math::constants::catalan;\r\nusing boost::math::constants::ln_two;\r\nusing boost::math::constants::root_two;\r\nusing boost::math::constants::root_two_pi;\r\nusing boost::math::constants::root_pi;\r\n//\r\n// Code for generating the coefficients:\r\n//\r\ntemplate <class T>\r\nvoid print_levels(const T& v, const char* suffix)\r\n{\r\n   std::cout << \"{\\n\";\r\n   for (unsigned i = 0; i < v.size(); ++i)\r\n   {\r\n      std::cout << \"      { \";\r\n      for (unsigned j = 0; j < v[i].size(); ++j)\r\n      {\r\n         std::cout << v[i][j] << suffix << \", \";\r\n      }\r\n      std::cout << \"},\\n\";\r\n   }\r\n   std::cout << \"   };\\n\";\r\n}\r\n\r\ntemplate <class T>\r\nvoid print_levels(const std::pair<T, T>& p, const char* suffix = \"\")\r\n{\r\n   std::cout << \"   static const std::vector<std::vector<Real> > abscissa = \";\r\n   print_levels(p.first, suffix);\r\n   std::cout << \"   static const std::vector<std::vector<Real> > weights = \";\r\n   print_levels(p.second, suffix);\r\n}\r\n\r\ntemplate <class Real, class TargetType>\r\nstd::pair<std::vector<std::vector<Real>>, std::vector<std::vector<Real>> > generate_constants(unsigned max_rows)\r\n{\r\n   using boost::math::constants::half_pi;\r\n   using boost::math::constants::two_div_pi;\r\n   using boost::math::constants::pi;\r\n   auto g = [](Real t) { return sinh(half_pi<Real>()*sinh(t)); };\r\n   auto w = [](Real t) { return cosh(t)*half_pi<Real>()*cosh(half_pi<Real>()*sinh(t)); };\r\n\r\n   std::vector<std::vector<Real>> abscissa, weights;\r\n\r\n   std::vector<Real> temp;\r\n\r\n   Real t_max = log(2 * two_div_pi<Real>()*log(2 * two_div_pi<Real>()*sqrt(boost::math::tools::max_value<TargetType>())));\r\n\r\n   std::cout << \"m_t_max = \" << t_max << \";\\n\";\r\n\r\n   Real h = 1;\r\n   for (Real t = 1; t < t_max; t += h)\r\n   {\r\n      temp.push_back(g(t));\r\n   }\r\n   abscissa.push_back(temp);\r\n   temp.clear();\r\n\r\n   for (Real t = 1; t < t_max; t += h)\r\n   {\r\n      temp.push_back(w(t * h));\r\n   }\r\n   weights.push_back(temp);\r\n   temp.clear();\r\n\r\n   for (unsigned row = 1; row < max_rows; ++row)\r\n   {\r\n      h /= 2;\r\n      for (Real t = h; t < t_max; t += 2 * h)\r\n         temp.push_back(g(t));\r\n      abscissa.push_back(temp);\r\n      temp.clear();\r\n   }\r\n   h = 1;\r\n   for (unsigned row = 1; row < max_rows; ++row)\r\n   {\r\n      h /= 2;\r\n      for (Real t = h; t < t_max; t += 2 * h)\r\n         temp.push_back(w(t));\r\n      weights.push_back(temp);\r\n      temp.clear();\r\n   }\r\n\r\n   return std::make_pair(abscissa, weights);\r\n}\r\n\r\ntemplate<class Real>\r\nvoid test_nr_examples()\r\n{\r\n    std::cout << \"Testing type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\r\n    Real integration_limit = sqrt(boost::math::tools::epsilon<Real>());\r\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\r\n    std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\r\n    Real Q;\r\n    Real Q_expected;\r\n    Real L1;\r\n    Real error;\r\n    sinh_sinh<Real> integrator(10);\r\n\r\n    auto f0 = [](Real)->Real { return (Real) 0; };\r\n    Q = integrator.integrate(f0, integration_limit, &error, &L1);\r\n    Q_expected = 0;\r\n    BOOST_CHECK_SMALL(Q, tol);\r\n    BOOST_CHECK_SMALL(L1, tol);\r\n\r\n    // In spite of the poles at \\pm i, we still get a doubling of the correct digits at each level of refinement.\r\n    auto f1 = [](const Real& t) { return 1/(1+t*t); };\r\n    Q = integrator.integrate(f1, integration_limit, &error, &L1);\r\n    Q_expected = pi<Real>();\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\r\n#if defined(BOOST_MSVC) && (BOOST_MSVC < 1900)\r\n    auto f2 = [](const Real& x) { return fabs(x) > boost::math::tools::log_max_value<Real>() ? 0 : exp(-x*x); };\r\n#else\r\n    auto f2 = [](const Real& x) { return exp(-x*x); };\r\n#endif\r\n    Q = integrator.integrate(f2, integration_limit, &error, &L1);\r\n    Q_expected = root_pi<Real>();\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\r\n\r\n    auto f5 = [](const Real& t) { return 1/cosh(t);};\r\n    Q = integrator.integrate(f5, integration_limit, &error, &L1);\r\n    Q_expected = pi<Real>();\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\r\n\r\n    // This oscillatory integral has rapid convergence because the oscillations get swamped by the exponential growth of the denominator,\r\n    // none the less the error is slightly higher than for the other cases:\r\n    tol *= 10;\r\n    auto f8 = [](const Real& t) { return cos(t)/cosh(t);};\r\n    Q = integrator.integrate(f8, integration_limit, &error, &L1);\r\n    Q_expected = pi<Real>()/cosh(half_pi<Real>());\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    // Try again with progressively fewer arguments:\r\n    Q = integrator.integrate(f8, integration_limit);\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    Q = integrator.integrate(f8);\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n}\r\n\r\n// Test formulas for in the CRC Handbook of Mathematical functions, 32nd edition.\r\ntemplate<class Real>\r\nvoid test_crc()\r\n{\r\n    std::cout << \"Testing CRC formulas on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\r\n    Real integration_limit = sqrt(boost::math::tools::epsilon<Real>());\r\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\r\n    std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\r\n    Real Q;\r\n    Real Q_expected;\r\n    Real L1;\r\n    Real error;\r\n    sinh_sinh<Real> integrator(10);\r\n\r\n    // CRC Definite integral 698:\r\n    auto f0 = [](Real x)->Real {\r\n      using std::sinh;\r\n      if(x == 0) {\r\n        return (Real) 1;\r\n      }\r\n      return x/sinh(x);\r\n    };\r\n    Q = integrator.integrate(f0, integration_limit, &error, &L1);\r\n    Q_expected = pi_sqr<Real>()/2;\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\r\n\r\n\r\n    // CRC Definite integral 695:\r\n    auto f1 = [](Real x)->Real {\r\n      using std::sin; using std::sinh;\r\n      if(x == 0) {\r\n        return (Real) 1;\r\n      }\r\n      return (Real) sin(x)/sinh(x);\r\n    };\r\n    Q = integrator.integrate(f1, integration_limit, &error, &L1);\r\n    Q_expected = pi<Real>()*tanh(half_pi<Real>());\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(sinh_sinh_quadrature_test)\r\n{\r\n    //\r\n    // Uncomment the following to print out the coefficients:\r\n    //\r\n    /*\r\n    std::cout << std::scientific << std::setprecision(8);\r\n    print_levels(generate_constants<cpp_bin_float_100, float>(8), \"f\");\r\n    std::cout << std::setprecision(18);\r\n    print_levels(generate_constants<cpp_bin_float_100, double>(8), \"\");\r\n    std::cout << std::setprecision(35);\r\n    print_levels(generate_constants<cpp_bin_float_100, cpp_bin_float_quad>(8), \"L\");\r\n    */\r\n    test_nr_examples<float>();\r\n    test_nr_examples<double>();\r\n    test_nr_examples<long double>();\r\n    test_nr_examples<cpp_bin_float_quad>();\r\n    test_nr_examples<boost::math::concepts::real_concept>();\r\n#if !BOOST_WORKAROUND(BOOST_MSVC, < 1900)\r\n    test_nr_examples<boost::multiprecision::cpp_dec_float_50>();\r\n#endif\r\n\r\n    test_crc<float>();\r\n    test_crc<double>();\r\n    test_crc<long double>();\r\n    test_crc<cpp_bin_float_quad>();\r\n    test_crc<boost::math::concepts::real_concept>();\r\n#if !BOOST_WORKAROUND(BOOST_MSVC, < 1900)\r\n    test_crc<boost::multiprecision::cpp_dec_float_50>();\r\n#endif\r\n}\r\n", "meta": {"hexsha": "611fb82a9184d667dd0e593a2935ce3d9ad0cf20", "size": 8933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ReactAndroid/third-party-ndk/boost/boost_1_66_0/libs/math/test/sinh_sinh_quadrature_test.cpp", "max_stars_repo_name": "yinhangfeng/react-native", "max_stars_repo_head_hexsha": "35e88f14195aa7a75ace8881956a0eb4bdadea62", "max_stars_repo_licenses": ["CC-BY-4.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": "ReactAndroid/third-party-ndk/boost/boost_1_66_0/libs/math/test/sinh_sinh_quadrature_test.cpp", "max_issues_repo_name": "yinhangfeng/react-native", "max_issues_repo_head_hexsha": "35e88f14195aa7a75ace8881956a0eb4bdadea62", "max_issues_repo_licenses": ["CC-BY-4.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": "ReactAndroid/third-party-ndk/boost/boost_1_66_0/libs/math/test/sinh_sinh_quadrature_test.cpp", "max_forks_repo_name": "yinhangfeng/react-native", "max_forks_repo_head_hexsha": "35e88f14195aa7a75ace8881956a0eb4bdadea62", "max_forks_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T11:06:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-08T11:06:22.000Z", "avg_line_length": 33.8371212121, "max_line_length": 138, "alphanum_fraction": 0.6387551774, "num_tokens": 2431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146847, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5416520700958376}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Filename    : algorithms.cpp                                                                        *\n * Project     : Planewalker - Schnorr-Euchner sphere decoder simulation for space-time lattice codes  *\n * Authors     : Pasi Pyrr\u00f6, Oliver Gnilke                                                             *\n * Version     : 1.0                                                                                   *\n * Copyright   : Aalto University ~ School of Science ~ Department of Mathematics and Systems Analysis *\n * Date        : 9.1.2017                                                                              *\n * Language    : C++ (2011 or newer standard)                                                          *\n * Description : All custom mathematical algorithms not found in Armadillo or STL are collected here   *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#define ARMA_NO_DEBUG /* disable Armadillo bound checks for addiotional speed */\n#define FPLLL_WITH_ZDOUBLE\n#define FPLLL_WITH_LONG_DOUBLE\n\n#include <iostream>\n#include <armadillo> /* linear algebra library */\n#include <algorithm>\n#include <complex>\n#include <vector>\n#include <string>\n#include <set>\n#include <random>\n#include <omp.h>\n#include <tuple>\n\n/* library for LLL reduction (optional) */\n#ifdef USE_LLL\n#include <fplll.h>\n#endif\n/* required packages to install:\n *   libmpfr-dev\n *   libgmp-dev\n */\n\n#include \"algorithms.hpp\"\n#include \"misc.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\n/* Signum function for schorr-euchnerr sphere decoder (sesd) \n * ---------------------------------------------------------\n * Note that sesd_sign(0) = -1\n */\nint sesd_sign(double x) {\n    return (x <= 0) ? -1 : 1;\n}\n\n\n/* compute greatest common divisor of a and b\n * credits go to: https://codereview.stackexchange.com/a/66735\n */\nint gcd(int a, int b) {\n    return b == 0 ? a : gcd(b, a % b);\n}\n\n/* Rounds x to nearest integer in S\n * --------------------------------\n * E.g. let S = 4-PAM and x = 1.8 then \n * nearest_symbol(1.8) = 3\n * cf. round(1.8) = 2\n */\ndouble nearest_symbol(double x, const vector<int> &S){\n    double min = 10e6;\n    double d = 0.0;\n    double nearest = 0.0;\n\n    for (const int symbol : S) {\n        d = fabs(x - symbol);\n        if (d < min) {\n            nearest = symbol;\n            min = d;\n        }\n    }\n    return nearest;\n}\n\ndouble nearest_symbol_floor(double x, const vector<int> &S){\n\n    // for (const int symbol : S) {\n    //     if (symbol < x) {\n    //         return symbol;\n    //     }\n    // }\n    for (int i = S.size()-1; i >= 0; i--) {\n        if (S[i] <= x) {\n            return S[i];\n        }\n    }\n    // return S[S.size()-1];\n    return S[0];\n}\n\ndouble nearest_symbol_ceil(double x, const vector<int> &S){\n\n    for (auto i = 0u; i < S.size()-1; i++) {\n        if (S[i] >= x) {\n            return S[i];\n        }\n    }\n    return S[S.size()-1];\n}\n\n/* A simple heuristic function based on the idea that the volume of the hypersphere divided by the volume of the fundamental region of the lattice \n * should roughly equal to the number of lattice points inside the hypersphere\n * i.e. this function estimates the squared radius required for the hypersphere in order to have 2^s codewords (lattice points) inside it\n * (for q-PAM we need to multiply the generator matrix by 2 to get the correct volume for the fundamental region)\n */\ndouble estimate_squared_radius(const mat &G, int s){\n    int n = params[\"no_of_matrices\"];\n    double pi = 3.1415926535897;\n    // cout << \"lattice constant: \" << to_string(sqrt(det(4*G.t()*G))) << endl;\n    // cout << \"volume of the sphere: \" << to_string(pow(pi, n/2.0)*pow(dparams[\"spherical_shaping_max_power\"], n/2)/tgamma(n/2.0 + 1.0)) << endl;\n\n    /* The basic idea: 2^s = vol(Sphere(R))/vol(Lambda) \n     * --> Solve for R when s and Lambda (G) are given\n     */\n\n    /* This algorithm uses this equation for the volume of the n-ball: \n     * https://en.wikipedia.org/wiki/Volume_of_an_n-ball\n     */\n    return pow(pow(2.0, s)*tgamma(n/2.0 + 1.0)*sqrt(det(4*G.t()*G))*pow(pi, n/-2.0), 2.0/n);\n}\n\n/* Generates a new symbolset where elements are between given lower and upper bounds */\nvector<int> slice_symbset(const vector<int> &S, double lb, double ub){\n    vector<int> retval;\n    for (const int q : S){\n        if (lb <= (double)q && (double)q <= ub) {\n            retval.push_back(q);\n        }\n    }\n    return retval;\n}\n\n/* Takes the squared Frobenius norm from a complex matrix A */\ndouble frob_norm_squared(const cx_mat &A){\n    double sum = 0;\n    for (auto i = 0u; i < A.n_rows; i++)\n        for (auto j = 0u; j < A.n_cols; j++)\n            sum += norm(A(i,j)); \n    return sum;\n}\n\n/* Makes sure the upper triangular matrix R has only positive diagonal elements */\nvoid process_qr(mat &Q, mat &R){\n    for (auto i = 0u; i < R.n_cols; i++){\n        if (R(i,i) < 0.0){\n            // R.col(i) *= -1;\n            // Q.row(i) *= -1;\n            R.row(i) *= -1;\n            Q.col(i) *= -1;\n        }\n    }\n}\n\n/* Create the lattice generator matrix G out of basis matrices B_i\n * i.e. G = vec(B_i), i = 1,...,k\n */\ncx_mat create_generator_matrix(const vector<cx_mat> &bases){\n    int m = params[\"no_of_transmit_antennas\"];\n    int t = params[\"time_slots\"];\n    int k = params[\"no_of_matrices\"];\n    cx_mat G(k, m*t);\n    for(int i = 0; i < k; i++){\n        G.row(i) = vectorise(bases[i], 1);\n    }\n    return G.st();\n}\n\n\n/***** DEPRECATED *****\n * Use \n * G_real = to_real_matrix(create_generator_matrix(bases));\n * instead \n **********************/\n\n/* Create the real valued lattice generator matrix G out of basis matrices */\n// mat create_real_generator_matrix(const vector<cx_mat> &bases){\n//     int m = params[\"no_of_transmit_antennas\"];\n//     int t = params[\"time_slots\"];\n//     int k = params[\"no_of_matrices\"];\n//     mat G(2*m*t,k);\n//     for(int i = 0; i < k; i++){    \n//         G.col(i) = to_real_vector(bases[i]);\n//     }\n//     return G;\n// }\n\n\n/* Inverse of the create_generator_matrix() function \n * Useful for generating basis matrix files in conjunction with\n * output_complex_matrix()\n * See main.cpp for an example of this use case\n */\nvector<cx_mat> generator_to_bases(const cx_mat &G){\n    int m = params[\"no_of_transmit_antennas\"];\n    int t = params[\"time_slots\"];\n    int idx = 0;\n\n    vector<cx_mat> bases;\n    cx_mat X(m, t);\n    cx_vec col(m*t);\n\n    for (auto i = 0u; i < G.n_cols; i++){\n        X.zeros();\n        col = G.col(i);\n        for (int j = 0; j < m; j++){\n            for (int s = 0; s < t; s++){\n                X(j,s) = col[idx];\n                idx++;\n            }\n        }\n        idx = 0;\n        bases.push_back(X);\n    }\n    return bases;\n}\n\n/* Vectorizes a complex matrix A to real vector (each row is concatenated) */\nvec to_real_vector(const cx_mat &A, bool row_wise){\n    vec a(2*A.n_elem); \n    // as the imaginary parts are now independent real elements in the vector,\n    // we need to double the number of elements in the returned vector\n    int index = 0;\n    if (row_wise){\n        for (auto i = 0u; i < A.n_rows; i++){\n            for (auto j = 0u; j < A.n_cols; j++){\n                auto z = A(i,j);\n                a[index++] = z.real();\n                a[index++] = z.imag();\n            }\n        }\n    } else { /* concatenate columns instead */\n        for (auto i = 0u; i < A.n_cols; i++){\n            for (auto j = 0u; j < A.n_rows; j++){\n                auto z = A(j,i);\n                a[index++] = z.real();\n                a[index++] = z.imag();\n            }\n        }\n    }\n    return a;\n}\n\n/* Converts a complex matrix A to its real representation */\nmat to_real_matrix(const cx_mat &A){\n    mat B(2*A.n_rows, A.n_cols);\n    for(auto i = 0u; i < A.n_cols; i++){   \n        B.col(i) = to_real_vector(A.col(i));\n    }\n    return B;\n}\n\n/* Converts a real matrix constructed out of a complex matrix back to complex */\ncx_mat to_complex_matrix(const mat &A){\n    if (A.n_rows % 2 != 0){\n        log_msg(\"to_complex_matrix: the input matrix needs to have an even number of rows!\", \"Error\");\n        exit(1);\n    }\n\n    cx_mat B(A.n_rows/2, A.n_cols);\n    // int index = 0;\n    for (auto j = 0u; j < A.n_cols; j++){\n        for (auto i = 0u; i < B.n_rows; i++){\n            B(i,j) = complex<double>(A(2*i,j), A(2*i+1,j));\n        }\n        // index = 0;\n    }\n    return B;\n}\n\n/* generates a random n x m 'full' complex matrix from normal distribution */\ncx_mat create_random_matrix(int n, int m, double mean, double variance){\n    normal_distribution<double> distr(mean, sqrt(variance));\n    cx_mat A(n,m);\n    return A.imbue([&]() { /* Armadillo magic with lambda function */\n        return complex<double>(distr(mersenne_twister), distr(mersenne_twister));\n    });\n}\n\n/* generates a random n x n diagonal complex matrix from normal distribution \n * Used for generating the SISO channel matrix\n */\ncx_mat create_random_diag_matrix(int n, double mean, double variance){\n    normal_distribution<double> distr(mean, sqrt(variance));\n    cx_vec diag(n);\n    cx_mat A(n,n);\n\n    A.zeros();\n    diag.imbue([&]() { /* Armadillo magic with lambda function */\n        return complex<double>(distr(mersenne_twister), 0.0);\n    });\n    A.diag() = diag;\n    return A;\n}\n\n/* Creates q-PAM symbol set (integer vector) \n * q is usually some power of two, i.e. q = 2, 4, 8, 16...\n * Example: 4-PAM = {-3, -1, 1, 3}\n */\nvector<int> create_symbolset(int q){\n    vector<int> symbset(q);\n    for (int u = 0; u < q; u++) {\n        symbset[u] = 2*u - q + 1;\n    }\n    return symbset; \n}\n\n/* Calculates all possible combinations of elements for code vector _a_\n   given the set of feasible symbols (element values)\n   Used for generating the whole codebook, rarely needed though */\nvoid combinations(parallel_set< vector<int> > &comblist, const vector<int> &symbset, vector<int> comb, int dim){\n    comblist.par_insert(comb);\n    if (dim >= 0){\n        #pragma omp parallel \n        {\n            vector<int> new_comb = comb;\n            #pragma omp for\n            for (size_t i = 0; i < symbset.size(); i++){\n                new_comb[dim] = symbset[i];\n                combinations(comblist, symbset, new_comb, dim-1);\n            }\n        }\n    }\n}\n\n/* Helper function for above combinations algorithm */\nset< vector<int> > comb_wrapper(const vector<int> &symbset, int vector_len){\n    parallel_set< vector<int> > comblist;\n    vector<int> init(vector_len);\n    for (int i = 0; i < vector_len; i++)\n        init[i] = symbset[0];\n    combinations(comblist, symbset, init, vector_len-1);\n    return comblist;\n}\n\n/* Creates a random codeword from basis matrices B_i and symbolset x-PAM */\npair<vector<int>, cx_mat> create_random_codeword(const vector<cx_mat> &bases, const vector<int> &symbolset){\n    int m = params[\"no_of_transmit_antennas\"];\n    int t = params[\"time_slots\"];\n    int k = params[\"no_of_matrices\"];\n    int q = params[\"x-PAM\"];\n    int random_index = 0;\n\n    cx_mat X(m, t);\n    vector<int> coeffs(k);\n    X.zeros();\n\n    uniform_int_distribution<int> dist(0, q-1);\n\n    for (int i = 0; i < k; i++) {\n        random_index = dist(mersenne_twister);\n        coeffs[i] = symbolset[random_index];\n        X = X + symbolset[random_index]*bases[i];\n    }\n\n    return make_pair(coeffs, X);   \n}\n\n/* Attempts to take account the probability bias when picking vector coefficients uniform randomly \n   from hyperplane intervals within a hypersphere */\n// vector<int> create_unbiased_subset(const mat &R, const vector<int> &subset, vec xt,\n//                                    vec ener, vec curr, double radius, int i){\n//     if (i <= 0) return subset; /* can't perform lookahead for the lowest dimension */\n\n//     vector<int> unbiased_subset; //, delta_vec;\n//     unbiased_subset.reserve(4*subset.size());\n\n//     double xiener = 0.0;\n//     int ub = 0, lb = 0, delta = 0; //, delta_sum = 0, bias_correction_amount = 0;\n//     int k = params[\"no_of_matrices\"];\n\n//     // cout << i << endl;\n//     // cout << vec2str(xt, xt.size()) << endl;\n//     // cout << vec2str(ener, ener.size()) << endl;\n//     // cout << vec2str(curr, curr.size()) << endl << endl;\n\n//     for (const int elem : subset) {\n//         xt[i] = elem;\n//         xiener = pow(R(i,i)*xt[i] + curr[i], 2);\n\n//         for (int j = i; j < k; j++)\n//             curr[i-1] += xt[j]*R(i-1,j);\n//         ener[i-1] = ener[i] + xiener;\n\n//         lb = nearest_symbol_ceil(-(sqrt(radius - ener[i-1]) + curr[i-1])/R(i-1,i-1), subset);\n//         ub = nearest_symbol_floor((sqrt(radius - ener[i-1]) - curr[i-1])/R(i-1,i-1), subset);\n//         delta = (ub - lb)/2 + 1;\n\n//         // cout << lb << \", \" << ub << \", \" << delta << endl;\n\n//         for (int d = 0; d < delta; d++)\n//             unbiased_subset.push_back(elem);\n//         // delta_vec.push_back(delta);\n//         // delta_sum += delta;\n//     }\n//     // cout << vec2str(xt, xt.size()) << endl;\n//     // cout << vec2str(ener, ener.size()) << endl;\n//     // cout << vec2str(curr, curr.size()) << endl << endl;\n//     // cout << endl;\n\n//     // for (auto j = 0u; j < subset.size(); j++){\n//     //     bias_correction_amount = delta_sum/gcd(delta_sum, delta_vec[j]);\n//     //     for (int s = 0; s < bias_correction_amount; s++)\n//     //         unbiased_subset.push_back(subset[j]);\n//     // }\n//     // cout << vec2str(unbiased_subset, unbiased_subset.size()) << endl << endl;\n//     return unbiased_subset;\n// }\n\n\n/* Attempts to pick q-PAM coefficients which correspond to large subhyperspheres more often \n   This should eliminate some the bias present (picking border points too often) in naive uniform random picking */\nint unbiased_random_select(const mat &R, const vector<int> &subset, vec xt,\n                                   vec ener, vec curr, double radius, int i){\n    if (i <= 0) return 0; /* can't perform lookahead for the lowest dimension */\n\n    vector<int> unbiased_subset, feasible_coeffs;\n    vector<double> radiuses;\n    vector<pair<double, double>> intervals;\n    unbiased_subset.reserve(4*subset.size());\n    radiuses.reserve(subset.size());\n    intervals.reserve(subset.size());\n    feasible_coeffs.reserve(subset.size());\n\n    double xiener = 0.0, radius_sum = 0.0, r = 0.0, numer = 0.0, ub = 0, lb = 0;\n    int k = params[\"no_of_matrices\"];\n\n    /* calculate subsphere radiuses for each coefficient */\n    for (auto j = 0u; j < subset.size(); j++) {\n        xt[i] = subset[j];\n        xiener = pow(R(i,i)*xt[i] + curr[i], 2);\n        r = radius - xiener - ener[i];\n        if (r > 0){ /* We don't want negative radiuses, do we? */\n            r = pow(r, k-1);\n            radiuses.push_back(r);\n            radius_sum += r;\n            feasible_coeffs.push_back(subset[j]);\n        }\n    }\n\n    /* Calculate intervals from [0,1] for each coefficient */\n    for (auto j = 0u; j < radiuses.size(); j++) {\n        lb = numer/radius_sum;\n        ub = (numer+radiuses[j])/radius_sum;\n        intervals.push_back(make_pair(lb, ub));\n        numer += radiuses[j];\n    }\n\n    // intervals.back().second = 1.0;\n\n    // cout << vec2str(radiuses, radiuses.size()) << endl;\n    // cout << vec2str(feasible_coeffs, feasible_coeffs.size()) << endl;\n    // cout << vec2str(intervals, intervals.size()) << endl << endl;\n    // cout << endl;\n\n    // uniform_real_distribution<double> dist(0.0, 1.0);\n    double X = uniform_real_dist(mersenne_twister);\n    // cout << X << endl << endl;\n\n    /* Select the coefficient from distribution created earlier (weights large radiuses) */\n    for (auto j = 0u; j < feasible_coeffs.size(); j++) {\n        // cout << \"[\" << intervals[j].first << \", \" << intervals[j].second << \"]\" << endl;\n        if (intervals[j].first <= X && X <= intervals[j].second)\n            return feasible_coeffs[j];\n    }\n    // cout << \"------\" << endl;\n    \n    return 0;\n}\n\n/* Creates a random codeword from basis matrices B_i and symbolset x-PAM within given radius (spherical shaping) */\npair<vector<int>, cx_mat> create_random_spherical_codeword(const vector<cx_mat> &bases, const mat &R, const vector<int> &S, double radius){\n    int m = params[\"no_of_transmit_antennas\"];\n    int t = params[\"time_slots\"];\n    int k = params[\"no_of_matrices\"];\n\n    cx_mat X(m, t);\n    vector<int> coeffs(k), subset;\n    X.zeros();\n\n    vec xt(k), curr(k), ener(k);\n    xt.zeros(); curr.zeros(); ener.zeros();\n    int i = k-1;\n    double xiener = 0.0;\n    double lb = 0.0; // lower bound\n    double ub = 0.0; // upper bound\n\n    // radius = sqrt(radius);\n\n    /* Randomly pick each component of the codeword and check if it's still within the energy bound in each dimension */\n    while (i >= 0){\n        lb = -(sqrt(radius - ener[i]) + curr[i])/R(i,i);\n        ub = (sqrt(radius - ener[i]) - curr[i])/R(i,i);\n        // uniform_real_distribution<double> xirange(lb, ub);\n        // xt[i] = nearest_symbol(xirange(mersenne_twister), S); // probability bias fix this\n        subset = slice_symbset(S, lb, ub);\n        // if (i >= k-10 /*max(k-13, 3)*/ && !subset.empty())\n        //     subset = create_unbiased_subset(R, subset, xt, ener, curr, radius, i);\n\n        if (subset.empty()) { /* No lattice points are within energy bounds in this dimension */\n            i = k-1;\n            xt.zeros(); curr.zeros(); ener.zeros();\n            continue;\n        }\n        \n        // if (i > 0)\n        //     xt[i] = unbiased_random_select(R, subset, xt, ener, curr, radius, i);\n        // else\n        xt[i] = pick_uniform(subset);\n\n        if (xt[i] == 0) {\n            // cout << \"something went wrong\" << endl;\n            i = k-1;\n            xt.zeros(); curr.zeros(); ener.zeros();\n            continue;\n        }\n\n        xiener = pow(R(i,i)*xt[i] + curr[i], 2);\n\n        // if (xiener + ener[i] < radius + 1e-6) {  \n        if (i > 0) {                     \n            for (int j = i; j < k; j++)\n                curr[i-1] += xt[j]*R(i-1,j);\n            ener[i-1] = ener[i] + xiener;      \n        }  \n        i--;\n        // } else { /* we're outside the energy bound, start over */\n        //     log_msg(\"test!\", \"Error\");\n        //     i = k-1;\n        //     xt.zeros(); curr.zeros(); ener.zeros();\n        // }\n    }\n    coeffs = conv_to<vector<int>>::from(xt);\n    for (int i = 0; i < k; i++) {\n        X = X + coeffs[i]*bases[i];\n    }\n    return make_pair(coeffs, X);\n}\n\n/* Creates a codebook from basis matrices B_i and symbolset x-PAM within given radius (spherical shaping) */\n// vector<pair<vector<int>, cx_mat>> create_spherical_codebook(const vector<cx_mat> &bases, const mat &R, const vector<int> &S, double radius){\nvector<pair<vector<int>, cx_mat>> create_spherical_codebook(const vector<cx_mat> &bases, const mat &R, const vector<int> &S, \n                                                            double radius, vec xt, int dim, double dist) {\n    int m = params[\"no_of_transmit_antennas\"];\n    int t = params[\"time_slots\"];\n    int k = params[\"no_of_matrices\"];\n\n    cx_mat X(m, t, fill::zeros);\n    vector<int> coeffs(k); //, subset;\n    vector<pair<vector<int>,cx_mat>> codebook, part;\n\n    // vec xt(k), curr(k), ener(k), indices(k);\n    // xt.zeros(); curr.zeros(); ener.zeros(); indices.zeros();\n    // int i = k-1;\n    int i = dim-1;\n    double xidist = 0;\n    // double xiener = 0.0;\n    // double lb = 0.0; // lower bound\n    // double ub = 0.0; // upper bound\n    // bool nextlevel = true;\n\n    // while (true) {\n    //  if (nextlevel) {\n       //      lb = -(sqrt(radius - ener[i]) + curr[i])/R(i,i);\n       //      ub = (sqrt(radius - ener[i]) - curr[i])/R(i,i);\n       //      subset = slice_symbset(S, lb, ub);\n       //      if (subset.empty()) { /* No lattice points are within energy bounds in this dimension */\n       //       cout << \"empty interval!\" << endl;\n       //       if (i == k - 1) break;\n       //       else {\n       //           indices[i] = 0;\n       //           // indices[i+1]++;\n          //           i++;\n          //           continue;\n          //       }\n       //      }\n       //      nextlevel = false;\n       //  }\n    //      xt[i] = subset[indices[i]];\n\n    //     xiener = pow(R(i,i)*xt[i] + curr[i], 2);\n\n    //     cout << i << \": \" << vec2str(xt, k) << \", xiener = \" << xiener + ener[i] << \" interval: [\" << lb << \", \" << ub << \"], xt[i] = \" << xt[i] << endl;\n    //     cout << \"subset: \" << vec2str(subset, subset.size()) << endl;\n\n    //     // if (xiener + ener[i] < radius + 1e-6) {  \n    //     if (i > 0) {\n    //      curr[i-1] = 0;                     \n    //         for (int j = i; j < k; j++)\n    //             curr[i-1] += xt[j]*R(i-1,j);\n    //         ener[i-1] = ener[i] + xiener;  \n    //         i--;\n    //         nextlevel = true;\n    //         cout << \"lowering dimension!\" << endl;\n    //         // continue;    \n    //     } else {\n    //      coeffs = conv_to<vector<int>>::from(xt);\n    //      X.zeros();\n    //      for (int i = 0; i < k; i++) {\n          //       X = X + coeffs[i]*bases[i];\n          //   }\n          //   cout << \"found point!\" << endl;\n          //   codebook.push_back(make_pair(coeffs, X));\n    //     } \n    //     // }\n    //     if (indices[i] >= subset.size() - 1){\n    //      cout << \"subset clear!\" << endl;\n    //      if (i == k - 1) break;\n       //   else {\n       //       indices[i] = 0;\n       //       // indices[i+1]++;\n       //       i++;\n       //       nextlevel = true;\n       //      }\n    //     } else indices[i]++;         \n    // }\n    // return codebook;\n\n    // #pragma omp parallel for\n    for (auto j = 0u; j < S.size(); j++) {\n        vec tmp = xt;\n        tmp[i] = S[j];\n        xidist = pow(dot(R.row(i).subvec(i, k-1), tmp.subvec(i, k-1)), 2) + dist;\n        if (xidist <= radius) {\n            if (i > 0) {\n                part = create_spherical_codebook(bases, R, S, radius, tmp, dim-1, xidist);\n                codebook.insert(codebook.end(), part.begin(), part.end());\n            } else {\n                coeffs = conv_to<vector<int>>::from(tmp);\n                X.zeros();\n                for (int s = 0; s < k; s++) {\n                    X = X + coeffs[s]*bases[s];\n                }\n                // cout << vec2str(coeffs, k) << endl;\n                codebook.push_back(make_pair(coeffs, X));\n            }\n        }\n    }\n    return codebook;\n}\n\n\n/* Creates a codebook (set of X matrices) from basis matrices B_i and symbolset q-PAM */\nvector<pair<vector<int>,cx_mat>> create_codebook(const vector<cx_mat> &bases, const mat &R, const vector<int> &symbolset){\n    int m = params[\"no_of_transmit_antennas\"];\n    int t = params[\"time_slots\"];\n    int k = params[\"no_of_matrices\"];\n    int cs = dparams[\"codebook_size\"];\n    int samples = params[\"energy_estimation_samples\"];\n    double P = dparams[\"spherical_shaping_max_power\"];\n\n    vector<pair<vector<int>,cx_mat>> codebook;\n    pair<vector<int>,cx_mat> code;\n    vector<int> tmp;\n    cx_mat X(m, t);\n    X.zeros();\n    \n    if(samples > 0){\n        for (int j = 0; j < samples; j++){\n            if (P > 0)\n                code = create_random_spherical_codeword(bases, R, symbolset, P);\n            else\n                code = create_random_codeword(bases, symbolset);\n            codebook.push_back(code);\n        }\n    } else {\n        if (P > 0)\n            return create_spherical_codebook(bases, R, symbolset, P, vec(k, fill::zeros), k, 0);\n\n        if (cs > 1e6)\n            log_msg(\"create_codebook: Generating a codebook of size \" + to_string(cs) + \", this can be really slow!\", \"Warning\");\n\n        /* all possible combinations of code words */\n        auto c = comb_wrapper(symbolset, k);\n\n        // log_msg(\"All possible data vector combinations:\");\n        for (const auto &symbols : c){\n            X.zeros();\n            for (int i = 0; i < k; i++)\n                X = X + symbols[i]*bases[i];\n            // log_msg(vec2str(symbols, symbols.size()));\n            // if (frob_norm_squared(X) > P + 1e-6 && P > 0) continue;\n            codebook.push_back(make_pair(symbols, X));\n        }\n    }\n    return codebook;\n}\n\n/* Computes the average and maximum energy of given codebook X */\npair<double,double> code_energy(const vector<pair<vector<int>,cx_mat>> &X){\n    double sum = 0, max = 0, tmp = 0, average = 0;\n    int cs = (int) X.size();\n\n    for (int i = 0; i < cs; i++){\n        tmp = frob_norm_squared(X[i].second);\n        sum += tmp;\n        if (tmp > max)\n            max = tmp;\n    }\n    average = sum / cs;\n    return make_pair(average, max);\n}\n\n/* Returns the shortest lattice basis vector from the lattice generator matrix G*/\ncx_vec shortest_basis_vector(const cx_mat &G){\n    cx_vec shortest(G.n_rows, fill::zeros);\n    double len = 10e9;\n    for (auto i = 0u; i < G.n_cols; i++){\n        if (len > norm(G.col(i), 2)) {\n            shortest = G.col(i);\n            len = norm(shortest, 2);\n        }\n    }\n    return shortest;\n}\n\n/* Check if x belongs to the right coset (when using coset encoding)\n * i.e. check if the difference vector sent_x - decoded_x belongs in \n * the given sublattice of the codebook carved out of lattice G_b\n */\nbool coset_check(const cx_mat &Gb, const cx_mat &invGe, const Col<int> diff){\n    cx_vec x = Gb*diff;\n    cx_vec lambda = invGe*x;\n\n    vec lambda_real = to_real_vector(lambda);\n    \n    /* check if lambda_real has only integer entries */\n    for (const auto &l : lambda_real)\n        if (fabs(l - round(l)) > 10e-5) /* tolerance */\n            return false;\n\n    return true;\n}\n\n/* calculates different rates related to the coset encoded block code */\ntuple<double, double, double> code_rates(const cx_mat &Gb, const cx_mat &Ge){\n    mat RGb = to_real_matrix(Gb);\n    mat RGe = to_real_matrix(Ge);\n    // cout << \"Vol(Ge): \" << sqrt(det(RGe.t()*RGe)) << endl;\n    // cout << \"Vol(Gb): \" << sqrt(det(RGb.t()*RGb)) << endl;\n    double r = log2(dparams[\"codebook_size\"]);                          // overall rate\n    double rt = log2(sqrt(det(RGe.t()*RGe))/sqrt(det(RGb.t()*RGb)));   // transmission rate\n    double rc = r - rt;                                                // confusion rate\n    return make_tuple(r, rt, rc); \n}\n\n/* algorithm for counting the lattice points inside a _dim_ dimensional hypersphere of radius _radius_ \n * considers only a single radius, but probably faster than the function below thanks to parallelisation\n */\nint count_points(const mat &R, const vector<int> &S, double radius, vec xt, int dim, double dist){\n\n    int k = params[\"no_of_matrices\"];\n    int i = dim - 1;\n\n    vector<int> counters(omp_get_max_threads());\n\n    #pragma omp parallel for\n    for (auto j = 0u; j < S.size(); j++) {\n        vec tmp = xt;\n        tmp[i] = S[j];\n        double xidist = pow(dot(R.row(i).subvec(i, k-1), tmp.subvec(i, k-1)), 2) + dist;\n        if (xidist <= radius) {\n            if (i > 0) {\n                counters[omp_get_thread_num()] += count_points(R, S, radius, tmp, dim-1, xidist);\n            } else {\n                counters[omp_get_thread_num()]++;\n            }\n        }\n    }\n    return accumulate(counters.begin(), counters.end(), 0);\n}\n\n\n/* algorithm for counting the lattice points inside a _dim_ dimensional hypersphere of radiuses r_1, r_2, ..., r_n */\nvector<int> count_points_many_radiuses(const mat &R, const vector<int> &S, vector<double> radiuses, vec xt, int dim, double dist){\n\n    int k = params[\"no_of_matrices\"];\n    int i = dim - 1;\n\n    vector<int> counters(radiuses.size());\n\n    for (auto j = 0u; j < S.size(); j++){\n        vec tmp = xt;\n        tmp[i] = S[j];\n        double xidist = pow(dot(R.row(i).subvec(i, k-1), tmp.subvec(i, k-1)), 2) + dist;\n        \n        if (xidist <= radiuses[0]){\n            if (i > 0){\n                vector<int> counts = count_points_many_radiuses(R, S, radiuses, tmp, dim-1, xidist);\n                for (auto s = 0u; s < radiuses.size(); s++)\n                    counters[s] += counts[s];\n            } else {\n                for (auto k = 0u; k < radiuses.size(); k++){\n                    if (xidist <= radiuses[k])\n                        counters[k]++;\n                }\n            }\n        }  \n    }\n    return counters;\n}\n\n/* \n * Should return the LLL reduced (as close to orthogonal as possible) basis for lattice generated by G \n */\ncx_mat LLL_reduction(const cx_mat &G) {\n    #ifdef USE_LLL\n\n        mat G_real = to_real_matrix(G);\n\n        // ZZ_mat<double> fpG(G_real.n_rows, G_real.n_cols);\n        // ZZ_mat<double> fpG(G_real.n_cols, G_real.n_rows);\n        FP_mat<double> fpG(G_real.n_cols, G_real.n_rows);\n        for (auto i = 0u; i < G_real.n_rows; i++) {\n            for (auto j = 0u; j < G_real.n_cols; j++) {\n                // fpG(i, j) = G_real(i, j);\n                fpG(j, i) = G_real(i, j);\n            }\n        }\n        cout << fpG << endl << endl;\n        int status = lll_reduction(fpG, LLL_DEF_DELTA, LLL_DEF_ETA, LM_PROVED, FT_DEFAULT, 0, LLL_DEFAULT);\n        if (status != RED_SUCCESS) {\n            log_msg(\"LLL reduction failed!\", \"Error\"); //with error '\" + to_string(get_red_status_str(status)) + \"'\", \"Error\");\n            exit(1);\n        }\n        cout << fpG << endl << endl;\n        for (auto i = 0u; i < G_real.n_rows; i++) {\n            for (auto j = 0u; j < G_real.n_cols; j++) {\n                // G_real(i, j) = fpG(i, j).get_d();\n                G_real(i, j) = fpG(j, i).get_d();\n            }\n        }\n        cout << G_real << endl;\n        return to_complex_matrix(G_real);\n\n    #else /* Do nothing */\n\n        return G;\n\n    #endif\n}", "meta": {"hexsha": "368a0536963b859b643435c7b0667dee195ee203", "size": 29560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algorithms.cpp", "max_stars_repo_name": "Hyper5phere/sphere-decoder", "max_stars_repo_head_hexsha": "f84cbcb47314547150639bbed017e8e540d32ced", "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/algorithms.cpp", "max_issues_repo_name": "Hyper5phere/sphere-decoder", "max_issues_repo_head_hexsha": "f84cbcb47314547150639bbed017e8e540d32ced", "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/algorithms.cpp", "max_forks_repo_name": "Hyper5phere/sphere-decoder", "max_forks_repo_head_hexsha": "f84cbcb47314547150639bbed017e8e540d32ced", "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.0236966825, "max_line_length": 156, "alphanum_fraction": 0.5365020298, "num_tokens": 8102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5416520691100591}}
{"text": "#include <cstdio> \n#include <cstdlib> \n#include <iostream>\n#include <vector>\n#include <list>\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/bindings/lapack/geqrf.hpp> \n#include <boost/numeric/bindings/lapack/orgqr.hpp> \n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/vector_sparse.hpp>\n#include <boost/numeric/ublas/vector_of_vector.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n\n#ifdef OPENMP\n#include <omp.h>\n#endif\n\nvoid Perform_Alpert_transform(boost::numeric::ublas::vector<double> f, std::vector<int> ki, int J,int dir, boost::numeric::ublas::vector<double>& w, std::list<std::list<boost::numeric::ublas::matrix<double,boost::numeric::ublas::column_major> > > Uj, std::list<std::vector<int> > part, std::vector<int> G);\nvoid Compute_Uj(std::vector<std::vector<double> >p, std::vector<int> ki, int &J, std::list<std::list<boost::numeric::ublas::matrix<double,boost::numeric::ublas::column_major> > > &Uj, std::list<std::vector<int> > &part, std::vector<int> &G);\nvoid Optimal_Alpert_transform(boost::numeric::ublas::vector<double> f, std::vector<std::vector<double> >p, std::vector<int> ki, int J, boost::numeric::ublas::vector<double>& w, std::list<std::list<boost::numeric::ublas::matrix<double,boost::numeric::ublas::column_major> > > Uj, std::list<std::vector<int> > part, std::vector<int> G, double NRMSE, double &R, double mx, double mn, double mxg, double mng, double alpha);", "meta": {"hexsha": "d4054b70339140e4511409ece8f7c90606b527b7", "size": 1825, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "swinzip-v2.0/src/Alpert/Alpert_Transform.hpp", "max_stars_repo_name": "msalloum80/SWinzip", "max_stars_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-17T07:58:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-17T07:58:23.000Z", "max_issues_repo_path": "swinzip-v2.5/src/Alpert/Alpert_Transform.hpp", "max_issues_repo_name": "msalloum80/SWinzip", "max_issues_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swinzip-v2.5/src/Alpert/Alpert_Transform.hpp", "max_forks_repo_name": "msalloum80/SWinzip", "max_forks_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-05T20:18:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T20:18:25.000Z", "avg_line_length": 60.8333333333, "max_line_length": 419, "alphanum_fraction": 0.7495890411, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.541652069110059}}
{"text": "//\n// Created by jachu on 27.02.18.\n//\n\n#include <iostream>\n\n#include <Eigen/Dense>\n\n#include <g2o/types/slam3d/se3quat.h>\n\n#include \"PlaneEstimator.hpp\"\n\nusing namespace std;\n\nPlaneEstimator::PlaneEstimator() {\n\n}\n\nPlaneEstimator::PlaneEstimator(const Eigen::MatrixXd &pts) {\n    init(pts);\n}\n\nPlaneEstimator::PlaneEstimator(const Eigen::Vector3d &icentroid,\n                               const Eigen::Matrix3d &icovar,\n                               int inpts)\n{\n    init(icentroid,\n         icovar,\n         inpts);\n}\n\nvoid PlaneEstimator::init(const Eigen::MatrixXd &pts) {\n    Eigen::Vector3d icentroid;\n    Eigen::Matrix3d icovar;\n    compCentroidAndCovar(pts, icentroid, icovar);\n    init(icentroid, icovar, pts.cols());\n}\n\nvoid\nPlaneEstimator::init(const Eigen::Vector3d &icentroid, const Eigen::Matrix3d &icovar, int inpts) {\n    centroid = icentroid;\n    covar = icovar;\n    npts = inpts;\n    compPlaneParams(centroid,\n                    covar,\n                    evecs,\n                    evals,\n                    planeEq);\n}\n\nvoid\nPlaneEstimator::update(const Eigen::Vector3d &ucentroid, const Eigen::Matrix3d &ucovar, int unpts) {\n//    cout << \"centroid = \" << centroid.transpose() << endl;\n//    cout << \"covar = \" << covar << endl;\n//    cout << \"npts = \" << npts << endl;\n//    cout << \"ucentroid = \" << ucentroid.transpose() << endl;\n//    cout << \"ucovar = \" << ucovar << endl;\n//    cout << \"unpts = \" << unpts << endl;\n    \n    updateCentroidAndCovar(centroid,\n                           covar,\n                           npts,\n                           ucentroid,\n                           ucovar,\n                           unpts,\n                           centroid,\n                           covar,\n                           npts);\n    \n//    cout << \"centroid = \" << centroid.transpose() << endl;\n//    cout << \"covar = \" << covar << endl;\n//    cout << \"npts = \" << npts << endl;\n    \n    static constexpr int ptsLimit = 500000;\n    if(npts > ptsLimit){\n        double scale = (double)npts/ptsLimit;\n        covar /= scale;\n        npts = ptsLimit;\n    }\n//    cout << \"centroid = \" << centroid.transpose() << endl;\n//    cout << \"covar = \" << covar << endl;\n//    cout << \"npts = \" << npts << endl;\n    \n    compPlaneParams(centroid,\n                    covar,\n                    evecs,\n                    evals,\n                    planeEq);\n}\n\ndouble PlaneEstimator::distance(const PlaneEstimator &other) const {\n    const Eigen::Vector3d &centroid1 = centroid;\n    const Eigen::Vector3d &centroid2 = other.centroid;\n    Eigen::Matrix3d covar1 = covar / npts;\n    Eigen::Matrix3d covar2 = other.covar / other.npts;\n    int npts1 = npts;\n    int npts2 = other.npts;\n    \n//    cout << \"centroid1 = \" << centroid1.transpose() << endl;\n//    cout << \"covar1 = \" << covar1 << endl;\n//    cout << \"centroid2 = \" << centroid2.transpose() << endl;\n//    cout << \"covar2 = \" << covar2 << endl;\n//\n//    Eigen::Vector3d centrDiff = centroid1 - centroid2;\n//    Eigen::Matrix3d infComb = (covar1 + covar2).inverse();\n//    Eigen::Matrix3d covarProd = covar1 * infComb * covar2;\n//    Eigen::Vector3d meanProd = covar2 * infComb * centroid1 +\n//                               covar1 * infComb * centroid2;\n//    double detVal = (2*M_PI*(covar1 + covar2)).determinant();\n//    double expVal = -0.5 * centrDiff.transpose() * infComb * centrDiff;\n//    double normFactor = 1.0 / sqrt(detVal) * exp(expVal);\n//    cout << \"detVal = \" << detVal << endl;\n//    cout << \"expVal = \" << -2.0*expVal << endl;\n//    cout << \"normFactor = \" << normFactor << endl;\n//    cout << \"dist = \" << 1.0/normFactor << endl;\n    \n    Eigen::Vector3d centrDiff = centroid1 - centroid2;\n    // covariance of the second plane relative to the centroid of the first plane\n    Eigen::Matrix3d relCovar = covar2 + (centrDiff * centrDiff.transpose());\n    \n    const Eigen::Vector3d &normal = evecs.col(2);\n    double varNorm = normal.transpose() * relCovar * normal;\n//    cout << \"covar2 = \" << covar2 << endl;\n//    cout << \"relCovar = \" << relCovar << endl;\n//    cout << \"normal = \" << normal.transpose() << endl;\n//    cout << \"varNorm = \" << varNorm << endl;\n    return varNorm;\n}\n\nvoid PlaneEstimator::compCentroidAndCovar(const Eigen::MatrixXd &pts,\n                                         Eigen::Vector3d &centroid,\n                                         Eigen::Matrix3d &covar)\n{\n    Eigen::Vector4d mean = Eigen::Vector4d::Zero();\n    for(int i = 0; i < pts.cols(); ++i){\n        mean += pts.col(i);\n    }\n    mean /= pts.cols();\n    \n    centroid = mean.head<3>();\n    \n    Eigen::MatrixXd demeanPts = pts;\n    for(int i = 0; i < demeanPts.cols(); ++i){\n        demeanPts.col(i) -= mean;\n    }\n    \n    covar = demeanPts.topRows<3>() * demeanPts.topRows<3>().transpose();\n}\n\nvoid PlaneEstimator::compPlaneParams(const Eigen::Vector3d centroid,\n                                     const Eigen::Matrix3d &covar,\n                                     Eigen::Matrix3d &evecs,\n                                     Eigen::Vector3d &evals,\n                                     Eigen::Vector4d &planeEq)\n{\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> evd(covar);\n    \n    for(int i = 0; i < 3; ++i){\n        evecs.col(i) = evd.eigenvectors().col(2 - i);\n        evals(i) = evd.eigenvalues()(2 - i);\n    }\n    \n    planeEq.head<3>() = evecs.col(2).cast<double>();\n    // distance is the dot product of normal and point lying on the plane\n    planeEq(3) = -planeEq.head<3>().dot(centroid);\n}\n\nvoid PlaneEstimator::transform(const Vector7d &transform) {\n    g2o::SE3Quat transformSE3Quat(transform);\n    Eigen::Matrix4d transformMat = transformSE3Quat.to_homogeneous_matrix();\n    Eigen::Matrix3d R = transformMat.block<3, 3>(0, 0);\n    Eigen::Vector3d t = transformMat.block<3, 1>(0, 3);\n    Eigen::Matrix4d Tinvt = transformMat.inverse();\n    Tinvt.transposeInPlace();\n    \n    // Eigen::Vector3d centroid;\n    centroid = R * centroid + t;\n    \n    // Eigen::Matrix3d covar;\n    covar = R * covar * R.transpose();\n    \n    // Eigen::Matrix3d evecs;\n    evecs = R * evecs;\n    \n    // Eigen::Vector3d evals;\n    // no need to transform\n    \n    // Eigen::Vector4d planeEq;\n    planeEq = Tinvt * planeEq;\n    \n    // int npts;\n    // no need to transform\n}\n\nvoid PlaneEstimator::updateCentroidAndCovar(const Eigen::Vector3d &centroid1,\n                                            const Eigen::Matrix3d &covar1,\n                                            const int &npts1,\n                                            const Eigen::Vector3d &centroid2,\n                                            const Eigen::Matrix3d &covar2,\n                                            const int &npts2,\n                                            Eigen::Vector3d &ocentroid,\n                                            Eigen::Matrix3d &ocovar,\n                                            int &onpts)\n{\n    ocentroid = (npts1 * centroid1 + npts2 * centroid2)/(npts1 + npts2);\n    Eigen::Vector3d centrDiff = centroid1 - centroid2;\n    double fact = ((double)npts1 * npts2)/(npts1 + npts2);\n//    cout << \"(npts1 * npts2)/(npts1 + npts2) = \" << fact << endl;\n//    cout << \"(centrDiff * centrDiff.transpose()) = \" << (centrDiff * centrDiff.transpose()) << endl;\n    ocovar = covar1 + covar2 + fact*(centrDiff * centrDiff.transpose());\n    onpts = npts1 + npts2;\n}\n", "meta": {"hexsha": "3c53407b1f36b61e713f6915520aa818b0bac746", "size": 7359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PlaneEstimator.cpp", "max_stars_repo_name": "richard5635/PlaneLoc", "max_stars_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-08-29T06:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T07:42:31.000Z", "max_issues_repo_path": "src/PlaneEstimator.cpp", "max_issues_repo_name": "richard5635/PlaneLoc", "max_issues_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-03-26T06:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T01:59:41.000Z", "max_forks_repo_path": "src/PlaneEstimator.cpp", "max_forks_repo_name": "richard5635/PlaneLoc", "max_forks_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-04-24T08:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T07:56:58.000Z", "avg_line_length": 34.5492957746, "max_line_length": 102, "alphanum_fraction": 0.533632287, "num_tokens": 1995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.541652047952531}}
{"text": "#include <algorithm>\n#include <csv_reader/csv_reader.h>\n#include <iostream>\n#include <string>\n\n#include <dlib/matrix.h>\n\nnamespace my_dlib {\ntemplate <typename T, size_t num_rows> struct MatrixData {\n  MatrixData() = default;\n  MatrixData(const std::string &csv_line) {\n    std::istringstream iss(csv_line);\n    for (size_t idx_element = 0; idx_element < num_rows; idx_element++) {\n      data(idx_element, 0) = parse_token<T>(iss);\n    }\n  }\n  dlib::matrix<T, num_rows, 1> data;\n};\n\n} // namespace my_dlib\n\nint main(int argc, char *argv[]) {\n\n  /*\n  auto sensor_data = load_csv_file<my_dlib::MatrixData<double, 13>>(argv[1]);\n  std::cout << sensor_data[0].data << std::endl;\n  std::cout << sensor_data[1].data << std::endl;\n  */\n\n  std::ifstream ifs(argv[1]);\n  dlib::matrix<double> my_matrix;\n  dlib::set_all_elements(my_matrix, 0);\n  std::cout << \"test matrix: \" << my_matrix << std::endl;\n  ifs >> my_matrix;\n  std::cout << \"test matrix: \" << my_matrix << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "9bc53633e28623c6dd41a170fcd3907213464fcf", "size": 985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/csv_reader/src/csv_reader_dlib_ex.cpp", "max_stars_repo_name": "Maverobot/cpp_playground", "max_stars_repo_head_hexsha": "c06ab8a0e7004a6cd5897695a7c00b7f4aee26b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-09-17T00:57:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T07:48:45.000Z", "max_issues_repo_path": "utils/csv_reader/src/csv_reader_dlib_ex.cpp", "max_issues_repo_name": "Maverobot/cpp_playground", "max_issues_repo_head_hexsha": "c06ab8a0e7004a6cd5897695a7c00b7f4aee26b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 58.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T10:45:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T16:19:11.000Z", "max_forks_repo_path": "utils/csv_reader/src/csv_reader_dlib_ex.cpp", "max_forks_repo_name": "Maverobot/cpp_playground", "max_forks_repo_head_hexsha": "c06ab8a0e7004a6cd5897695a7c00b7f4aee26b0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T11:49:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T04:08:58.000Z", "avg_line_length": 25.2564102564, "max_line_length": 77, "alphanum_fraction": 0.6598984772, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5416520354022095}}
{"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_REDUCTION_FUNCTORS_INCLUDE\n#define MTL_REDUCTION_FUNCTORS_INCLUDE\n\n#include <cmath>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/operation/squared_abs.hpp>\n\nnamespace mtl { namespace vector {\n\nstruct one_norm_functor\n{\n    template <typename Value>\n    static inline void init(Value& value)\n    {\n\tusing math::zero;\n\tvalue= zero(value);\n    }\n\n    template <typename Value, typename Element>\n    static inline void update(Value& value, const Element& x)\n    {    \n\tusing std::abs;\n\tvalue+= abs(x);\n    }\n\n    template <typename Value>\n    static inline void finish(Value& value, const Value& value2)\n    {\n\tvalue+= value2;\n    }\n\n    template <typename Value>\n    static inline Value post_reduction(const Value& value)\n    {\n\treturn value;\n    }\n};\n\n\n// sub-optimal if abs is not needed\nstruct two_norm_functor\n{\n    template <typename Value>\n    static inline void init(Value& value)\n    {\n\tusing math::zero;\n\tvalue= zero(value);\n    }\n\n    template <typename Value, typename Element>\n    static inline void update(Value& value, const Element& x)\n    {    \n\tusing mtl::squared_abs;\n\tvalue+= squared_abs(x);\n    }\n\n    template <typename Value>\n    static inline void finish(Value& value, const Value& value2)\n    {\n\tvalue+= value2;\n    }\n\n    // After reduction compute square root\n    template <typename Value>\n    static inline Value post_reduction(const Value& value)\n    {\n\tusing std::sqrt;\n\treturn sqrt(value);\n    }\n};\n\n// same as two-norm without the root at the end\nstruct unary_dot_functor\n  : two_norm_functor\n{\n    template <typename Value>\n    static inline Value post_reduction(const Value& value)\n    {\n\treturn value;\n    }\n};\n\nstruct infinity_norm_functor\n{\n    template <typename Value>\n    static inline void init(Value& value)\n    {\n\tusing math::zero;\n\tvalue= zero(value);\n    }\n\n    template <typename Value, typename Element>\n    static inline void update(Value& value, const Element& x)\n    {    \n\tusing std::abs; using std::max;\n\tvalue= max(value, Value(abs(x)));\n    }\n\n    template <typename Value>\n    static inline void finish(Value& value, const Value& value2)\n    {\n\tusing std::abs; using std::max;\n\tvalue= max(value, Value(abs(value2)));\n    }\n\n    template <typename Value>\n    static inline Value post_reduction(const Value& value)\n    {\n\treturn value;\n    }\n};\n\n\nstruct sum_functor\n{\n    template <typename Value>\n    static inline void init(Value& value)\n    {\n\tusing math::zero;\n\tvalue= zero(value);\n    }\n\n    template <typename Value, typename Element>\n    static inline void update(Value& value, const Element& x)\n    {    \n\tvalue+= x;\n    }\n\n    template <typename Value>\n    static inline void finish(Value& value, const Value& value2)\n    {\n\tvalue+= value2;\n    }\n\n    template <typename Value>\n    static inline Value post_reduction(const Value& value)\n    {\n\treturn value;\n    }\n};\n\n\nstruct product_functor\n{\n    template <typename Value>\n    static inline void init(Value& value)\n    {\n\tusing math::one;\n\tvalue= one(value);\n    }\n\n    template <typename Value, typename Element>\n    static inline void update(Value& value, const Element& x)\n    {    \n\tvalue*= x;\n    }\n\n    template <typename Value>\n    static inline void finish(Value& value, const Value& value2)\n    {\n\tvalue*= value2;\n    }\n\n    template <typename Value>\n    static inline Value post_reduction(const Value& value)\n    {\n\treturn value;\n    }\n};\n\n\nstruct max_functor\n{\n    template <typename Value>\n    static inline void init(Value& value)\n    {\n\tusing math::identity; \n\tvalue= math::identity(math::max<Value>(), value); // ADL doesn't work here in g++ 4.4\n    }\n\n    template <typename Value, typename Element>\n    static inline void update(Value& value, const Element& x)\n    {    \n\tvalue= math::max<Value>()(value, x);\n    }\n\n    template <typename Value>\n    static inline void finish(Value& value, const Value& value2)\n    {\n\tvalue= math::max<Value>()(value, value2);\n    }\n\n    template <typename Value>\n    static inline Value post_reduction(const Value& value)\n    {\n\treturn value;\n    }\n};\n\n\nstruct min_functor\n{\n    template <typename Value>\n    static inline void init(Value& value)\n    {\n\tusing math::identity; \n\tvalue= math::identity(math::min<Value>(), value); // ADL doesn't work here in g++ 4.4\n    }\n\n    template <typename Value, typename Element>\n    static inline void update(Value& value, const Element& x)\n    {    \n\tvalue= math::min<Value>()(value, x);\n    }\n\n    template <typename Value>\n    static inline void finish(Value& value, const Value& value2)\n    {\n\tvalue= math::min<Value>()(value, value2);\n    }\n\n    template <typename Value>\n    static inline Value post_reduction(const Value& value)\n    {\n\treturn value;\n    }\n};\n\n\n}} // namespace mtl::vector\n\n#endif // MTL_REDUCTION_FUNCTORS_INCLUDE\n", "meta": {"hexsha": "c4f3d09502d2fedd820a6e260edaf7893ceb2b6c", "size": 5230, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/vector/reduction_functors.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/vector/reduction_functors.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/vector/reduction_functors.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": 21.3469387755, "max_line_length": 94, "alphanum_fraction": 0.6638623327, "num_tokens": 1243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5416308655651617}}
{"text": "#pragma once\n#include <manipulate_topics/msg_filter_base.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <numeric>\n#include <dynamic_reconfigure/server.h>\n#include<manipulate_topics/MeanConfig.h>\n\n/**\n * @brief Class that implements a mean filter for a given Topic type.\n * \n * |Ros-Parameter | Desciption|\n * |---- | -----|\n * |~sample_number | Number of samples the mean is calculated from|\n * \n * @tparam T Type of the topic to be filtered. Operators + and / must be implemented within the msg_operators namespace.\n */\n\ntemplate<class T>\nclass MessageMeanFilter: public MessageFilterBase<T>{\n    public:\n        MessageMeanFilter(ros::NodeHandle &nh);\n        \n    private:\n        dynamic_reconfigure::Server<manipulate_topics::MeanConfig> server_; \n        void dynConfigcallback(manipulate_topics::MeanConfig &config, uint32_t level); ///<Callback for the dynamic reconfigure server\n        int samples_num_;\n        T filter() override; \n        \n};\n#include \"../src/msg_mean_filter.cpp\"", "meta": {"hexsha": "e8b780d650f669a1eafb799d76a0daa2604217ad", "size": 1057, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Match_Mobile_Robotics/general_hardware_helper/manipulate_topics/include/manipulate_topics/msg_mean_filter.hpp", "max_stars_repo_name": "Grossbier/simulation_multirobots", "max_stars_repo_head_hexsha": "1fe00bf81932ad6de20709ad85f677f4cf196333", "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/Match_Mobile_Robotics/general_hardware_helper/manipulate_topics/include/manipulate_topics/msg_mean_filter.hpp", "max_issues_repo_name": "Grossbier/simulation_multirobots", "max_issues_repo_head_hexsha": "1fe00bf81932ad6de20709ad85f677f4cf196333", "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/Match_Mobile_Robotics/general_hardware_helper/manipulate_topics/include/manipulate_topics/msg_mean_filter.hpp", "max_forks_repo_name": "Grossbier/simulation_multirobots", "max_forks_repo_head_hexsha": "1fe00bf81932ad6de20709ad85f677f4cf196333", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-04T09:16:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T09:16:28.000Z", "avg_line_length": 34.0967741935, "max_line_length": 134, "alphanum_fraction": 0.7190160833, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5416308607105697}}
{"text": "/**\n * @file nca_test.cpp\n * @author Ryan Curtin\n *\n * Unit tests for Neighborhood Components Analysis and related code (including\n * the softmax error function).\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 <mlpack/methods/nca/nca.hpp>\n#include <ensmallen.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::metric;\nusing namespace mlpack::nca;\nusing namespace ens;\n\n//\n// Tests for the SoftmaxErrorFunction\n//\n\nBOOST_AUTO_TEST_SUITE(NCATest);\n\n/**\n * The Softmax error function should return the identity matrix as its initial\n * point.\n */\nBOOST_AUTO_TEST_CASE(SoftmaxInitialPoint)\n{\n  // Cheap fake dataset.\n  arma::mat data;\n  data.randu(5, 5);\n  arma::Row<size_t> labels;\n  labels.zeros(5);\n\n  SoftmaxErrorFunction<SquaredEuclideanDistance> sef(data, labels);\n\n  // Verify the initial point is the identity matrix.\n  arma::mat initialPoint = sef.GetInitialPoint();\n  for (int row = 0; row < 5; row++)\n  {\n    for (int col = 0; col < 5; col++)\n    {\n      if (row == col)\n        BOOST_REQUIRE_CLOSE(initialPoint(row, col), 1.0, 1e-5);\n      else\n        BOOST_REQUIRE_SMALL(initialPoint(row, col), 1e-5);\n    }\n  }\n}\n\n/***\n * On a simple fake dataset, ensure that the initial function evaluation is\n * correct.\n */\nBOOST_AUTO_TEST_CASE(SoftmaxInitialEvaluation)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat data           = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  SoftmaxErrorFunction<SquaredEuclideanDistance> sef(data, labels);\n\n  double objective = sef.Evaluate(arma::eye<arma::mat>(2, 2));\n\n  // Result painstakingly calculated by hand by rcurtin (recorded forever in his\n  // notebook).  As a result of lack of precision of the by-hand result, the\n  // tolerance is fairly high.\n  BOOST_REQUIRE_CLOSE(objective, -1.5115, 0.01);\n}\n\n/**\n * On a simple fake dataset, ensure that the initial gradient evaluation is\n * correct.\n */\nBOOST_AUTO_TEST_CASE(SoftmaxInitialGradient)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat data           = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  SoftmaxErrorFunction<SquaredEuclideanDistance> sef(data, labels);\n\n  arma::mat gradient;\n  arma::mat coordinates = arma::eye<arma::mat>(2, 2);\n  sef.Gradient(coordinates, gradient);\n\n  // Results painstakingly calculated by hand by rcurtin (recorded forever in\n  // his notebook).  As a result of lack of precision of the by-hand result, the\n  // tolerance is fairly high.\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.089766, 0.05);\n  BOOST_REQUIRE_SMALL(gradient(1, 0), 1e-5);\n  BOOST_REQUIRE_SMALL(gradient(0, 1), 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 1.63823, 0.01);\n}\n\n/**\n * On optimally separated datasets, ensure that the objective function is\n * optimal (equal to the negative number of points).\n */\nBOOST_AUTO_TEST_CASE(SoftmaxOptimalEvaluation)\n{\n  // Simple optimal dataset.\n  arma::mat data           = \" 500  500 -500 -500;\"\n                             \"   1    0    1    0 \";\n  arma::Row<size_t> labels = \"   0    0    1    1 \";\n\n  SoftmaxErrorFunction<SquaredEuclideanDistance> sef(data, labels);\n\n  double objective = sef.Evaluate(arma::eye<arma::mat>(2, 2));\n\n  // Use a very close tolerance for optimality; we need to be sure this function\n  // gives optimal results correctly.\n  BOOST_REQUIRE_CLOSE(objective, -4.0, 1e-10);\n}\n\n/**\n * On optimally separated datasets, ensure that the gradient is zero.\n */\nBOOST_AUTO_TEST_CASE(SoftmaxOptimalGradient)\n{\n  // Simple optimal dataset.\n  arma::mat data           = \" 500  500 -500 -500;\"\n                             \"   1    0    1    0 \";\n  arma::Row<size_t> labels = \"   0    0    1    1 \";\n\n  SoftmaxErrorFunction<SquaredEuclideanDistance> sef(data, labels);\n\n  arma::mat gradient;\n  sef.Gradient(arma::eye<arma::mat>(2, 2), gradient);\n\n  BOOST_REQUIRE_SMALL(gradient(0, 0), 1e-5);\n  BOOST_REQUIRE_SMALL(gradient(0, 1), 1e-5);\n  BOOST_REQUIRE_SMALL(gradient(1, 0), 1e-5);\n  BOOST_REQUIRE_SMALL(gradient(1, 1), 1e-5);\n}\n\n/**\n * Ensure the separable objective function is right.\n */\nBOOST_AUTO_TEST_CASE(SoftmaxSeparableObjective)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat data           = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  SoftmaxErrorFunction<SquaredEuclideanDistance> sef(data, labels);\n\n  // Results painstakingly calculated by hand by rcurtin (recorded forever in\n  // his notebook).  As a result of lack of precision of the by-hand result, the\n  // tolerance is fairly high.\n  arma::mat coordinates = arma::eye<arma::mat>(2, 2);\n  BOOST_REQUIRE_CLOSE(sef.Evaluate(coordinates, 0, 1), -0.22480, 0.01);\n  BOOST_REQUIRE_CLOSE(sef.Evaluate(coordinates, 1, 1), -0.30613, 0.01);\n  BOOST_REQUIRE_CLOSE(sef.Evaluate(coordinates, 2, 1), -0.22480, 0.01);\n  BOOST_REQUIRE_CLOSE(sef.Evaluate(coordinates, 3, 1), -0.22480, 0.01);\n  BOOST_REQUIRE_CLOSE(sef.Evaluate(coordinates, 4, 1), -0.30613, 0.01);\n  BOOST_REQUIRE_CLOSE(sef.Evaluate(coordinates, 5, 1), -0.22480, 0.01);\n}\n\n/**\n * Ensure the optimal separable objective function is right.\n */\nBOOST_AUTO_TEST_CASE(OptimalSoftmaxSeparableObjective)\n{\n  // Simple optimal dataset.\n  arma::mat data           = \" 500  500 -500 -500;\"\n                             \"   1    0    1    0 \";\n  arma::Row<size_t> labels = \"   0    0    1    1 \";\n\n  SoftmaxErrorFunction<SquaredEuclideanDistance> sef(data, labels);\n\n  arma::mat coordinates = arma::eye<arma::mat>(2, 2);\n\n  // Use a very close tolerance for optimality; we need to be sure this function\n  // gives optimal results correctly.\n  BOOST_REQUIRE_CLOSE(sef.Evaluate(coordinates, 0, 1), -1.0, 1e-10);\n  BOOST_REQUIRE_CLOSE(sef.Evaluate(coordinates, 1, 1), -1.0, 1e-10);\n  BOOST_REQUIRE_CLOSE(sef.Evaluate(coordinates, 2, 1), -1.0, 1e-10);\n  BOOST_REQUIRE_CLOSE(sef.Evaluate(coordinates, 3, 1), -1.0, 1e-10);\n}\n\n/**\n * Ensure the separable gradient is right.\n */\nBOOST_AUTO_TEST_CASE(SoftmaxSeparableGradient)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat data           = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  SoftmaxErrorFunction<SquaredEuclideanDistance> sef(data, labels);\n\n  arma::mat coordinates = arma::eye<arma::mat>(2, 2);\n  arma::mat gradient(2, 2);\n\n  sef.Gradient(coordinates, 0, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -2.0 * 0.0069708, 0.01);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), -2.0 * -0.0101707, 0.01);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), -2.0 * -0.0101707, 0.01);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), -2.0 * -0.14359, 0.01);\n\n  sef.Gradient(coordinates, 1, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -2.0 * 0.008496, 0.01);\n  BOOST_REQUIRE_SMALL(gradient(0, 1), 1e-5);\n  BOOST_REQUIRE_SMALL(gradient(1, 0), 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), -2.0 * -0.12238, 0.01);\n\n  sef.Gradient(coordinates, 2, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -2.0 * 0.0069708, 0.01);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), -2.0 * 0.0101707, 0.01);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), -2.0 * 0.0101707, 0.01);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), -2.0 * -0.1435886, 0.01);\n\n  sef.Gradient(coordinates, 3, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -2.0 * 0.0069708, 0.01);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), -2.0 * 0.0101707, 0.01);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), -2.0 * 0.0101707, 0.01);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), -2.0 * -0.1435886, 0.01);\n\n  sef.Gradient(coordinates, 4, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -2.0 * 0.008496, 0.01);\n  BOOST_REQUIRE_SMALL(gradient(0, 1), 1e-5);\n  BOOST_REQUIRE_SMALL(gradient(1, 0), 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), -2.0 * -0.12238, 0.01);\n\n  sef.Gradient(coordinates, 5, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -2.0 * 0.0069708, 0.01);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), -2.0 * -0.0101707, 0.01);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), -2.0 * -0.0101707, 0.01);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), -2.0 * -0.1435886, 0.01);\n}\n\n//\n// Tests for the NCA algorithm.\n//\n\n/**\n * On our simple dataset, ensure that the NCA algorithm fully separates the\n * points.\n */\nBOOST_AUTO_TEST_CASE(NCASGDSimpleDataset)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat data           = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  // Huge learning rate because this is so simple.\n  NCA<SquaredEuclideanDistance> nca(data, labels);\n  nca.Optimizer().StepSize() = 1.2;\n  nca.Optimizer().MaxIterations() = 300000;\n  nca.Optimizer().Tolerance() = 0;\n  nca.Optimizer().Shuffle() = true;\n\n  arma::mat outputMatrix;\n  nca.LearnDistance(outputMatrix);\n\n  // Ensure that the objective function is better now.\n  SoftmaxErrorFunction<SquaredEuclideanDistance> sef(data, labels);\n\n  double initObj = sef.Evaluate(arma::eye<arma::mat>(2, 2));\n  double finalObj = sef.Evaluate(outputMatrix);\n  arma::mat finalGradient;\n  sef.Gradient(outputMatrix, finalGradient);\n\n  // finalObj must be less than initObj.\n  BOOST_REQUIRE_LT(finalObj, initObj);\n  // Verify that final objective is optimal.\n  BOOST_REQUIRE_CLOSE(finalObj, -6.0, 0.005);\n  // The solution is not unique, so the best we can do is ensure the gradient\n  // norm is close to 0.\n  BOOST_REQUIRE_LT(arma::norm(finalGradient, 2), 1e-4);\n}\n\nBOOST_AUTO_TEST_CASE(NCALBFGSSimpleDataset)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat data           = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  // Huge learning rate because this is so simple.\n  NCA<SquaredEuclideanDistance, L_BFGS> nca(data, labels);\n  nca.Optimizer().NumBasis() = 5;\n\n  arma::mat outputMatrix;\n  nca.LearnDistance(outputMatrix);\n\n  // Ensure that the objective function is better now.\n  SoftmaxErrorFunction<SquaredEuclideanDistance> sef(data, labels);\n\n  double initObj = sef.Evaluate(arma::eye<arma::mat>(2, 2));\n  double finalObj = sef.Evaluate(outputMatrix);\n  arma::mat finalGradient;\n  sef.Gradient(outputMatrix, finalGradient);\n\n  // finalObj must be less than initObj.\n  BOOST_REQUIRE_LT(finalObj, initObj);\n  // Verify that final objective is optimal.\n  BOOST_REQUIRE_CLOSE(finalObj, -6.0, 1e-5);\n  // The solution is not unique, so the best we can do is ensure the gradient\n  // norm is close to 0.\n  BOOST_REQUIRE_LT(arma::norm(finalGradient, 2), 1e-6);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "90cb53eeeb9f32a646cf87c89bdbd36afc989a9f", "size": 11317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/nca_test.cpp", "max_stars_repo_name": "RMaron/mlpack", "max_stars_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:20:29.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-21T23:30:34.000Z", "max_issues_repo_path": "src/mlpack/tests/nca_test.cpp", "max_issues_repo_name": "RMaron/mlpack", "max_issues_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-01-23T18:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T13:58:34.000Z", "max_forks_repo_path": "src/mlpack/tests/nca_test.cpp", "max_forks_repo_name": "RMaron/mlpack", "max_forks_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-20T00:54:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-16T05:34:32.000Z", "avg_line_length": 34.7147239264, "max_line_length": 80, "alphanum_fraction": 0.6611292745, "num_tokens": 3673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5416308607105697}}
{"text": "// Copyright (C) 2017 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 (sweeney.chris.m@gmail.com)\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <ceres/rotation.h>\n\n#include \"gtest/gtest.h\"\n\n#include \"theia/math/rotation.h\"\n#include \"theia/math/util.h\"\n\nnamespace theia {\n\nvoid TestTwoRotations(const Eigen::Vector3d& rotation1,\n                      const Eigen::Vector3d& rotation2,\n                      const double tolerance_degrees) {\n  // Convert to rotation matrices.\n  Eigen::Matrix3d rotation1_matrix, rotation2_matrix;\n  ceres::AngleAxisToRotationMatrix(\n      rotation1.data(), ceres::ColumnMajorAdapter3x3(rotation1_matrix.data()));\n  ceres::AngleAxisToRotationMatrix(\n      rotation2.data(), ceres::ColumnMajorAdapter3x3(rotation2_matrix.data()));\n\n  // Compose the rotations to obtain R3 = R1 * R2;\n  const Eigen::Matrix3d rotation_matrix = rotation1_matrix * rotation2_matrix;\n\n  // Get the estimated rotation.\n  const Eigen::Vector3d estimated_rotation =\n      MultiplyRotations(rotation1, rotation2);\n\n  // Convert the estimated rotation to a rotation matrix.\n  Eigen::Matrix3d estimated_rotation_matrix;\n  ceres::AngleAxisToRotationMatrix(\n      estimated_rotation.data(),\n      ceres::ColumnMajorAdapter3x3(estimated_rotation_matrix.data()));\n\n  // Determine the angle between the two rotations.\n  const Eigen::AngleAxisd rotation_difference(rotation_matrix.transpose() *\n                                              estimated_rotation_matrix);\n  EXPECT_LT(RadToDeg(rotation_difference.angle()), tolerance_degrees);\n}\n\nTEST(MultiplyRotations, BasicTest) {\n  static const double kToleranceDegrees = 1e-8;\n  const Eigen::Vector3d rotation1(-0.3, -0.2, 0.1);\n  const Eigen::Vector3d rotation2(0.13, 0.06, -0.4);\n  TestTwoRotations(rotation1, rotation2, kToleranceDegrees);\n}\n\nTEST(MultiplyRotations, SmallFirstRotation) {\n  static const double kToleranceDegrees = 1e-8;\n  const Eigen::Vector3d rotation1(1e-12, 4e-10, 1e-16);\n  const Eigen::Vector3d rotation2(0.13, 0.06, -0.4);\n  TestTwoRotations(rotation1, rotation2, kToleranceDegrees);\n}\n\nTEST(MultiplyRotations, SmallSecondRotation) {\n  static const double kToleranceDegrees = 1e-8;\n  const Eigen::Vector3d rotation1(-0.3, -0.2, 0.1);\n  const Eigen::Vector3d rotation2(1e-12, 4e-10, 1e-16);\n  TestTwoRotations(rotation1, rotation2, kToleranceDegrees);\n}\n\nTEST(MultiplyRotations, BothSmallRotations) {\n  static const double kToleranceDegrees = 1e-8;\n  const Eigen::Vector3d rotation1(-4e-12, -2e-10, 1e-16);\n  const Eigen::Vector3d rotation2(3e-12, 1e-10, 8e-16);\n  TestTwoRotations(rotation1, rotation2, kToleranceDegrees);\n}\n\nTEST(MultiplyRotations, OppositeRotations) {\n  static const double kToleranceDegrees = 1e-8;\n  const Eigen::Vector3d rotation1(-0.3, -0.2, 0.1);\n  const Eigen::Vector3d rotation2(0.3, 0.2, -0.1);\n  TestTwoRotations(rotation1, rotation2, kToleranceDegrees);\n}\n\nTEST(MultiplyRotations, DifficultRotatations) {\n  static const double kToleranceDegrees = 1e-8;\n  const Eigen::Vector3d rotation1(0.00648212, -1.05947, 0.204346);\n  const Eigen::Vector3d rotation2(0.0158538, -2.07541, 0.356276);\n  TestTwoRotations(rotation1, rotation2, kToleranceDegrees);\n}\n}  // namespace theia\n", "meta": {"hexsha": "a9206217882686132a9e9a760dd4f61afd7da0df", "size": 4889, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/math/rotation_test.cc", "max_stars_repo_name": "urbste/TheiaSfM", "max_stars_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T03:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T08:08:45.000Z", "max_issues_repo_path": "src/theia/math/rotation_test.cc", "max_issues_repo_name": "urbste/TheiaSfM", "max_issues_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/math/rotation_test.cc", "max_forks_repo_name": "urbste/TheiaSfM", "max_forks_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-20T03:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T08:08:52.000Z", "avg_line_length": 41.7863247863, "max_line_length": 79, "alphanum_fraction": 0.7422785846, "num_tokens": 1255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5416308558559775}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <shz/math/matrix.hpp>\n \nextern bool is_aligned(void *p, intptr_t N);\n\nBOOST_AUTO_TEST_CASE(matrix4fConstructors)\n{\n\tshz::math::matrix4f m = shz::math::matrix4f::identity();\n\tshz::math::matrix4f n = shz::math::matrix4f::identity();\n\tshz::math::matrix4f nn(n);\n\n\tBOOST_CHECK(is_aligned(&m, 16));\n\tBOOST_CHECK(is_aligned(&n, 16));\n\tBOOST_CHECK(is_aligned(&nn, 16));\n\t\n\tBOOST_CHECK(true == m.is_identity());\n\tBOOST_CHECK(true == n.is_identity());\n\tBOOST_CHECK(true == nn.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(0.f == m.data[3]);\n\n\tBOOST_CHECK(0.f == m.data[4]);\n\tBOOST_CHECK(1.f == m.data[5]);\n\tBOOST_CHECK(0.f == m.data[6]);\n\tBOOST_CHECK(0.f == m.data[7]);\n\n\tBOOST_CHECK(0.f == m.data[8]);\n\tBOOST_CHECK(0.f == m.data[9]);\n\tBOOST_CHECK(1.f == m.data[10]);\n\tBOOST_CHECK(0.f == m.data[11]);\n\n\tBOOST_CHECK(0.f == m.data[12]);\n\tBOOST_CHECK(0.f == m.data[13]);\n\tBOOST_CHECK(0.f == m.data[14]);\n\tBOOST_CHECK(1.f == m.data[15]);\n}\n\nBOOST_AUTO_TEST_CASE(matrix4fSizeConstructors)\n{\n\tshz::math::matrix4f m = shz::math::matrix4f::identity();\n\tshz::math::matrix4f n = shz::math::matrix4f::identity();\n\n\n\tBOOST_CHECK(true == m.is_identity());\n\tBOOST_CHECK(true == n.is_identity());\n\n\tBOOST_CHECK(4*4 == m.size);\n\tBOOST_CHECK(4 == m.mindimension);\n\tBOOST_CHECK(4 == m.columns);\n\tBOOST_CHECK(4 == m.rows);\n}\n\nBOOST_AUTO_TEST_CASE(matrix4fAdds)\n{\n\tshz::math::matrix4f m = shz::math::matrix4f::identity();\n\tshz::math::matrix4f n = shz::math::matrix4f::identity();\n\n\tshz::math::matrix4f j = m+n;\n\tBOOST_CHECK(true != j.is_identity());\n\tBOOST_CHECK(4*4 == 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(0.f == j.data[3]);\n\n\tBOOST_CHECK(0.f == j.data[4]);\n\tBOOST_CHECK(2.f == j.data[5]);\n\tBOOST_CHECK(0.f == j.data[6]);\n\tBOOST_CHECK(0.f == j.data[7]);\n\n\tBOOST_CHECK(0.f == j.data[8]);\n\tBOOST_CHECK(0.f == j.data[9]);\n\tBOOST_CHECK(2.f == j.data[10]);\n\tBOOST_CHECK(0.f == j.data[11]);\n\n\tBOOST_CHECK(0.f == j.data[12]);\n\tBOOST_CHECK(0.f == j.data[13]);\n\tBOOST_CHECK(0.f == j.data[14]);\n\tBOOST_CHECK(2.f == j.data[15]);\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(0.f == m.data[3]);\n\n\tBOOST_CHECK(0.f == m.data[4]);\n\tBOOST_CHECK(2.f == m.data[5]);\n\tBOOST_CHECK(0.f == m.data[6]);\n\tBOOST_CHECK(0.f == m.data[7]);\n\n\tBOOST_CHECK(0.f == m.data[8]);\n\tBOOST_CHECK(0.f == m.data[9]);\n\tBOOST_CHECK(2.f == m.data[10]);\n\tBOOST_CHECK(0.f == m.data[11]);\n\n\tBOOST_CHECK(0.f == m.data[12]);\n\tBOOST_CHECK(0.f == m.data[13]);\n\tBOOST_CHECK(0.f == m.data[14]);\n\tBOOST_CHECK(2.f == m.data[15]);\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(2.f == n.data[3]);\n\n\tBOOST_CHECK(2.f == n.data[4]);\n\tBOOST_CHECK(3.f == n.data[5]);\n\tBOOST_CHECK(2.f == n.data[6]);\n\tBOOST_CHECK(2.f == n.data[7]);\n\n\tBOOST_CHECK(2.f == n.data[8]);\n\tBOOST_CHECK(2.f == n.data[9]);\n\tBOOST_CHECK(3.f == n.data[10]);\n\tBOOST_CHECK(2.f == n.data[11]);\n\n\tBOOST_CHECK(2.f == n.data[12]);\n\tBOOST_CHECK(2.f == n.data[13]);\n\tBOOST_CHECK(2.f == n.data[14]);\n\tBOOST_CHECK(3.f == n.data[15]);\n}\n\nBOOST_AUTO_TEST_CASE(matrix4fSubs)\n{\n\tshz::math::matrix4f m = shz::math::matrix4f::identity();\n\tshz::math::matrix4f n = shz::math::matrix4f::identity();\n\n\tshz::math::matrix4f j = m-n;\n\tBOOST_CHECK(true != j.is_identity());\n\tBOOST_CHECK(16 == 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(-2.f == n.data[3]);\n\n\tBOOST_CHECK(-2.f == n.data[4]);\n\tBOOST_CHECK(-1.f == n.data[5]);\n\tBOOST_CHECK(-2.f == n.data[6]);\n\tBOOST_CHECK(-2.f == n.data[7]);\n\n\tBOOST_CHECK(-2.f == n.data[8]);\n\tBOOST_CHECK(-2.f == n.data[9]);\n\tBOOST_CHECK(-1.f == n.data[10]);\n\tBOOST_CHECK(-2.f == n.data[11]);\n\n\tBOOST_CHECK(-2.f == n.data[12]);\n\tBOOST_CHECK(-2.f == n.data[13]);\n\tBOOST_CHECK(-2.f == n.data[14]);\n\tBOOST_CHECK(-1.f == n.data[15]);\n}\n\n\nBOOST_AUTO_TEST_CASE(matrix4fMuls)\n{\n\tshz::math::matrix4f m = shz::math::matrix4f::identity();\n\tshz::math::matrix4f n = shz::math::matrix4f::identity();\n\n\tshz::math::matrix4f j = m*n;\n\tBOOST_CHECK(true == j.is_identity());\n\tBOOST_CHECK(4*4 == j.size);\n\n\tshz::math::vector4f v = shz::math::vector4f();\n\tv.data[0] = 2.f;\n\tv.data[1] = 2.f;\n\tv.data[2] = 0.f;\n\tv.data[3] = 0.f;\n\tshz::math::vector4f b = m*v;\n\tBOOST_CHECK(2.f == b.data[0]);\n\tBOOST_CHECK(2.f == b.data[1]);\n\tBOOST_CHECK(0.f == b.data[2]);\n\tBOOST_CHECK(0.f == b.data[3]);\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\tBOOST_CHECK(0.f == b.data[2]);\n\tBOOST_CHECK(0.f == b.data[3]);\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(0.f == m.data[3]);\n\n\tBOOST_CHECK(0.f == m.data[4]);\n\tBOOST_CHECK(2.f == m.data[5]);\n\tBOOST_CHECK(0.f == m.data[6]);\n\tBOOST_CHECK(0.f == m.data[7]);\n\n\tBOOST_CHECK(0.f == m.data[8]);\n\tBOOST_CHECK(0.f == m.data[9]);\n\tBOOST_CHECK(2.f == m.data[10]);\n\tBOOST_CHECK(0.f == m.data[11]);\n\n\tBOOST_CHECK(0.f == m.data[12]);\n\tBOOST_CHECK(0.f == m.data[13]);\n\tBOOST_CHECK(0.f == m.data[14]);\n\tBOOST_CHECK(2.f == m.data[15]);\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(0.f == m.data[3]);\n\n\tBOOST_CHECK(0.f == m.data[4]);\n\tBOOST_CHECK(4.f == m.data[5]);\n\tBOOST_CHECK(0.f == m.data[6]);\n\tBOOST_CHECK(0.f == m.data[7]);\n\n\tBOOST_CHECK(0.f == m.data[8]);\n\tBOOST_CHECK(0.f == m.data[9]);\n\tBOOST_CHECK(4.f == m.data[10]);\n\tBOOST_CHECK(0.f == m.data[11]);\n\n\tBOOST_CHECK(0.f == m.data[12]);\n\tBOOST_CHECK(0.f == m.data[13]);\n\tBOOST_CHECK(0.f == m.data[14]);\n\tBOOST_CHECK(4.f == m.data[15]);\n\n}\n\nBOOST_AUTO_TEST_CASE(matrixRotation)\n{\n\t//shz::math::vector3f axis(0.f, 1.f, 0.f);\n\t//auto rot = shz::math::matrix4f::from_rotation(axis, shz::math::HALF_PI);\n\n}\n\n/*\nBOOST_AUTO_TEST_CASE(matrixPerformance)\n{\n\tauto m = shz::math::matrix<shz::math::f32, 200, 200>::identity();\n\tauto n = shz::math::matrix<shz::math::f32, 200, 200>::identity();\n\n\tfor(size_t i=0; i<10000; i++)\n\t\tauto r = m*n;\n}*/\n", "meta": {"hexsha": "c538c217042142787fb004393abdc3433690178a", "size": 6591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Math/matrix4f_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/matrix4f_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/matrix4f_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": 25.4478764479, "max_line_length": 75, "alphanum_fraction": 0.6167501138, "num_tokens": 2196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5416308558559774}}
{"text": "#include \"convergence/moments/convergence_checker_l1_norm.hpp\"\n\n#include <deal.II/lac/vector.h>\n\n#include \"test_helpers/test_helper_functions.h\"\n#include \"test_helpers/gmock_wrapper.h\"\n\nnamespace {\n\nusing namespace bart;\n\nclass SingleMomentCheckerL1NormTest : public ::testing::Test {\n public:\n  using Vector = dealii::Vector<double>;\n  static constexpr double max_delta{ 1e-6 };\n  static constexpr Vector::size_type moment_size{5 };\n  bart::convergence::moments::ConvergenceCheckerL1Norm checker{ max_delta };\n  Vector moment_one, moment_two;\n  auto SetUp() -> void override;\n};\n\nauto SingleMomentCheckerL1NormTest::SetUp() -> void {\n  auto set_up_moment = [=](Vector& moment) {\n    moment.reinit(moment_size);\n    const auto random_vector{ test_helpers::RandomVector(5, 0, 2) };\n    for (Vector::size_type i = 0; i < moment_size; ++i)\n      moment[i] = random_vector.at(i);\n  };\n  set_up_moment(moment_one);\n  moment_two = moment_one;\n}\n\n// Max Delta getter should return the correct value\nTEST_F(SingleMomentCheckerL1NormTest, Getters) {\n  EXPECT_EQ(checker.max_delta(), this->max_delta);\n}\n\n// Max delta setter should set value correctly\nTEST_F(SingleMomentCheckerL1NormTest, MaxDeltaSetter) {\n  const double max_delta_to_set{ test_helpers::RandomDouble(1e-16, 1e-8) };\n  EXPECT_EQ(checker.max_delta(), this->max_delta);\n  checker.SetMaxDelta(max_delta_to_set);\n  EXPECT_EQ(checker.max_delta(), max_delta_to_set);\n}\n\n// Setter should throw if provided a negative value\nTEST_F(SingleMomentCheckerL1NormTest, SetterBadValue) {\n  const double max_delta_to_set{ test_helpers::RandomDouble(-1e-8, -1e-16) };\n  EXPECT_EQ(checker.max_delta(), this->max_delta);\n  EXPECT_ANY_THROW({checker.SetMaxDelta(max_delta_to_set);});\n}\n\n// The same vector should return true\nTEST_F(SingleMomentCheckerL1NormTest, SameVector) {\n  EXPECT_TRUE(checker.IsConverged(moment_one, moment_one));\n  EXPECT_TRUE(checker.is_converged());\n}\n\n// Being slightly less than one max delta away should return true\nTEST_F(SingleMomentCheckerL1NormTest, OneThresholdAway) {\n  double to_add = moment_one.l1_norm() * 0.99 * checker.max_delta();\n  moment_two(2) += to_add;\n\n  EXPECT_TRUE(checker.IsConverged(moment_one, moment_two));\n  EXPECT_TRUE(checker.IsConverged(moment_two, moment_one));\n  EXPECT_TRUE(checker.is_converged());\n  EXPECT_NEAR(0.99 * checker.max_delta(), checker.delta().value(), 1e-6);\n}\n\n// Being greater than max delta away should return false\nTEST_F(SingleMomentCheckerL1NormTest, TwoThresholdAway) {\n  const double to_add = moment_one.l1_norm() * 2 * checker.max_delta();\n  moment_two(2) += to_add;\n\n  EXPECT_FALSE(checker.IsConverged(moment_one, moment_two));\n  EXPECT_FALSE(checker.IsConverged(moment_two, moment_one));\n  EXPECT_FALSE(checker.is_converged());\n  EXPECT_NEAR(2 * checker.max_delta(), checker.delta().value(), 1e-6);\n}\n\n// Setting new max delta should still work for convergence\nTEST_F(SingleMomentCheckerL1NormTest, SetMaxDelta) {\n  const double to_set{ 1e-5 };\n  checker.SetMaxDelta(to_set);\n  EXPECT_EQ(checker.max_delta(), to_set);\n\n  const double to_add = moment_one.l1_norm() * 0.99 * to_set;\n  moment_two(2) += to_add;\n\n  EXPECT_TRUE(checker.IsConverged(moment_one, moment_two));\n  EXPECT_TRUE(checker.IsConverged(moment_two, moment_one));\n}\n\n} // namespace", "meta": {"hexsha": "57e2b5200e2caffd0ddda46bcc28f4560b824c23", "size": 3267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/convergence/moments/tests/convergence_checker_l1_norm_test.cpp", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/convergence/moments/tests/convergence_checker_l1_norm_test.cpp", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/convergence/moments/tests/convergence_checker_l1_norm_test.cpp", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 34.7553191489, "max_line_length": 77, "alphanum_fraction": 0.7597183961, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5416308534332837}}
{"text": "/*\n * Copyright 2015 C. Brett Witherspoon\n */\n\n#define BOOST_TEST_MODULE signum_tests\n#include <boost/test/unit_test.hpp>\n\n#include <cmath>\n#include <cstdint>\n#include <limits>\n#include <type_traits>\n\n#include \"signum/utility/fixed.hpp\"\n\nnamespace\n{\ntemplate<typename Float, typename Fixed>\nvoid _fixed_to_float_test()\n{\n  using signum::utility::fixed_to_float;\n\n  const auto delta = 1.0 / (std::numeric_limits<Fixed>::max() + 1.0);\n\n  const auto fixed_lower  = std::numeric_limits<Fixed>::lowest();\n  const auto float_lower  = (std::is_signed<Fixed>::value) ? -1.0 : 0.0;\n\n  const auto fixed_median = std::numeric_limits<Fixed>::max() / 2;\n  const auto float_median = 0.5 - delta;\n\n  const auto fixed_upper  = std::numeric_limits<Fixed>::max();\n  const auto float_upper  = 1.0 - delta;\n\n  const auto lower  = fixed_to_float<Float, Fixed>(fixed_lower);\n  const auto median = fixed_to_float<Float, Fixed>(fixed_median);\n  const auto upper  = fixed_to_float<Float, Fixed>(fixed_upper);\n\n  BOOST_CHECK_CLOSE(lower,\n                    static_cast<Float>(float_lower),\n                    static_cast<Float>(100.0*delta/float_lower));\n  BOOST_CHECK_CLOSE(median,\n                    static_cast<Float>(float_median),\n                    static_cast<Float>(100.0*delta/float_median));\n  BOOST_CHECK_CLOSE(upper,\n                    static_cast<Float>(float_upper),\n                    static_cast<Float>(100.0*delta/float_upper));\n}\n\ntemplate<typename Fixed, typename Float>\nvoid _float_to_fixed_test()\n{\n  using signum::utility::float_to_fixed;\n\n  const auto delta = 1.0 / (std::numeric_limits<Fixed>::max() + 1.0);\n  const auto epsilon = std::numeric_limits<Float>::epsilon();\n\n  const auto fixed_lower  = std::numeric_limits<Fixed>::lowest();\n  const auto float_lower  = (std::is_signed<Fixed>::value) ? -1.0 : 0.0;\n\n  const auto fixed_median = std::numeric_limits<Fixed>::max() / 2;\n  const auto float_median = 0.5 - epsilon - delta;\n\n  const auto fixed_upper  = std::numeric_limits<Fixed>::max();\n  const auto float_upper  = 1.0 - epsilon - delta;\n\n  const auto lower  = float_to_fixed<Fixed, Float>(float_lower);\n  const auto median = float_to_fixed<Fixed, Float>(float_median);\n  const auto upper  = float_to_fixed<Fixed, Float>(float_upper);\n\n  BOOST_CHECK_EQUAL(lower, fixed_lower);\n  BOOST_CHECK_EQUAL(median, fixed_median);\n  BOOST_CHECK_EQUAL(upper, fixed_upper);\n}\n} // namespace (anonymous)\n\nBOOST_AUTO_TEST_CASE(fixed_to_float_unsigned_single_test)\n{\n  _fixed_to_float_test<float, uint8_t>();\n  _fixed_to_float_test<float, uint16_t>();\n  _fixed_to_float_test<float, uint32_t>();\n  _fixed_to_float_test<float, uint64_t>();\n}\n\nBOOST_AUTO_TEST_CASE(fixed_to_float_signed_single_test)\n{\n  _fixed_to_float_test<float, int8_t>();\n  _fixed_to_float_test<float, int16_t>();\n  _fixed_to_float_test<float, int32_t>();\n  _fixed_to_float_test<float, int64_t>();\n}\n\nBOOST_AUTO_TEST_CASE(fixed_to_float_unsigned_double_test)\n{\n  _fixed_to_float_test<double, uint8_t>();\n  _fixed_to_float_test<double, uint16_t>();\n  _fixed_to_float_test<double, uint32_t>();\n  _fixed_to_float_test<double, uint64_t>();\n}\n\nBOOST_AUTO_TEST_CASE(fixed_to_float_signed_double_test)\n{\n  _fixed_to_float_test<double, int8_t>();\n  _fixed_to_float_test<double, int16_t>();\n  _fixed_to_float_test<double, int32_t>();\n  _fixed_to_float_test<double, int64_t>();\n}\n\nBOOST_AUTO_TEST_CASE(float_to_fixed_unsigned_single_test)\n{\n  _float_to_fixed_test<uint8_t, float>();\n  _float_to_fixed_test<uint16_t, float>();\n}\n\nBOOST_AUTO_TEST_CASE(float_to_fixed_signed_single_test)\n{\n  _float_to_fixed_test<int8_t, float>();\n  _float_to_fixed_test<int16_t, float>();\n}\n\nBOOST_AUTO_TEST_CASE(float_to_fixed_unsigned_double_test)\n{\n  _float_to_fixed_test<uint8_t, double>();\n  _float_to_fixed_test<uint16_t, double>();\n  _float_to_fixed_test<uint32_t, double>();\n}\n\nBOOST_AUTO_TEST_CASE(float_to_fixed_signed_double_test)\n{\n  _float_to_fixed_test<int8_t, double>();\n  _float_to_fixed_test<int16_t, double>();\n  _float_to_fixed_test<int32_t, double>();\n}\n\n", "meta": {"hexsha": "71c3fe905034209ab274afeeaa49ca376d353e1c", "size": 4008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fixed_test.cpp", "max_stars_repo_name": "spoonb/libcomm", "max_stars_repo_head_hexsha": "5638dac889bddb16420d8321067c783438a5deaf", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/fixed_test.cpp", "max_issues_repo_name": "spoonb/libcomm", "max_issues_repo_head_hexsha": "5638dac889bddb16420d8321067c783438a5deaf", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/fixed_test.cpp", "max_forks_repo_name": "spoonb/libcomm", "max_forks_repo_head_hexsha": "5638dac889bddb16420d8321067c783438a5deaf", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1353383459, "max_line_length": 72, "alphanum_fraction": 0.7365269461, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5416308437240993}}
{"text": "#include <armadillo>\n#include <ForwardBackward.hpp>\n#include <HSMM.hpp>\n#include <cmath>\n#include <json.hpp>\n#include <iostream>\n#include <memory>\n#include <vector>\n\nusing namespace arma;\nusing namespace std;\nusing json = nlohmann::json;\n\nnamespace hsmm {\n\n    // TODO: Make sure there is not any bias here.\n    int sampleFromCategorical(rowvec pmf) {\n        rowvec prefixsum(pmf);\n        for(int i = 1; i < pmf.n_elem; i++)\n            prefixsum(i) += prefixsum(i - 1);\n        assert(abs(prefixsum(pmf.n_elem - 1) - 1.0) < 1e-7);\n        return lower_bound(prefixsum.begin(), prefixsum.end(), randu()) -\n                prefixsum.begin();\n    }\n\n    /**\n     * HSMM implementation.\n     */\n    HSMM::HSMM(shared_ptr<AbstractEmission> emission, mat transition,\n            vec pi, mat duration, int min_duration) : emission_(emission),\n            duration_learning_choice_(\"histogram\"), debug_(false),\n            learning_transitions_(true), learning_pi_(true) {\n        nstates_ = emission_->getNumberStates();\n        ndurations_ = duration.n_cols;\n        min_duration_ = min_duration;\n        assert(min_duration_ >= 1);\n        assert(nstates_ >= 1);\n        assert(ndurations_ >= 1);\n        setDuration(duration);\n        setPi(pi);\n        setTransition(transition);\n        mat default_dirichlet_parameters = ones<mat>(nstates_, ndurations_);\n        setDurationDirichletPrior(default_dirichlet_parameters);\n    }\n\n    HSMM::HSMM(shared_ptr<AbstractEmission> emission, int nstates, int ndurations,\n            int min_duration) : HSMM(emission,\n            ones<mat>(nstates, nstates) * (1.0/nstates),\n            ones<vec>(nstates) * (1.0/nstates),\n            ones<mat>(nstates, ndurations) * (1.0/ndurations), min_duration)\n    {}\n\n    void HSMM::setDuration(mat duration) {\n        assert(duration.n_rows == nstates_);\n        assert(duration.n_cols == ndurations_);\n        duration_ = duration;\n    }\n\n    void HSMM::setEmission(shared_ptr<AbstractEmission> emission) {\n        assert(emission->getNumberStates() == nstates_);\n        emission_ = emission;\n    }\n\n    void HSMM::setPi(vec pi) {\n        assert(pi.n_elem == nstates_);\n        pi_ = pi;\n    }\n\n    void HSMM::setTransition(mat transition) {\n        assert(transition.n_rows == transition.n_cols);\n        assert(transition.n_rows == nstates_);\n        transition_ = transition;\n    }\n\n    void HSMM::setPiFromLabels(field<ivec> seqs) {\n        vec new_pi(nstates_, fill::zeros);\n        for(auto& s: seqs)\n            new_pi(s(0))++;\n        new_pi = new_pi / accu(new_pi);\n        setPi(new_pi);\n    }\n\n    void HSMM::setTransitionFromLabels(field<ivec> seqs) {\n        mat new_transition(nstates_, nstates_, fill::zeros);\n        for(auto& s: seqs) {\n            const ivec& hs = computeViterbiStateDurationSequenceFromLabels(\n                    s).first;\n            for(int i = 0; i < hs.n_elem - 1; i++)\n                new_transition(hs(i), hs(i + 1))++;\n        }\n        for(int i = 0; i < nstates_; i++) {\n            auto row = new_transition.row(i);\n            new_transition.row(i) = row / accu(row);\n        }\n        setTransition(new_transition);\n    }\n\n    void HSMM::setDurationFromLabels(field<ivec> seqs) {\n        mat new_duration(nstates_, ndurations_, fill::zeros);\n        for(auto& s: seqs) {\n            pair<ivec,ivec> p = computeViterbiStateDurationSequenceFromLabels(\n                    s);\n            const ivec& hs = p.first;\n            const ivec& dur = p.second;\n            for(int i = 0; i < dur.n_elem; i++) {\n                if (hs(i)<nstates_ && dur(i)<=min_duration_ + ndurations_)\n                    new_duration(hs(i), dur(i) - min_duration_)++;\n                else\n                    cout << \"There is an invalid (hs,d) entry\" << endl;\n            }\n        }\n\n        // Taking into account the Dirichlet prior.\n        for(int i = 0; i < nstates_; i++)\n            for(int j = 0; j < ndurations_; j++)\n                new_duration(i, j) += dirichlet_alphas_(i, j) - 1;\n\n        for(int i = 0; i < nstates_; i++) {\n            auto row = new_duration.row(i);\n            new_duration.row(i) = row / accu(row);\n        }\n\n        setDuration(new_duration);\n    }\n\n    void HSMM::setDurationDirichletPrior(mat alphas) {\n        assert(alphas.n_rows == nstates_);\n        assert(alphas.n_cols == ndurations_);\n        for(auto alpha: alphas)\n            assert(alpha > 1.0 - 1e-7);\n        dirichlet_alphas_ = alphas;\n    }\n\n    void HSMM::setDurationLearningChoice(string choice) {\n        duration_learning_choice_ = choice;\n    }\n\n    field<mat> HSMM::sampleSegments(int nsegments, ivec& hiddenStates,\n            ivec& hiddenDurations) {\n        assert(nsegments >= 1);\n\n        // Generating states sequence.\n        ivec states(nsegments);\n        states(0) = sampleFromCategorical(pi_.t());\n        for(int i = 1; i < nsegments; i++) {\n            rowvec nstateDist = transition_.row(states(i - 1));\n            states(i) = sampleFromCategorical(nstateDist);\n        }\n\n        // Generating durations from states.\n        int sampleSequenceLength = 0;\n        ivec durations(nsegments);\n        for(int i = 0; i < nsegments; i++) {\n            int currentDuration = sampleFromCategorical(\n                    duration_.row(states(i))) + min_duration_;\n            durations(i) = currentDuration;\n            sampleSequenceLength += currentDuration;\n        }\n\n        // Generating samples\n        field<mat> samples(sampleSequenceLength);\n        int idx = 0;\n        for(int i = 0; i < nsegments; i++) {\n            field<mat> currSample = emission_->sampleFromState(\n                    states(i), durations(i));\n            samples.rows(idx, idx + durations(i) - 1) = currSample;\n            idx += durations(i);\n        }\n        hiddenStates = states;\n        hiddenDurations = durations;\n        return samples;\n    }\n\n    field<field<mat>> HSMM::sampleMultipleSequences(int nsequences,\n            int nsegments, field<ivec>& seqsHiddenStates,\n            field<ivec>& seqsHiddenDurations) {\n        field<field<mat>> mobs(nsequences);\n        field<ivec> seqsHS(nsequences);\n        field<ivec> seqsDur(nsequences);\n        for(int s = 0; s < nsequences; s++) {\n            ivec hs, dur;\n            mobs(s) = sampleSegments(nsegments, hs, dur);\n            seqsHS(s) = hs;\n            seqsDur(s) = dur;\n        }\n        seqsHiddenStates = seqsHS;\n        seqsHiddenDurations = seqsDur;\n        return mobs;\n    }\n\n    void HSMM::init_params_from_data(const field<field<mat>> &mobs) {\n        emission_->init_params_from_data(min_duration_, ndurations_, mobs);\n    }\n\n    bool HSMM::fit(field<field<mat>> mobs, field<Labels> mobserved_segments,\n            int max_iter, double tol) {\n\n        // Array initializations.\n        int nseq = mobs.n_elem;\n        assert(nseq >= 1 && nseq == mobserved_segments.n_elem);\n        field<mat> malpha(nseq);\n        field<mat> mbeta(nseq);\n        field<mat> malpha_s(nseq);\n        field<mat> mbeta_s(nseq);\n        field<vec> mbeta_s_0(nseq);\n        field<cube> meta(nseq);\n        field<cube> mzeta(nseq);\n        for(int i = 0; i < nseq; i++) {\n            int nobs = mobs(i).n_elem;\n            assert(nobs >= min_duration_);\n            malpha(i) = zeros<mat>(nstates_, nobs);\n            mbeta(i) = zeros<mat>(nstates_, nobs);\n            malpha_s(i) = zeros<mat>(nstates_, nobs);\n            mbeta_s(i) = zeros<mat>(nstates_, nobs);\n            mbeta_s_0(i) = zeros<vec>(nstates_);\n            meta(i) = zeros<cube>(nstates_, ndurations_, nobs);\n            mzeta(i) = zeros<cube>(nstates_, nstates_, nobs - 1);\n        }\n\n        mat log_estimated_transition = log(transition_);\n        vec log_estimated_pi = log(pi_);\n        mat log_estimated_duration = log(duration_);\n        double marginal_llikelihood = -datum::inf;\n        bool convergence_reached = false;\n        for(int i = 0; i < max_iter && !convergence_reached; i++) {\n            for(int s = 0; s < nseq; s++) {\n                const field<mat>& obs = mobs(s);\n                const Labels& observed_segments = mobserved_segments(s);\n\n                // Assertions if labels are provided.\n                if (!observed_segments.empty()) {\n                    for(const auto &segment : observed_segments.getLabels())\n                        assert(segment.getDuration() >= min_duration_ &&\n                                segment.getDuration() < min_duration_ +\n                                ndurations_);\n                    int start_time = observed_segments.getFirstSegment(\n                            ).getStartingTime();\n                    int end_time = observed_segments.getLastSegment(\n                            ).getEndingTime();\n                    if (start_time > 0)\n                        assert(start_time >= min_duration_);\n                    if (end_time < obs.n_elem - 1)\n                        assert(obs.n_elem - end_time > min_duration_);\n                }\n\n                mat& alpha = malpha(s);\n                mat& beta = mbeta(s);\n                mat& alpha_s = malpha_s(s);\n                mat& beta_s = mbeta_s(s);\n                vec& beta_s_0 = mbeta_s_0(s);\n                cube& eta = meta(s);\n                cube& zeta = mzeta(s);\n\n                // Recomputing the emission likelihoods.\n                cube logpdf = computeEmissionsLogLikelihood(obs);\n\n                logsFB(log_estimated_transition, log_estimated_pi,\n                        log_estimated_duration, logpdf, observed_segments,\n                        alpha, beta, alpha_s, beta_s, beta_s_0, eta, zeta,\n                        min_duration_, obs.n_elem);\n            }\n            vec sequences_llikelihood(nseq);\n            for(int s = 0; s < nseq; s++) {\n                int nobs = mobs(s).n_elem;\n\n                // Computing the marginal likelihood (aka observation\n                // likelihood).\n                sequences_llikelihood(s) = logsumexp(malpha(s).col(nobs - 1));\n            }\n            double current_llikelihood = sum(sequences_llikelihood);\n            cout << \"EM iteration \" << i << \" marginal log-likelihood: \" <<\n                    current_llikelihood << \". Diff: \" <<\n                    current_llikelihood - marginal_llikelihood << endl;\n            if (current_llikelihood < marginal_llikelihood)\n                cout << \"Warning: The log-likelihood decreased probably due\" <<\n                        \" to numerical errors.\" << endl;\n            if (current_llikelihood - marginal_llikelihood < tol) {\n                convergence_reached = true;\n                marginal_llikelihood = current_llikelihood;\n                break;\n            }\n            marginal_llikelihood = current_llikelihood;\n\n            // M step.\n            // Lower bound before M step.\n            double lb_pi, lb_transition, lb_duration;\n            if (debug_) {\n                lb_pi = lower_bound_term_pi(meta, log_estimated_pi);\n                lb_transition = lower_bound_term_transition(mzeta,\n                        log_estimated_transition);\n                lb_duration = lower_bound_term_duration(meta,\n                        log_estimated_duration);\n            }\n\n            mat tmp_transition(log_estimated_transition);\n            for(int i = 0; i < nstates_; i++) {\n                vector<double> den;\n                for(int j = 0; j < nstates_; j++) {\n                    vector<double> num;\n                    for(int s = 0; s < nseq; s++) {\n                        const cube& zeta = mzeta(s);\n                        for(int t = 0; t < mobs(s).n_elem - 1; t++) {\n                            num.push_back(zeta(i, j, t));\n                            den.push_back(zeta(i, j, t));\n                        }\n                    }\n                    vec num_v(num);\n                    if (num_v.n_elem > 0)\n                        tmp_transition(i, j) = logsumexp(num_v);\n                }\n                vec den_v(den);\n                if (den_v.n_elem > 0) {\n                    double denominator = logsumexp(den_v);\n\n                    // Handling the case when the transition probability is 0.\n                    if (denominator != -datum::inf) {\n                        for(int j = 0; j < nstates_; j++)\n                            tmp_transition(i, j) -= denominator;\n                    }\n                }\n            }\n            if (learning_transitions_)\n                log_estimated_transition = tmp_transition;\n\n            // Reestimating the initial state pmf.\n            vec tmp_pi(size(pi_), fill::zeros);\n            for(const cube& eta : meta) {\n                vec current_log_estimated_pi(nstates_);\n                for(int i = 0; i < nstates_; i++) {\n                    vector<double> terms;\n                    for(int d = 0; d < ndurations_; d++)\n                        terms.push_back(eta(i, d, min_duration_ + d - 1));\n                    vec vterms(terms);\n                    current_log_estimated_pi(i) = logsumexp(vterms);\n                }\n                vec current_pi = exp(current_log_estimated_pi);\n                assert(abs(sum(current_pi) - 1) < 1e-7);\n                tmp_pi += current_pi;\n            }\n            if (learning_pi_)\n                log_estimated_pi = log(tmp_pi / nseq);\n\n            // Reestimating durations.\n            // D(j, d) represents the expected number of times that state\n            // j is visited with duration d (non-normalized).\n            mat D(size(duration_), fill::zeros);\n            for(int i = 0; i < nstates_; i++) {\n                vector<double> den;\n                for(int d = 0; d < ndurations_; d++) {\n                    vector<double> ts;\n                    for(int s = 0; s < nseq; s++) {\n                        int nobs = mobs(s).n_rows;\n                        const cube& eta = meta(s);\n                        for(int t = 0; t < nobs; t++) {\n                            ts.push_back(eta(i, d, t));\n                            den.push_back(eta(i, d, t));\n                        }\n                    }\n\n                    // Taking into account the Dirichlet prior.\n                    double log_alpha_minus_one = log(dirichlet_alphas_(\n                                i, d) - 1);\n                    ts.push_back(log_alpha_minus_one);\n                    den.push_back(log_alpha_minus_one);\n\n                    vec ts_v(ts);\n                    D(i, d) = logsumexp(ts_v);\n                }\n                vec den_v(den);\n                double denominator = logsumexp(den_v);\n\n                // Handling the case when the transition probability mass is 0.\n                if (denominator != -datum::inf) {\n                    for(int d = 0; d < ndurations_; d++)\n                        D(i, d) -= denominator;\n                }\n            }\n            if (!duration_learning_choice_.compare(\"histogram\"))\n                log_estimated_duration = D;\n            else if (!duration_learning_choice_.compare(\"momentmatching\"))\n                log_estimated_duration = gaussianMomentMatching(D);\n            else if (duration_learning_choice_.compare(\"nodur\")) {\n                cout << \"Duration learning not supported or invalid.\" << endl;\n                assert(false);\n            }\n\n            // Lower bound after M step.\n            if (debug_) {\n                double lb_pi_after = lower_bound_term_pi(meta, log_estimated_pi);\n                double lb_transition_after = lower_bound_term_transition(mzeta,\n                        log_estimated_transition);\n                double lb_duration_after = lower_bound_term_duration(meta,\n                        log_estimated_duration);\n                cout << \"Diff lower bound before and after M step\" << endl;\n                cout << \"pi: \" << lb_pi_after - lb_pi << endl;\n                cout << \"transition: \" << lb_transition_after - lb_transition << endl;\n                cout << \"duration: \" << lb_duration_after - lb_duration << endl;\n                assert(lb_pi_after - lb_pi > -tol);\n                assert(lb_transition_after - lb_transition > -tol);\n                assert(lb_duration_after - lb_duration > -tol);\n            }\n\n            // Reestimating emissions.\n            // NOTE: the rest of the HSMM parameters are updated out of\n            // this loop.\n            emission_->reestimate(min_duration_, meta, mobs);\n        }\n\n        cout << \"Stopped because of \" << ((convergence_reached) ?\n                \"convergence.\" : \"max iter.\") << endl;\n\n       // Updating the model parameters.\n       setTransition(exp(log_estimated_transition));\n       setPi(exp(log_estimated_pi));\n       setDuration(exp(log_estimated_duration));\n       return convergence_reached;\n    }\n\n    bool HSMM::fit(field<field<mat>> mobs, int max_iter, double tol) {\n        field<Labels> mobserved_segments(mobs.n_elem);  // empty.\n        return fit(mobs, mobserved_segments, max_iter, tol);\n    }\n\n    double HSMM::loglikelihood(const field<field<mat>>& mobs) {\n        field<Labels> no_labels(mobs.n_elem);  // empty.\n        return loglikelihood(mobs, no_labels);\n    }\n\n    // TODO: make this a const function.\n    double HSMM::loglikelihood(const field<field<mat>>& mobs,\n            const field<Labels>& labels) {\n        int nseq = mobs.n_elem;\n        assert(nseq >= 1);\n        double ll = 0.0;\n        for(int i = 0; i < nseq; i++) {\n            const field<mat>& obs = mobs(i);\n            int nobs = obs.n_elem;\n            mat alpha =  zeros<mat>(nstates_, nobs);\n            mat beta = zeros<mat>(nstates_, nobs);\n            mat alpha_s = zeros<mat>(nstates_, nobs);\n            mat beta_s = zeros<mat>(nstates_, nobs);\n            vec beta_s_0 =  zeros<vec>(nstates_);\n            cube eta = zeros<cube>(nstates_, ndurations_, nobs);\n            cube zeta = zeros<cube>(nstates_, nstates_, nobs - 1);\n            cube logpdf = computeEmissionsLogLikelihood(obs);\n            mat ltransition = log(transition_);\n            vec lpi = log(pi_);\n            mat ldur = log(duration_);\n            logsFB(ltransition, lpi, ldur, logpdf, labels(i), alpha, beta,\n                    alpha_s, beta_s, beta_s_0, eta, zeta, min_duration_, nobs);\n            ll += logsumexp(alpha.col(nobs - 1));\n        }\n        return ll;\n    }\n\n    // Computes the likelihoods w.r.t. the emission model.\n    cube HSMM::computeEmissionsLikelihood(const field<mat>& obs) {\n        return emission_->likelihoodCube(min_duration_, ndurations_, obs);\n    }\n\n    // Computes the loglikelihoods w.r.t. the emission model.\n    cube HSMM::computeEmissionsLogLikelihood(const field<mat>& obs) {\n        return emission_->loglikelihoodCube(min_duration_, ndurations_,\n            obs);\n    }\n\n    // Returns a json representation of the model.\n    nlohmann::json HSMM::to_stream() const {\n        nlohmann::json ret;\n        ret[\"nstates\"] = nstates_;\n        ret[\"min_duration\"] = min_duration_;\n        ret[\"ndurations\"] = ndurations_;\n        ret[\"initial_pmf\"] = pi_;\n        ret[\"emission_params\"] = emission_->to_stream();\n\n        // Taking care of the serialization of armadillo matrices.\n        vector<vector<double>> transition_v, duration_v;\n        for(int i = 0; i < nstates_; i++) {\n            transition_v.push_back(conv_to<vector<double>>::from(\n                    transition_.row(i)));\n            duration_v.push_back(conv_to<vector<double>>::from(\n                    duration_.row(i)));\n        }\n        ret[\"transition\"] = transition_v;\n        ret[\"duration\"] = duration_v;\n        return ret;\n    }\n\n    // Reads the parameters from a json file.\n    void HSMM::from_stream(const nlohmann::json &params) {\n        nstates_ = params.at(\"nstates\");\n        min_duration_ = params.at(\"min_duration\");\n        ndurations_ = params.at(\"ndurations\");\n        const nlohmann::json& emission_params = params.at(\"emission_params\");\n        emission_->from_stream(emission_params);\n\n        // Parsing the armadillo matrices (transition, pi, duration).\n        vector<double> initial_pmf_v = params.at(\"initial_pmf\");\n        vector<vector<double>> transition_v = params.at(\"transition\");\n        vector<vector<double>> duration_v = params.at(\"duration\");\n        vec pi = conv_to<vec>::from(initial_pmf_v);\n        mat transition = zeros<mat>(nstates_, nstates_);\n        mat duration = zeros<mat>(nstates_, ndurations_);\n        for(int i = 0; i < nstates_; i++) {\n            transition.row(i) = conv_to<rowvec>::from(transition_v.at(i));\n            duration.row(i) = conv_to<rowvec>::from(duration_v.at(i));\n        }\n        setPi(pi);\n        setTransition(transition);\n        setDuration(duration);\n    }\n\n    pair<ivec,ivec> HSMM::computeViterbiStateDurationSequenceFromLabels(\n            ivec seq) {\n        assert(seq.n_elem > 0);\n        int last_state = seq(0);\n        int current_dur = 1;\n        vector<int> hs, dur;\n        for(int i = 1; i < seq.n_elem; i++) {\n            if (seq(i) == last_state)\n                current_dur++;\n            else {\n                hs.push_back(last_state);\n                dur.push_back(current_dur);\n                last_state = seq(i);\n                current_dur = 1;\n            }\n        }\n        hs.push_back(last_state);\n        dur.push_back(current_dur);\n        ivec hs_v = conv_to<ivec>::from(hs);\n        ivec dur_v = conv_to<ivec>::from(dur);\n        return make_pair(hs_v, dur_v);\n    }\n\n    mat HSMM::gaussianMomentMatching(mat duration) const {\n        duration = exp(duration);\n        mat ret = zeros(size(duration));\n        for(int i = 0; i < duration.n_rows; i++) {\n            double mean = 0;\n            for(int j = 0; j < duration.n_cols; j++)\n                mean += j * duration(i, j);\n            double var = 0;\n            for(int j = 0; j < duration.n_cols; j++)\n                var += (j - mean) * (j - mean) * duration(i, j);\n            for(int j = 0; j < duration.n_cols; j++) {\n                double tmp = (j - mean);\n                tmp = (tmp * tmp) / var;\n                tmp = -0.5 * tmp;\n                tmp = exp(tmp);\n                ret(i, j) = tmp;\n            }\n\n            // Renormalizing.\n            ret.row(i) = ret.row(i) / sum(ret.row(i));\n        }\n        return log(ret);\n    }\n\n    // Debugging functions.\n    double HSMM::lower_bound_term_transition(const field<cube>& zetas,\n            const mat& log_transition) const {\n        double ret = 0;\n        for(const cube& zeta : zetas)\n            for(int i = 0; i < nstates_; i++)\n                for(int j = 0; j < nstates_; j++)\n                    for(int t = 0; t < zeta.n_slices; t++)\n                        if (log_transition(i, j) > -datum::inf)\n                            ret += exp(zeta(i, j, t)) * log_transition(i, j);\n       return ret;\n    }\n\n    double HSMM::lower_bound_term_pi(const field<cube>& etas,\n            const vec& log_pi) const {\n        double ret = 0;\n        for(const cube& eta : etas)\n            for(int i = 0; i < nstates_; i++)\n                for(int d = 0; d < ndurations_; d++)\n                    if (log_pi(i) > -datum::inf)\n                        ret += exp(eta(i, d, min_duration_ + d - 1)) *\n                            log_pi(i);\n        return ret;\n    }\n\n    double HSMM::lower_bound_term_duration(const field<cube>& etas,\n            const mat& log_duration) const {\n        double ret = 0;\n        for(const cube& eta : etas)\n            for(int i = 0; i < nstates_; i++)\n                for(int d = 0; d < ndurations_; d++)\n                    for(int t = 0; t < eta.n_slices; t++)\n                        if (log_duration(i, d) > -datum::inf)\n                            ret += exp(eta(i, d, t)) * log_duration(i, d);\n        return ret;\n    }\n\n\n    /*\n     * Online HSMM implementation\n     */\n    OnlineHSMM::OnlineHSMM(shared_ptr<AbstractEmissionOnlineSetting> emission,\n            mat transition, vec pi, mat duration, int min_duration) : HSMM(\n            static_pointer_cast<AbstractEmission>(emission), transition,\n            pi, duration, min_duration),\n            last_log_posterior_(ndurations_, min_duration_ + ndurations_,\n            nstates_) {}\n\n    shared_ptr<AbstractEmissionOnlineSetting> OnlineHSMM::getOnlineEmission(\n            ) const {\n        return static_pointer_cast<AbstractEmissionOnlineSetting>(emission_);\n    }\n\n    void OnlineHSMM::addNewObservation(const mat& obs) {\n        if (observations_.empty())\n             alpha_posteriors_.push_back(log(pi_));\n        observations_.push_back(obs);\n        mat log_duration = log(duration_);\n        mat log_transition = log(transition_);\n        last_log_posterior_.fill(-datum::inf);\n        vector<double> normalization_terms;\n        for(int d = min_duration_; d < min_duration_ + ndurations_; d++) {\n            for(int s = 0; s < d; s++) {\n\n                // Making sure the offset is consistent with the number of\n                // observations so far.\n                if (s >= observations_.size())\n                    break;\n\n                // Building the current segment. Notice that it is padded with\n                // empty matrices.\n                field<mat> current_segment(d);\n                for(int idx = s, obs_idx = observations_.size()-1; idx >= 0;\n                        idx--, obs_idx--) {\n                    current_segment(idx) = observations_[obs_idx];\n                }\n                const vec& relevant_alpha_posterior = alpha_posteriors_.at(\n                        alpha_posteriors_.size() - 1 - s);\n                for(int i = 0; i < nstates_; i++) {\n                    double log_pdf_seg = emission_->loglikelihood(i,\n                            current_segment) + log_duration(i,d-min_duration_);\n                    double log_unnormalized_value = log_pdf_seg +\n                            relevant_alpha_posterior(i);\n                    last_log_posterior_(d - min_duration_, s, i) =\n                            log_unnormalized_value;\n                    normalization_terms.push_back(log_unnormalized_value);\n                }\n            }\n        }\n\n        // Normalizing the current joint posterior.\n        last_normalization_c_ = logsumexp(normalization_terms);\n        assert(last_normalization_c_ > -datum::inf);\n        last_log_posterior_ -= last_normalization_c_;\n\n        // Computing the marginal posterior over the next hidden state assuming\n        // there is a change point right after the current input observation.\n        vec current_marginal_posterior(nstates_);\n        for(int i = 0; i < nstates_; i++) {\n            vector<double> terms;\n            for(int j = 0; j < nstates_; j++) {\n                for(int dur = 0; dur < ndurations_; dur++) {\n                    double term = last_log_posterior_(dur,\n                            min_duration_ + dur - 1, j) + log_transition(j, i);\n                    terms.push_back(term);\n                }\n            }\n            current_marginal_posterior(i) = logsumexp(terms);\n        }\n\n        // Pushing back the computed posterior. NOTE: it isn't a pmf.\n        alpha_posteriors_.push_back(current_marginal_posterior);\n    }\n\n    void OnlineHSMM::sampleFromPosterior(int & dur, int & offset,\n            int & hs) const {\n        dur = offset = hs = -1;\n        cube current_posterior = exp(last_log_posterior_);\n        int nrows = current_posterior.n_rows;\n        int ncols = current_posterior.n_cols;\n        int nslices = current_posterior.n_slices;\n        double accum = 0.0;\n        double usample = randu();\n        int found = 0;\n        mat sample;\n        for(int i = 0; i < nslices; i++) {\n            for(int d = 0; d < nrows; d++) {\n                for(int s = 0; s < ncols; s++) {\n                    double naccum = accum + current_posterior(d, s, i);\n                    if (accum < usample && usample < naccum) {\n                        found++;\n                        dur = d;\n                        offset = s;\n                        hs = i;\n                    }\n                    accum = naccum;\n                }\n            }\n        }\n        assert(found == 1);\n        assert(abs(accum - 1.0) < 1e-7);\n        return;\n    }\n\n    field<mat> OnlineHSMM::sampleNextObservations(int nobs) const {\n        assert(!observations_.empty());  // TODO: handle empty observations.\n\n        // Sampling a triplet (d,s,i) from the current posterior.\n        int d, s, i;\n        sampleFromPosterior(d, s, i);\n        if (debug_) {\n            cout << \"Posterior sample (\" << d << \", \" << s << \", \" <<\n                    i << \")\" << endl;\n        }\n        field<mat> last_obs(s + 1);\n        int tam = observations_.size();\n        for(int j = s, idx = tam - 1; j >= 0; j--, idx--)\n            last_obs(j) = observations_.at(idx);\n        field<mat> ret(nobs);\n        int idx = 0;\n        field<mat> seg;\n        int curr_state;\n        if (s == min_duration_ + d - 1) {\n\n            // Handling the case when there is a transition\n            // right after the current observation. Sampling\n            // next state and duration.\n            int next_state = sampleFromCategorical(\n                    transition_.row(i));\n            int next_duration = sampleFromCategorical(\n                    duration_.row(next_state)) + min_duration_;\n            seg = getOnlineEmission()->sampleFirstSegmentObsGivenLastSegment(\n                    next_state, next_duration, last_obs, i);\n            curr_state = next_state;\n            for(int j = 0; j < seg.n_elem && idx < ret.n_elem; j++)\n                ret(idx++) = seg(j);\n        }\n        else {\n            seg = getOnlineEmission()->sampleNextObsGivenPastObs(i,\n                    min_duration_ + d, last_obs);\n            curr_state = i;\n            field<mat> suffix = seg.rows(last_obs.n_elem, seg.n_elem - 1);\n            idx = appendToField(ret, idx, suffix);\n        }\n\n        while(idx < ret.n_elem) {\n             int next_state = sampleFromCategorical(transition_.row(\n                         curr_state));\n             int next_duration =  sampleFromCategorical(duration_.row(\n                         next_state)) + min_duration_;\n             if (debug_) {\n                cout << \"Next state and dur: \" << next_state << \" \" <<\n                        next_duration << endl;\n             }\n             seg = getOnlineEmission()->sampleFirstSegmentObsGivenLastSegment(\n                     next_state, next_duration, seg, curr_state);\n             curr_state = next_state;\n             idx = appendToField(ret, idx, seg);\n        }\n        assert(idx == nobs);\n        return ret;\n    }\n\n    void OnlineHSMM::printTopKFromPosterior(int k) const {\n        cube current_posterior = exp(last_log_posterior_);\n        set<pair<double,string>> pq;\n        for(int d = 0; d < ndurations_; d++)\n            for(int s = 0; s < min_duration_ + d; s++)\n                for(int i = 0; i < nstates_; i++) {\n                    double p = current_posterior(d, s, i);\n                    string str = \"(\" + to_string(d) + \", \" + to_string(s) +\n                            \", \" + to_string(i) + \")\";\n                    pq.insert(make_pair(p, str));\n                    if (pq.size() > k)\n                        pq.erase(pq.begin());\n                }\n        for(auto p: pq)\n            cout << p.first << \" \" << p.second << endl;\n    }\n\n    vec OnlineHSMM::getStateMarginal() const {\n        cube current_posterior = exp(last_log_posterior_);\n        mat tmp = sum(current_posterior, 0);\n        vec ret = vectorise(sum(tmp, 0));\n        assert(abs(sum(ret) - 1.0) < 1e-7);\n        assert(ret.n_elem == nstates_);\n        return ret;\n    }\n\n    // TODO: the output len shoud be actually min_duration_ + ndurations_ - 1.\n    vec OnlineHSMM::getRunlengthMarginal() const {\n        cube current_posterior = exp(last_log_posterior_);\n        mat tmp = sum(current_posterior, 0);\n        vec ret = vectorise(sum(tmp, 1));\n        assert(abs(sum(ret) - 1.0) < 1e-7);\n        assert(ret.n_elem == min_duration_ + ndurations_);\n        return ret;\n    }\n\n    vec OnlineHSMM::getDurationMarginal() const {\n        cube current_posterior = exp(last_log_posterior_);\n        mat tmp = sum(current_posterior, 2);\n        vec ret = vectorise(sum(tmp, 1));\n        assert(abs(sum(ret) - 1.0) < 1e-7);\n        assert(ret.n_elem == ndurations_);\n        return ret;\n    }\n\n    vec OnlineHSMM::getResidualTimeMarginal() const {\n        cube current_posterior = exp(last_log_posterior_);\n        mat tmp = sum(current_posterior, 2);\n        vec ret(min_duration_ + ndurations_, fill::zeros);\n        for(int d = 0; d < ndurations_; d++) {\n            for(int r = 0; r < min_duration_ + ndurations_; r++) {\n                if (r < min_duration_ + d) {\n                    int residual_time = min_duration_ + d - r - 1;\n                    ret(residual_time) += tmp(d, r);\n                }\n            }\n        }\n        assert(abs(sum(ret) - 1.0) < 1e-7);\n        return ret;\n    }\n\n    vec OnlineHSMM::getImplicitDurationMarginal() const {\n        cube current_posterior = exp(last_log_posterior_);\n        mat runlength_state_posterior = sum(current_posterior, 0);\n\n        vec ret(ndurations_, fill::zeros);\n        mat dur_suffix_sum = getDurationSuffixSum();\n        for(int i = 0; i < nstates_; i++) {\n            for(int r = 0; r < min_duration_ + ndurations_; r++) {\n                for(int d = 0; d < ndurations_; d++) {\n                    if (r < min_duration_ + d) {\n                        double value = runlength_state_posterior(r, i) *\n                                duration_(i, d) /\n                                dur_suffix_sum(i, max(0,r - min_duration_+ 1));\n                        ret(d) += value;\n                    }\n                }\n            }\n        }\n        assert(abs(sum(ret) - 1.0) < 1e-7);\n        return ret;\n    }\n\n    vec OnlineHSMM::getImplicitResidualTimeMarginal() const {\n        cube current_posterior = exp(last_log_posterior_);\n        mat duration_runlength_posterior = sum(current_posterior, 2);\n        vec ret(min_duration_ + ndurations_, fill::zeros);\n        for(int r = 0; r < min_duration_ + ndurations_; r++) {\n            for(int d = 0; d < ndurations_; d++) {\n                int current_dur = min_duration_ + d;\n                if (r < current_dur)\n                    ret(current_dur-r-1) += duration_runlength_posterior(d,r);\n            }\n        }\n        assert(abs(sum(ret) - 1.0) < 1e-7);\n        return ret;\n    }\n\n    double OnlineHSMM::getLastOneStepAheadLoglikelihood() const {\n        assert(observations_.size() > 0);\n        return last_normalization_c_;\n    }\n\n    // TODO: This could be cached.\n    mat OnlineHSMM::getDurationSuffixSum() const {\n        mat suffix_sum(duration_);\n        for(int i = suffix_sum.n_cols - 2; i >= 0; i--)\n            suffix_sum.col(i) += suffix_sum.col(i + 1);\n        return suffix_sum;\n    }\n\n    int OnlineHSMM::appendToField(field<mat> &current_obs, int idx,\n            const field<mat> new_obs) const {\n        for(int j = 0; j < new_obs.n_elem && idx < current_obs.n_elem; j++)\n            current_obs(idx++) = new_obs(j);\n        return idx;\n    }\n\n\n    /*\n     * Online OnlineHSMMRunlengthBased implementation. The emission doesn't\n     * take into account the total segment duration.\n     */\n    OnlineHSMMRunlengthBased::OnlineHSMMRunlengthBased(\n            shared_ptr<AbstractEmissionObsCondIIDgivenState> emission,\n            mat transition, vec pi, mat duration, int min_duration) : HSMM(\n            static_pointer_cast<AbstractEmission>(emission), transition,\n            pi, duration, min_duration),\n            last_posterior_(min_duration + duration.n_cols - 1, pi.n_elem),\n            last_residualtime_posterior_(min_duration + duration.n_cols - 1,\n                    pi.n_elem) {\n        init();\n    }\n\n    OnlineHSMMRunlengthBased::OnlineHSMMRunlengthBased(\n            shared_ptr<AbstractEmissionObsCondIIDgivenState> emission,\n            int nstates, int ndurations, int min_duration) : HSMM(\n            static_pointer_cast<AbstractEmission>(emission), nstates,\n            ndurations, min_duration),\n            last_posterior_(min_duration + ndurations - 1, nstates),\n            last_residualtime_posterior_(min_duration + ndurations - 1,\n                    nstates) {\n        init();\n    }\n\n    void OnlineHSMMRunlengthBased::init() {\n        last_posterior_.zeros();\n        last_residualtime_posterior_.zeros();\n        observations_.clear();\n    }\n\n    shared_ptr<AbstractEmissionObsCondIIDgivenState>\n            OnlineHSMMRunlengthBased::getOnlineDurationAgnosticEmission(\n            ) const {\n        return static_pointer_cast<AbstractEmissionObsCondIIDgivenState>(\n                emission_);\n    }\n\n    void OnlineHSMMRunlengthBased::addNewObservation(const mat& obs) {\n        observations_.push_back(obs);\n        mat new_posterior(size(last_posterior_), fill::zeros);\n        mat new_residualtime_posterior(size(last_residualtime_posterior_),\n                fill::zeros);\n        int max_duration = min_duration_ + ndurations_ - 1;\n        mat hazard = getHazardFunction_();\n        if (observations_.size() == 1) {\n\n            // Base case.\n            for(int i = 0; i < nstates_; i++)\n                new_posterior(0, i) = pi_(i) * exp(loglikelihood_(i, obs));\n\n            // Residential time base case.\n            for(int i = 0; i < nstates_; i++) {\n                double tmp = pi_(i) * exp(loglikelihood_(i, obs));\n                for(int d = 0; d < ndurations_; d++)\n                    new_residualtime_posterior(min_duration_ + d - 1, i) =\n                            tmp * duration_(i, d);\n            }\n        }\n        else {\n\n            // Runlength posterior updates.\n            for(int r = 0; r < max_duration; r++) {\n\n                // Segment transition.\n                for(int i = 0; i < nstates_; i++) {\n                    if (!is_finite(hazard(i, r)))\n                        continue;\n                    for(int j = 0; j < nstates_; j++) {\n                        new_posterior(0, j) += hazard(i, r)*transition_(i, j) *\n                            exp(loglikelihood_(j, obs)) * last_posterior_(r, i);\n                    }\n                }\n\n                // Segment continuation.\n                if (r + 1 < max_duration) {\n                    for(int i = 0; i < nstates_; i++)\n                        if (is_finite(hazard(i, r))) {\n                            new_posterior(r + 1, i) = last_posterior_(r, i) *\n                                    (1 - hazard(i, r)) *\n                                    exp(loglikelihood_(i, obs));\n                        }\n                }\n            }\n\n            // Residualtime posterior updates.\n            // Segment continuation.\n            for(int r = 1; r < max_duration; r++)\n                for(int i = 0; i < nstates_; i++)\n                    new_residualtime_posterior(r - 1, i) = exp(loglikelihood_(\n                            i, obs)) * last_residualtime_posterior_(r, i);\n\n            // Segment transition\n            vec prob_of_transition_to(nstates_, fill::zeros);\n            for(int i = 0; i < nstates_; i++)\n                for(int j = 0; j < nstates_; j++)\n                    prob_of_transition_to(i) += transition_(j, i) *\n                            last_residualtime_posterior_(0, j);\n\n            for(int i = 0; i < nstates_; i++)\n                for(int d = 0; d < ndurations_; d++)\n                    new_residualtime_posterior(min_duration_ + d - 1, i) +=\n                            prob_of_transition_to(i) *\n                            exp(loglikelihood_(i, obs)) * duration_(i, d);\n        }\n\n        // Normalizing the current posteriors.\n        new_posterior = new_posterior / accu(new_posterior);\n        new_residualtime_posterior = new_residualtime_posterior /\n                accu(new_residualtime_posterior);\n\n        assert(abs(accu(new_posterior) - 1.0) < 1e-7);\n        assert(abs(accu(new_residualtime_posterior) - 1.0) < 1e-7);\n        last_posterior_ = new_posterior;\n        last_residualtime_posterior_ = new_residualtime_posterior;\n        return;\n    }\n\n    vec OnlineHSMMRunlengthBased::getRunlengthMarginal() const {\n        vec marginal = conv_to<vec>::from(sum(last_posterior_, 1));\n        assert(abs(accu(marginal) - 1.0) < 1e-7);\n        assert(marginal.n_elem == min_duration_ + ndurations_ - 1);\n        return marginal;\n    }\n\n    vec OnlineHSMMRunlengthBased::getStateMarginal() const {\n        vec marginal = conv_to<vec>::from(sum(last_posterior_, 0));\n        assert(abs(accu(marginal) - 1.0) < 1e-7);\n        assert(marginal.n_elem == nstates_);\n        return marginal;\n    }\n\n    vec OnlineHSMMRunlengthBased::getResidualTimeMarginal() const {\n        vec marginal = conv_to<vec>::from(sum(last_residualtime_posterior_,\n                    1));\n        assert(abs(accu(marginal) - 1.0) < 1e-7);\n        assert(marginal.n_elem == min_duration_ + ndurations_ - 1);\n        return marginal;\n    }\n\n    vec OnlineHSMMRunlengthBased::getStateMarginal2() const {\n        vec marginal = conv_to<vec>::from(sum(last_residualtime_posterior_,\n                    0));\n        assert(abs(accu(marginal) - 1.0) < 1e-7);\n        assert(marginal.n_elem == nstates_);\n        return marginal;\n    }\n\n    double OnlineHSMMRunlengthBased::oneStepAheadLoglikelihood(\n            const arma::mat& obs) const {\n        if (observations_.size() == 0) {\n            vec ret(nstates_);\n            for(int i = 0; i < nstates_; i++)\n                ret(i) = loglikelihood_(i, obs) + log(pi_(i));\n            return logsumexp(ret);\n        }\n        int max_duration = min_duration_ + ndurations_ - 1;\n        mat hazard = getHazardFunction_();\n        vector<double> v;\n        for(int r = 0; r < max_duration; r++) {\n\n            // Segment transition.\n            for(int i = 0; i < nstates_; i++)\n                if (is_finite(hazard(i, r)))\n                    for(int j = 0; j < nstates_; j++)\n                        v.push_back(log(last_posterior_(r, i)) + log(\n                                hazard(i, r)) + log(transition_(i, j)) +\n                                loglikelihood_(j, obs));\n\n            // Segment continuation.\n            if (r > 0) {\n                for(int i = 0; i < nstates_; i++)\n                    if (is_finite(hazard(i, r - 1)))\n                        v.push_back(log(last_posterior_(r - 1, i)) +\n                            loglikelihood_(i, obs) + log(1 - hazard(i, r - 1)));\n            }\n        }\n        vec ret = conv_to<vec>::from(v);\n        return logsumexp(ret);\n    }\n\n    double OnlineHSMMRunlengthBased::oneStepAheadLoglikelihood2(\n            const arma::mat& obs) const {\n        if (observations_.size() == 0) {\n            vec ret(nstates_);\n            for(int i = 0; i < nstates_; i++)\n                ret(i) = loglikelihood_(i, obs) + log(pi_(i));\n            return logsumexp(ret);\n        }\n        int max_duration = min_duration_ + ndurations_ - 1;\n        mat hazard = getHazardFunction_();\n        vector<double> v;\n\n        // Segment continuation.\n        for(int r = 1; r < max_duration; r++)\n            for(int i = 0; i < nstates_; i++)\n                v.push_back(log(last_residualtime_posterior_(r, i)) +\n                        loglikelihood_(i, obs));\n\n        // Segment transition. Notice that the next bit is not log scaled.\n        vec prob_of_transition_to(nstates_, fill::zeros);\n        for(int i = 0; i < nstates_; i++)\n            for(int j = 0; j < nstates_; j++)\n                prob_of_transition_to(i) += transition_(j, i) *\n                        last_residualtime_posterior_(0, j);\n        for(int i = 0; i < nstates_; i++)\n            v.push_back(log(prob_of_transition_to(i)) + loglikelihood_(i, obs));\n        vec ret = conv_to<vec>::from(v);\n        return logsumexp(ret);\n    }\n\n    double OnlineHSMMRunlengthBased::loglikelihood_(int state,\n            const mat& obs) const {\n\n        // TODO: assuming for now that the input can be converted into a vec.\n        vec obs_v = conv_to<vec>::from(obs);\n        getOnlineDurationAgnosticEmission()->loglikelihood(state, obs_v);\n    }\n\n    mat OnlineHSMMRunlengthBased::getDurationSuffixSum_() const {\n        mat suffix_sum(duration_);\n        for(int i = suffix_sum.n_cols - 2; i >= 0; i--)\n            suffix_sum.col(i) += suffix_sum.col(i + 1);\n        return suffix_sum;\n    }\n\n    mat OnlineHSMMRunlengthBased::getHazardFunction_() const {\n        mat suffix_sum = getDurationSuffixSum_();\n        mat hazard = duration_ / suffix_sum;\n        if (min_duration_ > 1)\n            hazard = join_horiz(zeros<mat>(nstates_,min_duration_ -1), hazard);\n        assert(hazard.n_rows == nstates_ && hazard.n_cols == min_duration_\n                + ndurations_ - 1);\n        return hazard;\n    }\n\n};\n", "meta": {"hexsha": "b447cf223c9dd0db95f9fee8d22185c4f8770df4", "size": 44693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HSMM.cpp", "max_stars_repo_name": "DiegoAE/BOSD", "max_stars_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-05-03T05:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:14:31.000Z", "max_issues_repo_path": "src/HSMM.cpp", "max_issues_repo_name": "DiegoAE/BOSD", "max_issues_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T15:29:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T10:14:54.000Z", "max_forks_repo_path": "src/HSMM.cpp", "max_forks_repo_name": "DiegoAE/BOSD", "max_forks_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T07:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T07:44:09.000Z", "avg_line_length": 39.9044642857, "max_line_length": 86, "alphanum_fraction": 0.5310898798, "num_tokens": 10493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5414591106922302}}
{"text": "#include <NTL/ZZXFactoring.h>\n\nNTL_CLIENT\n\nlong NumFacs(const vec_pair_ZZX_long& v)\n{\n   long i;\n   long res;\n\n   res = 0;\n   \n   for (i = 0; i < v.length(); i++)\n      res += v[i].b;\n\n   return res;\n}\n\n\nint main()\n{\n   long cnt = 0;\n   while (SkipWhiteSpace(cin)) {\n      cnt++;\n      cerr << \".\";\n\n      vec_ZZ w;\n      ZZX f1, f;\n      long nfacs;\n\n      cin >> w;\n      cin >> nfacs;\n\n      long i, n;\n      n = w.length();\n      f.rep.SetLength(n);\n      for (i = 0; i < n; i++)\n         f.rep[i] = w[n-1-i];\n      f.normalize();\n\n      vec_pair_ZZX_long factors;\n      ZZ c;\n\n      factor(c, factors, f, 0);\n\n\n      mul(f1, factors);\n      mul(f1, f1, c);\n\n      if (f != f1) {\n         cerr << f << \"\\n\";\n         cerr << c << \" \" << factors << \"\\n\";\n         Error(\"FACTORIZATION INCORRECT (1) !!!\");\n      }\n\n      long nfacs1 = NumFacs(factors);\n\n      if (nfacs1 != nfacs)\n         Error(\"FACTORIZATION INCORRECT (2) !!!\");\n   }\n\n\n   cerr << \"\\n\";\n   cerr << \"MoreFacTest OK\\n\";\n\n   return 0;\n}\n", "meta": {"hexsha": "9604c9da601a400b08bc03fc1b82d7b48e40eacf", "size": 1006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/tests/MoreFacTest.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/MoreFacTest.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/MoreFacTest.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": 15.0149253731, "max_line_length": 50, "alphanum_fraction": 0.4522862823, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5414578133145703}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nint main()\n{\n\tEigen::Vector3f acc, acc_result;\n\n\tEigen::Matrix3f rot_x, rot_y, rot_z;\n\trot_x = Eigen::AngleAxisf(0.1, Eigen::Vector3f(1.0, 0.0, 0.0));\n\trot_y = Eigen::AngleAxisf(0.1, Eigen::Vector3f(0.0, 1.0, 0.0));\n\trot_z = Eigen::AngleAxisf(0.1, Eigen::Vector3f(0.0, 0.0, 1.0));\n\n\tacc_result = ( rot_z * (rot_y * (rot_x * acc)));\n\n\tstd::cout << acc_result << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "5028332fb4f3d5f9b1c3bdf4edffab0bcfcc1aad", "size": 456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/eigen/angle_axis.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/angle_axis.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/angle_axis.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": 22.8, "max_line_length": 64, "alphanum_fraction": 0.6469298246, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5414578016003196}}
{"text": "// Copyright (C) 2018 Thanaphon Chavengsaksongkram <as12production@gmail.com>, He Sun <he.sun@ed.ac.uk>\n// This file is subject to the license terms in the LICENSE file\n// found in the top-level directory of this distribution.\n\n#ifndef GSPARSE_ER_POLICY_EXACTERJACOBICG_HPP\n#define GSPARSE_ER_POLICY_EXACTERJACOBICG_HPP\n\n#include \"../../Config.hpp\"\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\nnamespace gSparse \n{\n    namespace ER \n    {\n        namespace Policy\n        {\n            /// \\ingroup EffectiveResistance\n            ///\n            /// This class implements Spectral Sparsifier by Effective Weight Sampling.\n            /// Adaptation from http://ccom.uprrp.edu/~ikoutis/SpectralAlgorithms.htm\n            /// The algorithm leverages Conjugated Graident with Jacobi preconditioner to solve linear system\n            ///\n            class ExactERJacobiCG\n            {\n            protected:\n                /// This function calculates Effective Resistance and return computation status.\n                /// \\param er A row matrix to receive the EffectiveResistance value\n                /// \\param graph A std::shared_ptr<IGraph> object representing the graph to calculate resistance\n                /// \\param eps Error tolerance for conjugated gradient. Default is 1.0f.\n                /// \\param JLTol Tolerance for JL projection Matrix. Default is 0.5f. (See http://ccom.uprrp.edu/~ikoutis/SpectralAlgorithms.htm.)\n                /// \\param maxIter  Maximum iteration for conjugated gradient. Default is 300 iterations.\n                inline gSparse::COMPUTE_INFO _calculateER(\n                    gSparse::PrecisionRowMatrix & er,\n                    const gSparse::Graph & graph,\n                    int maxIter = 300\n                    )\n                {\n                    er = gSparse::PrecisionRowMatrix::Zero(graph->GetEdgeCount(), 1);\n                    for (int i = 0; i != graph->GetEdgeCount(); ++i)\n                    {\n                        Eigen::ConjugateGradient<gSparse::SparsePrecisionMatrix, Eigen::Lower | Eigen::Upper  > cg;\n                        cg.setMaxIterations(maxIter);\n                        auto b = graph->GetIncidentMatrix().row(i);\n                        cg.compute(graph->GetLaplacianMatrix());\n                        Eigen::VectorXd x = cg.solve(b.transpose());\n                        b.toDense();\n                        er(i) = b.toDense() * x;\n                    }\n                    // Non finite number goes to zero\n                    er = er.unaryExpr([](double v) { return std::isfinite(v)? v : 0.0; });\n                    return gSparse::SUCCESSFUL;\n                }\n            };\n        }\n        \n    }\n}\n#endif\n", "meta": {"hexsha": "2ac81f8158fc864fde09d0c5b551d1c5b071934b", "size": 2703, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gSparse/ER/Policy/ExactERJacobiCG.hpp", "max_stars_repo_name": "As-12/gSparse", "max_stars_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-14T09:38:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:03:55.000Z", "max_issues_repo_path": "include/gSparse/ER/Policy/ExactERJacobiCG.hpp", "max_issues_repo_name": "As-12/gSparse", "max_issues_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gSparse/ER/Policy/ExactERJacobiCG.hpp", "max_forks_repo_name": "As-12/gSparse", "max_forks_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-11T13:03:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T13:03:58.000Z", "avg_line_length": 45.05, "max_line_length": 146, "alphanum_fraction": 0.5593784684, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5414092186947602}}
{"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_SECPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SECPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing secpi capabilities\n\n    secant of the angle in pi multiples.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = secpi(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = rec(cospi(x));\n    @endcode\n\n    @see secd, sec, cospi, cos\n\n  **/\n  const boost::dispatch::functor<tag::secpi_> secpi = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/secpi.hpp>\n#include <boost/simd/function/simd/secpi.hpp>\n\n#endif\n", "meta": {"hexsha": "a66811606657927456cc3d81b558961e193a3f4a", "size": 1102, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/secpi.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/secpi.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/secpi.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": 21.6078431373, "max_line_length": 100, "alphanum_fraction": 0.5716878403, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5414092019184676}}
{"text": "#include \"catch.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <ezarpack/arpack_worker.hpp>\n#include <ezarpack/storages/eigen.hpp>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace ezarpack;\n\nTEST_CASE(\"ok\", \"[ezarpack]\") {\n  int ndim = 10;\n  MatrixXd matA = MatrixXd::Random(ndim, ndim);\n  MatrixXd matB = MatrixXd::Random(ndim, ndim);\n  matA = matA * matA.transpose();\n  matB = matB * matB.transpose();\n  matB += ndim * MatrixXd::Identity(ndim, ndim);\n  matA = -matA;\n  matB = -matB;\n\n  using worker_t = arpack_worker<ezarpack::Symmetric, eigen_storage>;\n  using vector_view_t = worker_t::vector_view_t;\n  using vector_const_view_t = worker_t::vector_const_view_t;\n\n  auto op = [&](vector_view_t from, vector_view_t to) { to = matA * from; };\n  auto b = [&](vector_const_view_t from, vector_view_t to) {\n    to = matB * from;\n  };\n\n  worker_t worker(ndim);\n\n  using params_t = worker_t::params_t;\n  int nev = ndim - 1;\n  params_t params(nev, params_t::Smallest, false);\n\n  worker(b, params);\n\n  std::cout << \"Eigenvalues (Ritz values):\" << std::endl;\n  std::cout << worker.eigenvalues().transpose() << std::endl;\n\n  EigenSolver<MatrixXd> es(matB, false);\n  std::cout << es.eigenvalues().transpose().real() << std::endl;\n\n  worker_t worker2(ndim);\n\n  double sigma = 0.5;\n  MatrixXd mat_op = matA - sigma * matB;\n\n  auto op2 = [&](vector_view_t from, vector_view_t to) {\n    to = matB * from;\n    to = mat_op.ldlt().solve(to);\n  };\n  params.sigma = sigma;\n  worker2(op2, b, worker_t::ShiftAndInvert, params);\n\n  std::cout << \"Eigenvalues (Ritz values):\" << std::endl;\n  std::cout << worker2.eigenvalues().transpose() << std::endl;\n\n  GeneralizedEigenSolver<MatrixXd> es2(matA, matB, false);\n  std::cout << es2.eigenvalues().transpose().real() << std::endl;\n}", "meta": {"hexsha": "67a63a3b55f044c5fe7ce9d4492a82b6483516f3", "size": 1788, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test_ezarpack.cc", "max_stars_repo_name": "pan3rock/shift-invert", "max_stars_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_stars_repo_licenses": ["MIT"], "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_ezarpack.cc", "max_issues_repo_name": "pan3rock/shift-invert", "max_issues_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_issues_repo_licenses": ["MIT"], "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_ezarpack.cc", "max_forks_repo_name": "pan3rock/shift-invert", "max_forks_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_forks_repo_licenses": ["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.8387096774, "max_line_length": 76, "alphanum_fraction": 0.6739373602, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.541409196397582}}
{"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/Core>\n#include <Eigen/Cholesky>\n#include \"integration/ModifiedCholesky.hpp\"\n\nAUTO_TEST_CASE( test_modified_cholesky_positive_definite ) {\n\ttypedef Eigen::VectorXd Vector ;\n\ttypedef Eigen::MatrixXd Matrix ;\n    integration::ModifiedCholesky< Matrix > comp ;\n\tEigen::LDLT< Matrix > ldlt ;\n\tMatrix const identity = Matrix::Identity( 2, 2 ) ;\n\n\t\n\t{\n\t\tMatrix const identity = Matrix::Identity( 1, 1 ) ;\n\t\tMatrix test( 1, 1 ) ;\n\t\ttest << 1 ;\n\t\tcomp.compute( test ) ;\n\t\tldlt.compute( test ) ;\n\t\tBOOST_CHECK_EQUAL( comp.matrixP() * identity, ldlt.transpositionsP() * identity ) ;\n\t\tBOOST_CHECK_EQUAL( comp.vectorD(), ldlt.vectorD() ) ;\n\t\tBOOST_CHECK_EQUAL( comp.matrixL() * identity, ldlt.matrixL() * identity ) ;\n\t\tBOOST_CHECK_EQUAL( comp.solve( identity ) * test, identity ) ;\n\t}\n\n\t{\n\t\tMatrix test( 2, 2 ) ;\n\t\ttest << 1, 0, 0, 1 ;\n\t\tcomp.compute( test ) ;\n\t\tldlt.compute( test ) ;\n\t\tBOOST_CHECK_EQUAL( comp.matrixP() * identity, ldlt.transpositionsP() * identity ) ;\n\t\tBOOST_CHECK_EQUAL( comp.vectorD(), ldlt.vectorD() ) ;\n\t\tBOOST_CHECK_EQUAL( comp.matrixL() * identity, ldlt.matrixL() * identity ) ;\n\t\tBOOST_CHECK_EQUAL( comp.solve( identity ) * test, identity ) ;\n\t}\n\n\t{\n\t\t// This is a non-positive definite matrix\n\t\tMatrix test( 2, 2 ) ;\n\t\ttest << 1, 0.5, 0.5, 1 ;\n\t\tcomp.compute( test ) ;\n\t\tldlt.compute( test ) ;\n\t\tBOOST_CHECK_EQUAL( comp.matrixP() * identity, ldlt.transpositionsP() * identity ) ;\n\t\tBOOST_CHECK_EQUAL( comp.vectorD(), ldlt.vectorD() ) ;\n\t\tBOOST_CHECK_EQUAL( comp.matrixL() * identity, ldlt.matrixL() * identity ) ;\n\t\tBOOST_CHECK_EQUAL( comp.solve( identity ) * test, identity ) ;\n\t}\n}\n\nAUTO_TEST_CASE( test_modified_cholesky_nonpositive_definite ) {\n\ttypedef Eigen::VectorXd Vector ;\n\ttypedef Eigen::MatrixXd Matrix ;\n    integration::ModifiedCholesky< Matrix > comp ;\n\n\tMatrix const identity = Matrix::Identity( 2, 2 ) ;\n\n\t{\n\t\t// This is a non-positive definite matrix\n\t\tMatrix test( 2, 2 ) ;\n\t\ttest << 1, 2, 2, 1 ;\n\t\tcomp.compute( test ) ;\n\t\tBOOST_CHECK_EQUAL( comp.matrixP() * identity, identity ) ;\n\t\t// Diagonal should be at least as large as that of LDLT.\n\t\tfor( int j = 0; j < 2; ++j ) {\n\t\t\tTEST_ASSERT( comp.vectorD()(j) >= std::numeric_limits< double >::epsilon() ) ;\n\t\t}\n\n\t\tstd::cerr << \"test_modified_cholesky_nonpositive_definite(): reconstructed matrix is:\\n\"\n\t\t\t<< comp.solve( identity ).inverse() << \".\\n\" ;\n\t}\t\n}\n\n\n", "meta": {"hexsha": "e3e888f397ddb99ca82f1c58aaf22cdee41e0dcc", "size": 2684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "integration/test/test_modified_cholesky.cpp", "max_stars_repo_name": "gavinband/bingwa", "max_stars_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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": "integration/test/test_modified_cholesky.cpp", "max_issues_repo_name": "gavinband/bingwa", "max_issues_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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": "integration/test/test_modified_cholesky.cpp", "max_forks_repo_name": "gavinband/bingwa", "max_forks_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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.3373493976, "max_line_length": 90, "alphanum_fraction": 0.6754843517, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5414091963738449}}
{"text": "#include \"mst.hpp\"\n\n#include \"graph/algorithms.hpp\"\n\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include <numeric>\n#include <vector>\n\nnamespace awesome {\n\n\tMSTHeuristic::MSTHeuristic(Graph const& psg, MapGraph const& map)\n\t      : Heuristic(psg, map) {}\n\n\tint MSTHeuristic::operator()(MapGraph const& state, GraphConstNode const&) {\n\t\tMapGraph undirectedMap = graph::undirected(state);\n\t\tMapGraph mst = graph::minimumSpanningTree(undirectedMap, undirectedMap.begin());\n\n\t\tsize_t sum = 0;\n\t\tmst.eachEdges([&mst, &sum](MapGraphConstNode begin, MapGraphConstNode end) {\n\t\t\tsum += mst.getEdgeProperty(begin, end).weight;\n\t\t});\n\n\t\t// Directed graph \u21d2 2\u00d7 more edges !\n\t\treturn sum / 2;\n\t}\n}\n", "meta": {"hexsha": "53dfabcfd6ae6301dccbd07632c4bc40e27d730d", "size": 696, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/heuristics/mst.cpp", "max_stars_repo_name": "minijackson/PR-3602", "max_stars_repo_head_hexsha": "197c47434fcfbd4b5aa1aff85e6a680f2671f8e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/heuristics/mst.cpp", "max_issues_repo_name": "minijackson/PR-3602", "max_issues_repo_head_hexsha": "197c47434fcfbd4b5aa1aff85e6a680f2671f8e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-04-11T11:15:01.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-29T16:22:04.000Z", "max_forks_repo_path": "src/heuristics/mst.cpp", "max_forks_repo_name": "minijackson/PR-3602", "max_forks_repo_head_hexsha": "197c47434fcfbd4b5aa1aff85e6a680f2671f8e4", "max_forks_repo_licenses": ["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.7777777778, "max_line_length": 82, "alphanum_fraction": 0.7183908046, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5414091851896494}}
{"text": "#pragma once\n\n#include <algorithm>\n\n#include <Eigen/Core>\n#include <Eigen/CXX11/Tensor>\n\n#include \"../piecewise_polynomial.hpp\"\n#include \"spline.hpp\"\n\nnamespace irlib {\n    //template<typename T>\n    //reutrn\n    template<typename T> T const_pi();\n\n    template<>\n    inline mpfr::mpreal const_pi<mpfr::mpreal>() {\n        return mpfr::const_pi();\n    }\n\n    template<>\n    inline double const_pi<double>() {\n        return M_PI;\n    }\n\n    inline std::complex<mpreal> my_exp(const mpreal& z_img) {\n        return std::complex<mpreal>(\n                mpfr::cos(z_img), mpfr::sin(z_img)\n        );\n    }\n\n    template<typename mp_type>\n    std::vector<std::pair<mp_type, mp_type> >\n    composite_gauss_legendre_nodes(\n            const std::vector<mp_type> &section_edges,\n            const std::vector<std::pair<mp_type, mp_type> > &nodes\n    ) {\n        int num_sec = section_edges.size() - 1;\n        int num_local_nodes = nodes.size();\n\n        std::vector<std::pair<mp_type, mp_type> > all_nodes(num_sec * num_local_nodes);\n        for (int s = 0; s < num_sec; ++s) {\n            auto a = section_edges[s];\n            auto b = section_edges[s + 1];\n            for (int n = 0; n < num_local_nodes; ++n) {\n                mp_type x = a + ((b - a) / mp_type(2)) * (nodes[n].first + mp_type(1));\n                mp_type w = ((b - a) / mp_type(2)) * nodes[n].second;\n                all_nodes[s * num_local_nodes + n] = std::make_pair(x, w);\n            }\n        }\n        return all_nodes;\n    };\n\n    template<typename Tx, typename Ty, typename F>\n    Ty integrate_gauss_legendre(const std::vector<Tx>& section_edges, const F& f, int num_local_nodes) {\n        std::vector<std::pair<Tx, Tx>> nodes = detail::gauss_legendre_nodes<Tx>(num_local_nodes);\n        auto nodes_x = composite_gauss_legendre_nodes(section_edges, nodes);\n        Ty r = 0;\n        for (int n=0; n<nodes_x.size(); ++n) {\n            r += f(static_cast<Ty>(nodes_x[n].first)) * static_cast<Ty>(nodes_x[n].second);\n        }\n        return r;\n    };\n\n    /**\n     * Compute Matrix representation of a given Kernel\n     * @tparam Scalar\n     * @tparam K\n     * @param kernel\n     * @param section_edges_x\n     * @param section_edges_y\n     * @param num_local_nodes\n     * @param num_local_poly\n     * @return Matrix representation\n     */\n    template<typename Scalar, typename K>\n    Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>\n    matrix_rep(const K &kernel,\n               const std::vector<mpreal> &section_edges_x,\n               const std::vector<mpreal> &section_edges_y,\n               int num_local_nodes,\n               int num_local_poly) {\n\n        using mpreal_matrix_type = Eigen::Matrix<mpreal, Eigen::Dynamic, Eigen::Dynamic>;\n        using matrix_type = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n\n        int num_sec_x = section_edges_x.size() - 1;\n        int num_sec_y = section_edges_y.size() - 1;\n\n        // nodes for Gauss-Legendre integration\n        std::vector<std::pair<mpreal, mpreal >> nodes = detail::gauss_legendre_nodes<mpreal>(num_local_nodes);\n        auto nodes_x = composite_gauss_legendre_nodes(section_edges_x, nodes);\n        auto nodes_y = composite_gauss_legendre_nodes(section_edges_y, nodes);\n\n        std::vector<mpreal_matrix_type> phi_x(num_sec_x);\n        for (int s = 0; s < num_sec_x; ++s) {\n            phi_x[s] = mpreal_matrix_type(num_local_poly, num_local_nodes);\n            for (int n = 0; n < num_local_nodes; ++n) {\n                for (int l = 0; l < num_local_poly; ++l) {\n                    auto leg_val = normalized_legendre_p(l, nodes[n].first);\n                    phi_x[s](l, n) = detail::sqrt<mpreal>(mpreal(2) / (section_edges_x[s + 1] - section_edges_x[s])) * leg_val *\n                                     nodes_x[s * num_local_nodes + n].second;\n                }\n            }\n        }\n\n        std::vector<mpreal_matrix_type> phi_y(num_sec_y);\n        for (int s = 0; s < num_sec_y; ++s) {\n            phi_y[s] = mpreal_matrix_type(num_local_poly, num_local_nodes);\n            for (int n = 0; n < num_local_nodes; ++n) {\n                for (int l = 0; l < num_local_poly; ++l) {\n                    auto leg_val = normalized_legendre_p(l, nodes[n].first);\n                    phi_y[s](l, n) = detail::sqrt<mpreal>(mpreal(\"2\") / (section_edges_y[s + 1] - section_edges_y[s])) * leg_val *\n                                     nodes_y[s * num_local_nodes + n].second;\n                }\n            }\n        }\n\n        matrix_type K_mat(num_sec_x * num_local_poly, num_sec_y * num_local_poly);\n        for (int s2 = 0; s2 < num_sec_y; ++s2) {\n            for (int s = 0; s < num_sec_x; ++s) {\n\n                mpreal_matrix_type K_nn(num_local_nodes, num_local_nodes);\n                for (int n = 0; n < num_local_nodes; ++n) {\n                    for (int n2 = 0; n2 < num_local_nodes; ++n2) {\n                        K_nn(n, n2) = kernel(static_cast<Scalar>(nodes_x[s * num_local_nodes + n].first),\n                                             static_cast<Scalar>(nodes_y[s2 * num_local_nodes + n2].first)\n                        );\n                    }\n                }\n\n                // phi_x(l, n) * K_nn(n, n2) * phi_y(l2, n2)^T\n                mpreal_matrix_type r = phi_x[s] * K_nn * phi_y[s2].transpose();\n\n                for (int l2 = 0; l2 < num_local_poly; ++l2) {\n                    for (int l = 0; l < num_local_poly; ++l) {\n                        K_mat(num_local_poly * s + l, num_local_poly * s2 + l2) = static_cast<Scalar>(r(l, l2));\n                    }\n                }\n            }\n        }\n\n        return K_mat;\n    }\n\n    /**\n     * Estimate absolute errors in ulx and vly by computing the residual of the integral equation\n     *   r(x) = u(x) - s^{-1} int_0^1 K(x,y) v(y) dy\n     *   This returns an estimate of max_x |r(x)|\n     * @tparam K\n     * @param ux defined on [0, 1]\n     * @param vy defined on [0, 1]\n     * @param kernel a function of (x, y)\n     * @return residual for ux\n     */\n    template<typename T, typename K>\n    double estimate_residual(const piecewise_polynomial<T,T>& ux, const piecewise_polynomial<T,T>& vy, T s, const K& kernel, int num_local_nodes) {\n        auto section_edges_x = ux.section_edges();\n        auto section_edges_y = vy.section_edges();\n\n        auto local_nodes = detail::gauss_legendre_nodes<mpfr::mpreal>(num_local_nodes);\n        auto nodes_y = composite_gauss_legendre_nodes(section_edges_y, local_nodes);\n\n        std::vector<T> sampling_points(section_edges_x);\n        for (int i=0; i < section_edges_x.size()-1; ++i) {\n            auto dx = section_edges_x[i+1]-section_edges_x[i];\n            sampling_points.push_back(0.25*dx + section_edges_x[i]);\n            sampling_points.push_back(0.50*dx + section_edges_x[i]);\n            sampling_points.push_back(0.75*dx + section_edges_x[i]);\n        }\n\n        // Now we compute residual for u_l(x)\n        double residual_x = 0.0;\n        for (auto i = 0; i < section_edges_x.size()-1; ++i) {\n            auto x = (section_edges_x[i+1] + section_edges_x[i])/2;\n            mpfr::mpreal sum(0);\n            for (int n=0; n < nodes_y.size(); ++n) {\n                auto y = nodes_y[n].first;\n                auto w = nodes_y[n].second;\n                sum += w * kernel(x,y) * vy.compute_value(y);\n            }\n            auto diff = mpfr::abs(sum/s - ux.compute_value(x));\n            residual_x = std::max(residual_x, static_cast<double>(diff));\n        }\n\n        return residual_x;\n    }\n\n    template<typename SVD>\n    void check_SVD(const MatrixXmp& Kmat_even, const SVD& svd_even) {\n        MatrixXmp S(svd_even.matrixU().cols(), svd_even.matrixV().cols());\n        MatrixXmp invS(svd_even.matrixU().cols(), svd_even.matrixV().cols());\n        S.setZero();\n        invS.setZero();\n        for (int l=0; l<svd_even.singularValues().rows(); ++l) {\n            S(l,l) = svd_even.singularValues()[l];\n            invS(l,l) = 1/svd_even.singularValues()[l];\n        }\n        for (int l=0; l<svd_even.matrixV().cols(); ++l) {\n            MatrixXmp diff = (Kmat_even * svd_even.matrixV().col(l))/svd_even.singularValues()[l] - svd_even.matrixU().col(l);\n            std::cout << \"Residual of SVD at l = \" << l << \" \" << diff.squaredNorm() << \" \" << svd_even.singularValues()[l] << std::endl;\n        }\n        /*\n         * MatrixXmp diff = Kmat_even - svd_even.matrixU() * S * svd_even.matrixV().transpose();\n        for (int l=0; l<std::min(diff.rows(), diff.cols()); ++l) {\n            std::cout << \"Residual of SVD at l = \" << l << \" \" << diff(l,l) << std::endl;\n        }\n         */\n    }\n\n\n    /**\n     *\n     * @tparam ScalarType\n     * @tparam KernelType\n     * @r_int_eq absolute errors in ulx and vly estimated by the residual of integral equations. This estimate may be too big\n     *    for very small singular values because the residual contains the inverse of singular values.\n     */\n    template<typename ScalarType, typename KernelType>\n    std::tuple<\n            std::vector<mpreal>,\n            std::vector<piecewise_polynomial<mpreal,mpreal>>,\n            std::vector<piecewise_polynomial<mpreal,mpreal>>\n    >\n    generate_ir_basis_functions_impl(\n            const KernelType &kernel,\n            int max_dim,\n            double sv_cutoff,\n            int num_local_poly,\n            int num_nodes_gauss_legendre,\n            const std::vector<mpreal> &section_edges_x,\n            const std::vector<mpreal> &section_edges_y,\n            std::vector<double> &residual_x,\n            std::vector<double> &residual_y,\n            std::pair<double,double>& r_int_eq,\n            bool verbose\n    ) throw(std::runtime_error) {\n        using vector_t = Eigen::Matrix<ScalarType, Eigen::Dynamic, 1>;\n        using matrix_t = Eigen::Matrix<ScalarType, Eigen::Dynamic, Eigen::Dynamic>;\n        using mp_vector_t = Eigen::Matrix<mpreal, Eigen::Dynamic, 1>;\n        using mp_matrix_t = Eigen::Matrix<mpreal, Eigen::Dynamic, Eigen::Dynamic>;\n\n        if (num_local_poly < 2) {\n            throw std::runtime_error(\"num_local_poly < 2! : \" + std::to_string(num_local_poly));\n        }\n\n        // Compute Kernel matrix and do SVD for even/odd sector\n        if (verbose) {\n            std::cout << \"  Constructing kernel matrix for even sector ... \"  << std::flush;\n        }\n        auto kernel_even = [&](const mpreal &x, const mpreal &y) { return kernel(x, y) + kernel(x, -y); };\n        auto Kmat_even = irlib::matrix_rep<ScalarType>(\n                kernel_even, section_edges_x, section_edges_y, num_nodes_gauss_legendre, num_local_poly\n        );\n        if (verbose) {\n            std::cout << \" done \" << std::endl;\n            std::cout << \"  SVD kernel matrix for even sector ... \" << std::flush;\n        }\n        Eigen::BDCSVD<matrix_t> svd_even(Kmat_even, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        if (verbose) {\n            std::cout << \" done \" << std::endl;\n            std::cout << \"  Constructing kernel matrix for odd sector ... \" << std::flush;\n        }\n        auto kernel_odd = [&](const mpreal &x, const mpreal &y) { return kernel(x, y) - kernel(x, -y); };\n        auto Kmat_odd = irlib::matrix_rep<ScalarType>(\n                kernel_odd, section_edges_x, section_edges_y, num_nodes_gauss_legendre, num_local_poly\n        );\n        if (verbose) {\n            std::cout << \" done \" << std::endl;\n            std::cout << \"  SVD kernel matrix for odd sector ... \" << std::flush;\n        }\n        Eigen::BDCSVD<matrix_t> svd_odd(Kmat_odd, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        if (verbose) {\n            std::cout << \" done \" << std::endl;\n        }\n\n        // Pick up singular values and basis functions larger than cutoff\n        std::vector<mpfr::mpreal> sv;\n        std::vector<vector_t> Uvec, Vvec;\n        auto s0 = svd_even.singularValues()[0];\n        for (int i = 0; i < svd_even.singularValues().size(); ++i) {\n            if (sv.size() == max_dim || svd_even.singularValues()[i] / s0 < sv_cutoff) {\n                break;\n            }\n            sv.push_back(svd_even.singularValues()[i]);\n            Uvec.push_back(svd_even.matrixU().col(i));\n            Vvec.push_back(svd_even.matrixV().col(i));\n            if (sv.size() == max_dim || svd_odd.singularValues()[i] / s0 < sv_cutoff) {\n                break;\n            }\n            sv.push_back(svd_odd.singularValues()[i]);\n            Uvec.push_back(svd_odd.matrixU().col(i));\n            Vvec.push_back(svd_odd.matrixV().col(i));\n        }\n        assert(sv.size() <= max_dim);\n\n        // Check if singular values are in decreasing order\n        for (int l = 0; l < sv.size() - 1; ++l) {\n            if (sv[l] < sv[l + 1]) {\n                throw std::runtime_error(\n                        \"Singular values are not in decreasing order. This may be due to numerical round erros. You may ask for fewer basis functions!\");\n            }\n        }\n\n        // Construct basis functions\n        std::vector<std::vector<mpreal>> deriv_xm1 = normalized_legendre_p_derivatives(num_local_poly, mpreal(\"-1\"));\n        std::vector<mpreal> inv_factorial;\n        inv_factorial.push_back(mpreal(1));\n        for (int l = 1; l < num_local_poly; ++l) {\n            inv_factorial.push_back(inv_factorial.back() / mpreal(l));\n        }\n\n        auto gen_pp = [&](const std::vector<mpreal> &section_edges, const std::vector<vector_t> &vectors) {\n            std::vector<piecewise_polynomial<mpreal,mpreal>> pp;\n\n            int ns_pp = section_edges.size() - 1;\n            for (int v = 0; v < vectors.size(); ++v) {\n                Eigen::Matrix<mpreal,Eigen::Dynamic,Eigen::Dynamic> coeff(ns_pp, num_local_poly);\n                coeff.setZero();\n                int parity = v % 2 == 0 ? 1 : -1;\n                // loop over sections in [0, 1]\n                for (int s = 0; s < section_edges.size() - 1; ++s) {\n                    // loop over normalized Legendre polynomials\n                    for (int l = 0; l < num_local_poly; ++l) {\n                        mpreal coeff2 = mpreal(1)/mpfr::sqrt(section_edges[s + 1] - section_edges[s]);\n                        // loop over the orders of derivatives\n                        for (int d = 0; d < num_local_poly; ++d) {\n                            mpreal tmp = inv_factorial[d] * coeff2 * vectors[v][s * num_local_poly + l] * deriv_xm1[l][d];\n                            coeff(s, d) += tmp;\n                            coeff2 *= mpreal(2)/(section_edges[s + 1] - section_edges[s]);\n                        }\n                    }\n                }\n                pp.push_back(piecewise_polynomial<mpreal,mpreal>(section_edges.size() - 1, section_edges, coeff));\n            }\n\n            return pp;\n        };\n\n        auto u_basis_pp = gen_pp(section_edges_x, Uvec);\n        auto v_basis_pp = gen_pp(section_edges_y, Vvec);\n\n        for (int i = 0; i < u_basis_pp.size(); ++i) {\n            if (u_basis_pp[i].compute_value(1) < 0) {\n                u_basis_pp[i] = mpreal(-1.0) * u_basis_pp[i];\n                v_basis_pp[i] = mpreal(-1.0) * v_basis_pp[i];\n            }\n        }\n\n        if (u_basis_pp.size()%2 == 1) {\n            r_int_eq.first = estimate_residual(u_basis_pp.back(), v_basis_pp.back(), sv.back(), kernel_even, num_nodes_gauss_legendre);\n            auto k_yx = [&](mpreal y, mpreal x) {return kernel_even(x,y);};\n            r_int_eq.second = estimate_residual(v_basis_pp.back(), u_basis_pp.back(), sv.back(), k_yx, num_nodes_gauss_legendre);\n        } else {\n            r_int_eq.first = estimate_residual(u_basis_pp.back(), v_basis_pp.back(), sv.back(), kernel_odd, num_nodes_gauss_legendre);\n            auto k_yx = [&](mpreal y, mpreal x) {return kernel_odd(x,y);};\n            r_int_eq.second = estimate_residual(v_basis_pp.back(), u_basis_pp.back(), sv.back(), k_yx, num_nodes_gauss_legendre);\n        }\n\n\n        residual_x.resize(section_edges_x.size() - 1);\n        residual_y.resize(section_edges_y.size() - 1);\n        //std::fill(residual_x.begin(), residual_x.end(), 0.0);\n        ////std::fill(residual_y.begin(), residual_y.end(), 0.0);\n\n        {\n            auto l = Uvec.size() -1;\n            for (int s = 0; s < residual_x.size(); ++s) {\n                double dx = static_cast<double>(section_edges_x[s+1]-section_edges_x[s]);\n                double a_diff = static_cast<double>(Uvec[l](s * num_local_poly + num_local_poly - 1)) * std::sqrt((2.*l+1)/dx);\n                residual_x[s] = std::abs(a_diff);\n            }\n            for (int s = 0; s < residual_y.size(); ++s) {\n                double dy = static_cast<double>(section_edges_y[s+1]-section_edges_y[s]);\n                double a_diff = static_cast<double>(Vvec[l](s * num_local_poly + num_local_poly - 1)) * std::sqrt((2.*l+1)/dy);\n                residual_y[s] = std::abs(a_diff);\n            }\n        }\n\n        return std::make_tuple(sv, u_basis_pp, v_basis_pp);\n    }\n\n    template<typename ScalarType, typename KernelType>\n    std::tuple<\n            std::vector<mpreal>,\n            std::vector<piecewise_polynomial<mpreal,mpreal>>,\n            std::vector<piecewise_polynomial<mpreal,mpreal>>\n    >\n    generate_ir_basis_functions(\n            const KernelType &kernel,\n            int max_dim,\n            double sv_cutoff = 1e-12,\n            bool verbose = false,\n            double r_tol = 1e-6,\n            int num_local_poly = 10,\n            int num_nodes_gauss_legendre = 24\n    ) throw(std::runtime_error) {\n        using vector_t = Eigen::Matrix<ScalarType, Eigen::Dynamic, 1>;\n        // Compute approximate positions of nodes of the highest basis function in the even sector\n        std::vector<double> nodes_x, nodes_y;\n        if (verbose){\n            std::cout << \"Computing approximate positions of zeros... \";\n            std::tie(nodes_x, nodes_y) = compute_approximate_nodes_even_sector(kernel, 500, std::max(1e-12, sv_cutoff));\n            std::cout << \"Done\" << std::endl;\n        }\n\n        auto gen_section_edges = [](const std::vector<double> &nodes) {\n            std::vector<mpreal> section_edges;\n            section_edges.push_back(0);\n            for (int i = 0; i < nodes.size(); ++i) {\n                section_edges.push_back(static_cast<mpreal>(nodes[i]));\n            }\n            section_edges.push_back(1);\n            return section_edges;\n        };\n\n        auto u = [](const std::vector<mpreal> &section_edges,\n                    std::vector<double> &residual, double eps) {\n            std::vector<mpreal> section_edges_new(section_edges);\n            for (int s = 0; s < section_edges.size() - 1; ++s) {\n                if (residual[s] > eps) {\n                    section_edges_new.push_back(\n                            (section_edges[s] + section_edges[s + 1]) / 2\n                    );\n                }\n            }\n            std::sort(section_edges_new.begin(), section_edges_new.end());\n            return section_edges_new;\n        };\n\n        std::vector<mpreal> section_edges_x = gen_section_edges(nodes_x);\n        std::vector<mpreal> section_edges_y = gen_section_edges(nodes_y);\n\n        int ite = 0;\n\n        // Sections are split recursively until convergence is reached.\n        while (true) {\n            if (verbose) {\n                std::cout << \"Iteration \" << ite+1 << \" : \" << section_edges_x.size()-1 << \" sections for x, \" << section_edges_y.size()-1 << \" sections for y.\" << std::endl;\n            }\n            std::vector<double> residual_x, residual_y;\n            std::pair<double,double> r_int_eq;\n            auto r = generate_ir_basis_functions_impl<ScalarType>(kernel, max_dim, sv_cutoff, num_local_poly, num_nodes_gauss_legendre,\n                    section_edges_x,\n                    section_edges_y,\n                    residual_x,\n                    residual_y,\n                    r_int_eq,\n                    verbose\n            );\n            int ns = section_edges_x.size() + section_edges_y.size();\n\n            int dim = std::get<1>(r).size();\n\n            auto a_tol_x = r_tol * std::abs(\n                    static_cast<double>(std::get<1>(r).back().compute_value(1))\n            );\n            auto a_tol_y = r_tol * std::max(\n                    std::abs(static_cast<double>(std::get<2>(r)[2*(dim/2)-1].compute_value(1))),\n                    std::abs(static_cast<double>(std::get<2>(r)[2*(dim/2)-1].compute_value(0)))\n            );\n\n            section_edges_x = u(section_edges_x, residual_x, a_tol_x);\n            section_edges_y = u(section_edges_y, residual_y, a_tol_y);\n\n            if (verbose) {\n                std::cout << \"Iteration \" << ite+1 << \" : found \" << std::get<1>(r).size() <<  \" basis functions. \" << std::endl;\n                std::cout << \"Iteration \" << ite+1 << \" : max_x |u_l(x) - s_l^{-1} dy int_{-1}^1 K(x,y) v_l(y)| = \" << r_int_eq.first << \" for largest l.\" << std::endl;\n                std::cout << \"Iteration \" << ite+1 << \" : max_y |v_l(y) - s_l^{-1} dx int_{-1}^1 K(x,y) u_l(x)| = \" << r_int_eq.second << \" for largest l.\" << std::endl;\n                std::cout << \"Iteration \" << ite+1 << \" : residual estimated by expansion coefficients for x = \" << *std::max_element(residual_x.begin(),residual_x.end()) << std::endl;\n                std::cout << \"Iteration \" << ite+1 << \" : residual estimated by expansion coefficients for y = \" << *std::max_element(residual_y.begin(),residual_y.end()) << std::endl;\n            }\n\n            if (section_edges_x.size() + section_edges_y.size() == ns) {\n                return r;\n            }\n\n            ite += 1;\n        }\n\n    };\n\n    template<typename T>\n    inline std::vector<T> linspace(T minval, T maxval, int N, bool include_last_point = true) {\n        int end = include_last_point ? N : N-1;\n        std::vector<T> r(end);\n        for (int i = 0; i < end; ++i) {\n            r[i] = i * (maxval - minval) / (N - T(1)) + minval;\n        }\n        return r;\n    }\n\n\n\n    template<typename T>\n    piecewise_polynomial<T,T> construct_piecewise_polynomial_cspline(\n            const std::vector<T> &x_array, const std::vector<T> &y_array) {\n        const int n_points = x_array.size();\n        const int n_section = n_points - 1;\n\n        Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> coeff(n_section, 4);\n\n        // Cubic spline interpolation\n        tk::spline<T> spline;\n        spline.set_points(x_array, y_array);\n\n        // Construct piecewise_polynomial\n        for (int s = 0; s < n_section; ++s) {\n            for (int p = 0; p < 4; ++p) {\n                coeff(s, p) = spline.get_coeff(s, p);\n            }\n        }\n        return piecewise_polynomial<T,T>(n_section, x_array, coeff);\n    };\n\n    /**\n     * Find all zeros of a piecewise polynomial defined on (0,1)\n     * @tparam T\n     * @tparam Tx\n     * @param p\n     * @param delta tolerance\n     * @return\n     */\n    template<typename T, typename Tx>\n    std::vector<Tx> find_zeros(\n            const piecewise_polynomial<T,Tx>& p,\n            Tx delta\n    ) {\n        int N = 10000;\n        Tx de_cutoff = 3.0;\n\n        std::vector<Tx> tx_vec = linspace<Tx>(0.0, de_cutoff, N);\n        std::vector<Tx> x_vec(N), zeros;\n        for (int i = 0; i < N; ++i) {\n            x_vec[i] = tanh(0.5 * const_pi<Tx>() * sinh(tx_vec[i]));\n        }\n\n        for (int i = 0; i < N-1; ++i) {\n            if (p.compute_value(x_vec[i]) * p.compute_value(x_vec[i+1]) < 0) {\n                Tx x_left = x_vec[i];\n                T p_left = p.compute_value(x_vec[i]);\n\n                Tx x_right = x_vec[i+1];\n                T p_right = p.compute_value(x_vec[i+1]);\n\n                while (x_right-x_left > delta) {\n                    Tx x_mid = (x_left+x_right)/2;\n                    if (p_left * p.compute_value(x_mid) > 0) {\n                        x_left = x_mid;\n                    } else {\n                        x_right = x_mid;\n                    }\n                }\n                zeros.push_back((x_left+x_right)/2);\n            }\n        }\n\n        return zeros;\n    };\n\n    template<typename T, typename Tx>\n    std::vector<piecewise_polynomial<T,Tx> > cspline_approximation(\n            const std::vector<piecewise_polynomial<T,Tx> >& basis_vectors,\n            double r_tol\n    ) {\n        std::vector<piecewise_polynomial<T,Tx> > basis_vectors_cspline;\n\n\n        // Determine sampling points\n        std::set<Tx> x_set{0.0, 1.0};\n        int largest_even_l = 2*((basis_vectors.size()-1)/2);\n        std::vector<Tx> zeros = find_zeros(basis_vectors[largest_even_l], static_cast<Tx>(1e-10));\n        std::copy(zeros.begin(), zeros.end(), std::inserter(x_set, x_set.begin()));\n        std::vector<Tx> x(x_set.size());\n        std::vector<Tx> y(x_set.size());\n        while (true) {\n            // construct cubic spline interpolation of the highest-l basis function\n            int index = 0;\n            x.resize(x_set.size());\n            y.resize(x_set.size());\n            for (auto it=x_set.begin(); it != x_set.end(); ++it) {\n                x[index] = *it;\n                y[index] = basis_vectors.back().compute_value(*it);\n                ++ index;\n            }\n            auto cspline = construct_piecewise_polynomial_cspline<T>(x, y);\n\n            // check convergence\n            for (int i=0; i < x.size()-1; ++i) {\n                auto x_mid = (x[i]+x[i+1])/2;\n                auto diff = std::abs(static_cast<double>(\n                                             (cspline.compute_value(x_mid)-basis_vectors.back().compute_value(x_mid))/\n                                                     basis_vectors.back().compute_value(1)\n                                     ));\n                if (diff > r_tol) {\n                    //std::cout << \"add \" << x_mid << \" \" << diff << std::endl;\n                    x_set.insert(x_mid);\n                }\n            }\n\n            if (x_set.size() == x.size()) {\n                break;\n            }\n        }\n\n        int Nx = x.size();\n\n        // construct cspline approximation one by one\n        for (int l=0; l < basis_vectors.size(); ++l) {\n            for (int ix=0; ix<Nx; ++ix) {\n                //std::cout << \" final x \" << std::setprecision(20) << x[ix] << std::endl;\n                y[ix] = basis_vectors[l].compute_value(x[ix]);\n            }\n            basis_vectors_cspline.push_back(construct_piecewise_polynomial_cspline<T>(x, y));\n        }\n\n        return basis_vectors_cspline;\n    };\n\n    //Compute nodes (zeros) of Legendre polynomials\n    inline std::vector<double> compute_legendre_nodes(int l) {\n        double eps = 1e-10;\n        if (l > 200) {\n            throw std::runtime_error(\"l > 200 in compute_legendre_nodes\");\n        }\n\n        std::vector<double> nodes;\n\n        auto leg_diff = [](int l, double x) {\n            return l * (x * legendre_p(l, x) - legendre_p(l - 1, x)) / (x * x - 1);\n        };\n\n        //i-th zero\n        for (int i = 0; i < l / 2; i++) {\n            //initial guess\n            double x = std::cos(M_PI * (i + 1 - 0.25) / (l + 0.5));\n\n            //Newton-Raphson iteration\n            while (true) {\n                double leg = legendre_p(l, x);\n                double x_new = x - 0.1 * leg / leg_diff(l, x);\n                if (std::abs(x_new - x) < eps && std::abs(leg) < eps) {\n                    break;\n                }\n                x = x_new;\n            }\n\n            nodes.push_back(x);\n            nodes.push_back(-x);\n        }\n\n        if (l % 2 == 1) {\n            nodes.push_back(0.0);\n        }\n\n        std::sort(nodes.begin(), nodes.end());\n\n        return nodes;\n    }\n\n    //AVOID USING BOOST_TYPEOF\n    template<class T1, class T2>\n    struct result_of_overlap {\n        typedef std::complex<double> value;\n    };\n\n    template<>\n    struct result_of_overlap<double, double> {\n        typedef double value;\n    };\n\n    /// Construct piecewise polynomials representing exponential functions: exp(i w_i x)\n    template<class T, typename Tx>\n    void construct_exp_functions_coeff(\n            const std::vector<T> &w,\n            const std::vector<Tx> &section_edges,\n            int k,\n            Eigen::Tensor<std::complex<T>, 3> &coeffs) {\n        const int N = section_edges.size() - 1;\n\n        std::complex<T> z;\n        coeffs = Eigen::Tensor<std::complex<T>,3>(w.size(), N, k + 1);\n\n        std::vector<T> pre_factor(k + 1);\n        pre_factor[0] = 1.0;\n        for (int j = 1; j < k + 1; ++j) {\n            pre_factor[j] = pre_factor[j - 1] / j;\n        }\n\n        for (int n = 0; n < w.size(); ++n) {\n            auto z = std::complex<T>(0.0, w[n]);\n            for (int section = 0; section < N; ++section) {\n                auto x = section_edges[section];\n                std::complex<T> exp0 = std::exp(z * (x + 1));\n                std::complex<T> z_power = T(1);\n                for (int j = 0; j < k + 1; ++j) {\n                    coeffs(n, section, j) = exp0 * z_power * pre_factor[j];\n                    z_power *= z;\n                }\n            }\n        }\n    }\n\n/**\n *  Compute \\int_x0^x1 dx exp(i w (x+1)) (x-x0)^k\n *      for k=0, 1, ..., K+1. x1 = x0+dx.\n**/\n    template<typename T>\n    void compute_Ik(T x0, T dx, T w, int K, std::vector<std::complex<T> >& Ik) {\n        auto x1 = x0 + dx;\n        auto iw = std::complex<T>(0.0, w);\n        auto exp0 = exp(iw*(x0+1));\n        auto exp1 = exp(iw*(x1+1));\n        auto exp10 = exp(iw*(x1-x0));\n        Ik[0] = (exp1 - exp0)/iw;\n        //Ik[0] = (exp10 - 1) * exp0 /iw;\n\n        auto dx_k = dx;\n        for (int k=1; k<K+1; ++k) {\n            Ik[k] = (dx_k * exp1 - static_cast<T>(k) * Ik[k-1])/iw;\n            dx_k *= dx;\n        }\n    }\n\n\n/**\n * Compute integral of exponential functions and given piecewise polynomials\n *           \\int dx exp(i w_i (x+1)) p_j(x),\n *           where w_i are given real double objects and p_j are piecewise polynomials.\n * @tparam T  scalar type of piecewise polynomials\n * @param w vector of w_i in ascending order\n * @param statis Statistics (fermion or boson)\n * @param p vector of piecewise polynomials.\n * @param results  computed results\n */\n    template<typename T, typename Tx>\n    void compute_integral_with_exp(\n            const std::vector<T> &w,\n            const std::vector<piecewise_polynomial<T,Tx> > &pp_func,\n            Eigen::Tensor<std::complex<T>, 2> &Tnl\n    ) {\n        typedef std::complex<T> dcomplex;\n        typedef piecewise_polynomial<std::complex<T>,Tx> pp_type;\n        typedef Eigen::Matrix<std::complex<T>, Eigen::Dynamic, Eigen::Dynamic> ex_matrix_t;\n        typedef Eigen::Tensor<std::complex<T>, 2> tensor_t;\n\n        T pi = const_pi<T>();\n\n        //order of polynomials used for representing exponential functions internally.\n        const int k_iw = 16;//for debug\n        const int k = pp_func[0].order();\n        const int n_section = pp_func[0].num_sections();\n\n        std::vector<std::complex<T> > Ik(k+1);\n\n        for (int l = 0; l < pp_func.size(); ++l) {\n            if (k != pp_func[l].order()) {\n                throw std::runtime_error(\n                        \"Error in compute_transformation_matrix_to_matsubara: basis functions must be pieacewise polynomials of the same order\");\n            }\n            if (pp_func[l].section_edge(0) != 0 || pp_func[l].section_edge(n_section) != 1) {\n                throw std::runtime_error(\"Piecewise polynomials must be defined on [0,1]\");\n            }\n        }\n\n        const int n_iw = w.size();\n        const int n_max = n_iw - 1;\n\n        for (int i = 0; i < w.size() - 1; ++i) {\n            if (w[i] > w[i + 1]) {\n                throw std::runtime_error(\"w must be give in ascending order.\");\n            }\n        }\n\n        //Use Taylor expansion for exp(i w_n tau) for w_n*dx < cutoff*M_PI\n        const double cutoff = 0.1;\n\n        Eigen::Tensor<std::complex<T>,3> exp_coeffs(w.size(), n_section, k_iw + 1);\n        construct_exp_functions_coeff(w, pp_func[0].section_edges(), k_iw, exp_coeffs);\n\n        ex_matrix_t left_mid_matrix(n_iw, k + 1);\n        ex_matrix_t left_matrix(n_iw, k_iw + 1);\n        ex_matrix_t mid_matrix(k_iw + 1, k + 1);\n        ex_matrix_t right_matrix(k + 1, pp_func.size());\n        ex_matrix_t r(n_iw, pp_func.size());\n        r.setZero();\n\n        std::vector<T> dx_power(k + k_iw + 2);\n\n        for (int s = 0; s < n_section; ++s) {\n            auto x0 = pp_func[0].section_edge(s);\n            T dx = static_cast<T>(pp_func[0].section_edge(s + 1) - pp_func[0].section_edge(s));\n            left_mid_matrix.setZero();\n\n            dx_power[0] = 1.0;\n            for (int p = 1; p < dx_power.size(); ++p) {\n                dx_power[p] = dx * dx_power[p - 1];\n            }\n\n            //Use Taylor expansion for exp(i w_n tau) for w_n*dx < cutoff*M_PI\n            auto w_max_cs = cutoff * pi / dx;\n            int n_max_cs = -1;\n            for (int i = 0; i < w.size(); ++i) {\n                if (w[i] <= w_max_cs) {\n                    n_max_cs = i;\n                }\n            }\n\n            //Use Taylor expansion\n            if (n_max_cs >= 0) {\n                for (int p = 0; p < k_iw + 1; ++p) {\n                    for (int p2 = 0; p2 < k + 1; ++p2) {\n                        mid_matrix(p, p2) = dx_power[p + p2 + 1] / (p + p2 + 1.0);\n                    }\n                }\n\n                for (int n = 0; n < n_max_cs + 1; ++n) {\n                    for (int p = 0; p < k_iw + 1; ++p) {\n                        left_matrix(n, p) = exp_coeffs(n,s,p);\n                    }\n                }\n\n                left_mid_matrix.block(0, 0, n_max_cs + 1, k + 1) =\n                        left_matrix.block(0, 0, n_max_cs + 1, k_iw + 1) * mid_matrix;\n            }\n\n            //Otherwise, compute the overlap exactly\n            for (int n = std::max(n_max_cs + 1, 0); n <= n_max; ++n) {\n                compute_Ik(x0, dx, w[n], k, Ik);\n                for (int i=0; i<k+1; ++i) {\n                    left_mid_matrix(n, i) = Ik[i];\n                }\n            }\n\n            for (int l = 0; l < pp_func.size(); ++l) {\n                for (int p2 = 0; p2 < k + 1; ++p2) {\n                    right_matrix(p2, l) = static_cast<T>(pp_func[l].coefficient(s, p2));\n                }\n            }\n\n            r += left_mid_matrix * right_matrix;\n        }\n\n        Tnl = tensor_t(n_iw, pp_func.size());\n        for (int n = 0; n < n_iw; ++n) {\n            for (int l = 0; l < pp_func.size(); ++l) {\n                Tnl(n, l) = r(n, l);\n            }\n        }\n    }\n\n\n    /**\n    * Compute a transformation matrix from a give orthogonal basis set to Matsubara freq.\n    * @tparam T  scalar type\n    * @tparam Tx  scalar type for x in [-1,1]\n    * @param n_vec indices of Matsubara frequqneices for which matrix elements will be computed (in strictly ascending order).\n    *          The Matsubara basis functions look like exp(i PI * (n[i]+1/2)) for fermions, exp(i PI * n[i]) for bosons.\n    * @param bf_src orthogonal basis functions on [-1,1]. They must be piecewise polynomials of the same order. Piecewise polynomial representations on [0,1] must be provided.\n    *               Basis functions u_l(x) are assumed to be even or odd for even l and odd l, respectively.\n    * @param Tnl  computed transformation matrix, results are cast into double\n    */\n    template<typename T, typename Tx>\n    void compute_transformation_matrix_to_matsubara(\n            const std::vector<long> &n_vec,\n            irlib::statistics::statistics_type statis,\n            const std::vector<piecewise_polynomial<T,Tx> > &bf_src,\n            Eigen::Tensor<std::complex<double>, 2> &Tnl\n    ) {\n        typedef std::complex<double> dcomplex;\n        typedef Eigen::Matrix<std::complex<T>, Eigen::Dynamic, Eigen::Dynamic> matrix_t;\n        typedef Eigen::Tensor<std::complex<T>, 2> tensor_t;\n\n        int Nl = bf_src.size();\n        auto pi = const_pi<T>();\n\n        if (n_vec.size() == 0) {\n            return;\n        }\n\n        for (int i = 0; i < n_vec.size() - 1; ++i) {\n            if (n_vec[i] > n_vec[i + 1]) {\n                throw std::runtime_error(\"n_vec must be in strictly ascending order!\");\n            }\n        }\n\n        if (n_vec[0] < 0) {\n            throw std::runtime_error(\"n_vec cannot be negative!\");\n        }\n\n        long offset = (statis == statistics::FERMIONIC ? 1 : 0);\n\n        // compute tails\n        int sign_s = (statis == statistics::FERMIONIC ? -1 : 1);\n        // even number close to (bf_src[0].order()/2\n        int num_tail = std::min(2*(bf_src[0].order()/2), 4);\n        if (num_tail < 4) {\n            throw std::runtime_error(\"num_tail < 4.\");\n        }\n        Eigen::Matrix<std::complex<T>,Eigen::Dynamic,Eigen::Dynamic> tails(bf_src.size(), num_tail);\n        const std::complex<T> zi(0.0, 1.0);\n        for (int l=0; l<bf_src.size(); ++l) {\n            auto ztmp = zi;\n            for (int m=0; m<num_tail; ++m) {\n                int sign_lm = (l+m)%2==0 ? 1 : -1;\n                tails(l,m) = - sqrt(T(2.0)) * pow(T(2), m) * ztmp * static_cast<T>((sign_s - sign_lm) * bf_src[l].derivative(1, m));\n                ztmp *= zi;\n            }\n        }\n\n        // Determine for which Matsubara frequencies tail is used\n        // Store those indices in ovec\n        std::vector<int> num_low_freq(Nl);\n        double eps = 1e-8;\n        for (int l=0; l<Nl; ++l) {\n            int m_low = (l+offset-1)%2==0 ?  0 : 1;\n            int m_high = (l+offset-1)%2==0 ?  num_tail-2 : num_tail-1;\n            auto wn_limit = pow(eps * abs(tails(l,m_low)/tails(l,m_high)), 1.0/(m_low-m_high) );\n            auto n_limit = 0.5*(wn_limit/pi-offset);\n\n            num_low_freq[l] = std::count_if(n_vec.begin(), n_vec.end(), [&](long n){return n < n_limit;});\n        }\n        auto max_num_low_freq = *std::max_element(num_low_freq.begin(), num_low_freq.end());\n        auto last = n_vec.begin();\n        std::advance(last, max_num_low_freq);\n        std::vector<long> ovec;\n        std::transform(n_vec.begin(), last, std::back_inserter(ovec), [&](long n){return 2*n+offset;});\n\n        // Compute Tnl\n        Eigen::Tensor<std::complex<T>, 2> Tnl_low_freq;\n        compute_Tbar_ol(ovec, bf_src, Tnl_low_freq);\n        Tnl = Eigen::Tensor<std::complex<double>,2>(n_vec.size(), bf_src.size());\n        Tnl.setZero();\n        for(int l=0; l<Nl; ++l) {\n            for(int i=0; i<max_num_low_freq; ++i) {\n                Tnl(i,l) = to_dcomplex(Tnl_low_freq(i,l));\n            }\n        }\n\n        // Relace with tail\n        for (int l=0; l<Nl; ++l) {\n            for (int i=num_low_freq[l]; i<n_vec.size(); ++i) {\n                double wn = (2*n_vec[i]+offset) * M_PI;\n                Tnl(i, l) = 0.0;\n                for (int m=0; m<num_tail; ++m) {\n                    Tnl(i, l) += to_dcomplex(tails(l,m)/pow(wn, m+1));\n                }\n            }\n        }\n\n    }\n\n\n    /**\n    * Compute a transformation matrix (\\bar{T}_{nl}) from a give orthogonal basis set to Matsubara freq.\n    * @tparam T  scalar type\n    * @tparam Tx  scalar type for x \\in [-1, 1]\n    * @param n indices of Matsubara frequqneices for which matrix elements will be computed (in strictly ascending order).\n    *          The Matsubara basis functions look like exp(i PI * (n[i]/2) * (x+1)).\n    * @param bf_src orthogonal basis functions on [-1,1]. They must be piecewise polynomials of the same order. Piecewise polynomial representations on [0,1] must be provided.\n    *               Basis functions u_l(x) are assumed to be even or odd for even l and odd l, respectively.\n    * @param Tnl  computed transformation matrix\n    */\n    template<typename T, typename Tx>\n    void compute_Tbar_ol(\n            const std::vector<long> &o_vec,\n            const std::vector<irlib::piecewise_polynomial<T,Tx>> &bf_src,\n            Eigen::Tensor<std::complex<T>, 2> &Tbar_ol\n    ) {\n        typedef std::complex<T> dcomplex;\n        typedef Eigen::Matrix<std::complex<T>, Eigen::Dynamic, Eigen::Dynamic> matrix_t;\n        typedef Eigen::Tensor<std::complex<T>, 2> tensor_t;\n\n        if (o_vec.size() == 0) {\n            return;\n        }\n\n        for (int i = 0; i < o_vec.size() - 1; ++i) {\n            if (o_vec[i] > o_vec[i + 1]) {\n                throw std::runtime_error(\"o must be given in strictly ascending order!\");\n            }\n        }\n\n        std::vector<T> w;\n        std::transform(o_vec.begin(), o_vec.end(), std::back_inserter(w), [](long o) { return 0.5 * M_PI * o; });\n\n        compute_integral_with_exp(w, bf_src, Tbar_ol);\n\n        for (int l=0; l<bf_src.size(); ++l) {\n            for (int i=0; i<o_vec.size(); ++i) {\n                if ( (l+o_vec[i])%2 == 0) {\n                    Tbar_ol(i,l) = 2 * Tbar_ol(i,l).real();\n                } else {\n                    Tbar_ol(i,l) = std::complex<T>(0.0, 2 * Tbar_ol(i,l).imag());\n                }\n            }\n        }\n\n        std::vector<T> inv_norm(bf_src.size());\n        for (int l = 0; l < bf_src.size(); ++l) {\n            inv_norm[l] = 1. / sqrt(2*bf_src[l].overlap(bf_src[l]));\n        }\n        for (int n = 0; n < w.size(); ++n) {\n            for (int l = 0; l < bf_src.size(); ++l) {\n                Tbar_ol(n, l) *= inv_norm[l] * sqrt(static_cast<T>(0.5));\n            }\n        }\n    }\n\n\n    /**\n     * Find approximate positions of nodes for the even singular vectors with the lowest singular value larger than a cutoff\n     * @tparam Kernel kernel type\n     * @param knl Kernel object\n     * @param N Number of points for discretizing the kernel\n     * @param cutoff_singular_values smallest relative singular value\n     * @return positions of nodes\n     */\n    template<typename Kernel>\n    std::pair<std::vector<double>,std::vector<double>>\n    compute_approximate_nodes_even_sector(const Kernel &knl, int N, double cutoff_singular_values) {\n        typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> matrix_t;\n\n        double de_cutoff = 2.5;\n\n        //DE mesh for x\n        std::vector<double> tx_vec = linspace<double>(0.0, de_cutoff, N);\n        std::vector<double> weight_x(N), x_vec(N);\n        for (int i = 0; i < N; ++i) {\n            x_vec[i] = std::tanh(0.5 * M_PI * std::sinh(tx_vec[i]));\n            //sqrt of the weight of DE formula\n            weight_x[i] =\n                    std::sqrt(0.5 * M_PI * std::cosh(tx_vec[i])) / std::cosh(0.5 * M_PI * std::sinh(tx_vec[i]));\n        }\n\n        //DE mesh for y\n        std::vector<double> ty_vec = linspace<double>(-de_cutoff, 0.0, N);\n        std::vector<double> y_vec(N), weight_y(N);\n        for (int i = 0; i < N; ++i) {\n            y_vec[i] = std::tanh(0.5 * M_PI * std::sinh(ty_vec[i])) + 1.0;\n            //sqrt of the weight of DE formula\n            weight_y[i] =\n                    std::sqrt(0.5 * M_PI * std::cosh(ty_vec[i])) / std::cosh(0.5 * M_PI * std::sinh(ty_vec[i]));\n        }\n\n        matrix_t K(N, N);\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                K(i, j) = weight_x[i] * static_cast<double>(knl(x_vec[i], y_vec[j]) + knl(x_vec[i], -y_vec[j])) *\n                          weight_y[j];\n            }\n        }\n\n        //Perform SVD\n        Eigen::BDCSVD<matrix_t> svd(K, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        const Eigen::VectorXd& svalues = svd.singularValues();\n        const matrix_t& U = svd.matrixU();\n        const matrix_t& V = svd.matrixV();\n\n        //Count non-zero SV\n        int dim = N;\n        for (int i = 1; i < N; ++i) {\n            if (std::abs(svalues(i) / svalues(0)) < cutoff_singular_values) {\n                dim = i;\n                break;\n            }\n        }\n\n        //find nodes\n        std::vector<double> nodes_x, nodes_y;\n        for (int i = 0; i < N - 1; ++i) {\n            if (U(i, dim - 1) * U(i + 1, dim - 1) < 0.0) {\n                nodes_x.push_back(0.5 * (x_vec[i] + x_vec[i + 1]));\n            }\n            if (V(i, dim - 1) * V(i+1, dim - 1) < 0.0) {\n                nodes_y.push_back(0.5 * (y_vec[i] + y_vec[i + 1]));\n            }\n        }\n\n        if (nodes_x.size() != dim - 1 || nodes_y.size() != dim - 1) {\n            std::cerr << \"The number of nodes for x is \" << nodes_x.size() << \" , which is different from l \" << dim-1 << std::endl;\n            std::cerr << \"The number of nodes for y is \" << nodes_y.size() << \" , which is different from l \" << dim-1 << std::endl;\n            for (auto n : nodes_y) {\n                std::cout << n << std::endl;\n            }\n            throw std::runtime_error(\"The number of nodes is wrong.\");\n        }\n\n        return std::make_pair(nodes_x, nodes_y);\n    }\n\n/**\n *  Compute \\int_{-1}^1 dx exp(i w x) p(x)\n**/\n/*\n    inline std::vector<std::complex<mpfr::mpreal>>\n    compute_Tnl_impl(const std::vector<piecewise_polynomial<mpreal,mpreal>>& p,\n                                                       std::vector<mpreal>& w_vec,\n                                                       int digits) {\n        auto prec_bak = mpfr::mpreal::get_default_prec();\n\n        mpfr::mpreal::set_default_prec(mpfr::digits2bits(digits));\n\n        int num_local_nodes = 24;\n        auto local_nodes = detail::gauss_legendre_nodes<mpreal>(num_local_nodes);\n        std::vector<mpreal> section_edges = p.section_edges();\n        auto global_nodes = composite_gauss_legendre_nodes(section_edges, local_nodes);\n        auto n_local_nodes = local_nodes.size();\n\n        std::vector<mpreal> values(global_nodes.size());\n        for (int n=0; n<global_nodes.(); ++n) {\n            values[n] = p.compute_value(global_nodes[n].first);\n        }\n\n        auto num_sections = p.num_sections();\n        auto n_poly = p.order()+1;\n        std::vector<mpreal> deriv_values_left(num_sections*n_poly), deriv_values_left(num_sections*n_poly);\n        for (int s=0; s<num_sections; s++) {\n            for (int k=0; k<n_poly; ++k) {\n                deriv_values_left[k + s*n_poly] = p.derivative(p.section_edge(s), k, s);\n                deriv_values_right[k + s*n_poly] = p.derivative(p.section_edge(s+1), k, s);\n            }\n        }\n\n        std::vector<std::complex<mpreal>> result(w_vec.size());\n        for (int i=0; i < w_vec.size(); ++i) {\n            result[i] = 0;\n\n            for (int s = 0; s < p.num_sections(); ++s) {\n                mpreal x0 = p.section_edge(s);\n                mpreal x1 = p.section_edge(s+1);\n\n                if (w * (x1-x0) < 0.1 * const_pi<mpreal>()){\n                    std::complex<mpreal> tmp(0);\n                    for (int n = 0; n < n_local_nodes; ++n) {\n                        tmp += values(s*n_local_nodes + n) * my_exp(w*x_smpl) * global_nodes[s*n_local_nodes + n].second;\n                    }\n                    result[i] += tmp;\n                } else {\n                    std::complex<mpreal> Jk(0, 0);\n                    std::complex<mpreal> iw(0, w);\n                    std::complex<mpreal> exp0 = my_exp(w*x0);\n                    std::complex<mpreal> exp_tmp = my_exp(w*(x1-x0));\n\n                    //p contains x^0, x^1, xj^2, ..., x^K (K = p.order())\n                    for (int k=p.order(); k >= 0; --k) {\n                        mpreal f0 = deriv_values_left[k + s*n_poly];\n                        mpreal f1 = deriv_values_right[k + s*n_poly];\n                        Jk = ((exp_tmp * f1 - f0) * exp0 - Jk)/iw;\n                    }\n                    result[i] += Jk;\n                }\n            }\n\n            if (even) {\n                result[i] = mpfr::sqrt(2) * result[i].real() * my_exp(w);\n            } else {\n                result[i] = mpfr::sqrt(2) * std::complex<mpreal>(0, result[i].imag()) * my_exp(w);\n            }\n        }\n\n        mpfr::mpreal::set_default_prec(prec_bak);\n\n        return result;\n    }\n    */\n\n\n    inline std::complex<mpreal> compute_Tnl_tail(const piecewise_polynomial<mpreal,mpreal>& p,\n                                   mpreal w,\n                                   bool l_even,\n                                   irlib::statistics::statistics_type s,\n                                   int num_deriv) {\n        int sign_s = (s == irlib::statistics::BOSONIC ? 1 : -1);\n\n        if (w == 0.0) {\n            throw std::runtime_error(\"Error zero frequency\");\n        }\n\n        std::complex<mpreal> result(0);\n        std::complex<mpreal> fact(0, 1/w);\n        std::complex<mpreal> coeff(fact);\n        int sign_l = l_even ? 1 : -1;\n        for (int m = 0; m < num_deriv; ++m) {\n            int sign_m = m%2 == 0 ? 1 : -1;\n            int sign_lm = sign_l * sign_m;\n            result += -static_cast<mpreal>(sign_s) * coeff * static_cast<mpreal>(1 - sign_s * sign_lm) * p.derivative(1, m);\n            coeff *= fact;\n        }\n\n        return result/mpfr::sqrt(2);\n    }\n\n/**\n *  Compute \\int_{-1}^1 dx exp(i w x) p(x)\n**/\n    inline std::complex<mpfr::mpreal> compute_Tnl_impl(const piecewise_polynomial<mpreal,mpreal>& p, bool even,\n                                                       irlib::statistics::statistics_type s, mpreal w,\n                                                       int digits_A = 30, int digits_B = 30) {\n        auto prec_bak = mpfr::mpreal::get_default_prec();\n\n        int num_local_nodes = 24;\n        auto local_nodes = detail::gauss_legendre_nodes<mpreal>(num_local_nodes);\n        std::vector<mpreal> section_edges = p.section_edges();\n        auto global_nodes = composite_gauss_legendre_nodes(section_edges, local_nodes);\n        auto n_local_nodes = local_nodes.size();\n\n        std::complex<mpreal> result(0);\n        for (int s = 0; s < p.num_sections(); ++s) {\n            mpreal x0 = p.section_edge(s);\n            mpreal x1 = p.section_edge(s+1);\n\n            if (w * (x1-x0) < 0.1 * const_pi<mpreal>()){\n                // using low-frequency formula (Gauss-Legendre quadrature)\n                mpfr::mpreal::set_default_prec(mpfr::digits2bits(digits_A));\n                std::complex<mpreal> tmp(0);\n                for (int n = 0; n < n_local_nodes; ++n) {\n                    auto x_smpl = global_nodes[s*n_local_nodes + n].first;\n                    tmp += p.compute_value(x_smpl) * my_exp(w*x_smpl) * global_nodes[s*n_local_nodes + n].second;\n                }\n                result += tmp;\n            } else {\n                // using low-frequency formula (Gauss-Legendre quadrature)\n                mpfr::mpreal::set_default_prec(mpfr::digits2bits(digits_B));\n                std::complex<mpreal> Jk(0, 0);\n                std::complex<mpreal> iw(0, w);\n                std::complex<mpreal> exp0 = my_exp(w*x0);\n                std::complex<mpreal> exp_tmp = my_exp(w*(x1-x0));\n\n                //p contains x^0, x^1, xj^2, ..., x^K (K = p.order())\n                for (int k=p.order(); k >= 0; --k) {\n                    mpreal f0 = p.derivative(x0, k, s);\n                    mpreal f1 = p.derivative(x1, k, s);\n                    Jk = ((exp_tmp * f1 - f0) * exp0 - Jk)/iw;\n                }\n                result += Jk;\n            }\n        }\n\n        if (even) {\n            result = mpfr::sqrt(2) * result.real() * my_exp(w);\n        } else {\n            result = mpfr::sqrt(2) * std::complex<mpreal>(0, result.imag()) * my_exp(w);\n        }\n\n        // replace with tail\n        if (w != 0.0) {\n            int num_deriv = p.order()+1;\n            auto tail_full = compute_Tnl_tail(p, w, even, s, num_deriv);\n            auto tail_two_less = compute_Tnl_tail(p, w, even, s, num_deriv-2);\n            if (std::abs((tail_full-tail_two_less)/tail_full) < 1e-12) {\n                result = tail_full;\n            }\n        }\n\n        mpfr::mpreal::set_default_prec(prec_bak);\n\n        return result;\n    }\n\n}\n", "meta": {"hexsha": "cb6ef93bcc9e993dc4de8034e2c174c35c784b0c", "size": 51351, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "c++/include/irlib/detail/basis_impl.ipp", "max_stars_repo_name": "dombrno/irlib", "max_stars_repo_head_hexsha": "c081ac6af6d0f80424e6f3651f02ce5028942e0e", "max_stars_repo_licenses": ["MIT"], "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++/include/irlib/detail/basis_impl.ipp", "max_issues_repo_name": "dombrno/irlib", "max_issues_repo_head_hexsha": "c081ac6af6d0f80424e6f3651f02ce5028942e0e", "max_issues_repo_licenses": ["MIT"], "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++/include/irlib/detail/basis_impl.ipp", "max_forks_repo_name": "dombrno/irlib", "max_forks_repo_head_hexsha": "c081ac6af6d0f80424e6f3651f02ce5028942e0e", "max_forks_repo_licenses": ["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.6901743265, "max_line_length": 184, "alphanum_fraction": 0.5223656793, "num_tokens": 13792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.541394401796568}}
{"text": "#include <elasty/constraint.hpp>\n#include <elasty/particle.hpp>\n#include <algorithm>\n#include <cstring>\n#include <Eigen/Geometry>\n\nnamespace\n{\n    inline Eigen::Matrix3d convert_vector_to_cross_operator(const Eigen::Vector3d& vec)\n    {\n        Eigen::Matrix3d mat = Eigen::Matrix3d::Zero();\n        mat(0, 1) = + vec(2);\n        mat(0, 2) = - vec(1);\n        mat(1, 0) = - vec(2);\n        mat(1, 2) = + vec(0);\n        mat(2, 0) = + vec(1);\n        mat(2, 1) = - vec(0);\n        return mat;\n    };\n\n    inline double calculateCotTheta(const Eigen::Vector3d& x, const Eigen::Vector3d& y)\n    {\n        const double cos_theta = x.dot(y);\n        const double sin_theta = x.cross(y).norm();\n        return cos_theta / sin_theta;\n    }\n\n    template<int Num>\n    void projectPositions(const double C,\n                          const Eigen::Matrix<double, Num * 3, 1>& grad_C,\n                          const Eigen::Matrix<double, Num * 3, 1>& inv_M,\n                          const double stiffness,\n                          std::vector<std::shared_ptr<elasty::Particle>>& particles)\n    {\n        // Skip if the gradient is sufficiently small\n        if (grad_C.isApprox(Eigen::Matrix<double, Num * 3, 1>::Zero())) { return; }\n\n        // Calculate $s$\n        const double s = C / (grad_C.transpose() * inv_M.asDiagonal() * grad_C);\n\n        // Calculate $\\Delta x$\n        const Eigen::Matrix<double, Num * 3, 1> delta_x = - s * inv_M.asDiagonal() * grad_C;\n        assert(!delta_x.hasNaN());\n\n        // Update predicted positions\n        for (unsigned int j = 0; j < Num; ++ j)\n        {\n            particles[j]->p += stiffness * delta_x.segment(3 * j, 3);\n        }\n    }\n\n    template<int Num>\n    Eigen::Matrix<double, Num * 3, 1> constructInverseMassMatrix(const std::vector<std::shared_ptr<elasty::Particle>>& particles)\n    {\n        Eigen::Matrix<double, Num * 3, 1> inv_M;\n        for (unsigned int j = 0; j < Num; ++ j)\n        {\n            inv_M(j * 3 + 0) = particles[j]->w;\n            inv_M(j * 3 + 1) = particles[j]->w;\n            inv_M(j * 3 + 2) = particles[j]->w;\n        }\n        return inv_M;\n    }\n}\n\nelasty::BendingConstraint::BendingConstraint(const std::shared_ptr<Particle> p_0,\n                                             const std::shared_ptr<Particle> p_1,\n                                             const std::shared_ptr<Particle> p_2,\n                                             const std::shared_ptr<Particle> p_3,\n                                             const double stiffness,\n                                             const double dihedral_angle) :\nConstraint(std::vector<std::shared_ptr<Particle>>{ p_0, p_1, p_2, p_3 }, stiffness),\nm_dihedral_angle(dihedral_angle)\n{\n}\n\nvoid elasty::BendingConstraint::projectParticles()\n{\n    const double C = calculateValue();\n\n    Eigen::Matrix<double, 12, 1> grad_C;\n    calculateGrad(grad_C.data());\n\n    projectPositions<4>(C, grad_C, m_inv_M, m_stiffness, m_particles);\n}\n\ndouble elasty::BendingConstraint::calculateValue()\n{\n    const Eigen::Vector3d& x_0 = m_particles[0]->p;\n    const Eigen::Vector3d& x_1 = m_particles[1]->p;\n    const Eigen::Vector3d& x_2 = m_particles[2]->p;\n    const Eigen::Vector3d& x_3 = m_particles[3]->p;\n\n    const Eigen::Vector3d p_10 = x_1 - x_0;\n    const Eigen::Vector3d p_20 = x_2 - x_0;\n    const Eigen::Vector3d p_30 = x_3 - x_0;\n\n    const Eigen::Vector3d n_0 = p_10.cross(p_20).normalized();\n    const Eigen::Vector3d n_1 = p_10.cross(p_30).normalized();\n\n    assert(!n_0.hasNaN());\n    assert(!n_1.hasNaN());\n\n    const double current_dihedral_angle = std::acos(std::min(+ 1.0, std::max(- 1.0, n_0.dot(n_1))));\n\n    assert(!std::isnan(current_dihedral_angle));\n\n    return current_dihedral_angle - m_dihedral_angle;\n}\n\nvoid elasty::BendingConstraint::calculateGrad(double* grad_C)\n{\n    const Eigen::Vector3d& x_0 = m_particles[0]->p;\n    const Eigen::Vector3d& x_1 = m_particles[1]->p;\n    const Eigen::Vector3d& x_2 = m_particles[2]->p;\n    const Eigen::Vector3d& x_3 = m_particles[3]->p;\n\n    // Assuming that p_0 = [ 0, 0, 0 ]^T without loss of generality\n    const Eigen::Vector3d p_1 = x_1 - x_0;\n    const Eigen::Vector3d p_2 = x_2 - x_0;\n    const Eigen::Vector3d p_3 = x_3 - x_0;\n\n    const Eigen::Vector3d p_1_cross_p_2 = p_1.cross(p_2);\n    const Eigen::Vector3d p_1_cross_p_3 = p_1.cross(p_3);\n\n    const Eigen::Vector3d n_0 = p_1_cross_p_2.normalized();\n    const Eigen::Vector3d n_1 = p_1_cross_p_3.normalized();\n\n    const double d = n_0.dot(n_1);\n\n    // If the dihedral angle is sufficiently small, return zeros\n    constexpr double epsilon = 1e-12;\n    if (std::abs(d) - 1.0 < epsilon)\n    {\n        std::fill(grad_C, grad_C + 12, 0.0);\n        return;\n    }\n\n    const double common_coeff = - 1.0 / std::sqrt(1.0 - d * d);\n\n    auto calculate_gradient_of_normalized_cross_product_wrt_p_1 = [](const Eigen::Vector3d& p_1,\n                                                                     const Eigen::Vector3d& p_2,\n                                                                     const Eigen::Vector3d& n)\n    -> Eigen::Matrix3d\n    {\n        return + (1.0 / p_1.cross(p_2).norm()) * (- convert_vector_to_cross_operator(p_2) + n * (n.cross(p_2)).transpose());\n    };\n\n    auto calculate_gradient_of_normalized_cross_product_wrt_p_2 = [](const Eigen::Vector3d& p_1,\n                                                                     const Eigen::Vector3d& p_2,\n                                                                     const Eigen::Vector3d& n)\n    -> Eigen::Matrix3d\n    {\n        return - (1.0 / p_1.cross(p_2).norm()) * (- convert_vector_to_cross_operator(p_1) + n * (n.cross(p_1)).transpose());\n    };\n\n    const Eigen::Vector3d grad_C_wrt_p_1 = common_coeff * (calculate_gradient_of_normalized_cross_product_wrt_p_1(n_0, p_1, p_2).transpose() * n_1 + calculate_gradient_of_normalized_cross_product_wrt_p_1(n_1, p_1, p_3).transpose() * n_0);\n    const Eigen::Vector3d grad_C_wrt_p_2 = common_coeff * calculate_gradient_of_normalized_cross_product_wrt_p_2(n_0, p_1, p_2).transpose() * n_1;\n    const Eigen::Vector3d grad_C_wrt_p_3 = common_coeff * calculate_gradient_of_normalized_cross_product_wrt_p_2(n_1, p_1, p_3).transpose() * n_0;\n    const Eigen::Vector3d grad_C_wrt_p_0 = - grad_C_wrt_p_1 - grad_C_wrt_p_2 - grad_C_wrt_p_3;\n\n    std::memcpy(grad_C + (3 * 0), grad_C_wrt_p_0.data(), sizeof(double) * 3);\n    std::memcpy(grad_C + (3 * 1), grad_C_wrt_p_1.data(), sizeof(double) * 3);\n    std::memcpy(grad_C + (3 * 2), grad_C_wrt_p_2.data(), sizeof(double) * 3);\n    std::memcpy(grad_C + (3 * 3), grad_C_wrt_p_3.data(), sizeof(double) * 3);\n}\n\nelasty::DistanceConstraint::DistanceConstraint(const std::shared_ptr<Particle> p_0,\n                                               const std::shared_ptr<Particle> p_1,\n                                               const double stiffness,\n                                               const double d) :\nConstraint(std::vector<std::shared_ptr<Particle>>{ p_0, p_1 }, stiffness),\nm_inv_M(constructInverseMassMatrix<2>(m_particles)),\nm_d(d)\n{\n    assert(d >= 0.0);\n}\n\nvoid elasty::DistanceConstraint::projectParticles()\n{\n    const double C = calculateValue();\n\n    Eigen::Matrix<double, 6, 1> grad_C;\n    calculateGrad(grad_C.data());\n\n    projectPositions<2>(C, grad_C, m_inv_M, m_stiffness, m_particles);\n}\n\ndouble elasty::DistanceConstraint::calculateValue()\n{\n    const Eigen::Vector3d& x_0 = m_particles[0]->p;\n    const Eigen::Vector3d& x_1 = m_particles[1]->p;\n\n    return (x_0 - x_1).norm() - m_d;\n}\n\nvoid elasty::DistanceConstraint::calculateGrad(double* grad_C)\n{\n    const Eigen::Vector3d& x_0 = m_particles[0]->p;\n    const Eigen::Vector3d& x_1 = m_particles[1]->p;\n\n    Eigen::Vector3d n = (x_0 - x_1).normalized();\n\n    if (n.hasNaN()) { n = Eigen::Vector3d::Random(3).normalized(); }\n\n    grad_C[0] = + n(0);\n    grad_C[1] = + n(1);\n    grad_C[2] = + n(2);\n    grad_C[3] = - n(0);\n    grad_C[4] = - n(1);\n    grad_C[5] = - n(2);\n}\n\nelasty::EnvironmentalCollisionConstraint::EnvironmentalCollisionConstraint(const std::shared_ptr<Particle> p_0,\n                                                                           const double stiffness,\n                                                                           const Eigen::Vector3d& n,\n                                                                           const double d) :\nConstraint(std::vector<std::shared_ptr<Particle>>{ p_0 }, stiffness),\nm_inv_M(constructInverseMassMatrix<1>(m_particles)),\nm_n(n),\nm_d(d)\n{\n}\n\nvoid elasty::EnvironmentalCollisionConstraint::projectParticles()\n{\n    const double C = calculateValue();\n\n    if (C >= 0.0) { return; }\n\n    Eigen::Vector3d grad_C;\n    calculateGrad(grad_C.data());\n\n    projectPositions<1>(C, grad_C, m_inv_M, m_stiffness, m_particles);\n}\n\ndouble elasty::EnvironmentalCollisionConstraint::calculateValue()\n{\n    const Eigen::Vector3d& x = m_particles[0]->p;\n    return m_n.transpose() * x - m_d;\n}\n\nvoid elasty::EnvironmentalCollisionConstraint::calculateGrad(double* grad_C)\n{\n    std::memcpy(grad_C, m_n.data(), sizeof(double) * 3);\n}\n\nelasty::FixedPointConstraint::FixedPointConstraint(const std::shared_ptr<Particle> p_0,\n                                                   const double stiffness,\n                                                   const Eigen::Vector3d& point) :\nConstraint(std::vector<std::shared_ptr<Particle>>{ p_0 }, stiffness),\nm_inv_M(constructInverseMassMatrix<1>(m_particles)),\nm_point(point)\n{\n}\n\nvoid elasty::FixedPointConstraint::projectParticles()\n{\n    const double C = calculateValue();\n\n    Eigen::Vector3d grad_C;\n    calculateGrad(grad_C.data());\n\n    projectPositions<1>(C, grad_C, m_inv_M, m_stiffness, m_particles);\n}\n\ndouble elasty::FixedPointConstraint::calculateValue()\n{\n    const Eigen::Vector3d& x = m_particles[0]->p;\n    return (x - m_point).norm();\n}\n\nvoid elasty::FixedPointConstraint::calculateGrad(double* grad_C)\n{\n    const Eigen::Vector3d& x = m_particles[0]->p;\n    const Eigen::Vector3d n = (x - m_point).normalized();\n\n    if (n.hasNaN()) { std::fill(grad_C, grad_C + 3, 0.0); }\n\n    std::memcpy(grad_C, n.data(), sizeof(double) * 3);\n}\n\nelasty::IsometricBendingConstraint::IsometricBendingConstraint(const std::shared_ptr<Particle> p_0,\n                                                               const std::shared_ptr<Particle> p_1,\n                                                               const std::shared_ptr<Particle> p_2,\n                                                               const std::shared_ptr<Particle> p_3,\n                                                               const double stiffness) :\nConstraint(std::vector<std::shared_ptr<Particle>>{ p_0, p_1, p_2, p_3 }, stiffness),\nm_inv_M(constructInverseMassMatrix<4>(m_particles))\n{\n    const Eigen::Vector3d& x_0 = p_0->x;\n    const Eigen::Vector3d& x_1 = p_1->x;\n    const Eigen::Vector3d& x_2 = p_2->x;\n    const Eigen::Vector3d& x_3 = p_3->x;\n\n    const Eigen::Vector3d e0 = x_1 - x_0;\n    const Eigen::Vector3d e1 = x_2 - x_1;\n    const Eigen::Vector3d e2 = x_0 - x_2;\n    const Eigen::Vector3d e3 = x_3 - x_0;\n    const Eigen::Vector3d e4 = x_1 - x_3;\n\n    const double cot_01 = calculateCotTheta(e0, - e1);\n    const double cot_02 = calculateCotTheta(e0, - e2);\n    const double cot_03 = calculateCotTheta(e0, e3);\n    const double cot_04 = calculateCotTheta(e0, e4);\n\n    const Eigen::Vector4d K = Eigen::Vector4d(cot_01 + cot_04, cot_02 + cot_03, - cot_01 - cot_02, - cot_03 - cot_04);\n\n    const double A_0 = 0.5 * e0.cross(e1).norm();\n    const double A_1 = 0.5 * e0.cross(e3).norm();\n\n    m_Q = (3.0 / (A_0 + A_1)) * K * K.transpose();\n}\n\nvoid elasty::IsometricBendingConstraint::projectParticles()\n{\n    const double C = calculateValue();\n\n    Eigen::Matrix<double, 12, 1> grad_C;\n    calculateGrad(grad_C.data());\n\n    projectPositions<4>(C, grad_C, m_inv_M, m_stiffness, m_particles);\n}\n\ndouble elasty::IsometricBendingConstraint::calculateValue()\n{\n    double sum = 0.0;\n    for (unsigned int i = 0; i < 4; ++ i)\n    {\n        for (unsigned int j = 0; j < 4; ++ j)\n        {\n            sum += m_Q(i, j) * double(m_particles[i]->p.transpose() * m_particles[j]->p);\n        }\n    }\n    return 0.5 * sum;\n}\n\nvoid elasty::IsometricBendingConstraint::calculateGrad(double* grad_C)\n{\n    for (unsigned int i = 0; i < 4; ++ i)\n    {\n        Eigen::Vector3d sum = Eigen::Vector3d::Zero();\n        for (unsigned int j = 0; j < 4; ++ j)\n        {\n            sum += m_Q(i, j) * m_particles[j]->p;\n        }\n        std::memcpy(grad_C + (3 * i), sum.data(), sizeof(double) * 3);\n    }\n}\n", "meta": {"hexsha": "1b7ca6e27a1940cf99fb875535663143321fbc3f", "size": 12588, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/constraint.cpp", "max_stars_repo_name": "0x0c/elasty", "max_stars_repo_head_hexsha": "3995cacbefa8d7f39249e9f75fa291828e2e7c2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/constraint.cpp", "max_issues_repo_name": "0x0c/elasty", "max_issues_repo_head_hexsha": "3995cacbefa8d7f39249e9f75fa291828e2e7c2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/constraint.cpp", "max_forks_repo_name": "0x0c/elasty", "max_forks_repo_head_hexsha": "3995cacbefa8d7f39249e9f75fa291828e2e7c2d", "max_forks_repo_licenses": ["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.9657142857, "max_line_length": 238, "alphanum_fraction": 0.5887353035, "num_tokens": 3594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5413944009771885}}
{"text": "#include \"problem_generator.h\"\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <random>\n#include <vector>\n\nnamespace poselib {\n\nstatic const double kPI = 3.14159265358979323846;\n\ndouble CalibPoseValidator::compute_pose_error(const AbsolutePoseProblemInstance &instance, const CameraPose &pose,\n                                              double scale) {\n    return (instance.pose_gt.R() - pose.R()).norm() + (instance.pose_gt.t - pose.t).norm() +\n           std::abs(instance.scale_gt - scale);\n}\ndouble CalibPoseValidator::compute_pose_error(const RelativePoseProblemInstance &instance, const CameraPose &pose) {\n    return (instance.pose_gt.R() - pose.R()).norm() + (instance.pose_gt.t - pose.t).norm();\n}\n\nbool CalibPoseValidator::is_valid(const AbsolutePoseProblemInstance &instance, const CameraPose &pose, double scale,\n                                  double tol) {\n\n    // Point to point correspondences\n    // alpha * p + lambda*x = R*X + t\n    for (int i = 0; i < instance.x_point_.size(); ++i) {\n        double err = 1.0 - std::abs(instance.x_point_[i].dot(\n                               (pose.R() * instance.X_point_[i] + pose.t - scale * instance.p_point_[i]).normalized()));\n        if (err > tol)\n            return false;\n    }\n\n    // Point to Line correspondences\n    // alpha * p + lambda * x = R*(X + mu*V) + t\n    for (int i = 0; i < instance.x_line_.size(); ++i) {\n        // lambda * x - mu * R*V = R*X + t - alpha * p\n        // x.cross(R*V).dot(R*X+t-alpha.p) = 0\n        Eigen::Vector3d X = pose.R() * instance.X_line_[i] + pose.t - scale * instance.p_line_[i];\n        double err = instance.x_line_[i].cross(pose.R() * instance.V_line_[i]).normalized().dot(X);\n\n        if (err > tol)\n            return false;\n    }\n\n    // Line to point correspondences\n    // l'*(R*X + t - alpha*p) = 0\n    for (int i = 0; i < instance.l_line_point_.size(); ++i) {\n\n        Eigen::Vector3d X = pose.R() * instance.X_line_point_[i] + pose.t - scale * instance.p_line_point_[i];\n\n        double err = std::abs(instance.l_line_point_[i].dot(X.normalized()));\n        if (err > tol)\n            return false;\n    }\n\n    // Line to line correspondences\n    // l'*(R*(X + mu*V) + t - alpha*p) = 0\n    for (int i = 0; i < instance.l_line_line_.size(); ++i) {\n\n        Eigen::Vector3d X = pose.R() * instance.X_line_line_[i] + pose.t - scale * instance.p_line_line_[i];\n        Eigen::Vector3d V = pose.R() * instance.V_line_line_[i];\n\n        double err = std::abs(instance.l_line_line_[i].dot(X.normalized())) +\n                     std::abs(instance.l_line_line_[i].dot(V.normalized()));\n        if (err > tol)\n            return false;\n    }\n\n    return true;\n}\n\nbool CalibPoseValidator::is_valid(const RelativePoseProblemInstance &instance, const CameraPose &pose, double tol) {\n    if ((pose.R().transpose() * pose.R() - Eigen::Matrix3d::Identity()).norm() > tol)\n        return false;\n\n    // Point to point correspondences\n    // R * (alpha * p1 + lambda1 * x1) + t = alpha * p2 + lambda2 * x2\n    //\n    // cross(R*x1, x2)' * (alpha * p2 - t - alpha * R*p1) = 0\n    for (int i = 0; i < instance.x1_.size(); ++i) {\n        double err = std::abs(instance.x2_[i]\n                                  .cross(pose.R() * instance.x1_[i])\n                                  .normalized()\n                                  .dot(pose.R() * instance.p1_[i] + pose.t - instance.p2_[i]));\n        if (err > tol)\n            return false;\n    }\n\n    return true;\n}\n\ndouble HomographyValidator::compute_pose_error(const RelativePoseProblemInstance &instance, const Eigen::Matrix3d &H) {\n    double err1 = (H.normalized() - instance.H_gt.normalized()).norm();\n    double err2 = (H.normalized() + instance.H_gt.normalized()).norm();\n    return std::min(err1, err2);\n}\n\nbool HomographyValidator::is_valid(const RelativePoseProblemInstance &instance, const Eigen::Matrix3d &H, double tol) {\n\n    for (int i = 0; i < instance.x1_.size(); ++i) {\n        Eigen::Vector3d z = H * instance.x1_[i];\n        double err = 1.0 - std::abs(z.normalized().dot(instance.x2_[i].normalized()));\n        if (err > tol)\n            return false;\n    }\n\n    return true;\n}\n\ndouble UnknownFocalValidator::compute_pose_error(const AbsolutePoseProblemInstance &instance, const CameraPose &pose,\n                                                 double focal) {\n    return (instance.pose_gt.R() - pose.R()).norm() + (instance.pose_gt.t - pose.t).norm() +\n           std::abs(instance.focal_gt - focal);\n}\n\nbool UnknownFocalValidator::is_valid(const AbsolutePoseProblemInstance &instance, const CameraPose &pose, double focal,\n                                     double tol) {\n    if ((pose.R().transpose() * pose.R() - Eigen::Matrix3d::Identity()).norm() > tol)\n        return false;\n\n    if (focal < 0)\n        return false;\n\n    Eigen::Matrix3d Kinv;\n    Kinv.setIdentity();\n    Kinv(2, 2) = focal;\n    // lambda*diag(1,1,alpha)*x = R*X + t\n    for (int i = 0; i < instance.x_point_.size(); ++i) {\n        double err = 1.0 - std::abs((Kinv * instance.x_point_[i])\n                                        .normalized()\n                                        .dot((pose.R() * instance.X_point_[i] + pose.t).normalized()));\n        if (err > tol)\n            return false;\n    }\n\n    return true;\n}\n\ndouble RadialPoseValidator::compute_pose_error(const AbsolutePoseProblemInstance &instance, const CameraPose &pose,\n                                               double scale) {\n    // Only compute up to sign for radial cameras\n\n    double err1 = (instance.pose_gt.R().topRows(2) - pose.R().topRows(2)).norm() +\n                  (instance.pose_gt.t.topRows(2) - pose.t.topRows(2)).norm();\n    double err2 = (instance.pose_gt.R().topRows(2) + pose.R().topRows(2)).norm() +\n                  (instance.pose_gt.t.topRows(2) + pose.t.topRows(2)).norm();\n\n    return std::min(err1, err2);\n}\n\nbool RadialPoseValidator::is_valid(const AbsolutePoseProblemInstance &instance, const CameraPose &pose, double scale,\n                                   double tol) {\n    if ((pose.R().transpose() * pose.R() - Eigen::Matrix3d::Identity()).norm() > tol)\n        return false;\n\n    // Point to point correspondences -- Convert these to line correspondences\n    // alpha * p + lambda*x = R*X + t\n    for (int i = 0; i < instance.x_point_.size(); ++i) {\n        Eigen::Vector3d radial_line{-instance.x_point_[i](1), instance.x_point_[i](0), 0.0};\n        Eigen::Vector3d X = pose.R() * instance.X_point_[i] + pose.t;\n        double err = std::abs(radial_line.dot(X.normalized()));\n        if (err > tol)\n            return false;\n    }\n\n    // Line to point correspondences\n    // l'*(R*X + t) = 0\n    for (int i = 0; i < instance.l_line_point_.size(); ++i) {\n        Eigen::Vector3d X = pose.R() * instance.X_line_point_[i] + pose.t;\n\n        double err = std::abs(instance.l_line_point_[i].dot(X.normalized()));\n        if (err > tol)\n            return false;\n    }\n\n    return true;\n}\n\nvoid set_random_pose(CameraPose &pose, bool upright, bool planar) {\n    if (upright) {\n        Eigen::Vector2d r;\n        r.setRandom().normalize();\n        Eigen::Matrix3d R;\n        R << r(0), 0.0, r(1), 0.0, 1.0, 0.0, -r(1), 0.0, r(0); // y-gravity\n        // pose.R << r(0), r(1), 0.0, -r(1), r(0), 0.0, 0.0, 0.0, 1.0; // z-gravity\n        pose.q = rotmat_to_quat(R);\n    } else {\n        pose.q = Eigen::Quaternion<double>::UnitRandom().coeffs();\n    }\n    pose.t.setRandom();\n    if (planar) {\n        pose.t.y() = 0;\n    }\n}\n\nvoid generate_abspose_problems(int n_problems, std::vector<AbsolutePoseProblemInstance> *problem_instances,\n                               const ProblemOptions &options) {\n    problem_instances->clear();\n    problem_instances->reserve(n_problems);\n\n    double fov_scale = std::tan(options.camera_fov_ / 2.0 * kPI / 180.0);\n\n    // Random generators\n    std::default_random_engine random_engine;\n    std::uniform_real_distribution<double> depth_gen(options.min_depth_, options.max_depth_);\n    std::uniform_real_distribution<double> coord_gen(-fov_scale, fov_scale);\n    std::uniform_real_distribution<double> scale_gen(options.min_scale_, options.max_scale_);\n    std::uniform_real_distribution<double> focal_gen(options.min_focal_, options.max_focal_);\n    std::normal_distribution<double> direction_gen(0.0, 1.0);\n    std::normal_distribution<double> offset_gen(0.0, 1.0);\n\n    for (int i = 0; i < n_problems; ++i) {\n        AbsolutePoseProblemInstance instance;\n        set_random_pose(instance.pose_gt, options.upright_, options.planar_);\n\n        if (options.unknown_scale_) {\n            instance.scale_gt = scale_gen(random_engine);\n        }\n        if (options.unknown_focal_) {\n            instance.focal_gt = focal_gen(random_engine);\n        }\n\n        // Point to point correspondences\n        instance.x_point_.reserve(options.n_point_point_);\n        instance.X_point_.reserve(options.n_point_point_);\n        instance.p_point_.reserve(options.n_point_point_);\n        for (int j = 0; j < options.n_point_point_; ++j) {\n\n            Eigen::Vector3d p{0.0, 0.0, 0.0};\n            Eigen::Vector3d x{coord_gen(random_engine), coord_gen(random_engine), 1.0};\n            x.normalize();\n            Eigen::Vector3d X;\n\n            if (options.generalized_) {\n                p << offset_gen(random_engine), offset_gen(random_engine), offset_gen(random_engine);\n            }\n\n            X = instance.scale_gt * p + x * depth_gen(random_engine);\n\n            X = instance.pose_gt.R().transpose() * (X - instance.pose_gt.t);\n\n            if (options.unknown_focal_) {\n                x.block<2, 1>(0, 0) *= instance.focal_gt;\n                x.normalize();\n            }\n\n            instance.x_point_.push_back(x);\n            instance.X_point_.push_back(X);\n            instance.p_point_.push_back(p);\n        }\n\n        // This generates instances where the same 3D point is observed twice in a generalized camera\n        // This is degenerate case for the 3Q3 based gp3p/gp4ps solver unless specifically handled.\n        if (options.generalized_ && options.generalized_duplicate_obs_) {\n            std::vector<int> ind = {0, 1, 2, 3};\n            assert(options.n_point_point_ >= 4);\n\n            std::random_shuffle(ind.begin(), ind.end());\n            instance.X_point_[ind[1]] = instance.X_point_[ind[0]];\n            instance.x_point_[ind[1]] = (instance.pose_gt.R() * instance.X_point_[ind[0]] + instance.pose_gt.t -\n                                         instance.scale_gt * instance.p_point_[ind[1]])\n                                            .normalized();\n        }\n\n        // Point to line correspondences\n        instance.x_line_.reserve(options.n_point_line_);\n        instance.X_line_.reserve(options.n_point_line_);\n        instance.V_line_.reserve(options.n_point_line_);\n        instance.p_line_.reserve(options.n_point_line_);\n        for (int j = 0; j < options.n_point_line_; ++j) {\n            Eigen::Vector3d p{0.0, 0.0, 0.0};\n            Eigen::Vector3d x{coord_gen(random_engine), coord_gen(random_engine), 1.0};\n            x.normalize();\n            Eigen::Vector3d X;\n\n            if (options.generalized_) {\n                p << offset_gen(random_engine), offset_gen(random_engine), offset_gen(random_engine);\n            }\n            X = instance.scale_gt * p + x * depth_gen(random_engine);\n            X = instance.pose_gt.R().transpose() * (X - instance.pose_gt.t);\n\n            Eigen::Vector3d V{direction_gen(random_engine), direction_gen(random_engine), direction_gen(random_engine)};\n            V.normalize();\n\n            // Translate X such that X.dot(V) = 0\n            X = X - V.dot(X) * V;\n\n            if (options.unknown_focal_) {\n                // TODO implement this.\n            }\n\n            instance.x_line_.push_back(x);\n            instance.X_line_.push_back(X);\n            instance.V_line_.push_back(V);\n            instance.p_line_.push_back(p);\n        }\n\n        // Line to point correspondences\n        instance.l_line_point_.reserve(options.n_line_point_);\n        instance.X_line_point_.reserve(options.n_line_point_);\n        instance.p_line_point_.reserve(options.n_line_point_);\n        for (int j = 0; j < options.n_line_point_; ++j) {\n            Eigen::Vector3d p{0.0, 0.0, 0.0};\n            Eigen::Vector3d x{coord_gen(random_engine), coord_gen(random_engine), 1.0};\n            x.normalize();\n            Eigen::Vector3d X;\n\n            if (options.generalized_) {\n                p << offset_gen(random_engine), offset_gen(random_engine), offset_gen(random_engine);\n            }\n            X = instance.scale_gt * p + x * depth_gen(random_engine);\n            X = instance.pose_gt.R().transpose() * (X - instance.pose_gt.t);\n\n            // Cross product with random vector to generate line\n            Eigen::Vector3d l;\n            if (options.radial_lines_) {\n                // Line passing through image center\n                l = x.cross(Eigen::Vector3d{0.0, 0.0, 1.0});\n            } else {\n                // Random line\n                l = x.cross(Eigen::Vector3d(direction_gen(random_engine), direction_gen(random_engine),\n                                            direction_gen(random_engine)));\n            }\n\n            l.normalize();\n\n            if (options.unknown_focal_) {\n                // TODO implement this.\n            }\n\n            instance.l_line_point_.push_back(l);\n            instance.X_line_point_.push_back(X);\n            instance.p_line_point_.push_back(p);\n        }\n\n        // Line to line correspondences\n        instance.l_line_line_.reserve(options.n_line_line_);\n        instance.X_line_line_.reserve(options.n_line_line_);\n        instance.V_line_line_.reserve(options.n_line_line_);\n        instance.p_line_line_.reserve(options.n_line_line_);\n        for (int j = 0; j < options.n_line_line_; ++j) {\n            Eigen::Vector3d p{0.0, 0.0, 0.0};\n            Eigen::Vector3d x{coord_gen(random_engine), coord_gen(random_engine), 1.0};\n            x.normalize();\n            Eigen::Vector3d X;\n\n            if (options.generalized_) {\n                p << offset_gen(random_engine), offset_gen(random_engine), offset_gen(random_engine);\n            }\n            X = instance.scale_gt * p + x * depth_gen(random_engine);\n            X = instance.pose_gt.R().transpose() * (X - instance.pose_gt.t);\n\n            Eigen::Vector3d V{direction_gen(random_engine), direction_gen(random_engine), direction_gen(random_engine)};\n            V.normalize();\n\n            // Translate X such that X.dot(V) = 0\n            X = X - V.dot(X) * V;\n\n            Eigen::Vector3d l = x.cross(instance.pose_gt.R() * V);\n            l.normalize();\n\n            if (options.unknown_focal_) {\n                // TODO implement this.\n            }\n\n            instance.l_line_line_.push_back(l);\n            instance.X_line_line_.push_back(X);\n            instance.V_line_line_.push_back(V);\n            instance.p_line_line_.push_back(p);\n        }\n\n        problem_instances->push_back(instance);\n    }\n}\n\nvoid generate_relpose_problems(int n_problems, std::vector<RelativePoseProblemInstance> *problem_instances,\n                               const ProblemOptions &options) {\n    problem_instances->clear();\n    problem_instances->reserve(n_problems);\n\n    double fov_scale = std::tan(options.camera_fov_ / 2.0 * kPI / 180.0);\n\n    // Random generators\n    std::default_random_engine random_engine;\n    std::uniform_real_distribution<double> depth_gen(options.min_depth_, options.max_depth_);\n    std::uniform_real_distribution<double> coord_gen(-fov_scale, fov_scale);\n    std::uniform_real_distribution<double> scale_gen(options.min_scale_, options.max_scale_);\n    std::uniform_real_distribution<double> focal_gen(options.min_focal_, options.max_focal_);\n    std::normal_distribution<double> direction_gen(0.0, 1.0);\n    std::normal_distribution<double> offset_gen(0.0, 1.0);\n\n    for (int i = 0; i < n_problems; ++i) {\n        RelativePoseProblemInstance instance;\n        set_random_pose(instance.pose_gt, options.upright_, options.planar_);\n\n        if (options.unknown_scale_) {\n            instance.scale_gt = scale_gen(random_engine);\n        }\n        if (options.unknown_focal_) {\n            instance.focal_gt = focal_gen(random_engine);\n        }\n\n        if (!options.generalized_) {\n            instance.pose_gt.t.normalize();\n        }\n\n        // Point to point correspondences\n        instance.p1_.reserve(options.n_point_point_);\n        instance.x1_.reserve(options.n_point_point_);\n        instance.p2_.reserve(options.n_point_point_);\n        instance.x2_.reserve(options.n_point_point_);\n\n        for (int j = 0; j < options.n_point_point_; ++j) {\n\n            Eigen::Vector3d p1{0.0, 0.0, 0.0};\n            Eigen::Vector3d p2{0.0, 0.0, 0.0};\n            Eigen::Vector3d x1{coord_gen(random_engine), coord_gen(random_engine), 1.0};\n            x1.normalize();\n            Eigen::Vector3d X;\n\n            if (options.generalized_) {\n                p1 << offset_gen(random_engine), offset_gen(random_engine), offset_gen(random_engine);\n                p2 << offset_gen(random_engine), offset_gen(random_engine), offset_gen(random_engine);\n\n                if (j > 0 && j < options.generalized_first_cam_obs_) {\n                    p1 = instance.p1_[0];\n                    p2 = instance.p2_[0];\n                }\n            }\n\n            X = instance.scale_gt * p1 + x1 * depth_gen(random_engine);\n            // Map into second image\n            X = instance.pose_gt.R() * X + instance.pose_gt.t;\n\n            Eigen::Vector3d x2 = (X - instance.scale_gt * p2).normalized();\n\n            if (options.unknown_focal_) {\n                // NYI\n                assert(false);\n            }\n\n            // TODO: ensure FoV of second cameras as well...\n\n            instance.p1_.push_back(p1);\n            instance.x1_.push_back(x1);\n            instance.p2_.push_back(p2);\n            instance.x2_.push_back(x2);\n        }\n\n        problem_instances->push_back(instance);\n    }\n}\n\nvoid generate_homography_problems(int n_problems, std::vector<RelativePoseProblemInstance> *problem_instances,\n                                  const ProblemOptions &options) {\n    problem_instances->clear();\n    problem_instances->reserve(n_problems);\n\n    double fov_scale = std::tan(options.camera_fov_ / 2.0 * kPI / 180.0);\n\n    // Random generators\n    std::default_random_engine random_engine;\n    std::uniform_real_distribution<double> depth_gen(options.min_depth_, options.max_depth_);\n    std::uniform_real_distribution<double> coord_gen(-fov_scale, fov_scale);\n    std::uniform_real_distribution<double> scale_gen(options.min_scale_, options.max_scale_);\n    std::uniform_real_distribution<double> focal_gen(options.min_focal_, options.max_focal_);\n    std::normal_distribution<double> direction_gen(0.0, 1.0);\n    std::normal_distribution<double> offset_gen(0.0, 1.0);\n\n    while (problem_instances->size() < n_problems) {\n        RelativePoseProblemInstance instance;\n        set_random_pose(instance.pose_gt, options.upright_, options.planar_);\n\n        if (options.unknown_scale_) {\n            instance.scale_gt = scale_gen(random_engine);\n        }\n        if (options.unknown_focal_) {\n            instance.focal_gt = focal_gen(random_engine);\n        }\n\n        if (!options.generalized_) {\n            instance.pose_gt.t.normalize();\n        }\n\n        // Point to point correspondences\n        instance.x1_.reserve(options.n_point_point_);\n        instance.x2_.reserve(options.n_point_point_);\n\n        // Generate plane\n        Eigen::Vector3d n;\n        n << direction_gen(random_engine), direction_gen(random_engine), direction_gen(random_engine);\n        n.normalize();\n\n        // Choose depth of plane such that center point of image 1 is at depth d\n        double d_center = depth_gen(random_engine);\n        double alpha = d_center / n(2);\n        // plane is n'*X = alpha\n\n        // ground truth homography\n        instance.H_gt = alpha * instance.pose_gt.R() + instance.pose_gt.t * n.transpose();\n\n        bool failed_instance = false;\n        for (int j = 0; j < options.n_point_point_; ++j) {\n            bool point_okay = false;\n            for (int trials = 0; trials < 10; ++trials) {\n                Eigen::Vector3d x1{coord_gen(random_engine), coord_gen(random_engine), 1.0};\n                x1.normalize();\n                Eigen::Vector3d X;\n\n                // compute depth\n                double lambda = alpha / n.dot(x1);\n                X = x1 * lambda;\n                // Map into second image\n                X = instance.pose_gt.R() * X + instance.pose_gt.t;\n\n                Eigen::Vector3d x2 = X.normalized();\n\n                // Check cheirality\n                if (x2(2) < 0 || lambda < 0) {\n                    // try to generate another point\n                    continue;\n                }\n\n                // Check FoV of second camera\n                Eigen::Vector2d x2h = x2.hnormalized();\n                if (x2h(0) < -fov_scale || x2h(0) > fov_scale || x2h(1) < -fov_scale || x2h(1) > fov_scale) {\n                    // try to generate another point\n                    continue;\n                }\n\n                if (options.generalized_) {\n                    // NYI\n                    assert(false);\n                }\n                if (options.unknown_focal_) {\n                    // NYI\n                    assert(false);\n                }\n\n                instance.x1_.push_back(x1);\n                instance.x2_.push_back(x2);\n                point_okay = true;\n                break;\n            }\n            if (!point_okay) {\n                failed_instance = true;\n                break;\n            }\n        }\n        if (failed_instance) {\n            continue;\n        }\n\n        problem_instances->push_back(instance);\n    }\n}\n\n}; // namespace poselib\n", "meta": {"hexsha": "206a0ed9bb4d9955630a81a62774fe34864bddf0", "size": 21842, "ext": "cc", "lang": "C++", "max_stars_repo_path": "benchmark/problem_generator.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": "benchmark/problem_generator.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": "benchmark/problem_generator.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": 39.0733452594, "max_line_length": 120, "alphanum_fraction": 0.5820895522, "num_tokens": 5234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5413943987128896}}
{"text": "#define BOOST_TEST_MODULE \"test_aabb\"\n#include <boost/test/included/unit_test.hpp>\n#include <afmize/collision.hpp>\n#include <random>\n\nBOOST_AUTO_TEST_CASE(aabb_sphere)\n{\n    using sphere = afmize::sphere<double>;\n    using aabb   = afmize::aabb<double>;\n    using point  = mave::vector<double, 3>;\n\n    std::mt19937 mt(123456789);\n    std::uniform_real_distribution<double> uni(-100.0, 100.0);\n\n    for(std::size_t i=0; i<1000; ++i)\n    {\n        const sphere s{uni(mt), point{uni(mt), uni(mt), uni(mt)}};\n        const aabb box = afmize::make_aabb(s);\n\n        BOOST_TEST(box.lower[0] == s.center[0] - s.radius,\n                   boost::test_tools::tolerance(1e-6));\n        BOOST_TEST(box.lower[1] == s.center[1] - s.radius,\n                   boost::test_tools::tolerance(1e-6));\n        BOOST_TEST(box.lower[2] == s.center[2] - s.radius,\n                   boost::test_tools::tolerance(1e-6));\n\n        BOOST_TEST(box.upper[0] == s.center[0] + s.radius,\n                   boost::test_tools::tolerance(1e-6));\n        BOOST_TEST(box.upper[1] == s.center[1] + s.radius,\n                   boost::test_tools::tolerance(1e-6));\n        BOOST_TEST(box.upper[2] == s.center[2] + s.radius,\n                   boost::test_tools::tolerance(1e-6));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(merge_aabb)\n{\n    using sphere = afmize::sphere<double>;\n    using aabb   = afmize::aabb<double>;\n    using point  = mave::vector<double, 3>;\n\n    std::mt19937 mt(123456789);\n    std::uniform_real_distribution<double> uni(-100.0, 100.0);\n\n    for(std::size_t i=0; i<1000; ++i)\n    {\n        const aabb box1{point{uni(mt), uni(mt), uni(mt)},\n                        point{uni(mt), uni(mt), uni(mt)}};\n        const aabb box2{point{uni(mt), uni(mt), uni(mt)},\n                        point{uni(mt), uni(mt), uni(mt)}};\n\n        const aabb box3 = afmize::merge_aabb(box1, box2);\n\n        BOOST_TEST(box3.lower[0] == std::min(box1.lower[0], box2.lower[0]),\n                   boost::test_tools::tolerance(1e-6));\n        BOOST_TEST(box3.lower[1] == std::min(box1.lower[1], box2.lower[1]),\n                   boost::test_tools::tolerance(1e-6));\n        BOOST_TEST(box3.lower[2] == std::min(box1.lower[2], box2.lower[2]),\n                   boost::test_tools::tolerance(1e-6));\n\n        BOOST_TEST(box3.upper[0] == std::max(box1.upper[0], box2.upper[0]),\n                   boost::test_tools::tolerance(1e-6));\n        BOOST_TEST(box3.upper[1] == std::max(box1.upper[1], box2.upper[1]),\n                   boost::test_tools::tolerance(1e-6));\n        BOOST_TEST(box3.upper[2] == std::max(box1.upper[2], box2.upper[2]),\n                   boost::test_tools::tolerance(1e-6));\n    }\n}\n", "meta": {"hexsha": "db1e3da0e8f896bd03685b41acb178fcb9a0d571", "size": 2653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_aabb.cpp", "max_stars_repo_name": "0ncorhynchus/afmize", "max_stars_repo_head_hexsha": "d41ec2fa985fdd1fdc5f25f2dafbbef7eead041d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-09-28T08:43:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-14T05:30:39.000Z", "max_issues_repo_path": "test/test_aabb.cpp", "max_issues_repo_name": "0ncorhynchus/afmize", "max_issues_repo_head_hexsha": "d41ec2fa985fdd1fdc5f25f2dafbbef7eead041d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-04-23T14:29:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-31T04:07:06.000Z", "max_forks_repo_path": "test/test_aabb.cpp", "max_forks_repo_name": "0ncorhynchus/afmize", "max_forks_repo_head_hexsha": "d41ec2fa985fdd1fdc5f25f2dafbbef7eead041d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-04-23T07:25:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-12T08:17:42.000Z", "avg_line_length": 38.4492753623, "max_line_length": 75, "alphanum_fraction": 0.5702977761, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5413690896033951}}
{"text": "#ifndef HOPS_DIKINPROPOSAL_HPP\n#define HOPS_DIKINPROPOSAL_HPP\n\n#include <Eigen/LU>\n#include \"DikinEllipsoidCalculator.hpp\"\n#include \"../../RandomNumberGenerator/RandomNumberGenerator.hpp\"\n#include <random>\n\nnamespace hops {\n    template<typename MatrixType, typename VectorType>\n    class DikinProposal {\n    public:\n        using StateType = VectorType;\n\n        /**\n         * @brief Constructs Gaussian Dikin proposal mechanism on polytope defined as Ax<b.\n         * @param A\n         * @param b\n         * @param currentState\n         */\n        DikinProposal(MatrixType A, VectorType b, VectorType currentState);\n\n        void propose(RandomNumberGenerator &randomNumberGenerator);\n\n        void acceptProposal();\n\n        typename MatrixType::Scalar computeLogAcceptanceProbability();\n\n        StateType getState() const;\n\n        void setState(StateType newState);\n\n        StateType getProposal() const;\n\n        typename MatrixType::Scalar getStepSize() const;\n\n        void setStepSize(typename MatrixType::Scalar newStepSize);\n\n        std::string getName();\n\n    private:\n        MatrixType A;\n        VectorType b;\n\n        StateType state;\n        StateType proposal;\n        typename MatrixType::Scalar stateLogSqrtDeterminant = 0;\n        typename MatrixType::Scalar proposalLogSqrtDeterminant = 0;\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> stateCholeskyOfDikinEllipsoid;\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> proposalCholeskyOfDikinEllipsoid;\n\n        typename MatrixType::Scalar stepSize = 0.075; // value  from dikin walk publication\n        typename MatrixType::Scalar geometricFactor;\n        typename MatrixType::Scalar covarianceFactor;\n        constexpr static typename MatrixType::Scalar boundaryCushion = 0;\n\n        std::normal_distribution<typename MatrixType::Scalar> normalDistribution{0., 1.};\n        DikinEllipsoidCalculator<MatrixType, VectorType> dikinEllipsoidCalculator;\n    };\n\n    template<typename MatrixType, typename VectorType>\n    DikinProposal<MatrixType, VectorType>::DikinProposal(MatrixType A,\n                                                         VectorType b,\n                                                         VectorType currentState) :\n            A(std::move(A)),\n            b(std::move(b)),\n            dikinEllipsoidCalculator(this->A, this->b) {\n        setStepSize(1.);\n        setState(std::move(currentState));\n        proposal = state;\n    }\n\n    template<typename MatrixType, typename VectorType>\n    void DikinProposal<MatrixType, VectorType>::propose(RandomNumberGenerator &randomNumberGenerator) {\n        for (long i = 0; i < proposal.rows(); ++i) {\n            proposal(i) = normalDistribution(randomNumberGenerator);\n        }\n        proposal = state + covarianceFactor *\n                           stateCholeskyOfDikinEllipsoid.template triangularView<Eigen::Lower>().solve(proposal);\n    }\n\n    template<typename MatrixType, typename VectorType>\n    void DikinProposal<MatrixType, VectorType>::acceptProposal() {\n        state.swap(proposal);\n        stateCholeskyOfDikinEllipsoid = std::move(proposalCholeskyOfDikinEllipsoid);\n        stateLogSqrtDeterminant = proposalLogSqrtDeterminant;\n    }\n\n    template<typename MatrixType, typename VectorType>\n    typename MatrixType::Scalar\n    DikinProposal<MatrixType, VectorType>::computeLogAcceptanceProbability() {\n        bool isProposalInteriorPoint = ((A * proposal - b).array() < -boundaryCushion).all();\n        if (!isProposalInteriorPoint) {\n            return -std::numeric_limits<typename MatrixType::Scalar>::infinity();\n        }\n\n        auto choleskyResult = dikinEllipsoidCalculator.computeCholeskyFactorOfDikinEllipsoid(proposal);\n        if (!choleskyResult.first) {\n            return -std::numeric_limits<typename MatrixType::Scalar>::infinity();\n        }\n        proposalCholeskyOfDikinEllipsoid = std::move(choleskyResult.second);\n\n        proposalLogSqrtDeterminant = proposalCholeskyOfDikinEllipsoid.diagonal().array().log().sum();\n        VectorType stateDifference = state - proposal;\n\n        return proposalLogSqrtDeterminant\n               - stateLogSqrtDeterminant\n               + geometricFactor * ((stateCholeskyOfDikinEllipsoid * stateDifference).squaredNorm()\n                                    - (proposalCholeskyOfDikinEllipsoid * stateDifference).squaredNorm()\n        );\n    }\n\n    template<typename MatrixType, typename VectorType>\n    typename DikinProposal<MatrixType, VectorType>::StateType\n    DikinProposal<MatrixType, VectorType>::getState() const {\n        return state;\n    }\n\n    template<typename MatrixType, typename VectorType>\n    void DikinProposal<MatrixType, VectorType>::setState(StateType newState) {\n        state.swap(newState);\n        auto choleskyResult = dikinEllipsoidCalculator.computeCholeskyFactorOfDikinEllipsoid(state);\n        if (!choleskyResult.first) {\n            throw std::runtime_error(\"Could not compute cholesky factorization for newState.\");\n        }\n        stateCholeskyOfDikinEllipsoid = std::move(choleskyResult.second);\n        stateLogSqrtDeterminant = stateCholeskyOfDikinEllipsoid.diagonal().array().log().sum();\n    }\n\n    template<typename MatrixType, typename VectorType>\n    typename DikinProposal<MatrixType, VectorType>::StateType\n    DikinProposal<MatrixType, VectorType>::getProposal() const {\n        return proposal;\n    }\n\n    template<typename MatrixType, typename VectorType>\n    typename MatrixType::Scalar DikinProposal<MatrixType, VectorType>::getStepSize() const {\n        return stepSize;\n    }\n\n    template<typename MatrixType, typename VectorType>\n    void DikinProposal<MatrixType, VectorType>::setStepSize(typename MatrixType::Scalar newStepSize) {\n        stepSize = newStepSize;\n        geometricFactor = A.cols() / (2 * stepSize);\n        covarianceFactor = std::sqrt(stepSize / A.cols());\n    }\n\n    template<typename MatrixType, typename VectorType>\n    std::string DikinProposal<MatrixType, VectorType>::getName() {\n        return \"Dikin Walk\";\n    }\n}\n\n#endif //HOPS_DIKINPROPOSAL_HPP\n", "meta": {"hexsha": "4497eab320a60008549b234893de2e93c8d9a4ea", "size": 6120, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hops/MarkovChain/Proposal/DikinProposal.hpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "include/hops/MarkovChain/Proposal/DikinProposal.hpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "include/hops/MarkovChain/Proposal/DikinProposal.hpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["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.4838709677, "max_line_length": 116, "alphanum_fraction": 0.6825163399, "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5413690671031548}}
{"text": "#include <iostream>\r\n#include <fstream>\r\n#include <cmath>\r\n#include <math.h>\r\n#include <vector>\r\n#include <array>\r\n#include \"SpaceAdaptiveSolver.hpp\"\r\n#include \"TriDiagMatrix.hpp\"\r\n#include \"MassMatrix.hpp\"\r\n#include \"StiffnessMatrix.hpp\"\r\n#include <string>\r\n#include <functional>\r\n#include <boost/math/quadrature/gauss.hpp>\r\nusing namespace std;\r\nusing namespace boost::math::quadrature;\r\n\r\nvoid AdaptiveSolver::SetTolerances(const double refineby, const double coarsenby)\r\n{\r\n    tolerance = refineby;\r\n    coarseningtol = coarsenby;\r\n}\r\n\r\nvoid AdaptiveSolver::AdaptiveSolve()\r\n{\r\nmpsmesh.PrintSpaceNodes();\r\nmpcurrenTimeStep = 0;\r\nmpcurrentMeshIndex = 0;\r\noldmesh.CopySpaceMesh(mpsmesh);\r\n\r\n//AnalyticSolutionVec();\r\n//mpPreviousSolution = mpAnalyticSolution;\r\nmppde->InitialCondition(mpsmesh, mpPreviousSolution);\r\nstiff.SetParameters(k_0, k_L, mpa);\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.BuildGeneralStiffnessMatrix ( mpsmesh );\r\nstiff.MultiplyByScalar( mptmesh.ReadTimeMesh(mpcurrentMeshIndex) );\r\nmass.BuildGeneralMassMatrix(mpsmesh);\r\n\r\nLHS.AddTwoMatrices( mass, stiff );\r\ng_0 = mppde->FirstBoundary(mptmesh.ReadTimeStep(mpcurrenTimeStep));\r\ng_L =mppde->SecondBoundary(mptmesh.ReadTimeStep(mpcurrenTimeStep));\r\nBuildRHS();\r\nBuiltbrVec();\r\nVectorTimesScalar( br, mptmesh.ReadTimeMesh(mpcurrentMeshIndex) );\r\n\r\nAddVectors( br, mpRHS, mpRHS );\r\n\r\nLHS.MatrixSolver( mpRHS, mpx );\r\n\r\noldmesh.CopySpaceMesh(mpsmesh);\r\nmpsmesh.PrintSpaceNodes();\r\n\r\nmpPreviousSolution = mpx;\r\n\r\n    BuildGradientVec(mpx, mpsmesh, FEMGradient);\r\n    GradientRecoveryFunction( mpsmesh, FEMGradient, GradientRecovery );\r\n    BuildErrorEstimate();\r\n    PrintVector(ErrorEstimate);\r\n\r\n\r\n\r\n\r\n    SaveRefinementNodes(mpNodeToInsert);\r\n    PrintVector(mpNodeToInsert);\r\n\r\n    if(ErrorEstimate.size()>3)\r\n    {\r\n    std::cout<< ErrorEstimate.size()<<\"\\n\";\r\n    SaveIntervalsForCoarsening();\r\n    mpsmesh.CoarsenIntervals(NodesForRemoval);\r\n    }\r\n    else\r\n    {\r\n    NodesForRemoval.clear();\r\n    }\r\n\r\n    mpsmesh.InsertArray( mpNodeToInsert );\r\n}\r\n    std::cout<<mpsmesh.meshsize() <<\"\\n\";\r\n    std::cout<<\"\\n\";\r\n}\r\n\r\nvoid AdaptiveSolver::SaveIntervalsForCoarsening(  )\r\n{\r\n    NodesForRemoval.clear();\r\n    for(int i=1; i<ErrorEstimate.size()-1; i++)\r\n    {\r\n        if (sqrt(ErrorEstimate.at(i)+ErrorEstimate.at(i+1))<coarseningtol)\r\n        {\r\n            NodesForRemoval.push_back(i+1);\r\n        }\r\n    }\r\n        for (auto k: NodesForRemoval)\r\n        std::cout << k << \", \";\r\n        std::cout << \" \\n\";\r\n}\r\n\r\nvoid AdaptiveSolver::SaveIntervalsForRefinement()\r\n{\r\n    intervalsForRefinement.clear();\r\n    for(int i=0; i<ErrorEstimate.size(); i++)\r\n    {\r\n        if (sqrt(ErrorEstimate.at(i))>tolerance)\r\n        {\r\n            intervalsForRefinement.push_back(i);\r\n        }\r\n    }\r\n}\r\n\r\nvoid AdaptiveSolver::SaveRefinementNodes( std::vector<double>& Nodes_to_insert )\r\n{\r\n    Nodes_to_insert.clear();\r\n    double midpoint;\r\n    for(int i=0; i<ErrorEstimate.size(); i++)\r\n    {\r\n        if (sqrt(ErrorEstimate.at(i))>tolerance)\r\n        {\r\n           midpoint = 0.5*(mpsmesh.ReadSpaceNode(i)+mpsmesh.ReadSpaceNode(i+1));\r\n           Nodes_to_insert.push_back(midpoint);\r\n        }\r\n    }\r\n}\r\n\r\nvoid AdaptiveSolver::BuildRHS()\r\n{\r\nmpRHS.clear();\r\nstd::vector<double> intervals;\r\n\r\nrefinedsmesh.CommonMesh(mpsmesh, oldmesh);\r\n\r\ndouble integral;\r\nrefinedsmesh.Range(mpsmesh.ReadSpaceNode(0), mpsmesh.ReadSpaceNode(1), intervals);\r\n    for(int j = 0; j<intervals.size()-1; j++)\r\n    {\r\n        integral = integral + IntegrateBasisWithU(0, intervals.at(j), intervals.at(j+1));\r\n    }\r\n    mpRHS.push_back(integral);\r\n\r\nfor (int i = 1; i<mpsmesh.meshsize(); i++)\r\n{\r\n    integral=0;\r\n    refinedsmesh.Range(mpsmesh.ReadSpaceNode(i-1), mpsmesh.ReadSpaceNode(i+1), intervals);\r\n\r\n    for(int j = 0; j<intervals.size()-1; j++)\r\n    {\r\n        integral = integral + IntegrateBasisWithU(i, intervals.at(j),\r\n                    intervals.at(j+1));\r\n    }\r\n    mpRHS.push_back(integral);\r\n}\r\nintegral=0;\r\nrefinedsmesh.Range(mpsmesh.ReadSpaceNode(mpsmesh.meshsize()-1), mpsmesh.ReadSpaceNode(mpsmesh.meshsize()), intervals);\r\n    for(int j = 0; j<intervals.size()-1; j++)\r\n    {\r\n        integral = integral + IntegrateBasisWithU(mpsmesh.meshsize(), intervals.at(j), intervals.at(j+1));\r\n    }\r\n    mpRHS.push_back(integral);\r\n}\r\n\r\nvoid AdaptiveSolver::MeshRefinement()\r\n{\r\n\r\n    SaveIntervalsForRefinement();\r\n    SaveIntervalsForCoarsening();\r\n    mpsmesh.BisectIntervals(intervalsForRefinement);\r\n    mpsmesh.CoarsenIntervals(NodesForRemoval);\r\n\r\n}\r\n\r\ndouble AdaptiveSolver::IntegrateBasisWithU( int NodeIndex, double lowerlimit,\r\n                              double upperlimit )\r\n{\r\n   //std::cout<<NodeIndex<<\", \"<<lowerlimit<<\", \"<< upperlimit<< \"\\n\";\r\n    auto SolutionWithBasis = [&](double x)\r\n        { return mpsmesh.GeneralTestFunctions( NodeIndex, x)*GeneralInterpolant( x, mpPreviousSolution, oldmesh ); };\r\n\r\n    return gauss<double, 7>::integrate(SolutionWithBasis, lowerlimit, upperlimit);\r\n}\r\n\r\nvoid AdaptiveSolver::UnitTest()\r\n{\r\nmpsmesh.GenerateUniformMesh(1,4);\r\noldmesh.GenerateUniformMesh(1, 4);\r\nmpPreviousSolution = {1,2,2,1};\r\n\r\n\r\nBuildRHS();\r\n\r\nMassMatrix test;\r\ntest.BuildGeneralMassMatrix(mpsmesh);\r\ntest.MatrixVectorMultiplier( mpPreviousSolution, mpRHS );\r\nPrintVector(mpRHS);\r\n\r\nmpsmesh.RemoveSpaceNode(1);\r\nmpsmesh.PrintSpaceNodes();\r\n\r\nBuildRHS();\r\n}\r\n\r\n//void AdaptiveSolver::SaveIntervalsForCoarsening2()\r\n//{\r\n//    NodesForRemoval.clear();\r\n//    for(int i=0; i<ErrorEstimate.size()-1; i++)\r\n//    {\r\n//        if ((sqrt(ErrorEstimate.at(i))<coarseningtol)||(sqrt(ErrorEstimate.at(i+1))<coarseningtol))\r\n//        {\r\n//            NodesForRemoval.push_back(i+1);\r\n//        }\r\n//    }\r\n//}\r\n\r\nvoid AdaptiveSolver::SaveIntervalsForCoarsening2()\r\n{\r\n    NodesForRemoval.clear();\r\n    for(int i=1; i<ErrorEstimate.size()-1; i++)\r\n    {\r\n        if ((sqrt(ErrorEstimate.at(i))<coarseningtol)||(sqrt(ErrorEstimate.at(i+1))<coarseningtol))\r\n        {\r\n            NodesForRemoval.push_back(i+1);\r\n        }\r\n    }\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "68a2ebc521f50539c143cda150d41a12a7e538ff", "size": 6114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solver class with methods to adapt in space/SpaceAdaptiveSolver.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": "Solver class with methods to adapt in space/SpaceAdaptiveSolver.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": "Solver class with methods to adapt in space/SpaceAdaptiveSolver.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": 26.5826086957, "max_line_length": 119, "alphanum_fraction": 0.6578344782, "num_tokens": 1651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5413690616544605}}
{"text": "#include <NTL/GF2XFactoring.h>\n#include <NTL/GF2EX.h>\n\nNTL_CLIENT\n\n\n\nvoid test(GF2X& P, GF2EX& f, GF2EX& g, GF2EX& h, GF2EX& hx, GF2EX& s, GF2EX& t)\n{\n   /* P is the polynomial of the extension\n    * f and g the polynomials\n    * h the gcd\n    * hx the gcd obtained using XGCD\n    * s, t are Bezout coefficients hx=f*s+g*t\n    */\n   GF2EX htest,rf,rg;\n\n   if (h!=hx){\n       cout << P << \"\\n\" << f << \"\\n\" << g << \"\\n\";\n       Error(\"different gcd:\\n\");\n   }\n\n   if (max(deg(f), deg(g)) > 0 || min(deg(f), deg(g)) >= 0) {\n      if (deg(s) >= deg(g) || deg(t) >= deg(f)) {\n\t cout << P << \"\\n\" << f << \"\\n\" << g << \"\\n\";\n\t Error(\"degree bounds at fault:\\n\");\n      }\n   }\n\n\n   mul(s,s,f);\n   mul(t,t,g);\n   add(htest,t,s);\n   if (h!=htest){\n      cout << P << \"\\n\" << f << \"\\n\" << g << \"\\n\";\n      Error(\"xgcd at fault:\\n\");\n   }\n   if (!IsZero(h)){\n      rem(rf,f,h);\n      rem(rg,f,h);\n      if ((!IsZero(rf))||(!IsZero(rg))){\n         cout << P << \"\\n\" << f << \"\\n\" << g << \"\\n\";\n         Error(\"not a common divisor\\n\");\n      }\n   }else{\n       if (!IsZero(f) && !IsZero(g)){\n         cout << \"debug:\\n\";\n         cout << P << \"\\n\" << f << \"\\n\" << g << \"\\n\" << h << \"\\n\";\n         Error(\"ooops:\\n\");\n      }\n   }\n}\n\n\nint main()\n{\n\n   GF2X P;\n\n   BuildIrred(P, 128);\n\n   GF2E::init(P);\n\n   for (long i = 0; i < 400; i++) {\n      if (i%10 == 0) cerr << \".\";\n      GF2EX f,g,h,s,t,hx;\n\n      long deg_h;\n      if (RandomBnd(2)) \n         deg_h = RandomBnd(10)+1;\n      else\n         deg_h = RandomBnd(500)+1;\n\n      random(h, deg_h);\n      SetCoeff(h, deg_h);\n\n      long deg_f;\n      if (RandomBnd(2))\n         deg_f = RandomBnd(10)+1;\n      else\n         deg_f = RandomBnd(1000)+1;\n\n      random(f, deg_f);\n      f *= h;\n\n      long deg_g;\n      if (RandomBnd(2))\n         deg_g = RandomBnd(10)+1;\n      else\n         deg_g = RandomBnd(1000)+1;\n\n      random(g, deg_g);\n      g *= h;\n\n      h = 0;\n\n      GCD(h, f, g);\n      XGCD(hx, s, t, f, g);\n      test(P, f, g, h, hx, s, t);\n   }\n\n   cerr << \"\\n\";\n\n}\n", "meta": {"hexsha": "f3279a90d7a43fc2f19a04f184c3c664851bb1c9", "size": 2009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/GF2EXGCDTest.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-03-21T19:39:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T06:14:16.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/GF2EXGCDTest.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-12-24T22:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-25T10:03:13.000Z", "max_forks_repo_path": "LibSource/ExtendedNTL/tests/GF2EXGCDTest.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2016-01-16T07:59:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T10:27:23.000Z", "avg_line_length": 19.1333333333, "max_line_length": 79, "alphanum_fraction": 0.4290691887, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5413690616544604}}
{"text": "/*\n * base_types.hpp\n *\n *  Copyright (c) 2014 Kumar Robotics. All rights reserved.\n *\n *  This file is part of kr_math.\n *\n *  Created on: 28/06/2014\n *      Author: gareth\n */\n\n/*\n * @brief Convenient shorthand names for working with vectors/matrices.\n */\n#ifndef KR_MATH_BASE_TYPES_H_\n#define KR_MATH_BASE_TYPES_H_\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace kr {\n\ntemplate <typename Scalar, int Rows, int Cols>\nusing Mat = Eigen::Matrix<Scalar, Rows, Cols>;\n\ntemplate <typename Scalar, int Rows>\nusing Vec = Eigen::Matrix<Scalar, Rows, 1>;\n\ntemplate <typename Scalar> using Vec2 = Mat<Scalar, 2, 1>;\n\ntemplate <typename Scalar> using Vec3 = Mat<Scalar, 3, 1>;\n\ntemplate <typename Scalar> using Vec4 = Mat<Scalar, 4, 1>;\n\ntemplate <typename Scalar> using Mat2 = Mat<Scalar, 2, 2>;\n\ntemplate <typename Scalar> using Mat3 = Mat<Scalar, 3, 3>;\n\ntemplate <typename Scalar> using Mat4 = Mat<Scalar, 4, 4>;\n\ntemplate <typename Scalar> using Quat = Eigen::Quaternion<Scalar>;\n\ntypedef Vec2<float> Vec2f;\ntypedef Vec2<double> Vec2d;\n\ntypedef Vec3<float> Vec3f;\ntypedef Vec3<double> Vec3d;\n\ntypedef Vec4<float> Vec4f;\ntypedef Vec4<double> Vec4d;\n\ntypedef Mat2<float> Mat2f;\ntypedef Mat2<double> Mat2d;\n\ntypedef Mat3<float> Mat3f;\ntypedef Mat3<double> Mat3d;\n\ntypedef Mat4<float> Mat4f;\ntypedef Mat4<double> Mat4d;\n\ntypedef Quat<float> Quatf;\ntypedef Quat<double> Quatd;\n\n} // namespace kr\n\n#endif // KR_MATH_BASE_TYPES_H_\n", "meta": {"hexsha": "6f707e721f3ce709dc359fd57a91bc7869f93e39", "size": 1432, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kr_math/include/kr_math/base_types.hpp", "max_stars_repo_name": "KumarRobotics/kr_utils", "max_stars_repo_head_hexsha": "049685a8fd9bb8a37490cafeda94b4ab652c829e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-10-12T01:59:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-19T05:03:26.000Z", "max_issues_repo_path": "kr_math/include/kr_math/base_types.hpp", "max_issues_repo_name": "KumarRobotics/kr_utils", "max_issues_repo_head_hexsha": "049685a8fd9bb8a37490cafeda94b4ab652c829e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-02-25T08:58:26.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-29T07:25:38.000Z", "max_forks_repo_path": "kr_math/include/kr_math/base_types.hpp", "max_forks_repo_name": "KumarRobotics/kr_utils", "max_forks_repo_head_hexsha": "049685a8fd9bb8a37490cafeda94b4ab652c829e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:39:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-19T05:03:30.000Z", "avg_line_length": 21.3731343284, "max_line_length": 71, "alphanum_fraction": 0.7248603352, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059707450326, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5413533093573722}}
{"text": "\n#include <I3Test.h>\n\n#include \"common.h\"\n#include \"MuonGun/Cylinder.h\"\n\n#include <boost/make_shared.hpp>\n\nTEST_GROUP(Integration);\n\nusing namespace I3MuonGun;\n\nnamespace {\n\ndouble one(double depth, double cos_theta) {\n\treturn 1.;\n}\n\n}\n\nTEST(Constant)\n{\n\tCylinder surface(1000, 500);\n\t\n\tENSURE_DISTANCE(surface.IntegrateFlux(one, 0., 1.),\n\t    surface.GetAcceptance(0., 1.), surface.GetAcceptance(0., 1.)/1e4,\n\t    \"Numerical integration of a constant is accurate to 1e-4\");\n}\n", "meta": {"hexsha": "095048df02785b7e9f2c29c9b74dfb80ef68e545", "size": 477, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "MuonGun/private/test/Integration.cxx", "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_issues_repo_path": "MuonGun/private/test/Integration.cxx", "max_issues_repo_name": "hschwane/offline_production", "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MuonGun/private/test/Integration.cxx", "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "avg_line_length": 16.4482758621, "max_line_length": 70, "alphanum_fraction": 0.7106918239, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5413532908843777}}
{"text": "#include \"benchmark.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <Eigen/LU>\n#include <fstream>\n#include <chrono>\n#include <iostream>\n#include <cstdlib>\n\nnamespace\n{\n\tclass Gaussian\n\t{\n\t\tstatic const double log2pi;\n\n\t\tsize_t n_;\n\t\tEigen::VectorXd mean_;\n\t\tEigen::MatrixXd covariance_;\n\t\tEigen::MatrixXd invCovariance_;\n\t\tdouble logdet_;\n\t\tEigen::LLT<Eigen::MatrixXd> cholesky_;\n\n\t\tEigen::VectorXd tmp_;\n\n\t\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\t\t\n\tpublic:\n\t\tGaussian(const Eigen::VectorXd& mean, const Eigen::MatrixXd& cov)\n\t\t\t: n_(mean.size()), mean_(mean), covariance_(cov), logdet_(0)\n\t\t{\n\t\t\tinvCovariance_.resizeLike(covariance_);\n\t\t\tcomputeDetInv();\n\t\t}\n\t\tvoid computeDetInv()\n\t\t{\n\t\t\tbool invertible = true;\n\t\t\tdouble det;\n\t\t\tif (n_ == 1) {\n\t\t\t\tcovariance_.block<1, 1>(0, 0).computeInverseAndDetWithCheck(invCovariance_, det, invertible);\n\t\t\t\tlogdet_ = std::log(det);\n\t\t\t}\n\t\t\telse if (n_ == 2) {\n\t\t\t\tcovariance_.block<2, 2>(0, 0).computeInverseAndDetWithCheck(invCovariance_, det, invertible);\n\t\t\t\tlogdet_ = std::log(det);\n\t\t\t}\n\t\t\telse if (n_ == 3) {\n\t\t\t\tcovariance_.block<3, 3>(0, 0).computeInverseAndDetWithCheck(invCovariance_, det, invertible);\n\t\t\t\tlogdet_ = std::log(det);\n\t\t\t}\n\t\t\telse if (n_ == 4) {\n\t\t\t\tcovariance_.block<4, 4>(0, 0).computeInverseAndDetWithCheck(invCovariance_, det, invertible);\n\t\t\t\tlogdet_ = std::log(det);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcholesky_.compute(covariance_);\n\t\t\t\tinvertible = cholesky_.info() == Eigen::Success;\n\t\t\t\t//https://gist.github.com/redpony/fc8a0db6b20f7b1a3f23#gistcomment-2277286\n\t\t\t\tlogdet_ = cholesky_.matrixL().toDenseMatrix().diagonal().array().log().sum();\n\t\t\t}\n\t\t\tif (!invertible)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Covariance is singular, re-initialize with the identity matrix\" << std::endl;\n\t\t\t\tcovariance_.setIdentity(n_, n_);\n\t\t\t\tinvCovariance_.setIdentity(n_, n_);\n\t\t\t\tlogdet_ = 0; // log(det(In))=log(1)=0\n\t\t\t}\n\t\t}\n\t\t//Returns the log-probability of x in this gaussian\n\t\tdouble logP(const Eigen::VectorXd& x)\n\t\t{\n\t\t\ttmp_ = x - mean_;\n\t\t\tdouble alpha;\n\t\t\tif (n_ <= 4)\n\t\t\t\talpha = tmp_.dot(invCovariance_*tmp_);\n\t\t\telse\n\t\t\t\talpha = tmp_.dot(cholesky_.solve(tmp_));\n\t\t\treturn -0.5 * (alpha + n_*log2pi + logdet_);\n\t\t}\n\t\t//getter+setter\n\t\tconst Eigen::VectorXd& mean() const { return mean_; }\n\t\tEigen::VectorXd& mean() { return mean_; }\n\t\tconst Eigen::MatrixXd& cov() const { return covariance_; }\n\t\tEigen::MatrixXd& cov() { return covariance_; }\n\n\t\tfriend std::ostream& operator<<(std::ostream& o, const Gaussian& g)\n\t\t{\n\t\t\to << \"Mean: \" << g.mean().transpose() << \"\\n\"\n\t\t\t\t<< \"Cov:\\n\" << g.cov();\n\t\t\treturn o;\n\t\t}\n\t};\n\tconst double Gaussian::log2pi = 1.8378770664093454835606594728112f;\n\n\ttemplate<typename Derived, typename Scalar = typename Derived::Scalar>\n\tScalar LSE(const Eigen::MatrixBase<Derived>& vec)\n\t{\n\t\tScalar m = vec.maxCoeff();\n\t\treturn m + std::log((vec.array() - m).exp().sum());\n\t}\n\n}\n\nvoid benchmark_Eigen(\n\tconst std::string& pointsFile,\n\tconst std::string& settingsFile,\n\tint numIterations,\n    Json::Object& returnValues)\n{\n    //load settings and points\n\tint dimension, components, numPoints;\n\tEigen::MatrixXd points;\n\tstd::vector<double> logWeights;\n\tstd::vector<Gaussian> gaussians;\n\t{ //points\n\t\tstd::ifstream in(pointsFile);\n\t\tin >> dimension >> components >> numPoints;\n\t\tpoints.resize(dimension, numPoints);\n\t\tfloat dummy; //skip ground truth\n\t\tfor (int i = 0; i < components * (1 + dimension + dimension * dimension); ++i) in >> dummy;\n\t\tfor (int i = 0; i < numPoints; ++i) { //read points\n\t\t\tEigen::VectorXd p(dimension);\n\t\t\tfor (int d = 0; d < dimension; ++d) in >> p[d];\n\t\t\tpoints.col(i) = p;\n\t\t}\n\t}\n\t{ //initial settings\n\t\tstd::ifstream in(settingsFile);\n\t\tint dummy;\n\t\tin >> dimension >> components >> dummy;\n\t\tlogWeights.resize(components);\n\t\tgaussians.reserve(components);\n\t\tEigen::VectorXd mean(dimension);\n\t\tEigen::MatrixXd cov(dimension, dimension);\n\t\tfor (int i=0; i<components; ++i)\n\t\t{\n\t\t\tdouble weight;\n\t\t\tin >> weight;\n\t\t\tlogWeights[i] = std::log(weight);\n\t\t\tfor (int x = 0; x < dimension; ++x) in >> mean[x];\n\t\t\tfor (int x = 0; x < dimension; ++x)\n\t\t\t\tfor (int y = 0; y < dimension; ++y)\n\t\t\t\t\tin >> cov(x, y);\n\t\t\tgaussians.emplace_back(mean, cov);\n\t\t}\n\t}\n\n#ifndef NDEBUG\n\tfor (int k = 0; k < components; ++k)\n\t{\n\t\tstd::cout << \"\\nComponent \" << k\n\t\t\t<< \"\\nWeight: \" << std::exp(logWeights[k])\n\t\t\t<< \"\\n\" << gaussians[k] << std::endl;\n\t}\n#endif\n\n\t//temporary memory\n\tEigen::MatrixXd logW(numPoints, components);\n\n\t//run EM (fixed number of iterations)\n\tstd::cout << \"Run EM algorithm\" << std::endl;\n\tstd::chrono::time_point<std::chrono::steady_clock> start;\n\tdouble logLikeliehoodAccum;\n\tfor (int iter=0; iter < numIterations; ++iter)\n\t{\n\t\t//half of the iterations for warm up\n\t\tif (iter==numIterations/2) start = std::chrono::steady_clock::now();\n\n#ifndef NDEBUG\n\t\tstd::cout << \"    Iteration \" << iter << std::endl;\n#endif\n\n\t\t//Precomputation\n#pragma omp parallel for\n\t\tfor (int i = 0; i < components; ++i)\n\t\t\tgaussians[i].computeDetInv();\n\n\t\t//E-Step\n\t\tlogLikeliehoodAccum = 0;\n\t\tfor (int i=0; i<numPoints; ++i)\n\t\t{\n\t\t\t//compute membership weight w_ik\n\t\t\tfor (int k=0; k<components; ++k)\n\t\t\t{\n\t\t\t\tdouble lw = gaussians[k].logP(points.col(i)) + logWeights[k];\n\t\t\t\tlogW(i, k) = lw;\n\t\t\t}\n\t\t\tdouble lse = LSE(logW.row(i));\n\t\t\tlogW.row(i) -= Eigen::RowVectorXd::Constant(components, lse);\n\t\t\tlogLikeliehoodAccum += lse;\n\n#ifndef NDEBUG\n\t\t\tstd::cout << \"Point \" << i << \":\";\n\t\t\tfor (int k = 0; k < components; ++k)\n\t\t\t\tstd::cout << \" \" << std::exp(logW(i, k));\n\t\t\tstd::cout << std::endl;\n#endif\n\t\t}\n\n\t\t//M-Step\n\t\tfor (int k=0; k<components; ++k)\n\t\t{\n#ifndef NDEBUG\n\t\t\tstd::cout << \"\\nComponent \" << k << \" pre-update:\"\n\t\t\t\t<< \"\\nWeight: \" << std::exp(logWeights[k])\n\t\t\t\t<< \"\\n\" << gaussians[k] << std::endl;\n#endif\n\n\t\t\tdouble logNk = LSE(logW.col(k));\n\t\t\tdouble divNk = 1.0f / std::exp(logNk);\n\t\t\tlogWeights[k] = logNk - std::log(numPoints);\n\t\t\t//Eigen does not support batches, so I have to write it explicitly as a loop here\n\t\t\t//(and broadcasting is very ugly)\n\t\t\tgaussians[k].mean().setZero();\n\t\t\tgaussians[k].cov().setZero();\n\t\t\tfor (int i = 0; i < numPoints; ++i)\n\t\t\t\tgaussians[k].mean() += std::exp(logW(i, k)) * points.col(i);\n\t\t\tgaussians[k].mean() *= divNk;\n\t\t\tfor (int i = 0; i < numPoints; ++i)\n\t\t\t\tgaussians[k].cov() += std::exp(logW(i, k)) *\n\t\t\t\t\t(points.col(i) - gaussians[k].mean()) * (points.col(i) - gaussians[k].mean()).transpose();\n\t\t\tgaussians[k].cov() = gaussians[k].cov()*divNk \n\t\t\t+ Eigen::MatrixXd::Identity(dimension, dimension) * 1e-1;\n\n#ifndef NDEBUG\n\t\t\tstd::cout << \"Component \" << k << \" post-update:\"\n\t\t\t\t<< \"\\nWeight: \" << std::exp(logWeights[k])\n\t\t\t\t<< \"\\n\" << gaussians[k] << std::endl;\n#endif\n\t\t}\n\n#ifndef NDEBUG\n\t\tstd::cout << \" -> log-likelihood: \" << logLikeliehoodAccum << \"\\n\";\n#endif\n\t}\n#ifdef NDEBUG\n\tstd::cout << \" -> log-likelihood: \" << logLikeliehoodAccum << \"\\n\";\n#endif\n\n\tauto finish = std::chrono::steady_clock::now();\n\tdouble elapsed = std::chrono::duration_cast<\n\t\tstd::chrono::duration<double>>(finish - start).count() * 1000 * 2; //*2 for warm up\n\tstd::cout << \"    Done in \" << elapsed << \"ms\" << std::endl;\n\n\t//save results\n\treturnValues.Insert(std::make_pair(\"Time\", elapsed));\n\treturnValues.Insert(std::make_pair(\"LogLikelihood\", logLikeliehoodAccum));\n\tJson::Array comData;\n\tfor (int k=0; k<components; ++k)\n\t{\n\t\tJson::Object com;\n\t\tcom.Insert(std::make_pair(\"Weight\", std::exp(logWeights[k])));\n\t\tJson::Array m, c;\n\t\tfor (int i = 0; i < dimension; ++i) m.PushBack(gaussians[k].mean()[i]);\n\t\tfor (int i = 0; i < dimension; ++i)\n\t\t\tfor (int j = 0; j < dimension; ++j)\n\t\t\t\tc.PushBack(gaussians[k].cov()(i, j));\n\t\tcom.Insert(std::make_pair(\"Mean\", m));\n\t\tcom.Insert(std::make_pair(\"Cov\", c));\n\t\tcomData.PushBack(com);\n\t}\n\treturnValues.Insert(std::make_pair(\"Components\", comData));\n}", "meta": {"hexsha": "b3263ef9ee2f560b8ea2d7a8c6076d4029e536bc", "size": 7729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/gmm/Implementation_Eigen.cpp", "max_stars_repo_name": "chrismile/cuMat", "max_stars_repo_head_hexsha": "8bfe48393cc93aa4555c7b81b5b4f44c142b4ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-03-08T18:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T20:32:56.000Z", "max_issues_repo_path": "benchmarks/gmm/Implementation_Eigen.cpp", "max_issues_repo_name": "chrismile/cuMat", "max_issues_repo_head_hexsha": "8bfe48393cc93aa4555c7b81b5b4f44c142b4ebb", "max_issues_repo_licenses": ["MIT"], "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/gmm/Implementation_Eigen.cpp", "max_forks_repo_name": "chrismile/cuMat", "max_forks_repo_head_hexsha": "8bfe48393cc93aa4555c7b81b5b4f44c142b4ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-26T01:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T13:32:46.000Z", "avg_line_length": 29.3878326996, "max_line_length": 97, "alphanum_fraction": 0.6334584034, "num_tokens": 2475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5413532908843777}}
{"text": "\ufeff/*! \\file mabinogi_roulette_mc.cpp\n    \\brief \u30de\u30d3\u30ce\u30ae\u306e\u30eb\u30fc\u30ec\u30c3\u30c8\u30d3\u30f3\u30b4\u3092\u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u3059\u308b\n\n    Copyright \u00a9 2015-2017 @dc1394 All Rights Reserved.\n    This software is released under the BSD 2-Clause License.\n*/\n\n#include \"../checkpoint/checkpoint.h\"\n#include \"goexit/goexit.h\"\n#ifdef HAVE_SSE2\n\t#include \"myrandom/myrandsfmt.h\"\n#else\n\t#include \"myrandom/myrand.h\"\n#endif\n#include <algorithm>                            // for std::shuffle\n#include <cstdint>                              // for std::int32_t\n#include <cmath>                                // for std::sqrt\n#ifdef _MSC_VER\n\t#include <format>                           // for std::format\n#endif\n#include <fstream>                              // for std::ofstream\n#include <iostream>                             // for std::cout\n#include <iterator>                             // for std::begin, std::ostream_iterator\n#include <map>                                  // for std::map\n#include <random>                               // for std::mt19937\n#include <unordered_map>                        // for std::unordered_map\n#include <utility>                              // for std::make_pair, std::move\n#include <vector>                               // for std::vector\n#include <valarray>                             // for std::valarray\n#include <boost/algorithm/cxx11/iota.hpp>       // for boost::algorithm::iota\n#ifndef _MSC_VER\n\t#include <boost/format.hpp>                 // for boost::format\n#endif\n#include <boost/range/algorithm.hpp>            // for boost::find, boost::max_element, boost::transform\n#include <tbb/concurrent_vector.h>              // for tbb::concurrent_vector\n#include <tbb/parallel_for.h>                   // for tbb::parallel_for\n\nnamespace {\n    //! A global variable (constant expression).\n    /*!\n        \u5217\u306e\u30b5\u30a4\u30ba\n    */\n    static auto constexpr COLUMN = 5ULL;\n\n    //! A global variable (constant expression).\n    /*!\n        \u884c\u306e\u30b5\u30a4\u30ba\n    */\n    static auto constexpr ROW = 5ULL;\n\n    //! A global variable (constant expression).\n    /*!\n        \u30d3\u30f3\u30b4\u30dc\u30fc\u30c9\u306e\u30de\u30b9\u6570\n    */\n    static auto constexpr BOARDSIZE = ROW * COLUMN;\n\n    //! A global variable (constant expression).\n    /*!\n        \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u8a66\u884c\u56de\u6570\n    */\n    static auto constexpr MCMAX = 1000000U;\n\n    //! A global variable (constant expression).\n    /*!\n        \u884c\u30fb\u5217\u306e\u7dcf\u6570\n    */\n    static auto constexpr ROWCOLUMN = ROW + COLUMN;\n\n    //! A typedef.\n    /*!\n        \u305d\u306e\u30de\u30b9\u306b\u66f8\u304b\u308c\u3066\u3042\u308b\u756a\u53f7\u3068\u3001\u305d\u306e\u30de\u30b9\u304c\u5f53\u305f\u3063\u305f\u304b\u3069\u3046\u304b\u3092\u793a\u3059\u30d5\u30e9\u30b0\u306estd::pair\n    */\n    using mypair = std::pair<std::int32_t, bool>;\n\n    //! A typedef.\n    /*!\n        \u6570\u5b57\u3068\u6570\u5b57\u306estd::pair\n    */\n    using mypair2 = std::pair<std::int32_t, std::int32_t>;\n\n    //! A typedef.\n    /*!\n        (n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u5206\u5e03\u3092\u683c\u7d0d\u3059\u308b\u305f\u3081\u306emap\u306e\u578b\n    */\n    using mymap = std::map<std::int32_t, std::int32_t>;\n    \n\t//! A function.\n\t/*!\n\t\t(n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u307e\u305f\u306f\u30de\u30b9\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u5e73\u5747\u8a66\u884c\u56de\u6570\u3001\u57cb\u307e\u3063\u3066\u3044\u308b\u30de\u30b9\u307e\u305f\u306f\u884c\u30fb\u5217\u306e\u5e73\u5747\u500b\u6570\u3092\u6c42\u3081\u308b\n\t\t\\param mcresult \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u304c\u683c\u7d0d\u3055\u308c\u305f\u4e8c\u6b21\u5143\u53ef\u5909\u9577\u914d\u5217\n\t\t\\param size \u884c\u30fb\u5217\u307e\u305f\u306f\u30de\u30b9\u306e\u7dcf\u6570\n\t\t\\return (n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u5e73\u5747\u8a66\u884c\u56de\u6570\u3001\u57cb\u307e\u3063\u3066\u3044\u308b\u30de\u30b9\u306e\u5e73\u5747\u500b\u6570\u304c\u683c\u7d0d\u3055\u308c\u305f\u53ef\u5909\u9577\u914d\u5217\u306estd::pair\n\t*/\n\tstd::pair< std::valarray<double>, std::valarray<double> > eval_average(tbb::concurrent_vector< std::vector<mypair2> > const & mcresult, std::size_t size);\n\n\t//! A function.\n\t/*!\n\t\t(n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u4e2d\u592e\u5024\u3092\u6c42\u3081\u308b\n\t\t\\param (n + 1)\u500b\u76ee\u306e\u6570\u5024n\n\t\t\\param mcresult \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u304c\u683c\u7d0d\u3055\u308c\u305f\u4e8c\u6b21\u5143\u53ef\u5909\u9577\u914d\u5217\n\t\t\\return (n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u4e2d\u592e\u5024\n\t*/\n\tstd::int32_t eval_median(tbb::concurrent_vector< std::vector<mypair2> > const & mcresult, std::int32_t n);\n\n\t//! A function.\n\t/*!\n\t\t(n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u6700\u983b\u5024\u3068\u5206\u5e03\u3092\u6c42\u3081\u308b\n\t\t\\param (n + 1)\u500b\u76ee\u306e\u6570\u5024n\n\t\t\\param mcresult \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u304c\u683c\u7d0d\u3055\u308c\u305f\u4e8c\u6b21\u5143\u53ef\u5909\u9577\u914d\u5217\n\t\t\\return (n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u6700\u983b\u5024\u3068\u5206\u5e03\u306estd::pair\n\t*/\n\tstd::pair<std::int32_t, std::map<std::int32_t, std::int32_t> > eval_mode(tbb::concurrent_vector< std::vector<mypair2> > const & mcresult, std::int32_t n);\n\n\t//! A function.\n\t/*!\n\t\t(n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u6a19\u6e96\u504f\u5dee\u3092\u6c42\u3081\u308b\n\t\t\\param avgten (n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u5e73\u5747\u8a66\u884c\u56de\u6570\n\t\t\\param (n + 1)\u500b\u76ee\u306e\u6570\u5024n\n\t\t\\param mcresult \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u304c\u683c\u7d0d\u3055\u308c\u305f\u4e8c\u6b21\u5143\u53ef\u5909\u9577\u914d\u5217\n\t\t\\return (n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u6a19\u6e96\u504f\u5dee\n\t*/\n\tdouble eval_std_deviation(double avg, tbb::concurrent_vector< std::vector<mypair2> > const & mcresult, std::int32_t n);\n\n    //! A function.\n    /*!\n        \u30d3\u30f3\u30b4\u30dc\u30fc\u30c9\u3092\u751f\u6210\u3059\u308b\n        \\return \u30d3\u30f3\u30b4\u30dc\u30fc\u30c9\u304c\u683c\u7d0d\u3055\u308c\u305f\u53ef\u5909\u9577\u914d\u5217\n    */\n    auto makeboard();\n\n#ifdef _CHECK_PARALELL_PERFORM\n    //! A function.\n    /*!\n        \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u3092\u884c\u3046\n        \\return \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u304c\u683c\u7d0d\u3055\u308c\u305f\u4e8c\u6b21\u5143\u53ef\u5909\u9577\u914d\u5217\n    */\n\tstd::pair<std::vector< std::vector<mypair2> >, std::vector< std::vector<mypair2> > > montecarlo();\n#endif\n\n    //! A function.\n    /*!\n        \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u5b9f\u88c5\n        \\param mr \u81ea\u4f5c\u4e71\u6570\u30af\u30e9\u30b9\u306e\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\n        \\return \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u6cd5\u306e\u7d50\u679c\u304c\u683c\u7d0d\u3055\u308c\u305f\u53ef\u5909\u9577\u914d\u5217\n    */\n\ttemplate <typename MyRandom>\n\tstd::pair<std::vector<mypair2>, std::vector<mypair2> > montecarloImpl(MyRandom & mr);\n\n    //! A function.\n    /*!\n        \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u3092TBB\u3067\u4e26\u5217\u5316\u3057\u3066\u884c\u3046\n        \\return \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u304c\u683c\u7d0d\u3055\u308c\u305f\u4e8c\u6b21\u5143\u53ef\u5909\u9577\u914d\u5217\n    */\n\tstd::pair<tbb::concurrent_vector< std::vector<mypair2> >, tbb::concurrent_vector< std::vector<mypair2> > > montecarloTBB();\n\n    //! A function.\n    /*!\n        (n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u5206\u5e03\u3092csv\u30d5\u30a1\u30a4\u30eb\u306b\u51fa\u529b\u3059\u308b\n\t\t\\param distmap (n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u5206\u5e03\n\t\t\\param filename \u30d5\u30a1\u30a4\u30eb\u540d\n    */\n    void outputcsv(mymap const & distmap, std::string const & filename);\n}\n\nint main()\n{\n    checkpoint::CheckPoint cp;\n\n    cp.checkpoint(\"\u51e6\u7406\u958b\u59cb\", __LINE__);\n\n#ifdef _CHECK_PARALELL_PERFORM\n    // \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u3092\u4ee3\u5165\n    auto const mcresult(montecarlo());\n\n    cp.checkpoint(\"\u4e26\u5217\u5316\u7121\u52b9\", __LINE__);\n#endif      \n\t\n    // TBB\u3067\u4e26\u5217\u5316\u3057\u305f\u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u3092\u4ee3\u5165\n    auto const mcresult2(montecarloTBB());\n\n    cp.checkpoint(\"\u4e26\u5217\u5316\u6709\u52b9\", __LINE__);\n\n    auto const [trialavg, fillavg] = eval_average(mcresult2.first, ROWCOLUMN);\n\n    for (auto n = 0U; n < ROWCOLUMN; n++) {\n\t\tauto const [mode, distmap] = eval_mode(mcresult2.first, n);\n#ifdef _MSC_VER\n\t\toutputcsv(distmap, std::format(\"result/distribution_{:d}\u500b\u76ee.csv\", n + 1));\n\n        std::cout \n\t\t\t<< std::format(\"\u30d3\u30f3\u30b4{:d}\u500b\u76ee\u306b\u5fc5\u8981\u306a\u5e73\u5747\u8a66\u884c\u56de\u6570\uff1a{:.1f}\u56de, \u52b9\u7387\uff1a{:.1f}(\u56de/\u500b), \", n + 1, trialavg[n], trialavg[n] / static_cast<double>(n + 1))\n\t\t\t<< std::format(\"\u4e2d\u592e\u5024\uff1a{:d}\u56de, \u6700\u983b\u5024\uff1a{:d}\u56de, \u6a19\u6e96\u504f\u5dee\uff1a{:.1f}, \", eval_median(mcresult2.first, n), mode, eval_std_deviation(trialavg[n], mcresult2.first, n))\n\t\t\t<< std::format(\"\u57cb\u307e\u3063\u3066\u3044\u308b\u30de\u30b9\u306e\u5e73\u5747\u500b\u6570\uff1a{:.1f}\u500b\\n\", fillavg[n]);\n#else\n        outputcsv(distmap, (boost::format(\"result/distribution_%d\u500b\u76ee.csv\") % (n + 1)).str());\n\n        std::cout\n            << boost::format(\"\u30d3\u30f3\u30b4%d\u500b\u76ee\u306b\u5fc5\u8981\u306a\u5e73\u5747\u8a66\u884c\u56de\u6570\uff1a%.1f\u56de, \u52b9\u7387\uff1a%.1f(\u56de/\u500b), \")\n            % (n + 1)\n            % trialavg[n]\n            % (trialavg[n] / static_cast<double>(n + 1))\n            << boost::format(\"\u4e2d\u592e\u5024\uff1a%d\u56de, \u6700\u983b\u5024\uff1a%d\u56de, \u6a19\u6e96\u504f\u5dee\uff1a%.1f, \")\n            % eval_median(mcresult2.first, n)\n            % mode\n            % eval_std_deviation(trialavg[n], mcresult2.first, n)\n            << boost::format(\"\u57cb\u307e\u3063\u3066\u3044\u308b\u30de\u30b9\u306e\u5e73\u5747\u500b\u6570\uff1a%.1f\u500b\\n\")\n            % fillavg[n];\n#endif\n    }\n\n\tauto const [trialavg2, fillavg2] = eval_average(mcresult2.second, BOARDSIZE);\n\n\tfor (auto n = 0U; n < BOARDSIZE; n++) {\n\t\tauto const [mode, distmap] = eval_mode(mcresult2.second, n);\n#ifdef _MSC_VER\n        outputcsv(distmap, std::format(\"result/distribution2_{:d}\u500b\u76ee.csv\", n + 1));\n\n        std::cout\n            << std::format(\"{:d}\u500b\u76ee\u306e\u30de\u30b9\u306b\u5fc5\u8981\u306a\u5e73\u5747\u8a66\u884c\u56de\u6570\uff1a{:.1f}\u56de, \u52b9\u7387\uff1a{:.1f}(\u56de/\u500b), \", n + 1, trialavg2[n], trialavg2[n] / static_cast<double>(n + 1))\n            << std::format(\"\u4e2d\u592e\u5024\uff1a{:d}\u56de, \u6700\u983b\u5024\uff1a{:d}\u56de, \u6a19\u6e96\u504f\u5dee\uff1a{:.1f}, \", eval_median(mcresult2.second, n), mode, eval_std_deviation(trialavg2[n], mcresult2.second, n))\n            << std::format(\"\u57cb\u307e\u3063\u3066\u3044\u308b\u884c\u30fb\u5217\u306e\u5e73\u5747\u500b\u6570\uff1a{:.1f}\u500b\\n\", fillavg2[n]);\n#else\n\t\toutputcsv(distmap, (boost::format(\"result/distribution2_%d\u500b\u76ee.csv\") % (n + 1)).str());\n\n\t\tstd::cout\n\t\t\t<< boost::format(\"%d\u500b\u76ee\u306e\u30de\u30b9\u306b\u5fc5\u8981\u306a\u5e73\u5747\u8a66\u884c\u56de\u6570\uff1a%.1f\u56de, \u52b9\u7387\uff1a%.1f(\u56de/\u500b), \")\n\t\t\t% (n + 1)\n\t\t\t% trialavg2[n]\n\t\t\t% (trialavg2[n] / static_cast<double>(n + 1))\n\t\t\t<< boost::format(\"\u4e2d\u592e\u5024\uff1a%d\u56de, \u6700\u983b\u5024\uff1a%d\u56de, \u6a19\u6e96\u504f\u5dee\uff1a%.1f, \")\n\t\t\t% eval_median(mcresult2.second, n)\n\t\t\t% mode\n\t\t\t% eval_std_deviation(trialavg2[n], mcresult2.second, n)\n\t\t\t<< boost::format(\"\u57cb\u307e\u3063\u3066\u3044\u308b\u884c\u30fb\u5217\u306e\u5e73\u5747\u500b\u6570\uff1a%.1f\u500b\\n\")\n\t\t\t% fillavg2[n];\n#endif\n\t}\n\n    cp.checkpoint(\"\u305d\u308c\u4ee5\u5916\u306e\u51e6\u7406\", __LINE__);\n\n    cp.checkpoint_print();\n\n\tgoexit::goexit();\n\n    return 0;\n}\n\nnamespace {\n    std::pair< std::valarray<double>, std::valarray<double> > eval_average(tbb::concurrent_vector< std::vector<mypair2> > const & mcresult, std::size_t size)\n    {\n        // \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u5e73\u5747\u8a66\u884c\u56de\u6570\u306e\u7d50\u679c\u3092\u683c\u7d0d\u3057\u305f\u53ef\u5909\u9577\u914d\u5217\n        std::valarray<double> trialavg(size);\n\n        // \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306en\u56de\u76ee\u306e\u8a66\u884c\u3067\u3001\u57cb\u307e\u3063\u3066\u3044\u308b\u30de\u30b9\u306e\u6570\u3092\u683c\u7d0d\u3057\u305f\u53ef\u5909\u9577\u914d\u5217\n        std::valarray<double> fillavg(size);\n\n        // \u884c\u30fb\u5217\u306e\u7dcf\u6570\u5206\u7e70\u308a\u8fd4\u3059\n        for (auto n = 0U; n < size; n++) {\n            // \u7dcf\u548c\u30920\u3067\u521d\u671f\u5316\n            auto trialsum = 0;\n            auto fillsum = 0;\n\n            // \u8a66\u884c\u56de\u6570\u5206\u7e70\u308a\u8fd4\u3059\n            for (auto j = 0U; j < MCMAX; j++) {\n                // j\u56de\u76ee\u306e\u7d50\u679c\u3092\u52a0\u3048\u308b\n                trialsum += mcresult[j][n].first;\n                fillsum += mcresult[j][n].second;\n            }\n\n            // \u5e73\u5747\u3092\u7b97\u51fa\u3057\u3066n\u884c\u30fb\u5217\u76ee\u306etrialavg\u3001fillavg\u306b\u4ee3\u5165\n            trialavg[n] = static_cast<double>(trialsum) / static_cast<double>(MCMAX);\n            fillavg[n] = static_cast<double>(fillsum) / static_cast<double>(MCMAX);\n        }\n\n        return std::make_pair(std::move(trialavg), std::move(fillavg));\n    }\n\n\tstd::int32_t eval_median(tbb::concurrent_vector< std::vector<mypair2> > const & mcresult, std::int32_t n)\n\t{\n\t\t// \u4e2d\u592e\u5024\u3092\u6c42\u3081\u308b\u305f\u3081\u306b\u5fc5\u8981\u306a\u53ef\u5909\u9577\u914d\u5217\n\t\tstd::vector<std::int32_t> medtmp(MCMAX);\n\n\t\t// \u4e2d\u592e\u5024\u3092\u6c42\u3081\u308b\u305f\u3081\u306b\u5fc5\u8981\u306a\u53ef\u5909\u9577\u914d\u5217\u3092\u3001\u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u6cd5\u306e\u7d50\u679c\u304b\u3089\u751f\u6210\n\t\tboost::transform(\n\t\t\tmcresult,\n\t\t\tmedtmp.begin(),\n\t\t\t[n](auto const & res) { return res[n].first; });\n\n\t\t// \u4e2d\u592e\u5024\u3092\u6c42\u3081\u308b\u305f\u3081\u306b\u30bd\u30fc\u30c8\u3059\u308b\n\t\tboost::sort(medtmp);\n\n\t\t// \u4e2d\u592e\u5024\u3092\u6c42\u3081\u308b\n\t\tif constexpr (MCMAX % 2) {\n\t\t\t// \u8981\u7d20\u304c\u5947\u6570\u500b\u306a\u3089\u4e2d\u592e\u306e\u8981\u7d20\u3092\u8fd4\u3059\n\t\t\treturn medtmp[(MCMAX - 1) / 2];\n\t\t}\n\t\telse {\n\t\t\t// \u8981\u7d20\u304c\u5076\u6570\u500b\u306a\u3089\u4e2d\u592e\u4e8c\u3064\u306e\u5e73\u5747\u3092\u8fd4\u3059\n\t\t\treturn (medtmp[(MCMAX / 2) - 1] + medtmp[MCMAX / 2]) / 2;\n\t\t}\n\t}\n\n\tstd::pair<std::int32_t, mymap> eval_mode(tbb::concurrent_vector< std::vector<mypair2> > const & mcresult, std::int32_t n)\n\t{\n\t\t// (n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u5206\u5e03\n\t\tstd::unordered_map<std::int32_t, std::int32_t> distmap;\n\n\t\t// distmap\u3092\u57cb\u3081\u308b\n\t\tfor (auto const & res : mcresult) {\n\t\t\t// (n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u56de\u6570\u3092key\u3068\u3059\u308b\n\t\t\tauto const key = res[n].first;\n\n\t\t\t// key\u304c\u5b58\u5728\u3059\u308b\u304b\u3069\u3046\u304b\n\t\t\tauto itr = distmap.find(key);\n\t\t\tif (itr == distmap.end()) {\n\t\t\t\t// key\u304c\u5b58\u5728\u3057\u306a\u304b\u3063\u305f\u306e\u3067\u3001\u305d\u306e\u30ad\u30fc\u3067\u30cf\u30c3\u30b7\u30e5\u3092\u62e1\u5f35\uff08\u50241\uff09\n\t\t\t\tdistmap.emplace(key, 1);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// key\u304c\u6307\u3059\u5024\u3092\u66f4\u65b0\n\t\t\t\titr->second++;\n\t\t\t}\n\t\t}\n\n\t\t// \u6700\u983b\u5024\u3092\u63a2\u7d22\n\t\tauto const mode = boost::max_element(\n\t\t\tdistmap,\n\t\t\t[](auto const & p1, auto const & p2) { return p1.second < p2.second; })->first;\n\n\t\t// \u6700\u983b\u5024\u3068(n + 1)\u500b\u76ee\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u5206\u5e03\u3092pair\u306b\u3057\u3066\u8fd4\u3059\n\t\treturn std::make_pair(mode, mymap(distmap.begin(), distmap.end()));\n\t}\n\n\tdouble eval_std_deviation(double avg, tbb::concurrent_vector< std::vector<mypair2> > const & mcresult, std::int32_t n)\n\t{\n\t\t// \u6a19\u6e96\u504f\u5dee\u3092\u6c42\u3081\u308b\u305f\u3081\u306b\u5fc5\u8981\u306a\u53ef\u5909\u9577\u914d\u5217\n\t\tstd::valarray<double> devtmp(MCMAX);\n\n\t\t// \u6a19\u6e96\u504f\u5dee\u306e\u8a08\u7b97\n\t\tboost::transform(\n\t\t\tmcresult,\n\t\t\tstd::begin(devtmp),\n\t\t\t[avg, n](auto const & res) {\n\t\t\tauto const val = static_cast<double>(res[n].first);\n\t\t\treturn (val - avg) * (val - avg);\n\t\t});\n\n\t\t// \u6a19\u6e96\u504f\u5dee\u3092\u6c42\u3081\u308b\n\t\treturn std::sqrt(devtmp.sum() / static_cast<double>(MCMAX));\n\t}\n\n    auto makeboard()\n    {\n        // \u4eee\u306e\u30d3\u30f3\u30b4\u30dc\u30fc\u30c9\u3092\u751f\u6210\n        std::vector<std::int32_t> boardtmp(BOARDSIZE);\n\n        // \u4eee\u306e\u30d3\u30f3\u30b4\u30dc\u30fc\u30c9\u306b1\uff5e25\u306e\u6570\u5b57\u3092\u4ee3\u5165\n        boost::algorithm::iota(boardtmp, 1);\n\n        // \u4eee\u306e\u30d3\u30f3\u30b4\u30dc\u30fc\u30c9\u306e\u6570\u5b57\u3092\u30b7\u30e3\u30c3\u30d5\u30eb\n        std::shuffle(boardtmp.begin(), boardtmp.end(), std::mt19937());\n\n        // \u30d3\u30f3\u30b4\u30dc\u30fc\u30c9\u3092\u751f\u6210\n        std::vector<mypair> board(BOARDSIZE);\n\n        // \u4eee\u306e\u30d3\u30f3\u30b4\u30dc\u30fc\u30c9\u304b\u3089\u30d3\u30f3\u30b4\u30dc\u30fc\u30c9\u3092\u751f\u6210\u3059\u308b\n        boost::transform(\n            boardtmp,\n            board.begin(),\n            [](auto n) { return std::make_pair(n, false); });\n\n        // \u30d3\u30f3\u30b4\u30dc\u30fc\u30c9\u3092\u8fd4\u3059\n        return board;\n    }\n\n#ifdef _CHECK_PARALELL_PERFORM\n\tstd::pair<std::vector< std::vector<mypair2> >, std::vector< std::vector<mypair2> > > montecarlo()\n    {\n        // \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u3092\u683c\u7d0d\u3059\u308b\u305f\u3081\u306e\u4e8c\u6b21\u5143\u53ef\u5909\u9577\u914d\u5217\n\t\tstd::pair<std::vector< std::vector<mypair2> >, std::vector< std::vector<mypair2> > > mcresult;\n\n\t\t// MCMAX\u500b\u306e\u5bb9\u91cf\u3092\u78ba\u4fdd\n\t\tmcresult.first.reserve(MCMAX);\n\t\tmcresult.second.reserve(MCMAX);\n\n#ifdef HAVE_SSE2\n\t\t// \u81ea\u4f5c\u4e71\u6570\u30af\u30e9\u30b9\u3092\u521d\u671f\u5316\n\t\tmyrandom::MyRandSfmt mr(1, BOARDSIZE);\n#else\n\t\t// \u81ea\u4f5c\u4e71\u6570\u30af\u30e9\u30b9\u3092\u521d\u671f\u5316\n\t\tmyrandom::MyRand mr(1, BOARDSIZE);\n#endif\n        // \u8a66\u884c\u56de\u6570\u5206\u7e70\u308a\u8fd4\u3059\n        for (auto n = 0U; n < MCMAX; n++) {\n\t\t\t// \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u3092\u4ee3\u5165\n\t\t\tauto const [resf, ress] = montecarloImpl(mr);\n\t\t\tmcresult.first.emplace_back(resf);\n\t\t\tmcresult.second.emplace_back(ress);\n        }\n\n        // \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u3092\u8fd4\u3059\n        return mcresult;\n    }\n#endif\n\n\ttemplate <typename MyRandom>\n\tstd::pair<std::vector<mypair2>, std::vector<mypair2> > montecarloImpl(MyRandom & mr)\n    {\n        // \u30d3\u30f3\u30b4\u30dc\u30fc\u30c9\u3092\u751f\u6210\n        auto board(makeboard());\n\n        // \u305d\u306e\u884c\u30fb\u5217\u304c\u65e2\u306b\u57cb\u307e\u3063\u3066\u3044\u308b\u304b\u3069\u3046\u304b\u3092\u683c\u7d0d\u3059\u308b\u53ef\u5909\u9577\u914d\u5217\n        // ROWCOLUMN\u500b\u306e\u8981\u7d20\u3092false\u3067\u521d\u671f\u5316\n        std::vector<bool> rcfill(ROWCOLUMN, false);\n\n        // \u884c\u30fb\u5217\u304c\u57cb\u307e\u308b\u307e\u3067\u306b\u8981\u3057\u305f\u56de\u6570\u3068\u3001\u305d\u306e\u6642\u70b9\u3067\u57cb\u307e\u3063\u305f\u30de\u30b9\u3092\u683c\u7d0d\u3057\u305f\n        // \u53ef\u5909\u9577\u914d\u5217\n        std::vector<mypair2> fillnum;\n\n\t\t// (n + 1)\u500b\u76ee\u306e\u30de\u30b9\u304c\u57cb\u307e\u3063\u305f\u3068\u304d\u306e\u56de\u6570\u3068\u3001\u305d\u306e\u6642\u70b9\u3067\u57cb\u307e\u3063\u305f\u884c\u30fb\u5217\u3092\u683c\u7d0d\u3057\u305f\n        // \u53ef\u5909\u9577\u914d\u5217\n\t\tstd::vector<mypair2> fillnum2;\n\n        // ROWCOLUMN\u500b\u306e\u5bb9\u91cf\u3092\u78ba\u4fdd\n        fillnum.reserve(ROWCOLUMN);\n\n        // \u305d\u306e\u6642\u70b9\u3067\u57cb\u307e\u3063\u3066\u3044\u308b\u30de\u30b9\u3092\u8a08\u7b97\u3059\u308b\u305f\u3081\u306e\u30e9\u30e0\u30c0\u5f0f\n        auto const sum = [](auto const & vec) {\n            auto cnt = 0;\n            for (auto & e : vec) {\n                if (e.second) {\n                    cnt++;\n                }\n            }\n\n            return cnt;\n        };\n\n        // \u7121\u9650\u30eb\u30fc\u30d7\n        for (auto n = 1; ; n++) {\n            // \u4e71\u6570\u3067\u5f97\u305f\u6570\u5b57\u3067\u3001\u304b\u3064\u307e\u3060\u5f53\u305f\u3063\u3066\u306a\u3044\u30de\u30b9\u3092\u691c\u7d22\n            auto itr = boost::find(board, std::make_pair(mr.myrand(), false));\n\n            // \u305d\u306e\u3088\u3046\u306a\u30de\u30b9\u304c\u3042\u3063\u305f\n            if (itr != board.end()) {\n                // \u305d\u306e\u30de\u30b9\u306f\u5f53\u305f\u3063\u305f\u3068\u3057\u3001\u30d5\u30e9\u30b0\u3092true\u306b\u3059\u308b\n                itr->second = true;\n            }\n            // \u305d\u306e\u3088\u3046\u306a\u30de\u30b9\u304c\u306a\u304b\u3063\u305f\n            else {\n                //\u30eb\u30fc\u30d7\u7d9a\u884c\n                continue;\n            }\n\n            // \u5404\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u304b\u3069\u3046\u304b\u3092\u30c1\u30a7\u30c3\u30af\n            for (auto j = 0U; j < ROW; j++) {\n                // \u5404\u884c\u304c\u57cb\u307e\u3063\u305f\u304b\u3069\u3046\u304b\u306e\u30d5\u30e9\u30b0\n                auto rowflag = true;\n\n                // \u5404\u884c\u304c\u57cb\u307e\u3063\u305f\u304b\u3069\u3046\u304b\u3092\u30c1\u30a7\u30c3\u30af\n                for (auto k = 0U; k < COLUMN; k++) {\n                    rowflag &= board[COLUMN * j + k].second;\n                }\n\n                // \u884c\u306e\u51e6\u7406\n                if (rowflag &&\n                    // \u305d\u306e\u884c\u306f\u65e2\u306b\u57cb\u307e\u3063\u3066\u3044\u308b\u304b\u3069\u3046\u304b\n                    !rcfill[j]) {\n                    // \u305d\u306e\u884c\u306f\u57cb\u307e\u3063\u305f\u3068\u3057\u3066\u3001\u30d5\u30e9\u30b0\u3092true\u306b\u3059\u308b\n                    rcfill[j] = true;\n\n                    // \u8981\u3057\u305f\u8a66\u884c\u56de\u6570\u3068\u3001\u305d\u306e\u6642\u70b9\u3067\u57cb\u307e\u3063\u305f\u30de\u30b9\u306e\u6570\u3092\u683c\u7d0d\n                    fillnum.emplace_back(n, sum(board));\n                }\n\n                // \u5404\u5217\u304c\u57cb\u307e\u3063\u305f\u304b\u3069\u3046\u304b\u306e\u30d5\u30e9\u30b0\n                auto columnflag = true;\n\n                // \u5404\u5217\u304c\u57cb\u307e\u3063\u305f\u304b\u3069\u3046\u304b\u3092\u30c1\u30a7\u30c3\u30af    \n                for (auto k = 0U; k < ROW; k++) {\n                    columnflag &= board[j + COLUMN * k].second;\n                }\n\n                // \u5217\u306e\u51e6\u7406\n                if (columnflag &&\n                    // \u305d\u306e\u5217\u306f\u65e2\u306b\u57cb\u307e\u3063\u3066\u3044\u308b\u304b\u3069\u3046\u304b\n                    !rcfill[j + ROW]) {\n\n                    // \u305d\u306e\u5217\u306f\u57cb\u307e\u3063\u305f\u3068\u3057\u3066\u3001\u30d5\u30e9\u30b0\u3092true\u306b\u3059\u308b\n                    rcfill[j + ROW] = true;\n\n                    // \u8981\u3057\u305f\u8a66\u884c\u56de\u6570\u3068\u3001\u305d\u306e\u6642\u70b9\u3067\u57cb\u307e\u3063\u305f\u30de\u30b9\u306e\u6570\u3092\u683c\u7d0d\n                    fillnum.emplace_back(n, sum(board));\n                }\n            }\n\n\t\t\t// \u8981\u3057\u305f\u8a66\u884c\u56de\u6570\u3068\u3001\u305d\u306e\u6642\u70b9\u3067\u57cb\u307e\u3063\u3066\u3044\u308b\u884c\u30fb\u5217\u306e\u6570\u3092\u683c\u7d0d\n\t\t\tfillnum2.emplace_back(n, static_cast<std::int32_t>(fillnum.size()));\n\n            // \u5168\u3066\u306e\u884c\u30fb\u5217\u304c\u57cb\u307e\u3063\u305f\u304b\u3069\u3046\u304b\n            if (fillnum.size() == ROWCOLUMN) {\n                // \u57cb\u307e\u3063\u305f\u306e\u3067\u30eb\u30fc\u30d7\u8131\u51fa\n                break;\n            }\n        }\n\n        // \u8981\u3057\u305f\u8a66\u884c\u95a2\u6570\u306e\u53ef\u5909\u9577\u914d\u5217\u3092\u8fd4\u3059\n        return std::make_pair(std::move(fillnum), std::move(fillnum2));\n    }\n\n    std::pair<tbb::concurrent_vector< std::vector<mypair2> >, tbb::concurrent_vector< std::vector<mypair2> > > montecarloTBB()\n    {\n        // \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u3092\u683c\u7d0d\u3059\u308b\u305f\u3081\u306e\u4e8c\u6b21\u5143\u53ef\u5909\u9577\u914d\u5217\n        // \u8907\u6570\u306e\u30b9\u30ec\u30c3\u30c9\u304c\u540c\u6642\u306b\u30a2\u30af\u30bb\u30b9\u3059\u308b\u53ef\u80fd\u6027\u304c\u3042\u308b\u305f\u3081tbb::concurrent_vector\u3092\u4f7f\u3046\n        std::pair<tbb::concurrent_vector< std::vector<mypair2> >, tbb::concurrent_vector< std::vector<mypair2> > > mcresult;\n\n        // MCMAX\u500b\u306e\u5bb9\u91cf\u3092\u78ba\u4fdd\n        mcresult.first.reserve(MCMAX);\n\t\tmcresult.second.reserve(MCMAX);\n\n        // MCMAX\u56de\u306e\u30eb\u30fc\u30d7\u3092\u4e26\u5217\u5316\u3057\u3066\u5b9f\u884c\n        tbb::parallel_for(\n            0U,\n            MCMAX,\n            1U,\n            [&mcresult](auto) {\n\n#ifdef HAVE_SSE2\n\t\t\t// \u81ea\u4f5c\u4e71\u6570\u30af\u30e9\u30b9\u3092\u521d\u671f\u5316\n\t\t\tmyrandom::MyRandSfmt mr(1, BOARDSIZE);\n#else\n\t\t\t// \u81ea\u4f5c\u4e71\u6570\u30af\u30e9\u30b9\u3092\u521d\u671f\u5316\n\t\t\tmyrandom::MyRand mr(1, BOARDSIZE);\n#endif\n\n            // \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u3092\u4ee3\u5165\n\t\t\tauto const [resf, ress] = montecarloImpl(mr);\n            mcresult.first.emplace_back(resf);\n\t\t\tmcresult.second.emplace_back(ress);\n        });\n\n        // \u30e2\u30f3\u30c6\u30ab\u30eb\u30ed\u30fb\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3\u306e\u7d50\u679c\u3092\u8fd4\u3059\n        return mcresult;\n    }\n\n    void outputcsv(mymap const & distmap, std::string const & filename)\n    {\n        std::ofstream ofs(filename);\n\n        boost::transform(\n            distmap,\n            std::ostream_iterator<std::string>(ofs, \"\\n\"),\n#ifdef _MSC_VER\n            [](auto const& p) { return std::format(\"{:d},{:d}\", p.first, p.second); });\n#else\n            [](auto const & p) { return (boost::format(\"%d,%d\") % p.first % p.second).str(); });\n#endif\n    }\n}\n\n", "meta": {"hexsha": "e637c3460bb7d6195ea9565389ad340ce3186de7", "size": 16706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mabinogi_roulette_MC/mabinogi_roulette_mc.cpp", "max_stars_repo_name": "dc1394/mabinogi_roulette_MC", "max_stars_repo_head_hexsha": "0494666ae6bea8d5f266a4a4948a4d255721c1b5", "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/mabinogi_roulette_MC/mabinogi_roulette_mc.cpp", "max_issues_repo_name": "dc1394/mabinogi_roulette_MC", "max_issues_repo_head_hexsha": "0494666ae6bea8d5f266a4a4948a4d255721c1b5", "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/mabinogi_roulette_MC/mabinogi_roulette_mc.cpp", "max_forks_repo_name": "dc1394/mabinogi_roulette_MC", "max_forks_repo_head_hexsha": "0494666ae6bea8d5f266a4a4948a4d255721c1b5", "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.7789661319, "max_line_length": 160, "alphanum_fraction": 0.5755417215, "num_tokens": 6838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.541353285763154}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// MIT License\n//\n// Copyright (c) 2017 Jonas Spenger\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n////////////////////////////////////////////////////////////////////////////////\n//\n// This is a modified (see below) version of the SAX algorithm proposed in:\n//  Lin, Jessica, et al. \"A symbolic representation of time series, with\n//  implications for streaming algorithms.\" Proceedings of the 8th ACM SIGMOD\n//  workshop on Research issues in data mining and knowledge discovery.  ACM,\n//  2003.\n//\n// This implementation (MSAX) differs from the original SAX in two aspects.\n//  (1) The time series is normalized by normalizing each point to the\n//      neighbouring #windowsize points. That is, for each point we subtract\n//      the moving average and divide by the moving standard deviation (with\n//      a moving window of size windowsize). In the original SAX algorithm,\n//      each subsequence is normalized.\n//  (2) Because the entire time series is normalized, this implementation\n//      outputs just one symbolic sequence, that represents the entire time\n//      series. In comparison to the original SAX, which outputs a symbolic\n//      sequence for every subsequence of the time series (of size windowsize),\n//      resulting in more than one symbolic sequences.\n//\n//  To use this include file and run msax::run() with following parameters:\n//    timeSeries: the time series (a container / vector)\n//    alphabetSize: the size of the alphabet\n//    frameSize: the size of a frame that gets transformed to one symbol, the\n//               dimensionality reduction so to speak\n//    windowSize: the size of the moving window used for the normalization\n//\n////////////////////////////////////////////////////////////////////////////////\n\n\n#pragma once\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <boost/accumulators/statistics/rolling_mean.hpp>\n#include <boost/accumulators/statistics/rolling_variance.hpp>\n#include <vector>\n\nnamespace msax {\n\ntemplate <typename T>\nstd::vector<int> run(const T& timeSeries,\n                     size_t alphabetSize,\n                     size_t frameSize,\n                     size_t windowSize) {\n\n\n  //////////////////////////////////////////////////////////////////////////////\n  // Normalize the time series\n  //////////////////////////////////////////////////////////////////////////////\n\n  T normalizedTimeSeries(timeSeries.size());\n\n  // accumulator for calculating moving variance and moving average\n  boost::accumulators::accumulator_set\n    <double,\n    boost::accumulators::stats<boost::accumulators::tag::rolling_mean,\n    boost::accumulators::tag::rolling_variance> >\n    accumulator(boost::accumulators::tag::rolling_window::window_size = windowSize);\n\n  // calculate the mean and variance for first windowsize elements\n  for (size_t i = 0; i < windowSize; ++i) {\n      accumulator(timeSeries[i]);\n  }\n  // calculate the normalized values for the first windowsize / 2 elements\n  for (size_t i = 0; i < windowSize / 2; ++i) {\n    normalizedTimeSeries[i] = (timeSeries[i] - boost::accumulators::rolling_mean(accumulator))\n      / std::sqrt(boost::accumulators::rolling_variance(accumulator));\n  }\n  // calculate normalized values for windowsize/2 to timeSeries.size - (windowSize + 1) / 2 values\n  for (size_t i = windowSize; i < timeSeries.size(); ++i) {\n    accumulator(timeSeries[i]);\n    size_t j = i - (windowSize + 1) / 2;\n    normalizedTimeSeries[j] = (timeSeries[j] - boost::accumulators::rolling_mean(accumulator))\n      / std::sqrt(boost::accumulators::rolling_variance(accumulator));\n  }\n  // calculate normalized values for the last (windowSize + 1) / 2 values\n  for (size_t i = timeSeries.size() - (windowSize + 1) / 2; i < timeSeries.size(); ++i) {\n    normalizedTimeSeries[i] = (timeSeries[i] - boost::accumulators::rolling_mean(accumulator))\n      / std::sqrt(boost::accumulators::rolling_variance(accumulator));\n  }\n\n\n  //////////////////////////////////////////////////////////////////////////////\n  // Perform PAA (Piecewise Aggregate Approximation)\n  //////////////////////////////////////////////////////////////////////////////\n\n  T paaTimeSeries((normalizedTimeSeries.size() - 1) / frameSize + 1);\n\n  for (size_t i = 0; i < paaTimeSeries.size(); ++i) {\n    double mean = 0.0;\n\n    if (i == paaTimeSeries.size() - 1) {\n      for (size_t j = i * frameSize; j < normalizedTimeSeries.size(); ++j) {\n        mean += normalizedTimeSeries[j];\n      }\n      mean = mean / ((double)(normalizedTimeSeries.size() - i * frameSize));\n    } else {\n      for (size_t j = i * frameSize; j < (i+1) * frameSize; ++j) {\n        mean += normalizedTimeSeries[j];\n      }\n      mean = mean / ((double)frameSize);\n    }\n    paaTimeSeries[i] = mean;\n  }\n\n\n  //////////////////////////////////////////////////////////////////////////////\n  // Calculate breakpoints\n  //////////////////////////////////////////////////////////////////////////////\n\n  std::vector<double> breakpoints(alphabetSize - 1);\n  boost::math::normal stdNormDist(0.0, 1.0); // standard normal distribution\n  for (size_t i = 1; i < alphabetSize; ++i) {\n    double q = quantile(stdNormDist, ((double) i) / ((double) alphabetSize));\n    breakpoints[i-1] = q;\n  }\n\n\n  //////////////////////////////////////////////////////////////////////////////\n  // Discretize\n  //////////////////////////////////////////////////////////////////////////////\n\n  std::vector<int> output(paaTimeSeries.size());\n  // for each element of paaTimeSeries, map it to the corresponding symbol\n  // as defined by the breakpoints, if breakpoints[i] < value < breakpoints[i+1],\n  // then map it to symbol nom i+1\n  for (size_t i = 0; i < output.size(); ++i) {\n    for (size_t j = 0; j < breakpoints.size(); ++j) {\n      output[i] = breakpoints.size();\n      if (paaTimeSeries[i] < breakpoints[j]) {\n        output[i] = j;\n        break;\n      }\n    }\n  }\n\n  return output;\n} // run()\n\n} // namespace msax\n", "meta": {"hexsha": "4c54aa234a09952f218250b97c13f1420da1b6bc", "size": 7118, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/msax.hpp", "max_stars_repo_name": "spengerj/MSAX", "max_stars_repo_head_hexsha": "aacdd3ab3d9bdbe282962727f93cd4ca114973b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-22T03:37:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-22T03:37:22.000Z", "max_issues_repo_path": "src/msax.hpp", "max_issues_repo_name": "spengerj/MSAX", "max_issues_repo_head_hexsha": "aacdd3ab3d9bdbe282962727f93cd4ca114973b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/msax.hpp", "max_forks_repo_name": "spengerj/MSAX", "max_forks_repo_head_hexsha": "aacdd3ab3d9bdbe282962727f93cd4ca114973b9", "max_forks_repo_licenses": ["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.1393939394, "max_line_length": 98, "alphanum_fraction": 0.6050856982, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.541353284208492}}
{"text": "/*\n * statistics_ext.cc\n *\n *  Copyright (C) 2013 Diamond Light Source\n *\n *  Author: James Parkhurst\n *\n *  This code is distributed under the BSD license, a copy of which is\n *  included in the root directory of this package.\n */\n#include <boost/python.hpp>\n#include <boost/python/def.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <dials/array_family/scitbx_shared_and_versa.h>\n#include <dials/algorithms/statistics/kolmogorov_smirnov_one_sided_distribution.h>\n#include <dials/algorithms/statistics/kolmogorov_smirnov_two_sided_distribution.h>\n#include <dials/algorithms/statistics/kolmogorov_smirnov_test.h>\n#include <dials/algorithms/statistics/poisson_test.h>\n#include <dials/algorithms/statistics/correlation.h>\n#include <dials/algorithms/statistics/binned_gmm.h>\n\nnamespace dials { namespace algorithms { namespace boost_python {\n\n  using namespace boost::python;\n\n  template <typename RealType>\n  RealType kolmogorov_smirnov_one_sided_cdf(std::size_t n, RealType x) {\n    return cdf(kolmogorov_smirnov_one_sided_distribution<RealType>(n), x);\n  }\n\n  template <typename RealType>\n  RealType kolmogorov_smirnov_two_sided_cdf(std::size_t n, RealType x) {\n    return cdf(kolmogorov_smirnov_two_sided_distribution<RealType>(),\n               x * std::sqrt((double)n));\n  }\n\n  // template <typename RealType>\n  // RealType kolmogorov_smirnov_one_sided_pdf(std::size_t n, RealType x) {\n  // return pdf(kolmogorov_smirnov_one_sided_distribution<RealType>(n), x);\n  //}\n\n  template <typename RealType>\n  boost::python::tuple kolmogorov_smirnov_test_standard_normal(\n    const af::const_ref<RealType> &data,\n    std::string type) {\n    // Get the enumeration\n    KSType etype = TwoSided;\n    if (type.compare(\"less\") == 0) {\n      etype = Less;\n    } else if (type.compare(\"greater\") == 0) {\n      etype = Greater;\n    } else {\n      DIALS_ASSERT(type.compare(\"two_sided\") == 0);\n    }\n\n    // Perform the test\n    std::pair<RealType, RealType> result =\n      kolmogorov_smirnov_test(boost::math::normal_distribution<RealType>(0, 1),\n                              data.begin(),\n                              data.end(),\n                              etype);\n    return boost::python::make_tuple(result.first, result.second);\n  }\n\n  BOOST_PYTHON_MODULE(dials_algorithms_statistics_ext) {\n    def(\"kolmogorov_smirnov_one_sided_cdf\", &kolmogorov_smirnov_one_sided_cdf<double>);\n    def(\"kolmogorov_smirnov_two_sided_cdf\", &kolmogorov_smirnov_two_sided_cdf<double>);\n    // def(\"kolmogorov_smirnov_one_sided_pdf\",\n    //    &kolmogorov_smirnov_one_sided_pdf<double>);\n    def(\"kolmogorov_smirnov_test_standard_normal\",\n        &kolmogorov_smirnov_test_standard_normal<double>,\n        (arg(\"data\"), arg(\"type\") = \"two_sided\"));\n\n    def(\"poisson_expected_max_counts\", &poisson_expected_max_counts);\n\n    def(\"spearman_correlation_coefficient\", &spearman_correlation_coefficient<double>);\n    def(\"pearson_correlation_coefficient\", &pearson_correlation_coefficient<double>);\n\n    class_<BinnedGMMSingle1DFixedMean>(\"BinnedGMMSingle1DFixedMean\", no_init)\n      .def(init<const af::const_ref<double> &,\n                const af::const_ref<double> &,\n                const af::const_ref<double> &,\n                double,\n                double,\n                double,\n                std::size_t>())\n      .def(\"max_iter\", &BinnedGMMSingle1DFixedMean::max_iter)\n      .def(\"num_iter\", &BinnedGMMSingle1DFixedMean::num_iter)\n      .def(\"epsilon\", &BinnedGMMSingle1DFixedMean::epsilon)\n      .def(\"mu\", &BinnedGMMSingle1DFixedMean::mu)\n      .def(\"sigma\", &BinnedGMMSingle1DFixedMean::sigma);\n\n    class_<BinnedGMMSingle1D>(\"BinnedGMMSingle1D\", no_init)\n      .def(init<const af::const_ref<double> &,\n                const af::const_ref<double> &,\n                const af::const_ref<double> &,\n                double,\n                double,\n                double,\n                std::size_t>())\n      .def(\"max_iter\", &BinnedGMMSingle1D::max_iter)\n      .def(\"num_iter\", &BinnedGMMSingle1D::num_iter)\n      .def(\"epsilon\", &BinnedGMMSingle1D::epsilon)\n      .def(\"mu\", &BinnedGMMSingle1D::mu)\n      .def(\"sigma\", &BinnedGMMSingle1D::sigma);\n  }\n\n}}}  // namespace dials::algorithms::boost_python\n", "meta": {"hexsha": "fece0b5f97181b63fea6f5f0ab9f00fa5b9595dc", "size": 4205, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/statistics/boost_python/statistics_ext.cc", "max_stars_repo_name": "TiankunZhou/dials", "max_stars_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 58.0, "max_stars_repo_stars_event_min_datetime": "2015-10-15T09:28:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T20:09:38.000Z", "max_issues_repo_path": "algorithms/statistics/boost_python/statistics_ext.cc", "max_issues_repo_name": "TiankunZhou/dials", "max_issues_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1741.0, "max_issues_repo_issues_event_min_datetime": "2015-11-24T08:17:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:46:42.000Z", "max_forks_repo_path": "algorithms/statistics/boost_python/statistics_ext.cc", "max_forks_repo_name": "TiankunZhou/dials", "max_forks_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2015-10-14T13:44:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T14:45:56.000Z", "avg_line_length": 38.5779816514, "max_line_length": 87, "alphanum_fraction": 0.6832342449, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5413532790872683}}
{"text": "#include <boost/numeric/odeint.hpp>\n#include <catch/catch.hpp>\n#include <range/v3/all.hpp>\n\n#include \"../include/Plant.hpp\"\n#include \"../include/control-frp.hpp\"\n#include \"../include/pid.hpp\"\n#include \"../include/util/util-sim.hpp\"\n#include \"../include/util/util.hpp\"\n\n#include \"calculations/analytical_solutions.cpp\"\n\n#ifdef PLOT\n#include \"../include/plotting/gnuplot-iostream.h\"\n#include \"../include/plotting/plot-helpers.hpp\"\n#endif  // PLOT\n\nusing namespace ranges;\nnamespace ode = boost::numeric::odeint;\n\nusing CState = PIDState<>;                       // AKA U\nusing PState = SignalPt<std::array<double, 2>>;  // AKA X\n// NB:\n// PState = SignalPt<std::array<double, 2>>\n//          \u250c                \u2510\n//          \u2502        \u250c   \u2510   \u2502\n//        = \u2502  \u00b7 ,   \u2502 \u00b7 \u2502   \u2502\n//          \u2502        \u2502 \u00b7 \u2502   \u2502\n//          \u2502        \u2514   \u2518   \u2502\n//          \u2514                \u2518\n//            ^ Time   ^ [Position, Speed]\n//\n// On the other hand, sim::PState is just for Boost.odeint. It doesn't need\n// time, but must be augmented with the control variable:\n//\n// sim::Pstate = std::array<double, 3>\n//                \u250c   \u2510\n//                \u2502 \u00b7 \u2502  // Position\n//             =  \u2502 \u00b7 \u2502  // Speed\n//                \u2502 \u00b7 \u2502  // control variable for Boost.odeint.\n//                \u2514   \u2518\n\nconstexpr double dt = 0.001;  // seconds.\nconstexpr auto dts = util::double_to_duration(dt);\nconst auto now = chrono::steady_clock::now();\n\nconstexpr double mass = 1.;\nconstexpr double damp = 10. / mass;\nconstexpr double spring = 20. / mass;\nconstexpr double staticForce = 1. / mass;\nconstexpr double simTime = 2;  // seconds\nconst sim::Plant plant(staticForce, damp, spring);\node::runge_kutta4<sim::PState> stepper;\n\nconst CState u0 = {now, 0., 0., 0.};\nconst PState x0 = {now, {0., 0.}};\n\n// controlled_step : (X, U) \u2192 X  = (PState, CState) \u2192 PState\nconst auto controlled_step = [](const PState& x, const CState& u) -> PState {\n  // Remember: sim::PState is the timeless, augmented PState, not X. (See NB.)\n  sim::PState xOld = {x.value[0], x.value[1], u.ctrlVal};\n  sim::PState xNew = util::do_step_with(plant, stepper, dt, xOld);\n\n  return {x.time + dts, {xNew[0], xNew[1]}};\n};\n\n// step_response_coalg : (X, U) \u2192 optional<((X, U), (X, U))>\nconst auto make_step_response_coalg = [](auto controller) {\n  return\n      [controller](const std::pair<PState, CState>& xu)\n          -> std::optional<\n              std::pair<std::pair<PState, CState>, std::pair<PState, CState>>> {\n        const auto [x, u] = xu;\n        constexpr double positionSetpoint = 1.;\n\n        if (x.time > now + 2s) return {};\n\n        const SignalPt<double> error = {x.time, x.value[0] - positionSetpoint};\n        CState uNew = controller(u, error);\n        PState xNew = controlled_step(x, uNew);\n\n        return {{{x, u}, {xNew, uNew}}};\n      };\n};\n\nTEST_CASE(\n    \"Given system and controller parameters, simulation should reproduce \"\n    \"analytically computed step responses to within a margin of error. See \"\n    \"src/calculations for details. Simulations performed using anamorphism.\") {\n  SECTION(\"Test A (Proportional Control) anamorphism.\") {\n    constexpr double Kp = 300.;\n    constexpr double Ki = 0.;\n    constexpr double Kd = 0.;\n\n    auto step_response_coalg =\n        make_step_response_coalg(pid_algebra(Kp, Ki, Kd));\n\n    // result : std::vector<std::pair<PState, CState>>\n    auto result = util::unfold(step_response_coalg, std::pair{x0, u0});\n\n    {\n      constexpr double margin = 0.03;\n      auto simulatedPositions =\n          util::fmap([](auto xu) { return xu.first.value[0]; }, result);\n      auto theoreticalPositions = util::fmap(\n          [](auto xu) {\n            return analyt::test_A(util::unchrono_sec(xu.first.time - now));\n          },\n          result);\n\n#ifdef PLOT\n\n      const auto testData = util::fmap(\n          [](const auto& xu) {\n            return std::make_pair(util::unchrono_sec(xu.first.time - now),\n                                  xu.first.value[0]);\n          },\n          result);\n\n      plot_with_tube(\"Test A, (Kp, Ki, Kd) = (300, 0, 0).\", testData,\n                     &analyt::test_A, margin);\n\n#endif  // PLOT\n\n      REQUIRE(util::compareVectors(simulatedPositions, theoreticalPositions,\n                                   margin));\n    }\n  }\n\n  SECTION(\"Test B (Proportional-Derivative Control) anamorphism.\") {\n    constexpr double Kp = 300.;\n    constexpr double Ki = 0.;\n    constexpr double Kd = 10.;\n\n    auto step_response_coalg =\n        make_step_response_coalg(pid_algebra(Kp, Ki, Kd));\n\n    // result : std::vector<std::pair<PState, CState>>\n    auto result = util::unfold(step_response_coalg, std::pair{x0, u0});\n\n    {\n      constexpr double margin = 0.03;\n      auto simulatedPositions =\n          util::fmap([](auto xu) { return xu.first.value[0]; }, result);\n      auto theoreticalPositions = util::fmap(\n          [](auto xu) {\n            return analyt::test_B(util::unchrono_sec(xu.first.time - now));\n          },\n          result);\n\n#ifdef PLOT\n\n      const auto testData = util::fmap(\n          [](const auto& xu) {\n            return std::make_pair(util::unchrono_sec(xu.first.time - now),\n                                  xu.first.value[0]);\n          },\n          result);\n\n      plot_with_tube(\"Test B, (Kp, Ki, Kd) = (300, 0, 10).\", testData,\n                     &analyt::test_B, margin);\n\n#endif  // PLOT\n\n      REQUIRE(util::compareVectors(simulatedPositions, theoreticalPositions,\n                                   margin));\n    }\n  }\n\n  SECTION(\"Test C (Proportional-Integral Control) anamorphism.\") {\n    constexpr double Kp = 30.;\n    constexpr double Ki = 70.;\n    constexpr double Kd = 0.;\n\n    auto step_response_coalg =\n        make_step_response_coalg(pid_algebra(Kp, Ki, Kd));\n\n    // result : std::vector<std::pair<PState, CState>>\n    auto result = util::unfold(step_response_coalg, std::pair{x0, u0});\n\n    {\n      constexpr double margin = 0.03;\n      auto simulatedPositions =\n          util::fmap([](auto xu) { return xu.first.value[0]; }, result);\n      auto theoreticalPositions = util::fmap(\n          [](auto xu) {\n            return analyt::test_C(util::unchrono_sec(xu.first.time - now));\n          },\n          result);\n\n#ifdef PLOT\n\n      const auto testData = util::fmap(\n          [](const auto& xu) {\n            return std::make_pair(util::unchrono_sec(xu.first.time - now),\n                                  xu.first.value[0]);\n          },\n          result);\n\n      plot_with_tube(\"Test C, (Kp, Ki, Kd) = (30, 70, 0).\", testData,\n                     &analyt::test_C, margin);\n\n#endif  // PLOT\n\n      REQUIRE(util::compareVectors(simulatedPositions, theoreticalPositions,\n                                   margin));\n    }\n  }\n\n  SECTION(\"Test D (Proportional-Integral-Derivative Control) anamorphism.\") {\n    constexpr double Kp = 350.;\n    constexpr double Ki = 300.;\n    constexpr double Kd = 50.;\n\n    auto step_response_coalg =\n        make_step_response_coalg(pid_algebra(Kp, Ki, Kd));\n\n    // result : std::vector<std::pair<PState, CState>>\n    auto result = util::unfold(step_response_coalg, std::pair{x0, u0});\n\n    {\n      constexpr double margin = 0.07;\n      auto simulatedPositions =\n          util::fmap([](auto xu) { return xu.first.value[0]; }, result);\n      auto theoreticalPositions = util::fmap(\n          [](auto xu) {\n            return analyt::test_D(util::unchrono_sec(xu.first.time - now));\n          },\n          result);\n\n#ifdef PLOT\n\n      const auto testData = util::fmap(\n          [](const auto& xu) {\n            return std::make_pair(util::unchrono_sec(xu.first.time - now),\n                                  xu.first.value[0]);\n          },\n          result);\n\n      plot_with_tube(\"Test D, (Kp, Ki, Kd) = (350, 300, 50).\", testData,\n                     &analyt::test_D, margin);\n\n#endif  // PLOT\n\n      REQUIRE(util::compareVectors(simulatedPositions, theoreticalPositions,\n                                   margin));\n    }\n  }\n}\n", "meta": {"hexsha": "38dd8461fb3016d7d70fa2d69672f352fcade1e9", "size": 7939, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pid-unfold.cpp", "max_stars_repo_name": "timtro/pid-unfolding", "max_stars_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pid-unfold.cpp", "max_issues_repo_name": "timtro/pid-unfolding", "max_issues_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pid-unfold.cpp", "max_forks_repo_name": "timtro/pid-unfolding", "max_forks_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_forks_repo_licenses": ["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.756, "max_line_length": 80, "alphanum_fraction": 0.5682075828, "num_tokens": 2098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059462938815, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5413532773039874}}
{"text": "#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n  arma::mat output;\n  arma::mat input;\n\n  input = arma::zeros(16, 1);\n  input(0) = 1.5;\n  input(1) = 2.0;\n  input(2) = 2.3;\n  input(3) = 2.2;\n  input(4) = 1.7;\n  input(5) = 2.1;\n  input(6) = 1.9;\n  input(7) = 2.1;\n  input(8) = 1.4;\n  input(9) = 1.8;\n  input(10) = 1.5;\n  input(11) = 1.6;\n  input(12) = 1.3;\n  input(13) = 1.6;\n  input(14) = 1.4;\n  input(15) = 1.7;\n\n  //input = arma::mat(\"1.5 2.0 2.3 2.2 1.7 2.1 1.9 2.1 1.4 1.8 1.5 1.6 1.3 1.6 1.4 1.7\").t();\n\n  cout << \"-------------------------------------\" << endl;\n  cout << \"INPUT : \" << endl;\n  cout << \"Input shape : \"<< input.n_rows << \" \" << input.n_cols << endl;\n  cout << \"Input (Transposed view) : \" << input.t() << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  const size_t kernelWidth = 2;\n  const size_t kernelHeight = 2;\n  const size_t strideWidth = 2;\n  const size_t strideHeight = 2;\n  const bool floor = true;\n  size_t inSize = 0;\n  size_t outSize = 0;\n  bool reset = false;\n  size_t inputWidth = 0;\n  size_t inputHeight = 0;\n  size_t outputWidth = 0;\n  size_t outputHeight = 0;\n  bool deterministic = false;\n  size_t offset = 0;\n  size_t batchSize = 0;\n\n  inputHeight = 4;\n  inputWidth = 4;\n  batchSize = input.n_cols;\n  inSize = input.n_elem / (inputWidth * inputHeight * batchSize);\n\n  // cube(ptr_aux_mem, n_rows, n_cols, n_slices, copy_aux_mem = true, strict = false)\n  arma::cube inputTemp = arma::cube(const_cast<arma::mat &>(input).memptr(),\n      inputWidth, inputHeight, batchSize * inSize, false, false);\n\n  cout << \"inputTemp BEFORE POOLING: \" << endl;\n  cout << \"inputTemp shape : \"<< inputTemp.n_rows << \" \" << inputTemp.n_cols << endl;\n  cout << \"Num slices   : \" << inputTemp.n_slices << endl;\n  cout << inputTemp << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  outputWidth = std::floor(((inputWidth - (double) kernelWidth) / (double) strideWidth) + 1);\n  outputHeight = std::floor(((inputHeight - (double) kernelHeight) / (double) strideHeight) + 1);\n  offset = 0;\n\n  arma::cube outputTemp = arma::zeros<arma::cube>(outputWidth, outputHeight, batchSize * inSize);\n\n  cout << \"outputTemp BEFORE POOLING: \" << endl;\n  cout << \"outputTemp shape : \"<< outputTemp.n_rows << \" \" << outputTemp.n_cols << endl;\n  cout << outputTemp << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  std::vector<arma::cube> poolingIndices;\n  poolingIndices.push_back(outputTemp);\n\n  arma::Mat<size_t> indices;\n  arma::Col<size_t> indicesCol;\n\n  size_t elements = inputWidth * inputHeight;\n  indicesCol = arma::linspace<arma::Col<size_t> >(0, (elements - 1), elements);\n  indices = arma::Mat<size_t>(indicesCol.memptr(), inputWidth, inputHeight);\n  reset = true;\n\n  cout << \"All parameters of layer : \" << endl;\n  cout << \"kernelWidth   : \" << kernelWidth << endl;\n  cout << \"kernelHeight  : \" << kernelHeight << endl;\n  cout << \"strideWidth   : \" << strideWidth << endl;\n  cout << \"strideHeight  : \" << strideHeight << endl;\n  cout << \"inputWidth    : \" << inputWidth << endl;\n  cout << \"inputHeight   : \" << inputHeight << endl;\n  cout << \"outputWidth   : \" << outputWidth << endl;\n  cout << \"outputHeight  : \" << outputHeight << endl;\n  cout << \"batchSize     : \" << batchSize << endl;\n  cout << \"inSize        : \" << inSize << endl;\n  cout << \"outSize       : \" << batchSize * inSize << endl;\n  cout << \"offset        : \" << offset << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  cout << \"Calculations done inside (reset) conditional statement : \" << endl;\n  cout << \"indicesCol : \" << endl;\n  cout << \"indicesCol shape : \"<< indicesCol.n_rows << \" \" << indicesCol.n_cols << endl;\n  cout << \"indicesCol (Transposed view) : \" << indicesCol.t() << endl;\n  cout << \"indices : \" << endl;\n  cout << \"indices shape : \"<< indices.n_rows << \" \" << indices.n_cols << endl;\n  cout << indices << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  for (size_t s = 0; s < inputTemp.n_slices; s++)\n  {\n    // PoolingOperation(inputTemp.slice(s), outputTemp.slice(s),poolingIndices.back().slice(s));\n\n    const arma::mat& in = inputTemp.slice(s);\n    arma::mat& out = outputTemp.slice(s);\n    arma::mat& poolIndexes = poolingIndices.back().slice(s);\n\n    cout << \"poolingIndices FOR SLICE \" << s << \" BEFORE POOLING: \" << endl;\n    cout << poolingIndices.back().slice(s)<< endl;\n    cout << \"-------------------------------------\" << endl;\n\n    cout << \"POOLING OPERATIONS START NOW.\" << endl;\n    cout << \"-------------------------------------\" << endl;\n\n    size_t x = 0;\n    for (size_t j = 0, colidx = 0; j < out.n_cols; ++j, colidx += strideHeight)\n    {\n      size_t y = 0;\n      for (size_t i = 0, rowidx = 0; i < out.n_rows; ++i, rowidx += strideWidth)\n      {\n\n        arma::mat subInput = in(\n            arma::span(rowidx, rowidx + kernelWidth - 1 - offset),\n            arma::span(colidx, colidx + kernelHeight - 1 - offset)\n        );\n\n        // const size_t idx = pooling.Pooling(subInput);\n        const size_t idx = arma::as_scalar(arma::find(subInput.max() == subInput, 1));\n        out(i, j) = subInput(idx);\n\n\n        arma::Mat<size_t> subIndices = indices(\n            arma::span(rowidx, rowidx + kernelWidth - 1 - offset),\n            arma::span(colidx, colidx + kernelHeight - 1 - offset)\n        );\n\n        poolIndexes(i, j) = subIndices(idx);\n\n        cout << \"COUNTER (\" << x << \", \" << y << \") CALCULATIONS : \" << endl;\n        cout << \"subInput : \" << endl;\n        cout << subInput << endl;\n        cout << \"subIndices : \" << endl;\n        cout << subIndices << endl;\n        cout << \"idx : \" << idx << endl;\n        cout << \"subInput(idx) : \" << endl;\n        cout << subInput(idx) << endl;\n        cout << \"subIndices(idx) : \" << endl;\n        cout << subIndices(idx) << endl;\n        cout << \"-------------------------------------\" << endl;\n        y++;\n      }\n      x++;\n    }\n\n  cout << \"POOLING OPERATIONS END NOW.\" << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  cout << \"poolingIndices FOR SLICE \" << s << \" POST POOLING: \" << endl;\n  cout << poolingIndices.back().slice(s)<< endl;\n  cout << \"-------------------------------------\" << endl;\n\n  }\n\n  cout << \"inputTemp AFTER POOLING: \" << endl;\n  cout << \"inputTemp shape : \"<< inputTemp.n_rows << \" \" << inputTemp.n_cols << endl;\n  cout << \"Num slices   : \" << inputTemp.n_slices << endl;\n  cout << inputTemp << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  cout << \"outputTemp AFTER POOLING: \" << endl;\n  cout << \"outputTemp shape : \"<< outputTemp.n_rows << \" \" << outputTemp.n_cols << endl;\n  cout << outputTemp << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  output = arma::mat(outputTemp.memptr(), outputTemp.n_elem / batchSize, batchSize);\n  outputWidth = outputTemp.n_rows;\n  outputHeight = outputTemp.n_cols;\n  outSize = batchSize * inSize;\n\n  cout << \"OUTPUT : \" << endl;\n  cout << \"Output shape : \"<< output.n_rows << \" \" << output.n_cols << endl;\n  cout << \"Output (Transposed view) : \" << output.t() << endl;\n  cout << \"-------------------------------------\" << endl;\n\n\n  cout << \"-------------------------------------\" << endl;\n  cout << \"PSEUDO BACKWARD : \" << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  arma::cube gTemp;\n  gTemp = arma::zeros<arma::cube>(inputTemp.n_rows, inputTemp.n_cols, inputTemp.n_slices);\n\n  arma::cube mappedError;\n  mappedError = arma::ones<arma::cube>(outputWidth, outputHeight, outSize);\n\n  for (size_t s = 0; s < mappedError.n_slices; s++)\n  {\n    //Unpooling(mappedError.slice(s), gTemp.slice(s), poolingIndices.back().slice(s));\n\n    const arma::mat& error = mappedError.slice(s);\n    arma::mat& out = gTemp.slice(s);\n    arma::mat& poIdx = poolingIndices.back().slice(s);\n\n    for (size_t i = 0; i < poIdx.n_elem; ++i)\n    {\n      out(poIdx(i)) += error(i);\n    }\n\n    cout << \"OUTPUT : \" << endl;\n    cout << \"Output shape : \"<< out.n_rows << \" \" << out.n_cols << endl;\n    cout << \"Output (Transposed view) : \" << endl << out << endl;\n    cout << \"-------------------------------------\" << endl;\n  }\n\n\n  cout << \"-------------------------------------\" << endl;\n  cout << \"UNPOOLING : \" << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  // Output of MaxPool is the input for UnPooling.\n  input = arma::zeros(4, 1);\n  input(0) = 2.1;\n  input(1) = 2.3;\n  input(2) = 1.8;\n  input(3) = 1.7;\n\n  cout << \"-------------------------------------\" << endl;\n  cout << \"INPUT FOR UNPOOLING: \" << endl;\n  cout << \"Input shape : \"<< input.n_rows << \" \" << input.n_cols << endl;\n  cout << \"Input (Transposed view) : \" << input.t() << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  inSize = 0;\n  outSize = 0;\n  reset = false;\n  inputWidth = 0;\n  inputHeight = 0;\n  outputWidth = 0;\n  outputHeight = 0;\n  batchSize = 0;\n\n  inputHeight = 2;\n  inputWidth = 2;\n  batchSize = input.n_cols;\n  inSize = input.n_elem / (inputWidth * inputHeight * batchSize);\n\n  // cube(ptr_aux_mem, n_rows, n_cols, n_slices, copy_aux_mem = true, strict = false)\n  inputTemp = arma::cube(const_cast<arma::mat &>(input).memptr(),\n      inputWidth, inputHeight, batchSize * inSize, false, false);\n\n  cout << \"inputTemp BEFORE UNPOOLING: \" << endl;\n  cout << \"inputTemp shape : \"<< inputTemp.n_rows << \" \" << inputTemp.n_cols << endl;\n  cout << \"Num slices   : \" << inputTemp.n_slices << endl;\n  cout << inputTemp << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  outputWidth = (inputWidth - 1) * strideWidth + kernelWidth;\n  outputHeight = (inputHeight - 1) * strideHeight + kernelHeight;\n  outSize = batchSize * inSize;\n  outputTemp = arma::zeros<arma::cube>(outputWidth, outputHeight,\n      outSize);\n\n  cout << \"outputTemp BEFORE UNPOOLING: \" << endl;\n  cout << \"outputTemp shape : \"<< outputTemp.n_rows << \" \" << outputTemp.n_cols << endl;\n  cout << outputTemp << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  for (size_t s = 0; s < inputTemp.n_slices; s++)\n  {\n    // Unpooling(inputTemp.slice(s), outputTemp.slice(s), poolingIndices.back().slice(s));\n    const arma::mat& IN = inputTemp.slice(s);\n    arma::mat& OUT = outputTemp.slice(s);\n    arma::mat& INDICES = poolingIndices.back().slice(s);\n\n    for (size_t i = 0; i < INDICES.n_elem; ++i)\n    {\n      OUT(INDICES(i)) += IN(i);\n    }\n\n    cout << \"OUTPUT : \" << endl;\n    cout << \"Output shape : \"<< OUT.n_rows << \" \" << OUT.n_cols << endl;\n    cout << \"Output : \" << endl << OUT << endl;\n    cout << \"-------------------------------------\" << endl;\n  }\n\n  cout << \"inputTemp AFTER UNPOOLING: \" << endl;\n  cout << \"inputTemp shape : \"<< inputTemp.n_rows << \" \" << inputTemp.n_cols << endl;\n  cout << \"Num slices   : \" << inputTemp.n_slices << endl;\n  cout << inputTemp << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  cout << \"outputTemp AFTER UNPOOLING: \" << endl;\n  cout << \"outputTemp shape : \"<< outputTemp.n_rows << \" \" << outputTemp.n_cols << endl;\n  cout << outputTemp << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  cout << \"-------------------------------------\" << endl;\n  cout << \"UNPOOLING BACKWARD (PROOF OF CONCEPT): \" << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  arma::mat L;\n  L = arma::zeros(16, 1);\n  L(0) = 1;\n  L(1) = 2;\n  L(2) = 3;\n  L(3) = 4;\n  L(4) = 5;\n  L(5) = 6;\n  L(6) = 7;\n  L(7) = 8;\n  L(8) = 9;\n  L(9) = 10;\n  L(10) = 11;\n  L(11) = 12;\n  L(12) = 13;\n  L(13) = 14;\n  L(14) = 15;\n  L(15) = 16;\n\n  mappedError = arma::cube(const_cast<arma::mat &>(L).memptr(), outputWidth, outputHeight, outSize, false, false);\n  gTemp = arma::zeros<arma::cube>(inputWidth, inputHeight, outSize);\n\n  for (size_t s = 0; s < gTemp.n_slices; s++)\n  {\n    arma::mat& gySlice = mappedError.slice(s);\n    arma::mat& gSlice = gTemp.slice(s);\n    arma::mat& idxs = poolingIndices.back().slice(s);\n\n    cout << \"gySlice: \" << endl;\n    cout << \"gy shape : \"<< gySlice.n_rows << \" \" << gySlice.n_cols << endl;\n    cout << gySlice << endl;\n    cout << \"-------------------------------------\" << endl;\n\n    cout << \"gTempSlice BEFORE: \" << endl;\n    cout << \"g shape : \"<< gSlice.n_rows << \" \" << gSlice.n_cols << endl;\n    cout << gSlice << endl;\n    cout << \"-------------------------------------\" << endl;\n\n    for (size_t i = 0, j = 0; i < idxs.n_elem; ++i, ++j)\n    {\n      gSlice(j) = gySlice(idxs(i));\n    }\n\n    cout << \"gTempSlice AFTER: \" << endl;\n    cout << \"g shape : \"<< gSlice.n_rows << \" \" << gSlice.n_cols << endl;\n    cout << gSlice << endl;\n    cout << \"-------------------------------------\" << endl;\n  }\n\n  arma::mat g = arma::mat(gTemp.memptr(), gTemp.n_elem / batchSize, batchSize);\n  cout << \"g: \" << endl;\n  cout << \"g shape : \"<< g.n_rows << \" \" << g.n_cols << endl;\n  cout << g << endl;\n  cout << \"-------------------------------------\" << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "c21fe445305c99f8896e5cf111b8cefe63c15bd2", "size": 12941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unpool/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": "unpool/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": "unpool/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": 34.6943699732, "max_line_length": 114, "alphanum_fraction": 0.5187388919, "num_tokens": 3802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5413437123072459}}
{"text": "#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"vnl/vnl_matrix_ref.h\"\n#include \"vnl/vnl_matrix.h\"\n#include \"itkNumericTraits.h\"\n\n#include \"tkdCmdParser.h\"\n\n#include <iostream>\n#include <utility>\n#include <fstream>\n\n#include <boost/utility.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/betweenness_centrality.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/adjacency_matrix.hpp>\n\n/**\n * (Relative) Betweenness centrality.\n */\ntemplate< class DirectedProperty = boost::undirectedS >\nclass BC\n{\npublic:\n\n\ttypedef double PixelType;\n\n\ttypedef boost::property< boost::vertex_index_t, unsigned int, boost::property< boost::vertex_centrality_t, PixelType > > VertexPropertyType;\n\ttypedef boost::property< boost::edge_weight_t, PixelType, boost::property< boost::edge_centrality_t, PixelType > > EdgePropertyType;\n\ttypedef boost::adjacency_matrix< DirectedProperty, VertexPropertyType, EdgePropertyType > GraphMatrixType;\n\n\ttypedef itk::Image< PixelType, 2 > ImageType;\n\ttypedef vnl_matrix_ref< PixelType > DataMatrixType;\n\ttypedef vnl_vector< PixelType > VectorType;\n\n\t/**\n\t * Run.\n\t */\n\tvoid Run( const std::string& filename, PixelType lowerThreshold, PixelType upperThreshold, const std::string& outputFileName,\n\t\t\tbool relative, bool dominance )\n\t{\n\t\ttypedef itk::ImageFileReader< ImageType > ReaderType;\n\t\ttypename ReaderType::Pointer reader = ReaderType::New();\n\t\treader->SetFileName( filename.c_str() );\n\t\treader->Update();\n\n\t\ttypename ImageType::Pointer image = reader->GetOutput();\n\t\treader = 0;\n\n\t\tPixelType* buffer = image->GetPixelContainer()->GetBufferPointer();\n\t\ttypename ImageType::RegionType region = image->GetLargestPossibleRegion();\n\t\ttypename ImageType::SizeType size = region.GetSize();\n\t\tint rows = size[0];\n\t\tint cols = size[1];\n\n\t\tDataMatrixType data( rows, cols, buffer );\n\n\t\ttypename ImageType::Pointer output = ImageType::New();\n\t\toutput->CopyInformation( image );\n\t\toutput->SetRegions( image->GetLargestPossibleRegion() );\n\t\toutput->Allocate();\n\t\toutput->FillBuffer( 0 );\n\n\t\tDataMatrixType distance( rows, cols, output->GetPixelContainer()->GetBufferPointer() );\n\n\t\tGraphMatrixType g( rows );\n\n\t\t/* TEST List -> weighted version works, and indeed lower values are shorter paths,\n\t\tGraphMatrixType g( 5 );\n\t\tboost::add_edge( 0, 1, EdgePropertyType( 1.0 ), g );\n\t\tboost::add_edge( 1, 4, EdgePropertyType( 0.2 ), g );\n\t\tboost::add_edge( 4, 3, EdgePropertyType( 0.3 ), g );\n\t\tboost::add_edge( 0, 2, EdgePropertyType( 1.0 ), g );\n\t\tboost::add_edge( 2, 3, EdgePropertyType( 1.0 ), g );\n\t\t*/\n\n\t\tconst bool isUndirected = typeid(DirectedProperty) == typeid(boost::undirectedS);\n\t\tfor ( int i = 0; i < rows; ++i )\n\t\t{\n\t\t\tint start = isUndirected ? i + 1 : 0;\n\t\t\tfor ( int j = start; j < cols; ++j )\n\t\t\t{\n\t\t\t\tif ( i == j )\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tPixelType weight = data( i, j );\n\n\t\t\t\tif ( weight <= upperThreshold && weight > 0 && weight > lowerThreshold )\n\t\t\t\t{\n\t\t\t\t\t// bc makes use of fwsp, so invert weight (correlation coefficients ...)\n\t\t\t\t\tboost::add_edge( i, j, EdgePropertyType( 1.0 / weight ), g );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tVectorType centrality( boost::num_vertices( g ) );\n\t\ttypename boost::graph_traits< GraphMatrixType >::vertex_iterator vi, vi_end;\n\n\t\tboost::brandes_betweenness_centrality( g,\n\t\t\t\tcentrality_map( boost::get( boost::vertex_centrality, g ) ).\n\t\t\t\tedge_centrality_map( boost::get( boost::edge_centrality, g ) ).\n\t\t\t\tweight_map( boost::get(\n\t\t\t\t\t\tboost::edge_weight, g ) ) );\n\n\t\tif ( !relative )\n\t\t{\n\t\t\ttypename boost::property_map< GraphMatrixType, boost::vertex_centrality_t >::type b = boost::get( boost::vertex_centrality, g );\n\n\t\t\tfor ( tie( vi, vi_end ) = vertices( g ); vi != vi_end; ++vi )\n\t\t\t\tcentrality[*vi] = b[*vi];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tboost::relative_betweenness_centrality( g, boost::get( boost::vertex_centrality, g ) );\n\t\t\ttypename boost::property_map< GraphMatrixType, boost::vertex_centrality_t >::type r = boost::get( boost::vertex_centrality, g );\n\n\t\t\tfor ( boost::tie( vi, vi_end ) = vertices( g ); vi != vi_end; ++vi )\n\t\t\t\tcentrality[*vi] = r[*vi];\n\n\t\t\t// Central point dominance is correct if and only if betweenness centrality is relative!\n\t\t\tif ( dominance )\n\t\t\t{\n\t\t\t\tdouble dominance = boost::central_point_dominance( g, boost::get( boost::vertex_centrality, g ) );\n\t\t\t\tstd::cout << \"Dominance,\" << dominance << std::endl;\n\t\t\t}\n\t\t}\n\n\t\tWriteVectorToFile( outputFileName, centrality );\n\t}\n\n\t/**\n\t * Write vector to filename.\n\t */\n\tvoid WriteVectorToFile( const std::string& outputFileName, const VectorType& V )\n\t{\n\t\tstd::ofstream out( outputFileName.c_str() );\n\n\t\tif ( out.fail() )\n\t\t{\n\t\t\tstd::cerr << \"*** ERROR ***: Not able to write to: \" << outputFileName << \"!\" << std::endl;\n\t\t\texit( EXIT_FAILURE );\n\t\t}\n\n\t\tfor ( unsigned int i = 0; i < V.size(); i++ )\n\t\t\tout << V[i] << std::endl;\n\n\t\tout.close();\n\t}\n};\n\n/**\n * Betweenness centrality.\n */\nint main( int argc, char ** argv )\n{\n\ttkd::CmdParser p( \"betweenness centrality\", \"Calculate betweenness centrality measure for all vertices\" );\n\n\tstd::string inputFileName;\n\tstd::string outputFileName;\n\n\tfloat lowerThreshold = 0;\n\tfloat upperThreshold = 1.0;\n\tbool isUndirected = true;\n\tbool relative = true;\n\tbool dominance = false;\n\n\tp.AddArgument( inputFileName, \"input\" ) ->AddAlias( \"i\" ) ->SetDescription( \"Input image: 2D adjacency matrix\" ) ->SetRequired( true );\n\n\tp.AddArgument( upperThreshold, \"threshold\" ) ->AddAlias( \"thu\" ) ->AddAlias( \"t\" ) ->SetDescription(\n\t\t\t\"Threshold; only include paths with weight in (0, threshold] (default: 1.0)\" );\n\n\tp.AddArgument( lowerThreshold, \"threshold-lower\" ) ->AddAlias( \"thl\" ) ->SetDescription(\n\t\t\t\"Lower threshold; only include paths with weight > threshold (default: 0)\" );\n\n\tp.AddArgument( outputFileName, \"output\" ) ->AddAlias( \"o\" ) ->SetDescription(\n\t\t\t\"Output image: List with (relative) betweenness centralities per vertex\" ) ->SetRequired( true );\n\n\tp.AddArgument( isUndirected, \"undirected\" ) ->AddAlias( \"u\" ) ->SetDescription(\n\t\t\t\"Input is a symmetric matrix representing an undirected graph [default: true]\" );\n\n\tp.AddArgument( relative, \"relative\" ) ->AddAlias( \"r\" ) ->SetDescription( \"Relative betweenness centrality algorithm [default: true]\" );\n\n\tp.AddArgument( dominance, \"dominance\" ) ->AddAlias( \"d\" ) ->SetDescription( \"Print central point dominance [relative only, default: false]\" );\n\n\tif ( !p.Parse( argc, argv ) )\n\t{\n\t\tp.PrintUsage( std::cout );\n\t\treturn -1;\n\t}\n\n\tif ( isUndirected )\n\t{\n\t\tBC< boost::undirectedS > bc;\n\t\tbc.Run( inputFileName, lowerThreshold, upperThreshold, outputFileName, relative, dominance );\n\t} else\n\t{\n\t\tBC< boost::directedS > bc;\n\t\tbc.Run( inputFileName, lowerThreshold, upperThreshold, outputFileName, relative, dominance );\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "367fd9c6e1d8c49e3e76af9f34b993a8056890e5", "size": 6800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/graphs/betweenness.cpp", "max_stars_repo_name": "wmotte/toolkid", "max_stars_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/graphs/betweenness.cpp", "max_issues_repo_name": "wmotte/toolkid", "max_issues_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graphs/betweenness.cpp", "max_forks_repo_name": "wmotte/toolkid", "max_forks_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_forks_repo_licenses": ["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.5358851675, "max_line_length": 143, "alphanum_fraction": 0.6891176471, "num_tokens": 1899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5413437120807465}}
{"text": "/*! \\file cmsFundTrust.hpp\n    \\brief cms funding trust pricer - wrapper for excel export (Francis Duffy)\n\tPeter Caspers\n*/\n\n#include <ql/quantlib.hpp>\n\n#include <qle/models/hullwhite1.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <math.h>\n#include <qle/instruments/capfloorcmsswap.hpp>\n#include <qle/pricingengines/treecapfloorcmsswapengine.hpp>\n#include <qle/instruments/capfloorcmsswaption.hpp>\n#include <qle/pricingengines/treecapfloorcmsswaptionengine.hpp>\n\n#ifndef quantlib_cmsFundTrust_hpp\n#define quantlib_cmsFundTrust_hpp\n\nusing namespace boost;\nusing namespace std;\n\nnamespace QuantLib {\n\n\t/*! pricing for cms funding trust positions as developed by Francis Duffy */\n\t\n\tclass CmsFundTrust {\n\n\t\tpublic:\n\t\t\t\n\t\t\t/*! constructor */\n\t\t\tCmsFundTrust(const boost::shared_ptr<YieldTermStructure> yts, const boost::shared_ptr<SwaptionVolatilityStructure> swVol, const double meanRev, const double cmsMeanRev);\n\n\t\t\t/*! get results */\n\t\t\tvector<double> result(string tag);\n\t\t\n\t\tprivate:\n\t\t\t\n\t\t\tvoid calculate();\n\n\t\t\tboost::shared_ptr<YieldTermStructure> yts_;\n\t\t\tboost::shared_ptr<SwaptionVolatilityStructure> swVol_;\n\t\t\tdouble meanRev_, cmsMeanRev_;\n\n\t\t\tmap<string,vector<double>> results_;\n\n\t};\n\n\tnamespace cmsFundTrustHelper {\n\n\t\tReal cmsSwapletIntegrand(boost::shared_ptr<QuantExt::HullWhite1> aHw1, boost::shared_ptr<CmsCoupon> aCmsCoupon, \n\t\t\t\tReal cmsCap, Real cmsFloor, Handle<YieldTermStructure> aTermStructure, Real r);\n\t\n\t\tReal cmsIntegralValue(boost::shared_ptr<QuantExt::HullWhite1> aHw1, boost::shared_ptr<CmsCoupon> aCmsCoupon,\n\t\t\t\tReal cmsCap, Real cmsFloor, Handle<YieldTermStructure> aTermStructure, vector<Date> & volDates, vector<Real> & sigmas);\n\n\t\tReal solveVolFunc(boost::shared_ptr<QuantExt::HullWhite1> aHw1, boost::shared_ptr<CmsCoupon> aCmsCoupon,\n\t\t\t\tReal cmsCap, Real cmsFloor, Handle<YieldTermStructure> aTermStructure, Real aCmsRate, vector<Date> & volDates, \n\t\t\t\tvector<Real> sigmas, Real aVol);\n\n\t}\n\n}\n\n\n#endif\n\n", "meta": {"hexsha": "7d31748a4bb5aa8cf59b0eaef09dbce228179f67", "size": 1959, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/preexperimental/cmsFundTrust.hpp", "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": "ql/experimental/preexperimental/cmsFundTrust.hpp", "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": "ql/experimental/preexperimental/cmsFundTrust.hpp", "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": 29.2388059701, "max_line_length": 172, "alphanum_fraction": 0.7677386422, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5413437008325412}}
{"text": "//  (C) Copyright John Maddock 2007.\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#ifdef _MSC_VER\n#  define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#include <boost/detail/lightweight_test.hpp>\n#include <boost/math/special_functions/round.hpp>\n#include <boost/math/special_functions/trunc.hpp>\n#include <boost/math/special_functions/modf.hpp>\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include \"test.hpp\"\n\n#if !defined(TEST_MPF_50) && !defined(TEST_MPF) && !defined(TEST_BACKEND) && !defined(TEST_MPZ) && !defined(TEST_CPP_DEC_FLOAT) && !defined(TEST_MPFR) && !defined(TEST_MPFR_50) && !defined(TEST_MPQ)\n#  define TEST_MPF_50\n#  define TEST_MPFR_50\n#  define TEST_BACKEND\n#  define TEST_CPP_DEC_FLOAT\n\n#ifdef _MSC_VER\n#pragma message(\"CAUTION!!: No backend type specified so testing everything.... this will take some time!!\")\n#endif\n#ifdef __GNUC__\n#pragma warning \"CAUTION!!: No backend type specified so testing everything.... this will take some time!!\"\n#endif\n\n#endif\n\n#if defined(TEST_MPF_50)\n#include <boost/multiprecision/gmp.hpp>\n#endif\n#ifdef TEST_MPFR_50\n#include <boost/multiprecision/mpfr.hpp>\n#endif\n#ifdef TEST_BACKEND\n#include <boost/multiprecision/concepts/mp_number_archetypes.hpp>\n#endif\n#ifdef TEST_CPP_DEC_FLOAT\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#endif\n\n#ifdef BOOST_MSVC\n#pragma warning(disable:4127)\n#endif\n\nboost::mt19937 rng;\n\ntemplate <class T>\nT get_random()\n{\n   //\n   // Fill all the bits in T with random values,\n   // likewise set the exponent to a random value\n   // that will still fit inside a T, and always\n   // have a remainder as well as an integer part.\n   //\n   int bits = boost::math::tools::digits<T>();\n   int shift = 0;\n   int exponent = rng() % (bits - 4);\n   T result = 0;\n   while(bits > 0)\n   {\n      result += ldexp(static_cast<T>(rng()), shift);\n      shift += std::numeric_limits<int>::digits;\n      bits -= std::numeric_limits<int>::digits;\n   }\n   return rng() & 1u ? T(-ldexp(frexp(result, &bits), exponent)) : T(ldexp(frexp(result, &bits), exponent));\n}\n\ntemplate <class T, class U>\nvoid check_within_half(T a, U u)\n{\n   BOOST_MATH_STD_USING\n   if(fabs(a-u) > 0.5f)\n   {\n      BOOST_ERROR(\"Rounded result differed by more than 0.5 from the original\");\n      std::cerr << \"Values were: \" << std::setprecision(35) << std::setw(40)\n         << std::left << a << u << std::endl;\n   }\n   if((fabs(a - u) == 0.5f) && (fabs(static_cast<T>(u)) < fabs(a)))\n   {\n      BOOST_ERROR(\"Rounded result was towards zero with boost::round\");\n      std::cerr << \"Values were: \" << std::setprecision(35) << std::setw(40)\n         << std::left << a << u << std::endl;\n   }\n}\n\n//\n// We may not have an abs overload for long long so provide a fall back:\n//\ntemplate <class T>\ninline T safe_abs(T const& v ...)\n{\n   return v < 0 ? -v : v;\n}\n\ntemplate <class T, class U>\nvoid check_trunc_result(T a, U u)\n{\n   BOOST_MATH_STD_USING\n   if(fabs(a-u) >= 1)\n   {\n      BOOST_ERROR(\"Rounded result differed by more than 1 from the original\");\n      std::cerr << \"Values were: \" << std::setprecision(35) << std::setw(40)\n         << std::left << a << u << std::endl;\n   }\n   if(abs(a) < safe_abs(u))\n   {\n      BOOST_ERROR(\"Truncated result had larger absolute value than the original\");\n      std::cerr << \"Values were: \" << std::setprecision(35) << std::setw(40)\n         << std::left << a << u << std::endl;\n   }\n   if(fabs(static_cast<T>(u)) > fabs(a))\n   {\n      BOOST_ERROR(\"Rounded result was away from zero with boost::trunc\");\n      std::cerr << \"Values were: \" << std::setprecision(35) << std::setw(40)\n         << std::left << a << u << std::endl;\n   }\n}\n\ntemplate <class T, class U>\nvoid check_modf_result(T a, T fract, U ipart)\n{\n   BOOST_MATH_STD_USING\n   if(fract + ipart != a)\n   {\n      BOOST_ERROR(\"Fractional and integer results do not add up to the original value\");\n      std::cerr << \"Values were: \" << std::setprecision(35) << \" \"\n         << std::left << a << ipart << \" \" << fract << std::endl;\n   }\n   if((boost::math::sign(a) != boost::math::sign(fract)) && boost::math::sign(fract))\n   {\n      BOOST_ERROR(\"Original and fractional parts have differing signs\");\n      std::cerr << \"Values were: \" << std::setprecision(35) << \" \"\n         << std::left << a << ipart << \" \" << fract << std::endl;\n   }\n   if((boost::math::sign(a) != boost::math::sign(ipart)) && boost::math::sign(ipart))\n   {\n      BOOST_ERROR(\"Original and integer parts have differing signs\");\n      std::cerr << \"Values were: \" << std::setprecision(35) << \" \"\n         << std::left << a << ipart << \" \" << ipart << std::endl;\n   }\n   if(fabs(a-ipart) >= 1)\n   {\n      BOOST_ERROR(\"Rounded result differed by more than 1 from the original\");\n      std::cerr << \"Values were: \" << std::setprecision(35) << std::setw(40)\n         << std::left << a << ipart << std::endl;\n   }\n}\n\ntemplate <class T>\nvoid test()\n{\n   BOOST_MATH_STD_USING\n\n   for(int i = 0; i < 1000; ++i)\n   {\n      T arg = get_random<T>();\n      T r = round(arg);\n      check_within_half(arg, r);\n      BOOST_TEST(r == round(arg + 0));\n      r = trunc(arg);\n      check_trunc_result(arg, r);\n      BOOST_TEST(r == trunc(arg + 0));\n      T frac = modf(arg, &r);\n      check_modf_result(arg, frac, r);\n\n      if(abs(r) < (std::numeric_limits<int>::max)())\n      {\n         int i = iround(arg);\n         check_within_half(arg, i);\n         BOOST_TEST(i == iround(arg + 0));\n         i = itrunc(arg);\n         check_trunc_result(arg, i);\n         BOOST_TEST(i == itrunc(arg + 0));\n         r = modf(arg, &i);\n         check_modf_result(arg, r, i);\n      }\n      if(abs(r) < (std::numeric_limits<long>::max)())\n      {\n         long l = lround(arg);\n         check_within_half(arg, l);\n         BOOST_TEST(l == lround(arg + 0));\n         l = ltrunc(arg);\n         check_trunc_result(arg, l);\n         BOOST_TEST(l == ltrunc(arg + 0));\n         r = modf(arg, &l);\n         check_modf_result(arg, r, l);\n      }\n\n#ifdef BOOST_HAS_LONG_LONG\n      if(abs(r) < (std::numeric_limits<boost::long_long_type>::max)())\n      {\n         boost::long_long_type ll = llround(arg);\n         check_within_half(arg, ll);\n         BOOST_TEST(ll == llround(arg + 0));\n         ll = lltrunc(arg);\n         check_trunc_result(arg, ll);\n         BOOST_TEST(ll == lltrunc(arg + 0));\n         r = modf(arg, &ll);\n         check_modf_result(arg, r, ll);\n      }\n#endif\n   }\n   //\n   // Test boundary cases:\n   //\n   if(std::numeric_limits<T>::digits >= std::numeric_limits<int>::digits)\n   {\n      int si = iround(static_cast<T>((std::numeric_limits<int>::max)()));\n      check_within_half(static_cast<T>((std::numeric_limits<int>::max)()), si);\n      BOOST_TEST(si == iround(static_cast<T>((std::numeric_limits<int>::max)()) + 0));\n      si = iround(static_cast<T>((std::numeric_limits<int>::min)()));\n      check_within_half(static_cast<T>((std::numeric_limits<int>::min)()), si);\n      BOOST_TEST(si == iround(static_cast<T>((std::numeric_limits<int>::min)()) + 0));\n      si = itrunc(static_cast<T>((std::numeric_limits<int>::max)()));\n      check_trunc_result(static_cast<T>((std::numeric_limits<int>::max)()), si);\n      BOOST_TEST(si == itrunc(static_cast<T>((std::numeric_limits<int>::max)()) + 0));\n      si = itrunc(static_cast<T>((std::numeric_limits<int>::min)()));\n      check_trunc_result(static_cast<T>((std::numeric_limits<int>::min)()), si);\n      BOOST_TEST(si == itrunc(static_cast<T>((std::numeric_limits<int>::min)()) + 0));\n\n      si = iround(static_cast<T>((std::numeric_limits<int>::max)() - 1));\n      check_within_half(static_cast<T>((std::numeric_limits<int>::max)() - 1), si);\n      si = iround(static_cast<T>((std::numeric_limits<int>::min)() + 1));\n      check_within_half(static_cast<T>((std::numeric_limits<int>::min)() + 1), si);\n      si = itrunc(static_cast<T>((std::numeric_limits<int>::max)() - 1));\n      check_trunc_result(static_cast<T>((std::numeric_limits<int>::max)() - 1), si);\n      si = itrunc(static_cast<T>((std::numeric_limits<int>::min)() + 1));\n      check_trunc_result(static_cast<T>((std::numeric_limits<int>::min)() + 1), si);\n   }\n   if(std::numeric_limits<T>::digits >= std::numeric_limits<long>::digits)\n   {\n      long k = lround(static_cast<T>((std::numeric_limits<long>::max)()));\n      check_within_half(static_cast<T>((std::numeric_limits<long>::max)()), k);\n      BOOST_TEST(k == lround(static_cast<T>((std::numeric_limits<long>::max)()) + 0));\n      k = lround(static_cast<T>((std::numeric_limits<long>::min)()));\n      check_within_half(static_cast<T>((std::numeric_limits<long>::min)()), k);\n      BOOST_TEST(k == lround(static_cast<T>((std::numeric_limits<long>::min)()) + 0));\n      k = ltrunc(static_cast<T>((std::numeric_limits<long>::max)()));\n      check_trunc_result(static_cast<T>((std::numeric_limits<long>::max)()), k);\n      BOOST_TEST(k == ltrunc(static_cast<T>((std::numeric_limits<long>::max)()) + 0));\n      k = ltrunc(static_cast<T>((std::numeric_limits<long>::min)()));\n      check_trunc_result(static_cast<T>((std::numeric_limits<long>::min)()), k);\n      BOOST_TEST(k == ltrunc(static_cast<T>((std::numeric_limits<long>::min)()) + 0));\n\n      k = lround(static_cast<T>((std::numeric_limits<long>::max)() - 1));\n      check_within_half(static_cast<T>((std::numeric_limits<long>::max)() - 1), k);\n      k = lround(static_cast<T>((std::numeric_limits<long>::min)() + 1));\n      check_within_half(static_cast<T>((std::numeric_limits<long>::min)() + 1), k);\n      k = ltrunc(static_cast<T>((std::numeric_limits<long>::max)() - 1));\n      check_trunc_result(static_cast<T>((std::numeric_limits<long>::max)() - 1), k);\n      k = ltrunc(static_cast<T>((std::numeric_limits<long>::min)() + 1));\n      check_trunc_result(static_cast<T>((std::numeric_limits<long>::min)() + 1), k);\n   }\n#ifndef BOOST_NO_LONG_LONG\n   if(std::numeric_limits<T>::digits >= std::numeric_limits<boost::long_long_type>::digits)\n   {\n      boost::long_long_type j = llround(static_cast<T>((std::numeric_limits<boost::long_long_type>::max)()));\n      check_within_half(static_cast<T>((std::numeric_limits<boost::long_long_type>::max)()), j);\n      BOOST_TEST(j == llround(static_cast<T>((std::numeric_limits<long long>::max)()) + 0));\n      j = llround(static_cast<T>((std::numeric_limits<boost::long_long_type>::min)()));\n      check_within_half(static_cast<T>((std::numeric_limits<boost::long_long_type>::min)()), j);\n      BOOST_TEST(j == llround(static_cast<T>((std::numeric_limits<long long>::min)()) + 0));\n      j = lltrunc(static_cast<T>((std::numeric_limits<boost::long_long_type>::max)()));\n      check_trunc_result(static_cast<T>((std::numeric_limits<boost::long_long_type>::max)()), j);\n      BOOST_TEST(j == lltrunc(static_cast<T>((std::numeric_limits<long long>::max)()) + 0));\n      j = lltrunc(static_cast<T>((std::numeric_limits<boost::long_long_type>::min)()));\n      check_trunc_result(static_cast<T>((std::numeric_limits<boost::long_long_type>::min)()), j);\n      BOOST_TEST(j == lltrunc(static_cast<T>((std::numeric_limits<long long>::min)()) + 0));\n\n      j = llround(static_cast<T>((std::numeric_limits<boost::long_long_type>::max)() - 1));\n      check_within_half(static_cast<T>((std::numeric_limits<boost::long_long_type>::max)() - 1), j);\n      j = llround(static_cast<T>((std::numeric_limits<boost::long_long_type>::min)() + 1));\n      check_within_half(static_cast<T>((std::numeric_limits<boost::long_long_type>::min)() + 1), j);\n      j = lltrunc(static_cast<T>((std::numeric_limits<boost::long_long_type>::max)() - 1));\n      check_trunc_result(static_cast<T>((std::numeric_limits<boost::long_long_type>::max)() - 1), j);\n      j = lltrunc(static_cast<T>((std::numeric_limits<boost::long_long_type>::min)() + 1));\n      check_trunc_result(static_cast<T>((std::numeric_limits<boost::long_long_type>::min)() + 1), j);\n   }\n#endif\n   //\n   // Finish off by testing the error handlers:\n   //\n   BOOST_CHECK_THROW(static_cast<T>(iround(static_cast<T>(1e20))), boost::math::rounding_error);\n   BOOST_CHECK_THROW(static_cast<T>(iround(static_cast<T>(-1e20))), boost::math::rounding_error);\n   BOOST_CHECK_THROW(static_cast<T>(lround(static_cast<T>(1e20))), boost::math::rounding_error);\n   BOOST_CHECK_THROW(static_cast<T>(lround(static_cast<T>(-1e20))), boost::math::rounding_error);\n#ifdef BOOST_HAS_LONG_LONG\n   BOOST_CHECK_THROW(static_cast<T>(llround(static_cast<T>(1e20))), boost::math::rounding_error);\n   BOOST_CHECK_THROW(static_cast<T>(llround(static_cast<T>(-1e20))), boost::math::rounding_error);\n#endif\n   if(std::numeric_limits<T>::has_infinity)\n   {\n      BOOST_CHECK_THROW(static_cast<T>(round(std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(iround(std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(iround(-std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(lround(std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(lround(-std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n   #ifdef BOOST_HAS_LONG_LONG\n      BOOST_CHECK_THROW(static_cast<T>(llround(std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(llround(-std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n   #endif\n   }\n   if(std::numeric_limits<T>::has_quiet_NaN)\n   {\n      BOOST_CHECK_THROW(static_cast<T>(round(std::numeric_limits<T>::quiet_NaN())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(iround(std::numeric_limits<T>::quiet_NaN())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(lround(std::numeric_limits<T>::quiet_NaN())), boost::math::rounding_error);\n   #ifdef BOOST_HAS_LONG_LONG\n      BOOST_CHECK_THROW(static_cast<T>(llround(std::numeric_limits<T>::quiet_NaN())), boost::math::rounding_error);\n   #endif\n   }\n   BOOST_CHECK_THROW(static_cast<T>(itrunc(static_cast<T>(1e20))), boost::math::rounding_error);\n   BOOST_CHECK_THROW(static_cast<T>(itrunc(static_cast<T>(-1e20))), boost::math::rounding_error);\n   BOOST_CHECK_THROW(static_cast<T>(ltrunc(static_cast<T>(1e20))), boost::math::rounding_error);\n   BOOST_CHECK_THROW(static_cast<T>(ltrunc(static_cast<T>(-1e20))), boost::math::rounding_error);\n#ifdef BOOST_HAS_LONG_LONG\n   BOOST_CHECK_THROW(static_cast<T>(lltrunc(static_cast<T>(1e20))), boost::math::rounding_error);\n   BOOST_CHECK_THROW(static_cast<T>(lltrunc(static_cast<T>(-1e20))), boost::math::rounding_error);\n#endif\n   if(std::numeric_limits<T>::has_infinity)\n   {\n      BOOST_CHECK_THROW(static_cast<T>(trunc(std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(itrunc(std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(itrunc(-std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(ltrunc(std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(ltrunc(-std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n   #ifdef BOOST_HAS_LONG_LONG\n      BOOST_CHECK_THROW(static_cast<T>(lltrunc(std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(lltrunc(-std::numeric_limits<T>::infinity())), boost::math::rounding_error);\n   #endif\n   }\n   if(std::numeric_limits<T>::has_quiet_NaN)\n   {\n      BOOST_CHECK_THROW(static_cast<T>(trunc(std::numeric_limits<T>::quiet_NaN())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(itrunc(std::numeric_limits<T>::quiet_NaN())), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(ltrunc(std::numeric_limits<T>::quiet_NaN())), boost::math::rounding_error);\n   #ifdef BOOST_HAS_LONG_LONG\n      BOOST_CHECK_THROW(static_cast<T>(lltrunc(std::numeric_limits<T>::quiet_NaN())), boost::math::rounding_error);\n   #endif\n   }\n   if(std::numeric_limits<T>::digits >= std::numeric_limits<int>::digits)\n   {\n      BOOST_CHECK_THROW(static_cast<T>(itrunc(static_cast<T>((std::numeric_limits<int>::max)()) + 1)), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(itrunc(static_cast<T>((std::numeric_limits<int>::min)()) - 1)), boost::math::rounding_error);\n   }\n   if(std::numeric_limits<T>::digits >= std::numeric_limits<long>::digits)\n   {\n      BOOST_CHECK_THROW(static_cast<T>(ltrunc(static_cast<T>((std::numeric_limits<long>::max)()) + 1)), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(ltrunc(static_cast<T>((std::numeric_limits<long>::min)()) - 1)), boost::math::rounding_error);\n   }\n#ifndef BOOST_NO_LONG_LONG\n   if(std::numeric_limits<T>::digits >= std::numeric_limits<boost::long_long_type>::digits)\n   {\n      BOOST_CHECK_THROW(static_cast<T>(lltrunc(static_cast<T>((std::numeric_limits<boost::long_long_type>::max)()) + 1)), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(lltrunc(static_cast<T>((std::numeric_limits<boost::long_long_type>::min)()) - 1)), boost::math::rounding_error);\n   }\n#endif\n   if(std::numeric_limits<T>::digits >= std::numeric_limits<int>::digits)\n   {\n      BOOST_CHECK_THROW(static_cast<T>(iround(static_cast<T>((std::numeric_limits<int>::max)()) + 1)), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(iround(static_cast<T>((std::numeric_limits<int>::min)()) - 1)), boost::math::rounding_error);\n   }\n   if(std::numeric_limits<T>::digits >= std::numeric_limits<long>::digits)\n   {\n      BOOST_CHECK_THROW(static_cast<T>(lround(static_cast<T>((std::numeric_limits<long>::max)()) + 1)), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(lround(static_cast<T>((std::numeric_limits<long>::min)()) - 1)), boost::math::rounding_error);\n   }\n#ifndef BOOST_NO_LONG_LONG\n   if(std::numeric_limits<T>::digits >= std::numeric_limits<boost::long_long_type>::digits)\n   {\n      BOOST_CHECK_THROW(static_cast<T>(llround(static_cast<T>((std::numeric_limits<boost::long_long_type>::max)()) + 1)), boost::math::rounding_error);\n      BOOST_CHECK_THROW(static_cast<T>(llround(static_cast<T>((std::numeric_limits<boost::long_long_type>::min)()) - 1)), boost::math::rounding_error);\n   }\n#endif\n}\n\nint main()\n{\n#ifdef TEST_MPF_50\n   test<boost::multiprecision::mpf_float_50>();\n   test<boost::multiprecision::mpf_float_100>();\n#endif\n#ifdef TEST_MPFR_50\n   test<boost::multiprecision::mpfr_float_50>();\n   test<boost::multiprecision::mpfr_float_100>();\n#endif\n#ifdef TEST_CPP_DEC_FLOAT\n   test<boost::multiprecision::cpp_dec_float_50>();\n   test<boost::multiprecision::cpp_dec_float_100>();\n#ifndef SLOW_COMPLER\n   // Some \"peculiar\" digit counts which stress our code:\n   test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<65> > >();\n   test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<64> > >();\n   test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<63> > >();\n   test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<62> > >();\n   test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<61, long long> > >();\n   test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<60, long long> > >();\n   test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<59, long long, std::allocator<void> > > >();\n   test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<58, long long, std::allocator<void> > > >();\n#endif\n#endif\n#ifdef TEST_BACKEND\n   test<boost::multiprecision::number<boost::multiprecision::concepts::number_backend_float_architype> >();\n#endif\n   return boost::report_errors();\n}\n\n\n\n\n\n", "meta": {"hexsha": "f5375d4fba90cc9a41cbc7a719315f1ac7695b58", "size": 19900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/test/test_round.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/multiprecision/test/test_round.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/multiprecision/test/test_round.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": 47.6076555024, "max_line_length": 198, "alphanum_fraction": 0.6662311558, "num_tokens": 5324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5413246043255525}}
{"text": "\n// Copyright (c) 2007, 2008 libmv authors.\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\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell 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\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\n// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n// Copyright (c) 2012, 2013 Pierre MOULON.\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 http://mozilla.org/MPL/2.0/.\n\n#include \"openMVG/numeric/numeric.h\"\n\n#include <Eigen/Geometry>\n\n#include <fstream>\n\nnamespace openMVG {\n\nMat3 CrossProductMatrix(const Vec3 &x) {\n  Mat3 X;\n  X << 0, -x(2),  x(1),\n    x(2),     0, -x(0),\n   -x(1),  x(0),     0;\n  return X;\n}\n\nMat3 RotationAroundX(double angle) {\n  return Eigen::AngleAxisd(angle, Vec3::UnitX()).toRotationMatrix();\n}\n\nMat3 RotationAroundY(double angle) {\n  return Eigen::AngleAxisd(angle, Vec3::UnitY()).toRotationMatrix();\n}\n\nMat3 RotationAroundZ(double angle) {\n  return Eigen::AngleAxisd(angle, Vec3::UnitZ()).toRotationMatrix();\n}\n\ndouble getRotationMagnitude(const Mat3 & R2) {\n  const Mat3 R1 = Mat3::Identity();\n  double cos_theta = (R1.array() * R2.array()).sum() / 3.0;\n  cos_theta = clamp(cos_theta, -1.0, 1.0);\n  return std::acos(cos_theta);\n}\n\nMat3 LookAt(const Vec3 &center, const Vec3 & up) {\n  Vec3 zc = center.normalized();\n  Vec3 xc = up.cross(zc).normalized();\n  Vec3 yc = zc.cross(xc);\n  Mat3 R;\n  R.row(0) = xc;\n  R.row(1) = yc;\n  R.row(2) = zc;\n  return R;\n}\n\n//eyePosition3D is a XYZ position. This is where you are (your eye is).\n//center3D is the XYZ position where you want to look at.\n//upVector3D is a XYZ normalized vector. Quite often 0.0, 1.0, 0.0\n\nMat3 LookAt2(const Vec3 &eyePosition3D,\n  const Vec3 &center3D,\n  const Vec3 &upVector3D )\n{\n  Vec3 forward, side, up;\n  Mat3 matrix2, resultMatrix;\n  //------------------\n  forward = center3D - eyePosition3D;\n  forward.normalize();\n  //------------------\n  //Side = forward x up\n  //ComputeNormalOfPlane(side, forward, upVector3D);\n  side[0]=(forward[1]*upVector3D[2])-(forward[2]*upVector3D[1]);\n  side[1]=(forward[2]*upVector3D[0])-(forward[0]*upVector3D[2]);\n  side[2]=(forward[0]*upVector3D[1])-(forward[1]*upVector3D[0]);\n  side.normalize();\n  //------------------\n  //Recompute up as: up = side x forward\n  //ComputeNormalOfPlane(up, side, forward);\n  up[0]=(side[1]*forward[2])-(side[2]*forward[1]);\n  up[1]=(side[2]*forward[0])-(side[0]*forward[2]);\n  up[2]=(side[0]*forward[1])-(side[1]*forward[0]);\n\n  //------------------\n  matrix2(0) = side[0];\n  matrix2(1) = side[1];\n  matrix2(2) = side[2];\n  //------------------\n  matrix2(3) = up[0];\n  matrix2(4) = up[1];\n  matrix2(5) = up[2];\n  //------------------\n  matrix2(6) = -forward[0];\n  matrix2(7) = -forward[1];\n  matrix2(8) = -forward[2];\n\n  return matrix2;\n}\n\nvoid MeanAndVarianceAlongRows(const Mat &A,\n  Vec *mean_pointer,\n  Vec *variance_pointer) {\n  const Mat::Index n = A.rows();\n  const double m = static_cast<double>(A.cols());\n  (*mean_pointer) = Vec::Zero(n);\n  (*variance_pointer) = Vec::Zero(n);\n\n  for (Mat::Index i = 0; i < n; ++i) {\n    (*mean_pointer)(i) += A.row(i).array().sum();\n    (*variance_pointer)(i) += (A.row(i).array() * A.row(i).array()).array().sum();\n  }\n  (*mean_pointer) /= m;\n  for (Mat::Index i = 0; i < n; ++i) {\n    (*variance_pointer)(i) = (*variance_pointer)(i) / m - Square((*mean_pointer)(i));\n  }\n}\n\nbool exportMatToTextFile(const Mat & mat, const std::string & filename,\n  const std::string & sPrefix)\n{\n  bool bOk = false;\n  std::ofstream outfile;\n  outfile.open(filename.c_str(), std::ios_base::out);\n  if (outfile.is_open()) {\n    outfile << sPrefix << \"=[\" << std::endl;\n    for (int j=0; j < mat.rows(); ++j)  {\n      for (int i=0; i < mat.cols(); ++i)  {\n        outfile << mat(j,i) << \" \";\n      }\n      outfile << \";\\n\";\n    }\n    outfile << \"];\";\n    bOk = true;\n  }\n  outfile.close();\n  return bOk;\n}\n\n}  // namespace openMVG\n", "meta": {"hexsha": "61b4d015bbb095f4e4324350ad17f4f21a07ec21", "size": 4900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/numeric/numeric.cpp", "max_stars_repo_name": "Aurelio93/satellite-pose-estimation", "max_stars_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2019-05-19T03:48:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:20:49.000Z", "max_issues_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/numeric/numeric.cpp", "max_issues_repo_name": "Aurelio93/satellite-pose-estimation", "max_issues_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-05-22T07:45:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T01:48:26.000Z", "max_forks_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/numeric/numeric.cpp", "max_forks_repo_name": "Aurelio93/satellite-pose-estimation", "max_forks_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-05-19T03:48:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-29T18:19:16.000Z", "avg_line_length": 30.8176100629, "max_line_length": 85, "alphanum_fraction": 0.6416326531, "num_tokens": 1485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5413245937572577}}
{"text": "/******************************************************************************\n * Copyright (C) 2013 by Jerome Maye                                          *\n * jerome.maye@gmail.com                                                      *\n *                                                                            *\n * This program is free software; you can redistribute it and/or modify       *\n * it under the terms of the Lesser 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 * Lesser GNU General Public License for more details.                        *\n *                                                                            *\n * You should have received a copy of the Lesser GNU General Public License   *\n * along with this program. If not, see <http://www.gnu.org/licenses/>.       *\n ******************************************************************************/\n\n#include \"aslam/calibration/functions/IncompleteGammaQFunction.h\"\n\n#include <boost/math/special_functions/gamma.hpp>\n\nnamespace aslam {\n  namespace calibration {\n\n/******************************************************************************/\n/* Constructors and Destructor                                                */\n/******************************************************************************/\n\n    IncompleteGammaQFunction::IncompleteGammaQFunction(double alpha) :\n        mAlpha(alpha) {\n    }\n\n    IncompleteGammaQFunction::IncompleteGammaQFunction(const\n        IncompleteGammaQFunction& other) :\n        mAlpha(other.mAlpha) {\n    }\n\n    IncompleteGammaQFunction& IncompleteGammaQFunction::operator = (const\n        IncompleteGammaQFunction& other) {\n      if (this != &other) {\n        mAlpha = other.mAlpha;\n      }\n      return *this;\n    }\n\n    IncompleteGammaQFunction::~IncompleteGammaQFunction() {\n    }\n\n/******************************************************************************/\n/* Stream operations                                                          */\n/******************************************************************************/\n\n    void IncompleteGammaQFunction::read(std::istream& stream) {\n    }\n\n    void IncompleteGammaQFunction::write(std::ostream& stream) const {\n      stream << \"alpha: \" << mAlpha;\n    }\n\n    void IncompleteGammaQFunction::read(std::ifstream& stream) {\n    }\n\n    void IncompleteGammaQFunction::write(std::ofstream& stream) const {\n    }\n\n/******************************************************************************/\n/* Accessors                                                                  */\n/******************************************************************************/\n\n    double IncompleteGammaQFunction::getValue(const VariableType& argument)\n        const {\n      return boost::math::gamma_q(mAlpha, argument);\n    }\n\n    double IncompleteGammaQFunction::getAlpha() const {\n      return mAlpha;\n    }\n\n    void IncompleteGammaQFunction::setAlpha(double alpha) {\n      mAlpha = alpha;\n    }\n\n  }\n}\n", "meta": {"hexsha": "db12e989b621ba9a0f0e9b8bc9c25fb9bc4522b4", "size": 3447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_incremental_calibration/incremental_calibration/src/functions/IncompleteGammaQFunction.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": "aslam_incremental_calibration/incremental_calibration/src/functions/IncompleteGammaQFunction.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": "aslam_incremental_calibration/incremental_calibration/src/functions/IncompleteGammaQFunction.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": 40.0813953488, "max_line_length": 80, "alphanum_fraction": 0.4395126197, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.541324589062942}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.\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// Transformation Example\n\n#include <iostream>\n\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\n\n\nint main()\n{\n    using namespace boost::geometry;\n\n    typedef model::d2::point_xy<double> point_2d;\n    point_2d p(1, 1);\n    point_2d p2;\n\n    // Example: translate a point over (5,5)\n    strategy::transform::translate_transformer<point_2d, point_2d> translate(5, 5);\n\n    transform(p, p2, translate);\n    std::cout << \"transformed point \" << boost::geometry::dsv(p2) << std::endl;\n\n    // Transform a polygon\n    model::polygon<point_2d> poly, poly2;\n    const double coor[][2] = { {0, 0}, {0, 7}, {2, 2}, {2, 0}, {0, 0} };\n    // note that for this syntax you have to include the two\n    // include files above (c_array.hpp)\n    assign_points(poly, coor);\n    //read_wkt(\"POLYGON((0 0,0 7,4 2,2 0,0 0))\", poly);\n    transform(poly, poly2, translate);\n\n    std::cout << \"source      polygon \" << boost::geometry::dsv(poly) << std::endl;\n    std::cout << \"transformed polygon \" << boost::geometry::dsv(poly2) << std::endl;\n\n    // Many more transformations are possible:\n    // - from Cartesian to Spherical coordinate systems and back\n    // - from Cartesian to Cartesian (mapping, affine transformations) and back (inverse)\n    // - Map Projections\n    // - from Degree to Radian and back in spherical_equatorial or geographic coordinate systems\n\n    return 0;\n}\n", "meta": {"hexsha": "a0f0d2d71355ffd2d9e9069d66b9d0179ddf743a", "size": 1992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/example/06_a_transformation_example.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/example/06_a_transformation_example.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/example/06_a_transformation_example.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": 34.9473684211, "max_line_length": 96, "alphanum_fraction": 0.6902610442, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5413245843686263}}
{"text": "/*\n * Copyright Andrey Semashev 2020\n *\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/*!\n * \\file is_power_of_2.hpp\n *\n * This header defines \\c is_power_of_2 algorithm, which returns \\c true if the passed integer is a power of 2.\n */\n\n#ifndef BOOST_BIT_OPS_POW2_IS_POWER_OF_2_HPP_INCLUDED_\n#define BOOST_BIT_OPS_POW2_IS_POWER_OF_2_HPP_INCLUDED_\n\n#include <boost/bit_ops/detail/config.hpp>\n#include <boost/bit_ops/detail/type_traits/enable_if.hpp>\n#include <boost/bit_ops/detail/type_traits/is_integral.hpp>\n#include <boost/bit_ops/detail/type_traits/is_enum.hpp>\n#include <boost/bit_ops/detail/type_traits/is_signed.hpp>\n#include <boost/bit_ops/detail/type_traits/is_unsigned.hpp>\n#include <boost/bit_ops/detail/type_traits/make_unsigned.hpp>\n#include <boost/bit_ops/detail/type_traits/underlying_type.hpp>\n\nnamespace boost {\nnamespace bit_ops {\n\n//! Tests if the integer is a power of 2\ntemplate< typename T >\ninline BOOST_CONSTEXPR typename bit_ops::detail::enable_if<\n    bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_unsigned< T >::value,\n    bool\n>::type is_power_of_2(T value) BOOST_NOEXCEPT\n{\n    return static_cast< bool >((value == static_cast< T >(0u)) ^ ((value & (value - static_cast< T >(1u))) == static_cast< T >(0u)));\n}\n\n//! Tests if the integer is a power of 2\ntemplate< typename T >\ninline BOOST_CONSTEXPR typename bit_ops::detail::enable_if<\n    bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_signed< T >::value,\n    bool\n>::type is_power_of_2(T value) BOOST_NOEXCEPT\n{\n    typedef typename bit_ops::detail::make_unsigned< T >::type unsigned_type;\n    return value <= static_cast< T >(0) ? false : bit_ops::is_power_of_2(static_cast< unsigned_type >(value));\n}\n\n//! Tests if the enum is a power of 2\ntemplate< typename T >\ninline BOOST_CONSTEXPR typename bit_ops::detail::enable_if<\n    bit_ops::detail::is_enum< T >::value,\n    bool\n>::type is_power_of_2(T value) BOOST_NOEXCEPT\n{\n    return bit_ops::is_power_of_2(static_cast< typename bit_ops::detail::underlying_type< T >::type >(value));\n}\n\n} // namespace bit_ops\n} // namespace boost\n\n#endif // BOOST_BIT_OPS_POW2_IS_POWER_OF_2_HPP_INCLUDED_\n", "meta": {"hexsha": "ee747734713011ce237bf56ccd5757966cd6c8fe", "size": 2269, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/bit_ops/pow2/is_power_of_2.hpp", "max_stars_repo_name": "Lastique/bit_ops", "max_stars_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops/pow2/is_power_of_2.hpp", "max_issues_repo_name": "Lastique/bit_ops", "max_issues_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops/pow2/is_power_of_2.hpp", "max_forks_repo_name": "Lastique/bit_ops", "max_forks_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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.453125, "max_line_length": 133, "alphanum_fraction": 0.7487880123, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370421, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5413176326673353}}
{"text": "/*\n  [auto_generated]\n  boost/numeric/odeint/stepper/symplectic_rkn_sb3a_m4_mclachlan.hpp\n\n  [begin_description]\n  tba.\n  [end_description]\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#ifndef BOOST_NUMERIC_ODEINT_STEPPER_SYMPLECTIC_RKN_SB3A_M4_MCLACHLAN_HPP_DEFINED\n#define BOOST_NUMERIC_ODEINT_STEPPER_SYMPLECTIC_RKN_SB3A_M4_MCLACHLAN_HPP_DEFINED\n\n#include <boost/numeric/odeint/algebra/default_operations.hpp>\n#include <boost/numeric/odeint/algebra/algebra_dispatcher.hpp>\n#include <boost/numeric/odeint/algebra/operations_dispatcher.hpp>\n\n#include <boost/numeric/odeint/util/resizer.hpp>\n\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\n#ifndef DOXYGEN_SKIP\nnamespace detail {\nnamespace symplectic_rkn_sb3a_m4_mclachlan {\n\n    /*\n      exp( a1 t A ) exp( b1 t B )\n      exp( a2 t A ) exp( b2 t B )\n      exp( a3 t A )\n      exp( b2 t B ) exp( a2 t A )\n      exp( b1 t B ) exp( a1 t A )\n    */\n\n\n\n    template< class Value >\n    struct coef_a_type : public boost::array< Value , 5 >\n    {\n        coef_a_type( void )\n        {\n            using std::sqrt;\n\n            Value z = sqrt( static_cast< Value >( 7 ) / static_cast< Value >( 8 ) ) / static_cast< Value >( 3 );\n            (*this)[0] = static_cast< Value >( 1 ) / static_cast< Value >( 2 ) - z ;\n            (*this)[1] = static_cast< Value >( -1 ) / static_cast< Value >( 3 ) + z ;\n            (*this)[2] = static_cast< Value >( 2 ) / static_cast< Value >( 3 );\n            (*this)[3] = (*this)[1];\n            (*this)[4] = (*this)[0];\n        }\n    };\n\n    template< class Value >\n    struct coef_b_type : public boost::array< Value , 5 >\n    {\n        coef_b_type( void )\n        {\n            (*this)[0] = static_cast< Value >( 1 );\n            (*this)[1] = static_cast< Value >( -1 ) / static_cast< Value >( 2 );\n            (*this)[2] = (*this)[1];\n            (*this)[3] = (*this)[0];\n            (*this)[4] = static_cast< Value >( 0 );\n        }\n    };\n\n} // namespace symplectic_rkn_sb3a_m4_mclachlan\n} // namespace detail\n#endif // DOXYGEN_SKIP\n\n\n\n\ntemplate<\n    class Coor ,\n    class Momentum = Coor ,\n    class Value = double ,\n    class CoorDeriv = Coor ,\n    class MomentumDeriv = Coor ,\n    class Time = Value ,\n    class Algebra = typename algebra_dispatcher< Coor >::algebra_type ,\n    class Operations = typename operations_dispatcher< Coor >::operations_type ,\n    class Resizer = initially_resizer\n    >\n#ifndef DOXYGEN_SKIP\nclass symplectic_rkn_sb3a_m4_mclachlan :\n        public symplectic_nystroem_stepper_base\n<\n    5 , 4 ,\n    Coor , Momentum , Value , CoorDeriv , MomentumDeriv , Time , Algebra , Operations , Resizer\n    >\n#else\nclass symplectic_rkn_sb3a_m4_mclachlan : public symplectic_nystroem_stepper_base\n#endif\n{\npublic:\n#ifndef DOXYGEN_SKIP\n    typedef symplectic_nystroem_stepper_base\n    <\n    5 , 4 ,\n    Coor , Momentum , Value , CoorDeriv , MomentumDeriv , Time , Algebra , Operations , Resizer\n    > stepper_base_type;\n#endif\n    typedef typename stepper_base_type::algebra_type algebra_type;\n    typedef typename stepper_base_type::value_type value_type;\n\n\n    symplectic_rkn_sb3a_m4_mclachlan( const algebra_type &algebra = algebra_type() )\n        : stepper_base_type(\n            detail::symplectic_rkn_sb3a_m4_mclachlan::coef_a_type< value_type >() ,\n            detail::symplectic_rkn_sb3a_m4_mclachlan::coef_b_type< value_type >() ,\n            algebra )\n    { }\n};\n\n\n/***************** DOXYGEN ***************/\n\n/**\n * \\class symplectic_rkn_sb3a_m4_mclachlan\n * \\brief Implementation of the symmetric B3A Runge-Kutta Nystroem method of fifth order.\n *\n * The method is of fourth order and has five stages. It is described HERE. This method can be used\n * with multiprecision types since the coefficients are defined analytically.\n *\n * ToDo: add reference to paper.\n *\n * \\tparam Order The order of the stepper.\n * \\tparam Coor The type representing the coordinates q.\n * \\tparam Momentum The type representing the coordinates p.\n * \\tparam Value The basic value type. Should be something like float, double or a high-precision type.\n * \\tparam CoorDeriv The type representing the time derivative of the coordinate dq/dt.\n * \\tparam MomemtnumDeriv The type representing the time derivative of the momentum dp/dt.\n * \\tparam Time The type representing the time t.\n * \\tparam Algebra The algebra.\n * \\tparam Operations The operations.\n * \\tparam Resizer The resizer policy.\n */\n\n    /**\n     * \\fn symplectic_rkn_sb3a_m4_mclachlan::symplectic_rkn_sb3a_m4_mclachlan( const algebra_type &algebra )\n     * \\brief Constructs the symplectic_rkn_sb3a_m4_mclachlan. This constructor can be used as a default\n     * constructor if the algebra has a default constructor.\n     * \\param algebra A copy of algebra is made and stored inside explicit_stepper_base.\n     */\n\n} // namespace odeint\n} // namespace numeric\n} // namespace boost\n\n\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_SYMPLECTIC_RKN_SB3A_M4_MCLACHLAN_HPP_DEFINED\n", "meta": {"hexsha": "1b9756cc1ad80dbec6be0f0e57addd21b3fbf560", "size": 5120, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Externals/Boost/boost/numeric/odeint/stepper/symplectic_rkn_sb3a_m4_mclachlan.hpp", "max_stars_repo_name": "MINATILO/packing-generation", "max_stars_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2015-08-23T12:05:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:39:56.000Z", "max_issues_repo_path": "Externals/Boost/boost/numeric/odeint/stepper/symplectic_rkn_sb3a_m4_mclachlan.hpp", "max_issues_repo_name": "MINATILO/packing-generation", "max_issues_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2015-07-20T17:57:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T10:31:50.000Z", "max_forks_repo_path": "Externals/Boost/boost/numeric/odeint/stepper/symplectic_rkn_sb3a_m4_mclachlan.hpp", "max_forks_repo_name": "MINATILO/packing-generation", "max_forks_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2015-10-14T02:43:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T12:51:03.000Z", "avg_line_length": 31.801242236, "max_line_length": 112, "alphanum_fraction": 0.680078125, "num_tokens": 1410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5413176207280233}}
{"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\n#pragma once\n#include <iostream>\n#include <stdint.h>\n#include <vector>\n#include <Eigen/Dense>\n\n#include <boost/shared_ptr.hpp>\n\n#include <dpMM/dpMM.hpp>\n#include <dpMM/cat.hpp>\n#include <dpMM/dir.hpp>\n#include <dpMM/niw.hpp>\n#include <dpMM/sampler.hpp>\n#include <dpMM/basemeasure.hpp>\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl; \nusing boost::shared_ptr;\nusing std::vector; \n\ntemplate<typename T=double>\nclass DirNaiveBayes : public DpMM<T>{\n\npublic:\n  DirNaiveBayes(const Dir<Cat<T>, T>& alpha, const boost::shared_ptr<BaseMeasure<T> >& theta);\n  DirNaiveBayes(const Dir<Cat<T>, T>& alpha, const vector<boost::shared_ptr<BaseMeasure<T> > >&thetas);\n  virtual ~DirNaiveBayes();\n\n  virtual void initialize(const vector< Matrix<T,Dynamic,Dynamic> >&x);\n  virtual void initialize(const boost::shared_ptr<ClGMMData<T> >&cld)\n    {cout<<\"not supported\"<<endl; assert(false);};\n\n  virtual void sampleLabels();\n  virtual void sampleParameters();\n\n  virtual T logJoint(bool verbose=false);\n  virtual const VectorXu& labels(){return z_;};\n  virtual const VectorXu& getLabels(){return z_;};\n  virtual uint32_t getK() const { return K_;};\n\n//  virtual MatrixXu mostLikelyInds(uint32_t n);\n  virtual MatrixXu mostLikelyInds(uint32_t n, Matrix<T,Dynamic,Dynamic>& logLikes);\n\n  Matrix<T,Dynamic,1> getCounts();\n\n  virtual void inferAll(uint32_t nIter, bool verbose=false);\n  virtual void dump(std::ofstream& fOutMeans, std::ofstream& fOutCovs); \n\nprotected: \n  uint32_t K_;\n  Dir<Cat<T>, T> dir_;\n  Cat<T> pi_;\n#ifdef CUDA\n  SamplerGpu<T>* sampler_;\n#else \n  Sampler<T>* sampler_;\n#endif\n  Matrix<T,Dynamic,Dynamic> pdfs_;\n//  Cat cat_;\n  vector<boost::shared_ptr<BaseMeasure<T> > > thetas_;\n\n  vector<Matrix<T,Dynamic,Dynamic> > x_;\n  VectorXu z_;\n};\n\n// --------------------------------------- impl -------------------------------\n\n\ntemplate<typename T>\nDirNaiveBayes<T>::DirNaiveBayes(const Dir<Cat<T>,T>& alpha, const boost::shared_ptr<BaseMeasure<T> >& theta) :\n  K_(alpha.K_), dir_(alpha), pi_(dir_.sample()) //cat_(dir_.sample()),\n{\n// init the parameters\n    cout<<\"[DirNaiveBayes::DirNaiveBayes] creating thetas (you only gave me one)\"<<endl;\n    for (uint32_t k=0; k<K_; ++k)\n      thetas_.push_back(boost::shared_ptr<BaseMeasure<T> >(theta->copy()));\n};\n\n\ntemplate<typename T>\nDirNaiveBayes<T>::DirNaiveBayes(const Dir<Cat<T>,T>& alpha, \n    const vector<boost::shared_ptr<BaseMeasure<T> > >& thetas) :\n  K_(alpha.K_), dir_(alpha), pi_(dir_.sample()), //cat_(dir_.sample()),\n  thetas_(thetas)\n{};\n\n\ntemplate<typename T>\nDirNaiveBayes<T>::~DirNaiveBayes()\n{\n  if (sampler_ != NULL) delete sampler_;\n};\n\ntemplate <typename T>\nMatrix<T,Dynamic,1> DirNaiveBayes<T>::getCounts()\n{\n  return counts<T,uint32_t>(z_,K_);\n};\n\n\ntemplate<typename T>\nvoid DirNaiveBayes<T>::initialize(const vector< Matrix<T,Dynamic,Dynamic> > &x)\n{\n  cout<<\"init\"<<endl;\n  x_ = x;\n  // randomly init labels from prior\n  z_.setZero(x.size());\n  cout<<\"sample pi\"<<endl;\n  pi_ = dir_.sample(); \n  cout<<\"init pi=\"<<pi_.pdf().transpose()<<endl;\n  pi_.sample(z_);\n\n  pdfs_.setZero(x.size(),K_);\n#ifdef CUDA\n  sampler_ = new SamplerGpu<T>(uint32_t(x.size()),K_,dir_.pRndGen_);\n#else \n  sampler_ = new Sampler<T>(dir_.pRndGen_);\n#endif\n\n#pragma omp parallel for\n  for(int32_t k=0; k<int32_t(K_); ++k)\n    thetas_[k]->posterior(x_,z_,k);\n};\n\ntemplate<typename T>\nvoid DirNaiveBayes<T>::sampleLabels()\n{\n  // obtain posterior categorical under labels\n  pi_ = dir_.posterior(z_).sample();\n//  cout<<pi_.pdf().transpose()<<endl;\n  \n#pragma omp parallel for\n  for(int32_t i=0; i<z_.size(); ++i)\n  {\n    //TODO: could buffer this better\n    // compute categorical distribution over label z_i\n    VectorXd logPdf_z = pi_.pdf().array().log();\n    for(uint32_t k=0; k<K_; ++k)\n    {\n//      cout<<thetas_[k].logLikelihood(x_.col(i))<<\" \";\n\t\tfor(uint32_t w=0; w<x_[i].cols(); ++w)\n\t\t{\n\t\t\tlogPdf_z[k] += thetas_[k]->logLikelihood(x_[i],w);\n\t\t}\n    }\n//    cout<<endl;\n    // make pdf sum to 1. and exponentiate\n    pdfs_.row(i) = (logPdf_z.array()-logSumExp(logPdf_z)).exp().matrix().transpose();\n//    cout<<pi_.pdf().transpose()<<endl;\n//    cout<<pdf.transpose()<<\" |.|=\"<<pdf.sum();\n//    cout<<\" z_i=\"<<z_[i]<<endl;\n  }\n  // sample z_i\n  sampler_->sampleDiscPdf(pdfs_,z_);\n};\n\n\ntemplate<typename T>\nvoid DirNaiveBayes<T>::sampleParameters()\n{\n#pragma omp parallel for \n  for(int32_t k=0; k<int32_t(K_); ++k)\n  {\n    thetas_[k]->posterior(x_,z_,k);\n//    cout<<\"k:\"<<k<<endl;\n//    thetas_[k]->print();\n  }\n};\n\n\ntemplate<typename T>\nT DirNaiveBayes<T>::logJoint(bool verbose)\n{\n  T logJoint = dir_.logPdf(pi_);\n  if(verbose)\n  \tcout<<\"log p(pi)=\"<<logJoint<<\" -> \";\n\n#pragma omp parallel for reduction(+:logJoint)  \n  for (int32_t k=0; k<int32_t(K_); ++k)\n    logJoint = logJoint + thetas_[k]->logPdfUnderPrior();\n\tif(verbose)\n\t\tcout<<\"log p(pi)*p(theta)=\"<<logJoint<<\" -> \";\n\n#pragma omp parallel for reduction(+:logJoint)  \n  for (int32_t i=0; i<z_.size(); ++i)\n\t  for(int32_t w=0; w<x_[i].cols(); ++w)\n\t\tlogJoint = logJoint + thetas_[z_[i]]->logLikelihood(x_[i],w);\n  if(verbose)\n  \tcout<<\"log p(phi)*p(theta)*p(x|z,theta)=\"<<logJoint<<\"]\"<<endl;\n  \n  return logJoint;\n};\n\n\ntemplate<typename T>\nMatrixXu DirNaiveBayes<T>::mostLikelyInds(uint32_t n, Matrix<T,Dynamic,Dynamic>& logLikes)\n{\n  MatrixXu inds = MatrixXu::Zero(n,K_);\n  logLikes = Matrix<T,Dynamic,Dynamic>::Ones(n,K_);\n  logLikes *= -99999.0;\n  \n#pragma omp parallel for \n  for (int32_t k=0; k<int32_t(K_); ++k)\n  {\n    for (uint32_t i=0; i<z_.size(); ++i)\n      if(z_(i) == k)\n      {\n        T logLike = thetas_[z_[i]]->logLikelihood(x_[i]);\n        for (uint32_t j=0; j<n; ++j)\n          if(logLikes(j,k) < logLike)\n          {\n            for(uint32_t l=n-1; l>j; --l)\n            {\n              logLikes(l,k) = logLikes(l-1,k);\n              inds(l,k) = inds(l-1,k);\n            }\n            logLikes(j,k) = logLike;\n            inds(j,k) = i;\n//            cout<<\"after update \"<<logLike<<endl;\n//            Matrix<T,Dynamic,Dynamic> out(n,K_*2);\n//            out<<logLikes.cast<T>(),inds.cast<T>();\n//            cout<<out<<endl;\n            break;\n          }\n      }\n  } \n  cout<<\"::mostLikelyInds: logLikes\"<<endl;\n  cout<<logLikes<<endl;\n  cout<<\"::mostLikelyInds: inds\"<<endl;\n  cout<<inds<<endl;\n  return inds;\n};\n\n\ntemplate<typename T>\nvoid DirNaiveBayes<T>::inferAll(uint32_t nIter, bool verbose)\n{ \n  if(verbose){\n  \tcout<<\"[DirNaiveBayes::inferALL] ------ inferingALL (nIter=\" << nIter << \") ------\"<<endl;\n  \tcout <<\"initial labels:\"<< endl;\n  \tcout<<this->labels().transpose()<<endl;\n  }\n  for(uint32_t t=0; t<nIter; ++t)\n  {\n    this->sampleLabels();\n    this->sampleParameters();\n    if(verbose){\n\t\tcout << \"[\" << std::setw(3)<< std::setfill('0')  << t <<\"] label: \" \n    \t<< this->labels().transpose()\n      \t<< \" [joint= \" << std::setw(6) << this->logJoint(false) << \"]\"<< endl;\n    }\n  }\n}\n\n\ntemplate <typename T>\nvoid DirNaiveBayes<T>::dump(std::ofstream& fOutMeans, std::ofstream& fOutCovs)\n{\n\tcout << \"dumping naiveBayes\" << endl; \n\tcout << \"doc index: \" << endl;  \n\tcout << this->labels().transpose() << endl; \n\n\tcout << \"printing cluster params: \" << endl; \n\tcout << K_ << endl;\n\tfor(uint32_t k=0; k<K_; ++k)\n\t{\n\t\tcout << \"theta: \" << k << endl;\n\t\tthetas_[k]->print();\n\t}\n\n\tcout << \"printing mixture params: \" << endl;\n\tpi_.print();\n\n\n}\n", "meta": {"hexsha": "3b87ee4fee86e8bc6dc79187adf10dec5d579f26", "size": 7497, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/dirNaiveBayes.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/dirNaiveBayes.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/dirNaiveBayes.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.585106383, "max_line_length": 120, "alphanum_fraction": 0.6217153528, "num_tokens": 2296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5413176138009952}}
{"text": "/*! \\file demo_2d_uncertainty.cpp\n    \\brief Demonstration of some 2D plot features.\n    \\details including showing values with uncertainty information as 'plus minus', confidence intervals and degrees of freedom estimates.\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A. Bristow 2007, 2008, 2009, 2021\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[demo_2d_uncertainty_1\n\n/*`First we need some includes to use Boost.SVG_Plot, and C++ Standard Library:\n*/\n\n#include <boost/svg_plot/svg_2d_plot.hpp>\n// using namespace boost::svg;\n\n//#include <boost/svg_plot/show_2d_settings.hpp> // Only needed for showing ALL the many settings used.\n//using boost::svg::show_2d_plot_settings;\n//void boost::svg::show_2d_plot_settings(svg_2d_plot&);\n\n#include <boost/svg_plot/detail/pair.hpp>\n// using boost::svg::detail::pair; operator<<\n\n#include <boost/quan/unc.hpp>\n//#include <boost/quan/unc_init.hpp>\n\n#include <boost/quan/meas.hpp>\n\n#include <algorithm>\n//  using std::copy;\n//#include <functional>\n\n#include <map>\n  //using std::map;\n  //using std::multimap;\n\n#include <utility>\n  //using std::pair;\n  //using std::make_pair;\n\n#include <vector>\n//  using std::vector;\n\n#include <cmath>\n//   using std::sqrt;\n\n#include <iostream>\n   //using std::cout;\n   //using std::endl;\n   //using std::scientific;\n   //using std::hex;\n   //using std::ios;\n   //using std::boolalpha;\n#include <iomanip>\n// Using std::setw;\n// using std::setprecision;\n\n#include <iterator>\n//   using std::ostream_iterator;\n\n//] [/demo_2d_uncertainty_1]\n\n  enum side\n  { //! \\enum side Where axis labels go.\n    left_side = -1,\n    on_axis = 0,\n    right_side = +1,\n    bottom_side = -1,\n    top_side = +1,\n  };\n\nint main()\n{\n  using std::pair;\n  using std::make_pair;\n  using std::vector;\n  using std::map;\n  using std::multimap;\n  using std::cout;\n  using std::endl;\n  using std::scientific;\n  using std::hex;\n  using std::ios;\n  using std::boolalpha;\n  using std::sqrt;\n\n  using namespace boost::svg;\n  using boost::svg::detail::operator<<;\n\n\n  try\n  {\n//[demo_2d_uncertainty_2\n\n/*`STL map is used as the container for our two data-series,\nand pairs of values and their uncertainty information\n(approximately standard deviation and degrees of freedom)\nare inserted using push_back. Since this is a 2-D plot\nthe order of data values is important.\n*/\n  typedef unc<false> uncun; // Uncertain Uncorrelated (the normal case).\n\n  using boost::svg::detail::operator<<;\n  using std::ostream_iterator;\n\n  setUncDefaults(std::cout);  // Initialize for uncertain types.\n\n  //setPlusminusSds(2); // cout.iword(plusminusSdsIndex);\n\n  // Create pair for fundamental type double that is implicitly exact with no uncertainty information.\n  pair<double, double> double_pair; // double X and Y pair.\n  double_pair = make_pair(double(-2.234), double(-8.76)); // Construct and then echo the data values thus:\n  std::cout << double_pair.first << \", \" << double_pair.second << std::endl; //  make_pair(double(-2.234), double(-8.76)) = -2.234, -8.76\n  // But it is more convenient to use a specialization of operator<< for `std::pair` to show both:\n  std::cout << \"make_pair(double(-2.234), double(-8.76)) = \" << double_pair << std::endl;\n  // make_pair(double(-2.234), double(-8.76)) = -2.234, -8.76\n\n  // Or, more informatively, use an uncertain type `uncun` that holds explicit uncertainty information\n  // (standard-deviation, degrees of freedom and so can compute confidence internals).\n\n  uncun ux(2.0, 0.5F, 7); // For an X-value.\n  //uncun ux(1.03, 0.56F, 7); // For an X-value.\n  // Using the  `uncun operator<<` provided we can output all the details of the uncertain value.\n  std::cout << scientific << plusminus << addlimits << adddegfree << std::setw(20)  << std::left\n    << \"ux = \" << ux << std::endl; // 1.2 +/-0.56 <0.82, 1.64> (7)\n\n  uncun uy(4.0, 0.5F, 9); // For a Y-value.\n//  uncun uy(3.45, 0.67F, 9); // For a Y-value.\n  std::cout << \"uy = \" << uy << std::endl; // 3.5 +/-0.67 <3.01, 3.89> (9)\n\n  // Now we make a pair of X and Y uncertain values:\n  pair<uncun, uncun > mp1 = make_pair(ux, uy); // X & Y pair of two uncertain values.\n  // Echo both X and Y-values and add all the uncertainty information, standard deviation and degrees of freedom :\n  std::cout << \"mp1 = \"<< mp1 << std::endl; // 1.2 +/-0.56 <0.82, 1.64> (7), 3.5 +/-0.67 <3.01, 3.89> (9)\n\n  std::map<uncun, uncun > data1; // Container for X & Y pairs of data-point values.\n  data1.insert(mp1); // Insert 1st pair of X & Y.\n  //data1.insert(make_pair(uncun(3.9, 0.01F, 8), uncun(1.1, 0.1F, 18))); // and add another X&Y-pair\n  data1.insert(make_pair(uncun(3.9, 0.01F, 8), uncun(1.1, 0.2F, 18))); // and add another X&Y-pair\n  data1.insert(make_pair(uncun(-2.234, 0.1F, 7), uncun(-5.76, 0.4F, 9))); // and a third pair.\n\n /*\n`Make very sure you don't forget either uncun(...) like this\n`data1.insert(make_pair((-2.234, 0.12F, 7),(-8.76, 0.56F, 9)));`\nbecause, by the bizarre operation of the comma operator, the result will be an integer!\nSo you will astonished to find that the values will be the *pair of degrees of freedom, (7, 9)*\nand the other parts of uncun will be undefined!\n\nEcho the values input, correctly rounded using the uncertainy and degrees of freedom:\n  */\n  std::cout << data1.size() << \" XY data pairs:\" << std::endl;\n  std::copy(data1.begin(), data1.end(), ostream_iterator<pair<uncun, uncun> >(std::cout, \"\\n\"));\n  std::cout << std::endl;\n\n  /*\n  3 XY data pairs:\n   -2.23 +/-0.030 <-2.26, -2.21> (7), -8.8 +/-0.90 <-9.35, -8.17> (9)\n   1.2 +/-0.56 <0.82, 1.64> (7), 3.5 +/-0.67 <3.01, 3.89> (9)\n   4.1 +/-0.40 <3.82, 4.38> (8), 3.1 +/-0.30 <2.96, 3.24> (18)\n  */\n\n  svg_2d_plot my_plot;  // Construct an empty plot.\n\n  /*`If you can be confident that the data set(s) only contains normal, valid data,\n  so none are 'at limits' - too big or too small to be meaningful, infinite or NaN (NotANumber),\n  then these checks can be skipped (for speed).\n  An instrument or operator input might be known to provide only normal data.\n  For this example, we know this is true, so override the default autoscale_check_limits(true).\n  */\n  my_plot.autoscale_check_limits(false);\n  /*`The default is autoscale_plusminus(3.) so that confidence ellipses\n  at 1, 2 and 3 (uncertainty nominally standard deviations)\n  are all within the plot window,\n  but if you are less interested in seeing the 2 and 3 ellipses,\n  you could risk the outer edges spilling over the borders\n  by reducing autoscale_plusminus, for example, to 1.5, down to zero.\n  */\n  //my_plot.autoscale_plusminus(1.5); // default is 3.\n  // my_plot.confidence(0.01);  // Change from default 0.05 to 0.01 for 99% confidence.\n\n  /*`Use data set `data` to autoscale. (You can use a different data set to scale from the one you chose to plot).\n  */\n  //my_plot.xy_autoscale(data1); // But may display data point value labels illegibly outside the plot frame or image.\n  // Specifying the X- and Y-axes explicitly is usually best.\n\n  //my_plot.confidence(0.01);  // Optionally use an alpha of 0.01 (99%) rather than default of 0.05 (95%) for culculation of confidence interval.\n\n  //my_plot.plusminus_sds(2.); // Optionally display uncertainty multiplied by a factor of two instead of default one.\n\n  my_plot\n    // X values settings:\n    .x_label(\"times (sec)\")\n    .x_range(-3, +10)\n    //.x_values_on(true) // Show X-values next to each point. Triggers a warning if also write .xy_values_on(true)\n    // SVG_plot warning : x_values_on has overwritten xy_values_on!\n\n     //! \\note Essential use of Unicode space &\\#x00A0; in all strings - ANSI space has no effect!\n  //.x_decor(\"t \", \", \", \"sec\") // Keep all on one line using X-separator does NOT start with a newline.\n   .x_decor(\"g \", \"\\n\", \"sec\") // Split X and Y onto two lines because X-separator *does* start with newline.\n  // .x_decor(\"after t \", \"\\ntravels\", \"sec\") // Split X and Y onto two lines because X-separator *does* start with newline,\n    // and add some descriptive text too.\n   // .x_values_rotation(backdown) // Not good.\n   // .x_values_rotation(downward) // \n   .x_values_rotation(uphill)\n   //.x_values_rotation(steepup) // \n   // .x_values_rotation(horizontal) // Lines up vertically, but shifted too high???\n   // .x_values_rotation(upward) // \n   // .x_values_rotation(rightward) // \n    .x_values_font_size(10) // Bigger than default.\n    .x_values_font_family(\"Times New Roman\") // Serif font just to show difference from sans-serif used for Y value-labels.\n    .x_major_grid_on(true)\n    .y_major_grid_on(true)\n    .x_major_interval(1)\n    .y_major_interval(1)\n\n    .x_plusminus_color(red) // Show plus/minus +/- uncertainty data-point value-label in red.\n    .x_plusminus_on(true) // Show plus/minus +/- uncertainty with data-point value-labels, for example \"2.1 +/- 0.001\"\n\n    // Y values settings:\n    .y_label(\"distance (km)\")\n    .y_range(-10., +10.) // But may be over-written by x and or  y-autoscale below.\n    //.y_values_on(true) // Show Y values next to each point.\n    // SVG_plot warning : xy_values_on has overwritten y_values_on!\n\n   // .y_values_rotation(downhill) // is ignored if both X and Y-values are shown on line below.\n    .y_values_font_family(\"Arial\") // Sans serif different from X-values font just to show effect.\n    .y_values_font_size(8) // Smaller than default.\n    .y_decor(\"y=\", \"\", \"&#x2009;km\")\n //   .y_decor(\"&#x00A0;&#x00A0;&#x00A0;&#x00A0;&#x00A0;&#x00A0;&#x00A0;&#x00A0;   d &#x00A0;\", \"&#x00A0;\", \"&#x00A0;km\")\n//    .y_decor(\"&#x00A0;&#x00A0; time = \", \"&#x00A0;\", \"&#x00A0;sec\")\n     // Note: a few padding spaces are used to get Y-value-labels to lie more nearly under X-value-labels.\n     // This is only necessary when value-labels are not horizontal.\n     // y_prefix \"&#x00A0;&#x00A0;&#x00A0;\"   3 spaces.\n     // y_separator \"&#x00A0;time =\"  space before word time.\n     // y_suffix \"&#x00A0;sec\" space before word sec.\n\n    .y_plusminus_on(true) // Show plus/minus +/- uncertainty with data-point value-labels, for example \"2.1 +/- 0.001\"\n    .y_plusminus_color(magenta) // Show plus/minus +/- uncertainty in magenta.\n\n    .y_addlimits_on(true)  // Show plus/minus +/- confidence limits for data-point value-labels.\n    .y_addlimits_color(darkgreen) // Show +/- in darkgreen, for example: \"+/- 0.03\".\n\n    .y_df_on(true) // Show degrees of freedom (usually observations -1) for data-points.\n    .y_df_color(green) // Show degrees of freedom in green, for examples: \"11\").\n\n    .xy_values_on(true) // Show both X-values and Y-values next to each point.\n     // IS needed if both .x_values_on(true) and .y_values_on(true) specified.\n     // .xy_autoscale(data1) // may result in value-labels running off the plot and image.\n   // .y_values_alignment(align_style::left_align)\n    //.x_values_alignment(align_style::right_align) // By default, set by code #L2881 switch statement depending on rotation.\n\n  /*`The default uncertainty ellipse colors (that apply to both X and Y axes)\n  can be changed thus:\n  */\n    .one_sd_color(lightblue) // Color of ellipse for one standard deviation (about 66% probability).\n    .two_sd_color(svg_color(200, 230, 255)) // Color of ellipse for two standard deviation (~95%).\n    .three_sd_color(svg_color(230, 240, 255)) // Color of ellipse for two standard deviation (~99%).\n   ; // my_plot\n\n//  my_plot.plot(data1, \"data1\").shape(unc_ellipse).fill_color(lightyellow).stroke_color(magenta);\n  my_plot.plot(data1, \"data1\").shape(unc_ellipse).fill_color(blue).stroke_color(magenta);\n  // TODO the uncertainty ellipses are now not showing anything useful for 2D but OK for 1D??? :-(\n\n  my_plot.write(\"./demo_2d_uncertainty\");\n\n  std::cout << \"confidence alpha \" << my_plot.confidence() <<\", plusminus sd multiplier = \" << my_plot.plusminus_sds() << std::endl;\n\n  // show_2d_plot_settings(my_plot); // Needs #include <boost/svg_plot/show_2d_settings.hpp>\n\n //] [/demo_2d_uncertainty_2]\n\n  }\n  catch (const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n/*\n\nOutput :\n\n   ------ Build started: Project: demo_2d_uncertainty, Configuration: Debug Win32 ------\n  unc.cpp\n  unc_print.cpp\n  unc_read.cpp\n  demo_2d_uncertainty.cpp\n  Generating Code...\n  demo_2d_uncertainty.vcxproj -> J:\\Cpp\\SVG\\Debug\\demo_2d_uncertainty.exe\n  make_pair(double(-2.234), double(-8.76)) = -2.234, -8.76\n   make_pair(double(-2.234), double(-8.76)) = -2.234, -8.76\n  ux = 1.2\n  1.2, 3.5\n  3 XY data pairs:\n  -2.23, -8.8\n  1.2, 3.5\n  4.10, 3.100\n\n  No limits checks: x_min = -2.234, x_max = 4.1, y_min = -8.76, y_max = 3.45\n\n\n  axes_on true\n  background_border_width 2\n  background_border_color RGB(255,255,0)\n  background_color RGB(255,255,255)\n  image_border_margin() 3\n  image_border_width() 2\n  coord_precision 3\n  copyright_date\n  copyright_holder\n  description\n  document_title \"\"\n  x_size 500\n  image y_size 400\n  image_filename\n  legend_on false\n  legend_place 2\n  legend_top_left -1, -1, legend_bottom_right -1, -1\n  legend_background_color blank\n  legend_border_color RGB(255,255,0)\n  legend_color blank\n  legend_title \"\"\n  legend_title_font_size 14\n  legend_font_weight\n  legend_width 0\n  legend_lines true\n  limit points stroke color RGB(119,136,153)\n  limit points fill color RGB(250,235,215)\n  license_on false\n  license_reproduction permits\n  license_distribution permits\n  license_attribution requires\n  license_commercialuse permits\n  plot_background_color RGB(255,255,255)\n  plot_border_color RGB(119,136,153)\n  plot_border_width 2\n  plot_window_on true\n  plot_window_x 92.6, 474\n  plot_window_x_left 92.6\n  plot_window_x_right 474\n  plot_window_y 8, 341\n  plot_window_y_top 8\n  plot_window_y_bottom 341\n  title_on false\n  title \"\"\n  title_color blank\n  title_font_alignment 2\n  title_font_decoration\n  title_font_family Verdana\n  title_font_rotation 0\n  title_font_size 18\n  title_font_stretch\n  title_font_style\n  title_font_weight\n  x_values_on false\n  x_values_font_size 16\n  x_values_font_family Times New Roman\n  x_values_precision 3\n  x_values_ioflags 200 IOS format flags (0x200) dec.\n  y_values_precision 3\n  y_values_font_size() 3\n  y_values_ioflags 200 IOS format flags (0x200) dec.\n  y_values_color blank\n  y_values_font_family() Arial\n  y_values_font_size() 12\n  x_max 5\n  x_min -3\n  x_autoscale true\n  y_autoscale true\n  xy_autoscale true\n  x_autoscale_check_limits false\n  x_axis_on true\n  x_axis_color() RGB(0,0,0)\n  x_axis_label_color blank\n  x_values_color blank\n  x_axis_width 1\n  x_label_on true\n  x_label \"times (sec)\"\n  x_label_color blank\n  x_label_font_family Verdana\n  x_label_font_size 14\n  x_label_units\n  x_label_units_on false\n  x_major_labels_side left\n  x_major_label_rotation 0\n  x_major_grid_color RGB(200,220,255)\n  x_major_grid_on false\n  x_major_grid_width 1\n  x_major_interval 1\n  x_major_tick 1\n  x_major_tick_color RGB(0,0,0)\n  x_major_tick_length 5\n  x_major_tick_width 2\n  x_minor_interval 0\n  x_minor_tick_color RGB(0,0,0)\n  x_minor_tick_length 2\n  x_minor_tick_width 1\n  x_minor_grid_on false\n  x_minor_grid_color RGB(200,220,255)\n  x_minor_grid_width 0.5\n  x_range() -3, 5\n  x_num_minor_ticks 4\n  x_ticks_down_on true\n  x_ticks_up_on false\n  x_ticks_on_window_or_axis bottom\n  y_axis_position y_axis_position intersects X axis (X range includes zero)\n  x_axis_position x_axis_position intersects Y axis (Y range includes zero)\n  x_plusminus_on true\n  x_plusminus_color RGB(0,255,255)\n  x_df_on true\n  x_df_color RGB(255,0,255)\n  x_prefix\n  x_separator\n  x_suffix\n  xy_values_on true\n  y_label_on \"true\"\n  y_label_axis distance (km)\n  y_axis_color RGB(0,0,0)\n  y_axis_label_color blank\n  y_axis_on true\n  axes_on true\n  y_axis_value_color RGB(0,0,0)\n  y_axis_width 1\n  y_label distance (km)\n  y_label_color blank\n  y_label_font_family Verdana\n  y_label_font_size 14\n  y_label_on true\n  y_label_units\n  y_label_units_on false\n  y_label_width 0\n  y_major_grid_on false\n  y_major_grid_color RGB(200,220,255)\n  y_major_grid_width 1\n  y_major_interval 2.5\n  y_major_labels_side bottom\n  y_major_label_rotation 0\n  y_major_tick_color RGB(0,0,0)\n  y_major_tick_length  5\n  y_major_tick_width  2\n  y_minor_grid_on false\n  y_minor_grid_color  RGB(200,220,255)\n  y_minor_grid_width 0.5\n  y_minor_interval 0\n  y_minor_tick_color RGB(0,0,0)\n  y_minor_tick_length 2\n  y_minor_tick_width 1\n  y_range() -10, 5\n  y_num_minor_ticks\n  y_ticks_left_on true\n  y_ticks_right_on false\n  y_ticks_on_window_or_axis left\n  y_max 5\n  y_min -10\n  y_values_on false\n  y_plusminus_on true\n  y_plusminus_color RGB(255,0,0)\n  y_df_on true\n  y_df_color RGB(0,128,0)\n  y_prefix \"&#x00A0;&#x00A0;&#x00A0;\"\n  y_separator \"time = \"\n  y_suffix \"&#x00A0;sec\"\n  data lines width 2\n========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========\n\n\n\n\n\n\n\n*/\n", "meta": {"hexsha": "0fcff4d341162db985aa6873db249407f5f6955c", "size": 17222, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_2d_uncertainty.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_2d_uncertainty.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_2d_uncertainty.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 35.4362139918, "max_line_length": 145, "alphanum_fraction": 0.7042736035, "num_tokens": 5254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.5413176091546852}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_ELLIPTIC_FUNCTIONS_SCALAR_ELLIK_HPP_INCLUDED\n#define NT2_ELLIPTIC_FUNCTIONS_SCALAR_ELLIK_HPP_INCLUDED\n#include <nt2/elliptic/functions/ellik.hpp>\n#include <boost/math/special_functions/ellint_1.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/pio_2.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/atan.hpp>\n#include <nt2/include/functions/scalar/average.hpp>\n#include <nt2/include/functions/scalar/ellint_1.hpp>\n#include <nt2/include/functions/scalar/is_eqz.hpp>\n#include <nt2/include/functions/scalar/is_ltz.hpp>\n#include <nt2/include/functions/scalar/log.hpp>\n#include <nt2/include/functions/scalar/oneminus.hpp>\n#include <nt2/include/functions/scalar/oneplus.hpp>\n#include <nt2/include/functions/scalar/sqrt.hpp>\n#include <nt2/include/functions/scalar/tan.hpp>\n#include <nt2/include/functions/scalar/toint.hpp>\n#include <nt2/sdk/error/policies.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( ellik_, tag::cpu_\n                            , (A0)\n                            , (scalar_< double_<A0> >)\n                              (scalar_< double_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL_REPEAT(2)\n    {\n      if (a1>nt2::One<A0>()||(nt2::is_ltz(a1))) return nt2::Nan<A0>();\n      if (nt2::is_eqz(a1))  return A0(a0);\n      return boost::math::ellint_1(nt2::sqrt(a1), a0, nt2_policy());\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( ellik_, tag::cpu_\n                            , (A0)\n                            , (scalar_< single_<A0> >)(scalar_< single_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL_REPEAT(2)\n    {\n      if (a1>nt2::One<A0>()||(nt2::is_ltz(a1))) return nt2::Nan<A0>();\n      if (nt2::is_eqz(a1))  return a0;\n      A0 phi = nt2::abs(a0);\n      A0 m = a1;\n      A0 a = nt2::One<A0>();\n      A0 b = nt2::oneminus(m);\n      if( nt2::is_eqz(b) )   return nt2::log(nt2::tan(nt2::average(Pio_2<A0>(),phi)));\n      b = nt2::sqrt(b);\n      A0 c = nt2::sqrt(m);\n      A0 d = nt2::One<A0>();\n      A0 t = nt2::tan(phi);\n      int mod = nt2::toint((phi+nt2::Pio_2<A0>())/nt2::Pi<A0>());\n      while( nt2::abs(c) > nt2::abs(a)*nt2::Eps<A0>() )\n      {\n        A0 temp = b/a;\n        phi += nt2::atan(t*temp) + mod*nt2::Pi<A0>();\n        mod = nt2::toint((phi+nt2::Pio_2<A0>())/nt2::Pi<A0>());\n        t = t*nt2::oneplus(temp)/( nt2::oneminus(temp*t*t));\n        c = nt2::average(a,-b);\n        temp = nt2::sqrt(a*b);\n        a = nt2::average(a,b);\n        b = temp;\n        d += d;\n      }\n      A0 temp = (nt2::atan(t) + mod * nt2::Pi<A0>())/(d * a);\n      if( nt2::is_ltz(a0) )  temp = -temp;\n      return temp;\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "70abd7da2a91eabf6935e5f29807a03fa39e5071", "size": 3370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/elliptic/include/nt2/elliptic/functions/scalar/ellik.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/elliptic/include/nt2/elliptic/functions/scalar/ellik.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/elliptic/include/nt2/elliptic/functions/scalar/ellik.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 37.8651685393, "max_line_length": 86, "alphanum_fraction": 0.5599406528, "num_tokens": 997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5412247578257886}}
{"text": "#include \"xpbd/neohookean_elasticity_constraint.h\"\n\n#include <Eigen/Dense>\n#include <eigen/SVD>\n\nnamespace xpbd {\n\nneohookean_elasticity_constraint_t::neohookean_elasticity_constraint_t(\n    std::initializer_list<index_type> indices,\n    positions_type const& p,\n    scalar_type young_modulus,\n    scalar_type poisson_ratio,\n    scalar_type const alpha)\n    : base_type(indices, alpha), V0_{0.}, DmInv_{}, mu_{}, lambda_{}\n{\n    assert(indices.size() == 4u);\n\n    auto const v1 = this->indices().at(0);\n    auto const v2 = this->indices().at(1);\n    auto const v3 = this->indices().at(2);\n    auto const v4 = this->indices().at(3);\n\n    auto const p1 = p.row(v1);\n    auto const p2 = p.row(v2);\n    auto const p3 = p.row(v3);\n    auto const p4 = p.row(v4);\n\n    Eigen::Matrix3d Dm;\n    Dm.col(0) = (p1 - p4).transpose();\n    Dm.col(1) = (p2 - p4).transpose();\n    Dm.col(2) = (p3 - p4).transpose();\n\n    V0_     = (1. / 6.) * Dm.determinant();\n    DmInv_  = Dm.inverse();\n    mu_     = (young_modulus) / (2. * (1 + poisson_ratio));\n    lambda_ = (young_modulus * poisson_ratio) / ((1 + poisson_ratio) * (1 - 2 * poisson_ratio));\n}\n\nvoid neohookean_elasticity_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 v1 = this->indices().at(0);\n    auto const v2 = this->indices().at(1);\n    auto const v3 = this->indices().at(2);\n    auto const v4 = this->indices().at(3);\n\n    auto const p1 = p.row(v1);\n    auto const p2 = p.row(v2);\n    auto const p3 = p.row(v3);\n    auto const p4 = p.row(v4);\n\n    auto const w1 = 1. / m(v1);\n    auto const w2 = 1. / m(v2);\n    auto const w3 = 1. / m(v3);\n    auto const w4 = 1. / m(v4);\n\n    auto const Vsigned        = signed_volume(p);\n    bool const is_V_positive  = Vsigned >= 0.;\n    bool const is_V0_positive = V0_ >= 0.;\n    bool const is_tet_inverted =\n        (is_V_positive && !is_V0_positive) || (!is_V_positive && is_V0_positive);\n\n    Eigen::Matrix3d Ds;\n    Ds.col(0) = (p1 - p4).transpose();\n    Ds.col(1) = (p2 - p4).transpose();\n    Ds.col(2) = (p3 - p4).transpose();\n\n    Eigen::Matrix3d const F = Ds * DmInv_;\n    Eigen::Matrix3d const I = Eigen::Matrix3d::Identity();\n\n    scalar_type constexpr epsilon = 1e-20;\n\n    Eigen::Matrix3d Piola;\n    scalar_type psi{};\n\n    // TODO: Implement correct inversion handling described in\n    // Irving, Geoffrey, Joseph Teran, and Ronald Fedkiw. \"Invertible finite elements for robust\n    // simulation of large deformation.\" Proceedings of the 2004 ACM SIGGRAPH/Eurographics symposium\n    // on Computer animation. 2004.\n    if (is_tet_inverted)\n    {\n        Eigen::JacobiSVD<Eigen::Matrix3d> UFhatV(F, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        Eigen::Vector3d const Fsigma = UFhatV.singularValues();\n        Eigen::Matrix3d Fhat;\n        Fhat.setZero();\n        Fhat(0, 0) = Fsigma(0);\n        Fhat(1, 1) = Fsigma(1);\n        Fhat(2, 2) = Fsigma(2);\n\n        Eigen::Matrix3d U       = UFhatV.matrixU();\n        Eigen::Matrix3d const V = UFhatV.matrixV();\n\n        auto smallest_element_idx = 0;\n        if (Fsigma(0) < Fsigma(1) && Fsigma(0) < Fsigma(2))\n            smallest_element_idx = 0;\n        if (Fsigma(1) < Fsigma(0) && Fsigma(1) < Fsigma(2))\n            smallest_element_idx = 1;\n        if (Fsigma(2) < Fsigma(0) && Fsigma(2) < Fsigma(1))\n            smallest_element_idx = 2;\n\n        Fhat(smallest_element_idx, smallest_element_idx) =\n            -Fhat(smallest_element_idx, smallest_element_idx);\n        U.col(smallest_element_idx) = -U.col(smallest_element_idx);\n\n        // stress reaches maximum at 58% compression\n        scalar_type constexpr min_singular_value = 0.577;\n        Fhat(0, 0)                               = std::min(Fhat(0, 0), min_singular_value);\n        Fhat(1, 1)                               = std::min(Fhat(1, 1), min_singular_value);\n        Fhat(2, 2)                               = std::min(Fhat(2, 2), min_singular_value);\n\n        Eigen::Matrix3d const Fprime = U * Fhat * V.transpose();\n        Eigen::Matrix3d const F2     = Fprime.transpose() * Fprime;\n        Eigen::Matrix3d const Finv   = Fprime.inverse();\n        Eigen::Matrix3d const FinvT  = Finv.transpose();\n        scalar_type const I1         = F2.trace();\n        scalar_type const J          = Fprime.determinant();\n\n        scalar_type const logJ = std::log(J);\n        // psi(I1, J) = (mu/2)*(I1 - 3) - mu*log(J) + (lambda/2)*log^2(J)\n        psi = static_cast<scalar_type>(0.5) * mu_ * (I1 - static_cast<scalar_type>(3.)) -\n              mu_ * logJ + static_cast<scalar_type>(0.5) * lambda_ * logJ * logJ;\n        // P(F) = mu*(F - mu*F^-T) + lambda*log(J)*F^-T\n        Piola = mu_ * (Fprime - mu_ * FinvT) + lambda_ * logJ * FinvT;\n    }\n    else\n    {\n        Eigen::Matrix3d const F2    = F.transpose() * F;\n        Eigen::Matrix3d const Finv  = F.inverse();\n        Eigen::Matrix3d const FinvT = Finv.transpose();\n        scalar_type const I1        = F2.trace();\n        scalar_type const J         = F.determinant();\n\n        scalar_type const logJ = std::log(J);\n        // psi(I1, J) = (mu/2)*(I1 - 3) - mu*log(J) + (lambda/2)*log^2(J)\n        psi = static_cast<scalar_type>(0.5) * mu_ * (I1 - static_cast<scalar_type>(3.)) -\n              mu_ * logJ + static_cast<scalar_type>(0.5) * lambda_ * logJ * logJ;\n        // P(F) = mu*(F - mu*F^-T) + lambda*log(J)*F^-T\n        Piola = mu_ * (F - mu_ * FinvT) + lambda_ * logJ * FinvT;\n    }\n\n    // H is the negative gradient of the elastic potential\n    scalar_type const V0     = std::abs(V0_);\n    Eigen::Matrix3d const H  = -V0 * Piola * DmInv_.transpose();\n    Eigen::Vector3d const f1 = H.col(0);\n    Eigen::Vector3d const f2 = H.col(1);\n    Eigen::Vector3d const f3 = H.col(2);\n    Eigen::Vector3d const f4 = -(f1 + f2 + f3);\n\n    // clang-format off\n     auto const weighted_sum_of_gradients =\n        w1 * f1.squaredNorm() +\n        w2 * f2.squaredNorm() +\n        w3 * f3.squaredNorm() +\n        w4 * f4.squaredNorm();\n    // clang-format on\n\n    if (weighted_sum_of_gradients < epsilon)\n        return;\n\n    scalar_type const C           = V0 * psi;\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    // because f = - grad(potential), then grad(potential) = -f and thus grad(C) = -f\n    p.row(v1) += w1 * -f1 * delta_lagrange;\n    p.row(v2) += w2 * -f2 * delta_lagrange;\n    p.row(v3) += w3 * -f3 * delta_lagrange;\n    p.row(v4) += w4 * -f4 * delta_lagrange;\n}\n\nneohookean_elasticity_constraint_t::scalar_type\nneohookean_elasticity_constraint_t::signed_volume(positions_type const& V) const\n{\n    Eigen::RowVector3d const p1 = V.row(indices()[0]);\n    Eigen::RowVector3d const p2 = V.row(indices()[1]);\n    Eigen::RowVector3d const p3 = V.row(indices()[2]);\n    Eigen::RowVector3d const p4 = V.row(indices()[3]);\n\n    Eigen::Matrix3d Ds;\n    Ds.col(0)      = (p1 - p4).transpose();\n    Ds.col(1)      = (p2 - p4).transpose();\n    Ds.col(2)      = (p3 - p4).transpose();\n    auto const vol = (1. / 6.) * Ds.determinant();\n    return vol;\n}\n\n} // namespace xpbd", "meta": {"hexsha": "1a2b50dc088eeca612d406316866d1530169ca59", "size": 7208, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/xpbd/neohookean_elasticity_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/neohookean_elasticity_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/neohookean_elasticity_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": 37.5416666667, "max_line_length": 100, "alphanum_fraction": 0.5910099889, "num_tokens": 2284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924954, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5412247544247625}}
{"text": "#include \"mesh_components.hpp\"\n#include \"plane3d.hpp\"\n#include <vector>\n#include <functional>\n#include <array>\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nTetrahedron::Tetrahedron(const int _id, const vector<reference_wrapper<Vertex3d>> _vertices, const double _weight, const int _label){\n    id = _id;\n    vertices = _vertices;\n    weight = _weight;\n    label = _label;\n    //cout << vertices[0].get().Vec() << endl;\n\n    Vector3d v0 = vertices[0].get().Vec();\n    Vector3d v1 = vertices[1].get().Vec();\n    Vector3d v2 = vertices[2].get().Vec();\n    Vector3d v3 = vertices[3].get().Vec();\n\n    //array<double, 3> faceCentroid = {(v0[0] + v1[0] + v2[0]) / 3, (v0[1] + v1[1] + v2[1]) / 3, (v0[2] + v1[2] + v2[2]) / 3};\n\n    //Vector3f pt3 = vertices[3]->Vec();\n\n    sphereCenter = { (v0[0] + v1[0] + v2[0] + v3[0])/4, (v0[1] + v1[1] + v2[1] + v3[1])/4, (v0[2] + v1[2] + v2[2] + v3[2])/4};\n\n    double r0 = sqrt( pow(sphereCenter[0]-v0[0], 2) + pow(sphereCenter[1]-v0[1], 2) + pow(sphereCenter[2]-v0[2], 2));\n\n    double r1 = sqrt( pow(sphereCenter[0]-v1[0], 2) + pow(sphereCenter[1]-v1[1], 2) + pow(sphereCenter[2]-v1[2], 2));\n\n    double r2 = sqrt( pow(sphereCenter[0]-v2[0], 2) + pow(sphereCenter[1]-v2[1], 2) + pow(sphereCenter[2]-v2[2], 2));\n\n    double r3 = sqrt( pow(sphereCenter[0]-v3[0], 2) + pow(sphereCenter[1]-v3[1], 2) + pow(sphereCenter[2]-v3[2], 2));\n\n    double radii [4] = {r0, r1, r2, r3};\n\n    double r = r0;\n\n    for(int i=1; i<4; ++i){\n\t//float tmp_r = ;\n\tif (radii[i] > r){\n\t    r = radii[i];\n\t}\n    }\n\n    sphereRadius = r;\n}\n\nvoid Tetrahedron::addNeighbor(unsigned long int neighborId){\n    neighbors.push_back(neighborId);\n}\n\nFace::Face(const vector<reference_wrapper<Vertex3d>> _vertices, unsigned long int _tetId){\n    vertices = _vertices;\n    tetId=_tetId;\n}\n\nbool Tetrahedron::contains(const array<double, 3> pt_target){\n    if (sqrt( pow(pt_target[0] - sphereCenter[0], 2) + pow(pt_target[1] - sphereCenter[1], 2) + pow(pt_target[2] - sphereCenter[2], 2)) < sphereRadius){\n        /*cout << pt_target[0] << endl;\n        cout << pt_target[1] << endl;\n        cout << pt_target[2] << endl;\n        cout << \"HERE\" << endl;*/\n\n\tVector3d pt0 = {vertices[0].get().Vec()};\n\tVector3d pt1 = {vertices[1].get().Vec()};\n\tVector3d pt2 = {vertices[2].get().Vec()};\n\tVector3d pt3 = {vertices[3].get().Vec()};\n\n\t/*cout << \"pt0\" << endl;\n\tcout << pt0 << endl;\n\tcout << \"pt1\" << endl;\n\tcout << pt1 << endl;\n\tcout << \"pt2\" << endl;\n\tcout << pt2 << endl;\n\tcout << \"pt3\" << endl;\n\tcout << pt3 << endl;*/\n\n\tMatrix4d m0;\n\tMatrix4d m1;\n\tMatrix4d m2;\n\tMatrix4d m3;\n\tMatrix4d m4;\n\n\tm0 << pt0[0], pt0[1], pt0[2], 1,\n\t      pt1[0], pt1[1], pt1[2], 1,\n\t      pt2[0], pt2[1], pt2[2], 1,\n\t      pt3[0], pt3[1], pt3[2], 1;\n\n\tdouble d0 = m0.determinant();\n\n\tm1 << pt_target[0], pt_target[1], pt_target[2], 1,\n\t      pt1[0], pt1[1], pt1[2], 1,\n\t      pt2[0], pt2[1], pt2[2], 1,\n\t      pt3[0], pt3[1], pt3[2], 1;\n\n\tdouble d1 = m1.determinant();\n\n\tm2 << pt0[0], pt0[1], pt0[2], 1,\n\t      pt_target[0], pt_target[1], pt_target[2], 1,\n\t      pt2[0], pt2[1], pt2[2], 1,\n\t      pt3[0], pt3[1], pt3[2], 1;\n\n\tdouble d2 = m2.determinant();\n\n\tm3 << pt0[0], pt0[1], pt0[2], 1,\n\t      pt1[0], pt1[1], pt1[2], 1,\n\t      pt_target[0], pt_target[1], pt_target[2], 1,\n\t      pt3[0], pt3[1], pt3[2], 1;\n\n\tdouble d3 = m3.determinant();\n\n\tm4 << pt0[0], pt0[1], pt0[2], 1,\n\t      pt1[0], pt1[1], pt1[2], 1,\n\t      pt2[0], pt2[1], pt2[2], 1,\n\t      pt_target[0], pt_target[1], pt_target[2], 1;\n\n\tdouble d4 = m4.determinant();\n\n\t/*cout << d0 << endl;\n\tcout << d1 << endl;\n\tcout << d2 << endl;\n\tcout << d3 << endl;\n\tcout << d4 << endl;*/\n\n\treturn (d0<0 && d1<0 && d2<0 && d3<0 && d4<0) || (d0>0 && d1>0 && d2>0 && d3>0 && d4>0);\n    }\n    return false;\n}\n\n\nvector<array<double, 3>> Tetrahedron::intersectsPlane(Plane3d plane){\n    vector<array<double, 3>> intersectionPoints;\n\n    for(int i=0; i<4; ++i){\n\tVector3d v0 = vertices[i].get().Vec();\n\tif(plane.containsPoint(v0)){\n\t    array<double, 3> v0Pt = {v0[0], v0[1], v0[2]};\n\t    intersectionPoints.push_back(v0Pt);\n\t} \n\telse {\n\t    for(int j=i+1; j<4; ++j){\n\t\tVector3d v1 = vertices[j].get().Vec();\n\t\tif(plane.intersectsEdge(v0, v1)){\n\t\t    intersectionPoints.push_back(plane.findIntersection(v0,v1));\n\t\t}\n\t    }\n\t}\n    }\n\n    if(intersectionPoints.size()==4){\n\tintersectionPoints = {intersectionPoints[0], intersectionPoints[1], intersectionPoints[3], intersectionPoints[2]};\n    }\n\n\n    return intersectionPoints;\n\n}\n\nbool Face::intersectsPlane(Plane3d plane){\n    Vector3d v0 = vertices[0].get().Vec();\n    Vector3d v1 = vertices[1].get().Vec();\n    Vector3d v2 = vertices[2].get().Vec();\n\n    return (plane.intersectsEdge(v0, v1) || plane.intersectsEdge(v1, v2) || plane.intersectsEdge(v0, v2));\n}\n\n\nunsigned long int Tetrahedron::Id(){\n    return id;\n}\n\nvector<unsigned long int> Tetrahedron::Neighbors(){\n    return neighbors;\n}\n\nvector<reference_wrapper<Vertex3d>> Tetrahedron::Vertices(){\n    return vertices;\n}\n\ndouble Tetrahedron::Weight(){\n    return weight;\n}\n\nint Tetrahedron::Label(){\n    return label;\n}\n\nunsigned long int Face::TetId(){\n    return tetId;\n}\n\nvector<reference_wrapper<Vertex3d>> Face::Vertices(){\n    return vertices;\n}\n\nVertex3d::Vertex3d(array<double, 3> _vec) {\n    //vec = _vec;\n    vec << _vec[0], _vec[1], _vec[2];\n}\n\n\nVector3d Vertex3d::Vec(){\n    return vec;\n}\n\n", "meta": {"hexsha": "19f8e0b222b4808739f0362404481430f10a6044", "size": 5374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mesh_components.cpp", "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.cpp", "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.cpp", "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": 25.5904761905, "max_line_length": 152, "alphanum_fraction": 0.5874581317, "num_tokens": 1994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5412247464639323}}
{"text": "//  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// Basic sanity check that header\n// #includes all the files that it needs to.\n#include <boost/math/differentiation/finite_difference.hpp>\n//\n// Note this header includes no other headers, this is\n// important if this test is to be meaningful:\n//\n#include \"test_compile_result.hpp\"\n\nvoid compile_and_link_test()\n{\n    check_result<float>(boost::math::differentiation::finite_difference_derivative([](float x){return x;}, f));\n    check_result<double>(boost::math::differentiation::finite_difference_derivative([](double x){return x;}, d));\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    check_result<long double>(boost::math::differentiation::finite_difference_derivative([](long double x){return x;}, static_cast<long double>(0)));\n    #endif\n\n    check_result<float>(boost::math::differentiation::complex_step_derivative([](std::complex<float> x){return x;}, f));\n    check_result<double>(boost::math::differentiation::complex_step_derivative([](std::complex<double> x){return x;}, d));\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    check_result<long double>(boost::math::differentiation::complex_step_derivative([](std::complex<long double> x){return x;}, \n                                                                                       static_cast<long double>(0)));\n    #endif\n}\n", "meta": {"hexsha": "acaaf76476b23306c2e92317ba1c3de3d416c05b", "size": 1539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/diff_finite_difference_incl_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/compile_test/diff_finite_difference_incl_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/compile_test/diff_finite_difference_incl_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": 51.3, "max_line_length": 149, "alphanum_fraction": 0.7076023392, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5412247464639323}}
{"text": "#include <iostream>\n\n#include <opencv2/features2d/features2d.hpp>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n#include <opencv2/core/core.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include \"BA.h\"\n#include \"Edge.h\"\n#include \"match.h\"\n#include \"pixel2cam.h\"\n#include \"pose_estimate_3d3d.h\"\n\nusing namespace std;\nusing namespace cv;\n\n\nint main(int argc, char**argv)\n{\n    if(argc !=5)\n    {\n        cout<<\"usage: pose_estimation_3d3d img1 img2 depth1 depth2! \"<<endl;\n        return  1;\n    }\n\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\n    BA AAA;\n    EdgeProjectXYZRGBD BBB;\n    match CCC;\n    pixel2cam DDD;\n    pose_estimate_3d3d FFF;\n\n\n    CCC.find_feature_matches(img_1,img_2,keypoints_1,keypoints_2,matches);\n    cout<<\"totally found: \"<<matches.size()<<\" pairs. \"<<endl;\n\n    //build 3D points\n    Mat depth1 = imread ( argv[3], CV_LOAD_IMAGE_UNCHANGED);\n    Mat depth2 = imread ( argv[4], CV_LOAD_IMAGE_UNCHANGED); //unsigned single channel\n\n    Mat K = ( Mat_<double> (3,3) << 520.9, 0, 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n    vector<Point3f> pts1, pts2;\n\n    for ( DMatch m:matches ) //DMatch:size matches=m\n    {\n        ushort d1 = depth1.ptr <unsigned short> ( int (keypoints_1[m.queryIdx].pt.y ) ) [int(keypoints_1[m.queryIdx].pt.x)];\n        ushort d2 = depth1.ptr <unsigned short> ( int (keypoints_2[m.trainIdx].pt.y ) ) [int(keypoints_2[m.queryIdx].pt.x)];\n        if (d1==0||d2==0)\n            continue;\n        Point2d p1 = DDD.trans ( keypoints_1[m.queryIdx].pt, K );\n        Point2d p2 = DDD.trans ( keypoints_2[m.trainIdx].pt, K );\n        float dd1 = float ( d1 ) /1000.0;\n        float dd2 = float ( d2 ) /1000.0;\n        pts1.push_back( Point3f ( p1.x*dd1, p1.y*dd1, dd1 ) );\n        pts2.push_back( Point3f ( p2.x*dd2, p2.y*dd2, dd2 ) );\n    }\n    cout<<\"3d-3d pairs: \"<<pts1.size()<<endl;\n\n    Mat R, t;\n    FFF.pose_estimation_3d3d(pts1, pts2, R, t );\n    cout<<\"ICP via 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()<<endl;\n\n    cout<<\"calling bundle adjustment\"<<endl;\n\n//    AAA.bundleadjustment(pts1, pts2, R, t,);\n}", "meta": {"hexsha": "21d63f390531a4c0a29c0ee7df063d54c843743d", "size": 2319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7_VO1/pose_estimation_3d3d/src/main.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": "ch7_VO1/pose_estimation_3d3d/src/main.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": "ch7_VO1/pose_estimation_3d3d/src/main.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": 30.1168831169, "max_line_length": 124, "alphanum_fraction": 0.6209573092, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5412247464639323}}
{"text": "#ifndef HEADER_CONTROL_POINT\n#define HEADER_CONTROL_POINT\n#include <armadillo>\n#include <memory>\n\n#include <set>\n\nclass Element;\nclass ControlPoint;\ntemplate <class PointType> class ShapeModel;\n\nclass ControlPoint {\n\npublic:\n\n\n\tControlPoint(ShapeModel<ControlPoint> * owning_shape = nullptr);\n\n\n\t/**\n\tGetter to the vertex's coordinates\n\t@return coordinates vertex coordinates\n\t*/\n\tconst arma::vec::fixed<3> & get_point_coordinates() const;\n\n\n\t/**\n\tSetter to the vertex's coordinates\n\t@param coordinates vertex coordinates\n\t*/\n\tvoid set_point_coordinates(arma::vec::fixed<3> coordinates);\n\n\n\t/**\n\tAdds $facet to the vector of std::shared_ptr<Element>  that own this vertex.\n\tNothing happens if the facet is already listed\n\t@param facet index to the element owning this vertex\n\t*/\n\tvoid add_ownership(int el_index);\n\n\n\tarma::vec::fixed<3> get_normal_coordinates(bool bezier) const;\n\n\n\tstd::set< int >  common_elements(int control_point_index) const;\n\n\t/**\n\tDetermines if $this is owned by $facet\n\t@param facet Facet whose relationship with the facet is to be tested\n\t@return true is $this is owned by $facet, false otherwise\n\t*/\n\tbool is_owned_by( int el_index) const;\n\n\n\n\t/**\n\tDelete $facet from the list of Element * owning $this\n\tNothing happens if the facet was not listed (maybe throw a warning)>\n\t@param facet Pointer to the facet owning this vertex\n\t*/\n\tvoid remove_ownership(int el_index);\n\n\t/**\n\tRemoves all ownership relationships \n\t*/\n\tvoid reset_ownership();\n\n\n\t/**\n\tReturns the owning elements\n\t@return Owning elements\n\t*/\n\tstd::set< int  > get_owning_elements() const;\n\n\t/**\n\tSets the owning elements\n\t@param Owning elements\n\t*/\n\tvoid set_owning_elements(std::set< int  > & owning_elements);\n\n\t/**\n\tReturns point covariance\n\t@return point covariance\n\t*/\n\tarma::mat get_covariance() const;\n\n\t/**\n\t@param element owning element\n\t@param local_indices triplet of indices numbering this control point within the owning element\n\t*/\n\tvoid add_local_numbering(int element,const arma::uvec & local_indices);\n\n\t/**\n\tReturns the local numbering of this control point within the specified element\n\t@param element pointer to element to consider\n\t*/\n\tarma::uvec get_local_numbering(int element) const;\n\n\t/**\n\tSets the control point covariance\n\t@param P covariance\n\t*/\n\tvoid set_covariance(arma::mat P);\n\n\tvoid set_deviation(arma::vec d) { this -> deviation = d;}\n\tarma::vec get_deviation() const { return this -> deviation; }\n\n\t/**\n\tReturns the number of facets owning this vertex\n\t@return N number of owning of facets\n\t*/\n\tunsigned int get_number_of_owning_elements() const ;\n\n\t/**\n\tGet global index (shape wise)\n\t@return global index\n\t*/\n\tint get_global_index() const;\n\n\n\t/**\n\tSet global index (shape wise)\n\t@param global index\n\t*/\n\tvoid set_global_index(int index);\n\nprotected:\n\tarma::vec::fixed<3> coordinates;\n\tarma::vec mean_coordinates;\n\n\tstd::set<int> owning_elements;\n\tstd::map<int,arma::uvec> local_numbering;\n\tarma::mat covariance = arma::zeros<arma::mat>(3,3);\n\tarma::vec deviation = arma::zeros<arma::vec>(3);\n\n\tint global_index;\n\tShapeModel<ControlPoint> * owning_shape;\n\n};\n\n\n#endif", "meta": {"hexsha": "84875dd62ca42e1c73383c29613db6d65d57f226", "size": 3095, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ShapeUQLib/ControlPoint.hpp", "max_stars_repo_name": "bbercovici/ShapeUQLib", "max_stars_repo_head_hexsha": "4906704270ab306f799c88336b4b35484e89eb1b", "max_stars_repo_licenses": ["MIT"], "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/ShapeUQLib/ControlPoint.hpp", "max_issues_repo_name": "bbercovici/ShapeUQLib", "max_issues_repo_head_hexsha": "4906704270ab306f799c88336b4b35484e89eb1b", "max_issues_repo_licenses": ["MIT"], "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/ShapeUQLib/ControlPoint.hpp", "max_forks_repo_name": "bbercovici/ShapeUQLib", "max_forks_repo_head_hexsha": "4906704270ab306f799c88336b4b35484e89eb1b", "max_forks_repo_licenses": ["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.7957746479, "max_line_length": 95, "alphanum_fraction": 0.7366720517, "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.5412247457165157}}
{"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_ARCH_X86_SSE1_SIMD_FUNCTION_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_SSE1_SIMD_FUNCTION_RSQRT_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/function/raw.hpp>\n#include <boost/simd/function/pedantic.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/if_nan_else.hpp>\n#include <boost/simd/function/if_zero_else.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/refine_rsqrt.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/detail/constant/denormalfactor.hpp>\n#include <boost/simd/detail/constant/denormalsqrtfactor.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd =  boost::dispatch;\n  namespace bs =  boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( rsqrt_\n                          , (typename A0)\n                          , bs::sse1_\n                          , bs::raw_tag\n                          , bs::pack_<bd::single_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (raw_tag const&\n                                    , const A0 & a0) const BOOST_NOEXCEPT\n    {\n      return _mm_rsqrt_ps(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( rsqrt_\n                          , (typename A0)\n                          , bs::sse1_\n                          , bs::pack_<bd::single_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const A0 & a00) const BOOST_NOEXCEPT\n    {\n//       A0 a0 = refine_rsqrt(a00, refine_rsqrt(a00, raw_(rsqrt)(a00)));\n      A0 a0 =  raw_(rsqrt)(a00);\n      A0 y = sqr(a0)*a00;\n      a0 = a0*Ratio<A0, 1, 8>()*fnms(y, fnms(A0(3), y, A0(10)), A0(15)); //this is Halley cubically convergent iteration\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      a0 = if_zero_else(a00 == Inf<A0>(),a0);\n      #endif\n      return if_else(is_eqz(a00), Inf<A0>(), a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( rsqrt_\n                          , (typename A0)\n                          , bs::sse1_\n                          , bs::pedantic_tag\n                          , bs::pack_<bd::single_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (pedantic_tag const&\n                                    ,const A0 & a00) const BOOST_NOEXCEPT\n    {\n      A0 a0 = a00;\n      auto is_den = bs::abs(a00) < Smallestposval<A0>();\n      #ifndef BOOST_SIMD_NO_DENORMALS\n      a0 *= if_else(is_den, Denormalfactor<A0>(), One<A0>());\n      #endif\n      a0 = refine_rsqrt(a0, refine_rsqrt(a0, raw_(rsqrt)(a0)));\n      #ifndef BOOST_SIMD_NO_DENORMALS\n      a0 *= if_else(is_den, Denormalsqrtfactor<A0>(), One<A0>());\n      #endif\n\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      a0 = if_zero_else(a00 == Inf<A0>(),a0);\n      #endif\n      return if_else(is_eqz(a00), Inf<A0>(), a0);\n    }\n  };\n\n} } }\n\n#endif\n\n", "meta": {"hexsha": "96177bdecee49f0ac1e75f963fa66ea69ed64c38", "size": 3314, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/x86/sse1/simd/function/rsqrt.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/arch/x86/sse1/simd/function/rsqrt.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/arch/x86/sse1/simd/function/rsqrt.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": 34.5208333333, "max_line_length": 120, "alphanum_fraction": 0.5497887749, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5412247404092957}}
{"text": "//\n// Copyright 2012 Chung-Lin Wen\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#ifndef BOOST_GIL_EXTENSION_TOOLBOX_COLOR_SPACES_LAB_HPP\n#define BOOST_GIL_EXTENSION_TOOLBOX_COLOR_SPACES_LAB_HPP\n\n#include <boost/gil/extension/toolbox/color_spaces/xyz.hpp>\n\n#include <boost/gil/color_convert.hpp>\n#include <boost/gil.hpp> // FIXME: Include what you use, not everything, even in extensions!\n\n#include <boost/mpl/vector.hpp>\n\nnamespace boost{ namespace gil {\n\n/// \\addtogroup ColorNameModel\n/// \\{\nnamespace lab_color_space\n{\n/// \\brief Luminance\nstruct luminance_t {};\n/// \\brief a Color Component\nstruct a_color_opponent_t {};\n/// \\brief b Color Component\nstruct b_color_opponent_t {};\n}\n/// \\}\n\n/// \\ingroup ColorSpaceModel\nusing lab_t = mpl::vector3\n    <\n        lab_color_space::luminance_t,\n        lab_color_space::a_color_opponent_t,\n        lab_color_space::b_color_opponent_t\n    >;\n\n/// \\ingroup LayoutModel\nusing lab_layout_t = layout<lab_t>;\n\nGIL_DEFINE_ALL_TYPEDEFS(32f, float32_t, lab)\n\n/// \\ingroup ColorConvert\n/// \\brief LAB to XYZ\ntemplate <>\nstruct default_color_converter_impl< lab_t, xyz_t >\n{\n    template <typename P1, typename P2>\n    void operator()( const P1& src, P2& dst ) const\n    {\n        using namespace lab_color_space;\n        using namespace xyz_color_space;\n\n        float32_t p = ((get_color(src, luminance_t()) + 16.f)/116.f);\n\n        get_color(dst, y_t()) =\n                1.f * powf(p, 3.f);\n\n        get_color(dst, x_t()) =\n                0.95047f * powf((p +\n                                 (get_color(src, a_color_opponent_t())/500.f)\n                                 ), 3.f);\n        get_color(dst, z_t()) =\n                1.08883f * powf((p -\n                                 (get_color(src, b_color_opponent_t())/200.f)\n                                 ), 3.f);\n    }\n};\n\n/// \\ingroup ColorConvert\n/// \\brief XYZ to LAB\n/// \\note I assume \\c xyz_t\ntemplate <>\nstruct default_color_converter_impl< xyz_t, lab_t >\n{\nprivate:\n    /// \\ref http://www.brucelindbloom.com/index.html?Eqn_XYZ_to_Lab.html\n    BOOST_FORCEINLINE\n    float32_t forward_companding(float32_t value) const\n    {\n        if (value > 216.f/24389.f)\n        {\n            return powf(value, 1.f/3.f);\n        }\n        else\n        {\n            return ((24389.f/27.f * value + 16.f)/116.f);\n        }\n    }\n\npublic:\n    template <typename P1, typename P2>\n    void operator()( const P1& src, P2& dst ) const\n    {\n        using namespace lab_color_space;\n\n        float32_t f_y =\n                forward_companding(\n                    channel_convert<float32_t>(\n                        get_color(src, xyz_color_space::y_t())\n                        )\n                    // / 1.f\n                    );\n\n        float32_t f_x =\n                forward_companding(\n                    channel_convert<float32_t>(\n                        get_color(src, xyz_color_space::x_t())\n                        )\n                    * (1.f / 0.95047f)  // if the compiler is smart, it should\n                                        // precalculate this, no?\n                    );\n\n        float32_t f_z =\n                forward_companding(\n                    channel_convert<float32_t>(\n                        get_color(src, xyz_color_space::z_t())\n                        )\n                    * (1.f / 1.08883f)  // if the compiler is smart, it should\n                                        // precalculate this, no?\n                    );\n\n        get_color(dst, luminance_t()) =\n                116.f * f_y - 16.f;\n\n        get_color(dst, a_color_opponent_t()) =\n                500.f * (f_x - f_y);\n\n        get_color(dst, b_color_opponent_t()) =\n                200.f * (f_y - f_z);\n    }\n};\n\n\n/// \\ingroup ColorConvert\n/// \\brief RGB to LAB\ntemplate <>\nstruct default_color_converter_impl< rgb_t, lab_t >\n{\n    template <typename P1, typename P2>\n    void operator()( const P1& src, P2& dst ) const\n    {\n        using namespace lab_color_space;\n\n        xyz32f_pixel_t xyz32f_temp_pixel;\n        default_color_converter_impl<rgb_t, xyz_t>()(src, xyz32f_temp_pixel);\n        default_color_converter_impl<xyz_t, lab_t>()(xyz32f_temp_pixel, dst);\n    }\n};\n\n/// \\ingroup ColorConvert\n/// \\brief LAB to RGB\ntemplate <>\nstruct default_color_converter_impl<lab_t,rgb_t>\n{\n    template <typename P1, typename P2>\n    void operator()( const P1& src, P2& dst) const\n    {\n        using namespace lab_color_space;\n\n        xyz32f_pixel_t xyz32f_temp_pixel;\n        default_color_converter_impl<lab_t, xyz_t>()(src, xyz32f_temp_pixel);\n        default_color_converter_impl<xyz_t, rgb_t>()(xyz32f_temp_pixel, dst);\n    }\n};\n\n} // namespace gil\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "106cfb22c70e7b8a154fdf143b4258a7a597e2ef", "size": 4794, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/gil/extension/toolbox/color_spaces/lab.hpp", "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/boost/gil/extension/toolbox/color_spaces/lab.hpp", "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/boost/gil/extension/toolbox/color_spaces/lab.hpp", "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": 27.5517241379, "max_line_length": 92, "alphanum_fraction": 0.5759282436, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5412247404092957}}
{"text": "/*!\n * Copyright (C) tkornuta, IBM Corporation 2015-2019\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 mnist_conv_hebbian.cpp\n * @brief Program for visualization of hebbian formed filters trained on MNIST digits.\n * @Author: Alexis Asseman <alexis.asseman@ibm.com>, Tomasz Kornuta <tkornut@us.ibm.com>\n * @Date:   June 8, 2017\n *\n * Copyright (c) 2017, Alexis Asseman, Tomasz Kornuta, IBM Corporation. All rights reserved.\n *\n */\n\n#include <boost/thread/thread.hpp>\n#include <boost/bind.hpp>\n\n#include <data_io/MNISTMatrixImporter.hpp>\n\n#include <logger/Log.hpp>\n#include <logger/ConsoleOutput.hpp>\nusing namespace mic::logger;\n\n#include <application/ApplicationState.hpp>\n\n#include <configuration/ParameterServer.hpp>\n\n#include <opengl/visualization/WindowManager.hpp>\n#include <opengl/visualization/WindowGrayscaleBatch.hpp>\n#include <opengl/visualization/WindowCollectorChart.hpp>\n\nusing namespace mic::opengl::visualization;\n\n// Hebbian neural net.\n#include <mlnn/HebbianNeuralNetwork.hpp>\nusing namespace mic::mlnn;\n\n// Encoders.\n#include <encoders/ColMatrixEncoder.hpp>\n#include <encoders/UIntMatrixEncoder.hpp>\n\n#include <mlnn/experimental/ConvHebbian.hpp>\nusing namespace mic::mlnn::experimental;\n\n/// Window for displaying the MNIST batch.\nWindowGrayscaleBatch<double>* w_input;\n/// Window for displaying the weights.\nWindowGrayscaleBatch<double>* w_weights1;\n\nWindowGrayscaleBatch<double>* w_output;\nWindowGrayscaleBatch<double>* w_reconstruction;\nWindowGrayscaleBatch<double>* w_similarity;\n\n/// Data collector.\nWindowCollectorChart<double>* w_chart;\nmic::data_io::DataCollectorPtr<std::string, double> collector_ptr;\n\n/// MNIST importer.\nmic::data_io::MNISTMatrixImporter<double>* importer;\n/// Multi-layer neural network.\nHebbianNeuralNetwork<double> neural_net;\n\n/// MNIST matrix encoder.\nmic::encoders::ColMatrixEncoder<double>* mnist_encoder;\n/// Label 2 matrix encoder (1 hot).\n//mic::encoders::UIntMatrixXfEncoder* label_encoder;\n\nconst size_t patch_size = 28;\nconst size_t batch_size = 1;\nconst size_t input_channels = 1;\nconst size_t filter_size[] = {5};\nconst size_t filters[] = {16};\nconst size_t stride[] = {1};\n\n\n/*!\n * \\brief Function for batch sampling.\n * \\author tkornuta\n */\nvoid batch_function (void) {\n\n/*\tif (neural_net.load(fileName)) {\n        LOG(LINFO) << \"Loaded neural network from a file\";\n    } else {*/\n        {\n        // Create a simple hebbian network.\n        neural_net.pushLayer(new ConvHebbian<double>(patch_size, patch_size, input_channels, filters[0], filter_size[0], stride[0]));\n\n        LOG(LINFO) << \"Generated new neural network\";\n    }//: else\n\n    std::shared_ptr<mic::mlnn::experimental::ConvHebbian<double> > layer1 =\n            neural_net.getLayer<mic::mlnn::experimental::ConvHebbian<double> >(0);\n\n    size_t iteration = 0;\n    // Set training parameters.\n    const double learning_rate = 5e-3;\n\n    // Main application loop.\n    while (!APP_STATE->Quit()) {\n\n        // If not paused.\n        if (!APP_STATE->isPaused()) {\n\n            // If single step mode - pause after the step.\n            if (APP_STATE->isSingleStepModeOn())\n                APP_STATE->pressPause();\n\n            { // Enter critical section - with the use of scoped lock from AppState!\n                APP_DATA_SYNCHRONIZATION_SCOPED_LOCK();\n\n                // Retrieve the next minibatch.\n                mic::types::MNISTBatch<double> bt = importer->getRandomBatch();\n\n                // Encode data.\n                mic::types::MatrixPtr<double> encoded_batch = mnist_encoder->encodeBatch(bt.data());\n\n                MNISTBatch<double> next_batch = importer->getNextBatch();\n                encoded_batch  = mnist_encoder->encodeBatch(next_batch.data());\n\n                neural_net.train(encoded_batch, learning_rate);\n\n                if (iteration % 10 == 0) {\n                    //Visualize the weights.\n                    // Set batch to be displayed.\n                    w_input->setBatchUnsynchronized(layer1->getInputActivations());\n                    w_weights1->setBatchUnsynchronized(layer1->getWeightActivations());\n                    w_similarity->setBatchUnsynchronized(layer1->getWeightSimilarity(true));\n                    w_output->setBatchUnsynchronized(layer1->getOutputActivations());\n                    w_reconstruction->setBatchUnsynchronized(layer1->getOutputReconstruction());\n                    collector_ptr->addDataToContainer(\"Reconstruction error\", layer1->getOutputReconstructionError());\n                    LOG(LINFO) << \"Iteration: \" << iteration;\n                }//: if\n\n                iteration++;\n            }//: end of critical section\n\n        }//: if\n\n        // Sleep.\n        APP_SLEEP();\n    }//: while\n\n}//: image_encoder_and_visualization_test\n\n\n\n/*!\n * \\brief Main program function. Runs two threads: main (for GLUT) and another one (for data processing).\n * \\author tkornuta\n * @param[in] argc Number of parameters (passed to glManaged).\n * @param[in] argv List of parameters (passed to glManaged).\n * @return (not used)\n */\nint main(int argc, char* argv[]) {\n    // Set console output to logger.\n    LOGGER->addOutput(new ConsoleOutput());\n    LOG(LINFO) << \"Logger initialized. Starting application\";\n\n    // Parse parameters.\n    PARAM_SERVER->parseApplicationParameters(argc, argv);\n\n    // Initilize application state (\"touch it\") ;)\n    APP_STATE;\n\n    // Load dataset.\n    importer = new mic::data_io::MNISTMatrixImporter<double>();\n    importer->setDataFilename(\"../data/mnist/train-images.idx3-ubyte\");\n    importer->setLabelsFilename(\"../data/mnist/train-labels.idx1-ubyte\");\n    importer->setBatchSize(batch_size);\n\n    // Initialize the encoders.\n    mnist_encoder = new mic::encoders::ColMatrixEncoder<double>(patch_size, patch_size);\n    //label_encoder = new mic::encoders::UIntMatrixXfEncoder(batch_size);\n\n    // Set parameters of all property-tree derived objects - USER independent part.\n    PARAM_SERVER->loadPropertiesFromConfiguration();\n\n    // Initialize property-dependent variables of all registered property-tree objects - USER dependent part.\n    PARAM_SERVER->initializePropertyDependentVariables();\n\n    // Import data from datasets.\n    if (!importer->importData())\n        return -1;\n\n    // Initialize GLUT! :]\n    VGL_MANAGER->initializeGLUT(argc, argv);\n\n    // Create batch visualization window.\n    w_input = new WindowGrayscaleBatch<double>(\"Input batch\", Grayscale::Norm_HotCold, Grayscale::Grid_Both, 70, 0, 250, 250);\n    w_weights1 = new WindowGrayscaleBatch<double>(\"Permanences\", Grayscale::Norm_HotCold, Grayscale::Grid_Both, 70+250, 0, 250, 250);\n    w_similarity = new WindowGrayscaleBatch<double>(\"Cosine similarity matrix\", Grayscale::Norm_HotCold, Grayscale::Grid_Both, 70+(2*250), 0, 250, 250);\n    w_output = new WindowGrayscaleBatch<double>(\"Output\", Grayscale::Norm_HotCold, Grayscale::Grid_Both, 70+(3*250), 0, 250, 250);\n    w_reconstruction = new WindowGrayscaleBatch<double>(\"Reconstruction\", Grayscale::Norm_HotCold, Grayscale::Grid_Both, 70+(4*250), 0, 250, 250);\n\n    // Chart.\n    w_chart = new WindowCollectorChart<double>(\"Statistics\", 60, 878, 512, 256);\n    collector_ptr= std::make_shared < mic::data_io::DataCollector<std::string, double> >( );\n    w_chart->setDataCollectorPtr(collector_ptr);\n\n    // Create data containers.\n    collector_ptr->createContainer(\"Reconstruction error\", mic::types::color_rgba(255, 255, 255, 180));\n\n    boost::thread batch_thread(boost::bind(&batch_function));\n\n    // Start visualization thread.\n    VGL_MANAGER->startVisualizationLoop();\n\n    LOG(LINFO) << \"Waiting for threads to join...\";\n    // End test thread.\n    batch_thread.join();\n    LOG(LINFO) << \"Threads joined - ending application\";\n}//: main\n", "meta": {"hexsha": "76f05cf4b28c465cb43d2be7320f4fa0c0e2d400", "size": 8238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/mnist_conv_hebbian.cpp", "max_stars_repo_name": "kant/mi-neural-nets", "max_stars_repo_head_hexsha": "82aa18fddc1fac9b72d8cd3ddcc61c02569f9e20", "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/mnist_conv_hebbian.cpp", "max_issues_repo_name": "kant/mi-neural-nets", "max_issues_repo_head_hexsha": "82aa18fddc1fac9b72d8cd3ddcc61c02569f9e20", "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/mnist_conv_hebbian.cpp", "max_forks_repo_name": "kant/mi-neural-nets", "max_forks_repo_head_hexsha": "82aa18fddc1fac9b72d8cd3ddcc61c02569f9e20", "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.6133333333, "max_line_length": 152, "alphanum_fraction": 0.6911871814, "num_tokens": 1948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070839, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5412247381293939}}
{"text": "#include \"../accumulate_over_others.hxx\"\n\n#include <boost/math/special_functions/expint.hpp>\n\n#include <vector>\n\nBoost_Float integral(const Boost_Float &prefactor, const Boost_Float &b,\n                     const Boost_Float &x, const int64_t &k);\n\nvoid precompute(\n  const Boost_Float &base, std::vector<Boost_Float> &sorted_poles,\n  std::vector<std::pair<std::vector<Boost_Float>::const_iterator,\n                        std::vector<Boost_Float>::const_iterator>>\n    &equal_ranges,\n  std::vector<int64_t> &lengths, std::vector<Boost_Float> &products,\n  std::vector<std::vector<Boost_Float>> &integral_matrix)\n{\n  sorted_poles.erase(\n    std::remove_if(sorted_poles.begin(), sorted_poles.end(),\n                   [](const Boost_Float &a) { return a >= 0; }),\n    sorted_poles.end());\n  std::sort(sorted_poles.begin(), sorted_poles.end());\n\n  for(auto pole(sorted_poles.begin()); pole != sorted_poles.end();)\n    {\n      const Boost_Float &p(*pole);\n      equal_ranges.push_back(\n        std::equal_range(pole, sorted_poles.end(), p,\n                         [&](const Boost_Float &p, const Boost_Float &q) {\n                           return (p < q) && !(abs(p - q) < 1e-2);\n                         }));\n      auto &equal_range(equal_ranges.back());\n      lengths.push_back(std::distance(equal_range.first, equal_range.second));\n      int64_t l(lengths.back());\n\n      products.push_back(\n        1\n        / accumulate_over_others(\n            sorted_poles, equal_range, Boost_Float(1),\n            [&](const Boost_Float &product, const Boost_Float &q) {\n              return product * (p - q);\n            }));\n\n      Boost_Float integral_sum(0);\n      Boost_Float integral_prefactor(-boost::math::expint(-p * log(base))\n                                     * pow(base, p));\n\n      integral_matrix.emplace_back();\n      auto &integrals(integral_matrix.back());\n      for(int64_t k = 0; k < l; ++k)\n        {\n          integrals.push_back(\n            integral(integral_prefactor, base, p, l - k - 1));\n        }\n\n      std::advance(pole, l);\n    }\n}\n", "meta": {"hexsha": "f8f6cf3bdcf8392c867a7160c9233badf217150f", "size": 2056, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/sdp2input/write_output/bilinear_basis/precompute/precompute.cxx", "max_stars_repo_name": "suning1985/sdpb", "max_stars_repo_head_hexsha": "9263b89496d1c356f11d08f995825626b60f5b89", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sdp2input/write_output/bilinear_basis/precompute/precompute.cxx", "max_issues_repo_name": "suning1985/sdpb", "max_issues_repo_head_hexsha": "9263b89496d1c356f11d08f995825626b60f5b89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sdp2input/write_output/bilinear_basis/precompute/precompute.cxx", "max_forks_repo_name": "suning1985/sdpb", "max_forks_repo_head_hexsha": "9263b89496d1c356f11d08f995825626b60f5b89", "max_forks_repo_licenses": ["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.8474576271, "max_line_length": 78, "alphanum_fraction": 0.5899805447, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5412247354757838}}
{"text": "//\n// Created by Xinyu Zhang on 3/26/21.\n//\n// gcc -I/Users/xinyuzhang/Desktop/Spring2021/c++pattern/project/cosan /Users/xinyuzhang/Desktop/Spring2021/c++pattern/project/cosan/test/model/RidgeRegressionTest.cpp\n#include <iostream>\n// #include <Eigen/Dense>\n// #include <cosan/io/utils.h>\n#include <cosan/data/CosanData.h>\n#include <cosan/model/CosanLinearRegression.h>\n#include <cosan/model/CosanRidgeRegression.h>\n//using namespace Eigen;\n//using namespace std;\ntypedef double db;\nint main() {\n   Cosan::CosanRawData<db> CD(\"./example_data/toy/X.csv\",\"./example_data/toy/y.csv\");\n   db RegularizationTerm = 1;\n   Cosan::CosanRidgeRegression<db> CRRwBias(RegularizationTerm,true);\n   CRRwBias.fit(CD.GetInput(),CD.GetTarget());\n   std::cout<<CRRwBias.GetBeta()<<std::endl;\n   std::cout<<(CRRwBias.predict(CD.GetInput())-CD.GetTarget()).norm()<<std::endl;   \n   return 0;\n}\n", "meta": {"hexsha": "d54e5e3b7076441ef7f77e072d4fe03e2c016e95", "size": 874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/model/RidgeRegressionTest.cpp", "max_stars_repo_name": "zhxinyu/cosan", "max_stars_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_stars_repo_licenses": ["MIT"], "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/model/RidgeRegressionTest.cpp", "max_issues_repo_name": "zhxinyu/cosan", "max_issues_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_issues_repo_licenses": ["MIT"], "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/model/RidgeRegressionTest.cpp", "max_forks_repo_name": "zhxinyu/cosan", "max_forks_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-13T05:56:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T05:56:38.000Z", "avg_line_length": 38.0, "max_line_length": 167, "alphanum_fraction": 0.7288329519, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.541171265724963}}
{"text": "#include <iostream>\n#include <fstream>\n#include <stdio.h>\n#include <math.h>\n#include <omp.h>\n#include <chrono>\n\n#include <random>\n#include <map>\n#include <string>\n#include <iomanip>\n\n#include <unistd.h>\n#include <string>\n#include <algorithm>\n#include <random>\n\n#include <Eigen/Core>\n\n#include <boost/program_options.hpp>\n#include <iterator>\n\n#include \"BayesC_distributions.h\"\n#include \"Sampling_functions.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\nnamespace po = boost::program_options;\n\nvoid ReadFromFile(std::vector<double> &x, const std::string &file_name)\n{\n\tstd::ifstream read_file(file_name);\n\tassert(read_file.is_open());\n\n\tstd::copy(std::istream_iterator<double>(read_file), std::istream_iterator<double>(),\n\t\t\tstd::back_inserter(x));\n\n\tread_file.close();\n}\n\n\nint main(int argc, char *argv[])\n{\n\n\tpo::options_description desc(\"Options\");\n\tdesc.add_options()\n\t\t(\"M\", po::value<int>()->required(), \"No. of simulated markers\")\n\t\t(\"N\", po::value<int>()->required(), \"No. of simulated individuals\")\n\t\t(\"iter\", po::value<int>()->default_value(5000), \"No. of Gibbs iterations\")\n\t\t(\"pNZ\", po::value<double>()->default_value(0.5), \"Proportion nonzero (simulations)\")\n\t\t(\"h2\", po::value<double>()->default_value(0.6), \"Heritability (simulations)\")\n\t\t(\"input\", po::value<std::string>()->default_value(\"none\"),\"Input filename\")\n\t\t(\"out\", po::value<std::string>()->default_value(\"BayesC_out\"),\"Output filename\")\n\t;\n\n\t//clock starts\n\tstd::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n\n\t//map variables\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc,argv,desc),vm);\n\tpo::notify(vm);\n\n\tint M=vm[\"M\"].as<int>();\n\tint N=vm[\"N\"].as<int>();\n\tint iter=vm[\"iter\"].as<int>();\n\n\tstring input=vm[\"input\"].as<string>();\n\tstring output=vm[\"out\"].as<string>();\n\n\tMatrixXd X(N,M);\n\tVectorXd Y(N);\n\n\t//beta coefficients\n\tVectorXd beta_true(M);\n\tbeta_true.setZero();\n\n\tint i,j,k,l,m=0;\n\n\t//Was an input matrix given?\n\n\tif (input!=\"none\"){ //Either read input tables for X and Y\n\t\tifstream f1(input+\".X\");\n\t\t//f1 >> m >> n;\n\t\tfor (int i = 0; i < N; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < M; j++)\n\t\t\t{\n\t\t\t\tf1 >> X(i,j);\n\t\t\t\t//cout<<X(i,j)<<endl;\n\t\t\t}\n\t\t}\n\t\tf1.close();\n\t\tcout<<\"finished reading matrix X!\"<<endl;\n\n\t\tstd::vector<double> Y_in;\n\t\tReadFromFile(Y_in, input+\".Y\");\n\t\tdouble* ptr_Y = &Y_in[0];\n\t\tEigen::Map<Eigen::VectorXd> Y1(ptr_Y, Y_in.size());\n\t\tcout<<\"finished reading vector Y!\"<<endl;\n\t\tif(Y_in.size()!=N){cout<<\"input Y vector size doesnt much the size indicated in the command line\"<<endl;return 0;}\n\t\tY=Y1;\n\t\tY_in.clear();\n\n\n\t}else //or simulate\n\t{\n\t\tdouble h2=vm[\"h2\"].as<double>();\n\t\tdouble pNZ=vm[\"pNZ\"].as<double>();\n\t\tdouble sigmaY_true=1;\n\n\t\tint MT=pNZ*M;\n\n\t\t//Fill Genotype matrix\n\t\tfor (i=0;i<N;i++){\n\t\t\tfor (j=0;j<M;j++){\n\t\t\t\tX(i,j)=rnorm(0,1);\n\t\t\t}\n\t\t}\n\t\tfor (i=0;i<MT;i++){\n\t\t\tbeta_true[i]=rnorm(0,sqrt(h2/MT));\n\t\t}\n\n\t\t//error\n\t\tVectorXd error(N);\n\t\tfor (i=0;i<N;i++){\n\t\t\terror[i]=rnorm(0,sqrt(1-h2));\n\t\t}\n\n\t\t//construct phenotypes\n\t\tY=X*beta_true;\n\t\tY+=error;\n\t}\n\t//standardize matrix X\n\tRowVectorXd mean = X.colwise().mean();\n\tRowVectorXd sd = ((X.rowwise() - mean).array().square().colwise().sum() / (X.rows() - 1)).sqrt();\n\tX = (X.rowwise() - mean).array().rowwise() / sd.array();\n\n\t//standardize vector Y\n    Y = (Y.array() - Y.array().mean());\n    Y /= sqrt(Y.squaredNorm() / (double(N - 1)));\n\n    //Initialize variables\n\tdouble Emu=0;\n\tVectorXd vEmu(N);\n\tvEmu.setOnes();\n\n\tVectorXd Ebeta(M);\n\tEbeta.setZero();\n\tVectorXd ny(M);\n\tny.setZero();\n\tdouble Ew=0.5;\n\t//residual error\n\tVectorXd epsilon(N);\n\n\tepsilon=Y-X*Ebeta-vEmu*Emu;\n\n\tstd::vector<int> markerI;\n\tfor (int i=0; i<M; ++i) {\n\t\tmarkerI.push_back(i);\n\t}\n\tint marker=0;\n\n\n\tint NZ=0;\n\n\tdouble Esigma2=epsilon.squaredNorm()/(N*0.5);\n\tdouble Epsi2=rbeta(1,1);\n\n\t//Standard parameterization of hyperpriors for variances\n\t//double v0E=0.001,s0E=0.001,v0B=0.001,s0B=0.001;\n\n\n\t// Alternative parameterization of hyperpriors for variances\n\tdouble v0E=4,v0B=4;\n\tdouble s0B=((v0B-2)/v0B)*Epsi2;\n\tdouble s0E=((v0E-2)/v0E)*Esigma2;\n\n\n\t//pre-computed elements for calculations\n\tVectorXd el1(M);\n\tfor (int i=0; i<M; ++i) {\n\t\tel1[i]=X.col(i).transpose()*X.col(i);\n\t}\n\n\t//open files for writing\n\tstd::ofstream ofs;\n\tofs.open(output+\"_estimates.txt\");\n\tfor (int i=0; i<M; ++i) {\n\t\tofs << \"beta_\" <<i<< ' ';\n\t}\n\tfor (int i=0; i<M; ++i) {\n\t\tofs << \"incl_\" <<i<< ' ';\n\t}\n\tofs << \"Ew\" << \" \";\n\tofs << \"Epsi2\" << \" \";\n\tofs << \"Esigma2\" << \" \";\n\tofs << \"\\n\";\n\tofs.close();\n\n\tstd::chrono::steady_clock::time_point end1= std::chrono::steady_clock::now();\n\tstd::cout << \"Time taken for Reading/generating data = \" << std::chrono::duration_cast<std::chrono::nanoseconds> (end1 - begin).count()*1e-9 <<\" seconds\"<<std::endl;\n\n\t//begin GIBBS sampling iterations\n\n\tofs.open (output+\"_estimates.txt\", std::ios_base::app);\n\tfor (i=0;i<iter;i++){\n\n\t\tEmu=sample_mu(N,Esigma2,Y,X,Ebeta);\n\n\t\t//sample effects and probabilities jointly\n\t\tstd::random_shuffle(markerI.begin(), markerI.end());\n\n\t\tfor (j=0;j<M;j++){\n\t\t\tmarker=markerI[j];\n\n\t\t\tepsilon=epsilon+X.col(marker)*Ebeta[marker];\n\n\t\t\tdouble Cj=el1[marker]+Esigma2/Epsi2;\n\t\t\tdouble rj=X.col(marker).transpose()*epsilon;\n\n\t\t\tdouble ratio=(((exp(-(pow(rj,2))/(2*Cj*Esigma2))*sqrt((Epsi2*Cj)/Esigma2))));\n\t\t\tratio=Ew/(Ew+ratio*(1-Ew));\n\t\t\tny[marker]=rbernoulli(ratio);\n\n\t\t\tif (ny[marker]==0){\n\t\t\t\tEbeta[marker]=0;\n\t\t\t}\n\t\t\telse if (ny[marker]==1){\n\t\t\t\tEbeta[marker]=rnorm(rj/Cj,Esigma2/Cj);\n\t\t\t}\n\n\t\t\tepsilon=epsilon-X.col(marker)*Ebeta[marker];\n\n\t\t}\n\t\tfor (j=0;j<M;j++){\n\t\t\tofs << Ebeta[j] << \" \";\n\t\t}\n\t\tfor (j=0;j<M;j++){\n\t\t\tofs << ny[j] << \" \";\n\t\t}\n\t\tNZ=ny.sum();\n\t\t//cout<<NZ<<endl;\n\n\t\tEw=sample_w(M,NZ);\n\t\tepsilon=Y-X*Ebeta-vEmu*Emu;\n\n\t\tEpsi2=sample_psi2_chisq(Ebeta,NZ,v0B,s0B);\n\t\tEsigma2=sample_sigma_chisq(N,epsilon,v0E,s0E);\n\n\t\tofs << Ew << \" \";\n\t\tofs << Epsi2 << \" \";\n\t\tofs << Esigma2 << \" \";\n\t\tofs << \"\\n\";\n\n\t}\n\tofs.close();\n//write out simulated data\nif (input==\"none\"){\n\t//write to files\n\tofstream myfile1;\n\tmyfile1.open (output+\"_simulated_Y.txt\");\n\tfor (i=0;i<N;i++){\n\t\tmyfile1 << Y[i] << ' ';\n\t}\n\tmyfile1 << endl;\n\tmyfile1.close();\n/*\n\tofstream myfile2;\n\tmyfile2.open (output+\"_simulated_X.txt\");\n\tfor (i=0;i<N;i++){\n\t\tfor (j=0;j<M;j++){\n\t\t\tmyfile2<<X(i,j)<< ' ';\n\t\t}\n\t\tmyfile2<<endl;\n\t}\n\tmyfile2.close();\n*/\n\tofstream myfile3;\n\tmyfile3.open (output+\"_simulated_betatrue.txt\");\n\tmyfile3 << beta_true << ' ';\n\tmyfile3.close();\n}\n\n\nstd::chrono::steady_clock::time_point end2= std::chrono::steady_clock::now();\nstd::cout << \"Time taken for full analysis = \" << std::chrono::duration_cast<std::chrono::nanoseconds> (end2 - begin).count()*1e-9 <<\" seconds\"<<std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "820e256d2663970e196d8b762f282239d07e3615", "size": 6619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BayesC.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.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.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": 22.7457044674, "max_line_length": 166, "alphanum_fraction": 0.6253210455, "num_tokens": 2185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5411712489354631}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2017 - 2022 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n// Config files\n#include <SAMRAI_config.h>\n\n// Headers for basic PETSc functions\n#include <petscsys.h>\n\n// Headers for basic SAMRAI objects\n#include <BergerRigoutsos.h>\n#include <CartesianGridGeometry.h>\n#include <LoadBalancer.h>\n#include <StandardTagAndInitialize.h>\n\n// Headers for basic libMesh objects\n#include <libmesh/boundary_info.h>\n#include <libmesh/equation_systems.h>\n#include <libmesh/exodusII_io.h>\n#include <libmesh/mesh_generation.h>\n#include <libmesh/mesh_triangle_interface.h>\n#include <libmesh/replicated_mesh.h>\n\n// Headers for application-specific algorithm/data structure objects\n#include <ibamr/IBExplicitHierarchyIntegrator.h>\n#include <ibamr/IBFECentroidPostProcessor.h>\n#include <ibamr/IBFEMethod.h>\n#include <ibamr/INSCollocatedHierarchyIntegrator.h>\n#include <ibamr/INSStaggeredHierarchyIntegrator.h>\n\n#include <ibtk/AppInitializer.h>\n#include <ibtk/BoxPartitioner.h>\n#include <ibtk/IBTKInit.h>\n#include <ibtk/IBTK_MPI.h>\n#include <ibtk/libmesh_utilities.h>\n#include <ibtk/muParserCartGridFunction.h>\n#include <ibtk/muParserRobinBcCoefs.h>\n\n#include <boost/multi_array.hpp>\n\n// Set up application namespace declarations\n#include <ibamr/app_namespaces.h>\n\n// Elasticity model data.\nnamespace ModelData\n{\n// Coordinate mapping function.\nvoid\ncoordinate_mapping_function(libMesh::Point& X, const libMesh::Point& s, void* /*ctx*/)\n{\n    X(0) = s(0) + 0.6;\n    X(1) = s(1) + 0.5;\n#if (NDIM == 3)\n    X(2) = s(2) + 0.5;\n#endif\n    return;\n} // coordinate_mapping_function\n\n// Stress tensor functions.\nstatic double c1_s = 0.05;\nstatic double p0_s = 0.0;\nstatic double beta_s = 0.0;\nvoid\nPK1_dev_stress_function(TensorValue<double>& PP,\n                        const TensorValue<double>& FF,\n                        const libMesh::Point& /*X*/,\n                        const libMesh::Point& /*s*/,\n                        Elem* const /*elem*/,\n                        const vector<const vector<double>*>& /*var_data*/,\n                        const vector<const vector<VectorValue<double> >*>& /*grad_var_data*/,\n                        double /*time*/,\n                        void* /*ctx*/)\n{\n    PP = 2.0 * c1_s * FF;\n    return;\n} // PK1_dev_stress_function\n\nvoid\nPK1_dil_stress_function(TensorValue<double>& PP,\n                        const TensorValue<double>& FF,\n                        const libMesh::Point& /*X*/,\n                        const libMesh::Point& /*s*/,\n                        Elem* const /*elem*/,\n                        const vector<const vector<double>*>& /*var_data*/,\n                        const vector<const vector<VectorValue<double> >*>& /*grad_var_data*/,\n                        double /*time*/,\n                        void* /*ctx*/)\n{\n    PP = 2.0 * (-p0_s + beta_s * log(FF.det())) * tensor_inverse_transpose(FF, NDIM);\n    return;\n} // PK1_dil_stress_function\n} // namespace ModelData\nusing namespace ModelData;\n\n// Function prototypes\nvoid output_data(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                 Pointer<INSHierarchyIntegrator> navier_stokes_integrator,\n                 MeshBase& mesh,\n                 EquationSystems* equation_systems,\n                 const int iteration_num,\n                 const double loop_time,\n                 const string& data_dump_dirname);\n\n/*******************************************************************************\n * For each run, the input filename and restart information (if needed) must   *\n * be given on the command line.  For non-restarted case, command line is:     *\n *                                                                             *\n *    executable <input file name>                                             *\n *                                                                             *\n * For restarted run, command line is:                                         *\n *                                                                             *\n *    executable <input file name> <restart directory> <restart number>        *\n *                                                                             *\n *******************************************************************************/\n\nint\nmain(int argc, char* argv[])\n{\n    // Initialize IBAMR and libraries. Deinitialization is handled by this object as well.\n    IBTKInit ibtk_init(argc, argv, MPI_COMM_WORLD);\n    const LibMeshInit& init = ibtk_init.getLibMeshInit();\n\n    { // cleanup dynamically allocated objects prior to shutdown\n\n        // Parse command line options, set some standard options from the input\n        // file, initialize the restart database (if this is a restarted run),\n        // and enable file logging.\n        Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, \"IB.log\");\n        Pointer<Database> input_db = app_initializer->getInputDatabase();\n\n        // Get various standard options set in the input file.\n        const bool dump_viz_data = app_initializer->dumpVizData();\n        const int viz_dump_interval = app_initializer->getVizDumpInterval();\n        const bool uses_visit = dump_viz_data && app_initializer->getVisItDataWriter();\n#ifdef LIBMESH_HAVE_EXODUS_API\n        const bool uses_exodus = dump_viz_data && !app_initializer->getExodusIIFilename().empty();\n#else\n        const bool uses_exodus = false;\n        if (!app_initializer->getExodusIIFilename().empty())\n        {\n            plog << \"WARNING: libMesh was compiled without Exodus support, so no \"\n                 << \"Exodus output will be written in this program.\\n\";\n        }\n#endif\n        const string exodus_filename = app_initializer->getExodusIIFilename();\n\n        const bool dump_restart_data = app_initializer->dumpRestartData();\n        const int restart_dump_interval = app_initializer->getRestartDumpInterval();\n        const string restart_dump_dirname = app_initializer->getRestartDumpDirectory();\n        const string restart_read_dirname = app_initializer->getRestartReadDirectory();\n        const int restart_restore_num = app_initializer->getRestartRestoreNumber();\n\n        const bool dump_postproc_data = app_initializer->dumpPostProcessingData();\n        const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval();\n        const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory();\n        if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty())\n        {\n            Utilities::recursiveMkdir(postproc_data_dump_dirname);\n        }\n\n        const bool dump_timer_data = app_initializer->dumpTimerData();\n        const int timer_dump_interval = app_initializer->getTimerDumpInterval();\n\n        // Create a simple FE mesh.\n        ReplicatedMesh mesh(init.comm(), NDIM);\n        const double dx = input_db->getDouble(\"DX\");\n        const double ds = input_db->getDouble(\"MFAC\") * dx;\n        string elem_type = input_db->getString(\"ELEM_TYPE\");\n        const double R = 0.2;\n        if (NDIM == 2 && (elem_type == \"TRI3\" || elem_type == \"TRI6\"))\n        {\n#ifdef LIBMESH_HAVE_TRIANGLE\n            const int num_circum_nodes = ceil(2.0 * M_PI * R / ds);\n            for (int k = 0; k < num_circum_nodes; ++k)\n            {\n                const double theta = 2.0 * M_PI * static_cast<double>(k) / static_cast<double>(num_circum_nodes);\n                mesh.add_point(libMesh::Point(R * cos(theta), R * sin(theta)));\n            }\n            TriangleInterface triangle(mesh);\n            triangle.triangulation_type() = TriangleInterface::GENERATE_CONVEX_HULL;\n            triangle.elem_type() = Utility::string_to_enum<ElemType>(elem_type);\n            triangle.desired_area() = 1.5 * sqrt(3.0) / 4.0 * ds * ds;\n            triangle.insert_extra_points() = true;\n            triangle.smooth_after_generating() = true;\n            triangle.triangulate();\n#else\n            TBOX_ERROR(\"ERROR: libMesh appears to have been configured without support for Triangle,\\n\"\n                       << \"       but Triangle is required for TRI3 or TRI6 elements.\\n\");\n#endif\n        }\n        else\n        {\n            // NOTE: number of segments along boundary is 4*2^r.\n            const double num_circum_segments = 2.0 * M_PI * R / ds;\n            const int r = log2(0.25 * num_circum_segments);\n            MeshTools::Generation::build_sphere(mesh, R, r, Utility::string_to_enum<ElemType>(elem_type));\n        }\n\n        // Ensure nodes on the surface are on the analytic boundary.\n        MeshBase::element_iterator el_end = mesh.elements_end();\n        for (MeshBase::element_iterator el = mesh.elements_begin(); el != el_end; ++el)\n        {\n            Elem* const elem = *el;\n            for (unsigned int side = 0; side < elem->n_sides(); ++side)\n            {\n                const bool at_mesh_bdry = !elem->neighbor_ptr(side);\n                if (!at_mesh_bdry) continue;\n                for (unsigned int k = 0; k < elem->n_nodes(); ++k)\n                {\n                    if (!elem->is_node_on_side(k, side)) continue;\n                    Node& n = elem->node_ref(k);\n                    n = R * n.unit();\n                }\n            }\n        }\n        mesh.prepare_for_use();\n\n        c1_s = input_db->getDouble(\"C1_S\");\n        p0_s = input_db->getDouble(\"P0_S\");\n        beta_s = input_db->getDouble(\"BETA_S\");\n\n        // Create major algorithm and data objects that comprise the\n        // application.  These objects are configured from the input database\n        // and, if this is a restarted run, from the restart database.\n        Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>(\n            \"CartesianGeometry\", app_initializer->getComponentDatabase(\"CartesianGeometry\"));\n        Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>(\"PatchHierarchy\", grid_geometry);\n        Pointer<LoadBalancer<NDIM> > load_balancer =\n            new LoadBalancer<NDIM>(\"LoadBalancer\", app_initializer->getComponentDatabase(\"LoadBalancer\"));\n        Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>();\n\n        Pointer<INSHierarchyIntegrator> navier_stokes_integrator;\n        const string solver_type = app_initializer->getComponentDatabase(\"Main\")->getString(\"solver_type\");\n        if (solver_type == \"STAGGERED\")\n        {\n            navier_stokes_integrator = new INSStaggeredHierarchyIntegrator(\n                \"INSStaggeredHierarchyIntegrator\",\n                app_initializer->getComponentDatabase(\"INSStaggeredHierarchyIntegrator\"));\n        }\n        else if (solver_type == \"COLLOCATED\")\n        {\n            navier_stokes_integrator = new INSCollocatedHierarchyIntegrator(\n                \"INSCollocatedHierarchyIntegrator\",\n                app_initializer->getComponentDatabase(\"INSCollocatedHierarchyIntegrator\"));\n        }\n        else\n        {\n            TBOX_ERROR(\"Unsupported solver type: \" << solver_type << \"\\n\"\n                                                   << \"Valid options are: COLLOCATED, STAGGERED\");\n        }\n        Pointer<IBFEMethod> ib_method_ops =\n            new IBFEMethod(\"IBFEMethod\",\n                           app_initializer->getComponentDatabase(\"IBFEMethod\"),\n                           &mesh,\n                           app_initializer->getComponentDatabase(\"GriddingAlgorithm\")->getInteger(\"max_levels\"),\n                           /*register_for_restart*/ true,\n                           restart_read_dirname,\n                           restart_restore_num);\n        Pointer<IBHierarchyIntegrator> time_integrator =\n            new IBExplicitHierarchyIntegrator(\"IBHierarchyIntegrator\",\n                                              app_initializer->getComponentDatabase(\"IBHierarchyIntegrator\"),\n                                              ib_method_ops,\n                                              navier_stokes_integrator);\n        time_integrator->registerLoadBalancer(load_balancer);\n\n        Pointer<StandardTagAndInitialize<NDIM> > error_detector =\n            new StandardTagAndInitialize<NDIM>(\"StandardTagAndInitialize\",\n                                               time_integrator,\n                                               app_initializer->getComponentDatabase(\"StandardTagAndInitialize\"));\n        Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm =\n            new GriddingAlgorithm<NDIM>(\"GriddingAlgorithm\",\n                                        app_initializer->getComponentDatabase(\"GriddingAlgorithm\"),\n                                        error_detector,\n                                        box_generator,\n                                        load_balancer);\n\n        // Configure the IBFE solver.\n        ib_method_ops->registerInitialCoordinateMappingFunction(coordinate_mapping_function);\n        IBFEMethod::PK1StressFcnData PK1_dev_stress_data(PK1_dev_stress_function);\n        IBFEMethod::PK1StressFcnData PK1_dil_stress_data(PK1_dil_stress_function);\n        PK1_dev_stress_data.quad_order =\n            Utility::string_to_enum<libMesh::Order>(input_db->getStringWithDefault(\"PK1_DEV_QUAD_ORDER\", \"THIRD\"));\n        PK1_dil_stress_data.quad_order =\n            Utility::string_to_enum<libMesh::Order>(input_db->getStringWithDefault(\"PK1_DIL_QUAD_ORDER\", \"FIRST\"));\n        ib_method_ops->registerPK1StressFunction(PK1_dev_stress_data);\n        ib_method_ops->registerPK1StressFunction(PK1_dil_stress_data);\n        if (input_db->getBoolWithDefault(\"ELIMINATE_PRESSURE_JUMPS\", false))\n        {\n            ib_method_ops->registerStressNormalizationPart();\n        }\n        ib_method_ops->initializeFEEquationSystems();\n        EquationSystems* equation_systems = ib_method_ops->getFEDataManager()->getEquationSystems();\n\n        // Set up post processor to recover computed stresses.\n        ib_method_ops->initializeFEEquationSystems();\n        FEDataManager* fe_data_manager = ib_method_ops->getFEDataManager();\n\n        Pointer<IBFEPostProcessor> ib_post_processor =\n            new IBFECentroidPostProcessor(\"IBFEPostProcessor\", fe_data_manager);\n\n        ib_post_processor->registerTensorVariable(\"FF\", MONOMIAL, CONSTANT, IBFEPostProcessor::FF_fcn);\n\n        pair<IBTK::TensorMeshFcnPtr, void*> PK1_dev_stress_fcn_data(PK1_dev_stress_function, static_cast<void*>(NULL));\n        ib_post_processor->registerTensorVariable(\"sigma_dev\",\n                                                  MONOMIAL,\n                                                  CONSTANT,\n                                                  IBFEPostProcessor::cauchy_stress_from_PK1_stress_fcn,\n                                                  vector<SystemData>(),\n                                                  &PK1_dev_stress_fcn_data);\n\n        pair<IBTK::TensorMeshFcnPtr, void*> PK1_dil_stress_fcn_data(PK1_dil_stress_function, static_cast<void*>(NULL));\n        ib_post_processor->registerTensorVariable(\"sigma_dil\",\n                                                  MONOMIAL,\n                                                  CONSTANT,\n                                                  IBFEPostProcessor::cauchy_stress_from_PK1_stress_fcn,\n                                                  vector<SystemData>(),\n                                                  &PK1_dil_stress_fcn_data);\n\n        Pointer<hier::Variable<NDIM> > p_var = navier_stokes_integrator->getPressureVariable();\n        Pointer<VariableContext> p_current_ctx = navier_stokes_integrator->getCurrentContext();\n        HierarchyGhostCellInterpolation::InterpolationTransactionComponent p_ghostfill(\n            /*data_idx*/ -1, \"LINEAR_REFINE\", /*use_cf_bdry_interpolation*/ false, \"CONSERVATIVE_COARSEN\", \"LINEAR\");\n        FEDataManager::InterpSpec p_interp_spec(\"PIECEWISE_LINEAR\",\n                                                QGAUSS,\n                                                FIFTH,\n                                                /*use_adaptive_quadrature*/ false,\n                                                /*point_density*/ 2.0,\n                                                /*use_consistent_mass_matrix*/ true,\n                                                /*use_nodal_quadrature*/ false,\n                                                /*allow_rules_with_negative_weights*/ false);\n        ib_post_processor->registerInterpolatedScalarEulerianVariable(\n            \"p_f\", LAGRANGE, FIRST, p_var, p_current_ctx, p_ghostfill, p_interp_spec);\n\n        // Create Eulerian initial condition specification objects.\n        if (input_db->keyExists(\"VelocityInitialConditions\"))\n        {\n            Pointer<CartGridFunction> u_init = new muParserCartGridFunction(\n                \"u_init\", app_initializer->getComponentDatabase(\"VelocityInitialConditions\"), grid_geometry);\n            navier_stokes_integrator->registerVelocityInitialConditions(u_init);\n        }\n\n        if (input_db->keyExists(\"PressureInitialConditions\"))\n        {\n            Pointer<CartGridFunction> p_init = new muParserCartGridFunction(\n                \"p_init\", app_initializer->getComponentDatabase(\"PressureInitialConditions\"), grid_geometry);\n            navier_stokes_integrator->registerPressureInitialConditions(p_init);\n        }\n\n        // Create Eulerian boundary condition specification objects (when necessary).\n        const IntVector<NDIM>& periodic_shift = grid_geometry->getPeriodicShift();\n        vector<RobinBcCoefStrategy<NDIM>*> u_bc_coefs(NDIM);\n        if (periodic_shift.min() > 0)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                u_bc_coefs[d] = NULL;\n            }\n        }\n        else\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                const std::string bc_coefs_name = \"u_bc_coefs_\" + std::to_string(d);\n\n                const std::string bc_coefs_db_name = \"VelocityBcCoefs_\" + std::to_string(d);\n\n                u_bc_coefs[d] = new muParserRobinBcCoefs(\n                    bc_coefs_name, app_initializer->getComponentDatabase(bc_coefs_db_name), grid_geometry);\n            }\n            navier_stokes_integrator->registerPhysicalBoundaryConditions(u_bc_coefs);\n        }\n\n        // Create Eulerian body force function specification objects.\n        if (input_db->keyExists(\"ForcingFunction\"))\n        {\n            Pointer<CartGridFunction> f_fcn = new muParserCartGridFunction(\n                \"f_fcn\", app_initializer->getComponentDatabase(\"ForcingFunction\"), grid_geometry);\n            time_integrator->registerBodyForceFunction(f_fcn);\n        }\n\n        // Set up visualization plot file writers.\n        Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter();\n        if (uses_visit)\n        {\n            time_integrator->registerVisItDataWriter(visit_data_writer);\n            visit_data_writer->registerPlotQuantity(\"workload\", \"SCALAR\", time_integrator->getWorkloadDataIndex());\n        }\n        std::unique_ptr<ExodusII_IO> exodus_io(uses_exodus ? new ExodusII_IO(mesh) : NULL);\n\n        // Check to see if this is a restarted run to append current exodus files\n        if (uses_exodus)\n        {\n            const bool from_restart = RestartManager::getManager()->isFromRestart();\n            exodus_io->append(from_restart);\n        }\n\n        // Initialize hierarchy configuration and data on all patches.\n        ib_method_ops->initializeFEData();\n        if (ib_post_processor) ib_post_processor->initializeFEData();\n        time_integrator->initializePatchHierarchy(patch_hierarchy, gridding_algorithm);\n\n        // Deallocate initialization objects.\n        app_initializer.setNull();\n\n        // Print the input database contents to the log file.\n        plog << \"Input database:\\n\";\n        input_db->printClassData(plog);\n\n        // Write out initial visualization data.\n        int iteration_num = time_integrator->getIntegratorStep();\n        double loop_time = time_integrator->getIntegratorTime();\n        if (dump_viz_data)\n        {\n            pout << \"\\n\\nWriting visualization files...\\n\\n\";\n            if (uses_visit)\n            {\n                const System& position_system = equation_systems->get_system(IBFEMethod::COORDS_SYSTEM_NAME);\n                time_integrator->setupPlotData();\n                visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n                if (NDIM < 3)\n                {\n                    IBTK::BoxPartitioner partitioner(*patch_hierarchy, position_system);\n                    partitioner.writePartitioning(\"patch-part-\" + std::to_string(iteration_num) + \".txt\");\n                    // Write partitioning data from libMesh.\n                    IBTK::write_node_partitioning(\"node-part-\" + std::to_string(iteration_num) + \".txt\",\n                                                  position_system);\n                }\n            }\n            if (uses_exodus)\n            {\n                if (ib_post_processor) ib_post_processor->postProcessData(loop_time);\n                exodus_io->write_timestep(\n                    exodus_filename, *equation_systems, iteration_num / viz_dump_interval + 1, loop_time);\n            }\n        }\n\n        // Open streams to save volume of structure.\n        ofstream volume_stream;\n        if (IBTK_MPI::getRank() == 0)\n        {\n            volume_stream.open(\"volume.curve\", ios_base::out | ios_base::trunc);\n        }\n\n        // Main time step loop.\n        double loop_time_end = time_integrator->getEndTime();\n        double dt = 0.0;\n        while (!IBTK::rel_equal_eps(loop_time, loop_time_end) && time_integrator->stepsRemaining())\n        {\n            iteration_num = time_integrator->getIntegratorStep();\n            loop_time = time_integrator->getIntegratorTime();\n\n            pout << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"At beginning of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n\n            dt = time_integrator->getMaximumTimeStepSize();\n            time_integrator->advanceHierarchy(dt);\n            loop_time += dt;\n\n            pout << \"\\n\";\n            pout << \"At end       of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"\\n\";\n\n            // At specified intervals, write visualization and restart files,\n            // print out timer data, and store hierarchy data for post\n            // processing.\n            iteration_num += 1;\n            const bool last_step = !time_integrator->stepsRemaining();\n            if (dump_viz_data && (iteration_num % viz_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting visualization files...\\n\\n\";\n                if (uses_visit)\n                {\n                    const System& position_system = equation_systems->get_system(IBFEMethod::COORDS_SYSTEM_NAME);\n                    time_integrator->setupPlotData();\n                    visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n                    if (NDIM < 3)\n                    {\n                        IBTK::BoxPartitioner partitioner(*patch_hierarchy, position_system);\n                        partitioner.writePartitioning(\"patch-part-\" + std::to_string(iteration_num) + \".txt\");\n                        IBTK::write_node_partitioning(\"node-part-\" + std::to_string(iteration_num) + \".txt\",\n                                                      position_system);\n                    }\n                }\n                if (uses_exodus)\n                {\n                    if (ib_post_processor) ib_post_processor->postProcessData(loop_time);\n                    exodus_io->write_timestep(\n                        exodus_filename, *equation_systems, iteration_num / viz_dump_interval + 1, loop_time);\n                }\n            }\n            if (dump_restart_data && (iteration_num % restart_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting restart files...\\n\\n\";\n                RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num);\n                ib_method_ops->writeFEDataToRestartFile(restart_dump_dirname, iteration_num);\n            }\n            if (dump_timer_data && (iteration_num % timer_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting timer data...\\n\\n\";\n                TimerManager::getManager()->print(plog);\n            }\n            if (dump_postproc_data && (iteration_num % postproc_data_dump_interval == 0 || last_step))\n            {\n                output_data(patch_hierarchy,\n                            navier_stokes_integrator,\n                            mesh,\n                            equation_systems,\n                            iteration_num,\n                            loop_time,\n                            postproc_data_dump_dirname);\n            }\n\n            // Compute the volume of the structure.\n            double J_integral = 0.0;\n            System& X_system = equation_systems->get_system<System>(IBFEMethod::COORDS_SYSTEM_NAME);\n            NumericVector<double>* X_vec = X_system.solution.get();\n            NumericVector<double>* X_ghost_vec = X_system.current_local_solution.get();\n            copy_and_synch(*X_vec, *X_ghost_vec);\n            DofMap& X_dof_map = X_system.get_dof_map();\n            vector<vector<unsigned int> > X_dof_indices(NDIM);\n            std::unique_ptr<FEBase> fe(FEBase::build(NDIM, X_dof_map.variable_type(0)));\n            std::unique_ptr<QBase> qrule = QBase::build(QGAUSS, NDIM, FIFTH);\n            fe->attach_quadrature_rule(qrule.get());\n            const vector<double>& JxW = fe->get_JxW();\n            const vector<vector<VectorValue<double> > >& dphi = fe->get_dphi();\n            TensorValue<double> FF;\n            boost::multi_array<double, 2> X_node;\n            const auto el_begin = mesh.active_local_elements_begin();\n            const auto el_end = mesh.active_local_elements_end();\n            for (auto el_it = el_begin; el_it != el_end; ++el_it)\n            {\n                const auto elem = *el_it;\n                fe->reinit(elem);\n                for (unsigned int d = 0; d < NDIM; ++d)\n                {\n                    X_dof_map.dof_indices(elem, X_dof_indices[d], d);\n                }\n                const int n_qp = qrule->n_points();\n                get_values_for_interpolation(X_node, *X_ghost_vec, X_dof_indices);\n                for (int qp = 0; qp < n_qp; ++qp)\n                {\n                    jacobian(FF, qp, X_node, dphi);\n                    J_integral += abs(FF.det()) * JxW[qp];\n                }\n            }\n            J_integral = IBTK_MPI::sumReduction(J_integral);\n            if (IBTK_MPI::getRank() == 0)\n            {\n                volume_stream.precision(12);\n                volume_stream.setf(ios::fixed, ios::floatfield);\n                volume_stream << loop_time << \" \" << J_integral << endl;\n            }\n        }\n\n        // Close the logging streams.\n        if (IBTK_MPI::getRank() == 0)\n        {\n            volume_stream.close();\n        }\n\n        // Cleanup Eulerian boundary condition specification objects (when\n        // necessary).\n        for (unsigned int d = 0; d < NDIM; ++d) delete u_bc_coefs[d];\n\n    } // cleanup dynamically allocated objects prior to shutdown\n} // main\n\nvoid\noutput_data(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n            Pointer<INSHierarchyIntegrator> navier_stokes_integrator,\n            MeshBase& mesh,\n            EquationSystems* equation_systems,\n            const int iteration_num,\n            const double loop_time,\n            const string& data_dump_dirname)\n{\n    plog << \"writing hierarchy data at iteration \" << iteration_num << \" to disk\" << endl;\n    plog << \"simulation time is \" << loop_time << endl;\n\n    // Write Cartesian data.\n    string file_name = data_dump_dirname + \"/\" + \"hier_data.\";\n    char temp_buf[128];\n    sprintf(temp_buf, \"%05d.samrai.%05d\", iteration_num, IBTK_MPI::getRank());\n    file_name += temp_buf;\n    Pointer<HDFDatabase> hier_db = new HDFDatabase(\"hier_db\");\n    hier_db->create(file_name);\n    VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();\n    ComponentSelector hier_data;\n    hier_data.setFlag(var_db->mapVariableAndContextToIndex(navier_stokes_integrator->getVelocityVariable(),\n                                                           navier_stokes_integrator->getCurrentContext()));\n    hier_data.setFlag(var_db->mapVariableAndContextToIndex(navier_stokes_integrator->getPressureVariable(),\n                                                           navier_stokes_integrator->getCurrentContext()));\n    patch_hierarchy->putToDatabase(hier_db->putDatabase(\"PatchHierarchy\"), hier_data);\n    hier_db->putDouble(\"loop_time\", loop_time);\n    hier_db->putInteger(\"iteration_num\", iteration_num);\n    hier_db->close();\n\n    // Write Lagrangian data.\n    file_name = data_dump_dirname + \"/\" + \"fe_mesh.\";\n    sprintf(temp_buf, \"%05d\", iteration_num);\n    file_name += temp_buf;\n    file_name += \".xda\";\n    mesh.write(file_name);\n    file_name = data_dump_dirname + \"/\" + \"fe_equation_systems.\";\n    sprintf(temp_buf, \"%05d\", iteration_num);\n    file_name += temp_buf;\n    equation_systems->write(file_name, (EquationSystems::WRITE_DATA | EquationSystems::WRITE_ADDITIONAL_DATA));\n    return;\n} // output_data\n", "meta": {"hexsha": "b4ee26ff227058d5d1408febd2608c5331d4aff1", "size": 29944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/IBFE/explicit/ex4/example.cpp", "max_stars_repo_name": "colegruninger97/IBAMR", "max_stars_repo_head_hexsha": "0f9b9b95533022571cc1a9972c42d8fc3f9d2a18", "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/IBFE/explicit/ex4/example.cpp", "max_issues_repo_name": "colegruninger97/IBAMR", "max_issues_repo_head_hexsha": "0f9b9b95533022571cc1a9972c42d8fc3f9d2a18", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/IBFE/explicit/ex4/example.cpp", "max_forks_repo_name": "colegruninger97/IBAMR", "max_forks_repo_head_hexsha": "0f9b9b95533022571cc1a9972c42d8fc3f9d2a18", "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": 47.9871794872, "max_line_length": 119, "alphanum_fraction": 0.5849251937, "num_tokens": 6322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5411712430510872}}
{"text": "/*  \n * Copyright (c) 2009 Carnegie Mellon University. \n *     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,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n *      http://www.graphlab.ml.cmu.edu\n *\n */\n\n\n/**\n *\n * \\brief This application is almost identical to LBP structured\n * prediction except that it generates an artificial field for every\n * vertex enabling the studying of distributed LBP on various graph\n * structures without the need for actual data.  \n *\n *\n * Technical Explanation\n * ========================\n *\n * This application creates a pair-wise Markov Random Field with\n * Ising-Potts edge factors and then uses residual loopy belief\n * propagation to compute posterior belief estimates for each vertex.\n *\n *\n *  \\author Joseph Gonzalez\n */\n\n\n#include <boost/config/warning_disable.hpp>\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_stl.hpp>\n\n\n#include <Eigen/Dense>\n#include \"eigen_serialization.hpp\"\n\n\n\n#include <graphlab.hpp>\n#include <graphlab/macros_def.hpp>\n\n\n\n\n/**\n * \\brief Eigen library vectors are used to store factor in _LOG\n * SPACE_.\n */\ntypedef Eigen::VectorXd factor_type;\n\n/**\n * \\brief The Ising smoothing parameter which controls the coupling\n * between adjacent predictions in the graph.  Larger values imply\n * greater smoothing (stronger coupling). \n *\n * \\code\n * edge_factor(xi, xj) = exp( (xi == xj)? 0 : -SMOOTHING * edge_weight ); \n * \\endcode\n *\n * Not that the default edge weight is 1 however the graph file can\n * contain an additional edge weight column which allows per edge\n * control of the smoothing parameter.\n *\n * This parameter is set as a command line argument.\n */\ndouble SMOOTHING = 2;\n\n\ndouble FIELD = 2;\nsize_t NSTATES = 5;\n\n/**\n * \\brief The Damping parameter which helps ensure stable convergence.\n * Larger damping values lead to slower but more stable convergence.\n *\n * Currently damping is implemented in log-space in the following\n * equation:\n *\n * \\code\n * log(new_message) = DAMPING * log(old_message) + \n *                         (1-DAMPING) * log(new_message);\n * \\endcode\n *\n * This parameter is set as a command line argument.\n */\ndouble DAMPING = 0.1;\n\n/**\n * \\brief The convergence threshold for each message.  Smaller values\n * imply tighter convergence but slower execution.\n *\n *\n * The algorithm convergence when:\n *   \n * \\code\n * sum(abs(log(old_message) - log(new_message))) < TOLERANCE\n * \\endcode\n *\n * The parameter is set as a command line argument\n */\ndouble TOLERANCE = 0.01;\n\n\n\nbool USE_CACHE = false;\n\n\n/**\n * Make a synthetic node potential\n */\nfactor_type make_node_potential(size_t vid) {\n  // const size_t obs = vid % NSTATES;\n  const size_t obs = 0;\n  factor_type factor;\n  factor.setZero(NSTATES);\n  if(vid % 101 < 1) {\n    for(size_t i = 0; i <  NSTATES; ++i) {\n      factor(i) = (i == obs)? 0 : -FIELD;\n    }\n  } \n  return factor;\n}\n\n/**\n * \\brief The vertex data contains the vertex potential as well as the\n * current belief estimate and represents a random variable in the\n * Markov Random Field.\n *\n * The vertex potential represents the prior and is obtained from the\n * vertex prior file (stored in log form).\n *\n * The belief represents the current posterior estimate.\n */\nstruct vertex_data {\n  factor_type belief;\n  void load(graphlab::iarchive& arc) { arc >> belief; }\n  void save(graphlab::oarchive& arc) const { arc << belief; }\n}; // end of vertex_data\n\n\n/**\n * \\brief The edge data represents an edge in the Markov Random Field\n * and contains the loopy belief propagation message in both\n * directions along that edge as well as the old message in each\n * direction.  In addition each edge contains the weight parameter\n * used to set edge specific smoothing (default value is 1).\n */\nclass edge_data {\n  /**\n   * \\brief We store old and new messages in both directions as an\n   * array of messages.  The particular message index is then computed\n   * using the \\ref message_idx function.\n   */\n  factor_type messages_[4];\n  /**\n   * \\brief The weight associated with the edge (used to scale the\n   * smoothing parameter)\n   */\n  double weight_;\n  /**\n   * \\brief The function used to compute the message index in the edge\n   * message array.\n   */\n  size_t message_idx(size_t source_id, size_t target_id, bool is_new) {\n    return size_t(source_id < target_id)  + 2 * size_t(is_new);\n  }\n\npublic:\n\n  edge_data(const double w = 1) : weight_(w) { }\n  const double& weight() const { return weight_; }\n\n  /**\n   * \\brief Get the new message value from source_id to target_id\n   */\n  factor_type& message(size_t source_id, size_t target_id) { \n    return messages_[message_idx(source_id, target_id, true)];\n  }\n  /**\n   * \\brief Get the old message value from source_id to target_id\n   */\n  factor_type& old_message(size_t source_id, size_t target_id) { \n     return messages_[message_idx(source_id, target_id, false)];\n  }\n\n  /**\n   * \\brief Set the old message value equal to the new message value\n   */\n  void update_old(size_t source_id, size_t target_id) { \n    old_message(source_id, target_id) = message(source_id, target_id);\n  }\n  \n  /**\n   * \\brief Initialize the edge data with source and target having the\n   * appropriate number of states.\n   *\n   * \\param source_id the vertex id of the source\n   * \\param nsource the number of states the source vertex takes\n   * \\param target_id the vertex id of the target\n   * \\param ntarget the number of states the target vertex takes\n   */\n  void initialize(size_t source_id, size_t nsource, size_t target_id, size_t ntarget) {\n    ASSERT_GT(nsource, 0); ASSERT_GT(ntarget, 0);\n    message(source_id, target_id).setZero(ntarget);\n    old_message(source_id, target_id).setZero(ntarget);\n    message(target_id, source_id).setZero(nsource);\n    old_message(target_id, source_id).setZero(nsource);\n  }\n  void save(graphlab::oarchive& arc) const {\n    for(size_t i = 0; i < 4; ++i) arc << messages_[i];\n    arc << weight_;\n  }\n  void load(graphlab::iarchive& arc) {\n    for(size_t i = 0; i < 4; ++i) arc >> messages_[i];\n    arc >> weight_;\n  }\n}; // End of edge data\n\n\n\n/**\n * \\brief The graph type used to store the Markov Random Field with\n * vertex data containing node potentials and beliefs and edge data\n * containing messages and weights.\n */\ntypedef graphlab::distributed_graph<vertex_data, edge_data> graph_type;\n\n\n\n\n\n\n/** \n * \\brief The Loopy Belief Propagation Vertex Program which computes\n * the product of the inbound messages during the gather phase,\n * updates the belief during the apply phase, and then computes the\n * new out-bound messages during the scatter phase.\n *\n * Since the gather phase is computing the product of the inbound\n * messages and the messages are stored in log form the resulting sum\n * operation is actually a vector sum and so the gather type is simply\n * the factor type and the operator+= operation for the factor type is\n * sufficient.\n *\n */\nstruct bp_vertex_program : \n  public graphlab::ivertex_program< graph_type, factor_type,\n                                    graphlab::messages::sum_priority >,\n  public graphlab::IS_POD_TYPE {\n\n  /**\n   * \\brief Since the MRF is undirected we will use all edges for gather and\n   * scatter\n   */\n  edge_dir_type gather_edges(icontext_type& context,\n                             const vertex_type& vertex) const { \n    return graphlab::ALL_EDGES; \n  }; // end of gather_edges \n\n  /**\n   * \\brief Update the old message to be the new message and collect the\n   * message value.\n   */\n  factor_type gather(icontext_type& context, const vertex_type& vertex, \n                     edge_type& edge) const {\n    const vertex_type other_vertex = get_other_vertex(edge, vertex);\n    edge_data& edata = edge.data();\n    // Update the old message with the value of the new Message.  We\n    // then receive the old message during gather and then compute the\n    // \"cavity\" during scatter (again using the old message).\n    edata.update_old(other_vertex.id(), vertex.id());\n    const factor_type& recv_message = \n      edata.old_message(other_vertex.id(), vertex.id());\n    return recv_message;\n\n  }; // end of gather function\n\n  /**\n   * \\brief Multiply message product by node potential and update the\n   * belief.\n   */\n  void apply(icontext_type& context, vertex_type& vertex, \n             const factor_type& total) {\n    // If we have no neighbors than the belief is equal to the\n    // potential so simply update the belief\n    if(vertex.num_in_edges() + vertex.num_out_edges() == 0) {\n      vertex.data().belief = make_node_potential(vertex.id());\n    } else {\n      vertex_data& vdata = vertex.data();\n      // Multiply (add in log space) the potential to compute the belief\n      vdata.belief = make_node_potential(vertex.id()) + total;\n      ASSERT_GT(vdata.belief.size(), 0);\n      // Rescale the belief to ensure numerical stability.  (This is\n      // essentially normalization in log-space.)\n      vdata.belief.array() -= vdata.belief.maxCoeff();\n    }\n  }; // end of apply\n\n  /**\n   * \\brief Since the MRF is undirected we will use all edges for gather and\n   * scatter\n   */\n  edge_dir_type scatter_edges(icontext_type& context,\n                              const vertex_type& vertex) const { \n    return graphlab::ALL_EDGES; \n  }; // end of scatter edges\n\n  /**\n   * \\brief Compute new message value for each edge.\n   */\n  void scatter(icontext_type& context, const vertex_type& vertex, \n               edge_type& edge) const {  \n    const vertex_type other_vertex = get_other_vertex(edge, vertex);\n    edge_data& edata = edge.data();\n    // Divide (subtract in log space) out of the belief the old in\n    // message to construct the cavity\n    const factor_type& old_in_message = \n      edata.old_message(other_vertex.id(), vertex.id());\n    ASSERT_EQ(old_in_message.size(), vertex.data().belief.size());\n    factor_type cavity = vertex.data().belief - old_in_message;\n    // compute the new message by convolving with the Ising-Potts Edge\n    // factor.\n    factor_type& new_out_message = \n      edata.message(vertex.id(), other_vertex.id());\n    // Make a backup of the last sent message which we will use to\n    // maintain the cache\n    const factor_type last_sent_message = new_out_message;\n    const factor_type& last_recv_message = \n      edata.old_message(vertex.id(), other_vertex.id());\n    convolve(cavity, edata.weight(), new_out_message);\n    // Renormalize (done in log space)\n    new_out_message.array() -= new_out_message.maxCoeff();\n    // // Apply damping to the message to stabilize convergence.\n    new_out_message = DAMPING * last_sent_message + \n      (1-DAMPING) * new_out_message;\n    // Compute message residual\n    const double residual = \n      (new_out_message - last_recv_message).cwiseAbs().sum();\n    if(USE_CACHE) {\n      // context.clear_gather_cache(other_vertex);\n      context.post_delta(other_vertex, new_out_message - last_sent_message);\n      edata.update_old(vertex.id(), other_vertex.id());\n    }\n    // Schedule the adjacent vertex\n    if(residual > TOLERANCE) context.signal(other_vertex, residual);\n }; // end of scatter\n\nprivate:\n\n  /**\n   * \\brief Compute the convolution of the cavity with the Ising-Potts\n   * edge potential and store the result in the message\n   *\n   * \\param cavity the belief minus the in-bound message\n   * \\param weight the edge weight used to scale the smoothing parameter\n   * \\param [out] message The message in which to store the result of\n   * the convolution.\n   */\n  inline void convolve(const factor_type& cavity, const double& weight, \n                       factor_type& message) const {\n    for(int i = 0; i < message.size(); ++i) {\n      double sum = 0;\n      for(int j = 0; j < cavity.size(); ++j) {\n        sum += std::exp( cavity(j)  + ( i == j? 0 : -(SMOOTHING*weight) ) ); \n      }\n      // To try and ensure numerical stability we do not allow\n      // messages to underflow in log-space\n      message(i) = (sum > 0)? std::log(sum) : \n        std::numeric_limits<double>::min();\n    }\n  } // end of convolve\n  \n  /**\n   * \\brief Given an edge and a vertex return the other vertex along\n   * that edge. \n   */\n  inline vertex_type get_other_vertex(edge_type& edge, \n                                      const vertex_type& vertex) const {\n    return vertex.id() == edge.source().id()? edge.target() : edge.source();\n  }; // end of other_vertex\n\n}; // end of class bp_vertex_program\n\n\n\n\n \n\n\n\n\n\n/**\n * \\brief The edge data loader is used by the GraphLab graph loading\n * API to parse lines in the edge data file. \n */\nbool edge_loader(graph_type& graph, const std::string& fname, \n                 const std::string& line) {\n  ASSERT_FALSE(line.empty()); \n  namespace qi = boost::spirit::qi;\n  namespace ascii = boost::spirit::ascii;\n  namespace phoenix = boost::phoenix;\n  graphlab::vertex_id_type source(-1), target(-1);\n  double weight = 1;\n  const bool success = qi::phrase_parse\n    (line.begin(), line.end(),       \n     //  Begin grammar\n     (\n      qi::ulong_[phoenix::ref(source) = qi::_1] >>  -qi::char_(',') \n      >> qi::ulong_[phoenix::ref(target) = qi::_1] >>  \n      -(-qi::char_(',') >> qi::double_[phoenix::ref(weight) = qi::_1])\n      )\n     ,\n     //  End grammar\n     ascii::space);\n  if(!success) return false;\n  if(source == target) return true;\n  else {\n    graph.add_edge(source, target, edge_data(weight));\n    return true;\n  }\n} // end of edge loader\n\n\n\n/**\n * \\brief The edge initializer is used to allocate the messages along\n * each edge based on the number of states of the source and target\n * vertex.\n */\nvoid edge_initializer(graph_type::edge_type& edge) {\n  edge_data& edata = edge.data();\n  const graphlab::vertex_id_type source_id = edge.source().id();\n  const size_t nsource = NSTATES;\n  const graphlab::vertex_id_type target_id = edge.target().id();\n  const size_t ntarget = NSTATES;\n  edata.initialize(source_id, nsource, target_id, ntarget);\n} // end of edge initializer\n\n\n\n\n/**\n * \\brief The belief prediction saver is used to save the belief\n * predictions for each vertex.\n */\nstruct belief_prediction_saver {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  std::string save_vertex(const vertex_type& vertex) const {\n    std::stringstream strm;\n    strm << vertex.id() << '\\t';\n    factor_type pred = vertex.data().belief;\n    double sum = 0;\n    for(int i = 0; i < pred.size(); ++i) \n      sum += (pred(i) = std::exp(pred(i)));\n    pred.array() /= sum;\n    for(int i = 0; i < pred.size(); ++i) \n      strm << pred(i) << (i+1 < pred.size()? '\\t' : '\\n');\n    return strm.str();\n  }\n  std::string save_edge(const edge_type& edge) const {\n    return \"\"; // nop\n  }\n}; // end of belief_prediction_saver\n\n\n/**\n * \\brief The MAP prediction saver is used to save the map estimated\n * for each vertex.  The MAP estimate is the most likely assignment\n */\nstruct map_prediction_saver {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  std::string save_vertex(const vertex_type& vertex) const {\n    std::stringstream strm;\n    size_t prediction = 0;\n    vertex.data().belief.maxCoeff(&prediction);\n    strm << vertex.id() << '\\t' << prediction << '\\n';\n    return strm.str();\n  }\n  std::string save_edge(const edge_type& edge) const {\n    return \"\"; // nop\n  }\n}; // end of map prediction_saver\n\n\n\n\n\nint main(int argc, char** argv) {\n  global_logger().set_log_level(LOG_INFO);\n  global_logger().set_log_to_console(true);\n  ///! Initialize control plain using mpi\n  graphlab::mpi_tools::init(argc, argv);\n  graphlab::distributed_control dc;\n  // Parse command line options -----------------------------------------------\n  // \\todo update description string\n  const std::string description = \"Structure prediction solver\";\n  graphlab::command_line_options clopts(description);\n \n  std::string graph_dir;\n  std::string output_dir = \"pred\";\n  std::string exec_type = \"async\";\n  std::string format = \"tsv\";\n  bool map = false;\n  clopts.attach_option(\"graph\", graph_dir,\n                       \"The directory containing the adjacency graph\");\n  clopts.add_positional(\"graph\"); \n  clopts.attach_option(\"field\", FIELD, \n                       \"The background field used to construct the node potentials\");\n  clopts.attach_option(\"nstates\", NSTATES, \n                       \"The number of states for each variable\");\n  clopts.attach_option(\"cache\", USE_CACHE, \"use gather caching\");\n  clopts.attach_option(\"output\", output_dir,\n                       \"The directory in which to save the predictions\");\n  clopts.attach_option(\"format\", format, \"The graph file format.\");\n  clopts.add_positional(\"output\");\n  clopts.attach_option(\"smoothing\", SMOOTHING,\n                       \"The amount of smoothing (larger = more)\");\n  clopts.attach_option(\"damping\", DAMPING,\n                       \"The amount of damping (0 -> no damping and 1 -> no progress)\");\n  clopts.attach_option(\"tol\", TOLERANCE,\n                       \"The tolerance level for convergence.\");\n  clopts.attach_option(\"map\", map,\n                       \"Return maximizing assignment instead of the posterior distribution.\");\n  clopts.attach_option(\"engine\", exec_type,\n                       \"The type of engine to use {async, sync}.\");\n  if(!clopts.parse(argc, argv)) {\n    graphlab::mpi_tools::finalize();\n    return clopts.is_set(\"help\")? EXIT_SUCCESS : EXIT_FAILURE;\n  }\n\n  clopts.get_engine_args().set_option(\"use_cache\", USE_CACHE);\n\n  if(graph_dir.empty()) {\n    logstream(LOG_ERROR) << \"No graph was provided.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  // Start the webserver\n  graphlab::launch_metric_server();\n\n  ///! load the graph\n  graph_type graph(dc, clopts);  \n\n\n  ///! load the graph\n  graph.load_format(graph_dir, format);\n  graph.finalize();\n  dc.cout() << \"Initializing edge data\" << std::endl;\n  graph.transform_edges(edge_initializer);\n\n  typedef graphlab::omni_engine<bp_vertex_program> engine_type;\n  engine_type engine(dc, graph, exec_type, clopts);\n  engine.signal_all();\n  graphlab::timer timer;\n  dc.cout() << \"Running engine\" << std::endl;\n  engine.start();  \n  const double runtime = timer.current_time();\n    dc.cout() \n    << \"----------------------------------------------------------\" << std::endl\n    << \"Final Runtime (seconds):   \" << runtime \n    << std::endl\n    << \"Updates executed: \" << engine.num_updates() << std::endl\n    << \"Update Rate (updates/second): \" \n    << engine.num_updates() / runtime << std::endl;\n    \n    \n  std::cout << \"Saving predictions\" << std::endl;\n  const bool gzip_output = false;\n  const bool save_vertices = true;\n  const bool save_edges = false;\n  const size_t threads_per_machine = 2;\n  if(map) {\n    graph.save(output_dir, map_prediction_saver(),\n               gzip_output, save_vertices, \n               save_edges, threads_per_machine);\n  } else { \n    graph.save(output_dir, belief_prediction_saver(),\n               gzip_output, save_vertices, \n               save_edges, threads_per_machine);\n  }\n\n\n    \n  //  graphlab::stop_metric_server_on_eof();\n  graphlab::stop_metric_server();\n  graphlab::mpi_tools::finalize();\n  return EXIT_SUCCESS;\n\n\n} // end of main\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "0f5fdf11398341b222c5caf87fe3b0b03b740777", "size": 19767, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/graphical_models/profile_lbp_synthetic.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": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T11:46:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T22:45:55.000Z", "max_issues_repo_path": "toolkits/graphical_models/profile_lbp_synthetic.cpp", "max_issues_repo_name": "coreyp1/graphlab", "max_issues_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolkits/graphical_models/profile_lbp_synthetic.cpp", "max_forks_repo_name": "coreyp1/graphlab", "max_forks_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T12:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T16:48:40.000Z", "avg_line_length": 31.2768987342, "max_line_length": 94, "alphanum_fraction": 0.6673749178, "num_tokens": 4760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5411712421874584}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#define NT2_UNIT_MODULE \"nt2 exponential toolbox - logspace_add/scalar Mode\"\n\n//////////////////////////////////////////////////////////////////////////////\n// unit test behavior of exponential components in scalar mode\n//////////////////////////////////////////////////////////////////////////////\n/// created by jt the 08/12/2010\n///\n#include <nt2/exponential/include/functions/logspace_add.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/meta/as_floating.hpp>\n#include <nt2/sdk/meta/as_signed.hpp>\n#include <nt2/sdk/meta/upgrade.hpp>\n#include <nt2/sdk/meta/downgrade.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n#include <boost/type_traits/common_type.hpp>\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/memory/buffer.hpp>\n#include <nt2/constant/constant.hpp>\n\n\n\n\nNT2_TEST_CASE_TPL ( logspace_add_real__2_1,  NT2_REAL_TYPES)\n{\n\n  using nt2::logspace_add;\n  using nt2::tag::logspace_add_;\n  typedef typename nt2::meta::as_integer<T>::type iT;\n  typedef typename nt2::meta::call<logspace_add_(T,T)>::type r_t;\n  typedef typename nt2::meta::scalar_of<r_t>::type sr_t;\n  typedef typename nt2::meta::upgrade<T>::type u_t;\n  typedef typename boost::dispatch::meta::as_floating<T>::type wished_r_t;\n\n\n  // return type conformity test\n  NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) );\n  double ulpd;\n  ulpd=0.0;\n\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(logspace_add(nt2::Inf<T>(),nt2::Inf<T>()), nt2::Inf<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(logspace_add(nt2::Inf<T>(),nt2::Zero<T>()), nt2::Inf<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(logspace_add(nt2::Minf<T>(),nt2::Zero<T>()), nt2::Zero<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(logspace_add(nt2::Inf<T>(),nt2::Nan <T>()), nt2::Nan<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(logspace_add(nt2::Minf<T>(),nt2::Minf<T>()), nt2::Minf<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(logspace_add(nt2::Mone<T>(),nt2::Mone<T>()), nt2::Mone<sr_t>()+nt2::Log_2<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(logspace_add(nt2::Nan<T>(),nt2::Nan<T>()), nt2::Nan<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(logspace_add(nt2::One<T>(),nt2::One<T>()), nt2::One<sr_t>()+nt2::Log_2<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(logspace_add(nt2::Two <T>(), nt2::Two <T>()), nt2::Two <sr_t>()+nt2::Log_2<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(logspace_add(nt2::Zero<T>(),nt2::Zero<T>()), nt2::Log_2<sr_t>(), 0);\n} // end of test for floating_\n", "meta": {"hexsha": "a14b623a60b96e40ad744207003b7004087d0e9a", "size": 3001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/unit/scalar/logspace_add.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/core/exponential/unit/scalar/logspace_add.cpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/core/exponential/unit/scalar/logspace_add.cpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": 46.1692307692, "max_line_length": 108, "alphanum_fraction": 0.6187937354, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5411622101757594}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n//#define GRAPHBLAS_LOGGING_LEVEL 2\n\n#include <graphblas/graphblas.hpp>\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE mxm_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nusing namespace grb;\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n//****************************************************************************\n\nnamespace\n{\n    static std::vector<std::vector<double> > A_dense_3x3 =\n    {{12, 7, 3},\n     {4,  5, 6},\n     {7,  8, 9}};\n\n    static std::vector<std::vector<double> > AT_dense_3x3 =\n    {{12, 4, 7},\n     {7,  5, 8},\n     {3,  6, 9}};\n\n    static std::vector<std::vector<double> > B_dense_3x4 =\n    {{5, 8, 1, 2},\n     {6, 7, 3, 0.},\n     {4, 5, 9, 1}};\n\n    static std::vector<std::vector<double> > BT_dense_3x4 =\n    {{5, 6, 4},\n     {8, 7, 5},\n     {1, 3, 9},\n     {2, 0, 1}};\n\n    static std::vector<std::vector<double> > Answer_dense =\n    {{114, 160, 60,  27},\n     {74,  97,  73,  14},\n     {119, 157, 112, 23}};\n\n    static std::vector<std::vector<double> > Answer_plus1_dense =\n    {{115, 161, 61,  28},\n     {75,  98,  74,  15},\n     {120, 158, 113, 24}};\n\n    static std::vector<std::vector<double> > A_sparse_3x3 =\n    {{12, 7,  0},\n     {0, -5,  0},\n     {7,  0,  9}};\n\n    static std::vector<std::vector<double> > AT_sparse_3x3 =\n    {{12, 7,  0},\n     {0, -5,  0},\n     {7,  0,  9}};\n\n    static std::vector<std::vector<double> > B_sparse_3x4 =\n    {{5., 8.,  0, -2.},\n     {0., -7,  3., 0.},\n     {4., 0,   0,  1.}};\n\n    static std::vector<std::vector<double> > BT_sparse_3x4 =\n    {{5.,  0., 4},\n     {8., -7,  0.},\n     {0.,  3,  0.},\n     {-2., 0,  1}};\n\n    // A_sparse_3x3 * A_sparse_3x3\n    static std::vector<std::vector<double> > AA_answer_sparse =\n    {{144.,  49., 0},\n     {0.0,   25., 0},\n     {147.,  49., 81.}};\n\n    // A_sparse_3x3 * B_sparse_3x4\n    static std::vector<std::vector<double> > Answer_sparse =\n    {{60,   47., 21,  -24},\n     {0.0,  35.,-15,  0.0},\n     {71.0, 56,  0.0, -5.0}};\n\n    static std::vector<std::vector<double> > Symmetric_4x4 =\n    {{1, 1, 0, 0},\n     {1, 2, 2, 0},\n     {0, 2, 3, 3},\n     {0, 0, 3, 4}};\n\n    static std::vector<std::vector<double> > Symmetric2_4x4 =\n    {{2, 3, 2, 0},\n     {3, 9,10, 6},\n     {2,10,22,21},\n     {0, 6,21,25}};\n\n    static std::vector<std::vector<double> > Ones_4x4 =\n    {{1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > Ones_3x4 =\n    {{1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > Ones_3x3 =\n    {{1, 1, 1},\n     {1, 1, 1},\n     {1, 1, 1}};\n\n    static std::vector<std::vector<double> > Identity_3x3 =\n    {{1, 0, 0},\n     {0, 1, 0},\n     {0, 0, 1}};\n\n    static std::vector<std::vector<double> > Lower_3x3 =\n    {{1, 0, 0},\n     {1, 1, 0},\n     {1, 1, 1}};\n\n    static std::vector<std::vector<double> > Lower_3x4 =\n    {{1, 0, 0, 0},\n     {1, 1, 0, 0},\n     {1, 1, 1, 0}};\n\n    static std::vector<std::vector<double> > Lower_4x4 =\n    {{1, 0, 0, 0},\n     {1, 1, 0, 0},\n     {1, 1, 1, 0},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > NotLower_3x3 =\n    {{0, 1, 1},\n     {0, 0, 1},\n     {0, 0, 0}};\n\n    static std::vector<std::vector<double> > NotLower_3x4 =\n    {{0, 1, 1, 1},\n     {0, 0, 1, 1},\n     {0, 0, 0, 1}};\n\n    static std::vector<std::vector<double> > NotLower_4x4 =\n    {{0, 1, 1, 1},\n     {0, 0, 1, 1},\n     {0, 0, 0, 1},\n     {0, 0, 0, 0}};\n\n    static std::vector<std::vector<double> > LowerMask_3x4 =\n    {{1, 0,    0,   0},\n     {1, 0.5,  0,   0},\n     {1, -1.0, 1.5, 0}};\n\n    static std::vector<std::vector<bool> > LowerBool_3x4 =\n    {{true, false, false, false},\n     {true, true,  false, false},\n     {true, true,  true,  false}};\n\n    static std::vector<std::vector<bool> > LowerBool_3x3 =\n    {{true, false, false},\n     {true, true,  false},\n     {true, true,  true}};\n\n    static std::vector<std::vector<bool> > NotLowerBool_3x3 =\n    {{false,  true, true},\n     {false, false, true},\n     {false, false, false}};\n\n}\n\n//****************************************************************************\n// API error tests\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_bad_dimensions)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> A(A_dense_3x3, 0.); // 3x3\n    grb::Matrix<double, grb::DirectedMatrixTag> B(B_dense_3x4, 0.); // 3x4\n    grb::Matrix<double, grb::DirectedMatrixTag> result3x4(3, 4);\n    grb::Matrix<double, grb::DirectedMatrixTag> result3x3(3, 3);\n    grb::Matrix<double, grb::DirectedMatrixTag> ones3x4(Ones_3x4, 0.);\n\n    static std::vector<std::vector<double> > M_3x3 = {{1, 0, 0},\n                                                      {1, 1, 0},\n                                                      {1, 1, 1}};\n    grb::Matrix<double, grb::DirectedMatrixTag> M(M_3x3, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    // NoMask_NoAccum_AB\n\n    // ncols(A) != nrows(B)\n    BOOST_CHECK_THROW(\n        (mxm(result3x4,\n             grb::NoMask(), grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(),\n             B, A)),\n        DimensionException);\n\n    // dim(C) != dim(A*B)\n    BOOST_CHECK_THROW(\n        (mxm(result3x3,\n             grb::NoMask(), grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(),\n             A, B)),\n        DimensionException);\n\n    // NoMask_Accum_AB\n\n    // incompatible input matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(result3x4,\n                  grb::NoMask(),\n                  grb::Second<double>(),\n                  grb::ArithmeticSemiring<double>(), B, A)),\n        grb::DimensionException);\n\n    // incompatible output matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(result3x3,\n                  grb::NoMask(),\n                  grb::Second<double>(),\n                  grb::ArithmeticSemiring<double>(), A, B)),\n        grb::DimensionException);\n\n    // Mask_NoAccum\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(ones3x4,\n                  M,\n                  grb::NoAccumulate(),\n                  grb::ArithmeticSemiring<double>(), A, B,\n                  REPLACE)),\n        grb::DimensionException);\n\n    // Mask_Accum (replace and merge)\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(ones3x4,\n                  M,\n                  grb::Second<double>(),\n                  grb::ArithmeticSemiring<double>(), A, B, REPLACE)),\n        grb::DimensionException);\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(ones3x4,\n                  M,\n                  grb::Second<double>(),\n                  grb::ArithmeticSemiring<double>(), A, B)),\n        grb::DimensionException);\n\n    // CompMask_NoAccum (replace and merge)\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(ones3x4,\n                  grb::complement(M),\n                  grb::NoAccumulate(),\n                  grb::ArithmeticSemiring<double>(), A, B, REPLACE)),\n        grb::DimensionException);\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(result3x4,\n                  grb::complement(M),\n                  grb::NoAccumulate(),\n                  grb::ArithmeticSemiring<double>(), A, B)),\n        grb::DimensionException);\n\n    // CompMask_Accum (replace and merge)\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(ones3x4,\n                  grb::complement(M),\n                  grb::Second<double>(),\n                  grb::ArithmeticSemiring<double>(), A, B, REPLACE)),\n        grb::DimensionException);\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(result3x4,\n                  grb::complement(M),\n                  grb::Second<double>(),\n                  grb::ArithmeticSemiring<double>(), A, B)),\n        grb::DimensionException);\n}\n\n//****************************************************************************\n// NoMask_NoAccum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB)\n{\n    grb::Matrix<double> C(3, 4);\n    grb::Matrix<double> A(A_sparse_3x3, 0.);\n    grb::Matrix<double> B(B_sparse_3x4, 0.);\n\n    grb::Matrix<double> answer(Answer_sparse, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    for (grb::IndexType ix = 0; ix < answer.nrows(); ++ix)\n    {\n        for (grb::IndexType iy = 0; iy < answer.ncols(); ++iy)\n        {\n            BOOST_CHECK_EQUAL(C.hasElement(ix, iy), answer.hasElement(ix, iy));\n            if (C.hasElement(ix, iy))\n            {\n                BOOST_CHECK_CLOSE(C.extractElement(ix,iy),\n                                  answer.extractElement(ix,iy), 0.0001);\n            }\n        }\n    }\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_empty)\n{\n    grb::Matrix<double> Zero(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(Ones_3x3, 0.);\n    grb::Matrix<double> mD(Ones_3x3, 0.);\n\n    grb::mxm(C,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), Zero, Ones);\n    BOOST_CHECK_EQUAL(C, Zero);\n\n    grb::mxm(mD,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Zero);\n    BOOST_CHECK_EQUAL(mD, Zero);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_dense)\n{\n    IndexArrayType i_A    = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_A    = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_A = {12, 7, 3, 4, 5, 6, 7, 8, 9};\n    Matrix<double, DirectedMatrixTag> A(3, 3);\n    A.build(i_A, j_A, v_A);\n\n    IndexArrayType i_B    = {0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_B    = {0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 3};\n    std::vector<double> v_B = {5, 8, 1, 2, 6, 7, 3, 4, 5, 9, 1};\n    Matrix<double, DirectedMatrixTag> B(3, 4);\n    B.build(i_B, j_B, v_B);\n\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    IndexArrayType i_answer = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_answer = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3};\n    std::vector<double> v_answer = {114, 160, 60, 27, 74, 97,\n                                    73, 14, 119, 157, 112, 23};\n    Matrix<double, DirectedMatrixTag> answer(3, 4);\n    answer.build(i_answer, j_answer, v_answer);\n\n    mxm(result,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        A, B);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 7, 15},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11, 15}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    std::vector<std::vector<double>> answer_vals = {{0, 8, 0, 8},\n                                                    {0, 1, 0, 1},\n                                                    {0, 4, 0, 4}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_ABdup)\n{\n    // Build some matrices.\n    Matrix<double, DirectedMatrixTag> mat(Symmetric_4x4, 0.);\n    Matrix<double, DirectedMatrixTag> m3(4, 4);\n    Matrix<double, DirectedMatrixTag> answer(Symmetric2_4x4, 0.);\n\n    mxm(m3,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        mat, mat);\n\n    BOOST_CHECK_EQUAL(m3, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_ACdup)\n{\n    grb::Matrix<double> C(A_sparse_3x3, 0.);\n    grb::Matrix<double> B(A_sparse_3x3, 0.);\n\n    grb::Matrix<double> answer(AA_answer_sparse, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, B);\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_BCdup)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.);\n    grb::Matrix<double> C(B_sparse_3x4, 0.);\n\n    grb::Matrix<double> answer(Answer_sparse, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n//****************************************************************************\n// NoMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_AB)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.); // 3x3\n    grb::Matrix<double> B(B_dense_3x4, 0.); // 3x4\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(Answer_dense, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_AB_empty)\n{\n    grb::Matrix<double> Zero(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(Ones_3x3, 0.);\n    grb::Matrix<double> mD(Ones_3x3, 0.);\n\n    grb::mxm(C,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(), Zero, Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    grb::mxm(mD,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Zero);\n    BOOST_CHECK_EQUAL(mD, Ones);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_AB_stored_zero_result)\n{\n    // Build some matrices.\n    std::vector<std::vector<int> > B_mat = {{ 1,-2, 0,  0},\n                                            {-1, 1, 0,  0},\n                                            { 0, 0, 3, -4},\n                                            { 0, 0,-3,  3}};\n    grb::Matrix<double> A(Symmetric_4x4, 0);\n    grb::Matrix<int> B(B_mat, 0);\n    grb::Matrix<int> result(4, 4);\n\n    // use a different sentinel value so that stored zeros are preserved.\n    int const NIL(666);\n    std::vector<std::vector<int> > ans = {{  0,  -1, NIL, NIL},\n                                          { -1,   0,   6,  -8},\n                                          { -2,   2,   0,  -3},\n                                          {NIL, NIL,  -3,   0}};\n    grb::Matrix<int> answer(ans, NIL);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<int>(),\n             grb::ArithmeticSemiring<int>(), A, B);\n    BOOST_CHECK_EQUAL(result, answer);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_AB_ABdup_Cempty)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> result(4, 4);\n    grb::Matrix<double> answer(Symmetric2_4x4, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_AB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    std::vector<std::vector<double>> answer_vals = {{2, 1, 8, 16},\n                                                    {1, 1, 1, 1},\n                                                    {10,1, 12, 16}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> result(Ones_3x4, 0.);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_AB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    std::vector<std::vector<double>> answer_vals = {{1, 9, 1, 9},\n                                                    {1, 2, 1, 2},\n                                                    {1, 5, 1, 5}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> result(Ones_3x4, 0.);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_AB_ABdup)\n{\n    // Build some matrices.\n    Matrix<double> mat(A_sparse_3x3,0.);\n    Matrix<double> m3(Ones_3x3, 0.);\n\n    // A_sparse_3x3 * A_sparse_3x3 + Ones\n    static std::vector<std::vector<double> > ans =\n        {{145.,  50., 1},\n         {1.0,   26., 1},\n         {148.,  50., 82.}};\n\n    Matrix<double> answer(ans, 0.);\n\n    mxm(m3,\n        grb::NoMask(), grb::Plus<double>(),\n        grb::ArithmeticSemiring<double>(),\n        mat, mat);\n\n    BOOST_CHECK_EQUAL(m3, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_AB_ACdup)\n{\n    grb::Matrix<double> C(A_sparse_3x3, 0.);\n    grb::Matrix<double> B(A_sparse_3x3, 0.);\n\n    // A_sparse_3x3 * A_sparse_3x3 + A_sparse_3x3\n    static std::vector<std::vector<double> > ans =\n        {{156.,  56., 0},\n         {0.0,   20., 0},\n         {154.,  49., 90.}};\n    Matrix<double> answer(ans, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, B);\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_AB_BCdup)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.);\n    grb::Matrix<double> C(A_sparse_3x3, 0.);\n\n    // A_sparse_3x3 * A_sparse_3x3 + A_sparse_3x3\n    static std::vector<std::vector<double> > ans =\n        {{156.,  56., 0},\n         {0.0,   20., 0},\n         {154.,  49., 90.}};\n    Matrix<double> answer(ans, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n// ****************************************************************************\n// Mask_NoAccum\n// ****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             Ones, NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, A);\n\n    C = Ones;\n    grb::mxm(C,\n             A, NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             Ones, NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, A);\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ABM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, Ones);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_Merge_full_mask)\n{\n    IndexArrayType i_A      =  {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_A      =  {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_A = {12, 7, 3, 4, 5, 6, 7, 8, 9};\n    Matrix<double, DirectedMatrixTag> A(3, 3);\n    A.build(i_A, j_A, v_A);\n\n    IndexArrayType i_B      = {0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_B      = {0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 3};\n    std::vector<double> v_B = {5, 8, 1, 2, 6, 7, 3, 4, 5, 9, 1};\n    Matrix<double, DirectedMatrixTag> B(3, 4);\n    B.build(i_B, j_B, v_B);\n\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    IndexArrayType i_answer = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_answer = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3};\n    std::vector<double> v_answer = {114, 160, 60, 27, 74, 97,\n                                    73, 14, 119, 157, 112, 23};\n    Matrix<double, DirectedMatrixTag> answer(3, 4);\n    answer.build(i_answer, j_answer, v_answer);\n\n    Matrix<unsigned int, DirectedMatrixTag> mask(3,4);\n    std::vector<unsigned int> v_mask(i_answer.size(), 1);\n    mask.build(i_answer, j_answer, v_mask);\n\n    mxm(result,\n        mask, grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        A, B);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_mask_not_full)\n{\n    IndexArrayType i_A    = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_A    = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_A = {12, 7, 3, 4, 5, 6, 7, 8, 9};\n    Matrix<double, DirectedMatrixTag> A(3, 3);\n    A.build(i_A, j_A, v_A);\n\n    IndexArrayType i_B    = {0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_B    = {0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 3};\n    std::vector<double> v_B = {5, 8, 1, 2, 6, 7, 3, 4, 5, 9, 1};\n    Matrix<double, DirectedMatrixTag> B(3, 4);\n    B.build(i_B, j_B, v_B);\n\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    IndexArrayType i_answer = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_answer = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2};\n    std::vector<double> v_answer = {114, 160, 60, 27, 74, 97,\n                                    73, 14, 119, 157, 112};\n    Matrix<double, DirectedMatrixTag> answer(3, 4);\n    answer.build(i_answer, j_answer, v_answer);\n\n    Matrix<unsigned int, DirectedMatrixTag> mask(3,4);\n    std::vector<unsigned int> v_mask(i_answer.size(), 1);\n    mask.build(i_answer, j_answer, v_mask);\n\n    mxm(result,\n        mask, grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        A, B);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_Merge_Cones_Mlower_stored_zero)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(Lower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0},\n                                               {1, 0, 1},\n                                               {0, 0, 1}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_ABdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_ACdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_BCdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_MCdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\n// Mask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             A, Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             Ones, Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABMempty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0},\n                                               {1, 0, 1},\n                                               {0, 0, 1}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 1, 8},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 8},\n                                                     {1, 1, 1},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_ABdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_ACdup)\n{\n\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_BCdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_MCdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  0,  0,  0},\n                                             {4, 10,  0,  0},\n                                             {3, 11, 23,  0},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_Replace_lower_mask_result_ones)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(LowerMask_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_Replace_bool_masked_result_ones)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<bool> M(LowerBool_3x4, false);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_Replace_mask_stored_zero_result_ones)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(Lower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B,\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_Merge_Cones_Mlower)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > M_3x4 = {{1, 0, 0, 0},\n                                                      {1, 1, 0, 0},\n                                                      {1, 1, 1, 0}};\n    grb::Matrix<double> M(M_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompMask_NoAccum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_AB)\n{\n\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > Not_A_sparse_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_sparse_3x3, 0.0);\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, A);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotA), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, A);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_AB_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> Identity(Identity_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, Ones);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Ones);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_AB_Merge_Cones_Mlower_stored_zero)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             complement(M),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_AB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_AB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_AB_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0},\n                                               {1, 0, 1},\n                                               {0, 0, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x3, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_AB_ABdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_AB_ACdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_AB_BCdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_AB_Replace_ABdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    static std::vector<std::vector<double> > Not_A_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_3x3, 0.0);\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotA), Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Empty), Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> MNotLower(NotLowerBool_3x3, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_ABdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_ACdup)\n{\n\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_BCdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_MCdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_Replace_Cones_Mnlower)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B,\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_Replace_Mstored_zero)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n\n    M.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B,\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_Merge)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_Merge_Mstored_zero)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_Merge_ABdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// Structure tests\n//****************************************************************************\n\n\n// ****************************************************************************\n// StructMask_NoAccum\n// ****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_AB)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  0},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, A);\n    Ones.setElement(0, 0, 1.);\n\n    A.setElement(0, 2, 0.);\n    AFilled.setElement(0, 2, 0.);\n    C = Ones;\n    grb::mxm(C,\n             structure(A), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity);\n\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    MLower.setElement(2, 0, 0.);\n    grb::mxm(C,\n             structure(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    MNotLower.setElement(0, 2, 0.);\n    grb::mxm(C,\n             structure(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, A);\n    Ones.setElement(0, 0, 1.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    MLower.setElement(2, 0, 1.);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    MNotLower.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ABM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n    M.setElement(2, 0, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, Ones);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_AB_Merge_full_mask)\n{\n    IndexArrayType i_A      =  {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_A      =  {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_A = {12, 7, 3, 4, 5, 6, 7, 8, 9};\n    Matrix<double, DirectedMatrixTag> A(3, 3);\n    A.build(i_A, j_A, v_A);\n\n    IndexArrayType i_B      = {0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_B      = {0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 3};\n    std::vector<double> v_B = {5, 8, 1, 2, 6, 7, 3, 4, 5, 9, 1};\n    Matrix<double, DirectedMatrixTag> B(3, 4);\n    B.build(i_B, j_B, v_B);\n\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    IndexArrayType i_answer = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_answer = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3};\n    std::vector<double> v_answer = {114, 160, 60, 27, 74, 97,\n                                    73, 14, 119, 157, 112, 23};\n    Matrix<double, DirectedMatrixTag> answer(3, 4);\n    answer.build(i_answer, j_answer, v_answer);\n\n    Matrix<unsigned int, DirectedMatrixTag> mask(3,4);\n    std::vector<unsigned int> v_mask(i_answer.size(), 0);\n    mask.build(i_answer, j_answer, v_mask);\n\n    mxm(result,\n        structure(mask), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        A, B);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_AB_mask_not_full)\n{\n    IndexArrayType i_A    = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_A    = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_A = {12, 7, 3, 4, 5, 6, 7, 8, 9};\n    Matrix<double, DirectedMatrixTag> A(3, 3);\n    A.build(i_A, j_A, v_A);\n\n    IndexArrayType i_B    = {0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_B    = {0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 3};\n    std::vector<double> v_B = {5, 8, 1, 2, 6, 7, 3, 4, 5, 9, 1};\n    Matrix<double, DirectedMatrixTag> B(3, 4);\n    B.build(i_B, j_B, v_B);\n\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    IndexArrayType i_answer = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_answer = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2};\n    std::vector<double> v_answer = {114, 160, 60, 27, 74, 97,\n                                    73, 14, 119, 157, 112};\n    Matrix<double, DirectedMatrixTag> answer(3, 4);\n    answer.build(i_answer, j_answer, v_answer);\n\n    Matrix<unsigned int, DirectedMatrixTag> mask(3,4);\n    std::vector<unsigned int> v_mask(i_answer.size(), 0);\n    mask.build(i_answer, j_answer, v_mask);\n\n    mxm(result,\n        structure(mask), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        A, B);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_AB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_AB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_AB_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0},\n                                               {1, 0, 1},\n                                               {0, 0, 1}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_AB_ABdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(0, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_AB_ACdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(0, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_AB_BCdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(0, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_AB_MCdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    C.setElement(2, 0, 0.);\n    grb::mxm(C,\n             structure(C),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    C.setElement(2, 0, 0.);\n    grb::mxm(C,\n             structure(C),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\n// StructMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_AB)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mfull vs Mlower\n\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n    Ones.setElement(0, 0, 1.);\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    MLower.setElement(2, 0, 0.);\n    grb::mxm(C,\n             structure(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    MNotLower.setElement(0, 2, 0.);\n    grb::mxm(C,\n             structure(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mfull vs Mlower\n\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n    Ones.setElement(0, 0, 1.);\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ABMempty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n    M.setElement(2, 0, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_AB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_AB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_AB_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0},\n                                               {1, 0, 1},\n                                               {0, 0, 1}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 1, 8},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 8},\n                                                     {1, 1, 1},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_AB_ABdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(0, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_AB_ACdup)\n{\n\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(0, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_AB_BCdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(0, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_AB_MCdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  0,  0,  0},\n                                             {4, 10,  0,  0},\n                                             {2, 11, 23,  0},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    C.setElement(2, 0, 0.);\n    grb::mxm(C,\n             structure(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {2, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    C.setElement(2, 0, 0.);\n    grb::mxm(C,\n             structure(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_AB_Replace_lower_mask_result_ones)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(LowerMask_3x4, 0.);\n    M.setElement(2, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             structure(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_AB_Replace_bool_masked_result_ones)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<bool> M(LowerBool_3x4, false);\n    M.setElement(2, 0, false);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             structure(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_AB_Merge_Cones_Mlower)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > M_3x4 = {{1, 0, 0, 0},\n                                                      {1, 1, 0, 0},\n                                                      {1, 1, 1, 0}};\n    grb::Matrix<double> M(M_3x4, 0.);\n    M.setElement(2, 0, false);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             structure(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompStructMask_NoAccum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_AB)\n{\n\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    MLower.setElement(2, 0, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n    MNotLower.setElement(0, 2, 0.);\n\n    static std::vector<std::vector<double> > Not_A_sparse_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_sparse_3x3, 0.0);\n    NotA.setElement(1, 0, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity);\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, A);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotA)), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n    Ones.setElement(0, 0, 1.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, A);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    MLower.setElement(2, 0, 1.);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    MLower.setElement(2, 0, 0.);\n    grb::mxm(C,\n             complement(structure(MLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    MNotLower.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_AB_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> Identity(Identity_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n    M.setElement(2, 0, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n    mUpper.setElement(0, 2, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, Ones);\n    mUpper.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    mUpper.setElement(0, 2, 0.);\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty);\n    mUpper.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Empty, Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Ones);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_AB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_AB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_AB_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0},\n                                               {1, 0, 1},\n                                               {0, 0, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x3, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Lower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Lower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_AB_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_AB_ACdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), C, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_AB_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_AB_Replace_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n    M.setElement(0, 1, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompStructMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_AB)\n{\n    grb::Matrix<double> A(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    MLower.setElement(2, 0, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n    MNotLower.setElement(0, 2, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    static std::vector<std::vector<double> > Not_A_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_3x3, 0.0);\n    NotA.setElement(0, 2, 0.);\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity);\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotA)), Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Empty)), Plus<double>(),\n             ArithmeticSemiring<double>(), A, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Identity, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ABM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> MNotLower(NotLowerBool_3x3, false);\n    MNotLower.setElement(0, 2, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, Ones);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Empty);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    Ones.setElement(0, 2, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Ones);\n    Ones.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Empty, Ones, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    Ones.setElement(0, 2, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), Ones, Empty, REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_AB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 6},\n                                               {0, 0, 0},\n                                               {4, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 0, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x4, 0.);\n    MNotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_AB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 6},\n                                               {1, 0, 9},\n                                               {4, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0, 1},\n                                               {1, 0, 1, 1},\n                                               {0, 0, 0, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B, REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_AB_ABdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_AB_ACdup)\n{\n\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), C, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_AB_BCdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, C);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, C,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_AB_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  0,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {99, 6, 21, 25}};\n    grb::Matrix<double> answer(ans, 99.);\n\n    C = NotLower;\n    NotLower.setElement(0, 1, 0.);\n    grb::mxm(C,\n             complement(structure(C)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n    NotLower.setElement(0, 1, 1.);\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(structure(C)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_AB_Replace_Cones_Mnlower)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B,\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_AB_Merge)\n{\n    grb::Matrix<double> A(A_dense_3x3, 0.);\n    grb::Matrix<double> B(B_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), A, B);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_AB_Merge_ABdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n    M.setElement(0, 1, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d9621218b7a48f53d2f73f2c7fdeee234e47aa75", "size": 166829, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_mxm_AB.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_mxm_AB.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_mxm_AB.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 33.292556376, "max_line_length": 82, "alphanum_fraction": 0.4397317013, "num_tokens": 47037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5411622015995773}}
{"text": "/**\n * @author Eric Cousineau <eacousineau@gmail.com>, member of Dr. Aaron\n * Ames's AMBER Lab\n */\n#include <Eigen/Dense>\n\n// See test_runtime_config for more information\n\nnamespace test_runtime_config_clean_eigen\n{\n\nvoid resize_matrix()\n{\n    Eigen::MatrixXd blank;\n    blank.resize(5, 5);\n}\n\n}\n", "meta": {"hexsha": "ef9f623b05713cd3757c08ba5ae2affd344cd10a", "size": 296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_utilities/test/test_runtime_config_clean_eigen.cpp", "max_stars_repo_name": "noelc-s/amber_developer_stack", "max_stars_repo_head_hexsha": "dda28b1b79f8df6eb56c41a0e1b5c1d167631176", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-18T04:36:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T04:36:22.000Z", "max_issues_repo_path": "eigen_utilities/test/test_runtime_config_clean_eigen.cpp", "max_issues_repo_name": "noelc-s/amber_developer_stack", "max_issues_repo_head_hexsha": "dda28b1b79f8df6eb56c41a0e1b5c1d167631176", "max_issues_repo_licenses": ["MIT"], "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_utilities/test/test_runtime_config_clean_eigen.cpp", "max_forks_repo_name": "noelc-s/amber_developer_stack", "max_forks_repo_head_hexsha": "dda28b1b79f8df6eb56c41a0e1b5c1d167631176", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-04T21:22:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T21:22:48.000Z", "avg_line_length": 15.5789473684, "max_line_length": 70, "alphanum_fraction": 0.7128378378, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5411621974094996}}
{"text": "/*\n *  Copyright (c) 2008--2011, Universitaet Bremen\n *  All rights reserved.\n *\n *  Author: Christoph Hertzberg <chtz@informatik.uni-bremen.de>\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 Universitaet Bremen 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 * @file mtk/types/SOn.hpp\n * @brief Standard Orthogonal Groups i.e.\\ rotatation groups.\n */\n#ifndef SON_H_\n#define SON_H_\n\n\n#include \"vect.hpp\"\n#include \"../src/mtkmath.hpp\"\n\n#include <Eigen/Geometry>\n\nnamespace MTK {\n\n\n/**\n * Two-dimensional orientations represented as scalar.\n * There is no guarantee that the representing scalar is within any interval,\n * but the result of boxminus will always have magnitude @f$\\le\\pi @f$.\n */\ntemplate<class _scalar = double, int Options = Eigen::AutoAlign>\nstruct SO2 : public Eigen::Rotation2D<_scalar> {\n\tenum {DOF = 1, DIM = 2};\n\t\n\ttypedef _scalar scalar;\n\ttypedef Eigen::Rotation2D<scalar> base;\n\ttypedef vect<DIM, scalar, Options> vect_type;\n\t\n\t//using base::operator=;\n\t\n\t//! Construct from angle\n\tSO2(const scalar& angle = 0) : base(angle) {\t}\n\t\n\t//! Construct from Eigen::Rotation2D\n\tSO2(const base& src) : base(src) {}\n\t\n\t/**\n\t * Construct from 2D vector.\n\t * Resulting orientation will rotate the first unit vector to point to vec.\n\t */\n\tSO2(const vect_type &vec) : base(atan2(vec[1], vec[0])) {};\n\t\n\t\n\t//! Calculate @c this->inverse() * @c r\n\tSO2 operator%(const base &r) const {\n\t\treturn base::inverse() * r;\n\t}\n\n\t//! Calculate @c this->inverse() * @c r\n\ttemplate<class Derived>\n\tvect_type operator%(const Eigen::MatrixBase<Derived> &vec) const {\n\t\treturn base::inverse() * vec;\n\t}\n\t\n\t//! Calculate @c *this * @c r.inverse()\n\tSO2 operator/(const SO2 &r) const {\n\t\treturn *this * r.inverse();\n\t}\n\t\n\t//! Gets the angle as scalar.\n\toperator scalar() const {\n\t\treturn base::angle();\n\t}\n\t\n\t//! @name Manifold requirements\n\t//{\n\tvoid boxplus(MTK::vectview<const scalar, DOF> vec, scalar scale=1) {\n\t\tbase::angle() += scale * vec[0];\n\t}\n\tvoid boxminus(MTK::vectview<scalar, DOF> res, const SO2<scalar>& other) const {\n\t\tres[0] = MTK::normalize(base::angle() - other.angle(), scalar(MTK::pi));\n\t}\n\t//}\n\t\n\tfriend std::istream& operator>>(std::istream &is, SO2<scalar>& ang){\n\t\treturn is >> ang.angle();\n\t}\n\n};\n\n\n/**\n * Three-dimensional orientations represented as Quaternion.\n * It is assumed that the internal Quaternion always stays normalized,\n * should this not be the case, call inherited member function @c normalize().\n */\ntemplate<class _scalar = double, int Options = Eigen::AutoAlign>\nstruct SO3 : public Eigen::Quaternion<_scalar, Options> {\n\tenum {DOF = 3, DIM = 3};\n\ttypedef _scalar scalar_type;\n\ttypedef Eigen::Quaternion<scalar_type, Options> base;\n\ttypedef Eigen::Quaternion<scalar_type> Quaternion;\n\ttypedef vect<DIM, scalar_type, Options> vectorized_type;\n\t\n\t//using base::operator=;\n\t\n\t//! Calculate @c this->inverse() * @c r\n\ttemplate<class OtherDerived> EIGEN_STRONG_INLINE \n\tQuaternion operator%(const Eigen::QuaternionBase<OtherDerived> &r) const {\n\t\treturn base::conjugate() * r;\n\t}\n\t\n\t//! Calculate @c this->inverse() * @c r\n\ttemplate<class Derived>\n\tvectorized_type operator%(const Eigen::MatrixBase<Derived> &vec) const {\n\t\treturn base::conjugate() * vec;\n\t}\n\t\n\t//! Calculate @c this * @c r.conjugate()\n\ttemplate<class OtherDerived> EIGEN_STRONG_INLINE \n\tQuaternion operator/(const Eigen::QuaternionBase<OtherDerived> &r) const {\n\t\treturn *this * r.conjugate();\n\t}\n\t\n\t/**\n\t * Construct from real part and three imaginary parts.\n\t * Quaternion is normalized after construction.\n\t */\n\tSO3(const scalar_type& w, const scalar_type& x, const scalar_type& y, const scalar_type& z) : base(w, x, y, z) {\n\t\tbase::normalize();\n\t}\n\t\n\t/**\n\t * Construct from Eigen::Quaternion.\n\t * @note Non-normalized input may result result in spurious behavior.\n\t */\n\tSO3(const base& src = base::Identity()) : base(src) {}\n\t\n\t/**\n\t * Construct from rotation matrix.\n\t * @note Invalid rotation matrices may lead to spurious behavior.\n\t */\n\ttemplate<class Derived>\n\tSO3(const Eigen::MatrixBase<Derived>& matrix) : base(matrix) {}\n\t\n\t/**\n\t * Construct from arbitrary rotation type.\n\t * @note Invalid rotation matrices may lead to spurious behavior.\n\t */\n\ttemplate<class Derived>\n\tSO3(const Eigen::RotationBase<Derived, 3>& rotation) : base(rotation.derived()) {}\n\t\n\t//! @name Manifold requirements\n\t//{\n\tSO3 operator+(const vectorized_type& vec) const {\n\t\tSO3 delta = exp(vec);\n\t\treturn delta * *this;\n\t}\n\n    void operator+=(const vectorized_type& vec) {\n        *this = *this + vec;\n    }\n\n\tauto operator-(const SO3<scalar_type>& other) const {\n\t\treturn SO3::log(*this * other.conjugate());\n\t}\n\t//}\n\t\n\tfriend std::ostream& operator<<(std::ostream &os, const SO3<scalar_type, Options>& q){\n\t\treturn os << q.coeffs().transpose() << \" \";\n\t}\n\tfriend std::istream& operator>>(std::istream &is, SO3<scalar_type, Options>& q){\n\t\tvect<4,scalar_type> coeffs;\n\t\tis >> coeffs;\n\t\tq.coeffs() = coeffs.normalized();\n\t\treturn is;\n\t}\n\t\n\t//! @name Helper functions\n\t//{\n\t/**\n\t * Calculate the exponential map. In matrix terms this would correspond \n\t * to the Rodrigues formula.\n\t */\n\t// FIXME vectview<> can't be constructed from every MatrixBase<>, use const Vector3x& as workaround\n//\tstatic SO3 exp(MTK::vectview<const scalar, 3> dvec, scalar scale = 1){\n\tstatic SO3 exp(const Eigen::Matrix<scalar_type, 3, 1>& dvec, scalar_type scale = 1){\n\t\tSO3 res;\n\t\tres.w() = MTK::exp<scalar_type, 3>(res.vec(), dvec, scalar_type(scale / 2));\n\t\treturn res;\n\t}\n\t/**\n\t * Calculate the inverse of @c exp.\n\t * Only guarantees that <code>exp(log(x)) == x </code>\n\t */\n\tstatic typename base::Vector3 log(const SO3 &orient){\n\t\ttypename base::Vector3 res;\n\t\tMTK::log<scalar_type, 3>(res, orient.w(), orient.vec(), scalar_type(2), true);\n\t\treturn res;\n\t}\n\t//}\n};\n\nnamespace internal {\ntemplate<class Scalar, int Options>\nstruct UnalignedType<SO2<Scalar, Options > >{\n\ttypedef SO2<Scalar, Options | Eigen::DontAlign> type;\n};\n\ntemplate<class Scalar, int Options>\nstruct UnalignedType<SO3<Scalar, Options > >{\n\ttypedef SO3<Scalar, Options | Eigen::DontAlign> type;\n};\n\n}  // namespace internal\n\n\n}  // namespace MTK\n\n#endif /*SON_H_*/\n\n", "meta": {"hexsha": "8048b6d02f65aa7e91c291643f6dbdbe32b96fb3", "size": 7548, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/slam_and_orientation/mtk/types/SOn.hpp", "max_stars_repo_name": "mfkiwl/ADEKF", "max_stars_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T11:04:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T01:43:07.000Z", "max_issues_repo_path": "examples/slam_and_orientation/mtk/types/SOn.hpp", "max_issues_repo_name": "mfkiwl/ADEKF", "max_issues_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_issues_repo_licenses": ["MIT"], "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/slam_and_orientation/mtk/types/SOn.hpp", "max_forks_repo_name": "mfkiwl/ADEKF", "max_forks_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-04-26T09:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T01:43:10.000Z", "avg_line_length": 30.6829268293, "max_line_length": 113, "alphanum_fraction": 0.6963434022, "num_tokens": 1976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5411108167566047}}
{"text": "#include <Eigen/Core>\r\n#include <iostream>\r\n\r\nusing namespace Eigen;\r\n\r\n// [circulant_func]\r\ntemplate<class ArgType>\r\nclass circulant_functor {\r\n  const ArgType &m_vec;\r\npublic:\r\n  circulant_functor(const ArgType& arg) : m_vec(arg) {}\r\n\r\n  const typename ArgType::Scalar& operator() (Index row, Index col) const {\r\n    Index index = row - col;\r\n    if (index < 0) index += m_vec.size();\r\n    return m_vec(index);\r\n  }\r\n};\r\n// [circulant_func]\r\n\r\n// [square]\r\ntemplate<class ArgType>\r\nstruct circulant_helper {\r\n  typedef Matrix<typename ArgType::Scalar,\r\n                 ArgType::SizeAtCompileTime,\r\n                 ArgType::SizeAtCompileTime,\r\n                 ColMajor,\r\n                 ArgType::MaxSizeAtCompileTime,\r\n                 ArgType::MaxSizeAtCompileTime> MatrixType;\r\n};\r\n// [square]\r\n\r\n// [makeCirculant]\r\ntemplate <class ArgType>\r\nCwiseNullaryOp<circulant_functor<ArgType>, typename circulant_helper<ArgType>::MatrixType>\r\nmakeCirculant(const Eigen::MatrixBase<ArgType>& arg)\r\n{\r\n  typedef typename circulant_helper<ArgType>::MatrixType MatrixType;\r\n  return MatrixType::NullaryExpr(arg.size(), arg.size(), circulant_functor<ArgType>(arg.derived()));\r\n}\r\n// [makeCirculant]\r\n\r\n// [main]\r\nint main()\r\n{\r\n  Eigen::VectorXd vec(4);\r\n  vec << 1, 2, 4, 8;\r\n  Eigen::MatrixXd mat;\r\n  mat = makeCirculant(vec);\r\n  std::cout << mat << std::endl;\r\n}\r\n// [main]\r\n", "meta": {"hexsha": "f633af217cf721f0f116bee8c6503f0f455edc9c", "size": 1372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/make_circulant2.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/make_circulant2.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/make_circulant2.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 25.8867924528, "max_line_length": 101, "alphanum_fraction": 0.6501457726, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5411108086705307}}
{"text": "#include \"gtest/gtest.h\"\n\n#include <Eigen/Geometry>\n\n#include \"Predicates.h\"\n#include \"Utilities.h\"\n\nusing namespace FluidSim3D;\n\n//\n// Orient2d tests\n//\n\nTEST(PREDICATES_TEST, ORIENT_2D_ZERO_DET_TEST)\n{\n\texactinit();\n\n\tint testCases = 1000;\n\tfor (int testIndex = 0; testIndex < testCases; ++testIndex)\n\t{\n\t\tVec2d startPoint = 1e5 * Vec2d::Random();\n\t\tVec2d endPoint = 1e5 * Vec2d::Random();\n\n\t\tVec2d testPoint = startPoint;\n\t\t\n\t\tEXPECT_EQ(orient2d(&startPoint[0], &endPoint[0], &testPoint[0]), 0.);\n\n\t\ttestPoint = endPoint;\n\t\tEXPECT_EQ(orient2d(&startPoint[0], &endPoint[0], &testPoint[0]), 0.);\n\t}\n}\n\nTEST(PREDICATES_TEST, ORIENT_2D_POSITIVE_DET_TEST)\n{\n\texactinit();\n\n\tint testCases = 1000;\n\tfor (int testIndex = 0; testIndex < testCases; ++testIndex)\n\t{\n\t\tVec2d startPoint = 1e5 * Vec2d::Random();\n\t\tVec2d endPoint = 1e5 * Vec2d::Random();\n\n\t\tif (startPoint == endPoint)\n\t\t\tcontinue;\n\n\t\tVec2d vec = endPoint - startPoint;\n\t\tVec2d norm(-vec[1], vec[0]);\n\n\t\tdouble offsetScalar = 1e-12;\n\t\tVec2d testPoint = startPoint + offsetScalar * norm;\n\n\t\tEXPECT_GT(orient2d(&startPoint[0], &endPoint[0], &testPoint[0]), 0.);\n\n\t\ttestPoint = endPoint + offsetScalar * norm;\n\t\tEXPECT_GT(orient2d(&startPoint[0], &endPoint[0], &testPoint[0]), 0.);\n\n\t\ttestPoint = .5 * (startPoint + endPoint) + offsetScalar * norm;\n\t\tEXPECT_GT(orient2d(&startPoint[0], &endPoint[0], &testPoint[0]), 0.);\n\t}\n}\n\nTEST(PREDICATES_TEST, ORIENT_2D_NEGATIVE_DET_TEST)\n{\n\texactinit();\n\n\tint testCases = 1000;\n\tfor (int testIndex = 0; testIndex < testCases; ++testIndex)\n\t{\n\t\tVec2d startPoint = 1e5 * Vec2d::Random();\n\t\tVec2d endPoint = 1e5 * Vec2d::Random();\n\n\t\tif (startPoint == endPoint)\n\t\t\tcontinue;\n\n\t\tVec2d vec = endPoint - startPoint;\n\t\tVec2d norm(-vec[1], vec[0]);\n\n\t\tdouble offsetScalar = -1e-12;\n\t\tVec2d testPoint = startPoint + offsetScalar * norm;\n\n\t\tEXPECT_LT(orient2d(&startPoint[0], &endPoint[0], &testPoint[0]), 0.);\n\n\t\ttestPoint = endPoint + offsetScalar * norm;\n\t\tEXPECT_LT(orient2d(&startPoint[0], &endPoint[0], &testPoint[0]), 0.);\n\n\t\ttestPoint = .5 * (startPoint + endPoint) + offsetScalar * norm;\n\t\tEXPECT_LT(orient2d(&startPoint[0], &endPoint[0], &testPoint[0]), 0.);\n\t}\n}\n\n//\n// Orient3d tests\n//\n\nTEST(PREDICATES_TEST, ORIENT_3D_ZERO_DET_TEST)\n{\n\texactinit();\n\n\tint testCases = 1000;\n\tfor (int testIndex = 0; testIndex < testCases; ++testIndex)\n\t{\n\t\tVec3d v0 = 1e5 * Vec3d::Random();\n\t\tVec3d v1 = 1e5 * Vec3d::Random();\n        Vec3d v2 = 1e5 * Vec3d::Random();\n\n\t\tif (v0 == v1 || v1 == v2 || v2 == v0)\n\t\t\tcontinue;\n\n\t\tVec3d testPoint = v0;\n\t\tEXPECT_EQ(orient3d(v0.data(), v1.data(), v2.data(), testPoint.data()), 0.);\n\n        testPoint = v1;\n        EXPECT_EQ(orient3d(v0.data(), v1.data(), v2.data(), testPoint.data()), 0.);\n\n        testPoint = v2;\n        EXPECT_EQ(orient3d(v0.data(), v1.data(), v2.data(), testPoint.data()), 0.);\n\t}\n}\n\nTEST(PREDICATES_TEST, ORIENT_3D_POSITIVE_DET_TEST)\n{\n\texactinit();\n\n\tint testCases = 1000;\n\tfor (int testIndex = 0; testIndex < testCases; ++testIndex)\n\t{\n\t\tVec3d v0 = 1e5 * Vec3d::Random();\n\t\tVec3d v1 = 1e5 * Vec3d::Random();\n        Vec3d v2 = 1e5 * Vec3d::Random();\n\n\t\tif (v0 == v1 || v1 == v2 || v2 == v0)\n\t\t\tcontinue;\n\n        Vec3d vec0 = v1 - v0;\n        Vec3d vec1 = v2 - v0;\n        Vec3d norm = vec0.cross(vec1).normalized();\n\n\t\tdouble offsetScalar = 1e-10;\n\n\t\tVec3d testPoint = v0 + offsetScalar * norm;\n\t\tEXPECT_LT(orient3d(v0.data(), v1.data(), v2.data(), testPoint.data()), 0.);\n\n\t\ttestPoint = v1 + offsetScalar * norm;\n\t\tEXPECT_LT(orient3d(v0.data(), v1.data(), v2.data(), testPoint.data()), 0.);\n\n        testPoint = v2 + offsetScalar * norm;\n\t\tEXPECT_LT(orient3d(v0.data(), v1.data(), v2.data(), testPoint.data()), 0.);\n\n\t\ttestPoint = (1. / 3.) * (v0 + v1 + v2) + offsetScalar * norm;\n\t\tEXPECT_LT(orient3d(v0.data(), v1.data(), v2.data(), testPoint.data()), 0.);\n\t}\n}\n\nTEST(PREDICATES_TEST, ORIENT_3D_NEGATIVE_DET_TEST)\n{\n\texactinit();\n\n\tint testCases = 1000;\n\tfor (int testIndex = 0; testIndex < testCases; ++testIndex)\n\t{\n\t\tVec3d v0 = 1e5 * Vec3d::Random();\n\t\tVec3d v1 = 1e5 * Vec3d::Random();\n        Vec3d v2 = 1e5 * Vec3d::Random();\n\n\t\tif (v0 == v1 || v1 == v2 || v2 == v0)\n\t\t\tcontinue;\n\n        Vec3d vec0 = v1 - v0;\n        Vec3d vec1 = v2 - v0;\n        Vec3d norm = vec0.cross(vec1).normalized();\n\n\t\tdouble offsetScalar = 1e-10;\n\n\t\tVec3d testPoint = v0 - offsetScalar * norm;\n\t\tEXPECT_GT(orient3d(v0.data(), v1.data(), v2.data(), testPoint.data()), 0.);\n\n\t\ttestPoint = v1 - offsetScalar * norm;\n\t\tEXPECT_GT(orient3d(v0.data(), v1.data(), v2.data(), testPoint.data()), 0.);\n\n        testPoint = v2 - offsetScalar * norm;\n\t\tEXPECT_GT(orient3d(v0.data(), v1.data(), v2.data(), testPoint.data()), 0.);\n\n\t\ttestPoint = (1. / 3.) * (v0 + v1 + v2) - offsetScalar * norm;\n\t\tEXPECT_GT(orient3d(v0.data(), v1.data(), v2.data(), testPoint.data()), 0.);\n\t}\n}\n\nTEST(PREDICATES_TEST, EXACT_TRIANGLE_INTERSECTION_CROSSING_TRIANGLE_TEST)\n{\n\texactinit();\n\n\tint testCases = 100;\n\tint offsetCases = 100;\n\tfor (int testIndex = 0; testIndex < testCases; ++testIndex)\n\t{\n\t\tVec3d rayStart = 1e5 * Vec3d::Random();\n\n\t\tfor (auto axis : { Axis::XAXIS, Axis::YAXIS, Axis::ZAXIS })\n\t\t{\n            int axisIndex = axis == Axis::XAXIS ? 0 : axis == Axis::YAXIS ? 1 : 2;\n\n\t\t\tVec3d offset = 1e-10 * rayStart.cwiseAbs();\n\n\t\t\tfor (int offsetIndex = 0; offsetIndex < offsetCases; ++offsetIndex)\n\t\t\t{\n\t\t\t\tVec3d v0 = rayStart;\n                v0[axisIndex] += offset[axisIndex] + std::fabs(1e5 * double(std::rand()) / double(RAND_MAX));\n\n\t\t\t\tVec3d v1 = v0;\n                v1[(axisIndex + 1) % 3] += offset[(axisIndex + 1) % 3] + std::fabs(1e5 * double(std::rand()) / double(RAND_MAX));\n\n\t\t\t\tVec3d v2 = v0;\n                v2[(axisIndex + 1) % 3] -= offset[(axisIndex + 1) % 3] + std::fabs(1e5 * double(std::rand()) / double(RAND_MAX));\n\n                v0[(axisIndex + 2) % 3] += offset[(axisIndex + 2) % 3] + std::fabs(1e5 * double(std::rand()) / double(RAND_MAX));\n                v1[(axisIndex + 2) % 3] -= offset[(axisIndex + 2) % 3] + std::fabs(1e5 * double(std::rand()) / double(RAND_MAX));\n                v2[(axisIndex + 2) % 3] -= offset[(axisIndex + 2) % 3] + std::fabs(1e5 * double(std::rand()) / double(RAND_MAX));\n\n\t\t\t\tEXPECT_EQ(exactTriIntersect(rayStart, v0, v1, v2, axis), IntersectionLabels::YES);\n\t\n\t\t\t\tstd::swap(v0, v1);\n\n\t\t\t\tEXPECT_EQ(exactTriIntersect(rayStart, v0, v1, v2, axis), IntersectionLabels::YES);\n\t\t\t}\n\t\t}\n\t}\n}\n//\n//TEST(PREDICATES_TEST, EXACT_TRIANGLE_INTERSECTION_CROSSING_POINT_TEST)\n//{\n//\texactinit();\n//\n//\tint testCases = 1000;\n//\tint offsetCases = 1000;\n//\tfor (int testIndex = 0; testIndex < testCases; ++testIndex)\n//\t{\n//\t\tVec3d rayStart = 1e5 * Vec2d::Random();\n//\n//\t\tfor (auto axis : { Axis::XAXIS, Axis::YAXIS, Axis::ZAXIS })\n//\t\t{\n//\t\t\tdouble offset = 1e-12 * rayStart.cwiseAbs().maxCoeff();\n//\n//            int axisIndex = axis == Axis::XAXIS ? 0 : axis == Axis::YAXIS ? 1 : 2;\n//            \n//            Vec3d v0 = rayStart;\n//            v0[axisIndex] += offset + std::fabs(1e5 * double(std::rand()) / double(RAND_MAX));\n//\n//            \n//\n//\t\t\t// Start down-left, end up-right\n//\t\t\tfor (int offsetIndex = 0; offsetIndex < offsetCases; ++offsetIndex)\n//\t\t\t{\n//\t\t\t\tVec2d startPoint = rayStart;\n//\t\t\t\tVec2d endPoint = rayStart;\n//\n//\t\t\t\tstartPoint += Vec2d(-offset, -offset);\n//\t\t\t\tendPoint += Vec2d(offset, offset);\n//\n//\t\t\t\tEXPECT_EQ(exactTriIntersect(startPoint, endPoint, rayStart, axis), IntersectionLabels::ON);\n//\n//\t\t\t\tstd::swap(startPoint, endPoint);\n//\n//\t\t\t\tEXPECT_EQ(exactTriIntersect(startPoint, endPoint, rayStart, axis), IntersectionLabels::ON);\n//\t\t\t}\n//\n//\t\t\t// Start up-left, end down-right\n//\t\t\tfor (int offsetIndex = 0; offsetIndex < offsetCases; ++offsetIndex)\n//\t\t\t{\n//\t\t\t\tVec2d startPoint = rayStart;\n//\t\t\t\tVec2d endPoint = rayStart;\n//\n//\t\t\t\tstartPoint += Vec2d(-offset, offset);\n//\t\t\t\tendPoint += Vec2d(offset, -offset);\n//\n//\t\t\t\tEXPECT_EQ(exactEdgeIntersect(startPoint, endPoint, rayStart, axis), IntersectionLabels::ON);\n//\n//\t\t\t\tstd::swap(startPoint, endPoint);\n//\n//\t\t\t\tEXPECT_EQ(exactEdgeIntersect(startPoint, endPoint, rayStart, axis), IntersectionLabels::ON);\n//\t\t\t}\n//\n//\t\t\t// Start up, end down\n//\t\t\tfor (int offsetIndex = 0; offsetIndex < offsetCases; ++offsetIndex)\n//\t\t\t{\n//\t\t\t\tVec2d startPoint = rayStart;\n//\t\t\t\tVec2d endPoint = rayStart;\n//\n//\t\t\t\tif (axis == Axis::XAXIS)\n//\t\t\t\t{\n//\t\t\t\t\tstartPoint[1] += offset;\n//\t\t\t\t\tendPoint[1] -= offset;\n//\t\t\t\t}\n//\t\t\t\telse\n//\t\t\t\t{\n//\t\t\t\t\tstartPoint[0] += offset;\n//\t\t\t\t\tendPoint[0] -= offset;\n//\t\t\t\t}\n//\n//\t\t\t\tEXPECT_EQ(exactEdgeIntersect(startPoint, endPoint, rayStart, axis), IntersectionLabels::ON);\n//\n//\t\t\t\tstd::swap(startPoint, endPoint);\n//\n//\t\t\t\tEXPECT_EQ(exactEdgeIntersect(startPoint, endPoint, rayStart, axis), IntersectionLabels::ON);\n//\t\t\t}\n//\t\t}\n//\t}\n//}", "meta": {"hexsha": "993055781e09c0547a9d9bc66b2c306f3e30d11e", "size": 8716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "UnitTests/PredicatesTests.cpp", "max_stars_repo_name": "rgoldade/3dFluidSimulation", "max_stars_repo_head_hexsha": "680d84429e73e26671a52e1a725b1b76ec4ef0db", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T16:47:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-30T01:31:09.000Z", "max_issues_repo_path": "UnitTests/PredicatesTests.cpp", "max_issues_repo_name": "rgoldade/3dFluidSimulation", "max_issues_repo_head_hexsha": "680d84429e73e26671a52e1a725b1b76ec4ef0db", "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": "UnitTests/PredicatesTests.cpp", "max_forks_repo_name": "rgoldade/3dFluidSimulation", "max_forks_repo_head_hexsha": "680d84429e73e26671a52e1a725b1b76ec4ef0db", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3908794788, "max_line_length": 129, "alphanum_fraction": 0.6182882056, "num_tokens": 2946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5411108043334849}}
{"text": "#include <boost/numeric/conversion/cast.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include \"generalprimary.h\"\n#include \"primarynumber.h\"\n#include \"primaryvariable.h\"\n#include \"servicecontainer.h\"\n#include \"primaryfunction.h\"\n#include \"primaryexpression.h\"\n\n\n\ndouble compile_time_expression_structure::generalPrimary::value(double prime) const\n{\n    if (isFactorial)\n    {\n        if (prime<0.0)\n            throw std::logic_error(\"factorial applied to neg. value\");\n        using boost::numeric_cast;\n        unsigned int uif = numeric_cast<unsigned int>(prime);\n        double duif = numeric_cast<double>(uif);\n        if (prime-duif > std::numeric_limits<double>::min())\n            throw std::logic_error(\"factorial applied to not integer value\");\n        return boost::math::factorial<double>(uif);\n    }\n    else\n    {   \n        return prime;\n    }\n}\n\nstd::unique_ptr<compile_time_expression_structure::generalPrimary>\ncompile_time_expression_structure::generalPrimary::createPrimary\n(compile_time_expression_structure::serviceContainer& sc)\n{\n    Token t {sc.pop()};\n    std::unique_ptr<generalPrimary> gp{nullptr};\n    switch (t.kind) {\n        case TokenKind::number:\n        {\n            gp = std::make_unique<primaryNumber>(t.value);\n            break;\n        }\n        case TokenKind::variable:\n        {\n            // first find in constants\n            auto gcit {global_constants_id.find(t.name)};\n            if (gcit == cend(global_constants_id))\n            {\n                auto vit {global_variables_id.find(t.name)};\n                if (vit == cend(global_variables_id))\n                    throw std::logic_error(\"undefined variable literal \" + t.name);\n                // not constant\n                gp = std::make_unique<primaryVariable>(vit->second, sc);\n                break;\n            }\n            auto cit = global_constants.find(gcit->second);\n            if (cit == cend(global_constants))\n                throw std::logic_error(\"undefined symbolic literal\");\n            const double Value = cit->second;\n            gp = std::make_unique<primaryNumber>(Value);\n            break;\n        }\n        case TokenKind::function:\n        {\n            auto gfidIt {global_functions_id.find(t.name)};\n            if (gfidIt == cend(global_functions_id))\n                throw std::logic_error(\"unknown function name\");\n            gp = std::make_unique<primaryFunction>(gfidIt->second, sc);\n            break;\n        }\n        case TokenKind::bracket_left0:\n//        case TokenKind::bracket_left1:\n        {\n            gp = std::make_unique<primaryExpression>(sc);\n            //double d {expression(ist)};\n            Token t2 {sc.pop()};\n            if (t2.kind != TokenKind::bracket_right0)\n                throw std::logic_error(\"bracket_right expected\");\n            break;\n        }\n//        case TokenKind::bracket_left1:\n//        {\n//            double d {expression()};\n//            t = ts.pop();\n//            if (t.kind != TokenKind::bracket_right1)\n//                throw std::logic_error(\"bracket_right expected\");\n//            result = d;\n//            break;\n//        }\n        default:\n            throw std::logic_error(\"primary is expected\");\n    }\n\n    Token tp {sc.pop()};\n    if (tp.kind == TokenKind::factorial)\n    {\n        gp->setFactorial(true);\n    }\n    else {\n        sc.push(tp);\n    }\n    return gp;\n}\n\n\n", "meta": {"hexsha": "2c25be79f83215982400193e187f2575e14cfbbb", "size": 3396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ctexpression/generalprimary.cpp", "max_stars_repo_name": "vega1986/wcalc_expression_parser", "max_stars_repo_head_hexsha": "e9645a5fa8086c4108ce4dc1f3ad7da3cead6480", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ctexpression/generalprimary.cpp", "max_issues_repo_name": "vega1986/wcalc_expression_parser", "max_issues_repo_head_hexsha": "e9645a5fa8086c4108ce4dc1f3ad7da3cead6480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ctexpression/generalprimary.cpp", "max_forks_repo_name": "vega1986/wcalc_expression_parser", "max_forks_repo_head_hexsha": "e9645a5fa8086c4108ce4dc1f3ad7da3cead6480", "max_forks_repo_licenses": ["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.0377358491, "max_line_length": 83, "alphanum_fraction": 0.5736160188, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5410793229917973}}
{"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//\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::nsphere<point_type, double> circle_type;\ntypedef bg::model::box<point_type> box_type;\n\ntemplate <typename Geometry>\nvoid test_circle(std::string const& wkt_geometry, bool expected_within, bool expected_covered_by)\n{\n    circle_type circle(point_type(1.0, 1.0), 3.0);\n    //bg::assign(circle, 1.0, 1.0, 3.0);\n\n    Geometry geometry;\n    bg::read_wkt(wkt_geometry, geometry);\n\n    bool detected = bg::within(circle, geometry);\n\n    BOOST_CHECK_MESSAGE(detected == expected_within,\n        \"circle (1,1) with radius 3 within : \" << wkt_geometry\n        << \" -> Expected: \" << expected_within\n        << \" detected: \" << detected);\n\n    detected = bg::covered_by(circle, geometry);\n\n    BOOST_CHECK_MESSAGE(detected == expected_covered_by,\n        \"circle (1,1) with radius 3 covered_by : \" << wkt_geometry\n        << \" -> Expected: \" << expected_covered_by\n        << \" detected: \" << detected);\n}\n\nvoid test_circles()\n{\n    test_circle<box_type>(\"BOX(1 1, 1.1 1.1)\", false, false);\n    test_circle<box_type>(\"BOX(2 1, 4 4)\", false, false);\n    test_circle<box_type>(\"BOX(-2 -2, 4 4)\", false, true);\n    test_circle<box_type>(\"BOX(-2.1 -2.1, 4.1 4.1)\", true, true);\n}\n\n\nint test_main( int , char* [] )\n{\n    test_circles();\n\n    return 0;\n}\n", "meta": {"hexsha": "2f16acc0838dbef58b9c285317b93b663d3cb3a7", "size": 1975, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/nsphere/nsphere-nsphere_in_box.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-nsphere_in_box.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-nsphere_in_box.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.859375, "max_line_length": 97, "alphanum_fraction": 0.6875949367, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5410792996792325}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\r\n *    All rights reserved.\r\n *\r\n *    Redistribution and use in source and binary forms, with or without modification, are\r\n *    permitted provided that the following conditions are met:\r\n *      - Redistributions of source code must retain the above copyright notice, this list of\r\n *        conditions and the following disclaimer.\r\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\r\n *        conditions and the following disclaimer in the documentation and/or other materials\r\n *        provided with the distribution.\r\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\r\n *        may be used to endorse or promote products derived from this software without specific\r\n *        prior written permission.\r\n *\r\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\r\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\r\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\r\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\r\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\r\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\r\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *    Changelog\r\n *      YYMMDD    Author            Comment\r\n *      120116    B. Tong Minh      File added.\r\n *      120324    K. Kumar          Boostified unit tests; updated file header to new standard.\r\n *      120522    E. Heeren         Changed Tolerances.\r\n *\r\n *    References\r\n *\r\n *    Notes\r\n *\r\n */\r\n\r\n#define BOOST_TEST_MAIN\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <Eigen/Core>\r\n\r\n#include \"Tudat/Basics/testMacros.h\"\r\n\r\n#include \"Tudat/Mathematics/BasicMathematics/numericalDerivative.h\"\r\n\r\nnamespace tudat\r\n{\r\nnamespace unit_tests\r\n{\r\n\r\nBOOST_AUTO_TEST_SUITE( test_basic_functions )\r\n\r\ntypedef Eigen::MatrixXd( *DerivativeCallback )( const Eigen::VectorXd& );\r\ntypedef Eigen::VectorXd( *FunctionEvaluationCallback )( const Eigen::VectorXd& );\r\n\r\n//! Run a test case with the exponential density.\r\nvoid compareAnalyticalAndNumericalDerivative( const Eigen::VectorXd& input,\r\n                                              DerivativeCallback analyticalCallback,\r\n                                              FunctionEvaluationCallback numericalCallback )\r\n{\r\n    using numerical_derivatives::computeCentralDifference;\r\n\r\n    // Compute the expected partial.\r\n    Eigen::MatrixXd analyticalDerivative = analyticalCallback( input );\r\n\r\n    // Test 2nd-order numerical derivative.\r\n    {\r\n        Eigen::MatrixXd numericalDerivative = computeCentralDifference( input, numericalCallback );\r\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( analyticalDerivative, numericalDerivative,\r\n                                           1.0e-7 );\r\n    }\r\n\r\n    // Test 4th-order numerical derivative.\r\n    {\r\n        Eigen::MatrixXd numericalDerivative = computeCentralDifference(\r\n                    input, numericalCallback, 0.0, 0.0,\r\n                    numerical_derivatives::order4 );\r\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( analyticalDerivative, numericalDerivative,\r\n                                           1.0e-9 );\r\n\r\n    }\r\n\r\n    // Test 8th-order numerical derivative.\r\n    {\r\n        Eigen::MatrixXd numericalDerivative = computeCentralDifference(\r\n                    input, numericalCallback, 0.0, 0.0,\r\n                    numerical_derivatives::order8 );\r\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( analyticalDerivative, numericalDerivative,\r\n                                           1.0e-9 );\r\n    }\r\n}\r\n\r\n//! Callback that returns the analytical derivative of exp( ||r|| ).\r\nEigen::MatrixXd exponentialDensityAnalyticalDerivative( const Eigen::VectorXd& position )\r\n{\r\n    return position.transpose( ) / position.norm( ) * std::exp( position.norm( ) );\r\n}\r\n\r\n//! Callback to test numerical derivative calculation, returns exp( ||r|| ).\r\nEigen::VectorXd exponentialDensity( const Eigen::VectorXd& position )\r\n{\r\n    return Eigen::VectorXd::Constant( 1, std::exp( position.norm( ) ) );\r\n}\r\n\r\n//! Callback that returns the analytical derivative of -r/||r||.\r\nEigen::MatrixXd constantGravityAnalyticalDerivative( const Eigen::VectorXd& position )\r\n{\r\n    Eigen::MatrixXd partial = position * position.transpose( ) / std::pow( position.norm( ), 3.0 );\r\n    partial.diagonal( ) = position.array( ).pow( 2.0 ) / std::pow( position.norm( ), 3.0 )\r\n            - 1.0 / position.norm( );\r\n    return partial;\r\n}\r\n\r\n//! Callback to test numerical derivative calculation, returns -r/||r||.\r\nEigen::VectorXd constantGravity( const Eigen::VectorXd& position )\r\n{\r\n    return -position / position.norm( );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( testNumericalDerivatives )\r\n{\r\n    // Test numerical derivatives.\r\n    Eigen::MatrixXd positions( 10, 3 );\r\n    positions << 0.0416284088706, 0.365492068944, 0.805197604602,\r\n                 1.63074391170,   8.04179355586,  6.74984731916,\r\n                 55.4620045731,   86.8094364606,  95.4087064974,\r\n                 41.3971344853,   80.6456253401,  359.560049206,\r\n                 6389.36995846,   1891.72249537,  3768.41346114,\r\n                 18357.5991764,   5355.13286809,  24582.5658116,\r\n                 19887.9880951,   390769.463405,  949457.32454,\r\n                 3634565.52581,   5564841.99331,  3208769.36002,\r\n                 45156443.1799,   3463879.96686,  97241290.6455,\r\n                 478348640.774,   6705325.08872,  335953979.068;\r\n\r\n    // Loop through the input data and pass position data to check function.\r\n    for ( int i = 0; i < positions.cols( ); i++ )\r\n    {\r\n        Eigen::VectorXd position = positions.block< 1, 3 >( i, 0 ).transpose( );\r\n\r\n        compareAnalyticalAndNumericalDerivative( position,\r\n                                                 &exponentialDensityAnalyticalDerivative,\r\n                                                 &exponentialDensity );\r\n\r\n        compareAnalyticalAndNumericalDerivative( position,\r\n                                                 &constantGravityAnalyticalDerivative,\r\n                                                 &constantGravity );\r\n    }\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END( )\r\n\r\n} // namespace unit_tests\r\n} // namespace tudat\r\n\r\n", "meta": {"hexsha": "e8758049701dcc849e0b91f682494c75fe0caab5", "size": 6679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/UnitTests/unitTestNumericalDerivative.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/UnitTests/unitTestNumericalDerivative.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/UnitTests/unitTestNumericalDerivative.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": 42.8141025641, "max_line_length": 100, "alphanum_fraction": 0.637969756, "num_tokens": 1486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5410080685782563}}
{"text": "/* Copyright (c) 2012-2019 Big Ladder Software LLC. All rights reserved.\n * See the LICENSE file for additional terms and conditions. */\n\n#ifndef GEOMETRY_H_\n#define GEOMETRY_H_\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/multi/geometries/multi_point.hpp>\n#include <boost/geometry/multi/geometries/multi_polygon.hpp>\n\n#include \"Functions.hpp\"\n#include \"libkiva_export.h\"\n\nnamespace Kiva {\n\ntypedef boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> Point;\ntypedef boost::geometry::model::polygon<Point, true, false> Polygon;\ntypedef boost::geometry::model::ring<Point, true, false> Ring;\ntypedef boost::geometry::model::multi_polygon<Polygon> MultiPolygon;\ntypedef boost::geometry::model::multi_point<Point> MultiPoint;\ntypedef boost::geometry::model::linestring<Point> Line;\ntypedef boost::geometry::model::box<Point> Box;\ntypedef boost::geometry::model::point<double, 3, boost::geometry::cs::cartesian> Point3;\ntypedef boost::geometry::model::polygon<Point3, true, false> Polygon3;\n\nnamespace geom {\nenum Direction { X_NEG, X_POS, Y_NEG, Y_POS };\n\nenum Turn { LEFT, RIGHT };\n} // namespace geom\n\nbool isRectilinear(Polygon poly);\nPolygon offset(Polygon poly, double dist);\ngeom::Direction getDirectionIn(Polygon poly, std::size_t vertex);\ngeom::Direction getDirectionOut(Polygon poly, std::size_t vertex);\ngeom::Turn getTurn(Polygon poly, std::size_t vertex);\nMultiPolygon mirrorX(MultiPolygon poly, double x);\nMultiPolygon mirrorY(MultiPolygon poly, double y);\nPolygon symmetricUnit(Polygon poly);\nbool isXSymmetric(Polygon poly);\nbool isYSymmetric(Polygon poly);\ndouble getXmin(Polygon poly, std::size_t vertex);\ndouble getYmin(Polygon poly, std::size_t vertex);\ndouble getXmax(Polygon poly, std::size_t vertex);\ndouble getYmax(Polygon poly, std::size_t vertex);\n\nbool LIBKIVA_EXPORT comparePointsX(Point first, Point second);\nbool LIBKIVA_EXPORT comparePointsY(Point first, Point second);\nbool LIBKIVA_EXPORT pointOnPoly(Point point, Polygon poly);\nbool LIBKIVA_EXPORT isConvex(Polygon poly);\n\ndouble LIBKIVA_EXPORT getDistance(Point a, Point b);\n\ndouble getAngle(Point a, Point b, Point c);\n\n} // namespace Kiva\n\n#endif /* GEOMETRY_H_ */\n", "meta": {"hexsha": "b1378501824cdd9aaef61b55e2623fa4fd735ef6", "size": 2230, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libkiva/Geometry.hpp", "max_stars_repo_name": "jmarrec/kiva", "max_stars_repo_head_hexsha": "c4dea41f974d09167eaded71c3a41e66f98de92e", "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/libkiva/Geometry.hpp", "max_issues_repo_name": "jmarrec/kiva", "max_issues_repo_head_hexsha": "c4dea41f974d09167eaded71c3a41e66f98de92e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libkiva/Geometry.hpp", "max_forks_repo_name": "jmarrec/kiva", "max_forks_repo_head_hexsha": "c4dea41f974d09167eaded71c3a41e66f98de92e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-20T21:35:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-20T21:35:31.000Z", "avg_line_length": 37.1666666667, "max_line_length": 88, "alphanum_fraction": 0.7807174888, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5409777213834981}}
{"text": "#include <mlpack/core.hpp>\n#include <mlpack/methods/cf/svd_wrapper.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nBOOST_AUTO_TEST_SUITE(ArmadilloSVDTest);\n\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::cf;\nusing namespace arma;\n\n/**\n * Test armadillo SVD for normal factorization\n */\nBOOST_AUTO_TEST_CASE(ArmadilloSVDNormalFactorizationTest)\n{\n  mat test = randu<mat>(20, 20);\n\n  SVDWrapper<> svd;\n  arma::mat W, H, sigma;\n  double result = svd.Apply(test, W, sigma, H);\n\n  BOOST_REQUIRE_LT(result, 0.01);\n\n  test = randu<mat>(50, 50);\n  result = svd.Apply(test, W, sigma, H);\n\n  BOOST_REQUIRE_LT(result, 0.01);\n}\n\n/**\n * Test armadillo SVD for low rank matrix factorization\n */\nBOOST_AUTO_TEST_CASE(ArmadilloSVDLowRankFactorizationTest)\n{\n  mat W_t = randu<mat>(30, 3);\n  mat H_t = randu<mat>(3, 40);\n\n  // create a row-rank matrix\n  mat test = W_t * H_t;\n\n  SVDWrapper<> svd;\n  arma::mat W, H;\n  double result = svd.Apply(test, 3, W, H);\n\n  BOOST_REQUIRE_LT(result, 0.01);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "cb945b321941baeb42609ae90292f6eb5dc115cd", "size": 1069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/armadillo_svd_test.cpp", "max_stars_repo_name": "vj-ug/Contribution-to-mlpack", "max_stars_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T11:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:20.000Z", "max_issues_repo_path": "src/mlpack/tests/armadillo_svd_test.cpp", "max_issues_repo_name": "vj-ug/Contribution-to-mlpack", "max_issues_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/armadillo_svd_test.cpp", "max_forks_repo_name": "vj-ug/Contribution-to-mlpack", "max_forks_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "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.1698113208, "max_line_length": 58, "alphanum_fraction": 0.7128157156, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505966, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.5409777053120686}}
{"text": "#define CATCH_CONFIG_MAIN\n\n#include \"CALPHADFreeEnergyFunctionsBinary.h\"\n#include \"InterpolationType.h\"\n\n#include \"catch.hpp\"\n\n#include <boost/optional/optional.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n\n#include <string>\n\n#include <omp.h>\n\nnamespace pt = boost::property_tree;\n\nTEST_CASE(\"CALPHAD binary kks in a loop\", \"[binary kks loop]\")\n{\n    std::cout << \"Run test with \" << omp_get_max_threads() << \" threads\"\n              << std::endl;\n\n    Thermo4PFM::EnergyInterpolationType energy_interp_func_type\n        = Thermo4PFM::EnergyInterpolationType::PBG;\n    Thermo4PFM::ConcInterpolationType conc_interp_func_type\n        = Thermo4PFM::ConcInterpolationType::PBG;\n\n    const double Tmin     = 1300.;\n    const double Tmax     = 1500.;\n    const int nTintervals = 10;\n    const double deltaT   = (Tmax - Tmin) / (double)nTintervals;\n\n    std::cout << \" Read CALPHAD database...\" << std::endl;\n    pt::ptree calphad_db;\n    try\n    {\n        pt::read_json(\"../thermodynamic_data/calphadAuNi.json\", calphad_db);\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"exception caught: \" << e.what() << std::endl;\n    }\n\n    boost::optional<pt::ptree&> newton_db;\n\n    // nominal concentration for which to solve KKS eqs.\n    const double nominalc = 0.2;\n\n    // initial guesses\n    const double init_guess[2] = { 0.5, 0.5 };\n\n    std::vector<double> cl(nTintervals + 1);\n    std::vector<double> cs(nTintervals + 1);\n\n    Thermo4PFM::CALPHADFreeEnergyFunctionsBinary* cafe\n        = new Thermo4PFM::CALPHADFreeEnergyFunctionsBinary(calphad_db,\n            newton_db, energy_interp_func_type, conc_interp_func_type);\n\n    {\n        // serial loop\n        for (int i = 0; i < nTintervals + 1; i++)\n        {\n            const double temperature = Tmin + i * deltaT;\n\n            double phi = 0.5;\n            double conc[2];\n\n            // compute concentrations in each phase\n            cafe->computePhaseConcentrations(\n                temperature, &nominalc, &phi, conc);\n\n            std::cout << \"Temperature = \" << temperature << std::endl;\n            std::cout << \"Concentrations: cl = \" << conc[0]\n                      << \" and cs = \" << conc[1] << \"...\" << std::endl;\n\n            cl[i] = conc[0];\n            cs[i] = conc[1];\n        }\n    }\n\n    std::vector<short> nitscpu(nTintervals + 1);\n\n// parallel loop\n#pragma omp parallel for\n    for (int i = 0; i < nTintervals + 1; i++)\n    {\n        const double temperature = Tmin + i * deltaT;\n\n        double phi     = 0.5;\n        double conc[2] = { init_guess[0], init_guess[1] };\n\n        // compute concentrations in each phase\n        nitscpu[i] = cafe->computePhaseConcentrations(\n            temperature, &nominalc, &phi, conc);\n\n        CHECK(conc[0] == Approx(cl[i]).margin(1.e-6));\n        CHECK(conc[1] == Approx(cs[i]).margin(1.e-6));\n    }\n\n    short* nits  = new short[nTintervals + 1];\n    double* xdev = new double[2 * (nTintervals + 1)];\n\n// clang-format off\n#pragma omp target map(to : cafe [0:1]) \\\n                   map(to : init_guess[:2]) \\\n                   map(from : xdev[:2 * (nTintervals + 1)]) \\\n                   map(from : nits[:nTintervals + 1])\n// clang-format on\n#pragma omp parallel for\n    for (int i = 0; i < nTintervals + 1; i++)\n    {\n        const double temperature = Tmin + i * deltaT;\n\n        double phi = 0.5;\n        double c0  = nominalc;\n\n        xdev[2 * i]     = init_guess[0];\n        xdev[2 * i + 1] = init_guess[1];\n\n        // compute concentrations in each phase\n        nits[i] = cafe->computePhaseConcentrations(\n            temperature, &c0, &phi, &xdev[2 * i]);\n    }\n\n    for (int i = 0; i < nTintervals + 1; i++)\n    {\n        std::cout << \"Number of Newton iterations: \" << nits[i] << std::endl;\n        std::cout << \"Device: x=\" << xdev[2 * i] << \",\" << xdev[2 * i + 1]\n                  << std::endl;\n        CHECK(xdev[2 * i] == Approx(cl[i]).margin(1.e-6));\n        CHECK(xdev[2 * i + 1] == Approx(cs[i]).margin(1.e-6));\n        CHECK(nits[i] == nitscpu[i]);\n    }\n    delete[] nits;\n    delete[] xdev;\n}\n", "meta": {"hexsha": "7cd3edfa6ffa4c8bd10ce36c47519a3bc7e17620", "size": 4097, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/testLoopCALPHADbinaryKKS.cc", "max_stars_repo_name": "stvdwtt/Thermo4PFM", "max_stars_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "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/testLoopCALPHADbinaryKKS.cc", "max_issues_repo_name": "stvdwtt/Thermo4PFM", "max_issues_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/testLoopCALPHADbinaryKKS.cc", "max_forks_repo_name": "stvdwtt/Thermo4PFM", "max_forks_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "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.9051094891, "max_line_length": 77, "alphanum_fraction": 0.5670002441, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6442251064863695, "lm_q1q2_score": 0.5409776944083824}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Example: Affine Transformation (translate, scale, rotate)\n//\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\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\n#include <ctime> // for std::time\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <sstream>\n\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/algorithms/centroid.hpp>\n#include <boost/geometry/strategies/transform.hpp>\n#include <boost/geometry/strategies/transform/matrix_transformers.hpp>\n#include <boost/geometry/io/wkt/read.hpp>\n\n#if defined(HAVE_SVG)\n#  include <boost/geometry/io/svg/write_svg.hpp>\n#endif\n\n#include <boost/bind.hpp>\n#include <boost/random.hpp>\n#include <boost/range.hpp>\n#include <boost/shared_ptr.hpp>\n\nusing namespace boost::geometry;\n\nstruct random_style\n{\n    random_style()\n        : rng(static_cast<int>(std::time(0))), dist(0, 255), colour(rng, dist)\n    {}\n\n    std::string fill(double opacity = 1)\n    {\n        std::ostringstream oss;\n        oss << \"fill:rgba(\" << colour() << \",\" << colour() << \",\" << colour() << \",\" << opacity << \");\";\n        return oss.str();\n    }\n\n    std::string stroke(int width, double opacity = 1)\n    {\n        std::ostringstream oss;\n        oss << \"stroke:rgba(\" << colour() << \",\" << colour() << \",\" << colour() << \",\" << opacity << \");\";\n        oss << \"stroke-width:\" << width  << \";\";\n        return oss.str();\n    }\n\n    template <typename T>\n    std::string text(T x, T y, std::string const& text)\n    {\n        std::ostringstream oss;\n        oss << \"<text x=\\\"\" << static_cast<int>(x) - 90 << \"\\\" y=\\\"\" << static_cast<int>(y) << \"\\\" font-family=\\\"Verdana\\\">\" << text << \"</text>\";\n        return oss.str();\n    }\n\n    boost::mt19937 rng;\n    boost::uniform_int<> dist;\n    boost::variate_generator<boost::mt19937&, boost::uniform_int<> > colour;\n};\n\ntemplate <typename OutputStream>\nstruct svg_output\n{\n    svg_output(OutputStream& os, double opacity = 1) : os(os), opacity(opacity)\n    {\n        os << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\"\n            << \"<!DOCTYPE svg PUBLIC \\\"-//W3C//DTD SVG 1.1//EN\\\"\\n\"\n            << \"\\\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\\\">\\n\"\n            << \"<svg width=\\\"100%\\\" height=\\\"100%\\\" version=\\\"1.1\\\"\\n\"\n            << \"xmlns=\\\"http://www.w3.org/2000/svg\\\">\" << std::endl;\n    }\n\n    ~svg_output()\n    {\n        os << \"</svg>\" << std::endl;\n    }\n\n    template <typename G>\n    void put(G const& g, std::string const& label)\n    {\n        std::string style_str(style.fill(opacity) + style.stroke(5, opacity));\n#if defined(HAVE_SVG)\n        os << boost::geometry::svg(g, style_str) << std::endl;\n#endif\n        if (!label.empty())\n        {\n            typename point_type<G>::type c;\n            centroid(g, c);\n            os << style.text(static_cast<int>(get<0>(c)), static_cast<int>(get<1>(c)), label);\n        }\n    }\n\nprivate:\n\n    OutputStream& os;\n    double opacity;\n    random_style style;\n};\n\n\nint main()\n{\n    using namespace boost::geometry::strategy::transform;\n\n    typedef boost::geometry::model::d2::point_xy<double> point_2d;\n\n    try\n    {\n        std::string file(\"06_b_transformation_example.svg\");\n        std::ofstream ofs(file.c_str());\n        svg_output<std::ofstream> svg(ofs, 0.5);\n\n        // G1 - create subject for affine transformations\n        model::polygon<point_2d> g1;\n        read_wkt(\"POLYGON((50 250, 400 250, 150 50, 50 250))\", g1);\n        std::clog << \"source box:\\t\" << boost::geometry::dsv(g1) << std::endl;\n        svg.put(g1, \"g1\");\n\n        // G1 - Translate -> G2\n        translate_transformer<double, 2, 2> translate(0, 250);\n        model::polygon<point_2d> g2;\n        transform(g1, g2, translate);\n        std::clog << \"translated:\\t\" << boost::geometry::dsv(g2) << std::endl;\n        svg.put(g2, \"g2=g1.translate(0,250)\");\n\n        // G2 - Scale -> G3\n        scale_transformer<double, 2, 2> scale(0.5, 0.5);\n        model::polygon<point_2d> g3;\n        transform(g2, g3, scale);\n        std::clog << \"scaled:\\t\" << boost::geometry::dsv(g3) << std::endl;\n        svg.put(g3, \"g3=g2.scale(0.5,0.5)\");\n\n        // G3 - Combine rotate and translate -> G4\n        rotate_transformer<degree, double, 2, 2> rotate(45);\n\n        // Compose matrix for the two transformation\n        // Create transformer attached to the transformation matrix\n        ublas_transformer<double, 2, 2>\n                combined(boost::numeric::ublas::prod(rotate.matrix(), translate.matrix()));\n                //combined(rotate.matrix());\n\n        // Apply transformation to subject geometry point-by-point\n        model::polygon<point_2d> g4;\n        transform(g3, g4, combined);\n\n        std::clog << \"rotated & translated:\\t\" << boost::geometry::dsv(g4) << std::endl;\n        svg.put(g4, \"g4 = g3.(rotate(45) * translate(0,250))\");\n\n        std::clog << \"Saved SVG file:\\t\" << file << std::endl;\n    }\n    catch (std::exception const& e)\n    {\n        std::cerr << e.what() << std::endl;\n    }\n    catch (...)\n    {\n        std::cerr << \"unknown error\" << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "db125ff537fc1631f0b170bca1805ca35f067946", "size": 5365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/example/06_b_transformation_example.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-11-02T07:15:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:56:59.000Z", "max_issues_repo_path": "libs/geometry/example/06_b_transformation_example.cpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.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": "libs/geometry/example/06_b_transformation_example.cpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-17T15:37:11.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-10T14:06:31.000Z", "avg_line_length": 31.3742690058, "max_line_length": 146, "alphanum_fraction": 0.5863932898, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5409683094318732}}
{"text": "/**\n * @file intrinsics.hpp\n * @copyright Copyright (c) 2020 Nicolas Pope, MIT License\n * @author Nicolas Pope\n */\n\n#pragma once\n\n#include \"../defines.hpp\"\n\n#include <Eigen/Eigen>\n\nnamespace voltu\n{\n\n/** Intrinsic camera paramters */\nstruct Intrinsics\n{\n\tunsigned int width;\n\tunsigned int height;\n\tfloat principle_x;\n\tfloat principle_y;\n\tfloat focal_x;\n\tfloat focal_y;\n\n\t/** Projection matrix */\n\tPY_API Eigen::Matrix3d matrix();\n\t/** Size (width, height) */\n\tPY_API Eigen::Vector2i size();\n};\n\n/** Stereo camera intrinsic parameters.\n *\n * Baseline can be used to estimate depth accuracy for known depth. Assuming 1px\n * disparity accuracy, accuracy of given depth z, the accuracy of depth is\n * z^2/(f*T), where f is focal length and T baseline.\n */\nstruct StereoIntrinsics : public Intrinsics\n{\n\tfloat baseline;\n\tfloat min_depth;\n\tfloat max_depth;\n};\n\n}\n", "meta": {"hexsha": "4157ab383d10563d1a334127f2d768abb23301e6", "size": 857, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SDK/CPP/public/include/voltu/types/intrinsics.hpp", "max_stars_repo_name": "knicos/voltu", "max_stars_repo_head_hexsha": "70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-28T15:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-27T12:37:15.000Z", "max_issues_repo_path": "SDK/CPP/public/include/voltu/types/intrinsics.hpp", "max_issues_repo_name": "knicos/voltu", "max_issues_repo_head_hexsha": "70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01", "max_issues_repo_licenses": ["MIT"], "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/CPP/public/include/voltu/types/intrinsics.hpp", "max_forks_repo_name": "knicos/voltu", "max_forks_repo_head_hexsha": "70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-13T05:28:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T03:37:11.000Z", "avg_line_length": 18.6304347826, "max_line_length": 80, "alphanum_fraction": 0.7129521587, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5409682973492861}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing Eigen::Matrix3f;\nusing Eigen::Matrix3d;\nusing namespace std;\n\nvoid PrintMat(const Matrix3d& m) {\n  cout << \"Matrix : \" << m << endl;\n}\n\nEigen::Matrix3f GetMat() {\n  Matrix3f m;\n  m << 1, 2, 3,\n       4, 5, 6,\n       7, 8, 9;\n  return m;\n}\n\nchar const* Greet() {\n  return \"Hello, world ! \";\n}\n\n", "meta": {"hexsha": "7a8ce9bc0cc37fb3cd4693c48239fbf1a617a9c0", "size": 343, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/hello.cc", "max_stars_repo_name": "ColinTogashi/boost_numpy_eigen", "max_stars_repo_head_hexsha": "210fa9216bb3c4010e16839ab673e343cb363d17", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-02-18T20:41:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-10T21:15:47.000Z", "max_issues_repo_path": "src/hello.cc", "max_issues_repo_name": "Algomorph/boost_numpy_eigen", "max_issues_repo_head_hexsha": "f46dc261272aed8dc8672c4937b33381b5fa451c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-08-16T18:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T16:46:58.000Z", "max_forks_repo_path": "src/hello.cc", "max_forks_repo_name": "Algomorph/boost_numpy_eigen", "max_forks_repo_head_hexsha": "f46dc261272aed8dc8672c4937b33381b5fa451c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-02-06T21:41:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T21:44:02.000Z", "avg_line_length": 14.2916666667, "max_line_length": 35, "alphanum_fraction": 0.5860058309, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568415, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.540968297349286}}
{"text": "#include <boost/program_options.hpp>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <omp.h>\n#include <opencv2/opencv.hpp>\n#include <vector>\n\nusing complex = std::complex<double>;\nconstexpr double PI = 3.14159'26535'89793'23846'26433'83279'50288;\n\nstd::uint8_t colu(double t0) {\n  double t = std::fmod(std::fmod(t0, 3.0) + 3.0, 3.0);\n  if (t < 2) {\n    return static_cast<std::uint8_t>(\n        std::lround((1 - std::cos(t * PI)) * (255 / 2.0)));\n  } else {\n    return 0;\n  }\n}\n\ncv::Vec3b color(double t0) {\n  double t = t0;\n  return {colu(t), colu(t + 1), colu(t + 2)};\n}\n\ndouble abslog(double x) {\n  if (x == 0) {\n    return 0;\n  }\n  auto l = std::log(std::abs(x) + 1);\n  auto sign = x < 0 ? -1 : 1;\n  return l * sign;\n}\n\nclass mandel_maker {\n  cv::Vec3d pix_at(double x, double y) {\n    complex z{0.0, 0.0};\n    auto c = complex{x, y};\n    std::vector<cv::Point2f> points;\n    points.reserve(rep);\n    constexpr double LIMIT = 20;\n    for (int ix = 0; ix < rep; ++ix) {\n      z = z*z*z/(std::abs(z)+1e-10)+c;\n      if (LIMIT < std::abs(z)) {\n        return {static_cast<double>(ix), std::arg(z), std::abs(z)};\n      }\n      points.emplace_back(cv::Point2f(abslog(real(z)), abslog(imag(z))));\n    }\n    std::vector<cv::Point2f> hull;\n    cv::convexHull(points, hull);\n    auto area = cv::contourArea(hull);\n    return {-1, std::arg(z), area};\n  }\n  int rep;\n  int w, h;\n  double x0, dx;\n  double y0, dy;\n\npublic:\n  explicit mandel_maker(int rep_, int w_, int h_, double x0_, double x1_,\n                        double y0_)\n      : rep(rep_), w(w_), h(h_), x0(x0_), dx((x1_ - x0_) / w_), y0(y0_),\n        dy((x1_ - x0_) * h_ / w_ / h_) {}\n  cv::Mat make() {\n    cv::Mat im = cv::Mat::zeros(w, h, CV_64FC3);\n#pragma omp parallel for\n    for (int iy = 0; iy < h; ++iy) {\n      double y = y0 + dy * iy;\n      for (int ix = 0; ix < w; ++ix) {\n        double x = x0 + ix * dx;\n        auto col = pix_at(x, y);\n        im.at<cv::Vec3d>(iy, ix) = col;\n      }\n    }\n    return im;\n  }\n};\n\ncv::Rect2d rect(char const *cmd) {\n  double w0 = 1 << 5;\n  cv::Rect2d r(-w0 / 2, -w0 / 2, w0, w0);\n  for (; *cmd; ++cmd) {\n    if (*cmd=='s'){\n      auto w = r.width;\n      auto h = r.height;\n      auto dw = w/10;\n      auto dh = h/10;\n      r = cv::Rect2d( r.x+dw, r.y+dh, w-dw*2, h-dh*2 );\n      continue;\n    }\n    double w = r.width / 2;\n    double h = r.height / 2;\n    double x, y;\n    int c = *cmd - '0';\n    switch (c % 3) {\n    case 0:\n      x = r.x;\n      break;\n    case 1:\n      x = r.x + w / 2;\n      break;\n    case 2:\n      x = r.x + w;\n      break;\n    }\n    switch (c / 3) {\n    case 0:\n      y = r.y;\n      break;\n    case 1:\n      y = r.y + h / 2;\n      break;\n    case 2:\n      y = r.y + h;\n      break;\n    }\n    r = cv::Rect2d(x, y, w, h);\n  }\n  return r;\n}\n\nvoid save_image(char const *filename, cv::Mat const &im) {\n  cv::FileStorage fs(filename, cv::FileStorage::WRITE);\n  fs << \"image\" << im;\n}\n\nstd::pair<std::int32_t, std::int32_t> find_minmax(cv::Mat const &im) {\n  int min = INT32_MAX;\n  int max = INT32_MIN;\n  auto end = im.end<std::int32_t>();\n  for (auto it = im.begin<std::int32_t>(); it != end; ++it) {\n    int32_t col = *it;\n    if (col < 0) {\n      continue;\n    }\n    if (col < min) {\n      min = col;\n    }\n    if (max < col) {\n      max = col;\n    }\n  }\n  return {min, max};\n}\n\ncv::Mat colorize(cv::Mat const &src) {\n  cv::Mat dest = cv::Mat::zeros(src.rows, src.cols, CV_8UC3);\n#pragma omp parallel for\n  for (int y = 0; y < src.rows; ++y) {\n    for (int x = 0; x < src.cols; ++x) {\n      auto col{src.at<cv::Vec3d>(y, x)};\n      if (col[0] < 0) {\n        // auto c0 = color((col[2]*0.1 + col[1] / (PI * 2) * 3 + 3) * 3) / 2;\n        auto c0 = color(std::log(col[2]));\n        dest.at<cv::Vec3b>(y, x) = c0 / 2;\n      } else {\n        auto c0 = cv::Vec3b{255, 255, 255} - color(col[1] / (PI * 2) * 3 + 3);\n        auto c1 = cv::Vec3b{255, 255, 255} - color(col[0] * 0.006 + 1);\n        constexpr double W = 0.2;\n        dest.at<cv::Vec3b>(y, x) = c0 * W + c1 * (1 - W);\n      }\n    }\n  }\n  return dest;\n}\n\nnamespace po = boost::program_options;\n\npo::options_description calc_options() {\n  po::options_description desc(\"calc options\");\n  desc.add_options()                                                     //\n      (\"help\", \"produce help message\")                                   //\n      (\"size,s\", po::value<double>()->default_value(60), \"size in mm\")   //\n      (\"dpi,d\", po::value<double>()->default_value(96), \"DPI\")           //\n      (\"rep,r\", po::value<int>()->default_value(1000), \"repeat count\")   //\n      (\"pos,p\", po::value<std::string>()->default_value(\"\"), \"position\") //\n      ;\n  return desc;\n}\n\npo::options_description col_options() {\n  po::options_description desc(\"col options\");\n  desc.add_options()                   //\n      (\"help\", \"produce help message\") //\n      (\"infile,i\", po::value<std::string>()->default_value(\"data/hoge.yaml\"),\n       \"input yaml file\") //\n      (\"outfile,o\", po::value<std::string>()->default_value(\"data/hoge.png\"),\n       \"output image file\") //\n      ;\n  return desc;\n}\n\nint calc(int argc, char const *argv[]) {\n  auto desc = calc_options();\n  try {\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    if (vm.count(\"help\")) {\n      std::cout << desc << \"\\n\";\n      return 0;\n    }\n    double realsize = vm[\"size\"].as<double>();\n    double dpi = vm[\"dpi\"].as<double>();\n    auto pix = lround(realsize / 25.4 * dpi);\n    omp_set_num_threads(16);\n    int rep = vm[\"rep\"].as<int>();\n    cv::Rect2d rc = rect(vm[\"pos\"].as<std::string>().c_str());\n    auto mm = mandel_maker(rep, pix, pix, rc.x, rc.br().x, rc.y);\n    cv::Mat im = mm.make();\n    cv::imwrite(\"data/hoge.png\", colorize(im));\n    save_image(\"data/hoge.yaml\", im);\n    return 0;\n  } catch (po::error &e) {\n    std::cout << e.what() << std::endl;\n    return 0;\n  }\n}\n\nint colorize(int argc, char const *argv[]) {\n  auto desc = col_options();\n  try {\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    if (vm.count(\"help\")) {\n      std::cout << desc << \"\\n\";\n      return 0;\n    }\n    auto infile = vm[\"infile\"].as<std::string>();\n    auto outfile = vm[\"outfile\"].as<std::string>();\n    std::cout << infile << \", \" << outfile << \"\\n\";\n\n    cv::FileStorage fs(infile, cv::FileStorage::READ);\n    cv::Mat im;\n    fs[\"image\"] >> im;\n    cv::imwrite(outfile, colorize(im));\n    return 0;\n  } catch (po::error &e) {\n    std::cout << e.what() << std::endl;\n    return 0;\n  }\n}\nvoid show_help() {\n  std::cout << calc_options() << \"\\n\" << col_options() << \"\\n\";\n}\n\nint main(int argc, char const *argv[]) {\n  if (argc < 2) {\n    show_help();\n    return 0;\n  }\n  auto cmd = std::string(argv[1]);\n  if (cmd == \"calc\") {\n    return calc(argc - 1, argv + 1);\n  } else if (cmd == \"col\") {\n    return colorize(argc - 1, argv + 1);\n  } else {\n    show_help();\n    return 0;\n  }\n}\n", "meta": {"hexsha": "625e2db4c12d3e8b027343859894b640275b186d", "size": 6897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/m0.cpp", "max_stars_repo_name": "nabetani/mandel", "max_stars_repo_head_hexsha": "70b286fc1b96e9471bde9ddddacb96f640b9c313", "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/m0.cpp", "max_issues_repo_name": "nabetani/mandel", "max_issues_repo_head_hexsha": "70b286fc1b96e9471bde9ddddacb96f640b9c313", "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/m0.cpp", "max_forks_repo_name": "nabetani/mandel", "max_forks_repo_head_hexsha": "70b286fc1b96e9471bde9ddddacb96f640b9c313", "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.3244274809, "max_line_length": 78, "alphanum_fraction": 0.5173263738, "num_tokens": 2308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5408905082154837}}
{"text": "#pragma once\n/*!\t\\file\tinteger.hpp\n\t\\brief\tInteger class declaration.\n\t\\author\tGarth Santor\n\t\\date\t2021-10-29\n\t\\copyright\tGarth Santor, Trinh Han\n\n=============================================================\nDeclarations of the Integer class derived from Operand.\n\n=============================================================\nRevision History\n-------------------------------------------------------------\n\nVersion 2021.10.02\n\tC++ 20 validated\n\nVersion 2019.11.05\n\tC++ 17 cleanup\n\nVersion 2014.10.29\n\tC++ 11 refactor.\n\tConverted Integer::value_type to boost::multiprecision::cpp_int\n\tRemoved BinaryInteger\n\nVersion 2012.11.15\n\tAdded BinaryInteger.\n\nVersion 2012.11.13\n\tC++ 11 cleanup.\n\nVersion 2010.11.09\n\tSwitched boost::shared_ptr<> to std::shared_ptr<>.\n\tAdded TOKEN_PTR_TYPE macro.\n\tSwitched __int64 to long long.\n\nVersion 2009.11.25\n\tAlpha release.\n\n=============================================================\n\nCopyright Garth Santor/Trinh Han\n\nThe copyright to the computer program(s) herein\nis the property of Garth Santor/Trinh Han, Canada.\nThe program(s) may be used and/or copied only with\nthe written permission of Garth Santor/Trinh Han\nor in accordance with the terms and conditions\nstipulated in the agreement/contract under which\nthe program(s) have been supplied.\n=============================================================*/\n\n#include <ee/operand.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\n\n\n/*! Integer token. */\nclass Integer : public Operand {\npublic:\n\tusing value_type = boost::multiprecision::cpp_int;\n\tDEF_POINTER_TYPE(Integer)\nprivate:\n\tvalue_type\tvalue_;\npublic:\n\tInteger( value_type value = 0 )\n\t\t: value_( value ) { }\n\n\t[[nodiscard]]\tvalue_type\tvalue() const { return value_; }\n\t[[nodiscard]]\tstring_type\tstr() const override;\n};", "meta": {"hexsha": "8eb30aebdc1ed98a6ae7a85ddedb1967008977f8", "size": 1768, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ee21/common/inc/ee/integer.hpp", "max_stars_repo_name": "ygor-rezende/Expression-Evaluator", "max_stars_repo_head_hexsha": "52868ff11ce72a4ae6fa9a4052005c02f8485b3c", "max_stars_repo_licenses": ["FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ee21/common/inc/ee/integer.hpp", "max_issues_repo_name": "ygor-rezende/Expression-Evaluator", "max_issues_repo_head_hexsha": "52868ff11ce72a4ae6fa9a4052005c02f8485b3c", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ee21/common/inc/ee/integer.hpp", "max_forks_repo_name": "ygor-rezende/Expression-Evaluator", "max_forks_repo_head_hexsha": "52868ff11ce72a4ae6fa9a4052005c02f8485b3c", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9014084507, "max_line_length": 64, "alphanum_fraction": 0.6261312217, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5408905069363487}}
{"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_cloglog) {\n  EXPECT_EQ(1 - std::exp(-std::exp(3.7)), stan::math::inv_cloglog(3.7));\n  EXPECT_EQ(1 - std::exp(-std::exp(0.0)), stan::math::inv_cloglog(0.0));\n  EXPECT_EQ(1 - std::exp(-std::exp(-2.93)), stan::math::inv_cloglog(-2.93));\n}\n\nTEST(MathFunctions, inv_cloglog_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::inv_cloglog(nan));\n}\n", "meta": {"hexsha": "7d64276bd53d29b48f5bb8e8e68466e7685ed0b7", "size": 568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/inv_cloglog_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_cloglog_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_cloglog_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": 33.4117647059, "max_line_length": 76, "alphanum_fraction": 0.6954225352, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5408904907558113}}
{"text": "#pragma once\n\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n\n// std\n#include <iostream>\n#include \"darkroom/Sensor.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\nnamespace InYourGibbousPhase2 {\n// Generic functor for Eigen Levenberg-Marquardt minimizer\n    template<typename _Scalar, int NX = Dynamic, int NY = Dynamic>\n    struct Functor {\n        typedef _Scalar Scalar;\n        enum {\n            InputsAtCompileTime = NX,\n            ValuesAtCompileTime = NY\n        };\n        typedef Eigen::Matrix<Scalar, InputsAtCompileTime, 1> InputType;\n        typedef Eigen::Matrix<Scalar, ValuesAtCompileTime, 1> ValueType;\n        typedef Eigen::Matrix<Scalar, ValuesAtCompileTime, InputsAtCompileTime> JacobianType;\n\n        const int m_inputs, m_values;\n\n        Functor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\n\n        Functor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n        int inputs() const { return m_inputs; }\n\n        int values() const { return m_values; }\n    };\n\n    struct InYourGibbousPhase2 : Functor<double> {\n        /**\n         * Default amount of sensors needed for Eigen templated structure\n         * @param numberOfSensors you can however choose any number of sensors here\n         */\n        InYourGibbousPhase2(int trajectoryPoints = 4);\n\n        /**\n         * This is the function that is called in each iteration\n         * @param x contains the calibration values [phase0 phase1 tilt0 tilt1 curve0 curve1 gibphase0 gibphase1 gibmag0 gibmag1]\n         * @param fvec the error function (the difference between the sensor positions)\n         * @return\n         */\n        int operator()(const VectorXd &x, VectorXd &fvec) const;\n\n        vector<vector<Vector2d>> angles_measured_trajectory;\n        vector<vector<Vector3d>> relative_positions_trajectory;\n        double distance_y = 2.0;\n        int trajectoryPoints = 4;\n        bool lighthouse;\n        enum {phase_horizontal , phase_vertical, tilt_horizontal, tilt_vertical, curve_horizontal, curve_vertical,\n            gibphase_horizontal, gibphase_vertical, gibmag_horizontal, gibmag_vertical};\n    };\n}", "meta": {"hexsha": "14acda43ec22f70fa1a5e301bade687631677cde", "size": 2240, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "darkroom/include/darkroom/InYourGibbousPhase2.hpp", "max_stars_repo_name": "Roboy/roboy_darkroom", "max_stars_repo_head_hexsha": "ed9572dc92f27c8b40265a1d3369bf270e1fbc30", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-03-10T04:32:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T10:55:44.000Z", "max_issues_repo_path": "darkroom/include/darkroom/InYourGibbousPhase2.hpp", "max_issues_repo_name": "Roboy/roboy_darkroom", "max_issues_repo_head_hexsha": "ed9572dc92f27c8b40265a1d3369bf270e1fbc30", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "darkroom/include/darkroom/InYourGibbousPhase2.hpp", "max_forks_repo_name": "Roboy/roboy_darkroom", "max_forks_repo_head_hexsha": "ed9572dc92f27c8b40265a1d3369bf270e1fbc30", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-04T09:51:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-04T09:51:01.000Z", "avg_line_length": 35.5555555556, "max_line_length": 129, "alphanum_fraction": 0.6861607143, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.5408771173335649}}
{"text": "#define NOMINMAX\n#include \"interactions.hpp\"\n#include \"vsh_translation.hpp\"\n#include \"indices.hpp\"\n#include <cmath>\n#include <Eigen/IterativeLinearSolvers>\n#include <omp.h>\n\nusing std::complex;\nusing namespace std::complex_literals;\n\nusing Eigen::Vector3d;\n\nComplexVector matrix_vector_product(const Ref<const ComplexMatrix>& A, const Ref<const ComplexVector>& x) {\n    int size = x.size();\n    ComplexVector ret(size);\n#pragma omp parallel for\n    for (int i = 0; i < size; i++) {\n        ret(i) = A.row(i)*x;\n    }\n\n    return ret;\n}\n\ncomplex<double> dot_product(const Ref<const ComplexVector>& x, const Ref<const ComplexVector>& y) {\n    int size = x.size();\n    double real_part = 0;\n    double imag_part = 0;\n#pragma omp parallel for reduction(+:real_part,imag_part)\n    for (int i = 0; i < size; i++) {\n        real_part += x(i).real()*y(i).real() + x(i).imag()*y(i).imag();\n        imag_part += x(i).real()*y(i).imag() - x(i).imag()*y(i).real();\n    }\n\n    return std::complex<double>(real_part, imag_part);\n}\n\nComplexVector bicgstab(const Ref<const ComplexMatrix>& A, const Ref<const ComplexVector>& b,\n        int maxiter, double tolerance) {\n\n    int size = b.size();\n\n    // step 1\n    ComplexVector x_prev = b;\n    ComplexVector r_prev = b - matrix_vector_product(A, x_prev);\n\n    double error = (r_prev).norm();\n    if (error < tolerance)\n        return x_prev;\n\n    // step 2\n    ComplexVector r_hat = r_prev;\n\n    // step 3\n    complex<double> rho_prev = 1;\n    complex<double> alpha    = 1;\n    complex<double> w_prev   = 1;\n\n    // step 4\n    ComplexVector v_prev = ComplexVector::Zero(size);\n    ComplexVector p_prev = ComplexVector::Zero(size);\n\n    // step 5\n    int current_iteration = 1;\n\n    while (true) {\n        //complex<double> rho_i = r_hat.dot(r_prev);\n        complex<double> rho_i = dot_product(r_hat, r_prev);\n        complex<double> beta = (rho_i/rho_prev)*(alpha/w_prev);\n        ComplexVector pi = r_prev + beta*(p_prev - w_prev*v_prev);\n        ComplexVector vi = matrix_vector_product(A, pi);\n\n        //alpha = rho_i/r_hat.dot(vi);\n        alpha = rho_i/dot_product(r_hat, vi);\n        ComplexVector h = x_prev + alpha*pi;\n\n        ComplexVector s = r_prev - alpha*vi;\n        ComplexVector t = matrix_vector_product(A, s);\n        //complex<double> w_i = t.dot(s)/t.dot(t);\n        complex<double> w_i = dot_product(t,s)/dot_product(t,t);\n        ComplexVector xi = h + w_i*s;\n        ComplexVector ri = s - w_i*t;\n\n        error = ri.norm();\n        if (error < tolerance || current_iteration > maxiter)\n            return xi;\n\n        x_prev   = xi;\n        r_prev   = ri;\n        rho_prev = rho_i;\n        v_prev   = vi;\n        p_prev   = pi;\n        w_prev   = w_i;\n\n        current_iteration += 1;\n    }\n}\n\nComplexVector solve_linear_system(const Ref<const ComplexMatrix>& agg_tmatrix,\n        const Ref<const ComplexVector>& p_src, solver method) {\n\n    ComplexMatrix interaction_matrix = agg_tmatrix;\n    for (int i = 0; i < interaction_matrix.cols(); i++)\n        interaction_matrix(i,i) += 1;\n    \n    switch (method) {\n        case solver::exact:  // TODO: implment\n        default:\n        case solver::bicgstab:\n            //Eigen::BiCGSTAB<ComplexMatrix> solver;\n            //solver.setTolerance(1e-5);\n            //solver.compute(interaction_matrix);\n            //return solver.solveWithGuess(p_src, p_src);\n            return bicgstab(interaction_matrix, p_src);\n    }\n}\n\nComplexMatrix sphere_aggregate_tmatrix(const Ref<const position_t>& positions,\n        const Ref<const ComplexMatrix>& mie, double k) {\n\n    int lmax = mie.cols()/2;\n    int rmax = lmax_to_rmax(lmax);\n    int Nparticles = positions.rows();\n    int size = 2*rmax*Nparticles;\n\n    ComplexMatrix agg_tmatrix = ComplexMatrix::Zero(size, size);\n\n    if (Nparticles == 1)\n        return agg_tmatrix;\n    \n    int N = Nparticles*(Nparticles-1)/2;\n    Array ivals(N);\n    Array jvals(N);\n    int counter = 0;\n\n    for (int i = 0; i < Nparticles; i++) {\n        for (int j = i+1; j < Nparticles; j++) {\n            ivals(counter) = i;\n            jvals(counter) = j;\n            counter += 1;\n        }\n    }\n    \n    auto vsh_precompute = create_vsh_cache_map(lmax);\n\n    #pragma omp parallel for\n    for (int ij = 0; ij < N; ij++) {\n        int i = ivals(ij);\n        int j = jvals(ij);\n\n        Vector3d dji = positions.row(i) - positions.row(j);\n\n        double rad = dji.norm();\n        double theta = acos(dji(2)/rad);\n        double phi = atan2(dji(1), dji(0));\n\n        vsh_translation_insert_pair(agg_tmatrix, mie, i, j, rad, theta, phi, k, vsh_precompute);\n    } \n\n    return agg_tmatrix;\n}\n\nComplexMatrix particle_aggregate_tmatrix(const Ref<const position_t>& positions,\n        const tmatrix_t& tmatrix, double k) {\n\n    int rmax = tmatrix.dimensions()[1]/2;\n    int lmax = rmax_to_lmax(rmax);\n\n    int Nparticles = positions.rows();\n    int size = 2*rmax*Nparticles;\n\n    ComplexMatrix agg_tmatrix = ComplexMatrix::Zero(size, size);\n\n    if (Nparticles == 1)\n        return agg_tmatrix;\n    \n    int N = Nparticles*(Nparticles-1)/2;\n    Array ivals(N);\n    Array jvals(N);\n    int counter = 0;\n\n    for (int i = 0; i < Nparticles; i++) {\n        for (int j = i+1; j < Nparticles; j++) {\n            ivals(counter) = i;\n            jvals(counter) = j;\n            counter += 1;\n        }\n    }\n    \n    auto vsh_precompute = create_vsh_cache_map(lmax);\n\n    #pragma omp parallel for\n    for (int ij = 0; ij < N; ij++) {\n        int i = ivals(ij);\n        int j = jvals(ij);\n\n        Vector3d dji = positions.row(i) - positions.row(j);\n\n        double rad = dji.norm();\n        double theta = acos(dji(2)/rad);\n        double phi = atan2(dji(1), dji(0));\n\n        vsh_translation_insert_pair(agg_tmatrix, tmatrix, i, j, rad, theta, phi, k, vsh_precompute);\n    } \n\n    return agg_tmatrix;\n}\n\nComplexMatrix reflection_matrix_nia(const Ref<const position_t>& positions,\n        const Ref<const ComplexMatrix>& mie, double k, complex<double> reflection, double z) {\n\n    int lmax = mie.cols()/2;\n    int rmax = lmax_to_rmax(lmax);\n    int Nparticles = positions.rows();\n    int size = 2*rmax*Nparticles;\n\n    ComplexMatrix R_matrix = ComplexMatrix::Zero(size, size);\n    \n    for (int i = 0; i < Nparticles; i++) {\n        Vector3d pi = positions.row(i);\n        pi(2) -= 2*(pi(2) - z);\n        for (int j = 0; j < Nparticles; j++) {\n            Vector3d pj = positions.row(j);\n            Vector3d dji = pi - pj;\n\n            double rad = dji.norm();\n            double theta = acos(dji(2)/rad);\n            double phi = atan2(dji(1), dji(0));\n\n            for (int n = 1; n < lmax+1; n++) {\n                for (int m = -n; m < n+1; m++) {\n                    for (int v = 1; v < lmax+1; v++) {\n                        for (int u = -v; u < v+1; u++) {\n                            auto transfer = vsh_translation(m, n, u, v, rad, theta, phi, k, vsh_mode::outgoing);\n                            for (int a = 0; a < 2; a++) {\n                                for (int b = 0; b < 2; b++) {\n                                    complex<double> factor = -reflection*pow(-1, m + n + a + 1);\n                                    complex<double> val = transfer[(a+b)%2];\n                                    int idx = i*(2*rmax) + a*(rmax) + n*(n+2) - n + m - 1;\n                                    int idy = j*(2*rmax) + b*(rmax) + v*(v+2) - v + u - 1;\n                                    R_matrix(idx, idy) = factor*val*mie(j, b*lmax + v-1);\n                                } \n                            } \n                        } \n                    } \n                } \n            } \n        } \n    } \n\n    return R_matrix;\n}\n\n", "meta": {"hexsha": "6bd022da96438c206619f268e1af56ab6c3bcd3b", "size": 7658, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/interactions.cpp", "max_stars_repo_name": "johnaparker/MiePy", "max_stars_repo_head_hexsha": "5c5bb5a07c8ab79e9e2a9fc79fb9779e690147be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-05-30T06:45:29.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-30T19:58:56.000Z", "max_issues_repo_path": "cpp/src/interactions.cpp", "max_issues_repo_name": "johnaparker/MiePy", "max_issues_repo_head_hexsha": "5c5bb5a07c8ab79e9e2a9fc79fb9779e690147be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/interactions.cpp", "max_forks_repo_name": "johnaparker/MiePy", "max_forks_repo_head_hexsha": "5c5bb5a07c8ab79e9e2a9fc79fb9779e690147be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-12-13T02:05:31.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-23T07:11:30.000Z", "avg_line_length": 30.1496062992, "max_line_length": 112, "alphanum_fraction": 0.5507965526, "num_tokens": 2082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5408771102690515}}
{"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\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_math_quaternion_rotate);\r\n\r\nBOOST_AUTO_TEST_CASE(simple_test)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double,size_t> math_types;\r\n\r\n  typedef math_types::value_traits     value_traits;\r\n  typedef math_types::real_type        T;\r\n  typedef math_types::vector3_type     V;\r\n  typedef math_types::quaternion_type  Q;\r\n\r\n  {\r\n    // Set up a test rotation\r\n    Q q;\r\n    T const phi = value_traits::pi_half();\r\n    V const m = V( 1.0, 0.0, 0.0 );\r\n    q.Ru( phi, m);\r\n    V const n = V( 0.0, 1.0, 0.0 );\r\n    // Try to rotate n-vector\r\n    V const k = rotate( q, n);\r\n    // Test if result is what we expect\r\n    BOOST_CHECK( fabs( k(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( k(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( 1.0 - k(2) ) < 10e-10 );\r\n  }\r\n  {\r\n    // Set up a test rotation\r\n    Q q;\r\n    T const phi = value_traits::pi_half();\r\n    V const m = V( 1.0, 0.0, 0.0 );\r\n    q.Ru( phi, m);\r\n    V const n = V( 0.0, 0.0, 1.0 );\r\n    // Try to rotate n-vector\r\n    V const k = rotate( q, n);\r\n    // Test if result is what we expect\r\n    BOOST_CHECK( fabs( k(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( 1.0 + k(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( k(2) ) < 10e-10 );\r\n  }\r\n  {\r\n    // Set up a test rotation\r\n    Q q;\r\n    T const phi = value_traits::pi_half();\r\n    V const m = V( 1.0, 0.0, 0.0 );\r\n    q.Ru( phi, m);\r\n    V const n = V( 0.0, -1.0, 0.0 );\r\n    // Try to rotate n-vector\r\n    V const k = rotate( q, n);\r\n    // Test if result is what we expect\r\n    BOOST_CHECK( fabs( k(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( k(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( 1.0 + k(2) ) < 10e-10 );\r\n  }\r\n  {\r\n    // Set up a test rotation\r\n    Q q;\r\n    T const phi = value_traits::pi_half();\r\n    V const m = V( 1.0, 0.0, 0.0 );\r\n    q.Ru( phi, m);\r\n    V const n = V( 0.0, 0.0, -1.0 );\r\n    // Try to rotate n-vector\r\n    V const k = rotate( q, n);\r\n    // Test if result is what we expect\r\n    BOOST_CHECK( fabs( k(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( 1.0 - k(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( k(2) ) < 10e-10 );\r\n  }\r\n  {\r\n    // Set up a test rotation\r\n    Q q;\r\n    T const phi = value_traits::pi_half();\r\n    V const m = V( 0.0, 1.0, 0.0 );\r\n    q.Ru( phi, m);\r\n    V const n = V( 1.0, 0.0, 0.0 );\r\n    // Try to rotate n-vector\r\n    V const k = rotate( q, n);\r\n    // Test if result is what we expect\r\n    BOOST_CHECK( fabs( k(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( k(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( 1.0 + k(2) ) < 10e-10 );\r\n  }\r\n  {\r\n    // Set up a test rotation\r\n    Q q;\r\n    T const phi = value_traits::pi_half();\r\n    V const m = V( 0.0, 0.0, 1.0 );\r\n    q.Ru( phi, m);\r\n    V const n = V( 1.0, 0.0, 0.0 );\r\n    // Try to rotate n-vector\r\n    V const k = rotate( q, n);\r\n    // Test if result is what we expect\r\n    BOOST_CHECK( fabs( k(0) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( 1.0 - k(1) ) < 10e-10 );\r\n    BOOST_CHECK( fabs( k(2) ) < 10e-10 );\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "bca291dd1b6ecae59bcb80721ea723835be9e769", "size": 3543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/rotate/src/unit_rotate.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/rotate/src/unit_rotate.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/rotate/src/unit_rotate.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": 30.5431034483, "max_line_length": 79, "alphanum_fraction": 0.5687270675, "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.61878043374385, "lm_q1q2_score": 0.5408618907009419}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#include \"PoseInterpolator.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"Utils/cv.h\"\n#include <boost/optional.hpp>\n\n#include <arcana/analysis/object_trace.h>\n#include <arcana/analysis/data_point.h>\n\nnamespace E = Eigen;\n\nnamespace mage\n{\n    using seconds = std::chrono::duration<double>;\n\n    struct alignas(16) PoseInterpolator::Impl\n    {\n        mage::SensorSample::Timestamp m_gyroTime{};\n        mage::SensorSample::Timestamp m_accelTime{};\n\n        mage::Pose m_previousPose;\n\n        std::vector<std::pair<E::Vector3d, mage::SensorSample::Timestamp>, E::aligned_allocator<E::Vector3d>> m_positionHistory;\n\n        Eigen::Vector3d Acceleration = Eigen::Vector3d::Zero();\n        Eigen::Vector3d Velocity = Eigen::Vector3d::Zero();\n        Eigen::Vector3d Position = Eigen::Vector3d::Zero();\n\n        E::AngleAxisd AngularVelocity = E::AngleAxisd::Identity();\n        Eigen::Quaterniond Orientation = Eigen::Quaterniond::Identity();\n\n        void ProcessAngularVelocityUntil(mage::SensorSample::Timestamp ts)\n        {\n            if (m_gyroTime == mage::SensorSample::Timestamp{})\n                m_gyroTime = ts;\n\n            seconds dt = ts - m_gyroTime;\n\n            E::AngleAxisd av = AngularVelocity;\n            av.angle() *= dt.count();\n\n            Orientation = Orientation * av;\n            Orientation.normalize();\n\n            m_gyroTime = ts;\n        }\n\n        void ProcessLinearVelocityUntil(mage::SensorSample::Timestamp ts)\n        {\n            if (m_accelTime == mage::SensorSample::Timestamp{})\n                m_accelTime = ts;\n\n            seconds dt = ts - m_accelTime;\n\n            Position += Velocity * dt.count();\n\n            m_accelTime = ts;\n        }\n\n        void ProcessPose(mage::SensorSample::Timestamp ts, const mage::Pose& pose)\n        {\n            assert(m_positionHistory.empty() || ts >= m_positionHistory.back().second);\n\n            ProcessAngularVelocityUntil(ts);\n            ProcessLinearVelocityUntil(ts);\n\n            auto transform = Decompose(pose.GetInverseViewMatrix());\n\n            Orientation = transform.second.cast<double>();\n            Position = ToMap(transform.first).cast<double>();\n\n            if (!m_positionHistory.empty())\n            {\n                seconds dt = ts - m_positionHistory.back().second;\n                auto previous = Decompose(m_previousPose.GetInverseViewMatrix());\n\n                E::Vector3d previousPosition = ToMap(previous.first).cast<double>();\n\n                Velocity = (Position - previousPosition) / dt.count();\n\n                AngularVelocity = (transform.second * previous.second.inverse()).cast<double>();\n                AngularVelocity.angle() /= dt.count();\n            }\n\n            m_previousPose = pose;\n\n            m_positionHistory.push_back(make_pair(Position, ts));\n            if (m_positionHistory.size() == 3)\n            {\n                auto dt = seconds(m_positionHistory[2].second - m_positionHistory[1].second).count();\n\n                Velocity = (m_positionHistory[2].first - m_positionHistory[1].first) / dt;\n\n                E::Vector3d accel = (m_positionHistory[2].first - 2 * m_positionHistory[1].first + m_positionHistory[0].first) / (dt * dt);\n\n                FIRE_OBJECT_TRACE(\"IMU Linear Accel.PoseInterpolator\", this, (mira::make_data_point<float>(\n                    m_positionHistory[1].second,\n                    (float)accel.norm()\n                )));\n\n                m_positionHistory.erase(m_positionHistory.begin());\n            }\n\n            FIRE_OBJECT_TRACE(\"IMU Linear Velocity.PoseInterpolator\", this, (mira::make_data_point<float>(\n                ts,\n                (float)Velocity.norm()\n            )));\n        }\n    };\n\n    PoseInterpolator::PoseInterpolator()\n        : m_impl{ std::allocate_shared<Impl, Eigen::aligned_allocator<Impl>>({}) }\n    {}\n\n    PoseInterpolator::~PoseInterpolator() = default;\n\n    mage::Pose PoseInterpolator::GetPose() const\n    {\n        Eigen::Vector3f position{ m_impl->Position.cast<float>() };\n        return mage::Pose(FromQuatAndTrans(m_impl->Orientation.cast<float>(), { position.x(), position.y(), position.z() }));\n    }\n\n    void PoseInterpolator::PredictUpTo(mage::SensorSample::Timestamp ts)\n    {\n        m_impl->ProcessAngularVelocityUntil(ts);\n        m_impl->ProcessLinearVelocityUntil(ts);\n    }\n\n    void PoseInterpolator::AddPose(const mage::Pose& pose, mage::SensorSample::Timestamp timestamp)\n    {\n        m_impl->ProcessPose(timestamp, pose);\n    }\n}\n", "meta": {"hexsha": "5585eb47d6094018f2e96b02b7ed2fa3eb9c94fa", "size": 4567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Core/MAGESLAM/Source/Fuser/PoseInterpolator.cpp", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Fuser/PoseInterpolator.cpp", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Fuser/PoseInterpolator.cpp", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 32.8561151079, "max_line_length": 139, "alphanum_fraction": 0.6074009196, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5408618866414588}}
{"text": "#include <iostream>\n#include <mtl/dense1D.h>\n#include <mtl/mtl.h>\n\n\n/*\n  example output:\n\n  2\n\n  */\n\nint\nmain()\n{\n  //begin\n  mtl::dense1D< float > x(10, 3.0);\n  x[5] = 2.0;\n  float s = mtl::min(x);\n  std::cout << s << std::endl;\n  // end\n  return 0;\n}\n\n", "meta": {"hexsha": "26cd9834434583786154c41a83eff31cb5d3ffe5", "size": 254, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/vec_min.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/tools/mtl-2.0/contrib/examples/vec_min.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/tools/mtl-2.0/contrib/examples/vec_min.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": 10.16, "max_line_length": 35, "alphanum_fraction": 0.531496063, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5408539779444985}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n \n\n#pragma once\n\n#include <stdint.h>\n#include <algorithm>\n#include <vector>\n#include <Eigen/Dense>\n\n#include <boost/random/mersenne_twister.hpp>\n\n#include <dpMM/global.hpp>\n#include <dpMM/normal.hpp>\n\nusing  namespace Eigen;\nusing std::min;\nusing std::max;\nusing std::cout;\nusing std::endl;\n\n#ifdef BOOST_OLD\nusing boost::mt19937;\n#else\nusing boost::mt19937;\n#endif\n\n\n// TODO Template needs fixing - probably just remove\ntemplate <typename T>\nclass Sphere\n{\npublic:\n  Sphere(uint32_t D) : D_(D), north_(Matrix<T,Dynamic,1>::Zero(D))\n  {north_(D_-1) = 1.0;};\n  \n  //assumes north is size D and last entry is 1\n  Sphere(Matrix<T,Dynamic,1> north) : D_(north.rows()), north_(north)\n  {};\n  virtual ~Sphere() {};\n\n  /* \n   * normal in tangent space around p rotate to the north pole\n   * -> the last dimension will always be 0\n   * -> return only first 2 dims\n   */\n  virtual Matrix<T,Dynamic,Dynamic> Log_p_north(const Matrix<T,Dynamic,1>& p, \n      const Matrix<T,Dynamic,Dynamic>& q) const;\n  /* \n   * rotate points x in tangent plane around north pole down to p\n   */\n  Matrix<T,Dynamic,Dynamic> rotate_north2p(const Matrix<T,Dynamic,1>& p, \n      const Matrix<T,Dynamic,Dynamic>& xNorth) const;\n\n  /* rotate points x in tangent plane around p to north pole and\n   * return 2D coordinates */\n  Matrix<T,Dynamic,Dynamic> rotate_p2north(const Matrix<T,Dynamic,1>& p, \n      const Matrix<T,Dynamic,Dynamic>& x) const;\n  void rotate_p2north( const Matrix<T,Dynamic,Dynamic>& ps, \n    const Matrix<T,Dynamic,Dynamic>& x, Matrix<T,Dynamic,Dynamic>& xNorth,\n    const VectorXu& z, uint32_t K) const;\n  void rotate_p2north(const Matrix<T,Dynamic,1>& p, \n    const Matrix<T,Dynamic,Dynamic>& x_p, Matrix<T,Dynamic,Dynamic>& xNorth,\n    const VectorXu& z, uint32_t k) const;\n\n\n  /* compute rotation from TpS^2 to north pole on sphere */\n  Matrix<T,Dynamic,Dynamic> north_R_TpS2(const Matrix<T,Dynamic,1>& p) const;\n\n  /* compute logarithm map from sphere to T_pS */\n  Matrix<T,Dynamic,Dynamic> Log_p(const Matrix<T,Dynamic,1>& p, \n      const Matrix<T,Dynamic,Dynamic>& q) const;\n  Matrix<T,Dynamic,1> Log_p_single(const Matrix<T,Dynamic,1>& p, \n      const Matrix<T,Dynamic,1>& q) const;\n  /* compute logarithm map from sphere to T_pS skips points where w_i==0 */\n  Matrix<T,Dynamic,Dynamic> Log_p(const Matrix<T,Dynamic,1>& p, \n    const Matrix<T,Dynamic,Dynamic>& q, const Matrix<T,Dynamic,1>& w) const;\n  /* compute logmap for q where z_i ==k; leaves other x_i untouched */\n  void Log_p(const Matrix<T,Dynamic,1>& p, \n    const Matrix<T,Dynamic,Dynamic>& q, const VectorXu& z, uint32_t k,\n    Matrix<T,Dynamic,Dynamic>& x, uint32_t zDivider=1) const;\n  /* compute logarithm map from sphere to T_pS around several points p \n   * indicated by labels z; fill in matrix x */\n  void Log_ps(const Matrix<T,Dynamic,Dynamic>& p, \n    const Matrix<T,Dynamic,Dynamic>& q, const VectorXu& z, \n    Matrix<T,Dynamic,Dynamic>& x) const;\n\n  /* compute exponential map from T_pS to sphere */\n  Matrix<T,Dynamic,Dynamic> Exp_p(const Matrix<T,Dynamic,1>& p, \n      const Matrix<T,Dynamic,Dynamic>& x) const;\n  Matrix<T,Dynamic,1> Exp_p_single(const Matrix<T,Dynamic,1>& p, \n    const Matrix<T,Dynamic,1>& x) const;\n\n  Matrix<T,Dynamic,1> sampleUnif(mt19937* pRndGen);\n \n  // http://en.wikipedia.org/wiki/N-sphere\n  // http://keisan.casio.com/exec/system/1223381019\n  T logSurfaceArea() const {\n    return (LOG_2+0.5*D_*LOG_PI - boost::math::lgamma(0.5*D_));};\n\n  uint32_t D() const {return D_;};\n  const Matrix<T,Dynamic,1>& north() const {return north_;};\nprotected:\n\n  T invSincDot(T dot) const;\n\n  //static const double MIN_DOT = -0.95;\n  //static const double MAX_DOT = 0.95;\n  static double const MIN_DOT;\n  static double const MAX_DOT;\n  uint32_t D_; // dimension of ambient space; sphere is D-1 dimensional.\n  Matrix<T,Dynamic,1> north_;\n};\n\n/* rotation from point A to B; percentage specifies how far the rotation will \n * bring us towards B [0,1] */\ntemplate<typename T>\ninline Matrix<T,Dynamic,Dynamic> rotationFromAtoB(const Matrix<T,Dynamic,1>& a,\n    const Matrix<T,Dynamic,1>& b, T percentage=1.0)\n{\n  assert(b.size() == a.size());\n\n  uint32_t D_ = b.size();\n  Matrix<T,Dynamic,Dynamic> bRa(D_,D_);\n   \n  T dot = b.transpose()*a;\n  ASSERT(fabs(dot) <=1.0, \"a=\"<<a.transpose()<<\" |.| \"<<a.norm()\n      <<\" b=\"<<b.transpose()<<\" |.| \"<<b.norm()\n      <<\" -> \"<<dot);\n  dot = max(static_cast<T>(-1.0),min(static_cast<T>(1.0),dot));\n//  cout << \"dot=\"<<dot<<\" | |\"<<fabs(dot+1.)<<endl;\n  if(fabs(dot -1.) < 1e-6)\n  {\n    // points are almost the same -> just put identity\n    bRa =  Matrix<T,Dynamic,Dynamic>::Identity(D_,D_);\n//    bRa(0,0) = cos(percentage*PI);\n//    bRa(1,1) = cos(percentage*PI);\n//    bRa(0,1) = -sin(percentage*PI);\n//    bRa(1,0) = sin(percentage*PI);\n  }else if(fabs(dot +1.) <1e-6) \n  {\n    // direction does not matter since points are on opposing sides of sphere\n    // -> pick one and rotate by percentage;\n    bRa = -Matrix<T,Dynamic,Dynamic>::Identity(D_,D_);\n    bRa(0,0) = cos(percentage*PI*0.5);\n    bRa(1,1) = cos(percentage*PI*0.5);\n    bRa(0,1) = -sin(percentage*PI*0.5);\n    bRa(1,0) = sin(percentage*PI*0.5);\n  }else{\n    T alpha = acos(dot) * percentage;\n//    cout << \"alpha=\"<<alpha<<endl;\n\n    Matrix<T,Dynamic,1> c(D_);\n    c = a - b*dot;\n    ASSERT(c.norm() >1e-5, \"c=\"<<c.transpose()<<\" |.| \"<<c.norm());\n    c /= c.norm();\n    Matrix<T,Dynamic,Dynamic> A = b*c.transpose() - c*b.transpose();\n\n\tMatrix<T,Dynamic,Dynamic> temp = b*b.transpose() + c*c.transpose(); \n\tT temp2 = cos(alpha)-1.; \n    bRa = Matrix<T,Dynamic,Dynamic>::Identity(D_,D_) + sin(alpha)*A + \n      (temp2)*(temp);\n  }\n  return bRa;\n}\n\n", "meta": {"hexsha": "5d0b57548e9c4a2602b3a45f9974d3be63dc5968", "size": 5767, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/sphere.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/sphere.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/sphere.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": 34.124260355, "max_line_length": 79, "alphanum_fraction": 0.6597884515, "num_tokens": 1766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5408539653259424}}
{"text": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <vector>\n#include <Eigen/Dense>\n#include <iomanip>\n#include <cmath>\n#include <math.h>\n#include <float.h>\n#include <algorithm>\n#include \"ANN.cpp\"\n\n\nusing namespace Eigen;\n\nMatrixXd getTril(MatrixXd& mat) {\n\tMatrixXd tril = mat.triangularView<Lower>();\n\tfor (int i = 0; i < tril.rows(); i++)\n\t\ttril(i,i) = 0;\n\treturn tril;\n}\n\nvoid appendVec2Mat(MatrixXd& mat, VectorXd vec) {\n\tmat.conservativeResize(mat.rows(), mat.cols()+1);\n\tmat.col(mat.cols()-1) = vec;\n}\n\nVectorXd StdVec2Eigen(std::vector <double> vec){\n  VectorXd outvec(vec.size());\n  for(int i=0;i<vec.size();i++)\n    outvec(i)=vec[i];\n  return outvec;\n}\n\nstd::vector <double> EigenVec2Std(VectorXd vec){\n  std::vector <double> outvec(vec.rows(),0.0);\n  for(int i=0;i<vec.rows();i++)\n    outvec[i]=vec(i);\n  return outvec;\n}\n\n\nclass ObjFunc{\npublic:\n  \tvoid init(ANN& input) {\n  \t\tnnet = input;\n  \t\ttarget = VectorXd::Constant(20,0);\n  \t}\n  \tvoid setTarget(VectorXd input) {\n  \t\tfor (int i = 0; i < 10; i++) {\n  \t\t\ttarget(2*i) = input(i);\n  \t\t\ttarget(2*i + 1) = input(i);\n  \t\t}\n  \t}\n //  \tVectorXd evalANN(VectorXd input){\n //  \t\tstd::vector<double> temperature = nnet.ComputeANN(EigenVec2Std(input));\n\t// \tVectorXd output(10);\n\t// \tfor(int i=0;i<10;i++){\n\t// \t\toutput(i)=\t0.5*(0.15*temperature[3*i] + \n\t// \t\t\t\t\t0.85*temperature[3*i+1] + \n\t// \t\t\t\t\t0.85*temperature[3*i+2] + \n\t// \t\t\t\t\t0.15*temperature[3*i+3]);\n\t// \t}\n\t// \treturn output;\n\t// }\n  \tVectorXd evalANN(VectorXd input){\n  \t\tstd::vector<double> temperature = nnet.ComputeANN(EigenVec2Std(input));\n\t\tVectorXd output(20);\n\t\tfor(int i=0;i<10;i++){\n\t\t\toutput(2 * i) = (temperature[3*i] + temperature[3*i + 1]) * 0.015 / 2 + \n\t\t\t(1.5 * temperature[3*i + 1] + 0.5 * temperature[3*i + 2]) * 0.035 / 2;\n\t\t\toutput(2 * i) /= 0.05;\n\t\t\toutput(2 * i + 1) = (temperature[3*i + 2] + temperature[3*i + 3]) * 0.015 / 2 + \n\t\t\t(0.5 * temperature[3*i + 1] + 1.5 * temperature[3*i + 2]) * 0.035 / 2;\n\t\t\toutput(2*i + 1) /= 0.05;\n\t\t}\n\t\treturn output;\n\t}\n\tvoid eval(double& f, VectorXd& g, VectorXd input){\n\t\tVectorXd output = evalANN(input);\n\t\t// std::cout << output << std::endl;\n\t\tint n = input.rows();\n\t\tf = (output - target).dot(output - target);\n\t\tVectorXd gradient = VectorXd::Constant(n,0.0);\n\t\tdouble delta = 0.01;\n\t\t// std::cout << \"BP\\n\";\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tVectorXd d_input = VectorXd::Constant(n,0.0);\n\t\t\td_input(i) = delta;\n\t\t\tVectorXd temp_output1 = evalANN(input + d_input);\n\t\t\tVectorXd temp_output2 = evalANN(input - d_input);\n\t\t\tgradient(i) = (temp_output1 - target).dot(temp_output1 - target) - \n\t\t\t\t\t\t\t(temp_output2 - target).dot(temp_output2 - target);\n\t\t\tgradient(i) /= 2*delta;\n\t\t}\n\t\tg = gradient;\n\t}\nprivate:\n\tANN nnet;\n\tVectorXd target;\n};\n\n\nvoid quickSort(std::vector<double>& arr, std::vector<int>& indices, int left, int right) {\n\tint i = left, j = right;\n\tdouble pivot = arr[(left + right) / 2];\n\t/*partition*/\n\twhile (i <= j) {\n\t\twhile (arr[i] < pivot)\n\t\t\ti++;\n\t\twhile (arr[j] > pivot)\n\t\t\tj--;\n\t\tif (i <= j) {\n\t\t\tdouble tmp_v = arr[i];\n\t\t\tint tmp_i = indices[i];\n\t\t\tarr[i] = arr[j];\n\t\t\tindices[i] = indices[j];\n\t\t\tarr[j] = tmp_v;\n\t\t\tindices[j] = tmp_i;\n\t\t\ti++;\n\t\t\tj--;\n\t\t}\n\t}\n\t/*recursion*/\n\tif (left < j)\n\t\tquickSort(arr, indices, left, j);\n\tif (i < right)\n\t\tquickSort(arr, indices, i, right);\n}\n\nstruct LBFGSBParam{\n\tint m;\n\tint max_iters;\n\tdouble tol;\n\tbool display;\n\tbool xhistory;\n};\n\nstruct BPOutput{\n\tVectorXd t;\n\tVectorXd d;\n\tstd::vector<int> F;\n};\n\nstruct CauchyOutput{\n\tVectorXd xc;\n\tVectorXd c;\n};\n\nstruct SubspaceMinOutput{\n\tVectorXd xbar;\n\tbool line_search_flag;\n};\n\n\nstruct LBFGSB_Output {\n\tVectorXd x;\n\tdouble obj;\n};\n\nclass LBFGSB{\npublic:\n\tLBFGSBParam param;\n\tLBFGSB_Output solve(ObjFunc& obj, VectorXd x0, VectorXd l, VectorXd u, LBFGSBParam params);\nprivate:\n\tdouble f;\n\tVectorXd g;\n\tdouble getOptimality(VectorXd x, VectorXd g, VectorXd l, VectorXd u);\n\tBPOutput getBreakpoints(VectorXd x, VectorXd g, VectorXd l, VectorXd u);\n\tCauchyOutput getCauchyPoint(VectorXd x, VectorXd g, VectorXd l, VectorXd u,\n\t\t\t\t\t\t\t\tdouble theta, MatrixXd W, MatrixXd M);\n\tdouble findAlpha(VectorXd l, VectorXd u, VectorXd xc, VectorXd du, \n\t\t\t\t\tstd::vector<int> free_vars_idx);\n\tSubspaceMinOutput subspaceMin(VectorXd x, VectorXd g, VectorXd l, VectorXd u,\n\t\t\t\t\t\tVectorXd xc, VectorXd c, double theta, MatrixXd W, MatrixXd M);\n\tdouble strongWolfe(ObjFunc& obj, VectorXd x0, double f0, VectorXd g0, VectorXd p);\n\tdouble alphaZoom(ObjFunc& obj, VectorXd x0, double f0, VectorXd g0, VectorXd p,\n\t\t\t\t\tdouble alpha_lo, double alpha_hi);\n};\n\ndouble LBFGSB::getOptimality(VectorXd x, VectorXd g, VectorXd l, VectorXd u){\n\tVectorXd projected_g = x - g;\n\tfor(int i = 0; i < x.rows(); i++) {\n\t\tif (projected_g(i) < l(i))\n\t\t\tprojected_g(i) = l(i);\n\t\telse if (projected_g(i) > u(i))\n\t\t\tprojected_g(i) = u(i);\n\t}\n\tprojected_g = projected_g - x;\n\treturn projected_g.cwiseAbs().maxCoeff();\n}\n\nBPOutput LBFGSB::getBreakpoints(VectorXd x, VectorXd g, VectorXd l, VectorXd u){\n\tint nn = x.rows();\n\tVectorXd t = VectorXd::Constant(nn,0.0);\n\tVectorXd d = -g;\n\tfor (int i = 0; i < nn; i++) {\n\t\tif (g(i) < 0)\n\t\t\tt(i) = (x(i) - u(i)) / g(i);\n\t\telse if (g(i) > 0) \n\t\t\tt(i) = (x(i) - l(i)) / g(i);\n\t\telse\n\t\t\tt(i) = DBL_MAX;\n\t\tif (t(i) < DBL_EPSILON)\n\t\t\td(i) = 0.0;\n\t}\n\t// Sort elements of t and store indices in F\n\tstd::vector<int> Fvec(nn, 0);\n\tstd::vector<double> tvec(nn,0.0);\n\tfor (int i = 0; i < nn; i++){\n\t\ttvec[i] = t(i);\n\t\tFvec[i] = i;\n\t\t// std::cout << tvec[i] << \" \" << Fvec[i] <<std::endl;\n\t}\n\t//std::cout<<nn<<std::endl;\n\t// std::cout<<\"BP_quicksort\\n\";\n\tquickSort(tvec, Fvec, 0, nn-1);\n\t// std::cout<<\"BP_after_quicksort\\n\";\n\n\tBPOutput bpout;\n\tbpout.t = t;\n\tbpout.d = d;\n\tbpout.F = Fvec;\n\treturn bpout;\n}\n\nCauchyOutput LBFGSB::getCauchyPoint(VectorXd x, VectorXd g, VectorXd l, VectorXd u,\n\t\t\t\t\t\t\t\tdouble theta, MatrixXd W, MatrixXd M){\n\n\t//std::cout << \"BP0\" << std::endl;\n\tBPOutput bpout = getBreakpoints(x, g, l, u);\n\t// std::cout << \"t = \" << std::endl << bpout.t << std::endl;\n\t// std::cout << \"d = \" << std::endl << bpout.d << std::endl;\n\t// std::cout << \"F = \" << std::endl;\n\t// for (int i = 0; i < bpout.F.size(); i++) {\n\t// \tstd::cout << bpout.F[i] << std::endl;\n\t// }\n\tVectorXd xc = x;\n\t//std::cout << \"BP01\" << std::endl;\n\tVectorXd p = W.transpose() * bpout.d;\n\tVectorXd c = VectorXd::Constant(W.cols(), 0.0);\n\tdouble fp = - bpout.d.transpose() * bpout.d;\n\tdouble fpp = -theta * fp - p.dot(M * p);\n\tdouble fpp0 = -theta * fp;\n\tdouble dt_min = -fp / fpp;\n\tdouble t_old = 0;\n\tint i;\n\t//std::cout << \"BP1\" << std::endl;\n\tfor (int j = 0; j < x.rows(); j++) {\n\t\ti = j;\n\t\tif (bpout.F[i] > 0)\n\t\t\tbreak;\n\t}\n\tint b = bpout.F[i];\n\tdouble t = bpout.t(b);\n\tdouble dt = t - t_old;\n\t//std::cout << \"BP2\" << std::endl;\n\n\twhile ( (dt_min > dt) && (i < x.rows()) ) {\n\t\tif (bpout.d(b) > 0)\n\t\t\txc(b) = u(b);\n\t\telse if (bpout.d(b) < 0)\n\t\t\txc(b) = l(b);\n\t\t//std::cout << \"BP3\" << std::endl;\n\t\tdouble zb = xc(b) - x(b);\n\t\tc = c + dt * p;\n\t\tdouble gb = g(b);\n\t\tVectorXd wbt = W.row(b);\n\t\tfp += dt * fpp + gb * gb + theta * gb * zb - gb * wbt.dot(M * c);\n\t\tfpp -= theta * gb * gb - 2.0 * gb * wbt.dot(M * p) - gb * gb * wbt.dot(M * wbt);\n\t\tfpp = std::max(DBL_EPSILON * fpp0, fpp);\n\t\tp += gb * wbt;\n\t\tbpout.d(b) = 0.0;\n\t\tdt_min = -fp / fpp;\n\t\tt_old = t;\n\t\ti++;\n\t\tif (i < x.rows()){\n\t\t\tb = bpout.F[i];\n\t\t\tt = bpout.t(b);\n\t\t\tdt = t - t_old;\n\t\t}\n\t}\n\t// Perform final updates\n\tdt_min = std::max(dt_min, 0.0);\n\tt_old = t_old + dt_min;\n\tfor (int j = 0; j < xc.rows(); j++) {\n\t\tint idx = bpout.F[j];\n\t\txc(idx) += t_old * bpout.d(idx);\n\t}\n\tc += dt_min * p;\n\n\tCauchyOutput cpout;\n\tcpout.c = c;\n\tcpout.xc = xc;\n\treturn cpout;\n}\n\ndouble LBFGSB::findAlpha(VectorXd l, VectorXd u, VectorXd xc, VectorXd du, \n\t\t\t\tstd::vector<int> free_vars_idx) {\n\t// INPUTS:\n\t//  l: [n,1] lower bound constraint vector.\n\t//  u: [n,1] upper bound constraint vector.\n\t//  xc: [n,1] generalized Cauchy point.\n\t//  du: [num_free_vars,1] solution of unconstrained minimization.\n\t// OUTPUTS:\n\t//  alpha_star: positive scaling parameter.\n\tdouble alpha_star = 1;\n\tint n = free_vars_idx.size();\n\tfor (int i = 0; i < n; i++) {\n\t\tint idx = free_vars_idx[i];\n\t\tif (du(i) > 0)\n\t\t\talpha_star = std::min(alpha_star, (u(idx) - xc(idx)) / du(i));\n\t\telse\n\t\t\talpha_star = std::min(alpha_star, (l(idx) - xc(idx)) / du(i));\n\t}\n\treturn alpha_star;\n}\n\n\nSubspaceMinOutput LBFGSB::subspaceMin(VectorXd x, VectorXd g, VectorXd l, VectorXd u,\n\t\t\t\t\t\t\t\tVectorXd xc, VectorXd c, double theta, MatrixXd W, MatrixXd M){\n\tSubspaceMinOutput subminout;\n\tsubminout.line_search_flag = true;\n\n\tint n = x.rows();\n\tstd::vector<int> free_vars_idx;\n\tstd::vector<VectorXd> Z;\n\tfor (int i = 0; i < xc.rows(); i++) {\n\t\tif ((xc(i) != u(i)) && (xc(i) != l(i))) {\n\t\t\tfree_vars_idx.push_back(i);\n\t\t\tVectorXd unit = VectorXd::Constant(n,0);\n\t\t\tunit(i) = 1;\n\t\t\tZ.push_back(unit);\n\t\t}\n\t}\n\n\tint num_free_vars = free_vars_idx.size();\n\tif (num_free_vars == 0) {\n\t\tsubminout.xbar = xc;\n\t\tsubminout.line_search_flag = false;\n\t\treturn subminout;\n\t}\n\n\tMatrixXd ZZ = MatrixXd::Zero(n, num_free_vars);\n\tfor (int i = 0; i < num_free_vars; i++)\n\t\tZZ.col(i) = Z[i];\n\n\t// compute the reduced gradient of mk restricted to free variables\n\tMatrixXd WTZ = W.transpose() * ZZ;\n\tVectorXd rr = g + theta * (xc - x) - W*M*c;\n\tVectorXd r = VectorXd::Constant(num_free_vars, 0.0);\n\tfor (int i = 0; i < num_free_vars; i++)\n\t\tr(i) = rr(free_vars_idx[i]);\n\n\t// form intermediate variables\n\tdouble invtheata = 1.0 / theta;\n\tVectorXd v = M * WTZ * r;\n\tMatrixXd N = invtheata * WTZ * WTZ.transpose();\n\tint N_size = N.rows();\n\tN = MatrixXd::Identity(N_size, N_size) - M * N;\n\tv = N.inverse() * v;\n\tVectorXd du = -invtheata * r - invtheata * invtheata * WTZ.transpose()*v;\n\n\t// find alpha star\n\tdouble alpha_star = findAlpha(l, u, xc, du, free_vars_idx);\n\tVectorXd d_star = alpha_star * du;\n\tsubminout.xbar = xc;\n\tfor (int i = 0; i < num_free_vars; i++) {\n\t\tint idx = free_vars_idx[i];\n\t\tsubminout.xbar(idx) += d_star(i);\n\t}\n\treturn subminout;\n}\n\n\ndouble LBFGSB::strongWolfe(ObjFunc& obj, VectorXd x0, double f0, VectorXd g0, VectorXd p){\n\tdouble alpha; // return value;\n\tdouble c1 = 1e-4;\n\tdouble c2 = 0.9;\n\tdouble alpha_max = 2.5;\n\tdouble alpha_im1 = 0;\n\tdouble alpha_i = 1;\n\tdouble f_im1 = f0;\n\tdouble dphi0 = g0.dot(p);\n\tint i = 0;\n\tint max_iters = 20;\n\tVectorXd x;\n\tdouble f_i;\n\tVectorXd g_i;\n\t// search for alpha that satisfies strong Wolfe conditions\n\twhile (true) {\n\t\tx = x0 + alpha_i * p;\n\t\tobj.eval(f_i, g_i, x);\n\t\tif ((f_i > f0 + c1 * dphi0) || ( (i > 1) && (f_i >= f_im1) )) {\n\t\t\talpha = alphaZoom(obj, x0, f0, g0, p, alpha_im1, alpha_i);\n\t\t\tbreak;\n\t\t}\n\t\tdouble dphi = g_i.dot(p);\n\t\tif (fabs(dphi) <= -c2 * dphi0) {\n\t\t\talpha = alpha_i;\n\t\t\tbreak;\n\t\t}\n\t\tif (dphi >= 0) {\n\t\t\talpha = alphaZoom(obj, x0, f0, g0, p, alpha_i, alpha_im1);\n\t\t\tbreak;\n\t\t}\n\n\t\t// update\n\t\talpha_im1 = alpha_i;\n\t\tf_im1 = f_i;\n\t\talpha_i += 0.8 * (alpha_max - alpha_i);\n\n\t\tif (i > max_iters) {\n\t\t\talpha = alpha_i;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\treturn alpha;\n}\n\n\ndouble LBFGSB::alphaZoom(ObjFunc& obj, VectorXd x0, double f0, VectorXd g0, VectorXd p,\n\t\t\t\tdouble alpha_lo, double alpha_hi) {\n\tdouble alpha; // return value\n\tdouble c1 = 1e-4;\n\tdouble c2 = 0.9;\n\tint i = 0;\n\tint max_iters = 20;\n\tdouble dphi0 = g0.dot(p);\n\tdouble alpha_i;\n\tVectorXd x;\n\tdouble f_i;\n\tVectorXd g_i;\n\n\twhile (true) {\n\t\talpha_i = 0.5 * (alpha_lo + alpha_hi);\n\t\talpha = alpha_i;\n\t\tx = x0 + alpha_lo * p;\n\t\tobj.eval(f_i, g_i, x);\n\t\tVectorXd x_lo = x0 + alpha_lo * p;\n\t\tdouble f_lo;\n\t\tVectorXd dummy_g;\n\t\tobj.eval(f_lo, dummy_g, x_lo);\n\t\tif ( (f_i > f0 + c1 * alpha_i * dphi0) || (f_i >= f_lo) )\n\t\t\talpha_hi = alpha_i;\n\t\telse {\n\t\t\tdouble dphi = g_i.dot(p);\n\t\t\tif (fabs(dphi) <= -c2 * dphi0) {\n\t\t\t\talpha = alpha_i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (dphi * (alpha_hi - alpha_lo) >= 0) {\n\t\t\t\talpha_hi = alpha_lo;\n\t\t\t}\n\t\t\talpha_lo = alpha_i;\n\t\t}\n\t\ti++;\n\t\tif (i > max_iters) {\n\t\t\talpha = alpha_i;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn alpha;\n}\n\nLBFGSB_Output LBFGSB::solve(ObjFunc& obj, VectorXd x0, VectorXd l, \n\t\t\t\t\t\t\tVectorXd u, LBFGSBParam params) {\n\t\n    int rank=0;\n    rank=MPI::COMM_WORLD.Get_rank();\n\n\tint n = x0.rows();\n\tMatrixXd Y(n,0);\n\tMatrixXd S(n,0);\n\tMatrixXd W = MatrixXd::Zero(n,1);\n\tMatrixXd M = MatrixXd::Zero(1,1);\n\tdouble theta = 1;\n\n\t// initialize obj vars\n\tVectorXd x = x0;\n\tdouble f;\n\tVectorXd g;\n\tobj.eval(f, g, x);\n\tint k = 0;\n\tdouble opt;\n\n\tif (params.display && rank == 0) {\n\t\tstd::cout << \"iter\\t\\tf(x)\\t\\toptimality\\n\";\n\t\tstd::cout << \"-------------------------------------\\n\";\n\t\topt = getOptimality(x, g, l, u);\n\t\tstd::cout << k << \"\\t\\t\" << f << \"\\t\\t\" << opt << \"\\t\\t\" << std::endl;\n\t}\n\n\tMatrixXd xhist(n,0);\n\t//std::cout << \"BP0\" << std::endl;\n\tif (params.xhistory) {\n\t\tappendVec2Mat(xhist, x0);\n\t}\n\n\tVectorXd x_old;\n\tVectorXd g_old;\n\tVectorXd y;\n\tVectorXd s;\n\twhile ((getOptimality(x, g, l, u) > params.tol) && (k < params.max_iters) ) {\n\t\tx_old = x;\n\t\tg_old = g;\n\t\t//std::cout << \"BP01\" << std::endl;\n\n\t\tCauchyOutput cpout = getCauchyPoint(x, g, l, u, theta, W, M);\n\t\tVectorXd xc = cpout.xc;\n\t\tVectorXd c = cpout.c;\n\t\t// std::cout << \"xc = \" << std::endl;\n\t\t// std::cout << xc << std::endl;\n\t\t// std::cout << \"c = \" << std::endl;\n\t\t// std::cout << c << std::endl;\n\t\t// std::cout << \"BP1\" << std::endl;\n\t\tSubspaceMinOutput subminout = subspaceMin(x, g, l, u, xc, c, theta, W, M);\n\t\t//std::cout << \"BP2\" << std::endl;\n\n\t\tVectorXd xbar = subminout.xbar;\n\t\tbool line_search_flag = subminout.line_search_flag;\n\n\t\tdouble alpha = 1.0;\n\t\tif (line_search_flag) {\n\t\t\talpha = strongWolfe(obj, x, f, g, xbar - x);\n\t\t}\n\t\tx += alpha * (xbar - x);\n\t\t//std::cout << \"BP3\" << std::endl;\n\n\t\t// update LBFGS data structures\n\t\tobj.eval(f, g, x);\n\t\ty = g - g_old;\n\t\ts = x - x_old;\n\t\tdouble curv = fabs(s.dot(y));\n\t\tif (curv < DBL_EPSILON) {\n\t\t\tif (params.display && rank == 0) {\n    \t\t\tstd::cout << (\" warning: negative curvature detected\\n\");\n    \t\t\tstd::cout << (\"          skipping L-BFGS update\\n\");\n    \t\t}\t\n    \t\tk++;\n    \t\tcontinue;\t\t\n\t\t}\n\n\t\tif (Y.cols() < params.m) {\n\t\t\tappendVec2Mat(Y, y);\n\t\t\tappendVec2Mat(S, s);\n\t\t} else {\n\t\t\tY.block(0, 0, n, params.m - 1) = Y.block(0, 1, n, params.m - 1);\n\t\t\tS.block(0, 0, n, params.m - 1) = S.block(0, 1, n, params.m - 1);\n\t\t\tY.col(params.m - 1) = y;\n\t\t\tS.col(params.m - 1) = s;\n\t\t}\n\t\t//std::cout << \"BP4\" << std::endl;\n\t\ttheta = y.dot(y) / y.dot(s);\n\t\t//std::cout << \"BP401\" << std::endl;\n\t\tMatrixXd temp = Y;\n\t\t//std::cout << \"BP402\" << std::endl;\n\t\ttemp.conservativeResize(temp.rows(), temp.cols()+S.cols());\n\t\ttemp.block(0, Y.cols(), S.rows(), S.cols()) = theta * S;\n\t\t//std::cout << \"BP403\" << std::endl;\n\t\tW = temp;\n\t\t//std::cout << W << std::endl;\n\t\t//std::cout << \"BP41\" << std::endl;\n\t\tMatrixXd A = S.transpose() * Y;\n\t\tMatrixXd L = getTril(A);\n\t\tMatrixXd D = -1 * A.diagonal().asDiagonal();\n\t\tint D_size = D.rows();\n\t\tint L_size = L.rows();\n\n\t\t//std::cout << \"BP42\" << std::endl;\n\n\t\tMatrixXd MM(D_size + L_size, D_size + L_size);\n\t\tMM.block(0, 0, D_size, D_size) = D;\n\t\tMM.block(0, D_size, D_size, L_size) = L.transpose();\n\t\tMM.block(D_size, 0, L_size, D_size) = L;\n\t\tMM.block(D_size, D_size, L_size, L_size) = theta * S.transpose() * S;\n\t\t//std::cout << \"BP43\" << std::endl;\n\t\tM = MM.inverse();\n\t\t//std::cout << \"BP5\" << std::endl;\n\t\t// update the iteration\n\t\tk++;\n\t\tif (params.xhistory) {\n\t\t\tappendVec2Mat(xhist, x);\n\t\t}\n\t\tif (params.display && rank == 0) {\n\t\t\topt = getOptimality(x, g, l, u);\n\t\t\tstd::cout << k << \"\\t\\t\" << f << \"\\t\\t\" << opt << \"\\t\\t\" << std::endl;\n\t\t}\n\t}\n\tif (k == params.max_iters && params.display && rank == 0) {\n\t\tstd::cout << \" warning: maximum number of iterations reached\\n\";\n\t}\n\n\tif (getOptimality(x,g,l,u) < params.tol && params.display && rank == 0) {\n\t\tstd::cout << \" stopping because convergence tolerance met!\\n\";\n\t}\n\n\tLBFGSB_Output out;\n\tout.x = x;\n\tout.obj = f;\n\treturn out;\n}\n\n\n//705.023 701.723 697.852 691.804  692.91 667.241 667.139 672.044 674.512 680.647\n\n\n// int main(int argc, char** argv){\n// \tVectorXd x(10);\n// \tx = VectorXd::Constant(10,150);\n// \tVectorXd l = VectorXd::Constant(10,0.0);\n// \tVectorXd u = VectorXd::Constant(10,420.0);\n\n// \tLBFGSBParam params;\n// \tparams.m = 10;\n// \tparams.tol = 1e-2;\n// \tparams.max_iters = 50;\n// \tparams.display = true;\n// \tparams.xhistory = false;\n\n// \tObjFunc obj;\n// \tobj.init();\n// \tVectorXd base = VectorXd::Constant(10,673);\n// \tVectorXd increment(10);\n// \tincrement << 40, 40, 40, 40, 40, 20, 20, 20, 20, 20;\n// \tobj.setTarget(base + increment);\n// \t// obj.target << 50, 30, 60, 50, 60, 70, 1, 90, 50, 50;\n// \tLBFGSB opt;\n// \tstd::cout << \"starting to solve\\n\";\n// \tx = opt.solve(obj, x, l, u, params);\n// \tstd::cout << x.transpose() << std::endl;\n\n// \tVectorXd output = obj.evalANN(x);\n// \tstd::cout << (output - base).transpose() << std::endl;\n\n\t\n// \t// LBFGSB optimizer;\n// \t// // double opt = optimizer.getOptimality(x,g,l,u);\n// \t// // BPOutput bpout = optimizer.getBreakpoints(x,g,l,u);\n// \t// // std::cout<<bpout.t.transpose()<<std::endl;\n// \t// // std::cout<<bpout.d.transpose()<<std::endl;\n// \t// // for (int i = 0; i < bpout.F.size(); i++)\n// \t// // \tstd::cout<<bpout.F[i]<<\"  \";\n// \t// // std::cout<<std::endl;\n// \t// MatrixXd W = MatrixXd::Random(10,20);\n// \t// MatrixXd M = MatrixXd::Identity(20,20);\n// \t// VectorXd row = M.row(10);\n// \t// std::cout<<row<<std::endl;\n\n// \t// CauchyOutput cpout = optimizer.getCauchyPoint(x,g,l,u, 0.1, W, M);\n// \t// std::cout<<cpout.xc.transpose()<<std::endl;\n// \t// std::cout<<cpout.c.transpose()<<std::endl;\n// \t// using namespace std;\n// \t// MatrixXd mat(2,0);\n// \t// VectorXd vec(2);\n// \t// vec << 1, 1;\n// \t// cout << mat.rows() << \" \" << mat.cols() << endl;\n// \t// mat.conservativeResize(mat.rows(), mat.cols()+1);\n// \t// mat.col(mat.cols()-1) = vec;\n// \t// cout << mat << endl;\n// \treturn 0;\n// }", "meta": {"hexsha": "bbab08b8efb640b9a67e09a6bbbcb1b7a6a2e077", "size": 17598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LBFGSB.cpp", "max_stars_repo_name": "CJZheng91/L-BFGS-B", "max_stars_repo_head_hexsha": "570aae5eede74199449044e62917f5035c4390d6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-04-03T20:03:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T08:41:59.000Z", "max_issues_repo_path": "LBFGSB.cpp", "max_issues_repo_name": "CJZheng91/L-BFGS-B", "max_issues_repo_head_hexsha": "570aae5eede74199449044e62917f5035c4390d6", "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": "LBFGSB.cpp", "max_forks_repo_name": "CJZheng91/L-BFGS-B", "max_forks_repo_head_hexsha": "570aae5eede74199449044e62917f5035c4390d6", "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.5429864253, "max_line_length": 92, "alphanum_fraction": 0.5893283328, "num_tokens": 6304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5408385897012071}}
{"text": "#include <lib/utility.hpp>\n\n#include <boost/mp11.hpp>\n\n#include <type_traits>\n\nusing boost::mp11::index_sequence;\nusing boost::mp11::integer_sequence;\n\nusing xzr::utility::make_index_range;\nusing xzr::utility::make_integer_range;\n\nnamespace\n{\nstatic_assert(std::is_same<make_integer_range<int, 0, 0>, integer_sequence<int>>::value, \"\");\nstatic_assert(std::is_same<make_integer_range<unsigned, 0, 0>, integer_sequence<unsigned>>::value, \"\");\n\nstatic_assert(std::is_same<make_integer_range<int, 1, 1>, integer_sequence<int>>::value, \"\");\nstatic_assert(std::is_same<make_integer_range<unsigned, 5, 5>, integer_sequence<unsigned>>::value, \"\");\n\nstatic_assert(std::is_same<make_integer_range<int, 1, 5>, integer_sequence<int, 1, 2, 3, 4>>::value, \"\");\nstatic_assert(std::is_same<make_integer_range<unsigned, 5, 8>, integer_sequence<unsigned, 5, 6, 7>>::value, \"\");\n\nstatic_assert(std::is_same<make_integer_range<int, -3, 3>, integer_sequence<int, -3, -2, -1, 0, 1, 2>>::value, \"\");\nstatic_assert(std::is_same<make_integer_range<int, 3, -3>, integer_sequence<int, 3, 2, 1, 0, -1, -2>>::value, \"\");\n\nstatic_assert(std::is_same<make_index_range<42, 42>, index_sequence<>>::value, \"\");\nstatic_assert(std::is_same<make_index_range<3, 7>, index_sequence<3, 4, 5, 6>>::value, \"\");\n\nstatic_assert(std::is_same<make_index_range<7, 3>, index_sequence<7, 6, 5, 4>>::value, \"\");\n} // namespace\n", "meta": {"hexsha": "3fcf3e7c4c9c64396fc760f580cabde089b9b8e5", "size": 1377, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/lib/utility.test.cpp", "max_stars_repo_name": "XzoRit/cpp_test_eq_op", "max_stars_repo_head_hexsha": "32abe7949499fd81bd82aefccc6b4ccf550f0628", "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": "lib/lib/utility.test.cpp", "max_issues_repo_name": "XzoRit/cpp_test_eq_op", "max_issues_repo_head_hexsha": "32abe7949499fd81bd82aefccc6b4ccf550f0628", "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/lib/utility.test.cpp", "max_forks_repo_name": "XzoRit/cpp_test_eq_op", "max_forks_repo_head_hexsha": "32abe7949499fd81bd82aefccc6b4ccf550f0628", "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.03125, "max_line_length": 115, "alphanum_fraction": 0.7233115468, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.540838584958978}}
{"text": "/*\n *  divide_by_inplace_test.cpp\n *  MTL\n *\n *  Created by Hui Li (huil@Princeton.EDU)\n *\n */\n\n#include <iostream>\n#include <cmath>\n#include <complex>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/matrix/compressed2D.hpp> \n#include <boost/numeric/mtl/matrix/dense2D.hpp> \n#include <boost/numeric/mtl/matrix/laplacian_setup.hpp> \n#include <boost/numeric/mtl/operation/print.hpp>\n#include <boost/numeric/mtl/operation/operators.hpp>\n#include <boost/numeric/mtl/operation/divide_by_inplace.hpp>\n\n\nusing namespace std;  \n\ntemplate <typename MatrixA, typename MatrixB>\nvoid test(MatrixA& a, MatrixB& b, unsigned dim1, unsigned dim2, const char* name)\n{\n    unsigned size= dim1 * dim2;\n    MTL_THROW_IF(size == 0, mtl::runtime_error(\"Matrix size must be larger than 0 to make the test meaningful.\"));\n\t\n    const unsigned max_print_size= 25;\n    cout << \"\\n\" << name << \"\\n\";\n    laplacian_setup(a, dim1, dim2);\n    laplacian_setup(b, dim1, dim2);\n\t\n    // right_scale_inplace(a, 2.0);\n    a*= 2.0;\n    if (size <= max_print_size)\n\t\tcout << \"A= \\n\\n\" << a << \"\\n\";\n\t\n    typename mtl::Collection<MatrixA>::value_type eight(8.0);\n    MTL_THROW_IF(a[0][0] != eight, mtl::runtime_error(\"Scaling with scalar wrong\"));\n\t\n    a /= 2.0; // divide_by_inplace(a, 2.0);\n    a*= b;   // right_scale_inplace(a, b);\n\t\n    if (size <= max_print_size)\n\t\tcout << \"A= \\n\\n\" << a << \"B= \\n\\n\" << b << \"\\n\";\n\t\n    // Check for stencil below in the middle of the matrix\n    //        1\n    //     2 -8  2\n    //  1 -8 20 -8  1\n    //     2 -8  2\n    //        1    \n    if (dim1 == 5 && dim2 == 5) {\n\ttypename mtl::Collection<MatrixA>::value_type twenty(20.0), two(2.0), one(1.0), \n\t                                              zero(0.0), minus_eight(-8.0);\n\tMTL_THROW_IF(a[12][12] != twenty, mtl::runtime_error(\"wrong diagonal\"));\n\tMTL_THROW_IF(a[12][13] != minus_eight, mtl::runtime_error(\"wrong east neighbor\"));\n\tMTL_THROW_IF(a[12][14] != one, mtl::runtime_error(\"wrong east east neighbor\"));\n\tMTL_THROW_IF(a[12][15] != zero, mtl::runtime_error(\"wrong zero-element\"));\n\tMTL_THROW_IF(a[12][17] != minus_eight, mtl::runtime_error(\"wrong south neighbor\"));\n\tMTL_THROW_IF(a[12][18] != two, mtl::runtime_error(\"wrong south east neighbor\"));\n\tMTL_THROW_IF(a[12][22] != one, mtl::runtime_error(\"wrong south south neighbor\"));\n    }\n}\n\n\n\nint main(int argc, char* argv[])\n{\n    using namespace mtl;\n    unsigned dim1= 5, dim2= 5;\n\t\n    if (argc > 2) {dim1= atoi(argv[1]);dim2= atoi(argv[2]);}\n    unsigned size= dim1 * dim2; \n\t\n    compressed2D<double>                                 cr(size, size);\n    compressed2D<double, mat::parameters<col_major> > cc(size, size);\n\t\n    dense2D<double>                                      dr(size, size);\n    dense2D<double, mat::parameters<col_major> >      dc(size, size);\n\t\n    test(cr, dr, dim1, dim2, \"Row-major sparse scaled with row-major dense\");\n    test(cr, dc, dim1, dim2, \"Row-major sparse scaled with column-major dense\");\n    test(cc, dr, dim1, dim2, \"Column-major sparse scaled with row-major dense\");\n    test(cc, dc, dim1, dim2, \"Column-major sparse scaled with column-major dense\");\n\t\n    test(dr, cr, dim1, dim2, \"Row-major dense scaled with row-major sparse\");\n    test(dr, cc, dim1, dim2, \"Row-major dense scaled with column-major sparse\");\n    test(dc, cr, dim1, dim2, \"Column-major dense scaled with row-major sparse\");\n    test(dc, cc, dim1, dim2, \"Column-major dense scaled with column-major sparse\");\n\t\n    return 0;\n}\n", "meta": {"hexsha": "0e161375e045a513a74481cc960368e4b566a011", "size": 3491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/divide_by_inplace_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/divide_by_inplace_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/divide_by_inplace_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": 36.7473684211, "max_line_length": 114, "alphanum_fraction": 0.6301919221, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5408385802167489}}
{"text": "/**TODO:  Add copyright*/\n\n#define BOOST_TEST_MODULE ModelInterpreter DAG test suite \n#include <boost/test/included/unit_test.hpp>\n#include <EvoNet/ml/ModelInterpreterDefaultDevice.h>\n#include <EvoNet/ml/ModelBuilder.h> // comprehensive architecture tests\n\nusing namespace EvoNet;\nusing namespace std;\n\nModel<float> makeModelToy1()\n{\n  /**\n  * Directed Acyclic Graph Toy Network Model\n  */\n  Node<float> i1, i2, h1, h2, o1, o2, b1, b2;\n  Link l1, l2, l3, l4, lb1, lb2, l5, l6, l7, l8, lb3, lb4;\n  Weight<float> w1, w2, w3, w4, wb1, wb2, w5, w6, w7, w8, wb3, wb4;\n  Model<float> model_FC_Sum;\n\n  // Toy network: 1 hidden layer, fully connected, DAG\n  i1 = Node<float>(\"0\", NodeType::input, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n  i2 = Node<float>(\"1\", NodeType::input, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n  h1 = Node<float>(\"2\", NodeType::hidden, NodeStatus::initialized, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n  h2 = Node<float>(\"3\", NodeType::hidden, NodeStatus::initialized, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n  o1 = Node<float>(\"4\", NodeType::output, NodeStatus::initialized, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n  o2 = Node<float>(\"5\", NodeType::output, NodeStatus::initialized, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n  b1 = Node<float>(\"6\", NodeType::bias, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n  b2 = Node<float>(\"7\", NodeType::bias, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n  // weights  \n  std::shared_ptr<WeightInitOp<float>> weight_init;\n  std::shared_ptr<SolverOp<float>> solver;\n  // weight_init.reset(new RandWeightInitOp(1.0)); // No random init for testing\n  weight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n  solver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  w1 = Weight<float>(\"0\", weight_init, solver);\n  weight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n  solver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  w2 = Weight<float>(\"1\", weight_init, solver);\n  weight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n  solver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  w3 = Weight<float>(\"2\", weight_init, solver);\n  weight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n  solver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  w4 = Weight<float>(\"3\", weight_init, solver);\n  weight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n  solver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  wb1 = Weight<float>(\"4\", weight_init, solver);\n  weight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n  solver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  wb2 = Weight<float>(\"5\", weight_init, solver);\n  // input layer + bias\n  l1 = Link(\"0\", \"0\", \"2\", \"0\");\n  l2 = Link(\"1\", \"0\", \"3\", \"1\");\n  l3 = Link(\"2\", \"1\", \"2\", \"2\");\n  l4 = Link(\"3\", \"1\", \"3\", \"3\");\n  lb1 = Link(\"4\", \"6\", \"2\", \"4\");\n  lb2 = Link(\"5\", \"6\", \"3\", \"5\");\n  // weights\n  weight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n  solver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  w5 = Weight<float>(\"6\", weight_init, solver);\n  weight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n  solver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  w6 = Weight<float>(\"7\", weight_init, solver);\n  weight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n  solver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  w7 = Weight<float>(\"8\", weight_init, solver);\n  weight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n  solver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  w8 = Weight<float>(\"9\", weight_init, solver);\n  weight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n  solver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  wb3 = Weight<float>(\"10\", weight_init, solver);\n  weight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n  solver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n  wb4 = Weight<float>(\"11\", weight_init, solver);\n  // hidden layer + bias\n  l5 = Link(\"6\", \"2\", \"4\", \"6\");\n  l6 = Link(\"7\", \"2\", \"5\", \"7\");\n  l7 = Link(\"8\", \"3\", \"4\", \"8\");\n  l8 = Link(\"9\", \"3\", \"5\", \"9\");\n  lb3 = Link(\"10\", \"7\", \"4\", \"10\");\n  lb4 = Link(\"11\", \"7\", \"5\", \"11\");\n  model_FC_Sum.setId(1);\n  model_FC_Sum.addNodes({ i1, i2, h1, h2, o1, o2, b1, b2 });\n  model_FC_Sum.addWeights({ w1, w2, w3, w4, wb1, wb2, w5, w6, w7, w8, wb3, wb4 });\n  model_FC_Sum.addLinks({ l1, l2, l3, l4, lb1, lb2, l5, l6, l7, l8, lb3, lb4 });\n  return model_FC_Sum;\n}\n\nBOOST_AUTO_TEST_SUITE(modelInterpreter_DAG)\n\nBOOST_AUTO_TEST_CASE(constructor)\n{\n  ModelInterpreterDefaultDevice<float>* ptr = nullptr;\n  ModelInterpreterDefaultDevice<float>* nullPointer = nullptr;\n  ptr = new ModelInterpreterDefaultDevice<float>();\n  BOOST_CHECK_NE(ptr, nullPointer);\n}\n\nBOOST_AUTO_TEST_CASE(destructor)\n{\n  ModelInterpreterDefaultDevice<float>* ptr = nullptr;\n  ptr = new ModelInterpreterDefaultDevice<float>();\n  delete ptr;\n}\n\nBOOST_AUTO_TEST_CASE(constructor1)\n{\n  ModelResources model_resources = { ModelDevice(0, 1) };\n  ModelInterpreterDefaultDevice<float> model_interpreter(model_resources);\n\n  BOOST_CHECK_EQUAL(model_interpreter.getModelResources()[0].getID(), model_resources[0].getID());\n  BOOST_CHECK_EQUAL(model_interpreter.getModelResources()[0].getNEngines(), model_resources[0].getNEngines());\n}\n\nBOOST_AUTO_TEST_CASE(gettersAndSetters)\n{\n  ModelResources model_resources = { ModelDevice(0, 1) };\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n  model_interpreter.setModelResources(model_resources);\n\n  BOOST_CHECK_EQUAL(model_interpreter.getModelResources()[0].getID(), model_resources[0].getID());\n  BOOST_CHECK_EQUAL(model_interpreter.getModelResources()[0].getNEngines(), model_resources[0].getNEngines());\n}\n\nBOOST_AUTO_TEST_CASE(copy)\n{\n  ModelResources model_resources = { ModelDevice(0, 1) };\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n  model_interpreter.setModelResources(model_resources);\n  std::vector<ModelInterpreterDefaultDevice<float>> model_interpreters;\n  model_interpreters.push_back(model_interpreter);\n\n  BOOST_CHECK_EQUAL(model_interpreters[0].getModelResources()[0].getID(), model_resources[0].getID());\n  BOOST_CHECK_EQUAL(model_interpreters[0].getModelResources()[0].getNEngines(), model_resources[0].getNEngines());\n}\n\nBOOST_AUTO_TEST_CASE(comparison1)\n{\n  ModelResources model_resources = { ModelDevice(0, 1) };\n  ModelInterpreterDefaultDevice<float> model_interpreter(model_resources);\n  ModelInterpreterDefaultDevice<float> model_interpreter_test;\n  //BOOST_CHECK(model_interpreter != model_interpreter_test); // Need to fix '==' operator in `ModelInterpreter`\n\n  model_interpreter_test.setModelResources(model_resources);\n  BOOST_CHECK(model_interpreter == model_interpreter_test);\n}\n\n/**\n * Part 1 test suit for the Model class\n *\n * The following test methods that are\n * required of a standard feed-forward neural network\n*/\n\nModel<float> model_getNextInactiveLayer = makeModelToy1();\nBOOST_AUTO_TEST_CASE(getNextInactiveLayerWOBiases)\n{\n  // Toy network: 1 hidden layer, fully connected, DAG\n  // Model<float> model_FC_Sum = makeModelToy1();\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // initialize nodes\n  // NOTE: input and biases have been activated when the model was created\n\n  // get the next hidden layer\n  std::map<std::string, int> FP_operations_map;\n  std::vector<OperationList<float>> FP_operations_list;\n  model_interpreter.getNextInactiveLayerWOBiases(model_getNextInactiveLayer, FP_operations_map, FP_operations_list);\n\n  BOOST_CHECK_EQUAL(FP_operations_map.size(), 2);\n  BOOST_CHECK_EQUAL(FP_operations_map.at(\"2\"), 0);\n  BOOST_CHECK_EQUAL(FP_operations_map.at(\"3\"), 1);\n  BOOST_CHECK_EQUAL(FP_operations_list.size(), 2);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].result.sink_node->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments.size(), 2);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].source_node->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].weight->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].source_node->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].weight->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].result.sink_node->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments.size(), 2);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].source_node->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].weight->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[1].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[1].source_node->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[1].weight->getName(), \"3\");\n}\n\nModel<float> model_getNextInactiveLayerBiases = makeModelToy1();\nBOOST_AUTO_TEST_CASE(getNextInactiveLayerBiases)\n{\n  // Toy network: 1 hidden layer, fully connected, DAG\n  // Model<float> model_FC_Sum = makeModelToy1();\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // initialize nodes\n  // NOTE: input and biases have been activated when the model was created\n\n  // get the next hidden layer\n  std::map<std::string, int> FP_operations_map;\n  std::vector<OperationList<float>> FP_operations_list;\n  model_interpreter.getNextInactiveLayerWOBiases(model_getNextInactiveLayerBiases, FP_operations_map, FP_operations_list);\n\n  std::vector<std::string> sink_nodes_with_biases2;\n  model_interpreter.getNextInactiveLayerBiases(model_getNextInactiveLayerBiases, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n  BOOST_CHECK_EQUAL(FP_operations_map.size(), 2);\n  BOOST_CHECK_EQUAL(FP_operations_map.at(\"2\"), 0);\n  BOOST_CHECK_EQUAL(FP_operations_map.at(\"3\"), 1);\n  BOOST_CHECK_EQUAL(FP_operations_list.size(), 2);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].result.sink_node->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments.size(), 3);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].source_node->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].weight->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].source_node->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].weight->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].source_node->getName(), \"6\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].weight->getName(), \"4\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].result.sink_node->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments.size(), 3);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].source_node->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].weight->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[1].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[1].source_node->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[1].weight->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[2].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[2].source_node->getName(), \"6\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[2].weight->getName(), \"5\");\n  BOOST_CHECK_EQUAL(sink_nodes_with_biases2.size(), 2);\n  BOOST_CHECK_EQUAL(sink_nodes_with_biases2[0], \"2\");\n  BOOST_CHECK_EQUAL(sink_nodes_with_biases2[1], \"3\");\n}\n\nModel<float> model_getNextInactiveLayerCycles = makeModelToy1();\nBOOST_AUTO_TEST_CASE(getNextInactiveLayerCycles)\n{\n  // Toy network: 1 hidden layer, fully connected, DAG\n  // Model<float> model_FC_Sum = makeModelToy1();\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // initialize nodes\n  // NOTE: input and biases have been activated when the model was created\n\n  // get the next hidden layer\n  std::map<std::string, int> FP_operations_map;\n  std::vector<OperationList<float>> FP_operations_list;\n  model_interpreter.getNextInactiveLayerWOBiases(model_getNextInactiveLayerCycles, FP_operations_map, FP_operations_list);\n\n  std::vector<std::string> sink_nodes_with_biases2;\n  model_interpreter.getNextInactiveLayerBiases(model_getNextInactiveLayerCycles, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n  std::set<std::string> sink_nodes_with_cycles;\n  model_interpreter.getNextInactiveLayerCycles(model_getNextInactiveLayerCycles, FP_operations_map, FP_operations_list, sink_nodes_with_cycles);\n\n  BOOST_CHECK_EQUAL(FP_operations_map.size(), 2);\n  BOOST_CHECK_EQUAL(FP_operations_map.at(\"2\"), 0);\n  BOOST_CHECK_EQUAL(FP_operations_map.at(\"3\"), 1);\n  BOOST_CHECK_EQUAL(FP_operations_list.size(), 2);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].result.sink_node->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments.size(), 3);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].source_node->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].weight->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].source_node->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].weight->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].source_node->getName(), \"6\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].weight->getName(), \"4\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].result.sink_node->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments.size(), 3);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].source_node->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].weight->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[1].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[1].source_node->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[1].weight->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[2].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[2].source_node->getName(), \"6\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[2].weight->getName(), \"5\");\n  BOOST_CHECK_EQUAL(sink_nodes_with_cycles.size(), 0);\n}\n\nModel<float> model_pruneInactiveLayerCycles = makeModelToy1();\nBOOST_AUTO_TEST_CASE(pruneInactiveLayerCycles)\n{\n  // Toy network: 1 hidden layer, fully connected, DAG\n  // Model<float> model_FC_Sum = makeModelToy1();\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // initialize nodes\n  // NOTE: input and biases have been activated when the model was created\n\n  // get the next hidden layer\n  std::map<std::string, int> FP_operations_map;\n  std::vector<OperationList<float>> FP_operations_list;\n  model_interpreter.getNextInactiveLayerWOBiases(model_pruneInactiveLayerCycles, FP_operations_map, FP_operations_list);\n\n  std::vector<std::string> sink_nodes_with_biases2;\n  model_interpreter.getNextInactiveLayerBiases(model_pruneInactiveLayerCycles, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n  std::set<std::string> sink_nodes_with_cycles;\n  std::map<std::string, int> FP_operations_map_cycles = FP_operations_map;\n  std::vector<OperationList<float>> FP_operations_list_cycles = FP_operations_list;\n  model_interpreter.getNextInactiveLayerCycles(model_pruneInactiveLayerCycles, FP_operations_map_cycles, FP_operations_list_cycles, sink_nodes_with_cycles);\n\n  model_interpreter.pruneInactiveLayerCycles(model_pruneInactiveLayerCycles, FP_operations_map, FP_operations_map_cycles, FP_operations_list, FP_operations_list_cycles, sink_nodes_with_cycles);\n\n  BOOST_CHECK_EQUAL(FP_operations_map.size(), 2);\n  BOOST_CHECK_EQUAL(FP_operations_map.at(\"2\"), 0);\n  BOOST_CHECK_EQUAL(FP_operations_map.at(\"3\"), 1);\n  BOOST_CHECK_EQUAL(FP_operations_list.size(), 2);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].result.sink_node->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments.size(), 3);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].source_node->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].weight->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].source_node->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[1].weight->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].source_node->getName(), \"6\");\n  BOOST_CHECK_EQUAL(FP_operations_list[0].arguments[2].weight->getName(), \"4\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].result.sink_node->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments.size(), 3);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].source_node->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].weight->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[1].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[1].source_node->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[1].weight->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[2].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[2].source_node->getName(), \"6\");\n  BOOST_CHECK_EQUAL(FP_operations_list[1].arguments[2].weight->getName(), \"5\");\n}\n\nModel<float> model_expandAllForwardPropogationOperations = makeModelToy1();\nBOOST_AUTO_TEST_CASE(expandAllForwardPropogationOperations)\n{\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // initialize nodes\n  // NOTE: input and biases have been activated when the model was created\n\n  std::map<std::string, int> FP_operations_map;\n  std::vector<OperationList<float>> FP_operations_list;\n  model_interpreter.getNextInactiveLayerWOBiases(model_expandAllForwardPropogationOperations, FP_operations_map, FP_operations_list);\n\n  std::vector<std::string> sink_nodes_with_biases2;\n  model_interpreter.getNextInactiveLayerBiases(model_expandAllForwardPropogationOperations, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n  std::vector<OperationList<float>> FP_operations_expanded;\n  model_interpreter.expandAllForwardPropogationOperations(FP_operations_list, FP_operations_expanded);\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded.size(), 6);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[0].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[0].result.sink_node->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[0].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[0].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[0].arguments[0].source_node->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[0].arguments[0].weight->getName(), \"0\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[1].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[1].result.sink_node->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[1].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[1].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[1].arguments[0].source_node->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[1].arguments[0].weight->getName(), \"2\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[2].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[2].result.sink_node->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[2].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[2].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[2].arguments[0].source_node->getName(), \"6\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[2].arguments[0].weight->getName(), \"4\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[3].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[3].result.sink_node->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[3].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[3].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[3].arguments[0].source_node->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[3].arguments[0].weight->getName(), \"1\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[4].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[4].result.sink_node->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[4].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[4].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[4].arguments[0].source_node->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[4].arguments[0].weight->getName(), \"3\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[5].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[5].result.sink_node->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[5].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[5].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[5].arguments[0].source_node->getName(), \"6\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[5].arguments[0].weight->getName(), \"5\");\n}\n\nModel<float> model_getFPOpsOoO = makeModelToy1();\nBOOST_AUTO_TEST_CASE(getFPOpsOoO)\n{\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // initialize nodes\n  // NOTE: input and biases have been activated when the model was created\n\n  std::vector<OperationList<float>> FP_operations_expanded;\n  int iter = 0;\n  model_interpreter.getFPOpsOoO_(model_getFPOpsOoO, FP_operations_expanded, iter);\n\n  BOOST_CHECK_EQUAL(iter, 2);\n  BOOST_CHECK_EQUAL(FP_operations_expanded.size(), 12);\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[0].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[0].result.sink_node->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[0].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[0].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[0].arguments[0].source_node->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[0].arguments[0].weight->getName(), \"0\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[1].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[1].result.sink_node->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[1].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[1].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[1].arguments[0].source_node->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[1].arguments[0].weight->getName(), \"2\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[2].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[2].result.sink_node->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[2].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[2].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[2].arguments[0].source_node->getName(), \"6\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[2].arguments[0].weight->getName(), \"4\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[3].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[3].result.sink_node->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[3].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[3].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[3].arguments[0].source_node->getName(), \"0\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[3].arguments[0].weight->getName(), \"1\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[4].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[4].result.sink_node->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[4].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[4].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[4].arguments[0].source_node->getName(), \"1\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[4].arguments[0].weight->getName(), \"3\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[5].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[5].result.sink_node->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[5].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[5].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[5].arguments[0].source_node->getName(), \"6\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[5].arguments[0].weight->getName(), \"5\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[6].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[6].result.sink_node->getName(), \"4\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[6].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[6].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[6].arguments[0].source_node->getName(), \"7\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[6].arguments[0].weight->getName(), \"10\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[7].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[7].result.sink_node->getName(), \"4\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[7].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[7].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[7].arguments[0].source_node->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[7].arguments[0].weight->getName(), \"6\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[8].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[8].result.sink_node->getName(), \"4\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[8].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[8].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[8].arguments[0].source_node->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[8].arguments[0].weight->getName(), \"8\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[9].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[9].result.sink_node->getName(), \"5\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[9].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[9].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[9].arguments[0].source_node->getName(), \"7\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[9].arguments[0].weight->getName(), \"11\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[10].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[10].result.sink_node->getName(), \"5\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[10].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[10].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[10].arguments[0].source_node->getName(), \"2\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[10].arguments[0].weight->getName(), \"7\");\n\n  BOOST_CHECK_EQUAL(FP_operations_expanded[11].result.time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[11].result.sink_node->getName(), \"5\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[11].arguments.size(), 1);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[11].arguments[0].time_step, 0);\n  BOOST_CHECK_EQUAL(FP_operations_expanded[11].arguments[0].source_node->getName(), \"3\");\n  BOOST_CHECK_EQUAL(FP_operations_expanded[11].arguments[0].weight->getName(), \"9\");\n}\n\nModel<float> model_getTensorOperations = makeModelToy1();\nBOOST_AUTO_TEST_CASE(getTensorOperations)\n{\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // initialize nodes\n  // NOTE: input and biases have been activated when the model was created\n\n  std::map<std::string, int> FP_operations_map;\n  std::vector<OperationList<float>> FP_operations_list;\n  model_interpreter.getNextInactiveLayerWOBiases(model_getTensorOperations, FP_operations_map, FP_operations_list);\n\n  std::vector<std::string> sink_nodes_with_biases2;\n  model_interpreter.getNextInactiveLayerBiases(model_getTensorOperations, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n  std::vector<OperationList<float>> FP_operations_expanded;\n  model_interpreter.expandAllForwardPropogationOperations(FP_operations_list, FP_operations_expanded);\n\n  std::set<std::string> identified_sink_nodes;\n  std::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n  BOOST_CHECK_EQUAL(identified_sink_nodes.size(), 6);\n  BOOST_CHECK_EQUAL(identified_sink_nodes.count(\"2/0\"), 1);\n  BOOST_CHECK_EQUAL(identified_sink_nodes.count(\"2/1\"), 1);\n  BOOST_CHECK_EQUAL(identified_sink_nodes.count(\"2/2\"), 1);\n  BOOST_CHECK_EQUAL(identified_sink_nodes.count(\"3/3\"), 1);\n  BOOST_CHECK_EQUAL(identified_sink_nodes.count(\"3/4\"), 1);\n  BOOST_CHECK_EQUAL(identified_sink_nodes.count(\"3/5\"), 1);\n  BOOST_CHECK_EQUAL(tensor_ops.size(), 1);\n  BOOST_CHECK_EQUAL(tensor_ops.at(\"2/0\")[0], 0);\n  BOOST_CHECK_EQUAL(tensor_ops.at(\"2/0\")[1], 1);\n  BOOST_CHECK_EQUAL(tensor_ops.at(\"2/0\")[2], 2);\n  BOOST_CHECK_EQUAL(tensor_ops.at(\"2/0\")[3], 3);\n  BOOST_CHECK_EQUAL(tensor_ops.at(\"2/0\")[4], 4);\n  BOOST_CHECK_EQUAL(tensor_ops.at(\"2/0\")[5], 5);\n}\n\nModel<float> model_getForwardPropogationLayerTensorDimensions = makeModelToy1();\nBOOST_AUTO_TEST_CASE(getForwardPropogationLayerTensorDimensions)\n{\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // initialize nodes\n  // NOTE: input and biases have been activated when the model was created\n\n  // change the bias weights to shared\n  model_getForwardPropogationLayerTensorDimensions.links_.at(\"5\")->setWeightName(\"4\");\n\n  // Check iteration one with no source/sink/weight tensors already allocated\n  std::map<std::string, int> FP_operations_map;\n  std::vector<OperationList<float>> FP_operations_list;\n  model_interpreter.getNextInactiveLayerWOBiases(model_getForwardPropogationLayerTensorDimensions, FP_operations_map, FP_operations_list);\n\n  std::vector<std::string> sink_nodes_with_biases2;\n  model_interpreter.getNextInactiveLayerBiases(model_getForwardPropogationLayerTensorDimensions, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n  std::vector<OperationList<float>> FP_operations_expanded;\n  model_interpreter.expandAllForwardPropogationOperations(FP_operations_list, FP_operations_expanded);\n\n  std::set<std::string> identified_sink_nodes;\n  std::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n  std::map<int, int> max_layer_sizes;\n  std::map<std::string, int> layer_name_pos;\n  std::vector<int> source_layer_sizes, sink_layer_sizes;\n  std::vector<std::vector<std::pair<int, int>>> weight_indices;\n  std::vector<std::map<std::string, std::vector<std::pair<int, int>>>> shared_weight_indices;\n  std::vector<std::vector<float>> weight_values;\n  std::vector<bool> make_source_tensors, make_sink_tensors, make_weight_tensors;\n  std::vector<int> source_layer_pos, sink_layer_pos;\n  int tensor_layers_cnt = 0;\n  int weight_layers_cnt = 0;\n  model_interpreter.getForwardPropogationLayerTensorDimensions(FP_operations_expanded, tensor_ops, source_layer_sizes, sink_layer_sizes, weight_indices, shared_weight_indices, weight_values, make_source_tensors, make_sink_tensors, make_weight_tensors,\n    source_layer_pos, sink_layer_pos, max_layer_sizes, layer_name_pos, tensor_layers_cnt, weight_layers_cnt);\n\n  BOOST_CHECK_EQUAL(source_layer_sizes.size(), 1);\n  BOOST_CHECK_EQUAL(source_layer_sizes[0], 3);\n  BOOST_CHECK_EQUAL(sink_layer_sizes.size(), 1);\n  BOOST_CHECK_EQUAL(sink_layer_sizes[0], 2);\n\n  BOOST_CHECK_EQUAL(source_layer_pos.size(), 1);\n  BOOST_CHECK_EQUAL(source_layer_pos.at(0), 1);\n  BOOST_CHECK_EQUAL(sink_layer_pos.size(), 1);\n  BOOST_CHECK_EQUAL(sink_layer_pos.at(0), 0);\n\n  BOOST_CHECK_EQUAL(max_layer_sizes.size(), 2);\n  BOOST_CHECK_EQUAL(max_layer_sizes.at(0), 1);\n  BOOST_CHECK_EQUAL(max_layer_sizes.at(1), 2);\n\n  BOOST_CHECK_EQUAL(layer_name_pos.size(), 0);\n\n  BOOST_CHECK_EQUAL(weight_indices.size(), 1);\n  BOOST_CHECK_EQUAL(weight_indices[0].size(), 6);\n  std::vector<std::pair<int, int>> weight_indices_test = {\n    std::make_pair(0,0),std::make_pair(1,0),std::make_pair(2,0),std::make_pair(0,1),\n    std::make_pair(1,1),std::make_pair(2,1)\n  };\n  for (int i = 0; i < weight_indices_test.size(); ++i) {\n    BOOST_CHECK_EQUAL(weight_indices[0][i].first, weight_indices_test[i].first);\n    BOOST_CHECK_EQUAL(weight_indices[0][i].second, weight_indices_test[i].second);\n  }\n\n  BOOST_CHECK_EQUAL(shared_weight_indices.size(), 1);\n  BOOST_CHECK_EQUAL(shared_weight_indices[0].size(), 1);\n  std::map<std::string, std::vector<std::pair<int, int>>> shared_weight_indices_test = {\n    {\"4\", {std::make_pair(2,1), std::make_pair(2,0)}}\n  };\n  for (int i = 0; i < shared_weight_indices_test.at(\"4\").size(); ++i) {\n    BOOST_CHECK_EQUAL(shared_weight_indices[0].at(\"4\")[i].first, shared_weight_indices_test.at(\"4\")[i].first);\n    BOOST_CHECK_EQUAL(shared_weight_indices[0].at(\"4\")[i].second, shared_weight_indices_test.at(\"4\")[i].second);\n  }\n\n  BOOST_CHECK_EQUAL(weight_values.size(), 1);\n  BOOST_CHECK_EQUAL(weight_values[0].size(), 6);\n  std::vector<float> weight_values_test = { 1, 1, 1, 1, 1, 1 };\n  for (int i = 0; i < weight_values_test.size(); ++i) {\n    BOOST_CHECK_EQUAL(weight_values[0][i], weight_values_test[i]);\n  }\n\n  BOOST_CHECK_EQUAL(make_source_tensors.size(), 1);\n  BOOST_CHECK(make_source_tensors[0]);\n  BOOST_CHECK_EQUAL(make_sink_tensors.size(), 1);\n  BOOST_CHECK(make_sink_tensors[0]);\n  BOOST_CHECK_EQUAL(make_weight_tensors.size(), 1);\n  BOOST_CHECK(make_weight_tensors[0]);\n\n  // Check iteration two\n  model_getForwardPropogationLayerTensorDimensions.getNodesMap().at(\"2\")->setStatus(NodeStatus::activated);\n  model_getForwardPropogationLayerTensorDimensions.getNodesMap().at(\"3\")->setStatus(NodeStatus::activated);\n  FP_operations_map.clear();\n  FP_operations_list.clear();\n  model_interpreter.getNextInactiveLayerWOBiases(model_getForwardPropogationLayerTensorDimensions, FP_operations_map, FP_operations_list);\n\n  sink_nodes_with_biases2.clear();\n  model_interpreter.getNextInactiveLayerBiases(model_getForwardPropogationLayerTensorDimensions, FP_operations_map, FP_operations_list, sink_nodes_with_biases2);\n\n  FP_operations_expanded.clear();\n  model_interpreter.expandAllForwardPropogationOperations(FP_operations_list, FP_operations_expanded);\n\n  identified_sink_nodes.clear();\n  tensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n  max_layer_sizes.clear();\n  layer_name_pos.clear();\n  source_layer_sizes.clear(); sink_layer_sizes.clear();\n  weight_indices.clear();\n  shared_weight_indices.clear();\n  weight_values.clear();\n  make_source_tensors.clear(); make_sink_tensors.clear(); make_weight_tensors.clear();\n  source_layer_pos.clear(); sink_layer_pos.clear();\n  tensor_layers_cnt = 0; weight_layers_cnt = 0;\n  model_interpreter.getForwardPropogationLayerTensorDimensions(FP_operations_expanded, tensor_ops, source_layer_sizes, sink_layer_sizes, weight_indices, shared_weight_indices, weight_values, make_source_tensors, make_sink_tensors, make_weight_tensors,\n    source_layer_pos, sink_layer_pos, max_layer_sizes, layer_name_pos, tensor_layers_cnt, weight_layers_cnt);\n\n  BOOST_CHECK_EQUAL(source_layer_sizes.size(), 2);\n  BOOST_CHECK_EQUAL(source_layer_sizes[0], 2);\n  BOOST_CHECK_EQUAL(source_layer_sizes[1], 1);\n  BOOST_CHECK_EQUAL(sink_layer_sizes.size(), 2);\n  BOOST_CHECK_EQUAL(sink_layer_sizes[0], 2);\n  BOOST_CHECK_EQUAL(sink_layer_sizes[1], 2);\n\n  BOOST_CHECK_EQUAL(source_layer_pos.size(), 2);\n  BOOST_CHECK_EQUAL(source_layer_pos.at(0), 0);\n  BOOST_CHECK_EQUAL(source_layer_pos.at(1), 1);\n  BOOST_CHECK_EQUAL(sink_layer_pos.size(), 2);\n  BOOST_CHECK_EQUAL(sink_layer_pos.at(0), 0);\n  BOOST_CHECK_EQUAL(sink_layer_pos.at(1), 0);\n\n  BOOST_CHECK_EQUAL(max_layer_sizes.size(), 2);\n  BOOST_CHECK_EQUAL(max_layer_sizes.at(0), 1);\n  BOOST_CHECK_EQUAL(max_layer_sizes.at(0), 1);\n\n  BOOST_CHECK_EQUAL(layer_name_pos.size(), 0);\n\n  BOOST_CHECK_EQUAL(weight_indices.size(), 2);\n  BOOST_CHECK_EQUAL(weight_indices[0].size(), 4);\n  BOOST_CHECK_EQUAL(weight_indices[1].size(), 2);\n  std::vector<std::vector<std::pair<int, int>>> weight_indices_test2 = {\n    {std::make_pair(0,0),std::make_pair(1,0),\tstd::make_pair(0,1),std::make_pair(1,1)},\n    {std::make_pair(0,0),std::make_pair(0,1)}\n  };\n  for (int tensor_iter = 0; tensor_iter < weight_indices_test2.size(); ++tensor_iter) {\n    for (int i = 0; i < weight_indices_test2[tensor_iter].size(); ++i) {\n      BOOST_CHECK_EQUAL(weight_indices[tensor_iter][i].first, weight_indices_test2[tensor_iter][i].first);\n      BOOST_CHECK_EQUAL(weight_indices[tensor_iter][i].second, weight_indices_test2[tensor_iter][i].second);\n    }\n  }\n\n  BOOST_CHECK_EQUAL(shared_weight_indices.size(), 2);\n  BOOST_CHECK_EQUAL(shared_weight_indices[0].size(), 0);\n  BOOST_CHECK_EQUAL(shared_weight_indices[1].size(), 0);\n\n  BOOST_CHECK_EQUAL(weight_values.size(), 2);\n  BOOST_CHECK_EQUAL(weight_values[0].size(), 4);\n  BOOST_CHECK_EQUAL(weight_values[1].size(), 2);\n  std::vector<std::vector<float>> weight_values_test2 = { { 1, 1, 1, 1}, {1, 1} };\n  for (int tensor_iter = 0; tensor_iter < weight_values_test2.size(); ++tensor_iter) {\n    for (int i = 0; i < weight_values_test2[tensor_iter].size(); ++i) {\n      BOOST_CHECK_EQUAL(weight_values[tensor_iter][i], weight_values_test2[tensor_iter][i]);\n    }\n  }\n\n  BOOST_CHECK_EQUAL(make_source_tensors.size(), 2);\n  BOOST_CHECK(!make_source_tensors[0]);\n  BOOST_CHECK(make_source_tensors[1]);\n  BOOST_CHECK_EQUAL(make_sink_tensors.size(), 2);\n  BOOST_CHECK(make_sink_tensors[0]);\n  BOOST_CHECK(!make_sink_tensors[1]);\n  BOOST_CHECK_EQUAL(make_weight_tensors.size(), 2);\n  BOOST_CHECK(make_weight_tensors[0]);\n  BOOST_CHECK(make_weight_tensors[1]);\n}\n\n/* MISSING TEST COVERAGE:\n1. no explicit test coverage for `setForwardPropogationLayerTensors_`\n  - would need to break into seperate functions `getForwardPropogationLayerTensorDimensions_` and `allocateForwardPropogationLayerTensors_`\n    in order to properly test\n2. no explicit test coverage for `checkFutureOperations_` and `checkPreviousOperations_`\n*/\n\n/*\nThe following tests test the expected `tensor_ops_steps` and `FP_operations` for more complicated model structures\n  that include Dot product attention, Variational Autoencoder, and Convolution networks\n*/\n\ntemplate<typename TensorT>\nvoid makeModelSolution(Model<TensorT>& model, const int& n_inputs, const int& n_outputs, bool specify_layers = false)\n{\n  model.setId(0);\n  model.setName(\"AddProbAtt-Solution-NoBiases\");\n  // NOTE: Biases will be non-optimally split when layers are specified\n\n  ModelBuilder<TensorT> model_builder;\n\n  // Add the inputs\n  std::vector<std::string> node_names_random = model_builder.addInputNodes(model, \"Random\", \"Random\", n_inputs);\n  std::vector<std::string> node_names_mask = model_builder.addInputNodes(model, \"Mask\", \"Mask\", n_inputs);\n\n  std::shared_ptr<SolverOp<TensorT>> solver;\n  std::shared_ptr<WeightInitOp<TensorT>> weight_init;\n  solver.reset(new DummySolverOp<TensorT>());\n  weight_init = std::make_shared<ConstWeightInitOp<TensorT>>(ConstWeightInitOp<TensorT>(1));\n\n  // Add the hidden layer\n  std::vector<std::string> node_names = model_builder.addSinglyConnected(model, \"HiddenR\", \"HiddenR\", node_names_random, n_inputs,\n    std::make_shared<LinearOp<TensorT>>(LinearOp<TensorT>()),\n    std::make_shared<LinearGradOp<TensorT>>(LinearGradOp<TensorT>()),\n    std::make_shared<ProdOp<TensorT>>(ProdOp<TensorT>()),\n   std::make_shared<ProdErrorOp<TensorT>>(ProdErrorOp<TensorT>()),\n    std::make_shared<ProdWeightGradOp<TensorT>>(ProdWeightGradOp<TensorT>()),\n    weight_init, solver, 0.0f, 0.0f, false, specify_layers);\n  model_builder.addSinglyConnected(model, \"HiddenR\", node_names_mask, node_names,\n    weight_init, solver, 0.0f, specify_layers);\n\n  // Add the output layer\n  node_names = model_builder.addFullyConnected(model, \"Output\", \"Output\", node_names, n_outputs,\n    std::make_shared<LinearOp<TensorT>>(LinearOp<TensorT>()),\n    std::make_shared<LinearGradOp<TensorT>>(LinearGradOp<TensorT>()),\n    std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n    std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n    std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n    weight_init, solver, 0.0f, 0.0f, true, true);  // always specify the output layer!\n\n  for (const std::string& node_name : node_names)\n    model.nodes_.at(node_name)->setType(NodeType::output);\n}\ntemplate<typename TensorT>\nvoid makeModelAttention(Model<TensorT>& model, const int& n_inputs, const int& n_outputs,\n  std::vector<int> n_heads = { 2, 2 },\n  std::vector<int> key_query_values_lengths = { 4, 4 },\n  std::vector<int> model_lengths = { 2, 2 },\n  bool add_FC = true, bool add_skip = true, bool add_norm = false, bool specify_layers = false) {\n  model.setId(0);\n  model.setName(\"AddProbAtt-DotProdAtt-NoBiases\");\n  // NOTE: Biases will be non-optimally split when layers are specified\n\n  ModelBuilder<TensorT> model_builder;\n\n  // Add the inputs\n  std::vector<std::string> node_names_random = model_builder.addInputNodes(model, \"Random\", \"Random\", n_inputs, specify_layers); // Q and V matrices\n  std::vector<std::string> node_names_mask = model_builder.addInputNodes(model, \"Mask\", \"Mask\", n_inputs, specify_layers);  // K matrix\n  std::vector<std::string> node_names_input = node_names_random;  // initial \"input\"\n\n  // Multi-head attention\n  std::vector<std::string> node_names;\n  for (size_t i = 0; i < n_heads.size(); ++i) {\n    // Add the attention\n    std::string name_head1 = \"Attention\" + std::to_string(i);\n    node_names = model_builder.addMultiHeadAttention(model, name_head1, name_head1,\n      node_names_random, node_names_mask, node_names_random,\n      n_heads[i], \"DotProd\", model_lengths[i], key_query_values_lengths[i], key_query_values_lengths[i],\n      std::make_shared<LinearOp<TensorT>>(LinearOp<TensorT>()),\n      std::make_shared<LinearGradOp<TensorT>>(LinearGradOp<TensorT>()),\n      std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>(node_names_input.size(), 2)),\n      std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0f, 0.0f, false, specify_layers);\n    if (add_norm) {\n      std::string norm_name = \"Norm\" + std::to_string(i);\n      node_names = model_builder.addNormalization(model, norm_name, norm_name, node_names, specify_layers);\n      node_names = model_builder.addSinglyConnected(model, norm_name + \"-gain\", norm_name + \"-gain\", node_names, node_names.size(),\n        std::make_shared<LeakyReLUOp<TensorT>>(LeakyReLUOp<TensorT>()),\n        std::make_shared<LeakyReLUGradOp<TensorT>>(LeakyReLUGradOp<TensorT>()),\n        std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n        std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n        std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n        std::make_shared<ConstWeightInitOp<TensorT>>(ConstWeightInitOp<TensorT>(1)),\n        std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0, 0.0, true, specify_layers);\n    }\n    if (add_skip) {\n      std::string skip_name = \"Skip\" + std::to_string(i);\n      model_builder.addSinglyConnected(model, skip_name, node_names_input, node_names,\n        std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>(node_names_input.size(), 2)),\n        std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0f, specify_layers);\n    }\n    node_names_input = node_names;\n\n    // Add the feedforward net\n    if (add_FC) {\n      std::string norm_name = \"FC\" + std::to_string(i);\n      node_names = model_builder.addFullyConnected(model, norm_name, norm_name, node_names_input, n_inputs,\n        std::shared_ptr<ActivationOp<TensorT>>(new ReLUOp<TensorT>()),\n        std::shared_ptr<ActivationOp<TensorT>>(new ReLUGradOp<TensorT>()),\n        std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n        std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n        std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n        std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>(node_names_input.size(), 2)),\n        std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0f, 0.0f, false, specify_layers);\n    }\n    if (add_norm) {\n      std::string norm_name = \"Norm_FC\" + std::to_string(i);\n      node_names = model_builder.addNormalization(model, norm_name, norm_name, node_names, specify_layers);\n      node_names = model_builder.addSinglyConnected(model, norm_name + \"-gain\", norm_name + \"-gain\", node_names, node_names.size(),\n        std::make_shared<LeakyReLUOp<TensorT>>(LeakyReLUOp<TensorT>()),\n        std::make_shared<LeakyReLUGradOp<TensorT>>(LeakyReLUGradOp<TensorT>()),\n        std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n        std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n        std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n        std::make_shared<ConstWeightInitOp<TensorT>>(ConstWeightInitOp<TensorT>(1)),\n        std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0, 0.0, true, specify_layers);\n    }\n    //if (add_skip) {\n    //\tstd::string skip_name = \"Skip_FC\" + std::to_string(i);\n    //\tmodel_builder.addSinglyConnected(model, skip_name, node_names_input, node_names,\n    //\t\tstd::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>(n_inputs, 2)),\n    //\t\tstd::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0f);\n    //}\n    node_names_input = node_names;\n  }\n\n  // Add the FC layer\n  node_names = model_builder.addFullyConnected(model, \"Output\", \"Output\", node_names, n_outputs,\n    std::shared_ptr<ActivationOp<TensorT>>(new ReLUOp<TensorT>()),\n    std::shared_ptr<ActivationOp<TensorT>>(new ReLUGradOp<TensorT>()),\n    std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n    std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n    std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n    std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>(node_names.size(), 2)),\n    std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0f, 0.0f, true, true);\n\n  for (const std::string& node_name : node_names)\n    model.nodes_.at(node_name)->setType(NodeType::output);\n}\ntemplate<typename TensorT>\nvoid makeModelVAE(Model<TensorT>& model, int n_inputs = 784, int n_encodings = 64, int n_hidden_0 = 512, bool specify_layer = false) {\n  model.setId(0);\n  model.setName(\"VAE\");\n\n  ModelBuilder<TensorT> model_builder;\n\n  // Add the inputs\n  std::vector<std::string> node_names_input = model_builder.addInputNodes(model, \"Input\", \"Input\", n_inputs, specify_layer);\n\n  // Add the Endocer FC layers\n  std::vector<std::string> node_names, node_names_mu, node_names_logvar;\n  node_names = model_builder.addFullyConnected(model, \"EN0\", \"EN0\", node_names_input, n_hidden_0,\n    std::make_shared<LinearOp<TensorT>>(LinearOp<TensorT>()),\n    std::make_shared<LinearGradOp<TensorT>>(LinearGradOp<TensorT>()),\n    std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n    std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n    std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n    //std::shared_ptr<WeightInitOp<TensorT>>(new RangeWeightInitOp<TensorT>(0, 2 / (int)(node_names_input.size() + node_names.size()))),\n    std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>((int)(node_names_input.size() + node_names.size()) / 2, 1)),\n    std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8, 10.0)), 0.0f, 0.0f, false, specify_layer);\n  node_names = model_builder.addFullyConnected(model, \"EN1\", \"EN1\", node_names, n_hidden_0,\n    std::make_shared<LinearOp<TensorT>>(LinearOp<TensorT>()),\n    std::make_shared<LinearGradOp<TensorT>>(LinearGradOp<TensorT>()),\n    std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n    std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n    std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n    //std::shared_ptr<WeightInitOp<TensorT>>(new RangeWeightInitOp<TensorT>(0, 2 / (int)(node_names.size() + node_names.size()))),\n    std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>((int)(node_names.size() + node_names.size()) / 2, 1)),\n    std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8, 10.0)), 0.0f, 0.0f, false, specify_layer);\n  node_names_mu = model_builder.addFullyConnected(model, \"Mu\", \"Mu\", node_names, n_encodings,\n    std::make_shared<LinearOp<TensorT>>(LinearOp<TensorT>()),\n    std::make_shared<LinearGradOp<TensorT>>(LinearGradOp<TensorT>()),\n    std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n    std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n    std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n    //std::shared_ptr<WeightInitOp<TensorT>>(new RangeWeightInitOp<TensorT>(0, 2 / (int)(node_names.size() + n_encodings))),\n    std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>((int)(node_names.size() + n_encodings) / 2, 1)),\n    std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8, 10.0)), 0.0f, 0.0f, false, specify_layer);\n  node_names_logvar = model_builder.addFullyConnected(model, \"LogVar\", \"LogVar\", node_names, n_encodings,\n    std::make_shared<LinearOp<TensorT>>(LinearOp<TensorT>()),\n    std::make_shared<LinearGradOp<TensorT>>(LinearGradOp<TensorT>()),\n    std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n    std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n    std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n    //std::shared_ptr<WeightInitOp<TensorT>>(new RangeWeightInitOp<TensorT>(0, 2 / (int)(node_names.size() + n_encodings))),\n    std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>((int)(node_names.size() + n_encodings) / 2, 1)),\n    std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8, 10.0)), 0.0f, 0.0f, false, specify_layer);\n\n  // Specify the output node types manually\n  for (const std::string& node_name : node_names_mu)\n    model.nodes_.at(node_name)->setType(NodeType::output);\n  for (const std::string& node_name : node_names_logvar)\n    model.nodes_.at(node_name)->setType(NodeType::output);\n\n  // Add the Encoding layers\n  std::vector<std::string> node_names_encoder = model_builder.addGaussianEncoding(model, \"Encoding\", \"Encoding\", node_names_mu, node_names_logvar, specify_layer);\n\n  // Add the Decoder FC layers\n  node_names = model_builder.addFullyConnected(model, \"DE0\", \"DE0\", node_names_encoder, n_hidden_0,\n    std::make_shared<LinearOp<TensorT>>(LinearOp<TensorT>()),\n    std::make_shared<LinearGradOp<TensorT>>(LinearGradOp<TensorT>()),\n    std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n    std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n    std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n    //std::shared_ptr<WeightInitOp<TensorT>>(new RangeWeightInitOp<TensorT>(0, 2 / (int)(node_names_encoder.size() + n_hidden_0))),\n    std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>((int)(node_names_encoder.size() + n_hidden_0) / 2, 1)),\n    std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8, 10.0)), 0.0f, 0.0f, false, specify_layer);\n  node_names = model_builder.addFullyConnected(model, \"DE1\", \"DE1\", node_names, n_hidden_0,\n    std::make_shared<LinearOp<TensorT>>(LinearOp<TensorT>()),\n    std::make_shared<LinearGradOp<TensorT>>(LinearGradOp<TensorT>()),\n    std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n    std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n    std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n    //std::shared_ptr<WeightInitOp<TensorT>>(new RangeWeightInitOp<TensorT>(0, 2 / (int)(node_names.size() + n_hidden_0))),\n    std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>((int)(node_names.size() + n_hidden_0) / 2, 1)),\n    std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8, 10.0)), 0.0f, 0.0f, false, specify_layer);\n  node_names = model_builder.addFullyConnected(model, \"Output\", \"Output\", node_names, n_inputs,\n    std::make_shared<LinearOp<TensorT>>(LinearOp<TensorT>()),\n    std::make_shared<LinearGradOp<TensorT>>(LinearGradOp<TensorT>()),\n    std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n    std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n    std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n    //std::shared_ptr<WeightInitOp<TensorT>>(new RangeWeightInitOp<TensorT>(0, 2 / node_names.size())),\n    std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>(node_names.size(), 1)),\n    std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8, 10.0)), 0.0f, 0.0f, false, specify_layer);\n\n  // Specify the output node types manually\n  for (const std::string& node_name : node_names)\n    model.nodes_.at(node_name)->setType(NodeType::output);\n}\ntemplate<typename TensorT>\nvoid makeCovNet(Model<TensorT>& model, const int& n_inputs, const int& n_outputs, int n_depth_1 = 32, int n_depth_2 = 2, int n_fc = 128, int filter_size = 5, int pool_size = 2, bool add_norm = false, bool specify_layers = false) {\n  model.setId(0);\n  model.setName(\"CovNet\");\n\n  ModelBuilder<TensorT> model_builder;\n\n  // Add the inputs\n  std::vector<std::string> node_names_input = model_builder.addInputNodes(model, \"Input\", \"Input\", n_inputs, specify_layers);\n\n  // Add the first convolution -> max pool -> ReLU layers\n  std::vector<std::vector<std::string>> node_names_l0;\n  for (size_t d = 0; d < n_depth_1; ++d) {\n    std::vector<std::string> node_names;\n    std::string conv_name = \"Conv0-\" + std::to_string(d);\n    node_names = model_builder.addConvolution(model, conv_name, \"Conv0-\" /*conv_name*/, node_names_input,\n      sqrt(node_names_input.size()), sqrt(node_names_input.size()), 0, 0,\n      filter_size, filter_size, 1, 0, 0,\n      std::make_shared<LinearOp<TensorT>>(LinearOp<TensorT>()),\n      std::make_shared<LinearGradOp<TensorT>>(LinearGradOp<TensorT>()),\n      std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n      std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n      std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n      std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>(n_inputs, 2)),\n      std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0f, 0.0f, false, specify_layers);\n    if (add_norm) {\n      std::string norm_name = \"Norm0-\" + std::to_string(d);\n      node_names = model_builder.addNormalization(model, norm_name, \"Norm0-\" /*norm_name*/, node_names, specify_layers);\n      node_names = model_builder.addSinglyConnected(model, norm_name + \"-gain\", norm_name + \"-gain\", node_names, node_names.size(),\n        std::make_shared<LeakyReLUOp<TensorT>>(LeakyReLUOp<TensorT>()),\n        std::make_shared<LeakyReLUGradOp<TensorT>>(LeakyReLUGradOp<TensorT>()),\n        std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n        std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n        std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n        std::make_shared<ConstWeightInitOp<TensorT>>(ConstWeightInitOp<TensorT>(1)),\n        std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0, 0.0, true, specify_layers);\n    }\n    std::string pool_name = \"Pool0-\" + std::to_string(d);\n    node_names = model_builder.addConvolution(model, pool_name, \"Pool0-\" /*pool_name*/, node_names,\n      sqrt(node_names.size()), sqrt(node_names.size()), 1, 1,\n      pool_size, pool_size, 2, 0, 0,\n      std::shared_ptr<ActivationOp<TensorT>>(new ReLUOp<TensorT>()),\n      std::shared_ptr<ActivationOp<TensorT>>(new ReLUGradOp<TensorT>()),\n      std::make_shared<MaxOp<TensorT>>(MaxOp<float>()),\n      std::make_shared<MaxErrorOp<TensorT>>(MaxErrorOp<TensorT>()),\n      std::make_shared<MaxWeightGradOp<TensorT>>(MaxWeightGradOp<TensorT>()),\n      std::make_shared<ConstWeightInitOp<TensorT>>(ConstWeightInitOp<TensorT>(1.0)),\n      std::make_shared<DummySolverOp<TensorT>>(DummySolverOp<TensorT>()), 0.0, 0.0, false, specify_layers);\n    node_names_l0.push_back(node_names);\n  }\n\n  // Add the second convolution -> max pool -> ReLU layers\n  std::vector<std::vector<std::string>> node_names_l1;\n  int l_cnt = 0;\n  for (const std::vector<std::string> &node_names_l : node_names_l0) {\n    for (size_t d = 0; d < n_depth_2; ++d) {\n      std::vector<std::string> node_names;\n      std::string conv_name = \"Conv1-\" + std::to_string(l_cnt) + \"-\" + std::to_string(d);\n      node_names = model_builder.addConvolution(model, conv_name, \"Conv1-\" /*conv_name*/, node_names_l,\n        sqrt(node_names_l.size()), sqrt(node_names_l.size()), 0, 0,\n        filter_size, filter_size, 1, 0, 0,\n        std::make_shared<LinearOp<TensorT>>(LinearOp<TensorT>()),\n        std::make_shared<LinearGradOp<TensorT>>(LinearGradOp<TensorT>()),\n        std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n        std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n        std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n        std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>(n_inputs, 2)),\n        std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0f, 0.0f, false, specify_layers);\n      if (add_norm) {\n        std::string norm_name = \"Norm1-\" + std::to_string(l_cnt) + \"-\" + std::to_string(d);\n        node_names = model_builder.addNormalization(model, norm_name, \"Norm1-\" /*norm_name*/, node_names, specify_layers);\n        node_names = model_builder.addSinglyConnected(model, norm_name + \"-gain\", norm_name + \"-gain\", node_names, node_names.size(),\n          std::make_shared<LeakyReLUOp<TensorT>>(LeakyReLUOp<TensorT>()),\n          std::make_shared<LeakyReLUGradOp<TensorT>>(LeakyReLUGradOp<TensorT>()),\n          std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n          std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n          std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n          std::make_shared<ConstWeightInitOp<TensorT>>(ConstWeightInitOp<TensorT>(1)),\n          std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0, 0.0, true, specify_layers);\n      }\n      std::string pool_name = \"Pool1-\" + std::to_string(l_cnt) + \"-\" + std::to_string(d);\n      node_names = model_builder.addConvolution(model, pool_name, \"Pool1-\" /*pool_name*/, node_names,\n        sqrt(node_names.size()), sqrt(node_names.size()), 1, 1,\n        pool_size, pool_size, 2, 0, 0,\n        std::shared_ptr<ActivationOp<TensorT>>(new ReLUOp<TensorT>()),\n        std::shared_ptr<ActivationOp<TensorT>>(new ReLUGradOp<TensorT>()),\n        std::make_shared<MaxOp<TensorT>>(MaxOp<float>()),\n        std::make_shared<MaxErrorOp<TensorT>>(MaxErrorOp<TensorT>()),\n        std::make_shared<MaxWeightGradOp<TensorT>>(MaxWeightGradOp<TensorT>()),\n        std::make_shared<ConstWeightInitOp<TensorT>>(ConstWeightInitOp<TensorT>(1.0)),\n        std::make_shared<DummySolverOp<TensorT>>(DummySolverOp<TensorT>()), 0.0, 0.0, false, specify_layers);\n      node_names_l1.push_back(node_names);\n    }\n    ++l_cnt;\n  }\n\n  // Linearize the node names\n  std::vector<std::string> node_names;\n  //for (const std::vector<std::string> &node_names_l : node_names_l0) {\n  for (const std::vector<std::string> &node_names_l : node_names_l1) {\n    for (const std::string &node_name : node_names_l) {\n      node_names.push_back(node_name);\n    }\n  }\n\n  // Add the FC layers\n  //assert(node_names.size() == 320);\n  node_names = model_builder.addFullyConnected(model, \"FC0\", \"FC0\", node_names, n_fc,\n    std::shared_ptr<ActivationOp<TensorT>>(new ReLUOp<TensorT>()),\n    std::shared_ptr<ActivationOp<TensorT>>(new ReLUGradOp<TensorT>()),\n    std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n    std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n    std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n    std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>(180, 2)),\n    std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0f, 0.0f, false, specify_layers);\n  if (add_norm) {\n    std::string norm_name = \"NormFC0\";\n    node_names = model_builder.addNormalization(model, norm_name, norm_name, node_names, specify_layers);\n    node_names = model_builder.addSinglyConnected(model, norm_name + \"-gain\", norm_name + \"-gain\", node_names, node_names.size(),\n      std::make_shared<LeakyReLUOp<TensorT>>(LeakyReLUOp<TensorT>()),\n      std::make_shared<LeakyReLUGradOp<TensorT>>(LeakyReLUGradOp<TensorT>()),\n      std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n      std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n      std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n      std::make_shared<ConstWeightInitOp<TensorT>>(ConstWeightInitOp<TensorT>(1)),\n      std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(1e-4, 0.9, 0.999, 1e-8)), 0.0, 0.0, true, specify_layers);\n  }\n  node_names = model_builder.addFullyConnected(model, \"FC1\", \"FC1\", node_names, n_outputs,\n    std::shared_ptr<ActivationOp<TensorT>>(new ReLUOp<TensorT>()),\n    std::shared_ptr<ActivationOp<TensorT>>(new ReLUGradOp<TensorT>()),\n    std::make_shared<SumOp<TensorT>>(SumOp<TensorT>()),\n    std::make_shared<SumErrorOp<TensorT>>(SumErrorOp<TensorT>()),\n    std::make_shared<SumWeightGradOp<TensorT>>(SumWeightGradOp<TensorT>()),\n    std::make_shared<RandWeightInitOp<TensorT>>(RandWeightInitOp<TensorT>(n_fc, 2)),\n    std::make_shared<AdamOp<TensorT>>(AdamOp<TensorT>(0.001, 0.9, 0.999, 1e-8)), 0.0f, 0.0f, false, true);\n\n  for (const std::string& node_name : node_names)\n    model.getNodesMap().at(node_name)->setType(NodeType::output);\n}\n\nBOOST_AUTO_TEST_CASE(makeModelSolution1)\n{\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model_test;\n  makeModelSolution(model_test, 2, 1, true);\n\n  int iter_test = 0;\n  std::vector<OperationList<float>> FP_operations_expanded_test;\n  model_interpreter.getFPOpsOoO_(model_test, FP_operations_expanded_test, iter_test);\n\n  std::set<std::string> identified_sink_nodes_test;\n  std::map<std::string, std::vector<int>> tensor_ops_test = model_interpreter.getTensorOperations(FP_operations_expanded_test, identified_sink_nodes_test, true);\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model;\n  makeModelSolution(model, 2, 1, false);\n\n  int iter = 0;\n  std::vector<OperationList<float>> FP_operations_expanded;\n  model_interpreter.getFPOpsOoO_(model, FP_operations_expanded, iter);\n\n  std::set<std::string> identified_sink_nodes;\n  std::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n  BOOST_CHECK_EQUAL(iter_test, iter);\n  BOOST_CHECK(tensor_ops_test == tensor_ops);\n  BOOST_CHECK(identified_sink_nodes_test == identified_sink_nodes);\n  BOOST_CHECK_EQUAL(FP_operations_expanded_test.size(), FP_operations_expanded.size());\n  if (tensor_ops_test == tensor_ops && identified_sink_nodes_test == identified_sink_nodes && FP_operations_expanded_test.size() == FP_operations_expanded.size()) {\n    for (int i = 0; i < FP_operations_expanded_test.size(); ++i) {\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.sink_node->getName(), FP_operations_expanded[i].result.sink_node->getName());\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.time_step, FP_operations_expanded[i].result.time_step);\n      for (int j = 0; j < FP_operations_expanded_test[i].arguments.size(); ++j) {\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].source_node->getName(), FP_operations_expanded[i].arguments[j].source_node->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].weight->getName(), FP_operations_expanded[i].arguments[j].weight->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].time_step, FP_operations_expanded[i].arguments[j].time_step);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(makeModelAttention1)\n{\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model_test;\n  makeModelAttention(model_test, 1, 1, { 2 }, { 3 }, { 1 }, false, false, false, true);\n\n  int iter_test = 0;\n  std::vector<OperationList<float>> FP_operations_expanded_test;\n  model_interpreter.getFPOpsOoO_(model_test, FP_operations_expanded_test, iter_test);\n\n  std::set<std::string> identified_sink_nodes_test;\n  std::map<std::string, std::vector<int>> tensor_ops_test = model_interpreter.getTensorOperations(FP_operations_expanded_test, identified_sink_nodes_test, true);\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model;\n  makeModelAttention(model, 1, 1, { 2 }, { 3 }, { 1 }, false, false, false, false);\n\n  int iter = 0;\n  std::vector<OperationList<float>> FP_operations_expanded;\n  model_interpreter.getFPOpsOoO_(model, FP_operations_expanded, iter);\n\n  std::set<std::string> identified_sink_nodes;\n  std::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n  BOOST_CHECK_EQUAL(iter_test, iter);\n  BOOST_CHECK(tensor_ops_test == tensor_ops);\n  BOOST_CHECK(identified_sink_nodes_test == identified_sink_nodes);\n  BOOST_CHECK_EQUAL(FP_operations_expanded_test.size(), FP_operations_expanded.size());\n  if (tensor_ops_test == tensor_ops && identified_sink_nodes_test == identified_sink_nodes && FP_operations_expanded_test.size() == FP_operations_expanded.size()) {\n    for (int i = 0; i < FP_operations_expanded_test.size(); ++i) {\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.sink_node->getName(), FP_operations_expanded[i].result.sink_node->getName());\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.time_step, FP_operations_expanded[i].result.time_step);\n      for (int j = 0; j < FP_operations_expanded_test[i].arguments.size(); ++j) {\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].source_node->getName(), FP_operations_expanded[i].arguments[j].source_node->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].weight->getName(), FP_operations_expanded[i].arguments[j].weight->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].time_step, FP_operations_expanded[i].arguments[j].time_step);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(makeModelAttention2)\n{\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model_test;\n  makeModelAttention(model_test, 1, 1, { 2 }, { 3 }, { 1 }, true, true, false, true);\n\n  int iter_test = 0;\n  std::vector<OperationList<float>> FP_operations_expanded_test;\n  model_interpreter.getFPOpsOoO_(model_test, FP_operations_expanded_test, iter_test);\n\n  std::set<std::string> identified_sink_nodes_test;\n  std::map<std::string, std::vector<int>> tensor_ops_test = model_interpreter.getTensorOperations(FP_operations_expanded_test, identified_sink_nodes_test, true);\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model;\n  makeModelAttention(model, 1, 1, { 2 }, { 3 }, { 1 }, true, true, false, false);\n\n  int iter = 0;\n  std::vector<OperationList<float>> FP_operations_expanded;\n  model_interpreter.getFPOpsOoO_(model, FP_operations_expanded, iter);\n\n  std::set<std::string> identified_sink_nodes;\n  std::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n  BOOST_CHECK_EQUAL(iter_test, iter);\n  BOOST_CHECK(tensor_ops_test == tensor_ops);\n  BOOST_CHECK(identified_sink_nodes_test == identified_sink_nodes);\n  BOOST_CHECK_EQUAL(FP_operations_expanded_test.size(), FP_operations_expanded.size());\n  if (tensor_ops_test == tensor_ops && identified_sink_nodes_test == identified_sink_nodes && FP_operations_expanded_test.size() == FP_operations_expanded.size()) {\n    for (int i = 0; i < FP_operations_expanded_test.size(); ++i) {\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.sink_node->getName(), FP_operations_expanded[i].result.sink_node->getName());\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.time_step, FP_operations_expanded[i].result.time_step);\n      for (int j = 0; j < FP_operations_expanded_test[i].arguments.size(); ++j) {\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].source_node->getName(), FP_operations_expanded[i].arguments[j].source_node->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].weight->getName(), FP_operations_expanded[i].arguments[j].weight->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].time_step, FP_operations_expanded[i].arguments[j].time_step);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(makeModelAttention3)\n{\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model_test;\n  makeModelAttention(model_test, 1, 1, { 2 }, { 3 }, { 1 }, true, true, true, true);\n\n  int iter_test = 0;\n  std::vector<OperationList<float>> FP_operations_expanded_test;\n  model_interpreter.getFPOpsOoO_(model_test, FP_operations_expanded_test, iter_test);\n\n  std::set<std::string> identified_sink_nodes_test;\n  std::map<std::string, std::vector<int>> tensor_ops_test = model_interpreter.getTensorOperations(FP_operations_expanded_test, identified_sink_nodes_test, true);\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model;\n  makeModelAttention(model, 1, 1, { 2 }, { 3 }, { 1 }, true, true, true, false);\n\n  int iter = 0;\n  std::vector<OperationList<float>> FP_operations_expanded;\n  model_interpreter.getFPOpsOoO_(model, FP_operations_expanded, iter);\n\n  std::set<std::string> identified_sink_nodes;\n  std::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n  BOOST_CHECK_EQUAL(iter_test, iter);\n  BOOST_CHECK(tensor_ops_test == tensor_ops);\n  BOOST_CHECK(identified_sink_nodes_test == identified_sink_nodes);\n  BOOST_CHECK_EQUAL(FP_operations_expanded_test.size(), FP_operations_expanded.size());\n  if (tensor_ops_test == tensor_ops && identified_sink_nodes_test == identified_sink_nodes && FP_operations_expanded_test.size() == FP_operations_expanded.size()) {\n    for (int i = 0; i < FP_operations_expanded_test.size(); ++i) {\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.sink_node->getName(), FP_operations_expanded[i].result.sink_node->getName());\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.time_step, FP_operations_expanded[i].result.time_step);\n      for (int j = 0; j < FP_operations_expanded_test[i].arguments.size(); ++j) {\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].source_node->getName(), FP_operations_expanded[i].arguments[j].source_node->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].weight->getName(), FP_operations_expanded[i].arguments[j].weight->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].time_step, FP_operations_expanded[i].arguments[j].time_step);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(makeModelVAE1)\n{\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model_test;\n  makeModelVAE(model_test, 6, 2, 4, true);\n\n  int iter_test = 0;\n  std::vector<OperationList<float>> FP_operations_expanded_test;\n  model_interpreter.getFPOpsOoO_(model_test, FP_operations_expanded_test, iter_test);\n\n  std::set<std::string> identified_sink_nodes_test;\n  std::map<std::string, std::vector<int>> tensor_ops_test = model_interpreter.getTensorOperations(FP_operations_expanded_test, identified_sink_nodes_test, true);\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model;\n  makeModelVAE(model, 6, 2, 4, false);\n\n  int iter = 0;\n  std::vector<OperationList<float>> FP_operations_expanded;\n  model_interpreter.getFPOpsOoO_(model, FP_operations_expanded, iter);\n\n  std::set<std::string> identified_sink_nodes;\n  std::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n  BOOST_CHECK_EQUAL(iter_test, iter);\n  BOOST_CHECK(tensor_ops_test == tensor_ops);\n  BOOST_CHECK(identified_sink_nodes_test == identified_sink_nodes);\n  BOOST_CHECK_EQUAL(FP_operations_expanded_test.size(), FP_operations_expanded.size());\n  if (tensor_ops_test == tensor_ops && identified_sink_nodes_test == identified_sink_nodes && FP_operations_expanded_test.size() == FP_operations_expanded.size()) {\n    for (int i = 0; i < FP_operations_expanded_test.size(); ++i) {\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.sink_node->getName(), FP_operations_expanded[i].result.sink_node->getName());\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.time_step, FP_operations_expanded[i].result.time_step);\n      for (int j = 0; j < FP_operations_expanded_test[i].arguments.size(); ++j) {\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].source_node->getName(), FP_operations_expanded[i].arguments[j].source_node->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].weight->getName(), FP_operations_expanded[i].arguments[j].weight->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].time_step, FP_operations_expanded[i].arguments[j].time_step);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(makeModelCovNet1)\n{\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model_test;\n  makeCovNet(model_test, 4, 2, 2, 2, 3, 2, 2, false, true);\n\n  int iter_test = 0;\n  std::vector<OperationList<float>> FP_operations_expanded_test;\n  model_interpreter.getFPOpsOoO_(model_test, FP_operations_expanded_test, iter_test);\n\n  std::set<std::string> identified_sink_nodes_test;\n  std::map<std::string, std::vector<int>> tensor_ops_test = model_interpreter.getTensorOperations(FP_operations_expanded_test, identified_sink_nodes_test, true);\n\n  // Determine the tensor_ops_steps and FP_operations for the manually specified layer case\n  Model<float> model;\n  makeCovNet(model, 4, 2, 2, 2, 3, 2, 2, false, false);\n\n  int iter = 0;\n  std::vector<OperationList<float>> FP_operations_expanded;\n  model_interpreter.getFPOpsOoO_(model, FP_operations_expanded, iter);\n\n  std::set<std::string> identified_sink_nodes;\n  std::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_expanded, identified_sink_nodes, false);\n\n  BOOST_CHECK_EQUAL(iter_test, iter);\n  BOOST_CHECK(tensor_ops_test == tensor_ops);\n  BOOST_CHECK(identified_sink_nodes_test == identified_sink_nodes);\n  BOOST_CHECK_EQUAL(FP_operations_expanded_test.size(), FP_operations_expanded.size());\n  if (tensor_ops_test == tensor_ops && identified_sink_nodes_test == identified_sink_nodes && FP_operations_expanded_test.size() == FP_operations_expanded.size()) {\n    for (int i = 0; i < FP_operations_expanded_test.size(); ++i) {\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.sink_node->getName(), FP_operations_expanded[i].result.sink_node->getName());\n      BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].result.time_step, FP_operations_expanded[i].result.time_step);\n      for (int j = 0; j < FP_operations_expanded_test[i].arguments.size(); ++j) {\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].source_node->getName(), FP_operations_expanded[i].arguments[j].source_node->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].weight->getName(), FP_operations_expanded[i].arguments[j].weight->getName());\n        BOOST_CHECK_EQUAL(FP_operations_expanded_test[i].arguments[j].time_step, FP_operations_expanded[i].arguments[j].time_step);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "bacc9f478e11a363a8fbe3af5dd2e9cf5499f998", "size": 80424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/class_tests/evonet/source/ModelInterpreter_DAG_test.cpp", "max_stars_repo_name": "dmccloskey/smartPeak_cpp", "max_stars_repo_head_hexsha": "47a19a804b65daef712418b4e278704b340d20b9", "max_stars_repo_licenses": ["MIT"], "max_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/class_tests/evonet/source/ModelInterpreter_DAG_test.cpp", "max_issues_repo_name": "dmccloskey/smartPeak_cpp", "max_issues_repo_head_hexsha": "47a19a804b65daef712418b4e278704b340d20b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-01-11T20:39:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-11T21:02:31.000Z", "max_forks_repo_path": "src/tests/class_tests/evonet/source/ModelInterpreter_DAG_test.cpp", "max_forks_repo_name": "dmccloskey/smartPeak_cpp", "max_forks_repo_head_hexsha": "47a19a804b65daef712418b4e278704b340d20b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.832479883, "max_line_length": 354, "alphanum_fraction": 0.7553217945, "num_tokens": 22264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276107, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5408093404099871}}
{"text": "#include \"dynet/nodes.h\"\n#include \"dynet/dynet.h\"\n#include \"dynet/training.h\"\n#include \"dynet/timing.h\"\n#include \"dynet/rnn.h\"\n#include \"dynet/gru.h\"\n#include \"dynet/lstm.h\"\n#include \"dynet/dict.h\"\n#include \"dynet/expr.h\"\n#include \"../utils/getpid.h\"\n\n#include <iostream>\n#include <fstream>\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n\nusing namespace std;\nusing namespace dynet;\n\nunsigned INPUT_DIM = 36;\nunsigned OUTPUT_DIM = 36;\nunsigned VOCAB_SIZE = 0;\nunsigned LABEL_SIZE = 0;\nfloat pdropout = 0.5;\n\ndynet::Dict d;\ndynet::Dict ld;\nint kSOS;\nint kEOS;\n\nstruct NeuralBagOfWords {\n  LookupParameter p_w;\n  Parameter p_c2h;\n  Parameter p_hbias;\n  Parameter p_h2o;\n  Parameter p_obias;\n\n  explicit NeuralBagOfWords(Model& m) :\n      p_w(m.add_lookup_parameters(VOCAB_SIZE, {INPUT_DIM})),\n      p_c2h(m.add_parameters({OUTPUT_DIM, INPUT_DIM})),\n      p_hbias(m.add_parameters({OUTPUT_DIM})),\n      p_h2o(m.add_parameters({LABEL_SIZE, OUTPUT_DIM})),\n      p_obias(m.add_parameters({LABEL_SIZE})) {}\n\n  Expression BuildClassifier(const vector<int>& x, ComputationGraph& cg) {\n    Expression c2h = parameter(cg, p_c2h);\n    Expression hbias = parameter(cg, p_hbias);\n    Expression h2o = parameter(cg, p_h2o);\n    Expression obias = parameter(cg, p_obias);\n\n    vector<Expression> vx(x.size());\n    for (unsigned i = 0; i < x.size(); ++i)\n      vx[i] = lookup(cg, p_w, x[i]);\n    Expression c = sum(vx);\n    Expression h = rectify(c2h * c / x.size() + hbias);\n    Expression y_pred = obias + h2o * h;\n    return y_pred;\n  }\n};\n\nstruct ConvLayer {\n  // in_rows = rows per word in input matrix\n  // k_fold_rows = 1 no folding, 2 fold two rows together, 3 ...\n  // filter_width = length of filter (columns)\n  // in_nfmaps = number of feature maps in input\n  // out_nfmaps = number of feature maps in output\n  ConvLayer(Model& m, int in_rows, int k_fold_rows, int filter_width, int in_nfmaps, int out_nfmaps) :\n      p_filts(in_nfmaps),\n      p_fbias(in_nfmaps),\n      k_fold_rows(k_fold_rows) {\n    if (k_fold_rows < 1 || ((in_rows / k_fold_rows) * k_fold_rows != in_rows)) {\n      cerr << \"Bad k_fold_rows=\" << k_fold_rows << endl;\n      abort();\n    }\n    for (int i = 0; i < in_nfmaps; ++i) {\n      p_filts[i].resize(out_nfmaps);\n      p_fbias[i].resize(out_nfmaps);\n      for (int j = 0; j < out_nfmaps; ++j) {\n        p_filts[i][j] = m.add_parameters({(unsigned)in_rows, (unsigned)filter_width}, 0.01);\n        p_fbias[i][j] = m.add_parameters({(unsigned)in_rows}, 0.05);\n      }\n    }\n    //for (int j = 0; j < out_nfmaps; ++j)\n      //p_fbias[j] = m.add_parameters({in_rows});\n  }\n\n  vector<Expression> apply(ComputationGraph& cg, const vector<Expression>& inlayer, int k_out) const {\n    const unsigned out_nfmaps = p_filts.front().size();\n    const unsigned in_nfmaps = p_filts.size();\n    if (in_nfmaps != inlayer.size()) {\n      cerr << \"Mismatched number of input features (\" << inlayer.size() << \"), expected \" << in_nfmaps << endl;\n      abort();\n    }\n    vector<Expression> r(out_nfmaps);\n\n    vector<Expression> tmp(in_nfmaps);\n    for (unsigned fj = 0; fj < out_nfmaps; ++fj) {\n      for (unsigned fi = 0; fi < in_nfmaps; ++fi) {\n        Expression t = conv1d_wide(inlayer[fi], parameter(cg, p_filts[fi][fj]));\n        t = colwise_add(t, parameter(cg, p_fbias[fi][fj]));\n        tmp[fi] = t;\n      }\n      Expression s = sum(tmp);\n      if (k_fold_rows > 1)\n        s = fold_rows(s, k_fold_rows);\n      s = kmax_pooling(s, k_out);\n      r[fj] = rectify(s);\n    }\n    return r;\n  }\n  vector<vector<Parameter>> p_filts; // [feature map index from][feature map index to]\n  vector<vector<Parameter>> p_fbias; // [feature map index from][feature map index to]\n  int k_fold_rows;\n};\n\nstruct ConvNet {\n  LookupParameter p_w;\n  ConvLayer cl1;\n  ConvLayer cl2;\n  Parameter p_t2o;\n  Parameter p_obias;\n\n  explicit ConvNet(Model& m) :\n      p_w(m.add_lookup_parameters(VOCAB_SIZE, {INPUT_DIM})),\n  //ConvLayer(Model& m, int in_rows, int k_fold_rows, int filter_width, int in_nfmaps, int out_nfmaps) :\n      cl1(m, INPUT_DIM, 2,  10, 1, 6),\n      cl2(m, INPUT_DIM/2, 2, 6, 6, 14),\n      p_t2o(m.add_parameters({LABEL_SIZE, 14 * (INPUT_DIM / 4) * 5})),\n      p_obias(m.add_parameters({LABEL_SIZE})) {\n  }\n\n  Expression BuildClassifier(const vector<int>& x, ComputationGraph& cg, bool for_training) {\n    Expression t2o = parameter(cg, p_t2o);\n    Expression obias = parameter(cg, p_obias);\n    int k_2 = 5;\n    int len = x.size();\n    int k_1 = max(k_2, len / 2);\n    vector<Expression> vx(x.size());\n    for (unsigned i = 0; i < x.size(); ++i)\n      vx[i] = lookup(cg, p_w, x[i]);\n    Expression s = concatenate_cols(vx);\n    \n    vector<Expression> l0(1, s);\n    vector<Expression> l1 = cl1.apply(cg, l0, k_1);\n    vector<Expression> l2 = cl2.apply(cg, l1, k_2);\n    for(auto& fm : l2)\n      fm = reshape(fm, {k_2 * INPUT_DIM / 4});\n    Expression t = concatenate(l2);\n    if (for_training)\n      t = dropout(t, pdropout);\n    Expression r = t2o * t + obias;\n    return r;\n  }\n};\n\nbool IsCurrentPredictionCorrection(Expression y_pred, int y_true) {\n  ComputationGraph& cg = *y_pred.pg;\n  auto v = as_vector(cg.incremental_forward(y_pred));\n  assert(v.size() > 1);\n  int besti = 0;\n  float best = v[0];\n  for (unsigned i = 1; i < v.size(); ++i)\n    if (v[i] > best) { best = v[i]; besti = i; }\n  return (besti == y_true);\n}\n\nExpression CrossEntropyLoss(const Expression& y_pred, int y_true) {\n  Expression lp = log_softmax(y_pred);\n  Expression nll = -pick(lp, y_true);\n  return nll;\n}\n\nExpression HingeLoss(const Expression& y_pred, int y_true) {\n  Expression hl = hinge(y_pred, y_true, 10.0f);\n  return hl;\n}\n\nint main(int argc, char** argv) {\n  dynet::initialize(argc, argv);\n  if (argc != 3 && argc != 4) {\n    cerr << \"Usage: \" << argv[0] << \" corpus.txt dev.txt [model.params]\\n\";\n    return 1;\n  }\n  kSOS = d.convert(\"<s>\");\n  kEOS = d.convert(\"</s>\");\n  vector<pair<vector<int>,int>> training, dev;\n  string line;\n  int tlc = 0;\n  int ttoks = 0;\n  cerr << \"Reading training data from \" << argv[1] << \"...\\n\";\n  {\n    ifstream in(argv[1]);\n    assert(in);\n    while(getline(in, line)) {\n      ++tlc;\n      vector<int> x,y;\n      read_sentence_pair(line, x, d, y, ld);\n      if (x.size() == 0 || y.size() != 1) { cerr << line << endl; abort(); }\n      training.push_back(make_pair(x,y[0]));\n      ttoks += x.size();\n    }\n    cerr << tlc << \" lines, \" << ttoks << \" tokens, \" << d.size() << \" types\\n\";\n    cerr << \"Labels: \" << ld.size() << endl;\n  }\n  LABEL_SIZE = ld.size();\n  //d.freeze(); // no new word types allowed\n  ld.freeze(); // no new tag types allowed\n\n  int dlc = 0;\n  int dtoks = 0;\n  cerr << \"Reading dev data from \" << argv[2] << \"...\\n\";\n  {\n    ifstream in(argv[2]);\n    assert(in);\n    while(getline(in, line)) {\n      ++dlc;\n      vector<int> x,y;\n      read_sentence_pair(line, x, d, y, ld);\n      assert(y.size() == 1);\n      dev.push_back(make_pair(x,y[0]));\n      dtoks += x.size();\n    }\n    cerr << dlc << \" lines, \" << dtoks << \" tokens\\n\";\n  }\n  VOCAB_SIZE = d.size();\n  ostringstream os;\n  os << \"textcat\"\n     << '_' << INPUT_DIM\n     << '_' << OUTPUT_DIM\n     << \"-pid\" << getpid() << \".params\";\n  const string fname = os.str();\n  cerr << \"Parameters will be written to: \" << fname << endl;\n  double best = 9e+99;\n\n  Model model;\n  Trainer* sgd = nullptr;\n  //sgd = new MomentumSGDTrainer(model);\n  sgd = new AdagradTrainer(model);\n  //sgd = new SimpleSGDTrainer(model);\n\n  //NeuralBagOfWords nbow(model);\n  ConvNet nbow(model);\n\n  unsigned report_every_i = min(100, int(training.size()));\n  unsigned dev_every_i_reports = 25;\n  unsigned si = training.size();\n  vector<unsigned> order(training.size());\n  for (unsigned i = 0; i < order.size(); ++i) order[i] = i;\n  bool first = true;\n  int report = 0;\n  unsigned lines = 0;\n  while(1) {\n    Timer iteration(\"completed in\");\n    double loss = 0;\n    unsigned ttags = 0;\n    unsigned correct = 0;\n    for (unsigned i = 0; i < report_every_i; ++i) {\n      if (si == training.size()) {\n        si = 0;\n        if (first) { first = false; } else { sgd->update_epoch(); }\n        cerr << \"**SHUFFLE\\n\";\n        shuffle(order.begin(), order.end(), *rndeng);\n      }\n\n      // build graph for this instance\n      ComputationGraph cg;\n      auto& sentx_y = training[order[si]];\n      const auto& x = sentx_y.first;\n      const int y = sentx_y.second;\n      ++si;\n      //cerr << \"LINE: \" << order[si] << endl;\n      Expression y_pred = nbow.BuildClassifier(x, cg, true);\n      //Expression loss_expr = CrossEntropyLoss(y_pred, y);\n      Expression loss_expr = HingeLoss(y_pred, y);\n      loss += as_scalar(cg.forward(loss_expr));\n      cg.backward(loss_expr);\n      sgd->update(2.0);\n      ++lines;\n      ++ttags;\n    }\n    sgd->status();\n    cerr << \" E = \" << (loss / ttags) << \" ppl=\" << exp(loss / ttags) << \" (acc=\" << (correct / (double)ttags) << \") \";\n    model.project_weights();\n\n    // show score on dev data?\n    report++;\n    if (report % dev_every_i_reports == 0) {\n      double dloss = 0;\n      unsigned dtags = 0;\n      unsigned dcorr = 0;\n      for (auto& sent : dev) {\n        const auto& x = sent.first;\n        const int y = sent.second;\n        nbow.p_t2o.get()->scale_parameters(pdropout);\n        ComputationGraph cg;\n        Expression y_pred = nbow.BuildClassifier(x, cg, false);\n        if (IsCurrentPredictionCorrection(y_pred, y)) dcorr++;\n        //Expression loss_expr = CrossEntropyLoss(y_pred, y);\n        Expression loss_expr = HingeLoss(y_pred, y);\n        //cerr << \"DEVLINE: \" << dtags << endl;\n        dloss += as_scalar(cg.incremental_forward(loss_expr));\n        nbow.p_t2o.get()->scale_parameters(1.f/pdropout);\n        dtags++;\n      }\n      if (dloss < best) {\n        best = dloss;\n        ofstream out(fname);\n        boost::archive::text_oarchive oa(out);\n        oa << model;\n      }\n      cerr << \"\\n***DEV [epoch=\" << (lines / (double)training.size()) << \"] E = \" << (dloss / dtags) << \" ppl=\" << exp(dloss / dtags) << \" acc=\" << (dcorr / (double)dtags) << ' ';\n    }\n  }\n  delete sgd;\n}\n\n", "meta": {"hexsha": "ba068dd3b24f2ba3ea072c729dfa72eb8c8bcd9e", "size": 10058, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/cpp/textcat/train_textcat.cc", "max_stars_repo_name": "awesome-archive/dynet", "max_stars_repo_head_hexsha": "870bef1c4a8b6c66541c33777b962e6c7a18856f", "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/cpp/textcat/train_textcat.cc", "max_issues_repo_name": "awesome-archive/dynet", "max_issues_repo_head_hexsha": "870bef1c4a8b6c66541c33777b962e6c7a18856f", "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/cpp/textcat/train_textcat.cc", "max_forks_repo_name": "awesome-archive/dynet", "max_forks_repo_head_hexsha": "870bef1c4a8b6c66541c33777b962e6c7a18856f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-26T12:39:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-26T12:39:08.000Z", "avg_line_length": 31.6289308176, "max_line_length": 179, "alphanum_fraction": 0.6031020084, "num_tokens": 3022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5408093298391476}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <chrono>\n#include<deformation_measures.h>\n\ntypedef std::chrono::high_resolution_clock Clock;\ntypedef std::vector<double> stdv;\n\nint main(){\n    /*\n    ==============\n    |    main    |\n    ==============\n    \n    Tests different methods for computing tensor multiplications and reports the \n    relative speeds.\n    */\n\n    //Deformation measures\n    double J = 1.2;\n    Matrix_3x3 F;\n    Matrix_3x3 chi;\n\n    //Stress measures\n    Vector_9  PK2_voigt;\n    Vector_9  SIGMA_voigt;\n    Vector_27 M_voigt;\n\n    Vector_9  cauchy_voigt;\n    Vector_9  s_voigt;\n    Vector_27 m_voigt;\n\n    //PK2 Jacobians\n    Matrix_9x9  dPK2dF;\n    Matrix_9x9  dPK2dchi;\n    Matrix_9x27 dPK2dgrad_chi;\n\n    //SIGMA Jacobians\n    Matrix_9x9  dSIGMAdF;\n    Matrix_9x9  dSIGMAdchi;\n    Matrix_9x27 dSIGMAdgrad_chi;\n\n    //Higher order stress Jacobians\n    Matrix_27x9  dMdF;\n    Matrix_27x9  dMdchi;\n    Matrix_27x27 dMdgrad_chi;\n\n    //Cauchy jacobians\n    Matrix_9x9  dcauchydF;\n    Matrix_9x9  dcauchydchi;\n    Matrix_9x27 dcauchydgrad_chi;\n\n    //s Jacobians\n    Matrix_9x9  dsdF;\n    Matrix_9x9  dsdchi;\n    Matrix_9x27 dsdgrad_chi;\n\n    //m Jacobians\n    Matrix_27x9  dmdF;\n    Matrix_27x9  dmdchi;\n    Matrix_27x27 dmdgrad_chi;\n\n    //Set random values\n    F            = Matrix_3x3::Random();\n    chi          = Matrix_3x3::Random();\n\n    PK2_voigt    = Vector_9::Random();\n    SIGMA_voigt  = Vector_9::Random();\n    M_voigt      = Vector_27::Random();\n\n    cauchy_voigt = Vector_9::Random();\n    s_voigt      = Vector_9::Random();\n    m_voigt      = Vector_27::Random();\n\n    dPK2dF        = Matrix_9x9::Random();\n    dPK2dchi      = Matrix_9x9::Random();\n    dPK2dgrad_chi = Matrix_9x27::Random();\n\n    dSIGMAdF        = Matrix_9x9::Random();\n    dSIGMAdchi      = Matrix_9x9::Random();\n    dSIGMAdgrad_chi = Matrix_9x27::Random();\n\n    dMdF        = Matrix_27x9::Random();\n    dMdchi      = Matrix_27x9::Random();\n    dMdgrad_chi = Matrix_27x27::Random();\n\n    int n = 10000;\n\n    auto t0 = Clock::now();\n    auto t1 = Clock::now();\n    \n    t0 = Clock::now();\n    for (int _n=0; _n<n; _n++){\n        deformation_measures::map_jacobians_to_current_configuration(F, chi,\n            PK2_voigt,    SIGMA_voigt, M_voigt,\n            cauchy_voigt, s_voigt,     m_voigt,\n            dPK2dF,       dPK2dchi,    dPK2dgrad_chi,\n            dSIGMAdF,     dSIGMAdchi,  dSIGMAdgrad_chi,\n            dMdF,         dMdchi,      dMdgrad_chi,\n            dcauchydF,    dcauchydchi, dcauchydgrad_chi,\n            dsdF,         dsdchi,      dsdgrad_chi,\n            dmdF,         dmdchi,      dmdgrad_chi);\n    }\n    t1 = Clock::now();\n    std::cout << \"### Map Jacobians ###\\n\";\n    std::cout << \"   Eigen Matrices: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count()/((double)n) << \"\\n\";\n\n    t0 = Clock::now();\n    for (int _n = 0; _n<n; _n++){\n        deformation_measures::map_dAdgrad_chi_to_dadgrad_chi(dMdgrad_chi, J, F, chi, dmdgrad_chi); \n    }\n    t1 = Clock::now();\n    std::cout << \"### map_dAdgrad_chi_to_dadgrad_chi ###\\n\";\n    std::cout << \"    Full nested loops: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count()/((double)n) << \"\\n\";\n\n    t0 = Clock::now();\n    for (int _n = 0; _n<n; _n++){\n        deformation_measures::map_dAdgrad_chi_to_dadgrad_chi_alt(dMdgrad_chi, J, F, chi, dmdgrad_chi); \n    }\n    t1 = Clock::now();\n    std::cout << \"    Alternative nesting: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count()/((double)n) << \"\\n\";\n\n\n    return 1;\n}\n", "meta": {"hexsha": "078c51b39fcd8a384a50e3187ec108d0a34b93d2", "size": 3567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/efficiency_tests/tensor_multiplication.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/efficiency_tests/tensor_multiplication.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/efficiency_tests/tensor_multiplication.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": 28.3095238095, "max_line_length": 138, "alphanum_fraction": 0.6002242781, "num_tokens": 1214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5408093298391476}}
{"text": "#ifndef MODULE_OPTIMIZER_HPP\r\n#define MODULE_OPTIMIZER_HPP\r\n\r\n#define _USE_MATH_DEFINES\r\n#define M_PI 3.14159265358979323846\r\n\r\n#include <math.h>\r\n#include <Eigen/Core>\r\n#include <algorithm>\r\n#include <functional>\r\n#include <numeric>\r\n#include <vector>\r\n#include \"main.h\"\r\n#include \"utility/io/uart.hpp\"\r\n#include \"utility/math/saturation.hpp\"\r\n\r\nnamespace module {\r\nnamespace MPC {\r\n    namespace AdaptiveMPC {\r\n\r\n        class Optimizer {\r\n        public:\r\n            Optimizer(int ch_max);\r\n\r\n            template <typename T>\r\n            float ProcessModel(const T& model,\r\n                               int mode,\r\n                               std::vector<float>& states,\r\n                               std::vector<float>& setpoint,\r\n                               std::vector<float>& input_states,\r\n                               std::vector<float>& output_states) {\r\n\r\n                utility::io::debug.out(\"Process model mode %d\\n\", mode);\r\n\r\n                // Given a control action, select the correct model matrix, from that linearize the model about the\r\n                // current state point. Calculate the next state vector. Call the control error function and return the\r\n                // errors\r\n                Eigen::Matrix<float, 4, 4> A_mat;\r\n\r\n                if (mode == 1) {\r\n                    // Negative\r\n                    Linearise(model,\r\n                              states,\r\n                              -dotV_a(states[2], model.P_a, model.muscle1),\r\n                              dotV_a(model.P_t, states[3], model.muscle2),\r\n                              -dotV_a_P_m1(states[2], model.P_a, model.muscle1, mode),\r\n                              dotV_a_P_m2(model.P_t, states[3], model.muscle2, mode),\r\n                              A_mat);\r\n                }\r\n                else if (mode == 2) {\r\n                    // Positive\r\n                    Linearise(model,\r\n                              states,\r\n                              dotV_a(model.P_t, states[2], model.muscle1),\r\n                              -dotV_a(states[3], model.P_a, model.muscle2),\r\n                              dotV_a_P_m1(model.P_t, states[2], model.muscle1, mode),\r\n                              -dotV_a_P_m2(states[3], model.P_a, model.muscle2, mode),\r\n                              A_mat);\r\n                }\r\n                else if (mode == 3) {\r\n                    // No move\r\n                    Linearise(model,\r\n                              states,\r\n                              dotV_a(model.P_t, states[2], model.muscle1),\r\n                              dotV_a(model.P_t, states[3], model.muscle2),\r\n                              dotV_a_P_m1(model.P_t, states[2], model.muscle1, mode),\r\n                              dotV_a_P_m2(model.P_t, states[3], model.muscle2, mode),\r\n                              A_mat);\r\n                }\r\n                else {\r\n                    Error_Handler();\r\n                }\r\n\r\n                utility::io::debug.out(\"A mat\\n\");\r\n                utility::io::debug.out(\r\n                    \"%.2f\\t %.2f\\t %.2f\\t %.2f\\n\", A_mat(0, 0), A_mat(0, 1), A_mat(0, 2), A_mat(0, 3));\r\n                utility::io::debug.out(\r\n                    \"%.2f\\t %.2f\\t %.2f\\t %.2f\\n\", A_mat(1, 0), A_mat(1, 1), A_mat(1, 2), A_mat(1, 3));\r\n                utility::io::debug.out(\r\n                    \"%.2f\\t %.2f\\t %.2f\\t %.2f\\n\", A_mat(2, 0), A_mat(2, 1), A_mat(2, 2), A_mat(2, 3));\r\n                utility::io::debug.out(\r\n                    \"%.2f\\t %.2f\\t %.2f\\t %.2f\\n\", A_mat(3, 0), A_mat(3, 1), A_mat(3, 2), A_mat(3, 3));\r\n\r\n                float Sampling_time2 = 0.05;  // 0.01 T_s\r\n\r\n                Eigen::Matrix<float, 4, 1> x_state(input_states[0], input_states[1], input_states[2], input_states[3]);\r\n\r\n                Eigen::Matrix<float, 4, 1> x_states_update =\r\n                    (Eigen::Matrix<float, 4, 4>::Identity() + Sampling_time2 * A_mat) * x_state;\r\n\r\n                output_states.push_back(\r\n                    utility::math::sat(x_states_update(0, 0), std::make_pair(M_PI / 2.0, -M_PI / 2.0)));\r\n                output_states.push_back(utility::math::sat(x_states_update(1, 0), std::make_pair(10, -10)));\r\n                output_states.push_back(utility::math::sat(x_states_update(2, 0), std::make_pair(413685, 0)));\r\n                output_states.push_back(utility::math::sat(x_states_update(3, 0), std::make_pair(413685, 0)));\r\n\r\n                return (ControlError(setpoint, output_states));\r\n            }\r\n\r\n            float ControlError(std::vector<float>& setpoint, std::vector<float>& output_states) {\r\n\r\n                // Do the math to find the relative errors (state, input)\r\n\r\n                std::vector<float> state_error = {setpoint[0] - output_states[0],\r\n                                                  setpoint[1] - output_states[1],\r\n                                                  setpoint[2] - output_states[2],\r\n                                                  setpoint[3] - output_states[3]};\r\n\r\n                std::vector<float>::const_iterator i = output_states.begin();\r\n                std::vector<float>::const_iterator j = setpoint.begin();\r\n                std::vector<float>::const_iterator k = state_error.begin();\r\n                utility::io::debug.out(\"%f\\t - %f\\t = %f\\n\", *j, *i, *k);\r\n                i++;\r\n                j++;\r\n                k++;\r\n                utility::io::debug.out(\"%f\\t - %f\\t = %f\\n\", *j, *i, *k);\r\n                i++;\r\n                j++;\r\n                k++;\r\n                utility::io::debug.out(\"%f\\t - %f\\t = %f\\n\", *j, *i, *k);\r\n                i++;\r\n                j++;\r\n                k++;\r\n                utility::io::debug.out(\"%f\\t - %f\\t = %f\\n\", *j, *i, *k);\r\n                // TODO Fix\r\n                Eigen::Matrix<float, 4, 1> x_error(state_error[0], state_error[1], state_error[2], state_error[3]);\r\n                return (x_error.transpose() * state_weight * x_error);\r\n            }\r\n\r\n            template <typename T>\r\n            float dotV_a(float P_1, float P_2, const T& m) {\r\n                float b       = m.critical_ratio;\r\n                float C       = m.sonic_conductance;\r\n                float A       = C * std::sqrt(m.T_0 / m.T_1);\r\n                float P_b     = P_2 / P_1 - b;\r\n                float b_1     = 1 - b;\r\n                float P_bsqrt = std::sqrt(1 - (P_b / b_1) * (P_b / b_1));\r\n\r\n                if (P_2 / P_1 > b) {\r\n                    return std::isinf(P_1 * A * P_bsqrt) ? 0 : P_1 * A * P_bsqrt;\r\n                }\r\n                return std::isinf(P_1 * A) ? 0 : P_1 * A;\r\n            }\r\n\r\n            template <typename T>\r\n            float dotV_a_P_m1(float P_1, float P_2, const T& m, int mode) {\r\n                float b       = m.critical_ratio;\r\n                float C       = m.sonic_conductance;\r\n                float A       = C * std::sqrt(m.T_0 / m.T_1);\r\n                float P_b     = P_2 / P_1 - b;\r\n                float i       = A * P_b;\r\n                float b_1     = 1 - b;\r\n                float P_bsqrt = std::sqrt(1 - (P_b / b_1) * (P_b / b_1));\r\n\r\n                if (mode == 2 || mode == 3) {\r\n                    // P_2 == P_m1\r\n                    if (P_2 / P_1 > b) {\r\n                        return std::isinf(-(i / (b_1 * b_1 * P_bsqrt))) ? 0 : -(i / (b_1 * b_1 * P_bsqrt));\r\n                    }\r\n                    return 0;\r\n                }\r\n                else {\r\n                    // P_1 == P_m1\r\n                    if (P_2 / P_1 > b) {\r\n                        return std::isinf(A * P_bsqrt + (i * P_2 / (b_1 * b_1 * P_1 * P_bsqrt)))\r\n                                   ? 0\r\n                                   : A * P_bsqrt + (i * P_2 / (b_1 * b_1 * P_1 * P_bsqrt));\r\n                    }\r\n\r\n                    return std::isinf(C * std::sqrt(m.T_0 / m.T_1)) ? 0 : C * std::sqrt(m.T_0 / m.T_1);\r\n                }\r\n                return 0;\r\n            }\r\n\r\n            template <typename T>\r\n            float dotV_a_P_m2(float P_1, float P_2, const T& m, int mode) {\r\n                float b       = m.critical_ratio;\r\n                float C       = m.sonic_conductance;\r\n                float A       = C * std::sqrt(m.T_0 / m.T_1);\r\n                float P_b     = P_2 / P_1 - b;\r\n                float i       = A * P_b;\r\n                float b_1     = 1 - b;\r\n                float P_bsqrt = std::sqrt(1 - (P_b / b_1) * (P_b / b_1));\r\n\r\n                if (mode == 1 || mode == 3) {\r\n                    // P_2 == P_m2\r\n                    if (P_2 / P_1 > b) {\r\n                        // utility::io::debug.out(\"dotV_a_P_m2 mode 13 >\\n\");\r\n                        return std::isinf(-i / (b_1 * b_1 * P_bsqrt)) ? 0 : -i / (b_1 * b_1 * P_bsqrt);\r\n                    }\r\n                    // utility::io::debug.out(\"dotV_a_P_m2 mode 13 <\\n\");\r\n                    return 0;\r\n                }\r\n                else {\r\n                    // P_1 == P_m2\r\n                    if (P_2 / P_1 > b) {\r\n                        // utility::io::debug.out(\"dotV_a_P_m2 mode 2 >\\n\");\r\n                        return std::isinf(A * P_bsqrt + ((P_2 * i) / (b_1 * b_1 * P_1 * P_bsqrt)))\r\n                                   ? 0\r\n                                   : A * P_bsqrt + ((P_2 * i) / (b_1 * b_1 * P_1 * P_bsqrt));\r\n                    }\r\n\r\n                    // utility::io::debug.out(\"dotV_a_P_m2 mode 2 <\\n\");\r\n                    return std::isinf(C * std::sqrt(m.T_0 / m.T_1)) ? 0 : C * std::sqrt(m.T_0 / m.T_1);\r\n                }\r\n                return 0;\r\n            }\r\n\r\n            template <typename T>\r\n            void Linearise(const T& m,\r\n                           std::vector<float>& states,\r\n                           float dotV_a1,\r\n                           float dotV_a2,\r\n                           float ddotV_a1,\r\n                           float ddotV_a2,\r\n                           Eigen::Matrix<float, 4, 4>& A_mat) {\r\n\r\n                float L_10 = m.muscle1.L_0;\r\n                float L_20 = m.muscle2.L_0;\r\n                float k_10 = m.muscle1.K_0;\r\n                float k_20 = m.muscle2.K_0;\r\n                float y    = states[0];\r\n                float dy   = states[1];\r\n                float P_m1 = states[2];\r\n                float P_m2 = states[3];\r\n                float P_a  = m.P_a;\r\n                float a1   = m.muscle1.muscle_coefficients[0];\r\n                float b1   = m.muscle1.muscle_coefficients[1];\r\n                float c1   = m.muscle1.muscle_coefficients[2];\r\n                float d1   = m.muscle1.muscle_coefficients[3];\r\n                float a2   = m.muscle2.muscle_coefficients[0];\r\n                float b2   = m.muscle2.muscle_coefficients[1];\r\n                float c2   = m.muscle2.muscle_coefficients[2];\r\n                float d2   = m.muscle2.muscle_coefficients[3];\r\n                auto F_ce1 = m.muscle1.F_ce;\r\n                auto F_ce2 = m.muscle2.F_ce;\r\n                float R1   = m.muscle1.damping_coefficient;\r\n                float R2   = m.muscle2.damping_coefficient;\r\n                float mass = m.mass;\r\n\r\n                Eigen::Matrix<float, 6, 1> P_ce1;\r\n                Eigen::Matrix<float, 6, 1> P_ce2;\r\n                Eigen::Matrix<float, 6, 1> dP_ce1;\r\n                Eigen::Matrix<float, 6, 1> dP_ce2;\r\n\r\n                Eigen::Matrix<float, 1, 6> k_ce1;\r\n                Eigen::Matrix<float, 1, 6> k_ce2;\r\n                Eigen::Matrix<float, 1, 6> dk_ce1;\r\n                Eigen::Matrix<float, 1, 6> dk_ce2;\r\n\r\n                float F_s1;\r\n                float F_s2;\r\n                float F_d1;\r\n                float F_d2;\r\n                float V_m1;\r\n                float V_m2;\r\n                float dV_m1;\r\n                float dV_m2;\r\n                float dotV_m1;\r\n                float dotV_m2;\r\n                float ddotV_m1;\r\n                float ddotV_m2;\r\n                float ddotV_m1_dV_m1;\r\n                float ddotV_m2_dV_m2;\r\n\r\n                /* clang-format off */\r\n\r\n                float k1    = k_10 + y / L_10;\r\n                float k2    = k_20 - y / L_20;\r\n                float dotk1 = k_10 + dy / L_10;\r\n                float dotk2 = k_20 - dy / L_20;\r\n\r\n                P_ce1 << 1, \r\n                         P_m1, \r\n                         (P_m1 * P_m1), \r\n                         (P_m1 * P_m1 * P_m1), \r\n                         (P_m1 * P_m1 * P_m1 * P_m1), \r\n                         (P_m1 * P_m1 * P_m1 * P_m1 * P_m1);\r\n                P_ce2 << 1, \r\n                         P_m2, \r\n                         (P_m2 * P_m2), \r\n                         (P_m2 * P_m2 * P_m2), \r\n                         (P_m2 * P_m2 * P_m2 * P_m2), \r\n                         (P_m2 * P_m2 * P_m2 * P_m2 * P_m2);\r\n                dP_ce1 << 0, \r\n                          1, \r\n                          (2 * P_m1), \r\n                          (3 * P_m1 * P_m1), \r\n                          (4 * P_m1 * P_m1 * P_m1), \r\n                          (5 * P_m1 * P_m1 * P_m1 * P_m1);\r\n                dP_ce2 << 0, \r\n                          1, \r\n                          (2 * P_m2), \r\n                          (3 * P_m2 * P_m2), \r\n                          (4 * P_m2 * P_m2 * P_m2),\r\n                          (5 * P_m2 * P_m2 * P_m2 * P_m2);\r\n\r\n\r\n                k_ce1 << 1, \r\n                         k1, \r\n                         (k1 * k1), \r\n                         (k1 * k1 * k1), \r\n                         (k1 * k1 * k1 * k1), \r\n                         (k1 * k1 * k1 * k1 * k1);\r\n                k_ce2 << 1, \r\n                         k2, \r\n                         (k2 * k2), \r\n                         (k2 * k2 * k2), \r\n                         (k2 * k2 * k2 * k2), \r\n                         (k2 * k2 * k2 * k2 * k2);\r\n                dk_ce1 << 0, \r\n                          (1 / L_10), \r\n                          (2 * k1 / L_10), \r\n                          (3 * k1 * k1 / L_10), \r\n                          (4 * k1 * k1 * k1 / L_10),\r\n                          (5 * k1 * k1 * k1 * k1 / L_10);\r\n                dk_ce2 << 0, \r\n                          (-1 / L_20),\r\n                          (-2 * k2 / L_20), \r\n                          (-3 * k2 * k2 / L_20),\r\n                          (-4 * k2 * k2 * k2 / L_20),\r\n                          (-5 * k2 * k2 * k2 * k2 / L_20);\r\n\r\n                /******************************************************************************************************/\r\n                /********************************************** Column 1 **********************************************/\r\n                /******************************************************************************************************/\r\n\r\n                /********************************************* Lin_mat_0_0 ********************************************/\r\n                float Lin_mat_0_0 = 0;\r\n                /********************************************* Lin_mat_1_0 ********************************************/\r\n\r\n                // Calculate our first spring force\r\n                F_s1 = dk_ce1 * F_ce1 * P_ce1;\r\n\r\n                // Calculate our second spring force\r\n                F_s2 = dk_ce2 * F_ce2 * P_ce2;\r\n\r\n                float Lin_mat_1_0 = (-F_s2 - F_s1) / mass;\r\n\r\n                /********************************************* Lin_mat_2_0 ********************************************/\r\n                dV_m1          = (3 * a1 * k1 * k1 + 2 * b1 * k1 + c1) / L_10;\r\n                ddotV_m1_dV_m1 =\r\n                    ((a1 * k1 * k1 * k1 + b1 * k1 * k1 + c1 * k1 + d1) \r\n                        * (6 * a1 * k1 * dotk1 + 2 * b1 * dotk1)\r\n                    - (3 * a1 * k1 * k1 * dotk1 + 2 * b1 * k1 * dotk1 + c1 * dotk1) \r\n                        * (3 * a1 * k1 * k1 * dotk1 + 2 * b1 * k1 * dotk1 + c1 * dotk1))\r\n                    / (L_10 * (a1 * k1 * k1 * k1 + b1 * k1 * k1 + c1 * k1 + d1)\r\n                       * (a1 * k1 * k1 * k1 + b1 * k1 * k1 + c1 * k1 + d1));\r\n\r\n                float Lin_mat_2_0 = (P_a * dotV_a1 / dV_m1) - (P_m1 * ddotV_m1_dV_m1);\r\n                /********************************************* Lin_mat_3_0 ********************************************/\r\n                dV_m2          = (3 * a2 * k2 * k2 + 2 * b2 * k2 + c2) / L_20;\r\n                ddotV_m2_dV_m2 =\r\n                    ((a2 * k2 * k2 * k2 + b2 * k2 * k2 + c2 * k2 + d2) \r\n                        * (6 * a2 * k2 * dotk2 + 2 * b2 * dotk2)\r\n                    - (3 * a2 * k2 * k2 * dotk2 + 2 * b2 * k2 * dotk2 + c2 * dotk2) \r\n                        * (3 * a2 * k2 * k2 * dotk2 + 2 * b2 * k2 * dotk2 + c2 * dotk2))\r\n                    / (L_20 * (a2 * k2 * k2 * k2 + b2 * k2 * k2 + c2 * k2 + d2)\r\n                       * (a2 * k2 * k2 * k2 + b2 * k2 * k2 + c2 * k2 + d2));\r\n\r\n                float Lin_mat_3_0 = (P_a * dotV_a2 / dV_m2) - (P_m2 * ddotV_m2_dV_m2);\r\n                /******************************************************************************************************/\r\n                /********************************************** Column 2 **********************************************/\r\n                /******************************************************************************************************/\r\n\r\n                /********************************************* Lin_mat_0_1 ********************************************/\r\n                float Lin_mat_0_1 = 1;\r\n                /********************************************* Lin_mat_1_1 ********************************************/\r\n                F_d1 = -R1 * P_m1 / L_10;\r\n                F_d2 = -R2 * P_m2 / L_20;\r\n\r\n                float Lin_mat_1_1 = (-F_d2 - F_d1) / mass;\r\n                /********************************************* Lin_mat_2_1 ********************************************/\r\n                V_m1     = (a1 * k1 * k1 * k1) + (b1 * k1 * k1) + (c1 * k1) + d1;\r\n                ddotV_m1 = (3 * a1 * k1 * k1 + 2 * b1 * k1 + c1) / L_10;\r\n\r\n                float Lin_mat_2_1 = -P_m1 * ddotV_m1 / V_m1;\r\n                /********************************************* Lin_mat_3_1 ********************************************/\r\n                V_m2     = (a2 * k2 * k2 * k2) + (b2 * k2 * k2) + (c2 * k2) + d2;\r\n                ddotV_m2 = (3 * a2 * k2 * k2 + 2 * b2 * k2 + c2) / L_20;\r\n\r\n                float Lin_mat_3_1 = -P_m2 * ddotV_m2 / V_m2;\r\n                /******************************************************************************************************/\r\n                /********************************************** Column 3 **********************************************/\r\n                /******************************************************************************************************/\r\n\r\n                /********************************************* Lin_mat_0_2 ********************************************/\r\n                float Lin_mat_0_2 = 0;\r\n                /********************************************* Lin_mat_1_2 ********************************************/\r\n                F_s1 = k_ce1 * F_ce1 * dP_ce1;\r\n                F_d1 = -R1 * dotk1;\r\n\r\n                utility::io::debug.out(\"F_s1 = %f\\nk_ce1 = %f\\n F_ce1 = %f\\n dP_ce1 = %f\\n\\n\", F_s1, k_ce1, F_ce1, dP_ce1);\r\n                utility::io::debug.out(\"F_d1 = %f\\n -R1 = %f\\n dotk1 = %f\\n\", F_d1, -R1, dotk1);\r\n                \r\n                // TODO This is incorrect, but i don't know any better\r\n                float Lin_mat_1_2 = (F_s1 + F_d1) / mass;\r\n                /********************************************* Lin_mat_2_2 ********************************************/\r\n                dotV_m1 = (3 * a1 * k1 * k1 * dotk1 + 2 * b1 * k1 * dotk1 + c1 * dotk1) ;\r\n                V_m1    = (a1 * k1 * k1 * k1) + (b1 * k1 * k1) + (c1 * k1) + d1;\r\n\r\n                float Lin_mat_2_2 = (P_a * ddotV_a1 - dotV_m1) / V_m1 + 0.34;\r\n\r\n                /********************************************* Lin_mat_3_2 ********************************************/\r\n                float Lin_mat_3_2 = 0;\r\n                /******************************************************************************************************/\r\n                /********************************************** Column 4 **********************************************/\r\n                /******************************************************************************************************/\r\n\r\n                /********************************************* Lin_mat_0_3 ********************************************/\r\n                float Lin_mat_0_3 = 0;\r\n                /********************************************* Lin_mat_1_3 ********************************************/\r\n                F_s2 = k_ce2 * F_ce2 * dP_ce2;\r\n                F_d2 = -R2 * dotk2;\r\n\r\n                utility::io::debug.out(\"F_s2 = %f\\nk_ce2 = %f\\n F_ce2 = %f\\n dP_ce2 = %f\\n\\n\", F_s2, k_ce2, F_ce2, dP_ce2);\r\n                utility::io::debug.out(\"F_d2 = %f\\n -R2 = %f\\n dotk2 = %f\\n\", F_d2, -R2, dotk2);\r\n                \r\n                float Lin_mat_1_3 = (-F_s2 - F_d2) / mass;\r\n                /********************************************* Lin_mat_2_3 ********************************************/\r\n                float Lin_mat_2_3 = 0;\r\n                /********************************************* Lin_mat_3_3 ********************************************/\r\n                dotV_m2 = (3 * a2 * k2 * k2 * dotk2 + 2 * b2 * k2 * dotk2 + c2 * dotk2) ;\r\n                V_m2    = (a2 * k2 * k2 * k2) + (b2 * k2 * k2) + (c2 * k2) + d2;\r\n                \r\n                float Lin_mat_3_3 = (P_a * ddotV_a2 - dotV_m2) / V_m2 + 0.34;\r\n\r\n                A_mat << Lin_mat_0_0, Lin_mat_0_1, Lin_mat_0_2, Lin_mat_0_3, \r\n                         Lin_mat_1_0, Lin_mat_1_1, Lin_mat_1_2, Lin_mat_1_3, \r\n                         Lin_mat_2_0, Lin_mat_2_1, Lin_mat_2_2, Lin_mat_2_3, \r\n                         Lin_mat_3_0, Lin_mat_3_1, Lin_mat_3_2, Lin_mat_3_3;\r\n                /* clang-format on */\r\n            }\r\n\r\n            template <typename T>\r\n            std::pair<bool, bool> FirstLayer(const T& m, std::vector<float>& states, std::vector<float>& setpoint) {\r\n                // Increment the depth (control horizon itt)\r\n                // for (std::vector<float>::const_iterator i = states.begin(); i != states.end(); ++i) {\r\n                //     utility::io::debug.out(\"%f \", *i);\r\n                // }\r\n                // utility::io::debug.out(\"\\n\");\r\n\r\n                ch_itt = 1;\r\n\r\n                // Remove our previous results\r\n                cost_result.clear();\r\n\r\n                // Create a cost for each root\r\n                float cost_root_1;\r\n                float cost_root_2;\r\n                float cost_root_3;\r\n\r\n                // Create a output state vector for each process\r\n                std::vector<float> output_states_1;\r\n                std::vector<float> output_states_2;\r\n                std::vector<float> output_states_3;\r\n\r\n                // Calculate the result of performing each action and add the result error to the cost vector\r\n                cost_root_1 = ProcessModel(m, 1, states, setpoint, states, output_states_1);\r\n                cost_root_2 = ProcessModel(m, 2, states, setpoint, states, output_states_2);\r\n                cost_root_3 = ProcessModel(m, 3, states, setpoint, states, output_states_3);\r\n                // utility::io::debug.out(\"output_states_1\\n\");\r\n                // for (std::vector<float>::const_iterator i = output_states_1.begin(); i != output_states_1.end(); ++i)\r\n                // {\r\n                //     utility::io::debug.out(\"%f \", *i);\r\n                // }\r\n                // utility::io::debug.out(\"\\n\");\r\n                // utility::io::debug.out(\"output_states_2\\n\");\r\n                // for (std::vector<float>::const_iterator i = output_states_2.begin(); i != output_states_2.end(); ++i)\r\n                // {\r\n                //     utility::io::debug.out(\"%f \", *i);\r\n                // }\r\n                // utility::io::debug.out(\"\\n\");\r\n                // utility::io::debug.out(\"output_states_3\\n\");\r\n                // for (std::vector<float>::const_iterator i = output_states_3.begin(); i != output_states_3.end(); ++i)\r\n                // {\r\n                //     utility::io::debug.out(\"%f \", *i);\r\n                // }\r\n                // utility::io::debug.out(\"\\n\");\r\n\r\n                // Decide if the next layer is the last or not\r\n                if (ch_itt >= ch_max - 1) {\r\n                    // Must be on our last layer\r\n                    FinalLayer(m, states, setpoint, output_states_1, 1, cost_root_1);\r\n                    FinalLayer(m, states, setpoint, output_states_2, 2, cost_root_2);\r\n                    FinalLayer(m, states, setpoint, output_states_3, 3, cost_root_3);\r\n                }\r\n                else {\r\n                    // Not our last layer lets add a general layer\r\n                    AddLayer(m, states, setpoint, output_states_1, 1, cost_root_1);\r\n                    AddLayer(m, states, setpoint, output_states_2, 2, cost_root_2);\r\n                    AddLayer(m, states, setpoint, output_states_3, 3, cost_root_3);\r\n                }\r\n\r\n\r\n                // Now look through the cost_result vector and pick the lowest cost to perform the root action\r\n                auto result = *std::min_element(cost_result.cbegin(),\r\n                                                cost_result.cend(),\r\n                                                [](const auto& lhs, const auto& rhs) { return lhs.first < rhs.first; });\r\n                utility::io::debug.out(\"Cost results\\n\");\r\n                for (const auto& p : cost_result) {\r\n                    utility::io::debug.out(\"Mode %d, cost %f\\n\", p.second, p.first);\r\n                }\r\n                utility::io::debug.out(\"\\n\");\r\n\r\n                if (result.second == 1) {\r\n                    utility::io::debug.out(\"Optimizer result mode1, %f\\n\", result.first);\r\n                    return (std::make_pair(true, false));\r\n                }\r\n                else if (result.second == 2) {\r\n                    utility::io::debug.out(\"Optimizer result mode2, %f\\n\", result.first);\r\n                    return (std::make_pair(false, true));\r\n                }\r\n                else if (result.second == 3) {\r\n                    utility::io::debug.out(\"Optimizer result mode3, %f\\n\", result.first);\r\n                    return (std::make_pair(false, false));\r\n                }\r\n                utility::io::debug.out(\"Optimizer failed\\n\");\r\n                return (std::make_pair(false, false));\r\n            }\r\n\r\n            template <typename T>\r\n            void AddLayer(const T& m,\r\n                          std::vector<float>& states,\r\n                          std::vector<float>& setpoint,\r\n                          std::vector<float>& input_states,\r\n                          int root,\r\n                          float cost) {\r\n                // We're somewhere in the middle of our recursion\r\n                ch_itt += 1;\r\n\r\n                // Create a output state vector for each process\r\n                std::vector<float> output_states_1;\r\n                std::vector<float> output_states_2;\r\n                std::vector<float> output_states_3;\r\n\r\n                // Calculate the result of performing each action and add the result error to the cost vector\r\n                float cost1 = cost + ProcessModel(m, 1, states, setpoint, input_states, output_states_1);\r\n                float cost2 = cost + ProcessModel(m, 2, states, setpoint, input_states, output_states_2);\r\n                float cost3 = cost + ProcessModel(m, 3, states, setpoint, input_states, output_states_3);\r\n\r\n                // Decide if the next layer is the last or not\r\n                if (ch_itt >= ch_max - 1) {\r\n                    // Must be on our last layer\r\n                    FinalLayer(m, states, setpoint, output_states_1, root, cost1);\r\n                    FinalLayer(m, states, setpoint, output_states_2, root, cost2);\r\n                    FinalLayer(m, states, setpoint, output_states_3, root, cost3);\r\n                }\r\n                else {\r\n                    // Not our last layer lets add a general layer\r\n                    AddLayer(m, states, setpoint, output_states_1, root, cost1);\r\n                    AddLayer(m, states, setpoint, output_states_2, root, cost2);\r\n                    AddLayer(m, states, setpoint, output_states_3, root, cost3);\r\n                }\r\n\r\n                // As we're leaving a level, decrement the itterator\r\n                ch_itt -= 1;\r\n            }\r\n\r\n            template <typename T>\r\n            void FinalLayer(const T& m,\r\n                            std::vector<float>& states,\r\n                            std::vector<float>& setpoint,\r\n                            std::vector<float>& input_states,\r\n                            const int& root,\r\n                            float cost) {\r\n                // We're on or last layer, let's calculate the result append the cost and root\r\n\r\n                // utility::io::debug.out(\"input_states\\n\");\r\n                // for (std::vector<float>::const_iterator i = input_states.begin(); i != input_states.end(); ++i) {\r\n                //     utility::io::debug.out(\"%f \", *i);\r\n                // }\r\n                // utility::io::debug.out(\"\\n\");\r\n\r\n                // TODO This isn't needed on the last layer\r\n                // Create a output state vector for each process\r\n                std::vector<float> output_states_1;\r\n                std::vector<float> output_states_2;\r\n                std::vector<float> output_states_3;\r\n\r\n                // Calculate the result of performing each action and add the result error to the cost vector\r\n                float cost1 = cost + ProcessModel(m, 1, states, setpoint, input_states, output_states_1);\r\n                float cost2 = cost + ProcessModel(m, 2, states, setpoint, input_states, output_states_2);\r\n                float cost3 = cost + ProcessModel(m, 3, states, setpoint, input_states, output_states_3);\r\n\r\n                // utility::io::debug.out(\"Final Mode %d, Cost1 %f\\n\", root, cost1 - cost);\r\n                // utility::io::debug.out(\"Final Mode %d, Cost2 %f\\n\", root, cost2 - cost);\r\n                // utility::io::debug.out(\"Final Mode %d, Cost3 %f\\n\", root, cost3 - cost);\r\n\r\n                // Tally the cost and append it to the cost function list for each final cost\r\n                cost_result.push_back(std::pair<float, int>(cost1, root));\r\n                cost_result.push_back(std::pair<float, int>(cost2, root));\r\n                cost_result.push_back(std::pair<float, int>(cost3, root));\r\n            }\r\n\r\n        private:\r\n            int ch_itt;\r\n            const int ch_max;\r\n            std::vector<std::pair<float, int>> cost_result;\r\n            Eigen::Matrix<float, 4, 4> state_weight;\r\n        };\r\n\r\n        extern Optimizer optimizer1;\r\n    }  // namespace AdaptiveMPC\r\n}  // namespace MPC\r\n}  // namespace module\r\n\r\n#endif  // MODULE_OPTIMIZER_HPP", "meta": {"hexsha": "cefc2e6fc1e09bcf971e0780980bab64f058cee7", "size": 30983, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/module/MPC/AdaptiveMPC/Optimizer.hpp", "max_stars_repo_name": "tayloryoung6396/FYP", "max_stars_repo_head_hexsha": "3ad6589fa67f89d5522510aeea7cfa433530d398", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/module/MPC/AdaptiveMPC/Optimizer.hpp", "max_issues_repo_name": "tayloryoung6396/FYP", "max_issues_repo_head_hexsha": "3ad6589fa67f89d5522510aeea7cfa433530d398", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module/MPC/AdaptiveMPC/Optimizer.hpp", "max_forks_repo_name": "tayloryoung6396/FYP", "max_forks_repo_head_hexsha": "3ad6589fa67f89d5522510aeea7cfa433530d398", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.9588815789, "max_line_length": 124, "alphanum_fraction": 0.3807894652, "num_tokens": 7659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5407525077018461}}
{"text": "\n// BLAS level 2\n\n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <iostream>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include \"utils.h\" \n\nnamespace ublas = boost::numeric::ublas;\nnamespace blas = boost::numeric::bindings::blas;\n\nusing std::cout;\nusing std::endl; \n\ntypedef ublas::vector<double> vct_t;\ntypedef ublas::matrix<double, ublas::row_major> rm_t;\ntypedef ublas::matrix<double, ublas::column_major> cm_t;\n\nint main() {\n\n  cout << endl; \n\n  vct_t vx (2);\n  vct_t vy (4); \n\n  // row major matrix\n  rm_t rm (4, 2);\n  init_m (rm, kpp (1)); \n  print_m (rm, \"row major matrix m\"); \n  cout << endl; \n\n  blas::set (1., vx);\n  print_v (vx, \"vx\"); \n  cout << endl; \n\n  // vy = m vx\n  blas::gemv ( 1.0, rm, vx, 0.0, vy);\n  print_v (vy, \"vy = m vx\"); \n  cout << endl; \n\n  blas::set (1., vy); \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // vx = m^T vy\n  blas::gemv ( 1.0, bindings::trans(rm), vy, 0.0, vx);\n  print_v (vx, \"vx = m^T vy\"); \n  cout << endl; \n\n  cout << endl; \n\n  // column major matrix\n  cm_t cm (4, 2);\n  init_m (cm, kpp (1)); \n  print_m (cm, \"column major matrix m\"); \n  cout << endl; \n\n  blas::set (1., vx);\n  print_v (vx, \"vx\"); \n  cout << endl; \n\n  // vy = m vx\n  blas::gemv (1.0, cm, vx, 0.0, vy);\n  print_v (vy, \"vy = m vx\"); \n  cout << endl; \n\n  blas::set (1., vy); \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // vx = m^T vy\n  blas::gemv ( 1.0, bindings::trans(cm), vy, 0.0, vx);\n  print_v (vx, \"vx = m^T vy\"); \n  cout << endl; \n\n}\n", "meta": {"hexsha": "f5a5bb5f95621ce00a532f4a9fb96de850a81558", "size": 1663, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_matr2.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/atlas/ublas_matr2.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/atlas/ublas_matr2.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": 20.2804878049, "max_line_length": 56, "alphanum_fraction": 0.5935057126, "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5406486114733914}}
{"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   testPose2.cpp\n * @brief  Unit tests for Pose2 class\n */\n\n#include <cmath>\n#include <iostream>\n\n#include <boost/foreach.hpp>\n#include <boost/optional.hpp>\n#include <boost/assign/std/vector.hpp> // for operator +=\nusing namespace boost::assign;\n\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/base/Testable.h>\n#include <gtsam/base/numericalDerivative.h>\n#include <gtsam/base/lieProxies.h>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/geometry/Point2.h>\n#include <gtsam/geometry/Rot2.h>\n\nusing namespace gtsam;\nusing namespace std;\n\n// #define SLOW_BUT_CORRECT_EXPMAP\n\nGTSAM_CONCEPT_TESTABLE_INST(Pose2)\nGTSAM_CONCEPT_LIE_INST(Pose2)\n\n/* ************************************************************************* */\nTEST(Pose2, constructors) {\n  Point2 p;\n  Pose2 pose(0,p);\n  Pose2 origin;\n  assert_equal(pose,origin);\n\tPose2 t(M_PI/2.0+0.018, Point2(1.015, 2.01));\n\tEXPECT(assert_equal(t,Pose2(t.matrix())));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, manifold) {\n\tPose2 t1(M_PI/2.0, Point2(1, 2));\n\tPose2 t2(M_PI/2.0+0.018, Point2(1.015, 2.01));\n\tPose2 origin;\n\tVector d12 = t1.localCoordinates(t2);\n\tEXPECT(assert_equal(t2, t1.retract(d12)));\n\tEXPECT(assert_equal(t2, t1*origin.retract(d12)));\n\tVector d21 = t2.localCoordinates(t1);\n\tEXPECT(assert_equal(t1, t2.retract(d21)));\n\tEXPECT(assert_equal(t1, t2*origin.retract(d21)));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, retract) {\n  Pose2 pose(M_PI/2.0, Point2(1, 2));\n#ifdef SLOW_BUT_CORRECT_EXPMAP\n  Pose2 expected(1.00811, 2.01528, 2.5608);\n#else\n  Pose2 expected(M_PI/2.0+0.99, Point2(1.015, 2.01));\n#endif\n  Pose2 actual = pose.retract(Vector_(3, 0.01, -0.015, 0.99));\n  EXPECT(assert_equal(expected, actual, 1e-5));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, expmap) {\n  Pose2 pose(M_PI/2.0, Point2(1, 2));\n  Pose2 expected(1.00811, 2.01528, 2.5608);\n  Pose2 actual = expmap_default<Pose2>(pose, Vector_(3, 0.01, -0.015, 0.99));\n  EXPECT(assert_equal(expected, actual, 1e-5));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, expmap2) {\n  Pose2 pose(M_PI/2.0, Point2(1, 2));\n  Pose2 expected(1.00811, 2.01528, 2.5608);\n  Pose2 actual = expmap_default<Pose2>(pose, Vector_(3, 0.01, -0.015, 0.99));\n  EXPECT(assert_equal(expected, actual, 1e-5));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, expmap3) {\n  // do an actual series exponential map\n\t// see e.g. http://www.cis.upenn.edu/~cis610/cis610lie1.ps\n  Matrix A = Matrix_(3,3,\n  \t\t0.0, -0.99,  0.01,\n  \t\t0.99,  0.0, -0.015,\n  \t\t0.0,   0.0,  0.0);\n  Matrix A2 = A*A/2.0, A3 = A2*A/3.0, A4=A3*A/4.0;\n  Matrix expected = eye(3) + A + A2 + A3 + A4;\n\n  Vector v = Vector_(3, 0.01, -0.015, 0.99);\n  Pose2 pose = Pose2::Expmap(v);\n  Pose2 pose2(v);\n  EXPECT(assert_equal(pose, pose2));\n  Matrix actual = pose.matrix();\n  //EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, expmap0) {\n  Pose2 pose(M_PI/2.0, Point2(1, 2));\n//#ifdef SLOW_BUT_CORRECT_EXPMAP\n  Pose2 expected(1.01491, 2.01013, 1.5888);\n//#else\n//  Pose2 expected(M_PI/2.0+0.018, Point2(1.015, 2.01));\n//#endif\n  Pose2 actual = pose * (Pose2::Expmap(Vector_(3, 0.01, -0.015, 0.018)));\n  EXPECT(assert_equal(expected, actual, 1e-5));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, expmap0_full) {\n  Pose2 pose(M_PI/2.0, Point2(1, 2));\n  Pose2 expected(1.01491, 2.01013, 1.5888);\n  Pose2 actual = pose * Pose2::Expmap(Vector_(3, 0.01, -0.015, 0.018));\n  EXPECT(assert_equal(expected, actual, 1e-5));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, expmap0_full2) {\n  Pose2 pose(M_PI/2.0, Point2(1, 2));\n  Pose2 expected(1.01491, 2.01013, 1.5888);\n  Pose2 actual = pose * Pose2::Expmap(Vector_(3, 0.01, -0.015, 0.018));\n  EXPECT(assert_equal(expected, actual, 1e-5));\n}\n\n#ifdef SLOW_BUT_CORRECT_EXPMAP\n/* ************************************************************************* */\n// test case for screw motion in the plane\nnamespace screw {\n  double w=0.3;\n\tVector xi = Vector_(3, 0.0, w, w);\n\tRot2 expectedR = Rot2::fromAngle(w);\n\tPoint2 expectedT(-0.0446635, 0.29552);\n\tPose2 expected(expectedR, expectedT);\n}\n\nTEST(Pose3, expmap_c)\n{\n  EXPECT(assert_equal(screw::expected, expm<Pose2>(screw::xi),1e-6));\n  EXPECT(assert_equal(screw::expected, Pose2::Expmap(screw::xi),1e-6));\n  EXPECT(assert_equal(screw::xi, Pose2::Logmap(screw::expected),1e-6));\n}\n#endif\n\n/* ************************************************************************* */\nTEST(Pose2, expmap_c_full)\n{\n  double w=0.3;\n\tVector xi = Vector_(3, 0.0, w, w);\n\tRot2 expectedR = Rot2::fromAngle(w);\n\tPoint2 expectedT(-0.0446635, 0.29552);\n\tPose2 expected(expectedR, expectedT);\n  EXPECT(assert_equal(expected, expm<Pose2>(xi),1e-6));\n  EXPECT(assert_equal(expected, Pose2::Expmap(xi),1e-6));\n  EXPECT(assert_equal(xi, Pose2::Logmap(expected),1e-6));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, logmap) {\n  Pose2 pose0(M_PI/2.0, Point2(1, 2));\n  Pose2 pose(M_PI/2.0+0.018, Point2(1.015, 2.01));\n#ifdef SLOW_BUT_CORRECT_EXPMAP\n  Vector expected = Vector_(3, 0.00986473, -0.0150896, 0.018);\n#else\n  Vector expected = Vector_(3, 0.01, -0.015, 0.018);\n#endif\n  Vector actual = pose0.localCoordinates(pose);\n  EXPECT(assert_equal(expected, actual, 1e-5));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, logmap_full) {\n  Pose2 pose0(M_PI/2.0, Point2(1, 2));\n  Pose2 pose(M_PI/2.0+0.018, Point2(1.015, 2.01));\n  Vector expected = Vector_(3, 0.00986473, -0.0150896, 0.018);\n  Vector actual = logmap_default<Pose2>(pose0, pose);\n  EXPECT(assert_equal(expected, actual, 1e-5));\n}\n\n/* ************************************************************************* */\nstatic Point2 transform_to_proxy(const Pose2& pose, const Point2& point) {\n\treturn pose.transform_to(point);\n}\n\nTEST( Pose2, transform_to )\n{\n  Pose2 pose(M_PI/2.0, Point2(1,2)); // robot at (1,2) looking towards y\n  Point2 point(-1,4);    // landmark at (-1,4)\n\n  // expected\n  Point2 expected(2,2);\n  Matrix expectedH1 = Matrix_(2,3, -1.0, 0.0, 2.0,  0.0, -1.0, -2.0);\n  Matrix expectedH2 = Matrix_(2,2, 0.0, 1.0,  -1.0, 0.0);\n\n  // actual\n  Matrix actualH1, actualH2;\n  Point2 actual = pose.transform_to(point, actualH1, actualH2);\n  EXPECT(assert_equal(expected,actual));\n\n  EXPECT(assert_equal(expectedH1,actualH1));\n  Matrix numericalH1 = numericalDerivative21(transform_to_proxy, pose, point);\n  EXPECT(assert_equal(numericalH1,actualH1));\n\n  EXPECT(assert_equal(expectedH2,actualH2));\n  Matrix numericalH2 = numericalDerivative22(transform_to_proxy, pose, point);\n  EXPECT(assert_equal(numericalH2,actualH2));\n}\n\n/* ************************************************************************* */\nstatic Point2 transform_from_proxy(const Pose2& pose, const Point2& point) {\n\treturn pose.transform_from(point);\n}\n\nTEST (Pose2, transform_from)\n{\n\tPose2 pose(1., 0., M_PI/2.0);\n\tPoint2 pt(2., 1.);\n\tMatrix H1, H2;\n\tPoint2 actual = pose.transform_from(pt, H1, H2);\n\n\tPoint2 expected(0., 2.);\n\tEXPECT(assert_equal(expected, actual));\n\n\tMatrix H1_expected = Matrix_(2, 3, 0., -1., -2., 1., 0., -1.);\n\tMatrix H2_expected = Matrix_(2, 2, 0., -1., 1., 0.);\n\n\tMatrix numericalH1 = numericalDerivative21(transform_from_proxy, pose, pt);\n\tEXPECT(assert_equal(H1_expected, H1));\n\tEXPECT(assert_equal(H1_expected, numericalH1));\n\n\tMatrix numericalH2 = numericalDerivative22(transform_from_proxy, pose, pt);\n\tEXPECT(assert_equal(H2_expected, H2));\n\tEXPECT(assert_equal(H2_expected, numericalH2));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, compose_a)\n{\n  Pose2 pose1(M_PI/4.0, Point2(sqrt(0.5), sqrt(0.5)));\n  Pose2 pose2(M_PI/2.0, Point2(0.0, 2.0));\n\n  Matrix actualDcompose1;\n  Matrix actualDcompose2;\n  Pose2 actual = pose1.compose(pose2, actualDcompose1, actualDcompose2);\n\n  Pose2 expected(3.0*M_PI/4.0, Point2(-sqrt(0.5), 3.0*sqrt(0.5)));\n  EXPECT(assert_equal(expected, actual));\n\n  Matrix expectedH1 = Matrix_(3,3,\n  \t\t0.0, 1.0, 0.0,\n  \t   -1.0, 0.0, 2.0,\n  \t\t0.0, 0.0, 1.0\n  );\n  Matrix expectedH2 = eye(3);\n  Matrix numericalH1 = numericalDerivative21<Pose2, Pose2, Pose2>(testing::compose, pose1, pose2);\n  Matrix numericalH2 = numericalDerivative22<Pose2, Pose2, Pose2>(testing::compose, pose1, pose2);\n  EXPECT(assert_equal(expectedH1,actualDcompose1));\n  EXPECT(assert_equal(numericalH1,actualDcompose1));\n  EXPECT(assert_equal(expectedH2,actualDcompose2));\n  EXPECT(assert_equal(numericalH2,actualDcompose2));\n\n  Point2 point(sqrt(0.5), 3.0*sqrt(0.5));\n  Point2 expected_point(-1.0, -1.0);\n  Point2 actual_point1 = (pose1 * pose2).transform_to(point);\n  Point2 actual_point2 = pose2.transform_to(pose1.transform_to(point));\n  EXPECT(assert_equal(expected_point, actual_point1));\n  EXPECT(assert_equal(expected_point, actual_point2));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, compose_b)\n{\n  Pose2 pose1(Rot2::fromAngle(M_PI/10.0), Point2(.75, .5));\n  Pose2 pose2(Rot2::fromAngle(M_PI/4.0-M_PI/10.0), Point2(0.701289620636, 1.34933052585));\n\n  Pose2 pose_expected(Rot2::fromAngle(M_PI/4.0), Point2(1.0, 2.0));\n\n  Pose2 pose_actual_op = pose1 * pose2;\n  Matrix actualDcompose1, actualDcompose2;\n  Pose2 pose_actual_fcn = pose1.compose(pose2, actualDcompose1, actualDcompose2);\n\n  Matrix numericalH1 = numericalDerivative21<Pose2, Pose2, Pose2>(testing::compose, pose1, pose2);\n  Matrix numericalH2 = numericalDerivative22<Pose2, Pose2, Pose2>(testing::compose, pose1, pose2);\n  EXPECT(assert_equal(numericalH1,actualDcompose1,1e-5));\n  EXPECT(assert_equal(numericalH2,actualDcompose2));\n\n  EXPECT(assert_equal(pose_expected, pose_actual_op));\n  EXPECT(assert_equal(pose_expected, pose_actual_fcn));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, compose_c)\n{\n  Pose2 pose1(Rot2::fromAngle(M_PI/4.0), Point2(1.0, 1.0));\n  Pose2 pose2(Rot2::fromAngle(M_PI/4.0), Point2(sqrt(.5), sqrt(.5)));\n\n  Pose2 pose_expected(Rot2::fromAngle(M_PI/2.0), Point2(1.0, 2.0));\n\n  Pose2 pose_actual_op = pose1 * pose2;\n  Matrix actualDcompose1, actualDcompose2;\n  Pose2 pose_actual_fcn = pose1.compose(pose2, actualDcompose1, actualDcompose2);\n\n  Matrix numericalH1 = numericalDerivative21<Pose2, Pose2, Pose2>(testing::compose, pose1, pose2);\n  Matrix numericalH2 = numericalDerivative22<Pose2, Pose2, Pose2>(testing::compose, pose1, pose2);\n  EXPECT(assert_equal(numericalH1,actualDcompose1,1e-5));\n  EXPECT(assert_equal(numericalH2,actualDcompose2));\n\n  EXPECT(assert_equal(pose_expected, pose_actual_op));\n  EXPECT(assert_equal(pose_expected, pose_actual_fcn));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, inverse )\n{\n\tPoint2 origin, t(1,2);\n\tPose2 gTl(M_PI/2.0, t); // robot at (1,2) looking towards y\n\n\tPose2 identity, lTg = gTl.inverse();\n\tEXPECT(assert_equal(identity,lTg.compose(gTl)));\n\tEXPECT(assert_equal(identity,gTl.compose(lTg)));\n\n\tPoint2 l(4,5), g(-4,6);\n\tEXPECT(assert_equal(g,gTl*l));\n\tEXPECT(assert_equal(l,lTg*g));\n\n\t// Check derivative\n  Matrix numericalH = numericalDerivative11<Pose2,Pose2>(testing::inverse, lTg);\n  Matrix actualDinverse;\n  lTg.inverse(actualDinverse);\n  EXPECT(assert_equal(numericalH,actualDinverse));\n}\n\n/* ************************************************************************* */\nVector homogeneous(const Point2& p) {\n\treturn Vector_(3, p.x(), p.y(), 1.0);\n}\n\n/* ************************************************************************* */\nMatrix matrix(const Pose2& gTl) {\n\tMatrix gRl = gTl.r().matrix();\n\tPoint2 gt = gTl.t();\n\treturn Matrix_(3, 3,\n\t\t\tgRl(0, 0), gRl(0, 1), gt.x(),\n\t\t\tgRl(1, 0), gRl(1, 1), gt.y(),\n\t\t\t      0.0,       0.0,   1.0);\n}\n\n/* ************************************************************************* */\nTEST( Pose2, matrix )\n{\n\tPoint2 origin, t(1,2);\n\tPose2 gTl(M_PI/2.0, t); // robot at (1,2) looking towards y\n  Matrix gMl = matrix(gTl);\n  EXPECT(assert_equal(Matrix_(3,3,\n  \t\t0.0, -1.0, 1.0,\n  \t\t1.0,  0.0, 2.0,\n  \t\t0.0,  0.0, 1.0),\n  \t\tgMl));\n  Rot2 gR1 = gTl.r();\n  EXPECT(assert_equal(homogeneous(t),gMl*homogeneous(origin)));\n  Point2 x_axis(1,0), y_axis(0,1);\n  EXPECT(assert_equal(Matrix_(2,2,\n  \t\t0.0, -1.0,\n  \t\t1.0,  0.0),\n  \t\tgR1.matrix()));\n  EXPECT(assert_equal(Point2(0,1),gR1*x_axis));\n  EXPECT(assert_equal(Point2(-1,0),gR1*y_axis));\n  EXPECT(assert_equal(homogeneous(Point2(1+0,2+1)),gMl*homogeneous(x_axis)));\n  EXPECT(assert_equal(homogeneous(Point2(1-1,2+0)),gMl*homogeneous(y_axis)));\n\n  // check inverse pose\n  Matrix lMg = matrix(gTl.inverse());\n  EXPECT(assert_equal(Matrix_(3,3,\n  \t\t0.0,  1.0,-2.0,\n  \t -1.0,  0.0, 1.0,\n  \t\t0.0,  0.0, 1.0),\n  \t\tlMg));\n}\n\n/* ************************************************************************* */\nTEST( Pose2, compose_matrix )\n{\n  Pose2 gT1(M_PI/2.0, Point2(1,2)); // robot at (1,2) looking towards y\n  Pose2 _1T2(M_PI, Point2(-1,4));  // local robot at (-1,4) loooking at negative x\n  Matrix gM1(matrix(gT1)),_1M2(matrix(_1T2));\n  EXPECT(assert_equal(gM1*_1M2,matrix(gT1.compose(_1T2)))); // RIGHT DOES NOT\n}\n\n/* ************************************************************************* */\nTEST( Pose2, between )\n{\n  // <\n  //\n\t//       ^\n\t//\n\t// *--0--*--*\n  Pose2 gT1(M_PI/2.0, Point2(1,2)); // robot at (1,2) looking towards y\n  Pose2 gT2(M_PI, Point2(-1,4));  // robot at (-1,4) loooking at negative x\n\n  Matrix actualH1,actualH2;\n  Pose2 expected(M_PI/2.0, Point2(2,2));\n  Pose2 actual1 = gT1.between(gT2);\n  Pose2 actual2 = gT1.between(gT2,actualH1,actualH2);\n  EXPECT(assert_equal(expected,actual1));\n  EXPECT(assert_equal(expected,actual2));\n\n  Matrix expectedH1 = Matrix_(3,3,\n      0.0,-1.0,-2.0,\n      1.0, 0.0,-2.0,\n      0.0, 0.0,-1.0\n  );\n  Matrix numericalH1 = numericalDerivative21<Pose2,Pose2,Pose2>(testing::between, gT1, gT2);\n  EXPECT(assert_equal(expectedH1,actualH1));\n  EXPECT(assert_equal(numericalH1,actualH1));\n\t// Assert H1 = -AdjointMap(between(p2,p1)) as in doc/math.lyx\n  EXPECT(assert_equal(-gT2.between(gT1).adjointMap(),actualH1));\n\n  Matrix expectedH2 = Matrix_(3,3,\n       1.0, 0.0, 0.0,\n       0.0, 1.0, 0.0,\n       0.0, 0.0, 1.0\n  );\n  Matrix numericalH2 = numericalDerivative22<Pose2,Pose2,Pose2>(testing::between, gT1, gT2);\n  EXPECT(assert_equal(expectedH2,actualH2));\n  EXPECT(assert_equal(numericalH2,actualH2));\n\n}\n\n/* ************************************************************************* */\n// reverse situation for extra test\nTEST( Pose2, between2 )\n{\n  Pose2 p2(M_PI/2.0, Point2(1,2)); // robot at (1,2) looking towards y\n  Pose2 p1(M_PI, Point2(-1,4));  // robot at (-1,4) loooking at negative x\n\n  Matrix actualH1,actualH2;\n  p1.between(p2,actualH1,actualH2);\n  Matrix numericalH1 = numericalDerivative21<Pose2,Pose2,Pose2>(testing::between, p1, p2);\n  EXPECT(assert_equal(numericalH1,actualH1));\n  Matrix numericalH2 = numericalDerivative22<Pose2,Pose2,Pose2>(testing::between, p1, p2);\n  EXPECT(assert_equal(numericalH2,actualH2));\n}\n\n/* ************************************************************************* */\nTEST( Pose2, round_trip )\n{\n\tPose2 p1(1.23, 2.30, 0.2);\n\tPose2 odo(0.53, 0.39, 0.15);\n\tPose2 p2 = p1.compose(odo);\n\tEXPECT(assert_equal(odo, p1.between(p2)));\n}\n\n/* ************************************************************************* */\nTEST(Pose2, members)\n{\n  Pose2 pose;\n  EXPECT(pose.dim() == 3);\n}\n\n/* ************************************************************************* */\n// some shared test values\nPose2 x1, x2(1, 1, 0), x3(1, 1, M_PI/4.0);\nPoint2 l1(1, 0), l2(1, 1), l3(2, 2), l4(1, 3);\n\n/* ************************************************************************* */\nRot2 bearing_proxy(const Pose2& pose, const Point2& pt) {\n\treturn pose.bearing(pt);\n}\n\nTEST( Pose2, bearing )\n{\n\tMatrix expectedH1, actualH1, expectedH2, actualH2;\n\n\t// establish bearing is indeed zero\n\tEXPECT(assert_equal(Rot2(),x1.bearing(l1)));\n\n\t// establish bearing is indeed 45 degrees\n\tEXPECT(assert_equal(Rot2::fromAngle(M_PI/4.0),x1.bearing(l2)));\n\n\t// establish bearing is indeed 45 degrees even if shifted\n\tRot2 actual23 = x2.bearing(l3, actualH1, actualH2);\n\tEXPECT(assert_equal(Rot2::fromAngle(M_PI/4.0),actual23));\n\n\t// Check numerical derivatives\n\texpectedH1 = numericalDerivative21(bearing_proxy, x2, l3);\n\tEXPECT(assert_equal(expectedH1,actualH1));\n\texpectedH2 = numericalDerivative22(bearing_proxy, x2, l3);\n\tEXPECT(assert_equal(expectedH1,actualH1));\n\n\t// establish bearing is indeed 45 degrees even if rotated\n\tRot2 actual34 = x3.bearing(l4, actualH1, actualH2);\n\tEXPECT(assert_equal(Rot2::fromAngle(M_PI/4.0),actual34));\n\n\t// Check numerical derivatives\n\texpectedH1 = numericalDerivative21(bearing_proxy, x3, l4);\n\texpectedH2 = numericalDerivative22(bearing_proxy, x3, l4);\n\tEXPECT(assert_equal(expectedH1,actualH1));\n\tEXPECT(assert_equal(expectedH1,actualH1));\n}\n\n/* ************************************************************************* */\nRot2 bearing_pose_proxy(const Pose2& pose, const Pose2& pt) {\n\treturn pose.bearing(pt);\n}\n\nTEST( Pose2, bearing_pose )\n{\n\tPose2 xl1(1, 0, M_PI/2.0), xl2(1, 1, M_PI), xl3(2.0, 2.0,-M_PI/2.0), xl4(1, 3, 0);\n\n\tMatrix expectedH1, actualH1, expectedH2, actualH2;\n\n\t// establish bearing is indeed zero\n\tEXPECT(assert_equal(Rot2(),x1.bearing(xl1)));\n\n\t// establish bearing is indeed 45 degrees\n\tEXPECT(assert_equal(Rot2::fromAngle(M_PI/4.0),x1.bearing(xl2)));\n\n\t// establish bearing is indeed 45 degrees even if shifted\n\tRot2 actual23 = x2.bearing(xl3, actualH1, actualH2);\n\tEXPECT(assert_equal(Rot2::fromAngle(M_PI/4.0),actual23));\n\n\t// Check numerical derivatives\n\texpectedH1 = numericalDerivative21(bearing_pose_proxy, x2, xl3);\n\texpectedH2 = numericalDerivative22(bearing_pose_proxy, x2, xl3);\n\tEXPECT(assert_equal(expectedH1,actualH1));\n\tEXPECT(assert_equal(expectedH2,actualH2));\n\n\t// establish bearing is indeed 45 degrees even if rotated\n\tRot2 actual34 = x3.bearing(xl4, actualH1, actualH2);\n\tEXPECT(assert_equal(Rot2::fromAngle(M_PI/4.0),actual34));\n\n\t// Check numerical derivatives\n\texpectedH1 = numericalDerivative21(bearing_pose_proxy, x3, xl4);\n\texpectedH2 = numericalDerivative22(bearing_pose_proxy, x3, xl4);\n\tEXPECT(assert_equal(expectedH1,actualH1));\n\tEXPECT(assert_equal(expectedH2,actualH2));\n}\n\n/* ************************************************************************* */\nLieVector range_proxy(const Pose2& pose, const Point2& point) {\n\treturn LieVector(pose.range(point));\n}\nTEST( Pose2, range )\n{\n\tMatrix expectedH1, actualH1, expectedH2, actualH2;\n\n\t// establish range is indeed zero\n\tEXPECT_DOUBLES_EQUAL(1,x1.range(l1),1e-9);\n\n\t// establish range is indeed 45 degrees\n\tEXPECT_DOUBLES_EQUAL(sqrt(2.0),x1.range(l2),1e-9);\n\n\t// Another pair\n\tdouble actual23 = x2.range(l3, actualH1, actualH2);\n\tEXPECT_DOUBLES_EQUAL(sqrt(2.0),actual23,1e-9);\n\n\t// Check numerical derivatives\n\texpectedH1 = numericalDerivative21(range_proxy, x2, l3);\n\texpectedH2 = numericalDerivative22(range_proxy, x2, l3);\n\tEXPECT(assert_equal(expectedH1,actualH1));\n\tEXPECT(assert_equal(expectedH2,actualH2));\n\n\t// Another test\n\tdouble actual34 = x3.range(l4, actualH1, actualH2);\n\tEXPECT_DOUBLES_EQUAL(2,actual34,1e-9);\n\n\t// Check numerical derivatives\n\texpectedH1 = numericalDerivative21(range_proxy, x3, l4);\n\texpectedH2 = numericalDerivative22(range_proxy, x3, l4);\n\tEXPECT(assert_equal(expectedH1,actualH1));\n\tEXPECT(assert_equal(expectedH2,actualH2));\n}\n\n/* ************************************************************************* */\nLieVector range_pose_proxy(const Pose2& pose, const Pose2& point) {\n\treturn LieVector(pose.range(point));\n}\nTEST( Pose2, range_pose )\n{\n\tPose2 xl1(1, 0, M_PI/2.0), xl2(1, 1, M_PI), xl3(2.0, 2.0,-M_PI/2.0), xl4(1, 3, 0);\n\n\tMatrix expectedH1, actualH1, expectedH2, actualH2;\n\n\t// establish range is indeed zero\n\tEXPECT_DOUBLES_EQUAL(1,x1.range(xl1),1e-9);\n\n\t// establish range is indeed 45 degrees\n\tEXPECT_DOUBLES_EQUAL(sqrt(2.0),x1.range(xl2),1e-9);\n\n\t// Another pair\n\tdouble actual23 = x2.range(xl3, actualH1, actualH2);\n\tEXPECT_DOUBLES_EQUAL(sqrt(2.0),actual23,1e-9);\n\n\t// Check numerical derivatives\n\texpectedH1 = numericalDerivative21(range_pose_proxy, x2, xl3);\n\texpectedH2 = numericalDerivative22(range_pose_proxy, x2, xl3);\n\tEXPECT(assert_equal(expectedH1,actualH1));\n\tEXPECT(assert_equal(expectedH2,actualH2));\n\n\t// Another test\n\tdouble actual34 = x3.range(xl4, actualH1, actualH2);\n\tEXPECT_DOUBLES_EQUAL(2,actual34,1e-9);\n\n\t// Check numerical derivatives\n\texpectedH1 = numericalDerivative21(range_pose_proxy, x3, xl4);\n\texpectedH2 = numericalDerivative22(range_pose_proxy, x3, xl4);\n\tEXPECT(assert_equal(expectedH1,actualH1));\n\tEXPECT(assert_equal(expectedH2,actualH2));\n}\n\n/* ************************************************************************* */\n\nTEST(Pose2, align_1) {\n\tPose2 expected(Rot2::fromAngle(0), Point2(10,10));\n\n\tvector<Point2Pair> correspondences;\n\tPoint2Pair pq1(make_pair(Point2(0,0), Point2(10,10)));\n\tPoint2Pair pq2(make_pair(Point2(20,10), Point2(30,20)));\n\tcorrespondences += pq1, pq2;\n\n  boost::optional<Pose2> actual = align(correspondences);\n  EXPECT(assert_equal(expected, *actual));\n}\n\nTEST(Pose2, align_2) {\n\tPoint2 t(20,10);\n\tRot2 R = Rot2::fromAngle(M_PI/2.0);\n\tPose2 expected(R, t);\n\n\tvector<Point2Pair> correspondences;\n\tPoint2 p1(0,0), p2(10,0);\n\tPoint2 q1 = expected.transform_from(p1), q2 = expected.transform_from(p2);\n  EXPECT(assert_equal(Point2(20,10),q1));\n  EXPECT(assert_equal(Point2(20,20),q2));\n\tPoint2Pair pq1(make_pair(p1, q1));\n\tPoint2Pair pq2(make_pair(p2, q2));\n\tcorrespondences += pq1, pq2;\n\n  boost::optional<Pose2> actual = align(correspondences);\n  EXPECT(assert_equal(expected, *actual));\n}\n\nnamespace align_3 {\n\tPoint2 t(10,10);\n\tPose2 expected(Rot2::fromAngle(2*M_PI/3), t);\n\tPoint2 p1(0,0), p2(10,0), p3(10,10);\n\tPoint2 q1 = expected.transform_from(p1), q2 = expected.transform_from(p2), q3 = expected.transform_from(p3);\n}\n\nTEST(Pose2, align_3) {\n\tusing namespace align_3;\n\n\tvector<Point2Pair> correspondences;\n\tPoint2Pair pq1(make_pair(p1, q1));\n\tPoint2Pair pq2(make_pair(p2, q2));\n\tPoint2Pair pq3(make_pair(p3, q3));\n\tcorrespondences += pq1, pq2, pq3;\n\n  boost::optional<Pose2> actual = align(correspondences);\n  EXPECT(assert_equal(expected, *actual));\n}\n\n/* ************************************************************************* */\n// Prototype code to align two triangles using a rigid transform\n/* ************************************************************************* */\nstruct Triangle { size_t i_,j_,k_;};\n\nboost::optional<Pose2> align(const vector<Point2>& ps, const vector<Point2>& qs,\n\t\tconst pair<Triangle, Triangle>& trianglePair) {\n\tconst Triangle& t1 = trianglePair.first, t2 = trianglePair.second;\n\tvector<Point2Pair> correspondences;\n\tcorrespondences += make_pair(ps[t1.i_],qs[t2.i_]), make_pair(ps[t1.j_],qs[t2.j_]), make_pair(ps[t1.k_],qs[t2.k_]);\n\treturn align(correspondences);\n}\n\nTEST(Pose2, align_4) {\n\tusing namespace align_3;\n\n\tvector<Point2> ps,qs;\n\tps += p1, p2, p3;\n\tqs += q3, q1, q2; // note in 3,1,2 order !\n\n\tTriangle t1; t1.i_=0; t1.j_=1; t1.k_=2;\n\tTriangle t2; t2.i_=1; t2.j_=2; t2.k_=0;\n\n  boost::optional<Pose2> actual = align(ps, qs, make_pair(t1,t2));\n  EXPECT(assert_equal(expected, *actual));\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n\n", "meta": {"hexsha": "a79371e632ed8cadcf504e09d88f0c364e8d5ec5", "size": 24050, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/tests/testPose2.cpp", "max_stars_repo_name": "sdmiller/gtsam_pcl", "max_stars_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T16:41:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T07:02:44.000Z", "max_issues_repo_path": "gtsam/geometry/tests/testPose2.cpp", "max_issues_repo_name": "sdmiller/gtsam_pcl", "max_issues_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/geometry/tests/testPose2.cpp", "max_forks_repo_name": "sdmiller/gtsam_pcl", "max_forks_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T12:06:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T07:02:48.000Z", "avg_line_length": 33.8732394366, "max_line_length": 115, "alphanum_fraction": 0.6174220374, "num_tokens": 7423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.540648602947102}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu> Licensed\n * under the MIT license. See the license file LICENSE.\n */\n#pragma once\n\n#include <stdint.h>\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/QR>\n#include <unsupported/Eigen/MatrixFunctions>\n\n// CUDA runtime\n#include <cuda_runtime.h>\n// Utilities and system includes\n//#include <helper_functions.h>\n#include <nvidia/helper_cuda.h>\n\n//#include <mmf/defines.h>\n#include <mmf/sphereSimple.hpp>\n#include <mmf/optimizationSO3.hpp>\n//#include <mmf/timer.hpp>\n\nusing namespace Eigen;\n\nnamespace mmf{\n\nclass OptSO3vMF : public OptSO3\n{\n  public:\n  OptSO3vMF(float sigma, float t_max = 5.0f, float dt = 0.05f, float\n      *d_weights =NULL):\n    OptSO3(sigma,t_max, dt, d_weights)\n  {\n//    t_max_ = 5.0f;\n//    dt_ = 0.05f; // 0.1\n  };\n\n  virtual ~OptSO3vMF()\n  { };\n\nprotected:\n\n  virtual void conjugateGradientPostparation_impl(Matrix3f& R);\n  virtual float conjugateGradientPreparation_impl(Matrix3f& R, uint32_t& N);\n  /* evaluate cost function for a given assignment of npormals to axes */\n  virtual float evalCostFunction(Matrix3f& R);\n  /* compute Jacobian */\n  virtual void computeJacobian(Matrix3f&J, Matrix3f& R, float N);\n\n  virtual void init() {};\n};\n\n}\n", "meta": {"hexsha": "5f69aff7f72c148cbd0c97bb506fe9922f069757", "size": 1260, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mmf/optimizationSO3_vmf.hpp", "max_stars_repo_name": "jstraub/mmf", "max_stars_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-06-02T04:17:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T05:44:53.000Z", "max_issues_repo_path": "include/mmf/optimizationSO3_vmf.hpp", "max_issues_repo_name": "jstraub/mmf", "max_issues_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "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/mmf/optimizationSO3_vmf.hpp", "max_forks_repo_name": "jstraub/mmf", "max_forks_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-06T04:34:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-28T06:35:00.000Z", "avg_line_length": 22.9090909091, "max_line_length": 76, "alphanum_fraction": 0.7111111111, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5406294704808893}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.\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 <vector>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/extensions/triangulation/triangulation.hpp>\n\nnamespace bg = boost::geometry;\n\ntemplate <typename P>\nvoid test_all()\n{\n    typedef bg::model::triangulation<P, false> triangulation;\n    std::vector<P> in;\n    in.push_back(P(-1, -2));\n    in.push_back(P(1, -2));\n    in.push_back(P(-2, 0));\n    in.push_back(P(2, 0));\n    in.push_back(P(1, 2));\n    in.push_back(P(-1, 2));\n    in.push_back(P(0, 0));\n    in.push_back(P(0, 1));\n    triangulation t(8);\n    bg::delaunay_triangulation(in, t);\n    BOOST_CHECK( t.valid() );\n}\n\n\nint test_main(int, char* [])\n{\n    test_all<bg::model::point<double, 2, bg::cs::cartesian> >();\n    return 0;\n}\n", "meta": {"hexsha": "863aa506643913c36497f6a7b9e72ce0e91bed30", "size": 1055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/triangulation/triangulation.cpp", "max_stars_repo_name": "BoostGSoC19/geometry", "max_stars_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T19:33:37.000Z", "max_issues_repo_path": "extensions/test/triangulation/triangulation.cpp", "max_issues_repo_name": "BoostGSoC19/geometry", "max_issues_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "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": "extensions/test/triangulation/triangulation.cpp", "max_forks_repo_name": "BoostGSoC19/geometry", "max_forks_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T04:54:35.000Z", "avg_line_length": 24.5348837209, "max_line_length": 79, "alphanum_fraction": 0.6672985782, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5406294704808893}}
{"text": "#include <ql/quantlib.hpp>\n//#include <ql/userconfig.hpp>\n#include <iostream>\n#include <vector>\n#include <boost/foreach.hpp>\n\nusing namespace std;\nusing namespace QuantLib;\n\nvoid testingBlackScholesCalculator() {\n\n    Real S0  = 100.0;\n    Real K   = 105.0;\n    Real rd  = 0.034;\n    Real rf  = 0.021;\n    Real tau = 0.5;\n    Real vol = 0.177;\n\n    Real domDisc = std::exp(-rd*tau);\n    Real forDisc = std::exp(-rf*tau);\n    Real stdDev = vol*std::sqrt(tau);\n\n    boost::shared_ptr<PlainVanillaPayoff> vanillaPayoffPut(new PlainVanillaPayoff(Option::Put, K));\n    boost::shared_ptr<AssetOrNothingPayoff> aonPayoffCall(new AssetOrNothingPayoff(Option::Call, K));\n\n    BlackScholesCalculator vanillaPutPricer(vanillaPayoffPut, S0, forDisc, stdDev, domDisc);\n    BlackScholesCalculator aonCallPricer(aonPayoffCall, S0, forDisc, stdDev, domDisc);\n\n    cout << \"------------- Vanilla VAlues -----------------\" << endl;\n    cout << \"Value: \" << vanillaPutPricer.value() << endl;\n\n\n}\n\n\n\nint main(void) {\n\n    testingBlackScholesCalculator();\n    return 0;\n}\n\n", "meta": {"hexsha": "3c8e64e9043861ce6c308f6d03244aa2b3121256", "size": 1052, "ext": "cc", "lang": "C++", "max_stars_repo_path": "quantlib/bls.cc", "max_stars_repo_name": "guoxiaoyong/simple-useful", "max_stars_repo_head_hexsha": "63f483250cc5e96ef112aac7499ab9e3a35572a8", "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": "quantlib/bls.cc", "max_issues_repo_name": "guoxiaoyong/simple-useful", "max_issues_repo_head_hexsha": "63f483250cc5e96ef112aac7499ab9e3a35572a8", "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": "quantlib/bls.cc", "max_forks_repo_name": "guoxiaoyong/simple-useful", "max_forks_repo_head_hexsha": "63f483250cc5e96ef112aac7499ab9e3a35572a8", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4651162791, "max_line_length": 101, "alphanum_fraction": 0.6653992395, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5406294669700641}}
{"text": "#ifndef CALIBRATOR_MODELS_SHORTRATE_TWOFACTORMODELS_GENERALG2_HPP\n#define CALIBRATOR_MODELS_SHORTRATE_TWOFACTORMODELS_GENERALG2_HPP\n\n#include <boost/make_shared.hpp>\n\n#include <ql/models/shortrate/twofactormodel.hpp>\n#include <ql/instruments/swaption.hpp>\n#include <ql/math/solver1d.hpp>\n#include <ql/math/integrals/kronrodintegral.hpp>\n\n#include <calibrator/global.hpp>\n#include <calibrator/processes/generalornsteinuhlenbeckprocess.hpp>\n#include <calibrator/models/shortrate/dynamics/gaussianfactordynamics.hpp>\n\nnamespace HJCALIBRATOR\n{\n\t//! Two-additive-factor gaussian model class\n\t/*! This class implements a two-additive-factor model defined by\n\t\\f[\n\tdr_t = \\varphi(t) + x_t + y_t\n\t\\f]\n\twhere \\f$ x_t \\f$ and \\f$ y_t \\f$ are defined by\n\t\\f[\n\tdx_t = -a x_t dt + \\sigma dW^1_t, x_0 = 0\n\t\\f]\n\t\\f[\n\tdy_t = -b y_t dt + \\sigma dW^2_t, y_0 = 0\n\t\\f]\n\tand \\f$ dW^1_t dW^2_t = \\rho dt \\f$.\n\n\t\\bug This class was not tested enough to guarantee\n\tits functionality.\n\n\t\\todo Tree implementation\n\n\t\\ingroup shortrate\n\t*/\n\tclass GeneralizedG2 : public TwoFactorModel, public AffineModel, public TermStructureConsistentModel\n\t{\n\t\tclass Dynamics;\n\n\t\tshared_ptr<Gaussian2FactorDynamics> dynamics_;\n\n\tpublic:\n\t\tGeneralizedG2( shared_ptr<Gaussian2FactorDynamics> dynamics,\n\t\t\t\t\t   Real integralSignificance = 10, \n\t\t\t\t\t   shared_ptr<Integrator> integrator = boost::make_shared<GaussKronrodAdaptive>( GaussKronrodAdaptive( 1.e-8, 10000 ) ) );\n\t\tvirtual ~GeneralizedG2() {}\n\n\t\t// TwoFactorModel virtual override\n\t\tshared_ptr<Lattice> tree( const TimeGrid& grid ) const override\n\t\t{\n\t\t\t// todo\n\t\t\treturn shared_ptr<Lattice>();\n\t\t};\n\n\t\tshared_ptr<ShortRateDynamics> dynamics() const;\n\n\t\tvirtual DiscountFactor discount( Time t ) const override\n\t\t{\n\t\t\treturn termStructure()->discount( t );\n\t\t}\n\n\t\tvirtual Real discountBond( Time now,\n\t\t\t\t\t\t\t\t   Time maturity,\n\t\t\t\t\t\t\t\t   Array factors ) const;\n\n\t\tvirtual Real discountBondOption( Option::Type type,\n\t\t\t\t\t\t\t\t\t\t Real strike,\n\t\t\t\t\t\t\t\t\t\t Time maturity,\n\t\t\t\t\t\t\t\t\t\t Time bondMaturity ) const override;\n\n\t\tvirtual Real discountBondOption( Option::Type type, Real strike,\n\t\t\t\t\t\t\t\t\t\t Time maturity, Time bondStart,\n\t\t\t\t\t\t\t\t\t\t Time bondMaturity ) const override;\n\n\t\tvirtual Real swaption( const Swaption::arguments& arg, Real strike ) const;\n\n\t\tParameter a() const { return a_; }\n\t\tParameter b() const { return b_; }\n\t\tParameter sigma() const { return sigma_; }\n\t\tParameter eta() const { return eta_; }\n\t\tParameter rho() const { return rho_; }\n\n\tprotected:\n\t\t// CalibratedModel virtual override\n\t\tvirtual void generateArguments() override;\n\n\t\tReal A( Time t, Time T ) const;\n\n\t\tParameter& a_;\n\t\tParameter& sigma_;\n\t\tParameter& b_;\n\t\tParameter& eta_;\n\t\tParameter& rho_;\n\n\t\tReal integralSignificance_;\n\n\t\tshared_ptr<Integrator> integrator_;\n\t};\n\n\t//! Short-rate dynamics in the time-dependent Hull-White model\n\t/*! The short-rate follows an time-dependent Hull-White process */\n\tclass GeneralizedG2::Dynamics : public TwoFactorModel::ShortRateDynamics {\n\tpublic:\n\t\tDynamics( const shared_ptr<Gaussian2FactorDynamics> dynamics )\n\t\t\t: ShortRateDynamics( shared_ptr<StochasticProcess1D>( new GeneralizedOrnsteinUhlenbeckProcess( dynamics->a( 0 ), dynamics->sigma( 0 ) ) ),\n\t\t\t\t\t\t\t\t shared_ptr<StochasticProcess1D>( new GeneralizedOrnsteinUhlenbeckProcess( dynamics->a( 1 ), dynamics->sigma( 1 ) ) ),\n\t\t\t\t\t\t\t\t dynamics->rho( 0, 1 )(0.0) )\n\t\t\t, dynamics_( dynamics )\n\t\t{}\n\n\t\tvirtual Real shortRate( Time t, Real x, Real y ) const {\n\t\t\treturn x + y + dynamics_->phi( t );\n\t\t}\n\n\t\tshared_ptr<Gaussian2FactorDynamics> dynamics_;\n\t};\n\n\t// inline definitions\n\tinline shared_ptr<TwoFactorModel::ShortRateDynamics>\tGeneralizedG2::dynamics() const\n\t{\n\t\treturn shared_ptr<ShortRateDynamics>( new Dynamics( dynamics_ ) );\n\t}\n}\n#endif // !CALIBRATOR_MODELS_SHORTRATE_TWOFACTORMODELS_GENERALG2_HPP", "meta": {"hexsha": "68c0307016ee8815db95fffa9e75b41153109734", "size": 3799, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "calibrator/calibrator/models/shortrate/twofactormodels/generalg2.hpp", "max_stars_repo_name": "hanjin-kim/gaussian-n-factor", "max_stars_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-25T05:59:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T04:10:19.000Z", "max_issues_repo_path": "sources/calibrator/calibrator/models/shortrate/twofactormodels/generalg2.hpp", "max_issues_repo_name": "hanjin-kim/gaussian-n-factor", "max_issues_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sources/calibrator/calibrator/models/shortrate/twofactormodels/generalg2.hpp", "max_forks_repo_name": "hanjin-kim/gaussian-n-factor", "max_forks_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-27T04:10:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T04:10:42.000Z", "avg_line_length": 30.1507936508, "max_line_length": 141, "alphanum_fraction": 0.7246643854, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.540629462935397}}
{"text": "//\n// Created by Robert Schmoltzi on 19.05.21.\n//\n\n#include \"SpiAlgo.h\"\n#include <boost/math/special_functions/factorials.hpp>\n\nstatic GeneralizedRfAlgo::Scalar aSmallerB(const size_t a, const size_t b, const size_t n) {\n\treturn GeneralizedRfAlgo::factorials.lg_unrooted_dbl_fact_fast(static_cast<long>(n)) -\n\t       GeneralizedRfAlgo::factorials.lg_rooted_dbl_fact_fast(static_cast<long>(b)) -\n\t       GeneralizedRfAlgo::factorials.lg_rooted_dbl_fact_fast(static_cast<long>(n - a)) +\n\t       GeneralizedRfAlgo::factorials.lg_rooted_dbl_fact_fast(static_cast<long>(b - a + 1));\n}\n\n// Input: |A1|, |A2|, |X|\n// Called if splits overlap\n// Output:\n// if(S1 == S2):\n//      - lg_root(|A1|) - lg_root(|B1|) + lg_unroot(|X|)      [ <=> h(S1)]\n// else: // Let S1 be the greater split\n//      - lg_root(|A1|) - lg_root(|B2|) + lg_root(|A1| - |A2| + 1) + lg_unroot(|X|)  [ <=> h(S1,S2)]\nGeneralizedRfAlgo::Scalar SpiAlgo::one_overlap(const size_t a, const size_t b, const size_t n) {\n\tif (a == b) {\n\t\treturn GeneralizedRfAlgo::factorials.lg_unrooted_dbl_fact_fast(static_cast<long>(n)) -\n\t\t       GeneralizedRfAlgo::factorials.lg_rooted_dbl_fact_fast(static_cast<long>(a)) -\n\t\t       GeneralizedRfAlgo::factorials.lg_rooted_dbl_fact_fast(static_cast<long>(n - a));\n\t}\n\tif (a < b) {\n\t\treturn aSmallerB(a, b, n);\n\t}\n\n\treturn GeneralizedRfAlgo::factorials.lg_unrooted_dbl_fact_fast(static_cast<long>(n)) -\n\t       GeneralizedRfAlgo::factorials.lg_rooted_dbl_fact_fast(static_cast<long>(a)) -\n\t       GeneralizedRfAlgo::factorials.lg_rooted_dbl_fact_fast(static_cast<long>(n - b)) +\n\t       GeneralizedRfAlgo::factorials.lg_rooted_dbl_fact_fast(static_cast<long>(a - b + 1));\n}\n\n// Input: |A1|, |B2|, |X|\n// Called if splits overlap\n// Output:\n// if(S1 == S2):\n//      - lg_root(|A2|) - lg_root(|B2|) + lg_unroot(|X|)      [ <=> h(S1)]\n// else: // Let S1 be the greater split\n//      - lg_root(|A1|) - lg_root(|B2|) + lg_root(|A1| - |A2| + 1) + lg_unroot(|X|)  [ <=> h(S1,S2)]\nGeneralizedRfAlgo::Scalar\nSpiAlgo::one_overlap_notb(const size_t a, const size_t n_minus_b, const size_t n) {\n\tconst size_t b = n - n_minus_b;\n\tif (a == b) {\n\t\treturn GeneralizedRfAlgo::factorials.lg_unrooted_dbl_fact_fast(static_cast<long>(n)) -\n\t\t       GeneralizedRfAlgo::factorials.lg_rooted_dbl_fact_fast(static_cast<long>(b)) -\n\t\t       GeneralizedRfAlgo::factorials.lg_rooted_dbl_fact_fast(static_cast<long>(n_minus_b));\n\t}\n\tif (a < b) {\n\t\treturn aSmallerB(a, b, n);\n\t}\n\treturn GeneralizedRfAlgo::factorials.lg_unrooted_dbl_fact_fast(static_cast<long>(n)) -\n\t       GeneralizedRfAlgo::factorials.lg_rooted_dbl_fact_fast(static_cast<long>(a)) -\n\t       GeneralizedRfAlgo::factorials.lg_rooted_dbl_fact_fast(static_cast<long>(n_minus_b)) +\n\t       GeneralizedRfAlgo::factorials.lg_rooted_dbl_fact_fast(static_cast<long>(a - b + 1));\n}\n\n// Based on the implementation by Martin R. Smith, found at\n// https://github.com/ms609/TreeDist/blob/e05ab4c9e69c9548f066b2a7b256e35f7f92067d/src/tree_distance_functions.cpp\nGeneralizedRfAlgo::Scalar SpiAlgo::calc_split_score(const PllSplit &S1, const PllSplit &S2) {\n\t{\n\t\tbool found = false;\n\t\tfor (size_t i = 0; i != PllSplit::split_len; ++i) {\n\t\t\t// TODO: Time direct access vs vectorized Split-Methods (less iterations vs doing less\n\t\t\t// in each iteration)\n\t\t\tif ((~S1()[i] & S2()[i])) {\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!found)\n\t\t\treturn one_overlap(S1.getPrecalcPopcnt(), S2.getPrecalcPopcnt(), taxa);\n\t}\n\t{\n\t\tbool found = false;\n\n\t\tfor (size_t i = 0; i != PllSplit::split_len; ++i) {\n\t\t\tif ((S1()[i] & ~S2()[i])) {\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!found)\n\t\t\treturn one_overlap(S1.getPrecalcPopcnt(), S2.getPrecalcPopcnt(), taxa);\n\t}\n\tconst size_t bits_too_many = GeneralizedRfAlgo::bits_too_many(taxa);\n\tfor (size_t i = 0; i != PllSplit::split_len; ++i) {\n\t\tpll_split_base_t test = ~(S1()[i] | S2()[i]);\n\t\tif (i == PllSplit::split_len - 1 && bits_too_many) {\n\t\t\ttest &= (static_cast<pll_split_base_t>(~0) >> bits_too_many);\n\t\t}\n\t\tif (test) {\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn one_overlap_notb(S1.getPrecalcPopcnt(), S2.getPrecalcPopcnt(), taxa);\n}\nSpiAlgo::SpiAlgo(size_t split_len) : GeneralizedRfAlgo(split_len) {\n}\n\nRfAlgorithmInterface::Scalar SpiAlgo::calc_split_score(const PllSplit &S1) {\n\treturn S1.getHInfoContent();\n}\n\n// AB | DEFC\n// DEF | ABC --> ABC | DEF\n\n// ABC | DE\n// ADE | BC", "meta": {"hexsha": "d75290cb48429e7e95e8bf1ced5207ad735cae85", "size": 4325, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rf/SpiAlgo.cpp", "max_stars_repo_name": "DoktorBotti/RF_Metrics", "max_stars_repo_head_hexsha": "07b65723939b536883373b755a052f511c1c4f90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-03T07:54:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T02:23:49.000Z", "max_issues_repo_path": "src/rf/SpiAlgo.cpp", "max_issues_repo_name": "DoktorBotti/RF_Metrics", "max_issues_repo_head_hexsha": "07b65723939b536883373b755a052f511c1c4f90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rf/SpiAlgo.cpp", "max_forks_repo_name": "DoktorBotti/RF_Metrics", "max_forks_repo_head_hexsha": "07b65723939b536883373b755a052f511c1c4f90", "max_forks_repo_licenses": ["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.2743362832, "max_line_length": 114, "alphanum_fraction": 0.6830057803, "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024554, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5406294611799841}}
{"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_ASECPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASECPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing asecpi capabilities\n\n     inverse secant in \\$f\\pi\\$f multiples: \\f$(1/\\pi) \\arccos(1/x)\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = asecpi(x);\n    @endcode\n\n    @see asec, asecd, cospi, acospi\n\n  **/\n  Value asecpi(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/asecpi.hpp>\n#include <boost/simd/function/simd/asecpi.hpp>\n\n#endif\n", "meta": {"hexsha": "91ff984a25117673aa55b337d25a0e792871e6be", "size": 1020, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/asecpi.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/asecpi.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/asecpi.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": 23.1818181818, "max_line_length": 100, "alphanum_fraction": 0.5715686275, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5406294438097444}}
{"text": "#include<iostream>\n#define EIGEN_USE_MKL_ALL\n#include\"basis.hpp\"\n#include\"operators.hpp\"\n#include\"diag.h\"\n#include\"tpoperators.hpp\"\n#include\"files.hpp\"\n#include\"timeev.hpp\"\n#include\"ETH.hpp\"\n#include<iomanip>\n#include <boost/program_options.hpp>\n\nusing namespace boost::program_options;\nint main(int argc, char *argv[])\n{\n  using namespace Eigen;\nusing namespace std;\nusing namespace Many_Body;\nusing HolsteinBasis= TensorProduct<ElectronBasis, PhononBasis>;\n   // std::vector<size_t> ee(L, 0);\n using Mat= Operators::Mat;\n  size_t M{};\n  size_t L{};\n  double t0{};\n  double omega{};\n  double gamma{};\n  double T{};\n  bool PB{};\n  try\n  {\n    options_description desc{\"Options\"};\n    desc.add_options()\n      (\"help,h\", \"Help screen\")\n      (\"L\", value(&L)->default_value(4), \"L\")\n      (\"M\", value(&M)->default_value(2), \"M\")\n      (\"t\", value(&t0)->default_value(1.), \"t0\")\n      (\"gam\", value(&gamma)->default_value(1.), \"gamma\")\n      (\"omg\", value(&omega)->default_value(1.), \"omega\")\n      (\"T\", value(&T)->default_value(1.), \"T\")\n    (\"pb\", value(&PB)->default_value(true), \"PB\");\n  \n\n\n    variables_map vm;\n    store(parse_command_line(argc, argv, desc), vm);\n    notify(vm);\n\n    if (vm.count(\"help\"))\n      {std::cout << desc << '\\n'; return 0;}\n    else{\n      if (vm.count(\"L\"))\n      {      std::cout << \"L: \" << vm[\"L\"].as<size_t>() << '\\n';\n\t\n      }\n     if (vm.count(\"M,m\"))\n      {\n\tstd::cout << \"M: \" << vm[\"M\"].as<size_t>() << '\\n';\n\t\n      }\n      if (vm.count(\"t\"))\n      {\n\tstd::cout << \"t0: \" << vm[\"t\"].as<double>() << '\\n';\t\n      }\n       if (vm.count(\"omg\"))\n      {\n\tstd::cout << \"omega: \" << vm[\"omg\"].as<double>() << '\\n';\n      }\n       if (vm.count(\"gam\"))\n      {\n\tstd::cout << \"gamma: \" << vm[\"gam\"].as<double>() << '\\n';\n      }\n         if (vm.count(\"T\"))\n      {\n\tstd::cout << \"T: \" << vm[\"T\"].as<double>() << '\\n';\n      }\n              if (vm.count(\"pb\"))\n      {\n\tstd::cout << \"PB: \" << vm[\"pb\"].as<bool>() << '\\n';\n      }\n    }\n  }\n  catch (const error &ex)\n  {\n    std::cerr << ex.what() << '\\n';\n    return 0;\n  }\n   ElectronBasis e( L, 1);\n   //   std::cout<< e<<std::endl;\n      ElectronState e2( L, 0);\n   //   std::cout<< e<<std::endl;\n  \n  PhononBasis ph(L, M);\n  //  std::cout<< ph<<std::endl;\n  HolsteinBasis TP(e, ph);\n  //HolsteinBasis TP2(e2, ph);\n  //  std::cout<< TP<<std::endl;\n  e.insert(e2);\n  std::cout<< e<< std::endl;\n  //  std::cout<< TP2<< std::endl;\n  \n  std::cout<<\"total dim \"<< TP.dim << std::endl;\n  std::cout<<std::endl;\n        Mat E1=Operators::EKinOperatorL(TP, e, t0, PB);\n      Mat Ebdag=Operators::NBosonCOperator(TP, ph, gamma, PB);\n      Mat Eb=Operators::NBosonDOperator(TP, ph, gamma, PB);\n      Mat Eph=Operators::NumberOperator(TP, ph, omega,  PB);\n\n\n\n      Mat H=E1  +Ebdag + Eb+ Eph;\n          Eigen::MatrixXcd HH=Eigen::MatrixXcd(H);\n\n\n\t     Eigen::VectorXd ev=Eigen::VectorXd(TP.dim);\n\t     diagMat(HH, ev);\n\t     return 0;\n}\n \n", "meta": {"hexsha": "af6ad38d2dd61d98b1ef97a77b08714083006676", "size": 2915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/holstSpekfTex.cpp", "max_stars_repo_name": "jansendavid/many-body-lib", "max_stars_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_stars_repo_licenses": ["MIT"], "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/holstSpekfTex.cpp", "max_issues_repo_name": "jansendavid/many-body-lib", "max_issues_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_issues_repo_licenses": ["MIT"], "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/holstSpekfTex.cpp", "max_forks_repo_name": "jansendavid/many-body-lib", "max_forks_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_forks_repo_licenses": ["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.4957983193, "max_line_length": 64, "alphanum_fraction": 0.5324185249, "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5405903822710747}}
{"text": "#include <Eigen/LU>\n#include <elasty/fem.hpp>\n#include <gtest/gtest.h>\n\nnamespace\n{\n    constexpr double k_youngs_modulus = 800.0;\n    constexpr double k_poisson_ratio  = 0.40;\n\n    constexpr double k_first_lame  = elasty::fem::calcFirstLame(k_youngs_modulus, k_poisson_ratio);\n    constexpr double k_second_lame = elasty::fem::calcSecondLame(k_youngs_modulus, k_poisson_ratio);\n} // namespace\n\nTEST(FemTest, StVenantKirchhoff2d)\n{\n    auto calcPiolaStress = [](const Eigen::Matrix2d& F) -> Eigen::Matrix2d\n    {\n        return elasty::fem::calcStVenantKirchhoffPiolaStress(F, k_first_lame, k_second_lame);\n    };\n    auto calcEnergyDensity = [](const Eigen::Matrix2d& F) -> double\n    {\n        return elasty::fem::calcStVenantKirchhoffEnergyDensity(F, k_first_lame, k_second_lame);\n    };\n\n    Eigen::MatrixXd x_rest{2, 3};\n    x_rest.col(0) = Eigen::Vector2d{0.0, 0.0};\n    x_rest.col(1) = Eigen::Vector2d{1.0, 0.0};\n    x_rest.col(2) = Eigen::Vector2d{0.0, 1.0};\n\n    Eigen::MatrixXd x{2, 3};\n    x.col(0) = Eigen::Vector2d{0.0, 0.5};\n    x.col(1) = Eigen::Vector2d{2.0, 0.0};\n    x.col(2) = Eigen::Vector2d{0.0, 1.5};\n\n    // Calculate $\\frac{\\partial \\Psi}{\\partial \\mathbf{x}}$ analytically\n    const auto D_m      = elasty::fem::calc2dShapeMatrix(x_rest.col(0), x_rest.col(1), x_rest.col(2));\n    const auto D_m_inv  = D_m.inverse();\n    const auto F        = elasty::fem::calc2dTriangleDeformGrad(x.col(0), x.col(1), x.col(2), D_m_inv);\n    const auto P        = calcPiolaStress(F);\n    const auto vec_P    = Eigen::Map<const Eigen::Vector4d>{P.data(), P.size()};\n    const auto vec_PFPx = elasty::fem::calcVecTrianglePartDeformGradPartPos(D_m_inv);\n    const auto PPsiPx   = vec_PFPx.transpose() * vec_P;\n\n    // Calculate $\\frac{\\partial \\Psi}{\\partial \\mathbf{x}}$ numerically\n    Eigen::MatrixXd x_temp = x;\n    Eigen::VectorXd diff{6};\n    for (size_t i = 0; i < 3; ++i)\n    {\n        for (size_t j = 0; j < 2; ++j)\n        {\n            constexpr double eps = 1e-06;\n\n            x_temp(j, i) += eps;\n            const auto F_p =\n                elasty::fem::calc2dTriangleDeformGrad(x_temp.col(0), x_temp.col(1), x_temp.col(2), D_m_inv);\n            const auto e_p = calcEnergyDensity(F_p);\n\n            x_temp = x;\n\n            x_temp(j, i) -= eps;\n            const auto F_m =\n                elasty::fem::calc2dTriangleDeformGrad(x_temp.col(0), x_temp.col(1), x_temp.col(2), D_m_inv);\n            const auto e_m = calcEnergyDensity(F_m);\n\n            x_temp = x;\n\n            diff[i * 2 + j] = (e_p - e_m) / (2.0 * eps);\n        }\n    }\n\n    EXPECT_TRUE((PPsiPx - diff).norm() < 1e-04);\n}\n\nTEST(FemTest, CoRotational2d)\n{\n    auto calcPiolaStress = [](const Eigen::Matrix2d& F) -> Eigen::Matrix2d\n    {\n        return elasty::fem::calcCoRotationalPiolaStress(F, k_first_lame, k_second_lame);\n    };\n    auto calcEnergyDensity = [](const Eigen::Matrix2d& F) -> double\n    {\n        return elasty::fem::calcCoRotationalEnergyDensity(F, k_first_lame, k_second_lame);\n    };\n\n    Eigen::MatrixXd x_rest{2, 3};\n    x_rest.col(0) = Eigen::Vector2d{0.0, 0.0};\n    x_rest.col(1) = Eigen::Vector2d{1.0, 0.0};\n    x_rest.col(2) = Eigen::Vector2d{0.0, 1.0};\n\n    Eigen::MatrixXd x{2, 3};\n    x.col(0) = Eigen::Vector2d{0.0, 0.5};\n    x.col(1) = Eigen::Vector2d{2.0, 0.0};\n    x.col(2) = Eigen::Vector2d{0.0, 1.5};\n\n    // Calculate $\\frac{\\partial \\Psi}{\\partial \\mathbf{x}}$ analytically\n    const auto D_m      = elasty::fem::calc2dShapeMatrix(x_rest.col(0), x_rest.col(1), x_rest.col(2));\n    const auto D_m_inv  = D_m.inverse();\n    const auto F        = elasty::fem::calc2dTriangleDeformGrad(x.col(0), x.col(1), x.col(2), D_m_inv);\n    const auto P        = calcPiolaStress(F);\n    const auto vec_P    = Eigen::Map<const Eigen::Vector4d>{P.data(), P.size()};\n    const auto vec_PFPx = elasty::fem::calcVecTrianglePartDeformGradPartPos(D_m_inv);\n    const auto PPsiPx   = vec_PFPx.transpose() * vec_P;\n\n    // Calculate $\\frac{\\partial \\Psi}{\\partial \\mathbf{x}}$ numerically\n    Eigen::MatrixXd x_temp = x;\n    Eigen::VectorXd diff{6};\n    for (size_t i = 0; i < 3; ++i)\n    {\n        for (size_t j = 0; j < 2; ++j)\n        {\n            constexpr double eps = 1e-06;\n\n            x_temp(j, i) += eps;\n            const auto F_p =\n                elasty::fem::calc2dTriangleDeformGrad(x_temp.col(0), x_temp.col(1), x_temp.col(2), D_m_inv);\n            const auto e_p = calcEnergyDensity(F_p);\n\n            x_temp = x;\n\n            x_temp(j, i) -= eps;\n            const auto F_m =\n                elasty::fem::calc2dTriangleDeformGrad(x_temp.col(0), x_temp.col(1), x_temp.col(2), D_m_inv);\n            const auto e_m = calcEnergyDensity(F_m);\n\n            x_temp = x;\n\n            diff[i * 2 + j] = (e_p - e_m) / (2.0 * eps);\n        }\n    }\n\n    EXPECT_TRUE((PPsiPx - diff).norm() < 1e-04);\n}\n\nint main(int argc, char** argv)\n{\n    ::testing::InitGoogleTest(&argc, argv);\n\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "2274635f8a1969ddc059a5c433d65e2c504ff027", "size": 4917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/fem-test.cpp", "max_stars_repo_name": "yuki-koyama/elasty", "max_stars_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 176.0, "max_stars_repo_stars_event_min_datetime": "2019-04-27T00:45:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:15:45.000Z", "max_issues_repo_path": "tests/fem-test.cpp", "max_issues_repo_name": "yuki-koyama/elasty", "max_issues_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2019-04-27T00:00:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T07:01:12.000Z", "max_forks_repo_path": "tests/fem-test.cpp", "max_forks_repo_name": "yuki-koyama/elasty", "max_forks_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T01:09:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:30:41.000Z", "avg_line_length": 35.1214285714, "max_line_length": 108, "alphanum_fraction": 0.5991458206, "num_tokens": 1644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5405903690658125}}
{"text": "#include <crave/SystemC.hpp>\n#include <crave/ConstrainedRandom.hpp>\n#include <systemc.h>\n#include <boost/timer.hpp>\n\nusing crave::rand_obj;\nusing crave::randv;\nusing sc_dt::sc_bv;\nusing sc_dt::sc_uint;\n\n/**\n * ALU:\n * complete enumerated there are:\n * ADD 0x0: 136\n * SUB 0x1: 136\n * MUL 0x2:  76\n * DIV 0x3: 240\n * valid assignments.\n */\nstruct ALU4 : public rand_obj {\nrandv< sc_bv<2> >  op ;\n  randv< sc_uint<4> > a, b ;\n\n  ALU4(rand_obj* parent = 0)\n  : rand_obj(parent), op(this), a(this), b(this)\n  {\n    constraint ( (op() != (unsigned char)0x0) || ( (unsigned char)15 >= a() + b() ) );\n    constraint ( (op() != (unsigned char)0x1) || (((unsigned char)15 >= a() - b()) && (b() <= a()) ) );\n    constraint ( (op() != (unsigned char)0x2) || ( (unsigned char)15 >= a() * b() ) );\n    constraint ( (op() != (unsigned char)0x3) || ( b() != (unsigned char)0        ) );\n  }\n\n  friend std::ostream & operator<< (std::ostream & o, ALU4 const & alu) \n  {\n    o << alu.op \n      << ' ' << alu.a\n      << ' ' << alu.b\n      ;\n    return o;\n  }\n};\n\nint sc_main (int argc, char** argv)\n{\n  crave::init(\"./crave.cfg\");\n  boost::timer timer;\n  ALU4 c;\n  c.next();\n  std::cout << \"first: \" << timer.elapsed() << \"\\n\";\n  for (int i=0; i<1000; ++i) {\n    c.next();\n    //std::cout << i << \": \" << c << std::endl;\n  }\n  std::cout << \"complete: \" << timer.elapsed() << \"\\n\";\n  return 0;\n}\n\n\n", "meta": {"hexsha": "01ab46236e19cbff3bf2b1a492749cc5bdc4c2f3", "size": 1379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ALU/ALU4.cpp", "max_stars_repo_name": "hoangmle/crave-bundle-2015-07-22", "max_stars_repo_head_hexsha": "ffe89f3752887ca2fe12a327ba6c5b25bf23d98a", "max_stars_repo_licenses": ["MIT"], "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/ALU/ALU4.cpp", "max_issues_repo_name": "hoangmle/crave-bundle-2015-07-22", "max_issues_repo_head_hexsha": "ffe89f3752887ca2fe12a327ba6c5b25bf23d98a", "max_issues_repo_licenses": ["MIT"], "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/ALU/ALU4.cpp", "max_forks_repo_name": "hoangmle/crave-bundle-2015-07-22", "max_forks_repo_head_hexsha": "ffe89f3752887ca2fe12a327ba6c5b25bf23d98a", "max_forks_repo_licenses": ["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.3728813559, "max_line_length": 103, "alphanum_fraction": 0.5344452502, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5405002081984477}}
{"text": "#define DEBUG 1\n/**\n * File    : F2.cpp\n * Author  : Kazune Takahashi\n * Created : 10/7/2020, 7:10:56 PM\n * Powered by Visual Studio Code\n */\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n// ----- boost -----\n#include <boost/integer/common_factor_rt.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/rational.hpp>\n// ----- AtCoder Library -----\n#include <atcoder/all>\n// ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::integer::gcd; // for C++14 or for cpp_int\nusing boost::integer::lcm; // for C++14 or for cpp_int\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nbool ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\ntemplate <typename T>\nbool ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\n// ----- mint -----\nusing mint = atcoder::modint1000000007;\n// using mint = atcoder::modint998244353;\n// using mint = atcoder::modint; // atcoder::modint::set_mod(xxx);\n// using mint = atcoder::static_modint<1000000009>;\n// using mint0 = dynamic_modint<xxx>;\n// using mint1 = dynamic_modint<yyy>;\nistream &operator>>(istream &is, mint &x)\n{\n  ll t;\n  is >> t;\n  x = t;\n  return is;\n}\nostream &operator<<(ostream &os, mint const &x)\n{\n  return os << x.val();\n}\n// ----- Combination -----\ntemplate <typename Mint = mint>\nclass Combination\n{\npublic:\n  constexpr static ll MAX_SIZE{3'000'010LL};\n  // constexpr static ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed\n  vector<mint> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i{2LL}; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[Mint::mod() % i]) * (Mint::mod() / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i{1LL}; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing combination = Combination<mint>;\n// ----- for C++17 -----\ntemplate <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>\nsize_t popcount(T x) { return bitset<64>(x).count(); }\nsize_t popcount(string const &S) { return bitset<200010>{S}.count(); }\n// ----- Infty -----\ntemplate <typename T>\nconstexpr T Infty() { return numeric_limits<T>::max(); }\ntemplate <typename T>\nconstexpr T mInfty() { return numeric_limits<T>::min(); }\n// ----- FenwickTree -----\ntemplate <typename T = ll>\nclass FenwickTree : public atcoder::fenwick_tree<T>\n{\npublic:\n  using atcoder::fenwick_tree<T>::fenwick_tree;\n\n  FenwickTree(vector<T> const &v) : FenwickTree(static_cast<int>(v.size()))\n  {\n    for (auto i{size_t{0}}; i < v.size(); ++i)\n    {\n      atcoder::fenwick_tree<T>::add(i, v[i]);\n    }\n  }\n\n  T operator[](int i)\n  {\n    return atcoder::fenwick_tree<T>::sum(i, i + 1);\n  }\n};\n// ----- Math -----\nusing atcoder::floor_sum;\n// ----- UnionFind -----\nusing UnionFind = atcoder::dsu;\n// ----- MaxFlow -----\ntemplate <typename Cap = ll>\nclass MaxFlow : public atcoder::mf_graph<Cap>\n{\npublic:\n  using atcoder::mf_graph<Cap>::mf_graph;\n\n  int add_edge(int from, int to)\n  {\n    return atcoder::mf_graph<Cap>::add_edge(from, to, Cap{1});\n  }\n};\nostream &operator<<(ostream &os, typename atcoder::mf_graph<ll>::edge const &edge)\n{\n  return os << \"from: \" << edge.from << \", to: \" << edge.to << \", cap: \" << edge.cap << \", flow: \" << edge.flow;\n}\n// ----- MinCostFlow -----\ntemplate <typename Cap = ll, typename Cost = ll>\nclass MinCostFlow : public atcoder::mcf_graph<Cap, Cost>\n{\nprivate:\n  Cost infty;\n\npublic:\n  using atcoder::mcf_graph<Cap, Cost>::mcf_graph;\n\n  MinCostFlow(int n, Cost infty = Cost{0}) : atcoder::mcf_graph<Cap, Cost>::mcf_graph(n), infty{infty} {}\n\n  int add_edge(int from, int to, Cap cap)\n  {\n    return atcoder::mcf_graph<Cap, Cost>::add_edge(from, to, cap, Cost{0});\n  }\n\n  int add_edge(int from, int to, Cap cap, Cost cost)\n  {\n    return atcoder::mcf_graph<Cap, Cost>::add_edge(from, to, cap, cost + infty);\n  }\n\n  pair<Cap, Cost> flow(int s, int t)\n  {\n    return flow(s, t, std::numeric_limits<Cap>::max());\n  }\n\n  pair<Cap, Cost> flow(int s, int t, Cap flow_limit)\n  {\n    return slope(s, t, flow_limit).back();\n  }\n\n  vector<pair<Cap, Cost>> slope(int s, int t)\n  {\n    return slope(s, t, numeric_limits<Cap>::max());\n  }\n\n  vector<pair<Cap, Cost>> slope(int s, int t, Cap flow_limit)\n  {\n    auto res{atcoder::mcf_graph<Cap, Cost>::slope(s, t, flow_limit)};\n    for (auto &[cap, cost] : res)\n    {\n      cost -= cap * infty;\n    }\n    return res;\n  }\n\n  typename atcoder::mcf_graph<Cap, Cost>::edge get_edge(int i)\n  {\n    auto res{atcoder::mcf_graph<Cap, Cost>::get_edge(i)};\n    res.cost -= infty;\n    return res;\n  }\n\n  vector<typename atcoder::mcf_graph<Cap, Cost>::edge> edges()\n  {\n    auto res{atcoder::mcf_graph<Cap, Cost>::edges()};\n    for (auto &e : res)\n    {\n      e.cost -= infty;\n    }\n    return res;\n  }\n};\nostream &operator<<(ostream &os, typename atcoder::mcf_graph<ll, ll>::edge const &edge)\n{\n  return os << \"from: \" << edge.from << \", to: \" << edge.to << \", cap: \" << edge.cap << \", flow: \" << edge.flow << \", cost: \" << edge.cost;\n}\n// ----- frequently used constexpr -----\n// constexpr double epsilon{1e-10};\n// constexpr ll infty{1'000'000'000'000'010LL}; // or\n// constexpr int infty{1'000'000'010};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\n// ----- Solve -----\n\nclass Solve\n{\n\npublic:\n  Solve()\n  {\n  }\n\n  void flush()\n  {\n  }\n\nprivate:\n};\n\n// ----- main() -----\n\n/*\nint main()\n{\n  Solve solve;\n  solve.flush();\n}\n*/\n\ncombination C;\n\nint main()\n{\n  ll k;\n  string s;\n  cin >> k >> s;\n  mint ans{0};\n  ll y{static_cast<ll>(s.size())};\n  for (auto x{0}; x <= k; ++x)\n  {\n    ans += C(y + k - x - 1, y - 1) * mint{26}.pow(x) * mint{25}.pow(k - x);\n  }\n  cout << ans << endl;\n}\n", "meta": {"hexsha": "a0a2772cb5798f25f9afac5ba7452224f4caafdf", "size": 6892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/0621_ABC171/F2.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2020/0621_ABC171/F2.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/0621_ABC171/F2.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 22.6710526316, "max_line_length": 139, "alphanum_fraction": 0.5993905978, "num_tokens": 2114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5405001913476184}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/test/included/test_exec_monitor.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/tools/stats.hpp>\n#include <boost/math/tools/test.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 \"test_gamma_hooks.hpp\"\n#include \"handle_test_result.hpp\"\n\n//\n// DESCRIPTION:\n// ~~~~~~~~~~~~\n//\n// This file tests the incomplete gamma functions tgamma,\n// tgamma_lower, gamma_p and gamma_q. There are two sets of tests, spot\n// tests which compare our results with selected values computed\n// using the online special function calculator at \n// functions.wolfram.com, while the bulk of the accuracy tests\n// use values generated with NTL::RR at 1000-bit precision\n// and our generic versions of these functions.\n//\n// Note that when this file is first run on a new platform many of\n// these tests will fail: the default accuracy is 1 epsilon which\n// is too tight for most platforms.  In this situation you will \n// need to cast a human eye over the error rates reported and make\n// a judgement as to whether they are acceptable.  Either way please\n// report the results to the Boost mailing list.  Acceptable rates of\n// error are marked up below as a series of regular expressions that\n// identify the compiler/stdlib/platform/data-type/test-data/test-function\n// along with the maximum expected peek and RMS mean errors for that\n// test.\n//\n\nvoid expected_results()\n{\n   //\n   // Define the max and mean errors expected for\n   // various compilers and platforms.\n   //\n   const char* largest_type;\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())\n   {\n      largest_type = \"(long\\\\s+)?double\";\n   }\n   else\n   {\n      largest_type = \"long double\";\n   }\n#else\n   largest_type = \"(long\\\\s+)?double\";\n#endif\n   //\n   // Linux:\n   //\n   // These should not really be needed, but on *some* Linux\n   // versions these error rates are quite large and appear to\n   // be related to the accuracy of powl and expl.  On Itanium\n   // or Xeon machines the error rates are much lower than this.\n   // Worst cases appear to be AMD64 machines.\n   //\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"linux\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*medium[^|]*\",               // test data group\n      \"[^|]*\", 1000, 200);                 // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"linux\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*integer[^|]*\",               // test data group\n      \"[^|]*\", 1000, 200);                 // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"linux\",                          // platform\n      \"real_concept\",                   // test type(s)\n      \"[^|]*medium[^|]*\",               // test data group\n      \"[^|]*\", 600, 200);                // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"linux\",                          // platform\n      \"real_concept\",                   // test type(s)\n      \"[^|]*integer[^|]*\",               // test data group\n      \"[^|]*\", 600, 200);                // test function\n\n   //\n   // Mac OS X:\n   // It's not clear why these should be required, but see notes above\n   // about Linux.\n   //\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"Mac OS\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*medium[^|]*\",               // test data group\n      \"[^|]*\", 5000, 1000);                 // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"Mac OS\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*small[^|]*\",               // test data group\n      \"[^|]*\", 40, 15);                 // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"Mac OS\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*integer[^|]*\",               // test data group\n      \"[^|]*\", 2000, 300);                 // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"Mac OS\",                          // platform\n      \"real_concept\",                   // test type(s)\n      \"[^|]*medium[^|]*\",               // test data group\n      \"[^|]*\", 5000, 1000);                // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"Mac OS\",                          // platform\n      \"real_concept\",                     // test type(s)\n      \"[^|]*small[^|]*\",               // test data group\n      \"[^|]*\", 40, 15);                 // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"Mac OS\",                          // platform\n      \"real_concept\",                   // test type(s)\n      \"[^|]*integer[^|]*\",               // test data group\n      \"[^|]*\", 2000, 300);                // test function\n   //\n   // HP-UX:\n   //\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"HP-UX\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*medium[^|]*\",               // test data group\n      \"[^|]*\", 500, 50);                 // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"HP-UX\",                          // platform\n      \"real_concept\",                   // test type(s)\n      \"[^|]*medium[^|]*\",               // test data group\n      \"[^|]*\", 500, 100);                // test function\n   //\n   // Sun OS:\n   //\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"Sun.*\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*medium[^|]*\",               // test data group\n      \"[^|]*\", 500, 100);               // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"Sun.*\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*integer[^|]*\",              // test data group\n      \"[^|]*\", 100, 30);                // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"Sun.*\",                          // platform\n      \"real_concept\",                   // test type(s)\n      \"[^|]*medium[^|]*\",               // test data group\n      \"[^|]*\", 500, 100);                // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"Sun.*\",                          // platform\n      \"real_concept\",                   // test type(s)\n      \"[^|]*integer[^|]*\",               // test data group\n      \"[^|]*\", 100, 30);                // test function\n\n   //\n   // Mac OS X:\n   //\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"Mac OS\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*medium[^|]*\",               // test data group\n      \"[^|]*\", 100, 50);                 // test function\n\n   //\n   // Large exponent range causes more extreme test cases to be evaluated:\n   //\n   if(std::numeric_limits<long double>::max_exponent > std::numeric_limits<double>::max_exponent)\n   {\n      add_expected_result(\n         \"[^|]*\",                          // compiler\n         \"[^|]*\",                          // stdlib\n         \"[^|]*\",                          // platform\n         largest_type,                     // test type(s)\n         \"[^|]*large[^|]*\",                // test data group\n         \".*\", 40000, 3000);  // test function\n   }\n\n\n   //\n   // Catch all cases come last:\n   //\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"[^|]*\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*medium[^|]*\",               // test data group\n      \"[^|]*\", 50, 20);                 // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"[^|]*\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*small[^|]*\",                // test data group\n      \"[^|]*\", 20, 10);                  // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"[^|]*\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*large[^|]*\",                // test data group\n      \"boost::math::gamma_q\", 500, 50);  // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"Cygwin\",                         // platform\n      largest_type,                     // test type(s)\n      \"[^|]*large[^|]*\",                // test data group\n      \"boost::math::gamma_p\", 700, 50);  // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"[^|]*\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*large[^|]*\",                // test data group\n      \"boost::math::gamma_p\", 350, 50);  // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"[^|]*\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*integer[^|]*\",              // test data group\n      \".*\", 20, 10);                    // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"[^|]*\",                          // platform\n      \"real_concept\",                   // test type(s)\n      \"[^|]*medium[^|]*\",               // test data group\n      \"[^|]*\", 200, 50);                // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"[^|]*\",                          // platform\n      \"real_concept\",                   // test type(s)\n      \"[^|]*small[^|]*\",                // test data group\n      \".*\", 20, 10);                  // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"[^|]*\",                          // platform\n      \"real_concept\",                   // test type(s)\n      \"[^|]*large[^|]*\",                // test data group\n      \".*\", 1000000, 100000);        // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"[^|]*\",                          // platform\n      \"real_concept\",                   // test type(s)\n      \"[^|]*integer[^|]*\",              // test data group\n      \".*\", 40, 10);                    // test function\n\n   //\n   // Finish off by printing out the compiler/stdlib/platform names,\n   // we do this to make it easier to mark up expected error rates.\n   //\n   std::cout << \"Tests run with \" << BOOST_COMPILER << \", \" \n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << std::endl;\n}\n\ntemplate <class T>\nvoid do_test_gamma_2(const T& data, const char* type_name, const char* test_name)\n{\n   typedef typename T::value_type row_type;\n   typedef typename row_type::value_type value_type;\n\n   typedef value_type (*pg)(value_type, value_type);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::tgamma<value_type, value_type>;\n#else\n   pg funcp = boost::math::tgamma;\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 tgamma(T, T) against data:\n   //\n   if(data[0][2] > 0)\n   {\n      result = boost::math::tools::test(\n         data,\n         bind_func(funcp, 0, 1),\n         extract_result(2));\n      handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::tgamma\", test_name);\n      //\n      // test tgamma_lower(T, T) against data:\n      //\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n      funcp = boost::math::tgamma_lower<value_type, value_type>;\n#else\n      funcp = boost::math::tgamma_lower;\n#endif\n      result = boost::math::tools::test(\n         data,\n         bind_func(funcp, 0, 1),\n         extract_result(4));\n      handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::tgamma_lower\", test_name);\n   }\n   //\n   // test gamma_q(T, T) against data:\n   //\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   funcp = boost::math::gamma_q<value_type, value_type>;\n#else\n   funcp = boost::math::gamma_q;\n#endif\n   result = boost::math::tools::test(\n      data,\n      bind_func(funcp, 0, 1),\n      extract_result(3));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::gamma_q\", test_name);\n#if defined(TEST_CEPHES) || defined(TEST_GSL)\n   //\n   // test other gamma_q(T, T) against data:\n   //\n   if(boost::is_floating_point<value_type>::value)\n   {\n      funcp = other::gamma_q;\n      result = boost::math::tools::test(\n         data,\n         bind_func(funcp, 0, 1),\n         extract_result(3));\n      print_test_result(result, data[result.worst()], result.worst(), type_name, \"other::gamma_q\");\n   }\n#endif\n   //\n   // test gamma_p(T, T) against data:\n   //\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   funcp = boost::math::gamma_p<value_type, value_type>;\n#else\n   funcp = boost::math::gamma_p;\n#endif\n   result = boost::math::tools::test(\n      data,\n      bind_func(funcp, 0, 1),\n      extract_result(5));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::gamma_p\", test_name);\n#if defined(TEST_CEPHES) || defined(TEST_GSL)\n   //\n   // test other gamma_p(T, T) against data:\n   //\n   if(boost::is_floating_point<value_type>::value)\n   {\n      funcp = other::gamma_p;\n      result = boost::math::tools::test(\n         data,\n         bind_func(funcp, 0, 1),\n         extract_result(5));\n      print_test_result(result, data[result.worst()], result.worst(), type_name, \"other::gamma_p\");\n   }\n#endif\n   std::cout << std::endl;\n}\n\ntemplate <class T>\nvoid test_gamma(T, const char* name)\n{\n   //\n   // The actual test data is rather verbose, so it's in a separate file\n   //\n   // First the data for the incomplete gamma function, each\n   // row has the following 6 entries:\n   // Parameter a, parameter z,\n   // Expected tgamma(a, z), Expected gamma_q(a, z)\n   // Expected tgamma_lower(a, z), Expected gamma_p(a, z)\n   //\n#  include \"igamma_med_data.ipp\"\n\n   do_test_gamma_2(igamma_med_data, name, \"tgamma(a, z) medium values\");\n\n#  include \"igamma_small_data.ipp\"\n\n   do_test_gamma_2(igamma_small_data, name, \"tgamma(a, z) small values\");\n\n#  include \"igamma_big_data.ipp\"\n\n   do_test_gamma_2(igamma_big_data, name, \"tgamma(a, z) large values\");\n\n#  include \"igamma_int_data.ipp\"\n\n   do_test_gamma_2(igamma_int_data, name, \"tgamma(a, z) integer and half integer values\");\n}\n\ntemplate <class T>\nvoid test_spots(T)\n{\n   //\n   // basic sanity checks, tolerance is 10 epsilon expressed as a percentage:\n   //\n   T tolerance = boost::math::tools::epsilon<T>() * 1000;\n#if (defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__))\n   tolerance *= 10;\n#endif\n   BOOST_CHECK_CLOSE(::boost::math::tgamma(static_cast<T>(5), static_cast<T>(1)), static_cast<T>(23.912163676143750903709045060494956383977723517065L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::tgamma(static_cast<T>(5), static_cast<T>(5)), static_cast<T>(10.571838841565097874621959975919877646444998907920L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::tgamma(static_cast<T>(5), static_cast<T>(10)), static_cast<T>(0.70206451384706574414638719662835463671916532623256L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::tgamma(static_cast<T>(5), static_cast<T>(100)), static_cast<T>(3.8734332808745531496973774140085644548465762343719e-36L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::tgamma(static_cast<T>(0.5), static_cast<T>(0.5)), static_cast<T>(0.56241823159440712427949495730204306902676756479651L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::tgamma(static_cast<T>(0.5), static_cast<T>(9)/10), static_cast<T>(0.31853210360412109873859360390443790076576777747449L), tolerance*10);\n   BOOST_CHECK_CLOSE(::boost::math::tgamma(static_cast<T>(0.5), static_cast<T>(5)), static_cast<T>(0.0027746032604128093194908357272603294120210079791437L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::tgamma(static_cast<T>(0.5), static_cast<T>(100)), static_cast<T>(3.7017478604082789202535664481339075721362102520338e-45L), tolerance);\n\n   BOOST_CHECK_CLOSE(::boost::math::tgamma_lower(static_cast<T>(5), static_cast<T>(1)), static_cast<T>(0.087836323856249096290954939505043616022276482935091L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::tgamma_lower(static_cast<T>(5), static_cast<T>(5)), static_cast<T>(13.428161158434902125378040024080122353555001092080L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::tgamma_lower(static_cast<T>(5), static_cast<T>(10)), static_cast<T>(23.297935486152934255853612803371645363280834673767L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::tgamma_lower(static_cast<T>(5), static_cast<T>(100)), static_cast<T>(23.999999999999999999999999999999999996126566719125L), tolerance);\n\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q(static_cast<T>(5), static_cast<T>(1)), static_cast<T>(0.99634015317265628765454354418728984933240514654437L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q(static_cast<T>(5), static_cast<T>(5)), static_cast<T>(0.44049328506521241144258166566332823526854162116334L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q(static_cast<T>(5), static_cast<T>(10)), static_cast<T>(0.029252688076961072672766133192848109863298555259690L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q(static_cast<T>(5), static_cast<T>(100)), static_cast<T>(1.6139305336977304790405739225035685228527400976549e-37L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q(static_cast<T>(1.5), static_cast<T>(2)), static_cast<T>(0.26146412994911062220282207597592120190281060919079L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q(static_cast<T>(20.5), static_cast<T>(22)), static_cast<T>(0.34575332043467326814971590879658406632570278929072L), tolerance);\n\n   BOOST_CHECK_CLOSE(::boost::math::gamma_p(static_cast<T>(5), static_cast<T>(1)), static_cast<T>(0.0036598468273437123454564558127101506675948534556288L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_p(static_cast<T>(5), static_cast<T>(5)), static_cast<T>(0.55950671493478758855741833433667176473145837883666L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_p(static_cast<T>(5), static_cast<T>(10)), static_cast<T>(0.97074731192303892732723386680715189013670144474031L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_p(static_cast<T>(5), static_cast<T>(100)), static_cast<T>(0.9999999999999999999999999999999999998386069466302L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_p(static_cast<T>(1.5), static_cast<T>(2)), static_cast<T>(0.73853587005088937779717792402407879809718939080921L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_p(static_cast<T>(20.5), static_cast<T>(22)), static_cast<T>(0.65424667956532673185028409120341593367429721070928L), tolerance);\n\n   // naive check on derivative function:\n   using namespace std;  // For ADL of std functions\n   tolerance = boost::math::tools::epsilon<T>() * 5000; // 50 eps\n   BOOST_CHECK_CLOSE(::boost::math::gamma_p_derivative(static_cast<T>(20.5), static_cast<T>(22)), \n      exp(static_cast<T>(-22)) * pow(static_cast<T>(22), static_cast<T>(19.5)) / boost::math::tgamma(static_cast<T>(20.5)), tolerance);\n\n}\n\nint test_main(int, char* [])\n{\n   expected_results();\n   BOOST_MATH_CONTROL_FP;\n\n#ifndef BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS\n   test_spots(0.0F);\n#endif\n   test_spots(0.0);\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   test_spots(0.0L);\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n   test_spots(boost::math::concepts::real_concept(0.1));\n#endif\n#endif\n\n#ifndef BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS\n   test_gamma(0.1F, \"float\");\n#endif\n   test_gamma(0.1, \"double\");\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   test_gamma(0.1L, \"long double\");\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n   test_gamma(boost::math::concepts::real_concept(0.1), \"real_concept\");\n#endif\n#endif\n#else\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\n      \"either because the long double overloads of the usual math functions are \"\n      \"not available at all, or because they are too inaccurate for these tests \"\n      \"to pass.</note>\" << std::cout;\n#endif\n   return 0;\n}\n\n\n\n", "meta": {"hexsha": "2940ca09e6a4a21662fb8c51b078a81619d3a8ae", "size": 23090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_igamma.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/math/test/test_igamma.cpp", "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": 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_igamma.cpp", "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": 44.4894026975, "max_line_length": 172, "alphanum_fraction": 0.5343438718, "num_tokens": 5887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.5405001913476184}}
{"text": "#ifndef LEPP3_OBSTACLE_EVALUATOR_H_\n#define LEPP3_OBSTACLE_EVALUATOR_H_\n#include <boost/filesystem.hpp>\n#include <iostream>\n#include <sstream>\n#include \"lepp3/FrameData.hpp\"\n#include \"lepp3/util/util.h\"\n/**\n * A class that computes the volume of a given model.\n * It is a `ModelVisitor` implementation and it assumes one model as input,\n * regardless of how many sub-parts the approximation has, a.k.a the\n * `CompositeModel`.\n *\n * The volume computation is done by creating a 3D grid around the model and\n * estimating how many points on the grid are occupied.\n */\nclass VolumeEstimator : public ModelVisitor {\npublic:\n  VolumeEstimator()\n      : num_splits_(0) {\n    min_p_.x = std::numeric_limits<int>::max();\n    min_p_.y = std::numeric_limits<int>::max();\n    min_p_.z = std::numeric_limits<int>::max();\n    max_p_.x = std::numeric_limits<int>::min();\n    max_p_.y = std::numeric_limits<int>::min();\n    max_p_.z = std::numeric_limits<int>::min();\n  }\n  /**\n   * Implementation of the `ModelVisitor` interface. It will draw the given\n   * sphere onto the `PCLVisualizer` to which it holds a reference.\n   */\n  void visitSphere(lepp::SphereModel& sphere);\n  void visitCapsule(lepp::CapsuleModel& capsule);\n  int getSplitCount() { return num_splits_; }\n  /**\n   * Estimates the volume of the approximated model. This is achieved by\n   * creating a bounding box around the min/max points of the approximation and\n   * subdivide the region into small grids.\n   */\n  int estimateVolume();\nprivate:\n  /**\n   * Checks if the current point on the 3D grid (a.k.a the bounding box around\n   * the model) is inside the model.\n   */\n  bool isVoxelOccupied(double const& x, double const& y, double const& z);\n  /**\n   * Minimum/Maximum points of the bounding box surrounding the model.\n   */\n  Coordinate min_p_, max_p_;\n  /**\n   * Container to hold track of sphere models in a `CompositeModel`\n   */\n  std::vector<SphereModel> spheres_;\n  /**\n   * Container to hold track of capsule models in a `CompositeModel`\n   */\n  std::vector<CapsuleModel> capsules_;\n  /**\n   * Number of sub-models in this model. This determines how many split operations\n   * have been executed\n   */\n  int num_splits_;\n};\nvoid VolumeEstimator::visitSphere(lepp::SphereModel& sphere) {\n  ++num_splits_;\n  // Store the current Sphere model.\n  spheres_.push_back(sphere);\n  Coordinate const center = sphere.center_point();\n  double const max_x = center.x + sphere.radius();\n  double const max_y = center.y + sphere.radius();\n  double const max_z = center.z + sphere.radius();\n  double const min_x = center.x - sphere.radius();\n  double const min_y = center.y - sphere.radius();\n  double const min_z = center.z - sphere.radius();\n  max_p_.x = std::max(max_p_.x, max_x);\n  max_p_.y = std::max(max_p_.y, max_y);\n  max_p_.z = std::max(max_p_.z, max_z);\n  min_p_.x = std::min(min_p_.x, min_x);\n  min_p_.y = std::min(min_p_.y, min_y);\n  min_p_.z = std::min(min_p_.z, min_z);\n  double volume = 4/3*M_PI*sphere.radius()*sphere.radius()*sphere.radius();\n  //std::cout << volume << std::endl;\n}\nvoid VolumeEstimator::visitCapsule(lepp::CapsuleModel& capsule) {\n  ++num_splits_;\n  // Store the current Capsule model.\n  capsules_.push_back(capsule);\n  Coordinate first = capsule.first();\n  Coordinate second = capsule.second();\n  double a = std::sqrt((first.x - second.x)*(first.x - second.x) + (first.y - second.y)*(first.y - second.y) + (first.z - second.z)*(first.z - second.z));\n  double volume = M_PI*capsule.radius()*capsule.radius()*(4/3*capsule.radius() + a);\n  //std::cout << volume << std::endl;\n  Coordinate min, max;\n  min.x = std::min(first.x, second.x);\n  min.y = std::min(first.y, second.y);\n  min.z = std::min(first.z, second.z);\n  max.x = std::max(first.x, second.x);\n  max.y = std::max(first.y, second.y);\n  max.z = std::max(first.z, second.z);\n  // Add the capsule radius to min/max\n  min.x -= capsule.radius();\n  min.y -= capsule.radius();\n  min.z -= capsule.radius();\n  max.x += capsule.radius();\n  max.y += capsule.radius();\n  max.z += capsule.radius();\n  // Find the global min/max\n  min_p_.x = std::min(min_p_.x, min.x);\n  min_p_.y = std::min(min_p_.y, min.y);\n  min_p_.z = std::min(min_p_.z, min.z);\n  max_p_.x = std::max(max_p_.x, max.x);\n  max_p_.y = std::max(max_p_.y, max.y);\n  max_p_.z = std::max(max_p_.z, max.z);\n}\nbool VolumeEstimator::isVoxelOccupied(\n    double const& x, double const& y, double const& z) {\n  // Go through all spheres of the current model and check if the point is\n  // inside one of them.\n  {\n    size_t sz = spheres_.size();\n    for (size_t i=0; i<sz; ++i) {\n      double const r = spheres_[i].radius();\n      Coordinate const& center = spheres_[i].center_point();\n      double const distance =\n          (center.x - x) * (center.x - x) + (center.y - y) * (center.y - y) + (center.z - z) * (center.z - z);\n      if (distance <= r * r)\n        return true;\n    }\n  }\n  // Go through all capsules of the current model and check if the point is\n  // inside one of them.\n  {\n    size_t sz = capsules_.size();\n    for (size_t i=0; i<sz; ++i) {\n      double r = capsules_[i].radius();\n      /*\n       * Prepare the pcl::sqrPointToLineDistance input arguments.\n       */\n      // line_dir: line direction vector\n      Coordinate l = capsules_[i].second() - capsules_[i].first();\n      Eigen::Vector4f line_dir(l.x, l.y, l.z, 0.);\n      // line_pt: a point on the line\n      Eigen::Vector4f line_pt(\n          capsules_[i].second().x,\n          capsules_[i].second().y,\n          capsules_[i].second().z,\n          0.);\n      Eigen::Vector4f pt(x, y, z, 0);\n      double const distance = pcl::sqrPointToLineDistance(pt, line_pt, line_dir);\n      if (distance < r*r)\n        return true;\n    }\n  }\n  return false;\n}\nint VolumeEstimator::estimateVolume() {\n  // NOTE: All the values are in METERS\n  // Create a 3D grid and check the distance of each point on grid to the object\n  // models.\n  // TODO: 3D grid creation should depend on the point cloud resolution\n  double const step_size = 0.01;\n  int volume = 0;\n  for (double x = min_p_.x; x < max_p_.x; x += step_size) {\n    for (double y = min_p_.y; y < max_p_.y; y += step_size) {\n      for (double z = min_p_.z; z < max_p_.z; z += step_size) {\n        if (isVoxelOccupied(x, y, z))\n          ++volume;\n      }\n    }\n  }\n  return volume;\n}\n/**\n *\n */\nclass ObstacleEvaluator : public FrameDataObserver {\npublic:\n  ObstacleEvaluator();\n  ObstacleEvaluator(int vol);\n  /**\n   * ObstacleAggregator interface implementation: processes the current models.\n   */\n  void updateFrame(FrameDataPtr frameData);\nprivate:\n  void init();\n  bool evaluate(ObjectModelPtr const& model, double x, double y, double z);\n  std::string file_path_;\n  int ref_volume_;\n};\nObstacleEvaluator::ObstacleEvaluator()\n    : ref_volume_(0) {\n  init();\n}\nObstacleEvaluator::ObstacleEvaluator(int vol)\n    : ref_volume_(vol) {\n  init();\n}\nvoid ObstacleEvaluator::init() {\n  namespace bfs = boost::filesystem;\n  std::stringstream ss;\n  // Create the evaluation directory\n  ss << \"../evaluation/\";\n  std::string dir = ss.str();\n  if ( !bfs::exists(bfs::path(dir)) )\n    bfs::create_directory(bfs::path(dir));\n  // Create the sub directory based on current timestamp\n  ss << lepp::get_current_timestamp();\n  dir = ss.str();\n  bfs::create_directory(bfs::path(dir));\n  // Prepare the csv file path\n  ss  << \"/eval.csv\";\n  file_path_ = ss.str();\n  std::cout << \"file_path: \" << file_path_ << std::endl;\n  // Create the file header\n  std::ofstream tf_fout;\n  tf_fout.open(file_path_.c_str(), std::ofstream::app);\n  tf_fout << \"model_id,\"\n          << \"volume,\"\n          << \"sim_veloc_x,\"\n          << \"sim_veloc_y,\"\n          << \"sim_veloc_z,\"\n          << std::endl;\n  tf_fout.close();\n}\nbool ObstacleEvaluator::evaluate(ObjectModelPtr const& model, double x, double y, double z) {\n  // TODO incorporate try-catch scheme\n  VolumeEstimator estimator;\n  // Find the minimum and maximum point of the approximated model\n  model->accept(estimator);\n  // Compute the volume of the current model\n  int vol = estimator.estimateVolume();\n  //std::cout << \"Volume Tester \" << vol << std::endl;\n  // Evaluate the approximation based on the reference information\n  float ratio = -1;\n  if (ref_volume_ != 0)\n    ratio = vol / static_cast<float>(ref_volume_);\n\n  bool has_vel = false;\n  boost::shared_ptr<CompositeModel> cm = boost::static_pointer_cast<CompositeModel>(model);\n  for( auto& m : cm->models() )\n  {\n    boost::shared_ptr<CompositeModel> cmm = boost::static_pointer_cast<CompositeModel>(m);\n\n    for ( auto& mm : cmm->models() )\n    {\n      std::cout << model->id() << \": \" << mm->velocity().x << \", \" \n                << mm->velocity().y << \", \" << mm->velocity().z << std::endl;\n      if (!std::isnan(mm->velocity().x) &&\n          !std::isnan(mm->velocity().y) &&\n          !std::isnan(mm->velocity().z))\n      {\n\n        // Save the current approximation information\n        std::stringstream ss;\n        ss << model->id() << \",\"\n           << vol << \",\"\n           << mm->velocity().x << \",\"\n           << mm->velocity().y << \",\"\n           << mm->velocity().z\n           << std::endl;\n        std::ofstream tf_fout;\n        // open the file and add the current model evaluation to the end of it\n        tf_fout.open(file_path_.c_str(), std::ofstream::app);\n        tf_fout << ss.str();\n        tf_fout.close();\n        has_vel = true;\n        break;\n      }\n    }\n  }\n\n  // if obstacle did not have a velocity estimate, log zero\n  if (!has_vel)\n  {\n      std::ofstream tf_out;\n      tf_out.open(file_path_.c_str(), std::ofstream::app);\n      tf_out << model->id() << \",\"\n             << vol << \",\"\n             << \"0,0,0\"\n             << std::endl;\n  }\n\n  return true;\n}\nvoid ObstacleEvaluator::updateFrame(FrameDataPtr frameData) {\n  size_t sz = frameData->obstacles.size();\n  for (size_t i=0; i<sz; ++i) {\n    //evaluate(frameData->obstacles[i]);\n    double x = frameData->obstacles[i]->velocity().x;\n    double y = frameData->obstacles[i]->velocity().y;\n    double z = frameData->obstacles[i]->velocity().z;\n    evaluate(frameData->obstacles[i], x, y, z);\n  }\n}\n#endif // LEPP3_OBSTACLE_EVALUATOR_H_\n", "meta": {"hexsha": "5ec0b6c2e91111eb113ccdefe2735a8124ef3324", "size": 10125, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lepp3/ObstacleEvaluator.hpp", "max_stars_repo_name": "am-lola/lepp3", "max_stars_repo_head_hexsha": "7f92ce61bccad984e18ce86da0d8a1b9c48feb65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T10:41:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-09T09:13:30.000Z", "max_issues_repo_path": "src/lepp3/ObstacleEvaluator.hpp", "max_issues_repo_name": "am-lola/lepp3", "max_issues_repo_head_hexsha": "7f92ce61bccad984e18ce86da0d8a1b9c48feb65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lepp3/ObstacleEvaluator.hpp", "max_forks_repo_name": "am-lola/lepp3", "max_forks_repo_head_hexsha": "7f92ce61bccad984e18ce86da0d8a1b9c48feb65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-08-07T13:07:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T03:18:33.000Z", "avg_line_length": 34.0909090909, "max_line_length": 154, "alphanum_fraction": 0.633382716, "num_tokens": 2793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.540480981067031}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2017, Massachusetts Institute of Technology,\n * Cambridge, MA 02139\n * All Rights Reserved\n * Authors: Luca Carlone, et al. (see THANKS for the full author list)\n * See LICENSE for the license information\n * -------------------------------------------------------------------------- */\n\n/**\n * @file   testParallelPlaneRegularBasicFactor.cpp\n * @brief  test ParallelPlaneRegularBasicFactor\n * @author Antoni Rosinol Vidal\n */\n\n#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <random>\n\n#include <gtsam/base/numericalDerivative.h>\n#include <boost/assign/std/vector.hpp>\n#include <boost/bind.hpp>\n\n#include <gtsam/geometry/OrientedPlane3.h>\n#include <gtsam/geometry/Point3.h>\n#include <gtsam/nonlinear/GaussNewtonOptimizer.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/slam/PriorFactor.h>\n\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n\n#include \"kimera-vio/factors/ParallelPlaneRegularFactor.h\"\n#include \"kimera-vio/factors/PointPlaneFactor.h\"\n\nusing namespace std;\nusing namespace gtsam;\n\nstatic const double tol = 1e-5;\nstatic const double der_tol = 1e-5;\n\n/**\n * Test that error does give the right result when it is zero.\n */\nTEST(testParallelPlaneRegularBasicFactor, ErrorIsZero) {\n  /// Plane keys.\n  Key plane_key_1(1);\n  Key plane_key_2(2);\n\n  /// Noise model for cosntraint between the two planes.\n  noiseModel::Diagonal::shared_ptr parallel_plane_noise =\n      noiseModel::Diagonal::Sigmas(Vector3(0.1, 0.1, 0.1));\n\n  /// Parallelism constraint between Plane 1 and Plane 2.\n  ParallelPlaneRegularBasicFactor factor(plane_key_1, plane_key_2,\n                                         parallel_plane_noise);\n\n  /// Planes.\n  OrientedPlane3 plane_1(0.1, 0.1, 0.9, 0.9);\n  OrientedPlane3 plane_2(0.1, 0.1, 0.9, 0.1);\n\n  /// Calculate error.\n  Vector error = factor.evaluateError(plane_1, plane_2);\n\n  /// Expected error.\n  Vector3 expected_error = Vector3::Constant(0.0);\n\n  ASSERT_TRUE(assert_equal(expected_error, error, tol));\n}\n\n/**\n * Test that error does give the right result when it is not zero.\n */\nTEST(testParallelPlaneRegularBasicFactor, ErrorOtherThanZero) {\n  /// Plane keys.\n  Key plane_key_1(1);\n  Key plane_key_2(2);\n\n  /// Noise model for cosntraint between the two planes.\n  noiseModel::Diagonal::shared_ptr parallel_plane_noise =\n      noiseModel::Diagonal::Sigmas(Vector3(0.1, 0.1, 0.1));\n\n  /// Parallelism constraint between Plane 1 and Plane 2.\n  ParallelPlaneRegularBasicFactor factor(plane_key_1, plane_key_2,\n                                         parallel_plane_noise);\n\n  /// Planes.\n  OrientedPlane3 plane_1(0.3, 0.2, 1.9, 0.9);\n  OrientedPlane3 plane_2(0.1, 0.1, 0.9, 0.1);\n\n  /// Calculate error.\n  Vector error = factor.evaluateError(plane_1, plane_2);\n\n  /// Expected error.\n  Vector3 expected_error;\n  expected_error << 0.045362, -0.00634672, -0.00541173;\n\n  ASSERT_TRUE(assert_equal(expected_error, error, tol));\n}\n\n/**\n * Test that analytical jacobians equal numerical ones.\n *\n */\nTEST(testParallelPlaneRegularFactor, Jacobians) {\n  /// Plane keys.\n  Key plane_key_1(1);\n  Key plane_key_2(2);\n\n  /// Noise model for cosntraint between the two planes.\n  noiseModel::Diagonal::shared_ptr parallel_plane_noise =\n      noiseModel::Diagonal::Sigmas(Vector3(0.1, 0.1, 0.1));\n\n  /// Parallelism constraint between Plane 1 and Plane 2.\n  ParallelPlaneRegularBasicFactor factor(plane_key_1, plane_key_2,\n                                         parallel_plane_noise);\n\n  /// Planes.\n  OrientedPlane3 plane_1(0.3, 0.2, 1.9, 0.9);\n  OrientedPlane3 plane_2(0.1, 0.1, 0.9, 0.1);\n\n  // Use the factor to calculate the Jacobians\n  gtsam::Matrix H1Actual, H2Actual;\n  factor.evaluateError(plane_1, plane_2, H1Actual, H2Actual);\n\n  // Calculate numerical derivatives\n  Matrix H1Expected =\n      numericalDerivative21<Vector, OrientedPlane3, OrientedPlane3>(\n          boost::bind(&ParallelPlaneRegularBasicFactor::evaluateError, &factor,\n                      _1, _2, boost::none, boost::none),\n          plane_1, plane_2, der_tol);\n\n  Matrix H2Expected =\n      numericalDerivative22<Vector, OrientedPlane3, OrientedPlane3>(\n          boost::bind(&ParallelPlaneRegularBasicFactor::evaluateError, &factor,\n                      _1, _2, boost::none, boost::none),\n          plane_1, plane_2, der_tol);\n\n  // Verify the Jacobians are correct\n  ASSERT_TRUE(assert_equal(H1Expected, H1Actual, tol));\n  ASSERT_TRUE(assert_equal(H2Expected, H2Actual, tol));\n}\n\n/* ************************************************************************* */\nTEST(testParallelPlaneRegularBasicFactor, PlanePrior) {\n  /// Three landmarks, with prior factors, and a plane constrained together\n  /// using the landmark-plane factor.\n  NonlinearFactorGraph graph;\n\n  /// Keys\n  Key plane_key_1 = 1;\n\n  /// Shared noise for all landmarks.\n  noiseModel::Diagonal::shared_ptr prior_noise =\n      noiseModel::Diagonal::Sigmas(Vector3(0.1, 0.1, 0.1));\n\n  OrientedPlane3 priorMeanPlane(0.0, 0.0, 1.0, 0.0);\n  graph.emplace_shared<PriorFactor<OrientedPlane3> >(\n      plane_key_1, priorMeanPlane, prior_noise);\n\n  // graph.print(\"\\nFactor Graph:\\n\");\n\n  Values initial;\n  initial.insert(plane_key_1, OrientedPlane3(0.1, 0.2, 0.9, 0.8));\n\n  GaussNewtonParams params;\n  params.setVerbosity(\"ERROR\");\n  params.setMaxIterations(20);\n  params.setRelativeErrorTol(-std::numeric_limits<double>::max());\n  // params.setErrorTol(-std::numeric_limits<double>::max());\n  params.setAbsoluteErrorTol(-std::numeric_limits<double>::max());\n\n  Values result = GaussNewtonOptimizer(graph, initial, params).optimize();\n  // Values result = LevenbergMarquardtOptimizer(graph, initial,\n  // params).optimize();\n\n  Values expected;\n  expected.insert(plane_key_1, OrientedPlane3(0.0, 0.0, 1.0, 0.0));\n\n  ASSERT_TRUE(assert_equal(expected, result, tol));\n}\n\n/**\n * Test that optimization works.\n * A plane and a landmark with prior factors, and a second plane constrained\n * together with the first plane using the ParallelPlaneRegularBasic factor.\n *\n *              Prior                      +-------+    +-+\n *               +-+                       | Lmk 1 +----+ | Prior\n *               +-+        Parallelism    +---+---+    +-+\n *                |           factor           |\n *            +---+---+        +-+         +---+---+\n *            |Plane 1+--------+ +---------+Plane 2|\n *            +-------+        +-+         +-------+\n *\n */\nTEST(testParallelPlaneRegularBasicFactor, PlaneOptimization) {\n  NonlinearFactorGraph graph;\n\n  /// Keys\n  Key landmark_key = 1;\n  Key plane_key_1 = 2;\n  Key plane_key_2 = 3;\n\n  /// Shared noise for all landmarks.\n  noiseModel::Diagonal::shared_ptr prior_noise =\n      noiseModel::Diagonal::Sigmas(Vector3(0.1, 0.1, 0.1));\n\n  Point3 priorMeanLandmark1(0.0, 0.0, 0.0);\n  graph.emplace_shared<PriorFactor<Point3> >(landmark_key, priorMeanLandmark1,\n                                             prior_noise);\n\n  OrientedPlane3 priorMeanPlane1(0.0, 0.0, 1.0, 1.0);\n  graph.emplace_shared<PriorFactor<OrientedPlane3> >(\n      plane_key_1, priorMeanPlane1, prior_noise);\n\n  /// Shared noise for all constraints between landmarks and planes.\n  noiseModel::Isotropic::shared_ptr regularity_noise =\n      noiseModel::Isotropic::Sigma(1, 0.5);\n\n  /// Plane 2 to landmark.\n  graph.emplace_shared<PointPlaneFactor>(landmark_key, plane_key_2,\n                                         regularity_noise);\n\n  /// Noise model for cosntraint between the two planes.\n  noiseModel::Diagonal::shared_ptr parallel_plane_noise =\n      noiseModel::Diagonal::Sigmas(Vector3(0.1, 0.1, 0.1));\n\n  /// Parallelism constraint between Plane 1 and Plane 2.\n  graph.emplace_shared<ParallelPlaneRegularBasicFactor>(\n      plane_key_1, plane_key_2, parallel_plane_noise);\n\n  // graph.print(\"\\nFactor Graph:\\n\");\n\n  Values initial;\n  initial.insert(landmark_key, Point3(0.0, 0.2, 0.1));\n  initial.insert(plane_key_1, OrientedPlane3(0.1, 0.1, 0.9, 0.9));\n  initial.insert(plane_key_2, OrientedPlane3(0.1, 0.1, 0.8, 0.1));\n\n  // GaussianFactorGraph gfg = *graph.linearize(initial);\n  // gfg.print(\"\\nFactor Graph:\\n\");\n\n  GaussNewtonParams params;\n  // params.setVerbosity(\"LINEAR\");\n  params.setMaxIterations(20);\n  params.setRelativeErrorTol(-std::numeric_limits<double>::max());\n  // params.setErrorTol(-std::numeric_limits<double>::max());\n  params.setAbsoluteErrorTol(-std::numeric_limits<double>::max());\n\n  Values result = GaussNewtonOptimizer(graph, initial, params).optimize();\n  // Values result = LevenbergMarquardtOptimizer(graph, initial,\n  // params).optimize();\n\n  Values expected;\n  expected.insert(landmark_key, priorMeanLandmark1);\n  expected.insert(plane_key_1, priorMeanPlane1);\n  expected.insert(plane_key_2, OrientedPlane3(0.0, 0.0, 1.0, 0.0));\n\n  ASSERT_TRUE(assert_equal(expected, result, tol));\n}\n", "meta": {"hexsha": "b1413816fafc5a70d9ab5a5f3d6aef80a89c18c2", "size": 8899, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testParallelPlaneRegularBasicFactor.cpp", "max_stars_repo_name": "RongzhiW/Kimera-VIO", "max_stars_repo_head_hexsha": "7eff66bfdf02c2d63c5d464959a6b83d213e1082", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-12T19:45:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T19:45:04.000Z", "max_issues_repo_path": "tests/testParallelPlaneRegularBasicFactor.cpp", "max_issues_repo_name": "RongzhiW/Kimera-VIO", "max_issues_repo_head_hexsha": "7eff66bfdf02c2d63c5d464959a6b83d213e1082", "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/testParallelPlaneRegularBasicFactor.cpp", "max_forks_repo_name": "RongzhiW/Kimera-VIO", "max_forks_repo_head_hexsha": "7eff66bfdf02c2d63c5d464959a6b83d213e1082", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T06:00:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-12T06:00:55.000Z", "avg_line_length": 33.8365019011, "max_line_length": 80, "alphanum_fraction": 0.6651309136, "num_tokens": 2421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.540480974235197}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2013   MetaScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_META_NEXT_POWER_OF_2_HPP_INCLUDED\n#define BOOST_SIMD_META_NEXT_POWER_OF_2_HPP_INCLUDED\n\n/*!\n  @file\n  @brief Defines and implements next_power_of_2 and next_power_of_2_c\n**/\n\n#include <cstddef>\n#include <boost/mpl/size_t.hpp>\n#include <boost/mpl/integral_c.hpp>\n\nnamespace boost { namespace simd {  namespace details\n{\n  // Implementation courtesy from :\n  // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2\n  template<std::size_t N> struct next_power_of_2_impl\n  {\n    BOOST_STATIC_CONSTANT(std::size_t, x0    = N-1             );\n    BOOST_STATIC_CONSTANT(std::size_t, x1    = x0 | (x0 >>  1) );\n    BOOST_STATIC_CONSTANT(std::size_t, x2    = x1 | (x1 >>  2) );\n    BOOST_STATIC_CONSTANT(std::size_t, x3    = x2 | (x2 >>  4) );\n    BOOST_STATIC_CONSTANT(std::size_t, x4    = x3 | (x3 >>  8) );\n    BOOST_STATIC_CONSTANT(std::size_t, x5    = x4 | (x4 >> 16) );\n    BOOST_STATIC_CONSTANT(std::size_t, value = x5 + 1          );\n  };\n\n  // Required for MSVC\n  template<> struct next_power_of_2_impl<0>\n  {\n    BOOST_STATIC_CONSTANT(std::size_t, value = 0 );\n  };\n} } }\n\nnamespace boost { namespace simd {  namespace meta\n{\n  /*!\n    @brief Evaluates next power of 2\n\n    Computes the power of two greater or equal to any given integral value @c N.\n\n    @par Semantic:\n    For any given integral value @c N:\n\n    @code\n    typedef next_power_of_2_c<N>::type r;\n    @endcode\n\n    is equivalent to:\n\n    @code\n    typedef mpl::size_t<M> r;\n    @endcode\n\n    Where @c M is greater or equal to N and so that it exists a given @c P so\n    that @c M is equal to 2 at the power of @c P.\n\n    @usage{meta/next_power_of_2_c.cpp}\n\n    @tparam N Integral value to upgrade\n  **/\n  template<std::size_t N> struct  next_power_of_2_c\n#if !defined(DOXYGEN_ONLY)\n        : boost::mpl::size_t<details::next_power_of_2_impl<N>::value>\n#endif\n  {};\n\n  /*!\n    @brief Evaluates next power of 2\n\n    Computes the power of two greater or equal to any given @mplint @c N.\n\n    @par Semantic:\n    For any given @mplint @c N:\n\n    @code\n    typedef next_power_of_2<N>::type r;\n    @endcode\n\n    is equivalent to:\n\n    @code\n    typedef boost::mpl::integral_c< N::value_type\n                                  , next_power_of_2_c<N::value>::value\n                                  > r;\n    @endcode\n\n    @par Models:\n\n    @metafunction\n\n    @usage{meta/next_power_of_2.cpp}\n\n    @tparam N @mplint to downgrade\n  **/\n  template<class N> struct  next_power_of_2\n#if !defined(DOXYGEN_ONLY)\n        : boost::mpl::integral_c< typename N::value_type\n                                , details::next_power_of_2_impl<N::value>::value\n                                >\n#endif\n  {};\n} } }\n\n#endif\n", "meta": {"hexsha": "bc583d8d96bc50859d7c221334b10b811422da28", "size": 3252, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/include/boost/simd/meta/next_power_of_2.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/sdk/include/boost/simd/meta/next_power_of_2.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/boost/simd/sdk/include/boost/simd/meta/next_power_of_2.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 28.2782608696, "max_line_length": 80, "alphanum_fraction": 0.594403444, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5404809674033632}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2018, Ross Hartley <m.ross.hartley@gmail.com>\n * All Rights Reserved\n * See LICENSE for the license information\n * -------------------------------------------------------------------------- */\n\n/**\n *  @file   left_vs_right_error_dynamics.cpp\n *  @author Ross Hartley\n *  @brief  Test to make sure the left and right error dynamics are identical\n *  @date   February 18, 2019\n **/\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <cstdlib>\n#include <Eigen/Dense>\n#include <boost/algorithm/string.hpp>\n#include <vector>\n#include <random>\n#include <chrono>\n#include \"inekf/inekf.hpp\"\n\nusing namespace std;\nusing namespace inekf;\n\nint main() {\n    typedef std::chrono::high_resolution_clock myclock;\n    myclock::time_point beginning = myclock::now();\n\n    //  ---- Initialize invariant extended Kalman filter ----- //\n    RobotState initial_state; \n\n    // Initialize state mean\n    Eigen::Matrix3d R0;\n    Eigen::Vector3d v0, p0, bg0, ba0;\n    R0 << 1, 0, 0, // initial orientation\n          0, -1, 0, // IMU frame is rotated 90deg about the x-axis\n          0, 0, -1;\n    v0 << 1,2,3; // initial velocity\n    p0 << 4,5,6; // initial position\n    bg0 << 0,0,0; // initial gyroscope bias\n    ba0 << 0,0,0; // initial accelerometer bias\n    initial_state.setRotation(R0);\n    initial_state.setVelocity(v0);\n    initial_state.setPosition(p0);\n    initial_state.setGyroscopeBias(bg0);\n    initial_state.setAccelerometerBias(ba0);\n\n    // Initialize noise params\n    NoiseParams noise_params;\n    noise_params.setGyroscopeNoise(0.0);\n    noise_params.setAccelerometerNoise(0.0);\n    noise_params.setGyroscopeBiasNoise(0.0);\n    noise_params.setAccelerometerBiasNoise(0.0);\n    noise_params.setContactNoise(0.0);\n\n    // Initial Covariance and Adjoint\n    Eigen::Matrix<double,15,15> P = Eigen::Matrix<double,15,15>::Identity();\n    Eigen::MatrixXd Adj = Eigen::MatrixXd::Identity(initial_state.dimP(),initial_state.dimP());\n    Adj.block(0,0,initial_state.dimP()-initial_state.dimTheta(),initial_state.dimP()-initial_state.dimTheta()) = Adjoint_SEK3(initial_state.getX()); \n    \n    // Left invariant filter\n    initial_state.setP(P);\n    InEKF LI_filter(initial_state, noise_params, ErrorType::LeftInvariant);\n\n    // Right invariant filter\n    initial_state.setP(Adj*P*Adj.transpose());\n    InEKF RI_filter(initial_state, noise_params, ErrorType::RightInvariant);\n\n    // obtain a seed from the timer\n    myclock::duration d = myclock::now() - beginning;\n    unsigned seed = d.count();\n    std::default_random_engine generator(seed);\n    std::normal_distribution<double> distribution(0,1);\n\n    // ----- Propagate using random data ------\n    cout << \"\\n\\n ------ Propagate using random data -------\\n\\n\";\n    const int NUM_PROPAGATE = 100;\n    Eigen::Matrix<double,6,1> imu;\n    for (int i=0; i<NUM_PROPAGATE; ++i) {\n        for (int j=0; j<6; ++j) {\n            imu(j) = distribution(generator);\n        }\n        double dt = distribution(generator);\n        LI_filter.Propagate(imu, dt); \n        RI_filter.Propagate(imu, dt); \n    }\n    \n    // Print covariances\n    RobotState LI_state = LI_filter.getState();\n    RobotState RI_state = RI_filter.getState();\n    cout << \"Left Invariant State: \\n\" << LI_state << endl;\n    cout << \"Right Invariant State: \\n\" << RI_state << endl;\n    cout << \"Left Invariant Covariance: \\n\" << LI_state.getP() << endl << endl;\n    cout << \"Right Invariant Covariance: \\n\" << RI_state.getP() << endl << endl;\n    Adj = Eigen::MatrixXd::Identity(LI_state.dimP(),LI_state.dimP());\n    Adj.block(0,0,LI_state.dimP()-LI_state.dimTheta(),LI_state.dimP()-LI_state.dimTheta()) = Adjoint_SEK3(LI_state.getX()); \n    cout << \"Difference between right invariant covariance (left is mapped using adjoint): \\n\" << (RI_state.getP() - (Adj * LI_state.getP() * Adj.transpose()).eval()).norm() << endl << endl;\n    Eigen::MatrixXd AdjInv = Eigen::MatrixXd::Identity(RI_state.dimP(),RI_state.dimP());\n    AdjInv.block(0,0,RI_state.dimP()-RI_state.dimTheta(),RI_state.dimP()-RI_state.dimTheta()) = Adjoint_SEK3(RI_state.calcXinv()); \n    cout << \"Difference between left invariant covariance (right is mapped using adjoint inverse): \\n\" << (LI_state.getP() - (AdjInv * RI_state.getP() * AdjInv.transpose()).eval()).norm() << endl << endl;\n    cout << \"Difference between state estimates: \\n\" << (LI_state.getX() - RI_state.getX()).norm() << endl << endl;\n\n    // ----- Correct using random data ------\n    cout << \"\\n\\n ------ Correct using random data -------\\n\\n\";\n    // Set filter's contact state\n    vector<pair<int,bool> > contacts;\n    contacts.push_back(pair<int,bool> (0, true));\n    contacts.push_back(pair<int,bool> (1, true));\n    LI_filter.setContacts(contacts);\n    RI_filter.setContacts(contacts);\n\n    // Correct state using kinematic measurements\n    const int NUM_CORRECT = 10;\n    for (int i=0; i<NUM_CORRECT; ++i) {\n        vectorKinematics measured_kinematics;\n        Eigen::Matrix4d pose = Eigen::Matrix4d::Identity();\n        Eigen::Vector3d p = Eigen::Vector3d::Zero();\n        Eigen::Matrix<double,6,6> covariance = Eigen::Matrix<double,6,6>::Identity();\n        p <<  distribution(generator), distribution(generator), distribution(generator);\n        pose.block<3,1>(0,3) = p;\n        measured_kinematics.push_back(Kinematics(0, pose, covariance));\n        p <<  distribution(generator), distribution(generator), distribution(generator);\n        pose.block<3,1>(0,3) = p;\n        measured_kinematics.push_back(Kinematics(1, pose, covariance));\n        LI_filter.CorrectKinematics(measured_kinematics);\n        RI_filter.CorrectKinematics(measured_kinematics);\n    }\n\n    // Print covariances\n    LI_state = LI_filter.getState();\n    RI_state = RI_filter.getState();\n    cout << \"Left Invariant State: \\n\" << LI_state << endl;\n    cout << \"Right Invariant State: \\n\" << RI_state << endl;\n    cout << \"Left Invariant Covariance: \\n\" << LI_state.getP() << endl << endl;\n    cout << \"Right Invariant Covariance: \\n\" << RI_state.getP() << endl << endl;\n    Adj = Eigen::MatrixXd::Identity(LI_state.dimP(),LI_state.dimP());\n    Adj.block(0,0,LI_state.dimP()-LI_state.dimTheta(),LI_state.dimP()-LI_state.dimTheta()) = Adjoint_SEK3(LI_state.getX()); \n    cout << \"Difference between right invariant covariance (left is mapped using adjoint): \\n\" << (RI_state.getP() - (Adj * LI_state.getP() * Adj.transpose()).eval()).norm() << endl << endl;\n    AdjInv = Eigen::MatrixXd::Identity(RI_state.dimP(),RI_state.dimP());\n    AdjInv.block(0,0,RI_state.dimP()-RI_state.dimTheta(),RI_state.dimP()-RI_state.dimTheta()) = Adjoint_SEK3(RI_state.calcXinv()); \n    cout << \"Difference between left invariant covariance (right is mapped using adjoint inverse): \\n\" << (LI_state.getP() - (AdjInv * RI_state.getP() * AdjInv.transpose()).eval()).norm() << endl << endl;\n    cout << \"Difference between state estimates: \\n\" << (LI_state.getX() - RI_state.getX()).norm() << endl << endl;\n\n\n    return 0;\n}\n", "meta": {"hexsha": "bfdb3eb6bb9b5ec54a050417bd7657f4239a529c", "size": 7030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/left_vs_right_error_dynamics.cpp", "max_stars_repo_name": "mayataka/invariant-ekf", "max_stars_repo_head_hexsha": "775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T12:38:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T12:38:09.000Z", "max_issues_repo_path": "tests/left_vs_right_error_dynamics.cpp", "max_issues_repo_name": "mayataka/inekf", "max_issues_repo_head_hexsha": "775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/left_vs_right_error_dynamics.cpp", "max_forks_repo_name": "mayataka/inekf", "max_forks_repo_head_hexsha": "775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0", "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.8666666667, "max_line_length": 204, "alphanum_fraction": 0.6512091038, "num_tokens": 1831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5403940451379352}}
{"text": "\r\n//\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_TriMeshEdgeCollapse.h\"\r\n\r\n#include <vector>\r\n\r\n#pragma warning(push, 0)\r\n#include <igl/remove_unreferenced.h>\r\n#include <igl/edge_flaps.h>\r\n#include <igl/collapse_edge.h>\r\n#include <igl/is_edge_manifold.h>\r\n#include <igl/is_vertex_manifold.h>\r\n#include <igl/is_boundary_edge.h>\r\n#include <igl/is_border_vertex.h>\r\n#pragma warning(pop)\r\n\r\n#include <Eigen/Core>\r\n\r\n#include \"TriMesh.h\"\r\n#include \"ConversionUtilities.h\"\r\n\r\nusing Urho3D::Variant;\r\n\r\nnamespace {\r\n\r\nvoid collapse_edges_below_length(\r\n\tconst Eigen::MatrixXd& OV,\r\n\tconst Eigen::MatrixXi& OF,\r\n\tEigen::MatrixXd& NV,\r\n\tEigen::MatrixXi& NF,\r\n\tdouble L\r\n)\r\n{\r\n\tEigen::MatrixXd V = OV;\r\n\tEigen::MatrixXi F = OF;\r\n\r\n\t// Prepare array-based edge data structures\r\n\tEigen::VectorXi EMAP;\r\n\tEigen::MatrixXi E, EF, EI;\r\n\tigl::edge_flaps(F, E, EMAP, EF, EI);\r\n\r\n\tEigen::VectorXi B;\r\n\tstd::vector<bool> border_vertices = igl::is_border_vertex(V, F);\r\n\tassert(border_vertices.size() == V.rows());\r\n\r\n\tEigen::RowVector3d mid;\r\n\tdouble len;\r\n\tbool b;\r\n\r\n\tint numc = -1;\r\n\twhile (numc != 0) {\r\n\t\tnumc = 0;\r\n\t\tfor (int e = 0; e < E.rows(); ++e) {\r\n\r\n\t\t\tbool edge_totally_inside = false;\r\n\t\t\tif (\r\n\t\t\t\tborder_vertices[E(e, 0)] == false &&\r\n\t\t\t\tborder_vertices[E(e, 1)] == false\r\n\t\t\t\t)\r\n\t\t\t{\r\n\t\t\t\tedge_totally_inside = true;\r\n\t\t\t}\r\n\r\n\t\t\tlen = (V.row(E(e, 0)) - V.row(E(e, 1))).norm();\r\n\t\t\tif (len < L && edge_totally_inside) {\r\n\t\t\t\tmid = 0.5 * (V.row(E(e, 0)) + V.row(E(e, 1)));\r\n\t\t\t\tb = igl::collapse_edge(e, mid, V, F, E, EMAP, EF, EI);\r\n\t\t\t\tif (b) {\r\n\t\t\t\t\t++numc;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tEigen::VectorXi _1;\r\n\tigl::remove_unreferenced(V, F, NV, NF, _1);\r\n\r\n\tstd::vector<int> facePatch;\r\n\tfor (int i = 0; i < NF.rows(); ++i) {\r\n\t\tif ((NF(i, 0) == 0) && (NF(i, 1) == 0) && (NF(i, 2) == 0)) {\r\n\t\t}\r\n\t\telse {\r\n\t\t\tfacePatch.push_back(NF(i, 0));\r\n\t\t\tfacePatch.push_back(NF(i, 1));\r\n\t\t\tfacePatch.push_back(NF(i, 2));\r\n\t\t}\r\n\t}\r\n\tEigen::MatrixXi NF2(facePatch.size() / 3, 3);\r\n\tfor (int i = 0; i < facePatch.size() / 3; ++i) {\r\n\t\tNF2(i, 0) = facePatch[3 * i];\r\n\t\tNF2(i, 1) = facePatch[3 * i + 1];\r\n\t\tNF2(i, 2) = facePatch[3 * i + 2];\r\n\t}\r\n\tNF.setZero(NF2.rows(), 3);\r\n\tNF = NF2;\r\n}\r\n\r\n} // namespace\r\n\r\nUrho3D::Variant Geomlib::TriMesh_CollapseShortEdges(\r\n\tconst Urho3D::Variant& tri_mesh,\r\n\tfloat collapse_threshold\r\n)\r\n{\r\n\tif (!TriMesh_Verify(tri_mesh)) {\r\n\t\treturn Variant();\r\n\t}\r\n\r\n\tEigen::MatrixXf V;\r\n\tEigen::MatrixXi F;\r\n\tIglMeshToMatrices(tri_mesh, V, F);\r\n\r\n\tif (!igl::is_edge_manifold(F)) {\r\n\t\treturn Variant();\r\n\t}\r\n\r\n\tEigen::VectorXi B;\r\n\tif (!igl::is_vertex_manifold(F, B)) {\r\n\t\treturn Variant();\r\n\t}\r\n\r\n\t// Convert from float to double\r\n\tEigen::MatrixXd V_d = IglFloatToDouble(V);\r\n\r\n\r\n\tEigen::MatrixXd NV_d;\r\n\tEigen::MatrixXi NF;\r\n\tcollapse_edges_below_length(V_d, F, NV_d, NF, collapse_threshold);\r\n\r\n\tEigen::MatrixXf NV = IglDoubleToFloat(NV_d);\r\n\r\n\treturn TriMesh_Make(NV, NF);\r\n}", "meta": {"hexsha": "c0c765c1f562e55b388fd1f5e5393ef0bffbcd71", "size": 4010, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry/Geomlib_TriMeshEdgeCollapse.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_TriMeshEdgeCollapse.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_TriMeshEdgeCollapse.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.038961039, "max_line_length": 81, "alphanum_fraction": 0.646882793, "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5403940437229099}}
{"text": "/*\nLICENSE: see isogeometric_application/LICENSE.txt\n*/\n\n//\n//   Project Name:        Kratos\n//   Last modified by:    $Author: hbui $\n//   Date:                $Date: Nov 24, 2017 $\n//   Revision:            $Revision: 1.0 $\n//\n//\n\n\n// System includes\n#include <string>\n\n// External includes\n#include <boost/foreach.hpp>\n#include <boost/python.hpp>\n#include <boost/python/stl_iterator.hpp>\n#include <boost/python/operators.hpp>\n\n// Project includes\n#include \"includes/define.h\"\n#include \"python/pointer_vector_set_python_interface.h\"\n#include \"custom_utilities/patch.h\"\n#include \"custom_utilities/multipatch.h\"\n#include \"custom_utilities/tsplines/tcell.h\"\n#include \"custom_utilities/nurbs/pbbsplines_basis_function.h\"\n#include \"custom_utilities/nurbs/pbbsplines_fespace.h\"\n#include \"custom_utilities/import_export/multi_pbbsplines_patch_matlab_exporter.h\"\n#include \"custom_python/iga_define_python.h\"\n#include \"custom_python/add_pbbsplines_to_python.h\"\n#include \"custom_python/add_point_based_control_grid_to_python.h\"\n#include \"custom_python/add_import_export_to_python.h\"\n\n\nnamespace Kratos\n{\n\nnamespace Python\n{\n\nusing namespace boost::python;\n\ntemplate<int TDim>\nvoid IsogeometricApplication_AddPBBSplinesSpaceToPython()\n{\n\n    std::stringstream ss;\n\n    ss.str(std::string());\n    ss << \"PBBSplinesBasisFunction\" << TDim << \"D\";\n    typedef PBBSplinesBasisFunction<TDim, TCell> PBBSplinesBasisFunctionType;\n    class_<PBBSplinesBasisFunctionType, typename PBBSplinesBasisFunctionType::Pointer, boost::noncopyable>\n    (ss.str().c_str(), init<const std::size_t&>())\n    .add_property(\"Id\", Isogeometric_GetId<PBBSplinesBasisFunctionType>, Isogeometric_DoNotSetId<PBBSplinesBasisFunctionType>)\n    .add_property(\"EquationId\", Isogeometric_GetEquationId<PBBSplinesBasisFunctionType>, Isogeometric_SetEquationId<PBBSplinesBasisFunctionType>)\n    .def(\"Weight\", &PBBSplinesBasisFunctionType::Weight)\n    .def(self_ns::str(self))\n    ;\n\n    ss.str(std::string());\n    ss << \"PBBSplinesFESpace\" << TDim << \"D\";\n    typedef FESpace<TDim> FESpaceType;\n    typedef PBBSplinesFESpace<TDim, PBBSplinesBasisFunctionType, BCellManager<TDim, typename PBBSplinesBasisFunctionType::CellType> > PBBSplinesFESpaceType;\n    class_<PBBSplinesFESpaceType, typename PBBSplinesFESpaceType::Pointer, bases<FESpaceType>, boost::noncopyable>\n    (ss.str().c_str(), init<>())\n    .def(\"__getitem__\", &FESpace_GetItem<PBBSplinesFESpaceType>)\n    .def(\"UpdateCells\", &PBBSplinesFESpaceType::UpdateCells)\n    .def(self_ns::str(self))\n    ;\n\n    IsogeometricApplication_AddPointBasedControlGrid_Helper<Variable<double>, PBBSplinesFESpaceType>::Execute();\n    IsogeometricApplication_AddPointBasedControlGrid_Helper<Variable<array_1d<double, 3> >, PBBSplinesFESpaceType>::Execute();\n    IsogeometricApplication_AddPointBasedControlGrid_Helper<Variable<Vector>, PBBSplinesFESpaceType>::Execute();\n\n}\n\n////////////////////////////////////////\n\nvoid IsogeometricApplication_AddPBBSplinesToPython()\n{\n\n    /////////////////////////////////////////////////////////////////\n    ///////////////////////Point-based BSplines//////////////////////\n    /////////////////////////////////////////////////////////////////\n\n    IsogeometricApplication_AddPBBSplinesSpaceToPython<1>();\n    IsogeometricApplication_AddPBBSplinesSpaceToPython<2>();\n    IsogeometricApplication_AddPBBSplinesSpaceToPython<3>();\n\n    class_<MultiPBBSplinesPatchMatlabExporter, MultiPBBSplinesPatchMatlabExporter::Pointer, boost::noncopyable>\n    (\"MultiPBBSplinesPatchMatlabExporter\", init<>())\n    .def(\"Export\", &MultiPatchExporter_Export<1, MultiPBBSplinesPatchMatlabExporter, Patch<1> >)\n    .def(\"Export\", &MultiPatchExporter_Export<2, MultiPBBSplinesPatchMatlabExporter, Patch<2> >)\n    .def(\"Export\", &MultiPatchExporter_Export<3, MultiPBBSplinesPatchMatlabExporter, Patch<3> >)\n    .def(\"Export\", &MultiPatchExporter_Export<1, MultiPBBSplinesPatchMatlabExporter, MultiPatch<1> >)\n    .def(\"Export\", &MultiPatchExporter_Export<2, MultiPBBSplinesPatchMatlabExporter, MultiPatch<2> >)\n    .def(\"Export\", &MultiPatchExporter_Export<3, MultiPBBSplinesPatchMatlabExporter, MultiPatch<3> >)\n    .def(self_ns::str(self))\n    ;\n\n}\n\n}  // namespace Python.\n\n} // Namespace Kratos\n\n", "meta": {"hexsha": "10baa88376234f332276608b7cc66f8b910d90b5", "size": 4215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "custom_python/add_pbbsplines_to_python.cpp", "max_stars_repo_name": "rwilliams01/isogeometric_application", "max_stars_repo_head_hexsha": "e505061603b56b4f426220946da5ec551dc6c142", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "custom_python/add_pbbsplines_to_python.cpp", "max_issues_repo_name": "rwilliams01/isogeometric_application", "max_issues_repo_head_hexsha": "e505061603b56b4f426220946da5ec551dc6c142", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "custom_python/add_pbbsplines_to_python.cpp", "max_forks_repo_name": "rwilliams01/isogeometric_application", "max_forks_repo_head_hexsha": "e505061603b56b4f426220946da5ec551dc6c142", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-25T08:31:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T08:31:06.000Z", "avg_line_length": 38.3181818182, "max_line_length": 156, "alphanum_fraction": 0.7302491103, "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581049086031, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5403940366801834}}
{"text": "/**\n * \\file      miscellaneous-algorithms.hpp\n * \\author    Mehdi Benallegue\n * \\date       2013\n * \\brief      Gathers many kinds of algorithms\n *\n *\n *\n */\n\n#ifndef STATEOBSERVATIONTOOLSMISCELANEOUSALGORITHMS\n#define STATEOBSERVATIONTOOLSMISCELANEOUSALGORITHMS\n#include <boost/utility.hpp>\n#include <cmath>\n\n#include <state-observation/api.h>\n#include <state-observation/tools/definitions.hpp>\n\nnamespace stateObservation\n{\nnamespace tools\n{\n\n/// computes the square of a value of any type\ntemplate<class T>\ninline T square(const T & x)\n{\n  return T(x * x);\n}\n\n/// derivates any type with finite differences\ntemplate<class T>\ninline T derivate(const T & o1, const T & o2, double dt)\n{\n  T o(o2 - o1);\n  return o * (1 / dt);\n}\n\n/// gives the sign of a variable (1, 0 or -1)\ntemplate<typename T>\ninline int signum(T x)\n{\n  return (T(0) < x) - (x < T(0));\n}\n\ntemplate<typename T>\ninline std::string toString(T val)\n{\n  std::stringstream ss(\"\");\n  ss << val;\n  return ss.str();\n}\n\n/// @brief checks if the vector is already normalized or not\n///\n/// @param v                  the vector to normalize\n/// @return true              the vector is normalized\n/// @return false             The vector is not normalized\ninline bool checkIfNormalized(const Vector3 & v)\n{\n  if(fabs(v.squaredNorm() - 1) > cst::epsilon1)\n  {\n    return false;\n  }\n  else\n  {\n    return true;\n  }\n}\n\n/// @brief checks if the vector is already normalized or not\n///\n/// @param v                  the vector to normalize\n/// @param outputSquaredNorm  the squared norm as an output\n/// @return true              the vector is normalized\n/// @return false             The vector is not normalized\ninline bool checkIfNormalized(const Vector3 & v, double & outputSquaredNorm)\n{\n  outputSquaredNorm = v.squaredNorm();\n  if(fabs(outputSquaredNorm - 1) > cst::epsilon1)\n  {\n    return false;\n  }\n  else\n  {\n    return true;\n  }\n}\n\n/// @brief returns the value clamped between min and max\n///\n/// @tparam T The type of the scalar\n/// @param x the input value\n/// @param max the max value\n/// @param min the min value\n/// @return T the calmped value\ntemplate<typename T>\ninline T clampScalar(const T & x, const T & max, const T & min)\n{\n  if(x > max)\n  {\n    return max;\n  }\n  else\n  {\n    if(x < min)\n    {\n      return min;\n    }\n    else\n    {\n      return x;\n    }\n  }\n}\n\n/// @brief returns the value clamped between limit and -limit\n///\n/// @tparam T The type of the scalar\n/// @param x the input value\n/// @param limit is the maximum absolute value allowed, has to be positive\n/// @return T the clamped value\ntemplate<typename T>\ninline T clampScalar(const T & x, const T & limit)\n{\n  return clampScalar(x, limit, -limit);\n}\n\n/// @brief normalize the vector only if it is not normalized already. Useful if the vector is likely to be normalized\n///\n/// @param v the input vector\n/// @return Vector3\ninline Vector3 normalizedLazy(const Vector3 & v)\n{\n  double squaredNorm;\n  if(checkIfNormalized(v, squaredNorm))\n  {\n    return v;\n  }\n  else\n  {\n    return v / sqrt(squaredNorm);\n  }\n}\n\n/// provides an acceleration giving a finite time convergence to zero\n/// the state is the position x and the derivative xd and the output is the\n/// acceleration. The gains kp, kv must be negative\ninline double STATE_OBSERVATION_DLLAPI finiteTimeAccControl(double x, double xd, double kp = -1, double kv = -1)\n{\n  double sax = sqrt(fabs(x));\n  double xdr = kp * signum(x) * sax;\n  double y = xd - xdr;\n  double ydr = -kv * signum(y) * sqrt(fabs(y));\n  return ydr - kp * xd / (2 * sax);\n}\n\n/// sqme as the scalar version but for every member of the vector\ninline Vector STATE_OBSERVATION_DLLAPI finiteTimeAccControl(const Vector & x,\n                                                            const Vector & xd,\n                                                            double kp = -1,\n                                                            double kv = -1)\n{\n  Vector xdd(x.size());\n  for(Index i = 1; i < x.size(); ++i)\n  {\n    xdd(i) = finiteTimeAccControl(x(i), xd(i), kp, kv);\n  }\n  return xdd;\n}\n\nnamespace Detail\n{\ndouble constexpr sqrtNewtonRaphson(double x, double curr, double prev)\n{\n  return curr == prev ? curr : sqrtNewtonRaphson(x, 0.5 * (curr + x / curr), curr);\n}\n} // namespace Detail\n\n/// @brief Constexpr version of the square root\n/// @details For a finite and non-negative value of \"x\", returns an approximation for the square root of \"x\"\n///-Otherwise, returns NaN\n///\n/// @param x\n/// @return double constexpr\ndouble constexpr sqrt(double x)\n{\n  return x >= 0 && x < std::numeric_limits<double>::infinity() ? Detail::sqrtNewtonRaphson(x, x, 0)\n                                                               : std::numeric_limits<double>::quiet_NaN();\n}\n\n} // namespace tools\n\n} // namespace stateObservation\n\n#endif // STATEOBSERVATIONTOOLSMISCELANEOUSALGORITHMS\n", "meta": {"hexsha": "809bbd7c8ea1b900d4e5aa1fddfaa253e004d965", "size": 4847, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/state-observation/tools/miscellaneous-algorithms.hpp", "max_stars_repo_name": "mmurooka/state-observation", "max_stars_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-11-01T16:10:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T00:03:46.000Z", "max_issues_repo_path": "include/state-observation/tools/miscellaneous-algorithms.hpp", "max_issues_repo_name": "mmurooka/state-observation", "max_issues_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-10-18T09:06:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T04:22:09.000Z", "max_forks_repo_path": "include/state-observation/tools/miscellaneous-algorithms.hpp", "max_forks_repo_name": "mmurooka/state-observation", "max_forks_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-06-19T09:00:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T06:14:51.000Z", "avg_line_length": 24.6040609137, "max_line_length": 117, "alphanum_fraction": 0.6300804621, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5403920231785873}}
{"text": "// ----------------------------------------------------------------------------\n// -                        Open3D: www.open3d.org                            -\n// ----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2018 www.open3d.org\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\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n// ----------------------------------------------------------------------------\n\n#include \"open3d/utility/Eigen.h\"\n\n#include <Eigen/Geometry>\n#include <Eigen/Sparse>\n\n#include \"open3d/utility/Console.h\"\n\nnamespace open3d {\nnamespace utility {\n\n/// Function to solve Ax=b\nstd::tuple<bool, Eigen::VectorXd> SolveLinearSystemPSD(\n        const Eigen::MatrixXd &A,\n        const Eigen::VectorXd &b,\n        bool prefer_sparse /* = false */,\n        bool check_symmetric /* = false */,\n        bool check_det /* = false */,\n        bool check_psd /* = false */) {\n    // PSD implies symmetric\n    check_symmetric = check_symmetric || check_psd;\n    if (check_symmetric && !A.isApprox(A.transpose())) {\n        LogWarning(\"check_symmetric failed, empty vector will be returned\");\n        return std::make_tuple(false, Eigen::VectorXd::Zero(b.rows()));\n    }\n\n    if (check_det) {\n        double det = A.determinant();\n        if (fabs(det) < 1e-6 || std::isnan(det) || std::isinf(det)) {\n            LogWarning(\"check_det failed, empty vector will be returned\");\n            return std::make_tuple(false, Eigen::VectorXd::Zero(b.rows()));\n        }\n    }\n\n    // Check PSD: https://stackoverflow.com/a/54569657/1255535\n    if (check_psd) {\n        Eigen::LLT<Eigen::MatrixXd> A_llt(A);\n        if (A_llt.info() == Eigen::NumericalIssue) {\n            LogWarning(\"check_psd failed, empty vector will be returned\");\n            return std::make_tuple(false, Eigen::VectorXd::Zero(b.rows()));\n        }\n    }\n\n    Eigen::VectorXd x(b.size());\n\n    if (prefer_sparse) {\n        Eigen::SparseMatrix<double> A_sparse = A.sparseView();\n        // TODO: avoid deprecated API SimplicialCholesky\n        Eigen::SimplicialCholesky<Eigen::SparseMatrix<double>> A_chol;\n        A_chol.compute(A_sparse);\n        if (A_chol.info() == Eigen::Success) {\n            x = A_chol.solve(b);\n            if (A_chol.info() == Eigen::Success) {\n                // Both decompose and solve are successful\n                return std::make_tuple(true, std::move(x));\n            } else {\n                LogWarning(\"Cholesky solve failed, switched to dense solver\");\n            }\n        } else {\n            LogWarning(\"Cholesky decompose failed, switched to dense solver\");\n        }\n    }\n\n    x = A.ldlt().solve(b);\n    return std::make_tuple(true, std::move(x));\n}\n\nEigen::Matrix4d TransformVector6dToMatrix4d(const Eigen::Vector6d &input) {\n    Eigen::Matrix4d output;\n    output.setIdentity();\n    output.block<3, 3>(0, 0) =\n            (Eigen::AngleAxisd(input(2), Eigen::Vector3d::UnitZ()) *\n             Eigen::AngleAxisd(input(1), Eigen::Vector3d::UnitY()) *\n             Eigen::AngleAxisd(input(0), Eigen::Vector3d::UnitX()))\n                    .matrix();\n    output.block<3, 1>(0, 3) = input.block<3, 1>(3, 0);\n    return output;\n}\n\nEigen::Vector6d TransformMatrix4dToVector6d(const Eigen::Matrix4d &input) {\n    Eigen::Vector6d output;\n    Eigen::Matrix3d R = input.block<3, 3>(0, 0);\n    double sy = sqrt(R(0, 0) * R(0, 0) + R(1, 0) * R(1, 0));\n    if (!(sy < 1e-6)) {\n        output(0) = atan2(R(2, 1), R(2, 2));\n        output(1) = atan2(-R(2, 0), sy);\n        output(2) = atan2(R(1, 0), R(0, 0));\n    } else {\n        output(0) = atan2(-R(1, 2), R(1, 1));\n        output(1) = atan2(-R(2, 0), sy);\n        output(2) = 0;\n    }\n    output.block<3, 1>(3, 0) = input.block<3, 1>(0, 3);\n    return output;\n}\n\nstd::tuple<bool, Eigen::Matrix4d> SolveJacobianSystemAndObtainExtrinsicMatrix(\n        const Eigen::Matrix6d &JTJ, const Eigen::Vector6d &JTr) {\n    bool solution_exist;\n    Eigen::Vector6d x;\n    std::tie(solution_exist, x) = SolveLinearSystemPSD(JTJ, -JTr);\n\n    if (solution_exist) {\n        Eigen::Matrix4d extrinsic = TransformVector6dToMatrix4d(x);\n        return std::make_tuple(solution_exist, std::move(extrinsic));\n    }\n    return std::make_tuple(false, Eigen::Matrix4d::Identity());\n}\n\nstd::tuple<bool, std::vector<Eigen::Matrix4d, Matrix4d_allocator>>\nSolveJacobianSystemAndObtainExtrinsicMatrixArray(const Eigen::MatrixXd &JTJ,\n                                                 const Eigen::VectorXd &JTr) {\n    std::vector<Eigen::Matrix4d, Matrix4d_allocator> output_matrix_array;\n    output_matrix_array.clear();\n    if (JTJ.rows() != JTr.rows() || JTJ.cols() % 6 != 0) {\n        LogWarning(\n                \"[SolveJacobianSystemAndObtainExtrinsicMatrixArray] \"\n                \"Unsupported matrix format.\");\n        return std::make_tuple(false, std::move(output_matrix_array));\n    }\n\n    bool solution_exist;\n    Eigen::VectorXd x;\n    std::tie(solution_exist, x) = SolveLinearSystemPSD(JTJ, -JTr);\n\n    if (solution_exist) {\n        int nposes = (int)x.rows() / 6;\n        for (int i = 0; i < nposes; i++) {\n            Eigen::Matrix4d extrinsic =\n                    TransformVector6dToMatrix4d(x.block<6, 1>(i * 6, 0));\n            output_matrix_array.push_back(extrinsic);\n        }\n        return std::make_tuple(solution_exist, std::move(output_matrix_array));\n    } else {\n        return std::make_tuple(false, std::move(output_matrix_array));\n    }\n}\n\ntemplate <typename MatType, typename VecType>\nstd::tuple<MatType, VecType, double> ComputeJTJandJTr(\n        std::function<void(int, VecType &, double &, double &)> f,\n        int iteration_num,\n        bool verbose /*=true*/) {\n    MatType JTJ;\n    VecType JTr;\n    double r2_sum = 0.0;\n    JTJ.setZero();\n    JTr.setZero();\n#pragma omp parallel\n    {\n        MatType JTJ_private;\n        VecType JTr_private;\n        double r2_sum_private = 0.0;\n        JTJ_private.setZero();\n        JTr_private.setZero();\n        VecType J_r;\n        double r;\n        double w = 0.0;\n#pragma omp for nowait\n        for (int i = 0; i < iteration_num; i++) {\n            f(i, J_r, r, w);\n            JTJ_private.noalias() += J_r * w * J_r.transpose();\n            JTr_private.noalias() += J_r * w * r;\n            r2_sum_private += r * r;\n        }\n#pragma omp critical\n        {\n            JTJ += JTJ_private;\n            JTr += JTr_private;\n            r2_sum += r2_sum_private;\n        }\n    }\n    if (verbose) {\n        LogDebug(\"Residual : {:.2e} (# of elements : {:d})\",\n                 r2_sum / (double)iteration_num, iteration_num);\n    }\n    return std::make_tuple(std::move(JTJ), std::move(JTr), r2_sum);\n}\n\ntemplate <typename MatType, typename VecType>\nstd::tuple<MatType, VecType, double> ComputeJTJandJTr(\n        std::function<\n                void(int,\n                     std::vector<VecType, Eigen::aligned_allocator<VecType>> &,\n                     std::vector<double> &)> f,\n        int iteration_num,\n        bool verbose /*=true*/) {\n    MatType JTJ;\n    VecType JTr;\n    double r2_sum = 0.0;\n    JTJ.setZero();\n    JTr.setZero();\n#pragma omp parallel\n    {\n        MatType JTJ_private;\n        VecType JTr_private;\n        double r2_sum_private = 0.0;\n        JTJ_private.setZero();\n        JTr_private.setZero();\n        std::vector<double> r;\n        std::vector<VecType, Eigen::aligned_allocator<VecType>> J_r;\n#pragma omp for nowait\n        for (int i = 0; i < iteration_num; i++) {\n            f(i, J_r, r);\n            for (int j = 0; j < (int)r.size(); j++) {\n                JTJ_private.noalias() += J_r[j] * J_r[j].transpose();\n                JTr_private.noalias() += J_r[j] * r[j];\n                r2_sum_private += r[j] * r[j];\n            }\n        }\n#pragma omp critical\n        {\n            JTJ += JTJ_private;\n            JTr += JTr_private;\n            r2_sum += r2_sum_private;\n        }\n    }\n    if (verbose) {\n        LogDebug(\"Residual : {:.2e} (# of elements : {:d})\",\n                 r2_sum / (double)iteration_num, iteration_num);\n    }\n    return std::make_tuple(std::move(JTJ), std::move(JTr), r2_sum);\n}\n\n// clang-format off\ntemplate std::tuple<Eigen::Matrix6d, Eigen::Vector6d, double> ComputeJTJandJTr(\n        std::function<void(int, Eigen::Vector6d &, double &, double &)> f,\n        int iteration_num, bool verbose);\n\ntemplate std::tuple<Eigen::Matrix6d, Eigen::Vector6d, double> ComputeJTJandJTr(\n        std::function<void(int,\n                           std::vector<Eigen::Vector6d, Vector6d_allocator> &,\n                           std::vector<double> &)> f,\n        int iteration_num, bool verbose);\n// clang-format on\n\nEigen::Matrix3d RotationMatrixX(double radians) {\n    Eigen::Matrix3d rot;\n    rot << 1, 0, 0, 0, std::cos(radians), -std::sin(radians), 0,\n            std::sin(radians), std::cos(radians);\n    return rot;\n}\n\nEigen::Matrix3d RotationMatrixY(double radians) {\n    Eigen::Matrix3d rot;\n    rot << std::cos(radians), 0, std::sin(radians), 0, 1, 0, -std::sin(radians),\n            0, std::cos(radians);\n    return rot;\n}\n\nEigen::Matrix3d RotationMatrixZ(double radians) {\n    Eigen::Matrix3d rot;\n    rot << std::cos(radians), -std::sin(radians), 0, std::sin(radians),\n            std::cos(radians), 0, 0, 0, 1;\n    return rot;\n}\n\nEigen::Vector3uint8 ColorToUint8(const Eigen::Vector3d &color) {\n    Eigen::Vector3uint8 rgb;\n    for (int i = 0; i < 3; ++i) {\n        rgb[i] = uint8_t(\n                std::round(std::min(1., std::max(0., color(i))) * 255.));\n    }\n    return rgb;\n}\n\nEigen::Vector3d ColorToDouble(uint8_t r, uint8_t g, uint8_t b) {\n    return Eigen::Vector3d(r, g, b) / 255.0;\n}\n\nEigen::Vector3d ColorToDouble(const Eigen::Vector3uint8 &rgb) {\n    return ColorToDouble(rgb(0), rgb(1), rgb(2));\n}\n\ntemplate <typename IdxType>\nEigen::Matrix3d ComputeCovariance(const std::vector<Eigen::Vector3d> &points,\n                                  const std::vector<IdxType> &indices) {\n    Eigen::Matrix3d covariance;\n    Eigen::Matrix<double, 9, 1> cumulants;\n    cumulants.setZero();\n    for (const auto &idx : indices) {\n        const Eigen::Vector3d &point = points[idx];\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    cumulants /= (double)indices.size();\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\ntemplate <typename IdxType>\nstd::tuple<Eigen::Vector3d, Eigen::Matrix3d> ComputeMeanAndCovariance(\n        const std::vector<Eigen::Vector3d> &points,\n        const std::vector<IdxType> &indices) {\n    Eigen::Vector3d mean;\n    Eigen::Matrix3d covariance;\n    Eigen::Matrix<double, 9, 1> cumulants;\n    cumulants.setZero();\n    for (const auto &idx : indices) {\n        const Eigen::Vector3d &point = points[idx];\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    cumulants /= (double)indices.size();\n    mean(0) = cumulants(0);\n    mean(1) = cumulants(1);\n    mean(2) = cumulants(2);\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 std::make_tuple(mean, covariance);\n}\n\ntemplate Eigen::Matrix3d ComputeCovariance(\n        const std::vector<Eigen::Vector3d> &points,\n        const std::vector<size_t> &indices);\ntemplate std::tuple<Eigen::Vector3d, Eigen::Matrix3d> ComputeMeanAndCovariance(\n        const std::vector<Eigen::Vector3d> &points,\n        const std::vector<size_t> &indices);\ntemplate Eigen::Matrix3d ComputeCovariance(\n        const std::vector<Eigen::Vector3d> &points,\n        const std::vector<int> &indices);\ntemplate std::tuple<Eigen::Vector3d, Eigen::Matrix3d> ComputeMeanAndCovariance(\n        const std::vector<Eigen::Vector3d> &points,\n        const std::vector<int> &indices);\n}  // namespace utility\n}  // namespace open3d\n", "meta": {"hexsha": "a7fa23e6a7467f0d43250da8f4513164ba7d743d", "size": 14240, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/open3d/utility/Eigen.cpp", "max_stars_repo_name": "JohanVer/Open3D", "max_stars_repo_head_hexsha": "8129a01cc0d51e17a0760b8dc4467700023a808c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-22T07:54:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:54:12.000Z", "max_issues_repo_path": "cpp/open3d/utility/Eigen.cpp", "max_issues_repo_name": "JohanVer/Open3D", "max_issues_repo_head_hexsha": "8129a01cc0d51e17a0760b8dc4467700023a808c", "max_issues_repo_licenses": ["MIT"], "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/open3d/utility/Eigen.cpp", "max_forks_repo_name": "JohanVer/Open3D", "max_forks_repo_head_hexsha": "8129a01cc0d51e17a0760b8dc4467700023a808c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-31T15:27:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:27:11.000Z", "avg_line_length": 37.375328084, "max_line_length": 80, "alphanum_fraction": 0.5895365169, "num_tokens": 4089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5403920221021917}}
{"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://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestTransform\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/lambda.hpp>\n#include <boost/compute/system.hpp>\n#include <boost/compute/function.hpp>\n#include <boost/compute/functional.hpp>\n#include <boost/compute/algorithm/transform.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/iterator/counting_iterator.hpp>\n#include <boost/compute/functional/field.hpp>\n\n#include \"check_macros.hpp\"\n#include \"context_setup.hpp\"\n\nnamespace bc = boost::compute;\nnamespace compute = boost::compute;\n\nBOOST_AUTO_TEST_CASE(transform_int_abs)\n{\n    int data[] = { 1, -2, -3, -4, 5 };\n    bc::vector<int> vector(data, data + 5, queue);\n    CHECK_RANGE_EQUAL(int, 5, vector, (1, -2, -3, -4, 5));\n\n    bc::transform(vector.begin(),\n                  vector.end(),\n                  vector.begin(),\n                  bc::abs<int>(),\n                  queue);\n    CHECK_RANGE_EQUAL(int, 5, vector, (1, 2, 3, 4, 5));\n}\n\nBOOST_AUTO_TEST_CASE(transform_float_sqrt)\n{\n    float data[] = { 1.0f, 4.0f, 9.0f, 16.0f };\n    bc::vector<float> vector(data, data + 4, queue);\n    CHECK_RANGE_EQUAL(float, 4, vector, (1.0f, 4.0f, 9.0f, 16.0f));\n\n    bc::transform(vector.begin(),\n                  vector.end(),\n                  vector.begin(),\n                  bc::sqrt<float>(),\n                  queue);\n    queue.finish();\n    BOOST_CHECK_CLOSE(float(vector[0]), 1.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(vector[1]), 2.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(vector[2]), 3.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(vector[3]), 4.0f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(transform_float_clamp)\n{\n    float data[] = { 10.f, 20.f, 30.f, 40.f, 50.f };\n    bc::vector<float> vector(data, data + 5, queue);\n    CHECK_RANGE_EQUAL(float, 5, vector, (10.0f, 20.0f, 30.0f, 40.0f, 50.0f));\n\n    bc::transform(vector.begin(),\n                  vector.end(),\n                  vector.begin(),\n                  clamp(bc::_1, 15.f, 45.f),\n                  queue);\n    CHECK_RANGE_EQUAL(float, 5, vector, (15.0f, 20.0f, 30.0f, 40.0f, 45.0f));\n}\n\nBOOST_AUTO_TEST_CASE(transform_add_int)\n{\n    int data1[] = { 1, 2, 3, 4 };\n    bc::vector<int> input1(data1, data1 + 4, queue);\n\n    int data2[] = { 10, 20, 30, 40 };\n    bc::vector<int> input2(data2, data2 + 4, queue);\n\n    bc::vector<int> output(4, context);\n    bc::transform(input1.begin(),\n                  input1.end(),\n                  input2.begin(),\n                  output.begin(),\n                  bc::plus<int>(),\n                  queue);\n    CHECK_RANGE_EQUAL(int, 4, output, (11, 22, 33, 44));\n\n    bc::transform(input1.begin(),\n                  input1.end(),\n                  input2.begin(),\n                  output.begin(),\n                  bc::multiplies<int>(),\n                  queue);\n    CHECK_RANGE_EQUAL(int, 4, output, (10, 40, 90, 160));\n}\n\nBOOST_AUTO_TEST_CASE(transform_pow4)\n{\n    float data[] = { 1.0f, 2.0f, 3.0f, 4.0f };\n    bc::vector<float> vector(data, data + 4, queue);\n    CHECK_RANGE_EQUAL(float, 4, vector, (1.0f, 2.0f, 3.0f, 4.0f));\n\n    bc::vector<float> result(4, context);\n    bc::transform(vector.begin(),\n                  vector.end(),\n                  result.begin(),\n                  pown(bc::_1, 4),\n                  queue);\n    queue.finish();\n    BOOST_CHECK_CLOSE(float(result[0]), 1.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(result[1]), 16.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(result[2]), 81.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(result[3]), 256.0f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(transform_custom_function)\n{\n    float data[] = { 9.0f, 7.0f, 5.0f, 3.0f };\n    bc::vector<float> vector(data, data + 4, queue);\n\n    BOOST_COMPUTE_FUNCTION(float, pow3add4, (float x),\n    {\n        return pow(x, 3.0f) + 4.0f;\n    });\n\n    bc::vector<float> result(4, context);\n    bc::transform(vector.begin(),\n                  vector.end(),\n                  result.begin(),\n                  pow3add4,\n                  queue);\n    queue.finish();\n    BOOST_CHECK_CLOSE(float(result[0]), 733.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(result[1]), 347.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(result[2]), 129.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(result[3]), 31.0f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(extract_vector_component)\n{\n    using bc::int2_;\n\n    int data[] = { 1, 2,\n                   3, 4,\n                   5, 6,\n                   7, 8 };\n    bc::vector<int2_> vector(\n        reinterpret_cast<int2_ *>(data),\n        reinterpret_cast<int2_ *>(data) + 4,\n        queue\n    );\n    CHECK_RANGE_EQUAL(\n        int2_, 4, vector,\n        (int2_(1, 2), int2_(3, 4), int2_(5, 6), int2_(7, 8))\n    );\n\n    bc::vector<int> x_components(4, context);\n    bc::transform(vector.begin(),\n                  vector.end(),\n                  x_components.begin(),\n                  bc::get<0>(),\n                  queue);\n    CHECK_RANGE_EQUAL(int, 4, x_components, (1, 3, 5, 7));\n\n    bc::vector<int> y_components(4, context);\n    bc::transform(vector.begin(),\n                  vector.end(),\n                  y_components.begin(),\n                  bc::get<1>(),\n                  queue);\n    CHECK_RANGE_EQUAL(int, 4, y_components, (2, 4, 6, 8));\n}\n\nBOOST_AUTO_TEST_CASE(transform_pinned_vector)\n{\n    int data[] = { 2, -3, 4, -5, 6, -7 };\n    std::vector<int> vector(data, data + 6);\n\n    bc::buffer buffer(context,\n                      vector.size() * sizeof(int),\n                      bc::buffer::read_write | bc::buffer::use_host_ptr,\n                      &vector[0]);\n\n    bc::transform(bc::make_buffer_iterator<int>(buffer, 0),\n                  bc::make_buffer_iterator<int>(buffer, 6),\n                  bc::make_buffer_iterator<int>(buffer, 0),\n                  bc::abs<int>(),\n                  queue);\n\n    void *ptr = queue.enqueue_map_buffer(buffer,\n                                         bc::command_queue::map_read,\n                                         0,\n                                         buffer.size());\n    BOOST_VERIFY(ptr == &vector[0]);\n    BOOST_CHECK_EQUAL(vector[0], 2);\n    BOOST_CHECK_EQUAL(vector[1], 3);\n    BOOST_CHECK_EQUAL(vector[2], 4);\n    BOOST_CHECK_EQUAL(vector[3], 5);\n    BOOST_CHECK_EQUAL(vector[4], 6);\n    BOOST_CHECK_EQUAL(vector[5], 7);\n    queue.enqueue_unmap_buffer(buffer, ptr);\n}\n\nBOOST_AUTO_TEST_CASE(transform_popcount)\n{\n    using boost::compute::uint_;\n\n    uint_ data[] = { 0, 1, 2, 3, 4, 45, 127, 5000, 789, 15963 };\n    bc::vector<uint_> input(data, data + 10, queue);\n    bc::vector<uint_> output(input.size(), context);\n\n    bc::transform(\n        input.begin(),\n        input.end(),\n        output.begin(),\n        bc::popcount<uint_>(),\n        queue\n    );\n    CHECK_RANGE_EQUAL(uint_, 10, output, (0, 1, 1, 2, 1, 4, 7, 5, 5, 10));\n}\n\n// generates the first 25 fibonacci numbers in parallel using the\n// rounding-based fibonacci formula\nBOOST_AUTO_TEST_CASE(generate_fibonacci_sequence)\n{\n    using boost::compute::uint_;\n\n    boost::compute::vector<uint_> sequence(25, context);\n\n    BOOST_COMPUTE_FUNCTION(uint_, nth_fibonacci, (const uint_ n),\n    {\n        const float golden_ratio = (1.f + sqrt(5.f)) / 2.f;\n        return floor(pown(golden_ratio, n) / sqrt(5.f) + 0.5f);\n    });\n\n    boost::compute::transform(\n        boost::compute::make_counting_iterator(uint_(0)),\n        boost::compute::make_counting_iterator(uint_(sequence.size())),\n        sequence.begin(),\n        nth_fibonacci,\n        queue\n    );\n    CHECK_RANGE_EQUAL(\n        uint_, 25, sequence,\n        (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610,\n         987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368)\n    );\n}\n\nBOOST_AUTO_TEST_CASE(field)\n{\n    using compute::uint2_;\n    using compute::uint4_;\n    using compute::field;\n\n    unsigned int data[] = { 1, 2, 3, 4, 5, 6, 7, 8 };\n    compute::vector<uint4_> input(\n        reinterpret_cast<uint4_ *>(data),\n        reinterpret_cast<uint4_ *>(data) + 2,\n        queue\n    );\n    compute::vector<uint2_> output(input.size(), context);\n\n    compute::transform(\n        input.begin(),\n        input.end(),\n        output.begin(),\n        compute::field<uint2_>(\"xz\"),\n        queue\n    );\n\n    queue.finish();\n\n    BOOST_CHECK_EQUAL(uint2_(output[0]), uint2_(1, 3));\n    BOOST_CHECK_EQUAL(uint2_(output[1]), uint2_(5, 7));\n}\n\nBOOST_AUTO_TEST_CASE(transform_abs_doctest)\n{\n//! [transform_abs]\nint data[] = { -1, -2, -3, -4 };\nboost::compute::vector<int> vec(data, data + 4, queue);\n\nusing boost::compute::abs;\n\n// calculate the absolute value for each element in-place\nboost::compute::transform(\n    vec.begin(), vec.end(), vec.begin(), abs<int>(), queue\n);\n\n// vec == { 1, 2, 3, 4 }\n//! [transform_abs]\n\n    CHECK_RANGE_EQUAL(int, 4, vec, (1, 2, 3, 4));\n}\n\nBOOST_AUTO_TEST_CASE(abs_if_odd)\n{\n    // return absolute value only for odd values\n    BOOST_COMPUTE_FUNCTION(int, abs_if_odd, (int x),\n    {\n        if(x & 1){\n            return abs(x);\n        }\n        else {\n            return x;\n        }\n    });\n\n    int data[] = { -2, -3, -4, -5, -6, -7, -8, -9 };\n    compute::vector<int> vector(data, data + 8, queue);\n\n    compute::transform(\n        vector.begin(), vector.end(), vector.begin(), abs_if_odd, queue\n    );\n\n    CHECK_RANGE_EQUAL(int, 8, vector, (-2, +3, -4, +5, -6, +7, -8, +9));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "81b95c0ec7a5c4c2e8ecdd64c014e680014da71c", "size": 9703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/compute/test/test_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/compute/test/test_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/compute/test/test_transform.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": 29.8553846154, "max_line_length": 79, "alphanum_fraction": 0.5543646295, "num_tokens": 2778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5403920186465677}}
{"text": "#pragma once\n\n#include <ros/ros.h>\n#include \"roboy_communication_middleware/InverseKinematics.h\"\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <vector>\n#include <boost/numeric/odeint.hpp>\n#include \"common_utilities/CommonDefinitions.h\"\n#include <boost/thread/thread.hpp>\n#include <pcl/common/common_headers.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/console/parse.h>\n#include <thread>\n#include <mutex>\n#include \"common_utilities/rviz_visualization.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\nclass PaBiRoboyInverseKinematics:public rviz_visualization{\npublic:\n    PaBiRoboyInverseKinematics();\n    ~PaBiRoboyInverseKinematics(){};\n\n    template<typename _Matrix_Type_>\n    _Matrix_Type_ pseudoInverse(const _Matrix_Type_ &a, double epsilon = std::numeric_limits<double>::epsilon())\n    {\n        Eigen::JacobiSVD< _Matrix_Type_ > svd(a ,Eigen::ComputeThinU | Eigen::ComputeThinV);\n        double tolerance = epsilon * std::max(a.cols(), a.rows()) *svd.singularValues().array().abs()(0);\n        return svd.matrixV() *  (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(), 0).matrix().asDiagonal() * svd.matrixU().adjoint();\n    }\n\n    bool inverseKinematics(roboy_communication_middleware::InverseKinematics::Request &req,\n                               roboy_communication_middleware::InverseKinematics::Response &res);\n     /**\n      * Calculates the Jacobian of a lighthouse sensor\n      * @param out 3x5 Matrix will be filled with the values\n      * @param sensor for this sensor\n      * @param ankle_left\n      * @param ankle_right\n      * @param theta0 knee_left angle\n      * @param theta1 hip_left angle\n      * @param theta2 hip_right angle\n      * @param theta3 knee_right angle\n      * @param phi angle of lower left leg wrt to inertial_frame.z\n      */\n    void Jacobian(double *out, int sensor, double ankle_left, double ankle_right, double theta0, double theta1, double theta2, double theta3, double phi);\n    /**\n     * forward kinematics of joints\n     * @param out position\n     * @param joint for this joint\n     * @param ankle_x ankle_left position x\n     * @param ankle_y ankle_left position y\n     * @param theta0 knee_left angle\n     * @param theta1 hip_left angle\n     * @param theta2 hip_right angle\n     * @param theta3 knee_right angle\n     * @param phi angle of lower left leg wrt to inertial_frame.z\n     */\n    void joint_position(double *out, int joint, double ankle_x, double ankle_y, double theta0, double theta1, double theta2, double theta3, double phi);\n\n    /**\n     * forward kinematics of lighthouse sensors\n     * @param out\n     * @param sensor for this lighthouse sensor\n     * @param ankle_x ankle_left position x\n     * @param ankle_y ankle_left position y\n     * @param theta0 knee_left angle\n     * @param theta1 hip_left angle\n     * @param theta2 hip_right angle\n     * @param theta3 knee_right angle\n     * @param phi angle of lower left leg wrt to inertial_frame.z\n     */\n    void lighthouse_sensor(double *out, int sensor, double ankle_x, double ankle_y, double phi, double theta0, double theta1, double theta2, double theta3);\n    geometry_msgs::Vector3 lighthouse_sensor(int sensor, double ankle_x, double ankle_y, double phi, double theta0, double theta1, double theta2, double theta3);\n\n    void visualize();\n\n    enum JOINTS{\n        ANKLE_LEFT = 0,\n        KNEE_LEFT,\n        HIP_LEFT,\n        HIP_CENTER,\n        HIP_RIGHT,\n        KNEE_RIGHT,\n        ANKLE_RIGHT,\n        ANKLE_RIGHT_JACOBIAN = 9,\n    };\nprivate:\n    ros::NodeHandlePtr nh;\n    ros::ServiceServer ik_srv;\n    const double l1 = 0.34;\n    const double l2 = 0.40;\n    const double l3 = 0.18;\n    const double error_threshold = 0.005, max_number_iterations = 100;\n    boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;\n    map<string,Vector3d> initial_position, result_position;\n};\n\nint main(int argc, char* argv[]);\n\n", "meta": {"hexsha": "bac19b55ea7d938ab7b8df7b7bdd09cd77a60f11", "size": 4012, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/roboy_dynamics/PaBiRoboy_inverse_kinematics.hpp", "max_stars_repo_name": "Roboy/roboy_dynamics", "max_stars_repo_head_hexsha": "a0a0012bad28029d01b6aead507faeee4509dd62", "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/roboy_dynamics/PaBiRoboy_inverse_kinematics.hpp", "max_issues_repo_name": "Roboy/roboy_dynamics", "max_issues_repo_head_hexsha": "a0a0012bad28029d01b6aead507faeee4509dd62", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/roboy_dynamics/PaBiRoboy_inverse_kinematics.hpp", "max_forks_repo_name": "Roboy/roboy_dynamics", "max_forks_repo_head_hexsha": "a0a0012bad28029d01b6aead507faeee4509dd62", "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.8490566038, "max_line_length": 179, "alphanum_fraction": 0.6996510469, "num_tokens": 1025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5403918345899367}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file libs/numeric/ublasx/test/pow.cpp\n *\n * \\brief Test suite for the \\c pow operation.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2015, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublasx/operation/pow.hpp>\n#include <cmath>\n#include <complex>\n#include <cstddef>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\n\nnamespace ublas = ::boost::numeric::ublas;\nnamespace ublasx = ::boost::numeric::ublasx;\n\n\nstatic const double tol = 1.0e-5;\n\n\nBOOST_UBLASX_TEST_DEF( test_real_vector_1 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Vector -> [vector .^ scalar]\" );\n\n    typedef double value_type;\n    typedef std::size_t size_type;\n    typedef ublas::vector<value_type> vector_type;\n\n    const size_type n = 5;\n    const double exp = 3;\n\n    vector_type v(n);\n\n    v(0) = -1.9;\n    v(1) = -0.2;\n    v(2) =  3.4;\n    v(3) =  5.6;\n    v(4) =  7.0;\n\n\n    vector_type res;\n    vector_type expect_res(n);\n\n    res = ublasx::pow(v, exp);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"v = \" << v );\n    BOOST_UBLASX_DEBUG_TRACE( \"pow(v,\" << exp << \") = \" << res );\n\n    for (size_type i = 0; i < n; ++i)\n    {\n        expect_res(i) = std::pow(v(i), exp);\n    }\n\n    BOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect_res, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_real_vector_2 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Vector -> [scalar .^ vector]\" );\n\n    typedef double value_type;\n    typedef std::size_t size_type;\n    typedef ublas::vector<value_type> vector_type;\n\n    const size_type n = 5;\n    const double base = 10;\n\n    vector_type v(n);\n\n    v(0) = -1.9;\n    v(1) = -0.2;\n    v(2) =  3.4;\n    v(3) =  5.6;\n    v(4) =  7.0;\n\n\n    vector_type res;\n    vector_type expect_res(n);\n\n    res = ublasx::pow(base, v);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"v = \" << v );\n    BOOST_UBLASX_DEBUG_TRACE( \"pow(\" << base << \",v) = \" << res );\n\n    for (size_type i = 0; i < n; ++i)\n    {\n        expect_res(i) = std::pow(base, v(i));\n    }\n\n    BOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect_res, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_complex_vector_1 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Vector -> [vector .^ scalar]\" );\n\n    typedef std::complex<double> in_value_type;\n    typedef in_value_type out_value_type;\n    typedef std::size_t size_type;\n    typedef ublas::vector<in_value_type> in_vector_type;\n    typedef ublas::vector<out_value_type> out_vector_type;\n\n    const size_type n = 4;\n    const double exp = 3;\n\n    in_vector_type v(n);\n\n    v(0) = in_value_type(1,2);\n    v(1) = in_value_type(2,3);\n    v(2) = in_value_type(3,4);\n    v(3) = in_value_type(4,5);\n\n    out_vector_type res;\n    out_vector_type expect_res(n);\n\n    res = ublasx::pow(v, exp);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"v = \" << v );\n    BOOST_UBLASX_DEBUG_TRACE( \"pow(v, \" << exp << \") = \" << res );\n\n    for (size_type i = 0; i < n; ++i)\n    {\n        expect_res(i) = std::pow(v(i), exp);\n    }\n\n    BOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect_res, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_complex_vector_2 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Vector -> [scalar .^ vector]\" );\n\n    typedef std::complex<double> in_value_type;\n    typedef in_value_type out_value_type;\n    typedef std::size_t size_type;\n    typedef ublas::vector<in_value_type> in_vector_type;\n    typedef ublas::vector<out_value_type> out_vector_type;\n\n    const size_type n = 4;\n    const double base = 10;\n\n    in_vector_type v(n);\n\n    v(0) = in_value_type(1,2);\n    v(1) = in_value_type(2,3);\n    v(2) = in_value_type(3,4);\n    v(3) = in_value_type(4,5);\n\n    out_vector_type res;\n    out_vector_type expect_res(n);\n\n    res = ublasx::pow(base, v);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"v = \" << v );\n    BOOST_UBLASX_DEBUG_TRACE( \"pow(\" << base << \",v) = \" << res );\n\n    for (size_type i = 0; i < n; ++i)\n    {\n        // Remember that c^{a+ib} == e^{log_{10}(c)*(a+ib)}\n        expect_res(i) = std::exp(std::log(base)*v(i));\n    }\n\n    BOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect_res, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_real_matrix_1 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Matrix -> [matrix .^ scalar]\" );\n\n    typedef double value_type;\n    typedef std::size_t size_type;\n    typedef ublas::matrix<value_type> matrix_type;\n\n    const size_type nr = 2;\n    const size_type nc = 3;\n    const double exp = 3;\n\n    matrix_type A(nr,nc);\n\n    A(0,0) = 1; A(0,1) = 2; A(0,2) = 3;\n    A(1,0) = 4; A(1,1) = 5; A(1,2) = 6;\n\n    matrix_type R;\n    matrix_type expect_R(nr,nc);\n\n    R = ublasx::pow(A, exp);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"pow(A, \" << exp << \") = \" << R );\n\n    for (size_type r = 0; r < nr; ++r)\n    {\n        for (size_type c = 0; c < nc; ++c)\n        {\n            expect_R(r,c) = std::pow(A(r,c), exp);\n        }\n    }\n\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( R, expect_R, nr, nc, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_real_matrix_2 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Matrix -> [scalar .^ matrix]\" );\n\n    typedef double value_type;\n    typedef std::size_t size_type;\n    typedef ublas::matrix<value_type> matrix_type;\n\n    const size_type nr = 2;\n    const size_type nc = 3;\n    const double base = 10;\n\n    matrix_type A(nr,nc);\n\n    A(0,0) = 1; A(0,1) = 2; A(0,2) = 3;\n    A(1,0) = 4; A(1,1) = 5; A(1,2) = 6;\n\n    matrix_type R;\n    matrix_type expect_R(nr,nc);\n\n    R = ublasx::pow(base, A);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"pow(\" << base << \",A) = \" << R );\n\n    for (size_type r = 0; r < nr; ++r)\n    {\n        for (size_type c = 0; c < nc; ++c)\n        {\n            expect_R(r,c) = std::pow(base, A(r,c));\n        }\n    }\n\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( R, expect_R, nr, nc, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_complex_matrix_1 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Matrix -> [matrix .^ scalar]\" );\n\n    typedef std::complex<double> in_value_type;\n    typedef in_value_type out_value_type;\n    typedef std::size_t size_type;\n    typedef ublas::matrix<in_value_type> in_matrix_type;\n    typedef ublas::matrix<out_value_type> out_matrix_type;\n\n    const size_type nr = 2;\n    const size_type nc = 3;\n    const double exp = 3;\n\n    in_matrix_type A(nr,nc);\n\n    A(0,0) = in_value_type(1,2); A(0,1) = in_value_type(2,3); A(0,2) = in_value_type(3,4);\n    A(1,0) = in_value_type(4,5); A(1,1) = in_value_type(5,6); A(1,2) = in_value_type(6,7);\n\n    out_matrix_type R;\n    out_matrix_type expect_R(nr,nc);\n\n    R = ublasx::pow(A, exp);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"pow(A, \" << exp << \") = \" << R );\n\n    for (size_type r = 0; r < nr; ++r)\n    {\n        for (size_type c = 0; c < nc; ++c)\n        {\n            expect_R(r,c) = std::pow(A(r,c), exp);\n        }\n    }\n\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( R, expect_R, nr, nc, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_complex_matrix_2 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Matrix -> [scalar .^ matrix]\" );\n\n    typedef std::complex<double> in_value_type;\n    typedef in_value_type out_value_type;\n    typedef std::size_t size_type;\n    typedef ublas::matrix<in_value_type> in_matrix_type;\n    typedef ublas::matrix<out_value_type> out_matrix_type;\n\n    const size_type nr = 2;\n    const size_type nc = 3;\n    const double base = 10;\n\n    in_matrix_type A(nr,nc);\n\n    A(0,0) = in_value_type(1,2); A(0,1) = in_value_type(2,3); A(0,2) = in_value_type(3,4);\n    A(1,0) = in_value_type(4,5); A(1,1) = in_value_type(5,6); A(1,2) = in_value_type(6,7);\n\n    out_matrix_type R;\n    out_matrix_type expect_R(nr,nc);\n\n    R = ublasx::pow(base, A);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"pow(\" << base << \",A) = \" << R );\n\n    for (size_type r = 0; r < nr; ++r)\n    {\n        for (size_type c = 0; c < nc; ++c)\n        {\n            expect_R(r,c) = std::exp(std::log(base)*A(r,c));\n        }\n    }\n\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( R, expect_R, nr, nc, tol );\n}\n\n\nint main()\n{\n\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Suite: 'pow' operation\");\n\n    BOOST_UBLASX_TEST_BEGIN();\n\n    BOOST_UBLASX_TEST_DO( test_real_vector_1 );\n    BOOST_UBLASX_TEST_DO( test_real_vector_2 );\n    BOOST_UBLASX_TEST_DO( test_complex_vector_1 );\n    BOOST_UBLASX_TEST_DO( test_complex_vector_2 );\n    BOOST_UBLASX_TEST_DO( test_real_matrix_1 );\n    BOOST_UBLASX_TEST_DO( test_real_matrix_2 );\n    BOOST_UBLASX_TEST_DO( test_complex_matrix_1 );\n    BOOST_UBLASX_TEST_DO( test_complex_matrix_2 );\n\n    BOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "2cc3372c821c9e495e81a231868c23ef20ab5098", "size": 8907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/pow.cpp", "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": "libs/numeric/ublasx/test/pow.cpp", "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": "libs/numeric/ublasx/test/pow.cpp", "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.0901408451, "max_line_length": 90, "alphanum_fraction": 0.621421354, "num_tokens": 2931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5403019878807533}}
{"text": "#include <ImathEuler.h>\n#include <anim/datatypes/transform.h>\n\n#include <boost/test/unit_test.hpp>\n#include <cmath>\n#include <cstdlib>\n\nusing std::cout;\nusing std::endl;\n\nfloat compareMatrices(const Imath::M44f& m1, const Imath::M44f& m2) {\n\t// cout << m1 << endl << m2 << endl << endl;\n\n\tfloat result = 0.0f;\n\tfor(unsigned a = 0; a < 4; ++a)\n\t\tfor(unsigned b = 0; b < 4; ++b)\n\t\t\tresult += std::fabs(m1[a][b] - m2[a][b]);\n\treturn result;\n}\n\nfloat compareMatrices(const Imath::M33f& m1, const Imath::M33f& m2) {\n\t// cout << m1 << endl << m2 << endl << endl;\n\n\tfloat result = 0.0f;\n\tfor(unsigned a = 0; a < 3; ++a)\n\t\tfor(unsigned b = 0; b < 3; ++b)\n\t\t\tresult += std::fabs(m1[a][b] - m2[a][b]);\n\treturn result;\n}\n\nfloat compareTransforms(const anim::Transform& m1, const anim::Transform& m2) {\n\t// cout << m1 << endl << m2 << endl << endl;\n\n\t// antipodality - two possible solutions to matrix-to-quat transformation - make sure we handle both\n\tfloat antipod1 = 0.0f, antipod2 = 0.0f;\n\tfor(unsigned a = 0; a < 4; ++a) {\n\t\tantipod1 += std::fabs(m1.rotation[a] - m2.rotation[a]);\n\t\tantipod2 += std::fabs(m1.rotation[a] + m2.rotation[a]);\n\t}\n\tfloat result = std::min(antipod1, antipod2);\n\n\tfor(unsigned a = 0; a < 3; ++a)\n\t\tresult += std::fabs(m1.translation[a] - m2.translation[a]);\n\n\treturn result;\n}\n\nnamespace {\nstatic const float EPS = 1e-4f;\n}\n\n/////////////\n// tests mainly the correspondence between the transformation class\n// and a 4x4 matrix.\n\nBOOST_AUTO_TEST_CASE(transform_init) {\n\tstd::vector<std::pair<anim::Transform, Imath::M44f>> data = {\n\t    {anim::Transform(), Imath::M44f(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)},\n\t    {anim::Transform(Imath::V3f(1, 2, 3)), Imath::M44f(1, 0, 0, 1, 0, 1, 0, 2, 0, 0, 1, 3, 0, 0, 0, 1)},\n\t    {anim::Transform(Imath::Quatf(-0.326096f, -0.0849528, -0.190674, 0.922001)),\n\t     Imath::M44f(-0.772889, 0.633718, -0.0322979, 0, -0.568925, -0.71461, -0.407009, 0, -0.28101, -0.296198,\n\t                 0.912853, 0, 0, 0, 0, 1)},\n\t    {anim::Transform(Imath::Quatf(-0.326096f, -0.0849528, -0.190674, 0.922001), Imath::V3f(3, 4, 5)),\n\t     Imath::M44f(-0.772889, 0.633718, -0.0322979, 3, -0.568925, -0.71461, -0.407009, 4, -0.28101, -0.296198,\n\t                 0.912853, 5, 0, 0, 0, 1)}};\n\n\t// compare the resulting matrices (transform-to-matrix)\n\tfor(auto& i : data)\n\t\tBOOST_REQUIRE_SMALL(compareMatrices(i.first.toMatrix44(), i.second), EPS);\n\n\t// and compare the transformation (matrix-to-transform)\n\tfor(auto& i : data)\n\t\tBOOST_REQUIRE_SMALL(compareTransforms(i.first, anim::Transform(i.second)), EPS);\n\n\t// test inverses\n\tfor(auto& i : data) {\n\t\t// cout << i.first.inverse().toMatrix44() << endl;\n\t\t// cout << i.second.inverse() << endl << endl;\n\n\t\tBOOST_REQUIRE_SMALL(compareTransforms(i.first.inverse(), i.second.inverse()), EPS);\n\t}\n\n\t// and test that multiplication with inverse always leads to unit\n\tfor(auto& i : data) {\n\t\tBOOST_REQUIRE_SMALL(compareTransforms(i.first.inverse() * i.first, anim::Transform(Imath::Quatf(1, 0, 0, 0))),\n\t\t                    EPS);\n\n\t\tBOOST_REQUIRE_SMALL(compareTransforms(i.first * i.first.inverse(), anim::Transform(Imath::Quatf(1, 0, 0, 0))),\n\t\t                    EPS);\n\t}\n\n\t///\n\t{\n\t\tImath::Quatf q;\n\t\tq.setAxisAngle(Imath::V3f(0, 0, 1), 0);\n\n\t\tBOOST_REQUIRE_SMALL(compareMatrices(q.toMatrix33(), Imath::M33f(1, 0, 0, 0, 1, 0, 0, 0, 1)), EPS);\n\t}\n\n\tfor(unsigned a = 0; a < 100; ++a) {\n\t\tfloat angle = 8.0f * M_PI * (float)rand() / (float)RAND_MAX;\n\n\t\tImath::Quatf q;\n\t\tq.setAxisAngle(Imath::V3f(1, 0, 0), angle);\n\n\t\tBOOST_REQUIRE_SMALL(compareMatrices(q.toMatrix33(), Imath::M33f(1, 0, 0, 0, cos(angle), sin(angle), 0,\n\t\t                                                                -sin(angle), cos(angle))),\n\t\t                    EPS);\n\t}\n\n\tfor(unsigned a = 0; a < 100; ++a) {\n\t\tfloat angle = 8.0f * M_PI * (float)rand() / (float)RAND_MAX;\n\n\t\tImath::Quatf q;\n\t\tq.setAxisAngle(Imath::V3f(0, 1, 0), angle);\n\n\t\tBOOST_REQUIRE_SMALL(compareMatrices(q.toMatrix33(), Imath::M33f(cos(angle), 0, -sin(angle), 0, 1, 0, sin(angle),\n\t\t                                                                0, cos(angle))),\n\t\t                    EPS);\n\t}\n}\n\n////////////////\n\nnamespace {\nconst Imath::M44f toMatrix44(const std::pair<Imath::Eulerf, Imath::V3f>& data) {\n\tImath::M44f result = data.first.toMatrix44().transpose();\n\tresult[0][3] = data.second[0];\n\tresult[1][3] = data.second[1];\n\tresult[2][3] = data.second[2];\n\n\treturn result;\n}\n}  // namespace\n\nBOOST_AUTO_TEST_CASE(transform_operations) {\n\tstd::vector<std::pair<std::pair<Imath::Eulerf, Imath::V3f>, std::pair<Imath::Eulerf, Imath::V3f>>> data = {\n\t    {{Imath::Eulerf(-25, 20, 36), Imath::V3f(0, 0, 0)}, {Imath::Eulerf(89, -93, 63), Imath::V3f(0, 0, 0)}},\n\t    {{Imath::Eulerf(-25, 20, 36), Imath::V3f(1, 2, 3)}, {Imath::Eulerf(89, -93, 63), Imath::V3f(0, 0, 0)}},\n\t    {{Imath::Eulerf(-25, 20, 36), Imath::V3f(1, 2, 3)}, {Imath::Eulerf(89, -93, 63), Imath::V3f(7, 6, 5)}}};\n\n\tfor(auto& i : data) {\n\t\t// cout << (anim::Transform(~i.first.first.toQuat(), i.first.second) * anim::Transform(~i.second.first.toQuat(),\n\t\t// i.second.second)).toMatrix44() << endl; cout << toMatrix44(i.first) * toMatrix44(i.second) << endl;\n\n\t\tBOOST_REQUIRE_SMALL(compareMatrices((anim::Transform(i.first.first.toQuat(), i.first.second) *\n\t\t                                     anim::Transform(i.second.first.toQuat(), i.second.second))\n\t\t                                        .toMatrix44(),\n\t\t                                    toMatrix44(i.first) * toMatrix44(i.second)),\n\t\t                    EPS);\n\t}\n\n\t// cout << \"-----\" << endl;\n\n\tfor(auto& i : data)\n\t\tBOOST_REQUIRE_SMALL(compareTransforms(anim::Transform(i.first.first.toQuat(), i.first.second) *\n\t\t                                          anim::Transform(i.second.first.toQuat(), i.second.second),\n\t\t                                      anim::Transform(toMatrix44(i.first) * toMatrix44(i.second))),\n\t\t                    EPS);\n\n\tfor(auto& i : data) {\n\t\tanim::Transform t(i.first.first.toQuat(), i.first.second);\n\t\tt *= anim::Transform(i.second.first.toQuat(), i.second.second);\n\n\t\t// cout << t.toMatrix44() << endl;\n\t\t// cout << toMatrix44(i.first) * toMatrix44(i.second) << endl;\n\n\t\tBOOST_REQUIRE_SMALL(compareMatrices(t.toMatrix44(), toMatrix44(i.first) * toMatrix44(i.second)), EPS);\n\t}\n}\n\nnamespace {\nanim::Transform randomTransform() {\n\tconst float a = (float)rand() / (float)RAND_MAX * 180.0f - 90.0f;\n\tconst float b = (float)rand() / (float)RAND_MAX * 180.0f - 90.0f;\n\tconst float c = (float)rand() / (float)RAND_MAX * 180.0f - 90.0f;\n\tImath::Eulerf angle(a, b, c);\n\n\tconst float x = (float)rand() / (float)RAND_MAX * 20.0f - 10.0f;\n\tconst float y = (float)rand() / (float)RAND_MAX * 20.0f - 10.0f;\n\tconst float z = (float)rand() / (float)RAND_MAX * 20.0f - 10.0f;\n\tImath::V3f v(x, y, z);\n\n\treturn anim::Transform(angle.toQuat(), v);\n}\n}  // namespace\n\nBOOST_AUTO_TEST_CASE(transform_operations_random) {\n\tfor(unsigned a = 0; a < 1000; ++a) {\n\t\tanim::Transform t1 = randomTransform();\n\t\tanim::Transform t2 = randomTransform();\n\n\t\tBOOST_REQUIRE_SMALL(compareMatrices((t1 * t2).toMatrix44(), t1.toMatrix44() * t2.toMatrix44()), EPS);\n\t}\n\n\tfor(unsigned a = 0; a < 1000; ++a) {\n\t\tanim::Transform t1 = randomTransform();\n\t\tanim::Transform t2 = randomTransform();\n\t\tanim::Transform t3 = randomTransform();\n\n\t\tBOOST_REQUIRE_SMALL(\n\t\t    compareMatrices((t1 * t2 * t3).toMatrix44(), t1.toMatrix44() * t2.toMatrix44() * t3.toMatrix44()), EPS);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(transform_operations_1) {\n\t///\n\t{\n\t\tImath::Quatf q;\n\t\tq.setAxisAngle(Imath::V3f(0, 0, 1), 0);\n\n\t\tBOOST_REQUIRE_SMALL(compareMatrices(q.toMatrix33(), Imath::M33f(1, 0, 0, 0, 1, 0, 0, 0, 1)), EPS);\n\t}\n\n\tfor(unsigned a = 0; a < 100; ++a) {\n\t\tfloat angle = 8.0f * M_PI * (float)rand() / (float)RAND_MAX;\n\n\t\tImath::Quatf q;\n\t\tq.setAxisAngle(Imath::V3f(1, 0, 0), angle);\n\n\t\tBOOST_REQUIRE_SMALL(compareMatrices(q.toMatrix33(), Imath::M33f(1, 0, 0, 0, cos(angle), sin(angle), 0,\n\t\t                                                                -sin(angle), cos(angle))),\n\t\t                    EPS);\n\t}\n\n\tfor(unsigned a = 0; a < 100; ++a) {\n\t\tfloat angle = 8.0f * M_PI * (float)rand() / (float)RAND_MAX;\n\n\t\tImath::Quatf q;\n\t\tq.setAxisAngle(Imath::V3f(0, 1, 0), angle);\n\n\t\tBOOST_REQUIRE_SMALL(compareMatrices(q.toMatrix33(), Imath::M33f(cos(angle), 0, -sin(angle), 0, 1, 0, sin(angle),\n\t\t                                                                0, cos(angle))),\n\t\t                    EPS);\n\t}\n}\n", "meta": {"hexsha": "4ae24b45f7b405d88507ded2a388d98392c43938", "size": 8450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/anim/transform.cpp", "max_stars_repo_name": "LIUJUN-liujun/possumwood", "max_stars_repo_head_hexsha": "745e48eb44450b0b7f078ece81548812ab1ccc63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-06T08:40:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-06T08:40:10.000Z", "max_issues_repo_path": "src/tests/anim/transform.cpp", "max_issues_repo_name": "LIUJUN-liujun/possumwood", "max_issues_repo_head_hexsha": "745e48eb44450b0b7f078ece81548812ab1ccc63", "max_issues_repo_licenses": ["MIT"], "max_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/anim/transform.cpp", "max_forks_repo_name": "LIUJUN-liujun/possumwood", "max_forks_repo_head_hexsha": "745e48eb44450b0b7f078ece81548812ab1ccc63", "max_forks_repo_licenses": ["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.6540084388, "max_line_length": 114, "alphanum_fraction": 0.5865088757, "num_tokens": 2905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.769080247656264, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5403019857375373}}
{"text": "#include \"polyscope/polyscope.h\"\n\n#include <igl/PI.h>\n#include <igl/avg_edge_length.h>\n#include <igl/barycenter.h>\n#include <igl/boundary_loop.h>\n#include <igl/exact_geodesic.h>\n#include <igl/gaussian_curvature.h>\n#include <igl/invert_diag.h>\n#include <igl/lscm.h>\n#include <igl/massmatrix.h>\n#include <igl/per_vertex_normals.h>\n#include <igl/readOBJ.h>\n#include <igl/writeOBJ.h>\n#include <igl/doublearea.h>\n#include <igl/file_dialog_open.h>\n#include <igl/file_dialog_save.h>\n#include <igl/boundary_loop.h>\n#include <igl/cotmatrix_entries.h>\n#include <igl/triangle/triangulate.h>\n#include <filesystem>\n#include \"polyscope/messages.h\"\n#include \"polyscope/point_cloud.h\"\n#include \"polyscope/surface_mesh.h\"\n\n#include <iostream>\n#include <fstream>\n#include <unordered_set>\n#include <utility>\n#include <Eigen/SparseQR>\n\n#include \"../../include/CommonTools.h\"\n#include \"../../include/MeshLib/MeshConnectivity.h\"\n#include \"../../include/MeshLib/MeshUpsampling.h\"\n#include \"../../include/Visualization/PaintGeometry.h\"\n#include \"../../include/InterpolationScheme/VecFieldSplit.h\"\n#include \"../../include/Optimization/NewtonDescent.h\"\n#include \"../../include/Optimization/LinearConstrainedSolver.h\"\n#include \"../../include/IntrinsicFormula/InterpolateZvalsFromEdgeOmega.h\"\n#include \"../../include/DynamicInterpolation/ComputeZandZdot.h\"\n#include \"../../include/DynamicInterpolation/InterpolateKeyFrames.h\"\n//#include \"../../include/IntrinsicFormula/ComputeZdotFromEdgeOmega.h\"\n#include \"../../include/IntrinsicFormula/ComputeZdotFromHalfEdgeOmega.h\"\n//#include \"../../include/IntrinsicFormula/IntrinsicKeyFrameInterpolationFromEdge.h\"\n#include \"../../include/IntrinsicFormula/IntrinsicKeyFrameInterpolationFromHalfEdge.h\"\n#include \"../../include/IntrinsicFormula/KnoppelStripePattern.h\"\n\n\n\nEigen::MatrixXd triV, upsampledTriV;\nEigen::MatrixXi triF, upsampledTriF;\nMeshConnectivity triMesh, upsampledTriMesh;\nstd::vector<std::pair<int, Eigen::Vector3d>> bary;\n\nEigen::MatrixXd sourceOmegaFields, tarOmegaFields;\nEigen::MatrixXd theoOmega, tarTheoOmega;\n\n\nstd::vector<std::complex<double>> sourceZvals, sourceTheoZVals, upsampledTheoZVals;\nstd::vector<std::complex<double>> tarZvals, tarTheoZVals, upsampledTarTheoZVals;\nstd::vector<Eigen::Vector2cd> sourceTheoGradZvals, tarTheoGradZvals;\n\n\nstd::vector<Eigen::MatrixXd> omegaList;\nstd::vector<Eigen::MatrixXd> theoOmegaList;\nstd::vector<std::vector<std::complex<double>>> zList;\nstd::vector<std::vector<std::complex<double>>> theoZList;\n\nstd::vector<Eigen::VectorXd> phaseFieldsList;\nstd::vector<Eigen::VectorXd> ampFieldsList;\n\nstd::vector<Eigen::VectorXd> theoPhaseFieldsList;\nstd::vector<Eigen::VectorXd> theoAmpFieldsList;\n\n\nEigen::MatrixXd dataV;\nEigen::MatrixXi dataF;\nEigen::MatrixXd dataVec;\nEigen::MatrixXd curColor;\n\nint loopLevel = 1;\nbool isFixedSource = true;\nbool isFixedTar = true;\n\nbool isForceOptimize = false;\nbool isTwoTriangles = true;\n\nPaintGeometry mPaint;\n\nint numFrames = 2;\nint curFrame = 0;\n\nint singIndSource = 1, singIndSource1 = 1;\nint singIndTar = 1, singIndTar1 = 1;\nint numWavesSource = 2, numWaveTar = 4;\n\ndouble globalAmpMax = 1;\n\ndouble dragSpeed = 0.5;\n\ndouble triarea = 0.04;\n\nfloat vecratio = 0.1;\n\ndouble sourceCenter1x = 0, sourceCenter1y = 0, sourceCenter2x = 0.8, sourceCenter2y = -0.2, targetCenter1x = 0, targetCenter1y = 0, targetCenter2x = 0.3, targetCenter2y = -0.7;\ndouble sourceDirx = 1.0, sourceDiry = 0, targetDirx = 1, targetDiry = 0;\n\ndouble gradTol = 1e-6;\ndouble xTol = 0;\ndouble fTol = 0;\nint numIter = 1000;\nint quadOrder = 4;\n\n\nenum FunctionType {\n\tWhirlpool = 0,\n\tPlaneWave = 1,\n\tSummation = 2,\n\tYShape = 3,\n\tTwoWhirlPool = 4,\n};\n\nenum InitializationType{\n  Random = 0,\n  Linear = 1,\n  Theoretical = 2\n};\n\nbool isUseUpMesh = false;\n\nFunctionType functionType = FunctionType::PlaneWave;\nFunctionType tarFunctionType = FunctionType::PlaneWave;\nInitializationType initializationType = InitializationType::Linear;\n\n\nvoid generateSquare(double length, double width, double triarea, Eigen::MatrixXd& irregularV, Eigen::MatrixXi& irregularF)\n{\n\tdouble area = length * width;\n\tint N = (0.25 * std::sqrt(area / triarea));\n\tN = N > 1 ? N : 1;\n\tdouble deltaX = length / (4.0 * N);\n\tdouble deltaY = width / (4.0 * N);\n\n\tEigen::MatrixXd planeV;\n\tEigen::MatrixXi planeE;\n\n//\tplaneV.resize(10, 2);\n//\tplaneE.resize(10, 2);\n\n//\tfor (int i = -2; i <= 2; i++)\n//\t{\n//\t\tplaneV.row(i + 2) << length / 4.0 * i, -width / 2.0;\n//\t}\n//\n//\tfor (int i = 2; i >= -2; i--)\n//\t{\n//\t\tplaneV.row(5 + 2 - i) << length / 4.0 * i, width / 2.0;\n//\t}\n//\n//\tfor (int i = 0; i < 10; i++)\n//\t{\n//\t\tplaneE.row(i) << i, (i + 1) % 10;\n//\t}\n\n\tint M = 2 * N + 1;\n\tplaneV.resize(4 * M - 4, 2);\n\tplaneE.resize(4 * M - 4, 2);\n\n\tfor (int i = 0; i < M; i++)\n\t{\n\t    planeV.row(i) << -length / 2, i * width / (M - 1) - width / 2;\n\t}\n\tfor (int i = 1; i < M; i++)\n\t{\n\t    planeV.row(M - 1 + i) << i * length / (M - 1)-length / 2, width / 2;\n\t}\n\tfor (int i = 1; i < M; i++)\n\t{\n\t    planeV.row(2 * (M - 1) + i) << length / 2, width/2 - i * width / (M - 1);\n\t}\n\tfor (int i = 1; i < M - 1; i++)\n\t{\n\t    planeV.row(3 * (M - 1) + i) << length / 2- i * length / (M - 1), - width / 2;\n\t}\n\n\tfor (int i = 0; i < 4 * (M - 1); i++)\n\t{\n\t    planeE.row(i) << i, (i + 1) % (4 * (M - 1));\n\t}\n\n\tEigen::MatrixXd V2d;\n\tEigen::MatrixXi F;\n\tEigen::MatrixXi H(0, 2);\n\tstd::cout << triarea << std::endl;\n\t// Create an output string stream\n\tstd::ostringstream streamObj;\n\t//Add double to stream\n\tstreamObj << triarea;\n\tconst std::string flags = \"q20a\" + std::to_string(triarea);\n\n\tigl::triangle::triangulate(planeV, planeE, H, flags, V2d, F);\n\n\tif (isTwoTriangles)\n\t{\n\t\t/*V2d.resize(4, 3);\n\t\tV2d << -1, -1, 0,\n\t\t\t1, -1, 0,\n\t\t\t1, 1, 0,\n\t\t\t-1, 1, 0;\n\n\t\tF.resize(2, 3);\n\t\tF << 0, 1, 2,\n\t\t\t2, 3, 0;*/\n\n\t\tV2d.resize(3, 3);\n\t\tV2d << 0, 0, 0,\n\t\t\t1, 0, 0,\n\t\t\t0, 1, 0;\n\n\t\tF.resize(1, 3);\n\t\tF << 0, 1, 2;\n\t}\n\n\tirregularV.resize(V2d.rows(), 3);\n\tirregularV.setZero();\n\tirregularV.block(0, 0, irregularV.rows(), 2) = V2d.block(0, 0, irregularV.rows(), 2);\n\tirregularF = F;\n\tigl::writeOBJ(\"irregularPlane.obj\", irregularV, irregularF);\n}\n\n\nvoid generateWhirlPool(double centerx, double centery, Eigen::MatrixXd& w, std::vector<std::complex<double>>& z, int pow = 1, std::vector<Eigen::Vector2cd> *gradZ = NULL, std::vector<std::complex<double>> *upsampledZ = NULL)\n{\n\tz.resize(triV.rows());\n\tw.resize(triV.rows(), 2);\n\tstd::cout << \"whirl pool center: \" << centerx << \", \" << centery << std::endl;\n\tbool isnegative = false;\n\tif(pow < 0)\n\t{\n\t    isnegative = true;\n\t    pow *= -1;\n\t}\n\n\tfor (int i = 0; i < z.size(); i++)\n\t{\n\t\tdouble x = triV(i, 0) - centerx;\n\t\tdouble y = triV(i, 1) - centery;\n\t\tdouble rsquare = x * x + y * y;\n\n\t\tif(isnegative)\n\t\t{\n\t\t    z[i] = std::pow(std::complex<double>(x, -y), pow);\n\n\t\t    if (std::abs(std::sqrt(rsquare)) < 1e-10)\n\t\t        w.row(i) << 0, 0;\n\t\t    else\n\t\t        w.row(i) << pow * y / rsquare, -pow * x / rsquare;\n\t\t}\n\t\telse\n\t\t{\n\t\t    z[i] = std::pow(std::complex<double>(x, y), pow);\n\n\t\t    if (std::abs(std::sqrt(rsquare)) < 1e-10)\n\t\t        w.row(i) << 0, 0;\n\t\t    else\n\t\t        //\t\t\tw.row(i) << -y / rsquare, x / rsquare;\n\t\t        w.row(i) << -pow * y / rsquare, pow * x / rsquare;\n\t\t}\n\t}\n\n\tif(upsampledZ)\n\t{\n\t    upsampledZ->resize(upsampledTriV.rows());\n\t    for(int i = 0; i < upsampledZ->size(); i++)\n\t    {\n\t        double x = upsampledTriV(i, 0) - centerx;\n\t        double y = upsampledTriV(i, 1) - centery;\n\t        double rsquare = x * x + y * y;\n\n\t\t\tupsampledZ->at(i) = std::pow(std::complex<double>(x, y), pow);\n\t\t\tif(isnegative)\n\t\t\t    upsampledZ->at(i) = std::pow(std::complex<double>(x, -y), pow);\n\t    }\n\t}\n\tif(gradZ)\n\t{\n\t    gradZ->resize(triV.rows());\n\t    for(int i = 0; i < gradZ->size(); i++)\n\t    {\n\t        double x = upsampledTriV(i, 0) - centerx;\n\t        double y = upsampledTriV(i, 1) - centery;\n\n\t        Eigen::Vector2cd tmpGrad;\n\t        tmpGrad << 1, std::complex<double>(0, 1);\n\t        if(isnegative)\n\t            tmpGrad(1) *= -1;\n\n\t        (*gradZ)[i] = std::pow(std::complex<double>(x, y), pow - 1) * tmpGrad;\n\t        (*gradZ)[i] *= pow;\n\n\t    }\n\n\t}\n}\n\nvoid generatePlaneWave(Eigen::Vector2d v, Eigen::MatrixXd& w, std::vector<std::complex<double>>& z, std::vector<Eigen::Vector2cd> *gradZ = NULL, std::vector<std::complex<double>> *upsampledZ = NULL)\n{\n    z.resize(triV.rows());\n    w.resize(triV.rows(), 2);\n    std::cout << \"plane wave direction: \" << v.transpose() << std::endl;\n\n    for (int i = 0; i < z.size(); i++)\n    {\n        double theta = v.dot(triV.row(i).segment<2>(0));\n        double x = std::cos(theta);\n        double y = std::sin(theta);\n        z[i] = std::complex<double>(x, y);\n        w.row(i) = v;\n    }\n\n    if(upsampledZ)\n    {\n        upsampledZ->resize(upsampledTriV.rows());\n        for(int i = 0; i < upsampledZ->size(); i++)\n        {\n            double theta = v.dot(upsampledTriV.row(i).segment<2>(0));\n            double x = std::cos(theta);\n            double y = std::sin(theta);\n            upsampledZ->at(i) = std::complex<double>(x, y);\n        }\n    }\n    if(gradZ)\n    {\n        gradZ->resize(triV.rows());\n        for(int i = 0; i < gradZ->size(); i++)\n        {\n            double theta = v.dot(triV.row(i).segment<2>(0));\n            double x = std::cos(theta);\n            double y = std::sin(theta);\n            std::complex<double> tmpZ = std::complex<double>(x, y);\n            std::complex<double> I = std::complex<double>(0, 1);\n\n            (*gradZ)[i] << I * tmpZ * v(0), I * tmpZ * v(1);\n        }\n\n    }\n}\n\nvoid generatePeriodicWave(int waveNum, Eigen::MatrixXd& w, std::vector<std::complex<double>>& z, std::vector<Eigen::Vector2cd> *gradZ = NULL, std::vector<std::complex<double>> *upsampledZ = NULL)\n{\n    Eigen::Vector2d v(2 * M_PI * waveNum, 0);\n    generatePlaneWave(v, w, z, gradZ, upsampledZ);\n}\n\nvoid generateTwoWhirlPool(double centerx0, double centery0, double centerx1, double centery1, Eigen::MatrixXd& w, std::vector<std::complex<double>>& z, int n0 = 1, int n1 = 1, std::vector<Eigen::Vector2cd> *gradZ = NULL, std::vector<std::complex<double>>* upsampledZ = NULL)\n{\n\tEigen::MatrixXd w0, w1;\n\tstd::vector<Eigen::Vector2cd> gradZ0, gradZ1;\n\tstd::vector<std::complex<double>> z0, z1, upsampledZ0, upsampledZ1;\n\n\tgenerateWhirlPool(centerx0, centery0, w0, z0, n0, gradZ ? &gradZ0 : NULL, upsampledZ ? &upsampledZ0 : NULL);\n\tgenerateWhirlPool(centerx1, centery1, w1, z1, n1, gradZ ? &gradZ1 : NULL, upsampledZ ? &upsampledZ1 : NULL);\n\n\tstd::cout << \"whirl pool center: \" << centerx0 << \", \" << centery0 << std::endl;\n\tstd::cout << \"whirl pool center: \" << centerx1 << \", \" << centery1 << std::endl;\n\n\tz.resize(triV.rows());\n\tw.resize(triV.rows(), 2);\n\n\tw = w0 + w1;\n\n\tfor (int i = 0; i < z.size(); i++)\n\t{\n\t\tz[i] = z0[i] * z1[i];\n\t}\n\n\tif (upsampledZ)\n\t{\n\t\tupsampledZ->resize(upsampledTriV.rows());\n\t\tfor (int i = 0; i < upsampledZ->size(); i++)\n\t\t{\n\t\t\tupsampledZ->at(i) = upsampledZ0[i] * upsampledZ1[i];\n\t\t}\n\t}\n\n\tif(gradZ)\n\t{\n\t    *gradZ = gradZ0;\n\t    for(int i = 0; i < gradZ0.size(); i++)\n\t    {\n\t        (*gradZ)[i] = z0[i] * gradZ1[i] + z1[i] * gradZ0[i];\n\t    }\n\t}\n}\n\nvoid generatePlaneSumWhirl(double centerx, double centery, Eigen::Vector2d v, Eigen::MatrixXd& w, std::vector<std::complex<double>>& z, int pow = 1, std::vector<Eigen::Vector2cd> *gradZ = NULL, std::vector<std::complex<double>> *upsampledZ = NULL)\n{\n    z.resize(triV.rows());\n    w.resize(triV.rows(), 2);\n    std::cout << \"whirl pool center: \" << centerx << \", \" << centery << std::endl;\n    std::cout << \"plane wave direction: \" << v.transpose() << std::endl;\n\n    std::vector<Eigen::Vector2cd> gradWZ, gradPZ;\n    Eigen::MatrixXd whw, plw;\n    std::vector<std::complex<double>> wz, pz, upWz, upPz;\n\n    generatePlaneWave(v, plw, pz, gradZ ? &gradPZ : NULL, upsampledZ ? &upPz : NULL);\n    generateWhirlPool(centerx, centery, whw, wz, pow, gradZ? &gradWZ : NULL, upsampledZ? &upWz : NULL);\n\n\n\n    for (int i = 0; i < z.size(); i++)\n    {\n        z[i] = pz[i] * wz[i];\n        w = plw + whw;\n    }\n\n    if(upsampledZ)\n    {\n        upsampledZ->resize(upsampledTriV.rows());\n\n        for(int i = 0; i < upsampledZ->size(); i++)\n        {\n            (*upsampledZ)[i] = upPz[i] * upWz[i];\n        }\n    }\n\n    if(gradZ)\n    {\n        *gradZ = gradWZ;\n        for(int i = 0; i < gradWZ.size(); i++)\n        {\n            (*gradZ)[i] = pz[i] * gradWZ[i] + wz[i] * gradPZ[i];\n        }\n    }\n\n}\n\nvoid generateYshape(Eigen::Vector2d w1, Eigen::Vector2d w2, Eigen::MatrixXd &w, std::vector<std::complex<double>> &z, std::vector<Eigen::Vector2cd> *gradZ = NULL, std::vector<std::complex<double>> *upsampledZ = NULL)\n{\n    z.resize(triV.rows());\n    w.resize(triV.rows(), 2);\n\n    if(gradZ)\n        gradZ->resize(triV.rows());\n\n    std::cout << \"w1: \" << w1.transpose() << std::endl;\n    std::cout << \"w2: \" << w2.transpose() << std::endl;\n\n    Eigen::MatrixXd pw1, pw2;\n    std::vector<std::complex<double>> pz1, pz2;\n    std::vector<Eigen::Vector2cd> gradPZ1, gradPZ2;\n    std::vector<std::complex<double>> upsampledPZ1, upsampledPZ2;\n\n    generatePlaneWave(w1, pw1, pz1, gradZ ? & gradPZ1 : NULL, upsampledZ? &upsampledPZ1 : NULL);\n    generatePlaneWave(w2, pw2, pz2, gradZ ? & gradPZ2 : NULL, upsampledZ? &upsampledPZ2 : NULL);\n\n    double ymax = triV.col(1).maxCoeff();\n    double ymin = triV.col(1).minCoeff();\n\n    for (int i = 0; i < z.size(); i++)\n    {\n\n        double weight = (triV(i, 1) - triV.col(1).minCoeff()) / (triV.col(1).maxCoeff() - triV.col(1).minCoeff());\n        z[i] = (1 - weight) * pz1[i] + weight * pz2[i];\n        Eigen::Vector2cd dz = (1 - weight) * gradPZ1[i] + weight * gradPZ2[i];\n        if(gradZ)\n            (*gradZ)[i] = dz;\n\n        double wx = 0;\n        double wy = 1 / (ymax - ymin);\n\n        w.row(i) = (std::conj(z[i]) * dz).imag() / (std::abs(z[i]) * std::abs(z[i]));\n    }\n\n    if(upsampledZ)\n    {\n        upsampledZ->resize(upsampledTriV.rows());\n        for(int i = 0; i < upsampledZ->size(); i++)\n        {\n            double theta = w1.dot(upsampledTriV.row(i).segment<2>(0));\n            double x = std::cos(theta);\n            double y = std::sin(theta);\n            std::complex<double> z1 = std::complex<double>(x, y);\n\n            theta = w2.dot(upsampledTriV.row(i).segment<2>(0));\n            x = std::cos(theta);\n            y = std::sin(theta);\n            std::complex<double> z2 = std::complex<double>(x, y);\n\n            double weight = (upsampledTriV(i, 1) - upsampledTriV.col(1).minCoeff()) / (upsampledTriV.col(1).maxCoeff() - upsampledTriV.col(1).minCoeff());\n            upsampledZ->at(i) = (1 - weight) * z1 + weight * z2;\n        }\n    }\n}\n\nvoid initialization()\n{\n\tgenerateSquare(2.0, 2.0, triarea, triV, triF);\n\n\n\tEigen::SparseMatrix<double> S;\n\tstd::vector<int> facemap;\n\n\tmeshUpSampling(triV, triF, upsampledTriV, upsampledTriF, loopLevel, &S, &facemap, &bary);\n\tstd::cout << \"upsampling finished\" << std::endl;\n\n\ttriMesh = MeshConnectivity(triF);\n\tupsampledTriMesh = MeshConnectivity(upsampledTriF);\n\n    std::cout << \"nverts: \" << triV.rows() << \", nedges: \" << triMesh.nEdges() << std::endl;\n}\n\n\nvoid generateValues(FunctionType funType, Eigen::MatrixXd &vecFields, std::vector<std::complex<double>> &zvalues, std::vector<Eigen::Vector2cd> &gradZvals, std::vector<std::complex<double>> &upZvals, int singularityInd1 = 1, int singularityInd2 = 1, bool isFixedGenerator = false, double fixedx = 0, double fixedy = 0, Eigen::Vector2d fixedv = Eigen::Vector2d::Constant(1.0))\n{\n\tEigen::MatrixXd vertFields;\n\tif (funType == FunctionType::Whirlpool)\n\t{\n\t\tEigen::Vector2d center = Eigen::Vector2d::Random();\n\t\tif (isFixedGenerator)\n\t\t\tcenter << fixedx, fixedy;\n\t\tgenerateWhirlPool(center(0), center(1), vertFields, zvalues, singularityInd1, &gradZvals, &upZvals);\n\t}\n\telse if (funType == FunctionType::PlaneWave)\n\t{\n\t\tEigen::Vector2d v = Eigen::Vector2d::Random();\n\t\tif (isFixedGenerator)\n\t\t\tv = fixedv;\n\t\tgeneratePlaneWave(v, vertFields, zvalues, &gradZvals, &upZvals);\n\t}\n\telse if (funType == FunctionType::Summation)\n\t{\n\t\tEigen::Vector2d center = Eigen::Vector2d::Random();\n\t\tEigen::Vector2d v = Eigen::Vector2d::Random();\n\t\tif (isFixedGenerator)\n\t\t{\n\t\t\tv = fixedv;\n\t\t\tcenter << fixedx, fixedy;\n\t\t}\n\t\tgeneratePlaneSumWhirl(center(0), center(1), v, vertFields, zvalues, singularityInd1, &gradZvals, &upZvals);\n\t}\n\telse if (funType == FunctionType::YShape)\n\t{\n\t\tEigen::Vector2d w1(1, 0);\n\t\tEigen::Vector2d w2(1, 0);\n\n\t\tw1(0) = 2 * 3.1415926;\n\t\tw2(0) = 4 * 3.1415926;\n\t\tgenerateYshape(w1, w2, vertFields, zvalues, &gradZvals, &upZvals);\n\t}\n\telse if (funType == FunctionType::TwoWhirlPool)\n\t{\n\t\tEigen::Vector2d center0 = Eigen::Vector2d::Random();\n\t\tEigen::Vector2d center1 = Eigen::Vector2d::Random();\n\t\tif (isFixedGenerator)\n\t\t{\n\t\t\tcenter0 << fixedx, fixedy;\n\t\t\tcenter1 << 0.8, -0.3;\n\t\t}\n\t\tgenerateTwoWhirlPool(center0(0), center0(1), center1(0), center1(1), vertFields, zvalues, singularityInd1, singularityInd2, &gradZvals, &upZvals);\n\t}\n\tEigen::MatrixXd vertFields3D(triV.rows(), 3);\n\tvertFields3D.block(0, 0, triV.rows(), 2) = vertFields;\n\tvertFields3D.col(2).setZero();\n\n\tvecFields = vertexVec2IntrinsicHalfEdgeVec(vertFields3D, triV, MeshConnectivity(triF));\n}\n\n// TODO: remove this\nEigen::MatrixXd vertexVec2IntrinsicHalfEdgeVec2D(const Eigen::MatrixXd& v, const Eigen::MatrixXd& pos, const MeshConnectivity& mesh, std::vector<Eigen::Triplet<double>> &T)\n{\n    int nedges = mesh.nEdges();\n    Eigen::MatrixXd edgeOmega(nedges, 2);\n    T.clear();\n\n    for (int i = 0; i < nedges; i++)\n    {\n        int vid0 = mesh.edgeVertex(i, 0);\n        int vid1 = mesh.edgeVertex(i, 1);\n\n        Eigen::Vector2d e = (pos.row(vid1) - pos.row(vid0)).segment(0, 2);\n        edgeOmega(i, 0) = v.row(vid0).dot(e);\n        edgeOmega(i, 1) = -v.row(vid1).dot(e);\n\n        T.push_back({2 * i, 2 * vid0, e(0)});\n        T.push_back({2 * i, 2 * vid0 + 1, e(1)});\n\n        T.push_back({2 * i + 1, 2 * vid1, -e(0)});\n        T.push_back({2 * i + 1, 2 * vid1 + 1, -e(1)});\n    }\n    return edgeOmega;\n}\n\nvoid solveKeyFrames(const Eigen::MatrixXd& sourceVec, const Eigen::MatrixXd& tarVec, const std::vector<std::complex<double>>& sourceZvals, const std::vector<std::complex<double>>& tarZvals, const int numKeyFrames, std::vector<Eigen::MatrixXd>& wFrames, std::vector<std::vector<std::complex<double>>>& zFrames)\n{\n\tEigen::VectorXd faceArea;\n\tigl::doublearea(triV, triF, faceArea);\n\tfaceArea /= 2;\n\tIntrinsicFormula::IntrinsicKeyFrameInterpolationFromHalfEdge interpModel = IntrinsicFormula::IntrinsicKeyFrameInterpolationFromHalfEdge(MeshConnectivity(triF), faceArea, numFrames, quadOrder, sourceZvals, sourceVec, tarZvals, tarVec);\n\tEigen::VectorXd x;\n\tinterpModel.convertList2Variable(x);        // linear initialization\n\n    std::vector<std::complex<double>> testzvals;\n    Eigen::MatrixXd cotEntries;\n    igl::cotmatrix_entries(triV, triF, cotEntries);\n    IntrinsicFormula::roundVertexZvalsFromHalfEdgeOmega(triMesh, sourceVec, faceArea, cotEntries, triV.rows(), testzvals);\n    IntrinsicFormula::testRoundingEnergy(triMesh, sourceVec, faceArea, cotEntries, triV.rows(), testzvals);\n\tfor (auto& z : testzvals)\n\t{\n\t\tEigen::Vector2d rndvec;\n\t\trndvec.setRandom();\n\t\tz = std::complex<double>(rndvec(0), rndvec(1));\n\t}\n\tIntrinsicFormula::testRoundingEnergy(triMesh, sourceVec, faceArea, cotEntries, triV.rows(), testzvals);\n\n\t//interpModel.testEnergy(x);\n\t//\t\tstd::cout << \"starting energy: \" << interpModel.computeEnergy(x) << std::endl;\n\tif (initializationType == InitializationType::Theoretical)\n\t{\n\t\tinterpModel.setwzLists(theoZList, theoOmegaList);\n\t\tinterpModel.convertList2Variable(x);\n\t}\n\telse if (initializationType == InitializationType::Random)\n\t{\n\t\tx.setRandom();\n\t\tinterpModel.convertVariable2List(x);\n\t\tinterpModel.convertList2Variable(x);\n\t}\n\telse\n\t{\n\t\t// do nothing, since it is initialized as the linear interpolation.\n\t}\n\n\tauto initWFrames = interpModel.getWList();\n\tauto initZFrames = interpModel.getVertValsList();\n\tif (isForceOptimize)\n\t{\n\t\tauto funVal = [&](const Eigen::VectorXd& x, Eigen::VectorXd* grad, Eigen::SparseMatrix<double>* hess, bool isProj) {\n\t\t\tEigen::VectorXd deriv;\n\t\t\tEigen::SparseMatrix<double> H;\n\t\t\tdouble E = interpModel.computeEnergy(x, grad ? &deriv : NULL, hess ? &H : NULL, isProj);\n\n\t\t\tif (grad)\n\t\t\t{\n\t\t\t\t(*grad) = deriv;\n\t\t\t}\n\n\t\t\tif (hess)\n\t\t\t{\n\t\t\t\t(*hess) = H;\n\t\t\t}\n\n\t\t\treturn E;\n\t\t};\n\t\tauto maxStep = [&](const Eigen::VectorXd& x, const Eigen::VectorXd& dir) {\n\t\t\treturn 1.0;\n\t\t};\n\n\t\tauto getVecNorm = [&](const Eigen::VectorXd& x, double& znorm, double& wnorm) {\n\t\t\tinterpModel.getComponentNorm(x, znorm, wnorm);\n\t\t};\n\n\n\n\t\tOptSolver::testFuncGradHessian(funVal, x);\n\n\t\tauto x0 = x;\n\t\tOptSolver::newtonSolver(funVal, maxStep, x, numIter, gradTol, xTol, fTol, true, getVecNorm);\n\t\tstd::cout << \"before optimization: \" << x0.norm() << \", after optimization: \" << x.norm() << \", difference: \" << (x - x0).norm() << std::endl;\n\t\tstd::cout << \"x norm: \" << x.norm() << std::endl;\n\n\t\t/*Eigen::VectorXd deriv;\n\t\tEigen::SparseMatrix<double> H;\n\t\tdouble E = interpModel.computeEnergy(x, &deriv, &H, false);\n\n\t\tstd::cout << deriv.norm() << std::endl;*/\n\t\t//std::cout << \"hessian: \\n\" << H.toDense() << std::endl;\n\n\t\t/*Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es;\n\t\tes.compute(H.toDense());\n\t\tEigen::VectorXd evals = es.eigenvalues();\n\t\tstd::cout << \"evals: \" << evals.transpose() << std::endl;*/\n\n\t}\n\tinterpModel.convertVariable2List(x);\n\n\twFrames = interpModel.getWList();\n\tzFrames = interpModel.getVertValsList();\n\n\tfor (int i = 0; i < wFrames.size() - 1; i++)\n\t{\n\t\tdouble zdotNorm = interpModel._zdotModel.computeZdotIntegration(zFrames[i], wFrames[i], zFrames[i + 1], wFrames[i + 1], NULL, NULL);\n\n\t\tdouble initZdotNorm = interpModel._zdotModel.computeZdotIntegration(initZFrames[i], initWFrames[i], initZFrames[i + 1], initWFrames[i + 1], NULL, NULL);\n\n\t\tstd::cout << \"frame \" << i << \", before optimization: ||zdot||^2: \" << initZdotNorm << \", after optimization, ||zdot||^2 = \" << zdotNorm << std::endl;\n\t}\n\n\n}\n\nvoid updateMagnitudePhase(const std::vector<Eigen::MatrixXd>& wFrames, const std::vector<std::vector<std::complex<double>>>& zFrames, std::vector<Eigen::VectorXd>& magList, std::vector<Eigen::VectorXd>& phaseList)\n{\n\tstd::vector<std::vector<std::complex<double>>> interpZList(wFrames.size());\n\tmagList.resize(wFrames.size());\n\tphaseList.resize(wFrames.size());\n\n\tMeshConnectivity mesh(triF);\n\n\tauto computeMagPhase = [&](const tbb::blocked_range<uint32_t>& range) {\n\t\tfor (uint32_t i = range.begin(); i < range.end(); ++i)\n\t\t{\n\t\t\tinterpZList[i] = IntrinsicFormula::upsamplingZvals(mesh, zFrames[i], wFrames[i], bary);\n\t\t\tmagList[i].setZero(interpZList[i].size());\n\t\t\tphaseList[i].setZero(interpZList[i].size());\n\n\t\t\tfor (int j = 0; j < magList[i].size(); j++)\n\t\t\t{\n\t\t\t\tmagList[i](j) = std::abs(interpZList[i][j]);\n\t\t\t\tphaseList[i](j) = std::arg(interpZList[i][j]);\n\t\t\t}\n\t\t}\n\t};\n\n\ttbb::blocked_range<uint32_t> rangex(0u, (uint32_t)interpZList.size(), GRAIN_SIZE);\n\ttbb::parallel_for(rangex, computeMagPhase);\n}\n\nvoid updateTheoMagnitudePhase(const std::vector<std::complex<double>>& sourceZvals, const std::vector<std::complex<double>>& tarZvals,\n                              const std::vector<Eigen::Vector2cd>& sourceGradZvals, const std::vector<Eigen::Vector2cd>& tarGradZvals,\n                              const std::vector<std::complex<double>>& upSourceZvals, const std::vector<std::complex<double>>& upTarZvals,\n                              const int num, std::vector<Eigen::VectorXd>& magList, std::vector<Eigen::VectorXd>& phaseList,    // upsampled information\n                              std::vector<Eigen::MatrixXd>& wList, std::vector<std::vector<std::complex<double>>> &zvalList        // raw information\n                              )\n{\n\tmagList.resize(num + 2);\n\tphaseList.resize(num + 2);\n\twList.resize(num + 2);\n\tzvalList.resize(num + 2);\n\n\tdouble dt = 1.0 / (num + 1);\n\n\tauto computeMagPhase = [&](const tbb::blocked_range<uint32_t>& range) {\n\t\tfor (uint32_t i = range.begin(); i < range.end(); ++i)\n\t\t{\n\t\t\tdouble w = i * dt;\n\t\t\tmagList[i].setZero(upSourceZvals.size());\n\t\t\tphaseList[i].setZero(upSourceZvals.size());\n\t\t\tfor (int j = 0; j < upSourceZvals.size(); j++)\n\t\t\t{\n\t\t\t    std::complex<double> z = (1 - w) * upSourceZvals[j] + w * upTarZvals[j];\n\t\t\t    magList[i][j] = std::abs(z);\n\t\t\t    phaseList[i][j] = std::arg(z);\n\t\t\t}\n\t\t\tEigen::MatrixXd vertOmega = Eigen::MatrixXd::Zero(sourceZvals.size(), 3);\n\t\t\tzvalList[i].resize(sourceZvals.size());\n\n\t\t\tfor(int j = 0; j < sourceZvals.size(); j++)\n\t\t\t{\n\t\t\t    Eigen::Vector2cd gradf = (1 - w) * sourceGradZvals[j] + w * tarGradZvals[j];\n\t\t\t    std::complex<double> fbar = (1 - w) * std::conj(sourceZvals[j]) + w * std::conj(tarZvals[j]);\n\n\t\t\t\tvertOmega.row(j).segment<2>(0) = ((gradf * fbar) / (std::abs(fbar) * std::abs(fbar))).imag();\n\t\t\t    zvalList[i][j] = (1 - w) * sourceZvals[j] + w * tarZvals[j];\n\t\t\t}\n\t\t\twList[i] = vertexVec2IntrinsicHalfEdgeVec(vertOmega, triV, triMesh);\n\t\t}\n\t};\n\n\ttbb::blocked_range<uint32_t> rangex(0u, (uint32_t)(num + 2), GRAIN_SIZE);\n\ttbb::parallel_for(rangex, computeMagPhase);\n}\n\nvoid registerMeshByPart(const Eigen::MatrixXd& basePos, const Eigen::MatrixXi& baseF,\n\tconst Eigen::MatrixXd& upPos, const Eigen::MatrixXi& upF, const double& shifty, const double& ampMax,\n\tEigen::VectorXd ampVec, const Eigen::VectorXd& phaseVec,\n\tEigen::VectorXd theoAmpVec, const Eigen::VectorXd& theoPhaseVec,\n\tEigen::MatrixXd& renderV, Eigen::MatrixXi& renderF, Eigen::MatrixXd& renderColor)\n{\n\tint nverts = basePos.rows();\n\tint nfaces = baseF.rows();\n\n\tint nupverts = upPos.rows();\n\tint nupfaces = upF.rows();\n\n\tint ndataVerts = nverts + 4 * nupverts;\n\tint ndataFaces = nfaces + 4 * nupfaces;\n\t\n\trenderV.resize(ndataVerts, 3);\n\trenderF.resize(ndataFaces, 3);\n\trenderColor.setZero(ndataVerts, 3);\n\n\trenderColor.col(0).setConstant(1.0);\n\trenderColor.col(1).setConstant(1.0);\n\trenderColor.col(2).setConstant(1.0);\n\n\tint curVerts = 0;\n\tint curFaces = 0;\n\n\tEigen::VectorXd normalizedAmp = ampVec / ampMax, normalizedTheoAmp = theoAmpVec / ampMax;\n\n\n\tEigen::MatrixXd shiftV = basePos;\n\tshiftV.col(0).setConstant(0);\n\tshiftV.col(1).setConstant(shifty);\n\tshiftV.col(2).setConstant(0);\n\n\trenderV.block(0, 0, nverts, 3) = basePos - shiftV;\n\trenderF.block(0, 0, nfaces, 3) = baseF;\n\tcurVerts += nverts; \n\tcurFaces += nfaces;\n\n\tdouble shiftx = 1.5 * (basePos.col(0).maxCoeff() - basePos.col(0).minCoeff());\n\n\tshiftV = upPos;\n\tshiftV.col(0).setConstant(shiftx);\n\tshiftV.col(1).setConstant(shifty);\n\tshiftV.col(2).setConstant(0);\n\n\n\tEigen::MatrixXi shiftF = upF;\n\tshiftF.setConstant(curVerts);\n\n\t// interpolated phase\n\trenderV.block(curVerts, 0, nupverts, 3) = upPos - shiftV;\n\trenderF.block(curFaces, 0, nupfaces, 3) = upF + shiftF;\n\n\tmPaint.setNormalization(false);\n\tEigen::MatrixXd phiColor = mPaint.paintPhi(phaseVec);\n\trenderColor.block(curVerts, 0, nupverts, 3) = phiColor;\n\n\tcurVerts += nupverts;\n\tcurFaces += nupfaces;\n\t\n\t// interpolated amp\n\tshiftF.setConstant(curVerts);\n\tshiftV.col(0).setConstant(2 * shiftx);\n\trenderV.block(curVerts, 0, nupverts, 3) = upPos - shiftV;\n\trenderF.block(curFaces, 0, nupfaces, 3) = upF + shiftF;\n\n\tmPaint.setNormalization(false);\n\tEigen::MatrixXd ampColor = mPaint.paintAmplitude(ampVec / globalAmpMax);\n\trenderColor.block(curVerts, 0, nupverts, 3) = ampColor;\n\n\tcurVerts += nupverts;\n\tcurFaces += nupfaces;\n\n\t// theoretical phase\n\tshiftF.setConstant(curVerts);\n\tshiftV.col(0).setConstant(3 * shiftx);\n\trenderV.block(curVerts, 0, nupverts, 3) = upPos - shiftV;\n\trenderF.block(curFaces, 0, nupfaces, 3) = upF + shiftF;\n\n\tmPaint.setNormalization(false);\n\tphiColor = mPaint.paintPhi(theoPhaseVec);\n\trenderColor.block(curVerts, 0, nupverts, 3) = phiColor;\n\n\tcurVerts += nupverts;\n\tcurFaces += nupfaces;\n\n\t// theoretical amp\n\tshiftF.setConstant(curVerts);\n\tshiftV.col(0).setConstant(4 * shiftx);\n\trenderV.block(curVerts, 0, nupverts, 3) = upPos - shiftV;\n\trenderF.block(curFaces, 0, nupfaces, 3) = upF + shiftF;\n\n\tmPaint.setNormalization(false);\n\tampColor = mPaint.paintAmplitude(theoAmpVec / globalAmpMax);\n\trenderColor.block(curVerts, 0, nupverts, 3) = ampColor;\n\n}\n\nvoid registerMesh(int frameId)\n{\n\tEigen::MatrixXd sourceP, tarP, interpP;\n\tEigen::MatrixXi sourceF, tarF, interpF;\n\tEigen::MatrixXd sourceColor, tarColor, interpColor;\n\n\tdouble shiftx = 1.5 * (triV.col(0).maxCoeff() - triV.col(0).minCoeff());\n\tdouble shifty = 1.5 * (triV.col(1).maxCoeff() - triV.col(1).minCoeff());\n\tint totalfames = ampFieldsList.size();\n\tregisterMeshByPart(triV, triF, upsampledTriV, upsampledTriF, 0, globalAmpMax, ampFieldsList[0], phaseFieldsList[0], theoAmpFieldsList[0], theoPhaseFieldsList[0], sourceP, sourceF, sourceColor);\n\tregisterMeshByPart(triV, triF, upsampledTriV, upsampledTriF, shifty, globalAmpMax, ampFieldsList[totalfames - 1], phaseFieldsList[totalfames - 1], theoAmpFieldsList[totalfames - 1], theoPhaseFieldsList[totalfames - 1], tarP, tarF, tarColor);\n\tregisterMeshByPart(triV, triF, upsampledTriV, upsampledTriF, 2 * shifty, globalAmpMax, ampFieldsList[frameId], phaseFieldsList[frameId], theoAmpFieldsList[frameId], theoPhaseFieldsList[frameId], interpP, interpF, interpColor);\n\n\t\n\tEigen::MatrixXi shifF = sourceF;\n\n\tint nPartVerts = sourceP.rows();\n\tint nPartFaces = sourceF.rows();\n\tint nverts = triV.rows();\n\tint nfaces = triF.rows();\n\n\n\tdataV.setZero(3 * nPartVerts + nverts, 3);\n\tcurColor.setZero(3 * nPartVerts + nverts, 3);\n\tdataF.setZero(3 * nPartFaces + nfaces, 3);\n\n\tshifF.setConstant(nPartVerts);\n\n\tdataV.block(0, 0, nPartVerts, 3) = sourceP;\n\tcurColor.block(0, 0, nPartVerts, 3) = sourceColor;\n\tdataF.block(0, 0, nPartFaces, 3) = sourceF;\n\n\tdataV.block(nPartVerts, 0, nPartVerts, 3) = tarP;\n\tcurColor.block(nPartVerts, 0, nPartVerts, 3) = tarColor;\n\tdataF.block(nPartFaces, 0, nPartFaces, 3) = tarF + shifF;\n\n\tdataV.block(nPartVerts * 2, 0, nPartVerts, 3) = interpP;\n\tcurColor.block(nPartVerts * 2, 0, nPartVerts, 3) = interpColor;\n\tdataF.block(nPartFaces * 2, 0, nPartFaces, 3) = interpF + 2 * shifF;\n\n\tEigen::MatrixXd shiftV = triV;\n\tshiftV.col(0).setConstant(shiftx);\n\tshiftV.col(1).setConstant(-2 * shifty);\n\tshiftV.col(2).setZero();\n\n\tshifF = triF;\n\tshifF.setConstant(3 * nPartVerts);\n\n\tdataV.block(nPartVerts * 3, 0, nverts, 3) = triV + shiftV;\n\tcurColor.block(nPartVerts * 3, 0, nverts, 3).setConstant(1.0);\n\tdataF.block(nPartFaces * 3, 0, nfaces, 3) = triF + shifF;\n\n\tpolyscope::registerSurfaceMesh(\"input mesh\", dataV, dataF);\n\n}\n\nvoid updateFieldsInView(int frameId)\n{\n\tregisterMesh(frameId);\n\tpolyscope::getSurfaceMesh(\"input mesh\")->addVertexColorQuantity(\"VertexColor\", curColor);\n\tpolyscope::getSurfaceMesh(\"input mesh\")->getQuantity(\"VertexColor\")->setEnabled(true);\n\n\t/*polyscope::getSurfaceMesh(\"input mesh\")->addVertexVectorQuantity(\"vertex vector field\", dataVec * vecratio, polyscope::VectorType::AMBIENT);\n\tpolyscope::getSurfaceMesh(\"input mesh\")->getQuantity(\"vertex vector field\")->setEnabled(true);*/\n}\n\n\nvoid callback() {\n\tImGui::PushItemWidth(100);\n\tif (ImGui::Button(\"Reset\", ImVec2(-1, 0)))\n\t{\n\t\tcurFrame = 0;\n\t\tupdateFieldsInView(curFrame);\n\t}\n\t\n\tif (ImGui::InputDouble(\"triangle area\", &triarea))\n\t{\n\t\tif (triarea > 0)\n\t\t\tinitialization();\n\t}\n\tif (ImGui::Checkbox(\"Two Triangle Mesh\", &isTwoTriangles))\n\t{\n\t\tinitialization();\n\t}\n\tif (ImGui::InputInt(\"upsampled times\", &loopLevel))\n\t{\n\t\tif (loopLevel >= 0)\n\t\t\tinitialization();\n\t}\n\n\tif (ImGui::CollapsingHeader(\"source Vector Fields Info\", ImGuiTreeNodeFlags_DefaultOpen))\n\t{\n\t\tif (ImGui::Combo(\"source vec types\", (int*)&functionType, \"Whirl pool\\0plane wave\\0sum\\0Y shape\\0Two Whirl Pool\\0Periodic\\0\\0\")) {}\n\t\tif (ImGui::Checkbox(\"Fixed source center and dir\", &isFixedSource)) {}\n\n\t\tif (ImGui::CollapsingHeader(\"source whirl  pool Info\"))\n\t\t{\n\t\t    if (ImGui::InputInt(\"source singularity index 1\", &singIndSource)){}\n\t\t    if (ImGui::InputDouble(\"source center 1 x: \", &sourceCenter1x)) {}\n\t\t    ImGui::SameLine();\n\t\t    if (ImGui::InputDouble(\"source center 1 y: \", &sourceCenter1y)) {}\n\n\t\t    if (ImGui::InputInt(\"source singularity index 2\", &singIndSource1)){}\n\t\t    if (ImGui::InputDouble(\"source center 2 x: \", &sourceCenter2x)) {}\n\t\t    ImGui::SameLine();\n\t\t    if (ImGui::InputDouble(\"source center 2 y: \", &sourceCenter2y)) {}\n\t\t}\n\n\t\tif (ImGui::CollapsingHeader(\"source plane wave Info\"))\n\t\t{\n\t\t    if (ImGui::InputInt(\"source num waves\", &numWavesSource)){}\n\t\t    if (ImGui::InputDouble(\"source dir x: \", &sourceDirx)) {}\n\t\t    ImGui::SameLine();\n\t\t    if (ImGui::InputDouble(\"source dir y: \", &sourceDiry)) {}\n\t\t}\n\n\t}\n\tif (ImGui::CollapsingHeader(\"target Vector Fields Info\", ImGuiTreeNodeFlags_DefaultOpen))\n\t{\n\t\tif (ImGui::Combo(\"target vec types\", (int*)&tarFunctionType, \"Whirl pool\\0plane wave\\0sum\\0Y shape\\0Two Whirl Pool\\0Periodic\\0\\0\")) {}\n\n\t\tif (ImGui::Checkbox(\"Fixed target center and dir\", &isFixedTar)) {}\n\t\tif (ImGui::CollapsingHeader(\"target whirl  pool Info\"))\n\t\t{\n\t\t    if (ImGui::InputInt(\"target singularity index 1\", &singIndTar)) {}\n\t\t    if (ImGui::InputDouble(\"target center 1 x: \", &targetCenter1x)) {}\n\t\t    ImGui::SameLine();\n\t\t    if (ImGui::InputDouble(\"target center 1 y: \", &targetCenter1y)) {}\n\n\t\t    if (ImGui::InputInt(\"target singularity index 2\", &singIndTar1)) {}\n\t\t    if (ImGui::InputDouble(\"target center 2 x: \", &targetCenter2x)) {}\n\t\t    ImGui::SameLine();\n\t\t    if (ImGui::InputDouble(\"target center 2 y: \", &targetCenter2y)) {}\n\t\t}\n\n\t\tif (ImGui::CollapsingHeader(\"target plane wave Info\"))\n\t\t{\n\t\t    if (ImGui::InputInt(\"target num waves\", &numWaveTar)){}\n\t\t    if (ImGui::InputDouble(\"target dir x: \", &sourceDirx)) {}\n\t\t    ImGui::SameLine();\n\t\t    if (ImGui::InputDouble(\"target dir y: \", &sourceDiry)) {}\n\t\t}\n\n\n\t}\n\n\tif (ImGui::InputInt(\"num of frames\", &numFrames))\n\t{\n\t\tif (numFrames <= 0)\n\t\t\tnumFrames = 10;\n\t}\n\n\tif (ImGui::InputDouble(\"drag speed\", &dragSpeed))\n\t{\n\t\tif (dragSpeed <= 0)\n\t\t\tdragSpeed = 0.5;\n\t}\n\n\tif (ImGui::DragInt(\"current frame\", &curFrame, dragSpeed, 0, numFrames + 1))\n\t{\n\t\tupdateFieldsInView(curFrame);\n\t}\n\tif (ImGui::DragFloat(\"vec ratio\", &(vecratio), 0.005, 0, 1))\n\t{\n\t\tupdateFieldsInView(curFrame);\n\t}\n\tif (ImGui::CollapsingHeader(\"optimzation parameters\", ImGuiTreeNodeFlags_DefaultOpen))\n\t{\n\t\tif (ImGui::InputInt(\"num iterations\", &numIter))\n\t\t{\n\t\t\tif (numIter < 0)\n\t\t\t\tnumIter = 1000;\n\t\t}\n\t\tif (ImGui::InputDouble(\"grad tol\", &gradTol))\n\t\t{\n\t\t\tif (gradTol < 0)\n\t\t\t\tgradTol = 1e-6;\n\t\t}\n\t\tif (ImGui::InputDouble(\"x tol\", &xTol))\n\t\t{\n\t\t\tif (xTol < 0)\n\t\t\t\txTol = 0;\n\t\t}\n\t\tif (ImGui::InputDouble(\"f tol\", &fTol))\n\t\t{\n\t\t\tif (fTol < 0)\n\t\t\t\tfTol = 0;\n\t\t}\n\t\tif (ImGui::InputInt(\"quad order\", &quadOrder))\n\t\t{\n\t\t    if (quadOrder <= 0 || quadOrder > 20)\n\t\t        quadOrder = 4;\n\t\t}\n\t\tImGui::Checkbox(\"use upsampled mesh\", &isUseUpMesh);\n\n\t}\n\tif (ImGui::Combo(\"initialization types\", (int*)&initializationType, \"Random\\0Linear\\0Theoretical\\0\")) {}\n\n\tImGui::Checkbox(\"Try Optimization\", &isForceOptimize);\n\n\tif (ImGui::Button(\"update values\", ImVec2(-1, 0)))\n\t{\n\t\tdouble fixedx = 0;\n\t\tdouble fixedy = 0;\n\t\tEigen::Vector2d fixedv(1, 0);\n\t\t// source vector fields\n\t\tif(isFixedSource)\n\t\t{\n\t\t    fixedx = sourceCenter1x;\n\t\t    fixedy = sourceCenter1y;\n\t\t    fixedv << sourceDirx, sourceDiry;\n\t\t    fixedv *= numWavesSource * 2 * M_PI;\n\t\t}\n\t\tgenerateValues(functionType, sourceOmegaFields, sourceZvals, sourceTheoGradZvals, upsampledTheoZVals, singIndSource, singIndSource1, isFixedSource, fixedx, fixedy, fixedv);\n\t\t/*std::cout << \"triV: \\n\" << triV << std::endl;\n\n\t\tstd::cout << fixedv.transpose() << std::endl;\n\t\tfor (int i = 0; i < sourceOmegaFields.rows(); i++)\n\t\t{\n\t\t\tstd::cout << \"edge id: \" << i << \", vid: \" << triMesh.edgeVertex(i, 0) << \", zval: \" << sourceZvals[triMesh.edgeVertex(i, 0)] << \",  \" << triMesh.edgeVertex(i, 1) << \" \" << sourceZvals[triMesh.edgeVertex(i, 1)] << \", w: \" << sourceOmegaFields(i) << std::endl;\n\t\t}*/\n\t\t\n\n\t\tif(isFixedTar)\n\t\t{\n\t\t   fixedx = targetCenter1x;\n\t\t   fixedy = targetCenter1y;\n\t\t   fixedv << targetDirx, targetDiry;\n\t\t   fixedv *= numWaveTar * 2 * M_PI;\n\t\t}\n\t\t// target vector fields\n\t\tgenerateValues(tarFunctionType, tarOmegaFields, tarZvals, tarTheoGradZvals, upsampledTarTheoZVals, singIndTar, singIndTar1, isFixedTar, fixedx, fixedy, fixedv);\n\n\t\t// update the theoretic ones\n\t\tupdateTheoMagnitudePhase(sourceZvals, tarZvals, sourceTheoGradZvals, tarTheoGradZvals, upsampledTheoZVals, upsampledTarTheoZVals, numFrames, theoAmpFieldsList, theoPhaseFieldsList, theoOmegaList, theoZList);\n\n\t\t// solve for the path from source to target\n\t\tsolveKeyFrames(sourceOmegaFields, tarOmegaFields, sourceZvals, tarZvals, numFrames, omegaList, zList);\n\t\t// get interploated amp and phase frames\n\t\tupdateMagnitudePhase(omegaList, zList, ampFieldsList, phaseFieldsList);\n\n\t\t// update amp max\n\t\tif (theoAmpFieldsList.size() > 0)\n\t\t{\n\t\t\tglobalAmpMax = theoAmpFieldsList[0].maxCoeff();\n\t\t\tfor (int i = 0; i < theoAmpFieldsList.size(); i++)\n\t\t\t{\n\t\t\t\tglobalAmpMax = std::max(theoAmpFieldsList[i].maxCoeff(), globalAmpMax);\n\t\t\t\tglobalAmpMax = std::max(ampFieldsList[i].maxCoeff(), globalAmpMax);\n\t\t\t}\n\t\t}\n\t\t\n\t\tupdateFieldsInView(curFrame);\n\t\t\t\n\t}\n\n\tImGui::PopItemWidth();\n}\n\n\n\n\nint main(int argc, char** argv)\n{\n\tinitialization();\n//\n//\tEigen::MatrixXd testV(3, 3);\n//\ttestV << 0, 0, 0,\n//\t\t1, 0, 0,\n//\t\t0, 1, 0;\n//\tEigen::MatrixXi testF(1, 3);\n//\ttestF << 0, 1, 2;\n//\n//\tMeshConnectivity testMesh(testF);\n//\n//\tEigen::MatrixXd testw(3, 3), testw1;\n//\ttestw << 1, -1, 0,\n//\t\t1, 2, 0,\n//\t\t-1, 0, 0;\n//\n//\ttestw1 = testw;\n//\ttestw1.block<3, 2>(0, 0).setRandom();\n//\n//\tEigen::Vector3d testbary;\n//\tstd::vector<std::complex<double>> testZvals(3), testZvals1(3);\n//\ttestZvals[0] = std::complex<double>(0.1, 0.8);\n//\ttestZvals[1] = std::complex<double>(0.7, 0.3);\n//\ttestZvals[2] = std::complex<double>(0.34, 7.8);\n//\n//\ttestZvals1[0] = std::complex<double>(0.5, 0.6);\n//\ttestZvals1[1] = std::complex<double>(0.7, 0.4);\n//\ttestZvals1[2] = std::complex<double>(0.4, 0.8);\n//\n//\n//\tEigen::Matrix<double, 3, 2> edgew = vertexVec2IntrinsicHalfEdgeVec(testw, testV, testMesh);\n//\tEigen::Matrix<double, 3, 2> edgew1 = vertexVec2IntrinsicHalfEdgeVec(testw1, testV, testMesh);\n//\n//\tfor (int i = 0; i < 3; i++)\n//\t{\n//\t    int eid = testMesh.faceEdge(0, i);\n//\t\tstd::cout << \"eid: \" << eid << \", v0: \" << testMesh.edgeVertex(eid, 0) << \", v1: \" << testMesh.edgeVertex(eid, 1) << std::endl;\n//\t\tstd::cout << \"edge w: \" << edgew.row(eid) << std::endl;\n//\t}\n//\tint testqid = 3;\n//\tComputeZandZdot preModel(testV, testF, 4);\n//\ttestbary << 1 - preModel.getQuadPts()[testqid].u - preModel.getQuadPts()[testqid].v, preModel.getQuadPts()[testqid].u, preModel.getQuadPts()[testqid].v;\n//\n//\tEigen::VectorXd testFaceArea;\n//\tigl::doublearea(testV, testF, testFaceArea);\n//\ttestFaceArea /= 2;\n//\tIntrinsicFormula::ComputeZdotFromHalfEdgeOmega zdotmodel1(MeshConnectivity(testF), testFaceArea, 4, 0.1);\n//\n//\tdouble zdotnorm = zdotmodel1.computeZdotIntegration(testZvals, edgew, testZvals1, edgew1, NULL, NULL);\n//\tdouble zdotnorm1 = preModel.zDotSquareIntegration(testw.block<3, 2>(0, 0), testw1.block<3, 2>(0, 0), testZvals, testZvals1, 0.1, NULL, NULL);\n//\n//\tstd::cout << \"zdot: \" << zdotnorm << \", \" << \"zdot1: \" << zdotnorm1 << std::endl;\n//\n//\tIntrinsicFormula::IntrinsicKeyFrameInterpolationFromHalfEdge halfEdgeFormula(testMesh, testFaceArea, 50, 4, testZvals, edgew, testZvals1, edgew1);\n//\tEigen::VectorXd x;\n//\thalfEdgeFormula.convertList2Variable(x);\n//\tzdotnorm = halfEdgeFormula.computeEnergy(x);\n//\n//\tEigen::MatrixXd uptestV;\n//\tEigen::MatrixXi uptestF;\n//\n//\tstd::vector<std::pair<int, Eigen::Vector3d>> testBary;\n//    meshUpSampling(testV, testF, uptestV, uptestF, 2, NULL, NULL, &testBary);\n//\n//    InterpolateKeyFrames interpModelTest(testV, testF, uptestV, uptestF, testBary, testw.block<3, 2>(0, 0), testw1.block<3, 2>(0, 0), testZvals, testZvals1, 50, 4, false);\n//    interpModelTest.convertList2Variable(x);\n//    zdotnorm1 = interpModelTest.computeEnergy(x);\n\n//    std::cout << \"zdot: \" << zdotnorm << \", \" << \"zdot1: \" << zdotnorm1 << std::endl;\n//\tIntrinsicFormula::testZvalsFromHalfEdgeOmega(testbary, testZvals, edgew);\n//\tEigen::VectorXd faceArea;\n//\n//\tigl::doublearea(triV, triF, faceArea);\n//\tstd::vector<std::complex<double>> testZvals0(triV.rows()), testZvals1(triV.rows());\n//\tfor (int i = 0; i < triV.rows(); i++)\n//\t{\n//\t\tEigen::Vector2d randvec;\n//\t\trandvec.setRandom();\n//\t\ttestZvals0[i] = std::complex<double>(randvec(0), randvec(1));\n//\n//\t\trandvec.setRandom();\n//\t\ttestZvals1[i] = std::complex<double>(randvec(0), randvec(1));\n//\t}\n//\tEigen::MatrixXd edgew0, edgew1;\n//\tedgew0.setRandom(triMesh.nEdges(), 2);\n//\tedgew1.setRandom(triMesh.nEdges(), 2);\n//\n//\tIntrinsicFormula::ComputeZdotFromHalfEdgeOmega testmodel(triMesh, faceArea, 4, 1);\n//\ttestmodel.testZdotIntegrationPerface(testZvals0, edgew0, testZvals1, edgew1, 0);\n//\n//\tIntrinsicFormula::IntrinsicKeyFrameInterpolationFromHalfEdge halfedgemodel(triMesh, faceArea, 3, 4, testZvals0, edgew0, testZvals1, edgew1);\n//\tEigen::VectorXd testx;\n//\thalfedgemodel.convertList2Variable(testx);\n//\thalfedgemodel.testEnergy(testx);\n\n\t// Options\n    polyscope::options::autocenterStructures = true;\n    polyscope::view::windowWidth = 1024;\n    polyscope::view::windowHeight = 1024;\n\n    // Initialize polyscope\n    polyscope::init();\n\n\n    // Register the mesh with Polyscope\n    polyscope::registerSurfaceMesh(\"input mesh\", triV, triF);\n\n\n\n    // Add the callback\n    polyscope::state::userCallback = callback;\n\n    polyscope::options::groundPlaneHeightFactor = 0.25; // adjust the plane height\n    // Show the gui\n    polyscope::show();\n\n    return 0;\n}", "meta": {"hexsha": "c52acf41de4d511dcd0151aa4a4a6e6a52fe8f41", "size": 41302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/viewer2d/main.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": "app/viewer2d/main.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": "app/viewer2d/main.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": 32.9099601594, "max_line_length": 375, "alphanum_fraction": 0.6506706697, "num_tokens": 13688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5403019852340322}}
{"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_ARCH_COMMON_SCALAR_FUNCTION_TENPOWER_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_TENPOWER_HPP_INCLUDED\n\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/ten.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/is_odd.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/detail/dispatch/meta/as_floating.hpp>\n#include <boost/config.hpp>\n#include <boost/mpl/if.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( tenpower_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::int_<A0> >\n                          )\n  {\n    using result_t = bd::as_floating_t<A0>;\n    BOOST_FORCEINLINE result_t operator() ( A0 exp) const BOOST_NOEXCEPT\n    {\n\n      result_t result = One<result_t>();\n      result_t base = Ten<result_t>();\n      auto neg = is_ltz(exp);\n      exp =  boost::simd::abs(exp);\n      while(exp)\n      {\n        if (is_odd(exp)) result *= base;\n        exp >>= 1;\n        base = sqr(base);\n      }\n      return neg ? rec(result) : result;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( tenpower_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::uint_<A0> >\n                          )\n  {\n    using result_t = bd::as_floating_t<A0>;\n    BOOST_FORCEINLINE result_t operator() ( A0 exp) const BOOST_NOEXCEPT\n    {\n      result_t result = One<result_t>();\n      result_t base = Ten<result_t>();\n      while(exp)\n      {\n        if (is_odd(exp)) result *= base;\n        exp >>= 1;\n        base = sqr(base);\n      }\n      return result;\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "0e61b51f3f310be0be5f49527034863e1bf215e4", "size": 2293, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/tenpower.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/arch/common/scalar/function/tenpower.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/arch/common/scalar/function/tenpower.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": 29.7792207792, "max_line_length": 100, "alphanum_fraction": 0.5455734845, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5403019783008803}}
{"text": "#pragma once\n\n#include <boost/random/random_number_generator.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\nnamespace calotypes\n{\n\n/*! \\brief Boost-based reservoir sampling implementation. Best used when sampling\n * a medium subset. */\ntemplate<class Engine>\nvoid ReservoirSampling( unsigned int numItems, unsigned int subsetSize,\n\t\t\t\t\t\tstd::vector<unsigned int>& inds, Engine& engine )\n{\n\tinds.resize( subsetSize );\n\tfor( unsigned int i = 0; i < subsetSize; i++ )\n\t{\n\t\tinds[i] = i;\n\t}\n\t\n\tfor( unsigned int i = subsetSize; i < numItems; i++ )\n\t{\n\t\tboost::random::uniform_int_distribution<> dist( 0, i ); // i inclusive\n\t\tunsigned int j = (unsigned int) dist( engine );\n\t\tstd::cout << \"j: \" << j << \" \";\n\t\tif( j < subsetSize )\n\t\t{\n\t\t\tinds[j] = i;\n\t\t}\n\t}\n\tstd::cout << std::endl;\n}\n\t\n/*! \\brief Boost-based brute force sampling implementation. Best used when\n * sampling a small subset. */\ntemplate<class Engine>\nvoid BitmapSampling( unsigned int numItems, unsigned int subsetSize,\n\t\t\t\t\t std::vector<unsigned int>& inds, Engine& engine )\n{\n\tinds.resize( subsetSize );\n\t\n\tstd::vector<bool> bitmap( numItems, false );\n\tunsigned int count = 0;\n\tboost::random::uniform_int_distribution<> dist( 0, numItems - 1 );\n\twhile( count < subsetSize )\n\t{\n\t\tunsigned int j = (unsigned int) dist( engine );\n\t\tif( bitmap[j] ) { continue; }\n\t\tbitmap[j] = true;\n\t\tinds[count] = j;\n\t\tcount++;\n\t}\n\t\n}\n\t\n} // end namespace calotypes\n", "meta": {"hexsha": "6446d26b802712ac5a574bfffdacc83c09a62efd", "size": 1421, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/calotypes/SubsetSamplers.hpp", "max_stars_repo_name": "Humhu/calotypes", "max_stars_repo_head_hexsha": "a05a809b3b27983332c24d8fb04cb71f47e96763", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-18T14:59:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-18T14:59:39.000Z", "max_issues_repo_path": "include/calotypes/SubsetSamplers.hpp", "max_issues_repo_name": "Humhu/calotypes", "max_issues_repo_head_hexsha": "a05a809b3b27983332c24d8fb04cb71f47e96763", "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/calotypes/SubsetSamplers.hpp", "max_forks_repo_name": "Humhu/calotypes", "max_forks_repo_head_hexsha": "a05a809b3b27983332c24d8fb04cb71f47e96763", "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.9298245614, "max_line_length": 81, "alphanum_fraction": 0.6713581985, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5403019756541593}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_IEEE_FUNCTIONS_SCALAR_NEXTPOW2_HPP_INCLUDED\n#define BOOST_SIMD_IEEE_FUNCTIONS_SCALAR_NEXTPOW2_HPP_INCLUDED\n#include <boost/simd/ieee/functions/nextpow2.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/include/constants/half.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/include/functions/scalar/frexp.hpp>\n#include <boost/simd/include/functions/scalar/tofloat.hpp>\n#include <boost/simd/include/functions/scalar/minusone.hpp>\n#include <boost/simd/include/functions/scalar/abs.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::nextpow2_, tag::cpu_,\n                          (A0),\n                          (scalar_ < arithmetic_<A0> > )\n                         )\n  {\n    typedef typename dispatch::meta::as_integer<typename boost::dispatch::meta::as_floating<A0>::type, signed>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return boost::simd::nextpow2(tofloat(a0));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::nextpow2_, tag::cpu_,\n                          (A0),\n                          (scalar_ < floating_<A0> > )\n                         )\n  {\n    typedef typename dispatch::meta::as_integer<A0, signed>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      A0 m;\n      result_type p;\n      boost::simd::frexp(boost::simd::abs(a0), m, p);\n      return (m == Half<A0>())  ? minusone(p) :  p;\n    }\n  };\n} } }\n#endif\n", "meta": {"hexsha": "3cb94a2bdb9f1da2d97a917f721b5306cf10efb3", "size": 2001, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/ieee/include/boost/simd/ieee/functions/scalar/nextpow2.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/ieee/include/boost/simd/ieee/functions/scalar/nextpow2.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/ieee/include/boost/simd/ieee/functions/scalar/nextpow2.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": 40.02, "max_line_length": 129, "alphanum_fraction": 0.5912043978, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5403019735109437}}
{"text": "#include <bits/stdc++.h>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main()\n{\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        int n;\n        cpp_int fact = 1;\n        cin >> n;\n        while (n != 0)\n        {\n            fact *= n--;\n        }\n        cout << fact << endl;\n    }\n    return 0;\n}", "meta": {"hexsha": "537c6bb7d88c2534bdc72eca1853c6ca0d801c72", "size": 367, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Practice Programs/small_factorials1.cpp", "max_stars_repo_name": "SR-Sunny-Raj/CPP_Language_Programs", "max_stars_repo_head_hexsha": "3e10a365187f70cc473c5b62155ff51dc12e38b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T17:59:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T17:21:42.000Z", "max_issues_repo_path": "Practice Programs/small_factorials1.cpp", "max_issues_repo_name": "SR-Sunny-Raj/CPP_Language_Programs", "max_issues_repo_head_hexsha": "3e10a365187f70cc473c5b62155ff51dc12e38b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Practice Programs/small_factorials1.cpp", "max_forks_repo_name": "SR-Sunny-Raj/CPP_Language_Programs", "max_forks_repo_head_hexsha": "3e10a365187f70cc473c5b62155ff51dc12e38b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-10-02T14:38:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T06:19:22.000Z", "avg_line_length": 17.4761904762, "max_line_length": 43, "alphanum_fraction": 0.4741144414, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.540255834211753}}
{"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\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/morton_dense.hpp> \n#include <boost/numeric/mtl/matrix/transposed_view.hpp>\n#include <boost/numeric/mtl/recursion/predefined_masks.hpp>\n#include <boost/numeric/mtl/matrix/compressed2D.hpp>\n#include <boost/numeric/mtl/matrix/laplacian_setup.hpp>\n\n#include <boost/numeric/mtl/operation/print_matrix.hpp>\n#include <boost/numeric/mtl/operation/trace.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    laplacian_setup(a, dim1, dim2);\n\n    std::cout << \"\\n\" << name << \" a = \\n\" << a << \"\\n\"\n\t      << \"trace(a) = \" << trace(a) << \"\\n\"; std::cout.flush();\n\n    // Due to rounding errors, dimensions shouldn't be too large (or test less naive)\n    MTL_THROW_IF(trace(a) != 4.0 * int(dim1*dim2), mtl::runtime_error(\"wrong trace\")); \n}\n\n\nint main(int argc, char* argv[])\n{\n    using namespace mtl;\n    unsigned dim1= 3, dim2= 2;\n\n    if (argc > 2) {dim1= atoi(argv[1]);dim2= atoi(argv[2]);}\n    unsigned size= dim1 * dim2; \n\n    dense2D<double>                                      dr(size, size), dr2(0,0);\n    dense2D<double, mat::parameters<col_major> >      dc(size, size);\n    morton_dense<double, recursion::morton_z_mask>       mzd(size, size);\n    morton_dense<double, recursion::doppled_2_row_mask>  d2r(size, size);\n    compressed2D<double>                                 cr(size, size);\n    compressed2D<double, mat::parameters<col_major> > cc(size, size);\n\n    dense2D<complex<double> >                            drc(size, size);\n    compressed2D<complex<double> >                       crc(size, size);\n\n    test(dr, dim1, dim2, \"Dense row major\");\n    test(dc, dim1, dim2, \"Dense column major\");\n    test(mzd, dim1, dim2, \"Morton Z-order\");\n    test(d2r, dim1, dim2, \"Hybrid 2 row-major\");\n    test(cr, dim1, dim2, \"Compressed row major\");\n    test(cc, dim1, dim2, \"Compressed column major\");\n    test(drc, dim1, dim2, \"Dense row major complex\");\n    test(crc, dim1, dim2, \"Compressed row major complex\");\n    test(dr2, 0, 0, \"Dense row major\");\n\n    return 0;\n}\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "16df10c559c2cd0db785c568f61c0d0207cadfe0", "size": 2636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/trace_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/trace_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/trace_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 29.6179775281, "max_line_length": 94, "alphanum_fraction": 0.6399848255, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5402558264501657}}
{"text": "/**\n * @file tests/cosine_tree_test.cpp\n * @author Siddharth Agrawal\n *\n * Test file for CosineTree class.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n\n#include <mlpack/core.hpp>\n#include <mlpack/core/tree/cosine_tree/cosine_tree.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nBOOST_AUTO_TEST_SUITE(CosineTreeTest);\n\nusing namespace mlpack;\nusing namespace mlpack::tree;\n\n/**\n * Constructs a cosine tree with epsilon = 1. Checks if the root node is split\n * further, as it shouldn't be.\n */\nBOOST_AUTO_TEST_CASE(CosineTreeNoSplit)\n{\n  // Initialize constants required for the test.\n  const size_t numRows = 10;\n  const size_t numCols = 15;\n  const double epsilon = 1;\n  const double delta = 0.1;\n\n  // Make a random dataset.\n  arma::mat data = arma::randu(numRows, numCols);\n\n  // Make a cosine tree, with the generated dataset and the defined constants.\n  // Note that the value of epsilon is one.\n  CosineTree ctree(data, epsilon, delta);\n  arma::mat basis;\n  ctree.GetFinalBasis(basis);\n\n  // Since epsilon is one, there should be no splitting and the only vector in\n  // the basis should come from the root node.\n  BOOST_REQUIRE_EQUAL(basis.n_cols, 1);\n}\n\n/**\n * Checks CosineTree::CosineNodeSplit() by doing a depth first search on a\n * random dataset and checking if it satisfies the split condition.\n */\nBOOST_AUTO_TEST_CASE(CosineNodeCosineSplit)\n{\n  // Initialize constants required for the test.\n  const size_t numRows = 500;\n  const size_t numCols = 1000;\n  // Calculation accuracy.\n  const double precision = 1e-15;\n\n  // Make a random dataset and the root object.\n  arma::mat data = arma::randu(numRows, numCols);\n  CosineTree root(data);\n\n  // Stack for depth first search of the tree.\n  std::vector<CosineTree*> nodeStack;\n  nodeStack.push_back(&root);\n\n  // While stack is not empty.\n  while (nodeStack.size())\n  {\n    // Pop a node from the stack and split it.\n    CosineTree *currentNode, *currentLeft, *currentRight;\n    currentNode = nodeStack.back();\n    currentNode->CosineNodeSplit();\n    nodeStack.pop_back();\n\n    // Obtain pointers to the children of the node.\n    currentLeft = currentNode->Left();\n    currentRight = currentNode->Right();\n\n    // If children exist.\n    if (currentLeft && currentRight)\n    {\n      // Push the child nodes on to the stack.\n      nodeStack.push_back(currentLeft);\n      nodeStack.push_back(currentRight);\n\n      // Obtain the split point of the popped node.\n      arma::vec splitPoint = data.col(currentNode->SplitPointIndex());\n\n      // Column indices of the the child nodes.\n      std::vector<size_t> leftIndices, rightIndices;\n      leftIndices = currentLeft->VectorIndices();\n      rightIndices = currentRight->VectorIndices();\n\n      // The columns in the popped should be split into left and right nodes.\n      BOOST_REQUIRE_EQUAL(currentNode->NumColumns(), leftIndices.size() +\n          rightIndices.size());\n\n      // Calculate the cosine values for each of the columns in the node.\n      arma::vec cosines;\n      cosines.zeros(currentNode->NumColumns());\n\n      size_t i, j, k;\n      for (i = 0; i < leftIndices.size(); i++)\n        cosines(i) = arma::norm_dot(data.col(leftIndices[i]), splitPoint);\n\n      for (j = 0, k = i; j < rightIndices.size(); j++, k++)\n        cosines(k) = arma::norm_dot(data.col(rightIndices[j]), splitPoint);\n\n      // Check if the columns assigned to the children agree with the splitting\n      // condition.  Due to miscalculations cosineMax calculated by\n      // CosineNodeSplit may differ from cosineMax below, so we have to handle\n      // minor differences.\n      double cosineMax = arma::max(cosines % (cosines < 1.0 + precision));\n      double cosineMin = arma::min(cosines);\n      // If max(cosines) is close to 1.0 cosineMax and cosineMax2 may\n      // differ significantly.\n      double cosineMax2 = arma::max(cosines % (cosines < 1.0 - precision));\n\n\n      if (std::fabs(cosineMax - cosineMax2) < precision)\n      {\n        // Check with some precision.\n        for (i = 0; i < leftIndices.size(); i++)\n          BOOST_REQUIRE_LT(cosineMax - cosines(i),\n                           cosines(i) - cosineMin + precision);\n\n        for (j = 0, k = i; j < rightIndices.size(); j++, k++)\n          BOOST_REQUIRE_GT(cosineMax - cosines(k),\n                           cosines(k) - cosineMin - precision);\n      }\n      else\n      {\n        size_t numMax1Errors = 0;\n        size_t numMax2Errors = 0;\n\n        // Find errors for cosineMax.\n        for (i = 0; i < leftIndices.size(); i++)\n          if (cosineMax - cosines(i) >= cosines(i) - cosineMin + precision)\n            numMax1Errors++;\n\n        for (j = 0, k = i; j < rightIndices.size(); j++, k++)\n          if (cosineMax - cosines(k) <= cosines(k) - cosineMin - precision)\n            numMax1Errors++;\n\n        // Find errors for cosineMax2.\n        for (i = 0; i < leftIndices.size(); i++)\n          if (cosineMax2 - cosines(i) >= cosines(i) - cosineMin + precision)\n            numMax2Errors++;\n\n        for (j = 0, k = i; j < rightIndices.size(); j++, k++)\n          if (cosineMax2 - cosines(k) <= cosines(k) - cosineMin - precision)\n            numMax2Errors++;\n\n        // One of the maximum cosine values should be correct\n        BOOST_REQUIRE_EQUAL(std::min(numMax1Errors, numMax2Errors), 0);\n      }\n    }\n  }\n}\n\n/**\n * Checks CosineTree::ModifiedGramSchmidt() by creating a random basis for the\n * vector subspace and checking if all the vectors are orthogonal to each other.\n */\nBOOST_AUTO_TEST_CASE(CosineTreeModifiedGramSchmidt)\n{\n  // Initialize constants required for the test.\n  const size_t numRows = 100;\n  const size_t numCols = 50;\n  const double epsilon = 1;\n  const double delta = 0.1;\n\n  // Make a random dataset.\n  arma::mat data = arma::randu(numRows, numCols);\n\n  // Declare a queue and a dummy CosineTree object.\n  CosineNodeQueue basisQueue;\n  CosineTree dummyTree(data, epsilon, delta);\n\n  for (size_t i = 0; i < numCols; i++)\n  {\n    // Make a new CosineNode object.\n    CosineTree* basisNode;\n    basisNode = new CosineTree(data);\n\n    // Use the columns of the dataset as random centroids.\n    arma::vec centroid = data.col(i);\n    arma::vec newBasisVector;\n\n    // Obtain the orthonormalized version of the centroid.\n    dummyTree.ModifiedGramSchmidt(basisQueue, centroid, newBasisVector);\n\n    // Check if the obtained vector is orthonormal to the basis vectors.\n    CosineNodeQueue::const_iterator j = basisQueue.begin();\n    CosineTree* currentNode;\n\n    for (; j != basisQueue.end(); j++)\n    {\n      currentNode = *j;\n      BOOST_REQUIRE_SMALL(arma::dot(currentNode->BasisVector(), newBasisVector),\n                          1e-5);\n    }\n\n    // Add the obtained vector to the basis.\n    basisNode->BasisVector(newBasisVector);\n    basisNode->L2Error(arma::randu());\n    basisQueue.push(basisNode);\n  }\n\n  // Deallocate memory given to the objects.\n  for (size_t i = 0; i < numCols; i++)\n  {\n    CosineTree* currentNode;\n    currentNode = basisQueue.top();\n    basisQueue.pop();\n\n    delete currentNode;\n  }\n}\n\n/**\n * Test the copy constructor & copy assignment using Cosine trees.\n */\nBOOST_AUTO_TEST_CASE(CopyConstructorAndOperatorCosineTreeTest)\n{\n  // Initialize constants required for the test.\n  const size_t numRows = 10;\n  const size_t numCols = 15;\n\n  // Vectors to hold depth-first traversal\n  // of the number of columns in each node.\n  std::vector<int> v1, v2, v3;\n\n  // Make a random dataset.\n  arma::mat* data = new arma::mat(numRows, numCols, arma::fill::randu);\n\n  // Make a cosine tree, with the generated dataset.\n  CosineTree* ctree1 = new CosineTree(*data);\n\n  // Stacks for depth first search of the tree.\n  std::vector<CosineTree*> nodeStack1, nodeStack2, nodeStack3;\n  nodeStack1.push_back(ctree1);\n\n  // While stack is not empty.\n  while (nodeStack1.size())\n  {\n    // Pop a node from the stack and split it.\n    CosineTree *currentNode1, *currentLeft1, *currentRight1;\n\n    currentNode1 = nodeStack1.back();\n    currentNode1->CosineNodeSplit();\n    nodeStack1.pop_back();\n\n    // Obtain pointers to the children of the node.\n    currentLeft1 = currentNode1->Left();\n    currentRight1 = currentNode1->Right();\n\n    // If children exist.\n    if (currentLeft1 && currentRight1)\n    {\n      // Push the child nodes on to the stack.\n      nodeStack1.push_back(currentLeft1);\n      nodeStack1.push_back(currentRight1);\n\n      v1.push_back(currentNode1->NumColumns());\n    }\n  }\n\n  // Copy constructor and operator.\n  CosineTree ctree2(*ctree1);\n  CosineTree ctree3 = *ctree1;\n\n  delete ctree1;\n  delete data;\n\n  nodeStack2.push_back(&ctree2);\n  nodeStack3.push_back(&ctree3);\n\n  // While stacks are not empty.\n  while (nodeStack2.size() && nodeStack3.size())\n  {\n    // Pop a node from the stack and split it.\n    CosineTree *currentNode2, *currentLeft2, *currentRight2;\n    CosineTree *currentNode3, *currentLeft3, *currentRight3;\n\n    currentNode2 = nodeStack2.back();\n    nodeStack2.pop_back();\n\n    currentNode3 = nodeStack3.back();\n    nodeStack3.pop_back();\n\n    // Obtain pointers to the children of the node.\n    currentLeft2 = currentNode2->Left();\n    currentRight2 = currentNode2->Right();\n\n    currentLeft3 = currentNode3->Left();\n    currentRight3 = currentNode3->Right();\n\n    // If children exist.\n    if (currentLeft2 && currentRight2 && currentLeft3 && currentRight3)\n    {\n      // Push the child nodes on to the stack.\n      nodeStack2.push_back(currentLeft2);\n      nodeStack2.push_back(currentRight2);\n\n      v2.push_back(currentNode2->NumColumns());\n\n      nodeStack3.push_back(currentLeft3);\n      nodeStack3.push_back(currentRight3);\n\n      v3.push_back(currentNode3->NumColumns());\n    }\n  }\n\n  for (size_t i = 0; i < v1.size(); i++)\n  {\n    BOOST_REQUIRE_EQUAL(v1.at(i), v2.at(i));\n    BOOST_REQUIRE_EQUAL(v1.at(i), v3.at(i));\n  }\n}\n\n/**\n * Test the move constructor & move assignment using Cosine trees.\n */\nBOOST_AUTO_TEST_CASE(MoveConstructorAndOperatorCosineTreeTest)\n{\n  // Initialize constants required for the test.\n  const size_t numRows = 10;\n  const size_t numCols = 15;\n\n  // Vectors to hold depth-first traversal\n  // of the number of columns in each node.\n  std::vector<int> v1, v2, v3;\n\n  // Make a random dataset.\n  arma::mat data = arma::randu(numRows, numCols);\n\n  // Make a cosine tree, with the generated dataset.\n  CosineTree ctree1(data);\n\n  // Stacks for depth first search of the tree.\n  std::vector<CosineTree*> nodeStack1, nodeStack2, nodeStack3;\n  nodeStack1.push_back(&ctree1);\n\n  // While stack is not empty.\n  while (nodeStack1.size())\n  {\n    // Pop a node from the stack and split it.\n    CosineTree *currentNode1, *currentLeft1, *currentRight1;\n\n    currentNode1 = nodeStack1.back();\n    currentNode1->CosineNodeSplit();\n    nodeStack1.pop_back();\n\n    // Obtain pointers to the children of the node.\n    currentLeft1 = currentNode1->Left();\n    currentRight1 = currentNode1->Right();\n\n    // If children exist.\n    if (currentLeft1 && currentRight1)\n    {\n      // Push the child nodes on to the stack.\n      nodeStack1.push_back(currentLeft1);\n      nodeStack1.push_back(currentRight1);\n\n      v1.push_back(currentNode1->NumColumns());\n    }\n  }\n\n  // Move constructor.\n  CosineTree ctree2(std::move(ctree1));\n\n  nodeStack2.push_back(&ctree2);\n\n  // While stacks are not empty.\n  while (nodeStack2.size())\n  {\n    // Pop a node from the stack and split it.\n    CosineTree *currentNode2, *currentLeft2, *currentRight2;\n\n    currentNode2 = nodeStack2.back();\n    nodeStack2.pop_back();\n\n    // Obtain pointers to the children of the node.\n    currentLeft2 = currentNode2->Left();\n    currentRight2 = currentNode2->Right();\n\n    // If children exist.\n    if (currentLeft2 && currentRight2)\n    {\n      // Push the child nodes on to the stack.\n      nodeStack2.push_back(currentLeft2);\n      nodeStack2.push_back(currentRight2);\n\n      v2.push_back(currentNode2->NumColumns());\n    }\n  }\n\n  // Move operator.\n  CosineTree ctree3 = std::move(ctree2);\n\n  nodeStack3.push_back(&ctree3);\n\n  // While stacks are not empty.\n  while (nodeStack3.size())\n  {\n    // Pop a node from the stack and split it.\n    CosineTree *currentNode3, *currentLeft3, *currentRight3;\n\n    currentNode3 = nodeStack3.back();\n    nodeStack3.pop_back();\n\n    // Obtain pointers to the children of the node.\n    currentLeft3 = currentNode3->Left();\n    currentRight3 = currentNode3->Right();\n\n    // If children exist.\n    if (currentLeft3 && currentRight3)\n    {\n      // Push the child nodes on to the stack.\n      nodeStack3.push_back(currentLeft3);\n      nodeStack3.push_back(currentRight3);\n\n      v3.push_back(currentNode3->NumColumns());\n    }\n  }\n\n  for (size_t i = 0; i < v1.size(); i++)\n  {\n    BOOST_REQUIRE_EQUAL(v1.at(i), v2.at(i));\n    BOOST_REQUIRE_EQUAL(v1.at(i), v3.at(i));\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "f5f0f8a9f72236cd398d0e2d51131cd720b0cda4", "size": 13042, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/cosine_tree_test.cpp", "max_stars_repo_name": "KimSangYeon-DGU/mlpack", "max_stars_repo_head_hexsha": "defa29791f43d3372b019f552134abc39def234a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mlpack/tests/cosine_tree_test.cpp", "max_issues_repo_name": "KimSangYeon-DGU/mlpack", "max_issues_repo_head_hexsha": "defa29791f43d3372b019f552134abc39def234a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/cosine_tree_test.cpp", "max_forks_repo_name": "KimSangYeon-DGU/mlpack", "max_forks_repo_head_hexsha": "defa29791f43d3372b019f552134abc39def234a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T13:27:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-23T09:44:31.000Z", "avg_line_length": 29.6409090909, "max_line_length": 80, "alphanum_fraction": 0.6660788223, "num_tokens": 3401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5402558193655508}}
{"text": "/**\n * @file ess.hpp\n * @author Vahid Bastani\n *\n * Effective Sample Size (ESS) resampling criterion\n */\n#ifndef SSMPACK_FILTER_RESAMPLER_CRITERION_ESS\n#define SSMPACK_FILTER_RESAMPLER_CRITERION_ESS\n\n#include <armadillo>\n\nnamespace ssmkit {\nnamespace filter {\nnamespace resampler {\nnamespace criterion {\n\nstruct ESS{\n  double th;\n  /**\n   * @param threshold: minimum number of effective sample.\n   */\n  ESS(double threshold) : th{threshold} {}\n  ESS() = delete;\n  /**\n   * return true if number of effective samples with weights w falls bellow the\n   * threshold\n   */\n  bool operator()(const arma::vec &w){\n    return arma::sum(w)/arma::sum(arma::square(w)) < th;\n  }\n\n};\n} // namespace criterion\n} // namespace resampler\n} // namespace filter\n} // namespace ssmkit\n#endif // SSMPACK_FILTER_RESAMPLER_CRITERION_ESS\n", "meta": {"hexsha": "5bc910b352cfe3a12bfe6421d522d24f8d6c3dc0", "size": 816, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ssmkit/filter/resampler/criterion/ess.hpp", "max_stars_repo_name": "vahid-bastani/ssmpack", "max_stars_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-07-08T09:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-10T06:46:55.000Z", "max_issues_repo_path": "src/ssmkit/filter/resampler/criterion/ess.hpp", "max_issues_repo_name": "vahidbas/ssmkit", "max_issues_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ssmkit/filter/resampler/criterion/ess.hpp", "max_forks_repo_name": "vahidbas/ssmkit", "max_forks_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T17:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T17:46:08.000Z", "avg_line_length": 21.4736842105, "max_line_length": 79, "alphanum_fraction": 0.7071078431, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5402558172296698}}
{"text": "#ifndef HAMILTONIANS_XYZNNNSTO2_HPP\n#define HAMILTONIANS_XYZNNNSTO2_HPP\n#include <Eigen/Eigen>\n#include <nlohmann/json.hpp>\n\n/* Stoquastic for |a|, |b| > 1*/\nclass XYZNNNSto2\n{\nprivate:\n\tint n_;\n\tdouble a_;\n\tdouble b_;\n\tconstexpr static double J1 = -1.0;\n\tconstexpr static double J2 = -1.0;\npublic:\n\n\tXYZNNNSto2(int n, double a, double b)\n\t\t: n_(n), a_(a), b_(b)\n\t{\n\t}\n\n\tnlohmann::json params() const\n\t{\n\t\treturn nlohmann::json\n\t\t{\n\t\t\t{\"name\", \"XYZNNNSto2\"},\n\t\t\t{\"n\", n_},\n\t\t\t{\"a\", a_},\n\t\t\t{\"b\", b_}\n\t\t};\n\t}\n\t\n\ttemplate<class State>\n\ttypename State::Scalar operator()(const State& smp) const\n\t{\n\t\ttypename State::Scalar s = 0.0;\n\t\t//Nearest-neighbor\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tdouble yysign = -smp.sigmaAt(i)*smp.sigmaAt((i+1)%n_);\n\t\t\ts += -J1*b_*yysign; //zz\n\t\t\ts += J1*(a_+1.0*yysign)*smp.ratio(i, (i+1)%n_); //xx+yy\n\t\t}\n\t\t//Next-nearest-neighbor\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tdouble yysign = -smp.sigmaAt(i)*smp.sigmaAt((i+2)%n_);\n\t\t\ts += -J2*a_*yysign; //zz\n\t\t\ts += J2*(b_+1.0*yysign)*smp.ratio(i, (i+2)%n_); //xx+yy\n\t\t}\n\t\treturn s;\n\t}\n\t\n\tstd::map<uint32_t, double> operator()(uint32_t col) const\n\t{\n\t\tstd::map<uint32_t, double> m;\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tint b1 = (col >> i) & 1;\n\t\t\tint b2 = (col >> ((i+1)%n_)) & 1;\n\t\t\tint sgn = (1-2*b1)*(1-2*b2);\n\t\t\tlong long int x = (1 << i) | (1 << ((i+1)%(n_)));\n\t\t\tm[col ^ x] += J1*(a_ - 1.0*sgn);\n\t\t\tm[col] += J1*b_*sgn;\n\t\t}\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tint b1 = (col >> i) & 1;\n\t\t\tint b2 = (col >> ((i+2)%n_)) & 1;\n\t\t\tint sgn = (1-2*b1)*(1-2*b2);\n\t\t\tlong long int x = (1 << i) | (1 << ((i+2)%(n_)));\n\t\t\tm[col ^ x] += J2*(b_ - sgn*1.0);\n\t\t\tm[col] += J2*a_*sgn;\n\t\t}\n\t\treturn m;\n\t}\n};\n#endif//HAMILTONIANS_XYZNNNSTO2_HPP\n", "meta": {"hexsha": "d37a995e7494f0dbd527273a3a12efb74406d6f1", "size": 1703, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Hamiltonians/XYZSto2.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/Hamiltonians/XYZSto2.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/Hamiltonians/XYZSto2.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.5569620253, "max_line_length": 58, "alphanum_fraction": 0.5408103347, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5402005775245146}}
{"text": "#ifndef _CELERITE2_TERMS_HPP_DEFINED_\n#define _CELERITE2_TERMS_HPP_DEFINED_\n\n#include <tuple>\n#include <exception>\n#include <Eigen/Core>\n\nnamespace celerite2 {\n\n#ifndef CELERITE_MAX_WIDTH\n#define CELERITE_MAX_WIDTH 32\n#endif\n\nstruct dimension_mismatch : public std::exception {\n  const char *what() const throw() { return \"dimension mismatch\"; }\n};\n\ntemplate <int J1, int J2>\nstruct sum_width {\n  constexpr static int value = (J1 == Eigen::Dynamic || J2 == Eigen::Dynamic) ? Eigen::Dynamic : (J1 + J2);\n};\n\n/**\n * The abstract base class from which terms should inherit\n */\ntemplate <typename T, int J_ = Eigen::Dynamic>\nclass Term {\n  protected:\n  constexpr static int Width = ((0 < J_) && (J_ <= CELERITE_MAX_WIDTH)) ? J_ : Eigen::Dynamic;\n  static constexpr int Order = (Width != 1) ? Eigen::RowMajor : Eigen::ColMajor;\n\n  public:\n  /**\n   * \\typedef Scalar\n   * The underlying scalar type of this `Term` (should probably always be `double`)\n   */\n  typedef T Scalar;\n\n  /**\n   * \\typedef Vector\n   * An `Eigen` vector with data type `Scalar`\n   */\n  typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector;\n\n  /**\n   * \\typedef LowRank\n   * The `Eigen` type for the low-rank matrices used internally\n   */\n  typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Width, Order> LowRank;\n\n  /**\n   * \\typedef CoeffVector\n   * The `Eigen` type for a fixed width vector of coefficients\n   */\n  typedef Eigen::Matrix<Scalar, Width, 1> CoeffVector;\n\n  /**\n   * \\typedef Coeffs\n   * A tuple of vectors giving the coefficients for the celerite model\n   */\n  typedef std::tuple<Vector, Vector, Vector, Vector, Vector, Vector> Coeffs;\n\n  /**\n   * \\typedef Matrices\n   * A tuple of matrices representing this celerite process\n   */\n  typedef std::tuple<CoeffVector, Vector, LowRank, LowRank> Matrices;\n\n  Term(){};\n\n  int get_width() const { return Width; }\n\n  /**\n   * Set the coefficients of the term\n   *\n   * @param ar     (J_real,): The real amplitudes.\n   * @param cr     (J_real,): The real exponential.\n   * @param ac     (J_comp,): The complex even amplitude.\n   * @param bc     (J_comp,): The complex odd amplitude.\n   * @param cc     (J_comp,): The complex exponential.\n   * @param dc     (J_comp,): The complex frequency.\n   */\n  void set_coefficients(const Vector &ar, const Vector &cr, const Vector &ac, const Vector &bc, const Vector &cc, const Vector &dc) {\n    Eigen::Index nr = ar.rows(), nc = ac.rows();\n\n    ar_.resize(nr);\n    cr_.resize(nr);\n    ac_.resize(nc);\n    bc_.resize(nc);\n    cc_.resize(nc);\n    dc_.resize(nc);\n\n    ar_ << ar;\n    cr_ << cr;\n    ac_ << ac;\n    bc_ << bc;\n    cc_ << cc;\n    dc_ << dc;\n  }\n\n  /**\n   * Get the coefficients of the term as a tuple\n   */\n  Coeffs get_coefficients() const { return std::make_tuple(ar_, cr_, ac_, bc_, cc_, dc_); }\n\n  /**\n   * Get the matrices required to represent the celerite process\n   *\n   * @param x    (N,): The independent coordinates of the data.\n   * @param diag (N,): The diagonal variance of the process.\n   */\n  Matrices get_celerite_matrices(const Vector &x, const Vector &diag) const {\n    Eigen::Index N = x.rows();\n    if (diag.rows() != N) throw dimension_mismatch();\n\n    Eigen::Index nr = ar_.rows();\n    Eigen::Index nc = ac_.rows();\n    Eigen::Index J  = nr + 2 * nc;\n    if (Width != Eigen::Dynamic && Width != J) throw dimension_mismatch();\n\n    CoeffVector c(J);\n    Vector a = diag.array() + (ar_.sum() + ac_.sum());\n    LowRank U(N, J), V(N, J);\n\n    c << cr_, cc_, cc_;\n\n    U.block(0, 0, N, nr).rowwise() = ar_.transpose();\n    V.block(0, 0, N, nr).setConstant(Scalar(1));\n\n    auto arg                   = (x * dc_.transpose()).array().eval();\n    auto ca                    = cos(arg).eval();\n    auto sa                    = sin(arg).eval();\n    U.block(0, nr, N, nc)      = ca.array().rowwise() * ac_.transpose().array() + sa.array().rowwise() * bc_.transpose().array();\n    U.block(0, nr + nc, N, nc) = sa.array().rowwise() * ac_.transpose().array() - ca.array().rowwise() * bc_.transpose().array();\n    V.block(0, nr, N, nc)      = ca;\n    V.block(0, nr + nc, N, nc) = sa;\n\n    return std::make_tuple(c, a, U, V);\n  }\n\n  /**\n   * Adding two terms builds a new term where the coefficients have been concatenated\n   *\n   * @param other (Term): The term to add to this one.\n   */\n  template <typename Other>\n  Term<typename std::common_type<Scalar, typename Other::Scalar>::type, sum_width<Width, Other::Width>::value> operator+(const Other &other) const {\n    typedef typename std::common_type<Scalar, typename Other::Scalar>::type NewScalar;\n\n    auto coeffs = other.get_coefficients();\n\n    Eigen::Index nr = ar_.rows() + std::get<0>(coeffs).rows();\n    Eigen::Index nc = ac_.rows() + std::get<2>(coeffs).rows();\n\n    Eigen::Matrix<NewScalar, Eigen::Dynamic, 1> ar(nr), cr(nr), ac(nc), bc(nc), cc(nc), dc(nc);\n\n    ar << ar_, std::get<0>(coeffs);\n    cr << cr_, std::get<1>(coeffs);\n    ac << ac_, std::get<2>(coeffs);\n    bc << ac_, std::get<3>(coeffs);\n    cc << ac_, std::get<4>(coeffs);\n    dc << ac_, std::get<5>(coeffs);\n\n    Term<NewScalar, sum_width<Width, Other::Width>::value> new_term;\n    new_term.set_coefficients(ar, cr, ac, bc, cc, dc);\n\n    return new_term;\n  }\n\n  private:\n  Vector ar_, cr_, ac_, bc_, cc_, dc_;\n};\n\n/**\n * \\class RealTerm\n * The simplest celerite model\n *\n * @param a: The amplitude of the term.\n * @param c: The exponent of the term.\n */\ntemplate <typename T>\nclass RealTerm : public Term<T, 1> {\n  public:\n  /**\n   * \\typedef Scalar\n   * The underlying scalar type of this `Term` (should probably always be `double`)\n   */\n  typedef T Scalar;\n  constexpr static int Width = 1;\n  using typename Term<Scalar, 1>::Vector;\n  using typename Term<Scalar, 1>::LowRank;\n  RealTerm(const Scalar &a, const Scalar &c) {\n    Vector ar(1), cr(1), ac, bc, cc, dc;\n    ar << a;\n    cr << c;\n    this->set_coefficients(ar, cr, ac, bc, cc, dc);\n  };\n};\n\n/**\n * \\class ComplexTerm\n * A general celerite model\n *\n * @param a: The real part of the amplitude.\n * @param b: The complex part of the amplitude.\n * @param c: The real part of the exponent.\n * @param d: The complex part of the exponent.\n */\ntemplate <typename T>\nclass ComplexTerm : public Term<T, 2> {\n  public:\n  /**\n   * \\typedef Scalar\n   * The underlying scalar type of this `Term` (should probably always be `double`)\n   */\n  typedef T Scalar;\n  constexpr static int Width = 2;\n  using typename Term<Scalar, 2>::Vector;\n  using typename Term<Scalar, 2>::LowRank;\n  ComplexTerm(const Scalar &a, const Scalar &b, const Scalar &c, const Scalar &d) {\n    Vector ar, cr, ac(1), bc(1), cc(1), dc(1);\n    ac << a;\n    bc << b;\n    cc << c;\n    dc << d;\n    this->set_coefficients(ar, cr, ac, bc, cc, dc);\n  };\n};\n\n/**\n * \\class SHOTerm\n * A term representing a stochastically-driven, damped harmonic oscillator\n *\n * @param S0:  The power at `omega = 0`.\n * @param w0:  The undamped angular frequency.\n * @param Q:   The quality factor.\n * @param eps: A regularization parameter used for numerical stability.\n */\ntemplate <typename T>\nclass SHOTerm : public Term<T, 2> {\n  public:\n  /**\n   * \\typedef Scalar\n   * The underlying scalar type of this `Term` (should probably always be `double`)\n   */\n  typedef T Scalar;\n  constexpr static int Width = 2;\n  using typename Term<Scalar, 2>::Vector;\n  using typename Term<Scalar, 2>::LowRank;\n  SHOTerm(const Scalar &S0, const Scalar &w0, const Scalar &Q, const Scalar &eps = 1e-5) {\n    Vector ar, cr, ac, bc, cc, dc;\n    if (Q < 0.5) {\n      ar.resize(2);\n      cr.resize(2);\n      auto f = std::sqrt(std::max(1.0 - 4.0 * Q * Q, eps));\n      auto a = 0.5 * S0 * w0 * Q;\n      auto c = 0.5 * w0 / Q;\n      ar(0)  = a * (1 + 1 / f);\n      ar(1)  = a * (1 - 1 / f);\n      cr(0)  = c * (1 - f);\n      cr(1)  = c * (1 + f);\n    } else {\n      ac.resize(1);\n      bc.resize(1);\n      cc.resize(1);\n      dc.resize(1);\n      auto f = std::sqrt(std::max(4.0 * Q * Q - 1, eps));\n      auto a = S0 * w0 * Q;\n      auto c = 0.5 * w0 / Q;\n      ac(0)  = a;\n      bc(0)  = a / f;\n      cc(0)  = c;\n      dc(0)  = c * f;\n    }\n    this->set_coefficients(ar, cr, ac, bc, cc, dc);\n  };\n};\n\n} // namespace celerite2\n\n#endif // _CELERITE2_TERMS_HPP_DEFINED_\n", "meta": {"hexsha": "2d33833a4707e44fc18884919d4c34c9466f0eee", "size": 8159, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/include/celerite2/terms.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/terms.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/terms.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": 28.9326241135, "max_line_length": 148, "alphanum_fraction": 0.6069371246, "num_tokens": 2441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681086260461, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5402005738539944}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-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#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP\n\n\n#include <boost/geometry/util/math.hpp>\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace buffer\n{\n\n\n// TODO: once change this to proper strategy\n// It is different from current segment intersection because these are not segments but lines\n// If we have the Line concept, we can create a strategy\ntemplate <typename Point, typename Line1, typename Line2 = Line1>\nstruct line_line_intersection\n{\n    template <typename A, typename B, typename C, typename D>\n    static inline A det(A const& a, B const& b, C const& c, D const& d)\n    {\n        return a * d - b * c;\n    }\n\n    static inline bool apply(Line1 const& line1, Line2 const& line2, Point& p)\n    {\n        // See http://mathworld.wolfram.com/Line-LineIntersection.html\n        typedef typename coordinate_type<Point>::type coordinate_type;\n        coordinate_type x1 = get<0,0>(line1), y1 = get<0,1>(line1);\n        coordinate_type x2 = get<1,0>(line1), y2 = get<1,1>(line1);\n        coordinate_type x3 = get<0,0>(line2), y3 = get<0,1>(line2);\n        coordinate_type x4 = get<1,0>(line2), y4 = get<1,1>(line2);\n\n        coordinate_type denominator = det(x1 - x2, y1 - y2, x3 - x4, y3 - y4);\n\n        // TODO: use something else then denominator (sides?) to determine this.\n\n        // If denominator is zero, segments are parallel.\n        // We have context information, so know that it should then\n        // be the case that line1.p2 == line2.p1, and that is the\n        // intersection point.\n        if (geometry::math::equals(denominator, 0.0))\n        {\n            set<0>(p, x2);\n            set<1>(p, y2);\n            return false;\n        }\n\n        coordinate_type d1 = det(x1, y1, x2, y2);\n        coordinate_type d2 = det(x3, y3, x4, y4);\n        coordinate_type px = det(d1, x1 - x2, d2, x3 - x4) / denominator;\n        coordinate_type py = det(d1, y1 - y2, d2, y3 - y4) / denominator;\n\n        set<0>(p, px);\n        set<1>(p, py);\n\n#ifdef BOOST_GEOMETRY_DEBUG_BUFFER\n        if (geometry::math::abs(denominator) < 1.0e-7)\n        {\n            std::cout << \"small \" << denominator << std::endl;\n        }\n#endif\n        return geometry::math::abs(denominator) > 1.0e-7;\n    }\n};\n\n\n}} // namespace detail::buffer\n#endif // DOXYGEN_NO_DETAIL\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP\n", "meta": {"hexsha": "d01c75877dd9c3733924f27c481bbb0ddbb09c4a", "size": 2843, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/algorithms/buffer/line_line_intersection.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.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": "boost/geometry/extensions/algorithms/buffer/line_line_intersection.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.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": "boost/geometry/extensions/algorithms/buffer/line_line_intersection.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 32.6781609195, "max_line_length": 93, "alphanum_fraction": 0.6577558917, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5401815913948479}}
{"text": "/*\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 http://mozilla.org/MPL/2.0/.\n\n  Copyright (c) 2019 Panda Team\n*/\n#include <algorithm>\n\n#include \"modules/distance.hpp\"\n\n#include \"modules/utils/graph.hpp\"\n\n#define BOOST_TEST_MODULE Main\n#define BOOST_TEST_DYN_LINK\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(Metric)\n{\n    using Vector = std::vector<double>;\n    metric::Euclidian<double> metric;\n\n    Vector vNull = {};\n    Vector v0 = { 0, 0, 0, 0, 0 };\n    Vector v7 = { 7, 7, 7.5, 7, 7 };\n    Vector v = { 1, 2.3, -2.7, 0, 3 };\n\n    double t = 0.0000001;\n    BOOST_CHECK_CLOSE(metric(vNull, vNull), 0, t);\n    BOOST_CHECK_CLOSE(metric(v0, v0), 0, t);\n    BOOST_CHECK_CLOSE(metric(v7, v), 15.070832757349542, t);\n}\n\nBOOST_AUTO_TEST_CASE(Grid4)\n{\n    metric::Grid4 grid5(5);  // replaced everywhere mapping::SOM_details with graph by Max F, 2019-05-16\n    BOOST_CHECK(!grid5.isValid());\n\n    metric::Grid4 grid25(25);\n    BOOST_CHECK(grid25.isValid());\n    BOOST_CHECK_EQUAL(grid25.getNodesNumber(), 25);\n\n    metric::Grid4 grid32(3, 2);\n    BOOST_CHECK(grid32.isValid());\n    BOOST_CHECK_EQUAL(grid32.getNodesNumber(), 6);\n\n    auto neighboursList = grid25.getNeighbours(9, 3);\n    for (auto& neighbours : neighboursList) {\n        std::sort(neighbours.begin(), neighbours.end());\n    }\n\n    std::vector<size_t> neighbours0 = { 9 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[0].begin(), neighboursList[0].end(), neighbours0.begin(), neighbours0.end());\n\n    std::vector<size_t> neighbours1 = { 4, 8, 14 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[1].begin(), neighboursList[1].end(), neighbours1.begin(), neighbours1.end());\n\n    std::vector<size_t> neighbours2 = { 3, 7, 13, 19 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[2].begin(), neighboursList[2].end(), neighbours2.begin(), neighbours2.end());\n}\n\nBOOST_AUTO_TEST_CASE(Grid6)\n{\n    metric::Grid6 grid5(5);\n    BOOST_CHECK(!grid5.isValid());\n\n    metric::Grid6 grid25(25);\n    BOOST_CHECK(grid25.isValid());\n    BOOST_CHECK_EQUAL(grid25.getNodesNumber(), 25);\n\n    metric::Grid6 grid30(6, 5);\n    BOOST_CHECK(grid30.isValid());\n    BOOST_CHECK_EQUAL(grid30.getNodesNumber(), 30);\n\n    auto neighboursList = grid30.getNeighbours(12, 3);\n    for (auto& neighbours : neighboursList) {\n        std::sort(neighbours.begin(), neighbours.end());\n    }\n\n    std::vector<size_t> neighbours0 = { 12 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[0].begin(), neighboursList[0].end(), neighbours0.begin(), neighbours0.end());\n\n    std::vector<size_t> neighbours1 = { 6, 13, 18 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[1].begin(), neighboursList[1].end(), neighbours1.begin(), neighbours1.end());\n\n    std::vector<size_t> neighbours2 = { 0, 1, 7, 14, 19, 24, 25 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[2].begin(), neighboursList[2].end(), neighbours2.begin(), neighbours2.end());\n}\nBOOST_AUTO_TEST_CASE(Grid8)\n{\n    metric::Grid8 grid5(5);\n    BOOST_CHECK(!grid5.isValid());\n\n    metric::Grid8 grid25(25);\n    BOOST_CHECK(grid25.isValid());\n    BOOST_CHECK_EQUAL(grid25.getNodesNumber(), 25);\n\n    metric::Grid8 grid6(3, 2);\n    BOOST_CHECK(grid6.isValid());\n    BOOST_CHECK_EQUAL(grid6.getNodesNumber(), 6);\n\n    auto neighboursList = grid25.getNeighbours(9, 3);\n    for (auto& neighbours : neighboursList) {\n        std::sort(neighbours.begin(), neighbours.end());\n    }\n\n    std::vector<size_t> neighbours0 = { 9 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[0].begin(), neighboursList[0].end(), neighbours0.begin(), neighbours0.end());\n\n    std::vector<size_t> neighbours1 = { 3, 4, 8, 13, 14 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[1].begin(), neighboursList[1].end(), neighbours1.begin(), neighbours1.end());\n\n    std::vector<size_t> neighbours2 = { 2, 7, 12, 17, 18, 19 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[2].begin(), neighboursList[2].end(), neighbours2.begin(), neighbours2.end());\n\n    std::vector<size_t> neighbours3 = { 1, 6, 11, 16, 21, 22, 23, 24 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[3].begin(), neighboursList[3].end(), neighbours3.begin(), neighbours3.end());\n}\n\nBOOST_AUTO_TEST_CASE(LPS)\n{\n    metric::LPS lps5(5);\n    BOOST_CHECK_EQUAL(lps5.isValid(), true);\n\n    metric::LPS lps(11);\n    BOOST_CHECK_EQUAL(lps.isValid(), true);\n\n    auto neighboursList = lps.getNeighbours(9, 2);\n    for (auto& neighbours : neighboursList) {\n        std::sort(neighbours.begin(), neighbours.end());\n    }\n\n    std::vector<size_t> neighbours0 = { 9 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[0].begin(), neighboursList[0].end(), neighbours0.begin(), neighbours0.end());\n\n    std::vector<size_t> neighbours1 = { 5, 8, 10 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[1].begin(), neighboursList[1].end(), neighbours1.begin(), neighbours1.end());\n\n    std::vector<size_t> neighbours2 = { 0, 4, 6, 7 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[2].begin(), neighboursList[2].end(), neighbours2.begin(), neighbours2.end());\n\n    /* LPS(41) */\n    metric::LPS lps41(41);\n    BOOST_CHECK_EQUAL(lps41.isValid(), true);\n\n    neighboursList = lps41.getNeighbours(9, 2);\n    for (auto& neighbours : neighboursList) {\n        std::sort(neighbours.begin(), neighbours.end());\n    }\n\n    neighbours0 = { 9 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[0].begin(), neighboursList[0].end(), neighbours0.begin(), neighbours0.end());\n\n    neighbours1 = { 8, 10, 32 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[1].begin(), neighboursList[1].end(), neighbours1.begin(), neighbours1.end());\n\n    neighbours2 = { 7, 11, 31, 33, 36, 37 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[2].begin(), neighboursList[2].end(), neighbours2.begin(), neighbours2.end());\n}\n\nBOOST_AUTO_TEST_CASE(Paley)\n{\n    metric::Paley paley12(12);\n    BOOST_CHECK_EQUAL(paley12.isValid(), false);\n\n    metric::Paley paley13(13);\n    BOOST_CHECK_EQUAL(paley13.isValid(), true);\n\n    auto neighboursList = paley13.getNeighbours(9, 1);\n    for (auto& neighbours : neighboursList) {\n        std::sort(neighbours.begin(), neighbours.end());\n    }\n\n    std::vector<size_t> neighbours0 = { 9 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[0].begin(), neighboursList[0].end(), neighbours0.begin(), neighbours0.end());\n\n    std::vector<size_t> neighbours1 = { 0, 5, 6, 8, 10, 12 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[1].begin(), neighboursList[1].end(), neighbours1.begin(), neighbours1.end());\n}\n\nBOOST_AUTO_TEST_CASE(Margulis)\n{\n    metric::Margulis margulis5(5);\n    BOOST_CHECK_EQUAL(margulis5.isValid(), false);\n\n    metric::Margulis margulis25(25);\n    BOOST_CHECK_EQUAL(margulis25.isValid(), true);\n\n    auto neighboursList = margulis25.getNeighbours(7, 1);\n    for (auto& neighbours : neighboursList) {\n        std::sort(neighbours.begin(), neighbours.end());\n    }\n\n    std::vector<size_t> neighbours0 = { 7 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[0].begin(), neighboursList[0].end(), neighbours0.begin(), neighbours0.end());\n\n    std::vector<size_t> neighbours1 = { 2, 5, 9, 12 };\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        neighboursList[1].begin(), neighboursList[1].end(), neighbours1.begin(), neighbours1.end());\n}\n", "meta": {"hexsha": "f019534acd3b42953b40225a853868e7549b4a1b", "size": 7501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metric/tests/mapping_tests/mapping_tests.cpp", "max_stars_repo_name": "Stepka/telegram_clustering_contest", "max_stars_repo_head_hexsha": "52a012af2ce821410caa98cba840364710eb4256", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-12-03T17:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T05:06:29.000Z", "max_issues_repo_path": "metric/tests/mapping_tests/mapping_tests.cpp", "max_issues_repo_name": "Stepka/telegram_clustering_contest", "max_issues_repo_head_hexsha": "52a012af2ce821410caa98cba840364710eb4256", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-02T02:25:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T02:25:51.000Z", "max_forks_repo_path": "metric/tests/mapping_tests/mapping_tests.cpp", "max_forks_repo_name": "Stepka/telegram_clustering_contest", "max_forks_repo_head_hexsha": "52a012af2ce821410caa98cba840364710eb4256", "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.9411764706, "max_line_length": 104, "alphanum_fraction": 0.6691107852, "num_tokens": 2047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5401815729166004}}
{"text": "#ifndef mesh_reader\n#define mesh_reader\n\n\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <string>\n#include <math.h>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\ntypedef Matrix<int,Dynamic,Dynamic> MatrixXi;\n\nnamespace mesh\n{\n\n    MatrixXd read_vertices(std::string location)\n    {\n        /* index # is vertix id, contains x and y\n        coordinate respectively of vertix, and\n        a flag, 1 if boundary point 0 if not */\n        std::ifstream infile(location);\n        std::string line;\n        double a, b, c, d, line_nb = 0;\n        std::getline(infile, line);\n        std::istringstream iss(line);\n        iss >> a >> b >> c;\n        int nb_nodes = a;\n        MatrixXd vertices(nb_nodes, 3);\n        while (std::getline(infile, line))\n        {\n            std::istringstream iss(line);\n            if (iss >> a >> b >> c >> d)\n            {\n                vertices(line_nb, 0) = b/1000.;\n                vertices(line_nb, 1) = c/1000.;\n                vertices(line_nb, 2) = d;\n            }\n            else\n            {\n                break;\n            }\n            line_nb += 1;\n        }\n        return vertices;\n    }\n\n    MatrixXd read_triangles(MatrixXd& vertices,std::string location)\n    {\n        /* index # is triangle id, contains\n        the 3 vertix id's of the corner nodes  and\n        the area of the triangle, calculated using\n        the vertices matrix */\n        std::ifstream infile(location);\n        std::string line;\n        int a, b, c, d, line_nb = 0;\n        std::getline(infile, line);\n        std::istringstream iss(line);\n        iss >> a >> b >> c;\n        int nb_triangles = a;\n        MatrixXd triangles(nb_triangles, 4);\n        while (std::getline(infile, line))\n        {\n            std::istringstream iss(line);\n            if (iss >> a >> b >> c >> d)\n            {\n                triangles(line_nb, 0) = b-1;\n                triangles(line_nb, 1) = c-1;\n                triangles(line_nb, 2) = d-1;\n                triangles(line_nb, 3) = 0.5*fabs(vertices(b-1, 0)*(vertices(c-1, 1) - vertices(d-1, 1)) +\n                    vertices(c-1, 0)*(vertices(d-1, 1) - vertices(b-1, 1)) +\n                    vertices(d-1, 0)*(vertices(b-1, 1) - vertices(c-1, 1)));\n            }\n            else\n            {\n                break;\n            }\n            line_nb += 1;\n        }\n        return triangles;\n    }\n\n    MatrixXi read_boundaries(MatrixXd& vertices,std::string location) {\n        /* index # is triangle id, contains\n        the 3 vertix id's of the corner nodes  and\n        the area of the triangle, calculated using\n        the vertices matrix */\n        std::ifstream infile(location);\n        std::string line;\n        int a, b, c, d, count = 0;\n        std::getline(infile, line);\n        std::getline(infile, line);\n        std::istringstream iss(line);\n        iss >> a >> b;\n        int nb_boundaries = a;\n        MatrixXi boundaries(nb_boundaries, 2);\n        while (std::getline(infile, line))\n        {\n            std::istringstream iss(line);\n            if (iss >> a >> b >> c >> d)\n            {\n                if (vertices(b-1, 0) != 0 || vertices(c-1, 0) != 0) {\n                  boundaries(count, 0) = b-1;\n                  boundaries(count, 1) = c-1;\n                  count += 1;\n                }\n            }\n            else\n            {\n                break;\n            }\n        }\n\n        MatrixXi boundaries_red(count, 2);\n        boundaries_red = boundaries.block(0,0,count,2);\n        return boundaries_red;\n    }\n\n    void write_result(VectorXd& u,VectorXd& v)\n    {\n      std::ofstream output_u;\n      std::ofstream output_v;\n      output_u.open(\"../mesh/result_u.out\");\n      output_u << u;\n      output_v.open(\"../mesh/result_v.out\");\n      output_v << v;\n      output_u.close();\n      output_v.close();\n    }\n\n}\n\n\n#endif\n", "meta": {"hexsha": "098ccec42002214b273287e714375e5fcde57598", "size": 3850, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/mesh_reader_eigen.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/mesh_reader_eigen.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/mesh_reader_eigen.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.3088235294, "max_line_length": 105, "alphanum_fraction": 0.4963636364, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5401815699181435}}
{"text": "#include <bits/types/FILE.h>\n#include <fstream>\n#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <string>\n#include <tgmath.h>\n#include \"image_ppm.h\"\n#include <filesystem>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef Matrix<u_char, Dynamic, Dynamic> MatrixImg;\ntypedef Matrix<double, Dynamic, Dynamic> TempMatrixImg;\ntypedef Vector<u_char,Dynamic> ImgLine;\ntypedef Vector<double,Dynamic> TempImgLine;\n//typedef Matrix<ImgLine,Dynamic,Dynamic> FlattenedImages;\n\n\n\nunsigned char max(u_char a, u_char b){\n    if (a<b) return b;\n    else return a;\n}\n\nunsigned char min(u_char a, u_char b){\n    if (a>b) return b;\n    else return a;\n}\n\n\ndouble max(double a, double b){\n    if (a<b) return b;\n    else return a;\n}\n\ndouble min(double a, double b){\n    if (a>b) return b;\n    else return a;\n}\n\n\n\n\nvector<double> projectOnEigenSpace(vector<TempImgLine> eigenfaces, TempImgLine imToProj,int K){\n    vector<double> res = vector<double>();\n    for (int i=0;i<K;i++){\n        res.push_back(eigenfaces[i].dot(imToProj));\n    }\n    return res;\n}\n\nImgLine octToVec(OCTET* im, int nH, int nW){\n    ImgLine res(nH*nW);\n    for (int i=0; i<nH*nW;i++){\n        res(i)=im[i];\n    }\n    return res;\n}\n\n\n\n\nint main(){\n    vector<TempImgLine> eigenfaces;\n    int K =100; int nH;int nW;\n    for (int i=0; i<K;i++){\n        OCTET* im;\n        char name[50];\n        sprintf(name,\"eigenfaces/im%d.pgm\",i);\n        lire_nb_lignes_colonnes_image_pgm(name,&nH,&nW);\n        allocation_tableau(im,OCTET,nH*nW);\n        lire_image_pgm(name,im,nH*nW);\n        TempImgLine eigenFace(nH*nW) ;\n        double sum=0.0;\n        for (int j=0;j<nH*nW;j++){\n            eigenFace(j)=im[j]-127;\n            sum+=(double)(im[j]-127)*(double)(im[j]-127);\n        }\n        for (int j=0;j<nH*nW;j++){eigenFace(j)=eigenFace(j)/sqrt(sum);}\n        eigenfaces.push_back(eigenFace);\n        free(im);\n    }\n\n    OCTET* meanIm; allocation_tableau(meanIm,OCTET, nH*nW); lire_image_pgm(\"MEAN.pgm\",meanIm,nH*nW);\n    OCTET* felix; allocation_tableau(felix,OCTET,nH*nW); //lire_image_pgm(\"../Databases/yalefaces/test/pgms/subject01.noglasses.pgm\",felix,nH*nW);\n    lire_image_pgm(\"550.pgm\",felix,nH*nW);\n    //lire_image_pgm(\"felix320243.pgm\",felix,nH*nW);\n\n    //for (int i=0; i<nH*nW;i++){felix[i]=min(255,max(0,felix[i]-meanIm[i]));}\n\n    //ecrire_image_pgm(\"meanLessFix.pgm\",felix,nH,nW);\n\n    //cout<<eigenfaces[1]<<endl;\n    double sumF=0.0;\n    for (int i=0; i<nH*nW;i++){sumF+=(double)(felix[i]-127)*(double)(felix[i]-127);}\n    TempImgLine fixLine(nH*nW) ;for (int i=0;i<nH*nW;i++){fixLine(i)=(double)(felix[i]-127)/sumF;}\n    //cout<<fixLine<<endl;\n    //cout<<eigenfaces[0]<<endl;\n    //cout<<fixLine.dot(eigenfaces[0])<<endl;\n    vector<double> projs = projectOnEigenSpace(eigenfaces,fixLine,K);\n    double sum=0.0;\n    for (int i=0;i<K;i++){\n        //cout<<i<<\" : \"<<projs[i]<<endl;\n        sum+=projs[i];\n    }\n    //cout<<sum<<endl;\n\n    // for (int i=0;i<K;i++){\n    //     OCTET* im;allocation_tableau(im,OCTET,nH*nW);\n    //     for (int pix=0;pix<nH*nW;pix++){\n    //         im[pix]=eigenfaces[i](pix);\n\n    //     }\n    //     char name2[50];\n    //     sprintf(name2,\"testEigenFaces/im%d.pgm\",i);\n    //     ecrire_image_pgm(name2,im,nH,nW);\n    // }\n    \n    OCTET* reco; allocation_tableau(reco,OCTET, nH*nW);\n\n    TempImgLine recoTemp(nH*nW); for (int i=0;i<nH*nW;i++){recoTemp(i)=0.0;}\n\n    for (int i=0; i<K;i++){\n        for (int pix=0; pix<nH*nW;pix++){\n            recoTemp(pix)+=(projs[i]) * (eigenfaces[i])(pix);\n        }\n        //cout<<recoTemp<<endl;\n    }\n\n    // for (int i=0;i<nH*nW;i++){\n    //     recoTemp(i)+=meanIm[i];\n    // }\n\n\n    double minR=recoTemp(0); double maxR=recoTemp(0);\n    for (int i=0; i<nH*nW;i++){\n        minR=min(minR,recoTemp(i));\n        maxR=max(maxR,recoTemp(i));\n    }\n    cout<<minR<<\"  \"<<maxR<<endl;\n\n    for (int i=0;i<nH*nW;i++){\n        reco[i]=(unsigned char)((1.0/2.0)*(((recoTemp(i)-minR)*(255.0/(maxR-minR)))+(meanIm[i])));\n        //reco[i]=min(255,max(0,recoTemp(i)));\n        //cout<<(int)reco[i]<<endl;\n    }\n    \n\n    ecrire_image_pgm(\"RecoFelix.pgm\",reco,nH,nW);\n\n\n\n}", "meta": {"hexsha": "d571858fba973feb1ab4321762bc767724cb2ceb", "size": 4147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/eigenTesting.cpp", "max_stars_repo_name": "JPhilippot/FaceRecognition", "max_stars_repo_head_hexsha": "12a657d05f0103b0193a28a6347d1f41f466f0d0", "max_stars_repo_licenses": ["MIT"], "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/eigenTesting.cpp", "max_issues_repo_name": "JPhilippot/FaceRecognition", "max_issues_repo_head_hexsha": "12a657d05f0103b0193a28a6347d1f41f466f0d0", "max_issues_repo_licenses": ["MIT"], "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/eigenTesting.cpp", "max_forks_repo_name": "JPhilippot/FaceRecognition", "max_forks_repo_head_hexsha": "12a657d05f0103b0193a28a6347d1f41f466f0d0", "max_forks_repo_licenses": ["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.5833333333, "max_line_length": 146, "alphanum_fraction": 0.5907885218, "num_tokens": 1379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5401815699181435}}
{"text": "// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n// Copyright (c) 2013,2014 Pierre MOULON.\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 http://mozilla.org/MPL/2.0/.\n\n#include \"openMVG/geometry/box.hpp\"\n#include \"openMVG/geometry/frustum.hpp\"\n#include \"openMVG/geometry/half_space_intersection.hpp\"\n#include \"openMVG/multiview/projection.hpp\"\n#include \"openMVG/multiview/test_data_sets.hpp\"\n\n#include \"CppUnitLite/TestHarness.h\"\n#include \"testing/testing.h\"\n\n#include <Eigen/Geometry>\n\n#include <fstream>\n#include <iostream>\n\nusing namespace openMVG;\nusing namespace openMVG::geometry;\nusing namespace openMVG::geometry::halfPlane;\nusing namespace std;\n\n//--\n// Box/Camera frustum intersection unit test\n//--\n\nTEST(box_point, intersection)\n{\n  const Box box(Vec3::Zero(), sqrt(1.));\n\n  // Test with a point that is inside the defined volume\n  EXPECT_TRUE( box.contains(Vec3(0,0,0)) );\n\n  // Test with a point that is outside the defined volume\n  EXPECT_FALSE( box.contains(Vec3(1,1,1)) );\n}\n\nTEST(box_box, intersection)\n{\n  const double r = 1.;\n\n  // Test with a set of intersecting boxes\n  std::vector<HalfPlaneObject> boxes_ok;\n  for (int i=0; i < 6; ++i)\n  {\n    Vec3 center = Vec3::Zero();\n    center[i/2] += std::pow(-1, i%2) * r / 5.;\n    boxes_ok.emplace_back(Box(center, r));\n  }\n  EXPECT_TRUE( boxes_ok[0].intersect(boxes_ok[1]) );\n  EXPECT_TRUE( intersect(boxes_ok) );\n\n  // Test with a set of non-intersecting boxes\n  std::vector<HalfPlaneObject> boxes_ko;\n  for (int i=0; i < 6; ++i)\n  {\n    Vec3 center = Vec3::Zero();\n    center[i/2] += std::pow(-1, i%2) * 1.5 * r;\n    boxes_ko.emplace_back(Box(center, 1));\n  }\n  EXPECT_FALSE( boxes_ko[0].intersect(boxes_ko[1]) );\n  EXPECT_FALSE( intersect(boxes_ko) );\n}\n\nTEST(box_frustum, intersection)\n{\n  const int focal = 1000;\n  const int principal_Point = 500;\n  //-- Setup a circular camera rig or \"cardioid\".\n  const int iNviews = 4;\n  const int iNbPoints = 6;\n  const NViewDataSet d =\n    NRealisticCamerasRing(\n    iNviews, iNbPoints,\n    nViewDatasetConfigurator(focal, focal, principal_Point, principal_Point, 5, 0));\n\n  const Box box(Vec3::Zero(), sqrt(1.));\n  {\n    std::ostringstream os;\n    os << \"box.ply\";\n    Box::export_Ply(box, os.str());\n  }\n\n  // Test with infinite Frustum for each camera\n  {\n    for (int i=0; i < iNviews; ++i)\n    {\n      const Frustum f (principal_Point*2, principal_Point*2, d._K[i], d._R[i], d._C[i]);\n      EXPECT_TRUE(f.intersect(box));\n      EXPECT_TRUE(box.intersect(f));\n      EXPECT_TRUE(intersect({f, box}));\n\n      std::ostringstream os;\n      os << i << \"frust.ply\";\n      Frustum::export_Ply(f, os.str());\n    }\n  }\n\n  // Test with truncated frustum\n  {\n    // Build frustum with near and far plane defined by min/max depth per camera\n    for (int i=0; i < iNviews; ++i)\n    {\n      double minDepth = std::numeric_limits<double>::max();\n      double maxDepth = std::numeric_limits<double>::min();\n      for (int j=0; j < iNbPoints; ++j)\n      {\n        const double depth = Depth(d._R[i], d._t[i], d._X.col(j));\n        if (depth < minDepth)\n          minDepth = depth;\n        if (depth > maxDepth)\n          maxDepth = depth;\n      }\n      const Frustum f(principal_Point*2, principal_Point*2,\n          d._K[i], d._R[i], d._C[i], minDepth, maxDepth);\n\n      EXPECT_TRUE(f.intersect(box));\n      EXPECT_TRUE(box.intersect(f));\n      EXPECT_TRUE(intersect({f, box}));\n    }\n  }\n}\n\nTEST(box_frustum, no_intersection)\n{\n  const int focal = 1000;\n  const int principal_Point = 500;\n  //-- Setup a circular camera rig or \"cardioid\".\n  const int iNviews = 4;\n  const int iNbPoints = 6;\n  const NViewDataSet d =\n    NRealisticCamerasRing(\n      iNviews, iNbPoints,\n      nViewDatasetConfigurator(focal, focal, principal_Point, principal_Point, 5, 0));\n\n  // Put the box out of field of the camera\n  // (since camera are Y up, we move the box along Y axis)\n  const Vec3 position(0, -4, 0);\n  const Box box(position, sqrt(1.));\n  {\n    std::ostringstream os;\n    os << \"box.ply\";\n    Box::export_Ply(box, os.str());\n  }\n\n  // Test with infinite Frustum for each camera\n  {\n    std::vector<Frustum> vec_frustum;\n    for (int i = 0; i < iNviews; ++i)\n    {\n      const Frustum f(principal_Point * 2, principal_Point * 2, d._K[i], d._R[i], d._C[i]);\n      EXPECT_FALSE(f.intersect(box));\n      EXPECT_FALSE(box.intersect(f));\n      EXPECT_FALSE(intersect({f, box}));\n\n      std::ostringstream os;\n      os << i << \"frust.ply\";\n      Frustum::export_Ply(f, os.str());\n    }\n  }\n\n  // Test with truncated frustum\n  {\n    // Build frustum with near and far plane defined by min/max depth per camera\n    for (int i = 0; i < iNviews; ++i)\n    {\n      double minDepth = std::numeric_limits<double>::max();\n      double maxDepth = std::numeric_limits<double>::min();\n      for (int j = 0; j < iNbPoints; ++j)\n      {\n        const double depth = Depth(d._R[i], d._t[i], d._X.col(j));\n        if (depth < minDepth)\n          minDepth = depth;\n        if (depth > maxDepth)\n          maxDepth = depth;\n      }\n      const Frustum f(principal_Point * 2, principal_Point * 2,\n        d._K[i], d._R[i], d._C[i], minDepth, maxDepth);\n\n      EXPECT_FALSE(f.intersect(box));\n      EXPECT_FALSE(box.intersect(f));\n      EXPECT_FALSE(intersect({f, box}));\n    }\n  }\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "4fdb4504c77bb3a72a08baf605ffd745cba1c222", "size": 5633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/geometry/frustum_box_intersection_test.cpp", "max_stars_repo_name": "Aurelio93/satellite-pose-estimation", "max_stars_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2019-05-19T03:48:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:20:49.000Z", "max_issues_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/geometry/frustum_box_intersection_test.cpp", "max_issues_repo_name": "Aurelio93/satellite-pose-estimation", "max_issues_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-05-22T07:45:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T01:48:26.000Z", "max_forks_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/geometry/frustum_box_intersection_test.cpp", "max_forks_repo_name": "Aurelio93/satellite-pose-estimation", "max_forks_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-05-19T03:48:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-29T18:19:16.000Z", "avg_line_length": 28.8871794872, "max_line_length": 91, "alphanum_fraction": 0.6181430854, "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5400842930724734}}
{"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#ifndef MONTECARLO_HPP\r\n#define MONTECARLO_HPP\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 <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\tclass MonteCarlo : public Option\r\n\t{\r\n\tprivate:\r\n\t\t////////////////////////////\r\n\t\t// State Variables/Objects:\r\n\t\t////////////////////////////\r\n\t\tboost::variate_generator<boost::mt19937, boost::normal_distribution<double> > *mainRNG;\t/* Random number generator for Monte Carlo path generation. */\r\n\t\tunsigned long nSIM, nT;\t\t\t\t\t\t\t\t\t/* Number of trials and time intervals for price generator. */\r\n\tpublic:\r\n\t\t////////////////////////////\r\n\t\t// Constructors/Destructor:\r\n\t\t////////////////////////////\r\n\t\tMonteCarlo(double t, double s, double k, double b, double r, double sigma, bool isCall, unsigned long NSIM, unsigned long NT); /* Overloaded Constructor. Set all parameters AND set number of time intervals and simulations to run. */\r\n\t\tMonteCarlo(const MonteCarlo &in);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t/* Copy Constructor 1. */\r\n\t\tMonteCarlo(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\tvirtual ~MonteCarlo();\t\t\t\t\t\t\t\t\t/* Destructor. */\r\n\t\t////////////////////////////\r\n\t\t// Accessors:\r\n\t\t////////////////////////////\r\n\t\tunsigned long NSIM() const;\t\t\t\t\t\t\t\t/* Return number of simulations run in the Monte Carlo. */\r\n\t\tunsigned long 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\t////////////////////////////\r\n\t\t// Mutators:\r\n\t\t////////////////////////////\r\n\t\tvoid 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\tvoid 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\t////////////////////////////\r\n\t\t// Misc. Methods:\r\n\t\t////////////////////////////\r\n\t\tdouble Price() const;\t\t\t\t\t\t\t\t\t/* Calculate price using Monte Carlo method. */\r\n\t\t////////////////////////////\r\n\t\t// Overloaded Operators:\r\n\t\t////////////////////////////\r\n\t\tMonteCarlo& operator=(const MonteCarlo &in);\t\t    /* Assignment Operator. */\r\n\t};\r\n}\r\n#endif", "meta": {"hexsha": "c59cd672b615bc58ebe9a5170e32499a1ca8df71", "size": 3374, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Options/Files/MonteCarlo.hpp", "max_stars_repo_name": "BRutan/Cpp", "max_stars_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Options/Files/MonteCarlo.hpp", "max_issues_repo_name": "BRutan/Cpp", "max_issues_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Options/Files/MonteCarlo.hpp", "max_forks_repo_name": "BRutan/Cpp", "max_forks_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.8611111111, "max_line_length": 235, "alphanum_fraction": 0.6342620036, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.5400842884920046}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_BESSEL_FIRST_KIND_HPP\n#define STAN_MATH_PRIM_FUN_BESSEL_FIRST_KIND_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/err.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <stan/math/prim/functor/apply_scalar_binary.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n *\n   \\f[\n   \\mbox{bessel\\_first\\_kind}(v, x) =\n   \\begin{cases}\n     J_v(x) & \\mbox{if } -\\infty\\leq x \\leq \\infty \\\\[6pt]\n     \\textrm{error} & \\mbox{if } x = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{bessel\\_first\\_kind}(v, x)}{\\partial x} =\n   \\begin{cases}\n     \\frac{\\partial\\, J_v(x)}{\\partial x} & \\mbox{if } -\\infty\\leq x\\leq \\infty\n \\\\[6pt] \\textrm{error} & \\mbox{if } x = \\textrm{NaN} \\end{cases} \\f]\n\n   \\f[\n   J_v(x)=\\left(\\frac{1}{2}x\\right)^v\n   \\sum_{k=0}^\\infty \\frac{\\left(-\\frac{1}{4}x^2\\right)^k}{k!\\, \\Gamma(v+k+1)}\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, J_v(x)}{\\partial x} = \\frac{v}{x}J_v(x)-J_{v+1}(x)\n   \\f]\n *\n */\ntemplate <typename T2, require_arithmetic_t<T2>* = nullptr>\ninline T2 bessel_first_kind(int v, const T2 z) {\n  check_not_nan(\"bessel_first_kind\", \"z\", z);\n  return boost::math::cyl_bessel_j(v, z);\n}\n\n/**\n * Enables the vectorised application of the bessel first kind function, when\n * the first and/or second arguments are containers.\n *\n * @tparam T1 type of first input\n * @tparam T2 type of second input\n * @param a First input\n * @param b Second input\n * @return Bessel first kind function applied to the two inputs.\n */\ntemplate <typename T1, typename T2, require_any_container_t<T1, T2>* = nullptr,\n          require_not_var_matrix_t<T2>* = nullptr>\ninline auto bessel_first_kind(const T1& a, const T2& b) {\n  return apply_scalar_binary(a, b, [&](const auto& c, const auto& d) {\n    return bessel_first_kind(c, d);\n  });\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "706960afed3469a86db4c99092f51ab186902007", "size": 1861, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/bessel_first_kind.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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": "stan/math/prim/fun/bessel_first_kind.hpp", "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": "stan/math/prim/fun/bessel_first_kind.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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.6307692308, "max_line_length": 79, "alphanum_fraction": 0.6577109081, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5399992095760523}}
{"text": "#include \"Test.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXdR;\nJNIEXPORT void JNICALL Java_Test_inverse (JNIEnv *env, jclass cls,jdoubleArray jm1,  jdoubleArray jm2, jdoubleArray jr, jint nrow, jint ncol)\n{\n\tjboolean isCopy=JNI_TRUE;\n\tdouble* pm1=(double*)env->GetPrimitiveArrayCritical(jm1, &isCopy);\n\tdouble* pm2=(double*)env->GetPrimitiveArrayCritical(jm2, &isCopy);\n\tdouble* pr=(double*)env->GetPrimitiveArrayCritical(jr, &isCopy);\n\tEigen::Map<MatrixXdR> em1(pm1, nrow, ncol);\n\tEigen::Map<MatrixXdR> em2(pm2, nrow, ncol);\n\tEigen::Map<MatrixXdR> er(pr, nrow, ncol);\n\ter=em1*em2; //.inverse();\n\n\t/*\n\tstd::cout << \"----\" << std::endl;\n\tstd::cout << em1 << std::endl;\n\tstd::cout << em2 << std::endl;\n\tstd::cout << er << std::endl;\n\t*/\n\tenv->ReleasePrimitiveArrayCritical(jm1, pm1, 0);\n\tenv->ReleasePrimitiveArrayCritical(jm2, pm2, 0);\n\tenv->ReleasePrimitiveArrayCritical(jr, pr, 0);\n}\n\n\nJNIEXPORT void inverse(double* m1, double* m2, double* r, int nrow, int ncol)\n{\n\tEigen::Map<MatrixXdR> em1(m1, nrow, ncol);\n\tEigen::Map<MatrixXdR> em2(m2, nrow, ncol);\n\tEigen::Map<MatrixXdR> er(r, nrow, ncol);\n\t//er=em1*em2; //.inverse();\n}\n", "meta": {"hexsha": "f48df260b4b231ba5fe13a73ecedd570306b2858", "size": 1217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CommonWalkingControlModules/csrc/ActiveSetQP/JavaEigenTest/Test.cpp", "max_stars_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_stars_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 170.0, "max_stars_repo_stars_event_min_datetime": "2016-02-01T18:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T05:28:01.000Z", "max_issues_repo_path": "CommonWalkingControlModules/csrc/ActiveSetQP/JavaEigenTest/Test.cpp", "max_issues_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_issues_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 162.0, "max_issues_repo_issues_event_min_datetime": "2016-01-29T17:04:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T16:25:37.000Z", "max_forks_repo_path": "CommonWalkingControlModules/csrc/ActiveSetQP/JavaEigenTest/Test.cpp", "max_forks_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_forks_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2016-01-28T22:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:11:24.000Z", "avg_line_length": 33.8055555556, "max_line_length": 141, "alphanum_fraction": 0.6984387839, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5399991969057746}}
{"text": "// SPDX-License-Identifier: MIT\n// Copyright (c) 2019-2021 Thomas Vanderbruggen <th.vanderbruggen@gmail.com>\n\n#ifndef SCICPP_POLYNOMIALS_POLYNOMIAL\n#define SCICPP_POLYNOMIALS_POLYNOMIAL\n\n#include \"scicpp/core/equal.hpp\"\n#include \"scicpp/core/functional.hpp\"\n#include \"scicpp/core/macros.hpp\"\n#include \"scicpp/core/meta.hpp\"\n#include \"scicpp/core/numeric.hpp\"\n#include \"scicpp/linalg/solve.hpp\"\n#include \"scicpp/linalg/utils.hpp\"\n#include \"scicpp/signal/convolve.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <algorithm>\n#include <array>\n#include <cmath>\n#include <complex>\n#include <functional>\n#include <initializer_list>\n#include <iterator>\n#include <limits>\n#include <tuple>\n#include <utility>\n#include <vector>\n\nnamespace scicpp::polynomial {\n\n//---------------------------------------------------------------------------------\n// Polyval\n//---------------------------------------------------------------------------------\n\ntemplate <class T, class Array>\nauto polyval(T &&x, const Array &coeffs) {\n    if constexpr (meta::is_iterable_v<T>) {\n        return map([&](auto v) { return polyval(v, coeffs); },\n                   std::forward<T>(x));\n    } else {\n        using scalar_t = std::remove_reference_t<T>;\n        static_assert(std::is_same_v<scalar_t, typename Array::value_type>);\n\n        // https://en.wikipedia.org/wiki/Horner%27s_method\n        auto res = scalar_t{0};\n\n        std::for_each(coeffs.crbegin(), coeffs.crend(), [&](auto c) {\n            res = std::fma(res, x, c);\n        });\n\n        return res;\n    }\n}\n\n//---------------------------------------------------------------------------------\n// polyadd\n//---------------------------------------------------------------------------------\n\nnamespace detail {\n\ntemplate <class U, class V, class W>\nvoid add_arrays(const U &P1, const V &P2, W &P) {\n    using T = typename U::value_type;\n    static_assert(std::is_same_v<typename U::value_type, T>);\n    static_assert(std::is_same_v<typename W::value_type, T>);\n\n    if (P1.size() <= P2.size()) {\n        scicpp_require(P.size() >= P2.size());\n        std::transform(\n            P1.cbegin(), P1.cend(), P2.cbegin(), P.begin(), std::plus<T>());\n        std::copy(P2.cbegin() + int(P1.size()),\n                  P2.cend(),\n                  P.begin() + int(P1.size()));\n    } else {\n        scicpp_require(P.size() >= P1.size());\n        std::transform(\n            P2.cbegin(), P2.cend(), P1.cbegin(), P.begin(), std::plus<T>());\n        std::copy(P1.cbegin() + int(P2.size()),\n                  P1.cend(),\n                  P.begin() + int(P2.size()));\n    }\n}\n\n} // namespace detail\n\ntemplate <typename T, std::size_t M, std::size_t N>\nauto polyadd(const std::array<T, M> &P1, const std::array<T, N> &P2) {\n    std::array<T, (M > N ? M : N)> P{};\n    detail::add_arrays(P1, P2, P);\n    return P;\n}\n\ntemplate <typename T>\nauto polyadd(const std::vector<T> &P1, const std::vector<T> &P2) {\n    std::vector<T> P(P1.size() > P2.size() ? P1.size() : P2.size());\n    detail::add_arrays(P1, P2, P);\n    return P;\n}\n\n//---------------------------------------------------------------------------------\n// polysub\n//---------------------------------------------------------------------------------\n\nnamespace detail {\n\ntemplate <class U, class V, class W>\nvoid sub_arrays(const U &P1, const V &P2, W &P) {\n    using T = typename U::value_type;\n    static_assert(std::is_same_v<typename U::value_type, T>);\n    static_assert(std::is_same_v<typename W::value_type, T>);\n\n    if (P1.size() <= P2.size()) {\n        scicpp_require(P.size() >= P2.size());\n        std::transform(\n            P1.cbegin(), P1.cend(), P2.cbegin(), P.begin(), std::minus<T>());\n        std::transform(P2.cbegin() + int(P1.size()),\n                       P2.cend(),\n                       P.begin() + int(P1.size()),\n                       [](auto v) { return -v; });\n    } else {\n        scicpp_require(P.size() >= P1.size());\n        std::transform(P2.cbegin(),\n                       P2.cend(),\n                       P1.cbegin(),\n                       P.begin(),\n                       [](auto v2, auto v1) { return v1 - v2; });\n        std::copy(P1.cbegin() + int(P2.size()),\n                  P1.cend(),\n                  P.begin() + int(P2.size()));\n    }\n}\n\n} // namespace detail\n\ntemplate <typename T, std::size_t M, std::size_t N>\nauto polysub(const std::array<T, M> &P1, const std::array<T, N> &P2) {\n    std::array<T, (M > N ? M : N)> P{};\n    detail::sub_arrays(P1, P2, P);\n    return P;\n}\n\ntemplate <typename T>\nauto polysub(const std::vector<T> &P1, const std::vector<T> &P2) {\n    std::vector<T> P(P1.size() > P2.size() ? P1.size() : P2.size());\n    detail::sub_arrays(P1, P2, P);\n    return P;\n}\n\n//---------------------------------------------------------------------------------\n// polymul\n//---------------------------------------------------------------------------------\n\ntemplate <signal::ConvMethod method, class U, class V>\nauto polymul(const U &P1, const V &P2) {\n    return signal::convolve<method>(P1, P2);\n}\n\n// Specialization for the default convolution method\ntemplate <class U, class V>\nauto polymul(const U &P1, const V &P2) {\n    return polymul<signal::DIRECT>(P1, P2);\n}\n\n//---------------------------------------------------------------------------------\n// polydiv\n//---------------------------------------------------------------------------------\n\nnamespace detail {\n\n// https://stackoverflow.com/questions/44770632/fft-division-for-fast-polynomial-division\n// http://web.cs.iastate.edu/~cs577/handouts/polydivide.pdf\n\ntemplate <class U, class V>\nconstexpr auto polydiv_impl(const U &u, const V &v) {\n    using T = typename U::value_type;\n    static_assert(std::is_same_v<T, typename V::value_type>);\n\n    auto tmp(u);\n    const auto m = signed_size_t(u.size()) - 1;\n    const auto n = signed_size_t(v.size()) - 1;\n    const auto scale = T{1} / v[std::size_t(n)];\n\n    for (signed_size_t k = m - n; k >= 0; --k) {\n        const auto d = scale * tmp[std::size_t(n + k)];\n\n        for (signed_size_t j = n + k - 1; j >= k; --j) {\n            tmp[std::size_t(j)] -= d * v[std::size_t(j - k)];\n        }\n    }\n\n    return tmp;\n}\n\n} // namespace detail\n\ntemplate <typename T, std::size_t M, std::size_t N>\nconstexpr auto polydiv(const std::array<T, M> &u, const std::array<T, N> &v) {\n    static_assert(M > 0);\n    static_assert(N > 0);\n\n    if constexpr (N == 1) {\n        using namespace scicpp::operators;\n        return std::make_tuple(u / v[0], std::array<T, 1>{});\n    } else if constexpr (M < N) {\n        return std::make_tuple(std::array<T, 1>{}, u);\n    } else {\n        const auto tmp = detail::polydiv_impl(u, v);\n\n        std::array<T, M - N + 1> q{};\n        std::array<T, N - 1> r{};\n        std::move(tmp.begin(), tmp.begin() + r.size(), r.begin());\n        std::move(tmp.begin() + r.size(), tmp.end(), q.begin());\n        return std::make_tuple(q, r);\n    }\n}\n\ntemplate <typename T>\nauto polydiv(const std::vector<T> &u, const std::vector<T> &v) {\n    scicpp_require(!u.empty());\n    scicpp_require(!v.empty());\n\n    if (v.size() == 1) {\n        using namespace scicpp::operators;\n        return std::make_tuple(u / v[0], std::vector<T>(1, T{0}));\n    }\n\n    if (u.size() < v.size()) {\n        return std::make_tuple(std::vector<T>(1, T{0}), u);\n    }\n\n    const auto tmp = detail::polydiv_impl(u, v);\n    const auto len = signed_size_t(v.size()) - 1;\n\n    return std::make_tuple(\n        std::vector<T>(std::make_move_iterator(tmp.begin() + len),\n                       std::make_move_iterator(tmp.end())),\n        std::vector<T>(std::make_move_iterator(tmp.begin()),\n                       std::make_move_iterator(tmp.begin() + len)));\n}\n\n//---------------------------------------------------------------------------------\n// polymulx\n//---------------------------------------------------------------------------------\n\ntemplate <typename T, std::size_t N>\nauto polymulx(const std::array<T, N> &P) {\n    std::array<T, N + 1> res{};\n    std::copy(P.cbegin(), P.cend(), res.begin() + 1);\n    return res;\n}\n\ntemplate <typename T>\nauto polymulx(const std::vector<T> &P) {\n    std::vector<T> res(P.size() + 1);\n    std::copy(P.cbegin(), P.cend(), res.begin() + 1);\n    return res;\n}\n\ntemplate <typename T>\nauto polymulx(std::vector<T> &&P) {\n    P.push_back(T{0});\n    std::rotate(P.rbegin(), P.rbegin() + 1, P.rend());\n    return std::move(P);\n}\n\n//---------------------------------------------------------------------------------\n// polypow\n//---------------------------------------------------------------------------------\n\n// https://en.wikipedia.org/wiki/Exponentiation_by_squaring\n// - Recursive implementation is used for fixed size arrays (std::array).\n// - Iterative implementation is used for dynamic size arrays (std::vector).\n\ntemplate <std::size_t pow, typename T, std::size_t N>\nauto polypow(const std::array<T, N> &P) {\n    // Return a std::array<T, pow * (N - 1) + 1>\n    if constexpr (pow == 0) {\n        return std::array{T{1}};\n    } else if constexpr (pow == 1) {\n        return std::array{P};\n    } else {\n        if constexpr (pow % 2 == 0) {\n            return polypow<pow / 2>(polymul(P, P));\n        } else {\n            return polymul(P, polypow<(pow - 1) / 2>(polymul(P, P)));\n        }\n    }\n}\n\ntemplate <signal::ConvMethod method, typename T>\nauto polypow(const std::vector<T> &P, std::size_t pow) {\n    if (pow == 0) {\n        return std::vector(1, T{1});\n    } else if (pow == 1) {\n        return std::vector<T>(P.cbegin(), P.cend());\n    }\n\n    std::vector<T> x(P.cbegin(), P.cend());\n    std::vector<T> y(1, T(1));\n    x.reserve(pow * (P.size() - 1) + 1);\n    y.reserve(pow * (P.size() - 1) + 1);\n\n    while (pow > 1) {\n        if (pow % 2 == 1) {\n            y = std::move(polymul<method>(x, y));\n        }\n\n        pow = pow / 2;\n        x = std::move(polymul<method>(x, x));\n    }\n\n    return polymul(x, y);\n}\n\n// Specialization for the default convolution method (DIRECT)\ntemplate <typename T>\nauto polypow(const std::vector<T> &P, std::size_t pow) {\n    return polypow<signal::DIRECT>(P, pow);\n}\n\n//---------------------------------------------------------------------------------\n// polyder\n//---------------------------------------------------------------------------------\n\nnamespace detail {\n\ntemplate <typename T, std::size_t N>\nconstexpr auto polyder_once(const std::array<T, N> &P) {\n    static_assert(N >= 1);\n    std::array<T, N - 1> res{};\n\n    for (std::size_t i = 0; i < res.size(); ++i) {\n        res[i] = T(N - 1 - i) * P[i];\n    }\n\n    return res;\n}\n\ntemplate <typename T>\nvoid polyder_once(std::vector<T> &P) {\n    scicpp_require(P.size() >= 1);\n    const auto N = P.size();\n\n    for (std::size_t i = 0; i < (N - 1); ++i) {\n        P[i] *= T(N - 1 - i);\n    }\n\n    P.resize(N - 1);\n}\n\n} // namespace detail\n\ntemplate <signed_size_t m, typename T, std::size_t N>\nconstexpr auto polyder(const std::array<T, N> &P) {\n    static_assert(m >= 0);\n\n    if constexpr (m == 0) {\n        return std::array{P};\n    } else if constexpr (m >= N) {\n        return std::array<T, 0>{};\n    } else {\n        return polyder<m - 1>(detail::polyder_once(P));\n    }\n}\n\ntemplate <typename T, std::size_t N>\nconstexpr auto polyder(const std::array<T, N> &P) {\n    return polyder<1>(P);\n}\n\ntemplate <typename T>\nauto polyder(const std::vector<T> &P, signed_size_t m = 1) {\n    scicpp_require(m >= 0);\n\n    if (m == 0) {\n        return std::vector<T>(P);\n    }\n\n    if (m >= int(P.size())) {\n        return std::vector<T>(0);\n    }\n\n    std::vector<T> res(P);\n\n    while (m--) {\n        detail::polyder_once(res);\n    }\n\n    return res;\n}\n\n//---------------------------------------------------------------------------------\n// polyint\n//---------------------------------------------------------------------------------\n\nnamespace detail {\n\ntemplate <typename T, std::size_t N>\nconstexpr auto polyint_once(const std::array<T, N> &P) {\n    std::array<T, N + 1> res{};\n\n    for (std::size_t i = 0; i < N; ++i) {\n        res[i + 1] = P[i] / T(i + 1);\n    }\n\n    return res;\n}\n\ntemplate <typename T>\nvoid polyint_once(std::vector<T> &P) {\n    const auto N = P.size();\n    P.resize(N + 1);\n\n    for (signed_size_t i = signed_size_t(N) - 1; i >= 0; --i) {\n        P[std::size_t(i) + 1] = P[std::size_t(i)] / T(i + 1);\n    }\n\n    P[0] = T{0};\n}\n\n} // namespace detail\n\ntemplate <signed_size_t m, typename T, std::size_t N>\nconstexpr auto polyint(const std::array<T, N> &P) {\n    static_assert(N > 0);\n    static_assert(m >= 0);\n\n    if constexpr (m == 0) {\n        return std::array{P};\n    } else {\n        return polyint<m - 1>(detail::polyint_once(P));\n    }\n}\n\ntemplate <typename T, std::size_t N>\nconstexpr auto polyint(const std::array<T, N> &P) {\n    return polyint<1>(P);\n}\n\ntemplate <typename T>\nauto polyint(const std::vector<T> &P, signed_size_t m = 1) {\n    scicpp_require(P.size() > 0);\n    scicpp_require(m >= 0);\n\n    if (m == 0) {\n        return std::vector<T>(P);\n    }\n\n    std::vector<T> res(P);\n    res.reserve(P.size() + std::size_t(m));\n\n    while (m--) {\n        detail::polyint_once(res);\n    }\n\n    return res;\n}\n\n//---------------------------------------------------------------------------------\n// polycompanion\n//---------------------------------------------------------------------------------\n\ntemplate <typename T, std::size_t N>\nauto polycompanion(const std::array<T, N> &P) {\n    constexpr int deg = N - 1;\n    Eigen::Matrix<T, deg, deg> res{};\n    res.setZero();\n    res.diagonal(-1).setOnes();\n    res.col(deg - 1) = -linalg::to_eigen_array<deg>(P) / P[deg];\n    return res;\n}\n\ntemplate <typename T>\nauto polycompanion(const std::vector<T> &P) {\n    const int deg = int(P.size()) - 1;\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> res(deg, deg);\n    res.setZero();\n    res.diagonal(-1).setOnes();\n    res.col(deg - 1) = -linalg::to_eigen_matrix(P, deg) / P[std::size_t(deg)];\n    return res;\n}\n\n//---------------------------------------------------------------------------------\n// polyroots\n//---------------------------------------------------------------------------------\n\ntemplate <class Array>\nauto polyroots(const Array &P) {\n    return linalg::to_std_container(polycompanion(P).eigenvalues());\n}\n\n//---------------------------------------------------------------------------------\n// polyvander\n//---------------------------------------------------------------------------------\n\nnamespace detail {\n\ntemplate <class Matrix, class Vector>\nvoid polyvander_filler(Matrix &res, const Vector &x) {\n    static_assert(meta::is_eigen_matrix_v<Matrix>);\n\n    res.col(0).setOnes();\n    res.col(1) = linalg::to_eigen_array(x);\n\n    for (int i = 2; i < res.cols(); ++i) {\n        res.col(i) = res.col(i - 1).array() * res.col(1).array();\n    }\n}\n\n} // namespace detail\n\ntemplate <int deg, typename T, std::size_t N>\nauto polyvander(const std::array<T, N> &x) {\n    Eigen::Matrix<T, int(N), deg + 1> res{};\n    detail::polyvander_filler(res, x);\n    return res;\n}\n\ntemplate <typename T>\nauto polyvander(const std::vector<T> &x, int deg) {\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> res(int(x.size()),\n                                                         deg + 1);\n    detail::polyvander_filler(res, x);\n    return res;\n}\n\n//---------------------------------------------------------------------------------\n// polyfit\n//---------------------------------------------------------------------------------\n\ntemplate <int deg, typename T, std::size_t N>\nauto polyfit(const std::array<T, N> &x, const std::array<T, N> &y) {\n    return linalg::lstsq(polyvander<deg>(x), y);\n}\n\ntemplate <typename T>\nauto polyfit(const std::vector<T> &x, const std::vector<T> &y, int deg) {\n    return linalg::lstsq(polyvander(x, deg), y);\n}\n\n//---------------------------------------------------------------------------------\n// polytrim\n//---------------------------------------------------------------------------------\n\ntemplate <typename T>\nvoid polytrim(std::vector<T> &P, T tol = T{0}) {\n    P.erase(\n        std::find_if(P.crbegin(), P.crend(), [=](auto c) { return c > tol; })\n            .base(),\n        P.end());\n\n    if (P.empty()) {\n        P.push_back(T{0});\n    }\n}\n\n//---------------------------------------------------------------------------------\n// Polynomial class\n//---------------------------------------------------------------------------------\n\ntemplate <typename T>\nclass Polynomial {\n  public:\n    using value_type = typename std::vector<T>::value_type;\n    using size_type = typename std::vector<T>::size_type;\n\n    explicit Polynomial(size_type deg) : m_coef(deg + 1, T{0}) {}\n\n    explicit Polynomial(const std::vector<T> &coef) : m_coef(coef) {}\n    explicit Polynomial(std::vector<T> &&coef) : m_coef(std::move(coef)) {}\n\n    template <size_type N>\n    explicit Polynomial(const std::array<T, N> &coef)\n        : m_coef(coef.cbegin(), coef.cend()) {}\n\n    template <class Iterator>\n    Polynomial(Iterator first, Iterator last) : m_coef(first, last) {}\n\n    Polynomial(std::initializer_list<T> l)\n        : Polynomial(std::begin(l), std::end(l)) {}\n\n    size_type degree() const { return m_coef.size() - 1; }\n\n    const auto &data() const { return m_coef; }\n\n    void mulx() { m_coef = polymulx(std::move(m_coef)); }\n\n    void trim(T tol = T(0)) { polytrim(m_coef, tol); }\n\n    T operator()(T x) const { return polyval(x, m_coef); }\n\n    void reserve(size_type n_coefs) { m_coef.reserve(n_coefs); }\n\n    Polynomial &operator+=(const Polynomial &rhs) {\n        if (rhs.degree() > this->degree()) {\n            const long old_size = long(m_coef.size());\n            m_coef.resize(rhs.degree() + 1);\n            std::transform(rhs.m_coef.begin(),\n                           rhs.m_coef.begin() + old_size,\n                           m_coef.begin(),\n                           m_coef.begin(),\n                           std::plus<T>());\n            std::copy(rhs.m_coef.begin() + old_size,\n                      rhs.m_coef.end(),\n                      m_coef.begin() + old_size);\n        } else {\n            std::transform(rhs.m_coef.begin(),\n                           rhs.m_coef.end(),\n                           m_coef.begin(),\n                           m_coef.begin(),\n                           std::plus<T>());\n        }\n\n        return *this;\n    }\n\n    Polynomial &operator-=(const Polynomial &rhs) {\n        if (rhs.degree() > this->degree()) {\n            const auto old_size = m_coef.size();\n            m_coef.resize(rhs.degree() + 1);\n\n            for (size_type i = 0; i < old_size; ++i) {\n                m_coef[i] -= rhs.m_coef[i];\n            }\n\n            for (size_type i = old_size; i < m_coef.size(); ++i) {\n                m_coef[i] = -rhs.m_coef[i];\n            }\n        } else {\n            for (size_type i = 0; i < rhs.degree() + 1; ++i) {\n                m_coef[i] -= rhs.m_coef[i];\n            }\n        }\n\n        return *this;\n    }\n\n    Polynomial &operator*=(T scalar) {\n        for (auto &c : m_coef) {\n            c *= scalar;\n        }\n\n        return *this;\n    }\n\n    Polynomial &operator*=(const Polynomial &rhs) {\n        m_coef = std::move(polymul(m_coef, rhs.m_coef));\n        return *this;\n    }\n\n    Polynomial operator+(const Polynomial &rhs) const {\n        auto tmp(*this);\n        tmp += rhs;\n        return tmp;\n    }\n\n    Polynomial operator-(const Polynomial &rhs) const {\n        auto tmp(*this);\n        tmp -= rhs;\n        return tmp;\n    }\n\n    Polynomial operator*(const Polynomial &rhs) const {\n        auto tmp(*this);\n        tmp *= rhs;\n        return tmp;\n    }\n\n    bool scicpp_pure operator==(const Polynomial &rhs) const {\n        return m_coef == rhs.m_coef;\n    }\n\n    bool scicpp_pure operator!=(const Polynomial &rhs) const {\n        return m_coef != rhs.m_coef;\n    }\n\n    template <int rel_tol = 1>\n    bool is_approx(const Polynomial &rhs) const {\n        return almost_equal<rel_tol>(m_coef, rhs.m_coef);\n    }\n\n  private:\n    std::vector<T> m_coef;\n\n}; // class Polynomial\n\ntemplate <typename T>\nPolynomial<T> operator*(const Polynomial<T> &P, T scalar) {\n    auto tmp(P);\n    tmp *= scalar;\n    return tmp;\n}\n\ntemplate <typename T>\nPolynomial<T> operator*(T scalar, const Polynomial<T> &P) {\n    return P * scalar;\n}\n\n//---------------------------------------------------------------------------------\n// polyfromroots\n//---------------------------------------------------------------------------------\n\n// https://stackoverflow.com/questions/33594384/find-the-coefficients-of-the-polynomial-given-its-roots\ntemplate <class Array>\nauto polyfromroots(const Array &roots) {\n    using T = typename Array::value_type;\n\n    auto P = Polynomial<T>({T{1}});\n    auto P_ = Polynomial<T>({T{1}});\n    P.reserve(roots.size() + 1);\n    P_.reserve(roots.size());\n\n    for (const auto &r : roots) {\n        P_ = P * r;\n        P.mulx();\n        P -= P_;\n    }\n\n    return P;\n}\n\n} // namespace scicpp::polynomial\n\n#endif // SCICPP_POLYNOMIALS_POLYNOMIAL", "meta": {"hexsha": "da1ced961f25475777fdd3ae9dce344a95bd2c43", "size": 20952, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "scicpp/polynomials/polynomial.hpp", "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": "scicpp/polynomials/polynomial.hpp", "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": "scicpp/polynomials/polynomial.hpp", "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": 28.8993103448, "max_line_length": 103, "alphanum_fraction": 0.4906930126, "num_tokens": 5363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5399357810824265}}
{"text": "/*******************************************************************************\n *\n * Standard domain of numerical congruences extended with bitwise\n * operations.\n *\n * Author: Alexandre C. D. Wimmers (alexandre.c.wimmers@nasa.gov)\n *\n * Contributors: Jorge A. Navas (jorge.a.navaslaserna@nasa.gov)\n *\n * Notices:\n *\n * Copyright (c) 2011 United States Government as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * All Rights Reserved.\n *\n * Disclaimers:\n *\n * No Warranty: THE SUBJECT SOFTWARE IS PROVIDED \"AS IS\" WITHOUT ANY WARRANTY OF\n * ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED\n * TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS,\n * ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,\n * OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE\n * ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO\n * THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN\n * ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS,\n * RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS\n * RESULTING FROM USE OF THE SUBJECT SOFTWARE.  FURTHER, GOVERNMENT AGENCY\n * DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE,\n * IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT \"AS IS.\"\n *\n * Waiver and Indemnity:  RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST\n * THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL\n * AS ANY PRIOR RECIPIENT.  IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS\n * IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH\n * USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM,\n * RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD\n * HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS,\n * AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW.\n * RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE,\n * UNILATERAL TERMINATION OF THIS AGREEMENT.\n *\n ******************************************************************************/\n\n#pragma once\n\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/backward_assign_operations.hpp>\n#include <crab/domains/interval.hpp>\n#include <crab/domains/separate_domains.hpp>\n#include <crab/support/debug.hpp>\n#include <crab/support/stats.hpp>\n#include <crab/types/variable.hpp>\n\n#include <boost/optional.hpp>\n\nnamespace ikos {\n\ntemplate <typename Number> class congruence {\n  using interval_t = interval<Number>;\n\npublic:\n  using congruence_t = congruence<Number>;\n\nprivate:\n  bool _is_bottom;\n\n  /// A congruence is denoted by aZ + b, where b \\in Z and a \\in N.\n  /// The abstract state aZ + b represents all numbers that are\n  /// congruent to b modulo a.\n  Number _a; // modulo\n  Number _b; // remainder\n\n  // Notes about the % operator\n  //\n  // The semantics of r = n % d is to set r to \"n mod d\". The sign of\n  // the d is ignored and r is always non-negative.\n  //\n  // We assume that n % d (also n /d) raises a runtime error if d==0.\n\n  void normalize(void) {\n    // Set to standard form: 0 <= b < a for a != 0\n    if (_a != 0) {\n      _b = _b % _a;\n    }\n  }\n\n  // if true then top (1Z + 0) else bottom\n  congruence(bool b) : _is_bottom(!b), _a(1), _b(0) {}\n\n  congruence(int n) : _is_bottom(false), _a(0), _b(n) {}\n\n  congruence(Number a, Number b) : _is_bottom(false), _a(a), _b(b) {\n    normalize();\n  }\n\n  Number abs(Number x) const { return x < 0 ? -x : x; }\n\n  Number max(Number x, Number y) const { return x.operator<=(y) ? y : x; }\n\n  Number min(Number x, Number y) const { return x.operator<(y) ? x : y; }\n\n  Number gcd(Number x, Number y, Number z) const { return gcd(x, gcd(y, z)); }\n  // Not to be called explicitly outside of gcd\n  Number gcd_helper(Number x, Number y) const {\n    return (y == 0) ? x : gcd_helper(y, x % y);\n  }\n  Number gcd(Number x, Number y) const { return gcd_helper(abs(x), abs(y)); }\n\n  Number lcm(Number x, Number y) const {\n    Number tmp = gcd(x, y);\n    return abs(x * y) / tmp;\n  }\n\n  bool is_zero() const { return !is_bottom() && _a == 0 && _b == 0; }\n\n  bool all_ones() const { return !is_bottom() && _a == 0 && _b == -1; }\n\n  interval_t to_interval() const {\n    assert(singleton());\n    return interval_t(*(singleton()));\n  }\n\npublic:\n  static congruence_t top() { return congruence(true); }\n\n  static congruence_t bottom() { return congruence(false); }\n\n  congruence() : _is_bottom(false), _a(1), _b(0) {}\n\n  congruence(Number n) : _is_bottom(false), _a(0), _b(n) {}\n\n  congruence(const congruence_t &o)\n      : _is_bottom(o._is_bottom), _a(o._a), _b(o._b) {}\n\n  congruence_t operator=(congruence_t o) {\n    _is_bottom = o._is_bottom;\n    _a = o._a;\n    _b = o._b;\n    return *this;\n  }\n\n  bool is_bottom() const { return _is_bottom; }\n\n  bool is_top() const { return _a == 1; }\n\n  boost::optional<Number> singleton() const {\n    if (!this->is_bottom() && _a == 0) {\n      return boost::optional<Number>(_b);\n    } else {\n      return boost::optional<Number>();\n    }\n  }\n\n  Number get_modulo() const { return _a; }\n\n  Number get_remainder() const { return _b; }\n\n  bool operator==(congruence_t o) const {\n    return (is_bottom() == o.is_bottom() && _a == o._a && _b == o._b);\n  }\n\n  bool operator!=(congruence_t x) const { return !this->operator==(x); }\n\n  /** Lattice Operations **/\n\n  bool operator<=(const congruence_t &o) const {\n    if (is_bottom()) {\n      return true;\n    } else if (o.is_bottom()) {\n      return false;\n    } else if (_a == 0 && o._a == 0) {\n      return (_b == o._b);\n    } else if (_a == 0) {\n      if ((_b % o._a) == (o._b % o._a)) {\n        return true;\n      }\n    } else if (o._a == 0) {\n      if (_b % _a == (o._b % _a)) {\n        return false;\n      }\n    }\n    return (_a % o._a == 0) && (_b % o._a == o._b % o._a);\n  }\n\n  congruence_t operator|(congruence_t o) {\n    if (is_bottom()) {\n      return o;\n    } else if (o.is_bottom()) {\n      return *this;\n    } else if (is_top() || o.is_top()) {\n      return top();\n    } else {\n      return congruence_t(gcd(_a, o._a, abs(_b - o._b)), min(_b, o._b));\n    }\n  }\n\n  congruence_t operator&(congruence_t o) {\n    if (is_bottom() || o.is_bottom()) {\n      return bottom();\n    }\n\n    // lcm has meaning only if both a and o.a are not 0\n    if (_a == 0 && o._a == 0) {\n      if (_b == o._b) {\n        return *this;\n      } else {\n        return bottom();\n      }\n    } else if (_a == 0) {\n      // b & a'Z + b' iff \\exists k such that a'*k + b' = b iff ((b - b') %a' ==\n      // 0)\n      if ((_b - o._b) % o._a == 0) {\n        return *this;\n      } else {\n        return bottom();\n      }\n    } else if (o._a == 0) {\n      // aZ+b & b' iff \\exists k such that a*k+b  = b' iff ((b'-b %a) == 0)\n      if ((o._b - _b) % _a == 0) {\n        return o;\n      } else {\n        return bottom();\n      }\n    } else {\n      // pre: a and o.a != 0\n      Number x = gcd(_a, o._a);\n      if (_b % x == (o._b % x)) {\n        // the part max(b,o.b) needs to be verified. What we really\n        // want is to find b'' such that\n        // 1) b'' % lcm(a,a') == b  % lcm(a,a'), and\n        // 2) b'' % lcm(a,a') == b' % lcm(a,a').\n        // An algorithm for that is provided in Granger'89.\n        return congruence_t(lcm(_a, o._a), max(_b, o._b));\n      } else {\n        return congruence_t::bottom();\n      }\n    }\n  }\n\n  congruence_t operator||(congruence_t o) {\n    // Equivalent to join, domain is flat\n    return *this | o;\n  }\n\n  congruence_t operator&&(congruence_t o) {\n    // Simply refines top element\n    return (is_top()) ? o : *this;\n  }\n\n  /** Arithmetic Operators **/\n\n  congruence_t operator+(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else\n      return congruence_t(gcd(_a, o._a), _b + o._b);\n  }\n\n  congruence_t operator-(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else\n      return congruence_t(gcd(_a, o._a), _b - o._b);\n  }\n\n  congruence_t operator-() {\n    if (this->is_bottom() || this->is_top())\n      return *this;\n    else\n      return congruence_t(_a, -_b + _a);\n  }\n\n  congruence_t operator*(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if ((this->is_top() || o.is_top()) && _a != 0 && o._a != 0)\n      return congruence_t::top();\n    else\n      return congruence_t(gcd(_a * o._a, _a * o._b, o._a * _b), _b * o._b);\n  }\n\n  // signed division\n  congruence_t operator/(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (o == congruence(0))\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n\n      /*\n         aZ+b / 0Z+b':\n            if b'|a then  (a/b')Z + b/b'\n            else          top\n      */\n      if (o._a == 0) {\n        if (_a % o._b == 0)\n          return congruence_t(_a / o._b, _b / o._b);\n        else\n          return congruence_t::top();\n      }\n\n      /*\n         0Z+b / a'Z+b':\n            if N>0   (b div N)Z + 0\n            else     0Z + 0\n\n           where N = a'((b-b') div a') + b'\n      */\n      if (_a == 0) {\n        Number n(o._a * (((_b - o._b) / o._a) + o._b));\n        if (n > 0) {\n          return congruence_t(_b / n, 0);\n        } else {\n          return congruence_t(0, 0);\n        }\n      }\n\n      /*\n        General case: no singleton\n      */\n      return congruence_t::top();\n    }\n  }\n\n  // signed remainder operator\n  congruence_t operator%(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (o == congruence(0))\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n      /*\n         aZ+b mod 0Z+b':\n             if b'|a then  (a/b')Z + b/b'\n             else          top\n      */\n      if (o._a == 0) {\n        if (_a % o._b == 0) {\n          return congruence_t(0, _b % o._b);\n        } else {\n          return congruence_t(gcd(_a, o._b), _b);\n        }\n      }\n\n      /*\n          0Z+b mod a'Z+b':\n           if N<=0           then 0Z+b\n           if (b div N) == 1 then gcd(b',a')Z + b\n           if (b div N) >= 2 then N(b div N)Z  + b\n\n         where N = a'((b-b') div a') + b'\n      */\n      if (_a == 0) {\n        Number n(o._a * (((_b - o._b) / o._a) + o._b));\n        if (n <= 0) {\n          return congruence_t(_a, _b);\n        } else if (_b == n) {\n          return congruence_t(gcd(o._b, o._a), _b);\n        } else if ((_b / n) >= 2) {\n          return congruence_t(_b, _b);\n        } else {\n          CRAB_ERROR(\"unreachable\");\n        }\n      }\n\n      /*\n          general case: no singleton\n      */\n      return congruence_t(gcd(_a, o._a, o._b), _b);\n    }\n  }\n\n  /**\n      Bitwise operators.\n      They are very imprecise because we ignore bitwidth.\n\n      Bitwise operation can be implemented more precisely based on\n      Stefan Bygde's paper: Static WCET analysis based on abstract\n      interpretation and counting of elements, Vasteras : School of\n      Innovation, Design and Engineering, Malardalen University (2010).\n   **/\n\n  congruence_t And(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n      if (is_zero() || o.is_zero()) {\n        return congruence_t(0);\n      } else if (all_ones()) {\n        return o;\n      } else if (o.all_ones()) {\n        return *this;\n      } else if (_a == 0 && o._a == 0) {\n        return congruence_t(_b & o._b);\n      } else {\n        return top();\n      }\n    }\n  }\n\n  congruence_t Or(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n      if (all_ones() || o.all_ones()) {\n        return congruence_t(-1);\n      } else if (is_zero()) {\n        return o;\n      } else if (o.is_zero()) {\n        return *this;\n      } else if (_a == 0 && o._a == 0) {\n        return congruence_t(_b | o._b);\n      } else {\n        return top();\n      }\n    }\n  }\n\n  congruence_t Xor(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n      if (is_zero()) {\n        return o;\n      } else if (o.is_zero()) {\n        return *this;\n      } else if (_a == 0 && o._a == 0) {\n        return congruence_t(_b ^ o._b);\n      } else {\n        return top();\n      }\n    }\n  }\n\n  congruence_t Shl(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n\n      if (o._a == 0) { // singleton\n\n        if (o._b < 0) {\n          return bottom();\n        }\n\n        // aZ + b << 0Z + b'  = (a*2^b')Z + b*2^b'\n        Number x = Number(1) << o._b;\n        return congruence_t(_a * x, _b * x);\n      } else {\n\n        Number x = Number(1) << o._b;\n        Number y = Number(1) << o._a;\n        // aZ + b << a'Z + b' = (gcd(a, b * (2^a' - 1)))*(2^b')Z + b*(2^b')\n        return congruence_t(gcd(_a, _b * (y - 1)) * x, _b * x);\n      }\n    }\n  }\n\n  congruence_t AShr(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n\n      if (o._a == 0) { // singleton\n        // aZ + b >> 0Z + b'\n        if (o._b < 0) {\n          return congruence_t::bottom();\n        }\n      }\n\n      if (singleton() && o.singleton()) {\n        interval_t res = to_interval().AShr(o.to_interval());\n        if (boost::optional<Number> n = res.singleton()) {\n          return congruence(*n);\n        }\n      }\n\n      return congruence_t::top();\n    }\n  }\n\n  congruence_t LShr(congruence_t o) {\n    if (this->is_bottom() || o.is_bottom())\n      return congruence_t::bottom();\n    else if (this->is_top() || o.is_top())\n      return congruence_t::top();\n    else {\n\n      if (o._a == 0) {\n        // aZ + b >> 0Z + b'\n        if (o._b < 0) {\n          return congruence_t::bottom();\n        }\n      }\n\n      if (singleton() && o.singleton()) {\n        interval_t res = to_interval().LShr(o.to_interval());\n        if (boost::optional<Number> n = res.singleton()) {\n          return congruence(*n);\n        }\n      }\n\n      return congruence_t::top();\n    }\n  }\n\n  // division and remainder operations\n\n  congruence_t SDiv(congruence_t x) { return this->operator/(x); }\n\n  congruence_t UDiv(congruence_t x) { return congruence_t::top(); }\n\n  congruence_t SRem(congruence_t x) { return this->operator%(x); }\n\n  congruence_t URem(congruence_t x) { return congruence_t::top(); }\n\n  void write(crab::crab_os &o) const {\n    if (is_bottom()) {\n      o << \"_|_\";\n      return;\n    }\n\n    if (_a == 0) {\n      o << _b;\n      return;\n    }\n\n    o << _a << \"Z+\" << _b;\n  }\n}; // end class congruence\n\ntemplate <typename Number>\ninline crab::crab_os &operator<<(crab::crab_os &o,\n                                 const congruence<Number> &c) {\n  c.write(o);\n  return o;\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator+(Number c, congruence<Number> x) {\n  return congruence<Number>(c) + x;\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator+(congruence<Number> x, Number c) {\n  return x + congruence<Number>(c);\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator*(Number c, congruence<Number> x) {\n  return congruence<Number>(c) * x;\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator*(congruence<Number> x, Number c) {\n  return x * congruence<Number>(c);\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator/(Number c, congruence<Number> x) {\n  return congruence<Number>(c) / x;\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator/(congruence<Number> x, Number c) {\n  return x / congruence<Number>(c);\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator-(Number c, congruence<Number> x) {\n  return congruence<Number>(c) - x;\n}\n\ntemplate <typename Number>\ninline congruence<Number> operator-(congruence<Number> x, Number c) {\n  return x - congruence<Number>(c);\n}\n\ntemplate <typename Number, typename VariableName, typename CongruenceCollection>\nclass equality_congruence_solver {\n  // TODO: check correctness of the solver. Granger provides a sound\n  // and more precise solver for equality linear congruences (see\n  // Theorem 4.4).\nprivate:\n  using congruence_t = congruence<Number>;\n  using variable_t = crab::variable<Number, VariableName>;\n  using linear_expression_t = linear_expression<Number, VariableName>;\n  using linear_constraint_t = linear_constraint<Number, VariableName>;\n  using linear_constraint_system_t =\n      linear_constraint_system<Number, VariableName>;\n\n  using cst_table_t = std::vector<linear_constraint_t>;\n  using variable_set_t = std::set<variable_t>;\n\n  std::size_t m_max_cycles;\n  bool m_is_contradiction;\n  cst_table_t m_cst_table;\n  variable_set_t m_refined_variables;\n  std::size_t m_op_count;\n\nprivate:\n  bool refine(const variable_t &v, congruence_t i, CongruenceCollection &env) {\n    congruence_t old_i = env[v];\n    congruence_t new_i = old_i & i;\n    if (new_i.is_bottom()) {\n      return true;\n    }\n    if (old_i != new_i) {\n      env.set(v, new_i);\n      m_refined_variables.insert(v);\n      ++(m_op_count);\n    }\n    return false;\n  }\n\n  congruence_t compute_residual(const linear_constraint_t &cst,\n                                const variable_t &pivot,\n                                CongruenceCollection &env) {\n    congruence_t residual(cst.constant());\n    for (auto kv : cst) {\n      const variable_t &v = kv.second;\n      if (!(v == pivot)) {\n        residual = residual - (kv.first * env[v]);\n        ++(m_op_count);\n      }\n    }\n    return residual;\n  }\n\n  bool propagate(const linear_constraint_t &cst, CongruenceCollection &env) {\n    for (auto kv : cst) {\n      Number c = kv.first;\n      const variable_t &pivot = kv.second;\n      congruence_t rhs = compute_residual(cst, pivot, env) / congruence_t(c);\n\n      if (cst.is_equality()) {\n        if (refine(pivot, rhs, env)) {\n          return true;\n        }\n      } else if (cst.is_inequality() || cst.is_strict_inequality()) {\n        // Inequations (>=, <=, >, and <) do not work well with\n        // congruences because for any number n there is always x and y\n        // \\in gamma(aZ+b) such that n < x and n > y.\n        //\n        // The only cases we can catch is when all the expressions\n        // are constants. We do not bother because any product\n        // with intervals or constants should get those cases.\n        continue;\n      } else {\n        // TODO: cst is a disequation\n      }\n    }\n    return false;\n  }\n\n  bool solve_system(CongruenceCollection &env) {\n    std::size_t cycle = 0;\n    do {\n      ++cycle;\n      m_refined_variables.clear();\n      for (const linear_constraint_t &cst : m_cst_table) {\n        if (propagate(cst, env)) {\n          return true;\n        }\n      }\n    } while (m_refined_variables.size() > 0 && cycle <= m_max_cycles);\n    return false;\n  }\n\npublic:\n  equality_congruence_solver(const linear_constraint_system_t &csts,\n                             std::size_t max_cycles)\n      : m_max_cycles(max_cycles), m_is_contradiction(false) {\n    for (auto const &cst : csts) {\n      if (cst.is_contradiction()) {\n        m_is_contradiction = true;\n        return;\n      } else if (cst.is_tautology()) {\n        continue;\n      } else {\n        m_cst_table.push_back(cst);\n      }\n    }\n  }\n\n  void run(CongruenceCollection &env) {\n    if (m_is_contradiction) {\n      env.set_to_bottom();\n    } else {\n      if (solve_system(env)) {\n        env.set_to_bottom();\n      }\n    }\n  }\n\n}; // class equality_congruence_solver\n\ntemplate <typename Number, typename VariableName>\nclass congruence_domain final : public crab::domains::abstract_domain_api<\n                                    congruence_domain<Number, VariableName>> {\npublic:\n  using congruence_t = congruence<Number>;\n\nprivate:\n  // note that this is assuming that all variables have the same bit\n  // width which is unrealistic.\n  using congruence_domain_t = congruence_domain<Number, VariableName>;\n  using abstract_domain_t =\n      crab::domains::abstract_domain_api<congruence_domain_t>;\n\npublic:\n  using typename abstract_domain_t::disjunctive_linear_constraint_system_t;\n  using typename abstract_domain_t::interval_t;\n  using typename abstract_domain_t::linear_constraint_system_t;\n  using typename abstract_domain_t::linear_constraint_t;\n  using typename abstract_domain_t::linear_expression_t;\n  using typename abstract_domain_t::variable_or_constant_t;\n  using typename abstract_domain_t::variable_t;\n  using typename abstract_domain_t::variable_vector_t;\n  using typename abstract_domain_t::variable_or_constant_vector_t;  \n  using number_t = Number;\n  using varname_t = VariableName;\n  using typename abstract_domain_t::reference_constraint_t;\n\nprivate:\n  using separate_domain_t = separate_domain<variable_t, congruence_t>;\n  using solver_t =\n      equality_congruence_solver<number_t, varname_t, separate_domain_t>;\n\npublic:\n  using iterator = typename separate_domain_t::iterator;\n\nprivate:\n  separate_domain_t _env;\n\nprivate:\n  congruence_domain(separate_domain_t env) : _env(env) {}\n\npublic:\n  congruence_domain_t make_top() const override {\n    return congruence_domain_t(separate_domain_t::top());\n  }\n\n  congruence_domain_t make_bottom() const override {\n    return congruence_domain_t(separate_domain_t::bottom());\n  }\n\n  void set_to_top() override {\n    congruence_domain abs(separate_domain_t::top());\n    std::swap(*this, abs);\n  }\n\n  void set_to_bottom() override {\n    congruence_domain abs(separate_domain_t::bottom());\n    std::swap(*this, abs);\n  }\n\n  congruence_domain() : _env(separate_domain_t::top()) {}\n\n  congruence_domain(const congruence_domain_t &e) : _env(e._env) {\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n  }\n\n  congruence_domain_t &operator=(const congruence_domain_t &o) {\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n    if (this != &o)\n      this->_env = o._env;\n    return *this;\n  }\n\n  iterator begin() { return this->_env.begin(); }\n\n  iterator end() { return this->_env.end(); }\n\n  bool is_bottom() const override { return this->_env.is_bottom(); }\n\n  bool is_top() const override { return this->_env.is_top(); }\n\n  bool operator<=(const congruence_domain_t &e) const override {\n    crab::CrabStats::count(domain_name() + \".count.leq\");\n    crab::ScopedCrabStats __st__(domain_name() + \".leq\");\n    return this->_env <= e._env;\n  }\n\n  void operator|=(const congruence_domain_t &e) override {\n    crab::CrabStats::count(domain_name() + \".count.join\");\n    crab::ScopedCrabStats __st__(domain_name() + \".join\");\n    this->_env = this->_env | e._env;\n  }\n\n  congruence_domain_t operator|(const congruence_domain_t &e) const override {\n    crab::CrabStats::count(domain_name() + \".count.join\");\n    crab::ScopedCrabStats __st__(domain_name() + \".join\");\n    return this->_env | e._env;\n  }\n\n  congruence_domain_t operator&(const congruence_domain_t &e) const override {\n    crab::CrabStats::count(domain_name() + \".count.meet\");\n    crab::ScopedCrabStats __st__(domain_name() + \".meet\");\n    return this->_env & e._env;\n  }\n\n  congruence_domain_t operator||(const congruence_domain_t &e) const override {\n    crab::CrabStats::count(domain_name() + \".count.widening\");\n    crab::ScopedCrabStats __st__(domain_name() + \".widening\");\n    return this->_env || e._env;\n  }\n\n  congruence_domain_t widening_thresholds(\n      const congruence_domain_t &other,\n      const crab::iterators::thresholds<number_t> &) const override {\n    return (*this || other);\n  }\n\n  congruence_domain_t operator&&(const congruence_domain_t &e) const override {\n    crab::CrabStats::count(domain_name() + \".count.narrowing\");\n    crab::ScopedCrabStats __st__(domain_name() + \".narrowing\");\n    return this->_env && e._env;\n  }\n\n  void set(const variable_t &v, congruence_t i) {\n    crab::CrabStats::count(domain_name() + \".count.assign\");\n    crab::ScopedCrabStats __st__(domain_name() + \".assign\");\n    this->_env.set(v, i);\n  }\n\n  void set(const variable_t &v, number_t n) {\n    crab::CrabStats::count(domain_name() + \".count.assign\");\n    crab::ScopedCrabStats __st__(domain_name() + \".assign\");\n    this->_env.set(v, congruence_t(n));\n  }\n\n  void operator-=(const variable_t &v) override {\n    crab::CrabStats::count(domain_name() + \".count.forget\");\n    crab::ScopedCrabStats __st__(domain_name() + \".forget\");\n    this->_env -= v;\n  }\n\n  virtual interval_t operator[](const variable_t &v) override {\n    CRAB_WARN(domain_name(), \"::operator[] not implemented\");\n    return interval_t::top();\n  }\n\n  congruence_t to_congruence(const variable_t &v) { return this->_env[v]; }\n\n  congruence_t to_congruence(const linear_expression_t &expr) {\n    congruence_t r(expr.constant());\n    for (auto kv : expr) {\n      congruence_t c(kv.first);\n      r = r + (c * to_congruence(kv.second));\n    }\n    return r;\n  }\n\n  void operator+=(const linear_constraint_system_t &csts) override {\n    crab::CrabStats::count(domain_name() + \".count.add_constraints\");\n    crab::ScopedCrabStats __st__(domain_name() + \".add_constraints\");\n    const std::size_t threshold = 10;\n    if (!this->is_bottom()) {\n      solver_t solver(csts, threshold);\n      solver.run(this->_env);\n    }\n  }\n\n  void assign(const variable_t &x, const linear_expression_t &e) override {\n    crab::CrabStats::count(domain_name() + \".count.assign\");\n    crab::ScopedCrabStats __st__(domain_name() + \".assign\");\n\n    congruence_t r = e.constant();\n    for (auto kv : e) {\n      r = r + (kv.first * this->_env[kv.second]);\n    }\n    this->_env.set(x, r);\n  }\n\n  void apply(crab::domains::arith_operation_t op, const variable_t &x,\n             const variable_t &y, const variable_t &z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    congruence_t yi = this->_env[y];\n    congruence_t zi = this->_env[z];\n    congruence_t xi = congruence_t::bottom();\n\n    switch (op) {\n    case crab::domains::OP_ADDITION:\n      xi = yi + zi;\n      break;\n    case crab::domains::OP_SUBTRACTION:\n      xi = yi - zi;\n      break;\n    case crab::domains::OP_MULTIPLICATION:\n      xi = yi * zi;\n      break;\n    case crab::domains::OP_SDIV:\n      xi = yi / zi;\n      break;\n    case crab::domains::OP_UDIV:\n      xi = yi.UDiv(zi);\n      break;\n    case crab::domains::OP_SREM:\n      xi = yi.SRem(zi);\n      break;\n    case crab::domains::OP_UREM:\n      xi = yi.URem(zi);\n      break;\n    default:\n      CRAB_ERROR(\"Operation \", op, \" not supported\");\n    }\n    this->_env.set(x, xi);\n  }\n\n  void apply(crab::domains::arith_operation_t op, const variable_t &x,\n             const variable_t &y, number_t k) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    congruence_t yi = this->_env[y];\n    congruence_t zi(k);\n    congruence_t xi = congruence_t::bottom();\n\n    switch (op) {\n    case crab::domains::OP_ADDITION:\n      xi = yi + zi;\n      break;\n    case crab::domains::OP_SUBTRACTION:\n      xi = yi - zi;\n      break;\n    case crab::domains::OP_MULTIPLICATION:\n      xi = yi * zi;\n      break;\n    case crab::domains::OP_SDIV:\n      xi = yi / zi;\n      break;\n    case crab::domains::OP_UDIV:\n      xi = yi.UDiv(zi);\n      break;\n    case crab::domains::OP_SREM:\n      xi = yi.SRem(zi);\n      break;\n    case crab::domains::OP_UREM:\n      xi = yi.URem(zi);\n      break;\n    default:\n      CRAB_ERROR(\"Operation \", op, \" not supported\");\n    }\n    this->_env.set(x, xi);\n  }\n\n  // backward operations\n  void backward_assign(const variable_t &x, const linear_expression_t &e,\n                       const congruence_domain_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_assign\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_assign\");\n\n    crab::domains::BackwardAssignOps<congruence_domain_t>::assign(*this, x, e,\n                                                                  inv);\n  }\n\n  void backward_apply(crab::domains::arith_operation_t op, const variable_t &x,\n                      const variable_t &y, number_t z,\n                      const congruence_domain_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_apply\");\n\n    crab::domains::BackwardAssignOps<congruence_domain_t>::apply(*this, op, x,\n                                                                 y, z, inv);\n  }\n\n  void backward_apply(crab::domains::arith_operation_t op, const variable_t &x,\n                      const variable_t &y, const variable_t &z,\n                      const congruence_domain_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_apply\");\n\n    crab::domains::BackwardAssignOps<congruence_domain_t>::apply(*this, op, x,\n                                                                 y, z, inv);\n  }\n\n  // cast operations\n\n  void apply(crab::domains::int_conv_operation_t /*op*/, const variable_t &dst,\n             const variable_t &src) override {\n    // ignore widths\n    assign(dst, src);\n  }\n\n  // bitwise operations\n\n  void apply(crab::domains::bitwise_operation_t op, const variable_t &x,\n             const variable_t &y, const variable_t &z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    congruence_t yi = this->_env[y];\n    congruence_t zi = this->_env[z];\n    congruence_t xi = congruence_t::bottom();\n\n    switch (op) {\n    case crab::domains::OP_AND: {\n      xi = yi.And(zi);\n      break;\n    }\n    case crab::domains::OP_OR: {\n      xi = yi.Or(zi);\n      break;\n    }\n    case crab::domains::OP_XOR: {\n      xi = yi.Xor(zi);\n      break;\n    }\n    case crab::domains::OP_SHL: {\n      xi = yi.Shl(zi);\n      break;\n    }\n    case crab::domains::OP_LSHR: {\n      xi = yi.LShr(zi);\n      break;\n    }\n    case crab::domains::OP_ASHR: {\n      xi = yi.AShr(zi);\n      break;\n    }\n    default: { CRAB_ERROR(\"unreachable\"); }\n    }\n    this->_env.set(x, xi);\n  }\n\n  void apply(crab::domains::bitwise_operation_t op, const variable_t &x,\n             const variable_t &y, number_t k) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    congruence_t yi = this->_env[y];\n    congruence_t zi(k);\n    congruence_t xi = congruence_t::bottom();\n\n    switch (op) {\n    case crab::domains::OP_AND: {\n      xi = yi.And(zi);\n      break;\n    }\n    case crab::domains::OP_OR: {\n      xi = yi.Or(zi);\n      break;\n    }\n    case crab::domains::OP_XOR: {\n      xi = yi.Xor(zi);\n      break;\n    }\n    case crab::domains::OP_SHL: {\n      xi = yi.Shl(zi);\n      break;\n    }\n    case crab::domains::OP_LSHR: {\n      xi = yi.LShr(zi);\n      break;\n    }\n    case crab::domains::OP_ASHR: {\n      xi = yi.AShr(zi);\n      break;\n    }\n    default: { CRAB_ERROR(\"unreachable\"); }\n    }\n    this->_env.set(x, xi);\n  }\n\n  DEFAULT_SELECT(congruence_domain_t)\n  \n  /// congruence_domain implements only standard abstract operations\n  /// of a numerical domain so it is intended to be used as a leaf\n  /// domain in the hierarchy of domains.\n  BOOL_OPERATIONS_NOT_IMPLEMENTED(congruence_domain_t)\n  ARRAY_OPERATIONS_NOT_IMPLEMENTED(congruence_domain_t)\n  REGION_AND_REFERENCE_OPERATIONS_NOT_IMPLEMENTED(congruence_domain_t)\n    \n  void forget(const variable_vector_t &variables) override {\n    if (is_bottom() || is_top()) {\n      return;\n    }\n    for (variable_t var : variables) {\n      this->operator-=(var);\n    }\n  }\n\n  void project(const variable_vector_t &variables) override {\n    crab::CrabStats::count(domain_name() + \".count.project\");\n    crab::ScopedCrabStats __st__(domain_name() + \".project\");\n\n    _env.project(variables);\n  }\n\n  void expand(const variable_t &x, const variable_t &new_x) override {\n    crab::CrabStats::count(domain_name() + \".count.expand\");\n    crab::ScopedCrabStats __st__(domain_name() + \".expand\");\n\n    if (is_bottom() || is_top()) {\n      return;\n    }\n\n    set(new_x, this->_env[x]);\n  }\n\n  void normalize() override {}\n\n  void minimize() override {}\n\n  void rename(const variable_vector_t &from,\n              const variable_vector_t &to) override {\n    crab::CrabStats::count(domain_name() + \".count.rename\");\n    crab::ScopedCrabStats __st__(domain_name() + \".rename\");\n\n    _env.rename(from, to);\n  }\n\n  /* begin intrinsics operations */\n  void intrinsic(std::string name,\n\t\t const variable_or_constant_vector_t &inputs,\n                 const variable_vector_t &outputs) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", domain_name());\n  }\n\n  void backward_intrinsic(std::string name,\n\t\t\t  const variable_or_constant_vector_t &inputs,\n                          const variable_vector_t &outputs,\n                          const congruence_domain_t &invariant) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", domain_name());\n  }\n  /* end intrinsics operations */\n\n  void write(crab::crab_os &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.write\");\n    crab::ScopedCrabStats __st__(domain_name() + \".write\");\n\n    this->_env.write(o);\n  }\n\n  linear_constraint_system_t to_linear_constraint_system() const override {\n    crab::CrabStats::count(domain_name() +\n                           \".count.to_linear_constraint_system\");\n    crab::ScopedCrabStats __st__(domain_name() +\n                                 \".to_linear_constraint_system\");\n\n    linear_constraint_system_t csts;\n    if (is_bottom()) {\n      csts += linear_constraint_t::get_false();\n      return csts;\n    }\n\n    for (iterator it = this->_env.begin(); it != this->_env.end(); ++it) {\n      const variable_t &v = it->first;\n      congruence_t c = it->second;\n      boost::optional<number_t> n = c.singleton();\n      if (n) {\n        csts += (v == *n);\n      }\n    }\n    return csts;\n  }\n\n  disjunctive_linear_constraint_system_t\n  to_disjunctive_linear_constraint_system() const override {\n    auto lin_csts = to_linear_constraint_system();\n    if (lin_csts.is_false()) {\n      return disjunctive_linear_constraint_system_t(true /*is_false*/);\n    } else if (lin_csts.is_true()) {\n      return disjunctive_linear_constraint_system_t(false /*is_false*/);\n    } else {\n      return disjunctive_linear_constraint_system_t(lin_csts);\n    }\n  }\n\n  std::string domain_name() const override { return \"Congruences\"; }\n\n}; // class congruence_domain\n\n} // namespace ikos\n\nnamespace crab {\nnamespace domains {\n\ntemplate <typename Number, typename VariableName>\nstruct abstract_domain_traits<ikos::congruence_domain<Number, VariableName>> {\n  using number_t = Number;\n  using varname_t = VariableName;\n};\n\n} // namespace domains\n} // namespace crab\n", "meta": {"hexsha": "2fa97a3c72c7137fca0e717a16d984dc72727249", "size": 35730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/congruences.hpp", "max_stars_repo_name": "LinerSu/crab", "max_stars_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 152.0, "max_stars_repo_stars_event_min_datetime": "2016-02-28T06:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:44:56.000Z", "max_issues_repo_path": "include/crab/domains/congruences.hpp", "max_issues_repo_name": "LinerSu/crab", "max_issues_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2017-07-03T06:25:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T21:09:32.000Z", "max_forks_repo_path": "include/crab/domains/congruences.hpp", "max_forks_repo_name": "LinerSu/crab", "max_forks_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-11-22T15:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T00:46:57.000Z", "avg_line_length": 29.5289256198, "max_line_length": 80, "alphanum_fraction": 0.6056255248, "num_tokens": 10068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5399357755292202}}
{"text": "#include <stan/math/mix/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <math/rev/scal/util.hpp>\n#include <math/mix/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdBinomialCoefficientLog, FvarVar_Double_1stDeriv) {\n  using boost::math::digamma;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(2004.0, 1.0);\n  double z(1002);\n  fvar<var> a = binomial_coefficient_log(x, z);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.val_.grad(y, g);\n  EXPECT_FLOAT_EQ(0.69289774, g[0]);\n}\nTEST(AgradFwdBinomialCoefficientLog, Double_FvarVar_1stDeriv) {\n  using boost::math::digamma;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(2004.0);\n  fvar<var> z(1002.0, 2.0);\n  fvar<var> a = binomial_coefficient_log(x, z);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val());\n  EXPECT_NEAR(0, a.d_.val(), 1e-8);\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.val_.grad(y, g);\n  EXPECT_NEAR(0, g[0], 1e-8);\n}\nTEST(AgradFwdBinomialCoefficientLog, FvarVar_Double_2ndDeriv) {\n  using boost::math::digamma;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(2004.0, 1.0);\n  double z(1002);\n  fvar<var> a = binomial_coefficient_log(x, z);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.d_.grad(y, g);\n  EXPECT_FLOAT_EQ(-0.00049862865, g[0]);\n}\nTEST(AgradFwdBinomialCoefficientLog, Double_FvarVar_2ndDeriv) {\n  using boost::math::digamma;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(2004.0);\n  fvar<var> z(1002.0, 2.0);\n  fvar<var> a = binomial_coefficient_log(x, z);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val());\n  EXPECT_NEAR(0, a.d_.val(), 1e-8);\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.d_.grad(y, g);\n  EXPECT_FLOAT_EQ(-0.00399002460681026, g[0]);\n}\n\nTEST(AgradFwdBinomialCoefficientLog, FvarVar_FvarVar_1stDeriv) {\n  using boost::math::digamma;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(2004.0, 1.0);\n  fvar<var> z(1002.0, 2.0);\n  fvar<var> a = binomial_coefficient_log(x, z);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.d_.val());\n\n  AVEC y = createAVEC(x.val_, z.val_);\n  VEC g;\n  a.val_.grad(y, g);\n  EXPECT_FLOAT_EQ(0.69289774, g[0]);\n  EXPECT_NEAR(0, g[1], 1e-8);\n}\nTEST(AgradFwdBinomialCoefficientLog, FvarVar_FvarVar_2ndDeriv) {\n  using boost::math::digamma;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(2004.0, 1.0);\n  fvar<var> z(1002.0, 2.0);\n  fvar<var> a = binomial_coefficient_log(x, z);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.d_.val());\n\n  AVEC y = createAVEC(x.val_, z.val_);\n  VEC g;\n  a.d_.grad(y, g);\n  EXPECT_FLOAT_EQ(0.0014963837, g[0]);\n  EXPECT_FLOAT_EQ(-0.0029925184551076781, g[1]);\n}\n\nTEST(AgradFwdBinomialCoefficientLog, FvarFvarVar_FvarFvarVar_1stDeriv) {\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x, y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(), 1e-8);\n  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_, y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p, g);\n  EXPECT_FLOAT_EQ(0.69289774, g[0]);\n  EXPECT_NEAR(0, g[1], 1e-8);\n}\nTEST(AgradFwdBinomialCoefficientLog, FvarFvarVar_Double_1stDeriv) {\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  double y(1002.0);\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x, y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(), 1e-8);\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p, g);\n  EXPECT_FLOAT_EQ(0.69289774, g[0]);\n}\nTEST(AgradFwdBinomialCoefficientLog, Double_FvarFvarVar_1stDeriv) {\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(2004.0);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x, y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(), 1e-8);\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p, g);\n  EXPECT_NEAR(0, g[0], 1e-8);\n}\n\nTEST(AgradFwdBinomialCoefficientLog, FvarFvarVar_FvarFvarVar_2ndDeriv_x) {\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x, y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(), 1e-8);\n  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_, y.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p, g);\n  EXPECT_FLOAT_EQ(-0.00049862865, g[0]);\n  EXPECT_FLOAT_EQ(0.00099750615170258105, g[1]);\n}\nTEST(AgradFwdBinomialCoefficientLog, FvarFvarVar_FvarFvarVar_2ndDeriv_y) {\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x, y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(), 1e-8);\n  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_, y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p, g);\n  EXPECT_FLOAT_EQ(0.0009975062, g[0]);\n  EXPECT_FLOAT_EQ(-0.0019950123034051291, g[1]);\n}\nTEST(AgradFwdBinomialCoefficientLog, Double_FvarFvarVar_2ndDeriv) {\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(2004.0);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x, y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(), 1e-8);\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p, g);\n  EXPECT_NEAR(-0.00199501230340513, g[0], 1e-8);\n}\nTEST(AgradFwdBinomialCoefficientLog, FvarFvarVar_Double_2ndDeriv) {\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  double y(1002.0);\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x, y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(), 1e-8);\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p, g);\n  EXPECT_FLOAT_EQ(-0.00049862863648177515, g[0]);\n}\nTEST(AgradFwdBinomialCoefficientLog, FvarFvarVar_FvarFvarVar_3rdDeriv) {\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x, y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(), 1e-8);\n  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_, y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p, g);\n  EXPECT_FLOAT_EQ(-9.9501847e-07, g[0]);\n  EXPECT_FLOAT_EQ(9.9501847e-07, g[1]);\n}\nTEST(AgradFwdBinomialCoefficientLog, Double_FvarFvarVar_3rdDeriv) {\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(2004.0);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n  y.val_.d_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x, y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val_.val());\n  EXPECT_NEAR(0, a.val_.d_.val(), 1e-8);\n  EXPECT_NEAR(0, a.d_.val_.val(), 1e-8);\n  EXPECT_FLOAT_EQ(-0.0019950124, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p, g);\n  EXPECT_NEAR(0, g[0], 1e-8);\n}\nTEST(AgradFwdBinomialCoefficientLog, FvarFvarVar_Double_3rdDeriv) {\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n  x.d_.val_ = 1.0;\n\n  double y(1002.0);\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x, y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0.69289774181268948, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.00049862865, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p, g);\n  EXPECT_FLOAT_EQ(7.4613968e-07, g[0]);\n}\n\nstruct binomial_coefficient_log_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 binomial_coefficient_log(arg1, arg2);\n  }\n};\n\nTEST(AgradFwdBinomialCoefficientLog, nan_1) {\n  binomial_coefficient_log_fun binomial_coefficient_log_;\n  test_nan_mix(binomial_coefficient_log_, 3.0, 5.0, false);\n}\n", "meta": {"hexsha": "826b2570449e4deb277e1c44e293fd241ec61755", "size": 11004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/mix/scal/fun/binomial_coefficient_log_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/mix/scal/fun/binomial_coefficient_log_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/mix/scal/fun/binomial_coefficient_log_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": 28.4341085271, "max_line_length": 79, "alphanum_fraction": 0.6953834969, "num_tokens": 4177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.539935775433141}}
{"text": "// Copyright 2015 National ICT Australia Limited (NICTA)\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 <SgtCore/Random.h>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/discrete_distribution.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/weibull_distribution.hpp>\n\n#include <ctime>\n\nnamespace Sgt\n{\n    namespace\n    {\n        boost::random::mt19937 sRng; // Random number generator.\n    }\n    \n    void randSeedWithTime()\n    {\n        sRng.seed(static_cast<unsigned int>(std::time(nullptr)));\n    }\n\n    void randSeed(const unsigned int n)\n    {\n        sRng.seed(n);\n    }\n\n    double randDiscrete(const double probs[], int nProbs)\n    {\n        boost::random::discrete_distribution<> dist(&probs[0], &probs[nProbs]);\n        return dist(sRng);\n    }\n\n    double randNormal(double mu, double sig)\n    {\n        typedef boost::random::normal_distribution<> DistType;\n        static DistType dist(0.0, 1.0);\n        return dist(sRng, DistType::param_type(mu, sig));\n    }\n\n    double randUniform(double lower, double upper)\n    {\n        typedef boost::random::uniform_real_distribution<> DistType;\n        static DistType dist(0.0, 1.0);\n        return dist(sRng,  DistType::param_type(lower, upper));\n    }\n\n    int randUniformInt(int lower, int upper)\n    {\n        typedef boost::random::uniform_int_distribution<> DistType;\n        static DistType dist(0, 1);\n        return dist(sRng,  DistType::param_type(lower, upper));\n    }\n\n    double randWeibull(double a, double b)\n    {\n        typedef boost::random::weibull_distribution<> DistType;\n        static DistType dist(0.0, 1.0);\n        return dist(sRng,  DistType::param_type(a, b));\n    }\n}\n", "meta": {"hexsha": "9db26d33690009469d626fca8117e125b145a5a2", "size": 2334, "ext": "cc", "lang": "C++", "max_stars_repo_path": "SgtCore/Random.cc", "max_stars_repo_name": "dexterurbane/SmartGridToolbox", "max_stars_repo_head_hexsha": "ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7", "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": "SgtCore/Random.cc", "max_issues_repo_name": "dexterurbane/SmartGridToolbox", "max_issues_repo_head_hexsha": "ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7", "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": "SgtCore/Random.cc", "max_forks_repo_name": "dexterurbane/SmartGridToolbox", "max_forks_repo_head_hexsha": "ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7", "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.3116883117, "max_line_length": 79, "alphanum_fraction": 0.6812339332, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5399357644228078}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n\n#include <boost/python/class.hpp>\n#include <boost/python/return_by_value.hpp>\n#include <boost/python/return_value_policy.hpp>\n\n#include <scitbx/random.h>\n#include <scitbx/matrix/householder.h>\n\nnamespace scitbx { namespace matrix { namespace boost_python {\n\n  template <class TriangularDecompositionType>\n  struct householder_triangular_decomposition_wrapper\n  {\n    typedef TriangularDecompositionType wt;\n    typedef typename wt::scalar_t scalar_t;\n\n    static void wrap(char const *name) {\n      using namespace boost::python;\n      class_<wt>(name, no_init)\n      .def(init<af::ref<scalar_t, af::mat_grid> const &, optional<bool> >(\n           (arg(\"matrix\"), arg(\"may_accumulate_q\"))))\n      .def(\"q\", &wt::q, arg(\"thin\")=true)\n      .def(\"accumulate_q_in_place\", &wt::accumulate_q_in_place)\n      ;\n    }\n  };\n\n  template <typename FloatType>\n  struct householder_bidiagonalisation_wrapper\n  {\n    typedef householder::bidiagonalisation<FloatType> wt;\n    typedef typename wt::scalar_t scalar_t;\n\n    static void wrap(char const *name) {\n      using namespace boost::python;\n      class_<wt>(name, no_init)\n      .def(init<af::ref<scalar_t, af::mat_grid> const &>())\n      .def(\"u\", &wt::u, arg(\"thin\")=true)\n      .def(\"v\", &wt::v, arg(\"thin\")=true)\n      ;\n    }\n  };\n\n  template <typename FloatType, class UniformRandomNumberGenerator>\n  struct random_normal_matrix_generator_wrapper\n  {\n    typedef householder::random_normal_matrix_generator<\n      FloatType, UniformRandomNumberGenerator> wt;\n\n    static af::shared<std::size_t> get_state(wt const &self) {\n      return self.normal_gen.engine().getstate();\n    }\n\n    static void set_state(wt &self,\n                          af::const_ref<std::size_t> const &state)\n    {\n      self.normal_gen.engine().setstate(state);\n    }\n\n    static void wrap(char const *name) {\n      using namespace boost::python;\n      class_<wt>(name, no_init)\n      .def(init<int, int>(args(\"rows\", \"columns\")))\n      .def(\"normal_matrix\", &wt::normal_matrix)\n      .def(\"matrix_with_singular_values\", &wt::matrix_with_singular_values)\n      .def(\"symmetric_matrix_with_eigenvalues\",\n           &wt::symmetric_matrix_with_eigenvalues)\n      .add_property(\"state\", get_state, set_state)\n      ;\n    }\n  };\n\n  void wrap_householder() {\n    using namespace matrix::boost_python;\n    householder_triangular_decomposition_wrapper<\n    scitbx::matrix::householder::qr_decomposition<double> >::wrap(\n      \"householder_qr_decomposition\");\n    householder_triangular_decomposition_wrapper<\n    scitbx::matrix::householder::lq_decomposition<double> >::wrap(\n      \"householder_lq_decomposition\");\n    householder_bidiagonalisation_wrapper<double>::wrap(\n      \"householder_bidiagonalisation\");\n    random_normal_matrix_generator_wrapper<\n      double,\n      boost_random::mt19937\n    >::wrap(\"random_normal_matrix_generator\");\n  }\n\n}}}\n", "meta": {"hexsha": "e2554120a15847d736b6f71a629ee55cf27d99b9", "size": 2923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/linalg/boost_python/householder.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/linalg/boost_python/householder.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/linalg/boost_python/householder.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 32.1208791209, "max_line_length": 75, "alphanum_fraction": 0.692781389, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634456, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5399357615020857}}
{"text": "#define DEBUG 1\n/**\n * File    : E.cpp\n * Author  : Kazune Takahashi\n * Created : 6/2/2020, 12:34:10 PM\n * Powered by Visual Studio Code\n */\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n// ----- boost -----\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n// ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n// ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n// constexpr ll MOD{998244353LL}; // be careful\nconstexpr ll MAX_SIZE{3000010LL};\n// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n  }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n  }\n}\n// ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(const Mint &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(const Mint &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(const Mint &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator/=(const Mint &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }\n  bool operator<(const Mint &a) const { return x < a.x; }\n  bool operator<=(const Mint &a) const { return x <= a.x; }\n  bool operator>(const Mint &a) const { return x > a.x; }\n  bool operator>=(const Mint &a) const { return x >= a.x; }\n  bool operator==(const Mint &a) const { return x == a.x; }\n  bool operator!=(const Mint &a) const { return !(*this == a); }\n  const Mint power(ll N)\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N / 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n  return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)\n{\n  return Mint<MOD>{lhs} / rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n  return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n  return stream << a.x;\n}\n// ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i = 2LL; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i = 1LL; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x / gcd(x, y) * y; }\n// ----- for C++17 -----\ntemplate <typename T>\nint popcount(T x) // C++20\n{\n  int ans{0};\n  while (x != 0)\n  {\n    ans += x & 1;\n    x >>= 1;\n  }\n  return ans;\n}\n// ----- frequently used constexpr -----\n// constexpr double epsilon{1e-10};\nconstexpr ll infty{1000000000000000LL}; // or\n// constexpr int infty{1'000'000'010};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n// ----- main() -----\n\nstruct Edge\n{\n  bool valid;\n  int src, dst;\n  ll cost;\n\n  Edge() {}\n  Edge(int src, int dst, ll cost) : valid{true}, src{src}, dst{dst}, cost{cost} {}\n\n  void added_edge(vector<vector<int>> &V)\n  {\n    V[src].push_back(dst);\n  }\n\n  void added_rev(vector<vector<int>> &V)\n  {\n    V[dst].push_back(src);\n  }\n};\n\nclass Solve\n{\n  int N, M;\n  ll P;\n  vector<Edge> E;\n\npublic:\n  Solve(int N, int M) : N{N}, M{M}, E(M)\n  {\n    cin >> P;\n    for (auto i = 0; i < M; ++i)\n    {\n      int A, B;\n      ll C;\n      cin >> A >> B >> C;\n      --A;\n      --B;\n      E[i] = Edge(A, B, P - C);\n    }\n  }\n\n  void flush()\n  {\n    determine_validness();\n    cout << bf() << endl;\n  }\n\nprivate:\n  ll bf()\n  {\n    vector<ll> D(N, infty);\n    D[0] = 0;\n    bool updated{false};\n    for (auto t = 0; t < N + 2; ++t)\n    {\n      updated = false;\n      for (auto const &e : E)\n      {\n        if (!e.valid)\n        {\n          continue;\n        }\n        auto tmp{D[e.src] + e.cost};\n        if (D[e.dst] > tmp)\n        {\n          D[e.dst] = tmp;\n          updated = true;\n        }\n      }\n      if (!updated)\n      {\n        return max(0LL, -D[N - 1]);\n      }\n      if (t == N + 1)\n      {\n        return -1;\n      }\n    }\n    assert(false);\n    return -2;\n  }\n\n  void determine_validness()\n  {\n    auto table{valid_vertexes()};\n    for (auto &e : E)\n    {\n      if (!(table[e.src] && table[e.dst]))\n      {\n        e.valid = false;\n      }\n#if DEBUG == 1\n      else\n      {\n        cerr << \"src: \" << e.src << \", dst: \" << e.dst << \", cost: \" << e.cost << endl;\n      }\n#endif\n    }\n  }\n\n  vector<bool> valid_vertexes()\n  {\n    vector<vector<int>> V(N);\n    for (auto i = 0; i < M; ++i)\n    {\n      E[i].added_edge(V);\n    }\n    vector<bool> X(N, false);\n    dfs(V, X, 0);\n    vector<vector<int>> W(N);\n    for (auto i = 0; i < M; ++i)\n    {\n      E[i].added_rev(W);\n    }\n    vector<bool> Y(N, false);\n    dfs(W, Y, N - 1);\n    vector<bool> res(N, false);\n    for (auto i = 0; i < N; ++i)\n    {\n      res[i] = X[i] && Y[i];\n    }\n    return res;\n  }\n\n  void dfs(vector<vector<int>> const &V, vector<bool> &visited, int src, int parent = -1)\n  {\n    visited[src] = true;\n    for (auto dst : V[src])\n    {\n      if (dst != parent && !visited[dst])\n      {\n        dfs(V, visited, dst, src);\n      }\n    }\n  }\n};\n\nint main()\n{\n  int N, M;\n  cin >> N >> M;\n  Solve solve(N, M);\n  solve.flush();\n}\n", "meta": {"hexsha": "ff5ddc05815092e72eedc567caf8c27525a959e9", "size": 7585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/0810_ABC137/E.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2019/0810_ABC137/E.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "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/0810_ABC137/E.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 20.0131926121, "max_line_length": 89, "alphanum_fraction": 0.5278839815, "num_tokens": 2439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619134371954, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5399357614060061}}
{"text": "//\n// robust_pose_pnp.cpp\n//\n// Manolis Lourakis (lourakis **at** ics forth gr), February 2022\n\n#include <cmath>\n#include <cstdio>\n#include <iostream>\n#include <cstring>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <RansacLib/ransac.h>\n#include \"robust_pose_pnp.h\"\n\n#undef ROBUST_POSE_PNP_DEBUG  // enables some sample size checks\n\nnamespace robust_pose_pnp {\n\nPoseEstimator::PoseEstimator(const std::vector<sqpnp::_Point> *_3dpoints, const std::vector<sqpnp::_Projection> *_projections,\n                             int samplesz, int nm_samplesz) {\n  _3dpoints_ = _3dpoints;\n  _projections_ = _projections;\n\n  set_sample_sizes(samplesz, nm_samplesz);\n}\n\n// Robustly solves for camera pose lambda*x = R*X+t  with lambda > 0.\n// Inlier and outlier indices are optionally returned (in increasing order) in idxInliers & idxOutliers.\n// Returns 0 if successful, zero otherwise\nint PoseEstimator::ransacfit(int miniter, int maxiter, double inlPcent, double outlThresh, robust_pose_pnp::Matrix34d& best_pose, std::vector<int> *idxInliers, std::vector<int> *idxOutliers) const {\n  ransac_lib::LORansacOptions options;\n\n  options.min_num_iterations_ = (unsigned int)miniter;\n  options.max_num_iterations_ = (unsigned int)maxiter;\n  // make sure that min_num_iterations_ are at least as many as predicted for the given outlier ratio and sample size\n  options.min_num_iterations_ = ransac_lib::utils::NumRequiredIterations(inlPcent, 1.0-0.99, samplesz_, options.min_num_iterations_, options.max_num_iterations_);\n  options.squared_inlier_threshold_ = outlThresh * outlThresh;\n  options.final_least_squares_ = true;\n\n  // additional params with their defaults\n  //options.min_sample_multiplicator_ = 7;\n  //options.num_lsq_iterations_ = 4;\n  //options.num_lo_steps_ = 10;\n\n#if 0\n  std::random_device rand_dev;\n  options.random_seed_ = rand_dev();\n#endif\n\n  ransac_lib::LocallyOptimizedMSAC<robust_pose_pnp::Matrix34d,\n                                  std::vector<robust_pose_pnp::Matrix34d, Eigen::aligned_allocator<robust_pose_pnp::Matrix34d> >,\n                                  robust_pose_pnp::PoseEstimator>\n  lomsac;\n  ransac_lib::RansacStatistics ransac_stats;\n\n//std::cout << \"... running LOMSAC\" << std::endl;\n  int num_inliers = lomsac.EstimateModel(options, *this, &best_pose, &ransac_stats);\n\n  int npts = _3dpoints_->size();\n  int num_outliers = npts - num_inliers;\n\n  if (idxInliers != nullptr) {\n    idxInliers->clear();\n    idxInliers->resize(num_inliers);\n\n    for (int i=0; i<num_inliers; ++i)\n      (*idxInliers)[i] = ransac_stats.inlier_indices[i];\n  }\n\n  if (idxOutliers != nullptr) {\n    idxOutliers->clear();\n    idxOutliers->resize(num_outliers);\n\n    // num_inliers == ransac_stats.inlier_indices.size()\n    std::vector<int> isoutl(npts, 1);\n    for (int i=0; i<num_inliers; ++i)\n      isoutl[ransac_stats.inlier_indices[i]] = 0;\n    for (int i=0, j=0; i<npts; ++i)\n      if (isoutl[i]) (*idxOutliers)[j++] = i;\n  }\n\n/****/\n  std::cout << \"... LOMSAC found \" << num_inliers << \" inliers in \"\n            << ransac_stats.num_iterations << \" iterations with an inlier \"\n            << \"ratio of \" << ransac_stats.inlier_ratio << std::endl;\n/****/\n\n  return num_inliers == 0;\n}\n\n#if 1\n// this version creates local copies for the points corresponding to sample\nint PoseEstimator::sqpnp_solve(const std::vector<int>& sample,\n                                 std::vector<robust_pose_pnp::Matrix34d, Eigen::aligned_allocator<robust_pose_pnp::Matrix34d> > *poses) const {\n  const int nsample = sample.size();\n//std::cout<< \"in solve \"<<nsample<<\"\\n\"<<std::flush;\n\n  // pose from sample\n  std::vector<sqpnp::_Point> points(nsample);\n  std::vector<sqpnp::_Projection> projections(nsample);\n\n  for(int i=0; i<nsample; ++i){\n    int j = sample[i];\n\n    points[i] = (*_3dpoints_)[j];\n    projections[i] = (*_projections_)[j];\n  }\n\n  sqpnp::SolverParameters params;\n  // more relaxed convergence criteria below\n  //params.sqp_max_iteration = 10;\n  //params.rank_tolerance = 1E-06;\n  //params.sqp_squared_tolerance = 1E-09;\n\n  std::vector<double>wghts(nsample, 1.0);\n  sqpnp::PnPSolver solver(points, projections, wghts, params);\n\n  if(solver.IsValid()){\n    solver.Solve();\n\n    poses->resize(solver.NumberOfSolutions());\n    for (int i = 0; i < solver.NumberOfSolutions(); i++)\n    {\n      const sqpnp::SQPSolution *sol = solver.SolutionPtr(i);\n\n//      std::cout << \"\\nSolution \" << i << \":\\n\";\n//      std::cout << *sol << std::endl;\n//      std::cout << \" Average squared projection error : \" << solver.AverageSquaredProjectionErrors().at(i) << std::endl;\n\n      (*poses)[i].block<3,3>(0,0) = Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor> >( sol->r_hat.data() );\n      (*poses)[i].block<3,1>(0,3) = Eigen::Map<const Eigen::Matrix<double, 3, 1, Eigen::ColMajor> >( sol->t.data() );\n    }\n  }\n  else return 0;\n\n  return solver.NumberOfSolutions();\n}\n\n#else\n// this uses directly the correspondences using the weights: 1 for those in sample, 0 for the rest\nint PoseEstimator::sqpnp_solve(const std::vector<int>& sample,\n                                 std::vector<robust_pose_pnp::Matrix34d, Eigen::aligned_allocator<robust_pose_pnp::Matrix34d> > *poses) const {\n  const int npts = _3dpoints_->size();\n  const int nsample = sample.size();\n//std::cout<< \"in solve \"<<nsample<<\"\\n\"<<std::flush;\n\n  // pose from sample\n  std::vector<double>wghts(npts, 0.0);\n  for(int i=0; i<nsample; ++i){\n    wghts[sample[i]] = 1.0;\n  }\n\n  sqpnp::SolverParameters params;\n  // more relaxed convergence parameters next\n  //params.sqp_max_iteration = 10;\n  //params.rank_tolerance = 1E-06;\n  //params.sqp_squared_tolerance = 1E-09;\n  sqpnp::PnPSolver solver(*_3dpoints_, *_projections_, wghts, params);\n\n  if(solver.IsValid()){\n    solver.Solve();\n\n    poses->resize(solver.NumberOfSolutions());\n    for (int i = 0; i < solver.NumberOfSolutions(); i++)\n    {\n      const sqpnp::SQPSolution *sol = solver.SolutionPtr(i);\n\n//      std::cout << \"\\nSolution \" << i << \":\\n\";\n//      std::cout << *sol << std::endl;\n//      std::cout << \" Average squared projection error : \" << solver.AverageSquaredProjectionErrors().at(i) << std::endl;\n\n      (*poses)[i].block<3,3>(0,0) = Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor> >( sol->r_hat.data() );\n      (*poses)[i].block<3,1>(0,3) = Eigen::Map<const Eigen::Matrix<double, 3, 1, Eigen::ColMajor> >( sol->t.data() );\n    }\n  }\n  else return 0;\n\n  return solver.NumberOfSolutions();\n}\n#endif\n\n// minimal solver with SQPnP\nint PoseEstimator::MinimalSolver(const std::vector<int>& sample,\n                                 std::vector<robust_pose_pnp::Matrix34d, Eigen::aligned_allocator<robust_pose_pnp::Matrix34d> > *poses) const {\n\n  //const int npts = sample.size();\n  //std::cout<< \"in minimal solver (sqpnp) \"<<npts<<\"\\n\"<<std::flush;\n\n  poses->clear();\n\n#ifdef ROBUST_POSE_PNP_DEBUG\n  if (npts < samplesz_) return 0;\n#endif\n\n  return PoseEstimator::sqpnp_solve(sample, poses);\n}\n\n\n// non minimal solver with SQPnP\nint PoseEstimator::NonMinimalSolver(const std::vector<int>& sample,\n                                    robust_pose_pnp::Matrix34d *pose) const {\n  const int npts = sample.size();\n//std::cout<< \"in non minimal solver \"<<npts<<\"\\n\"<<std::flush;\n\n  // note that RansacLib might call the non minimal solver with fewer than nm_samplesz_ points, hence the following check\n  if (npts < nm_samplesz_) return 0;\n\n  std::vector<Matrix34d, Eigen::aligned_allocator<Matrix34d> > poses;\n\n  int n = PoseEstimator::sqpnp_solve(sample, &poses);\n\n  if (n > 1) std::cerr << \"More than one solution in PoseEstimator::NonMinimalSolver()!\\n\" << std::flush;\n\n  if (n > 0) *pose = poses[0];\n\n  return n > 0;\n}\n\n// Evaluates the pose on the i-th point pair.\ndouble PoseEstimator::EvaluateModelOnPoint(const robust_pose_pnp::Matrix34d& pose,\n                                           int i) const {\n  const sqpnp::_Point& xyz = (*_3dpoints_)[i];\n\n#if 0\n  double Xc     =       pose(0, 0)*xyz.vector[0] + pose(0, 1)*xyz.vector[1] + pose(0, 2)*xyz.vector[2] + pose(0, 3),\n         Yc     =       pose(1, 0)*xyz.vector[0] + pose(1, 1)*xyz.vector[1] + pose(1, 2)*xyz.vector[2] + pose(1, 3),\n         inv_Zc = 1./ ( pose(2, 0)*xyz.vector[0] + pose(2, 1)*xyz.vector[1] + pose(2, 2)*xyz.vector[2] + pose(2, 3) );\n\n#else\n  Eigen::Vector3d prod = pose.block<3,3>(0,0) * xyz.vector + pose.block<3,1>(0,3);\n  double Xc     =     prod(0),\n         Yc     =     prod(1),\n         inv_Zc = 1./ prod(2);\n\n\n  double dx = Xc*inv_Zc - (*_projections_)[i].vector[0];\n  double dy = Yc*inv_Zc - (*_projections_)[i].vector[1];\n#endif\n\n  return dx*dx + dy*dy;\n}\n\n}  // namespace robust_pose_pnp\n", "meta": {"hexsha": "c8f630f9418b3f7e6e84986d35c3e0a795b31a84", "size": 8653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/robust/robust_pose_pnp.cpp", "max_stars_repo_name": "oppenfuture/sqpnp", "max_stars_repo_head_hexsha": "e102e85d049b09fe9bfcced75016ddd7da8881c3", "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/robust/robust_pose_pnp.cpp", "max_issues_repo_name": "oppenfuture/sqpnp", "max_issues_repo_head_hexsha": "e102e85d049b09fe9bfcced75016ddd7da8881c3", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/robust/robust_pose_pnp.cpp", "max_forks_repo_name": "oppenfuture/sqpnp", "max_forks_repo_head_hexsha": "e102e85d049b09fe9bfcced75016ddd7da8881c3", "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.032388664, "max_line_length": 198, "alphanum_fraction": 0.6558419045, "num_tokens": 2615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5399333364259604}}
{"text": "\n/*\n * Mod_p.cpp\n *\n *  Created on: 15.09.2010\n *      Author: stephaniebayer\n */\n\n#include \"Mod_p.h\"\n\n\n#include \"G_q.h\"\nextern G_q G;\n\n#include <NTL/ZZ.h>\nNTL_CLIENT\n\n\nMod_p::Mod_p() {\n\t// TODO Auto-generated constructor stub\n\n}\n\n//Creates an instance which belongs to Z_p\nMod_p::Mod_p(long p){\n\n\tmod = to_ZZ(p);\n}\n\n\n//Creates an instance which belongs to Z_p\nMod_p::Mod_p(ZZ p){\n\n\tmod = p;\n}\n\n\n//Creates an instance which belongs to Z_p with value v\nMod_p::Mod_p(long v, long p){\n\n\tmod = to_ZZ(p);\n\tval = to_ZZ(v) % mod;\n}\n\n//Creates an instance which belongs to Z_p with value v\nMod_p::Mod_p(ZZ v, long p){\n\n\tmod = to_ZZ(p);\n\tval = v % mod;\n}\n\n\n//Creates an instance which belongs to Z_p with value v\nMod_p::Mod_p(long v, ZZ p){\n\n\tmod = p;\n\tval = to_ZZ(v) % mod;\n}\n\n\n//Creates an instance which belongs to Z_p with value v\nMod_p::Mod_p(ZZ v, ZZ p){\n\n\tmod = p;\n\tval = v % mod;\n}\n\n\nMod_p::~Mod_p() {\n\t// TODO Auto-generated destructor stub\n}\n\n\n//Changes the modular value p\nvoid Mod_p::set_mod(long p){\n\n\tmod = to_ZZ(p);\n}\n\n//Changes the modular value p\nvoid Mod_p::set_mod(ZZ p){\n\n\tmod = p;\n}\n\n//Sets or changes the value val\nvoid Mod_p::set_val(long v){\n\tif (mod ==0)\n\t\tcout << \"Please set a value for the modulus p\" << endl;\n\telse\n\t\tval = to_ZZ(v)% mod;\n}\n\n//Sets or changes the value val\nvoid Mod_p::set_val(ZZ p){\n\n\tif (mod ==0)\n\t\t\tcout << \"Please set a value for the modulus p\" << endl;\n\telse\n\t\tval = p % mod;\n}\n\n//Returns the modular value\nZZ Mod_p::get_mod() const{\n\n\treturn mod;\n}\n\n//returns the value of the instance\nZZ Mod_p::get_val() const{\n\n\treturn val;\n}\n\n\n//Assigment operator\nvoid Mod_p::operator =(const Mod_p& el){\n\n\tmod = el.get_mod();\n\tval = el.get_val();\n}\n\n//Addition\nMod_p Mod_p::operator +(const Mod_p& el) const{\n\tZZ temp;\n\tif (mod != el.get_mod())\n\t{\t\tcout <<\"It is not possible to add these elements\" << endl;\n\t\t\treturn Mod_p(0,1);}\n\telse\n\t{\n\t\ttemp = AddMod(val, el.get_val(),mod);\n\t\treturn Mod_p(temp, mod);}\n}\n\n//Subtraction\nMod_p Mod_p::operator -(const Mod_p& el) const{\n\tZZ temp;\n\tif (mod != el.get_mod())\n\t{\t\tcout <<\"It is not possible to subtract these elements\" << endl;\n\t\t\treturn Mod_p(0,1);}\n\telse\n\t{\n\t\ttemp = SubMod(val , el.get_val(),mod);\n\t\treturn Mod_p(temp, mod);}\n}\n\n//Unary plus\nMod_p Mod_p::operator +() const{\n\n\treturn Mod_p(val, mod);\n\n}\n\n//Unary Minus\nMod_p Mod_p::operator -() const{\n\n\tZZ temp;\n\ttemp = -val % mod;\n\treturn Mod_p(temp, mod);\n\n}\n\n//Multiplication\nMod_p Mod_p::operator *(const Mod_p& el) const{\n\n\tZZ temp;\n\tif (mod != el.get_mod())\n\t{\t\tcout <<\"It is not possible to multiply these elements\" << endl;\n\t\t\treturn Mod_p(0,1);}\n\telse\n\t{\n\t\ttemp = MulMod(val,el.get_val(),mod);\n\t\t\treturn Mod_p(temp, mod);}\n}\n\n//Division\nMod_p Mod_p::operator /(const Mod_p& el) const{\n\n\tZZ temp;\n\tif (mod != el.get_mod())\n\t{\t\tcout <<\"It is not possible to divide these elements\" << endl;\n\t\t\treturn Mod_p(0,1);}\n\telse\n\t{\n\t\ttemp = val*InvMod(el.get_val(), mod) ;\n\t\t\treturn Mod_p(temp, mod);}\n}\n\n//Increment prefix\nMod_p& Mod_p::operator ++(){\n\n\t++val;\n\treturn *this;\n}\n\n//Increment suffix\nMod_p Mod_p::operator ++(int){\n\n    Mod_p temp = *this;\n    ++val;\n    return temp;\n\n\n}\n\n//Decrement prefix\nMod_p& Mod_p::operator --(){\n\n\t--val;\n\treturn *this;\n}\n\n//Decrement suffix\nMod_p Mod_p::operator --(int){\n\n    Mod_p temp = *this;\n    --val;\n    return temp;\n\n\n}\n\n//Equal to\nbool Mod_p::operator ==(const Mod_p& el) const{\n\n\tif (mod == el.get_mod())\n\t{\n\t\tif (val == el.get_val())\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n}\n\n//Not equal to\nbool Mod_p::operator !=(const Mod_p& el) const{\n\n\tif (mod != el.get_mod())\n\t{\n\n\t\treturn true;\n\n\t}\n\telse\n\t{\n\t\tif (val != el.get_val())\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\n//Smaller\nbool Mod_p::operator <(const Mod_p& el) const{\n\n\tif (mod != el.get_mod())\n\t{\n\t\tcout << \"It is not possible to compare to elements with different modulus\" << endl;\n\t\treturn false;\n\n\t}\n\telse\n\t{\n\t\tif (val < el.get_val())\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\n//Bigger\nbool Mod_p::operator >(const Mod_p& el) const{\n\n\tif (mod != el.get_mod())\n\t{\n\t\tcout << \"It is not possible to compare to elements with different modulus\" << endl;\n\t\treturn false;\n\n\t}\n\telse\n\t{\n\t\tif (val > el.get_val())\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\n// Smaller equal\nbool Mod_p::operator <=(const Mod_p& el) const{\n\n\tif (mod != el.get_mod())\n\t{\n\t\tcout << \"It is not possible to compare to elements with different modulus\" << endl;\n\t\treturn false;\n\n\t}\n\telse\n\t{\n\t\tif (val <=el.get_val())\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\n//Bigger equal\nbool Mod_p::operator >=(const Mod_p& el) const{\n\n\tif (mod != el.get_mod())\n\t{\n\t\tcout << \"It is not possible to compare to elements with different modulus\" << endl;\n\t\treturn false;\n\n\t}\n\telse\n\t{\n\t\tif (val >=el.get_val())\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\n//Addition assignment\nMod_p& Mod_p::operator +=(const Mod_p& el){\n\n\tif (mod != el.get_mod())\n\t{\n\t\tcout << \"It is not possible to add these elements\" << endl;\n\t\treturn *this;\n\t}\n\telse\n\t{\n\t\tval = AddMod(val, el.get_val(), mod);\n\t\treturn *this;\n\t}\n}\n\n//Subtraction assignment\nMod_p& Mod_p::operator -=(const Mod_p& el){\n\n\tif (mod != el.get_mod())\n\t{\n\t\tcout << \"It is not possible to add these elements\" << endl;\n\t\treturn *this;\n\t}\n\telse\n\t{\n\t\tval = SubMod(val, el.get_val(), mod);\n\t\treturn *this;\n\t}\n}\n\n//Multiplication assignment\nMod_p& Mod_p::operator *=(const Mod_p& el){\n\n\tif (mod != el.get_mod())\n\t{\n\t\tcout << \"It is not possible to add these elements\" << endl;\n\t\treturn *this;\n\t}\n\telse\n\t{\n\t\tval = MulMod(val, el.get_val(),mod);\n\t\treturn *this;\n\t}\n}\n\n\n//Division assignment\nMod_p& Mod_p::operator /=(const Mod_p& el){\n\n\tif (mod != el.get_mod())\n\t{\n\t\tcout << \"It is not possible to add these elements\" << endl;\n\t\treturn *this;\n\t}\n\telse\n\t{\n\t\tval = MulMod(val,InvMod(el.get_val(),mod), mod);\n\t\treturn *this;\n\t}\n}\n\n//Output operator, output format is val (modular mod)\nostream& operator <<(ostream& os , const Mod_p &b){\n\n\treturn os << b.get_val();\n}\n\n//Input operator,\nistream& operator>>(istream& is, Mod_p &b){\n\tZZ val, mod;\n\n\tis>>val;\n\n\tmod = G.get_mod();\n\tb = Mod_p(val, mod);\n\treturn is;\n}\n\n\n//Returns the inverse modular p of the element\nMod_p Mod_p::inv(){\n\n\tZZ temp;\n\ttemp = InvMod(val,mod);\n\treturn Mod_p(temp,mod);\n}\n\n//Returns the inverse modular p of the element el\nMod_p Mod_p::inv(const Mod_p& el){\n\tZZ temp;\n\tZZ mod=el.get_mod();\n\ttemp = InvMod(el.get_val(),mod);\n\treturn Mod_p(temp, mod);\n\n}\n\nvoid Mod_p::inv(Mod_p&a, const Mod_p& el){\n\tZZ temp;\n\tZZ mod=el.get_mod();\n\tInvMod(temp, el.get_val(),mod);\n\ta= Mod_p(temp, mod);\n\n}\n\n//Multiplication functions\nvoid Mod_p::mult(Mod_p& a , const Mod_p& b, const Mod_p& c){\n\tZZ temp;\n\tZZ mod=b.get_mod();\n\tMulMod(temp,b.get_val(), c.get_val(),mod);\n\ta= Mod_p(temp,mod);\n}\n\n\n//exponentiation functions\nMod_p Mod_p::expo(const long e){\n\n\tZZ temp;\n\ttemp = PowerMod(val,e,mod);\n\treturn Mod_p(temp,mod);\n}\n\nMod_p Mod_p::expo(Mod_p& a, long e){\n\n\tZZ temp;\n\tZZ mod=a.get_mod();\n\ttemp = PowerMod(a.get_val(),e,mod);\n\treturn Mod_p(temp,mod);\n}\n\nvoid Mod_p::expo(Mod_p& a ,const Mod_p& b,const long e){\n\tZZ temp;\n\tZZ mod=b.get_mod();\n\tPowerMod(temp, b.get_val(),e,mod);\n\ta= Mod_p(temp,mod);\n}\n\nvoid Mod_p::expo(Mod_p& a , const Mod_p& b, const ZZ e){\n\tZZ temp;\n\tZZ mod=b.get_mod();\n\tPowerMod(temp, b.get_val(), e, mod);\n\ta= Mod_p(temp,mod);\n}\n\nMod_p Mod_p::expo(const ZZ e){\n\n\tZZ temp;\n\tPowerMod(temp, val,e, mod);\n\treturn Mod_p(temp,mod);\n}\n\nMod_p Mod_p::expo( Mod_p& a, ZZ e){\n\n\tZZ temp;\n\tZZ mod=a.get_mod();\n\ttemp = PowerMod(a.get_val(),e,mod);\n\treturn Mod_p(temp,a.mod);\n}\n\n", "meta": {"hexsha": "2896cbeef7c289f12ae887380d86805ca53d4683", "size": 7615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Mod_p.cpp", "max_stars_repo_name": "3for/verifiable-shuffle", "max_stars_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T14:06:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T08:28:26.000Z", "max_issues_repo_path": "src/Mod_p.cpp", "max_issues_repo_name": "3for/verifiable-shuffle", "max_issues_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "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/Mod_p.cpp", "max_forks_repo_name": "3for/verifiable-shuffle", "max_forks_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T06:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T15:21:49.000Z", "avg_line_length": 14.9021526419, "max_line_length": 85, "alphanum_fraction": 0.6231122784, "num_tokens": 2394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5399333251007166}}
{"text": "\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n\n#include <Eigen/Cholesky>\n\n#include \"convex_nmf.hpp\"\n#include \"progress_reporter.hpp\"\n#include \"projections.hpp\"\n\nnamespace convexnmf {\n\nvoid ConvexNMF::SetSparsifierType(const std::string &type_name, bool verbose) {\n\n    if (type_name == \"L2\") {\n        if (verbose)\n            std::cout << \"Set Sparsifier to L2.\" << std::endl;\n        sparsifier_type = SparsifierType::L2;\n    } else if (type_name == \"LInfty\") {\n        if (verbose)\n            std::cout << \"Set Sparsifier to LInfty.\" << std::endl;\n        sparsifier_type = SparsifierType::LInfty;\n    } else {\n        std::string current_setting = sparsifier_type == SparsifierType::L2 ? \"L2\" : \"LInfty\";\n        std::cout << \"Sparsifier type not recognized so not set, choose either 'L2' or 'LInfty'.\";\n        std::cout << \" Currently set to \" + current_setting + \" \\n\";\n    }\n}\n\nConvexNMFResults ConvexNMF::Fit(const MatrixRef &X, Scalar lambda) {\n    // TODO: Can move this to the Python front end.\n    int    N      = X.cols();\n    Matrix W_init = Matrix::Identity(N, N);\n    return Fit(X, lambda, W_init);\n}\n\nConvexNMFResults ConvexNMF::Fit(const MatrixRef &X, Scalar lambda, const MatrixRef &W_init) {\n\n    ConvexNMFProgressReporter reporter;\n    auto sparsifier = RowSparsifier::Create(sparsifier_type);\n    // W Update set up\n    int N = X.cols();\n    int T = X.rows();\n\n    Matrix XTXplusDeltaId = X.transpose() * X + rho * Matrix::Identity(N, N);\n    Matrix XTX            = X.transpose() * X;\n\n    std::cout << \"Factoring .... \";\n    Eigen::LLT<Matrix> cholesky_solver;\n    cholesky_solver.compute(XTXplusDeltaId);\n    std::cout << \"Done. \\n\";\n\n    // Set up W, Z, U\n    const Scalar sqrt_size = static_cast<Scalar>(std::sqrt(N * N));\n    Matrix       W         = W_init;\n    Matrix       Z_1 = W_init, Z_2 = W_init, Z_3 = W_init;\n    Matrix Y_1 = Matrix::Identity(N, N), Y_2 = Matrix::Identity(N, N), Y_3 = Matrix::Identity(N, N);\n\n    if (report_progress) {\n        reporter.PrintHeader();\n    }\n\n    for (int iteration = 1; iteration <= max_iterations; ++iteration) {\n        // Updates\n\n        Matrix previous_average = (Z_1 + Z_2 + Z_3) / 3.0; // Used in monitoring convergence.\n\n        Z_1 = cholesky_solver.solve(XTX + rho * W - Y_1);\n        Z_2 = sparsifier->Evaluate(W - Y_2 / rho, lambda, rho);\n        Z_3 = (W - Y_3 / rho).cwiseMax(0.0);\n\n        W = (Z_1 + Z_2 + Z_3 + (Y_1 + Y_2 + Y_3) / rho) / 3.0;\n\n        Y_1 = Y_1 + rho * (Z_1 - W);\n        Y_2 = Y_2 + rho * (Z_2 - W);\n        Y_3 = Y_3 + rho * (Z_3 - W);\n\n        // check primal and dual residual\n        Scalar primal_squared =\n            (W - Z_1).squaredNorm() + (W - Z_2).squaredNorm() + (W - Z_3).squaredNorm();\n        Scalar primal = std::sqrt(primal_squared);\n\n        Matrix current_average = (Z_1 + Z_2 + Z_3) / 3.0;\n        Scalar dual            = 3.0 * rho * (current_average - previous_average).norm();\n\n        Scalar z_norm     = std::sqrt(Z_1.squaredNorm() + Z_2.squaredNorm() + Z_3.squaredNorm());\n        Scalar primal_tol = std::sqrt(3.0) * abs_tolerance * sqrt_size +\n                            relative_tolerance * std::max(3 * W.norm(), z_norm);\n        Scalar dual_tol = abs_tolerance * sqrt_size + relative_tolerance * (Y_1 + Y_2 + Y_3).norm();\n\n        if (report_progress && (iteration % iteration_to_print == 0)) {\n            reporter.PrintStatistics(iteration, primal, primal_tol, dual, dual_tol);\n        }\n        if ((primal < primal_tol) && (dual < dual_tol)) {\n\n            ConvexNMFResults results{W, primal, dual, true};\n            if (report_progress) {\n                reporter.PrintConverged(iteration, primal, primal_tol, dual, dual_tol);\n            }\n            return results;\n        } else if (iteration == max_iterations) {\n            ConvexNMFResults results{W, primal, dual, false};\n            if (report_progress) {\n                reporter.PrintHitMaxIterations(iteration, primal, primal_tol, dual, dual_tol);\n            }\n            return results;\n        }\n    }\n}\n\n} // namespace convexnmf\n", "meta": {"hexsha": "23bfb806e11bbaf369d495f6ba36fedeaa27a41f", "size": 4058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/convex_nmf.cpp", "max_stars_repo_name": "miketoastmacneil/cvxnmf", "max_stars_repo_head_hexsha": "86011cf202406b7ee10ce618e433bcf82454ec73", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/convex_nmf.cpp", "max_issues_repo_name": "miketoastmacneil/cvxnmf", "max_issues_repo_head_hexsha": "86011cf202406b7ee10ce618e433bcf82454ec73", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/convex_nmf.cpp", "max_forks_repo_name": "miketoastmacneil/cvxnmf", "max_forks_repo_head_hexsha": "86011cf202406b7ee10ce618e433bcf82454ec73", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9115044248, "max_line_length": 100, "alphanum_fraction": 0.5889600789, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5399333143002703}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.\n// Copyright (c) 2008-2011 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, 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#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DISTANCE_PYTHAGORAS_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DISTANCE_PYTHAGORAS_HPP\n\n\n#include <boost/mpl/if.hpp>\n#include <boost/type_traits.hpp>\n\n#include <boost/geometry/core/access.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n\n#include <boost/geometry/util/select_calculation_type.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n\n\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <typename Point1, typename Point2, size_t I, typename T>\nstruct compute_pythagoras\n{\n    static inline T apply(Point1 const& p1, Point2 const& p2)\n    {\n        T const c1 = boost::numeric_cast<T>(get<I-1>(p2));\n        T const c2 = boost::numeric_cast<T>(get<I-1>(p1));\n        T const d = c1 - c2;\n        return d * d + compute_pythagoras<Point1, Point2, I-1, T>::apply(p1, p2);\n    }\n};\n\ntemplate <typename Point1, typename Point2, typename T>\nstruct compute_pythagoras<Point1, Point2, 0, T>\n{\n    static inline T apply(Point1 const&, Point2 const&)\n    {\n        return boost::numeric_cast<T>(0);\n    }\n};\n\n}\n#endif // DOXYGEN_NO_DETAIL\n\n\nnamespace comparable\n{\n\n/*!\n\\brief Strategy to calculate comparable distance between two points\n\\ingroup strategies\n\\tparam Point1 \\tparam_first_point\n\\tparam Point2 \\tparam_second_point\n\\tparam CalculationType \\tparam_calculation\n*/\ntemplate\n<\n    typename Point1,\n    typename Point2 = Point1,\n    typename CalculationType = void\n>\nclass pythagoras\n{\npublic :\n    typedef typename select_calculation_type\n            <\n                Point1,\n                Point2,\n                CalculationType\n            >::type calculation_type;\n\n    static inline calculation_type apply(Point1 const& p1, Point2 const& p2)\n    {\n        BOOST_CONCEPT_ASSERT( (concept::ConstPoint<Point1>) );\n        BOOST_CONCEPT_ASSERT( (concept::ConstPoint<Point2>) );\n\n        // Calculate distance using Pythagoras\n        // (Leave comment above for Doxygen)\n\n        assert_dimension_equal<Point1, Point2>();\n\n        return detail::compute_pythagoras\n            <\n                Point1, Point2,\n                dimension<Point1>::value,\n                calculation_type\n            >::apply(p1, p2);\n    }\n};\n\n} // namespace comparable\n\n\n/*!\n\\brief Strategy to calculate the distance between two points\n\\ingroup strategies\n\\tparam Point1 \\tparam_first_point\n\\tparam Point2 \\tparam_second_point\n\\tparam CalculationType \\tparam_calculation\n\n\\qbk{\n[heading Notes]\n[note Can be used for points with two\\, three or more dimensions]\n[heading See also]\n[link geometry.reference.algorithms.distance.distance_3_with_strategy distance (with strategy)]\n}\n\n*/\ntemplate\n<\n    typename Point1,\n    typename Point2 = Point1,\n    typename CalculationType = void\n>\nclass pythagoras\n{\n    typedef comparable::pythagoras<Point1, Point2, CalculationType> comparable_type;\npublic :\n    typedef typename promote_floating_point\n        <\n            typename services::return_type<comparable_type>::type\n        >::type calculation_type;\n\n    /*!\n    \\brief applies the distance calculation using pythagoras\n    \\return the calculated distance (including taking the square root)\n    \\param p1 first point\n    \\param p2 second point\n    */\n    static inline calculation_type apply(Point1 const& p1, Point2 const& p2)\n    {\n        calculation_type const t = comparable_type::apply(p1, p2);\n        return sqrt(t);\n    }\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename Point1, typename Point2, typename CalculationType>\nstruct tag<pythagoras<Point1, Point2, CalculationType> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename Point1, typename Point2, typename CalculationType>\nstruct return_type<pythagoras<Point1, Point2, CalculationType> >\n{\n    typedef typename pythagoras<Point1, Point2, CalculationType>::calculation_type type;\n};\n\n\ntemplate\n<\n    typename Point1,\n    typename Point2,\n    typename CalculationType,\n    typename P1,\n    typename P2\n>\nstruct similar_type<pythagoras<Point1, Point2, CalculationType>, P1, P2>\n{\n    typedef pythagoras<P1, P2, CalculationType> type;\n};\n\n\ntemplate\n<\n    typename Point1,\n    typename Point2,\n    typename CalculationType,\n    typename P1,\n    typename P2\n>\nstruct get_similar<pythagoras<Point1, Point2, CalculationType>, P1, P2>\n{\n    static inline typename similar_type\n        <\n            pythagoras<Point1, Point2, CalculationType>, P1, P2\n        >::type apply(pythagoras<Point1, Point2, CalculationType> const& )\n    {\n        return pythagoras<P1, P2, CalculationType>();\n    }\n};\n\n\ntemplate <typename Point1, typename Point2, typename CalculationType>\nstruct comparable_type<pythagoras<Point1, Point2, CalculationType> >\n{\n    typedef comparable::pythagoras<Point1, Point2, CalculationType> type;\n};\n\n\ntemplate <typename Point1, typename Point2, typename CalculationType>\nstruct get_comparable<pythagoras<Point1, Point2, CalculationType> >\n{\n    typedef comparable::pythagoras<Point1, Point2, CalculationType> comparable_type;\npublic :\n    static inline comparable_type apply(pythagoras<Point1, Point2, CalculationType> const& input)\n    {\n        return comparable_type();\n    }\n};\n\n\ntemplate <typename Point1, typename Point2, typename CalculationType>\nstruct result_from_distance<pythagoras<Point1, Point2, CalculationType> >\n{\nprivate :\n    typedef typename return_type<pythagoras<Point1, Point2, CalculationType> >::type return_type;\npublic :\n    template <typename T>\n    static inline return_type apply(pythagoras<Point1, Point2, CalculationType> const& , T const& value)\n    {\n        return return_type(value);\n    }\n};\n\n\n// Specializations for comparable::pythagoras\ntemplate <typename Point1, typename Point2, typename CalculationType>\nstruct tag<comparable::pythagoras<Point1, Point2, CalculationType> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename Point1, typename Point2, typename CalculationType>\nstruct return_type<comparable::pythagoras<Point1, Point2, CalculationType> >\n{\n    typedef typename comparable::pythagoras<Point1, Point2, CalculationType>::calculation_type type;\n};\n\n\n\n\ntemplate\n<\n    typename Point1,\n    typename Point2,\n    typename CalculationType,\n    typename P1,\n    typename P2\n>\nstruct similar_type<comparable::pythagoras<Point1, Point2, CalculationType>, P1, P2>\n{\n    typedef comparable::pythagoras<P1, P2, CalculationType> type;\n};\n\n\ntemplate\n<\n    typename Point1,\n    typename Point2,\n    typename CalculationType,\n    typename P1,\n    typename P2\n>\nstruct get_similar<comparable::pythagoras<Point1, Point2, CalculationType>, P1, P2>\n{\n    static inline typename similar_type\n        <\n            comparable::pythagoras<Point1, Point2, CalculationType>, P1, P2\n        >::type apply(comparable::pythagoras<Point1, Point2, CalculationType> const& )\n    {\n        return comparable::pythagoras<P1, P2, CalculationType>();\n    }\n};\n\n\ntemplate <typename Point1, typename Point2, typename CalculationType>\nstruct comparable_type<comparable::pythagoras<Point1, Point2, CalculationType> >\n{\n    typedef comparable::pythagoras<Point1, Point2, CalculationType> type;\n};\n\n\ntemplate <typename Point1, typename Point2, typename CalculationType>\nstruct get_comparable<comparable::pythagoras<Point1, Point2, CalculationType> >\n{\n    typedef comparable::pythagoras<Point1, Point2, CalculationType> comparable_type;\npublic :\n    static inline comparable_type apply(comparable::pythagoras<Point1, Point2, CalculationType> const& input)\n    {\n        return comparable_type();\n    }\n};\n\n\ntemplate <typename Point1, typename Point2, typename CalculationType>\nstruct result_from_distance<comparable::pythagoras<Point1, Point2, CalculationType> >\n{\nprivate :\n    typedef typename return_type<comparable::pythagoras<Point1, Point2, CalculationType> >::type return_type;\npublic :\n    template <typename T>\n    static inline return_type apply(comparable::pythagoras<Point1, Point2, CalculationType> const& , T const& value)\n    {\n        return_type const v = value;\n        return v * v;\n    }\n};\n\n\ntemplate <typename Point1, typename Point2>\nstruct default_strategy<point_tag, Point1, Point2, cartesian_tag, cartesian_tag, void>\n{\n    typedef pythagoras<Point1, Point2> type;\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::distance\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DISTANCE_PYTHAGORAS_HPP\n", "meta": {"hexsha": "2c8ee0f3609a8a933549a54831e3840f2a4851a5", "size": 9119, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/boost_1_47_0/boost/geometry/strategies/cartesian/distance_pythagoras.hpp", "max_stars_repo_name": "zigaosolin/Raytracer", "max_stars_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T14:37:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-25T07:38:07.000Z", "max_issues_repo_path": "external/boost_1_47_0/boost/geometry/strategies/cartesian/distance_pythagoras.hpp", "max_issues_repo_name": "zigaosolin/Raytracer", "max_issues_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2016-01-11T05:20:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T11:37:24.000Z", "max_forks_repo_path": "external/boost_1_47_0/boost/geometry/strategies/cartesian/distance_pythagoras.hpp", "max_forks_repo_name": "zigaosolin/Raytracer", "max_forks_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-01-05T15:10:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T04:59:16.000Z", "avg_line_length": 26.3554913295, "max_line_length": 116, "alphanum_fraction": 0.7283693387, "num_tokens": 2190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5399333143002703}}
{"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 <omp.h>\n\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/numeric/odeint/external/openmp/openmp.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\n    const double m_kap, m_lam;\n\n    osc_chain( const double kap , const double lam )\n        : m_kap( kap ) , m_lam( lam )\n    { }\n\n    // Simple case with openmp_range_algebra\n    void operator()( const std::vector<double> &q ,\n                           std::vector<double> &dpdt ) const\n    {\n        const size_t N = q.size();\n        double coupling_lr = 0;\n        size_t last_i = N;\n        #pragma omp parallel for firstprivate(coupling_lr, last_i) lastprivate(coupling_lr) schedule(runtime)\n        for(size_t i = 0 ; i < N - 1 ; ++i)\n        {\n            if(i > 0 && i != last_i + 1)\n                coupling_lr = signed_pow( q[i-1]-q[i] , m_lam-1 );\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            last_i = i;\n        }\n        dpdt[N-1] = -signed_pow( q[N-1] , m_kap-1 ) + coupling_lr;\n    }\n\n    // Split case with openmp_algebra\n    void operator()( const boost::numeric::odeint::openmp_state<double> &q ,\n                           boost::numeric::odeint::openmp_state<double> &dpdt ) const\n    {\n        const size_t M = q.size();\n        #pragma omp parallel for schedule(runtime)\n        for(size_t i = 0 ; i < M ; ++i)\n        {\n            const std::vector<double> &_q = q[i];\n            std::vector<double> &_dpdt = dpdt[i];\n            const size_t N = q[i].size();\n            double coupling_lr = 0;\n            if(i > 0) coupling_lr = signed_pow( q[i-1].back() - _q[0] , m_lam-1 );\n            for(size_t j = 0 ; j < N-1 ; ++j)\n            {\n                _dpdt[j] = -signed_pow( _q[j] , m_kap-1 ) + coupling_lr;\n                coupling_lr = signed_pow( _q[j] - _q[j+1] , m_lam-1 );\n                _dpdt[j] -= coupling_lr;\n            }\n            _dpdt[N-1] = -signed_pow( _q[N-1] , m_kap-1 ) + coupling_lr;\n            if(i + 1 < M) _dpdt[N-1] -= signed_pow( _q[N-1] - q[i+1].front() , m_lam-1 );\n        }\n    }\n\n};\n\n#endif\n", "meta": {"hexsha": "d9a6c222d64a8f126d9f86f297187ab93c435ada", "size": 2986, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/performance/openmp/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/openmp/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/openmp/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": 30.1616161616, "max_line_length": 109, "alphanum_fraction": 0.5562625586, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6513548578981939, "lm_q1q2_score": 0.5399333141953112}}
{"text": "#pragma once\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/numerics/data_out.h>\n\n#include <fstream>\n#include <iostream>\n\nusing namespace dealii;\n\nclass Fem\n{\npublic:\n  Fem();\n\n  void run();\n\nprivate:\n  void make_grid();\n  void setup_system();\n  void assemble_system();\n  void solve();\n  void output_results() const;\n\n  Triangulation<2> triangulation;\n  FE_Q<2>          fe;\n  DoFHandler<2>    dof_handler;\n\n  SparsityPattern      sparsity_pattern;\n  SparseMatrix<double> system_matrix;\n\n  Vector<double> solution;\n  Vector<double> system_rhs;\n};\n", "meta": {"hexsha": "fd4076af95681d3bf8b7595fcc30d2ca3f85bba8", "size": 669, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fem/fem.hpp", "max_stars_repo_name": "timotheehornek/cpack-exercise", "max_stars_repo_head_hexsha": "e570c99022d33ea0a6d95e6f59661156c6e771ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fem/fem.hpp", "max_issues_repo_name": "timotheehornek/cpack-exercise", "max_issues_repo_head_hexsha": "e570c99022d33ea0a6d95e6f59661156c6e771ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2021-12-08T10:38:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T16:34:14.000Z", "max_forks_repo_path": "fem/fem.hpp", "max_forks_repo_name": "timotheehornek/cpack-exercise", "max_forks_repo_head_hexsha": "e570c99022d33ea0a6d95e6f59661156c6e771ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2021-11-25T14:42:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T15:46:11.000Z", "avg_line_length": 17.6052631579, "max_line_length": 49, "alphanum_fraction": 0.7085201794, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5399333030799864}}
{"text": "#include \"multinomial.hpp\"\n\n#include \"utils.hpp\"\n\n#include <boost/log/trivial.hpp>\n#include <cmath>\n#include <numeric>\n\nnamespace FilterModel {\n\nMultinomial::Multinomial(int n, std::vector<double> p, double log_adjust)\n    : n(n), p(p), log_adjust(log_adjust) {\n    assert(n >= 0);\n    assert_probability(p);\n};\n\nMultinomial Multinomial::fix_dimensions(std::vector<bool> is_dimension_fixed,\n                                        std::vector<int> fixed_counts) const {\n    std::vector<double> new_p;\n    for (int dimension = 0; dimension < is_dimension_fixed.size(); ++dimension) {\n        if (!is_dimension_fixed.at(dimension)) {\n            new_p.push_back(p.at(dimension));\n            fixed_counts.insert(fixed_counts.begin() + dimension, 0);\n        }\n    }\n    double norm_p = std::accumulate(new_p.begin(), new_p.end(), 0.0);\n    std::transform(new_p.begin(), new_p.end(), new_p.begin(),\n                   [norm_p](double x) { return x / norm_p; });\n    assert_probability(new_p);\n\n    int new_n = n - std::accumulate(fixed_counts.begin(), fixed_counts.end(), 0);\n\n    double log_adjust = std::lgamma(n + 1) - std::lgamma(new_n + 1);\n\n    // Adjust fo the alpha=false terms.\n    for (int index : bool_to_index<int>(is_dimension_fixed)) {\n        log_adjust += fixed_counts.at(index) * std::log(p.at(index));\n        log_adjust -= std::lgamma(fixed_counts.at(index) + 1);\n    }\n    log_adjust += new_n * std::log(norm_p);\n\n    return Multinomial(new_n, new_p, log_adjust);\n}\n\ndouble Multinomial::log_pdf(const std::vector<int> &k) const {\n    assert_nonnegative(k);\n    int sum_k = std::accumulate(k.begin(), k.end(), 0);\n\n    assert(sum_k == n);\n    assert(k.size() == p.size());\n\n    if (n == 0) {\n        return std::log(1);\n    }\n\n    double log_n_choose_k = std::lgamma(n + 1);\n    double log_prod_p_k = 0.0;\n    for (int i = 0; i < k.size(); ++i) {\n        log_n_choose_k -= std::lgamma(k.at(i) + 1);\n        log_prod_p_k += k.at(i) * std::log(p.at(i));\n    }\n    return log_n_choose_k + log_prod_p_k + log_adjust;\n}\n\n}  // namespace FilterModel\n", "meta": {"hexsha": "b066d29dcc0448b8ff244321bb3ad5805b0fe962", "size": 2060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/multinomial.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++/multinomial.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++/multinomial.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": 31.2121212121, "max_line_length": 81, "alphanum_fraction": 0.6131067961, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5398321322500381}}
{"text": "#include <Eigen/Core>\n#include <fstream>\n#include <iostream>\n#include <string>\n\n#include <sophus/se3.h>\n#include <sophus/so3.h>\n\n#include <gtsam/nonlinear/GaussNewtonOptimizer.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/slam/dataset.h>\n\nusing namespace std;\nusing Sophus::SE3;\nusing Sophus::SO3;\n\n/************************************************\n * \u672c\u7a0b\u5e8f\u6f14\u793a\u5982\u4f55\u7528 gtsam \u8fdb\u884c\u4f4d\u59ff\u56fe\u4f18\u5316\n * sphere.g2o \u662f\u4eba\u5de5\u751f\u6210\u7684\u4e00\u4e2a Pose graph\uff0c\u6211\u4eec\u6765\u4f18\u5316\u5b83\u3002\n * \u4e0e g2o \u76f8\u4f3c\uff0c\u5728 gtsam \u4e2d\u6dfb\u52a0\u7684\u662f\u56e0\u5b50\uff0c\u76f8\u5f53\u4e8e\u8bef\u5dee\n * **********************************************/\n\nint main(int argc, char** argv) {\n  if (argc != 2) {\n    cout << \"Usage: pose_graph_gtsam 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  gtsam::NonlinearFactorGraph::shared_ptr graph(\n      new gtsam::NonlinearFactorGraph);                  // gtsam\u7684\u56e0\u5b50\u56fe\n  gtsam::Values::shared_ptr initial(new gtsam::Values);  // \u521d\u59cb\u503c\n  // \u4eceg2o\u6587\u4ef6\u4e2d\u8bfb\u53d6\u8282\u70b9\u548c\u8fb9\u7684\u4fe1\u606f\n  int cntVertex = 0, cntEdge = 0;\n  cout << \"reading from g2o file\" << endl;\n\n  while (!fin.eof()) {\n    string tag;\n    fin >> tag;\n    if (tag == \"VERTEX_SE3:QUAT\") {\n      // \u9876\u70b9\n      gtsam::Key id;\n      fin >> id;\n      double data[7];\n      for (int i = 0; i < 7; i++) fin >> data[i];\n      // \u8f6c\u6362\u81f3gtsam\u7684Pose3\n      gtsam::Rot3 R =\n          gtsam::Rot3::Quaternion(data[6], data[3], data[4], data[5]);\n      gtsam::Point3 t(data[0], data[1], data[2]);\n      initial->insert(id, gtsam::Pose3(R, t));  // \u6dfb\u52a0\u521d\u59cb\u503c\n      cntVertex++;\n    } else if (tag == \"EDGE_SE3:QUAT\") {\n      // \u8fb9\uff0c\u5bf9\u5e94\u5230\u56e0\u5b50\u56fe\u4e2d\u7684\u56e0\u5b50\n      gtsam::Matrix m = gtsam::I_6x6;  // \u4fe1\u606f\u77e9\u9635\n      gtsam::Key id1, id2;\n      fin >> id1 >> id2;\n      double data[7];\n      for (int i = 0; i < 7; i++) fin >> data[i];\n      gtsam::Rot3 R =\n          gtsam::Rot3::Quaternion(data[6], data[3], data[4], data[5]);\n      gtsam::Point3 t(data[0], data[1], data[2]);\n      for (int i = 0; i < 6; i++)\n        for (int j = i; j < 6; j++) {\n          double mij;\n          fin >> mij;\n          m(i, j) = mij;\n          m(j, i) = mij;\n        }\n\n      // g2o\u7684\u4fe1\u606f\u77e9\u9635\u5b9a\u4e49\u65b9\u5f0f\u4e0egtsam\u4e0d\u540c\uff0c\u8fd9\u91cc\u5bf9\u5b83\u8fdb\u884c\u4fee\u6539\n      gtsam::Matrix mgtsam = gtsam::I_6x6;\n      mgtsam.block<3, 3>(0, 0) = m.block<3, 3>(3, 3);  // cov rotation\n      mgtsam.block<3, 3>(3, 3) = m.block<3, 3>(0, 0);  // cov translation\n      mgtsam.block<3, 3>(0, 3) = m.block<3, 3>(0, 3);  // off diagonal\n      mgtsam.block<3, 3>(3, 0) = m.block<3, 3>(3, 0);  // off diagonal\n\n      gtsam::SharedNoiseModel model =\n          gtsam::noiseModel::Gaussian::Information(mgtsam);  // \u9ad8\u65af\u566a\u58f0\u6a21\u578b\n      gtsam::NonlinearFactor::shared_ptr factor(\n          new gtsam::BetweenFactor<gtsam::Pose3>(id1, id2, gtsam::Pose3(R, t),\n                                                 model)  // \u6dfb\u52a0\u4e00\u4e2a\u56e0\u5b50\n          );\n      graph->push_back(factor);\n      cntEdge++;\n    }\n    if (!fin.good()) break;\n  }\n\n  cout << \"read total \" << cntVertex << \" vertices, \" << cntEdge << \" edges.\"\n       << endl;\n  // \u56fa\u5b9a\u7b2c\u4e00\u4e2a\u9876\u70b9\uff0c\u5728gtsam\u4e2d\u76f8\u5f53\u4e8e\u6dfb\u52a0\u4e00\u4e2a\u5148\u9a8c\u56e0\u5b50\n  gtsam::NonlinearFactorGraph graphWithPrior = *graph;\n  gtsam::noiseModel::Diagonal::shared_ptr priorModel =\n      gtsam::noiseModel::Diagonal::Variances(\n          (gtsam::Vector(6) << 1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6).finished());\n  gtsam::Key firstKey = 0;\n  for (const gtsam::Values::ConstKeyValuePair& key_value : *initial) {\n    cout << \"Adding prior to g2o file \" << endl;\n    graphWithPrior.add(gtsam::PriorFactor<gtsam::Pose3>(\n        key_value.key, key_value.value.cast<gtsam::Pose3>(), priorModel));\n    break;\n  }\n\n  // \u5f00\u59cb\u56e0\u5b50\u56fe\u4f18\u5316\uff0c\u914d\u7f6e\u4f18\u5316\u9009\u9879\n  cout << \"optimizing the factor graph\" << endl;\n  // \u6211\u4eec\u4f7f\u7528 LM \u4f18\u5316\n  gtsam::LevenbergMarquardtParams params_lm;\n  params_lm.setVerbosity(\"ERROR\");\n  params_lm.setMaxIterations(20);\n  params_lm.setLinearSolverType(\"MULTIFRONTAL_QR\");\n  gtsam::LevenbergMarquardtOptimizer optimizer_LM(graphWithPrior, *initial,\n                                                  params_lm);\n\n  // \u4f60\u53ef\u4ee5\u5c1d\u8bd5\u4e0b GN\n  // gtsam::GaussNewtonParams params_gn;\n  // params_gn.setVerbosity(\"ERROR\");\n  // params_gn.setMaxIterations(20);\n  // params_gn.setLinearSolverType(\"MULTIFRONTAL_QR\");\n  // gtsam::GaussNewtonOptimizer optimizer ( graphWithPrior, *initial, params_gn\n  // );\n\n  gtsam::Values result = optimizer_LM.optimize();\n  cout << \"Optimization complete\" << endl;\n  cout << \"initial error: \" << graph->error(*initial) << endl;\n  cout << \"final error: \" << graph->error(result) << endl;\n\n  cout << \"done. write to g2o ... \" << endl;\n  // \u5199\u5165 g2o \u6587\u4ef6\uff0c\u540c\u6837\u4f2a\u88c5\u6210 g2o \u4e2d\u7684\u9876\u70b9\u548c\u8fb9\uff0c\u4ee5\u4fbf\u7528 g2o_viewer \u67e5\u770b\u3002\n  // \u9876\u70b9\u54af\n  ofstream fout(\"result_gtsam.g2o\");\n  for (const gtsam::Values::ConstKeyValuePair& key_value : result) {\n    gtsam::Pose3 pose = key_value.value.cast<gtsam::Pose3>();\n    gtsam::Point3 p = pose.translation();\n    gtsam::Quaternion q = pose.rotation().toQuaternion();\n    fout << \"VERTEX_SE3:QUAT \" << key_value.key << \" \" << p.x() << \" \" << p.y()\n         << \" \" << p.z() << \" \" << q.x() << \" \" << q.y() << \" \" << q.z() << \" \"\n         << q.w() << \" \" << endl;\n  }\n  // \u8fb9\u54af\n  for (gtsam::NonlinearFactor::shared_ptr factor : *graph) {\n    gtsam::BetweenFactor<gtsam::Pose3>::shared_ptr f =\n        dynamic_pointer_cast<gtsam::BetweenFactor<gtsam::Pose3>>(factor);\n    if (f) {\n      gtsam::SharedNoiseModel model = f->noiseModel();\n      gtsam::noiseModel::Gaussian::shared_ptr gaussianModel =\n          dynamic_pointer_cast<gtsam::noiseModel::Gaussian>(model);\n      if (gaussianModel) {\n        // write the edge information\n        gtsam::Matrix info =\n            gaussianModel->R().transpose() * gaussianModel->R();\n        gtsam::Pose3 pose = f->measured();\n        gtsam::Point3 p = pose.translation();\n        gtsam::Quaternion q = pose.rotation().toQuaternion();\n        fout << \"EDGE_SE3:QUAT \" << f->key1() << \" \" << f->key2() << \" \"\n             << p.x() << \" \" << p.y() << \" \" << p.z() << \" \" << q.x() << \" \"\n             << q.y() << \" \" << q.z() << \" \" << q.w() << \" \";\n        gtsam::Matrix infoG2o = gtsam::I_6x6;\n        infoG2o.block(0, 0, 3, 3) = info.block(3, 3, 3, 3);  // cov translation\n        infoG2o.block(3, 3, 3, 3) = info.block(0, 0, 3, 3);  // cov rotation\n        infoG2o.block(0, 3, 3, 3) = info.block(0, 3, 3, 3);  // off diagonal\n        infoG2o.block(3, 0, 3, 3) = info.block(3, 0, 3, 3);  // off diagonal\n        for (int i = 0; i < 6; i++)\n          for (int j = i; j < 6; j++) {\n            fout << infoG2o(i, j) << \" \";\n          }\n        fout << endl;\n      }\n    }\n  }\n  fout.close();\n  cout << \"done.\" << endl;\n}\n", "meta": {"hexsha": "4e1d3409666b61e65bd7d015eb372680a4bfa7bf", "size": 6524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch11/pose_graph_gtsam.cpp", "max_stars_repo_name": "duyanwei/slambook", "max_stars_repo_head_hexsha": "0e257f885d7b31ef6272311c49ce4654d690ef97", "max_stars_repo_licenses": ["MIT"], "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_gtsam.cpp", "max_issues_repo_name": "duyanwei/slambook", "max_issues_repo_head_hexsha": "0e257f885d7b31ef6272311c49ce4654d690ef97", "max_issues_repo_licenses": ["MIT"], "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_gtsam.cpp", "max_forks_repo_name": "duyanwei/slambook", "max_forks_repo_head_hexsha": "0e257f885d7b31ef6272311c49ce4654d690ef97", "max_forks_repo_licenses": ["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.4469273743, "max_line_length": 80, "alphanum_fraction": 0.5571735132, "num_tokens": 2323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5398321319503006}}
{"text": "// The MIT License (MIT)\n// \n// Copyright (c) 2015 Jonathan McCluskey and William Harding\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_DYN_LINK\n\n#include <boost/test/unit_test.hpp>\n#include <gmpxx.h>\n#include <memory>\n#include <sstream>\n\n#include \"BlindSignature.h\"\n#include \"Rsa.h\"\n#include \"Utilities.h\"\n\n#include <omp.h>\n\nBOOST_AUTO_TEST_CASE(blind_signature_test_1)\n{\n    Rsa::PrivateKey priv;\n    Rsa::PublicKey  pub;\n    std::tie(priv, pub) = Rsa::GenerateKeys(512);\n\n    std::stringstream message;\n    message << \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\" <<\n               \"this is a very secret message\";\n    mpz_class plain_text = Utilities::StringToNumber(message.str());\n\n    mpz_class blinding_factor;\n    mpz_class blinded_text;\n    double start = omp_get_wtime();\n    std::tie(blinded_text, blinding_factor) = BlindSignature::Blind(plain_text, pub, true);\n    double end = omp_get_wtime();\n    std::cout << \"Blind Signature Test 1 Timing \" << end - start << \"s\" << std::endl;\n\n    BOOST_CHECK(plain_text != blinded_text);\n\n    // blinded_text = m*(k^e) mod N\n    mpz_class signed_blinded_text = Rsa::Sign(blinded_text, priv, pub, false);\n\n    BOOST_CHECK(blinded_text != signed_blinded_text);\n\n    // signed_blinded_tex = (m^d)*k mod N\n    start = omp_get_wtime();\n    mpz_class unblinded_signed_text = BlindSignature::Unblind(signed_blinded_text, pub, blinding_factor, false);\n    end = omp_get_wtime();\n    std::cout << \"Unblind Signature Test 1 Timing \" << end - start << \"s\" << std::endl;\n\n    BOOST_CHECK(plain_text != unblinded_signed_text);\n    \n    // unblinded_signed_text = (m^d) mod N\n    mpz_class unsigned_plain_text = Rsa::Unsign(unblinded_signed_text, pub, true);\n    std::string unblinded_str = Utilities::NumberToString(unsigned_plain_text);\n\n    BOOST_CHECK_EQUAL(message.str(), unblinded_str);\n}\n\n", "meta": {"hexsha": "481c872b6c8a018bc247180d440060dfb611b4be", "size": 3577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libcrypto/test/check_BlindSignature.cpp", "max_stars_repo_name": "ToadRedCarp/koolkash-digital-cash-protocol", "max_stars_repo_head_hexsha": "ad8b1ed8fdb79658c7d74934db53463d02c5cb42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libcrypto/test/check_BlindSignature.cpp", "max_issues_repo_name": "ToadRedCarp/koolkash-digital-cash-protocol", "max_issues_repo_head_hexsha": "ad8b1ed8fdb79658c7d74934db53463d02c5cb42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libcrypto/test/check_BlindSignature.cpp", "max_forks_repo_name": "ToadRedCarp/koolkash-digital-cash-protocol", "max_forks_repo_head_hexsha": "ad8b1ed8fdb79658c7d74934db53463d02c5cb42", "max_forks_repo_licenses": ["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.3076923077, "max_line_length": 112, "alphanum_fraction": 0.675146771, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5398321203598951}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <boost/range/adaptors.hpp>\nnamespace ba = boost::adaptors;\n\n#include <dionysus/simplex.h>\n#include <dionysus/filtration.h>\n#include <dionysus/fields/zp.h>\n#include <dionysus/fields/z2.h>\n#include <dionysus/zigzag-persistence.h>\n\nnamespace d = dionysus;\n\n#include <format.h>\n\n//typedef     d::Z2Field                      K;\ntypedef     d::ZpField<>                    K;\ntypedef     d::Simplex<>                    Simplex;\ntypedef     d::Filtration<Simplex>          Filtration;\n//typedef     d::ZigzagFiltration<Simplex>    Filtration;\ntypedef     d::ZigzagPersistence<K>         Persistence;\n\ntypedef     typename Persistence::Index                     Index;\ntypedef     typename Filtration::Cell                       Cell;\ntypedef     d::ChainEntry<K, Cell>                          CellChainEntry;\ntypedef     d::ChainEntry<K, Index>                         ChainEntry;\n\n\nint main()\n{\n    K k(11);\n    Filtration      filtration { Simplex{0}, Simplex{1}, Simplex{2}, Simplex{0,1}, Simplex{0,2}, Simplex{1,2}, Simplex{0,1,2} };\n    Persistence     persistence(k);\n\n    unsigned op = 0;\n    for(auto& c : filtration)\n    {\n        fmt::print(\"[{}] Adding: {} : {}\\n\", op++, c, boost::distance(c.boundary(persistence.field())));\n        Index pair = persistence.add(c.boundary(persistence.field()) |\n                                                ba::transformed([&filtration](const CellChainEntry& e)\n                                                { return ChainEntry(e.element(), filtration.index(e.index())); }));\n        //if (pair != persistence.unpaired())\n        //    std::cout << \"[\" << pair << \" - \" << i << \"]\" << std::endl;\n        //++i;\n    }\n\n    for (int i = 6; i >= 0; --i)\n    {\n        fmt::print(\"[{}] Removing: {}\\n\", op++, i);\n        Index pair = persistence.remove(i);\n        if (pair == Persistence::unpaired())\n            fmt::print(\"Birth\\n\");\n        else\n            fmt::print(\"Death: {}\\n\", pair);\n    }\n}\n", "meta": {"hexsha": "c1de4eeea74c5a518852944fb99c5e0ebd5be106", "size": 1994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/filtration/zigzag-filtration-persistence.cpp", "max_stars_repo_name": "dlm/dionysus", "max_stars_repo_head_hexsha": "f7768668c6820adb1d49db291270ae3a99e14d18", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 114.0, "max_stars_repo_stars_event_min_datetime": "2017-07-19T21:43:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:54:11.000Z", "max_issues_repo_path": "examples/filtration/zigzag-filtration-persistence.cpp", "max_issues_repo_name": "dlm/dionysus", "max_issues_repo_head_hexsha": "f7768668c6820adb1d49db291270ae3a99e14d18", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 50.0, "max_issues_repo_issues_event_min_datetime": "2017-07-19T21:39:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T17:40:19.000Z", "max_forks_repo_path": "examples/filtration/zigzag-filtration-persistence.cpp", "max_forks_repo_name": "dlm/dionysus", "max_forks_repo_head_hexsha": "f7768668c6820adb1d49db291270ae3a99e14d18", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2017-08-17T17:11:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T09:59:57.000Z", "avg_line_length": 34.3793103448, "max_line_length": 128, "alphanum_fraction": 0.5260782347, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.539832115763643}}
{"text": "#include <iostream>\n// #include <boost/mpi.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\n\ntemplate< typename matrix_type, typename vector_type, typename left_precon_type, \n\t  typename right_precon_type, typename iter_type >\nvoid test_solver(const matrix_type& A, vector_type& x, const vector_type& b, \n\t   const left_precon_type& L, const right_precon_type& R, iter_type& iter)\n{\n    itl::bicg(A, x, b, L, iter); // GEHT NICHT!\n    itl::bicgstab(A, x, b, L, iter);\n    itl::bicgstab_2(A, x, b, L, iter);\n    itl::bicgstab_ell(A, x, b, L, R, iter, 3);\n    itl::cg(A, x, b, L, R, iter);\n    itl::cgs(A, x, b, L, iter);\n    itl::gmres(A, x, b, L, R, iter, 30);\n    itl::qmr(A, x, b, L, R, iter);\n    itl::idr_s(A, x, b, L, R, iter,3);\n    itl::tfqmr(A, x, b, L, R, iter);\n}\n\ntemplate< typename matrix_type, typename vector_type >\nint trans_test(const matrix_type& A, vector_type& x, const vector_type& b)\n{\n    using namespace mtl;\n    using namespace itl;\n    \n    typedef mat::transposed_view<const matrix_type> trans_matrix_type;\n    trans_matrix_type B(A);\n    \n    // Create an ILU(0) preconditioner\n    pc::ilu_0<matrix_type>        \tP0(A);\n    pc::ilu_0<trans_matrix_type>\tP1(B);\n    \n    pc::identity<matrix_type>\t\tId0(A);\n    pc::identity<trans_matrix_type> \tId1(B);\n  \n    // Termination criterion: r < 1e-6 * b or N iterations\n    noisy_iteration<double>       iter(b, 500, 1.e-6);\n    \n    test_solver(A, x, b, P0, Id0, iter);\n    test_solver(A, x, b, P1, Id1, iter); // GEHT NICHT!\n    test_solver(B, x, b, P0, Id0, iter);\n    test_solver(B, x, b, P1, Id1, iter); // GEHT NICHT!\n\n    return 0;\n}\n\nint main(// int argc, char* argv[]\n\t ) \n{\n    using namespace mtl;\n\n    // mtl::par::environment env(argc, argv);\n\n    const int size = 10, N = size * size;\n    // typedef mat::distributed<compressed2D<double> >  matrix_type;\n    typedef compressed2D<double>   matrix_type;\n    matrix_type                                         A;\n    laplacian_setup(A, size, size);\n    \n    mtl::dense_vector<double>                           x(N, 1.0), b;\n    \n    b= A * x;\n    x= 0;\n    \n    int error_code = trans_test(A, x, b);\n    \n    return error_code;\n}\n", "meta": {"hexsha": "94886206f28d3e0f303654a84260ad935f523fff", "size": 2191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/trans_trans_solver_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/itl/test/trans_trans_solver_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/itl/test/trans_trans_solver_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.0136986301, "max_line_length": 81, "alphanum_fraction": 0.6042902784, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5398321099684408}}
{"text": "#include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp>\n", "meta": {"hexsha": "fdd899a0d1ea367cad9a54cb2986144195c0b4c6", "size": 63, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta_dopri5.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta_dopri5.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta_dopri5.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 31.5, "max_line_length": 62, "alphanum_fraction": 0.8412698413, "num_tokens": 21, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5398321041732385}}
{"text": "////////////////////////////////////////////////////////////////////////////////////////////////////\n//                               This file is part of CosmoScout VR                               //\n//      and may be used under the terms of the MIT license. See the LICENSE file for details.     //\n//                        Copyright: (c) 2019 German Aerospace Center (DLR)                       //\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef CS_UTILS_CONVERSIONS_HPP\n#define CS_UTILS_CONVERSIONS_HPP\n\n#include \"cs_utils_export.hpp\"\n\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#include <glm/glm.hpp>\n#include <glm/gtc/quaternion.hpp>\n\n/// This namespace contains utility functions for converting numbers between different units of\n/// measuring.\nnamespace cs::utils::convert {\n\ntemplate <typename T>\nT lightyearsToMeters(T lightyears) {\n  return lightyears * 9460730472580800.0;\n}\n\ntemplate <typename T>\nT metersToLightyears(T meters) {\n  return meters / 9460730472580800.0;\n}\n\n/// Converts AU to meters. One AU is equivalent to the average distance between the Earth and the\n///// Sun.\ntemplate <typename T>\nT astronomicalUnitsToMeters(T astronomicalUnits) {\n  return astronomicalUnits * 149597870700.0;\n}\n\n/// Converts meters to AU. One AU is equivalent to the average distance between the Earth and the\n/// Sun.\ntemplate <typename T>\nT metersToAstronomicalUnits(T meters) {\n  return meters / 149597870700.0;\n}\n\ntemplate <typename T>\nT toRadians(T degrees) {\n  return degrees * glm::pi<double>() / 180.0;\n}\n\ntemplate <typename T>\nT toDegrees(T radians) {\n  return radians * 180.0 / glm::pi<double>();\n}\n\n/// Transform cartesian (x,y,z) coordinates to geodetic (lng, lat, height above surface)\n/// coordinates.\nCS_UTILS_EXPORT glm::dvec3 toLngLatHeight(\n    glm::dvec3 const& cartesian, double radiusE, double radiusP);\n\n/// Transform geodetic coordinates (lng, lat) LngLat and elevation height to cartesian (x,y,z)\n/// coordinates for an ellipsoid of equatorial radius radiusE and polar radius radiusP. Height is an\n/// offset along the normal of the ellipsoid at (lng, lat).\nCS_UTILS_EXPORT glm::dvec3 toCartesian(\n    glm::dvec2 const& lngLat, double radiusE, double radiusP, double height = 0.0);\n\n/// Convert latitudes.\nCS_UTILS_EXPORT double geocentricToGeodetic(double lat, double radiusE, double radiusP);\nCS_UTILS_EXPORT double geocentricToParametric(double lat, double radiusE, double radiusP);\nCS_UTILS_EXPORT double geodeticToGeocentric(double lat, double radiusE, double radiusP);\nCS_UTILS_EXPORT double geodeticToParametric(double lat, double radiusE, double radiusP);\nCS_UTILS_EXPORT double parametricToGeocentric(double lat, double radiusE, double radiusP);\nCS_UTILS_EXPORT double parametricToGeodetic(double lat, double radiusE, double radiusP);\n\n/// Returns the normal vector (unit length) to the ellipsoid with equatorial radius radiusE and\n/// polar radius radiusP at geodetic coordinates (lng, lat) LngLat.\nCS_UTILS_EXPORT glm::dvec3 lngLatToNormal(glm::dvec2 const& lngLat, double radiusE, double radiusP);\n\n/// Returns the geodetic coordinates (lng, lat) for a given normal vector.\nCS_UTILS_EXPORT glm::dvec2 normalToLngLat(glm::dvec3 const& normal, double radiusE, double radiusP);\n\n/// Convert boost::posix_time::ptime to spice time, which is defined by the\n/// Barycentric Dynamical Time.\nCS_UTILS_EXPORT double toSpiceTime(boost::posix_time::ptime const& tIn);\n\n/// Convert a time string to spice time, which is defined by the Barycentric Dynamical Time.\nCS_UTILS_EXPORT double toSpiceTime(std::string const& tIn);\n\n/// Convert time in seconds since 2000-01-01 12:00:00.000 to boost::posix_time::ptime. Be\n/// aware, that fractional seconds will be truncated. //DocTODO\nCS_UTILS_EXPORT boost::posix_time::ptime toBoostTime(double tIn);\n\n} // namespace cs::utils::convert\n\n#endif // CS_UTILS_CONVERSIONS_HPP\n", "meta": {"hexsha": "e5e597dd6e347fa3f1d7c3e54fff223aec3a3423", "size": 3968, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cs-utils/convert.hpp", "max_stars_repo_name": "bernstein/cosmoscout-vr", "max_stars_repo_head_hexsha": "4243384a0f96853dc12fc8e9d5862c9c37f7cadf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cs-utils/convert.hpp", "max_issues_repo_name": "bernstein/cosmoscout-vr", "max_issues_repo_head_hexsha": "4243384a0f96853dc12fc8e9d5862c9c37f7cadf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cs-utils/convert.hpp", "max_forks_repo_name": "bernstein/cosmoscout-vr", "max_forks_repo_head_hexsha": "4243384a0f96853dc12fc8e9d5862c9c37f7cadf", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 100, "alphanum_fraction": 0.7111895161, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5398261872122397}}
{"text": "// C++ code to wrap some Boost functions and be able to use them in C.\n\n#include <boost/integer/common_factor.hpp>\n#include \"common_factor.h\"\n\nint boost_gcd (int a, int b) {\n        return boost::integer::gcd(a, b);\n}\n\nint boost_lcm (int a, int b) {\n        return boost::integer::lcm(a, b);\n}\n", "meta": {"hexsha": "b6f76b878dec86d636da1bb6276db7ff30fe43b7", "size": 294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Boost-common-factor/C_wrapper/common_factor.cpp", "max_stars_repo_name": "spainisnotequal/cffi-play", "max_stars_repo_head_hexsha": "02407c428052cd1c135a5c7c14d4b71a7fa9d41e", "max_stars_repo_licenses": ["MIT"], "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-common-factor/C_wrapper/common_factor.cpp", "max_issues_repo_name": "spainisnotequal/cffi-play", "max_issues_repo_head_hexsha": "02407c428052cd1c135a5c7c14d4b71a7fa9d41e", "max_issues_repo_licenses": ["MIT"], "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-common-factor/C_wrapper/common_factor.cpp", "max_forks_repo_name": "spainisnotequal/cffi-play", "max_forks_repo_head_hexsha": "02407c428052cd1c135a5c7c14d4b71a7fa9d41e", "max_forks_repo_licenses": ["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.6153846154, "max_line_length": 70, "alphanum_fraction": 0.6530612245, "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5398261824558196}}
{"text": "/*\n * \n * Copyright (c) Toon Knapen, Karl Meerbergen & Kresimir Fresl 2003\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 * KF acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_GEES_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_GEES_HPP\n\n#include <boost/numeric/bindings/traits/type.hpp>\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/traits/type_traits.hpp>\n#include <boost/numeric/bindings/lapack/lapack.h>\n#include <boost/numeric/bindings/lapack/workspace.hpp>\n#include <boost/numeric/bindings/traits/detail/array.hpp>\n#include <boost/numeric/bindings/traits/detail/utils.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits.hpp>\n#endif \n\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace lapack {\n\n    ///////////////////////////////////////////////////////////////////\n    //\n    // Schur factorization of general matrix.\n    // \n    ///////////////////////////////////////////////////////////////////\n\n    /* \n     * gees() computes a Schur factorization of an N-by-N matrix A.\n     *\n     * The Schur decomposition is A = U S * herm(U)  where  U  is a\n     * unitary matrix and S is upper triangular. The eigenvalues of A\n     * are on the main diagonal of S. If A is real, S is in pseudo\n     * upper triangular form.\n     *\n     * Workspace is organized following the arguments in the calling sequence.\n     *  optimal_workspace() : for optimizing use of blas 3 kernels\n     *  minimal_workspace() : minimum size of workarrays, but does not allow for optimization\n     *                        of blas 3 kernels\n     *  workspace( work ) for real matrices where work is a real array with\n     *                    vector_size( work ) >= 3*matrix_size1( a )\n     *  workspace( work, rwork ) for complex matrices where work is a complex\n     *                           array with vector_size( work ) >= 2*matrix_size1( a )\n     *                           and rwork is a real array with\n     *                           vector_size( rwork ) >= matrix_size1( a ).\n     */ \n\n    namespace detail {\n      inline \n      void gees (char const jobvs, char const sort, logical_t* select, int const n,\n                 float* a, int const lda, int& sdim, traits::complex_f* w,\n                 float* vs, int const ldvs, float* work, int const lwork,\n                 bool* bwork, int& info) \n      {\n        traits::detail::array<float> wr(n);\n        traits::detail::array<float> wi(n);\n        LAPACK_SGEES (&jobvs, &sort, select, &n, a, &lda, &sdim,\n                      traits::vector_storage(wr), traits::vector_storage(wi),\n                      vs, &ldvs, work, &lwork, bwork, &info);\n        traits::detail::interlace(traits::vector_storage(wr),\n                                  traits::vector_storage(wr)+n,\n                                  traits::vector_storage(wi),\n                                  w);\n      }\n\n\n      inline \n      void gees (char const jobvs, char const sort, logical_t* select, int const n,\n                 double* a, int const lda, int& sdim, traits::complex_d* w,\n                 double* vs, int const ldvs, double* work, int const lwork,\n                 bool* bwork, int& info) \n      {\n        traits::detail::array<double> wr(n);\n        traits::detail::array<double> wi(n);\n        LAPACK_DGEES (&jobvs, &sort, select, &n, a, &lda, &sdim,\n                      traits::vector_storage(wr), traits::vector_storage(wi),\n                      vs, &ldvs, work, &lwork, bwork, &info);\n        traits::detail::interlace(traits::vector_storage(wr),\n                                  traits::vector_storage(wr)+n,\n                                  traits::vector_storage(wi),\n                                  w);\n      }\n\n\n      inline \n      void gees (char const jobvs, char const sort, logical_t* select, int const n,\n                 traits::complex_f* a, int const lda, int& sdim, traits::complex_f* w,\n                 traits::complex_f* vs, int const ldvs,\n                 traits::complex_f* work, int lwork, float* rwork, bool* bwork,\n                 int& info) \n      {\n        LAPACK_CGEES (&jobvs, &sort, select, &n, traits::complex_ptr(a), &lda, &sdim,\n                      traits::complex_ptr(w), traits::complex_ptr (vs), &ldvs,\n                      traits::complex_ptr(work), &lwork, rwork, bwork, &info);\n      }\n\n\n      inline \n      void gees (char const jobvs, char const sort, logical_t* select, int const n,\n                 traits::complex_d* a, int const lda, int& sdim, traits::complex_d* w,\n                 traits::complex_d* vs, int const ldvs,\n                 traits::complex_d* work, int lwork, double* rwork, bool* bwork,\n                 int& info) \n      {\n        LAPACK_ZGEES (&jobvs, &sort, select, &n, traits::complex_ptr(a), &lda, &sdim,\n                      traits::complex_ptr(w), traits::complex_ptr(vs), &ldvs,\n                      traits::complex_ptr(work), &lwork, rwork, bwork, &info);\n      }\n\n    } \n\n\n    namespace detail {\n       /// Compute Schur factorization, passing one work array.\n       template <typename MatrA, typename SchVec, typename EigVal, typename Work>\n       inline\n       int gees (char jobvs, MatrA& a, EigVal& w, SchVec& vs, Work& work) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n         BOOST_STATIC_ASSERT((boost::is_same<\n           typename traits::matrix_traits<MatrA>::matrix_structure, \n           traits::general_t\n         >::value)); \n         BOOST_STATIC_ASSERT((boost::is_same<\n           typename traits::matrix_traits<SchVec>::matrix_structure, \n           traits::general_t\n         >::value)); \n#endif \n\n         typedef typename MatrA::value_type                            value_type ;\n\n         int const n = traits::matrix_size1 (a);\n         assert (n == traits::matrix_size2 (a)); \n         assert (n == traits::matrix_size1 (vs)); \n         assert (n == traits::matrix_size2 (vs)); \n         assert (n == traits::vector_size (w)); \n         assert (3*n <= traits::vector_size (work)); \n\n         logical_t* select=0;\n         bool* bwork=0;\n\n         int info, sdim; \n         detail::gees (jobvs, 'N', select, n,\n                       traits::matrix_storage (a), \n                       traits::leading_dimension (a),\n                       sdim,\n                       traits::vector_storage (w),\n                       traits::matrix_storage (vs),\n                       traits::leading_dimension (vs),\n\t\t       traits::vector_storage( work ),\n\t\t       traits::vector_size( work ),\n                       bwork, info);\n\t return info ;\n       } // gees()\n\n\n       /// Compute Schur factorization, passing two work arrays.\n       template <typename MatrA, typename SchVec, typename EigVal,\n                 typename Work, typename RWork>\n       inline\n       int gees (char jobvs, MatrA& a, EigVal& w, SchVec& vs,\n\t\t Work& work, RWork& rwork) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n         BOOST_STATIC_ASSERT((boost::is_same<\n           typename traits::matrix_traits<MatrA>::matrix_structure, \n           traits::general_t\n         >::value)); \n         BOOST_STATIC_ASSERT((boost::is_same<\n           typename traits::matrix_traits<SchVec>::matrix_structure, \n           traits::general_t\n         >::value)); \n#endif \n\n         typedef typename MatrA::value_type                            value_type ;\n\n         int const n = traits::matrix_size1 (a);\n         assert (n == traits::matrix_size2 (a)); \n         assert (n == traits::matrix_size1 (vs)); \n         assert (n == traits::matrix_size2 (vs)); \n         assert (n == traits::vector_size (w)); \n         assert (2*n <= traits::vector_size (work)); \n         assert (n <= traits::vector_size (rwork)); \n\n         logical_t* select=0;\n         bool* bwork=0;\n\n         int info, sdim; \n         detail::gees (jobvs, 'N', select, n,\n                       traits::matrix_storage (a), \n                       traits::leading_dimension (a),\n                       sdim,\n                       traits::vector_storage (w),\n                       traits::matrix_storage (vs),\n                       traits::leading_dimension (vs),\n\t\t       traits::vector_storage( work ),\n\t\t       traits::vector_size( work ),\n\t\t       traits::vector_storage( rwork ),\n                       bwork, info);\n\t return info ;\n       } // gees()\n\n\n       /// Compute Schur factorization, depending on whether we have one or\n       /// two workspace arrays. N= the number of workspace arrays.\n       template <int N>\n       struct Gees {};\n\n\n       template <>\n       struct Gees< 2 > {\n          template <typename MatrA, typename SchVec, typename EigVal>\n          inline\n          int operator() (char jobvs, MatrA& a, EigVal& w, SchVec& vs, optimal_workspace ) const {\n             typedef typename MatrA::value_type                            value_type ;\n             typedef typename traits::type_traits< value_type >::real_type real_type ;\n\n             int n = traits::matrix_size1( a );\n\n             traits::detail::array<value_type> work( 2*n );\n             traits::detail::array<real_type>  rwork( n );\n\n             return gees( jobvs, a, w, vs, work, rwork );\n          } // gees()\n\n          template <typename MatrA, typename SchVec, typename EigVal>\n          inline\n          int operator() (char jobvs, MatrA& a, EigVal& w, SchVec& vs, minimal_workspace ) const {\n             typedef typename MatrA::value_type                            value_type ;\n             typedef typename traits::type_traits< value_type >::real_type real_type ;\n\n             int n = traits::matrix_size1( a );\n\n             traits::detail::array<value_type> work( 2*n );\n             traits::detail::array<real_type>  rwork( n );\n\n             return gees( jobvs, a, w, vs, work, rwork );\n          } // gees()\n\n          /// Compute Schur factorization, passing workspace2 as workspace\n          template <typename MatrA, typename SchVec, typename EigVal, typename RWork, typename Work>\n          inline\n          int operator() (char jobvs, MatrA& a, EigVal& w, SchVec& vs, workspace2<Work,RWork>& workspace ) const {\n             return gees( jobvs, a, w, vs, workspace.w_, workspace.wr_ );\n          } // gees()\n       }; // Gees<2>\n\n\n       template <>\n       struct Gees< 1 > {\n          template <typename MatrA, typename SchVec, typename EigVal>\n          inline\n          int operator() (char jobvs, MatrA& a, EigVal& w, SchVec& vs, optimal_workspace ) const {\n             typedef typename MatrA::value_type                            value_type ;\n             typedef typename traits::type_traits< value_type >::real_type real_type ;\n\n             int n = traits::matrix_size1( a );\n\n             traits::detail::array<value_type> work( 3*n );\n\n             return gees( jobvs, a, w, vs, work );\n          } // gees()\n\n          template <typename MatrA, typename SchVec, typename EigVal>\n          inline\n          int operator() (char jobvs, MatrA& a, EigVal& w, SchVec& vs, minimal_workspace ) const {\n             typedef typename MatrA::value_type                            value_type ;\n             typedef typename traits::type_traits< value_type >::real_type real_type ;\n\n             int n = traits::matrix_size1( a );\n\n             traits::detail::array<value_type> work( 3*n );\n\n             return gees( jobvs, a, w, vs, work );\n          } // gees()\n\n          /// Compute Schur factorization, passing workspace1 as workspace\n          template <typename MatrA, typename SchVec, typename EigVal, typename Work>\n          inline\n          int operator() (char jobvs, MatrA& a, EigVal& w, SchVec& vs, detail::workspace1<Work> workspace ) const {\n             return gees( jobvs, a, w, vs, workspace.w_ );\n          } // gees()\n       }; // Gees<1>\n\n    } // namespace detail\n\n\n    /// Compute Schur factorization with Schur vectors.\n    ///\n    /// Workspace can be the following :\n    /// optimal_workspace() : for optimizing use of blas 3 kernels\n    /// minimal_workspace() : minimum size of workarrays, but does not allow for optimization\n    ///                       of blas 3 kernels\n    /// workspace( real_work ) for real matrices where\n    ///                       vector_size( real_work ) >= 3*matrix_size1( a )\n    /// workspace( complex_work, real_work ) for complex matrices where\n    ///                       vector_size( complex_work ) >= 2*matrix_size1( a )\n    ///                       and vector_size( real_work ) >= matrix_size1( a ).\n    template <typename MatrA, typename SchVec, typename EigVal, typename Workspace>\n    inline\n    int gees (MatrA& a, EigVal& e, SchVec& vs, Workspace workspace ) {\n       return detail::Gees< n_workspace_args<typename MatrA::value_type>::value>()\n               ( 'V', a, e, vs, workspace );\n    } // gees()\n\n\n    // Compute Schur factorization without Schur vectors.\n    ///\n    /// Workspace can be the following :\n    /// optimal_workspace() : for optimizing use of blas 3 kernels\n    /// minimal_workspace() : minimum size of workarrays, but does not allow for optimization\n    ///                       of blas 3 kernels\n    /// workspace( real_work ) for real matrices where\n    ///                       vector_size( real_work ) >= 3*matrix_size1( a )\n    /// workspace( complex_work, real_work ) for complex matrices where\n    ///                       vector_size( complex_work ) >= 2*matrix_size1( a )\n    ///                       and vector_size( real_work ) >= matrix_size1( a ).\n    template <typename MatrA, typename EigVal, typename Workspace>\n    inline\n    int gees (MatrA& a, EigVal& e, Workspace workspace) {\n      return detail::Gees< n_workspace_args<typename MatrA::value_type>::value>()\n              ('N', a, e, a, workspace );\n    }\n\n  }\n\n}}}\n\n#endif \n", "meta": {"hexsha": "b772e30d05c646320359e7baa3fa0d413ffa5bfe", "size": 13997, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/lapack/gees.hpp", "max_stars_repo_name": "inducer/boost-numeric-bindings", "max_stars_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-11-13T16:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T15:37:19.000Z", "max_issues_repo_path": "openrave/plugins/include/boost/numeric/bindings/lapack/gees.hpp", "max_issues_repo_name": "jdsika/holy", "max_issues_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-06-13T01:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-14T00:38:27.000Z", "max_forks_repo_path": "openrave/plugins/include/boost/numeric/bindings/lapack/gees.hpp", "max_forks_repo_name": "jdsika/holy", "max_forks_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-05T20:18:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T20:18:25.000Z", "avg_line_length": 40.8075801749, "max_line_length": 115, "alphanum_fraction": 0.5620490105, "num_tokens": 3322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5398261824558196}}
{"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_ASEC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASEC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing asec capabilities\n\n    inverse secant in radian: \\f$\\arccos(1/x)\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    auto r = asec(x);\n    @endcode\n\n    @see asecd, asecpi, sec, cos\n\n  **/\n  Value asec(Value const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/asec.hpp>\n#include <boost/simd/function/simd/asec.hpp>\n\n#endif\n", "meta": {"hexsha": "3edaa08332bcff74b83d2b28bed689d16cd0095d", "size": 982, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/asec.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/asec.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/asec.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": 22.3181818182, "max_line_length": 100, "alphanum_fraction": 0.566191446, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5398261764862954}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <scitbx/array_family/flex_types.h>\n#include <scitbx/array_family/shared.h>\n#include <scitbx/array_family/boost_python/shared_wrapper.h>\n\n#include <vector>\n#include <cmath>\n#include <stdexcept>\n#include <scitbx/lstbx/normal_equations.h>\n\nusing namespace boost::python;\nnamespace xfel{\n\nnamespace xes { namespace example {\n  class gaussian_fit_inheriting_from_non_linear_ls: public scitbx::lstbx::normal_equations::non_linear_ls<double> {\n\n    public:\n      gaussian_fit_inheriting_from_non_linear_ls(int n_parameters):\n        scitbx::lstbx::normal_equations::non_linear_ls<double>(n_parameters),\n        jacobian_one_row(n_parameters)\n        {}\n\n      void set_cpp_data(scitbx::af::shared<double> x,\n                        scitbx::af::shared<double> y,\n                        double const& g,\n                        double const& s) {\n                        free_x=x, free_y=y, gain_to_sigma=g, sigmafac=s; sigmafac_sq=s*s;\n                        residual_terms_0 = std::vector<double>(x.size());\n                        residual_terms_1 = std::vector<double>(x.size());\n                        residuals = scitbx::af::shared<double>(x.size());\n      }\n\n      void access_cpp_build_up_directly(bool objective_only, scitbx::af::shared<double> current_values) {\n        fvec_callable(current_values);\n        if (objective_only) {\n          add_residuals(residuals.const_ref(), scitbx::af::shared<double>().const_ref());\n        }else{\n          // add one of the normal equations for each observation\n          for (int ix = 0; ix < free_x.size(); ++ix) {\n            /*\n              z_mean = current_values[0]\n              z_ampl = current_values[1]\n              z_sigm = current_values[2]\n              o_ampl = current_values[3]\n              o_mean = z_mean + z_sigm * GAIN_TO_SIGMA\n              o_sigm = z_sigm * SIGMAFAC\n              # leaving out small cross terms where one-photon peak influences\n              # derivatives with respect to z_mean and z_sigm.\n              # XXX not accounting for charge sharing at all\n             */\n            double udiff = free_x[ix] - current_values[0];\n            double Afactor = udiff/(current_values[2] * current_values[2]);\n            double Sfactor = Afactor * udiff/current_values[2];\n            jacobian_one_row[0] = ( residual_terms_0[ix] * Afactor );\n            jacobian_one_row[1] = ( residual_terms_0[ix] / current_values[1] );\n            jacobian_one_row[2] = ( residual_terms_0[ix] * Sfactor );\n            jacobian_one_row[3] = ( residual_terms_1[ix] / current_values[3] );\n\n            add_equation(residuals[ix], jacobian_one_row.const_ref(), 1.);\n          }\n        }\n      }\n\n      void\n      fvec_callable(scitbx::af::shared<double> &current_values) {\n        /*\n          z_mean = current_values[0]\n          z_ampl = current_values[1]\n          z_sigm = current_values[2]\n          o_ampl = current_values[3]\n          o_mean = z_mean + z_sigm * GAIN_TO_SIGMA\n          o_sigm = z_sigm * SIGMAFAC\n\n          # model minus obs\n          # sqrt2pi_inv = 1./math.sqrt(2.*math.pi)\n          # the gaussian function is sqrt2pi_inv * exp( - (x-mean)**2 / (2.*(sigma**2)))/sigma\n          # take off the coefficient sqrt2pi_inv / sigma, use ampl\n        */\n\n        for (int ix = 0; ix < free_x.size(); ++ix) {\n          double model=0;\n          //zero-photon Gaussian\n          double diff = free_x[ix] - current_values[0];\n          residual_terms_0[ix] = (\n            current_values[1] * std::exp( - (diff*diff) / (2. * current_values[2] * current_values[2])));\n          model += residual_terms_0[ix];\n\n          //one-photon Gaussian\n          diff = free_x[ix] - ( current_values[0] + current_values[2] * gain_to_sigma );\n          residual_terms_1[ix] = (\n            current_values[3] * std::exp( - (diff*diff) / (2. * current_values[2] * current_values[2] * sigmafac_sq)));\n          model += residual_terms_1[ix];\n\n          //terms = [\n          //ampl * flex.exp(-flex.pow2(free_x - mean) / (2.*sigm*sigm))\n          //for mean,ampl,sigm in [(z_mean,z_ampl,z_sigm),(o_mean,o_ampl,o_sigm)]]\n          //#print \"residual\", math.sqrt(flex.sum((model-free_y)*(model-free_y)))\n          residuals[ix] = ( model - free_y[ix] );\n        }\n      }\n\n    private:\n      scitbx::af::shared<double> free_x, free_y, jacobian_one_row, residuals;\n      double gain_to_sigma, sigmafac, sigmafac_sq;\n      std::vector<double> residual_terms_0, residual_terms_1;\n\n  };\n\n  class gaussian_3fit_inheriting_from_non_linear_ls: public scitbx::lstbx::normal_equations::non_linear_ls<double> {\n\n    public:\n      gaussian_3fit_inheriting_from_non_linear_ls(int n_parameters):\n        scitbx::lstbx::normal_equations::non_linear_ls<double>(n_parameters),\n        jacobian_one_row(n_parameters)\n        {}\n\n      void set_cpp_data(scitbx::af::shared<double> const& val,\n                        scitbx::af::shared<double> const& x,\n                        scitbx::af::shared<double> const& y) {\n                        free_x=x, free_y=y;\n                        residual_terms_0 = std::vector<double>(x.size());\n                        residual_terms_1 = std::vector<double>(x.size());\n                        residual_terms_2 = std::vector<double>(x.size());\n                        residuals = scitbx::af::shared<double>(x.size());\n                        constants = val;\n      }\n\n      void access_cpp_build_up_directly(bool objective_only, scitbx::af::shared<double> current_values) {\n\n        fvec_callable(current_values);\n\n        if (objective_only) {\n\n          add_residuals(residuals.const_ref(), scitbx::af::shared<double>().const_ref());\n        }else{\n          // add one of the normal equations for each observation\n          for (int ix = 0; ix < free_x.size(); ++ix) {\n            /*\n              z_mean = current_values[0]\n              z_ampl = current_values[1]\n              z_sigm = current_values[2]\n              inelast_mean = zmean + zsigm * constants[0]\n              inelast_ampl = current_values[3]\n              inelast_sigm = (constants[0]/constants[1])*(elast_sigm[5] - zsigm[2])+zsigm[2]\n              elast_mean = z_mean + z_sigm * constants[1]\n              elast_ampl = current_values[4]\n              elast_sigm = current_values[5]\n              # leaving out small cross terms where one-photon peak influences\n              # derivatives with respect to z_mean and z_sigm.\n              # XXX not accounting for charge sharing or 2-photon peak\n             */\n            double udiff = free_x[ix] - current_values[0];\n            double Afactor = udiff/(current_values[2] * current_values[2]);\n            double Sfactor = Afactor * udiff/current_values[2];\n            jacobian_one_row[0] = ( residual_terms_0[ix] * Afactor );\n            jacobian_one_row[1] = ( residual_terms_0[ix] / current_values[1] );\n            jacobian_one_row[2] = ( residual_terms_0[ix] * Sfactor );\n            jacobian_one_row[3] = ( residual_terms_1[ix] / current_values[3] );\n            jacobian_one_row[4] = ( residual_terms_2[ix] / current_values[4] );\n            double udiff3 = free_x[ix] - (current_values[0] + current_values[2] * constants[1]);\n            double Afactor3 = udiff3/(current_values[5] * current_values[5]);\n            double Sfactor3 = Afactor3 * udiff3/current_values[5];\n            jacobian_one_row[5] = ( residual_terms_2[ix] * Sfactor3 );\n\n            add_equation(residuals[ix], jacobian_one_row.const_ref(), 1.);\n          }\n        }\n\n      }\n\n      void\n      fvec_callable(scitbx::af::shared<double> &current_values) {\n        /*\n          # model minus obs\n          # sqrt2pi_inv = 1./math.sqrt(2.*math.pi)\n          # the gaussian function is sqrt2pi_inv * exp( - (x-mean)**2 / (2.*(sigma**2)))/sigma\n          # take off the coefficient sqrt2pi_inv / sigma, use ampl\n        */\n\n\n        for (int ix = 0; ix < free_x.size(); ++ix) {\n          double model=0;\n\n\n          //zero-photon Gaussian\n          double diff = free_x[ix] - current_values[0];\n          residual_terms_0[ix] = (\n            current_values[1] * std::exp( - (diff*diff) / (2. * current_values[2] * current_values[2])));\n          model += residual_terms_0[ix];\n\n          //inelastic-photon Gaussian\n          {\n          double pmean = current_values[0] + current_values[2] * constants[0];\n          diff = free_x[ix] - pmean;\n          double psigma = (constants[0]/constants[1])*(current_values[5] - current_values[2])+current_values[2];\n          residual_terms_1[ix] = (\n            current_values[3] * std::exp( - (diff*diff) / (2. * psigma * psigma)));\n          model += residual_terms_1[ix];\n          }\n\n          //elastic-photon Gaussian\n          {\n          double pmean = current_values[0] + current_values[2] * constants[1];\n          diff = free_x[ix] - pmean;\n          double psigma = current_values[5];\n          residual_terms_2[ix] = (\n            current_values[4] * std::exp( - (diff*diff) / (2. * psigma * psigma)));\n          model += residual_terms_2[ix];\n          }\n\n          //terms = [\n          //ampl * flex.exp(-flex.pow2(free_x - mean) / (2.*sigm*sigm))\n          //for mean,ampl,sigm in [(z_mean,z_ampl,z_sigm),(o_mean,o_ampl,o_sigm)]]\n          //#print \"residual\", math.sqrt(flex.sum((model-free_y)*(model-free_y)))\n          residuals[ix] = ( model - free_y[ix] );\n        }\n      }\n\n    private:\n      scitbx::af::shared<double> free_x, free_y, jacobian_one_row, residuals;\n      scitbx::af::shared<double> constants;\n      double gain_to_sigma, sigmafac, sigmafac_sq;\n      std::vector<double> residual_terms_0, residual_terms_1, residual_terms_2;\n\n  };\n\n}} //xes::example\n\nnamespace boost_python { namespace {\n\n  void\n  xes_ext_init_module() {\n    using namespace boost::python;\n\n    typedef return_value_policy<return_by_value> rbv;\n    typedef default_call_policies dcp;\n    typedef xes::example::gaussian_fit_inheriting_from_non_linear_ls wt;\n    typedef xes::example::gaussian_3fit_inheriting_from_non_linear_ls wt3;\n\n    class_<xes::example::gaussian_fit_inheriting_from_non_linear_ls,\n           bases<scitbx::lstbx::normal_equations::non_linear_ls<double> > >(\n      \"gaussian_fit_inheriting_from_non_linear_ls\", no_init)\n      .def(init<int>(arg(\"n_parameters\")))\n      .def(\"access_cpp_build_up_directly\",&wt::access_cpp_build_up_directly,\n        (arg(\"objective_only\"),arg(\"current_values\")))\n      .def(\"set_cpp_data\",&wt::set_cpp_data,\n        (arg(\"free_x\"),arg(\"free_y\"),arg(\"gain_to_sigma\"),arg(\"sigmafac\")))\n    ;\n    class_<xes::example::gaussian_3fit_inheriting_from_non_linear_ls,\n           bases<scitbx::lstbx::normal_equations::non_linear_ls<double> > >(\n      \"gaussian_3fit_inheriting_from_non_linear_ls\", no_init)\n      .def(init<int>(arg(\"n_parameters\")))\n      .def(\"access_cpp_build_up_directly\",&wt3::access_cpp_build_up_directly,\n        (arg(\"objective_only\"),arg(\"current_values\")))\n      .def(\"set_cpp_data\",&wt3::set_cpp_data,\n        (arg(\"constants\"),arg(\"free_x\"),arg(\"free_y\")))\n    ;\n  }\n\n}\n}} // namespace xfel::boost_python::<anonymous>\n\nBOOST_PYTHON_MODULE(xes_ext)\n{\n  xfel::boost_python::xes_ext_init_module();\n\n}\n", "meta": {"hexsha": "86dcad1138e0c9c6feda591019c12a8457d501f2", "size": 11256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xfel/vonHamos/xes_ext.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T12:31:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:27:06.000Z", "max_issues_repo_path": "xfel/vonHamos/xes_ext.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "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": "xfel/vonHamos/xes_ext.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-26T12:52:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T12:52:30.000Z", "avg_line_length": 41.3823529412, "max_line_length": 119, "alphanum_fraction": 0.6024342573, "num_tokens": 2910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5398261711233229}}
{"text": "#include \"Quaca.h\"\n#include \"catch.hpp\"\n#include <armadillo>\n#include <complex>\n\nTEST_CASE(\"Vacuum Green's tensor constructors work as expected\",\n          \"[GreensTensorVacuum]\") {\n\n  SECTION(\"Direct constructor\") {\n    auto v = GENERATE(3.2e-3,1.2e-1);\n    auto beta = GENERATE(3.65,100.34);\n    auto relerr = GENERATE(1e-8,1e-7);\n\n    GreensTensorVacuum Greens(v, beta, relerr);\n\n    REQUIRE(Greens.get_v() == v);\n    REQUIRE(Greens.get_beta() == beta);\n    REQUIRE(Greens.get_relerr() == relerr);\n  }\n\n  SECTION(\"json file constructor\") {\n    double v = 0.1;\n    double beta = 5;\n    double relerr = 1E-9;\n\n    GreensTensorVacuum Greens(\"../data/test_files/GreensTensorVacuum.json\");\n\n    REQUIRE(Approx(Greens.get_v()).epsilon(1E-6) == v);\n    REQUIRE(Approx(Greens.get_beta()).epsilon(1E-6) == beta);\n    REQUIRE(Greens.get_relerr() == relerr);\n  }\n}\n\nTEST_CASE(\"Integrand 1d k is correctly implemented\", \"[GreensTensorVacuum]\") {\n  // Generate a Green's tensor with random attributes v and beta\n  auto v = GENERATE(1e-4,1e-8);\n  auto beta = GENERATE(0.21,1.32,5.23);\n  double relerr = 1E-9;\n  GreensTensorVacuum Greens(v, beta, relerr);\n\n  // Create the variables for the num_result, taking care, that\n  //\\omega^2 - k^2 >= 0 to stay in the non-trivial regime\n  auto omega = GENERATE(-7.43,0.21,1.76);\n  auto k_v = GENERATE(-.9,.1,.8);\n  if (k_v < 0)\n    k_v *= omega / (1 + v);\n  if (k_v >= 0)\n    k_v *= omega / (1 - v);\n\n  // Check the integrand for all possible integration options\n  double omega_kv = omega + v * k_v;\n  double xi = pow(omega_kv, 2) - pow(k_v, 2);\n\n  cx_mat::fixed<3,3> LHS(fill::zeros);\n  cx_mat::fixed<3,3> RHS(fill::zeros);\n\n\n  //Set the values of the analytical result\n  LHS(0,0) = .5 * xi;\n  LHS(1,1) = .5 * (pow(omega_kv, 2) - .5 * xi);\n  LHS(2,2) = LHS(1,1);\n\n  SECTION(\"Option: IM\") {\n    double factor = 1.;\n    for(size_t i = 0; i < 3; ++i) {\n      for(size_t j = 0; j < 3; ++j) {\n\tRHS(i,j) = Greens.integrand_k(k_v, omega, {i, j}, IM, UNIT);\n      }\n    }\n    //Ensure that result is non-trivial\n    REQUIRE(!RHS.is_zero());\n\n    REQUIRE(approx_equal(LHS,RHS,\"reldiff\",1e-12));\n  }\n\n  SECTION(\"Option: IM, KV\") {\n    double factor = k_v;\n    for(size_t i = 0; i < 3; ++i) {\n      for(size_t j = 0; j < 3; ++j) {\n\tRHS(i,j) = Greens.integrand_k(k_v, omega, {i, j}, IM, KV);\n      }\n    }\n    //Ensure that result is non-trivial\n    REQUIRE(!RHS.is_zero());\n\n    REQUIRE(approx_equal(factor*LHS,RHS,\"reldiff\",1e-12));\n  };\n\n  SECTION(\"Option: IM, TEMP\") {\n    double factor = 1. / (1. - exp(-beta * omega_kv));\n    for(size_t i = 0; i < 3; ++i) {\n      for(size_t j = 0; j < 3; ++j) {\n\tRHS(i,j) = Greens.integrand_k(k_v, omega, {i,j}, IM, TEMP);\n      }\n    }\n    //Ensure that result is non-trivial\n    REQUIRE(!RHS.is_zero());\n\n    REQUIRE(approx_equal(factor*LHS,RHS,\"reldiff\",1e-12));\n  };\n\n  SECTION(\"Option: IM, KV_TEMP\") {\n    double factor = k_v / (1. - exp(-beta * omega_kv));\n    for(size_t i = 0; i < 3; ++i) {\n      for(size_t j = 0; j < 3; ++j) {\n\tRHS(i,j) = Greens.integrand_k(k_v, omega, {i,j}, IM, KV_TEMP);\n      }\n    }\n    //Ensure that result is non-trivial\n    REQUIRE(!RHS.is_zero());\n\n    REQUIRE(approx_equal(factor*LHS,RHS,\"reldiff\",1e-12));\n  };\n\n  SECTION(\"Option: IM, NON_LTE\") {\n    double factor =\n        1. / (1. - exp(-beta * (omega_kv))) - 1. / (1. - exp(-beta * omega));\n    for(size_t i = 0; i < 3; ++i) {\n      for(size_t j = 0; j < 3; ++j) {\n\tRHS(i,j) = Greens.integrand_k(k_v, omega, {i,j}, IM, NON_LTE);\n      }\n    }\n\n    //Ensure non-trivial result\n    REQUIRE(!RHS.is_zero());\n\n    REQUIRE(approx_equal(factor*LHS,RHS,\"reldiff\",1e-12));\n  };\n};\n\n/*!\n * Some basic relations any Green's tensor should fulfill which can\n * be found in docs under: Relations_and_num_results.pdf\n */\nTEST_CASE(\"Crossing relation in frequency domain see eq. [1]\",\n          \"[GreensTensorVacuum]\") {\n  // Generate a Green's tensor with random attributes v and beta\n  auto v = GENERATE(1e-4,1e-8);\n  auto beta = GENERATE(0.01,10.);\n  double relerr = 1E-9;\n\n  // Create the variables for the num_result, taking care, that\n  //\\omega^2 - k^2 >= 0 to stay in the non-trivial regime\n  auto k_x = GENERATE(-12.42,0.124,76.543);\n  auto k_y = GENERATE(-6.543,-1.43,34.123);\n  auto omega = GENERATE(1.1, 5.3,10.2);\n  double k = sqrt(k_x * k_x + k_y * k_y);\n  omega *= k;\n\n  GreensTensorVacuum Greens(v, beta, relerr);\n\n  cx_mat::fixed<3, 3> Greens_lhs(fill::zeros);\n  cx_mat::fixed<3, 3> Greens_rhs(fill::zeros);\n\n  Greens.calculate_tensor(omega, {k_x, k_y}, Greens_lhs);\n  Greens.calculate_tensor(-omega, {-k_x, -k_y}, Greens_rhs);\n\n  //Ensure non-trivial result\n  REQUIRE(!Greens_lhs.is_zero());\n  REQUIRE(!Greens_rhs.is_zero());\n\n  REQUIRE(approx_equal(Greens_lhs, trans(conj(Greens_rhs)), \"reldiff\", 10E-5));\n}\n\nTEST_CASE(\"Reciprocity, see eq. [6]\", \"[GreensTensorVacuum]\") {\n  // Generate a Green's tensor with random attributes v and beta\n  auto v = GENERATE(1e-4,1e-8);\n  auto beta = GENERATE(0.01,10.);\n  double relerr = 1E-9;\n\n  auto k_x = GENERATE(-12.42,0.124,76.543);\n  auto k_y = GENERATE(-6.543,-1.43,34.123);\n  auto omega = GENERATE(1.1, 5.3,10.2);\n\n  // Take care that we are looking at the non trivial part of the Green's tensor\n  // where \\omega^2 - k^2 >= 0\n  double k = sqrt(k_x * k_x + k_y * k_y);\n  omega *= k;\n\n  GreensTensorVacuum Greens(v, beta, relerr);\n\n  // Create the matries storing the Green's tensors\n  cx_mat::fixed<3, 3> Greens_lhs(fill::zeros);\n  cx_mat::fixed<3, 3> Greens_rhs(fill::zeros);\n\n  Greens.calculate_tensor(omega, {k_x, k_y}, Greens_lhs);\n  Greens.calculate_tensor(omega, {-k_x, -k_y}, Greens_rhs);\n\n  //Ensure non-trivial result\n  REQUIRE(!Greens_lhs.is_zero());\n  REQUIRE(!Greens_rhs.is_zero());\n\n  REQUIRE(approx_equal(Greens_lhs, trans(Greens_rhs), \"reldiff\", 10E-5));\n}\n\nTEST_CASE(\"Reality, see eq. [7]\", \"[GreensTensorVacuum]\") {\n  // Generate a Green's tensor with random attributes v and beta\n  auto v = GENERATE(1e-4,1e-8);\n  auto beta = GENERATE(0.01,10.);\n  auto omega = GENERATE(1.32,6.34,10.32,54.21);\n  double relerr = 1E-9;\n\n  GreensTensorVacuum Greens(v, beta, relerr);\n\n  cx_mat::fixed<3, 3> Greens_lhs(fill::zeros);\n  cx_mat::fixed<3, 3> Greens_rhs(fill::zeros);\n\n  Greens.integrate_k(omega, Greens_lhs, IM, UNIT);\n  Greens.integrate_k(-omega, Greens_rhs, IM, UNIT);\n\n  //Ensure non-trivial result\n  REQUIRE(!Greens_lhs.is_zero());\n  REQUIRE(!Greens_rhs.is_zero());\n\n  REQUIRE(approx_equal(Greens_lhs, -Greens_rhs, \"reldiff\", 10E-5));\n}\n\nTEST_CASE(\"Test the integration routine\", \"[GreensTensorVacuum]\") {\n\n  SECTION(\"Option: IM\") {\n    // Generate a Green's tensor with random attributes v and beta\n    auto v = GENERATE(1e-4);\n    auto beta = GENERATE(1e-3);\n    auto omega = GENERATE(1.32);\n    double relerr = 1E-9;\n    GreensTensorVacuum Greens(v, beta, relerr);\n\n    // Matrix to store the analytic results\n    cx_mat::fixed<3, 3> ana_result(fill::zeros);\n    // Computing the analytical result and storing it in analytic\n    double ana_pref = 2. / 3. * pow(omega, 3) / pow(1 - pow(v, 2), 2);\n    ana_result(0, 0) = ana_pref;\n    ana_result(1, 1) = ana_pref * (1 + pow(v, 2)) / (1 - pow(v, 2));\n    ana_result(2, 2) = ana_pref * (1 + pow(v, 2)) / (1 - pow(v, 2));\n\n    // Matrix storing the numerical integration\n    cx_mat::fixed<3, 3> num_result(fill::zeros);\n    Greens.integrate_k(omega, num_result, IM, UNIT);\n\n    //Ensure non-trivial results\n    REQUIRE(!num_result.is_zero());\n    REQUIRE(!ana_result.is_zero());\n\n    REQUIRE(approx_equal(num_result, ana_result, \"reldiff\", 10E-5));\n  }\n\n  SECTION(\"Option: IM, KV\") {\n\n    // Generate a Green's tensor with random attributes v and beta\n    auto v = GENERATE(1e-4);\n    auto beta = GENERATE(1e-3);\n    auto omega = GENERATE(1.32);\n    double relerr = 1E-9;\n    GreensTensorVacuum Greens(v, beta, relerr);\n\n    // Matrix to store the analytic results\n    cx_mat::fixed<3, 3> ana_result(fill::zeros);\n    // Computing the analytical result and storing it in analytic\n    double ana_pref = 2. / 3. * pow(omega, 4) * v / pow(1 - pow(v, 2), 3);\n    ana_result(0.0) = ana_pref;\n    ana_result(1, 1) = ana_pref * (2. + pow(v, 2)) / (1. - pow(v, 2));\n    ana_result(2, 2) = ana_result(1, 1);\n\n    // Matrix storing the numerical integration\n    cx_mat::fixed<3, 3> num_result(fill::zeros);\n    Greens.integrate_k(omega, num_result, IM, KV);\n\n    //Ensure non-trivial results\n    REQUIRE(!num_result.is_zero());\n    REQUIRE(!ana_result.is_zero());\n\n    REQUIRE(approx_equal(num_result, ana_result, \"reldiff\", 10E-5));\n  }\n\n  SECTION(\"Option: IM, TEMP\") {\n    // Generate a Green's tensor with random attributes v and beta\n    auto v = GENERATE(1e-4);\n    auto beta = GENERATE(1e-3);\n    auto omega = GENERATE(1.32);\n    beta *= fabs(omega);\n    double relerr = 1E-9;\n    GreensTensorVacuum Greens(v, beta, relerr);\n\n    // Matrix to store the analytic results\n    cx_mat::fixed<3, 3> ana_result(fill::zeros);\n    // Computing the analytical result and storing it in analytic\n    double ana_pref = pow(omega, 2) / (2. * pow(v, 3) * beta);\n    ana_result(0.0) = ana_pref * (2. * v / (1. - pow(v, 2)) - 2. * atanh(v));\n    ana_result(1, 1) =\n        ana_pref * ((3. * pow(v, 3) - v) / pow(1 - pow(v, 2), 2) + atanh(v));\n    ana_result(2, 2) = ana_result(1, 1);\n\n    // Matrix storing the numerical integration\n    cx_mat::fixed<3, 3> num_result(fill::zeros);\n    Greens.integrate_k(omega, num_result, IM, TEMP);\n\n    //Ensure non-trivial results\n    REQUIRE(!num_result.is_zero());\n    REQUIRE(!ana_result.is_zero());\n\n    REQUIRE(approx_equal(num_result, ana_result, \"reldiff\", 10E-4));\n  }\n\n  SECTION(\"Option: IM, KV_TEMP\") {\n    // Generate a Green's tensor with random attributes v and beta\n    auto v = GENERATE(1e-2);\n    auto beta = GENERATE(1e-12);\n    auto omega = GENERATE(.54);\n    double relerr = 1E-9;\n    GreensTensorVacuum Greens(v, beta, relerr);\n\n    // Matrix to store the analytic results\n    cx_mat::fixed<3, 3> ana_result(fill::zeros);\n    // Computing the analytical result and storing it in analytic\n    double ana_pref = std::pow(omega, 3) / (6. * std::pow(v, 4) * beta);\n    ana_result(0, 0) =\n        ana_pref * (2 * (5 * pow(v, 3) - 3. * v) / pow(1. - pow(v, 2), 2) +\n                    6. * std::atanh(v));\n    ana_result(1, 1) = ana_pref * ((8. * pow(v, 3) - 3. * v - 13. * pow(v, 5)) /\n                                       pow(pow(v, 2) - 1, 3) -\n                                   3. * std::atanh(v));\n    ana_result(2, 2) = ana_result(1, 1);\n\n    // Matrix storing the numerical integration\n    cx_mat::fixed<3, 3> num_result(fill::zeros);\n    Greens.integrate_k(omega, num_result, IM, KV_TEMP);\n\n    //Ensure non-trivial results\n    REQUIRE(!num_result.is_zero());\n    REQUIRE(!ana_result.is_zero());\n\n    REQUIRE(approx_equal(num_result, ana_result, \"reldiff\", 10E-5));\n  }\n}\n", "meta": {"hexsha": "e6eff846e6f0dcf37dbeb3951b6f0f2881677e61", "size": 10777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/UnitTests/GreensTensor/test_GreensTensorVacuum_unit.cpp", "max_stars_repo_name": "QuaCaTeam/quaca", "max_stars_repo_head_hexsha": "ab2d213f3e0e357bd72930ae1e4e703184130270", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T09:01:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T07:57:54.000Z", "max_issues_repo_path": "test/UnitTests/GreensTensor/test_GreensTensorVacuum_unit.cpp", "max_issues_repo_name": "myoelmy/quaca", "max_issues_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T08:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-28T07:33:35.000Z", "max_forks_repo_path": "test/UnitTests/GreensTensor/test_GreensTensorVacuum_unit.cpp", "max_forks_repo_name": "myoelmy/quaca", "max_forks_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_forks_repo_licenses": ["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.1701492537, "max_line_length": 80, "alphanum_fraction": 0.6214159785, "num_tokens": 3577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7122321903471565, "lm_q1q2_score": 0.5397255526774747}}
{"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 <iostream>\r\n#include <fstream>\r\n#include <vector>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/graph/graphviz.hpp>\r\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  GraphvizGraph g_dot;\r\n  read_graphviz(\"figs/telephone-network.dot\", g_dot);\r\n\r\n  typedef adjacency_list < vecS, vecS, undirectedS, no_property,\r\n    property < edge_weight_t, int > > Graph;\r\n  Graph g(num_vertices(g_dot));\r\n  property_map < GraphvizGraph, edge_attribute_t >::type\r\n    edge_attr_map = get(edge_attribute, g_dot);\r\n  graph_traits < GraphvizGraph >::edge_iterator ei, ei_end;\r\n  for (boost::tie(ei, ei_end) = edges(g_dot); ei != ei_end; ++ei) {\r\n    int weight = lexical_cast < int >(edge_attr_map[*ei][\"label\"]);\r\n    property < edge_weight_t, int >edge_property(weight);\r\n    add_edge(source(*ei, g_dot), target(*ei, g_dot), edge_property, g);\r\n  }\r\n\r\n  typedef graph_traits < Graph >::vertex_descriptor Vertex;\r\n  std::vector < Vertex > parent(num_vertices(g));\r\n  property_map < Graph, edge_weight_t >::type weight = get(edge_weight, g);\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  property_map<Graph, vertex_index_t>::type indexmap = get(vertex_index, g);  \r\n  std::vector<std::size_t> distance(num_vertices(g));\r\n  prim_minimum_spanning_tree(g, *vertices(g).first, &parent[0], &distance[0],\r\n                             weight, indexmap, default_dijkstra_visitor());\r\n#else\r\n  prim_minimum_spanning_tree(g, &parent[0]);\r\n#endif\r\n\r\n  int total_weight = 0;\r\n  for (int v = 0; v < num_vertices(g); ++v)\r\n    if (parent[v] != v)\r\n      total_weight += get(weight, edge(parent[v], v, g).first);\r\n  std::cout << \"total weight: \" << total_weight << std::endl;\r\n\r\n  for (int u = 0; u < num_vertices(g); ++u)\r\n    if (parent[u] != u)\r\n      edge_attr_map[edge(parent[u], u, g_dot).first][\"color\"] = \"black\";\r\n  std::ofstream out(\"figs/telephone-mst-prim.dot\");\r\n  graph_property < GraphvizGraph, graph_edge_attribute_t >::type &\r\n    graph_edge_attr_map = get_property(g_dot, graph_edge_attribute);\r\n  graph_edge_attr_map[\"color\"] = \"gray\";\r\n  write_graphviz(out, g_dot);\r\n\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "61dc17a7ffae144f85b399c9e62a9a7dd64bc8b2", "size": 2562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/prim-telephone.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/prim-telephone.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/prim-telephone.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": 40.6666666667, "max_line_length": 79, "alphanum_fraction": 0.6405152225, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5397255480487079}}
{"text": "#include \"NumCpp.hpp\"\r\n#include <Eigen/Dense>\r\n\r\n#include <iostream>\r\n\r\ntypedef Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> EigenIntMatrix;\r\ntypedef Eigen::Map<EigenIntMatrix> EigenIntMatrixMap;\r\n\r\nint main()\r\n{\r\n    // construct some NumCpp arrays\r\n    auto ncA = nc::random::randInt<int>({ 5, 5 }, 0, 10);\r\n    auto ncB = nc::random::randInt<int>({ 5, 5 }, 0, 10);\r\n\r\n    std::cout << \"ncA:\\n\" << ncA << std::endl;\r\n    std::cout << \"ncB:\\n\" << ncB << std::endl;\r\n\r\n    // map the arrays to Eigen \r\n    auto eigenA = EigenIntMatrixMap(ncA.data(), ncA.numRows(), ncA.numCols());\r\n    auto eigenB = EigenIntMatrixMap(ncB.data(), ncB.numRows(), ncB.numCols());\r\n\r\n    // add the two Eigen matrices\r\n    auto eigenC = eigenA + eigenB;\r\n\r\n    // add the two NumCpp arrays for a sanity check\r\n    auto ncC = ncA + ncB;\r\n\r\n    // convert the Eigen result back to NumCpp\r\n    int* dataPtr = new int[eigenC.rows() * eigenC.cols()];\r\n    EigenIntMatrixMap(dataPtr, eigenC.rows(), eigenC.cols()) = eigenC;\r\n\r\n    constexpr bool takeOwnership = true;\r\n    auto ncCeigen = nc::NdArray<int>(dataPtr, eigenC.rows(), eigenC.cols(), takeOwnership);\r\n\r\n    // compare the two outputs\r\n    if (nc::array_equal(ncC, ncCeigen))\r\n    {\r\n        std::cout << \"Arrays are equal.\" << std::endl;\r\n        std::cout << ncC << std::endl;\r\n    }\r\n    else\r\n    {\r\n        std::cout << \"Arrays are not equal.\" << std::endl;\r\n        std::cout << \"ncCeigen:\\n\" << ncCeigen << std::endl;\r\n        std::cout << \"ncC:\\n\" << ncC << std::endl;\r\n    }\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "912faa72696d52b54d7c67095a5750cb75308a52", "size": 1562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/InterfaceWithEigen/InterfaceWithEigen.cpp", "max_stars_repo_name": "faichele/NumCpp", "max_stars_repo_head_hexsha": "7c8fc50fbe44b80eaa105f0f9258120abddfcec2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2358.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T03:43:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:02:56.000Z", "max_issues_repo_path": "examples/InterfaceWithEigen/InterfaceWithEigen.cpp", "max_issues_repo_name": "lamarrr/NumCpp", "max_issues_repo_head_hexsha": "a24328e9d8dc472607a09ba50419baf21b1d3142", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 134.0, "max_issues_repo_issues_event_min_datetime": "2018-11-07T09:45:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T17:23:01.000Z", "max_forks_repo_path": "examples/InterfaceWithEigen/InterfaceWithEigen.cpp", "max_forks_repo_name": "lamarrr/NumCpp", "max_forks_repo_head_hexsha": "a24328e9d8dc472607a09ba50419baf21b1d3142", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 370.0, "max_forks_repo_forks_event_min_datetime": "2018-09-05T08:38:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:24:46.000Z", "avg_line_length": 31.24, "max_line_length": 92, "alphanum_fraction": 0.5877080666, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5397255448856836}}
{"text": "#ifndef GUARD_PERM_GROUP_H\n#define GUARD_PERM_GROUP_H\n\n#include <cassert>\n#include <map>\n#include <tuple>\n#include <type_traits>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"bsgs.hpp\"\n#include \"perm.hpp\"\n#include \"perm_set.hpp\"\n#include \"timeout.hpp\"\n#include \"util.hpp\"\n\nnamespace mpsym\n{\n\nnamespace internal\n{\n\nclass Orbit;\nclass OrbitPartition;\n\nclass BlockSystem;\n\nclass PermGroup\n{\n  friend std::ostream &operator<<(std::ostream &os, PermGroup const &pg);\n\npublic:\n  using value_type = Perm;\n  using const_reference = Perm const &;\n\n  class const_iterator : public util::Iterator<const_iterator, Perm const>\n  {\n  public:\n    const_iterator() : _end(true) {};\n    const_iterator(PermGroup const &pg);\n\n    bool operator==(const_iterator const &rhs) const override;\n\n    PermSet const &factors() const\n    { return _current_factors; }\n\n  private:\n    reference current() override;\n    void next() override;\n\n    std::vector<unsigned> _state;\n    bool _trivial;\n    bool _end;\n\n    std::vector<PermSet> _transversals;\n    Perm _current;\n    bool _current_valid;\n    PermSet _current_factors;\n  };\n\n  explicit PermGroup(unsigned degree = 1)\n  : _bsgs(degree),\n    _order(1)\n  {}\n\n  explicit PermGroup(BSGS const &bsgs)\n  : _bsgs(bsgs),\n    _order(bsgs.order())\n  {}\n\n  PermGroup(PermSet const &generators)\n  : PermGroup(generators.degree(), generators)\n  {}\n\n  PermGroup(unsigned degree, PermSet const &generators);\n\n  static PermGroup symmetric(unsigned degree);\n  static PermGroup cyclic(unsigned degree);\n  static PermGroup dihedral(unsigned degree);\n\n  template<typename IT>\n  static PermGroup direct_product(IT first,\n                                  IT last,\n                                  BSGSOptions const *bsgs_options_ = nullptr,\n                                  timeout::flag aborted = timeout::unset())\n  {\n    assert(std::distance(first, last) > 0);\n\n    // direct product degree\n    unsigned dp_degree = 0u;\n\n    for (auto it = first; it != last; ++it)\n      dp_degree += it->degree();\n\n    // direct product order\n    auto dp_order(direct_product_order(first, last));\n\n    // direct product generators\n    unsigned d = 0u;\n\n    PermSet dp_generators;\n    for (auto it = first; it != last; ++it) {\n      for (Perm const &perm : it->generators())\n        dp_generators.insert(perm.shifted(d).extended(dp_degree));\n\n      d += it->degree();\n    }\n\n    // construct direct product\n    auto bsgs_options(BSGSOptions::fill_defaults(bsgs_options_));\n    bsgs_options.schreier_sims_random_known_order = dp_order;\n\n    return PermGroup(BSGS(dp_degree, dp_generators, &bsgs_options, aborted));\n  }\n\n  template<typename IT>\n  static BSGS::order_type direct_product_order(IT first, IT last)\n  {\n    BSGS::order_type dp_order = 1u;\n\n    for (auto it = first; it != last; ++it)\n      dp_order *= it->order();\n\n    return dp_order;\n  }\n\n  static PermSet wreath_product_generators(PermGroup const &lhs,\n                                           PermGroup const &rhs);\n\n  static PermGroup wreath_product(PermGroup const &lhs,\n                                  PermGroup const &rhs,\n                                  BSGSOptions const *bsgs_options = nullptr,\n                                  timeout::flag aborted = timeout::unset());\n\n  static BSGS::order_type wreath_product_order(PermGroup const &lhs,\n                                               PermGroup const &rhs);\n\n  bool operator==(PermGroup const &rhs) const;\n  bool operator!=(PermGroup const &rhs) const;\n\n  const_iterator begin() const { return const_iterator(*this); }\n  const_iterator end() const { return const_iterator(); }\n\n  PermSet generators() const { return _bsgs.strong_generators(); }\n\n  BSGS &bsgs() { return _bsgs; }\n  BSGS const &bsgs() const { return _bsgs; }\n\n  unsigned degree() const { return _bsgs.degree(); }\n  BSGS::order_type order() const { return _order; }\n\n  unsigned smallest_moved_point() const\n  { return generators().smallest_moved_point(); }\n\n  unsigned largest_moved_point() const\n  { return generators().largest_moved_point(); }\n\n  std::vector<unsigned> support() const\n  { return generators().support(); }\n\n  bool is_trivial() const { return _bsgs.base_empty(); }\n  bool is_symmetric() const;\n  bool is_shifted_symmetric() const;\n  bool is_transitive() const;\n\n  bool contains_element(Perm const &perm) const;\n  Perm random_element() const;\n\n  std::vector<PermGroup> disjoint_decomposition(\n    bool complete = true, bool disjoint_orbit_optimization = false) const;\n\n  std::vector<PermGroup> wreath_decomposition() const;\n\nprivate:\n  static boost::multiprecision::cpp_int symmetric_order(unsigned deg)\n  {\n    boost::multiprecision::cpp_int ret(1);\n    for (unsigned i = deg; i > 0u; --i)\n      ret *= i;\n\n    return ret;\n  }\n\n  // complete disjoint decomposition\n  bool disjoint_decomp_orbits_dependent(\n    Orbit const &orbit1,\n    Orbit const &orbit2) const;\n\n  void disjoint_decomp_generate_dependency_classes(\n    OrbitPartition &orbits) const;\n\n  static bool disjoint_decomp_restricted_subgroups(\n    OrbitPartition const &orbit_split,\n    PermGroup const &perm_group,\n    std::pair<PermGroup, PermGroup> &restricted_subgroups);\n\n  static std::vector<PermGroup> disjoint_decomp_join_results(\n    std::vector<PermGroup> const &res1,\n    std::vector<PermGroup> const &res2);\n\n  static std::vector<PermGroup> disjoint_decomp_complete_recursive(\n    OrbitPartition const &orbits,\n    PermGroup const &perm_group);\n\n  std::vector<PermGroup> disjoint_decomp_complete(\n    bool disjoint_orbit_optimization = true) const;\n\n  // incomplete disjoint decomposition\n  struct MovedSet : public std::vector<unsigned>\n  {\n    void init(Perm const &perm);\n    bool equivalent(MovedSet const &other) const;\n    void extend(MovedSet const &other);\n  };\n\n  struct EquivalenceClass\n  {\n    EquivalenceClass(Perm const &init, MovedSet const &moved)\n    : generators({init}),\n      moved(moved),\n      merged(false)\n    {}\n\n    PermSet generators;\n    MovedSet moved;\n    bool merged;\n  };\n\n  std::vector<EquivalenceClass> disjoint_decomp_find_equivalence_classes() const;\n\n  void disjoint_decomp_merge_equivalence_classes(\n    std::vector<EquivalenceClass> &equivalence_classes) const;\n\n  std::vector<PermGroup> disjoint_decomp_incomplete() const;\n\n  // wreath decomposition\n  std::vector<PermGroup> wreath_decomp_find_stabilizers(\n    BlockSystem const &block_system,\n    PermGroup const &block_permuter) const;\n\n  PermSet wreath_decomp_construct_block_permuter_image(\n    BlockSystem const &block_system,\n    PermGroup const &block_permuter) const;\n\n  bool wreath_decomp_reconstruct_block_permuter(\n    BlockSystem const &block_system,\n    PermGroup const &block_permuter,\n    PermSet const &block_permuter_image) const;\n\n  BSGS _bsgs;\n  BSGS::order_type _order;\n};\n\nstd::ostream &operator<<(std::ostream &os, PermGroup const &pg);\n\n} // namespace internal\n\n} // namespace mpsym\n\n#endif // GUARD_PERM_GROUP_H\n", "meta": {"hexsha": "e6ca6a8da16988c753578335e133975aec19934f", "size": 6931, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/perm_group.hpp", "max_stars_repo_name": "goens/TUD_computational_group_theory", "max_stars_repo_head_hexsha": "3f4703cae1ac049089db23eafc321e8daca2d99d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-10T09:31:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-14T15:19:20.000Z", "max_issues_repo_path": "include/perm_group.hpp", "max_issues_repo_name": "goens/TUD_computational_group_theory", "max_issues_repo_head_hexsha": "3f4703cae1ac049089db23eafc321e8daca2d99d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-06-11T07:25:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-19T09:07:50.000Z", "max_forks_repo_path": "include/perm_group.hpp", "max_forks_repo_name": "goens/TUD_computational_group_theory", "max_forks_repo_head_hexsha": "3f4703cae1ac049089db23eafc321e8daca2d99d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T19:31:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T13:17:50.000Z", "avg_line_length": 26.4541984733, "max_line_length": 81, "alphanum_fraction": 0.6890780551, "num_tokens": 1691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5397255448856834}}
{"text": "#pragma once\n#ifndef CANNON_RAY_FILTER_H\n#define CANNON_RAY_FILTER_H\n\n/*!\n * \\file cannon/ray/filter.hpp\n * File containing class definitions for Film reconstruction filters.\n */\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace ray {\n\n    /*!\n     * \\brief Abstract base class representing a reconstruction filter for\n     * integrating image samples.\n     */\n    class Filter {\n      public:\n\n        /*!\n         * \\brief Constructor taking a radius for this filter.\n         */\n        Filter(const Vector2d& radius) : radius_(radius), inv_radius_(1.0 /\n            radius.x(), 1.0 / radius.y()) {}\n\n        /*!\n         * \\brief Get the value of this filter at the input point. The filter\n         * is assumed to be centered at the origin, so the input point should\n         * be with respect to the actual filter position.\n         *\n         * \\param p The point to evaluate the filter for.\n         *\n         * \\returns The value of this filter at the point.\n         */\n        virtual double evaluate(const Vector2d& p) const = 0;\n\n        /*!\n         * \\brief Destructor.\n         */\n        virtual ~Filter() {}\n\n      public:\n        const Vector2d radius_; //!< Radius of this filter\n        const Vector2d inv_radius_; //!< 1 / radius, speeds up math\n\n    };\n\n    /*!\n     * \\brief Class representing the most basic image reconstruction filter,\n     * the Box Filter.\n     */\n    class BoxFilter : public Filter {\n      public:\n\n        /*!\n         * \\brief Constructor taking the radius of this filter.\n         */\n        BoxFilter(const Vector2d& radius) : Filter(radius) {}\n\n        /*!\n         * \\brief Destructor.\n         */\n        virtual ~BoxFilter() {}\n\n        /*!\n         * \\brief Inherited from Filter.\n         */\n        virtual double evaluate(const Vector2d& /*p*/) const override {\n          return 1.0;\n        }\n    };\n\n    /*!\n     * \\brief Class representing a triangle filter, which is not much better\n     * than a box filter.\n     */\n    class TriangleFilter : public Filter {\n      public:\n\n        /*!\n         * \\brief Constructor taking the radius of this filter.\n         */\n        TriangleFilter(const Vector2d& radius) : Filter(radius) {}\n\n        /*!\n         * \\brief Destructor.\n         */\n        virtual ~TriangleFilter() {}\n\n        /*!\n         * \\brief Inherited from Filter.\n         */\n        virtual double evaluate(const Vector2d& p) const override {\n          return std::max(0.0, radius_.x() - std::abs(p.x())) *\n                 std::max(0.0, radius_.y() - std::abs(p.y()));\n        }\n    };\n\n    /*!\n     * \\brief Class representing a Gaussian filter. Reasonable for image\n     * reconstruction.\n     */\n    class GaussianFilter : public Filter {\n      public:\n\n        /*!\n         * \\brief Constructor taking the radius of this filter and rate of\n         * Gaussian falloff.\n         */\n        GaussianFilter(const Vector2d &radius, double alpha)\n            : Filter(radius), alpha_(alpha * radius.x()),\n              exp_x_(std::exp(-alpha * radius.x() * radius.x())),\n              exp_y_(std::exp(-alpha * radius.y() * radius.y())) {}\n\n        /*!\n         * \\brief Destructor.\n         */\n        virtual ~GaussianFilter() {}\n\n        /*!\n         * \\brief Inherited from Filter.\n         */\n        virtual double evaluate(const Vector2d& p) const override {\n          return gaussian_(p.x(), exp_x_) * gaussian_(p.y(), exp_y_);\n        }\n\n      private:\n\n        /*!\n         * \\brief 1D Gaussian function, used to compute 2D Gaussian filter\n         * value since this filter is separable.\n         *\n         * \\param d Distance from center of filter\n         * \\param exp_v Constant term\n         */\n        double gaussian_(double d, double exp_v) const {\n          return std::max(0.0, std::exp(-alpha_ * d * d) - exp_v);\n        }\n\n\n        const double alpha_; //!< Gaussian falloff rate\n        const double exp_x_; //!< Cached constant term in x\n        const double exp_y_; //!< Cached constant term in y\n    };\n\n    /*!\n     * \\brief Class representing a Mitchell-Netravali filter. Reasonable for image\n     * reconstruction.\n     */\n    class MitchellFilter : public Filter {\n      public:\n\n        /*!\n         * \\brief Constructor taking the radius of this filter and\n         * Mitchell-Netravali parameters B and C.\n         */\n        MitchellFilter(const Vector2d &radius, double b, double c)\n            : Filter(radius), b_(b), c_(c) {}\n\n        /*!\n         * \\brief Destructor.\n         */\n        virtual ~MitchellFilter() {}\n\n        /*!\n         * \\brief Inherited from Filter.\n         */\n        virtual double evaluate(const Vector2d& p) const override {\n          return mitchell_1d_(p.x() * inv_radius_.x()) * mitchell_1d_(p.y() * inv_radius_.y());\n        }\n\n      private:\n\n        /*!\n         * \\brief 1D Mitchell function, used to compute 2D Mitchell filter\n         * value since this filter is separable.\n         *\n         * \\param x Scaled distance from center of filter\n         */\n        double mitchell_1d_(double x) const {\n          x = std::abs(2 * x);\n\n          if (x > 1)\n            return ((-b_ - 6*c_) * x*x*x + (6*b_ + 30*c_) * x*x + \n                    (-12*b_ - 48*c_) * x + (8*b_ + 24*c_)) * (1.0 / 6.0);\n          else\n            return ((12 - 9*b_ - 6*c_) * x*x*x +\n                    (-18 + 12*b_ + 6*c_) * x*x +\n                    (6 - 2*b_)) * (1.0 / 6.0);\n        }\n\n        double b_;\n        double c_;\n\n    };\n\n\n  } // namespace ray\n} // namespace cannon\n\n#endif /* ifndef CANNON_RAY_FILTER_H */\n", "meta": {"hexsha": "14286e469b5c8f47609b4ed8911cfe8321f97d05", "size": 5580, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/ray/filter.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/ray/filter.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/ray/filter.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": 27.0873786408, "max_line_length": 95, "alphanum_fraction": 0.5326164875, "num_tokens": 1311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.539725543419941}}
{"text": "//\n// Test module for ntl_wrapper.cpp\n//\n#include <cstdlib>\n#include <string>\n#include <fstream>\n#include <stdexcept>\n\n#define BOOST_TEST_MODULE ntl_wrapper\n#include <boost/test/included/unit_test.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include <NTL/matrix.h>\n#include <NTL/ZZ.h>\n\n#include \"types.h\"\n\n/* module being tested */\n#include \"ntl_wrapper.h\"\n\nusing std::ifstream;\nusing std::string;\nusing std::runtime_error;\n\nusing boost::numeric::ublas::matrix;\nusing NTL::ZZ;\nusing NTL::Mat;\n\nstatic const string LATTICE_95 = \"../test/data/lattice_95.tst\";\n\n// rank of the 64-dim'l lattice after LLL is still 64\nBOOST_AUTO_TEST_CASE( test_rk_LLL_lattice_95 ) {\n    Mat<ZZ> N = read_lattice_ntl(LATTICE_95);\n    ZZ det2;\n    BOOST_CHECK( NTL::LLL(det2, N) == 64 );\n}\n\n// rank of half the 64-dim'l lattice is 32\nBOOST_AUTO_TEST_CASE( test_rk_LLL_sublattice_95 ) {\n    Mat<ZZ> N = read_lattice_ntl(LATTICE_95);\n    Mat<ZZ> SN = take_cols(N, 32);\n    ZZ det2;\n    BOOST_CHECK( NTL::LLL(det2, SN) == 32 );\n}\n\nlong populate(size_t, size_t);\nlong populate(size_t i, size_t j) { return (long)(3*i + 2*j + 1); }\n\n// Fill a 3x3 boost matrix, convert to NTL, then test elements\nBOOST_AUTO_TEST_CASE( test_matrix_to_ntl ) {\n    matrix<int64> M (3, 3);\n    for (size_t i=0; i != M.size1(); i++) {\n        for (size_t j=0; j != M.size2(); j++) {\n            M(i, j) = populate(i, j);\n        }\n    }\n    Mat<ZZ> N;\n    matrix_to_ntl(M, N);\n    for (size_t i=0; i != (size_t)N.NumRows(); i++) {\n        for (size_t j=0; j != (size_t)N.NumCols(); j++) {\n            BOOST_CHECK( to_long(N[i][j]) == populate(i, j) );\n        }\n    }\n}\n", "meta": {"hexsha": "b4606390d5b990ee4c97ad8d78beabe4dd21ed2c", "size": 1624, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libblt/test_ntl.cc", "max_stars_repo_name": "spazm/blt", "max_stars_repo_head_hexsha": "1bbe307309fa0090f6dd4240af65a18dd630e8ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2016-11-15T22:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T02:47:27.000Z", "max_issues_repo_path": "libblt/test_ntl.cc", "max_issues_repo_name": "spazm/blt", "max_issues_repo_head_hexsha": "1bbe307309fa0090f6dd4240af65a18dd630e8ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-03-24T18:52:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T03:03:27.000Z", "max_forks_repo_path": "libblt/test_ntl.cc", "max_forks_repo_name": "spazm/blt", "max_forks_repo_head_hexsha": "1bbe307309fa0090f6dd4240af65a18dd630e8ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T23:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T08:32:52.000Z", "avg_line_length": 24.9846153846, "max_line_length": 67, "alphanum_fraction": 0.6373152709, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5397255402569169}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2010 Hartmut Kaiser\n    http://spirit.sourceforge.net/\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//[porting_guide_qi_includes\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <iostream>\n#include <string>\n#include <algorithm>\n//]\n\n//[porting_guide_qi_namespace\nusing namespace boost::spirit;\n//]\n\n//[porting_guide_qi_grammar\ntemplate <typename Iterator>\nstruct roman : qi::grammar<Iterator, unsigned()>\n{\n    roman() : roman::base_type(first)\n    {\n        hundreds.add\n            (\"C\"  , 100)(\"CC\"  , 200)(\"CCC\"  , 300)(\"CD\" , 400)(\"D\" , 500)\n            (\"DC\" , 600)(\"DCC\" , 700)(\"DCCC\" , 800)(\"CM\" , 900) ;\n\n        tens.add\n            (\"X\"  , 10)(\"XX\"  , 20)(\"XXX\"  , 30)(\"XL\" , 40)(\"L\" , 50)\n            (\"LX\" , 60)(\"LXX\" , 70)(\"LXXX\" , 80)(\"XC\" , 90) ;\n\n        ones.add\n            (\"I\"  , 1)(\"II\"  , 2)(\"III\"  , 3)(\"IV\" , 4)(\"V\" , 5)\n            (\"VI\" , 6)(\"VII\" , 7)(\"VIII\" , 8)(\"IX\" , 9) ;\n\n        // qi::_val refers to the attribute of the rule on the left hand side \n        first = eps          [qi::_val = 0] \n            >>  (  +lit('M') [qi::_val += 1000]\n                ||  hundreds [qi::_val += qi::_1]\n                ||  tens     [qi::_val += qi::_1]\n                ||  ones     [qi::_val += qi::_1]\n                ) ;\n    }\n\n    qi::rule<Iterator, unsigned()> first;\n    qi::symbols<char, unsigned> hundreds;\n    qi::symbols<char, unsigned> tens;\n    qi::symbols<char, unsigned> ones;\n};\n//]\n\nint main()\n{\n    {\n        //[porting_guide_qi_parse\n        std::string input(\"1,1\");\n        std::string::iterator it = input.begin();\n        bool result = qi::parse(it, input.end(), qi::int_);\n\n        if (result) \n            std::cout << \"successful match!\\n\";\n\n        if (it == input.end()) \n            std::cout << \"full match!\\n\";\n        else\n            std::cout << \"stopped at: \" << std::string(it, input.end()) << \"\\n\";\n\n        // seldomly needed: use std::distance to calculate the length of the match\n        std::cout << \"matched length: \" << std::distance(input.begin(), it) << \"\\n\";\n        //]\n    }\n\n    {\n        //[porting_guide_qi_phrase_parse\n        std::string input(\" 1, 1\");\n        std::string::iterator it = input.begin();\n        bool result = qi::phrase_parse(it, input.end(), qi::int_, ascii::space);\n\n        if (result) \n            std::cout << \"successful match!\\n\";\n\n        if (it == input.end()) \n            std::cout << \"full match!\\n\";\n        else\n            std::cout << \"stopped at: \" << std::string(it, input.end()) << \"\\n\";\n\n        // seldomly needed: use std::distance to calculate the length of the match\n        std::cout << \"matched length: \" << std::distance(input.begin(), it) << \"\\n\";\n        //]\n    }\n\n    {\n        //[porting_guide_qi_use_grammar\n        std::string input(\"MMIX\");        // MMIX == 2009\n        std::string::iterator it = input.begin();\n        unsigned value = 0;\n        roman<std::string::iterator> r;\n        if (qi::parse(it, input.end(), r, value)) \n            std::cout << \"successfully matched: \" << value << \"\\n\";\n        //]\n    }\n    return 0;\n}\n\n", "meta": {"hexsha": "cd93236a996e0cf6727deb68c5c85824620a5f97", "size": 3409, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/spirit/example/qi/porting_guide_qi.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/spirit/example/qi/porting_guide_qi.cpp", "max_issues_repo_name": "jonstewart/boost-svn", "max_issues_repo_head_hexsha": "7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59", "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/spirit/example/qi/porting_guide_qi.cpp", "max_forks_repo_name": "jonstewart/boost-svn", "max_forks_repo_head_hexsha": "7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59", "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": 31.8598130841, "max_line_length": 84, "alphanum_fraction": 0.4887063655, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.539725530999383}}
{"text": "/*\n * NOTE: This solution is based on https://www.reddit.com/r/adventofcode/comments/3xflz8/day_19_solutions/cy4etju/\n *\n * Conceptually, to get the minimum steps from molecule \"e\" to the medicine, we need to go backwards and\n * start with the medicine. The medicine is composed of output molecules, each for which there's an input\n * molecule. So we keep replacing each molecule in the medicine with its input until there's only molecule\n * \"e\" left.\n *\n * Looking at the input file, there are a couple observations we can make:\n *\n * a) There are only two kinds of replacements (\"|\" denotes multiple replacements for the same input):\n * 1. X => XX\n * 2. X => X Rn X Ar | X Rn X Y X Ar | X Rn X Y X Y X Ar\n *\n * b) Following observation a), Rn Y Ar is equivalent to ( , )\n * - X => X(X) | X(X,X) | X(X,X,X)\n *\n * c) When you have a molecule of type XX, that is, none of Rn, Y or Ar, you can apply the first production (see a)),\n * i.e. reverse the replacement like this:\n * - XX => X\n *\n * When you have a molecule of type X(X) | X(X,X) | X(X,X,X), you can apply the second production (see a)), i.e.\n * reverse the replacement like this:\n * - X(X) | X(X,X) | X(X,X,X) => X\n *\n * Applying a production counts as one step.\n *\n * d) Repeatedly applying XX => X until there's only one molecule left takes `count(X) - 1` steps\n * - ABCDE => XCDE => XDE => XE => X\n *\n * This example produces `count(`ABCDE`) - 1` = `5 - 1` = 4 steps.\n *\n * Applying X(X) => X is similar, but `()` must be taken into account, since it increases the count.\n * This is expressed by expanding the formula: `count(`X(X)`) - count(no. of parentheses) - 1` steps. Example:\n * - A(B(C(D(E)))) => A(B(C(X))) => A(B(X)) => A(X) => X\n *\n * count(`A(B(C(D(E))))`) = 13\n * count(`(((())))`) = 8\n *\n * Result: 13 - 8 - 1 = 4 steps\n *\n * Applying X(X,X) | X(X,X,X) => X adds another variable to the count formula, the comma `,`, representing molecule Y.\n * As you can observe, each comma adds two molecules `,X` to the output. Taking this into account, we can write\n * the final formula as follows:\n *\n * `count(`X(X,X)`) - count(parentheses) - 2*count(commas) - 1` steps.\n *\n * - X(X,X) => X is expressed as `6 - 2 - 2 - 1 = 1 step`\n * - X(X,X,X) => X is expressed as `8 - 2 - 4 - 1 = 1 step`\n *\n * Once those observations are understood, the implementation becomes rather simple:\n * count all the molecules in the medicine and subtract the ones that serve as `(,)`\n * using the formula as described above.\n */\n#include <iostream>\n#include <string_view>\n#include <unordered_set>\n\n#include <boost/range/adaptor/reversed.hpp>\n#include <boost/range/irange.hpp>\n\n#include \"input.hpp\"\n\nconstexpr auto NEWLINE = '\\n';\n\nconstexpr auto parse_stats(std::string_view input) {\n\n  auto num_lines = 0;\n\n  for(auto c : input) {\n    num_lines += (c == NEWLINE);\n  }\n\n  return ++num_lines;\n}\n\nconstexpr auto NUM_LINES = parse_stats(puzzle_input);\n\nusing Molecules = std::unordered_set<std::string_view>;\nusing Machine = std::pair<std::string_view, Molecules>;\n\nauto parse(std::string_view input) {\n\n  auto molecules = std::unordered_set<std::string_view>{};\n\n  constexpr auto SPACE = ' ';\n\n  for(const auto i : boost::irange(NUM_LINES-2)) {\n\n    const auto linepos = input.find(NEWLINE);\n\n    auto line = input.substr(0, linepos);\n\n    molecules.insert(line.substr(0, line.find(SPACE)));\n\n    auto output = line.substr((line.rfind(SPACE) + 1), line.npos);\n\n    auto outpos = decltype(output.size()){};\n\n    while(outpos != output.npos) {\n      const auto endpos = output.find_first_of(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", (outpos + 1));\n      molecules.insert(output.substr(outpos, (endpos - outpos)));\n      outpos = endpos;\n    }\n\n    input.remove_prefix(linepos + 1);\n  }\n  // only one newline remains, remove it, and the input is now equal to the medicine\n  input.remove_prefix(1);\n\n  return Machine{input, molecules};\n}\n\nauto min_steps(Machine machine) {\n\n  auto& [medicine, molecules] = machine;\n\n  int sum_molecules = 0,\n      sum_rn_ar = 0,\n      sum_y = 0;\n\n  const auto medsize = medicine.size();\n\n  const auto reversed_range = boost::irange(medsize) | boost::adaptors::reversed;\n\n  // going backwards through the medicine allows us to count the molecules in a single pass\n  for(const auto i : reversed_range) {\n\n    const auto molecule = molecules.find(medicine.substr(i, (medsize - i)));\n\n    if(molecule != molecules.end()) {\n\n      ++sum_molecules;\n\n      const auto value = *molecule;\n\n      sum_rn_ar += (value == \"Rn\" || value == \"Ar\");\n      sum_y += (value == \"Y\");\n\n      medicine.remove_suffix(molecule->size());\n    }\n  }\n\n  const auto result = (sum_molecules - sum_rn_ar - (2 * sum_y) - 1);\n\n  return result;\n}\n\nauto solution(std::string_view input) {\n\n  auto machine = parse(input);\n\n  return min_steps(machine);\n}\n\nint main() {\n\n\tstd::cout << solution(puzzle_input) << std::endl;\n\n}\n", "meta": {"hexsha": "f6febec46868598ded28d95bc682fced42710558", "size": 4850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 19 Part 2/main.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 19 Part 2/main.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 19 Part 2/main.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1242236025, "max_line_length": 118, "alphanum_fraction": 0.6517525773, "num_tokens": 1343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.5397255278363589}}
{"text": "#include \"alpha_shape_area.hpp\"\n#include <boost/lexical_cast.hpp>\n#include <iostream>\n#include <fstream>\n\n#include \"weight_data.hpp\"\n#include \"weight_func_obj_min.hpp\"\n#include \"create_alpha_shape.hpp\"\n#include \"alpha_shape_weighted_area.hpp\"\n\ntypedef float f_t;\ntypedef size_t i_t;\n\nint main(int argc, char* argv[]){\n\n\tfeenableexcept(FE_INVALID | FE_OVERFLOW);\n\n\tif(argc != 3){\n\t\tstd::cout << \"usage: \" << argv[0] << \" <window size> <index/coord/radii file>\" << std::endl;\n\t\treturn 1;\n\t}\n\ti_t window_size = boost::lexical_cast<i_t>(argv[1]);\n\tf_t alpha = 0.0;\n\tconst char* infilename = argv[2];\n\n\tstd::vector<i_t> indices;\n\tstd::vector<f_t> points, radii;\n\ti_t index;\n\tf_t x, y, z, r;\n\tstd::ifstream fs;\n\tfs.open(infilename, std::ifstream::in);\n\twhile(fs >> index >> x >> y >> z >> r){\n\t\tindices.push_back(index);\n\t\tpoints.push_back(x);\n\t\tpoints.push_back(y);\n\t\tpoints.push_back(z);\n\t\tradii.push_back(r);\n\t}\n\tsize_t numPoints = radii.size();\n\tstd::cout << \"number of points: \" << numPoints << std::endl;\n\n\tstd::vector<f_t> areas(numPoints);\n\n\tif(0){\n\t\tbusv::alpha_shape_area<f_t, i_t>(numPoints, alpha, &(points[0]), &(radii[0]), &(areas[0]));\n\t}\n\telse{\n\t\tstd::vector<busv::weight_data<f_t, i_t> > wd(numPoints);\n\t\tfor(i_t i = 0; i<numPoints; ++i){\n\t\t\twd[i].index = indices[i];\n\t\t}\n\t\tbusv::weight_func_obj_min<f_t, i_t> wfo(&(wd[0]), window_size);\n\t\tbusv::AlphaShapeContainer<f_t, i_t> asc = busv::create_alpha_shape(numPoints, alpha,  &(points[0]), &(radii[0]));\n\t\tbusv::alpha_shape_weighted_area<f_t, i_t>(asc, wfo, &(areas[0]));\n\t}\n\n\tfor(i_t i = 0; i<numPoints; ++i){\n\t\tstd::cout << i << \"\\t\" << indices[i] << \"\\t\" << areas[i] << std::endl;\n\t}\n\tstd::cout << std::endl;\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "88554f0226474bc67362d5179367f6afff32cccb", "size": 1688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/alpha_shapes/pointWindow.cpp", "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/pointWindow.cpp", "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/pointWindow.cpp", "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": 25.9692307692, "max_line_length": 115, "alphanum_fraction": 0.6492890995, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.53971498790427}}
{"text": "//! [distance-all]\n#include <algorithm>\n#include <chrono>\n#include <iostream>\n#include <vector>\n#include <limits>\n\n#include <boost/simd/function/aligned_load.hpp>\n#include <boost/simd/function/aligned_store.hpp>\n#include <boost/simd/function/deinterleave.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/sqrt.hpp>\n#include <boost/simd/memory/allocator.hpp>\n#include <boost/simd/pack.hpp>\n\nint main(int argc, char** argv)\n{\n  using namespace std::chrono;\n  namespace bs = boost::simd;\n  typedef float T;\n  using pack_t = bs::pack<T>;\n\n  //! [distance-declare]\n  std::size_t num_points = 1600000;\n  std::vector<T, bs::allocator<T>> X(num_points);\n  std::vector<T, bs::allocator<T>> Y(num_points);\n  std::vector<T, bs::allocator<T>> distance0(num_points);\n  std::vector<T, bs::allocator<T>> distance1(num_points);\n  std::vector<T, bs::allocator<T>> distance2(num_points);\n  std::vector<T, bs::allocator<T>> distance3(num_points);\n\n  std::generate(X.begin(), X.end(),\n                []() { return T(std::rand()) / std::numeric_limits<int>::max(); });\n  std::generate(Y.begin(), Y.end(),\n                []() { return T(std::rand()) / std::numeric_limits<int>::max(); });\n\n  T refX = 0, refY = 0;\n  //! [distance-declare]\n\n  auto t0 = high_resolution_clock::now();\n  //! [distance-scalar]\n  for (int i = 0; i < num_points; ++i) {\n    auto x       = refX - X[i];\n    auto y       = refY - Y[i];\n    distance0[i] = std::sqrt(x * x + y * y);\n  }\n  //! [distance-scalar]\n  auto t1 = high_resolution_clock::now();\n  std::cout << \" time scalar \" << duration_cast<microseconds>(t1 - t0).count() << std::endl;\n\n  //! [distance-time]\n  t0 = high_resolution_clock::now();\n  //! [distance-calc]\n  pack_t vrefX = pack_t(refX);\n  pack_t vrefY = pack_t(refY);\n\n  for (int i = 0; i < num_points; i += pack_t::static_size) {\n    pack_t vX  = bs::aligned_load<pack_t>(&X[i]);\n    pack_t vY  = bs::aligned_load<pack_t>(&Y[i]);\n    pack_t res = bs::sqrt(bs::sqr(vrefX - vX) + bs::sqr(vrefY - vY));\n    bs::aligned_store(res, &distance1[i]);\n  }\n  //! [distance-calc]\n  t1 = high_resolution_clock::now();\n  std::cout << \" time SIMD \" << duration_cast<microseconds>(t1 - t0).count() << std::endl;\n  //! [distance-time]\n\n  //! [distance-interleave]\n  // The input vector contains interleaved X and Y data, i.e. x0, y0, x1, y1,\n  // ..., xn, yn\n  std::vector<T, bs::allocator<T>> interleaved_data(num_points * 2);\n  for (int i = 0; i < num_points * 2; i += 2) {\n    interleaved_data[i]     = X[i / 2];\n    interleaved_data[i + 1] = Y[i / 2];\n  }\n  t0 = high_resolution_clock::now();\n  for (int i = 0; i < num_points * 2; i += pack_t::static_size * 2) {\n    pack_t v0 = bs::aligned_load<pack_t>(&interleaved_data[i]);\n    pack_t v1 = bs::aligned_load<pack_t>(&interleaved_data[i + pack_t::static_size]);\n\n    auto V     = bs::deinterleave(v0, v1);\n    pack_t res = bs::sqrt(bs::sqr(vrefX - V[0]) + bs::sqr(vrefY - V[1]));\n    bs::aligned_store(res, &distance2[i / 2]);\n  }\n  t1 = high_resolution_clock::now();\n  //! [distance-interleave]\n  std::cout << \" time SIMD de-interleave \" << duration_cast<microseconds>(t1 - t0).count()\n            << std::endl;\n}\n//! [distance-all]\n", "meta": {"hexsha": "d250be8b300cab015923e0dcd3836d3611870ff3", "size": 3173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/distance.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "doc/examples/distance.cpp", "max_issues_repo_name": "dendisuhubdy/boost.simd", "max_issues_repo_head_hexsha": "7630b1c1ffbd0300c100885b89ff78c2d579a24c", "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/distance.cpp", "max_forks_repo_name": "dendisuhubdy/boost.simd", "max_forks_repo_head_hexsha": "7630b1c1ffbd0300c100885b89ff78c2d579a24c", "max_forks_repo_licenses": ["BSL-1.0"], "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": 34.8681318681, "max_line_length": 92, "alphanum_fraction": 0.6205483769, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5397149807316937}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  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 http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/static_assert.hpp>\n#include \"test.hpp\"\n\nusing namespace boost::multiprecision;\n\nint main()\n{\n   BOOST_CHECK_EQUAL(std::numeric_limits<cpp_bin_float_single>::digits10, 6);\n   BOOST_CHECK_EQUAL(std::numeric_limits<cpp_bin_float_single>::max_digits10, 9);\n\n   BOOST_CHECK_EQUAL(std::numeric_limits<cpp_bin_float_double>::digits10, 15);\n   BOOST_CHECK_EQUAL(std::numeric_limits<cpp_bin_float_double>::max_digits10, 17);\n\n   BOOST_CHECK_EQUAL(std::numeric_limits<cpp_bin_float_double_extended>::digits10, 18);\n   BOOST_CHECK_EQUAL(std::numeric_limits<cpp_bin_float_double_extended>::max_digits10, 21);\n\n   BOOST_CHECK_EQUAL(std::numeric_limits<cpp_bin_float_quad>::digits10, 33);\n   BOOST_CHECK_EQUAL(std::numeric_limits<cpp_bin_float_quad>::max_digits10, 36);\n\n   BOOST_STATIC_ASSERT(std::numeric_limits<cpp_bin_float_single>::digits10 == 6);\n   BOOST_STATIC_ASSERT(std::numeric_limits<cpp_bin_float_single>::max_digits10 == 9);\n\n   BOOST_STATIC_ASSERT(std::numeric_limits<cpp_bin_float_double>::digits10 == 15);\n   BOOST_STATIC_ASSERT(std::numeric_limits<cpp_bin_float_double>::max_digits10 == 17);\n\n   BOOST_STATIC_ASSERT(std::numeric_limits<cpp_bin_float_double_extended>::digits10 == 18);\n   BOOST_STATIC_ASSERT(std::numeric_limits<cpp_bin_float_double_extended>::max_digits10 == 21);\n\n   BOOST_STATIC_ASSERT(std::numeric_limits<cpp_bin_float_quad>::digits10 == 33);\n   BOOST_STATIC_ASSERT(std::numeric_limits<cpp_bin_float_quad>::max_digits10 == 36);\n\n   return boost::report_errors();\n}\n", "meta": {"hexsha": "13891a32385dd9d805ec34ea895f00d83b629bc5", "size": 1824, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/test/git_issue_248.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/multiprecision/test/git_issue_248.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/multiprecision/test/git_issue_248.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": 45.6, "max_line_length": 95, "alphanum_fraction": 0.7598684211, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5397149758942732}}
{"text": "#ifndef BOOSTGRAPH\n#define BOOSTGRAPH\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/edge_connectivity.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <boost/graph/clustering_coefficient.hpp>\n#include <boost/graph/dominator_tree.hpp>\n\n#include <iostream>\n\nusing namespace std;\nusing namespace boost;\n\ntypedef int v_index;\ntypedef long e_index;\n\n// This struct is the output of the edge connectivity Boost algorithm.\ntypedef struct {\n    v_index ec; // The edge connectivity\n    vector<v_index> edges; // The edges in a minimum cut, stored as a list of\n                       // nodes. For instance, if the minimum cut is\n                       // {(1,2),(3,4)}, the output vector will be (1,2,3,4).\n} result_ec;\n\n\n// This struct is the output of the clustering coefficient Boost algorithm.\ntypedef struct {\n    double average_clustering_coefficient; // The average clustering coefficient\n    vector<double> clust_of_v;             // The clustering coefficient of each node.\n} result_cc;\n\ntemplate <class OutEdgeListS, // How neighbors are stored\n          class VertexListS,  // How vertices are stored\n          class DirectedS,    // The kind of graph (undirectedS, directedS, or bidirectionalS)\n          class EdgeListS>    // How the list of edges is stored\nclass BoostGraph\n/*\n * This generic class wraps a Boost graph, in order to make it Cython-friendly.\n *\n * In particular, it allows to \"keep together\" the Boost graph and the vector\n * *vertices: these two variables are generic, and Cython is not able to deal\n * with them properly, since it does not support generic classes.\n *\n * Vertices are numbers from 0 to n-1, where n is the total number of vertices:\n * this class takes care of the relation between number i and the corresponding\n * Boost vertex descriptor (which might be any object, depending on the value of\n * VertexListS). In particular, (*vertices)[i] contains the Boost vertex\n * corresponding to number i, while to transform a Boost vertex v into a number\n * we use vertex properties, and the syntax is (*graph)[v].\n*/\n{\n    typedef typename boost::adjacency_list<OutEdgeListS, VertexListS, DirectedS,\n    property<vertex_index_t, v_index>, no_property, no_property, EdgeListS> adjacency_list;\n    typedef typename boost::graph_traits<adjacency_list>::vertex_descriptor vertex_descriptor;\n    typedef typename boost::graph_traits<adjacency_list>::edge_descriptor edge_descriptor;\n    typedef typename std::vector<edge_descriptor> edge_container;\n    typedef typename boost::property_map<adjacency_list, boost::vertex_index_t>::type vertex_to_int_map;\n\npublic:\n    adjacency_list *graph;\n    vector<vertex_descriptor> *vertices;\n    vertex_to_int_map index;\n\n    BoostGraph() {\n        graph = new adjacency_list();\n        vertices = new vector<vertex_descriptor>();\n    }\n\n    ~BoostGraph() {\n        delete graph;\n        delete vertices;\n    }\n\n    v_index num_verts() {\n        return num_vertices(*graph);\n    }\n\n    e_index num_edges() {\n        return boost::num_edges(*graph);\n    }\n\n    void add_vertex() {\n        (*vertices).push_back(boost::add_vertex((*vertices).size(), *graph));\n    }\n\n    void add_edge(v_index u, v_index v) {\n        boost::add_edge((*vertices)[u], (*vertices)[v], *graph);\n    }\n\n    result_ec edge_connectivity() {\n        result_ec to_return;\n        edge_container disconnecting_set;\n        back_insert_iterator<edge_container> inserter(disconnecting_set);\n        to_return.ec = boost::edge_connectivity(*graph, inserter);\n\n        for (v_index i = 0; i < disconnecting_set.size(); i++) {\n            edge_descriptor edge = disconnecting_set[i];\n            to_return.edges.push_back(index[boost::source(edge, *graph)]);\n            to_return.edges.push_back(index[boost::target(edge, *graph)]);\n        }\n        return to_return;\n    }\n\n    double clustering_coeff(v_index v) {\n        return clustering_coefficient(*graph, (*vertices)[v]);\n    }\n\n    result_cc clustering_coeff_all() {\n        result_cc to_return;\n        to_return.clust_of_v.resize(num_verts());\n        to_return.average_clustering_coefficient = all_clustering_coefficients(*graph,\n                        make_iterator_property_map(to_return.clust_of_v.begin(), index));\n        return to_return;\n    }\n\n    vector<v_index> dominator_tree(v_index v) {\n        vector<v_index> fathers(num_verts());\n        vector<vertex_descriptor> fathers_descr(num_verts(),\n                    boost::graph_traits<adjacency_list>::null_vertex());\n\n        lengauer_tarjan_dominator_tree(*graph, (*vertices)[v],\n                                       make_iterator_property_map(\n                                           fathers_descr.begin(), index));\n\n        for (v_index i = 0; i < num_verts(); i++) {\n            vertex_descriptor v = fathers_descr[i];\n            if (v == boost::graph_traits<adjacency_list>::null_vertex()) {\n                fathers[i] = -1;\n            } else {\n                fathers[i] = index[v];\n            }\n        }\n        return fathers;\n    }\n};\n\n\n\n#endif // BOOSTGRAPH\n", "meta": {"hexsha": "cf895eb42b86edeafa9aa721bf68f0fd30d66006", "size": 5064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sage/graphs/base/boost_interface.cpp", "max_stars_repo_name": "switzel/sage", "max_stars_repo_head_hexsha": "7eb8510dacf61b691664cd8f1d2e75e5d473e5a0", "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/sage/graphs/base/boost_interface.cpp", "max_issues_repo_name": "switzel/sage", "max_issues_repo_head_hexsha": "7eb8510dacf61b691664cd8f1d2e75e5d473e5a0", "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/graphs/base/boost_interface.cpp", "max_forks_repo_name": "switzel/sage", "max_forks_repo_head_hexsha": "7eb8510dacf61b691664cd8f1d2e75e5d473e5a0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-24T12:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-24T12:20:37.000Z", "avg_line_length": 36.1714285714, "max_line_length": 104, "alphanum_fraction": 0.6674565561, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5397149733920088}}
{"text": "// Copyright Andr\u00e1s Vukics 2006\u20132020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#include \"BlitzArraySliceIterator.h\"\n\n#include \"Mode_.h\"\n\n#include \"LazyDensityOperator.tcc\"\n#include \"StateVector.h\"\n\n#include <boost/bind.hpp>\n\n#define BOOST_TEST_MODULE LazyDensityOperator test\n#include <boost/test/unit_test.hpp>\n\n\nusing mathutils::fcmp; using mathutils::sqr; using mathutils::sqrAbs; \n\nusing quantumdata::partialTrace;\n\nconst double eps=1e-12;\n\nconst tmptools::Vector<0> v0=tmptools::Vector<0>();\nconst tmptools::Vector<1> v1=tmptools::Vector<1>();\n\nconst dcomp alpha(2,3), beta(-1,2), gammaa(2,-2);\n\nconst mode::StateVector c23(mode::coherent(alpha,78)), c12(mode::coherent(beta,30)), c22(mode::coherent(gammaa,48)), \n  d23(mode::coherent(alpha,78)), d12(mode::coherent(beta,78)), d22(mode::coherent(gammaa,78));\n\nboost::function<double(const mode::LazyDensityOperator&)> photonNumber(static_cast<double(*)(const mode::LazyDensityOperator&)>(mode::photonNumber));\n\ntemplate<int I>\ndouble \nphotonNumberRecurse(const quantumdata::LazyDensityOperator<2>& m)\n{\n  return partialTrace(m,photonNumber,tmptools::Vector<I>(),0.);\n}\n\n\nconst mode::DensityOperatorLow\ndensityOperator(const mode::LazyDensityOperator& m)\n{\n  size_t dim=m.getDimension();\n  mode::DensityOperatorLow res(dim,dim);\n  for (int i=0; i<dim; i++) for (int j=0; j<dim; j++) res(i,j)=m(i,j);\n  return res;    \n}\n\n\nBOOST_AUTO_TEST_CASE( RANK_TWO )\n{\n  quantumdata::StateVector<2> psi(c23*c12);\n\n  BOOST_CHECK(!fcmp(photonNumberRecurse<0>(psi),13.,eps));\n  BOOST_CHECK(!fcmp(photonNumberRecurse<1>(psi), 5.,eps));\n\n  quantumdata::DensityOperator<2> rho(psi);\n\n  BOOST_CHECK(!fcmp(photonNumberRecurse<0>(rho),13.,eps));\n  BOOST_CHECK(!fcmp(photonNumberRecurse<1>(rho), 5.,eps));\n\n  dcomp alpha1(alpha), beta1(beta), alpha2(beta), beta2(gammaa);\n\n  quantumdata::StateVector<2> psii(d23*d12-d12*d22); double norm=psii.renorm();\n\n  BOOST_CHECK(!fcmp((sqrAbs(beta1)+sqrAbs(beta2)-2.*std::real(braket(d23,d12)*braket(d12,d22)*conj(beta1)*beta2))/sqr(norm),\n                    photonNumberRecurse<1>(psii),\n                    eps)\n              );\n\n\n  // The most stringent test for the whole of a partial-trace density operator:\n\n  mode::DensityOperator res(-braket(d23,d12)/sqr(norm)*dyad(d22,d12));\n\n  {\n    linalg::CMatrix tempView(res.matrixView());\n    linalg::calculateTwoTimesRealPartOfSelf(tempView);\n  }\n\n  res()+=(d12.dyad()+d22.dyad())/sqr(norm);\n\n  BOOST_CHECK(max(blitzplusplus::sqrAbs(partialTrace(psii,densityOperator,tmptools::Vector<1>(),mode::DensityOperatorLow())-res()))<sqr(eps));\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE( RANK_THREE_RECURSIVE )\n{\n  quantumdata::StateVector<3> psi(c23*c12*c22);\n\n  BOOST_CHECK(!fcmp(partialTrace(psi,photonNumberRecurse<0>,tmptools::Vector<0,1>(),0.),13.,eps));\n  BOOST_CHECK(!fcmp(partialTrace(psi,photonNumberRecurse<1>,tmptools::Vector<0,1>(),0.), 5.,eps));\n  BOOST_CHECK(!fcmp(partialTrace(psi,photonNumberRecurse<0>,tmptools::Vector<1,2>(),0.), 5.,eps));\n  BOOST_CHECK(!fcmp(partialTrace(psi,photonNumberRecurse<1>,tmptools::Vector<1,2>(),0.), 8.,eps));\n  BOOST_CHECK(!fcmp(partialTrace(psi,photonNumberRecurse<0>,tmptools::Vector<2,0>(),0.), 8.,eps));\n  BOOST_CHECK(!fcmp(partialTrace(psi,photonNumberRecurse<1>,tmptools::Vector<2,0>(),0.),13.,eps));\n\n  // BOOST_CHECK(!fcmp(partialTrace(psi,photonNumberRecurse<0>,v1,0.), 5.,eps));\n  // BOOST_CHECK(!fcmp(partialTrace(psi,photonNumberRecurse,tmptools::Vector<2,0>(),0.), 5.,eps));\n\n}\n\n\n\nconst mode::StateVector e0(mode::fock(2,3)), e1(mode::fock(3,7)), e2(mode::fock(0,1));\n\n\nint specialChecker(const quantumdata::LazyDensityOperator<3>& m, size_t i1, size_t i2, size_t i3)\n{\n  BOOST_CHECK(all(m.getDimensions()==ExtTiny<3>(i1,i2,i3)));\n  partialTrace(m,photonNumberRecurse<0>,tmptools::Vector<1,2>(),0.);\n  // This is only for checking whether the special implementations are also recursive.\n  return 0;\n}\n\n\nBOOST_AUTO_TEST_CASE( THE_SPECIAL_CASE )\n{\n  quantumdata::StateVector<3> psi(e0*e1*e2);\n  partialTrace(psi,bind(specialChecker,_1,3,7,1),tmptools::Vector<0,1,2>(),0); \n  partialTrace(psi,bind(specialChecker,_1,3,1,7),tmptools::Vector<0,2,1>(),0); \n\n  quantumdata::DensityOperator<3> rho(psi);\n  partialTrace(psi,bind(specialChecker,_1,3,7,1),tmptools::Vector<0,1,2>(),0); \n  partialTrace(psi,bind(specialChecker,_1,3,1,7),tmptools::Vector<0,2,1>(),0); \n\n}\n", "meta": {"hexsha": "f1d2eac36ccb4bc709a4bf41cac84e8f71a65b33", "size": 4373, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CPPQEDcore/testsuite/LazyDensityOperator.cc", "max_stars_repo_name": "bartoszek/cppqed", "max_stars_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T14:00:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T15:12:11.000Z", "max_issues_repo_path": "CPPQEDcore/testsuite/LazyDensityOperator.cc", "max_issues_repo_name": "bartoszek/cppqed", "max_issues_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-04-14T11:18:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T20:11:23.000Z", "max_forks_repo_path": "CPPQEDcore/testsuite/LazyDensityOperator.cc", "max_forks_repo_name": "bartoszek/cppqed", "max_forks_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T10:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T18:29:01.000Z", "avg_line_length": 33.8992248062, "max_line_length": 149, "alphanum_fraction": 0.7143837183, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5397149708897441}}
{"text": "#include <Eigen/Core>\n#include <optional>\n\n#include <citlali/core/timestream/ptc/sensitivity.h>\n\nnamespace internal {\n\nstd::tuple<Eigen::Index, Eigen::Index, double> stat(Eigen::Index scanlength, double fsmp) {\n    // make an even number of data points by rounding-down\n    Eigen::Index npts = scanlength;\n    if (npts % 2 == 1)\n        npts--;\n    // prepare containers in frequency domain\n    Eigen::Index nfreqs = npts / 2 + 1; // number of one sided freq bins\n    double dfreq = fsmp / npts;\n\n    return {npts, nfreqs, dfreq};\n}\n\nEigen::VectorXd freq(Eigen::Index npts, Eigen::Index nfreqs, double dfreq) {\n    return dfreq * Eigen::VectorXd::LinSpaced(nfreqs, 0, npts / 2);\n}\n\n} // namespace internal\n", "meta": {"hexsha": "f5fe07c26df2f1c2599e096325d678137583f433", "size": 706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/citlali/core/sensitivity.cpp", "max_stars_repo_name": "toltec-astro/citlali", "max_stars_repo_head_hexsha": "f4f14962be1c50b7f6ecddb0223db0f37c9b02ef", "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/citlali/core/sensitivity.cpp", "max_issues_repo_name": "toltec-astro/citlali", "max_issues_repo_head_hexsha": "f4f14962be1c50b7f6ecddb0223db0f37c9b02ef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-11-06T16:30:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T16:24:44.000Z", "max_forks_repo_path": "src/citlali/core/sensitivity.cpp", "max_forks_repo_name": "toltec-astro/citlali", "max_forks_repo_head_hexsha": "f4f14962be1c50b7f6ecddb0223db0f37c9b02ef", "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.24, "max_line_length": 91, "alphanum_fraction": 0.6756373938, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5396356584596363}}
{"text": "/*\n   bern_rat.cpp:  multi-modular algorithm for computing Bernoulli numbers\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#include <gmp.h>\n#include <NTL/ZZ.h>\n#include <cmath>\n#include <vector>\n#include <set>\n#include \"bern_modp_util.h\"\n#include \"bern_modp.h\"\n#include \"bern_rat.h\"\n\n#ifdef USE_THREADS\n#include <pthread.h>\n#endif\n\n\nusing namespace std;\nusing namespace NTL;\n\n\nnamespace bernmm {\n\n\n/*\n   Computes the denominator of B_k using Clausen/von Staudt.\n*/\nvoid bern_den(mpz_t res, long k, const PrimeTable& table)\n{\n   mpz_set_ui(res, 1);\n\n   // loop through factors of k\n   for (long f = 1; f*f <= k; f++)\n   {\n      // if f divides k....\n      if (k % f == 0)\n      {\n         // ... then both f + 1 and k/f + 1 are candidates for primes\n         // dividing the denominator of B_k\n         if (table.is_prime(f + 1))\n            mpz_mul_ui(res, res, f + 1);\n\n         if (f*f != k)\n            if (table.is_prime(k/f + 1))\n               mpz_mul_ui(res, res, k/f + 1);\n      }\n   }\n}\n\n\n// width of interval for each block\n#define BLOCK_SIZE 1000\n\n\n/*\n   Represents that B_k is congruent to _residue_ modulo _modulus_.\n*/\nstruct Item\n{\n   mpz_t modulus;\n   mpz_t residue;\n\n   Item()\n   {\n      mpz_init(modulus);\n      mpz_init(residue);\n   }\n\n   ~Item()\n   {\n      mpz_clear(residue);\n      mpz_clear(modulus);\n   }\n};\n\n\n/*\n   Items get sorted by modulus.\n*/\nstruct Item_cmp\n{\n   bool operator()(const Item* x, const Item* y)\n   {\n      return mpz_cmp(x->modulus, y->modulus) < 0;\n   }\n};\n\n\n/*\n   Returns new Item that combines information from op1 and op2 via CRT.\n*/\nItem* CRT(Item* op1, Item* op2)\n{\n   Item* res = new Item;\n\n   // let n1, n2 be the moduli, and r1, r2 be the residues\n\n   // res->modulus = t, where t = 0 mod n1, t = 1 mod n2\n   mpz_invert(res->modulus, op1->modulus, op2->modulus);\n   mpz_mul(res->modulus, res->modulus, op1->modulus);\n\n   // res->residue = r2 - r1\n   mpz_sub(res->residue, op2->residue, op1->residue);\n   // res->residue = t * (r2 - r1)\n   mpz_mul(res->residue, res->residue, res->modulus);\n   // res->residue = r1 + t * (r2 - r1)\n   mpz_add(res->residue, res->residue, op1->residue);\n   // res->modulus = n1 * n2\n   mpz_mul(res->modulus, op1->modulus, op2->modulus);\n   // res->residue = r1 mod n1, r2 = mod n2\n   mpz_mod(res->residue, res->residue, res->modulus);\n\n   return res;\n}\n\n\nstruct State\n{\n   long k;\n   long bound;   // only use primes less than this bound\n   const PrimeTable* table;\n\n   // index of block that should be processed next\n   long next;\n\n   std::set<Item*, Item_cmp> items;\n#ifdef USE_THREADS\n   pthread_mutex_t lock;\n#endif\n\n   State(long k, long bound, const PrimeTable& table)\n   {\n      this->k = k;\n      this->bound = bound;\n      this->next = 0;\n      this->table = &table;\n#ifdef USE_THREADS\n      pthread_mutex_init(&lock, NULL);\n#endif\n   }\n\n   ~State()\n   {\n#ifdef USE_THREADS\n      pthread_mutex_destroy(&lock);\n#endif\n   }\n};\n\n\nvoid* worker(void* arg)\n{\n   State& state = *((State*) arg);\n   long k = state.k;\n\n#ifdef USE_THREADS\n   pthread_mutex_lock(&state.lock);\n#endif\n\n   while (1)\n   {\n      if (state.next * BLOCK_SIZE < state.bound)\n      {\n         // need to generate more modular data\n\n         long next = state.next++;\n#ifdef USE_THREADS\n         pthread_mutex_unlock(&state.lock);\n#endif\n\n         Item* item = new Item;\n\n         mpz_set_ui(item->modulus, 1);\n         mpz_set_ui(item->residue, 0);\n\n         for (long p = max(5, state.table->next_prime(next * BLOCK_SIZE));\n              p < state.bound && p < (next+1) * BLOCK_SIZE;\n              p = state.table->next_prime(p))\n         {\n            if (k % (p-1) == 0)\n               continue;\n\n            // compute B_k mod p\n            long b = bern_modp(p, k);\n\n            // CRT into running total\n            long x = MulMod(SubMod(b, mpz_fdiv_ui(item->residue, p), p),\n                            InvMod(mpz_fdiv_ui(item->modulus, p), p), p);\n            mpz_addmul_ui(item->residue, item->modulus, x);\n            mpz_mul_ui(item->modulus, item->modulus, p);\n         }\n\n#ifdef USE_THREADS\n         pthread_mutex_lock(&state.lock);\n#endif\n         state.items.insert(item);\n      }\n      else\n      {\n         // all modular data has been generated\n\n         if (state.items.size() <= 1)\n         {\n            // no more CRTs for this thread to perform\n#ifdef USE_THREADS\n            pthread_mutex_unlock(&state.lock);\n#endif\n            return NULL;\n         }\n\n         // CRT two smallest items together\n         Item* item1 = *(state.items.begin());\n         state.items.erase(state.items.begin());\n         Item* item2 = *(state.items.begin());\n         state.items.erase(state.items.begin());\n#ifdef USE_THREADS\n         pthread_mutex_unlock(&state.lock);\n#endif\n\n         Item* item3 = CRT(item1, item2);\n         delete item1;\n         delete item2;\n\n#ifdef USE_THREADS\n         pthread_mutex_lock(&state.lock);\n#endif\n         state.items.insert(item3);\n      }\n   }\n}\n\n\nvoid bern_rat(mpq_t res, long k, int num_threads)\n{\n   // special cases\n\n   if (k == 0)\n   {\n      // B_0 = 1\n      mpq_set_ui(res, 1, 1);\n      return;\n   }\n\n   if (k == 1)\n   {\n      // B_1 = -1/2\n      mpq_set_si(res, -1, 2);\n      return;\n   }\n\n   if (k == 2)\n   {\n      // B_2 = 1/6\n      mpq_set_si(res, 1, 6);\n      return;\n   }\n\n   if (k & 1)\n   {\n      // B_k = 0 if k is odd\n      mpq_set_ui(res, 0, 1);\n      return;\n   }\n\n   if (num_threads <= 0)\n      num_threads = 1;\n\n   mpz_t num, den;\n   mpz_init(num);\n   mpz_init(den);\n\n   const double log2 =    0.69314718055994528622676;\n   const double invlog2 = 1.44269504088896340735992;   // = 1/log(2)\n\n   // compute preliminary prime bound and build prime table\n   long bound1 = (long) max(37.0, ceil((k + 0.5) * log(k) * invlog2));\n   PrimeTable table(bound1);\n\n   // compute denominator of B_k\n   bern_den(den, k, table);\n\n   // compute number of bits we need to resolve the numerator\n   long bits = (long) ceil((k + 0.5) * log(k) * invlog2 - 4.094 * k + 2.470\n                                      + log(mpz_get_d(den)) * invlog2);\n\n   // compute tighter prime bound\n   // (note: we can safely get away with double-precision here. It would\n   // only start being insufficient around k = 10^13 or so, which is totally\n   // impractical at present.)\n   double prod = 1.0;\n   long prod_bits = 0;\n   long p;\n   for (p = 5; prod_bits < bits + 1; p = table.next_prime(p))\n   {\n      if (p >= NTL_SP_BOUND)\n         abort();   // !!!!! not sure what else we can do here...\n      if (k % (p-1) != 0)\n         prod *= (double) p;\n      int exp;\n      prod = frexp(prod, &exp);\n      prod_bits += exp;\n   }\n   long bound2 = p;\n\n   State state(k, bound2, table);\n\n#ifdef USE_THREADS\n   vector<pthread_t> threads(num_threads - 1);\n\n   pthread_attr_t attr;\n   pthread_attr_init(&attr);\n#ifdef THREAD_STACK_SIZE\n   pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE * 1024);\n#endif\n\n   // spawn worker threads to process blocks\n   for (long i = 0; i < num_threads - 1; i++)\n      pthread_create(&threads[i], &attr, worker, &state);\n#endif\n\n   worker(&state);    // make this thread a worker too\n\n#ifdef USE_THREADS\n   for (long i = 0; i < num_threads - 1; i++)\n      pthread_join(threads[i], NULL);\n#endif\n\n   pthread_attr_destroy (&attr);\n\n   // reconstruct B_k as a rational number\n   Item* item = *(state.items.begin());\n   mpz_mul(num, item->residue, den);\n   mpz_mod(num, num, item->modulus);\n\n   if (k % 4 == 0)\n   {\n      // B_k is negative\n      mpz_sub(num, item->modulus, num);\n      mpz_neg(num, num);\n   }\n\n   delete item;\n\n   mpz_swap(num, mpq_numref(res));\n   mpz_swap(den, mpq_denref(res));\n\n   mpz_clear(num);\n   mpz_clear(den);\n}\n\n\n\n};    // end namespace\n\n\n// end of file ================================================================\n", "meta": {"hexsha": "963cb173524e35950de4c54b3206c72b62e1d01c", "size": 7928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sage/rings/bernmm/bern_rat.cpp", "max_stars_repo_name": "bopopescu/sage", "max_stars_repo_head_hexsha": "2d495be78e0bdc7a0a635454290b27bb4f5f70f0", "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_rat.cpp", "max_issues_repo_name": "Ivo-Maffei/sage", "max_issues_repo_head_hexsha": "467fbc70a08b552b3de33d9065204ee9cbfb02c7", "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_rat.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": 21.7205479452, "max_line_length": 79, "alphanum_fraction": 0.575554995, "num_tokens": 2282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5396356560786829}}
{"text": "\n#include <iostream>\n#include <autodiff/forward/real.hpp>\n#include <autodiff/forward/real/eigen.hpp>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\n#include \"object.hpp\"\n\n// using namespace autodiff;\nusing namespace Eigen;\n\nclass Box : public Object {\n    public:\n        Box();\n        autodiff::real U(const autodiff::ArrayXreal& pos);  // potential energy function\n    private:\n\n    protected:\n        double length = 1;\n        double width = 1;\n        double height = 1;\n\n};\n", "meta": {"hexsha": "7c6487a0f439dd1504bcace2a2dd93a1aaae4f85", "size": 480, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/dynamics/box.hpp", "max_stars_repo_name": "brysonjones/dynamics_sim", "max_stars_repo_head_hexsha": "201bdf0a93d00addc585ffa47f280cffacebb9b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dynamics/box.hpp", "max_issues_repo_name": "brysonjones/dynamics_sim", "max_issues_repo_head_hexsha": "201bdf0a93d00addc585ffa47f280cffacebb9b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dynamics/box.hpp", "max_forks_repo_name": "brysonjones/dynamics_sim", "max_forks_repo_head_hexsha": "201bdf0a93d00addc585ffa47f280cffacebb9b3", "max_forks_repo_licenses": ["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.2, "max_line_length": 88, "alphanum_fraction": 0.6520833333, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5396210333323208}}
{"text": "#include <iostream>\n#include <cmath>\n#include <numeric>\n#include <fstream>\n#include <algorithm>\n#include <iomanip>\n\n#include \"field2d.h\"\n#include \"weno.h\"\n#include \"rk.h\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/math/constants/constants.hpp>\nnamespace math = boost::math::constants;\nusing namespace boost::numeric;\n\nauto\npacman_factory ( double r , double alpha , double value=1.0 ) {\n  return [=]( double x , double y ) {\n    if ( ( x*x + y*y < r*r ) && ( (x<0.0) || (std::abs(y)>alpha*x) ) ) {\n      return value;\n    }\n    return 0.0;\n  };\n}\n#define SQ(X) ((X)*(X))\nauto\ngauss_factory ( double X0 , double Y0 , double tx , double ty ) {\n  return [=]( double x , double y ) {\n    return std::exp(-SQ(x-X0)/tx - SQ(y-Y0)/ty);\n  };\n}\n#undef SQ\n\nint\nmain(int,char**)\n{\n  std::size_t N = 100;\n  double xmax = 5.0;\n  std::size_t Nx=N,Ny=N;\n  field2d<double> f(boost::extents[Nx][Ny]);\n  f.range.x_min = -xmax; f.range.x_max = xmax;\n  f.range.y_min = -xmax; f.range.y_max = xmax;\n  f.compute_steps();\n\n  field2d<double> g(boost::extents[Nx][Ny]);\n  g.range = f.range;\n  g.steps = f.steps;\n\n  auto pacman = pacman_factory(1.0,0.5);\n  auto gauss = gauss_factory(0.0,1.0,0.75,0.25);\n  for ( auto i=0u ; i<f.size(0) ; ++i ) {\n    for ( auto j=0u ; j<f.size(1) ; ++j ) {\n       //f[i][j] = gauss(f.x(i),f.y(j));\n       f[i][j] = pacman(f.x(i),f.y(j));\n      // f[i][j] = std::cos(2.*math::pi<double>()*f.x(i)/xmax)*std::sin(2.*math::pi<double>()*f.y(j)/xmax);\n      //f[i][j] = std::cos(2.*math::pi<double>()*f.x(i)/xmax);\n\n       g[i][j] = f[i][j];\n    }\n  }\n  ublas::vector<double> E(2,0); E[0] = 0.1; E[1] = 0.1;\n\n  //double dt= 1.3*f.steps.dx/(std::abs(E[0])+std::abs(E[1])+2.0*xmax);\n  double dt= 1.3*f.steps.dx/(std::abs(E[0])+std::abs(E[1]));\n  double Tf= 1.0; //.5*math::pi<double>();\n\n\n  auto save_f = [](field2d<double> const& f,std::string filename) {\n    std::ofstream of(filename);\n    of << f << std::endl;\n    of.close();\n  };\n\n  save_f(f,\"finit.dat\");\n  save_f(g,\"ginit.dat\");\n\n\n\n  auto Lij_f = [&](double tn , const field2d<double> & u , std::size_t i, std::size_t j){\n    return - (weno2d::weno_x( E[0]+u.y(j) ,u,i,j) + weno2d::weno_y(  E[1]-u.x(i) ,u,i,j));\n  };\n  auto Lij_g = [&](double tn , const field2d<double> & u , std::size_t i , std::size_t j){\n    return - ( weno2d::weno_x( E[0]*std::cos(tn) - E[1]*std::sin(tn) ,u,i,j)\n             + weno2d::weno_y( E[0]*std::sin(tn) + E[1]*std::cos(tn) ,u,i,j) );\n  };\n\n  std::cout << \"dt: \"<< dt << \"\\tNiter: \" << std::floor(Tf/dt) << \"\\n\";\n  double current_time = 0.0;\n  std::size_t i_iter = 0;\n  while ( current_time < Tf ) {\n    std::cout << \"[\" << std::setw(10) << current_time << \"] \\r\" << std::flush;\n\n    f = rk33( Lij_f , current_time , f , dt );\n\n    g = rk33( Lij_g , current_time , g , dt );\n\n    ++i_iter;\n    current_time += dt;\n    if ( current_time+dt > Tf ) { dt = Tf - current_time; }\n  }\n  std::cout << \"[\" << std::setw(10) << current_time << \"]\" << std::endl;\n\n  save_f(f,\"fend.dat\");\n  save_f(g,\"gend.dat\");\n\n  f = rotation(g,current_time);\n\n  save_f(f,\"ffend.dat\");\n\n  return 0;\n}\n", "meta": {"hexsha": "47e58b2f2c97899e59d8049d25637a053b3cb47b", "size": 3078, "ext": "cc", "lang": "C++", "max_stars_repo_path": "misc/test_trp/2d/filtre.cc", "max_stars_repo_name": "kivvix/draft", "max_stars_repo_head_hexsha": "33b605be27e556df061f856be8e84e5b3f49a219", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "misc/test_trp/2d/filtre.cc", "max_issues_repo_name": "kivvix/draft", "max_issues_repo_head_hexsha": "33b605be27e556df061f856be8e84e5b3f49a219", "max_issues_repo_licenses": ["MIT"], "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/test_trp/2d/filtre.cc", "max_forks_repo_name": "kivvix/draft", "max_forks_repo_head_hexsha": "33b605be27e556df061f856be8e84e5b3f49a219", "max_forks_repo_licenses": ["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.2389380531, "max_line_length": 107, "alphanum_fraction": 0.5545808967, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5396158319619574}}
{"text": "#include \"../include/ScaramuzzaCamera.h\"\n#include \"../include/Utils.h\"\n\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <cmath>\n#include <cstdio>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/SVD>\n#include <iomanip>\n#include <iostream>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\nEigen::VectorXd polyfit(Eigen::VectorXd &xVec, Eigen::VectorXd &yVec,\n                        int poly_order)\n{\n  assert(poly_order > 0);\n  assert(xVec.size() > poly_order);\n  assert(xVec.size() == yVec.size());\n\n  Eigen::MatrixXd A(xVec.size(), poly_order + 1);\n  Eigen::VectorXd B(xVec.size());\n\n  for (int i = 0; i < xVec.size(); ++i)\n  {\n    const double x = xVec(i);\n    const double y = yVec(i);\n\n    double x_pow_k = 1.0;\n\n    for (int k = 0; k <= poly_order; ++k)\n    {\n      A(i, k) = x_pow_k;\n      x_pow_k *= x;\n    }\n\n    B(i) = y;\n  }\n\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(\n      A, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  Eigen::VectorXd x = svd.solve(B);\n\n  return x;\n}\n\nOCAMCamera::Parameters::Parameters()\n    : Camera::Parameters(SCARAMUZZA),\n      m_C(0.0),\n      m_D(0.0),\n      m_E(0.0),\n      m_center_x(0.0),\n      m_center_y(0.0)\n{\n  memset(m_poly, 0, sizeof(double) * SCARAMUZZA_POLY_SIZE);\n  memset(m_inv_poly, 0, sizeof(double) * SCARAMUZZA_INV_POLY_SIZE);\n}\n\nbool OCAMCamera::Parameters::readFromYamlFile(const std::string &filename)\n{\n  cv::FileStorage fs(filename, cv::FileStorage::READ);\n\n  if (!fs.isOpened())\n  {\n    return false;\n  }\n\n  if (!fs[\"model_type\"].isNone())\n  {\n    std::string sModelType;\n    fs[\"model_type\"] >> sModelType;\n\n    if (!boost::iequals(sModelType, \"scaramuzza\"))\n    {\n      return false;\n    }\n  }\n\n  m_modelType = SCARAMUZZA;\n  fs[\"camera_name\"] >> m_cameraName;\n  m_imageWidth = static_cast<int>(fs[\"image_width\"]);\n  m_imageHeight = static_cast<int>(fs[\"image_height\"]);\n\n  cv::FileNode n = fs[\"poly_parameters\"];\n  for (int i = 0; i < SCARAMUZZA_POLY_SIZE; i++)\n    m_poly[i] = static_cast<double>(\n        n[std::string(\"p\") + boost::lexical_cast<std::string>(i)]);\n\n  n = fs[\"inv_poly_parameters\"];\n  for (int i = 0; i < SCARAMUZZA_INV_POLY_SIZE; i++)\n    m_inv_poly[i] = static_cast<double>(\n        n[std::string(\"p\") + boost::lexical_cast<std::string>(i)]);\n\n  n = fs[\"affine_parameters\"];\n  m_C = static_cast<double>(n[\"ac\"]);\n  m_D = static_cast<double>(n[\"ad\"]);\n  m_E = static_cast<double>(n[\"ae\"]);\n\n  m_center_x = static_cast<double>(n[\"cx\"]);\n  m_center_y = static_cast<double>(n[\"cy\"]);\n\n  return true;\n}\n\nvoid OCAMCamera::Parameters::writeToYamlFile(\n    const std::string &filename) const\n{\n  cv::FileStorage fs(filename, cv::FileStorage::WRITE);\n\n  fs << \"model_type\"\n     << \"scaramuzza\";\n  fs << \"camera_name\" << m_cameraName;\n  fs << \"image_width\" << m_imageWidth;\n  fs << \"image_height\" << m_imageHeight;\n\n  fs << \"poly_parameters\";\n  fs << \"{\";\n  for (int i = 0; i < SCARAMUZZA_POLY_SIZE; i++)\n    fs << std::string(\"p\") + boost::lexical_cast<std::string>(i) << m_poly[i];\n  fs << \"}\";\n\n  fs << \"inv_poly_parameters\";\n  fs << \"{\";\n  for (int i = 0; i < SCARAMUZZA_INV_POLY_SIZE; i++)\n    fs << std::string(\"p\") + boost::lexical_cast<std::string>(i)\n       << m_inv_poly[i];\n  fs << \"}\";\n\n  fs << \"affine_parameters\";\n  fs << \"{\"\n     << \"ac\" << m_C << \"ad\" << m_D << \"ae\" << m_E << \"cx\" << m_center_x << \"cy\"\n     << m_center_y << \"}\";\n\n  fs.release();\n}\n\nOCAMCamera::Parameters &OCAMCamera::Parameters::operator=(\n    const OCAMCamera::Parameters &other)\n{\n  if (this != &other)\n  {\n    m_modelType = other.m_modelType;\n    m_cameraName = other.m_cameraName;\n    m_imageWidth = other.m_imageWidth;\n    m_imageHeight = other.m_imageHeight;\n    m_C = other.m_C;\n    m_D = other.m_D;\n    m_E = other.m_E;\n    m_center_x = other.m_center_x;\n    m_center_y = other.m_center_y;\n\n    memcpy(m_poly, other.m_poly, sizeof(double) * SCARAMUZZA_POLY_SIZE);\n    memcpy(m_inv_poly, other.m_inv_poly,\n           sizeof(double) * SCARAMUZZA_INV_POLY_SIZE);\n  }\n\n  return *this;\n}\n\nstd::ostream &operator<<(std::ostream &out,\n                         const OCAMCamera::Parameters &params)\n{\n  out << \"Camera Parameters:\" << std::endl;\n  out << \"    model_type \"\n      << \"scaramuzza\" << std::endl;\n  out << \"   camera_name \" << params.m_cameraName << std::endl;\n  out << \"   image_width \" << params.m_imageWidth << std::endl;\n  out << \"  image_height \" << params.m_imageHeight << std::endl;\n\n  out << std::fixed << std::setprecision(10);\n\n  out << \"Poly Parameters\" << std::endl;\n  for (int i = 0; i < SCARAMUZZA_POLY_SIZE; i++)\n    out << std::string(\"p\") + boost::lexical_cast<std::string>(i) << \": \"\n        << params.m_poly[i] << std::endl;\n\n  out << \"Inverse Poly Parameters\" << std::endl;\n  for (int i = 0; i < SCARAMUZZA_INV_POLY_SIZE; i++)\n    out << std::string(\"p\") + boost::lexical_cast<std::string>(i) << \": \"\n        << params.m_inv_poly[i] << std::endl;\n\n  out << \"Affine Parameters\" << std::endl;\n  out << \"            ac \" << params.m_C << std::endl\n      << \"            ad \" << params.m_D << std::endl\n      << \"            ae \" << params.m_E << std::endl;\n  out << \"            cx \" << params.m_center_x << std::endl\n      << \"            cy \" << params.m_center_y << std::endl;\n\n  return out;\n}\n\nOCAMCamera::OCAMCamera() : m_inv_scale(0.0) {}\n\nOCAMCamera::OCAMCamera(const OCAMCamera::Parameters &params)\n    : mParameters(params)\n{\n  m_inv_scale = 1.0 / (params.C() - params.D() * params.E());\n}\n\nCamera::ModelType OCAMCamera::modelType(void) const\n{\n  return mParameters.modelType();\n}\n\nconst std::string &OCAMCamera::cameraName(void) const\n{\n  return mParameters.cameraName();\n}\n\nint OCAMCamera::imageWidth(void) const { return mParameters.imageWidth(); }\n\nint OCAMCamera::imageHeight(void) const { return mParameters.imageHeight(); }\n\nvoid OCAMCamera::estimateIntrinsics(\n    const cv::Size &boardSize,\n    const std::vector<std::vector<cv::Point3f>> &objectPoints,\n    const std::vector<std::vector<cv::Point2f>> &imagePoints)\n{\n  // std::cout << \"OCAMCamera::estimateIntrinsics - NOT IMPLEMENTED\" <<\n  // std::endl;\n  // throw std::string(\"OCAMCamera::estimateIntrinsics - NOT IMPLEMENTED\");\n\n  // Reference: Page 30 of\n  // \" Scaramuzza, D. Omnidirectional Vision: from Calibration to Robot Motion\n  // Estimation, ETH Zurich. Thesis no. 17635.\"\n  // http://e-collection.library.ethz.ch/eserv/eth:30301/eth-30301-02.pdf\n  // Matlab code: calibrate.m\n\n  // First, estimate every image's extrinsics parameters\n  std::vector<Eigen::Matrix3d> RList;\n  std::vector<Eigen::Vector3d> TList;\n\n  RList.reserve(imagePoints.size());\n  TList.reserve(imagePoints.size());\n\n  // i-th image\n  for (size_t image_index = 0; image_index < imagePoints.size();\n       ++image_index)\n  {\n    const std::vector<cv::Point3f> &objPts = objectPoints.at(image_index);\n    const std::vector<cv::Point2f> &imgPts = imagePoints.at(image_index);\n\n    assert(objPts.size() == imgPts.size());\n    assert(objPts.size() ==\n           static_cast<unsigned int>(boardSize.width * boardSize.height));\n\n    Eigen::MatrixXd M(objPts.size(), 6);\n\n    for (size_t corner_index = 0; corner_index < objPts.size();\n         ++corner_index)\n    {\n      double X = objPts.at(corner_index).x;\n      double Y = objPts.at(corner_index).y;\n      assert(objPts.at(corner_index).z == 0.0);\n\n      double u = imgPts.at(corner_index).x;\n      double v = imgPts.at(corner_index).y;\n\n      M(corner_index, 0) = -v * X;\n      M(corner_index, 1) = -v * Y;\n      M(corner_index, 2) = u * X;\n      M(corner_index, 3) = u * Y;\n      M(corner_index, 4) = -v;\n      M(corner_index, 5) = u;\n    }\n\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(\n        M, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    assert(svd.matrixV().cols() == 6);\n    Eigen::VectorXd h = -svd.matrixV().col(5);\n\n    // scaled version of R and T\n    const double sr11 = h(0);\n    const double sr12 = h(1);\n    const double sr21 = h(2);\n    const double sr22 = h(3);\n    const double st1 = h(4);\n    const double st2 = h(5);\n\n    const double AA = square(sr11 * sr12 + sr21 * sr22);\n    const double BB = square(sr11) + square(sr21);\n    const double CC = square(sr12) + square(sr22);\n\n    const double sr32_squared_1 =\n        (-(CC - BB) + sqrt(square(CC - BB) + 4.0 * AA)) / 2.0;\n    const double sr32_squared_2 =\n        (-(CC - BB) - sqrt(square(CC - BB) + 4.0 * AA)) / 2.0;\n\n    // printf(\"rst = %.12f\\n\", sr32_squared_1*sr32_squared_1 +\n    // (CC-BB)*sr32_squared_1 - AA);\n\n    std::vector<double> sr32_squared_values;\n    if (sr32_squared_1 > 0)\n      sr32_squared_values.push_back(sr32_squared_1);\n    if (sr32_squared_2 > 0)\n      sr32_squared_values.push_back(sr32_squared_2);\n    assert(!sr32_squared_values.empty());\n\n    std::vector<double> sr32_values;\n    std::vector<double> sr31_values;\n    for (auto sr32_squared : sr32_squared_values)\n    {\n      for (int sign = -1; sign <= 1; sign += 2)\n      {\n        const double sr32 = static_cast<double>(sign) * std::sqrt(sr32_squared);\n        sr32_values.push_back(sr32);\n        if (sr32_squared == 0.0)\n        {\n          // sr31 can be calculated through norm equality,\n          // but it has positive and negative posibilities\n          // positive one\n          sr31_values.push_back(std::sqrt(CC - BB));\n          // negative one\n          sr32_values.push_back(sr32);\n          sr31_values.push_back(-std::sqrt(CC - BB));\n\n          break; // skip the same situation\n        }\n        else\n        {\n          // sr31 can be calculated throught dot product == 0\n          sr31_values.push_back(-(sr11 * sr12 + sr21 * sr22) / sr32);\n        }\n      }\n    }\n\n    // std::cout << \"h= \" << std::setprecision(12) << h.transpose() <<\n    // std::endl;\n    // std::cout << \"length: \" << sr32_values.size() << \" & \" <<\n    // sr31_values.size() << std::endl;\n\n    assert(!sr31_values.empty());\n    assert(sr31_values.size() == sr32_values.size());\n\n    std::vector<Eigen::Matrix3d> H_values;\n    for (size_t i = 0; i < sr31_values.size(); ++i)\n    {\n      const double sr31 = sr31_values.at(i);\n      const double sr32 = sr32_values.at(i);\n      const double lambda = 1.0 / sqrt(sr11 * sr11 + sr21 * sr21 + sr31 * sr31);\n      Eigen::Matrix3d H;\n      H.setZero();\n      H(0, 0) = sr11;\n      H(0, 1) = sr12;\n      H(0, 2) = st1;\n      H(1, 0) = sr21;\n      H(1, 1) = sr22;\n      H(1, 2) = st2;\n      H(2, 0) = sr31;\n      H(2, 1) = sr32;\n      H(2, 2) = 0;\n\n      H_values.push_back(lambda * H);\n      H_values.push_back(-lambda * H);\n    }\n\n    for (auto &H : H_values)\n    {\n      // std::cout << \"H=\\n\" << H << std::endl;\n      Eigen::Matrix3d R;\n      R.col(0) = H.col(0);\n      R.col(1) = H.col(1);\n      R.col(2) = H.col(0).cross(H.col(1));\n      // std::cout << \"R33 = \" << R(2,2) << std::endl;\n    }\n\n    std::vector<Eigen::Matrix3d> H_candidates;\n\n    for (auto &H : H_values)\n    {\n      Eigen::MatrixXd A_mat(2 * imagePoints.at(image_index).size(), 4);\n      Eigen::VectorXd B_vec(2 * imagePoints.at(image_index).size());\n      A_mat.setZero();\n      B_vec.setZero();\n\n      size_t line_index = 0;\n\n      // iterate images\n      const double &r11 = H(0, 0);\n      const double &r12 = H(0, 1);\n      // const double& r13 = H(0,2);\n      const double &r21 = H(1, 0);\n      const double &r22 = H(1, 1);\n      // const double& r23 = H(1,2);\n      const double &r31 = H(2, 0);\n      const double &r32 = H(2, 1);\n      // const double& r33 = H(2,2);\n      const double &t1 = H(0);\n      const double &t2 = H(1);\n\n      // iterate chessboard corners in the image\n      for (size_t j = 0; j < imagePoints.at(image_index).size(); ++j)\n      {\n        assert(line_index == 2 * j);\n\n        const double &X = objectPoints.at(image_index).at(j).x;\n        const double &Y = objectPoints.at(image_index).at(j).y;\n        const double &u = imagePoints.at(image_index).at(j).x;\n        const double &v = imagePoints.at(image_index).at(j).y;\n\n        double A = r21 * X + r22 * Y + t2;\n        double B = v * (r31 * X + r32 * Y);\n        double C = r11 * X + r12 * Y + t1;\n        double D = u * (r31 * X + r32 * Y);\n        double rou = std::sqrt(u * u + v * v);\n\n        A_mat(line_index + 0, 0) = A;\n        A_mat(line_index + 1, 0) = C;\n        A_mat(line_index + 0, 1) = A * rou;\n        A_mat(line_index + 1, 1) = C * rou;\n        A_mat(line_index + 0, 2) = A * rou * rou;\n        A_mat(line_index + 1, 2) = C * rou * rou;\n\n        A_mat(line_index + 0, 3) = -v;\n        A_mat(line_index + 1, 3) = -u;\n        B_vec(line_index + 0) = B;\n        B_vec(line_index + 1) = D;\n\n        line_index += 2;\n      }\n\n      assert(line_index == static_cast<unsigned int>(A_mat.rows()));\n\n      // pseudo-inverse for polynomial parameters and all t3s\n      {\n        Eigen::JacobiSVD<Eigen::MatrixXd> svd(\n            A_mat, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n        Eigen::VectorXd x = svd.solve(B_vec);\n\n        // std::cout << \"x(poly and t3) = \" << x << std::endl;\n\n        if (x(2) > 0 && x(3) > 0)\n        {\n          H_candidates.push_back(H);\n        }\n      }\n    }\n\n    // printf(\"H_candidates.size()=%zu\\n\", H_candidates.size());\n    assert(H_candidates.size() == 1);\n\n    Eigen::Matrix3d &H = H_candidates.front();\n\n    Eigen::Matrix3d R;\n    R.col(0) = H.col(0);\n    R.col(1) = H.col(1);\n    R.col(2) = H.col(0).cross(H.col(1));\n\n    Eigen::Vector3d T = H.col(2);\n    RList.push_back(R);\n    TList.push_back(T);\n\n    // std::cout << \"#\" << image_index << \" frame\" << \" R =\" << R << \" \\nT = \"\n    // << T.transpose() << std::endl;\n  }\n\n  // Second, estimate camera intrinsic parameters and all t3\n  Eigen::MatrixXd A_mat(2 * imagePoints.size() * imagePoints.at(0).size(),\n                        SCARAMUZZA_POLY_SIZE - 1 + imagePoints.size());\n  Eigen::VectorXd B_vec(2 * imagePoints.size() * imagePoints.at(0).size());\n  A_mat.setZero();\n  B_vec.setZero();\n\n  size_t line_index = 0;\n\n  // iterate images\n  for (size_t i = 0; i < imagePoints.size(); ++i)\n  {\n    const double &r11 = RList.at(i)(0, 0);\n    const double &r12 = RList.at(i)(0, 1);\n    // const double& r13 = RList.at(i)(0,2);\n    const double &r21 = RList.at(i)(1, 0);\n    const double &r22 = RList.at(i)(1, 1);\n    // const double& r23 = RList.at(i)(1,2);\n    const double &r31 = RList.at(i)(2, 0);\n    const double &r32 = RList.at(i)(2, 1);\n    // const double& r33 = RList.at(i)(2,2);\n    const double &t1 = TList.at(i)(0);\n    const double &t2 = TList.at(i)(1);\n\n    // iterate chessboard corners in the image\n    for (size_t j = 0; j < imagePoints.at(i).size(); ++j)\n    {\n      assert(line_index == 2 * (i * imagePoints.at(0).size() + j));\n\n      const double &X = objectPoints.at(i).at(j).x;\n      const double &Y = objectPoints.at(i).at(j).y;\n      const double &u = imagePoints.at(i).at(j).x;\n      const double &v = imagePoints.at(i).at(j).y;\n\n      double A = r21 * X + r22 * Y + t2;\n      double B = v * (r31 * X + r32 * Y);\n      double C = r11 * X + r12 * Y + t1;\n      double D = u * (r31 * X + r32 * Y);\n      double rou = std::sqrt(u * u + v * v);\n\n      for (int k = 1; k <= SCARAMUZZA_POLY_SIZE - 1; ++k)\n      {\n        double pow_rou = 0.0;\n        if (k == 1)\n        {\n          pow_rou = 1.0;\n        }\n        else\n        {\n          pow_rou = std::pow(rou, k);\n        }\n\n        A_mat(line_index + 0, k - 1) = A * pow_rou;\n        A_mat(line_index + 1, k - 1) = C * pow_rou;\n      }\n\n      A_mat(line_index + 0, SCARAMUZZA_POLY_SIZE - 1 + i) = -v;\n      A_mat(line_index + 1, SCARAMUZZA_POLY_SIZE - 1 + i) = -u;\n      B_vec(line_index + 0) = B;\n      B_vec(line_index + 1) = D;\n\n      line_index += 2;\n    }\n  }\n\n  assert(line_index == static_cast<unsigned int>(A_mat.rows()));\n\n  Eigen::Matrix<double, SCARAMUZZA_POLY_SIZE, 1> poly_coeff;\n  // pseudo-inverse for polynomial parameters and all t3s\n  {\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(\n        A_mat, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n    Eigen::VectorXd x = svd.solve(B_vec);\n\n    poly_coeff[0] = x(0);\n    poly_coeff[1] = 0.0;\n    for (int i = 1; i < poly_coeff.size() - 1; ++i)\n    {\n      poly_coeff[i + 1] = x(i);\n    }\n    assert(x.size() ==\n           static_cast<unsigned int>(SCARAMUZZA_POLY_SIZE - 1 + TList.size()));\n  }\n\n  Parameters params = getParameters();\n\n  // Affine matrix A is constructed as [C D; E 1]\n  params.C() = 1.0;\n  params.D() = 0.0;\n  params.E() = 0.0;\n\n  params.center_x() = params.imageWidth() / 2.0;\n  params.center_y() = params.imageHeight() / 2.0;\n\n  for (size_t i = 0; i < SCARAMUZZA_POLY_SIZE; ++i)\n  {\n    params.poly(i) = poly_coeff[i];\n  }\n\n  // params.poly(0) = -216.9657476318;\n  // params.poly(1) = 0.0;\n  // params.poly(2) = 0.0017866911;\n  // params.poly(3) = -0.0000019866;\n  // params.poly(4) =  0.0000000077;\n\n  // inv_poly\n  {\n    std::vector<double> rou_vec;\n    std::vector<double> z_vec;\n    for (double rou = 0.0;\n         rou <= (params.imageWidth() + params.imageHeight()) / 2; rou += 0.1)\n    {\n      double rou_pow_k = 1.0;\n      double z = 0.0;\n\n      for (int k = 0; k < SCARAMUZZA_POLY_SIZE; k++)\n      {\n        z += rou_pow_k * params.poly(k);\n        rou_pow_k *= rou;\n      }\n\n      rou_vec.push_back(rou);\n      z_vec.push_back(z);\n    }\n\n    assert(rou_vec.size() == z_vec.size());\n    Eigen::VectorXd xVec(rou_vec.size());\n    Eigen::VectorXd yVec(rou_vec.size());\n\n    for (size_t i = 0; i < rou_vec.size(); ++i)\n    {\n      xVec(i) = std::atan2(-z_vec.at(i), rou_vec.at(i));\n      yVec(i) = rou_vec.at(i);\n    }\n\n    // use lower order poly to eliminate over-fitting cause by noisy/inaccurate\n    // data\n    const int poly_fit_order = 4;\n    Eigen::VectorXd inv_poly_coeff = polyfit(xVec, yVec, poly_fit_order);\n\n    for (int i = 0; i <= poly_fit_order; ++i)\n    {\n      params.inv_poly(i) = inv_poly_coeff(i);\n    }\n  }\n\n  setParameters(params);\n\n  std::cout << \"initial params:\\n\"\n            << params << std::endl;\n}\n\n/**\n * \\brief Lifts a point from the image plane to the unit sphere\n *\n * \\param p image coordinates\n * \\param P coordinates of the point on the sphere\n */\nvoid OCAMCamera::liftSphere(const Eigen::Vector2d &p,\n                            Eigen::Vector3d &P) const\n{\n  liftProjective(p, P);\n  P.normalize();\n}\n\n/**\n * \\brief Lifts a point from the image plane to its projective ray\n *\n * \\param p image coordinates\n * \\param P coordinates of the projective ray\n */\nvoid OCAMCamera::liftProjective(const Eigen::Vector2d &p,\n                                Eigen::Vector3d &P) const\n{\n  // Relative to Center\n  Eigen::Vector2d xc(p[0] - mParameters.center_x(),\n                     p[1] - mParameters.center_y());\n\n  // Affine Transformation\n  // xc_a = inv(A) * xc;\n  Eigen::Vector2d xc_a(\n      m_inv_scale * (xc[0] - mParameters.D() * xc[1]),\n      m_inv_scale * (-mParameters.E() * xc[0] + mParameters.C() * xc[1]));\n\n  double phi = std::sqrt(xc_a[0] * xc_a[0] + xc_a[1] * xc_a[1]);\n  double phi_i = 1.0;\n  double z = 0.0;\n\n  for (int i = 0; i < SCARAMUZZA_POLY_SIZE; i++)\n  {\n    z += phi_i * mParameters.poly(i);\n    phi_i *= phi;\n  }\n\n  P << xc[0], xc[1], -z;\n}\n\n/**\n * \\brief Project a 3D point (\\a x,\\a y,\\a z) to the image plane in (\\a u,\\a v)\n *\n * \\param P 3D point coordinates\n * \\param p return value, contains the image point coordinates\n */\nvoid OCAMCamera::spaceToPlane(const Eigen::Vector3d &P,\n                              Eigen::Vector2d &p) const\n{\n  double norm = std::sqrt(P[0] * P[0] + P[1] * P[1]);\n  double theta = std::atan2(-P[2], norm);\n  double rho = 0.0;\n  double theta_i = 1.0;\n\n  for (int i = 0; i < SCARAMUZZA_INV_POLY_SIZE; i++)\n  {\n    rho += theta_i * mParameters.inv_poly(i);\n    theta_i *= theta;\n  }\n\n  double invNorm = 1.0 / norm;\n  Eigen::Vector2d xn(P[0] * invNorm * rho, P[1] * invNorm * rho);\n\n  p << xn[0] * mParameters.C() + xn[1] * mParameters.D() +\n           mParameters.center_x(),\n      xn[0] * mParameters.E() + xn[1] + mParameters.center_y();\n}\n\n/**\n * \\brief Projects an undistorted 2D point p_u to the image plane\n *\n * \\param p_u 2D point coordinates\n * \\return image point coordinates\n */\nvoid OCAMCamera::undistToPlane(const Eigen::Vector2d &p_u,\n                               Eigen::Vector2d &p) const\n{\n  Eigen::Vector3d P(p_u[0], p_u[1], 1.0);\n  spaceToPlane(P, p);\n}\n\n#if 0\nvoid\nOCAMCamera::initUndistortMap(cv::Mat& map1, cv::Mat& map2, double fScale) const\n{\n    cv::Size imageSize(mParameters.imageWidth(), mParameters.imageHeight());\n\n    cv::Mat mapX = cv::Mat::zeros(imageSize, CV_32F);\n    cv::Mat mapY = cv::Mat::zeros(imageSize, CV_32F);\n\n    for (int v = 0; v < imageSize.height; ++v)\n    {\n        for (int u = 0; u < imageSize.width; ++u)\n        {\n            double mx_u = m_inv_K11 / fScale * u + m_inv_K13 / fScale;\n            double my_u = m_inv_K22 / fScale * v + m_inv_K23 / fScale;\n\n            double xi = mParameters.xi();\n            double d2 = mx_u * mx_u + my_u * my_u;\n\n            Eigen::Vector3d P;\n            P << mx_u, my_u, 1.0 - xi * (d2 + 1.0) / (xi + sqrt(1.0 + (1.0 - xi * xi) * d2));\n\n            Eigen::Vector2d p;\n            spaceToPlane(P, p);\n\n            mapX.at<float>(v,u) = p(0);\n            mapY.at<float>(v,u) = p(1);\n        }\n    }\n\n    cv::convertMaps(mapX, mapY, map1, map2, CV_32FC1, false);\n}\n#endif\n\ncv::Mat OCAMCamera::initUndistortRectifyMap(cv::Mat &map1, cv::Mat &map2,\n                                            float fx, float fy,\n                                            cv::Size imageSize, float cx,\n                                            float cy, cv::Mat rmat) const\n{\n  if (imageSize == cv::Size(0, 0))\n  {\n    imageSize = cv::Size(mParameters.imageWidth(), mParameters.imageHeight());\n  }\n\n  cv::Mat mapX = cv::Mat::zeros(imageSize.height, imageSize.width, CV_32F);\n  cv::Mat mapY = cv::Mat::zeros(imageSize.height, imageSize.width, CV_32F);\n\n  Eigen::Matrix3f K_rect;\n\n  K_rect << fx, 0, cx < 0 ? imageSize.width / 2 : cx, 0, fy,\n      cy < 0 ? imageSize.height / 2 : cy, 0, 0, 1;\n\n  if (fx < 0 || fy < 0)\n  {\n    throw std::string(std::string(__FUNCTION__) +\n                      \": Focal length must be specified\");\n  }\n\n  Eigen::Matrix3f K_rect_inv = K_rect.inverse();\n\n  Eigen::Matrix3f R, R_inv;\n  cv::cv2eigen(rmat, R);\n  R_inv = R.inverse();\n\n  for (int v = 0; v < imageSize.height; ++v)\n  {\n    for (int u = 0; u < imageSize.width; ++u)\n    {\n      Eigen::Vector3f xo;\n      xo << u, v, 1;\n\n      Eigen::Vector3f uo = R_inv * K_rect_inv * xo;\n\n      Eigen::Vector2d p;\n      spaceToPlane(uo.cast<double>(), p);\n\n      mapX.at<float>(v, u) = p(0);\n      mapY.at<float>(v, u) = p(1);\n    }\n  }\n\n  cv::convertMaps(mapX, mapY, map1, map2, CV_32FC1, false);\n\n  cv::Mat K_rect_cv;\n  cv::eigen2cv(K_rect, K_rect_cv);\n  return K_rect_cv;\n}\n\nint OCAMCamera::parameterCount(void) const\n{\n  return SCARAMUZZA_CAMERA_NUM_PARAMS;\n}\n\nconst OCAMCamera::Parameters &OCAMCamera::getParameters(void) const\n{\n  return mParameters;\n}\n\nvoid OCAMCamera::setParameters(const OCAMCamera::Parameters &parameters)\n{\n  mParameters = parameters;\n\n  m_inv_scale = 1.0 / (parameters.C() - parameters.D() * parameters.E());\n}\n\nvoid OCAMCamera::readParameters(const std::vector<double> &parameterVec)\n{\n  if ((int)parameterVec.size() != parameterCount())\n  {\n    return;\n  }\n\n  Parameters params = getParameters();\n\n  params.C() = parameterVec.at(0);\n  params.D() = parameterVec.at(1);\n  params.E() = parameterVec.at(2);\n  params.center_x() = parameterVec.at(3);\n  params.center_y() = parameterVec.at(4);\n  for (int i = 0; i < SCARAMUZZA_POLY_SIZE; i++)\n    params.poly(i) = parameterVec.at(5 + i);\n  for (int i = 0; i < SCARAMUZZA_INV_POLY_SIZE; i++)\n    params.inv_poly(i) = parameterVec.at(5 + SCARAMUZZA_POLY_SIZE + i);\n\n  setParameters(params);\n}\n\nvoid OCAMCamera::writeParameters(std::vector<double> &parameterVec) const\n{\n  parameterVec.resize(parameterCount());\n  parameterVec.at(0) = mParameters.C();\n  parameterVec.at(1) = mParameters.D();\n  parameterVec.at(2) = mParameters.E();\n  parameterVec.at(3) = mParameters.center_x();\n  parameterVec.at(4) = mParameters.center_y();\n  for (int i = 0; i < SCARAMUZZA_POLY_SIZE; i++)\n    parameterVec.at(5 + i) = mParameters.poly(i);\n  for (int i = 0; i < SCARAMUZZA_INV_POLY_SIZE; i++)\n    parameterVec.at(5 + SCARAMUZZA_POLY_SIZE + i) = mParameters.inv_poly(i);\n}\n\nvoid OCAMCamera::writeParametersToYamlFile(const std::string &filename) const\n{\n  mParameters.writeToYamlFile(filename);\n}\n\nstd::string OCAMCamera::parametersToString(void) const\n{\n  std::ostringstream oss;\n  oss << mParameters;\n\n  return oss.str();\n}\n", "meta": {"hexsha": "8b3797f7a2919bcbec8655b15aca1f327187cf05", "size": 24419, "ext": "cc", "lang": "C++", "max_stars_repo_path": "camera_models/src/ScaramuzzaCamera.cc", "max_stars_repo_name": "daoran/CamLaserCalibraTool", "max_stars_repo_head_hexsha": "e3ba0c66e012989bec1411c4b4a41c0c150a324d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 400.0, "max_stars_repo_stars_event_min_datetime": "2018-12-14T09:36:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:14:37.000Z", "max_issues_repo_path": "camera_models/src/ScaramuzzaCamera.cc", "max_issues_repo_name": "chisyliu/CamLaserCalibraTool", "max_issues_repo_head_hexsha": "c2b72f8a6e50f2dfc863b393baefbb10c05c6c6d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2019-07-29T20:08:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T03:37:59.000Z", "max_forks_repo_path": "camera_models/src/ScaramuzzaCamera.cc", "max_forks_repo_name": "chisyliu/CamLaserCalibraTool", "max_forks_repo_head_hexsha": "c2b72f8a6e50f2dfc863b393baefbb10c05c6c6d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 158.0, "max_forks_repo_forks_event_min_datetime": "2018-12-14T10:30:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T03:14:10.000Z", "avg_line_length": 28.6607981221, "max_line_length": 93, "alphanum_fraction": 0.5835210287, "num_tokens": 7692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.539615815296225}}
{"text": "//! \\file examples/Minkowski_sum_2/approx_inset.cpp\n// Computing the approximated inset of a polygon.\n\n#include <fstream>\n#include <iostream>\n#include <list>\n#include <boost/timer.hpp>\n\n#include <CGAL/approximated_offset_2.h>\n\n#include \"bops_circular.h\"\n\ntypedef CGAL::Polygon_2<Kernel>                         Linear_polygon;\n\nint main(int argc, char* argv[])\n{\n  // Open the input file and read a polygon.\n  const char* filename = (argc > 1) ? argv[1] : \"tight.dat\";\n  std::ifstream in_file(filename);\n\n  if (! in_file.is_open()) {\n    std::cerr << \"Failed to open the input file.\" << std::endl;\n    return -1;\n  }\n\n  // Read the input polygon.\n  Linear_polygon P;\n  in_file >> P;\n  in_file.close();\n\n  std::cout << \"Read an input polygon with \" << P.size() << \" vertices.\"\n            << std::endl;\n\n  // Approximate the offset polygon.\n  std::list<Polygon_2> inset_polygons;\n  boost::timer timer;\n  approximated_inset_2(P, 1, 0.00001, std::back_inserter(inset_polygons));\n  double secs = timer.elapsed();\n\n  std::list<Polygon_2>::iterator it;\n  std::cout << \"The inset comprises \" << inset_polygons.size()\n            << \" polygon(s).\" << std::endl;\n  for (it = inset_polygons.begin(); it != inset_polygons.end(); ++it)\n    std::cout << \"    Polygon with \" << it->size() << \" vertices.\" << std::endl;\n  std::cout << \"Inset computation took \" << secs << \" seconds.\" << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "6d6fd9c711089191c6873cbc09392fadfcafa4b2", "size": 1397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Minkowski_sum_2/examples/Minkowski_sum_2/approx_inset.cpp", "max_stars_repo_name": "gaschler/cgal", "max_stars_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T09:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T05:00:23.000Z", "max_issues_repo_path": "Minkowski_sum_2/examples/Minkowski_sum_2/approx_inset.cpp", "max_issues_repo_name": "gaschler/cgal", "max_issues_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "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": "Minkowski_sum_2/examples/Minkowski_sum_2/approx_inset.cpp", "max_forks_repo_name": "gaschler/cgal", "max_forks_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_forks_repo_licenses": ["CC0-1.0"], "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.1041666667, "max_line_length": 80, "alphanum_fraction": 0.6327845383, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5396158100734972}}
{"text": "#include <base/cgal_typedefs.h>\n#include <util/geometricOperations.h>\n#include <Eigen/Core>\n#include <CGAL/Polyhedron_copy_3.h>\n\nusing namespace std;\n\ndouble dot(const Vector& v1, const Vector& v2){\n    return v1.x()*v2.x() + v1.y()*v2.y() + v1.z()*v2.z();\n}\n\ndouble dot(const Point& v1, const Point& v2){\n    return v1.x()*v2.x() + v1.y()*v2.y() + v1.z()*v2.z();\n}\n\ndouble dot(const Vector& v1, const Point& v2){\n    return v1.x()*v2.x() + v1.y()*v2.y() + v1.z()*v2.z();\n}\n\ndouble dot(const Point& v1, const Vector& v2){\n    return v1.x()*v2.x() + v1.y()*v2.y() + v1.z()*v2.z();\n}\n\nVector crossV(const Vector& v1, const Vector& v2){\n\n    return Vector(v1.y()*v2.z() - v1.z()*v2.y(),\n                  v1.z()*v2.x() - v1.x()*v2.z(),\n                  v1.x()*v2.y() - v1.y()*v2.x());\n}\n\nVector crossV(const Point& v1, const Point& v2){\n\n    return Vector(v1.y()*v2.z() - v1.z()*v2.y(),\n                  v1.z()*v2.x() - v1.x()*v2.z(),\n                  v1.x()*v2.y() - v1.y()*v2.x());\n}\n\nPoint crossP(const Vector& v1, const Vector& v2){\n\n    return Point(v1.y()*v2.z() - v1.z()*v2.y(),\n                  v1.z()*v2.x() - v1.x()*v2.z(),\n                  v1.x()*v2.y() - v1.y()*v2.x());\n}\n\nPoint crossP(const Point& v1, const Point& v2){\n\n    return Point(v1.y()*v2.z() - v1.z()*v2.y(),\n                  v1.z()*v2.x() - v1.x()*v2.z(),\n                  v1.x()*v2.y() - v1.y()*v2.x());\n}\n\nPoint neg(const Point& p){\n\n    return Point(-p.x(), -p.y(), -p.z());\n}\n\n\n\nconst double polyhedronVolume(vector<pair<Triangle, Vector>> polyhedron){\n\n    double volume;\n    for(auto const& facet : polyhedron){\n        volume+= dot(facet.first[0], facet.second);\n    }\n    return volume/6;\n\n}\n\n\ndouble pointPlaneDistance(EPICK::Plane_3 plane, Point point){\n\n    // implemented from: http://mathworld.wolfram.com/Point-PlaneDistance.html\n\n    double dist = (plane.a()*point.x() + plane.b()*point.y() + plane.c()*point.z() + plane.d()) /\n            std::sqrt(plane.a()*plane.a() + plane.b()*plane.b() + plane.c()*plane.c());\n\n    return dist;\n}\n\n\n\n// Implementation of geometry visualized in Figure 9 in P. Labatut, J\u2010P. Pons,\n// and R. Keriven. \"Robust and efficient surface reconstruction from range\n// data.\" Computer graphics forum, 2009.\ndouble computeCosFacetCellAngle(const Delaunay& Dt,\n                                const Delaunay::Facet& facet) {\n  if (Dt.is_infinite(facet.first)) {\n    return 1.0;\n  }\n\n  const Triangle triangle = Dt.triangle(facet);\n\n  const Vector facet_normal =\n      CGAL::cross_product(triangle[1] - triangle[0], triangle[2] - triangle[0]);\n  const double facet_normal_length_squared = facet_normal.squared_length();\n  if (facet_normal_length_squared == 0.0) {\n    return 0.5;\n  }\n\n  const Vector co_tangent = CGAL::circumcenter(Dt.tetrahedron(facet.first)) - triangle[0];\n  const float co_tangent_length_squared = co_tangent.squared_length();\n  if (co_tangent_length_squared == 0.0) {\n    return 0.5;\n  }\n\n  return (facet_normal * co_tangent) /\n         std::sqrt(facet_normal_length_squared * co_tangent_length_squared);\n}\n\n\ndouble computeFacetArea(const Delaunay& Dt,\n                        const Delaunay::Facet& facet){\n    if(Dt.is_infinite(facet))\n        return 0.0;\n    else\n        return sqrt(Dt.triangle(facet).squared_area());\n};\n\n\nconst Point barycenter(const Cell_handle& ch){\n    double x = 0, y = 0, z = 0;\n    for(int i = 0; i < 4; i++){\n        x+=ch->vertex(i)->point().x();\n        y+=ch->vertex(i)->point().y();\n        z+=ch->vertex(i)->point().z();\n    }\n    return Point(x/4.0,y/4.0,z/4.0);\n}\n\n\n\n\n\nbool rayTriangleIntersection(const Point& rayOrigin,\n                           const Vector& rayVector,\n                           const Triangle& inTriangle,\n                           Point& outIntersectionPoint){\n\n    // implemented after: https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm\n\n    using namespace Eigen;\n    const double EPSILON = 0.0000001;\n\n    // init \"Eigen\" vectors\n    Vector3d rayO(rayOrigin.x(), rayOrigin.y(), rayOrigin.z());\n    Vector3d rayV(rayVector.x(), rayVector.y(), rayVector.z());\n\n    Vector3d vertex0(inTriangle.vertex(0).x(), inTriangle.vertex(0).y(), inTriangle.vertex(0).z());\n    Vector3d vertex1(inTriangle.vertex(1).x(), inTriangle.vertex(1).y(), inTriangle.vertex(1).z());\n    Vector3d vertex2(inTriangle.vertex(2).x(), inTriangle.vertex(2).y(), inTriangle.vertex(2).z());\n\n    Vector3d edge1, edge2, h, s, q;\n    double a;\n    edge1 = vertex1 - vertex0;\n    edge2 = vertex2 - vertex0;\n\n    h = rayV.cross(edge2);\n    a = edge1.dot(h);\n    if (a > -EPSILON && a < EPSILON)\n        return false;    // This ray is parallel to this triangle.\n    double f = 1.0/a;\n    s = rayO - vertex0;\n    double u = f * s.dot(h);    // barycentric coordinate u\n    if (u < 0.0 || u > 1.0)     // if u is not between 0 and 1, intersection point does not lie in triangle\n        return false;\n    q = s.cross(edge1);\n    double v = f * rayV.dot(q); // barycentric coordinate v\n    if (v < 0.0 || u + v > 1.0) // if v is not between 0 and 1, intersection point does not lie in triangle\n        return false;\n    // At this stage we can compute t to find out where the intersection point is on the line.\n    double t = f * edge2.dot(q);\n    if (t > EPSILON) // ray intersection\n    {\n        outIntersectionPoint = rayOrigin + rayVector * t;\n        return true;\n    }\n    else // This means that there is a line intersection but not a ray intersection.\n        return false;\n}\n\n\n", "meta": {"hexsha": "a17d9c22b706ae09aa222711a0bac4617911d154", "size": 5483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util/geometricOperations.cpp", "max_stars_repo_name": "raphaelsulzer/mesh-tools", "max_stars_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-24T03:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T03:39:05.000Z", "max_issues_repo_path": "src/util/geometricOperations.cpp", "max_issues_repo_name": "raphaelsulzer/mesh-tools", "max_issues_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-24T06:59:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T01:25:09.000Z", "max_forks_repo_path": "src/util/geometricOperations.cpp", "max_forks_repo_name": "raphaelsulzer/mesh-tools", "max_forks_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_forks_repo_licenses": ["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.1263736264, "max_line_length": 107, "alphanum_fraction": 0.592923582, "num_tokens": 1644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5396158100734972}}
{"text": "#include \"chainparams.h\"\n#include \"libzerocoin/ArithmeticCircuit.h\"\n#include \"libzerocoin/PolynomialCommitment.h\"\n#include \"libzerocoin/Bulletproofs.h\"\n#include \"libzerocoin/SerialNumberSoK_small.h\"\n#include \"libzerocoin/SerialNumberSignatureOfKnowledge.h\"\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <util/time.h>\n#include <random.h>\n#include <veil/zerocoin/zchain.h>\n\n\nusing namespace libzerocoin;\n\n#define COLOR_STR_NORMAL  \"\\033[0m\"\n#define COLOR_BOLD        \"\\033[1m\"\n#define COLOR_STR_GREEN   \"\\033[32m\"\n#define COLOR_STR_RED     \"\\033[31m\"\n#define COLOR_CYAN        \"\\033[0;36m\"\n#define COLOR_MAGENTA     \"\\u001b[35m\"\n\nstd::string colorNormal(COLOR_STR_NORMAL);\nstd::string colorBold(COLOR_BOLD);\nstd::string colorGreen(COLOR_STR_GREEN);\nstd::string colorRed(COLOR_STR_RED);\nstd::string colorCyan(COLOR_CYAN);\nstd::string colorMagenta(COLOR_MAGENTA);\n\n// Global test counters\nuint32_t    zNumTests        = 0;\nuint32_t    zSuccessfulTests = 0;\n\nstd::string Pass(bool fReverseTest = false)\n{\n    return fReverseTest ? \"[FAIL (good)]\" : \"[PASS]\";\n}\n\nstd::string Fail(bool fReverseTest = false)\n{\n    return fReverseTest ? \"[PASS (when it shouldn't!)]\" : \"[FAIL]\";\n}\n\n\n// Parameters ----------------------------------------------------------------------------------------\n\nbool Test_generators(IntegerGroupParams SoKGroup)\n{\n    zNumTests++;\n    std::cout << \"- Testing generators...\";\n    for(unsigned int i=0; i<512; i++) {\n        if ( SoKGroup.gis[i].pow_mod(SoKGroup.groupOrder,SoKGroup.modulus) != CBigNum(1)) {\n            std::cout << colorRed << Fail() << std::endl;\n            std::cout << \"gis[\" << i << \"] ** q != 1\" << colorNormal << std::endl;\n            return false;\n        }\n    }\n    std::cout << colorGreen << Pass() << colorNormal << std::endl;\n    zSuccessfulTests++;\n    return true;\n}\n\n\nbool parameters_tests()\n{\n    std::cout << colorBold << \"*** parameters_tests ***\" << std::endl;\n    std::cout << \"------------------------\" << colorNormal << std::endl;\n\n    bool finalResult = true;\n\n    SelectParams(CBaseChainParams::MAIN);\n    ZerocoinParams *ZCParams = Params().Zerocoin_Params();\n    (void)ZCParams;\n\n    finalResult = finalResult & Test_generators(ZCParams->serialNumberSoKCommitmentGroup);\n\n    std::cout << std::endl;\n\n    return finalResult;\n}\n\n// ---------------------------------------------------------------------------------------------------\n// Arithmetic Circuit --------------------------------------------------------------------------------\nbool Test_multGates(ArithmeticCircuit ac, CBigNum q)\n{\n    zNumTests++;\n    // If multiplication gates hold this should be true\n    std::cout << \"- Testing A times B equals C...\";\n    for(unsigned int i=0; i<ZKP_M; i++) for(unsigned int j=0; j<ZKP_N; j++) {\n            if(ac.A[i][j].mul_mod(ac.B[i][j], q) != ac.C[i][j]) {\n                std::cout << colorRed << Fail() << std::endl;\n                std::cout << \"Hadamard Test failed at i=\" << i << \", j=\" << j << colorNormal << std::endl;\n                return false;\n            }\n        }\n\n    std::cout << colorGreen << Pass()  << colorNormal << std::endl;\n    zSuccessfulTests++;\n    return true;\n}\n\nbool Test_cfinalLog(ArithmeticCircuit ac, CBigNum q, CBigNum a, CBigNum b, bool fReverseTest = false)\n{\n    zNumTests++;\n    // If circuit correctly evaluates (a^serial)*(b^randomness) this should be true\n    std::cout << \"- Testing C_final equals Logarithm\";\n    if (fReverseTest)\n        std::cout << colorMagenta << \" with wrong assignment\" << colorNormal;\n    std::cout << \"...\";\n    CBigNum logarithm =\n            a.pow_mod(ac.getSerialNumber(),q).mul_mod(\n                    b.pow_mod(ac.getRandomness(),q),q);\n    CBigNum Cfinal = ac.C[ZKP_M-1][0];\n    bool test = (logarithm == Cfinal);\n    if (test == fReverseTest) {\n        std::cout << colorRed << Fail(fReverseTest) << colorNormal << std::endl;\n        return false;\n    }\n\n    std::cout << colorGreen << Pass(fReverseTest) << colorNormal << std::endl;\n    zSuccessfulTests++;\n    return true;\n}\n\nbool Test_arithConstraints(ArithmeticCircuit ac, CBigNum q, bool fReverseTest = false)\n{\n    zNumTests++;\n    // Checking that the expressions in Equation (2) of the paper hold\n    std::cout << \"- Testing the Arithmetic Constraints (eq. 2)\";\n    if (fReverseTest)\n        std::cout << colorMagenta << \" with wrong assignment\" << colorNormal;\n    std::cout << \"...\";\n    bool test = true;\n    unsigned int last_index = 0;\n    for(unsigned int i=0; i<4*ZKP_SERIALSIZE-2; i++) {\n        if (ac.sumWiresDotWs(i) != ac.K[i] % q) {\n            test = false;\n            last_index = i;\n            break;\n        }\n    }\n\n    if (test == fReverseTest) {\n        std::cout << colorRed << Fail(fReverseTest) << std::endl;\n        std::cout << \"Arithmetic Constraints Test failed at i=\" << last_index << colorNormal << std::endl;\n        return false;\n    }\n\n    std::cout << colorGreen << Pass(fReverseTest)  << colorNormal << std::endl;\n    zSuccessfulTests++;\n    return true;\n}\n\n\nbool arithmetic_circuit_tests()\n{\n    std::cout << colorBold << \"*** arithmetic_circuit_tests ***\" << std::endl;\n    std::cout << \"--------------------------------\" << colorNormal << std::endl;\n\n    bool finalResult = true;\n\n    SelectParams(CBaseChainParams::MAIN);\n    ZerocoinParams *ZCParams = Params().Zerocoin_Params();\n    (void)ZCParams;\n\n    CBigNum a = ZCParams->coinCommitmentGroup.g;\n    CBigNum b = ZCParams->coinCommitmentGroup.h;\n    CBigNum q = ZCParams->serialNumberSoKCommitmentGroup.groupOrder;\n\n    // mint a coin\n    PrivateCoin coin(ZCParams, CoinDenomination::ZQ_TEN, true);\n    // get random Y\n    CBigNum Y = CBigNum::randBignum(q);\n    ArithmeticCircuit circuit(ZCParams);\n    circuit.setWireValues(coin);\n    circuit.setYPoly(Y);\n\n    finalResult = finalResult & Test_multGates(circuit, q);\n    finalResult = finalResult & Test_cfinalLog(circuit, q, a, b);\n    finalResult = finalResult & Test_arithConstraints(circuit, q);\n\n    // !TODO: rewrite this test case.\n    // Checking that the expressions in Equation (3) of the paper hold\n    // (circuit.sumWiresDotWPoly() == circuit.Kconst)\n\n    // New circuit with random assignment\n    ArithmeticCircuit newCircuit(circuit);\n    for(unsigned int i=0; i<ZKP_M; i++) {\n        random_vector_mod(newCircuit.A[i], q);\n        random_vector_mod(newCircuit.B[i], q);\n        for(unsigned int j=0; j<ZKP_N; j++)\n            newCircuit.C[i][j] = newCircuit.A[i][j].mul_mod(newCircuit.B[i][j],q);\n    }\n\n    // If circuit correctly evaluates (a^serial)*(b^randomness) we have a problem\n    finalResult = finalResult & Test_cfinalLog(newCircuit, q, a, b, true);\n\n    // Checking that the expressions in Equation (2) of the paper does not hold\n    finalResult = finalResult & Test_arithConstraints(newCircuit, q, true);\n\n    // !TODO: rewrite this test case.\n    // Checking that the expressions in Equation (3) of the does not paper hold\n\n    std::cout << std::endl;\n\n    return finalResult;\n}\n\n\n// ---------------------------------------------------------------------------------------------------\n// Polynomial Commitment -----------------------------------------------------------------------------\n\n// Evaluate tpolynomial at x\nCBigNum eval_tpoly(CBN_vector tpoly, CBN_vector xPowersPos, CBN_vector xPowersNeg, CBigNum q)\n{\n    CBigNum sum = CBigNum(0);\n    for(unsigned int i=0; i<=ZKP_NDASH*ZKP_M1DASH; i++)\n        sum = ( sum + tpoly[i].mul_mod(xPowersNeg[ZKP_NDASH*ZKP_M1DASH-i],q) ) % q;\n    for(unsigned int i=ZKP_NDASH*ZKP_M1DASH+1; i<=ZKP_NDASH*(ZKP_M1DASH+ZKP_M2DASH); i++)\n        sum = ( sum + tpoly[i].mul_mod(xPowersPos[i-ZKP_NDASH*ZKP_M1DASH],q) ) % q;\n    return sum;\n}\n\nbool Test_polyVerify1(PolynomialCommitment pc, CBigNum &val, bool fReverseTest = false)\n{\n    zNumTests++;\n    // Poly-Verify: For honest prover, verifier should be satisfied\n    std::cout << \"- Testing PolyVerify\";\n    if (fReverseTest)\n        std::cout << colorMagenta << \" for dishonest prover\" << colorNormal;\n    std::cout << \"...\";\n    // val = t(x) if proofs checks out\n    bool test = (pc.Verify(val));\n    if (test == fReverseTest) {\n        std::cout << colorRed << Fail(fReverseTest) << colorNormal << std::endl;\n        return false;\n    }\n\n    std::cout << colorGreen << Pass(fReverseTest)  << colorNormal << std::endl;\n    zSuccessfulTests++;\n    return true;\n}\n\nbool Test_polyVerify2(CBigNum val, CBN_vector tpoly,\n                      CBN_vector xpos, CBN_vector xneg, CBigNum q)\n{\n    zNumTests++;\n    // Poly-Verify: For honest prover, verifier is able to compute t(x)\n    std::cout << \"- Testing t(x) == dotProduct(tbar,xPowersPos)...\";\n    CBigNum tx = eval_tpoly(tpoly, xpos, xneg, q);\n    if (val != tx) {\n        std::cout << colorRed << Fail() << colorNormal << std::endl;\n        return false;\n    }\n\n    std::cout << colorGreen << Pass()  << colorNormal << std::endl;\n    zSuccessfulTests++;\n    return true;\n}\n\nbool polynomial_commitment_tests()\n{\n    std::cout << colorBold << \"*** polynomial_commitment_tests ***\" << std::endl;\n    std::cout << \"-----------------------------------\" << colorNormal << std::endl;\n\n    bool finalResult = true;\n    SelectParams(CBaseChainParams::MAIN);\n    ZerocoinParams *ZCParams = Params().Zerocoin_Params();\n    (void)ZCParams;\n\n    CBigNum q = ZCParams->serialNumberSoKCommitmentGroup.groupOrder;\n    CBigNum p = ZCParams->serialNumberSoKCommitmentGroup.modulus;\n\n    // generate a random tpolynomial with 0 constant term\n    CBN_vector tpoly(ZKP_NDASH*(ZKP_M1DASH+ZKP_M2DASH)+1);\n    for(unsigned int i=0; i<tpoly.size(); i++)\n        tpoly[i] = CBigNum::randBignum(q);\n    tpoly[ZKP_M1DASH*ZKP_NDASH] = CBigNum(0);\n\n    // generate a random evaluation point x in R and compute powers\n    CBigNum x = CBigNum::randBignum(q);\n    CBN_vector xPowersPositive(ZKP_M2DASH*ZKP_NDASH+1);\n    CBN_vector xPowersNegative(ZKP_M1DASH*ZKP_NDASH+1);\n    xPowersPositive[0] = xPowersNegative[0] = CBigNum(1);\n    xPowersPositive[1] = x;\n    xPowersNegative[1] = x.pow_mod(-1,q);\n    for(unsigned int i=2; i<ZKP_M2DASH*ZKP_NDASH+1; i++)\n        xPowersPositive[i] = x.pow_mod(i,q);\n    for(unsigned int i=2; i<ZKP_M1DASH*ZKP_NDASH+1; i++)\n        xPowersNegative[i] = x.pow_mod(-(int)i,q);\n\n    // Poly-Commit and Poly-Evaluate\n    PolynomialCommitment polyCommitment(ZCParams);\n    polyCommitment.Commit(tpoly);\n    polyCommitment.Eval(xPowersPositive, xPowersNegative);\n\n    // Polynomial  evaluation\n    CBigNum val;\n\n    finalResult = finalResult & Test_polyVerify1(polyCommitment, val);\n    finalResult = finalResult & Test_polyVerify2(val, tpoly, xPowersPositive, xPowersNegative, q);\n\n    // Create copies of the polynomial commitment and mess things up\n    PolynomialCommitment newPolyComm1(polyCommitment);\n    PolynomialCommitment newPolyComm2(polyCommitment);\n    PolynomialCommitment newPolyComm3(polyCommitment);\n    random_vector_mod(newPolyComm1.tbar, q);\n    random_vector_mod(newPolyComm2.Tf, q);\n    random_vector_mod(newPolyComm3.Trho, q);\n\n    // Poly-Verify: For dishonest prover, verifier should fail the test\n    finalResult = finalResult & Test_polyVerify1(newPolyComm1, val, true);\n    finalResult = finalResult & Test_polyVerify1(newPolyComm2, val, true);\n    finalResult = finalResult & Test_polyVerify1(newPolyComm3, val, true);\n\n    std::cout << std::endl;\n\n    return finalResult;\n}\n\n// ---------------------------------------------------------------------------------------------------\n// Inner Product Argument ----------------------------------------------------------------------------\n\n// !TODO: Adapt to bulletproofs class\n/*\nBOOST_AUTO_TEST_CASE(inner_product_argument_tests)\n{\n    std::cout << \"*** inner_product_argument_tests ***\" << std::endl;\n    std::cout << \"------------------------------------\" << std::endl;\n    SelectParams(CBaseChainParams::MAIN);\n    ZerocoinParams *ZCParams = Params().Zerocoin_Params(false);\n    (void)ZCParams;\n    CBigNum q = ZCParams->serialNumberSoKCommitmentGroup.groupOrder;\n    CBigNum p = ZCParams->serialNumberSoKCommitmentGroup.modulus;\n    // Get random y in Z_q and (N+PADS)-vectors\n    CBigNum y = CBigNum::randBignum(q);\n    CBN_vector a_sets(ZKP_N+ZKP_PADS);\n    CBN_vector b_sets(ZKP_N+ZKP_PADS);\n    random_vector_mod(a_sets, q);\n    random_vector_mod(b_sets, q);\n    // Inner-product PROVE\n    InnerProductArgument innerProduct(ZCParams);\n    innerProduct.Prove(y, a_sets, b_sets);\n    // compute ck_inner sets\n    pair<CBN_vector, CBN_vector> resultSets = innerProduct.ck_inner_gen(ZCParams, y);\n    CBN_vector ck_inner_g = resultSets.first;\n    CBN_vector ck_inner_h = resultSets.second;\n    // Compute commitment A to a_sets under ck_inner_g\n    CBigNum A = CBigNum(1);\n    for(unsigned int i=0; i<a_sets.size(); i++)\n        A = A.mul_mod(ck_inner_g[i].pow_mod(a_sets[i], p), p);\n    // Compute commitment B to b_sets under ck_inner_h\n    CBigNum B = CBigNum(1);\n    for(unsigned int i=0; i<b_sets.size(); i++)\n        B = B.mul_mod(ck_inner_h[i].pow_mod(b_sets[i], p), p);\n    // Inner product z = <a,b>\n    CBigNum z = dotProduct(a_sets, b_sets, q);\n    // random_z != z\n    CBigNum random_z = CBigNum::randBignum(q);\n    while( random_z == dotProduct(a_sets, b_sets, q) ) random_z = CBigNum::randBignum(q);\n    // innerProductVerify\n    std::cout << \"- Testing innerProductVerify...\" << std::endl;\n    bool res = innerProduct.Verify(ZCParams, y, A, B, z);\n    BOOST_CHECK_MESSAGE(res,\"InnerProduct:: Verification failed\\n\");\n    // Inner product z != <a, b>  (z = 0, z = 1, z = random)\n    std::cout << \"- Testing innerProductVerify for dishonest prover...\" << std::endl;\n    BOOST_CHECK_MESSAGE( !innerProduct.Verify(ZCParams, y, A, B, CBigNum(0)),\n            \"InnerProduct:: Verification returned TRUE[1] for dishonest prover\\n\");\n    BOOST_CHECK_MESSAGE( !innerProduct.Verify(ZCParams, y, A, B, CBigNum(1)),\n            \"InnerProduct:: Verification returned TRUE[2] for dishonest prover\\n\");\n    BOOST_CHECK_MESSAGE( !innerProduct.Verify(ZCParams, y, A, B, random_z),\n            \"InnerProduct:: Verification returned TRUE[3] for dishonest prover\\n\");\n    std::cout << std::endl;\n}\n*/\n\n// ---------------------------------------------------------------------------------------------------\n// Signature Of Knowledge ----------------------------------------------------------------------------\n\nvoid printTime(int64_t start_time, int nProofs)\n{\n    int64_t total_time = GetTimeMillis() - start_time;\n    int64_t nTimePer = nProofs ? total_time/nProofs : 0;\n    std::string strPerProof = std::to_string(nTimePer) + \" msec per proof\";\n    std::cout << colorCyan << \"\\t(\" << total_time << \" msec \" << (nProofs ? strPerProof.c_str() : \"\") << \")\"  << colorNormal << std::endl;\n}\n\nbool Test_batchVerify(std::vector<const SerialNumberSoKProof*> proofs, bool fReverseTest = false)\n{\n    zNumTests++;\n    // verify the signature of the received SoKs\n    std::cout << \"- Verifying the Signatures of Knowledge\";\n    if (fReverseTest)\n        std::cout << colorMagenta << \" for dishonest prover\" << colorNormal;\n    std::cout << \"...\";\n\n    if (SerialNumberSoKProof::BatchVerify(proofs) == fReverseTest) {\n        std::cout << colorRed << Fail(fReverseTest) << colorNormal;\n        return false;\n    }\n\n    std::cout << colorGreen << Pass(fReverseTest) << colorNormal;\n    zSuccessfulTests++;\n    return true;\n}\n\nbool Test_threadedBatchVerify(std::vector<SerialNumberSoKProof>* proofs, int nThreads, bool fReverseTest = false)\n{\n    zNumTests++;\n    // verify the signature of the received SoKs\n    std::cout << \"- Threaded verification of the Signatures of Knowledge\";\n    if (fReverseTest)\n        std::cout << colorMagenta << \" for dishonest prover\" << colorNormal;\n    std::cout << \"...\";\n\n    if (ThreadedBatchVerify(proofs, nThreads) == fReverseTest) {\n        std::cout << colorRed << Fail(fReverseTest) << colorNormal;\n        return false;\n    }\n\n    std::cout << colorGreen << Pass(fReverseTest) << colorNormal;\n    zSuccessfulTests++;\n    return true;\n}\n\nbool batch_signature_of_knowledge_tests(unsigned int start, unsigned int end, unsigned int step)\n{\n    if (end < start || step < 1) {\n        std::cout << \"wrong range for batch_signature_of_knowledge_tests\";\n        return false;\n    }\n\n    std::cout << colorBold <<  \"*** batch_signature_of_knowledge_tests ***\" << std::endl;\n    std::cout << \"------------------------------------------\" << colorNormal <<  std::endl;\n    std::cout << \"starting size of the list: \" << start << std::endl;\n    std::cout << \"ending size of the list: \" << end << std::endl;\n    std::cout << \"step increment: \" << step << std::endl;\n\n    bool finalResult = true;\n    SelectParams(CBaseChainParams::MAIN);\n    ZerocoinParams *ZCParams = Params().Zerocoin_Params();\n    (void)ZCParams;\n\n    std::vector<uint256> msghashList;\n    std::vector<PrivateCoin> coinList;\n    std::vector<Commitment> commitmentList;\n    std::vector<uint256> msghashList2;\n    std::vector<PrivateCoin> coinList2;\n    std::vector<SerialNumberSoK_small> sigList;\n    std::vector<libzerocoin::SerialNumberSoKProof> vProofs_threaded;\n    std::vector<Commitment> commitmentList2;\n\n    for(unsigned int k=start; k<=end; k=k+step) {\n        // create k random message hashes\n        for(unsigned int i=0; i<step; i++) {\n            CBigNum rbn = CBigNum::randBignum(256);\n            msghashList.push_back(rbn.getuint256());\n        }\n\n        // mint k coins\n        for(unsigned int i=0; i<step; i++) {\n            PrivateCoin newCoin(ZCParams, CoinDenomination::ZQ_TEN, true);\n            coinList.push_back(newCoin);\n        }\n\n        // commit to these coins\n        for(unsigned int i=0; i<step; i++) {\n            const CBigNum newCoin_value = coinList[i].getPublicCoin().getValue();\n            Commitment commitment(&(ZCParams->serialNumberSoKCommitmentGroup), newCoin_value);\n            commitmentList.push_back(commitment);\n        }\n\n        // WRONG (random) assignments\n        // random messages\n        CBigNum rbn = CBigNum::randBignum(256);\n        msghashList2.push_back(rbn.getuint256());\n\n        // random coins\n        PrivateCoin newCoin(ZCParams, CoinDenomination::ZQ_TEN, true);\n        coinList2.push_back(newCoin);\n\n        // commit to these coins\n        const CBigNum newCoin_value = coinList2[0].getPublicCoin().getValue();\n        Commitment commitment(&(ZCParams->serialNumberSoKCommitmentGroup), newCoin_value);\n        commitmentList2.push_back(commitment);\n\n        std::cout << \"- Creating array of \" << k << \" Signatures of Knowledge...\\n\";\n\n        // create k signatures of knowledge\n\n        int64_t start_time = GetTimeMillis();\n        for(unsigned int i=0; i<step; i++) {\n            SerialNumberSoK_small sigOfKnowledge(ZCParams, coinList[i], commitmentList[i], msghashList[i]);\n            sigList.push_back(sigOfKnowledge);\n        }\n\n        printTime(start_time, 0);\n        std::cout << \"- Packing and serializing the Signatures...\" << std::endl;\n\n        // pack the signatures of knowledge (honest prover)\n        for(unsigned int i=0; i<step; i++) {\n            libzerocoin::SerialNumberSoKProof* p = new SerialNumberSoKProof(sigList[i], coinList[i].getSerialNumber(), commitmentList[i].getCommitmentValue(), msghashList[i]);\n            vProofs_threaded.emplace_back(*p);\n        }\n\n        // pack the signatures of knowledge (wrong msghash)\n        auto vProofs_threaded2 = vProofs_threaded;\n        libzerocoin::SerialNumberSoKProof* p_badmsg = new SerialNumberSoKProof(sigList[0], coinList[0].getSerialNumber(), commitmentList[0].getCommitmentValue(), msghashList2[0]);\n        vProofs_threaded2.emplace_back(*p_badmsg);\n\n        // pack the signatures of knowledge (wrong commitment)\n        //   Test with only one bad element inserted at the front (should be single thread failure)\n        auto vProofs_threaded3 = vProofs_threaded;\n        libzerocoin::SerialNumberSoKProof* p_badsig = new SerialNumberSoKProof(sigList[0], coinList[0].getSerialNumber(), commitmentList2[0].getCommitmentValue(), msghashList[0]);\n        vProofs_threaded3[0] = *p_badsig;\n\n        // pack the signatures of knowledge (wrong coin and commitment)\n        //   Test with only one bad element inserted at the end (should be single thread failure)\n        auto vProofs_threaded4 = vProofs_threaded;\n        libzerocoin::SerialNumberSoKProof* p = new SerialNumberSoKProof(sigList[0], coinList[0].getSerialNumber(), commitmentList2[0].getCommitmentValue(), msghashList2[0]);\n        vProofs_threaded4.emplace_back(*p);\n\n        //Add a bad proof into a random spot\n        auto vProofs_threaded5 = vProofs_threaded;\n        vProofs_threaded5[k - 1] = *p_badmsg;\n\n        start_time = GetTimeMillis();\n        finalResult = finalResult & Test_threadedBatchVerify(&vProofs_threaded, 3);\n        printTime(start_time, vProofs_threaded.size());\n\n        start_time = GetTimeMillis();\n        finalResult = finalResult & Test_threadedBatchVerify(&vProofs_threaded2, 3, true);\n        printTime(start_time, vProofs_threaded2.size());\n\n        start_time = GetTimeMillis();\n        finalResult = finalResult & Test_threadedBatchVerify(&vProofs_threaded3, 3, true);\n        printTime(start_time, vProofs_threaded3.size());\n\n        start_time = GetTimeMillis();\n        finalResult = finalResult & Test_threadedBatchVerify(&vProofs_threaded4, 3, true);\n        printTime(start_time, vProofs_threaded4.size());\n\n        start_time = GetTimeMillis();\n        finalResult = finalResult & Test_threadedBatchVerify(&vProofs_threaded5, 3, true);\n        printTime(start_time, vProofs_threaded5.size());\n    }\n    std::cout << std::endl;\n    return finalResult;\n}\n\n\nBOOST_AUTO_TEST_SUITE(zerocoin_zkp_tests)\n\nBOOST_AUTO_TEST_CASE(bulletproofs_tests)\n{\n    std::cout << std::endl;\n    RandomInit();\n    ECC_Start();\n    BOOST_CHECK(parameters_tests());\n    BOOST_CHECK(arithmetic_circuit_tests());\n    BOOST_CHECK(polynomial_commitment_tests());\n    BOOST_CHECK(batch_signature_of_knowledge_tests(8, 24, 8));\n    std::cout << std::endl << zSuccessfulTests << \" out of \" << zNumTests << \" tests passed.\" << std::endl << std::endl;\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "52d385b995b76a3d637d92f6c7c8b88f76e603b0", "size": 22102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/zerocoin_zkp_tests.cpp", "max_stars_repo_name": "blondfrogs/veil", "max_stars_repo_head_hexsha": "249cee76d69c3f057acd156c5ab4b76ae795df9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-20T21:44:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-20T21:44:50.000Z", "max_issues_repo_path": "src/test/zerocoin_zkp_tests.cpp", "max_issues_repo_name": "blondfrogs/veil", "max_issues_repo_head_hexsha": "249cee76d69c3f057acd156c5ab4b76ae795df9c", "max_issues_repo_licenses": ["MIT"], "max_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/zerocoin_zkp_tests.cpp", "max_forks_repo_name": "blondfrogs/veil", "max_forks_repo_head_hexsha": "249cee76d69c3f057acd156c5ab4b76ae795df9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T22:55:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-13T00:45:42.000Z", "avg_line_length": 39.0494699647, "max_line_length": 179, "alphanum_fraction": 0.6333815944, "num_tokens": 5876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262966, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5396158048507691}}
{"text": "#include \"Classes.h\"\n#include <Eigen/Dense>\n#include <fstream>\n#include <cstdlib>\nusing namespace Eigen;\n\nPlaneProjection* Object3D::project3D(double projectionPlane[4]) {\n    ///\n    /// General Function to project the current 3D object onto the projection plane passed as parameter \"projectionPlane\"\n    ///\n    // cout << \"Check\"<<endl; // --------Remove\n    // vector<Point> projectedVertices(len); --------Remove\n    bool checkinput=check3dobject();\n    vector<bool> isHidden;\n    vector<int> isHiddenEdge;\n    int len = vertices.size();    \n    // Before anything else, make all faces cyclic\n    for(int i = 0; i < this->faces.size(); i++) {\n        // cout << \"Operating over \" << faces[i];\n        faces[i] = getCyclicFace(faces[i]);\n        // cout << \" Got this face: \" << faces[i] << endl;\n    }\n    // cout << \"Cyclic Faces: \";\n    // for(int i = 0; i < this->faces.size(); i++) {\n    //     cout << faces[i];\n    // }\n    // cout << endl;\n    // Iteration to find all the projected vertices\n    for (int i = 0; i < len; i++) {\n        projectedVertices.push_back(vertices[i].projectPoint(projectionPlane));\n    }\n    cout << \"vertices projected \"<<endl;\n    // Now, we check if any of the vertices is hidden or not\n    for (int i = 0; i < len; i++) {\n        // cout << vertices[i].x << vertices[i].y << vertices[i].z << endl; -------Remove\n        int flag = 0;\n        for (int j = 0; j < this->faces.size(); j++) {\n            if(checkHiddenVertice(vertices[i],faces[j],projectionPlane,0))\n            {\n                flag = 1;\n                break;\n            }\n        }\n        if(flag==1)\n            isHidden.push_back(true);\n        else\n            isHidden.push_back(false);\n    }\n    cout << \"Vertices Done\" << endl; \n    // Next, we check for each edge, if it is hidden or not\n    /* Note: If a part of an edge is hidden then the edge is replaced by the first part \n       and the remaining part is added in the edges vector of the Object3D object */\n    for (auto i = 0; i < this->edges.size(); i++) {\n        int flag = 0;   \n        for (int j = 0; j < this->faces.size(); j++) {\n            // cout << \"Calling CHE \" << j <<  endl;\n            if(checkHiddenEdge(this->edges[i],faces[j],projectionPlane,i))\n            {\n                flag = 1;\n                break;\n            }\n        }\n        isHiddenEdge.push_back(flag);\n        // cout << i << \" \" << edges[i] << \":\" << flag << isHiddenEdge[i] << isHiddenEdge.size() << endl;\n    }\n    cout << \"Edges Done\" << endl;\n    // The vectors isHidden and isHiddenEdge store whether or not a point/edge is hidden.\n    // This can be used to generate an OrthoProjection object that can be returned from this function.\n    PlaneProjection* projection = new PlaneProjection;\n    for (int i = 0; i < 4; i++) {\n        projection->normal[i] = projectionPlane[i];\n    }\n    for (auto i = 0; i < projectedVertices.size(); i++) {\n        projection->vertices.push_back(projectedVertices[i]);\n    }\n    for (auto i = 0; i < this->edges.size(); i++) {\n        Edge edge;\n        edge.p1 = this->edges[i].p1.projectPoint(projectionPlane);\n        edge.p2 = this->edges[i].p2.projectPoint(projectionPlane);\n        if(isHiddenEdge[i])\n            projection->hiddenEdges.push_back(edge);\n        else\n            projection->visibleEdges.push_back(edge);\n    }\n    cout << \"project3D done\" << endl;\n    return projection;\n}\n\nint countIntersections(Vector3d avertice,Vector3d bvertice,Vector3d dvertice,Vector3d evertice,Vector3d linevector){\n    ///\n    /// Function to count intersections of the line originating from avertice in the direction of linevector, \n    /// with the edges of a polygon, formed using bvertice, dvertice, evertice\n    ///\n    int retValue = 0;\n    Vector3d zerovector(0,0,0);\n    Vector3d abvector = bvertice - avertice;\n    Vector3d acvector = linevector;\n    Vector3d advector = dvertice - avertice;\n    Vector3d aevector = evertice - avertice;\n    Vector3d t1 = abvector.cross(acvector);\n    Vector3d t2 = advector.cross(acvector);\n    Vector3d t3 = abvector.cross(advector);\n    Vector3d t6 = aevector.cross(acvector);\n    double t4 = t1.dot(t2);\n    double t5 = t1.dot(t3);\n    double t7 = t6.dot(t2);\n    double abdotac = abvector.dot(acvector);\n    if(t1==zerovector || t2==zerovector){\n        // Do Nothing\n    }else if((t4<=0) && (t5>=0)){\n        retValue = 1;\n    }\n    if(t1==zerovector && abdotac>0){\n        if(t7<=0)\n            retValue = 2;\n        else\n            retValue = 3;\n    }\n    return retValue;\n}\n\nVector3d intersectLines(Point a,Point b,Vector3d c,Vector3d d) {\n    Vector3d retVal;\n    Vector3d av(a.x,a.y,a.z);\n    Vector3d bv(b.x,b.y,b.z);\n    Vector3d f = bv-av;\n    Vector3d e = d-c;\n    Vector3d g = c-av;\n    Vector3d fcrossg = f.cross(g);\n    Vector3d fcrosse = f.cross(e);\n    double h = abs(fcrossg.norm());\n    double k = abs(fcrosse.norm());\n    if(fcrossg.dot(fcrosse)>0){\n        retVal = c + (h/k)*e;\n    }else{\n        retVal = c - (h/k)*e;\n    }\n    return retVal;\n}\n\nbool Object3D::rayCasting(Point point, vector<Point> polygon) {\n    ///\n    /// Function that returns if the Point \"point\" lies within the polygon formed by the Face \"polygon\", passed as parameter.\n    ///\n    int numverticesinpolygon = polygon.size();\n    // cout<< \"num of points in polygon is \"<< numverticesinpolygon<<endl;\n    int flag = 0;\n    for(int i = 0; i < numverticesinpolygon; i++) {\n        if(point.x==polygon[i].x && point.y==polygon[i].y  && point.z==polygon[i].z ){\n            flag = 1;\n            break;\n        }\n    }\n    if(flag==1)\n        return true;\n    Vector3d avertice;\n    avertice << point.x, point.y, point.z;\n    int numintersections = 0;\n    Vector3d zerovector(0,0,0);\n    Vector3d icap(1,0,0);\n    Vector3d jcap(0,1,0);\n    Vector3d startone;\n    startone << polygon[0].x, polygon[0].y, polygon[0].z;\n    Vector3d secondone;\n    secondone << polygon[1].x, polygon[1].y, polygon[1].z;\n    Vector3d thirdone;\n    thirdone << polygon[2].x, polygon[2].y, polygon[2].z;\n    Vector3d firstvector = secondone-startone;\n    Vector3d secondvector = thirdone-secondone;\n    Vector3d perpendicular = firstvector.cross(secondvector);\n    Vector3d linevector = perpendicular.cross(icap);\n\n    double checkzero = linevector.dot(linevector);\n    if(checkzero==0){\n        linevector = perpendicular.cross(jcap);\n    }\n    // Vector3d linevector(1,1,0);\n    int i=0;\n    for(auto it= polygon.begin();it!=polygon.end();it++){\n        Point thisone = *it;\n        Point nextone,prevone;\n        if(i==numverticesinpolygon-1){\n            prevone = *(it-1);\n            nextone = polygon.front();\n        }else if(i==0){\n            prevone = polygon.back();\n            nextone = *(it+1);\n        }else{\n            prevone = *(it-1);\n            nextone = *(it+1);\n        }\n        //Point nextone = *(it + 1);\n        Vector3d bvertice;\n        bvertice << thisone.x, thisone.y, thisone.z;\n        Vector3d dvertice;\n        dvertice << nextone.x,nextone.y, nextone.z;\n        Vector3d evertice;\n        evertice << prevone.x, prevone.y, prevone.z;\n        int ci = countIntersections(avertice,bvertice,dvertice,evertice,linevector);\n        if(ci==0){\n            // Do Nothing\n        }else if(ci==1 || ci==2){\n            numintersections = numintersections +1;\n        }else if(ci==3){\n            numintersections = numintersections + 2;            \n        }\n        i++;\n    }\n    // cout<< \"numintersections is \"<< numintersections<<endl;\n    if(numintersections%2==1){\n        return true;\n    }else{\n        return false;\n    }\n}\n\nbool Object3D::checkHiddenVertice(Point vertex, Face face, double plane[4], int predicate) {\n    ///\n    /// Function to check if the Point passed as parameter \"vertex\" is hidden by the face, \n    /// which is passed in the parameter \"face\", the projection being taken on the plane \"plane\"\n    ///\n    bool retValue = false;\n    Vector3d point1(vertices[face.vertices[0]].x,vertices[face.vertices[0]].y,vertices[face.vertices[0]].z);\n    Vector3d point2(vertices[face.vertices[1]].x,vertices[face.vertices[1]].y,vertices[face.vertices[1]].z);\n    Vector3d point3(vertices[face.vertices[2]].x,vertices[face.vertices[2]].y,vertices[face.vertices[2]].z);\n    Vector3d dir1 = (point3-point1);\n    Vector3d dir2 = (point2-point1);\n    Vector3d normal = dir1.cross(dir2);\n    double facePlane[4] = {normal.x(),normal.y(),normal.z(),normal.dot(point1)};\n    vector<Point> faceProject;\n    for (int i = 0; i < face.vertices.size(); i++) {\n        faceProject.push_back(projectedVertices[face.vertices[i]]);\n    }\n    // cout << \"Face Projected\" << endl;\n    Point projectedVertex = vertex.projectPoint(plane);\n    if(rayCasting(projectedVertex,faceProject)) {\n        if(predicate==0) {\n            if(vertex.relativePosition(facePlane)*projectedVertex.relativePosition(facePlane) >= 0)\n                retValue = false;\n            else\n                retValue = true;\n        }else{\n            if(vertex.relativePosition(facePlane)*projectedVertex.relativePosition(facePlane) > 0)\n                retValue = false;\n            else\n                retValue = true;\n        }\n    }\n    // cout << \"retvalue is \" << retValue << endl;\n    return retValue;\n}\n\nbool Object3D::checkHiddenEdge(Edge edge, Face face, double plane[4], int index) {\n    ///\n    /// Function to evaluate if the Edge \"edge\", passed as parameter is hidden by the face, \n    /// whose projection on the plane \"plane\" is passed as argument \"face\"\n    ///\n    cout << \"In CHE\" << endl;\n    bool retValue = false;\n    Point p1 = edge.p1;\n    Point p2 = edge.p2;\n    auto it1 = find_if(this->vertices.begin(), this->vertices.end(), \n        [p1](Point p) -> bool {return (p.x==p1.x && p.y==p1.y && p.z==p1.z);});\n    auto it2 = find_if(this->vertices.begin(), this->vertices.end(), \n        [p2](Point p) -> bool {return (p.x==p2.x && p.y==p2.y && p.z==p2.z);});\n    int index1,index2;\n    if(it1 != vertices.end())\n        index1 = distance(vertices.begin(),it1);\n    if(it2 != vertices.end())\n        index2 = distance(vertices.begin(),it2);\n    auto itin1 = find(face.vertices.begin(),face.vertices.end(),index1);\n    auto itin2 = find(face.vertices.begin(),face.vertices.end(),index2);\n    if (itin1 != face.vertices.end() && itin2 != face.vertices.end())\n        return false;\n    // If both endpoints are on the face, it isn't hidden.\n    Point projectp1 = edge.p1.projectPoint(plane);\n    Point projectp2 = edge.p2.projectPoint(plane);\n    vector<Point> faceProject;\n    for (int i = 0; i < face.vertices.size(); i++) {\n        faceProject.push_back(projectedVertices[face.vertices[i]]);\n    }\n    if(rayCasting(projectp1,faceProject)) {\n        if(checkHiddenVertice(edge.p1,face,plane,1)) {\n            // Evaluate the point of intersection of edge with the polygon faceProject\n            // cout << \"First point is hidden.\"; // -------Remove\n            Vector3d avertice(projectp1.x,projectp1.y,projectp1.z);\n            Vector3d endvertice(projectp2.x,projectp2.y,projectp2.z);\n            Vector3d linevector(projectp2.x-projectp1.x,projectp2.y-projectp1.y,projectp2.z-projectp1.z);\n            vector<Vector3d> intersections;\n            vector<Point> polygon;\n            for(int i = 0; i < face.vertices.size(); i++) {\n                polygon.push_back(this->projectedVertices[face.vertices[i]]);\n                // pointIndex.push_back(face.vertices[i]);\n            }\n            int i=0, numverticesinpolygon=polygon.size();\n            for(auto it= polygon.begin();it!=polygon.end();it++){\n                Point thisone = *it;\n                Point nextone,prevone;\n                if(i==numverticesinpolygon-1){\n                    prevone = *(it-1);\n                    nextone = polygon.front();\n                }else if(i==0){\n                    prevone = polygon.back();\n                    nextone = *(it+1);\n                }else{\n                    prevone = *(it-1);\n                    nextone = *(it+1);\n                }\n                //Point nextone = *(it + 1);\n                Vector3d bvertice;\n                bvertice << thisone.x, thisone.y, thisone.z;\n                Vector3d dvertice;\n                dvertice << nextone.x,nextone.y, nextone.z;\n                Vector3d evertice;\n                evertice << prevone.x, prevone.y, prevone.z;\n                int ci = countIntersections(avertice,bvertice,dvertice,evertice,linevector);\n                if(ci==2 || ci==3){\n                    intersections.push_back(bvertice);\n                }else if(ci==1){\n                    // Intersects (bvertice,dvertice) in the middle somewhere  \n                    Vector3d intersection = intersectLines(edge.p1,edge.p2,bvertice,dvertice);\n                    cout << \"Between \" << edge << \" and \" << bvertice << \", \" << dvertice << endl; // ---------Remove\n                    intersections.push_back(intersection);\n                }\n                i++;\n            }\n            // All intersections of the edge have been taken with the face, and are stored in intersections\n            Vector3d closestIntersection;\n            if(intersections.size()==1){\n                closestIntersection = intersections[0];\n            }else if(intersections.size()!=0){\n                closestIntersection = *min_element(intersections.begin(),intersections.end(),\n                [avertice] (Vector3d v1, Vector3d v2) -> bool {return (avertice-v1).norm()<(avertice-v2).norm();});\n            }\n            if(intersections.size()!=0) {\n                // cout << \"Intersection found.\"; -------Remove\n                if(closestIntersection.x()==projectp2.x && closestIntersection.y()==projectp2.y && closestIntersection.z()==projectp2.z){\n                    if(checkHiddenVertice(edge.p2,face,plane,1))\n                        retValue = true;\n                    else\n                        retValue = false;\n                }else{\n                    // The vector closestIntersection holds the closest point of intersection, from p1\n                    // This point is on the projected plane, and we must find the corresponding point in 3D \n                    Vector3d thirdPoint;\n                    double d1 = (closestIntersection-avertice).norm();\n                    double d2 = (endvertice-closestIntersection).norm();\n                    Vector3d p1(edge.p1.x,edge.p1.y,edge.p1.z);\n                    Vector3d p2(edge.p2.x,edge.p2.y,edge.p2.z);\n                    thirdPoint = (d1*p2 + d2*p1)/(d1+d2);\n                    // cout << \"Inserting new element \" << thirdPoint << endl; --------Remove\n                    Point newPoint,newPointProjected;\n                    newPoint.setCoordinates(thirdPoint.x(),thirdPoint.y(),thirdPoint.z());\n                    newPointProjected.setCoordinates(closestIntersection.x(),closestIntersection.y(),closestIntersection.z());\n                    Edge segment;\n                    segment.p1.setCoordinates(thirdPoint.x(),thirdPoint.y(),thirdPoint.z());\n                    segment.p2.setCoordinates(edge.p2.x,edge.p2.y,edge.p2.z); \n                    edge.p2.setCoordinates(thirdPoint.x(),thirdPoint.y(),thirdPoint.z());\n                    this->edges.insert(this->edges.begin()+index+1,segment);\n                    this->vertices.push_back(newPoint);\n                    this->projectedVertices.push_back(newPointProjected);\n                    retValue = true;\n                }\n            }else{\n                retValue = checkHiddenVertice(edge.p2,face,plane,1);\n            }\n        }else{\n            if(checkHiddenVertice(edge.p2,face,plane,0)) {\n                retValue = true;\n            }else{\n                retValue = false;\n            }\n        }\n    }\n    // if(retValue) \n    //     cout << edge << \" is hidden by the face formed by: \" << face << endl;\n    // else\n    //     cout << edge << \" is not hidden by the face formed by: \" << face << endl; // -------Remove\n    return retValue;\n}\n\nFace Object3D::getCyclicFace(Face face) {\n    ///\n    /// Function that reeturns the face with the vertices, re-arranged so that a cyclic order is maintained\n    ///\n    vector<int> pointIndex;\n    Face newFace;\n    for(int i = 0; i < face.vertices.size(); i++) {\n        // polygon.push_back(this->projectedVertices[face.vertices[i]]);\n        pointIndex.push_back(face.vertices[i]);\n    }\n    int i=0, numverticesinpolygon=face.vertices.size();\n    bool done = false;\n    Vector3d edge1(vertices[face.vertices[1]].x-vertices[face.vertices[0]].x,vertices[face.vertices[1]].y-vertices[face.vertices[0]].y,vertices[face.vertices[1]].z-vertices[face.vertices[0]].z);\n    Vector3d edge2(vertices[face.vertices[2]].x-vertices[face.vertices[1]].x,vertices[face.vertices[2]].y-vertices[face.vertices[1]].y,vertices[face.vertices[2]].z-vertices[face.vertices[1]].z);\n    Vector3d normalToFace = edge1.cross(edge2);\n    for(int i = 0; i < numverticesinpolygon; i++) {\n        if(i==0){\n            newFace.vertices.push_back(pointIndex[0]);\n        }else if(i==1){\n            int index = newFace.vertices[0];\n            Point p = this->vertices[index];\n            auto it = find_if(this->edges.begin(), this->edges.end(), \n                [p,normalToFace](Edge e) -> bool {\n                    bool retVal = false;\n                    if ((p.x==e.p1.x && p.y==e.p1.y && p.z==e.p1.z) || (p.x==e.p2.x && p.y==e.p2.y && p.z==e.p2.z)){\n                        Vector3d edge(e.p1.x-e.p2.x,e.p1.y-e.p2.y,e.p1.z-e.p2.z);\n                        if(edge.dot(normalToFace)==0){\n                            retVal = true;\n                        }\n                    }\n                    return retVal;});\n            Point neighbor;\n            Edge e = *it;\n            if(p.x==e.p1.x && p.y==e.p1.y && p.z==e.p1.z)\n                neighbor = e.p2;\n            else\n                neighbor = e.p1;\n            auto it1 = find_if(this->vertices.begin(), this->vertices.end(), \n                [neighbor](Point p) -> bool {return (p.x==neighbor.x && p.y==neighbor.y && p.z==neighbor.z);});\n            int index1;\n            if(it1 != vertices.end())\n                index1 = distance(vertices.begin(),it1);\n            newFace.vertices.push_back(index1);\n        }else{\n            int index = newFace.vertices[i-1];\n            int prevIndex = newFace.vertices[i-2];\n            Point p = this->vertices[index];\n            Point prevp = this->vertices[prevIndex];\n            auto it = find_if(this->edges.begin(), this->edges.end(), \n                [p,prevp,normalToFace](Edge e) -> bool {\n                    bool retVal = false;\n                    if ((p.x==e.p1.x && p.y==e.p1.y && p.z==e.p1.z) || (p.x==e.p2.x && p.y==e.p2.y && p.z==e.p2.z)){\n                        Vector3d edge(e.p1.x-e.p2.x,e.p1.y-e.p2.y,e.p1.z-e.p2.z);\n                        if(edge.dot(normalToFace)==0){\n                            if((p.x==e.p1.x && p.y==e.p1.y && p.z==e.p1.z) && !(prevp.x==e.p2.x && prevp.y==e.p2.y && prevp.z==e.p2.z)){\n                                retVal = true;\n                            }else if((p.x==e.p2.x && p.y==e.p2.y && p.z==e.p2.z) && !(prevp.x==e.p1.x && prevp.y==e.p1.y && prevp.z==e.p1.z)){\n                                retVal = true;\n                            }\n                        }\n                    }\n                    return retVal;});\n            Point neighbor;\n            Edge e = *it;\n            if(p.x==e.p1.x && p.y==e.p1.y && p.z==e.p1.z)\n                neighbor = e.p2;\n            else\n                neighbor = e.p1;\n            auto it1 = find_if(this->vertices.begin(), this->vertices.end(), \n                [neighbor](Point p) -> bool {return (p.x==neighbor.x && p.y==neighbor.y && p.z==neighbor.z);});\n            int index1;\n            if(it1 != vertices.end())\n                index1 = distance(vertices.begin(),it1);\n            newFace.vertices.push_back(index1);\n        }\n    }\n    return newFace;\n}\n\nbool Object3D::check3dobject(){\n    ///\n    /// Function to check the validity of input file, by rendering the Object in OpenScad\n    ///\n    try{\n        ofstream scadfile (\"object.scad\");\n        if(scadfile.is_open()){\n            // scadfile<< \"cube([2,3,9]);\";\n            scadfile <<\"ObjectPoints = [\\n\";\n            int numpoints = vertices.size();\n            for(int i=0;i<numpoints;i++){\n                Point temp = vertices[i];\n                scadfile<<\"    [ \"<<temp.x<<\", \"<<temp.y<<\", \"<<temp.z<<\" ]\";\n                if(i!=numpoints-1){\n                    scadfile<<\",\";\n                }else{\n                    scadfile<<\"];\";\n                }\n                scadfile<<  \"  //\"<<i<<\"\\n\";\n            }\n            scadfile <<\"\\n\";\n            scadfile << \"ObjectFaces = [\\n\";\n            int numfaces = faces.size();\n            for(int i=0;i<numfaces;i++){\n                scadfile<<\"[\";\n                for(int j=0;j<faces[i].vertices.size();j++){\n                    scadfile<<faces[i].vertices[j];\n                    if(j!=faces[i].vertices.size()-1){\n                        scadfile<<\",\";\n                    }\n                }\n                scadfile<< \"]\";\n                if(i!=numfaces-1){\n                    scadfile<<\",\\n\";\n                }else{\n                    scadfile<<\"];\\n\";\n                }\n            }\n            scadfile<< \"polyhedron( ObjectPoints, ObjectFaces );\";\n            scadfile.close();\n            system(\"openscad -o object.stl object.scad\");\n            ofstream renderfile (\"render.scad\");\n            if(renderfile.is_open()){\n                renderfile<< \"render(){import(\\\"object.stl\\\");}\";\n                renderfile.close();\n                system(\"openscad render.scad\");\n            }else{\n                cout<< \"unable to render the stl\";\n            }\n        }else{\n            cout<< \"unable to open file\"<<endl;\n        }\n        return true;\n    }catch(...){\n        return false;\n    }\n}", "meta": {"hexsha": "f38090b1f8d7c1229d4f173cc3d65f5ebd6ec91c", "size": 21883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Object3D.cpp", "max_stars_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_stars_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-03-04T18:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T23:07:12.000Z", "max_issues_repo_path": "src/Object3D.cpp", "max_issues_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_issues_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Object3D.cpp", "max_forks_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_forks_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-02-09T10:55:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-28T08:53:33.000Z", "avg_line_length": 42.3268858801, "max_line_length": 194, "alphanum_fraction": 0.5352099804, "num_tokens": 5594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262966, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5396157934077647}}
{"text": "#include <three-dim-util/camera.hpp>\n#include <Eigen/Geometry>\n\nnamespace threedimutil\n{\n    using namespace Eigen;\n\n    Camera::Camera() :\n    m_position(- 2.0, 0.0, 3.0),\n    m_target(0.0, 0.0, 0.0),\n    m_up(0.0, 1.0, 0.0),\n    m_mode(Mode::None)\n    {\n    }\n\n    void Camera::RotateAroundTarget(double theta_in_radian)\n    {\n        // Horizontal rotation\n        const Matrix3d rot_h = AngleAxisd(theta_in_radian, m_up).matrix();\n\n        // Update the camera position\n        m_position = m_target + rot_h * (m_position - m_target);\n    }\n\n    void Camera::BeginTrackball(int x, int y, Mode mode)\n    {\n        m_mode = mode;\n        m_prev_position = Vector2i(x, y);\n    }\n\n    void Camera::MoveTrackball(int x, int y)\n    {\n        constexpr double scale_x = 2000.0;\n        constexpr double scale_y = 2000.0;\n\n        switch (m_mode)\n        {\n            case Mode::None:\n                break;\n            case Mode::Pan:\n            {\n                const Vector3d eye      = m_position - m_target;\n                const Vector3d left_dir = eye.cross(m_up);\n                const double   len      = eye.norm();\n                const double   diff_x   = static_cast<double>(x - m_prev_position(0)) / scale_x;\n                const double   diff_y   = static_cast<double>(y - m_prev_position(1)) / scale_y;\n                const Vector3d trans_x  = len * diff_x * left_dir.normalized();\n                const Vector3d trans_y  = len * diff_y * m_up.normalized();\n                m_position += trans_x;\n                m_position += trans_y;\n                m_target   += trans_x;\n                m_target   += trans_y;\n                break;\n            }\n            case Mode::Rotate:\n            {\n                const double theta_x = (2.0 * M_PI * static_cast<double>(x - m_prev_position(0))) / scale_x;\n                const double theta_y = (2.0 * M_PI * static_cast<double>(y - m_prev_position(1))) / scale_y;\n\n                // Horizontal rotation\n                const Matrix3d rot_h = AngleAxisd(- theta_x, m_up).matrix();\n                Vector3d eye = m_position - m_target;\n\n                // Vertical rotation\n                const Vector3d left_dir = eye.cross(m_up).normalized();\n                const Matrix3d rot_v    = AngleAxisd(theta_y, left_dir).matrix();\n\n                const double test = left_dir.dot((rot_v * eye).cross(m_up));\n                if (test > 0.0) {\n                    eye = rot_v * rot_h * eye;\n                }\n\n                m_position = m_target + eye;\n                break;\n            }\n            case Mode::Zoom:\n            {\n                constexpr double scale = 0.5;\n\n                const double   speed   = static_cast<double>(y - m_prev_position(1)) / scale_y;\n                const Vector3d eye_ray = speed * (m_target - m_position);\n                m_position += scale * eye_ray;\n                break;\n            }\n            default:\n                break;\n        }\n\n        m_prev_position = Vector2i(x, y);\n    }\n\n    void Camera::EndTrackball()\n    {\n        m_mode = Mode::None;\n    }\n}\n\nEigen::Matrix4d threedimutil::Camera::GetLookAtMatrix() const\n{\n    Eigen::Matrix4d mat = Eigen::Matrix4d::Identity();\n\n    const Eigen::Vector3d forward = (m_target - m_position).normalized();\n    const Eigen::Vector3d side    = forward.cross(m_up).normalized();\n    const Eigen::Vector3d up      = side.cross(forward);\n\n    mat.block<1, 3>(0, 0) = side.transpose();\n    mat.block<1, 3>(1, 0) = up.transpose();\n    mat.block<1, 3>(2, 0) = - forward.transpose();\n    mat(0, 3) = - side.dot(m_position);\n    mat(1, 3) = - up.dot(m_position);\n    mat(2, 3) = forward.dot(m_position);\n\n    return mat;\n}\n", "meta": {"hexsha": "7d65945ba0ba672008932993915149114688e152", "size": 3679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/camera.cpp", "max_stars_repo_name": "yuki-koyama/3d-util", "max_stars_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-10-13T15:16:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T06:07:55.000Z", "max_issues_repo_path": "src/camera.cpp", "max_issues_repo_name": "yuki-koyama/3d-util", "max_issues_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-05-14T00:34:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-20T13:50:42.000Z", "max_forks_repo_path": "src/camera.cpp", "max_forks_repo_name": "yuki-koyama/3d-util", "max_forks_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T07:36:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T19:42:33.000Z", "avg_line_length": 31.9913043478, "max_line_length": 108, "alphanum_fraction": 0.5297635227, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5395952368851169}}
{"text": "\ufeff// copyright (c) 2012-2014 the dzcoin core developers\n// distributed under the mit software license, see the accompanying\n// file copying or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"bignum.h\"\n#include \"script/script.h\"\n#include \"test/test_dzcoin.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <limits.h>\n#include <stdint.h>\n\nboost_fixture_test_suite(scriptnum_tests, basictestingsetup)\n\nstatic const int64_t values[] = \\\n{ 0, 1, char_min, char_max, uchar_max, shrt_min, ushrt_max, int_min, int_max, uint_max, long_min, long_max };\nstatic const int64_t offsets[] = { 1, 0x79, 0x80, 0x81, 0xff, 0x7fff, 0x8000, 0xffff, 0x10000};\n\nstatic bool verify(const cbignum& bignum, const cscriptnum& scriptnum)\n{\n    return bignum.getvch() == scriptnum.getvch() && bignum.getint() == scriptnum.getint();\n}\n\nstatic void checkcreatevch(const int64_t& num)\n{\n    cbignum bignum(num);\n    cscriptnum scriptnum(num);\n    boost_check(verify(bignum, scriptnum));\n\n    cbignum bignum2(bignum.getvch());\n    cscriptnum scriptnum2(scriptnum.getvch(), false);\n    boost_check(verify(bignum2, scriptnum2));\n\n    cbignum bignum3(scriptnum2.getvch());\n    cscriptnum scriptnum3(bignum2.getvch(), false);\n    boost_check(verify(bignum3, scriptnum3));\n}\n\nstatic void checkcreateint(const int64_t& num)\n{\n    cbignum bignum(num);\n    cscriptnum scriptnum(num);\n    boost_check(verify(bignum, scriptnum));\n    boost_check(verify(bignum.getint(), cscriptnum(scriptnum.getint())));\n    boost_check(verify(scriptnum.getint(), cscriptnum(bignum.getint())));\n    boost_check(verify(cbignum(scriptnum.getint()).getint(), cscriptnum(cscriptnum(bignum.getint()).getint())));\n}\n\n\nstatic void checkadd(const int64_t& num1, const int64_t& num2)\n{\n    const cbignum bignum1(num1);\n    const cbignum bignum2(num2);\n    const cscriptnum scriptnum1(num1);\n    const cscriptnum scriptnum2(num2);\n    cbignum bignum3(num1);\n    cbignum bignum4(num1);\n    cscriptnum scriptnum3(num1);\n    cscriptnum scriptnum4(num1);\n\n    // int64_t overflow is undefined.\n    bool invalid = (((num2 > 0) && (num1 > (std::numeric_limits<int64_t>::max() - num2))) ||\n                    ((num2 < 0) && (num1 < (std::numeric_limits<int64_t>::min() - num2))));\n    if (!invalid)\n    {\n        boost_check(verify(bignum1 + bignum2, scriptnum1 + scriptnum2));\n        boost_check(verify(bignum1 + bignum2, scriptnum1 + num2));\n        boost_check(verify(bignum1 + bignum2, scriptnum2 + num1));\n    }\n}\n\nstatic void checknegate(const int64_t& num)\n{\n    const cbignum bignum(num);\n    const cscriptnum scriptnum(num);\n\n    // -int64_min is undefined\n    if (num != std::numeric_limits<int64_t>::min())\n        boost_check(verify(-bignum, -scriptnum));\n}\n\nstatic void checksubtract(const int64_t& num1, const int64_t& num2)\n{\n    const cbignum bignum1(num1);\n    const cbignum bignum2(num2);\n    const cscriptnum scriptnum1(num1);\n    const cscriptnum scriptnum2(num2);\n    bool invalid = false;\n\n    // int64_t overflow is undefined.\n    invalid = ((num2 > 0 && num1 < std::numeric_limits<int64_t>::min() + num2) ||\n               (num2 < 0 && num1 > std::numeric_limits<int64_t>::max() + num2));\n    if (!invalid)\n    {\n        boost_check(verify(bignum1 - bignum2, scriptnum1 - scriptnum2));\n        boost_check(verify(bignum1 - bignum2, scriptnum1 - num2));\n    }\n\n    invalid = ((num1 > 0 && num2 < std::numeric_limits<int64_t>::min() + num1) ||\n               (num1 < 0 && num2 > std::numeric_limits<int64_t>::max() + num1));\n    if (!invalid)\n    {\n        boost_check(verify(bignum2 - bignum1, scriptnum2 - scriptnum1));\n        boost_check(verify(bignum2 - bignum1, scriptnum2 - num1));\n    }\n}\n\nstatic void checkcompare(const int64_t& num1, const int64_t& num2)\n{\n    const cbignum bignum1(num1);\n    const cbignum bignum2(num2);\n    const cscriptnum scriptnum1(num1);\n    const cscriptnum scriptnum2(num2);\n\n    boost_check((bignum1 == bignum1) == (scriptnum1 == scriptnum1));\n    boost_check((bignum1 != bignum1) ==  (scriptnum1 != scriptnum1));\n    boost_check((bignum1 < bignum1) ==  (scriptnum1 < scriptnum1));\n    boost_check((bignum1 > bignum1) ==  (scriptnum1 > scriptnum1));\n    boost_check((bignum1 >= bignum1) ==  (scriptnum1 >= scriptnum1));\n    boost_check((bignum1 <= bignum1) ==  (scriptnum1 <= scriptnum1));\n\n    boost_check((bignum1 == bignum1) == (scriptnum1 == num1));\n    boost_check((bignum1 != bignum1) ==  (scriptnum1 != num1));\n    boost_check((bignum1 < bignum1) ==  (scriptnum1 < num1));\n    boost_check((bignum1 > bignum1) ==  (scriptnum1 > num1));\n    boost_check((bignum1 >= bignum1) ==  (scriptnum1 >= num1));\n    boost_check((bignum1 <= bignum1) ==  (scriptnum1 <= num1));\n\n    boost_check((bignum1 == bignum2) ==  (scriptnum1 == scriptnum2));\n    boost_check((bignum1 != bignum2) ==  (scriptnum1 != scriptnum2));\n    boost_check((bignum1 < bignum2) ==  (scriptnum1 < scriptnum2));\n    boost_check((bignum1 > bignum2) ==  (scriptnum1 > scriptnum2));\n    boost_check((bignum1 >= bignum2) ==  (scriptnum1 >= scriptnum2));\n    boost_check((bignum1 <= bignum2) ==  (scriptnum1 <= scriptnum2));\n\n    boost_check((bignum1 == bignum2) ==  (scriptnum1 == num2));\n    boost_check((bignum1 != bignum2) ==  (scriptnum1 != num2));\n    boost_check((bignum1 < bignum2) ==  (scriptnum1 < num2));\n    boost_check((bignum1 > bignum2) ==  (scriptnum1 > num2));\n    boost_check((bignum1 >= bignum2) ==  (scriptnum1 >= num2));\n    boost_check((bignum1 <= bignum2) ==  (scriptnum1 <= num2));\n}\n\nstatic void runcreate(const int64_t& num)\n{\n    checkcreateint(num);\n    cscriptnum scriptnum(num);\n    if (scriptnum.getvch().size() <= cscriptnum::nmaxnumsize)\n        checkcreatevch(num);\n    else\n    {\n        boost_check_throw (checkcreatevch(num), scriptnum_error);\n    }\n}\n\nstatic void runoperators(const int64_t& num1, const int64_t& num2)\n{\n    checkadd(num1, num2);\n    checksubtract(num1, num2);\n    checknegate(num1);\n    checkcompare(num1, num2);\n}\n\nboost_auto_test_case(creation)\n{\n    for(size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i)\n    {\n        for(size_t j = 0; j < sizeof(offsets) / sizeof(offsets[0]); ++j)\n        {\n            runcreate(values[i]);\n            runcreate(values[i] + offsets[j]);\n            runcreate(values[i] - offsets[j]);\n        }\n    }\n}\n\nboost_auto_test_case(operators)\n{\n    for(size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i)\n    {\n        for(size_t j = 0; j < sizeof(offsets) / sizeof(offsets[0]); ++j)\n        {\n            runoperators(values[i], values[i]);\n            runoperators(values[i], -values[i]);\n            runoperators(values[i], values[j]);\n            runoperators(values[i], -values[j]);\n            runoperators(values[i] + values[j], values[j]);\n            runoperators(values[i] + values[j], -values[j]);\n            runoperators(values[i] - values[j], values[j]);\n            runoperators(values[i] - values[j], -values[j]);\n            runoperators(values[i] + values[j], values[i] + values[j]);\n            runoperators(values[i] + values[j], values[i] - values[j]);\n            runoperators(values[i] - values[j], values[i] + values[j]);\n            runoperators(values[i] - values[j], values[i] - values[j]);\n        }\n    }\n}\n\nboost_auto_test_suite_end()\n\n\n", "meta": {"hexsha": "a0a941a4a410e34fa060aa3d9d8c0cf480f23c2a", "size": 7231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/scriptnum_tests.cpp", "max_stars_repo_name": "dzcoin/DzCoinMiningAlgorithm", "max_stars_repo_head_hexsha": "b0294cf5ac893fe907b08105f1aa826c3da464cf", "max_stars_repo_licenses": ["MIT"], "max_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/scriptnum_tests.cpp", "max_issues_repo_name": "dzcoin/DzCoinMiningAlgorithm", "max_issues_repo_head_hexsha": "b0294cf5ac893fe907b08105f1aa826c3da464cf", "max_issues_repo_licenses": ["MIT"], "max_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/scriptnum_tests.cpp", "max_forks_repo_name": "dzcoin/DzCoinMiningAlgorithm", "max_forks_repo_head_hexsha": "b0294cf5ac893fe907b08105f1aa826c3da464cf", "max_forks_repo_licenses": ["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.797029703, "max_line_length": 112, "alphanum_fraction": 0.6436177569, "num_tokens": 2123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5395952352526651}}
{"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_MLOGTWO2NMB_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_MLOGTWO2NMB_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    Generates constant Mlogtwo2nmb.\n\n\n    @par Header <boost/simd/constant/mlogtwo2nmb.hpp>\n\n    @par Semantic:\n\n    @code\n    T r = Mlogtwo2nmb<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n      r =  -log(exp2(T(Nbmantissabits<T>())));\n    @endcode\n\n\n**/\n  template<typename T> T Mlogtwo2nmb();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Generates constant Mlogtwo2nmb.\n\n      Generate the  constant mlogtwo2nmb.\n\n      @return The Mlogtwo2nmb constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::mlogtwo2nmb_> mlogtwo2nmb = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/scalar/mlogtwo2nmb.hpp>\n#include <boost/simd/constant/simd/mlogtwo2nmb.hpp>\n\n#endif\n", "meta": {"hexsha": "43a12b18042fe80be394cb5f84aa497988f4f169", "size": 1325, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/mlogtwo2nmb.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "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/mlogtwo2nmb.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "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/mlogtwo2nmb.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 21.0317460317, "max_line_length": 100, "alphanum_fraction": 0.5894339623, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5395952266759322}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2010 - 2021 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 * Authors: Chih-Che Chueh, University of Victoria, 2010 \n *          Wolfgang Bangerth, Texas A&M University, 2010 \n */ \n\n\n// @sect3{Include files}  \n\n// \u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u7b2c\u4e00\u6b65\u662f\u5305\u62ec\u4e00\u4e9bdeal.II\u548cC++\u5934\u6587\u4ef6\u7684\u529f\u80fd\u3002\n\n// \u5217\u8868\u4e2d\u5305\u62ec\u4e00\u4e9b\u63d0\u4f9b\u5411\u91cf\u3001\u77e9\u9635\u548c\u9884\u5904\u7406\u7c7b\u7684\u5934\u6587\u4ef6\uff0c\u8fd9\u4e9b\u5934\u6587\u4ef6\u5b9e\u73b0\u4e86\u5404\u81eaTrilinos\u7c7b\u7684\u63a5\u53e3\uff1b\u5173\u4e8e\u8fd9\u4e9b\u7684\u4e00\u4e9b\u66f4\u591a\u4fe1\u606f\u53ef\u4ee5\u5728  step-31  \u4e2d\u627e\u5230\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/base/utilities.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/tensor_function.h> \n#include <deal.II/base/index_set.h> \n\n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/solver_gmres.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/block_sparsity_pattern.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_tools.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_renumbering.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/fe_values.h> \n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/solution_transfer.h> \n\n#include <deal.II/lac/trilinos_sparse_matrix.h> \n#include <deal.II/lac/trilinos_block_sparse_matrix.h> \n#include <deal.II/lac/trilinos_vector.h> \n#include <deal.II/lac/trilinos_parallel_block_vector.h> \n#include <deal.II/lac/trilinos_precondition.h> \n\n#include <iostream> \n#include <fstream> \n#include <memory> \n\n// \u5728\u8fd9\u4e2a\u9876\u5c42\u8bbe\u8ba1\u7684\u6700\u540e\uff0c\u6211\u4eec\u4e3a\u5f53\u524d\u9879\u76ee\u5f00\u8f9f\u4e00\u4e2a\u547d\u540d\u7a7a\u95f4\uff0c\u4e0b\u9762\u7684\u6240\u6709\u6750\u6599\u90fd\u5c06\u8fdb\u5165\u8fd9\u4e2a\u547d\u540d\u7a7a\u95f4\uff0c\u7136\u540e\u5c06\u6240\u6709deal.II\u540d\u79f0\u5bfc\u5165\u8fd9\u4e2a\u547d\u540d\u7a7a\u95f4\u3002\n\nnamespace Step43 \n{ \n  using namespace dealii; \n// @sect3{Boundary and initial value classes}  \n\n// \u4e0b\u9762\u7684\u90e8\u5206\u76f4\u63a5\u53d6\u81ea step-21 \uff0c\u6240\u4ee5\u6ca1\u6709\u5fc5\u8981\u91cd\u590d\u90a3\u91cc\u7684\u63cf\u8ff0\u3002\n\n  template <int dim> \n  class PressureBoundaryValues : public Function<dim> \n  { \n  public: \n    PressureBoundaryValues() \n      : Function<dim>(1) \n    {} \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n  }; \n\n  template <int dim> \n  double \n  PressureBoundaryValues<dim>::value(const Point<dim> &p, \n                                     const unsigned int /*component*/) const \n  { \n    return 1 - p[0]; \n  } \n\n  template <int dim> \n  class SaturationBoundaryValues : public Function<dim> \n  { \n  public: \n    SaturationBoundaryValues() \n      : Function<dim>(1) \n    {} \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n  }; \n\n  template <int dim> \n  double \n  SaturationBoundaryValues<dim>::value(const Point<dim> &p, \n                                       const unsigned int /*component*/) const \n  { \n    if (p[0] == 0) \n      return 1; \n    else \n      return 0; \n  } \n\n  template <int dim> \n  class SaturationInitialValues : public Function<dim> \n  { \n  public: \n    SaturationInitialValues() \n      : Function<dim>(1) \n    {} \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n\n    virtual void vector_value(const Point<dim> &p, \n                              Vector<double> &  value) const override; \n  }; \n\n  template <int dim> \n  double \n  SaturationInitialValues<dim>::value(const Point<dim> & /*p*/, \n                                      const unsigned int /*component*/) const \n  { \n    return 0.2; \n  } \n\n  template <int dim> \n  void SaturationInitialValues<dim>::vector_value(const Point<dim> &p, \n                                                  Vector<double> &values) const \n  { \n    for (unsigned int c = 0; c < this->n_components; ++c) \n      values(c) = SaturationInitialValues<dim>::value(p, c); \n  } \n// @sect3{Permeability models}  \n\n// \u5728\u672c\u6559\u7a0b\u4e2d\uff0c\u6211\u4eec\u4ecd\u7136\u4f7f\u7528\u4e4b\u524d\u5728 step-21 \u4e2d\u4f7f\u7528\u7684\u4e24\u4e2a\u6e17\u900f\u7387\u6a21\u578b\uff0c\u6240\u4ee5\u6211\u4eec\u518d\u6b21\u907f\u514d\u5bf9\u5b83\u4eec\u8fdb\u884c\u8be6\u7ec6\u8bc4\u8bba\u3002\n\n  namespace SingleCurvingCrack \n  { \n    template <int dim> \n    class KInverse : public TensorFunction<2, dim> \n    { \n    public: \n      KInverse() \n        : TensorFunction<2, dim>() \n      {} \n\n      virtual void \n      value_list(const std::vector<Point<dim>> &points, \n                 std::vector<Tensor<2, dim>> &  values) const override; \n    }; \n\n    template <int dim> \n    void KInverse<dim>::value_list(const std::vector<Point<dim>> &points, \n                                   std::vector<Tensor<2, dim>> &  values) const \n    { \n      Assert(points.size() == values.size(), \n             ExcDimensionMismatch(points.size(), values.size())); \n\n      for (unsigned int p = 0; p < points.size(); ++p) \n        { \n          values[p].clear(); \n\n          const double distance_to_flowline = \n            std::fabs(points[p][1] - 0.5 - 0.1 * std::sin(10 * points[p][0])); \n\n          const double permeability = \n            std::max(std::exp(-(distance_to_flowline * distance_to_flowline) / \n                              (0.1 * 0.1)), \n                     0.01); \n\n          for (unsigned int d = 0; d < dim; ++d) \n            values[p][d][d] = 1. / permeability; \n        } \n    } \n  } // namespace SingleCurvingCrack \n\n  namespace RandomMedium \n  { \n    template <int dim> \n    class KInverse : public TensorFunction<2, dim> \n    { \n    public: \n      KInverse() \n        : TensorFunction<2, dim>() \n      {} \n\n      virtual void \n      value_list(const std::vector<Point<dim>> &points, \n                 std::vector<Tensor<2, dim>> &  values) const override; \n\n    private: \n      static std::vector<Point<dim>> centers; \n    }; \n\n    template <int dim> \n    std::vector<Point<dim>> KInverse<dim>::centers = []() { \n      const unsigned int N = \n        (dim == 2 ? 40 : (dim == 3 ? 100 : throw ExcNotImplemented())); \n\n      std::vector<Point<dim>> centers_list(N); \n      for (unsigned int i = 0; i < N; ++i) \n        for (unsigned int d = 0; d < dim; ++d) \n          centers_list[i][d] = static_cast<double>(rand()) / RAND_MAX; \n\n      return centers_list; \n    }(); \n\n    template <int dim> \n    void KInverse<dim>::value_list(const std::vector<Point<dim>> &points, \n                                   std::vector<Tensor<2, dim>> &  values) const \n    { \n      AssertDimension(points.size(), values.size()); \n\n      for (unsigned int p = 0; p < points.size(); ++p) \n        { \n          values[p].clear(); \n\n          double permeability = 0; \n          for (unsigned int i = 0; i < centers.size(); ++i) \n            permeability += \n              std::exp(-(points[p] - centers[i]).norm_square() / (0.05 * 0.05)); \n\n          const double normalized_permeability = \n            std::min(std::max(permeability, 0.01), 4.); \n\n          for (unsigned int d = 0; d < dim; ++d) \n            values[p][d][d] = 1. / normalized_permeability; \n        } \n    } \n  } // namespace RandomMedium \n// @sect3{Physical quantities}  \n\n// \u6240\u6709\u7269\u7406\u91cf\u7684\u5b9e\u73b0\uff0c\u5982\u603b\u6d41\u52a8\u6027 $\\lambda_t$ \u548c\u6c34\u7684\u90e8\u5206\u6d41\u91cf $F$ \u90fd\u6765\u81ea step-21 \uff0c\u6240\u4ee5\u6211\u4eec\u4e5f\u6ca1\u6709\u5bf9\u5b83\u4eec\u505a\u4efb\u4f55\u8bc4\u8bba\u3002\u4e0e step-21 \u76f8\u6bd4\uff0c\u6211\u4eec\u589e\u52a0\u4e86\u68c0\u67e5\uff0c\u5373\u4f20\u9012\u7ed9\u8fd9\u4e9b\u51fd\u6570\u7684\u9971\u548c\u5ea6\u5b9e\u9645\u4e0a\u662f\u5728\u7269\u7406\u4e0a\u6709\u6548\u7684\u8303\u56f4\u5185\u3002\u6b64\u5916\uff0c\u9274\u4e8e\u6da6\u6e7f\u76f8\u4ee5\u901f\u5ea6 $\\mathbf u F'(S)$ \u79fb\u52a8\uff0c\u5f88\u660e\u663e $F'(S)$ \u5fc5\u987b\u5927\u4e8e\u6216\u7b49\u4e8e\u96f6\uff0c\u6240\u4ee5\u6211\u4eec\u4e5f\u65ad\u8a00\uff0c\u4ee5\u786e\u4fdd\u6211\u4eec\u7684\u8ba1\u7b97\u5f97\u5230\u7684\u5bfc\u6570\u516c\u5f0f\u662f\u5408\u7406\u7684\u3002\n\n  double mobility_inverse(const double S, const double viscosity) \n  { \n    return 1.0 / (1.0 / viscosity * S * S + (1 - S) * (1 - S)); \n  } \n\n  double fractional_flow(const double S, const double viscosity) \n  { \n    Assert((S >= 0) && (S <= 1), \n           ExcMessage(\"Saturation is outside its physically valid range.\")); \n\n    return S * S / (S * S + viscosity * (1 - S) * (1 - S)); \n  } \n\n  double fractional_flow_derivative(const double S, const double viscosity) \n  { \n    Assert((S >= 0) && (S <= 1), \n           ExcMessage(\"Saturation is outside its physically valid range.\")); \n\n    const double temp = (S * S + viscosity * (1 - S) * (1 - S)); \n\n    const double numerator = \n      2.0 * S * temp - S * S * (2.0 * S - 2.0 * viscosity * (1 - S)); \n    const double denominator = std::pow(temp, 2.0); \n\n    const double F_prime = numerator / denominator; \n\n    Assert(F_prime >= 0, ExcInternalError()); \n\n    return F_prime; \n  } \n// @sect3{Helper classes for solvers and preconditioners}  \n\n// \u5728\u8fd9\u7b2c\u4e00\u90e8\u5206\u4e2d\uff0c\u6211\u4eec\u5b9a\u4e49\u4e86\u4e00\u4e9b\u6211\u4eec\u5728\u6784\u5efa\u7ebf\u6027\u6c42\u89e3\u5668\u548c\u9884\u5904\u7406\u5668\u65f6\u9700\u8981\u7684\u7c7b\u3002\u8fd9\u4e00\u90e8\u5206\u4e0e  step-31  \u4e2d\u4f7f\u7528\u7684\u57fa\u672c\u76f8\u540c\u3002\u552f\u4e00\u4e0d\u540c\u7684\u662f\uff0c\u539f\u6765\u7684\u53d8\u91cf\u540d\u79f0stokes_matrix\u88ab\u53e6\u4e00\u4e2a\u540d\u79f0darcy_matrix\u53d6\u4ee3\uff0c\u4ee5\u914d\u5408\u6211\u4eec\u7684\u95ee\u9898\u3002\n\n  namespace LinearSolvers \n  { \n    template <class MatrixType, class PreconditionerType> \n    class InverseMatrix : public Subscriptor \n    { \n    public: \n      InverseMatrix(const MatrixType &        m, \n                    const PreconditionerType &preconditioner); \n\n      template <typename VectorType> \n      void vmult(VectorType &dst, const VectorType &src) const; \n\n    private: \n      const SmartPointer<const MatrixType> matrix; \n      const PreconditionerType &           preconditioner; \n    }; \n\n    template <class MatrixType, class PreconditionerType> \n    InverseMatrix<MatrixType, PreconditionerType>::InverseMatrix( \n      const MatrixType &        m, \n      const PreconditionerType &preconditioner) \n      : matrix(&m) \n      , preconditioner(preconditioner) \n    {} \n\n    template <class MatrixType, class PreconditionerType> \n    template <typename VectorType> \n    void InverseMatrix<MatrixType, PreconditionerType>::vmult( \n      VectorType &      dst, \n      const VectorType &src) const \n    { \n      SolverControl        solver_control(src.size(), 1e-7 * src.l2_norm()); \n      SolverCG<VectorType> cg(solver_control); \n\n      dst = 0; \n\n      try \n        { \n          cg.solve(*matrix, dst, src, preconditioner); \n        } \n      catch (std::exception &e) \n        { \n          Assert(false, ExcMessage(e.what())); \n        } \n    } \n\n    template <class PreconditionerTypeA, class PreconditionerTypeMp> \n    class BlockSchurPreconditioner : public Subscriptor \n    { \n    public: \n      BlockSchurPreconditioner( \n        const TrilinosWrappers::BlockSparseMatrix &S, \n        const InverseMatrix<TrilinosWrappers::SparseMatrix, \n                            PreconditionerTypeMp> &Mpinv, \n        const PreconditionerTypeA &                Apreconditioner); \n\n      void vmult(TrilinosWrappers::MPI::BlockVector &      dst, \n                 const TrilinosWrappers::MPI::BlockVector &src) const; \n\n    private: \n      const SmartPointer<const TrilinosWrappers::BlockSparseMatrix> \n        darcy_matrix; \n      const SmartPointer<const InverseMatrix<TrilinosWrappers::SparseMatrix, \n                                             PreconditionerTypeMp>> \n                                 m_inverse; \n      const PreconditionerTypeA &a_preconditioner; \n\n      mutable TrilinosWrappers::MPI::Vector tmp; \n    }; \n\n    template <class PreconditionerTypeA, class PreconditionerTypeMp> \n    BlockSchurPreconditioner<PreconditionerTypeA, PreconditionerTypeMp>:: \n      BlockSchurPreconditioner( \n        const TrilinosWrappers::BlockSparseMatrix &S, \n        const InverseMatrix<TrilinosWrappers::SparseMatrix, \n                            PreconditionerTypeMp> &Mpinv, \n        const PreconditionerTypeA &                Apreconditioner) \n      : darcy_matrix(&S) \n      , m_inverse(&Mpinv) \n      , a_preconditioner(Apreconditioner) \n      , tmp(complete_index_set(darcy_matrix->block(1, 1).m())) \n    {} \n\n    template <class PreconditionerTypeA, class PreconditionerTypeMp> \n    void \n    BlockSchurPreconditioner<PreconditionerTypeA, PreconditionerTypeMp>::vmult( \n      TrilinosWrappers::MPI::BlockVector &      dst, \n      const TrilinosWrappers::MPI::BlockVector &src) const \n    { \n      a_preconditioner.vmult(dst.block(0), src.block(0)); \n      darcy_matrix->block(1, 0).residual(tmp, dst.block(0), src.block(1)); \n      tmp *= -1; \n      m_inverse->vmult(dst.block(1), tmp); \n    } \n  } // namespace LinearSolvers \n// @sect3{The TwoPhaseFlowProblem class}  \n\n// \u5b9a\u4e49\u89e3\u51b3\u968f\u65f6\u95f4\u53d8\u5316\u7684\u5e73\u6d41\u4e3b\u5bfc\u7684\u4e24\u76f8\u6d41\u95ee\u9898\uff08\u6216Buckley-Leverett\u95ee\u9898[Buckley 1942]\uff09\u7684\u9876\u5c42\u903b\u8f91\u7684\u7c7b\u7684\u5b9a\u4e49\u4e3b\u8981\u57fa\u4e8e\u6559\u7a0b\u7a0b\u5e8f step-21 \u548c step-33 \uff0c\u7279\u522b\u662f step-31 \uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u7684\u4e00\u822c\u7ed3\u6784\u57fa\u672c\u76f8\u540c\u3002\u4e0e step-31 \u4e00\u6837\uff0c\u5728\u4e0b\u9762\u7684\u5b9e\u73b0\u4e2d\u9700\u8981\u5bfb\u627e\u7684\u5173\u952e\u4f8b\u7a0b\u662f <code>run()</code> and <code>solve()</code> \u51fd\u6570\u3002\n\n// \u4e0e step-31 \u7684\u4e3b\u8981\u533a\u522b\u662f\uff0c\u7531\u4e8e\u8003\u8651\u4e86\u81ea\u9002\u5e94\u7b97\u5b50\u62c6\u5206\uff0c\u6211\u4eec\u9700\u8981\u591a\u51e0\u4e2a\u6210\u5458\u53d8\u91cf\u6765\u4fdd\u5b58\u6700\u8fd1\u4e24\u6b21\u8ba1\u7b97\u7684\u8fbe\u897f\uff08\u901f\u5ea6/\u538b\u529b\uff09\u89e3\uff0c\u4ee5\u53ca\u5f53\u524d\u7684\u8fbe\u897f\uff08\u76f4\u63a5\u8ba1\u7b97\uff0c\u6216\u4ece\u524d\u4e24\u6b21\u8ba1\u7b97\u4e2d\u63a8\u65ad\uff09\uff0c\u6211\u4eec\u9700\u8981\u8bb0\u4f4f\u6700\u8fd1\u4e24\u6b21\u8ba1\u7b97\u7684\u8fbe\u897f\u89e3\u3002\u6211\u4eec\u8fd8\u9700\u8981\u4e00\u4e2a\u8f85\u52a9\u51fd\u6570\u6765\u786e\u5b9a\u6211\u4eec\u662f\u5426\u771f\u7684\u9700\u8981\u91cd\u65b0\u8ba1\u7b97\u8fbe\u897f\u89e3\u3002\n\n// \u4e0e step-31 \u4e0d\u540c\uff0c\u8fd9\u4e00\u6b65\u591a\u7528\u4e86\u4e00\u4e2aAffineConstraints\u5bf9\u8c61\uff0c\u53eb\u505adarcy_preconditioner_constraints\u3002\u8fd9\u4e2a\u7ea6\u675f\u5bf9\u8c61\u53ea\u7528\u4e8e\u4e3aDarcy\u9884\u5904\u7406\u7a0b\u5e8f\u7ec4\u88c5\u77e9\u9635\uff0c\u5305\u62ec\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u4ee5\u53ca\u538b\u529b\u53d8\u91cf\u7684Dirichlet\u8fb9\u754c\u503c\u7ea6\u675f\u3002\u6211\u4eec\u9700\u8981\u8fd9\u4e2a\uff0c\u56e0\u4e3a\u6211\u4eec\u6b63\u5728\u4e3a\u538b\u529b\u5efa\u7acb\u4e00\u4e2a\u62c9\u666e\u62c9\u65af\u77e9\u9635\uff0c\u4f5c\u4e3a\u8212\u5c14\u8865\u7801\u7684\u8fd1\u4f3c\u503c\uff09\uff0c\u5982\u679c\u5e94\u7528\u8fb9\u754c\u6761\u4ef6\uff0c\u8fd9\u4e2a\u77e9\u9635\u662f\u6b63\u5b9a\u7684\u3002\n\n// \u8fd9\u6837\u5728\u8fd9\u4e2a\u7c7b\u4e2d\u58f0\u660e\u7684\u6210\u5458\u51fd\u6570\u548c\u53d8\u91cf\u7684\u96c6\u5408\u4e0e  step-31  \u4e2d\u7684\u76f8\u5f53\u76f8\u4f3c\u3002\n\n  template <int dim> \n  class TwoPhaseFlowProblem \n  { \n  public: \n    TwoPhaseFlowProblem(const unsigned int degree); \n    void run(); \n\n  private: \n    void setup_dofs(); \n    void assemble_darcy_preconditioner(); \n    void build_darcy_preconditioner(); \n    void assemble_darcy_system(); \n    void assemble_saturation_system(); \n    void assemble_saturation_matrix(); \n    void assemble_saturation_rhs(); \n    void assemble_saturation_rhs_cell_term( \n      const FEValues<dim> &                       saturation_fe_values, \n      const FEValues<dim> &                       darcy_fe_values, \n      const double                                global_max_u_F_prime, \n      const double                                global_S_variation, \n      const std::vector<types::global_dof_index> &local_dof_indices); \n    void assemble_saturation_rhs_boundary_term( \n      const FEFaceValues<dim> &                   saturation_fe_face_values, \n      const FEFaceValues<dim> &                   darcy_fe_face_values, \n      const std::vector<types::global_dof_index> &local_dof_indices); \n    void solve(); \n    void refine_mesh(const unsigned int min_grid_level, \n                     const unsigned int max_grid_level); \n    void output_results() const; \n\n// \u6211\u4eec\u63a5\u4e0b\u6765\u4f1a\u6709\u4e00\u4e9b\u8f85\u52a9\u51fd\u6570\uff0c\u8fd9\u4e9b\u51fd\u6570\u5728\u6574\u4e2a\u7a0b\u5e8f\u4e2d\u7684\u4e0d\u540c\u5730\u65b9\u90fd\u4f1a\u7528\u5230\u3002\n\n    double                    get_max_u_F_prime() const; \n    std::pair<double, double> get_extrapolated_saturation_range() const; \n    bool   determine_whether_to_solve_for_pressure_and_velocity() const; \n    void   project_back_saturation(); \n    double compute_viscosity( \n      const std::vector<double> &        old_saturation, \n      const std::vector<double> &        old_old_saturation, \n      const std::vector<Tensor<1, dim>> &old_saturation_grads, \n      const std::vector<Tensor<1, dim>> &old_old_saturation_grads, \n      const std::vector<Vector<double>> &present_darcy_values, \n      const double                       global_max_u_F_prime, \n      const double                       global_S_variation, \n      const double                       cell_diameter) const; \n\n// \u63a5\u4e0b\u6765\u662f\u6210\u5458\u53d8\u91cf\uff0c\u5176\u4e2d\u5927\u90e8\u5206\u4e0e step-31 \u4e2d\u7684\u53d8\u91cf\u7c7b\u4f3c\uff0c\u4f46\u4e0e\u901f\u5ea6/\u538b\u529b\u7cfb\u7edf\u7684\u5b8f\u89c2\u65f6\u95f4\u6b65\u957f\u6709\u5173\u7684\u53d8\u91cf\u9664\u5916\u3002\n\n    Triangulation<dim> triangulation; \n    double             global_Omega_diameter; \n\n    const unsigned int degree; \n\n    const unsigned int        darcy_degree; \n    FESystem<dim>             darcy_fe; \n    DoFHandler<dim>           darcy_dof_handler; \n    AffineConstraints<double> darcy_constraints; \n\n    AffineConstraints<double> darcy_preconditioner_constraints; \n\n    TrilinosWrappers::BlockSparseMatrix darcy_matrix; \n    TrilinosWrappers::BlockSparseMatrix darcy_preconditioner_matrix; \n\n    TrilinosWrappers::MPI::BlockVector darcy_solution; \n    TrilinosWrappers::MPI::BlockVector darcy_rhs; \n\n    TrilinosWrappers::MPI::BlockVector last_computed_darcy_solution; \n    TrilinosWrappers::MPI::BlockVector second_last_computed_darcy_solution; \n\n    const unsigned int        saturation_degree; \n    FE_Q<dim>                 saturation_fe; \n    DoFHandler<dim>           saturation_dof_handler; \n    AffineConstraints<double> saturation_constraints; \n\n    TrilinosWrappers::SparseMatrix saturation_matrix; \n\n    TrilinosWrappers::MPI::Vector saturation_solution; \n    TrilinosWrappers::MPI::Vector old_saturation_solution; \n    TrilinosWrappers::MPI::Vector old_old_saturation_solution; \n    TrilinosWrappers::MPI::Vector saturation_rhs; \n\n    TrilinosWrappers::MPI::Vector \n      saturation_matching_last_computed_darcy_solution; \n\n    const double saturation_refinement_threshold; \n\n    double       time; \n    const double end_time; \n\n    double current_macro_time_step; \n    double old_macro_time_step; \n\n    double       time_step; \n    double       old_time_step; \n    unsigned int timestep_number; \n\n    const double viscosity; \n    const double porosity; \n    const double AOS_threshold; \n\n    std::shared_ptr<TrilinosWrappers::PreconditionIC> Amg_preconditioner; \n    std::shared_ptr<TrilinosWrappers::PreconditionIC> Mp_preconditioner; \n\n    bool rebuild_saturation_matrix; \n\n// \u5728\u6700\u540e\uff0c\u6211\u4eec\u58f0\u660e\u4e00\u4e2a\u53d8\u91cf\uff0c\u8868\u793a\u6750\u6599\u6a21\u578b\u3002\u4e0e step-21 \u76f8\u6bd4\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u628a\u5b83\u4f5c\u4e3a\u4e00\u4e2a\u6210\u5458\u53d8\u91cf\uff0c\u56e0\u4e3a\u6211\u4eec\u60f3\u5728\u4e0d\u540c\u7684\u5730\u65b9\u4f7f\u7528\u5b83\uff0c\u6240\u4ee5\u6709\u4e00\u4e2a\u58f0\u660e\u8fd9\u6837\u4e00\u4e2a\u53d8\u91cf\u7684\u4e2d\u5fc3\u4f4d\u7f6e\uff0c\u5c06\u4f7f\u6211\u4eec\u66f4\u5bb9\u6613\u7528\u53e6\u4e00\u4e2a\u7c7b\u6765\u66ff\u6362 RandomMedium::KInverse \uff08\u4f8b\u5982\uff0c\u7528 SingleCurvingCrack::KInverse). \u66ff\u6362 RandomMedium::KInverse \uff09\u3002\n    const RandomMedium::KInverse<dim> k_inverse; \n  }; \n// @sect3{TwoPhaseFlowProblem<dim>::TwoPhaseFlowProblem}  \n\n// \u8fd9\u4e2a\u7c7b\u7684\u6784\u9020\u51fd\u6570\u662f\u5bf9  step-21  \u548c  step-31  \u4e2d\u7684\u6784\u9020\u51fd\u6570\u7684\u6269\u5c55\u3002\u6211\u4eec\u9700\u8981\u6dfb\u52a0\u6d89\u53ca\u9971\u548c\u5ea6\u7684\u5404\u79cd\u53d8\u91cf\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u6211\u4eec\u5c06\u518d\u6b21\u4f7f\u7528 $Q_2 \\times Q_1$ \uff08Taylor-Hood\uff09\u5143\u7d20\u6765\u5904\u7406Darcy\u7cfb\u7edf\uff0c\u8fd9\u662f\u4e00\u4e2a\u6ee1\u8db3Ladyzhenskaya-Babuska-Brezzi\uff08LBB\uff09\u6761\u4ef6\u7684\u5143\u7d20\u7ec4\u5408[Brezzi and Fortin 1991, Chen 2005]\uff0c\u5e76\u4f7f\u7528 $Q_1$ \u5143\u7d20\u5904\u7406\u9971\u548c\u5ea6\u3002\u7136\u800c\uff0c\u901a\u8fc7\u4f7f\u7528\u5b58\u50a8Darcy\u548c\u6e29\u5ea6\u6709\u9650\u5143\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u7684\u53d8\u91cf\uff0c\u53ef\u4ee5\u5f88\u5bb9\u6613\u5730\u6301\u7eed\u4fee\u6539\u8fd9\u4e9b\u5143\u7d20\u7684\u7a0b\u5ea6\u4ee5\u53ca\u5728\u5176\u4e0a\u4f7f\u7528\u7684\u6240\u6709\u6b63\u4ea4\u516c\u5f0f\u7684\u4e0b\u6e38\u3002\u6b64\u5916\uff0c\u6211\u4eec\u8fd8\u521d\u59cb\u5316\u4e86\u4e0e\u7b97\u5b50\u5206\u5272\u6709\u5173\u7684\u65f6\u95f4\u6b65\u8fdb\u53d8\u91cf\uff0c\u4ee5\u53ca\u77e9\u9635\u88c5\u914d\u548c\u9884\u5904\u7406\u7684\u9009\u9879\u3002\n\n  template <int dim> \n  TwoPhaseFlowProblem<dim>::TwoPhaseFlowProblem(const unsigned int degree) \n    : triangulation(Triangulation<dim>::maximum_smoothing) \n    , global_Omega_diameter(std::numeric_limits<double>::quiet_NaN()) \n    , degree(degree) \n    , darcy_degree(degree) \n    , darcy_fe(FE_Q<dim>(darcy_degree + 1), dim, FE_Q<dim>(darcy_degree), 1) \n    , darcy_dof_handler(triangulation) \n    , \n\n    saturation_degree(degree + 1) \n    , saturation_fe(saturation_degree) \n    , saturation_dof_handler(triangulation) \n    , \n\n    saturation_refinement_threshold(0.5) \n    , \n\n    time(0) \n    , end_time(10) \n    , \n\n    current_macro_time_step(0) \n    , old_macro_time_step(0) \n    , \n\n    time_step(0) \n    , old_time_step(0) \n    , timestep_number(0) \n    , viscosity(0.2) \n    , porosity(1.0) \n    , AOS_threshold(3.0) \n    , \n\n    rebuild_saturation_matrix(true) \n  {} \n// @sect3{TwoPhaseFlowProblem<dim>::setup_dofs}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u8bbe\u7f6e\u4e86\u6211\u4eec\u8fd9\u91cc\u7684DoFHandler\u5bf9\u8c61\uff08\u4e00\u4e2a\u7528\u4e8eDarcy\u90e8\u5206\uff0c\u4e00\u4e2a\u7528\u4e8e\u9971\u548c\u90e8\u5206\uff09\uff0c\u4ee5\u53ca\u5c06\u672c\u7a0b\u5e8f\u4e2d\u7ebf\u6027\u4ee3\u6570\u6240\u9700\u7684\u5404\u79cd\u5bf9\u8c61\u8bbe\u7f6e\u4e3a\u5408\u9002\u7684\u5c3a\u5bf8\u3002\u5176\u57fa\u672c\u64cd\u4f5c\u4e0e step-31 \u6240\u505a\u7684\u7c7b\u4f3c\u3002\n\n// \u8be5\u51fd\u6570\u7684\u4e3b\u4f53\u9996\u5148\u5217\u4e3e\u4e86\u8fbe\u897f\u548c\u9971\u548c\u7cfb\u7edf\u7684\u6240\u6709\u81ea\u7531\u5ea6\u3002\u5bf9\u4e8eDarcy\u90e8\u5206\uff0c\u81ea\u7531\u5ea6\u4f1a\u88ab\u6392\u5e8f\uff0c\u4ee5\u786e\u4fdd\u901f\u5ea6\u4f18\u5148\u4e8e\u538b\u529bDoF\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u5c06Darcy\u77e9\u9635\u5212\u5206\u4e3a\u4e00\u4e2a $2 \\times 2$ \u77e9\u9635\u3002\n//\u7136\u540e\uff0c\n//\u6211\u4eec\u9700\u8981\u5c06\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u548cDirichlet\u8fb9\u754c\u503c\u7ea6\u675f\u7eb3\u5165 darcy_preconditioner_constraints\u3002 \u8fb9\u754c\u6761\u4ef6\u7ea6\u675f\u53ea\u8bbe\u7f6e\u5728\u538b\u529b\u5206\u91cf\u4e0a\uff0c\u56e0\u4e3a\u5bf9\u5e94\u4e8e\u975e\u6df7\u5408\u5f62\u5f0f\u7684\u591a\u5b54\u4ecb\u8d28\u6d41\u7b97\u5b50\u7684Schur complement\u9884\u5904\u7406\u7a0b\u5e8f $-\\nabla \\cdot [\\mathbf K \\lambda_t(S)]\\nabla$  \uff0c\u53ea\u4f5c\u7528\u4e8e\u538b\u529b\u53d8\u91cf\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u8fc7\u6ee4\u6389\u901f\u5ea6\u5206\u91cf\u7684\u5206\u91cf\u63a9\u7801\uff0c\u8fd9\u6837\u5c31\u53ef\u4ee5\u53ea\u5bf9\u538b\u529b\u81ea\u7531\u5ea6\u8fdb\u884c\u7f29\u51cf\u3002\n\n// \u505a\u5b8c\u8fd9\u4e9b\u540e\uff0c\u6211\u4eec\u8ba1\u7b97\u5404\u4e2a\u5757\u4e2d\u7684\u81ea\u7531\u5ea6\u6570\u91cf\u3002\u7136\u540e\uff0c\u8fd9\u4e9b\u4fe1\u606f\u88ab\u7528\u6765\u521b\u5efa\u8fbe\u897f\u548c\u9971\u548c\u7cfb\u7edf\u77e9\u9635\u7684\u7a00\u758f\u6a21\u5f0f\uff0c\u4ee5\u53ca\u7528\u4e8e\u5efa\u7acb\u8fbe\u897f\u9884\u5904\u7406\u7684\u9884\u5904\u7406\u77e9\u9635\u3002\u5982\u540c step-31 \uff0c\u6211\u4eec\u9009\u62e9\u4f7f\u7528DynamicSparsityPattern\u7684\u5c01\u9501\u7248\u672c\u6765\u521b\u5efa\u6a21\u5f0f\u3002\u56e0\u6b64\uff0c\u5bf9\u4e8e\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u9075\u5faa\u4e0e step-31 \u76f8\u540c\u7684\u65b9\u5f0f\uff0c\u5bf9\u4e8e\u6210\u5458\u51fd\u6570\u7684\u5176\u4ed6\u90e8\u5206\uff0c\u6211\u4eec\u4e0d\u5fc5\u518d\u91cd\u590d\u63cf\u8ff0\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::setup_dofs() \n  { \n    std::vector<unsigned int> darcy_block_component(dim + 1, 0); \n    darcy_block_component[dim] = 1; \n    { \n      darcy_dof_handler.distribute_dofs(darcy_fe); \n      DoFRenumbering::Cuthill_McKee(darcy_dof_handler); \n      DoFRenumbering::component_wise(darcy_dof_handler, darcy_block_component); \n\n      darcy_constraints.clear(); \n      DoFTools::make_hanging_node_constraints(darcy_dof_handler, \n                                              darcy_constraints); \n      darcy_constraints.close(); \n    } \n    { \n      saturation_dof_handler.distribute_dofs(saturation_fe); \n\n      saturation_constraints.clear(); \n      DoFTools::make_hanging_node_constraints(saturation_dof_handler, \n                                              saturation_constraints); \n      saturation_constraints.close(); \n    } \n    { \n      darcy_preconditioner_constraints.clear(); \n\n      FEValuesExtractors::Scalar pressure(dim); \n\n      DoFTools::make_hanging_node_constraints(darcy_dof_handler, \n                                              darcy_preconditioner_constraints); \n      DoFTools::make_zero_boundary_constraints(darcy_dof_handler, \n                                               darcy_preconditioner_constraints, \n                                               darcy_fe.component_mask( \n                                                 pressure)); \n\n      darcy_preconditioner_constraints.close(); \n    } \n\n    const std::vector<types::global_dof_index> darcy_dofs_per_block = \n      DoFTools::count_dofs_per_fe_block(darcy_dof_handler, \n                                        darcy_block_component); \n    const unsigned int n_u = darcy_dofs_per_block[0], \n                       n_p = darcy_dofs_per_block[1], \n                       n_s = saturation_dof_handler.n_dofs(); \n\n    std::cout << \"Number of active cells: \" << triangulation.n_active_cells() \n              << \" (on \" << triangulation.n_levels() << \" levels)\" << std::endl \n              << \"Number of degrees of freedom: \" << n_u + n_p + n_s << \" (\" \n              << n_u << '+' << n_p << '+' << n_s << ')' << std::endl \n              << std::endl; \n\n    { \n      darcy_matrix.clear(); \n\n      BlockDynamicSparsityPattern dsp(2, 2); \n\n      dsp.block(0, 0).reinit(n_u, n_u); \n      dsp.block(0, 1).reinit(n_u, n_p); \n      dsp.block(1, 0).reinit(n_p, n_u); \n      dsp.block(1, 1).reinit(n_p, n_p); \n\n      dsp.collect_sizes(); \n\n      Table<2, DoFTools::Coupling> coupling(dim + 1, dim + 1); \n\n      for (unsigned int c = 0; c < dim + 1; ++c) \n        for (unsigned int d = 0; d < dim + 1; ++d) \n          if (!((c == dim) && (d == dim))) \n            coupling[c][d] = DoFTools::always; \n          else \n            coupling[c][d] = DoFTools::none; \n\n      DoFTools::make_sparsity_pattern( \n        darcy_dof_handler, coupling, dsp, darcy_constraints, false); \n\n      darcy_matrix.reinit(dsp); \n    } \n\n    { \n      Amg_preconditioner.reset(); \n      Mp_preconditioner.reset(); \n      darcy_preconditioner_matrix.clear(); \n\n      BlockDynamicSparsityPattern dsp(2, 2); \n\n      dsp.block(0, 0).reinit(n_u, n_u); \n      dsp.block(0, 1).reinit(n_u, n_p); \n      dsp.block(1, 0).reinit(n_p, n_u); \n      dsp.block(1, 1).reinit(n_p, n_p); \n\n      dsp.collect_sizes(); \n\n      Table<2, DoFTools::Coupling> coupling(dim + 1, dim + 1); \n      for (unsigned int c = 0; c < dim + 1; ++c) \n        for (unsigned int d = 0; d < dim + 1; ++d) \n          if (c == d) \n            coupling[c][d] = DoFTools::always; \n          else \n            coupling[c][d] = DoFTools::none; \n\n      DoFTools::make_sparsity_pattern( \n        darcy_dof_handler, coupling, dsp, darcy_constraints, false); \n\n      darcy_preconditioner_matrix.reinit(dsp); \n    } \n\n    { \n      saturation_matrix.clear(); \n\n      DynamicSparsityPattern dsp(n_s, n_s); \n\n      DoFTools::make_sparsity_pattern(saturation_dof_handler, \n                                      dsp, \n                                      saturation_constraints, \n                                      false); \n\n      saturation_matrix.reinit(dsp); \n    } \n\n    std::vector<IndexSet> darcy_partitioning(2); \n    darcy_partitioning[0] = complete_index_set(n_u); \n    darcy_partitioning[1] = complete_index_set(n_p); \n    darcy_solution.reinit(darcy_partitioning, MPI_COMM_WORLD); \n    darcy_solution.collect_sizes(); \n\n    last_computed_darcy_solution.reinit(darcy_partitioning, MPI_COMM_WORLD); \n    last_computed_darcy_solution.collect_sizes(); \n\n    second_last_computed_darcy_solution.reinit(darcy_partitioning, \n                                               MPI_COMM_WORLD); \n    second_last_computed_darcy_solution.collect_sizes(); \n\n    darcy_rhs.reinit(darcy_partitioning, MPI_COMM_WORLD); \n    darcy_rhs.collect_sizes(); \n\n    IndexSet saturation_partitioning = complete_index_set(n_s); \n    saturation_solution.reinit(saturation_partitioning, MPI_COMM_WORLD); \n    old_saturation_solution.reinit(saturation_partitioning, MPI_COMM_WORLD); \n    old_old_saturation_solution.reinit(saturation_partitioning, MPI_COMM_WORLD); \n\n    saturation_matching_last_computed_darcy_solution.reinit( \n      saturation_partitioning, MPI_COMM_WORLD); \n\n    saturation_rhs.reinit(saturation_partitioning, MPI_COMM_WORLD); \n  } \n// @sect3{Assembling matrices and preconditioners}  \n\n// \u63a5\u4e0b\u6765\u7684\u51e0\u4e2a\u51fd\u6570\u4e13\u95e8\u7528\u6765\u8bbe\u7f6e\u6211\u4eec\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u5fc5\u987b\u5904\u7406\u7684\u5404\u79cd\u7cfb\u7edf\u548c\u9884\u5904\u7406\u77e9\u9635\u53ca\u53f3\u624b\u8fb9\u3002\n\n//  @sect4{TwoPhaseFlowProblem<dim>::assemble_darcy_preconditioner}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u7ec4\u88c5\u6211\u4eec\u7528\u4e8e\u9884\u5904\u7406\u8fbe\u897f\u7cfb\u7edf\u7684\u77e9\u9635\u3002\u6211\u4eec\u9700\u8981\u7684\u662f\u5728\u901f\u5ea6\u5206\u91cf\u4e0a\u7528 $\\left(\\mathbf{K} \\lambda_t\\right)^{-1}$ \u52a0\u6743\u7684\u5411\u91cf\u8d28\u91cf\u77e9\u9635\u548c\u5728\u538b\u529b\u5206\u91cf\u4e0a\u7528 $\\left(\\mathbf{K} \\lambda_t\\right)$ \u52a0\u6743\u7684\u8d28\u91cf\u77e9\u9635\u3002\u6211\u4eec\u9996\u5148\u751f\u6210\u4e00\u4e2a\u9002\u5f53\u9636\u6570\u7684\u6b63\u4ea4\u5bf9\u8c61\uff0c\u5373FEValues\u5bf9\u8c61\uff0c\u53ef\u4ee5\u7ed9\u51fa\u6b63\u4ea4\u70b9\u7684\u6570\u503c\u548c\u68af\u5ea6\uff08\u8fde\u540c\u6b63\u4ea4\u6743\u91cd\uff09\u3002\u63a5\u4e0b\u6765\u6211\u4eec\u4e3a\u5355\u5143\u683c\u77e9\u9635\u548c\u5c40\u90e8\u4e0e\u5168\u5c40DoF\u4e4b\u95f4\u7684\u5173\u7cfb\u521b\u5efa\u6570\u636e\u7ed3\u6784\u3002\u5411\u91cfphi_u\u548cgrad_phi_p\u5c06\u4fdd\u5b58\u57fa\u51fd\u6570\u7684\u503c\uff0c\u4ee5\u4fbf\u66f4\u5feb\u5730\u5efa\u7acb\u5c40\u90e8\u77e9\u9635\uff0c\u6b63\u5982\u5728  step-22  \u4e2d\u5df2\u7ecf\u505a\u7684\u3002\u5728\u6211\u4eec\u5f00\u59cb\u5bf9\u6240\u6709\u6d3b\u52a8\u5355\u5143\u8fdb\u884c\u5faa\u73af\u4e4b\u524d\uff0c\u6211\u4eec\u5fc5\u987b\u6307\u5b9a\u54ea\u4e9b\u6210\u5206\u662f\u538b\u529b\uff0c\u54ea\u4e9b\u662f\u901f\u5ea6\u3002\n\n// \u5c40\u90e8\u77e9\u9635\u7684\u521b\u5efa\u662f\u76f8\u5f53\u7b80\u5355\u7684\u3002\u53ea\u6709\u4e00\u4e2a\u7531 $\\left(\\mathbf{K} \\lambda_t\\right)^{-1}$ \u52a0\u6743\u7684\u9879\uff08\u5173\u4e8e\u901f\u5ea6\uff09\u548c\u4e00\u4e2a\u7531 $\\left(\\mathbf{K} \\lambda_t\\right)$ \u52a0\u6743\u7684\u62c9\u666e\u62c9\u65af\u77e9\u9635\u9700\u8981\u751f\u6210\uff0c\u6240\u4ee5\u5c40\u90e8\u77e9\u9635\u7684\u521b\u5efa\u57fa\u672c\u4e0a\u53ea\u9700\u8981\u4e24\u884c\u5c31\u53ef\u4ee5\u5b8c\u6210\u3002\u7531\u4e8e\u8be5\u6587\u4ef6\u9876\u90e8\u7684\u6750\u6599\u6a21\u578b\u51fd\u6570\u53ea\u63d0\u4f9b\u4e86\u6e17\u900f\u7387\u548c\u8fc1\u79fb\u7387\u7684\u5012\u6570\uff0c\u6211\u4eec\u5fc5\u987b\u6839\u636e\u7ed9\u5b9a\u7684\u6570\u503c\u624b\u5de5\u8ba1\u7b97 $\\mathbf K$ \u548c $\\lambda_t$ \uff0c\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u4e00\u6b21\u3002\n\n// \u4e00\u65e6\u672c\u5730\u77e9\u9635\u51c6\u5907\u597d\u4e86\uff08\u5728\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u4e0a\u5bf9\u672c\u5730\u77e9\u9635\u7684\u884c\u548c\u5217\u8fdb\u884c\u5faa\u73af\uff09\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5f97\u5230\u672c\u5730\u7684DoF\u6307\u6570\uff0c\u5e76\u5c06\u672c\u5730\u4fe1\u606f\u5199\u5165\u5168\u5c40\u77e9\u9635\u4e2d\u3002\u6211\u4eec\u901a\u8fc7\u76f4\u63a5\u5e94\u7528\u7ea6\u675f\u6761\u4ef6\uff08\u5373darcy_preconditioner_constraints\uff09\u6765\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u8be5\u7ea6\u675f\u6761\u4ef6\u8d1f\u8d23\u5904\u7406\u60ac\u6302\u8282\u70b9\u548c\u96f6Dirichlet\u8fb9\u754c\u6761\u4ef6\u7ea6\u675f\u3002\u8fd9\u6837\u505a\uff0c\u6211\u4eec\u5c31\u4e0d\u5fc5\u4e8b\u540e\u518d\u505a\uff0c\u4ee5\u540e\u4e5f\u4e0d\u5fc5\u4f7f\u7528 AffineConstraints::condense \u548c MatrixTools::apply_boundary_values, \u8fd9\u4e24\u4e2a\u9700\u8981\u4fee\u6539\u77e9\u9635\u548c\u5411\u91cf\u9879\u7684\u51fd\u6570\uff0c\u56e0\u6b64\u5bf9\u4e8e\u6211\u4eec\u4e0d\u80fd\u7acb\u5373\u8bbf\u95ee\u5355\u4e2a\u5185\u5b58\u4f4d\u7f6e\u7684\u7279\u91cc\u8bfa\u65af\u7c7b\u6765\u8bf4\uff0c\u5f88\u96be\u7f16\u5199\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::assemble_darcy_preconditioner() \n  { \n    std::cout << \"   Rebuilding darcy preconditioner...\" << std::endl; \n\n    darcy_preconditioner_matrix = 0; \n\n    const QGauss<dim> quadrature_formula(darcy_degree + 2); \n    FEValues<dim>     darcy_fe_values(darcy_fe, \n                                  quadrature_formula, \n                                  update_JxW_values | update_values | \n                                    update_gradients | \n                                    update_quadrature_points); \n    FEValues<dim>     saturation_fe_values(saturation_fe, \n                                       quadrature_formula, \n                                       update_values); \n\n    const unsigned int dofs_per_cell = darcy_fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    std::vector<Tensor<2, dim>> k_inverse_values(n_q_points); \n\n    std::vector<double> old_saturation_values(n_q_points); \n\n    FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell); \n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    std::vector<Tensor<1, dim>> phi_u(dofs_per_cell); \n    std::vector<Tensor<1, dim>> grad_phi_p(dofs_per_cell); \n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure(dim); \n\n    auto       cell            = darcy_dof_handler.begin_active(); \n    const auto endc            = darcy_dof_handler.end(); \n    auto       saturation_cell = saturation_dof_handler.begin_active(); \n\n    for (; cell != endc; ++cell, ++saturation_cell) \n      { \n        darcy_fe_values.reinit(cell); \n        saturation_fe_values.reinit(saturation_cell); \n\n        local_matrix = 0; \n\n        saturation_fe_values.get_function_values(old_saturation_solution, \n                                                 old_saturation_values); \n\n        k_inverse.value_list(darcy_fe_values.get_quadrature_points(), \n                             k_inverse_values); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            const double old_s = old_saturation_values[q]; \n\n            const double inverse_mobility = mobility_inverse(old_s, viscosity); \n            const double mobility         = 1.0 / inverse_mobility; \n            const Tensor<2, dim> permeability = invert(k_inverse_values[q]); \n\n            for (unsigned int k = 0; k < dofs_per_cell; ++k) \n              { \n                phi_u[k]      = darcy_fe_values[velocities].value(k, q); \n                grad_phi_p[k] = darcy_fe_values[pressure].gradient(k, q); \n              } \n\n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                { \n                  local_matrix(i, j) += \n                    (k_inverse_values[q] * inverse_mobility * phi_u[i] * \n                       phi_u[j] + \n                     permeability * mobility * grad_phi_p[i] * grad_phi_p[j]) * \n                    darcy_fe_values.JxW(q); \n                } \n          } \n\n        cell->get_dof_indices(local_dof_indices); \n        darcy_preconditioner_constraints.distribute_local_to_global( \n          local_matrix, local_dof_indices, darcy_preconditioner_matrix); \n      } \n  } \n// @sect4{TwoPhaseFlowProblem<dim>::build_darcy_preconditioner}  \n\n// \u5728\u8c03\u7528\u4e0a\u8ff0\u51fd\u6570\u7ec4\u88c5\u9884\u5904\u7406\u77e9\u9635\u540e\uff0c\u8be5\u51fd\u6570\u751f\u6210\u5c06\u7528\u4e8e\u8212\u5c14\u8865\u5757\u9884\u5904\u7406\u7684\u5185\u90e8\u9884\u5904\u7406\u5668\u3002\u524d\u7f6e\u6761\u4ef6\u9700\u8981\u5728\u6bcf\u4e2a\u9971\u548c\u65f6\u95f4\u6b65\u957f\u65f6\u91cd\u65b0\u751f\u6210\uff0c\u56e0\u4e3a\u5b83\u4eec\u53d6\u51b3\u4e8e\u968f\u65f6\u95f4\u53d8\u5316\u7684\u9971\u548c\u5ea6  $S$  \u3002\n\n// \u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u4e3a\u901f\u5ea6-\u901f\u5ea6\u77e9\u9635  $\\mathbf{M}^{\\mathbf{u}}$  \u548cSchur\u8865\u7801  $\\mathbf{S}$  \u8bbe\u7f6e\u4e86\u9884\u5904\u7406\u5668\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u4e00\u4e2a\u57fa\u4e8e\u77e2\u91cf\u77e9\u9635 $\\mathbf{M}^{\\mathbf{u}}$ \u7684IC\u9884\u5904\u7406\u5668\u548c\u53e6\u4e00\u4e2a\u57fa\u4e8e\u6807\u91cf\u62c9\u666e\u62c9\u65af\u77e9\u9635 $\\tilde{\\mathbf{S}}^p$ \u7684IC\u9884\u5904\u7406\u5668\uff08\u5b83\u5728\u9891\u8c31\u4e0a\u4e0e\u8fbe\u897f\u77e9\u9635\u7684\u8212\u5c14\u8865\u7801\u63a5\u8fd1\uff09\u3002\u901a\u5e38\uff0c TrilinosWrappers::PreconditionIC \u7c7b\u53ef\u4ee5\u88ab\u770b\u4f5c\u662f\u4e00\u4e2a\u5f88\u597d\u7684\u9ed1\u76d2\u9884\u5904\u7406\u7a0b\u5e8f\uff0c\u4e0d\u9700\u8981\u5bf9\u77e9\u9635\u7ed3\u6784\u548c/\u6216\u80cc\u540e\u7684\u7b97\u5b50\u6709\u4efb\u4f55\u7279\u6b8a\u7684\u4e86\u89e3\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::build_darcy_preconditioner() \n  { \n    assemble_darcy_preconditioner(); \n\n    Amg_preconditioner = std::make_shared<TrilinosWrappers::PreconditionIC>(); \n    Amg_preconditioner->initialize(darcy_preconditioner_matrix.block(0, 0)); \n\n    Mp_preconditioner = std::make_shared<TrilinosWrappers::PreconditionIC>(); \n    Mp_preconditioner->initialize(darcy_preconditioner_matrix.block(1, 1)); \n  } \n// @sect4{TwoPhaseFlowProblem<dim>::assemble_darcy_system}  \n\n// \u8fd9\u662f\u4e3a\u8fbe\u897f\u7cfb\u7edf\u7ec4\u88c5\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\u3002\n\n// \u5173\u4e8e\u6267\u884c\u7684\u6280\u672f\u7ec6\u8282\uff0c\u5176\u7a0b\u5e8f\u4e0e  step-22  \u548c  step-31  \u4e2d\u7684\u7a0b\u5e8f\u76f8\u4f3c\u3002\u6211\u4eec\u91cd\u7f6e\u77e9\u9635\u548c\u5411\u91cf\uff0c\u5728\u5355\u5143\u683c\u4e0a\u521b\u5efa\u6b63\u4ea4\u516c\u5f0f\uff0c\u7136\u540e\u521b\u5efa\u76f8\u5e94\u7684FEValues\u5bf9\u8c61\u3002\n\n// \u6709\u4e00\u4ef6\u4e8b\u9700\u8981\u8bc4\u8bba\uff1a\u7531\u4e8e\u6211\u4eec\u6709\u4e00\u4e2a\u5355\u72ec\u7684\u6709\u9650\u5143\u548cDoFHandler\u6765\u5904\u7406\u9971\u548c\u95ee\u9898\uff0c\u6211\u4eec\u9700\u8981\u751f\u6210\u7b2c\u4e8c\u4e2aFEValues\u5bf9\u8c61\u6765\u6b63\u786e\u8bc4\u4f30\u9971\u548c\u89e3\u3002\u8981\u5b9e\u73b0\u8fd9\u4e00\u70b9\u5e76\u4e0d\u590d\u6742\uff1a\u53ea\u9700\u4f7f\u7528\u9971\u548c\u7ed3\u6784\uff0c\u5e76\u4e3a\u57fa\u51fd\u6570\u503c\u8bbe\u7f6e\u4e00\u4e2a\u66f4\u65b0\u6807\u5fd7\uff0c\u6211\u4eec\u9700\u8981\u5bf9\u9971\u548c\u89e3\u8fdb\u884c\u8bc4\u4f30\u3002\u8fd9\u91cc\u9700\u8981\u8bb0\u4f4f\u7684\u552f\u4e00\u91cd\u8981\u90e8\u5206\u662f\uff0c\u4e24\u4e2aFEValues\u5bf9\u8c61\u4f7f\u7528\u76f8\u540c\u7684\u6b63\u4ea4\u516c\u5f0f\uff0c\u4ee5\u786e\u4fdd\u6211\u4eec\u5728\u5faa\u73af\u8ba1\u7b97\u4e24\u4e2a\u5bf9\u8c61\u7684\u6b63\u4ea4\u70b9\u65f6\u83b7\u5f97\u5339\u914d\u7684\u4fe1\u606f\u3002\n\n// \u58f0\u660e\u7684\u8fc7\u7a0b\u4e2d\uff0c\u5bf9\u6570\u7ec4\u7684\u5927\u5c0f\u3001\u672c\u5730\u77e9\u9635\u7684\u521b\u5efa\u3001\u53f3\u624b\u8fb9\u4ee5\u53ca\u4e0e\u5168\u5c40\u7cfb\u7edf\u76f8\u6bd4\u8f83\u7684\u672c\u5730\u9053\u592b\u6307\u6570\u7684\u5411\u91cf\u90fd\u6709\u4e00\u4e9b\u5feb\u6377\u65b9\u5f0f\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::assemble_darcy_system() \n  { \n    darcy_matrix = 0; \n    darcy_rhs    = 0; \n\n    QGauss<dim>     quadrature_formula(darcy_degree + 2); \n    QGauss<dim - 1> face_quadrature_formula(darcy_degree + 2); \n\n    FEValues<dim> darcy_fe_values(darcy_fe, \n                                  quadrature_formula, \n                                  update_values | update_gradients | \n                                    update_quadrature_points | \n                                    update_JxW_values); \n\n    FEValues<dim> saturation_fe_values(saturation_fe, \n                                       quadrature_formula, \n                                       update_values); \n\n    FEFaceValues<dim> darcy_fe_face_values(darcy_fe, \n                                           face_quadrature_formula, \n                                           update_values | \n                                             update_normal_vectors | \n                                             update_quadrature_points | \n                                             update_JxW_values); \n\n    const unsigned int dofs_per_cell = darcy_fe.n_dofs_per_cell(); \n\n    const unsigned int n_q_points      = quadrature_formula.size(); \n    const unsigned int n_face_q_points = face_quadrature_formula.size(); \n\n    FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<double>     local_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    const Functions::ZeroFunction<dim> pressure_right_hand_side; \n    const PressureBoundaryValues<dim>  pressure_boundary_values; \n\n    std::vector<double>         pressure_rhs_values(n_q_points); \n    std::vector<double>         boundary_values(n_face_q_points); \n    std::vector<Tensor<2, dim>> k_inverse_values(n_q_points); \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u5411\u91cf\uff0c\u8be5\u5411\u91cf\u5c06\u5305\u542b\u524d\u4e00\u65f6\u95f4\u5c42\u5728\u6b63\u4ea4\u70b9\u7684\u9971\u548c\u89e3\u7684\u503c\uff0c\u4ee5\u7ec4\u88c5\u8fbe\u897f\u65b9\u7a0b\u4e2d\u7684\u9971\u548c\u76f8\u5173\u7cfb\u6570\u3002\n\n// \u6211\u4eec\u63a5\u4e0b\u6765\u521b\u5efa\u7684\u5411\u91cf\u96c6\u5305\u542b\u4e86\u57fa\u51fd\u6570\u7684\u8bc4\u4ef7\u4ee5\u53ca\u5b83\u4eec\u7684\u68af\u5ea6\uff0c\u5c06\u7528\u4e8e\u521b\u5efa\u77e9\u9635\u3002\u628a\u8fd9\u4e9b\u653e\u5230\u81ea\u5df1\u7684\u6570\u7ec4\u4e2d\uff0c\u800c\u4e0d\u662f\u6bcf\u6b21\u90fd\u5411FEValues\u5bf9\u8c61\u7d22\u53d6\u8fd9\u4e9b\u4fe1\u606f\uff0c\u662f\u4e3a\u4e86\u52a0\u901f\u88c5\u914d\u8fc7\u7a0b\u7684\u4f18\u5316\uff0c\u8be6\u60c5\u8bf7\u89c1 step-22 \u3002\n\n// \u6700\u540e\u4e24\u4e2a\u58f0\u660e\u662f\u7528\u6765\u4ece\u6574\u4e2aFE\u7cfb\u7edf\u4e2d\u63d0\u53d6\u5404\u4e2a\u5757\uff08\u901f\u5ea6\u3001\u538b\u529b\u3001\u9971\u548c\u5ea6\uff09\u7684\u3002\n\n    std::vector<double> old_saturation_values(n_q_points); \n\n    std::vector<Tensor<1, dim>> phi_u(dofs_per_cell); \n    std::vector<double>         div_phi_u(dofs_per_cell); \n    std::vector<double>         phi_p(dofs_per_cell); \n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure(dim); \n\n// \u73b0\u5728\u5f00\u59cb\u5bf9\u95ee\u9898\u4e2d\u7684\u6240\u6709\u5355\u5143\u683c\u8fdb\u884c\u5faa\u73af\u3002\u6211\u4eec\u5728\u8fd9\u4e2a\u88c5\u914d\u4f8b\u7a0b\u4e2d\u4f7f\u7528\u4e86\u4e24\u4e2a\u4e0d\u540c\u7684DoFHandlers\uff0c\u6240\u4ee5\u6211\u4eec\u5fc5\u987b\u4e3a\u4f7f\u7528\u4e2d\u7684\u4e24\u4e2a\u5bf9\u8c61\u8bbe\u7f6e\u4e24\u4e2a\u4e0d\u540c\u7684\u5355\u5143\u683c\u8fed\u4ee3\u5668\u3002\u8fd9\u53ef\u80fd\u770b\u8d77\u6765\u6709\u70b9\u5947\u602a\uff0c\u4f46\u662f\u7531\u4e8e\u8fbe\u897f\u7cfb\u7edf\u548c\u9971\u548c\u7cfb\u7edf\u90fd\u4f7f\u7528\u76f8\u540c\u7684\u7f51\u683c\uff0c\u6211\u4eec\u53ef\u4ee5\u5047\u8bbe\u8fd9\u4e24\u4e2a\u8fed\u4ee3\u5668\u5728\u4e24\u4e2aDoFHandler\u5bf9\u8c61\u7684\u5355\u5143\u683c\u4e2d\u540c\u6b65\u8fd0\u884c\u3002\n\n// \u5faa\u73af\u4e2d\u7684\u7b2c\u4e00\u6761\u8bed\u53e5\u53c8\u662f\u975e\u5e38\u719f\u6089\u7684\uff0c\u6309\u7167\u66f4\u65b0\u6807\u5fd7\u7684\u89c4\u5b9a\u5bf9\u6709\u9650\u5143\u6570\u636e\u8fdb\u884c\u66f4\u65b0\uff0c\u5c06\u5c40\u90e8\u6570\u7ec4\u6e05\u96f6\uff0c\u5e76\u5f97\u5230\u6b63\u4ea4\u70b9\u4e0a\u7684\u65e7\u89e3\u7684\u503c\u3002 \u5728\u8fd9\u4e00\u70b9\u4e0a\uff0c\u6211\u4eec\u8fd8\u5fc5\u987b\u5728\u6b63\u4ea4\u70b9\u4e0a\u83b7\u5f97\u524d\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u9971\u548c\u51fd\u6570\u7684\u503c\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528 FEValues::get_function_values \uff08\u4e4b\u524d\u5df2\u7ecf\u5728 step-9 \u3001 step-14 \u548c step-15 \u4e2d\u4f7f\u7528\uff09\uff0c\u8fd9\u4e2a\u51fd\u6570\u63a5\u6536\u4e00\u4e2a\u89e3\u5411\u91cf\uff0c\u5e76\u8fd4\u56de\u5f53\u524d\u5355\u5143\u7684\u6b63\u4ea4\u70b9\u7684\u51fd\u6570\u503c\u5217\u8868\u3002\u4e8b\u5b9e\u4e0a\uff0c\u5b83\u8fd4\u56de\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u7684\u5b8c\u6574\u77e2\u91cf\u503c\u89e3\uff0c\u5373\u4e0d\u4ec5\u662f\u9971\u548c\u5ea6\uff0c\u8fd8\u6709\u901f\u5ea6\u548c\u538b\u529b\u3002\n\n// \u7136\u540e\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5728\u5355\u5143\u683c\u4e0a\u7684\u6b63\u4ea4\u70b9\u4e0a\u8fdb\u884c\u5faa\u73af\uff0c\u4ee5\u8fdb\u884c\u79ef\u5206\u3002\u8fd9\u65b9\u9762\u7684\u516c\u5f0f\u76f4\u63a5\u6765\u81ea\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\u5185\u5bb9\u3002\n\n// \u4e00\u65e6\u8fd9\u6837\u505a\u4e86\uff0c\u6211\u4eec\u5c31\u5f00\u59cb\u5728\u5c40\u90e8\u77e9\u9635\u7684\u884c\u548c\u5217\u4e0a\u8fdb\u884c\u5faa\u73af\uff0c\u5e76\u5c06\u76f8\u5173\u7684\u4e58\u79ef\u8f93\u5165\u77e9\u9635\u4e2d\u3002\n\n// \u5faa\u73af\u6240\u6709\u5355\u5143\u7684\u6700\u540e\u4e00\u6b65\u662f\u5c06\u672c\u5730\u8d21\u732e\u8f93\u5165\u5230\u5168\u5c40\u77e9\u9635\u548c\u5411\u91cf\u7ed3\u6784\u4e2d\uff0c\u5e76\u5728local_dof_indices\u4e2d\u6307\u5b9a\u4f4d\u7f6e\u3002\u540c\u6837\uff0c\u6211\u4eec\u8ba9AffineConstraints\u7c7b\u5c06\u5355\u5143\u683c\u77e9\u9635\u5143\u7d20\u63d2\u5165\u5230\u5168\u5c40\u77e9\u9635\u4e2d\uff0c\u5168\u5c40\u77e9\u9635\u5df2\u7ecf\u6d53\u7f29\u4e86\u60ac\u6302\u8282\u70b9\u7684\u7ea6\u675f\u3002\n\n    auto       cell            = darcy_dof_handler.begin_active(); \n    const auto endc            = darcy_dof_handler.end(); \n    auto       saturation_cell = saturation_dof_handler.begin_active(); \n\n    for (; cell != endc; ++cell, ++saturation_cell) \n      { \n        darcy_fe_values.reinit(cell); \n        saturation_fe_values.reinit(saturation_cell); \n\n        local_matrix = 0; \n        local_rhs    = 0; \n\n        saturation_fe_values.get_function_values(old_saturation_solution, \n                                                 old_saturation_values); \n\n        pressure_right_hand_side.value_list( \n          darcy_fe_values.get_quadrature_points(), pressure_rhs_values); \n        k_inverse.value_list(darcy_fe_values.get_quadrature_points(), \n                             k_inverse_values); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            for (unsigned int k = 0; k < dofs_per_cell; ++k) \n              { \n                phi_u[k]     = darcy_fe_values[velocities].value(k, q); \n                div_phi_u[k] = darcy_fe_values[velocities].divergence(k, q); \n                phi_p[k]     = darcy_fe_values[pressure].value(k, q); \n              } \n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              { \n                const double old_s = old_saturation_values[q]; \n                for (unsigned int j = 0; j <= i; ++j) \n                  { \n                    local_matrix(i, j) += \n                      (phi_u[i] * k_inverse_values[q] * \n                         mobility_inverse(old_s, viscosity) * phi_u[j] - \n                       div_phi_u[i] * phi_p[j] - phi_p[i] * div_phi_u[j]) * \n                      darcy_fe_values.JxW(q); \n                  } \n\n                local_rhs(i) += \n                  (-phi_p[i] * pressure_rhs_values[q]) * darcy_fe_values.JxW(q); \n              } \n          } \n\n        for (const auto &face : cell->face_iterators()) \n          if (face->at_boundary()) \n            { \n              darcy_fe_face_values.reinit(cell, face); \n\n              pressure_boundary_values.value_list( \n                darcy_fe_face_values.get_quadrature_points(), boundary_values); \n\n              for (unsigned int q = 0; q < n_face_q_points; ++q) \n                for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                  { \n                    const Tensor<1, dim> phi_i_u = \n                      darcy_fe_face_values[velocities].value(i, q); \n\n                    local_rhs(i) += \n                      -(phi_i_u * darcy_fe_face_values.normal_vector(q) * \n                        boundary_values[q] * darcy_fe_face_values.JxW(q)); \n                  } \n            } \n\n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          for (unsigned int j = i + 1; j < dofs_per_cell; ++j) \n            local_matrix(i, j) = local_matrix(j, i); \n\n        cell->get_dof_indices(local_dof_indices); \n\n        darcy_constraints.distribute_local_to_global( \n          local_matrix, local_rhs, local_dof_indices, darcy_matrix, darcy_rhs); \n      } \n  } \n// @sect4{TwoPhaseFlowProblem<dim>::assemble_saturation_system}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u662f\u4e3a\u4e86\u7ec4\u88c5\u9971\u548c\u4f20\u8f93\u65b9\u7a0b\u7684\u7ebf\u6027\u7cfb\u7edf\u3002\u5982\u679c\u6709\u5fc5\u8981\uff0c\u5b83\u4f1a\u8c03\u7528\u53e6\u5916\u4e24\u4e2a\u6210\u5458\u51fd\u6570\uff1aassemble_saturation_matrix()\u548cassemble_saturation_rhs()\u3002\u524d\u4e00\u4e2a\u51fd\u6570\u7136\u540e\u7ec4\u88c5\u9971\u548c\u5ea6\u77e9\u9635\uff0c\u53ea\u9700\u8981\u5076\u5c14\u6539\u53d8\u3002\u53e6\u4e00\u65b9\u9762\uff0c\u540e\u4e00\u4e2a\u7ec4\u88c5\u53f3\u624b\u8fb9\u7684\u51fd\u6570\u5fc5\u987b\u5728\u6bcf\u4e2a\u9971\u548c\u65f6\u95f4\u6b65\u9aa4\u4e2d\u8c03\u7528\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::assemble_saturation_system() \n  { \n    if (rebuild_saturation_matrix == true) \n      { \n        saturation_matrix = 0; \n        assemble_saturation_matrix(); \n      } \n\n    saturation_rhs = 0; \n    assemble_saturation_rhs(); \n  } \n\n//  @sect4{TwoPhaseFlowProblem<dim>::assemble_saturation_matrix}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u5f88\u5bb9\u6613\u7406\u89e3\uff0c\u56e0\u4e3a\u5b83\u53ea\u662f\u901a\u8fc7\u57fa\u51fd\u6570phi_i_s\u548cphi_j_s\u4e3a\u9971\u548c\u7ebf\u6027\u7cfb\u7edf\u7684\u5de6\u4fa7\u5f62\u6210\u4e00\u4e2a\u7b80\u5355\u7684\u8d28\u91cf\u77e9\u9635\u3002\u6700\u540e\uff0c\u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u6211\u4eec\u901a\u8fc7\u5728local_dof_indices\u4e2d\u6307\u5b9a\u4f4d\u7f6e\u5c06\u5c40\u90e8\u8d21\u732e\u8f93\u5165\u5168\u5c40\u77e9\u9635\u3002\u8fd9\u662f\u901a\u8fc7\u8ba9AffineConstraints\u7c7b\u5c06\u5355\u5143\u77e9\u9635\u5143\u7d20\u63d2\u5165\u5168\u5c40\u77e9\u9635\u6765\u5b8c\u6210\u7684\uff0c\u5168\u5c40\u77e9\u9635\u5df2\u7ecf\u6d53\u7f29\u4e86\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::assemble_saturation_matrix() \n  { \n    QGauss<dim> quadrature_formula(saturation_degree + 2); \n\n    FEValues<dim> saturation_fe_values(saturation_fe, \n                                       quadrature_formula, \n                                       update_values | update_JxW_values); \n\n    const unsigned int dofs_per_cell = saturation_fe.n_dofs_per_cell(); \n\n    const unsigned int n_q_points = quadrature_formula.size(); \n\n    FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<double>     local_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    for (const auto &cell : saturation_dof_handler.active_cell_iterators()) \n      { \n        saturation_fe_values.reinit(cell); \n        local_matrix = 0; \n        local_rhs    = 0; \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            { \n              const double phi_i_s = saturation_fe_values.shape_value(i, q); \n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                { \n                  const double phi_j_s = saturation_fe_values.shape_value(j, q); \n                  local_matrix(i, j) += \n                    porosity * phi_i_s * phi_j_s * saturation_fe_values.JxW(q); \n                } \n            } \n        cell->get_dof_indices(local_dof_indices); \n\n        saturation_constraints.distribute_local_to_global(local_matrix, \n                                                          local_dof_indices, \n                                                          saturation_matrix); \n      } \n  } \n\n//  @sect4{TwoPhaseFlowProblem<dim>::assemble_saturation_rhs}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u662f\u7528\u6765\u7ec4\u88c5\u9971\u548c\u4f20\u8f93\u65b9\u7a0b\u7684\u53f3\u8fb9\u3002\u5728\u8fdb\u884c\u8fd9\u9879\u5de5\u4f5c\u4e4b\u524d\uff0c\u6211\u4eec\u5fc5\u987b\u4e3a\u8fbe\u897f\u7cfb\u7edf\u548c\u9971\u548c\u7cfb\u7edf\u5206\u522b\u521b\u5efa\u4e24\u4e2aFEValues\u5bf9\u8c61\uff0c\u6b64\u5916\uff0c\u8fd8\u5fc5\u987b\u4e3a\u8fd9\u4e24\u4e2a\u7cfb\u7edf\u521b\u5efa\u4e24\u4e2aFEFaceValues\u5bf9\u8c61\uff0c\u56e0\u4e3a\u6211\u4eec\u5728\u9971\u548c\u65b9\u7a0b\u7684\u5f31\u5f62\u5f0f\u4e2d\u5b58\u5728\u4e00\u4e2a\u8fb9\u754c\u79ef\u5206\u9879\u3002\u5bf9\u4e8e\u9971\u548c\u7cfb\u7edf\u7684FEFaceValues\u5bf9\u8c61\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u6cd5\u5411\u91cf\uff0c\u6211\u4eec\u4f7f\u7528update_normal_vectors\u6807\u5fd7\u6765\u7533\u8bf7\u3002\n\n// \u63a5\u4e0b\u6765\uff0c\u5728\u5bf9\u6240\u6709\u5355\u5143\u8fdb\u884c\u5faa\u73af\u4e4b\u524d\uff0c\u6211\u4eec\u5fc5\u987b\u8ba1\u7b97\u4e00\u4e9b\u53c2\u6570\uff08\u4f8b\u5982global_u_infty\u3001global_S_variation\u548cglobal_Omega_diameter\uff09\uff0c\u8fd9\u662f\u4eba\u5de5\u9ecf\u5ea6 $\\nu$ \u9700\u8981\u7684\u3002\u8fd9\u4e0e step-31 \u4e2d\u7684\u505a\u6cd5\u57fa\u672c\u76f8\u540c\uff0c\u6240\u4ee5\u4f60\u53ef\u4ee5\u5728\u90a3\u91cc\u770b\u5230\u66f4\u591a\u7684\u4fe1\u606f\u3002\n\n// \u771f\u6b63\u7684\u5de5\u4f5c\u662f\u4ece\u5faa\u73af\u6240\u6709\u7684\u9971\u548c\u548cDarcy\u5355\u5143\u5f00\u59cb\u7684\uff0c\u4ee5\u4fbf\u5c06\u5c40\u90e8\u8d21\u732e\u653e\u5230\u5168\u5c40\u77e2\u91cf\u4e2d\u3002\u5728\u8fd9\u4e2a\u5faa\u73af\u4e2d\uff0c\u4e3a\u4e86\u7b80\u5316\u5b9e\u73b0\uff0c\u6211\u4eec\u628a\u4e00\u4e9b\u5de5\u4f5c\u5206\u6210\u4e24\u4e2a\u8f85\u52a9\u51fd\u6570\uff1aassemble_saturation_rhs_cell_term\u548cassemble_saturation_rhs_boundary_term\u3002 \u6211\u4eec\u6ce8\u610f\u5230\uff0c\u6211\u4eec\u5728\u8fd9\u4e24\u4e2a\u51fd\u6570\u4e2d\u628a\u7ec6\u80de\u6216\u8fb9\u754c\u8d21\u732e\u63d2\u5165\u5168\u5c40\u5411\u91cf\uff0c\u800c\u4e0d\u662f\u5728\u672c\u51fd\u6570\u4e2d\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::assemble_saturation_rhs() \n  { \n    QGauss<dim>     quadrature_formula(saturation_degree + 2); \n    QGauss<dim - 1> face_quadrature_formula(saturation_degree + 2); \n\n    FEValues<dim> saturation_fe_values(saturation_fe, \n                                       quadrature_formula, \n                                       update_values | update_gradients | \n                                         update_quadrature_points | \n                                         update_JxW_values); \n    FEValues<dim> darcy_fe_values(darcy_fe, quadrature_formula, update_values); \n    FEFaceValues<dim> saturation_fe_face_values(saturation_fe, \n                                                face_quadrature_formula, \n                                                update_values | \n                                                  update_normal_vectors | \n                                                  update_quadrature_points | \n                                                  update_JxW_values); \n    FEFaceValues<dim> darcy_fe_face_values(darcy_fe, \n                                           face_quadrature_formula, \n                                           update_values); \n    FEFaceValues<dim> saturation_fe_face_values_neighbor( \n      saturation_fe, face_quadrature_formula, update_values); \n\n    const unsigned int dofs_per_cell = \n      saturation_dof_handler.get_fe().n_dofs_per_cell(); \n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    const double                    global_max_u_F_prime = get_max_u_F_prime(); \n    const std::pair<double, double> global_S_range = \n      get_extrapolated_saturation_range(); \n    const double global_S_variation = \n      global_S_range.second - global_S_range.first; \n\n    auto       cell       = saturation_dof_handler.begin_active(); \n    const auto endc       = saturation_dof_handler.end(); \n    auto       darcy_cell = darcy_dof_handler.begin_active(); \n    for (; cell != endc; ++cell, ++darcy_cell) \n      { \n        saturation_fe_values.reinit(cell); \n        darcy_fe_values.reinit(darcy_cell); \n\n        cell->get_dof_indices(local_dof_indices); \n\n        assemble_saturation_rhs_cell_term(saturation_fe_values, \n                                          darcy_fe_values, \n                                          global_max_u_F_prime, \n                                          global_S_variation, \n                                          local_dof_indices); \n\n        for (const auto &face : cell->face_iterators()) \n          if (face->at_boundary()) \n            { \n              darcy_fe_face_values.reinit(darcy_cell, face); \n              saturation_fe_face_values.reinit(cell, face); \n              assemble_saturation_rhs_boundary_term(saturation_fe_face_values, \n                                                    darcy_fe_face_values, \n                                                    local_dof_indices); \n            } \n      } \n  } \n\n//  @sect4{TwoPhaseFlowProblem<dim>::assemble_saturation_rhs_cell_term}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u8d1f\u8d23\u6574\u5408\u9971\u548c\u5ea6\u65b9\u7a0b\u53f3\u8fb9\u7684\u5355\u5143\u9879\uff0c\u7136\u540e\u5c06\u5176\u7ec4\u88c5\u6210\u5168\u5c40\u53f3\u8fb9\u7684\u77e2\u91cf\u3002\u9274\u4e8e\u4ecb\u7ecd\u4e2d\u7684\u8ba8\u8bba\uff0c\u8fd9\u4e9b\u8d21\u732e\u7684\u5f62\u5f0f\u5f88\u6e05\u695a\u3002\u552f\u4e00\u68d8\u624b\u7684\u90e8\u5206\u662f\u83b7\u5f97\u4eba\u5de5\u9ecf\u5ea6\u548c\u8ba1\u7b97\u5b83\u6240\u9700\u7684\u4e00\u5207\u3002\u8be5\u51fd\u6570\u7684\u524d\u534a\u90e8\u5206\u4e13\u95e8\u7528\u4e8e\u8fd9\u9879\u4efb\u52a1\u3002\n\n// \u8be5\u51fd\u6570\u7684\u6700\u540e\u4e00\u90e8\u5206\u662f\u5c06\u5c40\u90e8\u8d21\u732e\u590d\u5236\u5230\u5168\u5c40\u5411\u91cf\u4e2d\uff0c\u5176\u4f4d\u7f6e\u7531local_dof_indices\u6307\u5b9a\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::assemble_saturation_rhs_cell_term( \n    const FEValues<dim> &                       saturation_fe_values, \n    const FEValues<dim> &                       darcy_fe_values, \n    const double                                global_max_u_F_prime, \n    const double                                global_S_variation, \n    const std::vector<types::global_dof_index> &local_dof_indices) \n  { \n    const unsigned int dofs_per_cell = saturation_fe_values.dofs_per_cell; \n    const unsigned int n_q_points    = saturation_fe_values.n_quadrature_points; \n\n    std::vector<double>         old_saturation_solution_values(n_q_points); \n    std::vector<double>         old_old_saturation_solution_values(n_q_points); \n    std::vector<Tensor<1, dim>> old_grad_saturation_solution_values(n_q_points); \n    std::vector<Tensor<1, dim>> old_old_grad_saturation_solution_values( \n      n_q_points); \n    std::vector<Vector<double>> present_darcy_solution_values( \n      n_q_points, Vector<double>(dim + 1)); \n\n    saturation_fe_values.get_function_values(old_saturation_solution, \n                                             old_saturation_solution_values); \n    saturation_fe_values.get_function_values( \n      old_old_saturation_solution, old_old_saturation_solution_values); \n    saturation_fe_values.get_function_gradients( \n      old_saturation_solution, old_grad_saturation_solution_values); \n    saturation_fe_values.get_function_gradients( \n      old_old_saturation_solution, old_old_grad_saturation_solution_values); \n    darcy_fe_values.get_function_values(darcy_solution, \n                                        present_darcy_solution_values); \n\n    const double nu = \n      compute_viscosity(old_saturation_solution_values, \n                        old_old_saturation_solution_values, \n                        old_grad_saturation_solution_values, \n                        old_old_grad_saturation_solution_values, \n                        present_darcy_solution_values, \n                        global_max_u_F_prime, \n                        global_S_variation, \n                        saturation_fe_values.get_cell()->diameter()); \n\n    Vector<double> local_rhs(dofs_per_cell); \n\n    for (unsigned int q = 0; q < n_q_points; ++q) \n      for (unsigned int i = 0; i < dofs_per_cell; ++i) \n        { \n          const double   old_s = old_saturation_solution_values[q]; \n          Tensor<1, dim> present_u; \n          for (unsigned int d = 0; d < dim; ++d) \n            present_u[d] = present_darcy_solution_values[q](d); \n\n          const double         phi_i_s = saturation_fe_values.shape_value(i, q); \n          const Tensor<1, dim> grad_phi_i_s = \n            saturation_fe_values.shape_grad(i, q); \n\n          local_rhs(i) += \n            (time_step * fractional_flow(old_s, viscosity) * present_u * \n               grad_phi_i_s - \n             time_step * nu * old_grad_saturation_solution_values[q] * \n               grad_phi_i_s + \n             porosity * old_s * phi_i_s) * \n            saturation_fe_values.JxW(q); \n        } \n\n    saturation_constraints.distribute_local_to_global(local_rhs, \n                                                      local_dof_indices, \n                                                      saturation_rhs); \n  } \n// @sect4{TwoPhaseFlowProblem<dim>::assemble_saturation_rhs_boundary_term}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u8d1f\u8d23\u9971\u548c\u65b9\u7a0b\u53f3\u4fa7\u5f62\u5f0f\u4e2d\u7684\u8fb9\u754c\u79ef\u5206\u9879\u3002 \u5bf9\u4e8e\u8fd9\u4e9b\uff0c\u6211\u4eec\u5fc5\u987b\u8ba1\u7b97\u5168\u5c40\u8fb9\u754c\u9762\u4e0a\u7684\u4e0a\u884c\u901a\u91cf\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u53ea\u5bf9\u5168\u5c40\u8fb9\u754c\u7684\u6d41\u5165\u90e8\u5206\u5f31\u52a0\u8fea\u91cc\u5207\u7279\u8fb9\u754c\u6761\u4ef6\u3002\u5982\u524d\u6240\u8ff0\uff0c\u8fd9\u5728 step-21 \u4e2d\u5df2\u7ecf\u63cf\u8ff0\u8fc7\u4e86\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u5bf9\u5176\u8fdb\u884c\u66f4\u591a\u7684\u63cf\u8ff0\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::assemble_saturation_rhs_boundary_term( \n    const FEFaceValues<dim> &                   saturation_fe_face_values, \n    const FEFaceValues<dim> &                   darcy_fe_face_values, \n    const std::vector<types::global_dof_index> &local_dof_indices) \n  { \n    const unsigned int dofs_per_cell = saturation_fe_face_values.dofs_per_cell; \n    const unsigned int n_face_q_points = \n      saturation_fe_face_values.n_quadrature_points; \n\n    Vector<double> local_rhs(dofs_per_cell); \n\n \n    std::vector<Vector<double>> present_darcy_solution_values_face( \n      n_face_q_points, Vector<double>(dim + 1)); \n    std::vector<double> neighbor_saturation(n_face_q_points); \n\n    saturation_fe_face_values.get_function_values( \n      old_saturation_solution, old_saturation_solution_values_face); \n    darcy_fe_face_values.get_function_values( \n      darcy_solution, present_darcy_solution_values_face); \n\n    SaturationBoundaryValues<dim> saturation_boundary_values; \n    saturation_boundary_values.value_list( \n      saturation_fe_face_values.get_quadrature_points(), neighbor_saturation); \n\n    for (unsigned int q = 0; q < n_face_q_points; ++q) \n      { \n        Tensor<1, dim> present_u_face; \n        for (unsigned int d = 0; d < dim; ++d) \n          present_u_face[d] = present_darcy_solution_values_face[q](d); \n\n \n          present_u_face * saturation_fe_face_values.normal_vector(q); \n\n        const bool is_outflow_q_point = (normal_flux >= 0); \n\n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          local_rhs(i) -= \n            time_step * normal_flux * \n            fractional_flow((is_outflow_q_point == true ? \n                               old_saturation_solution_values_face[q] : \n                               neighbor_saturation[q]), \n                            viscosity) * \n            saturation_fe_face_values.shape_value(i, q) * \n            saturation_fe_face_values.JxW(q); \n      } \n    saturation_constraints.distribute_local_to_global(local_rhs, \n                                                      local_dof_indices, \n                                                      saturation_rhs); \n  } \n// @sect3{TwoPhaseFlowProblem<dim>::solve}  \n\n// \u8be5\u51fd\u6570\u5b9e\u73b0\u4e86\u7b97\u5b50\u5206\u5272\u7b97\u6cd5\uff0c\u5373\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\uff0c\u5b83\u8981\u4e48\u91cd\u65b0\u8ba1\u7b97\u8fbe\u897f\u7cfb\u7edf\u7684\u89e3\uff0c\u8981\u4e48\u4ece\u4ee5\u524d\u7684\u65f6\u95f4\u6b65\u957f\u4e2d\u63a8\u7b97\u51fa\u901f\u5ea6/\u538b\u529b\uff0c\u7136\u540e\u786e\u5b9a\u65f6\u95f4\u6b65\u957f\u7684\u5927\u5c0f\uff0c\u7136\u540e\u66f4\u65b0\u9971\u548c\u5ea6\u53d8\u91cf\u3002\u5176\u5b9e\u73b0\u4e3b\u8981\u9075\u5faa  step-31  \u4e2d\u7684\u7c7b\u4f3c\u4ee3\u7801\u3002\u9664\u4e86run()\u51fd\u6570\u5916\uff0c\u5b83\u662f\u672c\u7a0b\u5e8f\u4e2d\u7684\u6838\u5fc3\u51fd\u6570\u3002\n\n// \u5728\u51fd\u6570\u7684\u5f00\u59cb\uff0c\u6211\u4eec\u8be2\u95ee\u662f\u5426\u8981\u901a\u8fc7\u8bc4\u4f30\u540e\u9a8c\u51c6\u5219\u6765\u89e3\u51b3\u538b\u529b-\u901f\u5ea6\u90e8\u5206\uff08\u89c1\u4e0b\u9762\u7684\u51fd\u6570\uff09\u3002\u5982\u679c\u6709\u5fc5\u8981\uff0c\u6211\u4eec\u5c06\u4f7f\u7528GMRES\u6c42\u89e3\u5668\u548cSchur\u8865\u5145\u5757\u9884\u5904\u7406\u6765\u6c42\u89e3\u538b\u529b-\u901f\u5ea6\u90e8\u5206\uff0c\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::solve() \n  { \n    const bool solve_for_pressure_and_velocity = \n      determine_whether_to_solve_for_pressure_and_velocity(); \n\n    if (solve_for_pressure_and_velocity == true) \n      { \n        std::cout << \"   Solving Darcy (pressure-velocity) system...\" \n                  << std::endl; \n\n        assemble_darcy_system(); \n        build_darcy_preconditioner(); \n\n        { \n          const LinearSolvers::InverseMatrix<TrilinosWrappers::SparseMatrix, \n                                             TrilinosWrappers::PreconditionIC> \n            mp_inverse(darcy_preconditioner_matrix.block(1, 1), \n                       *Mp_preconditioner); \n\n          const LinearSolvers::BlockSchurPreconditioner< \n            TrilinosWrappers::PreconditionIC, \n            TrilinosWrappers::PreconditionIC> \n            preconditioner(darcy_matrix, mp_inverse, *Amg_preconditioner); \n\n          SolverControl solver_control(darcy_matrix.m(), \n                                       1e-16 * darcy_rhs.l2_norm()); \n\n          SolverGMRES<TrilinosWrappers::MPI::BlockVector> gmres( \n            solver_control, \n            SolverGMRES<TrilinosWrappers::MPI::BlockVector>::AdditionalData( \n              100)); \n\n          for (unsigned int i = 0; i < darcy_solution.size(); ++i) \n            if (darcy_constraints.is_constrained(i)) \n              darcy_solution(i) = 0; \n\n          gmres.solve(darcy_matrix, darcy_solution, darcy_rhs, preconditioner); \n\n          darcy_constraints.distribute(darcy_solution); \n\n          std::cout << \"        ...\" << solver_control.last_step() \n                    << \" GMRES iterations.\" << std::endl; \n        } \n\n        { \n  }; \n          last_computed_darcy_solution        = darcy_solution; \n\n          saturation_matching_last_computed_darcy_solution = \n            saturation_solution; \n        } \n      } \n\n// \u53e6\u4e00\u65b9\u9762\uff0c\u5982\u679c\u6211\u4eec\u51b3\u5b9a\u4e0d\u8ba1\u7b97\u5f53\u524d\u65f6\u95f4\u6b65\u957f\u7684\u8fbe\u897f\u7cfb\u7edf\u7684\u89e3\uff0c\u90a3\u4e48\u6211\u4eec\u9700\u8981\u7b80\u5355\u5730\u5c06\u524d\u4e24\u4e2a\u8fbe\u897f\u89e3\u5916\u63a8\u5230\u4e0e\u6211\u4eec\u8ba1\u7b97\u901f\u5ea6/\u538b\u529b\u7684\u65f6\u95f4\u76f8\u540c\u3002\u6211\u4eec\u505a\u4e00\u4e2a\u7b80\u5355\u7684\u7ebf\u6027\u5916\u63a8\uff0c\u5373\u7ed9\u5b9a\u4ece\u4e0a\u6b21\u8ba1\u7b97\u8fbe\u897f\u89e3\u5230\u73b0\u5728\u7684\u5b8f\u89c2\u65f6\u95f4\u6b65\u957f $dt$ \uff08\u7531 <code>current_macro_time_step</code> \u7ed9\u51fa\uff09\uff0c\u4ee5\u53ca $DT$ \u4e0a\u4e00\u4e2a\u5b8f\u89c2\u65f6\u95f4\u6b65\u957f\uff08\u7531 <code>old_macro_time_step</code> \u7ed9\u51fa\uff09\uff0c\u7136\u540e\u5f97\u5230 $u^\\ast = u_p + dt \\frac{u_p-u_{pp}}{DT} = (1+dt/DT)u_p - dt/DT u_{pp}$  \uff0c\u5176\u4e2d $u_p$ \u548c $u_{pp}$ \u662f\u6700\u8fd1\u4e24\u4e2a\u8ba1\u7b97\u7684\u8fbe\u897f\u89e3\u3002\u6211\u4eec\u53ea\u9700\u7528\u4e24\u884c\u4ee3\u7801\u5c31\u53ef\u4ee5\u5b9e\u73b0\u8fd9\u4e2a\u516c\u5f0f\u3002\n\n// \u8bf7\u6ce8\u610f\uff0c\u8fd9\u91cc\u7684\u7b97\u6cd5\u53ea\u6709\u5728\u6211\u4eec\u81f3\u5c11\u6709\u4e24\u4e2a\u5148\u524d\u8ba1\u7b97\u7684Darcy\u89e3\uff0c\u6211\u4eec\u53ef\u4ee5\u4ece\u4e2d\u63a8\u65ad\u51fa\u5f53\u524d\u7684\u65f6\u95f4\uff0c\u8fd9\u4e00\u70b9\u901a\u8fc7\u8981\u6c42\u91cd\u65b0\u8ba1\u7b97\u524d\u4e24\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7684Darcy\u89e3\u6765\u4fdd\u8bc1\u3002\n\n    else \n      { \n        darcy_solution = last_computed_darcy_solution; \n        darcy_solution.sadd(1 + current_macro_time_step / old_macro_time_step, \n                            -current_macro_time_step / old_macro_time_step, \n                            second_last_computed_darcy_solution); \n      } \n\n// \u7528\u8fd9\u6837\u8ba1\u7b97\u51fa\u6765\u7684\u901f\u5ea6\u77e2\u91cf\uff0c\u6839\u636e\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684CFL\u6807\u51c6\u8ba1\u7b97\u51fa\u6700\u4f73\u65f6\u95f4\u6b65\u957f......\n\n    { \n      old_time_step = time_step; \n\n      const double max_u_F_prime = get_max_u_F_prime(); \n      if (max_u_F_prime > 0) \n        time_step = porosity * GridTools::minimal_cell_diameter(triangulation) / \n                    saturation_degree / max_u_F_prime / 50; \n      else \n        time_step = end_time - time; \n    } \n\n// ......\u7136\u540e\u5728\u6211\u4eec\u5904\u7406\u65f6\u95f4\u6b65\u957f\u7684\u65f6\u5019\uff0c\u8fd8\u8981\u66f4\u65b0\u6211\u4eec\u4f7f\u7528\u7684\u5b8f\u89c2\u65f6\u95f4\u6b65\u957f\u3002\u5177\u4f53\u800c\u8a00\uff0c\u8fd9\u6d89\u53ca\u5230\u3002(i) \u5982\u679c\u6211\u4eec\u521a\u521a\u91cd\u65b0\u8ba1\u7b97\u4e86\u8fbe\u897f\u89e3\uff0c\u90a3\u4e48\u4e4b\u524d\u7684\u5b8f\u89c2\u65f6\u95f4\u6b65\u957f\u73b0\u5728\u662f\u56fa\u5b9a\u7684\uff0c\u5f53\u524d\u7684\u5b8f\u89c2\u65f6\u95f4\u6b65\u957f\uff0c\u5230\u73b0\u5728\u4e3a\u6b62\uff0c\u53ea\u662f\u5f53\u524d\uff08\u5fae\u89c2\uff09\u65f6\u95f4\u6b65\u957f\u3002(ii) \u5982\u679c\u6211\u4eec\u6ca1\u6709\u91cd\u65b0\u8ba1\u7b97\u8fbe\u897f\u89e3\uff0c\u90a3\u4e48\u5f53\u524d\u7684\u5b8f\u89c2\u65f6\u95f4\u6b65\u957f\u521a\u521a\u589e\u957f\u4e86 <code>time_step</code>  \u3002\n\n    if (solve_for_pressure_and_velocity == true) \n      { \n        old_macro_time_step     = current_macro_time_step; \n        current_macro_time_step = time_step; \n      } \n    else \n      current_macro_time_step += time_step; \n\n// \u8fd9\u4e2a\u51fd\u6570\u7684\u6700\u540e\u4e00\u6b65\u662f\u6839\u636e\u6211\u4eec\u521a\u521a\u5f97\u5230\u7684\u901f\u5ea6\u573a\u91cd\u65b0\u8ba1\u7b97\u9971\u548c\u89e3\u3002\u8fd9\u81ea\u7136\u53d1\u751f\u5728\u6bcf\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\uff0c\u6211\u4eec\u4e0d\u4f1a\u8df3\u8fc7\u8fd9\u4e9b\u8ba1\u7b97\u3002\u5728\u8ba1\u7b97\u9971\u548c\u5ea6\u7684\u6700\u540e\uff0c\u6211\u4eec\u6295\u5c04\u56de\u5141\u8bb8\u7684\u533a\u95f4 $[0,1]$ \uff0c\u4ee5\u786e\u4fdd\u6211\u4eec\u7684\u89e3\u4fdd\u6301\u7269\u7406\u72b6\u6001\u3002\n\n    { \n      std::cout << \"   Solving saturation transport equation...\" << std::endl; \n\n      assemble_saturation_system(); \n\n      SolverControl solver_control(saturation_matrix.m(), \n                                   1e-16 * saturation_rhs.l2_norm()); \n      SolverCG<TrilinosWrappers::MPI::Vector> cg(solver_control); \n\n      TrilinosWrappers::PreconditionIC preconditioner; \n      preconditioner.initialize(saturation_matrix); \n\n      cg.solve(saturation_matrix, \n               saturation_solution, \n               saturation_rhs, \n               preconditioner); \n\n      saturation_constraints.distribute(saturation_solution); \n      project_back_saturation(); \n\n      std::cout << \"        ...\" << solver_control.last_step() \n                << \" CG iterations.\" << std::endl; \n    } \n  } \n// @sect3{TwoPhaseFlowProblem<dim>::refine_mesh}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u5bf9\u7f51\u683c\u8fdb\u884c\u7ec6\u5316\u548c\u7c97\u5316\u3002\u5b83\u7684\u5de5\u4f5c\u5206\u4e09\u5757\u8fdb\u884c\u3002(i) \u8ba1\u7b97\u7ec6\u5316\u6307\u6807\uff0c\u65b9\u6cd5\u662f\u901a\u8fc7\u4f7f\u7528\u5404\u81ea\u7684\u65f6\u95f4\u6b65\u957f\uff08\u5982\u679c\u8fd9\u662f\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\uff0c\u5219\u53d6\u552f\u4e00\u7684\u89e3\u51b3\u65b9\u6848\uff09\uff0c\u4ece\u524d\u4e24\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u7ebf\u6027\u63a8\u65ad\u51fa\u7684\u89e3\u51b3\u65b9\u6848\u5411\u91cf\u7684\u68af\u5ea6\u3002(ii) \u5728\u68af\u5ea6\u5927\u4e8e\u6216\u5c0f\u4e8e\u67d0\u4e00\u9608\u503c\u7684\u5355\u5143\u4e2d\u6807\u8bb0\u51fa\u7ec6\u5316\u548c\u7c97\u5316\u7684\u5355\u5143\uff0c\u4fdd\u7559\u7f51\u683c\u7ec6\u5316\u7684\u6700\u5c0f\u548c\u6700\u5927\u6c34\u5e73\u3002(iii) \u5c06\u89e3\u51b3\u65b9\u6848\u4ece\u65e7\u7f51\u683c\u8f6c\u79fb\u5230\u65b0\u7f51\u683c\u3002\u8fd9\u4e9b\u90fd\u4e0d\u662f\u7279\u522b\u56f0\u96be\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::refine_mesh(const unsigned int min_grid_level, \n                                             const unsigned int max_grid_level) \n  { \n    Vector<double> refinement_indicators(triangulation.n_active_cells()); \n    { \n      const QMidpoint<dim>        quadrature_formula; \n      FEValues<dim>               fe_values(saturation_fe, \n                              quadrature_formula, \n                              update_gradients); \n      std::vector<Tensor<1, dim>> grad_saturation(1); \n\n      TrilinosWrappers::MPI::Vector extrapolated_saturation_solution( \n        saturation_solution); \n      if (timestep_number != 0) \n        extrapolated_saturation_solution.sadd((1. + time_step / old_time_step), \n                                              time_step / old_time_step, \n                                              old_saturation_solution); \n\n      for (const auto &cell : saturation_dof_handler.active_cell_iterators()) \n        { \n          const unsigned int cell_no = cell->active_cell_index(); \n          fe_values.reinit(cell); \n          fe_values.get_function_gradients(extrapolated_saturation_solution, \n                                           grad_saturation); \n\n          refinement_indicators(cell_no) = grad_saturation[0].norm(); \n        } \n    } \n\n    { \n      for (const auto &cell : saturation_dof_handler.active_cell_iterators()) \n        { \n          const unsigned int cell_no = cell->active_cell_index(); \n          cell->clear_coarsen_flag(); \n          cell->clear_refine_flag(); \n\n          if ((static_cast<unsigned int>(cell->level()) < max_grid_level) && \n              (std::fabs(refinement_indicators(cell_no)) > \n               saturation_refinement_threshold)) \n            cell->set_refine_flag(); \n          else if ((static_cast<unsigned int>(cell->level()) > \n                    min_grid_level) && \n                   (std::fabs(refinement_indicators(cell_no)) < \n                    0.5 * saturation_refinement_threshold)) \n            cell->set_coarsen_flag(); \n        } \n    } \n\n    triangulation.prepare_coarsening_and_refinement(); \n\n    { \n      std::vector<TrilinosWrappers::MPI::Vector> x_saturation(3); \n      x_saturation[0] = saturation_solution; \n      x_saturation[1] = old_saturation_solution; \n      x_saturation[2] = saturation_matching_last_computed_darcy_solution; \n\n      std::vector<TrilinosWrappers::MPI::BlockVector> x_darcy(2); \n      x_darcy[0] = last_computed_darcy_solution; \n      x_darcy[1] = second_last_computed_darcy_solution; \n\n      SolutionTransfer<dim, TrilinosWrappers::MPI::Vector> saturation_soltrans( \n        saturation_dof_handler); \n\n      SolutionTransfer<dim, TrilinosWrappers::MPI::BlockVector> darcy_soltrans( \n        darcy_dof_handler); \n\n      triangulation.prepare_coarsening_and_refinement(); \n      saturation_soltrans.prepare_for_coarsening_and_refinement(x_saturation); \n\n      darcy_soltrans.prepare_for_coarsening_and_refinement(x_darcy); \n\n      triangulation.execute_coarsening_and_refinement(); \n      setup_dofs(); \n\n      std::vector<TrilinosWrappers::MPI::Vector> tmp_saturation(3); \n      tmp_saturation[0].reinit(saturation_solution); \n      tmp_saturation[1].reinit(saturation_solution); \n      tmp_saturation[2].reinit(saturation_solution); \n      saturation_soltrans.interpolate(x_saturation, tmp_saturation); \n\n      saturation_solution                              = tmp_saturation[0]; \n      old_saturation_solution                          = tmp_saturation[1]; \n      saturation_matching_last_computed_darcy_solution = tmp_saturation[2]; \n\n      saturation_constraints.distribute(saturation_solution); \n      saturation_constraints.distribute(old_saturation_solution); \n      saturation_constraints.distribute( \n        saturation_matching_last_computed_darcy_solution); \n\n      std::vector<TrilinosWrappers::MPI::BlockVector> tmp_darcy(2); \n      tmp_darcy[0].reinit(darcy_solution); \n      tmp_darcy[1].reinit(darcy_solution); \n      darcy_soltrans.interpolate(x_darcy, tmp_darcy); \n\n      last_computed_darcy_solution        = tmp_darcy[0]; \n      second_last_computed_darcy_solution = tmp_darcy[1]; \n\n      darcy_constraints.distribute(last_computed_darcy_solution); \n      darcy_constraints.distribute(second_last_computed_darcy_solution); \n\n      rebuild_saturation_matrix = true; \n    } \n  } \n\n//  @sect3{TwoPhaseFlowProblem<dim>::output_results}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u751f\u6210\u56fe\u5f62\u8f93\u51fa\u3002\u5b83\u5b9e\u8d28\u4e0a\u662f\u5bf9  step-31  \u4e2d\u5b9e\u73b0\u7684\u590d\u5236\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::output_results() const \n  { \n    const FESystem<dim> joint_fe(darcy_fe, 1, saturation_fe, 1); \n    DoFHandler<dim>     joint_dof_handler(triangulation); \n    joint_dof_handler.distribute_dofs(joint_fe); \n    Assert(joint_dof_handler.n_dofs() == \n             darcy_dof_handler.n_dofs() + saturation_dof_handler.n_dofs(), \n           ExcInternalError()); \n\n    Vector<double> joint_solution(joint_dof_handler.n_dofs()); \n\n    { \n      std::vector<types::global_dof_index> local_joint_dof_indices( \n        joint_fe.n_dofs_per_cell()); \n      std::vector<types::global_dof_index> local_darcy_dof_indices( \n        darcy_fe.n_dofs_per_cell()); \n      std::vector<types::global_dof_index> local_saturation_dof_indices( \n        saturation_fe.n_dofs_per_cell()); \n\n      auto       joint_cell      = joint_dof_handler.begin_active(); \n      const auto joint_endc      = joint_dof_handler.end(); \n      auto       darcy_cell      = darcy_dof_handler.begin_active(); \n      auto       saturation_cell = saturation_dof_handler.begin_active(); \n\n      for (; joint_cell != joint_endc; \n           ++joint_cell, ++darcy_cell, ++saturation_cell) \n        { \n          joint_cell->get_dof_indices(local_joint_dof_indices); \n          darcy_cell->get_dof_indices(local_darcy_dof_indices); \n          saturation_cell->get_dof_indices(local_saturation_dof_indices); \n\n          for (unsigned int i = 0; i < joint_fe.n_dofs_per_cell(); ++i) \n            if (joint_fe.system_to_base_index(i).first.first == 0) \n              { \n                Assert(joint_fe.system_to_base_index(i).second < \n                         local_darcy_dof_indices.size(), \n                       ExcInternalError()); \n                joint_solution(local_joint_dof_indices[i]) = darcy_solution( \n                  local_darcy_dof_indices[joint_fe.system_to_base_index(i) \n                                            .second]); \n              } \n            else \n              { \n                Assert(joint_fe.system_to_base_index(i).first.first == 1, \n                       ExcInternalError()); \n                Assert(joint_fe.system_to_base_index(i).second < \n                         local_darcy_dof_indices.size(), \n                       ExcInternalError()); \n                joint_solution(local_joint_dof_indices[i]) = \n                  saturation_solution( \n                    local_saturation_dof_indices \n                      [joint_fe.system_to_base_index(i).second]); \n              } \n        } \n    } \n    std::vector<std::string> joint_solution_names(dim, \"velocity\"); \n    joint_solution_names.emplace_back(\"pressure\"); \n    joint_solution_names.emplace_back(\"saturation\"); \n\n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      data_component_interpretation( \n        dim, DataComponentInterpretation::component_is_part_of_vector); \n    data_component_interpretation.push_back( \n      DataComponentInterpretation::component_is_scalar); \n    data_component_interpretation.push_back( \n      DataComponentInterpretation::component_is_scalar); \n\n    DataOut<dim> data_out; \n\n    data_out.attach_dof_handler(joint_dof_handler); \n    data_out.add_data_vector(joint_solution, \n                             joint_solution_names, \n                             DataOut<dim>::type_dof_data, \n                             data_component_interpretation); \n\n    data_out.build_patches(); \n\n    std::string filename = \n      \"solution-\" + Utilities::int_to_string(timestep_number, 5) + \".vtu\"; \n    std::ofstream output(filename); \n    data_out.write_vtu(output); \n  } \n\n//  @sect3{Tool functions}  \n// @sect4{TwoPhaseFlowProblem<dim>::determine_whether_to_solve_for_pressure_and_velocity}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u5b9e\u73b0\u4e86\u81ea\u9002\u5e94\u8fd0\u7b97\u7b26\u62c6\u5206\u7684\u540e\u9a8c\u6807\u51c6\u3002\u8003\u8651\u5230\u6211\u4eec\u5728\u4e0a\u9762\u5b9e\u73b0\u5176\u4ed6\u51fd\u6570\u7684\u65b9\u5f0f\uff0c\u5e76\u8003\u8651\u5230\u8bba\u6587\u4e2d\u5f97\u51fa\u7684\u51c6\u5219\u516c\u5f0f\uff0c\u8be5\u51fd\u6570\u662f\u76f8\u5bf9\u7b80\u5355\u7684\u3002\n\n// \u5982\u679c\u6211\u4eec\u51b3\u5b9a\u8981\u91c7\u7528\u539f\u59cb\u7684IMPES\u65b9\u6cd5\uff0c\u5373\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u6c42\u89e3Darcy\u65b9\u7a0b\uff0c\u90a3\u4e48\u53ef\u4ee5\u901a\u8fc7\u5c06\u9608\u503c <code>AOS_threshold</code> \uff08\u9ed8\u8ba4\u4e3a $5.0$ \uff09\u8bbe\u7f6e\u4e3a0\u6765\u5b9e\u73b0\uff0c\u4ece\u800c\u8feb\u4f7f\u8be5\u51fd\u6570\u603b\u662f\u8fd4\u56detrue\u3002\n\n// \u6700\u540e\uff0c\u8bf7\u6ce8\u610f\uff0c\u8be5\u51fd\u6570\u5728\u524d\u4e24\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u65e0\u6761\u4ef6\u5730\u8fd4\u56de\u771f\uff0c\u4ee5\u786e\u4fdd\u6211\u4eec\u5728\u8df3\u8fc7\u8fbe\u897f\u7cfb\u7edf\u7684\u89e3\u65f6\u603b\u662f\u81f3\u5c11\u89e3\u4e86\u4e24\u6b21\uff0c\u4ece\u800c\u5141\u8bb8\u6211\u4eec\u4ece <code>solve()</code> \u4e2d\u7684\u6700\u540e\u4e24\u6b21\u89e3\u4e2d\u63a8\u7b97\u51fa\u901f\u5ea6\u3002\n\n  template <int dim> \n  bool TwoPhaseFlowProblem< \n    dim>::determine_whether_to_solve_for_pressure_and_velocity() const \n  { \n    if (timestep_number <= 2) \n      return true; \n\n    const QGauss<dim>  quadrature_formula(saturation_degree + 2); \n    const unsigned int n_q_points = quadrature_formula.size(); \n\n    FEValues<dim> fe_values(saturation_fe, \n                            quadrature_formula, \n                            update_values | update_quadrature_points); \n\n    std::vector<double> old_saturation_after_solving_pressure(n_q_points); \n    std::vector<double> present_saturation(n_q_points); \n\n    std::vector<Tensor<2, dim>> k_inverse_values(n_q_points); \n\n    double max_global_aop_indicator = 0.0; \n\n    for (const auto &cell : saturation_dof_handler.active_cell_iterators()) \n      { \n        double max_local_mobility_reciprocal_difference = 0.0; \n        double max_local_permeability_inverse_l1_norm   = 0.0; \n\n        fe_values.reinit(cell); \n        fe_values.get_function_values( \n          saturation_matching_last_computed_darcy_solution, \n          old_saturation_after_solving_pressure); \n        fe_values.get_function_values(saturation_solution, present_saturation); \n\n        k_inverse.value_list(fe_values.get_quadrature_points(), \n                             k_inverse_values); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            const double mobility_reciprocal_difference = std::fabs( \n              mobility_inverse(present_saturation[q], viscosity) - \n              mobility_inverse(old_saturation_after_solving_pressure[q], \n                               viscosity)); \n\n            max_local_mobility_reciprocal_difference = \n              std::max(max_local_mobility_reciprocal_difference, \n                       mobility_reciprocal_difference); \n\n            max_local_permeability_inverse_l1_norm = \n              std::max(max_local_permeability_inverse_l1_norm, \n                       l1_norm(k_inverse_values[q])); \n          } \n\n        max_global_aop_indicator = \n          std::max(max_global_aop_indicator, \n                   (max_local_mobility_reciprocal_difference * \n                    max_local_permeability_inverse_l1_norm)); \n      } \n\n    return (max_global_aop_indicator > AOS_threshold); \n  } \n\n//  @sect4{TwoPhaseFlowProblem<dim>::project_back_saturation}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u53ea\u662f\u786e\u4fdd\u9971\u548c\u5ea6\u503c\u59cb\u7ec8\u4fdd\u6301\u5728  $[0,1]$  \u7684\u7269\u7406\u5408\u7406\u8303\u56f4\u5185\u3002\u867d\u7136\u8fde\u7eed\u65b9\u7a0b\u4fdd\u8bc1\u4e86\u8fd9\u4e00\u70b9\uff0c\u4f46\u79bb\u6563\u65b9\u7a0b\u5e76\u6ca1\u6709\u3002\u7136\u800c\uff0c\u5982\u679c\u6211\u4eec\u5141\u8bb8\u79bb\u6563\u89e3\u9003\u8131\u8fd9\u4e2a\u8303\u56f4\uff0c\u6211\u4eec\u5c31\u4f1a\u9047\u5230\u9ebb\u70e6\uff0c\u56e0\u4e3a\u50cf $F(S)$ \u548c $F'(S)$ \u8fd9\u6837\u7684\u9879\u4f1a\u4ea7\u751f\u4e0d\u5408\u7406\u7684\u7ed3\u679c\uff08\u4f8b\u5982 $F'(S)<0$ \u4e3a $S<0$ \uff0c\u8fd9\u5c06\u610f\u5473\u7740\u6da6\u6e7f\u6db2\u76f8\u7684\u6d41\u52a8\u65b9\u5411\u4e3a<i>against</i>\u7684\u6563\u6d41\u4f53\u901f\u5ea6\uff09\uff09\u3002\u56e0\u6b64\uff0c\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7ed3\u675f\u65f6\uff0c\u6211\u4eec\u53ea\u9700\u5c06\u9971\u548c\u573a\u6295\u5c04\u56de\u7269\u7406\u4e0a\u5408\u7406\u7684\u533a\u57df\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::project_back_saturation() \n  { \n    for (unsigned int i = 0; i < saturation_solution.size(); ++i) \n      if (saturation_solution(i) < 0.2) \n        saturation_solution(i) = 0.2; \n      else if (saturation_solution(i) > 1) \n        saturation_solution(i) = 1; \n  } \n\n//  @sect4{TwoPhaseFlowProblem<dim>::get_max_u_F_prime}  \n\n// \u53e6\u4e00\u4e2a\u6bd4\u8f83\u7b80\u5355\u7684\u8f85\u52a9\u51fd\u6570\u3002\u8ba1\u7b97\u603b\u901f\u5ea6\u4e58\u4ee5\u5206\u6570\u6d41\u51fd\u6570\u7684\u5bfc\u6570\u7684\u6700\u5927\u503c\uff0c\u5373\u8ba1\u7b97  $\\|\\mathbf{u} F'(S)\\|_{L_\\infty(\\Omega)}$  \u3002\u8fd9\u4e2a\u9879\u65e2\u7528\u4e8e\u65f6\u95f4\u6b65\u957f\u7684\u8ba1\u7b97\uff0c\u4e5f\u7528\u4e8e\u4eba\u5de5\u9ecf\u5ea6\u4e2d\u71b5\u7559\u9879\u7684\u6b63\u5e38\u5316\u3002\n\n  template <int dim> \n  double TwoPhaseFlowProblem<dim>::get_max_u_F_prime() const \n  { \n    const QGauss<dim>  quadrature_formula(darcy_degree + 2); \n    const unsigned int n_q_points = quadrature_formula.size(); \n\n    FEValues<dim> darcy_fe_values(darcy_fe, quadrature_formula, update_values); \n    FEValues<dim> saturation_fe_values(saturation_fe, \n                                       quadrature_formula, \n                                       update_values); \n\n    std::vector<Vector<double>> darcy_solution_values(n_q_points, \n                                                      Vector<double>(dim + 1)); \n    std::vector<double>         saturation_values(n_q_points); \n\n    double max_velocity_times_dF_dS = 0; \n\n    auto       cell            = darcy_dof_handler.begin_active(); \n    const auto endc            = darcy_dof_handler.end(); \n    auto       saturation_cell = saturation_dof_handler.begin_active(); \n    for (; cell != endc; ++cell, ++saturation_cell) \n      { \n        darcy_fe_values.reinit(cell); \n        saturation_fe_values.reinit(saturation_cell); \n\n        darcy_fe_values.get_function_values(darcy_solution, \n                                            darcy_solution_values); \n        saturation_fe_values.get_function_values(old_saturation_solution, \n                                                 saturation_values); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            Tensor<1, dim> velocity; \n            for (unsigned int i = 0; i < dim; ++i) \n              velocity[i] = darcy_solution_values[q](i); \n\n            const double dF_dS = \n              fractional_flow_derivative(saturation_values[q], viscosity); \n\n            max_velocity_times_dF_dS = \n              std::max(max_velocity_times_dF_dS, velocity.norm() * dF_dS); \n          } \n      } \n\n    return max_velocity_times_dF_dS; \n  } \n// @sect4{TwoPhaseFlowProblem<dim>::get_extrapolated_saturation_range}  \n\n// \u4e3a\u4e86\u8ba1\u7b97\u7a33\u5b9a\u5316\u9879\uff0c\u6211\u4eec\u9700\u8981\u77e5\u9053\u9971\u548c\u53d8\u91cf\u7684\u8303\u56f4\u3002\u4e0e step-31 \u4e0d\u540c\uff0c\u8fd9\u4e2a\u8303\u56f4\u5f88\u5bb9\u6613\u88ab\u533a\u95f4 $[0,1]$ \u6240\u7ea6\u675f\uff0c\u4f46\u662f\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u5728\u6b63\u4ea4\u70b9\u7684\u96c6\u5408\u4e0a\u5faa\u73af\uff0c\u770b\u770b\u90a3\u91cc\u7684\u503c\u662f\u591a\u5c11\uff0c\u4ece\u800c\u505a\u5f97\u66f4\u597d\u3002\u5982\u679c\u53ef\u4ee5\u7684\u8bdd\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5982\u679c\u5468\u56f4\u81f3\u5c11\u6709\u4e24\u4e2a\u65f6\u95f4\u6b65\u957f\uff0c\u6211\u4eec\u751a\u81f3\u53ef\u4ee5\u628a\u8fd9\u4e9b\u503c\u63a8\u7b97\u5230\u4e0b\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u3002\n\n// \u548c\u4ee5\u524d\u4e00\u6837\uff0c\u8fd9\u4e2a\u51fd\u6570\u662f\u5728\u5bf9  step-31  \u8fdb\u884c\u6700\u5c0f\u4fee\u6539\u540e\u53d6\u7684\u3002\n\n  template <int dim> \n  std::pair<double, double> \n  TwoPhaseFlowProblem<dim>::get_extrapolated_saturation_range() const \n  { \n    const QGauss<dim>  quadrature_formula(saturation_degree + 2); \n    const unsigned int n_q_points = quadrature_formula.size(); \n\n    FEValues<dim> fe_values(saturation_fe, quadrature_formula, update_values); \n    std::vector<double> old_saturation_values(n_q_points); \n    std::vector<double> old_old_saturation_values(n_q_points); \n\n    if (timestep_number != 0) \n      { \n        double min_saturation = std::numeric_limits<double>::max(), \n               max_saturation = -std::numeric_limits<double>::max(); \n\n        for (const auto &cell : saturation_dof_handler.active_cell_iterators()) \n          { \n            fe_values.reinit(cell); \n            fe_values.get_function_values(old_saturation_solution, \n                                          old_saturation_values); \n            fe_values.get_function_values(old_old_saturation_solution, \n                                          old_old_saturation_values); \n\n            for (unsigned int q = 0; q < n_q_points; ++q) \n              { \n                const double saturation = \n                  (1. + time_step / old_time_step) * old_saturation_values[q] - \n                  time_step / old_time_step * old_old_saturation_values[q]; \n\n                min_saturation = std::min(min_saturation, saturation); \n                max_saturation = std::max(max_saturation, saturation); \n              } \n          } \n\n        return std::make_pair(min_saturation, max_saturation); \n      } \n    else \n      { \n        double min_saturation = std::numeric_limits<double>::max(), \n               max_saturation = -std::numeric_limits<double>::max(); \n\n        for (const auto &cell : saturation_dof_handler.active_cell_iterators()) \n          { \n            fe_values.reinit(cell); \n            fe_values.get_function_values(old_saturation_solution, \n                                          old_saturation_values); \n\n            for (unsigned int q = 0; q < n_q_points; ++q) \n              { \n                const double saturation = old_saturation_values[q]; \n\n                min_saturation = std::min(min_saturation, saturation); \n                max_saturation = std::max(max_saturation, saturation); \n              } \n          } \n\n        return std::make_pair(min_saturation, max_saturation); \n      } \n  } \n\n//  @sect4{TwoPhaseFlowProblem<dim>::compute_viscosity}  \n\n// \u6700\u540e\u4e00\u4e2a\u5de5\u5177\u51fd\u6570\u662f\u7528\u6765\u8ba1\u7b97\u7ed9\u5b9a\u5355\u5143\u4e0a\u7684\u4eba\u5de5\u7c98\u5ea6\u7684\u3002\u5982\u679c\u4f60\u9762\u524d\u6709\u5b83\u7684\u516c\u5f0f\uff0c\u8fd9\u5e76\u4e0d\u7279\u522b\u590d\u6742\uff0c\u770b\u4e00\u4e0b  step-31  \u4e2d\u7684\u5b9e\u73b0\u3002\u4e0e\u90a3\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u7684\u4e3b\u8981\u533a\u522b\u662f\uff0c\u8fd9\u91cc\u7684\u901f\u5ea6\u4e0d\u662f\u7b80\u5355\u7684 $\\mathbf u$ \uff0c\u800c\u662f $\\mathbf u F'(S)$ \uff0c\u4e00\u4e9b\u516c\u5f0f\u9700\u8981\u505a\u76f8\u5e94\u7684\u8c03\u6574\u3002\n\n  template <int dim> \n  double TwoPhaseFlowProblem<dim>::compute_viscosity( \n    const std::vector<double> &        old_saturation, \n    const std::vector<double> &        old_old_saturation, \n    const std::vector<Tensor<1, dim>> &old_saturation_grads, \n    const std::vector<Tensor<1, dim>> &old_old_saturation_grads, \n    const std::vector<Vector<double>> &present_darcy_values, \n    const double                       global_max_u_F_prime, \n    const double                       global_S_variation, \n    const double                       cell_diameter) const \n  { \n    const double beta  = .4 * dim; \n    const double alpha = 1; \n\n    if (global_max_u_F_prime == 0) \n      return 5e-3 * cell_diameter; \n\n    const unsigned int n_q_points = old_saturation.size(); \n\n    double max_residual             = 0; \n    double max_velocity_times_dF_dS = 0; \n\n    const bool use_dF_dS = true; \n\n    for (unsigned int q = 0; q < n_q_points; ++q) \n      { \n        Tensor<1, dim> u; \n        for (unsigned int d = 0; d < dim; ++d) \n          u[d] = present_darcy_values[q](d); \n\n        const double dS_dt = porosity * \n                             (old_saturation[q] - old_old_saturation[q]) / \n                             old_time_step; \n\n        const double dF_dS = fractional_flow_derivative( \n          (old_saturation[q] + old_old_saturation[q]) / 2.0, viscosity); \n\n        const double u_grad_S = \n          u * dF_dS * (old_saturation_grads[q] + old_old_saturation_grads[q]) / \n          2.0; \n\n        const double residual = \n          std::abs((dS_dt + u_grad_S) * \n                   std::pow((old_saturation[q] + old_old_saturation[q]) / 2, \n                            alpha - 1.)); \n\n        max_residual = std::max(residual, max_residual); \n        max_velocity_times_dF_dS = \n          std::max(std::sqrt(u * u) * (use_dF_dS ? std::max(dF_dS, 1.) : 1), \n                   max_velocity_times_dF_dS); \n      } \n\n    const double c_R            = 1.0; \n    const double global_scaling = c_R * porosity * \n                                  (global_max_u_F_prime)*global_S_variation / \n                                  std::pow(global_Omega_diameter, alpha - 2.); \n\n    return (beta * \n            (max_velocity_times_dF_dS)*std::min(cell_diameter, \n                                                std::pow(cell_diameter, alpha) * \n                                                  max_residual / \n                                                  global_scaling)); \n  } \n// @sect3{TwoPhaseFlowProblem<dim>::run}  \n\n// \u9664\u4e86 <code>solve()</code> \u4e4b\u5916\uff0c\u8fd9\u4e2a\u51fd\u6570\u662f\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u8981\u529f\u80fd\uff0c\u56e0\u4e3a\u5b83\u63a7\u5236\u4e86\u8fed\u4ee3\u7684\u65f6\u95f4\uff0c\u4ee5\u53ca\u4f55\u65f6\u5c06\u89e3\u51b3\u65b9\u6848\u5199\u5165\u8f93\u51fa\u6587\u4ef6\uff0c\u4f55\u65f6\u8fdb\u884c\u7f51\u683c\u7ec6\u5316\u3002\n\n// \u9664\u4e86\u542f\u52a8\u4ee3\u7801\u901a\u8fc7 <code>goto start_time_iteration</code> \u6807\u7b7e\u5faa\u73af\u56de\u5230\u51fd\u6570\u7684\u5f00\u5934\u5916\uff0c\u4e00\u5207\u90fd\u5e94\u8be5\u662f\u76f8\u5bf9\u7b80\u5355\u7684\u3002\u65e0\u8bba\u5982\u4f55\uff0c\u5b83\u6a21\u4eff\u4e86  step-31  \u4e2d\u7684\u76f8\u5e94\u51fd\u6570\u3002\n\n  template <int dim> \n  void TwoPhaseFlowProblem<dim>::run() \n  { \n    const unsigned int initial_refinement     = (dim == 2 ? 5 : 2); \n    const unsigned int n_pre_refinement_steps = (dim == 2 ? 3 : 2); \n\n    GridGenerator::hyper_cube(triangulation, 0, 1); \n    triangulation.refine_global(initial_refinement); \n    global_Omega_diameter = GridTools::diameter(triangulation); \n\n    setup_dofs(); \n\n    unsigned int pre_refinement_step = 0; \n\n  start_time_iteration: \n\n    VectorTools::project(saturation_dof_handler, \n                         saturation_constraints, \n                         QGauss<dim>(saturation_degree + 2), \n                         SaturationInitialValues<dim>(), \n                         old_saturation_solution); \n\n    time_step = old_time_step = 0; \n    current_macro_time_step = old_macro_time_step = 0; \n\n    time = 0; \n\n    do \n      { \n        std::cout << \"Timestep \" << timestep_number << \":  t=\" << time \n                  << \", dt=\" << time_step << std::endl; \n\n        solve(); \n\n        std::cout << std::endl; \n\n        if (timestep_number % 200 == 0) \n          output_results(); \n\n        if (timestep_number % 25 == 0) \n          refine_mesh(initial_refinement, \n                      initial_refinement + n_pre_refinement_steps); \n\n        if ((timestep_number == 0) && \n            (pre_refinement_step < n_pre_refinement_steps)) \n          { \n            ++pre_refinement_step; \n            goto start_time_iteration; \n          } \n\n        time += time_step; \n        ++timestep_number; \n\n        old_old_saturation_solution = old_saturation_solution; \n        old_saturation_solution     = saturation_solution; \n      } \n    while (time <= end_time); \n  } \n} // namespace Step43 \n\n//  @sect3{The <code>main()</code> function}  \n\n// \u4e3b\u51fd\u6570\u770b\u8d77\u6765\u4e0e\u6240\u6709\u5176\u4ed6\u7a0b\u5e8f\u51e0\u4e4e\u4e00\u6837\u3002\u5bf9\u4e8e\u4f7f\u7528Trilinos\u7684\u7a0b\u5e8f\u6765\u8bf4\uff0c\u9700\u8981\u521d\u59cb\u5316MPI\u5b50\u7cfb\u7edf--\u5373\u4f7f\u662f\u90a3\u4e9b\u5b9e\u9645\u4e0a\u6ca1\u6709\u5e76\u884c\u8fd0\u884c\u7684\u7a0b\u5e8f--\u5728  step-31  \u4e2d\u6709\u89e3\u91ca\u3002\n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      using namespace dealii; \n      using namespace Step43; \n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization( \n        argc, argv, numbers::invalid_unsigned_int); \n\n// \u8fd9\u4e2a\u7a0b\u5e8f\u53ea\u80fd\u5728\u4e32\u884c\u4e2d\u8fd0\u884c\u3002\u5426\u5219\uff0c\u5c06\u629b\u51fa\u4e00\u4e2a\u5f02\u5e38\u3002\n\n      AssertThrow(Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD) == 1, \n                  ExcMessage( \n                    \"This program can only be run in serial, use ./step-43\")); \n\n      TwoPhaseFlowProblem<2> two_phase_flow_problem(1); \n      two_phase_flow_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\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\n\n", "meta": {"hexsha": "beb497a7c257ea18bc540c0da85dad745a5660e8", "size": 75016, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-43/step-43.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-43/step-43.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-43/step-43.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.0098803952, "max_line_length": 337, "alphanum_fraction": 0.623040418, "num_tokens": 22762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5395952266759321}}
{"text": "// Copyright (C) 2018-2020 Chris Richardson (chris@bpi.cam.ac.uk)\n// SPDX-License-Identifier:    MIT\n\n#include <Eigen/Dense>\n#include <chrono>\n#include <iostream>\n#include <memory>\n#include <mpi.h>\n\n#include <spmv/spmv.h>\n\nvoid cg_main(int argc, char** argv)\n{\n  // Turn off profiling\n  MPI_Pcontrol(0);\n\n  int mpi_rank;\n  MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);\n  int mpi_size;\n  MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);\n\n  // Set CUDA device for this process\n  MPI_Comm local_comm;\n  MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_SHARED, mpi_rank,\n                      MPI_INFO_NULL, &local_comm);\n  int local_rank = -1;\n  MPI_Comm_rank(local_comm, &local_rank);\n  MPI_Comm_free(&local_comm);\n  int num_devices = 0;\n  cudaGetDeviceCount(&num_devices);\n  cudaSetDevice(local_rank % num_devices);\n\n  // Keep list of timings\n  std::map<std::string, std::chrono::duration<double>> timings;\n\n  auto timer_start = std::chrono::system_clock::now();\n\n  std::string argv1, argv2;\n  if (argc == 3) {\n    argv1 = argv[1];\n    argv2 = argv[2];\n  } else {\n    throw std::runtime_error(\"Use: ./cg_demo <matrix_file> <vector_file>\");\n  }\n\n  // Read matrix\n  bool symmetric = false;\n  spmv::CommunicationModel cm = spmv::CommunicationModel::p2p_blocking;\n  auto A = spmv::read_petsc_binary_matrix(MPI_COMM_WORLD, argv1, symmetric, cm);\n\n  // Read vector\n  auto b = spmv::read_petsc_binary_vector(MPI_COMM_WORLD, argv2);\n\n  // Get local and global sizes\n  std::shared_ptr<const spmv::L2GMap> l2g = A.col_map();\n  std::int64_t N = l2g->global_size();\n\n  if (mpi_rank == 0)\n    std::cout << \"Global vec size = \" << N << \"\\n\";\n\n  auto timer_end = std::chrono::system_clock::now();\n  timings[\"0.ReadPetsc\"] += (timer_end - timer_start);\n\n  int max_its = 100;\n  double rtol = 1e-10;\n\n  // Turn on profiling for solver only\n  MPI_Pcontrol(1);\n  timer_start = std::chrono::system_clock::now();\n  auto [x_dev, num_its] = spmv::cg(MPI_COMM_WORLD, A, b.data(), max_its, rtol);\n  timer_end = std::chrono::system_clock::now();\n  timings[\"1.Solve\"] += (timer_end - timer_start);\n  MPI_Pcontrol(0);\n\n  // Test result on host\n  int N_padded = l2g->local_size() + l2g->num_ghosts();\n  double* x_host = new double[N_padded]();\n  cudaMemcpy(x_host, x_dev, N_padded * sizeof(double), cudaMemcpyDeviceToHost);\n  l2g->update(x_host);\n  Eigen::Map<Eigen::VectorXd> x(x_host, N_padded);\n  Eigen::VectorXd r = A.mult(x) - b;\n  double rnorm = r.squaredNorm();\n  double rnorm_sum;\n  MPI_Allreduce(&rnorm, &rnorm_sum, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n\n  // Get norm of solution vector\n  double xnorm = x.head(l2g->local_size()).squaredNorm();\n  double xnorm_sum;\n  MPI_Allreduce(&xnorm, &xnorm_sum, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n\n  if (mpi_rank == 0) {\n    std::cout << \"r.norm = \" << std::sqrt(rnorm_sum) << \"\\n\";\n    std::cout << \"x.norm = \" << std::sqrt(xnorm_sum) << \" in \" << num_its\n              << \" iterations\\n\";\n    std::cout << \"\\nTimings (\" << mpi_size\n              << \")\\n----------------------------\\n\";\n  }\n\n  std::chrono::duration<double> total_time\n      = std::chrono::duration<double>::zero();\n  for (auto q : timings)\n    total_time += q.second;\n  timings[\"Total\"] = total_time;\n\n  for (auto q : timings) {\n    double q_local = q.second.count(), q_max, q_min;\n    MPI_Reduce(&q_local, &q_max, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);\n    MPI_Reduce(&q_local, &q_min, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD);\n\n    if (mpi_rank == 0) {\n      std::string pad(16 - q.first.size(), ' ');\n      std::cout << \"[\" << q.first << \"]\" << pad << q_min << '\\t' << q_max\n                << \"\\n\";\n    }\n  }\n\n  if (mpi_rank == 0)\n    std::cout << \"----------------------------\\n\";\n\n  // Cleanup\n  free(x_host);\n  cudaFree(x_dev);\n}\n//-----------------------------------------------------------------------------\nint main(int argc, char** argv)\n{\n  MPI_Init(&argc, &argv);\n\n  cg_main(argc, argv);\n\n  MPI_Finalize();\n  return 0;\n}\n", "meta": {"hexsha": "0412eb28342c71e6ae9eb958ad6e9584fc9be269", "size": 3926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/cg_cuda.cpp", "max_stars_repo_name": "Excalibur-SLE/spmv", "max_stars_repo_head_hexsha": "7bd7aa05c5c7018c807160e1d1d70b11a8143eca", "max_stars_repo_licenses": ["MIT"], "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/cg_cuda.cpp", "max_issues_repo_name": "Excalibur-SLE/spmv", "max_issues_repo_head_hexsha": "7bd7aa05c5c7018c807160e1d1d70b11a8143eca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-04T15:55:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-04T15:56:02.000Z", "max_forks_repo_path": "demos/cg_cuda.cpp", "max_forks_repo_name": "Excalibur-SLE/spmv", "max_forks_repo_head_hexsha": "7bd7aa05c5c7018c807160e1d1d70b11a8143eca", "max_forks_repo_licenses": ["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.2985074627, "max_line_length": 80, "alphanum_fraction": 0.6230259806, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5395952215713397}}
{"text": "#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 <boost/pending/disjoint_sets.hpp>\n#include <vector>\n#include <tuple>\n#include <algorithm>\n#include <iostream>\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>               Delaunay;\ntypedef std::pair<K::Point_2,int>                           IPoint;\n\nusing namespace std;\n\nstruct Edge {\n  int u, v;\n  long distance;\n  \n  bool operator<(const Edge& other) const {\n    return distance < other.distance;\n  }\n};\n\n// For a given component described by the boneDistances, compute the a value\nint getA(vector<long> boneDistances, long s) {\n  auto it = upper_bound(boneDistances.begin(), boneDistances.end(), s);\n  return distance(boneDistances.begin(), it);\n}\n\n// For a given component described by the boneDistances and the longest edge, compute the q value\nlong getQ(vector<long> boneDistances, long longestEdge, int k) {\n   if (boneDistances.size() >= k) {\n    return max(boneDistances[k - 1], longestEdge);\n  }\n  return numeric_limits<long>::max();\n}\n\n// Strategy:\n// - Get graph with Delaunay\n// - Use Union-Find to construct connected componets\n// - At each merge step compute a and q values\nvoid solve() {\n  int n, m, k;\n  long s; // == 4r^2\n  \n  cin >> n >> m >> s >> k;\n\n  // Constructe Delaunay triangulation of trees\n  vector<IPoint> points;\n  points.reserve(n);\n  int x, y;\n  for (int i = 0; i < n; ++i) {\n    cin >> x >> y;\n    points.emplace_back(K::Point_2(x, y), i);\n  }\n  Delaunay t;\n  t.insert(points.begin(), points.end());\n  \n  // For each bone: find closest tree\n  // Keep list for every tree t which contains the distances for all bones that have t as closest tree\n  vector<vector<long>> bones(n);\n  for (int i = 0; i < m; ++i) {\n    cin >> x >> y;\n    K::Point_2 p(x, y);\n    auto vertex = t.nearest_vertex(p);\n    int v = vertex->info();\n    auto d = 4 * long(CGAL::squared_distance(p, vertex->point()));\n    bones[v].push_back(d);\n  }\n  // Sort the bone lists\n  for (int i = 0; i < n; ++i) {\n    sort(bones[i].begin(), bones[i].end());\n  }\n\n  // Extract edges for union find\n  vector<Edge> edges;\n  edges.reserve(3*n);\n  for (auto e = t.finite_edges_begin(); e != t.finite_edges_end(); ++e) {\n    int u = e->first->vertex((e->second+1)%3)->info();\n    int v = e->first->vertex((e->second+2)%3)->info();\n    edges.push_back({u, v, long(t.segment(e).squared_length())});\n  }\n  std::sort(edges.begin(), edges.end());\n\n\n  // Compute solution for before connecting\n  int a = -1;\n  long q = numeric_limits<long>::max();\n  for (auto bonesOfTree : bones) {\n    q = min(q, getQ(bonesOfTree, -1, k));\n    a = max(a, getA(bonesOfTree, s));\n  }\n  \n\n  // Connect components\n  boost::disjoint_sets_with_storage<> uf(n);\n  int n_components = n;\n  for (auto e : edges) {\n    int u = e.u;\n    int v = e.v;\n    int c1 = uf.find_set(u);\n    int c2 = uf.find_set(v);\n    if (c1 != c2) {\n      \n      // Link components & merge distances\n      uf.link(c1, c2);\n      int c = uf.find_set(c1);\n      vector<long> dst;\n      merge(bones[c1].begin(), bones[c1].end(), bones[c2].begin(), bones[c2].end(), back_inserter(dst));\n      bones[c] = dst;\n      \n\n      // Update a & q\n      q = min(q, getQ(bones[c], e.distance, k));      \n      if (e.distance <= s) {\n        a = max(a, getA(bones[c], s));\n      }\n      \n      if (--n_components == 1) break;\n    }\n  }\n  \n  cout << a << \" \" << q << endl; \n}\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}\n", "meta": {"hexsha": "3360ae4918492f1d07bfafa4ebf8b8a9b3bf24a4", "size": 3885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/idefix.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/idefix.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/idefix.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": 27.5531914894, "max_line_length": 104, "alphanum_fraction": 0.6203346203, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5395635710531728}}
{"text": "#include <cstdio>\n#include <sr_grasp_msgs/KCL_ContactStateStamped.h>\n#include <geometry_msgs/WrenchStamped.h>\n#include <ros/ros.h>\n#include <Eigen/Core>\n\n#define MAX 1000\n#define pi 3.14159265\n\nusing namespace Eigen;\n\nclass ContactFO{\n\npublic:\n    ContactFO();\n    ros::NodeHandle n;\n    ros::Subscriber sub;\n    ros::Publisher KCL_ContactState_pub;\n\n    void sensorCallback(const geometry_msgs::WrenchStamped&);\n    int setFinger(char* arg);\n\nprotected:\n    int finger;\n    std::string frame_id_;\n    double a,b,c,y00,z0,frot,sfrot,cfrot;\n\n\n    geometry_msgs::Point changeFrame(geometry_msgs::Point in_pt);\n    geometry_msgs::Vector3 changeFrame(geometry_msgs::Vector3 in_v);\n    geometry_msgs::Vector3 normalise_vec(geometry_msgs::Vector3 in_v);\n    geometry_msgs::Point contact_location(geometry_msgs::Vector3 normal);\n    Vector4d func(Vector4d x, geometry_msgs::Vector3 normal);\n\n};\n\n\nContactFO::ContactFO(){\n    sub=n.subscribe(\"nano17ft\", 100, &ContactFO::sensorCallback,this);\n    KCL_ContactState_pub=n.advertise<sr_grasp_msgs::KCL_ContactStateStamped>(\"ContactState\",10);\n    n.getParam(\"frame\", frame_id_);\n\n\n    n.getParam(\"contact/a\", a);\n    n.getParam(\"contact/b\", b);\n    n.getParam(\"contact/c\", c);\n    n.getParam(\"contact/y00\", y00);\n    n.getParam(\"contact/z0\", z0);\n    n.getParam(\"contact/frot\", frot);\n    sfrot=sin(frot);\n    cfrot=cos(frot);\n\n\n}\n\ngeometry_msgs::Vector3 ContactFO::normalise_vec(geometry_msgs::Vector3 in_v){\n    geometry_msgs::Vector3 out;\n    double norm;\n\n    norm=sqrt(in_v.x*in_v.x+in_v.y*in_v.y+in_v.z*in_v.z);\n    out.x=in_v.x/norm;\n    out.y=in_v.y/norm;\n    out.z=in_v.z/norm;\n\n    return out;\n}\n\ngeometry_msgs::Point ContactFO::changeFrame(geometry_msgs::Point in_pt)\n{\n    geometry_msgs::Point new_pt;\n    new_pt.x= (in_pt.x)/1000.0;\n    new_pt.y= -in_pt.z/1000.0;\n    new_pt.z= (in_pt.y+b)/1000.0;\n    return new_pt;\n}\n\n//! changes frame from ellipsoid center to finger distal frame (used for shadow type finger)\ngeometry_msgs::Vector3 ContactFO::changeFrame(geometry_msgs::Vector3 in_v)\n{\n    geometry_msgs::Vector3 new_v;\n    new_v.x= in_v.x;\n    new_v.y= -in_v.z;\n    new_v.z= in_v.y;\n    return new_v;\n}\n\n\nVector4d ContactFO::func(Vector4d x,geometry_msgs::Vector3 normal){\n    Vector4d g;\n\n    g[0]=(x[0]/a)*(x[0]/a) + ((x[1]-y00)/b)*((x[1]-y00)/b) + ((x[2]-z0)/c)*((x[2]-z0)/c) - 1;\n    g[1]=normal.x+2/(a*a)*x[0];\n    g[2]=normal.y+2/(b*b)*(x[1]-y00);\n    g[3]=normal.z+2/(c*c)*(x[2]-z0);\n    return g;\n}\n\n\ngeometry_msgs::Point ContactFO::contact_location(geometry_msgs::Vector3 normal){\n\n    geometry_msgs::Point cl;\n    Vector4d g,jh,JtG,x,xh;\n    Matrix4d J;\n\n    g << 1,1,1,1;\n    J.setZero(4,4);\n\n    double h=0.02;\n    double eps=2;\n    int j=0;\n    int i=0;\n\n    x << 0,0,c+z0,0;\n\n\n    int iter=0;\n\n    while(fabs(g[0])>=0.01 || fabs(g[1])>=0.01 || fabs(g[2])>=0.01 || fabs(g[3])>=0.01)\t{\n        iter++;\n        if(iter>MAX) break;\n\n        g=func(x,normal);\n\n        for(i=0;i<4;i++){\n            xh=x;\n            xh[i]+=h;\n            jh=(func(xh,normal)-g)/h;\n            for(j=0;j<4;j++) J(j,i)=jh(j);\n        }\n        JtG=J.transpose()*g;\n        x=x-eps*JtG;\n    //   std::cout << iter << \":\\t\" << x[0] << \" \"<< x[1] << \" \"<< x[2] << std::endl;\n\n    }\n\n    cl.x= x[0];\n    cl.y= x[1];\n    cl.z= x[2];\n\n\n    //    cl.x= (a*a)/2 * normal.x;\n    //    cl.y= (b*b)/2 * normal.y +y00;\n    //    cl.z= (c*c)/2 * normal.z + z0;\n\n  //  ROS_INFO(\"%f %f %f \\t %f %f %f\",normal.x,normal.y,normal.z,cl.x,cl.y,cl.z);\n\n\n    return cl;\n\n}\n\nvoid ContactFO::sensorCallback(const geometry_msgs::WrenchStamped &msg){\n\n    sr_grasp_msgs::KCL_ContactStateStamped contact;\n    geometry_msgs::Vector3 in_v;\n\n    in_v.x=cfrot*msg.wrench.force.x+sfrot*msg.wrench.force.y;\n    in_v.y=-sfrot*msg.wrench.force.x+cfrot*msg.wrench.force.y;\n    in_v.z=msg.wrench.force.z;\n\n\n\n    contact.Fnormal=-sqrt(in_v.x*in_v.x+in_v.y*in_v.y+in_v.z*in_v.z);\n    contact.contact_normal=changeFrame(normalise_vec(in_v));\n    contact.contact_normal.x=-contact.contact_normal.x;\n    contact.contact_normal.y=-contact.contact_normal.y;\n    contact.contact_normal.z=-contact.contact_normal.z;\n    contact.contact_position=changeFrame(contact_location(normalise_vec(in_v)));\n    contact.header.stamp=msg.header.stamp;\n    contact.header.frame_id=frame_id_;\n\n    KCL_ContactState_pub.publish(contact);\n\n}\n\nint main(int argc,char *argv[]) {\n\n    ros::init(argc, argv, \"contact_force_only\");\n    ContactFO cloc;\n    ros::NodeHandle n(\"~\");\n    cloc.n=n;\n\n\n    while(ros::ok()){\n        ros::spin();\n    }\n\n\n\n}\n", "meta": {"hexsha": "03913e1e86f675a89f59db5cec48d07857d29338", "size": 4531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kcl_grasp_tactile/src/force_only.cpp", "max_stars_repo_name": "Kevin315/Contact_location_estimation", "max_stars_repo_head_hexsha": "be5d3f02d1c856d68420f1bc5b38faac38fcee22", "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/kcl_grasp_tactile/src/force_only.cpp", "max_issues_repo_name": "Kevin315/Contact_location_estimation", "max_issues_repo_head_hexsha": "be5d3f02d1c856d68420f1bc5b38faac38fcee22", "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/kcl_grasp_tactile/src/force_only.cpp", "max_forks_repo_name": "Kevin315/Contact_location_estimation", "max_forks_repo_head_hexsha": "be5d3f02d1c856d68420f1bc5b38faac38fcee22", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-09T12:57:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T12:57:17.000Z", "avg_line_length": 23.722513089, "max_line_length": 96, "alphanum_fraction": 0.6307658354, "num_tokens": 1437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5395004865019584}}
{"text": "#include <iostream>\n#include <fstream>\n#include <Eigen/Eigen>\n#include \"BinIO.hpp\"\n\nusing Eigen::MatrixXd;\nusing Eigen::Matrix;\nusing ionizing::BinIO;\n\nint main(int argc, char* argv[]) {\n  // BinIO io(\"test.bin\");\n\n  MatrixXd matrix = MatrixXd::Random(4, 5);\n  long rows = matrix.rows(), cols = matrix.cols();\n  \n  std::cout << \"matrix = \\n\" << matrix << std::endl;\n\n  std::ofstream ofs(\"test.bin\", std::ios::binary | std::ios::out | std::ios::trunc);\n  ofs.write((char*) &rows, sizeof(rows));\n  ofs.write((char*) &cols, sizeof(cols));\n  ofs.write((char*) matrix.data(), rows*cols*sizeof(double));\n  ofs.close();\n\n  BinIO io2(\"test.bin\");\n  rows = io2.readElement<long>();\n  cols = io2.readElement<long>();\n  // MatrixXd matrix2 = io2.readMatrix<double> (rows, cols);\n  // std::cout << \"matrix2 = \\n\" << matrix2 << std::endl;\n  std::cout << \"matrix2 = \\n\" << std::endl;\n  // for (int i=0; i!=rows; ++i) {\n    // std::cout << io2.readVectorRow<double>(cols) << std::endl;\n  // }\n  \n  matrix = io2.readMatrix<double>(rows, cols);\n  std::cout << matrix << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "1f7b58b95ccee694651a15d2636d9df6b2625f2d", "size": 1079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BinIO/test.cpp", "max_stars_repo_name": "Ionizing/usefultools-for-vasp", "max_stars_repo_head_hexsha": "b13e821fb5f4024a45b3d16176033b9577e1cf31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-03-18T08:21:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T07:56:39.000Z", "max_issues_repo_path": "BinIO/test.cpp", "max_issues_repo_name": "Ionizing/usefultools-for-vasp", "max_issues_repo_head_hexsha": "b13e821fb5f4024a45b3d16176033b9577e1cf31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-01-22T16:30:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-08T13:16:45.000Z", "max_forks_repo_path": "BinIO/test.cpp", "max_forks_repo_name": "IonizingRadiation/usefultools-for-vasp", "max_forks_repo_head_hexsha": "b13e821fb5f4024a45b3d16176033b9577e1cf31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-03-06T03:29:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-14T04:24:03.000Z", "avg_line_length": 27.6666666667, "max_line_length": 84, "alphanum_fraction": 0.6107506951, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5394936527802708}}
{"text": "/* =========================================================================\r\n   Copyright (c) 2010-2012, Institute for Microelectronics,\r\n                            Institute for Analysis and Scientific Computing,\r\n                            TU Wien.\r\n   Portions of this software are copyright by UChicago Argonne, LLC.\r\n\r\n                            -----------------\r\n                  ViennaCL - The Vienna Computing Library\r\n                            -----------------\r\n\r\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\r\n               \r\n   (A list of authors and contributors can be found in the PDF manual)\r\n\r\n   License:         MIT (X11), see file LICENSE in the base directory\r\n============================================================================= */\r\n\r\n/*\r\n* \r\n*   Tutorial: BLAS level 3 functionality on sub-matrices (blas3range.cpp and blas3range.cu are identical, the latter being required for compilation using CUDA nvcc)\r\n*   \r\n*/\r\n\r\n//disable debug mechanisms to have a fair comparison with ublas:\r\n#ifndef NDEBUG\r\n #define NDEBUG\r\n#endif\r\n\r\n\r\n//\r\n// include necessary system headers\r\n//\r\n#include <iostream>\r\n\r\n//\r\n// ublas includes\r\n//\r\n#include <boost/numeric/ublas/io.hpp>\r\n#include <boost/numeric/ublas/triangular.hpp>\r\n#include <boost/numeric/ublas/matrix_sparse.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/matrix_proxy.hpp>\r\n#include <boost/numeric/ublas/lu.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n\r\n\r\n// Must be set if you want to use ViennaCL algorithms on ublas objects\r\n#define VIENNACL_WITH_UBLAS 1\r\n\r\n//\r\n// ViennaCL includes\r\n//\r\n#include \"viennacl/scalar.hpp\"\r\n#include \"viennacl/vector.hpp\"\r\n#include \"viennacl/matrix.hpp\"\r\n#include \"viennacl/linalg/prod.hpp\"\r\n#include \"viennacl/matrix_proxy.hpp\"\r\n\r\n// Some helper functions for this tutorial:\r\n#include \"Random.hpp\"\r\n#include \"vector-io.hpp\"\r\n\r\n#include \"../benchmarks/benchmark-utils.hpp\"\r\n\r\n#define BLAS3_MATRIX_SIZE   1500\r\n\r\nusing namespace boost::numeric;\r\n\r\nint main()\r\n{\r\n  typedef float     ScalarType;\r\n\r\n  Timer timer;\r\n  double exec_time;\r\n\r\n  //\r\n  // Set up some ublas objects\r\n  //\r\n  ublas::matrix<ScalarType> ublas_A(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\r\n  ublas::matrix<ScalarType, ublas::column_major> ublas_B(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\r\n  ublas::matrix<ScalarType> ublas_C(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\r\n  ublas::matrix<ScalarType> ublas_C1(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\r\n  ublas::matrix<ScalarType> ublas_C2(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\r\n\r\n  //\r\n  // One alternative: Put the matrices into a contiguous block of memory (allows to use viennacl::fast_copy(), avoiding temporary memory)\r\n  //\r\n  std::vector<ScalarType> stl_A(BLAS3_MATRIX_SIZE * BLAS3_MATRIX_SIZE);\r\n  std::vector<ScalarType> stl_B(BLAS3_MATRIX_SIZE * BLAS3_MATRIX_SIZE);\r\n  std::vector<ScalarType> stl_C(BLAS3_MATRIX_SIZE * BLAS3_MATRIX_SIZE);\r\n\r\n  //\r\n  // Fill the matrix\r\n  //\r\n  for (unsigned int i = 0; i < ublas_A.size1(); ++i)\r\n    for (unsigned int j = 0; j < ublas_A.size2(); ++j)\r\n    {\r\n      ublas_A(i,j) = random<ScalarType>();\r\n      stl_A[i*ublas_A.size2() + j] = ublas_A(i,j);\r\n    }\r\n\r\n  for (unsigned int i = 0; i < ublas_B.size1(); ++i)\r\n    for (unsigned int j = 0; j < ublas_B.size2(); ++j)\r\n    {\r\n      ublas_B(i,j) = random<ScalarType>();\r\n      stl_B[i + j*ublas_B.size1()] = ublas_B(i,j);\r\n    }\r\n    \r\n  ublas::range ublas_r1(1, BLAS3_MATRIX_SIZE-1);\r\n  ublas::range ublas_r2(2, BLAS3_MATRIX_SIZE-2);\r\n  ublas::matrix_range< ublas::matrix<ScalarType> >  ublas_A_sub(ublas_A, ublas_r1, ublas_r2);\r\n  ublas::matrix_range< ublas::matrix<ScalarType, ublas::column_major> >  ublas_B_sub(ublas_B, ublas_r2, ublas_r1);\r\n  ublas::matrix_range< ublas::matrix<ScalarType> >  ublas_C_sub(ublas_C, ublas_r1, ublas_r1);\r\n\r\n  //\r\n  // Set up some ViennaCL objects\r\n  //\r\n  //viennacl::ocl::set_context_device_type(0, viennacl::ocl::gpu_tag());  //uncomment this is you wish to use GPUs only\r\n  viennacl::matrix<ScalarType> vcl_A(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\r\n  viennacl::matrix<ScalarType, viennacl::column_major> vcl_B(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\r\n  viennacl::matrix<ScalarType> vcl_C(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\r\n\r\n  viennacl::range vcl_r1(1, BLAS3_MATRIX_SIZE-1);\r\n  viennacl::range vcl_r2(2, BLAS3_MATRIX_SIZE-2);\r\n  viennacl::matrix_range< viennacl::matrix<ScalarType> >  vcl_A_sub(vcl_A, vcl_r1, vcl_r2);\r\n  viennacl::matrix_range< viennacl::matrix<ScalarType, viennacl::column_major> >  vcl_B_sub(vcl_B, vcl_r2, vcl_r1);\r\n  viennacl::matrix_range< viennacl::matrix<ScalarType> >  vcl_C_sub(vcl_C, vcl_r1, vcl_r1);\r\n  \r\n  ublas_C.clear();\r\n  viennacl::copy(ublas_C, vcl_C);\r\n  \r\n  /////////////////////////////////////////////////\r\n  //////////// Matrix-matrix products /////////////\r\n  /////////////////////////////////////////////////\r\n  \r\n  //\r\n  // Compute reference product using ublas:\r\n  //\r\n  std::cout << \"--- Computing matrix-matrix product using ublas ---\" << std::endl;\r\n  timer.start();\r\n  ublas_C_sub = ublas::prod(ublas_A_sub, ublas_B_sub);\r\n  exec_time = timer.get();\r\n  std::cout << \" - Execution time: \" << exec_time << std::endl;\r\n  \r\n  //std::cout << ublas_C << std::endl;\r\n  \r\n  //\r\n  // Now iterate over all OpenCL devices in the context and compute the matrix-matrix product\r\n  //\r\n  std::cout << std::endl << \"--- Computing matrix-matrix product on each available compute device using ViennaCL ---\" << std::endl;\r\n  std::vector<viennacl::ocl::device> devices = viennacl::ocl::current_context().devices();\r\n  for (size_t i=0; i<devices.size(); ++i)\r\n  {\r\n    viennacl::ocl::current_context().switch_device(devices[i]);\r\n    std::cout << \" - Device Name: \" << viennacl::ocl::current_device().name() << std::endl;\r\n\r\n    //viennacl::copy(ublas_A, vcl_A);\r\n    //viennacl::copy(ublas_B, vcl_B);\r\n    viennacl::fast_copy(&(stl_A[0]),\r\n                        &(stl_A[0]) + stl_A.size(),\r\n                        vcl_A);\r\n    viennacl::fast_copy(&(stl_B[0]),\r\n                        &(stl_B[0]) + stl_B.size(),\r\n                        vcl_B);\r\n    vcl_C_sub = viennacl::linalg::prod(vcl_A_sub, vcl_B_sub);\r\n    viennacl::ocl::get_queue().finish();\r\n    timer.start();\r\n    vcl_C_sub = viennacl::linalg::prod(vcl_A_sub, vcl_B_sub);\r\n    viennacl::ocl::get_queue().finish();\r\n    exec_time = timer.get();\r\n    std::cout << \" - Execution time on device (no setup time included): \" << exec_time << std::endl;\r\n    std::cout << \" - GFLOPs: \" << (vcl_A.size1() / 1000.0) * (vcl_A.size2() / 1000.0) * (vcl_B.size2() / 1000.0) / exec_time << std::endl;\r\n\r\n    //std::cout << vcl_C << std::endl;\r\n    \r\n    //\r\n    // Verify the result\r\n    //\r\n    //viennacl::copy(vcl_C, ublas_C1);\r\n    viennacl::fast_copy(vcl_C, &(stl_C[0]));\r\n    for (unsigned int i = 0; i < ublas_C1.size1(); ++i)\r\n      for (unsigned int j = 0; j < ublas_C1.size2(); ++j)\r\n        ublas_C1(i,j) = stl_C[i * ublas_C1.size2() + j];\r\n\r\n    std::cout << \" - Checking result... \";\r\n    bool check_ok = true;\r\n    for (unsigned int i = 0; i < ublas_A.size1(); ++i)\r\n    {\r\n      for (unsigned int j = 0; j < ublas_A.size2(); ++j)\r\n      {\r\n        if ( fabs(ublas_C1(i,j) - ublas_C(i,j)) / ublas_C(i,j) > 1e-4 )\r\n        {\r\n          check_ok = false;\r\n          break;\r\n        }\r\n      }\r\n      if (!check_ok)\r\n        break;\r\n    }\r\n    if (check_ok)\r\n      std::cout << \"[OK]\" << std::endl << std::endl;\r\n    else\r\n      std::cout << \"[FAILED]\" << std::endl << std::endl;\r\n      \r\n  }\r\n\r\n  //\r\n  //  That's it. \r\n  //\r\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\r\n  return EXIT_SUCCESS;\r\n}\r\n\r\n", "meta": {"hexsha": "33a87d741d101aa7762e607f6f1872c17188573c", "size": 7643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/blas3range.cpp", "max_stars_repo_name": "bollig/viennacl", "max_stars_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T08:33:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T08:33:10.000Z", "max_issues_repo_path": "examples/tutorial/blas3range.cpp", "max_issues_repo_name": "bollig/viennacl", "max_issues_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_issues_repo_licenses": ["MIT"], "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/blas3range.cpp", "max_forks_repo_name": "bollig/viennacl", "max_forks_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_forks_repo_licenses": ["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.714953271, "max_line_length": 165, "alphanum_fraction": 0.6019887479, "num_tokens": 2176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5394936377940857}}
{"text": "/* test_triangle_distribution.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_triangle_distribution.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\r\n *\r\n */\r\n\r\n#include <boost/random/triangle_distribution.hpp>\r\n#include <limits>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::triangle_distribution<>\r\n#define BOOST_RANDOM_ARG1 a\r\n#define BOOST_RANDOM_ARG2 b\r\n#define BOOST_RANDOM_ARG3 c\r\n#define BOOST_RANDOM_ARG1_DEFAULT 0.0\r\n#define BOOST_RANDOM_ARG2_DEFAULT 0.5\r\n#define BOOST_RANDOM_ARG3_DEFAULT 1.0\r\n#define BOOST_RANDOM_ARG1_VALUE -0.5\r\n#define BOOST_RANDOM_ARG2_VALUE 0.25\r\n#define BOOST_RANDOM_ARG3_VALUE 1.5\r\n\r\n#define BOOST_RANDOM_DIST0_MIN 0.0\r\n#define BOOST_RANDOM_DIST0_MAX 1.0\r\n#define BOOST_RANDOM_DIST1_MIN -0.5\r\n#define BOOST_RANDOM_DIST1_MAX 1.0\r\n#define BOOST_RANDOM_DIST2_MIN -0.5\r\n#define BOOST_RANDOM_DIST2_MAX 1.0\r\n#define BOOST_RANDOM_DIST3_MIN -0.5\r\n#define BOOST_RANDOM_DIST3_MAX 1.5\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS (-1, -0.5, 0)\r\n#define BOOST_RANDOM_TEST1_MAX 0\r\n\r\n#define BOOST_RANDOM_TEST2_PARAMS (0, 0.5, 1)\r\n#define BOOST_RANDOM_TEST2_MIN 0\r\n\r\n#include \"test_distribution.ipp\"\r\n", "meta": {"hexsha": "403d6f6ef2d6b768f3e9987fb7c2d403bbd7cf0b", "size": 1293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_triangle_distribution.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_triangle_distribution.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_triangle_distribution.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": 30.7857142857, "max_line_length": 84, "alphanum_fraction": 0.7873163186, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5394936358007042}}
{"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 <Eigen/Core>\n#include <boost/math/distributions/hypergeometric.hpp>\n#include \"metro/FishersExactTest.hpp\"\n\nnamespace metro {\n\tFishersExactTest::FishersExactTest( Eigen::Matrix2d const& matrix ):\n\t\tm_matrix( matrix ),\n\t\tm_distribution( m_matrix.col( 0 ).sum(), m_matrix.row( 0 ).sum(), m_matrix.sum() )\n\t{}\n\n\tdouble FishersExactTest::get_OR() const {\n\t\treturn ( m_matrix(0,0) * m_matrix(1,1) ) / ( m_matrix(0,1)*m_matrix(1,0) ) ;\n\t}\n\n\tstd::pair< double, double > FishersExactTest::get_confidence_interval() const {\n\t\tassert(0) ; // not implemented yet\n\t}\n\n\tdouble FishersExactTest::get_pvalue( Alternative const alternative ) const {\n\t\tusing boost::math::cdf ;\n\t\tusing boost::math::complement ;\n\n\t\tdouble result = 0 ;\n\t\tswitch( alternative ) {\n\t\t\tcase eGreater:\n\t\t\t\tif( m_matrix(0,0) == 0 || m_matrix(1,1) == 0 ) {\n\t\t\t\t\tresult = 1 ;\n\t\t\t\t} else {\n\t\t\t\t\tresult = cdf( complement( m_distribution, m_matrix( 0, 0 ) - 1.0 )) ;\n\t\t\t\t}\n\t\t\t\tbreak ;\n\t\t\tcase eLess:\n\t\t\t\tresult = cdf( m_distribution, m_matrix( 0, 0 ) ) ;\n\t\t\t\tbreak ;\n\t\t\tcase eTwoSided:\n\t\t\t\t// As in R's fisher.test(), we take as \"at least as extreme\" all tables\n\t\t\t\t// with equal or lower probability under hypergeometric distribution.\n\t\t\t\t\n\t\t\t\tdouble const p = pdf( m_distribution, m_matrix( 0, 0 ) ) ;\n\t\t\t\tresult = p ;\n\n\t\t\t\t// computation over all tables can be quite slow.\n\t\t\t\t// speed it up by inspecting which tail of the distribution our value is in\n\t\t\t\t// and then using the appropriate cdf.\n\t\t\t\tint const min_value = std::max( 0.0, m_matrix(0,0) - m_matrix(1,1)) ;\n\t\t\t\tint const lower_mode = std::max(\n\t\t\t\t\tint( ( m_matrix.col( 0 ).sum() + 1 ) * ( m_matrix.row( 0 ).sum() + 1 ) / ( m_matrix.sum() + 2 ) ),\n\t\t\t\t\tmin_value\n\t\t\t\t) ;\n\t\t\t\t\n\t\t\t\tif( m_matrix( 0, 0 ) == lower_mode ) {\n\t\t\t\t\tresult = 1 ;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// compute one tail using boost::cdf() and the other using\n\t\t\t\t\t// a recursion trick.\n\t\t\t\t\tdouble begin_a = 0 ;\n\t\t\t\t\tdouble end_a = 0 ;\n\t\t\t\t\tdouble direction = 0 ;\n\t\t\t\t\tif( m_matrix( 0, 0 ) > lower_mode ) {\n\t\t\t\t\t\t// compute upper tail\n\t\t\t\t\t\tresult = cdf( complement( m_distribution, m_matrix( 0, 0 ) - 1.0 )) ;\n\t\t\t\t\t\t// compute lower tail, walking out from mode towards tail.\n\t\t\t\t\t\tbegin_a = lower_mode ;\n\t\t\t\t\t\tend_a = std::max( 0.0, m_matrix(0,0) - m_matrix(1,1)) - 1 ;\n\t\t\t\t\t\tdirection = -1 ;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t// compute lower tail\n\t\t\t\t\t\tresult = cdf( m_distribution, m_matrix( 0, 0 ) ) ;\n\t\t\t\t\t\t// compute upper tail, walking out from mode towards tail.\n\t\t\t\t\t\tbegin_a = lower_mode ;\n\t\t\t\t\t\tend_a = std::min( m_matrix.row(0).sum(), m_matrix.col(0).sum() ) + 1 ;\n\t\t\t\t\t\tdirection = 1 ;\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\tdouble const R0 = m_matrix.row(0).sum() ;\n\t\t\t\t\tdouble const C0 = m_matrix.col(0).sum() ;\n\t\t\t\t\tdouble const C1 = m_matrix.col(1).sum() ;\n\t\t\t\t\tfor(\n\t\t\t\t\t\tdouble a = begin_a, q = pdf( m_distribution, begin_a ) ;\n\t\t\t\t\t\t(direction * a ) < (direction * end_a) ;\n\t\t\t\t\t\ta += direction\n\t\t\t\t\t) {\n\t\t\t\t\t\tif( q == 0 ) {\n\t\t\t\t\t\t\tbreak ;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if( ( q / p ) < 10 && ( q / p ) > 0.1 ) {\n\t\t\t\t\t\t\t// Within an order of magnitude of p.  Recompute q to avoid accuracy loss.\n\t\t\t\t\t\t\tq = pdf( m_distribution, a ) ;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif( q <= p ) {\n\t\t\t\t\t\t\tresult += q ;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdouble const b = R0 - a ;\n\t\t\t\t\t\tdouble const c = C0 - a ;\n\t\t\t\t\t\tdouble const d = C1 - b ;\n\t\t\t\t\t\tif( direction == 1 ) {\n\t\t\t\t\t\t\tq *= ( b / ( a + 1 ) ) * ( c / ( d + 1 )) ;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tq /= ( ( b + 1 ) / a ) * ( ( c + 1 ) / d ) ;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tbreak ;\n\t\t}\n\t\treturn result ;\n\t}\n}\n", "meta": {"hexsha": "efb75c88cae617cccbf73fe86f493e3b2e3a2861", "size": 3674, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metro/src/FishersExactTest.cpp", "max_stars_repo_name": "gavinband/bingwa", "max_stars_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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/src/FishersExactTest.cpp", "max_issues_repo_name": "gavinband/bingwa", "max_issues_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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/src/FishersExactTest.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.6724137931, "max_line_length": 103, "alphanum_fraction": 0.5683179096, "num_tokens": 1154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5394298882837518}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_FUNCTIONS_GENERIC_ACOTD_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_FUNCTIONS_GENERIC_ACOTD_HPP_INCLUDED\n\n#include <nt2/trigonometric/functions/acotd.hpp>\n#include <nt2/include/functions/simd/atand.hpp>\n#include <nt2/include/functions/simd/if_else_zero.hpp>\n#include <nt2/include/functions/simd/if_zero_else.hpp>\n#include <nt2/include/functions/simd/abs.hpp>\n#include <nt2/include/functions/simd/is_nez.hpp>\n#include <nt2/include/functions/simd/bitofsign.hpp>\n#include <nt2/include/functions/simd/bitwise_or.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/constants/_90.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/functions/simd/is_inf.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( acotd_,tag::cpu_\n                            , (A0)\n                            , ((generic_<floating_<A0> >))\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      A0 z = nt2::_90<A0>()-nt2::if_else_zero(nt2::is_nez(a0),nt2::atand(nt2::abs(a0)));\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      z = nt2::if_zero_else(nt2::is_inf(a0),z);\n      #endif\n      return nt2::b_or(z, nt2::bitofsign(a0));\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "5f4e5f1734c530791baec76d7c0476a3a90f08ac", "size": 1780, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/generic/acotd.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/generic/acotd.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/trigonometric/include/nt2/trigonometric/functions/generic/acotd.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 36.3265306122, "max_line_length": 88, "alphanum_fraction": 0.6151685393, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5393863863103221}}
{"text": "/* \n * benchmark_hogwild_regression.cpp\n * author: Abhijit Chowdhary (achowdh2@ncsu.edu)\n *\n * Benchmark HOGWILD! as applied to regression on to a simple random normal 50\n * x 50 matrix A and random normal vector b:\n *\n *  minimize (1/2)||Ax-b||_2^2\n *\n * Outputs to results.txt and stdout time taken to reach desired tolerance for\n * each core count possible in system.\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 */\n#include <omp.h>\n#include <stdio.h>\n\n#include <algorithm>\n#include <array>\n#include <atomic>\n#include <iostream>\n#include <random>\n\n#include <Eigen/Dense>\n\n#include \"readCSV.h\"\n\n#define ETA 0.00025\n#define NUM_EPOCHS 5\n\nint \nmain(int argc, char **argv)\n{\n  FILE *fresults, *fX;\n  fresults = fopen(\"results.txt\", \"w+\"); fX = fopen(\"X.txt\", \"w+\");\n  Eigen::initParallel();\n  omp_set_dynamic(0);\n  auto rng = std::default_random_engine {}; rng.seed(0);\n\n  unsigned P = omp_get_max_threads();\n  double timings[P];\n  for (unsigned k = 0; k < P; k++) { timings[k] = 0; }\n\n  // Read MSD dataset into memory and format matrices.\n  Eigen::MatrixXd Data;\n  readCSV<double>(\"winequality-white.csv\", Data);\n  unsigned const num_data = 4898; unsigned const num_features = 11;\n\n  Eigen::MatrixXd A = Data.topLeftCorner(num_data, num_features);\n  Eigen::VectorXd b = Data.col(num_features);\n\n  std::array<unsigned, num_data> ordering;\n  std::iota(ordering.begin(), ordering.end(), 0);\n\n  std::atomic<double> *x = new std::atomic<double>[num_features];\n  Eigen::MatrixXd X(num_features,1);\n  for (unsigned k = 0; k < num_features; k++) { x[k] = 1; X(k) = 1; }\n  fprintf(fresults, \"%f\\n\", (0.5/num_data)*(A*X-b).squaredNorm());\n\n  for (unsigned epoch = 0; epoch < NUM_EPOCHS; epoch++)\n  {\n    std::shuffle(ordering.begin(), ordering.end(), rng);\n    #pragma omp parallel for\n    for (unsigned k = 0; k < num_data; k++)\n    {\n      unsigned id = ordering[k];\n      double dg = 0;\n      for (unsigned i = 0; i < num_features; i++) { dg += A(id, i)*x[i].load(); }\n      dg -= b(id);\n      for (unsigned i = 0; i < num_features; i++)\n      {\n        double dgi = x[i].load() - ETA*(1.0/num_data)*( A(id,i)*dg + num_data*x[i].load() );\n        x[i].exchange( dgi );\n      }\n    }\n    for (unsigned k = 0; k < num_features; k++) { X(k) = x[k].load(); }\n    double epsilon = (0.5/num_data)*(A*X-b).squaredNorm();\n    fprintf(fresults, \"%f\\n\", epsilon);\n    if (epsilon < 1e-5)\n    {\n      break;\n    }\n  }\n\n  for (unsigned k = 0; k < num_features; k++)\n  {\n    fprintf(fX, \"%f\\n\", X(k));\n  }\n\n  fclose(fresults); fclose(fX);\n  return 0;\n}\n", "meta": {"hexsha": "b838fe34e4ac91bfa03b0703113a79a29e0ae63b", "size": 2773, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Tests/wine_quality/ridge_regression/benchmark_hogwild_regression.cc", "max_stars_repo_name": "abhijit-c/HOGWILD", "max_stars_repo_head_hexsha": "1ae85888fb5c33f0cf01043064d30106e7a3de39", "max_stars_repo_licenses": ["MIT"], "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/wine_quality/ridge_regression/benchmark_hogwild_regression.cc", "max_issues_repo_name": "abhijit-c/HOGWILD", "max_issues_repo_head_hexsha": "1ae85888fb5c33f0cf01043064d30106e7a3de39", "max_issues_repo_licenses": ["MIT"], "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/wine_quality/ridge_regression/benchmark_hogwild_regression.cc", "max_forks_repo_name": "abhijit-c/HOGWILD", "max_forks_repo_head_hexsha": "1ae85888fb5c33f0cf01043064d30106e7a3de39", "max_forks_repo_licenses": ["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.1894736842, "max_line_length": 92, "alphanum_fraction": 0.6069239091, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5393863746099675}}
{"text": "/* =========================================================================\r\n   Copyright (c) 2010-2012, Institute for Microelectronics,\r\n                            Institute for Analysis and Scientific Computing,\r\n                            TU Wien.\r\n   Portions of this software are copyright by UChicago Argonne, LLC.\r\n\r\n                            -----------------\r\n                  ViennaCL - The Vienna Computing Library\r\n                            -----------------\r\n\r\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\r\n               \r\n   (A list of authors and contributors can be found in the PDF manual)\r\n\r\n   License:         MIT (X11), see file LICENSE in the base directory\r\n============================================================================= */\r\n\r\n/*\r\n* \r\n*   Tutorial: BLAS level 2 functionality (blas2.cpp and blas2.cu are identical, the latter being required for compilation using CUDA nvcc)\r\n*   \r\n*/\r\n\r\n\r\n//\r\n// include necessary system headers\r\n//\r\n#include <iostream>\r\n\r\n//\r\n// ublas includes\r\n//\r\n#include <boost/numeric/ublas/io.hpp>\r\n#include <boost/numeric/ublas/triangular.hpp>\r\n#include <boost/numeric/ublas/matrix_sparse.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/matrix_proxy.hpp>\r\n#include <boost/numeric/ublas/lu.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n\r\n\r\n// Must be set if you want to use ViennaCL algorithms on ublas objects\r\n#define VIENNACL_WITH_UBLAS 1\r\n\r\n\r\n//\r\n// ViennaCL includes\r\n//\r\n#include \"viennacl/scalar.hpp\"\r\n#include \"viennacl/vector.hpp\"\r\n#include \"viennacl/matrix.hpp\"\r\n#include \"viennacl/linalg/direct_solve.hpp\"\r\n#include \"viennacl/linalg/prod.hpp\"       //generic matrix-vector product\r\n#include \"viennacl/linalg/norm_2.hpp\"     //generic l2-norm for vectors\r\n#include \"viennacl/linalg/lu.hpp\"         //LU substitution routines\r\n\r\n// Some helper functions for this tutorial:\r\n#include \"Random.hpp\"\r\n#include \"vector-io.hpp\"\r\n\r\nusing namespace boost::numeric;\r\n\r\nint main()\r\n{\r\n  typedef float       ScalarType;\r\n  \r\n  //\r\n  // Set up some ublas objects\r\n  //\r\n  ublas::vector<ScalarType> rhs(12);\r\n  for (unsigned int i = 0; i < rhs.size(); ++i)\r\n    rhs(i) = random<ScalarType>();\r\n  ublas::vector<ScalarType> rhs2 = rhs;\r\n  ublas::vector<ScalarType> result = ublas::zero_vector<ScalarType>(10);\r\n  ublas::vector<ScalarType> result2 = result;\r\n  ublas::vector<ScalarType> rhs_trans = rhs;\r\n  rhs_trans.resize(result.size(), true);\r\n  ublas::vector<ScalarType> result_trans = ublas::zero_vector<ScalarType>(rhs.size());\r\n\r\n  \r\n  ublas::matrix<ScalarType> matrix(result.size(),rhs.size());\r\n\r\n  //\r\n  // Fill the matrix\r\n  //\r\n  for (unsigned int i = 0; i < matrix.size1(); ++i)\r\n    for (unsigned int j = 0; j < matrix.size2(); ++j)\r\n      matrix(i,j) = random<ScalarType>();\r\n    \r\n  //\r\n  // Use some plain STL types:\r\n  //\r\n  std::vector< ScalarType > stl_result(result.size());\r\n  std::vector< ScalarType > stl_rhs(rhs.size());\r\n  std::vector< std::vector<ScalarType> > stl_matrix(result.size());\r\n  for (unsigned int i=0; i < result.size(); ++i)\r\n  {\r\n    stl_matrix[i].resize(rhs.size());\r\n    for (unsigned int j = 0; j < matrix.size2(); ++j)\r\n    {\r\n      stl_rhs[j] = rhs[j];\r\n      stl_matrix[i][j] = matrix(i,j);\r\n    }\r\n  }\r\n\r\n  //\r\n  // Set up some ViennaCL objects\r\n  //\r\n  viennacl::vector<ScalarType> vcl_rhs(rhs.size());\r\n  viennacl::vector<ScalarType> vcl_result(result.size()); \r\n  viennacl::matrix<ScalarType> vcl_matrix(result.size(), rhs.size());\r\n  viennacl::matrix<ScalarType> vcl_matrix2(result.size(), rhs.size());\r\n\r\n  viennacl::copy(rhs.begin(), rhs.end(), vcl_rhs.begin());\r\n  viennacl::copy(matrix, vcl_matrix);     //copy from ublas dense matrix type to ViennaCL type\r\n\r\n  //\r\n  // Some basic matrix operations\r\n  //\r\n  vcl_matrix2 = vcl_matrix;\r\n  vcl_matrix2 += vcl_matrix;\r\n  vcl_matrix2 -= vcl_matrix;\r\n  vcl_matrix2 = vcl_matrix2 + vcl_matrix;\r\n  vcl_matrix2 = vcl_matrix2 - vcl_matrix;\r\n  \r\n  viennacl::scalar<ScalarType> vcl_3(3.0);\r\n  vcl_matrix2 *= ScalarType(2.0);\r\n  vcl_matrix2 /= ScalarType(2.0);\r\n  vcl_matrix2 *= vcl_3;\r\n  vcl_matrix2 /= vcl_3;\r\n\r\n  //\r\n  // A matrix can be cleared directly:\r\n  //\r\n  vcl_matrix.clear();\r\n  \r\n  viennacl::copy(stl_matrix, vcl_matrix); //alternative: copy from STL vector< vector<> > type to ViennaCL type\r\n\r\n  //for demonstration purposes (no effect):\r\n  viennacl::copy(vcl_matrix, matrix); //copy back from ViennaCL to ublas type.\r\n  viennacl::copy(vcl_matrix, stl_matrix); //copy back from ViennaCL to STL type.\r\n  \r\n  /////////////////////////////////////////////////\r\n  //////////// Matrix vector products /////////////\r\n  /////////////////////////////////////////////////\r\n  \r\n  \r\n  //\r\n  // Compute matrix-vector products\r\n  //\r\n  std::cout << \"----- Matrix-Vector product -----\" << std::endl;\r\n  result = ublas::prod(matrix, rhs);                            //the ublas way\r\n  stl_result = viennacl::linalg::prod(stl_matrix, stl_rhs);     //using STL\r\n  vcl_result = viennacl::linalg::prod(vcl_matrix, vcl_rhs);     //the ViennaCL way\r\n  \r\n  //\r\n  // Compute transposed matrix-vector products\r\n  //\r\n  std::cout << \"----- Transposed Matrix-Vector product -----\" << std::endl;\r\n  result_trans = prod(trans(matrix), rhs_trans);\r\n  \r\n  viennacl::vector<ScalarType> vcl_rhs_trans(rhs_trans.size());\r\n  viennacl::vector<ScalarType> vcl_result_trans(result_trans.size()); \r\n  viennacl::copy(rhs_trans.begin(), rhs_trans.end(), vcl_rhs_trans.begin());\r\n  vcl_result_trans = viennacl::linalg::prod(trans(vcl_matrix), vcl_rhs_trans);\r\n  \r\n  \r\n  \r\n  /////////////////////////////////////////////////\r\n  //////////////// Direct solver  /////////////////\r\n  /////////////////////////////////////////////////\r\n  \r\n  \r\n  //\r\n  // Setup suitable matrices\r\n  //\r\n  ublas::matrix<ScalarType> tri_matrix(10,10);\r\n  for (size_t i=0; i<tri_matrix.size1(); ++i)\r\n  {\r\n    for (size_t j=0; j<i; ++j)\r\n      tri_matrix(i,j) = 0.0;\r\n\r\n    for (size_t j=i; j<tri_matrix.size2(); ++j)\r\n      tri_matrix(i,j) = matrix(i,j);\r\n  }\r\n  \r\n  viennacl::matrix<ScalarType> vcl_tri_matrix(tri_matrix.size1(), tri_matrix.size2());\r\n  viennacl::copy(tri_matrix, vcl_tri_matrix);\r\n  \r\n  rhs.resize(tri_matrix.size1(), true);\r\n  rhs2.resize(tri_matrix.size1(), true);\r\n  vcl_rhs.resize(tri_matrix.size1(), true);\r\n  \r\n  viennacl::copy(rhs.begin(), rhs.end(), vcl_rhs.begin());\r\n  vcl_result.resize(10);\r\n\r\n  \r\n  //\r\n  // Triangular solver\r\n  //\r\n  std::cout << \"----- Upper Triangular solve -----\" << std::endl;\r\n  result = ublas::solve(tri_matrix, rhs, ublas::upper_tag());                                    //ublas\r\n  vcl_result = viennacl::linalg::solve(vcl_tri_matrix, vcl_rhs, viennacl::linalg::upper_tag());  //ViennaCL\r\n  \r\n  //\r\n  // Inplace variants of the above\r\n  //\r\n  ublas::inplace_solve(tri_matrix, rhs, ublas::upper_tag());                                //ublas\r\n  viennacl::linalg::inplace_solve(vcl_tri_matrix, vcl_rhs, viennacl::linalg::upper_tag());  //ViennaCL\r\n  \r\n\r\n  //\r\n  // Set up a full system for LU solver:\r\n  // \r\n  std::cout << \"----- LU factorization -----\" << std::endl;\r\n  size_t lu_dim = 300;\r\n  ublas::matrix<ScalarType> square_matrix(lu_dim, lu_dim);\r\n  ublas::vector<ScalarType> lu_rhs(lu_dim);\r\n  viennacl::matrix<ScalarType> vcl_square_matrix(lu_dim, lu_dim);\r\n  viennacl::vector<ScalarType> vcl_lu_rhs(lu_dim);\r\n\r\n  for (size_t i=0; i<lu_dim; ++i)\r\n    for (size_t j=0; j<lu_dim; ++j)\r\n      square_matrix(i,j) = random<ScalarType>();\r\n\r\n  //put some more weight on diagonal elements:\r\n  for (size_t j=0; j<lu_dim; ++j)\r\n  {\r\n    square_matrix(j,j) += 10.0;\r\n    lu_rhs(j) = random<ScalarType>();\r\n  }\r\n    \r\n  viennacl::copy(square_matrix, vcl_square_matrix);\r\n  viennacl::copy(lu_rhs, vcl_lu_rhs);\r\n  viennacl::linalg::lu_factorize(vcl_square_matrix);\r\n  viennacl::linalg::lu_substitute(vcl_square_matrix, vcl_lu_rhs);\r\n  viennacl::copy(square_matrix, vcl_square_matrix);\r\n  viennacl::copy(lu_rhs, vcl_lu_rhs);\r\n\r\n  \r\n  //\r\n  // ublas:\r\n  //\r\n  ublas::lu_factorize(square_matrix);\r\n  ublas::inplace_solve (square_matrix, lu_rhs, ublas::unit_lower_tag ());\r\n  ublas::inplace_solve (square_matrix, lu_rhs, ublas::upper_tag ());\r\n\r\n\r\n  //\r\n  // ViennaCL:\r\n  //\r\n  viennacl::linalg::lu_factorize(vcl_square_matrix);\r\n  viennacl::linalg::lu_substitute(vcl_square_matrix, vcl_lu_rhs);\r\n\r\n  //\r\n  //  That's it. \r\n  //\r\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\r\n  \r\n  return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "16dcd7158da7771fd261336c09f78abccb49be2f", "size": 8434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/blas2.cpp", "max_stars_repo_name": "bollig/viennacl", "max_stars_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T08:33:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T08:33:10.000Z", "max_issues_repo_path": "examples/tutorial/blas2.cpp", "max_issues_repo_name": "bollig/viennacl", "max_issues_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_issues_repo_licenses": ["MIT"], "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/blas2.cpp", "max_forks_repo_name": "bollig/viennacl", "max_forks_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_forks_repo_licenses": ["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.0684410646, "max_line_length": 139, "alphanum_fraction": 0.5993597344, "num_tokens": 2254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5393863681216857}}
{"text": "#pragma once\n\n#include <mtao/types.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <set>\n\n#include \"mtao/algebra/sort_with_permutation_sign.hpp\"\n#include \"mtao/eigen/stl2eigen.hpp\"\n\nnamespace mtao::geometry::mesh {\n\n// Only for simplices\ntemplate <typename CellType>\nauto unique_simplices(const Eigen::MatrixBase<CellType>& C) ->\n    typename CellType::PlainMatrix {\n    // each simplex can be uniquely canonically represented by\n    // itself sorted and whether it took an even or odd permutation to obtain it\n    // Because we're assuming simplices of dimension <= 4 bubble sort is not\n    // only the most efficient, its easy to impl and check the number of swaps\n    // :)\n    constexpr int Rows = CellType::RowsAtCompileTime;\n    constexpr bool DynamicSize = Rows == Eigen::Dynamic;\n    using StlType = std::conditional_t<DynamicSize, std::vector<int>,\n                                       std::array<int, Rows>>;\n\n    std::map<StlType, bool> uniq_map;\n\n    for (int i = 0; i < C.cols(); ++i) {\n        if constexpr (DynamicSize) {\n            StlType s(C.rows());\n            mtao::eigen::stl2eigen(s) = C.col(i);\n            bool even = algebra::sort_with_permutation_sign_in_place<\n                algebra::SortType::Bubble>(s);\n\n            uniq_map.try_emplace(std::move(s), even);\n        } else {\n            StlType s;\n            mtao::eigen::stl2eigen(s) = C.col(i);\n            bool even = algebra::sort_with_permutation_sign_in_place<\n                algebra::SortType::Bubble>(s);\n\n            uniq_map.try_emplace(std::move(s), even);\n        }\n    }\n\n    // if  the input simplices were unique lets avoid messing with the input\n    if (int(uniq_map.size()) != C.cols()) {\n        typename CellType::PlainMatrix CC(C.rows(), uniq_map.size());\n        for (auto&& [idx, pr] : mtao::iterator::enumerate(uniq_map)) {\n            auto&& [c, even] = pr;\n            auto v = CC.col(idx) = mtao::eigen::stl2eigen(c);\n            if (C.rows() > 1 && !even) {\n                std::swap(v(0), v(1));\n            }\n        }\n        return CC;\n    }\n    return C;\n}\n\n}  // namespace mtao::geometry::mesh\n", "meta": {"hexsha": "2e728dbaebe3daa267ba283e19693933dafde402", "size": 2127, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/geometry/mesh/unique_simplices.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/geometry/mesh/unique_simplices.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/geometry/mesh/unique_simplices.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.234375, "max_line_length": 80, "alphanum_fraction": 0.5961448049, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5393158698914801}}
{"text": "//\n//  Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n\n#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include \"utility.hpp\"\n\nBOOST_AUTO_TEST_SUITE(test_tensor_static_rank_comparison)\n\nusing double_extended = boost::multiprecision::cpp_bin_float_double_extended;\n\nusing test_types = zip<int,float,double_extended>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\nstruct fixture {\n  template<size_t N>\n  using extents_t = boost::numeric::ublas::extents<N>;\n\n  std::tuple<\n    extents_t<2>, // 1\n    extents_t<2>, // 2\n    extents_t<3>, // 3\n    extents_t<3>, // 4\n    extents_t<4>  // 5\n    > extents = {  \n      extents_t<2>{1,1},\n      extents_t<2>{2,3},\n      extents_t<3>{4,1,3},\n      extents_t<3>{4,2,3},\n      extents_t<4>{4,2,3,5}\n  };\n};\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_comparison, value,  test_types, fixture)\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t  = typename value::first_type;\n  using layout_t = typename value::second_type;\n\n  auto check = [](auto const& /*unused*/, auto& e)\n  {\n    using extents_t = std::decay_t<decltype (e)>;\n    using tensor_t = ublas::tensor_static_rank<value_t, std::tuple_size_v<extents_t>, layout_t>;\n    auto t  = tensor_t (e);\n    auto t2 = tensor_t (e);\n    auto v  = value_t  {};\n\n    std::iota(t.begin(), t.end(), v);\n    std::iota(t2.begin(), t2.end(), v+2);\n\n    BOOST_CHECK( t == t  );\n    BOOST_CHECK( t != t2 );\n\n    if(t.empty())\n      return;\n\n    BOOST_CHECK(!(t < t));\n    BOOST_CHECK(!(t > t));\n    BOOST_CHECK( t < t2 );\n    BOOST_CHECK( t2 > t );\n    BOOST_CHECK( t <= t );\n    BOOST_CHECK( t >= t );\n    BOOST_CHECK( t <= t2 );\n    BOOST_CHECK( t2 >= t );\n    BOOST_CHECK( t2 >= t2 );\n    BOOST_CHECK( t2 >= t );\n  };\n\n  for_each_in_tuple(extents,check);\n\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_comparison_with_tensor_expressions, value,  test_types, fixture)\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n\n\n  for_each_in_tuple(extents,[](auto const& /*unused*/, auto& e) {\n    using extents_t = std::decay_t<decltype (e)>;\n    using tensor_t  = ublas::tensor_static_rank<value_t, std::tuple_size_v<extents_t>, layout_t>;\n\n    auto t  = tensor_t (e);\n    auto t2 = tensor_t (e);\n    auto v  = value_t  {};\n\n    std::iota(t.begin(), t.end(), v);\n    std::iota(t2.begin(), t2.end(), v+2);\n\n    BOOST_CHECK( t == t  );\n    BOOST_CHECK( t != t2 );\n\n    if(t.empty())\n      return;\n\n    BOOST_CHECK( !(t < t) );\n    BOOST_CHECK( !(t > t) );\n    BOOST_CHECK( t < (t2+t) );\n    BOOST_CHECK( (t2+t) > t );\n    BOOST_CHECK( t <= (t+t) );\n    BOOST_CHECK( (t+t2) >= t );\n    BOOST_CHECK( (t2+t2+2) >= t);\n    BOOST_CHECK( 2*t2 > t );\n    BOOST_CHECK( t < 2*t2 );\n    BOOST_CHECK( 2*t2 > t);\n    BOOST_CHECK( 2*t2 >= t2 );\n    BOOST_CHECK( t2 <= 2*t2);\n    BOOST_CHECK( 3*t2 >= t );\n  });\n\n\n}\n\n\n\n//BOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_comparison_with_scalar, value,  test_types, fixture)\n//{\n//  namespace ublas = boost::numeric::ublas;\n//  using value_t  = typename value::first_type;\n//  using layout_t = typename value::second_type;\n\n\n//  for_each_in_tuple(extents, [](auto const& /*unused*/, auto& e) {\n//    using extents_t = std::decay_t<decltype (e)>;\n//    using tensor_t  = ublas::tensor_static_rank<value_t, std::tuple_size_v<extents_t>, layout_t>;\n\n//    BOOST_CHECK( tensor_t(e,value_t{2}) == tensor_t(e,value_t{2})  );\n//    BOOST_CHECK( tensor_t(e,value_t{2}) != tensor_t(e,value_t{1})  );\n\n//    if(ublas::empty(e))\n//      return;\n\n//    BOOST_CHECK( !(tensor_t(e,2) <  2) );\n//    BOOST_CHECK( !(tensor_t(e,2) >  2) );\n//    BOOST_CHECK(  (tensor_t(e,2) >= 2) );\n//    BOOST_CHECK(  (tensor_t(e,2) <= 2) );\n//    BOOST_CHECK(  (tensor_t(e,2) == 2) );\n//    BOOST_CHECK(  (tensor_t(e,2) != 3) );\n\n//    BOOST_CHECK( !(2 >  tensor_t(e,2)) );\n//    BOOST_CHECK( !(2 <  tensor_t(e,2)) );\n//    BOOST_CHECK(  (2 <= tensor_t(e,2)) );\n//    BOOST_CHECK(  (2 >= tensor_t(e,2)) );\n//    BOOST_CHECK(  (2 == tensor_t(e,2)) );\n//    BOOST_CHECK(  (3 != tensor_t(e,2)) );\n\n//    BOOST_CHECK( !( tensor_t(e,2)+3 <  5) );\n//    BOOST_CHECK( !( tensor_t(e,2)+3 >  5) );\n//    BOOST_CHECK(  ( tensor_t(e,2)+3 >= 5) );\n//    BOOST_CHECK(  ( tensor_t(e,2)+3 <= 5) );\n//    BOOST_CHECK(  ( tensor_t(e,2)+3 == 5) );\n//    BOOST_CHECK(  ( tensor_t(e,2)+3 != 6) );\n\n\n//    BOOST_CHECK( !( 5 >  tensor_t(e,2)+3) );\n//    BOOST_CHECK( !( 5 <  tensor_t(e,2)+3) );\n//    BOOST_CHECK(  ( 5 >= tensor_t(e,2)+3) );\n//    BOOST_CHECK(  ( 5 <= tensor_t(e,2)+3) );\n//    BOOST_CHECK(  ( 5 == tensor_t(e,2)+3) );\n//    BOOST_CHECK(  ( 6 != tensor_t(e,2)+3) );\n\n\n//    BOOST_CHECK( !( tensor_t(e,2)+tensor_t(e,3) <  5) );\n//    BOOST_CHECK( !( tensor_t(e,2)+tensor_t(e,3) >  5) );\n//    BOOST_CHECK(  ( tensor_t(e,2)+tensor_t(e,3) >= 5) );\n//    BOOST_CHECK(  ( tensor_t(e,2)+tensor_t(e,3) <= 5) );\n//    BOOST_CHECK(  ( tensor_t(e,2)+tensor_t(e,3) == 5) );\n//    BOOST_CHECK(  ( tensor_t(e,2)+tensor_t(e,3) != 6) );\n\n\n//    BOOST_CHECK( !( 5 >  tensor_t(e,2)+tensor_t(e,3)) );\n//    BOOST_CHECK( !( 5 <  tensor_t(e,2)+tensor_t(e,3)) );\n//    BOOST_CHECK(  ( 5 >= tensor_t(e,2)+tensor_t(e,3)) );\n//    BOOST_CHECK(  ( 5 <= tensor_t(e,2)+tensor_t(e,3)) );\n//    BOOST_CHECK(  ( 5 == tensor_t(e,2)+tensor_t(e,3)) );\n//    BOOST_CHECK(  ( 6 != tensor_t(e,2)+tensor_t(e,3)) );\n\n//  });\n\n//}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "59338c38700333ab6ffdb14318dd6f27d4d190c4", "size": 5871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_fixed_rank_operators_comparison.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_fixed_rank_operators_comparison.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_fixed_rank_operators_comparison.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 29.6515151515, "max_line_length": 145, "alphanum_fraction": 0.5990461591, "num_tokens": 1943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5393158621974204}}
{"text": "/**\n * @file lqr_controller.cpp\n * @brief Infinite-horizon Linear Quadratic Regulator.\n * \n */\n\n#include <lqr_controller.hpp>\n#include <Eigen/Dense>\n\nusing namespace controller;\n\nLQR::LQR(\n    const Eigen::MatrixXd& Q, \n    const Eigen::MatrixXd& R\n    ):\n    Q(Q),\n    R(R)\n{\n    P.setZero(Q.rows(), Q.cols());\n    cmd_vel.setZero(1, R.rows()); // [translation rate, rotation rate].\n}\n\nEigen::MatrixXd LQR::computeHamiltonian(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B, const Eigen::MatrixXd& E)\n{\n    // Set Hamilton matrix.\n    Ham = Eigen::MatrixXd::Zero(2 * A.rows(), 2 * A.rows());\n    Ham << A, -B * R.inverse() * B.transpose(), -Q, -A.transpose();\n\n    // Get eigenvalues and eigenvectors from Hamilton matrix.\n    Eigen::EigenSolver<Eigen::MatrixXd> eigen(Ham);\n\n    // Form a 2nxn matrix whos columns from a basis of the corresponding subspace.\n    Eigen::MatrixXcd eigenVec = Eigen::MatrixXcd::Zero(2 * A.rows(), A.rows());\n\n    // Iterate over the Hamilton matrix and extract a stable Eigenvector.\n    int j = 0;\n    for(unsigned int i = 0; i < 2 * A.rows(); ++i)\n    {\n        // Get the negative real part: a stable value in the Laplace domain.\n        if(eigen.eigenvalues()[i].real() < 0)\n        {\n            eigenVec.col(j) = eigen.eigenvectors().block(0, i, 2 * A.rows(), 1);\n            ++j;\n        }\n    }\n\n    // Compute the solution to the Riccati equation.\n    Eigen::MatrixXcd U11, U21;\n\n    U11 = eigenVec.block(0, 0, A.rows(), A.rows());\n    U21 = eigenVec.block(A.rows(), 0, A.rows(), A.rows());\n    P = (U21 * U11.inverse()).real();\n\n    // Update LQR gain.\n    K = R.inverse() * B.transpose() * P;\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    return cmd_vel;\n}", "meta": {"hexsha": "37e240d71d8a53a0a256043ee6b26e2c6f6184bd", "size": 1967, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/control_system/src/lqr_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/lqr_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/lqr_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": 30.734375, "max_line_length": 117, "alphanum_fraction": 0.6014234875, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6406358685621719, "lm_q1q2_score": 0.539303704704921}}
{"text": "/*\nProvided to you by Emlid Ltd (c) 2014.\ntwitter.com/emlidtech || www.emlid.com || info@emlid.com\n\nExample: Get pressure from MS5611 barometer onboard of Navio shield for Raspberry Pi\n\nTo run this example navigate to the directory containing it and run following commands:\nmake\n./Barometer\n*/\n\n#include <Common/MS5611.h>\n#include <Common/Util.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <boost/circular_buffer.hpp>\n#define C_TO_KELVIN 273.15f\n\nfloat get_altitude_difference(float base_pressure, float pressure, float temperature) \n{\n    float ret;\n    float temp    = temperature + C_TO_KELVIN;\n    float scaling = pressure / base_pressure;\n\n    // This is an exact calculation that is within +-2.5m of the standard\n    // atmosphere tables in the troposphere (up to 11,000 m amsl).\n    ret = 153.8462f * temp * (1.0f - expf(0.190259f * logf(scaling)));\n\n    return ret;\n}\n\nclass AverageFilter \n{\npublic:\n    AverageFilter(int size = 20) : buffer(size){\n\n    }\n    float update(float value)\n    {\n        buffer.push_back(value);\n        float sum = 0.0f;\n        for(auto v: buffer)\n        {\n            sum += v;\n        }\n        return sum/buffer.size();\n    }\nprivate:\n    boost::circular_buffer<float> buffer;\n};\n\nint main()\n{\n    MS5611 barometer;\n\n    if (check_apm()) {\n        return 1;\n    }\n\n    barometer.initialize();\n    \n    AverageFilter filter, base_pressure_filter;\n    float base_pressure = -1;\n    long  count = 0;\n    while (true) {\n        barometer.refreshPressure();\n        usleep(10000); // Waiting for pressure data ready\n        barometer.readPressure();\n\n        barometer.refreshTemperature();\n        usleep(10000); // Waiting for temperature data ready\n        barometer.readTemperature();\n\n        barometer.calculatePressureAndTemperature();\n        if(count < 100)\n        {\n            base_pressure = barometer.getPressure();\n            base_pressure = base_pressure_filter.update(base_pressure);\n        }\n        float relative_altitude = get_altitude_difference(base_pressure, barometer.getPressure(), barometer.getTemperature());\n        float filtered_relative_altitude = filter.update(relative_altitude);\n        printf(\"#%d: Temperature(C): %f Pressure(millibar): %f, relative height(m): %f, filtered: %f\\n\", count, \n                barometer.getTemperature(), barometer.getPressure(), relative_altitude, filtered_relative_altitude);\n                \n        //usleep(300000);\n        count ++;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "7a48391da01418ea98598d6132e2a04d3e87c7e1", "size": 2473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/Examples/Barometer/Barometer.cpp", "max_stars_repo_name": "mirkow/Navio2", "max_stars_repo_head_hexsha": "23eda75860908daecb0641807e46ce789939f8a0", "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": "C++/Examples/Barometer/Barometer.cpp", "max_issues_repo_name": "mirkow/Navio2", "max_issues_repo_head_hexsha": "23eda75860908daecb0641807e46ce789939f8a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "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++/Examples/Barometer/Barometer.cpp", "max_forks_repo_name": "mirkow/Navio2", "max_forks_repo_head_hexsha": "23eda75860908daecb0641807e46ce789939f8a0", "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.1758241758, "max_line_length": 126, "alphanum_fraction": 0.6502224019, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5393036982376742}}
{"text": "//=======================================================================\n// Copyright 2014-2015 David Simmons-Duffin.\n// Distributed under the MIT License.\n// (See accompanying file LICENSE or copy at\n//  http://opensource.org/licenses/MIT)\n//=======================================================================\n\n#pragma once\n\n#include \"Block_Info.hxx\"\n#include \"Block_Matrix.hxx\"\n#include \"Block_Vector.hxx\"\n#include \"Index_Tuple.hxx\"\n\n#include <boost/filesystem.hpp>\n\n// The class SDP encodes a semidefinite program of the following form\n//\n// Dual: maximize f + b.y over y,Y such that\n//                Tr(A_p Y) + (B y)_p = c_p  (0 <= p < P)\n//                Y >= 0\n// Primal: minimize f + c.x over x,X such that\n//                X = \\sum_p A_p x_p - C\n//                B^T x = b\n//                X >= 0\n//\n// where the data of the SDP has the following structure\n//\n// - b,y are vectors of length N\n//\n// - c,x are vectors of length P\n//\n// - f is a constant that we add to the objective functions for\n//   convenience. It has no effect on the running of our algorithm.\n//\n// - B is a P x N matrix, called the free variable matrix\n//\n// - X and Y are block diagonal:\n//\n//   X = BlockDiagonal(X^(0), ..., X^(bMax-1))\n//   Y = BlockDiagonal(Y^(0), ..., Y^(bMax-1))\n//\n//   Let us define Block_b(M) as BlockDiagonal(0,...,0,M,0,...,0),\n//   where M is in the b-th block.  Then X and Y can be written\n//\n//   X = \\sum_{0<=b<bMax} Block_b(X^(b))\n//   Y = \\sum_{0<=b<bMax} Block_b(Y^(b))\n//\n// - The constraints labeled by 0 <= p < P are in 1-to-1\n//   correspondence with tuples\n//\n//   p <-> (j,r,s,k) where 0 <= j < J,\n//                         0 <= s < m_j,\n//                         0 <= r <= s,\n//                         0 <= k <= d_j,\n//\n//   We often interchange the index p with the tuple (j,r,s,k).  The\n//   constraint matrices A_p are given by\n//\n//   A_(j,r,s,k) = \\sum_{b \\in blocks[j]}\n//                     Block_b(v_{b,k} v_{b,k}^T \\otimes E^{rs}),\n//\n//   where\n//   - E^{rs} is the symmetrization of the m_j x m_j matrix with a\n//     1 in entry (r,s) and zeros elsewhere.\n//   - v_{b,k} is a vector of length (delta_b+1)\n//   - \\otimes denotes a tensor product\n//   - each block above thus has dimension (delta_b+1)*m_j.\n//   - blocks[j_1] and blocks[j_2] are disjoint if j_1 != j_2.  Thus,\n//     the block index b determines a unique j, but not vice-versa.\n//\n\nstruct SDP\n{\n  // bilinear_bases is a vector of Matrices encoding the v_{b,k}\n  // that enter the constraint matrices. Specifically, v_{b,k} are\n  // the columns of bilinear_bases[b],\n  //\n  // bilinear_bases[b].elt(m,k) = (v_{b,k})_m  (0 <= b < bMax,\n  //                                           0 <= k <= d_j,\n  //                                           0 <= m <= delta_b)\n  //\n  std::vector<El::Matrix<El::BigFloat>> bilinear_bases_local;\n  std::vector<El::DistMatrix<El::BigFloat>> bilinear_bases_dist;\n\n  // free_var_matrix = B, a PxN matrix\n  Block_Matrix free_var_matrix;\n\n  // c, a vector of length P used with primal_objective\n  Block_Vector primal_objective_c;\n\n  // b, a vector of length N used with dual_objective\n  // It is duplicated amongst all the blocks\n  El::DistMatrix<El::BigFloat> dual_objective_b;\n  // Transformation from internal yp to original y\n  El::DistMatrix<El::BigFloat> yp_to_y;\n\n  // objectiveConst = f\n  El::BigFloat objective_const;\n\n  SDP(const boost::filesystem::path &sdp_directory,\n      const Block_Info &block_info, const El::Grid &grid);\n  SDP(const El::BigFloat &objective_const,\n      const std::vector<El::BigFloat> &dual_objective_b_input,\n      const std::vector<std::vector<El::BigFloat>> &primal_objective_c_input,\n      const std::vector<El::Matrix<El::BigFloat>> &free_var_input,\n      const Block_Info &block_info, const El::Grid &grid);\n};\n", "meta": {"hexsha": "d461cc2cabfd88a0742ab55200b560237ba6c8eb", "size": 3793, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/sdp_solve/SDP.hxx", "max_stars_repo_name": "suning1985/sdpb", "max_stars_repo_head_hexsha": "9263b89496d1c356f11d08f995825626b60f5b89", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sdp_solve/SDP.hxx", "max_issues_repo_name": "suning1985/sdpb", "max_issues_repo_head_hexsha": "9263b89496d1c356f11d08f995825626b60f5b89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sdp_solve/SDP.hxx", "max_forks_repo_name": "suning1985/sdpb", "max_forks_repo_head_hexsha": "9263b89496d1c356f11d08f995825626b60f5b89", "max_forks_repo_licenses": ["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.7981651376, "max_line_length": 77, "alphanum_fraction": 0.5800158186, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5393036887600088}}
{"text": "// Copyright (c) 2007, 2008 libmv authors.\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\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell 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\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\n#include \"libmv/multiview/five_point.h\"\n\n#include <Eigen/QR>\n\n#include \"libmv/multiview/fundamental.h\"\n#include \"libmv/multiview/fundamental_kernel.h\"\n#include \"libmv/multiview/five_point_internal.h\"\n\nnamespace libmv {\n\nMat FivePointsNullspaceBasis(const Mat2X &x1, const Mat2X &x2) {\n  Matrix<double, 9, 9> A;\n  A.setZero();  // Make A square until Eigen supports rectangular SVD.\n  fundamental::kernel::EncodeEpipolarEquation(x1, x2, &A);\n  Eigen::JacobiSVD<Matrix<double, 9, 9> > svd;\n  return svd.compute(A, Eigen::ComputeFullV).matrixV().topRightCorner<9, 4>();\n}\n\nVec o1(const Vec &a, const Vec &b) {\n  Vec res = Vec::Zero(20);\n\n  res(coef_xx) = a(coef_x) * b(coef_x);\n  res(coef_xy) = a(coef_x) * b(coef_y)\n               + a(coef_y) * b(coef_x);\n  res(coef_xz) = a(coef_x) * b(coef_z)\n               + a(coef_z) * b(coef_x);\n  res(coef_yy) = a(coef_y) * b(coef_y);\n  res(coef_yz) = a(coef_y) * b(coef_z)\n               + a(coef_z) * b(coef_y);\n  res(coef_zz) = a(coef_z) * b(coef_z);\n  res(coef_x)  = a(coef_x) * b(coef_1)\n               + a(coef_1) * b(coef_x);\n  res(coef_y)  = a(coef_y) * b(coef_1)\n               + a(coef_1) * b(coef_y);\n  res(coef_z)  = a(coef_z) * b(coef_1)\n               + a(coef_1) * b(coef_z);\n  res(coef_1)  = a(coef_1) * b(coef_1);\n\n  return res;\n}\n\nVec o2(const Vec &a, const Vec &b) {\n  Vec res(20);\n\n  res(coef_xxx) = a(coef_xx) * b(coef_x);\n  res(coef_xxy) = a(coef_xx) * b(coef_y)\n                + a(coef_xy) * b(coef_x);\n  res(coef_xxz) = a(coef_xx) * b(coef_z)\n                + a(coef_xz) * b(coef_x);\n  res(coef_xyy) = a(coef_xy) * b(coef_y)\n                + a(coef_yy) * b(coef_x);\n  res(coef_xyz) = a(coef_xy) * b(coef_z)\n                + a(coef_yz) * b(coef_x)\n                + a(coef_xz) * b(coef_y);\n  res(coef_xzz) = a(coef_xz) * b(coef_z)\n                + a(coef_zz) * b(coef_x);\n  res(coef_yyy) = a(coef_yy) * b(coef_y);\n  res(coef_yyz) = a(coef_yy) * b(coef_z)\n                + a(coef_yz) * b(coef_y);\n  res(coef_yzz) = a(coef_yz) * b(coef_z)\n                + a(coef_zz) * b(coef_y);\n  res(coef_zzz) = a(coef_zz) * b(coef_z);\n  res(coef_xx)  = a(coef_xx) * b(coef_1)\n                + a(coef_x)  * b(coef_x);\n  res(coef_xy)  = a(coef_xy) * b(coef_1)\n                + a(coef_x)  * b(coef_y)\n                + a(coef_y)  * b(coef_x);\n  res(coef_xz)  = a(coef_xz) * b(coef_1)\n                + a(coef_x)  * b(coef_z)\n                + a(coef_z)  * b(coef_x);\n  res(coef_yy)  = a(coef_yy) * b(coef_1)\n                + a(coef_y)  * b(coef_y);\n  res(coef_yz)  = a(coef_yz) * b(coef_1)\n                + a(coef_y)  * b(coef_z)\n                + a(coef_z)  * b(coef_y);\n  res(coef_zz)  = a(coef_zz) * b(coef_1)\n                + a(coef_z)  * b(coef_z);\n  res(coef_x)   = a(coef_x)  * b(coef_1)\n                + a(coef_1)  * b(coef_x);\n  res(coef_y)   = a(coef_y)  * b(coef_1)\n                + a(coef_1)  * b(coef_y);\n  res(coef_z)   = a(coef_z)  * b(coef_1)\n                + a(coef_1)  * b(coef_z);\n  res(coef_1)   = a(coef_1)  * b(coef_1);\n\n  return res;\n}\n\n// Builds the polynomial constraint matrix M.\nMat FivePointsPolynomialConstraints(const Mat &E_basis) {\n  // Build the polynomial form of E (equation (8) in Stewenius et al. [1])\n  Vec E[3][3];\n  for (int i = 0; i < 3; ++i) {\n    for (int j = 0; j < 3; ++j) {\n      E[i][j] = Vec::Zero(20);\n      E[i][j](coef_x) = E_basis(3 * i + j, 0);\n      E[i][j](coef_y) = E_basis(3 * i + j, 1);\n      E[i][j](coef_z) = E_basis(3 * i + j, 2);\n      E[i][j](coef_1) = E_basis(3 * i + j, 3);\n    }\n  }\n\n  // The constraint matrix.\n  Mat M(10, 20);\n  int mrow = 0;\n\n  // Determinant constraint det(E) = 0; equation (19) of Nister [2].\n  M.row(mrow++) = o2(o1(E[0][1], E[1][2]) - o1(E[0][2], E[1][1]), E[2][0]) +\n                  o2(o1(E[0][2], E[1][0]) - o1(E[0][0], E[1][2]), E[2][1]) +\n                  o2(o1(E[0][0], E[1][1]) - o1(E[0][1], E[1][0]), E[2][2]);\n\n  // Cubic singular values constraint.\n  // Equation (20).\n  Vec EET[3][3];\n  for (int i = 0; i < 3; ++i) {    // Since EET is symmetric, we only compute\n    for (int j = 0; j < 3; ++j) {  // its upper triangular part.\n      if (i <= j) {\n        EET[i][j] = o1(E[i][0], E[j][0])\n                  + o1(E[i][1], E[j][1])\n                  + o1(E[i][2], E[j][2]);\n      } else {\n        EET[i][j] = EET[j][i];\n      }\n    }\n  }\n\n  // Equation (21).\n  Vec (&L)[3][3] = EET;\n  Vec trace  = 0.5 * (EET[0][0] + EET[1][1] + EET[2][2]);\n  for (int i = 0; i < 3; ++i) {\n    L[i][i] -= trace;\n  }\n\n  // Equation (23).\n  for (int i = 0; i < 3; ++i) {\n    for (int j = 0; j < 3; ++j) {\n      Vec LEij = o2(L[i][0], E[0][j])\n               + o2(L[i][1], E[1][j])\n               + o2(L[i][2], E[2][j]);\n      M.row(mrow++) = LEij;\n    }\n  }\n\n  return M;\n}\n\n// Gauss--Jordan elimination for the constraint matrix.\nvoid FivePointsGaussJordan(Mat *Mp) {\n  Mat &M = *Mp;\n\n  // Gauss Elimination.\n  for (int i = 0; i < 10; ++i) {\n    M.row(i) /= M(i, i);\n    for (int j = i + 1; j < 10; ++j) {\n      M.row(j) = M.row(j) / M(j, i) - M.row(i);\n    }\n  }\n\n  // Backsubstitution.\n  for (int i = 9; i >= 0; --i) {\n    for (int j = 0; j < i; ++j) {\n      M.row(j) = M.row(j) - M(j, i) * M.row(i);\n    }\n  }\n}\n\nvoid FivePointsRelativePose(const Mat2X &x1,\n                            const Mat2X &x2,\n                            vector<Mat3> *Es) {\n  // Step 1: Nullspace exrtraction.\n  Mat E_basis = FivePointsNullspaceBasis(x1, x2);\n\n  // Step 2: Constraint expansion.\n  Mat M = FivePointsPolynomialConstraints(E_basis);\n\n  // Step 3: Gauss-Jordan elimination.\n  FivePointsGaussJordan(&M);\n\n  // For the next steps, follow the matlab code given in Stewenius et al [1].\n\n  // Build the action matrix.\n  Mat B = M.topRightCorner<10, 10>();\n  Mat At = Mat::Zero(10, 10);\n  At.row(0) = -B.row(0);\n  At.row(1) = -B.row(1);\n  At.row(2) = -B.row(2);\n  At.row(3) = -B.row(4);\n  At.row(4) = -B.row(5);\n  At.row(5) = -B.row(7);\n  At(6, 0) = 1;\n  At(7, 1) = 1;\n  At(8, 3) = 1;\n  At(9, 6) = 1;\n\n  // Compute the solutions from action matrix's eigenvectors.\n  Eigen::EigenSolver<Mat> es(At);\n  typedef Eigen::EigenSolver<Mat>::EigenvectorsType Matc;\n  Matc V = es.eigenvectors();\n  Matc solutions(4, 10);\n  solutions.row(0) = V.row(6).array() / V.row(9).array();\n  solutions.row(1) = V.row(7).array() / V.row(9).array();\n  solutions.row(2) = V.row(8).array() / V.row(9).array();\n  solutions.row(3).setOnes();\n\n  // Get the ten candidate E matrices in vector form.\n  Matc Evec = E_basis * solutions;\n\n  // Build the essential matrices for the real solutions.\n  Es->reserve(10);\n  for (int s = 0; s < 10; ++s) {\n    Evec.col(s) /= Evec.col(s).norm();\n    bool is_real = true;\n    for (int i = 0; i < 9; ++i) {\n      if (Evec(i, s).imag() != 0) {\n        is_real = false;\n        break;\n      }\n    }\n    if (is_real) {\n      Mat3 E;\n      for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n          E(i, j) = Evec(3 * i + j, s).real();\n        }\n      }\n      Es->push_back(E);\n    }\n  }\n}\n\n}  // namespace libmv\n\n", "meta": {"hexsha": "dbaae5e4cfd8ca7c9950e4b6654e3bf69475cc61", "size": 8083, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libmv/multiview/five_point.cc", "max_stars_repo_name": "paulinus/libmv", "max_stars_repo_head_hexsha": "6656bde5aea4c715695fa98fca6e2b3417e82d76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-14T17:48:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-14T17:48:24.000Z", "max_issues_repo_path": "src/libmv/multiview/five_point.cc", "max_issues_repo_name": "rgkoo/libmv-blender", "max_issues_repo_head_hexsha": "cdf65edbb80d8904e2df9a20116d02546df93a81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libmv/multiview/five_point.cc", "max_forks_repo_name": "rgkoo/libmv-blender", "max_forks_repo_head_hexsha": "cdf65edbb80d8904e2df9a20116d02546df93a81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-05-29T21:58:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-17T15:52:18.000Z", "avg_line_length": 31.9486166008, "max_line_length": 79, "alphanum_fraction": 0.5436100458, "num_tokens": 2969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5393036880686435}}
{"text": "#ifndef sphere_hpp\n#define sphere_hpp\n\n#include <three-dim-util/opengl2/primitives/abstract-primitive.hpp>\n#include <Eigen/Core>\n\nnamespace threedimutil\n{\n    class Sphere : public AbstractPrimitive\n    {\n    public:\n        static void Initialize(int latitude_resolution = 20, int longitude_resolution = 30)\n        {\n            Sphere::GetInstance().latitude_resolution()  = latitude_resolution;\n            Sphere::GetInstance().longitude_resolution() = longitude_resolution;\n            Sphere::GetInstance().InitializeInternal();\n        }\n        \n        static void Draw()\n        {\n            Sphere::GetInstance().DrawInternal();\n        }\n        \n        static Sphere& GetInstance()\n        {\n            static Sphere sphere;\n            return sphere;\n        }\n        \n        int latitude_resolution() const { return latitude_resolution_; }\n        int& latitude_resolution() { return latitude_resolution_; }\n        int longitude_resolution() const { return longitude_resolution_; }\n        int& longitude_resolution() { return longitude_resolution_; }\n        \n    private:\n        void CreateVertexData()\n        {\n            constexpr double pi = M_PI;\n            \n            vertices_.resize(3, latitude_resolution_ * longitude_resolution_ * 6);\n            for (int i = 0; i < longitude_resolution_; ++ i)\n            {\n                const double theta_xy_1 = 2.0 * static_cast<double>(i + 0) * pi / static_cast<double>(longitude_resolution_);\n                const double theta_xy_2 = 2.0 * static_cast<double>(i + 1) * pi / static_cast<double>(longitude_resolution_);\n                const double x_1        = std::cos(theta_xy_1);\n                const double x_2        = std::cos(theta_xy_2);\n                const double y_1        = std::sin(theta_xy_1);\n                const double y_2        = std::sin(theta_xy_2);\n                \n                for (int j = 0; j < latitude_resolution_; ++ j)\n                {\n                    const double theta_z_1 = static_cast<double>(j + 0) * pi / static_cast<double>(latitude_resolution_);\n                    const double theta_z_2 = static_cast<double>(j + 1) * pi / static_cast<double>(latitude_resolution_);\n                    const double cos_1 = std::cos(theta_z_1);\n                    const double cos_2 = std::cos(theta_z_2);\n                    const double sin_1 = std::sin(theta_z_1);\n                    const double sin_2 = std::sin(theta_z_2);\n                    \n                    const int offset = i * latitude_resolution_ * 6 + j * 6;\n                    \n                    vertices_.col(offset + 0) = Eigen::Vector3d(sin_2 * x_1, sin_2 * y_1, cos_2);\n                    vertices_.col(offset + 1) = Eigen::Vector3d(sin_2 * x_2, sin_2 * y_2, cos_2);\n                    vertices_.col(offset + 2) = Eigen::Vector3d(sin_1 * x_2, sin_1 * y_2, cos_1);\n                    vertices_.col(offset + 3) = Eigen::Vector3d(sin_2 * x_1, sin_2 * y_1, cos_2);\n                    vertices_.col(offset + 4) = Eigen::Vector3d(sin_1 * x_2, sin_1 * y_2, cos_1);\n                    vertices_.col(offset + 5) = Eigen::Vector3d(sin_1 * x_1, sin_1 * y_1, cos_1);\n                }\n            }\n            normals_ = vertices_;\n        }\n        \n        int latitude_resolution_  = 20;\n        int longitude_resolution_ = 30;\n    };\n}\n\n#endif /* sphere_hpp */\n", "meta": {"hexsha": "e9e43f0e7e33c222ade75ba19f3e53eda58a9d40", "size": 3354, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/three-dim-util/opengl2/primitives/sphere.hpp", "max_stars_repo_name": "yuki-koyama/3d-util", "max_stars_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-10-13T15:16:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T06:07:55.000Z", "max_issues_repo_path": "include/three-dim-util/opengl2/primitives/sphere.hpp", "max_issues_repo_name": "yuki-koyama/3d-util", "max_issues_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-05-14T00:34:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-20T13:50:42.000Z", "max_forks_repo_path": "include/three-dim-util/opengl2/primitives/sphere.hpp", "max_forks_repo_name": "yuki-koyama/3d-util", "max_forks_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T07:36:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T19:42:33.000Z", "avg_line_length": 43.0, "max_line_length": 125, "alphanum_fraction": 0.5524746571, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6406358548398979, "lm_q1q2_score": 0.5393036880686434}}
{"text": "#include <aikido/common/PseudoInverse.hpp>\n\n#include <iostream>\n#include <limits>\n#include <memory>\n#include <Eigen/Dense>\n\nnamespace aikido {\nnamespace common {\n\n//==============================================================================\nEigen::MatrixXd pseudoinverse(const Eigen::MatrixXd& mat, double eps)\n{\n  if (mat.rows() == mat.cols() && mat.determinant() > eps)\n    return mat.inverse();\n\n  else\n  {\n    if (mat.cols() == 1)\n    {\n      if (mat.isApproxToConstant(0))\n      {\n        return Eigen::VectorXd::Zero(mat.rows());\n      }\n\n      return mat.transpose() / (pow(mat.norm(), 2));\n    }\n\n    /// Use SVD decomposition.\n    Eigen::JacobiSVD<Eigen::MatrixXd> jacSVD(\n        mat, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::MatrixXd U = jacSVD.matrixU();\n    Eigen::MatrixXd V = jacSVD.matrixV();\n    Eigen::VectorXd S = jacSVD.singularValues();\n\n    Eigen::MatrixXd S_inv(Eigen::MatrixXd::Zero(mat.cols(), mat.rows()));\n\n    for (int i = 0; i < S.rows(); i++)\n    {\n      if (S(i) > eps)\n      {\n        S_inv(i, i) = 1.0 / S(i);\n      }\n      else\n      {\n        S_inv(i, i) = 0;\n      }\n    }\n\n    return V * S_inv * U.transpose();\n  }\n}\n\n} // namespace common\n} // namespace aikido\n", "meta": {"hexsha": "1f33f164db69293759ce86c543b23ad9a0a92941", "size": 1216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common/PseudoInverse.cpp", "max_stars_repo_name": "usc-csci-545/aikido", "max_stars_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "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/PseudoInverse.cpp", "max_issues_repo_name": "usc-csci-545/aikido", "max_issues_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/PseudoInverse.cpp", "max_forks_repo_name": "usc-csci-545/aikido", "max_forks_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "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.7142857143, "max_line_length": 80, "alphanum_fraction": 0.5328947368, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5393036772082467}}
{"text": "/*=============================================================================\nCopyright 2020 Syed Ali Hasan <alihasan9922@gmail.com>\n\nDistributed under the Boost Software License, Version 1.0. (See accompanying\nfile License.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n\n#ifndef BOOST_ASTRONOMY_UTILITY_HPP\n#define BOOST_ASTRONOMY_UTILITY_HPP\n\n#include <iostream>\n#include <utility>\n#include <cmath>\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n//Angle\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/angle/degrees.hpp>\n#include <boost/units/systems/si/plane_angle.hpp>\n#include <boost/units/systems/si/dimensionless.hpp>\n#include <boost/units/physical_dimensions/plane_angle.hpp>\n\n//Time\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#include <boost/astronomy/coordinate/coord_sys/coord_sys.hpp>\n\nconstexpr long double PI = 3.141592653589793238462643383279502884L;\n\nusing namespace std;\nnamespace bu = boost::units;\nnamespace bud = boost::units::degree;\nusing namespace boost::numeric::ublas;\nnamespace bnu = boost::numeric::ublas;\n\nusing namespace boost::gregorian;\n\nnamespace boost { namespace astronomy { namespace coordinate {\n\n// Phi \u03c6 is the geographical latitude\n// ST is the Local Sidereal Time\n// \u03b5 is the obliquity of the ecliptic.\n\ntemplate\n    <\n        typename CoordinateType = double,\n        typename Angle = bu::quantity<bu::si::plane_angle, CoordinateType>,\n        typename ElementType = double\n    >\nstruct column_vector\n{\n public:\n  matrix<ElementType> vec = matrix<ElementType>(3, 1);\n\n  column_vector() {}\n\n  column_vector(Angle u, Angle v){\n    double _u = static_cast<bu::quantity<bu::si::plane_angle>>(u).value();\n    double _v = static_cast<bu::quantity<bu::si::plane_angle>>(v).value();\n\n    vec(0,0) = std::cos(_u) * std::cos(_v);\n    vec(1,0) = std::sin(_u) * std::cos(_v);\n    vec(2,0) = std::sin(_v);\n  }\n\n  matrix<ElementType> get(){\n    return vec;\n  }\n\n  std::string to_string(){\n    return \"Column Vector\";\n  }\n};\n\ntemplate\n    <\n        typename CoordinateType = double,\n        typename Angle = bu::quantity<bu::si::plane_angle, CoordinateType>,\n        typename ElementType = double\n    >\nstruct ha_dec_horizon\n{\n public:\n  matrix<ElementType> conv = matrix<ElementType>(3, 3);\n\n  ha_dec_horizon() {}\n\n  ha_dec_horizon(Angle phi){\n    double _phi = static_cast<bu::quantity<bu::si::plane_angle>>(phi).value();\n\n    conv(0,0) = -std::sin(_phi);\n    conv(0,1) = 0;\n    conv(0,2) = std::cos(_phi);\n    conv(1,0) = 0;\n    conv(1,1) = -1;\n    conv(1,2) = 0;\n    conv(2,0) = std::cos(_phi);\n    conv(2,1) = 0;\n    conv(2,2) = std::sin(_phi);\n  }\n\n  matrix<ElementType> get(){\n    return conv;\n  }\n\n  std::string to_string(){\n    return \"Equatorial Coordinate Hour Angle to and from Horizon\";\n  }\n};\n\ntemplate\n    <\n        typename CoordinateType = double,\n        typename Angle = bu::quantity<bu::si::plane_angle, CoordinateType>,\n        typename ElementType = double\n    >\nstruct ha_dec_ra_dec\n{\n public:\n  matrix<ElementType> conv = matrix<ElementType>(3, 3);\n\n  ha_dec_ra_dec() {}\n\n  ha_dec_ra_dec(Angle ST){\n    double _ST = static_cast<bu::quantity<bu::si::plane_angle>>(ST).value();\n\n    conv(0,0) = std::cos(_ST);\n    conv(0,1) = std::sin(_ST);\n    conv(0,2) = 0;\n    conv(1,0) = std::sin(_ST);\n    conv(1,1) = -std::cos(_ST);\n    conv(1,2) = 0;\n    conv(2,0) = 0;\n    conv(2,1) = 0;\n    conv(2,2) = 1;\n  }\n\n  matrix<ElementType> get(){\n    return conv;\n  }\n\n  std::string to_string(){\n    return \"Equatorial Coordinate Hour Angle to and from Equatorial Coordinate Right Ascension\";\n  }\n};\n\ntemplate\n    <\n        typename CoordinateType = double,\n        typename Angle = bu::quantity<bu::si::plane_angle, CoordinateType>,\n        typename ElementType = double\n    >\nstruct ecliptic_to_ra_dec\n{\n public:\n  matrix<ElementType> conv = matrix<ElementType>(3, 3);\n\n  ecliptic_to_ra_dec() {}\n\n  ecliptic_to_ra_dec(Angle obliquity){\n    double _obliquity = static_cast<bu::quantity<bu::si::plane_angle>>(obliquity).value();\n\n    conv(0,0) = 1;\n    conv(0,1) = 0;\n    conv(0,2) = 0;\n    conv(1,0) = 0;\n    conv(1,1) = std::cos(_obliquity);\n    conv(1,2) = -std::sin(_obliquity);\n    conv(2,0) = 0;\n    conv(2,1) = std::sin(_obliquity);\n    conv(2,2) = std::cos(_obliquity);\n  }\n\n  matrix<ElementType> get(){\n    return conv;\n  }\n\n  std::string to_string(){\n    return \"Ecliptic to Equatorial Coordinate Right Ascension\";\n  }\n};\n\ntemplate\n    <\n        typename CoordinateType = double,\n        typename Angle = bu::quantity<bu::si::plane_angle, CoordinateType>,\n        typename ElementType = double\n    >\nstruct ra_dec_to_ecliptic\n{\n public:\n  matrix<ElementType> conv = matrix<ElementType>(3, 3);\n\n  ra_dec_to_ecliptic() {}\n\n  ra_dec_to_ecliptic(Angle obliquity){\n    double _obliquity = static_cast<bu::quantity<bu::si::plane_angle>>(obliquity).value();\n\n    conv(0,0) = 1;\n    conv(0,1) = 0;\n    conv(0,2) = 0;\n    conv(1,0) = 0;\n    conv(1,1) = std::cos(_obliquity);\n    conv(1,2) = std::sin(_obliquity);\n    conv(2,0) = 0;\n    conv(2,1) = -std::sin(_obliquity);\n    conv(2,2) = std::cos(_obliquity);\n  }\n\n  matrix<ElementType> get(){\n    return conv;\n  }\n\n  std::string to_string(){\n    return \"Equatorial Coordinate Right Ascension to Ecliptic\";\n  }\n};\n\ntemplate\n    <typename ElementType = double>\nstruct galactic_to_ra_dec\n{\n public:\n  matrix<ElementType> conv = matrix<ElementType>(3, 3);\n\n  galactic_to_ra_dec(){\n    conv(0,0) = -0.0669887;\n    conv(0,1) = 0.8727558;\n    conv(0,2) = -0.4835389;\n    conv(1,0) = -0.4927285;\n    conv(1,1) = -0.4503470;\n    conv(1,2) = -0.7445846;\n    conv(2,0) = -0.8676008;\n    conv(2,1) = 0.1883746;\n    conv(2,2) = 0.4601998;\n  }\n\n  matrix<ElementType> get(){\n    return conv;\n  }\n\n  std::string to_string(){\n    return \"Galactic to Equatorial Coordinate Right Ascension\";\n  }\n};\n\ntemplate\n    <typename ElementType = double>\nstruct ra_dec_to_galactic\n{\n public:\n  matrix<ElementType> conv = matrix<ElementType>(3, 3);\n\n  ra_dec_to_galactic()\n  {\n    conv(0,0) = -0.0669887;\n    conv(0,1) = -0.8727558;\n    conv(0,2) = -0.4835389;\n    conv(1,0) = 0.4927285;\n    conv(1,1) = -0.4503470;\n    conv(1,2) = 0.7445846;\n    conv(2,0) = -0.8676008;\n    conv(2,1) = -0.1883746;\n    conv(2,2) = 0.4601998;\n  }\n\n  matrix<ElementType> get()\n  {\n    return conv;\n  }\n\n  std::string to_string()\n  {\n    return \"Equatorial Coordinate Right Ascension to Galactic\";\n  }\n\n};\n\ntypedef bu::quantity<bu::si::plane_angle, double> angle_radian;\n\nstruct extract_coordinates{\n private:\n  double theta = 0;\n  double phi = 0;\n\n public:\n  extract_coordinates(){}\n\n  explicit extract_coordinates(matrix<double> column_vector)\n  {\n    double m = column_vector(0,0);\n    double n = column_vector(1,0);\n    double p = column_vector(2,0);\n\n    theta = atan2(n,m);\n    phi = asin(p);\n  }\n\n  pair<angle_radian,angle_radian> get_coordinates() const{\n    return make_pair(theta * bu::si::radian,phi * bu::si::radian);\n  }\n};\n\nstruct obliquity_of_ecliptic{\n private:\n  angle_radian e = 0.0 * bu::si::radian;\n\n public:\n  obliquity_of_ecliptic(date d)\n  {\n    double julian_date = d.julian_day();\n\n    double modified_julian_date = julian_date - 2451545.0;\n\n    double julian_centuries = modified_julian_date / 36525.0;\n\n    double e_degrees =  23.439292 - (46.815 * julian_centuries + (0.0006 - 0.00181 * julian_centuries) * julian_centuries * julian_centuries) / 3600.0;\n\n    e = (e_degrees * PI / 180.0) * bu::si::radian;\n  }\n\n  angle_radian get(){\n    return e;\n  }\n};\n\n}}}\n\n#endif  // BOOST_ASTRONOMY_UTILITY_HPP\n", "meta": {"hexsha": "685066c8dbde9d49c2563b2b2d8fbc6e8890de3c", "size": 7667, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/coordinate/utility/utility.hpp", "max_stars_repo_name": "nitink25/astronomy", "max_stars_repo_head_hexsha": "0a1d137171b08d1014d4ff138b2a40a146f4f39b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T13:53:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T20:37:18.000Z", "max_issues_repo_path": "include/boost/astronomy/coordinate/utility/utility.hpp", "max_issues_repo_name": "Zyro9922/astronomy", "max_issues_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 96.0, "max_issues_repo_issues_event_min_datetime": "2019-05-28T17:46:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-09T07:59:17.000Z", "max_forks_repo_path": "include/boost/astronomy/coordinate/utility/utility.hpp", "max_forks_repo_name": "Zyro9922/astronomy", "max_forks_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T21:09:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T06:24:39.000Z", "avg_line_length": 23.024024024, "max_line_length": 151, "alphanum_fraction": 0.638320073, "num_tokens": 2389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5393012403182857}}
{"text": "//savageTestMain.cpp\n\n#include \"savageFunctions.h\"\n#include <iostream>\n#include <cmath>\n#include <cstdlib>\n#include <string>\n#include <Eigen/Dense>\n\n\nint main()\n{\n\n\t// Eigen::Matrix2d m;\n\t// \tm(0,0) = 1;\n\t// \tm(0,1) = 2;\n\t// \tm(1,0) = 3;\n\t// \tm(1,1) = 4;\n\n\t// std::cout << m << std::endl;\n\n\t// Eigen::Vector3d testVec;\n\t// \ttestVec << 1,2,3;\n\t// \t// testVec(1) = 2;\n\t// \t// testVec(2) = 3;\n\n\t// std::cout << testVec << std::endl;\n\n\n\t// //instance of the class\n\tsavageFunctions savageObject;\n\t// std::cout << savageObject.skew(testVec) << std::endl;\n\n\tEigen::Matrix3d dcm;\n\tdcm << 1, 0, 0, 0, 1, 0, 0, 0, 1;\n\n\tEigen::Vector3d acc;\n\tacc << 1.31, -2.5, 4.37;\n\n\tEigen::Vector3d omega;\n\tomega << 0.23,0.42,-0.11;\n\n\tdouble t = .54;\n\n\tEigen::VectorXd state(9);\n\tstate << 0,0,0,0,0,0,0,0,0;\n\n\tstd::cout << savageObject.stateIntegrate(omega, acc, state, dcm, t) << std::endl;\n\n\n\n\n\n\n\n\n\t\n\treturn 0;\n}", "meta": {"hexsha": "8da370f5c87f20d68d7adc7817a7eb582376d526", "size": 889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "savageTestMain.cpp", "max_stars_repo_name": "LyonFoster/GNC-Homework", "max_stars_repo_head_hexsha": "445ce0369785b6731555602eac1e0f42cad342eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "savageTestMain.cpp", "max_issues_repo_name": "LyonFoster/GNC-Homework", "max_issues_repo_head_hexsha": "445ce0369785b6731555602eac1e0f42cad342eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "savageTestMain.cpp", "max_forks_repo_name": "LyonFoster/GNC-Homework", "max_forks_repo_head_hexsha": "445ce0369785b6731555602eac1e0f42cad342eb", "max_forks_repo_licenses": ["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.0677966102, "max_line_length": 82, "alphanum_fraction": 0.570303712, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.5393012295629557}}
{"text": "#include <gmock/gmock.h>\n#include <Eigen/Dense>\n#include <chrono>\n\n\nclass eigen_runtime_test: public testing::Test\n{\n  public:\n};\n\ntemplate<int dim=3>\nvoid test_rt(int const num_iterations)\n{\n  Eigen::MatrixXd M1 =  Eigen::MatrixXd::Random(dim,dim);\n  Eigen::Matrix<double, dim, dim> M_stat = Eigen::Matrix<double, dim, dim>::Random();\n\n  typedef std::chrono::high_resolution_clock clk_t;\n  typedef clk_t::time_point tp_t;\n  {\n    tp_t t1 = clk_t::now();\n\n    for(int i=0; i < num_iterations; i++)\n    {\n      M1 = M1*M1;\n    }\n    tp_t t2 = clk_t::now();\n\n    auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();\n    std::cout << \"[\"<<dim << \"x\"<< dim << \"] Dynamic * Dynamic avg: \" << duration/(1.0*num_iterations) << \" us\" << std::endl;\n  }\n\n\n  {\n    tp_t t1 = clk_t::now();\n\n    for(int i=0; i < num_iterations; i++)\n    {\n      M_stat = M_stat*M_stat;\n    }\n    tp_t t2 = clk_t::now();\n\n    auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();\n    std::cout << \"[\"<<dim << \"x\"<< dim << \"] Static * Static avg: \" << duration/(1.0*num_iterations) << \" us\" << std::endl;\n  }\n\n  {\n    tp_t t1 = clk_t::now();\n\n    for(int i=0; i < num_iterations; i++)\n    {\n      M_stat = M1*M_stat;\n    }\n    tp_t t2 = clk_t::now();\n\n    auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();\n    std::cout << \"[\"<<dim << \"x\"<< dim << \"] Dynamic * Static avg: \" << duration/(1.0*num_iterations) << \" us\" << std::endl;\n  }\n}\n\nTEST_F(eigen_runtime_test, time_measurement_3)\n{\n  test_rt<3>(100000);\n}\n\nTEST_F(eigen_runtime_test, time_measurement_20)\n{\n  test_rt<20>(10000);\n}\n\nTEST_F(eigen_runtime_test, time_measurement_100)\n{\n  test_rt<100>(100);\n}\n", "meta": {"hexsha": "7e85bd43ab3831a1120c1566b7467c753df56e57", "size": 1743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/tests/mars-test/eigen_runtime_test.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/tests/mars-test/eigen_runtime_test.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/tests/mars-test/eigen_runtime_test.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": 23.5540540541, "max_line_length": 125, "alphanum_fraction": 0.604130809, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.5393012281340286}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <type_traits>\n#include <algorithm>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/hermitian.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/banded.hpp>\n#include <boost/numeric/bindings/ublas/hermitian.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include <boost/numeric/bindings/lapack/driver.hpp>\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\nnamespace lapack=boost::numeric::bindings::lapack;\n\nint main(int argc, char *argv[]) {\n  typedef ublas::vector<double> vector;\n  typedef ublas::matrix<double, ublas::column_major> matrix;\n  typedef ublas::banded_matrix<double, ublas::column_major> banded_matrix;\n  typedef typename std::make_signed<vector::size_type>::type size_type;\n\n  rand_normal<double>::reset();\n  size_type n=128, k=8;\n  banded_matrix A(n, n, 0, k);\n  for (size_type j=0; j<n; ++j) {\n    for (size_type i=std::max(j-k, size_type(0)); i<=j; ++i)\n      A(i, j)=rand_normal<double>::get();\n  }\n  {\n    vector lambda(n);\n    banded_matrix A_bak(A);\n    matrix vr(n ,n);\n    ublas::hermitian_adaptor<banded_matrix, ublas::upper> B(A);\n    int info=lapack::sbev('V', B, lambda, vr);\n    ublas::hermitian_adaptor<banded_matrix, ublas::upper> B_bak(A_bak);\n    if (info==0) {\n      for (int i=0; i<n; ++i) {\n  \t// res <- A*vr(i) - lambda(i)*vr(i)\n  \tublas::matrix_column<matrix> v(vr, i);\n  \tvector res(ublas::prod(B_bak, v)-lambda(i)*v);\n  \tstd::cout << \"norm of residual (right eigen vector \" << i\n  \t\t  << \" ): \" << blas::nrm2(res) << '\\n';\n      }\n    } else\n      if (info>0)\n  \tstd::cout << \"unable to compute all eigen values\\n\";\n      else \n  \tstd::cout << \"illegal arguments\\n\";\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "a8b2fe711193a9964fde7d8f8d56e25f9c9a11d4", "size": 2109, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/lapack/sbev.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/lapack/sbev.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/lapack/sbev.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.15, "max_line_length": 74, "alphanum_fraction": 0.6894262684, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5393012241852906}}
{"text": "#include <ceres/ceres.h>\n#include <Eigen/Core>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n#include <maplab-common/pose_types.h>\n#include <maplab-common/quaternion-math.h>\n#include <maplab-common/test/testing-entrypoint.h>\n#include <maplab-common/test/testing-predicates.h>\n\n#include \"ceres-error-terms/parameterization/quaternion-param-jpl.h\"\n#include \"ceres-error-terms/test/parameterization-numerical-diff.h\"\n\nTEST(JplQuaternionParameterization, JacobianCorrect) {\n  typedef Eigen::Matrix<double, 4, 3, Eigen::RowMajor> JacobianType;\n  Eigen::Quaterniond q_AB(1.0, 1.0, 0.0, 1.0);\n  q_AB.normalize();\n\n  ceres_error_terms::JplQuaternionParameterization parameterization;\n  JacobianType dq_dtheta;\n  ASSERT_TRUE(\n      parameterization.ComputeJacobian(q_AB.coeffs().data(), dq_dtheta.data()));\n\n  JacobianType dq_dtheta_numeric;\n  const bool success =\n      ceres_error_terms::EvaluateNumericalJacobianOfParameterization<\n          ceres_error_terms::JplQuaternionParameterization, 4, 3>(\n          parameterization, q_AB.coeffs(), &dq_dtheta_numeric);\n  ASSERT_TRUE(success);\n\n  EXPECT_NEAR_EIGEN(dq_dtheta, dq_dtheta_numeric, 1e-10);\n}\n\nTEST(JplYawQuaternionParameterization, Plus) {\n  Eigen::Quaterniond q_AB(1.0, 1.0, 0.0, 1.0);\n  q_AB.normalize();\n  const Eigen::Vector3d rpy_init =\n      common::getRollPitchYawFromQuaternionJpl(q_AB);\n\n  double delta_total_rad = 0.0;\n  ceres_error_terms::JplYawQuaternionParameterization yaw_param;\n  for (double delta : std::vector<double>{-0.5, 0.0, 0.5, 1.0}) {\n    Eigen::Quaterniond q_AB_plus_delta;\n    ASSERT_TRUE(yaw_param.Plus(q_AB.coeffs().data(), &delta,\n                               q_AB_plus_delta.coeffs().data()));\n    delta_total_rad += delta;\n    q_AB = q_AB_plus_delta;\n\n    const Eigen::Vector3d rpy =\n        common::getRollPitchYawFromQuaternionJpl(q_AB_plus_delta);\n    EXPECT_NEAR(rpy_init[0], rpy[0], 1e-6);\n    EXPECT_NEAR(rpy_init[1], rpy[1], 1e-6);\n\n    if (delta_total_rad == 0.0) {\n      // We are at the same yaw as initially.\n      EXPECT_NEAR(rpy_init[2], rpy[2], 1e-6);\n    } else {\n      EXPECT_NE(rpy_init[2], rpy[2]);\n    }\n  }\n}\n\nTEST(JplYawQuaternionParameterization, JacobianCorrect) {\n  typedef Eigen::Matrix<double, 4, 1> JacobianType;\n  Eigen::Quaterniond q_AB(1.0, 1.0, 0.0, 1.0);\n  q_AB.normalize();\n\n  ceres_error_terms::JplYawQuaternionParameterization parameterization;\n  JacobianType dq_dtheta;\n  ASSERT_TRUE(\n      parameterization.ComputeJacobian(q_AB.coeffs().data(), dq_dtheta.data()));\n\n  JacobianType dq_dtheta_numeric;\n  const bool success =\n      ceres_error_terms::EvaluateNumericalJacobianOfParameterization<\n          ceres_error_terms::JplYawQuaternionParameterization, 4, 1>(\n          parameterization, q_AB.coeffs(), &dq_dtheta_numeric);\n  ASSERT_TRUE(success);\n\n  EXPECT_NEAR_EIGEN(dq_dtheta, dq_dtheta_numeric, 1e-10);\n}\n\nTEST(JplRollPitchQuaternionParameterization, JacobianCorrect) {\n  typedef Eigen::Matrix<double, 4, 2, Eigen::RowMajor> JacobianType;\n  Eigen::Quaterniond q_IM(1.0, 1.0, 5.0, 0.0);\n  q_IM.normalize();\n\n  Eigen::Quaterniond q_GM(1.0, 5.0, 0.0, 2.0);\n  q_GM.normalize();\n\n  ceres_error_terms::JplRollPitchQuaternionParameterization parameterization(\n      q_GM.coeffs());\n  JacobianType dq_dtheta;\n  ASSERT_TRUE(\n      parameterization.ComputeJacobian(q_IM.coeffs().data(), dq_dtheta.data()));\n\n  JacobianType dq_dtheta_numeric;\n  const bool success =\n      ceres_error_terms::EvaluateNumericalJacobianOfParameterization<\n          ceres_error_terms::JplRollPitchQuaternionParameterization, 4, 2>(\n          parameterization, q_IM.coeffs(), &dq_dtheta_numeric);\n  ASSERT_TRUE(success);\n\n  EXPECT_NEAR_EIGEN(dq_dtheta, dq_dtheta_numeric, 1e-10);\n}\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "a7411a48514e502251f23556060e43f6ac72079c", "size": 3711, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/ceres-error-terms/test/test_quaternion_parameterization_test.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": "algorithms/ceres-error-terms/test/test_quaternion_parameterization_test.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": "algorithms/ceres-error-terms/test/test_quaternion_parameterization_test.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": 34.6822429907, "max_line_length": 80, "alphanum_fraction": 0.7334950148, "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5393012227563636}}
{"text": "#include \"deadreckoning.h\"\n\n#include \"math.h\"\n#include \"geometry.h\"\n#include \"nonmoveable.h\"\n#include \"occupancy_grid.h\" \n#include \"occupancy_grid.inl\" \n#include \"robot_configuration.h\"\n\n#include <vector>\n#include <chrono>\n#include <boost/algorithm/cxx11/all_of.hpp>\n\nCDeadReckoningMapping::CDeadReckoningMapping()\n{}\n        \nvoid CDeadReckoningMapping::receivedSensorData(SOdometryData const& odom) {\n    auto const posePrev = m_vecpose.empty() \n        ? rbt::pose<double>(rbt::point<double>::zero(), 0)\n        : m_vecpose.back();\n    \n    auto const poseNew = UpdatePose(posePrev, odom);\n\n    m_vecpose.emplace_back(poseNew);\n}\n\n// void CDeadReckoningMapping::receivedSensorData(SScanLine const& scanline) {\n//     m_occgrid.update(m_vecpose.back(), rbt::rad(data.m_nAngle), data.m_nDistance);    \n// }\n\ncv::Mat const& CDeadReckoningMapping::getMap() {\n    return m_occgrid.ObstacleMap();\n}\n", "meta": {"hexsha": "8e43d323effb048823b7be2d77275e4cb04e9642", "size": 896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "raspberry/deadreckoning.cpp", "max_stars_repo_name": "stheophil/MappingRover2", "max_stars_repo_head_hexsha": "25d968a4f27016a3eb61b70e48d3f137887d440c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-11-12T11:12:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T02:15:23.000Z", "max_issues_repo_path": "raspberry/deadreckoning.cpp", "max_issues_repo_name": "stheophil/MappingRover2", "max_issues_repo_head_hexsha": "25d968a4f27016a3eb61b70e48d3f137887d440c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "raspberry/deadreckoning.cpp", "max_forks_repo_name": "stheophil/MappingRover2", "max_forks_repo_head_hexsha": "25d968a4f27016a3eb61b70e48d3f137887d440c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-11-12T03:10:28.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-02T21:38:21.000Z", "avg_line_length": 26.3529411765, "max_line_length": 89, "alphanum_fraction": 0.7142857143, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5391215575207321}}
{"text": "//=======================================================================\n// Copyright 2007 Aaron Windsor\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#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <vector>\n\n#include <boost/graph/planar_canonical_ordering.hpp>\n#include <boost/graph/is_straight_line_drawing.hpp>\n#include <boost/graph/chrobak_payne_drawing.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n\n\n\nusing namespace boost;\n\n//a class to hold the coordinates of the straight line embedding\nstruct coord_t\n{\n  std::size_t x;\n  std::size_t y;\n};\n\n\nint main(int argc, char** argv)\n{\n  typedef adjacency_list\n    < vecS,\n      vecS,\n      undirectedS,\n      property<vertex_index_t, int>\n    > graph;\n\n\n\n  //Define the storage type for the planar embedding\n  typedef std::vector< std::vector< graph_traits<graph>::edge_descriptor > >\n    embedding_storage_t;\n  typedef boost::iterator_property_map\n    < embedding_storage_t::iterator,\n      property_map<graph, vertex_index_t>::type\n    >\n    embedding_t;\n\n\n\n  // Create the graph - a maximal planar graph on 7 vertices. The functions\n  // planar_canonical_ordering and chrobak_payne_straight_line_drawing both\n  // require a maximal planar graph. If you start with a graph that isn't\n  // maximal planar (or you're not sure), you can use the functions\n  // make_connected, make_biconnected_planar, and make_maximal planar in\n  // sequence to add a set of edges to any undirected planar graph to make\n  // it maximal planar.\n\n  graph g(7);\n  add_edge(0,1,g);\n  add_edge(1,2,g);\n  add_edge(2,3,g);\n  add_edge(3,0,g);\n  add_edge(3,4,g);\n  add_edge(4,5,g);\n  add_edge(5,6,g);\n  add_edge(6,3,g);\n  add_edge(0,4,g);\n  add_edge(1,3,g);\n  add_edge(3,5,g);\n  add_edge(2,6,g);\n  add_edge(1,4,g);\n  add_edge(1,5,g);\n  add_edge(1,6,g);\n\n\n\n  // Create the planar embedding\n  embedding_storage_t embedding_storage(num_vertices(g));\n  embedding_t embedding(embedding_storage.begin(), get(vertex_index,g));\n\n  boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n                               boyer_myrvold_params::embedding = embedding\n                               );\n\n\n\n  // Find a canonical ordering\n  std::vector<graph_traits<graph>::vertex_descriptor> ordering;\n  planar_canonical_ordering(g, embedding, std::back_inserter(ordering));\n\n\n  //Set up a property map to hold the mapping from vertices to coord_t's\n  typedef std::vector< coord_t > straight_line_drawing_storage_t;\n  typedef boost::iterator_property_map\n    < straight_line_drawing_storage_t::iterator,\n      property_map<graph, vertex_index_t>::type\n    >\n    straight_line_drawing_t;\n\n  straight_line_drawing_storage_t straight_line_drawing_storage\n    (num_vertices(g));\n  straight_line_drawing_t straight_line_drawing\n    (straight_line_drawing_storage.begin(),\n     get(vertex_index,g)\n     );\n\n\n\n  // Compute the straight line drawing\n  chrobak_payne_straight_line_drawing(g,\n                                      embedding,\n                                      ordering.begin(),\n                                      ordering.end(),\n                                      straight_line_drawing\n                                      );\n\n\n\n  std::cout << \"The straight line drawing is: \" << std::endl;\n  graph_traits<graph>::vertex_iterator vi, vi_end;\n  for(boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n    {\n      coord_t coord(get(straight_line_drawing,*vi));\n      std::cout << *vi << \" -> (\" << coord.x << \", \" << coord.y << \")\"\n                << std::endl;\n    }\n\n  // Verify that the drawing is actually a plane drawing\n  if (is_straight_line_drawing(g, straight_line_drawing))\n    std::cout << \"Is a plane drawing.\" << std::endl;\n  else\n    std::cout << \"Is not a plane drawing.\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "7bfd5f20fc749242d53c059ae660ec9a350e3109", "size": 4098, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/straight_line_drawing.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/graph/example/straight_line_drawing.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/graph/example/straight_line_drawing.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 29.2714285714, "max_line_length": 76, "alphanum_fraction": 0.6473889702, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.5390777595268268}}
{"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    @ingroup group-ieee\n    This function object returns  \\f$x\\f$ multiplied by\n    by \\f$2^{n}\\f$\n\n\n    @par Header <boost/simd/function/ldexp.hpp>\n\n    @par Note\n\n     If @c n is not of integral type it is truncated:\n     `ldexp(x,n)` is similar to: `x*pow(2, trunc(n))`\n\n    @pre\n     The @ref cardinal_of and the size of elements value of the types\n     of @c x and @c n must be identical\n\n    @par Decorators\n\n     - pedantic_ By default @c ldexp does not take care of denormal or limiting values.\n       Use the @c pedantic_ decorator if these are to be properly computed.\n\n     - std_ give access to std::ldexp\n\n    @par Example:\n\n      @snippet ldexp.cpp ldexp\n\n    @par Possible output:\n\n      @snippet ldexp.txt ldexp\n\n  **/\n  Value0 ldexp(Value0 const& x, Value1 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": "b731cd77149d55ad75b666423fe0503eab880016", "size": 1456, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/ldexp.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/function/ldexp.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/function/ldexp.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": 24.6779661017, "max_line_length": 100, "alphanum_fraction": 0.5934065934, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5390777546421633}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// random::poisson::devroye::detail::crtp::crtp.hpp                        \t//\n//                                                                          //\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#ifndef BOOST_RANDOM_POISSON_EXT_DEVROYE_CRTP_CRTP_HPP_ER_2010\n#define BOOST_RANDOM_POISSON_EXT_DEVROYE_CRTP_CRTP_HPP_ER_2010\n#include <boost/range.hpp>\n#include <boost/math/special_functions/modf.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/exponential_distribution.hpp>\n\n#include <boost/random/poisson_ext/devroye/crtp/parameters.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace poisson{\nnamespace devroye{     \n\n    // Samples from the poisson distribution with an integer mean\n    //\n    // Source : The computer generation of poisson random variables. L. Devroye,\n    // Computing 26, Springer-Verlag, 1981\n    //\n    // Parameter     Description\n    // Step4         A class that models the concept by the same name\n    // Int           An integer type\n    // T             A float type\n    // P             An error handling policy\n    // IntT          A converter from Int to T\n    // TInt          A converter from T to Int\n\t//\n    // Requiremens\n    // Expression                       Description\n    // crtp<Step4,Int,T,P,IntT,TInt>    Public base of Step4 \n\t//\n    // Concept Step4:\n    // crtp<Step4,Int,T,P> is a public base, and\n    // Expression    Result type   Side effect\n    //  accept()     bool          if true, y is set to the value to be returned\n    //\n    // The numbers on the right are those of the lines of the Fortran listing \n    // given in the reference above.\n    template<typename Step4,typename Int,typename T,\n        typename P = boost::math::policies::policy<>,\n        typename IntT = boost::numeric::converter<T,Int>,\n        typename TInt = boost::numeric::converter<Int,T>\n    >\n    class crtp : public devroye::parameters<Int,T,P,IntT>\n    {\n        typedef devroye::parameters<Int,T,P,IntT> parameters_;\n        typedef IntT converter_;\n        typedef std::string str_;\n\n\t\tpublic:\n\n        typedef T input_type;\n        typedef Int result_type;\n\n        T mean() const { return converter_::convert(this->i_mean_); }\n        void reset() { }\n                        \n\t\tcrtp(){}\n        explicit crtp(const Int& i_mean)\n        \t:parameters_(i_mean),max_step1_cnt_(10)\n            {\n            \tBOOST_ASSERT(this->i_mean()>=0);\n            }\n\n        explicit crtp(const Int& i_mean,const Int& max_step1_cnt)\n        \t:parameters_(i_mean),max_step1_cnt_(max_step1_cnt)\n            {\n            \tBOOST_ASSERT(this->i_mean()>=0);\n            }\n        \n  \t\ttemplate<class U>\n  \t\tInt operator()(U& urng)const\n  \t\t{\n            this->step1_cnt_ = 0;\n\t\t\tInt result =  this->step1(urng);\t        \n            BOOST_ASSERT(result >= 0);\n            return result;\n        }\n\n        const Int& step1_cnt()const{ return this->step1_cnt_; } \n\t\t\n        // --- I/O --- //\n            \n        template<class CharT, class Traits>\n        friend std::basic_ostream<CharT,Traits>&\n        operator<<(\n            std::basic_ostream<CharT,Traits>& os, \n            const crtp& pd\n        )\n        {\n            os \t<< \"devroye(\"\n                << pd.i_mean()\n                << ','\n                << pd.u() \n                << ','\n                << pd.x() \n                << ','\n                << pd.i_y() \n                << ','\n                << pd.v() \n                << ','\n                << pd.step1_cnt() \n                << ')';\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, crtp& pd)\n        {\n            Int new_mean;\n            is\t>> std::ws\n                >> new_mean\n                >> std::ws\n                >> std::ws \t// u\n                >> std::ws\n                >> std::ws\t// x\n                >> std::ws\n                >> std::ws\t// y\n                >> std::ws\n                >> std::ws\t// v\n                >> std::ws\n                >> std::ws\t// step1_cnt\n                >> std::ws;\n            static_cast<Step4&>(pd) = Step4(new_mean);\n            return is;\n        }\n            \n        // ----------- //\n            \n        protected:\n\t\t\n\t\ttemplate<typename U>\n\t\tInt step1(U& urng)const\n        {\n            static const str_ name = \"devroy::crtp<%1%>::step1()\";\n\n            using namespace boost::math::policies;\n            if( ( this->step1_cnt_++ ) > this->max_step1_cnt() ){\n                 raise_evaluation_error( //<boost::uintmax_t>\n                    name.c_str(),\n                    \"step1_cnt_ exceeded limit = %1%\", \n                    this->max_step1_cnt(), P());\n            }\n            // line 10 : case mean = 0;\n            \n            this->u_ = urng();\t\t\t\t\t\t\t\t\t\t\t\t//13\n            if( this->u() > this->p1() ){ \n            \t// Reconciliation with Fortran listing :\n                // ptail = p2 + p3 = 1-p1. \n                // u' ~ 1-u. (u'<ptail) <=> (1-u<p2+p3) <=> (u > p1)\n            \treturn this->step3( urng );\n            }else{\n                return this->step2( urng );\n            }\t\n\t\t}\n\n\t\ttemplate<typename U>\n\t\tInt step2(U& urng)const\n        {\n        \tT z = this->random_z( urng ); \t\t\t\t\t\t\t        //15\n        \tthis->x_ = ( this->sd1() * z ) + parameters_::loc1();\n            if( \n                ( this->x() > this->delta() ) || ( this->x() < ( -this->m1() ) ) \n            )\n            { \n            \treturn this->step1( urng );\n            }else{\n                using namespace std;\n            \t// y is rounded away from zero\n                if( this->x() <= -parameters_::eps /*strictly negative*/)\n                {\n                    this->i_y_ = floor( this->x() );\n                }else{\n                    this->i_y_ = ceil( this->x() );\n                }\n                T e  = this->random_exp1(urng);\n                this->v_ = -( e + pow( z, 2 ) / parameters_::two ) + this->c1();\n                return this->step4( urng );\n            }\n        }\n\n\t\ttemplate<typename U>\n\t\tInt step3(U& urng)const\n        {\n        \n            // Reconciliation with Fortran listing :\n            // pbody = p3 = 1-(p1+p2) \n            // u' ~ 1-u. (u'<pbody) <=> (1-u<p3) <=> (u > p1+p2)\n        \tif( this->u() > this->p1() + this->p2() ){ \t\t\t\t\t\t\t\n            \tthis->i_y_ = this->i_mean(); \n                return this->i_y();\n            }else{\n                using namespace std;\n            \tT e1 = this->random_exp1( urng );\n            \tT e2 = this->random_exp1( urng );\n            \tthis->x_ = this->delta() + e1 / this->shape2();\t\t\t\t//51 \n            \tthis->i_y_ = TInt::convert( ceil( this->x() ) );\n            \tthis->v_ = - ( \n                \te2 + this->shape2() * ( parameters_::one + this->x() )\n                );\n            \treturn this->step4( urng );\n            }\n        }\n\n\t\ttemplate<typename U>\n\t\tInt step4(U& urng)const\n        {\n            const Step4& derived = static_cast<const Step4&>(*this);\t\t\n            if( derived.accept() ){\n            \treturn this->i_y();\n            }else{\n\t\t\t\treturn this->step1( urng );            \n            }\n\t\t}\n\n\t\ttemplate<typename U>\n\t\tT random_z(U& urng)const\n        {\n        \ttypedef boost::normal_distribution<T> d_;\n            static d_ d = d_( parameters_::zero, parameters_::one );\n            return d( urng );\n        }\n\n\t\ttemplate<typename U>\n\t\tT random_exp1(U& urng)const\n        {\n        \ttypedef boost::exponential_distribution<T> d_;\n            static d_ d = d_( parameters_::one );\n            return d( urng );\n        }\n\n\t\t// Parameter\n\t\tInt i_mean_;\n        \n        // These are quantities that vary throughout sampling\n\t\tmutable T\tu_;\n        mutable T \tx_;\n        mutable Int i_y_;\n        mutable T \tv_;\n        \n        // Implementation detail\n        mutable Int step1_cnt_;\n        mutable Int max_step1_cnt_;\n\n        const Int& \ti_mean()const{ return this->i_mean_; } \n        const T& \tu()const{ return this->u_; } \n        const T& \tx()const{ return this->x_; } \n        const Int& \ti_y()const{ return this->i_y_; } \n        const T& \tv()const{ return this->v_; } \n        const Int& \tmax_step1_cnt()const{ return this->max_step1_cnt_; } \n\n\n\t};\n\n}// devroye\n}// poisson\n}// random\n}// boost\n\n#endif \n\n", "meta": {"hexsha": "426facc0991e52bfc450bb31015152b761628d66", "size": 8880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/poisson_ext/devroye/crtp/crtp.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": "random/boost/random/poisson_ext/devroye/crtp/crtp.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": "random/boost/random/poisson_ext/devroye/crtp/crtp.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": 32.5274725275, "max_line_length": 81, "alphanum_fraction": 0.4596846847, "num_tokens": 2184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5390777522838439}}
{"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_EPS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_EPS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-ieee\n    Computes the distance between its argument and the next representable value of its argument type.\n\n    @par Semantic:\n\n    For every parameter of type @c T\n\n    @code\n    T r = eps(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T  r = pow(2,exponent(x))*Eps<T>();\n    @endcode\n\n    if @c T is a floating-point type and to :\n\n    @code\n    T r = 1;\n    @endcode\n\n    if @c T is an integral type.\n\n    @param  x Base value for epsilon computation.\n    @return The distance between @c x and its next representable value.\n\n    @see ulp, ulpdist, Eps\n**/\n  Value eps(Value const & x);\n\n} }\n#endif\n\n#include <boost/simd/function/scalar/eps.hpp>\n#include <boost/simd/function/simd/eps.hpp>\n\n#endif\n", "meta": {"hexsha": "bf88837979accac5d707bc7f0a82db6619e4ef0c", "size": 1274, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/eps.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/eps.hpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "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/eps.hpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "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": 22.350877193, "max_line_length": 101, "alphanum_fraction": 0.5729984301, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5390777497575}}
{"text": "#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <fmt/format.h>\n#include <string>\n#include <iomanip>\n#include <boost/variant.hpp>\n#include <unordered_map>\n\nstruct Not\n{\n};\nstruct And\n{\n};\nstruct Or\n{\n};\nstruct Lshift\n{\n};\nstruct Rshift\n{\n};\n\n\ntemplate<typename OpTag>\nstruct binary_op;\n//template<typename OpTag>\n//struct unary_op;\ntypedef boost::variant<unsigned short,\n  boost::recursive_wrapper<binary_op<And>>,\n  boost::recursive_wrapper<binary_op<Or>>,\n  boost::recursive_wrapper<binary_op<Lshift>>,\n  boost::recursive_wrapper<binary_op<Rshift>>,\n  boost::recursive_wrapper<binary_op<Not>>>\n  Expr;\ntypedef std::unordered_map<std::string, Expr> ExprMap;\ntemplate<typename OpTag>\nstruct binary_op\n{\n  Expr left;\n  Expr right;\n\n  binary_op(const Expr &lhs, const Expr &rhs)\n    : left(lhs), right(rhs)\n  {\n  }\n  binary_op() {}\n};\ntemplate<class IntType>\nclass Calculator : public boost::static_visitor<IntType>\n{\npublic:\n  using value_type = IntType;\n  IntType operator()(IntType value) const\n  {\n    //std::cout << \"calculator value:\" << value << std::endl;\n    return value;\n  }\n\n  IntType operator()(const binary_op<And> &binary) const\n  {\n    return boost::apply_visitor(Calculator(), binary.left)\n           & boost::apply_visitor(Calculator(), binary.right);\n  }\n\n  IntType operator()(const binary_op<Or> &binary) const\n  {\n    return boost::apply_visitor(Calculator(), binary.left)\n           | boost::apply_visitor(Calculator(), binary.right);\n  }\n  IntType operator()(const binary_op<Lshift> &binary) const\n  {\n    return boost::apply_visitor(Calculator(), binary.left)\n           << boost::apply_visitor(Calculator(), binary.right);\n  }\n  IntType operator()(const binary_op<Rshift> &binary) const\n  {\n    return boost::apply_visitor(Calculator(), binary.left)\n           >> boost::apply_visitor(Calculator(), binary.right);\n  }\n  IntType operator()(const binary_op<Not> &binary) const\n  {\n    return ~(boost::apply_visitor(Calculator(), binary.left));\n  }\n};\nusing AocCal = Calculator<unsigned short>;\nstruct IS\n{\n  AocCal c_;\n  ExprMap exprmap_;\n  AocCal::value_type operator()(const std::string &s) const\n  {\n    if (auto i = exprmap_.find(s); i != exprmap_.end()) {\n      AocCal::value_type r = boost::apply_visitor(c_, i->second);\n      return r;\n    } else {\n      return 0;\n    }\n  }\n};\n\nint main(int argc, char **argv)\n{\n  Expr e;\n  e = 32;\n\n  if (argc > 1) {\n    std::ifstream ifs(argv[1]);\n    std::string line;\n    IS asms;\n    while (std::getline(ifs, line)) {\n      std::istringstream iss(line);\n      std::vector<std::string> v;\n      std::istream_iterator<std::string> b(iss);\n      std::istream_iterator<std::string> e;\n      std::copy(b, e, std::back_inserter(v));\n      if (v.size() == 3) {\n        //std::cout << v[0] << \"\\n\";\n        if (std::isdigit(v[0][0])) {\n          auto n = static_cast<unsigned short>(std::stoi(v[0]));\n          asms.exprmap_[v[2]] = n;\n        } else {\n          asms.exprmap_[v[2]] = asms.exprmap_[v[0]];\n        }\n      } else if (v.size() == 4) {\n        asms.exprmap_[v[3]] = binary_op<Not>(asms.exprmap_[v[1]], asms.exprmap_[v[1]]);\n      } else if (v.size() == 5) {\n        if (v[1] == \"OR\") {\n          asms.exprmap_[v[4]] = binary_op<Or>(asms.exprmap_[v[0]], asms.exprmap_[v[2]]);\n        } else if (v[1] == \"AND\") {\n          asms.exprmap_[v[4]] = binary_op<And>(asms.exprmap_[v[0]], asms.exprmap_[v[2]]);\n        } else if (v[1] == \"LSHIFT\") {\n          //std::cout << v[2] << \"\\n\";\n          asms.exprmap_[v[4]] = binary_op<Lshift>(asms.exprmap_[v[0]], std::stoi(v[2]));\n        } else if (v[1] == \"RSHIFT\") {\n          //std::cout << v[2] << \"\\n\";\n          asms.exprmap_[v[4]] = binary_op<Rshift>(asms.exprmap_[v[0]], std::stoi(v[2]));\n        }\n      }\n    }\n    std::cout << asms(\"d\") << std::endl;\n    std::cout << asms(\"e\") << std::endl;\n    std::cout << asms(\"f\") << std::endl;\n    std::cout << asms(\"g\") << std::endl;\n    std::cout << asms(\"h\") << std::endl;\n    std::cout << asms(\"i\") << std::endl;\n    std::cout << asms(\"x\") << std::endl;\n    std::cout << asms(\"y\") << std::endl;\n  }\n}\n", "meta": {"hexsha": "c8fcc719f0c894b4b81cb1b7d133aed7dcae78cc", "size": 4103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc2015/aoc151201_value.cpp", "max_stars_repo_name": "jiayuehua/adventOfCode", "max_stars_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "aoc2015/aoc151201_value.cpp", "max_issues_repo_name": "jiayuehua/adventOfCode", "max_issues_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "aoc2015/aoc151201_value.cpp", "max_forks_repo_name": "jiayuehua/adventOfCode", "max_forks_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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.6428571429, "max_line_length": 89, "alphanum_fraction": 0.5968803315, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5389933306559456}}
{"text": "/**\n * @file Newton.t.h Test driver for newton interpolation algorithm\n *\n * Copyright (C) 2010  Arthur D. Cherba\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#include \"interp/Newton.h\"\n#include \"operation/field/setup.h\"\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(newton)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(newton_alg, F, math::FieldTypes) {\n  math::FieldFixture<F> f;\n  BOOST_CHECK(f);  // avoid unreferenced local variable warning\n\n  BOOST_TEST_MESSAGE(\"  Testing \" << F::getName());\n\n  int const MAX_DEG = 10;\n  F x[MAX_DEG + 1];\n  F y[MAX_DEG + 1];\n  // Assume polynomial f = sum (i+1) x^i\n  for (int i = 0; i <= MAX_DEG; ++i) {\n    F sum;\n    sum.template setTo<0>();\n    x[i].setTo(i+1);\n    for (int j = 0; j <= MAX_DEG; ++j) {\n      sum += x[i].getPow(j) * F(j+1);\n    }\n    y[i] = sum;\n  }\n  boost::scoped_array<F> coeffs(new F[MAX_DEG+1]);\n  interp::newton(MAX_DEG, x, y, coeffs.get());\n\n  // verify result\n  for (int i = 0; i <= MAX_DEG; ++i) {\n    BOOST_CHECK_MESSAGE(coeffs[i] == F(i+1),\n        \" f[i]==F(i+1) with i=\" << i\n        << \" f[i]=\" << coeffs[i] << \" F(i+1)\" << F(i+1));\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\nbool init_unit_test() {\n  return true;\n}", "meta": {"hexsha": "11073248912c82d1f8b17033c6eb610c126da38a", "size": 1792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/interp/Newton.t.cpp", "max_stars_repo_name": "cherba29/slp-poly", "max_stars_repo_head_hexsha": "0812e433c19c3ae036610c50ce54bf2d8cb8bf93", "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/interp/Newton.t.cpp", "max_issues_repo_name": "cherba29/slp-poly", "max_issues_repo_head_hexsha": "0812e433c19c3ae036610c50ce54bf2d8cb8bf93", "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/Newton.t.cpp", "max_forks_repo_name": "cherba29/slp-poly", "max_forks_repo_head_hexsha": "0812e433c19c3ae036610c50ce54bf2d8cb8bf93", "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.3770491803, "max_line_length": 72, "alphanum_fraction": 0.6529017857, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.5389314712353181}}
{"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 testNoiseModel.cpp\n * @date Jan 13, 2010\n * @author Richard Roberts\n * @author Frank Dellaert\n */\n\n\n#include <iostream>\n#include <boost/foreach.hpp>\n#include <boost/assign/std/vector.hpp>\nusing namespace boost::assign;\n\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/base/TestableAssertions.h>\n#include <gtsam/linear/NoiseModel.h>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace noiseModel;\n\nstatic double sigma = 2, s_1=1.0/sigma, var = sigma*sigma, prc = 1.0/var;\nstatic Matrix R = Matrix_(3, 3,\n\t\ts_1, 0.0, 0.0,\n\t\t0.0, s_1, 0.0,\n\t\t0.0, 0.0, s_1);\nstatic Matrix Sigma = Matrix_(3, 3,\n\t\tvar, 0.0, 0.0,\n\t\t0.0, var, 0.0,\n\t\t0.0, 0.0, var);\n\n//static double inf = std::numeric_limits<double>::infinity();\n\n/* ************************************************************************* */\nTEST(NoiseModel, constructors)\n{\n\tVector whitened = Vector_(3,5.0,10.0,15.0);\n\tVector unwhitened = Vector_(3,10.0,20.0,30.0);\n\n\t// Construct noise models\n\tvector<Gaussian::shared_ptr> m;\n\tm.push_back(Gaussian::SqrtInformation(R));\n\tm.push_back(Gaussian::Covariance(Sigma));\n\t//m.push_back(Gaussian::Information(Q));\n\tm.push_back(Diagonal::Sigmas(Vector_(3, sigma, sigma, sigma)));\n\tm.push_back(Diagonal::Variances(Vector_(3, var, var, var)));\n\tm.push_back(Diagonal::Precisions(Vector_(3, prc, prc, prc)));\n\tm.push_back(Isotropic::Sigma(3, sigma));\n\tm.push_back(Isotropic::Variance(3, var));\n\tm.push_back(Isotropic::Precision(3, prc));\n\n\t// test whiten\n\tBOOST_FOREACH(Gaussian::shared_ptr mi, m)\n\t\tEXPECT(assert_equal(whitened,mi->whiten(unwhitened)));\n\n\t// test unwhiten\n\tBOOST_FOREACH(Gaussian::shared_ptr mi, m)\n\t\tEXPECT(assert_equal(unwhitened,mi->unwhiten(whitened)));\n\n\t// test Mahalanobis distance\n\tdouble distance = 5*5+10*10+15*15;\n\tBOOST_FOREACH(Gaussian::shared_ptr mi, m)\n\t\tDOUBLES_EQUAL(distance,mi->Mahalanobis(unwhitened),1e-9);\n\n\t// test R matrix\n\tMatrix expectedR(Matrix_(3, 3,\n\t\t\ts_1, 0.0, 0.0,\n\t\t\t0.0, s_1, 0.0,\n\t\t\t0.0, 0.0, s_1));\n\n\tBOOST_FOREACH(Gaussian::shared_ptr mi, m)\n\t\tEXPECT(assert_equal(expectedR,mi->R()));\n\n\t// test Whiten operator\n\tMatrix H(Matrix_(3, 4,\n\t\t\t0.0, 0.0, 1.0, 1.0,\n\t\t\t0.0, 1.0, 0.0, 1.0,\n\t\t\t1.0, 0.0, 0.0, 1.0));\n\n\tMatrix expected(Matrix_(3, 4,\n\t\t\t0.0, 0.0, s_1, s_1,\n\t\t\t0.0, s_1, 0.0, s_1,\n\t\t\ts_1, 0.0, 0.0, s_1));\n\n\tBOOST_FOREACH(Gaussian::shared_ptr mi, m)\n\t\tEXPECT(assert_equal(expected,mi->Whiten(H)));\n\n\t// can only test inplace version once :-)\n\tm[0]->WhitenInPlace(H);\n\tEXPECT(assert_equal(expected,H));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, Unit)\n{\n\tVector v = Vector_(3,5.0,10.0,15.0);\n\tGaussian::shared_ptr u(Unit::Create(3));\n\tEXPECT(assert_equal(v,u->whiten(v)));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, equals)\n{\n\tGaussian::shared_ptr g1 = Gaussian::SqrtInformation(R),\n\t\t\t\t\t\t\t\t\t\t\t g2 = Gaussian::SqrtInformation(eye(3,3));\n\tDiagonal::shared_ptr d1 = Diagonal::Sigmas(Vector_(3, sigma, sigma, sigma)),\n\t\t\t\t\t\t\t\t\t\t\t d2 = Diagonal::Sigmas(Vector_(3, 0.1, 0.2, 0.3));\n\tIsotropic::shared_ptr i1 = Isotropic::Sigma(3, sigma),\n\t\t\t\t\t\t\t\t\t\t\t\ti2 = Isotropic::Sigma(3, 0.7);\n\n\tEXPECT(assert_equal(*g1,*g1));\n\tEXPECT(assert_inequal(*g1, *g2));\n\n\tEXPECT(assert_equal(*d1,*d1));\n\tEXPECT(assert_inequal(*d1,*d2));\n\n\tEXPECT(assert_equal(*i1,*i1));\n\tEXPECT(assert_inequal(*i1,*i2));\n}\n\n// TODO enable test once a mechanism for smart constraints exists\n///* ************************************************************************* */\n//TEST(NoiseModel, ConstrainedSmart )\n//{\n//\tGaussian::shared_ptr nonconstrained = Constrained::MixedSigmas(Vector_(3, sigma, 0.0, sigma), true);\n//\tDiagonal::shared_ptr n1 = boost::shared_dynamic_cast<Diagonal>(nonconstrained);\n//\tConstrained::shared_ptr n2 = boost::shared_dynamic_cast<Constrained>(nonconstrained);\n//\tEXPECT(n1);\n//\tEXPECT(!n2);\n//\n//\tGaussian::shared_ptr constrained = Constrained::MixedSigmas(zero(3), true);\n//\tDiagonal::shared_ptr c1 = boost::shared_dynamic_cast<Diagonal>(constrained);\n//\tConstrained::shared_ptr c2 = boost::shared_dynamic_cast<Constrained>(constrained);\n//\tEXPECT(c1);\n//\tEXPECT(c2);\n//}\n\n/* ************************************************************************* */\nTEST(NoiseModel, ConstrainedConstructors )\n{\n\tConstrained::shared_ptr actual;\n\tsize_t d = 3;\n\tdouble m = 100.0;\n\tVector sigmas = Vector_(3, sigma, 0.0, 0.0);\n\tVector mu = Vector_(3, 200.0, 300.0, 400.0);\n\tactual = Constrained::All(d);\n\tEXPECT(assert_equal(gtsam::repeat(d, 1000.0), actual->mu()));\n\n\tactual = Constrained::All(d, m);\n\tEXPECT(assert_equal(gtsam::repeat(d, m), actual->mu()));\n\n\tactual = Constrained::All(d, mu);\n\tEXPECT(assert_equal(mu, actual->mu()));\n\n\tactual = Constrained::MixedSigmas(mu, sigmas);\n\tEXPECT(assert_equal(mu, actual->mu()));\n\n\tactual = Constrained::MixedSigmas(m, sigmas);\n\tEXPECT(assert_equal( gtsam::repeat(d, m), actual->mu()));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, ConstrainedMixed )\n{\n\tVector feasible = Vector_(3, 1.0, 0.0, 1.0),\n\t\t\tinfeasible = Vector_(3, 1.0, 1.0, 1.0);\n\tDiagonal::shared_ptr d = Constrained::MixedSigmas(Vector_(3, sigma, 0.0, sigma));\n\t// NOTE: we catch constrained variables elsewhere, so whitening does nothing\n\tEXPECT(assert_equal(Vector_(3, 0.5, 1.0, 0.5),d->whiten(infeasible)));\n\tEXPECT(assert_equal(Vector_(3, 0.5, 0.0, 0.5),d->whiten(feasible)));\n\n\tDOUBLES_EQUAL(1000.0 + 0.25 + 0.25,d->distance(infeasible),1e-9);\n\tDOUBLES_EQUAL(0.5,d->distance(feasible),1e-9);\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, ConstrainedAll )\n{\n\tVector feasible = Vector_(3, 0.0, 0.0, 0.0),\n\t\t\t infeasible = Vector_(3, 1.0, 1.0, 1.0);\n\n\tConstrained::shared_ptr i = Constrained::All(3);\n\t// NOTE: we catch constrained variables elsewhere, so whitening does nothing\n\tEXPECT(assert_equal(Vector_(3, 1.0, 1.0, 1.0),i->whiten(infeasible)));\n\tEXPECT(assert_equal(Vector_(3, 0.0, 0.0, 0.0),i->whiten(feasible)));\n\n\tDOUBLES_EQUAL(1000.0 * 3.0,i->distance(infeasible),1e-9);\n\tDOUBLES_EQUAL(0.0,i->distance(feasible),1e-9);\n}\n\n/* ************************************************************************* */\nnamespace exampleQR {\n  // create a matrix to eliminate\n  Matrix Ab = Matrix_(4, 6+1,\n      -1.,  0.,  1.,  0.,  0.,  0., -0.2,\n      0., -1.,  0.,  1.,  0.,  0.,  0.3,\n      1.,  0.,  0.,  0., -1.,  0.,  0.2,\n      0.,  1.,  0.,  0.,  0., -1., -0.1);\n  Vector sigmas = Vector_(4, 0.2, 0.2, 0.1, 0.1);\n\n  // the matrix AB yields the following factorized version:\n\tMatrix Rd = Matrix_(4, 6+1,\n\t\t\t11.1803,   0.0,   -2.23607, 0.0,    -8.94427, 0.0,     2.23607,\n\t\t\t0.0,   11.1803,    0.0,    -2.23607, 0.0,    -8.94427,-1.56525,\n\t\t\t0.0,       0.0,    4.47214, 0.0,    -4.47214, 0.0,     0.0,\n\t\t\t0.0,       0.0,   0.0,     4.47214, 0.0,    -4.47214, 0.894427);\n\n\tSharedDiagonal diagonal = noiseModel::Diagonal::Sigmas(sigmas);\n}\n\nTEST( NoiseModel, QR )\n{\n  Matrix Ab1 = exampleQR::Ab;\n\tMatrix Ab2 = exampleQR::Ab; // otherwise overwritten !\n\n\t// Expected result\n\tVector expectedSigmas = Vector_(4, 0.0894427, 0.0894427, 0.223607, 0.223607);\n\tSharedDiagonal expectedModel = noiseModel::Diagonal::Sigmas(expectedSigmas);\n\n\t// Call Gaussian version\n\tSharedDiagonal actual1 = exampleQR::diagonal->QR(Ab1);\n\tSharedDiagonal expected = noiseModel::Unit::Create(4);\n\tEXPECT(assert_equal(*expected,*actual1));\n\tEXPECT(linear_dependent(exampleQR::Rd,Ab1,1e-4)); // Ab was modified in place !!!\n\n\t// Call Constrained version\n\tSharedDiagonal constrained = noiseModel::Constrained::MixedSigmas(exampleQR::sigmas);\n\tSharedDiagonal actual2 = constrained->QR(Ab2);\n\tSharedDiagonal expectedModel2 = noiseModel::Diagonal::Sigmas(expectedSigmas);\n\tEXPECT(assert_equal(*expectedModel2,*actual2,1e-6));\n\tMatrix expectedRd2 = Matrix_(4, 6+1,\n\t\t\t1.,  0., -0.2,  0., -0.8, 0.,  0.2,\n\t\t\t0.,  1.,  0.,-0.2,   0., -0.8,-0.14,\n\t\t\t0.,  0.,  1.,   0., -1.,  0.,  0.0,\n\t\t\t0.,  0.,  0.,   1.,  0., -1.,  0.2);\n\tEXPECT(linear_dependent(expectedRd2,Ab2,1e-6)); // Ab was modified in place !!!\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, QRNan )\n{\n\tSharedDiagonal constrained = noiseModel::Constrained::All(2);\n\tMatrix Ab = Matrix_(2, 5, 1., 2., 1., 2., 3., 2., 1., 2., 4., 4.);\n\n\tSharedDiagonal expected = noiseModel::Constrained::All(2);\n\tMatrix expectedAb = Matrix_(2, 5, 1., 2., 1., 2., 3., 0., 1., 0., 0., 2.0/3);\n\n\tSharedDiagonal actual = constrained->QR(Ab);\n\tEXPECT(assert_equal(*expected,*actual));\n\tEXPECT(assert_equal(expectedAb,Ab));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, SmartCovariance )\n{\n\tbool smart = true;\n\tgtsam::SharedGaussian expected = Unit::Create(3);\n\tgtsam::SharedGaussian actual = Gaussian::Covariance(eye(3), smart);\n\tEXPECT(assert_equal(*expected,*actual));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, ScalarOrVector )\n{\n\tbool smart = true;\n\tSharedGaussian expected = Unit::Create(3);\n\tSharedGaussian actual = Gaussian::Covariance(eye(3), smart);\n\tEXPECT(assert_equal(*expected,*actual));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, WhitenInPlace)\n{\n\tVector sigmas = Vector_(3, 0.1, 0.1, 0.1);\n\tSharedDiagonal model = Diagonal::Sigmas(sigmas);\n\tMatrix A = eye(3);\n\tmodel->WhitenInPlace(A);\n\tMatrix expected = eye(3) * 10;\n\tEXPECT(assert_equal(expected, A));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, robustFunction)\n{\n  const double k = 5.0, error1 = 1.0, error2 = 10.0;\n  const MEstimator::Huber::shared_ptr huber = MEstimator::Huber::Create(k);\n  const double weight1 = huber->weight(error1),\n               weight2 = huber->weight(error2);\n  DOUBLES_EQUAL(1.0, weight1, 1e-8);\n  DOUBLES_EQUAL(0.5, weight2, 1e-8);\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, robustNoise)\n{\n  const double k = 10.0, error1 = 1.0, error2 = 100.0;\n  Matrix A = Matrix_(2, 2, 1.0, 10.0, 100.0, 1000.0);\n  Vector b = Vector_(2, error1, error2);\n  const Robust::shared_ptr robust = Robust::Create(\n    MEstimator::Huber::Create(k, MEstimator::Huber::Scalar),\n    Unit::Create(2));\n\n  robust->WhitenSystem(A,b);\n\n  DOUBLES_EQUAL(error1, b(0), 1e-8);\n  DOUBLES_EQUAL(sqrt(k*error2), b(1), 1e-8);\n\n  DOUBLES_EQUAL(1.0, A(0,0), 1e-8);\n  DOUBLES_EQUAL(10.0, A(0,1), 1e-8);\n  DOUBLES_EQUAL(sqrt(k*100.0), A(1,0), 1e-8);\n  DOUBLES_EQUAL(sqrt(k/100.0)*1000.0, A(1,1), 1e-8);\n}\n\n/* ************************************************************************* */\nint main() {\tTestResult tr; return TestRegistry::runAllTests(tr); }\n/* ************************************************************************* */\n", "meta": {"hexsha": "2243950518f94a51582331b4692492fe78717db5", "size": 11195, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/tests/testNoiseModel.cpp", "max_stars_repo_name": "sdmiller/gtsam_pcl", "max_stars_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T16:41:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T07:02:44.000Z", "max_issues_repo_path": "gtsam/linear/tests/testNoiseModel.cpp", "max_issues_repo_name": "sdmiller/gtsam_pcl", "max_issues_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/linear/tests/testNoiseModel.cpp", "max_forks_repo_name": "sdmiller/gtsam_pcl", "max_forks_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T12:06:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T07:02:48.000Z", "avg_line_length": 34.131097561, "max_line_length": 103, "alphanum_fraction": 0.5848146494, "num_tokens": 3584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5389058114569855}}
{"text": "// Copyright (c) 2021 Graphcore Ltd. All rights reserved.\n#define BOOST_TEST_MODULE MaxCliqueTest\n\n#include <boost/test/unit_test.hpp>\n\n#include <popart/maxclique.hpp>\n\nusing namespace popart;\nusing namespace popart::graphclique;\n\nBOOST_AUTO_TEST_CASE(MaxCliqueTest_0) {\n\n  graphclique::AGraph ag(7);\n\n  for (int i = 0; i < 5; ++i) {\n    for (int j = 0; j < 5; ++j) {\n      ag.addEdge(i, j);\n    }\n  }\n\n  for (int i = 4; i < 7; ++i) {\n    for (int j = 4; j < 7; ++j) {\n      ag.addEdge(i, j);\n    }\n  }\n\n  graphclique::MaxClique mq(ag);\n\n  auto mcliques = mq.getMaximumCliques(1, ag.numVertices());\n  BOOST_ASSERT(mcliques.size() == 2);\n  for (int i = 0; i < 5; ++i) {\n    BOOST_ASSERT(std::find(mcliques[0].begin(), mcliques[0].end(), i) !=\n                 mcliques[0].end());\n  }\n  for (int i = 5; i < 7; ++i) {\n    BOOST_ASSERT(std::find(mcliques[1].begin(), mcliques[1].end(), i) !=\n                 mcliques[1].end());\n  }\n}\n", "meta": {"hexsha": "29a362c5440cc1937fd7c1e81d2cec107f46745d", "size": 931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/integration/maxclique_test.cpp", "max_stars_repo_name": "gglin001/popart", "max_stars_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:51.000Z", "max_issues_repo_path": "tests/integration/maxclique_test.cpp", "max_issues_repo_name": "gglin001/popart", "max_issues_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-25T01:30:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T11:13:14.000Z", "max_forks_repo_path": "tests/integration/maxclique_test.cpp", "max_forks_repo_name": "gglin001/popart", "max_forks_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:33:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T06:55:00.000Z", "avg_line_length": 23.275, "max_line_length": 72, "alphanum_fraction": 0.5757250269, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5388913937010732}}
{"text": "#include <algorithm>\n#include <charconv>\n#include <iostream>\n#include <limits>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include <boost/range/irange.hpp>\n\n#include \"input.hpp\"\n\nusing intmax = std::intmax_t;\nusing uintmax = std::uintmax_t;\n\nconstexpr auto SPACE = ' ';\nconstexpr auto NEWLINE = '\\n';\n\n/*\n * compile-time parsing to allow for reserving the size of vectors\n * when taking another pass through the puzzle input\n */\nconstexpr auto parse_stats(std::string_view input) {\n  auto num_words = uintmax{},\n       num_lines = uintmax{};\n\n  for(auto c : input) {\n    num_words += (c == SPACE);\n    num_lines += (c == NEWLINE);\n  }\n\n  ++num_lines;\n  num_words = (num_words / num_lines) + 1;\n\n  return std::pair{num_words, num_lines};\n}\n\nconstexpr auto PARSE_STATS = parse_stats(puzzle_input);\nconstexpr auto NUM_WORDS = PARSE_STATS.first;\nconstexpr auto NUM_LINES = PARSE_STATS.second;\n\nauto triangle(uintmax n) {\n  return (n * (n - 1)) / 2;\n}\n\ntemplate<typename T>\nclass AdjacencyMatrix {\n  private:\n    std::vector<T> data;\n\n  public:\n    AdjacencyMatrix(uintmax size) : data(triangle(size), {}) {}\n\n    auto operator[](uintmax i) {\n      return &data[triangle(i)];\n    }\n\n    auto operator[](uintmax i) const {\n      return &data[triangle(i)];\n    }\n};\n\nusing ID = uintmax;\nusing Pair = std::pair<ID, ID>;\n\nauto operator==(const Pair& lhs, const Pair& rhs) {\n  return lhs.first == rhs.first\n         and lhs.second == rhs.second;\n}\n\nnamespace std {\n  template<>\n  struct hash<Pair> {\n    auto operator()(const Pair& pair) const {\n      const auto shift = std::numeric_limits<decltype(pair.second)>::digits / 2;\n      return pair.first + (pair.second << shift);\n    }\n  };\n}\n\nauto minmax(const Pair& pair) {\n  return std::minmax(pair.first, pair.second);\n}\n\nclass Happymeter {\n  private:\n    AdjacencyMatrix<intmax> matrix;\n\n  public:\n    uintmax num_people;\n\n    Happymeter(uintmax size) : matrix(size), num_people(size) {};\n\n    auto& operator[](const Pair& pair) {\n      const auto [min, max] = minmax(pair);\n      return matrix[max][min];\n    }\n\n    auto operator[](const Pair& pair) const {\n      const auto [min, max] = minmax(pair);\n      return matrix[max][min];\n    }\n};\n\nauto parse(std::string_view input) {\n\n  using Person = std::string_view;\n\n  auto num_people = ID{};\n\n  using People = std::unordered_map<Person, ID>;\n\n  auto lookup = [&, people = People{}] (auto person) mutable {\n    if(people.find(person) == people.end()) {\n      people[person] = num_people++;\n    }\n    return people.at(person);\n  };\n\n  const auto split = [] (auto input, auto delimiter, auto size) {\n    auto tokens = std::vector<decltype(input)>{};\n    tokens.reserve(size);\n    auto pos = decltype(input.size()){};\n    while(pos != input.npos) {\n      pos = input.find(delimiter);\n      tokens.push_back(input.substr({}, pos));\n      input.remove_prefix(pos + 1);\n    }\n    return tokens;\n  };\n\n  const auto to_int = [] (auto input) {\n    intmax result;\n    std::from_chars(input.begin(), input.end(), result);\n    return result;\n  };\n\n  using Score = intmax;\n  auto scores = std::unordered_map<Pair, Score>{};\n\n  for(const auto line : split(input, NEWLINE, NUM_LINES)) {\n    auto words = split(line, SPACE, NUM_WORDS);\n    words.back().remove_suffix(1);\n\n    const auto person1 = lookup(words.front());\n    const auto person2 = lookup(words.back());\n\n    const auto score = to_int(words[3]);\n    const auto modifier = ((words[2] == \"lose\") ? -1 : 1);\n\n    scores[{person1, person2}] = (score * modifier);\n  }\n\n  auto happymeter = Happymeter{num_people};\n\n  for(const auto [pair, score] : scores) {\n    happymeter[pair] += score;\n  }\n\n  return happymeter;\n}\n\nusing Seating = std::vector<ID>;\n\nauto get_happiness(const Seating& seating, const Happymeter& happymeter) {\n\n  /*\n   * We take out the last person so we can insert them\n   * where the happiness is the lowest later on\n   */\n  const auto begin = seating.begin();\n  const auto end  = seating.end() - 1;\n\n  const auto first = seating.front();\n  const auto last  = seating.back();\n  const auto next_to_last = *(end - 1);\n\n  /*\n   * a) Because the seating is circular, the people at both ends of\n   *    the seating need to be included as well, but it's not easily\n   *    done when iterating over the seating. So we include that pair\n   *    before the start of iterations.\n   *\n   * b) The last person is not yet included when collecting the scores\n   *    for happiness (see comment at the start of this function), so\n   *    we start off with the score for the next-to-last pair\n   */\n  const auto penultimate_score = happymeter[{first, next_to_last}];\n\n  auto total_score = penultimate_score;\n  auto min = penultimate_score;\n\n  std::adjacent_find(begin, end, [&] (const auto a, const auto b) {\n    const auto score = happymeter[{a, b}];\n    total_score += score;\n    min = std::min(min, score);\n    return false;\n  });\n\n  /*\n   * Now that we have all the necessary scores, we can insert the last\n   * person in order to get the highest potential score.\n   *\n   * \"Inserting\" includes removing the lowest happiness score, then adding\n   * two scores, one for the last two people and one for the people at both\n   * ends of the seating.\n   */\n  total_score -= min;\n  total_score += happymeter[{next_to_last, last}];\n  total_score += happymeter[{first, last}];\n\n  return total_score;\n}\n\nauto solution(std::string_view input) {\n\n  auto max = intmax{};\n\n  const auto happymeter = parse(input);\n  const auto num_people = happymeter.num_people;\n\n  auto seating = Seating(num_people, 0);\n\n  /*\n   * - Fixing one neighbor of the first person removes rotated seatings that are equivalent\n   *   (A-B-C-D == D-A-B-C)\n   * - Fixing the second neighbor removes mirrored seatings, which are also equivalent\n   *   (A-B-C-D == D-C-B-A)\n   * - Fixing the position of the first person to the second position of the seating lets\n   *   us fill up the remaining seating from the fourth position to the end through\n   *   std::generate.\n   * - Fixing the last person allows us to only look at permutations of the first seven seats,\n   *   at which point we can optimize the happiness function to insert the last person where\n   *   the happiness score is the lowest - this removes another chunk of permutations to look at\n   *\n   * - The effect of fixing a total of four positions of the seating before performing permutations\n   *   is a huge reduction of the search space: from 8! (40'320) to [(choose 2 out of 6) * 4!] (360).\n   *   That's a reduction of 99%.\n   */\n  const auto num_permutable_seats = num_people - 1;\n  seating[1] = 0;\n  seating.back() = num_permutable_seats;\n\n  for(const auto i : boost::irange({1}, (num_permutable_seats - 1))) {\n    // fixt the first neighbor of the first person\n    seating[0] = i;\n\n    for(const auto j : boost::irange((i + 1), num_permutable_seats)) {\n      // fix the second neighbor of the first person\n      seating[2] = j;\n\n      const auto begin = seating.begin() + 3;\n      const auto end   = seating.end() - 1;\n\n      auto current = ID{};\n\n      // fill the remaining seats\n      std::generate(begin, end, [&] {\n        while(++current == i or current == j);\n        return current;\n      });\n\n      do {\n        max = std::max(max, get_happiness(seating, happymeter));\n      } while(std::next_permutation(begin, end));\n    }\n  }\n\n  return max;\n}\n\nint main() {\n  std::cout << solution(puzzle_input) << std::endl;\n}\n", "meta": {"hexsha": "64555037bc8014444f2ce997bbcf44538d8e7fa1", "size": 7417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 13 Part 1/main_v2.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 13 Part 1/main_v2.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 13 Part 1/main_v2.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9709090909, "max_line_length": 101, "alphanum_fraction": 0.6512066873, "num_tokens": 1921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5388913853975122}}
{"text": "#include \"distributions.h\"\n\n#include <Eigen/Dense>\n#include <random>\n#include <stan/math/prim.hpp>\n\n#include \"src/utils/proto_utils.h\"\n\nint bayesmix::categorical_rng(const Eigen::VectorXd &probas,\n                              std::mt19937_64 &rng, int start /*= 0*/) {\n  return stan::math::categorical_rng(probas, rng) + (start - 1);\n}\n\ndouble bayesmix::multi_normal_prec_lpdf(const Eigen::VectorXd &datum,\n                                        const Eigen::VectorXd &mean,\n                                        const Eigen::MatrixXd &prec_chol,\n                                        double prec_logdet) {\n  using stan::math::NEG_LOG_SQRT_TWO_PI;\n  double base = prec_logdet + NEG_LOG_SQRT_TWO_PI * datum.size();\n  double exp = (prec_chol * (datum - mean)).squaredNorm();\n  return 0.5 * (base - exp);\n}\n\nEigen::VectorXd bayesmix::multi_normal_prec_lpdf_grid(\n    const Eigen::MatrixXd &data, const Eigen::VectorXd &mean,\n    const Eigen::MatrixXd &prec_chol, double prec_logdet) {\n  using stan::math::NEG_LOG_SQRT_TWO_PI;\n  Eigen::VectorXd exp =\n      ((data.rowwise() - mean.transpose()) * prec_chol.transpose())\n          .rowwise()\n          .squaredNorm();\n  Eigen::VectorXd base = Eigen::ArrayXd::Ones(data.rows()) * prec_logdet +\n                         NEG_LOG_SQRT_TWO_PI * data.cols();\n  return (base - exp) * 0.5;\n}\n\ndouble bayesmix::multi_student_t_invscale_lpdf(\n    const Eigen::VectorXd &datum, double df, const Eigen::VectorXd &mean,\n    const Eigen::MatrixXd &invscale_chol, double scale_logdet) {\n  int dim = datum.size();\n  double exp =\n      0.5 * (df + dim) *\n      std::log(1 + (invscale_chol * (datum - mean)).squaredNorm() / df);\n  double base = stan::math::lgamma((df + dim) * 0.5) -\n                stan::math::lgamma(df * 0.5) - (0.5 * dim) * std::log(df) -\n                (0.5 * dim) * stan::math::LOG_PI + 0.5 * scale_logdet;\n  return base - exp;\n}\n\nEigen::VectorXd bayesmix::multi_student_t_invscale_lpdf_grid(\n    const Eigen::MatrixXd &data, double df, const Eigen::VectorXd &mean,\n    const Eigen::MatrixXd &invscale_chol, double scale_logdet) {\n  int dim = data.cols();\n  int n = data.rows();\n  double base_coeff = stan::math::lgamma((df + dim) * 0.5) -\n                      stan::math::lgamma(df * 0.5) -\n                      (0.5 * dim) * std::log(df) -\n                      (0.5 * dim) * stan::math::LOG_PI + 0.5 * scale_logdet;\n  Eigen::VectorXd base = Eigen::VectorXd::Ones(n) * base_coeff;\n  Eigen::VectorXd quadforms =\n      ((data.rowwise() - mean.transpose()) * invscale_chol.transpose())\n          .rowwise()\n          .squaredNorm();\n  Eigen::VectorXd exp =\n      (quadforms.array() / df + 1.0).log() * 0.5 * (df + dim);\n  return base - exp;\n}\n\ndouble bayesmix::gaussian_mixture_dist(\n    Eigen::VectorXd means1, Eigen::VectorXd vars1, Eigen::VectorXd weights1,\n    Eigen::VectorXd means2, Eigen::VectorXd vars2, Eigen::VectorXd weights2) {\n  double mix1 = 0.0;\n#pragma omp parallel for collapse(2) reduction(+ : mix1)\n  for (int i = 0; i < means1.size(); i++) {\n    for (int j = 0; j < means1.size(); j++) {\n      mix1 += weights1(i) * weights1(j) *\n              std::exp(stan::math::normal_lpdf(means1(i), means1(j),\n                                               vars1(i) + vars1(j)));\n    }\n  }\n\n  double mix2 = 0.0;\n#pragma omp parallel for collapse(2) reduction(+ : mix2)\n  for (int i = 0; i < means2.size(); i++) {\n    for (int j = 0; j < means2.size(); j++) {\n      mix2 += weights2(i) * weights2(j) *\n              std::exp(stan::math::normal_lpdf(means2(i), means2(j),\n                                               vars2(i) + vars2(j)));\n    }\n  }\n\n  double inter = 0.0;\n#pragma omp parallel for collapse(2) reduction(+ : inter)\n  for (int i = 0; i < means1.size(); i++) {\n    for (int j = 0; j < means2.size(); j++) {\n      inter += weights1(i) * weights2(j) *\n               std::exp(stan::math::normal_lpdf(means1(i), means2(j),\n                                                vars1(i) + vars2(j)));\n    }\n  }\n\n  return mix1 + mix2 - 2 * inter;\n}\n\ndouble bayesmix::gaussian_mixture_dist(std::vector<Eigen::VectorXd> means1,\n                                       std::vector<Eigen::MatrixXd> precs1,\n                                       Eigen::VectorXd weights1,\n                                       std::vector<Eigen::VectorXd> means2,\n                                       std::vector<Eigen::MatrixXd> precs2,\n                                       Eigen::VectorXd weights2) {\n  std::vector<Eigen::MatrixXd> vars1;\n  std::vector<Eigen::MatrixXd> vars2;\n\n  for (const auto &p : precs1) vars1.push_back(stan::math::inverse_spd(p));\n\n  for (const auto &p : precs2) vars2.push_back(stan::math::inverse_spd(p));\n\n  double mix1 = 0.0;\n  for (int i = 0; i < means1.size(); i++) {\n    for (int j = 0; j < means1.size(); j++) {\n      Eigen::MatrixXd var_ij = vars1[i] + vars1[j];\n      mix1 += weights1(i) * weights1(j) *\n              std::exp(\n                  stan::math::multi_normal_lpdf(means1[i], means1[j], var_ij));\n    }\n  }\n\n  double mix2 = 0.0;\n  for (int i = 0; i < means2.size(); i++) {\n    for (int j = 0; j < means2.size(); j++) {\n      Eigen::MatrixXd var_ij = vars2[i] + vars2[j];\n      mix2 += weights2(i) * weights2(j) *\n              std::exp(\n                  stan::math::multi_normal_lpdf(means2[i], means2[j], var_ij));\n    }\n  }\n\n  double inter = 0.0;\n  for (int i = 0; i < means1.size(); i++) {\n    for (int j = 0; j < means2.size(); j++) {\n      Eigen::MatrixXd var_ij = vars1[i] + vars2[j];\n      inter += weights1(i) * weights2(j) *\n               std::exp(stan::math::multi_normal_lpdf(means1[i], means2[j],\n                                                      var_ij));\n    }\n  }\n\n  return mix1 + mix2 - 2 * inter;\n}\n\ndouble bayesmix::gaussian_mixture_dist(\n    std::vector<bayesmix::AlgorithmState::ClusterState> clus1,\n    Eigen::VectorXd weights1,\n    std::vector<bayesmix::AlgorithmState::ClusterState> clus2,\n    Eigen::VectorXd weights2) {\n  double out;\n\n  if (clus1[0].has_uni_ls_state()) {\n    Eigen::VectorXd means1(clus1.size());\n    Eigen::VectorXd vars1(clus1.size());\n    Eigen::VectorXd means2(clus2.size());\n    Eigen::VectorXd vars2(clus2.size());\n    for (int i = 0; i < clus1.size(); i++) {\n      means1(i) = clus1[i].uni_ls_state().mean();\n      vars1(i) = clus1[i].uni_ls_state().var();\n    }\n\n    for (int i = 0; i < clus2.size(); i++) {\n      means2(i) = clus2[i].uni_ls_state().mean();\n      vars2(i) = clus2[i].uni_ls_state().var();\n    }\n\n    out = gaussian_mixture_dist(means1, vars1, weights1, means2, vars2,\n                                weights2);\n  } else if (clus1[0].has_multi_ls_state()) {\n    std::vector<Eigen::VectorXd> means1, means2;\n    std::vector<Eigen::MatrixXd> precs1, precs2;\n\n    for (const auto &c : clus1) {\n      means1.push_back(bayesmix::to_eigen(c.multi_ls_state().mean()));\n      precs1.push_back(bayesmix::to_eigen(c.multi_ls_state().prec()));\n    }\n\n    for (const auto &c : clus2) {\n      means2.push_back(bayesmix::to_eigen(c.multi_ls_state().mean()));\n      precs2.push_back(bayesmix::to_eigen(c.multi_ls_state().prec()));\n    }\n\n    out = gaussian_mixture_dist(means1, precs1, weights1, means2, precs2,\n                                weights2);\n  } else {\n    throw std::invalid_argument(\"Parameter type not recognized\");\n  }\n\n  return out;\n}\n", "meta": {"hexsha": "ab8be64ccdaf4d9619e0ac54a644c1e82ee4b5b7", "size": 7308, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/utils/distributions.cc", "max_stars_repo_name": "bayesmix-dev/bayesmix", "max_stars_repo_head_hexsha": "b704b37a740b008f7c22527151026b041a5fe120", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-10-13T16:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T13:50:42.000Z", "max_issues_repo_path": "src/utils/distributions.cc", "max_issues_repo_name": "bayesmix-dev/bayesmix", "max_issues_repo_head_hexsha": "b704b37a740b008f7c22527151026b041a5fe120", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-10-26T09:49:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:23:38.000Z", "max_forks_repo_path": "src/utils/distributions.cc", "max_forks_repo_name": "bayesmix-dev/bayesmix", "max_forks_repo_head_hexsha": "b704b37a740b008f7c22527151026b041a5fe120", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2020-11-17T06:52:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T12:08:47.000Z", "avg_line_length": 37.0964467005, "max_line_length": 79, "alphanum_fraction": 0.5632183908, "num_tokens": 2098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245618, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5388913687903905}}
{"text": "//\n// Copyright (c) 2019 CNRS\n//\n\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/center-of-mass.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/algorithm/kinematics-derivatives.hpp\"\n#include \"pinocchio/algorithm/center-of-mass-derivatives.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_kinematics_derivatives_vcom)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  Model model;\n  buildModels::humanoid(model);\n  \n  Data data(model), data_ref(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  VectorXd vq(VectorXd::Random(model.nv));\n  VectorXd aq(VectorXd::Random(model.nv));\n\n  // Compute dvcom_dq using the algorithm\n  Data::Matrix3x dvcom_dq = Data::Matrix3x::Zero(3,model.nv);\n  computeForwardKinematicsDerivatives(model,data,q,vq,aq);\n  centerOfMass(model,data,q,vq);\n  getCenterOfMassVelocityDerivatives(model,data,dvcom_dq);\n\n  // Approximate dvcom_dq by finite diff.\n  Eigen::Vector3d vcom0 = data.vcom[0];\n  const double alpha = 1e-8;\n  Eigen::VectorXd dq = VectorXd::Zero(model.nv);\n  Data::Matrix3x dvcom_dqn(3,model.nv);\n\n  for(int k = 0; k < model.nv; ++k)\n  {\n    dq[k] = alpha;\n    centerOfMass(model,data,integrate(model,q,dq),vq);\n    dvcom_dqn.col(k) = (data.vcom[0]-vcom0)/alpha;\n    dq[k] = 0;\n  }\n\n  // Check that algo result and finite-diff approx are similar.\n  BOOST_CHECK(dvcom_dq.isApprox(dvcom_dqn,sqrt(alpha)));\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "8c775959190dcaba7e3ff8bc5d2ddb43efe8cdd1", "size": 1839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/center-of-mass-derivatives.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": "unittest/center-of-mass-derivatives.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": "unittest/center-of-mass-derivatives.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-04-21T16:00:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T06:24:52.000Z", "avg_line_length": 28.2923076923, "max_line_length": 63, "alphanum_fraction": 0.7417074497, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5388714736467052}}
{"text": "// Tests from ndarray lib\n#include <boost/python.hpp>\n#include <Eigen/Eigen>\n#include \"eigen_numpy.h\"\n\n#include <iostream>\n\nnamespace bp = boost::python;\n\ntemplate <typename M>\nbool acceptMatrix(M m) {\n    return (m(0,0) == 1) && (m(0,1) == 2) && (m(0,2) == 3) \n        && (m(1,0) == 4) && (m(1,1) == 5) && (m(1,2) == 6);\n}\n\ntemplate <typename M>\nbool acceptVector(M m) {\n    return (m[0] == 1) && (m[1] == 2) && (m[2] == 3) && (m[3] == 4);\n}\n\ntemplate <typename M>\nvoid fillMatrix(M & m) {\n    m(0,0) = 1;\n    m(0,1) = 2;\n    m(0,2) = 3;\n    m(1,0) = 4;\n    m(1,1) = 5;\n    m(1,2) = 6;\n}\n\ntemplate <typename M>\nM returnMatrix() {\n    static typename boost::remove_const<typename boost::remove_reference<M>::type>::type m(2,3);\n    fillMatrix(m);\n    return m;\n}\n\ntemplate <typename M>\nvoid fillVector(M & m) {\n    m[0] = 1;\n    m[1] = 2;\n    m[2] = 3;\n    m[3] = 4;\n}\n\ntemplate <typename M>\nM returnVector() {\n    static typename boost::remove_const<typename boost::remove_reference<M>::type>::type m(4);\n    fillVector(m);\n    return m;\n}\n\ntemplate <typename M>\nbp::object returnObject() {\n    static typename boost::remove_const<typename boost::remove_reference<M>::type>::type m(2,3);\n    fillMatrix(m);\n    bp::object o(m);\n    return o;\n}\n\nstatic const int X = Eigen::Dynamic;\n\nBOOST_PYTHON_MODULE(test_eigen_numpy_mod) {\n  SetupEigenConverters();\n  bp::def(\"acceptMatrix_23d_cref\", acceptMatrix< Eigen::Matrix<double,2,3> const &>);\n  bp::def(\"acceptMatrix_X3d_cref\", acceptMatrix< Eigen::Matrix<double,X,3> const &>);\n  bp::def(\"acceptMatrix_2Xd_cref\", acceptMatrix< Eigen::Matrix<double,2,X> const &>);\n  bp::def(\"acceptMatrix_XXd_cref\", acceptMatrix< Eigen::Matrix<double,X,X> const &>);\n  bp::def(\"acceptVector_41d_cref\", acceptVector< Eigen::Matrix<double,4,1> const &>);\n  bp::def(\"acceptVector_X1d_cref\", acceptVector< Eigen::Matrix<double,X,1> const &>);\n  bp::def(\"acceptVector_14d_cref\", acceptVector< Eigen::Matrix<double,1,4> const &>);\n  bp::def(\"acceptVector_1Xd_cref\", acceptVector< Eigen::Matrix<double,1,X> const &>);\n  bp::def(\"returnVector_41d\", returnVector< Eigen::Matrix<double,4,1> >);\n  bp::def(\"returnVector_14d\", returnVector< Eigen::Matrix<double,1,4> >);\n  bp::def(\"returnVector_X1d\", returnVector< Eigen::Matrix<double,X,1> >);\n  bp::def(\"returnVector_1Xd\", returnVector< Eigen::Matrix<double,1,X> >);\n  bp::def(\"returnMatrix_23d\", returnMatrix< Eigen::Matrix<double,2,3> >);\n  bp::def(\"returnMatrix_X3d\", returnMatrix< Eigen::Matrix<double,X,3> >);\n  bp::def(\"returnMatrix_2Xd\", returnMatrix< Eigen::Matrix<double,2,X> >);\n  bp::def(\"returnMatrix_XXd\", returnMatrix< Eigen::Matrix<double,X,X> >);\n  bp::def(\"returnMatrix_23d_c\", returnMatrix< Eigen::Matrix<double,2,3> const>);\n  bp::def(\"returnMatrix_X3d_c\", returnMatrix< Eigen::Matrix<double,X,3> const>);\n  bp::def(\"returnMatrix_2Xd_c\", returnMatrix< Eigen::Matrix<double,2,X> const>);\n  bp::def(\"returnMatrix_XXd_c\", returnMatrix< Eigen::Matrix<double,X,X> const>);\n  bp::def(\"returnObject_23d\", returnObject< Eigen::Matrix<double,2,3> >);\n  bp::def(\"returnObject_X3d\", returnObject< Eigen::Matrix<double,X,3> >);\n  bp::def(\"returnObject_2Xd\", returnObject< Eigen::Matrix<double,2,X> >);\n  bp::def(\"returnObject_XXd\", returnObject< Eigen::Matrix<double,X,X> >);\n}\n", "meta": {"hexsha": "9a14013c5453a193eccec1e785836a5555217627", "size": 3256, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/test_eigen_numpy_mod.cc", "max_stars_repo_name": "dendisuhubdy/boost_numpy_eigen", "max_stars_repo_head_hexsha": "8eb794027c9f9ea8f719a8f76b73af111465751a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-16T18:02:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-16T18:02:40.000Z", "max_issues_repo_path": "src/test_eigen_numpy_mod.cc", "max_issues_repo_name": "dendisuhubdy/boost_numpy_eigen", "max_issues_repo_head_hexsha": "8eb794027c9f9ea8f719a8f76b73af111465751a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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_eigen_numpy_mod.cc", "max_forks_repo_name": "dendisuhubdy/boost_numpy_eigen", "max_forks_repo_head_hexsha": "8eb794027c9f9ea8f719a8f76b73af111465751a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1777777778, "max_line_length": 96, "alphanum_fraction": 0.6606265356, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5388714736467052}}
{"text": "#include \"catch.hpp\"\n#include \"ezsolver.hpp\"\n#include \"shiftinvert_solver.hpp\"\n#include \"timer.hpp\"\n\n#include <Eigen/Dense>\n#include <complex>\n#include <fmt/format.h>\n#include <iostream>\n#include <string>\n\nusing namespace Eigen;\nusing namespace std::complex_literals;\n\nTEST_CASE(\"run through\", \"[solver]\") {\n  int ndim = 4;\n  MatrixXd matA = MatrixXd::Random(ndim, ndim);\n  MatrixXd matB = MatrixXd::Random(ndim, ndim);\n  GeneralizedEigenSolver<MatrixXd> ges(matA, matB);\n  VectorXcd ev = ges.eigenvalues();\n  for (int i = 0; i < ev.size(); ++i) {\n    fmt::print(\"({:12.5f}, {:12.5f})\\n\", ev(i).real(), ev(i).imag());\n  }\n  int maxiter = 20;\n  double tol = 1.0e-5;\n  ShiftinvertSolver sis(matA, matB, maxiter, tol);\n  std::complex<double> sigma = 0.59;\n  std::complex<double> ev2 = sis.compute(sigma);\n  fmt::print(\"eigenvalues near to ({:12.5f}, {:12.5f}): ({:12.5f}, {:12.5f})\\n\",\n             sigma.real(), sigma.imag(), ev2.real(), ev2.imag());\n  sigma = 2.8;\n  ev2 = sis.compute(sigma);\n  fmt::print(\"eigenvalues near to ({:12.5f}, {:12.5f}): ({:12.5f}, {:12.5f})\\n\",\n             sigma.real(), sigma.imag(), ev2.real(), ev2.imag());\n  sigma = 0.3 + 0.5i;\n  ev2 = sis.compute(sigma);\n  fmt::print(\"eigenvalues near to ({:12.5f}, {:12.5f}): ({:12.5f}, {:12.5f})\\n\",\n             sigma.real(), sigma.imag(), ev2.real(), ev2.imag());\n\n  double sigma3 = 0.03;\n  EzSolver ezs(matA, matB);\n  int nev = 2;\n  VectorXcd ev3 = ezs.compute(sigma3, nev);\n  for (int i = 0; i < ev3.size(); ++i) {\n    fmt::print(\"eigenvalues near to ({:12.5f}): ({:12.5f}, {:12.5f})\\n\", sigma3,\n               ev3(i).real(), ev3(i).imag());\n  }\n}\n\nvoid start_performance(int ndim, double sigma_in) {\n  MatrixXd matA = MatrixXd::Random(ndim, ndim);\n  // MatrixXd matB = MatrixXd::Random(ndim, ndim);\n  // MatrixXd matB = MatrixXd::Random(ndim, ndim);\n  // MatrixXd matA = MatrixXd::Identity(ndim, ndim);\n  MatrixXd matB = MatrixXd::Identity(ndim, ndim);\n  for (int i = 1; i < ndim; ++i) {\n    for (int j = 0; j < i; ++j) {\n      matA(j, i) = matA(i, j);\n      matB(j, i) = matB(i, j);\n    }\n  }\n  // for (int i = 0; i < ndim; ++i) {\n  //   for (int j = 0; j < ndim; ++j) {\n  //     fmt::print(\"{:9.4f}\", matA(i, j));\n  //   }\n  //   fmt::print(\"\\n\");\n  // }\n  // fmt::print(\"\\n\");\n  // for (int i = 0; i < ndim; ++i) {\n  //   for (int j = 0; j < ndim; ++j) {\n  //     fmt::print(\"{:9.4f}\", matB(i, j));\n  //   }\n  //   fmt::print(\"\\n\");\n  // }\n\n  Timer::begin(\"GeneralizedEigenSolver\");\n  GeneralizedEigenSolver<MatrixXd> ges(matA, matB);\n  VectorXcd ev = ges.eigenvalues();\n  Timer::end(\"GeneralizedEigenSolver\");\n  fmt::print(\"\\nGeneralizedEigenSolver\\n\");\n  for (int i = 0; i < ev.size(); ++i) {\n    fmt::print(\"({:12.5f}, {:12.5f})\\n\", ev(i).real(), ev(i).imag());\n  }\n  fmt::print(\"---------------------------------------------\\n\");\n\n  Timer::begin(\"shift-invert\");\n  int maxiter = 100;\n  double tol = 1.0e-5;\n  ShiftinvertSolver sis(matA, matB, maxiter, tol);\n  std::complex<double> sigma = sigma_in;\n  std::complex<double> ev2 = sis.compute(sigma);\n  Timer::end(\"shift-invert\");\n  fmt::print(\"eigenvalues near to ({:12.5f}, {:12.5f}):\\n\", sigma.real(),\n             sigma.imag());\n  fmt::print(\"({:12.5f}, {:12.5f})\\n\", ev2.real(), ev2.imag());\n  fmt::print(\"---------------------------------------------\\n\");\n\n  Timer::begin(\"ezsolver-asym\");\n  EzSolver ezs(matA, matB);\n  int nev = 4;\n  double sigma3 = sigma_in;\n  VectorXcd ev3 = ezs.compute(sigma3, nev);\n  Timer::end(\"ezsolver-asym\");\n  Timer::begin(\"ezsolver-sym\");\n  EzSolver ezs2(matA, matB);\n  VectorXcd ev4 = ezs2.compute_sym(sigma3, nev);\n  Timer::end(\"ezsolver-sym\");\n  fmt::print(\"eigenvalues near to {:12.5f}:\\n\", sigma3);\n  for (int i = 0; i < nev; ++i) {\n    fmt::print(\"({:12.5f}, {:12.5f})\\n\", ev3(i).real(), ev3(i).imag());\n  }\n  fmt::print(\"---------------------------------------------\\n\");\n  fmt::print(\"eigenvalues near to {:12.5f}:\\n\", sigma3);\n  for (int i = 0; i < nev; ++i) {\n    fmt::print(\"({:12.5f}, {:12.5f})\\n\", ev4(i).real(), ev4(i).imag());\n  }\n  fmt::print(\"---------------------------------------------\\n\");\n\n  std::cout << Timer::summery() << std::endl;\n}\n\nTEST_CASE(\"performance 10\", \"[solver]\") { start_performance(10, 0.59); }\n\nTEST_CASE(\"performance 20\", \"[solver]\") { start_performance(20, 0.59); }\n\nTEST_CASE(\"performance 100\", \"[solver]\") { start_performance(100, 0.59); }\n\nTEST_CASE(\"performance 400\", \"[solver]\") { start_performance(400, 0.59); }\n\nTEST_CASE(\"ezsolver performance\", \"[solver]\") {\n  int ndim = 100;\n  MatrixXd matA = MatrixXd::Random(ndim, ndim);\n  MatrixXd matB = MatrixXd::Random(ndim, ndim);\n  double sigma = 0.1;\n  EzSolver ezs(matA, matB);\n  VectorXi nevs(5);\n  nevs << 1, 10, 20, 40, 80;\n  for (int i = 0; i < nevs.size(); ++i) {\n    int nev = nevs(i);\n    std::string tag = fmt::format(\"nev = {:d}\", nev);\n    Timer::begin(tag);\n    VectorXcd ev = ezs.compute(sigma, nev);\n    Timer::end(tag);\n    fmt::print(\"{:s}\\n\", tag);\n    for (int i = 0; i < nev; ++i) {\n      fmt::print(\"({:12.5f}, {:12.5f})\\n\", ev(i).real(), ev(i).imag());\n    }\n    fmt::print(\"----------------------------\\n\");\n  }\n  std::cout << Timer::summery() << std::endl;\n}\n", "meta": {"hexsha": "490954140b2ff83917e309c0aab3039d963b6d37", "size": 5140, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test_solver.cc", "max_stars_repo_name": "pan3rock/shift-invert", "max_stars_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_stars_repo_licenses": ["MIT"], "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_solver.cc", "max_issues_repo_name": "pan3rock/shift-invert", "max_issues_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_issues_repo_licenses": ["MIT"], "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_solver.cc", "max_forks_repo_name": "pan3rock/shift-invert", "max_forks_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_forks_repo_licenses": ["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.8157894737, "max_line_length": 80, "alphanum_fraction": 0.5484435798, "num_tokens": 1793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5388714674037582}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright 2018 John Maddock. Distributed under the Boost\r\n//  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#ifndef BOOST_MP_CPP_COMPLEX_HPP\r\n#define BOOST_MP_CPP_COMPLEX_HPP\r\n\r\n#include <boost/multiprecision/cpp_bin_float.hpp>\r\n#include <boost/multiprecision/complex_adaptor.hpp>\r\n\r\nnamespace boost {\r\n   namespace multiprecision {\r\n\r\n#ifndef BOOST_NO_CXX11_TEMPLATE_ALIASES\r\n\r\n      template <unsigned Digits, backends::digit_base_type DigitBase = backends::digit_base_10, class Allocator = void, class Exponent = int, Exponent MinExponent = 0, Exponent MaxExponent = 0>\r\n      using cpp_complex_backend = complex_adaptor<cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinExponent, MaxExponent> >;\r\n\r\n      template <unsigned Digits, backends::digit_base_type DigitBase = digit_base_10, class Allocator = void, class Exponent = int, Exponent MinExponent = 0, Exponent MaxExponent = 0, expression_template_option ExpressionTemplates = et_off>\r\n      using cpp_complex = number<complex_adaptor<cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinExponent, MaxExponent> >, ExpressionTemplates>;\r\n\r\n      typedef cpp_complex<50> cpp_complex_50;\r\n      typedef cpp_complex<100> cpp_complex_100;\r\n\r\n      typedef cpp_complex<24, backends::digit_base_2, void, boost::int16_t, -126, 127> cpp_complex_single;\r\n      typedef cpp_complex<53, backends::digit_base_2, void, boost::int16_t, -1022, 1023> cpp_complex_double;\r\n      typedef cpp_complex<64, backends::digit_base_2, void, boost::int16_t, -16382, 16383> cpp_complex_extended;\r\n      typedef cpp_complex<113, backends::digit_base_2, void, boost::int16_t, -16382, 16383> cpp_complex_quad;\r\n      typedef cpp_complex<237, backends::digit_base_2, void, boost::int32_t, -262142, 262143> cpp_complex_oct;\r\n\r\n#else\r\n\r\n      typedef number<complex_adaptor<cpp_bin_float<50> >, et_off> cpp_complex_50;\r\n      typedef number<complex_adaptor<cpp_bin_float<100> >, et_off> cpp_complex_100;\r\n\r\n      typedef number<complex_adaptor<cpp_bin_float<24, backends::digit_base_2, void, boost::int16_t, -126, 127> >, et_off> cpp_complex_single;\r\n      typedef number<complex_adaptor<cpp_bin_float<53, backends::digit_base_2, void, boost::int16_t, -1022, 1023> >, et_off> cpp_complex_double;\r\n      typedef number<complex_adaptor<cpp_bin_float<64, backends::digit_base_2, void, boost::int16_t, -16382, 16383> >, et_off> cpp_complex_extended;\r\n      typedef number<complex_adaptor<cpp_bin_float<113, backends::digit_base_2, void, boost::int16_t, -16382, 16383> >, et_off> cpp_complex_quad;\r\n      typedef number<complex_adaptor<cpp_bin_float<237, backends::digit_base_2, void, boost::int32_t, -262142, 262143> >, et_off> cpp_complex_oct;\r\n\r\n#endif\r\n\r\n   }\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "c8080b4ab92c5b856167eb2b8cea89aeaa0513b2", "size": 2875, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost/boost/multiprecision/cpp_complex.hpp", "max_stars_repo_name": "YuukiTsuchida/v8_embeded", "max_stars_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 995.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z", "max_issues_repo_path": "externals/boost/boost/multiprecision/cpp_complex.hpp", "max_issues_repo_name": "YuukiTsuchida/v8_embeded", "max_issues_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z", "max_forks_repo_path": "externals/boost/boost/multiprecision/cpp_complex.hpp", "max_forks_repo_name": "YuukiTsuchida/v8_embeded", "max_forks_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z", "avg_line_length": 58.6734693878, "max_line_length": 241, "alphanum_fraction": 0.7370434783, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143955, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.538871461160811}}
{"text": "#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <string>\n#include <Eigen/Dense>\n#include \"include/sample_network.h\"\n\nusing namespace Eigen;\n\nint main()\n{\n    using namespace MyDL;\n    using std::cout;\n    using std::endl;\n    using std::vector;\n    using std::unordered_map;\n\n    // I/O containers\n    vector<MatrixXd> inputs;\n    vector<MatrixXd> outputs;\n    MatrixXd X = -2 * MatrixXd::Identity(2, 2) + MatrixXd::Ones(2, 2);\n    MatrixXd t = MatrixXd::Identity(2, 2);\n    inputs.push_back(X);\n\n    // Define MLP(2-Layer)\n    TwoLayerNet net(2, 3, 2, 0.01);\n\n    cout << \"--- predict ---\" << endl;\n    outputs = net.predict(inputs);\n    cout << outputs[0] << endl;\n\n    cout << \"--- loss ---\" << endl;\n    inputs.push_back(t);\n    outputs = net.loss(inputs);\n    cout << outputs[0] << endl;\n\n    cout << \"--- accuracy ---\" << endl;\n    double accuracy = net.accuracy(inputs);\n    cout << accuracy << endl;\n\n    cout << \"--- gradient ---\" << endl;\n    unordered_map<string, MatrixXd> grads;\n    grads = net.gradient(inputs);\n\n    for (auto grad: grads)\n    {\n        cout << grad.first << endl;\n        cout << grad.second << endl;\n    }\n\n    // cout << \"--- numerical gradient ---\" << endl;\n    // grads = net.numerical_gradient(inputs);\n    \n    // for (auto grad : grads)\n    // {\n    //     cout << grad.first << endl;\n    //     cout << grad.second << endl;\n    // }\n\n    // \u52fe\u914d\u66f4\u65b0\u78ba\u8a8d\n    for (int i = 0; i<5; i++){\n        cout << *(net.params[\"b2\"]) << endl;\n        *(net.params[\"b2\"]) -= grads[\"b2\"];\n        cout << \"--- parameter b2 ---\" << endl;\n        cout << *(net.params[\"b2\"]) << endl;\n    }\n\n    return 0;\n}", "meta": {"hexsha": "f73e5d86956063ab36aee7a8a3b92da595703c5f", "size": 1647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/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": "test/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": "test/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": 23.8695652174, "max_line_length": 70, "alphanum_fraction": 0.5415907711, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5388714576937323}}
{"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_LOG_10_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_LOG_10_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    Generates constant Log_10 : \\f$\\log(10)\\f$\n\n    @par Semantic:\n\n    @code\n    T r = Log_10<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n      r =  T(2.302585092994045684017991454684364207601101488628773);\n    @endcode\n\n\n**/\n  template<typename T> T Log_10();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Generates constant Log_10. (\\f$\\log(10)\\f$)\n\n      Generate the  constant log_10.\n\n      @return The Log_10 constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::log_10_> log_10 = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/log_10.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": "8833f1c1fdee95f8ee1df9a664503d880f051503", "size": 1357, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/log_10.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/log_10.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/log_10.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": 22.2459016393, "max_line_length": 100, "alphanum_fraction": 0.5924834193, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5388554169097682}}
{"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_FOURTHROOTEPS_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_FOURTHROOTEPS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate the 4th root of constant @ref Eps : \\f$\\sqrt[4]\\epsilon\\f$.\n\n    @par Semantic:\n\n    @code\n    T r = Fourthrooteps<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    if T is integral\n      r = T(1)\n    else if T is double\n      r =  pow(2.0, -13);\n    else if T is float\n      r =  pow(2.0f, -5.75f);\n    @endcode\n\n    @return The Fourthrooteps constant for the proper type\n  **/\n  template<typename T> T Fourthrooteps();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant fourthrooteps.\n\n      @return The Fourthrooteps constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::fourthrooteps_> fourthrooteps = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/fourthrooteps.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": "47c06b8d3ea9f4cfcee2a13f492820d16fceebdf", "size": 1527, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/fourthrooteps.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/fourthrooteps.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/fourthrooteps.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.0327868852, "max_line_length": 100, "alphanum_fraction": 0.5992141454, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.5388554093132724}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// percentage_effective_sample_size.hpp                                      //\n//                                                                           //\n//  Copyright 2008 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_ACCUMULATORS_STATISTICS_PERCENTAGE_EFFECTIVE_SAMPLE_SIZE_HPP_ER_2008_04\n#define BOOST_ACCUMULATORS_STATISTICS_PERCENTAGE_EFFECTIVE_SAMPLE_SIZE_HPP_ER_2008_04\n#include <cmath>\n\n#include <boost/mpl/size_t.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/placeholders.hpp>\n\n#include <boost/call_traits.hpp>\n#include <boost/array.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/type_traits/add_const.hpp>\n#include <boost/numeric/conversion/converter.hpp>\n\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n#include <boost/accumulators/statistics/integrated_acvf.hpp>\n#include <boost/accumulators/statistics/acv0.hpp>\n\nnamespace boost { namespace accumulators\n{\n\n\nnamespace impl\n{\n    ////////////////////////////////////////////////////////////////////////////\n    // percentage_effective_sample_size\n    template<typename T,typename I>\n    class percentage_effective_sample_size_impl\n      : public accumulator_base\n    {\n    public:\n        typedef std::size_t result_type;\n\n        percentage_effective_sample_size_impl(dont_care):val(0){}\n\n        template<typename Args>\n        void operator()(const Args& args)\n        {\n            T iacvf = integrated_acvf<I>(args[accumulator]);\n            if(iacvf>static_cast<T>(0)){\n\n                typedef boost::numeric::converter<result_type,T> T2res;\n                T acv0_val = acv0<I>(args[accumulator]);\n                T tmp = static_cast<T>(100)*acv0_val/iacvf;\n                val = T2res::convert(tmp);\n            }else{\n                val = 0;\n            }\n        }\n\n        result_type result(dont_care) const\n        {\n            return val;\n        }\n    private:\n        result_type val;\n    };\n\n} // namespace impl\n///////////////////////////////////////////////////////////////////////////////\n// tag::integrated_acvf\n//\n\nnamespace tag\n{\n    template <typename I = default_delay_discriminator>\n    struct percentage_effective_sample_size\n      : depends_on<acv0<I>, integrated_acvf<I> >\n    {\n        /// INTERNAL ONLY\n      typedef\n        accumulators::impl::percentage_effective_sample_size_impl<\n            mpl::_1,I> impl;\n\n    };\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::percentage_effective_sample_size\n//\n\nnamespace extract\n{\n\n//  extractor<tag::percentage_effective_sample_size<> >\n//    const percentage_effective_sample_size = {};\n\n  // see acvf about default_delay_discriminator\n  template<typename I,typename AccumulatorSet>\n  typename mpl::apply<\n    AccumulatorSet,tag::percentage_effective_sample_size<I>\n    >::type::result_type\n  percentage_effective_sample_size(AccumulatorSet const& acc){\n    typedef tag::percentage_effective_sample_size<I> the_tag;\n    return extract_result<the_tag>(acc);\n  }\n\n//  TODO\n//  overload (default) see acvf\n\n}\n\nusing extract::percentage_effective_sample_size;\n}}\n#endif\n", "meta": {"hexsha": "450fa091dabf99b159b4cfe2de5d399a29859bf5", "size": 3781, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "autocovariance/boost/accumulators/statistics/percentage_effective_sample_size.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": "autocovariance/boost/accumulators/statistics/percentage_effective_sample_size.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": "autocovariance/boost/accumulators/statistics/percentage_effective_sample_size.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": 31.2479338843, "max_line_length": 85, "alphanum_fraction": 0.6077757207, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5388554045884321}}
{"text": "// Copyright (C) 2017-2019 Chris N. Richardson and Garth N. Wells\n//\n// This file is part of FEniCS-miniapp (https://www.fenicsproject.org)\n//\n// SPDX-License-Identifier:    MIT\n\n#include \"poisson_problem.h\"\n#include \"Poisson.h\"\n#include <Eigen/Dense>\n#include <cfloat>\n#include <dolfinx/common/Timer.h>\n#include <dolfinx/fem/DirichletBC.h>\n#include <dolfinx/fem/Function.h>\n#include <dolfinx/fem/FunctionSpace.h>\n#include <dolfinx/fem/assembler.h>\n#include <dolfinx/fem/petsc.h>\n#include <dolfinx/fem/utils.h>\n#include <dolfinx/la/PETScMatrix.h>\n#include <dolfinx/la/PETScVector.h>\n#include <dolfinx/mesh/Mesh.h>\n#include <memory>\n#include <utility>\n\nstd::tuple<dolfinx::la::PETScMatrix, dolfinx::la::PETScVector,\n           std::shared_ptr<dolfinx::fem::Function<PetscScalar>>>\npoisson::problem(std::shared_ptr<dolfinx::mesh::Mesh> mesh)\n{\n  dolfinx::common::Timer t0(\"ZZZ FunctionSpace\");\n\n  auto V = dolfinx::fem::create_functionspace(\n      create_functionspace_form_Poisson_a, \"u\", mesh);\n\n  t0.stop();\n\n  dolfinx::common::Timer t1(\"ZZZ Assemble\");\n\n  // Define boundary condition\n  auto u0 = std::make_shared<dolfinx::fem::Function<PetscScalar>>(V);\n  std::fill(u0->x()->mutable_array().begin(), u0->x()->mutable_array().end(),\n            0.0);\n\n  const std::vector<std::int32_t> bdofs\n      = dolfinx::fem::locate_dofs_geometrical({*V}, [](auto& x) {\n          return (x.row(0) < DBL_EPSILON or x.row(0) > 1.0 - DBL_EPSILON);\n        });\n\n  auto bc = std::make_shared<dolfinx::fem::DirichletBC<PetscScalar>>(u0, bdofs);\n\n  // Define coefficients\n  auto f = std::make_shared<dolfinx::fem::Function<PetscScalar>>(V);\n  auto g = std::make_shared<dolfinx::fem::Function<PetscScalar>>(V);\n  f->interpolate([](auto& x) {\n    auto dx = x.row(0) - 0.5;\n    auto dy = x.row(1) - 0.5;\n    return 10 * (-(dx * dx + dy * dy).exp() / 0.02);\n  });\n  g->interpolate([](auto& x) {\n    {\n      return (5.0 * x.row(0)).sin();\n    }\n  });\n\n  // Define variational forms\n  auto L = dolfinx::fem::create_form<PetscScalar>(create_form_Poisson_L, {V},\n                                                  {{\"f\", f}, {\"g\", g}}, {}, {});\n  auto a = dolfinx::fem::create_form<PetscScalar>(create_form_Poisson_a, {V, V},\n                                                  {}, {}, {});\n\n  // Create matrices and vector, and assemble system\n  dolfinx::la::PETScMatrix A(dolfinx::fem::create_matrix(*a), false);\n  dolfinx::la::PETScVector b(*L->function_spaces()[0]->dofmap()->index_map,\n                             L->function_spaces()[0]->dofmap()->index_map_bs());\n\n  MatZeroEntries(A.mat());\n  dolfinx::common::Timer t2(\"ZZZ Assemble matrix\");\n  dolfinx::fem::assemble_matrix(dolfinx::la::PETScMatrix::add_fn(A.mat()), *a,\n                                {bc});\n  dolfinx::fem::add_diagonal(dolfinx::la::PETScMatrix::add_fn(A.mat()), *V,\n                             {bc});\n  MatAssemblyBegin(A.mat(), MAT_FINAL_ASSEMBLY);\n  MatAssemblyEnd(A.mat(), MAT_FINAL_ASSEMBLY);\n  t2.stop();\n\n  VecSet(b.vec(), 0.0);\n  VecGhostUpdateBegin(b.vec(), INSERT_VALUES, SCATTER_FORWARD);\n  VecGhostUpdateEnd(b.vec(), INSERT_VALUES, SCATTER_FORWARD);\n\n  dolfinx::common::Timer t3(\"ZZZ Assemble vector\");\n  dolfinx::fem::assemble_vector_petsc(b.vec(), *L);\n  dolfinx::fem::apply_lifting_petsc(b.vec(), {a}, {{bc}}, {}, 1.0);\n  VecGhostUpdateBegin(b.vec(), ADD_VALUES, SCATTER_REVERSE);\n  VecGhostUpdateEnd(b.vec(), ADD_VALUES, SCATTER_REVERSE);\n  dolfinx::fem::set_bc_petsc(b.vec(), {bc}, nullptr);\n  t3.stop();\n\n  t1.stop();\n\n  // Create Function to hold solution\n  auto u = std::make_shared<dolfinx::fem::Function<PetscScalar>>(V);\n\n  return {std::move(A), std::move(b), u};\n}\n", "meta": {"hexsha": "6643566874d322257b1bb61869b1551716e7e264", "size": 3641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/poisson_problem.cpp", "max_stars_repo_name": "chrisrichardson/performance-test", "max_stars_repo_head_hexsha": "80e82ac7387934c3b9eb06e94ed801f69248397f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/poisson_problem.cpp", "max_issues_repo_name": "chrisrichardson/performance-test", "max_issues_repo_head_hexsha": "80e82ac7387934c3b9eb06e94ed801f69248397f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/poisson_problem.cpp", "max_forks_repo_name": "chrisrichardson/performance-test", "max_forks_repo_head_hexsha": "80e82ac7387934c3b9eb06e94ed801f69248397f", "max_forks_repo_licenses": ["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.3495145631, "max_line_length": 80, "alphanum_fraction": 0.633891788, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5388554045884321}}
{"text": "/*\n * TypeDefs.hpp\n *\n *  Created on: March 18, 2014\n *      Author: P\u00e9ter Fankhauser\n *\t Institute: ETH Zurich, ANYbotics\n */\n\n// Eigen\n#include <Eigen/Core>\n\n#pragma once\n\nnamespace grid_map {\n\n  typedef Eigen::MatrixXf Matrix;\n  typedef Matrix::Scalar DataType;\n  typedef Eigen::Vector2d Position;\n  typedef Eigen::Vector2d Vector;\n  typedef Eigen::Vector3d Position3;\n  typedef Eigen::Vector3d Vector3;\n  typedef Eigen::Array2i Index;\n  typedef Eigen::Array2i Size;\n  typedef Eigen::Array2d Length;\n  typedef uint64_t Time;\n\n  /*\n   * Interpolations are ordered in the order\n   * of increasing accuracy and computational complexity.\n   * INTER_NEAREST - fastest, but least accurate,\n   * INTER_CUBIC - slowest, but the most accurate.\n   * see:\n   * https://en.wikipedia.org/wiki/Bicubic_interpolation\n   * https://web.archive.org/web/20051024202307/http://www.geovista.psu.edu/sites/geocomp99/Gc99/082/gc_082.htm\n   * for more info. Cubic convolution algorithm is also known as piecewise cubic\n   * interpolation and in general does not guarantee continuous\n   * first derivatives.\n   */\n  enum class InterpolationMethods{\n      INTER_NEAREST, // nearest neighbor interpolation\n      INTER_LINEAR,   // bilinear interpolation\n      INTER_CUBIC_CONVOLUTION, //piecewise bicubic interpolation using convolution algorithm\n      INTER_CUBIC // standard bicubic interpolation\n  };\n\n} /* namespace */\n", "meta": {"hexsha": "7e19c63fc00bd89c2e3f593b9fe8c9ebd68bde6d", "size": 1399, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid_map_core/include/grid_map_core/TypeDefs.hpp", "max_stars_repo_name": "fmrico/grid_map", "max_stars_repo_head_hexsha": "73ea27f5326ba920a5eeada6b2b4925d14abcb51", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1305.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T14:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:44:18.000Z", "max_issues_repo_path": "grid_map_core/include/grid_map_core/TypeDefs.hpp", "max_issues_repo_name": "fmrico/grid_map", "max_issues_repo_head_hexsha": "73ea27f5326ba920a5eeada6b2b4925d14abcb51", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 174.0, "max_issues_repo_issues_event_min_datetime": "2018-08-06T21:41:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T04:45:09.000Z", "max_forks_repo_path": "grid_map_core/include/grid_map_core/TypeDefs.hpp", "max_forks_repo_name": "fmrico/grid_map", "max_forks_repo_head_hexsha": "73ea27f5326ba920a5eeada6b2b4925d14abcb51", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 423.0, "max_forks_repo_forks_event_min_datetime": "2018-08-07T13:37:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:07:26.000Z", "avg_line_length": 29.7659574468, "max_line_length": 111, "alphanum_fraction": 0.7319513939, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5388287761870546}}
{"text": "// Copyright (c) 2015\n// Author: Chrono Law\n#include <std.hpp>\n#include <type_traits>\nusing namespace std;\n\n//////////////////////////////////////////\n\n#include <boost/integer_traits.hpp>\nusing namespace boost;\n\nvoid case1()\n{\n    cout << integer_traits<int >::const_max << endl;\n    cout << integer_traits<bool>::const_min << endl;\n    cout << integer_traits<long>::is_signed << endl;\n}\n\n//////////////////////////////////////////\n\n#include <boost/cstdint.hpp>\n#include <limits>\n\nvoid case2()\n{\n    uint8_t         u8;\n    int_fast16_t    i16;\n    int_least32_t   i32;\n    uintmax_t       um;\n\n    u8  = 255;\n    i16 = 32000;\n    i32 = i16;\n    um  = u8 + i16 + i32;\n\n    assert(sizeof(u8) == 1);\n\n    cout << \"u8 :\" << sizeof(u8)\n        << \" v = \"<< (short)u8 << endl;\n    cout << \"i16 :\" << sizeof(i16)\n        << \" v = \"<< i16 << endl;\n    cout << \"i32 :\" << sizeof(i32)\n        << \" v = \"<< i32 << endl;\n    cout << \"um :\" << sizeof(um)\n        << \" v = \"<< um << endl;\n\n    cout << (short)numeric_limits<int8_t>::max() << endl;\n    cout << numeric_limits<uint_least16_t>::max() << endl;\n    cout << numeric_limits<int_fast32_t>::max() << endl;\n    cout << numeric_limits<intmax_t>::min() << endl;\n}\n\n//////////////////////////////////////////\n\n#include <boost/integer.hpp>\n#include <boost/type_index.hpp>\n\nvoid case3()\n{\n    typedef int_fast_t<char>::fast cfast;\n    cout << typeindex::type_id<cfast>().pretty_name() << endl;\n\n    typedef int_fast_t<int>::fast ifast;\n    cout << typeindex::type_id<ifast>().pretty_name() << endl;\n\n    typedef int_fast_t<uint16_t>::fast u16fast;\n    cout << typeindex::type_id<u16fast>().pretty_name() << endl;\n}\n\n//////////////////////////////////////////\n\n#include <boost/format.hpp>\n\ntemplate<typename T>\nstring type_name()\n{\n    return typeindex::type_id<T>().pretty_name();\n}\n\nvoid case4()\n{\n    format fmt(\"type:%s,size=%dbit\\n\"); //\u4e00\u4e2aformat\u5bf9\u8c61\n\n    typedef uint_t<15>::fast u15;                 //\u53ef\u5bb9\u7eb315\u4f4d\u7684\u65e0\u7b26\u53f7\u6700\u5feb\u6574\u6570\n    cout << fmt % type_name<u15>() % (sizeof(u15) * 8) ;\n\n    typedef int_max_value_t<32700>::fast i32700;     //\u53ef\u5904\u740632700\u7684\u6700\u5feb\u6574\u6570\n    cout << fmt % type_name<i32700>() % (sizeof(i32700) * 8);\n\n    typedef int_min_value_t<-33000>::fast i33000;        //\u53ef\u5904\u7406-33000\u7684\u6700\u5feb\u6574\u6570\n    cout << fmt % type_name<i33000>() % (sizeof(33000) * 8);\n\n    typedef uint_value_t<33000>::fast u33000;            //\u53ef\u5904\u740633000\u7684\u6700\u5feb\u65e0\u7b26\u53f7\u6574\u6570\n    cout << fmt % type_name<u33000>() % (sizeof(u33000) * 8);\n}\n\nint main()\n{\n    case1();\n    case2();\n    case3();\n    case4();\n}\n\n", "meta": {"hexsha": "dcc59097aaa1e388894a2eff16879b0723896d02", "size": 2494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/integer.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/integer.cpp", "max_issues_repo_name": "xujungp02/boost_guide", "max_issues_repo_head_hexsha": "328516455d334506f824402455a17afc606ca3bc", "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/integer.cpp", "max_forks_repo_name": "xujungp02/boost_guide", "max_forks_repo_head_hexsha": "328516455d334506f824402455a17afc606ca3bc", "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": 23.7523809524, "max_line_length": 75, "alphanum_fraction": 0.5473135525, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5388287547375181}}
{"text": "#include <cstdio>\n#include <boost/math/distributions/beta.hpp>\n\n#include <iostream>\n#include <string>\n#include <map>\n#include <random>\n\nusing namespace boost::math;\nusing namespace std;\n\nint main() {\n\tsrand(time(0));\n\tdouble alpha = 0.5, beta = 0.5;\n\tbeta_distribution<> dist(alpha, beta);\n\n\tfor (int i = 0 ; i < 1000 ; i++) {\n\t\tdouble rngfloat = (double)(rand() % 101) / 100;\n\t\tcout<<\" \"<<quantile(dist, rngfloat)<<endl;\n\t}\n}\n", "meta": {"hexsha": "8af80d8c5aee300ac99a03d12953be2e84565e3b", "size": 427, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/randomNumber_beta_distribution.cpp", "max_stars_repo_name": "jxtopher/quick-codes", "max_stars_repo_head_hexsha": "577711394f3f338c061f1e53df875d958c645071", "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/randomNumber_beta_distribution.cpp", "max_issues_repo_name": "jxtopher/quick-codes", "max_issues_repo_head_hexsha": "577711394f3f338c061f1e53df875d958c645071", "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/randomNumber_beta_distribution.cpp", "max_forks_repo_name": "jxtopher/quick-codes", "max_forks_repo_head_hexsha": "577711394f3f338c061f1e53df875d958c645071", "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.4090909091, "max_line_length": 49, "alphanum_fraction": 0.6510538642, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5387546026015599}}
{"text": "#pragma once\n\n#include <Eigen/Sparse>\n#include <vector>\n\n#include \"mtao/eigen/shape_checks.hpp\"\n#include \"mtao/geometry/volume.hpp\"\n\nnamespace mtao::simulation::simplicial {\ntemplate <typename VDerived, typename SDerived>\nEigen::SparseMatrix<typename VDerived::Scalar> laplacian(\n    const Eigen::MatrixBase<VDerived>& V, const Eigen::MatrixBase<SDerived>& S);\n\nnamespace internal {\n    // NOTE: yes we do have a second impl in mtao/geometry/mesh/laplacian.hpp\ntemplate <typename VDerived, typename SDerived>\nEigen::SparseMatrix<typename VDerived::Scalar> laplacian2(\n    const Eigen::MatrixBase<VDerived>& V,\n    const Eigen::MatrixBase<SDerived>& S) {\n    using Scalar = typename VDerived::Scalar;\n    if (S.size() == 0) {\n        return {};\n    }\n    int size = S.maxCoeff() + 1;\n    Eigen::SparseMatrix<Scalar> L(size, size);\n    std::vector<Eigen::Triplet<Scalar>> trips;\n    trips.reserve(4 * 3 * S.cols());\n    eigen::row_check<3>(S);\n    assert(V.cols() >= size);\n\n    for (int sidx = 0; sidx < S.cols(); ++sidx) {\n        auto s = S.col(sidx);\n        for (int j = 0; j < S.rows(); ++j) {\n            const auto ai = s(j);\n            const auto bi = s((j + 1) % 3);\n            const auto ci = s((j + 2) % 3);\n            auto a = V.col(ai);\n            auto b = V.col(bi);\n            auto c = V.col(ci);\n            auto u = b - a;\n            auto v = c - a;\n\n            Scalar dot = u.dot(v);\n            Scalar cross;\n            if constexpr (VDerived::RowsAtCompileTime == 2) {\n                cross = u.x() * v.y() - u.y() * v.x();\n            } else if constexpr (VDerived::RowsAtCompileTime == 3) {\n                cross = u.cross(v);\n            }\n            Scalar val = std::abs(.5 * dot / cross);\n            trips.emplace_back(bi, ci, -val);\n            trips.emplace_back(ci, bi, -val);\n            trips.emplace_back(bi, bi, val);\n            trips.emplace_back(ci, ci, val);\n        }\n    }\n    L.setFromTriplets(trips.begin(), trips.end());\n    return L;\n}\n\n\n\ntemplate <typename VDerived, typename SDerived>\nEigen::SparseMatrix<typename VDerived::Scalar> laplacian3(\n    const Eigen::MatrixBase<VDerived>& V,\n    const Eigen::MatrixBase<SDerived>& S) {\n    using Scalar = typename VDerived::Scalar;\n    if (S.size() == 0) {\n        return {};\n    }\n    int size = S.maxCoeff() + 1;\n    Eigen::SparseMatrix<Scalar> L(size, size);\n    std::vector<Eigen::Triplet<Scalar>> trips;\n    trips.reserve(4 * 4 * S.cols());\n\n    eigen::row_check<4>(S);\n    eigen::row_check<3>(V);\n\n    auto vols = geometry::volumes(V, S);\n\n    assert(V.cols() >= size);\n    for (int sidx = 0; sidx < S.cols(); ++sidx) {\n        auto s = S.col(sidx);\n        auto vol = vols(sidx);\n        mtao::Matrix<Scalar, 3, 4> N;\n\n        for (int j = 0; j < S.rows(); ++j) {\n            const auto ai = s(j);\n            const auto bi = s((j + 1) % 4);\n            const auto ci = s((j + 2) % 4);\n            const auto di = s((j + 3) % 4);\n            auto a = V.col(ai);\n            auto b = V.col(bi);\n            auto c = V.col(ci);\n            auto d = V.col(di);\n            auto u = c - b;\n            auto v = d - b;\n            auto n = N.col(j);\n            n = u.cross(v);\n            n.normalize();\n            Scalar len = (a - b).dot(n);\n            if (len < 0) {\n                n *= -len * len;\n            } else {\n                n *= len * len;\n            }\n        }\n        for (int j = 0; j < S.rows(); ++j) {\n            const auto ai = s(j);\n            auto na = N.col(j);\n            for (int k = j+1; k < S.rows(); ++k) {\n                const auto bi = s(k);\n                auto nb = N.col(k);\n                Scalar val = vol * na.dot(nb);\n                trips.emplace_back(ai, bi, -val);\n                trips.emplace_back(bi, ai, -val);\n                trips.emplace_back(ai, ai, val);\n                trips.emplace_back(bi, bi, val);\n            }\n        }\n    }\n    L.setFromTriplets(trips.begin(), trips.end());\n    return L;\n}\n}  // namespace internal\n\ntemplate <typename VDerived, typename SDerived>\nEigen::SparseMatrix<typename VDerived::Scalar> laplacian(\n    const Eigen::MatrixBase<VDerived>& V,\n    const Eigen::MatrixBase<SDerived>& S) {\n    // TODO: make this use V with constant col sizes\n    if constexpr(SDerived::RowsAtCompileTime == 3) {\n        return internal::laplacian2(V, S);\n    } else if constexpr(SDerived::RowsAtCompileTime == 4) {\n        return internal::laplacian3(V, S);\n    }\n    return {};\n}\n\n}  // namespace mtao::simulation::simplicial\n", "meta": {"hexsha": "92eefd0d206b9ef8d9b5be30ca629af038c02e83", "size": 4500, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/simulation/simplicial/laplacian.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/simulation/simplicial/laplacian.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/simulation/simplicial/laplacian.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.914893617, "max_line_length": 80, "alphanum_fraction": 0.5213333333, "num_tokens": 1257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5387085595169977}}
{"text": "/**\n * August 8th, 2018\n * source: https://zhuanlan.zhihu.com/p/38745950\n * Constant velocity prediction Kalman filter for shield local position\n */\n\n#include <iostream>\n#include <ros/ros.h>\n#include <std_msgs/String.h>\n#include <geometry_msgs/TwistStamped.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include \"rm_cv/ArmorRecord.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nstring visual_topic, publisher_topic, debug_topic, real_visual_topic, transform_topic;\nros::Publisher filter_pub, debug_pub, transform_pub;\nMatrixXd imu_R_camera = MatrixXd::Identity(3, 3); // rotation matrix from camera to imu\nVector3d imu_T_camera = MatrixXd::Zero(3, 1);\n\nVectorXd x(6);      // state\nMatrixXd P = MatrixXd::Identity(6, 6); // covariance\nMatrixXd Q = MatrixXd::Identity(6, 6); // prediction noise covariance\nMatrixXd R = MatrixXd::Identity(3, 3); // observation noise covariance\nMatrixXd A = MatrixXd::Identity(6, 6); // state transfer function\n\nbool visual_initialized = false, visual_valid = false;\n\nros::Time t_prev;\ndouble R_pos, Q_pos, Q_vel, P_weight;\nconst double CV_UPDATE_TIME_MAX = 0.1; // maxium allowed update time\nconst double DELAY_MAX = 0.05;\nconst int ROS_FREQ = 100;\ndouble OUTLIER_THRESHOLD = 10000.0;\n\nVector3d camera_T_shield_prev = MatrixXd::Zero(3, 1);\nVector3d imu_T_shield_prev = MatrixXd::Zero(3, 1);\nbool vel_is_outlier = false;\ndouble chi_square = 0;\ndouble outlier_l2_norm_ratio = 1.5;\ndouble yaw_delay = 0.0;\ndouble pitch_delay = 0.0;\nVector3d OUTPUT_BOUND = MatrixXd::Zero(3, 1);;\n\nstatic void pub_result(const ros::Time &stamp, double delay_dt)\n{\n//    geometry_msgs::TwistStamped odom;\n    rm_cv::ArmorRecord odom;\n    odom.header.stamp = stamp;\n    double predict_x = x(0) + (delay_dt + yaw_delay)   * x(3);\n    double predict_y = x(1) + (delay_dt + pitch_delay) * x(4);\n    double predict_z = x(2) + delay_dt * x(5);\n    odom.armorPose.linear.x  = (predict_x < OUTPUT_BOUND[0]) ? predict_x * 1000 : OUTPUT_BOUND[0] * 1000;\n    odom.armorPose.linear.y  = (predict_y < OUTPUT_BOUND[1]) ? predict_y * 1000 : OUTPUT_BOUND[1] * 1000;\n    odom.armorPose.linear.z  = (predict_z < OUTPUT_BOUND[2]) ? predict_z * 1000 : OUTPUT_BOUND[2] * 1000;\n    odom.armorPose.angular.x = x(3) * 1000;\n    odom.armorPose.angular.y = x(4) * 1000;\n    odom.armorPose.angular.z = x(5) * 1000;\n    filter_pub.publish(odom);\n}\n\nstatic void pub_preprocessed(const std_msgs::Header &header,\n                      const Ref<const Vector3d> p,\n                      const Ref<const Vector3d> v,\n                      ros::Publisher &publisher)\n{\n    geometry_msgs::TwistStamped debug;\n    debug.header = header;\n    debug.twist.linear.x  = p[0] * 1000;\n    debug.twist.linear.y  = p[1] * 1000;\n    debug.twist.linear.z  = p[2] * 1000;\n    debug.twist.angular.x = v[0] * 1000;\n    debug.twist.angular.y = v[1] * 1000;\n    debug.twist.angular.z = v[2] * 1000;\n    publisher.publish(debug);\n}\n\n// Chi-square test for outlier rejection\nstatic bool velocity_is_outlier(const Vector3d &pos)\n{\n    VectorXd r = MatrixXd::Zero(3, 1);\n    VectorXd z = MatrixXd::Zero(3, 1);\n    MatrixXd S = MatrixXd::Zero(3, 3);\n    z << pos[0], pos[1], pos[2];\n\n    double pos_norm   = z.segment<3>(0).norm();\n    double state_norm = x.segment<3>(0).norm();\n    ROS_INFO(\"pos_norm %f, state_norm %f\", pos_norm, state_norm);\n    if (pos_norm > state_norm * outlier_l2_norm_ratio) {\n        return true;\n    } else if (pos_norm < state_norm / outlier_l2_norm_ratio) {\n        return true;\n    }\n\n    // r = z - H * x, residual\n    // S = H P H' + R, residual covariance\n    MatrixXd H = MatrixXd::Identity(3, 6); // observation matrix\n\n//    MatrixXd K_next = (H * P * H.transpose() + R).ldlt().solve(P * H.transpose());\n//    MatrixXd x_next = x + K_next * (z - H * x);\n//    MatrixXd P_next = P - K_next * H * P;\n\n    r = z - H * x;\n    S = H * P * H.transpose() + R;\n    chi_square = r.transpose() * S * r;\n    // cout << \"chi_square \" << endl << chi_square << endl;\n\n    return (chi_square > OUTLIER_THRESHOLD);\n}\n\nstatic void preprocess_visual(const std_msgs::Header &header,\n                              const geometry_msgs::Twist &twist,\n                              Vector3d &pos, double dt_update)\n{\n\n    Vector3d camera_T_shield, camera_vel_shield, imu_T_shield, imu_vel_shield;\n\n    camera_T_shield[0] = twist.linear.x;\n    camera_T_shield[1] = twist.linear.y;\n    camera_T_shield[2] = twist.linear.z;\n\n    camera_T_shield *= 0.001; // Convert millimeter to meter\n\n    // calculate and check the velocity\n    camera_vel_shield = (camera_T_shield - camera_T_shield_prev) / dt_update;\n    camera_T_shield_prev = camera_T_shield;\n\n    vel_is_outlier = velocity_is_outlier(camera_T_shield);\n\n    if (vel_is_outlier) {\n        pos = x.segment<3>(0);\n        ROS_INFO(\"outlier rejected\");\n    }\n    else {\n        pos = camera_T_shield;\n    }\n\n    // store the state\n    pub_preprocessed(header, camera_T_shield, camera_vel_shield, debug_pub);\n\n    imu_T_shield = imu_R_camera * camera_T_shield + imu_T_camera * 0.001;\n    imu_vel_shield = (imu_T_shield - imu_T_shield_prev) / dt_update;\n    imu_T_shield_prev = imu_T_shield;\n    pub_preprocessed(header, imu_T_shield, imu_vel_shield, transform_pub);\n}\n\nstatic void propagate(const double &dt) {\n    A.topRightCorner(3, 3) = dt * MatrixXd::Identity(3, 3);\n    // cout << \"A \" << endl << A << endl;\n    x = A * x;\n    P = A * P * A.transpose() + Q;\n    // cout << \"P \" << endl << P << endl;\n}\n\nstatic void update(const Vector3d &pos)\n{\n    MatrixXd H, K, z;\n\n    H = MatrixXd::Identity(3, 6); // observation matrix\n    K = P * H.transpose() * (H * P * H.transpose() + R).inverse();\n    z = MatrixXd::Zero(3, 1);\n    z << pos[0], pos[1], pos[2];\n\n    x = x + K * (z - H * x);\n    P = P - K * H * P;\n}\n\n\n/**\n * initialization of the state and convariance from visual\n * @param pnp\n */\nstatic void initialize_visual(const std_msgs::Header &header,\n                              const geometry_msgs::Twist &twist)\n{\n    ros::Time t_update = header.stamp;\n    ROS_INFO(\"visual init at %f\", t_update.toSec());\n\n    Vector3d camera_T_shield, imu_T_shield;\n    camera_T_shield[0] = twist.linear.x;\n    camera_T_shield[1] = twist.linear.y;\n    camera_T_shield[2] = twist.linear.z;\n    // imu_T_shield = imu_R_camera * camera_T_shield + imu_T_camera;\n    camera_T_shield *= 0.001; // Convert millimeter to meter\n\n    x.segment<3>(0) = camera_T_shield; // init velocity with zero\n    x.segment<3>(3).setZero(); // init velocity with zero\n\n    cout << \"DEBUG: x initialized with \" << endl << x.transpose() << endl;\n    camera_T_shield_prev = camera_T_shield;\n    t_prev = t_update;\n    visual_initialized = true;\n}\n\n/**\n * handle, save, and process visual messages\n * @param pnp\n */\nvoid visual_callback(const geometry_msgs::TwistStamped::ConstPtr &pnp)\n{\n    visual_valid = !(pnp->twist.linear.x == 0 &&\n                     pnp->twist.linear.y == 0 &&\n                     pnp->twist.linear.z == 0 );\n\n    if (visual_valid) {\n        if (!visual_initialized) {\n            initialize_visual(pnp->header, pnp->twist);\n        }\n        else {\n            double running_time = ros::Time::now().toSec();\n            double delay_dt = running_time - pnp->header.stamp.toSec();\n            delay_dt = (delay_dt < DELAY_MAX) ? delay_dt : DELAY_MAX;\n\n            ros::Time t_update = pnp->header.stamp;\n            double dt_update = (t_update - t_prev).toSec();\n            dt_update = (dt_update < CV_UPDATE_TIME_MAX) ? dt_update : CV_UPDATE_TIME_MAX;\n\n            Vector3d pos;\n\n            preprocess_visual(pnp->header, pnp->twist, pos, dt_update);\n\n            update(pos);\n\n            pub_result(pnp->header.stamp, delay_dt);\n            t_prev = t_update;\n        }\n    }\n}\n\n\n/**\n * handle, save, and process visual messages\n * @param armor\n */\nvoid real_visual_cb(const rm_cv::ArmorRecord::ConstPtr &armor)\n{\n    visual_valid = !(armor->armorPose.linear.x == 0 &&\n                     armor->armorPose.linear.y == 0 &&\n                     armor->armorPose.linear.z == 0 );\n\n    if (visual_valid) {\n        if (!visual_initialized) {\n            initialize_visual(armor->header, armor->armorPose);\n        }\n        else {\n\n            double running_time = ros::Time::now().toSec();\n            double delay_dt = running_time - armor->header.stamp.toSec();\n            delay_dt = (delay_dt < DELAY_MAX) ? delay_dt : DELAY_MAX;\n\n            ros::Time t_update = armor->header.stamp;\n            double dt_update = (t_update - t_prev).toSec();\n            dt_update = (dt_update < CV_UPDATE_TIME_MAX) ? dt_update : CV_UPDATE_TIME_MAX;\n\n            Vector3d pos;\n            preprocess_visual(armor->header, armor->armorPose, pos, dt_update);\n\n            update(pos);\n\n            propagate(dt_update);\n\n            pub_result(armor->header.stamp, delay_dt);\n            t_prev = t_update;\n        }\n    }\n\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"prediction_kalman_filter\");\n    ros::NodeHandle n(\"~\");\n\n    n.param(\"visual_topic\", visual_topic, string(\"/pnp_twist\"));\n    n.param(\"real_visual_topic\", real_visual_topic, string(\"/detected_armor\"));\n    n.param(\"publisher_topic\", publisher_topic, string(\"/prediction_kf/predict\"));\n    n.param(\"debug_topic\", debug_topic, string(\"/prediction_kf/preprocessed\"));\n    n.param(\"transform_topic\", transform_topic, string(\"/prediction_kf/transformed\"));\n    n.param(\"chi_square_threshold\", OUTLIER_THRESHOLD, 10000.0);\n    n.param(\"outlier_l2_norm_ratio\", outlier_l2_norm_ratio, 1.5);\n    n.param(\"R_pos\", R_pos, 16.0);\n    n.param(\"Q_pos\", Q_pos, 0.2);\n    n.param(\"Q_vel\", Q_vel, 1.0);\n    n.param(\"P_matrix_weight\", P_weight, 1.0);\n    n.param(\"yaw_delay\", yaw_delay, 0.0);\n    n.param(\"pitch_delay\", pitch_delay, 0.0);\n\n    // For chassis reading only\n    imu_R_camera <<  0, 0, 1,\n                    -1, 0, 0,\n                     0,-1, 0;\n    imu_T_camera <<  110, -70, -40; // in millimeter\n\n    OUTPUT_BOUND << 10.0, 10.0, 10.0;\n\n    x.setZero();\n    R = R_pos * MatrixXd::Identity(3, 3);\n    // R(0, 1) = R_pos * 0.1;\n    // R(0, 2) = R_pos * 0.1;\n    // R(1, 2) = R_pos * 0.1;\n    // R(1, 0) = R_pos * 0.1;\n    // R(2, 0) = R_pos * 0.1;\n    // R(2, 1) = R_pos * 0.1;\n    Q.topLeftCorner(3, 3)     = Q_pos * MatrixXd::Identity(3, 3);\n    Q.bottomRightCorner(3, 3) = Q_vel * MatrixXd::Identity(3, 3);\n    P.topLeftCorner(3, 3)     = P_weight * MatrixXd::Identity(3, 3);\n    // P.topRightCorner(3, 3)    = 0.5 * P_weight * MatrixXd::Identity(3, 3);\n    // P.bottomLeftCorner(3, 3)  = 0.5 * P_weight * MatrixXd::Identity(3, 3);\n    P.bottomRightCorner(3, 3) = 2 * P_weight * MatrixXd::Identity(3, 3);\n    cout << \"R \" << endl << R << endl;\n    cout << \"Q \" << endl << Q << endl;\n    cout << \"P \" << endl << P << endl;\n\n    ros::Subscriber s1 = n.subscribe(visual_topic, 40, visual_callback);\n    ros::Subscriber s2 = n.subscribe(real_visual_topic, 40, real_visual_cb);\n    filter_pub = n.advertise<rm_cv::ArmorRecord>(publisher_topic, 40);\n    debug_pub  = n.advertise<geometry_msgs::TwistStamped>(debug_topic, 40);\n    transform_pub = n.advertise<geometry_msgs::TwistStamped>(transform_topic, 40);\n    ros::Rate r(ROS_FREQ);\n    ros::spin();\n\n}\n", "meta": {"hexsha": "ccba7f43c1b723478cd611df52d74f94e0200194", "size": 11148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3_estimator/history/prediction_kf/src/prediction_kf_node.cpp", "max_stars_repo_name": "huying163/ros_environment", "max_stars_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-01-30T11:40:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T05:52:47.000Z", "max_issues_repo_path": "3_estimator/history/prediction_kf/src/prediction_kf_node.cpp", "max_issues_repo_name": "huying163/ros_environment", "max_issues_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_issues_repo_licenses": ["MIT"], "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_estimator/history/prediction_kf/src/prediction_kf_node.cpp", "max_forks_repo_name": "huying163/ros_environment", "max_forks_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-23T08:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-23T08:14:57.000Z", "avg_line_length": 34.3015384615, "max_line_length": 105, "alphanum_fraction": 0.6266594905, "num_tokens": 3264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5387085595169976}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    cpp_int x; cin >> x;\n    for (int i = -118; i <= 119; i++) {\n        for (int j = -119; j <= 118; j++) {\n            if (i * i * i * i * i - j * j * j * j * j == x) {\n                cout << i << \" \" << j << endl;\n                return 0;\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "7c410d0df73d3f21794f8205e081688fe7184c29", "size": 469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc166/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/abc166/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/abc166/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": 24.6842105263, "max_line_length": 61, "alphanum_fraction": 0.4712153518, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5387085553619365}}
{"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#include <cmath>\n\n#include <boost/random.hpp>\n#include <boost/make_shared.hpp>\n\n#if USE_GSL\n#include <gsl/gsl_qrng.h>\n#endif\n\n#include \"tudat/math/statistics/randomSampling.h\"\nnamespace tudat\n{\n\nnamespace statistics\n{\n\n//! Generate sample of random vectors, with entries of each vector independently, but not identically, distributed.\nstd::vector< Eigen::VectorXd > generateRandomSampleFromGenerator(\n        const int numberOfSamples,\n        const std::vector< std::shared_ptr< RandomVariableGenerator< double > > > randomVariableGenerators )\n{\n    std::vector< Eigen::VectorXd > randomSamples;\n    Eigen::VectorXd randomSample( randomVariableGenerators.size( ) );\n\n    // Generate samples\n    for( int i = 0; i < numberOfSamples; i++ )\n    {\n        for( unsigned int j = 0; j < randomVariableGenerators.size( ); j++ )\n        {\n            randomSample( j ) = randomVariableGenerators.at( j )->getRandomVariableValue( );\n        }\n        randomSamples.push_back( randomSample );\n    }\n\n    return randomSamples;\n}\n\n//! Generate sample of random vectors, with entries of each vector independently and identically distributed.\nstd::vector< Eigen::VectorXd > generateRandomSampleFromGenerator(\n        const int numberOfSamples, const int numberOfDimensions,\n        const std::shared_ptr< RandomVariableGenerator< double > > randomVariableGenerator )\n{\n    std::vector< std::shared_ptr< RandomVariableGenerator< double > > > randomVariableGenerators;\n    for( int i = 0; i < numberOfDimensions; i++ )\n    {\n        randomVariableGenerators.push_back( randomVariableGenerator );\n    }\n\n    return generateRandomSampleFromGenerator( numberOfSamples, randomVariableGenerators );\n}\n\n\n\n//! Generator random vector using pseudo random generator\nstd::vector< Eigen::VectorXd > generateUniformRandomSample(\n        const int seed, const int numberOfSamples,\n        const Eigen::VectorXd& lowerBound, const Eigen::VectorXd& upperBound )\n{\n    if( lowerBound.rows( ) != upperBound.rows( ) )\n    {\n        throw std::runtime_error( \"Error when making uniformly distributed samples, input is inconsistent\" );\n    }\n\n    // Create distributions\n    std::vector< std::shared_ptr< RandomVariableGenerator< double > > > randomVariableGenerators;\n    std::vector< double > currentParameters;\n    for( int i = 0; i < lowerBound.rows( ); i++ )\n    {\n        currentParameters = { lowerBound( i ), upperBound( i ) };\n        randomVariableGenerators.push_back(\n                    createBoostContinuousRandomVariableGenerator(\n                        uniform_boost_distribution, currentParameters, seed + i ) );\n    }\n\n    // Generate samples\n    return generateRandomSampleFromGenerator( numberOfSamples, randomVariableGenerators );\n}\n\n//! Generator random vector using pseudo random generator\nstd::vector< Eigen::VectorXd > generateUniformRandomSample(\n        const int seed, const int numberOfSamples, const int numberOfDimensions,\n         const double lowerBound, const double upperBound )\n{\n    return generateUniformRandomSample(\n                seed, numberOfSamples,\n                Eigen::VectorXd::Constant( numberOfDimensions, lowerBound ),\n                Eigen::VectorXd::Constant( numberOfDimensions, upperBound ) );\n}\n\n\n\n//! Generator random vector using pseudo random generator with gaussian distribution (without correlation)\nstd::vector< Eigen::VectorXd > generateGaussianRandomSample(\n        const int seed, const int numberOfSamples,\n        const Eigen::VectorXd& mean, const Eigen::VectorXd& standardDeviation )\n{\n    if( mean.rows( ) != standardDeviation.rows( ) )\n    {\n        throw std::runtime_error( \"Error when making Gaussian distributed samples, input is inconsistent\" );\n    }\n\n    // Create distributions\n    std::vector< std::shared_ptr< RandomVariableGenerator< double > > > randomVariableGenerators;\n    std::vector< double > currentParameters;\n    for( int i = 0; i < mean.rows( ); i++ )\n    {\n        currentParameters = { mean( i ), standardDeviation( i ) };\n        randomVariableGenerators.push_back(\n                    createBoostContinuousRandomVariableGenerator(\n                        normal_boost_distribution, currentParameters, seed + i ) );\n    }\n\n    // Generate samples\n    return generateRandomSampleFromGenerator( numberOfSamples, randomVariableGenerators );\n}\n\n\n//! Generator random vector using pseudo random generator with gaussian distribution (without correlation)\nstd::vector< Eigen::VectorXd > generateGaussianRandomSample(\n        const int seed, const int numberOfSamples, const int numberOfDimensions,\n        const double mean, const double standardDeviation )\n{\n    return generateGaussianRandomSample(\n                seed, numberOfSamples,\n                Eigen::VectorXd::Constant( numberOfDimensions, mean ),\n                Eigen::VectorXd::Constant( numberOfDimensions, standardDeviation ) );\n}\n\n\n#if USE_GSL\n\n//! Generator random vector using Sobol sampler\nstd::vector< Eigen::VectorXd > generateVectorSobolSample(\n        int numberOfSamples,\n        const Eigen::VectorXd& lowerBound, const Eigen::VectorXd& upperBound )\n{\n    int numberOfDimensions = upperBound.rows( );\n\n    // Compute propertie\n    Eigen::VectorXd width = upperBound - lowerBound;\n    Eigen::VectorXd average = (upperBound + lowerBound)/2.0 ;\n\n    std::vector< Eigen::VectorXd > sobolSamples( numberOfSamples );\n\n    Eigen::VectorXd randomSample( numberOfDimensions ) ;\n    double randomSampleArray[ numberOfDimensions ];\n\n    gsl_qrng * q = gsl_qrng_alloc (gsl_qrng_sobol, numberOfDimensions );\n\n    // Loop over samples\n    for( int j = 0 ; j < numberOfSamples ; j++ )\n    {\n        gsl_qrng_get( q, randomSampleArray ); // Generate sobol [0,1]\n\n        // Fill vector\n        for( int i = 0 ; i < numberOfDimensions ; i++ )\n        {\n            randomSample( i ) = randomSampleArray[ i ] - 0.5 ;\n        }\n        sobolSamples[ j ] = randomSample.cwiseProduct( width ) + average ; // Save vector\n    }\n\n    gsl_qrng_free (q); // Deallocate GSL variables\n\n    return sobolSamples;\n}\n\n//! Generator random vector using Sobol sampler\nstd::vector< Eigen::VectorXd > generateVectorSobolSample(\n        const int numberOfDimensions, int numberOfSamples,\n        const double lowerBound, const double upperBound )\n{\n    return generateVectorSobolSample( numberOfSamples,\n                                      Eigen::VectorXd::Constant( numberOfDimensions, lowerBound ),\n                                      Eigen::VectorXd::Constant( numberOfDimensions, upperBound ) );\n}\n#endif\n\n} // Close Namespace statistics\n\n} // Close Namespace tudat\n\n", "meta": {"hexsha": "a1d3f7e87c98a4766f46b5d4b2247edabe3f93b9", "size": 7003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/statistics/randomSampling.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": "src/math/statistics/randomSampling.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": "src/math/statistics/randomSampling.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": 36.2849740933, "max_line_length": 115, "alphanum_fraction": 0.6889904327, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5386859465698567}}
{"text": "#ifndef DART_REALTIME_VECTOR_LOG\n#define DART_REALTIME_VECTOR_LOG\n\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"dart/math/MathTypes.hpp\"\n\nnamespace dart {\nnamespace realtime {\n\nstruct VectorObservation\n{\n  long time;\n  Eigen::VectorXs value;\n\n  VectorObservation(long time, Eigen::VectorXs value);\n};\n\nclass VectorLog\n{\npublic:\n  VectorLog(int dim);\n\n  void record(long time, Eigen::VectorXs val);\n\n  Eigen::MatrixXs getValues(long start, int steps, long millisPerStep);\n\n  void discardBefore(long time);\n\n  long availableHistoryBefore(long time);\n\nprotected:\n  int mDim;\n  long mStartTime;\n  std::vector<VectorObservation> mObservations;\n};\n\n} // namespace realtime\n} // namespace dart\n\n#endif", "meta": {"hexsha": "b9e97f47746de9ae924f3511be9e780059b8d030", "size": 702, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/realtime/VectorLog.hpp", "max_stars_repo_name": "jyf588/nimblephysics", "max_stars_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T06:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T09:59:09.000Z", "max_issues_repo_path": "dart/realtime/VectorLog.hpp", "max_issues_repo_name": "jyf588/nimblephysics", "max_issues_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "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": "dart/realtime/VectorLog.hpp", "max_forks_repo_name": "jyf588/nimblephysics", "max_forks_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T13:56:14.000Z", "avg_line_length": 16.3255813953, "max_line_length": 71, "alphanum_fraction": 0.7507122507, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370423, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5386819949247562}}
{"text": "/*!\n * @file\n * Contains unit tests for `boost::mpl11::fix`.\n */\n\n#include <boost/mpl11/functional.hpp>\n\n#include <boost/mpl11/integer.hpp>\n#include <boost/mpl11/logical.hpp>\n\n\nusing namespace boost::mpl11;\n\n// Factorial using fix<>\ntemplate <typename f, typename n>\nusing fact_impl = if_c<n::type::value == 0,\n    ullong<1>,\n    mult<n, apply<f, pred<n>>>\n>;\n\ntemplate <unsigned long long n>\nstruct fact_fix {\n    static constexpr auto value = fix<lift<fact_impl>>::type::\n                                  template apply<ullong<n>>::type::value;\n};\n\n\n// Standard recursive factorial\ntemplate <unsigned long long n>\nstruct fact_rec { static constexpr auto value = n * fact_rec<n - 1>::value; };\n\ntemplate <>\nstruct fact_rec<0> { static constexpr unsigned long long value = 1; };\n\n\n// Compare both implementations for a couple of values.\ntemplate <unsigned long long from, unsigned long long to>\nstruct test_fact : test_fact<from + 1, to> {\n    static_assert(fact_fix<from>::value == fact_rec<from>::value, \"\");\n};\n\ntemplate <unsigned long long to>\nstruct test_fact<to, to> { };\n\nstruct tests\n    : test_fact<0, 15>\n{ };\n\n\nint main() { }\n", "meta": {"hexsha": "64962e93460b233babd39ba7a8a0c798e5673251", "size": 1138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/functional/fix.cpp", "max_stars_repo_name": "ldionne/mpl11", "max_stars_repo_head_hexsha": "927d4339edc0c0cc41fb65ced2bf19d26bcd4a08", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T03:19:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T06:44:12.000Z", "max_issues_repo_path": "test/functional/fix.cpp", "max_issues_repo_name": "rbock/mpl11", "max_issues_repo_head_hexsha": "7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-27T22:37:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-06T17:42:07.000Z", "max_forks_repo_path": "test/functional/fix.cpp", "max_forks_repo_name": "rbock/mpl11", "max_forks_repo_head_hexsha": "7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T00:18:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T03:00:49.000Z", "avg_line_length": 22.3137254902, "max_line_length": 78, "alphanum_fraction": 0.6678383128, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5386819930732147}}
{"text": "#ifdef _DEBUG\n\n#include \"../../../library/src/debug_template.hpp\"\n\n#define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__)\n#else\n#define DMP(...) ((void)0)\n#endif\n\n#include <cassert>\n#include <cstdio>\n#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_map>\n#include <queue>\n#include <numeric>\n#include <algorithm>\n#include <bitset>\n#include <variant>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace std;\nusing lint = long long;\nconstexpr int INF = 1010101010;\nconstexpr lint LINF = 1LL << 60;\n\nstruct init {\n    init() {\n        cin.tie(nullptr);\n        ios::sync_with_stdio(false);\n        cout << fixed << setprecision(10);\n    }\n} init_;\n\n\nint main() {\n\n    lint A, B, K;\n    cin >> A >> B >> K;\n    string s = string(A, 'a') + string(B, 'b');\n\n    int L = A + B;\n    boost::multiprecision::cpp_int mpP = 1;\n    for (int l = 1; l <= L; ++l) mpP *= l;\n    for (int l = 1; l <= A; ++l) mpP /= l;\n    for (int l = 1; l <= B; ++l) mpP /= l;\n\n    string ans;\n    lint sum = 0;\n    while (A + B) {\n        if (A == 0) {\n            ans += string(B, 'b');\n            break;\n        }\n        A--;\n        int a = 2, b = 2;\n        lint now = 1;\n        for (int i = 2; i <= A + B; ++i) {\n            now *= i;\n            while (a <= A && now % a == 0) {\n                now /= a;\n                a++;\n            }\n            while (b <= B && now % b == 0) {\n                now /= b;\n                b++;\n            }\n        }\n        if (now + sum >= K) ans += 'a';\n        else {\n            ans += 'b';\n            A++, B--;\n            K -= now;\n        }\n    }\n\n    cout << ans << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "780fa5e1c1e24208f791087b5b83f70619d5bd90", "size": 1709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ABC/ABC202/D.cpp", "max_stars_repo_name": "rajyan/AtCoder", "max_stars_repo_head_hexsha": "2c1187994016d4c19b95489d2f2d2c0eab43dd8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-01T17:13:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-01T17:13:44.000Z", "max_issues_repo_path": "ABC/ABC202/D.cpp", "max_issues_repo_name": "rajyan/AtCoder", "max_issues_repo_head_hexsha": "2c1187994016d4c19b95489d2f2d2c0eab43dd8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ABC/ABC202/D.cpp", "max_forks_repo_name": "rajyan/AtCoder", "max_forks_repo_head_hexsha": "2c1187994016d4c19b95489d2f2d2c0eab43dd8e", "max_forks_repo_licenses": ["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.8720930233, "max_line_length": 50, "alphanum_fraction": 0.4546518432, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5386819898829966}}
{"text": "/*\n * die_roll.cpp: Die rolling utility. Generates a random number of the following\n * format: NdS(+/-)M.\n *     - N: number of dice being rolled.\n *     - S: number of sides per die; any number is allowed, and % can be used\n *          as a stand-in for 100.\n *     - M: modifier to apply to the roll (positive or negative).\n * This program also allows for multiple rolls (same format for all), if desired.\n *\n * Version:     1.0.0\n * License:     MIT License (see LICENSE.txt for more details)\n * Author:      Joshua Morrison (GitHub: MrM21632)\n * Last Edited: 7/4/2018, 1:45pm\n */\n\n#include <cstdio>\n#include <cstdint>\n#include <cstdlib>\n#include <ctime>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/random_device.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n\nint main(int argc, char **argv) {\n    if (argc != 5) {\n        std::printf(\"Usage: die_roll total dice sides mod\\n\");\n        std::printf(\"Generates random numbers in the range [dice + mod, (dice)(sides) + mod].\\n\\n\");\n        std::printf(\"total\\t\\tTotal rolls to make (> 0)\\n\");\n        std::printf(\"dice\\t\\tNumber of dice to roll (> 0)\\n\");\n        std::printf(\"sides\\t\\tSides per die (any positive number, or %%)\\n\");\n        std::printf(\"mod\\t\\tModifier to die roll (positive or negative)\\n\");\n\n        return EXIT_FAILURE;\n    }\n\n    // Setting up the variables\n    int total = std::atoi(argv[1]);\n    int dice = std::atoi(argv[2]);\n    int mod = std::atoi(argv[4]);\n\n    int min = dice + mod;\n    if (min <= 0)\n        min = 1;  // Guaranteed minimum result\n\n    int sides;\n    if (argv[3][0] == '%')  // Percentile\n        sides = 100;\n    else\n        sides = std::atoi(argv[3]);\n\n    int max = (dice * sides) + mod;\n    if (max <= 0)\n        max = 1;  // Guaranteed maximum(?) result\n\n\n    // Roll the bones\n    boost::random::random_device rd;\n    boost::random::mt19937 mt(rd());\n    boost::random::uniform_int_distribution<uint32_t> dist(min, max);\n\n    for (int i = 1; i <= total; ++i)\n        std::printf(\"Die Roll #%d: %u\\n\", i, dist(mt));\n}\n", "meta": {"hexsha": "fdce3419d668ffae4d7ed5191c8100d58ee4ccbe", "size": 2057, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "die_roll.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": "die_roll.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": "die_roll.cpp", "max_forks_repo_name": "MrM21632/WinUtils", "max_forks_repo_head_hexsha": "1f8597ffbbea7ec8684fa723831cec2dc37900d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6461538462, "max_line_length": 100, "alphanum_fraction": 0.6057365095, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5386606748761683}}
{"text": "#include <iostream>\n#include <functional>   \n#include <numeric> \n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <map>\n#include <Eigen\\dense>\n\n#include \"markov.h\"\n#include \"TransitionMatrix.h\"\n\n\n// Hint: Set N - number of simulations low until you have it working\n//       Then set it much much higher, and run in release mode so its faster\n\nint main() {\n\n\tSetTransitionMatrix();\n\n\t// Print Results to File\n\tstd::ofstream myfile;\n\tmyfile.open(\"markov_results.txt\");\n\n\tint start = 0;\n\n\t//simulate discrete time Markov Chain\n\tunsigned int N = 50;\n\tstd::map<int, int> hist;\n\tstd::vector<int> discreteMC;\n\tfor (unsigned int i = 0; i < N; ++i) {\n\t\t\n\t\t//TODO (add DTMC, and histogram lines.)\n\n\t\t// Code if you wanted to print out results at each step\n\t\t//for (auto elem : discreteMC)\n\t\t//\tstd::cout << elem << std::endl;\n\n\t}\n\t//Returns an array discreteMC with the states at each step of the discrete-time Markov Chain\n\t//The number of transitions is given by steps. The initial state is given by start \n\t//(the states are indexed from 0 to n-1 where n is the number of arrays in transMatrix).\n\t//hist is the histogram \n\n\n\t// (double)p.second / N    - (decimal) percentage.\n\tfor (auto p : hist) {\n\t\tstd::cout << p.first << \"\\t\" << (double)p.second / N << std::endl;\n\t}\n\n\tmyfile.close();\n\n\treturn 1;\n}", "meta": {"hexsha": "69c2aeaf51f3f58c1cf043762fd7fdb480cc14a2", "size": 1313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homework2/SnakesAndLadders/test_dtmc.cpp", "max_stars_repo_name": "SteveUCF/HW2", "max_stars_repo_head_hexsha": "079de669fae83978d0985c71436a358c4ca19fc8", "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": "Homework2/SnakesAndLadders/test_dtmc.cpp", "max_issues_repo_name": "SteveUCF/HW2", "max_issues_repo_head_hexsha": "079de669fae83978d0985c71436a358c4ca19fc8", "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": "Homework2/SnakesAndLadders/test_dtmc.cpp", "max_forks_repo_name": "SteveUCF/HW2", "max_forks_repo_head_hexsha": "079de669fae83978d0985c71436a358c4ca19fc8", "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.3148148148, "max_line_length": 93, "alphanum_fraction": 0.674790556, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5386606682334878}}
{"text": "/******************************************************************************\n*       SOFA, Simulation Open-Framework Architecture, development version     *\n*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *\n*                                                                             *\n* This program is free software; you can redistribute it and/or modify it     *\n* under the terms of the GNU Lesser General Public License as published by    *\n* the Free Software Foundation; either version 2.1 of the License, or (at     *\n* your option) any later version.                                             *\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       *\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 this program. If not, see <http://www.gnu.org/licenses/>.        *\n*******************************************************************************\n* Authors: The SOFA Team and external contributors (see Authors.txt)          *\n*                                                                             *\n* Contact information: contact@sofa-framework.org                             *\n******************************************************************************/\n#define SOFA_COMPONENT_ENGINE_INERTIAALIGN_CPP\n\n#include \"InertiaAlign.h\"\n#include <sofa/core/ObjectFactory.h>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\nnamespace sofa\n{\n\nnamespace component\n{\n\n\nusing namespace sofa::defaulttype;\n\nint InertiaAlignClass = core::RegisterObject(\"An engine computing inertia matrix and the principal direction of a mesh.\")\n        .add< InertiaAlign >()\n        ;\n\n\nSOFA_DECL_CLASS(InertiaAlign)\n\nInertiaAlign::InertiaAlign()\n    : targetC( initData(&targetC,\"targetCenter\",\"input: the gravity center of the target mesh\") )\n    , sourceC( initData(&sourceC,\"sourceCenter\",\"input: the gravity center of the source mesh\") )\n    , targetInertiaMatrix( initData(&targetInertiaMatrix,\"targetInertiaMatrix\",\"input: the inertia matrix of the target mesh\") )\n    , sourceInertiaMatrix( initData(&sourceInertiaMatrix,\"sourceInertiaMatrix\",\"input: the inertia matrix of the source mesh\") )\n    , m_positiont( initData(&m_positiont,\"targetPosition\",\"input: positions of the target vertices\") )\n    , m_positions( initData(&m_positions,\"sourcePosition\",\"input: positions of the source vertices\") )\n{\n\n}\n\n\nInertiaAlign::~InertiaAlign()\n{\n}\n\nvoid InertiaAlign::init()\n{\n    //Activate an output data\n    m_positions.setPersistent(false);\n    m_positiont.setPersistent(false);\n\n    sourceInertiaMatrix.setPersistent(false);\n    // Allow to edit an output data\n\n    helper::WriteAccessor<Data<helper::vector<sofa::defaulttype::Vec<3,SReal> > > > waPositions = m_positions;\n\n\n    Eigen::MatrixXd eigenSourceInertiaMatrix(3,3);\n    Eigen::MatrixXd eigenTargetInertiaMatrix(3,3);\n\n    SReal Sxx,Syy,Szz,Txx,Tyy,Tzz;\n    for(unsigned int i=0; i<3; i++ )\n    {\n        for( unsigned int j=0; j<3; j++ )\n        {\n            eigenSourceInertiaMatrix(i,j) = sourceInertiaMatrix.getValue().col(j)[i];\n            eigenTargetInertiaMatrix(i,j) = targetInertiaMatrix.getValue().col(j)[i];\n\n        }\n    }\n    sout << \"Source intertia matrix\"<<sendl<<eigenSourceInertiaMatrix << sendl;\n    sout << \"Target intertia matrix\"<<sendl<<eigenTargetInertiaMatrix << sendl;\n\n    Eigen::EigenSolver<Eigen::Matrix3d> solverTarget(eigenTargetInertiaMatrix);\n    Eigen::EigenSolver<Eigen::Matrix3d> solverSource(eigenSourceInertiaMatrix);\n\n    /* Creation of the following transformation matrix:\n     *\n     *U.x V.x W.x tx\n     *U.y V.y W.Y ty\n     *U.Z V.Z W.z tz\n     * 0   0   0   1\n     *\n     *With U,V,W The proper vectors of the Source inertia matrix (represent the principal axis of inertia)\n     *And tx,ty,tz the translation beetween the source object and the world\n     */\n\n    Eigen::Matrix3d eigenvectorsTarget,tmp ;\n    Eigen::Vector3d eigenvaluesTarget;\n    Eigen::Matrix3cd complexEigenvectorsTarget = solverTarget.eigenvectors();\n    Eigen::Vector3cd complexEigenvaluesTarget = solverTarget.eigenvalues();\n\n    Eigen::Matrix3d eigenvectorsSource ;\n    Eigen::Vector3d eigenvaluesSource ;\n    Eigen::Matrix3cd complexEigenvectorsSource = solverSource.eigenvectors();\n    Eigen::Vector3cd complexEigenvaluesSource = solverSource.eigenvalues();\n\n    for(unsigned int i = 0; i<3; i++)\n    {\n        for(unsigned int j=0;j<3;j++)\n        {\n            eigenvectorsSource(i,j)= real(complexEigenvectorsSource(i,j));\n            eigenvectorsTarget(i,j)= real(complexEigenvectorsTarget(i,j));\n        }\n        eigenvaluesTarget(i) = real(complexEigenvaluesTarget(i));\n        eigenvaluesSource(i) = real(complexEigenvaluesSource(i));\n    }\n\n    SReal minSource = eigenvaluesSource(0);\n\n    //Compute the length of the principal axes\n    Sxx = eigenvaluesSource[0];\n    Syy = eigenvaluesSource[1];\n    Szz = eigenvaluesSource[2];\n    Txx = eigenvaluesTarget[0];\n    Tyy = eigenvaluesTarget[1];\n    Tzz = eigenvaluesTarget[2];\n\n    SReal Lxs = sqrt(abs(-Sxx+Syy+Szz)/2);\n    SReal Lys = sqrt(abs( Sxx-Syy+Szz)/2);\n    SReal Lzs = sqrt(abs( Sxx+Syy-Szz)/2);\n\n    SReal Lxt = sqrt(abs(-Txx+Tyy+Tzz)/2);\n    SReal Lyt = sqrt(abs( Txx-Tyy+Tzz)/2);\n    SReal Lzt = sqrt(abs( Txx+Tyy-Tzz)/2);\n\n    //Source inversion of axes (to be sure that u is on u', v on v' and w on w')\n    //Check thats the proper values are in the same order for the two objects\n    //If not switch the proper values.\n    //Inversion of u and v\n    if (eigenvaluesSource[0] < eigenvaluesSource[1])\n    {\n        eigenvaluesSource(0)= eigenvaluesSource(1);\n        eigenvaluesSource(1)=minSource;\n        minSource = eigenvaluesSource(0);\n        for(unsigned int i = 0; i<3; i++){\n            tmp(i) = eigenvectorsSource(i,1);\n            eigenvectorsSource(i,1) =   eigenvectorsSource(i,0);\n            eigenvectorsSource(i,0) = tmp(i);\n        }\n\n    }\n    //Inversion of u and w\n    if (eigenvaluesSource[0]<eigenvaluesSource[2])\n    {\n        eigenvaluesSource(0)= eigenvaluesSource(2);\n        eigenvaluesSource(2)=minSource;\n        minSource = eigenvaluesSource(0);\n        for(unsigned int i = 0; i<3; i++){\n            tmp(i) = eigenvectorsSource(i,2);\n            eigenvectorsSource(i,2) =   eigenvectorsSource(i,0);\n            eigenvectorsSource(i,0) = tmp(i);\n        }\n    }\n    //Inversion of v and w\n    minSource = eigenvaluesSource(1);\n\n    if (eigenvaluesSource[1]<eigenvaluesSource[2])\n    {\n        eigenvaluesSource(1)= eigenvaluesSource(2);\n        eigenvaluesSource(2)=minSource;\n        minSource = eigenvaluesSource(1);\n        for(unsigned int i = 0; i<3; i++){\n            tmp(i) = eigenvectorsSource(i,2);\n            eigenvectorsSource(i,2) =   eigenvectorsSource(i,1);\n            eigenvectorsSource(i,1) = tmp(i);\n        }\n    }\n\n\n    SReal minTarget = eigenvaluesTarget(0);\n\n    //Target Inversion of axes\n    //Inversion of u' and v'\n    if (eigenvaluesTarget[0]<eigenvaluesTarget[1])\n    {\n        eigenvaluesTarget(0)= eigenvaluesTarget(1);\n        eigenvaluesTarget(1)=minTarget;\n        minTarget = eigenvaluesTarget(0);\n        for(unsigned int i = 0; i<3; i++){\n            tmp(i) = eigenvectorsTarget(i,1);\n            eigenvectorsTarget(i,1) =   eigenvectorsTarget(i,0);\n            eigenvectorsTarget(i,0) = tmp(i);\n        }\n    }\n    //Inversion of u' and w'\n    if (eigenvaluesTarget[0]<eigenvaluesTarget[2])\n    {\n        eigenvaluesTarget(0)= eigenvaluesTarget(2);\n        eigenvaluesTarget(2)=minTarget;\n        minTarget = eigenvaluesTarget(0);\n        for(unsigned int i = 0; i<3; i++){\n            tmp(i) = eigenvectorsTarget(i,2);\n            eigenvectorsTarget(i,2) =   eigenvectorsTarget(i,0);\n            eigenvectorsTarget(i,0) = tmp(i);\n        }\n    }\n    //Inversion of v' and w'\n    minTarget = eigenvaluesTarget(1);\n\n    if (eigenvaluesTarget[1]<eigenvaluesTarget[2])\n    {\n        eigenvaluesTarget(1)= eigenvaluesTarget(2);\n        eigenvaluesTarget(2)=minTarget;\n        minTarget = eigenvaluesTarget(1);\n        for(unsigned int i = 0; i<3; i++){\n            tmp(i) = eigenvectorsTarget(i,2);\n            eigenvectorsTarget(i,2) =   eigenvectorsTarget(i,1);\n            eigenvectorsTarget(i,1) = tmp(i);\n        }\n    }\n    //Compute the length of the axes.\n    //The scale along x is Lxs/Lxt\n    //The ratio 1/5m have been supressed due to the ratio beetween the source/target\n\n    Sxx = eigenvaluesSource[0];\n    Syy = eigenvaluesSource[1];\n    Szz = eigenvaluesSource[2];\n    Txx = eigenvaluesTarget[0];\n    Tyy = eigenvaluesTarget[1];\n    Tzz = eigenvaluesTarget[2];\n\n    Lxs = sqrt(abs(-Sxx+Syy+Szz)/2);\n    Lys = sqrt(abs( Sxx-Syy+Szz)/2);\n    Lzs = sqrt(abs( Sxx+Syy-Szz)/2);\n\n    Lxt = sqrt(abs(-Txx+Tyy+Tzz)/2);\n    Lyt = sqrt(abs( Txx-Tyy+Tzz)/2);\n    Lzt = sqrt(abs( Txx+Tyy-Tzz)/2);\n\n\n    sout << \"EigenVectorsSource =\" << sendl;\n    for(unsigned int i=0;i<3;i++)\n    {\n        for(unsigned int j=0;j<3;j++)\n            sout << eigenvectorsSource(i,j) << \" \";\n        sout << sendl;\n\n    }\n\n    SReal scale_u = Lxs / Lxt;\n    SReal scale_v = Lys / Lyt;\n    SReal scale_w = Lzs / Lzt;\n\n    sout << \"Scale X = \" << scale_u << \"Scale Y = \"<< scale_v << \"Scale Z = \" << scale_w << sendl;\n\n\n    sout << \"Lxs = \" <<Lxs<< \"Lys = \" <<Lys<< \"Lzs = \" <<Lzs << sendl;\n    sout << \"Lxt = \" <<Lxt<< \"Lyt = \" <<Lyt<< \"Lzt = \" <<Lzt << sendl;\n    /*Creation of the two 4x4 transformation matrix:\n     *\n     *MTransformSource :\n     *\n     *U.x V.x W.x tx\n     *U.y V.y W.Y ty\n     *U.z V.z W.z tz\n     * 0   0   0   1\n     *\n     *\n     *Then inverse R = MtransformSource [0..2][0..2]\n     *t = -R*t\n     *\n     * with U,V and W the eigenvectors of the source inertia matrix in the world coordinates.\n     *And tx,ty,tz represents the translation beetween the center of the world and the inertia center of the object S\n     *\n     *\n     *MTransformTarget :\n     *\n     *U'.x V'.x W'.x tx\n     *U'.y V'.y W'.Y ty\n     *U'.z V'.z W'.z tz\n     *  0    0    0   1\n     *\n\n     *\n     * with U',V' and W' the eigenvectors of the target inertia matrix in the world coordinates.\n     *And tx,ty,tz represents the translation beetween the center of the world and the inertia center of the object T\n     *\n     *\n     */\n\n\n\n    Eigen::Matrix3d MRotationSource, MRotationTarget;\n    defaulttype::Matrix4 MTransformSource,MTransformTarget,MTransformTargetTest,MTransform,Mscale;\n    MRotationSource =  eigenvectorsSource;\n    MRotationTarget =  eigenvectorsTarget;\n    Eigen::Vector3d u,v,w;\n    SReal sdirect;\n    Mscale(0,0)=scale_u;\n    Mscale(1,1)=scale_v;\n    Mscale(2,2)=scale_w;\n    Mscale(3,3)=1;\n    for(unsigned int i=0;i<3;i++)\n    {\n        u(i) = MRotationSource(i,0);\n        v(i) = MRotationSource(i,1);\n        w(i) = MRotationSource(i,2);\n\n    }\n    sdirect = u.cross(v).dot(w);\n\n\n    for(unsigned int i=0;i<3;i++)\n    {\n        if(sdirect < 0)\n        {\n            MRotationSource(i,2) = -MRotationSource(i,2);\n        }\n    }\n\n\n    sout <<\"Source Directe? \"<< sdirect << sendl;\n\n    for(unsigned int i=0;i<3;i++)\n    {\n        u(i) = MRotationTarget(i,0);\n        v(i) = MRotationTarget(i,1);\n        w(i) = MRotationTarget(i,2);\n\n    }\n\n    //Checks if the axes are direct or not\n    sdirect = u.cross(v).dot(w);\n\n\n\n    for(unsigned int i=0;i<3;i++)\n    {\n        if(sdirect == -1)\n        {\n            MRotationTarget(i,2) = -MRotationTarget(i,2);\n        }\n    }\n\n    sout <<\"Target Directe? \"<< sdirect << sendl;\n\n    //Normalised last line\n    MTransformTarget(3,3) = 1;\n\n    for(unsigned int i=0;i<3;i++)\n    {\n        //TODO : v\u00e9rifier ces histoires de Lxs/Lxt\n\n        MTransformTarget(i,0) = MRotationTarget(i,0)*Lxt;\n        MTransformTarget(i,1) = MRotationTarget(i,1)*Lyt;\n        MTransformTarget(i,2) = MRotationTarget(i,2)*Lzt;\n        MTransformTarget(3,i) = 0;\n\n    }\n    Eigen::Vector3d TargetTransform;\n    for(unsigned int i=0;i<3;i++)\n    {\n        TargetTransform(i)= -(*targetC.beginEdit())[0];\n    }\n    MTransformTarget(0,3) = -(*targetC.beginEdit())[0];\n    MTransformTarget(1,3) = -(*targetC.beginEdit())[1];\n    MTransformTarget(2,3) = -(*targetC.beginEdit())[2];\n\n\n    //Construction of S\n    MTransformSource(3,3) = 1;\n    Vector4 TranslationSource;\n\n    MTransformSource(0,3) = -(*sourceC.beginEdit())[0];\n    MTransformSource(1,3) = -(*sourceC.beginEdit())[1];\n    MTransformSource(2,3) = -(*sourceC.beginEdit())[2];\n\n    for(unsigned int i=0;i<3;i++)\n    {\n        //TODO : v\u00e9rifier ces histoires de Lxs/Lxt\n\n        MTransformSource(i,0) = MRotationSource(i,0) *Lxs;\n        MTransformSource(i,1) = MRotationSource(i,1) *Lys;\n        MTransformSource(i,2) = MRotationSource(i,2) *Lzs;\n        MTransformSource(3,i) = 0;\n        TranslationSource(i)  = MTransformSource(i,3);\n\n    }\n\n    sout << \"MTransformSource before inversion =\"<< sendl;\n    for(unsigned int i=0;i<4;i++)\n    {\n        for(unsigned int j=0;j<4;j++)\n        {\n            sout <<MTransformSource(i,j)<< \" \";\n        }\n        sout << sendl;\n    }\n\n    MTransformSource = inverseTransform(MTransformSource);\n    sout << \"MTransformSource after inversion =\"<< sendl;\n    for(unsigned int i=0;i<4;i++)\n    {\n        for(unsigned int j=0;j<4;j++)\n        {\n            sout <<MTransformSource(i,j)<< \" \";\n        }\n        sout << sendl;\n    }\n    defaulttype::Matrix4 MTranslation;\n    for(unsigned int i=0;i<4;i++)\n    {\n        for(unsigned int j=0;j<4;j++)\n        {\n            MTranslation(i,j)=0;\n            if(i==j)\n                MTranslation(i,i) = 1;\n        }\n    }\n\n\n\n\n    int indice_min =0;\n    SReal distance, distance_min;\n\n    distance = std::numeric_limits<SReal>::max();\n    distance_min = std::numeric_limits<SReal>::max();\n\n    for (unsigned int i=0;i<4;i++)\n        for (unsigned int j=0;j<4;j++)\n            MTransformTargetTest(i,j) = MTransformTarget(i,j);\n\n    for(unsigned int i=0;i<4;i++)//Test of the 4 possible permutations\n    {\n        switch (i)\n        {\n        case 0 :\n            for(unsigned int j=0;j<3;j++)\n            {\n                MTransformTargetTest(j,0) = MTransformTarget(j,0) ;\n                MTransformTargetTest(j,1) = MTransformTarget(j,1) ;\n                MTransformTargetTest(j,2) = MTransformTarget(j,2) ;\n            }\n            break;\n        case 1 :\n\n            for(unsigned int j=0;j<3;j++)\n            {\n                MTransformTargetTest(j,0) = MTransformTarget(j,0) ;\n                MTransformTargetTest(j,1) =-MTransformTarget(j,1) ;\n                MTransformTargetTest(j,2) =-MTransformTarget(j,2) ;\n            }\n            break;\n        case 2 :\n\n            for(unsigned int j=0;j<3;j++)\n            {\n                MTransformTargetTest(j,0) =-MTransformTarget(j,0) ;\n                MTransformTargetTest(j,1) = MTransformTarget(j,1) ;\n                MTransformTargetTest(j,2) =-MTransformTarget(j,2) ;\n            }\n            break;\n        case 3:\n\n            for(unsigned int j=0;j<3;j++)\n            {\n                MTransformTargetTest(j,0) =-MTransformTarget(j,0) ;\n                MTransformTargetTest(j,1) =-MTransformTarget(j,1) ;\n                MTransformTargetTest(j,2) = MTransformTarget(j,2) ;\n\n            }\n            break;\n\n        }\n        MTransform = MTransformTargetTest * MTransformSource ;\n\n        positionDistSource = (*m_positions.beginEdit());\n        for (size_t j = 0; j < waPositions.size(); j++)\n        {\n            defaulttype::Vector4 pointS,pointT;\n            pointS(0) = (*m_positions.beginEdit())[j][0];\n            pointS(1) = (*m_positions.beginEdit())[j][1];\n            pointS(2) = (*m_positions.beginEdit())[j][2];\n            pointS(3) = 1;\n            pointT = MTransform * pointS  ;\n            (*m_positions.beginEdit())[j][0] =pointT(0);\n            (*m_positions.beginEdit())[j][1] =pointT(1);\n            (*m_positions.beginEdit())[j][2] =pointT(2);\n        }\n\n        distance =computeDistances(*m_positions.beginEdit(),*m_positiont.beginEdit());\n        if (distance < distance_min)\n        {\n            indice_min = i;\n            distance_min = distance;\n        }\n        (*m_positions.beginEdit()) = positionDistSource;\n    }\n    sout << \"Indice choisi : \" << indice_min << \" avec une distance de \" << distance_min << sendl;\n    //Compute the best transformation\n    switch(indice_min)\n    {\n    case 0 ://Nothing is inverted\n        for(unsigned int j=0;j<3;j++)\n        {\n            MTransformTarget(j,0) = MTransformTarget(j,0) ;\n            MTransformTarget(j,1) = MTransformTarget(j,1) ;\n            MTransformTarget(j,2) = MTransformTarget(j,2) ;\n        }\n        break;\n    case 1 ://v and w are inverted\n\n        for(unsigned int j=0;j<3;j++)\n        {\n            MTransformTarget(j,0) = MTransformTarget(j,0) ;\n            MTransformTarget(j,1) =-MTransformTarget(j,1) ;\n            MTransformTarget(j,2) =-MTransformTarget(j,2) ;\n        }\n        break;\n    case 2 ://u and w are inverted\n\n        for(unsigned int j=0;j<3;j++)\n        {\n            MTransformTarget(j,0) =-MTransformTarget(j,0) ;\n            MTransformTarget(j,1) = MTransformTarget(j,1) ;\n            MTransformTarget(j,2) =-MTransformTarget(j,2) ;\n        }\n        break;\n    case 3:// u and v are inverted\n\n        for(unsigned int j=0;j<3;j++)\n        {\n            MTransformTarget(j,0) =-MTransformTarget(j,0) ;\n            MTransformTarget(j,1) =-MTransformTarget(j,1) ;\n            MTransformTarget(j,2) = MTransformTarget(j,2) ;\n        }\n        break;\n    }\n\n    for(unsigned int k=0;k<4;k++)\n    {\n       for(unsigned int j=0;j<4;j++)\n       {\n         sout << MTransformTarget(k,j) << \" \";\n       }\n       sout << sendl;\n    }\n    MTransformSource = MTransformTarget * MTransformSource;\n\n\n    for(unsigned int k=0;k<4;k++)\n    {\n       for(unsigned int j=0;j<4;j++)\n       {\n         sout << MTransformSource(k,j) << \" \";\n       }\n       sout << sendl;\n    }\n\n    Eigen::Matrix4d MDeterminantTest;\n    for(unsigned int k=0;k<3;k++)\n    {\n       for(unsigned int j=0;j<3;j++)\n       {\n           MDeterminantTest(k,j)=MTransformSource(k,j);\n       }\n    }\n    if(MDeterminantTest.determinant()<0)\n        sout << \"The MTransformSourceMatrix is not a Transformation matrix\" << sendl;\n    for (size_t i = 0; i < waPositions.size(); i++)\n    {\n        defaulttype::Vector4 pointS,pointT;\n        pointS(0) = (*m_positions.beginEdit())[i][0];\n        pointS(1) = (*m_positions.beginEdit())[i][1];\n        pointS(2) = (*m_positions.beginEdit())[i][2];\n        pointS(3) = 1;\n        pointT = MTransformSource * pointS  ;\n        (*m_positions.beginEdit())[i][0] =pointT(0);\n        (*m_positions.beginEdit())[i][1] =pointT(1);\n        (*m_positions.beginEdit())[i][2] =pointT(2);\n    }\n    //After this step, this data cannot be modified\n    m_positions.endEdit();\n\n    m_positiont.endEdit();\n\n}\n\n\n\n//Hausdorff distance\n//good approx but slow\n\n/**\n * Compute the distance from a point to a point cloud\n */\n\nSReal InertiaAlign::distance(sofa::defaulttype::Vec<3,SReal> p, helper::vector<sofa::defaulttype::Vec<3,SReal> > S)\n{\n    SReal min = std::numeric_limits<SReal>::max();\n\n    for (unsigned int i = 0 ; i < S.size(); i++)\n    {\n        SReal d = (p-S[i]).norm();\n        if (d<min) min = d;\n    }\n\n    return min;\n}\n\n/**\n * Compute distances between both point clouds (symmetrical and non-symmetrical distances)\n */\nSReal InertiaAlign::computeDistances( helper::vector<sofa::defaulttype::Vec<3,SReal> > S, helper::vector<sofa::defaulttype::Vec<3,SReal> > T)\n{\n    SReal maxST = 0.0;\n    for (unsigned int i = 0 ; i < S.size(); i++)\n    {\n        SReal d = InertiaAlign::distance(S[i], T);\n        if (d>maxST) maxST = d;\n    }\n\n    SReal maxTS = 0.0;\n    for (unsigned int i = 0 ; i < T.size(); i++)\n    {\n        SReal d = InertiaAlign::distance(T[i], S);\n        if (d>maxTS) maxTS = d;\n    }\n\n    if (maxTS > maxST)\n        return maxST/S.size();\n    else\n        return maxTS/S.size();\n\n}\n\nMatrix4 InertiaAlign::inverseTransform(Matrix4 transformToInvert)\n{\n    Matrix3 rotationToInvert;\n    Matrix3 rotationInverted;\n    Vector3 Translation;\n    Matrix4 transformInverted;\n\n    sout << \"Before inversion\"<< sendl;\n    for(unsigned int i=0;i<4;i++)\n    {\n        for(unsigned int j=0;j<4;j++)\n        {\n            sout << transformToInvert(i,j)<< \" \";\n        }\n        sout << sendl;\n    }\n    for(unsigned int i=0;i<3;i++)\n    {\n        for(unsigned int j=0;j<3;j++)\n        {\n            rotationToInvert(i,j) = transformToInvert(i,j);\n        }\n        Translation(i)=transformToInvert(i,3);\n    }\n\n    bool bS = invertMatrix(rotationInverted,rotationToInvert);\n\n    sout << \"Translation = \" << Translation;\n    if(!bS)\n    {\n        sout <<\"Error : Source transformation matrix is not invertible\"<<sendl;\n    }\n    else //Compute R-1 * t\n    {\n        Translation = (-1*rotationInverted * Translation);\n    }\n    sout << \"Translation = \" << Translation;\n    for(unsigned int i=0;i<3;i++)\n    {\n        for(unsigned int j=0;j<3;j++)\n        {\n            transformInverted(i,j) = rotationInverted(i,j);\n        }\n        transformInverted(i,3)= Translation(i);\n    }\n    transformInverted(3,3)=1;\n\n    sout << \"After inversion\"<< sendl;\n    for(unsigned int i=0;i<4;i++)\n    {\n        for(unsigned int j=0;j<4;j++)\n        {\n            sout << transformInverted(i,j)<< \" \";\n        }\n        sout << sendl;\n    }\n    return transformInverted;\n\n}\n\nSReal InertiaAlign::abs(SReal a)\n{\n    return sqrt(a*a);\n}\n\n\n\n} // namespace component\n\n} // namespace sofa\n", "meta": {"hexsha": "f675d3765290b9fc086eb7aa450cbbe712797e11", "size": 21887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/plugins/Registration/InertiaAlign.cpp", "max_stars_repo_name": "sofa-framework/issofa", "max_stars_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_stars_repo_licenses": ["OML"], "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/plugins/Registration/InertiaAlign.cpp", "max_issues_repo_name": "sofa-framework/issofa", "max_issues_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_issues_repo_licenses": ["OML"], "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/plugins/Registration/InertiaAlign.cpp", "max_forks_repo_name": "sofa-framework/issofa", "max_forks_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_forks_repo_licenses": ["OML"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6111888112, "max_line_length": 141, "alphanum_fraction": 0.5687394344, "num_tokens": 6025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5385930730620885}}
{"text": "#include \"sbs/physics/xpbd/green_constraint.h\"\n\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <sbs/physics/simulation.h>\n\nnamespace sbs {\nnamespace physics {\nnamespace xpbd {\n\ngreen_constraint_t::green_constraint_t(\n    scalar_type const alpha,\n    scalar_type const beta,\n    simulation_t const& simulation,\n    index_type bi,\n    index_type v1,\n    index_type v2,\n    index_type v3,\n    index_type v4,\n    scalar_type young_modulus,\n    scalar_type poisson_ratio)\n    : constraint_t(alpha, beta),\n      bi_(bi),\n      v1_(v1),\n      v2_(v2),\n      v3_(v3),\n      v4_(v4),\n      DmInv_(),\n      V0_(),\n      mu_(),\n      lambda_()\n{\n    auto const& p1 = simulation.particles()[bi_][v1_];\n    auto const& p2 = simulation.particles()[bi_][v2_];\n    auto const& p3 = simulation.particles()[bi_][v3_];\n    auto const& p4 = simulation.particles()[bi_][v4_];\n\n    Eigen::Matrix3d Dm;\n    Dm.col(0) = (p1.x0() - p4.x0()).transpose();\n    Dm.col(1) = (p2.x0() - p4.x0()).transpose();\n    Dm.col(2) = (p3.x0() - p4.x0()).transpose();\n\n    DmInv_  = Dm.inverse();\n    V0_     = (1. / 6.) * Dm.determinant();\n    mu_     = (young_modulus) / (2. * (1 + poisson_ratio));\n    lambda_ = (young_modulus * poisson_ratio) / ((1 + poisson_ratio) * (1 - 2 * poisson_ratio));\n}\n\nvoid green_constraint_t::project_positions(simulation_t& simulation, scalar_type dt)\n{\n    auto& p1 = simulation.particles()[bi_][v1_];\n    auto& p2 = simulation.particles()[bi_][v2_];\n    auto& p3 = simulation.particles()[bi_][v3_];\n    auto& p4 = simulation.particles()[bi_][v4_];\n\n    scalar_type const w1 = p1.invmass();\n    scalar_type const w2 = p2.invmass();\n    scalar_type const w3 = p3.invmass();\n    scalar_type const w4 = p4.invmass();\n\n    auto const Vsigned        = signed_volume(p1.xi(), p2.xi(), p3.xi(), p4.xi());\n    bool const is_V_positive  = Vsigned >= 0.;\n    bool const is_V0_positive = V0_ >= 0.;\n    bool const is_tet_inverted =\n        (is_V_positive && !is_V0_positive) || (!is_V_positive && is_V0_positive);\n\n    scalar_type constexpr epsilon = 1e-20;\n\n    Eigen::Matrix3d Ds;\n    Ds.col(0) = (p1.xi() - p4.xi());\n    Ds.col(1) = (p2.xi() - p4.xi());\n    Ds.col(2) = (p3.xi() - p4.xi());\n\n    Eigen::Matrix3d const F = Ds * DmInv_;\n    Eigen::Matrix3d const I = Eigen::Matrix3d::Identity();\n\n    // TODO: Implement correct inversion handling described in\n    // Irving, Geoffrey, Joseph Teran, and Ronald Fedkiw. \"Invertible finite elements for robust\n    // simulation of large deformation.\" Proceedings of the 2004 ACM SIGGRAPH/Eurographics symposium\n    // on Computer animation. 2004.\n    Eigen::JacobiSVD<Eigen::Matrix3d> UFhatV(F, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::Vector3d const Fsigma = UFhatV.singularValues();\n    Eigen::Matrix3d Fhat;\n    Fhat.setZero();\n    Fhat(0, 0) = Fsigma(0);\n    Fhat(1, 1) = Fsigma(1);\n    Fhat(2, 2) = Fsigma(2);\n\n    Eigen::Matrix3d U       = UFhatV.matrixU();\n    Eigen::Matrix3d const V = UFhatV.matrixV();\n\n    if (is_tet_inverted)\n    {\n        Fhat(2, 2) = -Fhat(2, 2);\n        U.col(2)   = -U.col(2);\n    }\n\n    // stress reaches maximum at 58% compression\n    scalar_type constexpr min_singular_value = 0.577;\n    Fhat(0, 0)                               = std::max(Fhat(0, 0), min_singular_value);\n    Fhat(1, 1)                               = std::max(Fhat(1, 1), min_singular_value);\n    Fhat(2, 2)                               = std::max(Fhat(2, 2), min_singular_value);\n\n    Eigen::Matrix3d const Ehat     = 0.5 * (Fhat.transpose() * Fhat - I);\n    scalar_type const EhatTrace    = Ehat.trace();\n    Eigen::Matrix3d const Piolahat = Fhat * ((2. * mu_ * Ehat) + (lambda_ * EhatTrace * I));\n\n    Eigen::Matrix3d const E  = U * Ehat * V.transpose();\n    scalar_type const Etrace = E.trace();\n    scalar_type const psi = mu_ * (E.array() * E.array()).sum() + 0.5 * lambda_ * Etrace * Etrace;\n\n    Eigen::Matrix3d const Piola = U * Piolahat * V.transpose();\n\n    // H is the negative gradient of the elastic potential\n    scalar_type const V0     = std::abs(V0_);\n    Eigen::Matrix3d const H  = -V0 * Piola * DmInv_.transpose();\n    Eigen::Vector3d const f1 = H.col(0);\n    Eigen::Vector3d const f2 = H.col(1);\n    Eigen::Vector3d const f3 = H.col(2);\n    Eigen::Vector3d const f4 = -(f1 + f2 + f3);\n\n    // clang-format off\n     auto const weighted_sum_of_gradients =\n        w1 * f1.squaredNorm() +\n        w2 * f2.squaredNorm() +\n        w3 * f3.squaredNorm() +\n        w4 * f4.squaredNorm();\n    // clang-format on\n\n    if (weighted_sum_of_gradients < epsilon)\n        return;\n\n    scalar_type const C           = V0 * psi;\n    scalar_type const dt2         = dt * dt;\n    scalar_type const alpha_tilde = alpha() / dt2;\n    scalar_type const beta_tilde  = beta() * dt2;\n    scalar_type const gamma       = alpha_tilde * beta_tilde / dt;\n\n    // clang-format off\n    scalar_type const gradC_dot_displacement =\n        f1.dot(p1.xi() - p1.xn()) + \n        f2.dot(p2.xi() - p2.xn()) + \n        f3.dot(p3.xi() - p3.xn()) +\n        f4.dot(p4.xi() - p4.xn());\n    // clang-format on\n\n    scalar_type const delta_lagrange_num =\n        -(C + alpha_tilde * lagrange_) + gamma * gradC_dot_displacement;\n    scalar_type const delta_lagrange_den = (1. + gamma) * (weighted_sum_of_gradients) + alpha_tilde;\n    scalar_type const delta_lagrange     = delta_lagrange_num / delta_lagrange_den;\n\n    lagrange_ += delta_lagrange;\n    // because f = - grad(potential), then grad(potential) = -f and thus grad(C) = -f\n    p1.xi() += w1 * -f1 * delta_lagrange;\n    p2.xi() += w2 * -f2 * delta_lagrange;\n    p3.xi() += w3 * -f3 * delta_lagrange;\n    p4.xi() += w4 * -f4 * delta_lagrange;\n}\n\nscalar_type green_constraint_t::signed_volume(\n    Eigen::Vector3d const& p1,\n    Eigen::Vector3d const& p2,\n    Eigen::Vector3d const& p3,\n    Eigen::Vector3d const& p4) const\n{\n    Eigen::Matrix3d Dm;\n    Dm.col(0) = (p1 - p4);\n    Dm.col(1) = (p2 - p4);\n    Dm.col(2) = (p3 - p4);\n\n    scalar_type const V = (1. / 6.) * Dm.determinant();\n    return V;\n}\n\n} // namespace xpbd\n} // namespace physics\n} // namespace sbs", "meta": {"hexsha": "0583cbada85df297a86a93cce8c9c21a0f270c80", "size": 6053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/physics/xpbd/green_constraint.cpp", "max_stars_repo_name": "Q-Minh/soft-body-simulator", "max_stars_repo_head_hexsha": "f41640945df989d8c91d99e8f2e86d6af90211f6", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T01:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T17:35:49.000Z", "max_issues_repo_path": "src/physics/xpbd/green_constraint.cpp", "max_issues_repo_name": "Q-Minh/soft-body-simulator", "max_issues_repo_head_hexsha": "f41640945df989d8c91d99e8f2e86d6af90211f6", "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/physics/xpbd/green_constraint.cpp", "max_forks_repo_name": "Q-Minh/soft-body-simulator", "max_forks_repo_head_hexsha": "f41640945df989d8c91d99e8f2e86d6af90211f6", "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.197740113, "max_line_length": 100, "alphanum_fraction": 0.6068065422, "num_tokens": 1956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5385668245530144}}
{"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_SQRT_INCLUDE\n#define META_MATH_SQRT_INCLUDE\n\n#include <boost/numeric/meta_math/abs.hpp>\n\nnamespace meta_math {\n\ntemplate <long int root, long int x>\nstruct sqrt_check\n{\n    static bool const value = root * root <= x && (root+1) * (root+1) > x;\n};\n\n\nnamespace impl {\n\n    template <long int guess, long int x, bool Converged>\n    struct sqrt_impl\n    {\n\ttypedef long int type;\n\ttypedef sqrt_impl   self;\n\tstatic long int const quotient = x / guess,\n\t                      new_value = (quotient + guess) / 2;\n\tstatic bool const converging = abs<guess - quotient>::value < 2;\n\tstatic long int const value = sqrt_impl<new_value, x, converging>::value;\n    };\n\n    // If the condition becomes true the guessed root will be the returned value\n    template <long int guess, long int x>\n    struct sqrt_impl<guess, x, true> \n    {\n\tstatic long int const value = guess;\n    };\n\n}\n\ntemplate <long int x>\nstruct sqrt \n{\n  typedef long int type;\n  static long int const value = impl::sqrt_impl<1, x, false>::value;\n};  \n\n\n} // namespace meta_math\n\n#endif // META_MATH_SQRT_INCLUDE\n", "meta": {"hexsha": "dd9dc426dda4c2b4d448251ad8a24a5fc7674d6e", "size": 1531, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/meta_math/sqrt.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/sqrt.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/sqrt.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": 25.5166666667, "max_line_length": 94, "alphanum_fraction": 0.6845199216, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5385668081070973}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <cstdlib>\n#include <time.h>\n#include <math.h>\n#include <dirent.h>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <string>\n#include <algorithm>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/math/distributions/normal.hpp>\n\n#include \"opencv2/core/core.hpp\"\n#include \"opencv2/features2d/features2d.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/calib3d/calib3d.hpp\"\n#include \"opencv2/nonfree/features2d.hpp\"\n#include \"opencv2/flann/flann.hpp\"\n\n#include \"FastEMD/emd_hat.hpp\"\n#include \"FastEMD/emd_hat_signatures_interface.hpp\"\n#include \"RubnerEMD/emd.hpp\"\n#include \"FastEMD/tictoc.hpp\"\n\nusing namespace cv;\nusing namespace std;\n\nnamespace fs = boost::filesystem;\n\n// TODO: config\n/* CONFIGURATIONS */\nbool use_fast_emd = 1;\nfloat gd_dist = 350;\n/* END CONFIGURATIONS */\n\nvoid help();\nvoid print_progress(time_t start, int total, int& completed, int per_cout);\nvoid print_keypoints(const vector<KeyPoint>& kp);\n\nfloat calc_emd(int first, int second);\ndouble calc_fast_emd(int first, int second);\nfloat calc_scalar_manitude(const Mat& desc, int index);\nvoid calc_contrast(const vector<KeyPoint>& kp);\nvoid calc_dist_mat(const Mat& desc_1, const Mat& desc_2, bool gd = false);\nfloat euclid_dist(const float *v1, const float *v2, int dim1, int dim2);\nfloat emd_dist(feature_t *f1, feature_t *f2);\ndouble fast_emd_dist(feature_tt *f1, feature_tt *f2);\n\nMat dist_mat;\nvector<Mat> img_descriptors;\nvector<vector<KeyPoint> > img_keypoints;\nvector<string> img_paths;\n\nint main(int argc, char *argv[]) {\n\tif (argc < 4) {\n\t\thelp();\n\t\treturn -1;\n\t}\n\n\tconst char *index_path = argv[1];\n\tconst char *queries_path = argv[2];\n\tconst char *out_path = argv[3];\n\tif (argc > 5)\n\t\tgd_dist = atof(argv[5]);\n\n\tcout << \"Reading queries from \" << queries_path << endl;\n\tvector<string> query_paths;\n\tstring query_path;\n\tint query_count;\n\tifstream queries_file(queries_path);\n\tqueries_file >> query_count;\n\tfor (int i = 0; i < query_count; ++i) {\n\t\tqueries_file >> query_path;\n\t\tquery_paths.push_back(query_path);\n\t}\n\n\tcout << \"Reading index from \" << index_path << endl;\n\tFileStorage fs(index_path, FileStorage::READ);\n\tFileNode imgs = fs[\"index\"];\n\tFileNodeIterator it;\n\tint img_count = 0;\n\tvector<pair<int, int> > query_ids;\n\tfor (it = imgs.begin(); it != imgs.end(); ++it, ++img_count) {\n\t\tstring img_path;\n\t\tvector<KeyPoint> img_keypoint;\n\t\tMat img_descriptor;\n\n\t\t(*it)[\"path\"] >> img_path;\n\t\tread((*it)[\"keypoints\"], img_keypoint);\n\t\t(*it)[\"descriptors\"] >> img_descriptor;\n\n\t\timg_paths.push_back(img_path);\n\t\timg_keypoints.push_back(img_keypoint);\n\t\timg_descriptors.push_back(img_descriptor);\n\n\t\tfor (int i = 0; i < query_count; ++i) {\n\t\t\tif (img_path == query_paths[i])\n\t\t\t\tquery_ids.push_back(pair<int, int>(img_count, i));\n\t\t}\n\t}\n\n\tquery_count = query_ids.size();\n\n\tcout << \"Calcing emds...\" << endl;\n\n\tint total_process = query_count * img_count;\n\tint completed_process = 0;\n\ttime_t start = time(0);\n\n\tstring img_path_1, img_path_2;\n\tint query_id;\n\n\tofstream ofile(out_path);\n\n\ttictoc timer;\n\ttimer.tic();\n\t// calculate emd distances of each pair of images\n\tfor (int i = 0; i < query_count; ++i) {\n\t\tquery_id = query_ids[i].first;\n\t\timg_path_1 = query_paths[query_ids[i].second];\n\n\t\tfor (int j = 0; j < img_count; ++j) {\n\t\t\tif (query_id == j)\n\t\t\t\tcontinue;\n\n\t\t\timg_path_2 = img_paths[j];\n\n\t\t\tdouble emd_dist;\n\t\t\tif (use_fast_emd)\n\t\t\t\temd_dist = calc_fast_emd(query_id, j);\n\t\t\telse\n\t\t\t\temd_dist = calc_emd(query_id, j);\n\t\t\t\n\t\t\t// cout << setprecision(3) << fixed;\n\t\t\t// timer.clear();\n\t\t\t// timer.tic();\n\t\t\t// emd_dist = calc_fast_emd(i, j);\n\t\t\t// timer.toc();\n\t\t\t// cout << \"fast: \" << timer.totalTimeSec() << endl;\n\t\t\t// cout << img_path_1 << \" \" << img_path_2 << \" \" << emd_dist << endl;\n\t\t\t\n\t\t\t// timer.clear();\n\t\t\t// timer.tic();\n\t\t\t// emd_dist = calc_emd(i, j);\n\t\t\t// timer.toc();\n\t\t\t// cout << \"rubner: \" << timer.totalTimeSec() << endl;\n\t\t\t// cout << img_path_1 << \" \" << img_path_2 << \" \" << emd_dist << endl;\n\n\t\t\tofile << setprecision(3) << fixed;\n\t\t\tofile << img_path_1 << \" \" << img_path_2 << \" \" << emd_dist << endl;\n\n\t\t\t// print_progress(start, total_process, completed_process, 20);\n\t\t}\n\t}\n\ttimer.toc();\n\tcout << \"Time in seconds: \" << timer.totalTimeSec() << endl;\n\n\tofile.close();\n\n\treturn 0;\n}\n\nvoid help() {\n\tcout << \"Usage: ./feature-selection <index_path> <queries_path> <out_path> <fast_thresh=350>\" << endl;\n}\n\nvoid print_progress(time_t start, int total, int& completed, int per_count) {\n\t++completed;\n\tif (completed % per_count != 0)\n\t\treturn;\n\tint remaining_process = total - completed;\n\ttime_t current = time(0);\n\tfloat elapsed_time = difftime(current, start);\n\tfloat remaining_time = elapsed_time * remaining_process / completed;\n\tcout << fixed << setprecision(3);\n\tcout << \"Remaining time: \";\n\tcout << remaining_time / 60 << \"min\" << endl;\n}\n\nvoid print_keypoints(const vector<KeyPoint>& kp) {\n\tKeyPoint k;\n\tfor (int i = 0; i < (int) kp.size(); ++i) {\n\t\tk = kp[i];\n\t\tcout << \"(\" << k.pt.x << \",\" << k.pt.y << \"): \" << k.response << \", \" << k.size << endl;\n\t}\n}\n\nfloat calc_emd(int first, int second) {\n\tvector<KeyPoint> *keypoints_1, *keypoints_2;\n\tMat *desc_1, *desc_2;\n\n\tkeypoints_1 = &img_keypoints[first];\n\tdesc_1 = &img_descriptors[first];\n\n\tkeypoints_2 = &img_keypoints[second];\n\tdesc_2 = &img_descriptors[second];\n\n\tcalc_dist_mat(*desc_1, *desc_2);\n\n\tint feature_count_1 = keypoints_1->size();\n\tint feature_count_2 = keypoints_2->size();\n\n\tsignature_t signature_1;\n\tsignature_t signature_2;\n\n\tsignature_1.n = feature_count_1;\n\tsignature_2.n = feature_count_2;\n\n\tsignature_1.Features = new feature_t[feature_count_1];\n\tsignature_2.Features = new feature_t[feature_count_2];\n\n\tsignature_1.Weights = new float[feature_count_1];\n\tsignature_2.Weights = new float[feature_count_2];\n\n\tfor (int i = 0; i < feature_count_1; ++i) {\n\t\tsignature_1.Weights[i] = calc_scalar_manitude(*desc_1, i);\n\t\tsignature_1.Features[i] = i;\n\t}\n\n\tfor (int i = 0; i < feature_count_2; ++i) {\n\t\tsignature_2.Weights[i] = calc_scalar_manitude(*desc_2, i);\n\t\tsignature_2.Features[i] = i;\n\t}\n\n\tfloat dist = emd(&signature_1, &signature_2, emd_dist, 0, 0);\n\n\tdelete[] signature_1.Features;\n\tdelete[] signature_1.Weights;\n\tdelete[] signature_2.Features;\n\tdelete[] signature_2.Weights;\n\n\t// cout << \"EMD: \" << dist << endl;\n\n\treturn dist;\n}\n\ndouble calc_fast_emd(int first, int second) {\n\tvector<KeyPoint> *keypoints_1, *keypoints_2;\n\tMat *desc_1, *desc_2;\n\n\tkeypoints_1 = &img_keypoints[first];\n\tdesc_1 = &img_descriptors[first];\n\n\tkeypoints_2 = &img_keypoints[second];\n\tdesc_2 = &img_descriptors[second];\n\n\tcalc_dist_mat(*desc_1, *desc_2, true);\n\n\tint feature_count_1 = keypoints_1->size();\n\tint feature_count_2 = keypoints_2->size();\n\n\tsignature_tt<double> signature_1;\n\tsignature_tt<double> signature_2;\n\n\tsignature_1.n = feature_count_1;\n\tsignature_2.n = feature_count_2;\n\n\tsignature_1.Features = new feature_tt[feature_count_1];\n\tsignature_2.Features = new feature_tt[feature_count_2];\n\n\tsignature_1.Weights = new double[feature_count_1];\n\tsignature_2.Weights = new double[feature_count_2];\n\n\tfor (int i = 0; i < feature_count_1; ++i) {\n\t\tsignature_1.Weights[i] = calc_scalar_manitude(*desc_1, i);\n\t\tsignature_1.Features[i] = i;\n\t}\n\n\tfor (int i = 0; i < feature_count_2; ++i) {\n\t\tsignature_2.Weights[i] = calc_scalar_manitude(*desc_2, i);\n\t\tsignature_2.Features[i] = i;\n\t}\n\n\tdouble dist = emd_hat_signature_interface<double>(&signature_1, &signature_2, fast_emd_dist, -1);\n\n\tdelete[] signature_1.Features;\n\tdelete[] signature_1.Weights;\n\tdelete[] signature_2.Features;\n\tdelete[] signature_2.Weights;\n\n\t// cout << \"EMD: \" << dist << endl;\n\n\treturn dist / 1000;\n}\n\nfloat calc_scalar_manitude(const Mat& desc, int index) {\n\tconst float* d = desc.ptr<float>(index);\n\tint cols = desc.cols;\n\tfloat magnitude = 0;\n\tfor (int i = 0; i < cols; ++i)\n\t\tmagnitude += d[i] * d[i];\n\treturn sqrt(magnitude);\n}\n\nvoid calc_dist_mat(const Mat& desc_1, const Mat& desc_2, bool gd) {\n\tfloat dist;\n\tint rows = desc_1.rows;\n\tint cols = desc_2.rows;\n\tint dim1 = desc_1.cols;\n\tint dim2 = desc_2.cols;\n\tdist_mat = Mat::zeros(rows, cols, CV_32F);\n\tfor (int i = 0; i < rows; ++i) {\n\t\tfloat *row = dist_mat.ptr<float>(i);\n\t\tconst float *v1 = desc_1.ptr<float>(i);\n\t\tfor (int j = 0; j < cols; ++j) {\n\t\t\tconst float *v2 = desc_2.ptr<float>(j);\n\t\t\tdist = euclid_dist(v1, v2, dim1, dim2);\n\t\t\tif (gd)\n\t\t\t\trow[j] = gd_dist < dist ? gd_dist : dist;\n\t\t\telse\n\t\t\t\trow[j] = dist;\n\t\t}\n\t}\n}\n\nfloat euclid_dist(const float *v1, const float *v2, int dim1, int dim2) {\n\tint max_dim = max(dim1, dim2);\n\tfloat d1, d2;\n\tfloat dist = 0;\n\tfor (int i = 0; i < max_dim; ++i) {\n\t\tif (i < dim1)\n\t\t\td1 = v1[i];\n\t\telse\n\t\t\td1 = 0;\n\n\t\tif (i < dim2)\n\t\t\td2 = v2[i];\n\t\telse\n\t\t\td2 = 0;\n\n\t\tdist += pow(d1 - d2, 2);\n\t}\n\treturn sqrt(dist);\n}\n\nfloat emd_dist(feature_t *f1, feature_t *f2) {\n\tfloat dist = dist_mat.at<float>(*f1, *f2);\n\treturn dist;\n}\n\ndouble fast_emd_dist(feature_tt *f1, feature_tt *f2) {\n\tdouble dist = dist_mat.at<float>(*f1, *f2);\n\treturn dist;\n}\n", "meta": {"hexsha": "011985741fca7e4db89d85ef751e83324ff1d8a1", "size": 9095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "query_index.cpp", "max_stars_repo_name": "byildiz/feature-selection", "max_stars_repo_head_hexsha": "822484374b5a1a5ce385045e908148abfc4d2901", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "query_index.cpp", "max_issues_repo_name": "byildiz/feature-selection", "max_issues_repo_head_hexsha": "822484374b5a1a5ce385045e908148abfc4d2901", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "query_index.cpp", "max_forks_repo_name": "byildiz/feature-selection", "max_forks_repo_head_hexsha": "822484374b5a1a5ce385045e908148abfc4d2901", "max_forks_repo_licenses": ["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.9116809117, "max_line_length": 103, "alphanum_fraction": 0.6794942276, "num_tokens": 2766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5385668037806446}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <vector>\n#include <string>\n#include \"fringe_topofit.hpp\"\n\n\nint main(int argc, char **argv)\n{\n   \n    std::vector<std::string> files(4);\n    files[0] = \"test1.dat\";\n    files[1] = \"test2.dat\";\n    files[2] = \"test3.dat\";\n\n    std::complex<float> cJ(0.0, 1.0);\n\n    for(int ii=0; ii<3; ii++)\n    {\n        arma::fvec alldata;\n        alldata.load(files[ii], arma::raw_binary);\n\n        int nifg = (alldata.size() - 4)/2;\n        arma::fvec bperp(alldata.memptr() + 4, nifg, false);\n        arma::fvec ph(alldata.memptr()+nifg+4, nifg, false);\n        \n        arma::cx_fvec cph(nifg);\n        arma::cx_fvec resid(nifg);\n\n        for(int kk=0; kk<nifg; kk++)\n            cph[kk] = std::exp(cJ * ph[kk]);\n\n        float wvl = alldata[0];\n        float rng = alldata[1];\n        float inc = alldata[2];\n        float delz = alldata[3];\n\n        float Kmod, Cph;\n\n        topofit worker(20.0, 0.1, wvl, nifg);\n        \n        float coh = worker.fit(cph.memptr(), bperp.memptr(), rng, inc, resid.memptr(), Kmod, Cph);\n        std::cout << \"File: \" << files[ii] << \" K: \" << Kmod\n                << \" C: \" << Cph << \" coh: \" << coh \n                << \" K_true: \" << delz/(wvl*rng*sin(inc*M_PI/180.0)/4.0/M_PI)<< \"\\n\";\n    }\n}\n", "meta": {"hexsha": "f005abaceca74dd9c34bb800fef0707469cf8e99", "size": 1270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/topofit/test_fit.cpp", "max_stars_repo_name": "dbekaert/fringe", "max_stars_repo_head_hexsha": "c696c3651777d8007406fbce4470a16a39948f74", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T18:57:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:35:53.000Z", "max_issues_repo_path": "tests/topofit/test_fit.cpp", "max_issues_repo_name": "dbekaert/fringe", "max_issues_repo_head_hexsha": "c696c3651777d8007406fbce4470a16a39948f74", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2020-04-12T12:11:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T06:00:21.000Z", "max_forks_repo_path": "tests/topofit/test_fit.cpp", "max_forks_repo_name": "dbekaert/fringe", "max_forks_repo_head_hexsha": "c696c3651777d8007406fbce4470a16a39948f74", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2020-03-29T14:39:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T02:04:27.000Z", "avg_line_length": 26.4583333333, "max_line_length": 98, "alphanum_fraction": 0.511023622, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.5385667977209123}}
{"text": "#include \"Tensor.h\"\n#include \"AnisGeodesic.h\"\n#include <iostream>\n\n#include <Eigen/Dense>\nusing namespace Eigen;\n\nusing namespace GeoProperty;\n\n\nvoid Tensor::makeTensor(const Vec3& d1,const Vec3& d2,Tensor &t)\n{\n\tMatrix2d hesMat = Eigen::Matrix2d::Constant(2, 2, 0.0);\n\tfor (unsigned i = 0; i < 2; i++)\n\t{\n\t\tfor (unsigned j = 0; j < 2; j++)\n\t\t{\n\t\t\thesMat(i, j) = t.mat[i][j];\n\t\t}\n\t}\n\n\tSelfAdjointEigenSolver<Matrix2d> vd(hesMat);\n\tVector2d egval = vd.eigenvalues();\n\tMatrix2d egvec = vd.eigenvectors();\n\n\tunsigned ind1 = 0, ind2 = 1;\n\n\tt.mag1 = abs(egval[ind1]); t.mag2 = abs(egval[ind2]);\n\tt.dir1 = egvec(ind1, 0) * d1 + egvec(ind1, 1) * d2; t.dir1.normalize();\n\tt.dir2 = egvec(ind2, 0) * d1 + egvec(ind2, 1) * d2; t.dir2.normalize();\n}\n\nvoid Tensor::averageTensor(Tensor &t1,Tensor &t2,Tensor &t)\n{\n\tdouble rat1= 0.5;\n\tdouble rat2= 0.5;\n\n\tt1.mat[0][0]=t1.mag1; t1.mat[1][1]=t1.mag2;\n\tt1.mat[0][1]=t1.mat[1][0]=0;\n\n\tVec2 v1_,v2_;\n\tv1_.x=t2.dir1.dot(t1.dir1); v1_.y=t2.dir1.dot(t1.dir2);\n\tv2_.x=t2.dir2.dot(t1.dir1); v2_.y=t2.dir2.dot(t1.dir2);\n\n\tt2.mat[0][0]= t2.mag1*v1_.x*v1_.x+t2.mag2*v2_.x*v2_.x;\n\tt2.mat[0][1]= t2.mat[1][0]= t2.mag1*v1_.x*v1_.y+t2.mag2*v2_.x*v2_.y;\n\tt2.mat[1][1]= t2.mag1*v1_.y*v1_.y+t2.mag2*v2_.y*v2_.y;\n\n\tMatrix2d hesMat = Eigen::Matrix2d::Constant(2, 2, 0.0);\n\tfor (unsigned i = 0; i < 2; i++)\n\t{\n\t\tfor (unsigned j = 0; j < 2; j++)\n\t\t{\n\t\t\thesMat(i, j) = rat1*t1.mat[i][j] + rat2*t2.mat[i][j];\n\t\t}\n\t}\n\n\tSelfAdjointEigenSolver<Matrix2d> vd(hesMat);\n\tVector2d egval = vd.eigenvalues();\n\tMatrix2d egvec = vd.eigenvectors();\n\n\tunsigned ind1 = 0, ind2 = 1;\n\tif (abs(egval[0]) > abs(egval[1])) //////////////////////////////\n\t\tswap(ind1, ind2);\n\n\tdouble nl = (abs(t1.mag1) + abs(t1.mag2) + abs(t2.mag1) + abs(t2.mag2));\n\tif (nl > 1e-10)\n\t\tnl /= (2.0*(abs(egval[ind1]) + abs(egval[ind2])));\n\telse\n\t\tnl = 1;\n\n\tt.mag1 = egval[ind1] * nl; t.mag2 = egval[ind2] * nl; //how to normalized it is very important;\n\tt.dir1 = egvec(ind1, 0) * t1.dir1 + egvec(ind1, 1) * t1.dir2; t.dir1.normalize();\n\tt.dir2 = egvec(ind2, 0) * t1.dir1 + egvec(ind2, 1) * t1.dir2; t.dir2.normalize();\n}\n\nvoid Tensor::averageTensor(std::vector<Tensor> &ts,Tensor &t, double rat)\n{\n\tstd::vector<double> rats(ts.size(),rat/double(ts.size()-1)); rats[0]=1-rat;\n\tTensor& t1=ts.front();\n\tt1.mat[0][0]=t1.mag1; t1.mat[1][1]=t1.mag2;\n\tt1.mat[0][1]=t1.mat[1][0]=0;\n\tif(ts.size()==1) {t=t1; return;}\n\n\tVec2 v1_,v2_;\n\tfor(unsigned i=1;i<ts.size();i++)\n\t{\n\t\tTensor& t2=ts[i];\n\t\tv1_.x=t2.dir1.dot(t1.dir1); v1_.y=t2.dir1.dot(t1.dir2);\n\t\tv2_.x=t2.dir2.dot(t1.dir1); v2_.y=t2.dir2.dot(t1.dir2);\n\t\tt2.mat[0][0]= t2.mag1*v1_.x*v1_.x+t2.mag2*v2_.x*v2_.x;\n\t\tt2.mat[0][1]= t2.mat[1][0]= t2.mag1*v1_.x*v1_.y+t2.mag2*v2_.x*v2_.y;\n\t\tt2.mat[1][1]= t2.mag1*v1_.y*v1_.y+t2.mag2*v2_.y*v2_.y;\n\t}\n\n\tMatrix2d hesMat = Eigen::Matrix2d::Constant(2, 2, 0.0);\n\tfor(unsigned i=0;i<2;i++)\n\t{\n\t\tfor (unsigned j = 0; j < 2; j++)\n\t\t{\n\t\t\tfor (unsigned k = 0; k < ts.size(); k++)\n\t\t\t{\n\t\t\t\thesMat(i, j) += rats[k] * ts[k].mat[i][j];\n\t\t\t}\n\t\t}\n\t}\n\n\tSelfAdjointEigenSolver<Matrix2d> vd(hesMat);\n\tVector2d egval = vd.eigenvalues();\n\tMatrix2d egvec = vd.eigenvectors();\n\n\tunsigned ind1 = 0, ind2 = 1;\n\tif (abs(egval[0]) < abs(egval[1]))\n\t\tswap(ind1, ind2);\n\n\tdouble nl = 0;\n\tfor (unsigned i = 0; i<ts.size(); i++)\n\t\tnl += rats[i] * abs(ts[i].mag1) + abs(ts[i].mag2);\n\tif (nl>1e-10)\n\t\tnl /= ts.size()*(abs(egval[ind1]) + abs(egval[ind2]));\n\telse\n\t\tnl = 1;\n\n\tt.mag1 = egval[ind1] * nl; t.mag2 = egval[ind2] * nl; //how to normalized it is very important;\n\tt.dir1 = egvec(ind1, 0) * t1.dir1 + egvec(ind1, 1) * t1.dir2; t.dir1.normalize();\n\tt.dir2 = egvec(ind2, 0) * t1.dir1 + egvec(ind2, 1) * t1.dir2; t.dir2.normalize();\n}\n\nvoid Tensor::averageTensor(Tensor &t1,Tensor &t2,Tensor &t, double rat)\n{\n\tdouble rat1= 1-rat;\n\n\tt1.mat[0][0]=t1.mag1; t1.mat[1][1]=t1.mag2;\n\tt1.mat[0][1]=t1.mat[1][0]=0;\n\n\tVec2 v1_,v2_;\n\tv1_.x=t2.dir1.dot(t1.dir1); v1_.y=t2.dir1.dot(t1.dir2);\n\tv2_.x=t2.dir2.dot(t1.dir1); v2_.y=t2.dir2.dot(t1.dir2);\n\n\tt2.mat[0][0]= t2.mag1*v1_.x*v1_.x+t2.mag2*v2_.x*v2_.x;\n\tt2.mat[0][1]= t2.mat[1][0]= t2.mag1*v1_.x*v1_.y+t2.mag2*v2_.x*v2_.y;\n\tt2.mat[1][1]= t2.mag1*v1_.y*v1_.y+t2.mag2*v2_.y*v2_.y;\n\n\tMatrix2d hesMat = Eigen::Matrix2d::Constant(2, 2, 0.0);\n\tfor(unsigned i=0;i<2;i++)\n\t{\n\t\tfor (unsigned j = 0; j < 2; j++)\n\t\t{\n\t\t\thesMat(i, j) = rat1*t1.mat[i][j] + rat*t2.mat[i][j];\n\t\t}\n\t}\n\n\tSelfAdjointEigenSolver<Matrix2d> vd(hesMat);\n\tVector2d egval = vd.eigenvalues();\n\tMatrix2d egvec = vd.eigenvectors();\n\n\tunsigned ind1 = 0, ind2 = 1;\n\tif ((abs(egval[0]) < abs(egval[1])) && (t1.mag1 >= t1.mag2) || (abs(egval[0]) > abs(egval[1])) && (t1.mag1<t1.mag2))\n\t\tswap(ind1, ind2);\n\n\tdouble nl = (abs(t1.mag1) + abs(t1.mag2) + abs(t2.mag1) + abs(t2.mag2));\n\tif (nl>1e-10)\n\t\tnl /= (2.0*(abs(egval[ind1]) + abs(egval[ind2])));\n\telse\n\t\tnl = 1;\n\n\tt.mag1 = egval[ind1] * nl; t.mag2 = egval[ind2] * nl; //how to normalized it is very important;\n\tt.dir1 = egvec(ind1, 0) * t1.dir1 + egvec(ind1, 1) * t1.dir2; t.dir1.normalize();\n\tt.dir2 = egvec(ind2, 0) * t1.dir1 + egvec(ind2, 1) * t1.dir2; t.dir2.normalize();\n}\n\nvoid Tensor::averageTensor(std::vector<Tensor> &ts,Tensor &t)\n{\n\tif (ts.empty()) return;\n\n\tTensor& t1=ts.front();\n\tt1.mat[0][0]=t1.mag1; t1.mat[1][1]=t1.mag2;\n\tt1.mat[0][1]=t1.mat[1][0]=0;\n\n\tif(ts.size()==1) \n\t{\n\t\tt=t1; return;\n\t}\n\t\n\tfor(unsigned i=1;i<ts.size();i++)\n\t{\n\t\tTensor& t2=ts[i];\n\n\t\tVec2 v1(t2.dir1.dot(t1.dir1), t2.dir1.dot(t1.dir2));\n\t\tVec2 v2(t2.dir2.dot(t1.dir1), t2.dir2.dot(t1.dir2));\n\n\t\tt2.mat[0][0] = t2.mag1*v1.x*v1.x + t2.mag2*v2.x*v2.x;\n\t\tt2.mat[0][1] = t2.mat[1][0] = t2.mag1*v1.x*v1.y + t2.mag2*v2.x*v2.y;\n\t\tt2.mat[1][1] = t2.mag1*v1.y*v1.y + t2.mag2*v2.y*v2.y;\n\t}\n\n\tMatrix2d hesMat = Eigen::Matrix2d::Constant(2, 2, 0.0);\n\tfor (unsigned k = 0; k < ts.size(); k++)\n\t{\n\t\thesMat(0, 0) += ts[k].mat[0][0];\n\t\thesMat(0, 1) += ts[k].mat[0][1];\n\t\thesMat(1, 0) += ts[k].mat[1][0];\n\t\thesMat(1, 1) += ts[k].mat[1][1];\n\t}\n\tSelfAdjointEigenSolver<Matrix2d> vd(hesMat);\n\tVector2d egval = vd.eigenvalues();\n\tMatrix2d egvec = vd.eigenvectors();\n\n\tunsigned ind1 = 0, ind2 = 1;\n\tif (abs(egval[0]) < abs(egval[1]))\n\t\tswap(ind1, ind2);\n\n\tdouble nl = 0;\n\tfor (unsigned i = 0; i<ts.size(); i++)\n\t\tnl += abs(ts[i].mag1) + abs(ts[i].mag2);\n\tif (nl>1e-10)\n\t\tnl /= ts.size()*(abs(egval[ind1]) + abs(egval[ind2]));\n\telse\n\t\tnl = 1;\n\n\tt.mag1 = egval[ind1] * nl; t.mag2 = egval[ind2] * nl; //how to normalized it is very important;\n\tt.dir1 = egvec(ind1, 0) * t1.dir1 + egvec(ind1, 1) * t1.dir2; t.dir1.normalize();\n\tt.dir2 = egvec(ind2, 0) * t1.dir1 + egvec(ind2, 1) * t1.dir2; t.dir2.normalize();\n}\n\nvoid Tensor::computeTriangleCurvature(MyMesh* orgMesh,std::vector<Tensor>& faceTensor)\n{\n\t/*\n\tint fNum = orgMesh->getFaces().size();\n\tfaceTensor.clear(); faceTensor.resize(fNum);\n\tconst auto& fts = orgMesh->getFIter();\n#pragma omp parallel for\n\tfor(int i=0;i<fNum;i++){\n\t\tauto f_it = fts[i];\n\t\tMyMesh::VertexIter v[3]={f_it->vertex_iter(0),f_it->vertex_iter(1),f_it->vertex_iter(2)};\n\n\t\t// local coord system for single triangle;\n\t\tVec3 axix = v[1]->coordinate()- v[0]->coordinate(); axix.normalize();\n\t\tVec3 axiy = v[2]->coordinate()- v[0]->coordinate();\n\t\tVec3 norm = axix.cross(axiy); norm.normalize();\n\t\taxiy = norm.cross(axix); axiy.normalize();\n\n\t\tstd::vector<Tensor> ts(3);\n\t\tfor(unsigned i=0;i<3;i++){\n\t\t\tts[i].dir1 = basicNormalTransport(v[i]->normal(),norm,v[i]->direction(0));\n\t\t\tts[i].dir2 = basicNormalTransport(v[i]->normal(),norm,v[i]->direction(1));\n\t\t\tts[i].mag1 = v[0]->magnitude(0);\n\t\t\tts[i].mag2 = v[0]->magnitude(1);\n\t\t}\n\n\t\tTensor t;\n\t\taverageTensor(ts,t);\n\t\tfaceTensor[i] =t;\n/*  \n\t//second method;  which seems wrong, but whose result is close to method 1;\n\t\tdouble anis[2];\n\t\tJacobi jcb(2);\n\t\tfor(unsigned i=0;i<2;i++){\n\t\t\tstd::vector<std::vector<double> > mat(2,std::vector<double>(2,0));\n\t\t\tfor(unsigned j=0;j<3;j++){\n\t\t\t\tVec3 projVec = v_its[j]->direction(i); projVec.normalize();\n\t\t\t\tprojVec -= projVec.dot(norm) * norm; projVec.normalize();\n\n\t\t\t\tdouble x = v_its[j]->direction(i).dot(u);\t\n\t\t\t\tdouble y = v_its[j]->direction(i).dot(v);\n\n\t\t\t\tmat[0][0] += v_its[j]->magnitude(i)*x*x;\n\t\t\t\tmat[0][1] += v_its[j]->magnitude(i)*x*y;\n\t\t\t\tmat[1][1] += v_its[j]->magnitude(i)*y*y;\n\t\t\t}\n\t\t\tmat[1][0] = mat[0][1];\n\n\t\t\tjcb.setMatrix(mat);\n\t\t\tjcb.run();\n\n\t\t\tstd::vector<double> egvalue = jcb.getEigenvalues();\n\n\t\t\tstd::vector<std::vector<double> > egvector = jcb.getEigenvectors();\n\t\t\tunsigned ind=0;\n\t\t\tif(egvalue[0]<egvalue[1]) ind=1 ;\n\t\t\tVec3 td = u*egvector[ind][0] + v*egvector[ind][1]; td.normalize();\n\n\t\t\tanis[i]= *std::max_element(egvalue.begin(),egvalue.end());\n\t\t}\n\t\tfaceAnis.push_back(abs(anis[1]-anis[0]));\n*/\n//\t}\n\n\tfaceTensor.clear();\n\tTensor t;\n\tfor(auto f_it = orgMesh->getFaces().begin(); f_it!=orgMesh->getFaces().end(); f_it++)\n\t{\n\t\tMyMesh::VertexIter v[3]={f_it->vertex_iter(0),f_it->vertex_iter(1),f_it->vertex_iter(2)};\n\n\t\t// local coord system for single triangle;\n\t\tVec3 axix = v[1]->coordinate()- v[0]->coordinate(); axix.normalize();\n\t\tVec3 axiy = v[2]->coordinate()- v[0]->coordinate();\n\t\tVec3 norm = axix.cross(axiy); norm.normalize();\n\t\taxiy = norm.cross(axix); axiy.normalize();\n\n\t\tstd::vector<Tensor> ts(3);\n\t\tfor(unsigned i=0;i<3;i++)\n\t\t{\n\t\t\tts[i].dir1 = basicNormalTransport(v[i]->normal(),norm,v[i]->direction(0));\n\t\t\tts[i].dir2 = basicNormalTransport(v[i]->normal(),norm,v[i]->direction(1));\n\t\t\tts[i].mag1 = v[i]->magnitude(0);\n\t\t\tts[i].mag2 = v[i]->magnitude(1);\n\t\t}\n\n\t\taverageTensor(ts,t);\n\t\tfaceTensor.push_back(t);\n\t}\n}\n\nTensor GeoProperty::lineSearchHessian(Vec3& v, Tensor& tensor)\n{\n\tdouble x = v.dot(tensor.dir1);\n\tdouble y = v.dot(tensor.dir2);\n\n\t/*\n\tdouble denom = pow(x,2)*tensor.mag1+pow(y,2)*tensor.mag2;\n\tdouble denomSqrt = sqrt(denom);\n\tdouble upscale = 1e5;\n\n\ttensor.mat[0][0]=tensor.mag1;\n\ttensor.mat[1][1]=tensor.mag2;\n\ttensor.mat[0][1]=tensor.mat[1][0]=0;\n\tTensor res;\n\tfor (int i = 0; i < 2; i++){\n\tfor (int j = 0; j < 2; j++){\n\tdouble t1 = 0.0 , t2 = 0.0;\n\tfor (int k = 0; k < 2; k++){\n\tt1 += tensor.mat[i][k] * vecProj[k];\n\tt2 += tensor.mat[j][k] * vecProj[k];\n\t}\n\tres.mat[i][j] = (0.5 * tensor.mat[i][j] * upscale) / (denomSqrt * upscale) -\n\t(0.5 * t1 * upscale * t2) / (denom * upscale * denomSqrt);\n\t}\n\t}\n\t*/\n\n\t//make it as a metric tensor\n\n\tdouble a = tensor.mag1;\n\tdouble d = tensor.mag2;\n\n\tdouble dis = a*x*x + d*y*y;\n\tdouble dis23 = sqrt(dis) * dis;\n\n\tTensor res;\n\tif (dis23>1e-8)\n\t{\n\t\tres.mat[0][0] = a / dis - a*a*x*x / dis23;\n\t\tres.mat[0][1] = -a*d*x*y / dis23;\n\t\tres.mat[1][0] = res.mat[0][1];\n\t\tres.mat[1][1] = d / dis - d*d*y*y / dis23;\n\t\tTensor::makeTensor(tensor.dir1, tensor.dir2, res);\n\t}\n\treturn res;\n}\n\n// double Tensor::compareTensors(Tensor& t1, Tensor& t2, std::vector<Vec2> vs)\n// {\n// \t//compute the difference of two tensors.... it is hard to define the difference..\n// /*\n// \tU1 = {{a1, b1}, {c1, d1}} ;\n// \tU2 = {{a2, b2}, {c2, d2}};\n// \tV = {Cos[#], Sin[#]} &;\n// \tSum[Power[Sqrt[V[x].U1.V[x]] - Sqrt[V[x].U2.V[x]], 2], {x, 0, Pi,\n// \t\tPi/360}]\n// */\n// \tt1.mat[0][0]=t1.mag1; t1.mat[1][1]=t1.mag2;\n// \tt1.mat[0][1]=t1.mat[1][0]=0;\n// \n// \tVec2 v1_,v2_;\n// \tv1_.x=t2.dir1.dot(t1.dir1); v1_.y=t2.dir1.dot(t1.dir2);\n// \tv2_.x=t2.dir2.dot(t1.dir1); v2_.y=t2.dir2.dot(t1.dir2);\n// \tt2.mat[0][0]= t2.mag1*v1_.x*v1_.x+t2.mag2*v2_.x*v2_.x;\n// \tt2.mat[0][1]= t2.mat[1][0]= t2.mag1*v1_.x*v1_.y+t2.mag2*v2_.x*v2_.y;\n// \tt2.mat[1][1]= t2.mag1*v1_.y*v1_.y+t2.mag2*v2_.y*v2_.y;\n// \n// \t//Sum[Power[Sqrt[V[x].U1.V[x]] - Sqrt[V[x].U2.V[x]], 2]\n// \tdouble ds=0;\n// \tfor(unsigned i=0;i<vs.size();i++)\n// \t{\n// \t\tds+= pow(\n// \t\t\tsqrt(abs((vs[i].x*t1.mat[0][0] + vs[i].y*t1.mat[1][0])*vs[i].x + (vs[i].x*t1.mat[0][1] + vs[i].y*t1.mat[1][1])*vs[i].y)) -\n// \t\t\tsqrt(abs((vs[i].x*t2.mat[0][0] + vs[i].y*t2.mat[1][0])*vs[i].x + (vs[i].x*t2.mat[0][1] + vs[i].y*t2.mat[1][1])*vs[i].y))\n// \t\t\t,2);\n// \t}\n// /*\n// \tfor(unsigned i=0;i<vs.size();i++){\n// \t\tds+= abs(\n// \t\t\tsqrt(abs((vs[i].x*t1.mat[0][0] + vs[i].y*t1.mat[1][0])*vs[i].x + (vs[i].x*t1.mat[0][1] + vs[i].y*t1.mat[1][1])*vs[i].y)) -\n// \t\t\tsqrt(abs((vs[i].x*t2.mat[0][0] + vs[i].y*t2.mat[1][0])*vs[i].x + (vs[i].x*t2.mat[0][1] + vs[i].y*t2.mat[1][1])*vs[i].y))\n// \t\t\t);\n// \t}\n// */\n// \treturn ds;\n// }\n", "meta": {"hexsha": "f08df814cce345dddf84ac8788119fc0eec82f8f", "size": 12083, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/AnisGeodesics/include/Tensor.cpp", "max_stars_repo_name": "yixin26/Mesh-Segmentation", "max_stars_repo_head_hexsha": "4c0a775d73970710ff5108aa47b1be8455231285", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2017-11-21T13:55:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T07:57:28.000Z", "max_issues_repo_path": "libs/AnisGeodesics/include/Tensor.cpp", "max_issues_repo_name": "yixin26/CurveNet-Mesh", "max_issues_repo_head_hexsha": "4c0a775d73970710ff5108aa47b1be8455231285", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-03-02T22:36:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T10:43:38.000Z", "max_forks_repo_path": "libs/AnisGeodesics/include/Tensor.cpp", "max_forks_repo_name": "yixin26/CurveNet-Mesh", "max_forks_repo_head_hexsha": "4c0a775d73970710ff5108aa47b1be8455231285", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-01-15T08:57:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T12:03:57.000Z", "avg_line_length": 30.1321695761, "max_line_length": 128, "alphanum_fraction": 0.5912438964, "num_tokens": 5023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758842, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5385667951277383}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <fstream>\n#include <cassert>\n#include <time.h>\n#include <queue>\n\n//#include <boost/heap/fibonacci_heap.hpp>\n\n#include \"CRS.h\"\n\nusing namespace std;\n\nCRS data;\nbool* relaxed;\nunsigned* totalDist;\n\nclass ComparePair {\npublic:\n  bool operator()(pair<unsigned,unsigned> n1, pair<unsigned,unsigned> n2) {\n    if(n1.second > n2.second)\n      return true;\n    else\n      return false;\n  }\n};\npriority_queue<pair<unsigned, unsigned>, vector<pair<unsigned, unsigned> >, ComparePair> work;\n\ndouble abs(double val) {\n  if(val < 0)\n    return -1.0 * val;\n  else\n    return val;\n}\n\nunsigned min(unsigned a, unsigned b) {\n  return (a < b) ? a : b;\n}\n\nint main(int argc, char** argv) {\n  \n  if((argc != 3) && (argc != 5)) {\n    cout << \"ERROR: incorrect input parameters!\\n\";\n    cout << argv[0] << \" <input file name> <source vertex>\\n-- OR --\\n\";\n    cout << argv[0] << \" <input file name> <source vertex> -out <output file name>\" << endl;\n    exit(1);\n  }\n  \n  ifstream in(argv[1]);\n  unsigned source = atoi(argv[2]);\n  bool genOutput = false;\n  ofstream out(argv[4]);\n  if(argc == 5) {\n    genOutput = true;\n  }\n  \n  if(!in.is_open()) {\n    cout << \"ERROR: Can't open file \" << argv[1] << endl;\n    exit(1);\n  }\n  cout << \"Running on \" << argv[1] << \" with source vertex \" << source << endl;\n  time_t t1, t2, t3;\n  t1 = time(NULL);\n  \n  // Get vertices and edges\n  unsigned numVertices, numEdges;\n  in >> numVertices >> ws >> numEdges >> ws;\n  \n  totalDist = new unsigned[numVertices];\n  relaxed = new bool[numVertices];\n  for(int i = 0; i < numVertices; i++) {\n    relaxed[i] = false;\n    totalDist[i] = -1;\n  }\n  cout << \"EdgeDist initialized to \" << totalDist[0] << endl;\n  totalDist[source] = 0;\n  work.push(make_pair(source, 0));\n  \n  int src, dest, weight;\n  data.row->resize(numVertices);\n  while(in.good()) {\n    in >> src >> ws >> dest >> ws >> weight >> ws;\n    //cout << \"---\" << src << \" \" << dest << \" \" << weight << endl;\n    data.add(src, dest, weight);\n  }\n  //data.print();\n  t2 = time(NULL);\n  cout << \"Number of rows: \" << data.row->size() << endl;\n\n  cout << \"Running Dijkstra's Algorithm\\n\";\n  while(!work.empty()) {\n    pair<unsigned, unsigned> top = work.top();\n    work.pop();\n\n    //cout << \"Top: \" << top.first << \", \" << top.second << endl;\n    \n    int vertex = top.first;\n    if(relaxed[vertex])\n      continue;\n    \n    // Check for disconnected graphs!\n    if(totalDist[vertex] == -1) {\n      cout << \"Disconnected graph detected, break!\\n\";\n      break;\n    }\n    \n    relaxed[vertex] = true;\n\n    deque<pair<unsigned, unsigned> >* row = data.getRow(vertex);\n    if(row != NULL) {\n      for(deque<pair<unsigned,unsigned> >::iterator it = row->begin(); it!=row->end(); it++) {\n\tif(!relaxed[it->first]) {\n\t  // update distance\n\t  int dist = totalDist[vertex]+it->second;\n\t  if(dist < totalDist[it->first]) {\n\t    totalDist[it->first] = dist;\n\t    //cout << \"  Checking \" << it->first << \", minDist = \" << minDist << endl;\n\t    work.push(make_pair(it->first, dist));\n\t  }\n\t}\n      }\n    }\n  }\n  \n  t3 = time(NULL);\n  \n  cout << \"Setup time: \" << (t2 - t1) << \" seconds\\n\";\n  cout << \"Dijkstra SSSP time: \" << (t3 - t2) << \" seconds\\n\";\n  \n  if(genOutput) {\n    for(int i = 0; i < numVertices; i++) {\n      out <<  i << \",\" << totalDist[i] << endl;\n    }\n  }\n}\n", "meta": {"hexsha": "6605cdd632f48a77955c3d283c4d105e29e29e1e", "size": 3346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MX/SSSP/C_src/sssp_dij.cpp", "max_stars_repo_name": "dzhang50/convey", "max_stars_repo_head_hexsha": "65db1667705564535a8fc433c940ce9ceab4f620", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MX/SSSP/C_src/sssp_dij.cpp", "max_issues_repo_name": "dzhang50/convey", "max_issues_repo_head_hexsha": "65db1667705564535a8fc433c940ce9ceab4f620", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MX/SSSP/C_src/sssp_dij.cpp", "max_forks_repo_name": "dzhang50/convey", "max_forks_repo_head_hexsha": "65db1667705564535a8fc433c940ce9ceab4f620", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-22T07:01:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-22T07:01:57.000Z", "avg_line_length": 24.4233576642, "max_line_length": 94, "alphanum_fraction": 0.5678421996, "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5385207573221916}}
{"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/* Test_matmul.cpp - Testing the functionality of multiplying an encrypted\n * vector by a plaintext matrix, either over the extension- or the\n * base-field/ring.\n */\n#include <cassert>\n#include <NTL/lzz_pXFactoring.h>\n#include \"multiAutomorph.h\"\n#include \"FHE.h\"\n#include \"timing.h\"\n#include \"EncryptedArray.h\"\n\n// defined in debugging.cpp\nvoid decryptAndPrint(ostream& s, const Ctxt& ctxt, const FHESecKey& sk,\n\t\t     const EncryptedArray& ea, long flags);\n\nstatic void checkAuto(const Ctxt& cOrig, const Ctxt& cAuto, long amt,\n                      EncryptedArray& ea, const FHESecKey& sk)\n{\n  NewPlaintextArray v1(ea), v2(ea);\n  Ctxt cTmp = cOrig;\n  cTmp.smartAutomorph(amt);\n\n  ea.decrypt(cTmp, sk, v1);\n  ea.decrypt(cAuto, sk, v2);\n\n  if (!equals(ea, v1, v2)) { // check that we've got the right answer\n    cout << \" k = \"<<amt<<\"failed, Grrr@*\\n\";\n    exit(0);\n  }\n}\n\nclass AutoTester: public AutomorphHandler {\npublic:\n  const Ctxt& cOrig;\n  FHESecKey& sk;\n  EncryptedArray& ea;\n\n    AutoTester(const Ctxt& c, FHESecKey& k, EncryptedArray& e, bool v=false):\n    cOrig(c), sk(k), ea(e) {}\n\n  // cPtr points to the original ciphertext, ctxtx is after automorphism\n  bool handle(std::unique_ptr<Ctxt>& ctxt, long amt) override {\n    // check that ctxt is indeed the original ctxt after automorphism\n    checkAuto(cOrig, *ctxt, amt, ea, sk);\n\n    return true;\n  }\n};\n\nvoid  TestIt1(FHESecKey& secretKey, EncryptedArray& ea, bool verbose=false)\n{\n  const FHEcontext& context = ea.getContext();\n  const FHEPubKey& publicKey = secretKey;\n\n  // choose a random plaintext vector\n  NewPlaintextArray v(ea);\n  random(ea, v);\n\n  // encrypt the random vector\n  Ctxt ctxt(publicKey);\n  ea.encrypt(ctxt, publicKey, v);\n  ctxt.square();\n  ctxt.cube();\n\n  AutoTester test(ctxt, secretKey, ea);\n  for (long i=0; i<=ea.dimension(); i++) {\n    const AutGraph& tree = publicKey.getTree4dim(i);\n    multiAutomorph(ctxt, tree, test);\n  }\n  cout << \"  All tests using handler passed successfully\\n\";\n}\n\nvoid  TestIt2(FHESecKey& secretKey, EncryptedArray& ea, bool verbose=false)\n{\n  const FHEcontext& context = ea.getContext();\n  const FHEPubKey& publicKey = secretKey;\n\n  // choose a random plaintext vector\n  NewPlaintextArray v(ea);\n  random(ea, v);\n\n  // encrypt the random vector\n  Ctxt ctxt(publicKey);\n  ea.encrypt(ctxt, publicKey, v);\n  ctxt.square();\n  ctxt.cube();\n\n  Ctxt tmp(ZeroCtxtLike, ctxt);\n  for (long i=0; i<=ea.dimension(); i++) {\n    const AutGraph& tree = publicKey.getTree4dim(i);\n    std::unique_ptr<AutoIterator> it(AutoIterator::build(ctxt, tree));\n    while (long val = it->next(tmp))\n      checkAuto(ctxt, tmp, val, ea, secretKey);\n  }\n  cout << \"  All tests using iterator passed successfully\\n\";\n}\n\n\n\n/* Testing the new automorphism\n\n * Usage: Test_newAutomorph_x [optional params]\n *\n *  m defines the cyclotomic polynomial Phi_m(X) [default=2047]\n *    another useful setting to test is m=4369\n *  p is the plaintext base [default=2]\n *  L is the # of primes in the modulus chain [default=4]\n *  verbose print extra info [default=0]\n */\nint main(int argc, char *argv[]) \n{\n  ArgMapping amap;\n\n  long p=2;\n  amap.arg(\"p\", p, \"plaintext base\");\n  long m=2047;\n  amap.arg(\"m\", m, \"defines the cyclotomic polynomial Phi_m(X)\");\n  amap.note(\"another useful setting to test is m=4369, p=2\");\n  long L=15;\n  amap.arg(\"L\", L, \"# of levels in the modulus chain\");\n  bool verbose=false;\n  amap.arg(\"verbose\", verbose, \"print extra information\");\n  amap.parse(argc, argv);\n\n  cout << \"*** \"<<argv[0]\n       << \": m=\" << m\n       << \", p=\" << p\n       << \", L=\" << L\n       << endl;\n\n  FHEcontext context(m, p, 1);\n  buildModChain(context, L, /*c=*/3);\n    \n  FHESecKey secretKey(context);\n  secretKey.GenSecKey(/*w=*/64); // A Hamming-weight-w secret key\n\n  addSome1DMatrices(secretKey); // compute key-switching matrices that we need\n  addFrbMatrices(secretKey); // compute key-switching matrices that we need\n  EncryptedArray ea(context, context.alMod);\n\n  if (verbose) {\n    context.zMStar.printout();\n    cout << endl;\n    for (long i=0; i<=ea.dimension(); i++) {\n      cout << \"Tree(\"<<i<<\") =\\n\";\n      const AutGraph& tree = secretKey.getTree4dim(i);\n      for (auto x: tree) {\n        cout << \"  \"<< x.first<<\": \";\n        cout << x.second << endl;\n      }\n    }\n  }\n\n  resetAllTimers();  \n  TestIt1(secretKey, ea, verbose);\n  if (verbose) {\n    printAllTimers();\n    cout << endl;\n  }\n\n  resetAllTimers();\n  TestIt2(secretKey, ea, verbose);\n  if (verbose) {\n    printAllTimers();\n    cout << endl;\n  }\n}\n", "meta": {"hexsha": "f677f4f534d3701115d915c6ddae35e659e3e720", "size": 5152, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/misc/Test_multiAut.cpp", "max_stars_repo_name": "Valenceo/HElib", "max_stars_repo_head_hexsha": "f560416454d672e1253412c81840d2563ab9b456", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-01-29T09:29:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T13:32:07.000Z", "max_issues_repo_path": "src/misc/Test_multiAut.cpp", "max_issues_repo_name": "Valenceo/HElib", "max_issues_repo_head_hexsha": "f560416454d672e1253412c81840d2563ab9b456", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-05-17T21:41:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-18T21:37:26.000Z", "max_forks_repo_path": "src/misc/Test_multiAut.cpp", "max_forks_repo_name": "Valenceo/HElib", "max_forks_repo_head_hexsha": "f560416454d672e1253412c81840d2563ab9b456", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-01-30T08:15:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T12:21:00.000Z", "avg_line_length": 28.782122905, "max_line_length": 78, "alphanum_fraction": 0.663431677, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5385207402420946}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"functions/derivatives.hh\"\n#include \"functions/streaming.hh\"\n#include \"pointwise_equal.hh\"\n\nBOOST_AUTO_TEST_CASE(derivative_test) {\n  return;\n  using namespace manifolds;\n  BOOST_CHECK_EQUAL(Derivative(Sin()), Cos());\n  auto f = Cos()(x * x) * y;\n  auto d = Derivative(f);\n  auto check = 2_c * -x * Sin()(x * x) * y;\n  PointwiseEqual(d, check);\n\n  D<2> d2;\n  auto ddf = d2(f);\n  auto ddf2 = Derivative(d);\n  PointwiseEqual(ddf, ddf2);\n  auto fd = FullDerivative(f);\n  auto fd_check = GetFunctionMatrix(GetRow(d, Cos()(x * x)));\n  PointwiseEqual(fd, fd_check);\n  auto fd_check_d = Derivative(fd);\n  auto fd_check_check = GetFunctionMatrix(\n      GetRow(-2_c * Sin()(x * x) * y + -4_c * x * x * Cos()(x * x) * y,\n             -2_c * x * Sin()(x * x)));\n  PointwiseEqual(fd_check, fd_check_check);\n  PointwiseEqual(fd_check_d, fd_check_check);\n  auto p = Pow()(x, x);\n  auto pd = Derivative(p);\n  auto pd_check = (Log()(x) + 1_c) * Pow()(x, x);\n  PointwiseEqual(pd, pd_check, pointwise_default_num_points,\n                 pointwise_default_tolerance, 0.001);\n\n  auto m = D<3>()(Log()(x));\n  auto m_check = Derivative(Derivative(Derivative(Log()(x))));\n  BOOST_CHECK_EQUAL(m, m_check);\n}\n", "meta": {"hexsha": "b0e05c32573ed95d2528c47d1abc214c99cc0ccd", "size": 1230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_derivative.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_derivative.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_derivative.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": 32.3684210526, "max_line_length": 71, "alphanum_fraction": 0.6471544715, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.53850345560584}}
{"text": "\n\n#pragma once\n\n\n#include <vector>\n#include <Eigen/Eigen>\n#include \"types/SensorValues.hpp\"\n\n\n/* Complementary Kalman Filter (CKF), estimates robot torso pitch and roll \n   (forward lean and right side lean) using gyro and accelerometer */\n\nclass CKF {\n   public:\n\n      CKF();\n\n      void update(const SensorValues &sensorValues);\n\n      void resetFilter();\n\n      float getSideLean();\n\n      float getForwardLean();\n      \n   private:\n\n      Eigen::Vector4f state; // roll, pitch, roll_velocity, pitch_velocity\n      Eigen::Matrix<float, 4, 4> var;\n      Eigen::Matrix<float, 4, 4> Q; // Process noise\n      Eigen::Matrix<float, 4, 4> R; // Observation noise\n\n};\n", "meta": {"hexsha": "a62a150d56e8b0d9cb972f25f73822e85d0082d5", "size": 665, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/External/unsw/unsw/perception/kinematics/CKF.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/perception/kinematics/CKF.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/perception/kinematics/CKF.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": 19.0, "max_line_length": 75, "alphanum_fraction": 0.6496240602, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.53850345560584}}
{"text": "/**\n * Copyright (c) 2011, 2012\n * Claudio Kopper <claudio.kopper@icecube.wisc.edu>\n * and the IceCube Collaboration <http://www.icecube.wisc.edu>\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 ANY\n * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\n * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\n * $Id: I3CLSimVectorTransformMatrix.cxx 108199 2013-07-12 21:33:08Z nwhitehorn $\n *\n * @file I3CLSimVectorTransformMatrix.cxx\n * @version $Revision: 108199 $\n * @date $Date: 2013-07-12 15:33:08 -0600 (Fri, 12 Jul 2013) $\n * @author Claudio Kopper\n */\n\n#include <icetray/serialization.h>\n#include <clsim/function/I3CLSimVectorTransformMatrix.h>\n\n#include <typeinfo>\n#include <cmath>\n#include <math.h>\n#include <sstream>\n#include <stdexcept>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\n#include \"clsim/I3CLSimHelperToFloatString.h\"\nusing namespace I3CLSimHelper;\n\nI3CLSimVectorTransformMatrix::\nI3CLSimVectorTransformMatrix(\n    const I3Matrix &matrix,\n    bool renormalize)\n:\nmatrix_(matrix),\nrenormalize_(renormalize)\n{\n    if ((matrix_.size1() != 3) || (matrix_.size2() != 3))\n        throw std::range_error(\"matrix must be 3x3!\");\n}\n\nI3CLSimVectorTransformMatrix::I3CLSimVectorTransformMatrix() {;}\n\nI3CLSimVectorTransformMatrix::~I3CLSimVectorTransformMatrix() \n{;}\n\nbool I3CLSimVectorTransformMatrix::HasNativeImplementation() const \n{\n    return true;\n}\n\nstd::vector<double> I3CLSimVectorTransformMatrix::ApplyTransform(const std::vector<double> &vec) const\n{\n    if (vec.size() != 3)\n        throw std::range_error(\"vector must contain excatly 3 elements!\");\n\n    boost::numeric::ublas::vector<double> uvec_in(3);\n    std::copy(vec.begin(), vec.end(), uvec_in.begin());\n    boost::numeric::ublas::vector<double> uvec_out(3);\n\n    boost::numeric::ublas::noalias(uvec_out) = boost::numeric::ublas::prod(matrix_, uvec_in);\n\n    std::vector<double> out_vec(3, NAN);\n\n    double norm=1.;\n\n    if (renormalize_) {\n        norm=0.;\n        for (std::size_t i=0;i<3;++i)\n        {\n            norm += (uvec_out(i)*uvec_out(i));\n        }\n        norm = std::sqrt(norm);\n\n        for (std::size_t i=0;i<3;++i)\n        {\n            out_vec[i] = uvec_out(i)/norm;\n        }\n    } else {\n        for (std::size_t i=0;i<3;++i)\n        {\n            out_vec[i] = uvec_out(i);\n        }\n    }\n\n    return out_vec;\n}\n\nstd::string I3CLSimVectorTransformMatrix::GetOpenCLFunction(const std::string &functionName) const\n{\n    // the OpenCL interface takes a pointer to a float4, but ignores the fourth component\n\n    std::string funcDef = \n    std::string(\"inline void \") + functionName + std::string(\"(float4 *vec)\");\n    \n    std::string funcBody = std::string() + \n    \"{\\n\";\n\n    funcBody = funcBody +\n    \"    *vec = (float4)\\n\"\n    \"    (\\n\"\n    \"        (\" + ToFloatString(matrix_(0,0)) + \"*(*vec).x)+(\" + ToFloatString(matrix_(0,1)) + \"*(*vec).y)+(\" + ToFloatString(matrix_(0,2)) + \"*(*vec).z),\\n\"\n    \"        (\" + ToFloatString(matrix_(1,0)) + \"*(*vec).x)+(\" + ToFloatString(matrix_(1,1)) + \"*(*vec).y)+(\" + ToFloatString(matrix_(1,2)) + \"*(*vec).z),\\n\"\n    \"        (\" + ToFloatString(matrix_(2,0)) + \"*(*vec).x)+(\" + ToFloatString(matrix_(2,1)) + \"*(*vec).y)+(\" + ToFloatString(matrix_(2,2)) + \"*(*vec).z),\\n\"\n    \"        (*vec).w\\n\"\n    \"    );\\n\";\n\n    if (renormalize_) {\n        funcBody = funcBody +\n        \"#ifdef USE_NATIVE_MATH\\n\"\n        \"    (*vec).xyz = fast_normalize((*vec).xyz);\\n\"\n        \"#else\\n\"\n        \"    const float norm = rsqrt((*vec).x*(*vec).x + (*vec).y*(*vec).y + (*vec).z*(*vec).z);\\n\"\n        \"    (*vec).xyz = (*vec).xyz*norm;\\n\"\n        \"#endif\\n\";\n    }\n\n    funcBody = funcBody +\n    \"}\\n\";\n    \n    return funcDef + \";\\n\\n\" + funcDef + \"\\n\" + funcBody;\n}\n\nbool I3CLSimVectorTransformMatrix::CompareTo(const I3CLSimVectorTransform &other) const\n{\n    try\n    {\n        const I3CLSimVectorTransformMatrix &other_ = dynamic_cast<const I3CLSimVectorTransformMatrix &>(other);\n\n        if ((other_.matrix_.size1() != matrix_.size1()))\n            return false;\n        if ((other_.matrix_.size2() != matrix_.size2()))\n            return false;\n        for (std::size_t i=0;i<matrix_.size1();++i)\n            for (std::size_t j=0;j<matrix_.size2();++j)\n            {\n                if ((other_.matrix_(i,j) != matrix_(i,j)))\n                    return false;\n            }\n\n        if ((other_.renormalize_ != renormalize_))\n            return false;\n\n        return true;\n    }\n    catch (const std::bad_cast& e)\n    {\n        // not of the same type, treat it as non-equal\n        return false;\n    }\n    \n}\n\n\n\ntemplate <class Archive>\nvoid I3CLSimVectorTransformMatrix::serialize(Archive &ar, unsigned version)\n{\n    if (version>i3clsimvectortransformmatrix_version_)\n        log_fatal(\"Attempting to read version %u from file but running version %u of I3CLSimVectorTransformMatrix class.\",version,i3clsimvectortransformmatrix_version_);\n\n    ar & make_nvp(\"I3CLSimVectorTransform\", base_object<I3CLSimVectorTransform>(*this));\n    ar & make_nvp(\"matrix\", matrix_);\n    ar & make_nvp(\"renormalize\", renormalize_);\n}     \n\n\nI3_SERIALIZABLE(I3CLSimVectorTransformMatrix);\n", "meta": {"hexsha": "db6995cd57b1d1418d12f6fc4c42d0b284b2cd4c", "size": 5733, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "clsim/private/clsim/function/I3CLSimVectorTransformMatrix.cxx", "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_issues_repo_path": "clsim/private/clsim/function/I3CLSimVectorTransformMatrix.cxx", "max_issues_repo_name": "hschwane/offline_production", "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "clsim/private/clsim/function/I3CLSimVectorTransformMatrix.cxx", "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "avg_line_length": 31.6740331492, "max_line_length": 169, "alphanum_fraction": 0.6343973487, "num_tokens": 1636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.6113819591324418, "lm_q1q2_score": 0.5385034469583404}}
{"text": "#pragma once\n#include <Eigen/Eigen>\n\nclass XXZ\n{\nprivate:\n\tint n_;\n\tdouble J_;\n\tdouble Delta_;\n\npublic:\n\tXXZ(int n, double J, double Delta)\n\t\t: n_(n), J_(J), Delta_(Delta)\n\t{\n\t}\n\t\n\ttemplate<class State>\n\ttypename State::T operator()(const State& smp) const\n\t{\n\t\ttypename State::T s = 0.0;\n\t\t//Nearest-neighbor\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tint zz = smp.sigmaAt(i)*smp.sigmaAt((i+1)%n_);\n\t\t\ts += J_*Delta_*zz; //zz\n\t\t\ts += J_*(1-zz)*smp.ratio(i, (i+1)%n_); //xx+yy\n\t\t}\n\t\treturn s;\n\t}\n\n\tstd::vector<std::array<int,2> > offDiagonals(const Eigen::VectorXi& s) const\n\t{\n\t\tstd::vector< std::array<int, 2> > res;\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tif( s(i) != s((i+1)%n_) )\n\t\t\t\tres.push_back(std::array<int,2>{ i,(i+1)%n_ });\n\t\t}\n\t\treturn res;\n\t}\n\n\tstd::map<uint32_t, double> operator()(uint32_t col) const\n\t{\n\t\tstd::map<uint32_t, double> m;\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tint b1 = (col >> i) & 1;\n\t\t\tint b2 = (col >> ((i+1)%n_)) & 1;\n\t\t\tint zz = (1-2*b1)*(1-2*b2);\n\t\t\tlong long int x = (1 << i) | (1 << ((i+1)%(n_)));\n\t\t\tm[col] += J_*Delta_*zz;\n\t\t\tm[col ^ x] += J_*(1 - zz);\n\t\t}\n\t\treturn m;\n\t}\n};\n\n", "meta": {"hexsha": "553debc71198f989ed09c6af9ecd5fde6e240b79", "size": 1107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/XXZ.hpp", "max_stars_repo_name": "chaeyeunpark/ExactDiagonalization", "max_stars_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T08:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:47:05.000Z", "max_issues_repo_path": "tests/XXZ.hpp", "max_issues_repo_name": "chaeyeunpark/ExactDiagonalization", "max_issues_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T19:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T19:02:14.000Z", "max_forks_repo_path": "tests/XXZ.hpp", "max_forks_repo_name": "chaeyeunpark/ExactDiagonalization", "max_forks_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-22T18:59:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T18:59:11.000Z", "avg_line_length": 19.0862068966, "max_line_length": 77, "alphanum_fraction": 0.5356820235, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.538482759901675}}
{"text": "/***************************************************************************\n   Copyright 2015 Ufora Inc.\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#pragma once\n\n#include <boost/random.hpp>\n#include \"../lassert.hpp\"\n\nnamespace Ufora {\nnamespace math {\nnamespace Random {\n\ntemplate<class scalar_type>\nclass Normal {\npublic:\n\t\tNormal(uint32_t inSeed = 1u) :\n\t\t\t\tmSampler(mGen, mNormal)\n\t\t\t{\n\t\t\tmGen.seed(boost::uint32_t(inSeed));\n\t\t\t}\n\n\t\tscalar_type\toperator()(void)\n\t\t\t{\n\t\t\treturn mSampler();\n\t\t\t}\n\n\t\ttemplate<class T>\n\t\tT operator()(T value)\n\t\t\t{\n\t\t\treturn mSampler(value);\n\t\t\t}\n\n\t\ttypedef typename boost::variate_generator<boost::mt19937&, boost::normal_distribution<scalar_type> >::result_type result_type;\n\n\t\tresult_type min() const\n\t\t\t{\n\t\t\treturn mSampler.min();\n\t\t\t}\n\n\t\tresult_type max() const\n\t\t\t{\n\t\t\treturn mSampler.max();\n\t\t\t}\nprivate:\n\t\tboost::normal_distribution<scalar_type> mNormal;\n\n\t\tboost::mt19937 mGen;\n\n\t    boost::variate_generator<boost::mt19937&, boost::normal_distribution<scalar_type> > mSampler;\n};\n\ntemplate<class scalar_type,\n\tbool = std::is_integral<scalar_type>::value,\n\tbool = std::is_floating_point<scalar_type>::value>\nclass Uniform;\n\ntemplate<class scalar_type>\nclass Uniform<scalar_type, false, true> {\npublic:\n\t\tUniform(uint32_t inSeed = 1u) :\n\t\t\t\tmSampler(mGen, mUniform)\n\t\t\t{\n\t\t\tmGen.seed(boost::uint32_t(inSeed));\n\t\t\t}\n\n\t\tscalar_type\toperator()(void)\n\t\t\t{\n\t\t\treturn mSampler();\n\t\t\t}\n\n\t\ttemplate<class T>\n\t\tscalar_type operator()(T value)\n\t\t\t{\n\t\t\treturn mSampler(value);\n\t\t\t}\n\n\t\ttypedef typename boost::variate_generator<boost::mt19937&, boost::uniform_real<scalar_type> >::result_type result_type;\n\n\t\tresult_type min()\n\t\t\t{\n\t\t\treturn mSampler.min();\n\t\t\t}\n\n\t\tresult_type max()\n\t\t\t{\n\t\t\treturn mSampler.max();\n\t\t\t}\nprivate:\n\t\tboost::uniform_real<scalar_type> mUniform;\n\n\t\tboost::mt19937 mGen;\n\n\t\tboost::variate_generator<boost::mt19937&, boost::uniform_real<scalar_type> > mSampler;\n};\n\ntemplate<class scalar_type>\nclass Uniform<scalar_type, true, false> {\npublic:\n\t\tUniform(uint32_t inSeed = 1u) :\n\t\t\t\tmSampler(mGen, mUniform)\n\t\t\t{\n\t\t\tmGen.seed(boost::uint32_t(inSeed));\n\t\t\t}\n\n\t\tscalar_type\toperator()(void)\n\t\t\t{\n\t\t\treturn mSampler();\n\t\t\t}\n\n\t\ttemplate<class T>\n\t\tscalar_type operator()(T value)\n\t\t\t{\n\t\t\treturn mSampler(value);\n\t\t\t}\n\n\t\ttypedef typename boost::variate_generator<boost::mt19937&, boost::uniform_int<scalar_type> >::result_type result_type;\n\n\t\tresult_type min()\n\t\t\t{\n\t\t\treturn mSampler.min();\n\t\t\t}\n\n\t\tresult_type max()\n\t\t\t{\n\t\t\treturn mSampler.max();\n\t\t\t}\nprivate:\n\t\tboost::uniform_int<scalar_type> mUniform;\n\n\t\tboost::mt19937 mGen;\n\n\t    boost::variate_generator<boost::mt19937&, boost::uniform_int<scalar_type> > mSampler;\n};\n\ntemplate<class T, class scalar_type>\ndecltype(*T().begin()) pickRandomlyFromSet(\n\t\t\t\t\t\t\t\tconst T& values,\n\t\t\t\t\t\t\t\tUniform<scalar_type>& random\n\t\t\t\t\t\t\t\t)\n\t{\n\tint which = values.size();\n\n\twhile (which >= values.size())\n\t\twhich = random() * values.size();\n\n\tauto it = values.begin();\n\n\twhile (which)\n\t\t{\n\t\tit++;\n\t\twhich--;\n\t\t}\n\n\treturn *it;\n\t}\n\ntemplate<class T, class scalar_type, class weight_function_type>\ndecltype(*T().begin()) pickRandomlyFromSetWithWeight(\n\t\t\t\t\t\t\t\tconst T& values,\n\t\t\t\t\t\t\t\tUniform<scalar_type>& random,\n\t\t\t\t\t\t\t\tweight_function_type weightFunction\n\t\t\t\t\t\t\t\t)\n\t{\n\tdouble totalWeight = 0;\n\n\tfor (auto val: values)\n\t\ttotalWeight += weightFunction(val);\n\n\tlassert(totalWeight > 0.0);\n\n\tdouble w = totalWeight * random();\n\n\tfor (auto val: values)\n\t\tif (weightFunction(val) >= w)\n\t\t\treturn val;\n\t\telse\n\t\t\tw -= weightFunction(val);\n\n\tlassert(false);\n\t}\n\n\n}; //namespace Random\n}; //namespace math\n}; //namespace Ufora\n\n", "meta": {"hexsha": "c5d5e34fa40c47a0ea95f2197b7de725f2edc37e", "size": 4194, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ufora/core/math/Random.hpp", "max_stars_repo_name": "ufora/ufora", "max_stars_repo_head_hexsha": "04db96ab049b8499d6d6526445f4f9857f1b6c7e", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_stars_count": 571.0, "max_stars_repo_stars_event_min_datetime": "2015-11-05T20:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T22:31:09.000Z", "max_issues_repo_path": "ufora/core/math/Random.hpp", "max_issues_repo_name": "timgates42/ufora", "max_issues_repo_head_hexsha": "04db96ab049b8499d6d6526445f4f9857f1b6c7e", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_issues_count": 218.0, "max_issues_repo_issues_event_min_datetime": "2015-11-05T20:37:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-30T03:53:50.000Z", "max_forks_repo_path": "ufora/core/math/Random.hpp", "max_forks_repo_name": "timgates42/ufora", "max_forks_repo_head_hexsha": "04db96ab049b8499d6d6526445f4f9857f1b6c7e", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-11-07T21:42:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T03:48:19.000Z", "avg_line_length": 21.0753768844, "max_line_length": 128, "alphanum_fraction": 0.6621363853, "num_tokens": 1068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5384827264308526}}
{"text": "/**********************************************************************************************************************\nThis file is part of the Control Toolbox (https://github.com/ethz-adrl/control-toolbox), copyright by ETH Zurich\nLicensed under the BSD-2 license (see LICENSE file in main directory)\n**********************************************************************************************************************/\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <ct/core/core.h>\n#include \"Quadrotor.hpp\"\n\nnamespace ct {\nnamespace models {\n\nclass QuadrotorLinear final : public ct::core::LinearSystem<quadrotor::nStates, quadrotor::nControls>\n{\npublic:\n    typedef ct::core::StateVector<quadrotor::nStates> state_vector_t;\n    typedef ct::core::ControlVector<quadrotor::nControls> control_vector_t;\n\n    typedef Eigen::Matrix<double, quadrotor::nStates, quadrotor::nStates> state_matrix_t;\n    typedef Eigen::Matrix<double, quadrotor::nStates, quadrotor::nControls> state_control_matrix_t;\n\n\n    QuadrotorLinear* clone() const override { return new QuadrotorLinear(*this); }\n    const state_matrix_t& getDerivativeState(const state_vector_t& x,\n        const control_vector_t& u,\n        const ct::core::Time t = 0.0) override\n    {\n        A_ = A_quadrotor(x, u);\n        return A_;\n    }\n\n    const state_control_matrix_t& getDerivativeControl(const state_vector_t& x,\n        const control_vector_t& u,\n        const ct::core::Time t = 0.0) override\n    {\n        B_ = B_quadrotor(x, u);\n        return B_;\n    }\n\nprivate:\n    state_matrix_t A_;\n    state_control_matrix_t B_;\n};\n}\n}\n", "meta": {"hexsha": "32c2283b3ce3d55d071de81b313ad6e04e8451eb", "size": 1594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ct_models/include/ct/models/Quadrotor/QuadrotorLinear.hpp", "max_stars_repo_name": "romainreignier/control-toolbox", "max_stars_repo_head_hexsha": "6ee83d401b1a8d2fbfda2646a0ec1ec0e67b7c96", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 864.0, "max_stars_repo_stars_event_min_datetime": "2019-04-26T18:18:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T17:38:48.000Z", "max_issues_repo_path": "ct_models/include/ct/models/Quadrotor/QuadrotorLinear.hpp", "max_issues_repo_name": "romainreignier/control-toolbox", "max_issues_repo_head_hexsha": "6ee83d401b1a8d2fbfda2646a0ec1ec0e67b7c96", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 154.0, "max_issues_repo_issues_event_min_datetime": "2019-04-27T05:32:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:17:00.000Z", "max_forks_repo_path": "ct_models/include/ct/models/Quadrotor/QuadrotorLinear.hpp", "max_forks_repo_name": "romainreignier/control-toolbox", "max_forks_repo_head_hexsha": "6ee83d401b1a8d2fbfda2646a0ec1ec0e67b7c96", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 249.0, "max_forks_repo_forks_event_min_datetime": "2019-05-03T11:34:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T19:17:05.000Z", "avg_line_length": 33.2083333333, "max_line_length": 119, "alphanum_fraction": 0.6035131744, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.5384473448057631}}
{"text": "// g++ -O3 -DNDEBUG -DMATSIZE=<x> benchmark.cpp -o benchmark && time ./benchmark\n#include <Eigen/Array>\n\n#ifndef MATSIZE\n#define MATSIZE 3\n#endif\n\nusing namespace std;\nUSING_PART_OF_NAMESPACE_EIGEN\n\n#ifndef REPEAT\n#define REPEAT 40000000\n#endif\n\n#ifndef SCALAR\n#define SCALAR double\n#endif\n\nint main(int argc, char *argv[])\n{\n    Matrix<SCALAR,MATSIZE,MATSIZE> I = Matrix<SCALAR,MATSIZE,MATSIZE>::Ones();\n    Matrix<SCALAR,MATSIZE,MATSIZE> m;\n    for(int i = 0; i < MATSIZE; i++)\n        for(int j = 0; j < MATSIZE; j++)\n        {\n            m(i,j) = (i+MATSIZE*j);\n        }\n    asm(\"#begin\");\n    for(int a = 0; a < REPEAT; a++)\n    {\n        m = Matrix<SCALAR,MATSIZE,MATSIZE>::Ones() + 0.00005 * (m + (m*m));\n    }\n    asm(\"#end\");\n    cout << m << endl;\n    return 0;\n}\n", "meta": {"hexsha": "90e04dd3b847a58aeb6621a59d18d244d932ce89", "size": 776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "volna_init/external/eigen2/bench/benchmark.cpp", "max_stars_repo_name": "Devaraj-G/volna", "max_stars_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-07-08T23:53:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T11:55:28.000Z", "max_issues_repo_path": "volna_init/external/eigen2/bench/benchmark.cpp", "max_issues_repo_name": "Devaraj-G/volna", "max_issues_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-02T17:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-02T17:31:28.000Z", "max_forks_repo_path": "volna_init/external/eigen2/bench/benchmark.cpp", "max_forks_repo_name": "Devaraj-G/volna", "max_forks_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-02-05T19:34:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T08:46:34.000Z", "avg_line_length": 20.972972973, "max_line_length": 80, "alphanum_fraction": 0.5914948454, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.5384473333924529}}
{"text": "# include <cstdlib>\n# include <cmath>\n# include <sys/time.h>\n#include <boost/multi_array.hpp>\n\n# include \"matrix.hpp\"\n# include \"brain.hpp\"\n\n# define CONV_UP  1.0e-6  /* parametro de convergencia Jacobi */\n# define CONV_DO  1.0e2   /* parametro para chequear si Jacobi explota */\n# define ITER_MAX 100\n\n# define BTAG 0 \n# define ATAG 1\n\n# if not defined SOLVER_H\n# define SOLVER_H\n\n/* hold grid dimensions and indexes for both serial and\n * parallel cases */\nstruct dimensions_t {\n    int total;\n    int local;\n    int rest;\n    int nx_rest;\n    int nx_local;\n    std::pair<int, int> local_i;\n    int start_i;\n    int end_i;\n};\n\n\nclass Solver {\n  \nprivate:\n\n    /* number of parallel processes */\n    int num_tasks;\n\n    /* discrete grid dimensions */\n    int nx,ny,nz;\n    dimensions_t dims;\n\n    /* Jacobi matrix coefficients */\n    boost_array2d_t *coeffs;\n    int dim_coeffs;\n    int s_order;\n\n    /* space and time step values */\n    double dX;\n    double dT;\n\n    /* timing */\n    struct timeval tp;\n    int t_elap;\n    double t1, t2;\n\n    /* preparar vectores *after y *before */\n    void prepare_solution(const int, const int,\n            boost_array3d_t& solution, boost_array2d_t& before, boost_array2d_t& after);\n  \npublic:\n  \n  /* variables to keep track of timing */\n  double init_time;\n  double linear_time; \n  double nonlinear_time;\n  \n  Solver(const int nx, const int ny, const int nz, \n    const double dX, const double dT);\n  \n  ~Solver();\n\n  static dimensions_t get_local_dimensions(const int nx, const int ny, const int nz);\n  \n  /* solver initialization */\n  void start(const int task_id, BrainModel& brain, const int method);\n  \n  \n  /* solution methods */\n  void lie_trotter(const double current_time, \n                const int task_id, \n                boost_array3d_t& solution,\n                BrainModel& brain_model);\n\n  void expl(const int task_id, const int num_tasks,\n            boost_array3d_t& solution, BrainModel& brain);\n\n};\n\n# endif", "meta": {"hexsha": "a266372101d450fc988253c2450a33c033513166", "size": 1971, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/solver.hpp", "max_stars_repo_name": "madagra/brain-tumor-simulation", "max_stars_repo_head_hexsha": "134eacd34034a65a48e8aad1b42dc2fb701892a7", "max_stars_repo_licenses": ["MIT"], "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/solver.hpp", "max_issues_repo_name": "madagra/brain-tumor-simulation", "max_issues_repo_head_hexsha": "134eacd34034a65a48e8aad1b42dc2fb701892a7", "max_issues_repo_licenses": ["MIT"], "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/solver.hpp", "max_forks_repo_name": "madagra/brain-tumor-simulation", "max_forks_repo_head_hexsha": "134eacd34034a65a48e8aad1b42dc2fb701892a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-11T14:24:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-11T14:24:26.000Z", "avg_line_length": 21.6593406593, "max_line_length": 88, "alphanum_fraction": 0.6560121766, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5384473223166574}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2013 Alec Jacobson <alecjacobson@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 \"per_face_normals.h\"\n#include <Eigen/Geometry>\n\n#define SQRT_ONE_OVER_THREE 0.57735026918962573\ntemplate <typename DerivedV, typename DerivedF, typename DerivedZ, typename DerivedN>\nIGL_INLINE void igl::per_face_normals(\n  const Eigen::MatrixBase<DerivedV>& V,\n  const Eigen::MatrixBase<DerivedF>& F,\n  const Eigen::MatrixBase<DerivedZ> & Z,\n  Eigen::PlainObjectBase<DerivedN> & N)\n{\n  N.resize(F.rows(),3);\n  // loop over faces\n  int Frows = F.rows();\n#pragma omp parallel for if (Frows>10000)\n  for(int i = 0; i < Frows;i++)\n  {\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v1 = V.row(F(i,1)) - V.row(F(i,0));\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v2 = V.row(F(i,2)) - V.row(F(i,0));\n    N.row(i) = v1.cross(v2);//.normalized();\n    typename DerivedV::Scalar r = N.row(i).norm();\n    if(r == 0)\n    {\n      N.row(i) = Z;\n    }else\n    {\n      N.row(i) /= r;\n    }\n  }\n}\n\ntemplate <typename DerivedV, typename DerivedF, typename DerivedN>\nIGL_INLINE void igl::per_face_normals(\n  const Eigen::MatrixBase<DerivedV>& V,\n  const Eigen::MatrixBase<DerivedF>& F,\n  Eigen::PlainObjectBase<DerivedN> & N)\n{\n  using namespace Eigen;\n  Matrix<typename DerivedN::Scalar,3,1> Z(0,0,0);\n  return per_face_normals(V,F,Z,N);\n}\n\ntemplate <typename DerivedV, typename DerivedF, typename DerivedN>\nIGL_INLINE void igl::per_face_normals_stable(\n  const Eigen::MatrixBase<DerivedV>& V,\n  const Eigen::MatrixBase<DerivedF>& F,\n  Eigen::PlainObjectBase<DerivedN> & N)\n{\n  using namespace Eigen;\n  typedef Matrix<typename DerivedV::Scalar,1,3> RowVectorV3;\n  typedef typename DerivedV::Scalar Scalar;\n\n  const size_t m = F.rows();\n\n  N.resize(F.rows(),3);\n  // Grad all points\n  for(size_t f = 0;f<m;f++)\n  {\n    const RowVectorV3 p0 = V.row(F(f,0));\n    const RowVectorV3 p1 = V.row(F(f,1));\n    const RowVectorV3 p2 = V.row(F(f,2));\n    const RowVectorV3 n0 = (p1 - p0).cross(p2 - p0);\n    const RowVectorV3 n1 = (p2 - p1).cross(p0 - p1);\n    const RowVectorV3 n2 = (p0 - p2).cross(p1 - p2);\n\n    // careful sum\n    for(int d = 0;d<3;d++)\n    {\n      // This is a little _silly_ in terms of complexity, but its recursive\n      // implementation is clean looking...\n      const std::function<Scalar(Scalar,Scalar,Scalar)> sum3 =\n        [&sum3](Scalar a, Scalar b, Scalar c)->Scalar\n      {\n        if(fabs(c)>fabs(a))\n        {\n          return sum3(c,b,a);\n        }\n        // c < a\n        if(fabs(c)>fabs(b))\n        {\n          return sum3(a,c,b);\n        }\n        // c < a, c < b\n        if(fabs(b)>fabs(a))\n        {\n          return sum3(b,a,c);\n        }\n        return (a+b)+c;\n      };\n\n      N(f,d) = sum3(n0(d),n1(d),n2(d));\n    }\n    // sum better not be sure, or else NaN\n    N.row(f) /= N.row(f).norm();\n  }\n\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\n// Nonsense template\nnamespace igl{template<> void per_face_normals<Eigen::Matrix<double, -1, 2, 0, -1, 2>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 2, 0, -1, 2> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&){} }\n// generated by autoexplicit.sh\ntemplate void igl::per_face_normals<Eigen::Matrix<float, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<float, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 3, 0, -1, 3> >&);\n// generated by autoexplicit.sh\ntemplate void igl::per_face_normals<Eigen::Matrix<float, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<float, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, -1, 0, -1, -1> >&);\n// generated by autoexplicit.sh\ntemplate void igl::per_face_normals<Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, Eigen::Matrix<float, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, 3, 1, 0, 3, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, 3, 1, 0, 3, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, 1, 3, 1, 1, 3>, Eigen::Matrix<double, 1, -1, 1, 1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, 1, 3, 1, 1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 1, -1, 1, 1, -1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, Eigen::Matrix<double, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, Eigen::Matrix<double, -1, 3, 1, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<float, -1, -1, 1, -1, -1>, Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1>, Eigen::Matrix<float, -1, -1, 1, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, -1, 1, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, -1, 1, -1, -1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, 3, 1, -1, 3>, Eigen::Matrix<float, -1, 3, 1, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<unsigned int, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 3, 1, -1, 3> >&);\ntemplate void igl::per_face_normals<class Eigen::Matrix<double,-1,3,0,-1,3>,class Eigen::Matrix<int,-1,-1,0,-1,-1>,class Eigen::Matrix<double,-1,-1,0,-1,-1> >(class Eigen::MatrixBase<class Eigen::Matrix<double,-1,3,0,-1,3> > const &,class Eigen::MatrixBase<class Eigen::Matrix<int,-1,-1,0,-1,-1> > const &,class Eigen::PlainObjectBase<class Eigen::Matrix<double,-1,-1,0,-1,-1> > &);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, 2, 3, 0, 2, 3>, Eigen::Matrix<double, 2, 3, 0, 2, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, 2, 3, 0, 2, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 2, 3, 0, 2, 3> >&);\ntemplate void igl::per_face_normals_stable<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate void igl::per_face_normals_stable<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_face_normals_stable<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\n#endif\n", "meta": {"hexsha": "e909a487c85964df4f210313ada4428b32cbcdec", "size": 10311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/simpleuv/thirdparty/libigl/include/igl/per_face_normals.cpp", "max_stars_repo_name": "MelvinG24/dust3d", "max_stars_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "thirdparty/simpleuv/thirdparty/libigl/include/igl/per_face_normals.cpp", "max_issues_repo_name": "MelvinG24/dust3d", "max_issues_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "thirdparty/simpleuv/thirdparty/libigl/include/igl/per_face_normals.cpp", "max_forks_repo_name": "MelvinG24/dust3d", "max_forks_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 78.1136363636, "max_line_length": 474, "alphanum_fraction": 0.6189506352, "num_tokens": 3984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5384473221478998}}
{"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_DIVCEIL_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DIVCEIL_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing divceil capabilities\n\n    Computes the ceil of the division 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 = divceil(x, y);\n    @endcode\n\n    For floating point values the code is equivalent to:\n\n    @code\n    T r = ceil(x/y);\n    @endcode\n\n    for integral types, if y is null, it returns @ref Valmax (resp. @ref Valmin)\n    if x is positive (resp. negative), and 0 if x is null.\n    Take care also that dividing @ref Valmin by -1 for signed integral types has\n    undefined behaviour.\n\n    @see  divides, rec, divs, divfloor, divround, divround2even, divfix\n\n  **/\n  const boost::dispatch::functor<tag::divceil_> divceil = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/divceil.hpp>\n#include <boost/simd/function/simd/divceil.hpp>\n\n#endif\n", "meta": {"hexsha": "665a37610cf5ccf035a805e3e10764f733442176", "size": 1462, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/divceil.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/divceil.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/divceil.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": 26.5818181818, "max_line_length": 100, "alphanum_fraction": 0.60875513, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891174511733, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5384473192945721}}
{"text": "#include <memory>\n#include <vector>\n\n#include <Eigen/Core>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n\n#include <aslam/cameras/camera-pinhole.h>\n#include <aslam/cameras/camera.h>\n#include <aslam/cameras/distortion-fisheye.h>\n\n#include <geometric-vision/five-point-pose-estimator.h>\n#include <maplab-common/pose_types.h>\n#include <maplab-common/quaternion-math.h>\n#include <maplab-common/test/testing-entrypoint.h>\n#include <maplab-common/test/testing-predicates.h>\n\nclass VariableCameraAngle : public ::testing::TestWithParam<double> {};\n\nINSTANTIATE_TEST_CASE_P(\n    OpengvPoseEstimationFivePoint, VariableCameraAngle,\n    ::testing::Values(0, M_PI / 24.0, M_PI / 8.0, -M_PI / 8.0, -M_PI / 24.0));\n\nTEST_P(VariableCameraAngle, PinholeCameraFivePointPoseInterface) {\n  opengv_pose_estimation::FivePointPoseEstimator pose_estimator;\n\n  typedef aslam::FisheyeDistortion DistortionType;\n  typedef aslam::PinholeCamera CameraType;\n  const double distortion_param = 0.90;\n  const double fu = 200;\n  const double fv = 200;\n  const unsigned int ru = 640;\n  const unsigned int rv = 480;\n  const double cu = ru / 2;\n  const double cv = rv / 2;\n  Eigen::VectorXd distortion_params(1);\n  distortion_params << distortion_param;\n  std::shared_ptr<CameraType> camera;\n  aslam::Distortion::UniquePtr distortion(\n      new DistortionType(distortion_params));\n\n  Eigen::VectorXd intrinsics(4);\n  intrinsics << fu, fv, cu, cv;\n\n  camera = std::shared_ptr<CameraType>(\n      new CameraType(intrinsics, ru, rv, distortion));\n\n  constexpr double kVariationAngle = M_PI / 36;  // 5 deg.\n  Eigen::Quaterniond G_q_C_a(\n      Eigen::AngleAxisd(\n          GetParam() - kVariationAngle, Eigen::Vector3d::UnitY()));\n  Eigen::Quaterniond G_q_C_b(\n      Eigen::AngleAxisd(\n          GetParam() + kVariationAngle, Eigen::Vector3d::UnitY()));\n  Eigen::Matrix3d G_R_C_a = G_q_C_a.toRotationMatrix();\n  Eigen::Matrix3d G_R_C_b = G_q_C_b.toRotationMatrix();\n  Eigen::Vector3d G_p_C_a(1, 2.5, 3);\n  Eigen::Vector3d G_p_C_b(1, 2, 3);\n\n  const int num_of_points = 100;\n  const int num_of_outliers = 10;\n  Eigen::Matrix2Xd measurements_a;\n  Eigen::Matrix2Xd measurements_b;\n  Eigen::Matrix3Xd landmark_positions;\n  measurements_a.resize(Eigen::NoChange, num_of_points + num_of_outliers);\n  measurements_b.resize(Eigen::NoChange, num_of_points + num_of_outliers);\n  landmark_positions.resize(Eigen::NoChange, num_of_points + num_of_outliers);\n  for (int i = 0; i < num_of_points + num_of_outliers; ++i) {\n    // We need to vary the depth -- plane may not be enough to recover\n    // the camera pose.\n    Eigen::Vector3d C_p_fa = camera->createRandomVisiblePoint(i % 5 + 1);\n    Eigen::Vector2d keypoint_measurement_a;\n    camera->project3(C_p_fa, &keypoint_measurement_a);\n    measurements_a.col(i) = keypoint_measurement_a;\n\n    // Add outliers.\n    if (i >= num_of_points) {\n      measurements_a.col(i) =\n          keypoint_measurement_a +\n          (Eigen::Vector2d() << (i + 10) % 8, -10).finished();\n    }\n\n    Eigen::Matrix<double, 3, 1> G_landmark_position =\n        G_R_C_a * C_p_fa + G_p_C_a;\n\n    Eigen::Vector3d C_p_fb =\n        G_R_C_b.transpose() * (G_landmark_position - G_p_C_b);\n    Eigen::Vector2d keypoint_measurement_b;\n    camera->project3(C_p_fb, &keypoint_measurement_b);\n    measurements_b.col(i) = keypoint_measurement_b;\n\n    // Add outliers.\n    if (i >= num_of_points) {\n      measurements_b.col(i) = keypoint_measurement_b +\n                              (Eigen::Vector2d() << (i + 5) % 7, 10).finished();\n    }\n  }\n\n  Eigen::Quaterniond expected_rotation = G_q_C_a.inverse() * G_q_C_b;\n\n  pose::Transformation estimated_transform;\n  std::vector<int> inlier_matches;\n  constexpr double kPixelSigma = 0.8;\n  constexpr double kFocalLength = 100;\n  const double kRansacThreshold = 1.0 - cos(atan(kPixelSigma / kFocalLength));\n  pose_estimator.Compute(\n      measurements_a, measurements_b, kRansacThreshold, 500, camera,\n      &estimated_transform, &inlier_matches);\n\n  EXPECT_GT(inlier_matches.size(), num_of_points * 0.90);\n\n  EXPECT_NEAR_EIGEN(\n      estimated_transform.getRotation().toImplementation().coeffs(),\n      expected_rotation.coeffs(), 1e-2);\n}\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "ab31fcb7840532827c3ba6d65986acfbd29626c9", "size": 4181, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/geometric-vision-algorithms/test/test_five_point_pose_estimator_test.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": "algorithms/geometric-vision-algorithms/test/test_five_point_pose_estimator_test.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": "algorithms/geometric-vision-algorithms/test/test_five_point_pose_estimator_test.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": 35.4322033898, "max_line_length": 80, "alphanum_fraction": 0.7139440325, "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5384473167787598}}
{"text": "#include <algorithm>\n#include <boost/optional.hpp>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <numeric>\n#include <queue>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\n#define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++)\n#define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++)\n#define EACH(e, a) for(auto&& e : a)\n#define ALL(a) (a).begin(), (a).end()\n#define AALL(a, n) (a), ((a) + (n))\n#define FILL(a, n) memset((a), n, sizeof(a))\n#define FILLZ(a) FILL(a, 0)\n#define INT(x) (static_cast<int>(x))\n#define MODNUM (INT(1e9 + 7))\n#define MOD(x) ((x) % MODNUM)\n\nusing namespace std;\n\nusing ll = long long;\nusing VI = vector<int>;\nusing VI2D = vector<vector<int>>;\n\nconst int INF = 2e9;\nconst double EPS = 1e-10;\nconst double PI = acos(-1.0);\n\nconst int dx[] = {-1, 0, 1, 0};\nconst int dy[] = {0, -1, 0, 1};\n\ntemplate <typename T>\nint sign(T x) {\n\treturn x < 0 ? -1 : x > 0 ? 1 : 0;\n}\n\ntemplate <>\nint sign(double x) {\n\treturn x < -EPS ? -1 : x > EPS ? 1 : 0;\n}\n\ntemplate <typename T>\nvoid chmax(T& m, T x) {\n\tm = max(m, x);\n}\n\ntemplate <typename T>\nvoid chmin(T& m, T x) {\n\tm = min(m, x);\n}\n\ntemplate <typename T>\nT square(T x) {\n\treturn x * x;\n}\n\ninline int toInt(string s) {\n\tint v;\n\tistringstream sin(s);\n\tsin >> v;\n\treturn v;\n}\n\nint top_digit(int n) {\n\twhile(n / 10 > 0) {\n\t\tn /= 10;\n\t}\n\treturn n;\n}\n\nint bottom_digit(int n) {\n\treturn n % 10;\n}\n\nint kirisage(int n) {\n\tint ret = 1;\n\twhile(ret * 10 < n) {\n\t\tret *= 10;\n\t}\n\treturn ret;\n}\n\nint count(int n, int y, int x) {\n\tint ret = 0;\n\n\tRANGE(i, 1, n + 1) {\n\t\tint top = top_digit(i);\n\t\tint bottom = bottom_digit(i);\n\t\tif(top == y && bottom == x) {\n\t\t\tret++;\n\t\t}\n\t}\n\treturn ret;\n}\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tVI2D num(10, VI(10, 0));\n\tRANGE(i, 1, 10) {\n\t\tRANGE(j, 1, 10) { num[i][j] = count(n, i, j); }\n\t}\n\tll result = 0;\n\tRANGE(i, 1, 10) {\n\t\tRANGE(j, 1, 10) { result += (num[i][j] * num[j][i]); }\n\t}\n\n\tprintf(\"%lld\\n\", result);\n\treturn 0;\n}", "meta": {"hexsha": "a138f03603527253f1fb09d319ebcbdfcbcdc89e", "size": 2123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABC152/D.cpp", "max_stars_repo_name": "arlechann/atcoder", "max_stars_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "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": "AtCoder/ABC152/D.cpp", "max_issues_repo_name": "arlechann/atcoder", "max_issues_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "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": "AtCoder/ABC152/D.cpp", "max_forks_repo_name": "arlechann/atcoder", "max_forks_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "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": 17.5454545455, "max_line_length": 76, "alphanum_fraction": 0.5751295337, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5384130019876755}}
{"text": "/* plantcalc -- Power plant modelling\n * (c) 2012 Micha\u0142 G\u00f3rny\n * Released under the terms of the 2-clause BSD license\n */\n\n#ifdef HAVE_CONFIG_H\n#\tinclude \"config.h\"\n#endif\n\n#include \"linearequationsolver.hxx\"\n#include \"../equations/linearequation.hxx\"\n#include \"../exceptions/contradictionerror.hxx\"\n#include \"../variable.hxx\"\n\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <map>\n#include <stdexcept>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\nnamespace\n{\n\tclass col_index\n\t{\n\t\tint _i;\n\n\tpublic:\n\t\tcol_index()\n\t\t\t: _i(-1)\n\t\t{\n\t\t}\n\n\t\tvoid operator=(int x)\n\t\t{\n\t\t\t_i = x;\n\t\t}\n\n\t\toperator int() const\n\t\t{\n\t\t\treturn _i;\n\t\t}\n\t};\n}\n\nLinearEquationSolver::LinearEquationSolver(EquationSystem& eqs, double epsilon)\n\t: _eqs(eqs), _epsilon(epsilon)\n{\n}\n\nbool LinearEquationSolver::iterate()\n{\n\tEquationSystem& eqs = _eqs;\n\ttypedef std::vector<LinearEquation*> linear_eq_list;\n\tlinear_eq_list lineqs;\n\n\t// collect linear equations\n\tfor (EquationSystem::iterator it = eqs.begin(); it != eqs.end(); ++it)\n\t{\n\t\tLinearEquation* e = dynamic_cast<LinearEquation*>(*it);\n\n\t\tif (e)\n\t\t\tlineqs.push_back(e);\n\t}\n\n\tconst int num_eqs = lineqs.size();\n\tif (num_eqs == 0)\n\t\treturn false;\n\n\tint curr_var_index = 0;\n\n\ttypedef std::map<Variable*, col_index> variable_map;\n\tvariable_map varmap;\n\n\t// gather variable counts\n\tlinear_eq_list::iterator it;\n\tfor (it = lineqs.begin(); it != lineqs.end();)\n\t{\n\t\tLinearEquation& e = **it;\n\t\tLinearEquation::list_type::iterator jt;\n\n\t\tbool accepted = true;\n\n\t\tfor (jt = e._vars.begin(); jt != e._vars.end(); ++jt)\n\t\t{\n\t\t\tLinearEquation::list_elem_type& cv = *jt;\n\n\t\t\tVariable* unk_var = 0;\n\n\t\t\tif (!cv.variable1->is_set())\n\t\t\t\tunk_var = cv.variable1;\n\n\t\t\tif (cv.variable2 && !cv.variable2->is_set())\n\t\t\t{\n\t\t\t\t// if there's no usable coefficient, drop that eq\n\t\t\t\tif (unk_var)\n\t\t\t\t{\n\t\t\t\t\tit = lineqs.erase(it);\n\t\t\t\t\taccepted = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tunk_var = cv.variable2;\n\t\t\t}\n\n\t\t\tif (unk_var)\n\t\t\t{\n\t\t\t\tcol_index& col = varmap[unk_var];\n\n\t\t\t\tif (col == -1)\n\t\t\t\t\tcol = curr_var_index++;\n\t\t\t}\n\t\t}\n\n\t\tif (accepted)\n\t\t\t++it;\n\t}\n\n\tconst int num_vars = varmap.size();\n\tEigen::MatrixXd coeff_matrix\n\t\t= Eigen::MatrixXd::Zero(num_eqs + 1, num_vars);\n\tEigen::VectorXd value_vector(num_eqs + 1);\n\n\tint row;\n\tfor (it = lineqs.begin(), row = 0; it != lineqs.end(); ++it)\n\t{\n\t\tLinearEquation& e = **it;\n\t\tLinearEquation::list_type::iterator jt;\n\n\t\tdouble val = 0;\n\n\t\tfor (jt = e._vars.begin(); jt != e._vars.end(); ++jt)\n\t\t{\n\t\t\tLinearEquation::list_elem_type& cv = *jt;\n\n\t\t\tVariable* unk_var = 0;\n\t\t\tdouble coeff = cv.coefficient;\n\n\t\t\tif (!cv.variable1->is_set())\n\t\t\t\tunk_var = cv.variable1;\n\t\t\telse\n\t\t\t\tcoeff *= *cv.variable1;\n\n\t\t\tif (cv.variable2)\n\t\t\t{\n\t\t\t\tif (!cv.variable2->is_set())\n\t\t\t\t{\n\t\t\t\t\tassert(!unk_var);\n\t\t\t\t\tunk_var = cv.variable2;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tcoeff *= *cv.variable2;\n\t\t\t}\n\n\t\t\tif (!unk_var)\n\t\t\t\tval -= coeff;\n\t\t\telse\n\t\t\t{\n\t\t\t\tcol_index& col = varmap[unk_var];\n\t\t\t\tassert(col < num_vars);\n\n\t\t\t\tcoeff_matrix(row, col) = coeff;\n\t\t\t}\n\t\t}\n\n\t\tvalue_vector(row) = val;\n\t\t++row;\n\t}\n\n\tEigen::FullPivLU<Eigen::MatrixXd> lu = coeff_matrix.fullPivLu();\n\n\tEigen::VectorXd sol_vector = lu.solve(value_vector);\n\tEigen::VectorXd null_vector = lu.kernel().rowwise().sum();\n\n\tdouble error = (coeff_matrix * sol_vector - value_vector).norm();\n\n\tif (std::abs(error) > _epsilon)\n\t\tthrow ContradictionError();\n\n\tstd::vector<bool> keep_equations(num_eqs, false);\n\n\tvariable_map::iterator vt;\n\tfor (vt = varmap.begin(); vt != varmap.end(); ++vt)\n\t{\n\t\tVariable& v = *(*vt).first;\n\t\tcol_index& col = (*vt).second;\n\n\t\tif (null_vector(col) > 0.5)\n\t\t{\n\t\t\t// find all equations with the variable and remove them\n\t\t\t// so they will remain in the original system of equations\n\n\t\t\tfor (int i = 0; i < num_eqs; ++i)\n\t\t\t{\n\t\t\t\tif (std::abs(coeff_matrix(i, col)) > _epsilon)\n\t\t\t\t\tkeep_equations[i] = true;\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tv.set_value(sol_vector(col));\n\t}\n\n\t// remove the solved equations\n\t// they should be in the same order in both vectors\n\tEquationSystem::iterator et = eqs.begin();\n\tfor (linear_eq_list::size_type i = 0; i < lineqs.size(); ++i)\n\t{\n\t\tif (keep_equations[i])\n\t\t\tcontinue;\n\n\t\tEquation* eq = lineqs[i];\n\n\t\tassert(et != eqs.end());\n\t\twhile (*et != eq)\n\t\t{\n\t\t\t++et;\n\t\t\tassert(et != eqs.end());\n\t\t}\n\t\tet = eqs.erase(et);\n\t}\n\n\treturn false;\n}\n", "meta": {"hexsha": "9b015bc41a8f4e78c8f37b403f0c971f54287f94", "size": 4295, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/equationsolvers/linearequationsolver.cxx", "max_stars_repo_name": "mgorny/plantcalc", "max_stars_repo_head_hexsha": "4339d97c6597ec2b672063b4aa592311fb0b078c", "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/equationsolvers/linearequationsolver.cxx", "max_issues_repo_name": "mgorny/plantcalc", "max_issues_repo_head_hexsha": "4339d97c6597ec2b672063b4aa592311fb0b078c", "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/equationsolvers/linearequationsolver.cxx", "max_forks_repo_name": "mgorny/plantcalc", "max_forks_repo_head_hexsha": "4339d97c6597ec2b672063b4aa592311fb0b078c", "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": 18.8377192982, "max_line_length": 79, "alphanum_fraction": 0.6318975553, "num_tokens": 1328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.538412990684846}}
{"text": "#ifndef DYN_GCA_INCLUDED\n#define DYN_GCA_INCLUDED\n\n#include <boost/multi_array.hpp>\n\nusing namespace std;\n\n/**\n * @file   dyn_gca.hpp\n * @brief  ODE system for group SIS with group selection mechanism for transmission rates\n *\n * @author  LHD\n * @since   2021-02-06\n */\n\nstruct Sparam {\n    const double beta;\n    const double gamma;\n    const double rho;\n    const double b;\n    const double c;\n    const double mu;\n    const int dim1;\n    const int dim2;\n}; // parameter structure\n\n//********** function dydt definition **************************************************************\nint dydt(double t, const double y[], double f[], void * param) {\n// ODE system for interacting contagions\n\n    // Cast parameters\n    Sparam& p = *static_cast<Sparam* >(param);\n\n    // Create multi_array reference to y and f\n    typedef boost::multi_array_ref<const double,2> CSTmatref_type;\n    typedef boost::multi_array_ref<double,2> matref_type;\n    typedef CSTmatref_type::index indexref;\n    CSTmatref_type yref(y,boost::extents[p.dim1][p.dim2]);\n    matref_type fref(f,boost::extents[p.dim1][p.dim2]);\n\n    // Calculate mean-field coupling and observed fitness landscape\n    vector<double> Zvec(p.dim1, 0.0); vector<double> popvec(p.dim1, 0.0); double R=0.0;\n    for(int l=0; l<p.dim1; ++l) {\n        for(int i=0; i<p.dim2; ++i) {\n            Zvec[l] += exp(p.b*i-p.c*l)*yref[l][i]; //should this really be proportional to C_i,l?\n            popvec[l] += yref[l][i];\n            R += p.rho*i*yref[l][i];\n        }\n        if(popvec[l]>0.0) Zvec[l] /= popvec[l];\n    }\n    double Z = accumulate(Zvec.begin(), Zvec.end(), 0.0);\n    int n=p.dim2-1;\n    int L=p.dim1-1;\n\n    // Compute derivatives\n    for(int l=0; l<p.dim1; ++l) {\n        for(int i=0; i<p.dim2; ++i) {\n            fref[l][i] = -1.0*p.gamma*i*yref[l][i] - p.beta*l*(i+R)*(n-i)*yref[l][i];\n            if(i>0) fref[l][i] += p.beta*l*((i-1)+R)*(n-i+1)*yref[l][i-1];\n            if(i<n) fref[l][i] += p.gamma*(i+1)*yref[l][i+1];\n            if(l>0) fref[l][i] += p.rho*yref[l-1][i]*(Zvec[l]/Zvec[l-1]+p.mu) - p.rho*yref[l][i]*(Zvec[l-1]/Zvec[l]+p.mu);\n            if(l<L) fref[l][i] += p.rho*yref[l+1][i]*(Zvec[l]/Zvec[l+1]+p.mu) - p.rho*yref[l][i]*(Zvec[l+1]/Zvec[l]+p.mu);\n        }\n    }\n\n    return GSL_SUCCESS;\n\n} //********** end function dydt definition ********************************************************\n\n#endif // DYN_GCA_HPP_INCLUDED\n", "meta": {"hexsha": "08acb14f7c4c49ea23ef45778616eb3ae92ad63c", "size": 2402, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dyn_gca.hpp", "max_stars_repo_name": "LaurentHebert/group-cultural-adaptation", "max_stars_repo_head_hexsha": "806a7e3aea4d544e2d840ea517b8cbd19cd9e8bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dyn_gca.hpp", "max_issues_repo_name": "LaurentHebert/group-cultural-adaptation", "max_issues_repo_head_hexsha": "806a7e3aea4d544e2d840ea517b8cbd19cd9e8bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dyn_gca.hpp", "max_forks_repo_name": "LaurentHebert/group-cultural-adaptation", "max_forks_repo_head_hexsha": "806a7e3aea4d544e2d840ea517b8cbd19cd9e8bf", "max_forks_repo_licenses": ["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.8309859155, "max_line_length": 122, "alphanum_fraction": 0.5570358035, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5384129852659033}}
{"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:  Use of the iterative solvers in ViennaCL with Boost.uBLAS\n*\n*/\n\n//\n// include necessary system headers\n//\n#include <iostream>\n\n//\n// Necessary to obtain a suitable performance in ublas\n#ifndef NDEBUG\n #define NDEBUG\n#endif\n\n\n//\n// ublas includes\n//\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n// Must be set if you want to use ViennaCL algorithms on ublas objects\n#define VIENNACL_WITH_UBLAS 1\n\n//\n// ViennaCL includes\n//\n#include \"viennacl/linalg/ilu.hpp\"\n#include \"viennacl/linalg/cg.hpp\"\n#include \"viennacl/linalg/bicgstab.hpp\"\n#include \"viennacl/linalg/gmres.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n\n// Some helper functions for this tutorial:\n#include \"Random.hpp\"\n#include \"vector-io.hpp\"\n\nusing namespace boost::numeric;\n\n\nint main()\n{\n  typedef float       ScalarType;\n\n  //\n  // Set up some ublas objects\n  //\n  ublas::vector<ScalarType> rhs;\n  ublas::vector<ScalarType> rhs2;\n  ublas::vector<ScalarType> ref_result;\n  ublas::vector<ScalarType> result;\n  ublas::compressed_matrix<ScalarType> ublas_matrix;\n\n  //\n  // Read system from file\n  //\n  if (!viennacl::io::read_matrix_market_file(ublas_matrix, \"../examples/testdata/mat65k.mtx\"))\n  {\n    std::cout << \"Error reading Matrix file\" << std::endl;\n    return 0;\n  }\n  //std::cout << \"done reading matrix\" << std::endl;\n\n  if (!readVectorFromFile(\"../examples/testdata/rhs65025.txt\", rhs))\n  {\n    std::cout << \"Error reading RHS file\" << std::endl;\n    return 0;\n  }\n  //std::cout << \"done reading rhs\" << std::endl;\n\n  if (!readVectorFromFile(\"../examples/testdata/result65025.txt\", ref_result))\n  {\n    std::cout << \"Error reading Result file\" << std::endl;\n    return 0;\n  }\n  //std::cout << \"done reading result\" << std::endl;\n\n\n  //\n  // set up ILUT preconditioners for ViennaCL and ublas objects. Other preconditioners can also be used (see manual)\n  //\n  viennacl::linalg::ilut_precond< ublas::compressed_matrix<ScalarType> >    ublas_ilut(ublas_matrix, viennacl::linalg::ilut_tag());\n  viennacl::linalg::ilu0_precond< ublas::compressed_matrix<ScalarType> >    ublas_ilu0(ublas_matrix, viennacl::linalg::ilu0_tag());\n  viennacl::linalg::block_ilu_precond< ublas::compressed_matrix<ScalarType>,\n                                       viennacl::linalg::ilu0_tag>          ublas_block_ilu0(ublas_matrix, viennacl::linalg::ilu0_tag());\n\n  //\n  // Conjugate gradient solver:\n  //\n  std::cout << \"----- CG Test -----\" << std::endl;\n\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::cg_tag());\n  std::cout << \"Residual norm: \" << norm_2(prod(ublas_matrix, result) - rhs) << std::endl;\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::cg_tag(1e-6, 20), ublas_ilut);\n  std::cout << \"Residual norm: \" << norm_2(prod(ublas_matrix, result) - rhs) << std::endl;\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::cg_tag(1e-6, 20), ublas_ilu0);\n  std::cout << \"Residual norm: \" << norm_2(prod(ublas_matrix, result) - rhs) << std::endl;\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::cg_tag(1e-6, 20), ublas_block_ilu0);\n  std::cout << \"Residual norm: \" << norm_2(prod(ublas_matrix, result) - rhs) << std::endl;\n\n  //\n  // Stabilized BiConjugate gradient solver:\n  //\n  std::cout << \"----- BiCGStab Test -----\" << std::endl;\n\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::bicgstab_tag());          //without preconditioner\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::bicgstab_tag(1e-6, 20), ublas_ilut); //with preconditioner\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::bicgstab_tag(1e-6, 20), ublas_ilu0); //with preconditioner\n\n  //\n  // GMRES solver:\n  //\n  std::cout << \"----- GMRES Test -----\" << std::endl;\n\n  //\n  // for ublas objects:\n  //\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::gmres_tag());   //without preconditioner\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::gmres_tag(1e-6, 20), ublas_ilut);//with preconditioner\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::gmres_tag(1e-6, 20), ublas_ilu0);//with preconditioner\n\n  //\n  //  That's it.\n  //\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n\n  return 0;\n}\n\n", "meta": {"hexsha": "ad6a87e87204f41f88d1e3860a4d9c2eafa302cf", "size": 5407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/iterative-ublas.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/iterative-ublas.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/iterative-ublas.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": 34.4394904459, "max_line_length": 137, "alphanum_fraction": 0.6458294803, "num_tokens": 1545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143060406073, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5384129820914875}}
{"text": "//  (C) Copyright John Maddock 2005.\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_HYPOT_INCLUDED\n#define BOOST_MATH_HYPOT_INCLUDED\n\n#include <cmath>\n#include <boost/limits.hpp>\n#include <algorithm> // swap\n\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n#  include <boost/static_assert.hpp>\n#else\n#  include <boost/assert.hpp>\n#endif\n\n#ifdef BOOST_NO_STDC_NAMESPACE\nnamespace std{ using ::sqrt; using ::fabs; }\n#endif\n\n\nnamespace boost{ namespace math{\n\ntemplate <class T>\nT hypot(T x, T y)\n{\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n   BOOST_STATIC_ASSERT(::std::numeric_limits<T>::is_specialized);\n#else\n   BOOST_ASSERT(std::numeric_limits<T>::is_specialized);\n#endif\n\n   //\n   // normalize x and y, so that both are positive and x >= y:\n   //\n   x = (std::fabs)(x);\n   y = (std::fabs)(y);\n\n   // special case, see C99 Annex F:\n   if(std::numeric_limits<T>::has_infinity\n      && ((x == std::numeric_limits<T>::infinity())\n      || (y == std::numeric_limits<T>::infinity())))\n      return std::numeric_limits<T>::infinity();\n\n   if(y > x) \n      (std::swap)(x, y);\n   //\n   // figure out overflow and underflow limits:\n   //\n   T safe_upper = (std::sqrt)((std::numeric_limits<T>::max)()) / 2;\n   T safe_lower = (std::sqrt)((std::numeric_limits<T>::min)());\n   static const T one = 1;\n   //\n   // Now handle special cases:\n   //\n   if(x >= safe_upper)\n   {\n      if(y <= one)\n      {\n         // y is neligible:\n         return x;\n      }\n      return (std::sqrt)(x) * (std::sqrt)(y) * (std::sqrt)(x/y + y/x);\n   }\n   else if(y <= safe_lower)\n   {\n      if((x >= one) || (y == 0))\n      {\n         // y is negligible:\n         return x;\n      }\n      return (std::sqrt)(x) * (std::sqrt)(y) * (std::sqrt)(x/y + y/x);\n   }\n   //\n   // If we get here then x^2+y^2 will not overflow or underflow:\n   //\n   return (std::sqrt)(x*x + y*y);\n}\n\n} } // namespaces\n\n#endif // BOOST_MATH_HYPOT_INCLUDED\n", "meta": {"hexsha": "c827692b3c5a58822d0b1535b9c77bba3c74ab22", "size": 2064, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost-1_34_1/boost/math/special_functions/hypot.hpp", "max_stars_repo_name": "memoryboxes/bitcoin_satoshi", "max_stars_repo_head_hexsha": "efbe7e393c1ae3ee9f26a3040c423f176b1e48cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T01:42:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T18:33:43.000Z", "max_issues_repo_path": "include/boost-1_34_1/boost/math/special_functions/hypot.hpp", "max_issues_repo_name": "memoryboxes/bitcoin_satoshi", "max_issues_repo_head_hexsha": "efbe7e393c1ae3ee9f26a3040c423f176b1e48cd", "max_issues_repo_licenses": ["MIT"], "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-1_34_1/boost/math/special_functions/hypot.hpp", "max_forks_repo_name": "memoryboxes/bitcoin_satoshi", "max_forks_repo_head_hexsha": "efbe7e393c1ae3ee9f26a3040c423f176b1e48cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-10-29T08:02:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T16:57:29.000Z", "avg_line_length": 24.2823529412, "max_line_length": 70, "alphanum_fraction": 0.6114341085, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.5384129739630736}}
{"text": "#include <Eigen/Core>\n#include <Eigen/LU>\n#include \"gtest/gtest.h\"\n\n#include \"solver/qp_solver.h\"\n#include \"util/random.h\"\n\nnamespace GraphSfM {\n\n// A rigged QP minimization problem with a known output.\n//\n// 1/2 * x' * P * x + q' * x + r\n//     [  5  -2  -1 ]\n// P = [ -2   4   3 ]\n//     [ -1   3   5 ]\n//\n// q = [ 2  -35  -47 ]^t\n// r = 5\n//\n// Minimizing this unbounded problem should result in:\n//   x = [ 3  5  7 ]^t\nTEST(QPSolver, Unbounded) {\n  static const double kTolerance = 1e-4;\n\n  Eigen::MatrixXd P(3, 3);\n  P << 5, -2, -1,\n    -2, 4, 3,\n    -1, 3, 5;\n  Eigen::VectorXd q(3);\n  q << 2, -35, -47;\n  const double r = 5;\n\n  QPSolver::Options options;\n  options.max_num_iterations = 100;\n  Eigen::SparseMatrix<double> P_sparse(P.sparseView());\n  QPSolver qp_solver(options, P_sparse, q, r);\n  Eigen::VectorXd solution;\n  ASSERT_TRUE(qp_solver.Solve(&solution));\n\n  // Verify the solution is near (3, 5, 7).\n  const Eigen::Vector3d gt_solution(3, 5, 7);\n  for (int i = 0; i < 3; i++) {\n    EXPECT_NEAR(solution(i), gt_solution(i), kTolerance);\n  }\n\n  // Check that the residual is near optimal.\n  const double residual =\n      0.5 * solution.dot(P * solution) + solution.dot(q) + r;\n  const double gt_residual =\n      0.5 * gt_solution.dot(P * gt_solution) + gt_solution.dot(q) + r;\n  EXPECT_NEAR(residual, gt_residual, kTolerance);\n}\n\nTEST(QPSolver, LooseBounds) {\n  static const double kTolerance = 1e-4;\n\n  Eigen::MatrixXd P(3, 3);\n  P << 5, -2, -1,\n    -2, 4, 3,\n    -1, 3, 5;\n  Eigen::VectorXd q(3);\n  q << 2, -35, -47;\n  const double r = 5;\n\n  QPSolver::Options options;\n  options.max_num_iterations = 100;\n  Eigen::SparseMatrix<double> P_sparse(P.sparseView());\n  QPSolver qp_solver(options, P_sparse, q, r);\n\n  // Set a lower bound that should not affect the output.\n  Eigen::VectorXd lower_bound(3);\n  lower_bound << 0, 0, 0;\n  qp_solver.SetLowerBound(lower_bound);\n\n  // Set an upper bound that should not affect the output.\n  Eigen::VectorXd upper_bound(3);\n  upper_bound << 10, 10, 10;\n  qp_solver.SetUpperBound(upper_bound);\n  Eigen::VectorXd solution;\n\n  ASSERT_TRUE(qp_solver.Solve(&solution));\n\n  // Verify the solution is near (3, 5, 7).\n  const Eigen::Vector3d gt_solution(3, 5, 7);\n  for (int i = 0; i < 3; i++) {\n    EXPECT_NEAR(solution(i), gt_solution(i), kTolerance);\n  }\n\n  // Check that the residual is near optimal.\n  const double residual =\n      0.5 * solution.dot(P * solution) + solution.dot(q) + r;\n  const double gt_residual =\n      0.5 * gt_solution.dot(P * gt_solution) + gt_solution.dot(q) + r;\n  EXPECT_NEAR(residual, gt_residual, kTolerance);\n}\n\nTEST(QPSolver, TightBounds) {\n  static const double kTolerance = 1e-4;\n\n  Eigen::MatrixXd P(3, 3);\n  P << 5, -2, -1,\n    -2, 4, 3,\n    -1, 3, 5;\n  Eigen::VectorXd q(3);\n  q << 2, -35, -47;\n  const double r = 5;\n\n  QPSolver::Options options;\n  options.absolute_tolerance = 1e-8;\n  options.relative_tolerance = 1e-8;\n  Eigen::SparseMatrix<double> P_sparse(P.sparseView());\n  QPSolver qp_solver(options, P_sparse, q, r);\n\n  // Set a lower bound that constrains the output.\n  Eigen::VectorXd lower_bound(3);\n  lower_bound << 5, 7, 9;\n  qp_solver.SetLowerBound(lower_bound);\n\n  // Set an upper bound that constrains the output.\n  Eigen::VectorXd upper_bound(3);\n  upper_bound << 10, 12, 14;\n  qp_solver.SetUpperBound(upper_bound);\n\n  Eigen::VectorXd solution;\n  ASSERT_TRUE(qp_solver.Solve(&solution));\n\n  // Verify the solution is near (5, 7, 9).\n  const Eigen::Vector3d gt_solution(5, 7, 9);\n  for (int i = 0; i < 3; i++) {\n    EXPECT_NEAR(solution(i), gt_solution(i), kTolerance);\n  }\n\n  // Check that the residual is near optimal.\n  const double residual =\n      0.5 * solution.dot(P * solution) + solution.dot(q) + r;\n  const double gt_residual =\n      0.5 * gt_solution.dot(P * gt_solution) + gt_solution.dot(q) + r;\n  EXPECT_NEAR(residual, gt_residual, kTolerance);\n}\n\nTEST(QPSolver, InvalidBounds) {\n  Eigen::MatrixXd P(3, 3);\n  P << 5, -2, -1,\n    -2, 4, 3,\n    -1, 3, 5;\n  Eigen::VectorXd q(3);\n  q << 2, -35, -47;\n  const double r = 5;\n\n  QPSolver::Options options;\n  Eigen::SparseMatrix<double> P_sparse(P.sparseView());\n  QPSolver qp_solver(options, P_sparse, q, r);\n\n  // Set the upper bound as the lower bound.\n  Eigen::VectorXd lower_bound(3);\n  lower_bound << 5, 7, 9;\n  qp_solver.SetUpperBound(lower_bound);\n\n  // Set the lower bound as the upper bound, making the valid solution space\n  // non-existant.\n  Eigen::VectorXd upper_bound(3);\n  upper_bound << 10, 12, 14;\n  qp_solver.SetLowerBound(upper_bound);\n\n  Eigen::VectorXd solution;\n  EXPECT_FALSE(qp_solver.Solve(&solution));\n}\n\n}  // namespace GraphSfM\n", "meta": {"hexsha": "9dd3f6438e16b51001b5ca5000e36f79e6451623", "size": 4614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solver/qp_solver_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/solver/qp_solver_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/solver/qp_solver_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": 27.1411764706, "max_line_length": 76, "alphanum_fraction": 0.6499783268, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.5384129739630736}}
{"text": "#include <iostream>\n#include <sys/time.h>\n#include <Eigen/Core>\n#include <fstream>\n\n#include \"celerite/celerite.h\"\n#include \"celerite/carma.h\"\n#include \"celerite/utils.h\"\n#include \"../include/KF.h\"\n#include \"../include/ndsho.h\"\n#include \"../include/dsho.h\"\n\n\nusing namespace Eigen;\nusing namespace std;\n\n#define TWOPI 6.283185307179586\n\n// This program benchmarks a single DSHO using celerite and gpstate\n\n// Timer for the benchmark.\ndouble get_timestamp ()\n{\n  struct timeval now;\n  gettimeofday (&now, NULL);\n  return double(now.tv_usec) * 1.0e-6 + double(now.tv_sec);\n}\n\n// Function to read a whitespace separated file\nstd::vector<double> load_csv (const std::string & path) {\n    std::ifstream indata;\n    indata.open(path);\n    std::string line;\n    std::vector<double> values;\n    uint rows = 0;\n    while (std::getline(indata, line)) {\n        std::stringstream lineStream(line);\n        std::string cell;\n        while (std::getline(lineStream, cell, ' ')) {\n            //cout << std::stod(cell) << endl;\n            values.push_back(std::stod(cell));\n        }\n        ++rows;\n    }\n    return values;\n}\n\n\n\nint main (int argc, char* argv[])\n{\n  srand(42);\n\n  // we will benchmark models with up to N_max DSHO components\n  size_t N_max = 64;\n  //N_max=1;\n  if (argc >= 2) N_max = atoi(argv[1]);\n  // dfor each sample size, timeing will be done niter times\n  size_t niter = 5;\n  if (argc >= 3) niter = atoi(argv[2]);\n\n  std::random_device rd;\n  std::mt19937 rng(rd());\n  std::normal_distribution<double> gaussian(0.0,0.05);\n\n  int vecsize = 10000;\n\t// map data to VectorXds\n\tVectorXd yi(vecsize);\n  VectorXd times = Eigen::VectorXd::Random(vecsize);\n  times.array() += 1.0;\n  times.array() *= (10*0.5);\n  std::sort(times.data(), times.data() + times.size());\n  double omega0 = TWOPI;\n\n  for (int j=0; j<times.size(); j++){\n      //times(j) = 0.001*double(j);\n      yi(j) = sin(omega0 * times(j)) + gaussian(rng);\n  }\n\n\t// this is the observational error vector\n\tVectorXd yierr = VectorXd::Ones(yi.size());\n\tyierr.array() *= 0.05;\n\n\n\n  // Generate some fake data.\n  //size_t N_points = 4096;\n  //Eigen::VectorXd x = Eigen::VectorXd::Random(N_points),\n  //                yerr = Eigen::VectorXd::Random(N_points),\n  //                y, diag;\n  //yerr.array() *= 0.1;\n  //yerr.array() += 1.0;\n  //diag = yerr.array() * yerr.array();\n  //std::sort(x.data(), x.data() + x.size());\n  //y = sin(x.array());\n\n  //std::vector<double> values = load_csv(\"two_comp_dsho.txt\");\n  //std::vector<double> values = load_csv(\"GPtest10_dsho_trim.txt\");\n\n\n  //VectorXd times = Map<VectorXd, 0, InnerStride<2> > (values.data(), 10000);\n  //VectorXd yi = Map<VectorXd, 0, InnerStride<2> > (values.data()+1, 10000);\n  //VectorXd yierr = VectorXd::Ones(yi.size());\n  //yierr *= 0.01;\n  VectorXd diagi = yierr.array()*yierr.array();\n\n\n\n  //set up the single DSHO parameters we use as a base\n  //double omega0 = 0.785398;\n  double Q = 10.0;\n  double varf = 0.05;\n\n  double celerite_time = 0.0;\n  double gpstate_time = 0.0;\n  double strt;\n\n  Eigen::VectorXd alpha_real, beta_real;\n\n  for (size_t N = 1; N <= N_max; N +=1) {\n    // define arrays\n    // The DSHO is a CARMA model, with parameters as written below\n    Eigen::VectorXd omega0_arr(N), Q_arr(N), varf_arr(N);\n    Eigen::VectorXd alpha_complex_real_arr(N), alpha_complex_imag_arr(N), beta_complex_real_arr(N), beta_complex_imag_arr(N);\n    double log_likelihood=0.0, celerite_ll=0.0;\n\n    int nterms = 3;\n\n    for (size_t i=0; i<N; i++)\n    {\n      if (i == 0)\n      {\n        omega0_arr(i) = omega0; //0.785398; //0.1234234;\n      }\n      else\n      {\n        omega0_arr(i) = omega0 + static_cast<double>(i);\n      }\n      Q_arr(i) = Q;\n      varf_arr(i) = varf;\n      Eigen::VectorXd carma_arparams(nterms);\n      Eigen::VectorXd carma_maparams(nterms-1);\n      carma_arparams << omega0_arr(i)*omega0_arr(i), omega0_arr(i)/Q, 1.0;\n      carma_maparams << 1.0, 0.0;\n\n      // version that used to work!\n      double temp = std::sqrt(4.0*Q_arr(i)*Q_arr(i) - 1.0);\n      //double S0 = varf_arr(i)* std::pow(Q_arr(i),-2) * std::sqrt(M_PI) / std::sqrt(2);\n      double S0 = varf_arr(i)* std::pow(omega0_arr(i),-4) * std::sqrt(M_PI) / std::sqrt(2);\n      alpha_complex_real_arr(i) = S0 * omega0_arr(i) * Q_arr(i);\n      alpha_complex_imag_arr(i) = S0 * omega0_arr(i) * Q_arr(i) / temp;\n      beta_complex_real_arr(i) = 0.5 * omega0_arr(i) / Q_arr(i);\n      beta_complex_imag_arr(i) = 0.5 * temp * omega0_arr(i) / Q_arr(i);\n    }\n\n\n    celerite::solver::CholeskySolver<double> solver;\n\n    for (size_t i = 0; i < niter; ++i) {\n      strt = get_timestamp();\n      //int flag = solver.compute(alpha_real_arr, beta_real_arr, alpha_complex_real_arr, alpha_complex_imag_arr, beta_complex_real_arr, beta_complex_imag_arr, x, diag);\n      //celerite_ll = -0.5*(solver.dot_solve(y) + solver.log_determinant() + x.rows() * log(2.0 * M_PI));\n\n      solver.compute(0.0, alpha_real, beta_real, alpha_complex_real_arr, alpha_complex_imag_arr, beta_complex_real_arr, beta_complex_imag_arr, times, diagi);\n      celerite_ll = -0.5*(solver.dot_solve(yi) + solver.log_determinant() + times.rows() * log(2.0 * M_PI));\n      celerite_time += get_timestamp()-strt;\n    }\n\n    //gpstate::n_dsho::N_DSHOSolver ndsho(x,y,yerr,omega0_arr, Q_arr, varf_arr);\n    gpstate::n_dsho::N_DSHOSolver ndsho(times,yi,yierr,omega0_arr, Q_arr, varf_arr);\n    for (size_t i = 0; i < niter; ++i) {\n      strt = get_timestamp();\n      log_likelihood = ndsho.KF_log_likelihood();\n      gpstate_time += get_timestamp()-strt;\n    }\n\n\n    // Print the results.\n    std::cout << N;\n    std::cout << \" \";\n    std::cout << celerite_time / niter;\n    std::cout << \" \";\n    std::cout << gpstate_time / niter;\n    std::cout << \" \";\n    std::cout << celerite_ll;\n    std::cout << \" \";\n    std::cout << log_likelihood;\n    std::cout << \" \";\n\n    std::cout << \"\\n\";\n  }\n}\n", "meta": {"hexsha": "0a98156bb7d06510696f1560ebf3167222deba43", "size": 5856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/benchmark_ndsho.cpp", "max_stars_repo_name": "andres-jordan/gpstate", "max_stars_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-13T23:27:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-13T23:27:32.000Z", "max_issues_repo_path": "src/benchmark_ndsho.cpp", "max_issues_repo_name": "andres-jordan/gpstate", "max_issues_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/benchmark_ndsho.cpp", "max_forks_repo_name": "andres-jordan/gpstate", "max_forks_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_forks_repo_licenses": ["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.3419689119, "max_line_length": 168, "alphanum_fraction": 0.6236338798, "num_tokens": 1827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.538390522266041}}
{"text": "//  Copyright (c) 2006 Xiaogang Zhang, 2015 John Maddock\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//  History:\n//  XZ wrote the original of this file as part of the Google\n//  Summer of Code 2006.  JM modified it to fit into the\n//  Boost.Math conceptual framework better, and to correctly\n//  handle the y < 0 case.\n//  Updated 2015 to use Carlson's latest methods.\n//\n\n#ifndef BOOST_MATH_ELLINT_RC_HPP\n#define BOOST_MATH_ELLINT_RC_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/tools/config.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <iostream>\n\n// Carlson's degenerate elliptic integral\n// R_C(x, y) = R_F(x, y, y) = 0.5 * \\int_{0}^{\\infty} (t+x)^{-1/2} (t+y)^{-1} dt\n// Carlson, Numerische Mathematik, vol 33, 1 (1979)\n\nnamespace boost { namespace math { namespace detail{\n\ntemplate <typename T, typename Policy>\nT ellint_rc_imp(T x, T y, const Policy& pol)\n{\n    BOOST_MATH_STD_USING\n\n    static const char* function = \"boost::math::ellint_rc<%1%>(%1%,%1%)\";\n\n    if(x < 0)\n    {\n       return policies::raise_domain_error<T>(function,\n            \"Argument x must be non-negative but got %1%\", x, pol);\n    }\n    if(y == 0)\n    {\n       return policies::raise_domain_error<T>(function,\n            \"Argument y must not be zero but got %1%\", y, pol);\n    }\n\n    // for y < 0, the integral is singular, return Cauchy principal value\n    T prefix, result;\n    if(y < 0)\n    {\n        prefix = sqrt(x / (x - y));\n        x = x - y;\n        y = -y;\n    }\n    else\n       prefix = 1;\n\n    if(x == 0)\n    {\n       result = constants::half_pi<T>() / sqrt(y);\n    }\n    else if(x == y)\n    {\n       result = 1 / sqrt(x);\n    }\n    else if(y > x)\n    {\n       result = atan(sqrt((y - x) / x)) / sqrt(y - x);\n    }\n    else\n    {\n       if(y / x > 0.5)\n       {\n          T arg = sqrt((x - y) / x);\n          result = (boost::math::log1p(arg) - boost::math::log1p(-arg)) / (2 * sqrt(x - y));\n       }\n       else\n       {\n          result = log((sqrt(x) + sqrt(x - y)) / sqrt(y)) / sqrt(x - y);\n       }\n    }\n    return prefix * result;\n}\n\n} // namespace detail\n\ntemplate <class T1, class T2, class Policy>\ninline typename tools::promote_args<T1, T2>::type \n   ellint_rc(T1 x, T2 y, const Policy& pol)\n{\n   typedef typename tools::promote_args<T1, T2>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(\n      detail::ellint_rc_imp(\n         static_cast<value_type>(x),\n         static_cast<value_type>(y), pol), \"boost::math::ellint_rc<%1%>(%1%,%1%)\");\n}\n\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type \n   ellint_rc(T1 x, T2 y)\n{\n   return ellint_rc(x, y, policies::policy<>());\n}\n\n}} // namespaces\n\n#endif // BOOST_MATH_ELLINT_RC_HPP\n\n", "meta": {"hexsha": "846c752a1461b666987569fd7ec2dc33e6152ec5", "size": 3118, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/math/special_functions/ellint_rc.hpp", "max_stars_repo_name": "189569400/ClickHouse", "max_stars_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/math/special_functions/ellint_rc.hpp", "max_issues_repo_name": "189569400/ClickHouse", "max_issues_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/math/special_functions/ellint_rc.hpp", "max_forks_repo_name": "189569400/ClickHouse", "max_forks_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": 27.1130434783, "max_line_length": 92, "alphanum_fraction": 0.6173829378, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5383905124027453}}
{"text": "\n#ifndef STATS_STATS_HPP\n#define STATS_STATS_HPP\n\n#include <Eigen/Dense>\n#include <unordered_map>\n#include <string>\n#include <math.h>\n#ifdef BAZEL\n#include \"Models/Model.hpp\"\n#else\n#include \"../Models/Model.hpp\"\n#endif\n\nusing namespace Eigen;\nusing namespace std;\n\nnamespace Stats {\n//public:\n    float ChiSquaredTest(MatrixXf, MatrixXf);\n    float ChiToPValue(float, int);\n    float WaldTest(float mle, float var, float candidate);\n    float FisherExactTest(MatrixXf);\n    float BonCorrection(float, int);\n    float get_ts(float beta, float var, float sigma);\n    float get_qs(float ts, int N, int q);\n};\n\nclass StatsBasic : public Model{\nprotected:\n    bool shouldCorrect;\n    int genoType;\n\n    // algorithm use\n    float progress;\n    bool isRunning;\n    bool shouldStop;\n\n    void checkGenoType();\npublic:\n    virtual void setAttributeMatrix(const string&, MatrixXf*);\n\n    void BonferroniCorrection();\n\n    MatrixXf getBeta();\n\n    virtual void assertReadyToRun();\n    virtual void run() {};\n    virtual void setUpRun();\n    virtual void finishRun();\n\n    StatsBasic();\n    StatsBasic(const unordered_map<string, string>&);\n\n    // algorithm replacement\n    float getProgress();\n    bool getIsRunning();\n    void stop();\n\n    virtual ~StatsBasic(){};\n};\n\n#endif //STATS_STATS_HPP", "meta": {"hexsha": "0b088f5ff28cf18747c279589b015c99b1367d74", "size": 1285, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Stats/Stats.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/Stats/Stats.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/Stats/Stats.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": 20.3968253968, "max_line_length": 62, "alphanum_fraction": 0.6949416342, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5383905052561696}}
{"text": "#include <boost/math/distributions/logistic.hpp>\n", "meta": {"hexsha": "b1b03b649cd97a7a47940e6d29d8f46406c61696", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_logistic.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_logistic.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_logistic.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8163265306, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5383804664918282}}
{"text": "\n// This file is part of Man, a robotic perception, locomotion, and\n// team strategy application created by the Northern Bites RoboCup\n// team of Bowdoin College in Brunswick, Maine, for the Aldebaran\n// Nao robot.\n//\n// Man is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Lesser 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// Man 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 Lesser Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// and the GNU Lesser Public License along with Man.  If not, see\n// <http://www.gnu.org/licenses/>.\n\n#include <math.h>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/lu.hpp>              // for lu_factorize\n#include <boost/numeric/ublas/io.hpp>              // for cout\n\n#include \"nb/CoordFrame.h\"\n\nusing namespace NBMath;\nusing namespace CoordFrame4D;\n\n// -------------------- Helper matrix methods --------------------\n\n//TODO: Move all these rot4D, etc into a Coord4D namespace.\n// also, make all these use bounded matrices (see NBMatrixMath)\nconst NBMath::ufmatrix4\nCoordFrame4D::rotation4D(const Axis axis,\n                         const double angle) {\n    NBMath::ufmatrix4 rot = boost::numeric::ublas::identity_matrix <double>(4);\n\n    if (angle == 0.0) { //OPTIMIZAION POINT\n        return rot;\n    }\n\n    //TODO: Make this one call:\n    float sinAngle;\n    float cosAngle;\n    sincosf(angle, &sinAngle, &cosAngle);\n\n    switch(axis) {\n    case X_AXIS:\n        rot(Y_AXIS, Y_AXIS) =  cosAngle;\n        rot(Y_AXIS, Z_AXIS) = -sinAngle;\n        rot(Z_AXIS, Y_AXIS) =  sinAngle;\n        rot(Z_AXIS, Z_AXIS) =  cosAngle;\n        break;\n    case Y_AXIS:\n        rot(X_AXIS, X_AXIS) =  cosAngle;\n        rot(X_AXIS, Z_AXIS) =  sinAngle;\n        rot(Z_AXIS, X_AXIS) = -sinAngle;\n        rot(Z_AXIS, Z_AXIS) =  cosAngle;\n        break;\n    case Z_AXIS:\n        rot(X_AXIS, X_AXIS) =  cosAngle;\n        rot(X_AXIS, Y_AXIS) = -sinAngle;\n        rot(Y_AXIS, X_AXIS) =  sinAngle;\n        rot(Y_AXIS, Y_AXIS) =  cosAngle;\n        break;\n    default:\n        break;\n    }\n    return rot;\n}\n\nconst NBMath::ufmatrix4 CoordFrame4D::translation4D(const double dx,\n                                                    const double dy,\n                                                    const double dz) {\n    NBMath::ufmatrix4 trans = boost::numeric::ublas::identity_matrix <double>(4);\n    trans(X_AXIS, W_AXIS) = dx;\n    trans(Y_AXIS, W_AXIS) = dy;\n    trans(Z_AXIS, W_AXIS) = dz;\n    return trans;\n}\n\nconst NBMath::ufvector4 CoordFrame4D::vector4D(const double x, const double y,\n                                               const double z,\n                                               const double w) {\n    NBMath::ufvector4 p = boost::numeric::ublas::zero_vector <double> (4);\n    p(0) = x;\n    p(1) = y;\n    p(2) = z;\n    p(3) = w;\n    return p;\n}\n\n\n/**\n * Returns precalculated Trans[x,y,z].Rotz[wz].Roty[wy].Rotx[wx]\n */\nconst NBMath::ufmatrix4 CoordFrame4D::get6DTransform(const double x,\n                                                     const double y,\n                                                     const double z,\n                                                     const double wx,\n                                                     const double wy,\n                                                     const double wz){\n    float cwx,cwy,cwz,\n        swx,swy,swz;\n    sincosf(wx,&swx,&cwx);\n    sincosf(wy,&swy,&cwy);\n    sincosf(wz,&swz,&cwz);\n    NBMath::ufmatrix4 r = boost::numeric::ublas::identity_matrix<double>(4);\n\n    //Row 1\n    r(0,0) =cwy*cwz;\n    r(0,1) =cwz*swx*swy-cwx*swz;\n    r(0,2) =cwx*cwz*swy+swx*swz;\n    r(0,3) =x;\n    //Row2\n    r(1,0) =cwy*swz;\n    r(1,1) =cwx*cwz+swx*swy*swz;\n    r(1,2) =-cwz*swx+cwx*swy*swz;\n    r(1,3) =y;\n    //Row3\n    r(2,0) =-swy;\n    r(2,1) =cwy*swx;\n    r(2,2) =cwx*cwy;\n    r(2,3) =z;\n\n    return r;\n}\n\nconst NBMath::ufmatrix4\nCoordFrame4D::invertHomogenous(const NBMath::ufmatrix4 source){\n    const NBMath::ufmatrix3 Rt = trans(subrange(source,0,3,0,3));\n    const NBMath::ufvector3 Rtd = -prod(Rt,\n                                        CoordFrame3D::vector3D(source(0,3),\n                                                               source(1,3),\n                                                               source(2,3)));\n    NBMath::ufmatrix4 result =\n        boost::numeric::ublas::identity_matrix<double>(4);\n    subrange(result,0,3,0,3) = Rt;\n    result(0,3) = Rtd(0);\n    result(1,3) = Rtd(1);\n    result(2,3) = Rtd(2);\n    return result;\n}\n", "meta": {"hexsha": "32f9d65006594257c96f2c0640226c1289c44a04", "size": 4962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hardware/src/nb/CoordFrame4D.cpp", "max_stars_repo_name": "arssivka/naomech", "max_stars_repo_head_hexsha": "678e270d388498ae888b4f945b3753e21bf5ad5a", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-12-28T14:04:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T17:25:37.000Z", "max_issues_repo_path": "hardware/src/nb/CoordFrame4D.cpp", "max_issues_repo_name": "arssivka/naomech", "max_issues_repo_head_hexsha": "678e270d388498ae888b4f945b3753e21bf5ad5a", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-10-22T15:15:26.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-26T15:03:40.000Z", "max_forks_repo_path": "hardware/src/nb/CoordFrame4D.cpp", "max_forks_repo_name": "arssivka/naomech", "max_forks_repo_head_hexsha": "678e270d388498ae888b4f945b3753e21bf5ad5a", "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": 33.08, "max_line_length": 81, "alphanum_fraction": 0.5594518339, "num_tokens": 1378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.538380461949604}}
{"text": "\n#include <list>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\nnamespace bg  = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\ntypedef bg::model::point<float, 2, bg::cs::cartesian> point2;\ntypedef bg::model::box<point2> box2;\ntypedef std::pair<point2, uint> value2;\ntypedef bgi::rtree<value2, bgi::quadratic<16>> r2tree;\n\ntypedef bg::model::point<float, 3, bg::cs::cartesian> point;\ntypedef bg::model::box<point> box;\ntypedef std::pair<point, uint> value;\ntypedef bgi::rtree<value, bgi::quadratic<16>> r3tree;\n\n#include \"spatial-index.hpp\"\n\nnamespace perceive\n{\n// ------------------------------------------------------------- Spatial-2-Index\n\ninline LabeledVector2 value_to_lv2(const value2& v, const size_t& size)\n{\n   Expects(v.second < size);\n   return std::make_pair(to_vec2(Vector2f(v.first.get<0>(), v.first.get<1>())),\n                         v.second);\n}\n\nstruct Spatial2Index::Pimpl\n{\n   Pimpl(Spatial2Index& si) {}\n\n   r2tree index;\n   size_t size = 0;\n\n   template<typename Iterator> void init(Iterator begin, Iterator end)\n   {\n      index.clear();\n      auto to_r2tree = [&](const Vector2& p, uint idx) {\n         return std::make_pair(point2(float(p.x), float(p.y)), idx);\n      };\n      uint32_t counter = 0;\n      while(begin != end) index.insert(to_r2tree(*begin++, counter++));\n      size = counter;\n   }\n};\n\nSpatial2Index::Spatial2Index() { pimpl_ = new Pimpl(*this); }\nSpatial2Index::~Spatial2Index() { delete pimpl_; }\nSpatial2Index::Spatial2Index(const Spatial2Index& rhs)\n    : pimpl_(nullptr)\n{\n   pimpl_ = new Pimpl(*this);\n   *this  = rhs;\n}\nSpatial2Index::Spatial2Index(Spatial2Index&& rhs)\n    : pimpl_(nullptr)\n{\n   std::swap(pimpl_, rhs.pimpl_);\n}\nSpatial2Index& Spatial2Index::operator=(const Spatial2Index& rhs)\n{\n   if(this == &rhs) return *this;\n   *pimpl_ = *(rhs.pimpl_);\n   return *this;\n}\nSpatial2Index& Spatial2Index::operator=(Spatial2Index&& rhs)\n{\n   if(this == &rhs) return *this;\n   delete pimpl_;\n   pimpl_ = nullptr;\n   std::swap(pimpl_, rhs.pimpl_);\n   return *this;\n}\nvoid Spatial2Index::clear() { pimpl_->index.clear(); }\nvoid Spatial2Index::init(const vector<Vector2>& pts)\n{\n   pimpl_->init(pts.begin(), pts.end());\n}\nvoid Spatial2Index::init(const std::deque<Vector2>& pts)\n{\n   pimpl_->init(pts.begin(), pts.end());\n}\nsize_t Spatial2Index::size() const noexcept { return pimpl_->size; }\n\nbool Spatial2Index::empty() const noexcept { return size() == 0; }\n\nvoid Spatial2Index::query_nearest(const Vector2& P,\n                                  uint n_points,\n                                  std::deque<LabeledVector2>& ret) const\n{\n   ret.clear();\n   if(!empty()) {\n      vector<value2> values;\n      values.reserve(n_points);\n      pimpl_->index.query(\n          bgi::nearest(point2(float(P.x), float(P.y)), n_points),\n          std::back_inserter(values));\n      for(const value2& v : values) ret.push_back(value_to_lv2(v, size()));\n   }\n}\n\nvoid Spatial2Index::query_nearest(const Vector2& P,\n                                  uint n_points,\n                                  vector<LabeledVector2>& ret) const\n{\n   ret.clear();\n   if(!empty()) {\n      vector<value2> values;\n      values.reserve(n_points);\n      pimpl_->index.query(\n          bgi::nearest(point2(float(P.x), float(P.y)), n_points),\n          std::back_inserter(values));\n      ret.resize(values.size());\n      for(uint i = 0; i < values.size(); ++i)\n         ret[i] = value_to_lv2(values[i], size());\n   }\n}\n\nLabeledVector2 Spatial2Index::query_nearest(const Vector2& P) const\n{\n   if(empty()) {\n      return std::make_pair(Vector2::nan(), 0u);\n   } else {\n      std::list<value2> values;\n      pimpl_->index.query(bgi::nearest(point2(float(P.x), float(P.y)), 1),\n                          std::back_inserter(values));\n      return value_to_lv2(values.front(), size());\n   }\n}\n\nvoid Spatial2Index::query_region(const AABB& aabb,\n                                 std::deque<LabeledVector2>& ret) const\n{\n   // find values intersecting some area defined by a box\n   box2 query_box(point2(float(aabb.left), float(aabb.top)),\n                  point2(float(aabb.right), float(aabb.bottom)));\n   std::vector<value2> result_s;\n   const auto& rtree = pimpl_->index;\n   rtree.query(bgi::intersects(query_box), std::back_inserter(result_s));\n   for(const value2& v : result_s) ret.push_back(value_to_lv2(v, size()));\n}\n\nvoid Spatial2Index::query_region(const AABB& aabb,\n                                 vector<LabeledVector2>& ret) const\n{\n   // find values intersecting some area defined by a box\n   box2 query_box(point2(float(aabb.left), float(aabb.top)),\n                  point2(float(aabb.right), float(aabb.bottom)));\n   std::vector<value2> values;\n   const auto& rtree = pimpl_->index;\n   rtree.query(bgi::intersects(query_box), std::back_inserter(values));\n   ret.resize(values.size());\n   for(uint i = 0; i < values.size(); ++i)\n      ret[i] = value_to_lv2(values[i], size());\n}\n\nvoid Spatial2Index::query_region(const AABB& aabb, vector<Vector2>& ret) const\n{\n   // find values intersecting some area defined by a box\n   box2 query_box(point2(float(aabb.left), float(aabb.top)),\n                  point2(float(aabb.right), float(aabb.bottom)));\n   std::vector<value2> values;\n   const auto& rtree = pimpl_->index;\n   rtree.query(bgi::intersects(query_box), std::back_inserter(values));\n   ret.resize(values.size());\n   for(uint i = 0; i < values.size(); ++i)\n      ret[i] = to_vec2(\n          Vector2f(values[i].first.get<0>(), values[i].first.get<1>()));\n}\n\n// ------------------------------------------------------------- Spatial-3-Index\n\ninline LabeledVector3 value_to_lv3(const value& v)\n{\n   return std::make_pair(\n       to_vec3(Vector3f(v.first.get<0>(), v.first.get<1>(), v.first.get<2>())),\n       v.second);\n}\n\nstruct Spatial3Index::Pimpl\n{\n   Pimpl(Spatial3Index& si) {}\n\n   r3tree index;\n\n   template<typename Iterator> void init(Iterator begin, Iterator end)\n   {\n      index.clear();\n      auto to_r3tree = [&](const Vector3& q, uint idx) {\n         const Vector3f p = to_vec3f(q);\n         return std::make_pair(point(p.x, p.y, p.z), idx);\n      };\n      uint counter = 0;\n      while(begin != end) index.insert(to_r3tree(*begin++, counter++));\n   }\n};\n\nSpatial3Index::Spatial3Index() { pimpl_ = new Pimpl(*this); }\nSpatial3Index::~Spatial3Index() { delete pimpl_; }\nSpatial3Index::Spatial3Index(const Spatial3Index& rhs)\n    : pimpl_(nullptr)\n{\n   pimpl_ = new Pimpl(*this);\n   *this  = rhs;\n}\nSpatial3Index::Spatial3Index(Spatial3Index&& rhs)\n    : pimpl_(nullptr)\n{\n   pimpl_     = rhs.pimpl_;\n   rhs.pimpl_ = nullptr;\n}\nSpatial3Index& Spatial3Index::operator=(const Spatial3Index& rhs)\n{\n   if(this == &rhs) return *this;\n   *pimpl_ = *(rhs.pimpl_);\n   return *this;\n}\nSpatial3Index& Spatial3Index::operator=(Spatial3Index&& rhs)\n{\n   if(this == &rhs) return *this;\n   delete pimpl_;\n   pimpl_     = rhs.pimpl_;\n   rhs.pimpl_ = nullptr;\n   return *this;\n}\nvoid Spatial3Index::clear() { pimpl_->index.clear(); }\nvoid Spatial3Index::init(const vector<Vector3>& pts)\n{\n   pimpl_->init(pts.begin(), pts.end());\n}\nvoid Spatial3Index::init(const std::deque<Vector3>& pts)\n{\n   pimpl_->init(pts.begin(), pts.end());\n}\n\nvoid Spatial3Index::query_nearest(const Vector3& Q,\n                                  uint n_points,\n                                  std::deque<LabeledVector3>& ret) const\n{\n   vector<value> values;\n   values.reserve(n_points);\n   const Vector3f P = to_vec3f(Q);\n   pimpl_->index.query(bgi::nearest(point(P.x, P.y, P.z), n_points),\n                       std::back_inserter(values));\n   for(const value& v : values) ret.push_back(value_to_lv3(v));\n}\n\nLabeledVector3 Spatial3Index::query_nearest(const Vector3& Q) const\n{\n   std::list<value> values;\n   const Vector3f P = to_vec3f(Q);\n   pimpl_->index.query(bgi::nearest(point(P.x, P.y, P.z), 1),\n                       std::back_inserter(values));\n   return value_to_lv3(values.front());\n}\n\n} // namespace perceive\n", "meta": {"hexsha": "7b44bfc35df888e758f223608247f7f9873eb7a2", "size": 8106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/geometry/spatial-index.cpp", "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/spatial-index.cpp", "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/spatial-index.cpp", "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": 30.4736842105, "max_line_length": 80, "alphanum_fraction": 0.6254626203, "num_tokens": 2186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5383804616774067}}
{"text": "#include \"camodocal/calib/HandEyeCalibration.h\"\n\n#include <boost/throw_exception.hpp>\n#include <iostream>\n\n#include <ceres/ceres.h>\n#include \"camodocal/EigenUtils.h\"\n#include \"camodocal/calib/DualQuaternion.h\"\n\nnamespace camodocal {\n\n/// @todo there may be an alignment issue, see\n/// http://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html\nclass PoseError {\n  public:\n    PoseError(Eigen::Vector3d r1, Eigen::Vector3d t1, Eigen::Vector3d r2,\n              Eigen::Vector3d t2)\n        : m_rvec1(r1), m_rvec2(r2), m_tvec1(t1), m_tvec2(t2) {}\n\n    template <typename T>\n    bool operator()(const T* const q4x1, const T* const t3x1,\n                    T* residual) const {\n        Eigen::Quaternion<T> q(q4x1[0], q4x1[1], q4x1[2], q4x1[3]);\n        Eigen::Matrix<T, 3, 1> t;\n        t << t3x1[0], t3x1[1], t3x1[2];\n\n        DualQuaternion<T> dq(q, t);\n\n        Eigen::Matrix<T, 3, 1> r1 = m_rvec1.cast<T>();\n        Eigen::Matrix<T, 3, 1> t1 = m_tvec1.cast<T>();\n        Eigen::Matrix<T, 3, 1> r2 = m_rvec2.cast<T>();\n        Eigen::Matrix<T, 3, 1> t2 = m_tvec2.cast<T>();\n\n        DualQuaternion<T> dq1(AngleAxisToQuaternion<T>(r1), t1);\n        DualQuaternion<T> dq2(AngleAxisToQuaternion<T>(r2), t2);\n        DualQuaternion<T> dq1_ = dq * dq2 * dq.inverse();\n\n        DualQuaternion<T> diff = (dq1.inverse() * dq1_).log();\n        residual[0] = diff.real().squaredNorm() + diff.dual().squaredNorm();\n\n        return true;\n    }\n\n  private:\n    Eigen::Vector3d m_rvec1, m_rvec2, m_tvec1, m_tvec2;\n\n  public:\n    /// @see\n    /// http://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\nbool HandEyeCalibration::mVerbose = true;\n\nHandEyeCalibration::HandEyeCalibration() {}\n\nvoid HandEyeCalibration::setVerbose(bool on) { mVerbose = on; }\n\n/// Reorganize data to prepare for running SVD\n/// Daniilidis 1999 Section 6, Equations (31) and (33), on page 291\ntemplate <typename T>\nstatic Eigen::MatrixXd ScrewToStransposeBlockofT(\n    const Eigen::Matrix<T, 3, 1>& a, const Eigen::Matrix<T, 3, 1>& a_prime,\n    const Eigen::Matrix<T, 3, 1>& b, const Eigen::Matrix<T, 3, 1>& b_prime) {\n    Eigen::MatrixXd Stranspose(6, 8);\n    Stranspose.setZero();\n\n    typedef Eigen::Matrix<T, 3, 1> VecT;\n    auto skew_a_plus_b = skew(VecT(a + b));\n    auto a_minus_b = a - b;\n    Stranspose.block<3, 1>(0, 0) = a_minus_b;\n    Stranspose.block<3, 3>(0, 1) = skew_a_plus_b;\n    Stranspose.block<3, 1>(3, 0) = a_prime - b_prime;\n    Stranspose.block<3, 3>(3, 1) = skew(VecT(a_prime + b_prime));\n    Stranspose.block<3, 1>(3, 4) = a_minus_b;\n    Stranspose.block<3, 3>(3, 5) = skew_a_plus_b;\n\n    return Stranspose;\n}\n\n/// Reorganize data to prepare for running SVD\n/// Daniilidis 1999 Section 6, Equations (31) and (33), on page 291\n// @pre no zero rotations, thus (rvec1.norm() != 0 && rvec2.norm() != 0) == true\ntemplate <typename T>\nstatic Eigen::MatrixXd AxisAngleToSTransposeBlockOfT(\n    const Eigen::Matrix<T, 3, 1>& rvec1, const Eigen::Matrix<T, 3, 1>& tvec1,\n    const Eigen::Matrix<T, 3, 1>& rvec2, const Eigen::Matrix<T, 3, 1>& tvec2) {\n    double theta1, d1;\n    Eigen::Vector3d l1, m1;\n    AngleAxisAndTranslationToScrew(rvec1, tvec1, theta1, d1, l1, m1);\n\n    double theta2, d2;\n    Eigen::Vector3d l2, m2;\n    AngleAxisAndTranslationToScrew(rvec2, tvec2, theta2, d2, l2, m2);\n\n    Eigen::Vector3d a = l1;\n    Eigen::Vector3d a_prime = m1;\n    Eigen::Vector3d b = l2;\n    Eigen::Vector3d b_prime = m2;\n\n    return ScrewToStransposeBlockofT(a, a_prime, b, b_prime);\n}\n\n// docs in header\nvoid HandEyeCalibration::estimateHandEyeScrew(\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& rvecs1,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& tvecs1,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& rvecs2,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& tvecs2,\n    Eigen::Matrix4d& H_12, bool planarMotion) {\n    int motionCount = rvecs1.size();\n    Eigen::MatrixXd T(motionCount * 6, 8);\n    T.setZero();\n\n    for (size_t i = 0; i < motionCount; ++i) {\n        const Eigen::Vector3d& rvec1 = rvecs1.at(i);\n        const Eigen::Vector3d& tvec1 = tvecs1.at(i);\n        const Eigen::Vector3d& rvec2 = rvecs2.at(i);\n        const Eigen::Vector3d& tvec2 = tvecs2.at(i);\n\n        // Skip cases with zero rotation\n        if (rvec1.norm() == 0 || rvec2.norm() == 0)\n            continue;\n\n        T.block<6, 8>(i * 6, 0) =\n            AxisAngleToSTransposeBlockOfT(rvec1, tvec1, rvec2, tvec2);\n    }\n\n    auto dq = estimateHandEyeScrewInitial(T, planarMotion);\n\n    H_12 = dq.toMatrix();\n    if (mVerbose) {\n        std::cout << \"# INFO: Before refinement: H_12 = \" << std::endl;\n        std::cout << H_12 << std::endl;\n    }\n\n    estimateHandEyeScrewRefine(dq, rvecs1, tvecs1, rvecs2, tvecs2);\n\n    H_12 = dq.toMatrix();\n    if (mVerbose) {\n        std::cout << \"# INFO: After refinement: H_12 = \" << std::endl;\n        std::cout << H_12 << std::endl;\n    }\n}\n\n// docs in header\nvoid HandEyeCalibration::estimateHandEyeScrew(\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& rvecs1,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& tvecs1,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& rvecs2,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& tvecs2,\n    Eigen::Matrix4d& H_12, ceres::Solver::Summary& summary, bool planarMotion) {\n    int motionCount = rvecs1.size();\n    Eigen::MatrixXd T(motionCount * 6, 8);\n    T.setZero();\n\n    for (size_t i = 0; i < motionCount; ++i) {\n        const Eigen::Vector3d& rvec1 = rvecs1.at(i);\n        const Eigen::Vector3d& tvec1 = tvecs1.at(i);\n        const Eigen::Vector3d& rvec2 = rvecs2.at(i);\n        const Eigen::Vector3d& tvec2 = tvecs2.at(i);\n\n        // Skip cases with zero rotation\n        if (rvec1.norm() == 0 || rvec2.norm() == 0)\n            continue;\n\n        T.block<6, 8>(i * 6, 0) =\n            AxisAngleToSTransposeBlockOfT(rvec1, tvec1, rvec2, tvec2);\n    }\n\n    auto dq = estimateHandEyeScrewInitial(T, planarMotion);\n\n    H_12 = dq.toMatrix();\n    if (mVerbose) {\n        std::cout << \"# INFO: Before refinement: H_12 = \" << std::endl;\n        std::cout << H_12 << std::endl;\n    }\n\n    estimateHandEyeScrewRefine(dq, rvecs1, tvecs1, rvecs2, tvecs2, summary);\n\n    H_12 = dq.toMatrix();\n    if (mVerbose) {\n        std::cout << \"# INFO: After refinement: H_12 = \" << std::endl;\n        std::cout << H_12 << std::endl;\n    }\n}\n\n// docs in header\nDualQuaterniond\nHandEyeCalibration::estimateHandEyeScrewInitial(Eigen::MatrixXd& T,\n                                                bool planarMotion) {\n\n    // dq(r1, t1) = dq * dq(r2, t2) * dq.inv\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(T, Eigen::ComputeFullU |\n                                                 Eigen::ComputeFullV);\n\n    // v7 and v8 span the null space of T, v6 may also be one\n    // if rank = 5.\n    Eigen::Matrix<double, 8, 1> v6 = svd.matrixV().block<8, 1>(0, 5);\n    Eigen::Matrix<double, 8, 1> v7 = svd.matrixV().block<8, 1>(0, 6);\n    Eigen::Matrix<double, 8, 1> v8 = svd.matrixV().block<8, 1>(0, 7);\n\n    // if rank = 5\n    if (planarMotion) //(rank == 5)\n    {\n        if (mVerbose) {\n            std::cout\n                << \"# INFO: No unique solution, returned an arbitrary one. \"\n                << std::endl;\n        }\n\n        v7 += v6;\n    }\n\n    Eigen::Vector4d u1 = v7.block<4, 1>(0, 0);\n    Eigen::Vector4d v1 = v7.block<4, 1>(4, 0);\n    Eigen::Vector4d u2 = v8.block<4, 1>(0, 0);\n    Eigen::Vector4d v2 = v8.block<4, 1>(4, 0);\n\n    double lambda1 = 0;\n    double lambda2 = 0.0;\n\n    if (u1.dot(v1) == 0.0) {\n        std::swap(u1, u2);\n        std::swap(v1, v2);\n    }\n    if (u1.dot(v1) != 0.0) {\n        double s[2];\n        solveQuadraticEquation(u1.dot(v1), u1.dot(v2) + u2.dot(v1), u2.dot(v2),\n                               s[0], s[1]);\n\n        // find better solution for s\n        double t[2];\n        for (int i = 0; i < 2; ++i) {\n            t[i] =\n                s[i] * s[i] * u1.dot(u1) + 2 * s[i] * u1.dot(u2) + u2.dot(u2);\n        }\n\n        int idx;\n        if (t[0] > t[1]) {\n            idx = 0;\n        } else {\n            idx = 1;\n        }\n\n        double discriminant =\n            4.0 * square(u1.dot(u2)) - 4.0 * (u1.dot(u1) * u2.dot(u2));\n        if (discriminant == 0.0 && mVerbose) {\n            //            std::cout << \"# INFO: Noise-free case\" << std::endl;\n        }\n\n        lambda2 = sqrt(1.0 / t[idx]);\n        lambda1 = s[idx] * lambda2;\n    } else {\n        if (u1.norm() == 0 && u2.norm() > 0) {\n            lambda1 = 0;\n            lambda2 = 1.0 / u2.norm();\n        } else if (u2.norm() == 0 && u1.norm() > 0) {\n            lambda1 = 1.0 / u1.norm();\n            lambda2 = 0;\n        } else {\n            std::ostringstream ss;\n\n            ss << \"camodocal::HandEyeCalibration error: normalization could \"\n                  \"not be handled. Your rotations and translations are \"\n                  \"probably either not aligned or not passed in properly.\";\n            ss << \"u1:\" << std::endl;\n            ss << u1 << std::endl;\n            ss << \"v1:\" << std::endl;\n            ss << v1 << std::endl;\n            ss << \"u2:\" << std::endl;\n            ss << u2 << std::endl;\n            ss << \"v2:\" << std::endl;\n            ss << v2 << std::endl;\n            ss << \"Not handled yet. Your rotations and translations are \"\n                  \"probably either not aligned or not passed in properly.\"\n               << std::endl;\n\n            BOOST_THROW_EXCEPTION(std::runtime_error(ss.str()));\n        }\n    }\n\n    // rotation\n    Eigen::Vector4d q_coeffs = lambda1 * u1 + lambda2 * u2;\n    Eigen::Vector4d q_prime_coeffs = lambda1 * v1 + lambda2 * v2;\n\n    Eigen::Quaterniond q(q_coeffs(0), q_coeffs(1), q_coeffs(2), q_coeffs(3));\n    Eigen::Quaterniond d(q_prime_coeffs(0), q_prime_coeffs(1),\n                         q_prime_coeffs(2), q_prime_coeffs(3));\n\n    return DualQuaterniond(q, d);\n}\n\n// docs in header\nbool HandEyeCalibration::solveQuadraticEquation(double a, double b, double c,\n                                                double& x1, double& x2) {\n    double delta2 = b * b - 4.0 * a * c;\n\n    if (delta2 < 0.0) {\n        return false;\n    }\n\n    double delta = sqrt(delta2);\n\n    x1 = (-b + delta) / (2.0 * a);\n    x2 = (-b - delta) / (2.0 * a);\n\n    return true;\n}\n\n// docs in header\nvoid HandEyeCalibration::estimateHandEyeScrewRefine(\n    DualQuaterniond& dq,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& rvecs1,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& tvecs1,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& rvecs2,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& tvecs2,\n    ceres::Solver::Summary& summary) {\n    Eigen::Matrix4d H = dq.toMatrix();\n    double p[7] = {dq.real().w(), dq.real().x(), dq.real().y(), dq.real().z(),\n                   H(0, 3),       H(1, 3),       H(2, 3)};\n\n    ceres::Problem problem;\n    for (size_t i = 0; i < rvecs1.size(); i++) {\n        // ceres deletes the objects allocated here for the user\n        ceres::CostFunction* costFunction =\n            new ceres::AutoDiffCostFunction<PoseError, 1, 4, 3>(\n                new PoseError(rvecs1[i], tvecs1[i], rvecs2[i], tvecs2[i]));\n\n        problem.AddResidualBlock(costFunction, NULL, p, p + 4);\n    }\n\n    // ceres deletes the object allocated here for the user\n    ceres::LocalParameterization* quaternionParameterization =\n        new ceres::QuaternionParameterization;\n\n    problem.SetParameterization(p, quaternionParameterization);\n\n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_QR;\n    options.jacobi_scaling = true;\n    options.max_num_iterations = 500;\n\n    // ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n\n    if (mVerbose) {\n        std::cout << summary.BriefReport() << std::endl;\n    }\n\n    Eigen::Quaterniond q(p[0], p[1], p[2], p[3]);\n    Eigen::Vector3d t;\n    t << p[4], p[5], p[6];\n    dq = DualQuaterniond(q, t);\n}\n\nvoid HandEyeCalibration::estimateHandEyeScrewRefine(\n    DualQuaterniond& dq,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& rvecs1,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& tvecs1,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& rvecs2,\n    const std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>& tvecs2) {\n    Eigen::Matrix4d H = dq.toMatrix();\n    double p[7] = {dq.real().w(), dq.real().x(), dq.real().y(), dq.real().z(),\n                   H(0, 3),       H(1, 3),       H(2, 3)};\n    ceres::Solver::Summary summary;\n\n    ceres::Problem problem;\n    for (size_t i = 0; i < rvecs1.size(); i++) {\n        // ceres deletes the objects allocated here for the user\n        ceres::CostFunction* costFunction =\n            new ceres::AutoDiffCostFunction<PoseError, 1, 4, 3>(\n                new PoseError(rvecs1[i], tvecs1[i], rvecs2[i], tvecs2[i]));\n\n        problem.AddResidualBlock(costFunction, NULL, p, p + 4);\n    }\n\n    // ceres deletes the object allocated here for the user\n    ceres::LocalParameterization* quaternionParameterization =\n        new ceres::QuaternionParameterization;\n\n    problem.SetParameterization(p, quaternionParameterization);\n\n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_QR;\n    options.jacobi_scaling = true;\n    options.max_num_iterations = 500;\n\n    // ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n\n    if (mVerbose) {\n        std::cout << summary.BriefReport() << std::endl;\n    }\n\n    Eigen::Quaterniond q(p[0], p[1], p[2], p[3]);\n    Eigen::Vector3d t;\n    t << p[4], p[5], p[6];\n    dq = DualQuaterniond(q, t);\n}\n}\n", "meta": {"hexsha": "a13a614ddeaa5a8b8cb5e500cb85859147372cde", "size": 14401, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/camodocal/calib/HandEyeCalibration.cc", "max_stars_repo_name": "HViktorTsoi/handeye_calib_camodocal", "max_stars_repo_head_hexsha": "fade5271b9f6b94bbe83cef607af803fbad68802", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-10T08:40:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T15:22:07.000Z", "max_issues_repo_path": "src/camodocal/calib/HandEyeCalibration.cc", "max_issues_repo_name": "xiezhihua001/handeye_calib_camodocal", "max_issues_repo_head_hexsha": "2073c770ee8b45428862bacd6d80a23761aa1d83", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-04-10T14:02:57.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-10T14:02:57.000Z", "max_forks_repo_path": "src/camodocal/calib/HandEyeCalibration.cc", "max_forks_repo_name": "xiezhihua001/handeye_calib_camodocal", "max_forks_repo_head_hexsha": "2073c770ee8b45428862bacd6d80a23761aa1d83", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-15T15:30:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-15T15:30:58.000Z", "avg_line_length": 34.45215311, "max_line_length": 80, "alphanum_fraction": 0.5773210194, "num_tokens": 4444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5383804616774067}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// df.hpp                                                                    //\n//                                                                           //\n//  Copyright 2010 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_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_INDEPENDENCE_DF_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_INDEPENDENCE_DF_HPP_ER_2010\n#include <boost/mpl/detail/wrapper.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/cells/cells_count.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/common/df_formula.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/lost_df.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/tag.hpp>\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace contingency_table{\nnamespace pearson_chisq_statistic{\n\n  \ttemplate<typename Keys,typename AccSet>\n    long degrees_of_freedom(\n        const boost::mpl::detail::wrapper<\n            pearson_chisq_statistic::tag::independence_between<Keys>\n        >& statistic,    \n        const AccSet& acc\n    )\n    {\n        namespace ns = contingency_table;\n        return pearson_chisq_statistic::degrees_of_freedom<long>(\n            ns::cells_count<Keys>( acc ),\n            pearson_chisq_statistic::lost_degrees_of_freedom( statistic, acc )\n        );\n    }\n\n}// pearson_chisq_statistic\n}// contingency_table\n}// detail\n}// statistics\n}// boost\n\n#endif\n\n", "meta": {"hexsha": "57821d200bec1034e3e2528153ca0aee15f3c996", "size": 1933, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/pearson_chisq/independence/df.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": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/pearson_chisq/independence/df.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": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/pearson_chisq/independence/df.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.9555555556, "max_line_length": 106, "alphanum_fraction": 0.6332126229, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.538380450981057}}
{"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//[tiernan_girth_circumference\n#include <iostream>\n\n#include <boost/graph/directed_graph.hpp>\n#include <boost/graph/tiernan_all_cycles.hpp>\n\n#include \"helper.hpp\"\n\nusing namespace std;\nusing namespace boost;\n\n// Declare the graph type and its vertex and edge types.\ntypedef directed_graph<> Graph;\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef graph_traits<Graph>::edge_descriptor Edge;\n\nint\nmain(int argc, char *argv[])\n{\n    // Create the graph and read it from standard input.\n    Graph g;\n    read_graph(g, cin);\n\n    // Compute the girth and circumference simulataneously\n    size_t girth, circ;\n    tie(girth, circ) = tiernan_girth_and_circumference(g);\n\n    // Print the result\n    cout << \"girth: \" << girth << endl;\n    cout << \"circumference: \" << circ << endl;\n\n    return 0;\n}\n//]\n", "meta": {"hexsha": "06a996ab21fad850ef7461691ca97533e1eef413", "size": 1029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/tiernan_girth_circumference.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": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T10:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-08T10:44:28.000Z", "max_issues_repo_path": "libs/graph/example/tiernan_girth_circumference.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/tiernan_girth_circumference.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T05:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T05:20:43.000Z", "avg_line_length": 25.0975609756, "max_line_length": 61, "alphanum_fraction": 0.7191448008, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5383443143322134}}
{"text": "#pragma once\n\n#include <Eigen/Sparse>\n#include <cassert>\n#include <algorithm>\n#include <ostream>\n\n\ntemplate <typename Scalar>\nusing VectorX = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n\ntemplate <typename Scalar>\nusing MatrixX = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n\nnamespace detail\n{\n    template <typename Scalar, typename Index>\n    Eigen::VectorXi submatrix_sparsity_pattern(const Eigen::SparseMatrix<Scalar, 0, Index> & matrix,\n                                               const std::vector<Index> & reverse_rowmap,\n                                               const std::vector<Index> & cols)\n    {\n        typedef typename Eigen::SparseMatrix<Scalar, 0, Index>::InnerIterator InnerIterator;\n        const auto submat_cols = static_cast<Index>(cols.size());\n\n        // Each entry in the vector holds the number of non-zero rows in the column\n        Eigen::VectorXi sparsity_pattern(submat_cols);\n\n        for (Index col = 0; col < submat_cols; ++col)\n        {\n            sparsity_pattern(col) = 0;\n            const auto original_col = cols[col];\n\n            for (InnerIterator it(matrix, original_col); it; ++it)\n            {\n                const auto submatrix_row = reverse_rowmap[it.row()];\n                if (submatrix_row >= 0)\n                {\n                    sparsity_pattern(col) += 1;\n                }\n            }\n        }\n\n        return sparsity_pattern;\n    }\n}\n\ntemplate <typename Scalar, typename Index>\nEigen::SparseMatrix<Scalar, 0, Index> sparse_submatrix(const Eigen::SparseMatrix<Scalar, 0, Index> & matrix,\n                                                       const std::vector<Index> & rows,\n                                                       const std::vector<Index> & cols)\n{\n    typedef typename Eigen::SparseMatrix<Scalar, 0, Index>::InnerIterator InnerIterator;\n    assert(std::is_sorted(rows.cbegin(), rows.cend()) && \"Row indices must be sorted.\");\n    assert(std::is_sorted(cols.cbegin(), cols.cend()) && \"Column indices must be sorted.\");\n\n    // rows and cols map indices from the submatrix into the original matrix. We want to build a reverse map,\n    // which is generally not surjective, hence we denote elements that should not be present by -1.\n    std::vector<Index> reverse_rowmap(matrix.rows(), -1);\n\n    for (size_t submatrix_row = 0; submatrix_row < rows.size(); ++submatrix_row)\n    {\n        const auto original_row = rows[submatrix_row];\n        reverse_rowmap[original_row] = submatrix_row;\n    }\n\n    const auto submat_rows = static_cast<Index>(rows.size());\n    const auto submat_cols = static_cast<Index>(cols.size());\n\n    Eigen::SparseMatrix<Scalar, 0, Index> submat(submat_rows, submat_cols);\n    if (submat_rows == 0 || submat_cols == 0)\n    {\n        return submat;\n    }\n\n    submat.reserve(detail::submatrix_sparsity_pattern(matrix, reverse_rowmap, cols));\n\n    for (Index col = 0; col < submat.cols(); ++col)\n    {\n        const auto original_col = cols[col];\n\n        // We implicitly make the assumption here that the original matrix's columns are relatively sparse,\n        // which is almost always the case.\n        for (InnerIterator it(matrix, original_col); it; ++it)\n        {\n            const auto submatrix_row = reverse_rowmap[it.row()];\n            if (submatrix_row >= 0)\n            {\n                submat.insert(submatrix_row, col) = it.value();\n            }\n        }\n    }\n\n    submat.makeCompressed();\n    return submat;\n};\n\ntemplate <typename Scalar, typename Index>\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> sparse_submatrix_as_dense(\n        const Eigen::SparseMatrix<Scalar, 0, Index> & matrix,\n        const std::vector<Index> & rows,\n        const std::vector<Index> & cols)\n{\n    typedef typename Eigen::SparseMatrix<Scalar, 0, Index>::InnerIterator InnerIterator;\n    assert(std::is_sorted(rows.cbegin(), rows.cend()) && \"Row indices must be sorted.\");\n    assert(std::is_sorted(cols.cbegin(), cols.cend()) && \"Column indices must be sorted.\");\n\n    const auto submat_rows = static_cast<Index>(rows.size());\n    const auto submat_cols = static_cast<Index>(cols.size());\n\n    Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> submat(submat_rows, submat_cols);\n    submat.setZero();\n\n    if (submat_rows > 0)\n    {\n        for (Index col = 0; col < submat.cols(); ++col)\n        {\n            const auto original_col = cols[col];\n            Index current_submat_row = 0;\n\n            InnerIterator it(matrix, original_col);\n\n            for (InnerIterator it(matrix, original_col); it; ++it) {\n                while (current_submat_row < submat_rows && it.row() > rows[current_submat_row]) {\n                    ++current_submat_row;\n                }\n\n                if (current_submat_row < submat_rows && it.row() == rows[current_submat_row]) {\n                    submat(current_submat_row, col) = it.value();\n                }\n            }\n        }\n    }\n\n    return submat;\n};\n\ntemplate <typename Scalar, int Rows, int Cols>\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> submatrix(const Eigen::Matrix<Scalar, Rows, Cols> &matrix,\n                                                                const std::vector<int> rows,\n                                                                const std::vector<int> cols)\n{\n    assert(std::is_sorted(rows.cbegin(), rows.cend()) && \"Row indices must be sorted\");\n    assert(std::is_sorted(cols.cbegin(), cols.cend()) && \"Col indices must be sorted\");\n\n    Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> result(rows.size(), cols.size());\n\n    for (size_t j = 0; j < cols.size(); ++j)\n    {\n        for (size_t i = 0; i < rows.size(); ++i)\n        {\n            const int row = static_cast<int>(rows[i]);\n            const int col = static_cast<int>(cols[j]);\n            result(i, j) = matrix(row, col);\n        }\n    }\n\n    return result;\n};\n", "meta": {"hexsha": "e1ff48b308e64ccb8bcb43a7832a9b4b8c2f3dd6", "size": 5863, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crest/util/eigen_extensions.hpp", "max_stars_repo_name": "Andlon/crest", "max_stars_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_stars_repo_licenses": ["MIT"], "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/crest/util/eigen_extensions.hpp", "max_issues_repo_name": "Andlon/crest", "max_issues_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-01-24T10:45:27.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-27T16:21:37.000Z", "max_forks_repo_path": "include/crest/util/eigen_extensions.hpp", "max_forks_repo_name": "Andlon/crest", "max_forks_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_forks_repo_licenses": ["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.8742138365, "max_line_length": 112, "alphanum_fraction": 0.5903121269, "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5383443095596322}}
{"text": "#include \"visualizer.h\"\n#include \"mesh.h\"\n#include \"subdiv_evaluator.h\"\n#include \"fitting_functor.h\"\n\n#include <Eigen/Eigen>\n#include <Open3D/Open3D.h>\n\n#include <iostream>\n#include <random>\n#include \"timer.h\"\n\nusing Vector2d = Eigen::Vector2d;\nusing Vector3d = Eigen::Vector3d;\n\n// creates a mesh using given parameters, and evaluates points on the surface\nstd::vector<Vector3d> evaluate_parametric_mesh(const Vector3d scale, const Vector3d &translation, const std::vector<SurfacePoint> &sps)\n{\n    Mesh mesh = Mesh::create_sphere();\n    mesh.transform(scale, translation);\n    SubdivEvaluator evaluator(mesh);\n    SurfaceFeatures sf(sps.size());\n    evaluator.evaluate_subdiv_surface(mesh.vertices(), sps, sf, false);\n    return sf.S;\n}\n\nstd::vector<SurfacePoint> offset_gt_correspondences(const Mesh &mesh, const std::vector<SurfacePoint> &sps_gt)\n{\n    std::vector<SurfacePoint> sps{sps_gt};\n    SubdivEvaluator evaluator{mesh};\n\n    std::random_device rd;\n    std::mt19937 random_generator(rd());\n    std::normal_distribution<double> dist_offset(0.0, 3.0);\n    for (auto &sp : sps)\n    {\n        Vector2d du = {dist_offset(random_generator), dist_offset(random_generator)};\n        FittingFunctor::update_surface_point(mesh, evaluator, sp.face, sp.u, du);\n    }\n\n    return sps;\n}\n\nvoid print_vector_in_single_line(const std::string &param_name, const Eigen::VectorXd &param)\n{\n    std::cout << param_name << \": [\";\n    for (int i{0}; i < param.size(); ++i)\n    {\n        std::cout << param(i);\n        if (i != param.size() - 1)\n            std::cout << \", \";\n    }\n    std::cout << \"]\\n\";\n}\n\nint main()\n{\n    // for drawing various geometries in 1 window\n    Visualizer visualizer;\n\n    // template mesh\n    Mesh template_mesh{Mesh::create_sphere()};\n    // visualizer.add_mesh(template_mesh.tri_mesh);\n\n    // groundtruth parameters\n    const Vector3d scale_gt{2, 1.5, 1.0};\n    const Vector3d translation_gt{1.0, 2.0, 3.0};\n    const int n_data{100};\n    const std::vector<SurfacePoint> sps_gt = SurfacePoint::generate(n_data, template_mesh.n_triangles());\n\n    // generate data with groundtruth parameters\n    std::vector<Vector3d> points_observed = evaluate_parametric_mesh(scale_gt, translation_gt, sps_gt);\n    visualizer.add_point_cloud(points_observed, {0, 0, 1});\n\n    // init parameters\n    Vector3d scale_init{1., 1., 1.};\n    Vector3d translation_init{0.0, 0, 0};\n    Mesh mesh{Mesh::create_sphere()};\n    mesh.transform(scale_init, translation_init);\n    visualizer.add_mesh(mesh.tri_mesh);\n\n    // init correspondences\n    std::vector<SurfacePoint> sps_init = offset_gt_correspondences(mesh, sps_gt);\n    std::vector<Vector3d> points_init = evaluate_parametric_mesh(scale_init, translation_init, sps_init);\n    // visualizer.add_point_cloud(points_init, {1, 0, 0});\n\n    // optimize\n    FittingFunctor::InputType params(scale_init, translation_init, sps_init);\n    FittingFunctor fitting_functor(std::make_shared<std::vector<Vector3d>>(points_observed), mesh, template_mesh, &visualizer);\n    Eigen::LevenbergMarquardt<FittingFunctor> lm(fitting_functor);\n    lm.setVerbose(true);\n    lm.setMaxfev(10);\n    Timer timer;\n    Eigen::LevenbergMarquardtSpace::Status info = lm.minimize(params);\n    std::cout << \"\\nOptimization took \" << timer.elapsed() << \"s\\n\";\n\n    // log\n    std::cout << \"\\nGroundtruth\\n\";\n    print_vector_in_single_line(\"Scale\", scale_gt);\n    print_vector_in_single_line(\"Translation\", translation_gt);\n\n    std::cout << \"\\nInitial\\n\";\n    print_vector_in_single_line(\"Scale\", scale_init);\n    print_vector_in_single_line(\"Translation\", translation_init);\n\n    std::cout << \"\\nOptimized\\n\";\n    print_vector_in_single_line(\"Scale\", params.scale);\n    print_vector_in_single_line(\"Translation\", params.translation);\n\n    // hold visualizer\n    std::cout << \"\\nPress `q` to close visualizer window\\n\";\n    visualizer.run();\n\n    return 0;\n}", "meta": {"hexsha": "eefaa219fe13170bead4955c0d9ab91908b2f077", "size": 3880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fit_sphere.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": "src/fit_sphere.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": "src/fit_sphere.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": 33.7391304348, "max_line_length": 135, "alphanum_fraction": 0.699742268, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5383443075135977}}
{"text": "//\r\n// $Id$ \r\n//\r\n// Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>\r\n// Copyright 2011 Vanderbilt University\r\n//\r\n// Licensed under the Code Project Open License, Version 1.02 (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.codeproject.com/info/cpol10.aspx\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 \"pwiz/utility/misc/unit.hpp\"\r\n#include \"pwiz/utility/misc/Std.hpp\"\r\n#include <boost/accumulators/statistics/stats.hpp>\r\n#include <boost/accumulators/framework/accumulator_set.hpp>\r\n#include \"percentile.hpp\"\r\n\r\nusing namespace pwiz::util;\r\nusing namespace boost::accumulators;\r\n\r\nvoid test()\r\n{\r\n    // tested at http://www.wessa.net\r\n\r\n    accumulator_set<double, stats<tag::percentile> > acc;\r\n    const double epsilon = 1e-6;\r\n\r\n    acc(10);\r\n    unit_assert_equal(10, percentile(acc, percentile_number = 25), epsilon);\r\n    unit_assert_equal(10, percentile(acc, percentile_number = 50), epsilon);\r\n    unit_assert_equal(10, percentile(acc, percentile_number = 75), epsilon);\r\n\r\n    acc(30);\r\n    unit_assert_equal(15, percentile(acc, percentile_number = 25), epsilon);\r\n    unit_assert_equal(20, percentile(acc, percentile_number = 50), epsilon);\r\n    unit_assert_equal(25, percentile(acc, percentile_number = 75), epsilon);\r\n\r\n    acc(20);\r\n    unit_assert_equal(15, percentile(acc, percentile_number = 25), epsilon);\r\n    unit_assert_equal(20, percentile(acc, percentile_number = 50), epsilon);\r\n    unit_assert_equal(25, percentile(acc, percentile_number = 75), epsilon);\r\n\r\n    acc(40);\r\n    unit_assert_equal(17.5, percentile(acc, percentile_number = 25), epsilon);\r\n    unit_assert_equal(25, percentile(acc, percentile_number = 50), epsilon);\r\n    unit_assert_equal(32.5, percentile(acc, percentile_number = 75), epsilon);\r\n\r\n    acc(50);\r\n    unit_assert_equal(20, percentile(acc, percentile_number = 25), epsilon);\r\n    unit_assert_equal(30, percentile(acc, percentile_number = 50), epsilon);\r\n    unit_assert_equal(40, percentile(acc, percentile_number = 75), epsilon);\r\n\r\n    acc(60);\r\n    unit_assert_equal(22.5, percentile(acc, percentile_number = 25), epsilon);\r\n    unit_assert_equal(35, percentile(acc, percentile_number = 50), epsilon);\r\n    unit_assert_equal(47.5, percentile(acc, percentile_number = 75), epsilon);\r\n\r\n    acc(80);\r\n    unit_assert_equal(25, percentile(acc, percentile_number = 25), epsilon);\r\n    unit_assert_equal(40, percentile(acc, percentile_number = 50), epsilon);\r\n    unit_assert_equal(55, percentile(acc, percentile_number = 75), epsilon);\r\n\r\n    acc(35);\r\n    unit_assert_equal(27.5, percentile(acc, percentile_number = 25), epsilon);\r\n    unit_assert_equal(37.5, percentile(acc, percentile_number = 50), epsilon);\r\n    unit_assert_equal(52.5, percentile(acc, percentile_number = 75), epsilon);\r\n\r\n    acc(77); acc(88); acc(99); acc(100);\r\n    unit_assert_equal(21, percentile(acc, percentile_number = 10), epsilon);\r\n    unit_assert_equal(31, percentile(acc, percentile_number = 20), epsilon);\r\n    unit_assert_equal(36.5, percentile(acc, percentile_number = 30), epsilon);\r\n    unit_assert_equal(44, percentile(acc, percentile_number = 40), epsilon);\r\n    unit_assert_equal(55, percentile(acc, percentile_number = 50), epsilon);\r\n    unit_assert_equal(70.2, percentile(acc, percentile_number = 60), epsilon);\r\n    unit_assert_equal(79.1, percentile(acc, percentile_number = 70), epsilon);\r\n    unit_assert_equal(86.4, percentile(acc, percentile_number = 80), epsilon);\r\n    unit_assert_equal(97.9, percentile(acc, percentile_number = 90), epsilon);\r\n}\r\n\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n    TEST_PROLOG(argc, argv)\r\n\r\n    try\r\n    {\r\n        test();\r\n    }\r\n    catch (exception& e)\r\n    {\r\n        TEST_FAILED(e.what())\r\n    }\r\n    catch (...)\r\n    {\r\n        TEST_FAILED(\"Caught unknown exception.\")\r\n    }\r\n\r\n    TEST_EPILOG\r\n}\r\n", "meta": {"hexsha": "600591c6cf458162e27ee0b75d7d871989cb5a30", "size": 4220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz_tools/Bumbershoot/freicore/percentile_test.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_tools/Bumbershoot/freicore/percentile_test.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_tools/Bumbershoot/freicore/percentile_test.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": 38.7155963303, "max_line_length": 80, "alphanum_fraction": 0.6981042654, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5383443075135977}}
{"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/** \\example mtl4-with-viennacl.cpp\n*\n*   This tutorial shows how data can be directly transferred from the <a href=\"http://www.mtl4.org/\">MTL4 Library</a> to ViennaCL objects using the built-in convenience wrappers.\n*\n*   The first step is to include the necessary headers and activate the MTL4 convenience functions in ViennaCL:\n**/\n\n// System headers\n#include <iostream>\n\n\n// MTL4 headers\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\n\n// Must be set prior to any ViennaCL includes if you want to use ViennaCL algorithms on MTL4 objects\n#define VIENNACL_WITH_MTL4 1\n\n\n// ViennaCL headers\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n\n#include \"viennacl/linalg/ilu.hpp\"\n#include \"viennacl/linalg/cg.hpp\"\n#include \"viennacl/linalg/bicgstab.hpp\"\n#include \"viennacl/linalg/gmres.hpp\"\n\n\n// Some helper functions for this tutorial:\n#include \"Random.hpp\"\n#include \"vector-io.hpp\"\n#include \"../benchmarks/benchmark-utils.hpp\"\n\n/**\n*    The following function contains the main code for this tutorial.\n*    It consists of the following steps:\n*      - Creates MTL4 matrices and vectors\n*      - Initializes them with data\n*      - Create ViennaCL objects\n*      - Copy them over to the respective ViennaCL objects\n*      - Compute matrix-vector products in both MTL4 and ViennaCL and compare results.\n*\n**/\ntemplate<typename ScalarType>\nvoid run_tutorial()\n{\n  typedef mtl::dense2D<ScalarType>        MTL4DenseMatrix;\n  typedef mtl::compressed2D<ScalarType>   MTL4SparseMatrix;\n\n  /**\n  * Create and fill dense matrices from the MTL4 library:\n  **/\n  mtl::dense2D<ScalarType>   mtl4_densemat(5, 5);\n  mtl::dense2D<ScalarType>   mtl4_densemat2(5, 5);\n  mtl4_densemat(0,0) = 2.0;   mtl4_densemat(0,1) = -1.0;\n  mtl4_densemat(1,0) = -1.0;  mtl4_densemat(1,1) =  2.0;  mtl4_densemat(1,2) = -1.0;\n  mtl4_densemat(2,1) = -1.0;  mtl4_densemat(2,2) = -1.0;  mtl4_densemat(2,3) = -1.0;\n  mtl4_densemat(3,2) = -1.0;  mtl4_densemat(3,3) =  2.0;  mtl4_densemat(3,4) = -1.0;\n                              mtl4_densemat(4,4) = -1.0;  mtl4_densemat(4,4) = -1.0;\n\n\n  /**\n  * Create and fill sparse matrices from the MTL4 library:\n  **/\n  MTL4SparseMatrix mtl4_sparsemat;\n  set_to_zero(mtl4_sparsemat);\n  mtl4_sparsemat.change_dim(5, 5);\n\n  MTL4SparseMatrix mtl4_sparsemat2;\n  set_to_zero(mtl4_sparsemat2);\n  mtl4_sparsemat2.change_dim(5, 5);\n\n  {\n    mtl::matrix::inserter< MTL4SparseMatrix >  ins(mtl4_sparsemat);\n    typedef typename mtl::Collection<MTL4SparseMatrix>::value_type  ValueType;\n    ins(0,0) <<  ValueType(2.0);   ins(0,1) << ValueType(-1.0);\n    ins(1,1) <<  ValueType(2.0);   ins(1,2) << ValueType(-1.0);\n    ins(2,2) << ValueType(-1.0);   ins(2,3) << ValueType(-1.0);\n    ins(3,3) <<  ValueType(2.0);   ins(3,4) << ValueType(-1.0);\n    ins(4,4) << ValueType(-1.0);\n  }\n\n  /**\n  * Create and fill a few vectors from the MTL4 library:\n  **/\n  mtl::dense_vector<ScalarType> mtl4_rhs(5, 0.0);\n  mtl::dense_vector<ScalarType> mtl4_result(5, 0.0);\n  mtl::dense_vector<ScalarType> mtl4_temp(5, 0.0);\n\n\n  mtl4_rhs(0) = 10.0;\n  mtl4_rhs(1) = 11.0;\n  mtl4_rhs(2) = 12.0;\n  mtl4_rhs(3) = 13.0;\n  mtl4_rhs(4) = 14.0;\n\n  /**\n  * Create the corresponding ViennaCL objects:\n  **/\n  viennacl::vector<ScalarType> vcl_rhs(5);\n  viennacl::vector<ScalarType> vcl_result(5);\n  viennacl::matrix<ScalarType> vcl_densemat(5, 5);\n  viennacl::compressed_matrix<ScalarType> vcl_sparsemat(5, 5);\n\n  /**\n  * Directly copy the MTL4 objects to ViennaCL objects\n  **/\n  viennacl::copy(&(mtl4_rhs[0]), &(mtl4_rhs[0]) + 5, vcl_rhs.begin());  //method 1: via iterator interface (cf. std::copy())\n  viennacl::copy(mtl4_rhs, vcl_rhs);  //method 2: via built-in wrappers (convenience layer)\n\n  viennacl::copy(mtl4_densemat, vcl_densemat);\n  viennacl::copy(mtl4_sparsemat, vcl_sparsemat);\n\n  // For completeness: Copy matrices from ViennaCL back to Eigen:\n  viennacl::copy(vcl_densemat, mtl4_densemat2);\n  viennacl::copy(vcl_sparsemat, mtl4_sparsemat2);\n\n  /**\n  * Run dense matrix-vector products and compare results:\n  **/\n  mtl4_result = mtl4_densemat * mtl4_rhs;\n  vcl_result = viennacl::linalg::prod(vcl_densemat, vcl_rhs);\n  viennacl::copy(vcl_result, mtl4_temp);\n  mtl4_result -= mtl4_temp;\n  std::cout << \"Difference for dense matrix-vector product: \" << mtl::two_norm(mtl4_result) << std::endl;\n  mtl4_result = mtl4_densemat2 * mtl4_rhs - mtl4_temp;\n  std::cout << \"Difference for dense matrix-vector product (MTL4->ViennaCL->MTL4): \"\n            << mtl::two_norm(mtl4_result) << std::endl;\n\n  /**\n  * Run sparse matrix-vector products and compare results:\n  **/\n  mtl4_result = mtl4_sparsemat * mtl4_rhs;\n  vcl_result = viennacl::linalg::prod(vcl_sparsemat, vcl_rhs);\n  viennacl::copy(vcl_result, mtl4_temp);\n  mtl4_result -= mtl4_temp;\n  std::cout << \"Difference for sparse matrix-vector product: \" << mtl::two_norm(mtl4_result) << std::endl;\n  mtl4_result = mtl4_sparsemat2 * mtl4_rhs - mtl4_temp;\n  std::cout << \"Difference for sparse matrix-vector product (MTL4->ViennaCL->MTL4): \"\n            << mtl::two_norm(mtl4_result) << std::endl;\n\n}\n\n\n/**\n*   In the main() routine we only call the worker function defined above with both single and double precision arithmetic.\n**/\nint main(int, char *[])\n{\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << \"## Single precision\" << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  run_tutorial<float>();\n\n#ifdef VIENNACL_HAVE_OPENCL\n  if ( viennacl::ocl::current_device().double_support() )\n#endif\n  {\n    std::cout << \"----------------------------------------------\" << std::endl;\n    std::cout << \"## Double precision\" << std::endl;\n    std::cout << \"----------------------------------------------\" << std::endl;\n    run_tutorial<double>();\n  }\n\n  /**\n  *   That's it. Print a success message and exit.\n  **/\n  std::cout << std::endl;\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n  std::cout << std::endl;\n}\n", "meta": {"hexsha": "d7318198bc38e5861e8a95545e922e877e302547", "size": 6793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/mtl4-with-viennacl.cpp", "max_stars_repo_name": "ddemidov/viennacl-dev", "max_stars_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-08-23T17:05:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-23T17:06:24.000Z", "max_issues_repo_path": "examples/tutorial/mtl4-with-viennacl.cpp", "max_issues_repo_name": "ddemidov/viennacl-dev", "max_issues_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_issues_repo_licenses": ["MIT"], "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/mtl4-with-viennacl.cpp", "max_forks_repo_name": "ddemidov/viennacl-dev", "max_forks_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_forks_repo_licenses": ["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.1968911917, "max_line_length": 178, "alphanum_fraction": 0.6300603562, "num_tokens": 2055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5383443075135977}}
{"text": "#include \"ale/Rotation.h\"\n\n#include <exception>\n\n#include <Eigen/Geometry>\n\n#include \"ale/InterpUtils.h\"\n\nnamespace ale {\n\n///////////////////////////////////////////////////////////////////////////////\n// Helper Functions\n///////////////////////////////////////////////////////////////////////////////\n\n\n  // Helper function to convert an axis number into a unit Eigen vector down that axis.\n  Eigen::Vector3d axis(int axisIndex) {\n    switch (axisIndex) {\n      case 0:\n        return Eigen::Vector3d::UnitX();\n        break;\n      case 1:\n        return Eigen::Vector3d::UnitY();\n        break;\n      case 2:\n        return Eigen::Vector3d::UnitZ();\n        break;\n      default:\n        throw std::invalid_argument(\"Axis index must be 0, 1, or 2.\");\n    }\n  }\n\n\n  /**\n   * Create the skew symmetric matrix used when computing the derivative of a\n   * rotation matrix.\n   *\n   * This is actually the transpose of the skew AV matrix because we define AV\n   * as the AV from the destination to the source. This matches how NAIF\n   * defines AV.\n   */\n  Eigen::Quaterniond::Matrix3 avSkewMatrix(const Vec3d& av) {\n    Eigen::Quaterniond::Matrix3 avMat;\n    avMat <<  0.0,    av.z, -av.y,\n             -av.z,  0.0,    av.x,\n              av.y, -av.x,  0.0;\n    return avMat;\n  }\n\n  ///////////////////////////////////////////////////////////////////////////////\n  // Rotation Impl class\n  ///////////////////////////////////////////////////////////////////////////////\n\n  // Internal representation of the rotation as an Eigen Double Quaternion\n  class Rotation::Impl {\n    public:\n      Impl() : quat(Eigen::Quaterniond::Identity()) { }\n\n\n      Impl(double w, double x, double y, double z) : quat(w, x, y, z) { }\n\n\n      Impl(const std::vector<double>& matrix) {\n        if (matrix.size() != 9) {\n          throw std::invalid_argument(\"Rotation matrix must be 3 by 3.\");\n        }\n        quat = Eigen::Quaterniond(Eigen::Quaterniond::Matrix3(matrix.data()));\n      }\n\n\n      Impl(const std::vector<double>& angles, const std::vector<int>& axes) {\n        if (angles.empty() || axes.empty()) {\n          throw std::invalid_argument(\"Angles and axes must be non-empty.\");\n        }\n        if (angles.size() != axes.size()) {\n          throw std::invalid_argument(\"Number of angles and axes must be equal.\");\n        }\n        quat = Eigen::Quaterniond::Identity();\n\n        for (size_t i = 0; i < angles.size(); i++) {\n          quat *= Eigen::Quaterniond(Eigen::AngleAxisd(angles[i], axis(axes[i])));\n        }\n      }\n\n\n      Impl(const std::vector<double>& axis, double theta) {\n        if (axis.size() != 3) {\n          throw std::invalid_argument(\"Rotation axis must have 3 elements.\");\n        }\n        Eigen::Vector3d eigenAxis((double *) axis.data());\n        quat = Eigen::Quaterniond(Eigen::AngleAxisd(theta, eigenAxis.normalized()));\n      }\n\n\n      Eigen::Quaterniond quat;\n  };\n\n  ///////////////////////////////////////////////////////////////////////////////\n  // Rotation Class\n  ///////////////////////////////////////////////////////////////////////////////\n\n  Rotation::Rotation() :\n        m_impl(new Impl()) { }\n\n\n  Rotation::Rotation(double w, double x, double y, double z) :\n        m_impl(new Impl(w, x, y, z)) { }\n\n\n  Rotation::Rotation(const std::vector<double>& matrix) :\n        m_impl(new Impl(matrix)) { }\n\n\n  Rotation::Rotation(const std::vector<double>& angles, const std::vector<int>& axes) :\n        m_impl(new Impl(angles, axes)) { }\n\n\n  Rotation::Rotation(const std::vector<double>& axis, double theta) :\n        m_impl(new Impl(axis, theta)) { }\n\n\n  Rotation::~Rotation() = default;\n\n\n  Rotation::Rotation(Rotation && other) noexcept = default;\n\n\n  Rotation& Rotation::operator=(Rotation && other) noexcept = default;\n\n\n  // unique_ptr doesn't have a copy constructor so we have to define one\n  Rotation::Rotation(const Rotation& other) : m_impl(new Impl(*other.m_impl)) { }\n\n\n  // unique_ptr doesn't have an assignment operator so we have to define one\n  Rotation& Rotation::operator=(const Rotation& other) {\n    if (this != &other) {\n      m_impl.reset(new Impl(*other.m_impl));\n    }\n    return *this;\n  }\n\n\n  std::vector<double> Rotation::toQuaternion() const {\n    Eigen::Quaterniond normalized = m_impl->quat.normalized();\n    return {normalized.w(), normalized.x(), normalized.y(), normalized.z()};\n  }\n\n\n  std::vector<double> Rotation::toRotationMatrix() const {\n    Eigen::Quaterniond::RotationMatrixType mat = m_impl->quat.toRotationMatrix();\n    return std::vector<double>(mat.data(), mat.data() + mat.size());\n  }\n\n\n  std::vector<double> Rotation::toStateRotationMatrix(const Vec3d &av) const {\n    Eigen::Quaterniond::Matrix3 rotMat = m_impl->quat.toRotationMatrix();\n    Eigen::Quaterniond::Matrix3 avMat = avSkewMatrix(av);\n    Eigen::Quaterniond::Matrix3 dtMat = rotMat * avMat;\n    return {rotMat(0,0), rotMat(0,1), rotMat(0,2), 0.0,         0.0,         0.0,\n            rotMat(1,0), rotMat(1,1), rotMat(1,2), 0.0,         0.0,         0.0,\n            rotMat(2,0), rotMat(2,1), rotMat(2,2), 0.0,         0.0,         0.0,\n            dtMat(0,0),  dtMat(0,1),  dtMat(0,2),  rotMat(0,0), rotMat(0,1), rotMat(0,2),\n            dtMat(1,0),  dtMat(1,1),  dtMat(1,2),  rotMat(1,0), rotMat(1,1), rotMat(1,2),\n            dtMat(2,0),  dtMat(2,1),  dtMat(2,2),  rotMat(2,0), rotMat(2,1), rotMat(2,2)};\n  }\n\n\n  std::vector<double> Rotation::toEuler(const std::vector<int>& axes) const {\n    if (axes.size() != 3) {\n      throw std::invalid_argument(\"Must have 3 axes to convert to Euler angles.\");\n    }\n    if (axes[0] < 0 || axes[0] > 2 ||\n        axes[1] < 0 || axes[1] > 2 ||\n        axes[2] < 0 || axes[2] > 2) {\n      throw std::invalid_argument(\"Invalid axis number.\");\n    }\n    Eigen::Vector3d angles = m_impl->quat.toRotationMatrix().eulerAngles(\n          axes[0],\n          axes[1],\n          axes[2]);\n    return std::vector<double>(angles.data(), angles.data() + angles.size());\n  }\n\n\n  std::pair<std::vector<double>, double> Rotation::toAxisAngle() const {\n    Eigen::AngleAxisd eigenAxisAngle(m_impl->quat);\n    std::pair<std::vector<double>, double> axisAngle;\n    axisAngle.first = std::vector<double>(\n          eigenAxisAngle.axis().data(),\n          eigenAxisAngle.axis().data() + eigenAxisAngle.axis().size()\n    );\n    axisAngle.second = eigenAxisAngle.angle();\n    return axisAngle;\n  }\n\n\n  Vec3d Rotation::operator()(const Vec3d &vector) const {\n    Eigen::Vector3d eigenVector(vector.x, vector.y, vector.z);\n    Eigen::Vector3d rotatedVector = m_impl->quat._transformVector(eigenVector);\n    std::vector<double> tempVec = std::vector<double>(rotatedVector.data(), rotatedVector.data() + rotatedVector.size());\n    return Vec3d(tempVec);\n  }\n\n  State Rotation::operator()(\n        const State& state,\n        const Vec3d& av\n  ) const {\n    Vec3d position = state.position;\n    Vec3d velocity = state.velocity;\n\n    Eigen::Vector3d positionVector(position.x, position.y, position.z);\n    Eigen::Vector3d velocityVector(velocity.x, velocity.y, velocity.z);\n    Eigen::Quaterniond::Matrix3 rotMat = m_impl->quat.toRotationMatrix();\n    Eigen::Quaterniond::Matrix3 avMat = avSkewMatrix(av);\n    Eigen::Quaterniond::Matrix3 rotationDerivative = rotMat * avMat;\n    Eigen::Vector3d rotatedPosition = rotMat * positionVector;\n    Eigen::Vector3d rotatedVelocity = rotMat * velocityVector + rotationDerivative * positionVector;\n\n    return State({rotatedPosition(0), rotatedPosition(1), rotatedPosition(2),\n                  rotatedVelocity(0), rotatedVelocity(1), rotatedVelocity(2)});\n  }\n\n\n  Rotation Rotation::inverse() const {\n    Eigen::Quaterniond inverseQuat = m_impl->quat.inverse();\n    return Rotation(inverseQuat.w(), inverseQuat.x(), inverseQuat.y(), inverseQuat.z());\n  }\n\n\n  Rotation Rotation::operator*(const Rotation& rightRotation) const {\n    Eigen::Quaterniond combinedQuat = m_impl->quat * rightRotation.m_impl->quat;\n    return Rotation(combinedQuat.w(), combinedQuat.x(), combinedQuat.y(), combinedQuat.z());\n  }\n\n\n  Rotation Rotation::interpolate(\n        const Rotation& nextRotation,\n        double t,\n        RotationInterpolation interpType\n  ) const {\n    Eigen::Quaterniond interpQuat;\n    switch (interpType) {\n      case SLERP:\n        interpQuat = m_impl->quat.slerp(t, nextRotation.m_impl->quat);\n        break;\n      case NLERP:\n        interpQuat = Eigen::Quaterniond(\n              linearInterpolate(m_impl->quat.w(), nextRotation.m_impl->quat.w(), t),\n              linearInterpolate(m_impl->quat.x(), nextRotation.m_impl->quat.x(), t),\n              linearInterpolate(m_impl->quat.y(), nextRotation.m_impl->quat.y(), t),\n              linearInterpolate(m_impl->quat.z(), nextRotation.m_impl->quat.z(), t)\n        );\n        interpQuat.normalize();\n        break;\n      default:\n        throw std::invalid_argument(\"Unsupported rotation interpolation type.\");\n        break;\n    }\n    return Rotation(interpQuat.w(), interpQuat.x(), interpQuat.y(), interpQuat.z());\n  }\n\n}\n", "meta": {"hexsha": "031726c21a6b797ffced6593491bdc8f919662b5", "size": 8977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Rotation.cpp", "max_stars_repo_name": "kberryUSGS/SpiceRefactor", "max_stars_repo_head_hexsha": "1875bf6c873f084296004397ecf8f90ee5df7cef", "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/Rotation.cpp", "max_issues_repo_name": "kberryUSGS/SpiceRefactor", "max_issues_repo_head_hexsha": "1875bf6c873f084296004397ecf8f90ee5df7cef", "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/Rotation.cpp", "max_forks_repo_name": "kberryUSGS/SpiceRefactor", "max_forks_repo_head_hexsha": "1875bf6c873f084296004397ecf8f90ee5df7cef", "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": 34.0037878788, "max_line_length": 121, "alphanum_fraction": 0.590397683, "num_tokens": 2272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5383306195453846}}
{"text": "#include <iostream>\r\n#include <armadillo>\r\n\r\nusing namespace std;\r\nusing namespace arma;\r\n\r\nvoid\r\nSavePPM(const char*filename)\r\n{\r\n    cube c=randi<cube>(100,100,3, distr_param(0,255));\r\n    c.save(filename,ppm_binary);\r\n}\r\n\r\n", "meta": {"hexsha": "3484f620e311a5ae20b0f5670aa655ce5d851af6", "size": 226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Shell/RunRoot/ArmaDemo/save_ppm.cpp", "max_stars_repo_name": "wurui1994/test", "max_stars_repo_head_hexsha": "027cef75f98dbb252b322113dacd4a9a6997d84f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-12-19T09:15:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-30T13:02:00.000Z", "max_issues_repo_path": "Shell/RunRoot/ArmaDemo/save_ppm.cpp", "max_issues_repo_name": "wurui1994/test", "max_issues_repo_head_hexsha": "027cef75f98dbb252b322113dacd4a9a6997d84f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Shell/RunRoot/ArmaDemo/save_ppm.cpp", "max_forks_repo_name": "wurui1994/test", "max_forks_repo_head_hexsha": "027cef75f98dbb252b322113dacd4a9a6997d84f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2018-04-10T13:25:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T01:51:03.000Z", "avg_line_length": 16.1428571429, "max_line_length": 55, "alphanum_fraction": 0.6769911504, "num_tokens": 60, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5383306184071348}}
{"text": "// This example compiles with C++11.\n// C++11 and higher don't need the StdVector include (as mentioned inside the\n// include itself).\n//#include <Eigen/StdVector>\n// If we use C++17 there is no need to take care of memory alignment:\n// https://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html\n#include <pico_toolshed/scoped_timer.hpp>\n#include <pico_tree/eigen.hpp>\n#include <pico_tree/kd_tree.hpp>\n\n// Important! The Eigen example is not a performance benchmark. So don't take\n// the \"elapsed time\" numbers too seriously.\n\nusing Index = int;\n\ntemplate <typename Point>\nusing PointsMapCm = Eigen::Map<\n    Eigen::Matrix<\n        typename Point::Scalar,\n        Point::RowsAtCompileTime,\n        Eigen::Dynamic>,\n    Eigen::AlignedMax>;\n// The alignment used by Eigen equals Eigen::AlignedMax. Note that Eigen can\n// look at the data pointer to know if it is properly aligned.\n\ntemplate <typename Point>\nusing PointsMapRm = Eigen::Map<\n    Eigen::Matrix<\n        typename Point::Scalar,\n        Eigen::Dynamic,\n        Point::ColsAtCompileTime,\n        Eigen::RowMajor>,\n    Eigen::AlignedMax>;\n\nstd::size_t const kRunCount = 1024 * 1024;\nint const kNumPoints = 1024 * 1024 * 2;\nfloat const kArea = 1000.0;\nIndex const kMaxLeafCount = 16;\n\n// Certain fixed size matrices require us to use aligned memory.\n// https://eigen.tuxfamily.org/dox-devel/group__TopicFixedSizeVectorizable.html\ntemplate <typename PointX>\nstd::vector<PointX, Eigen::aligned_allocator<PointX>> GenerateRandomEigenN(\n    int n, typename PointX::Scalar size) {\n  std::vector<PointX, Eigen::aligned_allocator<PointX>> random(n);\n  for (auto& p : random) {\n    p = PointX::Random() * size / typename PointX::Scalar(2.0);\n  }\n\n  return random;\n}\n\n// Creates a KdTree from a vector of Eigen::VectorX and searches for nearest\n// neighbors.\nvoid BasicVector() {\n  using PointX = Eigen::Vector2f;\n  using Scalar = typename PointX::Scalar;\n\n  // Including <pico_tree/eigen.hpp> provides support for Eigen types with\n  // std::vector.\n  pico_tree::KdTree<pico_tree::StdTraits<\n      std::vector<PointX, Eigen::aligned_allocator<PointX>>>>\n      tree(GenerateRandomEigenN<PointX>(kNumPoints, kArea), kMaxLeafCount);\n\n  PointX p = PointX::Random() * kArea / Scalar(2.0);\n\n  pico_tree::Neighbor<Index, Scalar> nn;\n  ScopedTimer t(\"pico_tree eigen vector\", kRunCount);\n  for (std::size_t i = 0; i < kRunCount; ++i) {\n    tree.SearchNn(p, &nn);\n  }\n}\n\n// Creates a KdTree from an Eigen::Matrix<> and searches for nearest neighbors.\nvoid BasicMatrix() {\n  using Scalar = typename Eigen::Matrix3Xf::Scalar;\n  constexpr int Dim = Eigen::Matrix3Xf::RowsAtCompileTime;\n\n  Eigen::Vector3f p = Eigen::Vector3f::Random() * kArea / Scalar(2.0);\n\n  // The KdTree takes the matrix by value. Prevent a copy by:\n  // * Using a move.\n  // * Creating an Eigen::Map<>.\n  // * Wrap with an std::reference_wrapper<>.\n  {\n    pico_tree::KdTree<pico_tree::EigenTraits<Eigen::Matrix3Xf>> tree(\n        Eigen::Matrix3Xf::Random(Dim, kNumPoints) * kArea / Scalar(2.0),\n        kMaxLeafCount);\n\n    pico_tree::Neighbor<Index, Scalar> nn;\n    ScopedTimer t(\"pico_tree eigen val\", kRunCount);\n    for (std::size_t i = 0; i < kRunCount; ++i) {\n      tree.SearchNn(p, &nn);\n    }\n  }\n\n  {\n    Eigen::Matrix3Xf matrix =\n        Eigen::Matrix3Xf::Random(Dim, kNumPoints) * kArea / Scalar(2.0);\n\n    pico_tree::KdTree<\n        pico_tree::EigenTraits<std::reference_wrapper<Eigen::Matrix3Xf>>>\n        tree(matrix, kMaxLeafCount);\n\n    pico_tree::Neighbor<Index, Scalar> nn;\n    ScopedTimer t(\"pico_tree eigen ref\", kRunCount);\n    for (std::size_t i = 0; i < kRunCount; ++i) {\n      tree.SearchNn(p, &nn);\n    }\n  }\n}\n\n// Creates a KdTree from a col-major matrix. The matrix maps an\n// std::vector<Eigen::Vector3f>.\nvoid VectorMapColMajor() {\n  using PointX = Eigen::Vector3f;\n  using Scalar = typename PointX::Scalar;\n  constexpr int Dim = PointX::RowsAtCompileTime;\n  using Map = PointsMapCm<PointX>;\n\n  auto points = GenerateRandomEigenN<PointX>(kNumPoints, kArea);\n  PointX p = PointX::Random() * kArea / Scalar(2.0);\n\n  std::cout << \"Eigen RowMajor: \" << Map::IsRowMajor << std::endl;\n  {\n    pico_tree::KdTree<pico_tree::EigenTraits<Map>> tree(\n        Map(points.data()->data(), Dim, points.size()), kMaxLeafCount);\n\n    std::vector<pico_tree::Neighbor<Index, Scalar>> knn;\n    ScopedTimer t(\"pico_tree deflt l2\", kRunCount);\n    for (std::size_t i = 0; i < kRunCount; ++i) {\n      tree.SearchKnn(p, 1, &knn);\n    }\n  }\n}\n\n// Creates a KdTree from a row-major matrix. The matrix maps an\n// std::vector<Eigen::RowVector3f>.\nvoid VectorMapRowMajor() {\n  using PointX = Eigen::RowVector3f;\n  using Scalar = typename PointX::Scalar;\n  constexpr int Dim = PointX::ColsAtCompileTime;\n  using Map = PointsMapRm<PointX>;\n\n  auto points = GenerateRandomEigenN<PointX>(kNumPoints, kArea);\n  PointX p = PointX::Random() * kArea / Scalar(2.0);\n\n  std::cout << \"Eigen RowMajor: \" << PointX::IsRowMajor << std::endl;\n\n  {\n    pico_tree::KdTree<pico_tree::EigenTraits<Map>> tree(\n        Map(points.data()->data(), points.size(), Dim), kMaxLeafCount);\n\n    std::vector<pico_tree::Neighbor<Index, Scalar>> knn;\n    ScopedTimer t(\"pico_tree deflt l2\", kRunCount);\n    for (std::size_t i = 0; i < kRunCount; ++i) {\n      tree.SearchKnn(p, 1, &knn);\n    }\n  }\n}\n\n// The Metrics demo shows how it can be beneficial to use the metrics supplied\n// by the <pico_tree/eigen.hpp> header.\n//\n// Suppose we want to use a KdTree with a spatial dimension of 3 using floats as\n// a scalar. In this case we can use Eigen::Vector3f as the data type. However,\n// Eigen::Vector3f doesn't benefit from vectorization. With Eigen::Vector4f we\n// can, but in this case we have one dimension too many!\n//\n// Luckily, it is possible use a different dimension for both the points and the\n// KdTree, but some care needs to be taken:\n// * The default Metrics don't make explicit use of vectorization (perhaps\n// implicitly through optimization by the compiler) but the Eigen based Metrics\n// may do so.\n// * The extra coordinate of Eigen::Vector4f must be set 0 so it doesn't\n// influence any of the distance calculations. E.g., the squared distance uses a\n// dot product.\n//\n// See also:\n// http://eigen.tuxfamily.org/index.php?title=UsingVector4fForVector3fOperations\nvoid Metrics() {\n  // Eigen::Vector4f requires aligned memory.\n  using PointX = Eigen::Vector4f;\n  using Scalar = typename PointX::Scalar;\n  using Map = PointsMapCm<PointX>;\n  // Tell the KdTree to use a spatial dimension of 3 instead of 4.\n  constexpr int Dim = PointX::RowsAtCompileTime - 1;\n\n  auto points = GenerateRandomEigenN<PointX>(kNumPoints, kArea);\n  // The Eigen::Map uses the dimension of 4.\n  Map map(points.data()->data(), PointX::RowsAtCompileTime, points.size());\n  // Set the last row (4th coordinate) to 0.\n  map.bottomRows<1>().setZero();\n\n  PointX p = PointX::Random() * kArea / Scalar(2.0);\n  // Again, set the last row (4th coordinate) to 0.\n  p.w() = Scalar(0.0);\n\n  std::cout << \"Eigen Metrics: \" << std::endl;\n\n  {\n    // Using an std::reference_wrapper prevents a copy.\n    using Traits = pico_tree::StdTraits<std::reference_wrapper<\n        std::vector<PointX, Eigen::aligned_allocator<PointX>>>>;\n\n    pico_tree::KdTree<\n        Traits,\n        pico_tree::EigenL2Squared<Scalar>,\n        pico_tree::SplitterSlidingMidpoint<Traits>,\n        Dim>\n        tree(points, kMaxLeafCount);\n\n    std::vector<pico_tree::Neighbor<Index, Scalar>> knn;\n    ScopedTimer t(\"pico_tree eigen l2\", kRunCount);\n    for (std::size_t i = 0; i < kRunCount; ++i) {\n      tree.SearchKnn(p, 1, &knn);\n    }\n  }\n\n  {\n    // Using an Eigen::Map prevents a copy.\n    using Traits = pico_tree::EigenTraits<Map>;\n\n    pico_tree::KdTree<\n        Traits,\n        pico_tree::EigenL1<Scalar>,\n        pico_tree::SplitterSlidingMidpoint<Traits>,\n        Dim>\n        tree(map, kMaxLeafCount);\n\n    std::vector<pico_tree::Neighbor<Index, Scalar>> knn;\n    ScopedTimer t(\"pico_tree eigen l1\", kRunCount);\n    for (std::size_t i = 0; i < kRunCount; ++i) {\n      tree.SearchKnn(p, 1, &knn);\n    }\n  }\n}\n\nint main() {\n  BasicVector();\n  BasicMatrix();\n  VectorMapColMajor();\n  VectorMapRowMajor();\n  Metrics();\n  return 0;\n}\n", "meta": {"hexsha": "60651543a437a63cca39c5c847043679021d52b7", "size": 8192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/eigen/eigen.cpp", "max_stars_repo_name": "Jaybro/pico_tree", "max_stars_repo_head_hexsha": "c6f7fb798b60452add7d0e940c4a7737cd72a992", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2020-07-19T23:03:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T15:06:26.000Z", "max_issues_repo_path": "examples/eigen/eigen.cpp", "max_issues_repo_name": "Jaybro/pico_tree", "max_issues_repo_head_hexsha": "c6f7fb798b60452add7d0e940c4a7737cd72a992", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-26T16:53:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-26T23:20:54.000Z", "max_forks_repo_path": "examples/eigen/eigen.cpp", "max_forks_repo_name": "Jaybro/pico_tree", "max_forks_repo_head_hexsha": "c6f7fb798b60452add7d0e940c4a7737cd72a992", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-04T14:03:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T05:36:40.000Z", "avg_line_length": 33.1659919028, "max_line_length": 80, "alphanum_fraction": 0.6796875, "num_tokens": 2361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5383306184071348}}
{"text": "//\n// SPDX-License-Identifier: BSD-3-Clause\n// Copyright Contributors to the OpenEXR Project.\n//\n\n// clang-format off\n\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/format.hpp>\n#include <boost/python/make_constructor.hpp>\n#include \"PyImath.h\"\n#include \"PyImathMathExc.h\"\n#include \"PyImathFixedArray.h\"\n#include \"PyImathRandom.h\"\n#include \"PyImathDecorators.h\"\n\nnamespace PyImath{\nusing namespace boost::python;\n\ntemplate <class Rand, class T>\nstatic T\nnextf2 (Rand &rand, T min, T max)\n{\n    MATH_EXC_ON;\n    return rand.nextf(min, max);\n}\n\ntemplate <class Rand>\nstatic float\nnextGauss (Rand &rand)\n{\n    MATH_EXC_ON;\n    return gaussRand(rand);\n}\n\ntemplate <class T, class Rand>\nstatic IMATH_NAMESPACE::Vec3<T> nextGaussSphere(Rand &rand, const IMATH_NAMESPACE::Vec3<T> &v)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::gaussSphereRand<IMATH_NAMESPACE::Vec3<T>,Rand>(rand);\n}\ntemplate <class T, class Rand>\nstatic IMATH_NAMESPACE::Vec2<T> nextGaussSphere(Rand &rand, const IMATH_NAMESPACE::Vec2<T> &v)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::gaussSphereRand<IMATH_NAMESPACE::Vec2<T>,Rand>(rand);\n}\n\ntemplate <class T, class Rand>\nstatic IMATH_NAMESPACE::Vec3<T> nextHollowSphere(Rand &rand, const IMATH_NAMESPACE::Vec3<T> &v)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::hollowSphereRand<IMATH_NAMESPACE::Vec3<T>,Rand>(rand);\n}\n\ntemplate <class T, class Rand>\nstatic IMATH_NAMESPACE::Vec2<T> nextHollowSphere(Rand &rand, const IMATH_NAMESPACE::Vec2<T> &v)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::hollowSphereRand<IMATH_NAMESPACE::Vec2<T>,Rand>(rand);\n}\n\ntemplate <class T, class Rand>\nstatic IMATH_NAMESPACE::Vec3<T> nextSolidSphere(Rand &rand, const IMATH_NAMESPACE::Vec3<T> &v)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::solidSphereRand<IMATH_NAMESPACE::Vec3<T>,Rand>(rand);\n}\n\ntemplate <class T, class Rand>\nstatic IMATH_NAMESPACE::Vec2<T> nextSolidSphere(Rand &rand, const IMATH_NAMESPACE::Vec2<T> &v)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::solidSphereRand<IMATH_NAMESPACE::Vec2<T>,Rand>(rand);\n}\n\ntemplate <class Rand>\nstatic Rand *Rand_constructor1(unsigned long int seed)\n{\n    return new Rand(seed);\n}\n\ntemplate <class Rand>\nstatic Rand *Rand_constructor2(Rand rand)\n{\n    Rand *r = new Rand();\n    *r = rand;\n    \n    return r;\n}\n\ntemplate <class T, class Rand>\nstatic PyImath::FixedArray<IMATH_NAMESPACE::Vec3<T> >\nhollowSphereRand(Rand &rand, int num)\n{\n    MATH_EXC_ON;\n    PyImath::FixedArray<IMATH_NAMESPACE::Vec3<T> >  retval(num);\n    for (int i=0; i<num; ++i) {\n        retval[i] = IMATH_NAMESPACE::hollowSphereRand<IMATH_NAMESPACE::Vec3<T>,Rand>(rand);\n    }\n    return retval;\n}\n\ntemplate <class T, class Rand>\nstatic PyImath::FixedArray<IMATH_NAMESPACE::Vec3<T> >\nsolidSphereRand(Rand &rand, int num)\n{\n    MATH_EXC_ON;\n    PyImath::FixedArray<IMATH_NAMESPACE::Vec3<T> >  retval(num);\n    for (int i=0; i<num; ++i) {\n        retval[i] = IMATH_NAMESPACE::solidSphereRand<IMATH_NAMESPACE::Vec3<T>,Rand>(rand);\n    }\n    return retval;\n}\n\nPYIMATH_EXPORT\nclass_<IMATH_NAMESPACE::Rand32>\nregister_Rand32()\n{\n    float (IMATH_NAMESPACE::Rand32::*nextf1)(void) = &IMATH_NAMESPACE::Rand32::nextf;\n    \n    IMATH_NAMESPACE::Vec3<float> (*nextGaussSphere1)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec3<float> &v) = &nextGaussSphere<float,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec3<double> (*nextGaussSphere2)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec3<double> &v) = &nextGaussSphere<double,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec2<float> (*nextGaussSphere3)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec2<float> &v) = &nextGaussSphere<float,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec2<double> (*nextGaussSphere4)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec2<double> &v) = &nextGaussSphere<double,IMATH_NAMESPACE::Rand32>;\n    \n    IMATH_NAMESPACE::Vec3<float> (*nextHollowSphere1)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec3<float> &v) = &nextHollowSphere<float,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec3<double> (*nextHollowSphere2)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec3<double> &v) = &nextHollowSphere<double,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec2<float> (*nextHollowSphere3)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec2<float> &v) = &nextHollowSphere<float,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec2<double> (*nextHollowSphere4)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec2<double> &v) = &nextHollowSphere<double,IMATH_NAMESPACE::Rand32>;\n\n    IMATH_NAMESPACE::Vec3<float> (*nextSolidSphere1)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec3<float> &v) = &nextSolidSphere<float,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec3<double> (*nextSolidSphere2)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec3<double> &v) = &nextSolidSphere<double,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec2<float> (*nextSolidSphere3)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec2<float> &v) = &nextSolidSphere<float,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec2<double> (*nextSolidSphere4)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec2<double> &v) = &nextSolidSphere<double,IMATH_NAMESPACE::Rand32>;\n    \n    class_< IMATH_NAMESPACE::Rand32 > rand32_class(\"Rand32\");\n    rand32_class\n        .def(init<>(\"default construction\"))\n        .def(\"__init__\", make_constructor(Rand_constructor1<IMATH_NAMESPACE::Rand32>))\n        .def(\"__init__\", make_constructor(Rand_constructor2<IMATH_NAMESPACE::Rand32>))\n        .def(\"init\", &IMATH_NAMESPACE::Rand32::init,\n             \"r.init(i) -- initialize with integer \"\n\t\t\t \"seed i\")\n             \n        .def(\"nexti\", &IMATH_NAMESPACE::Rand32::nexti,\n        \t \"r.nexti() -- return the next integer \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\")\n        .def(\"nextf\", nextf1,\n        \t \"r.nextf() -- return the next floating-point \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\\n\"\n             \n        \t \"r.nextf(float, float) -- return the next floating-point \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\")             \n        .def(\"nextf\", &nextf2 <IMATH_NAMESPACE::Rand32, float>)\n             \n        .def(\"nextb\", &IMATH_NAMESPACE::Rand32::nextb,\n\t \t     \"r.nextb() -- return the next boolean \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\")\n\n        .def(\"nextGauss\", &nextGauss<IMATH_NAMESPACE::Rand32>,\n        \t \"r.nextGauss() -- returns the next \"\n\t\t\t \"floating-point value in the normally \"\n\t\t\t \"(Gaussian) distributed sequence\")\n             \n        .def(\"nextGaussSphere\", nextGaussSphere1, \n\t \t\t \"r.nextGaussSphere(v) -- returns the next \"\n\t\t\t \"point whose distance from the origin \"\n\t\t\t \"has a normal (Gaussian) distribution with \"\n\t\t\t \"mean 0 and variance 1.  The vector \"\n\t\t\t \"argument, v, specifies the dimension \"\n\t\t\t \"and number type.\")             \n        .def(\"nextGaussSphere\", nextGaussSphere2)             \n        .def(\"nextGaussSphere\", nextGaussSphere3)             \n        .def(\"nextGaussSphere\", nextGaussSphere4)\n        \n        .def(\"nextHollowSphere\", nextHollowSphere1,\n        \t \"r.nextHollowSphere(v) -- return the next \"\n\t \t\t \"point uniformly distributed on the surface \"\n\t \t\t \"of a sphere of radius 1 centered at the \"\n\t \t\t \"origin.  The vector argument, v, specifies \"\n\t\t\t \"the dimension and number type.\")             \n        .def(\"nextHollowSphere\", nextHollowSphere2)             \n        .def(\"nextHollowSphere\", nextHollowSphere3)             \n        .def(\"nextHollowSphere\", nextHollowSphere4)\n\n        .def(\"nextSolidSphere\", nextSolidSphere1,\n        \t \"r.nextSolidSphere(v) -- return the next \"\n\t\t\t \"point uniformly distributed in a sphere \"\n\t\t\t \"of radius 1 centered at the origin.  The \"\n\t\t\t \"vector argument, v, specifies the \"\n\t\t\t \"dimension and number type.\")             \n        .def(\"nextSolidSphere\", nextSolidSphere2)             \n        .def(\"nextSolidSphere\", nextSolidSphere3)             \n        .def(\"nextSolidSphere\", nextSolidSphere4)    \n        ;\n\n    def(\"hollowSphereRand\",&hollowSphereRand<float,IMATH_NAMESPACE::Rand32>,\"hollowSphereRand(randObj,num) return XYZ vectors uniformly \"\n        \"distributed across the surface of a sphere generated from the given Rand32 object\",\n        args(\"randObj\",\"num\"));\n        \n    def(\"solidSphereRand\",&solidSphereRand<float,IMATH_NAMESPACE::Rand32>,\"solidSphereRand(randObj,num) return XYZ vectors uniformly \"\n        \"distributed through the volume of a sphere generated from the given Rand32 object\",\n        args(\"randObj\",\"num\"));\n\n    decoratecopy(rand32_class);\n\n    return rand32_class;\n}\n\nPYIMATH_EXPORT\nclass_<IMATH_NAMESPACE::Rand48>\nregister_Rand48()\n{\n    double (IMATH_NAMESPACE::Rand48::*nextf1)(void) = &IMATH_NAMESPACE::Rand48::nextf;\n    \n    IMATH_NAMESPACE::Vec3<float> (*nextGaussSphere1)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec3<float> &v) = &nextGaussSphere<float,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec3<double> (*nextGaussSphere2)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec3<double> &v) = &nextGaussSphere<double,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec2<float> (*nextGaussSphere3)(IMATH_NAMESPACE::Rand48&, const IMATH_NAMESPACE::Vec2<float> &v) = &nextGaussSphere<float,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec2<double> (*nextGaussSphere4)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec2<double> &v) = &nextGaussSphere<double,IMATH_NAMESPACE::Rand48>;\n    \n    IMATH_NAMESPACE::Vec3<float> (*nextHollowSphere1)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec3<float> &v) = &nextHollowSphere<float,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec3<double> (*nextHollowSphere2)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec3<double> &v) = &nextHollowSphere<double,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec2<float> (*nextHollowSphere3)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec2<float> &v) = &nextHollowSphere<float,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec2<double> (*nextHollowSphere4)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec2<double> &v) = &nextHollowSphere<double,IMATH_NAMESPACE::Rand48>;\n\n    IMATH_NAMESPACE::Vec3<float> (*nextSolidSphere1)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec3<float> &v) = &nextSolidSphere<float,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec3<double> (*nextSolidSphere2)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec3<double> &v) = &nextSolidSphere<double,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec2<float> (*nextSolidSphere3)(IMATH_NAMESPACE::Rand48&, const IMATH_NAMESPACE::Vec2<float> &v) = &nextSolidSphere<float,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec2<double> (*nextSolidSphere4)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec2<double> &v) = &nextSolidSphere<double,IMATH_NAMESPACE::Rand48>;\n   \n    class_< IMATH_NAMESPACE::Rand48 > rand48_class(\"Rand48\");\n    rand48_class\n        .def(init<>(\"default construction\"))\n        .def(\"__init__\", make_constructor(Rand_constructor1<IMATH_NAMESPACE::Rand48>))\n        .def(\"__init__\", make_constructor(Rand_constructor2<IMATH_NAMESPACE::Rand48>))\n        .def(\"init\", &IMATH_NAMESPACE::Rand48::init,\n             \"r.init(i) -- initialize with integer \"\n\t\t\t \"seed i\")\n             \n        .def(\"nexti\", &IMATH_NAMESPACE::Rand48::nexti,\n        \t \"r.nexti() -- return the next integer \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\")\n             \n        .def(\"nextf\", nextf1,\n        \t \"r.nextf() -- return the next double \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\\n\"\n             \n        \t \"r.nextf(double,double) -- return the next double \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\")             \n        .def(\"nextf\", &nextf2 <IMATH_NAMESPACE::Rand48, double>)\n             \n        .def(\"nextb\", &IMATH_NAMESPACE::Rand48::nextb,\n\t \t     \"r.nextb() -- return the next boolean \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\")\n \n        .def(\"nextGauss\", &nextGauss<IMATH_NAMESPACE::Rand48>,\n        \t \"r.nextGauss() -- returns the next \"\n\t\t\t \"floating-point value in the normally \"\n\t\t\t \"(Gaussian) distributed sequence\")\n             \n        .def(\"nextGaussSphere\", nextGaussSphere1, \n\t \t\t \"r.nextGaussSphere(v) -- returns the next \"\n\t\t\t \"point whose distance from the origin \"\n\t\t\t \"has a normal (Gaussian) distribution with \"\n\t\t\t \"mean 0 and variance 1.  The vector \"\n\t\t\t \"argument, v, specifies the dimension \"\n\t\t\t \"and number type.\")             \n        .def(\"nextGaussSphere\", nextGaussSphere2)             \n        .def(\"nextGaussSphere\", nextGaussSphere3)             \n        .def(\"nextGaussSphere\", nextGaussSphere4)\n        \n        .def(\"nextHollowSphere\", nextHollowSphere1,\n        \t \"r.nextHollowSphere(v) -- return the next \"\n\t \t\t \"point uniformly distributed on the surface \"\n\t \t\t \"of a sphere of radius 1 centered at the \"\n\t \t\t \"origin.  The vector argument, v, specifies \"\n\t\t\t \"the dimension and number type.\")             \n        .def(\"nextHollowSphere\", nextHollowSphere2)             \n        .def(\"nextHollowSphere\", nextHollowSphere3)             \n        .def(\"nextHollowSphere\", nextHollowSphere4)\n\n        .def(\"nextSolidSphere\", nextSolidSphere1,\n        \t \"r.nextSolidSphere(v) -- return the next \"\n\t\t\t \"point uniformly distributed in a sphere \"\n\t\t\t \"of radius 1 centered at the origin.  The \"\n\t\t\t \"vector argument, v, specifies the \"\n\t\t\t \"dimension and number type.\")             \n        .def(\"nextSolidSphere\", nextSolidSphere2)             \n        .def(\"nextSolidSphere\", nextSolidSphere3)             \n        .def(\"nextSolidSphere\", nextSolidSphere4) \n        ;\n\n    decoratecopy(rand48_class);\n\n    return rand48_class;\n}\n\n//\n\nPyObject *\nRand32::wrap (const IMATH_NAMESPACE::Rand32 &r)\n{\n    boost::python::return_by_value::apply <IMATH_NAMESPACE::Rand32>::type converter;\n    PyObject *p = converter (r);\n    return p;\n}\n\nPyObject *\nRand48::wrap (const IMATH_NAMESPACE::Rand48 &r)\n{\n    boost::python::return_by_value::apply <IMATH_NAMESPACE::Rand48>::type converter;\n    PyObject *p = converter (r);\n    return p;\n}\n\n} //namespace PyIMath\n", "meta": {"hexsha": "d2accc633d430f6e2f398065faee7f3f04ff8335", "size": 14163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python/PyImath/PyImathRandom.cpp", "max_stars_repo_name": "JenusL/Imath", "max_stars_repo_head_hexsha": "749a1bfe017b2daccb3eb9759fbe837ea4718a0a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 156.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T06:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:55:55.000Z", "max_issues_repo_path": "src/python/PyImath/PyImathRandom.cpp", "max_issues_repo_name": "JenusL/Imath", "max_issues_repo_head_hexsha": "749a1bfe017b2daccb3eb9759fbe837ea4718a0a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 146.0, "max_issues_repo_issues_event_min_datetime": "2020-06-13T18:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:47:29.000Z", "max_forks_repo_path": "src/python/PyImath/PyImathRandom.cpp", "max_forks_repo_name": "JenusL/Imath", "max_forks_repo_head_hexsha": "749a1bfe017b2daccb3eb9759fbe837ea4718a0a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2020-06-16T18:44:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T20:50:06.000Z", "avg_line_length": 43.3119266055, "max_line_length": 174, "alphanum_fraction": 0.6879192262, "num_tokens": 3801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5383306090314902}}
{"text": "#ifndef SKYLARK_CT_DATA_HPP\n#define SKYLARK_CT_DATA_HPP\n\n#ifndef SKYLARK_SKETCH_HPP\n#error \"Include top-level sketch.hpp instead of including individuals headers\"\n#endif\n\n#include <boost/random.hpp>\n#include <boost/property_tree/ptree.hpp>\n\nnamespace skylark { namespace sketch {\n\nnamespace bstrand = boost::random;\n\n/**\n * Cauchy Transform (data)\n *\n * The CT is simply a dense random matrix with i.i.d Cauchy variables\n */\nstruct CT_data_t :\n   public random_dense_transform_data_t<bstrand::cauchy_distribution> {\n\n    typedef random_dense_transform_data_t<bstrand::cauchy_distribution> base_t;\n\n    /// Params structure\n    struct params_t : public sketch_params_t {\n\n        params_t(double C) : C(C) {\n\n        }\n\n        const double C;\n    };\n\n    CT_data_t(int N, int S, double C, skylark::base::context_t& context)\n        : base_t(N, S, C / static_cast<double>(S),\n            bstrand::cauchy_distribution<double>(),\n            context, \"CT\"), _C(C) {\n\n        context = base_t::build();\n    }\n\n    CT_data_t(int N, int S, const params_t& params,\n        skylark::base::context_t& context)\n        : base_t(N, S, params.C / static_cast<double>(S),\n            bstrand::cauchy_distribution<double>(),\n            context, \"CT\"), _C(params.C) {\n\n        context = base_t::build();\n    }\n\n    CT_data_t(const boost::property_tree::ptree &pt) :\n        base_t(pt.get<int>(\"N\"), pt.get<int>(\"S\"),\n            pt.get<double>(\"C\") / pt.get<double>(\"S\"),\n            bstrand::cauchy_distribution<double>(),\n            base::context_t(pt.get_child(\"creation_context\")), \"CT\"),\n        _C(pt.get<double>(\"C\")) {\n\n        base_t::build();\n    }\n\n    /**\n     *  Serializes a sketch to a string.\n     *\n     *  @param[out] property_tree describing the sketch.\n     */\n    virtual\n    boost::property_tree::ptree to_ptree() const {\n        boost::property_tree::ptree pt;\n        sketch_transform_data_t::add_common(pt);\n        pt.put(\"C\", _C);\n        return pt;\n    }\n\nprotected:\n\n    CT_data_t(int N, int S, double C, const skylark::base::context_t& context, \n        std::string type)\n        : base_t(N, S, C / static_cast<double>(S),\n            bstrand::cauchy_distribution<double>(),\n            context, type), _C(C) {\n\n    }\n\nprivate:\n\n    double _C;\n};\n\n} } /** namespace skylark::sketch */\n\n#endif // SKYLARK_CT_DATA_HPP\n", "meta": {"hexsha": "a1ed22a70bc5dcd1a2606feaa9a6434c1e628793", "size": 2333, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sketch/CT_data.hpp", "max_stars_repo_name": "wangg12/libskylark", "max_stars_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-12T07:26:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T07:26:47.000Z", "max_issues_repo_path": "sketch/CT_data.hpp", "max_issues_repo_name": "cjiyer/libskylark", "max_issues_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "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": "sketch/CT_data.hpp", "max_forks_repo_name": "cjiyer/libskylark", "max_forks_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "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.0860215054, "max_line_length": 79, "alphanum_fraction": 0.6163737677, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.538330603774543}}
{"text": "//\r\n//! Copyright \u00a9 2008-2011\r\n//! Brandon Kohn\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#ifndef GEOMETRIX_UTILITIES_HPP\r\n#define GEOMETRIX_UTILITIES_HPP\r\n#pragma once\r\n\r\n#include <geometrix/numeric/constants.hpp>\r\n#include <geometrix/arithmetic/arithmetic.hpp>\r\n#include <geometrix/tensor/numeric_sequence_compare.hpp>\r\n#include <geometrix/primitive/segment_traits.hpp>\r\n#include <geometrix/arithmetic/vector.hpp>\r\n#include <geometrix/algebra/expression.hpp>\r\n#include <geometrix/algebra/algebra.hpp>\r\n#include <geometrix/algebra/exterior_product.hpp>\r\n#include <boost/concept_check.hpp>\r\n#include <boost/numeric/conversion/cast.hpp>\r\n#include <boost/fusion/include/all.hpp>\r\n#include <geometrix/algorithm/orientation/point_segment_orientation.hpp>\r\n\r\nnamespace geometrix {\r\n\r\n    namespace result_of {\r\n\r\n        template <typename A, typename B>\r\n        struct angle_from_a_to_b\r\n        {\r\n        private:\r\n            typedef decltype(typename type_at<A, 0>::type() - typename type_at<B, 0>::type()) xtype;\r\n            typedef decltype(typename type_at<A, 1>::type() - typename type_at<B, 1>::type()) ytype;\r\n        public:\r\n            typedef decltype(atan2(std::declval<ytype>(), std::declval<xtype>())) type;\r\n        };\r\n\r\n    }//! namespace result_of;\r\n\r\n    //! Function to get the angle from an origin to a target point in the 2D XY plane.\r\n    template <typename CoordinateSequenceA, typename CoordinateSequenceB>\r\n    inline typename result_of::angle_from_a_to_b<CoordinateSequenceA, CoordinateSequenceB>::type\r\n        angle_from_a_to_b( const CoordinateSequenceA& A,\r\n                           const CoordinateSequenceB& B,\r\n                       typename boost::enable_if_c\r\n                       <\r\n                           geometric_traits<CoordinateSequenceA>::dimension_type::value == 2 &&\r\n                           geometric_traits<CoordinateSequenceB>::dimension_type::value == 2\r\n                       > ::type* = 0 )\r\n    {\r\n        using std::atan2;\r\n        return atan2( get<1>( B ) - get<1>( A ), get<0>( B ) - get<0>( A ) );\r\n    }\r\n\r\n    namespace result_of {\r\n\r\n        template <typename Vector>\r\n        struct vector_angle\r\n        {\r\n        private:\r\n            typedef decltype(typename type_at<Vector, 0>::type()) xtype;\r\n            typedef decltype(typename type_at<Vector, 1>::type()) ytype;\r\n        public:\r\n            typedef decltype(atan2(std::declval<ytype>(), std::declval<xtype>())) type;\r\n        };\r\n\r\n    }//! namespace result_of;\r\n\r\n    //! Return the angle in which the specified vector points.\r\n    template <typename Vector>\r\n    inline typename result_of::vector_angle<Vector>::type\r\n        vector_angle(const Vector& v)\r\n    {\r\n        BOOST_CONCEPT_ASSERT((Vector2DConcept<Vector>));\r\n        using std::atan2;\r\n        return atan2(get<1>(v), get<0>(v));\r\n    }\r\n\r\n    //! Function to normalize an angle to within the interval [0,2*PI]\r\n    template <typename CoordinateType>\r\n    inline void normalize_angle_0_2pi(CoordinateType& angle)\r\n    {\r\n        //simplifies the angle to lay in the range of the interval 0 - 2*pi\r\n        CoordinateType twoPI = constants::two_pi<CoordinateType>();\r\n        if (angle > twoPI || angle < constants::zero<CoordinateType>())\r\n        {\r\n            using std::floor;\r\n            auto n = floor(angle / twoPI);\r\n            if (n != constants::zero<decltype(n)>())\r\n                angle -= twoPI * n;\r\n            if (angle > twoPI)\r\n                angle -= twoPI;\r\n            else if (angle < constants::zero<CoordinateType>())\r\n                angle += twoPI;\r\n        }\r\n    }\r\n\r\n    //! Function to normalize a copy of a given angle to within the interval [0,2*PI] and return the normalized value.\r\n    template <typename CoordinateType>\r\n    inline CoordinateType normalize_angle_0_2pi_copy(CoordinateType angle)\r\n    {\r\n        //simplifies the angle to lay in the range of the interval 0 - 2*pi\r\n        normalize_angle_0_2pi(angle);\r\n        return angle;\r\n    }\r\n\r\n    //! Function to normalize an angle to within the interval [-PI,PI]\r\n    template <typename CoordinateType>\r\n    inline void normalize_angle_minus_pi_to_pi( CoordinateType& angle )\r\n    {\r\n        //simplifies the angle to lay in the range of the interval 0 - 2*pi first and then into the -pi,pi range.\r\n        normalize_angle_0_2pi(angle);\r\n\r\n        CoordinateType pi = constants::pi<CoordinateType>();\r\n        CoordinateType twoPI = constants::two_pi<CoordinateType>();\r\n        if( angle > pi )\r\n            angle -= twoPI;\r\n        else if( angle <= geometrix::get(-pi) )\r\n            angle += twoPI;\r\n    }\r\n\r\n    //! Function to normalize a copy of a given angle to within the interval [-PI,PI] and return the normalized value.\r\n    template <typename CoordinateType>\r\n    inline CoordinateType normalize_angle_minus_pi_to_pi_copy( CoordinateType angle )\r\n    {\r\n        //simplifies the angle to lay in the range of the interval 0 - 2*pi        \r\n        normalize_angle_minus_pi_to_pi(angle);\r\n        return angle;\r\n    }\r\n\r\n    //! Function to determine if 3 points are collinear in the 2D XY plane.\r\n    //! From Computational Geometry in C by J. O'Rourke.\r\n    template <typename PointA, typename PointB, typename PointC, typename NumberComparisonPolicy>\r\n    inline bool is_collinear( const PointA& A,\r\n                       const PointB& B,\r\n                       const PointC& C,\r\n                       const NumberComparisonPolicy& compare,\r\n                       typename boost::enable_if_c\r\n                       <\r\n                           geometric_traits<PointA>::dimension_type::value == 2 &&\r\n                           geometric_traits<PointB>::dimension_type::value == 2 &&\r\n                           geometric_traits<PointC>::dimension_type::value == 2\r\n                       > ::type* = 0 )\r\n    {\r\n        auto det = exterior_product_area( B-A, C-A );\r\n        return compare.equals( det, constants::zero<decltype(det)>() );//Absolute tolerance checks are fine for Zero checks.\r\n    }\r\n    \r\n    template <typename PointA, typename PointB, typename PointC, typename NumberComparisonPolicy>\r\n    inline bool is_collinear( const PointA& A,\r\n                       const PointB& B,\r\n                       const PointC& C,\r\n                       const NumberComparisonPolicy& compare,\r\n                       typename boost::enable_if_c\r\n                       <\r\n                           geometric_traits<PointA>::dimension_type::value == 3 &&\r\n                           geometric_traits<PointB>::dimension_type::value == 3 &&\r\n                           geometric_traits<PointC>::dimension_type::value == 3\r\n                       > ::type* = 0 )\r\n    {\r\n        using length_t = typename arithmetic_type_of<PointA>::type;\r\n        using vector_t = vector<length_t, dimension_of<PointA>::value>;\r\n        using cross_result_t = typename result_of::cross_product<vector_t, vector_t>::type;\r\n\t\tauto d = cross_result_t(( B - A ) ^ ( C - A ));\r\n\t\treturn compare.equals( get<0>( d ), constants::zero<typename type_at<cross_result_t, 0>::type>() )\r\n\t\t\t&& compare.equals( get<1>( d ), constants::zero<typename type_at<cross_result_t, 0>::type>() )\r\n\t\t\t&& compare.equals( get<2>( d ), constants::zero<typename type_at<cross_result_t, 0>::type>() );\r\n    }\r\n\r\n    //! Function to determine if Point C is between points A-B\r\n    //! From Computational Geometry in C by J. O'Rourke.\r\n    template <typename PointA, typename PointB, typename PointC, typename NumberComparisonPolicy>\r\n    inline bool is_between( const PointA& A,\r\n                     const PointB& B,\r\n                     const PointC& C,\r\n                     bool includeBounds,\r\n                     const NumberComparisonPolicy& compare,\r\n                     typename boost::enable_if_c\r\n                     <\r\n                        geometric_traits<PointA>::dimension_type::value == 2 &&\r\n                        geometric_traits<PointB>::dimension_type::value == 2 &&\r\n                        geometric_traits<PointC>::dimension_type::value == 2\r\n                     >::type* = 0 )\r\n    {\r\n        return is_collinear( A, B, C, compare ) && is_collinear_point_between( A, B, C, includeBounds, compare );\r\n    }\r\n\r\n    //! Function to determine if Point C is between points A-B where C is already determined to be collinear to A-B.\r\n    //! From Computational Geometry in C by J. O'Rourke.\r\n    template <typename PointA, typename PointB, typename PointC, typename NumberComparisonPolicy>\r\n    inline bool is_collinear_point_between( const PointA& A,\r\n        const PointB& B,\r\n        const PointC& C,\r\n        bool includeBounds,\r\n        const NumberComparisonPolicy& compare,\r\n        typename boost::enable_if_c\r\n        <\r\n        geometric_traits<PointA>::dimension_type::value == 2 &&\r\n        geometric_traits<PointB>::dimension_type::value == 2 &&\r\n        geometric_traits<PointC>::dimension_type::value == 2\r\n        > ::type* = 0 )\r\n    {\r\n        GEOMETRIX_ASSERT( is_collinear( A, B, C, compare ) );\r\n\r\n        //If AB not vertical, check between on x; else on y.\r\n        bool ABVertical = compare.equals( get<0>( A ), get<0>( B ) );\r\n        if( !ABVertical )\r\n        {\r\n            if( includeBounds )\r\n            {\r\n                return ((compare.less_than_or_equal( get<0>( A ), get<0>( C ) ) && compare.less_than_or_equal( get<0>( C ), get<0>( B ) )) ||\r\n                    (compare.greater_than_or_equal( get<0>( A ), get<0>( C ) ) && compare.greater_than_or_equal( get<0>( C ), get<0>( B ) )));\r\n            }\r\n            else\r\n            {\r\n                return ((compare.less_than( get<0>( A ), get<0>( C ) ) && compare.less_than( get<0>( C ), get<0>( B ) )) ||\r\n                    (compare.greater_than( get<0>( A ), get<0>( C ) ) && compare.greater_than( get<0>( C ), get<0>( B ) )));\r\n            }\r\n        }\r\n        else\r\n        {\r\n            if( includeBounds )\r\n            {\r\n                return ((compare.less_than_or_equal( get<1>( A ), get<1>( C ) ) && compare.less_than_or_equal( get<1>( C ), get<1>( B ) )) ||\r\n                    (compare.greater_than_or_equal( get<1>( A ), get<1>( C ) ) && compare.greater_than_or_equal( get<1>( C ), get<1>( B ) )));\r\n            }\r\n            else\r\n            {\r\n                return ((compare.less_than( get<1>( A ), get<1>( C ) ) && compare.less_than( get<1>( C ), get<1>( B ) )) ||\r\n                    (compare.greater_than( get<1>( A ), get<1>( C ) ) && compare.greater_than( get<1>( C ), get<1>( B ) )));\r\n            }\r\n        }\r\n    }\r\n\r\n    //! \\brief Function to determine if vector c falls in between vectors a and b.\r\n    //! This can be used to check angle ranges without using atan2.\r\n    template <typename Vector1, typename Vector2, typename Vector3, typename NumberComparisonPolicy>\r\n    inline bool is_vector_between(const Vector1& a, const Vector2& b, const Vector3& c, bool includeBounds, const NumberComparisonPolicy& cmp)\r\n    {\r\n        using namespace geometrix;\r\n        BOOST_CONCEPT_ASSERT((Vector2DConcept<Vector1>));\r\n        BOOST_CONCEPT_ASSERT((Vector2DConcept<Vector2>));\r\n        BOOST_CONCEPT_ASSERT((Vector2DConcept<Vector3>));\r\n        BOOST_CONCEPT_ASSERT((NumberComparisonPolicyConcept<NumberComparisonPolicy, double>));\r\n\r\n        BOOST_AUTO(const detcb, exterior_product_area(c, b));\r\n\r\n        //! If b is along c bounds included it's between.\r\n        if (cmp.equals(detcb, constants::zero<decltype(detcb)>()) && cmp.greater_than_or_equal(dot_product(b, c), constants::zero<decltype(dot_product(b,c))>()))\r\n            return includeBounds;\r\n\r\n        BOOST_AUTO(const detac, exterior_product_area(a, c));\r\n\r\n        //! If a is along c and includeBounds it's between.\r\n        if (cmp.equals(detac, constants::zero<decltype(detac)>()) && cmp.greater_than_or_equal(dot_product(a, c), constants::zero<decltype(dot_product(a,c))>()))\r\n            return includeBounds;\r\n\r\n        BOOST_AUTO(const detab, exterior_product_area(a, b));\r\n\r\n        //! If b is along a, c can only be between if it is along a and included and that's handled above.\r\n        if (cmp.equals(detab, constants::zero<decltype(detab)>()) && cmp.greater_than_or_equal(dot_product(b, a), constants::zero<decltype(dot_product(b,a))>()))\r\n            return false;\r\n\r\n        //! If detab and detac have the same sign, then b and c are on the same side of a and can be compared directly.\r\n        if (cmp.greater_than_or_equal(detac * detab, constants::zero<decltype(detac*detab)>()))\r\n        {\r\n            //! Both are on same side of a; compare to each other.\r\n            return cmp.greater_than(detcb, constants::zero<decltype(detcb)>());\r\n        }\r\n\r\n        //! At this point b and c straddle a. A negative determinant means a large angle WRT a.\r\n        //! If c's is positive it must be between a and b, else the opposite must be true.\r\n        return cmp.greater_than(detac, constants::zero<decltype(detac)>());\r\n    }\r\n\r\n    template <typename Point, typename NumberComparisonPolicy>\r\n    inline bool is_vertical( const Point& start,\r\n                      const Point& end,\r\n                      const NumberComparisonPolicy& compare )\r\n    {\r\n        return compare.equals( get<0>( start ), get<0>( end ) );\r\n    }\r\n\r\n    template <typename Segment, typename NumberComparisonPolicy>\r\n    inline bool is_vertical( const Segment& s,\r\n                      const NumberComparisonPolicy& compare )\r\n    {\r\n        return is_vertical( get_start( s ),\r\n                            get_end( s ),\r\n                            compare );\r\n    }\r\n\r\n    template <typename Point, typename NumberComparisonPolicy>\r\n    inline bool is_horizontal( const Point& start, const Point& end, const NumberComparisonPolicy& compare )\r\n    {\r\n        return compare.equals( get<1>( start ),\r\n                               get<1>( end ) );\r\n    }\r\n\r\n    template <typename Segment, typename NumberComparisonPolicy>\r\n    inline bool is_horizontal( const Segment& s,const NumberComparisonPolicy& compare )\r\n    {\r\n        return is_horizontal( get_start( s ),\r\n                              get_end( s ),\r\n                              compare );\r\n    }\r\n\r\n    //! function to get the slope defined by two points\r\n    template <typename Point>\r\n    inline typename geometric_traits< Point >::arithmetic_type\r\n        get_slope( const Point& s_start, const Point& s_end )\r\n    {\r\n        return arithmetic_promote(get<1>( s_end ) - get<1>( s_start )) / (get<0>( s_end )-get<0>( s_start ));\r\n    }\r\n\r\n    //! function to get the slope defined by a segment.\r\n    template <typename Segment>\r\n    inline typename geometric_traits< typename geometric_traits< Segment >::point_type >::arithmetic_type get_slope( const Segment& s )\r\n    {\r\n        return get_slope( get_start( s ), get_end ( s ) );\r\n    }\r\n\r\n    //! Given two points which define a (non-vertical) line segment and a coordinate X calculate Y and the slope.\r\n    template <typename Point, typename CoordinateType>\r\n    inline CoordinateType y_of_x( const Point& s_start,\r\n                           const Point& s_end,\r\n                           CoordinateType x,\r\n                           CoordinateType& slope )\r\n    {\r\n        BOOST_AUTO( x0, get<0>( s_start ) );\r\n        BOOST_AUTO( x1, get<0>( s_end ) );\r\n        BOOST_AUTO( y0, get<1>( s_start ) );\r\n        BOOST_AUTO( y1, get<1>( s_end ) );\r\n        slope = arithmetic_promote( (y1-y0) )/(x1-x0);\r\n        return (x - x0) * slope + y0;\r\n    }\r\n\r\n    //! Given two points which define a (non-vertical) line segment and a coordinate X calculate Y and the slope.\r\n    template <typename Point, typename CoordinateType>\r\n    inline CoordinateType y_of_x( const Point& s_start,\r\n                           const Point& s_end,\r\n                           CoordinateType x )\r\n    {\r\n        CoordinateType slope;\r\n        return y_of_x( s_start, s_end, x, slope );\r\n    }\r\n\r\n    //! Given two points which define a (non-vertical) line segment and a coordinate X calculate Y and the slope.\r\n    template <typename Point, typename CoordinateType>\r\n    inline CoordinateType x_of_y( const Point& s_start,\r\n                           const Point& s_end,\r\n                           CoordinateType y,\r\n                           CoordinateType& slope )\r\n    {\r\n        CoordinateType y0, y1, x0, x1;\r\n\r\n        x0 = get<0>( s_start );\r\n        x1 = get<0>( s_end );\r\n        y0 = get<1>( s_start );\r\n        y1 = get<1>( s_end );\r\n\r\n        slope = (y1-y0)/(x1-x0);\r\n\r\n        CoordinateType x = (y - y0)/slope + x0;\r\n        return x;\r\n    }\r\n\r\n    //! Given two points which define a (non-vertical) line segment and a coordinate X calculate Y and the slope.\r\n    template <typename Point, typename CoordinateType>\r\n    inline CoordinateType x_of_y( const Point& s_start,\r\n                           const Point& s_end,\r\n                           CoordinateType y )\r\n    {\r\n        CoordinateType slope;\r\n        return x_of_y( s_start, s_end, y, slope );\r\n    }\r\n\r\n    template <typename T1, typename T2>\r\n    inline bool lexicographical_compare(const T1& t1, const T2& t2)\r\n    {\r\n        return t1 < t2;\r\n    }\r\n\r\n    template <typename T1, typename T2, typename U, typename ...Params>\r\n    inline bool lexicographical_compare(const T1& t1, const T2& t2, const U& u, const Params&... p)\r\n    {\r\n        return !(t2 < t1) && (t1 < t2 || lexicographical_compare(u, p...));\r\n    }\r\n\r\n    namespace detail\r\n    {\r\n        template <std::size_t D>\r\n        struct lexicographical\r\n        {\r\n            template <typename NumericSequence, typename NumberComparisonPolicy>\r\n            static bool compare( const NumericSequence& lhs, const NumericSequence& rhs, const NumberComparisonPolicy& nCompare )\r\n            {\r\n                if( nCompare.less_than( get<dimension_of<NumericSequence>::value - D>( lhs ), get<dimension_of<NumericSequence>::value - D>( rhs ) ) )\r\n                    return true;\r\n                else if( nCompare.equals( get<dimension_of<NumericSequence>::value - D>( lhs ), get<dimension_of<NumericSequence>::value - D>( rhs ) ) )\r\n                    return lexicographical<D-1>::compare( lhs, rhs, nCompare );\r\n                else\r\n                    return false;\r\n            }\r\n        };\r\n\r\n        template <>\r\n        struct lexicographical<0>\r\n        {\r\n            template <typename NumericSequence, typename NumberComparisonPolicy>\r\n            static bool compare( const NumericSequence&, const NumericSequence&, const NumberComparisonPolicy& )\r\n            {\r\n                return false;//all were equal.\r\n            }\r\n        };\r\n    }\r\n\r\n    //! Lexicographical compare functor for Cartesian points. Sorts first in X and then in Y (then Z).\r\n    template <typename NumberComparisonPolicy>\r\n    class lexicographical_comparer\r\n    {\r\n        template <typename NumericSequence1, typename NumericSequence2>\r\n        struct comparer\r\n        {\r\n            static bool compare( const NumericSequence1& lhs, const NumericSequence2& rhs, const NumberComparisonPolicy& nCompare )\r\n            {\r\n                return detail::lexicographical<dimension_of<NumericSequence1>::value>::compare( lhs, rhs, nCompare );\r\n            }\r\n        };\r\n\r\n    public:\r\n\r\n        lexicographical_comparer(){}\r\n        lexicographical_comparer( const NumberComparisonPolicy& compare )\r\n            : m_compare( compare )\r\n        {}\r\n\r\n        template <typename NumericSequence1, typename NumericSequence2>\r\n        bool operator()( const NumericSequence1& p1, const NumericSequence2& p2 ) const\r\n        {\r\n            return comparer<NumericSequence1, NumericSequence2>::compare( p1, p2, m_compare );\r\n        }\r\n\r\n    private:\r\n\r\n        NumberComparisonPolicy m_compare;\r\n\r\n    };\r\n\r\n    //! Test if lhs sequence is lexicographically less than rhs sequence.\r\n    template <typename NumericSequence1, typename NumericSequence2, typename NumberComparisonPolicy>\r\n    inline bool lexicographically_less_than(const NumericSequence1& lhs, const NumericSequence2& rhs, const NumberComparisonPolicy& cmp)\r\n    {\r\n        return lexicographical_comparer<NumberComparisonPolicy>(cmp)(lhs, rhs);\r\n    }\r\n\r\n    //! Lexicographical compare functor for points - reversed to sort in (Z), then Y then X.\r\n    template <typename NumberComparisonPolicy>\r\n    struct reverse_lexicographical_point_compare\r\n    {\r\n        reverse_lexicographical_point_compare(){}\r\n        reverse_lexicographical_point_compare( const NumberComparisonPolicy& compare )\r\n            : m_compare( compare )\r\n        {}\r\n\r\n        //! older compilers require disambiguation\r\n        template <int> struct disambiguation_tag { disambiguation_tag(int) {} };\r\n\r\n        template <typename Point>\r\n        bool operator()( const Point& p1, const Point& p2, typename boost::enable_if< boost::is_same< typename geometric_traits<Point>::dimension_type, dimension<2> > >::type* = 0, disambiguation_tag<0> = 0 ) const\r\n        {\r\n            return ( m_compare.less_than( get<1>( p1 ), get<1>( p2 ) ) ) ||\r\n                   ( m_compare.equals( get<1>( p1 ), get<1>( p2 ) ) && m_compare.less_than( get<0>( p1 ), get<0>( p2 ) ) );\r\n        }\r\n\r\n        template <typename Point>\r\n        bool operator()( const Point& p1, const Point& p2, typename boost::disable_if< boost::is_same< typename geometric_traits<Point>::dimension_type, dimension<2> > >::type* = 0, disambiguation_tag<1> = 0 ) const\r\n        {\r\n            return ( m_compare.less_than( get<2>( p1 ), get<2>( p2 ) ) )||\r\n                   ( m_compare.equals( get<2>( p1 ), get<2>( p2 ) ) && m_compare.less_than( get<1>( p1 ), get<1>( p2 ) ) ) ||\r\n                   ( m_compare.equals( get<2>( p1 ), get<2>( p2 ) ) && m_compare.equals( get<1>( p1 ), get<1>( p2 ) ) && m_compare.less_than( get<0>( p1 ), get<0>( p2 ) ) );\r\n        }\r\n\r\n        NumberComparisonPolicy m_compare;\r\n\r\n    };\r\n\r\n    //! Lexicographical compare functor for Cartesian points. Sorts first in X and then in Y (then Z).\r\n    template <typename NumberComparisonPolicy>\r\n    struct lexicographical_segment_compare\r\n    {\r\n        lexicographical_segment_compare(){}\r\n        lexicographical_segment_compare( const NumberComparisonPolicy& compare )\r\n            : m_compare( compare )\r\n            , m_pointCompare( compare )\r\n        {}\r\n\r\n        template <typename Segment>\r\n        bool operator()( const Segment& s1, const Segment& s2 ) const\r\n        {\r\n            typedef typename geometric_traits< Segment >::point_type point_type;\r\n\r\n            const point_type& start1 = get_start( s1 );\r\n            const point_type& end1   = get_end( s2 );\r\n            const point_type& start2 = get_start( s2 );\r\n            const point_type& end2   = get_end( s2 );\r\n\r\n            //Order the segments lexicographically first.\r\n            const point_type* lower1;\r\n            const point_type* upper1;\r\n            const point_type* lower2;\r\n            const point_type* upper2;\r\n\r\n            if( m_pointCompare( start1, end1 ) )\r\n            {\r\n                lower1 = &start1;\r\n                upper1 = &end1;\r\n            }\r\n            else\r\n            {\r\n                lower1 = &end1;\r\n                upper1 = &start1;\r\n            }\r\n\r\n            if( m_pointCompare( start2, end2 ) )\r\n            {\r\n                lower2 = &start2;\r\n                upper2 = &end2;\r\n            }\r\n            else\r\n            {\r\n                lower2 = &end2;\r\n                upper2 = &start2;\r\n            }\r\n\r\n            return m_pointCompare( *lower1, *lower2 ) || ( numeric_sequence_equals( *lower1, *lower2, m_compare ) && m_pointCompare( *upper1, *upper2 ) );\r\n        }\r\n\r\n        NumberComparisonPolicy                            m_compare;\r\n        lexicographical_comparer< NumberComparisonPolicy > m_pointCompare;\r\n\r\n    };\r\n\r\n    //! Functor to compare segments lexicographically as intervals A-C !< B-C if [A-B-C].\r\n    template <typename NumberComparisonPolicy>\r\n    struct segment_interval_compare\r\n    {\r\n        typedef lexicographical_comparer< NumberComparisonPolicy > lex_point_compare;\r\n\r\n        segment_interval_compare(){}\r\n        segment_interval_compare( const NumberComparisonPolicy& compare )\r\n            : m_lexCompare( compare ){}\r\n\r\n        template <typename Segment>\r\n        bool operator()( const Segment& lhs, const Segment& rhs ) const\r\n        {\r\n            typedef typename geometric_traits<Segment>::point_type       point_type;\r\n\r\n            const point_type* lhs_end;\r\n            if( m_lexCompare( get_start( lhs ), get_end( lhs ) ) )\r\n                lhs_end   = &get_end( lhs );\r\n            else\r\n                lhs_end   = &get_start( lhs );\r\n\r\n            const point_type* rhs_start;\r\n            if( m_lexCompare( get_start( rhs ), get_end( rhs ) ) )\r\n                rhs_start = &get_start( rhs );\r\n            else\r\n                rhs_start = &get_end( rhs );\r\n\r\n            //Now we have the segments in lexi order... we can compare the intervals.\r\n            return m_lexCompare( *lhs_end, *rhs_start );\r\n        }\r\n\r\n        lex_point_compare m_lexCompare;\r\n\r\n    };\r\n\r\n    //! Given a set of segments take the geometrix difference of the set and the specified segments.\r\n    //! precondition segments must all be collinear.\r\n    template <typename Segment, typename SegmentIntervalSet, typename NumberComparisonPolicy>\r\n    inline void collinear_segment_difference( SegmentIntervalSet& segments, const Segment& segment, const NumberComparisonPolicy& compare )\r\n    {\r\n        typedef lexicographical_comparer< NumberComparisonPolicy > lex_point_compare;\r\n        typedef typename geometric_traits<Segment>::point_type    point_type;\r\n        lex_point_compare lexCompare( compare );\r\n\r\n        const point_type& C = get_start( segment );\r\n        const point_type& D = get_end( segment );\r\n        if (numeric_sequence_equals(C, D, compare))\r\n            return;\r\n\r\n        typename SegmentIntervalSet::iterator lb,ub;\r\n        boost::tie( lb, ub ) = segments.equal_range( segment );\r\n\r\n        std::vector< Segment > toInsert;\r\n        while( lb != ub )\r\n        {\r\n            const Segment& overlappedSegment = *lb;\r\n\r\n            const point_type& A = get_start( overlappedSegment );\r\n            const point_type& B = get_end( overlappedSegment );\r\n\r\n            //! must be collinear\r\n            GEOMETRIX_ASSERT( is_collinear( C, D, A, compare ) && is_collinear( C, D, B, compare ) );\r\n\r\n            bool CAD = is_between( C, D, A, true, compare );\r\n            bool CBD = is_between( C, D, B, true, compare );\r\n\r\n            if( CAD && CBD )\r\n            {\r\n                //remove this one.\r\n                segments.erase( lb++ );\r\n                continue;\r\n            }\r\n\r\n            bool AEqualC = numeric_sequence_equals( A, C, compare );\r\n            bool AEqualD = numeric_sequence_equals( A, D, compare );\r\n            bool BEqualC = numeric_sequence_equals( B, C, compare );\r\n            bool BEqualD = numeric_sequence_equals( B, D, compare );\r\n\r\n            bool ACB = is_between( A, B, C, true, compare );\r\n            bool ADB = is_between( A, B, D, true, compare );\r\n            if( ACB && ADB )\r\n            {\r\n                bool CDB = is_between( C, B, D, true, compare );\r\n                if( CDB && !BEqualC )\r\n                {\r\n                    if( !AEqualC )\r\n                        toInsert.push_back( construct< Segment >( A, C ) );\r\n                    if( !BEqualD )\r\n                        toInsert.push_back( construct< Segment >( D, B ) );\r\n                    segments.erase( lb++ );\r\n                    continue;\r\n                }\r\n\r\n                bool ADC = is_between(A, C, D, true, compare);\r\n                if( ADC && !AEqualC )\r\n                {\r\n                    if( !AEqualD )\r\n                        toInsert.push_back( construct< Segment >( A, D ) );\r\n                    if( !BEqualC)\r\n                        toInsert.push_back( construct< Segment >( C, B ) );\r\n                    segments.erase( lb++ );\r\n                    continue;\r\n                }\r\n\r\n                GEOMETRIX_ASSERT( false );\r\n            }\r\n\r\n            if( CAD && !(AEqualC || AEqualD) )\r\n            {\r\n                if( ADB && !BEqualD )\r\n                {\r\n                    toInsert.push_back( construct< Segment >( D, B ) );\r\n                    //remove this one.\r\n                    segments.erase( lb++ );\r\n                    continue;\r\n                }\r\n                else if( ACB && !BEqualC )\r\n                {\r\n                    toInsert.push_back( construct< Segment >( C, B ) );\r\n                    //remove this one.\r\n                    segments.erase( lb++ );\r\n                    continue;\r\n                }\r\n            }\r\n            else if( CBD && !(BEqualC || BEqualD) )\r\n            {\r\n                if( ADB && !AEqualD)\r\n                {\r\n                    toInsert.push_back( construct< Segment >( A, D ) );\r\n                    //remove this one.\r\n                    segments.erase( lb++ );\r\n                    continue;\r\n                }\r\n                else if( ACB && !AEqualC )\r\n                {\r\n                    toInsert.push_back( construct< Segment >( A, C ) );\r\n                    //remove this one.\r\n                    segments.erase( lb++ );\r\n                    continue;\r\n                }\r\n            }\r\n\r\n            ++lb;\r\n        }\r\n\r\n        segments.insert( toInsert.begin(), toInsert.end() );\r\n    }\r\n\r\n    //! Given a set of segments take the geometrix union of the set and the specified segments.\r\n    //! precondition segments must all be collinear.\r\n    template <typename Segment, typename SegmentIntervalSet, typename NumberComparisonPolicy>\r\n    inline void collinear_segment_union( SegmentIntervalSet& segments, const Segment& segment, const NumberComparisonPolicy& compare )\r\n    {\r\n        typedef lexicographical_comparer< NumberComparisonPolicy > lex_point_compare;\r\n        typedef typename geometric_traits<Segment>::point_type    point_type;\r\n        lex_point_compare lexCompare( compare );\r\n\r\n        typename SegmentIntervalSet::iterator lb,ub;\r\n        boost::tie( lb, ub ) = segments.equal_range( segment );\r\n\r\n        Segment unionSegment = construct<Segment>( get_start( segment ), get_end( segment ) );\r\n\r\n        while( lb != ub )\r\n        {\r\n            const Segment& overlappedSegment = *lb;\r\n\r\n            const point_type& A = get_start( overlappedSegment );\r\n            const point_type& B = get_end( overlappedSegment );\r\n            const point_type& C = get_start( unionSegment );\r\n            const point_type& D = get_end( unionSegment );\r\n\r\n            //! must be collinear\r\n            GEOMETRIX_ASSERT( is_collinear( C, D, A, compare ) && is_collinear( C, D, B, compare ) );\r\n\r\n            bool CAD = is_between( C, D, A, true, compare );\r\n            bool CBD = is_between( C, D, B, true, compare );\r\n\r\n            //Already contained in the union.\r\n            if( CAD && CBD )\r\n            {\r\n                //remove this one.\r\n                segments.erase( lb++ );\r\n                continue;\r\n            }\r\n\r\n            bool ACB = is_between( A, B, C, true, compare );\r\n            bool ADB = is_between( A, B, D, true, compare );\r\n\r\n            //New segment contains existing union.. replace.\r\n            if( ACB && ADB )\r\n            {\r\n                unionSegment = construct<Segment>( A, B );\r\n                segments.erase( lb++ );\r\n                continue;\r\n            }\r\n\r\n            if( CAD )\r\n            {\r\n                if( ADB )\r\n                {\r\n                    unionSegment = construct<Segment>( C, B );\r\n                    segments.erase( lb++ );\r\n                    continue;\r\n                }\r\n                if( ACB )\r\n                {\r\n                    unionSegment = construct<Segment>( D, B );\r\n                    segments.erase( lb++ );\r\n                    continue;\r\n                }\r\n            }\r\n            else if( CBD )\r\n            {\r\n                if( ADB )\r\n                {\r\n                    unionSegment = construct<Segment>( A, C );\r\n                    segments.erase( lb++ );\r\n                    continue;\r\n                }\r\n                if( ACB )\r\n                {\r\n                    unionSegment = construct<Segment>( A, D );\r\n                    segments.erase( lb++ );\r\n                    continue;\r\n                }\r\n            }\r\n\r\n            ++lb;\r\n        }\r\n\r\n        segments.insert( unionSegment );\r\n    }\r\n\r\n    //! sorting compare functor to sort coordinates by less than order.\r\n    template <typename CoordinateType, typename NumberComparisonPolicy>\r\n    struct coordinate_less_compare\r\n    {\r\n        coordinate_less_compare( const NumberComparisonPolicy& compare )\r\n            : m_compare( compare )\r\n        {}\r\n\r\n        bool operator() ( const CoordinateType& lhs, const CoordinateType& rhs ) const\r\n        {\r\n            return m_compare.less_than( rhs, lhs );\r\n        }\r\n\r\n        NumberComparisonPolicy m_compare;\r\n    };\r\n\r\n    template <typename Compare>\r\n    struct pair_first_compare\r\n    {\r\n        pair_first_compare( const Compare& compare )\r\n            : m_compare( compare )\r\n        {}\r\n\r\n        template <typename T1, typename T2>\r\n        bool operator()(const std::pair<T1,T2>& p1, const std::pair<T1,T2>& p2) const\r\n        {\r\n            return m_compare(p1.first, p2.first);\r\n        }\r\n\r\n        Compare m_compare;\r\n\r\n    };\r\n\r\n    template <typename Compare>\r\n    struct pair_second_compare\r\n    {\r\n        pair_second_compare( const Compare& compare )\r\n            : m_compare( compare )\r\n        {}\r\n\r\n        template <typename T1, typename T2>\r\n        bool operator()(const std::pair<T1,T2>& p1, const std::pair<T1,T2>& p2) const\r\n        {\r\n            return m_compare(p1.second, p2.second);\r\n        }\r\n\r\n        Compare m_compare;\r\n\r\n    };\r\n\r\n    //! \\struct dimension_compare\r\n    //! \\brief A predicate to compare two numeric sequences by the value at a specified dimension.\r\n    template <std::size_t D, typename NumberComparisonPolicy>\r\n    struct dimension_compare\r\n    {\r\n        dimension_compare( const NumberComparisonPolicy& compare )\r\n            : m_compare( compare )\r\n            , m_lexicographicalCompare( compare )\r\n        {}\r\n\r\n        template <typename NumericSequence>\r\n        bool operator()( const NumericSequence& lhs, const NumericSequence& rhs ) const\r\n        {\r\n            //! Sequences are compared by dimension specified. In the case where coordinates at D are equal, the sequences are\r\n            //! given a total order lexicographically.\r\n            if( m_compare.less_than( get<D>( lhs ), get<D>( rhs ) ) )\r\n                return true;\r\n            else if( m_compare.equals( get<D>( lhs ), get<D>( rhs ) ) )\r\n                return m_lexicographicalCompare( lhs, rhs );\r\n            else\r\n                return false;\r\n        }\r\n\r\n        NumberComparisonPolicy                          m_compare;\r\n        lexicographical_comparer<NumberComparisonPolicy> m_lexicographicalCompare;\r\n    };\r\n\r\n    template <typename T>\r\n    inline T min_copy(const T& a, const T& b)\r\n    {\r\n        return a < b ? a : b;\r\n    }\r\n\r\n    template <typename T>\r\n    inline T max_copy(const T& a, const T& b)\r\n    {\r\n        return a > b ? a : b;\r\n    }\r\n\r\n    // clamp n to lie within the range [min, max]\r\n    template <typename T>\r\n    inline T clamp(T n, T min, T max)\r\n    {\r\n        if (n < min) return min;\r\n        if (n > max) return max;\r\n        return n;\r\n    }\r\n\r\n    template <typename T>\r\n    inline int sign(const T& value)\r\n    {\r\n        return value >= constants::zero<T>() ? 1 : -1;\r\n    }\r\n\r\n}//namespace geometrix;\r\n\r\n#endif //GEOMETRIX_UTILITIES_HPP\r\n", "meta": {"hexsha": "13a970eff5ea41d947de27979002680c313c39f8", "size": 35844, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometrix/utility/utilities.hpp", "max_stars_repo_name": "brandon-kohn/Geometrix", "max_stars_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometrix/utility/utilities.hpp", "max_issues_repo_name": "brandon-kohn/Geometrix", "max_issues_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometrix/utility/utilities.hpp", "max_forks_repo_name": "brandon-kohn/Geometrix", "max_forks_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": 40.4559819413, "max_line_length": 216, "alphanum_fraction": 0.5583361232, "num_tokens": 7812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5383306026362935}}
{"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_REM_PIO2_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REM_PIO2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n\n    This function object computes the remainder modulo \\f$\\pi/2\\f$,\n     and the angle quadrant between 0 and 3.\n\n     This is a rather slow version,  but accurate in the full floating range.\n\n\n    @par Header <boost/simd/function/rem_pio2.hpp>\n\n    @par Notes\n\n     - This algorithm is accurate over  the full floating range,  but also is over\n      costly and implies the knowledge  of a few hundred \\f$\\pi\\f$ decimals\n\n     - Some simpler algorithms  @ref rem_pio2_medium, @ref rem_pio2_cephes or @ref rem_pio2_straight\n      can often be used, but the precision is only insured on smaller intervals.\n\n      - Using  `std::tie(n, r) = rem_pio2(x);` is similar to ` n = div(inearbyint, x, Pio_2<T>())`\n      and `r =  remainder(x, Pio_2<T>())`\n\n    @see rem_pio2_medium, rem_pio2_straight, rem_2pi,  rem_pio2_cephes,\n\n    @par Example:\n\n      @snippet rem_pio2.cpp rem_pio2\n\n    @par Possible output:\n\n      @snippet rem_pio2.txt rem_pio2\n\n  **/\n  std::pair<IEEEValue, IEEEValue> rem_pio2(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/rem_pio2.hpp>\n#include <boost/simd/function/simd/rem_pio2.hpp>\n\n#endif\n", "meta": {"hexsha": "7fbda2b426191ca95c30689138bfc97ea22d1740", "size": 1730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/rem_pio2.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/function/rem_pio2.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/function/rem_pio2.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 29.3220338983, "max_line_length": 100, "alphanum_fraction": 0.6283236994, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5383305973793463}}
{"text": "#include <boost/test/included/unit_test_framework.hpp>\n#include \"mcrl2/lps/parse.h\"\n#include \"mcrl2/lps/linearise.h\"\n#include \"mcrl2/lps/detail/test_input.h\"\n#include \"mcrl2/pbes/bisimulation.h\"\n#include \"mcrl2/pbes/detail/pbes2bool.h\"\n\nusing namespace mcrl2;\nusing namespace mcrl2::lps;\nusing namespace mcrl2::pbes_system;\nusing namespace mcrl2::log;\n\nvoid test_bisimulation(const std::string& s1, const std::string& s2,\n                       bool strongly_bisimilar,\n                       bool branching_bisimilar,\n                       bool branching_similar,\n                       bool weakly_bisimilar,\n                       bool linearize = false)\n{\n  specification spec1;\n  specification spec2;\n  if (linearize)\n  {\n    spec1=remove_stochastic_operators(linearise(s1));\n    spec2=remove_stochastic_operators(linearise(s2));\n  }\n  else\n  {\n    spec1 = parse_linear_process_specification(s1);\n    spec2 = parse_linear_process_specification(s2);\n  }\n\n  std::clog << \"Testing strong bisimulation\" << std::endl;\n  pbes sb  = strong_bisimulation(spec1, spec2);\n  BOOST_CHECK(sb.is_well_typed());\n  bool sb_solution = pbes_system::detail::pbes2bool(sb);\n  BOOST_CHECK(sb_solution == strongly_bisimilar);\n\n  std::clog << \"Testing branching bisimulation\" << std::endl;\n  pbes bb  = branching_bisimulation(spec1, spec2);\n  bool bb_solution = pbes_system::detail::pbes2bool(bb);\n  BOOST_CHECK(bb.is_well_typed());\n  BOOST_CHECK(bb_solution == branching_bisimilar);\n\n  std::clog << \"Testing branching simulation\" << std::endl;\n  pbes bs = branching_simulation_equivalence(spec1, spec2);\n  bool bs_solution = pbes_system::detail::pbes2bool(bs);\n  BOOST_CHECK(bs.is_well_typed());\n  BOOST_CHECK(bs_solution == branching_similar);\n\n  std::clog << \"Testing weak bisimulation\" << std::endl;\n  pbes wb  = weak_bisimulation(spec1, spec2);\n  bool wb_solution = pbes_system::detail::pbes2bool(wb);\n  BOOST_CHECK(wb.is_well_typed());\n  BOOST_CHECK(wb_solution == weakly_bisimilar);\n}\n\nBOOST_AUTO_TEST_CASE(ABP)\n{\n  test_bisimulation(lps::detail::LINEAR_ABP_SPECIFICATION(), lps::detail::LINEAR_ABP_SPECIFICATION(), true, true, true, true);\n}\n\nBOOST_AUTO_TEST_CASE(SMALLSPEC)\n{\n  const std::string SMALLSPEC =\n    \"act a,b;                 \\n\"\n    \"proc X(s: Pos) =         \\n\"\n    \"  (s == 1) -> a . X(2)   \\n\"\n    \"+ (s == 2) -> tau . X(3) \\n\"\n    \"+ (s == 3) -> tau . X(4) \\n\"\n    \"+ (s == 4) -> b . X(1);  \\n\"\n    \"init X(1);               \\n\"\n    ;\n  test_bisimulation(SMALLSPEC, SMALLSPEC, true, true, true, true);\n}\n\nBOOST_AUTO_TEST_CASE(small_different_specs)\n{\n  const std::string s1 =\n    \"act a,b;                 \\n\"\n    \"proc X(s: Pos) =         \\n\"\n    \"  (s == 1) ->  a . X(2)  \\n\"\n    \"+ (s == 2) -> b . X(1);  \\n\"\n    \"init X(1);               \\n\"\n    ;\n  const std::string s2 =\n    \"act a,b,c;               \\n\"\n    \"proc X(s: Pos) =     \\n\"\n    \"  (s == 1) ->  a . X(2)  \\n\"\n    \"+ (s == 1) ->  c . X(1)  \\n\"\n    \"+ (s == 2) -> b . X(1);  \\n\"\n    \"init X(1);               \\n\"\n    ;\n    ;\n  test_bisimulation(s1, s2, false, false, false, false);\n  test_bisimulation(s2, s1, false, false, false, false);\n}\n\nBOOST_AUTO_TEST_CASE(buffers_silent_lose)\n{\n  const std::string buffer =\n    \"sort D = struct d1 | d2;\\n\"\n    \"map  n: Pos;\\n\"\n    \"eqn  n  =  2;\\n\"\n    \"act  r,s: D;\\n\"\n    \"proc P(b_Buffer: List(D)) =\\n\"\n    \"       !(b_Buffer == []) ->\\n\"\n    \"         s(rhead(b_Buffer)) .\\n\"\n    \"         P(b_Buffer = rtail(b_Buffer))\\n\"\n    \"     + sum d_Buffer: D.\\n\"\n    \"         (#b_Buffer < 2) ->\\n\"\n    \"         r(d_Buffer) .\\n\"\n    \"         P(b_Buffer = d_Buffer |> b_Buffer)\\n\"\n    \"     + delta;\\n\"\n    \"init P([]);\\n\";\n\n  const std::string lossy_buffer =\n    \"sort D = struct d1 | d2;\\n\"\n    \"map  n: Pos;\\n\"\n    \"eqn  n  =  2;\\n\"\n    \"act  r,s: D;\\n\"\n    \"proc P(s3_Buffer: Pos, d_Buffer: D, b_Buffer: List(D)) =\\n\"\n    \"       sum e_Buffer: Bool.\\n\"\n    \"         (s3_Buffer == 2) ->\\n\"\n    \"         tau .\\n\"\n    \"         P(s3_Buffer = 1, d_Buffer = d1, b_Buffer = if(e_Buffer, d_Buffer |> b_Buffer, b_Buffer))\\n\"\n    \"     + (s3_Buffer == 1 && !(b_Buffer == [])) ->\\n\"\n    \"         s(rhead(b_Buffer)) .\\n\"\n    \"         P(s3_Buffer = 1, d_Buffer = d1, b_Buffer = rtail(b_Buffer))\\n\"\n    \"     + sum d0_Buffer: D.\\n\"\n    \"         (s3_Buffer == 1 && #b_Buffer < 2) ->\\n\"\n    \"         r(d0_Buffer) .\\n\"\n    \"         P(s3_Buffer = 2, d_Buffer = d0_Buffer)\\n\"\n    \"     + delta;\\n\"\n    \"init P(1, d1, []);\\n\";\n\n  test_bisimulation(buffer, lossy_buffer, false, false, false, false);\n  test_bisimulation(lossy_buffer, buffer, false, false, false, false);\n}\n\nBOOST_AUTO_TEST_CASE(buffers_explicit_lose)\n{\n  const std::string buffer =\n    \"sort D = struct d1 | d2;\\n\"\n    \"map  n: Pos;\\n\"\n    \"eqn  n  =  2;\\n\"\n    \"act  r,s: D;\\n\"\n    \"proc P(b_Buffer: List(D)) =\\n\"\n    \"       !(b_Buffer == []) ->\\n\"\n    \"         s(rhead(b_Buffer)) .\\n\"\n    \"         P(b_Buffer = rtail(b_Buffer))\\n\"\n    \"     + sum d_Buffer: D.\\n\"\n    \"         (#b_Buffer < 2) ->\\n\"\n    \"         r(d_Buffer) .\\n\"\n    \"         P(b_Buffer = d_Buffer |> b_Buffer)\\n\"\n    \"     + delta;\\n\"\n    \"init P([]);\\n\";\n\n  const std::string lossy_buffer =\n      \"sort D = struct d1 | d2;\\n\"\n      \"map  n: Pos;\\n\"\n      \"eqn  n  =  2;\\n\"\n      \"act  r,s: D;\\n\"\n      \"     lose;\\n\"\n      \"proc P(s3_Buffer: Pos, d_Buffer: D, b_Buffer: List(D)) =\\n\"\n      \"       sum d0_Buffer: D.\\n\"\n      \"         (s3_Buffer == 1 && #b_Buffer < 2) ->\\n\"\n      \"         r(d0_Buffer) .\\n\"\n      \"         P(s3_Buffer = 2, d_Buffer = d0_Buffer)\\n\"\n      \"     + (s3_Buffer == 1 && !(b_Buffer == [])) ->\\n\"\n      \"         s(rhead(b_Buffer)) .\\n\"\n      \"         P(s3_Buffer = 1, d_Buffer = d1, b_Buffer = rtail(b_Buffer))\\n\"\n      \"     + (s3_Buffer == 2) ->\\n\"\n      \"         tau .\\n\"\n      \"         P(s3_Buffer = 3, d_Buffer = d1)\\n\"\n      \"     + (s3_Buffer == 2) ->\\n\"\n      \"         tau .\\n\"\n      \"         P(s3_Buffer = 1, d_Buffer = d1, b_Buffer = d_Buffer |> b_Buffer)\\n\"\n      \"     + (s3_Buffer == 3) ->\\n\"\n      \"         lose .\\n\"\n      \"         P(s3_Buffer = 1, d_Buffer = d1)\\n\"\n      \"     + delta;\\n\"\n      \"init P(1, d1, []);\\n\";\n\n  test_bisimulation(buffer, lossy_buffer, false, false, false, false);\n  test_bisimulation(lossy_buffer, buffer, false, false, false, false);\n}\n\nBOOST_AUTO_TEST_CASE(test_fresh_variables)\n{\n  data::variable_list w = { data::variable(\"d\", data::basic_sort(\"D\")), data::variable(\"e\", data::basic_sort(\"E\")), data::variable(\"f\", data::basic_sort(\"F\")) };\n  std::set<std::string> context;\n  context.insert(\"e\");\n  context.insert(\"f_00\");\n  data::variable_list w1 = pbes_system::detail::fresh_variables(w, context);\n  std::cout << \"w1 = \" << data::pp(w1) << std::endl;\n\n  context.clear();\n  context.insert(\"e3_Sx0\");\n  context.insert(\"e_Sx0\");\n  context.insert(\"n0_Sx0\");\n  context.insert(\"n_S\");\n  context.insert(\"s3_S\");\n  std::cout << \"\\n\" << core::detail::print_set(context, \"context\") << std::endl;\n  data::variable_list yi = { data::variable(\"e3_S\", data::basic_sort(\"A\")) };\n  std::cout << \"\\nyi \" << data::pp(yi) << std::endl;\n  data::variable_list y = pbes_system::detail::fresh_variables(yi, context);\n  std::cout << \"\\ny \" << data::pp(y) << std::endl;\n  BOOST_CHECK(y.size() == 1);\n  BOOST_CHECK(std::string(y.front().name()) != \" e3_Sx0\");\n}\n\nboost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[])\n{\n  return nullptr;\n}\n", "meta": {"hexsha": "6fb6eb1a3fe750d3fb90884bddedcf75e4e89b81", "size": 7363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/pbes/test/bisimulation_test.cpp", "max_stars_repo_name": "gijskant/mcrl2-pmc", "max_stars_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/pbes/test/bisimulation_test.cpp", "max_issues_repo_name": "gijskant/mcrl2-pmc", "max_issues_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/pbes/test/bisimulation_test.cpp", "max_forks_repo_name": "gijskant/mcrl2-pmc", "max_forks_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "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.930875576, "max_line_length": 161, "alphanum_fraction": 0.553986147, "num_tokens": 2445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.5383053435117373}}
{"text": "#include <vector>\n#include <math.h>\n#include <iostream>\n#include <string>\n#include <sstream>\n\n#include <ros/ros.h>\n#include <ros/console.h>\n\n#include <common/Factor.h>\n#include <common/Keyframe.h>\n#include <common/ClosestKeyframe.h>\n#include <common/LastKeyframe.h>\n#include <common/Registration.h>\n#include <common/Pose2DWithCovariance.h>\n#include <common/OdometryBuffer.h>\n\n#include <gtsam/inference/Key.h>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/nonlinear/Values.h>\n#include <gtsam/nonlinear/Marginals.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n\ncommon::Pose2DWithCovariance compose(common::Pose2DWithCovariance input_1, common::Pose2DWithCovariance input_2) {\n  common::Pose2DWithCovariance output;\n  double cos_th = cos( input_1.pose.theta );\n  double sin_th = sin( input_1.pose.theta );\n  double dx = input_2.pose.x;\n  double dy = input_2.pose.y;\n  double dth = input_2.pose.theta;\n  output.pose.x = ( cos_th * dx ) + ( -sin_th * dy );\n  output.pose.y = ( sin_th * dx ) + ( cos_th *dy );\n  output.pose.theta = input_1.pose.theta + dth;\n  output.pose.theta = std::fmod(output.pose.theta + M_PI, 2 * M_PI) - M_PI;\n\n  return output;\n}\n\nEigen::MatrixXd covariance_to_eigen(common::Factor input) {\n  Eigen::MatrixXd Q(3, 3);\n  Q.row(0) << input.delta.covariance[0],\n    input.delta.covariance[1],\n    input.delta.covariance[2];\n  Q.row(1) << input.delta.covariance[3],\n    input.delta.covariance[4],\n    input.delta.covariance[5];\n  Q.row(2) << input.delta.covariance[6],\n    input.delta.covariance[7],\n    input.delta.covariance[8];\n\n  return Q;\n}\n\ncommon::Pose2DWithCovariance eigen_to_covariance(common::Pose2DWithCovariance pose, Eigen::MatrixXd Q) {\n  for(int i = 0; i < Q.rows(); i++) {\n    for(int j = 0; j < Q.cols(); j++) {\n      pose.covariance[( i * Q.rows() ) + j] = Q(i, j);\n    }\n  }\n\n  return pose;\n}\n", "meta": {"hexsha": "b600366c6de90f2baba769c9b699ffe2e8f45549", "size": 2066, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/graph/include/graph.hpp", "max_stars_repo_name": "Sergimech/GraphSLAM", "max_stars_repo_head_hexsha": "f215ef0940011ffd9609e0a751d985e9249b5ddd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-02-15T20:18:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-03T08:45:55.000Z", "max_issues_repo_path": "src/graph/include/graph.hpp", "max_issues_repo_name": "Sergimech/GraphSLAM", "max_issues_repo_head_hexsha": "f215ef0940011ffd9609e0a751d985e9249b5ddd", "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/graph/include/graph.hpp", "max_forks_repo_name": "Sergimech/GraphSLAM", "max_forks_repo_head_hexsha": "f215ef0940011ffd9609e0a751d985e9249b5ddd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T15:14:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-03T08:45:56.000Z", "avg_line_length": 29.9420289855, "max_line_length": 114, "alphanum_fraction": 0.706195547, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.538305320472173}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra. Eigen itself is part of the KDE project.\n//\n// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>\n//\n// Eigen is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3 of the License, or (at your option) any later version.\n//\n// Alternatively, you can redistribute it and/or\n// modify it under the terms of the GNU General Public License as\n// published by the Free Software Foundation; either version 2 of\n// the License, or (at your option) any later version.\n//\n// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License and a copy of the GNU General Public License along with\n// Eigen. If not, see <http://www.gnu.org/licenses/>.\n\n#include \"main.h\"\n#include <limits>\n#include <Eigen/Eigenvalues>\n\ntemplate<typename MatrixType> void schur(int size = MatrixType::ColsAtCompileTime)\n{\n  typedef typename ComplexSchur<MatrixType>::ComplexScalar ComplexScalar;\n  typedef typename ComplexSchur<MatrixType>::ComplexMatrixType ComplexMatrixType;\n\n  // Test basic functionality: T is triangular and A = U T U*\n  for(int counter = 0; counter < g_repeat; ++counter) {\n    MatrixType A = MatrixType::Random(size, size);\n    ComplexSchur<MatrixType> schurOfA(A);\n    VERIFY_IS_EQUAL(schurOfA.info(), Success);\n    ComplexMatrixType U = schurOfA.matrixU();\n    ComplexMatrixType T = schurOfA.matrixT();\n    for(int row = 1; row < size; ++row) {\n      for(int col = 0; col < row; ++col) {\n VERIFY(T(row,col) == (typename MatrixType::Scalar)0);\n      }\n    }\n    VERIFY_IS_APPROX(A.template cast<ComplexScalar>(), U * T * U.adjoint());\n  }\n\n  // Test asserts when not initialized\n  ComplexSchur<MatrixType> csUninitialized;\n  VERIFY_RAISES_ASSERT(csUninitialized.matrixT());\n  VERIFY_RAISES_ASSERT(csUninitialized.matrixU());\n  VERIFY_RAISES_ASSERT(csUninitialized.info());\n\n  // Test whether compute() and constructor returns same result\n  MatrixType A = MatrixType::Random(size, size);\n  ComplexSchur<MatrixType> cs1;\n  cs1.compute(A);\n  ComplexSchur<MatrixType> cs2(A);\n  VERIFY_IS_EQUAL(cs1.info(), Success);\n  VERIFY_IS_EQUAL(cs2.info(), Success);\n  VERIFY_IS_EQUAL(cs1.matrixT(), cs2.matrixT());\n  VERIFY_IS_EQUAL(cs1.matrixU(), cs2.matrixU());\n\n  // Test computation of only T, not U\n  ComplexSchur<MatrixType> csOnlyT(A, false);\n  VERIFY_IS_EQUAL(csOnlyT.info(), Success);\n  VERIFY_IS_EQUAL(cs1.matrixT(), csOnlyT.matrixT());\n  VERIFY_RAISES_ASSERT(csOnlyT.matrixU());\n\n  if (size > 1)\n  {\n    // Test matrix with NaN\n    A(0,0) = std::numeric_limits<typename MatrixType::RealScalar>::quiet_NaN();\n    ComplexSchur<MatrixType> csNaN(A);\n    VERIFY_IS_EQUAL(csNaN.info(), NoConvergence);\n  }\n}\n\nvoid test_schur_complex()\n{\n  CALL_SUBTEST_1(( schur<Matrix4cd>() ));\n  CALL_SUBTEST_2(( schur<MatrixXcf>(internal::random<int>(1,50)) ));\n  CALL_SUBTEST_3(( schur<Matrix<std::complex<float>, 1, 1> >() ));\n  CALL_SUBTEST_4(( schur<Matrix<float, 3, 3, Eigen::RowMajor> >() ));\n\n  // Test problem size constructors\n  CALL_SUBTEST_5(ComplexSchur<MatrixXf>(10));\n}", "meta": {"hexsha": "a770cdeb196b67314991c0624aee539141bca092", "size": 3478, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/schur_complex.cpp", "max_stars_repo_name": "mathstuf/ParaView", "max_stars_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T20:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T20:20:59.000Z", "max_issues_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/schur_complex.cpp", "max_issues_repo_name": "mathstuf/ParaView", "max_issues_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "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": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/schur_complex.cpp", "max_forks_repo_name": "mathstuf/ParaView", "max_forks_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-04-14T13:42:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T04:59:42.000Z", "avg_line_length": 39.0786516854, "max_line_length": 82, "alphanum_fraction": 0.72426682, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.5382898699124236}}
{"text": "#include <iostream>\n#include <vector>\n#include <opencv2/opencv.hpp>\n#include <dlib/matrix.h>\n\n\nusing namespace std;\nusing namespace cv;\nusing namespace dlib;\n\nstd::vector<Point2f> get_points( std::string filename, int &num_shape ) {\n    std::vector<Point2f> points_set;    \n    FileStorage fs( filename, FileStorage::READ );\n    if( !fs.isOpened() ) {\n        cout << \"File not found at get_points: \" << filename << endl;\n        num_shape--;\n        return points_set;\n    }\n    \n    FileNode features = fs[\"features\"];\n    for( auto point:features ){\n        Point2f p2f( point[\"x\"], point[\"y\"] );\n        points_set.push_back( p2f );\n    }\n    fs.release();\n\n    return points_set;\n}\nstd::vector<std::vector<Point2f>> get_delaunay( std::string filename, int &num_shape ) {\n    std::vector<Point2f> init(68, Point2f(0, 0));\n    std::vector<std::vector<Point2f>> delaunay_set;\n    std::vector<Point2f> points = get_points( filename, num_shape );\n    FileStorage fs( filename, FileStorage::READ );\n    if( !fs.isOpened() ) {\n        cout << \"File not found at delaunay: \" << filename << endl;\n        num_shape--;\n        return delaunay_set;\n    }\n    FileNode delaunay = fs[\"delaunay_index\"];\n    for( auto t:delaunay ){\n        Vec3i v_index;\n        std::vector<Point2f> v_points;\n        t[\"index\"] >> v_index;\n        v_points.push_back( points[ v_index[0] ] );\n        v_points.push_back( points[ v_index[1] ] );\n        v_points.push_back( points[ v_index[2] ] );\n        delaunay_set.push_back( v_points );\n    }\n\n    return delaunay_set;\n}\n\nvoid point_drawing( Mat& plane, std::vector<Point2f> points, double scale, Scalar& color ) {\n    for( auto p:points ){\n        circle( plane, p, 1, color, -1);\n    }\n}\nvoid delaunay_drawing( Mat& plane, std::vector<std::vector<Point2f>> vertices, Scalar& color ) {\n    float line_weight = 1.5;\n    for( auto v:vertices ){\n        line(plane, v[0], v[1], color, line_weight);\n        line(plane, v[1], v[2], color, line_weight);\n        line(plane, v[2], v[0], color, line_weight);\n    }\n}\n\nint main( int argc, char *argv[] ) {\n    int num_shape = atoi(argv[1]);\n    std::string mean_filename = \"../face2yaml/dataset/meanShape.yaml\";\n    Mat plane = Mat::zeros( Size(512,512), CV_32FC3 );\n    std::vector<std::vector<Point2f>> shape_store;\n    std::vector<std::vector<Point2f>> delaunay = get_delaunay( mean_filename, num_shape );\n    std::vector<Point2f>  mean_points = get_points( mean_filename, num_shape );\n    Scalar red_color = Scalar( 0, 0, 255 );\n    Scalar blue_color = Scalar( 255, 0, 0 );\n    Scalar green_color = Scalar( 0, 255, 0 );\n\n    for(int i = 1; i <= num_shape; ++i) {\n        std::vector<Point2f> left_shape_points = get_points(\"../face2yaml/dataset/\"+ to_string(i) +\"L.yaml\", num_shape);\n        \n        // Centroid(x, y)\n        cv::Vec2f cg;\n        double scale = 0;\n        int left_num_shape = left_shape_points.size();\n        for(int i = 0; i < left_num_shape; ++i){\n            cg[0] += left_shape_points[i].x;\n            cg[1] += left_shape_points[i].y;\n        }\n        cg[0] = cg[0]/left_num_shape;\n        cg[1] = cg[1]/left_num_shape;\n        \n        std::vector<Point2f> left_shape_mean;\n\n        for( int i = 0; i < left_num_shape; ++i ){\n            int offset = 256;\n            float tx_point = left_shape_points[i].x - cg[0];\n            float ty_point = left_shape_points[i].y - cg[1];\n            scale += tx_point*tx_point + ty_point*ty_point;\n            Point2f left_s( tx_point + offset, ty_point + offset);\n            left_shape_mean.push_back(left_s);\n        }\n\n        scale = sqrt(scale/left_num_shape);\n        cout << \"Scale : \" << scale << endl;\n\n        point_drawing( plane, left_shape_mean, scale, green_color );\n\n        if( i%5 == 0 ){\n            float percentage = ( (float)i/num_shape )*100;\n            if( percentage == 100 )\n                break;\n            cout << \"processing \";\n            cout <<  setprecision(2) << \"[ \" << percentage << \" \\% ]\" << endl;\n        }\n    }\n    // delaunay_drawing( plane, delaunay, red_color );\n    cout << \"Num_shape: \" << num_shape << endl;\n    imshow (\"Plane\", plane );\n    cout << \"[ 100\\% Done ], \" << num_shape << \" Faces\" << endl;\n    waitKey(0);\n\n    return 0;\n}\n\n\n\n", "meta": {"hexsha": "af8399c8ba2a661ad889f001628f23d2616b8de9", "size": 4233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AAM/src/core_aam.cpp", "max_stars_repo_name": "adadesions/trainingJackson", "max_stars_repo_head_hexsha": "ac17bbd7155b6f04c28662ff1007ee28b73aacfc", "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": "AAM/src/core_aam.cpp", "max_issues_repo_name": "adadesions/trainingJackson", "max_issues_repo_head_hexsha": "ac17bbd7155b6f04c28662ff1007ee28b73aacfc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AAM/src/core_aam.cpp", "max_forks_repo_name": "adadesions/trainingJackson", "max_forks_repo_head_hexsha": "ac17bbd7155b6f04c28662ff1007ee28b73aacfc", "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.3307086614, "max_line_length": 120, "alphanum_fraction": 0.5844554689, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5382898663763832}}
{"text": "// Copyright (c) 2017 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n \n#include <stdio.h>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n \n#include \"utils/maths.hpp\"\n \nnamespace octopus { namespace test {\n \nstatic constexpr double tolerance {1e-10};\n \nBOOST_AUTO_TEST_SUITE(utils)\nBOOST_AUTO_TEST_SUITE(maths)\n \nBOOST_AUTO_TEST_CASE(log_sum_exp_handles_edge_cases)\n{\n    using octopus::maths::log_sum_exp;\n    static constexpr double zero {0.0};\n    static constexpr double lnHalf {-0.6931471805599453};\n    BOOST_CHECK_CLOSE(log_sum_exp(lnHalf, lnHalf), zero, tolerance);\n    BOOST_CHECK_CLOSE(log_sum_exp(zero, zero), -lnHalf, tolerance);\n}\n \nBOOST_AUTO_TEST_SUITE_END()\nBOOST_AUTO_TEST_SUITE_END()\n \n} // namespace test\n} // namespace octopus\n", "meta": {"hexsha": "47d5bc8814478dcf25ef2736407c6553a72a76c5", "size": 850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/utils/maths_tests.cpp", "max_stars_repo_name": "gunjanbaid/octopus", "max_stars_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 278.0, "max_stars_repo_stars_event_min_datetime": "2016-10-03T16:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:59:32.000Z", "max_issues_repo_path": "test/unit/utils/maths_tests.cpp", "max_issues_repo_name": "gunjanbaid/octopus", "max_issues_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 229.0, "max_issues_repo_issues_event_min_datetime": "2016-10-13T14:07:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:59:58.000Z", "max_forks_repo_path": "test/unit/utils/maths_tests.cpp", "max_forks_repo_name": "gunjanbaid/octopus", "max_forks_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-10-28T22:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:28:43.000Z", "avg_line_length": 27.4193548387, "max_line_length": 96, "alphanum_fraction": 0.7658823529, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5382394653801235}}
{"text": "/*\n\u041f\u043e\u0434\u0441\u0447\u0451\u0442 \u0441\u0443\u043c\u043c\u044b \u044d\u0442\u043e\u0433\u043e \u0440\u044f\u0434\u0430:\nhttps://i.imgur.com/JjdxXIt.png\n*/\n\n#include <iostream>\n#include <iomanip>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"../include/calcSeries.h\"\n\nusing namespace boost::multiprecision;\n\nvoid calcSeries(const unsigned threadNum)\n{\n    const size_t N = 7500000;\n    const cpp_int num_87 = 87;\n    const cpp_int num_13 = 13;\n\n    const unsigned REP_NUM = 2;\n\n    for(unsigned i = 0; i < REP_NUM; ++i)\n    {\n\n\n\n        cpp_int sum = 0;\n\n        #pragma omp parallel num_threads(threadNum)\n        {\n            #pragma omp for nowait\n            for(size_t i = 0; i < N; ++i)\n            {\n                cpp_int buff;\n                buff = i+1;\n                buff = pow(buff, 5) + num_87*buff + num_13*buff*buff;\n                #pragma omp critical\n                {\n                    sum += buff;\n                }\n            }\n        }\n\n        //std::cout << \"sum = \" << sum << std::endl;\n\n\n\n    }\n}\n", "meta": {"hexsha": "dad72800689367023425fe9c2676dfc7aaf85c0d", "size": 949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "func/calcSeries.cpp", "max_stars_repo_name": "The220th/easybenchk", "max_stars_repo_head_hexsha": "01db67b6e86c0c2f81d5247b79533ada4e4cd221", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-21T20:45:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:18:50.000Z", "max_issues_repo_path": "func/calcSeries.cpp", "max_issues_repo_name": "The220th/easybenchk", "max_issues_repo_head_hexsha": "01db67b6e86c0c2f81d5247b79533ada4e4cd221", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "func/calcSeries.cpp", "max_forks_repo_name": "The220th/easybenchk", "max_forks_repo_head_hexsha": "01db67b6e86c0c2f81d5247b79533ada4e4cd221", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6078431373, "max_line_length": 69, "alphanum_fraction": 0.5089567966, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5381656286841354}}
{"text": "#include \"thermalDistribution.h\"\n\n\n#include \"maxwellJuttner.h\"\n#include \"modelParameters.h\"\n\n//#include <fmath/RungeKutta.h>\n#include <fparameters/Dimension.h>\n#include <fparameters/SpaceIterator.h>\n#include <fparameters/parameters.h>\n\n#include <fmath/physics.h>\n\n#include <boost/math/special_functions/bessel.hpp>\n\nvoid thermalDistribution(Particle& p, State& st)\n{\n\tdouble Erest = p.mass*cLight2;\n\t\n\tdouble gMin = p.emin()/Erest;\n\tdouble gMax = p.emax()/Erest;\n\t\n\tp.ps.iterate([&](const SpaceIterator& i) {\n\t//p.distribution.fill ([&](const SpaceIterator& i){\n\t\t\n\t\t//const double E = i.val(DIM_E);\n\t\tdouble r = i.val(DIM_R);\n\t\t\n\t\tdouble norm_temp, A;\n\n\t\tif(p.id == \"electron\"){\n\t\t\tnorm_temp = boltzmann*st.tempElectrons.get(i)/(Erest);\n\t\t\tA = st.denf_e.get(i); \n\t\t}\n\t\telse if(p.id == \"proton\"){\n\t\t\tnorm_temp = boltzmann*st.tempIons.get(i)/(Erest);\n\t\t\tA = st.denf_i.get(i); \n\t\t}\n\t\t\n\t\t//double K2 =  boost::math::cyl_bessel_k(2, 1.0/norm_temp); //bessk(2, 1.0/norm_temp);\n\t\t\n\t\t\n\t\tp.ps.iterate([&](const SpaceIterator& j) {\n\t\t\t\t\n\t\t\tconst double E = j.val(DIM_E);\n\t\t\tdouble g = E/Erest;\n\t\t\t\n\t\t\tdouble result =  maxwellRel(g, norm_temp, A/Erest);\n\t\t\t\n\t\t\tp.distribution.set(j,result); //en unidades de cm^-3 erg^-1\n\t\t\t\t\t\t\n\t\t}, { -1, i.coord[DIM_R]} );\n\t\t\n\t}, { 0, -1} );\n\t\n\t\n}", "meta": {"hexsha": "d780ecf26d3bd72a0b1cf2c328534a7fa4127982", "size": 1272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/adaf/thermalDistribution.cpp", "max_stars_repo_name": "eduardomgutierrez/RIAF_radproc", "max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z", "max_issues_repo_path": "src/adaf/thermalDistribution.cpp", "max_issues_repo_name": "eduardomgutierrez/RIAF_radproc", "max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/adaf/thermalDistribution.cpp", "max_forks_repo_name": "eduardomgutierrez/RIAF_radproc", "max_forks_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_forks_repo_licenses": ["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.3157894737, "max_line_length": 88, "alphanum_fraction": 0.6399371069, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642526773001, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5380839038692588}}
{"text": "//\n// Copyright (c) 2015-2016,2018 CNRS\n// Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.\n//\n\n#include <iostream>\n\n#include \"pinocchio/math/fwd.hpp\"\n#include \"pinocchio/spatial/force.hpp\"\n#include \"pinocchio/spatial/motion.hpp\"\n#include \"pinocchio/spatial/se3.hpp\"\n#include \"pinocchio/spatial/inertia.hpp\"\n#include \"pinocchio/multibody/joint/joint-revolute.hpp\"\n#include \"pinocchio/multibody/joint/joint-revolute-unaligned.hpp\"\n#include \"pinocchio/multibody/joint/joint-revolute-unbounded.hpp\"\n#include \"pinocchio/multibody/joint/joint-spherical.hpp\"\n#include \"pinocchio/multibody/joint/joint-spherical-ZYX.hpp\"\n#include \"pinocchio/multibody/joint/joint-prismatic.hpp\"\n#include \"pinocchio/multibody/joint/joint-prismatic-unaligned.hpp\"\n#include \"pinocchio/multibody/joint/joint-translation.hpp\"\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/compute-all-terms.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\n//#define VERBOSE\n\nusing namespace pinocchio;\n\ntemplate <typename JoinData_t>\nvoid printOutJointData(\n#ifdef VERBOSE\n  const Eigen::VectorXd & q,\n  const Eigen::VectorXd & q_dot,\n  const JoinData_t & joint_data)\n{\n  using namespace std;\n  \n  cout << \"q: \" << q.transpose () << endl;\n  cout << \"q_dot: \" << q_dot.transpose () << endl;\n  cout << \"Joint configuration:\" << endl << joint_data.M << endl;\n  cout << \"v_J:\\n\" << (Motion) joint_data.v << endl;\n  cout << \"c_J:\\n\" << (Motion) joint_data.c << endl;\n}\n#else\nconst Eigen::VectorXd &,\nconst Eigen::VectorXd &,\nconst JoinData_t &)\n{}\n#endif\n\ntemplate<typename D>\nvoid addJointAndBody(Model & model, const JointModelBase<D> & jmodel, const Model::JointIndex parent_id, const SE3 & joint_placement, const std::string & joint_name, const Inertia & Y)\n{\n  Model::JointIndex idx;\n  \n  idx = model.addJoint(parent_id,jmodel,joint_placement,joint_name);\n  model.appendBodyToJoint(idx,Y);\n}\n\nBOOST_AUTO_TEST_SUITE(JointRevoluteUnaligned)\n\nBOOST_AUTO_TEST_CASE(vsRX)\n{\n  using namespace pinocchio;\n  typedef Eigen::Matrix <double, 3, 1> Vector3;\n  typedef Eigen::Matrix <double, 3, 3> Matrix3;\n\n  Eigen::Vector3d axis;\n  axis << 1.0, 0.0, 0.0;\n\n  Model modelRX, modelRevoluteUnaligned;\n\n  Inertia inertia (1., Vector3 (0.5, 0., 0.0), Matrix3::Identity ());\n  SE3 pos(1); pos.translation() = SE3::LinearType(1.,0.,0.);\n\n  JointModelRevoluteUnaligned joint_model_RU(axis);\n  \n  addJointAndBody(modelRX,JointModelRX(),0,pos,\"rx\",inertia);\n  addJointAndBody(modelRevoluteUnaligned,joint_model_RU,0,pos,\"revolute-unaligned\",inertia);\n\n  Data dataRX(modelRX);\n  Data dataRevoluteUnaligned(modelRevoluteUnaligned);\n\n  Eigen::VectorXd q = Eigen::VectorXd::Ones (modelRX.nq);\n  Eigen::VectorXd v = Eigen::VectorXd::Ones (modelRX.nv);\n  Eigen::VectorXd tauRX = Eigen::VectorXd::Ones (modelRX.nv);\n  Eigen::VectorXd tauRevoluteUnaligned = Eigen::VectorXd::Ones (modelRevoluteUnaligned.nv);\n  Eigen::VectorXd aRX = Eigen::VectorXd::Ones (modelRX.nv);\n  Eigen::VectorXd aRevoluteUnaligned(aRX);\n\n  forwardKinematics(modelRX, dataRX, q, v);\n  forwardKinematics(modelRevoluteUnaligned, dataRevoluteUnaligned, q, v);\n\n  computeAllTerms(modelRX, dataRX, q, v);\n  computeAllTerms(modelRevoluteUnaligned, dataRevoluteUnaligned, q, v);\n\n  BOOST_CHECK(dataRevoluteUnaligned.oMi[1].isApprox(dataRX.oMi[1]));\n  BOOST_CHECK(dataRevoluteUnaligned.liMi[1].isApprox(dataRX.liMi[1]));\n  BOOST_CHECK(dataRevoluteUnaligned.Ycrb[1].matrix().isApprox(dataRX.Ycrb[1].matrix()));\n  BOOST_CHECK(dataRevoluteUnaligned.f[1].toVector().isApprox(dataRX.f[1].toVector()));\n  \n  BOOST_CHECK(dataRevoluteUnaligned.nle.isApprox(dataRX.nle));\n  BOOST_CHECK(dataRevoluteUnaligned.com[0].isApprox(dataRX.com[0]));\n\n  // InverseDynamics == rnea\n  tauRX = rnea(modelRX, dataRX, q, v, aRX);\n  tauRevoluteUnaligned = rnea(modelRevoluteUnaligned, dataRevoluteUnaligned, q, v, aRevoluteUnaligned);\n\n  BOOST_CHECK(tauRX.isApprox(tauRevoluteUnaligned));\n\n  // ForwardDynamics == aba\n  Eigen::VectorXd aAbaRX = aba(modelRX,dataRX, q, v, tauRX);\n  Eigen::VectorXd aAbaRevoluteUnaligned = aba(modelRevoluteUnaligned,dataRevoluteUnaligned, q, v, tauRevoluteUnaligned);\n\n  BOOST_CHECK(aAbaRX.isApprox(aAbaRevoluteUnaligned));\n\n  // CRBA\n  crba(modelRX, dataRX,q);\n  crba(modelRevoluteUnaligned, dataRevoluteUnaligned, q);\n\n  BOOST_CHECK(dataRX.M.isApprox(dataRevoluteUnaligned.M));\n   \n  // Jacobian\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobianRX;jacobianRX.resize(6,1); jacobianRX.setZero();\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobianRevoluteUnaligned;jacobianRevoluteUnaligned.resize(6,1);jacobianRevoluteUnaligned.setZero();\n  computeJointJacobians(modelRX, dataRX, q);\n  computeJointJacobians(modelRevoluteUnaligned, dataRevoluteUnaligned, q);\n  getJointJacobian(modelRX, dataRX, 1, LOCAL, jacobianRX);\n  getJointJacobian(modelRevoluteUnaligned, dataRevoluteUnaligned, 1, LOCAL, jacobianRevoluteUnaligned);\n\n\n  BOOST_CHECK(jacobianRX.isApprox(jacobianRevoluteUnaligned));\n}\nBOOST_AUTO_TEST_SUITE_END ()\n\nBOOST_AUTO_TEST_SUITE (JointPrismaticUnaligned)\n  \n  BOOST_AUTO_TEST_CASE(spatial)\n  {\n    SE3 M(SE3::Random());\n    Motion v(Motion::Random());\n    \n    MotionPrismaticUnaligned mp(MotionPrismaticUnaligned::Vector3(1.,2.,3.),6.);\n    Motion mp_dense(mp);\n    \n    BOOST_CHECK(M.act(mp).isApprox(M.act(mp_dense)));\n    BOOST_CHECK(M.actInv(mp).isApprox(M.actInv(mp_dense)));\n    \n    BOOST_CHECK(v.cross(mp).isApprox(v.cross(mp_dense)));\n  }\n\nBOOST_AUTO_TEST_CASE (vsPX)\n{\n  using namespace pinocchio;\n  typedef Eigen::Matrix <double, 3, 1> Vector3;\n  typedef Eigen::Matrix <double, 3, 3> Matrix3;\n\n  Eigen::Vector3d axis;\n  axis << 1.0, 0.0, 0.0;\n\n  Model modelPX, modelPrismaticUnaligned;\n\n  Inertia inertia (1., Vector3 (0.5, 0., 0.0), Matrix3::Identity ());\n  SE3 pos(1); pos.translation() = SE3::LinearType(1.,0.,0.);\n\n  JointModelPrismaticUnaligned joint_model_PU(axis);\n  \n  addJointAndBody(modelPX,JointModelPX(),0,pos,\"px\",inertia);\n  addJointAndBody(modelPrismaticUnaligned,joint_model_PU,0,pos,\"prismatic-unaligned\",inertia);\n\n  Data dataPX(modelPX);\n  Data dataPrismaticUnaligned(modelPrismaticUnaligned);\n\n  Eigen::VectorXd q = Eigen::VectorXd::Ones (modelPX.nq);\n  Eigen::VectorXd v = Eigen::VectorXd::Ones (modelPX.nv);\n  Eigen::VectorXd tauPX = Eigen::VectorXd::Ones (modelPX.nv);\n  Eigen::VectorXd tauPrismaticUnaligned = Eigen::VectorXd::Ones (modelPrismaticUnaligned.nv);\n  Eigen::VectorXd aPX = Eigen::VectorXd::Ones (modelPX.nv);\n  Eigen::VectorXd aPrismaticUnaligned(aPX);\n  \n  forwardKinematics(modelPX, dataPX, q, v);\n  forwardKinematics(modelPrismaticUnaligned, dataPrismaticUnaligned, q, v);\n\n  computeAllTerms(modelPX, dataPX, q, v);\n  computeAllTerms(modelPrismaticUnaligned, dataPrismaticUnaligned, q, v);\n\n  BOOST_CHECK(dataPrismaticUnaligned.oMi[1].isApprox(dataPX.oMi[1]));\n  BOOST_CHECK(dataPrismaticUnaligned.liMi[1].isApprox(dataPX.liMi[1]));\n  BOOST_CHECK(dataPrismaticUnaligned.Ycrb[1].matrix().isApprox(dataPX.Ycrb[1].matrix()));\n  BOOST_CHECK(dataPrismaticUnaligned.f[1].toVector().isApprox(dataPX.f[1].toVector()));\n  \n  BOOST_CHECK(dataPrismaticUnaligned.nle.isApprox(dataPX.nle));\n  BOOST_CHECK(dataPrismaticUnaligned.com[0].isApprox(dataPX.com[0]));\n\n  // InverseDynamics == rnea\n  tauPX = rnea(modelPX, dataPX, q, v, aPX);\n  tauPrismaticUnaligned = rnea(modelPrismaticUnaligned, dataPrismaticUnaligned, q, v, aPrismaticUnaligned);\n\n  BOOST_CHECK(tauPX.isApprox(tauPrismaticUnaligned));\n\n  // ForwardDynamics == aba\n  Eigen::VectorXd aAbaPX = aba(modelPX,dataPX, q, v, tauPX);\n  Eigen::VectorXd aAbaPrismaticUnaligned = aba(modelPrismaticUnaligned,dataPrismaticUnaligned, q, v, tauPrismaticUnaligned);\n\n  BOOST_CHECK(aAbaPX.isApprox(aAbaPrismaticUnaligned));\n\n  // crba\n  crba(modelPX, dataPX,q);\n  crba(modelPrismaticUnaligned, dataPrismaticUnaligned, q);\n\n  BOOST_CHECK(dataPX.M.isApprox(dataPrismaticUnaligned.M));\n   \n  // Jacobian\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobianPX;jacobianPX.resize(6,1); jacobianPX.setZero();\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobianPrismaticUnaligned;jacobianPrismaticUnaligned.resize(6,1);jacobianPrismaticUnaligned.setZero();\n  computeJointJacobians(modelPX, dataPX, q);\n  computeJointJacobians(modelPrismaticUnaligned, dataPrismaticUnaligned, q);\n  getJointJacobian(modelPX, dataPX, 1, LOCAL, jacobianPX);\n  getJointJacobian(modelPrismaticUnaligned, dataPrismaticUnaligned, 1, LOCAL, jacobianPrismaticUnaligned);\n\n  BOOST_CHECK(jacobianPX.isApprox(jacobianPrismaticUnaligned));\n}\nBOOST_AUTO_TEST_SUITE_END ()\n\nBOOST_AUTO_TEST_SUITE (JointSpherical)\n  \n  BOOST_AUTO_TEST_CASE(spatial)\n  {\n    SE3 M(SE3::Random());\n    Motion v(Motion::Random());\n    \n    MotionSpherical mp(MotionSpherical::Vector3(1.,2.,3.));\n    Motion mp_dense(mp);\n    \n    BOOST_CHECK(M.act(mp).isApprox(M.act(mp_dense)));\n    BOOST_CHECK(M.actInv(mp).isApprox(M.actInv(mp_dense)));\n    \n    BOOST_CHECK(v.cross(mp).isApprox(v.cross(mp_dense)));\n  }\n\nBOOST_AUTO_TEST_CASE (vsFreeFlyer)\n{\n  using namespace pinocchio;\n  typedef Eigen::Matrix <double, 3, 1> Vector3;\n  typedef Eigen::Matrix <double, 6, 1> Vector6;\n  typedef Eigen::Matrix <double, 7, 1> VectorFF;\n  typedef Eigen::Matrix <double, 3, 3> Matrix3;\n\n  Model modelSpherical, modelFreeflyer;\n\n  Inertia inertia (1., Vector3 (0.5, 0., 0.0), Matrix3::Identity ());\n  SE3 pos(1); pos.translation() = SE3::LinearType(1.,0.,0.);\n\n  addJointAndBody(modelSpherical,JointModelSpherical(),0,pos,\"spherical\",inertia);\n  addJointAndBody(modelFreeflyer,JointModelFreeFlyer(),0,pos,\"free-flyer\",inertia);\n\n  Data dataSpherical(modelSpherical);\n  Data dataFreeFlyer(modelFreeflyer);\n\n  Eigen::VectorXd q = Eigen::VectorXd::Ones (modelSpherical.nq);q.normalize();\n  VectorFF qff; qff << 0, 0, 0, q[0], q[1], q[2], q[3];\n  Eigen::VectorXd v = Eigen::VectorXd::Ones (modelSpherical.nv);\n  Vector6 vff; vff << 0, 0, 0, 1, 1, 1;\n  Eigen::VectorXd tauSpherical = Eigen::VectorXd::Ones (modelSpherical.nv);\n  Eigen::VectorXd tauff; tauff.resize(7); tauff << 0,0,0,1,1,1,1;\n  Eigen::VectorXd aSpherical = Eigen::VectorXd::Ones (modelSpherical.nv);\n  Eigen::VectorXd aff(vff);\n  \n  forwardKinematics(modelSpherical, dataSpherical, q, v);\n  forwardKinematics(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  computeAllTerms(modelSpherical, dataSpherical, q, v);\n  computeAllTerms(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  BOOST_CHECK(dataFreeFlyer.oMi[1].isApprox(dataSpherical.oMi[1]));\n  BOOST_CHECK(dataFreeFlyer.liMi[1].isApprox(dataSpherical.liMi[1]));\n  BOOST_CHECK(dataFreeFlyer.Ycrb[1].matrix().isApprox(dataSpherical.Ycrb[1].matrix()));\n  BOOST_CHECK(dataFreeFlyer.f[1].toVector().isApprox(dataSpherical.f[1].toVector()));\n  \n  Eigen::VectorXd nle_expected_ff(3); nle_expected_ff << dataFreeFlyer.nle[3],\n                                                         dataFreeFlyer.nle[4],\n                                                         dataFreeFlyer.nle[5]\n                                                         ;\n  BOOST_CHECK(nle_expected_ff.isApprox(dataSpherical.nle));\n  BOOST_CHECK(dataFreeFlyer.com[0].isApprox(dataSpherical.com[0]));\n\n  // InverseDynamics == rnea\n  tauSpherical = rnea(modelSpherical, dataSpherical, q, v, aSpherical);\n  tauff = rnea(modelFreeflyer, dataFreeFlyer, qff, vff, aff);\n\n  Vector3 tau_expected; tau_expected << tauff(3), tauff(4), tauff(5);\n  BOOST_CHECK(tauSpherical.isApprox(tau_expected));\n\n  // ForwardDynamics == aba\n  Eigen::VectorXd aAbaSpherical = aba(modelSpherical,dataSpherical, q, v, tauSpherical);\n  Eigen::VectorXd aAbaFreeFlyer = aba(modelFreeflyer,dataFreeFlyer, qff, vff, tauff);\n  Vector3 a_expected; a_expected << aAbaFreeFlyer[3],\n                                    aAbaFreeFlyer[4],\n                                    aAbaFreeFlyer[5]\n                                    ;\n  BOOST_CHECK(aAbaSpherical.isApprox(a_expected));\n\n  // crba\n  crba(modelSpherical, dataSpherical,q);\n  crba(modelFreeflyer, dataFreeFlyer, qff);\n\n  Eigen::Matrix<double, 3, 3> M_expected(dataFreeFlyer.M.bottomRightCorner<3,3>());\n\n  BOOST_CHECK(dataSpherical.M.isApprox(M_expected));\n   \n  // Jacobian\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian_planar;jacobian_planar.resize(6,3); jacobian_planar.setZero();\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian_ff;jacobian_ff.resize(6,6);jacobian_ff.setZero();\n  computeJointJacobians(modelSpherical, dataSpherical, q);\n  computeJointJacobians(modelFreeflyer, dataFreeFlyer, qff);\n  getJointJacobian(modelSpherical, dataSpherical, 1, LOCAL, jacobian_planar);\n  getJointJacobian(modelFreeflyer, dataFreeFlyer, 1, LOCAL, jacobian_ff);\n\n\n  Eigen::Matrix<double, 6, 3> jacobian_expected; jacobian_expected << jacobian_ff.col(3),\n                                                                      jacobian_ff.col(4),\n                                                                      jacobian_ff.col(5)\n                                                                      ;\n\n  BOOST_CHECK(jacobian_planar.isApprox(jacobian_expected));\n\n}\nBOOST_AUTO_TEST_SUITE_END ()\n\n\nBOOST_AUTO_TEST_SUITE (JointSphericalZYX)\n  \n  BOOST_AUTO_TEST_CASE(spatial)\n  {\n    SE3 M(SE3::Random());\n    Motion v(Motion::Random());\n    \n    MotionSpherical mp(MotionSpherical::Vector3(1.,2.,3.));\n    Motion mp_dense(mp);\n    \n    BOOST_CHECK(M.act(mp).isApprox(M.act(mp_dense)));\n    BOOST_CHECK(M.actInv(mp).isApprox(M.actInv(mp_dense)));\n    \n    BOOST_CHECK(v.cross(mp).isApprox(v.cross(mp_dense)));\n  }\n\nBOOST_AUTO_TEST_CASE (vsFreeFlyer)\n{\n  // WARNIG : Dynamic algorithm's results cannot be compared to FreeFlyer's ones because \n  // of the representation of the rotation and the ConstraintSubspace difference.\n  using namespace pinocchio;\n  typedef Eigen::Matrix <double, 3, 1> Vector3;\n  typedef Eigen::Matrix <double, 6, 1> Vector6;\n  typedef Eigen::Matrix <double, 7, 1> VectorFF;\n  typedef Eigen::Matrix <double, 3, 3> Matrix3;\n\n  Model modelSphericalZYX, modelFreeflyer;\n\n  Inertia inertia (1., Vector3 (0.5, 0., 0.0), Matrix3::Identity ());\n  SE3 pos(1); pos.translation() = SE3::LinearType(1.,0.,0.);\n\n  addJointAndBody(modelSphericalZYX,JointModelSphericalZYX(),0,pos,\"spherical-zyx\",inertia);\n  addJointAndBody(modelFreeflyer,JointModelFreeFlyer(),0,pos,\"free-flyer\",inertia);\n\n  Data dataSphericalZYX(modelSphericalZYX);\n  Data dataFreeFlyer(modelFreeflyer);\n\n  Eigen::AngleAxisd rollAngle(1, Eigen::Vector3d::UnitZ());\n  Eigen::AngleAxisd yawAngle(1, Eigen::Vector3d::UnitY());\n  Eigen::AngleAxisd pitchAngle(1, Eigen::Vector3d::UnitX());\n  Eigen::Quaterniond q_sph = rollAngle * yawAngle * pitchAngle;\n  \n  Eigen::VectorXd q = Eigen::VectorXd::Ones (modelSphericalZYX.nq);\n  VectorFF qff; qff << 0, 0, 0, q_sph.x(), q_sph.y(), q_sph.z(), q_sph.w();\n  Eigen::VectorXd v = Eigen::VectorXd::Ones (modelSphericalZYX.nv);\n  Vector6 vff; vff << 0, 0, 0, 1, 1, 1;\n  Eigen::VectorXd tauSpherical = Eigen::VectorXd::Ones (modelSphericalZYX.nv);\n  Eigen::VectorXd tauff; tauff.resize(6); tauff << 0,0,0,1,1,1;\n  Eigen::VectorXd aSpherical = Eigen::VectorXd::Ones (modelSphericalZYX.nv);\n  Eigen::VectorXd aff(vff);\n  \n  forwardKinematics(modelSphericalZYX, dataSphericalZYX, q, v);\n  forwardKinematics(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  computeAllTerms(modelSphericalZYX, dataSphericalZYX, q, v);\n  computeAllTerms(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  BOOST_CHECK(dataFreeFlyer.oMi[1].isApprox(dataSphericalZYX.oMi[1]));\n  BOOST_CHECK(dataFreeFlyer.liMi[1].isApprox(dataSphericalZYX.liMi[1]));\n  BOOST_CHECK(dataFreeFlyer.Ycrb[1].matrix().isApprox(dataSphericalZYX.Ycrb[1].matrix()));\n\n  BOOST_CHECK(dataFreeFlyer.com[0].isApprox(dataSphericalZYX.com[0]));\n}\n\nBOOST_AUTO_TEST_CASE ( test_rnea )\n{\n  using namespace pinocchio;\n  typedef Eigen::Matrix <double, 3, 1> Vector3;\n  typedef Eigen::Matrix <double, 3, 3> Matrix3;\n\n  Model model;\n  Inertia inertia (1., Vector3 (0.5, 0., 0.0), Matrix3::Identity ());\n\n  addJointAndBody(model,JointModelSphericalZYX(),model.getJointId(\"universe\"),SE3::Identity(),\"root\",inertia);\n\n  Data data (model);\n\n  Eigen::VectorXd q = Eigen::VectorXd::Zero (model.nq);\n  Eigen::VectorXd v = Eigen::VectorXd::Zero (model.nv);\n  Eigen::VectorXd a = Eigen::VectorXd::Zero (model.nv);\n\n  rnea (model, data, q, v, a);\n  Vector3 tau_expected (0., -4.905, 0.);\n\n  BOOST_CHECK (tau_expected.isApprox(data.tau, 1e-14));\n\n  q = Eigen::VectorXd::Ones (model.nq);\n  v = Eigen::VectorXd::Ones (model.nv);\n  a = Eigen::VectorXd::Ones (model.nv);\n\n  rnea (model, data, q, v, a);\n  tau_expected << -0.53611600195085, -0.74621832606188, -0.38177329067604;\n\n  BOOST_CHECK (tau_expected.isApprox(data.tau, 1e-12));\n\n  q << 3, 2, 1;\n  v = Eigen::VectorXd::Ones (model.nv);\n  a = Eigen::VectorXd::Ones (model.nv);\n\n  rnea (model, data, q, v, a);\n  tau_expected << 0.73934458094049,  2.7804530848031, 0.50684940972146;\n\n  BOOST_CHECK (tau_expected.isApprox(data.tau, 1e-12));\n}\n\nBOOST_AUTO_TEST_CASE ( test_crba )\n{\n  using namespace pinocchio;\n  using namespace std;\n  typedef Eigen::Matrix <double, 3, 1> Vector3;\n  typedef Eigen::Matrix <double, 3, 3> Matrix3;\n\n  Model model;\n  Inertia inertia (1., Vector3 (0.5, 0., 0.0), Matrix3::Identity ());\n\n  addJointAndBody(model,JointModelSphericalZYX(),model.getJointId(\"universe\"),SE3::Identity(),\"root\",inertia);\n\n  Data data (model);\n\n  Eigen::VectorXd q (Eigen::VectorXd::Zero (model.nq));\n  Eigen::MatrixXd M_expected (model.nv,model.nv);\n\n  crba (model, data, q);\n  M_expected <<\n  1.25,    0,    0,\n  0, 1.25,    0,\n  0,    0,    1;\n\n  BOOST_CHECK (M_expected.isApprox(data.M, 1e-14));\n\n  q = Eigen::VectorXd::Ones (model.nq);\n\n  crba (model, data, q);\n  M_expected <<\n  1.0729816454316, -5.5511151231258e-17,     -0.8414709848079,\n  -5.5511151231258e-17,                 1.25,                    0,\n  -0.8414709848079,                    0,                    1;\n\n  BOOST_CHECK (M_expected.isApprox(data.M, 1e-12));\n\n  q << 3, 2, 1;\n\n  crba (model, data, q);\n  M_expected <<\n  1.043294547392, 2.7755575615629e-17,   -0.90929742682568,\n  0,                1.25,                   0,\n  -0.90929742682568,                   0,                  1;\n\n  BOOST_CHECK (M_expected.isApprox(data.M, 1e-10));\n}\n\nBOOST_AUTO_TEST_SUITE_END ()\n\nBOOST_AUTO_TEST_SUITE ( JointPrismatic )\n  \nBOOST_AUTO_TEST_CASE(spatial)\n{\n  typedef TransformPrismaticTpl<double,0,0> TransformX;\n  typedef TransformPrismaticTpl<double,0,1> TransformY;\n  typedef TransformPrismaticTpl<double,0,2> TransformZ;\n  \n  typedef SE3::Vector3 Vector3;\n  \n  const double displacement = 0.2;\n  SE3 Mplain, Mrand(SE3::Random());\n  \n  TransformX Mx(displacement);\n  Mplain = Mx;\n  BOOST_CHECK(Mplain.translation().isApprox(Vector3(displacement,0,0)));\n  BOOST_CHECK(Mplain.rotation().isIdentity());\n  BOOST_CHECK((Mrand*Mplain).isApprox(Mrand*Mx));\n  \n  TransformY My(displacement);\n  Mplain = My;\n  BOOST_CHECK(Mplain.translation().isApprox(Vector3(0,displacement,0)));\n  BOOST_CHECK(Mplain.rotation().isIdentity());\n  BOOST_CHECK((Mrand*Mplain).isApprox(Mrand*My));\n  \n  TransformZ Mz(displacement);\n  Mplain = Mz;\n  BOOST_CHECK(Mplain.translation().isApprox(Vector3(0,0,displacement)));\n  BOOST_CHECK(Mplain.rotation().isIdentity());\n  BOOST_CHECK((Mrand*Mplain).isApprox(Mrand*Mz));\n  \n  SE3 M(SE3::Random());\n  Motion v(Motion::Random());\n  \n  MotionPrismaticTpl<double,0,0> mp_x(2.);\n  Motion mp_dense_x(mp_x);\n  \n  BOOST_CHECK(M.act(mp_x).isApprox(M.act(mp_dense_x)));\n  BOOST_CHECK(M.actInv(mp_x).isApprox(M.actInv(mp_dense_x)));\n  \n  BOOST_CHECK(v.cross(mp_x).isApprox(v.cross(mp_dense_x)));\n  \n  MotionPrismaticTpl<double,0,1> mp_y(2.);\n  Motion mp_dense_y(mp_y);\n  \n  BOOST_CHECK(M.act(mp_y).isApprox(M.act(mp_dense_y)));\n  BOOST_CHECK(M.actInv(mp_y).isApprox(M.actInv(mp_dense_y)));\n  \n  BOOST_CHECK(v.cross(mp_y).isApprox(v.cross(mp_dense_y)));\n  \n  MotionPrismaticTpl<double,0,2> mp_z(2.);\n  Motion mp_dense_z(mp_z);\n  \n  BOOST_CHECK(M.act(mp_z).isApprox(M.act(mp_dense_z)));\n  BOOST_CHECK(M.actInv(mp_z).isApprox(M.actInv(mp_dense_z)));\n  \n  BOOST_CHECK(v.cross(mp_z).isApprox(v.cross(mp_dense_z)));\n}\n\nBOOST_AUTO_TEST_CASE ( test_kinematics )\n{\n  using namespace pinocchio;\n\n\n  Motion expected_v_J (Motion::Zero ());\n  Motion expected_c_J (Motion::Zero ());\n\n  SE3 expected_configuration (SE3::Identity ());\n\n  JointDataPX joint_data;\n  JointModelPX joint_model;\n\n  joint_model.setIndexes (0, 0, 0);\n\n  Eigen::VectorXd q (Eigen::VectorXd::Zero (1));\n  Eigen::VectorXd q_dot (Eigen::VectorXd::Zero (1));\n\n  // -------\n  q << 0. ;\n  q_dot << 0.;\n\n  joint_model.calc (joint_data, q, q_dot);\n\n  printOutJointData <JointDataPX> (q, q_dot, joint_data);\n\n  BOOST_CHECK (expected_configuration.rotation ().isApprox(joint_data.M.rotation(), 1e-12));\n  BOOST_CHECK (expected_configuration.translation ().isApprox(joint_data.M.translation (), 1e-12));\n  BOOST_CHECK (expected_v_J.toVector ().isApprox(((Motion) joint_data.v).toVector(), 1e-12));\n  BOOST_CHECK (expected_c_J.toVector ().isApprox(((Motion) joint_data.c).toVector(), 1e-12));\n\n  // -------\n  q << 1.;\n  q_dot << 1.;\n\n\n  joint_model.calc (joint_data, q, q_dot);\n\n  printOutJointData <JointDataPX> (q, q_dot, joint_data);\n\n  expected_configuration.translation () << 1, 0, 0;\n\n  expected_v_J.linear () << 1., 0., 0.;\n\n  BOOST_CHECK (expected_configuration.rotation ().isApprox(joint_data.M.rotation(), 1e-12));\n  BOOST_CHECK (expected_configuration.translation ().isApprox(joint_data.M.translation (), 1e-12));\n  BOOST_CHECK (expected_v_J.toVector ().isApprox(((Motion) joint_data.v).toVector(), 1e-12));\n  BOOST_CHECK (expected_c_J.toVector ().isApprox(((Motion) joint_data.c).toVector(), 1e-12));\n}\n\nBOOST_AUTO_TEST_CASE ( test_rnea )\n{\n  using namespace pinocchio;\n  typedef Eigen::Matrix <double, 3, 1> Vector3;\n  typedef Eigen::Matrix <double, 3, 3> Matrix3;\n\n  Model model;\n  Inertia inertia (1., Vector3 (0.5, 0., 0.0), Matrix3::Identity ());\n\n  addJointAndBody(model,JointModelPX(),model.getJointId(\"universe\"),SE3::Identity(),\"root\",inertia);\n\n  Data data (model);\n\n  Eigen::VectorXd q (Eigen::VectorXd::Zero (model.nq));\n  Eigen::VectorXd v (Eigen::VectorXd::Zero (model.nv));\n  Eigen::VectorXd a (Eigen::VectorXd::Zero (model.nv));\n\n  rnea (model, data, q, v, a);\n\n  Eigen::VectorXd tau_expected (Eigen::VectorXd::Zero (model.nq));\n  tau_expected  << 0;\n\n  BOOST_CHECK (tau_expected.isApprox(data.tau, 1e-14));\n\n  // -----\n  q = Eigen::VectorXd::Ones (model.nq);\n  v = Eigen::VectorXd::Ones (model.nv);\n  a = Eigen::VectorXd::Ones (model.nv);\n\n  rnea (model, data, q, v, a);\n  tau_expected << 1;\n\n  BOOST_CHECK (tau_expected.isApprox(data.tau, 1e-12));\n\n  q << 3;\n  v = Eigen::VectorXd::Ones (model.nv);\n  a = Eigen::VectorXd::Ones (model.nv);\n\n  rnea (model, data, q, v, a);\n  tau_expected << 1;\n\n  BOOST_CHECK (tau_expected.isApprox(data.tau, 1e-12));\n}\n\nBOOST_AUTO_TEST_CASE ( test_crba )\n{\n  using namespace pinocchio;\n  using namespace std;\n  typedef Eigen::Matrix <double, 3, 1> Vector3;\n  typedef Eigen::Matrix <double, 3, 3> Matrix3;\n\n  Model model;\n  Inertia inertia (1., Vector3 (0.5, 0., 0.0), Matrix3::Identity ());\n\n  addJointAndBody(model,JointModelPX(),model.getJointId(\"universe\"),SE3::Identity(),\"root\",inertia);\n\n  Data data (model);\n\n  Eigen::VectorXd q (Eigen::VectorXd::Zero (model.nq));\n  Eigen::MatrixXd M_expected (model.nv,model.nv);\n\n  crba (model, data, q);\n  M_expected << 1.0;\n\n  BOOST_CHECK (M_expected.isApprox(data.M, 1e-14));\n\n  q = Eigen::VectorXd::Ones (model.nq);\n\n  crba (model, data, q);\n\n  BOOST_CHECK (M_expected.isApprox(data.M, 1e-12));\n\n  q << 3;\n\n  crba (model, data, q);\n  \n  BOOST_CHECK (M_expected.isApprox(data.M, 1e-10));\n}\n\nBOOST_AUTO_TEST_SUITE_END ()\n\nBOOST_AUTO_TEST_SUITE (JointPlanar)\n  \nBOOST_AUTO_TEST_CASE(spatial)\n{\n  SE3 M(SE3::Random());\n  Motion v(Motion::Random());\n  \n  MotionPlanar mp(1.,2.,3.);\n  Motion mp_dense(mp);\n  \n  BOOST_CHECK(M.act(mp).isApprox(M.act(mp_dense)));\n  BOOST_CHECK(M.actInv(mp).isApprox(M.actInv(mp_dense)));\n  \n  BOOST_CHECK(v.cross(mp).isApprox(v.cross(mp_dense)));\n}\n\nBOOST_AUTO_TEST_CASE (vsFreeFlyer)\n{\n  using namespace pinocchio;\n  typedef Eigen::Matrix <double, 3, 1> Vector3;\n  typedef Eigen::Matrix <double, 6, 1> Vector6;\n  typedef Eigen::Matrix <double, 4, 1> VectorPl;\n  typedef Eigen::Matrix <double, 7, 1> VectorFF;\n  typedef Eigen::Matrix <double, 3, 3> Matrix3;\n\n  Model modelPlanar, modelFreeflyer;\n\n  Inertia inertia (1., Vector3 (0.5, 0., 0.0), Matrix3::Identity ());\n  SE3 pos(1); pos.translation() = SE3::LinearType(1.,0.,0.);\n\n  addJointAndBody(modelPlanar,JointModelPlanar(),0,SE3::Identity(),\"planar\",inertia);\n  addJointAndBody(modelFreeflyer,JointModelFreeFlyer(),0,SE3::Identity(),\"free-flyer\",inertia);\n\n  Data dataPlanar(modelPlanar);\n  Data dataFreeFlyer(modelFreeflyer);\n\n  VectorPl q; q << 1, 1, 0, 1; // Angle is PI /2;\n  VectorFF qff; qff << 1, 1, 0, 0, 0, sqrt(2)/2, sqrt(2)/2 ;\n  Eigen::VectorXd v = Eigen::VectorXd::Ones (modelPlanar.nv);\n  Vector6 vff; vff << 1, 1, 0, 0, 0, 1;\n  Eigen::VectorXd tauPlanar = Eigen::VectorXd::Ones (modelPlanar.nv);\n  Eigen::VectorXd tauff = Eigen::VectorXd::Ones (modelFreeflyer.nv);\n  Eigen::VectorXd aPlanar = Eigen::VectorXd::Ones (modelPlanar.nv);\n  Eigen::VectorXd aff(vff);\n  \n  forwardKinematics(modelPlanar, dataPlanar, q, v);\n  forwardKinematics(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  computeAllTerms(modelPlanar, dataPlanar, q, v);\n  computeAllTerms(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  BOOST_CHECK(dataFreeFlyer.oMi[1].isApprox(dataPlanar.oMi[1]));\n  BOOST_CHECK(dataFreeFlyer.liMi[1].isApprox(dataPlanar.liMi[1]));\n  BOOST_CHECK(dataFreeFlyer.Ycrb[1].matrix().isApprox(dataPlanar.Ycrb[1].matrix()));\n  BOOST_CHECK(dataFreeFlyer.f[1].toVector().isApprox(dataPlanar.f[1].toVector()));\n  \n  Eigen::VectorXd nle_expected_ff(3); nle_expected_ff << dataFreeFlyer.nle[0],\n                                                         dataFreeFlyer.nle[1],\n                                                         dataFreeFlyer.nle[5]\n                                                         ;\n  BOOST_CHECK(nle_expected_ff.isApprox(dataPlanar.nle));\n  BOOST_CHECK(dataFreeFlyer.com[0].isApprox(dataPlanar.com[0]));\n\n  // InverseDynamics == rnea\n  tauPlanar = rnea(modelPlanar, dataPlanar, q, v, aPlanar);\n  tauff = rnea(modelFreeflyer, dataFreeFlyer, qff, vff, aff);\n\n  Vector3 tau_expected; tau_expected << tauff(0), tauff(1), tauff(5);\n  BOOST_CHECK(tauPlanar.isApprox(tau_expected));\n\n  // ForwardDynamics == aba\n  Eigen::VectorXd aAbaPlanar = aba(modelPlanar,dataPlanar, q, v, tauPlanar);\n  Eigen::VectorXd aAbaFreeFlyer = aba(modelFreeflyer,dataFreeFlyer, qff, vff, tauff);\n  Vector3 a_expected; a_expected << aAbaFreeFlyer[0],\n                                    aAbaFreeFlyer[1],\n                                    aAbaFreeFlyer[5]\n                                    ;\n  BOOST_CHECK(aAbaPlanar.isApprox(a_expected));\n\n  // crba\n  crba(modelPlanar, dataPlanar,q);\n  crba(modelFreeflyer, dataFreeFlyer, qff);\n\n  Eigen::Matrix<double, 3, 3> M_expected;\n  M_expected.block<2,2>(0,0) = dataFreeFlyer.M.block<2,2>(0,0);\n  M_expected.block<1,2>(2,0) = dataFreeFlyer.M.block<1,2>(5,0);\n  M_expected.block<2,1>(0,2) = dataFreeFlyer.M.col(5).head<2>();\n  M_expected.block<1,1>(2,2) = dataFreeFlyer.M.col(5).tail<1>();\n\n  BOOST_CHECK(dataPlanar.M.isApprox(M_expected));\n   \n  // Jacobian\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian_planar;jacobian_planar.resize(6,3); jacobian_planar.setZero();\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian_ff;jacobian_ff.resize(6,6);jacobian_ff.setZero();\n  computeJointJacobians(modelPlanar, dataPlanar, q);\n  computeJointJacobians(modelFreeflyer, dataFreeFlyer, qff);\n  getJointJacobian(modelPlanar, dataPlanar, 1, LOCAL, jacobian_planar);\n  getJointJacobian(modelFreeflyer, dataFreeFlyer, 1, LOCAL, jacobian_ff);\n\n  Eigen::Matrix<double, 6, 3> jacobian_expected; jacobian_expected << jacobian_ff.col(0),\n                                                                      jacobian_ff.col(1),\n                                                                      jacobian_ff.col(5)\n                                                                      ;\n\n  BOOST_CHECK(jacobian_planar.isApprox(jacobian_expected));\n}\nBOOST_AUTO_TEST_SUITE_END ()\n\nBOOST_AUTO_TEST_SUITE (JointTranslation)\n  \nBOOST_AUTO_TEST_CASE(spatial)\n{\n  typedef TransformTranslationTpl<double,0> TransformTranslation;\n  typedef SE3::Vector3 Vector3;\n  \n  const Vector3 displacement(Vector3::Random());\n  SE3 Mplain, Mrand(SE3::Random());\n  \n  TransformTranslation Mtrans(displacement);\n  Mplain = Mtrans;\n  BOOST_CHECK(Mplain.translation().isApprox(displacement));\n  BOOST_CHECK(Mplain.rotation().isIdentity());\n  BOOST_CHECK((Mrand*Mplain).isApprox(Mrand*Mtrans));\n  \n  SE3 M(SE3::Random());\n  Motion v(Motion::Random());\n  \n  MotionTranslation mp(MotionTranslation::Vector3(1.,2.,3.));\n  Motion mp_dense(mp);\n  \n  BOOST_CHECK(M.act(mp).isApprox(M.act(mp_dense)));\n  BOOST_CHECK(M.actInv(mp).isApprox(M.actInv(mp_dense)));\n  \n  BOOST_CHECK(v.cross(mp).isApprox(v.cross(mp_dense)));\n}\n\nBOOST_AUTO_TEST_CASE (vsFreeFlyer)\n{\n  using namespace pinocchio;\n  typedef Eigen::Matrix <double, 3, 1> Vector3;\n  typedef Eigen::Matrix <double, 6, 1> Vector6;\n  typedef Eigen::Matrix <double, 7, 1> VectorFF;\n  typedef Eigen::Matrix <double, 3, 3> Matrix3;\n\n  Model modelTranslation, modelFreeflyer;\n\n  Inertia inertia (1., Vector3 (0.5, 0., 0.0), Matrix3::Identity ());\n  SE3 pos(1); pos.translation() = SE3::LinearType(1.,0.,0.);\n\n  addJointAndBody(modelTranslation,JointModelTranslation(),0,SE3::Identity(),\"translation\",inertia);\n  addJointAndBody(modelFreeflyer,JointModelFreeFlyer(),0,SE3::Identity(),\"free-flyer\",inertia);\n\n  Data dataTranslation(modelTranslation);\n  Data dataFreeFlyer(modelFreeflyer);\n\n  Eigen::VectorXd q = Eigen::VectorXd::Ones (modelTranslation.nq);               VectorFF qff; qff << 1, 1, 1, 0, 0, 0, 1 ;\n  Eigen::VectorXd v = Eigen::VectorXd::Ones (modelTranslation.nv);               Vector6 vff; vff << 1, 1, 1, 0, 0, 0;\n  Eigen::VectorXd tauTranslation = Eigen::VectorXd::Ones (modelTranslation.nv);       Eigen::VectorXd tauff(6); tauff << 1, 1, 1, 0, 0, 0;\n  Eigen::VectorXd aTranslation = Eigen::VectorXd::Ones (modelTranslation.nv);         Eigen::VectorXd aff(vff);\n  \n  forwardKinematics(modelTranslation, dataTranslation, q, v);\n  forwardKinematics(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  computeAllTerms(modelTranslation, dataTranslation, q, v);\n  computeAllTerms(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  BOOST_CHECK(dataFreeFlyer.oMi[1].isApprox(dataTranslation.oMi[1]));\n  BOOST_CHECK(dataFreeFlyer.liMi[1].isApprox(dataTranslation.liMi[1]));\n  BOOST_CHECK(dataFreeFlyer.Ycrb[1].matrix().isApprox(dataTranslation.Ycrb[1].matrix()));\n  BOOST_CHECK(dataFreeFlyer.f[1].toVector().isApprox(dataTranslation.f[1].toVector()));\n  \n  Eigen::VectorXd nle_expected_ff(3); nle_expected_ff << dataFreeFlyer.nle[0],\n                                                         dataFreeFlyer.nle[1],\n                                                         dataFreeFlyer.nle[2]\n                                                         ;\n  BOOST_CHECK(nle_expected_ff.isApprox(dataTranslation.nle));\n  BOOST_CHECK(dataFreeFlyer.com[0].isApprox(dataTranslation.com[0]));\n\n  // InverseDynamics == rnea\n  tauTranslation = rnea(modelTranslation, dataTranslation, q, v, aTranslation);\n  tauff = rnea(modelFreeflyer, dataFreeFlyer, qff, vff, aff);\n\n  Vector3 tau_expected; tau_expected << tauff(0), tauff(1), tauff(2);\n  BOOST_CHECK(tauTranslation.isApprox(tau_expected));\n\n  // ForwardDynamics == aba\n  Eigen::VectorXd aAbaTranslation = aba(modelTranslation,dataTranslation, q, v, tauTranslation);\n  Eigen::VectorXd aAbaFreeFlyer = aba(modelFreeflyer,dataFreeFlyer, qff, vff, tauff);\n  Vector3 a_expected; a_expected << aAbaFreeFlyer[0],\n                                    aAbaFreeFlyer[1],\n                                    aAbaFreeFlyer[2]\n                                    ;\n  BOOST_CHECK(aAbaTranslation.isApprox(a_expected));\n\n  // crba\n  crba(modelTranslation, dataTranslation,q);\n  crba(modelFreeflyer, dataFreeFlyer, qff);\n\n  Eigen::Matrix<double, 3, 3> M_expected(dataFreeFlyer.M.topLeftCorner<3,3>());\n\n  BOOST_CHECK(dataTranslation.M.isApprox(M_expected));\n   \n  // Jacobian\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian_planar;jacobian_planar.resize(6,3); jacobian_planar.setZero();\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian_ff;jacobian_ff.resize(6,6);jacobian_ff.setZero();\n  computeJointJacobians(modelTranslation, dataTranslation, q);\n  computeJointJacobians(modelFreeflyer, dataFreeFlyer, qff);\n  getJointJacobian(modelTranslation, dataTranslation, 1, LOCAL, jacobian_planar);\n  getJointJacobian(modelFreeflyer, dataFreeFlyer, 1, LOCAL, jacobian_ff);\n\n\n  Eigen::Matrix<double, 6, 3> jacobian_expected; jacobian_expected << jacobian_ff.col(0),\n                                                                      jacobian_ff.col(1),\n                                                                      jacobian_ff.col(2)\n                                                                      ;\n\n  BOOST_CHECK(jacobian_planar.isApprox(jacobian_expected));\n}\nBOOST_AUTO_TEST_SUITE_END ()\n\nBOOST_AUTO_TEST_SUITE (JointRevoluteUnbounded)\n  \n  BOOST_AUTO_TEST_CASE(spatial)\n  {\n    SE3 M(SE3::Random());\n    Motion v(Motion::Random());\n    \n    MotionRevoluteTpl<double,0,0> mp_x(2.);\n    Motion mp_dense_x(mp_x);\n    \n    BOOST_CHECK(M.act(mp_x).isApprox(M.act(mp_dense_x)));\n    BOOST_CHECK(M.actInv(mp_x).isApprox(M.actInv(mp_dense_x)));\n    \n    BOOST_CHECK(v.cross(mp_x).isApprox(v.cross(mp_dense_x)));\n    \n    MotionRevoluteTpl<double,0,1> mp_y(2.);\n    Motion mp_dense_y(mp_y);\n    \n    BOOST_CHECK(M.act(mp_y).isApprox(M.act(mp_dense_y)));\n    BOOST_CHECK(M.actInv(mp_y).isApprox(M.actInv(mp_dense_y)));\n    \n    BOOST_CHECK(v.cross(mp_y).isApprox(v.cross(mp_dense_y)));\n    \n    MotionRevoluteTpl<double,0,2> mp_z(2.);\n    Motion mp_dense_z(mp_z);\n    \n    BOOST_CHECK(M.act(mp_z).isApprox(M.act(mp_dense_z)));\n    BOOST_CHECK(M.actInv(mp_z).isApprox(M.actInv(mp_dense_z)));\n    \n    BOOST_CHECK(v.cross(mp_z).isApprox(v.cross(mp_dense_z)));\n  }\n\nBOOST_AUTO_TEST_CASE (vsRX)\n{\n  typedef Eigen::Matrix <double, 3, 1> Vector3;\n  typedef Eigen::Matrix <double, 3, 3> Matrix3;\n\n\n  Model modelRX, modelRevoluteUnbounded;\n\n  Inertia inertia (1., Vector3 (0.5, 0., 0.0), Matrix3::Identity ());\n  SE3 pos(1); pos.translation() = SE3::LinearType(1.,0.,0.);\n\n  JointModelRUBX joint_model_RUX;\n  addJointAndBody(modelRX,JointModelRX(),0,SE3::Identity(),\"rx\",inertia);\n  addJointAndBody(modelRevoluteUnbounded,joint_model_RUX,0,SE3::Identity(),\"revolute unbounded x\",inertia);\n\n  Data dataRX(modelRX);\n  Data dataRevoluteUnbounded(modelRevoluteUnbounded);\n\n\n  Eigen::VectorXd q_rx = Eigen::VectorXd::Ones (modelRX.nq);\n  Eigen::VectorXd q_rubx = Eigen::VectorXd::Ones (modelRevoluteUnbounded.nq);\n  double ca, sa; double alpha = q_rx(0); SINCOS (alpha, &sa, &ca);\n  q_rubx(0) = ca;\n  q_rubx(1) = sa;\n  Eigen::VectorXd v_rx = Eigen::VectorXd::Ones (modelRX.nv);\n  Eigen::VectorXd v_rubx = v_rx;\n  Eigen::VectorXd tauRX = Eigen::VectorXd::Ones (modelRX.nv);       Eigen::VectorXd tauRevoluteUnbounded = Eigen::VectorXd::Ones (modelRevoluteUnbounded.nv);\n  Eigen::VectorXd aRX = Eigen::VectorXd::Ones (modelRX.nv);         Eigen::VectorXd aRevoluteUnbounded = aRX;\n  \n\n\n  forwardKinematics(modelRX, dataRX, q_rx, v_rx);\n  forwardKinematics(modelRevoluteUnbounded, dataRevoluteUnbounded, q_rubx, v_rubx);\n\n  computeAllTerms(modelRX, dataRX, q_rx, v_rx);\n  computeAllTerms(modelRevoluteUnbounded, dataRevoluteUnbounded, q_rubx, v_rubx);\n\n  BOOST_CHECK(dataRevoluteUnbounded.oMi[1].isApprox(dataRX.oMi[1]));\n  BOOST_CHECK(dataRevoluteUnbounded.liMi[1].isApprox(dataRX.liMi[1]));\n  BOOST_CHECK(dataRevoluteUnbounded.Ycrb[1].matrix().isApprox(dataRX.Ycrb[1].matrix()));\n  BOOST_CHECK(dataRevoluteUnbounded.f[1].toVector().isApprox(dataRX.f[1].toVector()));\n  \n  BOOST_CHECK(dataRevoluteUnbounded.nle.isApprox(dataRX.nle));\n  BOOST_CHECK(dataRevoluteUnbounded.com[0].isApprox(dataRX.com[0]));\n\n\n\n  // InverseDynamics == rnea\n  tauRX = rnea(modelRX, dataRX, q_rx, v_rx, aRX);\n  tauRevoluteUnbounded = rnea(modelRevoluteUnbounded, dataRevoluteUnbounded, q_rubx, v_rubx, aRevoluteUnbounded);\n\n  BOOST_CHECK(tauRX.isApprox(tauRevoluteUnbounded));\n\n  // ForwardDynamics == aba\n  Eigen::VectorXd aAbaRX= aba(modelRX,dataRX, q_rx, v_rx, tauRX);\n  Eigen::VectorXd aAbaRevoluteUnbounded = aba(modelRevoluteUnbounded,dataRevoluteUnbounded, q_rubx, v_rubx, tauRevoluteUnbounded);\n\n\n  BOOST_CHECK(aAbaRX.isApprox(aAbaRevoluteUnbounded));\n\n  // crba\n  crba(modelRX, dataRX,q_rx);\n  crba(modelRevoluteUnbounded, dataRevoluteUnbounded, q_rubx);\n\n  BOOST_CHECK(dataRX.M.isApprox(dataRevoluteUnbounded.M));\n   \n  // Jacobian\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobianPX;jacobianPX.resize(6,1); jacobianPX.setZero();\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobianPrismaticUnaligned;jacobianPrismaticUnaligned.resize(6,1);jacobianPrismaticUnaligned.setZero();\n  computeJointJacobians(modelRX, dataRX, q_rx);\n  computeJointJacobians(modelRevoluteUnbounded, dataRevoluteUnbounded, q_rubx);\n  getJointJacobian(modelRX, dataRX, 1, LOCAL, jacobianPX);\n  getJointJacobian(modelRevoluteUnbounded, dataRevoluteUnbounded, 1, LOCAL, jacobianPrismaticUnaligned);\n\n\n  BOOST_CHECK(jacobianPX.isApprox(jacobianPrismaticUnaligned));\n\n\n}\nBOOST_AUTO_TEST_SUITE_END ()\n  \nBOOST_AUTO_TEST_SUITE(JointRevolute)\n  \n  BOOST_AUTO_TEST_CASE(spatial)\n  {\n    typedef TransformRevoluteTpl<double,0,0> TransformX;\n    typedef TransformRevoluteTpl<double,0,1> TransformY;\n    typedef TransformRevoluteTpl<double,0,2> TransformZ;\n    \n    typedef SE3::Vector3 Vector3;\n    \n    const double alpha = 0.2;\n    double sin_alpha, cos_alpha; SINCOS(alpha,&sin_alpha,&cos_alpha);\n    SE3 Mplain, Mrand(SE3::Random());\n    \n    TransformX Mx(sin_alpha,cos_alpha);\n    Mplain = Mx;\n    BOOST_CHECK(Mplain.translation().isZero());\n    BOOST_CHECK(Mplain.rotation().isApprox(Eigen::AngleAxisd(alpha,Vector3::UnitX()).toRotationMatrix()));\n    BOOST_CHECK((Mrand*Mplain).isApprox(Mrand*Mx));\n    \n    TransformY My(sin_alpha,cos_alpha);\n    Mplain = My;\n    BOOST_CHECK(Mplain.translation().isZero());\n    BOOST_CHECK(Mplain.rotation().isApprox(Eigen::AngleAxisd(alpha,Vector3::UnitY()).toRotationMatrix()));\n    BOOST_CHECK((Mrand*Mplain).isApprox(Mrand*My));\n    \n    TransformZ Mz(sin_alpha,cos_alpha);\n    Mplain = Mz;\n    BOOST_CHECK(Mplain.translation().isZero());\n    BOOST_CHECK(Mplain.rotation().isApprox(Eigen::AngleAxisd(alpha,Vector3::UnitZ()).toRotationMatrix()));\n    BOOST_CHECK((Mrand*Mplain).isApprox(Mrand*Mz));\n    \n    SE3 M(SE3::Random());\n    Motion v(Motion::Random());\n    \n    MotionRevoluteTpl<double,0,0> mp_x(2.);\n    Motion mp_dense_x(mp_x);\n    \n    BOOST_CHECK(M.act(mp_x).isApprox(M.act(mp_dense_x)));\n    BOOST_CHECK(M.actInv(mp_x).isApprox(M.actInv(mp_dense_x)));\n    \n    BOOST_CHECK(v.cross(mp_x).isApprox(v.cross(mp_dense_x)));\n    \n    MotionRevoluteTpl<double,0,1> mp_y(2.);\n    Motion mp_dense_y(mp_y);\n    \n    BOOST_CHECK(M.act(mp_y).isApprox(M.act(mp_dense_y)));\n    BOOST_CHECK(M.actInv(mp_y).isApprox(M.actInv(mp_dense_y)));\n    \n    BOOST_CHECK(v.cross(mp_y).isApprox(v.cross(mp_dense_y)));\n    \n    MotionRevoluteTpl<double,0,2> mp_z(2.);\n    Motion mp_dense_z(mp_z);\n    \n    BOOST_CHECK(M.act(mp_z).isApprox(M.act(mp_dense_z)));\n    BOOST_CHECK(M.actInv(mp_z).isApprox(M.actInv(mp_dense_z)));\n    \n    BOOST_CHECK(v.cross(mp_z).isApprox(v.cross(mp_dense_z)));\n  }\n  \nBOOST_AUTO_TEST_SUITE_END()\n  \nBOOST_AUTO_TEST_SUITE(JointRevoluteUnaligned)\n  \n  BOOST_AUTO_TEST_CASE(spatial)\n  {\n    SE3 M(SE3::Random());\n    Motion v(Motion::Random());\n    \n    MotionRevoluteUnaligned mp(MotionRevoluteUnaligned::Vector3(1.,2.,3.),6.);\n    Motion mp_dense(mp);\n    \n    BOOST_CHECK(M.act(mp).isApprox(M.act(mp_dense)));\n    BOOST_CHECK(M.actInv(mp).isApprox(M.actInv(mp_dense)));\n    \n    BOOST_CHECK(v.cross(mp).isApprox(v.cross(mp_dense)));\n  }\n  \nBOOST_AUTO_TEST_SUITE_END()\n  \nBOOST_AUTO_TEST_SUITE(JointModelBase_test)\n  \n  struct TestJointModelIsEqual\n  {\n    template<typename JointModel>\n    void operator()(const pinocchio::JointModelBase<JointModel> &) const\n    {\n      JointModel jmodel;\n      jmodel.setIndexes(0,0,0);\n      \n      test(jmodel);\n    }\n    \n    template<typename Scalar, int Options>\n    void operator()(const JointModelRevoluteUnalignedTpl<Scalar,Options> & ) const\n    {\n      typedef JointModelRevoluteUnalignedTpl<Scalar,Options> JointModelRevoluteUnaligned;\n      typedef typename JointModelRevoluteUnaligned::Vector3 Vector3;\n      JointModelRevoluteUnaligned jmodel(Vector3::Random().normalized());\n      jmodel.setIndexes(0,0,0);\n      \n      test(jmodel);\n    }\n    \n    template<typename Scalar, int Options>\n    void operator()(const JointModelPrismaticUnalignedTpl<Scalar,Options> & ) const\n    {\n      typedef JointModelPrismaticUnalignedTpl<Scalar,Options> JointModelPrismaticUnaligned;\n      typedef typename JointModelPrismaticUnaligned::Vector3 Vector3;\n      JointModelPrismaticUnaligned jmodel(Vector3::Random().normalized());\n      jmodel.setIndexes(0,0,0);\n      \n      test(jmodel);\n    }\n    \n    template<typename Scalar, int Options, template<typename,int> class JointCollection>\n    void operator()(const JointModelTpl<Scalar,Options,JointCollection> & ) const\n    {\n      typedef JointModelRevoluteTpl<Scalar,Options,0> JointModelRX;\n      typedef JointModelTpl<Scalar,Options,JointCollection> JointModel;\n      JointModel jmodel((JointModelRX()));\n      jmodel.setIndexes(0,0,0);\n      \n      test(jmodel);\n    }\n    \n    template<typename JointModel>\n    static void test(const JointModelBase<JointModel> & jmodel)\n    {\n      JointModel jmodel_copy = jmodel.derived();\n      BOOST_CHECK(jmodel_copy == jmodel.derived());\n      \n      JointModel jmodel_any;\n      BOOST_CHECK(jmodel_any != jmodel.derived());\n      BOOST_CHECK(!jmodel_any.isEqual(jmodel.derived()));\n    }\n  };\n  \n  BOOST_AUTO_TEST_CASE(isEqual)\n  {\n    typedef JointCollectionDefault::JointModelVariant JointModelVariant;\n    boost::mpl::for_each<JointModelVariant::types>(TestJointModelIsEqual());\n    \n    JointModelRX joint_revolutex;\n    JointModelRY joint_revolutey;\n    \n    BOOST_CHECK(joint_revolutex != joint_revolutey);\n    \n    JointModel jmodelx(joint_revolutex);\n    jmodelx.setIndexes(0,0,0);\n    TestJointModelIsEqual()(JointModel());\n    \n    JointModel jmodel_any;\n    BOOST_CHECK(jmodel_any != jmodelx);\n  }\n  \n  struct TestJointModelCast\n  {\n    template<typename JointModel>\n    void operator()(const pinocchio::JointModelBase<JointModel> &) const\n    {\n      JointModel jmodel;\n      jmodel.setIndexes(0,0,0);\n      \n      test(jmodel);\n    }\n    \n    template<typename Scalar, int Options>\n    void operator()(const JointModelRevoluteUnalignedTpl<Scalar,Options> & ) const\n    {\n      typedef JointModelRevoluteUnalignedTpl<Scalar,Options> JointModelRevoluteUnaligned;\n      typedef typename JointModelRevoluteUnaligned::Vector3 Vector3;\n      JointModelRevoluteUnaligned jmodel(Vector3::Random().normalized());\n      jmodel.setIndexes(0,0,0);\n      \n      test(jmodel);\n    }\n    \n    template<typename Scalar, int Options>\n    void operator()(const JointModelPrismaticUnalignedTpl<Scalar,Options> & ) const\n    {\n      typedef JointModelPrismaticUnalignedTpl<Scalar,Options> JointModelPrismaticUnaligned;\n      typedef typename JointModelPrismaticUnaligned::Vector3 Vector3;\n      JointModelPrismaticUnaligned jmodel(Vector3::Random().normalized());\n      jmodel.setIndexes(0,0,0);\n      \n      test(jmodel);\n    }\n    \n    template<typename Scalar, int Options, template<typename,int> class JointCollection>\n    void operator()(const JointModelTpl<Scalar,Options,JointCollection> & ) const\n    {\n      typedef JointModelRevoluteTpl<Scalar,Options,0> JointModelRX;\n      typedef JointModelTpl<Scalar,Options,JointCollection> JointModel;\n      JointModel jmodel((JointModelRX()));\n      jmodel.setIndexes(0,0,0);\n      \n      test(jmodel);\n    }\n    \n    template<typename JointModel>\n    static void test(const JointModelBase<JointModel> & jmodel)\n    {\n      typedef typename JointModel::Scalar Scalar;\n      BOOST_CHECK(jmodel.template cast<Scalar>() == jmodel);\n      BOOST_CHECK(jmodel.template cast<long double>().template cast<double>() == jmodel);\n    }\n  };\n  \n  BOOST_AUTO_TEST_CASE(cast)\n  {\n    typedef JointCollectionDefault::JointModelVariant JointModelVariant;\n    boost::mpl::for_each<JointModelVariant::types>(TestJointModelCast());\n    \n    TestJointModelCast()(JointModel());\n  }\n  \nBOOST_AUTO_TEST_SUITE_END()\n  \n", "meta": {"hexsha": "20b1b0bfe150dbf1e79e62cf54ed7355e9a842b1", "size": 44685, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/joints.cpp", "max_stars_repo_name": "matthieuvigne/pinocchio", "max_stars_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "unittest/joints.cpp", "max_issues_repo_name": "matthieuvigne/pinocchio", "max_issues_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "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/joints.cpp", "max_forks_repo_name": "matthieuvigne/pinocchio", "max_forks_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 36.2702922078, "max_line_length": 184, "alphanum_fraction": 0.6995859908, "num_tokens": 12961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5380554672863488}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <stdlib.h>\n#include <string>\n#include <tuple>\n#include <vector>\n#include <limits>\n#include <algorithm>\n#include <boost/numeric/odeint.hpp>\n\n#include \"ode.h\"\n#include <ebit-ode-messages.pb.h>\n\nusing namespace std;\n\ntypedef std::vector<double> state_type;\n\ntypedef ::google::protobuf::RepeatedPtrField<::EbitODEMessages::MatrixValue>\nmatrix;\ntypedef ::google::protobuf::RepeatedPtrField<::EbitODEMessages::InitialValue>\ninitValue;\ntypedef ::google::protobuf::RepeatedPtrField<::EbitODEMessages::Nuclide>\nnuclides;\n\ntypedef ::google::protobuf::RepeatedField<double> times;\n\ndouble *create_matrix(int dimension, const matrix &sparse) {\n    double *result = new double[dimension * dimension];\n    \n    for (int i = 0; i < 2 * dimension; ++i) result[i] = 0.0;\n    for (auto ptr = sparse.begin(); ptr < sparse.end(); ++ptr) {\n\t// to keep it in sync with julia, decf 1 on array offsets\n\tauto i = ptr->row() - 1;\n\tauto j = ptr->column() - 1;\n\tresult[dimension * i + j] += ptr->value();\n\t// std::cout << \"R_{\" << i << \",\" << j << \"}: \" << ptr->value() << std::endl;\n    }\n    // std::cout << endl;\n\n    return result;\n}\n\nstate_type &create_init_values(int dimension, const initValue &init_values) {\n    auto result =\n\tnew state_type(2 * dimension); \n    for (auto ptr = init_values.begin(); ptr < init_values.end(); ++ptr) {\n\t\n\tauto i = ptr->index() - 1;\n\t(*result)[i] = ptr->number_of_particles();\n\t(*result)[dimension + i] = ptr->temperature_in_ev();\n    }\n    return *result;\n}\n\nclass ebit_ode {\n    const double *qV_e;\n    const double *qV_t;\n    const double *A;\n    const double *phi;\n    const double *qVe_over_Vol_x_kT;\n    const double *source;\n\n    const double *Xi_ij;\n    const double *eta_ij;\n    const double *CX_ij;\n\n    unsigned int no_dimensions;\n    double min_N;\n\npublic:\n    ~ebit_ode() {}\n    ebit_ode(const EbitODEMessages::DiffEqParameters &p) {\n\tno_dimensions = p.no_dimensions();\n\tqV_e = p.qve().data();\n\tqV_t = p.qvt().data();\n\tA = p.mass_number().data();\n\tphi = p.spitzer_divided_by_overlap().data();\n\tqVe_over_Vol_x_kT = p.qve_over_vol_x_kt().data();\n\tsource = p.source_terms().data();\n\tmin_N = p.minimum_n();\n\tXi_ij = create_matrix(no_dimensions, p.inverted_collision_constant());\n\teta_ij = create_matrix(no_dimensions, p.rate_of_change_divided_by_n());\n\tCX_ij = create_matrix(no_dimensions, p.dcharge_ex_divided_by_n_times_tau());\n    }\n    \n    void operator()(const state_type &x, state_type &dxdt, const double) {\n\tauto tau = [&](int i) { return std::max(0.0, x[no_dimensions + i]); };\n\tauto N = [&](int i) { return std::max(0.0, x[i]); };\n\n\tauto dN = [&](int i, double incf) { dxdt[i] += incf; };\n\tauto dtau = [&](int i, double incf) { dxdt[i + no_dimensions] += incf; };\n\n\tauto set_dN = [&](int i, double set_point) { dxdt[i] = set_point; };\n\tauto set_dtau = [&](int i, double set_point) { dxdt[i + no_dimensions] = set_point; };\n\n\tauto CX = [&](int i, int j) { return CX_ij[no_dimensions*i + j]; };\n\tauto eta = [&](int i, int j) { return eta_ij[no_dimensions*i + j]; };\n\tauto Xi = [&](int i, int j) { return Xi_ij[no_dimensions*i + j]; };\n\n\tfor (int i = 0; i < no_dimensions; ++i) {\n\t    double R_esc_sum_j = 0.0;\n\t    double R_exchange_sum_j = 0.0;\n\t    \n\t    set_dN(i, source[i]);\n\t    set_dtau(i, 0.0);\n\n\t    for (int j = 0; j < no_dimensions; ++j) {\n\n\t\tif (N(i) > min_N && N(j) > min_N && tau(j) > 0.0 && tau(i) > 0.0) {\n\t\t    double f_ij = std::min((tau(i) * qV_e[j]) / (tau(j) * qV_e[i]), 1.0);\n\t\t    double n_j = N(j) * qVe_over_Vol_x_kT[j] / tau(j);\n\t\t    double arg = (tau(i) / A[i] + tau(j) / A[j]);\n\t\t    double Sigma = Xi(i,j) * n_j * pow(arg, -1.5);\n\t\t    R_esc_sum_j += f_ij * Sigma;\n\t\t    R_exchange_sum_j += f_ij * Sigma * (tau(j) - tau(i));\n\n\t\t    dN(i,  CX(i,j) * N(j) * sqrt(tau(j)));\n\t\t}\n\n\t\tdN(i, eta(i,j) * N(j));\n\t    }\n\n\t    dtau(i, R_exchange_sum_j);\n\t    if (N(i) > min_N) {\n\t\tdouble R_esc = 3 / sqrt(3) * R_esc_sum_j * (tau(i) / qV_t[i]) *\n\t\t    exp(-qV_t[i] / tau(i));\n\t\tdtau(i, (std::min(qV_e[i] / tau(i), 1.0) * phi[i] ) - (tau(i) + qV_t[i]) * R_esc);\n\t\tdN(i, -N(i) * R_esc);\n\t    }\n\t}\n    }\n};\n\n\nvoid publish(const nuclides& m_nuclides, const state_type &x, double time){\n    std::cout << \"time: \" << time << \" \";\n    for (auto n = m_nuclides.begin(); n < m_nuclides.end(); ++n) {\n\tstd::cout << \", N(A=\" << n->a() << \",Z=\" << n->z() << \",q=\" << n->q() << \"+): \"\n\t\t  << x[n->i() - 1];\n    }\n    std::cout << endl;\n}\n\nclass write_state {\n    const nuclides& m_nuclides;\npublic:\n    write_state(const nuclides& nuclides) : m_nuclides(nuclides) {}\n    \n    void operator()(const state_type &x, double time) const {\n\tpublish(m_nuclides, x, time);\n    }\n};\n\nEbitODEMessages::Result *prepare_result(const nuclides &nuclides) {\n    auto result = new EbitODEMessages::Result();\n\n    for (auto p = nuclides.begin(); p < nuclides.end(); ++p) {\n\tauto n = result->add_n();\n\tauto kt = result->add_kt();\n\n\tn->set_allocated_nuclide(new EbitODEMessages::Nuclide(*p));\n\tkt->set_allocated_nuclide(new EbitODEMessages::Nuclide(*p));\n    }\n    return result;\n}\n\n\nbool save_state(const state_type &x, EbitODEMessages::Result &result,\n                const nuclides &nuclides, int no_dimensions, double last_time, \n\t\tdouble only_if_larger = 0.0) {\n    if (last_time < only_if_larger)\n\treturn false;\n    \n    result.add_times(last_time);\n    for (auto n = nuclides.begin(); n < nuclides.end(); ++n) {\n\tauto i = n->i() - 1;\n\tresult.mutable_n(i)->add_values(x[i]);\n\tresult.mutable_kt(i)->add_values(x[no_dimensions + i]);\n    }\n\n    return true;\n}\n\n\nclass push_back_state_and_time {\n    EbitODEMessages::Result &m_result;\n    const nuclides &m_nuclides;\n    int m_no_dimensions;\n    int m_last_time_i = 0;\n    const times& m_times;\npublic:\n    push_back_state_and_time(EbitODEMessages::Result &result, const nuclides &nuclides, \n\t\t\t     int no_dimensions, const times& times)\n\t: m_result(result), m_nuclides(nuclides), \n\t  m_no_dimensions(no_dimensions), m_times(times)\n\t{}\n\n    void operator()(const state_type &x, double t) {\n\t// publish(m_nuclides, x, t);\n\tauto saved = save_state(x, m_result, m_nuclides, \n\t\t\t\tm_no_dimensions, t,\n\t\t\t\tm_times.Get(m_last_time_i));\n\tif (saved && m_last_time_i + 1 < m_times.size())\n\t    ++m_last_time_i;\n    }\n};\n\n\n\nEbitODEMessages::Result* do_solve(const ebit_ode &ode,\n\t\t\t\t  const EbitODEMessages::SolverParameters &solver_params,\n\t\t\t\t  const EbitODEMessages::DiffEqParameters &diff_params,\n\t\t\t\t  const EbitODEMessages::ProblemParameters& problem_params,\n\t\t\t\t  const nuclides &nuclides) {\n    using namespace boost::numeric::odeint;\n\n    std::cout << \"Start solving problem of size: \" << diff_params.no_dimensions()\n\t      << std::endl;\n\n    auto saveat = solver_params.saveat();\n    auto x = create_init_values(diff_params.no_dimensions(),\n\t\t\t\tdiff_params.initial_values());\n\n    typedef runge_kutta_fehlberg78<state_type> error_stepper_type;\n    typedef controlled_runge_kutta<error_stepper_type> controlled_stepper_type;\n    controlled_stepper_type controlled_stepper;\n\n    auto result = prepare_result(nuclides);\n\n    auto ptr = saveat.begin();\n    double last_time = *ptr++;\n\n  \n    integrate_adaptive(controlled_stepper, ode, x, \n\t\t       problem_params.time_span().start(), \n\t\t       problem_params.time_span().stop(), 1e-1\n\t\t       //write_state(nuclides)\n\t\t       ,push_back_state_and_time(*result, nuclides, \n\t\t       \t\t\t\tdiff_params.no_dimensions(),\n\t\t       \t\t\t\tsolver_params.saveat())\n\t);\n\n\n    result->set_return_code(EbitODEMessages::Success);\n\n    return result;\n}\n\nvoid solve_ode(const char *msg_buffer, unsigned int size, char **answer_buffer,\n               unsigned int *answer_size) {\n\n    EbitODEMessages::Message msg;\n    if (!msg.ParseFromArray(msg_buffer, size))\n\tthrow \"Couldn't parse message.\";\n\n    auto problem = msg.ode_problem();\n    auto diff_params = problem.diff_eq_parameters();\n    auto ode = ebit_ode(diff_params);\n\n    auto answer = new EbitODEMessages::Message();\n\n    auto result = do_solve(ode, problem.solver_parameters(), diff_params, \n\t\t\t   problem.problem_parameters(), problem.nuclides());\n    result->set_allocated_problem(&problem);\n    result->set_start_time(0.0);\n    result->set_stop_time(0.0);\n\n    answer->set_msg_type(EbitODEMessages::ODEResult);\n    answer->set_allocated_ode_result(result);\n\n    *answer_size = answer->ByteSize();\n    *answer_buffer = static_cast<char *>(malloc(*answer_size));\n\n    answer->SerializeToArray(*answer_buffer, *answer_size);\n}\n", "meta": {"hexsha": "b59da89706d6680a6ed70242fd5d25abd043fd7e", "size": 8448, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ode.cpp", "max_stars_repo_name": "deepestthought42/ebit-cpp-server", "max_stars_repo_head_hexsha": "638225c537a5baf8d6bfcb3341e1b280cefe07e5", "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/ode.cpp", "max_issues_repo_name": "deepestthought42/ebit-cpp-server", "max_issues_repo_head_hexsha": "638225c537a5baf8d6bfcb3341e1b280cefe07e5", "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/ode.cpp", "max_forks_repo_name": "deepestthought42/ebit-cpp-server", "max_forks_repo_head_hexsha": "638225c537a5baf8d6bfcb3341e1b280cefe07e5", "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.4981949458, "max_line_length": 88, "alphanum_fraction": 0.6458333333, "num_tokens": 2475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5380554667060594}}
{"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 <complex>\n\n\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;  \n\ntemplate <typename T>\nT inline my_value(std::size_t i, T) { return T(i); }\n\nstd::complex<double> \ninline my_value(std::size_t i, std::complex<double>)\n{ return std::complex<double>(i, i+1); }\n\ntemplate <typename VectorU>\nvoid test(VectorU& u, const char* name)\n{\n    using std::abs;\n\n    typedef typename mtl::Collection<VectorU>::value_type value_type;\n    typedef typename mtl::Collection<VectorU>::size_type  size_type;\n    for (size_type i= 0; i < size(u); i++)\n\tu[i]= my_value(i+1, value_type());\n\n    value_type dot_cmp= dot(u, u);\n\n    bool wrong= abs(unary_dot(u) - dot_cmp) > 0.001,\n\t not_two_norm= abs(two_norm(u) * two_norm(u) - abs(unary_dot(u))) > 0.001;\n    std::cout << name << \": u = \" << u << \"\\n unary_dot(u) = \" << unary_dot(u) << \" is \" \n\t      << (wrong ? \"not\" : \"\") << \"equal with dot(u, u)\\n\";     \n    if (wrong) \n\tthrow \"unary_dot product wrong\";\n\n    std::cout << \" two_norm(u) = \" << two_norm(u) << \", unary_dot(u) is \" << (not_two_norm ? \"not\" : \"\") << \"equal with square of it\\n\";\n    if (not_two_norm)\n\tthrow \"different from square of two_norm\";\n\n    std::cout << \" unary_dot<2>(u) = \" << mtl::unary_dot<2>(u) << \"\\n\"; std::cout.flush();\n    if (abs(mtl::unary_dot<2>(u) - dot_cmp) > 0.001) \n\tthrow \"unary_dot product wrong\";\n\n    std::cout << \" unary_dot<6>(u) = \" << mtl::unary_dot<6>(u) << \"\\n\"; std::cout.flush();\n    if (abs(mtl::unary_dot<6>(u) - dot_cmp) > 0.001) \n\tthrow \"unary_dot product wrong\";\n}\n \n\nint main(int ,char**)\n{\n    using mtl::vec::parameters;\n    const int size= 9;\n\n    mtl::dense_vector<float>   u(size);\n    mtl::dense_vector<double>  x(size);\n    mtl::dense_vector<std::complex<double> >  xc(size);\n\n    std::cout << \"Testing vector operations\\n\";\n\n    test(u, \"test float\");\n    test(x, \"test double\");\n    test(xc, \"test complex<double>\");\n\n    mtl::dense_vector<float, parameters<mtl::row_major> >   ur(size);\n    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": "e4f5381b3946b77e7754a53db8116b34710fd040", "size": 2516, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/unary_dot_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/unary_dot_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/unary_dot_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": 25.6734693878, "max_line_length": 136, "alphanum_fraction": 0.6212241653, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5380078529139092}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"simple_witness_complex\"\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <gudhi/Simplex_tree.h>\n\n#include <gudhi/Witness_complex.h>\n\n#include <iostream>\n#include <vector>\n#include <utility>\n\n\nBOOST_AUTO_TEST_CASE(simple_witness_complex) {\n  using Nearest_landmark_range = std::vector<std::pair<std::size_t, double>>;\n  using Nearest_landmark_table = std::vector<Nearest_landmark_range>;\n  using Witness_complex = Gudhi::witness_complex::Witness_complex<Nearest_landmark_table>;\n  using Simplex_tree = Gudhi::Simplex_tree<>;\n\n  Simplex_tree stree;\n  Nearest_landmark_table nlt;\n\n  // Example contains 5 witnesses and 5 landmarks\n  Nearest_landmark_range w0 = {std::make_pair(0, 0), std::make_pair(1, 1), std::make_pair(2, 2),\n                               std::make_pair(3, 3), std::make_pair(4, 4)}; nlt.push_back(w0);\n  Nearest_landmark_range w1 = {std::make_pair(1, 0), std::make_pair(2, 1), std::make_pair(3, 2),\n                               std::make_pair(4, 3), std::make_pair(0, 4)}; nlt.push_back(w1);\n  Nearest_landmark_range w2 = {std::make_pair(2, 0), std::make_pair(3, 1), std::make_pair(4, 2),\n                               std::make_pair(0, 3), std::make_pair(1, 4)}; nlt.push_back(w2);\n  Nearest_landmark_range w3 = {std::make_pair(3, 0), std::make_pair(4, 1), std::make_pair(0, 2),\n                               std::make_pair(1, 3), std::make_pair(2, 4)}; nlt.push_back(w3);\n  Nearest_landmark_range w4 = {std::make_pair(4, 0), std::make_pair(0, 1), std::make_pair(1, 2),\n                               std::make_pair(2, 3), std::make_pair(3, 4)}; nlt.push_back(w4);\n\n  Witness_complex witness_complex(nlt);\n  BOOST_CHECK(witness_complex.create_complex(stree, 4.1));\n\n  std::clog << \"Number of simplices: \" << stree.num_simplices() << std::endl;\n  BOOST_CHECK(stree.num_simplices() == 31);\n\n  // Check when complex not empty\n  BOOST_CHECK(!witness_complex.create_complex(stree, 4.1));\n\n  // Check when max_alpha_square negative\n  Simplex_tree stree2;\n  BOOST_CHECK(!witness_complex.create_complex(stree2, -0.02));\n\n  witness_complex.create_complex(stree2, 4.1, 2);\n  std::clog << \"Number of simplices: \" << stree2.num_simplices() << std::endl;\n  BOOST_CHECK(stree2.num_simplices() == 25);\n\n}\n", "meta": {"hexsha": "7c48cc54fdb3d05be441199ba5029bb53614bb40", "size": 2295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Witness_complex/test/test_simple_witness_complex.cpp", "max_stars_repo_name": "m0baxter/gudhi-devel", "max_stars_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "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/Witness_complex/test/test_simple_witness_complex.cpp", "max_issues_repo_name": "m0baxter/gudhi-devel", "max_issues_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "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/Witness_complex/test/test_simple_witness_complex.cpp", "max_forks_repo_name": "m0baxter/gudhi-devel", "max_forks_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "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.5, "max_line_length": 96, "alphanum_fraction": 0.6775599129, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834734, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5380078364224468}}
{"text": "#pragma once\r\n\r\n#include <vector>\r\n#include <fstream>\r\n#include <array>\r\n#include <Eigen/Dense>\r\n\r\n#include \"common.hpp\"\r\n\r\nnamespace Discregrid\r\n{\r\n\r\nclass DiscreteGrid\r\n{\r\npublic:\r\n\r\n\tusing CoefficientVector = Eigen::Matrix<Real, 32, 1>;\r\n\tusing ContinuousFunction = std::function<Real(Vector3r const&)>;\r\n\tusing MultiIndex = std::array<unsigned int, 3>;\r\n\tusing Predicate = std::function<bool(Vector3r const&, Real)>;\r\n\tusing SamplePredicate = std::function<bool(Vector3r const&)>;\r\n\r\n\tDiscreteGrid() = default;\r\n\tDiscreteGrid(AlignedBox3r const& domain, std::array<unsigned int, 3> const& resolution)\r\n\t\t: m_domain(domain), m_resolution(resolution), m_n_fields(0u)\r\n\t{\r\n\t\tauto n = Eigen::Matrix<unsigned int, 3, 1>::Map(resolution.data());\r\n\t\tm_cell_size = domain.diagonal().cwiseQuotient(n.cast<Real>());\r\n\t\tm_inv_cell_size = m_cell_size.cwiseInverse();\r\n\t\tm_n_cells = n.prod();\r\n\t}\r\n\tvirtual ~DiscreteGrid() = default;\r\n\r\n\tvirtual void save(std::string const& filename) const = 0;\r\n\tvirtual void load(std::string const& filename) = 0;\r\n\r\n\tvirtual unsigned int addFunction(ContinuousFunction const& func, bool verbose = false,\r\n\t\tSamplePredicate const& pred = nullptr) = 0;\r\n\r\n\tReal interpolate(Vector3r const& xi, Vector3r* gradient = nullptr) const\r\n\t{\r\n\t\treturn interpolate(0u, xi, gradient);\r\n\t}\r\n\r\n\tvirtual Real interpolate(unsigned int field_id, Vector3r const& xi,\r\n\t\tVector3r* gradient = nullptr) const = 0;\r\n\r\n\t/**\r\n\t * @brief Determines the shape functions for the discretization with ID field_id at point xi.\r\n\t * \r\n\t * @param field_id Discretization ID\r\n\t * @param x Location where the shape functions should be determined\r\n\t * @param cell cell of x\r\n\t * @param c0 vector required for the interpolation\r\n\t * @param N\tshape functions for the cell of x\r\n\t * @param dN (Optional) derivatives of the shape functions, required to compute the gradient\r\n\t * @return Success of the function.\r\n\t */\r\n\tvirtual bool determineShapeFunctions(unsigned int field_id, Vector3r const &x,\r\n\t\tstd::array<unsigned int, 32> &cell, Vector3r &c0, Eigen::Matrix<Real, 32, 1> &N,\r\n\t\tEigen::Matrix<Real, 32, 3> *dN = nullptr) const = 0;\r\n\r\n\t/**\r\n\t * @brief Evaluates the given discretization with ID field_id at point xi.\r\n\t * \r\n\t * @param field_id Discretization ID\r\n\t * @param xi Location where the discrete function is evaluated\r\n\t * @param cell cell of xi\r\n\t * @param c0 vector required for the interpolation\r\n\t * @param N\tshape functions for the cell of xi\r\n\t * @param gradient (Optional) if a pointer to a vector is passed the gradient of the discrete function will be evaluated\r\n\t * @param dN (Optional) derivatives of the shape functions, required to compute the gradient\r\n\t * @return Real Results of the evaluation of the discrete function at point xi\r\n\t */\r\n\tvirtual Real interpolate(unsigned int field_id, Vector3r const& xi, const std::array<unsigned int, 32> &cell, const Vector3r &c0, const Eigen::Matrix<Real, 32, 1> &N,\r\n\t\tVector3r* gradient = nullptr, Eigen::Matrix<Real, 32, 3> *dN = nullptr) const = 0;\r\n\r\n\tvirtual void reduceField(unsigned int field_id, Predicate pred) {}\r\n\r\n\r\n\tMultiIndex singleToMultiIndex(unsigned int i) const;\r\n\tunsigned int multiToSingleIndex(MultiIndex const& ijk) const;\r\n\r\n\tAlignedBox3r subdomain(MultiIndex const& ijk) const;\r\n\tAlignedBox3r subdomain(unsigned int l) const;\r\n\r\n\tAlignedBox3r const& domain() const { return m_domain; }\r\n\tstd::array<unsigned int, 3> const& resolution() const { return m_resolution; };\r\n\tVector3r const& cellSize() const { return m_cell_size;}\r\n\tVector3r const& invCellSize() const { return m_inv_cell_size;}\r\n\r\nprotected:\r\n\r\n\r\n\tAlignedBox3r m_domain;\r\n\tstd::array<unsigned int, 3> m_resolution;\r\n\tVector3r m_cell_size;\r\n\tVector3r m_inv_cell_size;\r\n\tstd::size_t m_n_cells;\r\n\tstd::size_t m_n_fields;\r\n};\r\n}\r\n", "meta": {"hexsha": "202f32de904d4c2422ec80cc54b2b328655fe286", "size": 3775, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "discregrid/include/Discregrid/discrete_grid.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": "discregrid/include/Discregrid/discrete_grid.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": "discregrid/include/Discregrid/discrete_grid.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": 36.6504854369, "max_line_length": 168, "alphanum_fraction": 0.719205298, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597974, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5380078358357898}}
{"text": "/*\n * padding.hpp\n *\n *  Created on: Apr 8, 2019\n *      Author: Gregory Kramida\n *   Copyright: 2019 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\nnamespace math{\n\n/**\n * Pad tensor by repeating its border values.\n * Same border behavior as mode='edge' for NumPy or BORDER_REPLICATE for OpenCV\n * NB: For simple padding with zeros, use the Tensor::pad method provided by Eigen.\n * @param tensor input tensor\n * @return padded tensor\n */\ntemplate<typename Scalar>\nEigen::Tensor<Scalar,3,Eigen::ColMajor> pad_replicate(const Eigen::Tensor<Scalar,3,Eigen::ColMajor>& tensor, int border_width=1);\n\n//TODO: provide Eigen::Matrix overload (if there is no Eigen equivalent)\n\n\n} //end namespace math\n\n\n\n\n", "meta": {"hexsha": "89fcf2546330363bd5f130d2164a44bd091d3565", "size": 1336, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/padding.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/padding.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/padding.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": 28.4255319149, "max_line_length": 129, "alphanum_fraction": 0.7260479042, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5380078278833869}}
{"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\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;  \nusing mtl::generate_mask; using mtl::row_major; using mtl::col_major;\n\ntemplate <typename Matrix>\nvoid print_matrix(Matrix& matrix)\n{ \n    using std::cout;\n    typedef typename mtl::Collection<Matrix>::size_type size_type;\n    for (size_type i= 0 ; i < num_rows(matrix); i++ ){\n\tfor(size_type j=0; j < num_cols(matrix);  j++ ){\n\t    cout.fill (' '); cout.width (8); cout.precision (5); cout.flags (ios_base::left);\n\t    cout << showpoint <<  matrix[i][j] <<\"  \";\n\t}\n\tcout << endl;\n    }\n}\n\n\n\ntemplate <typename Matrix>\nvoid test(Matrix& matrix, const char* name)\n{\n    namespace with_bracket = mtl::mat::with_bracket;\n    // namespace with_iterator = mtl::mat::with_iterator;\n\n    using mtl::mat::recursive_cholesky_visitor_t;\n    using mtl::mat::detail::mult_schur_update_t;\n\n    std::cout << \"Test \" << name << \"\\n-----\\n\\n\";\n    fill_matrix_for_cholesky(matrix);\n\n    recursive_cholesky(matrix);\n    if (matrix.num_cols() <= 10) { \n\tprint_matrix(matrix); std::cout << \"\\n\"; \n    }\n\n    fill_matrix_for_cholesky(matrix);\n\n#if 0\n    with_iterator::recursive_cholesky_base_visitor_t  iter_vis;\n    recursive_cholesky(matrix, iter_vis);\n    if (matrix.num_cols() <= 10) { \n\tprint_matrix(matrix); std::cout << \"\\n\"; \n    }\n\n    fill_matrix_for_cholesky(matrix);\n#endif\n\n    recursive_cholesky_visitor_t<mtl::recursion::bound_test_static<2>, with_bracket::cholesky_base_t, with_bracket::tri_solve_base_t, \n                                 with_bracket::tri_schur_base_t, with_bracket::schur_update_base_t>   \n        iter_vis2; \n    recursive_cholesky(matrix, iter_vis2);\n    if (matrix.num_cols() <= 10) { \n\tprint_matrix(matrix); std::cout << \"\\n\"; \n    }\n\n    fill_matrix_for_cholesky(matrix);\n\n\n#if 0 // ITERATOR VERSION CURRENTLY NOT SUPPORTED -- CAUSES SEGFAULT, e.g. with icc 11.0 in r8536 !!!!\n\n    recursive_cholesky_visitor_t<mtl::recursion::bound_test_static<2>, with_iterator::cholesky_base_t, with_iterator::tri_solve_base_t, \n                                 with_iterator::tri_schur_base_t, with_iterator::schur_update_base_t>   \n        iter_vis3;\n\n    recursive_cholesky(matrix, iter_vis3);\n    if (matrix.num_cols() <= 10) { \n\tprint_matrix(matrix); std::cout << \"\\n\"; \n    }\n\n\n    fill_matrix_for_cholesky(matrix);\n\n    typedef mult_schur_update_t<mtl::gen_tiling_22_dmat_dmat_mult_t<mtl::assign::minus_sum> > schur_update_22_t;\n    recursive_cholesky_visitor_t<mtl::recursion::bound_test_static<2>, with_iterator::cholesky_base_t, with_iterator::tri_solve_base_t, \n                                 with_iterator::tri_schur_base_t, schur_update_22_t>   \n        iter_vis4;\n\n    recursive_cholesky(matrix, iter_vis4);\n    if (matrix.num_cols() <= 10) { \n\tprint_matrix(matrix); std::cout << \"\\n\"; \n    }\n\n\n    typedef detail::mult_schur_update_t<gen_tiling_44_dmat_dmat_mult_t<minus_mult_assign_t> > schur_update_44_t;\n\n#endif\n}\n\n\n\nint main(int argc, char* argv[])\n{\n    mtl::vampir_trace<9999> tracer;\n\n    using namespace mtl;\n    unsigned size= 13; \n    if (argc > 1) size= atoi(argv[1]); \n\n    dense2D<double>                                dr(size, size);\n    dense2D<double, mat::parameters<col_major> > dc(size, size);\n    morton_dense<double,  morton_mask>             md(size, size);\n    morton_dense<double,  morton_z_mask>           mzd(size, size);\n    morton_dense<double,  doppled_2_row_mask>      d2r(size, size);\n    morton_dense<double,  doppled_2_col_mask>      d2c(size, size);\n    morton_dense<double,  doppled_16_row_mask>     d16r(size, size);\n    morton_dense<double,  doppled_32_row_mask>     d32r(size, size);\n    morton_dense<double,  doppled_64_row_mask>     d64r(size, size);\n    morton_dense<double,  doppled_64_col_mask>     d64c(size, size);\n    morton_dense<double,  doppled_128_col_mask>    d128r(size, size);\n    size= 9; \n    dense2D<double>                                dr2(size, size);\n    \n    test(dr2, \"Dense row major\");\n    test(dr, \"Dense row major\");\n    test(dc, \"Dense column major\");\n    test(md, \"Morton N-order\");\n    test(mzd, \"Morton Z-order\");\n    test(d2r, \"Hybrid 2 row-major\");\n    test(d2c, \"Hybrid 2 column-major\");\n    test(d16r, \"Hybrid 16 row-major\");\n\n\n    return 0;\n}\n\n\n\n\n\n", "meta": {"hexsha": "06bb34296d4b0f495bbb030478dd397fdafd931b", "size": 4693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/cholesky_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/cholesky_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/cholesky_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.4966442953, "max_line_length": 136, "alphanum_fraction": 0.6622629448, "num_tokens": 1337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5379636984957077}}
{"text": "#include \"BaseSpectrumCode.h\"\n#include \"SlabSpectrumCode.h\"\n#include \"numeric_tools.h\"\n\n#include <boost/math/special_functions/expint.hpp>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace Numerics;\nusing namespace PrintFuncs;\nusing namespace boost::math;\n\nstd::pair<Tensor3d, Tensor4d> SlabSpectrumCode::calcTracks()\n{ \n    Tensor4d tau = Tensor4d(m_cells, m_cells, m_rays, m_energies);\n\ttau.setZero();\n\n    Tensor3d zz(m_cells, m_cells, m_rays);\n    zz.setZero();\n\n\tstd::vector<double> delta(m_radii.size() - 1, 0.0);\n\n\tfor(size_t i = 0; i < delta.size(); i++)\n\t{\n\t\tdelta[i] = m_radii[i + 1] - m_radii[i];\n\t}\n\t\n\tfor(int h = 0; h < m_energies; h++)\n\t\tfor(int i = 0; i < m_cells; i++)\n          for(int j = i; j < m_cells; j++)\n\t      {\t\n\t          if (i == j) \n                  tau(i, j, 0, h) = delta[i] * m_totalXS(h, i);\n              else\n              {\n                  if (i == 0)\n\t\t\t\t\t  tau(i, j, 0, h) = delta[j] * m_totalXS(h, j) + tau(0, j - 1, 0, h);\n                  else\n                      tau(i, j, 0, h) = delta[j] * m_totalXS(h, j) \n                      + tau(0, j - 1, 0, h) - tau(0, i - 1, 0, h);\n              }\n\t\t  }\t  \n\n\tfor(int h = 0; h < m_energies; h++)\n\t\tfor(int i = 0; i < m_cells; i++)\n          for(int j = i; j < m_cells; j++)\n\t      {\t\n\t        if (i != j) tau(i, j, 0, h) -= delta[j] * m_totalXS(h, j) +  delta[i] * m_totalXS(h, i);\n\t\t\tif (tau(i, j, 0, h) < 0.0) tau(i, j, 0, h) = 0.0;\n\n\t\t\tout.print(TraceLevel::TRACE, \"Tau: {:3d} {:3d} {:3d} {:5.4f}\", h, i, j, tau(i, j,  0, h));\n\t\t  }\n  \n    std::pair<Tensor3d, Tensor4d> trackData = std::make_pair(zz, tau);\n\treturn trackData;\t\t\n}\n\nTensor3d SlabSpectrumCode::calcCPs(std::pair<Tensor3d, Tensor4d> &trackData)\n{\t\n\tTensor4d tau = trackData.second;\n\n\tTensor3d gcpm = Tensor3d(m_cells, m_cells, m_energies);\n\tgcpm.setZero();\n\n\tTensor3d CSet1(m_cells, m_cells, m_cells);\n\tTensor3d CSet2(m_cells, m_cells, m_cells);\n\t\n\tMatrixXd P = MatrixXd::Zero(m_cells, m_cells);\n\t\n    for(int h = 0; h < m_energies; h++)\n\t{\n\t  for(int i = 0; i < m_cells; i++)\n        for(int j = i; j < m_cells; j++)\n\t\t{\n          if (j == i) \n            P(i, j) = 1.0 - (1.0 / (2.0 * tau(i, i, 0, h))) * (1.0 - 2.0 * expint(3, tau(i, i, 0, h)));\n          else\n            P(i, j) = (1.0 / (2.0 * tau(i, i, 0, h))) * (expint(3, tau(i, j, 0, h)) \n\t\t\t          - expint(3, tau(i, j, 0, h) + tau(i, i, 0, h)) \n\t\t\t\t\t  - expint(3, tau(i, j, 0, h) + tau(j, j, 0, h)) \n\t\t\t\t\t  + expint(3, tau(i, j, 0, h) + tau(j, j, 0, h) + tau(i, i, 0, h)));\n\t\t}\n\n\tfor(int i = 0; i < m_cells; i++)\n\t  for(int j = i + 1; j < m_cells; j++)\n          P(j, i) = P(i, j) * (m_totalXS(h, i) / m_totalXS(h, j)) * (m_volumes(i) / m_volumes(j));\n\n\tfor(int i = 0; i < m_cells; i++)\n\t  for(int j = 0; j < m_cells; j++)\n\t\tgcpm(i, j, h) = P(i, j);\n\t}\n\n\tout.print(TraceLevel::INFO, \"P matrix (vacuum BC)\");\n    printMatrix(gcpm, out, TraceLevel::INFO, \"Group\");\n\treturn gcpm;\n}\n\nvoid SlabSpectrumCode::applyBoundaryConditions(Tensor3d &gcpm)\n{\t\n\tfor(int h = 0; h < m_energies; h++)\n\t{\n\t\tout.print(TraceLevel::INFO, \"Apply boundary conditions Group {}\", h + 1);\n\t\t\n\t\tdouble albedo = m_solverData.getAlbedo()[0];\n\t\t\n\t\tVectorXd Pis   = VectorXd::Zero(m_cells);\n\t    VectorXd psi   = VectorXd::Zero(m_cells);\n\t\t\n\t\tPis.setZero();\n\t\tpsi.setZero();\n\n\t\tfor(int i = 0; i < m_cells; i++)\n\t\t{\n\t\t\tfor(int j = 0; j < m_cells; j++)\n\t\t\t{\n\t\t\t\tgcpm(i, j, h) /= m_totalXS(h, j);  //reduced\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor(int i = 0; i < m_cells; i++)\n\t\t{\n\t\t\tfor(int j = 0; j < m_cells; j++)\n\t\t\t{\n\t\t\t\tPis(i) += gcpm(i, j, h) * m_totalXS(h, j);\n\t\t\t}\n\t\t\t\n\t\t\tPis(i) = 1.0 - Pis(i);\n\t\t\tpsi(i) = (4.0 * m_volumes(i) / m_surface) * Pis(i);\n\t\t\t\n\t\t\tout.print(TraceLevel::INFO, \"Cell n: {} Pis: {:7.6e}  psi [cm]: {:7.6e}\", i, Pis(i), psi(i));\n\t\t}\n\t\t\n\t\tdouble Pss = 0.0;\n\t\t\n\t\tfor(int i = 0; i < m_cells; i++)\n        {\n\t\t\tPss += psi(i) * m_totalXS(h, i);\n\t\t}\n\t\t\n\t\tPss = 1.0 - Pss;\n\t\t\n\t\tout.print(TraceLevel::INFO, \"Pss [cm2]: {:7.6e} \\n\", Pss);\n\t\t\n\t\tfor(int i = 0; i < m_cells; i++)\n\t\t{\n\t\t\tfor(int j = 0; j < m_cells; j++)\n\t\t\t{\n\t\t\t\tgcpm(i, j, h) += Pis(i) * psi(j) * (albedo / (1.0 - Pss * albedo));\n\t\t\t\tgcpm(i, j, h) *= m_totalXS(h, j);\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t}\t\n\t\n\tout.print(TraceLevel::INFO, \"P matrix (white BC)\");\n    printMatrix(gcpm, out, TraceLevel::INFO, \"Group\");\n\n    for(int h = 0; h < m_energies; h++)\n\t{\n\t    for(int i = 0; i < m_cells; i++)\n\t\t{\n\t\t\tfor(int j = 0; j < m_cells; j++)\n\t\t\t{\n\t\t\t\tgcpm(i, j, h) /= m_totalXS(h, j);\n\t\t\t}\n\t\t}\n\t}\t\n}\n", "meta": {"hexsha": "2fff5d5a1f67ca52bd17486a69e8e7b2188919cf", "size": 4437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CPM/SlabSpectrumCode.cpp", "max_stars_repo_name": "FrancisKhan/ALMOST", "max_stars_repo_head_hexsha": "06e36666ca18aa06167baac3123dbbe913f74b5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-12-20T15:37:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T18:11:17.000Z", "max_issues_repo_path": "CPM/SlabSpectrumCode.cpp", "max_issues_repo_name": "FrancisKhan/ALMOST", "max_issues_repo_head_hexsha": "06e36666ca18aa06167baac3123dbbe913f74b5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CPM/SlabSpectrumCode.cpp", "max_forks_repo_name": "FrancisKhan/ALMOST", "max_forks_repo_head_hexsha": "06e36666ca18aa06167baac3123dbbe913f74b5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2544378698, "max_line_length": 103, "alphanum_fraction": 0.506874014, "num_tokens": 1760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5379196461154351}}
{"text": "/**********************************************************************\r\n*  Copyright (c) 2008-2014, Alliance for Sustainable Energy.  \r\n*  All rights reserved.\r\n*  \r\n*  This library is free software; you can redistribute it and/or\r\n*  modify it under the terms of the GNU Lesser General Public\r\n*  License as published by the Free Software Foundation; either\r\n*  version 2.1 of the License, or (at your option) any later version.\r\n*  \r\n*  This library is distributed in the hope that it will be useful,\r\n*  but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n*  Lesser General Public License for more details.\r\n*  \r\n*  You should have received a copy of the GNU Lesser General Public\r\n*  License along with this library; if not, write to the Free Software\r\n*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\r\n**********************************************************************/\r\n\r\n#include <gtest/gtest.h>\r\n#include \"GeometryFixture.hpp\"\r\n\r\n#include \"../Transformation.hpp\"\r\n#include \"../Point3d.hpp\"\r\n#include \"../Vector3d.hpp\"\r\n#include \"../EulerAngles.hpp\"\r\n\r\n#include <boost/math/constants/constants.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\nusing namespace openstudio;\r\n\r\nTEST_F(GeometryFixture, RotationTransformations)\r\n{\r\n  double tol = 1.0E-12;\r\n  Vector3d z(0,0,1);\r\n  Point3d point1(1,0,0);\r\n  Transformation T;\r\n  Point3d temp;\r\n\r\n  // identity transformation\r\n  temp = T*point1;\r\n  EXPECT_NEAR(1.0, temp.x(), tol);\r\n  EXPECT_NEAR(0.0, temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n\r\n  // rotation 30 degrees about z\r\n  T = Transformation::rotation(z, degToRad(30));\r\n  temp = T*point1;\r\n  EXPECT_NEAR(cos(degToRad(30)), temp.x(), tol);\r\n  EXPECT_NEAR(sin(degToRad(30)), temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n\r\n  // rotation -30 degrees about z\r\n  temp = T.inverse()*point1;\r\n  EXPECT_NEAR(cos(degToRad(30)), temp.x(), tol);\r\n  EXPECT_NEAR(-sin(degToRad(30)), temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n\r\n  // rotation 0 degrees about z\r\n  temp = T.inverse()*T*point1;\r\n  EXPECT_NEAR(1.0, temp.x(), tol);\r\n  EXPECT_NEAR(0.0, temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n\r\n  // rotation 0 degrees about z\r\n  temp = T*T.inverse()*point1;\r\n  EXPECT_NEAR(1.0, temp.x(), tol);\r\n  EXPECT_NEAR(0.0, temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n\r\n  // rotation 90 degrees about z\r\n  T = Transformation::rotation(z, degToRad(90));\r\n  temp = T*point1;\r\n  EXPECT_NEAR(0.0, temp.x(), tol);\r\n  EXPECT_NEAR(1.0, temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n}\r\n\r\nTEST_F(GeometryFixture, RotationAboutPointTransformations)\r\n{\r\n  double tol = 1.0E-6;\r\n  Vector3d z(0,0,1);\r\n  Point3d point1(1,0,0);\r\n  Transformation T;\r\n  Point3d temp;\r\n\r\n  // rotation around origin, 30 degrees about z\r\n  T = Transformation::rotation(Point3d(0,0,0), z, degToRad(30));\r\n  temp = T*point1;\r\n  EXPECT_NEAR(0.866025, temp.x(), tol);\r\n  EXPECT_NEAR(0.5, temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n\r\n  // rotation around 1*x, 30 degrees about z\r\n  T = Transformation::rotation(Point3d(1,0,0), z, degToRad(30));\r\n  temp = T*point1;\r\n  EXPECT_NEAR(1.0, temp.x(), tol);\r\n  EXPECT_NEAR(0.0, temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n\r\n  // rotation around 1*y, 30 degrees about z\r\n  T = Transformation::rotation(Point3d(0,1,0), z, degToRad(30));\r\n  temp = T*point1;\r\n  EXPECT_NEAR(1.366025, temp.x(), tol);\r\n  EXPECT_NEAR(0.633975, temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n\r\n  // rotation around 1*z, 30 degrees about z\r\n  T = Transformation::rotation(Point3d(0,0,1), z, degToRad(30));\r\n  temp = T*point1;\r\n  EXPECT_NEAR(0.866025, temp.x(), tol);\r\n  EXPECT_NEAR(0.5, temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n\r\n  // rotation around 1*x + 1*y + 1*z, 30 degrees about z\r\n  T = Transformation::rotation(Point3d(1,1,1), z, degToRad(30));\r\n  temp = T*point1;\r\n  EXPECT_NEAR(1.5, temp.x(), tol);\r\n  EXPECT_NEAR(0.133975, temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n}\r\n\r\nTEST_F(GeometryFixture, TranslationTransformations)\r\n{\r\n  double tol = 1.0E-12;\r\n  Vector3d trans(1,1,1);\r\n  Point3d point1(1,0,0);\r\n  Transformation T;\r\n  Point3d temp;\r\n\r\n  // identity transformation\r\n  temp = T*point1;\r\n  EXPECT_NEAR(1.0, temp.x(), tol);\r\n  EXPECT_NEAR(0.0, temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n\r\n  // move by 1, 1, 1\r\n  T = Transformation::translation(trans);\r\n  temp = T*point1;\r\n  EXPECT_NEAR(2.0, temp.x(), tol);\r\n  EXPECT_NEAR(1.0, temp.y(), tol);\r\n  EXPECT_NEAR(1.0, temp.z(), tol);\r\n\r\n  // move by -1, -1, -1\r\n  temp = T.inverse()*point1;\r\n  EXPECT_NEAR(0.0, temp.x(), tol);\r\n  EXPECT_NEAR(-1.0, temp.y(), tol);\r\n  EXPECT_NEAR(-1.0, temp.z(), tol);\r\n\r\n  // identity transformation\r\n  temp = T.inverse()*T*point1;\r\n  EXPECT_NEAR(1.0, temp.x(), tol);\r\n  EXPECT_NEAR(0.0, temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n\r\n  // identity transformation\r\n  temp = T*T.inverse()*point1;\r\n  EXPECT_NEAR(1.0, temp.x(), tol);\r\n  EXPECT_NEAR(0.0, temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n}\r\n\r\nTEST_F(GeometryFixture, AlignZPrimeTransformations)\r\n{\r\n  Vector3d xAxis(1,0,0);\r\n  Vector3d yAxis(0,1,0);\r\n  Vector3d zAxis(0,0,1);\r\n  Transformation T;\r\n\r\n  Vector3d outwardNormal(0, -1, 0);\r\n  T = Transformation::alignZPrime(outwardNormal);\r\n  EXPECT_TRUE(xAxis == T*xAxis);\r\n  EXPECT_TRUE(zAxis == T*yAxis);\r\n  EXPECT_TRUE(outwardNormal == T*zAxis);\r\n\r\n  outwardNormal = Vector3d(1, 0, 0);\r\n  T = Transformation::alignZPrime(outwardNormal);\r\n  EXPECT_TRUE(yAxis == T*xAxis);\r\n  EXPECT_TRUE(zAxis == T*yAxis);\r\n  EXPECT_TRUE(outwardNormal == T*zAxis);\r\n\r\n  outwardNormal = Vector3d(0, 1, 0);\r\n  T = Transformation::alignZPrime(outwardNormal);\r\n  EXPECT_TRUE(-xAxis == T*xAxis);\r\n  EXPECT_TRUE(zAxis == T*yAxis);\r\n  EXPECT_TRUE(outwardNormal == T*zAxis);\r\n\r\n  outwardNormal = Vector3d(-1, 0, 0);\r\n  T = Transformation::alignZPrime(outwardNormal);\r\n  EXPECT_TRUE(-yAxis == T*xAxis);\r\n  EXPECT_TRUE(zAxis == T*yAxis);\r\n  EXPECT_TRUE(outwardNormal == T*zAxis);\r\n\r\n  outwardNormal = Vector3d(0, 0, 1);\r\n  T = Transformation::alignZPrime(outwardNormal);\r\n  EXPECT_TRUE(-xAxis == T*xAxis);\r\n  EXPECT_TRUE(-yAxis == T*yAxis);\r\n  EXPECT_TRUE(outwardNormal == T*zAxis);\r\n\r\n  outwardNormal = Vector3d(0, 0, -1);\r\n  T = Transformation::alignZPrime(outwardNormal);\r\n  EXPECT_TRUE(-xAxis == T*xAxis);\r\n  EXPECT_TRUE(yAxis == T*yAxis);\r\n  EXPECT_TRUE(outwardNormal == T*zAxis);\r\n}\r\n\r\nTEST_F(GeometryFixture, AlignFaceTransformations)\r\n{\r\n  double tol = 1.0E-12;\r\n\r\n  Point3dVector vertices(4);\r\n  vertices[0] = Point3d(1, 0, 1);\r\n  vertices[1] = Point3d(1, 0, 0);\r\n  vertices[2] = Point3d(2, 0, 0);\r\n  vertices[3] = Point3d(2, 0, 1);\r\n  Point3dVector testVertices;\r\n  Point3dVector tempVertices;\r\n  Transformation T;\r\n\r\n  // rotate 0 degrees about z\r\n  testVertices = Transformation::rotation(Vector3d(0,0,1), 0)*vertices;\r\n  T = Transformation::alignFace(testVertices);\r\n  tempVertices = T.inverse()*testVertices;\r\n  EXPECT_NEAR(0, tempVertices[0].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[0].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[0].z(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].z(), tol);\r\n  EXPECT_NEAR(1, tempVertices[2].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].z(), tol);\r\n  EXPECT_NEAR(1, tempVertices[3].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[3].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[3].z(), tol);\r\n\r\n  // rotate 30 degrees about z\r\n  testVertices = Transformation::rotation(Vector3d(0,0,1), degToRad(30))*vertices;\r\n  T = Transformation::alignFace(testVertices);\r\n  tempVertices = T.inverse()*testVertices;\r\n  EXPECT_NEAR(0, tempVertices[0].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[0].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[0].z(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].z(), tol);\r\n  EXPECT_NEAR(1, tempVertices[2].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].z(), tol);\r\n  EXPECT_NEAR(1, tempVertices[3].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[3].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[3].z(), tol);\r\n\r\n  // rotate -30 degrees about z\r\n  testVertices = Transformation::rotation(Vector3d(0,0,1), -degToRad(30))*vertices;\r\n  T = Transformation::alignFace(testVertices);\r\n  tempVertices = T.inverse()*testVertices;\r\n  EXPECT_NEAR(0, tempVertices[0].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[0].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[0].z(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].z(), tol);\r\n  EXPECT_NEAR(1, tempVertices[2].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].z(), tol);\r\n  EXPECT_NEAR(1, tempVertices[3].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[3].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[3].z(), tol);\r\n\r\n  // rotate -30 degrees about x\r\n  testVertices = Transformation::rotation(Vector3d(1,0,0), -degToRad(30))*vertices;\r\n  T = Transformation::alignFace(testVertices);\r\n  tempVertices = T.inverse()*testVertices;\r\n  EXPECT_NEAR(0, tempVertices[0].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[0].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[0].z(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].z(), tol);\r\n  EXPECT_NEAR(1, tempVertices[2].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].z(), tol);\r\n  EXPECT_NEAR(1, tempVertices[3].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[3].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[3].z(), tol);\r\n\r\n  // rotate -90 degrees about x\r\n  testVertices = Transformation::rotation(Vector3d(1,0,0), -degToRad(90))*vertices;\r\n  T = Transformation::alignFace(testVertices);\r\n  tempVertices = T.inverse()*testVertices;\r\n  EXPECT_NEAR(1, tempVertices[0].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[0].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[0].z(), tol);\r\n  EXPECT_NEAR(1, tempVertices[1].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[1].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].z(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[2].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].z(), tol);\r\n  EXPECT_NEAR(0, tempVertices[3].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[3].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[3].z(), tol);\r\n\r\n  // rotate 30 degrees about x\r\n  testVertices = Transformation::rotation(Vector3d(1,0,0), degToRad(30))*vertices;\r\n  T = Transformation::alignFace(testVertices);\r\n  tempVertices = T.inverse()*testVertices;\r\n  EXPECT_NEAR(0, tempVertices[0].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[0].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[0].z(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].z(), tol);\r\n  EXPECT_NEAR(1, tempVertices[2].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].z(), tol);\r\n  EXPECT_NEAR(1, tempVertices[3].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[3].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[3].z(), tol);\r\n\r\n  // rotate 90 degrees about x\r\n  testVertices = Transformation::rotation(Vector3d(1,0,0), degToRad(90))*vertices;\r\n  T = Transformation::alignFace(testVertices);\r\n  tempVertices = T.inverse()*testVertices;\r\n  EXPECT_NEAR(1, tempVertices[0].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[0].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[0].z(), tol);\r\n  EXPECT_NEAR(1, tempVertices[1].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[1].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].z(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].x(), tol);\r\n  EXPECT_NEAR(1, tempVertices[2].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].z(), tol);\r\n  EXPECT_NEAR(0, tempVertices[3].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[3].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[3].z(), tol);\r\n}\r\n\r\nTEST_F(GeometryFixture, AlignFaceTransformations_TrapezoidFloor)\r\n{\r\n  double tol = 1.0E-12;\r\n\r\n  Point3dVector vertices(4);\r\n  vertices[0] = Point3d(27.69, 0, 0);\r\n  vertices[1] = Point3d(0, 0, 0);\r\n  vertices[2] = Point3d(5, 5, 0);\r\n  vertices[3] = Point3d(22.69, 5, 0);\r\n  Point3dVector tempVertices;\r\n  Transformation T;\r\n\r\n  T = Transformation::alignFace(vertices);\r\n  tempVertices = T.inverse()*vertices;\r\n  EXPECT_NEAR(0, tempVertices[0].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[0].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[0].z(), tol);\r\n  EXPECT_NEAR(27.69, tempVertices[1].x(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[1].z(), tol);\r\n  EXPECT_NEAR(22.69, tempVertices[2].x(), tol);\r\n  EXPECT_NEAR(5, tempVertices[2].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[2].z(), tol);\r\n  EXPECT_NEAR(5, tempVertices[3].x(), tol);\r\n  EXPECT_NEAR(5, tempVertices[3].y(), tol);\r\n  EXPECT_NEAR(0, tempVertices[3].z(), tol);\r\n\r\n}\r\n\r\n\r\nTEST_F(GeometryFixture, Transformations)\r\n{\r\n\r\n  /* SketchUp implementation of this test:\r\n      origin = Geom::Point3d.new(0,0,0)\r\n      x_axis = Geom::Vector3d.new(0,0,1)\r\n      y_axis = Geom::Vector3d.new(0,0,1)\r\n      z_axis = Geom::Vector3d.new(0,0,1)\r\n      trans = Geom::Vector3d.new(1,1,1)\r\n\r\n      point = Geom::Point3d.new(1,0,0)\r\n\r\n      temp = Geom::Transformation.rotation(origin, z_axis, 30.degrees)*point\r\n      puts temp\r\n\r\n      temp = Geom::Transformation.translation(trans )*temp\r\n      puts temp\r\n\r\n      temp = Geom::Transformation.rotation(origin, x_axis, 30.degrees)*temp\r\n      puts temp\r\n\r\n      temp = Geom::Transformation.translation(trans )*temp\r\n      puts temp\r\n\r\n      temp = Geom::Transformation.rotation(origin, y_axis, 30.degrees)*temp\r\n      puts temp\r\n\r\n      temp = Geom::Transformation.translation(trans )*temp\r\n      puts temp\r\n  */\r\n\r\n  double tol = 1.0E-6;\r\n  Vector3d xAxis(0,0,1);\r\n  Vector3d yAxis(0,0,1);\r\n  Vector3d zAxis(0,0,1);\r\n  Vector3d trans(1,1,1);\r\n  Point3d point(1,0,0);\r\n  Point3d temp;\r\n\r\n  temp = Transformation::rotation(zAxis, degToRad(30))*point;\r\n  EXPECT_NEAR(0.866025, temp.x(), tol);\r\n  EXPECT_NEAR(0.5, temp.y(), tol);\r\n  EXPECT_NEAR(0.0, temp.z(), tol);\r\n\r\n  temp = Transformation::translation(trans)*temp;\r\n  EXPECT_NEAR(1.866025, temp.x(), tol);\r\n  EXPECT_NEAR(1.5, temp.y(), tol);\r\n  EXPECT_NEAR(1.0, temp.z(), tol);\r\n\r\n  temp = Transformation::rotation(xAxis, degToRad(30))*temp;\r\n  EXPECT_NEAR(0.866025, temp.x(), tol);\r\n  EXPECT_NEAR(2.232051, temp.y(), tol);\r\n  EXPECT_NEAR(1.0, temp.z(), tol);\r\n\r\n  temp = Transformation::translation(trans)*temp;\r\n  EXPECT_NEAR(1.866025, temp.x(), tol);\r\n  EXPECT_NEAR(3.232051, temp.y(), tol);\r\n  EXPECT_NEAR(2.0, temp.z(), tol);\r\n\r\n  temp = Transformation::rotation(yAxis, degToRad(30))*temp;\r\n  EXPECT_NEAR(0.0, temp.x(), tol);\r\n  EXPECT_NEAR(3.732051, temp.y(), tol);\r\n  EXPECT_NEAR(2.0, temp.z(), tol);\r\n\r\n  temp = Transformation::translation(trans)*temp;\r\n  EXPECT_NEAR(1.0, temp.x(), tol);\r\n  EXPECT_NEAR(4.732051, temp.y(), tol);\r\n  EXPECT_NEAR(3.0, temp.z(), tol);\r\n}\r\n\r\nTEST_F(GeometryFixture, EulerAngles)\r\n{\r\n  Transformation transformation;\r\n  EulerAngles angles = transformation.eulerAngles();\r\n  EXPECT_EQ(0.0, angles.psi());\r\n  EXPECT_EQ(0.0, angles.theta());\r\n  EXPECT_EQ(0.0, angles.phi());\r\n\r\n  angles = EulerAngles(0,0,0);\r\n  transformation = Transformation::rotation(angles);\r\n  Matrix rotationMatrix = transformation.rotationMatrix();\r\n  ASSERT_EQ(static_cast<unsigned>(3), rotationMatrix.size1());\r\n  ASSERT_EQ(static_cast<unsigned>(3), rotationMatrix.size2());\r\n  EXPECT_EQ(1.0, rotationMatrix(0,0));\r\n  EXPECT_EQ(0.0, rotationMatrix(0,1));\r\n  EXPECT_EQ(0.0, rotationMatrix(0,2));\r\n  EXPECT_EQ(0.0, rotationMatrix(1,0));\r\n  EXPECT_EQ(1.0, rotationMatrix(1,1));\r\n  EXPECT_EQ(0.0, rotationMatrix(1,2));\r\n  EXPECT_EQ(0.0, rotationMatrix(2,0));\r\n  EXPECT_EQ(0.0, rotationMatrix(2,1));\r\n  EXPECT_EQ(1.0, rotationMatrix(2,2));\r\n\r\n  transformation = Transformation::translation(Vector3d(1,1,1));\r\n  angles = transformation.eulerAngles();\r\n  EXPECT_EQ(0.0, angles.psi());\r\n  EXPECT_EQ(0.0, angles.theta());\r\n  EXPECT_EQ(0.0, angles.phi());\r\n\r\n  transformation = Transformation::rotation(Vector3d(1,0,0), 1.0);\r\n  angles = transformation.eulerAngles();\r\n  EXPECT_EQ(1.0, angles.psi());\r\n  EXPECT_EQ(0.0, angles.theta());\r\n  EXPECT_EQ(0.0, angles.phi());\r\n\r\n  angles = EulerAngles(1,0,0);\r\n  transformation = Transformation::rotation(angles);\r\n  rotationMatrix = transformation.rotationMatrix();\r\n  ASSERT_EQ(static_cast<unsigned>(3), rotationMatrix.size1());\r\n  ASSERT_EQ(static_cast<unsigned>(3), rotationMatrix.size2());\r\n  EXPECT_NEAR(1.0, rotationMatrix(0,0), 0.0001);\r\n  EXPECT_NEAR(0.0, rotationMatrix(0,1), 0.0001);\r\n  EXPECT_NEAR(0.0, rotationMatrix(0,2), 0.0001);\r\n  EXPECT_NEAR(0.0, rotationMatrix(1,0), 0.0001);\r\n  EXPECT_NEAR(cos(1.0), rotationMatrix(1,1), 0.0001);\r\n  EXPECT_NEAR(-sin(1.0), rotationMatrix(1,2), 0.0001);\r\n  EXPECT_NEAR(0.0, rotationMatrix(2,0), 0.0001);\r\n  EXPECT_NEAR(sin(1.0), rotationMatrix(2,1), 0.0001);\r\n  EXPECT_NEAR(cos(1.0), rotationMatrix(2,2), 0.0001);\r\n\r\n  transformation = Transformation::rotation(Vector3d(0,1,0), 1.0);\r\n  angles = transformation.eulerAngles();\r\n  EXPECT_EQ(0.0, angles.psi());\r\n  EXPECT_EQ(1.0, angles.theta());\r\n  EXPECT_EQ(0.0, angles.phi());\r\n\r\n  angles = EulerAngles(0,1,0);\r\n  transformation = Transformation::rotation(angles);\r\n  rotationMatrix = transformation.rotationMatrix();\r\n  ASSERT_EQ(static_cast<unsigned>(3), rotationMatrix.size1());\r\n  ASSERT_EQ(static_cast<unsigned>(3), rotationMatrix.size2());\r\n  EXPECT_NEAR(cos(1.0), rotationMatrix(0,0), 0.0001);\r\n  EXPECT_NEAR(0.0, rotationMatrix(0,1), 0.0001);\r\n  EXPECT_NEAR(sin(1.0), rotationMatrix(0,2), 0.0001);\r\n  EXPECT_NEAR(0.0, rotationMatrix(1,0), 0.0001);\r\n  EXPECT_NEAR(1.0, rotationMatrix(1,1), 0.0001);\r\n  EXPECT_NEAR(0.0, rotationMatrix(1,2), 0.0001);\r\n  EXPECT_NEAR(-sin(1.0), rotationMatrix(2,0), 0.0001);\r\n  EXPECT_NEAR(0.0, rotationMatrix(2,1), 0.0001);\r\n  EXPECT_NEAR(cos(1.0), rotationMatrix(2,2), 0.0001);\r\n\r\n  transformation = Transformation::rotation(Vector3d(0,0,1), 1.0);\r\n  angles = transformation.eulerAngles();\r\n  EXPECT_EQ(0.0, angles.psi());\r\n  EXPECT_EQ(0.0, angles.theta());\r\n  EXPECT_EQ(1.0, angles.phi());\r\n\r\n  angles = EulerAngles(0,0,1);\r\n  transformation = Transformation::rotation(angles);\r\n  rotationMatrix = transformation.rotationMatrix();\r\n  ASSERT_EQ(static_cast<unsigned>(3), rotationMatrix.size1());\r\n  ASSERT_EQ(static_cast<unsigned>(3), rotationMatrix.size2());\r\n  EXPECT_NEAR(cos(1.0), rotationMatrix(0,0), 0.0001);\r\n  EXPECT_NEAR(-sin(1.0), rotationMatrix(0,1), 0.0001);\r\n  EXPECT_NEAR(0.0, rotationMatrix(0,2), 0.0001);\r\n  EXPECT_NEAR(sin(1.0), rotationMatrix(1,0), 0.0001);\r\n  EXPECT_NEAR(cos(1.0), rotationMatrix(1,1), 0.0001);\r\n  EXPECT_NEAR(0.0, rotationMatrix(1,2), 0.0001);\r\n  EXPECT_NEAR(0.0, rotationMatrix(2,0), 0.0001);\r\n  EXPECT_NEAR(0.0, rotationMatrix(2,1), 0.0001);\r\n  EXPECT_NEAR(1.0, rotationMatrix(2,2), 0.0001);\r\n\r\n  Matrix matrix(4,4);\r\n  matrix(0,0) = 0.5;\r\n  matrix(0,1) = -0.1464;\r\n  matrix(0,2) = 0.8536;\r\n  matrix(1,0) = 0.5;\r\n  matrix(1,1) = 0.8536;\r\n  matrix(1,2) = -0.1464;\r\n  matrix(2,0) = -0.7071;\r\n  matrix(2,1) = 0.5;\r\n  matrix(2,2) = 0.5;\r\n  matrix(3,3) = 1.0;\r\n\r\n  transformation = Transformation(matrix);\r\n  angles = transformation.eulerAngles();\r\n  EXPECT_NEAR(boost::math::constants::pi<double>()/4.0, angles.psi(), 0.0001);\r\n  EXPECT_NEAR(boost::math::constants::pi<double>()/4.0, angles.theta(), 0.0001);\r\n  EXPECT_NEAR(boost::math::constants::pi<double>()/4.0, angles.phi(), 0.0001);\r\n\r\n  angles = EulerAngles(boost::math::constants::pi<double>()/4.0,\r\n                       boost::math::constants::pi<double>()/4.0,\r\n                       boost::math::constants::pi<double>()/4.0);\r\n  transformation = Transformation::rotation(angles);\r\n  rotationMatrix = transformation.rotationMatrix();\r\n  EXPECT_NEAR(0.5, rotationMatrix(0,0), 0.0001);\r\n  EXPECT_NEAR(-0.1464, rotationMatrix(0,1), 0.0001);\r\n  EXPECT_NEAR(0.8536, rotationMatrix(0,2), 0.0001);\r\n  EXPECT_NEAR(0.5, rotationMatrix(1,0), 0.0001);\r\n  EXPECT_NEAR(0.8536, rotationMatrix(1,1), 0.0001);\r\n  EXPECT_NEAR(-0.1464, rotationMatrix(1,2), 0.0001);\r\n  EXPECT_NEAR(-0.7071, rotationMatrix(2,0), 0.0001);\r\n  EXPECT_NEAR(0.5, rotationMatrix(2,1), 0.0001);\r\n  EXPECT_NEAR(0.5, rotationMatrix(2,2), 0.0001);\r\n}\r\n\r\nTEST_F(GeometryFixture, Transformation_Decompose)\r\n{\r\n  Transformation translation = Transformation::translation(Vector3d(1, 0, 0));\r\n  Transformation rotation = Transformation::rotation(Vector3d(0,0,1), degToRad(-90));\r\n\r\n  Transformation transformation = translation*rotation;\r\n  Vector3d origin = transformation.translation();\r\n  EulerAngles angles = transformation.eulerAngles();\r\n  Transformation test = Transformation::translation(origin)*Transformation::rotation(angles);\r\n\r\n  EXPECT_TRUE(transformation.matrix() == test.matrix()) << transformation.matrix() << std::endl << test.matrix();\r\n\r\n  transformation = rotation*translation;\r\n  origin = transformation.translation();\r\n  angles = transformation.eulerAngles();\r\n  test = Transformation::translation(origin)*Transformation::rotation(angles);\r\n\r\n  EXPECT_TRUE(transformation.matrix() == test.matrix()) << transformation.matrix() << std::endl << test.matrix();\r\n\r\n}\r\n", "meta": {"hexsha": "284c18bb0533cb30cefec5f24cc99776b38d8555", "size": 21366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/geometry/Test/Transformation_GTest.cpp", "max_stars_repo_name": "zhouchong90/OpenStudio", "max_stars_repo_head_hexsha": "f8570cb8297547b5e9cc80fde539240d8f7b9c24", "max_stars_repo_licenses": ["BSL-1.0", "blessing"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openstudiocore/src/utilities/geometry/Test/Transformation_GTest.cpp", "max_issues_repo_name": "zhouchong90/OpenStudio", "max_issues_repo_head_hexsha": "f8570cb8297547b5e9cc80fde539240d8f7b9c24", "max_issues_repo_licenses": ["BSL-1.0", "blessing"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openstudiocore/src/utilities/geometry/Test/Transformation_GTest.cpp", "max_forks_repo_name": "zhouchong90/OpenStudio", "max_forks_repo_head_hexsha": "f8570cb8297547b5e9cc80fde539240d8f7b9c24", "max_forks_repo_licenses": ["BSL-1.0", "blessing"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3367346939, "max_line_length": 114, "alphanum_fraction": 0.6589441168, "num_tokens": 6618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5378211386699382}}
{"text": "/**\n * @file\n * @brief NPDE homework TestQuadratureRules\n * @author Erick Schulz, Liaowang Huang (refactoring)\n * @date 08/03/2019, 22/02/2020 (refactoring)\n * @copyright Developed at ETH Zurich\n */\n\n#include \"testquadraturerules.h\"\n\n#include <lf/base/base.h>\n#include <lf/quad/quad.h>\n\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace TestQuadratureRules {\n\ndouble factorial(int i) { return std::tgamma(i + 1); }\n\n/* SAM_LISTING_BEGIN_1 */\nbool testQuadOrderTria(const lf::quad::QuadRule &quad_rule,\n                       unsigned int order) {\n  bool order_isExact = true;  // return variable\n  //====================\n  // Your code goes here\n  //====================\n  return order_isExact;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nbool testQuadOrderQuad(const lf::quad::QuadRule &quad_rule,\n                       unsigned int order) {\n  bool order_isExact = true;  // return variable\n\n  //====================\n  // Your code goes here\n  //====================\n  return order_isExact;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\nunsigned int calcQuadOrder(const lf::quad::QuadRule &quad_rule) {\n  unsigned int maximal_order = quad_rule.Order();\n\n  //====================\n  // Your code goes here\n  //====================\n  return maximal_order;\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace TestQuadratureRules\n", "meta": {"hexsha": "54a07bad5547bd212ac07ab556085718068b7f04", "size": 1353, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/TestQuadratureRules/templates/testquadraturerules.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/TestQuadratureRules/templates/testquadraturerules.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/TestQuadratureRules/templates/testquadraturerules.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 23.7368421053, "max_line_length": 65, "alphanum_fraction": 0.6215816704, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.769080247656264, "lm_q1q2_score": 0.5377827633226074}}
{"text": "//\n// Created by erik on 10/1/16.\n//\n\n#include \"vec.h\"\n#define BOOST_TEST_MODULE VEC\n#include <boost/test/included/unit_test.hpp>\n\n\nBOOST_AUTO_TEST_SUITE(VecTest)\n    using spatacs::Vec;\n    BOOST_AUTO_TEST_CASE(OPS)\n    {\n        Vec a = {1, 2, 3};\n        Vec b = {5, 4, 7};\n\n        BOOST_CHECK_EQUAL(a + b, (Vec{6, 6, 10}));\n        Vec c = a;\n        c += b;\n        BOOST_CHECK_EQUAL( c , a + b );\n\n        BOOST_CHECK_EQUAL( b - a , (Vec{4, 2, 4}) );\n        c -= b;\n        BOOST_CHECK_EQUAL(c , a);\n\n        float f = 2;\n        BOOST_CHECK_EQUAL(1*a , a);\n        BOOST_CHECK_EQUAL(f*a , a*f);\n        BOOST_CHECK_EQUAL(2*a , (Vec{2, 4, 6}));\n        c *= f;\n        BOOST_CHECK_EQUAL(c , f*a);\n    }\n\n    BOOST_AUTO_TEST_CASE(Length)\n    {\n        Vec a = {1, 0, 0};\n        BOOST_CHECK_EQUAL(1 , length(a));\n\n        Vec b = {2, 2, 1};\n        BOOST_CHECK_EQUAL(3 , length(b));\n\n        BOOST_CHECK_EQUAL(length(2*b) , 2*length(b));\n    }\n\n    BOOST_AUTO_TEST_CASE(Dot)\n    {\n        Vec a = {1, 3, 2};\n        Vec b = {2, 2, 1};\n        Vec c = {0, 3, 1};\n        BOOST_CHECK_EQUAL(dot(b, b) , length(b) * length(b));\n\n        Vec ex = {1, 0, 0};\n        Vec ey = {0, 1, 0};\n        Vec ez = {0, 0, 1};\n        BOOST_CHECK_EQUAL(dot(ex, b) , b.x);\n        BOOST_CHECK_EQUAL(dot(ey, b) , b.y);\n        BOOST_CHECK_EQUAL(dot(ez, b) , b.z);\n\n        BOOST_CHECK_EQUAL( dot(a+b, c) , dot(a, c) + dot(b, c));\n        BOOST_CHECK_EQUAL( dot(a, b) , dot(b, a));\n        BOOST_CHECK_EQUAL( dot(2*a, b) , 2*dot(a, b));\n    }\n\n    BOOST_AUTO_TEST_CASE(Decomposition)\n    {\n        Vec a = {1, 3, 2};\n        Vec b = {2, 2, 1};\n        Vec ex = {1, 0, 0};\n\n        BOOST_CHECK_EQUAL(parallel(a, ex) , (Vec{1, 0, 0}));\n        BOOST_CHECK_EQUAL(perpendicular(a, ex) , (Vec{0, 3, 2}));\n\n        BOOST_CHECK_EQUAL(parallel(a, b) + perpendicular(a, b) , a);\n        BOOST_CHECK_EQUAL(parallel(a, b) , parallel(a, 2*b));\n        BOOST_CHECK_EQUAL(perpendicular(a, b) , perpendicular(a, 2*b));\n\n        BOOST_CHECK_SMALL( dot(parallel(a, b), perpendicular(a, b)), 1e-6 );\n    }\n\n    BOOST_AUTO_TEST_CASE(Decomposition_CornerCases)\n    {\n        Vec a = {1, 3, 2};\n        Vec ex = {0, 0, 0};\n\n        BOOST_CHECK_EQUAL(parallel(a, ex) , a);\n        BOOST_CHECK_EQUAL(perpendicular(a, ex) , a);\n    }\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a6b36d4fc049e6ac5781018475fdd111a28366a1", "size": 2324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/vec_test.cpp", "max_stars_repo_name": "ngc92/SpaTacS", "max_stars_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "max_stars_repo_licenses": ["MIT"], "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/vec_test.cpp", "max_issues_repo_name": "ngc92/SpaTacS", "max_issues_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "max_issues_repo_licenses": ["MIT"], "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/vec_test.cpp", "max_forks_repo_name": "ngc92/SpaTacS", "max_forks_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "max_forks_repo_licenses": ["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.1123595506, "max_line_length": 76, "alphanum_fraction": 0.5210843373, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5377827607407268}}
{"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//! \\file\r\n//!\\brief Tests round-trip for fixed_point negatable with 2 decimal digits.\r\n\r\n#define BOOST_TEST_MODULE test_negatable_round_trip_digits10_002\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/cstdint.hpp>\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/lexical_cast.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 2 decimal digits of precision.\r\n  typedef\r\n  boost::fixed_point::negatable<0,\r\n                                -8,\r\n                                boost::fixed_point::round::nearest_even>\r\n  fixed_point_type;\r\n\r\n  bool round_trip(const fixed_point_type& x);\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 << std::setprecision(std::numeric_limits<fixed_point_type>::digits10)\r\n      << 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_digits10_002)\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(99);\r\n\r\n  bool b = true;\r\n\r\n  // Test every single value with 2 decimal digits of precision\r\n  // ranging from 0.01, 0.02, 0.03, ... 0.99.\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 << count;\r\n\r\n    std::string str(ss1.str());\r\n\r\n    str.insert(std::string::size_type(0U),\r\n               std::string::size_type(2U) - ((std::min)(std::string::size_type(2U), str.length())),\r\n               char('0'));\r\n\r\n    const fixed_point_type x(boost::lexical_cast<floating_point_type>(str.insert(std::string::size_type(0U), \"0.\")));\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": "fc7ec293f82a9342362fbbe83bd1c96c3b8dd693", "size": 2564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_round_trip_digits10_002.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_digits10_002.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_digits10_002.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": 26.9894736842, "max_line_length": 118, "alphanum_fraction": 0.6478159126, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.5377827485186418}}
{"text": "#include \"advent.hpp\"\n\n#include <bitset>\n#include <fmt/color.h>\n#include <fmt/ranges.h>\n#include <fstream>\n#include <gsl/gsl_util>\n#include <iostream>\n#include <numeric>\n#include <queue>\n#include <ranges>\n#include <scn/scn.h>\n#include <unordered_set>\n#include <vector>\n\n#include <Eigen/Core>\n#include <robin_hood.h>\n\nusing std::array;\nusing std::ifstream;\nusing std::pair;\nusing std::queue;\nusing std::string;\nusing std::string_view;\nusing std::vector;\nusing std::ranges::sort;\nusing std::views::iota;\n\nauto day09(int argc, char** argv) -> int\n{\n    if (argc < 2) {\n        fmt::print(\"Error: no input.\");\n        return 1;\n    }\n\n    ifstream infile(argv[1]); // NOLINT\n    string line;\n\n    std::getline(infile, line);\n\n    const i64 nrow = std::count(std::istreambuf_iterator<char>(infile), std::istreambuf_iterator<char>(), '\\n');\n    const i64 ncol = std::ssize(line);\n\n    Eigen::Array<i64, -1, -1> map(nrow + 1, ncol);\n\n    infile.seekg(0); // rewind the input stream\n\n    i64 row { 0 };\n    while (std::getline(infile, line)) { // NOLINT\n        i64 v { 0 };\n        for (auto i : iota(0, std::ssize(line))) {\n            scn::scan(std::string { line[i] }, \"{}\", v);\n            map(row, i) = v;\n        }\n        ++row;\n    }\n\n    using point = pair<i64, i64>;\n\n    // part1\n    vector<point> low_points;\n    for (auto i : iota(0, map.rows())) {\n        auto x = std::max(0, i-1);\n        auto sx = std::min(3L - (i == 0), map.rows() - x);\n\n        for (auto j : iota(0, map.cols())) {\n            auto y = std::max(0, j-1);\n            auto sy = std::min(3L - (j == 0), map.cols() - y);\n            if ((map.block(x, y, sx, sy) <= map(i, j)).count() == 1) {\n                low_points.emplace_back(i, j);\n            }\n        }\n    }\n    auto part1 = std::transform_reduce(low_points.begin(), low_points.end(), u64 { 0 }, std::plus<> {}, [&](auto p) { return map(p.first, p.second); }) + low_points.size();\n    fmt::print(\"part 1: {}\\n\", part1);\n\n    // part2\n    // we simply do a fill flood \n    vector<u64> basin_sizes;\n    basin_sizes.reserve(low_points.size());\n    decltype(map) visited = decltype(map)::Zero(map.rows(), map.cols());\n    queue<point> q;\n\n    auto visit = [&](auto i, auto j) {\n        if (visited(i, j)) { return; }\n        visited(i, j) = 1;\n        q.push({ i, j });\n    };\n\n    const i64 max_height = 9;\n    auto valid = [max_height](auto x, auto v) { return x > v && x < max_height; };\n\n    for (auto [i, j] : low_points) {\n        visit(i, j);\n\n        u64 sz { 0 };\n        while (!q.empty()) {\n            auto [x, y] = q.front();\n            q.pop();\n            auto v = map(x, y);\n            ++sz;\n\n            if (x > 0 && valid(map(x-1, y), v))              { visit(x-1, y); }\n            if (x < map.rows() - 1 && valid(map(x+1, y), v)) { visit(x+1, y); }\n            if (y > 0 && valid(map(x, y-1), v))              { visit(x, y-1); }\n            if (y < map.cols() - 1 && valid(map(x, y+1), v)) { visit(x, y+1); }\n        }\n        basin_sizes.push_back(sz);\n    }\n    sort(basin_sizes);\n    auto part2 = std::reduce(std::rbegin(basin_sizes), std::rbegin(basin_sizes) + 3, u64 { 1 }, std::multiplies<> {});\n    fmt::print(\"part 2: {}\\n\", part2);\n\n    return 0;\n}\n", "meta": {"hexsha": "565b41ab3ed0847aa522546a0f1ab04d9622b82f", "size": 3213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/day09.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/day09.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/day09.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": 27.6982758621, "max_line_length": 172, "alphanum_fraction": 0.5163398693, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5377827485186417}}
{"text": "#ifndef ROBOT_HPP\n#define ROBOT_HPP\n\n#include <math.h>\n#include <armadillo>\n#include \"dynamicalSystems/system.hpp\"\n#include \"dynamicalSystems/cartpendulum.hpp\"\n#include \"dSAClib/SAC.hpp\"\n#include \"dSAClib/objective.hpp\"\n\n#include \"dynamicalSystems/koopman/koopman_operator.hpp\"\n#include \"dynamicalSystems/koopman/basis_functions/basis.hpp\"\n\ntypedef PolynomialBasis BasisFun;\n\nclass Robot {\n\npublic:\n    System* sys;\n    KoopmanOperator* ksys;\n    arma::vec x0;\n    deiSAC* controller;\n    float time_step;\n\n    Robot(float _dt) {\n        time_step = _dt;\n        const float T = 1.5;\n        const int N = T/time_step;\n        sys = new CartPendulum(time_step);\n        ksys = new KoopmanOperator(new BasisFun());\n        arma::vec Qdiag = arma::zeros<arma::vec>(ksys->_nX);\n        Qdiag.head_rows(2) = arma::vec({100, 0.001});\n        const arma::vec xd = arma::zeros<arma::vec>(ksys->_nX);\n        const arma::mat Q = arma::diagmat(Qdiag);\n        arma::vec Rdiag = {0.1};\n        const arma::mat R = arma::diagmat(Rdiag);\n        arma::vec umax = (5)*arma::ones<arma::vec>(ksys->_nU);\n        arma::vec unom = (0.01)*arma::ones<arma::vec>(ksys->_nU);\n        controller = new deiSAC(ksys,\n                                new Objective(Q, R, xd, new BasisFun()),\n                                N, umax, unom);\n\n    }\n\n    ~Robot() {\n        std::cout << \"Deconstructing the robot\" << std::endl;\n        delete controller;\n        delete sys;\n    }\n\n};\n\n#endif\n", "meta": {"hexsha": "ae21ea9d7d50d21783fe478ee9c9f9ebaffcc664", "size": 1464, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/model_based_shared_control/src/robotlib/robot.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/robot.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/robot.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": 27.1111111111, "max_line_length": 72, "alphanum_fraction": 0.6004098361, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5377725759322476}}
{"text": "//  Copyright John Maddock 2007.\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 \"required_defines.hpp\"\n\n#include \"performance_measure.hpp\"\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/array.hpp>\n\n#define T double\n#include \"../test/igamma_big_data.ipp\"\n#include \"../test/igamma_int_data.ipp\"\n#include \"../test/igamma_med_data.ipp\"\n#include \"../test/igamma_small_data.ipp\"\n\ntemplate <std::size_t N>\ndouble igamma_evaluate2(const boost::array<boost::array<T, 6>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n   {\n      result += boost::math::gamma_p(data[i][0], data[i][1]);\n      result += boost::math::gamma_q(data[i][0], data[i][1]);\n   }\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(igamma_test, \"igamma\")\n{\n   double result = igamma_evaluate2(igamma_big_data);\n   result += igamma_evaluate2(igamma_int_data);\n   result += igamma_evaluate2(igamma_med_data);\n   result += igamma_evaluate2(igamma_small_data);\n\n   consume_result(result);\n   set_call_count(\n      2 * (sizeof(igamma_big_data) \n      + sizeof(igamma_int_data) \n      + sizeof(igamma_med_data)\n      + sizeof(igamma_small_data)) / sizeof(igamma_big_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble igamma_inv_evaluate2(const boost::array<boost::array<T, 6>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n   {\n      result += boost::math::gamma_p_inv(data[i][0], data[i][5]);\n      result += boost::math::gamma_q_inv(data[i][0], data[i][3]);\n   }\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(igamma_inv_test, \"igamma_inv\")\n{\n   double result = igamma_inv_evaluate2(igamma_big_data);\n   result += igamma_inv_evaluate2(igamma_int_data);\n   result += igamma_inv_evaluate2(igamma_med_data);\n   result += igamma_inv_evaluate2(igamma_small_data);\n\n   consume_result(result);\n   set_call_count(\n      2 * (sizeof(igamma_big_data) \n      + sizeof(igamma_int_data) \n      + sizeof(igamma_med_data)\n      + sizeof(igamma_small_data)) / sizeof(igamma_big_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble igamma_inva_evaluate2(const boost::array<boost::array<T, 6>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n   {\n      result += boost::math::gamma_p_inva(data[i][1], data[i][5]);\n      result += boost::math::gamma_q_inva(data[i][1], data[i][3]);\n   }\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(igamma_inva_test, \"igamma_inva\")\n{\n   double result = igamma_inva_evaluate2(igamma_big_data);\n   result += igamma_inva_evaluate2(igamma_int_data);\n   result += igamma_inva_evaluate2(igamma_med_data);\n   result += igamma_inva_evaluate2(igamma_small_data);\n\n   consume_result(result);\n   set_call_count(\n      2 * (sizeof(igamma_big_data) \n      + sizeof(igamma_int_data) \n      + sizeof(igamma_med_data)\n      + sizeof(igamma_small_data)) / sizeof(igamma_big_data[0]));\n}\n\n#ifdef TEST_CEPHES\n\nextern \"C\" {\n\ndouble igam(double, double);\ndouble igami(double, double);\n\n}\n\ntemplate <std::size_t N>\ndouble igamma_evaluate_cephes(const boost::array<boost::array<T, 6>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += igam(data[i][0], data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(igamma_test, \"igamma-cephes\")\n{\n   double result = igamma_evaluate_cephes(igamma_big_data);\n   result += igamma_evaluate_cephes(igamma_int_data);\n   result += igamma_evaluate_cephes(igamma_med_data);\n   result += igamma_evaluate_cephes(igamma_small_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(igamma_big_data) \n      + sizeof(igamma_int_data) \n      + sizeof(igamma_med_data)\n      + sizeof(igamma_small_data)) / sizeof(igamma_big_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble igamma_inv_evaluate_cephes(const boost::array<boost::array<T, 6>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += igami(data[i][0], data[i][3]); // note needs complement of probability!!\n   return result;\n}\n\n//\n// This test does not run to completion, gets stuck\n// in infinite loop inside cephes....\n//\nBOOST_MATH_PERFORMANCE_TEST(igamma_inv_test, \"igamma_inv-cephes\")\n{\n   double result = igamma_inv_evaluate_cephes(igamma_big_data);\n   result += igamma_inv_evaluate_cephes(igamma_int_data);\n   result += igamma_inv_evaluate_cephes(igamma_med_data);\n   result += igamma_inv_evaluate_cephes(igamma_small_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(igamma_big_data) \n      + sizeof(igamma_int_data) \n      + sizeof(igamma_med_data)\n      + sizeof(igamma_small_data)) / sizeof(igamma_big_data[0]));\n}\n#endif\n\n#ifdef TEST_GSL\n\n#include <gsl/gsl_sf_gamma.h>\n\ntemplate <std::size_t N>\ndouble igamma_evaluate_gsl(const boost::array<boost::array<T, 6>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += gsl_sf_gamma_inc_P(data[i][0], data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(igamma_test, \"igamma-gsl\")\n{\n   double result = igamma_evaluate_gsl(igamma_big_data);\n   result += igamma_evaluate_gsl(igamma_int_data);\n   result += igamma_evaluate_gsl(igamma_med_data);\n   result += igamma_evaluate_gsl(igamma_small_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(igamma_big_data) \n      + sizeof(igamma_int_data) \n      + sizeof(igamma_med_data)\n      + sizeof(igamma_small_data)) / sizeof(igamma_big_data[0]));\n}\n\n#endif\n", "meta": {"hexsha": "b81de2bfa97e6fa660d441ce2806a082905c3f08", "size": 5478, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/performance/test_igamma.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": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T17:17:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-22T17:17:41.000Z", "max_issues_repo_path": "libs/math/performance/test_igamma.cpp", "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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/performance/test_igamma.cpp", "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": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T05:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T05:20:43.000Z", "avg_line_length": 28.6806282723, "max_line_length": 88, "alphanum_fraction": 0.7015334064, "num_tokens": 1599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5377725734304244}}
{"text": "#include <iostream>\n#include <cmath>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\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>>>>\n    graph;\n\ntypedef traits::vertex_descriptor vertex_desc;\ntypedef traits::edge_descriptor edge_desc;\n\nclass edge_adder\n{\n    graph &G;\n\npublic:\n    explicit edge_adder(graph &G) : G(G) {}\n\n    void add_edge(int from, int to, long capacity)\n    {\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    void add_edge_if_exists(int i1, int j1, int i2, int j2, int n, std::vector<bool>& present) {\n        int from = i1 * n + j1;\n        int to = i2 * n + j2;\n        if (i1 < 0 || i2 < 0 || j1 < 0 || j2 < 0 \n            || i1 >= n || i2 >= n || j1 >= n || j2 >= n \n            || !present[from] || !present[to]) {\n            return;\n        }\n        add_edge(from, to, 1);\n    }\n};\n\nusing namespace std;\n\nvoid solve() {\n    int n; cin >> n;\n\n    graph G(n * n);\n    edge_adder adder(G);\n\n    auto source = boost::add_vertex(G);\n    auto target = boost::add_vertex(G);\n\n\n    bool p;\n    vector<bool> present(n * n, false);\n    int count = 0;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> p;\n            present[i * n + j] = p;\n\n            if (!p) {\n                continue;\n            }\n\n            ++count;\n\n            int parity = (i + j) % 2;\n            if (parity == 0) {\n                adder.add_edge(source, i * n + j, 1);\n            }\n            else {\n                adder.add_edge(i * n + j, target, 1);\n            }\n        }\n    }\n\n    // Build conflict graph\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            int parity = (i + j) % 2;\n            if (parity == 1) {\n                continue;\n            }\n            adder.add_edge_if_exists(i, j, (i - 1), (j - 2), n, present);\n            adder.add_edge_if_exists(i, j, (i - 1), (j + 2), n, present);\n            adder.add_edge_if_exists(i, j, (i + 1), (j - 2), n, present);\n            adder.add_edge_if_exists(i, j, (i + 1), (j + 2), n, present);\n            adder.add_edge_if_exists(i, j, (i - 2), (j - 1), n, present);\n            adder.add_edge_if_exists(i, j, (i - 2), (j + 1), n, present);\n            adder.add_edge_if_exists(i, j, (i + 2), (j - 1), n, present);\n            adder.add_edge_if_exists(i, j, (i + 2), (j + 1), n, present);\n        }\n    }\n\n\n    long maxFlow = boost::push_relabel_max_flow(G, source, target);\n    long maxMatching = maxFlow;\n    long minVC = maxMatching;\n    long maxIS = count - minVC;\n\n    cout << maxIS << endl;\n}\n\nint main() {\n    int t; cin >> t;\n    for (int i = 0; i < t; ++i) {\n        solve();\n    }\n}", "meta": {"hexsha": "815dafe914d2b019464b2940d87e5d56fcc8c37e", "size": 3453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/placing_knights.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/placing_knights.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/placing_knights.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.2894736842, "max_line_length": 128, "alphanum_fraction": 0.4975383724, "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5377725687477815}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2018-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#ifndef BOOST_GEOMETRY_ARITHMETIC_LINE_FUNCTIONS_HPP\n#define BOOST_GEOMETRY_ARITHMETIC_LINE_FUNCTIONS_HPP\n\n#include <boost/geometry/arithmetic/determinant.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/config.hpp>\n#include <boost/geometry/geometries/infinite_line.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace arithmetic\n{\n\ntemplate <typename Line, typename Line::type Line::* member1, typename Line::type Line::* member2>\ninline auto determinant(Line const& p, Line const& q)\n{\n    return geometry::detail::determinant<typename Line::type>(p.*member1, p.*member2,\n                                                              q.*member1, q.*member2);\n}\n\ntemplate <typename Point, typename Line, typename Type>\ninline Point assign_intersection_point(Line const& p, Line const& q, Type const& denominator)\n{\n    BOOST_ASSERT(denominator != Type(0));\n\n    // x = | pb pc | / d  and y = | pc pa | / d\n    //     | qb qc |              | qc qa |\n\n    Point result;\n    geometry::set<0>(result, determinant<Line, &Line::b, &Line::c>(p, q) / denominator);\n    geometry::set<1>(result, determinant<Line, &Line::c, &Line::a>(p, q) / denominator);\n    return result;\n}\n\n// Calculates intersection point of two infinite lines.\n// Returns true if the lines intersect.\n// Returns false if lines are parallel (or collinear, possibly opposite)\ntemplate <typename Line, typename Point>\ninline bool intersection_point(Line const& p, Line const& q, Point& ip)\n{\n    auto const denominator = determinant<Line, &Line::a, &Line::b>(p, q);\n    constexpr decltype(denominator) const zero = 0;\n\n    if (math::equals(denominator, zero))\n    {\n        // Lines are parallel\n        return false;\n    }\n\n    ip = assign_intersection_point<Point>(p, q, denominator);\n\n    return true;\n}\n\n//! Return a distance-side-measure for a point to a line\n//! Point is located left of the line if value is positive,\n//! right of the line is value is negative, and on the line if the value\n//! is exactly zero\ntemplate <typename Type, typename CoordinateType>\ninline\ntypename select_most_precise<Type, CoordinateType>::type\nside_value(model::infinite_line<Type> const& line,\n    CoordinateType const& x, CoordinateType const& y)\n{\n    // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_an_equation\n    // Distance from point to line in general form is given as:\n    // (a * x + b * y + c) / sqrt(a * a + b * b);\n    // In most use cases comparisons are enough, saving the sqrt\n    // and often even the division.\n    // Also, this gives positive values for points left to the line,\n    // and negative values for points right to the line.\n    return line.a * x + line.b * y + line.c;\n}\n\ntemplate <typename Type, typename Point>\ninline\ntypename select_most_precise\n<\n    Type,\n    typename geometry::coordinate_type<Point>::type\n>::type\nside_value(model::infinite_line<Type> const& line, Point const& p)\n{\n    return side_value(line, geometry::get<0>(p), geometry::get<1>(p));\n}\n\ntemplate <typename Type>\ninline bool is_degenerate(const model::infinite_line<Type>& line)\n{\n    static Type const zero = 0;\n    return math::equals(line.a, zero) && math::equals(line.b, zero);\n}\n\n\n} // namespace arithmetic\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ARITHMETIC_LINE_FUNCTIONS_HPP\n", "meta": {"hexsha": "529e83716bc281e8ccd547599c6c87c4746b3fce", "size": 3741, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/arithmetic/infinite_line_functions.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/arithmetic/infinite_line_functions.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/arithmetic/infinite_line_functions.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": 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.8157894737, "max_line_length": 98, "alphanum_fraction": 0.7035551991, "num_tokens": 915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5377725687477815}}
{"text": "/* \n    Authors: Darya Filippova, Geet Duggal, Rob Patro\n    dfilippo | geet | robp @cs.cmu.edu\n    See LICENSE.txt included with this distribution.\n*/\n\n#include <limits>\n#include <boost/heap/binomial_heap.hpp>\n#include <algorithm>\n#include \"ArmatusDAG.hpp\"\n\n\n/*\n\nOPT(l) = max{  max_{ k<l } OPTD(k-1),  // OPT(l) ends in a non-domain\n               OPTD(l) }               // OPT(l) ends in a domain\n\nOPTD(l) = max_{ k<l } OPT(k-1) + q(k,l)\n\nq(k,l) = {  s(k,l)   if s(k,l) > 0,\n            -inf     otherwise  }\n\nOPT(0) = OPT(1) = OPTD(0) = OPTD(1) = 0\n\n*/\n\nArmatusDAG::ArmatusDAG(ArmatusParams& p) : \n    OPT(SubProbMatrix(p.n+1)),\n    OPTD(SubProbMatrix(p.n+1)) { \n\tparams = &p;\n    for (size_t l=0; l <= p.n; l++) {\n       OPT[l].resize(p.K); \n       OPTD[l].resize(p.K); \n    }\n}\n\ndouble ArmatusDAG::s(size_t k, size_t l) {\n    size_t d_i = d(k,l);\n    return params->sums(k-1, l-1)/ std::pow(static_cast<double>(d_i),params->gamma);\n}\n\n\n/*\nq(k,l) = {  s(k,l)   if s(k,l) > 0,\n            -inf     otherwise }\n*/\ndouble ArmatusDAG::q(size_t k, size_t l) {\n    size_t d_i = d(k,l);\n    double score = (s(k, l) - params->mu[d_i]);\n    if (score > 0) {\n        return score;\n    }\n\treturn -std::numeric_limits<double>::infinity();\n}\n\nvoid ArmatusDAG::build() {\n    // OPTD(0) = OPTD(1) = 0 for all K near-optimal solutions\n    OPT[0][0] = OPT[1][0] = {0, 1, 0};\n    OPTD[0][0] = OPTD[1][0] = {0, 1, 0};\n    for (size_t i=1; i<params->K; i++) {\n        OPT[0][i] = OPT[1][i] = {-std::numeric_limits<double>::infinity(), 1, 0};\n        OPTD[0][i] = OPTD[1][i] = {-std::numeric_limits<double>::infinity(), 1, 0};\n    }\n\n    // Build optimal solutions for l=2 to n\n    for (size_t l=2; l<=params->n; l++) {\n\n        // Initialize best scores and backpointers\n        double scoreDomain, scoreNonDomain;\n        size_t backPointerDomain, backPointerNonDomain;\n\n        scoreDomain = scoreNonDomain = -std::numeric_limits<double>::infinity();\n        backPointerDomain = backPointerNonDomain = 1;\n\n\n        // max_{ k<l } OPTD( k-1 )\n        for (size_t k=1; k<l; k++) {\n            if (OPTD[k-1][0].score > scoreNonDomain) {\n                scoreNonDomain = OPTD[k-1][0].score;\n                backPointerNonDomain = k;\n            }\n        }\n\n        // OPTD(l) = max_{ k<l } OPT(k-1) + q(k,l)\n        for (size_t k=1; k<l; k++) {\n            double candidateScore = OPT[k-1][0].score + q(k,l);\n            if (candidateScore > scoreDomain) {\n                scoreDomain = candidateScore;\n                backPointerDomain = k;\n            }\n        }\n        OPTD[l][0] = {scoreDomain, backPointerDomain, 0};\n\n        /*  OPT(l) = max{  max_{ k<l } OPTD(k-1),  // OPT(l) ends in a non-domain\n                           OPTD(l) }               // OPT(l) ends in a domain     */\n        if (scoreNonDomain > scoreDomain) {\n            OPT[l][0] = {scoreNonDomain, backPointerNonDomain, 0};\n        } else {\n            OPT[l][0] = OPTD[l][0];\n        }\n    }\n    cout << \"OPTIMAL SCORE: \" << OPT[params->n][0].score << endl;\n}\n\nvoid ArmatusDAG::computeTopK() {\n    std::cerr << \"begin computeTopK()\\n\";\n    for (size_t l=2; l<=params->n; l++) {\n        /*\n        \n        OPT(l) = max{  max_{ k<l } OPTD(k-1),  // OPT(l) ends in a non-domain\n                       OPTD(l) }               // OPT(l) ends in a domain\n        \n        OPTD(l) = max_{ k<l } OPT(k-1) + q(k,l)\n        \n        */\n        using heapT = boost::heap::binomial_heap<SubProblem>;\n        heapT heapOPTNonDomain;\n        heapT heapOPTDomain;\n\n        for (size_t k=1; k<l; k++) {\n            auto nonDomainCandidate = OPTD[k-1][0];\n            nonDomainCandidate.backPointer = k;\n            heapOPTNonDomain.push(nonDomainCandidate); \n\n            auto domainCandidate = OPT[k-1][0];\n            domainCandidate.score += q(k,l);\n            domainCandidate.backPointer = k;\n            heapOPTDomain.push(domainCandidate);\n        }\n\n        auto pushSubProblem = [&](heapT & heap, SubProblem & subProb, bool isDomain) {\n            heap.pop();\n            auto nextOptimalIndex = subProb.backOptimalIndex + 1;\n            auto k = subProb.backPointer;\n\n            if (nextOptimalIndex < params->K) {\n                SubProblem newCandidate;\n                if (isDomain) {\n                    newCandidate = OPT[k-1][nextOptimalIndex];\n                    newCandidate.score += q(k,l);\n                } else {\n                    newCandidate = OPTD[k-1][nextOptimalIndex];\n                }\n                newCandidate.backPointer = k;\n                newCandidate.backOptimalIndex = nextOptimalIndex;\n                heap.push(newCandidate);\n            }\n        };\n\n        size_t i = 0;\n        size_t j = 0;\n        while (i < params->K) {\n            OPTD[l][i] = heapOPTDomain.top();\n            pushSubProblem(heapOPTDomain, OPTD[l][i], true);\n            auto nonDomainCandidate = heapOPTNonDomain.top();\n             \n            if (nonDomainCandidate.score > OPTD[l][j].score) {\n                OPT[l][i] = nonDomainCandidate;\n                pushSubProblem(heapOPTNonDomain, nonDomainCandidate, false);\n            } else {\n                OPT[l][i] = OPTD[l][j];\n                j++;\n            }\n\n            i++;    \n        }\n    }\n\n    std::cerr << \"In topK()\\n\";\n    for (size_t i = 0; i < params->K; ++i) {\n        std::cerr << \"The \" << i << \"th-best solution had score \" << OPT[params->n][i].score << \"\\n\";\n    }\n}\n\nDomainSet ArmatusDAG::extractDomains(size_t i) {\n    size_t k,l;\n    DomainSet dset;\n\n    l = params->n;\n    do {\n        k = OPT[l][i].backPointer;\n        if (q(k,l) > 0) {\n            dset.push_back(Domain(k-1,l-1)); \n        }\n        l = k-1;\n    } while(l > 1);\n\n    return dset;\n}\n\nWeightedDomainEnsemble ArmatusDAG::extractTopK() {\n    WeightedDomainEnsemble ensemble;\n\n    for (size_t i = 0; i < params->K; i++) { \n        ensemble.domainSets.push_back( extractDomains(i) );\n        ensemble.weights.push_back( OPT[params->n][i].score/OPT[params->n][0].score );\n    }\n\n    return ensemble;\n}\n", "meta": {"hexsha": "9ee71dac76c8b7170452e420f91b6a3589e353ac", "size": 6018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ArmatusDAG.cpp", "max_stars_repo_name": "cosmoskaluga/armatus", "max_stars_repo_head_hexsha": "baa7234096cad439cf7035a40c9a392015a395ac", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2015-05-21T18:19:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T14:15:04.000Z", "max_issues_repo_path": "src/ArmatusDAG.cpp", "max_issues_repo_name": "Khrameeva-Lab/ArmatusParallel", "max_issues_repo_head_hexsha": "9e3f36230e8443da980920a633b5501964d388e3", "max_issues_repo_licenses": ["BSD-2-Clause", "MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2015-01-22T23:24:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-13T13:59:58.000Z", "max_forks_repo_path": "src/ArmatusDAG.cpp", "max_forks_repo_name": "Khrameeva-Lab/ArmatusParallel", "max_forks_repo_head_hexsha": "9e3f36230e8443da980920a633b5501964d388e3", "max_forks_repo_licenses": ["BSD-2-Clause", "MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T18:34:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-05T01:46:04.000Z", "avg_line_length": 29.9402985075, "max_line_length": 101, "alphanum_fraction": 0.5103024261, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5377725664064599}}
{"text": "#ifndef MULTI_LAYER_PERCEPTRON_CLASSIFIER_HPP\n#define MULTI_LAYER_PERCEPTRON_CLASSIFIER_HPP\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\nnamespace mlt {\nnamespace models {\nnamespace classifiers {\n    \n    // Implementation of a Multi Layer Perceptron Classifier\n    // Categorization: \n    // - Application: Classifier\n    // - Parametrization: Parametrized\n    // - Method of Training: Gradient-Based\n    // - Supervision: Supervised\n\t// Parameters:\n\t// - size_t[] hidden_layers_neurons: array with number of neurons per layer.\n\t// - double regularization: amount of L2 regularization to apply. Set to 0 or less if don't want to use.\n\ttemplate <typename Params>\n    class MultiLayerPerceptronClassifier {\n    public:         \n\t\tMultiLayerPerceptronClassifier() : _init(false) {}\n\n\t\tMultiLayerPerceptronClassifier(size_t input, size_t classes) : _init(true) {\n\t\t\tsize_t previous_layer = input;\n\n\t\t\tfor (unsigned int i = 0; i < params_t::hidden_layers_neurons_size(); i++) {\n\t\t\t\tassert(params_t::hidden_layers_neurons(i) > 0);\n\t\t\t\tthis->_theta.push_back(Eigen::MatrixXd::Random(params_t::hidden_layers_neurons(i), previous_layer + 1) * params_t::epsilon_init());\n\n\t\t\t\tprevious_layer = params_t::hidden_layers_neurons(i);\n\t\t\t}\n\n\t\t\tthis->_theta.push_back(Eigen::MatrixXd::Random(output, previous_layer + 1) * params_t::epsilon_init());\n\t\t}\n\n        // Disable copy constructors\n\t\tMultiLayerPerceptronClassifier(const MultiLayerPerceptronClassifier& other) = delete;\n\t\tMultiLayerPerceptronClassifier& operator=(const MultiLayerPerceptronClassifier& other) = delete;\n\n        inline size_t input() const {\n            assert(_init);\n            return this->_theta[0].rows() - 1;\n        }\n\n        inline size_t output() const {\n            assert(_init);\n            return this->_theta.back().cols();\n        }\n\n        inline bool add_intercept() const {\n            return true;\n        }\n\n        inline bool is_initialized() const {\n            return _init;\n        }\n\n        inline void init(size_t input, size_t classes) {\n\t\t\tsize_t previous_layer = input;\n\n\t\t\tthis->_theta.clear();\n\n\t\t\tfor (unsigned int i = 0; i < params_t::hidden_layers_neurons_size(); i++) {\n\t\t\t\tassert(params_t::hidden_layers_neurons(i) > 0);\n\t\t\t\tthis->_theta.push_back(Eigen::MatrixXd::Random(params_t::hidden_layers_neurons(i), previous_layer + 1) * params_t::epsilon_init());\n\n\t\t\t\tprevious_layer = params_t::hidden_layers_neurons(i);\n\t\t\t}\n\n\t\t\tthis->_theta.push_back(Eigen::MatrixXd::Random(output, previous_layer + 1) * params_t::epsilon_init());\n\n            _init = true;\n        }\n\n        inline void reset() {\n            assert(_init);\n\t\t\tfor (auto w : this->_theta) {\n\t\t\t\tw.setRandom() * params_t::epsilon_init();\n\t\t\t}\n        }\n\n        inline Eigen::VectorXd score_single(const Eigen::VectorXd& input) const {\n\t\t\tassert(_init);\n\t\t\treturn this->_feed_forward(this->_theta(), input.transpose()).transpose();\n\t\t}\n\n        inline Eigen::MatrixXd score_multi(const Eigen::MatrixXd& input) const {\n\t\t\tassert(_init);\n\t\t\treturn this->_feed_forward(this->_theta(), input);\n        }\n\n        inline size_t params_size() const {\n            assert(_init);\n\t\t\tsize_t counter = 0;\n\t\t\tfor (size_t i = 0; i < this->_theta.size(); i++) {\n\t\t\t\tcounter += this->_theta[i].size();\n\t\t\t}\n\n\t\t\treturn counter;\n        }\n\n        inline Eigen::VectorXd params() const {\n            assert(_init);\n\n\t\t\tsize_t counter = 0;\n\t\t\tfor (size_t i = 0; i < this->_theta.size(); i++) {\n\t\t\t\tcounter += this->_theta[i].size();\n\t\t\t}\n\n\t\t\tEigen::VectorXd theta_plain(counter);\n\t\t\tcounter = 0;\n\t\t\tfor (size_t i = 0; i < this->_theta.size(); i++) {\n\t\t\t\ttheta_plain.block(counter, 0, this->_theta[i].size(), 1) = VectorXd::Map(this->_theta[i].data(), this->_theta[i].size());\n\t\t\t\tcounter += this->_theta[i].size();\n\t\t\t}\n\n\t\t\treturn theta_plain;\n\t\t}\n\n        inline void set_params(const Eigen::VectorXd& beta) {\n            assert(_init);\n\n\t\t\tsize_t counter = 0;\n\t\t\tfor (size_t i = 0; i < this->_theta.size(); i++) {\n\t\t\t\tthis->_theta[i] = Eigen::MatrixXd::Map(parameters.data() + counter, this->_theta[i].rows(), this->_theta[i].cols());\n\t\t\t\tcounter += this->_theta[i].size();\n\t\t\t}\n\t\t\tassert(parameters.size() == counter);\n        }\n\n        inline double cost(const Eigen::MatrixXd& input, const Eigen::MatrixXd& result) const {\n            assert(_init);\n            return _cost_internal(this->_theta(), input, result);\n        }\n\n        inline double cost(const Eigen::VectorXd& thetas, const Eigen::MatrixXd& input, const Eigen::MatrixXd& result) const {\n\t\t\tassert(_init);\n\t\t\tstd::vector<MatrixXd> theta(this->_theta.size());\n\n\t\t\tsize_t counter = 0;\n\t\t\tfor (size_t i = 0; i < this->_theta.size(); i++) {\n\t\t\t\ttheta[i] = Eigen::MatrixXd::Map(parameters.data() + counter, this->_theta[i].rows(), this->_theta[i].cols());\n\t\t\t\tcounter += this->_theta[i].size();\n\t\t\t}\n\n            return _cost_internal(theta, input, result);\n        }\n        \n        inline std::tuple<double, Eigen::VectorXd> cost_and_gradient(const Eigen::MatrixXd& input, const Eigen::MatrixXd& result) const {\n            assert(_init);\n            auto c_a_g = _cost_and_gradient_internal(this->_theta, input, result);\n\t\t\tauto d_theta = std::get<1>(c_a_g);\n\n\t\t\tEigen::VectorXd d_theta_plain(counter);\n\t\t\tcounter = 0;\n\t\t\tfor (size_t i = 0; i < d_theta.size(); i++) {\n\t\t\t\td_theta_plain.block(counter, 0, d_theta[i].size(), 1) = VectorXd::Map(d_theta[i].data(), d_theta[i].size());\n\t\t\t\tcounter += d_theta[i].size();\n\t\t\t}\n\n\t\t\treturn std::make_tuple(std::get<0>(c_a_g), d_theta_plain);\n        }\n\n\t\tinline std::tuple<double, Eigen::VectorXd> cost_and_gradient(const Eigen::VectorXd& thetas, const Eigen::MatrixXd& input, const Eigen::MatrixXd& result) const {\n            assert(_init);\n\t\t\tstd::vector<MatrixXd> theta(this->_theta.size());\n\n\t\t\tsize_t counter = 0;\n\t\t\tfor (size_t i = 0; i < this->_theta.size(); i++) {\n\t\t\t\ttheta[i] = Eigen::MatrixXd::Map(parameters.data() + counter, this->_theta[i].rows(), this->_theta[i].cols());\n\t\t\t\tcounter += this->_theta[i].size();\n\t\t\t}\n\n            auto c_a_g = _cost_and_gradient_internal(theta, input, result);\n\t\t\tauto d_theta = std::get<1>(c_a_g);\n\n\t\t\tEigen::VectorXd d_theta_plain(counter);\n\t\t\tcounter = 0;\n\t\t\tfor (size_t i = 0; i < d_theta.size(); i++) {\n\t\t\t\td_theta_plain.block(counter, 0, d_theta[i].size(), 1) = VectorXd::Map(d_theta[i].data(), d_theta[i].size());\n\t\t\t\tcounter += d_theta[i].size();\n\t\t\t}\n\n\t\t\treturn std::make_tuple(std::get<0>(c_a_g), d_theta_plain);\n        }\n\n    protected:\n\t\ttypedef Params::MultiLayerPerceptronClassifier params_t;\n\n\t\tinline MatrixXd _feed_forward(const std::vector<MatrixXd>& theta, const MatrixXd& input) const {\t\t\t\n\t\t\tMatrixXd previous = input.transpose();\n\n\t\t\tfor (unsigned int i = 0; i < theta.size() - 1; i++) {\n\t\t\t\tMatrixXd temp = MatrixXd::Ones(theta[i].rows() + 1, input.rows());\n\t\t\t\ttemp.bottomRows(theta[i].rows()) = (theta[i] * previous).unaryExpr(std::ptr_fun(sigmoid));\n\t\t\t\tprevious = temp;\n\t\t\t}\n\n\t\t\treturn (theta.back() * previous).unaryExpr(std::ptr_fun(sigmoid));\n\t\t}\n\n\t\tinline double _cost_internal(const std::vector<Eigen::MatrixXd>& theta, const Eigen::MatrixXd& input, const Eigen::MatrixXd& result) const {\n\t\t\tEigen::MatrixXd output = this->_feed_forward(theta, x);\n\n\t\t\tEigen::MatrixXd ones = MatrixXd::Ones(theta.back().rows(), x.rows());\n\t\t\tdouble loss = ((-y).array() * output.array().log() - (ones - y).array() * (ones - output).array().log()).sum() / x.rows();\n\t\t\tdouble reg = 0;\n\n\t\t\tfor (unsigned int i = 0; i < theta.size(); i++) {\n\t\t\t\treg += theta[i].rightCols(theta[i].cols() - 1).array().pow(2).sum();\n\t\t\t}\n\n\t\t\treg *= (params_t::regularization() / (double)(2 * x.rows()));\n\n\t\t\tloss += reg;\n\n\t\t\treturn loss;\n\t\t}\n\n\t\tinline std::tuple<double, std::vector<Eigen::MatrixXd>> _cost_and_gradient_internal(const std::vector<Eigen::MatrixXd>& theta, const Eigen::MatrixXd& input, const Eigen::MatrixXd& result) const {\n\t\t\tstd::vector<MatrixXd> z, a;\n\t\t\ta.push_back(input.transpose());\n\n\t\t\tfor (unsigned int i = 0; i < theta.size() - 1; i++) {\n\t\t\t\tEigen::MatrixXd temp = Eigen::MatrixXd::Ones(theta[i].rows() + 1, input.rows());\n\t\t\t\tz.push_back(theta[i] * a.back());\n\t\t\t\ttemp.bottomRows(theta[i].rows()) = (z.back()).unaryExpr(std::ptr_fun(sigmoid));\n\t\t\t\ta.push_back(temp);\n\t\t\t}\n\n\t\t\ta.push_back((theta.back() * a.back()).unaryExpr(std::ptr_fun(sigmoid)));\n\n\t\t\tEigen::MatrixXd ones = MatrixXd::Ones(theta.back().rows(), x.rows());\n\t\t\tdouble loss = ((-y).array() * a.back().array().log() - (ones - y).array() * (ones - a.back()).array().log()).sum() / x.rows();\n\t\t\tdouble reg = 0;\n\n\t\t\tfor (unsigned int i = 0; i < theta.size(); i++) {\n\t\t\t\treg += theta[i].rightCols(theta[i].cols() - 1).array().pow(2).sum();\n\t\t\t}\n\n\t\t\treg *= (params_t::regularization() / (double)(2 * x.rows()));\n\t\t\tloss += reg;\n\n\t\t\tstd::vector<Eigen::MatrixXd> d_theta;\n\n\t\t\tEigen::MatrixXd previous_delta = a.back() - y;\n\t\t\td_theta.push_back(previous_delta * a[a.size() - 2].transpose() / (double)y.cols());\n\t\t\td_theta.back().rightCols(d_theta.back().cols() - 1) += (params_t::regularization() / (double)(x.rows())) * theta.back().rightCols(theta.back().cols() - 1);\n\n\t\t\tfor (size_t i = theta.size() - 1; i > 0; i--) {\n\t\t\t\tEigen::MatrixXd temp = (theta[i].rightCols(theta[i].cols() - 1).transpose() * previous_delta).array() *\n\t\t\t\t\tz[i - 1].unaryExpr(std::ptr_fun(sigmoidGradient)).array();\n\t\t\t\td_theta.push_back(temp * a[i - 1].transpose() / (double)y.cols());\n\t\t\t\td_theta.back().rightCols(d_theta.back().cols() - 1) += (params_t::regularization() / (double)(x.rows())) * theta[i].rightCols(theta[i].cols() - 1);\n\t\t\t\tprevious_delta = temp;\n\t\t\t}\n\t\t\t\n\t\t\tstd::reverse(d_theta.begin(), d_theta.end());\n\n\t\t\treturn std::make_tuple(loss, d_theta);\n        }\n\n        bool _init;\n\t\tstd::vector<Eigen::MatrixXd> _theta;\n    };\n}\n}\n}\n#endif", "meta": {"hexsha": "59e6465af5a9b2d961c641abac151b2d70402704", "size": 9718, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/models/classifiers/multi_layer_perceptron_classifier.hpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/mlt/models/classifiers/multi_layer_perceptron_classifier.hpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlt/models/classifiers/multi_layer_perceptron_classifier.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": 35.8597785978, "max_line_length": 197, "alphanum_fraction": 0.6302737189, "num_tokens": 2606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5377725662459573}}
{"text": "// This file is part of KWIVER, and is distributed under the\n// OSI-approved BSD 3-Clause License. See top-level LICENSE file or\n// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.\n\n/**\n * \\file\n * \\brief core essential matrix template implementations\n */\n\n#include \"essential_matrix.h\"\n\n#include <cmath>\n\n#include <vital/exceptions/math.h>\n\n#include <Eigen/SVD>\n\nnamespace kwiver {\nnamespace vital {\n\n/// Compute the twisted pair rotation from the rotation and translation\nrotation_d\nessential_matrix\n::twisted_rotation() const\n{\n  // The quaternion representation of a 180 degree rotation about\n  // unit vector [X,Y,Z] is simply [X, Y, Z, 0]\n  vector_3d t = this->translation();\n  return rotation_d(vector_4d(t.x(), t.y(), t.z(), 0.0)) * this->rotation();\n}\n\n/// Construct from a provided matrix\ntemplate <typename T>\nessential_matrix_<T>\n::essential_matrix_( Eigen::Matrix<T,3,3> const &mat )\n{\n  const matrix_t W = (matrix_t() << T(0), T(-1), T(0),\n                                    T(1), T( 0), T(0),\n                                    T(0), T( 0), T(1)).finished();\n  Eigen::JacobiSVD<matrix_t> svd(mat, Eigen::ComputeFullU |\n                                      Eigen::ComputeFullV);\n  const matrix_t& U = svd.matrixU();\n  const matrix_t& V = svd.matrixV();\n  trans_ = U.col(2);\n  matrix_t R = U*W*V.transpose();\n  if( R.determinant() < T(0) )\n  {\n    R *= T(-1);\n  }\n  rot_ = rotation_<T>(R);\n}\n\n/// Construct from a rotation and translation\ntemplate <typename T>\nessential_matrix_<T>\n::essential_matrix_( rotation_<T> const &rot,\n                     vector_t const &trans )\n  : rot_( rot ),\n    trans_( trans.normalized() )\n{\n}\n\n/// Conversion Copy constructor -- float specialization\ntemplate <>\ntemplate <>\nessential_matrix_<float>\n::essential_matrix_( essential_matrix_<float> const &other )\n  : rot_( other.rot_ ),\n    trans_( other.trans_ )\n{\n}\n\n/// Conversion Copy constructor -- double specialization\ntemplate <>\ntemplate <>\nessential_matrix_<double>\n::essential_matrix_( essential_matrix_<double> const &other )\n  : rot_( other.rot_ ),\n    trans_( other.trans_ )\n{\n}\n\n/// Construct from a generic essential_matrix\ntemplate <typename T>\nessential_matrix_<T>\n::essential_matrix_( essential_matrix const &base )\n  : rot_( static_cast<rotation_<T> >(base.rotation()) ),\n    trans_( base.translation().template cast<T>() )\n{\n}\n\n/// Construct from a generic essential_matrix -- double specialization\ntemplate <>\nessential_matrix_<double>\n::essential_matrix_( essential_matrix const &base )\n  : rot_( base.rotation() ),\n    trans_( base.translation() )\n{\n}\n\n/// Create a clone of outself as a shared pointer\ntemplate <typename T>\nessential_matrix_sptr\nessential_matrix_<T>\n::clone() const\n{\n  return essential_matrix_sptr( new essential_matrix_<T>( *this ) );\n}\n\n/// Get a double-typed copy of the underlying matrix\ntemplate <typename T>\nEigen::Matrix<double,3,3>\nessential_matrix_<T>\n::matrix() const\n{\n  return this->compute_matrix().template cast<double>();\n}\n\n/// Specialization for matrices with native double type\ntemplate <>\nEigen::Matrix<double,3,3>\nessential_matrix_<double>\n::matrix() const\n{\n  return this->compute_matrix();\n}\n\n/// Return the one of two possible 3D rotations that can parameterize E\ntemplate <typename T>\nrotation_d\nessential_matrix_<T>\n::rotation() const\n{\n  return static_cast<rotation_d>(this->rot_);\n}\n\n/// Return the second possible rotation that can parameterize E\ntemplate <typename T>\nrotation_d\nessential_matrix_<T>\n::twisted_rotation() const\n{\n  return static_cast<rotation_d>(this->compute_twisted_rotation());\n}\n\n/// Return a unit translation vector (up to a sign) that parameterizes E\ntemplate <typename T>\nvector_3d\nessential_matrix_<T>\n::translation() const\n{\n  return this->trans_.template cast<double>();\n}\n\n/// Get the underlying matrix\ntemplate <typename T>\ntypename essential_matrix_<T>::matrix_t\nessential_matrix_<T>\n::compute_matrix() const\n{\n  matrix_t t_cross;\n  t_cross << T(0), -trans_[2], trans_[1],\n             trans_[2], T(0), -trans_[0],\n            -trans_[1], trans_[0], T(0);\n  return t_cross * matrix_t(rot_.matrix());\n}\n\n/// Compute the twisted pair rotation from the rotation and translation\ntemplate <typename T>\nrotation_<T>\nessential_matrix_<T>\n::compute_twisted_rotation() const\n{\n  typedef Eigen::Matrix<T,4,1> vector_4;\n  // The quaternion representation of a 180 degree rotation about\n  // unit vector [X,Y,Z] is simply [X, Y, Z, 0]\n  const vector_t& t = trans_;\n  return rotation_<T>(vector_4(t.x(), t.y(), t.z(), T(0))) * rot_;\n}\n\n/// Get a const reference to the underlying rotation\ntemplate <typename T>\nrotation_<T> const&\nessential_matrix_<T>\n::get_rotation() const\n{\n  return rot_;\n}\n\n/// Get a const reference to the underlying translation\ntemplate <typename T>\ntypename essential_matrix_<T>::vector_t const&\nessential_matrix_<T>\n::get_translation() const\n{\n  return trans_;\n}\n\n// ===========================================================================\n// Other Functions\n// ---------------------------------------------------------------------------\n\n/// essential_matrix_<T> output stream operator\ntemplate <typename T>\nstd::ostream&\noperator<<( std::ostream &s, essential_matrix_<T> const &e )\n{\n  s << e.compute_matrix();\n  return s;\n}\n\n/// Output stream operator for \\p essential_matrix instances\nstd::ostream&\noperator<<( std::ostream &s, essential_matrix const &e )\n{\n  s << e.matrix();\n  return s;\n}\n\n// ===========================================================================\n// Template class instantiation\n// ---------------------------------------------------------------------------\n/// \\cond DoxygenSuppress\n#define INSTANTIATE_ESSENTIAL_MATRIX(T)                                 \\\n  template class essential_matrix_<T>;                                  \\\n  template VITAL_EXPORT std::ostream& operator<<( std::ostream &,       \\\n                        essential_matrix_<T> const & )\n\nINSTANTIATE_ESSENTIAL_MATRIX(float);\nINSTANTIATE_ESSENTIAL_MATRIX(double);\n#undef INSTANTIATE_ESSENTIAL_MATRIX\n/// \\endcond\n\n} } // end vital namespace\n", "meta": {"hexsha": "dc2c474153843fb6561fee8eb1be5553882386ba", "size": 6073, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vital/types/essential_matrix.cxx", "max_stars_repo_name": "mwoehlke-kitware/kwiver", "max_stars_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 176.0, "max_stars_repo_stars_event_min_datetime": "2015-07-31T23:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T23:42:44.000Z", "max_issues_repo_path": "vital/types/essential_matrix.cxx", "max_issues_repo_name": "mwoehlke-kitware/kwiver", "max_issues_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1276.0, "max_issues_repo_issues_event_min_datetime": "2015-05-03T01:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:32:20.000Z", "max_forks_repo_path": "vital/types/essential_matrix.cxx", "max_forks_repo_name": "mwoehlke-kitware/kwiver", "max_forks_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2015-01-25T05:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T14:59:37.000Z", "avg_line_length": 25.8425531915, "max_line_length": 78, "alphanum_fraction": 0.6517371974, "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5376964675880817}}
{"text": "#include <gtest/gtest.h>\n\n#include \"scheme/numeric/rand_xform.hh\"\n\n#include <Eigen/Geometry>\n\n#include <random>\n#include \"scheme/util/Timer.hh\"\n\nnamespace scheme { namespace numeric { namespace pref_test {\n\nusing std::cout;\nusing std::endl;\n\ntypedef Eigen::Transform<double,3,Eigen::AffineCompact> Xform;\n// typedef Eigen::Affine3d Xform;\n\n\n// TEST( XformMap, basic_test ){\ntemplate< class Xform >\nvoid test_xform_perf(){\n\tint NSAMP = 100*1000;\n\t#ifdef SCHEME_BENCHMARK\n\tNSAMP = 10*1000*1000;\n\t#endif\n\tstd::mt19937 rng;\n\tXform x,sum = Xform::Identity();\n\trand_xform(rng,x);\n\n\tutil::Timer<> t;\n\tfor(int i = 0; i < NSAMP; ++i){\n\t\tsum = sum * x;\n\t}\n\tdouble time = t.elapsed_nano();\n\tprintf( \"runtime %7.3fns nonsense: %7.3f \\n\", time/NSAMP, sum.translation()[0] );\n\n}\n\nTEST( xform_perf, preformance ){\n\tcout << \"AffineCompact d \"; test_xform_perf< Eigen::Transform<double,3,Eigen::AffineCompact> >();\n\tcout << \"Affine        d \"; test_xform_perf< Eigen::Affine3d  >();\n\tcout << \"AffineCompact f \"; test_xform_perf< Eigen::Transform<float ,3,Eigen::AffineCompact> >();\n\tcout << \"Affine        f \"; test_xform_perf< Eigen::Affine3f  >();\n\t// cout << \"XformHash_bt24_Cubic_Zorder\"; test_xform_perf< XformHash_bt24_Cubic_Zorder >();\n}\n\n}}}\n", "meta": {"hexsha": "529f4fb8b0b5583c142f993d927017056da8c9a1", "size": 1233, "ext": "cc", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/numeric/xform_perf.gtest.cc", "max_stars_repo_name": "YaoYinYing/rifdock", "max_stars_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T01:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:16:08.000Z", "max_issues_repo_path": "schemelib/scheme/numeric/xform_perf.gtest.cc", "max_issues_repo_name": "YaoYinYing/rifdock", "max_issues_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-30T17:45:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:02:44.000Z", "max_forks_repo_path": "schemelib/scheme/numeric/xform_perf.gtest.cc", "max_forks_repo_name": "YaoYinYing/rifdock", "max_forks_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T01:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:56:17.000Z", "avg_line_length": 25.6875, "max_line_length": 98, "alphanum_fraction": 0.6877534469, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5376964614367882}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2018 - 2021 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 *      Author: Zhuoran Wang, Colorado State University, 2018 \n */ \n\n\n// @sect3{Include files}  \u8fd9\u4e2a\u7a0b\u5e8f\u662f\u57fa\u4e8e step-7  \u3001 step-20  \u548c  step-51  \uff0c\u6240\u4ee5\u4e0b\u9762\u7684\u5934\u6587\u4ef6\u5927\u90e8\u5206\u662f\u719f\u6089\u7684\u3002\u6211\u4eec\u9700\u8981\u4ee5\u4e0b\u6587\u4ef6\uff0c\u5176\u4e2d\u53ea\u6709\u5bfc\u5165FE_DGRaviartThomas\u7c7b\u7684\u6587\u4ef6\uff08\u5373`deal.II/fe/fe_dg_vector.h`\uff09\u662f\u771f\u6b63\u7684\u65b0\u6587\u4ef6\uff1bFE_DGRaviartThomas\u5b9e\u73b0\u4e86\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684 \"\u7834\u788e \"Raviart-Thomas\u7a7a\u95f4\u3002\n\n#include <deal.II/base/quadrature.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/tensor_function.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/point.h> \n#include <deal.II/lac/block_vector.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/block_sparse_matrix.h> \n#include <deal.II/lac/sparse_matrix.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/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n#include <deal.II/fe/fe_dgq.h> \n#include <deal.II/fe/fe_raviart_thomas.h> \n#include <deal.II/fe/fe_dg_vector.h> \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/fe/fe_face.h> \n#include <deal.II/fe/component_mask.h> \n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/data_out_faces.h> \n\n#include <fstream> \n#include <iostream> \n\n// \u6211\u4eec\u7684\u7b2c\u4e00\u6b65\uff0c\u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u662f\u628a\u6240\u6709\u4e0e\u672c\u6559\u7a0b\u7a0b\u5e8f\u6709\u5173\u7684\u4e1c\u897f\u653e\u5230\u81ea\u5df1\u7684\u547d\u540d\u7a7a\u95f4\u4e2d\u3002\n\nnamespace Step61 \n{ \n  using namespace dealii; \n// @sect3{The WGDarcyEquation class template}  \n\n// \u8fd9\u662f\u672c\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u3002\u6211\u4eec\u5c06\u4f7f\u7528\u5f31\u52a0\u52d2\u91d1\uff08WG\uff09\u65b9\u6cd5\u6c42\u89e3\u5185\u90e8\u548c\u9762\u4e0a\u7684\u6570\u503c\u538b\u529b\uff0c\u5e76\u8ba1\u7b97\u51fa\u538b\u529b\u7684 $L_2$ \u8bef\u5dee\u3002\u5728\u540e\u5904\u7406\u6b65\u9aa4\u4e2d\uff0c\u6211\u4eec\u8fd8\u5c06\u8ba1\u7b97\u901f\u5ea6\u548c\u901a\u91cf\u7684 $L_2$  \u8bef\u5dee\u3002\n\n// \u8be5\u7c7b\u7684\u7ed3\u6784\u4e0e\u4ee5\u524d\u7684\u6559\u7a0b\u7a0b\u5e8f\u6ca1\u6709\u6839\u672c\u7684\u4e0d\u540c\uff0c\u6240\u4ee5\u9664\u4e86\u4e00\u4e2a\u4f8b\u5916\uff0c\u6ca1\u6709\u5fc5\u8981\u5bf9\u7ec6\u8282\u8fdb\u884c\u8bc4\u8bba\u3002\u8be5\u7c7b\u6709\u4e00\u4e2a\u6210\u5458\u53d8\u91cf`fe_dgrt`\uff0c\u5bf9\u5e94\u4e8e\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684 \"\u7834\u788e \"\u7684Raviart-Thomas\u7a7a\u95f4\u3002\u8fd8\u6709\u4e00\u4e2a\u4e0e\u4e4b\u5339\u914d\u7684`dof_handler_dgrt`\uff0c\u8868\u793a\u4ece\u8fd9\u4e2a\u5143\u7d20\u521b\u5efa\u7684\u6709\u9650\u5143\u573a\u7684\u5168\u5c40\u679a\u4e3e\uff0c\u8fd8\u6709\u4e00\u4e2a\u5411\u91cf`darcy_velocity`\uff0c\u7528\u4e8e\u4fdd\u6301\u8fd9\u4e2a\u573a\u7684\u8282\u70b9\u503c\u3002\u5728\u6c42\u89e3\u538b\u529b\u540e\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u8fd9\u4e09\u4e2a\u53d8\u91cf\u6765\u8ba1\u7b97\u4e00\u4e2a\u540e\u5904\u7406\u7684\u901f\u5ea6\u573a\uff0c\u7136\u540e\u6211\u4eec\u53ef\u4ee5\u5bf9\u5176\u8fdb\u884c\u8bef\u5dee\u8bc4\u4f30\uff0c\u5e76\u5c06\u5176\u8f93\u51fa\u7528\u4e8e\u53ef\u89c6\u5316\u3002\n\n  template <int dim> \n  class WGDarcyEquation \n  { \n  public: \n    WGDarcyEquation(const unsigned int degree); \n    void run(); \n\n  private: \n    void make_grid(); \n    void setup_system(); \n    void assemble_system(); \n    void solve(); \n    void compute_postprocessed_velocity(); \n    void compute_velocity_errors(); \n    void compute_pressure_error(); \n    void output_results() const; \n\n    Triangulation<dim> triangulation; \n\n    FESystem<dim>   fe; \n    DoFHandler<dim> dof_handler; \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    FE_DGRaviartThomas<dim> fe_dgrt; \n    DoFHandler<dim>         dof_handler_dgrt; \n    Vector<double>          darcy_velocity; \n  }; \n\n//  @sect3{Right hand side, boundary values, and exact solution}  \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5b9a\u4e49\u7cfb\u6570\u77e9\u9635 $\\mathbf{K}$ \uff08\u8fd9\u91cc\u662f\u8eab\u4efd\u77e9\u9635\uff09\uff0c\u8fea\u91cc\u5e0c\u7279\u8fb9\u754c\u6761\u4ef6\uff0c\u53f3\u624b\u8fb9 $f = 2\\pi^2 \\sin(\\pi x) \\sin(\\pi y)$  \uff0c\u4ee5\u53ca\u4e0e\u8fd9\u4e9b\u9009\u62e9\u76f8\u5bf9\u5e94\u7684 $K$ \u548c $f$ \u7684\u7cbe\u786e\u89e3\uff0c\u5373 $p = \\sin(\\pi x) \\sin(\\pi y)$  \u3002\n\n  template <int dim> \n  class Coefficient : public TensorFunction<2, dim> \n  { \n  public: \n    Coefficient() \n      : TensorFunction<2, dim>() \n    {} \n\n    virtual void value_list(const std::vector<Point<dim>> &points, \n                            std::vector<Tensor<2, dim>> &values) const override; \n  }; \n\n  template <int dim> \n  void Coefficient<dim>::value_list(const std::vector<Point<dim>> &points, \n                                    std::vector<Tensor<2, dim>> &  values) const \n  { \n    Assert(points.size() == values.size(), \n           ExcDimensionMismatch(points.size(), values.size())); \n    for (unsigned int p = 0; p < points.size(); ++p) \n      values[p] = unit_symmetric_tensor<dim>(); \n  } \n\n  template <int dim> \n  class BoundaryValues : public Function<dim> \n  { \n  public: \n    BoundaryValues() \n      : Function<dim>(2) \n    {} \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n  }; \n\n  template <int dim> \n  double BoundaryValues<dim>::value(const Point<dim> & /*p*/, \n                                    const unsigned int /*component*/) const \n  { \n    return 0; \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  template <int dim> \n  double RightHandSide<dim>::value(const Point<dim> &p, \n                                   const unsigned int /*component*/) const \n  { \n    return (2 * numbers::PI * numbers::PI * std::sin(numbers::PI * p[0]) * \n            std::sin(numbers::PI * p[1])); \n  } \n\n// \u5b9e\u73b0\u7cbe\u786e\u538b\u529b\u89e3\u51b3\u65b9\u6848\u7684\u7c7b\u6709\u4e00\u4e2a\u5947\u602a\u7684\u5730\u65b9\uff0c\u6211\u4eec\u628a\u5b83\u4f5c\u4e3a\u4e00\u4e2a\u6709\u4e24\u4e2a\u5206\u91cf\u7684\u5411\u91cf\u503c\u6765\u5b9e\u73b0\u3002(\u6211\u4eec\u5728\u6784\u9020\u51fd\u6570\u4e2d\u8bf4\u5b83\u6709\u4e24\u4e2a\u5206\u91cf\uff0c\u5728\u8fd9\u91cc\u6211\u4eec\u8c03\u7528\u57fa\u51fd\u6570\u7c7b\u7684\u6784\u9020\u51fd\u6570)\u3002\u5728`value()`\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u4e0d\u6d4b\u8bd5`component`\u53c2\u6570\u7684\u503c\uff0c\u8fd9\u610f\u5473\u7740\u6211\u4eec\u4e3a\u5411\u91cf\u503c\u51fd\u6570\u7684\u4e24\u4e2a\u5206\u91cf\u8fd4\u56de\u76f8\u540c\u7684\u503c\u3002\u6211\u4eec\u8fd9\u6837\u505a\u662f\u56e0\u4e3a\u6211\u4eec\u5c06\u672c\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u7684\u6709\u9650\u5143\u63cf\u8ff0\u4e3a\u4e00\u4e2a\u5305\u542b\u5185\u90e8\u548c\u754c\u9762\u538b\u529b\u7684\u77e2\u91cf\u503c\u7cfb\u7edf\uff0c\u5f53\u6211\u4eec\u8ba1\u7b97\u8bef\u5dee\u65f6\uff0c\u6211\u4eec\u5e0c\u671b\u4f7f\u7528\u76f8\u540c\u7684\u538b\u529b\u89e3\u6765\u6d4b\u8bd5\u8fd9\u4e24\u4e2a\u5206\u91cf\u3002\n\n  template <int dim> \n  class ExactPressure : public Function<dim> \n  { \n  public: \n    ExactPressure() \n      : Function<dim>(2) \n    {} \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component) const override; \n  }; \n\n  template <int dim> \n  double ExactPressure<dim>::value(const Point<dim> &p, \n                                   const unsigned int /*component*/) const \n  { \n    return std::sin(numbers::PI * p[0]) * std::sin(numbers::PI * p[1]); \n  } \n\n  template <int dim> \n  class ExactVelocity : public TensorFunction<1, dim> \n  { \n  public: \n    ExactVelocity() \n      : TensorFunction<1, dim>() \n    {} \n\n    virtual Tensor<1, dim> value(const Point<dim> &p) const override; \n  }; \n\n  template <int dim> \n  Tensor<1, dim> ExactVelocity<dim>::value(const Point<dim> &p) const \n  { \n    Tensor<1, dim> return_value; \n    return_value[0] = -numbers::PI * std::cos(numbers::PI * p[0]) * \n                      std::sin(numbers::PI * p[1]); \n    return_value[1] = -numbers::PI * std::sin(numbers::PI * p[0]) * \n                      std::cos(numbers::PI * p[1]); \n    return return_value; \n  } \n\n//  @sect3{WGDarcyEquation class implementation}  \n// @sect4{WGDarcyEquation::WGDarcyEquation}  \n\n// \u5728\u8fd9\u4e2a\u6784\u9020\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u521b\u5efa\u4e86\u4e00\u4e2a\u77e2\u91cf\u503c\u51fd\u6570\u7684\u6709\u9650\u5143\u7a7a\u95f4\uff0c\u8fd9\u91cc\u5c06\u5305\u62ec\u7528\u4e8e\u5185\u90e8\u548c\u754c\u9762\u538b\u529b\u7684\u51fd\u6570\uff0c $p^\\circ$  \u548c  $p^\\partial$  \u3002\n\n  template <int dim> \n  WGDarcyEquation<dim>::WGDarcyEquation(const unsigned int degree) \n    : fe(FE_DGQ<dim>(degree), 1, FE_FaceQ<dim>(degree), 1) \n    , dof_handler(triangulation) \n    , fe_dgrt(degree) \n    , dof_handler_dgrt(triangulation) \n  {} \n\n//  @sect4{WGDarcyEquation::make_grid}  \n\n// \u6211\u4eec\u5728\u5355\u4f4d\u5e73\u65b9\u57df\u4e0a\u751f\u6210\u4e00\u4e2a\u7f51\u683c\u5e76\u5bf9\u5176\u8fdb\u884c\u7ec6\u5316\u3002\n\n  template <int dim> \n  void WGDarcyEquation<dim>::make_grid() \n  { \n    GridGenerator::hyper_cube(triangulation, 0, 1); \n    triangulation.refine_global(5); \n\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  } \n\n//  @sect4{WGDarcyEquation::setup_system}  \n\n// \u5728\u6211\u4eec\u521b\u5efa\u4e86\u4e0a\u9762\u7684\u7f51\u683c\u540e\uff0c\u6211\u4eec\u5206\u914d\u81ea\u7531\u5ea6\u5e76\u8c03\u6574\u77e9\u9635\u548c\u5411\u91cf\u7684\u5927\u5c0f\u3002\u8fd9\u4e2a\u51fd\u6570\u4e2d\u552f\u4e00\u503c\u5f97\u5173\u6ce8\u7684\u90e8\u5206\u662f\u6211\u4eec\u5982\u4f55\u63d2\u503c\u538b\u529b\u7684\u8fb9\u754c\u503c\u3002\u7531\u4e8e\u538b\u529b\u7531\u5185\u90e8\u548c\u754c\u9762\u5206\u91cf\u7ec4\u6210\uff0c\u6211\u4eec\u9700\u8981\u786e\u4fdd\u6211\u4eec\u53ea\u63d2\u503c\u5230\u77e2\u91cf\u503c\u89e3\u7a7a\u95f4\u4e2d\u4e0e\u754c\u9762\u538b\u529b\u76f8\u5bf9\u5e94\u7684\u5206\u91cf\u4e0a\uff08\u56e0\u4e3a\u8fd9\u4e9b\u5206\u91cf\u662f\u552f\u4e00\u5b9a\u4e49\u5728\u57df\u7684\u8fb9\u754c\u4e0a\u7684\uff09\u3002\u6211\u4eec\u901a\u8fc7\u4e00\u4e2a\u53ea\u9488\u5bf9\u754c\u9762\u538b\u529b\u7684\u5206\u91cf\u5c4f\u853d\u5bf9\u8c61\u6765\u505a\u5230\u8fd9\u4e00\u70b9\u3002\n\n  template <int dim> \n  void WGDarcyEquation<dim>::setup_system() \n  { \n    dof_handler.distribute_dofs(fe); \n    dof_handler_dgrt.distribute_dofs(fe_dgrt); \n\n    std::cout << \"   Number of pressure degrees of freedom: \" \n              << dof_handler.n_dofs() << std::endl; \n\n    solution.reinit(dof_handler.n_dofs()); \n    system_rhs.reinit(dof_handler.n_dofs()); \n\n    { \n      constraints.clear(); \n      const FEValuesExtractors::Scalar interface_pressure(1); \n      const ComponentMask              interface_pressure_mask = \n        fe.component_mask(interface_pressure); \n      VectorTools::interpolate_boundary_values(dof_handler, \n                                               0, \n                                               BoundaryValues<dim>(), \n                                               constraints, \n                                               interface_pressure_mask); \n      constraints.close(); \n    } \n\n// \u5728\u53cc\u7ebf\u6027\u5f62\u5f0f\u4e2d\uff0c\u5728\u4e24\u4e2a\u76f8\u90bb\u5355\u5143\u4e4b\u95f4\u7684\u9762\u4e0a\u6ca1\u6709\u79ef\u5206\u9879\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u76f4\u63a5\u4f7f\u7528 <code>DoFTools::make_sparsity_pattern</code> \u6765\u8ba1\u7b97\u7a00\u758f\u77e9\u9635\u3002\n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints); \n    sparsity_pattern.copy_from(dsp); \n\n    system_matrix.reinit(sparsity_pattern); \n  } \n\n//  @sect4{WGDarcyEquation::assemble_system}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u6bd4\u8f83\u6709\u8da3\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u8be6\u8ff0\u7684\uff0c\u7ebf\u6027\u7cfb\u7edf\u7684\u88c5\u914d\u8981\u6c42\u6211\u4eec\u8bc4\u4f30\u5f62\u72b6\u51fd\u6570\u7684\u5f31\u68af\u5ea6\uff0c\u8fd9\u662fRaviart-Thomas\u7a7a\u95f4\u7684\u4e00\u4e2a\u5143\u7d20\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u9700\u8981\u5b9a\u4e49\u4e00\u4e2aRaviart-Thomas\u6709\u9650\u5143\u5bf9\u8c61\uff0c\u5e76\u6709FEValues\u5bf9\u8c61\u5728\u6b63\u4ea4\u70b9\u8bc4\u4f30\u5b83\u3002\u7136\u540e\u6211\u4eec\u9700\u8981\u8ba1\u7b97\u6bcf\u4e2a\u5355\u5143 $K$ \u4e0a\u7684\u77e9\u9635 $C^K$ \uff0c\u4e3a\u6b64\u6211\u4eec\u9700\u8981\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\u77e9\u9635 $M^K$ \u548c $G^K$ \u3002\n\n// \u6709\u4e00\u70b9\u53ef\u80fd\u4e0d\u662f\u5f88\u660e\u663e\uff0c\u5728\u4e4b\u524d\u6240\u6709\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u603b\u662f\u7528DoFHandler\u7684\u5355\u5143\u683c\u8fed\u4ee3\u5668\u6765\u8c03\u7528 FEValues::reinit() \u3002\u8fd9\u6837\u5c31\u53ef\u4ee5\u8c03\u7528\u8bf8\u5982 FEValuesBase::get_function_values() \u8fd9\u6837\u7684\u51fd\u6570\uff0c\u5728\u5355\u5143\u683c\u7684\u6b63\u4ea4\u70b9\u4e0a\u63d0\u53d6\u6709\u9650\u5143\u51fd\u6570\u7684\u503c\uff08\u7528DoF\u503c\u7684\u77e2\u91cf\u8868\u793a\uff09\u3002\u4e3a\u4e86\u4f7f\u8fd9\u79cd\u64cd\u4f5c\u53d1\u6325\u4f5c\u7528\uff0c\u4eba\u4eec\u9700\u8981\u77e5\u9053\u54ea\u4e9b\u5411\u91cf\u5143\u7d20\u5bf9\u5e94\u4e8e\u7ed9\u5b9a\u5355\u5143\u4e0a\u7684\u81ea\u7531\u5ea6--\u4e5f\u5c31\u662f\u8bf4\uff0c\u6b63\u662fDoFHandler\u7c7b\u6240\u63d0\u4f9b\u7684\u90a3\u79cd\u4fe1\u606f\u548c\u64cd\u4f5c\u3002\n\n// \u6211\u4eec\u53ef\u4ee5\u4e3a \"\u7834\u788e\u7684 \"Raviart-Thomas\u7a7a\u95f4\u521b\u5efa\u4e00\u4e2aDoFHandler\u5bf9\u8c61\uff08\u4f7f\u7528FE_DGRT\u7c7b\uff09\uff0c\u4f46\u662f\u6211\u4eec\u5728\u8fd9\u91cc\u771f\u7684\u4e0d\u60f3\u8fd9\u6837\u505a\u3002\u81f3\u5c11\u5728\u5f53\u524d\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u4efb\u4f55\u4e0e\u8fd9\u4e2a\u7834\u788e\u7a7a\u95f4\u76f8\u5173\u7684\u5168\u5c40\u5b9a\u4e49\u7684\u81ea\u7531\u5ea6\uff0c\u800c\u53ea\u9700\u8981\u5f15\u7528\u5f53\u524d\u5355\u5143\u4e0a\u7684\u8fd9\u79cd\u7a7a\u95f4\u7684\u5f62\u72b6\u51fd\u6570\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5229\u7528\u8fd9\u6837\u4e00\u4e2a\u4e8b\u5b9e\uff0c\u5373\u4eba\u4eec\u4e5f\u53ef\u4ee5\u7528\u5355\u5143\u683c\u8fed\u4ee3\u5668\u6765\u8c03\u7528 FEValues::reinit() \u7684Triangulation\u5bf9\u8c61\uff08\u800c\u4e0d\u662fDoFHandler\u5bf9\u8c61\uff09\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0cFEValues\u5f53\u7136\u53ea\u80fd\u4e3a\u6211\u4eec\u63d0\u4f9b\u53ea\u5f15\u7528\u5355\u5143\u683c\u7684\u4fe1\u606f\uff0c\u800c\u4e0d\u662f\u8fd9\u4e9b\u5355\u5143\u683c\u4e0a\u5217\u4e3e\u7684\u81ea\u7531\u5ea6\u3002\u6240\u4ee5\u6211\u4eec\u4e0d\u80fd\u4f7f\u7528 FEValuesBase::get_function_values(), \uff0c\u4f46\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528 FEValues::shape_value() \u6765\u83b7\u53d6\u5f53\u524d\u5355\u5143\u4e0a\u6b63\u4ea4\u70b9\u7684\u5f62\u72b6\u51fd\u6570\u503c\u3002\u4e0b\u9762\u6211\u4eec\u8981\u5229\u7528\u7684\u5c31\u662f\u8fd9\u79cd\u529f\u80fd\u3002\u4e0b\u9762\u7ed9\u6211\u4eec\u63d0\u4f9bRaviart-Thomas\u51fd\u6570\u4fe1\u606f\u7684\u53d8\u91cf\u662f`fe_values_rt`\uff08\u548c\u76f8\u5e94\u7684`fe_face_values_rt`\uff09\u5bf9\u8c61\u3002\n\n// \u9274\u4e8e\u4e0a\u8ff0\u4ecb\u7ecd\uff0c\u4e0b\u9762\u7684\u58f0\u660e\u5e94\u8be5\u662f\u975e\u5e38\u660e\u663e\u7684\u3002\n\n  template <int dim> \n  void WGDarcyEquation<dim>::assemble_system() \n  { \n    const QGauss<dim>     quadrature_formula(fe_dgrt.degree + 1); \n    const QGauss<dim - 1> face_quadrature_formula(fe_dgrt.degree + 1); \n\n    FEValues<dim>     fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_quadrature_points | \n                              update_JxW_values); \n    FEFaceValues<dim> fe_face_values(fe, \n                                     face_quadrature_formula, \n                                     update_values | update_normal_vectors | \n                                       update_quadrature_points | \n                                       update_JxW_values); \n\n    FEValues<dim>     fe_values_dgrt(fe_dgrt, \n                                 quadrature_formula, \n                                 update_values | update_gradients | \n                                   update_quadrature_points | \n                                   update_JxW_values); \n    FEFaceValues<dim> fe_face_values_dgrt(fe_dgrt, \n                                          face_quadrature_formula, \n                                          update_values | \n                                            update_normal_vectors | \n                                            update_quadrature_points | \n                                            update_JxW_values); \n\n    const unsigned int dofs_per_cell      = fe.n_dofs_per_cell(); \n    const unsigned int dofs_per_cell_dgrt = fe_dgrt.n_dofs_per_cell(); \n\n    const unsigned int n_q_points      = fe_values.get_quadrature().size(); \n    const unsigned int n_q_points_dgrt = fe_values_dgrt.get_quadrature().size(); \n\n    const unsigned int n_face_q_points = fe_face_values.get_quadrature().size(); \n\n    RightHandSide<dim>  right_hand_side; \n    std::vector<double> right_hand_side_values(n_q_points); \n\n    const Coefficient<dim>      coefficient; \n    std::vector<Tensor<2, dim>> coefficient_values(n_q_points); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n// \u63a5\u4e0b\u6765\uff0c\u8ba9\u6211\u4eec\u58f0\u660e\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u5404\u79cd\u5355\u5143\u683c\u77e9\u9635\u3002\n\n    FullMatrix<double> cell_matrix_M(dofs_per_cell_dgrt, dofs_per_cell_dgrt); \n    FullMatrix<double> cell_matrix_G(dofs_per_cell_dgrt, dofs_per_cell); \n    FullMatrix<double> cell_matrix_C(dofs_per_cell, dofs_per_cell_dgrt); \n    FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<double>     cell_rhs(dofs_per_cell); \n    Vector<double>     cell_solution(dofs_per_cell); \n\n// \u6211\u4eec\u9700\u8981  <code>FEValuesExtractors</code>  \u6765\u8bbf\u95ee\u5f62\u72b6\u51fd\u6570\u7684  @p interior  \u548c  @p face  \u90e8\u5206\u3002\n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure_interior(0); \n    const FEValuesExtractors::Scalar pressure_face(1); \n\n// \u8fd9\u6700\u7ec8\u8ba9\u6211\u4eec\u5728\u6240\u6709\u5355\u5143\u683c\u4e0a\u8fdb\u884c\u5faa\u73af\u3002\u5728\u6bcf\u4e2a\u5355\u5143\u4e2d\uff0c\u6211\u4eec\u5c06\u9996\u5148\u8ba1\u7b97\u7528\u4e8e\u6784\u5efa\u5c40\u90e8\u77e9\u9635\u7684\u5404\u79cd\u5355\u5143\u77e9\u9635--\u56e0\u4e3a\u5b83\u4eec\u53d6\u51b3\u4e8e\u76f8\u5173\u7684\u5355\u5143\uff0c\u6240\u4ee5\u5b83\u4eec\u9700\u8981\u5728\u6bcf\u4e2a\u5355\u5143\u4e2d\u91cd\u65b0\u8ba1\u7b97\u3002\u6211\u4eec\u8fd8\u9700\u8981Raviart-Thomas\u7a7a\u95f4\u7684\u5f62\u72b6\u51fd\u6570\uff0c\u4e3a\u6b64\u6211\u4eec\u9700\u8981\u9996\u5148\u521b\u5efa\u4e00\u4e2a\u901a\u5f80\u4e09\u89d2\u5316\u5355\u5143\u7684\u8fed\u4ee3\u5668\uff0c\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u4ece\u6307\u5411DoFHandler\u7684\u5355\u5143\u4e2d\u7684\u8d4b\u503c\u6765\u83b7\u5f97\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        fe_values.reinit(cell); \n\n        const typename Triangulation<dim>::active_cell_iterator cell_dgrt = \n          cell; \n        fe_values_dgrt.reinit(cell_dgrt); \n\n        right_hand_side.value_list(fe_values.get_quadrature_points(), \n                                   right_hand_side_values); \n        coefficient.value_list(fe_values.get_quadrature_points(), \n                               coefficient_values); \n\n// \u6211\u4eec\u8981\u8ba1\u7b97\u7684\u7b2c\u4e00\u4e2a\u5355\u5143\u77e9\u9635\u662f\u62c9\u7ef4-\u6258\u9a6c\u65af\u7a7a\u95f4\u7684\u8d28\u91cf\u77e9\u9635\u3002 \u56e0\u6b64\uff0c\u6211\u4eec\u9700\u8981\u5faa\u73af\u8ba1\u7b97\u901f\u5ea6FEValues\u5bf9\u8c61\u7684\u6240\u6709\u6b63\u4ea4\u70b9\u3002\n\n        cell_matrix_M = 0; \n        for (unsigned int q = 0; q < n_q_points_dgrt; ++q) \n          for (unsigned int i = 0; i < dofs_per_cell_dgrt; ++i) \n            { \n              const Tensor<1, dim> v_i = fe_values_dgrt[velocities].value(i, q); \n              for (unsigned int k = 0; k < dofs_per_cell_dgrt; ++k) \n                { \n                  const Tensor<1, dim> v_k = \n                    fe_values_dgrt[velocities].value(k, q); \n                  cell_matrix_M(i, k) += (v_i * v_k * fe_values_dgrt.JxW(q)); \n                } \n            } \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u901a\u8fc7\u4f7f\u7528 FullMatrix::gauss_jordan(). \u5bf9\u8fd9\u4e2a\u77e9\u9635\u8fdb\u884c\u6c42\u9006 \u5b83\u5c06\u88ab\u7528\u6765\u8ba1\u7b97\u540e\u9762\u7684\u7cfb\u6570\u77e9\u9635 $C^K$ \u3002\u503c\u5f97\u4e00\u63d0\u7684\u662f\uff0c\u540e\u9762\u7684 \"cell_matrix_M \"\u5b9e\u9645\u4e0a\u5305\u542b\u4e86*\u7684\u9006*\u3002\n//\u5728\u8fd9\u4e2a\u8c03\u7528\u4e4b\u540e\u7684 $M^K$ \u7684*\u9006\u3002\n\n        cell_matrix_M.gauss_jordan(); \n\n// \u4ece\u4ecb\u7ecd\u4e2d\uff0c\u6211\u4eec\u77e5\u9053\u5b9a\u4e49 $C^K$ \u7684\u65b9\u7a0b\u7684\u53f3\u8fb9 $G^K$ \u662f\u9762\u79ef\u5206\u548c\u5355\u5143\u79ef\u5206\u7684\u533a\u522b\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u5bf9\u5185\u90e8\u7684\u8d21\u732e\u7684\u8d1f\u503c\u8fdb\u884c\u4e86\u8fd1\u4f3c\u3002\u8fd9\u4e2a\u77e9\u9635\u7684\u6bcf\u4e2a\u5206\u91cf\u90fd\u662f\u591a\u9879\u5f0f\u7a7a\u95f4\u7684\u4e00\u4e2a\u57fa\u51fd\u6570\u4e0e\u62c9\u7ef4-\u6258\u9a6c\u65af\u7a7a\u95f4\u7684\u4e00\u4e2a\u57fa\u51fd\u6570\u7684\u53d1\u6563\u4e4b\u95f4\u7684\u4e58\u79ef\u7684\u79ef\u5206\u3002\u8fd9\u4e9b\u57fa\u51fd\u6570\u662f\u5728\u5185\u90e8\u5b9a\u4e49\u7684\u3002\n\n        cell_matrix_G = 0; \n        for (unsigned int q = 0; q < n_q_points; ++q) \n          for (unsigned int i = 0; i < dofs_per_cell_dgrt; ++i) \n            { \n              const double div_v_i = \n                fe_values_dgrt[velocities].divergence(i, q); \n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                { \n                  const double phi_j_interior = \n                    fe_values[pressure_interior].value(j, q); \n\n                  cell_matrix_G(i, j) -= \n                    (div_v_i * phi_j_interior * fe_values.JxW(q)); \n                } \n            } \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u7528\u6b63\u4ea4\u6cd5\u5bf9\u9762\u7684\u79ef\u5206\u8fdb\u884c\u8fd1\u4f3c\u3002\u6bcf\u4e2a\u5206\u91cf\u90fd\u662f\u591a\u9879\u5f0f\u7a7a\u95f4\u7684\u57fa\u51fd\u6570\u4e0eRaviart-Thomas\u7a7a\u95f4\u7684\u57fa\u51fd\u6570\u4e0e\u6cd5\u5411\u91cf\u7684\u70b9\u79ef\u7684\u79ef\u5206\u3002\u6240\u4ee5\u6211\u4eec\u5728\u5143\u7d20\u7684\u6240\u6709\u9762\u4e0a\u5faa\u73af\uff0c\u5f97\u5230\u6cd5\u5411\u91cf\u3002\n\n        for (const auto &face : cell->face_iterators()) \n          { \n            fe_face_values.reinit(cell, face); \n            fe_face_values_dgrt.reinit(cell_dgrt, face); \n\n            for (unsigned int q = 0; q < n_face_q_points; ++q) \n              { \n                const Tensor<1, dim> &normal = fe_face_values.normal_vector(q); \n\n                for (unsigned int i = 0; i < dofs_per_cell_dgrt; ++i) \n                  { \n                    const Tensor<1, dim> v_i = \n                      fe_face_values_dgrt[velocities].value(i, q); \n                    for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                      { \n                        const double phi_j_face = \n                          fe_face_values[pressure_face].value(j, q); \n\n                        cell_matrix_G(i, j) += \n                          ((v_i * normal) * phi_j_face * fe_face_values.JxW(q)); \n                      } \n                  } \n              } \n          } \n// @p cell_matrix_C \u662f $G^K$ \u7684\u8f6c\u7f6e\u4e0e\u8d28\u91cf\u77e9\u9635\u7684\u9006\u4e4b\u95f4\u7684\u77e9\u9635\u4e58\u79ef\uff08\u8be5\u9006\u5b58\u50a8\u5728 @p cell_matrix_M): \u4e2d\uff09\u3002\n        cell_matrix_G.Tmmult(cell_matrix_C, cell_matrix_M); \n\n// \u6700\u540e\u6211\u4eec\u53ef\u4ee5\u8ba1\u7b97\u51fa\u672c\u5730\u77e9\u9635  $A^K$  \u3002 \u5143\u7d20  $A^K_{ij}$  \u7531  $\\int_{E} \\sum_{k,l} C_{ik} C_{jl} (\\mathbf{K} \\mathbf{v}_k) \\cdot \\mathbf{v}_l \\mathrm{d}x$  \u5f97\u5230\u3002\u6211\u4eec\u5728\u4e0a\u4e00\u6b65\u5df2\u7ecf\u8ba1\u7b97\u4e86\u7cfb\u6570 $C$ \uff0c\u56e0\u6b64\u5728\u9002\u5f53\u5730\u91cd\u65b0\u6392\u5217\u5faa\u73af\u540e\u5f97\u5230\u4ee5\u4e0b\u7ed3\u679c\u3002\n\n        local_matrix = 0; \n        for (unsigned int q = 0; q < n_q_points_dgrt; ++q) \n          { \n            for (unsigned int k = 0; k < dofs_per_cell_dgrt; ++k) \n              { \n                const Tensor<1, dim> v_k = \n                  fe_values_dgrt[velocities].value(k, q); \n                for (unsigned int l = 0; l < dofs_per_cell_dgrt; ++l) \n                  { \n                    const Tensor<1, dim> v_l = \n                      fe_values_dgrt[velocities].value(l, q); \n\n                    for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                      for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                        local_matrix(i, j) += \n                          (coefficient_values[q] * cell_matrix_C[i][k] * v_k) * \n                          cell_matrix_C[j][l] * v_l * fe_values_dgrt.JxW(q); \n                  } \n              } \n          } \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u8ba1\u7b97\u53f3\u624b\u8fb9\uff0c $\\int_{K} f q \\mathrm{d}x$  \u3002\n\n        cell_rhs = 0; \n        for (unsigned int q = 0; q < n_q_points; ++q) \n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            { \n              cell_rhs(i) += (fe_values[pressure_interior].value(i, q) * \n                              right_hand_side_values[q] * fe_values.JxW(q)); \n            } \n\n// \u6700\u540e\u4e00\u6b65\u662f\u5c06\u672c\u5730\u77e9\u9635\u7684\u7ec4\u4ef6\u5206\u914d\u5230\u7cfb\u7edf\u77e9\u9635\u4e2d\uff0c\u5e76\u5c06\u5355\u5143\u683c\u53f3\u4fa7\u7684\u7ec4\u4ef6\u8f6c\u79fb\u5230\u7cfb\u7edf\u53f3\u4fa7\u3002\n\n        cell->get_dof_indices(local_dof_indices); \n        constraints.distribute_local_to_global( \n          local_matrix, cell_rhs, local_dof_indices, system_matrix, system_rhs); \n      } \n  } \n\n//  @sect4{WGDarcyEquation<dim>::solve}  \n\n// \u8fd9\u4e00\u6b65\u76f8\u5f53\u7410\u788e\uff0c\u4e0e\u4e4b\u524d\u7684\u8bb8\u591a\u6559\u7a0b\u7a0b\u5e8f\u76f8\u540c\u3002\n\n  template <int dim> \n  void WGDarcyEquation<dim>::solve() \n  { \n    SolverControl            solver_control(1000, 1e-8 * system_rhs.l2_norm()); \n    SolverCG<Vector<double>> solver(solver_control); \n    solver.solve(system_matrix, solution, system_rhs, PreconditionIdentity()); \n    constraints.distribute(solution); \n  } \n// @sect4{WGDarcyEquation<dim>::compute_postprocessed_velocity}  \n\n// \u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\uff0c\u6839\u636e\u4e4b\u524d\u8ba1\u7b97\u7684\u538b\u529b\u89e3\u8ba1\u7b97\u51fa\u901f\u5ea6\u573a\u3002\u901f\u5ea6\u88ab\u5b9a\u4e49\u4e3a $\\mathbf{u}_h = \\mathbf{Q}_h \\left(-\\mathbf{K}\\nabla_{w,d}p_h \\right)$ \uff0c\u8fd9\u9700\u8981\u6211\u4eec\u8ba1\u7b97\u8bb8\u591a\u4e0e\u7cfb\u7edf\u77e9\u9635\u7ec4\u88c5\u76f8\u540c\u7684\u9879\u3002\u8fd8\u6709\u4e00\u4e9b\u77e9\u9635 $E^K,D^K$ \u6211\u4eec\u4e5f\u9700\u8981\u7ec4\u88c5\uff08\u89c1\u4ecb\u7ecd\uff09\uff0c\u4f46\u5b83\u4eec\u5b9e\u9645\u4e0a\u53ea\u662f\u9075\u5faa\u76f8\u540c\u7684\u6a21\u5f0f\u3002\n\n// \u5728\u8fd9\u91cc\u8ba1\u7b97\u4e0e\u6211\u4eec\u5728`assemble_system()`\u51fd\u6570\u4e2d\u5df2\u7ecf\u5b8c\u6210\u7684\u76f8\u540c\u7684\u77e9\u9635\uff0c\u5f53\u7136\u662f\u6d6a\u8d39CPU\u65f6\u95f4\u7684\u3002\u540c\u6837\u5730\uff0c\u6211\u4eec\u628a\u90a3\u91cc\u7684\u4e00\u4e9b\u4ee3\u7801\u590d\u5236\u5230\u8fd9\u4e2a\u51fd\u6570\u4e2d\uff0c\u8fd9\u901a\u5e38\u4e5f\u662f\u4e00\u4e2a\u7cdf\u7cd5\u7684\u4e3b\u610f\u3002\u4e00\u4e2a\u66f4\u597d\u7684\u5b9e\u73b0\u53ef\u80fd\u4f1a\u63d0\u4f9b\u4e00\u4e2a\u51fd\u6570\u6765\u5c01\u88c5\u8fd9\u4e9b\u91cd\u590d\u7684\u4ee3\u7801\u3002\u6211\u4eec\u4e5f\u53ef\u4ee5\u8003\u8651\u4f7f\u7528\u8ba1\u7b97\u6548\u7387\u548c\u5185\u5b58\u6548\u7387\u4e4b\u95f4\u7684\u7ecf\u5178\u6743\u8861\uff0c\u5728\u88c5\u914d\u8fc7\u7a0b\u4e2d\u6bcf\u4e2a\u5355\u5143\u53ea\u8ba1\u7b97\u4e00\u6b21 $C^K$ \u77e9\u9635\uff0c\u628a\u5b83\u4eec\u5b58\u50a8\u5728\u8fb9\u4e0a\u7684\u67d0\u4e2a\u5730\u65b9\uff0c\u7136\u540e\u5728\u8fd9\u91cc\u91cd\u65b0\u4f7f\u7528\u5b83\u4eec\u3002\u4f8b\u5982\uff0c step-51 \u5c31\u662f\u8fd9\u6837\u505a\u7684\uff0c`assemble_system()`\u51fd\u6570\u9700\u8981\u4e00\u4e2a\u53c2\u6570\u6765\u51b3\u5b9a\u662f\u5426\u91cd\u65b0\u8ba1\u7b97\u672c\u5730\u77e9\u9635\uff0c\u7c7b\u4f3c\u7684\u65b9\u6cd5--\u4e5f\u8bb8\u662f\u5c06\u672c\u5730\u77e9\u9635\u5b58\u50a8\u5728\u5176\u4ed6\u5730\u65b9--\u53ef\u4ee5\u9002\u7528\u4e8e\u5f53\u524d\u7684\u7a0b\u5e8f\uff09\u3002\n\n  template <int dim> \n  void WGDarcyEquation<dim>::compute_postprocessed_velocity() \n  { \n    darcy_velocity.reinit(dof_handler_dgrt.n_dofs()); \n\n    const QGauss<dim>     quadrature_formula(fe_dgrt.degree + 1); \n    const QGauss<dim - 1> face_quadrature_formula(fe_dgrt.degree + 1); \n\n    FEValues<dim> fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_quadrature_points | \n                              update_JxW_values); \n\n    FEFaceValues<dim> fe_face_values(fe, \n                                     face_quadrature_formula, \n                                     update_values | update_normal_vectors | \n                                       update_quadrature_points | \n                                       update_JxW_values); \n\n    FEValues<dim> fe_values_dgrt(fe_dgrt, \n                                 quadrature_formula, \n                                 update_values | update_gradients | \n                                   update_quadrature_points | \n                                   update_JxW_values); \n\n    FEFaceValues<dim> fe_face_values_dgrt(fe_dgrt, \n                                          face_quadrature_formula, \n                                          update_values | \n                                            update_normal_vectors | \n                                            update_quadrature_points | \n                                            update_JxW_values); \n\n    const unsigned int dofs_per_cell      = fe.n_dofs_per_cell(); \n    const unsigned int dofs_per_cell_dgrt = fe_dgrt.n_dofs_per_cell(); \n\n    const unsigned int n_q_points      = fe_values.get_quadrature().size(); \n    const unsigned int n_q_points_dgrt = fe_values_dgrt.get_quadrature().size(); \n\n    const unsigned int n_face_q_points = fe_face_values.get_quadrature().size(); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n    std::vector<types::global_dof_index> local_dof_indices_dgrt( \n      dofs_per_cell_dgrt); \n\n    FullMatrix<double> cell_matrix_M(dofs_per_cell_dgrt, dofs_per_cell_dgrt); \n    FullMatrix<double> cell_matrix_G(dofs_per_cell_dgrt, dofs_per_cell); \n    FullMatrix<double> cell_matrix_C(dofs_per_cell, dofs_per_cell_dgrt); \n    FullMatrix<double> cell_matrix_D(dofs_per_cell_dgrt, dofs_per_cell_dgrt); \n    FullMatrix<double> cell_matrix_E(dofs_per_cell_dgrt, dofs_per_cell_dgrt); \n\n    Vector<double> cell_solution(dofs_per_cell); \n    Vector<double> cell_velocity(dofs_per_cell_dgrt); \n\n    const Coefficient<dim>      coefficient; \n    std::vector<Tensor<2, dim>> coefficient_values(n_q_points_dgrt); \n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure_interior(0); \n    const FEValuesExtractors::Scalar pressure_face(1); \n\n// \u5728\u4ecb\u7ecd\u4e2d\uff0c\u6211\u4eec\u89e3\u91ca\u4e86\u5982\u4f55\u8ba1\u7b97\u5355\u5143\u4e0a\u7684\u6570\u503c\u901f\u5ea6\u3002\u6211\u4eec\u9700\u8981\u6bcf\u4e2a\u5355\u5143\u4e0a\u7684\u538b\u529b\u89e3\u503c\u3001\u683c\u62c9\u59c6\u77e9\u9635\u7684\u7cfb\u6570\u548c $L_2$ \u6295\u5f71\u7684\u7cfb\u6570\u3002\u6211\u4eec\u5df2\u7ecf\u8ba1\u7b97\u4e86\u5168\u5c40\u89e3\uff0c\u6240\u4ee5\u6211\u4eec\u5c06\u4ece\u5168\u5c40\u89e3\u4e2d\u63d0\u53d6\u5355\u5143\u89e3\u3002\u683c\u62c9\u59c6\u77e9\u9635\u7684\u7cfb\u6570\u5728\u6211\u4eec\u8ba1\u7b97\u538b\u529b\u7684\u7cfb\u7edf\u77e9\u9635\u65f6\u5df2\u7ecf\u8ba1\u7b97\u8fc7\u4e86\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u4e5f\u8981\u8fd9\u6837\u505a\u3002\u5bf9\u4e8e\u6295\u5f71\u7684\u7cfb\u6570\uff0c\u6211\u4eec\u505a\u77e9\u9635\u4e58\u6cd5\uff0c\u5373\u7528\u683c\u62c9\u59c6\u77e9\u9635\u7684\u5012\u6570\u4e58\u4ee5 $(\\mathbf{K} \\mathbf{w}, \\mathbf{w})$ \u7684\u77e9\u9635\u4f5c\u4e3a\u7ec4\u6210\u90e8\u5206\u3002\u7136\u540e\uff0c\u6211\u4eec\u5c06\u6240\u6709\u8fd9\u4e9b\u7cfb\u6570\u76f8\u4e58\uff0c\u79f0\u4e4b\u4e3a\u03b2\u3002\u6570\u503c\u901f\u5ea6\u662f\u8d1d\u5854\u548c\u62c9\u7ef4\u5c14\u7279-\u6258\u9a6c\u65af\u7a7a\u95f4\u7684\u57fa\u7840\u51fd\u6570\u7684\u4e58\u79ef\u3002\n\n    typename DoFHandler<dim>::active_cell_iterator \n      cell = dof_handler.begin_active(), \n      endc = dof_handler.end(), cell_dgrt = dof_handler_dgrt.begin_active(); \n    for (; cell != endc; ++cell, ++cell_dgrt) \n      { \n        fe_values.reinit(cell); \n        fe_values_dgrt.reinit(cell_dgrt); \n\n        coefficient.value_list(fe_values_dgrt.get_quadrature_points(), \n                               coefficient_values); \n\n// \u8fd9\u4e2a <code>cell_matrix_E</code> \u7684\u5206\u91cf\u662f $(\\mathbf{K} \\mathbf{w}, \\mathbf{w})$ \u7684\u79ef\u5206\u3002  <code>cell_matrix_M</code> \u662f\u683c\u62c9\u59c6\u77e9\u9635\u3002\n\n        cell_matrix_M = 0; \n        cell_matrix_E = 0; \n        for (unsigned int q = 0; q < n_q_points_dgrt; ++q) \n          for (unsigned int i = 0; i < dofs_per_cell_dgrt; ++i) \n            { \n              const Tensor<1, dim> v_i = fe_values_dgrt[velocities].value(i, q); \n              for (unsigned int k = 0; k < dofs_per_cell_dgrt; ++k) \n                { \n                  const Tensor<1, dim> v_k = \n                    fe_values_dgrt[velocities].value(k, q); \n\n                  cell_matrix_E(i, k) += \n                    (coefficient_values[q] * v_i * v_k * fe_values_dgrt.JxW(q)); \n\n                  cell_matrix_M(i, k) += (v_i * v_k * fe_values_dgrt.JxW(q)); \n                } \n            } \n\n// \u4e3a\u4e86\u8ba1\u7b97\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\u77e9\u9635 $D$ \uff0c\u6211\u4eec\u5c31\u9700\u8981\u6309\u7167\u4ecb\u7ecd\u4e2d\u7684\u89e3\u91ca\u6765\u8bc4\u4f30 $D=M^{-1}E$ \u3002\n\n        cell_matrix_M.gauss_jordan(); \n        cell_matrix_M.mmult(cell_matrix_D, cell_matrix_E); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u518d\u6b21\u8ba1\u7b97\u77e9\u9635 $C$ \uff0c\u7528\u4e8e\u8bc4\u4f30\u5f31\u79bb\u6563\u68af\u5ea6\u3002\u8fd9\u4e0e\u7ec4\u88c5\u7cfb\u7edf\u77e9\u9635\u65f6\u4f7f\u7528\u7684\u4ee3\u7801\u5b8c\u5168\u76f8\u540c\uff0c\u6240\u4ee5\u6211\u4eec\u53ea\u9700\u4ece\u90a3\u91cc\u590d\u5236\u5b83\u3002\n\n        cell_matrix_G = 0; \n        for (unsigned int q = 0; q < n_q_points; ++q) \n          for (unsigned int i = 0; i < dofs_per_cell_dgrt; ++i) \n            { \n              const double div_v_i = \n                fe_values_dgrt[velocities].divergence(i, q); \n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                { \n                  const double phi_j_interior = \n                    fe_values[pressure_interior].value(j, q); \n\n                  cell_matrix_G(i, j) -= \n                    (div_v_i * phi_j_interior * fe_values.JxW(q)); \n                } \n            } \n\n        for (const auto &face : cell->face_iterators()) \n          { \n            fe_face_values.reinit(cell, face); \n            fe_face_values_dgrt.reinit(cell_dgrt, face); \n\n            for (unsigned int q = 0; q < n_face_q_points; ++q) \n              { \n                const Tensor<1, dim> &normal = fe_face_values.normal_vector(q); \n\n                for (unsigned int i = 0; i < dofs_per_cell_dgrt; ++i) \n                  { \n                    const Tensor<1, dim> v_i = \n                      fe_face_values_dgrt[velocities].value(i, q); \n                    for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                      { \n                        const double phi_j_face = \n                          fe_face_values[pressure_face].value(j, q); \n\n                        cell_matrix_G(i, j) += \n                          ((v_i * normal) * phi_j_face * fe_face_values.JxW(q)); \n                      } \n                  } \n              } \n          } \n        cell_matrix_G.Tmmult(cell_matrix_C, cell_matrix_M); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u9700\u8981\u63d0\u53d6\u5bf9\u5e94\u4e8e\u5f53\u524d\u5355\u5143\u7684\u538b\u529b\u672a\u77e5\u6570\u3002\n\n        cell->get_dof_values(solution, cell_solution); \n\n// \u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u8ba1\u7b97\u5f53\u5730\u7684\u901f\u5ea6\u672a\u77e5\u6570\uff08\u76f8\u5bf9\u4e8e\u6211\u4eec\u5c06 $-\\mathbf K \\nabla_{w,d} p_h$ \u9879\u6295\u5f71\u5230\u7684Raviart-Thomas\u7a7a\u95f4\u800c\u8a00\uff09\u3002\n\n        cell_velocity = 0; \n        for (unsigned int k = 0; k < dofs_per_cell_dgrt; ++k) \n          for (unsigned int j = 0; j < dofs_per_cell_dgrt; ++j) \n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              cell_velocity(k) += \n                -(cell_solution(i) * cell_matrix_C(i, j) * cell_matrix_D(k, j)); \n\n// \u6211\u4eec\u8ba1\u7b97\u8fbe\u897f\u901f\u5ea6\u3002\u8fd9\u4e0ecell_velocity\u76f8\u540c\uff0c\u4f46\u7528\u4e8e\u7ed8\u5236Darcy\u901f\u5ea6\u56fe\u3002\n\n        cell_dgrt->get_dof_indices(local_dof_indices_dgrt); \n        for (unsigned int k = 0; k < dofs_per_cell_dgrt; ++k) \n          for (unsigned int j = 0; j < dofs_per_cell_dgrt; ++j) \n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              darcy_velocity(local_dof_indices_dgrt[k]) += \n                -(cell_solution(i) * cell_matrix_C(i, j) * cell_matrix_D(k, j)); \n      } \n  } \n\n//  @sect4{WGDarcyEquation<dim>::compute_pressure_error}  \n\n// \u8fd9\u4e00\u90e8\u5206\u662f\u4e3a\u4e86\u8ba1\u7b97\u538b\u529b\u7684 $L_2$ \u8bef\u5dee\u3002 \u6211\u4eec\u5b9a\u4e49\u4e00\u4e2a\u5411\u91cf\uff0c\u7528\u6765\u4fdd\u5b58\u6bcf\u4e2a\u5355\u5143\u4e0a\u7684\u8bef\u5dee\u89c4\u8303\u3002\u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u4f7f\u7528 VectorTool::integrate_difference() \u6765\u8ba1\u7b97\u6bcf\u4e2a\u5355\u5143\u4e0a\u7684 $L_2$ \u51c6\u5219\u7684\u8bef\u5dee\u3002\u7136\u800c\uff0c\u6211\u4eec\u5b9e\u9645\u4e0a\u53ea\u5173\u5fc3\u89e3\u5411\u91cf\u7684\u5185\u90e8\u5206\u91cf\u7684\u8bef\u5dee\uff08\u6211\u4eec\u751a\u81f3\u4e0d\u80fd\u8bc4\u4f30\u6b63\u4ea4\u70b9\u7684\u754c\u9762\u538b\u529b\uff0c\u56e0\u4e3a\u8fd9\u4e9b\u90fd\u4f4d\u4e8e\u5355\u5143\u683c\u7684\u5185\u90e8\uff09\uff0c\u56e0\u6b64\u5fc5\u987b\u4f7f\u7528\u4e00\u4e2a\u6743\u91cd\u51fd\u6570\uff0c\u786e\u4fdd\u89e3\u53d8\u91cf\u7684\u754c\u9762\u5206\u91cf\u88ab\u5ffd\u7565\u3002\u8fd9\u662f\u901a\u8fc7\u4f7f\u7528ComponentSelectFunction\u6765\u5b9e\u73b0\u7684\uff0c\u5176\u53c2\u6570\u8868\u660e\u6211\u4eec\u8981\u9009\u62e9\u54ea\u4e2a\u5206\u91cf\uff08\u96f6\u5206\u91cf\uff0c\u5373\u5185\u90e8\u538b\u529b\uff09\u4ee5\u53ca\u603b\u5171\u6709\u591a\u5c11\u5206\u91cf\uff08\u4e24\u4e2a\uff09\u3002\n\n  template <int dim> \n  void WGDarcyEquation<dim>::compute_pressure_error() \n  { \n    Vector<float> difference_per_cell(triangulation.n_active_cells()); \n    const ComponentSelectFunction<dim> select_interior_pressure(0, 2); \n    VectorTools::integrate_difference(dof_handler, \n                                      solution, \n                                      ExactPressure<dim>(), \n                                      difference_per_cell, \n                                      QGauss<dim>(fe.degree + 2), \n                                      VectorTools::L2_norm, \n                                      &select_interior_pressure); \n\n    const double L2_error = difference_per_cell.l2_norm(); \n    std::cout << \"L2_error_pressure \" << L2_error << std::endl; \n  } \n\n//  @sect4{WGDarcyEquation<dim>::compute_velocity_error}  \n\n// \u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u8bc4\u4f30\u6bcf\u4e2a\u5355\u5143\u7684\u901f\u5ea6\u7684 $L_2$ \u8bef\u5dee\uff0c\u4ee5\u53ca\u9762\u7684\u6d41\u91cf\u7684 $L_2$ \u8bef\u5dee\u3002\u8be5\u51fd\u6570\u4f9d\u8d56\u4e8e\u4e4b\u524d\u8ba1\u7b97\u8fc7\u7684`compute_postprocessed_velocity()`\u51fd\u6570\uff0c\u8be5\u51fd\u6570\u6839\u636e\u4e4b\u524d\u8ba1\u7b97\u8fc7\u7684\u538b\u529b\u89e3\u6765\u8ba1\u7b97\u901f\u5ea6\u573a\u3002\n\n// \u6211\u4eec\u5c06\u8bc4\u4f30\u6bcf\u4e2a\u5355\u5143\u7684\u901f\u5ea6\uff0c\u5e76\u8ba1\u7b97\u6570\u503c\u901f\u5ea6\u548c\u7cbe\u786e\u901f\u5ea6\u4e4b\u95f4\u7684\u5dee\u5f02\u3002\n\n  template <int dim> \n  void WGDarcyEquation<dim>::compute_velocity_errors() \n  { \n    const QGauss<dim>     quadrature_formula(fe_dgrt.degree + 1); \n    const QGauss<dim - 1> face_quadrature_formula(fe_dgrt.degree + 1); \n\n    FEValues<dim> fe_values_dgrt(fe_dgrt, \n                                 quadrature_formula, \n                                 update_values | update_gradients | \n                                   update_quadrature_points | \n                                   update_JxW_values); \n\n    FEFaceValues<dim> fe_face_values_dgrt(fe_dgrt, \n                                          face_quadrature_formula, \n                                          update_values | \n                                            update_normal_vectors | \n                                            update_quadrature_points | \n                                            update_JxW_values); \n\n    const unsigned int n_q_points_dgrt = fe_values_dgrt.get_quadrature().size(); \n    const unsigned int n_face_q_points_dgrt = \n      fe_face_values_dgrt.get_quadrature().size(); \n\n    std::vector<Tensor<1, dim>> velocity_values(n_q_points_dgrt); \n    std::vector<Tensor<1, dim>> velocity_face_values(n_face_q_points_dgrt); \n\n    const FEValuesExtractors::Vector velocities(0); \n\n    const ExactVelocity<dim> exact_velocity; \n\n    double L2_err_velocity_cell_sqr_global = 0; \n    double L2_err_flux_sqr                 = 0; \n\n// \u5728\u4e4b\u524d\u8ba1\u7b97\u4e86\u540e\u5904\u7406\u7684\u901f\u5ea6\u4e4b\u540e\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u53ea\u9700\u8981\u63d0\u53d6\u6bcf\u4e2a\u5355\u5143\u548c\u9762\u7684\u76f8\u5e94\u6570\u503c\uff0c\u5e76\u4e0e\u7cbe\u786e\u7684\u6570\u503c\u8fdb\u884c\u6bd4\u8f83\u3002\n\n    for (const auto &cell_dgrt : dof_handler_dgrt.active_cell_iterators()) \n      { \n        fe_values_dgrt.reinit(cell_dgrt); \n\n// \u9996\u5148\u8ba1\u7b97\u540e\u5904\u7406\u7684\u901f\u5ea6\u573a\u4e0e\u7cbe\u786e\u901f\u5ea6\u573a\u4e4b\u95f4\u7684 $L_2$ \u8bef\u5dee\u3002\n\n        fe_values_dgrt[velocities].get_function_values(darcy_velocity, \n                                                       velocity_values); \n        double L2_err_velocity_cell_sqr_local = 0; \n        for (unsigned int q = 0; q < n_q_points_dgrt; ++q) \n          { \n            const Tensor<1, dim> velocity = velocity_values[q]; \n            const Tensor<1, dim> true_velocity = \n              exact_velocity.value(fe_values_dgrt.quadrature_point(q)); \n\n            L2_err_velocity_cell_sqr_local += \n              ((velocity - true_velocity) * (velocity - true_velocity) * \n               fe_values_dgrt.JxW(q)); \n          } \n        L2_err_velocity_cell_sqr_global += L2_err_velocity_cell_sqr_local; \n\n// \u4e3a\u4e86\u91cd\u5efa\u901a\u91cf\uff0c\u6211\u4eec\u9700\u8981\u5355\u5143\u683c\u548c\u9762\u7684\u5927\u5c0f\u3002\u7531\u4e8e\u901a\u91cf\u662f\u6309\u9762\u8ba1\u7b97\u7684\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u6bcf\u4e2a\u5355\u5143\u7684\u6240\u6709\u56db\u4e2a\u9762\u4e0a\u8fdb\u884c\u5faa\u73af\u3002\u4e3a\u4e86\u8ba1\u7b97\u9762\u7684\u901f\u5ea6\uff0c\u6211\u4eec\u4ece\u4e4b\u524d\u8ba1\u7b97\u7684`darcy_velocity`\u4e2d\u63d0\u53d6\u6b63\u4ea4\u70b9\u7684\u503c\u3002\u7136\u540e\uff0c\u6211\u4eec\u8ba1\u7b97\u6cd5\u7ebf\u65b9\u5411\u7684\u901f\u5ea6\u5e73\u65b9\u8bef\u5dee\u3002\u6700\u540e\uff0c\u6211\u4eec\u901a\u8fc7\u5bf9\u9762\u548c\u5355\u5143\u9762\u79ef\u7684\u9002\u5f53\u7f29\u653e\u6765\u8ba1\u7b97\u5355\u5143\u4e0a\u7684 $L_2$ \u901a\u91cf\u8bef\u5dee\uff0c\u5e76\u5c06\u5176\u52a0\u5165\u5168\u5c40\u8bef\u5dee\u3002\n\n        const double cell_area = cell_dgrt->measure(); \n        for (const auto &face_dgrt : cell_dgrt->face_iterators()) \n          { \n            const double face_length = face_dgrt->measure(); \n            fe_face_values_dgrt.reinit(cell_dgrt, face_dgrt); \n            fe_face_values_dgrt[velocities].get_function_values( \n              darcy_velocity, velocity_face_values); \n\n            double L2_err_flux_face_sqr_local = 0; \n            for (unsigned int q = 0; q < n_face_q_points_dgrt; ++q) \n              { \n                const Tensor<1, dim> velocity = velocity_face_values[q]; \n                const Tensor<1, dim> true_velocity = \n                  exact_velocity.value(fe_face_values_dgrt.quadrature_point(q)); \n\n                const Tensor<1, dim> &normal = \n                  fe_face_values_dgrt.normal_vector(q); \n\n \n                  ((velocity * normal - true_velocity * normal) * \n                   (velocity * normal - true_velocity * normal) * \n                   fe_face_values_dgrt.JxW(q)); \n              } \n            const double err_flux_each_face = \n              L2_err_flux_face_sqr_local / face_length * cell_area; \n            L2_err_flux_sqr += err_flux_each_face; \n          } \n      } \n\n// \u5c06\u6240\u6709\u5355\u5143\u548c\u9762\u7684\u8bef\u5dee\u76f8\u52a0\u540e\uff0c\u6211\u4eec\u8fdb\u884c\u5e73\u65b9\u6839\u8ba1\u7b97\uff0c\u5f97\u5230\u901f\u5ea6\u548c\u6d41\u91cf\u7684 $L_2$ \u8bef\u5dee\u3002\u6211\u4eec\u5c06\u8fd9\u4e9b\u6570\u636e\u8f93\u51fa\u5230\u5c4f\u5e55\u4e0a\u3002\n\n    const double L2_err_velocity_cell = \n      std::sqrt(L2_err_velocity_cell_sqr_global); \n    const double L2_err_flux_face = std::sqrt(L2_err_flux_sqr); \n\n    std::cout << \"L2_error_vel:  \" << L2_err_velocity_cell << std::endl \n              << \"L2_error_flux: \" << L2_err_flux_face << std::endl; \n  } \n// @sect4{WGDarcyEquation::output_results}  \n\n// \u6211\u4eec\u6709\u4e24\u7ec4\u7ed3\u679c\u8981\u8f93\u51fa\uff1a\u5185\u90e8\u89e3\u548c\u9aa8\u67b6\u89e3\u3002\u6211\u4eec\u4f7f\u7528 <code>DataOut</code> \u6765\u663e\u793a\u5185\u90e8\u7ed3\u679c\u3002\u9aa8\u67b6\u7ed3\u679c\u7684\u56fe\u5f62\u8f93\u51fa\u662f\u901a\u8fc7\u4f7f\u7528DataOutFaces\u7c7b\u5b8c\u6210\u7684\u3002\n\n// \u5728\u8fd9\u4e24\u4e2a\u8f93\u51fa\u6587\u4ef6\u4e2d\uff0c\u5185\u90e8\u548c\u9762\u7684\u53d8\u91cf\u90fd\u88ab\u5b58\u50a8\u3002\u5bf9\u4e8e\u754c\u9762\u8f93\u51fa\uff0c\u8f93\u51fa\u6587\u4ef6\u53ea\u662f\u5305\u542b\u4e86\u5185\u90e8\u538b\u529b\u5bf9\u9762\u7684\u63d2\u503c\uff0c\u4f46\u662f\u56e0\u4e3a\u6ca1\u6709\u786e\u5b9a\u4ece\u4e24\u4e2a\u76f8\u90bb\u7684\u5355\u5143\u4e2d\u5f97\u5230\u7684\u662f\u54ea\u4e00\u4e2a\u5185\u90e8\u538b\u529b\u53d8\u91cf\uff0c\u6240\u4ee5\u5728\u754c\u9762\u8f93\u51fa\u6587\u4ef6\u4e2d\u6700\u597d\u662f\u5ffd\u7565\u5185\u90e8\u538b\u529b\u3002\u76f8\u53cd\uff0c\u5bf9\u4e8e\u5355\u5143\u683c\u5185\u90e8\u8f93\u51fa\u6587\u4ef6\uff0c\u5f53\u7136\u4e0d\u53ef\u80fd\u663e\u793a\u4efb\u4f55\u754c\u9762\u538b\u529b $p^\\partial$ \uff0c\u56e0\u4e3a\u8fd9\u4e9b\u538b\u529b\u53ea\u9002\u7528\u4e8e\u754c\u9762\uff0c\u800c\u4e0d\u662f\u5355\u5143\u683c\u5185\u90e8\u3002\u56e0\u6b64\uff0c\u4f60\u4f1a\u770b\u5230\u5b83\u4eec\u88ab\u663e\u793a\u4e3a\u4e00\u4e2a\u65e0\u6548\u7684\u503c\uff08\u6bd4\u5982\u4e00\u4e2a\u65e0\u7a77\u5927\uff09\u3002\n\n// \u5bf9\u4e8e\u5355\u5143\u5185\u90e8\u7684\u8f93\u51fa\uff0c\u6211\u4eec\u8fd8\u60f3\u8f93\u51fa\u901f\u5ea6\u53d8\u91cf\u3002\u8fd9\u6709\u70b9\u68d8\u624b\uff0c\u56e0\u4e3a\u5b83\u751f\u6d3b\u5728\u540c\u4e00\u4e2a\u7f51\u683c\u4e0a\uff0c\u4f46\u4f7f\u7528\u4e0d\u540c\u7684DoFHandler\u5bf9\u8c61\uff08\u538b\u529b\u53d8\u91cf\u751f\u6d3b\u5728`dof_handler`\u5bf9\u8c61\u4e0a\uff0c\u8fbe\u897f\u901f\u5ea6\u751f\u6d3b\u5728`dof_handler_dgrt`\u5bf9\u8c61\u4e0a\uff09\u3002\u5e78\u8fd0\u7684\u662f\uff0c DataOut::add_data_vector() \u51fd\u6570\u6709\u4e00\u4e9b\u53d8\u5316\uff0c\u5141\u8bb8\u6307\u5b9a\u4e00\u4e2a\u77e2\u91cf\u5bf9\u5e94\u7684DoFHandler\uff0c\u56e0\u6b64\u6211\u4eec\u53ef\u4ee5\u5728\u540c\u4e00\u4e2a\u6587\u4ef6\u4e2d\u5bf9\u4e24\u4e2aDoFHandler\u5bf9\u8c61\u7684\u6570\u636e\u8fdb\u884c\u53ef\u89c6\u5316\u3002\n\n  template <int dim> \n  void WGDarcyEquation<dim>::output_results() const \n  { \n    { \n      DataOut<dim> data_out; \n\n// \u9996\u5148\u5c06\u538b\u529b\u89e3\u51b3\u65b9\u6848\u9644\u52a0\u5230DataOut\u5bf9\u8c61\u4e0a\u3002\n\n      const std::vector<std::string> solution_names = {\"interior_pressure\", \n                                                       \"interface_pressure\"}; \n      data_out.add_data_vector(dof_handler, solution, solution_names); \n\n// \u7136\u540e\u5bf9\u8fbe\u897f\u901f\u5ea6\u573a\u505a\u540c\u6837\u7684\u5904\u7406\uff0c\u5e76\u7ee7\u7eed\u5c06\u6240\u6709\u5185\u5bb9\u5199\u8fdb\u6587\u4ef6\u3002\n\n      const std::vector<std::string> velocity_names(dim, \"velocity\"); \n      const std::vector< \n        DataComponentInterpretation::DataComponentInterpretation> \n        velocity_component_interpretation( \n          dim, DataComponentInterpretation::component_is_part_of_vector); \n      data_out.add_data_vector(dof_handler_dgrt, \n                               darcy_velocity, \n                               velocity_names, \n                               velocity_component_interpretation); \n\n      data_out.build_patches(fe.degree); \n      std::ofstream output(\"solution_interior.vtu\"); \n      data_out.write_vtu(output); \n    } \n\n    { \n      DataOutFaces<dim> data_out_faces(false); \n      data_out_faces.attach_dof_handler(dof_handler); \n      data_out_faces.add_data_vector(solution, \"Pressure_Face\"); \n      data_out_faces.build_patches(fe.degree); \n      std::ofstream face_output(\"solution_interface.vtu\"); \n      data_out_faces.write_vtu(face_output); \n    } \n  } \n// @sect4{WGDarcyEquation::run}  \n\n// \u8fd9\u662f\u4e3b\u7c7b\u7684\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u3002\u5b83\u8c03\u7528\u6211\u4eec\u7c7b\u7684\u5176\u4ed6\u51fd\u6570\u3002\n\n  template <int dim> \n  void WGDarcyEquation<dim>::run() \n  { \n    std::cout << \"Solving problem in \" << dim << \" space dimensions.\" \n              << std::endl; \n    make_grid(); \n    setup_system(); \n    assemble_system(); \n    solve(); \n    compute_postprocessed_velocity(); \n    compute_pressure_error(); \n    compute_velocity_errors(); \n    output_results(); \n  } \n\n} // namespace Step61 \n// @sect3{The <code>main</code> function}  \n\n// \u8fd9\u662f\u4e3b\u51fd\u6570\u3002\u6211\u4eec\u53ef\u4ee5\u5728\u8fd9\u91cc\u6539\u53d8\u7ef4\u5ea6\u4ee5\u57283D\u4e2d\u8fd0\u884c\u3002\n\nint main() \n{ \n  try \n    { \n      Step61::WGDarcyEquation<2> wg_darcy(0); \n      wg_darcy.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\n  return 0; \n} \n\n", "meta": {"hexsha": "ad860baacb9bace350c86371b6fe0922aca24e03", "size": 34723, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-61/step-61.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-61/step-61.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-61/step-61.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.5929304447, "max_line_length": 449, "alphanum_fraction": 0.5989401837, "num_tokens": 11866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5376964537891089}}
{"text": "// ALGOLAB BGL Tutorial 3\n// Flow example demonstrating\n// - breadth first search (BFS) on the residual graph\n\n// Compile and run with one of the following:\n// g++ -std=c++11 -O2 bgl_residual_bfs.cpp -o bgl_residual_bfs ./bgl_residual_bfs\n// g++ -std=c++11 -O2 -I path/to/boost_1_58_0 bgl_residual_bfs.cpp -o bgl_residual_bfs; ./bgl_residual_bfs\n\n// Includes\n// ========\n// STL includes\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <queue>\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/tuple/tuple.hpp>\n// Namespaces\nusing namespace std;\nusing namespace boost;\n\n// BGL Graph definitions\n// =====================\n// Graph Type with nested interior edge properties for Flow Algorithms\ntypedef\tadjacency_list_traits<vecS, vecS, directedS> Traits;\ntypedef adjacency_list<vecS, vecS, directedS, no_property,\n\tproperty<edge_capacity_t, long,\n\t\tproperty<edge_residual_capacity_t, long,\n\t\t\tproperty<edge_reverse_t, Traits::edge_descriptor> > > >\tGraph;\n// Interior Property Maps\ntypedef\tproperty_map<Graph, edge_capacity_t>::type\t\tEdgeCapacityMap;\ntypedef\tproperty_map<Graph, edge_residual_capacity_t>::type\tResidualCapacityMap;\ntypedef\tproperty_map<Graph, edge_reverse_t>::type\t\tReverseEdgeMap;\ntypedef\tgraph_traits<Graph>::vertex_descriptor\t\t\tVertex;\ntypedef\tgraph_traits<Graph>::edge_descriptor\t\t\tEdge;\ntypedef\tgraph_traits<Graph>::out_edge_iterator\t\t\tOutEdgeIt;\n\n// Custom Edge Adder Class, that holds the references\n// to the graph, capacity map and reverse edge map\n// ===================================================\nclass EdgeAdder {\n\tGraph &G;\n\tEdgeCapacityMap\t&capacitymap;\n\tReverseEdgeMap\t&revedgemap;\n\npublic:\n\t// to initialize the Object\n\tEdgeAdder(Graph & G, EdgeCapacityMap &capacitymap, ReverseEdgeMap &revedgemap):\n\t\tG(G), capacitymap(capacitymap), revedgemap(revedgemap){}\n\n\t// to use the Function (add an edge)\n\tvoid addEdge(int from, int to, long capacity) {\n\t\tEdge e, reverseE;\n\t\tbool success;\n\t\ttie(e, success) = add_edge(from, to, G);\n\t\ttie(reverseE, success) = add_edge(to, from, G);\n\t\tcapacitymap[e] = capacity;\n\t\tcapacitymap[reverseE] = 0;\n\t\trevedgemap[e] = reverseE;\n\t\trevedgemap[reverseE] = e;\n\t}\n};\n\n\n// Main\nint main() {\n\t// build Graph\n\tconst int N = 6;\n\tGraph G(N);\n\tEdgeCapacityMap capacitymap = get(edge_capacity, G);\n\tReverseEdgeMap revedgemap = get(edge_reverse, G);\n\tResidualCapacityMap rescapacitymap = get(edge_residual_capacity, G);\n\tEdgeAdder eaG(G, capacitymap, revedgemap);\n\n\tVertex src = 0;\n\tVertex sink = 5;\n\n\t// add edges\n\teaG.addEdge(src, 1, 5);\n\teaG.addEdge(1, 2, 3);\n\teaG.addEdge(1, 3, 2);\n\teaG.addEdge(2, 3, 1);\n\teaG.addEdge(2, 4, 2);\n\teaG.addEdge(3, 4, 2);\n\teaG.addEdge(4, sink, 4);\n\n\t// Find a min cut via maxflow\n\tint flow = push_relabel_max_flow(G, src, sink);\n\tcout << \"maximum flow = minimum cut = \" << flow << endl;\n\n\t// BFS to find vertex set S\n\tvector<int> vis(N, false); // visited flags\n\tstd::queue<int> Q; // BFS queue (from std:: not boost::)\n\tvis[src] = true; // Mark the source as visited\n\tQ.push(src);\n\twhile (!Q.empty()) {\n\t\tconst int u = Q.front();\n\t\tQ.pop();\n\t\tOutEdgeIt ebeg, eend;\n\t\tfor (tie(ebeg, eend) = out_edges(u, G); ebeg != eend; ++ebeg) {\n\t\t\tconst int v = target(*ebeg, G);\n\t\t\t// Only follow edges with spare capacity\n\t\t\tif (rescapacitymap[*ebeg] == 0 || vis[v]) continue;\n\t\t\tvis[v] = true;\n\t\t\tQ.push(v);\n\t\t}\n\t}\n\n\t// Output S\n\tfor (int i = 0; i < N; ++i) {\n\t\tif (vis[i]) cout << i << \" \";\n\t}\n\tcout << endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "646d1cfe2e360f191fc07854e0c5ce7fb3f72aa5", "size": 3495, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week9/examples/tut9_bgl_residual_bfs.cpp", "max_stars_repo_name": "KarlKode/algo-lab", "max_stars_repo_head_hexsha": "69bf7e65bda465e09b72f4adaddee3f65e7a7567", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week9/examples/tut9_bgl_residual_bfs.cpp", "max_issues_repo_name": "KarlKode/algo-lab", "max_issues_repo_head_hexsha": "69bf7e65bda465e09b72f4adaddee3f65e7a7567", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week9/examples/tut9_bgl_residual_bfs.cpp", "max_forks_repo_name": "KarlKode/algo-lab", "max_forks_repo_head_hexsha": "69bf7e65bda465e09b72f4adaddee3f65e7a7567", "max_forks_repo_licenses": ["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.3697478992, "max_line_length": 106, "alphanum_fraction": 0.6892703863, "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5376964507134622}}
{"text": "//// Copyright (c) 2018 Silvio Mayolo\n//// See LICENSE.txt for licensing details\n\n#ifndef NUMBER_HPP\n#define NUMBER_HPP\n\n#include <ios>\n#include <string>\n#include <type_traits>\n#include <complex>\n#include <boost/variant.hpp>\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/distance.hpp>\n#include <boost/mpl/begin_end.hpp>\n#include <boost/mpl/find.hpp>\n#include <boost/mpl/size.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/operators.hpp>\n#include <boost/optional.hpp>\n\n/// \\file\n///\n/// \\brief The Number class and its helpers.\n\n/// A Latitude number can be stored in one of five ways, depending on\n/// the precision needed. They are listed here, in increasing order of\n/// \"wideness\". That is, if an operation is performed that involves\n/// two numbers, the resulting number will be at least as wide as the\n/// wider of the two operands.\n///\n/// -# `smallint` A fixed-precision integer value\n/// -# `bigint` An arbitrary precision integer value\n/// -# `ratio` A fraction consisting of arbitrary precision integers\n/// -# `floating` A floating-point real value\n/// -# `complex` A floating-point complex value\nclass Number :\n    private boost::integer_arithmetic<Number>,\n    private boost::bitwise<Number>,\n    private boost::unit_steppable<Number> {\npublic:\n\n    /// A fixed-precision integer is a C++ long integer.\n    typedef long smallint;\n\n    /// An arbitrary precision integer.\n    typedef boost::multiprecision::cpp_int bigint;\n\n    /// A rational number.\n    typedef boost::multiprecision::cpp_rational ratio;\n\n    /// A floating-point number, using the appropriate C++ type.\n    typedef double floating;\n\n    /// A C++ complex type, consisting of floating-point values.\n    typedef std::complex<double> complex;\n\n    /// \\brief This is the internal type of the Number instance which\n    /// contains the actual value.\n    typedef boost::variant<smallint, bigint, ratio, floating, complex> magic_t;\n\n    /// An enumeration representing the levels of the Latitude\n    /// numerical hierarchy.\n    enum hierarchy_t {\n        SMALLINT = 0,\n        BIGINT   = 1,\n        RATIO    = 2,\n        FLOATING = 3,\n        COMPLEX  = 4\n    };\n\nprivate:\n    std::unique_ptr<magic_t> value;\npublic:\n\n    /// \\details Constructs a zero number of the narrowest type.\n    Number();\n\n    /// Constructs a number.\n    ///\n    /// \\param arg a small integer\n    Number(smallint arg);\n\n    /// Constructs a number.\n    ///\n    /// \\param arg a large integer\n    Number(bigint arg);\n\n    /// Constructs a number.\n    ///\n    /// \\param arg a rational number\n    Number(ratio arg);\n\n    /// Constructs a number.\n    ///\n    /// \\param arg a floating-point number\n    Number(floating arg);\n\n    /// Constructs a number.\n    ///\n    /// \\param arg a complex number\n    Number(complex arg);\n\n    /// Copy-constructs a number.\n    ///\n    /// \\param num the other number\n    Number(const Number& num);\n\n    /// Copy-assigns a number.\n    ///\n    /// \\param other the other number\n    Number& operator=(Number other);\n\n    /// Adds the number in-place.\n    ///\n    /// \\param other the number to add\n    /// \\return the current number\n    Number& operator +=(const Number& other);\n\n    /// Subtracts the number in-place.\n    ///\n    /// \\param other the number to subtract\n    /// \\return the current number\n    Number& operator -=(const Number& other);\n\n    /// Multiplies the number in-place.\n    ///\n    /// \\param other the number to multiply\n    /// \\return the current number\n    Number& operator *=(const Number& other);\n\n    /// Divides the number in-place.\n    ///\n    /// \\param other the divisor\n    /// \\return the current number\n    Number& operator /=(const Number& other);\n\n    /// Replaces the number with its value modulo some divisor.\n    ///\n    /// \\param other the divisor\n    /// \\return the current number\n    Number& operator %=(const Number& other);\n\n    /// Returns the current number to the power of the argument. If\n    /// the answer does not exist, then the appropriate floating-point\n    /// exceptional value, such as NaN, is returned. If floating-point\n    /// special values are unsupported on the current system, the\n    /// behavior is undefined.\n    ///\n    /// \\param other the exponent\n    /// \\return the resulting value\n    Number pow(const Number& other) const;\n\n    /// Negates the current number.\n    ///\n    /// \\return the additive inverse\n    Number operator -() const;\n\n    /// Reciprocates the value. If the value is zero, then the\n    /// appropriate floating-point exceptional value is returned, with\n    /// an architecture-defined fallback if that fails.\n    ///\n    /// \\return the multiplicative inverse\n    Number recip() const;\n\n    /// Performs bitwise AND on the number in-place.\n    ///\n    /// \\param other the other number\n    /// \\return the current number\n    Number& operator &=(const Number& other);\n\n    /// Performs bitwise OR on the number in-place.\n    ///\n    /// \\param other the other number\n    /// \\return the current number\n    Number& operator |=(const Number& other);\n\n    /// Performs bitwise XOR on the number in-place.\n    ///\n    /// \\param other the other number\n    /// \\return the current number\n    Number& operator ^=(const Number& other);\n\n    /// Performs bitwise NOT on the number in-place.\n    ///\n    /// \\return the result\n    Number operator ~() const;\n\n    /// Returns the sine of the number.\n    ///\n    /// \\return the result of the computation\n    Number sin() const;\n\n    /// Returns the cosine of the number.\n    ///\n    /// \\return the result of the computation\n    Number cos() const;\n\n    /// Returns the tangent of the number.\n    ///\n    /// \\return the result of the computation\n    Number tan() const;\n\n    /// Returns the hyperbolic sine of the number.\n    ///\n    /// \\return the result of the computation\n    Number sinh() const;\n\n    /// Returns the hyperbolic cosine of the number.\n    ///\n    /// \\return the result of the computation\n    Number cosh() const;\n\n    /// Returns the hyperbolic tangent of the number.\n    ///\n    /// \\return the result of the computation\n    Number tanh() const;\n\n    /// Returns e to the power of the number.\n    ///\n    /// \\return the result of the computation\n    Number exp() const;\n\n    /// Returns the inverse sine of the number.\n    ///\n    /// \\return the result of the computation\n    Number asin() const;\n\n    /// Returns the inverse cosine of the number.\n    ///\n    /// \\return the result of the computation\n    Number acos() const;\n\n    /// Returns the inverse tangent of the number.\n    ///\n    /// \\return the result of the computation\n    Number atan() const;\n\n    /// Returns the inverse hyperbolic sine of the number.\n    ///\n    /// \\return the result of the computation\n    Number asinh() const;\n\n    /// Returns the inverse hyperbolic cosine of the number.\n    ///\n    /// \\return the result of the computation\n    Number acosh() const;\n\n    /// Returns the inverse hyperbolic tangent of the number.\n    ///\n    /// \\return the result of the computation\n    Number atanh() const;\n\n    /// Returns the natural logarithm of the number.\n    ///\n    /// \\return the result of the computation\n    Number log() const;\n\n    /// Returns the floor of the number, truncated toward negative\n    /// infinity. If the caller is a complex number, the resulting\n    /// value is simply zero, as the greatest integer function is not\n    /// well-defined on complex numbers.\n    ///\n    /// \\return the result of the computation\n    Number floor() const;\n\n    /// Returns the real part of the number, or the number itself if\n    /// it is real.\n    ///\n    /// \\return the real part\n    Number realPart() const;\n\n    /// Returns the imaginary part of the number, or zero if it is\n    /// real.\n    ///\n    /// \\return the imaginary part\n    Number imagPart() const;\n\n    /// Returns a string representation of the number. Where possible,\n    /// the string is be a valid Latitude string that evaluates to the\n    /// number.\n    ///\n    /// \\return the string representation\n    std::string asString() const;\n\n    /// Forcibly casts the number to the C++ integral type\n    /// corresponding to Number::smallint. If the value was wider, it\n    /// will be truncated. This is useful in VM functions that require\n    /// an enumeration value, as it is convenient to simply assume\n    /// that the enumeration value is a small integer.\n    ///\n    /// \\return the casted value\n    smallint asSmallInt() const;\n\n    /// Returns a numerical value corresponding to the level of the\n    /// hierarchy that the value belongs to, with 0 being the\n    /// narrowest type (small integer) and 4 being the largest\n    /// (complex number).\n    ///\n    /// \\return the hierarchy level\n    hierarchy_t hierarchyLevel() const;\n\n    friend Number complexNumber(const Number& real, const Number& imag);\n    friend bool operator ==(const Number& self, const Number& other);\n    friend bool operator <(const Number& self, const Number& other);\n\n};\n\n/// Constructs a complex number from its real and imaginary parts. If\n/// either of the real or the imaginary parts is itself a non-real\n/// number, then the complex number is constructed using the formula\n/// `a + b i` where `a` is the first argument and `b` is the second,\n/// even if they are complex.\n///\n/// \\param real the real part\n/// \\param imag the imaginary part\n/// \\return the complex number\nNumber complexNumber(const Number& real, const Number& imag);\n\n/// Returns a floating point number representing NaN, if it exists.\n///\n/// \\return the value NaN\nboost::optional<Number> constantNan();\n\n/// Returns a floating point number representing positive infinity, if\n/// it exists.\n///\n/// \\return the value infinity\nboost::optional<Number> constantInf();\n\n/// Returns a floating point number representing negative infinity, if\n/// it exists.\n///\n/// \\return the value negative infinity\nboost::optional<Number> constantNegInf();\n\n/// Returns the smallest floating point number strictly greater than\n/// zero representable on the current system.\n///\n/// \\return the epsilon value\nNumber constantEps();\n\n/// Reads an integer. This function expects a string in the format\n/// used internally by the Latitude VM for radix literals. That is,\n/// the first character should be D, X, O, or B (case sensitive),\n/// respectively representing base 10, base 16, base 8, or base 2.\n/// This is optionally followed by a sign, either + or -, and then one\n/// or more digits.\n///\n/// \\param integer the text to parse\n/// \\return the number (an integer) or none\nboost::optional<Number> parseInteger(const char* integer);\n\n/// Returns whether the two numbers are the same. The comparison\n/// is done by coercing to the wider type.\n///\n/// \\param self the first number\n/// \\param other the other number\n/// \\return whether the values are equal\nbool operator ==(const Number& self, const Number& other);\n\n/// Returns whether the number is less than another number. The\n/// comparison is done by coercing to the wider type. Comparing\n/// complex numbers with this operator always returns false.\n///\n/// \\param self the first number\n/// \\param other the other number\n/// \\return whether the value is less than the argument\nbool operator <(const Number& self, const Number& other);\n\nbool operator >(const Number& self, const Number& other);\nbool operator <=(const Number& self, const Number& other);\nbool operator >=(const Number& self, const Number& other);\nbool operator !=(const Number& self, const Number& other);\n\nstd::ostream& operator <<(std::ostream& out, const Number& number);\n\n#endif // NUMBER_HPP\n", "meta": {"hexsha": "8f92fd2c1766e5e830a120d8e78ac7df6222ab72", "size": 11578, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Number.hpp", "max_stars_repo_name": "Mercerenies/latitude", "max_stars_repo_head_hexsha": "29b1697f1f615d52480197a52e20ff8c1872f07d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-02T18:19:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T23:33:32.000Z", "max_issues_repo_path": "src/Number.hpp", "max_issues_repo_name": "Mercerenies/latitude", "max_issues_repo_head_hexsha": "29b1697f1f615d52480197a52e20ff8c1872f07d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45.0, "max_issues_repo_issues_event_min_datetime": "2017-11-28T15:13:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T18:45:46.000Z", "max_forks_repo_path": "src/Number.hpp", "max_forks_repo_name": "Mercerenies/proto-lang", "max_forks_repo_head_hexsha": "29b1697f1f615d52480197a52e20ff8c1872f07d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6296296296, "max_line_length": 79, "alphanum_fraction": 0.6623769217, "num_tokens": 2635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5376964507134622}}
{"text": "#include \"ammannbeenker.h\"\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\nnamespace quacry{\nusing Vec2 = glm::vec2;\nusing namespace kipod::Shapes;\nusing Vec3 = glm::vec3;\nusing Vec4 = glm::vec4;\nusing Mat4 = glm::mat4;\n\nauto GetOrthogonalLine(const Vec2&a, const Vec2& b) -> Vec2\n{\n    Vec2 dir = b-a;\n    return {-dir.y, dir.x};\n}\n\nauto FindIntersection(const Vec2& a,const Vec2& b, const Vec2& x, const Vec2& y) -> Vec2\n{\n    using Line2 = Eigen::Hyperplane<float,2>;\n    auto ToEigen = [](Vec2 x){ return Eigen::Vector2f{x.x,x.y}; };\n    Line2 A = Line2::Through(ToEigen(a), ToEigen(b));\n    Line2 B = Line2::Through(ToEigen(x), ToEigen(y));\n    Eigen::Vector2f p = A.intersection(B);\n    LOG_INFO(\"Intersection found: {}\", p);\n    return {p[0],p[1]};\n}\n\nauto AvgPoint(const std::vector<Vec2>& vs) -> Vec2\n{\n    return std::accumulate(begin(vs),end(vs),Vec2(0))/float(size(vs));\n}\n\nauto Pattern1(float s) ->std::vector<Vec2>\n{   //      ____a   0\n    //          \\\n    //           \\b   7\n    //         i/ |\n    //          \\ |c  6\n    //           /\n    //     _____/d   5\n    auto o = Octagon(s);\n    auto a = o.GetVertex(0);\n    auto b = o.GetVertex(7);\n    auto c = o.GetVertex(6);\n    auto d = o.GetVertex(5);\n    auto i = FindIntersection(b, \n                              b+GetOrthogonalLine(b, a),\n                              c,\n                              c+GetOrthogonalLine(d,c)); \n    return {c,b,i};\n}\n\nauto Pattern2(float s) ->std::vector<Vec2>\n{\n    auto o = Octagon(s);\n    auto a = o.GetVertex(0);\n    auto b = o.GetVertex(7);\n    auto c = o.GetVertex(6);\n    auto d = o.GetVertex(5);\n    auto e = o.GetVertex(4);\n    auto f = o.GetVertex(3);\n    auto g = o.GetVertex(2);\n    auto h = o.GetVertex(1);\n    auto i = FindIntersection(a,d,b,g);\n    auto j = FindIntersection(a,d,c,h);\n    auto k = FindIntersection(c,h,b,e);\n    return {b,i,j,k};\n}\n\nauto Pattern3(float s) -> std::vector<Vec2>\n{\n    auto o = Octagon(s);\n\n    auto i = FindIntersection(o.GetVertex(6), o.GetVertex(1), o.GetVertex(7), o.GetVertex(4));\n    auto j = FindIntersection(o.GetVertex(0), o.GetVertex(5), o.GetVertex(6), o.GetVertex(1));\n    auto k = FindIntersection(o.GetVertex(0), o.GetVertex(5), o.GetVertex(7), o.GetVertex(4));\n    auto toflip = i-j; toflip.x *= -1;\n    auto jk = j+toflip;\n    return {i,j,jk,k};\n}\n\nauto Pattern4(float s) -> std::vector<Vec2>\n{\n    auto o = Octagon(s);\n\n    auto i = FindIntersection(o.GetVertex(6), o.GetVertex(1), o.GetVertex(7), o.GetVertex(4));\n    auto j = FindIntersection(o.GetVertex(0), o.GetVertex(5), o.GetVertex(6), o.GetVertex(1));\n    auto k = FindIntersection(o.GetVertex(0), o.GetVertex(5), o.GetVertex(7), o.GetVertex(4));\n    auto toflip = i-j; toflip.x *= -1;\n    auto jk = j+toflip;\n\n    \n    auto c = FindIntersection(j,j+Vec2(-1,0), o.GetVertex(7)+Vec2(-s,0), o.GetVertex(6)+Vec2(-s,0));\n    auto d = FindIntersection(jk,k, o.GetVertex(7)+Vec2(-s,0), o.GetVertex(6)+Vec2(-s,0));\n    return {jk, j, c, d};\n}\n\nauto Pattern5(float s) -> std::vector<Vec2>\n{\n    auto prev = Pattern4(s);\n    auto a = prev[0];\n    auto b = prev[3];\n    auto toflip = b-a; toflip.y *= -1;\n    auto c = a + toflip;\n    return {a,b,c};\n}\n\nauto Pattern6(float s) -> std::vector<Vec2>\n{\n    double lambda = -1.+std::sqrt(2.);\n    auto o = Octagon(s);\n    auto vs = o.transformed_vertices_;\n    for(auto& v : vs) v*= lambda*lambda;\n    return vs;\n}\n\nauto Rotate8(const Vec2& in) -> std::vector<Vec2>\n{\n    std::vector<Vec2> out;\n    auto theta = [](int i){ return \t3.1415926535897*2./i; };\n    for(int i = 0; i<8; ++i)\n        out.emplace_back(Mat2(cos(theta(i)),sin(theta(i)),-sin(theta(i)),cos(theta(i)))*in);\n    return out;\n}\n\nauto AmmannBeenker() -> Quasicrystal22 \n{\n    const float s = std::sqrt(2);\n\n    Basis4 basis = {1,0,s,0,\n                   1,2,0,s,\n                   1,0,-s,0,\n                   1,2,0,-s}; basis = glm::transpose(basis);\n\n    SampleSize sample_range = {-20,20,-20,20,-10,10,-10,10};\n    Quasicrystal22 AmmBee = {basis, Shape(Octagon(s)),\n                           \"Ammann Beenker\", sample_range};\n    auto vs = Pattern1(s); auto polygon1 = Polygon{vs,AvgPoint(vs)};\n    AmmBee.patterns_.emplace_back( std::make_unique<Window2>(Shape(polygon1)));\n    \n    auto vs2 = Pattern2(s); auto polygon2 = Polygon{vs2,AvgPoint(vs2)};\n    AmmBee.patterns_.emplace_back( std::make_unique<Window2>(Shape(polygon2)));\n\n    auto vs3 = Pattern3(s); auto polygon3 = Polygon{vs3,AvgPoint(vs3)};\n    AmmBee.patterns_.emplace_back( std::make_unique<Window2>(Shape(polygon3)));\n\n    auto vs4 = Pattern4(s); auto polygon4 = Polygon{vs4,AvgPoint(vs4)};\n    AmmBee.patterns_.emplace_back( std::make_unique<Window2>(Shape(polygon4)));\n    \n    auto vs5 = Pattern5(s); auto polygon5 = Polygon{vs5,AvgPoint(vs5)};\n    AmmBee.patterns_.emplace_back( std::make_unique<Window2>(Shape(polygon5)));\n\n    auto vs6 = Pattern6(s); auto polygon6 = Polygon{vs6,AvgPoint(vs6)};\n    AmmBee.patterns_.emplace_back( std::make_unique<Window2>(Shape(polygon6)));\n\n    for(auto& p : AmmBee.patterns_)\n        p->Init();\n    return AmmBee;\n}\n}\n", "meta": {"hexsha": "0f043335c27187ec0f66083ade9540166db40600", "size": 5063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/ammannbeenker.cpp", "max_stars_repo_name": "reneruhr/quacry", "max_stars_repo_head_hexsha": "cb2f3448b348a26dd8dec018285e7bf030b4e395", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/examples/ammannbeenker.cpp", "max_issues_repo_name": "reneruhr/quacry", "max_issues_repo_head_hexsha": "cb2f3448b348a26dd8dec018285e7bf030b4e395", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/ammannbeenker.cpp", "max_forks_repo_name": "reneruhr/quacry", "max_forks_repo_head_hexsha": "cb2f3448b348a26dd8dec018285e7bf030b4e395", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4472049689, "max_line_length": 100, "alphanum_fraction": 0.5952992297, "num_tokens": 1623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5376964491342008}}
{"text": "/* Copyright (c) 2017, 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\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <dpMM/basemeasure.hpp>\n#include <dpMM/vmfPriorAOne.hpp>\n\n/*\n * vmf base measure; uses closed form for marginal data density\n * (J. Straub, \"Nonparamatric Directional Perception\", 2017)\n */\ntemplate<typename T>\nclass vMFbase3D : public BaseMeasure<T>\n{\npublic:\n  vMFbase3D(const vMFprior<T>& vmfPrior);\n  vMFbase3D(const vMFbase3D<T>& vmf);\n  ~vMFbase3D();\n\n  virtual BaseMeasure<T>* copy();\n  virtual vMFbase3D<T>* copyNative();\n\n  T logLikelihood(const Matrix<T,Dynamic,1>& x) const;\n  T logLikelihood(const Matrix<T,Dynamic,Dynamic>& x, uint32_t i) const \n    {return logLikelihood(x.col(i));};\n  void posterior(const Matrix<T,Dynamic,Dynamic>& x, const VectorXu& z, \n    uint32_t k);\n  void posterior(const vector<Matrix<T,Dynamic,Dynamic> >&x, const VectorXu& z, \n    uint32_t k);\n  void sample();\n\n  T logPdfUnderPrior() const;\n  virtual T logPdfUnderPriorMarginalized() const;\n\n  virtual T logPdfUnderPriorMarginalized(const Matrix<T,Dynamic,1>& x);\n\n//  virtual NiwSampled<T>* merge(const NiwSampled<T>& other);\n//  void fromMerge(const NiwSampled<T>& niwA, const NiwSampled<T>& niwB);\n\n  void print() const;\n  virtual uint32_t getDim() const {return(uint32_t(vmf_.D_));}; \n\n//  const Matrix<T,Dynamic,Dynamic>& scatter() const {return niw0_.scatter();};\n//  const Matrix<T,Dynamic,1>& mean() const {return niw0_.mean();};\n//  T count() const {return niw0_.count();};\n////  T& count() {return niw0_.count_;};\n  const Matrix<T,Dynamic,1>& getMean() const {return vmf_.mu_;};\n  const T tau() const {return vmf_.tau();};\n\n  vMFprior<T> vmfPrior_;\n  vMF<T> vmf_;\nprivate:\n\n};\n\n// ------------------------- impl -------------------------------------------\n\ntemplate<typename T>\nvMFbase3D<T>::vMFbase3D(const vMFprior<T>& vmfPrior)\n  : vmfPrior_(vmfPrior), vmf_(vmfPrior_.sample())\n{};\n\ntemplate<typename T>\nvMFbase3D<T>::vMFbase3D(const vMFbase3D<T>& base)\n  :  vmfPrior_(base.vmfPrior_), vmf_(base.vmf_) \n{};\n\n\ntemplate<typename T>\nvMFbase3D<T>::~vMFbase3D()\n{};\n\ntemplate<typename T>\nBaseMeasure<T>* vMFbase3D<T>::copy()\n{\n  return new vMFbase3D<T>(*this);\n};\n\ntemplate<typename T>\nvMFbase3D<T>* vMFbase3D<T>::copyNative()\n{\n  return new vMFbase3D<T>(*this);\n};\n\ntemplate<typename T>\nT vMFbase3D<T>::logLikelihood(const Matrix<T,Dynamic,1>& x) const\n{\n//  cout<<vmf_.logPdf(x)<<endl;\n  return vmf_.logPdf(x);\n};\n\ntemplate<typename T>\nvoid vMFbase3D<T>::posterior(const Matrix<T,Dynamic,Dynamic>& x, const VectorXu& z, \n    uint32_t k)\n{ \n  vmfPrior_.getSufficientStatistics(x,z,k);\n  std::cout << vmfPrior_.xSum_.transpose() << \" \" << vmfPrior_.count_ << std::endl;\n  vmf_ = vmfPrior_.sampleFromPosterior();\n};\n\ntemplate<typename T>\nvoid vMFbase3D<T>::posterior(const vector<Matrix<T,Dynamic,Dynamic> >&x, const VectorXu& z, \n    uint32_t k)\n{\n};\n\ntemplate<typename T>\nvoid vMFbase3D<T>::sample()\n{\n  vmf_ = vmfPrior_.sample();\n};\n\ntemplate<typename T>\nvoid vMFbase3D<T>::print() const\n{\n  vmf_.print();\n};\n\ntemplate<typename T>\nT vMFbase3D<T>::logPdfUnderPrior() const\n{\n  return 0.;\n};\n\ntemplate<typename T>\nT vMFbase3D<T>::logPdfUnderPriorMarginalized() const\n{\n  return vmfPrior_.logPdfMarginalized();\n};\n\ntemplate<typename T>\nT vMFbase3D<T>::logPdfUnderPriorMarginalized(const Matrix<T,Dynamic,1>& x) \n{\n  return vmfPrior_.logMarginal(x);\n};\n\n", "meta": {"hexsha": "1d5fa815859a81e074bf27c81d04045c8bd98040", "size": 3492, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/vmfBaseMeasure3D.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/vmfBaseMeasure3D.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/vmfBaseMeasure3D.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": 24.5915492958, "max_line_length": 120, "alphanum_fraction": 0.6844215349, "num_tokens": 1090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640463, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5376964437725378}}
{"text": "#include \"KMC/integrals.hpp\"\n#include \"KMC/lookup_table.hpp\"\n#include \"catch.hpp\"\n\n#include <cmath>\n#include <cstdio>\n#include <iostream>\n#include <string>\n\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n\nconstexpr double ABSTOL = 1e-3;\nconstexpr double RELTOL = 1e-2;\n\nconstexpr double REVERSEFAC = 10;\n/**\n * EXPLAIN:\n * Reverse lookup on regions where the CDF is flat gives large error\n * But this is a rare event in simulations because this requires\n * the U01 rng to be very close to either 0 or 1\n * WARNING:\n * When spring is stiff and distPerp is large,\n * the reverse lookup error is very large\n * because function values are tiny and very flat.\n */\n\ninline double absError(double a, double b) { return fabs(a - b); }\n\ninline double relError(double a, double b) {\n    return b < 1e-8 ? absError(a, b) : fabs((a - b) / b);\n}\n\ninline bool errorPass(double a, double b, double fac = 1) {\n    return absError(a, b) < fac * ABSTOL || relError(a, b) < fac * RELTOL;\n}\n\nTEST_CASE(\"Lookup table test SOFT spring \", \"[lookup]\") {\n    constexpr double errTol = 1e-2;\n    LookupTable LUT;\n\n    const double D = 0.024;\n    const double alpha = 0.1 / (2 * 0.00411);\n    const double freelength = 0.05;\n    const double M = alpha * D * D;\n    const double ell0 = freelength / D;\n    LUT.Init(alpha, freelength, D);\n\n    double distPerp = 0;\n    distPerp = 0.2;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(relError(LUT.Lookup(distPerp, sbound * D),\n                       D * integral(distPerp / D, 0, sbound, M, ell0)) <\n              errTol);\n    }\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    distPerp = 0.1;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(relError(LUT.Lookup(distPerp, sbound * D),\n                       D * integral(distPerp / D, 0, sbound, M, ell0)) <\n              errTol);\n    }\n    // (\"distPerp = 0.06 < D+ell0, double peaked\")\n    distPerp = 0.06;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(relError(LUT.Lookup(distPerp, sbound * D),\n                       D * integral(distPerp / D, 0, sbound, M, ell0)) <\n              errTol);\n    }\n}\n\nTEST_CASE(\"Lookup table test MEDIUM spring \", \"[lookup]\") {\n    LookupTable LUT;\n\n    const double D = 0.024;\n    const double alpha = 1.0 / (2 * 0.00411);\n    const double freelength = 0.05;\n    const double M = alpha * D * D;\n    const double ell0 = freelength / D;\n    LUT.Init(alpha, freelength, D);\n\n    double distPerp = 0;\n    distPerp = 0.2;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(errorPass(LUT.Lookup(distPerp, sbound * D),\n                        D * integral(distPerp / D, 0, sbound, M, ell0)));\n    }\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    distPerp = 0.1;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(errorPass(LUT.Lookup(distPerp, sbound * D),\n                        D * integral(distPerp / D, 0, sbound, M, ell0)));\n    }\n    // (\"distPerp = 0.06 < D+ell0, double peaked\")\n    distPerp = 0.06;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(errorPass(LUT.Lookup(distPerp, sbound * D),\n                        D * integral(distPerp / D, 0, sbound, M, ell0)));\n    }\n}\n\nTEST_CASE(\"Lookup table test STIFF spring \", \"[lookup]\") {\n    LookupTable LUT;\n\n    const double D = 0.024;\n    const double alpha = 10.0 / (2 * 0.00411);\n    const double freelength = 0.05;\n    const double M = alpha * D * D;\n    const double ell0 = freelength / D;\n    LUT.Init(alpha, freelength, D);\n\n    double distPerp = 0;\n    distPerp = 0.2;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(errorPass(LUT.Lookup(distPerp, sbound * D),\n                        D * integral(distPerp / D, 0, sbound, M, ell0)));\n    }\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    distPerp = 0.1;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(errorPass(LUT.Lookup(distPerp, sbound * D),\n                        D * integral(distPerp / D, 0, sbound, M, ell0)));\n    }\n    // (\"distPerp = 0.06 < D+ell0, double peaked\")\n    distPerp = 0.06;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(errorPass(LUT.Lookup(distPerp, sbound * D),\n                        D * integral(distPerp / D, 0, sbound, M, ell0)));\n    }\n}\n\nTEST_CASE(\"Lookup table test manual medium spring REL error\", \"[lookup]\") {\n    // integrated by mathematica\n    LookupTable LUT;\n    const double D = 0.024;\n    constexpr double errTol = RELTOL;\n\n    double distPerp = 0;\n    LUT.Init(1.0 / (2 * 0.00411), 0.05, D);\n\n    distPerp = 0.2;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    CHECK(relError(LUT.Lookup(distPerp, 0.5 * D) / D, 0.0722077) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 1.0 * D) / D, 0.142839) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 1.5 * D) / D, 0.210412) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 2.0 * D) / D, 0.273623) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 3.0 * D) / D, 0.383039) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 4.0 * D) / D, 0.466375) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 5.0 * D) / D, 0.523889) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 6.0 * D) / D, 0.55967) < errTol);\n\n    distPerp = 0.08;\n    // \"distPerp = 0.08 > D+ell0, single peaked\"/D,\n    CHECK(relError(LUT.Lookup(distPerp, 0.5 * D) / D, 0.497588) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 1.0 * D) / D, 0.993608) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 1.5 * D) / D, 1.48554) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 2.0 * D) / D, 1.96929) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 3.0 * D) / D, 2.88784) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 4.0 * D) / D, 3.6925) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 5.0 * D) / D, 4.3332) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 6.0 * D) / D, 4.78986) < errTol);\n\n    distPerp = 0.06;\n    // \"distPerp = 0.06 < D+ell0, double peaked\"/D,\n    CHECK(relError(LUT.Lookup(distPerp, 0.5 * D) / D, 0.488864) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 1.0 * D) / D, 0.981139) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 1.5 * D) / D, 1.47815) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 2.0 * D) / D, 1.97788) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 3.0 * D) / D, 2.96052) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 4.0 * D) / D, 3.85857) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 5.0 * D) / D, 4.59864) < errTol);\n    CHECK(relError(LUT.Lookup(distPerp, 6.0 * D) / D, 5.14058) < errTol);\n}\n\nTEST_CASE(\"REVERSE Lookup table test manual medium spring REL error\",\n          \"[REVERSE lookup]\") {\n    // integrated by mathematica\n    LookupTable LUT;\n    const double D = 0.024;\n\n    double distPerp = 0;\n    LUT.Init(1.0 / (2 * 0.00411), 0.05, D);\n\n    double tol = RELTOL * REVERSEFAC;\n\n    distPerp = 0.1;\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    CHECK(relError(LUT.ReverseLookup(distPerp, D * 0) / D, 0.0) < tol);\n    CHECK(relError(LUT.ReverseLookup(distPerp, D * 0.0460519) / D, 0.05) < tol);\n    CHECK(relError(LUT.ReverseLookup(distPerp, D * 0.322128) / D, 0.35) < tol);\n    CHECK(relError(LUT.ReverseLookup(distPerp, D * 0.459824) / D, 0.5) < tol);\n    CHECK(relError(LUT.ReverseLookup(distPerp, D * 0.915356) / D, 1.0) < tol);\n    CHECK(relError(LUT.ReverseLookup(distPerp, D * 1.36196) / D, 1.5) < tol);\n    CHECK(relError(LUT.ReverseLookup(distPerp, D * 1.79446) / D, 2.0) < tol);\n    CHECK(relError(LUT.ReverseLookup(distPerp, D * 2.20718) / D, 2.5) < tol);\n    CHECK(relError(LUT.ReverseLookup(distPerp, D * 3.27015) / D, 4.0) < tol);\n    CHECK(relError(LUT.ReverseLookup(distPerp, D * 3.79115) / D, 5.0) < tol);\n    CHECK(relError(LUT.ReverseLookup(distPerp, D * 4.15242) / D, 6.0) < tol);\n    // CHECK(relError(LUT.ReverseLookup(distPerp / D, 4.37561), 7.0) < tol);\n}\n\nTEST_CASE(\"REVERSE Lookup table test soft spring \", \"[REVERSE lookup]\") {\n    LookupTable LUT;\n\n    const double D = 0.024;\n    const double alpha = 0.1 / (2 * 0.00411);\n    const double freelength = 0.05;\n    const double M = alpha * D * D;\n    const double ell0 = freelength / D;\n    LUT.Init(alpha, freelength, D);\n\n    double distPerp = 0;\n    distPerp = 0.2;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 3; sbound += 0.2) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n                        REVERSEFAC));\n    }\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    distPerp = 0.1;\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 3; sbound += 0.2) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n                        REVERSEFAC));\n    }\n    // (\"distPerp = 0.06 < D+ell0, double peaked\")\n    distPerp = 0.06;\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 3; sbound += 0.2) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n                        REVERSEFAC));\n    }\n}\n\nTEST_CASE(\"REVERSE Lookup table test medium spring \", \"[REVERSE lookup]\") {\n    LookupTable LUT;\n\n    const double D = 0.024;\n    const double alpha = 1.0 / (2 * 0.00411);\n    const double freelength = 0.05;\n    const double M = alpha * D * D;\n    const double ell0 = freelength / D;\n    LUT.Init(alpha, freelength, D);\n\n    double distPerp = 0;\n    distPerp = 0.2;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 4; sbound += 0.2) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n                        REVERSEFAC));\n    }\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    distPerp = 0.1;\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 3; sbound += 0.2) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n                        REVERSEFAC));\n    }\n    // (\"distPerp = 0.06 < D+ell0, double peaked\")\n    distPerp = 0.06;\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 3; sbound += 0.2) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n                        REVERSEFAC));\n    }\n}\n\nTEST_CASE(\"REVERSE Lookup table test stiff spring \", \"[REVERSE lookup]\") {\n    LookupTable LUT;\n\n    const double D = 0.024;\n    const double alpha = 10.0 / (2 * 0.00411);\n    const double freelength = 0.05;\n    const double M = alpha * D * D;\n    const double ell0 = freelength / D;\n    LUT.Init(alpha, freelength, D);\n\n    double distPerp = 0;\n    distPerp = 0.2;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    // WARNING: This reverse lookup fails\n    // for (double sbound = 0; sbound < 3; sbound += 0.1) {\n    //     double val = integral(distPerp / D, 0, sbound, M, ell0);\n    //     CHECK(errorPass(LUT.ReverseLookup(distPerp / D, val), sbound,\n    //                     REVERSEFAC));\n    // }\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    distPerp = 0.1;\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 4; sbound += 0.1) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n                        REVERSEFAC));\n    }\n    // (\"distPerp = 0.06 < D+ell0, double peaked\")\n    distPerp = 0.06;\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 4; sbound += 0.1) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n                        REVERSEFAC));\n    }\n}\n", "meta": {"hexsha": "afebead33d509bf3260226847bbec282d6e40373", "size": 12118, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/lookup_test.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": "tests/lookup_test.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": "tests/lookup_test.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": 39.6013071895, "max_line_length": 80, "alphanum_fraction": 0.5854926556, "num_tokens": 4249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5376775889278731}}
{"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 <opencv2/xfeatures2d.hpp>\n#include <opencv2/xfeatures2d/nonfree.hpp>\n#include <opencv2/opencv.hpp>\n\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 <Eigen/Core>\n\n#include <chrono>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <cmath>\n#include<math.h>   \nusing namespace std;\nusing namespace cv;\n//AVERAGE\ndouble Average(vector<double> v)\n{      double sum=0;\n       for(int i=0;i<v.size();i++)\n               sum+=v[i];\n       return sum/v.size();\n}\n//DEVIATION\ndouble Deviation(vector<double> v, double ave)\n{\n       double E=0;\n       for(int i=0;i<v.size();i++){\n               E+=(v[i] - ave)*(v[i] - ave);\n       }\n       return sqrt(E/v.size());\n}\nvoid writeResults( const string& filename, const vector<string>& timestamps, const vector<Mat>& Rt )\n{\n    CV_Assert( timestamps.size() == Rt.size() );\n\n    ofstream file( filename.c_str() );\n    if( !file.is_open() )\n        return;\n\n    cout.precision(4);\n    for( size_t i = 0; i < Rt.size(); i++ )\n    {\n        const Mat& Rt_curr = Rt[i];\n        if( Rt_curr.empty() )\n            continue;\n\n        CV_Assert( Rt_curr.type() == CV_64FC1 );\n\n        Mat R = Rt_curr(Rect(0,0,3,3)), rvec;\n        Rodrigues(R, rvec);\n        double alpha = norm( rvec );\n        if(alpha > DBL_MIN)\n            rvec = rvec / alpha;\n\n        double cos_alpha2 = std::cos(0.5 * alpha);\n        double sin_alpha2 = std::sin(0.5 * alpha);\n\n        rvec *= sin_alpha2;\n\n        CV_Assert( rvec.type() == CV_64FC1 );\n        // timestamp tx ty tz qx qy qz qw\n        file << timestamps[i] << \" \" << fixed\n             << Rt_curr.at<double>(0,3) << \" \" << Rt_curr.at<double>(1,3) << \" \" << Rt_curr.at<double>(2,3) << \" \"\n             << rvec.at<double>(0) << \" \" << rvec.at<double>(1) << \" \" << rvec.at<double>(2) << \" \" << cos_alpha2 << endl;\n\n    }\n    file.close();\n}\n\nvoid find_feature_matches(\n const Mat &img_1, const Mat &img_2, std::vector<KeyPoint> &keypoints_1,vector<KeyPoint> &keypoints_2,std::vector<DMatch> &matches, const Mat &img_3);\n void find_feature_matches_another(\n const Mat &img_1, const Mat &img_2, std::vector<KeyPoint> &keypoints_1,vector<KeyPoint> &keypoints_2,std::vector<DMatch> &matches, const Mat &img_3);\n\n// // \u50cf\u7d20\u5750\u6807\u8f6c\u76f8\u673a\u5f52\u4e00\u5316\u5750\u6807\n Point2d 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\nMat bundleAdjustmentG2O(\n  const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose,\n  const string& filename, \n  const vector<string>& timestamps\n);\n\n// BA by gauss-newton\nMat bundleAdjustmentGaussNewton(\n  const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose,\n  int mode\n);\ndouble calc_residual(\n   const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  Sophus::SE3d &pose,\n  const Mat &K,\n  vector<double>& residuals\n);\nint main(int argc, char **argv) {\n\tif(argc != 4){\n        cout << \"Format: file_with_rgb_depth_pairs trajectory_file odometry_name [Rgbd or ICP or RgbdICP or FastICP]\" << endl;\n        return -1;\n   }\n\n   vector<string> timestamps;\n   vector<Mat> Rts, Rts_ba;\n   Rts.push_back(Mat::eye(4,4,CV_64FC1));\n   Rts_ba.push_back(Mat::eye(4,4,CV_64FC1));\n   const string filename = argv[1];\n   ifstream file( filename.c_str() );\n   if( !file.is_open() )\n      return -1;\n   char dlmrt = '/';\n   size_t pos = filename.rfind(dlmrt);\n   string dirname = pos == string::npos ? \"\" : filename.substr(0, pos) + dlmrt;\n\n   const int timestampLength = 17;\n   const int rgbPathLehgth = 17+8;\n   const int depthPathLehgth = 17+10;\n\n   float fx = 517.3f, // default\n         fy = 516.5f,\n         cx = 318.6f,\n         cy = 255.3f;\n   // string value;\n   // string inFileStr;\n   // string myArray[10000];\n   // int j = 0;\n\n   // int arrSize = sizeof(myArray)/sizeof(myArray[0]);\n   // cout << arrSize << endl;\n\n   // cout << \"first \" << myArray[0] << endl;\n\n   string datas[793];\n   string str1;\n   std::getline(file, str1);\n\tdatas[0] = str1;\n   string timestap3 = str1.substr(0, timestampLength);\n   timestamps.push_back(timestap3);\n   for(int i = 1; !file.eof(); i++)\n   {\n      string str;\n      std::getline(file, str);\n      datas[i] = str;\n      if(str.empty()) break;\n      if(str.at(0) == '#') continue; /* comment */\n      cout << \" previous image: \" << datas[i-1] << \"\\n\" << \" current image \"<< str << endl;\n      Mat image, depth, image1, depth1, image2, depth2;\n      if(i > 2) {\n         string rgbFilename2 = datas[i-2].substr(timestampLength + 1, rgbPathLehgth );\n         string timestap2 = datas[i-2].substr(0, timestampLength);\n         string depthFilename2 = datas[i-2].substr(2*timestampLength + rgbPathLehgth + 3, depthPathLehgth );\n\n         image2 = imread(dirname + rgbFilename2);\n         depth2 = imread(dirname + depthFilename2, -1);\n      }\n      \n\t   string rgbFilename1 = datas[i-1].substr(timestampLength + 1, rgbPathLehgth );\n      string timestap1 = datas[i-1].substr(0, timestampLength);\n      string depthFilename1 = datas[i-1].substr(2*timestampLength + rgbPathLehgth + 3, depthPathLehgth );\n      image1 = imread(dirname + rgbFilename1);\n      depth1 = imread(dirname + depthFilename1, -1);\n\n\t   string rgbFilename = str.substr(timestampLength + 1, rgbPathLehgth );\n      string timestap = str.substr(0, timestampLength);\n      string depthFilename = str.substr(2*timestampLength + rgbPathLehgth + 3, depthPathLehgth );\n      image = imread(dirname + rgbFilename);\n      depth = imread(dirname + depthFilename, -1);\n      // cout << \"height \" << image.rows << \" width \" << image.cols << endl; // 480 * 640\n      // cout << \"prev prev \" << datas[i-2] << \" previous image: \" << datas[i-1] << \" current image \"<< str << endl;\n      CV_Assert(!image.empty());\n      CV_Assert(!depth.empty());\n      CV_Assert(!image1.empty());\n      CV_Assert(!depth1.empty());\n      CV_Assert(depth.type() == CV_16UC1);\n      CV_Assert(depth1.type() == CV_16UC1);\n\n      if(i > 2){\n         CV_Assert(!image2.empty());\n         CV_Assert(!depth2.empty()); \n         CV_Assert(depth2.type() == CV_16UC1);\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      std::vector<KeyPoint> keypoints_1, keypoints_2, key1, key2;\n      vector<DMatch> matches;\n      Ptr<FeatureDetector> detector = ORB::create();\n      detector->detect(image1, key1);\n      detector->detect(image, key2);\n      // if(key1.size() == 0 || key2.size() == 0){\n      //    find_feature_matches_another(image1, image, keypoints_1, keypoints_2, matches, image2);\n      //    cout << \"\u7b2c\u4e8c\u500b: \" <<  \"\u4e00\u5171\u627e\u5230\u4e86\" << matches.size() << \"\u7ec4\u5339\u914d\u70b9\" << endl;\n      // }\n      // else{\n         find_feature_matches(image1, image, keypoints_1, keypoints_2, matches, image2);\n         // find_feature_matches(image1, image, keypoints_1, keypoints_2, matches, image2);\n         cout << \"\u7b2c\u4e00\u500b: \" <<\"\u4e00\u5171\u627e\u5230\u4e86\" << matches.size() << \"\u7ec4\u5339\u914d\u70b9\" << endl;\n      // }\n      \n      // \u5efa\u7acb3D\u70b9\n      //Mat d1 = imread(depth1, IMREAD_UNCHANGED);       // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n      Mat K = (Mat_<double>(3, 3) << 517.3f, 0, 318.6f, 0, 516.5f, 255.3f, 0, 0, 1);\n      vector<Point3f> pts_3d;\n      vector<Point2f> pts_2d;\n      std::vector<KeyPoint> keys1, keys2;\n      std::vector<cv::Point2f> points1, points2;\n      int index = 1;\n      for (DMatch m:matches) {\n         // if (index <keypoints_2.size()){\n            ushort d = depth1.ptr<unsigned short>(int(keypoints_1[m.queryIdx].pt.y))[int(keypoints_1[m.queryIdx].pt.x)];\n            // cout << \"depth \" << d << endl;\n            if (d == 0){   // bad depth\n               continue;\n               // d = 1;\n            }\n            // cout << \"this is matches: \" <<  index << endl;\n            float dd = d / 5000.0;\n            \n            // cout << \"keypoints_1[m.queryIdx].pt \" << keypoints_1[m.queryIdx].pt << \" keypoints_2[m.trainIdx].pt \" << keypoints_2[m.trainIdx].pt << \" depth \" << d << endl;\n            Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n            keys1.push_back(keypoints_1[m.queryIdx]);\n            keys2.push_back(keypoints_2[m.trainIdx]);\n            points1.push_back(keypoints_1[m.queryIdx].pt);\n            points2.push_back(keypoints_2[m.trainIdx].pt);\n            // cout << \"p1.x \" << p1.x << \" p1.y \" << p1.y << \" depth \" << dd << endl;\n            \n            pts_3d.push_back(Point3f(p1.x * dd, p1.y * dd, dd));\n            pts_2d.push_back(keypoints_2[m.trainIdx].pt);\n            index += 1;\n         // }\n      }\n      bool b = false;\n      // if(i ==373) {b = true;}\n      cout << \"3d-2d pairs: \" << pts_3d.size() << \" \" << pts_2d.size() << \" \"  << i <<  endl;\n      keypoints_1.clear();\n      keypoints_1 = keys1;\n      keypoints_2.clear();\n      keypoints_2 = keys2;\n      chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n      Mat r, t, inliers;\n      solvePnPRansac(pts_3d, pts_2d, K, Mat(), r, t, b, 1000, 6.0, 0.99, inliers, SOLVEPNP_ITERATIVE);\n      // cout << inliers << inliers.size()  << inliers.at<int>(1,0)  << inliers.at<int>(3,0)<< endl;\n      for (int i=0; i<inliers.rows; i++){\n         cout << \"inliers -> keypoints_1: \" << keypoints_1[inliers.at<int>(i,0)].pt << \"inliers -> keypoints_2: \" << keypoints_2[inliers.at<int>(i,0)].pt << endl;\n      }\n      // cout << \"inliers \"<< inliers << endl;\n      cout<<\"pnp OK = \"<<b<<\", inliers point num = \"<<inliers.rows<<endl;\n      vector<Scalar> colors;\n      RNG rng;\n      for(int j = 0; j < 100; j++){\n         int r = rng.uniform(0, 256);\n         int g = rng.uniform(0, 256);\n         int b = rng.uniform(0, 256);\n         colors.push_back(Scalar(r,g,b));\n      }\n      for(int j=0; j<inliers.rows; j++){\n         circle(image1, keys1[inliers.at<int>(j,0)].pt, 5, colors[j], -1);\n         circle(image, keys2[inliers.at<int>(j,0)].pt, 5, colors[j], -1);\n      }\n      \n      Mat combined_img;\n      hconcat(image1,image,combined_img);\n      imwrite(\"./images/\" + to_string(i) + \".jpg\", combined_img);\n      // imwrite(\"./images/\" + to_string(i) + \".jpg\", image);\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      cout << \"R=\" << endl << R << endl;\n      cout << \"t=\" << endl << t << endl;\n      timestamps.push_back( timestap );\n      Mat output;\n      hconcat(R, t, output);\n   \n      Mat Rt = Mat::eye(4,4,CV_64FC1);\n      Rt.at<double>(0,0) = R.at<double>(0,0);\n      Rt.at<double>(0,1) = R.at<double>(0,1);\n      Rt.at<double>(0,2) = R.at<double>(0,2);\n      Rt.at<double>(1,0) = R.at<double>(1,0);\n      Rt.at<double>(1,1) = R.at<double>(1,1);\n      Rt.at<double>(1,2) = R.at<double>(1,2);\n      Rt.at<double>(2,0) = R.at<double>(2,0);\n      Rt.at<double>(2,1) = R.at<double>(2,1);\n      Rt.at<double>(2,2) = R.at<double>(2,2);\n      Rt.at<double>(0,3) = t.at<double>(0,0);\n      Rt.at<double>(1,3) = t.at<double>(0,1);\n      Rt.at<double>(2,3) = t.at<double>(0,2);\n      \n      \n      Mat& prevRt = *Rts.rbegin();\n      cout << \"prevRt \" << prevRt << endl;\n      cout << \"Rt \" << Rt << endl; \n      \n      // for (int l=0; l<2; l++){\n      //    cout << pts_3d[l].x << endl;\n      // }\n      // for (int i=0; i<inliers.rows; i++){\n      //    cout << \"inliers -> keypoints_1: \" << keypoints_1[inliers.at<int>(i,0)].pt << \"inliers -> keypoints_2: \" << keypoints_2[inliers.at<int>(i,0)].pt << endl;\n      // }\n      for (int i=0; i<inliers.rows; i++){\n         Mat m( 4,1, CV_64FC1);\n         m.at<double>(0,0) = keypoints_1[inliers.at<int>(i,0)].pt.x;\n         m.at<double>(1,0) = keypoints_1[inliers.at<int>(i,0)].pt.y;\n         m.at<double>(2,0) = pts_3d[i].z;\n         m.at<double>(3,0) = 1;\n         // cout << \"original \" << m.t() << \" projected \" << (prevRt * Rt * m).t() << \"  \" << \"actual \" << keypoints_2[inliers.at<int>(i,0)].pt<< endl;\n      }\n      Rts.push_back(prevRt * Rt);\n      Mat Rt_ba;\n      VecVector3d pts_3d_eigen;\n      VecVector2d pts_2d_eigen;\n      for (size_t i = 0; i < pts_3d.size(); ++i) {\n         // cout << \"vector3d \" << Eigen::Vector3d(pts_3d[i].x, pts_3d[i].y, pts_3d[i].z) << \"vector2d \" << Eigen::Vector2d(pts_2d[i].x, pts_2d[i].y) << endl;\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      // for (size_t i = 0; i < pts_3d.size(); ++i) {\n      //    for (size_t j = 0; j < 3; ++j) {\n      //       cout << \" eigen3d \" << pts_3d_eigen[i][j] << cout << \" eigen2d \"  <<*pts_2d_eigen[i][j];\n      //    }\n      // }\n      // cout << \"calling bundle adjustment by g2o\" << endl;\n      // Sophus::SE3d pose_g2o;\n      // t1 = chrono::steady_clock::now();\n      // Rt_ba = bundleAdjustmentG2O(pts_3d_eigen, pts_2d_eigen, K, pose_g2o, argv[2], timestamps);\n      // Mat& prevRtba = *Rts_ba.rbegin();\n      // Rts_ba.push_back(prevRtba * Rt_ba);\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     cout << \"calling bundle adjustment by gauss newton\" << endl;\n     Sophus::SE3d pose_gn;\n     t1 = chrono::steady_clock::now();\n     int mode = 0; // 0=huber\n     Mat Rt_baGauss = bundleAdjustmentGaussNewton(pts_3d_eigen, pts_2d_eigen, K, pose_gn, mode);\n      Mat& prevRtbaGauss = *Rts_ba.rbegin();\n      cout << \"prevRt \" << prevRtbaGauss << endl;\n      cout << \"Rt \" << RtGauss << endl; \n      Rts_ba.push_back(prevRtbaGauss * Rt_baGauss);\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      \n   }\n   // writeResults(argv[2], timestamps, Rts);\n   writeResults(argv[2], timestamps, Rts_ba);\n   \n  return 0;\n}\nvoid find_feature_matches_another(const Mat &img_1, const Mat &img_2,\n                           std::vector<KeyPoint> &keypoints_1,\n\t\t\t                  std::vector<KeyPoint> &keypoints_2,\n                           std::vector<DMatch> &matches,\n                           const Mat &img_3) {\n   Mat descriptors_1, descriptors_2, descriptors_3, descriptors_4;\n   Ptr<FeatureDetector> detector = AgastFeatureDetector::create();\n   Ptr<DescriptorExtractor> descriptor = AgastFeatureDetector::create();\n   Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n   detector->detect(img_1, keypoints_1);\n   detector->detect(img_2, keypoints_2);\n   cout << \"keypoints_1.size() \"<< keypoints_1.size() << \" keypoints_2.size() \" << keypoints_2.size() << endl;\n   // if(keypoints_1.size() != 0 && keypoints_2.size() != 0){\n      for (int i=0; i< keypoints_1.size(); i++){\n         // cout << \"keypoint1 \" << keypoints_1[i].pt << \"keypoint2 \" << keypoints_2[i].pt << endl;\n      }\n      descriptor->compute(img_1, keypoints_1, descriptors_1);\n      descriptor->compute(img_2, keypoints_2, descriptors_2);\n   // }\n   int eee = descriptors_1.empty();\n   int ddd = descriptors_2.empty();\n\n   vector<DMatch> match;\n   // Mat de1, de2;\n   // if(ddd == true || eee == true){\n   //    de1 = descriptors_3;\n   //    de2 = descriptors_4;\n   // }else {\n   //    de1 = descriptors_1;\n   //    de2 = descriptors_2;\n   // }\n   // matcher->match(de1, de2, match);\n   matcher->match(descriptors_1, descriptors_2, match);\n   double min_dist = 10000, max_dist = 0;\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   printf(\"-- Max dist : %f \\n\", max_dist);\n   printf(\"-- Min dist : %f \\n\", min_dist);\n   for (int i = 0; i < descriptors_1.rows; i++) {\n    if (match[i].distance <= max(2 * min_dist, 10.0)) {\n       matches.push_back(match[i]);\n     }\n   }\n }\n void find_feature_matches(const Mat &img_1, const Mat &img_2,\n                           std::vector<KeyPoint> &keypoints_1,\n\t\t\t                  std::vector<KeyPoint> &keypoints_2,\n                           std::vector<DMatch> &matches,\n                           const Mat &img_3) {\n\n   Mat descriptors_1, descriptors_2, descriptors_3, descriptors_4;\n   Ptr<FeatureDetector> detector = ORB::create();\n   Ptr<DescriptorExtractor> descriptor = ORB::create();\n   // Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n   Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(\"FlannBased\");\n   // cv::FlannBasedMatcher matcher = cv::FlannBasedMatcher(cv::makePtr<cv::flann::LshIndexParams>(12, 20, 2));\n   detector->detect(img_1, keypoints_1);\n   detector->detect(img_2, keypoints_2);\n   cout << \"keypoints_1.size() \"<< keypoints_1.size() << \" keypoints_2.size() \" << keypoints_2.size() << endl;\n   // if(keypoints_1.size() != 0 && keypoints_2.size() != 0){\n      \n      descriptor->compute(img_1, keypoints_1, descriptors_1);\n      descriptor->compute(img_2, keypoints_2, descriptors_2);\n   // }\n   // cout << \"des1 \" << descriptors_1  << \"des2 \" << descriptors_2 << endl;\n   int eee = descriptors_1.empty();\n   int ddd = descriptors_2.empty();\n   // for (int i=0; i< keypoints_1.size(); i++){\n   //    cout << \"keypoint1 \" << keypoints_1[i].pt << \"keypoint2 \" << keypoints_2[i].pt << endl;\n   // }\n   // cout << \"ddd \" << ddd << \" eee \" << eee << endl;\n   // if(ddd == true || eee == true){\n   //    keypoints_1.clear();\n   //    keypoints_2.clear();\n   //    detector->detect( img_3, keypoints_1 );\n   //    detector->detect( img_2, keypoints_2 );\n   //    cout << \"keypoints_3.size() \"<< keypoints_1.size() << \" keypoints_3.size() \" << keypoints_2.size() << endl;\n   //    for (int i=0; i< keypoints_1.size(); i++){\n   //       cout << \"keypoint3 \" << keypoints_1[i].pt << \"keypoint4 \" << keypoints_2[i].pt << endl;\n   //    }    \n   //    descriptor->compute( img_3, keypoints_1, descriptors_3 );\n   //    descriptor->compute( img_2, keypoints_2, descriptors_4 );\n   //    cout << \"des3 \" << descriptors_3  << \"des4 \" << descriptors_4 << endl;\n\n   // }\n   vector<DMatch> match;\n   // BFMatcher matcher ( NORM_HAMMING );\n   // Mat de1, de2;\n   \n   // if(ddd == true || eee == true){\n   //    de1 = descriptors_3;\n   //    de2 = descriptors_4;\n   // }else {\n   //    de1 = descriptors_1;\n   //    de2 = descriptors_2;\n   // }\n   // matcher->match(de1, de2, match);\n\n   // matcher->match(descriptors_1, descriptors_2, match);\n   vector<vector<DMatch>> knn_matches; \n   descriptors_1.convertTo(descriptors_1, CV_32F);\n   descriptors_2.convertTo(descriptors_2, CV_32F);\n   matcher->knnMatch( descriptors_1, descriptors_2, knn_matches, 2);\n   // descriptors_1.convertTo(descriptors_1, CV_8UC1);\n   // descriptors_2.convertTo(descriptors_2, CV_8UC1);\n   // matcher.knnMatch( descriptors_1, descriptors_2, knn_matches, 2);\n   // for (size_t k = 0; k < knn_matches.size(); k++)\n   //  {\n   //      for (size_t i = 0; i < knn_matches[k].size(); i++)\n   //      {\n   //          // const cv::DMatch& match = knn_matches[k][i];\n   //          cout << knn_matches[i][k].trainIdx << \" \";\n   //      }\n   //      cout << endl;\n   //  }\n    const float ratio_thresh = 0.7f;\n   //  std::vector<DMatch> good_matches;\n    for (size_t i = 0; i < knn_matches.size(); i++)\n    {\n        if (knn_matches[i][0].distance < ratio_thresh * knn_matches[i][1].distance)\n        {\n            matches.push_back(knn_matches[i][0]);\n        }\n    }\n   // double min_dist = 10000, max_dist = 0;\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   // cout << match.size() << endl;\n   // printf(\"-- Max dist : %f \\n\", max_dist);\n   // printf(\"-- Min dist : %f \\n\", min_dist);\n   // for (int i = 0; i < match.size(); i++) {\n   //  if (match[i].distance <= max(2 * min_dist, 10.0)) {\n   //    // if (matches[i].distance < 2 * min_dist) {\n   //       matches.push_back(match[i]);\n   //   }\n   // }\n   \n }\n\n Point2d 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 }\ndouble calc_residual(\n   const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  Sophus::SE3d &pose,\n  const Mat &K,\n  vector<double>& residuals\n){\ndouble 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  vector<double> res_std;\n  for (int i=0; i<points_3d.size(); i++){\n     Eigen::Vector3d pc = pose * points_3d[i];\n     Eigen::Vector2d proj(fx * pc[0] / pc[2] + cx, fy * pc[1] / pc[2] + cy);\n     Eigen::Vector2d error = points_2d[i] - proj;\n     residuals.push_back(error.squaredNorm());\n      if (isnan(pc[2]) == false) {\n         res_std.push_back(error.squaredNorm());\n      }\n  }\n  double avg = Average(res_std); \n  double std = Deviation(res_std,avg);\n  return std;\n}\nMat bundleAdjustmentGaussNewton(\n  const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose,\n  int mode) {\n  typedef Eigen::Matrix<double, 6, 1> Vector6d;\n  const int iterations = 100;\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   vector<double> residuals;\n   double res_std = calc_residual(points_3d, points_2d, pose, K, residuals);\n   // for(int i=0; i < residuals.size(); i++) {\n   //    cout << residuals.at(i) << endl;\n   // }\n   cout << \"deviation: \" << res_std << endl;\n   double huber_k = 1.345 * res_std;\n   vector<double> weight;\n   if(mode == 0){\n      for (int j=0; j<residuals.size(); j++){\n         if(residuals[j] <= huber_k){\n            weight.push_back(1.0);\n         }else {\n            weight.push_back(huber_k/residuals[j]);\n         }\n      }\n   }else {\n      for (int j=0; j<residuals.size(); j++){\n         weight.push_back(0.0);\n      }\n   }\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 * weight[i]);\n      b += -J.transpose() * (e * weight[i]);\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   Mat Rt = Mat::eye(4,4,CV_64FC1);\n      Rt.at<double>(0,0) = pose.matrix()(0);\n      Rt.at<double>(1,0) = pose.matrix()(1);\n      Rt.at<double>(2,0) = pose.matrix()(2);\n      Rt.at<double>(3,0) = pose.matrix()(3);\n      Rt.at<double>(0,1) = pose.matrix()(4);\n      Rt.at<double>(1,1) = pose.matrix()(5);\n      Rt.at<double>(2,1) = pose.matrix()(6);\n      Rt.at<double>(3,1) = pose.matrix()(7);\n      Rt.at<double>(0,2) = pose.matrix()(8);\n      Rt.at<double>(1,2) = pose.matrix()(9);\n      Rt.at<double>(2,2) = pose.matrix()(10);\n      Rt.at<double>(3,2) = pose.matrix()(11);\n      Rt.at<double>(0,3) = pose.matrix()(12);\n      Rt.at<double>(1,3) = pose.matrix()(13);\n      Rt.at<double>(2,3) = pose.matrix()(14);\n      Rt.at<double>(3,3) = pose.matrix()(15);\n\n      cout << \"pose by g-n: \\n\" << pose.matrix() << endl;\n\n      return Rt;\n}\n\n/// vertex and edges used in g2o ba\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   /// 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> {\n   public:\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\n   private:\n      Eigen::Vector3d _pos3d;\n      Eigen::Matrix3d _K;\n};\n\nMat bundleAdjustmentG2O(\n  const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose,\n  const string& filename, \n  const vector<string>& timestamps) {\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//   cout << \"pose matrix \"  << vertex_pose->estimate().matrix()(0) << vertex_pose->estimate().matrix()(1) << vertex_pose->estimate().matrix()(4) << endl;\n\n  Mat Rt = Mat::eye(4,4,CV_64FC1);\n  Rt.at<double>(0,0) = vertex_pose->estimate().matrix()(0);\n  Rt.at<double>(1,0) = vertex_pose->estimate().matrix()(1);\n  Rt.at<double>(2,0) = vertex_pose->estimate().matrix()(2);\n  Rt.at<double>(3,0) = vertex_pose->estimate().matrix()(3);\n  Rt.at<double>(0,1) = vertex_pose->estimate().matrix()(4);\n  Rt.at<double>(1,1) = vertex_pose->estimate().matrix()(5);\n  Rt.at<double>(2,1) = vertex_pose->estimate().matrix()(6);\n  Rt.at<double>(3,1) = vertex_pose->estimate().matrix()(7);\n  Rt.at<double>(0,2) = vertex_pose->estimate().matrix()(8);\n  Rt.at<double>(1,2) = vertex_pose->estimate().matrix()(9);\n  Rt.at<double>(2,2) = vertex_pose->estimate().matrix()(10);\n  Rt.at<double>(3,2) = vertex_pose->estimate().matrix()(11);\n  Rt.at<double>(0,3) = vertex_pose->estimate().matrix()(12);\n  Rt.at<double>(1,3) = vertex_pose->estimate().matrix()(13);\n  Rt.at<double>(2,3) = vertex_pose->estimate().matrix()(14);\n  Rt.at<double>(3,3) = vertex_pose->estimate().matrix()(15);\n\n  pose = vertex_pose->estimate();\n  return Rt;\n}\n\n", "meta": {"hexsha": "ca90865a09d476ed2333cf5ac7bcceb3d8e0fd91", "size": 30485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main_old.cpp", "max_stars_repo_name": "Peter52550/visual-odometry", "max_stars_repo_head_hexsha": "985a02b69ff8384a2b488500c7308f0e58385739", "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_old.cpp", "max_issues_repo_name": "Peter52550/visual-odometry", "max_issues_repo_head_hexsha": "985a02b69ff8384a2b488500c7308f0e58385739", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_old.cpp", "max_forks_repo_name": "Peter52550/visual-odometry", "max_forks_repo_head_hexsha": "985a02b69ff8384a2b488500c7308f0e58385739", "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.7757125155, "max_line_length": 173, "alphanum_fraction": 0.5832048548, "num_tokens": 9718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5376775889278731}}
{"text": "// Compute and store ridgelet coefficients in linearized form\n// Input: fsolution*h5 file(s) computed with bte_omp_ftcg executable\n\n#include <hdf5.h>\n#include <omp.h>\n#include <yaml-cpp/yaml.h>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n#include <cmath>\n#include <cstdio>\n#include <iostream>\n#include <memory>\n#include <regex>\n#include <stdexcept>\n#include <string>\n#include <tuple>\n\n#include \"base/eigen2hdf.hpp\"\n#include \"base/exceptions.hpp\"\n#include \"brt_config.h\"\n#include \"fft/fft2_r2c.hpp\"\n#include \"ridgelet/rc_linearize.hpp\"\n#include \"ridgelet/ridgelet_cell_array.hpp\"\n#include \"ridgelet/ridgelet_frame.hpp\"\n#include \"ridgelet/rt.hpp\"\n#include \"spectral/quadrature/qhermitew.hpp\"\n\ntypedef FFTr2c<PlannerR2C> fft_t;\n// typedef FFTr2c<PlannerR2COD> fft_t;\n\nunsigned int PLANNER_STRATEGY = FFTW_MEASURE;\n\ntypedef RT<double, RidgeletFrame, fft_t> RT_t;\ntypedef RT_t::rt_coeff_t rt_coeff_t;\ntypedef RidgeletCellArray<rt_coeff_t> rca_t;\n\nnamespace po = boost::program_options;\n\nstd::string out_fname = \"rt_coeffs.h5\";\n\nint get_frame(const std::string& fname)\n{\n  std::regex my_regex(\".*solution_vector([0-9]*)\");\n  std::smatch match;\n  bool found = std::regex_search(fname, match, my_regex);\n  if (found) {\n    return atoi(match[1].str().c_str());\n  } else {\n    throw std::runtime_error(\"could not find frame number\");\n  }\n}\n\nunsigned int get_ncoeffs(const RidgeletFrame& rf)\n{\n  unsigned int nc = 0;\n  for (auto& lam : rf.lambdas()) {\n    auto t = tgrid_dim(lam, rf);\n    unsigned int TX = std::get<0>(t) * std::get<1>(t);\n    nc += TX;\n  }\n  return nc;\n}\n\n\nbool is_power_of_two(int x)\n{\n  return (x>0) && !(x & (x-1));\n}\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"SOURCE::INFO::GIT_BRANCHNAME \" << GIT_BNAME << \"\\n\";\n  std::cout << \"SOURCE::INFO::GIT_SHA1       \" << GIT_SHA1 << \"\\n\";\n\n  // disable buffering of printf\n  std::setbuf(stdout, NULL);\n\n  po::options_description options(\"options\");\n  options.add_options()\n      (\"help\", \"produce help message\")\n      (\"dst\", po::value<std::string>(), \"write output to dst\");\n\n  po::variables_map vm;\n  try {\n    po::store(po::parse_command_line(argc, argv, options), vm);\n    po::notify(vm);\n  } catch (std::exception& e) {\n    if (vm.count(\"help\"))\n      std::cout << options << \"\\n\";\n    else\n      std::cout << e.what() << \"\\n\";\n    return 1;\n  }\n  if (vm.count(\"help\")) {\n    std::cout << options << \"\\n\";\n    return 0;\n  }\n\n  if (vm.count(\"dst\")) {\n    out_fname = vm[\"dst\"].as<std::string>();\n  }\n  std::cerr << \"writing output to \" << out_fname << std::endl;\n\n  typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> array_t;\n  // read input files from stdin and check if they exist\n  std::string input_line;\n  std::vector<std::string> fnames;\n  while (std::cin) {\n    std::getline(std::cin, input_line);\n    // check for empty (e.g. terminating line)\n    std::regex my_regex(\"^([[:space:]]*|)$\");\n    std::smatch my_match;\n    std::regex_search(input_line, my_match, my_regex);\n    // cout << \"match size: \" << my_match.size() << \"\\n\";\n    if (my_match.size() > 0) {\n      break;\n    } else {\n      if (boost::filesystem::is_regular_file(input_line) ||\n          boost::filesystem::is_symlink(input_line))\n        fnames.push_back(input_line);\n      else\n        throw std::runtime_error(\"File \" + input_line + \" does not exist. Exiting.\");\n    }\n  };\n\n  std::cout << \"Found \" << fnames.size() << \" input files\\n\";\n\n  // load files\n  std::shared_ptr<RidgeletFrame> rf_ptr;\n  std::shared_ptr<RCLinearize> rcl_ptr;\n\n  hid_t h5f_out = H5Fcreate(out_fname.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n\n  for (auto& fname : fnames) {\n    int frame = get_frame(fname);\n    array_t coeffs;\n    hid_t h5f = H5Fopen(fname.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);\n    eigen2hdf::load(h5f, \"C\", coeffs);\n    int N = coeffs.rows();\n    int L = coeffs.cols();\n    int K = std::sqrt(N);\n    ASSERT(K * K == N);\n    int Lx = std::sqrt(L);\n    std::cout << \"Lx: \" << Lx << \"\\n\";\n    ASSERT(Lx * Lx == L);\n    ASSERT(is_power_of_two(Lx));\n    H5Fclose(h5f);\n\n    if (!rf_ptr) {\n      int J = std::log2(2 * Lx) - 2;\n      std::cout << \"J: \"  << J << \"\\n\";\n      rf_ptr = std::make_shared<RidgeletFrame>(J, J, 1, 1);\n      rcl_ptr = std::make_shared<RCLinearize>(*rf_ptr);\n      fft_t fft;\n      init_fftw(fft, PLANNER_STRATEGY, *rf_ptr);\n    }\n    fft_t fft;\n    RT_t rt(*rf_ptr);\n\n    typedef RT_t::complex_array_t complex_array_t;\n\n    // store Ridgelet coefficients for each direction in the following array:\n    typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> out_array_t;\n\n    int ncoeffs = get_ncoeffs(*rf_ptr);\n    out_array_t RTCOEFFS(K * K, ncoeffs);\n\n#pragma omp parallel\n    {\n      complex_array_t Fhh(Lx, Lx);\n      complex_array_t Fh(2 * Lx, 2 * Lx);\n      rca_t f_rc(*rf_ptr);\n\n#pragma omp for schedule(dynamic) collapse(2)\n      for (int j1 = 0; j1 < K; j1++) {\n        for (int j2 = 0; j2 < K; j2++) {\n          // read F..\n          int idv = j2 * K + j1;\n          Eigen::Map<array_t> F(coeffs.data() + L * idv, Lx, Lx);\n          fft.ft(Fhh, F, false);\n          Fh.setZero();\n          ftcut(Fh, Lx, Lx) = Fhh;\n          hf_zero(Fh);\n          rt.rt(f_rc.coeffs(), Fh);\n\n          std::vector<double> rclin = rcl_ptr->linearize(f_rc.coeffs());\n\n          // valgrind complains about the following\n          // std::copy(rclin.begin(), rclin.end(), RTCOEFFS.row(idv).data());\n          Eigen::Map<Eigen::VectorXd> vrclin(rclin.data(), rclin.size());\n          RTCOEFFS.row(idv) = vrclin;\n        }  // end for j2\n      }    // end for j1\n    }      // end omp parallel\n\n    // save to hdf\n    eigen2hdf::save(h5f_out, std::to_string(frame), RTCOEFFS);\n\n  }  // end for files\n  H5Fclose(h5f_out);\n\n  return 0;\n}\n", "meta": {"hexsha": "55668129b73738afc55ee7d90c122e1b8782656e", "size": 5810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/post_processing/compute_rt.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": "applications/post_processing/compute_rt.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": "applications/post_processing/compute_rt.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": 28.2038834951, "max_line_length": 94, "alphanum_fraction": 0.6201376936, "num_tokens": 1757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5376775798899551}}
{"text": "#include <gnuplot-iostream/gnuplot-iostream.h>\n#include <boost/tuple/tuple.hpp>\n#include <utility>\n#include <vector>\n#include <string>\n#include \"Graph.hpp\"\n#include \"Planet.hpp\"\nusing namespace std;\n\n/*****************************************************************************\n\nGRAPHING PROGRAM! To graph both the system and the log-log plot\n\n*****************************************************************************/\n\nvoid graphSystem(vector<vec3D> paths[], int planets, int asts, int base, double scale, string fname){\n\tGnuplot gp;\n\n\tdouble sz = scale*149597870700; // Scale from au to meters\n\n\tgp << setprecision(3);\n\tgp << \"set xrange [\" << -sz << \":\" << sz << \"]\\n\";\n\tgp << \"set yrange [\" << -sz << \":\" << sz << \"]\\n\";\n\tgp << \"set zrange [\" << -sz << \":\" << sz << \"]\\n\";\n\tgp << \"set xlabel \\\"x\\\"\\n\";\n\tgp << \"set ylabel \\\"y\\\"\\n\";\n\tgp << \"set zlabel \\\"z\\\"\\n\";\n\tgp << \"set term png size 1920,1080 font \\\"FreeSerif,12\\\"\\n\";\n\tgp << \"set title \\\"ZOLAR ZYZDEM\\\"\\n\"; \n\tgp << \"set output \\\"\" << fname << \"\\\"\\n\";\n\tgp << \"set hidden3d\\n\";\n\tgp << \"set view 60, 60, 1, 1.5\\n\";\n\tgp << \"splot \";\n\n\tfor(int i = 0; i < planets+asts; i++){\t// Plot planets in black and asteroids in red\n\t\tgp << \"'-' with lines lc rgb \\\"\";\n\t\tif(i >= planets){\n\t\t\tgp << \"red\";\n\t\t} else {\n\t\t\tgp << \"black\";\n\t\t}\n\t\tgp << \"\\\" notitle, \";\n\t}\n\tgp << \"\\n\";\n\t\n\tfor(int i = 0; i < planets+asts; i++){\t\t\t// Data must be rearranged into vectors of doubles, removed from vec3D tuple\n\t\tvector<double> x;\n\t\tvector<double> y;\n\t\tvector<double> z;\n\n\t\tfor(int j = 0; j < paths[i].size(); j++){\n\t\t\tvec3D v = paths[i][j];\n\t\t\tx.push_back(v.x-paths[base][j].x);\t\t// Adjust coordinates to be centered around the base (the sun)\n\t\t\ty.push_back(v.y-paths[base][j].y);\n\t\t\tz.push_back(v.z-paths[base][j].z);\n\t\t}\n\n\t\tgp.send1d(boost::make_tuple(x,y,z));\n\t}\n}\n\nvoid graphLogLog(vector<double> lSMA, vector<double> lPeriod){\n\tGnuplot gp;\n\n\tauto line = getLeastSquares(lSMA,lPeriod);\t\t\t// Get the least squares parameters (slope, intercept) from the Calcs.cpp file\n\n\tgp << \"set xrange [20:35]\\n\";\n\tgp << \"set yrange [0:30]\\n\";\n\tgp << \"set xlabel \\\"log(SMA)\\\"\\n\";\n\tgp << \"set ylabel \\\"log(period)\\\"\\n\";\n\tgp << \"set term png size 720,480 font \\\"FreeSerif,12\\\"\\n\";\n\tgp << \"set title \\\"Log-Log plot of Semi-Major Axis vs. Period\\\"\\n\";\n\tgp << \"set output \\\"ll.png\\\"\\n\";\n\tgp << \"f(x) = \" << line.first << \"*x + \" << line.second << \"\\n\"; // Defines a function for gnuplot to evaluate\n\tgp << \"plot '-' with lines lc rgb \\\"black\\\" notitle, f(x) with lines title 'Trendline y = \" << line.first << \"*x + \" << line.second << \"'\\n\";\n\tgp.send1d(boost::make_tuple(lSMA,lPeriod));\n}", "meta": {"hexsha": "e83c46392cd926f3d0c0874e377a4f2a3649fdff", "size": 2607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Planets/Graph.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": "Planets/Graph.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": "Planets/Graph.cpp", "max_forks_repo_name": "GEslinger/PhysClass", "max_forks_repo_head_hexsha": "5e34167c34ca0e8779e4002063d95ffa24a24c9d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8571428571, "max_line_length": 142, "alphanum_fraction": 0.5581127733, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5376775681456283}}
{"text": "// Copyright 2021 Yu-Kai Lin. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n#pragma once\n\n#include \"kcp/common.hpp\"\n\n#include <Eigen/Core>\n\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <map>\n#include <memory>\n#include <stdexcept>\n#include <vector>\n\n#define deg2red(deg) ((deg)*M_PI / 180)\n#define red2deg(red) ((red)*180 / M_PI)\n\n#define MAX(A, B) ((A) > (B) ? A : B)\n#define MIN(A, B) ((A) < (B) ? A : B)\n\n#define l2Norm2D(x, y) sqrt(pow(x, 2) + pow(y, 2))\n#define l2Norm3D(x, y, z) sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2))\n#define _GET_L2NORM_MACRO(_1, _2, _3, NAME, ...) NAME\n#define l2Norm(...)                                  \\\n  _GET_L2NORM_MACRO(__VA_ARGS__, l2Norm3D, l2Norm2D) \\\n  (__VA_ARGS__)\n\n#define CYCLIC_INDEX(i, start, end) ((i < start) ? (end - (start - (i))) : ((i > end) ? start + (i - (end)) : i))\n\nnamespace kcp {\n\n/**\n * @brief Get the set of k-closest-points correspondences with kd-tree.\n * \n * @param src The source point cloud.\n * @param dst The target point cloud.\n * @param src_feature The source feature cloud used to compute distances.\n * @param dst_feature The target feature cloud used to compute distances.\n * @param k The number of closest points for each source point.\n * @return Shared pointer to the set of correspondences.\n */\nstd::shared_ptr<Correspondences>\nget_kcp_correspondences(const Eigen::MatrixX3d& src,\n                        const Eigen::MatrixX3d& dst,\n                        const Eigen::MatrixXd& src_feature,\n                        const Eigen::MatrixXd& dst_feature,\n                        size_t k);\n\n};  // namespace kcp\n", "meta": {"hexsha": "b7745681fc98280e563d12b6144b507920366027", "size": 1669, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kcp/include/kcp/utility.hpp", "max_stars_repo_name": "StephLin/KCP", "max_stars_repo_head_hexsha": "9776a2bc66974fa6c596579a3c56e46b1bf1ead1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2021-12-22T06:02:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:48:47.000Z", "max_issues_repo_path": "kcp/include/kcp/utility.hpp", "max_issues_repo_name": "StephLin/KCP", "max_issues_repo_head_hexsha": "9776a2bc66974fa6c596579a3c56e46b1bf1ead1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-02-23T09:34:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T04:38:42.000Z", "max_forks_repo_path": "kcp/include/kcp/utility.hpp", "max_forks_repo_name": "StephLin/KCP", "max_forks_repo_head_hexsha": "9776a2bc66974fa6c596579a3c56e46b1bf1ead1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2022-01-08T05:51:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T07:18:48.000Z", "avg_line_length": 31.4905660377, "max_line_length": 113, "alphanum_fraction": 0.6339125225, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5376775681456283}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Surface_mesh.h>\n\n#include <CGAL/Polygon_mesh_processing/connected_components.h>\n#include <CGAL/Polygon_mesh_processing/IO/polygon_mesh_io.h>\n\n#include <boost/iterator/function_output_iterator.hpp>\n#include <boost/property_map/property_map.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <map>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::Point_3                                     Point;\ntypedef Kernel::Compare_dihedral_angle_3                    Compare_dihedral_angle_3;\n\ntypedef CGAL::Surface_mesh<Point>                           Mesh;\n\nnamespace PMP = CGAL::Polygon_mesh_processing;\n\ntemplate <typename G>\nstruct Constraint : public boost::put_get_helper<bool,Constraint<G> >\n{\n  typedef typename boost::graph_traits<G>::edge_descriptor edge_descriptor;\n  typedef boost::readable_property_map_tag      category;\n  typedef bool                                  value_type;\n  typedef bool                                  reference;\n  typedef edge_descriptor                       key_type;\n\n  Constraint()\n    :g_(NULL)\n  {}\n\n  Constraint(G& g, double bound)\n    : g_(&g), bound_(bound)\n  {}\n\n  bool operator[](edge_descriptor e) const\n  {\n    const G& g = *g_;\n    return compare_(g.point(source(e, g)),\n                    g.point(target(e, g)),\n                    g.point(target(next(halfedge(e, g), g), g)),\n                    g.point(target(next(opposite(halfedge(e, g), g), g), g)),\n                   bound_) == CGAL::SMALLER;\n  }\n\n  const G* g_;\n  Compare_dihedral_angle_3 compare_;\n  double bound_;\n};\n\n\ntemplate <typename PM>\nstruct Put_true\n{\n  Put_true(const PM pm)\n    :pm(pm)\n  {}\n\n  template <typename T>\n  void operator()(const T& t)\n  {\n    put(pm, t, true);\n  }\n\n  PM pm;\n};\n\n\nint main(int argc, char* argv[])\n{\n  const std::string filename = (argc > 1) ? argv[1] : CGAL::data_file_path(\"meshes/blobby_3cc.off\");\n\n  Mesh mesh;\n  if(!PMP::IO::read_polygon_mesh(filename, mesh))\n  {\n    std::cerr << \"Invalid input.\" << std::endl;\n    return 1;\n  }\n\n  typedef boost::graph_traits<Mesh>::face_descriptor face_descriptor;\n  const double bound = std::cos(0.75 * CGAL_PI);\n\n  std::vector<face_descriptor> cc;\n  face_descriptor fd = *faces(mesh).first;\n  PMP::connected_component(fd,\n      mesh,\n      std::back_inserter(cc));\n\n  std::cerr << \"Connected components without edge constraints\" << std::endl;\n  std::cerr << cc.size() << \" faces in the CC of \" << fd << std::endl;\n\n  // Instead of writing the faces into a container, you can set a face property to true\n  typedef Mesh::Property_map<face_descriptor, bool> F_select_map;\n  F_select_map fselect_map =\n    mesh.add_property_map<face_descriptor, bool>(\"f:select\", false).first;\n  PMP::connected_component(fd,\n      mesh,\n      boost::make_function_output_iterator(Put_true<F_select_map>(fselect_map)));\n\n\n  std::cerr << \"\\nConnected components with edge constraints (dihedral angle < 3/4 pi)\" << std::endl;\n  Mesh::Property_map<face_descriptor, std::size_t> fccmap =\n    mesh.add_property_map<face_descriptor, std::size_t>(\"f:CC\").first;\n  std::size_t num = PMP::connected_components(mesh,\n      fccmap,\n      PMP::parameters::edge_is_constrained_map(Constraint<Mesh>(mesh, bound)));\n\n  std::cerr << \"- The graph has \" << num << \" connected components (face connectivity)\" << std::endl;\n  typedef std::map<std::size_t/*index of CC*/, unsigned int/*nb*/> Components_size;\n  Components_size nb_per_cc;\n  for(face_descriptor f : faces(mesh)){\n    nb_per_cc[ fccmap[f] ]++;\n  }\n  for(const Components_size::value_type& cc : nb_per_cc){\n    std::cout << \"\\t CC #\" << cc.first\n              << \" is made of \" << cc.second << \" faces\" << std::endl;\n  }\n\n  std::cerr << \"- We keep only components which have at least 4 faces\" << std::endl;\n  PMP::keep_large_connected_components(mesh,\n      4,\n      PMP::parameters::edge_is_constrained_map(Constraint<Mesh>(mesh, bound)));\n\n  std::cerr << \"- We keep the two largest components\" << std::endl;\n  PMP::keep_largest_connected_components(mesh,\n      2,\n      PMP::parameters::edge_is_constrained_map(Constraint<Mesh>(mesh, bound)));\n\n  return 0;\n}\n", "meta": {"hexsha": "ba220bbd3d9d8faca85de8b1e2dd4c02182cf679", "size": 4187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Polygon_mesh_processing/examples/Polygon_mesh_processing/connected_components_example.cpp", "max_stars_repo_name": "VincentRouvreau/cgal", "max_stars_repo_head_hexsha": "bdec97bccb3c77020f38179d00e8d7c998b4f52f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-28T06:29:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T06:29:48.000Z", "max_issues_repo_path": "Polygon_mesh_processing/examples/Polygon_mesh_processing/connected_components_example.cpp", "max_issues_repo_name": "VincentRouvreau/cgal", "max_issues_repo_head_hexsha": "bdec97bccb3c77020f38179d00e8d7c998b4f52f", "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": "Polygon_mesh_processing/examples/Polygon_mesh_processing/connected_components_example.cpp", "max_forks_repo_name": "VincentRouvreau/cgal", "max_forks_repo_head_hexsha": "bdec97bccb3c77020f38179d00e8d7c998b4f52f", "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": 31.2462686567, "max_line_length": 101, "alphanum_fraction": 0.6584666826, "num_tokens": 1053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5376775667924237}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n/**\n * Abstract class that should be inherited from to create specific\n * kalman filters\n *\n * Must initialize:\n *  x_k1_k1, x_k_k1, x_k_k,\n *  P_k1_k1, P_k_k1, P_k_k,\n *  F_k, B_k, H_k,\n *  Q_k, R_k\n *\n * Every predict, must update:\n *  u_k\n *\n * Every PredictWithUpdate, must update:\n *  u_k, z_k\n *\n * The most recently updated values\n *  x_k_k, P_k_k\n *\n * Taken from https://en.wikipedia.org/wiki/Kalman_filter\n *\n * Conversion between code notation and wiki notation is...\n * x_k1_k1 is X_(k-1, k-1)\n * x_k_k is X_(k, k)\n * etc\n */\nclass KalmanFilter {\npublic:\n    /**\n     * Creates a general kalman filter with the given sizes\n     * Use a child class to setup the specific state matricies\n     * Assumes 1 input\n     *\n     * @param stateSize The size of the state vector\n     * @param observationSize The size of the observation vector\n     */\n    KalmanFilter(unsigned int stateSize, unsigned int observationSize) :\n        x_k1_k1(stateSize), x_k_k1(stateSize), x_k_k(stateSize),\n        u_k(1), z_k(observationSize),\n        y_k_k1(observationSize), y_k_k(observationSize),\n        P_k1_k1(stateSize, stateSize), P_k_k1(stateSize, stateSize), P_k_k(stateSize, stateSize),\n        S_k(observationSize, observationSize), K_k(stateSize, observationSize),\n        F_k(stateSize, stateSize), B_k(stateSize, 1), H_k(observationSize, stateSize),\n        Q_k(stateSize, stateSize), R_k(observationSize, observationSize),\n        I(Eigen::MatrixXd::Identity(stateSize, stateSize)) {}\n\n    /**\n     * Predicts without update\n     */\n    void predict();\n\n    /**\n     * Predicts with update\n     * z_k must be set with the observation\n     */\n    void predictWithUpdate();\n\nprotected:\n    Eigen::VectorXd x_k1_k1;\n    Eigen::VectorXd x_k_k1;\n    Eigen::VectorXd x_k_k;\n\n    Eigen::VectorXd u_k;\n    Eigen::VectorXd z_k;\n\n    Eigen::VectorXd y_k_k1;\n    Eigen::VectorXd y_k_k;\n\n    Eigen::MatrixXd P_k1_k1;\n    Eigen::MatrixXd P_k_k1;\n    Eigen::MatrixXd P_k_k;\n\n    Eigen::MatrixXd S_k;\n    Eigen::MatrixXd K_k;\n\n    Eigen::MatrixXd F_k;\n    Eigen::MatrixXd B_k;\n    Eigen::MatrixXd H_k;\n\n    Eigen::MatrixXd Q_k;\n    Eigen::MatrixXd R_k;\n\n    Eigen::MatrixXd I;\n};", "meta": {"hexsha": "fcf169d54a1af301e2d2d48a032c2a651fd62190", "size": 2205, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "soccer/vision/filter/KalmanFilter.hpp", "max_stars_repo_name": "AniruddhaG123/robocup-software", "max_stars_repo_head_hexsha": "0eb3b3957428894f2f39341594800be803665f44", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-24T22:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-24T22:59:25.000Z", "max_issues_repo_path": "soccer/vision/filter/KalmanFilter.hpp", "max_issues_repo_name": "ananth-kumar01/robocup-software", "max_issues_repo_head_hexsha": "4043a7f9590d02f617d8e9a762697e4aaa27f1a6", "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": "soccer/vision/filter/KalmanFilter.hpp", "max_forks_repo_name": "ananth-kumar01/robocup-software", "max_forks_repo_head_hexsha": "4043a7f9590d02f617d8e9a762697e4aaa27f1a6", "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.0568181818, "max_line_length": 97, "alphanum_fraction": 0.6639455782, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5376770210216542}}
{"text": "/* test_array_derivatives.cpp - Test derivatives of array expressions\n\n    Copyright (C) 2017 European Centre for Medium-Range Weather Forecasts\n\n    Author: Robin Hogan <r.j.hogan@ecmwf.int>\n\n  Copying and distribution of this file, with or without modification,\n  are permitted in any medium without royalty provided the copyright\n  notice and this notice are preserved.  This file is offered as-is,\n  without any warranty.\n\n*/\n\n#include <adept_arrays.h>\n\n\n// Arbitrary algorithm converting array of general type A to scalar of\n// type S, which may be active or passive\ntemplate <class A, class S>\nvoid algorithm(const A& x, S& y) {\n  using namespace adept;\n  A tmp;\n  intVector index(2);\n  index << 1, 0;\n  tmp = atan2((exp(x) * x), spread<0>(x(index,1),2)) / x(0,0);\n  y = sum(tmp);\n}\n\n\nint\nmain(int argc, const char** argv) {\n  using namespace adept;\n\n  Stack stack;\n\n  // Matrix dimension\n  static const int N = 2;\n  static const Real MAX_FRAC_ERR = 1.0e-5;\n\n  // Perturbation size for numerical calculation\n  Real dx = 1.0e-6;\n\n  if (sizeof(Real) < 8) {\n    // Single precision only works with larger perturbations\n    dx = 1.0e-4;\n  }\n\n  // Maximum fractional error\n  Real max_frac_err;\n  bool error_too_large = false;\n\n  // Input data\n  Matrix X(N,N);\n  X << 2, 3, 5, 7;\n  \n  // Numerical calculation \n  std::cout << \"NUMERICAL CALCULATION\\n\";\n  Matrix dJ_dx_num(N,N);\n  {\n    Real J;\n    algorithm(X, J);\n    std::cout << \"J = \" << J << \"\\n\";\n\n    for (int i = 0; i < N; ++i) {\n      for (int j = 0; j < N; ++j) {\n\tMatrix Xpert(N,N);\n\tXpert = X;\n\tXpert(i,j) += dx;\n\tReal Jpert;\n\talgorithm(Xpert, Jpert);\n\tdJ_dx_num(i,j) = (Jpert - J) / dx;\n      }\n    }\n  }\n\n  std::cout << \"dJ_dx_num = \" << dJ_dx_num << \"\\n\";\n\n  std::cout << \"\\nNUMERICAL CALCULATION WITH \\\"FixedArray\\\"\\n\";\n  Matrix22 dJ_dx_num_FixedArray;\n  {\n    Real J;\n    algorithm(X, J);\n    std::cout << \"J = \" << J << \"\\n\";\n\n    for (int i = 0; i < N; ++i) {\n      for (int j = 0; j < N; ++j) {\n\tMatrix22 Xpert = X;\n\tXpert(i,j) += dx;\n\tReal Jpert;\n\talgorithm(Xpert, Jpert);\n\tdJ_dx_num_FixedArray(i,j) = (Jpert - J) / dx;\n      }\n    }\n  }\n\n  std::cout << \"dJ_dx_num_FixedArray = \" << dJ_dx_num_FixedArray << \"\\n\";\n\n // Adept calculation with aArray\n  std::cout << \"\\nADEPT CALCULATION WITH \\\"aArray\\\"\\n\";\n  Matrix dJ_dx_adept_Array(N,N);\n  {\n    aMatrix aX = X;\n    stack.new_recording();\n    aReal aJ;\n    algorithm(aX, aJ);\n    std::cout << \"J = \" << aJ << \"\\n\";\n    aJ.set_gradient(1.0);\n    stack.reverse();\n   \n    dJ_dx_adept_Array = aX.get_gradient();\n  }\n\n  std::cout << \"dJ_dx_adept_Array = \" << dJ_dx_adept_Array << \"\\n\";\n\n  max_frac_err = maxval(abs(dJ_dx_adept_Array-dJ_dx_num)/dJ_dx_num);\n  if (max_frac_err <= MAX_FRAC_ERR) {\n    std::cout << \"max fractional error = \" << max_frac_err\n\t\t<< \": PASSED\\n\";\n  }\n  else {\n    std::cout << \"max fractional error = \"\n\t      << max_frac_err << \": FAILED\\n\";\n    error_too_large = true;\n  }\n  // Adept calculation with aFixedArray\n  std::cout << \"\\nADEPT CALCULATION WITH \\\"aFixedArray\\\"\\n\";\n  Matrix dJ_dx_adept_FixedArray;\n  {\n    aMatrix22 aX = X;\n    stack.new_recording();\n    aReal aJ;\n    algorithm(aX, aJ);\n    std::cout << \"J = \" << aJ << \"\\n\";\n    aJ.set_gradient(1.0);\n    stack.reverse();\n    dJ_dx_adept_FixedArray = aX.get_gradient();\n\n  }\n  std::cout << \"dJ_dx_adept_FixedArray = \" << dJ_dx_adept_FixedArray << \"\\n\";\n\n  max_frac_err = maxval(abs(dJ_dx_adept_FixedArray-dJ_dx_num)/dJ_dx_num);\n  if (max_frac_err <= MAX_FRAC_ERR) {\n    std::cout << \"max fractional error = \" << max_frac_err\n\t\t<< \": PASSED\\n\";\n  }\n  else {\n    std::cout << \"max fractional error = \"\n\t      << max_frac_err << \": FAILED\\n\";\n    error_too_large = true;\n  }\n\n  std::cout << \"\\n\";\n\n  if (error_too_large) {\n    std::cerr << \"*** Error: fractional error in the derivatives of some configurations too large\\n\";\n\n    if (sizeof(Real) < 8) {\n      std::cerr << \"*** (but you are using less than double precision so it is not surprising)\\n\";\n    }\n\n    return 1;\n  }\n  else {\n    return 0;\n  }\n\n\n}\n", "meta": {"hexsha": "50dae8608e9b682934ff5632912f808772132924", "size": 4010, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_array_derivatives.cpp", "max_stars_repo_name": "yairchu/Adept-2", "max_stars_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 131.0, "max_stars_repo_stars_event_min_datetime": "2016-07-06T04:06:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T22:34:47.000Z", "max_issues_repo_path": "test/test_array_derivatives.cpp", "max_issues_repo_name": "yairchu/Adept-2", "max_issues_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2016-06-20T20:20:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T14:55:01.000Z", "max_forks_repo_path": "test/test_array_derivatives.cpp", "max_forks_repo_name": "yairchu/Adept-2", "max_forks_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-10-07T00:07:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T17:51:17.000Z", "avg_line_length": 23.7278106509, "max_line_length": 101, "alphanum_fraction": 0.6104738155, "num_tokens": 1286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5376747624770887}}
{"text": "#pragma once\n\n//TODO to be removed...\n\n#include <cmath>\n\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n\n#include <pcl/filters/uniform_sampling.h>\n\n#include <pcl/common/centroid.h>\n\n#include <pcl/kdtree/kdtree_flann.h>\n\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n\n#include \"types.h\"\n\n\nnamespace PoseEstimation\n{\n    /**********************************************************\n     *     Useful helper methods (unused at this moment)      *\n     **********************************************************/\n\n    const double PI = 3.14159265358979323846264338327950288419716939937510582;\n    const double DEG2RAD = PI / 180.0;\n    const double RAD2DEG = 180.0 / PI;\n\n    /**\n     * @brief Finds the minimum element in an array.\n     * @details Returns the index of the minimum element in an array. -1 if array is empty / null.\n     *\n     * @param array The input array.\n     * @return The index of the minimum element.\n     */\n    template<class T>\n    int min_element(const T *array)\n    {\n        if (!array)\n            return -1;\n        int length = sizeof(array) / sizeof(T);\n        if (length <= 0)\n            return -1;\n        int m = 0;\n        for (int i = 1; i < length; ++i)\n        {\n            if (array[i] < array[m])\n                m = i;\n        }\n        return m;\n    }\n\n    /**\n     * @brief Calculates the squared distance between two points.\n     * @details Calculates the squared Euclidean distance between the two points.\n     *\n     * @param a First point with xyz-coordinates.\n     * @param b Second point with xyz-coordinates.\n     *\n     * @return Squared distance between a and b.\n     */\n    float sqr_distance(const PointType &a, const PointType &b)\n    {\n        return pow(a.x-b.x, 2) + pow(a.y-b.y, 2) + pow(a.z-b.z, 2);\n    }\n\n    /**\n     * @brief Calculates the squared distance between two points.\n     * @details Calculates the squared Euclidean distance between the two points.\n     *\n     * @param a First point with xyz-coordinates.\n     * @param b Second point with xyz-coordinates.\n     *\n     * @return Squared distance between a and b.\n     */\n    float sqr_distance(const Eigen::Vector3f &a, const Eigen::Vector3f &b)\n    {\n        return pow(a[0]-b[0], 2) + pow(a[1]-b[1], 2) + pow(a[2]-b[2], 2);\n    }\n\n    /**\n     * @brief Converts a PCL point to an Eigen vector.\n     * @details Converts a PCL point to an Eigen 3d vector by using the xyz-coordinates.\n     *\n     * @param point The PCL point.\n     * @return The Eigen vector.\n     */\n    Eigen::Vector3f point2vec(const PointType &point)\n    {\n        return Eigen::Vector3f(point.x, point.y, point.z);\n    }\n\n    /**\n     * @brief Converts an Eigen vector to a PCL point.\n     * @details Converts an Eigen 3d vector to a PCL point by using the xyz-coordinates.\n     *\n     * @param point The PCL point.\n     * @return The Eigen vector.\n     */\n    PointType vec2point(const Eigen::Vector3f &point)\n    {\n        PointType p;\n        p.x = point[0];\n        p.y = point[1];\n        p.z = point[2];\n        return p;\n    }\n\n    /**\n     * @brief Generates a skew-symmetric matrix from a vector.\n     * @details The skew-symmetric matrix S from a vector u allows to calculate the\n     * cross-product u x v by using only the matrix multiplication S * v.\n     *\n     * @param v The input vector.\n     * @return The skew-symmetric matrix of v.\n     */\n    template <typename T>\n    inline Eigen::Matrix<T, 3, 3> makeSkewSymmetric(const Eigen::Matrix<T, 3, 1> &v)\n    {\n        Eigen::Matrix<T, 3, 3> out;\n        out <<\t   0, -v[2],  v[1],\n                v[2],     0, -v[0],\n               -v[1],  v[0],     0;\n\n        return out;\n    }\n}\n", "meta": {"hexsha": "92067f7b243a47eb1adcb96e4169f414f69fb02d", "size": 3660, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils.hpp", "max_stars_repo_name": "vbillys/pose-estimation", "max_stars_repo_head_hexsha": "e1b57da68d9c961358a6f8fd37706ed521c5c256", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2017-03-30T23:56:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T10:30:32.000Z", "max_issues_repo_path": "utils.hpp", "max_issues_repo_name": "vbillys/pose-estimation", "max_issues_repo_head_hexsha": "e1b57da68d9c961358a6f8fd37706ed521c5c256", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-10T14:14:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-10T10:08:04.000Z", "max_forks_repo_path": "utils.hpp", "max_forks_repo_name": "aviate/pose-estimation", "max_forks_repo_head_hexsha": "e1b57da68d9c961358a6f8fd37706ed521c5c256", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2017-03-30T23:56:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-12T12:08:20.000Z", "avg_line_length": 27.9389312977, "max_line_length": 98, "alphanum_fraction": 0.562295082, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5376747592338045}}
{"text": "// unit test file atanh.hpp for the special functions test suite\r\n\r\n//  (C) Copyright Hubert Holin 2003. Permission to copy, use, modify, sell and\r\n//  distribute this software is granted provided this copyright notice appears\r\n//  in all copies. This software is provided \"as is\" without express or implied\r\n//  warranty, and with no claim as to its suitability for any purpose.\r\n\r\n\r\n#include <functional>\r\n#include <iomanip>\r\n#include <iostream>\r\n\r\n\r\n#include <boost/math/special_functions/atanh.hpp>\r\n\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n\r\ntemplate<typename T>\r\nT    atanh_error_evaluator(T x)\r\n{\r\n    using    ::std::abs;\r\n    using    ::std::tanh;\r\n    using    ::std::cosh;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    using    ::boost::math::atanh;\r\n    \r\n    \r\n    static T const   epsilon = numeric_limits<float>::epsilon();\r\n    \r\n    T                y = tanh(x);\r\n    T                z = atanh(y);\r\n    \r\n    T                absolute_error = abs(z-x);\r\n    T                relative_error = absolute_error/(cosh(x)*cosh(x));\r\n    T                scaled_error = relative_error/epsilon;\r\n    \r\n    return(scaled_error);\r\n}\r\n\r\n\r\ntemplate<typename T>\r\nvoid    atanh_test(const char * more_blurb)\r\n{\r\n    using    ::std::abs;\r\n    using    ::std::tanh;\r\n    using    ::std::log;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    using    ::boost::math::atanh;\r\n    \r\n    \r\n    BOOST_MESSAGE(\"Testing atanh in the real domain for \"\r\n        << more_blurb << \".\");\r\n    \r\n    BOOST_CHECK_PREDICATE(::std::less_equal<T>(), 2,\r\n        (\r\n            abs(atanh<T>(static_cast<T>(0))),\r\n            numeric_limits<T>::epsilon()\r\n        ));\r\n    \r\n    BOOST_CHECK_PREDICATE(::std::less_equal<T>(), 2,\r\n        (\r\n            abs(atanh<T>(static_cast<T>(3)/5) - log(static_cast<T>(2))),\r\n            numeric_limits<T>::epsilon()\r\n        ));\r\n    \r\n    BOOST_CHECK_PREDICATE(::std::less_equal<T>(), 2,\r\n        (\r\n            abs(atanh<T>(static_cast<T>(-3)/5) + log(static_cast<T>(2))),\r\n            numeric_limits<T>::epsilon()\r\n        ));\r\n    \r\n    for    (int i = 0; i <= 100; i++)\r\n    {\r\n        T    x = static_cast<T>(i-50)/static_cast<T>(5);\r\n        T    y = tanh(x);\r\n        \r\n        if    (\r\n                (abs(y-static_cast<T>(1)) >= numeric_limits<T>::epsilon())&&\r\n                (abs(y+static_cast<T>(1)) >= numeric_limits<T>::epsilon())\r\n            )\r\n        {\r\n            BOOST_CHECK_PREDICATE(::std::less_equal<T>(), 2,\r\n                (\r\n                    atanh_error_evaluator(x),\r\n                    static_cast<T>(4)\r\n                ));\r\n        }\r\n    }\r\n}\r\n\r\n\r\nvoid    atanh_manual_check()\r\n{\r\n    using    ::std::abs;\r\n    using    ::std::tanh;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    \r\n    BOOST_MESSAGE(\"atanh\");\r\n    \r\n    for    (int i = 0; i <= 100; i++)\r\n    {\r\n        float        xf = static_cast<float>(i-50)/static_cast<float>(5);\r\n        double       xd = static_cast<double>(i-50)/static_cast<double>(5);\r\n        long double  xl =\r\n                static_cast<long double>(i-50)/static_cast<long double>(5);\r\n        \r\n        float        yf = tanh(xf);\r\n        double       yd = tanh(xd);\r\n        long double  yl = tanh(xl);\r\n        \r\n        if    (\r\n                std::numeric_limits<float>::has_infinity &&\r\n                std::numeric_limits<double>::has_infinity &&\r\n                std::numeric_limits<long double>::has_infinity\r\n            )\r\n        {\r\n            BOOST_MESSAGE( ::std::setw(15)\r\n                        << atanh_error_evaluator(xf)\r\n                        << ::std::setw(15)\r\n                        << atanh_error_evaluator(xd)\r\n                        << ::std::setw(15)\r\n                        << atanh_error_evaluator(xl));\r\n        }\r\n        else\r\n        {\r\n            if    (\r\n                    (abs(yf-static_cast<float>(1)) <\r\n                        numeric_limits<float>::epsilon())||\r\n                    (abs(yf+static_cast<float>(1)) <\r\n                        numeric_limits<float>::epsilon())||\r\n                    (abs(yf-static_cast<double>(1)) <\r\n                        numeric_limits<double>::epsilon())||\r\n                    (abs(yf+static_cast<double>(1)) <\r\n                        numeric_limits<double>::epsilon())||\r\n                    (abs(yf-static_cast<long double>(1)) <\r\n                        numeric_limits<long double>::epsilon())||\r\n                    (abs(yf+static_cast<long double>(1)) <\r\n                        numeric_limits<long double>::epsilon())\r\n                )\r\n            {\r\n                BOOST_MESSAGE(\"Platform's numerics may lack precision.\");\r\n            }\r\n            else\r\n            {\r\n                BOOST_MESSAGE( ::std::setw(15)\r\n                            << atanh_error_evaluator(xf)\r\n                            << ::std::setw(15)\r\n                            << atanh_error_evaluator(xd)\r\n                            << ::std::setw(15)\r\n                            << atanh_error_evaluator(xl));\r\n            }\r\n        }\r\n    }\r\n    \r\n    BOOST_MESSAGE(\" \");\r\n}\r\n\r\n", "meta": {"hexsha": "bee5bc55235ced381158274ea9b14aa835423132", "size": 5090, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/atanh_test.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/atanh_test.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/libs/math/special_functions/atanh_test.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6626506024, "max_line_length": 80, "alphanum_fraction": 0.4599214145, "num_tokens": 1134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5376747375458047}}
{"text": "// g2o - General Graph Optimization\n// Copyright (C) 2012 R. K\u00fcmmerle\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 notice,\n//   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//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n// IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n// 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#include <Eigen/Core>\n#include <iostream>\n\n#include \"g2o/stuff/sampler.h\"\n#include \"g2o/stuff/command_args.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_levenberg.h\"\n#include \"g2o/core/base_vertex.h\"\n#include \"g2o/core/base_unary_edge.h\"\n#include \"g2o/solvers/dense/linear_solver_dense.h\"\n\nusing namespace std;\n\n/**\n * \\brief the params, a, b, and lambda for a * exp(-lambda * t) + b\n */\nclass VertexParams : public g2o::BaseVertex<3, Eigen::Vector3d>\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    VertexParams()\n    {\n    }\n\n    virtual bool read(std::istream& /*is*/)\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n      return false;\n    }\n\n    virtual bool write(std::ostream& /*os*/) const\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n      return false;\n    }\n\n    virtual void setToOriginImpl()\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n    }\n\n    virtual void oplusImpl(const double* update)\n    {\n      Eigen::Vector3d::ConstMapType v(update);\n      _estimate += v;\n    }\n};\n\n/**\n * \\brief measurement for a point on the curve\n *\n * Here the measurement is the point which is lies on the curve.\n * The error function computes the difference between the curve\n * and the point.\n */\nclass EdgePointOnCurve : public g2o::BaseUnaryEdge<1, Eigen::Vector2d, VertexParams>\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    EdgePointOnCurve()\n    {\n    }\n    virtual bool read(std::istream& /*is*/)\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n      return false;\n    }\n    virtual bool write(std::ostream& /*os*/) const\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n      return false;\n    }\n\n    void computeError()\n    {\n      const VertexParams* params = static_cast<const VertexParams*>(vertex(0));\n      const double& a = params->estimate()(0);\n      const double& b = params->estimate()(1);\n      const double& lambda = params->estimate()(2);\n      double fval = a * exp(-lambda * measurement()(0)) + b;\n      _error(0) = fval - measurement()(1);\n    }\n};\n\nint main(int argc, char** argv)\n{\n  int numPoints;\n  int maxIterations;\n  bool verbose;\n  std::vector<int> gaugeList;\n  string dumpFilename;\n  g2o::CommandArgs arg;\n  arg.param(\"dump\", dumpFilename, \"\", \"dump the points into a file\");\n  arg.param(\"numPoints\", numPoints, 50, \"number of points sampled from the curve\");\n  arg.param(\"i\", maxIterations, 10, \"perform n iterations\");\n  arg.param(\"v\", verbose, false, \"verbose output of the optimization process\");\n\n  arg.parseArgs(argc, argv);\n\n  // generate random data\n  double a = 2.;\n  double b = 0.4;\n  double lambda = 0.2;\n  Eigen::Vector2d* points = new Eigen::Vector2d[numPoints];\n  for (int i = 0; i < numPoints; ++i) {\n    double x = g2o::Sampler::uniformRand(0, 10);\n    double y = a * exp(-lambda * x) + b;\n    // add Gaussian noise\n    y += g2o::Sampler::gaussRand(0, 0.02);\n    points[i].x() = x;\n    points[i].y() = y;\n  }\n\n  if (dumpFilename.size() > 0) {\n    ofstream fout(dumpFilename.c_str());\n    for (int i = 0; i < numPoints; ++i)\n      fout << points[i].transpose() << endl;\n  }\n\n  // some handy typedefs\n  typedef g2o::BlockSolver< g2o::BlockSolverTraits<Eigen::Dynamic, Eigen::Dynamic> >  MyBlockSolver;\n  typedef g2o::LinearSolverDense<MyBlockSolver::PoseMatrixType> MyLinearSolver;\n\n  // setup the solver\n  g2o::SparseOptimizer optimizer;\n  optimizer.setVerbose(false);\n\n  g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(\n    g2o::make_unique<MyBlockSolver>(g2o::make_unique<MyLinearSolver>()));\n\n  optimizer.setAlgorithm(solver);\n\n  // build the optimization problem given the points\n  // 1. add the parameter vertex\n  VertexParams* params = new VertexParams();\n  params->setId(0);\n  params->setEstimate(Eigen::Vector3d(1,1,1)); // some initial value for the params\n  optimizer.addVertex(params);\n  // 2. add the points we measured to be on the curve\n  for (int i = 0; i < numPoints; ++i) {\n    EdgePointOnCurve* e = new EdgePointOnCurve;\n    e->setInformation(Eigen::Matrix<double, 1, 1>::Identity());\n    e->setVertex(0, params);\n    e->setMeasurement(points[i]);\n    optimizer.addEdge(e);\n  }\n\n  // perform the optimization\n  optimizer.initializeOptimization();\n  optimizer.setVerbose(verbose);\n  optimizer.optimize(maxIterations);\n\n  if (verbose)\n    cout << endl;\n\n  // print out the result\n  cout << \"Target curve\" << endl;\n  cout << \"a * exp(-lambda * x) + b\" << endl;\n  cout << \"Iterative least squares solution\" << endl;\n  cout << \"a      = \" << params->estimate()(0) << endl;\n  cout << \"b      = \" << params->estimate()(1) << endl;\n  cout << \"lambda = \" << params->estimate()(2) << endl;\n  cout << endl;\n\n  // clean up\n  delete[] points;\n\n  return 0;\n}\n", "meta": {"hexsha": "f55fee1073ba09a7a2b10e5798596c5164990d53", "size": 6299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/g2o/g2o/examples/data_fitting/curve_fit.cpp", "max_stars_repo_name": "xloem/xivo", "max_stars_repo_head_hexsha": "a7dd2553aed28adeee6b6f4c69feb9ba760f12f2", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 662.0, "max_stars_repo_stars_event_min_datetime": "2019-09-01T02:16:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T19:24:07.000Z", "max_issues_repo_path": "3rdPartLib/g2o/g2o/examples/data_fitting/curve_fit.cpp", "max_issues_repo_name": "JazzyFeng/FLVIS-gpu", "max_issues_repo_head_hexsha": "74dd8a136d1923592d2ca74d2408cc2c3bbb8c7b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2019-09-05T05:02:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T02:59:49.000Z", "max_forks_repo_path": "3rdPartLib/g2o/g2o/examples/data_fitting/curve_fit.cpp", "max_forks_repo_name": "JazzyFeng/FLVIS-gpu", "max_forks_repo_head_hexsha": "74dd8a136d1923592d2ca74d2408cc2c3bbb8c7b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 104.0, "max_forks_repo_forks_event_min_datetime": "2019-09-01T07:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T16:24:54.000Z", "avg_line_length": 31.8131313131, "max_line_length": 100, "alphanum_fraction": 0.6772503572, "num_tokens": 1649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5376747375458047}}
{"text": "#ifndef COMMON_COLOR_HPP_\n#define COMMON_COLOR_HPP_\n//----------------------------------------------------------------------------//\n#include <Danvil/Color.h>\n#include <Eigen/Dense>\n#include <Slimage/Slimage.hpp>\n//----------------------------------------------------------------------------//\nnamespace common {\n//----------------------------------------------------------------------------//\n\ntemplate<typename K>\ninline Eigen::Vector3f GreyColor(K x, K a, K b)\n{\n\tfloat p = (static_cast<float>(x) - static_cast<float>(a)) / (static_cast<float>(b) - static_cast<float>(a));\n\tp = std::min(1.0f, std::max(0.0f, p));\n\treturn {p,p,p};\n}\n\n/** Computes a color to express a similarity value between 0 and 1 */\ninline Eigen::Vector3f SimilarityColor(float x)\n{\n\tstatic auto cm = Danvil::ContinuousIntervalColorMapping<float, float>::Factor_Black_Blue_Red_Yellow_White();\n\tcm.setRange(0.0f, 1.0f);\n\tDanvil::Colorf color = cm(x);\n\treturn {color.r,color.g,color.b};\n}\n\ninline Eigen::Vector3f IntensityColor(float x, float a=0.0f, float b=1.0f)\n{\n\tstatic auto cm = Danvil::ContinuousIntervalColorMapping<float, float>::Factor_Black_Blue_Red_Yellow_White();\n\tcm.setRange(a, b);\n\tDanvil::Colorf color = cm(x);\n\treturn {color.r,color.g,color.b};\n}\n\ninline Eigen::Vector3f InvIntensityColor(float x, float a=0.0f, float b=1.0f)\n{\n\treturn IntensityColor(a + b - x, a, b);\n}\n\ninline Eigen::Vector3f PlusMinusColor(float x, float range=1.0f)\n{\n\tstatic auto cm = Danvil::ContinuousIntervalColorMapping<float, float>::Factor_MinusPlus();\n\tcm.setRange(-range, +range);\n\tDanvil::Colorf color = cm(x);\n\treturn {color.r,color.g,color.b};\n}\n\ntemplate<typename T>\ninline Eigen::Vector3f CountColor(T num, T min, T max)\n{\n\treturn IntensityColor(\n\t\t(num < min)\n\t\t\t? 0.0f\n\t\t\t: static_cast<float>(num - min)/static_cast<float>(max-min)\n\t);\n}\n\ninline slimage::Pixel3ub ColorToPixel(const Eigen::Vector3f& color) {\n\treturn slimage::Pixel3ub{{\n\t\tstatic_cast<unsigned char>(255.f*std::min(1.0f, std::max(0.0f, color[0]))),\n\t\tstatic_cast<unsigned char>(255.f*std::min(1.0f, std::max(0.0f, color[1]))),\n\t\tstatic_cast<unsigned char>(255.f*std::min(1.0f, std::max(0.0f, color[2])))\n\t}};\n}\n\ninline slimage::Image3ub Colorize(const slimage::Image1ub& img) {\n\tslimage::Image3ub result(img.width(), img.height());\n\tconst int n = img.size();\n\tfor(int i=0; i<n; i++) {\n\t\tresult[i] = ColorToPixel(CountColor<uint8_t>(img[i], 0, 255));\n\t}\n\treturn result;\n}\n\ninline slimage::Image3ub ColorizeDepth(const slimage::Image1ui16& img16, uint16_t min, uint16_t max) {\n\tslimage::Image3ub img(img16.width(), img16.height());\n\tconst int n = img16.size();\n\tfor(int i=0; i<n; i++) {\n\t\timg[i] = ColorToPixel(CountColor((uint16_t)img16[i], min, max));\n\t}\n\treturn img;\n}\n\ninline slimage::Image3ub GreyDepth(const slimage::Image1ui16& img16, uint16_t min, uint16_t max) {\n\tslimage::Image3ub img(img16.width(), img16.height());\n\tconst int n = img16.size();\n\tfor(int i=0; i<n; i++) {\n\t\timg[i] = ColorToPixel(GreyColor<uint16_t>(img16[i], min, max));\n\t}\n\treturn img;\n}\n\ntemplate<typename CF>\ninline slimage::Image3ub MatrixToImage(const Eigen::MatrixXf& mat, CF cf)\n{\n\tslimage::Image3ub vis = slimage::Image3ub(mat.rows(), mat.cols());\n\tconst float* p = mat.data();\n\tfor(unsigned int i=0; i<vis.size(); i++) {\n\t\tvis[i] = ColorToPixel(cf(p[i]));\n\t}\n\treturn vis;\n}\n\nnamespace detail\n{\n\tinline unsigned char mean(unsigned char x1, unsigned char x2, unsigned char x3, unsigned char x4, unsigned char x5) {\n\t\tunsigned int nb = 4*static_cast<unsigned int>(x1)\n\t\t\t+ static_cast<unsigned int>(x2)\n\t\t\t+ static_cast<unsigned int>(x3)\n\t\t\t+ static_cast<unsigned int>(x4)\n\t\t\t+ static_cast<unsigned int>(x5);\n\t\treturn nb / 8;\n\t}\n\t// inline slimage::Pixel1ub mean(slimage::Pixel1ub x1, slimage::Pixel1ub x2, slimage::Pixel1ub x3, slimage::Pixel1ub x4) {\n\t// \treturn slimage::Pixel1ub{{ mean(x1[0],x2[0],x3[0],x4[0]) }};\n\t// }\n\tinline slimage::Pixel3ub mean(slimage::Pixel3ub x1, slimage::Pixel3ub x2, slimage::Pixel3ub x3, slimage::Pixel3ub x4, slimage::Pixel3ub x5) {\n\t\treturn slimage::Pixel3ub{{\n\t\t\tmean(x1[0],x2[0],x3[0],x4[0],x5[0]),\n\t\t\tmean(x1[1],x2[1],x3[1],x4[1],x5[1]),\n\t\t\tmean(x1[2],x2[2],x3[2],x4[2],x5[2]) }};\n\t}\n}\n\ntemplate<typename T>\nslimage::Image<T> Smooth(const slimage::Image<T>& src)\n{\n\tslimage::Image3ub tmp = src.clone();\n\tfor(unsigned int x=1; x<tmp.width()-1; x++) {\n\t\tfor(unsigned int y=1; y<tmp.height()-1; y++) {\n\t\t\ttmp(x,y) = detail::mean(src(x,y), src(x-1,y), src(x+1,y), src(x,y-1), src(x,y+1));\n\t\t}\n\t}\n\treturn tmp;\n}\n\n//----------------------------------------------------------------------------//\n}\n//----------------------------------------------------------------------------//\n#endif\n", "meta": {"hexsha": "49ce2618486f39738ecf8007b669f5f07b150e87", "size": 4641, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib_dasp/lib_dasp_common/color.hpp", "max_stars_repo_name": "jbellis/superpixel-benchmark", "max_stars_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2016-12-16T10:11:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:08:14.000Z", "max_issues_repo_path": "lib_dasp/lib_dasp_common/color.hpp", "max_issues_repo_name": "jbellis/superpixel-benchmark", "max_issues_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2018-02-15T19:34:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-31T17:04:48.000Z", "max_forks_repo_path": "lib_dasp/lib_dasp_common/color.hpp", "max_forks_repo_name": "jbellis/superpixel-benchmark", "max_forks_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 111.0, "max_forks_repo_forks_event_min_datetime": "2016-12-08T07:19:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:08:16.000Z", "avg_line_length": 32.6830985915, "max_line_length": 142, "alphanum_fraction": 0.6246498599, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5376534892700588}}
{"text": "//==================================================================================================\n/*!\n  @file\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_ARCH_COMMON_SIMD_FUNCTION_STIRLING_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_STIRLING_HPP_INCLUDED\n\n#include <boost/config.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/arch/common/detail/generic/stirling_kernel.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/real.hpp>\n#include <boost/simd/constant/sqrt_2pi.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/if_else_nan.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_gez.hpp>\n#include <boost/simd/function/pow_abs.hpp>\n#include <boost/simd/function/rec.hpp>\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/function/is_nan.hpp>\n#endif\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD_IF ( stirling_\n                             , (typename A0, typename X)\n                             , (detail::is_native<X>)\n                             , bd::cpu_\n                             , bs::pack_< bd::floating_<A0>, X>\n                             )\n  {\n    BOOST_FORCEINLINE A0 operator() (const A0& a00) const BOOST_NOEXCEPT\n    {\n      const A0 Stirlingsplitlim = Real<A0, 0X4061E083BA3443D4ULL, 0X41D628F6UL>();// 143.01608, 26.77f\n      const A0 Stirlinglargelim = Real<A0, 0x4065800000000000ULL, 0X420C28F3UL>();// 172, 35.0399895f\n      A0 a0 = if_else_nan(is_gez(a00), a00);\n      A0 w = bs::rec(a0);\n      w = fma(w,detail::stirling_kernel<A0>::stirling1(w), bs::One<A0>());\n      A0 y = bs::exp(-a0);\n      auto test = is_less(a0, Stirlingsplitlim);\n      A0 z =  a0 - bs::Half<A0>();\n      z =  if_else(test, z, Half<A0>()*z);\n      A0 v =  bs::pow_abs(a0,z);\n      y *= v;\n      y = if_else(test,y, y*v); /* Avoid overflow in pow() */\n      y *= bs::Sqrt_2pi<A0>()*w;\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      y = if_else(is_equal(a0, Inf<A0>()), a0, y);\n      #endif\n      return if_else(a0 > Stirlinglargelim, Inf<A0>(), y);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "7c5d12674fa54dbfd7aaaa905fe58c1481ad5c80", "size": 2577, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/stirling.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/arch/common/simd/function/stirling.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/arch/common/simd/function/stirling.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": 37.8970588235, "max_line_length": 102, "alphanum_fraction": 0.6034148234, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5376130136522799}}
{"text": "//  (C) Copyright John Maddock 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// As detailed in https://github.com/boostorg/math/issues/544\n// our original non-central T test data wasn't accurate past about\n// 20 decimal places.  This data generator takes the original input\n// values and generates new CDF and CDF-complement values via\n// tanh_sinh integration - an option that wasn't available when\n// the original values were generated back in 2008.\n//\n// Note that this code will take SEVERAL DAYS to run on typical\n// 2021 hardware.\n//\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <boost/math/special_functions/hypergeometric_1F1.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/quadrature/exp_sinh.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <fstream>\n\n#include <libs/math/test/table_type.hpp>\n\nusing namespace boost::math::tools;\nusing namespace boost::math;\nusing namespace std;\nusing namespace boost::multiprecision;\n\n//using big_t = number<cpp_bin_float<200, digit_base_10, void, long long>>;\nusing big_t = number<mpfr_float_backend<200>>;\n\nbig_t nct_A(big_t v, big_t x, big_t nu)\n{\n   big_t result = boost::math::hypergeometric_1F1(v / 2 + 1, big_t(3) / 2, nu * nu * x * x / (2 * (v + x * x)));\n   result *= boost::math::constants::root_two<big_t>() * nu * x;\n   result /= (v + x * x) * boost::math::tgamma((v + 1) / 2);\n   return result;\n}\nbig_t nct_B(big_t v, big_t x, big_t nu)\n{\n   big_t result = boost::math::hypergeometric_1F1((v + 1) / 2, big_t(1) / 2, nu * nu * x * x / (2 * (x * x + v)));\n   result /= sqrt(v + x * x) * boost::math::tgamma(v / 2 + 1);\n   return result;\n}\nbig_t nct_PDF(big_t v, big_t nu, big_t x)\n{\n   big_t result = nct_A(v, x, nu) + nct_B(v, x, nu);\n   result *= pow(v, v / 2) * boost::math::tgamma(v + 1);\n   result /= pow(big_t(2), v) * exp(nu * nu / 2) * pow(v + x * x, v / 2) * boost::math::tgamma(v / 2);\n   return result;\n}\n\nbig_t nc_t_F(big_t v, big_t nc, big_t t)\n{\n   unsigned j = 0;\n   big_t sum = 0;\n   big_t tol = std::numeric_limits<big_t>::epsilon();\n   do\n   {\n      big_t x = t * t / (t * t + v);\n      big_t p = exp(-nc * nc / 2) * pow(nc * nc / 2, j) / (2 * boost::math::factorial<big_t>(j));\n      big_t q = (nc / 2) * exp(-nc * nc / 2) * pow(nc * nc / 2, j) / (boost::math::constants::root_two<big_t>() * boost::math::tgamma(j + big_t(3) / 2));\n      big_t term = p * boost::math::ibeta(big_t(j) + 0.5, v / 2, x) + q * boost::math::ibeta(big_t(j + 1), v / 2, x);\n      ++j;\n\n      sum += term;\n\n      if (fabs(sum * tol) > fabs(term))\n         break;\n   } while (true);\n\n   return sum + boost::math::constants::half<big_t>() * (1 + boost::math::erf(-nc / boost::math::constants::root_two<big_t>()));\n}\nbig_t nc_t(big_t v, big_t nc, big_t t)\n{\n   return t < 0 ? 1 - nc_t_F(v, -nc, t) : nc_t_F(v, nc, t);\n}\n\n#define SC_(x) BOOST_JOIN(x, f)\n\nint main(int, char* [])\n{\n   mpfr_set_emax(mpfr_get_emax_max());\n   mpfr_set_emin(mpfr_get_emin_min());\n\n   boost::math::quadrature::exp_sinh<big_t> integrator(10);\n   using T = float;\n\n#include <libs/math/test/nct.ipp>\n\n\n   for (unsigned i = 0; i < nct.size(); ++i)\n   {\n      big_t error1, error2;\n      big_t v(nct[i][0]), nc(nct[i][1]), x(nct[i][2]);\n      big_t cdf, ccdf;\n      try{\n         cdf = integrator.integrate([&](big_t y) { return nct_PDF(v, nc, y); }, -std::numeric_limits<big_t>::infinity(), x, big_t(1e-36), &error1);\n         ccdf = integrator.integrate([&](big_t y) { return nct_PDF(v, nc, y); }, x, std::numeric_limits<big_t>::infinity(), big_t(1e-36), &error2);\n      }\n      catch(const std::exception& e)\n      {\n         std::cout << \"// \" << e.what() << \" reverting to ibeta method\" << std::endl;\n         error1 = error2 = 0;\n         cdf = nc_t(v, nc, x);\n         ccdf = 1 - cdf;\n      }\n\n      if (error1 > 1e-35)\n      {\n         std::cout << \"// Accuracy for cdf was \" << error1 << \" reverting to ibeta method\" << std::endl;\n         cdf = nc_t(v, nc, x);\n      }\n      if (error2 > 1e-35)\n      {\n         std::cout << \"// Accuracy for complement cdf was \" << error2 << \" reverting to ibeta method\" << std::endl;\n         ccdf = 1 - nc_t(v, nc, x);\n      }\n\n      std::cout << std::setprecision(40);\n      std::cout << \"{{ SC_(\" << nct[i][0] << \"), SC_(\" << nct[i][1] << \"), SC_(\" << nct[i][2] << \"), SC_(\";\n      std::cout << cdf << \"), SC_(\" << ccdf << \") }},\" << std::endl;\n   }\n\n#include <libs/math/test/nct_small_delta.ipp>\n   for (unsigned i = 0; i < nct_small_delta.size(); ++i)\n   {\n      big_t error1, error2;\n      big_t v(nct_small_delta[i][0]), nc(nct_small_delta[i][1]), x(nct_small_delta[i][2]);\n      big_t cdf, ccdf;\n      try {\n         cdf = integrator.integrate([&](big_t y) { return nct_PDF(v, nc, y); }, -std::numeric_limits<big_t>::infinity(), x, big_t(1e-36), &error1);\n         ccdf = integrator.integrate([&](big_t y) { return nct_PDF(v, nc, y); }, x, std::numeric_limits<big_t>::infinity(), big_t(1e-36), &error2);\n      }\n      catch (const std::exception& e)\n      {\n         std::cout << \"// \" << e.what() << \" reverting to ibeta method\" << std::endl;\n         error1 = error2 = 0;\n         cdf = nc_t(v, nc, x);\n         ccdf = 1 - cdf;\n      }\n\n      if (error1 > 1e-35)\n      {\n         std::cout << \"// Accuracy for cdf was \" << error1 << \" reverting to ibeta method\" << std::endl;\n         cdf = nc_t(v, nc, x);\n      }\n      if (error2 > 1e-35)\n      {\n         std::cout << \"// Accuracy for complement cdf was \" << error2 << \" reverting to ibeta method\" << std::endl;\n         ccdf = 1 - nc_t(v, nc, x);\n      }\n\n      std::cout << std::setprecision(40);\n      std::cout << \"{{ SC_(\" << v << \"), SC_(\" << nc << \"), SC_(\" << x << \"), SC_(\";\n      std::cout << cdf << \"), SC_(\" << ccdf << \") }},\" << std::endl;\n   }\n\n#include \"../test/nct_asym.ipp\"\n   for (unsigned i = 0; i < nct_asym.size(); ++i)\n   {\n      big_t error1, error2;\n      big_t v(nct_asym[i][0]), nc(nct_asym[i][1]), x(nct_asym[i][2]);\n      big_t cdf, ccdf;\n      try {\n         cdf = integrator.integrate([&](big_t y) { return nct_PDF(v, nc, y); }, -std::numeric_limits<big_t>::infinity(), x, big_t(1e-36), &error1);\n         ccdf = integrator.integrate([&](big_t y) { return nct_PDF(v, nc, y); }, x, std::numeric_limits<big_t>::infinity(), big_t(1e-36), &error2);\n      }\n      catch (const std::exception& e)\n      {\n         std::cout << \"// \" << e.what() << \" reverting to ibeta method\" << std::endl;\n         error1 = error2 = 0;\n         cdf = nc_t(v, nc, x);\n         ccdf = 1 - cdf;\n      }\n\n      if (error1 > 1e-35)\n      {\n         std::cout << \"// Accuracy for cdf was \" << error1 << \" reverting to ibeta method\" << std::endl;\n         cdf = nc_t(v, nc, x);\n      }\n      if (error2 > 1e-35)\n      {\n         std::cout << \"// Accuracy for complement cdf was \" << error2 << \" reverting to ibeta method\" << std::endl;\n         ccdf = 1 - nc_t(v, nc, x);\n      }\n\n      std::cout << std::setprecision(40);\n      std::cout << \"{{ SC_(\" << v << \"), SC_(\" << nc << \"), SC_(\" << x << \"), SC_(\";\n      std::cout << cdf << \"), SC_(\" << ccdf << \") }},\" << std::endl;\n   }\n\n\n   return 0;\n}\n\n\n", "meta": {"hexsha": "90b9e615585d230c301053f38b010dd5c1fc63bb", "size": 7329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/nc_t_data.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": "tools/nc_t_data.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": "tools/nc_t_data.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": 36.1034482759, "max_line_length": 153, "alphanum_fraction": 0.5584663665, "num_tokens": 2425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5376130136522799}}
{"text": "#include \"mex.h\"\n#include <array>\n#include <cmath>\n#include <complex>\n#include <fstream>\n#include <iostream>\n#include <math.h>\n#include <string> // for string class\n#include <time.h>\n#include <vector>\n\n//#define EIGEN_USE_MKL_ALL\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <Eigen/Sparse>\n#include <unsupported/Eigen/CXX11/Tensor>\n#include <unsupported/Eigen/KroneckerProduct>\n#include <unsupported/Eigen/SparseExtra>\n\n#include <eigen3/Eigen/PaStiXSupport>\n\nusing namespace Eigen;\nusing complex_sparse_matrix = Eigen::SparseMatrix<std::complex<double>>;\nusing complex_vector = Eigen::VectorXcd;\nusing complex_matrix = Eigen::MatrixXcd;\n\n#define PI acos(-1.0)\n\n//*******************Changing***************************\n// Without damping matrix\n// full geometry, no symmetric boundarycondition\n//********************************************************\n\n//#include \"mkl_lapacke.h\"\n//#include \"lapack.h\"\n\n// typedef size_t INT;\n//#define MKL_INT INT\n//#ifndef lapack_int\n//#define lapack_int MKL_INT\n//#endif\n// written by Chau Nguyen Khanh\n#define MIN(a, b) ((a) < (b) ? (a) : (b))\n//#ifdef __cplusplus\n// extern \"C\" bool utIsInterruptPending();\n//#else\n// extern bool utIsInterruptPending();\n//#endif\n\n#if defined(NAN_EQUALS_ZERO)\n#define IsNonZero(d) ((d) != 0.0 || mxIsNaN(d))\n#else\n#define IsNonZero(d) ((d) != 0.0)\n#endif\n\n// Dynamic force\n// double force(double x)\n// {\n// \tdouble i;\n// \tif ((1 - x) >= 0)\n// \t{\n// \t\ti = 1.0;\n// \t}\n// \telse\n// \t{\n// \t\ti = 0.0;\n// \t}\n// \treturn -4 * (1.0 - pow((2.0 * x - 1.0), 2.0)) * i;\n// }\ndouble force(double x) { return 1e9 * sin(460 * x); }\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n  //*********************************************\n  /* get the values from the struct 1x1 */\n  // int NoTimeStep = (int) mxGetScalar(mxGetField(prhs[0], 0, \"NoTimeStep\"));\n  // int N_DoF = (int) mxGetScalar(mxGetField(prhs[0], 0, \"N_DoF\")); // number\n  // of dof per element double dt = (double) mxGetScalar(mxGetField(prhs[0], 0,\n  // \"dt\")); // number of dof per element\n  //*********************************************\n\n  /* get the values from the struct Matrix m x 1 */ /*only use the pointer*/\n  // double *TIME_vec = (double *) mxGetPr(mxGetField(prhs[0], 0, \"TIME_vec\"));\n  // int *TIMEPLOT = (int*) mxGetPr(mxGetField(prhs[0], 0, \"TIMEPLOT\"));\n  // int LengthTIMEPLOT = (int) mxGetScalar(mxGetField(prhs[0], 0,\n  // \"LengthTIMEPLOT\")); // number of dof per element\n\n  // \tdouble *val_v0 = (double *) mxGetPr(mxGetField(prhs[0], 0, \"v0\")); //\n  // \tEigen::VectorXd v0 = Map < VectorXd > (val_v0, N_DoF);\n  //*********************************************\n  double *val_rhs_matrix =\n      (double *)mxGetPr(mxGetField(prhs[0], 0, \"rhs_matrix\"));\n  int m_rhs_matrix = mxGetM(mxGetField(prhs[0], 0, \"rhs_matrix\"));\n  int n_rhs_matrix = mxGetN(mxGetField(prhs[0], 0, \"rhs_matrix\"));\n  Eigen::MatrixXd rhs_matrix =\n      Eigen::Map<MatrixXd>(val_rhs_matrix, m_rhs_matrix, n_rhs_matrix);\n\n  double *nnzval_K = (double *)mxGetPr(mxGetField(prhs[0], 0, \"nnzval_K\"));\n  int m_K = (int)mxGetScalar(mxGetField(prhs[0], 0, \"m_K\"));\n  int nnz_K = (int)mxGetScalar(mxGetField(prhs[0], 0, \"nnz_K\"));\n  int *Ir_K = (int *)mxGetPr(mxGetField(prhs[0], 0, \"Ir_K\"));\n  int *Jc_K = (int *)mxGetPr(mxGetField(prhs[0], 0, \"Jc_K\"));\n  std::vector<Eigen::Triplet<double>> trip_K(3 * nnz_K);\n  for (int i = 0; i < nnz_K; ++i) {\n    trip_K.push_back(\n        Eigen::Triplet<double>(Ir_K[i] - 1, Jc_K[i] - 1, nnzval_K[i]));\n  }\n  Eigen::SparseMatrix<double> K(m_K, m_K);\n  K.setFromTriplets(trip_K.begin(), trip_K.end());\n\n  //\t* Out put *//* Out put *//* Out put *//* Out put *//* Out put *//* Out\n  // put */\n  plhs[0] =\n      mxCreateDoubleMatrix((mwSize)m_rhs_matrix, (mwSize)n_rhs_matrix, mxREAL);\n  double *u0_out =\n      mxGetPr(plhs[0]); // pointer pr_out will manage data in COLUMN Major.\n  // plhs[1] = mxCreateDoubleMatrix((mwSize) N_DoF, (mwSize) LengthTIMEPLOT,\n  // mxREAL); double *v0_out = mxGetPr(plhs[1]); // pointer pr_out will manage\n  // data in COLUMN Major. plhs[2] = mxCreateDoubleMatrix((mwSize) N_DoF,\n  // (mwSize) LengthTIMEPLOT, mxREAL); double *a0_out = mxGetPr(plhs[2]); //\n  // pointer pr_out will manage data in COLUMN Major.\n\n  std::cout << \"finishing read matrix from matlab\" << std::endl;\n\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver_LHS;\n  // Eigen::PastixLU<Eigen::SparseMatrix<double>, true> solver_LHS;\n  // Eigen::PastixLDLT<Eigen::SparseMatrix<double>, Eigen::Upper> solver_LHS;\n\n  std::cout << \"1\" << std::endl;\n  // solver_LHS.iparm(34) = 4;\n  std::cout << \"2\" << std::endl;\n  solver_LHS.analyzePattern(K);\n  std::cout << \"3\" << std::endl;\n  solver_LHS.factorize(K);\n  std::cout << \"4\" << std::endl;\n\n  Eigen::MatrixXd u_n1(m_rhs_matrix, n_rhs_matrix);\n  u_n1 = solver_LHS.solve(rhs_matrix);\n\n  std::cout << \"finishing read matrix from matlab\" << std::endl;\n  // Update solution to Final matrix\n\n  Eigen::Map<MatrixXd>(u0_out + (m_rhs_matrix * 0), m_rhs_matrix,\n                       n_rhs_matrix) = u_n1;\n}\n", "meta": {"hexsha": "b33eed64239ddfb94a1516e3af29c5d59d376724", "size": 5059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab/matlab_mex/src_mex/tests/solver_pastix_mex.cpp", "max_stars_repo_name": "shadialameddin/numerical_tools_and_friends", "max_stars_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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": "matlab/matlab_mex/src_mex/tests/solver_pastix_mex.cpp", "max_issues_repo_name": "shadialameddin/numerical_tools_and_friends", "max_issues_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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": "matlab/matlab_mex/src_mex/tests/solver_pastix_mex.cpp", "max_forks_repo_name": "shadialameddin/numerical_tools_and_friends", "max_forks_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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": 34.4149659864, "max_line_length": 79, "alphanum_fraction": 0.6236410358, "num_tokens": 1600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5375871693262009}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University. \n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\ntypedef std::complex<double> cmp;\n\ntemplate <typename Vector>\nvoid test(const Vector& , const char* name)\n{\n    mtl::multi_vector<Vector> A(5, 5);\n    A= 3.0;\n    A[3][2]= cmp(0, 1);\n    cout << name << \":\\n A after initialization is \\n\" << A << \"\\n\";\n\n    mtl::dense_vector<cmp>  b(5, 4.0), x;\n    x= hermitian(A) * b;\n\n    cout << \"x = \" << x << \"\\n\";\n    MTL_THROW_IF(x[1] != 12.0, mtl::runtime_error(\"Wrong value\"));\n    MTL_THROW_IF(x[2] != cmp(12.0, -4.0), mtl::runtime_error(\"Wrong value\"));\n}\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    dense_vector<cmp>    v;\n    test(v, \"dense_vector<double>\");\n\n    return 0;\n}\n", "meta": {"hexsha": "279502dd6d78f55f4829160c9170e4900001bc30", "size": 1162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/multi_vector_hermitian_times_vector_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/multi_vector_hermitian_times_vector_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/multi_vector_hermitian_times_vector_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.7234042553, "max_line_length": 94, "alphanum_fraction": 0.6290877797, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5375871676384247}}
{"text": "// Composite trajectory\n// Author: Max Schwarz <max.schwarz@uni-bonn.de>\n\n#include \"compositetrajectory.h\"\n\n#include <math.h>\n#include <boost/concept_check.hpp>\n\nconst double STEP_PATTERN_LENGTH = 6.0 + 5.0 * 0.9;\nconst double NUM_STEP_PATTERNS = 2.0;\n\nconst double TIME_WAIT = 1.0;\n\nconst double KICK_DRAWBACK_HIP = 50.0 * M_PI/180.0;\nconst double KICK_DRAWBACK_KNEE = 45.0 * M_PI/180.0;\nconst double KICK_DEST_HIP = -60.0 * M_PI/180.0;\nconst double KICK_DEST_KNEE = 0;\nconst double KICK_LENGTH = 0.9;\nconst double KICK_STOP_LENGTH = 0.4;\nconst double KICK_DRAWBACK_LEN = 2.0;\n\nconst double NUM_KICK_PATTERNS = 5.0;\n\nconst int ID_KNEE = 14;\nconst int ID_HIP = 12;\n\ndouble sinFromTo(double from, double to, double freq, double time)\n{\n\tconst double AMPLITUDE = to-from;\n\n\treturn 0.5 * AMPLITUDE * sin(freq * 2.0 * M_PI * time - M_PI/2.0) + 0.5*AMPLITUDE + from;\n}\n\ndouble CompositeTrajectory::endTime() const\n{\n\treturn NUM_STEP_PATTERNS * STEP_PATTERN_LENGTH + TIME_WAIT\n\t\t+ NUM_KICK_PATTERNS * (KICK_LENGTH + KICK_STOP_LENGTH + KICK_DRAWBACK_LEN);\n}\n\ndouble stepPattern(int id, double time)\n{\n\tif(time < 6.0)\n\t{\n\t\tconst double ANGLE = 60.0 * M_PI / 180.0;\n\t\tconst double FREQ = 0.5;\n\n\t\tswitch(id)\n\t\t{\n\t\t\tcase ID_HIP: return sinFromTo(0, -ANGLE, FREQ, time);\n\t\t\tcase ID_KNEE: return sinFromTo(0, 2.0*ANGLE, FREQ, time);\n\t\t}\n\t}\n\telse\n\t{\n\t\tconst double ANGLE = 30.0 * M_PI / 180.0;\n\t\tconst double FREQ = 1.0 / 0.9;\n\t\ttime -= 6.0;\n\t\tswitch(id)\n\t\t{\n\t\t\tcase ID_HIP: return sinFromTo(0, -ANGLE, FREQ, time);\n\t\t\tcase ID_KNEE: return sinFromTo(0, 2.0*ANGLE, FREQ, time);\n\t\t}\n\t}\n\n\treturn 0.0;\n}\n\ndouble kickPattern(int id, double time)\n{\n\tdouble FREQ = 1.0 / (KICK_LENGTH - 0.25) / 2.0;\n\tdouble hip_freq = (time / KICK_LENGTH) * FREQ;\n\n\tdouble amplitudeFactor = 0.5 * (KICK_DRAWBACK_HIP / (KICK_LENGTH/2));\n\tdouble amplitude = amplitudeFactor * time * time;\n\n\tif(time <= KICK_LENGTH)\n\t{\n\t\tswitch(id)\n\t\t{\n\t\t\tcase ID_HIP: return amplitude * sin(2.0 * M_PI * hip_freq * time);\n\t\t\tcase ID_KNEE:\n\t\t\t{\n\t\t\t\tdouble hipZeroTime = sqrt(0.5 / FREQ * KICK_LENGTH);\n\n\t\t\t\tif(time > hipZeroTime)\n\t\t\t\t\treturn 0;\n\n\t\t\t\treturn sinFromTo(KICK_DEST_KNEE, KICK_DRAWBACK_KNEE, 1.0 / hipZeroTime, time);\n\t\t\t}\n\t\t}\n\t}\n\ttime -= KICK_LENGTH;\n\n\tdouble endPos = kickPattern(ID_HIP, KICK_LENGTH);\n\tdouble endVel = 2.0 * amplitudeFactor * KICK_LENGTH * sin(2.0 * M_PI * FREQ * KICK_LENGTH)\n\t\t+ 4.0 * M_PI * FREQ * amplitudeFactor * KICK_LENGTH * KICK_LENGTH * cos(2.0 * M_PI * FREQ * KICK_LENGTH);\n\n\tdouble stopPos = endPos + 0.5 * endVel * KICK_STOP_LENGTH;\n\n\tif(time <= KICK_STOP_LENGTH)\n\t{\n\t\tswitch(id)\n\t\t{\n\t\t\tcase ID_HIP:\n\t\t\t{\n\t\t\t\treturn endPos + endVel * time - 0.5 * endVel / KICK_STOP_LENGTH * time*time;\n\t\t\t}\n\t\t\tcase ID_KNEE:\n\t\t\t\treturn 0;\n\t\t}\n\t}\n\ttime -= KICK_STOP_LENGTH;\n\n\tdouble k = stopPos;\n\tswitch(id)\n\t{\n\t\tcase ID_HIP: return k - k/KICK_DRAWBACK_LEN * time;\n\t\tcase ID_KNEE: return 0;\n\t}\n\n\treturn 0;\n}\n\ndouble CompositeTrajectory::position(int id, double time) const\n{\n\tif(id != ID_HIP && id != ID_KNEE)\n\t\treturn 0.0;\n\n\tif(time < NUM_STEP_PATTERNS * STEP_PATTERN_LENGTH)\n\t{\n\t\tdouble ptime = time;\n\t\twhile(ptime >= STEP_PATTERN_LENGTH)\n\t\t\tptime -= STEP_PATTERN_LENGTH;\n\n\t\tdouble pos = stepPattern(id, ptime);\n\n\t\tif(id == ID_HIP)\n\t\t{\n\t\t\tconst double ANGLE = 70.0 * M_PI / 180.0;\n\t\t\tconst double FREQ = 1.0 / (NUM_STEP_PATTERNS * STEP_PATTERN_LENGTH);\n\t\t\tpos += 0.5 * ANGLE * sin(FREQ * 2.0 * M_PI * time + M_PI/2.0) - 0.5*ANGLE;\n\t\t}\n\n\t\treturn pos;\n\t}\n\ttime -= NUM_STEP_PATTERNS*STEP_PATTERN_LENGTH;\n\n\tif(time < TIME_WAIT)\n\t\treturn 0;\n\ttime -= TIME_WAIT;\n\n\tdouble ptime = time;\n\twhile(ptime >= KICK_LENGTH + KICK_STOP_LENGTH + KICK_DRAWBACK_LEN)\n\t\tptime -= KICK_LENGTH + KICK_STOP_LENGTH + KICK_DRAWBACK_LEN;\n\treturn kickPattern(id, ptime);\n}\n\n", "meta": {"hexsha": "f386227bfccc2d51167acf8bce5e62b691b3a06c", "size": 3714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nimbro_robotcontrol/hardware/servomodel/src/testbench/compositetrajectory.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/hardware/servomodel/src/testbench/compositetrajectory.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_robotcontrol/hardware/servomodel/src/testbench/compositetrajectory.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": 23.5063291139, "max_line_length": 107, "alphanum_fraction": 0.6782444803, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5375871626364035}}
{"text": "#ifndef __GUIDANCE_HH__\n#define __GUIDANCE_HH__\n/********************************* TRICK HEADER *******************************\nPURPOSE:\n      (Describe the GUIDANCE Module On Board)\nLIBRARY DEPENDENCY:\n      ((../src/Guidance.cpp))\nPROGRAMMERS:\n      (((Chung-Fan Yang) () () () ))\n*******************************************************************************/\n#include <armadillo>\n#include \"aux.hh\"\n\nclass Guidance {\n    TRICK_INTERFACE(Guidance);\n\n public:\n    Guidance();\n    Guidance(const Guidance& other);\n\n    Guidance& operator= (const Guidance& other);\n\n    void default_data();\n    void initialize();\n\n    void guidance(double int_step);\n\n    arma::vec3 guidance_ltg(int &mprop, double int_step, double time_ltg);\n    void guidance_ltg_tgo(double &tgop,\n                          arma::mat &BURNTN,\n                          arma::mat &L_IGRLN,\n                          arma::mat &TGON,\n                          double &l_igrl,\n                          int &nstmax,\n                          double &tgo,\n                          int &nst,\n                          arma::mat &TAUN,\n                          arma::mat VEXN,\n                          arma::mat BOTN,\n                          double delay_ignition,\n                          double vgom,\n                          double amag1,\n                          double amin,\n                          double time_ltg,\n                          int num_stages);\n    void guidance_ltg_igrl(double &s_igrl,\n                           double &j_igrl,\n                           double &q_igrl,\n                           double &h_igrl,\n                           double &p_igrl,\n                           double &j_over_l,\n                           double &tlam,\n                           double &qprime,\n                           int nst,\n                           int nstmax,\n                           arma::mat BURNTN,\n                           arma::mat L_IGRLN,\n                           arma::mat TGON,\n                           arma::mat TAUN,\n                           arma::mat VEXN,\n                           double l_igrl,\n                           double time_ltg);\n    void guidance_ltg_trate(arma::mat &ULAM,\n                            arma::mat &LAMD,\n                            arma::mat &RGO,\n                            int &ipas2_flag,\n                            arma::mat VGO,\n                            double s_igrl,\n                            double q_igrl,\n                            double j_over_l,\n                            double lamd_limit,\n                            double vgom,\n                            double time_ltg,\n                            double tgo,\n                            double tgop,\n                            arma::mat SDII,\n                            arma::mat SBIIC,\n                            arma::mat VBIIC,\n                            arma::mat RBIAS,\n                            arma::mat UD,\n                            arma::mat UY,\n                            arma::mat UZ,\n                            arma::mat &RGRAV);\n    void guidance_ltg_trate_rtgo(arma::mat &RGO,\n                                 arma::mat &RGRAV,\n                                 double tgo,\n                                 double tgop,\n                                 arma::mat SDII,\n                                 arma::mat SBIIC,\n                                 arma::mat VBIIC,\n                                 arma::mat RBIAS,\n                                 arma::mat ULAM,\n                                 arma::mat UD,\n                                 arma::mat UY,\n                                 arma::mat UZ,\n                                 double s_igrl);\n    void guidance_ltg_pdct(arma::mat &SPII,\n                           arma::mat &VPII,\n                           arma::mat &RGRAV,\n                           arma::mat &RBIAS,\n                           arma::mat LAMD,\n                           arma::mat ULAM,\n                           double l_igrl,\n                           double s_igrl,\n                           double j_igrl,\n                           double q_igrl,\n                           double h_igrl,\n                           double p_igrl,\n                           double j_over_l,\n                           double qprime,\n                           arma::mat SBIIC,\n                           arma::mat VBIIC,\n                           arma::mat RGO,\n                           double tgo);\n    void guidance_ltg_crct(arma::mat &SDII,\n                           arma::mat &UD,\n                           arma::mat &UY,\n                           arma::mat &UZ,\n                           arma::mat &VMISS,\n                           arma::mat &VGO,\n                           double dbi_desired,\n                           double dvbi_desired,\n                           double thtvdx_desired,\n                           arma::mat SPII,\n                           arma::mat VPII,\n                           arma::mat SBIIC,\n                           arma::mat VBIIC);\n\n    std::function<int()>            grab_mprop;\n\n    std::function<double()>         grab_dbi;\n    std::function<double()>         grab_dvbi;\n    std::function<double()>         grab_thtvdx;\n    std::function<double()>         grab_fmassr;\n    std::function<arma::vec3()>     grab_VBIIC;\n    std::function<arma::vec3()>     grab_SBIIC;\n    std::function<arma::mat33()>    grab_TBIC;\n    std::function<arma::vec3()>     grab_FSPCB;\n\n    std::function<void()>           set_no_thrust;\n    std::function<void()>           set_ltg_thrust;\n\n    ///////////////////////////////////////////////////////////////////////////////\n    // Definition of guidance module-variables\n    // Member function of class 'Hyper'\n    // Module-variable locations are assigned to hyper[400-499]\n    // Overflow assignment hyper[850-899]\n    //\n    //       mguide =  0 no guidance\n    //              =  5 linear tangent guidance law (LTG) for rocket ascent\n    //\n    // 030616 Created by Peter H Zipfel\n    // 091214 Modified for ROCKET6, PZi\n    ///////////////////////////////////////////////////////////////////////////////\n    arma::vec3  get_UTBC();\n\n    double  get_alphacomx();\n    double  get_betacomx();\n\n    void    set_degree(double, double);\n\n private:\n    /* Propagative Stats */\n    arma::vec  UTBC;        /* *io  (--)        Commanded unit thrust vector in body coor */\n    double  _UTBC[3];        /* *io  (--)        Commanded unit thrust vector in body coor */\n\n    /* Diagnostic */\n    arma::vec  UTIC;        /* *io  (--)        Commanded unit thrust vector in inertial coor */\n    double  _UTIC[3];        /* *io  (--)        Commanded unit thrust vector in inertial coor */\n\n    /* Set by input.py */\n    double  alphacomx;      /* *io  (d)         Alpha command */\n    double  betacomx;       /* *io  (d)         Beta command */\n\n    /* Internally set parameter */\n    int     init_flag;      /* *io  (--)        Flag for initializing LTG flags */\n    int     inisw_flag;     /* *io  (--)        Flag to initialize '..._intl()' */\n    int     skip_flag;      /* *io  (--)        Flag to delay output */\n    int     ipas_flag;      /* *io  (--)        Flag to initialize in '..._tgo()'  */\n    int     ipas2_flag;     /* *io  (--)        Flag to initialize in '..._trat()'  */\n    int     print_flag;     /* *io  (--)        Flag to cause print-out  */\n    double  time_ltg;       /* *io  (s)         Time since initiating LTG */\n\n    int     ltg_count;      /* *io  (--)        Counter of LTG guidance cycles  */\n\n    /* Externally set parameter */\n    int     mguide;         /* *io  (--)        Guidance modes, see table */\n    double  ltg_step;       /* *io  (s)         LTG guidance time step */\n\n    arma::vec RBIAS;       /* *io  (m)         Range-to-be-gained bias */\n    double   _RBIAS[3];       /* *io  (m)         Range-to-be-gained bias */\n    int     beco_flag;      /* *io  (--)        Boost engine cut-off flag */\n    double  dbi_desired;    /* *io  (m)         Desired orbital end position */\n    double  dvbi_desired;   /* *io  (m/s)       Desired orbital end velocity */\n    double  thtvdx_desired; /* *io  (d)         Desired orbital flight path angle */\n    int     num_stages;     /* *io  (s)         Number of stages in boost phase */\n    double  delay_ignition; /* *io  (s)         Delay of motor ignition after staging */\n    double  amin;           /* *io  (m/s2)      Minimum longitudinal acceleration */\n    double  char_time1;     /* *io  (s)         Characteristic time 'tau' of stage 1 */\n    double  char_time2;     /* *io  (s)         Characteristic time 'tau' of stage 2 */\n    double  char_time3;     /* *io  (s)         Characteristic time 'tau' of stage 3 */\n    double  exhaust_vel1;   /* *io  (m/s)       Exhaust velocity of stage 1 */\n    double  exhaust_vel2;   /* *io  (m/s)       Exhaust velocity of stage 2 */\n    double  exhaust_vel3;   /* *io  (m/s)       Exhaust velocity of stage 3 */\n    double  burnout_epoch1; /* *io  (s)         Burn out of stage 1 at 'time_ltg' */\n    double  burnout_epoch2; /* *io  (s)         Burn out of stage 2 at 'time_ltg' */\n    double  burnout_epoch3; /* *io  (s)         Burn out of stage 3 at 'time_ltg' */\n    double  lamd_limit;     /* *io  (1/s)       Limiter on 'lamd' */\n    arma::vec  RGRAV;       /* *io  (m)         Postion loss due to gravity */\n    double  _RGRAV[3];       /* *io  (m)         Postion loss due to gravity */\n    arma::vec  RGO;         /* *io  (m)         Range-to-go vector */\n    double  _RGO[3];         /* *io  (m)         Range-to-go vector */\n    arma::vec  VGO;         /* *io  (m/s)       Velocity still to be gained */\n    double  _VGO[3];         /* *io  (m/s)       Velocity still to be gained */\n    arma::vec  SDII;        /* *io  (m)         Desired inertial position */\n    double  _SDII[3];        /* *io  (m)         Desired inertial position */\n    arma::vec  UD;          /* *io  (--)        Unit vector of SPII and SDII */\n    double  _UD[3];          /* *io  (--)        Unit vector of SPII and SDII */\n    arma::vec  UY;          /* *io  (--)        Unit vector normal to traj plane */\n    double  _UY[3];          /* *io  (--)        Unit vector normal to traj plane */\n    arma::vec  UZ;          /* *io  (--)        Unit vector in traj plane, normal to SBBI_D */\n    double  _UZ[3];          /* *io  (--)        Unit vector in traj plane, normal to SBBI_D */\n    double  vgom;           /* *io  (m/s)       Velocity to be gained magnitude */\n    double  tgo;            /* *io  (s)         Time to go to desired end state */\n    int     nst;            /* *io  (--)        N-th stage number */\n    arma::vec  ULAM;        /* *io  (--)        Unit thrust vector in VGO direction */\n    double  _ULAM[3];        /* *io  (--)        Unit thrust vector in VGO direction */\n    arma::vec  LAMD;       /* *io  (1/s)       Thrust vector turning rate */\n    double  _LAMD[3];       /* *io  (1/s)       Thrust vector turning rate */\n    int     nstmax;         /* *io  (--)        # of stages needed to meet end state */\n    double  lamd;           /* *io  (1/s)       Magnitude of LAMD */\n    double  dpd;            /* *io  (m)         Distance of the predicted from the desired end-point */\n    double  dbd;            /* *io  (m)         Distance of vehicle from the desired end-point */\n    double  ddb;            /* *io  (m)         Position error at BECO */\n    double  dvdb;           /* *io  (m/s)       Distance of vehicle from the desired end-point */\n    double  thtvddbx;       /* *io  (d)         Angle error at BECO */\n};\n\n#endif  // __GUIDANCE_HH__\n", "meta": {"hexsha": "627a52e018df515d83adf5ee91d3ced079df160d", "size": 11653, "ext": "hh", "lang": "C++", "max_stars_repo_path": "models/gnc/include/Guidance.hh", "max_stars_repo_name": "ultype/Next-simulation", "max_stars_repo_head_hexsha": "0fb59d02b2f88e813792a486d7fcab7242f77c11", "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/gnc/include/Guidance.hh", "max_issues_repo_name": "ultype/Next-simulation", "max_issues_repo_head_hexsha": "0fb59d02b2f88e813792a486d7fcab7242f77c11", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/gnc/include/Guidance.hh", "max_forks_repo_name": "ultype/Next-simulation", "max_forks_repo_head_hexsha": "0fb59d02b2f88e813792a486d7fcab7242f77c11", "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": 48.5541666667, "max_line_length": 103, "alphanum_fraction": 0.4254698361, "num_tokens": 2746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5375871610099351}}
{"text": "#include <algorithm>\n#include <iterator>\n#include <stdexcept>\n#include <vector>\n#include <boost/iterator/counting_iterator.hpp>\n#include <CGAL/Orthogonal_k_neighbor_search.h>\n#include <CGAL/Search_traits_3.h>\n#include <CGAL/Search_traits_adapter.h>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <Euclid/Geometry/TriMeshGeometry.h>\n\nnamespace Euclid\n{\n\nnamespace _impl\n{\n\n// Construct linear system for mesh\ntemplate<typename Mesh, typename FT>\nvoid construct_equation(const Mesh& mesh,\n                        const std::vector<int>& ids,\n                        Eigen::SparseMatrix<FT>& A,\n                        Eigen::SparseMatrix<FT>& B)\n{\n    using SpMat = Eigen::SparseMatrix<FT>;\n    const auto inv_sigma = static_cast<FT>(1.0); // parameter\n\n    auto fimap = get(boost::face_index, mesh);\n    auto vpmap = get(boost::vertex_point, mesh);\n    auto m = B.cols();\n    auto n = B.rows();\n    auto sum = 0.0;\n    auto n_faces = num_faces(mesh);\n    std::vector<int> rows;\n    std::vector<int> cols;\n    std::vector<FT> edge_len;\n    std::vector<FT> ds;\n    rows.reserve(3 * n_faces);\n    cols.reserve(3 * n_faces);\n    edge_len.reserve(3 * n_faces);\n    ds.reserve(3 * n_faces);\n\n    // Compute the ingredients of the laplacian matrix\n    for (auto fa : faces(mesh)) {\n        auto fa_id = ids[get(fimap, fa)];\n        auto na = Euclid::face_normal(fa, mesh);\n\n        for (auto ha : CGAL::halfedges_around_face(halfedge(fa, mesh), mesh)) {\n            auto hb = opposite(ha, mesh);\n            if (!is_border(hb, mesh)) { // Non-boundary\n\n                // Determine whether the incident edge is concave or convex\n                auto pa = get(vpmap, target(next(ha, mesh), mesh));\n                auto pb = get(vpmap, target(next(hb, mesh), mesh));\n                auto p = pb - pa;\n                auto eta = p * na <= 0.0 ? 0.2 : 1.0;\n\n                auto fb = face(hb, mesh);\n                auto fb_id = ids[get(fimap, fb)];\n                auto nb = Euclid::face_normal(fb, mesh);\n                auto diff = 0.5 * eta * (na - nb).squared_length();\n\n                cols.push_back(fa_id);\n                rows.push_back(fb_id);\n                ds.push_back(diff);\n                edge_len.push_back(Euclid::edge_length(ha, mesh));\n                sum += diff;\n            }\n            else { // Placeholder\n                ds.push_back(-1.0);\n            }\n        }\n    }\n\n    // Normalize\n    std::vector<Eigen::Triplet<FT>> values;\n    values.reserve(cols.size());\n    auto inv_avg = edge_len.size() / (sum * 0.5);\n    auto d_iter = ds.begin();\n    auto e_iter = edge_len.begin();\n    auto c_iter = cols.begin();\n    auto r_iter = rows.begin();\n    while (d_iter != ds.end()) {\n        auto prob_sum = 0.0;\n        for (auto j = 0; j < 3; ++j) {\n            if (*d_iter != -1.0) {\n                auto prob =\n                    std::exp(-(*d_iter * inv_avg) * inv_sigma) * *e_iter++;\n                *d_iter++ = -prob;\n                prob_sum += prob;\n            }\n            else {\n                ++d_iter;\n            }\n        }\n        prob_sum = 1.0 / prob_sum;\n        d_iter -= 3;\n        for (auto j = 0; j < 3; ++j) {\n            if (*d_iter != -1.0) {\n                values.emplace_back(*c_iter++, *r_iter++, *d_iter++ * prob_sum);\n            }\n            else {\n                ++d_iter;\n            }\n        }\n    }\n\n    for (unsigned i = 0; i < num_faces(mesh); ++i) {\n        values.emplace_back(i, i, static_cast<FT>(1.0));\n    }\n\n    // Fill in the matrix\n    SpMat L(m + n, m + n);\n    L.setFromTriplets(values.begin(), values.end());\n    A = L.bottomRightCorner(n, n);\n    B = -L.bottomLeftCorner(n, m);\n    A.makeCompressed();\n    B.makeCompressed();\n}\n\n// // Construct linear system for point cloud\n// template<typename ForwardIterator,\n//          typename Index,\n//          typename PPMap,\n//          typename NPMap,\n//          typename FT>\n// void construct_equation(ForwardIterator first,\n//                         ForwardIterator beyond,\n//                         PPMap point_pmap,\n//                         NPMap normal_pmap,\n//                         const std::vector<std::vector<int>>& neighbors,\n//                         const std::vector<Index>& indices,\n//                         const std::vector<int>& ids,\n//                         Eigen::SparseMatrix<FT>& A,\n//                         Eigen::SparseMatrix<FT>& B)\n// {\n//     using SpMat = Eigen::SparseMatrix<FT>;\n\n//     const auto inv_sigma1 = 1.0;\n//     const auto inv_sigma2 = 1.0;\n//     auto m = B.cols();\n//     auto n = B.rows();\n//     auto n_points = m + n;\n//     auto n_neighbors = neighbors[0].size();\n//     std::vector<int> rows;\n//     std::vector<int> cols;\n//     std::vector<FT> d1s;\n//     std::vector<FT> d2s;\n//     rows.reserve(n_points * n_neighbors);\n//     cols.reserve(n_points * n_neighbors);\n//     d1s.reserve(n_points * n_neighbors);\n//     d2s.reserve(n_points * n_neighbors);\n//     auto d2_sum = 0.0;\n\n//     // Compute the ingredients of the laplacian matrix\n//     auto i = 0;\n//     for (auto iter = first; iter != beyond; ++iter, ++i) {\n//         auto pi = get(point_pmap, *iter);\n//         auto ni = get(normal_pmap, *iter);\n//         auto d1_sum = 0.0;\n\n//         for (auto j = 0; j < n_neighbors; ++j) {\n//             auto neighbor = neighbors[i][j];\n//             cols.push_back(ids[i]);\n//             rows.push_back(ids[neighbor]);\n\n//             auto pj = get(point_pmap, indices[neighbor]);\n//             auto nj = get(normal_pmap, indices[neighbor]);\n//             auto eta = ((pj - pi) - ((pj - pi) * ni) * ni) * nj >= 0.0\n//                            ? 0.2\n//                            : 1.0; // convex : concave\n\n//             auto d1 = (pi - pj).squared_length();\n//             d1s.push_back(d1);\n//             d1_sum += d1;\n//             auto d2 = 0.5 * eta * (ni - nj).squared_length();\n//             d2s.push_back(d2);\n//             d2_sum += d2;\n//         }\n\n//         auto d1_inv_avg = n_neighbors / d1_sum;\n//         for (auto j = 0; j < n_neighbors; ++j) {\n//             auto idx = i * n_neighbors + j;\n//             d1s[idx] = std::exp(-d1s[idx] * d1_inv_avg * inv_sigma1);\n//         }\n//     }\n\n//     auto d2_inv_avg = (n_points * n_neighbors) / d2_sum;\n//     for (auto& d2 : d2s) {\n//         d2 = std::exp(-d2 * d2_inv_avg * inv_sigma2);\n//     }\n\n//     // Normalize\n//     std::vector<Eigen::Triplet<FT>> values;\n//     values.reserve(n_points * (n_neighbors + 1));\n//     for (auto i = 0; i < n_points; ++i) {\n//         std::vector<FT> ds(n_neighbors);\n//         FT sum = 0.0;\n//         for (auto j = 0; j < n_neighbors; ++j) {\n//             auto idx = i * n_neighbors + j;\n//             ds[j] = d1s[idx] * d2s[idx];\n//             sum += ds[j];\n//         }\n//         FT inv_sum = 1.0 / sum;\n//         for (auto j = 0; j < n_neighbors; ++j) {\n//             auto idx = i * n_neighbors + j;\n//             values.emplace_back(cols[idx], rows[idx], -ds[j] * inv_sum);\n//         }\n//         values.emplace_back(i, i, static_cast<FT>(1.0));\n//     }\n\n//     // Fill in the matrix\n//     SpMat L(m + n, m + n);\n//     L.setFromTriplets(values.begin(), values.end());\n//     A = L.bottomRightCorner(n, n);\n//     B = -L.bottomLeftCorner(n, m);\n//     A.makeCompressed();\n//     B.makeCompressed();\n// }\n\n// // Adapt PointPropertyMap to take in integer as key type\n// template<typename PPMap>\n// class IPMapAdaptor\n// {\n//     using PointKey = typename boost::property_traits<PPMap>::key_type;\n//     using Point_3 = typename boost::property_traits<PPMap>::value_type;\n\n// public:\n//     using value_type = Point_3;\n//     using reference = const value_type&;\n//     using key_type = int;\n//     using category = boost::lvalue_property_map_tag;\n\n//     IPMapAdaptor(PPMap ppmap, const std::vector<PointKey>& pks)\n//         : _ppmap(ppmap), _pks(pks)\n//     {}\n\n//     reference operator[](key_type key) const { return _ppmap[_pks[key]]; }\n\n//     friend reference get(IPMapAdaptor ipmap, key_type key)\n//     {\n//         return ipmap[key];\n//     }\n\n// private:\n//     PPMap _ppmap;\n//     const std::vector<PointKey>& _pks;\n// };\n\n} // namespace _impl\n\ntemplate<typename Mesh>\nvoid random_walk_segmentation(const Mesh& mesh,\n                              const std::vector<unsigned>& seeds,\n                              std::vector<unsigned>& segments)\n{\n    using VertexPointMap =\n        typename boost::property_map<Mesh, boost::vertex_point_t>::type;\n    using Point_3 = typename boost::property_traits<VertexPointMap>::value_type;\n    using FT = typename CGAL::Kernel_traits<Point_3>::Kernel::FT;\n    using SpMat = Eigen::SparseMatrix<FT>;\n\n    // Construct the linear equation\n    auto seed_indices = seeds;\n    auto m = static_cast<int>(seed_indices.size()); // Number of seeded\n    auto n = static_cast<int>(num_faces(mesh)) - m; // Number of unseeded\n    std::sort(seed_indices.begin(), seed_indices.end());\n    std::vector<int> ids(m + n, -1); // ids[FacetID] -> MatrixID\n    size_t inc = 0;\n    while (inc < seed_indices.size()) {\n        ids[seed_indices[inc]] = inc;\n        ++inc;\n    }\n    for (auto& id : ids) {\n        if (id == -1) {\n            id = inc++;\n        }\n    }\n    SpMat A(n, n);\n    SpMat B(n, m);\n    _impl::construct_equation(mesh, ids, A, B);\n\n    std::vector<int> inv_ids(m + n);\n    for (auto i = 0; i < m + n; ++i) {\n        inv_ids[ids[i]] = i;\n    }\n\n    // Solve the equation to segment\n    segments.resize(n + m, 0);\n    for (auto s : seed_indices) {\n        segments[s] = s;\n    }\n    std::vector<FT> max_probabilities(n, static_cast<FT>(-1.0));\n    Eigen::SparseLU<SpMat> solver;\n    solver.compute(A);\n    if (solver.info() != Eigen::Success) {\n        throw std::runtime_error(solver.lastErrorMessage());\n    }\n    for (auto i = 0; i < m; ++i) {\n        Eigen::Matrix<FT, Eigen::Dynamic, 1> b = B.col(i);\n        Eigen::Matrix<FT, Eigen::Dynamic, 1> x = solver.solve(b);\n        for (auto j = 0; j < n; ++j) {\n            if (x(j, 0) > max_probabilities[j]) {\n                max_probabilities[j] = x(j, 0);\n                segments[inv_ids[j + m]] = seed_indices[i];\n            }\n        }\n    }\n}\n\n// template<typename ForwardIterator, typename PPMap, typename NPMap>\n// void random_walk_segmentation(ForwardIterator first,\n//                               ForwardIterator beyond,\n//                               PPMap point_pmap,\n//                               NPMap normal_pmap,\n//                               const std::vector<unsigned>& seeds,\n//                               std::vector<unsigned>& segments)\n// {\n\n//     using Index = std::iterator_traits<ForwardIterator>::value_type;\n//     using Point_3 = boost::property_traits<PPMap>::value_type;\n//     using Vector_3 = boost::property_traits<NPMap>::value_type;\n//     using Kernel = CGAL::Kernel_traits<Point_3>::Kernel;\n//     using IPMap = _impl::IPMapAdaptor<PPMap>;\n//     using BaseTraits = CGAL::Search_traits_3<Kernel>;\n//     using KdTreeTraits = CGAL::Search_traits_adapter<int, IPMap, BaseTraits>;\n//     using KNN = CGAL::Orthogonal_k_neighbor_search<KdTreeTraits>;\n//     using KdTree = typename KNN::Tree;\n//     using Splitter = KdTree::Splitter;\n//     using Distance = KNN::Distance;\n//     using FT = Kernel::FT;\n//     using SpMat = Eigen::SparseMatrix<FT>;\n//     const int k = 6; // Use 6 neighbors according to Euler formula\n\n//     // Construct the IPMap\n//     std::vector<Index> indices;\n//     int n = 0;\n//     for (auto iter = first; iter != beyond; ++iter) {\n//         indices.push_back(*iter);\n//         ++n;\n//     }\n//     IPMap ipmap(point_pmap, indices);\n\n//     // Construct the k-d tree\n//     KdTree tree(boost::counting_iterator<int>(0),\n//                 boost::counting_iterator<int>(n),\n//                 Splitter(),\n//                 KdTreeTraits(ipmap));\n//     Distance dist(ipmap);\n\n//     // Query neighbors for all points and store the neighbors' indices\n//     std::vector<std::vector<int>> neighbors;\n//     for (auto iter = first; iter < beyond; ++iter) {\n//         std::vector<int> neighbors_i;\n//         neighbors_i.reserve(k);\n\n//         auto p = point_pmap[*iter];\n//         KNN knn(tree, p, k + 1, static_cast<FT>(0.00001), true, dist);\n\n//         auto it = knn.begin();\n//         ++it; // The first will always return the identical point\n//         for (it; it != knn.end(); ++it) {\n//             neighbors_i.push_back(it->first);\n//         }\n\n//         neighbors.push_back(neighbors_i);\n//     }\n\n//     // Construct the linear equation\n//     auto seed_indices = seeds;\n//     auto m = static_cast<int>(seed_indices.size()); // Number of seeded\n//     n -= m;                                         // Number of unseeded\n//     std::sort(seed_indices.begin(), seed_indices.end());\n//     SpMat A(n, n);\n//     SpMat B(n, m);\n//     std::vector<int> ids(m + n, -1); // ids[PointID] -> MatrixID\n//     int inc = 0;\n//     while (inc < seed_indices.size()) {\n//         ids[seed_indices[inc]] = inc;\n//         ++inc;\n//     }\n//     for (auto& id : ids) {\n//         if (id == -1) { id = inc++; }\n//     }\n//     _impl::construct_equation(\n//         first, beyond, point_pmap, normal_pmap, neighbors, indices, ids, A,\n//         B);\n\n//     std::vector<int> inv_ids(m + n);\n//     for (auto i = 0; i < m + n; ++i) {\n//         inv_ids[ids[i]] = i;\n//     }\n\n//     // Solve the equation to segment\n//     segments.resize(n + m, 0);\n//     for (auto s : seed_indices) {\n//         segments[s] = s;\n//     }\n//     std::vector<FT> max_probabilities(n, static_cast<FT>(-1.0));\n//     Eigen::SparseLU<SpMat> solver;\n//     solver.compute(A);\n//     if (solver.info() != Eigen::Success) {\n//         std::cerr << solver.lastErrorMessage() << std::endl;\n//         return;\n//     }\n//     for (auto i = 0; i < m; ++i) {\n//         Eigen::Matrix<FT, Eigen::Dynamic, 1> b = B.col(i);\n//         Eigen::Matrix<FT, Eigen::Dynamic, 1> x = solver.solve(b);\n//         for (auto j = 0; j < n; ++j) {\n//             if (x(j, 0) > max_probabilities[j]) {\n//                 max_probabilities[j] = x(j, 0);\n//                 segments[inv_ids[j + m]] = seed_indices[i];\n//             }\n//         }\n//     }\n// }\n\n} // namespace Euclid\n", "meta": {"hexsha": "7b8b164bbe8612d54992aa04eba5c8dedf981442", "size": 14249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/Segmentation/src/RandomWalk.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/Segmentation/src/RandomWalk.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/Segmentation/src/RandomWalk.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": 33.9261904762, "max_line_length": 80, "alphanum_fraction": 0.5240367745, "num_tokens": 3869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.537494487471048}}
{"text": "#ifndef PRODUCTQUANTIZER_HPP\n#define PRODUCTQUANTIZER_HPP\n\n#include <Eigen/Dense>\n#include \"../iterator/iterator.hpp\"\n\n/**\n * @brief well known product quantizer\n */\ntemplate<typename T, uint D, uint C, uint P>\nclass productquantizer {\n\n    typedef Eigen::Matrix < T, D / P, 1 > vSegment_t;\n\n    static_assert(D % P == 0, \"dim = 0 mod p failed\");\n    static_assert(C % 2 == 0, \"cells = 0 mod 2 failed\");\n\npublic:\n\n\n    // ================================================================================\n    // Methods\n    // ================================================================================\n\n    productquantizer() {\n        _raw_centroids = new T[C * D];\n        _centroids = Eigen::Map<Eigen::Matrix<T, C, D>>(_raw_centroids, C, D);\n    }\n\n    ~productquantizer() {\n        delete[] _raw_centroids;\n    }\n\n    /**\n     * @brief expectation step of Lloyd-iteration\n     * @details assign each given vector from the iterator to coarse cluster part-wise\n     *\n     * @param iter [description]\n     */\n    void getAssignment(iterator<T, D> &iter) {\n        // for each vector ...\n        for (uint n = 0, n_e = iter.num(); n < n_e; ++n) {\n            // for each part ...\n            for (uint p = 0; p < P; ++p) {\n                // extract part of base_vector\n                vSegment_t vec = iter[n].segment(p * S, S);\n\n                // find minimum\n                uint bestIdx = 0;\n                T bestDist = HUGE_VAL;\n\n                // for each cluster\n                for (uint c = 0, c_e = _step; c < c_e; ++c) {\n                    vSegment_t cec = _centroids.row(c).segment(p * S, S);\n                    T curDist = (vec - cec).squaredNorm();\n                    if ( curDist  < bestDist ) {\n                        bestDist = curDist;\n                        bestIdx = c;\n                    }\n                }\n\n                _mapping[n * P + p] = bestIdx;\n                _distances[n * P + p] = bestDist;\n            }\n        }\n    }\n\n    /**\n     * @brief maximization step of Lloyd-iteration\n     * @details centroids should be the mean of all cluster vectors\n     *\n     * @param iter [description]\n     */\n    void updateCentroids(iterator<T, D> &iter) {\n        _centroids = Eigen::Matrix<T, C, D>::Zero(C, D);\n        T centerCounter[C * P] = {0};\n        // find mean\n        for (uint n = 0, n_e = iter.num(); n < n_e; ++n) {\n            for (uint p = 0; p < P; ++p) {\n                const uint c = _mapping[n * P + p];\n                _centroids.row(c).segment(p * S, S) += iter[n].segment(p * S, S);\n                ++centerCounter[p * C + c ];\n            }\n        }\n        for (uint c = 0; c < C; ++c) {\n            for (uint p = 0; p < P; ++p) {\n                if (centerCounter[p * C + c] != 0)\n                    _centroids.row(c).segment(p * S, S).array() /= static_cast<T>(centerCounter[p * C + c]);\n            }\n        }\n    }\n\n    /**\n     * @brief split each centroid +- eps\n     * @details [long description]\n     */\n    void augmentCentroids() {\n        for (uint i = 0; i < _step; ++i) {\n            _centroids.row(i + _step) = _centroids.row(i).array() + 0.001;\n            _centroids.row(i) = _centroids.row(i).array() - 0.001;\n        }\n        _step *= 2;\n    }\n\n    /**\n     * @brief compute squared loss as distorsion distances\n     * @details [long description]\n     *\n     * @param iter [description]\n     * @return squared loss\n     */\n    T loss(iterator<T, D> &iter) {\n        T sum = 0;\n        const uint N = iter.num() * P;\n\n        #pragma omp parallel for reduction(+:sum)\n        for (uint i = 0; i < N; ++i) {\n            sum += _distances[i];\n        }\n        return sum;\n        // Eigen::MatrixXf l = Eigen::Map<  Eigen::MatrixXf >(_distances, iter.num(), P);\n        // return l.sum();\n    }\n\n    /**\n     * @brief start k-means\n     * @details [long description]\n     *\n     * @param iter vector collection that be be clusterized\n     */\n    void generate(iterator<T, D> &iter) {\n        _step = 1;\n\n        _mapping = new uint8_t[iter.num()*P]();\n        _distances = new T[iter.num()*P]();\n\n        \n        _centroids.row(0) = iter.center();\n\n        T currentLoss = 0.0;\n        T lastLoss    = 0.0;\n\n\n        do {\n            uint run = 1000;\n            augmentCentroids();\n            do {\n                lastLoss = currentLoss;\n                getAssignment(iter);    // E step\n                updateCentroids(iter);  // M step\n                currentLoss = loss(iter);\n                //std::cout << \"loss \"<<currentLoss<<std::endl;\n                run--;\n            } while (  (abs(lastLoss - currentLoss) >   0.005) && (run > 0) );\n        } while (_step < C );\n\n\n    }\n\n    // ================================================================================\n    // Variables\n    // ================================================================================\n\n    const uint S = D / P;\n    T* _raw_centroids;\n    Eigen::Matrix<T, C, D> _centroids;  // centroids of all clusters\n    uint _step;                         // current number of centroids\n    uint8_t *_mapping;                  // current mapping of all vectors from iter\n    T *_distances;                      // current distorsion sq. distances between iter and centroids\n\n};\n\n#endif", "meta": {"hexsha": "90232c3a11fff83ed812c509167d112c7c95c635", "size": 5257, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpu_version/quantizer/productquantizer.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/quantizer/productquantizer.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/quantizer/productquantizer.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": 30.387283237, "max_line_length": 108, "alphanum_fraction": 0.4512079133, "num_tokens": 1327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5374261728615509}}
{"text": "//\n//  IglUtils.hpp\n//  DOT\n//\n//  Created by Minchen Li on 8/30/17.\n//\n\n#ifndef IglUtils_hpp\n#define IglUtils_hpp\n\n#include \"Mesh.hpp\"\n\n#ifdef USE_CLOSEDFORMSVD2D\n#include \"ClosedFormSVD2d.hpp\"\n#else\n#include \"AutoFlipSVD.hpp\"\n#endif\n\n#include \"LinSysSolver.hpp\"\n\n#include <Eigen/Eigen>\n\n#include <iostream>\n#include <fstream>\n\nnamespace DOT {\n    \n    // a static class implementing basic geometry processing operations that are not provided in libIgl\n    class IglUtils {\n\n    public:\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    public:\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        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        template<int blockSize, int indexSize>\n        static void addBlockToMatrix(const Eigen::Matrix<double, blockSize, blockSize>& block,\n                                     const Eigen::Matrix<int, indexSize, 1>& index,\n                                     int dim, Eigen::VectorXd* V,\n                                     Eigen::VectorXi* I = NULL,\n                                     Eigen::VectorXi* J = NULL)\n        {\n            assert(indexSize * dim == blockSize);\n            \n            int num_free = 0;\n            for(int indI = 0; indI < indexSize; indI++) {\n                if(index[indI] >= 0) {\n                    num_free++;\n                }\n            }\n            if(!num_free) {\n                return;\n            }\n            \n            assert(V);\n            int tripletInd = static_cast<int>(V->size());\n            const int entryAmt = static_cast<int>(dim * dim * num_free * num_free);\n            V->conservativeResize(tripletInd + entryAmt);\n            if(I) {\n                assert(J);\n                assert(I->size() == tripletInd);\n                assert(J->size() == tripletInd);\n                I->conservativeResize(tripletInd + entryAmt);\n                J->conservativeResize(tripletInd + entryAmt);\n            }\n            \n            for(int indI = 0; indI < indexSize; indI++) {\n                if(index[indI] < 0) {\n                    continue;\n                }\n                int startIndI = index[indI] * dim;\n                int startIndI_block = indI * dim;\n                \n                for(int indJ = 0; indJ < indexSize; indJ++) {\n                    if(index[indJ] < 0) {\n                        continue;\n                    }\n                    int startIndJ = index[indJ] * dim;\n                    int startIndJ_block = indJ * dim;\n                    \n                    for(int dimI = 0; dimI < dim; dimI++) {\n                        for(int dimJ = 0; dimJ < dim; dimJ++) {\n                            (*V)[tripletInd] = block(startIndI_block + dimI, startIndJ_block + dimJ);\n                            if(I) {\n                                (*I)[tripletInd] = startIndI + dimI;\n                                (*J)[tripletInd] = startIndJ + dimJ;\n                            }\n                            tripletInd++;\n                        }\n                    }\n                }\n            }\n            assert(tripletInd == V->size());\n        }\n        static void addDiagonalToMatrix(const Eigen::VectorXd& diagonal,\n                                        const Eigen::VectorXi& index,\n                                        int dim, Eigen::VectorXd* V,\n                                        Eigen::VectorXi* I = NULL,\n                                        Eigen::VectorXi* J = NULL);\n        template<int dim>\n        static void addBlockToMatrix(const Eigen::Matrix<double, dim, dim * (dim + 1)>& block,\n                                     const Eigen::Matrix<int, 1, dim + 1>& index, int rowIndI,\n                                     Eigen::MatrixXd& hessian)\n        {\n            int rowStart = index[rowIndI] * dim;\n            if(rowStart < 0) {\n                rowStart = -rowStart - dim;\n                hessian.diagonal().segment(rowStart, dim).setOnes();\n                return;\n            }\n            \n            if(index[0] >= 0) {\n                int _dimIndex0 = index[0] * dim;\n                hessian.block<dim, dim>(rowStart, _dimIndex0) += block.block(0, 0, dim, dim);\n            }\n            \n            if(index[1] >= 0) {\n                int _dimIndex1 = index[1] * dim;\n                hessian.block<dim, dim>(rowStart, _dimIndex1) += block.block(0, dim, dim, dim);\n            }\n            \n            if(index[2] >= 0) {\n                int _2dim = 2 * dim;\n                int _dimIndex2 = index[2] * dim;\n                hessian.block<dim, dim>(rowStart, _dimIndex2) += block.block(0, _2dim, dim, dim);\n            }\n            \n            if(dim == 3) {\n                if(index[3] >= 0) {\n                    int _3dim = 3 * dim;\n                    int _dimIndex3 = index[3] * dim;\n                    hessian.block<dim, dim>(rowStart, _dimIndex3) += block.block(0, _3dim, dim, dim);\n                }\n            }\n        }\n        template<int dim>\n        static void addBlockToMatrix(const Eigen::Matrix<double, dim, dim * (dim + 1)>& block,\n                                     const Eigen::Matrix<int, 1, dim + 1>& index, int rowIndI,\n                                     LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* linSysSolver)\n        {\n            int rowStart = index[rowIndI] * dim;\n            if(rowStart < 0) {\n                rowStart = -rowStart - dim;\n                linSysSolver->setCoeff(rowStart, rowStart, 1.0);\n                linSysSolver->setCoeff(rowStart + 1, rowStart + 1, 1.0);\n                if(dim == 3) {\n                    linSysSolver->setCoeff(rowStart + 2, rowStart + 2, 1.0);\n                }\n                return;\n            }\n            \n            if(index[0] >= 0) {\n                int _dimIndex0 = index[0] * dim;\n                linSysSolver->addCoeff(rowStart, _dimIndex0, block(0, 0));\n                linSysSolver->addCoeff(rowStart, _dimIndex0 + 1, block(0, 1));\n                linSysSolver->addCoeff(rowStart + 1, _dimIndex0, block(1, 0));\n                linSysSolver->addCoeff(rowStart + 1, _dimIndex0 + 1, block(1, 1));\n                if(dim == 3) {\n                    linSysSolver->addCoeff(rowStart, _dimIndex0 + 2, block(0, 2));\n                    linSysSolver->addCoeff(rowStart + 1, _dimIndex0 + 2, block(1, 2));\n                    linSysSolver->addCoeff(rowStart + 2, _dimIndex0, block(2, 0));\n                    linSysSolver->addCoeff(rowStart + 2, _dimIndex0 + 1, block(2, 1));\n                    linSysSolver->addCoeff(rowStart + 2, _dimIndex0 + 2, block(2, 2));\n                }\n            }\n            \n            if(index[1] >= 0) {\n                int _dimIndex1 = index[1] * dim;\n                linSysSolver->addCoeff(rowStart, _dimIndex1, block(0, dim));\n                linSysSolver->addCoeff(rowStart, _dimIndex1 + 1, block(0, dim + 1));\n                linSysSolver->addCoeff(rowStart + 1, _dimIndex1, block(1, dim));\n                linSysSolver->addCoeff(rowStart + 1, _dimIndex1 + 1, block(1, dim + 1));\n                if(dim == 3) {\n                    linSysSolver->addCoeff(rowStart, _dimIndex1 + 2, block(0, dim + 2));\n                    linSysSolver->addCoeff(rowStart + 1, _dimIndex1 + 2, block(1, dim + 2));\n                    linSysSolver->addCoeff(rowStart + 2, _dimIndex1, block(2, dim));\n                    linSysSolver->addCoeff(rowStart + 2, _dimIndex1 + 1, block(2, dim + 1));\n                    linSysSolver->addCoeff(rowStart + 2, _dimIndex1 + 2, block(2, dim + 2));\n                }\n            }\n            \n            if(index[2] >= 0) {\n                int _2dim = 2 * dim;\n                int _dimIndex2 = index[2] * dim;\n                linSysSolver->addCoeff(rowStart, _dimIndex2, block(0, _2dim));\n                linSysSolver->addCoeff(rowStart, _dimIndex2 + 1, block(0, _2dim + 1));\n                linSysSolver->addCoeff(rowStart + 1, _dimIndex2, block(1, _2dim));\n                linSysSolver->addCoeff(rowStart + 1, _dimIndex2 + 1, block(1, _2dim + 1));\n                if(dim == 3) {\n                    linSysSolver->addCoeff(rowStart, _dimIndex2 + 2, block(0, _2dim + 2));\n                    linSysSolver->addCoeff(rowStart + 1, _dimIndex2 + 2, block(1, _2dim + 2));\n                    linSysSolver->addCoeff(rowStart + 2, _dimIndex2, block(2, _2dim));\n                    linSysSolver->addCoeff(rowStart + 2, _dimIndex2 + 1, block(2, _2dim + 1));\n                    linSysSolver->addCoeff(rowStart + 2, _dimIndex2 + 2, block(2, _2dim + 2));\n                }\n            }\n            \n            if(dim == 3) {\n                if(index[3] >= 0) {\n                    int _3dim = 3 * dim;\n                    int _dimIndex3 = index[3] * dim;\n                    linSysSolver->addCoeff(rowStart, _dimIndex3, block(0, _3dim));\n                    linSysSolver->addCoeff(rowStart, _dimIndex3 + 1, block(0, _3dim + 1));\n                    linSysSolver->addCoeff(rowStart, _dimIndex3 + 2, block(0, _3dim + 2));\n                    linSysSolver->addCoeff(rowStart + 1, _dimIndex3, block(1, _3dim));\n                    linSysSolver->addCoeff(rowStart + 1, _dimIndex3 + 1, block(1, _3dim + 1));\n                    linSysSolver->addCoeff(rowStart + 1, _dimIndex3 + 2, block(1, _3dim + 2));\n                    linSysSolver->addCoeff(rowStart + 2, _dimIndex3, block(2, _3dim));\n                    linSysSolver->addCoeff(rowStart + 2, _dimIndex3 + 1, block(2, _3dim + 1));\n                    linSysSolver->addCoeff(rowStart + 2, _dimIndex3 + 2, block(2, _3dim + 2));\n                }\n            }\n        }\n        template<int dim>\n        static void addIdBlockToMatrixDiag(const Eigen::VectorXi& index,\n                                           LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* linSysSolver)\n        {\n            for(int indI = 0; indI < index.size(); indI++) {\n                int rowStart = index[indI] * dim;\n                assert(rowStart >= 0);\n                linSysSolver->addCoeff(rowStart, rowStart, 1.0);\n                linSysSolver->addCoeff(rowStart + 1, rowStart + 1, 1.0);\n                if(dim == 3) {\n                    linSysSolver->addCoeff(rowStart + 2, rowStart + 2, 1.0);\n                }\n            }\n        }\n        \n        template<typename Scalar, int size>\n        static void symmetrizeMatrix(Eigen::Matrix<Scalar, size, size>& mtr) {\n            if(size == Eigen::Dynamic) {\n                assert(mtr.rows() == mtr.cols());\n            }\n            int rows = ((size == Eigen::Dynamic) ? mtr.rows() : size);\n            \n            for(int rowI = 0; rowI < rows; rowI++) {\n                for(int colI = rowI + 1; colI < rows; 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            for(int i = 0; i < rows; i++) {\n                if(D.diagonal()[i] < 0.0) {\n                    D.diagonal()[i] = 0.0;\n                }\n                else {\n                    break;\n                }\n            }\n            symMtr = eigenSolver.eigenvectors() * D * eigenSolver.eigenvectors().transpose();\n        }\n        template<typename Scalar, int size>\n        static void makePD2d(Eigen::Matrix<Scalar, size, size>& symMtr)\n        {\n            // based on http://www.math.harvard.edu/archive/21b_fall_04/exhibits/2dmatrices/\n            \n            if(size == Eigen::Dynamic) {\n                assert(symMtr.rows() == 2);\n            }\n            else {\n                assert(size == 2);\n            }\n            \n            const double a = symMtr(0, 0);\n            const double b = (symMtr(0, 1) + symMtr(1, 0)) / 2.0;\n            const double d = symMtr(1, 1);\n            \n            double b2 = b * b;\n            const double D = a * d - b2;\n            const double T_div_2 = (a + d) / 2.0;\n            const double sqrtTT4D = std::sqrt(T_div_2 * T_div_2 - D);\n            const double L2 = T_div_2 - sqrtTT4D;\n            if(L2 < 0.0) {\n                const double L1 = T_div_2 + sqrtTT4D;\n                if(L1 <= 0.0) {\n                    symMtr.setZero();\n                }\n                else {\n                    if(b2 == 0.0) {\n                        symMtr << L1, 0.0, 0.0 ,0.0;\n                    }\n                    else {\n                        const double L1md = L1 - d;\n                        const double L1md_div_L1 = L1md / L1;\n                        symMtr(0, 0) = L1md_div_L1 * L1md;\n                        symMtr(0, 1) = symMtr(1, 0) = b * L1md_div_L1;\n                        symMtr(1, 1) = b2 / L1;\n                    }\n                }\n            }\n        }\n        template<typename Scalar, int size>\n        static void flipDet_SVD(Eigen::Matrix<Scalar, size, size>& mtr) {\n            Eigen::JacobiSVD<Eigen::Matrix<Scalar, size, size>> svd(mtr, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n            Eigen::Matrix<Scalar, size, size> U = svd.matrixU(), V = svd.matrixV();\n            if(U.determinant() < 0) {\n                U.col(U.cols() - 1) *= -1.0;\n            }\n            if(V.determinant() < 0) {\n                V.col(V.cols() - 1) *= -1.0;\n            }\n            mtr = U * Eigen::DiagonalMatrix<Scalar, size>(svd.singularValues()) * V.transpose();\n        }\n        \n        static void writeSparseMatrixToFile(const std::string& filePath,\n                                            const Eigen::SparseMatrix<double>& mtr,\n                                            bool MATLAB = false);\n        static void writeSparseMatrixToFile(const std::string& filePath,\n                                            const Eigen::VectorXi& I, const Eigen::VectorXi& J,\n                                            const Eigen::VectorXd& V, bool MATLAB = false);\n        static void writeSparseMatrixToFile(const std::string& filePath,\n                                            const std::map<std::pair<int, int>, double>& mtr,\n                                            bool MATLAB = false);\n        static void writeSparseMatrixToFile(const std::string& filePath,\n                                            LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* linSysSolver,\n                                            bool MATLAB = false);\n        static void writeDenseMatrixToFile(const std::string& filePath,\n                                           const Eigen::MatrixXd& matrix,\n                                           bool MATLAB = false);\n        static void loadSparseMatrixFromFile(const std::string& filePath,\n                                             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 void writeVectorToFile(const std::string& filePath,\n                                      const Eigen::VectorXd& vec);\n        static void readVectorFromFile(const std::string& filePath,\n                                       Eigen::VectorXd& vec);\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 findSurfaceTris(const Eigen::MatrixXi& TT, Eigen::MatrixXi& F);\n        static void buildSTri2Tet(const Eigen::MatrixXi& F, const Eigen::MatrixXi& SF,\n                                  std::vector<int>& sTri2Tet);\n        \n        static void saveTetMesh(const std::string& filePath,\n                                const Eigen::MatrixXd& TV, const Eigen::MatrixXi& TT,\n                                const Eigen::MatrixXi& F = Eigen::MatrixXi(),\n                                bool findSurface = true);\n        static bool readTetMesh(const std::string& filePath,\n                                Eigen::MatrixXd& TV, Eigen::MatrixXi& TT,\n                                Eigen::MatrixXi& F, bool findSurface = true);\n        static void readNodeEle(const std::string& filePath,\n                                Eigen::MatrixXd& TV, Eigen::MatrixXi& TT,\n                                Eigen::MatrixXi& F);\n        \n        static void smoothVertField(const Mesh<DIM>& mesh, Eigen::VectorXd& field);\n        \n        static void compute_dF_div_dx(const Eigen::Matrix<double, DIM, DIM>& A,\n                                      Eigen::Matrix<double, DIM * (DIM + 1), DIM * DIM>& dF_div_dx);\n        template<int colSize>\n        static void dF_div_dx_mult(const Eigen::Matrix<double, DIM * DIM, colSize>& right,\n                                   const Eigen::Matrix<double, DIM, DIM>& A,\n                                   Eigen::Matrix<double, DIM * (DIM + 1), colSize>& result,\n                                   bool symmetric)\n        {\n            if(colSize == Eigen::Dynamic) {\n                assert(right.cols() > 0);\n            }\n            else {\n                assert(colSize > 0);\n            }\n#if(DIM == 2)\n            if(symmetric) {\n                if(colSize == Eigen::Dynamic) {\n                    assert(right.cols() == 6);\n                }\n                else {\n                    assert(colSize == 6);\n                }\n                // int colI = 0;\n                const double _0000 = right(0, 0) * A(0, 0);\n                const double _0010 = right(0, 0) * A(1, 0);\n                const double _1001 = right(1, 0) * A(0, 1);\n                const double _1011 = right(1, 0) * A(1, 1);\n                const double _2000 = right(2, 0) * A(0, 0);\n                const double _2010 = right(2, 0) * A(1, 0);\n                const double _3001 = right(3, 0) * A(0, 1);\n                const double _3011 = right(3, 0) * A(1, 1);\n                result(2, 0) = result(0, 2) = _0000 + _1001;\n                result(3, 0) = result(0, 3) = _2000 + _3001;\n                result(4, 0) = result(0, 4) = _0010 + _1011;\n                result(5, 0) = result(0, 5) = _2010 + _3011;\n                result(0, 0) = -result(2, 0) - result(4, 0);\n                result(1, 0) = result(0, 1) = -result(3, 0) - result(5, 0);\n                // colI = 1;\n                const double _2100 = right(2, 1) * A(0, 0);\n                const double _2110 = right(2, 1) * A(1, 0);\n                const double _3101 = right(3, 1) * A(0, 1);\n                const double _3111 = right(3, 1) * A(1, 1);\n                result(2, 1) = result(1, 2) = right(0, 1) * A(0, 0) + right(1, 1) * A(0, 1);\n                result(3, 1) = result(1, 3) = _2100 + _3101;\n                result(4, 1) = result(1, 4) = right(0, 1) * A(1, 0) + right(1, 1) * A(1, 1);\n                result(5, 1) = result(1, 5) = _2110 + _3111;\n                result(1, 1) = -result(3, 1) - result(5, 1);\n                // colI = 2;\n                result(2, 2) = right(0, 2) * A(0, 0) + right(1, 2) * A(0, 1);\n                result(3, 2) = result(2, 3) = right(2, 2) * A(0, 0) + right(3, 2) * A(0, 1);\n                result(4, 2) = result(2, 4) = right(0, 2) * A(1, 0) + right(1, 2) * A(1, 1);\n                result(5, 2) = result(2, 5) = right(2, 2) * A(1, 0) + right(3, 2) * A(1, 1);\n                // colI = 3;\n                result(3, 3) = right(2, 3) * A(0, 0) + right(3, 3) * A(0, 1);\n                result(4, 3) = result(3, 4) = right(0, 3) * A(1, 0) + right(1, 3) * A(1, 1);\n                result(5, 3) = result(3, 5) = right(2, 3) * A(1, 0) + right(3, 3) * A(1, 1);\n                // colI = 4;\n                result(4, 4) = right(0, 4) * A(1, 0) + right(1, 4) * A(1, 1),\n                result(5, 4) = result(4, 5) = right(2, 4) * A(1, 0) + right(3, 4) * A(1, 1);\n                // colI = 5;\n                result(5, 5) = right(2, 5) * A(1, 0) + right(3, 5) * A(1, 1);\n            }\n            else {\n                for(int colI = 0; colI < right.cols(); colI++) {\n                    const double _000 = right(0, colI) * A(0, 0);\n                    const double _010 = right(0, colI) * A(1, 0);\n                    const double _101 = right(1, colI) * A(0, 1);\n                    const double _111 = right(1, colI) * A(1, 1);\n                    const double _200 = right(2, colI) * A(0, 0);\n                    const double _210 = right(2, colI) * A(1, 0);\n                    const double _301 = right(3, colI) * A(0, 1);\n                    const double _311 = right(3, colI) * A(1, 1);\n                    \n                    result(2, colI) = _000 + _101;\n                    result(3, colI) = _200 + _301;\n                    result(4, colI) = _010 + _111;\n                    result(5, colI) = _210 + _311;\n                    result(0, colI) = -result(2, colI) - result(4, colI);\n                    result(1, colI) = -result(3, colI) - result(5, colI);\n                }\n            }\n#else\n            //TODO: use symmetric\n            for(int colI = 0; colI < right.cols(); colI++) {\n                result(3, colI) = (A.row(0) * right.block(0, colI, DIM, 1))[0];\n                result(4, colI) = (A.row(0) * right.block(DIM, colI, DIM, 1))[0];\n                result(5, colI) = (A.row(0) * right.block(DIM * 2, colI, DIM, 1))[0];\n                result(6, colI) = (A.row(1) * right.block(0, colI, DIM, 1))[0];\n                result(7, colI) = (A.row(1) * right.block(DIM, colI, DIM, 1))[0];\n                result(8, colI) = (A.row(1) * right.block(DIM * 2, colI, DIM, 1))[0];\n                result(9, colI) = (A.row(2) * right.block(0, colI, DIM, 1))[0];\n                result(10, colI) = (A.row(2) * right.block(DIM, colI, DIM, 1))[0];\n                result(11, colI) = (A.row(2) * right.block(DIM * 2, colI, DIM, 1))[0];\n                result(0, colI) = - result(3, colI) - result(6, colI) - result(9, colI);\n                result(1, colI) = - result(4, colI) - result(7, colI) - result(10, colI);\n                result(2, colI) = - result(5, colI) - result(8, colI) - result(11, colI);\n            }\n#endif\n        }\n        static void dF_div_dx_mult(const Eigen::Matrix<double, DIM, DIM>& right,\n                                   const Eigen::Matrix<double, DIM, DIM>& A,\n                                   Eigen::Matrix<double, DIM * (DIM + 1), 1>& result);\n        template<int dim>\n        static void computeCofactorMtr(const Eigen::Matrix<double, dim, dim>& F,\n                                       Eigen::Matrix<double, dim, dim>& A)\n        {\n            switch(dim) {\n                case 2:\n                    A(0, 0) = F(1, 1);\n                    A(0, 1) = -F(1, 0);\n                    A(1, 0) = -F(0, 1);\n                    A(1, 1) = F(0, 0);\n                    break;\n                    \n                case 3:\n                    A(0, 0) = F(1, 1) * F(2, 2) - F(1, 2) * F(2, 1);\n                    A(0, 1) = F(1, 2) * F(2, 0) - F(1, 0) * F(2, 2);\n                    A(0, 2) = F(1, 0) * F(2, 1) - F(1, 1) * F(2, 0);\n                    A(1, 0) = F(0, 2) * F(2, 1) - F(0, 1) * F(2, 2);\n                    A(1, 1) = F(0, 0) * F(2, 2) - F(0, 2) * F(2, 0);\n                    A(1, 2) = F(0, 1) * F(2, 0) - F(0, 0) * F(2, 1);\n                    A(2, 0) = F(0, 1) * F(1, 2) - F(0, 2) * F(1, 1);\n                    A(2, 1) = F(0, 2) * F(1, 0) - F(0, 0) * F(1, 2);\n                    A(2, 2) = F(0, 0) * F(1, 1) - F(0, 1) * F(1, 0);\n                    break;\n                    \n                default:\n                    assert(0 && \"dim not 2 or 3\");\n                    break;\n            }\n        }\n        \n        static void extractRotation(const Eigen::Matrix3d &A,\n                                    Eigen::Quaterniond &q,\n                                    const unsigned int maxIter);\n        \n        static void sampleSegment(const Eigen::RowVectorXd& vs,\n                                  const Eigen::RowVectorXd& ve,\n                                  double spacing,\n                                  Eigen::MatrixXd& inBetween);\n        \n        static void findBorderVerts(const Eigen::MatrixXd& V,\n                                    std::vector<std::vector<int>>& borderVerts,\n                                    double ratio);\n\n        static void computeSVD_SIMD(std::vector<Eigen::Matrix3d>& testF,\n                                    std::vector<Eigen::Matrix3d>& U, std::vector<Eigen::Vector3d>& Sigma, std::vector<Eigen::Matrix3d>& V);\n\n        static void matrixProduct(const std::vector<Eigen::Matrix3d>& left,\n                                  const std::vector<Eigen::Matrix3d>& right,\n                                  std::vector<Eigen::Matrix3d>& result);\n\n        static void matrixVectorMatrixTProduct(const std::vector<Eigen::Matrix3d>& left,\n                                                const std::vector<Eigen::Vector3d>& vec,\n                                                const std::vector<Eigen::Matrix3d>& right,\n                                                std::vector<Eigen::Matrix3d>& result);\n    };\n\n}\n\n#endif /* IglUtils_hpp */\n", "meta": {"hexsha": "f4e35a2cf77f4705b53dd3f5d087a34acd4d7914", "size": 26918, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Utils/IglUtils.hpp", "max_stars_repo_name": "liminchen/DOT", "max_stars_repo_head_hexsha": "26525fba815fb081e90676321e42d0a60ecb0cb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T00:43:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-25T14:35:54.000Z", "max_issues_repo_path": "src/Utils/IglUtils.hpp", "max_issues_repo_name": "liminchen/DOT", "max_issues_repo_head_hexsha": "26525fba815fb081e90676321e42d0a60ecb0cb1", "max_issues_repo_licenses": ["MIT"], "max_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/IglUtils.hpp", "max_forks_repo_name": "liminchen/DOT", "max_forks_repo_head_hexsha": "26525fba815fb081e90676321e42d0a60ecb0cb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-27T05:19:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-23T22:49:53.000Z", "avg_line_length": 49.4816176471, "max_line_length": 139, "alphanum_fraction": 0.4484731406, "num_tokens": 7310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.537290711805671}}
{"text": "#define BOOST_TEST_MODULE pcraster geo point\n#include <boost/test/unit_test.hpp>\n#include <algorithm>\n#include \"geo_point.h\"\n\n\nBOOST_AUTO_TEST_CASE(layout)\n{\n  using namespace geo;\n\n  // assure size of point is equal to\n  // the vector of coordinates\n {\n  typedef Point<float,2> Punt;\n  BOOST_CHECK(sizeof(Punt)==8);\n }\n {\n  typedef Point<double,3> Punt;\n  BOOST_CHECK(sizeof(Punt)==24);\n }\n}\n\n\nBOOST_AUTO_TEST_CASE(index_direction)\n{\n  using namespace geo;\n\n {\n  //  1D:\n  //          0\n  //    <  1 -c- >= 0\n  typedef Point<float,1> Punt;\n  Punt c,p;\n  c[0]=0;\n\n  p[0]=-1;\n  BOOST_CHECK(p.indexDirection(c) == 1);\n  p[0]=1;\n  BOOST_CHECK(p.indexDirection(c) == 0);\n  p[0]=0;\n  BOOST_CHECK(p.indexDirection(c) == 0);\n }\n {\n /*  2D:\n  *   NW 1(b) | NE 0(a)\n  *           0(e)\n  *  1(h)-----C---------0(g)\n  *   SW 3(c) | SE 2(d)\n  *           2(f)\n  */\n  typedef Point<float,2> Punt;\n  Punt c,p;\n  c[0]=c[1]=0;\n  p[0]=p[1]=1;\n  BOOST_CHECK(p.indexDirection(c) == 0); // a\n  p[0]=-1;\n  BOOST_CHECK(p.indexDirection(c) == 1); // b\n  p[0]=p[1]=-1;\n  BOOST_CHECK(p.indexDirection(c) == 3); // c\n  p[0]=1;\n  BOOST_CHECK(p.indexDirection(c) == 2); // d\n\n  p[0]=0;p[1]=1;\n  BOOST_CHECK(p.indexDirection(c) == 0); // e\n  p[0]=0;p[1]=-1;\n  BOOST_CHECK(p.indexDirection(c) == 2); // f\n  p[0]=1;p[1]=0;\n  BOOST_CHECK(p.indexDirection(c) == 0); // g\n  p[0]=-1;p[1]=0;\n  BOOST_CHECK(p.indexDirection(c) == 1); // h\n }\n}\n\n\nBOOST_AUTO_TEST_CASE(closer)\n{\n  using namespace geo;\n\n  typedef Point<float,2> P;\n  typedef Closer<P>      C;\n\n  C c(P(-5,0));\n\n  BOOST_CHECK( c(P(1,0),P(2,0)));\n  BOOST_CHECK(!c(P(2,0),P(1,0)));\n\n  std::vector<P> l;\n  l.push_back(P(2,0));\n  l.push_back(P(1,0));\n\n  BOOST_CHECK(l[0][X]==2);\n  BOOST_CHECK(l[1][X]==1);\n  std::sort(l.begin(),l.end(), C(P(-5,0)));\n  BOOST_CHECK(l[0][X]==1);\n  BOOST_CHECK(l[1][X]==2);\n  // reverse\n  std::sort(l.begin(),l.end(), std::not2(c));\n  BOOST_CHECK(l[0][X]==2);\n  BOOST_CHECK(l[1][X]==1);\n}\n\n\nBOOST_AUTO_TEST_CASE(distance)\n{\n  using namespace geo;\n\n  typedef Point<float,2> P;\n\n  // test compilation of enum\n  BOOST_CHECK(P::Dim == 2);\n\n  P p1(2,20),p2(3,21);\n  BOOST_CHECK(p1.squaredDistance(p2) == 2);\n  double d=p1.distance(p2);\n  BOOST_CHECK(d>1.4 && d<1.43); // sqrt(2)\n}\n", "meta": {"hexsha": "6005383e6f921dd15ef8d20b2db91c21b69fbd65", "size": 2228, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_pointtest.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_pointtest.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_pointtest.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["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.0427350427, "max_line_length": 45, "alphanum_fraction": 0.5736086176, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.537290711805671}}
{"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, log2_fun) {\n  using stan::math::log2;\n\n  EXPECT_FLOAT_EQ(std::log(2.0), log2());\n}\n\nTEST(MathFunctions, log2) {\n  using stan::math::log2;\n\n  EXPECT_FLOAT_EQ(1.0, log2(2.0));\n  EXPECT_FLOAT_EQ(2.0, log2(4.0));\n  EXPECT_FLOAT_EQ(3.0, log2(8.0));\n}\n\nTEST(MathFunctions, log2_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::log2(nan));\n}\n", "meta": {"hexsha": "8d42b05fd08632ae6d9d742243e6be1844b90e81", "size": 560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/log2_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/log2_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/log2_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": 22.4, "max_line_length": 66, "alphanum_fraction": 0.7, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5372907009517243}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// survival::modelss::exponential::scalar::model.hpp                   \t\t //\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_DISTRIBUTION_SURVIVAL_MODELS_EXPONENTIAL_SCALAR_MODEL_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_EXPONENTIAL_SCALAR_MODEL_HPP_ER_2009\n#include <boost/operators.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/statistics/detail/mpl/nested_type.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/exponential/include.hpp>\n#include <boost/statistics/detail/distribution/survival/models/exponential/scalar/log_rate/identity/identity.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace distribution{\nnamespace survival{\n\n    // TODO add an error policy\n\n    template<\n        typename T, \n        typename L = exponential_model_::log_rate::identity<T>, \n        typename Err = boost::math::policies::policy<>\n    >\n    class exponential_model : L{\n    \t// TODO Err\n\n        public:\n        typedef T value_type;\n\n        //typedef exponential_model<T,L> distribution_type;\n    \n        exponential_model():L(){}\n        exponential_model(const exponential_model& that) \n            : L(static_cast<const L&>(that)),b_(that.b_){}\n        exponential_model& operator=(const exponential_model& that)\n        {\n            if(&that!=this)\n            {\n                static_cast<L&>(*this) = static_cast<const L&>(that);\n                b_ = that.b_;\n            }\n            return (*this);\n        }\n                \n        template<typename X>\n        T log_rate(const X& x)const\n        {\n            T cross_prod =  static_cast<T>( x );\n            cross_prod *= this->parameter() ;\n            return this->log_rate_impl( cross_prod );\n        }\n\n        const T& parameter()const{ return this-> b_; }\n        template<typename B>\n        void set_parameter(const B& b)const{ this->b_ = b; }\n\n        protected:\n\n        friend class boost::serialization::access;\n        template<class Archive>\n        void serialize(Archive & ar, const unsigned int version){\n            ar & b_;\n        }\n\n        mutable T b_;\n    };\n\n}// survival\n}// distribution\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "bc60a29771f2b36f801a9a297e30ead7425ae8e7", "size": 2787, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/model.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_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/model.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_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/model.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.4074074074, "max_line_length": 113, "alphanum_fraction": 0.584140653, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5372271096344234}}
{"text": "#include \"OccupancyGrid/occgrid.hpp\"\n#include \"OccupancyGrid/cvmat_serialization.h\"\n#include <opencv2/opencv.hpp>\n#include <boost/format.hpp>\n\n/// Override class to override is_occupied function so that it can copy the\n/// ground truth map everytime a laser crosses a cell.\ntemplate<typename real_t, typename int_t>\nclass OccupancyGrid2DInverseSensor : public OccupancyGrid2D<real_t, int_t> {\n  public:\n    using OccupancyGrid2D<real_t, int_t>::og_;\n    using OccupancyGrid2D<real_t, int_t>::cell_size_;\n    using OccupancyGrid2D<real_t, int_t>::min_pt_;\n    using OccupancyGrid2D<real_t, int_t>::FREE;\n    int_t observed_manh_range_;\n    cv::Vec<int_t, 2> robot_position_;\n    cv::Mat_<real_t> log_odds_map_;\n    const real_t LOG_ODDS_OCCUPIED;\n    const real_t LOG_ODDS_FREE;\n\n    OccupancyGrid2DInverseSensor(real_t min_x, real_t min_y, real_t cell_size_x, real_t\n        cell_size_y, int_t ncells_x, int_t ncells_y) :\n      OccupancyGrid2D<real_t, int_t>(min_x, min_y, cell_size_x, cell_size_y,\n          ncells_x, ncells_y),\n      observed_manh_range_(),\n      robot_position_(),\n      log_odds_map_(ncells_x, ncells_y, 0.0L),\n      LOG_ODDS_OCCUPIED(1.3863),\n      LOG_ODDS_FREE(-1.3863)\n    {\n    };\n\n    void set_up_ray_trace(\n        real_t px,\n        real_t py,\n        real_t ptheta,\n        real_t observed_range) {\n        robot_position_(0) = \n            (int)floor((px - min_pt_(0)) / cell_size_(0));\n        robot_position_(1) =\n            (int)floor((py - min_pt_(1)) / cell_size_(1));\n        real_t dx_abs = fabs(cos(ptheta));\n        real_t dy_abs = fabs(sin(ptheta));\n        real_t dmag = sqrt(dx_abs * dx_abs + dy_abs * dy_abs);\n        observed_manh_range_ =\n          floor(observed_range * dx_abs / dmag / cell_size_(0)) +\n          floor(observed_range * dy_abs / dmag / cell_size_(1));\n        //printf(\"-----------------\\n\");\n    }\n    \n    inline int_t manh_distance(int_t i, int_t j) {\n        return std::abs(i - robot_position_(0)) + std::abs(j - robot_position_(1));\n    }\n\n    virtual bool is_occupied(int_t i, int_t j) {\n        uint8_t val = og_.ptr(i)[j];\n        bool retval = (val != FREE);\n        int_t d = manh_distance(i, j);\n        // update step\n        // printf(\"%d < %d\\n\", d, observed_manh_range_);\n        log_odds_map_(i, j) += \n          (d < observed_manh_range_) ?  LOG_ODDS_FREE\n          : (d == observed_manh_range_) ? LOG_ODDS_OCCUPIED\n          : 0; // unknown\n        return retval;\n    }\n\n    inline void show(int r) {\n        cv::Mat vis;\n        cv::exp(log_odds_map_, vis);\n        vis = 1 / (1 + vis);\n        vis *= 255;\n        vis.convertTo(vis, CV_8U);\n        cv::imshow(\"c\", vis);\n        //cv::imwrite((boost::format(\"out-%d.png\") % r).str(), vis);\n        cv::waitKey(1);\n        cv::imwrite(\"/tmp/two_assumption_algo.png\", vis);\n    }\n};\n\nint main(int argc, char** argv) {\n    if (argc != 4) {\n        std::cout << \"Sample Usage:\" << std::endl;\n        std::cout << \"bin/two_assumption_alg Data/player_sim/laser_pose_all.bin Data/player_sim/laser_range_all.bin Data/player_sim/scan_angles_all.bin\" << std::endl;\n        exit(1);\n    }\n    cv::Mat laser_pose;\n    loadMat(laser_pose, argv[1]);\n    cv::Mat laser_ranges;\n    loadMat(laser_ranges, argv[2]);\n    cv::Mat scan_angles;\n    loadMat(scan_angles, argv[3]);\n\n    cv::Vec2d min_pt(-9, -9);\n    cv::Vec2d range = -2 * min_pt;\n    cv::Vec2i gridsize(100, 100);\n    cv::Vec2d cellsize; \n    cv::divide(range, gridsize, cellsize);\n    //std::cout << cellsize(0) << cellsize(1) << std::endl;\n    cv::Vec2i ncells;\n    cv::divide(min_pt, cellsize, ncells, -2);\n\n    //std::cout << ncells(0) << ncells(1) << std::endl;\n\n    OccupancyGrid2DInverseSensor<double, int> map(\n        min_pt(0), \n        min_pt(1),\n        cellsize(0),\n        cellsize(1),\n        ncells(0),\n        ncells(1));\n\n    double MAX_RANGE = 8;\n\n    int r;\n    for (r = 0; r < laser_pose.rows; r++) {\n        double* pose = laser_pose.ptr<double>(r);\n        double* ranges = laser_ranges.ptr<double>(r);\n        double* angles = scan_angles.ptr<double>(r);\n        double robot_angle = pose[2];\n        for (int c = 0; c < scan_angles.cols; c++) {\n            double total_angle = robot_angle + angles[c];\n            cv::Vec2d final_pos;\n            map.set_up_ray_trace(pose[0], pose[1], total_angle, ranges[c]);\n            bool reflectance;\n            map.ray_trace(pose[0], pose[1], total_angle, MAX_RANGE, final_pos, reflectance);\n        }\n    }\n    map.show(r);\n}\n", "meta": {"hexsha": "d328d73535c0d12e39a58a4e80e0a4d9372cf7f2", "size": 4475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/two_assumption_alg.cpp", "max_stars_repo_name": "wecacuee/modern-occupancy-grid", "max_stars_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-03-14T16:24:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T05:39:06.000Z", "max_issues_repo_path": "src/two_assumption_alg.cpp", "max_issues_repo_name": "wecacuee/modern-occupancy-grid", "max_issues_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/two_assumption_alg.cpp", "max_forks_repo_name": "wecacuee/modern-occupancy-grid", "max_forks_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-08-10T02:02:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-20T12:20:29.000Z", "avg_line_length": 34.1603053435, "max_line_length": 166, "alphanum_fraction": 0.603575419, "num_tokens": 1312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.537227099031562}}
{"text": "/* compile_time_power.hpp\n *\n*/\n\n\n\n#ifndef _COMPILE_TIME_POWER_HPP_\n#define _COMPILE_TIME_POWER_HPP_\n\n#include <type_traits>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n\n\nnamespace alex::utils::math\n{\n    namespace concepts\n    {\n    #if __cplusplus > 201703L && __cpp_concepts >= 201907L\n        template<typename T>\n        concept NumberType = std::is_integral_v<T> ||\n                            std::is_floating_point_v<T> ||\n                            boost::multiprecision::is_number<T>::value;\n    #else\n        // Legacy SFINAE\n        template<typename T> struct IsNumberType\n        { static constexpr bool value{std::is_integral<T>::value || std::is_floating_point<T>::value}; };\n    #endif\n    } // namespace alex::utils::math::concepts\n\n#if 0\n    template<\n#if __cplusplus > 201703L && __cpp_concepts >= 201907L\n        concepts::NumberType number_type,\n        number_type number,\n        size_t pow\n#else\n        typename number_type,\n        number_type number,\n        size_t pow,\n        typename = std::enable_if_t<concepts::IsNumberType<number_type>::value>\n#endif\n    >\n    struct ct_power\n    { static constexpr number_type value{number * ct_power<number_type, number, pow - 1>::value}; };\n\n    template<\n#if __cplusplus > 201703L && __cpp_concepts >= 201907L\n        concepts::NumberType number_type,\n        number_type number\n#else\n        typename number_type,\n        number_type number\n#endif\n    > struct ct_power<number_type, number, 1> { static constexpr number_type value{number}; };\n\n    template<\n#if __cplusplus > 201703L && __cpp_concepts >= 201907L\n        concepts::NumberType number_type,\n        number_type number\n#else\n        typename number_type,\n        number_type number\n#endif\n    > struct ct_power<number_type, number, 0> { static constexpr number_type value{static_cast<number_type>(1)}; };\n#else\n    template<\n#if __cplusplus > 201703L && __cpp_concepts >= 201907L\n        concepts::NumberType number_type\n#else\n        typename number_type, typename = std::enable_if_t<concepts::IsNumberType<number_type>::value>\n#endif\n    >\n    constexpr number_type ct_power(number_type number, size_t pow)\n    {\n        if (pow == 0) return 1;\n        if (pow == 1) return number;\n        return number * ct_power(number, pow - 1);\n    }\n#endif\n} // namespace alex::utils::math\n\n#endif // _COMPILE_TIME_POWER_HPP_", "meta": {"hexsha": "4fda55cf7c1ba7e005f3938ef9665b763aa1153c", "size": 2356, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/utils/math/compile_time_power.hpp", "max_stars_repo_name": "AlexCr4ckPentest/CppHacks", "max_stars_repo_head_hexsha": "b622111955dd4f87d6a8fefb7cf3fd9febd1e106", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-03T19:04:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-19T09:02:55.000Z", "max_issues_repo_path": "include/utils/math/compile_time_power.hpp", "max_issues_repo_name": "AlexCr4ckPentest/CppHacks", "max_issues_repo_head_hexsha": "b622111955dd4f87d6a8fefb7cf3fd9febd1e106", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-10T19:36:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-11T21:33:14.000Z", "max_forks_repo_path": "include/utils/math/compile_time_power.hpp", "max_forks_repo_name": "AlexCr4ckPentest/CppHacks", "max_forks_repo_head_hexsha": "b622111955dd4f87d6a8fefb7cf3fd9febd1e106", "max_forks_repo_licenses": ["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.0476190476, "max_line_length": 115, "alphanum_fraction": 0.6608658744, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5372270970291889}}
{"text": "#define CATCH_CONFIG_MAIN\n#include <Eigen/Dense>\n#include <catch.hpp>\n#include <random>\n\n#include \"EDP/ConstructSparseMat.hpp\"\n#include \"EDP/LocalHamiltonian.hpp\"\n\n#include \"yavque/Operators/HamEvol.hpp\"\n#include \"yavque/utils.hpp\"\n\n#include \"common.hpp\"\n\ntemplate<typename RandomEngine>\nvoid test_single_qubit(const uint32_t N, const Eigen::SparseMatrix<double>& m,\n                       RandomEngine& re)\n{\n\tusing namespace Eigen;\n\tusing std::cos;\n\tusing std::exp;\n\tusing std::sin;\n\tusing std::sqrt;\n\n\tconstexpr yavque::cx_double I(0., 1.);\n\tstd::normal_distribution<> nd;\n\n\tedp::LocalHamiltonian<double> ham_ct(N, 2);\n\tfor(uint32_t i = 0; i < N; i++)\n\t{\n\t\tham_ct.addOneSiteTerm(i, m);\n\t}\n\n\tauto ham\n\t\t= yavque::Hamiltonian(edp::constructSparseMat<yavque::cx_double>(1 << N, ham_ct));\n\tauto hamEvol = yavque::HamEvol(ham);\n\tauto var = hamEvol.get_variable();\n\n\tfor(int i = 0; i < 100; i++)\n\t{\n\t\tVectorXcd ini = VectorXcd::Random(1 << N);\n\t\tini.normalize();\n\t\tdouble t = nd(re);\n\t\tvar = t;\n\t\tVectorXcd out_test = hamEvol * ini;\n\n\t\tMatrixXcd mevol = (cos(t) * MatrixXcd::Identity(2, 2) - I * sin(t) * m);\n\t\tVectorXcd out = apply_kronecker(N, mevol, ini);\n\n\t\tREQUIRE((out - out_test).norm() < 1e-6);\n\t}\n\n\thamEvol.dagger_in_place();\n\tfor(int i = 0; i < 100; i++)\n\t{\n\t\tVectorXcd ini = VectorXcd::Random(1 << N);\n\t\tini.normalize();\n\n\t\tdouble t = nd(re);\n\t\tvar = t;\n\t\tVectorXcd out_test = hamEvol * ini;\n\n\t\tMatrixXcd mevol = (cos(t) * MatrixXcd::Identity(2, 2) + I * sin(t) * m);\n\t\tVectorXcd out = apply_kronecker(N, mevol, ini);\n\n\t\tREQUIRE((out - out_test).norm() < 1e-6);\n\t}\n}\n\nTEST_CASE(\"test single qubit Hamiltonian\", \"[one-site]\")\n{\n\tconstexpr uint32_t N = 8; // number of qubits\n\n\t// ini is |+>^N\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\n\tSECTION(\"test using pauli X\") { test_single_qubit(N, yavque::pauli_x(), re); }\n\n\tSECTION(\"test using pauli Z\") { test_single_qubit(N, yavque::pauli_z(), re); }\n}\n\nTEST_CASE(\"Test basic operations\", \"[basic]\")\n{\n\tusing namespace Eigen;\n\tusing namespace yavque;\n\tusing std::cos;\n\tusing std::exp;\n\tusing std::sin;\n\tusing std::sqrt;\n\tconstexpr uint32_t N = 8; // number of qubits\n\n\t// ini is |+>^N\n\tVectorXcd ini = VectorXcd::Ones(1 << N);\n\tini /= sqrt(1 << N);\n\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\tstd::normal_distribution<> nd;\n\n\tconstexpr yavque::cx_double I(0., 1.);\n\n\tedp::LocalHamiltonian<double> ham_ct(N, 2);\n\tfor(uint32_t i = 0; i < N; i++)\n\t{\n\t\tham_ct.addOneSiteTerm(i, yavque::pauli_x());\n\t}\n\n\tauto ham\n\t\t= yavque::Hamiltonian(edp::constructSparseMat<yavque::cx_double>(1 << N, ham_ct));\n\tauto hamEvol = HamEvol(ham);\n\n\tauto copied = hamEvol.clone();\n\n\tREQUIRE(hamEvol.get_variable()\n\t        != dynamic_cast<HamEvol*>(copied.get())->get_variable());\n\n\tREQUIRE(hamEvol.hamiltonian().is_same_ham(\n\t\tdynamic_cast<HamEvol*>(copied.get())->hamiltonian()));\n}\n\nTEST_CASE(\"Test gradient\", \"[log-deriv]\")\n{\n\tusing namespace Eigen;\n\tusing namespace yavque;\n\tusing std::cos;\n\tusing std::exp;\n\tusing std::sin;\n\tusing std::sqrt;\n\tconstexpr uint32_t N = 8; // number of qubits\n\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\n\tstd::vector<Eigen::SparseMatrix<double>> pauli_ops\n\t\t= {yavque::pauli_xx(), yavque::pauli_yy(), yavque::pauli_zz()};\n\n\tstd::uniform_int_distribution<> uid(0, 2);\n\tstd::normal_distribution<> nd;\n\n\tfor(uint32_t k = 0; k < 100; ++k) // instances\n\t{\n\t\t// ini is random\n\t\tVectorXcd ini = VectorXcd::Random(1 << N);\n\t\tini.normalize();\n\n\t\tedp::LocalHamiltonian<double> ham_ct(N, 2);\n\t\tham_ct.addTwoSiteTerm(random_connection(N, re), pauli_ops[uid(re)]);\n\n\t\tauto ham = yavque::Hamiltonian(\n\t\t\tedp::constructSparseMat<yavque::cx_double>(1 << N, ham_ct));\n\t\tauto hamEvol = HamEvol(ham);\n\n\t\tdouble val = nd(re);\n\n\t\thamEvol.set_variable_value(val);\n\t\tEigen::VectorXcd grad1\n\t\t\t= hamEvol.log_deriv()->apply_right(hamEvol.apply_right(ini));\n\n\t\thamEvol.get_variable() += M_PI / 2;\n\t\tEigen::VectorXcd grad2 = hamEvol.apply_right(ini);\n\t\thamEvol.get_variable() = val - M_PI / 2;\n\t\tgrad2 -= hamEvol.apply_right(ini);\n\t\tgrad2 /= 2.0;\n\n\t\tREQUIRE((grad1 - grad2).norm() < 1e-6);\n\t}\n}\n", "meta": {"hexsha": "74b00b5c0e43ebcea956bef7466b0f59a3e96fd7", "size": 4091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/TestHamEvol.cpp", "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": "Tests/TestHamEvol.cpp", "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": "Tests/TestHamEvol.cpp", "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": 24.3511904762, "max_line_length": 84, "alphanum_fraction": 0.6685406991, "num_tokens": 1335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5372270907265714}}
{"text": "// random.cpp\n//\n#include <stdint.h>\n#include <ctime>\n#include <iostream>\n\n#include <boost/random.hpp>\n#include <boost/random/random_device.hpp>\n\nint main(int argc, char* argv[])\n{\n    namespace random = boost::random;\n\n    std::time_t now = std::time(0);\n    random::mt19937 rand(static_cast<uint32_t>(now));\n    std::cout << rand() << '\\n';\n\n    random::random_device rand_dev;\n    random::uniform_int_distribution<> dist(1, 100);\n    std::cout << dist(rand_dev) << '\\n';\n    random::bernoulli_distribution<> dist1;\n    std::cout << dist1(rand_dev) << '\\n';\n}\n", "meta": {"hexsha": "10d96510b4f1571f05bc0ce96ff63ea46c3b4243", "size": 562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/random.cpp", "max_stars_repo_name": "uwydoc/the-practices", "max_stars_repo_head_hexsha": "61ea1d868017ac88fddf6c0e726f0e9adde3f80e", "max_stars_repo_licenses": ["MIT"], "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/random.cpp", "max_issues_repo_name": "uwydoc/the-practices", "max_issues_repo_head_hexsha": "61ea1d868017ac88fddf6c0e726f0e9adde3f80e", "max_issues_repo_licenses": ["MIT"], "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/random.cpp", "max_forks_repo_name": "uwydoc/the-practices", "max_forks_repo_head_hexsha": "61ea1d868017ac88fddf6c0e726f0e9adde3f80e", "max_forks_repo_licenses": ["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.4166666667, "max_line_length": 53, "alphanum_fraction": 0.6459074733, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5372270854251409}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file dcs/fog/confidence_intervals.hpp\n *\n * \\brief Confidence interval estimation\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2017 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_FOG_CONFIDENCE_INTERVALS_HPP\n#define DCS_FOG_CONFIDENCE_INTERVALS_HPP\n\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/students_t.hpp>\n#include <dcs/assert.hpp>\n#include <dcs/debug.hpp>\n#include <dcs/logging.hpp>\n#include <dcs/macro.hpp>\n#include <dcs/math/function/iszero.hpp>\n#include <dcs/math/function/sqr.hpp>\n#include <dcs/math/traits/float.hpp>\n#include <cstddef>\n#include <limits>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\n\nnamespace dcs { namespace fog {\n\ntemplate <typename RealT>\nclass ci_mean_estimator\n{\nprivate:\n    typedef boost::accumulators::accumulator_set<RealT,\n                                                 boost::accumulators::stats<boost::accumulators::tag::count,\n                                                                            boost::accumulators::tag::mean,\n                                                                            boost::accumulators::tag::variance>> accumulator_type;\n\npublic:\n    static const RealT default_ci_level;\n    static const RealT default_relative_precision;\n    static const std::size_t default_min_sample_size;\n    static const std::size_t default_max_sample_size;\n\n\n    explicit ci_mean_estimator(RealT confidence_level = default_ci_level,\n                                       RealT relative_precision = default_relative_precision,\n                                       std::size_t min_sample_size = default_min_sample_size,\n                                       std::size_t max_sample_size = default_max_sample_size)\n    : ci_level_(confidence_level),\n      target_rel_prec_(relative_precision),\n      n_min_(min_sample_size),\n      n_max_(max_sample_size),\n      name_(\"Unnamed\"),\n      n_target_(std::numeric_limits< std::size_t >::max()),\n      n_detected_(false),\n      n_aborted_(false),\n      n_first_call_(true),\n      unstable_(false),\n      done_(false)\n    {\n        // pre: min sample size >= 2\n        DCS_ASSERT(n_min_ >= 2,\n                   DCS_EXCEPTION_THROW(std::invalid_argument,\n                                       \"Min sample size must be >= 2\"));\n        // pre: min sample size <= max sample size\n        DCS_ASSERT(n_min_ <= n_max_,\n                   DCS_EXCEPTION_THROW(std::invalid_argument,\n                                       \"Min sample size must be <= max sample size\"));\n    }\n\n    void name(std::string const& s)\n    {\n        name_ = s;\n    }\n\n    std::string name() const\n    {\n        return name_;\n    }\n\n    std::size_t size() const\n    {\n        return boost::accumulators::count(stat_);\n    }\n\n    std::size_t target_size() const\n    {\n        return n_target_;\n    }\n\n    RealT estimate() const\n    {\n        return boost::accumulators::mean(stat_);\n    }\n\n    RealT variance() const\n    {\n        //FIXME: Boost.Accumulators variance computes the biased sample variance\n        const std::size_t n = this->size();\n        return (n/static_cast<RealT>(n-1))*boost::accumulators::variance(stat_);\n    }\n\n    RealT standard_deviation() const\n    {\n        return std::sqrt(this->variance());\n    }\n\n    RealT half_width() const\n    {\n        const std::size_t n = this->size();\n\n        if (n > 1)\n        {\n            boost::math::students_t_distribution<RealT> t_dist(n-1);\n            const RealT t = boost::math::quantile(t_dist, (1+ci_level_)*0.5);\n\n            return t*(this->standard_deviation()/std::sqrt(n));\n        }\n\n        return std::numeric_limits<RealT>::infinity();\n    }\n\n    RealT target_relative_precision() const\n    {\n        return target_rel_prec_;\n    }\n\n    RealT relative_precision() const\n    {\n        if (!::dcs::math::iszero(this->estimate()) && this->size() > 1)\n        {\n            return this->half_width() / std::abs(this->estimate());\n        }\n\n        return std::numeric_limits<RealT>::infinity();\n    }\n\n    RealT lower() const\n    {\n        return this->estimate() - this->half_width();\n    }\n\n    RealT upper() const\n    {\n        return this->estimate() + this->half_width();\n    }\n\n    bool done() const\n    {\n        return done_;\n    }\n\n    bool unstable() const\n    {\n        return unstable_;\n    }\n\n    void collect(RealT obs)\n    {\n        if (n_aborted_)\n        {\n            return;\n        }\n\n        stat_(obs);\n\n        //this->check_precision();\n        this->check_precision_alt();\nDCS_DEBUG_TRACE(\"(\" << name_ << \") Statistic Info: estimate: \" << this->estimate() << \", s.d.: \" << this->standard_deviation() << \", size: \" << this->size() << \", n_target_: \" << n_target_ << \", n_min_: \" << n_min_ << \", n_max_: \" << n_max_ << \", rel.prec.: \" << this->relative_precision() << \", n_detected_: \" << std::boolalpha << n_detected_ << \", n_aborted_: \" << n_aborted_ << \", unstable: \" << unstable_ << \", done: \" << done_ << \")\");//XXX\n    }\n\n    void reset()\n    {\n        stat_ = accumulator_type();\n        n_aborted_ = n_detected_\n                   = false;\n        n_first_call_ = true;\n        unstable_ = false;\n        done_ = false;\n        n_target_ = std::numeric_limits< std::size_t >::max();\n    }\n\nprivate:\n    void check_precision()\n    {\n        const std::size_t n = this->size();\n\n        if (n_detected_ && n >= n_target_)\n        {\n            if (std::isinf(target_rel_prec_))\n            {\n                done_ = true;\n            }\n            else\n            {\n                done_ = ::dcs::math::float_traits<RealT>::definitely_less_equal(this->relative_precision(), target_rel_prec_);\n            }\n        }\n        if (!n_detected_ || (n >= n_target_ && !done_))\n        {\n            // Sample size is still to be detected...\n            // ... or needs to be redetected since, after having performed the\n            //        detection, the precision has not been reached yet.\n\n            DCS_DEBUG_TRACE(\"(\" << name_ << \") Detecting sample size...\");\n\n            this->detect();\n\n            if (n_detected_)\n            {\n                if (n >= n_target_)\n                {\n                    if (done_)\n                    {\n                        // Ooops! The new detected number of replications is the\n                        // same of or greater than the one previously detected\n                        // AND we have already performed this number of replications\n                        // AND precision has not been reached yet.\n                        // This means that we are unable to reach the target\n                        // precision. So disable this statistic.\n\n                        ::dcs::log_warn(DCS_LOGGING_AT, \"Statistic '\" + name_ + \"' will be disabled: unable to reach the wanted precision.\");\n\n                        unstable_ = true;\n                    }\n\n                    done_ = true;\n                }\n\n                DCS_DEBUG_TRACE(\"(\" << name_ << \") Sample size detected: \" << n_target_ << \" (already collected: \" << n << \")\");\n            }\n        }\n\n#ifdef DCS_DEBUG\n        if (done_)\n        {\n            DCS_DEBUG_TRACE(\"(\" << name_ << \") [Sample #\" << n << \"] Detected precision: mean = \" << this->estimate() << \" - reached precision = \" << this->relative_precision() << \" - target precision: \" << target_rel_prec_);\n        }\n        else if (n_detected_)\n        {\n            //DCS_DEBUG_TRACE(\"(\" << name_ << \") Sample size detected: \" << n_target_ << \" (already collected: \" << n << \")\");\n            if (n >= n_target_)\n            {\n                DCS_DEBUG_TRACE(\"(\" << name_ << \") [Sample #\" << n << \"] Failed to detect precision: mean = \" << this->estimate() << \" - reached precision = \" << this->relative_precision() << \" - target precision: \" << target_rel_prec_);\n            }\n            else\n            {\n                DCS_DEBUG_TRACE(\"(\" << name_ << \") [Sample #\" << n << \"] Precision not yet reached: not enough replications (done: \" << n << \" - needed: \" << n_target_ << \")\");\n            }\n        }\n#endif\n    }\n\n    bool detect()\n    {\n        std::size_t n = this->size();\n\n        if (n < n_min_)\n        {\n            n_detected_ = false;\n            return false;\n        }\n        if (n >= n_max_)\n        {\n            n_aborted_ = true;\n            return false;\n        }\n        if (std::isinf(target_rel_prec_) && !n_detected_)\n        {\n            n_target_ = n;\n            n_detected_ = true;\n            return true;\n        }\n\n        // Use the procedure described in [1], chapter 11.\n        //\n        // References\n        // 1. J. Banks et al.\n        //    \"Discrete-Event System Simulations,\"\n        //    4th Edition, Prentice-Hall, 2005\n        //\n\n        const RealT mean = this->estimate();\n        const RealT sd = this->standard_deviation();\n\n        if (sd < 0 || std::isinf(sd))\n        {\n            ::dcs::log_warn(DCS_LOGGING_AT, \"Standard deviation is negative or infinite\");\n            n_detected_ = false;\n            return false;\n        }\n\n        const RealT half_alpha = (1-ci_level_)*0.5;\n\n        // Compute an initial estimate of sample size\n        if (n_first_call_)\n        {\n            n_first_call_ = false;\n\n            boost::math::normal_distribution<RealT> norm;\n            const RealT z = boost::math::quantile(norm, half_alpha);\n            n =  static_cast< std::size_t >(::dcs::math::sqr(z*sd/(target_rel_prec_*mean)));\n\n            if (n < n_min_)\n            {\n                n = n_min_;\n            }\n        }\n\n        RealT n_want = 0;\n\n        // Compute the real estimate of sample size\n        do\n        {\n            boost::math::students_t_distribution<RealT> student_t(n-1);\n            const RealT t = boost::math::quantile(student_t, half_alpha);\n            n_want = ::dcs::math::sqr(t*sd/(target_rel_prec_*mean));\n\n            if (n < n_want)\n            {\n                ++n;\n            }\n        }\n        while (n < n_want && n < n_max_);\n\n        if (n <= n_max_)\n        {\n            if (n_detected_ && n >= n_target_ && !done_)\n            {\n                // Ooops! The new detected sample size is the\n                // same of or greater than the one previously detected\n                // AND we have already collected this number of samples\n                // AND precision has not been reached yet.\n                // This means that we are unable to reach the target\n                // precision. So disable this statistic.\n\n                ::dcs::log_warn(DCS_LOGGING_AT, \"Statistic '\" + name_ + \"' will be disabled: unable to reach the wanted precision.\");\n\n                unstable_ = true;\n            }\n\n            n_target_ = n;\n            n_detected_ = true;\n            //done_ = true;\n        }\n        else\n        {\n            n_target_ = n_max_;\n            n_detected_ = false;\n            n_aborted_ = true;\n        }\n\nDCS_DEBUG_TRACE(\"(\" << name_ << \") Detecting Sample Size --> \" << std::boolalpha << n_detected_ << \" (n_target_: \" << n_target_ << \" - n_want: \" << n_want << \" - n_max_: \" << n_max_ << \" - n_aborted_: \" << n_aborted_ << \" - unstable: \" << unstable_ << \" - done: \" << done_ << \")\");//XXX\n\n        return n_detected_;\n    }\n\n    bool check_precision_alt()\n    {\n        std::size_t n = this->size();\n\n        if (n < n_min_)\n        {\n            n_detected_ = false;\n            return false;\n        }\n        if (n >= n_max_)\n        {\n            n_aborted_ = true;\n            return false;\n        }\n        if (std::isinf(target_rel_prec_))\n        {\n            n_target_ = n;\n            n_detected_ = true;\n            done_ = true;\n            return true;\n        }\n\n        // Use the procedure described in [1], chapter 11.\n        //\n        // References\n        // 1. J. Banks et al.\n        //    \"Discrete-Event System Simulations,\"\n        //    4th Edition, Prentice-Hall, 2005\n        //\n\n        const RealT mean = this->estimate();\n        const RealT sd = this->standard_deviation();\n\n        if (sd < 0 || std::isinf(sd))\n        {\n            ::dcs::log_warn(DCS_LOGGING_AT, \"Standard deviation is negative or infinite\");\n            n_detected_ = false;\n            return false;\n        }\n\n        const RealT half_alpha = (1-ci_level_)*0.5;\n\n        // Compute an initial estimate of sample size\n        if (n_first_call_)\n        {\n            n_first_call_ = false;\n\n            boost::math::normal_distribution<RealT> norm;\n            const RealT z = boost::math::quantile(norm, half_alpha);\n            n =  static_cast< std::size_t >(::dcs::math::sqr(z*sd/(target_rel_prec_*mean)));\n\n            if (n < n_min_)\n            {\n                n = n_min_;\n            }\n        }\n\n        RealT n_want = 0;\n\n        // Compute the real estimate of sample size\n        do\n        {\n            boost::math::students_t_distribution<RealT> student_t(n-1);\n            const RealT t = boost::math::quantile(student_t, half_alpha);\n            n_want = ::dcs::math::sqr(t*sd/(target_rel_prec_*mean));\n\n            if (n < n_want)\n            {\n                ++n;\n            }\n        }\n        while (n < n_want && n < n_max_);\n\n        if (n <= n_max_)\n        {\n//          if (n_detected_ && n >= n_target_ && !done_)\n//          {\n//              // Ooops! The new detected sample size is the\n//              // same of or greater than the one previously detected\n//              // AND we have already collected this number of samples\n//              // AND precision has not been reached yet.\n//              // This means that we are unable to reach the target\n//              // precision. So disable this statistic.\n//\n//              ::dcs::log_warn(DCS_LOGGING_AT, \"Statistic '\" + name_ + \"' will be disabled: unable to reach the wanted precision.\");\n//\n//              unstable_ = true;\n//          }\n\n            if (n <= this->size())\n            {\n//              n_target_ = this->size();\n                done_ = true;\n            }\n//          else\n//          {\n//              n_target_ = n;\n//          }\n            n_target_ = n;\n            n_detected_ = true;\n            //done_ = true;\n        }\n        else\n        {\n            n_target_ = n_max_;\n            n_detected_ = false;\n            n_aborted_ = true;\n        }\n\nDCS_DEBUG_TRACE(\"(\" << name_ << \") Detecting Sample Size --> \" << std::boolalpha << n_detected_ << \" (n_target_: \" << n_target_ << \" - n_want: \" << n_want << \" - n_max_: \" << n_max_ << \" - n_aborted_: \" << n_aborted_ << \" - unstable: \" << unstable_ << \" - done: \" << done_ << \")\");//XXX\n\n        return n_detected_;\n    }\n\n\nprivate:\n    RealT ci_level_;\n    RealT target_rel_prec_;\n    std::size_t n_min_;\n    std::size_t n_max_;\n    std::string name_;\n    accumulator_type stat_; ///< The accumulated statistics\n    std::size_t n_target_; ///< The sample size needed to reach the target relative precision\n    bool n_detected_; ///< Tells if the sample size needed to reach the target relative precision has been achieved\n    bool n_aborted_; ///< Tells if the sample size detection process has been aborted\n    bool n_first_call_; ///< Tells if this is the first invocation of the sample size detection process\n    bool unstable_; ///< Tells if this statistics has shown an unstable behavior\n    bool done_; ///< Tells if this statistics has reached the target precision\n}; // ci_mean_estimator\n\ntemplate <typename RT>\nconst RT ci_mean_estimator<RT>::default_ci_level = 0.95;\n\ntemplate <typename RT>\nconst RT ci_mean_estimator<RT>::default_relative_precision = 0.04;\n\ntemplate <typename RT>\nconst std::size_t ci_mean_estimator<RT>::default_min_sample_size = 2;\n\ntemplate <typename RT>\nconst std::size_t ci_mean_estimator<RT>::default_max_sample_size = std::numeric_limits< std::size_t >::max();\n\n}} // Namespace dcs::fog\n\n#endif // DCS_FOG_CONFIDENCE_INTERVALS_HPP\n", "meta": {"hexsha": "fee1edb0f7b266ca2fc81c02e6a25adbc7c7d414", "size": 16743, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/include/dcs/fog/confidence_intervals.hpp", "max_stars_repo_name": "sguazt/fog-vmalloc", "max_stars_repo_head_hexsha": "e4fc3f7fc9a5e554ae0a0819f1a446a4dc9d9595", "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++/include/dcs/fog/confidence_intervals.hpp", "max_issues_repo_name": "sguazt/fog-vmalloc", "max_issues_repo_head_hexsha": "e4fc3f7fc9a5e554ae0a0819f1a446a4dc9d9595", "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++/include/dcs/fog/confidence_intervals.hpp", "max_forks_repo_name": "sguazt/fog-vmalloc", "max_forks_repo_head_hexsha": "e4fc3f7fc9a5e554ae0a0819f1a446a4dc9d9595", "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.7102272727, "max_line_length": 445, "alphanum_fraction": 0.5392104163, "num_tokens": 3903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5371709201165165}}
{"text": "/*\n * checks.hpp\n *\n *  Created on: Mar 1, 2019\n *      Author: Gregory Kramida\n *   Copyright: 2019 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#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n\nnamespace math {\n\ninline static\nbool is_power_of_two(int number){\n\treturn !(number == 0) && !(number & (number - 1));\n}\n\ntemplate<typename ScalarA, typename ScalarB>\ninline static\nbool are_dimensions_equal(\n\t\tconst Eigen::Matrix<ScalarA,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& container_a,\n\t\tconst Eigen::Matrix<ScalarB,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& container_b){\n\treturn container_a.rows() == container_b.rows() && container_a.cols() == container_b.cols();\n}\n\ntemplate<typename ScalarA, typename ScalarB, typename ScalarC>\ninline static\nbool are_dimensions_equal(\n\t\tconst Eigen::Matrix<ScalarA,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& container_a,\n\t\tconst Eigen::Matrix<ScalarB,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& container_b,\n\t\tconst Eigen::Matrix<ScalarC,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& container_c){\n\treturn container_a.rows() == container_b.rows() && container_a.cols() == container_b.cols()\n\t\t\t&& container_c.rows() == container_b.rows() && container_c.cols() == container_b.cols();\n}\n\ntemplate<typename ScalarA, typename ScalarB>\ninline static\nbool are_dimensions_equal(\n\t\tconst Eigen::Tensor<ScalarA,3,Eigen::ColMajor>& container_a,\n\t\tconst Eigen::Tensor<ScalarB,3,Eigen::ColMajor>& container_b){\n\tfor (int i_dim = 0; i_dim < 3; i_dim++) {\n\t\tif (container_a.dimension(i_dim) != container_b.dimension(i_dim)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\ntemplate<typename ScalarA, typename ScalarB, typename ScalarC>\ninline static\nbool are_dimensions_equal(\n\t\tconst Eigen::Tensor<ScalarA,3,Eigen::ColMajor>& container_a,\n\t\tconst Eigen::Tensor<ScalarB,3,Eigen::ColMajor>& container_b,\n\t\tconst Eigen::Tensor<ScalarC,3,Eigen::ColMajor>& container_c){\n\tfor (int i_dim = 0; i_dim < 3; i_dim++) {\n\t\tif (container_a.dimension(i_dim) != container_b.dimension(i_dim) ||\n\t\t\t\tcontainer_c.dimension(i_dim) != container_c.dimension(i_dim)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n} //namespace math\n\n\n", "meta": {"hexsha": "b9d435099421295d931f472aad5c56bf4bd86199", "size": 2731, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/checks.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/checks.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/checks.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": 33.3048780488, "max_line_length": 93, "alphanum_fraction": 0.7312339802, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334525, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.5371709042914996}}
{"text": "\n/* Copyright (c) 2018-2019 Bradley Worley <geekysuavo@gmail.com>\n * Released under the MIT License.\n */\n\n#pragma once\n#include <random>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <Eigen/Dense>\n\n/* problem data initializers:\n *  @unif: whether or not to use uniform-amplitude impulses.\n *  @k: number of impulses in the weight vector.\n *  @sigma: measurement noise standard deviation.\n *  @seed: pseudorandom number generator seed.\n */\nbool unif = true;\nstd::size_t k = 10;\ndouble sigma = 0.001;\nstd::size_t seed = 47351;\n\n/* weight prior parameters:\n *  @alpha0: shape.\n *  @beta0: rate.\n */\ndouble alpha0 = 0.001;\ndouble beta0 = 0.001;\n\n/* noise prior parameters:\n *  @nu0: shape.\n *  @lambda0: rate.\n */\ndouble nu0 = 0.001;\ndouble lambda0 = 0.001;\n\n/* algorithm parameters:\n *  @iters: iteration count.\n *  @burn: (monte carlo) burn-in iteration count.\n *  @thin: (monte carlo) thinning iteration count.\n */\nstd::size_t iters = 1000;\nstd::size_t burn = 10;\nstd::size_t thin = 1;\n\n/* instance-constant expressions:\n *  @alpha: weight posterior shape parameter.\n *  @nu: noise posterior shape parameter.\n */\nconstexpr double pi = 3.14159265358979323846264338327950288;\ndouble alpha;\ndouble nu;\n\n/* global pseudorandom number generator:\n */\nstd::default_random_engine gen;\n\n/* instance data:\n *  @A: measurement matrix.\n *  @x0: true weight vector.\n *  @y: data vector.\n */\nEigen::Matrix<double, m, n> A;\nEigen::Matrix<double, n, 1> x0;\nEigen::Matrix<double, m, 1> y;\n\n/* precomputed data:\n *  @a: vector of diagonal elements of the measurement gramian.\n *  @L: twice the maximal eigenvalue of the measurement gramian.\n *  @phi0: constant offset term of the universal sbl objective.\n */\nEigen::Matrix<double, n, 1> a;\ndouble L, phi0;\n\n/* instance_init(): initialize the current problem instance.\n */\nstatic void instance_init (int argc, char **argv) {\n  /* parse runtime arguments. */\n  for (std::size_t i = 1; i < argc; i++) {\n    /* get the current argument. */\n    std::string arg(argv[i]);\n    auto idx = arg.find_first_of('=');\n    if (idx == std::string::npos)\n      continue;\n\n    /* split the argument into key=val. */\n    auto key = arg.substr(0, idx);\n    auto val = arg.substr(idx + 1);\n\n    /* run some dirty argument parsing. */\n    if (key.compare(\"unif\") == 0) {\n      if (val.compare(\"true\") == 0)       unif = true;\n      else if (val.compare(\"false\") == 0) unif = false;\n    }\n    else if (key.compare(\"k\")     == 0) { k = std::stoi(val); }\n    else if (key.compare(\"sigma\") == 0) { sigma = std::stod(val); }\n    else if (key.compare(\"seed\")  == 0) { seed = std::stoull(val); }\n    else if (key.compare(\"alpha0\") == 0) { alpha0 = std::stod(val); }\n    else if (key.compare(\"beta0\")  == 0) { beta0 = std::stod(val); }\n    else if (key.compare(\"nu0\")     == 0) { nu0 = std::stod(val); }\n    else if (key.compare(\"lambda0\") == 0) { lambda0 = std::stod(val); }\n    else if (key.compare(\"iters\") == 0) { iters = std::stoul(val); }\n    else if (key.compare(\"burn\")  == 0) { burn = std::stoul(val); }\n    else if (key.compare(\"thin\")  == 0) { thin = std::stoul(val); }\n  }\n\n  /* update the posterior shape parameters. */\n  alpha = alpha0 + 0.5;\n  nu = nu0 + 0.5 * m;\n\n  /* prepare to sample from two distributions:\n   *  @idx: {0, 1, 2, ..., n-1}.\n   *  @nrm: N(0, 1).\n   */\n  std::uniform_int_distribution<std::size_t> idx{0, n - 1};\n  std::uniform_int_distribution<std::size_t> bin{0, 1};\n  std::normal_distribution<double> nrm{0, 1};\n  gen.seed(seed);\n\n  /* compute each row of the measurement matrix. */\n  for (std::size_t i = 0; i < m; i++) {\n    /* sample the row elements from a standard normal. */\n    for (std::size_t j = 0; j < n; j++)\n      A(i,j) = nrm(gen);\n\n    /* normalize the row to unit length. */\n    A.row(i).normalize();\n  }\n\n  /* fill the feature vector with spikes. */\n  std::size_t spikes = 0;\n  x0.setZero();\n  do {\n    /* sample a new element index. */\n    std::size_t j = idx(gen);\n    if (x0(j) != 0)\n      continue;\n\n    /* sample a random spike intensity. */\n    double xj = 0;\n    if (unif)\n      xj = (bin(gen) ? 1 : -1);\n    else\n      xj = nrm(gen);\n\n    /* store the spike intensity. */\n    x0(j) = xj;\n    spikes++;\n  }\n  while (spikes < k);\n\n  /* compute the noise-free data vector. */\n  y = A * x0;\n\n  /* check if the noise is nonzero. */\n  if (sigma > 0) {\n    /* add noise to the data vector. */\n    for (std::size_t i = 0; i < m; i++)\n      y(i) += sigma * nrm(gen);\n  }\n\n  /* construct an eigenvalue solver for the measurement matrix gramian. */\n  Eigen::Matrix<double, n, n> AtA = A.transpose() * A;\n  Eigen::EigenSolver<decltype(AtA)> es(AtA, false);\n\n  /* get the diagonal elements of the gramian. */\n  a = AtA.diagonal();\n\n  /* identify the maximal eigenvalue of the gramian. */\n  L = es.eigenvalues()(0).real();\n  for (std::size_t j = 1; j < n; j++)\n    L = std::max(L, es.eigenvalues()(j).real());\n\n  /* double the result (should be twice the maximal eigenvalue). */\n  L *= 2;\n\n  /* compute the constant offset to the sbl objective. */\n  phi0 = 0.5 * (m + n) * std::log(2 * pi)\n       - nu0 * std::log(lambda0)\n       - n * alpha0 * std::log(beta0)\n       - (std::lgamma(nu) - std::lgamma(nu0))\n       - n * (std::lgamma(alpha) - std::lgamma(alpha0));\n}\n\n", "meta": {"hexsha": "d3c84434e2f4d22a55c70def9640ee333329541c", "size": 5236, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/inst.hh", "max_stars_repo_name": "geekysuavo/sbl-sandbox", "max_stars_repo_head_hexsha": "2d52de5442fe7ad30c08f50dab3e92b051df5d70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-12-29T14:24:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T08:27:31.000Z", "max_issues_repo_path": "src/inst.hh", "max_issues_repo_name": "geekysuavo/sbl-sandbox", "max_issues_repo_head_hexsha": "2d52de5442fe7ad30c08f50dab3e92b051df5d70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/inst.hh", "max_forks_repo_name": "geekysuavo/sbl-sandbox", "max_forks_repo_head_hexsha": "2d52de5442fe7ad30c08f50dab3e92b051df5d70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-04T02:49:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T02:49:57.000Z", "avg_line_length": 28.1505376344, "max_line_length": 74, "alphanum_fraction": 0.602750191, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5371709030766585}}
{"text": "\r\n#include <iostream>\r\n#include <boost/numeric/interval.hpp>\r\n\r\n\r\nint main()\r\n{\r\n\tauto range1 = boost::numeric::hull(0, 100);\r\n\t//auto range2 = boost::numeric::hull(20.5, 120);\r\n\tauto range2 = boost::numeric::hull(20.5, 120.0);\r\n\t\r\n\tstd::cout << range1.lower() << \" ~ \"\r\n\t\t<< range1.upper() << std::endl;\r\n\r\n\tstd::cout << range2.lower() << \" ~ \"\r\n\t\t<< range2.upper() << std::endl;\r\n\r\n\treturn 0;\r\n}\r\n\r\n", "meta": {"hexsha": "1832057cb497974265143ad170ccef37f32e53cc", "size": 401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Boost_20140423/interval_03/interval_03.cpp", "max_stars_repo_name": "jacking75/book_semina_samples", "max_stars_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_stars_repo_licenses": ["MIT"], "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_20140423/interval_03/interval_03.cpp", "max_issues_repo_name": "jacking75/book_semina_samples", "max_issues_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_issues_repo_licenses": ["MIT"], "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_20140423/interval_03/interval_03.cpp", "max_forks_repo_name": "jacking75/book_semina_samples", "max_forks_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_forks_repo_licenses": ["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.0952380952, "max_line_length": 50, "alphanum_fraction": 0.5635910224, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5371708957715706}}
{"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_ARCH_COMMON_SIMD_FUNCTION_SQRT1PM1_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SQRT1PM1_HPP_INCLUDED\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/sqrt.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD_IF ( sqrt1pm1_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::floating_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      A0 tmp =  bs::sqrt(inc(a0));\n      return  bs::if_else((bs::abs(a0) < bs::Half<A0>()),\n                          a0/bs::inc(tmp),\n                          bs::dec(tmp));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "7d7278d7d5b7a5a0ef6ef088af90b77e618b7791", "size": 1615, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/sqrt1pm1.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/arch/common/simd/function/sqrt1pm1.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/arch/common/simd/function/sqrt1pm1.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": 33.6458333333, "max_line_length": 100, "alphanum_fraction": 0.5535603715, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5371114862916173}}
{"text": "// Example of a program that uses the Boost library.\n\n#include <boost/integer/common_factor.hpp>\n#include <iostream>\n\nint main (void)\n{\n        using std::cout;\n        using std::endl;\n\n        cout << \"The GCD and LCM of 6 and 15 are \"\n             << boost::integer::gcd(6, 15) << \" and \"\n             << boost::integer::lcm(6, 15) << \", respectively.\"\n             << endl;\n\n        cout << \"The GCD and LCM of 8 and 9 are \"\n             << boost::integer::static_gcd<8, 9>::value\n             << \" and \"\n             << boost::integer::static_lcm<8, 9>::value\n             << \", respectively.\" << endl;\n\n        return 0;\n}\n", "meta": {"hexsha": "794eb5be8ef3a5d5d1f58d40d3e83fe25c13fa68", "size": 629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Boost-common-factor/C++_code_example/boost_example.cpp", "max_stars_repo_name": "spainisnotequal/cffi-play", "max_stars_repo_head_hexsha": "02407c428052cd1c135a5c7c14d4b71a7fa9d41e", "max_stars_repo_licenses": ["MIT"], "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-common-factor/C++_code_example/boost_example.cpp", "max_issues_repo_name": "spainisnotequal/cffi-play", "max_issues_repo_head_hexsha": "02407c428052cd1c135a5c7c14d4b71a7fa9d41e", "max_issues_repo_licenses": ["MIT"], "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-common-factor/C++_code_example/boost_example.cpp", "max_forks_repo_name": "spainisnotequal/cffi-play", "max_forks_repo_head_hexsha": "02407c428052cd1c135a5c7c14d4b71a7fa9d41e", "max_forks_repo_licenses": ["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.2083333333, "max_line_length": 63, "alphanum_fraction": 0.5039745628, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.5371114824252579}}
{"text": "// Copyright John Maddock 2012.\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_AIRY_HPP\n#define BOOST_MATH_AIRY_HPP\n\n#include <limits>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/cbrt.hpp>\n#include <boost/math/special_functions/detail/airy_ai_bi_zero.hpp>\n#include <boost/math/tools/roots.hpp>\n\nnamespace boost{ namespace math{\n\nnamespace detail{\n\ntemplate <class T, class Policy>\nT airy_ai_imp(T x, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n\n   if(x < 0)\n   {\n      T p = (-x * sqrt(-x) * 2) / 3;\n      T v = T(1) / 3;\n      T j1 = boost::math::cyl_bessel_j(v, p, pol);\n      T j2 = boost::math::cyl_bessel_j(-v, p, pol);\n      T ai = sqrt(-x) * (j1 + j2) / 3;\n      //T bi = sqrt(-x / 3) * (j2 - j1);\n      return ai;\n   }\n   else if(fabs(x * x * x) / 6 < tools::epsilon<T>())\n   {\n      T tg = boost::math::tgamma(constants::twothirds<T>(), pol);\n      T ai = 1 / (pow(T(3), constants::twothirds<T>()) * tg);\n      //T bi = 1 / (sqrt(boost::math::cbrt(T(3))) * tg);\n      return ai;\n   }\n   else\n   {\n      T p = 2 * x * sqrt(x) / 3;\n      T v = T(1) / 3;\n      //T j1 = boost::math::cyl_bessel_i(-v, p, pol);\n      //T j2 = boost::math::cyl_bessel_i(v, p, pol);\n      //\n      // Note that although we can calculate ai from j1 and j2, the accuracy is horrible\n      // as we're subtracting two very large values, so use the Bessel K relation instead:\n      //\n      T ai = cyl_bessel_k(v, p, pol) * sqrt(x / 3) / boost::math::constants::pi<T>();  //sqrt(x) * (j1 - j2) / 3;\n      //T bi = sqrt(x / 3) * (j1 + j2);\n      return ai;\n   }\n}\n\ntemplate <class T, class Policy>\nT airy_bi_imp(T x, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n\n   if(x < 0)\n   {\n      T p = (-x * sqrt(-x) * 2) / 3;\n      T v = T(1) / 3;\n      T j1 = boost::math::cyl_bessel_j(v, p, pol);\n      T j2 = boost::math::cyl_bessel_j(-v, p, pol);\n      //T ai = sqrt(-x) * (j1 + j2) / 3;\n      T bi = sqrt(-x / 3) * (j2 - j1);\n      return bi;\n   }\n   else if(fabs(x * x * x) / 6 < tools::epsilon<T>())\n   {\n      T tg = boost::math::tgamma(constants::twothirds<T>(), pol);\n      //T ai = 1 / (pow(T(3), constants::twothirds<T>()) * tg);\n      T bi = 1 / (sqrt(boost::math::cbrt(T(3))) * tg);\n      return bi;\n   }\n   else\n   {\n      T p = 2 * x * sqrt(x) / 3;\n      T v = T(1) / 3;\n      T j1 = boost::math::cyl_bessel_i(-v, p, pol);\n      T j2 = boost::math::cyl_bessel_i(v, p, pol);\n      T bi = sqrt(x / 3) * (j1 + j2);\n      return bi;\n   }\n}\n\ntemplate <class T, class Policy>\nT airy_ai_prime_imp(T x, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n\n   if(x < 0)\n   {\n      T p = (-x * sqrt(-x) * 2) / 3;\n      T v = T(2) / 3;\n      T j1 = boost::math::cyl_bessel_j(v, p, pol);\n      T j2 = boost::math::cyl_bessel_j(-v, p, pol);\n      T aip = -x * (j1 - j2) / 3;\n      return aip;\n   }\n   else if(fabs(x * x) / 2 < tools::epsilon<T>())\n   {\n      T tg = boost::math::tgamma(constants::third<T>(), pol);\n      T aip = 1 / (boost::math::cbrt(T(3)) * tg);\n      return -aip;\n   }\n   else\n   {\n      T p = 2 * x * sqrt(x) / 3;\n      T v = T(2) / 3;\n      //T j1 = boost::math::cyl_bessel_i(-v, p, pol);\n      //T j2 = boost::math::cyl_bessel_i(v, p, pol);\n      //\n      // Note that although we can calculate ai from j1 and j2, the accuracy is horrible\n      // as we're subtracting two very large values, so use the Bessel K relation instead:\n      //\n      T aip = -cyl_bessel_k(v, p, pol) * x / (boost::math::constants::root_three<T>() * boost::math::constants::pi<T>());\n      return aip;\n   }\n}\n\ntemplate <class T, class Policy>\nT airy_bi_prime_imp(T x, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n\n   if(x < 0)\n   {\n      T p = (-x * sqrt(-x) * 2) / 3;\n      T v = T(2) / 3;\n      T j1 = boost::math::cyl_bessel_j(v, p, pol);\n      T j2 = boost::math::cyl_bessel_j(-v, p, pol);\n      T aip = -x * (j1 + j2) / constants::root_three<T>();\n      return aip;\n   }\n   else if(fabs(x * x) / 2 < tools::epsilon<T>())\n   {\n      T tg = boost::math::tgamma(constants::third<T>(), pol);\n      T bip = sqrt(boost::math::cbrt(T(3))) / tg;\n      return bip;\n   }\n   else\n   {\n      T p = 2 * x * sqrt(x) / 3;\n      T v = T(2) / 3;\n      T j1 = boost::math::cyl_bessel_i(-v, p, pol);\n      T j2 = boost::math::cyl_bessel_i(v, p, pol);\n      T aip = x * (j1 + j2) / boost::math::constants::root_three<T>();\n      return aip;\n   }\n}\n\ntemplate <class T, class Policy>\nT airy_ai_zero_imp(int m, const Policy& pol)\n{\n   BOOST_MATH_STD_USING // ADL of std names, needed for log, sqrt.\n\n   // Handle cases when a negative zero (negative rank) is requested.\n   if(m < 0)\n   {\n      return policies::raise_domain_error<T>(\"boost::math::airy_ai_zero<%1%>(%1%, int)\",\n                                             \"Requested the %1%'th zero, but the rank must be 1 or more !\", m, pol);\n   }\n\n   // Handle case when the zero'th zero is requested.\n   if(m == 0U)\n   {\n      return policies::raise_domain_error<T>(\"boost::math::airy_ai_zero<%1%>(%1%,%1%)\",\n        \"The requested rank of the zero is %1%, but must be 1 or more !\", static_cast<T>(m), pol);\n   }\n\n   // Set up the initial guess for the upcoming root-finding.\n   const T guess_root = boost::math::detail::airy_zero::airy_ai_zero_detail::initial_guess<T>(m);\n\n   // Select the maximum allowed iterations based on the number\n   // of decimal digits in the numeric type T, being at least 12.\n   const int my_digits10 = static_cast<int>(static_cast<float>(policies::digits<T, Policy>() * 0.301F));\n\n   const boost::uintmax_t iterations_allowed = static_cast<boost::uintmax_t>((std::max)(12, my_digits10 * 2));\n\n   boost::uintmax_t iterations_used = iterations_allowed;\n\n   // Use a dynamic tolerance because the roots get closer the higher m gets.\n   T tolerance;\n\n   if     (m <=   10) { tolerance = T(0.3F); }\n   else if(m <=  100) { tolerance = T(0.1F); }\n   else if(m <= 1000) { tolerance = T(0.05F); }\n   else               { tolerance = T(1) / sqrt(T(m)); }\n\n   // Perform the root-finding using Newton-Raphson iteration from Boost.Math.\n   const T am =\n      boost::math::tools::newton_raphson_iterate(\n         boost::math::detail::airy_zero::airy_ai_zero_detail::function_object_ai_and_ai_prime<T, Policy>(pol),\n         guess_root,\n         T(guess_root - tolerance),\n         T(guess_root + tolerance),\n         policies::digits<T, Policy>(),\n         iterations_used);\n\n   static_cast<void>(iterations_used);\n\n   return am;\n}\n\ntemplate <class T, class Policy>\nT airy_bi_zero_imp(int m, const Policy& pol)\n{\n   BOOST_MATH_STD_USING // ADL of std names, needed for log, sqrt.\n\n   // Handle cases when a negative zero (negative rank) is requested.\n   if(m < 0)\n   {\n      return policies::raise_domain_error<T>(\"boost::math::airy_bi_zero<%1%>(%1%, int)\",\n                                             \"Requested the %1%'th zero, but the rank must 1 or more !\", m, pol);\n   }\n\n   // Handle case when the zero'th zero is requested.\n   if(m == 0U)\n   {\n      return policies::raise_domain_error<T>(\"boost::math::airy_bi_zero<%1%>(%1%,%1%)\",\n        \"The requested rank of the zero is %1%, but must be 1 or more !\", static_cast<T>(m), pol);\n   }\n   // Set up the initial guess for the upcoming root-finding.\n   const T guess_root = boost::math::detail::airy_zero::airy_bi_zero_detail::initial_guess<T>(m);\n\n   // Select the maximum allowed iterations based on the number\n   // of decimal digits in the numeric type T, being at least 12.\n   const int my_digits10 = static_cast<int>(static_cast<float>(policies::digits<T, Policy>() * 0.301F));\n\n   const boost::uintmax_t iterations_allowed = static_cast<boost::uintmax_t>((std::max)(12, my_digits10 * 2));\n\n   boost::uintmax_t iterations_used = iterations_allowed;\n\n   // Use a dynamic tolerance because the roots get closer the higher m gets.\n   T tolerance;\n\n   if     (m <=   10) { tolerance = T(0.3F); }\n   else if(m <=  100) { tolerance = T(0.1F); }\n   else if(m <= 1000) { tolerance = T(0.05F); }\n   else               { tolerance = T(1) / sqrt(T(m)); }\n\n   // Perform the root-finding using Newton-Raphson iteration from Boost.Math.\n   const T bm =\n      boost::math::tools::newton_raphson_iterate(\n         boost::math::detail::airy_zero::airy_bi_zero_detail::function_object_bi_and_bi_prime<T, Policy>(pol),\n         guess_root,\n         T(guess_root - tolerance),\n         T(guess_root + tolerance),\n         policies::digits<T, Policy>(),\n         iterations_used);\n\n   static_cast<void>(iterations_used);\n\n   return bm;\n}\n\n} // namespace detail\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type airy_ai(T x, const Policy&)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::airy_ai_imp<value_type>(static_cast<value_type>(x), forwarding_policy()), \"boost::math::airy<%1%>(%1%)\");\n}\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type airy_ai(T x)\n{\n   return airy_ai(x, policies::policy<>());\n}\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type airy_bi(T x, const Policy&)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::airy_bi_imp<value_type>(static_cast<value_type>(x), forwarding_policy()), \"boost::math::airy<%1%>(%1%)\");\n}\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type airy_bi(T x)\n{\n   return airy_bi(x, policies::policy<>());\n}\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type airy_ai_prime(T x, const Policy&)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::airy_ai_prime_imp<value_type>(static_cast<value_type>(x), forwarding_policy()), \"boost::math::airy<%1%>(%1%)\");\n}\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type airy_ai_prime(T x)\n{\n   return airy_ai_prime(x, policies::policy<>());\n}\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type airy_bi_prime(T x, const Policy&)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::airy_bi_prime_imp<value_type>(static_cast<value_type>(x), forwarding_policy()), \"boost::math::airy<%1%>(%1%)\");\n}\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type airy_bi_prime(T x)\n{\n   return airy_bi_prime(x, policies::policy<>());\n}\n\ntemplate <class T, class Policy>\ninline T airy_ai_zero(int m, const Policy& /*pol*/)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename policies::evaluation<T, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   BOOST_STATIC_ASSERT_MSG(    false == std::numeric_limits<T>::is_specialized\n                           || (   true  == std::numeric_limits<T>::is_specialized\n                               && false == std::numeric_limits<T>::is_integer),\n                           \"Airy value type must be a floating-point type.\");\n\n   return policies::checked_narrowing_cast<T, Policy>(detail::airy_ai_zero_imp<value_type>(m, forwarding_policy()), \"boost::math::airy_ai_zero<%1%>(unsigned)\");\n}\n\ntemplate <class T>\ninline T airy_ai_zero(int m)\n{\n   return airy_ai_zero<T>(m, policies::policy<>());\n}\n\ntemplate <class T, class OutputIterator, class Policy>\ninline OutputIterator airy_ai_zero(\n                         int start_index,\n                         unsigned number_of_zeros,\n                         OutputIterator out_it,\n                         const Policy& pol)\n{\n   typedef T result_type;\n\n   BOOST_STATIC_ASSERT_MSG(    false == std::numeric_limits<T>::is_specialized\n                           || (   true  == std::numeric_limits<T>::is_specialized\n                               && false == std::numeric_limits<T>::is_integer),\n                           \"Airy value type must be a floating-point type.\");\n\n   for(unsigned i = 0; i < number_of_zeros; ++i)\n   {\n      *out_it = boost::math::airy_ai_zero<result_type>(start_index + i, pol);\n      ++out_it;\n   }\n   return out_it;\n}\n\ntemplate <class T, class OutputIterator>\ninline OutputIterator airy_ai_zero(\n                         int start_index,\n                         unsigned number_of_zeros,\n                         OutputIterator out_it)\n{\n   return airy_ai_zero<T>(start_index, number_of_zeros, out_it, policies::policy<>());\n}\n\ntemplate <class T, class Policy>\ninline T airy_bi_zero(int m, const Policy& /*pol*/)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename policies::evaluation<T, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   BOOST_STATIC_ASSERT_MSG(    false == std::numeric_limits<T>::is_specialized\n                           || (   true  == std::numeric_limits<T>::is_specialized\n                               && false == std::numeric_limits<T>::is_integer),\n                           \"Airy value type must be a floating-point type.\");\n\n   return policies::checked_narrowing_cast<T, Policy>(detail::airy_bi_zero_imp<value_type>(m, forwarding_policy()), \"boost::math::airy_bi_zero<%1%>(unsigned)\");\n}\n\ntemplate <typename T>\ninline T airy_bi_zero(int m)\n{\n   return airy_bi_zero<T>(m, policies::policy<>());\n}\n\ntemplate <class T, class OutputIterator, class Policy>\ninline OutputIterator airy_bi_zero(\n                         int start_index,\n                         unsigned number_of_zeros,\n                         OutputIterator out_it,\n                         const Policy& pol)\n{\n   typedef T result_type;\n\n   BOOST_STATIC_ASSERT_MSG(    false == std::numeric_limits<T>::is_specialized\n                           || (   true  == std::numeric_limits<T>::is_specialized\n                               && false == std::numeric_limits<T>::is_integer),\n                           \"Airy value type must be a floating-point type.\");\n\n   for(unsigned i = 0; i < number_of_zeros; ++i)\n   {\n      *out_it = boost::math::airy_bi_zero<result_type>(start_index + i, pol);\n      ++out_it;\n   }\n   return out_it;\n}\n\ntemplate <class T, class OutputIterator>\ninline OutputIterator airy_bi_zero(\n                         int start_index,\n                         unsigned number_of_zeros,\n                         OutputIterator out_it)\n{\n   return airy_bi_zero<T>(start_index, number_of_zeros, out_it, policies::policy<>());\n}\n\n}} // namespaces\n\n#endif // BOOST_MATH_AIRY_HPP\n", "meta": {"hexsha": "82167dc5f04f978daee1bdb2ca321d852d58a39a", "size": 16310, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/math/special_functions/airy.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 133.0, "max_stars_repo_stars_event_min_datetime": "2018-04-20T14:09:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T11:51:25.000Z", "max_issues_repo_path": "3party/boost/boost/math/special_functions/airy.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_issues_repo_licenses": ["Apache-2.0"], "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": "3party/boost/boost/math/special_functions/airy.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2018-04-27T03:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:23:40.000Z", "avg_line_length": 34.7021276596, "max_line_length": 183, "alphanum_fraction": 0.622685469, "num_tokens": 4455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5371114765571938}}
{"text": "/*\n * Copyright (c) 2016 Shanghai Jiao Tong University.\n *     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,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n *      http://ipads.se.sjtu.edu.cn/projects/wukong\n *\n */\n#pragma once\n#include <Eigen/Dense>\n\n#include \"optimizer/stats_type.hpp\"\n\n#include \"utils/logger2.hpp\"\n\nnamespace wukong {\n\n#define L2U_FACTOR_NUM 2\n#define K2U_FACTOR_NUM 4\n#define K2L_FACTOR_NUM 5\n#define K2K_FACTOR_NUM 5\n\nusing namespace Eigen;\n\nclass CostModel{\n    private:\n     MatrixXd matrix_l2u;\n     VectorXd vector_l2u;\n     double b_l2u = 0.046;  // explore, const\n     double d_l2u = 0;\n\n     MatrixXd matrix_k2u;\n     VectorXd vector_k2u;\n     double a1_k2u = 0.07;\n     double a2_k2u = 0.09;\n     double b_k2u = 0.01;\n     double d_k2u = 0;  // init-prune, prune, explore, const\n\n     MatrixXd matrix_k2l;\n     VectorXd vector_k2l;\n     double a1_k2l = 0.013;\n     double a2_k2l = 0.015;\n     double b_k2l = 0.012;\n     double c_k2l = 0;\n     double d_k2l = 0;  // init-prune, prune, explore, match, const\n\n     MatrixXd matrix_k2k;\n     VectorXd vector_k2k;\n     double a1_k2k = 0.44;\n     double a2_k2k = 0.01;\n     double b_k2k = -0.022;\n     double c_k2k = 0;\n     double d_k2k = 0;  // init-prune, prune, explore, match, const\n\n    public:\n     void print(){\n        logstream(LOG_INFO) << \"cost model factor: l2u \" << b_l2u << \"  \" << d_l2u << \" \" << LOG_endl;\n        logstream(LOG_INFO)\n            << \"cost model factor: k2u \" << a1_k2u << \"  \" << a2_k2u << \" \"\n            << b_k2u << \"  \" << d_k2u << \" \" << LOG_endl;\n        logstream(LOG_INFO)\n            << \"cost model factor: k2l \" << a1_k2l << \"  \" << a2_k2l << \" \"\n            << b_k2l << \"  \" << c_k2l << \"  \" << d_k2l << \" \" << LOG_endl;\n        logstream(LOG_INFO)\n            << \"cost model factor: k2k \" << a1_k2k << \"  \" << a2_k2k << \" \"\n            << b_k2k << \"  \" << c_k2k << \"  \" << d_k2k << \" \" << LOG_endl;\n     }\n\n     void calculate(CostResult &result){\n        if(result.current_model != model_t::L2U && result.init_bind == 0){\n            result.add_cost = 0;\n            return;\n        }\n        switch (result.current_model)\n         {\n         case model_t::T2U:\n         case model_t::L2U:\n             result.add_cost = result.explore_bind * b_l2u + d_l2u;\n             break;\n         case model_t::K2U:\n             result.add_cost = (result.init_bind-result.prune_bind) * a1_k2u + result.prune_bind * a2_k2u + \n                        result.explore_bind * b_k2u + d_k2u;\n             break;\n         case model_t::K2L:{\n             result.add_cost = (result.init_bind - result.prune_bind) * a1_k2l +\n                               result.prune_bind * a2_k2l + result.explore_bind * b_k2l + d_k2l;\n         }   \n             break;\n         case model_t::K2K:{\n             result.add_cost = (result.init_bind - result.prune_bind) * a1_k2k +\n                               result.prune_bind * a2_k2k + result.explore_bind * b_k2k + d_k2k;\n         }   \n             break;\n         default:\n             break;\n         }\n\n         if(result.add_cost < 0)\n            result.add_cost = 0;\n     }\n\n     void generate_factor(model_t model_type=model_t::ALL){\n         VectorXd result;\n         switch (model_type)\n         {\n         case model_t::ALL:\n             result = matrix_l2u.jacobiSvd(ComputeThinU | ComputeThinV).solve(vector_l2u);\n             b_l2u = abs(result(0)); d_l2u = result(1);\n             result = matrix_k2u.jacobiSvd(ComputeThinU | ComputeThinV).solve(vector_k2u);\n             a1_k2u = abs(result(0)); a2_k2u = abs(result(1)); b_k2u = abs(result(2));\n             d_k2u = result(3);\n             result = matrix_k2l.jacobiSvd(ComputeThinU | ComputeThinV).solve(vector_k2l);\n             a1_k2l = abs(result(0)); a2_k2l = abs(result(1)); b_k2l = abs(result(2));\n             c_k2l = abs(result(3)); d_k2l = result(4);\n             break;\n         case model_t::L2U:\n             result = matrix_l2u.jacobiSvd(ComputeThinU | ComputeThinV).solve(vector_l2u);\n             b_l2u = result(0); d_l2u = result(1);\n             break;\n         case model_t::K2U:\n             result = matrix_k2u.jacobiSvd(ComputeThinU | ComputeThinV).solve(vector_k2u);\n             a1_k2u = result(0); a2_k2u = result(1); b_k2u = result(2);d_k2u = result(3);\n             break;\n         case model_t::K2L:\n             result = matrix_k2l.jacobiSvd(ComputeThinU | ComputeThinV).solve(vector_k2l);\n             a1_k2l = result(0); a2_k2l = result(1); b_k2l = result(2);\n             b_k2l = result(3); d_k2l = result(4);\n             break;\n         case model_t::K2K:\n             result = matrix_k2k.jacobiSvd(ComputeThinU | ComputeThinV).solve(vector_k2k);\n             a1_k2k = result(0); a2_k2k = result(1); b_k2k = result(2);\n             c_k2k = result(3); d_k2k = result(4);\n             break;\n         default:\n             break;\n         }\n\n         print();\n     }\n\n     void add_l2u_sample(int sample_index, int row_explore, int latency){\n         matrix_l2u.row(sample_index) << row_explore , 1;\n         vector_l2u.row(sample_index) << latency;\n     }\n\n     void add_k2u_sample(int sample_index, int row_init, int row_prune, int row_explore, int latency) {\n         matrix_k2u.row(sample_index) << (row_init-row_prune), row_prune, row_explore, 1;\n         vector_k2u.row(sample_index) << latency;\n     }\n\n     void add_k2l_sample(int sample_index, int row_init, int row_prune, int row_explore, \n                                                int row_match, int latency) {\n         matrix_k2l.row(sample_index) << (row_init-row_prune), row_prune, row_explore, 0, 1;\n         vector_k2l.row(sample_index) << latency;\n     }\n\n     void add_k2k_sample(int sample_index, int row_init, int row_prune, int row_explore, \n                                                int row_match, int latency) {\n         matrix_k2k.row(sample_index) << (row_init-row_prune), row_prune, row_explore, 0, 1;\n         vector_k2k.row(sample_index) << latency;\n     }\n\n     void resize(int sample_num, model_t model_type=model_t::K2K){\n         switch (model_type)\n         {\n         case model_t::ALL:\n             matrix_l2u = MatrixXd(sample_num, L2U_FACTOR_NUM);\n             vector_l2u = VectorXd(sample_num);\n             matrix_k2u = MatrixXd(sample_num, K2U_FACTOR_NUM);\n             vector_k2u = VectorXd(sample_num);\n             matrix_k2l = MatrixXd(sample_num, K2L_FACTOR_NUM);\n             vector_k2l = VectorXd(sample_num);\n             break;\n         case model_t::L2U:\n             matrix_l2u = MatrixXd(sample_num, L2U_FACTOR_NUM);\n             vector_l2u = VectorXd(sample_num);\n             break;\n         case model_t::K2U:\n             matrix_k2u = MatrixXd(sample_num, K2U_FACTOR_NUM);\n             vector_k2u = VectorXd(sample_num);\n             break;\n         case model_t::K2L:\n             matrix_k2l = MatrixXd(sample_num, K2L_FACTOR_NUM);\n             vector_k2l = VectorXd(sample_num);\n             break;\n         case model_t::K2K:\n             matrix_k2k.resize(sample_num, K2K_FACTOR_NUM);\n             vector_k2k.resize(sample_num);\n             break;\n         default:\n             break;\n         }\n     }\n\n     void init(int sample_num, model_t model_type=model_t::ALL){\n         switch (model_type)\n         {\n         case model_t::ALL:\n             matrix_l2u = MatrixXd(sample_num, L2U_FACTOR_NUM);\n             vector_l2u = VectorXd(sample_num);\n             matrix_k2u = MatrixXd(sample_num, K2U_FACTOR_NUM);\n             vector_k2u = VectorXd(sample_num);\n             matrix_k2l = MatrixXd(sample_num, K2L_FACTOR_NUM);\n             vector_k2l = VectorXd(sample_num);\n             break;\n         case model_t::L2U:\n             matrix_l2u = MatrixXd(sample_num, L2U_FACTOR_NUM);\n             vector_l2u = VectorXd(sample_num);\n             break;\n         case model_t::K2U:\n             matrix_k2u = MatrixXd(sample_num, K2U_FACTOR_NUM);\n             vector_k2u = VectorXd(sample_num);\n             break;\n         case model_t::K2L:\n             matrix_k2l = MatrixXd(sample_num, K2L_FACTOR_NUM);\n             vector_k2l = VectorXd(sample_num);\n             break;\n         case model_t::K2K:\n             matrix_k2k = MatrixXd(sample_num, K2K_FACTOR_NUM);\n             vector_k2k = VectorXd(sample_num);\n             break;\n         default:\n             break;\n         }\n     }\n};\n\n} // namespace wukong", "meta": {"hexsha": "9711bdb7c04e240cff49f0888b55571b09bf9b51", "size": 8916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/optimizer/cost_model.hpp", "max_stars_repo_name": "SJTU-IPADS/wukong-cube", "max_stars_repo_head_hexsha": "ccabf1b754978322277dc881a43cedfd2687070f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T06:24:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T02:48:38.000Z", "max_issues_repo_path": "src/optimizer/cost_model.hpp", "max_issues_repo_name": "SJTU-IPADS/wukong-cube", "max_issues_repo_head_hexsha": "ccabf1b754978322277dc881a43cedfd2687070f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-12-22T15:11:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T15:27:50.000Z", "max_forks_repo_path": "src/optimizer/cost_model.hpp", "max_forks_repo_name": "SJTU-IPADS/wukong-cube", "max_forks_repo_head_hexsha": "ccabf1b754978322277dc881a43cedfd2687070f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-19T04:23:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T04:23:18.000Z", "avg_line_length": 36.9958506224, "max_line_length": 108, "alphanum_fraction": 0.5720053836, "num_tokens": 2521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5371058168237446}}
{"text": "#ifndef PYTHONIC_INCLUDE_NUMPY_LOGADDEXP2_HPP\n#define PYTHONIC_INCLUDE_NUMPY_LOGADDEXP2_HPP\n\n#include \"pythonic/include/utils/functor.hpp\"\n#include \"pythonic/include/types/ndarray.hpp\"\n#include \"pythonic/include/types/numpy_broadcast.hpp\"\n#include \"pythonic/include/utils/numpy_traits.hpp\"\n\n#include <boost/simd/function/log2.hpp>\n#include <boost/simd/function/pow.hpp>\nPYTHONIC_NS_BEGIN\n\nnamespace numpy\n{\n  namespace wrapper\n  {\n    template <class T0, class T1>\n    auto logaddexp2(T0 const &t0, T1 const &t1)\n        -> decltype(boost::simd::log2(boost::simd::pow(T0(2), t0) +\n                                      boost::simd::pow(T1(2), t1)));\n  }\n\n#define NUMPY_NARY_FUNC_NAME logaddexp2\n#define NUMPY_NARY_FUNC_SYM wrapper::logaddexp2\n#include \"pythonic/include/types/numpy_nary_expr.hpp\"\n}\nPYTHONIC_NS_END\n\n#endif\n", "meta": {"hexsha": "89176e5a35a669423564cbbb9396839f26343cc0", "size": 823, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pythran/pythonic/include/numpy/logaddexp2.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-24T00:33:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-24T00:33:03.000Z", "max_issues_repo_path": "pythran/pythonic/include/numpy/logaddexp2.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": "pythran/pythonic/include/numpy/logaddexp2.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "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.4333333333, "max_line_length": 68, "alphanum_fraction": 0.737545565, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5371058072704258}}
{"text": "// -*- compile-command: \"c++ -std=c++14 -O3 -DNDEBUG -ffast-math -march=native kdtree_triangles.cpp -o kdtree_triangles `pkg-config --cflags eigen3` -lstdc++\" -*-\n\n#include \"kdtree_triangles.hpp\"\n#include <Eigen/Geometry>\n\n\nusing real = double;\n\nusing vec3 = Eigen::Matrix<real, 3, 1>;\nusing quat = Eigen::Quaternion<real>;\n\nusing vec3i = Eigen::Matrix<Eigen::Index, 3, 1>\nusing vec2i = Eigen::Matrix<Eigen::Index, 2, 1>;\n\nstatic void unit_tetrahedron(std::vector<vec3>& points, std::vector<vec3i>& triangles) {\n  points.clear();\n  triangles.clear();\n  \n  const quat q1(Eigen::AngleAxis<real>(2 * M_PI / 3, vec3::UnitY()));\n  const quat q2(Eigen::AngleAxis<real>(1 * M_PI / 3, vec3::UnitZ()));\n\n  const quat q = q2 * q1;\n\n  vec3 a = vec3::UnitX();\n  vec3 b = q * a;\n  vec3 c = q * b;\n\n  const quat r = q2.conjugate() * q1;\n  vec3 d = r * a;\n\n  points = {a, b, c, d};\n\n  triangles = {{0, 2, 1},\n               {1, 2, 3},\n               {3, 0, 1},\n               {2, 0, 3}};               \n}\n\nstruct geometry {\n  std::vector<vec3> vertices;\n  std::vector<vec3i> triangles;\n};\n\n\nstatic geometry subdivide(geometry g, std::size_t n) {\n  std::map<vec2i, std::size_t> edges;\n  for(auto tri: g.triangles) {\n    for(auto e: {{tri\n  }\n}\n                      \n\n\n\nint main(int, char**) {\n  \n  std::vector<vec3> points;\n  std::ve\n  \n  return 0;\n}\n", "meta": {"hexsha": "1b308a8947170eed925b4a4e0a47ff2f9466e4ab", "size": 1336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kdtree_triangles.cpp", "max_stars_repo_name": "maxime-tournier/cpp", "max_stars_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kdtree_triangles.cpp", "max_issues_repo_name": "maxime-tournier/cpp", "max_issues_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kdtree_triangles.cpp", "max_forks_repo_name": "maxime-tournier/cpp", "max_forks_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_forks_repo_licenses": ["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.5483870968, "max_line_length": 162, "alphanum_fraction": 0.5823353293, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.537069361803488}}
{"text": "/**\n * Copyright (c) 2018, University Osnabr\u00fcck\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 University Osnabr\u00fcck 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 University Osnabr\u00fcck 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/**\n * EigenSVDPointAlign.cpp\n *\n *  @date Feb 21, 2014\n *  @author Thomas Wiemann\n */\n#include <lvr2/registration/EigenSVDPointAlign.hpp>\n\n#include <limits>\n#include <cmath>\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\nusing namespace Eigen;\nusing std::numeric_limits;\n\nnamespace lvr2\n{\n\ntemplate <typename BaseVecT>\ndouble EigenSVDPointAlign<BaseVecT>::alignPoints(const PointPairVector<BaseVecT>& pairs,\n        const BaseVecT centroid_m, const BaseVecT centroid_d, Matrix4<BaseVecT>& alignfx)\n{\n    double error = 0;\n    double sum = 0.0;\n\n    // Get centered PtPairs\n    double** m = new double*[pairs.size()];\n    double** d = new double*[pairs.size()];\n\n    for(unsigned int i = 0; i <  pairs.size(); i++){\n        m[i] = new double[3];\n        d[i] = new double[3];\n        m[i][0] = pairs[i].first.x - centroid_m[0];\n        m[i][1] = pairs[i].first.y - centroid_m[1];\n        m[i][2] = pairs[i].first.z - centroid_m[2];\n        d[i][0] = pairs[i].second.x - centroid_d[0];\n        d[i][1] = pairs[i].second.y - centroid_d[1];\n        d[i][2] = pairs[i].second.z - centroid_d[2];\n\n        sum += pow(pairs[i].first.x - pairs[i].second.x, 2)\n             + pow(pairs[i].first.y - pairs[i].second.y, 2)\n             + pow(pairs[i].first.z - pairs[i].second.z, 2) ;\n\n    }\n\n    error = sqrt(sum / (double)pairs.size());\n\n    // Fill H matrix\n    Matrix3d H, R;\n    for(int i = 0; i < 3; i++)\n    {\n        for(int j = 0; j < 3; j++)\n        {\n            H(i,j) = 0.0;\n            R(i,j) = 0.0;\n        }\n    }\n\n    for(size_t i = 0; i < pairs.size(); i++){\n        for(int j = 0; j < 3; j++){\n            for(int k = 0; k < 3; k++){\n                H(j, k) += d[i][j]*m[i][k];\n            }\n        }\n    }\n\n    JacobiSVD<Matrix3d> svd(H, ComputeFullU | ComputeFullV);\n\n    Matrix3d U = svd.matrixU();\n    Matrix3d V = svd.matrixV();\n\n    R = V * U.transpose();\n\n\n    // Calculate translation\n    double translation[3];\n\n\n    MatrixXd col_vec(3,1);\n    for(int j = 0; j < 3; j++)\n        col_vec(j,0) = centroid_d[j];\n\n    MatrixXd r_time_colVec(3,1);\n\n    r_time_colVec = R * col_vec;\n    translation[0] = centroid_m[0] - r_time_colVec(0);\n    translation[1] = centroid_m[1] - r_time_colVec(1);\n    translation[2] = centroid_m[2] - r_time_colVec(2);\n\n\n    // Fill result\n    alignfx[0] = R(0,0);\n    alignfx[1] = R(1,0);\n    alignfx[2] = 0;\n    alignfx[2] = R(2,0);\n    alignfx[3] = 0;\n    alignfx[4] = R(0,1);\n    alignfx[5] = R(1,1);\n    alignfx[6] = R(2,1);\n    alignfx[7] = 0;\n    alignfx[8] = R(0,2);\n    alignfx[9] = R(1,2);\n    alignfx[10] = R(2,2);\n    alignfx[11] = 0;\n    alignfx[12] = translation[0];\n    alignfx[13] = translation[1];\n    alignfx[14] = translation[2];\n    alignfx[15] = 1;\n\n\n    for(unsigned int i = 0; i <  pairs.size(); i++){\n        delete m[i];\n        delete d[i];\n    }\n    delete[] m;\n    delete[] d;\n\n    return error;\n}\n\n} // namespace lvr2\n", "meta": {"hexsha": "f2ef2de877c6be145fc1b13fde663ebec763ad4e", "size": 4480, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "include/lvr2/registration/EigenSVDPointAlign.tcc", "max_stars_repo_name": "jtpils/lvr2", "max_stars_repo_head_hexsha": "b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-07T03:55:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-07T03:55:27.000Z", "max_issues_repo_path": "include/lvr2/registration/EigenSVDPointAlign.tcc", "max_issues_repo_name": "jtpils/lvr2", "max_issues_repo_head_hexsha": "b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/lvr2/registration/EigenSVDPointAlign.tcc", "max_forks_repo_name": "jtpils/lvr2", "max_forks_repo_head_hexsha": "b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce", "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.8666666667, "max_line_length": 89, "alphanum_fraction": 0.6127232143, "num_tokens": 1299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5370693564049548}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    cpp_int N; cin >> N;\n\n    cpp_int three = 3;\n    for (int i = 1; i <= 37; i++) {\n        cpp_int five = 5;\n        for (int j = 1; j <= 25; j++) {\n            if (three + five == N) {\n                cout << i << \" \" << j << endl;\n                return 0;\n            }\n            else if (three + five > N) break;\n            five *= 5;\n        }\n        three *= 3;\n    }\n\n    cout << -1 << endl;\n    return 0;\n}", "meta": {"hexsha": "66c135d9371941e45c7219d102770e59c613b772", "size": 613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/arc106/a/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/arc106/a/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/arc106/a/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": 22.7037037037, "max_line_length": 46, "alphanum_fraction": 0.4681892333, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5370693535427125}}
{"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 <Eigen/Core>\n#include <Eigen/SVD>\n#include <Eigen/Eigenvalues>\n#include <glog/logging.h>\n#include <vector>\n\n#include \"theia/vision/sfm/triangulation/triangulation.h\"\n\nnamespace theia {\nusing Eigen::MatrixXd;\nusing Eigen::Matrix4d;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\n\n// Triangulates 2 posed views\nbool Triangulate(const ProjectionMatrix& pose_left,\n                 const ProjectionMatrix& pose_right,\n                 const Vector2d& point_left, const Vector2d& point_right,\n                 Vector3d* triangulated_point) {\n  Matrix4d design_matrix;\n  design_matrix.row(0) = point_left[0] * pose_left.row(2) - pose_left.row(0);\n  design_matrix.row(1) = point_left[1] * pose_left.row(2) - pose_left.row(1);\n  design_matrix.row(2) = point_right[0] * pose_right.row(2) - pose_right.row(0);\n  design_matrix.row(3) = point_right[1] * pose_right.row(2) - pose_right.row(1);\n\n  // Extract nullspace.\n  Eigen::Vector4d homog_triangulated_point =\n      design_matrix.jacobiSvd(Eigen::ComputeFullV).matrixV().rightCols<1>();\n  if (homog_triangulated_point[3] != 0) {\n    *triangulated_point = homog_triangulated_point.hnormalized();\n    return true;\n  } else {\n    return false;\n  }\n}\n\n// Triangulates N views by computing SVD that minimizes the error.\nbool TriangulateNViewSVD(const std::vector<ProjectionMatrix>& poses,\n                         const std::vector<Vector2d>& points,\n                         Vector3d* triangulated_point) {\n  CHECK_EQ(poses.size(), points.size());\n\n  MatrixXd design_matrix(3 * points.size(), 4 + points.size());\n\n  for (int i = 0; i < points.size(); i++) {\n    design_matrix.block<3, 4>(3 * i, 0) = -poses[i].matrix();\n    design_matrix.block<3, 1>(3 * i, 4 + i) = points[i].homogeneous();\n  }\n\n  // Computing SVD on A'A is more efficient and gives the same null-space.\n  Eigen::Vector4d homog_triangulated_point =\n      (design_matrix.transpose() * design_matrix).jacobiSvd(Eigen::ComputeFullV)\n          .matrixV().rightCols<1>().head(4);\n  if (homog_triangulated_point[3] != 0) {\n    *triangulated_point = homog_triangulated_point.hnormalized();\n    return true;\n  } else {\n    return false;\n  }\n}\n\nbool TriangulateNView(const std::vector<ProjectionMatrix>& poses,\n                      const std::vector<Vector2d>& points,\n                      Vector3d* triangulated_point) {\n  CHECK_EQ(poses.size(), points.size());\n\n  Matrix4d design_matrix = Matrix4d::Zero();\n  for (int i = 0; i < points.size(); i++) {\n    const Vector3d norm_point = points[i].homogeneous().normalized();\n    const Eigen::Matrix<double, 3, 4> cost_term =\n        poses[i].matrix() -\n        norm_point * norm_point.transpose() * poses[i].matrix();\n    design_matrix = design_matrix + cost_term.transpose() * cost_term;\n  }\n\n  Eigen::SelfAdjointEigenSolver<Matrix4d> eigen_solver(design_matrix);\n  Eigen::Vector4d homog_triangulated_point = eigen_solver.eigenvectors().col(0);\n  if (homog_triangulated_point[3] != 0) {\n    *triangulated_point = homog_triangulated_point.hnormalized();\n    return true;\n  } else {\n    return false;\n  }\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "3cbb97c2817135d5e62c812fee39798d5e084c39", "size": 4881, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/vision/sfm/triangulation/triangulation.cc", "max_stars_repo_name": "nuernber/Theia", "max_stars_repo_head_hexsha": "4bac771b09458a46c44619afa89498a13cd39999", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-02T13:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T13:30:52.000Z", "max_issues_repo_path": "src/theia/vision/sfm/triangulation/triangulation.cc", "max_issues_repo_name": "nuernber/Theia", "max_issues_repo_head_hexsha": "4bac771b09458a46c44619afa89498a13cd39999", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/vision/sfm/triangulation/triangulation.cc", "max_forks_repo_name": "nuernber/Theia", "max_forks_repo_head_hexsha": "4bac771b09458a46c44619afa89498a13cd39999", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T08:43:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T08:43:13.000Z", "avg_line_length": 40.3388429752, "max_line_length": 80, "alphanum_fraction": 0.7043638599, "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5370693489896096}}
{"text": "#ifndef SVDSENSITIVITY_HH\n#define SVDSENSITIVITY_HH\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.\nstruct SVDSensitivity {\n    using M2d = Eigen::Matrix2d;\n    using V2d = Eigen::Vector2d;\n\n    SVDSensitivity() { }\n\n    template<typename Derived>\n    SVDSensitivity(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        Eigen::JacobiSVD<M2d> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        m_U     = svd.matrixU();\n        m_V     = svd.matrixV();\n        m_Sigma = svd.singularValues();\n\n        // Cache first derivatives (needed for computing second derivatives)\n        m_dSigma[0] = m_U.col(0) * m_V.col(0).transpose();\n        m_dSigma[1] = m_U.col(1) * m_V.col(1).transpose();\n\n        const double sigmaSqDiff = m_Sigma[0] * m_Sigma[0] - m_Sigma[1] * m_Sigma[1];\n        if (std::abs(sigmaSqDiff) < 1e-15) { m_degenerate =  true; m_invSigmaSqDiff = 0.0; }\n        else                               { m_degenerate = false; m_invSigmaSqDiff = 1.0 / sigmaSqDiff; }\n\n        m_y = m_invSigmaSqDiff * (m_Sigma[1] * m_U.col(0) * m_V.col(1).transpose()\n                                + m_Sigma[0] * m_U.col(1) * m_V.col(0).transpose());\n        m_du0[0] =  m_y * m_U(0, 1);\n        m_du0[1] =  m_y * m_U(1, 1);\n        m_du1[0] = -m_y * m_U(0, 0);\n        m_du1[1] = -m_y * m_U(1, 0);\n\n        m_z = m_invSigmaSqDiff * (m_Sigma[0] * m_U.col(0) * m_V.col(1).transpose()\n                                + m_Sigma[1] * m_U.col(1) * m_V.col(0).transpose());\n        m_dv0[0] =  m_z * m_V(0, 1);\n        m_dv0[1] =  m_z * m_V(1, 1);\n        m_dv1[0] = -m_z * m_V(0, 0);\n        m_dv1[1] = -m_z * m_V(1, 0);\n    }\n\n    // Access SVD\n    const M2d &    U() const { return m_U; }\n    const M2d &    V() const { return m_V; }\n    const V2d &Sigma() const { return m_Sigma; }\n\n    auto       u(size_t i) const { return m_U.col(i); }\n    auto       v(size_t i) const { return m_V.col(i); }\n    double sigma(size_t i) const { return m_Sigma[i]; }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // First derivative expressions\n    ////////////////////////////////////////////////////////////////////////////\n    M2d dsigma(size_t i) const { return m_dSigma.at(i); }\n    M2d du0   (size_t i) const { return m_du0   .at(i); }\n    M2d du1   (size_t i) const { return m_du1   .at(i); }\n    M2d dv0   (size_t i) const { return m_dv0   .at(i); }\n    M2d dv1   (size_t i) const { return m_dv1   .at(i); }\n\n    template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> V2d dSigma(const M2d_ &dA) const { return V2d(doubleContract(m_dSigma[0], dA), doubleContract(m_dSigma[1], dA)); }\n    template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> V2d du0   (const M2d_ &dA) const { return V2d(doubleContract(m_du0   [0], dA), doubleContract(m_du0   [1], dA)); }\n    template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> V2d du1   (const M2d_ &dA) const { return V2d(doubleContract(m_du1   [0], dA), doubleContract(m_du1   [1], dA)); }\n    template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> V2d dv0   (const M2d_ &dA) const { return V2d(doubleContract(m_dv0   [0], dA), doubleContract(m_dv0   [1], dA)); }\n    template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> V2d dv1   (const M2d_ &dA) const { return V2d(doubleContract(m_dv1   [0], dA), doubleContract(m_dv1   [1], dA)); }\n\n    template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0>\n    double dsigma(size_t i, const M2d_ &dA) const { return doubleContract(m_dSigma[i], dA); }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Second derivative expressions\n    ////////////////////////////////////////////////////////////////////////////\n    // Note, to avoid using high order tensors, we only provide the contraction of the\n    // singular value/vector Hessians with perturbation matrices.\n\n    // Second derivative of singular values with respect to variables inducing\n    // perturbations dA_1 and dA_2, respectively.\n    template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0>\n    V2d d2Sigma(const M2d_ &dA_1, const M2d_ &dA_2) const {\n        return V2d(du0(dA_2).dot((dA_1 * m_V.col(0)).matrix()) + m_U.col(0).dot((dA_1 * dv0(dA_2)).matrix()),\n                   du1(dA_2).dot((dA_1 * m_V.col(1)).matrix()) + m_U.col(1).dot((dA_1 * dv1(dA_2)).matrix()));\n    }\n    template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0>\n    double d2sigma(size_t i, const M2d_ &dA_1, const M2d_ &dA_2) const {\n        if (i == 0) return du0(dA_2).dot((dA_1 * m_V.col(0)).matrix()) + m_U.col(0).dot((dA_1 * dv0(dA_2)).matrix());\n        if (i == 1) return du1(dA_2).dot((dA_1 * m_V.col(1)).matrix()) + m_U.col(1).dot((dA_1 * dv1(dA_2)).matrix());\n        throw std::runtime_error(\"Index out of bounds\");\n    }\n\n    // Second derivative of first left singular vector with respect to variables inducing\n    // perturbations dA_1 and dA_2, respectively.\n    template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0>\n    V2d d2u0(const M2d_ &dA_1, const M2d_ &dA_2) const {\n        M2d Ut_dA1_V = m_U.transpose() * (dA_1 * m_V);\n\n        V2d d_sigma_d2 = dSigma(dA_2);\n        const double y1 = doubleContract(m_y, dA_1);\n        const double y2 = doubleContract(m_y, dA_2);\n        const double z2 = doubleContract(m_z, dA_2);\n\n        const double dy1_d2 = m_invSigmaSqDiff * (d_sigma_d2[1] * (2 * m_Sigma[1] * y1 + Ut_dA1_V(0, 1)) + d_sigma_d2[0] * (Ut_dA1_V(1, 0) - 2 * m_Sigma[0] * y1)\n                                                  + Ut_dA1_V(1, 1) * (m_Sigma[1] * y2 + m_Sigma[0] * z2)\n                                                  - Ut_dA1_V(0, 0) * (m_Sigma[0] * y2 + m_Sigma[1] * z2));\n\n        return dy1_d2 * m_U.col(1) - y1 * y2 * m_U.col(0);\n    }\n\n    // Second derivative of second right singular vector with respect to variables inducing\n    // perturbations dA_1 and dA_2, respectively.\n    //      -d z_1 / d2 v0 - z_1 z_2 v1\n    // Note: \"z\" is the same as \"y\" with sigma_0 and sigma_1 swapped (apart from the m_invSigmaSqDiff factor).\n    template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0>\n    V2d d2v1(const M2d_ &dA_1, const M2d_ &dA_2) const {\n        M2d Ut_dA1_V = m_U.transpose() * (dA_1 * m_V);\n\n        V2d d_sigma_d2 = dSigma(dA_2);\n        const double z1 = doubleContract(m_z, dA_1);\n        const double z2 = doubleContract(m_z, dA_2);\n        const double y2 = doubleContract(m_y, dA_2);\n\n        const double dz1_d2 = m_invSigmaSqDiff * (d_sigma_d2[0] * (Ut_dA1_V(0, 1) - 2 * m_Sigma[0] * z1) + d_sigma_d2[1] * (Ut_dA1_V(1, 0) + 2 * m_Sigma[1] * z1)\n                                                  + Ut_dA1_V(1, 1) * (m_Sigma[0] * y2 + m_Sigma[1] * z2)\n                                                  - Ut_dA1_V(0, 0) * (m_Sigma[1] * y2 + m_Sigma[0] * z2));\n\n        return -dz1_d2 * m_V.col(0) - z1 * z2 * m_V.col(1);\n    }\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n    M2d m_U, m_V, m_y, m_z;\n    V2d m_Sigma;\n\n    bool m_degenerate;\n    double m_invSigmaSqDiff;\n\n    std::array<M2d, 2> m_dSigma;\n    std::array<M2d, 2> m_du0, m_du1,\n                       m_dv0, m_dv1;\n};\n\n#endif /* end of include guard: SVDSENSITIVITY_HH */\n", "meta": {"hexsha": "2e6e2f5fda2244b3f5b534f8f78b9ba319590cec", "size": 7520, "ext": "hh", "lang": "C++", "max_stars_repo_path": "SVDSensitivity.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": "SVDSensitivity.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": "SVDSensitivity.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": 51.156462585, "max_line_length": 185, "alphanum_fraction": 0.572606383, "num_tokens": 2646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5370693444365066}}
{"text": "#include \"Interrupt.h\"\n#include \"OGR.h\"\n#include \"ProjInfo.h\"\n#include \"Shape_circle.h\"\n#include \"Shape_rect.h\"\n#include \"SpatialReference.h\"\n#include <boost/math/constants/constants.hpp>\n#include <macgyver/Exception.h>\n#include <ogr_geometry.h>\n#include <ogr_spatialref.h>\n\n#include <iostream>\n\nnamespace Fmi\n{\nconst double epsilon = 1e-6;\n\nconst double wgs84radius = 6378137.0;\n\nconst int default_circle_segments = 360;\n\n// Longitude to -180...180 range\ndouble modlon(double lon)\n{\n  try\n  {\n    if (lon > 180)\n      return fmod(lon + 180, 360) - 180;\n    if (lon < -180)\n      return -(fmod(-lon + 180, 360) - 180);\n    return lon;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// Create a circle in WGS84 coordinates. Range may span from -360 to +360\n\nOGRPolygon* make_circle(double lon, double lat, double radius, int segments)\n{\n  try\n  {\n    auto* poly = new OGRPolygon;\n    auto* ring = new OGRLinearRing;\n\n    // We start from -180 instead of zero for southern circles to avoid extra joining work\n    const auto angle_offset = (lat >= 0 ? 0.0 : -M_PI);\n\n    const auto lon1 = lon * boost::math::double_constants::degree;\n    const auto lat1 = lat * boost::math::double_constants::degree;\n    const auto dr = radius / wgs84radius;  // angular distance in radians\n\n    const auto sindr = sin(dr);\n    const auto cosdr = cos(dr);\n\n    const auto sinlat1 = sin(lat1);\n    const auto coslat1 = cos(lat1);\n\n    for (int i = 0; i <= segments; i++)\n    {\n      const auto angle = 2 * M_PI * i / segments + angle_offset;\n\n      auto la = asin(sinlat1 * cosdr + coslat1 * sindr * cos(angle));\n      auto lo = lon1 + atan2(sin(angle) * sindr * coslat1, cosdr - sinlat1 * sin(la));\n\n      la *= boost::math::double_constants::radian;\n      lo *= boost::math::double_constants::radian;\n\n      // Note: No mod 360 math here, we wish to preserve the overflow for clipping\n\n      ring->addPoint(lo, la);\n    }\n\n    // Now we need to check if we must add either pole to close the ring\n\n    const auto n = ring->getNumPoints();\n\n    const auto x1 = ring->getX(0);\n    const auto y1 = ring->getY(0);\n    auto x2 = ring->getX(n - 1);\n    auto y2 = ring->getY(n - 1);\n\n    const double step = 10;  // degrees\n\n    if (std::hypot(x1 - x2, y1 - y2) > 1e-3)\n    {\n      if (lat >= 0)\n      {\n        // close via north pole\n        while (y2 + step < 90)\n        {\n          y2 += step;\n          ring->addPoint(x2, y2);\n        }\n        while (x2 < x1)\n        {\n          ring->addPoint(x2, 90);\n          x2 += step;\n        }\n        y2 = 90;\n        while (y2 > y1)\n        {\n          ring->addPoint(x1, y2);\n          y2 -= step;\n        }\n      }\n      else\n      {\n        // close via south pole\n        while (y2 - step > -90)\n        {\n          y2 -= step;\n          ring->addPoint(x2, y2);\n        }\n        while (x2 > x1)\n        {\n          ring->addPoint(x2, -90);\n          x2 -= step;\n        }\n        y2 = -90;\n        while (y2 < y1)\n        {\n          ring->addPoint(x1, y2);\n          y2 += step;\n        }\n      }\n    }\n\n    ring->closeRings();  // close if not already closed\n    poly->addRingDirectly(ring);\n    return poly;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// Create a rect\n\nOGRPolygon* make_rect(double x1, double y1, double x2, double y2)\n{\n  try\n  {\n    auto* poly = new OGRPolygon;\n    auto* ring = new OGRLinearRing;\n\n    ring->addPoint(x1, y1);\n    ring->addPoint(x1, y2);\n    ring->addPoint(x2, y2);\n    ring->addPoint(x2, y1);\n    ring->addPoint(x1, y1);\n\n    poly->addRingDirectly(ring);\n    return poly;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// Create a circle cutgeometry\n\nOGRGeometry* circle_cut(double lon,\n                        double lat,\n                        double radius,\n                        int segments = default_circle_segments)\n{\n  try\n  {\n    // One circle\n    auto* geom = make_circle(lon, lat, radius, segments);\n\n    // Extract envelope\n\n    OGREnvelope env;\n    geom->getEnvelope(&env);\n\n    // Nothing to do if the circle is fully within normal bounds\n    if (env.MinX >= -180 && env.MaxX <= 180)\n    {\n      geom->assignSpatialReference(OGRSpatialReference::GetWGS84SRS());\n      return geom;\n    }\n\n    // Otherwise we must take at least 2 intersections, maybe 3\n\n    auto* result = new OGRGeometryCollection;\n\n    auto* rect = make_rect(-180, -90, 180, 90);\n    auto* cut = geom->Intersection(rect);\n    if (cut != nullptr && cut->IsEmpty() == 0)\n      result->addGeometryDirectly(cut);\n    CPLFree(rect);\n\n    if (env.MinX < -180)\n    {\n      auto* rect = make_rect(-540, -90, -180, 90);\n      auto* cut = geom->Intersection(rect);\n      OGR::translate(cut, +360, 0);\n      if (cut != nullptr && cut->IsEmpty() == 0)\n        result->addGeometryDirectly(cut);\n      CPLFree(rect);\n    }\n\n    if (env.MaxX > 180)\n    {\n      auto* rect = make_rect(180, -90, 540, 90);\n      auto* cut = geom->Intersection(rect);\n      OGR::translate(cut, -360, 0);\n      if (cut != nullptr && cut->IsEmpty() == 0)\n        result->addGeometryDirectly(cut);\n      CPLFree(rect);\n    }\n\n    CPLFree(geom);\n\n    result->assignSpatialReference(OGRSpatialReference::GetWGS84SRS());\n    return result;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nShape_sptr make_vertical_cut(double lon, double lat1, double lat2)\n{\n  try\n  {\n    return std::make_shared<Shape_rect>(\n        lon - epsilon, std::min(lat1, lat2), lon + epsilon, std::max(lat1, lat2));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nShape_sptr make_horizontal_cut(double lat, double lon1, double lon2)\n{\n  try\n  {\n    return std::make_shared<Shape_rect>(\n        std::min(lon1, lon2), lat - epsilon, std::max(lon1, lon2), lat + epsilon);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nInterrupt interruptGeometry(const SpatialReference& theSRS)\n{\n  try\n  {\n    Interrupt result;\n\n    const auto opt_name = theSRS.projInfo().getString(\"proj\");\n    if (!opt_name)\n      return result;\n\n    const auto name = *opt_name;\n\n    const auto opt_lon_0 = theSRS.projInfo().getDouble(\"lon_0\");\n    const auto lon_0 = opt_lon_0 ? *opt_lon_0 : 0.0;\n\n    const auto opt_lat_0 = theSRS.projInfo().getDouble(\"lat_0\");\n    const auto lat_0 = opt_lat_0 ? *opt_lat_0 : 0.0;\n\n    // If general oblique transformation such as rotated latlon, cut the Antarctic in half at the\n    // central meridian. -60 is large enough to make the cut, since Drake passage is below\n    // that latitude. In reality, the cut should be made for any polygon which spans the south pole,\n    // and the cut should be made for that polygon only. Hence this code is not generic enough.\n    // Similar logic would be needed for the north pole should there be a polygon covering it.\n    //\n    // The Interrupt struct should thus contain conditional cuts for individual polygons based\n    // on the envelope of the individual polygon. The current implementation does not support this.\n    //\n    // The code commented out shows various tests used to find out how a nonzero lon_0 should be\n    // handled, but the (random) experimental approach failed.\n\n    if (theSRS.projInfo().getString(\"proj\") == std::string(\"ob_tran\"))\n    {\n      auto opt_lat_p = theSRS.projInfo().getDouble(\"o_lat_p\");\n      if (opt_lat_p)\n      {\n        const auto opt_lon_0 = theSRS.projInfo().getDouble(\"lon_0\");\n        const auto lon_0 = (opt_lon_0 ? *opt_lon_0 : 0.0);\n\n        const auto lat_p = *opt_lat_p;\n\n        result.shapeCuts.emplace_back(make_vertical_cut(0, -90, lat_p - 90));\n        result.shapeCuts.emplace_back(make_vertical_cut(lon_0, -90, lat_p - 90));\n        result.shapeCuts.emplace_back(make_vertical_cut(-lon_0, -90, lat_p - 90));\n\n        result.shapeCuts.emplace_back(make_vertical_cut(lat_p, -90, lat_p - 90));\n        result.shapeCuts.emplace_back(make_vertical_cut(-lat_p, -90, lat_p - 90));\n\n        result.shapeCuts.emplace_back(make_horizontal_cut(-lat_p, -180, 180));\n        result.shapeCuts.emplace_back(make_horizontal_cut(-90, -180, 180));\n        result.shapeCuts.emplace_back(make_horizontal_cut(+90, -180, 180));\n        result.shapeCuts.emplace_back(make_vertical_cut(+180, -90, 90));\n        result.shapeCuts.emplace_back(make_vertical_cut(-180, -90, 90));\n      }\n    }\n\n    // Geographic: cut everything at lon_wrap (default=Greenwich) antimeridians\n    if (theSRS.isGeographic())\n    {\n      const auto opt_lon_wrap = theSRS.projInfo().getDouble(\"lon_wrap\");\n      const auto lon_wrap = (opt_lon_wrap ? *opt_lon_wrap : 0.0);\n\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_wrap + 180), -90, 90));\n      if (lon_wrap == 0)\n        result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_wrap - 180), -90, 90));\n\n      return result;\n    }\n\n    if (name == \"laea\")\n    {\n      // Poles always project to x-coordinate zero, we need to cut them out too\n      // Cannot use epsilon here, the cut would be too small for PROJ.7\n      result.shapeClips.push_back(std::make_shared<Shape_rect>(-178, -89.99, 178, 89.99));\n      return result;\n    }\n\n    if (name == \"nicol\")\n    {\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 180), -90, 90));\n      if (lon_0 == 0)\n        result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 180), -90, 90));\n\n      // TODO: proj=nicol is hard to handle correctly since the projection seems to wrap\n      // around itself around -+90 longitudes\n      //\n      // Very slow:\n      // result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 90), -90, 90));\n      // result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 90), -90, 90));\n      return result;\n    }\n\n    if (name == \"nsper\")\n    {\n      // TODO: Something odd, maybe the result is shifted?\n      const auto radius = 90 * wgs84radius * boost::math::double_constants::degree;\n      result.andGeometry.reset(circle_cut(lon_0, lat_0, radius));\n      return result;\n    }\n\n    if (name == \"tcc\")\n    {\n      // TODO: Figure out what's wrong in longitude range 90...130\n      result.shapeCuts.emplace_back(std::make_shared<Shape_rect>(90, -90, 130, 90));\n      return result;\n    }\n\n    if (name == \"lcc\")\n    {\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 180), -90, 90));\n      if (lon_0 == 0)\n        result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 180), -90, 90));\n      result.shapeCuts.emplace_back(make_horizontal_cut(-90, -180, 180));\n    }\n\n    if (name == \"imw_p\")\n    {\n      // TODO: Slow as hell, disabled for now\n      // const auto radius = 80 * wgs84radius * boost::math::double_constants::degree;\n      // result.andGeometry.reset(circle_cut(lon_0, lat_0, radius));\n      return result;\n    }\n\n    if (name == \"aeqd\")\n    {\n      // TODO: 130 is just an experimental value getting some things right, but\n      // this clipping is not even close to correct. Not sure what kind of clipping this needs.\n      //\n      // Also: The antarctic is missing completely. Probably the fault of the current\n      // version of circle cutting.\n\n      const auto radius = 130 * wgs84radius * boost::math::double_constants::degree;\n      result.andGeometry.reset(circle_cut(lon_0, lat_0, radius));\n      return result;\n    }\n\n    if (name == \"tmerc\")\n    {\n      // TODO: This is just experimental to get something out\n      // const auto radius = 90 * wgs84radius * boost::math::double_constants::degree;\n      // result.andGeometry.reset(circle_cut(lon_0, lat_0, radius));\n      return result;\n    }\n    if (name == \"gstmerc\")\n    {\n      // 90 causes errors\n      const auto radius = 89.5 * wgs84radius * boost::math::double_constants::degree;\n      result.andGeometry.reset(circle_cut(lon_0, lat_0, radius));\n      return result;\n    }\n\n    if (name == \"gnom\")\n    {\n      // TODO: Nothing seems to work, result is full of NaN values\n      const auto radius = 89 * wgs84radius * boost::math::double_constants::degree;\n      result.andGeometry.reset(circle_cut(lon_0, lat_0, radius));\n      return result;\n    }\n\n    if (name == \"airy\" || name == \"ortho\")\n    {\n      const auto radius = 90 * wgs84radius * boost::math::double_constants::degree;\n      result.andGeometry.reset(circle_cut(lon_0, lat_0, radius));\n      return result;\n    }\n\n    if (name == \"tpers\")\n    {\n      // 50 was found experimentally\n      const auto radius = 50 * wgs84radius * boost::math::double_constants::degree;\n      result.andGeometry.reset(circle_cut(lon_0, lat_0, radius));\n      return result;\n    }\n\n    if (name == \"geos\")\n    {\n      // 80 was found experimentally\n      const auto radius = 80 * wgs84radius * boost::math::double_constants::degree;\n      result.andGeometry.reset(circle_cut(lon_0, lat_0, radius));\n      return result;\n    }\n\n    if (name == \"adams_hemi\")\n    {\n      // TODO: Just something that works on small scales not up to the maximum\n      const auto radius = 90 * wgs84radius * boost::math::double_constants::degree;\n      result.andGeometry.reset(circle_cut(lon_0, lat_0, radius));\n      return result;\n    }\n\n    if (name == \"bertin1953\" || name == \"peirce_q\")\n    {\n      // TODO: No idea how to fix these\n      return result;\n    }\n\n    if (name == \"tpeqd\")\n    {\n      const auto opt_lon_1 = theSRS.projInfo().getDouble(\"lon_1\");\n      const auto lon_1 = opt_lon_1 ? *opt_lon_1 : 0.0;\n\n      const auto opt_lat_1 = theSRS.projInfo().getDouble(\"lat_1\");\n      const auto lat_1 = opt_lat_1 ? *opt_lat_1 : 0.0;\n\n      const auto opt_lon_2 = theSRS.projInfo().getDouble(\"lon_2\");\n      const auto lon_2 = opt_lon_2 ? *opt_lon_2 : 0.0;\n\n      const auto opt_lat_2 = theSRS.projInfo().getDouble(\"lat_2\");\n      const auto lat_2 = opt_lat_2 ? *opt_lat_2 : 0.0;\n\n      // Hack solution: rough estimate on the center\n      const auto lon = 0.5 * (lon_1 + lon_2);\n      const auto lat = 0.5 * (lat_1 + lat_2);\n\n      const auto radius = 145 * wgs84radius * boost::math::double_constants::degree;\n      result.andGeometry.reset(circle_cut(lon, lat, radius));\n      return result;\n    }\n\n    if (name == \"igh\")\n    {\n      // Interrupted Goode Homolosine\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 180), -90, 90));\n      if (lon_0 == 0)\n        result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 180), -90, 90));\n\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 40), 0, 90));\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 100), -90, 0));\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 20), -90, 0));\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 80), -90, 0));\n\n      return result;\n    }\n\n    if (name == \"igh_o\")\n    {\n      // Interrupted Goode Homolosine (Oseanic)\n\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 180), -90, 90));\n      if (lon_0 == 0)\n        result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 180), -90, 90));\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 90), 0, 90));\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 60), 0, 90));\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 60), -90, 0));\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 90), -90, 0));\n      return result;\n    }\n\n    if (name == \"healpix\")\n    {\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 180), -90, 90));\n      if (lon_0 == 0)\n        result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 180), -90, 90));\n\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 90), -90, -45));\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 90), 45, 90));\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0), -90, -45));\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0), 45, 90));\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 90), -90, -45));\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 90), 45, 90));\n\n      return result;\n    }\n\n    if (name == \"isea\")\n    {\n      // Icosahedral Snyder Equal Area.\n      // TODO: PROJ.7 implementation seems to have the cuts at odd locations, perhaps a bug?\n\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 180), -90, 90));\n      if (lon_0 == 0)\n        result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 180), -90, 90));\n\n      // result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 108), 30, 90));\n      // result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 36), 30, 90));\n      // result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 36), 30, 90));\n      // result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 108), 30, 90));\n      //\n      // result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 144), -90, -30));\n      // result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 72), -90, -30));\n      // result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 0), -90, -30));\n      // result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 72), -90, -30));\n      // result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 144), -90, -30));\n\n      return result;\n    }\n\n    // Regular geometric: cut everything at lon_0+180 antimeridian\n    // lon_0 is needed for all remaining geometric projections\n\n    result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 + 180), -90, 90));\n    if (lon_0 == 0)\n      result.shapeCuts.emplace_back(make_vertical_cut(modlon(lon_0 - 180), -90, 90));\n\n    return result;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nOGREnvelope interruptEnvelope(const SpatialReference& theSRS)\n{\n  try\n  {\n    // Default answer covers nothing. User should check for this special case.\n    OGREnvelope env;\n    env.MinY = 0;\n    env.MaxY = 0;\n    env.MinX = 0;\n    env.MaxX = 0;\n\n    if (theSRS.isGeographic())\n    {\n      // geographic projections are modified by +lon_wrap which defines the wanter center longitude\n      const auto opt_lon_wrap = theSRS.projInfo().getDouble(\"lon_wrap\");\n      const auto lon_wrap = (opt_lon_wrap ? *opt_lon_wrap : 0);\n\n      env.MinY = -90;\n      env.MaxY = +90;\n      env.MinX = lon_wrap - 180;\n      env.MaxX = lon_wrap + 180;\n      return env;\n    }\n\n    // For geometric projections the default box is modified by +lon_0\n    // whose default value is zero.  Anything not rectilinear must be\n    // clipped to produce shorted edges at the antimeridians, or the\n    // edges will not curve nicely enough when projected. In practise it\n    // seems like only cylindrical projections and pseudocylindrical\n    // projections with straight sides such as collg can be handled via\n    // envelopes.\n\n    const auto opt_name = theSRS.projInfo().getString(\"proj\");\n    if (!opt_name)\n      return env;\n    const auto name = *opt_name;\n\n    if (name == \"cc\" || name == \"cea\" || name == \"collg\" || name == \"comill\" || name == \"eqc\" ||\n        name == \"fouc_s\" || name == \"gall\" || name == \"merc\" || name == \"mill\" || name == \"ocea\" ||\n        name == \"patterson\" || name == \"webmerc\")\n    {\n      const auto opt_lon_0 = theSRS.projInfo().getDouble(\"lon_0\");\n      const auto lon_0 = opt_lon_0 ? *opt_lon_0 : 0.0;\n\n      env.MinY = -90;\n      env.MaxY = +90;\n      env.MinX = lon_0 - 180;\n      env.MaxX = lon_0 + 180;\n    }\n\n    return env;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n}  // namespace Fmi\n", "meta": {"hexsha": "2551a8f06bd39b182c8b17f1841ebe326be22c90", "size": 19629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gis/Interrupt.cpp", "max_stars_repo_name": "fmidev/smartmet-library-gis", "max_stars_repo_head_hexsha": "3fd5e7ede8f04e262d7de3f884fb575d98ae956d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gis/Interrupt.cpp", "max_issues_repo_name": "fmidev/smartmet-library-gis", "max_issues_repo_head_hexsha": "3fd5e7ede8f04e262d7de3f884fb575d98ae956d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-01T10:15:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-11T10:53:26.000Z", "max_forks_repo_path": "gis/Interrupt.cpp", "max_forks_repo_name": "fmidev/smartmet-library-gis", "max_forks_repo_head_hexsha": "3fd5e7ede8f04e262d7de3f884fb575d98ae956d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-16T15:14:06.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-16T15:14:06.000Z", "avg_line_length": 31.8652597403, "max_line_length": 100, "alphanum_fraction": 0.6271333231, "num_tokens": 5568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.537042219859494}}
{"text": "// ==BEGIN LICENSE==\n// \n// MIT License\n// \n// Copyright (c) 2018 SRI Lab, ETH Zurich\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// ==END LICENSE==\n\n\n#include <iostream>\n#include <math.h>\n#include <boost/math/distributions/normal.hpp> // for normal_distribution\n#include <dlfcn.h> // for loading shared library\n#include \"toms462.hpp\"\n\nusing boost::math::normal; // typedef provides default type is double.\n\nusing namespace std;\n\ntypedef double numb;\n\n// http://static.stevereads.com/papers_to_read/on_the_ratio_of_two_correlated_normal_random_variables.pdf -> page 3\n\n\n// LOAD TOMS462 functions\n#define STRINGIFY2(X) #X\n#define STRINGIFY(X) STRINGIFY2(X)\ntypedef double (*bivnorlib_t)( double ah, double ak, double r );\ndouble bivnor( double ah, double ak, double r ){\n\tvoid* lib = dlopen(STRINGIFY(MYPATH)\"/libtoms462.so\", RTLD_LAZY);\n\tbivnorlib_t bivnorlib = (bivnorlib_t)dlsym(lib, \"bivnor\" );\n\tdouble ret = bivnorlib(ah, ak, r);\n\tdlclose(lib);\n\treturn ret;\n}\n\n\n// MY FUNCTIONS\n\nnumb a(numb w, numb sx, numb sy, numb rho){\n\tnumb w2=w*w;\n\tnumb sx2=sx*sx;\n\tnumb sy2=sy*sy;\n\treturn sqrt(w2/sx2-2*rho*w/(sx*sy)+1/sy2);\n}\n\ndouble b(double w, double mx, double my, double sx, double sy, double rho){\n\tdouble sx2=sx*sx;\n\tdouble sy2=sy*sy;\n\treturn mx*w/sx2-rho*(mx+my*w)/(sx*sy)+my/sy2;\n}\n\ndouble c(double mx, double my, double sx, double sy, double rho){\n\tdouble mx2=mx*mx;\n\tdouble sx2=sx*sx;\n\tdouble my2=my*my;\n\tdouble sy2=sy*sy;\n\treturn mx2/sx2-2*rho*mx*my/(sx*sy)+my2/sy2;\n}\n\ndouble d(double w, double mx, double my, double sx, double sy, double rho){\n\tdouble a_=a(w,sx,sy,rho);\n\tdouble a2=a_*a_;\n\tdouble b_=b(w,mx,my,sx,sy,rho);\n\tdouble b2=b_*b_;\n\tdouble c_=c(mx,my,sx,sy,rho);\n\tdouble rho2=rho*rho;\n\treturn exp((b2-c_*a2)/(2*(1-rho2)*a2));\n}\n\nnumb phi(numb x){\n\tnormal s; // (default mean = zero, and standard deviation = unity)\n\treturn cdf(s,x);\n}\n\nnumb ratio_pdf(numb w, numb mx, numb my, numb sx, numb sy, numb rho){\n\tnumb a_=a(w,sx,sy,rho);\n\tnumb b_=b(w,mx,my,sx,sy,rho);\n\tnumb c_=c(mx,my,sx,sy,rho);\n\tnumb d_=d(w,mx,my,sx,sy,rho);\n\t\n\tnumb a2=a_*a_;\n\tnumb a3=a_*a_*a_;\n\tnumb rho2=rho*rho;\n\t\n\tnumb pi=M_PI;\n\t\n\tnumb frac1=b_*d_/(sqrt(2*pi)*sx*sy*a3);\n\tnumb arg1=b_/(sqrt(1-rho2)*a_);\n\tnumb arg2=-b_/(sqrt(1-rho2)*a_);\n\tnumb frac2=sqrt(1-rho2)/(pi*sx*sy*a2);\n\tnumb e=exp(-c_/(2*(1-rho2)));\n\t\n\treturn frac1*(phi(arg1)-phi(arg2))+frac2*e;\n}\n\nnumb ratio_cdf(numb w, numb mx, numb my, numb sx, numb sy, numb rho){\n\t//cout << \"Running ratio_cdf with \" << w << \"/\" << mx << \"/\" << my << \"/\" << sx << \"/\" << sy << endl;\n\n\tnumb a_=a(w,sx,sy,rho);\n\n\tnumb h1=(mx-my*w)/(sx*sy*a_);\n\tnumb k1=-my/sy;\n\tnumb gamma=(sy*w-rho*sx)/(sx*sy*a_);\n\t//cout << \"Running with \" << h1 << \"/\" << k1 << \"/\" << gamma << endl;\n\tnumb L1=bivnor(h1,k1,gamma);\n\t\n\tnumb h2=(my*w-mx)/(sx*sy*a_);\n\tnumb k2=my/sy;\n\t//cout << \"Running with \" << h2 << \"/\" << k2 << \"/\" << gamma << endl;\n\tnumb L2=bivnor(h2,k2,gamma);\n\t\n\tnumb ret=L1+L2;\n\treturn ret;\n}\n\ndouble ratio_cdf(double lower, double upper, double mx, double my, double sx, double sy, double rho){\n\t//mpf_set_default_prec(n_bits);\n\t\n\tnumb lower_=lower;\n\tnumb upper_=upper;\n\tnumb mx_=mx;\n\tnumb my_=my;\n\tnumb sx_=sx;\n\tnumb sy_=sy;\n\tnumb rho_=rho;\n\t\n\tnumb cdf1=ratio_cdf(upper_, mx_, my_, sx_, sy_, rho_);\n\tnumb cdf2=ratio_cdf(lower_, mx_, my_, sx_, sy_, rho_);\n\t\n\tnumb ret=cdf1-cdf2;\n\treturn ret;//ret.get_d();\n}\n\ndouble interval_fallback_threshold=1e-7;\n\ndouble get_err_interval(double p1,double p2,double std1,double std2,double center, double confidence){\n\tdouble confidence_2=1-(1-confidence)/2;\n\tdouble z_2=sqrt(2)*boost::math::erf_inv(confidence_2);\n\tdouble d1=std1*z_2;\n\tdouble d2=std2*z_2;\n\tif (p2>p1){\n\t\tswap(p1,p2);\n\t\tswap(d1,d2);\n\t}\n\tdouble err=0;\n\tif (p2-d2<=0){\n\t\t// p2 may be 0\n\t\tif (p2+d2<=0){\n\t\t\t// p2 must be 0. Thus, eps must be infinity\n\t\t\terr=0;\n\t\t}else{\n\t\t\t// p2 may or may not be 0. Thus, eps may or may not be infinity\n\t\t\terr=numeric_limits<double>::infinity();\n\t\t}\n\t}else if (p1-d1<=0){\n\t\t\t// p1 may be 0. In that case, eps would have to be -inf\n\t\t\terr=numeric_limits<double>::infinity();\n\t}else{\n\t\t// neither p1 nor p2 can be 0\n\t\tdouble min_eps=log(p1-d1)-log(p2+d2);\n\t\tdouble max_eps=log(p1+d1)-log(p2-d2);\n\t\tmax_eps=max(max_eps,abs(min_eps));\n\t\tmin_eps=max(min_eps,0.0);\n\t\t\n\t\tdouble eps=center;\n\t\terr=max(max_eps-eps,eps-min_eps);\n\t}\n\treturn err;\n}\n\n// returns: confidence interval for logarithm of ratio\n// center: center of confidence interval\n// err_goal: precision of confidence interval\ndouble ratio_confidence_interval(double p1, double p2, double d1, double d2, double corr, double center, double confidence, double err_goal){\n\tif (d1<interval_fallback_threshold || d2<interval_fallback_threshold){\n\t\t\tcout << \"Falling back to interval arithmetic...\" << endl;\n\t\t\treturn get_err_interval(p1,p2,d1,d2,center,confidence);\n\t}\n\t\n\tdouble d_old=0;\n\tdouble d=err_goal/2;\n\twhile (true) {\n\t\tdouble min=center-d;\n\t\tdouble max=center+d;\n\t\tdouble p=ratio_cdf(exp(min),exp(max),p1,p2,d1,d2,corr);\n\t\t//cout << \"Pr[ratio\u220a \" << center << \"\u00b1\" << d << \"]=\" << p << \" (exponential search)\" << endl;\n\t\tif (p>=confidence){\n\t\t\tbreak;\n\t\t}\n\t\td_old=d;\n\t\td*=2;\n\t\tif (d>10){\n\t\t\treturn INFINITY;\n\t\t}\n\t}\n\tdouble d_lower=d_old;\n\tdouble d_upper=d;\n\twhile(d_upper-d_lower>err_goal/200){\n\t\tdouble middle=(d_lower+d_upper)/2;\n\t\tdouble min=center-middle;\n\t\tdouble max=center+middle;\n\t\tdouble p=ratio_cdf(exp(min),exp(max),p1,p2,d1,d2,corr);\n\t\t//cout << \"Pr[ratio\u220a \" << center << \"\u00b1\" << middle << \"]=\" << p << \" (binary search)\" << endl;\n\t\tif (p<confidence){\n\t\t\td_lower=middle;\n\t\t}else{\n\t\t\td_upper=middle;\n\t\t}\n\t}\n\t\n\t/*double l=center-d_upper;\n\tdouble u=center+d_upper;\n\tdouble p_too_small=ratio_cdf(l,p1,p2,d1,d2,corr);\n\tdouble p_correct=ratio_cdf(l,u,p1,p2,d1,d2,corr);\n\tdouble p_too_large=1-ratio_cdf(u,p1,p2,d1,d2,corr);\n\tcout << \"Pr[ratio<\" << center << \"-\" << d_upper << \"]=\" << p_too_small << endl;\n\tcout << \"Pr[ratio\u220a \" << center << \"\u00b1\" << d_upper << \"]=\" << p_correct << endl;\n\tcout << \"Pr[ratio>\" << center << \"+\" << d_upper << \"]=\" << p_too_large << endl;\n\tcout << p_too_small + p_correct + p_too_large << endl;*/\n\t\n\treturn d_upper;\n}\n\nextern \"C\" {\n\t\n\tdouble ratio_cdf_extern(double lower, double upper, double mx, double my, double sx, double sy, double rho) {\n\t\treturn ratio_cdf(lower,upper,mx,my,sx,sy,rho);\n\t}\n\t\n\tdouble ratio_pdf_extern(double w, double mx, double my, double sx, double sy, double rho) {\n\t\treturn ratio_pdf(w,mx,my,sx,sy,rho);\n\t}\n\t\n\tdouble ratio_confidence_interval_extern(double p1, double p2, double d1, double d2, double corr, double center, double confidence, double err_goal){\n\t\t// cout << p1 << \" \" << p2 << \" \" << d1 << \" \" << d2 << \" \" << corr << \" \" << center << \" \" << confidence << \" \" << err_goal << endl;\n\t\treturn ratio_confidence_interval(p1, p2, d1, d2, corr, center, confidence, err_goal);\n\t}\n\n}\n\n\nint main() {\n\tdouble x = bivnor(1,0,0);\n\tcout << x << endl;\n\treturn 0;\n}\n\n", "meta": {"hexsha": "d86776fd4d698be562cbdd411f0b62157c9bcbdb", "size": 7871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dpfinder/searcher/statistics/ratio/ratio_cdf.cpp", "max_stars_repo_name": "barryZZJ/dp-finder", "max_stars_repo_head_hexsha": "ddf8e3589110b4b35920b437d605b45dd56291da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2018-10-19T05:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T20:34:16.000Z", "max_issues_repo_path": "dpfinder/searcher/statistics/ratio/ratio_cdf.cpp", "max_issues_repo_name": "barryZZJ/dp-finder", "max_issues_repo_head_hexsha": "ddf8e3589110b4b35920b437d605b45dd56291da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-22T22:55:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T22:55:39.000Z", "max_forks_repo_path": "dpfinder/searcher/statistics/ratio/ratio_cdf.cpp", "max_forks_repo_name": "barryZZJ/dp-finder", "max_forks_repo_head_hexsha": "ddf8e3589110b4b35920b437d605b45dd56291da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-11-13T12:37:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T11:11:52.000Z", "avg_line_length": 29.4794007491, "max_line_length": 149, "alphanum_fraction": 0.668530047, "num_tokens": 2553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5370172977148248}}
{"text": "#pragma once\n\n#include \"definitions.hpp\"\n\n#include <Eigen/Dense>\n\nnamespace activation\n{\nclass ActivationFunction\n{\npublic:\n    virtual Matrix evaluate(const MatrixRef& x) const      = 0;\n    virtual Matrix derivative(const MatrixRef& x) const    = 0;\n    virtual Matrix dblDerivative(const MatrixRef& x) const = 0;\n};\n\ntemplate <typename F, typename DF, typename DDF>\nclass DerivedActivationFunction : public ActivationFunction\n{\nprivate:\n    const F   f {};\n    const DF  df {};\n    const DDF ddf {};\n\npublic:\n    Matrix evaluate(const MatrixRef& x) const override { return x.unaryExpr(f); }\n\n    Matrix derivative(const MatrixRef& y) const override { return y.unaryExpr(df); }\n\n    Matrix dblDerivative(const MatrixRef& y) const override { return y.unaryExpr(ddf); }\n};\n\nnamespace functors\n{\nnamespace relu\n{\nstruct eval\n{\n    constexpr Real operator()(Real x) const { return x > 0 ? x : 0; }\n};\nstruct deriv\n{\n    constexpr Real operator()(Real y) const { return y > 0 ? 1 : 0; }\n};\nstruct dblDeriv\n{\n    constexpr Real operator()(Real y) const\n    {\n        (void) y;\n        return 0;\n    }\n};\n}  // namespace relu\n\nnamespace identity\n{\nstruct eval\n{\n    constexpr Real operator()(Real x) const { return x; }\n};\nstruct deriv\n{\n    constexpr Real operator()(Real y) const\n    {\n        (void) y;\n        return 1;\n    }\n};\nstruct dblDeriv\n{\n    constexpr Real operator()(Real y) const\n    {\n        (void) y;\n        return 0;\n    }\n};\n}  // namespace identity\n\nnamespace sigmoid\n{\nstruct eval\n{\n    constexpr Real operator()(Real x) const { return 1 / (1 + std::exp(-x)); }\n};\nstruct deriv\n{\n    constexpr Real operator()(Real y) const { return y * (1 - y); }\n};\nstruct dblDeriv\n{\n    constexpr Real operator()(Real y) const { return y * (1 - y) * (1 - 2 * y); }\n};\n}  // namespace sigmoid\n\nnamespace tanh\n{\nstruct eval\n{\n    constexpr Real operator()(Real x) const { return std::tanh(x); }\n};\nstruct deriv\n{\n    constexpr Real operator()(Real y) const { return 1 - y * y; }\n};\nstruct dblDeriv\n{\n    constexpr Real operator()(Real y) const\n    {\n        Real x = std::atanh(y);\n        return -2 * y / square(std::cosh(x));\n    }\n};\n}  // namespace tanh\n\nnamespace exponential\n{\nstruct eval\n{\n    constexpr Real operator()(Real x) const { return std::exp(x); }\n};\nstruct deriv\n{\n    constexpr Real operator()(Real y) const { return y; }\n};\nstruct dblDeriv\n{\n    constexpr Real operator()(Real y) const { return y; }\n};\n}  // namespace exponential\n\n}  // namespace functors\n\nusing ReluActivation     = DerivedActivationFunction<functors::relu::eval,\n                                                 functors::relu::deriv,\n                                                 functors::relu::dblDeriv>;\nusing IdentityActivation = DerivedActivationFunction<functors::identity::eval,\n                                                     functors::identity::deriv,\n                                                     functors::identity::dblDeriv>;\nusing SigmoidActivation  = DerivedActivationFunction<functors::sigmoid::eval,\n                                                    functors::sigmoid::deriv,\n                                                    functors::sigmoid::dblDeriv>;\nusing TanhActivation     = DerivedActivationFunction<functors::tanh::eval,\n                                                 functors::tanh::deriv,\n                                                 functors::tanh::dblDeriv>;\nusing ExponentialActivation\n    = DerivedActivationFunction<functors::exponential::eval,\n                                functors::exponential::deriv,\n                                functors::exponential::dblDeriv>;\n\nextern ReluActivation        relu;\nextern IdentityActivation    identity;\nextern SigmoidActivation     sigmoid;\nextern TanhActivation        tanh;\nextern ExponentialActivation exponential;\n\n}  // namespace activation\n", "meta": {"hexsha": "78592a7d47c8adbbaa0b4b85f433d8b52c6480b0", "size": 3842, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "qflow/wavefunctions/nn/activations/activation.hpp", "max_stars_repo_name": "johanere/qflow", "max_stars_repo_head_hexsha": "5453cd5c3230ad7f082adf9ec1aea63ab0a4312a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-07-24T21:46:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T18:18:24.000Z", "max_issues_repo_path": "qflow/wavefunctions/nn/activations/activation.hpp", "max_issues_repo_name": "johanere/qflow", "max_issues_repo_head_hexsha": "5453cd5c3230ad7f082adf9ec1aea63ab0a4312a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2019-02-19T10:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-18T09:42:13.000Z", "max_forks_repo_path": "qflow/wavefunctions/nn/activations/activation.hpp", "max_forks_repo_name": "bsamseth/FYS4411", "max_forks_repo_head_hexsha": "72b879e7978364498c48fc855b5df676c205f211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-24T06:44:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-12T20:34:38.000Z", "avg_line_length": 24.4713375796, "max_line_length": 88, "alphanum_fraction": 0.5916189485, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5370172976759184}}
{"text": "/*\n * position_control.cpp\n *\n * Author:mz\n *\n * Time: 2018.11.27\n *\n * \u8bf4\u660e: mavros\u4f4d\u7f6e\u63a7\u5236\u793a\u4f8b\u7a0b\u5e8f\n *      \u8f93\u5165\uff1amavros\u53d1\u5e03\u7684\u4f4d\u7f6e/\u901f\u5ea6\u4fe1\u606f\n *      \u8f93\u51fa\uff1a\u65e0\u4eba\u673a\u7684\u63a8\u529b\u548c\u59ff\u6001\u4fe1\u606f\n *      \u91c7\u7528\u4f4d\u7f6e\u73af/\u901f\u5ea6\u73af\u4e32\u7ea7PID\u63a7\u5236\uff0c\u4f4d\u7f6e\u73afP\u63a7\u5236\uff0c\u901f\u5ea6\u73afPID\u63a7\u5236\n */\n#include <fstream>\n#include <math.h>\n#include <string>\n#include <time.h>\n#include <queue>\n#include <vector>\n#include <cstdlib>\n#include <stdlib.h>\n#include <iostream>\n#include <sstream>\n#include <stdio.h>\n#include <Eigen/Eigen>\n#include <Eigen/Geometry> \n#include <Eigen/Core> \n\n\n#include <ros/ros.h>\n#include \"Parameter.h\"\n#include <PID.h>\n#include <FILTER.h>\n\n\n//topic\n#include <geometry_msgs/Point.h>\n#include <geometry_msgs/Vector3.h>\n#include <geometry_msgs/Quaternion.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/TwistStamped.h>\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\n#include <mavros_msgs/State.h>\n#include <mavros_msgs/AttitudeTarget.h>\n#include <mavros_msgs/CommandBool.h>\n#include <mavros_msgs/SetMode.h>\n#include <mavros_msgs/PositionTarget.h>\n#include <nav_msgs/Odometry.h>\n#include <std_msgs/Bool.h>\n#include <std_msgs/Float32.h>\n#include <std_msgs/Float64.h>\n#include <mavros_msgs/Thrust.h>\n#include <mavros_msgs/AttitudeTarget.h>\n#include <sensor_msgs/Imu.h>\n\n\n#include \"ros/ros.h\"\n#include \"std_msgs/Float32.h\"\n#include <chrono>\n#include \"iomanip\"\n#include <thread>\n#include <unistd.h>\n#include <mutex>\n#include \"offb_posctl/controlstate.h\"\n\nusing namespace Eigen;//\u91ca\u653eeigen\u547d\u540d\u7a7a\u95f4 \u77e9\u9635\u5e93\nusing namespace std;\n\n///>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u5168 \u5c40 \u53d8 \u91cf<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\nmavros_msgs::State current_state;           //\u65e0\u4eba\u673a\u5f53\u524d\u72b6\u6001\nnav_msgs::Odometry pose_drone_odom;       //\u8bfb\u5165\u7684\u65e0\u4eba\u673adrone\u5f53\u524d\u4f4d\u7f6e\uff0cx\uff0cy\uff0cz+\u59ff\u6001\nsensor_msgs::Imu pose_drone_Imu;       //\u8bfb\u5165\u7684\u65e0\u4eba\u673adrone\u5f53\u524d\u4f4d\u7f6e\uff0cx\uff0cy\uff0cz+\u59ff\u6001\nnav_msgs::Odometry pose_car_odom;       //\u8bfb\u5165car\u5f53\u524d\u4f4d\u7f6e\ngeometry_msgs::TwistStamped vel_drone;      //\u8bfb\u5165\u7684\u65e0\u4eba\u673a\u5f53\u524d\u901f\u5ea6 \u7ebf\u901f\u5ea6+\u89d2\u901f\u5ea6\ngeometry_msgs::Quaternion orientation_target;   //\u53d1\u7ed9\u65e0\u4eba\u673a\u7684\u59ff\u6001\u6307\u4ee4  \u56db\u5143\u6570\ngeometry_msgs::Vector3 angle_target;   //\u6b27\u62c9\u89d2\ngeometry_msgs::Vector3 vel_target;   //\u671f\u671b\u901f\u5ea6\ngeometry_msgs::Point plane_expected_position; //\u8f66\u7684\u96f6\u70b9\u548c\u98de\u673a\u7684\u96f6\u70b9\u5dee3m\uff0c\u6839\u636e\u8f66\u7684\u5f53\u524d\u4f4d\u7f6e\u8ba1\u7b97\u98de\u673a\u4f4d\u7f6e\ngeometry_msgs::PoseStamped target_attitude;  //1\nmavros_msgs::Thrust target_thrust_msg; //1\u5faa\u73af\nstd_msgs::Float64 plane_real_alt; //control\u524d\nmavros_msgs::AttitudeTarget target_atti_thrust_msg; //\u6700\u7ec8\u53d1\u5e03\u7684\u6d88\u606f \u6cb9\u95e8+\u89d2\u5ea6\nmavros_msgs::AttitudeTarget base_atti_thrust_msg; //\u6700\u7ec8\u53d1\u5e03\u7684\u6d88\u606f \u6cb9\u95e8+\u89d2\u5ea6\n//mavros_msgs::PositionTarget target_pos_msg;\nnav_msgs::Odometry  planned_postwist_msg;\nnav_msgs::Odometry planned_u_msg;\nnav_msgs::Odometry current_relativepostwist_msg;\ngeometry_msgs::Vector3 targeterror_msg;\ngeometry_msgs::Vector3 temp_angle;\ngeometry_msgs::Vector3 rpy;\noffb_posctl::controlstate controlstatearray_msg;\n\nfloat thrust_target;        //\u671f\u671b\u63a8\u529b\nfloat Yaw_Init;\nfloat Yaw_Locked = 0;           //\u9501\u5b9a\u7684\u504f\u822a\u89d2(\u4e00\u822c\u9501\u5b9a\u4e3a0)\nbool got_initial_point = false;\nPID PIDVX, PIDVY, PIDVZ;    //\u58f0\u660ePID\u7c7b\nParameter param;\nstd::ofstream logfile;\n\n///for psopt\nfloat px_ini = -3.0;\nfloat pz_ini = 0;\nfloat py_ini=0;\nfloat vx_ini = -0.1;\nfloat vz_ini = 0.0;\nfloat vy_ini=0;\nfloat phi_ini=0;\nfloat omegax_ini=0;\nfloat thrust_ini=9.8;\nfloat tau_ini=0;\nFILTER derivation_omegax(3);\nfloat t_end = 3;\ndouble thrustforceacc = 0.0;\nint pointnumber=150;// the number is almost always 20. It less, the accuracy won't be enough, if more, the time consumpiton will be too large.\nint controlfreq=50;\nint discretizedpointpersecond = (int)pointnumber/t_end;\nint controlcounter=0;\n//int controltime = 15; //\u53d6\u7684\u63a7\u5236\u5e8f\u5217\u70b9\u6570\nint controlmode = 0;//0\u4e3a\u6700\u4f18\u63a7\u5236,1\u4e3atractor\nbool adjust_flag = true;\ndouble euler_anlge_limit=0.314;\n\n\n///for pitch compensation\nfloat comp_integrate,comp_last_error;\nfloat comp_kp = 0,comp_ki = 0,comp_kd = 0;\n\n\n/// for tractor\nstd::mutex mtx;\ndouble amp=0.5;\nfloat sinrate=3;\ndouble ocpPitch=0;\ndouble ocpRoll=0;\ndouble ax=0.0,az=0.0,ay=0.0;\ndouble axp=0.0,azp=0.0,ayp=0.0;\ndouble axv=0.0,azv=0.0,ayv=0.0;\n\n///virtual car pos_twist\nfloat virtual_pos_x = 0;\nfloat virtual_vel_x = 0;\n\n///\ndouble bvp_restrict_ax, bvp_restrict_az;// bvp acc_x&z restriction\ndouble bvp_feedback_gain_x[2] = {0.5,0.3}, bvp_feedback_gain_z[2] = {0.5,0.3}; ///bvp pos&vel feedback gain\ndouble bvp_acc_x, bvp_acc_y,bvp_acc_z, bvp_ocpPitch, bvp_thrustforceacc; ///bvp feedback acc desired\n///>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u58f0 \u660e \u51fd \u6570<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n//\u6b27\u62c9\u89d2\u8f6c\u56db\u5143\u6570\ngeometry_msgs::Quaternion euler2quaternion(float roll, float pitch, float yaw);//geometry_msgs\u7684Quaternion\u7c7b\u578b\u7684\u51fd\u6570\ngeometry_msgs::Vector3 quaternion2euler(float x, float y, float z, float w);\n\nfloat get_ros_time(ros::Time time_begin);                                            //\u83b7\u53d6ros\u5f53\u524d\u65f6\u95f4\nint pix_controller(float cur_time);\nvoid vector3dLimit(Vector3d &v, double limit) ; ///limit should be positive\nVector3d vectorElementMultiply(Vector3d v1, Vector3d v2);\nvoid tractor_controller(float time);\n//int pix_controller(int cur_time);\nvoid data_log(std::ofstream &logfile, float cur_time);\nfloat pitch_compensation(float theta_dc, float theta_dn, float yk[],float uk[]);\n\n///>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u56de \u8c03 \u51fd \u6570<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\nvoid state_cb(const mavros_msgs::State::ConstPtr &msg){\n    current_state = *msg;\n\n}//\u5f53\u6709\u6d88\u606f\u5230\u8fbetopic\u65f6\u4f1a\u81ea\u52a8\u8c03\u7528\u4e00\u6b21\nbool planeupdateflag= false;\nvoid plane_pos_cb(const nav_msgs::Odometry::ConstPtr &msg){\n    pose_drone_odom = *msg;//pose_drone_odom is nav_msgs::Odometry type\n    planeupdateflag= true;\n}\nvoid plane_imu_cb(const sensor_msgs::Imu::ConstPtr &msg){\n    pose_drone_Imu = *msg;\n}\n\nvoid plane_vel_cb(const geometry_msgs::TwistStamped::ConstPtr &msg){\n    vel_drone = *msg;\n}\n\nvoid car_pos_cb(const nav_msgs::Odometry::ConstPtr &msg) {\n    pose_car_odom = *msg;\n\n    plane_expected_position.x = pose_car_odom.pose.pose.position.x; //-1 means axis difference\n    plane_expected_position.y = pose_car_odom.pose.pose.position.y; //-1 means axis difference\n    plane_expected_position.z = pose_car_odom.pose.pose.position.z + 0.5;\n}\nvoid plane_alt_cb(const std_msgs::Float64::ConstPtr &msg){\n    plane_real_alt = *msg;\n}\nbool contstaterecieveflag= false;\nvoid controlstate_cb(const offb_posctl::controlstate::ConstPtr &msg)\n{\n    controlstatearray_msg = *msg;\n    controlcounter = controlstatearray_msg.inicounter;\n    if(contstaterecieveflag == false)//\u7b2c\u4e00\u6b21\u56de\u8c03\u65f6\u521d\u59cb\u5316\uff0c\u4e4b\u540e\u8fd9\u4e2aflag\u4e00\u76f4\u662ftrue\n    {\n        contstaterecieveflag= true;\n        discretizedpointpersecond=controlstatearray_msg.discrepointpersecond;\n    }\n\n}\n\n///>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u4e3b \u51fd \u6570<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nint main(int argc, char **argv)//argc  argument count \u4f20\u53c2\u4e2a\u6570\uff0cargument value\n{\n    ros::init(argc, argv, \"position_control\");//\u521d\u59cb\u5316\u8282\u70b9\u540d\u79f0\n    ros::NodeHandle nh;\n\n\n    ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool>(\n            \"mavros/cmd/arming\"); //\u4f7f\u80fd\u89e3\u9501\u98de\u673a  \u521b\u5efaclient\u5bf9\u8c61\u5e76\u5411arming\u53d1\u51fa\u8bf7\u6c42\uff0c\u670d\u52a1\u7c7b\u578b\u4e3aCommandBool\n    ros::ServiceClient setmode_client = nh.serviceClient<mavros_msgs::SetMode>(\n            \"mavros/set_mode\"); //\u8bbe\u7f6e\u4e3a\u81ea\u52a8\u63a7\u5236\u6a21\u5f0f \u670d\u52a1\u7c7b\u578b\u4e3aSetMode\n\n    // \u3010\u8ba2\u9605\u3011\u65e0\u4eba\u673a\u5f53\u524d\u72b6\u6001/\u4f4d\u7f6e/\u901f\u5ea6\u4fe1\u606f\n    ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State>(\"mavros/state\", 1,\n                                                                 state_cb);//\u8ba2\u9605\u5668\uff0c\u8ba2\u9605\u63a5\u6536mavros/state\u8bdd\u9898\u7684mavros_msgs::State\u7c7b\u578b\u7684\u6d88\u606f\uff0c\u6709\u6d88\u606f\u5230\u8fbe\u8fd9\u4e2a\u8bdd\u9898\u65f6\u4f1a\u81ea\u52a8\u8c03\u7528state_cb\u51fd\u6570\n    ros::Subscriber plane_position_pose_sub = nh.subscribe<nav_msgs::Odometry>(\"mavros/local_position/odom\", 1,\n                                                                               plane_pos_cb);//pos+twist\n    ros::Subscriber plane_poseimu_sub = nh.subscribe<sensor_msgs::Imu>(\"/mavros/imu/data\", 1,\n                                                                       plane_imu_cb);//pos+twist\n    ros::Subscriber plane_velocity_sub = nh.subscribe<geometry_msgs::TwistStamped>(\n            \"mavros/local_position/velocity_local\", 1, plane_vel_cb); //twist\n    ros::Subscriber car_position_sub = nh.subscribe<nav_msgs::Odometry>(\"odom\", 1, car_pos_cb); //\u8f66\u7684pos+twist\n    ros::Subscriber plane_alt_sub = nh.subscribe<std_msgs::Float64>(\"mavros/global_position/rel_alt\", 1, plane_alt_cb);\n    ros::Subscriber controlstate_sub = nh.subscribe<offb_posctl::controlstate>(\"bvp_controlstate\", 1, controlstate_cb);\n    // \u3010\u53d1\u5e03\u3011\u98de\u673a\u59ff\u6001/\u62c9\u529b\u4fe1\u606f \u5750\u6807\u7cfb:NED\u7cfb\n    ros::Publisher ocplan_postwist_pub = nh.advertise<nav_msgs::Odometry>(\"ocplan_positiontwist\", 1);//bvp\u8ba1\u7b97\u7684\u671f\u671b\u4f4d\u7f6e\n    ros::Publisher ocplan_u_pub = nh.advertise<nav_msgs::Odometry>(\"ocplan_u\", 1);//bvp\u8ba1\u7b97\u7684\u671f\u671b\u63a7\u5236\u91cf(,\u6ca1\u6709\u8f6c\u5316\u7684)\n    ros::Publisher target_atti_thrust_pub = nh.advertise<mavros_msgs::AttitudeTarget>(\"mavros/setpoint_raw/attitude\",\n                                                                                      1);//\u53d1\u5e03\u7ed9mavros\u7684\u63a7\u5236\u91cf(\u7ecf\u8fc7\u6362\u7b97)\n    ros::Publisher plane_rpy_pub = nh.advertise<geometry_msgs::Vector3>(\"drone/current_rpy\", 1);//\u98de\u673a\u5f53\u524d\u7684rpy\u89d2\n    ros::Publisher current_relativepostwist_pub = nh.advertise<nav_msgs::Odometry>(\"current_relative_postwist\",\n                                                                                   1);//\u5f53\u524d\u72b6\u6001\u65b9\u7a0b\u4e2d\u7684\u72b6\u6001\u91cf,\u5373\u76f8\u5bf9\u91cf\n    ros::Publisher targeterror_pub = nh.advertise<geometry_msgs::Vector3>(\"targeterror\", 1);//\u76ee\u6807\u8bef\u5dee\n    // \u9891\u7387 [30Hz]\n    ros::Rate rate(controlfreq);   //50hz\u7684\u9891\u7387\u53d1\u9001/\u63a5\u6536topic  ros\u4e0epixhawk\u4e4b\u95f4,50Hz control frequency\n\n    // log\u8f93\u51fa\u6587\u4ef6\u521d\u59cb\u5316\n    logfile.open(\"/home/sensenliu/catkin_ws/src/gazebo_ros_learning/offb_posctl/log/pitch_log_hover1.csv\", std::ios::out);\n    if (!logfile.is_open()) {\n        ROS_ERROR(\"log to file error!\");\n//        return 0;\n    }\n\n    // \u8bfb\u53d6PID\u53c2\u6570\n    std::string paraadr(\"/home/sensenliu/catkin_ws/src/gazebo_ros_learning/offb_posctl/src/param\");\n    if (param.readParam(paraadr.c_str()) == 0) {\n        std::cout << \"read config file error!\" << std::endl;\n//        return 0;\n    }\n\n\n    /// \u8bbe\u7f6e\u901f\u5ea6\u73afPID\u53c2\u6570 \u6bd4\u4f8b\u53c2\u6570 \u79ef\u5206\u53c2\u6570 \u5fae\u5206\u53c2\u6570\n    PIDVX.setPID(param.vx_p, param.vx_i, param.vx_d);\n    PIDVY.setPID(param.vy_p, param.vy_i, param.vy_d);\n    PIDVZ.setPID(param.vz_p, param.vz_i, param.vz_d);\n    // \u8bbe\u7f6e\u901f\u5ea6\u73af\u79ef\u5206\u4e0a\u9650 \u63a7\u5236\u91cf\u6700\u5927\u503c \u8bef\u5dee\u6b7b\u533a\n    PIDVX.set_sat(6, 10, 0);\n    PIDVY.set_sat(2, 3, 0);\n    PIDVZ.set_sat(2, 5, 0);\n\n    /// \u7b49\u5f85\u548c\u98de\u63a7\u7684\u8fde\u63a5\n    while (ros::ok() && current_state.connected == 0) {\n\n        ros::spinOnce(); //\u8c03\u7528\u56de\u8c03\u51fd\u6570\n        ros::Duration(1).sleep();\n        ROS_INFO(\"Not Connected\");\n    }\n    ROS_INFO(\"Connected!!\");\n\n    target_atti_thrust_msg.orientation.x = 0;\n    target_atti_thrust_msg.orientation.y = 0;\n    target_atti_thrust_msg.orientation.z = 0;\n    target_atti_thrust_msg.orientation.w = -1;\n    target_atti_thrust_msg.thrust = 0.65; //65%\u7684\u6cb9\u95e8 50%\u4e0e\u91cd\u529b\u5e73\u8861\u5373\u60ac\u505c\n\n    /// get car current pose to set plane pose\n    float x = pose_car_odom.pose.pose.orientation.x;\n    float y = pose_car_odom.pose.pose.orientation.y;\n    float z = pose_car_odom.pose.pose.orientation.z;\n    float w = pose_car_odom.pose.pose.orientation.w;\n    Yaw_Init = quaternion2euler(x, y, z, w).z;\n\n    ///set initial hover position and pose\n    target_atti_thrust_msg.orientation.x = x;\n    target_atti_thrust_msg.orientation.y = y;\n    target_atti_thrust_msg.orientation.z = z;\n    target_atti_thrust_msg.orientation.w = w;\n    ROS_INFO(\"got initial point \");\n\n    for (int i = 10; ros::ok() && i >0; --i)// let drone take off slightly at begining, but this step seems useless because the drono has not been armed\n    {\n        target_atti_thrust_pub.publish(target_atti_thrust_msg);\n        ros::spinOnce();//\u8ba9\u56de\u8c03\u51fd\u6570\u6709\u673a\u4f1a\u88ab\u6267\u884c\n        rate.sleep();\n    }\n    ROS_INFO(\"OUT OF LOOP WAIT\");\n\n\n    mavros_msgs::CommandBool arm_cmd; //\u89e3\u9501\n    mavros_msgs::SetMode offb_set_mode;\n    offb_set_mode.request.custom_mode = \"OFFBOARD\";\n    arm_cmd.request.value = true;\n\n    ros::Time last_request = ros::Time::now();\n\n    ///\u89e3\u9501\u98de\u673a\n    while (ros::ok()) {\n        if (current_state.mode != \"OFFBOARD\" &&\n            (ros::Time::now() - last_request > ros::Duration(5.0))) {\n            if (setmode_client.call(offb_set_mode) && offb_set_mode.response.mode_sent) {\n                ROS_INFO(\"Offboard enabled\");\n            }\n            last_request = ros::Time::now();\n        } else {\n            if (!current_state.armed &&\n                (ros::Time::now() - last_request > ros::Duration(5.0))) {\n                if (arming_client.call(arm_cmd) &&\n                    arm_cmd.response.success) {\n                    ROS_INFO(\"Vehicle armed\");\n                }\n                last_request = ros::Time::now();\n            }\n        }\n        target_atti_thrust_pub.publish(target_atti_thrust_msg);\n        if (plane_real_alt.data > 0.7) {\n            ROS_INFO(\"plane takeoff !\");\n            break;\n        }\n        ros::spinOnce();\n        rate.sleep();\n    }\n\n\n    /// reach initial hover position and pose by position control\n    /*float error_position_sum = 0;\n    float error_pose_sum = 5;\n    float yaw_current;\n    ros::Time begin_time_01 = ros::Time::now();\n    int count = 0;\n    float thrust_target_sum = 0;\n    vector<float> orientation_x;\n    vector<float> orientation_y;\n    vector<float> orientation_z;\n    vector<float> orientation_w;\n    got_initial_point = true;\n    base_atti_thrust_msg.thrust=0.57;\n\n    while (ros::ok() && count < 500)//\u6ca1\u6709\u7ed9\u5c0f\u8f66\u901f\u5ea6\u65f6\u59cb\u7ec8\u5728\u8fd9\u4e2a\u5faa\u73af\u91cc\n    {\n\n        ros::spinOnce();\n        plane_expected_position.x = 0; //-1 means axis difference\n        plane_expected_position.y = 0; //-1 means axis difference\n        plane_expected_position.z = 0.5;\n\n        float cur_time_01 = get_ros_time(begin_time_01);  // \u76f8\u5bf9\u65f6\u95f4\n        pix_controller(cur_time_01);\n        target_atti_thrust_msg.header.stamp.sec = pose_car_odom.header.stamp.sec;\n        target_atti_thrust_msg.header.stamp.nsec = pose_car_odom.header.stamp.nsec;\n        target_atti_thrust_msg.orientation = orientation_target;\n        target_atti_thrust_msg.thrust = thrust_target;\n\n        temp_angle = quaternion2euler(pose_drone_odom.pose.pose.orientation.x, pose_drone_odom.pose.pose.orientation.y,\n                                      pose_drone_odom.pose.pose.orientation.z, \\\n                                      pose_drone_odom.pose.pose.orientation.w);//\u6b27\u62c9\u89d2\n        rpy.y = temp_angle.y;\n        rpy.x = temp_angle.x;\n        rpy.z = temp_angle.z;\n        plane_rpy_pub.publish(rpy);\n\n\n        target_atti_thrust_pub.publish(target_atti_thrust_msg);\n        rate.sleep();//\u4f11\u606f\n\n        count += 1;\n        if (count >= 500)//count\u5230\u8fbe500\u4ee5\u540e,\u4e0d\u4f1a\u518d\u589e\u52a0\n        {\n            cout << \"You can run Waffle pi!\" << endl;\n        }\n\n    }\n\n    ROS_INFO(\"reached initial point and pose \");\n    */\n    // \u8bb0\u5f55\u542f\u63a7\u65f6\u95f4\n    ros::Time begin_time_02 = ros::Time::now();\n    int quad_state=0;//0 climbhover, 1 AggressiveFly, 2 AdhesionPhase, 3 keep current state hover, 4 AdhesionSuccess\n    int tempcounter=0;\n    float ascentvel=15;\n    float tempCurrentPx=0,tempCurrentPy=0,tempCurrentPz=0;\n    int lefnodeindex = 0;\n    int rightnodeindex = 0;\n\n///>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u4e3b  \u5faa  \u73af<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n    while (ros::ok()) {\n\n        ros::spinOnce();//\u5237\u65b0callback\u7684\u6d88\u606f\n\n        float cur_time = get_ros_time(begin_time_02);  // \u5f53\u524d\u65f6\u95f4\n        switch (quad_state) {\n            case 0:\n                plane_expected_position.z=plane_expected_position.z+ascentvel*cur_time;\n                plane_expected_position.z=min(plane_expected_position.z,0.5);\n                plane_expected_position.x=0;\n                plane_expected_position.y=0;\n                pix_controller(cur_time);\n\n                if(plane_expected_position.z>=0.5)\n                {\n                    tempcounter++;\n                    if(tempcounter>=150)\n                    {\n                        quad_state=1;\n                        controlcounter=1;\n                        tempcounter=0;\n                    }\n                }\n                break;\n            case 1:\n                if(contstaterecieveflag)  //\u8ba2\u9605\u5230bvp\u8ba1\u7b97\u7684\u63a7\u5236\u91cf\u5219flag\u4e3atrue,\u7528\u4e8e\u8d77\u59cb\u65f6\u523b,\u8fd8\u6ca1\u7b97\u51fabvp\u65f6\n                {\n                    lefnodeindex = controlcounter;\n                    if (lefnodeindex+1 < controlstatearray_msg.arraylength)\n                    {\n                        ///compensation\n                        ocpRoll = controlstatearray_msg.phiarray[lefnodeindex];\n                        thrustforceacc = controlstatearray_msg.thrustarray[lefnodeindex];\n\n                        plane_expected_position.z=controlstatearray_msg.stateZarray[lefnodeindex];\n                        plane_expected_position.x=controlstatearray_msg.stateXarray[lefnodeindex];\n                        plane_expected_position.y=controlstatearray_msg.stateYarray[lefnodeindex];\n                        pix_controller(cur_time);\n\n                        if (lefnodeindex <= 6)\n                        {\n                            orientation_target = euler2quaternion(ocpRoll, angle_target.y, angle_target.z);\n                            thrust_target = (float) (param.hoverthrust) * thrustforceacc / 9.8;\n                        }\n                    }\n                    controlcounter++;\n                    if(controlcounter>=controlstatearray_msg.arraylength ||controlstatearray_msg.arraylength<=10)\n                    {\n                        quad_state=2;\n                    }\n                } else{\n                    pix_controller(cur_time);\n                }\n                break;\n            case 2:\n                tempCurrentPx=pose_drone_odom.pose.pose.position.x;\n                tempCurrentPy=pose_drone_odom.pose.pose.position.y;\n                tempCurrentPz=pose_drone_odom.pose.pose.position.z;;\n                tempcounter++;\n                if(tempCurrentPz<controlstatearray_msg.stateZarray[controlstatearray_msg.arraylength-1]-0.15)\n                {\n                    quad_state=3;\n                    tempcounter=0;\n                }\n                if(tempcounter>=100&&tempCurrentPz>=controlstatearray_msg.stateZarray[controlstatearray_msg.arraylength-1]-0.15)\n                {\n                    quad_state=4;\n                    tempcounter=0;\n                }\n                orientation_target = euler2quaternion(controlstatearray_msg.phiarray[controlstatearray_msg.arraylength-1], controlstatearray_msg.thetaarray[controlstatearray_msg.arraylength-1], angle_target.z);\n                thrust_target  = param.hoverthrust*cos(controlstatearray_msg.phiarray[controlstatearray_msg.arraylength-1])*cos(controlstatearray_msg.thetaarray[controlstatearray_msg.arraylength-1]);   //\u76ee\u6807\u63a8\u529b\u503c to alleviate the gravity's component along the drone's z axis\n//                thrust_target  = 0.2;   //\u76ee\u6807\u63a8\u529b\u503c,\u53ea\u662f\u7528\u6765\u4fdd\u8bc1\u63d0\u4f9b\u626d\u77e9\uff0cthe drone is easy to fall freely and crash\n                ROS_INFO_STREAM(\"Duringsuck_thrust_target: \"<< thrust_target<<\" roll:\"<<controlstatearray_msg.phiarray[controlstatearray_msg.arraylength-1]<<\" pitch:\"<<controlstatearray_msg.thetaarray[controlstatearray_msg.arraylength-1]<<\" yaw:\"<<angle_target.z);\n                break;\n                break;\n            case 3:\n                plane_expected_position.x=tempCurrentPx;\n                plane_expected_position.y=tempCurrentPy;\n                plane_expected_position.z=tempCurrentPz;\n                pix_controller(cur_time);\n                break;\n            case 4:\n                orientation_target = euler2quaternion(controlstatearray_msg.phiarray[controlstatearray_msg.arraylength-1], controlstatearray_msg.thetaarray[controlstatearray_msg.arraylength-1], angle_target.z);\n                thrust_target  = 0;   //\u76ee\u6807\u63a8\u529b\u503c\n                ROS_INFO_STREAM(\"Sucksuccess_thrust_target: \"<< thrust_target<<\" roll:\"<<angle_target.x<<\" pitch:\"<<angle_target.y<<\" yaw:\"<<angle_target.z);\n                break;\n            default:\n                break;\n        }\n//        if(quad_state!=4&&quad_state!=2)\n//        {\n//            pix_controller(cur_time);\n//        }\n        cout<<\"refpos x y z: \"<<plane_expected_position.x<<\"   y:\"<<plane_expected_position.y<<\"  z:\"<<plane_expected_position.z<<endl;\n\n        if (planeupdateflag && pose_drone_odom.pose.pose.position.z>=0.2)   //\u8ba2\u9605\u5230\u98de\u673a\u4f4d\u7f6e\u5219flag\u4e3atrue\uff0c\u53d1\u5e03\u5b8c\u76f8\u5bf9\u4f4d\u7f6e\u7684\u6d88\u606f\u540eflag\u7f6efalse\n        {\n            omegax_ini=min(max(pose_drone_odom.twist.twist.angular.x,-10.0),10.0);\n\n            tau_ini=derivation_omegax.derivation(cur_time,pose_drone_odom.twist.twist.angular.x);\n            tau_ini=min(max((double)tau_ini,-10.0),10.0);\n\n            phi_ini=temp_angle.x;\n\n            px_ini = pose_drone_odom.pose.pose.position.x;\n            pz_ini = max(pose_drone_odom.pose.pose.position.z,0.2);\n            py_ini = pose_drone_odom.pose.pose.position.y;\n            vx_ini = vel_drone.twist.linear.x;\n            vz_ini = vel_drone.twist.linear.z;\n            vy_ini = vel_drone.twist.linear.y;\n\n            thrust_ini=thrust_target/param.hoverthrust*9.8;\n            thrust_ini=min((double)thrust_ini,19.6);\n\n\n            std::cout << \"px_ini:  \" << px_ini << \"pz_ini:  \" << pz_ini << \"vx_ini:  \" << vx_ini << \"vz_ini:  \"\n                      << vz_ini << std::endl;//\u8f93\u51fa,\u653e\u5230py\u6587\u4ef6\u4e2d\u6c42\u89e3\n            cout<<\"va_ini:\"<<vel_drone.twist.linear.x<<endl;\n            current_relativepostwist_msg.pose.pose.position.x = px_ini;\n            current_relativepostwist_msg.pose.pose.position.z = pz_ini;\n            current_relativepostwist_msg.pose.pose.position.y = py_ini;\n            current_relativepostwist_msg.twist.twist.linear.x = vx_ini;\n            current_relativepostwist_msg.twist.twist.linear.y = vy_ini;\n            current_relativepostwist_msg.twist.twist.linear.z = vz_ini;\n            current_relativepostwist_msg.pose.pose.orientation.x=phi_ini;\n            current_relativepostwist_msg.pose.pose.orientation.y=omegax_ini;\n            current_relativepostwist_msg.pose.pose.orientation.z=thrust_ini;\n            current_relativepostwist_msg.pose.pose.orientation.w=tau_ini;\n            current_relativepostwist_msg.header.stamp = pose_drone_odom.header.stamp;\n            current_relativepostwist_pub.publish(current_relativepostwist_msg);\n            planeupdateflag = false;\n        }\n\n            ///publish plane current rpy\n            temp_angle = quaternion2euler(pose_drone_odom.pose.pose.orientation.x,\n                                          pose_drone_odom.pose.pose.orientation.y,\n                                          pose_drone_odom.pose.pose.orientation.z,\n                                          pose_drone_odom.pose.pose.orientation.w);//\u6b27\u62c9\u89d2\n            rpy.y = temp_angle.y;\n            rpy.x = temp_angle.x;\n            rpy.z = temp_angle.z;\n            plane_rpy_pub.publish(rpy);\n\n\n            ///publish thrust & orientation\n            std::cout << \"thrust_target: \" << thrust_target << std::endl;\n            target_atti_thrust_msg.header.stamp = ros::Time::now();\n            target_atti_thrust_msg.orientation = orientation_target;\n            target_atti_thrust_msg.thrust = thrust_target;\n            target_atti_thrust_pub.publish(target_atti_thrust_msg);\n\n            ///publish planned pos&twist in x&z\n            planned_postwist_msg.header.stamp = ros::Time::now();\n            ocplan_postwist_pub.publish(planned_postwist_msg);\n\n            ///publish planned thrust & pitch\n            ocplan_u_pub.publish(planned_u_msg);\n\n            ///publish targeterror_msg\n            targeterror_msg.x = px_ini + 3;\n            targeterror_msg.z = pz_ini + px_ini * rpy.y;\n            targeterror_msg.y = py_ini;//pub time consumption\n            targeterror_pub.publish(targeterror_msg);\n            rate.sleep();\n\n        }\n        logfile.close();\n        return 0;\n    }\n\n/**\n * \u83b7\u53d6\u5f53\u524d\u65f6\u95f4 \u5355\u4f4d\uff1a\u79d2\n */\nfloat get_ros_time(ros::Time time_begin)\n{\n    ros::Time time_now = ros::Time::now();\n    float currTimeSec = time_now.sec-time_begin.sec;\n    float currTimenSec = time_now.nsec / 1e9 - time_begin.nsec / 1e9;\n    return (currTimeSec + currTimenSec);\n}\n\n///>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\u51fd \u6570 \u5b9a \u4e49<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nfloat pitch_compensation(float theta_dc, float theta_dn, float yk[],float uk[])\n{\n    float y_next,pitch_revise,current_error;\n\n    y_next = 1.461 * yk[0] - 0.5345 * yk[1] + 0.01827 * uk[3] +0.03653 * uk[4] + 0.01827 * uk[5]; // the predicted pitch in the next moment\n    current_error = theta_dn - y_next;//current error\n    comp_integrate += current_error;//error sum\n\n    pitch_revise = theta_dc + comp_kp*current_error + comp_ki*comp_integrate + comp_kd*(current_error - comp_last_error)*controlfreq;\n    comp_last_error = current_error;\n\n    return (pitch_revise);\n}\n\nvoid vector3dLimit(Vector3d &v, double limit)  ///limit should be positive\n{\n    if(limit > 0){\n        for(int i=0; i<3; i++){\n            v(i) = fabs(v(i)) > limit ? (v(i) > 0 ? limit : -limit) : v(i);\n        }\n    }\n}\n\nVector3d vectorElementMultiply(Vector3d v1, Vector3d v2)\n{\n    Vector3d result;\n    result << v1(0)*v2(0), v1(1)*v2(1), v1(2)*v2(2);\n    return result;\n}\n\nvoid tractor_controller(float time)\n{\n    static Vector3d z_w_norm(0, 0, 1.0);\n    Vector3d p_error;\n    Vector3d v_error;\n    Vector3d planned_a;\n    switch (controlmode)\n    {\n        case 0 :{\n            p_error << (planned_postwist_msg.pose.pose.position.x - px_ini), (pose_car_odom.pose.pose.position.y-py_ini), (planned_postwist_msg.pose.pose.position.z-pz_ini);\n            v_error << (planned_postwist_msg.twist.twist.linear.x - vx_ini), (pose_car_odom.twist.twist.linear.y-vy_ini), (planned_postwist_msg.twist.twist.linear.z-vz_ini);\n            planned_a << sin(ocpPitch)*thrustforceacc, 0, thrustforceacc-9.8;\n            break;\n        }\n        case 1 :{\n            p_error << (planned_postwist_msg.pose.pose.position.x - px_ini), (pose_car_odom.pose.pose.position.y-py_ini), (planned_postwist_msg.pose.pose.position.z-pz_ini);\n            v_error << (planned_postwist_msg.twist.twist.linear.x - vx_ini), (pose_car_odom.twist.twist.linear.y-vy_ini), (planned_postwist_msg.twist.twist.linear.z-vz_ini);\n            planned_a << -amp*sinrate*sinrate*sin(sinrate*time), 0, 0;\n            break;\n        }\n    }\n\n    static Vector3d p_error_last;\n    static Vector3d v_error_last;\n    static Vector3d p_error_accumulate;\n    static Vector3d v_error_accumulate;\n    static bool if_init = true;\n    static Vector3d position_error_p(param.txp_p,param.typ_p,param.tzp_p);\n    static Vector3d position_error_d(param.txp_d,param.typ_d,param.tzp_d);\n    static Vector3d position_error_i(param.txp_i,param.typ_i,param.tzp_i);\n    static Vector3d velocity_error_p(param.txv_p,param.tyv_p,param.tzv_p);\n    static Vector3d velocity_error_d(param.txv_d,param.tyv_d,param.tzv_d);\n    static Vector3d velocity_error_i(param.txv_i,param.tyv_i,param.tzv_i);\n\n    if(if_init){\n        if_init = false;\n        p_error_last = p_error;\n        v_error_last = v_error;\n        p_error_accumulate = p_error;\n        v_error_accumulate = v_error;\n        return;\n    }\n\n    /**Core code**/\n    Vector3d delt_p_error = p_error - p_error_last;\n    Vector3d delt_v_error = v_error - v_error_last;\n\n    p_error_accumulate += p_error;\n    v_error_accumulate += v_error;\n    vector3dLimit(p_error_accumulate, 0.6);\n    vector3dLimit(v_error_accumulate, 0.5);\n\n    Vector3d a_fb =   /// PID\n            vectorElementMultiply(p_error, position_error_p) + vectorElementMultiply(v_error, velocity_error_p) +\n            vectorElementMultiply(delt_p_error, position_error_d) + vectorElementMultiply(delt_v_error, velocity_error_d) +\n            vectorElementMultiply(p_error_accumulate, position_error_i) + vectorElementMultiply(v_error_accumulate, velocity_error_i);\n\n    ax=a_fb(0);\n    az=a_fb(2);\n    ay=a_fb(1);\n    axp=(vectorElementMultiply(p_error, position_error_p)+vectorElementMultiply(delt_p_error, position_error_d)+vectorElementMultiply(p_error_accumulate, position_error_i))(0);\n    azp=(vectorElementMultiply(p_error, position_error_p)+vectorElementMultiply(delt_p_error, position_error_d)+vectorElementMultiply(p_error_accumulate, position_error_i))(2);\n    ayp=(vectorElementMultiply(p_error, position_error_p)+vectorElementMultiply(delt_p_error, position_error_d)+vectorElementMultiply(p_error_accumulate, position_error_i))(1);\n    axv=(vectorElementMultiply(v_error, velocity_error_p)+vectorElementMultiply(delt_v_error, velocity_error_d)+ vectorElementMultiply(v_error_accumulate, velocity_error_i))(0);\n    azv=(vectorElementMultiply(v_error, velocity_error_p)+vectorElementMultiply(delt_v_error, velocity_error_d)+ vectorElementMultiply(v_error_accumulate, velocity_error_i))(2);\n    ayv=(vectorElementMultiply(v_error, velocity_error_p)+vectorElementMultiply(delt_v_error, velocity_error_d)+ vectorElementMultiply(v_error_accumulate, velocity_error_i))(1);\n\n    p_error_last = p_error;\n    v_error_last = v_error;\n\n\n    Vector3d a_des = a_fb + planned_a + 9.8 * z_w_norm;\n    Vector3d att_des_norm = a_des / a_des.norm();\n    ///quaternion way to determine attitude\n//    Quaterniond att_des_q = Quaterniond::FromTwoVectors(z_w_norm, att_des_norm);\n//    //add yaw\n//    Quaterniond yaw_quat(cos(0/2.0), att_des_norm(0)*sin(0/2.0),\n//                         att_des_norm(1)*sin(0/2.0),att_des_norm(2)*sin(0/2.0));\n//    att_des_q = yaw_quat * att_des_q;\n//\n//    //Calculate thrust\n//    orientation_target.x = att_des_q.x();\n//    orientation_target.y = att_des_q.y();\n//    orientation_target.z = att_des_q.z();\n//    orientation_target.w = att_des_q.w();\n    ///quaternion way to determine attitude\n\n    angle_target.x = asin(-a_des(1)/a_des.norm());\n    angle_target.y = atan(a_des(0)/a_des(2));\n    angle_target.z = Yaw_Init;\n    orientation_target = euler2quaternion(angle_target.x, angle_target.y, angle_target.z);\n\n//    thrust_target  = (float)a_des.norm() /9.8*(base_atti_thrust_msg.thrust);   //\u76ee\u6807\u63a8\u529b\u503c\n\n    temp_angle = quaternion2euler(pose_drone_odom.pose.pose.orientation.x, pose_drone_odom.pose.pose.orientation.y,\n                                  pose_drone_odom.pose.pose.orientation.z, \\\n        pose_drone_odom.pose.pose.orientation.w);\n    thrust_target  = (float)(a_des(0)*sin(temp_angle.y)*cos(temp_angle.x)-a_des(1)*sin(temp_angle.x)+a_des(2)*cos(temp_angle.y)*cos(temp_angle.x)) /9.8*(base_atti_thrust_msg.thrust);   //\u76ee\u6807\u63a8\u529b\u503c\n}\n\nint pix_controller(float cur_time)\n{\n//\u4f4d \u7f6e \u73af\n    //\u8ba1\u7b97\u8bef\u5dee\n    float error_x = plane_expected_position.x - pose_drone_odom.pose.pose.position.x;\n    float error_y = plane_expected_position.y - pose_drone_odom.pose.pose.position.y;\n    float error_z = plane_expected_position.z - plane_real_alt.data;\n//    std::cout << \"error: x\uff1a\" << error_x << \"\\ty\uff1a\" << error_y << \"\\tz\uff1a\" << error_z << std::endl;\n    //\u8ba1\u7b97\u6307\u5b9a\u901f\u5ea6\u8bef\u5dee\n    float vel_xd = param.x_p * error_x;\n    float vel_yd = param.y_p * error_y;\n    float vel_zd = param.z_p * error_z;\n    vel_target.x = vel_xd;\n    vel_target.y = vel_yd;\n    vel_target.z = vel_zd;\n\n//\u901f \u5ea6 \u73af\n    //\u79ef\u5206\u6807\u5fd7\u4f4d.\u672a\u8fdb\u5165OFFBOARD\u65f6,\u4e0d\u7d2f\u79ef\u79ef\u5206\u9879;\u8fdb\u5165OFFBOARD\u65f6,\u5f00\u59cb\u79ef\u5206.\n    PIDVX.start_intergrate_flag = true;\n    PIDVY.start_intergrate_flag = true;\n    PIDVZ.start_intergrate_flag = true;\n    if(got_initial_point == false){\n        PIDVX.start_intergrate_flag = false;\n        PIDVY.start_intergrate_flag = false;\n        PIDVZ.start_intergrate_flag = false;\n    }\n    //\u8ba1\u7b97\u8bef\u5dee\n    float error_vx = vel_xd - vel_drone.twist.linear.x;\n    float error_vy = vel_yd - vel_drone.twist.linear.y;\n    float error_vz = vel_zd - vel_drone.twist.linear.z;\n    //\u4f20\u9012\u8bef\u5dee\n    PIDVX.add_error(error_vx, cur_time); //\u628aerror\u653e\u5230list\u4e2d\n    PIDVY.add_error(error_vy, cur_time);\n    PIDVZ.add_error(error_vz, cur_time);\n    //\u8ba1\u7b97\u8f93\u51fa\n    PIDVX.pid_output();\n    PIDVY.pid_output();\n    PIDVZ.pid_output();\n\n//    Matrix2f A_yaw;\n//    A_yaw << sin(Yaw_Locked), cos(Yaw_Locked),\n//            -cos(Yaw_Locked), sin(Yaw_Locked);\n//    Vector2f mat_temp(PIDVX.Output,PIDVY.Output);       //\u8d4b\u503c\u5230\u671f\u671b\u63a8\u529b\u548c\u59ff\u6001 x\u662f\u524d\u540e\uff0cy\u662f\u5de6\u53f3\n//    Vector2f euler_temp= 1/9.8 * A_yaw.inverse() * mat_temp;\n//    angle_target.x = euler_temp[0];\n//    angle_target.y = euler_temp[1];\n//    std::cout << \" PIDVX.pid_output(): \" << PIDVX.Output << \"\\tangle_target.y: \" << angle_target.y << std::endl;\n////    angle_target.z = Yaw_Locked + Yaw_Init;\n//    angle_target.z = Yaw_Init;\n\n    angle_target.x = asin(-PIDVY.Output/sqrt(pow(PIDVX.Output,2)+pow(PIDVY.Output,2)+pow(PIDVZ.Output+9.8,2)));\n    angle_target.y = atan(PIDVX.Output/(PIDVZ.Output+9.8));\n    angle_target.z = Yaw_Init;\n\n    orientation_target = euler2quaternion(angle_target.x, angle_target.y, angle_target.z);\n//    thrust_target = (float)(0.05 * (9.8 + PIDVZ.Output));   //\u76ee\u6807\u63a8\u529b\u503c\n    thrust_target  = (float)sqrt(pow(PIDVX.Output,2)+pow(PIDVY.Output,2)+pow(PIDVZ.Output+9.8,2))/9.8*(param.hoverthrust);   //\u76ee\u6807\u63a8\u529b\u503c\n\n//    std::cout << \"PIDVZ.OUTPUT:  \" << PIDVZ.Output << std::endl;\n//    std::cout << \"thrust_target:  \" << thrust_target << std::endl;\n\n    return 0;\n}\n/**\n * \u5c06\u6b27\u62c9\u89d2\u8f6c\u5316\u4e3a\u56db\u5143\u6570\n * @param roll\n * @param pitch\n * @param yaw\n * @return \u8fd4\u56de\u56db\u5143\u6570\n */\ngeometry_msgs::Quaternion euler2quaternion(float roll, float pitch, float yaw)\n{\n    geometry_msgs::Quaternion temp;\n    temp.w = cos(roll/2)*cos(pitch/2)*cos(yaw/2) + sin(roll/2)*sin(pitch/2)*sin(yaw/2);\n    temp.x = sin(roll/2)*cos(pitch/2)*cos(yaw/2) - cos(roll/2)*sin(pitch/2)*sin(yaw/2);\n    temp.y = cos(roll/2)*sin(pitch/2)*cos(yaw/2) + sin(roll/2)*cos(pitch/2)*sin(yaw/2);\n    temp.z = cos(roll/2)*cos(pitch/2)*sin(yaw/2) - sin(roll/2)*sin(pitch/2)*cos(yaw/2);\n    return temp;\n}\n\n/**\n * \u5c06\u56db\u5143\u6570\u8f6c\u5316\u4e3a\u6b27\u62c9\u89d2\u5f62\u5f0f\n * @param x\n * @param y\n * @param z\n * @param w\n * @return \u8fd4\u56deVector3\u7684\u6b27\u62c9\u89d2\n */\ngeometry_msgs::Vector3 quaternion2euler(float x, float y, float z, float w)\n{\n    geometry_msgs::Vector3 temp;\n    temp.x = atan2(2.0 * (w * x + y * z), 1.0 - 2.0 * (x * x + y * y));\n    temp.y = asin(2.0 * (w * y - z * x));\n    temp.z = atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z));\n    return temp;\n}\n\n/**\n * \u5c06\u8fdb\u5165offboard\u540e\u7684\u4f4d\u7f6e&\u901f\u5ea6&\u59ff\u6001\u4fe1\u606f\u8bb0\u5f55\u8fdb\u6587\u4ef6\n * @param cur_time\n */\n\nvoid data_log(std::ofstream &logfile, float cur_time)\n{\n    logfile<<cur_time<<\",\"<<rpy.y<<std::endl;\n\n}", "meta": {"hexsha": "247c4a81ebe3b30a899cf4930f5086b578722164", "size": 33552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "offb_posctl/src/offb_posctl.cpp", "max_stars_repo_name": "SensenLiu/aggrecup", "max_stars_repo_head_hexsha": "0c381ee259b388684205c1fa5fc41265a7e849b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "offb_posctl/src/offb_posctl.cpp", "max_issues_repo_name": "SensenLiu/aggrecup", "max_issues_repo_head_hexsha": "0c381ee259b388684205c1fa5fc41265a7e849b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "offb_posctl/src/offb_posctl.cpp", "max_forks_repo_name": "SensenLiu/aggrecup", "max_forks_repo_head_hexsha": "0c381ee259b388684205c1fa5fc41265a7e849b3", "max_forks_repo_licenses": ["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.0171149144, "max_line_length": 271, "alphanum_fraction": 0.6478600381, "num_tokens": 9482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5370172920960753}}
{"text": "// Copyright (C) 2012  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n\r\n#include <sstream>\r\n#include <string>\r\n#include <cstdlib>\r\n#include <ctime>\r\n#include <cmath>\r\n#include <dlib/svm.h>\r\n\r\n#include \"tester.h\"\r\n\r\nnamespace  \r\n{\r\n\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n\r\n    logger dlog(\"test.rls\");\r\n\r\n\r\n    void test_rls()\r\n    {\r\n        dlib::rand rnd;\r\n\r\n        running_stats<double> rs1, rs2, rs3, rs4, rs5;\r\n\r\n        for (int k = 0; k < 2; ++k)\r\n        {\r\n            for (long num_vars = 1; num_vars < 4; ++num_vars)\r\n            {\r\n                print_spinner();\r\n                for (long size = 1; size < 300; ++size)\r\n                {\r\n                    {\r\n                        matrix<double> X = randm(size,num_vars,rnd);\r\n                        matrix<double,0,1> Y = randm(size,1,rnd);\r\n\r\n\r\n                        const double C = 1000;\r\n                        const double forget_factor = 1.0;\r\n                        rls r(forget_factor, C);\r\n                        for (long i = 0; i < Y.size(); ++i)\r\n                        {\r\n                            r.train(trans(rowm(X,i)), Y(i));\r\n                        }\r\n\r\n\r\n                        matrix<double> w = pinv(1.0/C*identity_matrix<double>(X.nc()) + trans(X)*X)*trans(X)*Y;\r\n\r\n                        rs1.add(length(r.get_w() - w));\r\n                    }\r\n\r\n                    {\r\n                        matrix<double> X = randm(size,num_vars,rnd);\r\n                        matrix<double,0,1> Y = randm(size,1,rnd);\r\n\r\n                        matrix<double,0,1> G(size,1);\r\n\r\n                        const double C = 10000;\r\n                        const double forget_factor = 0.8;\r\n                        rls r(forget_factor, C);\r\n                        for (long i = 0; i < Y.size(); ++i)\r\n                        {\r\n                            r.train(trans(rowm(X,i)), Y(i));\r\n\r\n                            G(i) = std::pow(forget_factor, i/2.0);\r\n                        }\r\n\r\n                        G = flipud(G);\r\n\r\n                        X = diagm(G)*X;\r\n                        Y = diagm(G)*Y;\r\n\r\n                        matrix<double> w = pinv(1.0/C*identity_matrix<double>(X.nc()) + trans(X)*X)*trans(X)*Y;\r\n\r\n                        rs5.add(length(r.get_w() - w));\r\n                    }\r\n\r\n                    {\r\n                        matrix<double> X = randm(size,num_vars,rnd);\r\n                        matrix<double> Y = colm(X,0)*10;\r\n\r\n\r\n                        const double C = 1000000;\r\n                        const double forget_factor = 1.0;\r\n                        rls r(forget_factor, C);\r\n                        for (long i = 0; i < Y.size(); ++i)\r\n                        {\r\n                            r.train(trans(rowm(X,i)), Y(i));\r\n                        }\r\n\r\n\r\n                        matrix<double> w = pinv(1.0/C*identity_matrix<double>(X.nc()) + trans(X)*X)*trans(X)*Y;\r\n\r\n                        rs2.add(length(r.get_w() - w));\r\n                    }\r\n\r\n                    {\r\n                        matrix<double> X = join_rows(randm(size,num_vars,rnd)-0.5, ones_matrix<double>(size,1));\r\n                        matrix<double> Y = uniform_matrix<double>(size,1,10);\r\n\r\n\r\n                        const double C = 1e7;\r\n                        const double forget_factor = 1.0;\r\n\r\n                        matrix<double> w = pinv(1.0/C*identity_matrix<double>(X.nc()) + trans(X)*X)*trans(X)*Y;\r\n\r\n                        rls r(forget_factor, C);\r\n                        for (long i = 0; i < Y.size(); ++i)\r\n                        {\r\n                            r.train(trans(rowm(X,i)), Y(i));\r\n                            rs3.add(std::abs(r(trans(rowm(X,i))) - 10));\r\n                        }\r\n\r\n\r\n                    }\r\n                    {\r\n                        matrix<double> X = randm(size,num_vars,rnd)-0.5;\r\n                        matrix<double> Y = colm(X,0)*10;\r\n\r\n\r\n                        const double C = 1e6;\r\n                        const double forget_factor = 0.7;\r\n\r\n\r\n                        rls r(forget_factor, C);\r\n                        DLIB_TEST(std::abs(r.get_c() - C) < 1e-10);\r\n                        DLIB_TEST(std::abs(r.get_forget_factor() - forget_factor) < 1e-15);\r\n                        DLIB_TEST(r.get_w().size() == 0);\r\n\r\n                        for (long i = 0; i < Y.size(); ++i)\r\n                        {\r\n                            r.train(trans(rowm(X,i)), Y(i));\r\n                            rs4.add(std::abs(r(trans(rowm(X,i))) - X(i,0)*10));\r\n                        }\r\n\r\n                        DLIB_TEST(r.get_w().size() == num_vars);\r\n\r\n                        decision_function<linear_kernel<matrix<double,0,1> > > df = r.get_decision_function();\r\n                        DLIB_TEST(std::abs(df(trans(rowm(X,0))) - r(trans(rowm(X,0)))) < 1e-15);\r\n                    }\r\n                }\r\n            } \r\n        }\r\n\r\n        dlog << LINFO << \"rs1.mean(): \" << rs1.mean();\r\n        dlog << LINFO << \"rs2.mean(): \" << rs2.mean();\r\n        dlog << LINFO << \"rs3.mean(): \" << rs3.mean();\r\n        dlog << LINFO << \"rs4.mean(): \" << rs4.mean();\r\n        dlog << LINFO << \"rs5.mean(): \" << rs5.mean();\r\n        dlog << LINFO << \"rs1.max(): \" << rs1.max();\r\n        dlog << LINFO << \"rs2.max(): \" << rs2.max();\r\n        dlog << LINFO << \"rs3.max(): \" << rs3.max();\r\n        dlog << LINFO << \"rs4.max(): \" << rs4.max();\r\n        dlog << LINFO << \"rs5.max(): \" << rs5.max();\r\n\r\n        DLIB_TEST_MSG(rs1.mean() < 1e-10, rs1.mean());\r\n        DLIB_TEST_MSG(rs2.mean() < 1e-9, rs2.mean());\r\n        DLIB_TEST_MSG(rs3.mean() < 1e-6, rs3.mean());\r\n        DLIB_TEST_MSG(rs4.mean() < 1e-6, rs4.mean());\r\n        DLIB_TEST_MSG(rs5.mean() < 1e-3, rs5.mean());\r\n\r\n        DLIB_TEST_MSG(rs1.max() < 1e-10, rs1.max());\r\n        DLIB_TEST_MSG(rs2.max() < 1e-6,  rs2.max());\r\n        DLIB_TEST_MSG(rs3.max() < 0.001, rs3.max());\r\n        DLIB_TEST_MSG(rs4.max() < 0.01,  rs4.max());\r\n        DLIB_TEST_MSG(rs5.max() < 0.1,  rs5.max());\r\n        \r\n    }\r\n\r\n\r\n\r\n\r\n    class rls_tester : public tester\r\n    {\r\n    public:\r\n        rls_tester (\r\n        ) :\r\n            tester (\"test_rls\",\r\n                    \"Runs tests on the rls component.\")\r\n        {}\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            test_rls();\r\n        }\r\n    } a;\r\n\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "b1e58539852a01874cde9064f14d1a6fb9cfcbd7", "size": 6453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/rls.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": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-10-11T18:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-11T18:37:52.000Z", "max_issues_repo_path": "dlib/test/rls.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": "dlib/test/rls.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": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-19T06:15:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-02T11:11:57.000Z", "avg_line_length": 32.7563451777, "max_line_length": 113, "alphanum_fraction": 0.3850922052, "num_tokens": 1545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5370172864773255}}
{"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_ASECPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASECPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the inverse secant in \\f$\\pi\\f$ multiples:\n    \\f$(1/\\pi) \\arccos(1/x)\\f$.\n\n    @see asec, asecd, cospi, acospi\n\n\n\n    @par Header <boost/simd/function/asecpi.hpp>\n\n    @par Example:\n\n      @snippet asecpi.cpp asecpi\n\n    @par Possible output:\n\n      @snippet asecpi.txt asecpi\n\n  **/\n  IEEEValue asecpi(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/asecpi.hpp>\n#include <boost/simd/function/simd/asecpi.hpp>\n\n#endif\n", "meta": {"hexsha": "d854ddcc7d484749c746a6093c239b0485da680f", "size": 1067, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/asecpi.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/function/asecpi.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/function/asecpi.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": 23.1956521739, "max_line_length": 100, "alphanum_fraction": 0.5763823805, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.536985099569935}}
{"text": "// Copyright Louis Dionne 2013-2017\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/div.hpp>\r\n#include <boost/hana/equal.hpp>\r\n#include <boost/hana/ext/std/ratio.hpp>\r\n#include <boost/hana/minus.hpp>\r\n#include <boost/hana/mod.hpp>\r\n#include <boost/hana/mult.hpp>\r\n#include <boost/hana/one.hpp>\r\n#include <boost/hana/plus.hpp>\r\n#include <boost/hana/zero.hpp>\r\n\r\n#include <ratio>\r\nnamespace hana = boost::hana;\r\n\r\n\r\nBOOST_HANA_CONSTANT_CHECK(hana::equal(\r\n    hana::plus(std::ratio<5, 3>{}, std::ratio<3, 12>{}),\r\n    std::ratio<23, 12>{}\r\n));\r\n\r\nBOOST_HANA_CONSTANT_CHECK(hana::equal(\r\n    hana::minus(std::ratio<5, 3>{}, std::ratio<3, 13>{}),\r\n    std::ratio<56, 39>{}\r\n));\r\n\r\nBOOST_HANA_CONSTANT_CHECK(hana::equal(\r\n    hana::mult(std::ratio<5, 3>{}, std::ratio<3, 13>{}),\r\n    std::ratio<15, 39>{}\r\n));\r\n\r\nBOOST_HANA_CONSTANT_CHECK(hana::equal(\r\n    hana::div(std::ratio<5, 3>{}, std::ratio<3, 13>{}),\r\n    std::ratio<65, 9>{}\r\n));\r\n\r\n// The mod of two ratios is always 0, because they can always be\r\n// divided without remainder.\r\nBOOST_HANA_CONSTANT_CHECK(hana::equal(\r\n    hana::mod(std::ratio<5, 3>{}, std::ratio<3, 13>{}),\r\n    std::ratio<0>{}\r\n));\r\n\r\nBOOST_HANA_CONSTANT_CHECK(hana::equal(\r\n    hana::zero<hana::ext::std::ratio_tag>(),\r\n    std::ratio<0>{}\r\n));\r\n\r\nBOOST_HANA_CONSTANT_CHECK(hana::equal(\r\n    hana::one<hana::ext::std::ratio_tag>(),\r\n    std::ratio<1>{}\r\n));\r\n\r\nint main() { }\r\n", "meta": {"hexsha": "3cfd64d590f1269e6dbcbaf53f278b68e19125f9", "size": 1558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/ext/std/ratio/arithmetic.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/hana/example/ext/std/ratio/arithmetic.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/hana/example/ext/std/ratio/arithmetic.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": 26.8620689655, "max_line_length": 82, "alphanum_fraction": 0.6399229782, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5369850771855321}}
{"text": "#include \"numpy_utils.hpp\"\n#include <boost/foreach.hpp>\n#include <boost/python.hpp>\n#include <Eigen/Core>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <iostream>\n#include <iostream>\n#include <vector>\n\n\nusing namespace Eigen;\nusing namespace std;\nnamespace py = boost::python;\n\n\n/////////////////\n\n\n\n\n// http://en.wikipedia.org/wiki/Axis_angle#Log_map_from_SO.283.29_to_so.283.29\nVector3d LogMap(const Matrix3d& m) {\n  double cosarg = (m.trace() - 1)/2;\n  cosarg = fmin(cosarg, 1);\n  cosarg = fmax(cosarg, -1);\n  double theta = acos( cosarg );\n  if (theta==0) return Vector3d::Zero();\n  else return theta*(1/(2*sin(theta))) * Vector3d(m(2,1) - m(1,2), m(0,2)-m(2,0), m(1,0)-m(0,1));\n}\n\ndouble RotReg(const Matrix3d& b, const Vector3d& rot_coeffs, double scale_coeff) {\n  // regularize rotation using polar decomposition\n  JacobiSVD<Matrix3d> svd(b.transpose(), ComputeFullU | ComputeFullV);\n  Vector3d s = svd.singularValues();\n  if (b.determinant() <= 0) return INFINITY;\n  return LogMap(svd.matrixU() * svd.matrixV().transpose()).cwiseAbs().dot(rot_coeffs) + s.array().log().square().sum()*scale_coeff;\n}\n\nMatrix3d RotRegGrad(const Matrix3d& b, const Vector3d& rot_coeffs, double scale_coeff) {\n  Matrix3d out;\n  double y0 = RotReg(b, rot_coeffs, scale_coeff);\n  Matrix3d xpert = b;\n  double epsilon = 1e-5;\n  for (int i=0; i < 3; ++i) {\n    for (int j=0; j < 3; ++j) {\n      xpert(i,j) = b(i,j) + epsilon;\n      out(i,j) = (RotReg(xpert, rot_coeffs, scale_coeff) - y0)/epsilon;\n      xpert(i,j) = b(i,j);\n    }\n  }\n  return out;\n}\n\nVector3d gRotCoeffs;\ndouble gScaleCoeff;\n\nvoid PySetCoeffs(py::object rot_coeffs, py::object scale_coeff) {\n  gRotCoeffs = Vector3d(py::extract<double>(rot_coeffs[0]), py::extract<double>(rot_coeffs[1]), py::extract<double>(rot_coeffs[2]));\n  gScaleCoeff = py::extract<double>(scale_coeff);\n}\n\n\ndouble PyRotReg(const py::object& m ){\n  const double* data = getPointer<double>(m);\n  return RotReg( Map< const Matrix<double,3,3,RowMajor> >(data), gRotCoeffs, gScaleCoeff);\n}\n\npy::object PyRotRegGrad(const py::object& m) {\n  static py::object np_mod = py::import(\"numpy\");\n  py::object out = np_mod.attr(\"empty\")(py::make_tuple(3,3));\n  const double* data = getPointer<double>(m);\n  Matrix<double,3,3,RowMajor> g = RotRegGrad( Map< const Matrix<double,3,3,RowMajor> >(data), gRotCoeffs, gScaleCoeff);\n  memcpy(getPointer<double>(out), g.data(), sizeof(double)*9);\n  return out;\n}\n\n\n\n////////////////\n\nvoid Interp(float x0, float x1, const VectorXf& y0, const VectorXf& y1, const VectorXf& newxs, MatrixXf& newys) {\n  float dx = x1 - x0;\n  for (int i=0; i < newxs.size(); ++i) {\n    newys.row(i) = ((x1 - newxs[i])/dx) * y0 + ((newxs[i] - x0)/dx) * y1;\n  }\n}\n\nvector<int> Resample(const MatrixXf& x, const VectorXf& _t, float max_err, float max_dx, float max_dt) {\n  int N = x.rows(); // number of timesteps\n  VectorXf t;\n  if (_t.size() == 0){\n    t.resize(N);\n    for (int i=0; i < N; ++i) t[i] = i;\n  }\n  else t=_t;\n  VectorXi cost(N); // shortest path cost\n  VectorXi pred(N); // shortest path predecessor\n\n  MatrixXf q(20, x.cols()); // scratch space for interpolation\n  q.setConstant(-666);\n\n  const int NOPRED = -666;\n  const int BIGINT = 999999;\n\n  pred.setConstant(NOPRED);\n  cost.setConstant(BIGINT);\n  cost(0) = 0;\n  pred(0) = NOPRED;\n  for (int iSrc = 0; iSrc < N; ++iSrc) {\n    for (int iTarg = iSrc+1; iTarg < N; ++iTarg) {\n      float dx = (x.row(iTarg) - x.row(iSrc)).maxCoeff();\n      float dt = t(iTarg) - t(iSrc);\n      int seglen = iTarg - iSrc + 1;\n      if (q.rows() < seglen) q.resize(2*q.rows(), q.cols());\n      Interp(t(iSrc), t(iTarg), x.row(iSrc), x.row(iTarg), t.middleRows(iSrc, seglen), q);\n      float err = (q.block(0,0,seglen, x.cols()) - x.middleRows(iSrc, seglen)).cwiseAbs().maxCoeff();\n      if ((dx <= max_dx) && (dt <= max_dt || iTarg == iSrc+1) && (err <= max_err)) {\n        int newcost = cost(iSrc) + 1;\n        if (newcost < cost(iTarg)) {\n          cost(iTarg) = newcost;\n          pred(iTarg) = iSrc;\n        }\n      }\n      else break;\n    }\n  }\n\n  int i=N-1;\n  vector<int> revpath;\n  while (i > 0) {\n    revpath.push_back(i);\n    i = pred(i);\n  }\n  revpath.push_back(0);\n  std::reverse(revpath.begin(), revpath.end());\n  return revpath;\n}\n\npy::object pyResample(py::object x, py::object t, float max_err, float max_dx, float max_dt) {\n  x = np_mod.attr(\"array\")(x, \"float32\");\n  int xdim0 = py::extract<int>(x.attr(\"shape\")[0]);\n  int xdim1 = py::extract<int>(x.attr(\"shape\")[1]);\n  float* xdata = getPointer<float>(x);\n  t = np_mod.attr(\"array\")(t, \"float32\");\n  int tdim0 = py::extract<int>(t.attr(\"__len__\")());\n  float* tdata = getPointer<float>(t);\n  vector<int> inds = Resample(Map<MatrixXf>(xdata, xdim0, xdim1), Map<VectorXf>(tdata, tdim0), max_err, max_dx, max_dt);\n  return toNdarray1<int>(inds.data(), inds.size());\n}\n//BOOST_PYTHON_FUNCTION_OVERLOADS(resample_overloads, pyResample, 3, 5);\n\n///////////////////\n\n\nBOOST_PYTHON_MODULE(fastrapp) {\n\n  np_mod = py::import(\"numpy\");\n\n  py::def(\"resample\", &pyResample, (py::arg(\"x\"), py::arg(\"t\"), py::arg(\"max_err\"),   py::arg(\"max_dx\")=INFINITY, py::arg(\"max_dt\")=INFINITY));\n  \n  py::def(\"set_coeffs\", &PySetCoeffs, (py::arg(\"rot_coeffs\"), py::arg(\"scale_coeff\")));\n  py::def(\"rot_reg\", &PyRotReg, (py::arg(\"B\")));\n  py::def(\"rot_reg_grad\", &PyRotRegGrad, (py::arg(\"B\")));\n  \n\n}\n", "meta": {"hexsha": "e50db50fa5a1a8e7ca24c2b1bee1111ba42c3191", "size": 5348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fastrapp/fastrapp.cpp", "max_stars_repo_name": "wjchen84/rapprentice", "max_stars_repo_head_hexsha": "9232a6a21e2c80f00854912f07dcdc725b0be95a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T19:40:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T09:23:06.000Z", "max_issues_repo_path": "fastrapp/fastrapp.cpp", "max_issues_repo_name": "wjchen84/rapprentice", "max_issues_repo_head_hexsha": "9232a6a21e2c80f00854912f07dcdc725b0be95a", "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": "fastrapp/fastrapp.cpp", "max_forks_repo_name": "wjchen84/rapprentice", "max_forks_repo_head_hexsha": "9232a6a21e2c80f00854912f07dcdc725b0be95a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-05-18T20:13:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-03T16:09:50.000Z", "avg_line_length": 31.6449704142, "max_line_length": 143, "alphanum_fraction": 0.6299551234, "num_tokens": 1780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.5369850715491052}}
{"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_XYZ_HAMILTONIAN_HPP\n#define ROKKO_UTILITY_XYZ_HAMILTONIAN_HPP\n\n#include <vector>\n#include <boost/tuple/tuple.hpp>\n#include <rokko/localized_matrix.hpp>\n\nnamespace rokko {\n\nnamespace xyz_hamiltonian {\n\ntemplate<typename T>\nvoid multiply(int L, const std::vector<std::pair<int, int> >& lattice,\n  const std::vector<boost::tuple<double, double, double> >& coupling, const T* v, T* w) {\n  int N = 1 << L;\n  for (int l = 0; l < lattice.size(); ++l) {\n    int i = lattice[l].first;\n    int j = lattice[l].second;\n    double jx = coupling[l].get<0>();\n    double jy = coupling[l].get<1>();\n    double jz = coupling[l].get<2>();\n\n    double diag_plus = jz / 4.0;\n    double diag_minus = - jz / 4.0;\n    double offdiag_plus = (jx + jy) / 4.0;\n    double offdiag_minus = (jx - jy) / 4.0;\n\n    int m1 = 1 << i;\n    int m2 = 1 << j;\n    int m3 = m1 + m2;\n    for (int k=0; k<N; ++k) {\n      if (((k & m3) == m1) || ((k & m3) == m2)) {\n        // when (bit i == 1, bit j == 0) or (bit i == 0, bit j == 1)\n        w[k] += diag_minus * v[k] + offdiag_plus * v[k^m3];\n      } else {\n        w[k] += diag_plus * v[k] + offdiag_minus * v[k^m3];\n      }\n    }\n  }\n}\n\ntemplate<typename T>\nvoid multiply(int L, const std::vector<std::pair<int, int> >& lattice,\n  const std::vector<boost::tuple<double, double, double> >& coupling, const std::vector<T>& v,\n  std::vector<T>& w) {\n  multiply(L, lattice, coupling, &v[0], &w[0]);\n}\n\ntemplate<typename T>\nvoid fill_diagonal(int L, const std::vector<std::pair<int, int> >& lattice,\n  const std::vector<boost::tuple<double, double, double> >& coupling, T* w) {\n  int N = 1 << L;\n  for (int k=0; k<N; ++k) {\n    w[k] = 0;\n  }\n  for (int l=0; l<lattice.size(); ++l) {\n    int i = lattice[l].first;\n    int j = lattice[l].second;\n    double jx = coupling[l].get<0>();\n    double jy = coupling[l].get<1>();\n    double jz = coupling[l].get<2>();\n\n    double diag_plus = jz / 4.0;\n    double diag_minus = - jz / 4.0;\n    double offdiag_plus = (jx + jy) / 4.0;\n    double offdiag_minus = (jx - jy) / 4.0;\n\n    int m1 = 1 << i;\n    int m2 = 1 << j;\n    int m3 = m1 + m2;\n    for (int k=0; k<N; ++k) {\n      if (((k & m3) == m1) || ((k & m3) == m2)) {\n        // when (bit i == 1, bit j == 0) or (bit i == 0, bit j == 1)\n        w[k] += diag_minus;\n      } else {\n        w[k] += diag_plus;\n      }\n    }\n  }\n}\n\ntemplate<typename T>\nvoid fill_diagonal(int L, const std::vector<std::pair<int, int> >& lattice,\n  const std::vector<boost::tuple<double, double, double> >& coupling, std::vector<T>& w) {\n  fill_diagonal(L, lattice, coupling, &w[0]);\n}\n\ntemplate<typename T, typename MATRIX_MAJOR>\nvoid generate(int L, const std::vector<std::pair<int, int> >& lattice,\n  const std::vector<boost::tuple<double, double, double> >& coupling,\n  rokko::localized_matrix<T, MATRIX_MAJOR>& mat) {\n  mat.set_zeros();\n  int N = 1 << L;\n  for (int l=0; l<lattice.size(); ++l) {\n    int i = lattice[l].first;\n    int j = lattice[l].second;\n    double jx = coupling[l].get<0>();\n    double jy = coupling[l].get<1>();\n    double jz = coupling[l].get<2>();\n    double diag_plus = jz / 4.0;\n    double diag_minus = - jz/ 4.0;\n    double offdiag_plus = (jx + jy) / 4.0;\n    double offdiag_minus = (jx - jy) / 4.0;\n\n    int m1 = 1 << i;\n    int m2 = 1 << j;\n    int m3 = m1 + m2;\n    for (int k=0; k<N; ++k) {\n      if (((k & m3) == m1) || ((k & m3) == m2)) {\n        // when (bit i == 1, bit j == 0) or (bit i == 0, bit j == 1)\n        mat(k^m3, k) += offdiag_plus;\n        mat(k, k) += diag_minus;\n      } else {\n        mat(k^m3, k) += offdiag_minus;\n        mat(k, k) += diag_plus;\n      }\n    }\n  }\n}\n\n} // namespace xyz_hamiltonian\n\n} // namespace rokko\n\n#endif // ROKKO_UTILITY_XYZ_HAMILTONIAN_HPP\n", "meta": {"hexsha": "34862249772cda392e7670574f5512e6e54b837f", "size": 4189, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rokko/utility/xyz_hamiltonian.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/xyz_hamiltonian.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/xyz_hamiltonian.hpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5766423358, "max_line_length": 94, "alphanum_fraction": 0.5504893769, "num_tokens": 1387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5369438466398014}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <chrono>\n#include <limits>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <opencv2/calib3d.hpp>\n#include <opencv2/core/eigen.hpp>\n\n#include \"poseocv.h\"\n#include \"math.hh\"\n#include \"display.h\"\n\nnamespace poseocv\n{\n   void homography_pose(const cv::Mat& intrinsics, const std::vector<cv::Point3d>& train_img_pts,\n                        const std::vector<cv::Point3d>& query_img_pts, std::vector<cv::Mat>& rotations,\n                        std::vector<cv::Mat>& translations, std::vector<cv::Mat>& normals, bool isRANSAC)\n//---------------------------------------------------------------------------------------------\n   {\n      cv::Mat H;\n      rotations.clear(); translations.clear();\n      std::vector<cv::Point2f> train_pts, query_pts;\n      for (size_t i = 0; i < std::min(train_img_pts.size(), query_img_pts.size()); i++)\n      {\n         const cv::Point3d tpt = train_img_pts[i];\n         train_pts.emplace_back(tpt.x, tpt.y);\n         const cv::Point3d qpt = query_img_pts[i];\n         query_pts.emplace_back(qpt.x, qpt.y);\n      }\n      if ((isRANSAC) && (train_img_pts.size() > 3))\n         H = cv::findHomography(train_pts, query_pts, cv::RANSAC);\n      else\n         H = cv::findHomography(train_pts, query_pts);\n      if (H.empty()) return;\n      cv::decomposeHomographyMat(H, intrinsics, rotations, translations, normals);\n   }\n\n\n   bool pose_PnP(const std::vector<cv::Point3d>& world_pts, const std::vector<cv::Point3d>& image_pts,\n                 const cv::Mat& intrinsics, cv::Mat& rotation_vec, cv::Mat& translations3x1, cv::Mat* R,\n                 long& total_time, bool is_refine, int flags, PnPRANSACParameters* RANSACParams)\n//--------------------------------------------------------------------------------------------------\n   {\n      std::vector<cv::Point2f> points2d;\n      std::vector<cv::Point3f> points3d;\n      std::size_t n = std::min(world_pts.size(), image_pts.size());\n      for (size_t i = 0; i < n; i++)\n      {\n         if ((i >= 4) &&\n             ((flags == cv::SOLVEPNP_P3P) || (flags == cv::SOLVEPNP_AP3P)))\n         {\n//         std::cout << \"poseocv::pose_PnP WARNING: Abbreviated input point count to \" << points2d.size() << std::endl;\n            break;\n         }\n         cv::Point3d pt = image_pts[i];\n         points2d.emplace_back(pt.x, pt.y);\n         pt = world_pts[i];\n         points3d.emplace_back(pt.x, pt.y, pt.z);\n      }\n      if ( (RANSACParams != nullptr) && (n > 4) )\n      {\n         std::vector<unsigned char> inliers(points3d.size());\n         auto start = std::chrono::high_resolution_clock::now();\n         if (cv::solvePnPRansac(points3d, points2d, intrinsics, cv::noArray(), rotation_vec, translations3x1,\n                                is_refine, RANSACParams->iterationsCount, RANSACParams->reprojectionError,\n                                RANSACParams->confidence, inliers, flags))\n         {\n            auto diff = std::chrono::high_resolution_clock::now() - start;\n            total_time = std::chrono::duration_cast<std::chrono::nanoseconds>(diff).count();\n//         for (size_t j = 0; j < points3d.size(); j++)\n//         {\n//            if (!inliers[j])\n//               fprintf(stdout, \"outlier (%.5f, %.5f) (%.5f, %.5f, %.5f)\\n\", points2d[j].x, points2d[j].y, points3d[j].x,\n//                       points3d[j].y, points3d[j].z);\n//         }\n            if (R != nullptr)\n               cv::Rodrigues(rotation_vec, *R);\n            return true;\n         }\n         else\n            total_time = -1;\n      }\n      else\n      {\n         auto start = std::chrono::high_resolution_clock::now();\n         try\n         {\n            if (cv::solvePnP(points3d, points2d, intrinsics, cv::noArray(), rotation_vec, translations3x1, is_refine,\n                             flags))\n            {\n               auto diff = std::chrono::high_resolution_clock::now() - start;\n               total_time = std::chrono::duration_cast<std::chrono::nanoseconds>(diff).count();\n               if (R != nullptr)\n                  cv::Rodrigues(rotation_vec, *R);\n               return true;\n            }\n            else\n               total_time = -1;\n         }\n         catch (...)\n         {\n            return false;\n         }\n      }\n      return false;\n   }\n\n   void display_PnP(const std::vector<cv::Point3d>& world_points,\n                    const std::vector<cv::Point3d>& image_points,\n                    const cv::Mat& intrinsics, bool isMinimal, const cv::Mat* query_img,\n                    bool show_reprojection, bool save_reprojection, bool is_time)\n//----------------------------------------------------------------------------------------------------\n   {\n      cv::Mat rotation_vec, translations3x1, R;\n      std::array<std::pair<std::string, int>, 5> methods {std::make_pair(\"Iterative\", cv::SOLVEPNP_ITERATIVE),\n                                                          std::make_pair(\"P3P\", cv::SOLVEPNP_P3P),\n                                                          std::make_pair(\"EPnP\", cv::SOLVEPNP_EPNP),\n                                                          std::make_pair(\"DLS\", cv::SOLVEPNP_DLS),\n                                                          std::make_pair(\"AP3P\", cv::SOLVEPNP_AP3P)\n      };\n      for (auto pp : methods)\n      {\n         bool is_pose;\n         std::vector<cv::Point3d> world_pts, image_pts, new_world_pts, new_image_pts;\n         if (world_points.size() != image_points.size())\n         {\n            size_t n = std::min(world_points.size(), image_points.size());\n            std::copy(world_points.begin(), world_points.begin() + n, std::back_inserter(world_pts));\n            std::copy(image_points.begin(), image_points.begin() + n, std::back_inserter(image_pts));\n         }\n         else\n         {\n            world_pts = world_points;\n            image_pts = image_points;\n         }\n         switch (pp.second)\n         {\n            case cv::SOLVEPNP_AP3P:\n            case cv::SOLVEPNP_P3P:\n               if (world_pts.size() > 4)\n               {\n                  std::copy(world_pts.begin(), world_pts.begin() + 4, std::back_inserter(new_world_pts));\n                  std::copy(image_pts.begin(), image_pts.begin() + 4, std::back_inserter(new_image_pts));\n               }\n         }\n         long time_ns;\n         for (int i = 0; i < 1; i++)\n         {\n            bool is_ransac = (i > 0);\n            PnPRANSACParameters RANSAC_params, *pRANSAC_params = nullptr;\n            if (is_ransac)\n            {\n               std::cout << \"RANSAC:\";\n               RANSAC_params.iterationsCount = 1000;\n               pRANSAC_params = &RANSAC_params;\n            }\n            try\n            {\n               if (new_world_pts.size() > 0)\n                  is_pose = pose_PnP(new_world_pts, new_image_pts, intrinsics, rotation_vec, translations3x1, &R,\n                                     time_ns, false, pp.second, pRANSAC_params);\n               else\n                  is_pose = pose_PnP(world_pts, image_pts, intrinsics, rotation_vec, translations3x1, &R,\n                                     time_ns, false, pp.second, pRANSAC_params);\n            }\n            catch (std::exception& e)\n            {\n//            std::cerr << \"   display_PnP \" << pp.first << \" Exception: \" << e.what() << std::endl;\n               std::cout << \"    No PnP solution (exception)\" << std::endl;\n               continue;\n            }\n            if (is_pose)\n            {\n               std::cout << \"    ***** \" << pp.first << \" (\" << time_ns << \"ns )\" << std::endl;\n               cv::Mat TT = translations3x1.t();\n               Eigen::Matrix3d ER;\n               cv::cv2eigen(R, ER);\n               Eigen::AngleAxisd aa(ER);\n               Eigen::Quaterniond QQ(ER);\n               if (!isMinimal)\n               {\n                  std::cout << \"    Axis: \" << aa.axis().transpose() << \" Angle: \" << mut::radiansToDegrees(aa.angle())\n                            << std::endl;\n                  std::cout << \"    Quaternion: [\" << QQ.w() << \", (\" << QQ.vec().transpose() << \")\" << std::endl;\n               }\n\n               const cv::Vec3f& euler = mut::rotation2Euler(R);\n               std::cout << std::fixed << std::setprecision(4) << \"Rotation Roll,Pitch,Yaw: [\"\n                         << mut::radiansToDegrees(euler[0]) << \",\"\n                         << mut::radiansToDegrees(euler[1]) << \",\" << mut::radiansToDegrees(euler[2]) << \" ]\\u00B0 (\"\n                         << euler[0] << \",\" << euler[1] << \",\" << euler[2] << \") radians (\"\n                         << mut::radiansToDegrees(euler[0]) << \"\\\\textdegree,\"\n                         << mut::radiansToDegrees(euler[1]) << \"\\\\textdegree,\" << mut::radiansToDegrees(euler[2])\n                         << \"\\\\textdegree)\" << std::endl;\n               std::cout << std::fixed << std::setprecision(4) << \"    Translation: \" << TT.at<double>(0, 0) << \",\"\n                         << TT.at<double>(0, 1) << \",\" << TT.at<double>(0, 2) << std::endl;\n               cv::Mat empty_img;\n               if (query_img == nullptr)\n               {\n                  query_img = &empty_img;\n                  show_reprojection = false;\n               }\n               Eigen::Quaterniond Q(aa);\n               Eigen::Vector3d t;\n               cv::cv2eigen(translations3x1, t);\n               std::string name;\n               char* pname = nullptr;\n               if ((save_reprojection) && (query_img != nullptr))\n               {\n                  name = \"reproject-\" + pp.first + \".jpg\";\n                  pname = const_cast<char*>(name.c_str());\n               }\n               double max_error, mean_error, stddev_error;\n               show_projection(*query_img, world_pts, image_pts, intrinsics, Q, t[0], t[1], t[2],\n                               max_error, mean_error, stddev_error, show_reprojection, pname);\n               std::cout << std::setprecision(4) << \"    Max Error \" << max_error << \", mean error \" << mean_error\n                         << \" Std Deviation \" << stddev_error << std::endl;\n            }\n            else\n               std::cout << \"    No PnP solution\" << std::endl;\n            std::cout << \"---------------------------------------------\" << std::endl;\n         }\n      }\n   }\n}", "meta": {"hexsha": "dbd0bac00780567a514d4cb48ff720657042b2b2", "size": 10269, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/pose/poseocv.cc", "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/poseocv.cc", "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/poseocv.cc", "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": 45.0394736842, "max_line_length": 122, "alphanum_fraction": 0.4771642808, "num_tokens": 2478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5369438408756056}}
{"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\n#include <Eigen/Core>\n\n#include <vector>\n\n#include \"tudat/math/basic/numericalDerivative.h\"\n#include \"tudat/basics/testMacros.h\"\n#include \"tudat/basics/utilities.h\"\n#include \"tudat/io/matrixTextFileReader.h\"\n\n#include \"tudat/math/interpolators/createInterpolator.h\"\n#include \"tudat/io/basicInputOutput.h\"\n\n#include \"tudat/interface/spice/spiceInterface.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n\ntemplate< typename TimeType, typename StateScalarType >\nstd::vector< Eigen::Matrix< StateScalarType, 6, 1 > > computeSecondOrderCentralDifferenceCartesianStateDerivative(\n        const std::map< TimeType, Eigen::Matrix< StateScalarType, 6, 1 > >& cartesianStateMap )\n{\n    std::vector< Eigen::Matrix< StateScalarType, 6, 1 > > cartesianStateDerivativeMap;\n\n    auto lowerIterator = cartesianStateMap.begin( );\n    auto centralIterator = cartesianStateMap.begin( );\n    std::advance( centralIterator, 1 );\n    auto upperIterator = cartesianStateMap.begin( );\n    std::advance( upperIterator, 2 );\n\n    Eigen::Matrix< StateScalarType, 6, 1 > currentStateDerivative;\n    while( upperIterator != cartesianStateMap.end( ) )\n    {\n        if( lowerIterator == cartesianStateMap.begin( ) )\n        {\n            currentStateDerivative.segment( 0, 3 ) = lowerIterator->second.segment( 3, 3 );\n            currentStateDerivative.segment( 3, 3 ) =\n                    ( upperIterator->second.segment( 3, 3 ) - centralIterator->second.segment( 3, 3 ) ) /\n                    ( upperIterator->first - centralIterator->first );\n            cartesianStateDerivativeMap.push_back( currentStateDerivative );\n\n        }\n\n        currentStateDerivative.segment( 0, 3 ) = centralIterator->second.segment( 3, 3 );\n        currentStateDerivative.segment( 3, 3 ) =\n                ( upperIterator->second.segment( 3, 3 ) - lowerIterator->second.segment( 3, 3 ) ) /\n                ( upperIterator->first - lowerIterator->first );\n        cartesianStateDerivativeMap.push_back( currentStateDerivative );\n\n\n        lowerIterator++;\n        centralIterator++;\n        upperIterator++;\n\n        if( upperIterator == cartesianStateMap.end( ) )\n        {\n            currentStateDerivative.segment( 0, 3 ) = upperIterator->second.segment( 3, 3 );\n            currentStateDerivative.segment( 3, 3 ) =\n                    ( centralIterator->second.segment( 3, 3 ) - lowerIterator->second.segment( 3, 3 ) ) /\n                    ( centralIterator->first - lowerIterator->first );\n            cartesianStateDerivativeMap.push_back( currentStateDerivative );\n\n        }\n\n    }\n\n    return cartesianStateDerivativeMap;\n}\n\nusing namespace interpolators;\n\nBOOST_AUTO_TEST_SUITE( test_interpolator_vector_conversion )\n\nBOOST_AUTO_TEST_CASE( testInterpolatorVectorConversion )\n{\n    spice_interface::loadStandardSpiceKernels( );\n\n    std::map< double, Eigen::Vector6d > vector6dInterpolatorInput;\n    std::map< double, Eigen::VectorXd > vectorXdInterpolatorInput;\n    std::map< double, Eigen::MatrixXd > matrixXdInterpolatorInput;\n    for( int i = 0; i < 30; i++ )\n    {\n        double time = static_cast< double >( i ) * 86400.0;\n        vector6dInterpolatorInput[ time ] = spice_interface::getBodyCartesianStateAtEpoch(\n                    \"Moon\", \"Earth\", \"J2000\", \"None\", time );\n        vectorXdInterpolatorInput[ time ] = vector6dInterpolatorInput[ time ];\n        matrixXdInterpolatorInput[ time ] = vector6dInterpolatorInput[ time ];\n    }\n\n    std::vector< Eigen::Vector6d > vector6dDerivativeInput =\n            computeSecondOrderCentralDifferenceCartesianStateDerivative(\n                vector6dInterpolatorInput );\n    std::vector< Eigen::VectorXd > vectorXdDerivativeInput;\n    std::vector< Eigen::MatrixXd > matrixXdDerivativeInput;\n\n    for( unsigned int i = 0; i < vector6dDerivativeInput.size( ); i++ )\n    {\n        vectorXdDerivativeInput.push_back( vector6dDerivativeInput.at( i ) );\n        matrixXdDerivativeInput.push_back( vector6dDerivativeInput.at( i ) );\n\n    }\n\n\n    std::vector< double > interpolationTimes = { 1.0, 5.0 * 86400.0, 12.43 * 86400.0 };\n\n    for( int i = 0; i < 5; i++ )\n    {\n        std::shared_ptr< InterpolatorSettings > interpolatorSettings;\n        switch( i )\n        {\n        case 0:\n            interpolatorSettings =\n                    std::make_shared< InterpolatorSettings >( linear_interpolator );\n            break;\n        case 1:\n            interpolatorSettings =\n                    std::make_shared< InterpolatorSettings >( cubic_spline_interpolator );\n            break;\n        case 2:\n            interpolatorSettings =\n                    std::make_shared< LagrangeInterpolatorSettings >( 8 );\n            break;\n        case 3:\n            interpolatorSettings =\n                    std::make_shared< InterpolatorSettings >( hermite_spline_interpolator );\n            break;\n        case 4:\n            interpolatorSettings =\n                    std::make_shared< InterpolatorSettings >( piecewise_constant_interpolator );\n            break;\n        }\n        std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > direct6dInterpolator =\n                createOneDimensionalInterpolator(\n                    vector6dInterpolatorInput, interpolatorSettings,\n                    std::make_pair( IdentityElement::getAdditionIdentity< Eigen::Vector6d >( ),\n                                    IdentityElement::getAdditionIdentity< Eigen::Vector6d >( ) ),\n                    vector6dDerivativeInput );\n        std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > directXdInterpolator =\n                createOneDimensionalInterpolator(\n                    vectorXdInterpolatorInput, interpolatorSettings,\n                    std::make_pair( IdentityElement::getAdditionIdentity< Eigen::VectorXd >( ),\n                                    IdentityElement::getAdditionIdentity< Eigen::VectorXd >( ) ),\n                    vectorXdDerivativeInput );\n        std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > directXdMatrixInterpolator =\n                createOneDimensionalInterpolator(\n                    matrixXdInterpolatorInput, interpolatorSettings,\n                    std::make_pair( IdentityElement::getAdditionIdentity< Eigen::MatrixXd >( ),\n                                    IdentityElement::getAdditionIdentity< Eigen::MatrixXd >( ) ),\n                    matrixXdDerivativeInput);\n\n        std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > converted6dInterpolator =\n                convertBetweenStaticDynamicEigenTypeInterpolators<  double, double, -1, 1, 6, 1 >( directXdInterpolator );\n        std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > converted6dInterpolator2 =\n                convertBetweenStaticDynamicEigenTypeInterpolators<  double, double, -1, -1, 6, 1 >( directXdMatrixInterpolator );\n\n        std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > convertedXdInterpolator =\n                convertBetweenStaticDynamicEigenTypeInterpolators<  double, double, 6, 1, -1, 1 >( direct6dInterpolator );\n        std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > convertedXdInterpolator2 =\n                convertBetweenStaticDynamicEigenTypeInterpolators<  double, double, -1, -1, -1, 1 >( directXdMatrixInterpolator );\n\n        std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > convertedXdMatrixInterpolator =\n                convertBetweenStaticDynamicEigenTypeInterpolators<  double, double, 6, 1, -1, -1 >( direct6dInterpolator );\n        std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > convertedXdMatrixInterpolator2 =\n                convertBetweenStaticDynamicEigenTypeInterpolators<  double, double, -1, 1, -1, -1 >( directXdInterpolator );\n\n        for( unsigned int j = 0; j < interpolationTimes.size( ); j++ )\n        {\n            std::vector< Eigen::MatrixXd > testMatrices;\n            testMatrices.push_back( direct6dInterpolator->interpolate( interpolationTimes.at( j ) ) );\n            testMatrices.push_back( directXdInterpolator->interpolate( interpolationTimes.at( j ) ) );\n            testMatrices.push_back( directXdMatrixInterpolator->interpolate( interpolationTimes.at( j ) ) );\n\n            testMatrices.push_back( converted6dInterpolator->interpolate( interpolationTimes.at( j ) ) );\n            testMatrices.push_back( converted6dInterpolator2->interpolate( interpolationTimes.at( j ) ) );\n\n            testMatrices.push_back( convertedXdInterpolator->interpolate( interpolationTimes.at( j ) ) );\n            testMatrices.push_back( convertedXdInterpolator2->interpolate( interpolationTimes.at( j ) ) );\n\n            testMatrices.push_back( convertedXdMatrixInterpolator->interpolate( interpolationTimes.at( j ) ) );\n            testMatrices.push_back( convertedXdMatrixInterpolator2->interpolate( interpolationTimes.at( j ) ) );\n\n            for( unsigned int k = 1; k < testMatrices.size( ); k++ )\n            {\n                TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                            ( testMatrices.at( 0 ) ), ( testMatrices.at( k ) ), std::numeric_limits< double >::epsilon( ) );\n            }\n\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "f5a85bb273849a60d294c273dd19cd0346c92ecc", "size": 9799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/math/interpolators/unitTestInterpolatorVectorConversion.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/unitTestInterpolatorVectorConversion.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/unitTestInterpolatorVectorConversion.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": 45.7897196262, "max_line_length": 130, "alphanum_fraction": 0.6581283804, "num_tokens": 2234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5369438355949329}}
{"text": "#include \"functions/integral_polynomial.hh\"\n#include \"functions/polynomial.hh\"\n#include \"functions/full_function_defs.hh\"\n#include \"functions/operators.hh\"\n#include <boost/test/unit_test.hpp>\n#include <complex>\n#include \"functions/std_functions.hh\"\n#include \"functions/all_simplifications.hh\"\n\nBOOST_AUTO_TEST_CASE(polynomial_test) {\n  using namespace manifolds;\n\n  auto p = GetPolynomial(1, 0.5);\n  BOOST_CHECK_EQUAL(p(0), 1);\n  BOOST_CHECK_EQUAL(p(1), 1.5);\n  BOOST_CHECK_EQUAL(p(2), 2);\n\n  auto p2 = GetPolynomial(2, 5, 6);\n  auto p3 = p + p2;\n  static_assert(\n      std::is_same<decltype(p3), Polynomial<double, int_<3> > >::value,\n      \"Failed to simplify adding two polynomials!\");\n  BOOST_CHECK_EQUAL(p3(0), 3);\n  BOOST_CHECK_EQUAL(p3(1), 14.5);\n  BOOST_CHECK_EQUAL(p3(-1), 3.5);\n\n  auto p4 = p * p2;\n  static_assert(\n      std::is_same<decltype(p4), Polynomial<double, int_<4> > >::value,\n      \"Failed to simplify multiplying\"\n      \" two polynomials!\");\n  BOOST_CHECK_EQUAL(p4(0), p(0) * p2(0));\n  BOOST_CHECK_EQUAL(p4(1), p(1) * p2(1));\n  BOOST_CHECK_EQUAL(p4(2), p(2) * p2(2));\n\n  auto p5 = p3(p4);\n\n  static_assert(Simplifies<decltype(p5)>::value,\n                \"Failed to simplify polynomial composition\");\n  auto p6 = Composition<decltype(p3), decltype(p4)>(p3, p4);\n  for (int i = -3; i < 4; i++) {\n    BOOST_CHECK_EQUAL(p5(i), p6(i));\n  }\n\n  std::complex<double> c{ 1, 2 };\n  auto pc = GetPolynomial(c, 2.0 * c, c * c);\n\n  BOOST_CHECK_EQUAL(pc(0.0), c);\n  using namespace std::literals;\n  BOOST_CHECK_EQUAL(pc(1i), 0i);\n\n  auto ps = sin_ + sin_ + sin_;\n\n  BOOST_CHECK_EQUAL(ps(2), 3 * sin_(2));\n\n  ps = sin_ + (sin_ + sin_);\n  // The fact that the line above compiles means that\n  // the reverse generic simplification worked and gave\n  // the expected type.\n\n  BOOST_CHECK_EQUAL(ps(2), 3 * sin_(2));\n\n  IntegralPolynomial<1, -2, 3> ip;\n  IntegralPolynomial<3, 3, 7, 4> ip2;\n\n  auto ip3 = ip + ip2;\n\n  BOOST_CHECK_EQUAL(ip3(0), ip(0) + ip2(0));\n  BOOST_CHECK_EQUAL(ip3(1), ip(1) + ip2(1));\n  BOOST_CHECK_EQUAL(ip3(2), ip(2) + ip2(2));\n  BOOST_CHECK_EQUAL(ip3(3), ip(3) + ip2(3));\n  BOOST_CHECK_EQUAL(ip3(4), ip(4) + ip2(4));\n\n  auto ip4 = ip * ip2;\n\n  BOOST_CHECK_EQUAL(ip4(0), ip(0) * ip2(0));\n  BOOST_CHECK_EQUAL(ip4(1), ip(1) * ip2(1));\n  BOOST_CHECK_EQUAL(ip4(2), ip(2) * ip2(2));\n  BOOST_CHECK_EQUAL(ip4(3), ip(3) * ip2(3));\n  BOOST_CHECK_EQUAL(ip4(4), ip(4) * ip2(4));\n  BOOST_CHECK_EQUAL(ip4(5), ip(5) * ip2(5));\n  BOOST_CHECK_EQUAL(ip4(6), ip(6) * ip2(6));\n\n  auto ip5 = ip4 + IntegralPolynomial<-1, -1, -1, 0, -13, -12>();\n  static_assert(decltype(ip5)::num_coeffs == 4,\n                \"Failed to remove extraneous coefficients\");\n\n  auto p7 = p6 * ip5;\n  static_assert(!IsVariadic<Multiplication, decltype(p7)>::value,\n                \"Failed to simplify multiplication of polynomial \"\n                \"and integral polynomial\");\n}\n", "meta": {"hexsha": "db0191a7bb8898eeaa9a318f28cf901f96519b0c", "size": 2863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_polynomial.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_polynomial.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_polynomial.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": 30.7849462366, "max_line_length": 71, "alphanum_fraction": 0.6468739085, "num_tokens": 942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5369438298307372}}
{"text": "/***************************************************************************\n *   Copyright (C) 2006 by Nicola Bellotto                                 *\n *   nbellotto@lincoln.ac.uk                                                    *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n ***************************************************************************/\n\n#include \"models.h\"\n#include <bayes_tracking/BayesFilter/matSup.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <float.h>\n\n\nusing namespace Bayesian_filter;\nusing namespace Models;\n\n\n//*************************************************************************\n//                      CV PREDICTION MODEL\n//*************************************************************************\n\nCVModel::CVModel(Float wxSD, Float wySD) :\n        Linrz_predict_model(x_size, q_size),\n        Sampled_predict_model(),\n        fx(x_size),\n        genn(rnd),\n        xp(x_size),\n        n(q_size), rootq(q_size),\n        m_wxSD(wxSD), m_wySD(wySD)\n{\n    first_init = true;\n    init();\n}\n\n\nvoid CVModel::init()\n{\n    Fx.clear();\n    // x\n    Fx(0,0) = 1.;\n    Fx(0,1) = dt;\n    Fx(0,2) = 0.;\n    Fx(0,3) = 0.;\n    // dx\n    Fx(1,0) = 0.;\n    Fx(1,1) = 1.;\n    Fx(1,2) = 0.;\n    Fx(1,3) = 0.;\n    // y\n    Fx(2,0) = 0.;\n    Fx(2,1) = 0.;\n    Fx(2,2) = 1.;\n    Fx(2,3) = dt;\n    // dy\n    Fx(3,0) = 0.;\n    Fx(3,1) = 0.;\n    Fx(3,2) = 0.;\n    Fx(3,3) = 1.;\n    // noise\n    q[0] = sqr(m_wxSD); // cov(w_x)\n    q[1] = sqr(m_wySD); // cov(w_y)\n    G.clear();\n    G(0,0) = 0.5*sqr(dt);\n    G(1,0) = dt;\n    G(2,1) = 0.5*sqr(dt);\n    G(3,1) = dt;\n}\n\n\nconst FM::Vec& CVModel::f(const FM::Vec& x) const\n{  // human model\n    fx[0] = x[0] + x[1] * dt;  // x\n    fx[1] = x[1];              // dx\n    fx[2] = x[2] + x[3] * dt;  // y\n    fx[3] = x[3];              // dy\n    return fx;\n}\n\n\nvoid CVModel::update(double dt)\n{\n    // time interval\n    this->dt = dt;\n\n    //     | 0.5dt^2     0    |\n    // G = |    dt       0    |\n    //     |    0     0.5dt^2 |\n    //     |    0        dt   |\n    G(0,0) = 0.5*sqr(dt);\n    G(1,0) = dt;\n    G(2,1) = 0.5*sqr(dt);\n    G(3,1) = dt;\n}\n\n\nvoid CVModel::updateJacobian(const FM::Vec& x) {\n    //      | 1  dt 0  0 |\n    // Fx = | 0  1  0  0 |\n    //      | 0  0  1  dt|\n    //      | 0  0  0  1 |\n    Fx(0,1) = dt;\n    Fx(2,3) = dt;\n}\n\n\nconst Vec& CVModel::fw(const FM::Vec& x) const\n/*\n   * Definition of sampler for additive noise model given state x\n   *  Generate Gaussian correlated samples\n   * Precond: init_GqG, automatic on first use\n   */\n{\n    if (first_init)\n        init_GqG();\n    // Predict state using supplied functional predict model\n    xp = f(x);\n    // Additive random noise\n    CVModel::genn.normal(n);            // independant zero mean normal\n    // multiply elements by std dev\n    for (FM::DenseVec::iterator ni = n.begin(); ni != n.end(); ++ni) {\n        *ni *= rootq[ni.index()];\n    }\n    FM::noalias(xp) += FM::prod(this->G,n);         // add correlated noise\n    return xp;\n}\n\n\nvoid CVModel::init_GqG() const\n/* initialise predict given a change to q,G\n   *  Implementation: Update rootq\n   */\n{\n    first_init = false;\n    for (FM::Vec::const_iterator qi = this->q.begin(); qi != this->q.end(); ++qi) {\n        if (*qi < 0)\n            error (Numeric_exception(\"Negative q in init_GqG\"));\n        rootq[qi.index()] = std::sqrt(*qi);\n    }\n}\n\n\n\n//*************************************************************************\n//                  2D CARTESIAN SUBTRACTION OBSERVATION MODEL\n//*************************************************************************\n\nCartesianModel::CartesianModel(Float xSD, Float ySD) :\n        Linrz_correlated_observe_model(x_size, z_size),\n        Likelihood_observe_model(z_size),\n        z_pred(z_size),\n        li(z_size)\n{\n    // Hx = | 1  0  0  0 |\n    //      | 0  0  1  0 |\n    Hx.clear();\n    Hx(0,0) = 1.;\n    Hx(1,2) = 1.;\n    // noise\n    Z.clear();\n    Z(0,0) = sqr(xSD);\n    Z(1,1) = sqr(ySD);\n}\n\nBayes_base::Float\nCartesianModel::Likelihood_correlated::L(const Correlated_additive_observe_model& model, const FM::Vec& z, const FM::Vec& zp) const\n/*\n * Definition of likelihood given an additive Gaussian observation model:\n *  p(z|x) = exp(-0.5*(z-h(x))'*inv(Z)*(z-h(x))) / sqrt(2pi^nz*det(Z));\n *  L(x) the the Likelihood L(x) doesn't depend on / sqrt(2pi^nz) for constant z size\n * Precond: Observation Information: z,Z_inv,detZterm\n */\n{\n    if (!zset)\n        Bayes_base::error (Logic_exception (\"BGSubModel used without Lz set\"));\n    // Normalised innovation\n    zInnov = z;\n    model.normalise (zInnov, zp);\n    FM::noalias(zInnov) -= zp;\n\n    Float logL = scaled_vector_square(zInnov, Z_inv);\n    using namespace std;\n    return exp(Float(-0.5)*(logL + z.size()*log(2*M_PI) + logdetZ));   // normalized likelihood\n}\n\n\nvoid CartesianModel::Likelihood_correlated::Lz (const Correlated_additive_observe_model& model)\n/* Set the observation zz and Z about which to evaluate the Likelihood function\n * Postcond: Observation Information: z,Z_inv,detZterm\n */\n{\n    zset = true;\n    // Compute inverse of Z and its reciprocal condition number\n    Float detZ;\n    Float rcond = FM::UdUinversePD (Z_inv, detZ, model.Z);\n    model.rclimit.check_PD(rcond, \"Z not PD in observe\");\n    // detZ > 0 as Z PD\n    using namespace std;\n    logdetZ = log(detZ);\n}\n\n\nBayes_base::Float\nCartesianModel::Likelihood_correlated::scaled_vector_square(const FM::Vec& v, const FM::SymMatrix& V)\n/*\n * Compute covariance scaled square inner product of a Vector: v'*V*v\n */\n{\n    return FM::inner_prod(v, FM::prod(V,v));\n}\n\n\nconst FM::Vec& CartesianModel::h(const FM::Vec& x) const\n{\n    z_pred[0] = x[0];\n    z_pred[1] = x[2];\n    return z_pred;\n};\n\n\nvoid CartesianModel::updateJacobian(const FM::Vec& x) {\n    // nothing to do\n}\n\n\nvoid CartesianModel::normalise(FM::Vec& z_denorm, const FM::Vec& z_from) const {\n}\n\n//*************************************************************************\n//                      CV 3D PREDICTION MODEL\n//*************************************************************************\n\nCVModel3D::CVModel3D(Float wxSD, Float wySD, Float wzSD) :\n        Linrz_predict_model(x_size, q_size),\n        Sampled_predict_model(),\n        fx(x_size),\n        genn(rnd),\n        xp(x_size),\n        n(q_size), rootq(q_size),\n        m_wxSD(wxSD), m_wySD(wySD),m_wzSD(wzSD)\n{\n    first_init = true;\n    init();\n}\n\n\nvoid CVModel3D::init()\n{\n    Fx.clear();\n    // x\n    Fx(0,0) = 1.;\n    Fx(0,1) = dt;\n    Fx(0,2) = 0.;\n    Fx(0,3) = 0.;\n    Fx(0,4) = 0.;\n    Fx(0,5) = 0.;\n    // dx\n    Fx(1,0) = 0.;\n    Fx(1,1) = 1.;\n    Fx(1,2) = 0.;\n    Fx(1,3) = 0.;\n    Fx(1,4) = 0.;\n    Fx(1,5) = 0.;\n    // y\n    Fx(2,0) = 0.;\n    Fx(2,1) = 0.;\n    Fx(2,2) = 1.;\n    Fx(2,3) = dt;\n    Fx(2,4) = 0.;\n    Fx(2,5) = 0.;\n    // dy\n    Fx(3,0) = 0.;\n    Fx(3,1) = 0.;\n    Fx(3,2) = 0.;\n    Fx(3,3) = 1.;\n    Fx(3,4) = 0.;\n    Fx(3,5) = 0.;\n    // z\n    Fx(4,0) = 0.;\n    Fx(4,1) = 0.;\n    Fx(4,2) = 0.;\n    Fx(4,3) = 0.;\n    Fx(4,4) = 1.;\n    Fx(4,5) = dt;\n    // dz\n    Fx(5,0) = 0.;\n    Fx(5,1) = 0.;\n    Fx(5,2) = 0.;\n    Fx(5,3) = 0.;\n    Fx(5,4) = 0.;\n    Fx(5,5) = 1.;\n\n    // noise\n    q[0] = sqr(m_wxSD); // cov(w_x)\n    q[1] = sqr(m_wySD); // cov(w_y)\n    q[2] = sqr(m_wzSD); // cov(w_z)\n    G.clear();\n    G(0,0) = 0.5*sqr(dt);\n    G(1,0) = dt;\n    G(2,1) = 0.5*sqr(dt);\n    G(3,1) = dt;\n    G(4,2) = 0.5*sqr(dt);\n    G(5,2) = dt;\n}\n\nconst FM::Vec& CVModel3D::f(const FM::Vec& x) const\n{  // human model\n    fx[0] = x[0] + x[1] * dt;  // x\n    fx[1] = x[1];              // dx\n    fx[2] = x[2] + x[3] * dt;  // y\n    fx[3] = x[3];              // dy\n    fx[4] = x[4] + x[5] * dt;  // z\n    fx[5] = x[5];              // dz\n    return fx;\n}\n\n\nvoid CVModel3D::update(double dt)\n{\n    // time interval\n    this->dt = dt;\n\n    //     | 0.5dt^2     0        0    |\n    //     |    dt       0        0    |\n    //     |    0     0.5dt^2     0    |\n    // G = |    0        dt       0    |\n    //     |    0        0     0.5dt^2 |\n    //     |    0        0         dt  |\n    G(0,0) = 0.5*sqr(dt);\n    G(1,0) = dt;\n    G(2,1) = 0.5*sqr(dt);\n    G(3,1) = dt;\n    G(4,2) = 0.5*sqr(dt);\n    G(5,2) = dt;\n}\n\n\nvoid CVModel3D::updateJacobian(const FM::Vec& x) {\n    //      | 1  dt 0  0  0  0 |\n    // Fx = | 0  1  0  0  0  0 |\n    //      | 0  0  1  dt 0  0 |\n    //      | 0  0  0  1  0  0 |\n    //      | 0  0  0  0  1  dt|\n    //      | 0  0  0  0  0  1 |\n    Fx(0,1) = dt;\n    Fx(2,3) = dt;\n    Fx(4,5) = dt;\n}\n\n\nconst Vec& CVModel3D::fw(const FM::Vec& x) const\n/*\n   * Definition of sampler for additive noise model given state x\n   *  Generate Gaussian correlated samples\n   * Precond: init_GqG, automatic on first use\n   */\n{\n    if (first_init)\n        init_GqG();\n    // Predict state using supplied functional predict model\n    xp = f(x);\n    // Additive random noise\n    CVModel3D::genn.normal(n);            // independent zero mean normal\n    // multiply elements by std dev\n    for (FM::DenseVec::iterator ni = n.begin(); ni != n.end(); ++ni) {\n        *ni *= rootq[ni.index()];\n    }\n    FM::noalias(xp) += FM::prod(this->G,n);         // add correlated noise\n    return xp;\n}\n\n\nvoid CVModel3D::init_GqG() const\n/* initialise predict given a change to q,G\n   *  Implementation: Update rootq\n   */\n{\n    first_init = false;\n    for (FM::Vec::const_iterator qi = this->q.begin(); qi != this->q.end(); ++qi) {\n        if (*qi < 0)\n            error (Numeric_exception(\"Negative q in init_GqG\"));\n        rootq[qi.index()] = std::sqrt(*qi);\n    }\n}\n\n\n//*************************************************************************\n//                      STATIC 3D PREDICTION MODEL\n//*************************************************************************\n\nStaticModel3D::StaticModel3D() :\n        CVModel3D(0., 0., 0.),\n        fx(x_size)\n//        genn(rnd),\n//        xp(x_size)\n//        n(q_size), rootq(q_size)\n//        m_wxSD(wxSD), m_wySD(wySD),m_wzSD(wzSD)\n{\n//    first_init = true;\n    init();\n}\n\n\nvoid StaticModel3D::init()\n{\n    //      | 1  0  0  0  0  0 | x\n    // Fx = | 0  0  0  0  0  0 | vx\n    //      | 0  0  1  0  0  0 | y\n    //      | 0  0  0  0  0  0 | vy\n    //      | 0  0  0  0  1  0 | z\n    //      | 0  0  0  0  0  0 | vz\n\n    Fx.clear();\n\n    Fx(0,0) = 1.;\n    Fx(2,2) = 1.;\n    Fx(4,4) = 1.;\n\n    q.clear();\n//    q[0] = 0.; // cov(w_x)\n//    q[1] = 0.; // cov(w_y)\n//    q[2] = 0.; // cov(w_z)\n    G.clear(); // G = zero matrix\n\n}\n\nconst FM::Vec& StaticModel3D::f(const FM::Vec& x) const\n{  // static object model\n    fx[0] = x[0];  // x\n    fx[1] = 0;     // dx\n    fx[2] = x[2];  // y\n    fx[3] = 0;     // dy\n    fx[4] = x[4];  // z\n    fx[5] = 0;     // dz\n    return fx;\n}\n\n\nvoid StaticModel3D::update(double dt)\n{\n    // time interval\n    this->dt = dt;\n//  G = zero matrix (no noise in static state)\n}\n\n\nvoid StaticModel3D::updateJacobian(const FM::Vec& x) {\n    //      | 1  0  0  0  0  0 | x\n    // Fx = | 0  0  0  0  0  0 | vx\n    //      | 0  0  1  0  0  0 | y\n    //      | 0  0  0  0  0  0 | vy\n    //      | 0  0  0  0  1  0 | z\n    //      | 0  0  0  0  0  0 | vz\n    // No need to update the Jacobian since the function is linear and independent from state\n}\n\n\nconst Vec& StaticModel3D::fw(const FM::Vec& x) const\n/*\n   * Definition of sampler for additive noise model given state x\n   */\n{\n    return f(x);\n}\n\n//*************************************************************************\n//                 3D  CARTESIAN SUBTRACTION OBSERVATION MODEL\n//*************************************************************************\n\nCartesianModel3D::CartesianModel3D(Float xSD, Float ySD, Float zSD) :\n        Linrz_correlated_observe_model(x_size, z_size),\n        Likelihood_observe_model(z_size),\n        z_pred(z_size),\n        li(z_size)\n{\n    // Hx = | 1  0  0  0  0  0 |\n    //      | 0  0  1  0  0  0 |\n    //      | 0  0  0  0  1  0 |\n    Hx.clear();\n    Hx(0,0) = 1.;\n    Hx(1,2) = 1.;\n    Hx(2,4) = 1.;\n    // noise\n    Z.clear();\n    Z(0,0) = sqr(xSD);\n    Z(1,1) = sqr(ySD);\n    Z(2,2) = sqr(zSD);\n}\n\nBayes_base::Float\nCartesianModel3D::Likelihood_correlated::L(const Correlated_additive_observe_model& model, const FM::Vec& z, const FM::Vec& zp) const\n/*\n * Definition of likelihood given an additive Gaussian observation model:\n *  p(z|x) = exp(-0.5*(z-h(x))'*inv(Z)*(z-h(x))) / sqrt(2pi^nz*det(Z));\n *  L(x) the the Likelihood L(x) doesn't depend on / sqrt(2pi^nz) for constant z size\n * Precond: Observation Information: z,Z_inv,detZterm\n */\n{\n    if (!zset)\n        Bayes_base::error (Logic_exception (\"BGSubModel used without Lz set\"));\n    // Normalised innovation\n    zInnov = z;\n    model.normalise (zInnov, zp);\n    FM::noalias(zInnov) -= zp;\n\n    Float logL = scaled_vector_square(zInnov, Z_inv);\n    using namespace std;\n    return exp(Float(-0.5)*(logL + z.size()*log(2*M_PI) + logdetZ));   // normalized likelihood\n}\n\n\nvoid CartesianModel3D::Likelihood_correlated::Lz (const Correlated_additive_observe_model& model)\n/* Set the observation zz and Z about which to evaluate the Likelihood function\n * Postcond: Observation Information: z,Z_inv,detZterm\n */\n{\n    zset = true;\n    // Compute inverse of Z and its reciprocal condition number\n    Float detZ;\n    Float rcond = FM::UdUinversePD (Z_inv, detZ, model.Z);\n    model.rclimit.check_PD(rcond, \"Z not PD in observe\");\n    // detZ > 0 as Z PD\n    using namespace std;\n    logdetZ = log(detZ);\n}\n\n\nBayes_base::Float\nCartesianModel3D::Likelihood_correlated::scaled_vector_square(const FM::Vec& v, const FM::SymMatrix& V)\n/*\n * Compute covariance scaled square inner product of a Vector: v'*V*v\n */\n{\n    return FM::inner_prod(v, FM::prod(V,v));\n}\n\n\nconst FM::Vec& CartesianModel3D::h(const FM::Vec& x) const\n{\n    z_pred[0] = x[0];\n    z_pred[1] = x[2];\n    z_pred[2] = x[4];\n    return z_pred;\n};\n\n\nvoid CartesianModel3D::updateJacobian(const FM::Vec& x) {\n    // nothing to do\n}\n\n\nvoid CartesianModel3D::normalise(FM::Vec& z_denorm, const FM::Vec& z_from) const {\n}\n", "meta": {"hexsha": "b86971ee35766e58fab5b47e813073ca0b513959", "size": 15045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/models.cpp", "max_stars_repo_name": "socrob/bayes_objects_tracker", "max_stars_repo_head_hexsha": "1373ac19ae5a19d0f077e703ef7a1340a82b7225", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models.cpp", "max_issues_repo_name": "socrob/bayes_objects_tracker", "max_issues_repo_head_hexsha": "1373ac19ae5a19d0f077e703ef7a1340a82b7225", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models.cpp", "max_forks_repo_name": "socrob/bayes_objects_tracker", "max_forks_repo_head_hexsha": "1373ac19ae5a19d0f077e703ef7a1340a82b7225", "max_forks_repo_licenses": ["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.5812720848, "max_line_length": 133, "alphanum_fraction": 0.485078099, "num_tokens": 5114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5369438240665414}}
{"text": "#include <gtest/gtest.h>\n#include <Eigen/Dense>\n\n#include <ceres/internal/eigen.h>\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n\nstruct PointToPlaneFunctor {\n\n    explicit PointToPlaneFunctor(Eigen::Vector3d *reference,\n                                 Eigen::Vector3d *target,\n                                 Eigen::Vector3d *reference_normal) : reference_(reference),\n                                                                      target_(target),\n                                                                      reference_normal_(reference_normal) {}\n\n    template<typename T>\n    bool operator()(const T *const rot_params, const T *const trans_params, T *residual) const {\n        Eigen::Map<Eigen::Quaternion<T>> quat(const_cast<T *>(rot_params));\n        Eigen::Matrix<T, 3, 1> transformed = quat * target_->template cast<T>();\n        transformed(0, 0) += trans_params[0];\n        transformed(1, 0) += trans_params[1];\n        transformed(2, 0) += trans_params[2];\n\n        residual[0] =\n                (reference_->template cast<T>() - transformed).transpose() * reference_normal_->template cast<T>();\n        return true;\n    }\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n    Eigen::Vector3d *reference_;\n    Eigen::Vector3d *target_;\n    Eigen::Vector3d *reference_normal_;\n};\n\nTEST(Ceres, ceres) {\n\n    int num_points = 10000;\n    std::vector<Eigen::Vector3d> points(num_points), transformed_points(num_points), normals(num_points);\n    Eigen::Quaterniond rot = Eigen::Quaterniond::UnitRandom();\n    Eigen::Vector3d trans = Eigen::Vector3d::Random();\n\n    Eigen::Vector3d point, normal, transformed;\n    for (auto i(0); i < num_points; ++i) {\n        point = Eigen::Vector3d::Random();\n        normal = Eigen::Vector3d::Random();\n        transformed = rot * point + trans;\n        points[i] = point;\n        normals[i] = normal;\n        transformed_points[i] = transformed;\n    }\n\n    Eigen::Quaterniond rot_init = rot.slerp(0.01, Eigen::Quaterniond::UnitRandom());\n    Eigen::Vector3d trans_init = trans + Eigen::Vector3d::Random() * 0.1;\n\n    ceres::Solver::Options options;\n    options.max_num_iterations = 10;\n    options.linear_solver_type = ceres::DENSE_QR;\n    ceres::Solver::Summary summary;\n\n    ceres::Problem problem;\n    ceres::EigenQuaternionParameterization parameterization;\n    ceres::CauchyLoss *loss = new ceres::CauchyLoss(0.1);\n\n    // Add Parameters Block\n    Eigen::Matrix<double, 4, 1> rot_coeffs = rot_init.coeffs();\n    problem.AddParameterBlock(&rot_coeffs(0, 0), 4);\n    problem.AddParameterBlock(&trans_init(0, 0), 3);\n\n    for (int i(0); i < num_points; ++i) {\n        ceres::CostFunction *cost_function =\n                new ceres::AutoDiffCostFunction<PointToPlaneFunctor, 1, 4, 3>(\n                        new PointToPlaneFunctor(&transformed_points[i], &points[i], &normals[i]));\n\n        problem.AddResidualBlock(cost_function, loss, &rot_coeffs(0, 0), &trans_init(0, 0));\n    }\n\n    // Add Residual Blocks\n    ceres::Solve(options, &problem, &summary);\n    ASSERT_TRUE(summary.IsSolutionUsable());\n\n    std::cout << summary.FullReport() << std::endl;\n\n\n}\n\n", "meta": {"hexsha": "56fd30cd5124537879ed6df02390a09a51373e79", "size": 3127, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ct_icp/test_ceres.cpp", "max_stars_repo_name": "xiang-1208/ct_icp", "max_stars_repo_head_hexsha": "42928e584c24595c49e147e2ea120f8cc31ec716", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2021-10-08T01:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:55:15.000Z", "max_issues_repo_path": "src/ct_icp/test_ceres.cpp", "max_issues_repo_name": "ZuoJiaxing/ct_icp", "max_issues_repo_head_hexsha": "1c371331aad833faec157c015fb8f72143019caa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-10-19T07:25:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T03:20:19.000Z", "max_forks_repo_path": "src/ct_icp/test_ceres.cpp", "max_forks_repo_name": "ZuoJiaxing/ct_icp", "max_forks_repo_head_hexsha": "1c371331aad833faec157c015fb8f72143019caa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2021-10-08T01:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T15:35:07.000Z", "avg_line_length": 35.5340909091, "max_line_length": 115, "alphanum_fraction": 0.6197633515, "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5369438240665413}}
{"text": "/**\n * @file feedforward_network_test.cpp\n * @author Marcus Edel\n *\n * Tests the feed forward network.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>\n#include <mlpack/methods/ann/activation_functions/tanh_function.hpp>\n\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n\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#include <mlpack/methods/ann/layer/dropout_layer.hpp>\n#include <mlpack/methods/ann/layer/binary_classification_layer.hpp>\n\n#include <mlpack/methods/ann/trainer/trainer.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/performance_functions/mse_function.hpp>\n#include <mlpack/methods/ann/optimizer/rmsprop.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\n\nBOOST_AUTO_TEST_SUITE(FeedForwardNetworkTest);\n\n/**\n * Train and evaluate a vanilla network with the specified structure.\n */\ntemplate<\n    typename PerformanceFunction,\n    typename OutputLayerType,\n    typename PerformanceFunctionType,\n    typename MatType = arma::mat\n>\nvoid BuildVanillaNetwork(MatType& trainData,\n                         MatType& trainLabels,\n                         MatType& testData,\n                         MatType& testLabels,\n                         const size_t hiddenLayerSize,\n                         const size_t maxEpochs,\n                         const double classificationErrorThreshold,\n                         const double ValidationErrorThreshold)\n{\n  /*\n   * Construct a feed forward network with trainData.n_rows input nodes,\n   * hiddenLayerSize hidden nodes and trainLabels.n_rows output nodes. The\n   * network structure looks like:\n   *\n   *  Input         Hidden        Output\n   *  Layer         Layer         Layer\n   * +-----+       +-----+       +-----+\n   * |     |       |     |       |     |\n   * |     +------>|     +------>|     |\n   * |     |     +>|     |     +>|     |\n   * +-----+     | +--+--+     | +-----+\n   *             |             |\n   *  Bias       |  Bias       |\n   *  Layer      |  Layer      |\n   * +-----+     | +-----+     |\n   * |     |     | |     |     |\n   * |     +-----+ |     +-----+\n   * |     |       |     |\n   * +-----+       +-----+\n   */\n\n  LinearLayer<> inputLayer(trainData.n_rows, hiddenLayerSize);\n  BiasLayer<> inputBiasLayer(hiddenLayerSize);\n  BaseLayer<PerformanceFunction> inputBaseLayer;\n\n  LinearLayer<> hiddenLayer1(hiddenLayerSize, trainLabels.n_rows);\n  BiasLayer<> hiddenBiasLayer1(trainLabels.n_rows);\n  BaseLayer<PerformanceFunction> outputLayer;\n\n  OutputLayerType classOutputLayer;\n\n  auto modules = std::tie(inputLayer, inputBiasLayer, inputBaseLayer,\n  \t\t\t\t\t\t  hiddenLayer1, hiddenBiasLayer1, outputLayer);\n\n  FFN<decltype(modules), decltype(classOutputLayer), PerformanceFunctionType>\n      net(modules, classOutputLayer);\n\n  Trainer<decltype(net)> trainer(net, maxEpochs, 1, 0.01);\n  trainer.Train(trainData, trainLabels, testData, testLabels);\n\n  MatType prediction;\n  size_t error = 0;\n\n  for (size_t i = 0; i < testData.n_cols; i++)\n  {\n  \tMatType predictionInput = testData.unsafe_col(i);\n  \tMatType targetOutput = testLabels.unsafe_col(i);\n\n    net.Predict(predictionInput, prediction);\n\n    if (arma::sum(arma::sum(arma::abs(prediction - targetOutput))) == 0)\n      error++;\n  }\n\n  double classificationError = 1 - double(error) / testData.n_cols;\n\n  BOOST_REQUIRE_LE(classificationError, classificationErrorThreshold);\n  BOOST_REQUIRE_LE(trainer.ValidationError(), ValidationErrorThreshold);\n}\n\n/**\n * Train the vanilla network on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(VanillaNetworkTest)\n{\n  // Load the dataset.\n  arma::mat dataset;\n  data::Load(\"thyroid_train.csv\", dataset, true);\n\n  arma::mat trainData = dataset.submat(0, 0, dataset.n_rows - 4,\n      dataset.n_cols - 1);\n  arma::mat trainLabels = dataset.submat(dataset.n_rows - 3, 0,\n      dataset.n_rows - 1, dataset.n_cols - 1);\n\n  data::Load(\"thyroid_test.csv\", dataset, true);\n\n  arma::mat testData = dataset.submat(0, 0, dataset.n_rows - 4,\n      dataset.n_cols - 1);\n  arma::mat testLabels = dataset.submat(dataset.n_rows - 3, 0,\n      dataset.n_rows - 1, dataset.n_cols - 1);\n\n  // Vanilla neural net with logistic activation function.\n  // Because 92 percent of the patients are not hyperthyroid the neural\n  // network must be significant better than 92%.\n  BuildVanillaNetwork<LogisticFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n      (trainData, trainLabels, testData, testLabels, 4, 500, 0.1, 60);\n\n  dataset.load(\"mnist_first250_training_4s_and_9s.arm\");\n\n  // Normalize each point since these are images.\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n    dataset.col(i) /= norm(dataset.col(i), 2);\n\n  arma::mat labels = arma::zeros(1, dataset.n_cols);\n  labels.submat(0, labels.n_cols / 2, 0, labels.n_cols - 1).fill(1);\n\n  // Vanilla neural net with logistic activation function.\n  BuildVanillaNetwork<LogisticFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n      (dataset, labels, dataset, labels, 30, 100, 0.6, 10);\n\n  // Vanilla neural net with tanh activation function.\n  BuildVanillaNetwork<TanhFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n    (dataset, labels, dataset, labels, 10, 200, 0.6, 20);\n}\n\n/**\n * Train and evaluate a Dropout network with the specified structure.\n */\ntemplate<\n    typename PerformanceFunction,\n    typename OutputLayerType,\n    typename PerformanceFunctionType,\n    typename MatType = arma::mat\n>\nvoid BuildDropoutNetwork(MatType& trainData,\n                         MatType& trainLabels,\n                         MatType& testData,\n                         MatType& testLabels,\n                         const size_t hiddenLayerSize,\n                         const size_t maxEpochs,\n                         const double classificationErrorThreshold,\n                         const double ValidationErrorThreshold)\n{\n  /*\n   * Construct a feed forward network with trainData.n_rows input nodes,\n   * hiddenLayerSize hidden nodes and trainLabels.n_rows output nodes. The\n   * network structure looks like:\n   *\n   *  Input         Hidden        Dropout      Output\n   *  Layer         Layer         Layer        Layer\n   * +-----+       +-----+       +-----+       +-----+\n   * |     |       |     |       |     |       |     |\n   * |     +------>|     +------>|     +------>|     |\n   * |     |     +>|     |       |     |       |     |\n   * +-----+     | +--+--+       +-----+       +-----+\n   *             |\n   *  Bias       |\n   *  Layer      |\n   * +-----+     |\n   * |     |     |\n   * |     +-----+\n   * |     |\n   * +-----+\n   */\n\n  LinearLayer<> inputLayer(trainData.n_rows, hiddenLayerSize);\n  BiasLayer<> biasLayer(hiddenLayerSize);\n  BaseLayer<PerformanceFunction> hiddenLayer0;\n  DropoutLayer<> dropoutLayer0;\n\n  LinearLayer<> hiddenLayer1(hiddenLayerSize, trainLabels.n_rows);\n  BaseLayer<PerformanceFunction> outputLayer;\n\n  OutputLayerType classOutputLayer;\n\n  auto modules = std::tie(inputLayer, biasLayer, hiddenLayer0, dropoutLayer0,\n      \t\t\t\t\t  hiddenLayer1, outputLayer);\n\n  FFN<decltype(modules), decltype(classOutputLayer), PerformanceFunctionType>\n      net(modules, classOutputLayer);\n\n  Trainer<decltype(net)> trainer(net, maxEpochs, 1, 0.001);\n  trainer.Train(trainData, trainLabels, testData, testLabels);\n\n  MatType prediction;\n  size_t error = 0;\n\n  for (size_t i = 0; i < testData.n_cols; i++)\n  {\n  \tMatType input = testData.unsafe_col(i);\n    net.Predict(input, prediction);\n    if (arma::sum(arma::sum(arma::abs(\n    \tprediction - testLabels.unsafe_col(i)))) == 0)\n      error++;\n  }\n\n  double classificationError = 1 - double(error) / testData.n_cols;\n\n  BOOST_REQUIRE_LE(classificationError, classificationErrorThreshold);\n  BOOST_REQUIRE_LE(trainer.ValidationError(), ValidationErrorThreshold);\n}\n\n/**\n * Train the dropout network on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(DropoutNetworkTest)\n{\n  // Load the dataset.\n  arma::mat dataset;\n  data::Load(\"thyroid_train.csv\", dataset, true);\n\n  arma::mat trainData = dataset.submat(0, 0, dataset.n_rows - 4,\n      dataset.n_cols - 1);\n  arma::mat trainLabels = dataset.submat(dataset.n_rows - 3, 0,\n      dataset.n_rows - 1, dataset.n_cols - 1);\n\n  data::Load(\"thyroid_test.csv\", dataset, true);\n\n  arma::mat testData = dataset.submat(0, 0, dataset.n_rows - 4,\n      dataset.n_cols - 1);\n  arma::mat testLabels = dataset.submat(dataset.n_rows - 3, 0,\n      dataset.n_rows - 1, dataset.n_cols - 1);\n\n  // Vanilla neural net with logistic activation function.\n  // Because 92 percent of the patients are not hyperthyroid the neural\n  // network must be significant better than 92%.\n  BuildDropoutNetwork<LogisticFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n      (trainData, trainLabels, testData, testLabels, 4, 100, 0.1, 60);\n\n  dataset.load(\"mnist_first250_training_4s_and_9s.arm\");\n\n  // Normalize each point since these are images.\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n    dataset.col(i) /= norm(dataset.col(i), 2);\n\n  arma::mat labels = arma::zeros(1, dataset.n_cols);\n  labels.submat(0, labels.n_cols / 2, 0, labels.n_cols - 1).fill(1);\n\n  // Vanilla neural net with logistic activation function.\n  BuildVanillaNetwork<LogisticFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n      (dataset, labels, dataset, labels, 8, 100, 0.6, 10);\n\n  // Vanilla neural net with tanh activation function.\n  BuildVanillaNetwork<TanhFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n    (dataset, labels, dataset, labels, 8, 100, 0.6, 20);\n}\n\n/**\n * Train the network until the validation error converge.\n */\nBOOST_AUTO_TEST_CASE(VanillaNetworkConvergenceTest)\n{\n  arma::mat input;\n  arma::mat labels;\n\n  // Test on a non-linearly separable dataset (XOR).\n  input << 0 << 1 << 1 << 0 << arma::endr\n        << 1 << 0 << 1 << 0 << arma::endr;\n  labels << 0 << 0 << 1 << 1;\n\n  // Vanilla neural net with logistic activation function.\n  BuildVanillaNetwork<LogisticFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n      (input, labels, input, labels, 4, 5000, 0, 0.01);\n\n  // Vanilla neural net with tanh activation function.\n  BuildVanillaNetwork<TanhFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n      (input, labels, input, labels, 4, 5000, 0, 0.01);\n\n  // Test on a linearly separable dataset (AND).\n  input << 0 << 1 << 1 << 0 << arma::endr\n        << 1 << 0 << 1 << 0 << arma::endr;\n  labels << 0 << 0 << 1 << 0;\n\n  // vanilla neural net with sigmoid activation function.\n  BuildVanillaNetwork<LogisticFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n    (input, labels, input, labels, 4, 5000, 0, 0.01);\n\n  // Vanilla neural net with tanh activation function.\n  BuildVanillaNetwork<TanhFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n      (input, labels, input, labels, 4, 5000, 0, 0.01);\n}\n\n/**\n * Train a vanilla network with the specified structure step by step and\n * evaluate the network.\n */\ntemplate<\n    typename PerformanceFunction,\n    typename OutputLayerType,\n    typename PerformanceFunctionType,\n    typename MatType = arma::mat\n>\nvoid BuildNetworkOptimzer(MatType& trainData,\n                          MatType& trainLabels,\n                          MatType& testData,\n                          MatType& testLabels,\n                          size_t hiddenLayerSize,\n                          size_t epochs)\n{\n  /*\n   * Construct a feed forward network with trainData.n_rows input nodes,\n   * hiddenLayerSize hidden nodes and trainLabels.n_rows output nodes. The\n   * network structure looks like:\n   *\n   *  Input         Hidden        Output\n   *  Layer         Layer         Layer\n   * +-----+       +-----+       +-----+\n   * |     |       |     |       |     |\n   * |     +------>|     +------>|     |\n   * |     |     +>|     |     +>|     |\n   * +-----+     | +--+--+     | +-----+\n   *             |             |\n   *  Bias       |  Bias       |\n   *  Layer      |  Layer      |\n   * +-----+     | +-----+     |\n   * |     |     | |     |     |\n   * |     +-----+ |     +-----+\n   * |     |       |     |\n   * +-----+       +-----+\n   */\n\n  RandomInitialization randInit(0.5, 0.5);\n\n  LinearLayer<RMSPROP, RandomInitialization> inputLayer(trainData.n_rows,\n      hiddenLayerSize, randInit);\n  BiasLayer<RMSPROP, RandomInitialization> inputBiasLayer(hiddenLayerSize,\n      1, randInit);\n  BaseLayer<PerformanceFunction> inputBaseLayer;\n\n  LinearLayer<RMSPROP, RandomInitialization> hiddenLayer1(hiddenLayerSize,\n      trainLabels.n_rows, randInit);\n  BiasLayer<RMSPROP, RandomInitialization> hiddenBiasLayer1(trainLabels.n_rows,\n      1, randInit);\n  BaseLayer<PerformanceFunction> outputLayer;\n\n  OutputLayerType classOutputLayer;\n\n  auto modules = std::tie(inputLayer, inputBiasLayer, inputBaseLayer,\n  \t\t\t\t\t\t  hiddenLayer1, hiddenBiasLayer1, outputLayer);\n\n  FFN<decltype(modules), OutputLayerType, PerformanceFunctionType>\n      net(modules, classOutputLayer);\n\n  Trainer<decltype(net)> trainer(net, epochs, 1, 0.0001, false);\n\n  double error = DBL_MAX;\n  for (size_t i = 0; i < 5; i++)\n  {\n    trainer.Train(trainData, trainLabels, testData, testLabels);\n    double validationError = trainer.ValidationError();\n\n    bool b = validationError < error || validationError == 0;\n    BOOST_REQUIRE_EQUAL(b, 1);\n\n    error = validationError;\n  }\n}\n\n/**\n * Train the network with different optimzer and check if the error decreases\n * over time.\n */\nBOOST_AUTO_TEST_CASE(NetworkDecreasingErrorTest)\n{\n  arma::mat dataset;\n  dataset.load(\"mnist_first250_training_4s_and_9s.arm\");\n\n  // Normalize each point since these are images.\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n    dataset.col(i) /= norm(dataset.col(i), 2);\n\n  arma::mat labels = arma::zeros(1, dataset.n_cols);\n  labels.submat(0, labels.n_cols / 2, 0, labels.n_cols - 1) += 1;\n\n  // Vanilla neural net with logistic activation function.\n  BuildNetworkOptimzer<LogisticFunction,\n                       BinaryClassificationLayer,\n                       MeanSquaredErrorFunction>\n      (dataset, labels, dataset, labels, 20, 15);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "f8b964e9a889b9b5c18234ea672f2185b1d2a658", "size": 14724, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/feedforward_network_test.cpp", "max_stars_repo_name": "vj-ug/Contribution-to-mlpack", "max_stars_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "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/mlpack/tests/feedforward_network_test.cpp", "max_issues_repo_name": "vj-ug/Contribution-to-mlpack", "max_issues_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/feedforward_network_test.cpp", "max_forks_repo_name": "vj-ug/Contribution-to-mlpack", "max_forks_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "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.8482758621, "max_line_length": 79, "alphanum_fraction": 0.6198723173, "num_tokens": 3685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5369438238247792}}
{"text": "//==================================================================================================\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_ARCH_COMMON_SCALAR_FUNCTION_EPS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_EPS_HPP_INCLUDED\n\n#include <boost/simd/constant/mindenormal.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/nbmantissabits.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/bitwise_cast.hpp>\n#include <boost/simd/function/exponent.hpp>\n#include <boost/simd/function/is_invalid.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( eps_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::integer_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator()( A0 ) const BOOST_NOEXCEPT\n    {\n      return static_cast<A0>(1);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( eps_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    A0 operator()(A0 a0) const BOOST_NOEXCEPT\n    {\n      using lim = std::numeric_limits<A0>;\n\n      const A0 a = bs::abs(a0);\n\n            if (is_invalid(a))  return Nan<A0>();\n      else  if (a < lim::min()) return Mindenormal<A0>();\n      else\n      {\n        using i_t = bd::as_integer_t<A0, unsigned>;\n\n        i_t e1 = exponent(a)-lim::digits+1;\n        return bitwise_cast<A0>(bitwise_cast<i_t>(A0(1))+(e1 << Nbmantissabits<A0>()));\n      }\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "0ff1df340271d8cd9ce04d57355780627ec5e019", "size": 2086, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/eps.hpp", "max_stars_repo_name": "timblechmann/boost.simd", "max_stars_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_stars_repo_licenses": ["BSL-1.0"], "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": "include/boost/simd/arch/common/scalar/function/eps.hpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "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/arch/common/scalar/function/eps.hpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "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": 31.1343283582, "max_line_length": 100, "alphanum_fraction": 0.5536912752, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5369438127799111}}
{"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_ASINPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASINPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing asinpi capabilities\n\n    inverse sine in \\f$\\pi\\f$ multiples.\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = asinpi(x);\n    @endcode\n\n    Returns the arc @c r in the interval\n    \\f$[-0.5, 0.5[\\f$ such that <tt>cos(r) == x</tt>.\n    If @c x is outside \\f$[-1, 1[\\f$ the result is Nan.\n\n  **/\n  const boost::dispatch::functor<tag::asinpi_> asinpi = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/asinpi.hpp>\n#include <boost/simd/function/simd/asinpi.hpp>\n\n#endif\n", "meta": {"hexsha": "de8af6e3a00f030fb2b070fbe5dc0a1f53633557", "size": 1160, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/asinpi.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/asinpi.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/asinpi.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.2173913043, "max_line_length": 100, "alphanum_fraction": 0.574137931, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5369113704633682}}
{"text": "/**\n *  .file test/oglplus/angle.cpp\n *  .brief Test case for Angle class and related functionality.\n *\n *  .author Matus Chochlik\n *\n *  Copyright 2011-2015 Matus Chochlik. 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#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE OGLPLUS_Angle\n#include <boost/test/unit_test.hpp>\n\n#include <oglplus/gl.hpp>\n#include <oglplus/math/angle.hpp>\n\nBOOST_AUTO_TEST_SUITE(Angle)\n\nBOOST_AUTO_TEST_CASE(Angle_default_construction)\n{\n\toglplus::Angle<float> af;\n\toglplus::Angle<double> ad;\n}\n\nBOOST_AUTO_TEST_CASE(Angle_construction)\n{\n\ttypedef oglplus::Angle<float> Anglef;\n\tAnglef a1 = Anglef::Degrees(90);\n\tAnglef a2 = Anglef::Radians(oglplus::math::HalfPi());\n\tAnglef a3 = oglplus::Degrees(90);\n\tAnglef a4 = oglplus::Radians(oglplus::math::HalfPi());\n\tAnglef a5 = oglplus::RightAngles(1.0f);\n\tAnglef a6 = oglplus::FullCircles(1.0f);\n\tAnglef a7 = a6;\n}\n\nBOOST_AUTO_TEST_CASE(Angle_value)\n{\n\ttypedef oglplus::Angle<float> Anglef;\n\n\tAnglef a1 = Anglef::Radians(oglplus::math::HalfPi());\n\tAnglef a2 = Anglef::Radians(oglplus::math::Pi());\n\tAnglef a3 = Anglef::Radians(oglplus::math::TwoPi());\n\n\tBOOST_CHECK_EQUAL(a1.ValueInDegrees(), 90);\n\tBOOST_CHECK_EQUAL(a2.ValueInDegrees(), 180);\n\tBOOST_CHECK_EQUAL(a3.ValueInDegrees(), 360);\n\tBOOST_CHECK_EQUAL(a1.Value(), float(oglplus::math::HalfPi()));\n\tBOOST_CHECK_EQUAL(a2.Value(), float(oglplus::math::Pi()));\n\tBOOST_CHECK_EQUAL(a3.Value(), float(oglplus::math::TwoPi()));\n\n\tAnglef a4 = oglplus::RightAngles(1.0f);\n\tAnglef a5 = oglplus::FullCircles(1.0f);\n\n\tBOOST_CHECK_EQUAL(a1.ValueInDegrees(), a4.ValueInDegrees());\n\tBOOST_CHECK_EQUAL(a3.ValueInDegrees(), a5.ValueInDegrees());\n}\n\nBOOST_AUTO_TEST_CASE(Angle_cmp)\n{\n\ttypedef oglplus::Angle<float> Anglef;\n\n\tAnglef a1 = Anglef::Radians(oglplus::math::HalfPi());\n\tAnglef a2 = Anglef::Radians(oglplus::math::TwoPi());\n\n\tAnglef a3 = oglplus::RightAngles(1.0f);\n\tAnglef a4 = oglplus::FullCircles(1.0f);\n\n\tBOOST_CHECK(a1 == a1);\n\tBOOST_CHECK(a2 == a2);\n\n\tBOOST_CHECK(a1 != a2);\n\tBOOST_CHECK(a3 != a4);\n\n\tBOOST_CHECK(a1 == a3);\n\tBOOST_CHECK(a2 == a4);\n}\n\nBOOST_AUTO_TEST_CASE(Angle_addition)\n{\n\ttypedef oglplus::Angle<double> Angled;\n\n\tAngled a0;\n\tAngled a1 = Angled::Radians(oglplus::math::HalfPi());\n\tAngled a2 = Angled::Radians(oglplus::math::Pi());\n\tAngled a3 = Angled::Radians(oglplus::math::TwoPi());\n\n\tBOOST_CHECK((a0+a0) == a0);\n\tBOOST_CHECK((a0+a1) == a1);\n\tBOOST_CHECK((a1+a1) == a2);\n\tBOOST_CHECK((a2+a2) == a3);\n\tBOOST_CHECK((a1+a2+a1) == a3);\n\tBOOST_CHECK((a1+a1+a1+a1) == a3);\n}\n\nBOOST_AUTO_TEST_CASE(Angle_subtraction)\n{\n\ttypedef oglplus::Angle<double> Angled;\n\n\tAngled a0;\n\tAngled a1 = Angled::Radians(oglplus::math::HalfPi());\n\tAngled a2 = Angled::Radians(oglplus::math::Pi());\n\tAngled a3 = Angled::Radians(oglplus::math::TwoPi());\n\n\tBOOST_CHECK((a0-a0) == a0);\n\tBOOST_CHECK((a1-a1) == a0);\n\tBOOST_CHECK((a1-a0) == a1);\n\tBOOST_CHECK((a0-a1) ==-a1);\n\tBOOST_CHECK((a2-a1) == a1);\n\tBOOST_CHECK((-a1+a2) == a1);\n\tBOOST_CHECK((a3-a2-a1) == a1);\n\tBOOST_CHECK((a3-a2-a1-a1) == a0);\n\tBOOST_CHECK((-a1-a2+a3) == a1);\n\tBOOST_CHECK((-a1-a1-a1-a1) == -a3);\n\tBOOST_CHECK(-(-a1-a1-a2) == a3);\n}\n\nBOOST_AUTO_TEST_CASE(Angle_multiplication)\n{\n\ttypedef oglplus::Angle<double> Angled;\n\n\tAngled a0;\n\tAngled a1 = Angled::Radians(oglplus::math::HalfPi());\n\tAngled a2 = Angled::Radians(oglplus::math::Pi());\n\tAngled a3 = Angled::Radians(oglplus::math::TwoPi());\n\n\tBOOST_CHECK((2*a0) == a0);\n\tBOOST_CHECK((0*a1) == a0);\n\tBOOST_CHECK((2*a1) == a2);\n\tBOOST_CHECK((2*a2) == a3);\n\tBOOST_CHECK(a1 == (a2*0.5));\n\tBOOST_CHECK((4*a1) == (2*a2));\n\tBOOST_CHECK((2.1*a1) == (a1*2.1));\n\tBOOST_CHECK((3.0*a1) == (a2*1.5));\n\tBOOST_CHECK((2.4*a1) == (a2*1.2));\n\tBOOST_CHECK((4.4*a1) == (a3*1.1));\n\tBOOST_CHECK((oglplus::math::TwoPi()*a1) == (a2*oglplus::math::Pi()));\n}\n\nBOOST_AUTO_TEST_CASE(Angle_division)\n{\n\ttypedef oglplus::Angle<double> Angled;\n\n\tAngled a0;\n\tAngled a1 = Angled::Radians(oglplus::math::HalfPi());\n\tAngled a2 = Angled::Radians(oglplus::math::Pi());\n\tAngled a3 = Angled::Radians(oglplus::math::TwoPi());\n\n\tBOOST_CHECK(a0 == (a0/2));\n\tBOOST_CHECK(a1 == (a2/2));\n\tBOOST_CHECK(a2 == (a3/2));\n\tBOOST_CHECK(a1 == (a3/4));\n\tBOOST_CHECK((a1/3) == (a2/6));\n\tBOOST_CHECK((a1/3) == (a3/12));\n\tBOOST_CHECK((a1/oglplus::math::Pi()) == (a2/oglplus::math::TwoPi()));\n}\n\nBOOST_AUTO_TEST_CASE(Angle_arithmetic)\n{\n\ttypedef oglplus::Angle<double> Angled;\n\n\tAngled a0;\n\tAngled a1 = Angled::Radians(oglplus::math::HalfPi());\n\tAngled a2 = Angled::Radians(oglplus::math::Pi());\n\tAngled a3 = Angled::Radians(oglplus::math::TwoPi());\n\n\tBOOST_CHECK((a1+a1+a1) == (3.0*a2)/2.0);\n\tBOOST_CHECK((a1+a0) == (a1-a0));\n\tBOOST_CHECK(2.0*(-a1-a2+a3) == a3/2.0);\n\tBOOST_CHECK((9*a1-4*a2)*3.0+a1 == a3);\n}\n\nBOOST_AUTO_TEST_CASE(Angle_sin_cos)\n{\n\ttypedef oglplus::Angle<double> Angled;\n\n\tAngled a0;\n\tAngled a1 = Angled::Radians(oglplus::math::HalfPi());\n\tAngled a2 = Angled::Radians(oglplus::math::Pi());\n\tAngled a3 = Angled::Radians(oglplus::math::TwoPi());\n\tdouble eps = 1e-9;\n\n\tBOOST_CHECK_EQUAL(Sin(a0), 0.0);\n\tBOOST_CHECK_EQUAL(Cos(a0), 1.0);\n\n\tBOOST_CHECK_CLOSE(Sin(a1), 1.0, eps);\n\tBOOST_CHECK_CLOSE(Sin(a2)+1.0, 1.0, eps);\n\tBOOST_CHECK_CLOSE(Sin(a2)+1.0, Sin(a0)+1.0, eps);\n\tBOOST_CHECK_CLOSE(Sin(a2+a1), -1.0, eps);\n\n\tBOOST_CHECK_CLOSE(Cos(a1)+1.0, 1.0, eps);\n\tBOOST_CHECK_CLOSE(Cos(a2), -1.0, eps);\n\tBOOST_CHECK_CLOSE(Cos(a2+a1)+1.0, 1.0, eps);\n\n\tBOOST_CHECK_CLOSE(Sin(a1), Sin(100000*a3+a1), eps);\n\tBOOST_CHECK_CLOSE(Cos(a0), Cos(100000*a3+a0), eps);\n\n\tBOOST_CHECK(Sin(a2+a1) == Sin(a3-a1));\n\tBOOST_CHECK(Cos(a2+a1) == Cos(a3-a1));\n}\n\nBOOST_AUTO_TEST_CASE(Angle_sin_cos_2)\n{\n\ttypedef oglplus::Angle<double> Angled;\n\tAngled a3 = Angled::Radians(oglplus::math::TwoPi());\n\n\tdouble eps = 1e-8;\n\tdouble d = 1.6181;\n\n\tfor(unsigned i=0; i!=1000; ++i)\n\t{\n\t\tAngled a = Angled::Radians(i*i*d);\n\t\tBOOST_CHECK_CLOSE(Sin(a)+2.0, Sin(a+a3*i)+2.0, eps);\n\t\tBOOST_CHECK_CLOSE(Cos(a)+2.0, Cos(a+a3*i)+2.0, eps);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(Angle_tan)\n{\n\ttypedef oglplus::Angle<double> Angled;\n\n\tdouble eps = 1e-9;\n\tdouble d = 1.6181;\n\n\tfor(unsigned i=0; i!=1000; ++i)\n\t{\n\t\tAngled a = Angled::Radians(i*i*d);\n\t\tBOOST_CHECK_CLOSE(Sin(a)/Cos(a)+2.0, Tan(a)+2.0, eps);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(Angle_arc)\n{\n\tusing oglplus::ArcSin;\n\tusing oglplus::ArcCos;\n\n\ttypedef oglplus::Angle<double> Angled;\n\n\tdouble eps = 2;\n\n\tfor(unsigned i=1; i!=1000; ++i)\n\t{\n\t\tAngled a = Angled::Radians(oglplus::math::HalfPi()/i);\n\t\tBOOST_CHECK_CLOSE(a.Value(), ArcSin(Sin(a)).Value(), eps);\n\t\tBOOST_CHECK_CLOSE(a.Value(), ArcCos(Cos(a)).Value(), eps);\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d6210d1d5d008835efd9a84ec8ff854b23413279", "size": 6650, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/oglplus/angle.cpp", "max_stars_repo_name": "Extrunder/oglplus", "max_stars_repo_head_hexsha": "c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-06-09T00:28:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-09T00:28:43.000Z", "max_issues_repo_path": "test/oglplus/angle.cpp", "max_issues_repo_name": "Extrunder/oglplus", "max_issues_repo_head_hexsha": "c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791", "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/oglplus/angle.cpp", "max_forks_repo_name": "Extrunder/oglplus", "max_forks_repo_head_hexsha": "c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-01-30T22:06:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-14T17:24:36.000Z", "avg_line_length": 26.4940239044, "max_line_length": 70, "alphanum_fraction": 0.6789473684, "num_tokens": 2332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5369113570562984}}
{"text": "#include \"../../src/worldmap/TrICP.h\"\n#include \"../../src/Util.h\"\n\n#include <Eigen/LU>\n#include <iostream>\n\n#include <catch2/catch.hpp>\n\n#include \"../../src/worldmap/GlobalMap.h\"\n\nusing namespace navtypes;\nusing namespace util;\n\nnamespace\n{\ndouble rand(double low, double high)\n{\n\treturn low + (::rand() / (RAND_MAX / (high - low))); // NOLINT(cert-msc50-cpp)\n}\n} // namespace\n\nTEST_CASE(\"Trimmed ICP\")\n{\n\tpoints_t map;\n\tpoints_t sample;\n\tpoints_t truths;\n\ttransform_t trf = toTransformRotateFirst(0.1, -0.25, M_PI / 24);\n\tsrand(time(nullptr)); // NOLINT(cert-msc51-cpp)\n\tfor (int i = 0; i < 150; i++)\n\t{\n\t\tdouble x1 = rand(-6, 2);\n\t\tdouble y1 = pow(x1, 3);\n\t\tmap.push_back({x1, y1, 1});\n\n\t\tdouble x2 = rand(-2, 6);\n\t\tdouble y2 = pow(x2, 3);\n\t\tpoint_t p = {x2, y2, 1};\n\t\ttruths.push_back(p);\n\t\tp = trf * p;\n\t\tsample.push_back(p);\n\t}\n\n\tGlobalMap globalMap(1000);\n\tglobalMap.addPoints(transform_t::Identity(), map, 1);\n\n\tTrICP icp(25, 0.005, std::bind(&GlobalMap::getClosest, &globalMap, std::placeholders::_1));\n\t// approximate the inverse of the transform used to create the sample\n\ttransform_t trfApprox = icp.correct(sample, 0.3);\n\ttransform_t trfInv = trf.inverse();\n\n\tdouble mse = (trfInv - trfApprox).array().square().mean();\n\tstd::cout << \"TrICP MSE: \" << mse << std::endl;\n\tCHECK(mse == Approx(0).margin(0.01));\n}\n", "meta": {"hexsha": "2d6f58b99b777bc3a8d60b906a22a8a65d238023", "size": 1321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/worldmap/TrICPTest.cpp", "max_stars_repo_name": "huskyroboticsteam/Resurgence", "max_stars_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-23T23:31:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:17:41.000Z", "max_issues_repo_path": "tests/worldmap/TrICPTest.cpp", "max_issues_repo_name": "huskyroboticsteam/Resurgence", "max_issues_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-22T05:33:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T07:01:47.000Z", "max_forks_repo_path": "tests/worldmap/TrICPTest.cpp", "max_forks_repo_name": "huskyroboticsteam/Resurgence", "max_forks_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "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.0181818182, "max_line_length": 92, "alphanum_fraction": 0.6532929599, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.536911348359251}}
{"text": "/**\n * @file hmm_test.cpp\n *\n * Test file for HMMs.\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/hmm/hmm.hpp>\n#include <mlpack/methods/gmm/gmm.hpp>\n#include <mlpack/methods/gmm/diagonal_gmm.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::hmm;\nusing namespace mlpack::distribution;\nusing namespace mlpack::gmm;\n\nBOOST_AUTO_TEST_SUITE(HMMTest);\n\n/**\n * We will use the simple case proposed by Russell and Norvig in Artificial\n * Intelligence: A Modern Approach, 2nd Edition, around p.549.\n */\nBOOST_AUTO_TEST_CASE(SimpleDiscreteHMMTestViterbi)\n{\n  // We have two hidden states: rain/dry.  Two emission states: umbrella/no\n  // umbrella.\n  // In this example, the transition matrix is\n  //  rain  dry\n  // [[0.7 0.3]  rain\n  //  [0.3 0.7]] dry\n  // and the emission probability is\n  //  rain dry\n  // [[0.9 0.2]  umbrella\n  //  [0.1 0.8]] no umbrella\n  arma::vec initial(\"1 0\"); // Default MATLAB initial states.\n  arma::mat transition(\"0.7 0.3; 0.3 0.7\");\n  std::vector<DiscreteDistribution> emission(2);\n  emission[0] = DiscreteDistribution(std::vector<arma::vec>{\"0.9 0.1\"});\n  emission[1] = DiscreteDistribution(std::vector<arma::vec>{\"0.2 0.8\"});\n\n  HMM<DiscreteDistribution> hmm(initial, transition, emission);\n\n  // Now let's take a sequence and find what the most likely state is.\n  // We'll use the sequence [U U N U U] (U = umbrella, N = no umbrella) like on\n  // p. 547.\n  arma::mat observation = \"0 0 1 0 0\";\n  arma::Row<size_t> states;\n  hmm.Predict(observation, states);\n\n  // Check each state.\n  BOOST_REQUIRE_EQUAL(states[0], 0); // Rain.\n  BOOST_REQUIRE_EQUAL(states[1], 0); // Rain.\n  BOOST_REQUIRE_EQUAL(states[2], 1); // No rain.\n  BOOST_REQUIRE_EQUAL(states[3], 0); // Rain.\n  BOOST_REQUIRE_EQUAL(states[4], 0); // Rain.\n}\n\n/**\n * This example is from Borodovsky & Ekisheva, p. 80-81.  It is just slightly\n * more complex.\n */\nBOOST_AUTO_TEST_CASE(BorodovskyHMMTestViterbi)\n{\n  // Equally probable initial states.\n  arma::vec initial(3);\n  initial.fill(1.0 / 3.0);\n\n  // Two hidden states: H (high GC content) and L (low GC content), as well as a\n  // start state.\n  arma::mat transition(\"0.0 0.0 0.0;\"\n                       \"0.5 0.5 0.4;\"\n                       \"0.5 0.5 0.6\");\n  // Four emission states: A, C, G, T.  Start state doesn't emit...\n  std::vector<DiscreteDistribution> emission(3);\n  emission[0] = DiscreteDistribution(\n      std::vector<arma::vec>{\"0.25 0.25 0.25 0.25\"});\n  emission[1] = DiscreteDistribution(\n      std::vector<arma::vec>{\"0.20 0.30 0.30 0.20\"});\n  emission[2] = DiscreteDistribution(\n      std::vector<arma::vec>{\"0.30 0.20 0.20 0.30\"});\n\n  HMM<DiscreteDistribution> hmm(initial, transition, emission);\n\n  // GGCACTGAA.\n  arma::mat observation(\"2 2 1 0 1 3 2 0 0\");\n  arma::Row<size_t> states;\n  hmm.Predict(observation, states);\n\n  // Most probable path is HHHLLLLLL.\n  BOOST_REQUIRE_EQUAL(states[0], 1);\n  BOOST_REQUIRE_EQUAL(states[1], 1);\n  BOOST_REQUIRE_EQUAL(states[2], 1);\n  BOOST_REQUIRE_EQUAL(states[3], 2);\n  // This could actually be one of two states (equal probability).\n  BOOST_REQUIRE((states[4] == 1) || (states[4] == 2));\n  BOOST_REQUIRE_EQUAL(states[5], 2);\n  // This could also be one of two states.\n  BOOST_REQUIRE((states[6] == 1) || (states[6] == 2));\n  BOOST_REQUIRE_EQUAL(states[7], 2);\n  BOOST_REQUIRE_EQUAL(states[8], 2);\n}\n\n/**\n * Ensure that the forward-backward algorithm is correct.\n */\nBOOST_AUTO_TEST_CASE(ForwardBackwardTwoState)\n{\n  arma::mat obs(\"3 3 2 1 1 1 1 3 3 1\");\n\n  // The values used for the initial distribution here don't entirely make\n  // sense.  I am not sure how the output came from hmmdecode(), and the\n  // documentation below doesn't completely say.  It seems like maybe the\n  // transition matrix needs to be transposed and the results recalculated, but\n  // I am not certain.\n  arma::vec initial(\"0.1 0.4\");\n  arma::mat transition(\"0.1 0.9; 0.4 0.6\");\n  std::vector<DiscreteDistribution> emis(2);\n  emis[0] = DiscreteDistribution(std::vector<arma::vec>{\"0.85 0.15 0.00 0.00\"});\n  emis[1] = DiscreteDistribution(std::vector<arma::vec>{\"0.00 0.00 0.50 0.50\"});\n\n  HMM<DiscreteDistribution> hmm(initial, transition, emis);\n\n  // Now check we are getting the same results as MATLAB for this sequence.\n  arma::mat stateProb;\n  arma::mat forwardProb;\n  arma::mat backwardProb;\n  arma::vec scales;\n\n  const double log = hmm.Estimate(obs, stateProb, forwardProb, backwardProb,\n      scales);\n\n  // All values obtained from MATLAB hmmdecode().\n  BOOST_REQUIRE_CLOSE(log, -23.4349, 1e-3);\n\n  BOOST_REQUIRE_SMALL(stateProb(0, 0), 1e-5);\n  BOOST_REQUIRE_CLOSE(stateProb(1, 0), 1.0, 1e-5);\n  BOOST_REQUIRE_SMALL(stateProb(0, 1), 1e-5);\n  BOOST_REQUIRE_CLOSE(stateProb(1, 1), 1.0, 1e-5);\n  BOOST_REQUIRE_SMALL(stateProb(0, 2), 1e-5);\n  BOOST_REQUIRE_CLOSE(stateProb(1, 2), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(stateProb(0, 3), 1.0, 1e-5);\n  BOOST_REQUIRE_SMALL(stateProb(1, 3), 1e-5);\n  BOOST_REQUIRE_CLOSE(stateProb(0, 4), 1.0, 1e-5);\n  BOOST_REQUIRE_SMALL(stateProb(1, 4), 1e-5);\n  BOOST_REQUIRE_CLOSE(stateProb(0, 5), 1.0, 1e-5);\n  BOOST_REQUIRE_SMALL(stateProb(1, 5), 1e-5);\n  BOOST_REQUIRE_CLOSE(stateProb(0, 6), 1.0, 1e-5);\n  BOOST_REQUIRE_SMALL(stateProb(1, 6), 1e-5);\n  BOOST_REQUIRE_SMALL(stateProb(0, 7), 1e-5);\n  BOOST_REQUIRE_CLOSE(stateProb(1, 7), 1.0, 1e-5);\n  BOOST_REQUIRE_SMALL(stateProb(0, 8), 1e-5);\n  BOOST_REQUIRE_CLOSE(stateProb(1, 8), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(stateProb(0, 9), 1.0, 1e-5);\n  BOOST_REQUIRE_SMALL(stateProb(1, 9), 1e-5);\n}\n\n/**\n * In this example we try to estimate the transmission and emission matrices\n * based on some observations.  We use the simplest possible model.\n */\nBOOST_AUTO_TEST_CASE(SimplestBaumWelchDiscreteHMM)\n{\n  // Don't yet require a useful distribution.  1 state, 1 emission.\n  HMM<DiscreteDistribution> hmm(1, DiscreteDistribution(1));\n\n  std::vector<arma::mat> observations;\n  // Different lengths for each observation sequence.\n  observations.push_back(\"0 0 0 0 0 0 0 0\"); // 8 zeros.\n  observations.push_back(\"0 0 0 0 0 0 0\"); // 7 zeros.\n  observations.push_back(\"0 0 0 0 0 0 0 0 0 0 0 0\"); // 12 zeros.\n  observations.push_back(\"0 0 0 0 0 0 0 0 0 0\"); // 10 zeros.\n\n  hmm.Train(observations);\n\n  BOOST_REQUIRE_CLOSE(hmm.Initial()[0], 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(hmm.Emission()[0].Probability(\"0\"), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(hmm.Transition()(0, 0), 1.0, 1e-5);\n}\n\n/**\n * A slightly more complex model to estimate.\n */\nBOOST_AUTO_TEST_CASE(SimpleBaumWelchDiscreteHMM)\n{\n  HMM<DiscreteDistribution> hmm(1, 2); // 1 state, 2 emissions.\n  // Randomize the emission matrix.\n  hmm.Emission()[0].Probabilities() = arma::randu<arma::vec>(2);\n  hmm.Emission()[0].Probabilities() /= accu(hmm.Emission()[0].Probabilities());\n\n  // P(each emission) = 0.5.\n  // I've been careful to make P(first emission = 0) = P(first emission = 1).\n  std::vector<arma::mat> observations;\n  observations.push_back(\"0 1 0 1 0 1 0 1 0 1 0 1\");\n  observations.push_back(\"0 0 0 0 0 0 1 1 1 1 1 1\");\n  observations.push_back(\"1 1 1 1 1 1 0 0 0 0 0 0\");\n  observations.push_back(\"1 1 1 0 0 0 1 1 1 0 0 0\");\n  observations.push_back(\"0 0 1 1 0 0 0 0 1 1 1 1\");\n  observations.push_back(\"1 1 1 0 0 0 1 1 1 0 0 0\");\n  observations.push_back(\"0 1 0 1 0 1 0 1 0 1 0 1\");\n  observations.push_back(\"0 0 0 0 0 0 1 1 1 1 1 1\");\n  observations.push_back(\"1 1 1 1 1 0 1 0 0 0 0 0\");\n  observations.push_back(\"1 1 1 0 0 1 0 1 1 0 0 0\");\n  observations.push_back(\"0 0 1 1 0 0 0 1 0 1 1 1\");\n  observations.push_back(\"1 1 1 0 0 1 0 1 1 0 0 0\");\n\n  hmm.Train(observations);\n\n  BOOST_REQUIRE_CLOSE(hmm.Emission()[0].Probability(\"0\"), 0.5, 1e-5);\n  BOOST_REQUIRE_CLOSE(hmm.Emission()[0].Probability(\"1\"), 0.5, 1e-5);\n  BOOST_REQUIRE_CLOSE(hmm.Transition()(0, 0), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(hmm.Initial()[0], 1.0, 1e-5);\n}\n\n/**\n * Increasing complexity, but still simple; 4 emissions, 2 states; the state can\n * be determined directly by the emission.\n */\nBOOST_AUTO_TEST_CASE(SimpleBaumWelchDiscreteHMM_2)\n{\n  HMM<DiscreteDistribution> hmm(2, DiscreteDistribution(4));\n\n  // A little bit of obfuscation to the solution.\n  hmm.Transition() = arma::mat(\"0.1 0.4; 0.9 0.6\");\n  hmm.Emission()[0].Probabilities() = \"0.85 0.15 0.00 0.00\";\n  hmm.Emission()[1].Probabilities() = \"0.00 0.00 0.50 0.50\";\n\n  // True emission matrix:\n  //  [[0.4 0  ]\n  //   [0.6 0  ]\n  //   [0   0.2]\n  //   [0   0.8]]\n\n  // True transmission matrix:\n  //  [[0.5 0.5]\n  //   [0.5 0.5]]\n\n  // Generate observations randomly by hand.  This is kinda ugly, but it works.\n  std::vector<arma::mat> observations;\n  size_t obsNum = 250; // Number of observations.\n  size_t obsLen = 500; // Number of elements in each observation.\n  size_t stateZeroStarts = 0; // Number of times we start in state 0.\n  for (size_t i = 0; i < obsNum; i++)\n  {\n    arma::mat observation(1, obsLen);\n\n    size_t state = 0;\n    size_t emission = 0;\n\n    for (size_t obs = 0; obs < obsLen; obs++)\n    {\n      // See if state changed.\n      double r = math::Random();\n\n      if (r <= 0.5)\n      {\n        if (obs == 0)\n          ++stateZeroStarts;\n        state = 0;\n      }\n      else\n      {\n        state = 1;\n      }\n\n      // Now set the observation.\n      r = math::Random();\n\n      switch (state)\n      {\n        // case 0 is not possible.\n        case 0:\n          if (r <= 0.4)\n            emission = 0;\n          else\n            emission = 1;\n          break;\n        case 1:\n          if (r <= 0.2)\n            emission = 2;\n          else\n            emission = 3;\n          break;\n      }\n\n      observation(0, obs) = emission;\n    }\n\n    observations.push_back(observation);\n  }\n\n  hmm.Train(observations);\n\n  // Calculate true probability of class 0 at the start.\n  double prob = double(stateZeroStarts) / observations.size();\n\n  // Only require 2.5% tolerance, because this is a little fuzzier.\n  BOOST_REQUIRE_CLOSE(hmm.Initial()[0], prob, 2.5);\n  BOOST_REQUIRE_CLOSE(hmm.Initial()[1], 1.0 - prob, 2.5);\n\n  BOOST_REQUIRE_CLOSE(hmm.Transition()(0, 0), 0.5, 2.5);\n  BOOST_REQUIRE_CLOSE(hmm.Transition()(1, 0), 0.5, 2.5);\n  BOOST_REQUIRE_CLOSE(hmm.Transition()(0, 1), 0.5, 2.5);\n  BOOST_REQUIRE_CLOSE(hmm.Transition()(1, 1), 0.5, 2.5);\n\n  BOOST_REQUIRE_CLOSE(hmm.Emission()[0].Probability(\"0\"), 0.4, 4.0);\n  BOOST_REQUIRE_CLOSE(hmm.Emission()[0].Probability(\"1\"), 0.6, 4.0);\n  BOOST_REQUIRE_SMALL(hmm.Emission()[0].Probability(\"2\"), 2.5);\n  BOOST_REQUIRE_SMALL(hmm.Emission()[0].Probability(\"3\"), 2.5);\n  BOOST_REQUIRE_SMALL(hmm.Emission()[1].Probability(\"0\"), 2.5);\n  BOOST_REQUIRE_SMALL(hmm.Emission()[1].Probability(\"1\"), 2.5);\n  BOOST_REQUIRE_CLOSE(hmm.Emission()[1].Probability(\"2\"), 0.2, 4.0);\n  BOOST_REQUIRE_CLOSE(hmm.Emission()[1].Probability(\"3\"), 0.8, 4.0);\n}\n\nBOOST_AUTO_TEST_CASE(DiscreteHMMLabeledTrainTest)\n{\n  // Generate a random Markov model with 3 hidden states and 6 observations.\n  arma::mat transition;\n  std::vector<DiscreteDistribution> emission(3);\n\n  transition.randu(3, 3);\n  emission[0].Probabilities() = arma::randu<arma::vec>(6);\n  emission[0].Probabilities() /= accu(emission[0].Probabilities());\n  emission[1].Probabilities() = arma::randu<arma::vec>(6);\n  emission[1].Probabilities() /= accu(emission[1].Probabilities());\n  emission[2].Probabilities() = arma::randu<arma::vec>(6);\n  emission[2].Probabilities() /= accu(emission[2].Probabilities());\n\n  // Normalize so they we have a correct transition matrix.\n  for (size_t col = 0; col < 3; col++)\n    transition.col(col) /= accu(transition.col(col));\n\n  // Now generate sequences.\n  size_t obsNum = 250;\n  size_t obsLen = 800;\n\n  std::vector<arma::mat> observations(obsNum);\n  std::vector<arma::Row<size_t> > states(obsNum);\n\n  for (size_t n = 0; n < obsNum; n++)\n  {\n    observations[n].set_size(1, obsLen);\n    states[n].set_size(obsLen);\n\n    // Random starting state.\n    states[n][0] = math::RandInt(3);\n\n    // Random starting observation.\n    observations[n].col(0) = emission[states[n][0]].Random();\n\n    // Now the rest of the observations.\n    for (size_t t = 1; t < obsLen; t++)\n    {\n      // Choose random number for state transition.\n      double state = math::Random();\n\n      // Decide next state.\n      double sumProb = 0;\n      for (size_t st = 0; st < 3; st++)\n      {\n        sumProb += transition(st, states[n][t - 1]);\n        if (sumProb >= state)\n        {\n          states[n][t] = st;\n          break;\n        }\n      }\n\n      // Decide observation.\n      observations[n].col(t) = emission[states[n][t]].Random();\n    }\n  }\n\n  // Now that our data is generated, we give the HMM the labeled data to train\n  // on.\n  HMM<DiscreteDistribution> hmm(3, DiscreteDistribution(6));\n\n  hmm.Train(observations, states);\n\n  // Make sure the initial weights are fine.  They should be equal (or close).\n  arma::vec initial(3);\n  initial.fill(1.0 / 3.0);\n  BOOST_REQUIRE_LT(arma::norm(hmm.Initial() - initial), 0.2);\n\n  // Check that the transition matrix is close.\n  BOOST_REQUIRE_LT(arma::norm(hmm.Transition() - transition), 0.1);\n\n  for (size_t col = 0; col < hmm.Emission().size(); col++)\n  {\n    for (size_t row = 0; row < hmm.Emission()[col].Probabilities().n_elem;\n        row++)\n    {\n      arma::vec obs(1);\n      obs[0] = row;\n      BOOST_REQUIRE_SMALL(hmm.Emission()[col].Probability(obs) -\n          emission[col].Probability(obs), 0.07);\n    }\n  }\n}\n\n/**\n * Make sure the Generate() function works for a uniformly distributed HMM;\n * we'll take many samples just to make sure.\n */\nBOOST_AUTO_TEST_CASE(DiscreteHMMSimpleGenerateTest)\n{\n  // Very simple HMM.  4 emissions with equal probability and 2 states with\n  // equal probability.\n  HMM<DiscreteDistribution> hmm(2, DiscreteDistribution(4));\n  hmm.Initial() = arma::ones<arma::vec>(2) / 2.0;\n  hmm.Transition() = arma::ones<arma::mat>(2, 2) / 2.0;\n\n  // Now generate a really, really long sequence.\n  arma::mat dataSeq;\n  arma::Row<size_t> stateSeq;\n\n  hmm.Generate(100000, dataSeq, stateSeq);\n\n  // Now find the empirical probabilities of each state.\n  arma::vec emissionProb(4);\n  arma::vec stateProb(2);\n  emissionProb.zeros();\n  stateProb.zeros();\n  for (size_t i = 0; i < 100000; i++)\n  {\n    emissionProb[(size_t) dataSeq.col(i)[0] + 0.5]++;\n    stateProb[stateSeq[i]]++;\n  }\n\n  // Normalize so these are probabilities.\n  emissionProb /= accu(emissionProb);\n  stateProb /= accu(stateProb);\n\n  // Now check that the probabilities are right.  3% tolerance.\n  BOOST_REQUIRE_CLOSE(emissionProb[0], 0.25, 3.0);\n  BOOST_REQUIRE_CLOSE(emissionProb[1], 0.25, 3.0);\n  BOOST_REQUIRE_CLOSE(emissionProb[2], 0.25, 3.0);\n  BOOST_REQUIRE_CLOSE(emissionProb[3], 0.25, 3.0);\n\n  BOOST_REQUIRE_CLOSE(stateProb[0], 0.50, 3.0);\n  BOOST_REQUIRE_CLOSE(stateProb[1], 0.50, 3.0);\n}\n\n/**\n * More complex test for Generate().\n */\nBOOST_AUTO_TEST_CASE(DiscreteHMMGenerateTest)\n{\n  // 6 emissions, 4 states.  Random transition and emission probability.\n  arma::vec initial(\"1 0 0 0\");\n  arma::mat transition(4, 4);\n  std::vector<DiscreteDistribution> emission(4);\n  emission[0].Probabilities() = arma::randu<arma::vec>(6);\n  emission[0].Probabilities() /= accu(emission[0].Probabilities());\n  emission[1].Probabilities() = arma::randu<arma::vec>(6);\n  emission[1].Probabilities() /= accu(emission[1].Probabilities());\n  emission[2].Probabilities() = arma::randu<arma::vec>(6);\n  emission[2].Probabilities() /= accu(emission[2].Probabilities());\n  emission[3].Probabilities() = arma::randu<arma::vec>(6);\n  emission[3].Probabilities() /= accu(emission[3].Probabilities());\n\n  transition.randu();\n\n  // Normalize matrix.\n  for (size_t col = 0; col < 4; col++)\n    transition.col(col) /= accu(transition.col(col));\n\n  // Create HMM object.\n  HMM<DiscreteDistribution> hmm(initial, transition, emission);\n\n  // We'll create a bunch of sequences.\n  int numSeq = 400;\n  int numObs = 3000;\n  std::vector<arma::mat> sequences(numSeq);\n  std::vector<arma::Row<size_t> > states(numSeq);\n  for (int i = 0; i < numSeq; i++)\n  {\n    // Random starting state.\n    size_t startState = math::RandInt(4);\n\n    hmm.Generate(numObs, sequences[i], states[i], startState);\n  }\n\n  // Now we will calculate the full probabilities.\n  HMM<DiscreteDistribution> hmm2(4, 6);\n  hmm2.Train(sequences, states);\n\n  // Check that training gives the same result.\n  BOOST_REQUIRE_LT(arma::norm(hmm.Transition() - hmm2.Transition()), 0.01);\n\n  for (size_t row = 0; row < 6; row++)\n  {\n    arma::vec obs(1);\n    obs[0] = row;\n    for (size_t col = 0; col < 4; col++)\n    {\n      BOOST_REQUIRE_SMALL(hmm.Emission()[col].Probability(obs) -\n          hmm2.Emission()[col].Probability(obs), 0.01);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(DiscreteHMMLogLikelihoodTest)\n{\n  // Create a simple HMM with three states and four emissions.\n  arma::vec initial(\"0.5 0.2 0.3\"); // Default MATLAB initial states.\n  arma::mat transition(\"0.5 0.0 0.1;\"\n                       \"0.2 0.6 0.2;\"\n                       \"0.3 0.4 0.7\");\n  std::vector<DiscreteDistribution> emission(3);\n  emission[0].Probabilities() = \"0.75 0.25 0.00 0.00\";\n  emission[1].Probabilities() = \"0.00 0.25 0.25 0.50\";\n  emission[2].Probabilities() = \"0.10 0.40 0.40 0.10\";\n\n  HMM<DiscreteDistribution> hmm(initial, transition, emission);\n\n  // Now generate some sequences and check that the log-likelihood is the same\n  // as MATLAB gives for this HMM.\n  BOOST_REQUIRE_CLOSE(hmm.LogLikelihood(\"0 1 2 3\"), -4.9887223949, 1e-5);\n  BOOST_REQUIRE_CLOSE(hmm.LogLikelihood(\"1 2 0 0\"), -6.0288487077, 1e-5);\n  BOOST_REQUIRE_CLOSE(hmm.LogLikelihood(\"3 3 3 3\"), -5.5544000018, 1e-5);\n  BOOST_REQUIRE_CLOSE(hmm.LogLikelihood(\"0 2 2 1 2 3 0 0 1 3 1 0 0 3 1 2 2\"),\n      -24.51556128368, 1e-5);\n}\n\n/**\n * A simple test to make sure HMMs with Gaussian output distributions work.\n */\nBOOST_AUTO_TEST_CASE(GaussianHMMSimpleTest)\n{\n  // We'll have two Gaussians, far away from each other, one corresponding to\n  // each state.\n  //  E(0) ~ N([ 5.0  5.0], eye(2)).\n  //  E(1) ~ N([-5.0 -5.0], eye(2)).\n  // The transition matrix is simple:\n  //  T = [[0.75 0.25]\n  //       [0.25 0.75]]\n  GaussianDistribution g1(\"5.0 5.0\", \"1.0 0.0; 0.0 1.0\");\n  GaussianDistribution g2(\"-5.0 -5.0\", \"1.0 0.0; 0.0 1.0\");\n\n  arma::vec initial(\"1 0\"); // Default MATLAB initial states.\n  arma::mat transition(\"0.75 0.25; 0.25 0.75\");\n\n  std::vector<GaussianDistribution> emission;\n  emission.push_back(g1);\n  emission.push_back(g2);\n\n  HMM<GaussianDistribution> hmm(initial, transition, emission);\n\n  // Now, generate some sequences.\n  arma::mat observations(2, 1000);\n  arma::Row<size_t> classes(1000);\n\n  // 1000-observations sequence.\n  classes[0] = 0;\n  observations.col(0) = g1.Random();\n  for (size_t i = 1; i < 1000; i++)\n  {\n    double randValue = math::Random();\n\n    if (randValue > 0.75) // Then we change state.\n      classes[i] = (classes[i - 1] + 1) % 2;\n    else\n      classes[i] = classes[i - 1];\n\n    if (classes[i] == 0)\n      observations.col(i) = g1.Random();\n    else\n      observations.col(i) = g2.Random();\n  }\n\n  // Now predict the sequence.\n  arma::Row<size_t> predictedClasses;\n  arma::mat stateProb;\n\n  hmm.Predict(observations, predictedClasses);\n  hmm.Estimate(observations, stateProb);\n\n  // Check that each prediction is right.\n  for (size_t i = 0; i < 1000; i++)\n  {\n    BOOST_REQUIRE_EQUAL(predictedClasses[i], classes[i]);\n\n    // The probability of the wrong class should be infinitesimal.\n    BOOST_REQUIRE_SMALL(stateProb((classes[i] + 1) % 2, i), 0.001);\n  }\n}\n\n/**\n * Ensure that Gaussian HMMs can be trained properly, for the labeled training\n * case and also for the unlabeled training case.\n */\nBOOST_AUTO_TEST_CASE(GaussianHMMTrainTest)\n{\n  // Four emission Gaussians and three internal states.  The goal is to estimate\n  // the transition matrix correctly, and each distribution correctly.\n  std::vector<GaussianDistribution> emission;\n  emission.push_back(GaussianDistribution(\"0.0 0.0 0.0\", \"1.0 0.2 0.2;\"\n                                                         \"0.2 1.5 0.0;\"\n                                                         \"0.2 0.0 1.1\"));\n  emission.push_back(GaussianDistribution(\"2.0 1.0 5.0\", \"0.7 0.3 0.0;\"\n                                                         \"0.3 2.6 0.0;\"\n                                                         \"0.0 0.0 1.0\"));\n  emission.push_back(GaussianDistribution(\"5.0 0.0 0.5\", \"1.0 0.0 0.0;\"\n                                                         \"0.0 1.0 0.0;\"\n                                                         \"0.0 0.0 1.0\"));\n\n  arma::mat transition(\"0.3 0.5 0.7;\"\n                       \"0.3 0.4 0.1;\"\n                       \"0.4 0.1 0.2\");\n\n  // Now generate observations.\n  std::vector<arma::mat> observations(100);\n  std::vector<arma::Row<size_t> > states(100);\n\n  for (size_t obs = 0; obs < 100; obs++)\n  {\n    observations[obs].set_size(3, 1000);\n    states[obs].set_size(1000);\n\n    // Always start in state zero.\n    states[obs][0] = 0;\n    observations[obs].col(0) = emission[0].Random();\n\n    for (size_t t = 1; t < 1000; t++)\n    {\n      // Choose the state.\n      double randValue = math::Random();\n      double probSum = 0;\n      for (size_t state = 0; state < 3; state++)\n      {\n        probSum += transition(state, states[obs][t - 1]);\n        if (probSum >= randValue)\n        {\n          states[obs][t] = state;\n          break;\n        }\n      }\n\n      // Now choose the emission.\n      observations[obs].col(t) = emission[states[obs][t]].Random();\n    }\n  }\n\n  // Now that the data is generated, train the HMM.\n  HMM<GaussianDistribution> hmm(3, GaussianDistribution(3));\n\n  hmm.Train(observations, states);\n\n  // Check initial weights.\n  BOOST_REQUIRE_CLOSE(hmm.Initial()[0], 1.0, 1e-5);\n  BOOST_REQUIRE_SMALL(hmm.Initial()[1], 1e-3);\n  BOOST_REQUIRE_SMALL(hmm.Initial()[2], 1e-3);\n\n  // We use a tolerance of 0.05 for the transition matrices.\n  // Check that the transition matrix is correct.\n  BOOST_REQUIRE_LT(arma::norm(hmm.Transition() - transition), 0.05);\n\n  // Check that each distribution is correct.\n  for (size_t dist = 0; dist < 3; dist++)\n  {\n    BOOST_REQUIRE_LT(arma::norm(hmm.Emission()[dist].Mean() -\n        emission[dist].Mean()), 0.05);\n    BOOST_REQUIRE_LT(arma::norm(hmm.Emission()[dist].Covariance() -\n        emission[dist].Covariance()), 0.1);\n  }\n\n  // Now let's try it all again, but this time, unlabeled.  Everything will fail\n  // if we don't have a decent guess at the Gaussians, so we'll take a \"poor\"\n  // guess at it ourselves.  I won't use K-Means because we can't afford to add\n  // the instability of that to our test.  We'll leave the covariances as the\n  // identity.\n  HMM<GaussianDistribution> hmm2(3, GaussianDistribution(3));\n  hmm2.Emission()[0].Mean() = \"0.3 -0.2 0.1\"; // Actual: [0 0 0].\n  hmm2.Emission()[1].Mean() = \"1.0 1.4 3.2\";  // Actual: [2 1 5].\n  hmm2.Emission()[2].Mean() = \"3.1 -0.2 6.1\"; // Actual: [5 0 5].\n\n  // We'll only use 20 observation sequences to try and keep training time\n  // shorter.\n  observations.resize(20);\n\n  hmm.Train(observations);\n\n  BOOST_REQUIRE_CLOSE(hmm.Initial()[0], 1.0, 0.1);\n  BOOST_REQUIRE_SMALL(hmm.Initial()[1], 0.05);\n  BOOST_REQUIRE_SMALL(hmm.Initial()[2], 0.05);\n\n  // The tolerances are increased because there is more error in unlabeled\n  // training; we use an absolute tolerance of 0.03 for the transition matrices.\n  // Check that the transition matrix is correct.\n  for (size_t row = 0; row < 3; row++)\n    for (size_t col = 0; col < 3; col++)\n      BOOST_REQUIRE_SMALL(transition(row, col) - hmm.Transition()(row, col),\n          0.03);\n\n  // Check that each distribution is correct.\n  for (size_t dist = 0; dist < 3; dist++)\n  {\n    BOOST_REQUIRE_LT(arma::norm(hmm.Emission()[dist].Mean() -\n        emission[dist].Mean()), 0.1);\n    BOOST_REQUIRE_LT(arma::norm(hmm.Emission()[dist].Covariance() -\n        emission[dist].Covariance()), 0.25);\n  }\n}\n\n/**\n * Make sure that a random sequence generated by a Gaussian HMM fits the\n * distribution correctly.\n */\nBOOST_AUTO_TEST_CASE(GaussianHMMGenerateTest)\n{\n  // Our distribution will have three two-dimensional output Gaussians.\n  HMM<GaussianDistribution> hmm(3, GaussianDistribution(2));\n  hmm.Transition() = arma::mat(\"0.4 0.6 0.8; 0.2 0.2 0.1; 0.4 0.2 0.1\");\n  hmm.Emission()[0] = GaussianDistribution(\"0.0 0.0\", \"1.0 0.0; 0.0 1.0\");\n  hmm.Emission()[1] = GaussianDistribution(\"2.0 2.0\", \"1.0 0.5; 0.5 1.2\");\n  hmm.Emission()[2] = GaussianDistribution(\"-2.0 1.0\", \"2.0 0.1; 0.1 1.0\");\n\n  // Now we will generate a long sequence.\n  std::vector<arma::mat> observations(1);\n  std::vector<arma::Row<size_t> > states(1);\n\n  // Start in state 1 (no reason).\n  hmm.Generate(10000, observations[0], states[0], 1);\n\n  HMM<GaussianDistribution> hmm2(3, GaussianDistribution(2));\n\n  // Now estimate the HMM from the generated sequence.\n  hmm2.Train(observations, states);\n\n  // Check that the estimated matrices are the same.\n  BOOST_REQUIRE_LT(arma::norm(hmm.Transition() - hmm2.Transition()), 0.1);\n\n  // Check that each Gaussian is the same.\n  for (size_t dist = 0; dist < 3; dist++)\n  {\n    BOOST_REQUIRE_LT(arma::norm(hmm.Emission()[dist].Mean() -\n        hmm2.Emission()[dist].Mean()), 0.2);\n    BOOST_REQUIRE_LT(arma::norm(hmm.Emission()[dist].Covariance() -\n        hmm2.Emission()[dist].Covariance()), 0.3);\n  }\n}\n\n/**\n * Make sure that Predict() is numerically stable.\n */\nBOOST_AUTO_TEST_CASE(GaussianHMMPredictTest)\n{\n  size_t numState = 10;\n  size_t obsDimension = 2;\n  HMM<GaussianDistribution> hmm(numState, GaussianDistribution(obsDimension));\n\n  arma::vec initial = {1.0000, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n  arma::mat transition = {{0.9149, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n                          {0.0851, 0.8814, 0, 0, 0, 0, 0, 0, 0, 0},\n                          {0, 0.1186, 0.9031, 0, 0, 0, 0, 0, 0, 0},\n                          {0, 0, 0.0969, 0.903, 0, 0, 0, 0, 0, 0},\n                          {0, 0, 0, 0.097, 0.8941, 0, 0, 0, 0, 0},\n                          {0, 0, 0, 0, 0.1059, 0.9024, 0, 0, 0, 0},\n                          {0, 0, 0, 0, 0, 0.0976, 0.8902, 0, 0, 0},\n                          {0, 0, 0, 0, 0, 0, 0.1098, 0.9107, 0, 0},\n                          {0, 0, 0, 0, 0, 0, 0, 0.0893, 0.8964, 0},\n                          {0, 0, 0, 0, 0, 0, 0, 0, 0.1036, 1}};\n\n  std::vector<arma::vec> mean = {{0, 0.259},\n                                 {0.0372, 0.2063},\n                                 {0.1496, -0.3075},\n                                 {-0.0366, -0.3255},\n                                 {-0.2866, -0.0202},\n                                 {0.1804, 0.1385},\n                                 {0.1922, -0.0616},\n                                 {-0.378, -0.1751},\n                                 {-0.1346, 0.1357},\n                                 {0.338, 0.183}};\n\n  std::vector<arma::mat> cov = {\n      {{3.2837e-07, 0}, {0, 0.032837}},\n      {{0.0154, -0.0093}, {-0.0093, 0.0358}},\n      {{0.1087, -0.0032}, {-0.0032, 0.0587}},\n      {{0.3185, -0.0069}, {-0.0069, 0.0396}},\n      {{0.3472, 0.0484}, {0.0484, 0.0706}},\n      {{0.39, 0.0406}, {0.0406, 0.0653}},\n      {{0.4502, 0.0718}, {0.0718, 0.0705}},\n      {{0.3253, 0.0312}, {0.0312, 0.0783}},\n      {{0.2355, 0.0195}, {0.0195, 0.0276}},\n      {{0.0818, 0.022}, {0.022, 0.0282}}};\n\n  hmm.Initial() = initial;\n  hmm.Transition() = transition;\n\n  for (size_t i = 0; i < numState; ++i)\n  {\n    GaussianDistribution& emission = hmm.Emission().at(i);\n    emission.Mean() = mean.at(i);\n    emission.Covariance(cov.at(i));\n  }\n\n  arma::mat obs = {\n      {\n          -0.0424, -0.0395, -0.0336, -0.0294, -0.0299, -0.032, -0.0289, -0.0148,\n          0.0095, 0.0416, 0.0795, 0.1173, 0.1491, 0.1751, 0.1999, 0.2277,\n          0.2586, 0.2858, 0.3019, 0.303, 0.289, 0.2632, 0.2301, 0.1923, 0.1498,\n          0.1021, 0.0471, -0.0191, -0.0969, -0.1795, -0.2559, -0.323, -0.3882,\n          -0.4582, -0.5334, -0.609, -0.6778999999999999, -0.7278, -0.7481,\n          -0.7356, -0.6953, -0.635, -0.5617, -0.478, -0.3833, -0.2721, -0.1365,\n          0.0283, 0.217, 0.4148, 0.6028, 0.7664, 0.8937, 0.9737, 1, 0.972,\n          0.8972, 0.7891, 0.6613, 0.524, 0.3847, 0.2489, 0.1187, -0.0045,\n          -0.1214, -0.2316, -0.3328, -0.4211, -0.4963, -0.5607, -0.6136,\n          -0.6532, -0.6777, -0.6867, -0.6807, -0.6612, -0.6345, -0.6075,\n          -0.5748, -0.5278, -0.4747, -0.4176, -0.33, -0.2036, -0.0597,\n          0.07240000000000001, 0.1754, 0.2471, 0.295, 0.3356, 0.3809, 0.4299,\n          0.4737, 0.4987, 0.4958, 0.4676, 0.4253, 0.3802, 0.342, 0.3183\n      },\n      {\n          0.2355, 0.2639, 0.2971, 0.3301, 0.3598, 0.3842, 0.3995, 0.4019, 0.39,\n          0.3624, 0.3201, 0.2658, 0.203, 0.1341, 0.06, -0.0179, -0.1006,\n          -0.1869, -0.2719, -0.35, -0.4176, -0.4739, -0.52, -0.5584, -0.5913,\n          -0.6196, -0.642, -0.6554, -0.6567, -0.6459, -0.6271, -0.6029, -0.5722,\n          -0.5318000000000001, -0.4802, -0.4174, -0.3449, -0.2685, -0.1927,\n          -0.1201, -0.0532, 0.008699999999999999, 0.0673, 0.1204, 0.1647,\n          0.2008, 0.2284, 0.2447, 0.2504, 0.2479, 0.2373, 0.2148, 0.1781,\n          0.1283, 0.06710000000000001, -0.0022, -0.0743, -0.1463, -0.2149,\n          -0.2784, -0.3362, -0.3867, -0.4297, -0.4651, -0.4924, -0.5101,\n          -0.5168, -0.5117, -0.496, -0.4706, -0.4358, -0.3923, -0.3419, -0.2868,\n          -0.2289, -0.1702, -0.1094, -0.0421, 0.0311, 0.1047, 0.1732, 0.2257,\n          0.254, 0.2532, 0.2308, 0.2017, 0.1724, 0.1425, 0.1195, 0.099, 0.0759,\n          0.0521, 0.0313, 0.0188, 0.0113, 0.0068, 0.0042, 0.0026, 0.0018, 0.0014\n      }\n  };\n\n  arma::Row<size_t> stateSeq;\n  auto likelihood = hmm.LogLikelihood(obs);\n  hmm.Predict(obs, stateSeq);\n\n  arma::Row<size_t> stateSeqRef = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n      1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4,\n      4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7,\n      7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,\n      9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };\n\n  BOOST_REQUIRE_CLOSE(likelihood, -2734.43, 1e-3);\n\n  for (size_t i = 0; i < stateSeqRef.n_cols; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(stateSeqRef.at(i), stateSeq.at(i));\n  }\n}\n\n/**\n * Test that HMMs work with Gaussian mixture models.  We'll try putting in a\n * simple model by hand and making sure that prediction of observation sequences\n * works correctly.\n */\nBOOST_AUTO_TEST_CASE(GMMHMMPredictTest)\n{\n  // It's possible, but extremely unlikely, that this test can fail.  So we are\n  // willing to do three trials in case the first two fail.\n  bool success = false;\n  for (size_t trial = 0; trial < 3; ++trial)\n  {\n    // We will use two GMMs; one with two components and one with three.\n    std::vector<GMM> gmms(2);\n    gmms[0] = GMM(2, 2);\n    gmms[0].Weights() = arma::vec(\"0.75 0.25\");\n\n    // N([2.25 3.10], [1.00 0.20; 0.20 0.89])\n    gmms[0].Component(0) = GaussianDistribution(\"4.25 3.10\",\n                                                \"1.00 0.20; 0.20 0.89\");\n\n    // N([4.10 1.01], [1.00 0.00; 0.00 1.01])\n    gmms[0].Component(1) = GaussianDistribution(\"7.10 5.01\",\n                                                \"1.00 0.00; 0.00 1.01\");\n\n    gmms[1] = GMM(3, 2);\n    gmms[1].Weights() = arma::vec(\"0.4 0.2 0.4\");\n\n    gmms[1].Component(0) = GaussianDistribution(\"-3.00 -6.12\",\n                                                \"1.00 0.00; 0.00 1.00\");\n\n    gmms[1].Component(1) = GaussianDistribution(\"-4.25 -7.12\",\n                                                \"1.50 0.60; 0.60 1.20\");\n\n    gmms[1].Component(2) = GaussianDistribution(\"-6.15 -2.00\",\n                                                \"1.00 0.80; 0.80 1.00\");\n\n    // Default MATLAB initial probabilities.\n    arma::vec initial(\"1 0\");\n\n    // Transition matrix.\n    arma::mat trans(\"0.30 0.50;\"\n                    \"0.70 0.50\");\n\n    // Now build the model.\n    HMM<GMM> hmm(initial, trans, gmms);\n\n    // Make a sequence of observations.\n    arma::mat observations(2, 1000);\n    arma::Row<size_t> states(1000);\n    states[0] = 0;\n    observations.col(0) = gmms[0].Random();\n\n    for (size_t i = 1; i < 1000; i++)\n    {\n      double randValue = math::Random();\n\n      if (randValue <= trans(0, states[i - 1]))\n        states[i] = 0;\n      else\n        states[i] = 1;\n\n      observations.col(i) = gmms[states[i]].Random();\n    }\n\n    // Run the prediction.\n    arma::Row<size_t> predictions;\n    hmm.Predict(observations, predictions);\n\n    // Check that the predictions were correct.\n    success = true;\n    for (size_t i = 0; i < 1000; i++)\n    {\n      if (predictions[i] != states[i])\n      {\n        success = false;\n        break;\n      }\n    }\n\n    if (success)\n      break;\n  }\n\n  BOOST_REQUIRE_EQUAL(success, true);\n}\n\n/**\n * Test that GMM-based HMMs can train on models correctly using labeled training\n * data.\n */\nBOOST_AUTO_TEST_CASE(GMMHMMLabeledTrainingTest)\n{\n  // We will use two GMMs; one with two components and one with three.\n  std::vector<GMM> gmms(2, GMM(2, 2));\n  gmms[0].Weights() = arma::vec(\"0.3 0.7\");\n\n  // N([2.25 3.10], [1.00 0.20; 0.20 0.89])\n  gmms[0].Component(0) = GaussianDistribution(\"4.25 3.10\",\n                                              \"1.00 0.20; 0.20 0.89\");\n\n  // N([4.10 1.01], [1.00 0.00; 0.00 1.01])\n  gmms[0].Component(1) = GaussianDistribution(\"7.10 5.01\",\n                                              \"1.00 0.00; 0.00 1.01\");\n\n  gmms[1].Weights() = arma::vec(\"0.20 0.80\");\n\n  gmms[1].Component(0) = GaussianDistribution(\"-3.00 -6.12\",\n                                              \"1.00 0.00; 0.00 1.00\");\n\n  gmms[1].Component(1) = GaussianDistribution(\"-4.25 -2.12\",\n                                              \"1.50 0.60; 0.60 1.20\");\n\n  // Transition matrix.\n  arma::mat transMat(\"0.40 0.60;\"\n                     \"0.60 0.40\");\n\n  // Make a sequence of observations.\n  std::vector<arma::mat> observations(5, arma::mat(2, 2500));\n  std::vector<arma::Row<size_t> > states(5, arma::Row<size_t>(2500));\n  for (size_t obs = 0; obs < 5; obs++)\n  {\n    states[obs][0] = 0;\n    observations[obs].col(0) = gmms[0].Random();\n\n    for (size_t i = 1; i < 2500; i++)\n    {\n      double randValue = (double) rand() / (double) RAND_MAX;\n\n      if (randValue <= transMat(0, states[obs][i - 1]))\n        states[obs][i] = 0;\n      else\n        states[obs][i] = 1;\n\n      observations[obs].col(i) = gmms[states[obs][i]].Random();\n    }\n  }\n\n  // Set up the GMM for training.\n  HMM<GMM> hmm(2, GMM(2, 2));\n\n  // Train the HMM.\n  hmm.Train(observations, states);\n\n  // Check the initial weights.  The dataset was generated with 100% probability\n  // of a sequence starting in state 0.\n  BOOST_REQUIRE_CLOSE(hmm.Initial()[0], 1.0, 0.01);\n  BOOST_REQUIRE_SMALL(hmm.Initial()[1], 0.01);\n\n  // Check the results.  Use absolute tolerances instead of percentages.\n  BOOST_REQUIRE_SMALL(hmm.Transition()(0, 0) - transMat(0, 0), 0.03);\n  BOOST_REQUIRE_SMALL(hmm.Transition()(0, 1) - transMat(0, 1), 0.03);\n  BOOST_REQUIRE_SMALL(hmm.Transition()(1, 0) - transMat(1, 0), 0.03);\n  BOOST_REQUIRE_SMALL(hmm.Transition()(1, 1) - transMat(1, 1), 0.03);\n\n  // Now the emission probabilities (the GMMs).\n  // We have to sort each GMM for comparison.\n  arma::uvec sortedIndices = sort_index(hmm.Emission()[0].Weights());\n\n  BOOST_REQUIRE_SMALL(hmm.Emission()[0].Weights()[sortedIndices[0]] -\n      gmms[0].Weights()[0], 0.08);\n  BOOST_REQUIRE_SMALL(hmm.Emission()[0].Weights()[sortedIndices[1]] -\n      gmms[0].Weights()[1], 0.08);\n\n  BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[0].Component(sortedIndices[0]).Mean() -\n      gmms[0].Component(0).Mean()), 0.2);\n  BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[0].Component(sortedIndices[1]).Mean() -\n      gmms[0].Component(1).Mean()), 0.2);\n\n  BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[0].Component(sortedIndices[0]).Covariance() -\n      gmms[0].Component(0).Covariance()), 0.5);\n  BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[0].Component(sortedIndices[1]).Covariance() -\n      gmms[0].Component(0).Covariance()), 0.5);\n\n  // Sort the GMM.\n  sortedIndices = sort_index(hmm.Emission()[1].Weights());\n\n  BOOST_REQUIRE_SMALL(hmm.Emission()[1].Weights()[sortedIndices[0]] -\n      gmms[1].Weights()[0], 0.08);\n  BOOST_REQUIRE_SMALL(hmm.Emission()[1].Weights()[sortedIndices[1]] -\n      gmms[1].Weights()[1], 0.08);\n\n  BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[1].Component(sortedIndices[0]).Mean() -\n      gmms[1].Component(0).Mean()), 0.2);\n  BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[1].Component(sortedIndices[1]).Mean() -\n      gmms[1].Component(1).Mean()), 0.2);\n\n  BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[1].Component(sortedIndices[0]).Covariance() -\n      gmms[1].Component(0).Covariance()), 0.5);\n  BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[1].Component(sortedIndices[1]).Covariance() -\n      gmms[1].Component(1).Covariance()), 0.5);\n}\n\n/**\n * Test saving and loading of GMM HMMs\n */\nBOOST_AUTO_TEST_CASE(GMMHMMLoadSaveTest)\n{\n  // Create a GMM HMM, save it, and load it.\n  HMM<GMM> hmm(3, GMM(4, 3));\n\n  for (size_t j = 0; j < hmm.Emission().size(); ++j)\n  {\n    hmm.Emission()[j].Weights().randu();\n    for (size_t i = 0; i < hmm.Emission()[j].Gaussians(); ++i)\n    {\n      hmm.Emission()[j].Component(i).Mean().randu();\n      arma::mat covariance = arma::randu<arma::mat>(\n          hmm.Emission()[j].Component(i).Covariance().n_rows,\n          hmm.Emission()[j].Component(i).Covariance().n_cols);\n      covariance *= covariance.t();\n      covariance += arma::eye<arma::mat>(covariance.n_rows, covariance.n_cols);\n      hmm.Emission()[j].Component(i).Covariance(std::move(covariance));\n    }\n  }\n\n  // Save the HMM.\n  {\n    std::ofstream ofs(\"test-hmm-save.xml\");\n    boost::archive::xml_oarchive ar(ofs);\n    ar << BOOST_SERIALIZATION_NVP(hmm);\n  }\n\n  // Load the HMM.\n  HMM<GMM> hmm2(3, GMM(4, 3));\n  {\n    std::ifstream ifs(\"test-hmm-save.xml\");\n    boost::archive::xml_iarchive ar(ifs);\n    ar >> BOOST_SERIALIZATION_NVP(hmm2);\n  }\n\n  // Remove clutter.\n  remove(\"test-hmm-save.xml\");\n\n  for (size_t j = 0; j < hmm.Emission().size(); ++j)\n  {\n    BOOST_REQUIRE_EQUAL(hmm.Emission()[j].Gaussians(),\n                        hmm2.Emission()[j].Gaussians());\n    BOOST_REQUIRE_EQUAL(hmm.Emission()[j].Dimensionality(),\n                        hmm2.Emission()[j].Dimensionality());\n\n    for (size_t i = 0; i < hmm.Emission()[j].Dimensionality(); ++i)\n      BOOST_REQUIRE_CLOSE(hmm.Emission()[j].Weights()[i],\n                          hmm2.Emission()[j].Weights()[i], 1e-3);\n\n    for (size_t i = 0; i < hmm.Emission()[j].Gaussians(); ++i)\n    {\n      for (size_t l = 0; l < hmm.Emission()[j].Dimensionality(); ++l)\n      {\n        BOOST_REQUIRE_CLOSE(hmm.Emission()[j].Component(i).Mean()[l],\n            hmm2.Emission()[j].Component(i).Mean()[l], 1e-3);\n\n        for (size_t k = 0; k < hmm.Emission()[j].Dimensionality(); ++k)\n        {\n          BOOST_REQUIRE_CLOSE(hmm.Emission()[j].Component(i).Covariance()(l, k),\n              hmm2.Emission()[j].Component(i).Covariance()(l, k), 1e-3);\n        }\n      }\n    }\n  }\n}\n\n/**\n * Test saving and loading of Gaussian HMMs\n */\nBOOST_AUTO_TEST_CASE(GaussianHMMLoadSaveTest)\n{\n  // Create a Gaussian HMM, save it, and load it.\n  HMM<GaussianDistribution> hmm(3, GaussianDistribution(2));\n\n  for (size_t j = 0; j < hmm.Emission().size(); ++j)\n  {\n    hmm.Emission()[j].Mean().randu();\n    arma::mat covariance = arma::randu<arma::mat>(\n        hmm.Emission()[j].Covariance().n_rows,\n        hmm.Emission()[j].Covariance().n_cols);\n    covariance *= covariance.t();\n    covariance += arma::eye<arma::mat>(covariance.n_rows, covariance.n_cols);\n    hmm.Emission()[j].Covariance(std::move(covariance));\n  }\n\n  // Save the HMM.\n  {\n    std::ofstream ofs(\"test-hmm-save.xml\");\n    boost::archive::xml_oarchive ar(ofs);\n    ar << BOOST_SERIALIZATION_NVP(hmm);\n  }\n\n  // Load the HMM.\n  HMM<GaussianDistribution> hmm2(3, GaussianDistribution(2));\n  {\n    std::ifstream ifs(\"test-hmm-save.xml\");\n    boost::archive::xml_iarchive ar(ifs);\n    ar >> BOOST_SERIALIZATION_NVP(hmm2);\n  }\n\n  // Remove clutter.\n  remove(\"test-hmm-save.xml\");\n\n  for (size_t j = 0; j < hmm.Emission().size(); ++j)\n  {\n    BOOST_REQUIRE_EQUAL(hmm.Emission()[j].Dimensionality(),\n                        hmm2.Emission()[j].Dimensionality());\n\n    for (size_t i = 0; i < hmm.Emission()[j].Dimensionality(); ++i)\n    {\n      BOOST_REQUIRE_CLOSE(hmm.Emission()[j].Mean()[i],\n          hmm2.Emission()[j].Mean()[i], 1e-3);\n      for (size_t k = 0; k < hmm.Emission()[j].Dimensionality(); ++k)\n      {\n        BOOST_REQUIRE_CLOSE(hmm.Emission()[j].Covariance()(i, k),\n            hmm2.Emission()[j].Covariance()(i, k), 1e-3);\n      }\n    }\n  }\n}\n\n/**\n * Test saving and loading of Discrete HMMs\n */\nBOOST_AUTO_TEST_CASE(DiscreteHMMLoadSaveTest)\n{\n  // Create a Discrete HMM, save it, and load it.\n  std::vector<DiscreteDistribution> emission(4);\n  emission[0].Probabilities() = arma::randu<arma::vec>(6);\n  emission[0].Probabilities() /= accu(emission[0].Probabilities());\n  emission[1].Probabilities() = arma::randu<arma::vec>(6);\n  emission[1].Probabilities() /= accu(emission[1].Probabilities());\n  emission[2].Probabilities() = arma::randu<arma::vec>(6);\n  emission[2].Probabilities() /= accu(emission[2].Probabilities());\n  emission[3].Probabilities() = arma::randu<arma::vec>(6);\n  emission[3].Probabilities() /= accu(emission[3].Probabilities());\n\n\n  // Create HMM object.\n  HMM<DiscreteDistribution> hmm(3, DiscreteDistribution(3));\n\n\n  for (size_t j = 0; j < hmm.Emission().size(); ++j)\n  {\n    hmm.Emission()[j].Probabilities() = arma::randu<arma::vec>(3);\n    hmm.Emission()[j].Probabilities() /= accu(emission[j].Probabilities());\n  }\n\n  // Save the HMM.\n  {\n    std::ofstream ofs(\"test-hmm-save.xml\");\n    boost::archive::xml_oarchive ar(ofs);\n    ar << BOOST_SERIALIZATION_NVP(hmm);\n  }\n\n  // Load the HMM.\n  HMM<DiscreteDistribution> hmm2(3, DiscreteDistribution(3));\n  {\n    std::ifstream ifs(\"test-hmm-save.xml\");\n    boost::archive::xml_iarchive ar(ifs);\n    ar >> BOOST_SERIALIZATION_NVP(hmm2);\n  }\n\n  // Remove clutter.\n  remove(\"test-hmm-save.xml\");\n\n  for (size_t j = 0; j < hmm.Emission().size(); ++j)\n    for (size_t i = 0; i < hmm.Emission()[j].Probabilities().n_elem; ++i)\n      BOOST_REQUIRE_CLOSE(hmm.Emission()[j].Probabilities()[i],\n          hmm2.Emission()[j].Probabilities()[i], 1e-3);\n}\n\n/********************************************/\n/** DiagonalGMM Hidden Markov Models Tests **/\n/********************************************/\n\n//! Make sure the prediction of DiagonalGMM HMMs is reasonable.\nBOOST_AUTO_TEST_CASE(DiagonalGMMHMMPredictTest)\n{\n  // This test is probabilistic, so we perform it three times to make it robust.\n  bool success = false;\n  for (size_t trial = 0; trial < 3; trial++)\n  {\n    std::vector<DiagonalGMM> gmms(2);\n    gmms[0] = DiagonalGMM(2, 2);\n\n    gmms[0].Component(0) = DiagonalGaussianDistribution(\"3.25 2.10\",\n        \"0.97 1.00\");\n    gmms[0].Component(1) = DiagonalGaussianDistribution(\"5.03 7.28\",\n        \"1.20 0.89\");\n\n    gmms[1] = DiagonalGMM(3, 2);\n    gmms[1].Weights() = arma::vec(\"0.3 0.2 0.5\");\n    gmms[1].Component(0) = DiagonalGaussianDistribution(\"-2.48 -3.02\",\n        \"1.02 0.80\");\n    gmms[1].Component(1) = DiagonalGaussianDistribution(\"-1.24 -2.40\",\n        \"0.85 0.78\");\n    gmms[1].Component(2) = DiagonalGaussianDistribution(\"-5.68 -4.83\",\n        \"1.42 0.96\");\n\n    // Initial probabilities.\n    arma::vec initial(\"1 0\");\n\n    // Transition matrix.\n    arma::mat transProb(\"0.40 0.70;\"\n                        \"0.60 0.30\");\n\n    // Build the model.\n    HMM<DiagonalGMM> hmm(initial, transProb, gmms);\n\n    // Make a sequence of observations according to transition probabilities.\n    arma::mat observations(2, 1000);\n    arma::Row<size_t> states(1000);\n\n    // Set initial state to zero.\n    states[0] = 0;\n    observations.col(0) = gmms[0].Random();\n\n    for (size_t i = 1; i < 1000; i++)\n    {\n      double randValue = math::Random();\n\n      if (randValue <= transProb(0, states[i - 1]))\n        states[i] = 0;\n      else\n        states[i] = 1;\n\n      observations.col(i) = gmms[states[i]].Random();\n    }\n\n    // Predict the most probable hidden state sequence.\n    arma::Row<size_t> predictions;\n    hmm.Predict(observations, predictions);\n\n    // Check them.\n    success = true;\n    for (size_t i = 0; i < 1000; i++)\n    {\n      if (predictions[i] != states[i])\n      {\n        success = false;\n        break;\n      }\n    }\n\n    if (success)\n      break;\n  }\n\n  BOOST_REQUIRE_EQUAL(success, true);\n}\n\n/**\n * Make sure a random data sequence generation is correct when the emission\n * distribution is DiagonalGMM.\n */\nBOOST_AUTO_TEST_CASE(DiagonalGMMHMMGenerateTest)\n{\n  // Build the model.\n  HMM<DiagonalGaussianDistribution> hmm(3, DiagonalGaussianDistribution(2));\n  hmm.Transition() = arma::mat(\"0.2 0.3 0.8;\"\n                               \"0.4 0.5 0.1;\"\n                               \"0.4 0.2 0.1\");\n\n  hmm.Emission()[0] = DiagonalGaussianDistribution(\"0.0 0.0\", \"1.0 0.7\");\n  hmm.Emission()[1] = DiagonalGaussianDistribution(\"1.0 1.0\", \"0.7 0.5\");\n  hmm.Emission()[2] = DiagonalGaussianDistribution(\"-3.0 2.0\", \"2.0 0.3\");\n\n  // Now we will generate a long sequence.\n  std::vector<arma::mat> observations(1);\n  std::vector<arma::Row<size_t> > states(1);\n\n  // Generate a random data sequence.\n  hmm.Generate(10000, observations[0], states[0], 1);\n\n  // Build the hmm2.\n  HMM<DiagonalGaussianDistribution> hmm2(3, DiagonalGaussianDistribution(2));\n\n  // Now estimate the HMM from the generated sequence.\n  hmm2.Train(observations, states);\n\n  // Check that the estimated matrices are the same.\n  BOOST_REQUIRE_LT(arma::norm(hmm.Transition() - hmm2.Transition()), 0.05);\n\n  // Check that each Gaussian is the same.\n  for (size_t dist = 0; dist < 3; dist++)\n  {\n    BOOST_REQUIRE_LT(arma::norm(hmm.Emission()[dist].Mean() -\n        hmm2.Emission()[dist].Mean()), 0.1);\n    BOOST_REQUIRE_LT(arma::norm(hmm.Emission()[dist].Covariance() -\n        hmm2.Emission()[dist].Covariance()), 0.2);\n  }\n}\n\n/**\n * Make sure the unlabeled 1-state training works reasonably given a single\n * distribution with diagonal covariance.\n */\nBOOST_AUTO_TEST_CASE(DiagonalGMMHMMOneGaussianOneStateTrainingTest)\n{\n  // Create a Gaussian distribution with diagonal covariance.\n  DiagonalGaussianDistribution d(\"2.05 3.45\", \"0.89 1.05\");\n\n  // Make a sequence of observations.\n  std::vector<arma::mat> observations(1, arma::mat(2, 5000));\n  for (size_t obs = 0; obs < 1; obs++)\n  {\n    observations[obs].col(0) = d.Random();\n\n    for (size_t i = 1; i < 5000; i++)\n    {\n      observations[obs].col(i) = d.Random();\n    }\n  }\n\n  // Build the model.\n  HMM<DiagonalGMM> hmm(1, DiagonalGMM(1, 2));\n\n  // Train with observations.\n  hmm.Train(observations);\n\n  // Generate the ground truth values.\n  arma::vec actualMean = arma::mean(observations[0], 1);\n  arma::vec actualCovar = arma::diagvec(\n      arma::ccov(observations[0], 1 /* biased estimator */));\n\n  // Check the model to see that it is correct.\n  CheckMatrices(hmm.Emission()[0].Component(0).Mean(), actualMean);\n  CheckMatrices(hmm.Emission()[0].Component(0).Covariance(), actualCovar);\n}\n\n/**\n * Make sure the unlabeled training works reasonably given a single\n * distribution with diagonal covariance.\n */\nBOOST_AUTO_TEST_CASE(DiagonalGMMHMMOneGaussianUnlabeledTrainingTest)\n{\n  // Create a sequence of DiagonalGMMs. Each GMM has one gaussian distribution.\n  std::vector<DiagonalGMM> gmms(2, DiagonalGMM(1, 2));\n  gmms[0].Component(0) = DiagonalGaussianDistribution(\"1.25 2.10\",\n      \"0.97 1.00\");\n\n  gmms[1].Component(0) = DiagonalGaussianDistribution(\"-2.48 -3.02\",\n      \"1.02 0.80\");\n\n  // Transition matrix.\n  arma::mat transProbs(\"0.30 0.80;\"\n                       \"0.70 0.20\");\n\n  arma::vec initialProb(\"1 0\");\n\n  // Make a sequence of observations.\n  std::vector<arma::mat> observations(2, arma::mat(2, 500));\n  std::vector<arma::Row<size_t>> states(2, arma::Row<size_t>(500));\n  for (size_t obs = 0; obs < 2; obs++)\n  {\n    states[obs][0] = 0;\n    observations[obs].col(0) = gmms[0].Random();\n\n    for (size_t i = 1; i < 500; i++)\n    {\n      double randValue = math::Random();\n\n      if (randValue <= transProbs(0, states[obs][i - 1]))\n        states[obs][i] = 0;\n      else\n        states[obs][i] = 1;\n\n      observations[obs].col(i) = gmms[states[obs][i]].Random();\n    }\n  }\n\n  // Build the model.\n  HMM<DiagonalGMM> hmm(initialProb, transProbs, gmms);\n\n  // Train the model. If labels are not given, when training GMM, the estimated\n  // probabilities based on the forward and backward probabilities is used.\n  hmm.Train(observations);\n\n  // Check the initial weights.\n  BOOST_REQUIRE_CLOSE(hmm.Initial()[0], 1.0, 0.01);\n  BOOST_REQUIRE_SMALL(hmm.Initial()[1], 0.01);\n\n  // Check the transition probability matrix.\n  for (size_t i = 0; i < 2; i++)\n    for (size_t j = 0; j < 2; j++)\n      BOOST_REQUIRE_SMALL(hmm.Transition()(i, j) - transProbs(i, j), 0.08);\n\n  // Check the estimated weights of the each emission distribution.\n  for (size_t i = 0; i < 2; i++)\n    BOOST_REQUIRE_SMALL(hmm.Emission()[i].Weights()[0] - gmms[i].Weights()[0],\n        0.08);\n\n  // Check the estimated means of the each emission distribution.\n  for (size_t i = 0; i < 2; i++)\n    BOOST_REQUIRE_LT(arma::norm(hmm.Emission()[i].Component(0).Mean() -\n        gmms[i].Component(0).Mean()), 0.2);\n\n  // Check the estimated covariances of the each emission distribution.\n  for (size_t i = 0; i < 2; i++)\n    BOOST_REQUIRE_LT(arma::norm(hmm.Emission()[i].Component(0).Covariance() -\n        gmms[i].Component(0).Covariance()), 0.5);\n}\n\n/**\n * Make sure the labeled training works reasonably given a single distribution\n * with diagonal covariance.\n */\nBOOST_AUTO_TEST_CASE(DiagonalGMMHMMOneGaussianLabeledTrainingTest)\n{\n  // Create a sequence of DiagonalGMMs.\n  std::vector<DiagonalGMM> gmms(3, DiagonalGMM(1, 2));\n  gmms[0].Component(0) = DiagonalGaussianDistribution(\"5.25 7.10\",\n      \"0.97 1.00\");\n\n  gmms[1].Component(0) = DiagonalGaussianDistribution(\"4.48 6.02\",\n      \"1.02 0.80\");\n\n  gmms[2].Component(0) = DiagonalGaussianDistribution(\"-3.28 -5.30\",\n      \"0.87 1.05\");\n\n  // Transition matrix.\n  arma::mat transProbs(\"0.2 0.4 0.4;\"\n                       \"0.3 0.4 0.3;\"\n                       \"0.5 0.2 0.3\");\n\n  arma::vec initialProb(\"1 0 0\");\n\n  // Make a sequence of observations.\n  std::vector<arma::mat> observations(3, arma::mat(2, 5000));\n  std::vector<arma::Row<size_t>> states(3, arma::Row<size_t>(5000));\n  for (size_t obs = 0; obs < 3; obs++)\n  {\n    states[obs][0] = 0;\n    observations[obs].col(0) = gmms[0].Random();\n\n    for (size_t i = 1; i < 5000; i++)\n    {\n      double randValue = math::Random();\n      double probSum = 0;\n      for (size_t state = 0; state < 3; state++)\n      {\n        probSum += transProbs(state, states[obs][i - 1]);\n        if (randValue <= probSum)\n        {\n          states[obs][i] = state;\n          break;\n        }\n      }\n\n      observations[obs].col(i) = gmms[states[obs][i]].Random();\n    }\n  }\n\n  // Build the model.\n  HMM<DiagonalGMM> hmm(3, DiagonalGMM(1, 2));\n\n  // Train the model.\n  hmm.Train(observations, states);\n\n  // Check the initial weights.\n  BOOST_REQUIRE_CLOSE(hmm.Initial()[0], 1.0, 0.01);\n  BOOST_REQUIRE_SMALL(hmm.Initial()[1], 0.01);\n  BOOST_REQUIRE_SMALL(hmm.Initial()[2], 0.01);\n\n  // Check the transition probability matrix.\n  for (size_t i = 0; i < 3; i++)\n    for (size_t j = 0; j < 3; j++)\n      BOOST_REQUIRE_SMALL(hmm.Transition()(i, j) - transProbs(i, j), 0.03);\n\n  // Check the estimated weights of the each emission distribution.\n  for (size_t i = 0; i < 3; i++)\n    BOOST_REQUIRE_SMALL(hmm.Emission()[i].Weights()[0] - gmms[i].Weights()[0],\n        0.08);\n\n  // Check the estimated means of the each emission distribution.\n  for (size_t i = 0; i < 3; i++)\n    BOOST_REQUIRE_LT(arma::norm(hmm.Emission()[i].Component(0).Mean() -\n        gmms[i].Component(0).Mean()), 0.2);\n\n  // Check the estimated covariances of the each emission distribution.\n  for (size_t i = 0; i < 3; i++)\n    BOOST_REQUIRE_LT(arma::norm(hmm.Emission()[i].Component(0).Covariance() -\n        gmms[i].Component(0).Covariance()), 0.5);\n}\n\n/**\n * Make sure the unlabeled training works reasonably given multiple\n * distributions with diagonal covariance.\n */\nBOOST_AUTO_TEST_CASE(DiagonalGMMHMMMultipleGaussiansUnlabeledTrainingTest)\n{\n  // Create a sequence of DiagonalGMMs.\n  std::vector<DiagonalGMM> gmms(2, DiagonalGMM(2, 2));\n  gmms[0].Weights() = arma::vec(\"0.3 0.7\");\n  gmms[0].Component(0) = DiagonalGaussianDistribution(\"8.25 7.10\",\n      \"0.97 1.00\");\n  gmms[0].Component(1) = DiagonalGaussianDistribution(\"-3.03 -2.28\",\n      \"1.20 0.89\");\n\n  gmms[1].Weights() = arma::vec(\"0.4 0.6\");\n  gmms[1].Component(0) = DiagonalGaussianDistribution(\"4.48 6.02\",\n        \"1.02 0.80\");\n  gmms[1].Component(1) = DiagonalGaussianDistribution(\"-9.24 -8.40\",\n        \"0.85 1.58\");\n\n  // Transition matrix.\n  arma::mat transProbs(\"0.30 0.40;\"\n                       \"0.70 0.60\");\n\n  arma::vec initialProb(\"1 0\");\n\n  // Make a sequence of observations.\n  std::vector<arma::mat> observations(2, arma::mat(2, 1000));\n  std::vector<arma::Row<size_t>> states(2, arma::Row<size_t>(1000));\n  for (size_t obs = 0; obs < 2; obs++)\n  {\n    states[obs][0] = 0;\n    observations[obs].col(0) = gmms[0].Random();\n\n    for (size_t i = 1; i < 1000; i++)\n    {\n      double randValue = math::Random();\n\n      if (randValue <= transProbs(0, states[obs][i - 1]))\n        states[obs][i] = 0;\n      else\n        states[obs][i] = 1;\n\n      observations[obs].col(i) = gmms[states[obs][i]].Random();\n    }\n  }\n\n  // Build the model.\n  HMM<DiagonalGMM> hmm(initialProb, transProbs, gmms);\n\n  // Train the model. If labels are not given, when training GMM, the estimated\n  // probabilities based on the forward and backward probabilities is used.\n  hmm.Train(observations);\n\n  // Check the initial weights.\n  BOOST_REQUIRE_CLOSE(hmm.Initial()[0], 1.0, 0.01);\n  BOOST_REQUIRE_SMALL(hmm.Initial()[1], 0.01);\n\n  // Check the transition probability matrix.\n  for (size_t i = 0; i < 2; i++)\n    for (size_t j = 0; j < 2; j++)\n      BOOST_REQUIRE_SMALL(hmm.Transition()(i, j) - transProbs(i, j), 0.08);\n\n  // Sort by the estimated weights of the first emission distribution.\n  arma::uvec sortedIndices = sort_index(hmm.Emission()[0].Weights());\n\n  // Check the first emission distribution.\n  for (size_t i = 0; i < 2; i++)\n  {\n    // Check the estimated weights using the first DiagonalGMM.\n    BOOST_REQUIRE_SMALL(hmm.Emission()[0].Weights()[sortedIndices[i]] -\n        gmms[0].Weights()[i], 0.08);\n\n    // Check the estimated means using the first DiagonalGMM.\n    BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[0].Component(sortedIndices[i]).Mean() -\n      gmms[0].Component(i).Mean()), 0.35);\n\n    // Check the estimated covariances using the first DiagonalGMM.\n    BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[0].Component(sortedIndices[i]).Covariance() -\n      gmms[0].Component(i).Covariance()), 0.6);\n  }\n\n  // Sort by the estimated weights of the second emission distribution.\n  sortedIndices = sort_index(hmm.Emission()[1].Weights());\n\n  // Check the second emission distribution.\n  for (size_t i = 0; i < 2; i++)\n  {\n    // Check the estimated weights using the second DiagonalGMM.\n    BOOST_REQUIRE_SMALL(hmm.Emission()[1].Weights()[sortedIndices[i]] -\n        gmms[1].Weights()[i], 0.08);\n\n    // Check the estimated means using the second DiagonalGMM.\n    BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[1].Component(sortedIndices[i]).Mean() -\n      gmms[1].Component(i).Mean()), 0.35);\n\n    // Check the estimated covariances using the second DiagonalGMM.\n    BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[1].Component(sortedIndices[i]).Covariance() -\n      gmms[1].Component(i).Covariance()), 0.6);\n  }\n}\n\n/**\n * Make sure the labeled training works reasonably given multiple distributions\n * with diagonal covariance.\n */\nBOOST_AUTO_TEST_CASE(DiagonalGMMHMMMultipleGaussiansLabeledTrainingTest)\n{\n  math::RandomSeed(std::time(NULL));\n  // Create a sequence of DiagonalGMMs.\n  std::vector<DiagonalGMM> gmms(2, DiagonalGMM(2, 2));\n  gmms[0].Weights() = arma::vec(\"0.3 0.7\");\n  gmms[0].Component(0) = DiagonalGaussianDistribution(\"2.25 5.30\",\n      \"0.97 1.00\");\n  gmms[0].Component(1) = DiagonalGaussianDistribution(\"-3.15 -2.50\",\n      \"1.20 0.89\");\n\n  gmms[1].Weights() = arma::vec(\"0.4 0.6\");\n  gmms[1].Component(0) = DiagonalGaussianDistribution(\"-4.48 -6.30\",\n        \"1.02 0.80\");\n  gmms[1].Component(1) = DiagonalGaussianDistribution(\"5.24 2.40\",\n        \"0.85 1.58\");\n\n  // Transition matrix.\n  arma::mat transProbs(\"0.30 0.80;\"\n                       \"0.70 0.20\");\n\n  // Make a sequence of observations.\n  std::vector<arma::mat> observations(5, arma::mat(2, 2500));\n  std::vector<arma::Row<size_t>> states(5, arma::Row<size_t>(2500));\n  for (size_t obs = 0; obs < 5; obs++)\n  {\n    states[obs][0] = 0;\n    observations[obs].col(0) = gmms[0].Random();\n\n    for (size_t i = 1; i < 2500; i++)\n    {\n      double randValue = math::Random();\n\n      if (randValue <= transProbs(0, states[obs][i - 1]))\n        states[obs][i] = 0;\n      else\n        states[obs][i] = 1;\n\n      observations[obs].col(i) = gmms[states[obs][i]].Random();\n    }\n  }\n\n  // Build the model.\n  HMM<DiagonalGMM> hmm(2, DiagonalGMM(2, 2));\n\n  // Train the model.\n  hmm.Train(observations, states);\n\n  // Check the initial weights.\n  BOOST_REQUIRE_CLOSE(hmm.Initial()[0], 1.0, 0.01);\n  BOOST_REQUIRE_SMALL(hmm.Initial()[1], 0.01);\n\n  // Check the transition probability matrix.\n  for (size_t i = 0; i < 2; i++)\n    for (size_t j = 0; j < 2; j++)\n      BOOST_REQUIRE_SMALL(hmm.Transition()(i, j) - transProbs(i, j), 0.03);\n\n  // Sort by the estimated weights of the first emission distribution.\n  arma::uvec sortedIndices = sort_index(hmm.Emission()[0].Weights());\n\n  // Check the first emission distribution.\n  for (size_t i = 0; i < 2; i++)\n  {\n    // Check the estimated weights using the first DiagonalGMM.\n    BOOST_REQUIRE_SMALL(hmm.Emission()[0].Weights()[sortedIndices[i]] -\n        gmms[0].Weights()[i], 0.08);\n\n    // Check the estimated means using the first DiagonalGMM.\n    BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[0].Component(sortedIndices[i]).Mean() -\n      gmms[0].Component(i).Mean()), 0.2);\n\n    // Check the estimated covariances using the first DiagonalGMM.\n    BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[0].Component(sortedIndices[i]).Covariance() -\n      gmms[0].Component(i).Covariance()), 0.5);\n  }\n\n  // Sort by the estimated weights of the second emission distribution.\n  sortedIndices = sort_index(hmm.Emission()[1].Weights());\n\n  // Check the second emission distribution.\n  for (size_t i = 0; i < 2; i++)\n  {\n    // Check the estimated weights using the second DiagonalGMM.\n    BOOST_REQUIRE_SMALL(hmm.Emission()[1].Weights()[sortedIndices[i]] -\n        gmms[1].Weights()[i], 0.08);\n\n    // Check the estimated means using the second DiagonalGMM.\n    BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[1].Component(sortedIndices[i]).Mean() -\n      gmms[1].Component(i).Mean()), 0.2);\n\n    // Check the estimated covariances using the second DiagonalGMM.\n    BOOST_REQUIRE_LT(arma::norm(\n      hmm.Emission()[1].Component(sortedIndices[i]).Covariance() -\n      gmms[1].Component(i).Covariance()), 0.5);\n  }\n}\n\n/**\n * Make sure loading and saving the model is correct.\n */\nBOOST_AUTO_TEST_CASE(DiagonalGMMHMMLoadSaveTest)\n{\n  // Create a GMM HMM, save and load it.\n  HMM<DiagonalGMM> hmm(3, DiagonalGMM(4, 3));\n\n  // Generate intial random values.\n  for (size_t j = 0; j < hmm.Emission().size(); j++)\n  {\n    hmm.Emission()[j].Weights().randu();\n    for (size_t i = 0; i < hmm.Emission()[j].Gaussians(); i++)\n    {\n      hmm.Emission()[j].Component(i).Mean().randu();\n      arma::vec covariance = arma::randu<arma::vec>(\n          hmm.Emission()[j].Component(i).Covariance().n_elem);\n\n      covariance += arma::ones<arma::vec>(covariance.n_elem);\n      hmm.Emission()[j].Component(i).Covariance(std::move(covariance));\n    }\n  }\n\n  // Save the HMM.\n  {\n    std::ofstream ofs(\"test-hmm-save.xml\");\n    boost::archive::xml_oarchive ar(ofs);\n    ar << BOOST_SERIALIZATION_NVP(hmm);\n  }\n\n  // Load the HMM.\n  HMM<DiagonalGMM> hmm2(3, DiagonalGMM(4, 3));\n  {\n    std::ifstream ifs(\"test-hmm-save.xml\");\n    boost::archive::xml_iarchive ar(ifs);\n    ar >> BOOST_SERIALIZATION_NVP(hmm2);\n  }\n\n  // Remove clutter.\n  remove(\"test-hmm-save.xml\");\n\n  for (size_t j = 0; j < hmm.Emission().size(); j++)\n  {\n    // Check the number of Gaussians.\n    BOOST_REQUIRE_EQUAL(hmm.Emission()[j].Gaussians(),\n                        hmm2.Emission()[j].Gaussians());\n\n    // Check the dimensionality.\n    BOOST_REQUIRE_EQUAL(hmm.Emission()[j].Dimensionality(),\n                        hmm2.Emission()[j].Dimensionality());\n\n    for (size_t i = 0; i < hmm.Emission()[j].Dimensionality(); i++)\n      // Check the weights.\n      BOOST_REQUIRE_CLOSE(hmm.Emission()[j].Weights()[i],\n                          hmm2.Emission()[j].Weights()[i], 1e-3);\n\n    for (size_t i = 0; i < hmm.Emission()[j].Gaussians(); i++)\n    {\n      for (size_t l = 0; l < hmm.Emission()[j].Dimensionality(); l++)\n      {\n        // Check the means.\n        BOOST_REQUIRE_CLOSE(hmm.Emission()[j].Component(i).Mean()[l],\n            hmm2.Emission()[j].Component(i).Mean()[l], 1e-3);\n\n        // Check the covariances.\n        BOOST_REQUIRE_CLOSE(hmm.Emission()[j].Component(i).Covariance()[l],\n            hmm2.Emission()[j].Component(i).Covariance()[l], 1e-3);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "3b7f838f393d666ca355258f821ba5a501de6590", "size": 61749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/hmm_test.cpp", "max_stars_repo_name": "Dhawgupta/mlpack", "max_stars_repo_head_hexsha": "945e29cbcfeb6fa1c06bd360d5d818f62a863134", "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/hmm_test.cpp", "max_issues_repo_name": "Dhawgupta/mlpack", "max_issues_repo_head_hexsha": "945e29cbcfeb6fa1c06bd360d5d818f62a863134", "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/hmm_test.cpp", "max_forks_repo_name": "Dhawgupta/mlpack", "max_forks_repo_head_hexsha": "945e29cbcfeb6fa1c06bd360d5d818f62a863134", "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": 33.7610716238, "max_line_length": 80, "alphanum_fraction": 0.611135403, "num_tokens": 20577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.536911348359251}}
{"text": "#ifndef PA_MATH_TYPES_HPP\n#define PA_MATH_TYPES_HPP\n\n#define EIGEN_USE_MKL \n#define EIGEN_USE_MKL_ALL\n#define MKL_DIRECT_CALL \n\n#include <cstdint>\n\n#include <Eigen/Core>\n\nnamespace pa\n{\nusing scalar   = float          ;\nusing vector2  = Eigen::Vector2f;\nusing vector3  = Eigen::Vector3f;\nusing vector4  = Eigen::Vector4f;\n\nusing integer  = std::int32_t   ;\nusing ivector2 = Eigen::Vector2i;\nusing ivector3 = Eigen::Vector3i;\nusing ivector4 = Eigen::Vector4i;\n\nusing matrix2  = Eigen::Matrix2f;\nusing matrix3  = Eigen::Matrix3f;\nusing matrix4  = Eigen::Matrix4f;\n\nusing imatrix2 = Eigen::Matrix2i;\nusing imatrix3 = Eigen::Matrix3i;\nusing imatrix4 = Eigen::Matrix4i;\n}\n\n#endif", "meta": {"hexsha": "462950daf2510d0ecebe3ca7608f274e9b313601", "size": 674, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pa/include/pa/math/types.hpp", "max_stars_repo_name": "acdemiralp/pars", "max_stars_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-12T18:20:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T12:04:14.000Z", "max_issues_repo_path": "pa/include/pa/math/types.hpp", "max_issues_repo_name": "acdemiralp/pars", "max_issues_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pa/include/pa/math/types.hpp", "max_forks_repo_name": "acdemiralp/pars", "max_forks_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-18T14:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T14:35:49.000Z", "avg_line_length": 20.4242424242, "max_line_length": 33, "alphanum_fraction": 0.7403560831, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5369113467892438}}
{"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#include \"toplevelfixture.hpp\"\n#include <boost/test/unit_test.hpp>\n#include <ql/currencies/europe.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <qle/instruments/payment.hpp>\n#include <qle/pricingengines/paymentdiscountingengine.hpp>\n\n#include <boost/make_shared.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace boost::unit_test_framework;\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(PaymentTest)\n\nBOOST_AUTO_TEST_CASE(testDomesicPayment) {\n\n    BOOST_TEST_MESSAGE(\"Testing Domestic Payment NPV...\");\n\n    SavedSettings backup;\n\n    Date refDate = Date(8, Dec, 2016);\n    Settings::instance().evaluationDate() = refDate;\n    Date paymentDate = refDate + 10 * Years;\n    Payment payment(100.0, EURCurrency(), paymentDate);\n    Handle<YieldTermStructure> yts(boost::make_shared<FlatForward>(0, TARGET(), 0.03, ActualActual()));\n    boost::shared_ptr<PricingEngine> engine = boost::make_shared<PaymentDiscountingEngine>(yts);\n    payment.setPricingEngine(engine);\n\n    Real expectedNpv = 100.0 * yts->discount(paymentDate);\n\n    BOOST_CHECK_SMALL(payment.NPV() - expectedNpv, 0.000001);\n}\n\nBOOST_AUTO_TEST_CASE(testForeignPayment) {\n\n    BOOST_TEST_MESSAGE(\"Testing Foreign Payment NPV...\");\n\n    SavedSettings backup;\n\n    Date refDate = Date(8, Dec, 2016);\n    Settings::instance().evaluationDate() = refDate;\n    Date paymentDate = refDate + 10 * Years;\n    Payment payment(100.0, EURCurrency(), paymentDate);\n    Handle<YieldTermStructure> yts(boost::make_shared<FlatForward>(0, TARGET(), 0.03, ActualActual()));\n    Handle<Quote> fx(boost::make_shared<SimpleQuote>(0.789));\n    boost::shared_ptr<PricingEngine> engine = boost::make_shared<PaymentDiscountingEngine>(yts, fx);\n    payment.setPricingEngine(engine);\n\n    Real expectedNpv = 100.0 * yts->discount(paymentDate) * fx->value();\n\n    BOOST_CHECK_SMALL(payment.NPV() - expectedNpv, 0.000001);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "03f746116b2d4063c61a9b4abf1fe666cd918d27", "size": 2882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/payment.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/test/payment.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/test/payment.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": 35.5802469136, "max_line_length": 103, "alphanum_fraction": 0.761276891, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5369113416557163}}
{"text": "\n// solving A * X = B\n// in two steps -- factor (getrf()) and solve (getrs())\n\n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <cstddef>\n#include <iostream>\n#include <boost/numeric/bindings/blas.hpp>\n#include <boost/numeric/bindings/lapack/computational/getrf.hpp>\n#include <boost/numeric/bindings/lapack/computational/getrs.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace blas = boost::numeric::bindings::blas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\n#ifndef F_ROW_MAJOR\ntypedef ublas::matrix<double, ublas::column_major> m_t;\n#else\ntypedef ublas::matrix<double, ublas::row_major> m_t;\n#endif\n\nint main() {\n\n  cout << endl; \n\n  size_t n = 5; \n  m_t a (n, n);   // system matrix \n\n  size_t nrhs = 2; \n  m_t x (n, nrhs); \n  // b -- right-hand side matrix:\n  // .. see leading comments for `gesv()' in clapack.hpp\n#ifndef F_ROW_MAJOR\n  m_t b (n, nrhs);\n#else\n  m_t b (nrhs, n);\n#endif\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  ublas::matrix_row<m_t> ar1 (a, 0), ar3 (a, 3);\n  swap (ar1, ar3);   // swap rows to force pivoting \n\n  ublas::matrix_column<m_t> xc0 (x, 0), xc1 (x, 1); \n  blas::set (1., xc0);  // x[.,0] = 1\n  blas::set (2., xc1);  // x[.,1] = 2\n#ifndef F_ROW_MAJOR\n  blas::gemm ( 1.0, a, x, 0.0, b);  // b = a x, so we know the result ;o) \n#else\n  // see leading comments for `gesv()' in clapack.hpp\n  ublas::matrix_row<m_t> br0 (b, 0), br1 (b, 1); \n  blas::gemv (a, xc0, br0);  // b[0,.] = a x[.,0]\n  blas::gemv (a, xc1, br1);  // b[1,.] = a x[.,1]  =>  b^T = a x\n#endif \n\n  print_m (a, \"A\"); \n  cout << endl; \n  print_m (b, \"B\"); \n  cout << endl; \n\n  std::vector<int> ipiv (n);  // pivot vector\n\n  lapack::getrf (a, ipiv);      // factor a\n  lapack::getrs (a, ipiv, b);   // solve from factorization \n  print_m (b, \"X\"); \n  cout << endl; \n\n  print_v (ipiv, \"pivots\"); \n\n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "51f38a58ce41a1f7180cf6163d3c432390dc7985", "size": 2195, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_getrf_getrs.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/atlas/ublas_getrf_getrs.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/atlas/ublas_getrf_getrs.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": 25.2298850575, "max_line_length": 74, "alphanum_fraction": 0.5954441913, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5368669059178997}}
{"text": "//\n// Created by vlad on 14.11.16.\n//\n\n#pragma once\n\n#include \"route_solver/structs/data_structs.hpp\"\n\n#include <Eigen/Core>\n\n#include <map>\n#include <vector>\n#include <set>\n\nnamespace rs {\n\nbool isPointInWorkZone(const point2d& pt, const std::vector<point2d>& workzone);\n\nclass VehicleTaskChecker {\n\npublic:\n\tVehicleTaskChecker(const std::vector <Vehicle>& venchiles,\n\t\t\t\t\t   const std::vector<Zone>& zones,\n\t\t\t\t\t   const std::vector <Task>& tasks);\n\n\tbool taskAcceptableForVenchile(std::uint32_t taskId, std::uint32_t venhileId) const;\n\n\tconst Eigen::MatrixXd& possibilityVehicleToTask() const;\n\nprivate:\n\tEigen::MatrixXd m_possibilityVehicleToTask;\n\n};\n\n}\n", "meta": {"hexsha": "47c0e9bfb65c20190d13fac549b430515cd829d3", "size": 659, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/route_solver/include/route_solver/solve/vehicle_to_task_checker.hpp", "max_stars_repo_name": "antlad/route_solver_service", "max_stars_repo_head_hexsha": "a6a24766066e2da734079fb25e216afad72ad14b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-03-28T09:34:22.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-30T16:30:49.000Z", "max_issues_repo_path": "libs/route_solver/include/route_solver/solve/vehicle_to_task_checker.hpp", "max_issues_repo_name": "antlad/route_solver_service", "max_issues_repo_head_hexsha": "a6a24766066e2da734079fb25e216afad72ad14b", "max_issues_repo_licenses": ["MIT"], "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/route_solver/include/route_solver/solve/vehicle_to_task_checker.hpp", "max_forks_repo_name": "antlad/route_solver_service", "max_forks_repo_head_hexsha": "a6a24766066e2da734079fb25e216afad72ad14b", "max_forks_repo_licenses": ["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.3055555556, "max_line_length": 85, "alphanum_fraction": 0.7329286798, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5368558450257372}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 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 \"cech_complex\"\n#include <boost/test/unit_test.hpp>\n\n#include <cmath>  // float comparison\n#include <limits>\n#include <string>\n#include <vector>\n#include <algorithm>  // std::max\n\n#include <gudhi/Cech_complex.h>\n// to construct Cech_complex from a OFF file of points\n#include <gudhi/Points_off_io.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/distance_functions.h>\n#include <gudhi/Unitary_tests_utils.h>\n#include <gudhi/Miniball.hpp>\n\n// Type definitions\nusing Simplex_tree = Gudhi::Simplex_tree<>;\nusing Filtration_value = Simplex_tree::Filtration_value;\nusing Point = std::vector<Filtration_value>;\nusing Point_cloud = std::vector<Point>;\nusing Points_off_reader = Gudhi::Points_off_reader<Point>;\nusing Cech_complex = Gudhi::cech_complex::Cech_complex<Simplex_tree, Point_cloud>;\n\nusing Point_iterator = Point_cloud::const_iterator;\nusing Coordinate_iterator = Point::const_iterator;\nusing Min_sphere = Gudhi::Miniball::Miniball<Gudhi::Miniball::CoordAccessor<Point_iterator, Coordinate_iterator>>;\n\nBOOST_AUTO_TEST_CASE(Cech_complex_for_documentation) {\n  // ----------------------------------------------------------------------------\n  //\n  // Init of a Cech complex from a point cloud\n  //\n  // ----------------------------------------------------------------------------\n  Point_cloud points;\n  points.push_back({1., 0.});                  // 0\n  points.push_back({0., 1.});                  // 1\n  points.push_back({2., 1.});                  // 2\n  points.push_back({3., 2.});                  // 3\n  points.push_back({0., 3.});                  // 4\n  points.push_back({3. + std::sqrt(3.), 3.});  // 5\n  points.push_back({1., 4.});                  // 6\n  points.push_back({3., 4.});                  // 7\n  points.push_back({2., 4. + std::sqrt(3.)});  // 8\n  points.push_back({0., 4.});                  // 9\n  points.push_back({-0.5, 2.});                // 10\n\n  Filtration_value max_radius = 1.0;\n  std::cout << \"========== NUMBER OF POINTS = \" << points.size() << \" - Cech max_radius = \" << max_radius\n            << \"==========\" << std::endl;\n\n  Cech_complex cech_complex_for_doc(points, max_radius);\n\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(cech_complex_for_doc.max_radius(), max_radius);\n  std::size_t i = 0;\n  for (; i < points.size(); i++) {\n    BOOST_CHECK(points[i] == cech_complex_for_doc.get_point(i));\n  }\n\n  const int DIMENSION_1 = 1;\n  Simplex_tree st;\n  cech_complex_for_doc.create_complex(st, DIMENSION_1);\n  std::cout << \"st.dimension()=\" << st.dimension() << std::endl;\n  BOOST_CHECK(st.dimension() == DIMENSION_1);\n\n  const int NUMBER_OF_VERTICES = 11;\n  std::cout << \"st.num_vertices()=\" << st.num_vertices() << std::endl;\n  BOOST_CHECK(st.num_vertices() == NUMBER_OF_VERTICES);\n\n  std::cout << \"st.num_simplices()=\" << st.num_simplices() << std::endl;\n  BOOST_CHECK(st.num_simplices() == 27);\n\n  // Check filtration values of vertices is 0.0\n  for (auto f_simplex : st.skeleton_simplex_range(0)) {\n    BOOST_CHECK(st.filtration(f_simplex) == 0.0);\n  }\n\n  // Check filtration values of edges\n  for (auto f_simplex : st.skeleton_simplex_range(DIMENSION_1)) {\n    if (DIMENSION_1 == st.dimension(f_simplex)) {\n      std::vector<Point> vp;\n      std::cout << \"vertex = (\";\n      for (auto vertex : st.simplex_vertex_range(f_simplex)) {\n        std::cout << vertex << \",\";\n        vp.push_back(points.at(vertex));\n      }\n      std::cout << \") - distance =\" << Gudhi::Minimal_enclosing_ball_radius()(vp.at(0), vp.at(1))\n                << \" - filtration =\" << st.filtration(f_simplex) << std::endl;\n      BOOST_CHECK(vp.size() == 2);\n      GUDHI_TEST_FLOAT_EQUALITY_CHECK(st.filtration(f_simplex),\n                                      Gudhi::Minimal_enclosing_ball_radius()(vp.at(0), vp.at(1)));\n    }\n  }\n\n  const int DIMENSION_2 = 2;\n\n#ifdef GUDHI_DEBUG\n  BOOST_CHECK_THROW(cech_complex_for_doc.create_complex(st, DIMENSION_2), std::invalid_argument);\n#endif\n\n  Simplex_tree st2;\n  cech_complex_for_doc.create_complex(st2, DIMENSION_2);\n  std::cout << \"st2.dimension()=\" << st2.dimension() << std::endl;\n  BOOST_CHECK(st2.dimension() == DIMENSION_2);\n\n  std::cout << \"st2.num_vertices()=\" << st2.num_vertices() << std::endl;\n  BOOST_CHECK(st2.num_vertices() == NUMBER_OF_VERTICES);\n\n  std::cout << \"st2.num_simplices()=\" << st2.num_simplices() << std::endl;\n  BOOST_CHECK(st2.num_simplices() == 30);\n\n  Point_cloud points012;\n  for (std::size_t vertex = 0; vertex <= 2; vertex++) {\n    points012.push_back(cech_complex_for_doc.get_point(vertex));\n  }\n  std::size_t dimension = points[0].end() - points[0].begin();\n  Min_sphere ms012(dimension, points012.begin(), points012.end());\n\n  Simplex_tree::Filtration_value f012 = st2.filtration(st2.find({0, 1, 2}));\n  std::cout << \"f012= \" << f012 << \" | ms012_radius= \" << std::sqrt(ms012.squared_radius()) << std::endl;\n\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(f012, std::sqrt(ms012.squared_radius()));\n\n  Point_cloud points1410;\n  points1410.push_back(cech_complex_for_doc.get_point(1));\n  points1410.push_back(cech_complex_for_doc.get_point(4));\n  points1410.push_back(cech_complex_for_doc.get_point(10));\n  Min_sphere ms1410(dimension, points1410.begin(), points1410.end());\n\n  Simplex_tree::Filtration_value f1410 = st2.filtration(st2.find({1, 4, 10}));\n  std::cout << \"f1410= \" << f1410 << \" | ms1410_radius= \" << std::sqrt(ms1410.squared_radius()) << std::endl;\n\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(f1410, std::sqrt(ms1410.squared_radius()));\n\n  Point_cloud points469;\n  points469.push_back(cech_complex_for_doc.get_point(4));\n  points469.push_back(cech_complex_for_doc.get_point(6));\n  points469.push_back(cech_complex_for_doc.get_point(9));\n  Min_sphere ms469(dimension, points469.begin(), points469.end());\n\n  Simplex_tree::Filtration_value f469 = st2.filtration(st2.find({4, 6, 9}));\n  std::cout << \"f469= \" << f469 << \" | ms469_radius= \" << std::sqrt(ms469.squared_radius()) << std::endl;\n\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(f469, std::sqrt(ms469.squared_radius()));\n\n  BOOST_CHECK((st2.find({6, 7, 8}) == st2.null_simplex()));\n  BOOST_CHECK((st2.find({3, 5, 7}) == st2.null_simplex()));\n}\n\nBOOST_AUTO_TEST_CASE(Cech_complex_from_points) {\n  // ----------------------------------------------------------------------------\n  // Init of a list of points\n  // ----------------------------------------------------------------------------\n  Point_cloud points;\n  std::vector<double> coords = {0.0, 0.0, 0.0, 1.0};\n  points.push_back(Point(coords.begin(), coords.end()));\n  coords = {0.0, 0.0, 1.0, 0.0};\n  points.push_back(Point(coords.begin(), coords.end()));\n  coords = {0.0, 1.0, 0.0, 0.0};\n  points.push_back(Point(coords.begin(), coords.end()));\n  coords = {1.0, 0.0, 0.0, 0.0};\n  points.push_back(Point(coords.begin(), coords.end()));\n\n  // ----------------------------------------------------------------------------\n  // Init of a Cech complex from the list of points\n  // ----------------------------------------------------------------------------\n  Cech_complex cech_complex_from_points(points, 2.0);\n\n  std::cout << \"========== cech_complex_from_points ==========\" << std::endl;\n  Simplex_tree st;\n  const int DIMENSION = 3;\n  cech_complex_from_points.create_complex(st, DIMENSION);\n\n  // Another way to check num_simplices\n  std::cout << \"Iterator on Cech complex simplices in the filtration order, with [filtration value]:\" << std::endl;\n  int num_simplices = 0;\n  for (auto f_simplex : st.filtration_simplex_range()) {\n    num_simplices++;\n    std::cout << \"   ( \";\n    for (auto vertex : st.simplex_vertex_range(f_simplex)) {\n      std::cout << vertex << \" \";\n    }\n    std::cout << \") -> \"\n              << \"[\" << st.filtration(f_simplex) << \"] \";\n    std::cout << std::endl;\n  }\n  BOOST_CHECK(num_simplices == 15);\n  std::cout << \"st.num_simplices()=\" << st.num_simplices() << std::endl;\n  BOOST_CHECK(st.num_simplices() == 15);\n\n  std::cout << \"st.dimension()=\" << st.dimension() << std::endl;\n  BOOST_CHECK(st.dimension() == DIMENSION);\n  std::cout << \"st.num_vertices()=\" << st.num_vertices() << std::endl;\n  BOOST_CHECK(st.num_vertices() == 4);\n\n  for (auto f_simplex : st.filtration_simplex_range()) {\n    std::cout << \"dimension(\" << st.dimension(f_simplex) << \") - f = \" << st.filtration(f_simplex) << std::endl;\n    switch (st.dimension(f_simplex)) {\n      case 0:\n        GUDHI_TEST_FLOAT_EQUALITY_CHECK(st.filtration(f_simplex), 0.0);\n        break;\n      case 1:\n        GUDHI_TEST_FLOAT_EQUALITY_CHECK(st.filtration(f_simplex), 0.707107, .00001);\n        break;\n      case 2:\n        GUDHI_TEST_FLOAT_EQUALITY_CHECK(st.filtration(f_simplex), 0.816497, .00001);\n        break;\n      case 3:\n        GUDHI_TEST_FLOAT_EQUALITY_CHECK(st.filtration(f_simplex), 0.866025, .00001);\n        break;\n      default:\n        BOOST_CHECK(false);  // Shall not happen\n        break;\n    }\n  }\n}\n\n#ifdef GUDHI_DEBUG\nBOOST_AUTO_TEST_CASE(Cech_create_complex_throw) {\n  // ----------------------------------------------------------------------------\n  //\n  // Init of a Cech complex from a OFF file\n  //\n  // ----------------------------------------------------------------------------\n  std::string off_file_name(\"alphacomplexdoc.off\");\n  double max_radius = 12.0;\n  std::cout << \"========== OFF FILE NAME = \" << off_file_name << \" - Cech max_radius=\" << max_radius\n            << \"==========\" << std::endl;\n\n  Gudhi::Points_off_reader<Point> off_reader(off_file_name);\n  Cech_complex cech_complex_from_file(off_reader.get_point_cloud(), max_radius);\n\n  Simplex_tree stree;\n  std::vector<int> simplex = {0, 1, 2};\n  stree.insert_simplex_and_subfaces(simplex);\n  std::cout << \"Check exception throw in debug mode\" << std::endl;\n  // throw excpt because stree is not empty\n  BOOST_CHECK_THROW(cech_complex_from_file.create_complex(stree, 1), std::invalid_argument);\n}\n#endif\n", "meta": {"hexsha": "c6b15d7fb0baa5c581082aa8ba17225761343cc9", "size": 10171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Cech_complex/test/test_cech_complex.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/Cech_complex/test/test_cech_complex.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/Cech_complex/test/test_cech_complex.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": 40.2015810277, "max_line_length": 115, "alphanum_fraction": 0.6173434274, "num_tokens": 2802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5368558420740807}}
{"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 relevance vector machine\n    utilities 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 cross validation and rvm training functions\n    to find a good decision function that can classify examples in our\n    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 10\n    from the origin are labeled +1 and all other points are labeled\n    as -1.\n        \n*/\n\n\n#include <iostream>\n#include <dlib/svm.h>\n\nusing namespace std;\nusing namespace dlib;\n\n\nint main()\n{\n    // The rvm functions use column vectors to contain a lot of the data on which they \n    // operate. So the first thing we do here is declare a convenient typedef.  \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 (int r = -20; r <= 20; ++r)\n    {\n        for (int c = -20; c <= 20; ++c)\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 10 from the origin\n            if (sqrt((double)r*r + c*c) <= 10)\n                labels.push_back(+1);\n            else\n                labels.push_back(-1);\n\n        }\n    }\n\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\n\n    // Now that we have some data we want to train on it.  However, there is a parameter to the \n    // training.  This is the gamma parameter of the RBF kernel.  Our choice for this parameter will \n    // influence how good the resulting decision function is.  To test how good a particular choice of\n    // kernel parameters is we can use the cross_validate_trainer() function to perform n-fold cross\n    // validation on our training data.  However, there is a problem with the way we have sampled \n    // our distribution.  The problem is that there is a definite ordering to the samples.  \n    // That is, the first half of the samples look like they are from a different distribution \n    // than the second half.  This would screw up the cross validation process but we can \n    // fix it by randomizing the order of the samples with the following function call.\n    randomize_samples(samples, labels);\n\n\n    // here we make an instance of the rvm_trainer object that uses our kernel type.\n    rvm_trainer<kernel_type> trainer;\n\n    // One thing you can do to reduce the RVM training time is to make its\n    // stopping epsilon bigger.  However, this might make the outputs less\n    // reliable.  But sometimes it works out well.  0.001 is the default.\n    trainer.set_epsilon(0.001);\n    // You can also set an explicit limit on the number of iterations used by the numeric\n    // solver.  The default is 2000.\n    trainer.set_max_iterations(2000);\n\n    // Now we loop over some different gamma values to see how good they are.  Note\n    // that this is a very simple way to try out a few possible parameter choices.  You \n    // should look at the model_selection_ex.cpp program for examples of more sophisticated \n    // strategies for determining good parameter choices.\n    cout << \"doing 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        cout << \"gamma: \" << gamma;\n        // Print out the cross validation accuracy for 3-fold cross validation using the current gamma.  \n        // cross_validate_trainer() returns a row vector.  The first element of the vector is the fraction\n        // of +1 training examples correctly classified and the second number is the fraction of -1 training \n        // examples correctly classified.\n        cout << \"     cross validation accuracy: \" << cross_validate_trainer(trainer, samples, labels, 3);\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.08.  So that is what we will use.\n\n    // Now we train on the full set of data and obtain the resulting decision function.  We use the\n    // value of 0.08 for gamma.  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    trainer.set_kernel(kernel_type(0.08));\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 RVM training and save the results\n\n    // Print out the number of relevance vectors in the resulting decision function.\n    cout << \"\\nnumber of relevance 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    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    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 relevance vectors in the resulting decision function.  \n    // (it should be the same as in the one above)\n    cout << \"\\nnumber of relevance 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": "d1d5935e7b688a32a8b87f83f8e7628c655756a1", "size": 9741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/examples/rvm_ex.cpp", "max_stars_repo_name": "maxmert/nlp-mitie", "max_stars_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "examples/rvm_ex.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "examples/rvm_ex.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 44.6834862385, "max_line_length": 119, "alphanum_fraction": 0.6895595935, "num_tokens": 2318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7057850216484837, "lm_q1q2_score": 0.5368558373667731}}
{"text": "#include <gtest/gtest.h>\n#include <cmath>\n#include <vector>\n#include <Eigen/Dense>\n#include \"pid_controller/pid_controller.h\"\n\n\nnamespace controls \n{\n\n    class PID_Test : public ::testing::Test \n    {\n        protected:\n        /// Pointer for Kalman Filter object\n        std::shared_ptr<PID_Controller> pid_ptr;\n        double kp, ki, kd;\n        double max, min;\n        double imax, imin;\n        double init_val;\n        double fltr_coef;\n\n        virtual void SetUp()\n        {\n            kp = 0.0F;\n            ki = 0.0F;\n            kd = 0.0F;\n            max = 10.0F;\n            min = -max;\n            imax = 3.0F;\n            imin = -imax;\n            init_val = 0.0F;\n            fltr_coef = 1.0F;\n            pid_ptr = std::make_shared<PID_Controller>(kp, ki, kd, max, min, imax, imin, init_val, fltr_coef);\n        }\n\n        virtual void TearDown()\n        {\n        }\n    };\n\n    TEST_F(PID_Test, PTEST)\n    {\n        double kp = 3.0F;\n        double ki = 0.0F;\n        double kd = 0.0F;\n        double dT = 0.1F;\n        bool result = false;\n\n        Eigen::VectorXd error(63);          /// Control Error\n        Eigen::VectorXd pid_expected(63);   /// Expected \n        Eigen::VectorXd pid_out(63);        /// Controller Output\n        double cmp_error = 0.0F;            /// Compare Error\n        double mae = 0.0F;                  /// Mean Abs Error\n        \n        pid_ptr->Init();\n        pid_ptr->Update_Gains(kp, ki, kd);\n        pid_ptr->Update_dT(dT);\n\n        /// Run Controler with 5.17 deg/100ms error signal\n        for(int i=0; i<63; i++)\n        {      \n            error(i) = sin(i*dT);      \n            pid_expected(i) = kp*error(i);\n            pid_out(i) = pid_ptr->Step(error(i));\n            cmp_error = pid_expected(i) - pid_out(i);\n            mae += cmp_error;\n        }\n        \n        /// Mean Absolute Error\n        mae /= 63;\n        if(fabs(mae) < 1e-6)\n        {\n            result = true;\n        }\n        else \n        {\n            result = false;\n            std::cerr << \"PTest Mean Absolute Arror: \" << mae << std::endl;\n        }\n        EXPECT_TRUE(result);\n    }\n\n    TEST_F(PID_Test, ITEST)\n    {\n        double kp = 0.0F;\n        double ki = 1.0F;\n        double kd = 0.0F;\n        double dT = 0.01F;\n        double imax = 5.0F;\n        double imin = -5.0F;\n        double initial_val = 0.0F;\n        bool result = false;\n\n        Eigen::VectorXd error(630);          /// Control Error\n        Eigen::VectorXd pid_expected(630);   /// Expected \n        Eigen::VectorXd pid_out(630);        /// Controller Output\n        double cmp_error = 0.0F;            /// Compare Error\n        double mae = 0.0F;                  /// Mean Abs Error\n\n        /// Initialize Controller\n        pid_ptr->Init();\n        pid_ptr->Update_I_Sat_Limit(imax, imin);\n        pid_ptr->Update_InitVal(initial_val);\n        pid_ptr->Update_Gains(kp, ki, kd);\n        pid_ptr->Update_dT(dT);\n\n        /// Run Controler with 0.57 deg/10ms error signal\n        for(int i=0; i<630; i++)\n        {\n            error(i) = sin(i*dT);\n\n            pid_expected(i) = ki*1.0F-cos(i*dT);\n            pid_out(i) = pid_ptr->Step(error(i));\n            cmp_error = pid_expected(i) - pid_out(i);\n            mae += cmp_error;\n        }\n\n        /// Mean Absolute Error\n        mae /= 630;\n        if(fabs(mae) < 0.002)\n        {\n            result = true;\n        }\n        else \n        {\n            result = false;\n            std::cerr << \"ITest Mean Absolute Error: \" << mae << std::endl;\n        }\n        EXPECT_TRUE(result);\n    }\n\n    TEST_F(PID_Test, ISAT_TEST)\n    {\n        double kp = 0.0F;\n        double ki = 1.0F;\n        double kd = 0.0F;\n        double dT = 0.01F;\n        double max = 1.0F;\n        double min = -1.0F;\n        double imax = 0.5F;\n        double imin = -0.5F;\n        double initial_val = 0.0F;\n        bool result = false;\n\n        double pid_out;        /// Controller Output\n        double error;          /// Controller Error\n\n        /// Initialize Controller\n        pid_ptr->Init();\n        pid_ptr->Update_Sat_Limit(max, min);\n        pid_ptr->Update_I_Sat_Limit(imax, imin);\n        pid_ptr->Update_InitVal(initial_val);\n        pid_ptr->Update_Gains(kp, ki, kd);\n        pid_ptr->Update_dT(dT);\n\n        /// Run Controler with 0.57 deg/10ms error signal\n        for(int i=0; i<1260; i++)\n        {\n            error = sin(i*dT);\n            pid_out = pid_ptr->Step(error);\n            if(pid_out > imax || pid_out < imin)\n            {\n                result = false;\n                std::cerr << \"PID_OUT: \" << pid_out << \"   I LIM +/-: \" \n                          << imax << std::endl;\n            }\n        }\n        EXPECT_TRUE(result);\n    }\n\n    TEST_F(PID_Test, PIDSAT_DYN_UPDATE_TEST)\n    {\n        double kp = 1.0F;\n        double ki = 2.0F;\n        double kd = 0.0F;\n        double dT = 0.01F;\n        double max = 1.6F;\n        double min = 1.6F;\n        double imax = 0.5F;\n        double imin = 0.5F;\n        double initial_val = 0.0F;\n        bool result = false;\n\n        double pid_out;        /// Controller Output\n        double error;          /// Controller Error\n\n        /// Initialize Controller\n        pid_ptr->Init();\n        pid_ptr->Update_Sat_Limit(max, min);\n        pid_ptr->Update_I_Sat_Limit(imax, imin);\n        pid_ptr->Update_InitVal(initial_val);\n        pid_ptr->Update_Gains(kp, ki, kd);\n        pid_ptr->Update_dT(dT);\n\n        /// Run Controler with 0.57 deg/10ms error signal\n        for(int i=0; i<1260; i++)\n        {\n            \n            if(i < 315)\n            {\n                error = 1.0F;\n            }\n            else if (i == 315)\n            {\n                /// Dynamically Update P-Gain so that PID Limit is Exercised\n                /// At this point, the I term should be saturated at 0.5F\n                /// The PID Out should be Saturated at 1.5F (I:0.5F P:1.0F)\n                kp = 5.0F;\n                pid_ptr->Update_Gains(kp, ki, kd);\n            }\n            else if(i == 630)\n            {\n                error = -1.0F;\n                kp = 1.0F;\n                pid_ptr->Update_Gains(kp, ki, kd);\n            }\n            else if(i == 945)\n            {\n                /// Same Strategy as above but Exercising the negative limit\n                kp = 5.0F;\n                pid_ptr->Update_Gains(kp, ki, kd);\n            }\n\n            /// Step PID Controller\n            pid_out = pid_ptr->Step(error);\n\n            if(pid_out > max || pid_out < min)\n            {\n                result = false;\n                std::cerr << \"PID_OUT: \" << pid_out << \"   PID LIM +/-: \" \n                          << max << std::endl;\n            }\n        }\n        EXPECT_TRUE(result);\n    }\n\n    TEST_F(PID_Test, DTERM_LPF_TEST)\n    {\n        double kp = 0.0F;\n        double ki = 0.0F;\n        double kd = 1.0F;\n        double dT = 0.01F;\n        double fltr_coef = 0.75F;\n        double initial_val = 0.0F;\n        bool result = false;\n\n        Eigen::VectorXd error(315);        /// Control Error\n        Eigen::VectorXd pid_expected(315); /// Expected \n        Eigen::VectorXd pid_out(315);      /// Controller Output\n        double cmp_error = 0.0F;            /// Compare Error\n        double mae = 0.0F;                  /// Mean Abs Error\n        double rmse = 0.0F;                 //RMSE\n\n        /// Initialize Controller\n        pid_ptr->Init();\n        pid_ptr->Update_InitVal(initial_val);\n        pid_ptr->Update_Gains(kp, ki, kd);\n        pid_ptr->Update_D_Filter(fltr_coef);\n        pid_ptr->Update_dT(dT);\n\n        /// Run Controler with 0.57 deg/10ms error signal\n        for(int i=0; i<315; i++)\n        {\n            error(i) = sin(i*dT);\n            pid_expected(i) = kd*cos(i*dT);\n\n            /// Inject Transient\n            /// RMSE NO Transient No LPF:           0.0564541\n            /// RMSE With Transient No LPF:         0.069098\n            /// RMSE No Tranisent With COEF 0.75:   0.0584871\n            /// RMSE Transient With COEF 0.75       0.0643062\n            if(i == 310)\n            {\n                error(i) = 0.005F+error(i);\n            }\n\n            pid_out(i) = pid_ptr->Step(error(i));\n            cmp_error = pid_expected(i) - pid_out(i);\n            mae += cmp_error;\n            rmse += cmp_error *cmp_error;\n        }\n\n        mae /= 315;\n        rmse /= 315;\n        rmse = sqrt(rmse);\n\n        if(rmse > 0.065F)\n        {\n            result = false;\n            std::cerr << \"RMSE: \" << rmse << std::endl;\n            std::cerr << \"MAE: \" << mae << std::endl;\n        }\n\n        EXPECT_TRUE(result);\n    }\n\n    TEST_F(PID_Test, DTEST)\n    {\n        double kp = 0.0F;\n        double ki = 0.0F;\n        double kd = 1.3F;\n        double dT = 0.01F;\n        bool result = false;\n\n        Eigen::VectorXd error(630);          /// Control Error\n        Eigen::VectorXd pid_expected(630);   /// Expected \n        Eigen::VectorXd pid_out(630);        /// Controller Output\n        double cmp_error = 0.0F;            /// Compare Error\n        double mae = 0.0F;\n        double rmse = 0.0F;                  /// Mean Abs Error\n\n        /// Initialize Controller\n        pid_ptr->Init();\n        pid_ptr->Update_Gains(kp, ki, kd);\n        pid_ptr->Update_dT(dT);\n\n        /// Run Controler with 0.57 deg/10ms error signal\n        for(int i=0; i<630; i++)\n        {\n            error(i) = sin(i*dT);\n\n            pid_expected(i) = kd*cos(i*dT);\n            pid_out(i) = pid_ptr->Step(error(i));\n            cmp_error = pid_expected(i) - pid_out(i);\n            mae += cmp_error;\n            cmp_error = cmp_error * cmp_error;\n            rmse += cmp_error;\n        }\n\n        /// Mean Absolute Error\n        mae /= 630;\n        rmse /= 630;\n        rmse = sqrt(rmse);\n        //std::cerr << \"DTest RMSE \" << rmse << std::endl;\n        //std::cerr << \"DTest MAE \" << mae << std::endl;\n        if(fabs(mae) < 0.005)\n        {\n            result = true;\n        }\n        else \n        {\n            result = false;\n            std::cerr << \"DTest Mean Absolute Error: \" << mae << std::endl;\n        }\n        EXPECT_TRUE(result);\n    }\n};\n\nint main(int argc, char **argv) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}", "meta": {"hexsha": "da2f3c0b10d368f43edfed4e4cf632680f97af67", "size": 10220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/pid_controller_test.cpp", "max_stars_repo_name": "shedlock987/base_controls", "max_stars_repo_head_hexsha": "6a60115e63646cd710b779e4649497f39f8cab22", "max_stars_repo_licenses": ["MIT"], "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/pid_controller_test.cpp", "max_issues_repo_name": "shedlock987/base_controls", "max_issues_repo_head_hexsha": "6a60115e63646cd710b779e4649497f39f8cab22", "max_issues_repo_licenses": ["MIT"], "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/pid_controller_test.cpp", "max_forks_repo_name": "shedlock987/base_controls", "max_forks_repo_head_hexsha": "6a60115e63646cd710b779e4649497f39f8cab22", "max_forks_repo_licenses": ["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.0340909091, "max_line_length": 110, "alphanum_fraction": 0.4693737769, "num_tokens": 2787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5368486482037059}}
{"text": "#include <map>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\n#include \"GaussSeq.h\"\n#include \"ARSeq.h\"\n\nusing utils::my_float;\n\nint main() {\n    using boost::multiprecision::cpp_bin_float_50;\n\n    // set precision of output\n//    std::streamsize precision = std::numeric_limits<cpp_bin_float_50>::digits10;\n//    std::cout << std::setprecision(10);\n\n    // testing\n    std::map<int, my_float> coeff {\n        {3, 0.5},\n        {20, 20},\n    };\n    ARSeq seq(coeff, 1);\n    seq.print_lags();\n    std::vector<my_float> v;\n    for (auto i = 0; i < 20; i++) {\n        v.push_back(0);\n    }\n    v[2] = 2;\n    v[19] = 3;\n\n    seq.seed_prev_vals(v);\n    \n    seq.print_past_vals();\n    for (auto i = 0; i < 100; i++) {\n        seq.next();\n    }\n    seq.print_past_vals();\n    \n    \n    return 0;\n}\n", "meta": {"hexsha": "8940b16a139862a2356fe9cc34233e4ae342dee7", "size": 951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gen-data/test/main.cpp", "max_stars_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_stars_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gen-data/test/main.cpp", "max_issues_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_issues_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gen-data/test/main.cpp", "max_forks_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_forks_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_forks_repo_licenses": ["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.6739130435, "max_line_length": 82, "alphanum_fraction": 0.6014721346, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695627, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5368486368193818}}
{"text": "#pragma once\n\n// C++ standard library\n#include <utility>\n\n// Armadillo\n#include <armadillo>\n\nnamespace mant {\n  namespace itd {\n    const double heliocentricGravitationalConstant = 1.32712440018e20;\n    const double solarMass = 1.98892e30;\n\n    double stumpffFunction(\n        const double parameter,\n        const arma::uword type);\n\n    double timeOfFlight(\n        const double universalVariable,\n        const arma::vec::fixed<3>& departurePosition,\n        const arma::vec::fixed<3>& arrivalPosition,\n        const bool useProgradeTrajectory);\n\n    double sphereOfInfluenceRadius(\n        const double semimajorAxis,\n        const double mass);\n\n    std::pair<arma::vec::fixed<3>, arma::vec::fixed<3>> positionAndVelocityOnOrbit(\n        const double modifiedJulianDate,\n        const arma::vec::fixed<7>& keplerianElements);\n\n    arma::vec::fixed<3> gravityAssist(\n        const arma::vec::fixed<3>& satelliteVelocity,\n        const arma::vec::fixed<3>& planetPosition,\n        const arma::vec::fixed<3>& planetVelocity,\n        const double standardGravitationalParameter,\n        const double periapsis);\n\n    std::pair<arma::vec::fixed<3>, arma::vec::fixed<3>> lambert(\n        const arma::vec::fixed<3>& departurePosition,\n        const arma::vec::fixed<3>& arrivalPosition,\n        const bool useProgradeTrajectory,\n        const arma::uword numberOfRevolutions,\n        const double transferTime);\n  }\n}\n", "meta": {"hexsha": "b4a1b74c0a443a193c9a6a7659fb2697a3a6bdff", "size": 1416, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mantella_bits/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": "include/mantella_bits/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": "include/mantella_bits/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": 30.1276595745, "max_line_length": 83, "alphanum_fraction": 0.6723163842, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.5368486268701391}}
{"text": "\n#define CATCH_CONFIG_RUNNER\n#include \"catch.hpp\"\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n#include <general/nmspc_tensor_omp.h>\n\n#ifdef OpenBLAS_AVAILABLE\n#include <cblas.h>\n    #include <openblas_config.h>\n#endif\n\n#ifdef MKL_AVAILABLE\n#include <mkl.h>\n#include <mkl_service.h>\n#endif\n#include <thread>\n\n#include <Eigen/Core>\n#include <h5pp/h5pp.h>\n#include <math/svd.h>\n\n\n\n\nTEST_CASE(\"Singular value decomposition in Eigen and Lapacke\", \"[svd]\") {\n    SECTION(\"Test all svd decompositions\") {\n        using reciter = h5pp::fs::recursive_directory_iterator;\n        svd::settings svd_settings;\n        svd_settings.threshold = 1e-8;\n        svd_settings.loglevel  = 0;\n        svd_settings.use_lapacke = false;\n        svd::solver svd(svd_settings);\n\n        [[maybe_unused]] Eigen::MatrixXcd U1,V1,U2,V2;\n        Eigen::VectorXcd S1,S2;\n        for(auto &item : reciter(std::string(TEST_MATRIX_DIR))) {\n            if(item.path().filename().string().find(\"svdmatrix\") == std::string::npos) continue;\n            if(item.path().extension() != \".h5\") continue;\n            size_t     logLevel = 2;\n            h5pp::File file(item.path().string(), h5pp::FilePermission::READONLY, logLevel);\n            auto       matrix = file.readDataset<Eigen::MatrixXcd>(\"svdmatrix\");\n            svd.use_lapacke   = false;\n            std::tie(U1, S1, V1) = svd.decompose(matrix);\n            svd.use_lapacke   = true;\n            std::tie(U2, S2, V2) = svd.decompose(matrix);\n            double differenceS = std::log10((S2.array() - S1.array()).cwiseAbs().sum());\n            fmt::print(\"S {:<32} diff {:.24f}\\n\", item.path().filename().string(), differenceS);\n            REQUIRE(differenceS < -12);\n        }\n    }\n}\n\n\nint main(int argc, char **argv){\n\n// Set the number of threads to be used\n    [[maybe_unused]] int num_threads = 1;\n#ifdef _OPENMP\n    omp_set_num_threads(num_threads);\n    Eigen::setNbThreads(num_threads);\n    Textra::omp::setNumThreads(num_threads);\n#ifdef OpenBLAS_AVAILABLE\n    openblas_set_num_threads(num_threads);\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(num_threads);\n    std::cout <<  \"Using Intel MKL with \" <<  mkl_get_max_threads() << \" threads\" << std::endl;\n#endif\n\n#endif\n\n    return Catch::Session().run(argc, argv);\n}", "meta": {"hexsha": "1897cd24a214e7d570d8bfd618e4958c18c72363", "size": 2665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test-svd.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/test-svd.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/test-svd.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": 32.1084337349, "max_line_length": 96, "alphanum_fraction": 0.6281425891, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5368486261525991}}
{"text": "#ifndef __PROBABILITY_DISTRIBUTIONS__ASYMMETRIC_NORMAL_HPP__\n#define __PROBABILITY_DISTRIBUTIONS__ASYMMETRIC_NORMAL_HPP__\n\n#include \"asymmetric_distribution.hpp\"\n#include \"normal.hpp\"\n\n#include <boost/random/normal_distribution.hpp>\n\nnamespace ProbabilityDistributions {\n  template <class D, class W = D, class T = W>\n  class AsymmetricNormal:\n    public AsymmetricDistribution<AsymmetricNormal<D,W,T>,D,W,T> {\n    public:\n      AsymmetricNormal(T p, T mu, T sigma);\n\n      static constexpr unsigned int sample_size = 1;\n\n      void fix_sigma(bool fixed = true) { fixed_sigma_ = fixed; }\n      bool is_sigma_fixed() const { return fixed_sigma_; }\n      void set_sigma(T sigma) {\n        assert(sigma > 0); sigma_ = sigma; sigma2_ = 2*sigma*sigma; }\n      T get_sigma() const { return sigma_; }\n\n      AsymmetricNormal<D,W,T> const&\n        operator=(AsymmetricNormal<D,W,T> const& other) {\n          base_class::set_p(other.get_p());\n          base_class::set_mu(other.get_mu());\n          set_sigma(other.get_sigma());\n          base_class::fixed_p_ = other.is_p_fixed();\n          base_class::fixed_mu_ = other.is_mu_fixed();\n          fixed_sigma_ = other.is_sigma_fixed();\n          return *this;\n        }\n      AsymmetricNormal<D,W,T> const&\n        operator=(Normal<D,W,T> const& other) {\n          base_class::set_p(0.5);\n          base_class::set_mu(other.get_mu());\n          set_sigma(other.get_sigma());\n          base_class::fixed_p_ = true;\n          base_class::fixed_mu_ = other.is_mu_fixed();\n          fixed_sigma_ = other.is_sigma_fixed();\n          return *this;\n        }\n\n    private:\n      typedef AsymmetricDistribution<AsymmetricNormal<D,W,T>,D,W,T> base_class;\n      friend class AsymmetricDistribution<AsymmetricNormal<D,W,T>,D,W,T>;\n\n      struct TruncatedNormal {\n        TruncatedNormal(T sigma): dist(0, sigma) { }\n\n        template <class RNG>\n        T operator()(RNG& rng) { return std::abs(dist(rng)); }\n\n        boost::random::normal_distribution<T> dist;\n      };\n\n      TruncatedNormal create_gamma_plus() const;\n      TruncatedNormal create_gamma_minus() const;\n\n      T constant_likelihood() const;\n      T negative_ll(T s, T mu) const;\n      T positive_ll(T s, T mu) const;\n      void set_parameter_vector(std::vector<T> const& p) {\n        assert(p.size() == 1); sigma_ = p[0]; }\n      std::vector<T> get_parameter_vector() const { return {sigma_}; }\n\n      void init_MLE(MA::ConstArray<D> const& data,\n          MA::ConstArray<W> const& weight, std::vector<size_t> const& indexes);\n      void end_MLE();\n      void updated_p();\n\n      void MLE_fixed_p(MA::ConstArray<D> const& data,\n          MA::ConstArray<W> const& weight, std::vector<size_t> const& indexes);\n\n      bool fixed_sigma_;\n      T sigma_, sigma2_, alpha_, alpha_inv_, alpha2_, alpha2_inv_;\n      std::vector<T> pos_sum_all_0_, pos_sum_all_1_, pos_sum_all_2_;\n      std::vector<T> neg_sum_all_0_, neg_sum_all_1_, neg_sum_all_2_;\n  };\n};\n\n#include \"asymmetric_normal_impl.hpp\"\n\n#endif\n", "meta": {"hexsha": "13fd08209d03c96718c31919e35a8f463da436e7", "size": 2992, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/asymmetric_normal.hpp", "max_stars_repo_name": "mirandaconrado/probability-distributions", "max_stars_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/asymmetric_normal.hpp", "max_issues_repo_name": "mirandaconrado/probability-distributions", "max_issues_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/asymmetric_normal.hpp", "max_forks_repo_name": "mirandaconrado/probability-distributions", "max_forks_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7906976744, "max_line_length": 79, "alphanum_fraction": 0.6527406417, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5368486257938285}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/point_generators_3.h>\n#include <CGAL/iterator.h>\n#include <CGAL/Timer.h>\n\n#include <boost/version.hpp>\n#if BOOST_VERSION < 107200\n#include <boost/progress.hpp>\nusing boost::progress_display;\n#else\n#include <boost/timer/progress_display.hpp>\nusing boost::timer::progress_display;\n#endif\n\n#include <CGAL/Orthogonal_k_neighbor_search.h>\n#include <CGAL/K_neighbor_search.h>\n#include <CGAL/Search_traits_3.h>\n\n#include <ANN/ANN.h>\n#include <ANN/ANNperf.h>\n\n#include<sfcnn.hpp>\n\n\n\ntypedef CGAL::Simple_cartesian<double> Kernel;\ntypedef Kernel::Point_3 Point_3;\ntypedef CGAL::Random_points_in_cube_3<Point_3> Random_points_iterator;\ntypedef CGAL::Counting_iterator<Random_points_iterator> N_Random_points_iterator;\n\ntypedef CGAL::Search_traits_3<Kernel> TreeTraits;\ntypedef CGAL::Sliding_midpoint<TreeTraits> Splitter;\ntypedef CGAL::Orthogonal_k_neighbor_search<TreeTraits> OK_search;\n\ntemplate <class Output_iterator>\nint read_points(std::string filename,Output_iterator out)\n{\n  std::ifstream file(filename.c_str());\n  int nb_pts;\n  Point_3 p;\n  file >> nb_pts;\n  for (int i=0;i<nb_pts;++i){\n    file >> p;\n    *out++=p;\n  }\n  return nb_pts;\n}\n\nint main(int argc,char** argv)\n{\n\n  if (argc!=3 && argc!=4){\n    std::cerr << \"Usage: main nb_input_point nb_neighbors_needed\\n\";\n    std::cerr << \"or     main Input.xyz Queries.xyz nb_neighbors_needed\\n\";\n    exit(EXIT_FAILURE);\n  }\n\n  int nb_input_point,k,nb_queries;\n  std::vector<Point_3> points;\n  std::vector<Point_3> queries;\n\n  if (argc==3){\n    nb_input_point=atoi(argv[1]);\n    k=atoi(argv[2]);\n    nb_queries=1;\n    points.reserve(nb_input_point);\n    Random_points_iterator rpit(1.0);\n    points.insert(points.begin(),N_Random_points_iterator(rpit,0), N_Random_points_iterator(nb_input_point));\n    queries.push_back(Point_3(0,0,0));\n  }\n  else{\n    k=atoi(argv[3]);\n    nb_input_point=read_points(argv[1],std::back_inserter(points));\n    nb_queries=read_points(argv[2],std::back_inserter(queries));\n  }\n\n  std::cout << \"Looking for \" << k << \" nearest neighbors amongst \" << nb_input_point << \" points, with \"<< nb_queries <<\" query points.\\n\";\n\n  std::random_shuffle(points.begin(),points.end());\n\n  double STANN_time=0,ANN_time=0,OK_time=0;\n\n  CGAL::Timer time;\n//Building trees\n//--STANN\n  time.start();\n  sfcnn<Point_3, 3, double> NN(&points[0], nb_input_point);\n  time.stop();\n  double STANN_tree=time.time();\n  time.reset();\n//--ANN\n  ANNpointArray    dataPts;     // data points\n  ANNpoint         queryPt;     // query point\n  ANNidxArray      nnIdx;       // near neighbor indices\n  ANNdistArray     dists;       // near neighbor distances\n  ANNkd_tree*      kdTree;      // search structure\n  dataPts = annAllocPts(nb_input_point, 3);      // allocate data points\n\n\n  queryPt = annAllocPt(3);          // allocate query point\n  nnIdx = new ANNidx[k];            // allocate near neigh indices\n  dists = new ANNdist[k];            // allocate near neighbor dists\n  //set points\n  for (int i=0;i<nb_input_point;++i){\n     dataPts[i][0]=points[i][0];\n     dataPts[i][1]=points[i][1];\n     dataPts[i][2]=points[i][2];\n  }\n  time.start();\n  kdTree = new ANNkd_tree(dataPts,nb_input_point,3);\n  time.stop();\n  double ANN_tree=time.time();\n  time.reset();\n//--OK_search\n  time.start();\n  Splitter splitter(10); //bucket size can be changed here\n  OK_search::Tree ok_tree(points.begin(),points.end(),splitter);\n  ok_tree.build();\n  time.stop();\n  double OK_tree=time.time();\n  time.reset();\n\n  progress_display show_progress( nb_queries );\n\n//running NN algorithms\n  for (std::vector<Point_3>::const_iterator it=queries.begin();it!=queries.end();++it)\n  {\n    const Point_3& query=*it;\n\n  //STANN\n    CGAL::Timer time;\n    std::vector<long unsigned int> answer;\n    time.start();\n    NN.ksearch(query, k, answer);\n    time.stop();\n    STANN_time+=time.time();\n    time.reset();\n  //ANN\n    queryPt[0]=query[0];\n    queryPt[1]=query[1];\n    queryPt[2]=query[2];\n\n    time.start();\n    kdTree->annkSearch(            // search\n                    queryPt,            // query point\n                    k,                // number of near neighbors\n                    nnIdx,              // nearest neighbors (returned)\n                    dists,              // distance (returned)\n                    0);              // error bound\n\n    time.stop();\n    ANN_time+=time.time();\n    time.reset();\n\n    //~ ANNkdStats stats;\n    //~ kdTree->getStats(stats);\n    //~ std::cout << \"====ANN stats ====\\n\";\n    //~ std::cout << \"dimension of space \" << stats.dim << \"\\n\";\n    //~ std::cout << \"no. of points \" << stats.n_pts << \"\\n\";\n    //~ std::cout << \"bucket size \" << stats.bkt_size << \"\\n\";\n    //~ std::cout << \"no. of leaves (including trivial) \" << stats.n_lf << \"\\n\";\n    //~ std::cout << \"no. of trivial leaves (no points) \" << stats.n_tl << \"\\n\";\n    //~ std::cout << \"no. of splitting nodes \" << stats.n_spl << \"\\n\";\n    //~ std::cout << \"no. of shrinking nodes (for bd-trees) \" << stats.n_shr << \"\\n\";\n    //~ std::cout << \"depth of tree \" << stats.depth << \"\\n\";\n    //~ std::cout << \"sum of leaf aspect ratios \" << stats.sum_ar << \"\\n\";\n    //~ std::cout << \"average leaf aspect ratio \" << stats.avg_ar << \"\\n\";\n    //~ std::cout << \"==================\\n\";\n\n    //~ std::cout << \"====ANN tree  ====\\n\";\n    //~ kdTree->Print(ANNtrue,std::cout);\n    //~ std::cout << \"==================\\n\";\n\n  //Ortho-k-NN\n    std::vector<std::pair<Point_3,double> > ok_result;\n    ok_result.reserve(k);\n    time.start();\n    OK_search ok_search(ok_tree, query,k);\n    time.stop();\n    std::copy(ok_search.begin(),ok_search.end(),std::back_inserter(ok_result));\n    OK_time+=time.time();\n\n    //~ std::cout << std::endl; ok_tree.statistics(std::cout); std::cout << std::endl;\n\n    //~ std::cout << \"====CGAL tree ====\\n\";\n    //~ ok_tree.print();\n    //~ std::cout << \"==================\\n\";\n\n    for (int i = 0; i < k; i++) {      //check results are the same\n      if ( nnIdx[i]!=answer[i] ){\n        std::cerr << \"STANN and ANN produced different results\\n\";\n        exit(EXIT_FAILURE);\n      }\n      if ( ok_result[i].first!=points[answer[i]] ){\n        std::cerr << \"CGAL::OK_search and STANN (ANN) produced different results\\n\";\n        exit(EXIT_FAILURE);\n      }\n    }\n    ++show_progress;\n  }\n\n  std::cout << \"Time to build trees\\n\";\n  std::cout << \"STANN ANN OK_search\\n\";\n  std::cout << STANN_tree << \" \" << ANN_tree << \" \" << OK_tree << \"\\n\";\n  std::cout << \"Time spent for all queries\\n\";\n  std::cout << \"STANN ANN OK_search\\n\";\n  std::cout << STANN_time << \" \" << ANN_time << \" \" << OK_time << \"\\n\";\n\n  delete [] nnIdx;              // clean things up\n  delete [] dists;\n  delete kdTree;\n  annClose();\n}\n", "meta": {"hexsha": "c466b4e4c6d4bfd97f16adac8c7ff98965324f23", "size": 6773, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Spatial_searching/benchmark/Spatial_searching/Compare_ANN_STANN_CGAL.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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": "Spatial_searching/benchmark/Spatial_searching/Compare_ANN_STANN_CGAL.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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": "Spatial_searching/benchmark/Spatial_searching/Compare_ANN_STANN_CGAL.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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": 31.2119815668, "max_line_length": 140, "alphanum_fraction": 0.6085929426, "num_tokens": 1860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5368486208192075}}
{"text": "#include <boost/random/uniform_on_sphere.hpp>\n", "meta": {"hexsha": "e16f6fbafb8e526da358401662bc6f9c1768e911", "size": 46, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_uniform_on_sphere.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_uniform_on_sphere.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_uniform_on_sphere.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.0, "max_line_length": 45, "alphanum_fraction": 0.8260869565, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5368486208192075}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// This file is manually converted from PROJ4\r\n\r\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017.\r\n// Modifications copyright (c) 2017, 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// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Geometry Library by Barend Gehrels (Geodan, Amsterdam)\r\n\r\n// Original copyright notice:\r\n\r\n// Permission is hereby granted, free of charge, to any person obtaining a\r\n// copy of this software and associated documentation files (the \"Software\"),\r\n// to deal in the Software without restriction, including without limitation\r\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n// and/or sell copies of the Software, and to permit persons to whom the\r\n// Software is furnished to do so, subject to the following conditions:\r\n\r\n// The above copyright notice and this permission notice shall be included\r\n// in all copies or substantial portions of the Software.\r\n\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n// THE 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\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n// DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef BOOST_GEOMETRY_PROJECTIONS_PHI2_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_PHI2_HPP\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n\r\nnamespace boost { namespace geometry { namespace projections {\r\nnamespace detail {\r\n\r\ntemplate <typename T>\r\ninline T pj_phi2(T const& ts, T const& e)\r\n{\r\n    static const T TOL = 1.0e-10;\r\n    static const int N_ITER = 15;\r\n\r\n    T eccnth, Phi, con, dphi;\r\n    int i;\r\n\r\n    eccnth = .5 * e;\r\n    Phi = geometry::math::half_pi<T>() - 2. * atan (ts);\r\n    i = N_ITER;\r\n    do {\r\n        con = e * sin (Phi);\r\n        dphi = geometry::math::half_pi<T>() - 2. * atan (ts * pow((1. - con) /\r\n           (1. + con), eccnth)) - Phi;\r\n        Phi += dphi;\r\n    } while ( geometry::math::abs(dphi) > TOL && --i);\r\n    if (i <= 0)\r\n        BOOST_THROW_EXCEPTION( projection_exception(-18) );\r\n    return Phi;\r\n}\r\n\r\n} // namespace detail\r\n}}} // namespace boost::geometry::projections\r\n\r\n#endif\r\n", "meta": {"hexsha": "7417f4c79e6afd927812adef59f113b8f6c90f40", "size": 2861, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/impl/pj_phi2.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/impl/pj_phi2.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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/impl/pj_phi2.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": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6621621622, "max_line_length": 80, "alphanum_fraction": 0.6987067459, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5368486097936537}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_FFT_GSLBACKEND_HPP\n#define BOOST_MATH_FFT_GSLBACKEND_HPP\n\n#include <complex>\n\n#if defined(__GNUC__)\n#include <gsl/gsl_fft_complex.h>\n#include <gsl/gsl_fft_real.h>\n#include <gsl/gsl_fft_halfcomplex.h>\n#endif\n\n#include <boost/math/fft/dft_api.hpp>\n\nnamespace boost { namespace math { \nnamespace fft { namespace detail {\n\n    #if defined(__GNUC__)\n    template<class T, class A>\n    class gsl_backend;\n\n    template<class T, class A>\n    class gsl_rfft_backend;\n\n    template<class Allocator_t>\n    class gsl_backend< std::complex<double>, Allocator_t >\n    {\n    public:\n      using value_type     = std::complex<double>;\n      using allocator_type = Allocator_t;\n      \n    private:\n      using real_value_type    = double;\n      using complex_value_type = std::complex<real_value_type>;\n      enum plan_type { forward_plan, backward_plan };\n      \n      std::size_t my_size; \n      allocator_type my_alloc;\n      \n      // complex fft\n      gsl_fft_complex_wavetable *wtable;\n      gsl_fft_complex_workspace *wspace;\n      \n      void execute(plan_type p, const complex_value_type* in, complex_value_type* out) const\n      {\n        if(in!=out)\n        {\n          // we avoid this extra step for in-place transforms\n          // notice that if in==out, the following code has\n          // undefined-behavior\n          std::copy(in,in+size(),out);\n        }\n        \n        if(p==forward_plan)\n        gsl_fft_complex_forward(\n          reinterpret_cast<real_value_type*>(std::addressof(*out)),\n          1, my_size, wtable, wspace);\n        else\n        gsl_fft_complex_backward(\n          reinterpret_cast<real_value_type*>(std::addressof(*out)),\n          1, my_size, wtable, wspace);\n      }\n      void free()\n      {\n        gsl_fft_complex_wavetable_free(wtable);\n        gsl_fft_complex_workspace_free(wspace);\n      }\n      void alloc()\n      {\n        wtable = gsl_fft_complex_wavetable_alloc(size());\n        wspace = gsl_fft_complex_workspace_alloc(size());\n      }\n   public:\n      \n      gsl_backend(std::size_t n, const allocator_type& = allocator_type{}):\n          my_size{n}\n      {\n        alloc();\n      }\n        \n      ~gsl_backend()\n      {\n        free();\n      }\n      std::size_t size() const {return my_size;}\n      \n      void resize(std::size_t new_size)\n      {\n        if(size()!=new_size)\n        {\n          free();\n          my_size = new_size;\n          alloc();\n        }\n      }\n        \n      void forward(const complex_value_type* in, complex_value_type* out) const\n      {\n        execute(forward_plan,in,out);\n      }\n      void backward(const complex_value_type* in, complex_value_type* out) const\n      {\n        execute(backward_plan,in,out);\n      }\n    };\n    \n    template<class Allocator_t>\n    class gsl_rfft_backend< double, Allocator_t >\n    {\n    public:\n      // using value_type     = double;\n      using allocator_type = Allocator_t;\n      \n    private:\n      enum plan_type { forward_plan, backward_plan };\n      using real_value_type    = double;\n      \n      template<class U>\n      using vector_t = std::vector<U, typename std::allocator_traits<allocator_type>::template rebind_alloc<U> >;\n      \n      std::size_t my_size; \n      allocator_type my_alloc;\n      \n      gsl_fft_real_wavetable        *real_wtable;\n      gsl_fft_halfcomplex_wavetable *halfcomplex_wtable;\n      gsl_fft_real_workspace        *real_wspace;\n      \n      void pack_halfcomplex(real_value_type* out) const\n      // precondition:\n      // -> size(out) >= N\n      {\n        const std::size_t N = size();\n        vector_t<real_value_type> tmp(out,out+N);\n        out[0]=tmp[0];\n        for(unsigned int i=1,j=1;j<N;++i,j+=2)\n        {\n          out[j] = tmp[i];\n          if(j+1<N)\n            out[j+1] = -tmp[N-i];\n        }\n      }\n      void unpack_halfcomplex(real_value_type* out) const\n      // precondition:\n      // -> size(out) >= N\n      {\n        const std::size_t N = size();\n        vector_t<real_value_type> tmp(out,out+N);\n        out[0]=tmp[0];\n        for(unsigned int i=1,j=1;j<N;++i,j+=2)\n        {\n          out[i] = tmp[j];\n          if(j+1<N)\n            out[N-i] = -tmp[j+1];\n        }\n      }\n      template<plan_type p>\n      void execute(const real_value_type* in, \n                   real_value_type* out,\n                   const typename std::enable_if<p==forward_plan>::type* = nullptr) const\n      {\n        const std::size_t N = size();\n        if(in!=out)\n        {\n          // we avoid this extra step for in-place transforms\n          // notice that if in==out, the following code has\n          // undefined-behavior\n          std::copy(in,in+N,out);\n        }\n        gsl_fft_real_transform(\n          out,1, N, real_wtable, real_wspace);\n        unpack_halfcomplex(out);\n      }\n      template<plan_type p>\n      void execute(const real_value_type* in, \n                   real_value_type* out,\n                   const typename std::enable_if<p==backward_plan>::type* = nullptr) const\n      {\n        const std::size_t N = size();\n        if(in!=out)\n        {\n          // we avoid this extra step for in-place transforms\n          // notice that if in==out, the following code has\n          // undefined-behavior\n          std::copy(in,in+N,out);\n        }\n        pack_halfcomplex(out);\n        gsl_fft_halfcomplex_transform(\n          out,1, N, halfcomplex_wtable, real_wspace);\n      }\n      \n      void free()\n      {\n        gsl_fft_real_wavetable_free(real_wtable);\n        gsl_fft_halfcomplex_wavetable_free(halfcomplex_wtable);\n        gsl_fft_real_workspace_free(real_wspace);\n      }\n      void alloc()\n      {\n        const std::size_t N = size();\n        real_wtable        = gsl_fft_real_wavetable_alloc(N);\n        halfcomplex_wtable = gsl_fft_halfcomplex_wavetable_alloc(N);\n        real_wspace        = gsl_fft_real_workspace_alloc(N);\n      }\n   public:\n      \n      gsl_rfft_backend(std::size_t n, const allocator_type& A= allocator_type{}):\n          my_size{n},\n          my_alloc{A}\n      {\n        alloc();\n      }\n        \n      ~gsl_rfft_backend()\n      {\n        free();\n      }\n      constexpr std::size_t size() const {return my_size;}\n      constexpr std::size_t unique_complex_size() const {return my_size/2 + 1;}\n      \n      void resize(std::size_t new_size)\n      {\n        if(size()!=new_size)\n        {\n          free();\n          my_size = new_size;\n          alloc();\n        }\n      }\n        \n      void real_to_halfcomplex(const real_value_type* in, real_value_type* out) const\n      {\n        execute<forward_plan>(in,out);\n      }\n      void halfcomplex_to_real(const real_value_type* in, real_value_type* out) const\n      {\n        execute<backward_plan>(in,out);\n      }\n    };\n    #endif\n  } // namespace detail    \n\n  #if defined(__GNUC__)\n  template<class RingType = std::complex<double>, class Allocator_t = std::allocator<RingType> >\n  using gsl_dft = detail::complex_dft<detail::gsl_backend,RingType,Allocator_t>;\n\n  template<class T = double, class Allocator_t = std::allocator<T> >\n  using gsl_rdft = detail::real_dft<detail::gsl_rfft_backend,T,Allocator_t>;\n\n  using gsl_transform = transform< gsl_dft<> >;\n  using gsl_real_transform = transform< gsl_rdft<> >;\n  #endif\n\n} // namespace fft\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_FFT_GSLBACKEND_HPP\n\n\n", "meta": {"hexsha": "603824456264661e5becd66e79ab04501a703d8f", "size": 7657, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/fft/gsl_backend.hpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/math/fft/gsl_backend.hpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "include/boost/math/fft/gsl_backend.hpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 28.6779026217, "max_line_length": 113, "alphanum_fraction": 0.585477341, "num_tokens": 1838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5367633430328965}}
{"text": "#ifndef EVALUATE_HPP\n#define EVALUATE_HPP\n\n\n#include <cstddef>\n#include <tuple>\n#include <type_traits>\n#include <utility>\n#include <boost/proto/proto.hpp>\n\n#include \"domain.hpp\"\n#include \"terminal.hpp\"\n#include \"tuple_expand.hpp\"\n#include \"var.hpp\"\n#include \"varstore.hpp\"\n\n\nnamespace sme { namespace detail {\n\n\n        namespace proto = boost::proto;\n\n\n        struct eval_result {\n            // create eval result\n            template<typename Value, typename VarStore>\n            static auto create(Value&& value, VarStore&& varstore) {\n                return std::make_tuple(std::forward<Value>(value), std::forward<VarStore>(varstore));\n            }\n\n            // get value from eval result\n            template<typename EvalResult>\n            static decltype(auto) get_value(EvalResult const& result) {\n                return std::get<0>(result);\n            }\n\n            // get varstore from eval result\n            template<typename EvalResult>\n            static decltype(auto) get_varstore(EvalResult const& result) {\n                return std::get<1>(result);\n            }\n        };\n\n\n        //\n        template<\n            typename Expr,\n            typename Tag = typename proto::tag_of<Expr>::type\n        >\n        struct eval;\n\n\n        // evaluate an expr with given varstore\n        template<typename Expr, typename VarStore>\n        auto evaluate(Expr const& expr, VarStore const& varstore) {\n            eval<Expr const> eval_function;\n            return eval_function(expr, varstore);\n        }\n\n\n        // +x, -x, !x ...\n        #define UNARY_OPERATOR(OP, TAG)                                                                                     \\\n            template<typename Expr>                                                                                         \\\n            struct eval<Expr, proto::tag::TAG> {                                                                            \\\n                template<typename VarStore>                                                                                 \\\n                auto operator()(Expr const& expr, VarStore const& varstore) const {                                         \\\n                    auto x = evaluate(proto::child(expr), varstore);                                                        \\\n                    return eval_result::create( OP eval_result::get_value(x), eval_result::get_varstore(x));                \\\n                }                                                                                                           \\\n            };\n\n\n        // x + y, x - y ...\n        #define BINARY_OPERATOR(OP, TAG)                                                                                    \\\n            template<typename Expr>                                                                                         \\\n            struct eval<Expr, proto::tag::TAG> {                                                                            \\\n                template<typename VarStore>                                                                                 \\\n                auto operator()(Expr const& expr, VarStore const& varstore) const {                                         \\\n                    auto computed_lhs = evaluate(proto::left(expr), varstore);                                              \\\n                    auto computed_rhs = evaluate(                                                                           \\\n                        proto::right(expr),                                                                                 \\\n                        varstore::create_view(eval_result::get_varstore(computed_lhs), varstore)                            \\\n                    );                                                                                                      \\\n                                                                                                                            \\\n                    auto new_varstore = varstore::create_view(                                                              \\\n                        eval_result::get_varstore(computed_rhs),                                                            \\\n                        eval_result::get_varstore(computed_lhs)                                                             \\\n                    );                                                                                                      \\\n                                                                                                                            \\\n                    return eval_result::create(                                                                             \\\n                        eval_result::get_value(computed_lhs) OP eval_result::get_value(computed_rhs),                       \\\n                        varstore::varstore_from_view(new_varstore)                                                          \\\n                    );                                                                                                      \\\n                }                                                                                                           \\\n            };\n\n\n        // x += y ...\n        #define COMPOUND_ASSIGNMENT_OPERATOR(OP, TAG)                                                                       \\\n            template<typename Expr>                                                                                         \\\n            struct eval<Expr, proto::tag::TAG> {                                                                            \\\n                template<typename VarStore>                                                                                 \\\n                auto operator()(Expr const& expr, VarStore const& varstore) const {                                         \\\n                    using VarId =                                                                                           \\\n                        typename proto::result_of::value<                                                                   \\\n                            typename proto::result_of::left<Expr const>::type                                               \\\n                        >::type;                                                                                            \\\n                    static_assert(                                                                                          \\\n                        terminal::is_var<VarId>::value,                                                                     \\\n                        \"\\n\\n\\n\\n*****     left hand side of an assignment must be a var     *****\\n\\n\\n\"                   \\\n                    );                                                                                                      \\\n                                                                                                                            \\\n                    auto computed_rhs = evaluate(proto::right(expr), varstore);                                             \\\n                    auto lhs = var::get_value(                                                                              \\\n                        varstore::get_var<VarId>(                                                                           \\\n                            varstore::create_view(eval_result::get_varstore(computed_rhs), varstore)                        \\\n                        )                                                                                                   \\\n                    );                                                                                                      \\\n                                                                                                                            \\\n                    lhs OP eval_result::get_value(computed_rhs);                                                            \\\n                                                                                                                            \\\n                    auto new_var = varstore::varstore_from_var(var::create_var<VarId>(lhs));                                \\\n                    auto new_varstore = varstore::create_view(                                                              \\\n                        new_var,                                                                                            \\\n                        eval_result::get_varstore(computed_rhs)                                                             \\\n                    );                                                                                                      \\\n                                                                                                                            \\\n                    return eval_result::create(lhs, varstore::varstore_from_view(new_varstore));                            \\\n                }                                                                                                           \\\n            };\n\n\n        // !sizeof(Expr) is always false\n        // it's there just to make sure the compiler doesn't assert until this struct actually instantiated\n        #define NOT_SUPPORTED_OPERATOR(OP, TAG)                                                                             \\\n            template<typename Expr>                                                                                         \\\n            struct eval<Expr, proto::tag::TAG> {                                                                            \\\n                static_assert(                                                                                              \\\n                    !sizeof(Expr),                                                                                          \\\n                    \"\\n\\n\\n\\n*****     \" #OP \" operator is not supported      *****\\n\\n\\n\"                                  \\\n                );                                                                                                          \\\n            };\n\n\n        UNARY_OPERATOR(+, unary_plus)\n        UNARY_OPERATOR(-, negate)\n        UNARY_OPERATOR(~, complement)\n        UNARY_OPERATOR(!, logical_not)\n        UNARY_OPERATOR(++, pre_inc)\n        UNARY_OPERATOR(--, pre_dec)\n        NOT_SUPPORTED_OPERATOR(*, dereference)\n        NOT_SUPPORTED_OPERATOR(&, address_of)\n        NOT_SUPPORTED_OPERATOR(++, post_inc)\n        NOT_SUPPORTED_OPERATOR(--, post_dec)\n\n        BINARY_OPERATOR(<<, shift_left)\n        BINARY_OPERATOR(>>, shift_right)\n        BINARY_OPERATOR(*, multiplies)\n        BINARY_OPERATOR(/, divides)\n        BINARY_OPERATOR(%, modulus)\n        BINARY_OPERATOR(+, plus)\n        BINARY_OPERATOR(-, minus)\n\n        BINARY_OPERATOR(<, less)\n        BINARY_OPERATOR(>, greater)\n        BINARY_OPERATOR(<=, less_equal)\n        BINARY_OPERATOR(>=, greater_equal)\n        BINARY_OPERATOR(==, equal_to)\n        BINARY_OPERATOR(!=, not_equal_to)\n\n        // cannot implement short circuit evaluation\n        BINARY_OPERATOR(||, logical_or)\n        BINARY_OPERATOR(&&, logical_and)\n\n        BINARY_OPERATOR(&, bitwise_and)\n        BINARY_OPERATOR(|, bitwise_or)\n        BINARY_OPERATOR(^, bitwise_xor)\n\n        COMPOUND_ASSIGNMENT_OPERATOR(<<=, shift_left_assign)\n        COMPOUND_ASSIGNMENT_OPERATOR(>>=, shift_right_assign)\n        COMPOUND_ASSIGNMENT_OPERATOR(*=, multiplies_assign)\n        COMPOUND_ASSIGNMENT_OPERATOR(/=, divides_assign)\n        COMPOUND_ASSIGNMENT_OPERATOR(%=, modulus_assign)\n        COMPOUND_ASSIGNMENT_OPERATOR(+=, plus_assign)\n        COMPOUND_ASSIGNMENT_OPERATOR(-=, minus_assign)\n        COMPOUND_ASSIGNMENT_OPERATOR(&=, bitwise_and_assign)\n        COMPOUND_ASSIGNMENT_OPERATOR(|=, bitwise_or_assign)\n        COMPOUND_ASSIGNMENT_OPERATOR(^=, bitwise_xor_assign)\n\n\n        #undef UNARY_OPERATOR\n        #undef BINARY_OPERATOR\n        #undef COMPOUND_ASSIGNMENT_OPERATOR\n        #undef NOT_SUPPORTED_OPERATOR\n\n\n        //\n        // terminal\n        //\n        template<typename Expr>\n        struct eval<Expr, proto::tag::terminal> {\n            // constant terminal\n            template<typename Terminal>\n            struct helper {\n                template<typename VarStore>\n                auto operator()(Expr const& expr, VarStore const& varstore) const {\n                    return eval_result::create(proto::value(expr), varstore::empty());\n                }\n            };\n\n\n            // var terminal\n            template<typename I>\n            struct helper<terminal::var<I>> {\n                template<typename VarStore>\n                auto operator()(Expr const& expr, VarStore const& varstore) const {\n                    return eval_result::create(\n                        var::get_value(varstore::get_var<terminal::var<I>>(varstore)),\n                        varstore::empty()\n                    );\n                }\n            };\n\n\n            template<typename VarStore>\n            auto operator()(Expr const& expr, VarStore const& varstore) const {\n                using Terminal = typename proto::result_of::value<Expr const>::type;\n                return helper<Terminal>{}(expr, varstore);\n            }\n        };\n\n\n        //\n        // x = y\n        //\n        template<typename Expr>\n        struct eval<Expr, proto::tag::assign> {\n            template<typename VarStore>\n            auto operator()(Expr const& expr, VarStore const& varstore) const {\n                // left hand side must be a var\n                using VarId =\n                    typename proto::result_of::value<\n                        typename proto::result_of::left<Expr const>::type\n                    >::type;\n                static_assert(\n                    terminal::is_var<VarId>::value,\n                    \"\\n\\n\\n\\n*****     left hand side of an assignment must be a var     *****\\n\\n\\n\"\n                );\n\n                auto computed_rhs = evaluate(proto::right(expr), varstore);\n                auto new_var = varstore::varstore_from_var(var::create_var<VarId>(eval_result::get_value(computed_rhs)));\n\n                auto new_varstore = varstore::create_view(\n                    new_var,\n                    eval_result::get_varstore(computed_rhs)\n                );\n\n                return eval_result::create(\n                    eval_result::get_value(computed_rhs),\n                    varstore::varstore_from_view(new_varstore)\n                );\n            }\n        };\n\n\n        //\n        // x(y, z, t)\n        //\n        template<typename Expr>\n        struct eval<Expr, proto::tag::function> {\n\n            // sme terminals\n            template<typename Ignore0, std::size_t IsSmeTerminal>\n            struct helper {\n                template<typename, std::size_t SmeTerminalId>\n                struct inner_helper;\n\n                // original function\n                template<typename Ignore1>\n                struct inner_helper<Ignore1, terminal::id::original_function> {\n                    template<std::size_t Begin, std::size_t End>\n                    struct collect_and_call {\n                        template<typename VarStore, typename Tuple>\n                        auto operator()(Expr const& expr, VarStore const& varstore, Tuple const& t) const {\n                            auto arg = evaluate(proto::child_c<Begin>(expr), varstore);\n                            decltype(auto) value = eval_result::get_value(arg);\n                            auto new_varstore = varstore::create_view(eval_result::get_varstore(arg), varstore);\n\n                            return collect_and_call<Begin+1, End>{}(expr, new_varstore, std::tuple_cat(t, std::tie(value)));\n                        }\n                    };\n\n\n                    template<std::size_t End>\n                    struct collect_and_call<End, End> {\n                        template<typename VarStore, typename Tuple>\n                        auto operator()(Expr const& expr, VarStore const& varstore, Tuple const& t) const {\n                            // expand the collected values from tuple to function\n                            return tuple_utility::expand(t, proto::value(proto::child_c<0>(expr)));\n                        }\n                    };\n\n\n                    template<typename VarStore>\n                    auto operator()(Expr const& expr, VarStore const& varstore) const {\n                        auto value = collect_and_call<1, proto::arity_of<Expr const>::value>{}(expr, varstore, std::tuple<>{});\n\n                        // return computed value\n                        return eval_result::create(value, varstore::empty());\n                    }\n                };\n\n\n                // scoped\n                template<typename Ignore1>\n                struct inner_helper<Ignore1, terminal::id::scoped> {\n                    template<typename VarStore>\n                    auto operator()(Expr const& expr, VarStore const& varstore) const {\n                        auto result = evaluate(proto::child_c<1>(expr), varstore);\n                        return eval_result::create(eval_result::get_value(result), varstore::empty());\n                    }\n                };\n\n\n                template<typename VarStore>\n                auto operator()(Expr const& expr, VarStore const& varstore) const {\n                    return inner_helper<\n                        void,\n                        terminal::sme_terminal_expr_id<\n                            typename proto::result_of::child_c<Expr const, 0>::type\n                        >::value\n                    >{}(expr, varstore);\n                }\n            };\n\n\n            // expr function\n            template<typename Ignore0>\n            struct helper<Ignore0, 0> {\n                template<std::size_t Begin, std::size_t End>\n                struct collect_and_call {\n                    template<typename VarStore>\n                    auto operator()(Expr const& expr, VarStore const& varstore) const {\n                        auto arg = evaluate(proto::child_c<Begin>(expr), varstore);\n                        auto new_varstore = varstore::create_view(eval_result::get_varstore(arg), varstore);\n\n                        return collect_and_call<Begin+1, End>{}(expr, new_varstore);\n                    }\n                };\n\n                template<std::size_t End>\n                struct collect_and_call<End, End> {\n                    template<typename VarStore>\n                    auto operator()(Expr const& expr, VarStore const& varstore) const {\n                        // looped through all arguments\n                        // now evaluate function\n                        auto result = evaluate(proto::child_c<0>(expr), varstore);\n\n                        // only return the value, ignore the varstore\n                        return eval_result::create(eval_result::get_value(result), varstore::empty());\n                    }\n                };\n\n\n                template<typename VarStore>\n                auto operator()(Expr const& expr, VarStore const& varstore) const {\n                    return collect_and_call<1, proto::arity_of<Expr const>::value>{}(expr, varstore);\n                }\n            };\n\n\n            template<typename VarStore>\n            auto operator()(Expr const& expr, VarStore const& varstore) const {\n                return helper<\n                    void,\n                    terminal::is_sme_terminal_expr<\n                        typename proto::result_of::child_c<Expr const, 0>::type\n                    >::value\n                >{}(expr, varstore);\n            }\n\n        };\n\n\n        //\n        // (x + y) ->* z\n        // compute (x + y), return z\n        //\n        template<typename Expr>\n        struct eval<Expr, proto::tag::mem_ptr> {\n            template<typename VarStore>\n            auto operator()(Expr const& expr, VarStore const& varstore) const {\n                auto computed_lhs = evaluate(proto::left(expr), varstore);\n                auto computed_rhs = evaluate(\n                    proto::right(expr),\n                    varstore::create_view(eval_result::get_varstore(computed_lhs), varstore)\n                );\n\n                auto new_varstore = varstore::create_view(\n                    eval_result::get_varstore(computed_rhs),\n                    eval_result::get_varstore(computed_lhs)\n                );\n\n                return eval_result::create(\n                    eval_result::get_value(computed_rhs),\n                    varstore::varstore_from_view(new_varstore)\n                );\n            }\n        };\n\n\n        //\n        // x[y]\n        //\n        template<typename Expr>\n        struct eval<Expr, proto::tag::subscript> {\n            template<typename VarStore>\n            auto operator()(Expr const& expr, VarStore const& varstore) const {\n                auto computed_lhs = evaluate(proto::left(expr), varstore);\n                auto computed_rhs = evaluate(\n                    proto::right(expr),\n                    varstore::create_view(eval_result::get_varstore(computed_lhs), varstore)\n                );\n\n                auto new_varstore = varstore::create_view(\n                    eval_result::get_varstore(computed_rhs),\n                    eval_result::get_varstore(computed_lhs)\n                );\n\n                return eval_result::create(\n                    eval_result::get_value(computed_lhs)[eval_result::get_value(computed_rhs)],\n                    varstore::varstore_from_view(new_varstore)\n                );\n            }\n        };\n\n\n        //\n        // x, y, z\n        //\n        template<typename Expr>\n        struct eval<Expr, proto::tag::comma> {\n            template<typename VarStore>\n            auto operator()(Expr const& expr, VarStore const& varstore) const {\n                auto computed_lhs = evaluate(proto::left(expr), varstore);\n                auto computed_rhs = evaluate(\n                    proto::right(expr),\n                    varstore::create_view(eval_result::get_varstore(computed_lhs), varstore)\n                );\n\n                auto new_varstore = varstore::create_view(\n                    eval_result::get_varstore(computed_rhs),\n                    eval_result::get_varstore(computed_lhs)\n                );\n\n                return eval_result::create(\n                    eval_result::get_value(computed_rhs),\n                    varstore::varstore_from_view(new_varstore)\n                );\n            }\n        };\n\n\n}} // namespace sme::detail\n\n\n#endif // EVALUATE_HPP\n", "meta": {"hexsha": "dc312b6cdc6effac70a7b397d5c95979f7fef67c", "size": 22682, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/simple-math-expression/sme/detail/evaluate.hpp", "max_stars_repo_name": "so61pi/examples", "max_stars_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-01T07:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T00:05:06.000Z", "max_issues_repo_path": "cpp/simple-math-expression/sme/detail/evaluate.hpp", "max_issues_repo_name": "so61pi/examples", "max_issues_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-02-24T13:04:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T10:19:48.000Z", "max_forks_repo_path": "cpp/simple-math-expression/sme/detail/evaluate.hpp", "max_forks_repo_name": "so61pi/examples", "max_forks_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-30T07:29:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-30T07:29:58.000Z", "avg_line_length": 48.4658119658, "max_line_length": 127, "alphanum_fraction": 0.401155101, "num_tokens": 3520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410784, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5367633409715105}}
{"text": "#include <iostream>\n#include <omp.h>\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n\n#include <unsupported/Eigen/SparseExtra> // For reading MatrixMarket files\n#include <unsupported/Eigen/IterativeSolvers>\n\n#include <amgcl/adapter/eigen.hpp>\n#include <amgcl/backend/builtin.hpp>\n#include <amgcl/make_solver.hpp>\n#include <amgcl/solver/bicgstab.hpp>\n#include <amgcl/solver/bicgstabl.hpp>\n#include <amgcl/solver/idrs.hpp>\n#include <amgcl/amg.hpp>\n#include <amgcl/coarsening/smoothed_aggregation.hpp>\n#include <amgcl/relaxation/spai0.hpp>\n#include <amgcl/relaxation/ilu0.hpp>\n#include <amgcl/relaxation/as_preconditioner.hpp>\n#include <amgcl/profiler.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <amgcl/adapter/eigen.hpp>\n#include <amgcl/backend/eigen.hpp>\n\n#include \"../include/config.hpp\"\n\n#ifdef USE_CUDA\n#include <amgcl/backend/cuda.hpp>\n#include <amgcl/relaxation/cusparse_ilu0.hpp>\n#endif\n#include \"cxxopts.hpp\"\n\nstruct LinearSystem\n{\n    Eigen::VectorXd b;\n    Eigen::VectorXd x0;\n    Eigen::SparseMatrix<double, Eigen::RowMajor> A;\n};\n\nstruct Convoptions\n{\n    int iterations;\n    double tolerance;\n};\n\nstruct returnvalue\n{\n    int iterations;\n    double error;\n    double error_exact;\n};\n\ntemplate <class T>\nreturnvalue RunEigen_Solver(amgcl::profiler<> &prof, Convoptions opt, const LinearSystem &Axb, const std::string &name)\n{\n\n    prof.tic(\"setup_\" + name);\n    T Solver;\n    Solver.setTolerance(opt.tolerance);\n    Solver.setMaxIterations(opt.iterations);\n    Solver.compute(Axb.A);\n    prof.toc(\"setup_\" + name);\n    prof.tic(\"solve_\" + name);\n    Eigen::VectorXd result_eigen = Solver.solveWithGuess(Axb.b, Axb.x0);\n    prof.toc(\"solve_\" + name);\n    returnvalue result;\n    result.iterations = Solver.iterations();\n    result.error = Solver.error();\n    result.error_exact=(Axb.A*result_eigen-Axb.b).norm()/Axb.b.norm();\n    return result;\n}\n\ntemplate <class T>\nreturnvalue RunAMGCLEigen_backend(amgcl::profiler<> &prof, Convoptions opt, const LinearSystem &Axb, const std::string &name)\n{\n\n    Eigen::VectorXd x = Axb.x0;\n    typename T::params prm;\n    prm.solver.tol = opt.tolerance;\n    prm.solver.maxiter = opt.iterations;\n    prof.tic(\"setup_\" + name);\n    T solve(Axb.A, prm);\n    prof.toc(\"setup_\" + name);\n    returnvalue result;\n    prof.tic(\"solve_\" + name);\n    std::tie(result.iterations, result.error) = solve(Axb.A, Axb.b, x);\n    prof.toc(\"solve_\" + name);\n    std::cout << solve << std::endl;\n    result.error_exact=(Axb.A*x-Axb.b).norm()/Axb.b.norm();\n    return result;\n}\n\ntemplate <class T>\nreturnvalue RunAMGCL_backend(amgcl::profiler<> &prof, Convoptions opt, const LinearSystem &Axb, const std::string &name)\n{\n\n    std::vector<double> x0 = std::vector<double>(Axb.x0.data(), Axb.x0.data() + Axb.x0.size());\n    std::vector<double> b = std::vector<double>(Axb.b.data(), Axb.b.data() + Axb.b.size());\n    size_t n = Axb.A.rows();\n    const int *ptr = Axb.A.outerIndexPtr();\n    const int *col = Axb.A.innerIndexPtr();\n    const double *val = Axb.A.valuePtr();\n    amgcl::backend::crs<double> A_amgcl(std::make_tuple(n,\n                                                        amgcl::make_iterator_range(ptr, ptr + n + 1),\n                                                        amgcl::make_iterator_range(col, col + ptr[n]),\n                                                        amgcl::make_iterator_range(val, val + ptr[n])));\n\n    typename T::params prm;\n    prm.solver.tol = opt.tolerance;\n    prm.solver.maxiter = opt.iterations;\n    prof.tic(\"setup_\" + name);\n    T solve(A_amgcl, prm);\n    prof.toc(\"setup_\" + name);\n    returnvalue result;\n    prof.tic(\"solve_\" + name);\n    std::tie(result.iterations, result.error) = solve(A_amgcl, b, x0);\n    prof.toc(\"solve_\" + name);\n    std::cout << solve << std::endl;\n    Eigen::Map<Eigen::VectorXd> x=Eigen::Map<Eigen::VectorXd>(x0.data(),x0.size());\n\n    result.error_exact=(Axb.A*x-Axb.b).norm()/Axb.b.norm();\n    return result;\n}\n\n#ifdef USE_CUDA\n\ntemplate <class T>\nreturnvalue RunAMGCLCUDA_backend(amgcl::profiler<> &prof, Convoptions opt, const LinearSystem &Axb, const std::string &name)\n{\n\n\tthrust::device_vector<double> X = std::vector<double>(Axb.x0.data(), Axb.x0.data() + Axb.x0.size());\n\tthrust::device_vector<double> F = std::vector<double>(Axb.b.data(), Axb.b.data() + Axb.b.size());\nsize_t n = Axb.A.rows();\n\n\n    amgcl::backend::cuda<double>::params bprm;\n    cusparseCreate(&bprm.cusparse_handle);\n    typename T::params prm;\n    prm.solver.tol = opt.tolerance;\n    prm.solver.maxiter = opt.iterations;\n    prof.tic(\"setup_\" + name);\n    T solve(Axb.A, prm,bprm);\n    prof.toc(\"setup_\" + name);\n    returnvalue result;\n    prof.tic(\"solve_\" + name);\n    std::tie(result.iterations, result.error) = solve(F, X);\n    prof.toc(\"solve_\" + name);\n    std::cout << solve << std::endl;\n    thrust::host_vector<double> X_cpu=X;\n    Eigen::Map<Eigen::VectorXd> x=Eigen::Map<Eigen::VectorXd>(X_cpu.data(),X_cpu.size());\n    result.error_exact=(Axb.A*x-Axb.b).norm()/Axb.b.norm();\n    return result;\n}\n#endif\n\nint main(int argc, char *argv[])\n{\n\n    cxxopts::Options options(\"SparseSolverBench\", \"Benchmarking various sparse linear solvers\");\n\n    options.add_options()(\"t,threads\", \"How many threads to use\", cxxopts::value<int>()->default_value(\"1\"))(\"s,tolerance\", \"Tolerance to which solvers should converge\", cxxopts::value<double>()->default_value(\"1e-12\"))(\"i,iterations\", \"max number of iterations\", cxxopts::value<int>()->default_value(\"1000\"))(\"A,SparseMatrix\", \"MM Format File for Sparse Matrix\", cxxopts::value<std::string>())(\"b,Rightside\", \"MM Format File for Vector\", cxxopts::value<std::string>())(\"x,initialguess\", \"MM Format File for InitialGuess\", cxxopts::value<std::string>())(\"h,help\", \"Print usage\");\n\n    auto result = options.parse(argc, argv);\n\n    if (result.count(\"help\"))\n    {\n        std::cout << options.help() << std::endl;\n        exit(0);\n    }\n\n    std::string intial_guess_filename = \"\";\n    if (result.count(\"initialguess\"))\n    {\n        intial_guess_filename = result[\"initialguess\"].as<std::string>();\n    }\n\n    Convoptions opt;\n\n    int threads = result[\"threads\"].as<int>();\n    opt.tolerance = result[\"tolerance\"].as<double>();\n    opt.iterations = result[\"iterations\"].as<int>();\n    std::string A_filename = result[\"SparseMatrix\"].as<std::string>();\n    std::string b_filename = result[\"Rightside\"].as<std::string>();\n\n    std::cout << \"Running profiler with \" << threads << \" threads\\n\"\n              << \"Required tolerance \" << opt.tolerance << \" num iterations \" << opt.iterations << \"\\nA:\" << A_filename << \"\\nb\" << b_filename << std::endl;\n    if (intial_guess_filename.size())\n    {\n        std::cout << \"x0:\" << intial_guess_filename << std::endl;\n    }\n    omp_set_num_threads(threads);\n\n    amgcl::profiler<> prof;\n    LinearSystem Axb;\n\n    prof.tic(\"read_input\");\n    Eigen::loadMarket(Axb.A, A_filename);\n\n    Eigen::loadMarketVector(Axb.b, b_filename);\n    Axb.x0 = Eigen::VectorXd::Zero(Axb.A.rows());\n    if (intial_guess_filename.size())\n    {\n        Eigen::loadMarketVector(Axb.x0, intial_guess_filename);\n    }\n    prof.toc(\"read_input\");\n\n    std::vector<std::string> names;\n    std::vector<returnvalue> results;\n\n    // Setup the solver:\n    typedef amgcl::make_solver<\n        amgcl::amg<\n            amgcl::backend::builtin<double>,\n            amgcl::coarsening::smoothed_aggregation,\n            amgcl::relaxation::spai0>,\n        amgcl::solver::bicgstab<amgcl::backend::builtin<double>>>\n        Solver_bicgstab;\nnames.push_back(\"amgcl_bicgstab\");\n  results.push_back(RunAMGCL_backend<Solver_bicgstab>(prof, opt, Axb, names.back()));\n\n    typedef amgcl::make_solver<\n        amgcl::relaxation::as_preconditioner<\n        amgcl::backend::builtin<double>,\n        amgcl::relaxation::ilu0>,\n        amgcl::solver::bicgstab<amgcl::backend::builtin<double>>>\n        Solver_bicgstab_ilut;\n  names.push_back(\"amgcl_bicgstab_ilut\");\n  results.push_back(RunAMGCL_backend<Solver_bicgstab_ilut>(prof, opt, Axb, names.back()));\n\n    // Setup the solver:\n    typedef amgcl::make_solver<\n        amgcl::amg<\n            amgcl::backend::builtin<double>,\n            amgcl::coarsening::smoothed_aggregation,\n            amgcl::relaxation::spai0>,\n        amgcl::solver::bicgstabl<amgcl::backend::builtin<double>>>\n        Solver_bicgstabl;\n   names.push_back(\"amgcl_bicgstabl\");\n   results.push_back(RunAMGCL_backend<Solver_bicgstabl>(prof, opt, Axb, names.back()));\n\n    // Setup the solver:\n    typedef amgcl::make_solver<\n        amgcl::amg<\n            amgcl::backend::builtin<double>,\n            amgcl::coarsening::smoothed_aggregation,\n            amgcl::relaxation::spai0>,\n        amgcl::solver::idrs<amgcl::backend::builtin<double>>>\n        Solver_idrs;\n\n   names.push_back(\"amgcl_idrs\");\n   results.push_back(RunAMGCL_backend<Solver_idrs>(prof, opt, Axb, names.back()));\n\n    // Setup the solver:\n    typedef amgcl::make_solver<\n        amgcl::amg<\n            amgcl::backend::eigen<double>,\n            amgcl::coarsening::smoothed_aggregation,\n            amgcl::relaxation::spai0>,\n        amgcl::solver::bicgstab<amgcl::backend::eigen<double>>>\n        Solver2;\n\n   names.push_back(\"amgcl_bicgstab_eigen\");\n   results.push_back(RunAMGCLEigen_backend<Solver2>(prof, opt, Axb, names.back()));\n\n  names.push_back(\"eigen_bicgstab\");\nresults.push_back(RunEigen_Solver<Eigen::BiCGSTAB<Eigen::SparseMatrix<double, Eigen::RowMajor>>>(prof, opt, Axb, names.back()));\n\n    names.push_back(\"eigen_bicgstabl\");\n    results.push_back(RunEigen_Solver<Eigen::BiCGSTABL<Eigen::SparseMatrix<double, Eigen::RowMajor>>>(prof, opt, Axb, names.back()));\n\n    names.push_back(\"eigen_idrstab\");\n    results.push_back(RunEigen_Solver<Eigen::IDRStab<Eigen::SparseMatrix<double, Eigen::RowMajor>>>(prof, opt, Axb, names.back()));\n\n#ifdef USE_CUDA\n\n    typedef amgcl::make_solver<\n        amgcl::amg<\n        amgcl::backend::cuda<double>,\n       amgcl::coarsening::smoothed_aggregation,\n            amgcl::relaxation::spai0>,\n        amgcl::solver::bicgstab<amgcl::backend::cuda<double>>>\n        Solver_cuda_bicgstab;\n    names.push_back(\"amgcl_cuda_bicgstab\");\n    results.push_back(RunAMGCLCUDA_backend<Solver_cuda_bicgstab>(prof, opt, Axb, names.back()));\n\n\n    typedef amgcl::make_solver<\n            amgcl::relaxation::as_preconditioner<\n            amgcl::backend::cuda<double>,\n            amgcl::relaxation::ilu0>,\n            amgcl::solver::bicgstab<amgcl::backend::cuda<double>>>\n            Solver_cuda_bicgstab_ilut;\n        names.push_back(\"amgcl_cuda_bicgstab_ilut\");\n        results.push_back(RunAMGCLCUDA_backend<Solver_cuda_bicgstab_ilut>(prof, opt, Axb, names.back()));\n    #endif\n\n\n    std::cout << \"Eigen uses \" << Eigen::nbThreads() << \" threads\" << std::endl;\n    for(int i=0;i<names.size();i++){\n        std::cout << names[i]<<\"\\t iter:\" << results[i].iterations << \"\\t error \" << results[i].error << \"\\t error_exact \" << results[i].error_exact <<std::endl;\n    }\n\n    std::cout << prof << std::endl;\n}\n", "meta": {"hexsha": "5bb7d6265610cba3c9316f8dde61b7a0cf6398c0", "size": 10975, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/benchmark.cpp", "max_stars_repo_name": "NLESC-JCER/sparse_solver", "max_stars_repo_head_hexsha": "59c44108f807034b740af7b5470788d40a2f962d", "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/benchmark.cpp", "max_issues_repo_name": "NLESC-JCER/sparse_solver", "max_issues_repo_head_hexsha": "59c44108f807034b740af7b5470788d40a2f962d", "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/benchmark.cpp", "max_forks_repo_name": "NLESC-JCER/sparse_solver", "max_forks_repo_head_hexsha": "59c44108f807034b740af7b5470788d40a2f962d", "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.9836065574, "max_line_length": 579, "alphanum_fraction": 0.6546697039, "num_tokens": 3111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.5367633384629732}}
{"text": "#pragma once\n\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\n#include \"hermite_to_nodal.hpp\"\n#include \"polar_to_hermite.hpp\"\n\n#include <omp.h>\n#include <Eigen/Dense>\n#include <cassert>\n#include <memory>\n#include <string>\n\nnamespace boltzmann {\n\ntemplate <typename PolarBasis = SpectralBasisFactoryKS::basis_type>\nclass Polar2Nodal\n{\n public:\n  typedef PolarBasis polar_basis_t;\n  typedef SpectralBasisFactoryHN::basis_type hermite_basis_t;\n  typedef Polar2Hermite<polar_basis_t, hermite_basis_t> p2h_t;\n  typedef Hermite2Nodal<hermite_basis_t> h2n_t;\n\n public:\n  Polar2Nodal() { /* empty */}\n\n  /**\n   *  @brief Transform coefficients btw Polar-Laguerre and nodal basis. The\n   *         nodes of the nodal basis are located at the underlying\n   *         Gauss-Hermite quadrature points.\n   *\n   *  @param polar_basis Polar-Laguerre basis object\n   *  @param a exp weight factor in quad rule, e.g. for basis functions which\n   *           decay like \\f$exp(-r^/2)\\f$, @param a is 1.0\n   */\n  Polar2Nodal(const polar_basis_t &polar_basis, double a = 1.0);\n\n public:\n  void init(const polar_basis_t &polar_basis, double a);\n  std::shared_ptr<p2h_t> get_p2h() const { return p2h_; }\n  std::shared_ptr<h2n_t> get_h2n() const { return h2n_; }\n  /// size Polar-Laguerre basis\n  int N() const { return N_; }\n  /// max. polynomial degree\n  int K() const { return K_; }\n\n  template <typename DERIVED1, typename DERIVED2>\n  void to_nodal(Eigen::DenseBase<DERIVED1> &dst,\n                const Eigen::DenseBase<DERIVED2> &src,\n                bool transpose = false) const;\n\n  template <typename DERIVED1, typename DERIVED2>\n  void to_polar(Eigen::DenseBase<DERIVED1> &dst,\n                const Eigen::DenseBase<DERIVED2> &src,\n                bool transpose = false) const;\n\n  bool is_initialized() const { return is_initialized_; }\n\n private:\n  std::shared_ptr<p2h_t> p2h_;\n  std::shared_ptr<h2n_t> h2n_;\n  int N_;\n  int K_;\n  bool is_initialized_ = false;\n\n  thread_local static ArrayBuffer<> buf_;\n};\n\ntemplate <typename PolarBasis>\nthread_local ArrayBuffer<> Polar2Nodal<PolarBasis>::buf_;\n\ntemplate <typename PolarBasis>\nPolar2Nodal<PolarBasis>::Polar2Nodal(const polar_basis_t &polar_basis, double a)\n{\n  this->init(polar_basis, a);\n}\n\n//  -------------------------------------------------------------------------------------\ntemplate <typename PolarBasis>\nvoid\nPolar2Nodal<PolarBasis>::init(const polar_basis_t &polar_basis, double a)\n{\n  K_ = spectral::get_max_k(polar_basis) + 1;\n  N_ = polar_basis.n_dofs();\n\n  hermite_basis_t hermite_basis;\n  SpectralBasisFactoryHN::create(hermite_basis, K_, 2);\n\n  assert(hermite_basis.n_dofs() == polar_basis.n_dofs());\n\n  // make_unique not available in c++11\n  // p2h_ = std::make_unique<p2h_t>(polar_basis, hermite_basis);\n  // h2n_ = std::make_unique<h2n_t>(hermite_basis, K);\n  typedef Eigen::MatrixXd mat_t;\n  p2h_ = std::make_shared<p2h_t>(polar_basis, hermite_basis);\n  const int K = K_;\n  if (a == 1.0) {\n    h2n_ = std::make_shared<h2n_t>(\n        hermite_basis, K_, [K](mat_t &m1, mat_t &m2) { H2N_1d<>::create(m1, m2, K); });\n  } else {\n    h2n_ = std::make_shared<h2n_t>(\n        hermite_basis, K_, [K, a](mat_t &m1, mat_t &m2) { H2NG_1d::create(m1, m2, K, a); });\n  }\n\n  is_initialized_ = true;\n}\n\n// //\n// --------------------------------------------------------------------------------------\n// template<typename PolarBasis>\n// void Polar2Nodal<PolarBasis>::\n// to_nodal(numeric_t* dst, const numeric_t* src, bool transpose) const\n// {\n//   typedef Eigen::Map<Eigen::VectorXd> mvec_t;\n//   auto buffer = buf_.get<mvec_t>(N_);\n\n//  if(!transpose) {\n//     p2h_->to_hermite(buffer, src);\n//     h2n_->to_nodal(dst, buffer);\n//   } else {\n//     throw std::runtime_error(std::string(__FILE__)\n//                              + \":\" + std::to_string(__LINE__) + \" not\n//                              implemented\");\n//   }\n// }\n\n// template<typename PolarBasis>\n// void Polar2Nodal<PolarBasis>::\n// to_polar(numeric_t* dst, const numeric_t* src, bool transpose) const\n// {\n//   auto buffer = buf_.get<Eigen::VectorXd>(N_);\n\n//   if(!transpose) {\n//     h2n_->to_hermite(buffer, src);\n//     p2h_->to_polar(dst, buffer);\n//   } else {\n//     throw std::runtime_error(std::string(__FILE__)\n//                              + \":\" + std::to_string(__LINE__) + \" not\n//                              implemented\");\n//   }\n// }\n\ntemplate <typename PolarBasis>\ntemplate <typename DERIVED1, typename DERIVED2>\nvoid\nPolar2Nodal<PolarBasis>::to_nodal(Eigen::DenseBase<DERIVED1> &dst,\n                                  const Eigen::DenseBase<DERIVED2> &src,\n                                  bool transpose) const\n{\n  auto buffer = buf_.get<Eigen::VectorXd>(N_);\n  BOOST_ASSERT(is_initialized_);\n\n  if (!transpose) {\n    p2h_->to_hermite(buffer, src);\n    h2n_->to_nodal(dst, buffer);\n  } else {\n    throw std::runtime_error(std::string(__FILE__) + \":\" + std::to_string(__LINE__) +\n                             \" not implemented\");\n  }\n}\n\ntemplate <typename PolarBasis>\ntemplate <typename DERIVED1, typename DERIVED2>\nvoid\nPolar2Nodal<PolarBasis>::to_polar(Eigen::DenseBase<DERIVED1> &dst,\n                                  const Eigen::DenseBase<DERIVED2> &src,\n                                  bool transpose) const\n{\n  BOOST_ASSERT(is_initialized_);\n  auto buffer = buf_.get<Eigen::VectorXd>(N_);\n\n  if (!transpose) {\n    h2n_->to_hermite(buffer, src);\n    p2h_->to_polar(dst, buffer);\n  } else {\n    throw std::runtime_error(std::string(__FILE__) + \":\" + std::to_string(__LINE__) +\n                             \" not implemented\");\n  }\n}\n}  // end namespace boltzmann\n", "meta": {"hexsha": "478ca62d1423810d975e42717c0b4a2e035ea58b", "size": 5733, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/polar_to_nodal.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/polar_to_nodal.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/polar_to_nodal.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": 31.1576086957, "max_line_length": 92, "alphanum_fraction": 0.6312576313, "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5367633371215204}}
{"text": "#include <igl/copyleft/marching_cubes.h>\n#include <igl/sparse_voxel_grid.h>\n#include <igl/opengl/glfw/Viewer.h>\n\n#include <Eigen/Core>\n#include <iostream>\n\n#include \"tutorial_shared_path.h\"\n\nint main(int argc, char * argv[])\n{\n  // An implicit function which is zero on the surface of a sphere centered at the origin with radius 1\n  // This function is negative inside the surface and positive outside the surface\n  std::function<double(const Eigen::RowVector3d&)> scalar_func = [](const Eigen::RowVector3d& pt) -> double {\n    return pt.norm() - 1.0;\n  };\n\n  // We know that the point (0, 0, 1) lies on the implicit surface\n  Eigen::RowVector3d p0(0., 0., 1.);\n\n  // Construct a sparse voxel grid whose cubes have edge length eps = 0.1.\n  // The cubes will form a thin shell around the implicit surface\n  const double eps = 0.1;\n\n  // CS will hold one scalar value at each cube vertex corresponding\n  // the value of the implicit at that vertex\n  Eigen::VectorXd CS;\n\n  // CV will hold the positions of the corners of the sparse voxel grid\n  Eigen::MatrixXd CV;\n\n  // CI is a #cubes x 8 matrix of indices where each row contains the\n  // indices into CV of the 8 corners of a cube\n  Eigen::MatrixXi CI;\n\n  // Construct the voxel grid, populating CS, CV, and CI\n  igl::sparse_voxel_grid(p0, scalar_func, eps, 1024 /*expected_number_of_cubes*/, CS, CV, CI);\n\n  // Given the sparse voxel grid, use Marching Cubes to construct a triangle mesh of the surface\n  Eigen::MatrixXi F;\n  Eigen::MatrixXd V;\n  igl::copyleft::marching_cubes(CS, CV, CI, V, F);\n\n  // Draw the meshed implicit surface\n  igl::opengl::glfw::Viewer viewer;\n  viewer.data().clear();\n  viewer.data().set_mesh(V,F);\n  viewer.data().set_face_based(true);\n  viewer.launch();\n}\n", "meta": {"hexsha": "c2b6f0b0ef987d0ab1a9310a43c2fc68069ee68a", "size": 1738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isometric-deformation/ext/libigl/tutorial/715_MeshImplicitFunction/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/715_MeshImplicitFunction/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/715_MeshImplicitFunction/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": 34.0784313725, "max_line_length": 109, "alphanum_fraction": 0.7105868815, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5367633325515978}}
{"text": "#pragma once\n\n#include \"algorithms/util/PeakDetection.hpp\"\n#include \"algorithms/public/DataSetIdSequence.hpp\"\n#include \"algorithms/util/DistanceFuncs.hpp\"\n#include \"algorithms/public/KDTree.hpp\"\n#include \"algorithms/public/KMeans.hpp\"\n#include \"algorithms/public/MelBands.hpp\"\n#include \"algorithms/util/AlgorithmUtils.hpp\"\n#include \"algorithms/util/FluidEigenMappings.hpp\"\n#include \"algorithms/util/MedianFilter.hpp\"\n#include \"algorithms/util/SpectralEmbedding.hpp\"\n#include \"data/TensorTypes.hpp\"\n#include \"data/FluidDataSet.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <vector>\n#include <fstream>\n#include <random>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass GraphPlayUtils {\n\npublic:\n  using  MatrixXd = Eigen::MatrixXd;\n  using  VectorXd = Eigen::VectorXd;\n  using DataSet = FluidDataSet<std::string, double, 1>;\n\n  GraphPlayUtils(){\n    using namespace std;\n    random_device rd;\n    mGen = mt19937(rd());\n    mDis = uniform_real_distribution<> (0.0, 1.0);\n    mFilter.init(5);\n  }\n\n  index randInt(index N){\n    return static_cast<index>(mDis(mGen) * N);\n  }\n\n  double rand(){\n    return mDis(mGen);\n  }\n\n  Eigen::ArrayXXd computeDM(RealMatrixView mag, index numBands,\n    double sampleRate, index windowSize, index fftSize, index dist){\n    using namespace Eigen;\n    using namespace _impl;\n    MelBands melBands = MelBands(numBands, fftSize);\n    melBands.init(20, 5000, numBands, mag.cols(), sampleRate, windowSize);\n    RealMatrix melSpec = RealMatrix(mag.rows(), numBands);\n    for(index i = 0; i < mag.rows(); i++){\n      melBands.processFrame(mag.row(i), melSpec.row(i), true, false, false);\n    }\n    MatrixXd tmp = asEigen<Matrix>(melSpec);\n    return DistanceMatrix(tmp, dist);\n  }\n\n  void onsetDetection(Eigen::Ref<Eigen::ArrayXd> odf,\n                      Eigen::Ref<Eigen::ArrayXXd> transitions, index offset = 2){\n    for(index i = 0; i < odf.size(); i++){\n      odf(i) = odf(i) - mFilter.processSample(odf(i));\n    }\n    auto onsets = mPD.process(odf, 0, 0.1, false, false);\n    for(index i = 0; i < onsets.size(); i++){\n      index pos = onsets[i].first;\n      index start = std::max(index(0), pos - offset);\n      index end = std::min(transitions.rows() - 1, pos + offset + 1);\n      transitions.block(start, 0, end - start, transitions.cols()).setZero();\n      transitions.block(0, start, transitions.rows(), end - start).setZero();\n    }\n  }\n\n  FluidTensor<index, 1> kmeans(RealMatrixView data, index nClusters){\n      algorithm::DataSetIdSequence seq(\"\", 0, 0);\n      index minClusterSize = 10;\n      DataSet tmpDS = DataSet(data.cols());\n      for(index i = 0; i < data.rows(); i++){\n        tmpDS.add(seq.next(), data.row(i));\n      }\n      mKMeans.clear();\n      mKMeans.train(tmpDS, nClusters, 100);\n      FluidTensor<index, 1> clusters(data.rows());\n      mKMeans.getAssignments(clusters);\n      RealMatrix means(mKMeans.size(), mKMeans.dims());\n      mKMeans.getMeans(means);\n      for(index i = 0; i < nClusters; i++){\n        index cSize = mKMeans.getClusterSize(i);\n        //std::cout<<cSize<<std::endl;\n        if(cSize > 0 && cSize < minClusterSize){\n          RealMatrix distances(1, mKMeans.size());\n          RealMatrix mean(1, mKMeans.dims());\n          mean.row(0) =  means.col(i);\n          mKMeans.getDistances(mean, distances);\n          index closest = std::min_element(distances.begin(), distances.end()) - distances.begin();\n          for(index j = 0; j < clusters.size(); j++)\n            if(clusters(j) == i) clusters(j) = closest;\n        }\n      }\n      //std::ofstream ofs (\"clusters.mat\", std::ofstream::out);ofs << clusters;ofs.close();\n      return clusters;\n  }\n\n  void writeMatrix(Eigen::Ref<Eigen::MatrixXd> mat, std::string name){\n    //std::ofstream ofs (name+\".mat\", std::ofstream::out);ofs << mat;ofs.close();\n  }\n\n  FluidTensor<index, 1>  spectralClustering(Eigen::Ref<Eigen::ArrayXXd> dm, index numClusters = 0){\n    using namespace Eigen;\n    index maxClusters = numClusters > 0? numClusters : std::min(index(50), dm.rows());\n    index nPoints = dm.rows();\n    MatrixXd tmpRp = (dm.array() < 0.25).cast<double>();\n    MatrixXd weightedGraph = (1 - dm) * tmpRp.array();\n    SpectralEmbedding spectralEmbedding;\n    spectralEmbedding.train(weightedGraph.sparseView(), maxClusters);\n    if(numClusters == 0 ){\n      VectorXd eigenValues  =  spectralEmbedding.eigenValues();\n      ArrayXd diff = (\n        eigenValues.segment(1, eigenValues.size() - 2) -\n        eigenValues.segment(0, eigenValues.size() - 2));\n        VectorXd::Index maxIndex;\n        double maxVal = diff.maxCoeff(&maxIndex);\n        numClusters = std::min(2*(maxIndex + 1), maxClusters);\n    }\n    MatrixXd eigenVectors = spectralEmbedding.eigenVectors().block(0,0, nPoints, numClusters);\n    eigenVectors.rowwise().normalize();\n    return kmeans( _impl::asFluid(eigenVectors), numClusters);\n  }\n\n\nprivate:\n  MedianFilter mFilter;\n  PeakDetection mPD;\n  KMeans mKMeans;\n  std::mt19937 mGen;\n  std::uniform_real_distribution<> mDis;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "96cc6baac11fca1606c803a290e320f09a30f1d9", "size": 5034, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/GraphPlayUtils.hpp", "max_stars_repo_name": "flucoma/graph_loop_grain", "max_stars_repo_head_hexsha": "db9bbc603412d44a49b0d882bc3fdb604aeb63d1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-06-05T10:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T10:40:25.000Z", "max_issues_repo_path": "include/algorithms/GraphPlayUtils.hpp", "max_issues_repo_name": "flucoma/graph_loop_grain", "max_issues_repo_head_hexsha": "db9bbc603412d44a49b0d882bc3fdb604aeb63d1", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/GraphPlayUtils.hpp", "max_forks_repo_name": "flucoma/graph_loop_grain", "max_forks_repo_head_hexsha": "db9bbc603412d44a49b0d882bc3fdb604aeb63d1", "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.4507042254, "max_line_length": 99, "alphanum_fraction": 0.6557409615, "num_tokens": 1359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5367497243350547}}
{"text": "// ========================================================================= //\n// Filename      :  test_sampling.cpp\n// Creation Date :  2016-6-21\n// Created by    :  anfranek\n// ========================================================================= //\n\n#include <gtest/gtest.h>\n\n#include <cmath>\n\n#include <Eigen/Core>\n\n#include \"sampling.h\"\n\nTEST(equidistant_sampling, two_point_line)\n{\n    util::AlignedVecOfVec2d line = {{0, 0}, {4, 0}};\n\n    util::AlignedVecOfVec2d expected = {{0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}};\n    auto sampled = util::sample_equidistant(line, 5);\n\n    EXPECT_EQ(expected, sampled);\n}\n\nTEST(equidistant_sampling, three_point_line)\n{\n    util::AlignedVecOfVec2d line = {{0, 0}, {1, 1}, {2, 0}};\n\n    util::AlignedVecOfVec2d expected = {{0, 0}, {2./3., 2./3.}, {4./3., 2./3.}, {2, 0}};\n    auto sampled = util::sample_equidistant(line, 4);\n\n    for(int i = 0; i < static_cast<int>(expected.size()); i++)\n    {\n        EXPECT_DOUBLE_EQ(expected[i][0], sampled[i][0]);\n        EXPECT_DOUBLE_EQ(expected[i][1], sampled[i][1]);\n    }\n}\n", "meta": {"hexsha": "55cd69d5da3dfc6ca48450ae38709f06c8363188", "size": 1064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_sampling.cpp", "max_stars_repo_name": "andy-held/gesture_recog", "max_stars_repo_head_hexsha": "2e7c0a399dbe0f4a02b37cd4ed42782b62018d10", "max_stars_repo_licenses": ["MIT"], "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_sampling.cpp", "max_issues_repo_name": "andy-held/gesture_recog", "max_issues_repo_head_hexsha": "2e7c0a399dbe0f4a02b37cd4ed42782b62018d10", "max_issues_repo_licenses": ["MIT"], "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_sampling.cpp", "max_forks_repo_name": "andy-held/gesture_recog", "max_forks_repo_head_hexsha": "2e7c0a399dbe0f4a02b37cd4ed42782b62018d10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 88, "alphanum_fraction": 0.5131578947, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5366843735786118}}
{"text": "/**\n* @file distance.hpp\n* @author Toyas Dhake (Driver), Shivam Akhauri (Navigator)\n* @date 11 October 2019\n* @copyright 2019 Toyas Dhake, Shivam Akhauri\n* @brief This is a class for depth perception module based on image from single \n* camera. \n*/\n\n#ifndef INCLUDE_DISTANCE_HPP_\n#define INCLUDE_DISTANCE_HPP_\n\n#include <dlib/image_processing/frontal_face_detector.h>\n#include <vector>\n#include <opencv2/opencv.hpp>\n#include <face.hpp>\n\nclass CalculateDistance {\n private:\n    // width of the face in the refernce image\n    double knownWidth = 7.0;\n    // distance of the face in the refernce image\n    double knownDistance = 36.0;\n public:\n    // focal length of the camera\n    double focalLength;\n    // the calculated distance of the detcetd face in the frame\n    double realTimeDistance = 0;\n    double calculateFocalLength();\n    // constructor\n    CalculateDistance();\n    // function to pass each detected face in the\n    // frame to calculateFocalLength function\n    std::vector<Face> getDistance(cv::Mat image,\n                                        dlib::frontal_face_detector detector);\n    // function to calculate distance of the frame which contains formula\n    double calDist(double width, double focalLength);\n};\n\n\n#endif  // INCLUDE_DISTANCE_HPP_\n", "meta": {"hexsha": "78197d7022609a44268c0fda015054cec5a5146e", "size": 1265, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/distance.hpp", "max_stars_repo_name": "shivamakhauri04/midterm_project", "max_stars_repo_head_hexsha": "4d062d90cb459d035fa9453aa837463b1e72f5a5", "max_stars_repo_licenses": ["MIT"], "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/distance.hpp", "max_issues_repo_name": "shivamakhauri04/midterm_project", "max_issues_repo_head_hexsha": "4d062d90cb459d035fa9453aa837463b1e72f5a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-10-19T06:55:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-21T15:08:33.000Z", "max_forks_repo_path": "include/distance.hpp", "max_forks_repo_name": "shivamakhauri04/midterm_project", "max_forks_repo_head_hexsha": "4d062d90cb459d035fa9453aa837463b1e72f5a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-19T02:12:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-19T02:12:38.000Z", "avg_line_length": 30.119047619, "max_line_length": 80, "alphanum_fraction": 0.7114624506, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5366843650244345}}
{"text": "//\n// $Id$\n//\n//\n// Original author: Witold Wolski <wewolski@gmail.com>\n//\n// Copyright : ETH Zurich\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 GAUSSFILTERTYPES_H\n#define GAUSSFILTERTYPES_H\n\n#include <boost/math/distributions/normal.hpp>\n#include \"pwiz/utility/findmf/base/filter/utilities/gauss.hpp\"\n\n\nnamespace ralab{\n  namespace base{\n    namespace filter{\n\n      /*! \\brief generate the gauss filter function for filtering of peaks with fwhm (full width at half max)\n\n                        \\post accumulate(gauss) == 1.\n                        \\return accumulate(gauss) == 1.\n                        */\n      template <typename TReal>\n      TReal getGaussianFilter\n      (\n          std::vector<TReal> & gauss, //!<[out] Gaussian for filtering\n          TReal fwhm = 20 //!<[in] full width at half max in points\n          )\n      {\n        std::vector<TReal> x;\n        ralab::base::base::seq<TReal>( -ceil(TReal(2*fwhm)), ceil(TReal(2*fwhm)) , x);\n        TReal sigma = fwhm/2.35;\n        //generate response\n        return utilities::getGaussWorker(sigma, gauss, x);\n      }\n\n      /*! \\brief generate the gauss filter function for filtering of peaks with fwhm (full width at half max)\n\n                        \\post accumulate(gauss) == 1.\n                        \\return accumulate(gauss) == 1.\n                        */\n      template <typename TReal>\n      TReal getGaussianFilterQuantile\n      (\n          std::vector<TReal> & gauss, //!<[out] Gaussian for filtering\n          TReal fwhm = 20, //!<[in] full width at half max in points\n          TReal quantile = 0.01 //!< would mean that the generated distribution covers at least 99.8 of mass\n          )\n      {\n        if( quantile >= 0.5)\n          {\n            throw std::logic_error(\"quantile >= 0.5\");\n          }\n        std::vector<TReal> x;\n\n        TReal sigma = fwhm/2.35;\n        boost::math::normal_distribution<TReal> nd_(0,sigma);\n        TReal quant = floor(boost::math::quantile(nd_,quantile));\n        ralab::base::base::seq( quant , -quant , x);\n        return utilities::getGaussWorker(sigma, gauss, x);\n\n      }\n\n\n      /*! \\brief generate first derivative Gauss\n\n                        \\post accumulate(gauss1d) == 0.\n                        \\post accumulate(fabs(gauss1d)) == 1.\n                        */\n\n      template <typename TReal>\n      TReal getGaussian1DerFilter(\n          std::vector<TReal> & gauss1d, //!<[out] Gaussian for filtering\n          TReal fwhm = 20 //!<[in] full width at half max in points\n          )\n      {\n        std::vector<TReal> x;\n        ralab::base::base::seq( - ceil(TReal(2*fwhm)), ceil(TReal(2*fwhm)) , x);\n        TReal sigma = fwhm/2.35;\n        //generate response\n        return utilities::getGaussian1DerWorker(sigma, gauss1d, x);\n      }\n\n\n\n      template <typename TReal>\n      TReal getGaussian1DerFilterQuantile(\n          std::vector<TReal> & gauss1d, //!<[out] Gaussian for filtering\n          TReal fwhm = 20, //!<[in] full width at half max in points\n          TReal quantile = 0.1\n          )\n      {\n        if( quantile >= 0.5)\n          {\n            throw std::logic_error(\"quantile >= 0.5\");\n          }\n        std::vector<TReal> x;\n        TReal sigma = fwhm/2.35;\n        boost::math::normal_distribution<TReal> nd_(0,sigma);\n        TReal quant = floor(boost::math::quantile(nd_,quantile));\n        ralab::base::base::seq( quant , -quant , x);\n        //generate response\n        return utilities::getGaussian1DerWorker(sigma, gauss1d, x);\n      }\n    }//filter\n  }//base\n}//ralab\n\n#endif\n", "meta": {"hexsha": "c056ad2a38779f74f41b6e5c8800b5e74aff6ba2", "size": 4072, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/findmf/base/filter/gaussfilter.hpp", "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/findmf/base/filter/gaussfilter.hpp", "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/findmf/base/filter/gaussfilter.hpp", "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": 32.576, "max_line_length": 109, "alphanum_fraction": 0.5822691552, "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5366462725401188}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2006 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 lmdif.hpp\n    \\brief wrapper for MINPACK minimization routine\n*/\n\n#ifndef quantlib_optimization_lmdif_hpp\n#define quantlib_optimization_lmdif_hpp\n\n#include <ql/qldefines.hpp>\n#include <boost/function.hpp>\n\nnamespace QuantLib {\n\n    namespace MINPACK {\n        typedef boost::function<void (int,\n                                      int, \n                                      double*,\n                                      double*,\n                                      int*)> LmdifCostFunction;\n\n        void lmdif(int m,int n,double* x,double* fvec,double ftol,\n                   double xtol,double gtol,int maxfev,double epsfcn,\n                   double* diag, int mode, double factor,\n                   int nprint, int* info,int* nfev,double* fjac,\n                   int ldfjac,int* ipvt,double* qtf,\n                   double* wa1,double* wa2,double* wa3,double* wa4,\n                   const LmdifCostFunction& fcn);\n        \n        void qrsolv(int n,double* r,int ldr,int* ipvt,\n                    double* diag,double* qtb, double* x,\n                    double* sdiag,double* wa);\n        void qrfac(int m,int n,double* a,int, int pivot,int* ipvt,\n                   int,double* rdiag,double* acnorm,double* wa);\n    }\n}\n#endif\n", "meta": {"hexsha": "38cec5f924482e1afb7396507c797a3f23e1633f", "size": 2055, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantLib/ql/math/optimization/lmdif.hpp", "max_stars_repo_name": "frannuca/quantlib", "max_stars_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "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": "QuantLib/ql/math/optimization/lmdif.hpp", "max_issues_repo_name": "frannuca/quantlib", "max_issues_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/ql/math/optimization/lmdif.hpp", "max_forks_repo_name": "frannuca/quantlib", "max_forks_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-24T04:54:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T04:54:18.000Z", "avg_line_length": 37.3636363636, "max_line_length": 79, "alphanum_fraction": 0.6145985401, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5366462725401187}}
{"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_MATH_HPP\n#define SPRIG_MATH_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/type_traits/is_arithmetic.hpp>\n#include <boost/mpl/and.hpp>\n#include <boost/mpl/not.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <sprig/type_traits/is_call_copy_param.hpp>\n\nnamespace sprig {\n\t//\n\t// integer_digits\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tboost::mpl::and_<\n\t\t\ttypename boost::is_arithmetic<T>::type,\n\t\t\ttypename is_call_copy_param<T>::type\n\t\t>,\n\t\tstd::size_t\n\t>::type\n\tinteger_digits(T const t) {\n\t\treturn static_cast<std::size_t>(std::ceil(std::log10(t)));\n\t}\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tboost::mpl::and_<\n\t\t\ttypename boost::is_arithmetic<T>::type,\n\t\t\ttypename boost::mpl::not_<typename is_call_copy_param<T>::type>::type\n\t\t>,\n\t\tstd::size_t\n\t>::type\n\tinteger_digits(T const& t) {\n\t\treturn static_cast<std::size_t>(std::ceil(std::log10(t)));\n\t}\n\t//\n\t// numeric_abs\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<sprig::is_call_copy_param<T>, T>::type\n\tnumeric_abs(T const t) {\n\t\treturn t < 0 ? -t : t;\n\t}\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::disable_if<sprig::is_call_copy_param<T>, T>::type\n\tnumeric_abs(T const& t) {\n\t\treturn t < 0 ? -t : t;\n\t}\n} // namespace sprig\n\n#endif\t// #ifndef SPRIG_MATH_HPP\n", "meta": {"hexsha": "0ea9b6dbf829157509b155169e02c64225e72d38", "size": 1844, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sprig/math.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/math.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/math.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": 27.5223880597, "max_line_length": 79, "alphanum_fraction": 0.6637744035, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5366462725401187}}
{"text": "#include \"geometrycentral/numerical/linear_solvers.h\"\n#include \"geometrycentral/surface/manifold_surface_mesh.h\"\n#include \"geometrycentral/surface/meshio.h\"\n#include \"geometrycentral/surface/simple_polygon_mesh.h\"\n#include \"geometrycentral/surface/vertex_position_geometry.h\"\n\n#include <emscripten/bind.h>\n#include <emscripten/val.h>\n\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n\n#include \"geometrycentral/surface/manifold_surface_mesh.h\"\n#include \"geometrycentral/surface/simple_polygon_mesh.h\"\n#include \"geometrycentral/surface/trace_geodesic.h\"\n#include \"geometrycentral/surface/vertex_position_geometry.h\"\n\n#include \"Walker.h\"\n\nusing namespace emscripten;\nusing namespace geometrycentral;\nusing namespace geometrycentral::surface;\n\nstruct GeoMesh {\n  std::unique_ptr<ManifoldSurfaceMesh> mesh;\n  std::unique_ptr<VertexPositionGeometry> geo;\n};\n\nstruct StepResult {\n  Vector3 T, N, B, pos;\n  Vector2 dir;\n  SurfacePoint surfacePos;\n  std::vector<Vector3> trajectory;\n};\n\n// Stolen from Ricky Reusser https://observablehq.com/d/d0df0c04ce5c94FCC\ntemplate <typename T>\nvoid copyToVector(const val &typedArray, std::vector<T> &vec) {\n  unsigned int length = typedArray[\"length\"].as<unsigned int>();\n  val memory = val::module_property(\"buffer\");\n  vec.reserve(length);\n  val memoryView = typedArray[\"constructor\"].new_(\n      memory, reinterpret_cast<uintptr_t>(vec.data()), length);\n  memoryView.call<void>(\"set\", typedArray);\n}\n\nSurfacePoint getStartingPoint(GeoMesh &geo) {\n  Face start = geo.mesh->face(0);\n  return SurfacePoint(start, Vector3{1. / 3., 1. / 3., 1. / 3.});\n}\n\nStepResult takeStep(Vector2 direction, SurfacePoint pos, GeoMesh &geo,\n                    double stepSize) {\n  StepResult result;\n\n  result.trajectory = step(direction, pos, *geo.geo, stepSize);\n\n  result.pos = pos.interpolate(geo.geo->inputVertexPositions);\n  result.T = getExtrinsicDirection(direction, pos, *geo.geo).normalize();\n  geo.geo->requireFaceNormals();\n  result.N = geo.geo->faceNormals[pos.face];\n  result.B = cross(result.T, result.N);\n  result.dir = direction;\n  result.surfacePos = pos;\n\n  return result;\n}\n\n// Mostly stolen from Ricky Reusser https://observablehq.com/d/d0df0c04ce5c94fc\nEMSCRIPTEN_BINDINGS(my_module) {\n  value_array<Vector3>(\"Vector3\")\n      .element(&Vector3::x)\n      .element(&Vector3::y)\n      .element(&Vector3::z);\n  value_array<Vector2>(\"Vector2\").element(&Vector2::x).element(&Vector2::y);\n\n  register_vector<Vector3>(\"VectorVector3\");\n  register_vector<size_t>(\"VectorSizeT\");\n  register_vector<std::vector<size_t>>(\"VectorVectorSizeT\");\n\n  class_<SurfacePoint>(\"SurfacePoint\");\n\n  class_<GeoMesh>(\"GCMesh\")\n      .function(\"polygons\", optional_override([](GeoMesh &self) {\n                  return self.mesh->getFaceVertexList();\n                }))\n      .function(\"vertexCoordinates\", optional_override([](const GeoMesh &self) {\n                  std::vector<Vector3> vCoords;\n                  for (Vertex v : self.mesh->vertices())\n                    vCoords.push_back(self.geo->inputVertexPositions[v]);\n                  return vCoords;\n                }));\n\n  function(\n      \"readMesh\", optional_override([](std::string str, std::string type = \"\") {\n        std::stringstream in;\n        in << str;\n\n        GeoMesh gMesh;\n        std::tie(gMesh.mesh, gMesh.geo) = readManifoldSurfaceMesh(in, type);\n        return gMesh;\n      }));\n\n  value_object<StepResult>(\"StepResult\")\n      .field(\"T\", &StepResult::T)\n      .field(\"N\", &StepResult::N)\n      .field(\"B\", &StepResult::B)\n      .field(\"pos\", &StepResult::pos)\n      .field(\"dir\", &StepResult::dir)\n      .field(\"surfacePos\", &StepResult::surfacePos)\n      .field(\"trajectory\", &StepResult::trajectory);\n\n  function(\"getStartingPoint\", &getStartingPoint);\n  function(\"takeStep\", &takeStep);\n}\n", "meta": {"hexsha": "bbb826887e39b158206c83155283832e0f6de160", "size": 3790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/embind.cpp", "max_stars_repo_name": "MarkGillespie/GeodesicWalker", "max_stars_repo_head_hexsha": "c0c190027c75dcb153c4b9ce22e8548b0d838cdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-30T01:54:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T01:54:28.000Z", "max_issues_repo_path": "src/embind.cpp", "max_issues_repo_name": "MarkGillespie/GeodesicWalker", "max_issues_repo_head_hexsha": "c0c190027c75dcb153c4b9ce22e8548b0d838cdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/embind.cpp", "max_forks_repo_name": "MarkGillespie/GeodesicWalker", "max_forks_repo_head_hexsha": "c0c190027c75dcb153c4b9ce22e8548b0d838cdf", "max_forks_repo_licenses": ["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.6724137931, "max_line_length": 80, "alphanum_fraction": 0.6920844327, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5366462672996195}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n#include <functional>\n#include <iostream>\n#include <vector>\n\n#include <graphblas/graphblas.hpp>\n\nusing namespace grb;\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE algebra_binary_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n//****************************************************************************\n// Summary\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(misc_math_tests)\n{\n    BOOST_CHECK_EQUAL(Equal<double>()(1, 1), true);\n    BOOST_CHECK_EQUAL(Equal<double>()(0xC0FFEE, 0xCAFE), false);\n    BOOST_CHECK_EQUAL(NotEqual<double>()(1, 1), false);\n    BOOST_CHECK_EQUAL(NotEqual<double>()(0xC0FFEE, 0xCAFE), true);\n\n    BOOST_CHECK_EQUAL(GreaterThan<double>()(1, 2), false);\n    BOOST_CHECK_EQUAL(LessThan<double>()(1, 2), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<double>()(1, 2), false);\n    BOOST_CHECK_EQUAL(LessEqual<double>()(1, 1), true);\n\n    BOOST_CHECK_EQUAL(First<double>()(5, 1337), 5);\n    BOOST_CHECK_EQUAL(Second<double>()(5, 1337), 1337);\n\n    BOOST_CHECK_EQUAL(Min<double>()(0, 1000000), 0);\n    BOOST_CHECK_EQUAL(Min<double>()(-5, 0), -5);\n    BOOST_CHECK_EQUAL(Min<double>()(7, 3), 3);\n    BOOST_CHECK_EQUAL(Max<double>()(0, 1000000), 1000000);\n    BOOST_CHECK_EQUAL(Max<double>()(-5, 0), 0);\n    BOOST_CHECK_EQUAL(Max<double>()(7, 3), 7);\n\n    BOOST_CHECK_EQUAL(Plus<double>()(2, 6), 8);\n    BOOST_CHECK_EQUAL(Minus<double>()(2, 6), -4);\n    BOOST_CHECK_EQUAL(Times<double>()(3, 10), 30);\n    BOOST_CHECK_EQUAL(Div<double>()(500, 5), 100);\n    BOOST_CHECK_EQUAL(Power<double>()(2, 5), 32.0);\n}\n\n//****************************************************************************\n// Test Binary Operators\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(equal_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(Equal<double>()(0.0, 0.0), true);\n    BOOST_CHECK_EQUAL(Equal<double>()(1.0, 0.0), false);\n    BOOST_CHECK_EQUAL(Equal<double>()(0.0, 1.0), false);\n    BOOST_CHECK_EQUAL(Equal<double>()(1.0, 1.0), true);\n\n    BOOST_CHECK_EQUAL(Equal<float>()(0.0f, 0.0f), true);\n    BOOST_CHECK_EQUAL(Equal<float>()(1.0f, 0.0f), false);\n    BOOST_CHECK_EQUAL(Equal<float>()(0.0f, 1.0f), false);\n    BOOST_CHECK_EQUAL(Equal<float>()(1.0f, 1.0f), true);\n\n    BOOST_CHECK_EQUAL(Equal<uint64_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(Equal<uint64_t>()(1, 0), false);\n    BOOST_CHECK_EQUAL(Equal<uint64_t>()(0, 1), false);\n    BOOST_CHECK_EQUAL(Equal<uint64_t>()(1, 1), true);\n\n    BOOST_CHECK_EQUAL(Equal<uint32_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(Equal<uint32_t>()(1, 0), false);\n    BOOST_CHECK_EQUAL(Equal<uint32_t>()(0, 1), false);\n    BOOST_CHECK_EQUAL(Equal<uint32_t>()(1, 1), true);\n\n    BOOST_CHECK_EQUAL(Equal<uint16_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(Equal<uint16_t>()(1, 0), false);\n    BOOST_CHECK_EQUAL(Equal<uint16_t>()(0, 1), false);\n    BOOST_CHECK_EQUAL(Equal<uint16_t>()(1, 1), true);\n\n    BOOST_CHECK_EQUAL(Equal<uint8_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(Equal<uint8_t>()(1, 0), false);\n    BOOST_CHECK_EQUAL(Equal<uint8_t>()(0, 1), false);\n    BOOST_CHECK_EQUAL(Equal<uint8_t>()(1, 1), true);\n\n    BOOST_CHECK_EQUAL(Equal<int64_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(Equal<int64_t>()(-1, 0), false);\n    BOOST_CHECK_EQUAL(Equal<int64_t>()(0, -1), false);\n    BOOST_CHECK_EQUAL(Equal<int64_t>()(-1, -1), true);\n\n    BOOST_CHECK_EQUAL(Equal<int32_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(Equal<int32_t>()(-1, 0), false);\n    BOOST_CHECK_EQUAL(Equal<int32_t>()(0, -1), false);\n    BOOST_CHECK_EQUAL(Equal<int32_t>()(-1, -1), true);\n\n    BOOST_CHECK_EQUAL(Equal<int16_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(Equal<int16_t>()(-1, 0), false);\n    BOOST_CHECK_EQUAL(Equal<int16_t>()(0, -1), false);\n    BOOST_CHECK_EQUAL(Equal<int16_t>()(-1, -1), true);\n\n    BOOST_CHECK_EQUAL(Equal<int8_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(Equal<int8_t>()(-1, 0), false);\n    BOOST_CHECK_EQUAL(Equal<int8_t>()(0, -1), false);\n    BOOST_CHECK_EQUAL(Equal<int8_t>()(-1, -1), true);\n\n    BOOST_CHECK_EQUAL(Equal<bool>()(false, false), true);\n    BOOST_CHECK_EQUAL(Equal<bool>()(false, true),  false);\n    BOOST_CHECK_EQUAL(Equal<bool>()(true, false),  false);\n    BOOST_CHECK_EQUAL(Equal<bool>()(true, true),   true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(equal_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((Equal<double,bool    >()(0.0, 0.0)), true);\n    BOOST_CHECK_EQUAL((Equal<double,int32_t >()(1.0, 0.0)), false);\n    BOOST_CHECK_EQUAL((Equal<double,uint64_t>()(0.0, 1.0)), false);\n    BOOST_CHECK_EQUAL((Equal<double,float   >()(1.0, 1.0f)), true);\n\n    BOOST_CHECK_EQUAL((Equal<float,bool    >()(0.0f, false)), true);\n    BOOST_CHECK_EQUAL((Equal<float,double  >()(1.0f, 0.0)), false);\n    BOOST_CHECK_EQUAL((Equal<float,uint64_t>()(0.0f, 1)), false);\n    BOOST_CHECK_EQUAL((Equal<float,int32_t >()(1.0f, 1)), true);\n\n    BOOST_CHECK_EQUAL((Equal<uint64_t,bool    >()(0, false)), true);\n    BOOST_CHECK_EQUAL((Equal<uint64_t,int32_t >()(1, 0)), false);\n    BOOST_CHECK_EQUAL((Equal<uint64_t,uint64_t>()(0, 1)), false);\n    BOOST_CHECK_EQUAL((Equal<uint64_t,float   >()(1, 1.0f)), true);\n\n    BOOST_CHECK_EQUAL((Equal<uint32_t,bool    >()(0, false)), true);\n    BOOST_CHECK_EQUAL((Equal<uint32_t,int32_t >()(1, 0)), false);\n    BOOST_CHECK_EQUAL((Equal<uint32_t,uint64_t>()(0, 1)), false);\n    BOOST_CHECK_EQUAL((Equal<uint32_t,float   >()(1, 1)), true);\n\n    BOOST_CHECK_EQUAL((Equal<uint16_t,bool    >()(0, false)), true);\n    BOOST_CHECK_EQUAL((Equal<uint16_t,int32_t >()(1, 0)), false);\n    BOOST_CHECK_EQUAL((Equal<uint16_t,uint64_t>()(0, 1)), false);\n    BOOST_CHECK_EQUAL((Equal<uint16_t,float   >()(1, 1.0f)), true);\n\n    BOOST_CHECK_EQUAL((Equal<uint8_t,bool    >()(0, false)), true);\n    BOOST_CHECK_EQUAL((Equal<uint8_t,int32_t >()(1, 0)), false);\n    BOOST_CHECK_EQUAL((Equal<uint8_t,uint64_t>()(0, 1)), false);\n    BOOST_CHECK_EQUAL((Equal<uint8_t,float   >()(1, 1.0f)), true);\n\n    BOOST_CHECK_EQUAL((Equal<int64_t,bool    >()( 0,  false)), true);\n    BOOST_CHECK_EQUAL((Equal<int64_t,uint32_t>()(-1,  0)), false);\n    BOOST_CHECK_EQUAL((Equal<int64_t,int64_t >()( 0, -1)), false);\n    BOOST_CHECK_EQUAL((Equal<int64_t,float   >()(-1, -1.0f)), true);\n\n    BOOST_CHECK_EQUAL((Equal<int32_t,bool    >()( 0,  false)), true);\n    BOOST_CHECK_EQUAL((Equal<int32_t,uint32_t>()(-1,  0)), false);\n    BOOST_CHECK_EQUAL((Equal<int32_t,int64_t >()( 0, -1)), false);\n    BOOST_CHECK_EQUAL((Equal<int32_t,float   >()(-1, -1.0f)), true);\n\n    BOOST_CHECK_EQUAL((Equal<int16_t,bool    >()( 0,  false)), true);\n    BOOST_CHECK_EQUAL((Equal<int16_t,uint32_t>()(-1,  0)),     false);\n    BOOST_CHECK_EQUAL((Equal<int16_t,int64_t >()( 0, -1)),     false);\n    BOOST_CHECK_EQUAL((Equal<int16_t,float   >()(-1, -1.0f)),   true);\n\n    BOOST_CHECK_EQUAL((Equal<int8_t,bool    >()( 0,  false)), true);\n    BOOST_CHECK_EQUAL((Equal<int8_t,uint32_t>()(-1,  0)),     false);\n    BOOST_CHECK_EQUAL((Equal<int8_t,int64_t> ()( 0, -1)),     false);\n    BOOST_CHECK_EQUAL((Equal<int8_t,float   >()(-1, -1.f)),   true);\n\n    BOOST_CHECK_EQUAL((Equal<bool,int8_t  >()(false, 0)),   true);\n    BOOST_CHECK_EQUAL((Equal<bool,int32_t >()(false, 1)),   false);\n    BOOST_CHECK_EQUAL((Equal<bool,uint64_t>()(true,  0UL)), false);\n    BOOST_CHECK_EQUAL((Equal<bool,float   >()(true,  1.0f)),true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(not_equal_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(NotEqual<double>()(0.0, 0.0), false);\n    BOOST_CHECK_EQUAL(NotEqual<double>()(1.0, 0.0), true);\n    BOOST_CHECK_EQUAL(NotEqual<double>()(0.0, 1.0), true);\n    BOOST_CHECK_EQUAL(NotEqual<double>()(1.0, 1.0), false);\n\n    BOOST_CHECK_EQUAL(NotEqual<float>()(0.0f, 0.0f), false);\n    BOOST_CHECK_EQUAL(NotEqual<float>()(1.0f, 0.0f), true);\n    BOOST_CHECK_EQUAL(NotEqual<float>()(0.0f, 1.0f), true);\n    BOOST_CHECK_EQUAL(NotEqual<float>()(1.0f, 1.0f), false);\n\n    BOOST_CHECK_EQUAL(NotEqual<uint64_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(NotEqual<uint64_t>()(1, 0), true);\n    BOOST_CHECK_EQUAL(NotEqual<uint64_t>()(0, 1), true);\n    BOOST_CHECK_EQUAL(NotEqual<uint64_t>()(1, 1), false);\n\n    BOOST_CHECK_EQUAL(NotEqual<uint32_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(NotEqual<uint32_t>()(1, 0), true);\n    BOOST_CHECK_EQUAL(NotEqual<uint32_t>()(0, 1), true);\n    BOOST_CHECK_EQUAL(NotEqual<uint32_t>()(1, 1), false);\n\n    BOOST_CHECK_EQUAL(NotEqual<uint16_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(NotEqual<uint16_t>()(1, 0), true);\n    BOOST_CHECK_EQUAL(NotEqual<uint16_t>()(0, 1), true);\n    BOOST_CHECK_EQUAL(NotEqual<uint16_t>()(1, 1), false);\n\n    BOOST_CHECK_EQUAL(NotEqual<uint8_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(NotEqual<uint8_t>()(1, 0), true);\n    BOOST_CHECK_EQUAL(NotEqual<uint8_t>()(0, 1), true);\n    BOOST_CHECK_EQUAL(NotEqual<uint8_t>()(1, 1), false);\n\n    BOOST_CHECK_EQUAL(NotEqual<int64_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(NotEqual<int64_t>()(-1, 0), true);\n    BOOST_CHECK_EQUAL(NotEqual<int64_t>()(0, -1), true);\n    BOOST_CHECK_EQUAL(NotEqual<int64_t>()(-1, -1), false);\n\n    BOOST_CHECK_EQUAL(NotEqual<int32_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(NotEqual<int32_t>()(-1, 0), true);\n    BOOST_CHECK_EQUAL(NotEqual<int32_t>()(0, -1), true);\n    BOOST_CHECK_EQUAL(NotEqual<int32_t>()(-1, -1), false);\n\n    BOOST_CHECK_EQUAL(NotEqual<int16_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(NotEqual<int16_t>()(-1, 0), true);\n    BOOST_CHECK_EQUAL(NotEqual<int16_t>()(0, -1), true);\n    BOOST_CHECK_EQUAL(NotEqual<int16_t>()(-1, -1), false);\n\n    BOOST_CHECK_EQUAL(NotEqual<int8_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(NotEqual<int8_t>()(-1, 0), true);\n    BOOST_CHECK_EQUAL(NotEqual<int8_t>()(0, -1), true);\n    BOOST_CHECK_EQUAL(NotEqual<int8_t>()(-1, -1), false);\n\n    BOOST_CHECK_EQUAL(NotEqual<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(NotEqual<bool>()(false, true),  true);\n    BOOST_CHECK_EQUAL(NotEqual<bool>()(true, false),  true);\n    BOOST_CHECK_EQUAL(NotEqual<bool>()(true, true),   false);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(not_equal_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((NotEqual<double,bool    >()(0.0, 0.0)), false);\n    BOOST_CHECK_EQUAL((NotEqual<double,int32_t >()(1.0, 0.0)), true);\n    BOOST_CHECK_EQUAL((NotEqual<double,uint64_t>()(0.0, 1.0)), true);\n    BOOST_CHECK_EQUAL((NotEqual<double,float   >()(1.0, 1.0f)), false);\n\n    BOOST_CHECK_EQUAL((NotEqual<float,bool    >()(0.0f, false)), false);\n    BOOST_CHECK_EQUAL((NotEqual<float,double  >()(1.0f, 0.0)), true);\n    BOOST_CHECK_EQUAL((NotEqual<float,uint64_t>()(0.0f, 1)), true);\n    BOOST_CHECK_EQUAL((NotEqual<float,int32_t >()(1.0f, 1)), false);\n\n    BOOST_CHECK_EQUAL((NotEqual<uint64_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((NotEqual<uint64_t,int32_t >()(1, 0)), true);\n    BOOST_CHECK_EQUAL((NotEqual<uint64_t,uint64_t>()(0, 1)), true);\n    BOOST_CHECK_EQUAL((NotEqual<uint64_t,float   >()(1, 1.0f)), false);\n\n    BOOST_CHECK_EQUAL((NotEqual<uint32_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((NotEqual<uint32_t,int32_t >()(1, 0)), true);\n    BOOST_CHECK_EQUAL((NotEqual<uint32_t,uint64_t>()(0, 1)), true);\n    BOOST_CHECK_EQUAL((NotEqual<uint32_t,float   >()(1, 1)), false);\n\n    BOOST_CHECK_EQUAL((NotEqual<uint16_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((NotEqual<uint16_t,int32_t >()(1, 0)), true);\n    BOOST_CHECK_EQUAL((NotEqual<uint16_t,uint64_t>()(0, 1)), true);\n    BOOST_CHECK_EQUAL((NotEqual<uint16_t,float   >()(1, 1.0f)), false);\n\n    BOOST_CHECK_EQUAL((NotEqual<uint8_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((NotEqual<uint8_t,int32_t >()(1, 0)), true);\n    BOOST_CHECK_EQUAL((NotEqual<uint8_t,uint64_t>()(0, 1)), true);\n    BOOST_CHECK_EQUAL((NotEqual<uint8_t,float   >()(1, 1.0f)), false);\n\n    BOOST_CHECK_EQUAL((NotEqual<int64_t,bool    >()( 0,  false)), false);\n    BOOST_CHECK_EQUAL((NotEqual<int64_t,uint32_t>()(-1,  0)), true);\n    BOOST_CHECK_EQUAL((NotEqual<int64_t,int64_t >()( 0, -1)), true);\n    BOOST_CHECK_EQUAL((NotEqual<int64_t,float   >()(-1, -1.0f)), false);\n\n    BOOST_CHECK_EQUAL((NotEqual<int32_t,bool    >()( 0,  false)), false);\n    BOOST_CHECK_EQUAL((NotEqual<int32_t,uint32_t>()(-1,  0)), true);\n    BOOST_CHECK_EQUAL((NotEqual<int32_t,int64_t >()( 0, -1)), true);\n    BOOST_CHECK_EQUAL((NotEqual<int32_t,float   >()(-1, -1.0f)), false);\n\n    BOOST_CHECK_EQUAL((NotEqual<int16_t,bool    >()( 0,  false)), false);\n    BOOST_CHECK_EQUAL((NotEqual<int16_t,uint32_t>()(-1,  0)),     true);\n    BOOST_CHECK_EQUAL((NotEqual<int16_t,int64_t >()( 0, -1)),     true);\n    BOOST_CHECK_EQUAL((NotEqual<int16_t,float   >()(-1, -1.0f)),   false);\n\n    BOOST_CHECK_EQUAL((NotEqual<int8_t,bool    >()( 0,  false)), false);\n    BOOST_CHECK_EQUAL((NotEqual<int8_t,uint32_t>()(-1,  0)),     true);\n    BOOST_CHECK_EQUAL((NotEqual<int8_t,int64_t> ()( 0, -1)),     true);\n    BOOST_CHECK_EQUAL((NotEqual<int8_t,float   >()(-1, -1.f)),   false);\n\n    BOOST_CHECK_EQUAL((NotEqual<bool,int8_t  >()(false, 0)),   false);\n    BOOST_CHECK_EQUAL((NotEqual<bool,int32_t >()(false, 1)),   true);\n    BOOST_CHECK_EQUAL((NotEqual<bool,uint64_t>()(true,  0UL)), true);\n    BOOST_CHECK_EQUAL((NotEqual<bool,float   >()(true,  1.0f)),false);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(greater_than_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(GreaterThan<double>()(0.0, 0.0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<double>()(1.0, 0.0), true);\n    BOOST_CHECK_EQUAL(GreaterThan<double>()(0.0, 1.0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<double>()(1.0, 1.0), false);\n\n    BOOST_CHECK_EQUAL(GreaterThan<float>()(0.0f, 0.0f), false);\n    BOOST_CHECK_EQUAL(GreaterThan<float>()(1.0f, 0.0f), true);\n    BOOST_CHECK_EQUAL(GreaterThan<float>()(0.0f, 1.0f), false);\n    BOOST_CHECK_EQUAL(GreaterThan<float>()(1.0f, 1.0f), false);\n\n    BOOST_CHECK_EQUAL(GreaterThan<uint64_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<uint64_t>()(1, 0), true);\n    BOOST_CHECK_EQUAL(GreaterThan<uint64_t>()(0, 1), false);\n    BOOST_CHECK_EQUAL(GreaterThan<uint64_t>()(1, 1), false);\n\n    BOOST_CHECK_EQUAL(GreaterThan<uint32_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<uint32_t>()(1, 0), true);\n    BOOST_CHECK_EQUAL(GreaterThan<uint32_t>()(0, 1), false);\n    BOOST_CHECK_EQUAL(GreaterThan<uint32_t>()(1, 1), false);\n\n    BOOST_CHECK_EQUAL(GreaterThan<uint16_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<uint16_t>()(1, 0), true);\n    BOOST_CHECK_EQUAL(GreaterThan<uint16_t>()(0, 1), false);\n    BOOST_CHECK_EQUAL(GreaterThan<uint16_t>()(1, 1), false);\n\n    BOOST_CHECK_EQUAL(GreaterThan<uint8_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<uint8_t>()(1, 0), true);\n    BOOST_CHECK_EQUAL(GreaterThan<uint8_t>()(0, 1), false);\n    BOOST_CHECK_EQUAL(GreaterThan<uint8_t>()(1, 1), false);\n\n    BOOST_CHECK_EQUAL(GreaterThan<int64_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<int64_t>()(-1, 0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<int64_t>()(0, -1), true);\n    BOOST_CHECK_EQUAL(GreaterThan<int64_t>()(-1, -1), false);\n\n    BOOST_CHECK_EQUAL(GreaterThan<int32_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<int32_t>()(-1, 0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<int32_t>()(0, -1), true);\n    BOOST_CHECK_EQUAL(GreaterThan<int32_t>()(-1, -1), false);\n\n    BOOST_CHECK_EQUAL(GreaterThan<int16_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<int16_t>()(-1, 0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<int16_t>()(0, -1), true);\n    BOOST_CHECK_EQUAL(GreaterThan<int16_t>()(-1, -1), false);\n\n    BOOST_CHECK_EQUAL(GreaterThan<int8_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<int8_t>()(-1, 0), false);\n    BOOST_CHECK_EQUAL(GreaterThan<int8_t>()(0, -1), true);\n    BOOST_CHECK_EQUAL(GreaterThan<int8_t>()(-1, -1), false);\n\n    BOOST_CHECK_EQUAL(GreaterThan<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(GreaterThan<bool>()(false, true),  false);\n    BOOST_CHECK_EQUAL(GreaterThan<bool>()(true, false),  true);\n    BOOST_CHECK_EQUAL(GreaterThan<bool>()(true, true),   false);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(greater_than_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((GreaterThan<double,bool    >()(0.0, 0.0)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<double,int32_t >()(1.0, 0.0)), true);\n    BOOST_CHECK_EQUAL((GreaterThan<double,uint64_t>()(0.0, 1.0)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<double,float   >()(1.0, 1.0f)), false);\n\n    BOOST_CHECK_EQUAL((GreaterThan<float,bool    >()(0.0f, false)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<float,double  >()(1.0f, 0.0)), true);\n    BOOST_CHECK_EQUAL((GreaterThan<float,uint64_t>()(0.0f, 1)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<float,int32_t >()(1.0f, 1)), false);\n\n    BOOST_CHECK_EQUAL((GreaterThan<uint64_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<uint64_t,int32_t >()(1, 0)), true);\n    BOOST_CHECK_EQUAL((GreaterThan<uint64_t,uint64_t>()(0, 1)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<uint64_t,float   >()(1, 1.0f)), false);\n\n    BOOST_CHECK_EQUAL((GreaterThan<uint32_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<uint32_t,int32_t >()(1, 0)), true);\n    BOOST_CHECK_EQUAL((GreaterThan<uint32_t,uint64_t>()(0, 1)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<uint32_t,float   >()(1, 1)), false);\n\n    BOOST_CHECK_EQUAL((GreaterThan<uint16_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<uint16_t,int32_t >()(1, 0)), true);\n    BOOST_CHECK_EQUAL((GreaterThan<uint16_t,uint64_t>()(0, 1)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<uint16_t,float   >()(1, 1.0f)), false);\n\n    BOOST_CHECK_EQUAL((GreaterThan<uint8_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<uint8_t,int32_t >()(1, 0)), true);\n    BOOST_CHECK_EQUAL((GreaterThan<uint8_t,uint64_t>()(0, 1)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<uint8_t,float   >()(1, 1.0f)), false);\n\n    BOOST_CHECK_EQUAL((GreaterThan<int64_t,bool    >()( 0,  false)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<int64_t,uint32_t>()(-1,  0)), false);\n    BOOST_CHECK_EQUAL((GreaterThan<int64_t,int64_t >()( 0, -1)), true);\n    BOOST_CHECK_EQUAL((GreaterThan<int64_t,float   >()(-1, -1.0f)), false);\n\n    BOOST_CHECK_EQUAL((GreaterThan<int32_t,bool    >()( 0,  false)), false);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((GreaterThan<int32_t,uint32_t>()(-1,  0)), true);\n    BOOST_CHECK_EQUAL((GreaterThan<int32_t,int64_t >()( 0, -1)), true);\n    BOOST_CHECK_EQUAL((GreaterThan<int32_t,float   >()(-1, -1.0f)), false);\n\n    BOOST_CHECK_EQUAL((GreaterThan<int16_t,bool    >()( 0,  false)), false);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((GreaterThan<int16_t,uint32_t>()(-1,  0)),     true);\n    BOOST_CHECK_EQUAL((GreaterThan<int16_t,int64_t >()( 0, -1)),     true);\n    BOOST_CHECK_EQUAL((GreaterThan<int16_t,float   >()(-1, -1.0f)),   false);\n\n    BOOST_CHECK_EQUAL((GreaterThan<int8_t,bool    >()( 0,  false)), false);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((GreaterThan<int8_t,uint32_t>()(-1,  0)),     true);\n    BOOST_CHECK_EQUAL((GreaterThan<int8_t,int64_t> ()( 0, -1)),     true);\n    BOOST_CHECK_EQUAL((GreaterThan<int8_t,float   >()(-1, -1.f)),   false);\n\n    BOOST_CHECK_EQUAL((GreaterThan<bool,int8_t  >()(false, 0)),   false);\n    BOOST_CHECK_EQUAL((GreaterThan<bool,int32_t >()(false, 1)),   false);\n    BOOST_CHECK_EQUAL((GreaterThan<bool,uint64_t>()(true,  0UL)), true);\n    BOOST_CHECK_EQUAL((GreaterThan<bool,float   >()(true,  1.0f)),false);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(less_than_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(LessThan<double>()(0.0, 0.0), false);\n    BOOST_CHECK_EQUAL(LessThan<double>()(1.0, 0.0), false);\n    BOOST_CHECK_EQUAL(LessThan<double>()(0.0, 1.0), true);\n    BOOST_CHECK_EQUAL(LessThan<double>()(1.0, 1.0), false);\n\n    BOOST_CHECK_EQUAL(LessThan<float>()(0.0f, 0.0f), false);\n    BOOST_CHECK_EQUAL(LessThan<float>()(1.0f, 0.0f), false);\n    BOOST_CHECK_EQUAL(LessThan<float>()(0.0f, 1.0f), true);\n    BOOST_CHECK_EQUAL(LessThan<float>()(1.0f, 1.0f), false);\n\n    BOOST_CHECK_EQUAL(LessThan<uint64_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(LessThan<uint64_t>()(1, 0), false);\n    BOOST_CHECK_EQUAL(LessThan<uint64_t>()(0, 1), true);\n    BOOST_CHECK_EQUAL(LessThan<uint64_t>()(1, 1), false);\n\n    BOOST_CHECK_EQUAL(LessThan<uint32_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(LessThan<uint32_t>()(1, 0), false);\n    BOOST_CHECK_EQUAL(LessThan<uint32_t>()(0, 1), true);\n    BOOST_CHECK_EQUAL(LessThan<uint32_t>()(1, 1), false);\n\n    BOOST_CHECK_EQUAL(LessThan<uint16_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(LessThan<uint16_t>()(1, 0), false);\n    BOOST_CHECK_EQUAL(LessThan<uint16_t>()(0, 1), true);\n    BOOST_CHECK_EQUAL(LessThan<uint16_t>()(1, 1), false);\n\n    BOOST_CHECK_EQUAL(LessThan<uint8_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(LessThan<uint8_t>()(1, 0), false);\n    BOOST_CHECK_EQUAL(LessThan<uint8_t>()(0, 1), true);\n    BOOST_CHECK_EQUAL(LessThan<uint8_t>()(1, 1), false);\n\n    BOOST_CHECK_EQUAL(LessThan<int64_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(LessThan<int64_t>()(-1, 0), true);\n    BOOST_CHECK_EQUAL(LessThan<int64_t>()(0, -1), false);\n    BOOST_CHECK_EQUAL(LessThan<int64_t>()(-1, -1), false);\n\n    BOOST_CHECK_EQUAL(LessThan<int32_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(LessThan<int32_t>()(-1, 0), true);\n    BOOST_CHECK_EQUAL(LessThan<int32_t>()(0, -1), false);\n    BOOST_CHECK_EQUAL(LessThan<int32_t>()(-1, -1), false);\n\n    BOOST_CHECK_EQUAL(LessThan<int16_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(LessThan<int16_t>()(-1, 0), true);\n    BOOST_CHECK_EQUAL(LessThan<int16_t>()(0, -1), false);\n    BOOST_CHECK_EQUAL(LessThan<int16_t>()(-1, -1), false);\n\n    BOOST_CHECK_EQUAL(LessThan<int8_t>()(0, 0), false);\n    BOOST_CHECK_EQUAL(LessThan<int8_t>()(-1, 0), true);\n    BOOST_CHECK_EQUAL(LessThan<int8_t>()(0, -1), false);\n    BOOST_CHECK_EQUAL(LessThan<int8_t>()(-1, -1), false);\n\n    BOOST_CHECK_EQUAL(LessThan<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(LessThan<bool>()(false, true),  true);\n    BOOST_CHECK_EQUAL(LessThan<bool>()(true, false),  false);\n    BOOST_CHECK_EQUAL(LessThan<bool>()(true, true),   false);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(less_than_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((LessThan<double,bool    >()(0.0, 0.0)), false);\n    BOOST_CHECK_EQUAL((LessThan<double,int32_t >()(1.0, 0.0)), false);\n    BOOST_CHECK_EQUAL((LessThan<double,uint64_t>()(0.0, 1.0)), true);\n    BOOST_CHECK_EQUAL((LessThan<double,float   >()(1.0, 1.0f)), false);\n\n    BOOST_CHECK_EQUAL((LessThan<float,bool    >()(0.0f, false)), false);\n    BOOST_CHECK_EQUAL((LessThan<float,double  >()(1.0f, 0.0)), false);\n    BOOST_CHECK_EQUAL((LessThan<float,uint64_t>()(0.0f, 1)), true);\n    BOOST_CHECK_EQUAL((LessThan<float,int32_t >()(1.0f, 1)), false);\n\n    BOOST_CHECK_EQUAL((LessThan<uint64_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((LessThan<uint64_t,int32_t >()(1, 0)), false);\n    BOOST_CHECK_EQUAL((LessThan<uint64_t,uint64_t>()(0, 1)), true);\n    BOOST_CHECK_EQUAL((LessThan<uint64_t,float   >()(1, 1.0f)), false);\n\n    BOOST_CHECK_EQUAL((LessThan<uint32_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((LessThan<uint32_t,int32_t >()(1, 0)), false);\n    BOOST_CHECK_EQUAL((LessThan<uint32_t,uint64_t>()(0, 1)), true);\n    BOOST_CHECK_EQUAL((LessThan<uint32_t,float   >()(1, 1)), false);\n\n    BOOST_CHECK_EQUAL((LessThan<uint16_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((LessThan<uint16_t,int32_t >()(1, 0)), false);\n    BOOST_CHECK_EQUAL((LessThan<uint16_t,uint64_t>()(0, 1)), true);\n    BOOST_CHECK_EQUAL((LessThan<uint16_t,float   >()(1, 1.0f)), false);\n\n    BOOST_CHECK_EQUAL((LessThan<uint8_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((LessThan<uint8_t,int32_t >()(1, 0)), false);\n    BOOST_CHECK_EQUAL((LessThan<uint8_t,uint64_t>()(0, 1)), true);\n    BOOST_CHECK_EQUAL((LessThan<uint8_t,float   >()(1, 1.0f)), false);\n\n    BOOST_CHECK_EQUAL((LessThan<int64_t,bool    >()( 0,  false)), false);\n    BOOST_CHECK_EQUAL((LessThan<int64_t,uint32_t>()(-1,  0)), true);\n    BOOST_CHECK_EQUAL((LessThan<int64_t,int64_t >()( 0, -1)), false);\n    BOOST_CHECK_EQUAL((LessThan<int64_t,float   >()(-1, -1.0f)), false);\n\n    BOOST_CHECK_EQUAL((LessThan<int32_t,bool    >()( 0,  false)), false);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((LessThan<int32_t,uint32_t>()(-1,  0)), false);\n    BOOST_CHECK_EQUAL((LessThan<int32_t,int64_t >()( 0, -1)), false);\n    BOOST_CHECK_EQUAL((LessThan<int32_t,float   >()(-1, -1.0f)), false);\n\n    BOOST_CHECK_EQUAL((LessThan<int16_t,bool    >()( 0,  false)), false);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((LessThan<int16_t,uint32_t>()(-1,  0)),     false);\n    BOOST_CHECK_EQUAL((LessThan<int16_t,int64_t >()( 0, -1)),     false);\n    BOOST_CHECK_EQUAL((LessThan<int16_t,float   >()(-1, -1.0f)),   false);\n\n    BOOST_CHECK_EQUAL((LessThan<int8_t,bool    >()( 0,  false)), false);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((LessThan<int8_t,uint32_t>()(-1,  0)),     false);\n    BOOST_CHECK_EQUAL((LessThan<int8_t,int64_t> ()( 0, -1)),     false);\n    BOOST_CHECK_EQUAL((LessThan<int8_t,float   >()(-1, -1.f)),   false);\n\n    BOOST_CHECK_EQUAL((LessThan<bool,int8_t  >()(false, 0)),   false);\n    BOOST_CHECK_EQUAL((LessThan<bool,int32_t >()(false, 1)),   true);\n    BOOST_CHECK_EQUAL((LessThan<bool,uint64_t>()(true,  0UL)), false);\n    BOOST_CHECK_EQUAL((LessThan<bool,float   >()(true,  1.0f)),false);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(greater_equal_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(GreaterEqual<double>()(0.0, 0.0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<double>()(1.0, 0.0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<double>()(0.0, 1.0), false);\n    BOOST_CHECK_EQUAL(GreaterEqual<double>()(1.0, 1.0), true);\n\n    BOOST_CHECK_EQUAL(GreaterEqual<float>()(0.0f, 0.0f), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<float>()(1.0f, 0.0f), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<float>()(0.0f, 1.0f), false);\n    BOOST_CHECK_EQUAL(GreaterEqual<float>()(1.0f, 1.0f), true);\n\n    BOOST_CHECK_EQUAL(GreaterEqual<uint64_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<uint64_t>()(1, 0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<uint64_t>()(0, 1), false);\n    BOOST_CHECK_EQUAL(GreaterEqual<uint64_t>()(1, 1), true);\n\n    BOOST_CHECK_EQUAL(GreaterEqual<uint32_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<uint32_t>()(1, 0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<uint32_t>()(0, 1), false);\n    BOOST_CHECK_EQUAL(GreaterEqual<uint32_t>()(1, 1), true);\n\n    BOOST_CHECK_EQUAL(GreaterEqual<uint16_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<uint16_t>()(1, 0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<uint16_t>()(0, 1), false);\n    BOOST_CHECK_EQUAL(GreaterEqual<uint16_t>()(1, 1), true);\n\n    BOOST_CHECK_EQUAL(GreaterEqual<uint8_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<uint8_t>()(1, 0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<uint8_t>()(0, 1), false);\n    BOOST_CHECK_EQUAL(GreaterEqual<uint8_t>()(1, 1), true);\n\n    BOOST_CHECK_EQUAL(GreaterEqual<int64_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<int64_t>()(-1, 0), false);\n    BOOST_CHECK_EQUAL(GreaterEqual<int64_t>()(0, -1), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<int64_t>()(-1, -1), true);\n\n    BOOST_CHECK_EQUAL(GreaterEqual<int32_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<int32_t>()(-1, 0), false);\n    BOOST_CHECK_EQUAL(GreaterEqual<int32_t>()(0, -1), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<int32_t>()(-1, -1), true);\n\n    BOOST_CHECK_EQUAL(GreaterEqual<int16_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<int16_t>()(-1, 0), false);\n    BOOST_CHECK_EQUAL(GreaterEqual<int16_t>()(0, -1), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<int16_t>()(-1, -1), true);\n\n    BOOST_CHECK_EQUAL(GreaterEqual<int8_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<int8_t>()(-1, 0), false);\n    BOOST_CHECK_EQUAL(GreaterEqual<int8_t>()(0, -1), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<int8_t>()(-1, -1), true);\n\n    BOOST_CHECK_EQUAL(GreaterEqual<bool>()(false, false), true);\n    BOOST_CHECK_EQUAL(GreaterEqual<bool>()(false, true),  false);\n    BOOST_CHECK_EQUAL(GreaterEqual<bool>()(true, false),  true);\n    BOOST_CHECK_EQUAL(GreaterEqual<bool>()(true, true),   true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(greater_equal_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((GreaterEqual<double,bool    >()(0.0, 0.0)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<double,int32_t >()(1.0, 0.0)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<double,uint64_t>()(0.0, 1.0)), false);\n    BOOST_CHECK_EQUAL((GreaterEqual<double,float   >()(1.0, 1.0f)), true);\n\n    BOOST_CHECK_EQUAL((GreaterEqual<float,bool    >()(0.0f, false)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<float,double  >()(1.0f, 0.0)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<float,uint64_t>()(0.0f, 1)), false);\n    BOOST_CHECK_EQUAL((GreaterEqual<float,int32_t >()(1.0f, 1)), true);\n\n    BOOST_CHECK_EQUAL((GreaterEqual<uint64_t,bool    >()(0, false)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<uint64_t,int32_t >()(1, 0)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<uint64_t,uint64_t>()(0, 1)), false);\n    BOOST_CHECK_EQUAL((GreaterEqual<uint64_t,float   >()(1, 1.0f)), true);\n\n    BOOST_CHECK_EQUAL((GreaterEqual<uint32_t,bool    >()(0, false)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<uint32_t,int32_t >()(1, 0)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<uint32_t,uint64_t>()(0, 1)), false);\n    BOOST_CHECK_EQUAL((GreaterEqual<uint32_t,float   >()(1, 1)), true);\n\n    BOOST_CHECK_EQUAL((GreaterEqual<uint16_t,bool    >()(0, false)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<uint16_t,int32_t >()(1, 0)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<uint16_t,uint64_t>()(0, 1)), false);\n    BOOST_CHECK_EQUAL((GreaterEqual<uint16_t,float   >()(1, 1.0f)), true);\n\n    BOOST_CHECK_EQUAL((GreaterEqual<uint8_t,bool    >()(0, false)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<uint8_t,int32_t >()(1, 0)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<uint8_t,uint64_t>()(0, 1)), false);\n    BOOST_CHECK_EQUAL((GreaterEqual<uint8_t,float   >()(1, 1.0f)), true);\n\n    BOOST_CHECK_EQUAL((GreaterEqual<int64_t,bool    >()( 0,  false)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<int64_t,uint32_t>()(-1,  0)), false);\n    BOOST_CHECK_EQUAL((GreaterEqual<int64_t,int64_t >()( 0, -1)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<int64_t,float   >()(-1, -1.0f)), true);\n\n    BOOST_CHECK_EQUAL((GreaterEqual<int32_t,bool    >()( 0,  false)), true);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((GreaterEqual<int32_t,uint32_t>()(-1,  0)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<int32_t,int64_t >()( 0, -1)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<int32_t,float   >()(-1, -1.0f)), true);\n\n    BOOST_CHECK_EQUAL((GreaterEqual<int16_t,bool    >()( 0,  false)), true);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((GreaterEqual<int16_t,uint32_t>()(-1,  0)),     true);\n    BOOST_CHECK_EQUAL((GreaterEqual<int16_t,int64_t >()( 0, -1)),     true);\n    BOOST_CHECK_EQUAL((GreaterEqual<int16_t,float   >()(-1, -1.0f)),   true);\n\n    BOOST_CHECK_EQUAL((GreaterEqual<int8_t,bool    >()( 0,  false)), true);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((GreaterEqual<int8_t,uint32_t>()(-1,  0)),     true);\n    BOOST_CHECK_EQUAL((GreaterEqual<int8_t,int64_t> ()( 0, -1)),     true);\n    BOOST_CHECK_EQUAL((GreaterEqual<int8_t,float   >()(-1, -1.f)),   true);\n\n    BOOST_CHECK_EQUAL((GreaterEqual<bool,int8_t  >()(false, 0)),   true);\n    BOOST_CHECK_EQUAL((GreaterEqual<bool,int32_t >()(false, 1)),   false);\n    BOOST_CHECK_EQUAL((GreaterEqual<bool,uint64_t>()(true,  0UL)), true);\n    BOOST_CHECK_EQUAL((GreaterEqual<bool,float   >()(true,  1.0f)),true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(less_equal_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(LessEqual<double>()(0.0, 0.0), true);\n    BOOST_CHECK_EQUAL(LessEqual<double>()(1.0, 0.0), false);\n    BOOST_CHECK_EQUAL(LessEqual<double>()(0.0, 1.0), true);\n    BOOST_CHECK_EQUAL(LessEqual<double>()(1.0, 1.0), true);\n\n    BOOST_CHECK_EQUAL(LessEqual<float>()(0.0f, 0.0f), true);\n    BOOST_CHECK_EQUAL(LessEqual<float>()(1.0f, 0.0f), false);\n    BOOST_CHECK_EQUAL(LessEqual<float>()(0.0f, 1.0f), true);\n    BOOST_CHECK_EQUAL(LessEqual<float>()(1.0f, 1.0f), true);\n\n    BOOST_CHECK_EQUAL(LessEqual<uint64_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(LessEqual<uint64_t>()(1, 0), false);\n    BOOST_CHECK_EQUAL(LessEqual<uint64_t>()(0, 1), true);\n    BOOST_CHECK_EQUAL(LessEqual<uint64_t>()(1, 1), true);\n\n    BOOST_CHECK_EQUAL(LessEqual<uint32_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(LessEqual<uint32_t>()(1, 0), false);\n    BOOST_CHECK_EQUAL(LessEqual<uint32_t>()(0, 1), true);\n    BOOST_CHECK_EQUAL(LessEqual<uint32_t>()(1, 1), true);\n\n    BOOST_CHECK_EQUAL(LessEqual<uint16_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(LessEqual<uint16_t>()(1, 0), false);\n    BOOST_CHECK_EQUAL(LessEqual<uint16_t>()(0, 1), true);\n    BOOST_CHECK_EQUAL(LessEqual<uint16_t>()(1, 1), true);\n\n    BOOST_CHECK_EQUAL(LessEqual<uint8_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(LessEqual<uint8_t>()(1, 0), false);\n    BOOST_CHECK_EQUAL(LessEqual<uint8_t>()(0, 1), true);\n    BOOST_CHECK_EQUAL(LessEqual<uint8_t>()(1, 1), true);\n\n    BOOST_CHECK_EQUAL(LessEqual<int64_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(LessEqual<int64_t>()(-1, 0), true);\n    BOOST_CHECK_EQUAL(LessEqual<int64_t>()(0, -1), false);\n    BOOST_CHECK_EQUAL(LessEqual<int64_t>()(-1, -1), true);\n\n    BOOST_CHECK_EQUAL(LessEqual<int32_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(LessEqual<int32_t>()(-1, 0), true);\n    BOOST_CHECK_EQUAL(LessEqual<int32_t>()(0, -1), false);\n    BOOST_CHECK_EQUAL(LessEqual<int32_t>()(-1, -1), true);\n\n    BOOST_CHECK_EQUAL(LessEqual<int16_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(LessEqual<int16_t>()(-1, 0), true);\n    BOOST_CHECK_EQUAL(LessEqual<int16_t>()(0, -1), false);\n    BOOST_CHECK_EQUAL(LessEqual<int16_t>()(-1, -1), true);\n\n    BOOST_CHECK_EQUAL(LessEqual<int8_t>()(0, 0), true);\n    BOOST_CHECK_EQUAL(LessEqual<int8_t>()(-1, 0), true);\n    BOOST_CHECK_EQUAL(LessEqual<int8_t>()(0, -1), false);\n    BOOST_CHECK_EQUAL(LessEqual<int8_t>()(-1, -1), true);\n\n    BOOST_CHECK_EQUAL(LessEqual<bool>()(false, false), true);\n    BOOST_CHECK_EQUAL(LessEqual<bool>()(false, true),  true);\n    BOOST_CHECK_EQUAL(LessEqual<bool>()(true, false),  false);\n    BOOST_CHECK_EQUAL(LessEqual<bool>()(true, true),   true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(less_equal_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((LessEqual<double,bool    >()(0.0, 0.0)), true);\n    BOOST_CHECK_EQUAL((LessEqual<double,int32_t >()(1.0, 0.0)), false);\n    BOOST_CHECK_EQUAL((LessEqual<double,uint64_t>()(0.0, 1.0)), true);\n    BOOST_CHECK_EQUAL((LessEqual<double,float   >()(1.0, 1.0f)), true);\n\n    BOOST_CHECK_EQUAL((LessEqual<float,bool    >()(0.0f, false)), true);\n    BOOST_CHECK_EQUAL((LessEqual<float,double  >()(1.0f, 0.0)), false);\n    BOOST_CHECK_EQUAL((LessEqual<float,uint64_t>()(0.0f, 1)), true);\n    BOOST_CHECK_EQUAL((LessEqual<float,int32_t >()(1.0f, 1)), true);\n\n    BOOST_CHECK_EQUAL((LessEqual<uint64_t,bool    >()(0, false)), true);\n    BOOST_CHECK_EQUAL((LessEqual<uint64_t,int32_t >()(1, 0)), false);\n    BOOST_CHECK_EQUAL((LessEqual<uint64_t,uint64_t>()(0, 1)), true);\n    BOOST_CHECK_EQUAL((LessEqual<uint64_t,float   >()(1, 1.0f)), true);\n\n    BOOST_CHECK_EQUAL((LessEqual<uint32_t,bool    >()(0, false)), true);\n    BOOST_CHECK_EQUAL((LessEqual<uint32_t,int32_t >()(1, 0)), false);\n    BOOST_CHECK_EQUAL((LessEqual<uint32_t,uint64_t>()(0, 1)), true);\n    BOOST_CHECK_EQUAL((LessEqual<uint32_t,float   >()(1, 1)), true);\n\n    BOOST_CHECK_EQUAL((LessEqual<uint16_t,bool    >()(0, false)), true);\n    BOOST_CHECK_EQUAL((LessEqual<uint16_t,int32_t >()(1, 0)), false);\n    BOOST_CHECK_EQUAL((LessEqual<uint16_t,uint64_t>()(0, 1)), true);\n    BOOST_CHECK_EQUAL((LessEqual<uint16_t,float   >()(1, 1.0f)), true);\n\n    BOOST_CHECK_EQUAL((LessEqual<uint8_t,bool    >()(0, false)), true);\n    BOOST_CHECK_EQUAL((LessEqual<uint8_t,int32_t >()(1, 0)), false);\n    BOOST_CHECK_EQUAL((LessEqual<uint8_t,uint64_t>()(0, 1)), true);\n    BOOST_CHECK_EQUAL((LessEqual<uint8_t,float   >()(1, 1.0f)), true);\n\n    BOOST_CHECK_EQUAL((LessEqual<int64_t,bool    >()( 0,  false)), true);\n    BOOST_CHECK_EQUAL((LessEqual<int64_t,uint32_t>()(-1,  0)), true);\n    BOOST_CHECK_EQUAL((LessEqual<int64_t,int64_t >()( 0, -1)), false);\n    BOOST_CHECK_EQUAL((LessEqual<int64_t,float   >()(-1, -1.0f)), true);\n\n    BOOST_CHECK_EQUAL((LessEqual<int32_t,bool    >()( 0,  false)), true);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((LessEqual<int32_t,uint32_t>()(-1,  0)), false);\n    BOOST_CHECK_EQUAL((LessEqual<int32_t,int64_t >()( 0, -1)), false);\n    BOOST_CHECK_EQUAL((LessEqual<int32_t,float   >()(-1, -1.0f)), true);\n\n    BOOST_CHECK_EQUAL((LessEqual<int16_t,bool    >()( 0,  false)), true);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((LessEqual<int16_t,uint32_t>()(-1,  0)),     false);\n    BOOST_CHECK_EQUAL((LessEqual<int16_t,int64_t >()( 0, -1)),     false);\n    BOOST_CHECK_EQUAL((LessEqual<int16_t,float   >()(-1, -1.0f)),   true);\n\n    BOOST_CHECK_EQUAL((LessEqual<int8_t,bool    >()( 0,  false)), true);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((LessEqual<int8_t,uint32_t>()(-1,  0)),     false);\n    BOOST_CHECK_EQUAL((LessEqual<int8_t,int64_t> ()( 0, -1)),     false);\n    BOOST_CHECK_EQUAL((LessEqual<int8_t,float   >()(-1, -1.f)),   true);\n\n    BOOST_CHECK_EQUAL((LessEqual<bool,int8_t  >()(false, 0)),   true);\n    BOOST_CHECK_EQUAL((LessEqual<bool,int32_t >()(false, 1)),   true);\n    BOOST_CHECK_EQUAL((LessEqual<bool,uint64_t>()(true,  0UL)), false);\n    BOOST_CHECK_EQUAL((LessEqual<bool,float   >()(true,  1.0f)),true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(first_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(First<double>()(0.0, 0.0), 0.0);\n    BOOST_CHECK_EQUAL(First<double>()(1.0, 0.0), 1.0);\n    BOOST_CHECK_EQUAL(First<double>()(0.0, 1.0), 0.0);\n    BOOST_CHECK_EQUAL(First<double>()(1.0, 1.0), 1.0);\n\n    BOOST_CHECK_EQUAL(First<float>()(0.0f, 0.0f), 0.0f);\n    BOOST_CHECK_EQUAL(First<float>()(1.0f, 0.0f), 1.0f);\n    BOOST_CHECK_EQUAL(First<float>()(0.0f, 1.0f), 0.0f);\n    BOOST_CHECK_EQUAL(First<float>()(1.0f, 1.0f), 1.0f);\n\n    BOOST_CHECK_EQUAL(First<uint64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(First<uint64_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(First<uint64_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(First<uint64_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(First<uint32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(First<uint32_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(First<uint32_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(First<uint32_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(First<uint16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(First<uint16_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(First<uint16_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(First<uint16_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(First<uint8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(First<uint8_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(First<uint8_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(First<uint8_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(First<int64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(First<int64_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(First<int64_t>()(0, -1), 0);\n    BOOST_CHECK_EQUAL(First<int64_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(First<int32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(First<int32_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(First<int32_t>()(0, -1), 0);\n    BOOST_CHECK_EQUAL(First<int32_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(First<int16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(First<int16_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(First<int16_t>()(0, -1), 0);\n    BOOST_CHECK_EQUAL(First<int16_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(First<int8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(First<int8_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(First<int8_t>()(0, -1), 0);\n    BOOST_CHECK_EQUAL(First<int8_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(First<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(First<bool>()(false, true),  false);\n    BOOST_CHECK_EQUAL(First<bool>()(true, false),  true);\n    BOOST_CHECK_EQUAL(First<bool>()(true, true),   true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(first_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((First<double,bool    >()(0.2, true)), 0.2);\n    BOOST_CHECK_EQUAL((First<double,int32_t >()(1.2, 0)), 1.2);\n    BOOST_CHECK_EQUAL((First<double,uint64_t>()(0.2, 1UL)), 0.2);\n    BOOST_CHECK_EQUAL((First<double,float   >()(1.2, 1.0f)), 1.2);\n\n    BOOST_CHECK_EQUAL((First<float,bool    >()(0.1f, false)), 0.1f);\n    BOOST_CHECK_EQUAL((First<float,double  >()(1.1f, 0.2)), 1.1f);\n    BOOST_CHECK_EQUAL((First<float,uint64_t>()(0.1f, 1UL)), 0.1f);\n    BOOST_CHECK_EQUAL((First<float,int32_t >()(1.1f, 1)), 1.1f);\n\n    BOOST_CHECK_EQUAL((First<uint64_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((First<uint64_t,int32_t >()(1, 0)), 1);\n    BOOST_CHECK_EQUAL((First<uint64_t,uint64_t>()(0, 1)), 0);\n    BOOST_CHECK_EQUAL((First<uint64_t,float   >()(1, 1.1f)), 1);\n\n    BOOST_CHECK_EQUAL((First<uint32_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((First<uint32_t,int32_t >()(1, 0)), 1);\n    BOOST_CHECK_EQUAL((First<uint32_t,uint64_t>()(0, 1)), 0);\n    BOOST_CHECK_EQUAL((First<uint32_t,float   >()(1, 1)), 1);\n\n    BOOST_CHECK_EQUAL((First<uint16_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((First<uint16_t,int32_t >()(1, 0)), 1);\n    BOOST_CHECK_EQUAL((First<uint16_t,uint64_t>()(0, 1)), 0);\n    BOOST_CHECK_EQUAL((First<uint16_t,float   >()(1, 1.1f)), 1);\n\n    BOOST_CHECK_EQUAL((First<uint8_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((First<uint8_t,int32_t >()(1, 0)), 1);\n    BOOST_CHECK_EQUAL((First<uint8_t,uint64_t>()(0, 1)), 0);\n    BOOST_CHECK_EQUAL((First<uint8_t,float   >()(1, 1.1f)), 1);\n\n    BOOST_CHECK_EQUAL((First<int64_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((First<int64_t,uint32_t>()(-1,  0)), -1);\n    BOOST_CHECK_EQUAL((First<int64_t,int64_t >()( 0, -1)), 0);\n    BOOST_CHECK_EQUAL((First<int64_t,float   >()(-1, -1.1f)), -1);\n\n    BOOST_CHECK_EQUAL((First<int32_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((First<int32_t,uint32_t>()(-1,  0)), -1);\n    BOOST_CHECK_EQUAL((First<int32_t,int64_t >()( 0, -1)), 0);\n    BOOST_CHECK_EQUAL((First<int32_t,float   >()(-1, -1.1f)), -1);\n\n    BOOST_CHECK_EQUAL((First<int16_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((First<int16_t,uint32_t>()(-1,  0)), -1);\n    BOOST_CHECK_EQUAL((First<int16_t,int64_t >()( 0, -1)), 0);\n    BOOST_CHECK_EQUAL((First<int16_t,float   >()(-1, -1.1f)), -1);\n\n    BOOST_CHECK_EQUAL((First<int8_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((First<int8_t,uint32_t>()(-1,  0)),     -1);\n    BOOST_CHECK_EQUAL((First<int8_t,int64_t> ()( 0, -1)),     0);\n    BOOST_CHECK_EQUAL((First<int8_t,float   >()(-1, -1.f)),   -1);\n\n    BOOST_CHECK_EQUAL((First<bool,int8_t  >()(false, 0)),   false);\n    BOOST_CHECK_EQUAL((First<bool,int32_t >()(false, 1)),   false);\n    BOOST_CHECK_EQUAL((First<bool,uint64_t>()(true,  0UL)), true);\n    BOOST_CHECK_EQUAL((First<bool,float   >()(true,  1.1f)),true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(second_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(Second<double>()(0.0, 0.0), 0.0);\n    BOOST_CHECK_EQUAL(Second<double>()(1.0, 0.0), 0.0);\n    BOOST_CHECK_EQUAL(Second<double>()(0.0, 1.0), 1.0);\n    BOOST_CHECK_EQUAL(Second<double>()(1.0, 1.0), 1.0);\n\n    BOOST_CHECK_EQUAL(Second<float>()(0.0f, 0.0f), 0.0f);\n    BOOST_CHECK_EQUAL(Second<float>()(1.0f, 0.0f), 0.0f);\n    BOOST_CHECK_EQUAL(Second<float>()(0.0f, 1.0f), 1.0f);\n    BOOST_CHECK_EQUAL(Second<float>()(1.0f, 1.0f), 1.0f);\n\n    BOOST_CHECK_EQUAL(Second<uint64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Second<uint64_t>()(1, 0), 0);\n    BOOST_CHECK_EQUAL(Second<uint64_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(Second<uint64_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Second<uint32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Second<uint32_t>()(1, 0), 0);\n    BOOST_CHECK_EQUAL(Second<uint32_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(Second<uint32_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Second<uint16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Second<uint16_t>()(1, 0), 0);\n    BOOST_CHECK_EQUAL(Second<uint16_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(Second<uint16_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Second<uint8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Second<uint8_t>()(1, 0), 0);\n    BOOST_CHECK_EQUAL(Second<uint8_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(Second<uint8_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Second<int64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Second<int64_t>()(-1, 0), 0);\n    BOOST_CHECK_EQUAL(Second<int64_t>()(0, -1), -1);\n    BOOST_CHECK_EQUAL(Second<int64_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(Second<int32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Second<int32_t>()(-1, 0), 0);\n    BOOST_CHECK_EQUAL(Second<int32_t>()(0, -1), -1);\n    BOOST_CHECK_EQUAL(Second<int32_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(Second<int16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Second<int16_t>()(-1, 0), 0);\n    BOOST_CHECK_EQUAL(Second<int16_t>()(0, -1), -1);\n    BOOST_CHECK_EQUAL(Second<int16_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(Second<int8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Second<int8_t>()(-1, 0), 0);\n    BOOST_CHECK_EQUAL(Second<int8_t>()(0, -1), -1);\n    BOOST_CHECK_EQUAL(Second<int8_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(Second<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(Second<bool>()(false, true),  true);\n    BOOST_CHECK_EQUAL(Second<bool>()(true, false),  false);\n    BOOST_CHECK_EQUAL(Second<bool>()(true, true),   true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(second_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((Second<double,bool    >()(0.2, true)), true);\n    BOOST_CHECK_EQUAL((Second<double,int32_t >()(1.2, 0)), 0);\n    BOOST_CHECK_EQUAL((Second<double,uint64_t>()(0.2, 1UL)), 1UL);\n    BOOST_CHECK_EQUAL((Second<double,float   >()(1.2, 1.1f)), 1.1f);\n\n    BOOST_CHECK_EQUAL((Second<float,bool    >()(0.1f, false)), false);\n    BOOST_CHECK_EQUAL((Second<float,double  >()(1.1f, 0.0)), 0.0);\n    BOOST_CHECK_EQUAL((Second<float,uint64_t>()(0.1f, 1UL)), 1UL);\n    BOOST_CHECK_EQUAL((Second<float,int32_t >()(1.1f, 1)), 1U);\n\n    BOOST_CHECK_EQUAL((Second<uint64_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((Second<uint64_t,int32_t >()(1, 0)), 0);\n    BOOST_CHECK_EQUAL((Second<uint64_t,uint64_t>()(0, 1UL)), 1UL);\n    BOOST_CHECK_EQUAL((Second<uint64_t,float   >()(1, 1.1f)), 1.1f);\n\n    BOOST_CHECK_EQUAL((Second<uint32_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((Second<uint32_t,int32_t >()(1, 0)), 0);\n    BOOST_CHECK_EQUAL((Second<uint32_t,uint64_t>()(0, 1UL)), 1UL);\n    BOOST_CHECK_EQUAL((Second<uint32_t,float   >()(1, 1.1f)), 1.1f);\n\n    BOOST_CHECK_EQUAL((Second<uint16_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((Second<uint16_t,int32_t >()(1, 0)), 0);\n    BOOST_CHECK_EQUAL((Second<uint16_t,uint64_t>()(0, 1)), 1);\n    BOOST_CHECK_EQUAL((Second<uint16_t,float   >()(1, 1.1f)), 1.1f);\n\n    BOOST_CHECK_EQUAL((Second<uint8_t,bool    >()(0, false)), false);\n    BOOST_CHECK_EQUAL((Second<uint8_t,int32_t >()(1, 0)), 0);\n    BOOST_CHECK_EQUAL((Second<uint8_t,uint64_t>()(0, 1)), 1);\n    BOOST_CHECK_EQUAL((Second<uint8_t,float   >()(1, 1.1f)), 1.1f);\n\n    BOOST_CHECK_EQUAL((Second<int64_t,bool    >()( 0,  false)), false);\n    BOOST_CHECK_EQUAL((Second<int64_t,uint32_t>()(-1,  0)), 0);\n    BOOST_CHECK_EQUAL((Second<int64_t,int64_t >()( 0, -1)), -1);\n    BOOST_CHECK_EQUAL((Second<int64_t,float   >()(-1, -1.1f)), -1.1f);\n\n    BOOST_CHECK_EQUAL((Second<int32_t,bool    >()( 0,  false)), false);\n    BOOST_CHECK_EQUAL((Second<int32_t,uint32_t>()(-1,  0)), 0);\n    BOOST_CHECK_EQUAL((Second<int32_t,int64_t >()( 0, -1)), -1);\n    BOOST_CHECK_EQUAL((Second<int32_t,float   >()(-1, -1.1f)), -1.1f);\n\n    BOOST_CHECK_EQUAL((Second<int16_t,bool    >()( 0,  false)), false);\n    BOOST_CHECK_EQUAL((Second<int16_t,uint32_t>()(-1,  0)), 0);\n    BOOST_CHECK_EQUAL((Second<int16_t,int64_t >()( 0, -1)), -1);\n    BOOST_CHECK_EQUAL((Second<int16_t,float   >()(-1, -1.1f)), -1.1f);\n\n    BOOST_CHECK_EQUAL((Second<int8_t,bool    >()( 0,  false)), false);\n    BOOST_CHECK_EQUAL((Second<int8_t,uint32_t>()(-1,  0)),     0);\n    BOOST_CHECK_EQUAL((Second<int8_t,int64_t> ()( 0, -1)),    -1);\n    BOOST_CHECK_EQUAL((Second<int8_t,float   >()(-1, -1.f)),  -1.f);\n\n    BOOST_CHECK_EQUAL((Second<bool,int8_t  >()(false, 0)),   0);\n    BOOST_CHECK_EQUAL((Second<bool,int32_t >()(false, 1)),   1);\n    BOOST_CHECK_EQUAL((Second<bool,uint64_t>()(true,  0UL)), 0UL);\n    BOOST_CHECK_EQUAL((Second<bool,float   >()(true,  1.1f)),1.1f);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(min_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(Min<double>()(0.0, 0.0), 0.0);\n    BOOST_CHECK_EQUAL(Min<double>()(1.0, 0.0), 0.0);\n    BOOST_CHECK_EQUAL(Min<double>()(0.0, 1.0), 0.0);\n    BOOST_CHECK_EQUAL(Min<double>()(1.0, 1.0), 1.0);\n\n    BOOST_CHECK_EQUAL(Min<float>()(0.0f, 0.0f), 0.0f);\n    BOOST_CHECK_EQUAL(Min<float>()(1.0f, 0.0f), 0.0f);\n    BOOST_CHECK_EQUAL(Min<float>()(0.0f, 1.0f), 0.0f);\n    BOOST_CHECK_EQUAL(Min<float>()(1.0f, 1.0f), 1.0f);\n\n    BOOST_CHECK_EQUAL(Min<uint64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Min<uint64_t>()(1, 0), 0);\n    BOOST_CHECK_EQUAL(Min<uint64_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(Min<uint64_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Min<uint32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Min<uint32_t>()(1, 0), 0);\n    BOOST_CHECK_EQUAL(Min<uint32_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(Min<uint32_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Min<uint16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Min<uint16_t>()(1, 0), 0);\n    BOOST_CHECK_EQUAL(Min<uint16_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(Min<uint16_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Min<uint8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Min<uint8_t>()(1, 0), 0);\n    BOOST_CHECK_EQUAL(Min<uint8_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(Min<uint8_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Min<int64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Min<int64_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(Min<int64_t>()(0, -1), -1);\n    BOOST_CHECK_EQUAL(Min<int64_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(Min<int32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Min<int32_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(Min<int32_t>()(0, -1), -1);\n    BOOST_CHECK_EQUAL(Min<int32_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(Min<int16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Min<int16_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(Min<int16_t>()(0, -1), -1);\n    BOOST_CHECK_EQUAL(Min<int16_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(Min<int8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Min<int8_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(Min<int8_t>()(0, -1), -1);\n    BOOST_CHECK_EQUAL(Min<int8_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(Min<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(Min<bool>()(false, true),  false);\n    BOOST_CHECK_EQUAL(Min<bool>()(true, false),  false);\n    BOOST_CHECK_EQUAL(Min<bool>()(true, true),   true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(min_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((Min<double,bool    >()(0.2, true)), 0.2);\n    BOOST_CHECK_EQUAL((Min<double,int32_t >()(1.2, 0)), 0.0);\n    BOOST_CHECK_EQUAL((Min<double,uint64_t>()(0.2, 1UL)), 0.2);\n    BOOST_CHECK_EQUAL((Min<double,float   >()(1.2, 1.1f)), ((double)1.1f));\n\n    BOOST_CHECK_EQUAL((Min<float,bool    >()(0.1f, false)), 0.0f);\n    BOOST_CHECK_EQUAL((Min<float,double  >()(1.1f, 0.0)), 0.0f);\n    BOOST_CHECK_EQUAL((Min<float,uint64_t>()(0.1f, 1UL)), 0.1f);\n    BOOST_CHECK_EQUAL((Min<float,int32_t >()(1.1f, 1)), 1.0f);\n\n    BOOST_CHECK_EQUAL((Min<uint64_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Min<uint64_t,int32_t >()(1, 0)), 0);\n    BOOST_CHECK_EQUAL((Min<uint64_t,uint64_t>()(0, 1UL)), 0);\n    BOOST_CHECK_EQUAL((Min<uint64_t,float   >()(1, 1.1f)), 1);\n\n    BOOST_CHECK_EQUAL((Min<uint32_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Min<uint32_t,int32_t >()(1, 0)), 0);\n    BOOST_CHECK_EQUAL((Min<uint32_t,uint64_t>()(0, 1UL)), 0U);\n    BOOST_CHECK_EQUAL((Min<uint32_t,float   >()(1, 1.1f)), 1U);\n\n    BOOST_CHECK_EQUAL((Min<uint16_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Min<uint16_t,int32_t >()(1, 0)), 0);\n    BOOST_CHECK_EQUAL((Min<uint16_t,uint64_t>()(0, 1)), 0);\n    BOOST_CHECK_EQUAL((Min<uint16_t,float   >()(1, 1.1f)), 1);\n\n    BOOST_CHECK_EQUAL((Min<uint8_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Min<uint8_t,int32_t >()(1, 0)), 0);\n    BOOST_CHECK_EQUAL((Min<uint8_t,uint64_t>()(0, 1)), 0);\n    BOOST_CHECK_EQUAL((Min<uint8_t,float   >()(1, 1.1f)), 1);\n\n    BOOST_CHECK_EQUAL((Min<int64_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((Min<int64_t,uint32_t>()(-1,  0)), -1);\n    BOOST_CHECK_EQUAL((Min<int64_t,int64_t >()( 0, -1)), -1);\n    BOOST_CHECK_EQUAL((Min<int64_t,float   >()(-1, -1.1f)), -1);\n\n    BOOST_CHECK_EQUAL((Min<int32_t,bool    >()( 0,  false)), 0);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((Min<int32_t,uint32_t>()(-1,  0)), 0);\n    BOOST_CHECK_EQUAL((Min<int32_t,int64_t >()( 0, -1)), -1);\n    BOOST_CHECK_EQUAL((Min<int32_t,float   >()(-1, -1.1f)), -1);\n\n    BOOST_CHECK_EQUAL((Min<int16_t,bool    >()( 0,  false)), 0);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((Min<int16_t,uint32_t>()(-1,  0)), 0);\n    BOOST_CHECK_EQUAL((Min<int16_t,int64_t >()( 0, -1)), -1);\n    BOOST_CHECK_EQUAL((Min<int16_t,float   >()(-1, -1.1f)), -1);\n\n    BOOST_CHECK_EQUAL((Min<int8_t,bool    >()( 0,  false)), 0);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((Min<int8_t,uint32_t>()(-1,  0)),    0);\n    BOOST_CHECK_EQUAL((Min<int8_t,int64_t> ()( 0, -1)),    -1);\n    BOOST_CHECK_EQUAL((Min<int8_t,float   >()(-1, -1.f)),  -1);\n\n    BOOST_CHECK_EQUAL((Min<bool,int8_t  >()(false, 0)),   false);\n    BOOST_CHECK_EQUAL((Min<bool,int32_t >()(false, 1)),   false);\n    BOOST_CHECK_EQUAL((Min<bool,uint64_t>()(true,  0UL)), false);\n    BOOST_CHECK_EQUAL((Min<bool,float   >()(true,  1.1f)),true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(max_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(Max<double>()(0.0, 0.0), 0.0);\n    BOOST_CHECK_EQUAL(Max<double>()(1.0, 0.0), 1.0);\n    BOOST_CHECK_EQUAL(Max<double>()(0.0, 1.0), 1.0);\n    BOOST_CHECK_EQUAL(Max<double>()(1.0, 1.0), 1.0);\n\n    BOOST_CHECK_EQUAL(Max<float>()(0.0f, 0.0f), 0.0f);\n    BOOST_CHECK_EQUAL(Max<float>()(1.0f, 0.0f), 1.0f);\n    BOOST_CHECK_EQUAL(Max<float>()(0.0f, 1.0f), 1.0f);\n    BOOST_CHECK_EQUAL(Max<float>()(1.0f, 1.0f), 1.0f);\n\n    BOOST_CHECK_EQUAL(Max<uint64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Max<uint64_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(Max<uint64_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(Max<uint64_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Max<uint32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Max<uint32_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(Max<uint32_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(Max<uint32_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Max<uint16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Max<uint16_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(Max<uint16_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(Max<uint16_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Max<uint8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Max<uint8_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(Max<uint8_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(Max<uint8_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Max<int64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Max<int64_t>()(-1, 0), 0);\n    BOOST_CHECK_EQUAL(Max<int64_t>()(0, -1), 0);\n    BOOST_CHECK_EQUAL(Max<int64_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(Max<int32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Max<int32_t>()(-1, 0), 0);\n    BOOST_CHECK_EQUAL(Max<int32_t>()(0, -1), 0);\n    BOOST_CHECK_EQUAL(Max<int32_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(Max<int16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Max<int16_t>()(-1, 0), 0);\n    BOOST_CHECK_EQUAL(Max<int16_t>()(0, -1), 0);\n    BOOST_CHECK_EQUAL(Max<int16_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(Max<int8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Max<int8_t>()(-1, 0), 0);\n    BOOST_CHECK_EQUAL(Max<int8_t>()(0, -1), 0);\n    BOOST_CHECK_EQUAL(Max<int8_t>()(-1, -1), -1);\n\n    BOOST_CHECK_EQUAL(Max<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(Max<bool>()(false, true),  true);\n    BOOST_CHECK_EQUAL(Max<bool>()(true, false),  true);\n    BOOST_CHECK_EQUAL(Max<bool>()(true, true),   true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(max_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((Max<double,bool    >()(0.2, true)), 1.0);\n    BOOST_CHECK_EQUAL((Max<double,int32_t >()(1.2, 0)), 1.2);\n    BOOST_CHECK_EQUAL((Max<double,uint64_t>()(0.2, 1UL)), 1.0);\n    BOOST_CHECK_EQUAL((Max<double,float   >()(1.2, 1.1f)), 1.2);\n\n    BOOST_CHECK_EQUAL((Max<float,bool    >()(0.1f, false)), 0.1f);\n    BOOST_CHECK_EQUAL((Max<float,double  >()(1.1f, 0.0)), 1.1f);\n    BOOST_CHECK_EQUAL((Max<float,uint64_t>()(0.1f, 1UL)), 1.0f);\n    BOOST_CHECK_EQUAL((Max<float,int32_t >()(1.1f, 1)), 1.1f);\n\n    BOOST_CHECK_EQUAL((Max<uint64_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Max<uint64_t,int32_t >()(1, 0)), 1);\n    BOOST_CHECK_EQUAL((Max<uint64_t,uint64_t>()(0, 1UL)), 1);\n    BOOST_CHECK_EQUAL((Max<uint64_t,float   >()(1, 1.1f)), 1);\n\n    BOOST_CHECK_EQUAL((Max<uint32_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Max<uint32_t,int32_t >()(1, 0)), 1);\n    BOOST_CHECK_EQUAL((Max<uint32_t,uint64_t>()(0, 1UL)), 1U);\n    BOOST_CHECK_EQUAL((Max<uint32_t,float   >()(1, 1.1f)), 1U);\n\n    BOOST_CHECK_EQUAL((Max<uint16_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Max<uint16_t,int32_t >()(1, 0)), 1);\n    BOOST_CHECK_EQUAL((Max<uint16_t,uint64_t>()(0, 1)), 1);\n    BOOST_CHECK_EQUAL((Max<uint16_t,float   >()(1, 1.1f)), 1);\n\n    BOOST_CHECK_EQUAL((Max<uint8_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Max<uint8_t,int32_t >()(1, 0)), 1);\n    BOOST_CHECK_EQUAL((Max<uint8_t,uint64_t>()(0, 1)), 1);\n    BOOST_CHECK_EQUAL((Max<uint8_t,float   >()(1, 1.1f)), 1);\n\n    BOOST_CHECK_EQUAL((Max<int64_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((Max<int64_t,uint32_t>()(-1,  0)),  0);\n    BOOST_CHECK_EQUAL((Max<int64_t,int64_t >()( 0, -1)),  0);\n    BOOST_CHECK_EQUAL((Max<int64_t,float   >()(-1, -1.1f)), -1);\n\n    BOOST_CHECK_EQUAL((Max<int32_t,bool    >()( 0,  false)), 0);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((Max<int32_t,uint32_t>()(-1,  0)), -1);\n    BOOST_CHECK_EQUAL((Max<int32_t,int64_t >()( 0, -1)),  0);\n    BOOST_CHECK_EQUAL((Max<int32_t,float   >()(-1, -1.1f)), -1);\n\n    BOOST_CHECK_EQUAL((Max<int16_t,bool    >()( 0,  false)), 0);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((Max<int16_t,uint32_t>()(-1,  0)), -1);\n    BOOST_CHECK_EQUAL((Max<int16_t,int64_t >()( 0, -1)), 0);\n    BOOST_CHECK_EQUAL((Max<int16_t,float   >()(-1, -1.1f)), -1);\n\n    BOOST_CHECK_EQUAL((Max<int8_t,bool    >()( 0,  false)), 0);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((Max<int8_t,uint32_t>()(-1,  0)),  -1);\n    BOOST_CHECK_EQUAL((Max<int8_t,int64_t> ()( 0, -1)),   0);\n    BOOST_CHECK_EQUAL((Max<int8_t,float   >()(-1, -1.f)),  -1);\n\n    BOOST_CHECK_EQUAL((Max<bool,int8_t  >()(false, 0)),   false);\n    BOOST_CHECK_EQUAL((Max<bool,int32_t >()(false, 1)),   true);\n    BOOST_CHECK_EQUAL((Max<bool,uint64_t>()(true,  0UL)), true);\n    BOOST_CHECK_EQUAL((Max<bool,float   >()(true,  1.1f)),true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(plus_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(Plus<double>()(0.0, 0.0), 0.0);\n    BOOST_CHECK_EQUAL(Plus<double>()(1.0, 0.0), 1.0);\n    BOOST_CHECK_EQUAL(Plus<double>()(0.0, 1.0), 1.0);\n    BOOST_CHECK_EQUAL(Plus<double>()(1.0, 1.0), 2.0);\n\n    BOOST_CHECK_EQUAL(Plus<float>()(0.0f, 0.0f), 0.0f);\n    BOOST_CHECK_EQUAL(Plus<float>()(1.0f, 0.0f), 1.0f);\n    BOOST_CHECK_EQUAL(Plus<float>()(0.0f, 1.0f), 1.0f);\n    BOOST_CHECK_EQUAL(Plus<float>()(1.0f, 1.0f), 2.0f);\n\n    BOOST_CHECK_EQUAL(Plus<uint64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Plus<uint64_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(Plus<uint64_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(Plus<uint64_t>()(1, 1), 2);\n\n    BOOST_CHECK_EQUAL(Plus<uint32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Plus<uint32_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(Plus<uint32_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(Plus<uint32_t>()(1, 1), 2);\n\n    BOOST_CHECK_EQUAL(Plus<uint16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Plus<uint16_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(Plus<uint16_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(Plus<uint16_t>()(1, 1), 2);\n\n    BOOST_CHECK_EQUAL(Plus<uint8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Plus<uint8_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(Plus<uint8_t>()(0, 1), 1);\n    BOOST_CHECK_EQUAL(Plus<uint8_t>()(1, 1), 2);\n\n    BOOST_CHECK_EQUAL(Plus<int64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Plus<int64_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(Plus<int64_t>()(0, -1), -1);\n    BOOST_CHECK_EQUAL(Plus<int64_t>()(-1, -1), -2);\n\n    BOOST_CHECK_EQUAL(Plus<int32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Plus<int32_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(Plus<int32_t>()(0, -1), -1);\n    BOOST_CHECK_EQUAL(Plus<int32_t>()(-1, -1), -2);\n\n    BOOST_CHECK_EQUAL(Plus<int16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Plus<int16_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(Plus<int16_t>()(0, -1), -1);\n    BOOST_CHECK_EQUAL(Plus<int16_t>()(-1, -1), -2);\n\n    BOOST_CHECK_EQUAL(Plus<int8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Plus<int8_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(Plus<int8_t>()(0, -1), -1);\n    BOOST_CHECK_EQUAL(Plus<int8_t>()(-1, -1), -2);\n\n    BOOST_CHECK_EQUAL(Plus<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(Plus<bool>()(false, true),  true);\n    BOOST_CHECK_EQUAL(Plus<bool>()(true, false),  true);\n    BOOST_CHECK_EQUAL(Plus<bool>()(true, true),   true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(plus_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((Plus<double,bool    >()(0.2, true)), 1.2);\n    BOOST_CHECK_EQUAL((Plus<double,int32_t >()(1.2, 0)), 1.2);\n    BOOST_CHECK_EQUAL((Plus<double,uint64_t>()(0.2, 1UL)), 1.2);\n    BOOST_CHECK_EQUAL((Plus<double,float   >()(1.2, 1.1f)),\n                      (double)(1.2 + 1.1f));\n\n    BOOST_CHECK_EQUAL((Plus<float,bool    >()(0.1f, false)), 0.1f);\n    BOOST_CHECK_EQUAL((Plus<float,double  >()(1.1f, 0.0)), 1.1f);\n    BOOST_CHECK_EQUAL((Plus<float,uint64_t>()(0.1f, 1UL)), 1.1f);\n    BOOST_CHECK_EQUAL((Plus<float,int32_t >()(1.1f, 1)), 2.1f);\n\n    BOOST_CHECK_EQUAL((Plus<uint64_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Plus<uint64_t,int32_t >()(1, -1)), 0);\n    BOOST_CHECK_EQUAL((Plus<uint64_t,uint64_t>()(0, 1UL)), 1);\n    BOOST_CHECK_EQUAL((Plus<uint64_t,float   >()(1, -1.1f)), 0);\n\n    BOOST_CHECK_EQUAL((Plus<uint32_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Plus<uint32_t,int32_t >()(1, -1)), 0U);\n    BOOST_CHECK_EQUAL((Plus<uint32_t,uint64_t>()(0, 1UL)), 1U);\n    BOOST_CHECK_EQUAL((Plus<uint32_t,float   >()(1, -1.1f)), 0U);\n\n    BOOST_CHECK_EQUAL((Plus<uint16_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Plus<uint16_t,int32_t >()(1, -1)), 0);\n    BOOST_CHECK_EQUAL((Plus<uint16_t,uint64_t>()(0, 1)), 1);\n    BOOST_CHECK_EQUAL((Plus<uint16_t,float   >()(1, -1.1f)), 0);\n\n    BOOST_CHECK_EQUAL((Plus<uint8_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Plus<uint8_t,int32_t >()(1, -1)), 0);\n    BOOST_CHECK_EQUAL((Plus<uint8_t,uint64_t>()(0, 1)), 1);\n    BOOST_CHECK_EQUAL((Plus<uint8_t,float   >()(1, -1.1f)), 0);\n\n    BOOST_CHECK_EQUAL((Plus<int64_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((Plus<int64_t,uint32_t>()(-1,  0)), -1);\n    BOOST_CHECK_EQUAL((Plus<int64_t,int64_t >()( 0, -1)), -1);\n    BOOST_CHECK_EQUAL((Plus<int64_t,float   >()(-1, -1.1f)), -2);\n\n    BOOST_CHECK_EQUAL((Plus<int32_t,bool    >()( 0,  false)), 0);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((Plus<int32_t,uint32_t>()(-1,  0)), -1);\n    BOOST_CHECK_EQUAL((Plus<int32_t,int64_t >()( 0, -1)),  -1);\n    BOOST_CHECK_EQUAL((Plus<int32_t,float   >()(-1, -1.1f)), -2);\n\n    BOOST_CHECK_EQUAL((Plus<int16_t,bool    >()( 0,  false)), 0);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((Plus<int16_t,uint32_t>()(-1,  0)), -1);\n    BOOST_CHECK_EQUAL((Plus<int16_t,int64_t >()( 0, -1)), -1);\n    BOOST_CHECK_EQUAL((Plus<int16_t,float   >()(-1, -1.1f)), -2);\n\n    BOOST_CHECK_EQUAL((Plus<int8_t,bool    >()( 0,  false)), 0);\n    // STRANGE RESULT...-1 must be converted to uint32_t before comparison\n    BOOST_CHECK_EQUAL((Plus<int8_t,uint32_t>()(-1,  0)),  -1);\n    BOOST_CHECK_EQUAL((Plus<int8_t,int64_t> ()( 0, -1)),   -1);\n    BOOST_CHECK_EQUAL((Plus<int8_t,float   >()(-1, -1.f)),  -2);\n\n    BOOST_CHECK_EQUAL((Plus<bool,int8_t  >()(false, 0)),   false);\n    BOOST_CHECK_EQUAL((Plus<bool,int32_t >()(false, 1)),   true);\n    BOOST_CHECK_EQUAL((Plus<bool,uint64_t>()(true,  0UL)), true);\n    BOOST_CHECK_EQUAL((Plus<bool,float   >()(true,  1.1f)),true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(minus_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(Minus<double>()(0.0, 0.0), 0.0);\n    BOOST_CHECK_EQUAL(Minus<double>()(1.0, 0.0), 1.0);\n    BOOST_CHECK_EQUAL(Minus<double>()(2.0, 1.0), 1.0);\n    BOOST_CHECK_EQUAL(Minus<double>()(1.0, 1.0), 0.0);\n\n    BOOST_CHECK_EQUAL(Minus<float>()(0.0f, 0.0f), 0.0f);\n    BOOST_CHECK_EQUAL(Minus<float>()(1.0f, 0.0f), 1.0f);\n    BOOST_CHECK_EQUAL(Minus<float>()(2.0f, 1.0f), 1.0f);\n    BOOST_CHECK_EQUAL(Minus<float>()(1.0f, 1.0f), 0.0f);\n\n    BOOST_CHECK_EQUAL(Minus<uint64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Minus<uint64_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(Minus<uint64_t>()(2, 1), 1);\n    BOOST_CHECK_EQUAL(Minus<uint64_t>()(1, 1), 0);\n\n    BOOST_CHECK_EQUAL(Minus<uint32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Minus<uint32_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(Minus<uint32_t>()(2, 1), 1);\n    BOOST_CHECK_EQUAL(Minus<uint32_t>()(1, 1), 0);\n\n    BOOST_CHECK_EQUAL(Minus<uint16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Minus<uint16_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(Minus<uint16_t>()(2, 1), 1);\n    BOOST_CHECK_EQUAL(Minus<uint16_t>()(1, 1), 0);\n\n    BOOST_CHECK_EQUAL(Minus<uint8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Minus<uint8_t>()(1, 0), 1);\n    BOOST_CHECK_EQUAL(Minus<uint8_t>()(2, 1), 1);\n    BOOST_CHECK_EQUAL(Minus<uint8_t>()(1, 1), 0);\n\n    BOOST_CHECK_EQUAL(Minus<int64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Minus<int64_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(Minus<int64_t>()(-2, -1), -1);\n    BOOST_CHECK_EQUAL(Minus<int64_t>()(-1, -1), 0);\n\n    BOOST_CHECK_EQUAL(Minus<int32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Minus<int32_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(Minus<int32_t>()(-2, -1), -1);\n    BOOST_CHECK_EQUAL(Minus<int32_t>()(-1, -1), 0);\n\n    BOOST_CHECK_EQUAL(Minus<int16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Minus<int16_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(Minus<int16_t>()(-2, -1), -1);\n    BOOST_CHECK_EQUAL(Minus<int16_t>()(-1, -1), 0);\n\n    BOOST_CHECK_EQUAL(Minus<int8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Minus<int8_t>()(-1, 0), -1);\n    BOOST_CHECK_EQUAL(Minus<int8_t>()(-2, -1), -1);\n    BOOST_CHECK_EQUAL(Minus<int8_t>()(-1, -1), 0);\n\n    BOOST_CHECK_EQUAL(Minus<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(Minus<bool>()(false, true),  true);\n    BOOST_CHECK_EQUAL(Minus<bool>()(true, false),  true);\n    BOOST_CHECK_EQUAL(Minus<bool>()(true, true),   false);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(minus_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((Minus<double,bool    >()(0.2, true)), -0.8);\n    BOOST_CHECK_EQUAL((Minus<double,int32_t >()(1.2, 0)), 1.2);\n    BOOST_CHECK_EQUAL((Minus<double,uint64_t>()(0.2, 1UL)), -0.8);\n    BOOST_CHECK_EQUAL((Minus<double,float   >()(1.2, 1.1f)),\n                      (double)(1.2 - 1.1f));\n\n    BOOST_CHECK_EQUAL((Minus<float,bool    >()(0.1f, false)), 0.1f);\n    BOOST_CHECK_EQUAL((Minus<float,double  >()(1.1f, 0.0)),   1.1f);\n    BOOST_CHECK_EQUAL((Minus<float,uint64_t>()(0.1f, 1UL)),  -0.9f);\n    BOOST_CHECK_EQUAL((Minus<float,int32_t >()(1.1f, 1)), float(1.1f - 1));\n\n    BOOST_CHECK_EQUAL((Minus<uint64_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Minus<uint64_t,int32_t >()(1, -1)), 2);\n    BOOST_CHECK_EQUAL((Minus<uint64_t,uint64_t>()(0, 1UL)), -1);\n    BOOST_CHECK_EQUAL((Minus<uint64_t,float   >()(1, -1.1f)), 2);\n\n    BOOST_CHECK_EQUAL((Minus<uint32_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Minus<uint32_t,int32_t >()(1, -1)), 2U);\n    BOOST_CHECK_EQUAL((Minus<uint32_t,uint64_t>()(0, 1UL)), -1U);\n    BOOST_CHECK_EQUAL((Minus<uint32_t,float   >()(1, -1.1f)), 2U);\n\n    BOOST_CHECK_EQUAL((Minus<uint16_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Minus<uint16_t,int32_t >()(1, -1)), 2);\n    BOOST_CHECK_EQUAL((Minus<uint16_t,uint64_t>()(0, 1)), (uint16_t)-1);\n    BOOST_CHECK_EQUAL((Minus<uint16_t,float   >()(1, -1.1f)), 2);\n\n    BOOST_CHECK_EQUAL((Minus<uint8_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Minus<uint8_t,int32_t >()(1, -1)), 2);\n    BOOST_CHECK_EQUAL((Minus<uint8_t,uint64_t>()(0, 1)), (uint8_t)-1);\n    BOOST_CHECK_EQUAL((Minus<uint8_t,float   >()(1, -1.1f)), 2);\n\n    BOOST_CHECK_EQUAL((Minus<int64_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((Minus<int64_t,uint32_t>()(-1,  0)), -1);\n    BOOST_CHECK_EQUAL((Minus<int64_t,int64_t >()( 0, -1)), 1);\n    BOOST_CHECK_EQUAL((Minus<int64_t,float   >()(-1, -1.1f)), 0);\n\n    BOOST_CHECK_EQUAL((Minus<int32_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((Minus<int32_t,uint32_t>()(-1,  0)), -1);\n    BOOST_CHECK_EQUAL((Minus<int32_t,int64_t >()( 0, -1)),  1);\n    BOOST_CHECK_EQUAL((Minus<int32_t,float   >()(-1, -1.1f)), 0);\n\n    BOOST_CHECK_EQUAL((Minus<int16_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((Minus<int16_t,uint32_t>()(-1,  0)), -1);\n    BOOST_CHECK_EQUAL((Minus<int16_t,int64_t >()( 0, -1)), 1);\n    BOOST_CHECK_EQUAL((Minus<int16_t,float   >()(-1, -1.1f)), 0);\n\n    BOOST_CHECK_EQUAL((Minus<int8_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((Minus<int8_t,uint32_t>()(-1,  0)),  -1);\n    BOOST_CHECK_EQUAL((Minus<int8_t,int64_t> ()( 0, -1)),   1);\n    BOOST_CHECK_EQUAL((Minus<int8_t,float   >()(-1, -1.f)), 0);\n\n    BOOST_CHECK_EQUAL((Minus<bool,int8_t  >()(false, 0)),   false);\n    BOOST_CHECK_EQUAL((Minus<bool,int32_t >()(false, 1)),   true);\n    BOOST_CHECK_EQUAL((Minus<bool,uint64_t>()(true,  0UL)), true);\n    BOOST_CHECK_EQUAL((Minus<bool,float   >()(true,  1.1f)),true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(times_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(Times<double>()(0.0, 0.0), 0.0);\n    BOOST_CHECK_EQUAL(Times<double>()(1.0, 0.0), 0.0);\n    BOOST_CHECK_EQUAL(Times<double>()(2.0, 1.0), 2.0);\n    BOOST_CHECK_EQUAL(Times<double>()(1.0, 1.0), 1.0);\n\n    BOOST_CHECK_EQUAL(Times<float>()(0.0f, 0.0f), 0.0f);\n    BOOST_CHECK_EQUAL(Times<float>()(1.0f, 0.0f), 0.0f);\n    BOOST_CHECK_EQUAL(Times<float>()(2.0f, 1.0f), 2.0f);\n    BOOST_CHECK_EQUAL(Times<float>()(1.0f, 1.0f), 1.0f);\n\n    BOOST_CHECK_EQUAL(Times<uint64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Times<uint64_t>()(1, 0), 0);\n    BOOST_CHECK_EQUAL(Times<uint64_t>()(2, 1), 2);\n    BOOST_CHECK_EQUAL(Times<uint64_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Times<uint32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Times<uint32_t>()(1, 0), 0);\n    BOOST_CHECK_EQUAL(Times<uint32_t>()(2, 1), 2);\n    BOOST_CHECK_EQUAL(Times<uint32_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Times<uint16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Times<uint16_t>()(1, 0), 0);\n    BOOST_CHECK_EQUAL(Times<uint16_t>()(2, 1), 2);\n    BOOST_CHECK_EQUAL(Times<uint16_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Times<uint8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Times<uint8_t>()(1, 0), 0);\n    BOOST_CHECK_EQUAL(Times<uint8_t>()(2, 1), 2);\n    BOOST_CHECK_EQUAL(Times<uint8_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Times<int64_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Times<int64_t>()(-1, 0), 0);\n    BOOST_CHECK_EQUAL(Times<int64_t>()(-2, 1), -2);\n    BOOST_CHECK_EQUAL(Times<int64_t>()(-1, -1), 1);\n\n    BOOST_CHECK_EQUAL(Times<int32_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Times<int32_t>()(-1, 0), 0);\n    BOOST_CHECK_EQUAL(Times<int32_t>()(-2, 1), -2);\n    BOOST_CHECK_EQUAL(Times<int32_t>()(-1, -1), 1);\n\n    BOOST_CHECK_EQUAL(Times<int16_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Times<int16_t>()(-1, 0), 0);\n    BOOST_CHECK_EQUAL(Times<int16_t>()(-2, 1), -2);\n    BOOST_CHECK_EQUAL(Times<int16_t>()(-1, -1), 1);\n\n    BOOST_CHECK_EQUAL(Times<int8_t>()(0, 0), 0);\n    BOOST_CHECK_EQUAL(Times<int8_t>()(-1, 0), 0);\n    BOOST_CHECK_EQUAL(Times<int8_t>()(-2, 1), -2);\n    BOOST_CHECK_EQUAL(Times<int8_t>()(-1, -1), 1);\n\n    BOOST_CHECK_EQUAL(Times<bool>()(false, false), false);\n    BOOST_CHECK_EQUAL(Times<bool>()(false, true),  false);\n    BOOST_CHECK_EQUAL(Times<bool>()(true, false),  false);\n    BOOST_CHECK_EQUAL(Times<bool>()(true, true),   true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(times_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((Times<double,bool    >()(0.1,  false)), 0.);\n    BOOST_CHECK_EQUAL((Times<double,int32_t >()(1.2, 0)), 0.);\n    BOOST_CHECK_EQUAL((Times<double,uint64_t>()(0.2, 1UL)), 0.2);\n    BOOST_CHECK_EQUAL((Times<double,float   >()(1.2, 1.1f)),\n                      (double)(1.2*1.1f));\n\n    BOOST_CHECK_EQUAL((Times<float,bool    >()(0.1f, false)), 0.f);\n    BOOST_CHECK_EQUAL((Times<float,double  >()(1.1f, 0.0)),   0.f);\n    BOOST_CHECK_EQUAL((Times<float,uint64_t>()(0.1f, 1UL)),   0.1f);\n    BOOST_CHECK_EQUAL((Times<float,int32_t >()(1.1f, 1)),     1.1f);\n\n    BOOST_CHECK_EQUAL((Times<uint64_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Times<uint64_t,int32_t >()(1, -1)), (uint64_t)-1L);\n    BOOST_CHECK_EQUAL((Times<uint64_t,uint64_t>()(0, 1UL)),   0);\n    float    opfl = -1.1f;\n    uint64_t op64 = 1;\n    uint64_t ans64 = op64*opfl;  // debug and opt builds are different.\n    BOOST_CHECK_EQUAL((Times<uint64_t,float   >()(1, -1.1f)), ans64);\n\n    BOOST_CHECK_EQUAL((Times<uint32_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Times<uint32_t,int32_t >()(1, -1)), (uint32_t)-1);\n    BOOST_CHECK_EQUAL((Times<uint32_t,uint64_t>()(0, 1UL)),   0U);\n    uint32_t op32 = 1;\n    uint32_t ans32 = op32*opfl;  // debug and opt builds are different.\n    BOOST_CHECK_EQUAL((Times<uint32_t,float   >()(1, -1.1f)), ans32);\n\n    BOOST_CHECK_EQUAL((Times<uint16_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Times<uint16_t,int32_t >()(1, -1)), (uint16_t)-1);\n    BOOST_CHECK_EQUAL((Times<uint16_t,uint64_t>()(0, 1)), 0);\n    uint16_t op16 = 1;\n    uint16_t ans16 = op16*opfl;  // debug and opt builds are different.\n    BOOST_CHECK_EQUAL((Times<uint16_t,float   >()(1, -1.1f)), ans16);\n\n    BOOST_CHECK_EQUAL((Times<uint8_t,bool    >()(0, false)), 0);\n    BOOST_CHECK_EQUAL((Times<uint8_t,int32_t >()(1, -1)), (uint8_t)-1);\n    BOOST_CHECK_EQUAL((Times<uint8_t,uint64_t>()(0, 1)), 0);\n    uint8_t op8 = 1;\n    uint8_t ans8 = op8*opfl;  // debug and opt builds are different.\n    BOOST_CHECK_EQUAL((Times<uint8_t,float   >()(1, -1.1f)), ans8);\n\n    BOOST_CHECK_EQUAL((Times<int64_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((Times<int64_t,uint32_t>()(-1,  0)), 0);\n    BOOST_CHECK_EQUAL((Times<int64_t,uint64_t >()( 0, -1)), 0);\n    BOOST_CHECK_EQUAL((Times<int64_t,float   >()(-1, -1.1f)), 1);\n\n    BOOST_CHECK_EQUAL((Times<int32_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((Times<int32_t,uint32_t>()(-1,  0)), 0);\n    BOOST_CHECK_EQUAL((Times<int32_t,int64_t >()( 1, -1)), -1);\n    BOOST_CHECK_EQUAL((Times<int32_t,float   >()(-1, -1.1f)), 1);\n\n    BOOST_CHECK_EQUAL((Times<int16_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((Times<int16_t,uint32_t>()(-1,  0)), 0);\n    BOOST_CHECK_EQUAL((Times<int16_t,int64_t >()( 0, -1)), 0);\n    BOOST_CHECK_EQUAL((Times<int16_t,float   >()(-1, -1.1f)), 1);\n\n    BOOST_CHECK_EQUAL((Times<int8_t,bool    >()( 0,  false)), 0);\n    BOOST_CHECK_EQUAL((Times<int8_t,uint32_t>()(-1,  0)),  0);\n    BOOST_CHECK_EQUAL((Times<int8_t,int64_t> ()( 0, -1)),   0);\n    BOOST_CHECK_EQUAL((Times<int8_t,float   >()(-1, -1.f)), 1);\n\n    BOOST_CHECK_EQUAL((Times<bool,int8_t  >()(false, 0)),   false);\n    BOOST_CHECK_EQUAL((Times<bool,int32_t >()(false, 1)),   false);\n    BOOST_CHECK_EQUAL((Times<bool,uint64_t>()(true,  0UL)), false);\n    BOOST_CHECK_EQUAL((Times<bool,float   >()(true,  1.1f)),true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(div_same_domain_test)\n{\n    BOOST_CHECK_EQUAL(Div<double>()(0.0, 1.0), 0.0);\n    BOOST_CHECK_EQUAL(Div<double>()(1.0, 2.0), 0.5);\n    BOOST_CHECK_EQUAL(Div<double>()(2.0, 1.0), 2.0);\n    BOOST_CHECK_EQUAL(Div<double>()(1.0, 1.0), 1.0);\n\n    BOOST_CHECK_EQUAL(Div<float>()(0.0f, 1.0f), 0.0f);\n    BOOST_CHECK_EQUAL(Div<float>()(1.0f, 2.0f), 0.5f);\n    BOOST_CHECK_EQUAL(Div<float>()(2.0f, 1.0f), 2.0f);\n    BOOST_CHECK_EQUAL(Div<float>()(1.0f, 1.0f), 1.0f);\n\n    BOOST_CHECK_EQUAL(Div<uint64_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(Div<uint64_t>()(1, 2), 0);\n    BOOST_CHECK_EQUAL(Div<uint64_t>()(2, 1), 2);\n    BOOST_CHECK_EQUAL(Div<uint64_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Div<uint32_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(Div<uint32_t>()(1, 2), 0);\n    BOOST_CHECK_EQUAL(Div<uint32_t>()(2, 1), 2);\n    BOOST_CHECK_EQUAL(Div<uint32_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Div<uint16_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(Div<uint16_t>()(1, 2), 0);\n    BOOST_CHECK_EQUAL(Div<uint16_t>()(2, 1), 2);\n    BOOST_CHECK_EQUAL(Div<uint16_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Div<uint8_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(Div<uint8_t>()(1, 2), 0);\n    BOOST_CHECK_EQUAL(Div<uint8_t>()(2, 1), 2);\n    BOOST_CHECK_EQUAL(Div<uint8_t>()(1, 1), 1);\n\n    BOOST_CHECK_EQUAL(Div<int64_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(Div<int64_t>()(-1, 2), 0);\n    BOOST_CHECK_EQUAL(Div<int64_t>()(-2, 1), -2);\n    BOOST_CHECK_EQUAL(Div<int64_t>()(-1, -1), 1);\n\n    BOOST_CHECK_EQUAL(Div<int32_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(Div<int32_t>()(-1, 2), 0);\n    BOOST_CHECK_EQUAL(Div<int32_t>()(-2, 1), -2);\n    BOOST_CHECK_EQUAL(Div<int32_t>()(-1, -1), 1);\n\n    BOOST_CHECK_EQUAL(Div<int16_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(Div<int16_t>()(-1, 2), 0);\n    BOOST_CHECK_EQUAL(Div<int16_t>()(-2, 1), -2);\n    BOOST_CHECK_EQUAL(Div<int16_t>()(-1, -1), 1);\n\n    BOOST_CHECK_EQUAL(Div<int8_t>()(0, 1), 0);\n    BOOST_CHECK_EQUAL(Div<int8_t>()(-1, 2), 0);\n    BOOST_CHECK_EQUAL(Div<int8_t>()(-2, 1), -2);\n    BOOST_CHECK_EQUAL(Div<int8_t>()(-1, -1), 1);\n\n    //BOOST_CHECK_EQUAL(Div<bool>()(false, false), ?);\n    BOOST_CHECK_EQUAL(Div<bool>()(false, true),  false);\n    //BOOST_CHECK_EQUAL(Div<bool>()(true, false),  ?);\n    BOOST_CHECK_EQUAL(Div<bool>()(true, true),   true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(div_different_domain_test)\n{\n    BOOST_CHECK_EQUAL((Div<double,bool    >()(0.1, true)), 0.1);\n    BOOST_CHECK_EQUAL((Div<double,int32_t >()(1.2, -2)),  -0.6);\n    BOOST_CHECK_EQUAL((Div<double,uint64_t>()(0.2, 1UL)),  0.2);\n    BOOST_CHECK_EQUAL((Div<double,float   >()(1.2, -1.f)),-1.2);\n\n    BOOST_CHECK_EQUAL((Div<float,bool    >()(0.1f, true)),  0.1f);\n    BOOST_CHECK_EQUAL((Div<float,double  >()(1.1f, -2.0)), -0.55f);\n    BOOST_CHECK_EQUAL((Div<float,uint64_t>()(0.1f, 1UL)),   0.1f);\n    BOOST_CHECK_EQUAL((Div<float,int32_t >()(1.1f, -1)),   -1.1f);\n\n    BOOST_CHECK_EQUAL((Div<uint64_t,bool    >()(0, true)),  0);\n    BOOST_CHECK_EQUAL((Div<uint64_t,int32_t >()(1, -2)),    0);\n    BOOST_CHECK_EQUAL((Div<uint64_t,uint64_t>()(0, 1UL)),   0);\n    BOOST_CHECK_EQUAL((Div<uint64_t,float   >()(1, -1.1f)), 0);\n\n    BOOST_CHECK_EQUAL((Div<uint32_t,bool    >()(0, true)),  0);\n    BOOST_CHECK_EQUAL((Div<uint32_t,int32_t >()(1, -2)),    0);\n    BOOST_CHECK_EQUAL((Div<uint32_t,uint64_t>()(0, 1UL)),   0U);\n    BOOST_CHECK_EQUAL((Div<uint32_t,float   >()(1, -1.1f)), 0);\n\n    BOOST_CHECK_EQUAL((Div<uint16_t,bool    >()(0, true)),  0);\n    BOOST_CHECK_EQUAL((Div<uint16_t,int32_t >()(1, -2)),    0);\n    BOOST_CHECK_EQUAL((Div<uint16_t,uint64_t>()(0, 1)),     0);\n    BOOST_CHECK_EQUAL((Div<uint16_t,float   >()(1, -1.1f)), 0);\n\n    BOOST_CHECK_EQUAL((Div<uint8_t,bool    >()(0, true)),  0);\n    BOOST_CHECK_EQUAL((Div<uint8_t,int32_t >()(1, -2)),    0);\n    BOOST_CHECK_EQUAL((Div<uint8_t,uint64_t>()(0, 1)),     0);\n    BOOST_CHECK_EQUAL((Div<uint8_t,float   >()(1, -1.1f)), 0);\n\n    BOOST_CHECK_EQUAL((Div<int64_t,bool    >()( 0,  true)), 0);\n    BOOST_CHECK_EQUAL((Div<int64_t,uint32_t>()(-1,  2)),    0);\n    BOOST_CHECK_EQUAL((Div<int64_t,uint64_t >()( 0, 1)),    0);\n    BOOST_CHECK_EQUAL((Div<int64_t,float   >()(-1, -1.1f)), 0);\n\n    BOOST_CHECK_EQUAL((Div<int32_t,bool    >()( 0,  true)), 0);\n    BOOST_CHECK_EQUAL((Div<int32_t,uint32_t>()(-1,  2)),     ((uint32_t)-1)/2);\n    BOOST_CHECK_EQUAL((Div<int32_t,int64_t >()( 1, -1)),   -1);\n    BOOST_CHECK_EQUAL((Div<int32_t,float   >()(-1, -1.1f)), 0);\n\n    BOOST_CHECK_EQUAL((Div<int16_t,bool    >()( 0,  true)), 0);\n    BOOST_CHECK_EQUAL((Div<int16_t,uint32_t>()(-1,  2)),    -1);\n    BOOST_CHECK_EQUAL((Div<int16_t,int64_t >()( 0, -1)),    0);\n    BOOST_CHECK_EQUAL((Div<int16_t,float   >()(-1, -1.1f)), 0);\n\n    BOOST_CHECK_EQUAL((Div<int8_t,bool    >()( 0,  true)), 0);\n    BOOST_CHECK_EQUAL((Div<int8_t,uint32_t>()(-1,  2)),   -1);\n    BOOST_CHECK_EQUAL((Div<int8_t,int64_t> ()( 0, -1)),    0);\n    BOOST_CHECK_EQUAL((Div<int8_t,float   >()(-1, -1.f)),  1);\n\n    BOOST_CHECK_EQUAL((Div<bool,int8_t  >()(true,  1)),   true);\n    BOOST_CHECK_EQUAL((Div<bool,int32_t >()(false,-2)),   false);\n    BOOST_CHECK_EQUAL((Div<bool,uint64_t>()(true,  1UL)), true);\n    BOOST_CHECK_EQUAL((Div<bool,float   >()(true, -1.1f)),true);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "807b3b985d004d8188012d589ed78f6655ca5940", "size": 85081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_algebra_binary.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_algebra_binary.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_algebra_binary.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 48.0141083521, "max_line_length": 80, "alphanum_fraction": 0.6289183249, "num_tokens": 27777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5366462672996195}}
{"text": "// This file is part of KWIVER, and is distributed under the\n// OSI-approved BSD 3-Clause License. See top-level LICENSE file or\n// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.\n\n/**\n * \\file\n * \\brief core homography template implementations\n */\n\n#include \"homography.h\"\n\n#include <cmath>\n\n#include <vital/exceptions/math.h>\n\n#include <Eigen/LU>\n\nnamespace kwiver {\nnamespace vital {\n\nnamespace //anonymous\n{\n\n/// Private helper method for point transformation via homography matrix\ntemplate < typename T >\nEigen::Matrix< T, 2, 1 >\nh_map_point( Eigen::Matrix< T, 3, 3 > const& h, Eigen::Matrix< T, 2, 1 > const& p )\n{\n  Eigen::Matrix< T, 3, 1 > out_pt = h * Eigen::Matrix< T, 3, 1 > ( p[0], p[1], 1.0 );\n\n  if ( fabs( out_pt[2] ) <= Eigen::NumTraits< T >::dummy_precision() )\n  {\n    VITAL_THROW(point_maps_to_infinity);\n  }\n  return Eigen::Matrix< T, 2, 1 > ( out_pt[0] / out_pt[2], out_pt[1] / out_pt[2] );\n}\n\n} // end anonymous namespace\n\n/// Construct an identity homography\ntemplate < typename T >\nhomography_< T >\n::homography_()\n  : h_( matrix_t::Identity() )\n{\n}\n\n/// Construct from a provided transformation matrix\ntemplate < typename T >\nhomography_< T >\n::homography_( Eigen::Matrix< T, 3, 3 > const& mat )\n  : h_( mat )\n{\n}\n\n/// Conversion Copy constructor -- float specialization\ntemplate < >\ntemplate < >\nhomography_< float >\n::homography_( homography_< float > const& other )\n  : h_( other.get_matrix() )\n{\n}\n\n/// Conversion Copy constructor -- double specialization\ntemplate < >\ntemplate < >\nhomography_< double >\n::homography_( homography_< double > const& other )\n  : h_( other.get_matrix() )\n{\n}\n\n/// Construct from a generic homography\ntemplate < typename T >\nhomography_< T >\n::homography_( homography const& base )\n  : h_( base.matrix().template cast< T > () )\n{\n}\n\n/// Construct from a generic homography -- double specialization\ntemplate < >\nhomography_< double >\n::homography_( homography const& base )\n  : h_( base.matrix() )\n{\n}\n\n/// Create a clone of outself as a shared pointer\ntemplate < typename T >\ntransform_2d_sptr\nhomography_< T >\n::clone() const\n{\n  return std::make_shared< homography_< T > >( *this );\n}\n\n/// Get a double-typed copy of the underlying matrix transformation\ntemplate < typename T >\nEigen::Matrix< double, 3, 3 >\nhomography_< T >\n::matrix() const\n{\n  return this->h_.template cast< double > ();\n}\n\n/// Specialization for homographies with native double type\ntemplate < >\nEigen::Matrix< double, 3, 3 >\nhomography_< double >\n::matrix() const\n{\n  return this->h_;\n}\n\n/// Normalize homography transformation in-place\ntemplate < typename T >\nhomography_sptr\nhomography_< T >\n::normalize() const\n{\n  matrix_t norm = this->get_matrix();\n\n  if ( fabs( norm( 2, 2 ) ) >= Eigen::NumTraits< T >::dummy_precision() )\n  {\n    norm /= norm( 2, 2 );\n  }\n  return std::make_shared< homography_< T > >( norm );\n}\n\n/// Inverse the homography transformation returning a new transformation\ntemplate < typename T >\nhomography_sptr\nhomography_< T >\n::inverse() const\n{\n  matrix_t inv;\n  bool isvalid;\n\n  this->h_.computeInverseWithCheck( inv, isvalid );\n  if ( ! isvalid )\n  {\n    VITAL_THROW(non_invertible);\n  }\n  return std::make_shared< homography_< T > >( inv );\n}\n\n/// Map a 2D double-type point using this homography\ntemplate < typename T >\nEigen::Matrix< double, 2, 1 >\nhomography_< T >\n::map( Eigen::Matrix< double, 2, 1 > const& p ) const\n{\n  // Explicitly refer to templated version of method so as to not infinitely\n  // recurse.\n  Eigen::Matrix< double, 3, 3 > m = h_.template cast< double > ();\n\n  return h_map_point( m, p );\n}\n\n/// Map a 2D double-type point using this homography -- double specialization\ntemplate < >\nEigen::Matrix< double, 2, 1 >\nhomography_< double >\n::map( Eigen::Matrix< double, 2, 1 > const& p ) const\n{\n  return h_map_point( h_, p );\n}\n\n/// Get the underlying matrix transformation\ntemplate < typename T >\ntypename homography_< T >::matrix_t &\nhomography_< T >\n::get_matrix()\n{\n  return this->h_;\n}\n\n/// Get a const new copy of the underlying matrix transformation.\ntemplate < typename T >\ntypename homography_< T >::matrix_t const &\nhomography_< T >\n::get_matrix() const\n{\n  return this->h_;\n}\n\n/// Map a 2D point using this homography -- generic version\ntemplate < typename T >\nEigen::Matrix< T, 2, 1 >\nhomography_< T >\n::map_point( Eigen::Matrix< T, 2, 1 > const& p ) const\n{\n  return h_map_point< T > ( h_.template cast< T > (), p );\n}\n\n/// Map a 2D point using this homography -- float specialization\ntemplate < >\nEigen::Matrix< float, 2, 1 >\nhomography_< float >\n::map_point( Eigen::Matrix< float, 2, 1 > const& p ) const\n{\n  return h_map_point( h_, p );\n}\n\n/// Map a 2D point using this homography -- double specialization\ntemplate < >\nEigen::Matrix< double, 2, 1 >\nhomography_< double >\n::map_point( Eigen::Matrix< double, 2, 1 > const& p ) const\n{\n  return h_map_point( h_, p );\n}\n\n/// Custom f2f_homography multiplication operator.\ntemplate < typename T >\nhomography_< T >\nhomography_< T >\n::operator*( homography_< T > const& rhs ) const\n{\n  return homography_< T > ( h_ * rhs.h_ );\n}\n\n// ===========================================================================\n// Other Functions\n// ---------------------------------------------------------------------------\n\n/// homography_<T> output stream operator\ntemplate < typename T >\nstd::ostream&\noperator<<( std::ostream& s, homography_< T > const& h )\n{\n  s << h.get_matrix();\n  return s;\n}\n\n/// Output stream operator for \\p homography instances\nstd::ostream&\noperator<<( std::ostream& s, homography const& h )\n{\n  s << h.matrix();\n  return s;\n}\n\n// ===========================================================================\n// Template class instantiation\n// ---------------------------------------------------------------------------\n/// \\cond DoxygenSuppress\n#define INSTANTIATE_HOMOGRAPHY( T )              \\\n  template class homography_< T >;               \\\n  template VITAL_EXPORT std::ostream&            \\\n  operator<<( std::ostream&,                     \\\n              homography_< T > const& )\n\nINSTANTIATE_HOMOGRAPHY( float );\nINSTANTIATE_HOMOGRAPHY( double );\n#undef INSTANTIATE_HOMOGRAPHY\n/// \\endcond\n\n} } // end vital namespace\n", "meta": {"hexsha": "740e4943af2ca4ab39a73e1d7064982e9c79359b", "size": 6198, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vital/types/homography.cxx", "max_stars_repo_name": "mwoehlke-kitware/kwiver", "max_stars_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 176.0, "max_stars_repo_stars_event_min_datetime": "2015-07-31T23:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T23:42:44.000Z", "max_issues_repo_path": "vital/types/homography.cxx", "max_issues_repo_name": "mwoehlke-kitware/kwiver", "max_issues_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1276.0, "max_issues_repo_issues_event_min_datetime": "2015-05-03T01:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:32:20.000Z", "max_forks_repo_path": "vital/types/homography.cxx", "max_forks_repo_name": "mwoehlke-kitware/kwiver", "max_forks_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2015-01-25T05:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T14:59:37.000Z", "avg_line_length": 23.6564885496, "max_line_length": 85, "alphanum_fraction": 0.6360116167, "num_tokens": 1632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.5366462620591202}}
{"text": "//!\n//! Contains the implementation of some statistical diagnostic tests for MCMC.\n//!\n//! \\file infer/diagnostics.hpp\n//! \\author Darren Shen\n//! \\date 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\nnamespace stateline\n{\n  namespace mcmc\n  {\n    //! Convergence test using estimated potential scale reduction (EPSR).\n    //! It is a convergence metric that takes into account the variance of the \n    //! means between chains and the variance of the samples within each chain.\n    //!\n    class EpsrConvergenceCriteria\n    {\n      public:\n        //! Initialise the convergence criteria.\n        //!\n        //! \\param numChains The number of chains to be tested for convergence.\n        //! \\param numDims The number of dimensions in each state.\n        //!\n        EpsrConvergenceCriteria(int numChains, int numDims) :\n          M_(Eigen::ArrayXXd::Zero(numDims, numChains)),\n          S_(Eigen::ArrayXXd::Zero(numDims, numChains)),\n          numSamples_(Eigen::ArrayXi::Zero(numChains))\n        {\n        }\n\n        //! Update the convergence statistics for a new sample in a particular chain.\n        //!\n        //! \\param id The chain which has the new sample.\n        //! \\param sample The new sample to update the convergence statistics with.\n        //!\n        void update(uint id, const Eigen::VectorXd &sample)\n        {\n          // See http://www.johndcook.com/standard_deviation.html\n          int n = numSamples_(id) + 1;\n\n          Eigen::ArrayXd x = sample.array();\n\n          // Update the running mean and variance\n          Eigen::ArrayXd newM = M_.col(id) + (x - M_.col(id)) / n;\n          S_.col(id) = S_.col(id) + (x - M_.col(id)) * (x - newM);\n          M_.col(id) = newM;\n\n          numSamples_(id) = n;\n        }\n\n        //! Compute the estimated potential scale factor. A low value indicates\n        //! that the chains are converging.\n        //!\n        //! \\return A vector containing the scale factors for each dimension.\n        //!\n        Eigen::ArrayXd rHat() const\n        {\n          // Number of samples (use the length of the shortest chain)\n          int n = numSamples_.minCoeff();\n\n          // Number of chains\n          int m = numSamples_.rows();\n\n          // Find the overall mean of the chains\n          Eigen::ArrayXXd overallMean = M_.rowwise().mean().replicate(1, M_.cols());\n\n          // Calculate the between chain variance\n          Eigen::ArrayXd b = (n / (m - 1.0)) * (M_ - overallMean).matrix().rowwise().squaredNorm().array();\n\n          // Calculate the within chain variance\n          Eigen::ArrayXd w = ((1.0 / m) * S_ / (n - 1.0)).rowwise().sum();\n\n          // Compute the weighted average of the between chain variance and within chain variance\n          Eigen::ArrayXd vHat = ((n - 1.0) / n) * w + (1.0 / n) * b;\n\n          // Compute the potential scale reduction\n          return (vHat / (w + 1e-30)).sqrt();\n        }\n\n        //! Check if all the chains have converged. The chains have converged if the\n        //! potential scale reduction factor is below 1.1 for all dimensions.\n        //!\n        //! \\return Whether all the chains have converged.\n        //!\n        bool hasConverged() const\n        {\n          return (rHat() < 1.1).all();\n        }\n\n      private:\n        Eigen::ArrayXXd M_;\n        Eigen::ArrayXXd S_;\n        Eigen::ArrayXi numSamples_;\n    };\n  }\n}\n", "meta": {"hexsha": "58479aea17f3596259c50cd4c61fda54a98ca15e", "size": 3445, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/infer/diagnostics.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/infer/diagnostics.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/infer/diagnostics.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": 33.125, "max_line_length": 107, "alphanum_fraction": 0.5837445573, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.5366462620591201}}
{"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/*! \\file portfolio/builders/fxoption.hpp\n    \\brief\n    \\ingroup builders\n*/\n\n#pragma once\n\n#include <boost/make_shared.hpp>\n#include <ored/portfolio/builders/cachingenginebuilder.hpp>\n#include <ored/portfolio/enginefactory.hpp>\n#include <ql/pricingengines/vanilla/analyticeuropeanengine.hpp>\n#include <ql/processes/blackscholesprocess.hpp>\n\nnamespace ore {\nnamespace data {\n\n//! Engine Builder for European FX Options\n/*! Pricing engines are cached by currency pair\n\n    \\ingroup builders\n */\nclass FxOptionEngineBuilder : public CachingPricingEngineBuilder<string, const Currency&, const Currency&> {\npublic:\n    FxOptionEngineBuilder() : CachingEngineBuilder(\"GarmanKohlhagen\", \"AnalyticEuropeanEngine\", {\"FxOption\"}) {}\n\nprotected:\n    virtual string keyImpl(const Currency& forCcy, const Currency& domCcy) override {\n        return forCcy.code() + domCcy.code();\n    }\n\n    virtual boost::shared_ptr<PricingEngine> engineImpl(const Currency& forCcy, const Currency& domCcy) override {\n        string pair = keyImpl(forCcy, domCcy);\n        boost::shared_ptr<GeneralizedBlackScholesProcess> gbsp = boost::make_shared<GeneralizedBlackScholesProcess>(\n            market_->fxSpot(pair, configuration(MarketContext::pricing)),\n            market_->discountCurve(forCcy.code(),\n                                   configuration(MarketContext::pricing)), // dividend yield ~ foreign yield\n            market_->discountCurve(domCcy.code(), configuration(MarketContext::pricing)),\n            market_->fxVol(pair, configuration(MarketContext::pricing)));\n        return boost::make_shared<AnalyticEuropeanEngine>(gbsp);\n    }\n};\n\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "84710715ff3a340c7d08ca85d7bfe251bc8b320b", "size": 2416, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/portfolio/builders/fxoption.hpp", "max_stars_repo_name": "PiotrSiejda/Engine", "max_stars_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "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": "OREData/ored/portfolio/builders/fxoption.hpp", "max_issues_repo_name": "PiotrSiejda/Engine", "max_issues_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OREData/ored/portfolio/builders/fxoption.hpp", "max_forks_repo_name": "PiotrSiejda/Engine", "max_forks_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T02:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T02:04:10.000Z", "avg_line_length": 38.3492063492, "max_line_length": 116, "alphanum_fraction": 0.7421357616, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5366462608442985}}
{"text": "/**\n * @file minibatch_sgd_test.cpp\n * @author Ryan Curtin\n *\n * Test file for minibatch SGD.\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/optimizers/sgd/sgd.hpp>\n#include <mlpack/core/optimizers/minibatch_sgd/minibatch_sgd.hpp>\n#include <mlpack/core/optimizers/lbfgs/test_functions.hpp>\n#include <mlpack/core/optimizers/sgd/test_function.hpp>\n\n#include <mlpack/methods/logistic_regression/logistic_regression.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace std;\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::optimization;\nusing namespace mlpack::optimization::test;\n\nusing namespace mlpack::distribution;\nusing namespace mlpack::regression;\n\nBOOST_AUTO_TEST_SUITE(MiniBatchSGDTest);\n\n/**\n * If the batch size is 1, and we aren't shuffling, we should get the exact same\n * results as regular SGD.\n */\nBOOST_AUTO_TEST_CASE(SGDSimilarityTest)\n{\n  SGDTestFunction f;\n  StandardSGD s(0.0003, 100000, 1e-4, false);\n  MiniBatchSGD ms(1, 0.0003, 100000, 1e-4, false);\n\n  arma::mat sCoord = f.GetInitialPoint();\n  arma::mat msCoord = f.GetInitialPoint();\n\n  const double sResult = s.Optimize(f, sCoord);\n  const double msResult = ms.Optimize(f, msCoord);\n\n  BOOST_REQUIRE_CLOSE(sResult, msResult, 1e-2);\n  BOOST_REQUIRE_CLOSE(sCoord[0], msCoord[0], 1e-2);\n  BOOST_REQUIRE_CLOSE(sCoord[1], msCoord[1], 1e-2);\n  BOOST_REQUIRE_CLOSE(sCoord[2], msCoord[2], 1e-2);\n}\n\n/*\nBOOST_AUTO_TEST_CASE(SimpleSGDTestFunction)\n{\n  SGDTestFunction f;\n  // Batch size of 3.\n  MiniBatchSGD<SGDTestFunction> s(f, 3, 0.0005, 2000000, 1e-9, true);\n\n  arma::mat coordinates = f.GetInitialPoint();\n  double result = s.Optimize(coordinates);\n\n  BOOST_REQUIRE_CLOSE(result, -1.0, 0.05);\n  BOOST_REQUIRE_SMALL(coordinates[0], 1e-3);\n  BOOST_REQUIRE_SMALL(coordinates[1], 1e-7);\n  BOOST_REQUIRE_SMALL(coordinates[2], 1e-7);\n}\n*/\n\n/**\n * Run mini-batch SGD on logistic regression and make sure the results are\n * acceptable.\n */\nBOOST_AUTO_TEST_CASE(LogisticRegressionTest)\n{\n  // Generate a two-Gaussian dataset.\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, 500);\n  arma::Row<size_t> responses(500);\n  for (size_t i = 0; i < 250; ++i)\n  {\n    data.col(i) = g1.Random();\n    responses[i] = 0;\n  }\n  for (size_t i = 250; i < 500; ++i)\n  {\n    data.col(i) = g2.Random();\n    responses[i] = 1;\n  }\n\n  // Shuffle the dataset.\n  arma::uvec indices = arma::shuffle(arma::linspace<arma::uvec>(0,\n      data.n_cols - 1, data.n_cols));\n  arma::mat shuffledData(3, 500);\n  arma::Row<size_t> shuffledResponses(500);\n  for (size_t i = 0; i < data.n_cols; ++i)\n  {\n    shuffledData.col(i) = data.col(indices[i]);\n    shuffledResponses[i] = responses[indices[i]];\n  }\n\n  // Create a test set.\n  arma::mat testData(3, 500);\n  arma::Row<size_t> testResponses(500);\n  for (size_t i = 0; i < 250; ++i)\n  {\n    testData.col(i) = g1.Random();\n    testResponses[i] = 0;\n  }\n  for (size_t i = 250; i < 500; ++i)\n  {\n    testData.col(i) = g2.Random();\n    testResponses[i] = 1;\n  }\n\n  // Now run mini-batch SGD with a couple of batch sizes.\n  for (size_t batchSize = 5; batchSize < 50; batchSize += 5)\n  {\n    MiniBatchSGD mbsgd(batchSize);\n    LogisticRegression<> lr(shuffledData, shuffledResponses, mbsgd, 0.5);\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, 0.3); // 0.3% error tolerance.\n\n    const double testAcc = lr.ComputeAccuracy(testData, testResponses);\n    BOOST_REQUIRE_CLOSE(testAcc, 100.0, 0.6); // 0.6% error tolerance.\n  }\n}\n\n/**\n * Run mini-batch SGD on a simple test function and make sure the last batch\n * size is handled correctly.\n *\n * When using a batchsize that fulfilled the constraint:\n * (numFunctions % batchSize) == 1 we have to make sure that the last batch size\n * isn't zero.\n */\nBOOST_AUTO_TEST_CASE(ZeroBatchSizeTest)\n{\n  // Create the generalized Rosenbrock function.\n  GeneralizedRosenbrockFunction f(10);\n\n  MiniBatchSGD s(f.NumFunctions() - 1, 0.01, 3);\n\n  arma::mat coordinates = f.GetInitialPoint();\n  s.Optimize(f, coordinates);\n\n  const bool finite = coordinates.is_finite();\n  BOOST_REQUIRE_EQUAL(finite, true);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "f68ee52f5bbfa6db0ef50d800678d55ed8f694ff", "size": 4622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/minibatch_sgd_test.cpp", "max_stars_repo_name": "17minutes/mlpack", "max_stars_repo_head_hexsha": "8f4af1ec454a662dd7c990cf2146bfeb1bd0cb3a", "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": "2021-09-22T18:12:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:39:58.000Z", "max_issues_repo_path": "src/mlpack/tests/minibatch_sgd_test.cpp", "max_issues_repo_name": "kosmaz/Mlpack", "max_issues_repo_head_hexsha": "62100ddca45880a57e7abb0432df72d285e5728b", "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/minibatch_sgd_test.cpp", "max_forks_repo_name": "kosmaz/Mlpack", "max_forks_repo_head_hexsha": "62100ddca45880a57e7abb0432df72d285e5728b", "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.0691823899, "max_line_length": 80, "alphanum_fraction": 0.6990480312, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5366330484110688}}
{"text": "/* ScaFES\n * Copyright (c) 2017-2018, ZIH, TU Dresden, Federal Republic of Germany.\n * For details, see the files COPYING and LICENSE in the base directory\n * of the package.\n */\n\n/**\n *  @file HeatEqnFDMInitFile.hpp\n *\n *  @brief Implementation of n-dimensional heat equation problem on unit hybercube\n *         with init function and config file parser.\n */\n\n#include \"ScaFES.hpp\"\n#include \"analyticalFunctions.hpp\"\n\n#include <boost/property_tree/ini_parser.hpp>\n\n/*******************************************************************************\n ******************************************************************************/\n/**\n * \\class HeatEqnFDM\n *  @brief Class for discretized heat equation problem.\n *\n * \\section heatEqnFDM 3D Heat Equation Problem on Unit Cube\n *\n *\n * \\subsection mathdescr Mathematical Description\n * Given:\n * <ul>\n * <li> Time interval \\f[[t_S; t_E] \\mbox{ with } 0 \\le t_S < t_E,\\f] </li>\n * <li> domain \\f[\\Omega := (0,1)^3,\\f] </li>\n * <li> source \\f[f: \\bar{\\Omega} \\times (t_S;t_E] \\to R, \\quad\n        f(x,t) := 0,\\f] </li>\n * <li> boundary condition \\f[g: \\partial\\Omega \\times (t_S;t_E] \\to R, \\quad\n         g(x,t) := 0,\\f] </li>\n * <li> initial condition \\f[\\widetilde{y}: \\bar{\\Omega} \\to R, \\quad\n        \\widetilde{y}(x) :=  \\prod_{i=0}^{d-1} x_i \\cdot\n                    (x_i - 1/2)^2 \\cdot (1 - x_i),\\f] </li>\n * </ul>\n * Find \\f[y: \\bar{\\Omega} \\times [t_S; t_E] \\to {R}\\f] such that\n * \\f{eqnarray*}{\n * \\partial_t y - \\Delta y & =&  f  \\quad \\mbox{in }\n *          \\Omega \\times (t_S;t_E], \\\\\n *                      y & =&  g \\quad \\mbox{on }\n *          \\partial\\Omega \\times (t_S;t_E], \\\\\n *             y(\\cdot,t_S) & =& \\widetilde{y}  \\quad \\mbox{in } \\bar{\\Omega}.\n * \\f}\n *\n * \\subsection mathdiscretization Discretization of the problem\n * \\subsubsection discrTD Discretization of the time interval and the domain\n * Let the time interval [t_S;t_E] be uniformly discretised with\n * \\f[t_l := \\{ t_S + l \\cdot \\tau\\}_l \\f]\n * with time step size tau > 0.\n *\n * Let the domain Omega be uniformly discretised with\n * \\f[ x_{(i,j,k)} :=  \\{ (i \\cdot h_0, j \\cdot h_1, k \\cdot h_2) \\}_{(i,j,k)}\n * \\f]\n * with grid sizes h_p>0 for all p.\n * <ul>\n * <li>G_I: Set of all interior grid nodes, </li>\n * <li>G_B: Set of all boundary grid nodes,</li>\n * <li>G := G_I with G_B: Set of all grid nodes</li>\n * </ul>\n *\n * \\subsubsection discrHeatEqn Discretization of the heat equation\n * Define the following vectors:\n * \\f{eqnarray*}{\n * Y^{(l)}_{(i,j,k)} &:=& y(x_{(i,j,k)},t_l), \\\\\n * F^{(l)}_{(i,j,k)} &:=& f(x_{(i,j,k)},t_l), \\\\\n * G^{(l)}_{(i,j,k)} &:=& g(x_{(i,j,k)},t_l), \\\\\n * \\widetilde{Y}_{(i,j,k)} &:=& \\widetilde{y}(x_{(i,j,k)}) \\\\\n * && \\quad \\mbox{for all } t_l \\in \\tau_h, x_{(i,j,k)} \\in \\Omega_h.\n * \\f}\n * Discretise derivatives in space using the symmetric difference quotients\n * (Finite Difference Method with 7-point stencil) and in time using the\n * forward difference quotient (explicit Euler scheme):\n * Discretise in space (Finite Difference Method with 7-point stencil)\n * and in time (explicit Euler scheme):\n * \\f{eqnarray*}{\n * Y^{(l+1)}_{(i,j,k)} &=&  Y^{(l)}_{(i,j,k)}\n *                   + \\big( Y^{(l)}_{(i-1,j,k)} - 2 \\cdot Y^{(l)}_{(i,j,k)}\n *               + Y^{(l)}_{(i+1,j,k)} \\big) \\cdot \\tau / h_0^2   \\\\\n * &&\n *               \\quad  \\quad \\quad  \\quad  + \\big(  Y^{(l)}_{(i,j-1,k)} - 2 \\cdot Y^{(l)}_{(i,j,k)}\n *               + Y^{(l)}_{(i,j+1,k)} \\big) \\cdot \\tau / h_1^2   \\\\\n * &&            \\quad \\quad  \\quad \\quad  + \\big( Y^{(l)}_{(i,j,k-1)}  - 2 \\cdot Y^{(l)}_{(i,j,k)}\n *               + Y^{(l)}_{(i,j,k+1)} \\big) \\cdot \\tau / h_2^2  \\\\\n * &&  \\quad \\quad \\quad\\quad + \\tau \\cdot F^{(l)}_{(i,j,k)}  \\quad\\quad\n * \\forall l, \\, \\forall {(i,j,k)} \\in \\cal{G}_I, \\\\\n * Y^{(l+1)}_{(i,j,k)} &=&  G^{(l+1)}_{(i,j,k)}\n *               \\quad   \\quad \\forall l, \\, \\forall {(i,j,k)} \\in \\cal{G}_B, \\\\\n *            Y^{(0)}_{(i,j,k)} & =&  \\widetilde{Y}_{(i,j,k)}\\quad \\quad\n * \\forall {(i,j,k)} \\in \\cal{G}.\n * \\f}\n*/\ntemplate<typename CT, std::size_t DIM>\nclass HeatEqnFDM : public ScaFES::Problem<HeatEqnFDM<CT,DIM>, CT, DIM> {\n   private:\n   using PTree = boost::property_tree::ptree;\n   const PTree ptree;\n\n   public:\n    /** Coefficient a. */\n    const double A;\n\n    /** Coefficient alpha. */\n    const double ALPHA;\n\n    /** Coefficient c. */\n    const double C;\n\n    /** Coefficient lambda. */\n    const double LAMBDA;\n\n    /** Coefficient rho. */\n    const double RHO;\n\n   public:\n    /** All fields which are related to the underlying problem\n     * are added in terms of an entry of the parameters of\n     * type \\c std::vector.\n     * @param params Set of ScaFES parameters.\n     * @param gg Global grid.\n     * @param useLeapfrog Should the leap frog scheme be used?\n     * @param nameDatafield Name of the fields.\n     * @param stencilWidth Stencil width of the fields.\n     * @param isKnownDf Is the data field are known or unknown one?\n     * @param nLayers Number of layers at the global boundary.\n     * @param defaultValue Default value of fields.\n     * @param writeToFile How often should the data field be written to file.\n     * @param computeError Should the Linf error between the numerical\n     *                     and exact solution be computed?\n     * @param geomparamsInit Initial guess of geometrical parameters.\n     */\n    HeatEqnFDM(ScaFES::Parameters const& params,\n               ScaFES::GridGlobal<DIM> const& gg,\n               bool useLeapfrog,\n               std::vector<std::string> const& nameDatafield,\n               std::vector<int> const& stencilWidth,\n               std::vector<bool> const& isKnownDf,\n               const PTree& ptree_,\n               std::vector<int> const& nLayers = std::vector<int>(),\n               std::vector<CT> const& defaultValue = std::vector<CT>(),\n               std::vector<ScaFES::WriteHowOften> const& writeToFile\n                 = std::vector<ScaFES::WriteHowOften>(),\n               std::vector<bool> const& computeError = std::vector<bool>(),\n               std::vector<CT> const& geomparamsInit = std::vector<CT>() )\n        : ScaFES::Problem<HeatEqnFDM<CT, DIM>, CT, DIM>(params, gg, useLeapfrog,\n                                                        nameDatafield, stencilWidth,\n                                                        isKnownDf, nLayers,\n                                                        defaultValue, writeToFile,\n                                                        computeError, geomparamsInit),\n        ptree(ptree_),\n        A(ptree.get<CT>(\"Parameters.a\")),\n        ALPHA(ptree.get<CT>(\"Parameters.alpha\")),\n        C(ptree.get<CT>(\"Parameters.c\")),\n        LAMBDA(ptree.get<CT>(\"Parameters.lambda\")),\n        RHO(ptree.get<CT>(\"Parameters.rho\"))\n        { }\n\n    /** Evaluates all fields at one given global inner grid node.\n     *  @param vNew Set of all fields.\n     *  @param idxNode Index of given grid node.\n     */\n    void evalInner(std::vector< ScaFES::DataField<CT, DIM> >& vNew,\n                   ScaFES::Ntuple<int,DIM> const& idxNode,\n                   int const& timestep) {\n        ScaFES::Ntuple<double,DIM> x = this->coordinates(idxNode);\n        double t = this->time(timestep);\n\n        /* Vector for f. */\n        vNew[0](idxNode) = this->RHO * this->C * timeLinSpaceLindTime<CT,DIM>(x);\n        vNew[0](idxNode) -= this->LAMBDA * timeLinSpaceLinSumOfdSpace2ndOrder<CT,DIM>(x, t);\n        /* Vector for g. */\n        vNew[1](idxNode) = timeLinSpaceLinFunc<CT,DIM>(x, t);\n        /* Vector for y. */\n        vNew[2](idxNode) = timeLinSpaceLinFunc<CT,DIM>(x, t);\n    }\n\n    /** Evaluates all fields at one given global border grid node.\n     *  @param vNew Set of all fields.\n     *  @param idxNode Index of given grid node.\n     *  @param timestep Given time step.\n     */\n    void evalBorder(std::vector< ScaFES::DataField<CT, DIM> >& vNew,\n                    ScaFES::Ntuple<int,DIM> const& idxNode,\n                    int const& timestep) {\n        this->evalInner(vNew, idxNode, timestep);\n    }\n\n    /** Initializes all unknown fields at one given global inner grid node.\n     *  @param vNew Set of all unknown fields (return value).\n     *  @param idxNode Index of given grid node.\n     */\n    template<typename TT>\n    void initInner(std::vector< ScaFES::DataField<TT, DIM> >& vNew,\n                   std::vector<TT> const& /*vOld*/,\n                   ScaFES::Ntuple<int,DIM> const& idxNode,\n                   int const& timestep) {\n        ScaFES::Ntuple<double,DIM> x = this->coordinates(idxNode);\n        double t_s = this->time(timestep);\n\n        vNew[0](idxNode) = timeLinSpaceLinFunc<CT,DIM>(x, t_s);\n    }\n\n    /** Initializes all unknown fields at one given global border grid node.\n     *  @param vNew Set of all unknown fields (return value).\n     *  @param vOld Set of all given fields.\n     *  @param idxNode Index of given grid node.\n     *  @param timestep Given time step.\n     */\n    template<typename TT>\n    void initBorder(std::vector< ScaFES::DataField<TT, DIM> >& vNew,\n                    std::vector<TT> const& vOld,\n                    ScaFES::Ntuple<int,DIM> const& idxNode,\n                    int const& timestep) {\n        this->template initInner<TT>(vNew, vOld, idxNode, timestep);\n    }\n\n    /** Updates all unknown fields at one given global inner grid node.\n     *  @param vNew Set of all unknown fields at new time step (return value).\n     *  @param vOld Set of all unknown fields at old time step.\n     *  @param idxNode Index of given grid node.\n     */\n    template<typename TT>\n    void updateInner(std::vector<ScaFES::DataField<TT,DIM>>& vNew,\n                     std::vector<ScaFES::DataField<TT,DIM>> const& vOld,\n                     ScaFES::Ntuple<int,DIM> const& idxNode,\n                     int const& /*timestep*/) {\n        vNew[0](idxNode) = vOld[0](idxNode);\n        for (std::size_t pp = 0; pp < DIM; ++pp) {\n            vNew[0](idxNode) += this->tau() * A * (\n                     vOld[0](this->connect(idxNode, 2*pp))\n                     + vOld[0](this->connect(idxNode, 2*pp+1))\n                     - 2.0 * vOld[0](idxNode) )\n                     / (this->gridsize(pp) * this->gridsize(pp));\n        }\n        vNew[0](idxNode) += this->tau() * (1.0/(RHO*C)) * this->knownDf(0, idxNode);\n    }\n\n    /** Updates all unknown fields at one given global border grid node.\n     *  @param vNew Set of all unknown fields at new time step (return value).\n     *  @param idxNode Index of given grid node.\n     */\n    template<typename TT>\n    void updateBorder(std::vector<ScaFES::DataField<TT,DIM>>& vNew,\n                      std::vector<ScaFES::DataField<TT,DIM>>const& /*vOld*/,\n                      ScaFES::Ntuple<int,DIM> const& idxNode,\n                      int const& /*timestep*/) {\n        vNew[0](idxNode) = this->knownDf(1, idxNode);\n    }\n\n    /** Updates (2nd cycle) all unknown fields at one given global inner grid node.\n     *  \\remarks Only important if leap frog scheme is used.\n     */\n    template<typename TT>\n    void updateInner2(std::vector<ScaFES::DataField<TT,DIM>>&,\n                      std::vector<ScaFES::DataField<TT,DIM>> const&,\n                      ScaFES::Ntuple<int,DIM> const&,\n                      int const&) { }\n\n    /** Updates (2nd cycle) all unknown fields at one given global border\n     *  grid node.\n     *  \\remarks Only important if leap frog scheme is used.\n     */\n    template<typename TT>\n    void updateBorder2(std::vector<ScaFES::DataField<TT,DIM>>&,\n                       std::vector<ScaFES::DataField<TT,DIM>>const&,\n                       ScaFES::Ntuple<int,DIM> const&,\n                       int const&) { }\n};\n", "meta": {"hexsha": "a019f988f528add53d0af40091bde74dd524cc37", "size": 11677, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/HeatEqnFDMInitFile/HeatEqnFDMInitFile.hpp", "max_stars_repo_name": "nih23/MRIDrivenHeatSimulation", "max_stars_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "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": "examples/HeatEqnFDMInitFile/HeatEqnFDMInitFile.hpp", "max_issues_repo_name": "nih23/MRIDrivenHeatSimulation", "max_issues_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "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": "examples/HeatEqnFDMInitFile/HeatEqnFDMInitFile.hpp", "max_forks_repo_name": "nih23/MRIDrivenHeatSimulation", "max_forks_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.7728937729, "max_line_length": 100, "alphanum_fraction": 0.5533099255, "num_tokens": 3433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.5366330402975733}}
{"text": "//\n// Created by tom on 09/01/2021.\n//\n\n#include <sstream>\n#include <fstream>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include \"utils.h\"\n\n\nvector<string> utils::split(const string &s, char delim) {\n    /*********************************************************\n     *  Split a string by a delimiter into a vector of strings\n     ********************************************************/\n    stringstream stream(s);\n    string item;\n    vector<string> elems;\n    while (getline(stream, item, delim)) {\n        if (!item.empty()){\n            elems.push_back(item);\n        }\n    }\n    return elems;\n}\n\nEigen::MatrixXd utils::symmetric_matrix_from_file(const string &filename){\n    /*******************************************************\n     *  Extract a symmetric matrix from a file, where the\n     *  file is formatted as:\n     *\n     *  idx1  idx2 value\n     ******************************************************/\n    string line, item;\n    ifstream input_file(filename);\n\n    std::vector<long> idxs1;\n    std::vector<long> idxs2;\n    std::vector<double> values;\n\n    // Iterate through the file line by line\n    while (getline(input_file, line, '\\n')) {\n\n        // Ignore any blank lines\n        if (line.empty()) {\n            continue;\n        }\n        vector<string> items = utils::split(line, ' ');\n        if (items.size() != 3){\n            throw runtime_error(\"Overlap matrix file not correctly formatted.\"\n                                \"Expecting lines in the format: idx1  idx2 value\");\n        }\n        idxs1.push_back(stol(items[0]));\n        idxs2.push_back(stol(items[1]));\n        values.push_back(stod(items[2]));\n\n    }\n    long max_idx1 = *max_element(begin(idxs1), end(idxs1));\n    long min_idx1 = *min_element(begin(idxs1), end(idxs1));\n    long size = max_idx1 - min_idx1 + 1;     // Allows for indexing from 0 or 1 in the file\n\n    Eigen::MatrixXd matrix(size, size);\n    for (int n = 0; n < values.size(); n++){\n\n        long i = idxs1[n] - min_idx1;\n        long j = idxs2[n] - min_idx1;\n\n        matrix(i, j) = values[n];\n        // And because the matrix is symmetric the flipped element can also be set\n        matrix(j, i) = values[n];\n    }\n\n    return matrix;\n}\n\n\nEigen::VectorXd utils::ee_from_file(const string &filename, const int &length){\n    /*******************************************************\n     *  Extract a 1D vector of values for 4 index electron\n     *  repulsion integrals from a file\n     *\n     *  idx1  idx2 idx3 idx4  value\n     ******************************************************/\n    // Set up the vector we're going to populate\n    int M = (length*(length+1))/2;\n    int max_ijkl = (M*(M+1))/2;\n    Eigen::VectorXd ee_vector(max_ijkl+1);\n\n    string line;\n    int i, j, k, l;\n    double value;\n\n    ifstream input_file(filename);\n\n    // Iterate through the file line by line\n    while (getline(input_file, line, '\\n')) {\n\n        // Ignore any blank lines\n        if (line.empty()) {\n            continue;\n        }\n        vector<string> items = utils::split(line, ' ');\n        if (items.size() != 5){\n            throw runtime_error(\"Unexpected line length\");\n        }\n\n        // Indexes from 1\n        i = stoi(items[0]) - 1;\n        j = stoi(items[1]) - 1;\n        k = stoi(items[2]) - 1;\n        l = stoi(items[3]) - 1;\n\n        value = stod(items[4]);\n\n        if (i < j){\n            swap(i, j);\n        }\n        if (k < l){\n            swap(k, l);\n        }\n\n        int ij = i * (i + 1) / 2 + j;\n        int kl = k * (k + 1) / 2 + l;\n\n        if (ij < kl){\n            swap(ij, kl);\n        }\n        int idx = ij*(ij+1)/2+kl;\n\n        if (idx >= ee_vector.size()){\n            throw runtime_error(\"Index not settable, exceeded the \"\n                                \"size of the array\");\n        }\n        ee_vector(idx) = value;\n    }\n    return ee_vector;\n}\n\n\n", "meta": {"hexsha": "cd739afb5588e9a38aee37ba0b3fdbdc49a20059", "size": 3848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project3/utils.cpp", "max_stars_repo_name": "t-young31/cpp_tutorials", "max_stars_repo_head_hexsha": "321135177a8fb3a058e479b4974ec35dd65e7dc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project3/utils.cpp", "max_issues_repo_name": "t-young31/cpp_tutorials", "max_issues_repo_head_hexsha": "321135177a8fb3a058e479b4974ec35dd65e7dc5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project3/utils.cpp", "max_forks_repo_name": "t-young31/cpp_tutorials", "max_forks_repo_head_hexsha": "321135177a8fb3a058e479b4974ec35dd65e7dc5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2907801418, "max_line_length": 91, "alphanum_fraction": 0.4911642412, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5366330402975732}}
{"text": "#include <gsl/gsl_integration.h>\n\n#include <algorithm>\n\n#include <Eigen/Dense>\n\n#include \"GaussLegendre2d.hh\"\n#include \"TypesFunctions.hh\"\n\nusing namespace Eigen;\n\nvoid GaussLegendre2d::init() {\n  size_t npoints = 0;\n  for (size_t n: m_xorders) {\n    npoints += n;\n  }\n  m_xpoints.resize(npoints);\n  m_xweights.resize(npoints);\n  size_t k = 0;\n  for (size_t i = 0; i < m_xorders.size(); ++i) {\n    size_t n = m_xorders[i];\n    auto *t = gsl_integration_glfixed_table_alloc(n);\n\n    double a = m_xedges[i];\n    double b = m_xedges[i+1];\n\n    for (size_t j = 0; j < t->n; ++j) {\n      gsl_integration_glfixed_point(a, b, j, &m_xpoints[k], &m_xweights[k], t);\n      k++;\n    }\n    gsl_integration_glfixed_table_free(t);\n  }\n\n  auto *t = gsl_integration_glfixed_table_alloc(m_yorder);\n  m_ypoints.resize(t->n);\n  m_yweights.resize(t->n);\n  for (size_t i = 0; i < t->n; ++i) {\n    gsl_integration_glfixed_point(m_ymin, m_ymax, i,\n                                  &m_ypoints[i], &m_yweights[i], t);\n  }\n  gsl_integration_glfixed_table_free(t);\n\n  transformation_(\"points\")\n    .output(\"x\")\n    .output(\"y\")\n    .output(\"xedges\")\n    .output(\"xhist\")\n    .types([](GaussLegendre2d *obj, TypesFunctionArgs& fargs) {\n        auto& rets=fargs.rets;\n        rets[0] = DataType().points().shape(obj->m_xpoints.size());\n        rets[1] = DataType().points().shape(obj->m_ypoints.size());\n        rets[2] = DataType().points().shape(obj->m_xedges.size());\n        rets[3] = DataType().hist().edges(obj->m_xedges);\n      })\n    .func([](GaussLegendre2d *obj, FunctionArgs& fargs) {\n        auto& rets=fargs.rets;\n        rets[0].x = Eigen::Map<const Eigen::ArrayXd>(&obj->m_xpoints[0], obj->m_xpoints.size());\n        rets[1].x = Eigen::Map<const Eigen::ArrayXd>(&obj->m_ypoints[0], obj->m_ypoints.size());\n        rets[2].x = Eigen::Map<const Eigen::ArrayXd>(&obj->m_xedges[0], obj->m_xedges.size());\n        rets.untaint();\n        rets.freeze();\n      })\n    .finalize()\n    ;\n}\n\nGaussLegendre2dHist::GaussLegendre2dHist(const GaussLegendre2d *base)\n  : m_base(base)\n{\n  transformation_(\"hist\")\n    .input(\"f\")\n    .output(\"hist\")\n    .types(TypesFunctions::ifSame, [](GaussLegendre2dHist *obj, TypesFunctionArgs& fargs) {\n        fargs.rets[0] = DataType().hist().bins(obj->m_base->m_xorders.size()).edges(obj->m_base->m_xedges);\n      })\n    .func([](GaussLegendre2dHist *obj, FunctionArgs& fargs) {\n        auto& args=fargs.args;\n        auto& rets=fargs.rets;\n        size_t shape[2];\n        shape[0] = obj->m_base->m_xpoints.size();\n        shape[1] = obj->m_base->m_ypoints.size();\n        for (size_t k = 0; k < rets.size(); ++k) {\n          Map<const ArrayXXd, Aligned> pts(args[k].x.data(), shape[0], shape[1]);\n          auto &xw = obj->m_base->m_xweights, &yw = obj->m_base->m_yweights;\n          ArrayXd prod = (pts.rowwise()*yw.transpose()).rowwise().sum()*xw;\n          auto *data = prod.data();\n          for (size_t i = 0; i < obj->m_base->m_xorders.size(); ++i) {\n            size_t n = obj->m_base->m_xorders[i];\n            rets[k].x(i) = std::accumulate(data, data+n, 0.0);\n            data += n;\n          }\n        }\n      })\n    ;\n}\n\n", "meta": {"hexsha": "44fb767da2c03798e6c8584dc4a4055678e12076", "size": 3147, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/legacy/GaussLegendre2d.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/legacy/GaussLegendre2d.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/legacy/GaussLegendre2d.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.4432989691, "max_line_length": 107, "alphanum_fraction": 0.5907213219, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5366093593596749}}
{"text": "#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n#include <algorithm>\n#include <cstring>\n#include <elasty/constraint.hpp>\n#include <elasty/fem.hpp>\n#include <elasty/particle.hpp>\n\nnamespace\n{\n    inline Eigen::Matrix3d convertVecToCrossOp(const Eigen::Vector3d& vec)\n    {\n        Eigen::Matrix3d mat = Eigen::Matrix3d::Zero();\n\n        mat(0, 1) = -vec(2);\n        mat(0, 2) = +vec(1);\n        mat(1, 0) = +vec(2);\n        mat(1, 2) = -vec(0);\n        mat(2, 0) = -vec(1);\n        mat(2, 1) = +vec(0);\n\n        return mat;\n    };\n\n    inline double calculateCotTheta(const Eigen::Vector3d& x, const Eigen::Vector3d& y)\n    {\n        const double scaled_cos_theta = x.dot(y);\n        const double scaled_sin_theta = x.cross(y).norm();\n        return scaled_cos_theta / scaled_sin_theta;\n    }\n} // namespace\n\nelasty::BendingConstraint::BendingConstraint(const std::shared_ptr<Particle> p_0,\n                                             const std::shared_ptr<Particle> p_1,\n                                             const std::shared_ptr<Particle> p_2,\n                                             const std::shared_ptr<Particle> p_3,\n                                             const double                    stiffness,\n                                             const double                    compliance,\n                                             const double                    delta_time,\n                                             const double                    dihedral_angle)\n    : FixedNumAbstractConstraint(std::vector<std::shared_ptr<Particle>>{p_0, p_1, p_2, p_3},\n                                 stiffness,\n                                 compliance,\n                                 delta_time),\n      m_dihedral_angle(dihedral_angle)\n{\n}\n\ndouble elasty::BendingConstraint::calculateValue()\n{\n    const Eigen::Vector3d& x_0 = m_particles[0]->p;\n    const Eigen::Vector3d& x_1 = m_particles[1]->p;\n    const Eigen::Vector3d& x_2 = m_particles[2]->p;\n    const Eigen::Vector3d& x_3 = m_particles[3]->p;\n\n    const Eigen::Vector3d p_10 = x_1 - x_0;\n    const Eigen::Vector3d p_20 = x_2 - x_0;\n    const Eigen::Vector3d p_30 = x_3 - x_0;\n\n    const Eigen::Vector3d n_0 = p_10.cross(p_20).normalized();\n    const Eigen::Vector3d n_1 = p_10.cross(p_30).normalized();\n\n    const double current_dihedral_angle = std::acos(std::clamp(n_0.dot(n_1), -1.0, 1.0));\n\n    assert(n_0.norm() > 0.0);\n    assert(n_1.norm() > 0.0);\n    assert(!std::isnan(current_dihedral_angle));\n\n    return current_dihedral_angle - m_dihedral_angle;\n}\n\n// See the appendix of the original paper by Muller et al. (2007) for details.\nvoid elasty::BendingConstraint::calculateGrad(double* grad_C)\n{\n    const Eigen::Vector3d& x_0 = m_particles[0]->p;\n    const Eigen::Vector3d& x_1 = m_particles[1]->p;\n    const Eigen::Vector3d& x_2 = m_particles[2]->p;\n    const Eigen::Vector3d& x_3 = m_particles[3]->p;\n\n    // Assuming that p_0 = [ 0, 0, 0 ]^T without loss of generality\n    const Eigen::Vector3d p_1 = x_1 - x_0;\n    const Eigen::Vector3d p_2 = x_2 - x_0;\n    const Eigen::Vector3d p_3 = x_3 - x_0;\n\n    const Eigen::Vector3d p_1_cross_p_2 = p_1.cross(p_2);\n    const Eigen::Vector3d p_1_cross_p_3 = p_1.cross(p_3);\n\n    const Eigen::Vector3d n_0 = p_1_cross_p_2.normalized();\n    const Eigen::Vector3d n_1 = p_1_cross_p_3.normalized();\n\n    const double d = n_0.dot(n_1);\n\n    // If the current dihedral angle is sufficiently small or large (i.e., zero or pi), return zeros.\n    // This is only an ad-hoc solution for stability and it needs to be solved in a more theoretically grounded way.\n    constexpr double epsilon = 1e-12;\n    if (1.0 - d * d < epsilon)\n    {\n        std::fill(grad_C, grad_C + 12, 0.0);\n        return;\n    }\n\n    const double common_coeff = -1.0 / std::sqrt(1.0 - d * d);\n\n    auto calc_grad_of_normalized_cross_prod_wrt_p_a =\n        [](const Eigen::Vector3d& p_a, const Eigen::Vector3d& p_b, const Eigen::Vector3d& n) -> Eigen::Matrix3d\n    {\n        return +(1.0 / p_a.cross(p_b).norm()) * (-convertVecToCrossOp(p_b) + n * (n.cross(p_b)).transpose());\n    };\n\n    auto calc_grad_of_normalized_cross_prod_wrt_p_b =\n        [](const Eigen::Vector3d& p_a, const Eigen::Vector3d& p_b, const Eigen::Vector3d& n) -> Eigen::Matrix3d\n    {\n        return -(1.0 / p_a.cross(p_b).norm()) * (-convertVecToCrossOp(p_a) + n * (n.cross(p_a)).transpose());\n    };\n\n    const Eigen::Matrix3d partial_n_0_per_partial_p_1 = calc_grad_of_normalized_cross_prod_wrt_p_a(p_1, p_2, n_0);\n    const Eigen::Matrix3d partial_n_1_per_partial_p_1 = calc_grad_of_normalized_cross_prod_wrt_p_a(p_1, p_3, n_1);\n    const Eigen::Matrix3d partial_n_0_per_partial_p_2 = calc_grad_of_normalized_cross_prod_wrt_p_b(p_1, p_2, n_0);\n    const Eigen::Matrix3d partial_n_1_per_partial_p_3 = calc_grad_of_normalized_cross_prod_wrt_p_b(p_1, p_3, n_1);\n\n    const Eigen::Vector3d grad_C_wrt_p_1 =\n        common_coeff * (partial_n_0_per_partial_p_1.transpose() * n_1 + partial_n_1_per_partial_p_1.transpose() * n_0);\n    const Eigen::Vector3d grad_C_wrt_p_2 = common_coeff * partial_n_0_per_partial_p_2.transpose() * n_1;\n    const Eigen::Vector3d grad_C_wrt_p_3 = common_coeff * partial_n_1_per_partial_p_3.transpose() * n_0;\n    const Eigen::Vector3d grad_C_wrt_p_0 = -grad_C_wrt_p_1 - grad_C_wrt_p_2 - grad_C_wrt_p_3;\n\n    std::memcpy(grad_C + (3 * 0), grad_C_wrt_p_0.data(), sizeof(double) * 3);\n    std::memcpy(grad_C + (3 * 1), grad_C_wrt_p_1.data(), sizeof(double) * 3);\n    std::memcpy(grad_C + (3 * 2), grad_C_wrt_p_2.data(), sizeof(double) * 3);\n    std::memcpy(grad_C + (3 * 3), grad_C_wrt_p_3.data(), sizeof(double) * 3);\n}\n\nelasty::ContinuumTriangleConstraint::ContinuumTriangleConstraint(const std::shared_ptr<Particle> p_0,\n                                                                 const std::shared_ptr<Particle> p_1,\n                                                                 const std::shared_ptr<Particle> p_2,\n                                                                 const double                    stiffness,\n                                                                 const double                    compliance,\n                                                                 const double                    delta_time,\n                                                                 const double                    youngs_modulus,\n                                                                 const double                    poisson_ratio)\n    : FixedNumAbstractConstraint(std::vector<std::shared_ptr<Particle>>{p_0, p_1, p_2},\n                                 stiffness,\n                                 compliance,\n                                 delta_time),\n      m_first_lame(fem::calcFirstLame(youngs_modulus, poisson_ratio)),\n      m_second_lame(fem::calcSecondLame(youngs_modulus, poisson_ratio))\n{\n    const Eigen::Vector3d& x_0 = m_particles[0]->x;\n    const Eigen::Vector3d& x_1 = m_particles[1]->x;\n    const Eigen::Vector3d& x_2 = m_particles[2]->x;\n\n    // Calculate the two axes for defining material coordinates\n    const Eigen::Vector3d r_1    = x_1 - x_0;\n    const Eigen::Vector3d r_2    = x_2 - x_0;\n    const Eigen::Vector3d cross  = r_1.cross(r_2);\n    const Eigen::Vector3d axis_1 = r_1.normalized();\n    const Eigen::Vector3d axis_2 = cross.cross(axis_1).normalized();\n\n    // Calculate the rest positions in the material coordinates\n    const Eigen::Vector2d mat_x_0(axis_1.dot(x_0), axis_2.dot(x_0));\n    const Eigen::Vector2d mat_x_1(axis_1.dot(x_1), axis_2.dot(x_1));\n    const Eigen::Vector2d mat_x_2(axis_1.dot(x_2), axis_2.dot(x_2));\n\n    // Calculate the rest shape matrix\n    Eigen::Matrix2d rest_D;\n    rest_D.col(0) = mat_x_1 - mat_x_0;\n    rest_D.col(1) = mat_x_2 - mat_x_0;\n\n    // Calculate the inverse of the rest shape matrix\n    assert(rest_D.determinant() > 0.0);\n    m_rest_D_inv = rest_D.inverse();\n\n    // Calculate the area of the rest configuration\n    m_rest_area = 0.5 * cross.norm();\n}\n\ndouble elasty::ContinuumTriangleConstraint::calculateValue()\n{\n    const Eigen::Vector3d& x_0 = m_particles[0]->p;\n    const Eigen::Vector3d& x_1 = m_particles[1]->p;\n    const Eigen::Vector3d& x_2 = m_particles[2]->p;\n\n    // Calculate the shape matrix\n    Eigen::Matrix<double, 3, 2> D;\n    D.col(0) = x_1 - x_0;\n    D.col(1) = x_2 - x_0;\n\n    // Calculate the deformation gradient (a 3-by-2 matrix)\n    const auto F = D * m_rest_D_inv;\n\n    // Calculate the strain energy density\n    const double psi = fem::calcStVenantKirchhoffEnergyDensity(F, m_first_lame, m_second_lame);\n\n    // Return the constraint value\n    return m_rest_area * psi;\n}\n\nvoid elasty::ContinuumTriangleConstraint::calculateGrad(double* grad_C)\n{\n    const Eigen::Vector3d& x_0 = m_particles[0]->p;\n    const Eigen::Vector3d& x_1 = m_particles[1]->p;\n    const Eigen::Vector3d& x_2 = m_particles[2]->p;\n\n    // Calculate the shape matrix\n    Eigen::Matrix<double, 3, 2> D;\n    D.col(0) = x_1 - x_0;\n    D.col(1) = x_2 - x_0;\n\n    // Calculate the deformation gradient (a 3-by-2 matrix)\n    const auto F = D * m_rest_D_inv;\n\n    // Calculate the first Piola-Kirchhoff stress tensor (a 3-by-2 matrix)\n    const auto P = fem::calcStVenantKirchhoffPiolaStress(F, m_first_lame, m_second_lame);\n\n    // Calculate the gradient of the constraint\n    const Eigen::Matrix<double, 3, 2> grad_12 = m_rest_area * P * m_rest_D_inv.transpose();\n    const Eigen::Vector3d             grad_0  = -grad_12.col(0) - grad_12.col(1);\n\n    // Copy the results\n    std::memcpy(grad_C + 0, grad_0.data(), sizeof(double) * 3);\n    std::memcpy(grad_C + 3, grad_12.data(), sizeof(double) * 6);\n}\n\nelasty::DistanceConstraint::DistanceConstraint(const std::shared_ptr<Particle> p_0,\n                                               const std::shared_ptr<Particle> p_1,\n                                               const double                    stiffness,\n                                               const double                    compliance,\n                                               const double                    delta_time,\n                                               const double                    d)\n    : FixedNumAbstractConstraint(std::vector<std::shared_ptr<Particle>>{p_0, p_1}, stiffness, compliance, delta_time),\n      m_d(d)\n{\n    assert(d >= 0.0);\n}\n\ndouble elasty::DistanceConstraint::calculateValue()\n{\n    const Eigen::Vector3d& x_0 = m_particles[0]->p;\n    const Eigen::Vector3d& x_1 = m_particles[1]->p;\n\n    return (x_0 - x_1).norm() - m_d;\n}\n\nvoid elasty::DistanceConstraint::calculateGrad(double* grad_C)\n{\n    const Eigen::Vector3d& x_0 = m_particles[0]->p;\n    const Eigen::Vector3d& x_1 = m_particles[1]->p;\n\n    const Eigen::Vector3d r = x_0 - x_1;\n\n    const double dist = r.norm();\n\n    constexpr double epsilon = 1e-24;\n\n    // Calculate a normalized vector, where a random direction is selected when the points are degenerated\n    const Eigen::Vector3d n = (dist < epsilon) ? Eigen::Vector3d::Random().normalized() : (1.0 / dist) * r;\n\n    grad_C[0] = +n(0);\n    grad_C[1] = +n(1);\n    grad_C[2] = +n(2);\n    grad_C[3] = -n(0);\n    grad_C[4] = -n(1);\n    grad_C[5] = -n(2);\n}\n\nelasty::EnvironmentalCollisionConstraint::EnvironmentalCollisionConstraint(const std::shared_ptr<Particle> p_0,\n                                                                           const double                    stiffness,\n                                                                           const double                    compliance,\n                                                                           const double                    delta_time,\n                                                                           const Eigen::Vector3d&          n,\n                                                                           const double                    d)\n    : FixedNumAbstractConstraint(std::vector<std::shared_ptr<Particle>>{p_0}, stiffness, compliance, delta_time),\n      m_n(n),\n      m_d(d)\n{\n}\n\ndouble elasty::EnvironmentalCollisionConstraint::calculateValue()\n{\n    const Eigen::Vector3d& x = m_particles[0]->p;\n    return m_n.transpose() * x - m_d;\n}\n\nvoid elasty::EnvironmentalCollisionConstraint::calculateGrad(double* grad_C)\n{\n    std::memcpy(grad_C, m_n.data(), sizeof(double) * 3);\n}\n\nelasty::FixedPointConstraint::FixedPointConstraint(const std::shared_ptr<Particle> p_0,\n                                                   const double                    stiffness,\n                                                   const double                    compliance,\n                                                   const double                    delta_time,\n                                                   const Eigen::Vector3d&          point)\n    : FixedNumAbstractConstraint(std::vector<std::shared_ptr<Particle>>{p_0}, stiffness, compliance, delta_time),\n      m_point(point)\n{\n}\n\ndouble elasty::FixedPointConstraint::calculateValue()\n{\n    const Eigen::Vector3d& x = m_particles[0]->p;\n    return (x - m_point).norm();\n}\n\nvoid elasty::FixedPointConstraint::calculateGrad(double* grad_C)\n{\n    const Eigen::Vector3d& x    = m_particles[0]->p;\n    const Eigen::Vector3d  r    = x - m_point;\n    const double           dist = r.norm();\n\n    constexpr double epsilon = 1e-24;\n\n    // Calculate a normalized vector, where a random direction is selected when the points are degenerated\n    const Eigen::Vector3d n = (dist < epsilon) ? Eigen::Vector3d::Random().normalized() : (1.0 / dist) * r;\n\n    std::memcpy(grad_C, n.data(), sizeof(double) * 3);\n}\n\nelasty::IsometricBendingConstraint::IsometricBendingConstraint(const std::shared_ptr<Particle> p_0,\n                                                               const std::shared_ptr<Particle> p_1,\n                                                               const std::shared_ptr<Particle> p_2,\n                                                               const std::shared_ptr<Particle> p_3,\n                                                               const double                    stiffness,\n                                                               const double                    compliance,\n                                                               const double                    delta_time)\n    : FixedNumAbstractConstraint(std::vector<std::shared_ptr<Particle>>{p_0, p_1, p_2, p_3},\n                                 stiffness,\n                                 compliance,\n                                 delta_time)\n{\n    const Eigen::Vector3d& x_0 = p_0->x;\n    const Eigen::Vector3d& x_1 = p_1->x;\n    const Eigen::Vector3d& x_2 = p_2->x;\n    const Eigen::Vector3d& x_3 = p_3->x;\n\n    const Eigen::Vector3d e0 = x_1 - x_0;\n    const Eigen::Vector3d e1 = x_2 - x_1;\n    const Eigen::Vector3d e2 = x_0 - x_2;\n    const Eigen::Vector3d e3 = x_3 - x_0;\n    const Eigen::Vector3d e4 = x_1 - x_3;\n\n    const double cot_01 = calculateCotTheta(e0, -e1);\n    const double cot_02 = calculateCotTheta(e0, -e2);\n    const double cot_03 = calculateCotTheta(e0, e3);\n    const double cot_04 = calculateCotTheta(e0, e4);\n\n    const Eigen::Vector4d K = Eigen::Vector4d(cot_01 + cot_04, cot_02 + cot_03, -cot_01 - cot_02, -cot_03 - cot_04);\n\n    const double A_0 = 0.5 * e0.cross(e1).norm();\n    const double A_1 = 0.5 * e0.cross(e3).norm();\n\n    m_Q = (3.0 / (A_0 + A_1)) * K * K.transpose();\n}\n\ndouble elasty::IsometricBendingConstraint::calculateValue()\n{\n    double sum = 0.0;\n    for (unsigned int i = 0; i < 4; ++i)\n    {\n        for (unsigned int j = 0; j < 4; ++j)\n        {\n            sum += m_Q(i, j) * double(m_particles[i]->p.transpose() * m_particles[j]->p);\n        }\n    }\n    return 0.5 * sum;\n}\n\nvoid elasty::IsometricBendingConstraint::calculateGrad(double* grad_C)\n{\n    for (unsigned int i = 0; i < 4; ++i)\n    {\n        Eigen::Vector3d sum = Eigen::Vector3d::Zero();\n        for (unsigned int j = 0; j < 4; ++j)\n        {\n            sum += m_Q(i, j) * m_particles[j]->p;\n        }\n        std::memcpy(grad_C + (3 * i), sum.data(), sizeof(double) * 3);\n    }\n}\n\nelasty::ShapeMatchingConstraint::ShapeMatchingConstraint(const std::vector<std::shared_ptr<Particle>>& particles,\n                                                         const double                                  stiffness,\n                                                         const double                                  compliance,\n                                                         const double                                  delta_time)\n    : VariableNumConstraint(particles, stiffness, compliance, delta_time)\n{\n    // Calculate the initial center of mass and the total mass\n    Eigen::Vector3d x_0_cm = Eigen::Vector3d::Zero();\n    m_total_mass           = 0.0;\n    for (int i = 0; i < m_particles.size(); ++i)\n    {\n        m_total_mass += m_particles[i]->m;\n        x_0_cm += m_particles[i]->m * m_particles[i]->p;\n    }\n    x_0_cm /= m_total_mass;\n\n    // Calculate q\n    m_q.resize(m_particles.size());\n    for (int i = 0; i < m_particles.size(); ++i)\n    {\n        m_q[i] = m_particles[i]->x - x_0_cm;\n    }\n}\n\ndouble elasty::ShapeMatchingConstraint::calculateValue()\n{\n    throw std::runtime_error(\"ShapeMatchingConstraint does not directly provide its cost value or the gradient.\");\n}\n\nvoid elasty::ShapeMatchingConstraint::calculateGrad(double* grad_C)\n{\n    throw std::runtime_error(\"ShapeMatchingConstraint does not directly provide its cost value or the gradient.\");\n}\n\nvoid elasty::ShapeMatchingConstraint::projectParticles(const AlgorithmType type)\n{\n    // Calculate the current center of mass\n    Eigen::Vector3d x_cm = Eigen::Vector3d::Zero();\n    for (int i = 0; i < m_particles.size(); ++i)\n    {\n        x_cm += m_particles[i]->m * m_particles[i]->p;\n    }\n    x_cm /= m_total_mass;\n\n    // Calculate A_pq\n    Eigen::Matrix3d A_pq = Eigen::Matrix3d::Zero();\n    for (int i = 0; i < m_particles.size(); ++i)\n    {\n        A_pq += m_particles[i]->m * (m_particles[i]->p - x_cm) * m_q[i].transpose();\n    }\n\n    // Calculate the rotation matrix\n    const auto            ATA          = A_pq.transpose() * A_pq;\n    const auto            eigen_solver = Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d>(ATA);\n    const auto            S_inv        = eigen_solver.operatorInverseSqrt();\n    const Eigen::Matrix3d R            = A_pq * S_inv;\n\n    assert(R.determinant() > 0);\n\n    // Update the particle positions\n    for (int i = 0; i < m_particles.size(); ++i)\n    {\n        // Calculate the goal position\n        const Eigen::Vector3d g = R * m_q[i] + x_cm;\n\n        // Move the particle\n        m_particles[i]->p = m_stiffness * g + (1.0 - m_stiffness) * m_particles[i]->p;\n    }\n}\n", "meta": {"hexsha": "297c0a7ed3a7750d1f1d5b1d1e0c3df31de887ab", "size": 18671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/constraint.cpp", "max_stars_repo_name": "yuki-koyama/elasty", "max_stars_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 176.0, "max_stars_repo_stars_event_min_datetime": "2019-04-27T00:45:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:15:45.000Z", "max_issues_repo_path": "src/constraint.cpp", "max_issues_repo_name": "yuki-koyama/elasty", "max_issues_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2019-04-27T00:00:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T07:01:12.000Z", "max_forks_repo_path": "src/constraint.cpp", "max_forks_repo_name": "yuki-koyama/elasty", "max_forks_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T01:09:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:30:41.000Z", "avg_line_length": 41.4911111111, "max_line_length": 119, "alphanum_fraction": 0.5655294307, "num_tokens": 4916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5365702759558904}}
{"text": "#include \"rbfcore.h\"\n#include \"utility.h\"\n#include \"Solver.h\"\n#include <armadillo>\n#include <fstream>\n#include <limits>\n#include <iomanip>\n#include <ctime>\n#include <chrono>\n#include<algorithm>\n\n\n\ndouble sigma = 2.0;\ndouble inv_sigma_squarex2 = 1/(2 * pow(sigma, 2));\ndouble Gaussian_Kernel(const double x_square){\n\n    return exp(-x_square*inv_sigma_squarex2);\n\n}\n\ndouble Gaussian_Kernel_2p(const double *p1, const double *p2){\n\n\n\n    return Gaussian_Kernel(MyUtility::vecSquareDist(p1,p2));\n\n\n}\n\ndouble Gaussian_PKernel_Dirichlet_2p(const double *p1, const double *p2){\n\n\n    double d2 = MyUtility::vecSquareDist(p1,p2);\n    return (6*sigma*sigma-d2)*sqrt(Gaussian_Kernel(d2));\n\n\n}\n\ndouble Gaussian_PKernel_Bending_2p(const double *p1, const double *p2){\n\n\n    double d2 = MyUtility::vecSquareDist(p1,p2);\n    double d4 = d2*d2;\n    double sigma2 = sigma * sigma;\n    double sigma4 = sigma2 * sigma2;\n    return (60*sigma4-20*sigma2*d2+d4)*sqrt(Gaussian_Kernel(d2));\n\n\n}\n\n\ndouble XCube_Kernel(const double x){\n\n    return pow(x,3);\n}\n\ndouble XCube_Kernel_2p(const double *p1, const double *p2){\n\n\n    return XCube_Kernel(MyUtility::_VerticesDistance(p1,p2));\n\n}\n\nvoid XCube_Gradient_Kernel_2p(const double *p1, const double *p2, double *G){\n\n\n    double len_dist  = MyUtility::_VerticesDistance(p1,p2);\n    for(int i=0;i<3;++i)G[i] = 3*len_dist*(p1[i]-p2[i]);\n    return;\n\n}\n\ndouble XCube_GradientDot_Kernel_2p(const double *p1, const double *p2, const double *p3){\n\n\n    double G[3];\n    XCube_Gradient_Kernel_2p(p1,p2,G);\n    return MyUtility::dot(p3,G);\n\n}\n\nvoid XCube_Hessian_Kernel_2p(const double *p1, const double *p2, double *H){\n\n\n    double diff[3];\n    for(int i=0;i<3;++i)diff[i] = p1[i] - p2[i];\n    double len_dist  = sqrt(MyUtility::len(diff));\n\n    if(len_dist<1e-8){\n        for(int i=0;i<9;++i)H[i] = 0;\n    }else{\n        for(int i=0;i<3;++i)for(int j=0;j<3;++j)\n            if(i==j)H[i*3+j] = 3 * pow(diff[i],2) / len_dist + 3 * len_dist;\n            else H[i*3+j] = 3 * diff[i] * diff[j] / len_dist;\n    }\n\n\n    return;\n\n}\n\nvoid XCube_HessianDot_Kernel_2p(const double *p1, const double *p2, const double *p3, vector<double>&dotout){\n\n\n    double H[9];\n    XCube_Gradient_Kernel_2p(p1,p2,H);\n    dotout.resize(3);\n    for(int i=0;i<3;++i){\n        dotout[i] = 0;\n        for(int j=0;j<3;++j){\n            dotout[i] += H[i*3+j] * p3[j];\n        }\n    }\n\n}\n\nRBF_Core::RBF_Core(){\n\n    Kernal_Function = Gaussian_Kernel;\n    Kernal_Function_2p = Gaussian_Kernel_2p;\n    P_Function_2p = Gaussian_PKernel_Dirichlet_2p;\n\n    isHermite = false;\n\n    mp_RBF_INITMETHOD.insert(make_pair(GT_NORMAL,\"GT_NORMAL\"));\n    mp_RBF_INITMETHOD.insert(make_pair(GlobalEigen,\"GlobalEigen\"));\n    mp_RBF_INITMETHOD.insert(make_pair(GlobalEigenWithMST,\"GlobalEigenWithMST\"));\n    mp_RBF_INITMETHOD.insert(make_pair(GlobalEigenWithGT,\"GlobalEigenWithGT\"));\n    mp_RBF_INITMETHOD.insert(make_pair(LocalEigen,\"LocalEigen\"));\n    mp_RBF_INITMETHOD.insert(make_pair(IterativeEigen,\"IterativeEigen\"));\n    mp_RBF_INITMETHOD.insert(make_pair(ClusterEigen,\"ClusterEigen\"));\n\n\n    mp_RBF_METHOD.insert(make_pair(Variational,\"Variational\"));\n    mp_RBF_METHOD.insert(make_pair(Variational_P,\"Variation_P\"));\n    mp_RBF_METHOD.insert(make_pair(LS,\"LS\"));\n    mp_RBF_METHOD.insert(make_pair(LSinterp,\"LSinterp\"));\n    mp_RBF_METHOD.insert(make_pair(Interp,\"Interp\"));\n    mp_RBF_METHOD.insert(make_pair(RayleighQuotients,\"Rayleigh\"));\n    mp_RBF_METHOD.insert(make_pair(RayleighQuotients_P,\"Rayleigh_P\"));\n    mp_RBF_METHOD.insert(make_pair(RayleighQuotients_I,\"Rayleigh_I\"));\n    mp_RBF_METHOD.insert(make_pair(Hermite,\"Hermite\"));\n    mp_RBF_METHOD.insert(make_pair(Hermite_UnitNorm,\"UnitNorm\"));\n    mp_RBF_METHOD.insert(make_pair(Hermite_UnitNormal,\"UnitNormal\"));\n    mp_RBF_METHOD.insert(make_pair(Hermite_Tangent_UnitNorm,\"T_UnitNorm\"));\n    mp_RBF_METHOD.insert(make_pair(Hermite_Tangent_UnitNormal,\"T_UnitNormal\"));\n\n    mp_RBF_Kernal.insert(make_pair(XCube,\"TriH\"));\n    mp_RBF_Kernal.insert(make_pair(ThinSpline,\"ThinSpline\"));\n    mp_RBF_Kernal.insert(make_pair(XLinear,\"XLinear\"));\n    mp_RBF_Kernal.insert(make_pair(Gaussian,\"Gaussian\"));\n\n}\nRBF_Core::RBF_Core(RBF_Kernal kernal){\n    isHermite = false;\n    Init(kernal);\n}\n\nvoid RBF_Core::Init(RBF_Kernal kernal){\n\n    this->kernal = kernal;\n    switch(kernal){\n    case Gaussian:\n        Kernal_Function = Gaussian_Kernel;\n        Kernal_Function_2p = Gaussian_Kernel_2p;\n        P_Function_2p = Gaussian_PKernel_Dirichlet_2p;\n        break;\n\n    case XCube:\n        Kernal_Function = XCube_Kernel;\n        Kernal_Function_2p = XCube_Kernel_2p;\n        Kernal_Gradient_Function_2p = XCube_Gradient_Kernel_2p;\n        Kernal_Hessian_Function_2p = XCube_Hessian_Kernel_2p;\n        break;\n\n    default:\n        break;\n\n    }\n\n}\n\nvoid RBF_Core::SetSigma(double x){\n    sigma = x;\n    inv_sigma_squarex2 = 1/(2 * pow(sigma, 2));\n}\n\ndouble RBF_Core::Dist_Function(const double x, const double y, const double z){\n\n\n\treturn -1;\n\n}\n\n\n\ninline double RBF_Core::Dist_Function(const double *p){\n\n    n_evacalls++;\n    double *p_pts = pts.data();\n    static arma::vec kern(npt), kb;\n    if(isHermite){\n        kern.set_size(npt*4);\n        double G[3];\n        for(int i=0;i<npt;++i)kern(i) = Kernal_Function_2p(p_pts+i*3, p);\n        for(int i=0;i<npt;++i){\n            Kernal_Gradient_Function_2p(p,p_pts+i*3,G);\n            //for(int j=0;j<3;++j)kern(npt+i*3+j) = -G[j];\n            for(int j=0;j<3;++j)kern(npt+i+j*npt) = G[j];\n        }\n    }else{\n        kern.set_size(npt);\n        for(int i=0;i<npt;++i)kern(i) = Kernal_Function_2p(p_pts+i*3, p);\n    }\n\n    double loc_part = dot(kern,a);\n\n    if(polyDeg==1){\n        kb.set_size(4);\n        for(int i=0;i<3;++i)kb(i+1) = p[i];\n        kb(0) = 1;\n    }else if(polyDeg==2){\n        vector<double>buf(4,1);\n        int ind = 0;\n        kb.set_size(10);\n        for(int j=0;j<3;++j)buf[j+1] = p[j];\n        for(int j=0;j<4;++j)for(int k=j;k<4;++k)kb(ind++) = buf[j] * buf[k];\n    }\n    double poly_part = dot(kb,b);\n\n    if(0){\n        cout<<\"dist: \"<<p[0]<<' '<<p[1]<<' '<<p[2]<<' '<<p_pts[3]<<' '<<p_pts[4]<<' '<<p_pts[5]<<' '<<\n              Kernal_Function_2p(p,p_pts+3)<<endl;\n        for(int i=0;i<npt;++i)cout<<kern(i)<<' ';\n        for(int i=0;i<bsize;++i)cout<<kb(i)<<' ';\n        cout<<endl;\n    }\n\n    double re = loc_part + poly_part;\n    return re;\n\n\n}\nstatic RBF_Core * s_hrbf;\ndouble RBF_Core::Dist_Function(const R3Pt &in_pt){\n    return s_hrbf->Dist_Function(&(in_pt[0]));\n}\n\n//FT RBF_Core::Dist_Function(const Point_3 in_pt){\n\n//    return s_hrbf->Dist_Function(&(in_pt.x()));\n//}\n\nvoid RBF_Core::SetThis(){\n\n    s_hrbf = this;\n}\n\nvoid RBF_Core::Write_Surface(string fname){\n\n    //writeObjFile(fname,finalMesh_v,finalMesh_fv);\n\n    writePLYFile_VF(fname,finalMesh_v,finalMesh_fv);\n}\n\n/**********************************************************/\n\n\nvoid RBF_Core::Record(RBF_METHOD method, RBF_Kernal kernal, Solution_Struct &rsol, double time){\n\n    npoints.push_back(npt);\n\n    record_initmethod.push_back(mp_RBF_INITMETHOD[curInitMethod]);\n    record_method.push_back(mp_RBF_METHOD[method]);\n    record_kernal.push_back(mp_RBF_Kernal[kernal]);\n    record_initenergy.push_back(rsol.init_energy);\n    record_energy.push_back(rsol.energy);\n    record_time.push_back(time);\n\n\n    setup_timev.push_back(setup_time);\n    init_timev.push_back(init_time);\n    solve_timev.push_back(solve_time);\n    callfunc_timev.push_back(callfunc_time);\n    invM_timev.push_back(invM_time);\n    setK_timev.push_back(setK_time);\n\n}\n\nvoid RBF_Core::Record(){\n\n    //cout<<\"record\"<<endl;\n    npoints.push_back(npt);\n\n    record_initmethod.push_back(mp_RBF_INITMETHOD[curInitMethod]);\n    record_method.push_back(mp_RBF_METHOD[curMethod]);\n    //record_kernal.push_back(mp_RBF_Kernal[kernal]);\n    record_initenergy.push_back(sol.init_energy);\n    record_energy.push_back(sol.energy);\n    //cout<<\"record\"<<endl;\n\n\n//    setup_timev.push_back(setup_time);\n//    init_timev.push_back(init_time);\n//    solve_timev.push_back(solve_time);\n//    callfunc_timev.push_back(callfunc_time);\n//    invM_timev.push_back(invM_time);\n//    setK_timev.push_back(setK_time);\n   // cout<<\"record end\"<<endl;\n}\n\nvoid RBF_Core::AddPartition(string pname){\n\n    record_partition.push_back(record_method.size());\n    record_partition_name.push_back(pname);\n}\n\n\nvoid RBF_Core::Print_Record(){\n\n    cout<<\"Method\\t\\t Kernal\\t\\t Energy\\t\\t Time\"<<endl;\n    cout<<std::setprecision(8)<<endl;\n    if(record_partition.size()==0){\n        for(int i=0;i<record_method.size();++i){\n            cout<<record_method[i]<<\"\\t\\t\"<<record_kernal[i]<<\"\\t\\t\"<<record_energy[i]<<\"\\t\\t\"<<record_time[i]<<endl;\n        }\n        for(int i=0;i<setup_timev.size();++i){\n            cout<<setup_timev[i]<<\"\\t\\t\"<<init_timev[i]<<\"\\t\\t\"<<solve_timev[i]<<\"\\t\\t\"<<callfunc_timev[i]<<\"\\t\\t\"<<invM_timev[i]<<\"\\t\\t\"<<setK_timev[i]<<endl;\n        }\n    }else{\n        for(int j=0;j<record_partition.size();++j){\n            cout<<record_partition_name[j]<<endl;\n            for(int i=j==0?0:record_partition[j-1];i<record_partition[j];++i){\n                cout<<record_method[i]<<\"\\t\\t\"<<record_kernal[i]<<\"\\t\\t\"<<record_energy[i]<<\"\\t\\t\"<<record_time[i]<<endl;\n            }\n            for(int i=j==0?0:record_partition[j-1];i<record_partition[j];++i){\n                cout<<setup_timev[i]<<\"\\t\\t\"<<init_timev[i]<<\"\\t\\t\"<<solve_timev[i]<<\"\\t\\t\"<<callfunc_timev[i]<<endl;\n            }\n        }\n    }\n\n}\n\n\nvoid RBF_Core::Print_TimerRecord(string fname){\n\n    ofstream fout(fname);\n    fout<<setprecision(5);\n    if(!fout.fail()){\n        for(int i=0;i<setup_timev.size();++i){\n            fout<<npoints[i]<<'\\t'<<setup_timev[i]<<\"\\t\"<<init_timev[i]<<\"\\t\"<<solve_timev[i]<<\"\\t\"<<callfunc_timev[i]<<\"\\t\"<<invM_timev[i]<<\"\\t\"<<setK_timev[i]<<endl;\n        }\n    }\n    fout.close();\n\n}\n\nvoid RBF_Core::Print_TimerRecord_Single(string fname){\n\n    ofstream fout(fname);\n    fout<<setprecision(5);\n    if(!fout.fail()){\n        fout<<\"number of points: \"<<npt<<endl\n           <<\"setup_time (Compute H): \"<<setup_time<<\" s\"<<endl\n          <<\"init_time (Optimize g/Eigen): \"<<init_time<<\" s\"<<endl\n         <<\"solve_time (Optimize g/LBFGS): \"<<solve_time<<\" s\"<<endl\n        <<\"surfacing_time: \"<<surf_time<<\" s\"<<endl;\n    }\n    fout.close();\n}\n\nvoid RBF_Core::Clear_TimerRecord(){\n    npoints.clear();\n    setup_timev.clear();\n    init_timev.clear();\n    solve_timev.clear();\n    callfunc_timev.clear();\n    invM_timev.clear();\n    setK_timev.clear();\n\n}\n", "meta": {"hexsha": "1d47fc3ca9a618a5ae95df9ded439c6f9b3fe544", "size": 10495, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vipss/src/rbfcore.cpp", "max_stars_repo_name": "jpanetta/VIPSS", "max_stars_repo_head_hexsha": "34491070a49047f8071f1670139ffe01d38598a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-05-18T05:22:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:40:11.000Z", "max_issues_repo_path": "vipss/src/rbfcore.cpp", "max_issues_repo_name": "jpanetta/VIPSS", "max_issues_repo_head_hexsha": "34491070a49047f8071f1670139ffe01d38598a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-25T01:34:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T15:15:31.000Z", "max_forks_repo_path": "vipss/src/rbfcore.cpp", "max_forks_repo_name": "jpanetta/VIPSS", "max_forks_repo_head_hexsha": "34491070a49047f8071f1670139ffe01d38598a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-05-18T05:22:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T11:50:58.000Z", "avg_line_length": 27.4020887728, "max_line_length": 167, "alphanum_fraction": 0.6445926632, "num_tokens": 3125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504228, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5365382366521079}}
{"text": "\n\n#include <NTL/FFT.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\n\nFFTPrimeInfo *FFTTables = 0;\nVec<FFTPrimeInfo> FFTTables_store;\n\nlong *FFTPrime = 0;\nVec<long> FFTPrime_store;\n\ndouble *FFTPrimeInv = 0;\nVec<double> FFTPrimeInv_store;\n\n// We separate the pointer from the Vec, to ensure\n// portability: global initialization of C++ objects\n// can be problematic.\n\n\n\nlong NumFFTPrimes = 0;\n\n\n\n\nstatic\nlong IsFFTPrime(long n, long& w)\n{\n   long  m, x, y, z;\n   long j, k;\n\n   if (n % 3 == 0) return 0;\n\n   if (n % 5 == 0) return 0;\n\n   if (n % 7 == 0) return 0;\n   \n   m = n - 1;\n   k = 0;\n   while ((m & 1) == 0) {\n      m = m >> 1;\n      k++;\n   }\n\n   for (;;) {\n      x = RandomBnd(n);\n\n      if (x == 0) continue;\n      z = PowerMod(x, m, n);\n      if (z == 1) continue;\n\n      x = z;\n      j = 0;\n      do {\n         y = z;\n         z = MulMod(y, y, n);\n         j++;\n      } while (j != k && z != 1);\n\n      if (z != 1 || y !=  n-1) return 0;\n\n      if (j == k) \n         break;\n   }\n\n   /* x^{2^k} = 1 mod n, x^{2^{k-1}} = -1 mod n */\n\n   long TrialBound;\n\n   TrialBound = m >> k;\n   if (TrialBound > 0) {\n      if (!ProbPrime(n, 5)) return 0;\n   \n      /* we have to do trial division by special numbers */\n   \n      TrialBound = SqrRoot(TrialBound);\n   \n      long a, b;\n   \n      for (a = 1; a <= TrialBound; a++) {\n         b = (a << k) + 1;\n         if (n % b == 0) return 0; \n      }\n   }\n\n   /* n is an FFT prime */\n\n   for (j = NTL_FFTMaxRoot; j < k; j++)\n      x = MulMod(x, x, n);\n\n   w = x;\n   return 1;\n}\n\n\nstatic\nvoid NextFFTPrime(long& q, long& w)\n{\n   static long m = NTL_FFTMaxRootBnd + 1;\n   static long k = 0;\n\n   long t, cand;\n\n   for (;;) {\n      if (k == 0) {\n         m--;\n         if (m < 5) Error(\"ran out of FFT primes\");\n         k = 1L << (NTL_SP_NBITS-m-2);\n      }\n\n      k--;\n\n      cand = (1L << (NTL_SP_NBITS-1)) + (k << (m+1)) + (1L << m) + 1;\n\n      if (!IsFFTPrime(cand, t)) continue;\n      q = cand;\n      w = t;\n      return;\n   }\n}\n\n\nlong CalcMaxRoot(long p)\n{\n   p = p-1;\n   long k = 0;\n   while ((p & 1) == 0) {\n      p = p >> 1;\n      k++;\n   }\n\n   if (k > NTL_FFTMaxRoot)\n      return NTL_FFTMaxRoot;\n   else\n      return k; \n}\n\n\n\nvoid UseFFTPrime(long index)\n{\n   long numprimes = FFTTables_store.length();\n\n   if (index < 0 || index > numprimes)\n      Error(\"invalid FFT prime index\");\n\n   if (index < numprimes) return;\n\n   // index == numprimes\n\n   long q, w;\n\n   NextFFTPrime(q, w);\n\n   double qinv = 1/((double) q);\n\n   long mr = CalcMaxRoot(q);\n\n   FFTTables_store.SetLength(numprimes+1);\n   FFTTables = FFTTables_store.elts();\n\n   FFTPrimeInfo& info = FFTTables[numprimes];\n\n   info.q = q;\n   info.qinv = qinv;\n\n   info.RootTable.SetLength(mr+1);\n   info.RootInvTable.SetLength(mr+1);\n   info.TwoInvTable.SetLength(mr+1);\n   info.TwoInvPreconTable.SetLength(mr+1);\n\n   long *rt = &info.RootTable[0];\n   long *rit = &info.RootInvTable[0];\n   long *tit = &info.TwoInvTable[0];\n   mulmod_precon_t *tipt = &info.TwoInvPreconTable[0];\n\n   long j;\n   long t;\n\n   rt[mr] = w;\n   for (j = mr-1; j >= 0; j--)\n      rt[j] = MulMod(rt[j+1], rt[j+1], q);\n\n   rit[mr] = InvMod(w, q);\n   for (j = mr-1; j >= 0; j--)\n      rit[j] = MulMod(rit[j+1], rit[j+1], q);\n\n   t = InvMod(2, q);\n   tit[0] = 1;\n   for (j = 1; j <= mr; j++)\n      tit[j] = MulMod(tit[j-1], t, q);\n\n   for (j = 0; j <= mr; j++)\n      tipt[j] = PrepMulModPrecon(tit[j], q, qinv);\n\n\n   // initialize data structures for the legacy inteface\n\n   NumFFTPrimes = FFTTables_store.length();\n   \n   FFTPrime_store.SetLength(NumFFTPrimes);\n   FFTPrime = FFTPrime_store.elts();\n   FFTPrime[NumFFTPrimes-1] = q;\n\n   FFTPrimeInv_store.SetLength(NumFFTPrimes);\n   FFTPrimeInv = FFTPrimeInv_store.elts();\n   FFTPrimeInv[NumFFTPrimes-1] = qinv;\n}\n\n\n\n/*\n * Our FFT is based on the routine in Cormen, Leiserson, Rivest, and Stein.\n * For very large inputs, it should be relatively cache friendly.\n * The inner loop has been unrolled and pipelined, to exploit any\n * low-level parallelism in the machine.\n * \n * This version now allows input to alias output.\n */\n\n\n\n\nstatic\nlong RevInc(long a, long k)\n{\n   long j, m;\n\n   j = k; \n   m = 1L << (k-1);\n\n   while (j && (m & a)) {\n      a ^= m;\n      m >>= 1;\n      j--;\n   }\n   if (j) a ^= m;\n   return a;\n}\n\n\n\nstatic Vec<long> brc_mem[NTL_FFTMaxRoot+1];\n\nstatic\nvoid BitReverseCopy(long *A, const long *a, long k)\n{\n   long n = 1L << k;\n   long* rev;\n   long i, j;\n\n   rev = brc_mem[k].elts();\n   if (!rev) {\n      brc_mem[k].SetLength(n);\n      rev = brc_mem[k].elts();\n      for (i = 0, j = 0; i < n; i++, j = RevInc(j, k))\n         rev[i] = j;\n   }\n\n   for (i = 0; i < n; i++)\n      A[rev[i]] = a[i];\n}\n\nstatic\nvoid BitReverseCopy(unsigned long *A, const long *a, long k)\n{\n   long n = 1L << k;\n   long* rev;\n   long i, j;\n\n   rev = brc_mem[k].elts();\n   if (!rev) {\n      brc_mem[k].SetLength(n);\n      rev = brc_mem[k].elts();\n      for (i = 0, j = 0; i < n; i++, j = RevInc(j, k))\n         rev[i] = j;\n   }\n\n   for (i = 0; i < n; i++)\n      A[rev[i]] = a[i];\n}\n\n\n\nvoid FFT(long* A, const long* a, long k, long q, const long* root)\n// performs a 2^k-point convolution modulo q\n\n{\n   if (k <= 1) {\n      if (k == 0) {\n\t A[0] = a[0];\n\t return;\n      }\n      if (k == 1) {\n\t long a0 = AddMod(a[0], a[1], q);\n\t long a1 = SubMod(a[0], a[1], q);\n         A[0] = a0;\n         A[1] = a1;\n\t return;\n      }\n   }\n\n   // assume k > 1\n\n   \n\n   static Vec<long> wtab_store;\n   static Vec<mulmod_precon_t> wqinvtab_store;\n   static Vec<long> AA_store;\n\n   wtab_store.SetLength(1L << (k-2));\n   wqinvtab_store.SetLength(1L << (k-2));\n   AA_store.SetLength(1L << k);\n\n   long * NTL_RESTRICT wtab = wtab_store.elts();\n   mulmod_precon_t * NTL_RESTRICT wqinvtab = wqinvtab_store.elts();\n   long *AA = AA_store.elts();\n\n   double qinv = 1/((double) q);\n\n   wtab[0] = 1;\n   wqinvtab[0] = PrepMulModPrecon(1, q, qinv);\n\n\n   BitReverseCopy(AA, a, k);\n\n   long n = 1L << k;\n\n   long s, m, m_half, m_fourth, i, j, t, u, t1, u1, tt, tt1;\n\n   long w;\n   mulmod_precon_t wqinv;\n\n   // s = 1\n\n   for (i = 0; i < n; i += 2) {\n      t = AA[i + 1];\n      u = AA[i];\n      AA[i] = AddMod(u, t, q);\n      AA[i+1] = SubMod(u, t, q);\n   }\n\n   \n  \n   for (s = 2; s < k; s++) {\n      m = 1L << s;\n      m_half = 1L << (s-1);\n      m_fourth = 1L << (s-2);\n\n      w = root[s];\n      wqinv = PrepMulModPrecon(w, q, qinv);\n\n      // prepare wtab...\n\n      if (s == 2) {\n         wtab[1] = MulModPrecon(wtab[0], w, q, wqinv);\n         wqinvtab[1] = PrepMulModPrecon(wtab[1], q, qinv);\n      }\n      else {\n         // some software pipelining\n\n         i = m_half-1; j = m_fourth-1;\n         wtab[i-1] = wtab[j];\n         wqinvtab[i-1] = wqinvtab[j];\n         wtab[i] = MulModPrecon(wtab[i-1], w, q, wqinv);\n\n         i -= 2; j --;\n\n         for (; i >= 0; i -= 2, j --) {\n            long wp2 = wtab[i+2];\n            long wm1 = wtab[j];\n            wqinvtab[i+2] = PrepMulModPrecon(wp2, q, qinv);\n            wtab[i-1] = wm1;\n            wqinvtab[i-1] = wqinvtab[j];\n            wtab[i] = MulModPrecon(wm1, w, q, wqinv);\n         }\n\n         wqinvtab[1] = PrepMulModPrecon(wtab[1], q, qinv);\n      }\n\n      for (i = 0; i < n; i+= m) {\n\n         long * NTL_RESTRICT AA0 = &AA[i];\n         long * NTL_RESTRICT AA1 = &AA[i + m_half];\n          \n         t = AA1[0];\n         u = AA0[0];\n         t1 = MulModPrecon(AA1[1], w, q, wqinv);\n         u1 = AA0[1];\n\n         for (j = 0; j < m_half-2; j += 2) {\n            long a02 = AA0[j+2];\n            long a03 = AA0[j+3];\n            long a12 = AA1[j+2];\n            long a13 = AA1[j+3];\n            long w2 = wtab[j+2];\n            long w3 = wtab[j+3];\n            mulmod_precon_t wqi2 = wqinvtab[j+2];\n            mulmod_precon_t wqi3 = wqinvtab[j+3];\n\n            tt = MulModPrecon(a12, w2, q, wqi2);\n            long b00 = AddMod(u, t, q);\n            long b10 = SubMod(u, t, q);\n            t = tt;\n            u = a02;\n\n            tt1 = MulModPrecon(a13, w3, q, wqi3);\n            long b01 = AddMod(u1, t1, q);\n            long b11 = SubMod(u1, t1, q);\n            t1 = tt1;\n            u1 = a03;\n\n            AA0[j] = b00;\n            AA1[j] = b10;\n            AA0[j+1] = b01;\n            AA1[j+1] = b11;\n         }\n\n\n         AA0[j] = AddMod(u, t, q);\n         AA1[j] = SubMod(u, t, q);\n         AA0[j + 1] = AddMod(u1, t1, q);\n         AA1[j + 1] = SubMod(u1, t1, q);\n      }\n   }\n\n\n   // s == k...special case\n\n   m = 1L << s;\n   m_half = 1L << (s-1);\n   m_fourth = 1L << (s-2);\n\n\n   w = root[s];\n   wqinv = PrepMulModPrecon(w, q, qinv);\n\n   // j = 0, 1\n\n   t = AA[m_half];\n   u = AA[0];\n   t1 = MulModPrecon(AA[1+ m_half], w, q, wqinv);\n   u1 = AA[1];\n\n   A[0] = AddMod(u, t, q);\n   A[m_half] = SubMod(u, t, q);\n   A[1] = AddMod(u1, t1, q);\n   A[1 + m_half] = SubMod(u1, t1, q);\n\n   for (j = 2; j < m_half; j += 2) {\n      t = MulModPrecon(AA[j + m_half], wtab[j >> 1], q, wqinvtab[j >> 1]);\n      u = AA[j];\n      t1 = MulModPrecon(AA[j + 1+ m_half], wtab[j >> 1], q, \n                        wqinvtab[j >> 1]);\n      t1 = MulModPrecon(t1, w, q, wqinv);\n      u1 = AA[j + 1];\n\n      A[j] = AddMod(u, t, q);\n      A[j + m_half] = SubMod(u, t, q);\n      A[j + 1] = AddMod(u1, t1, q);\n      A[j + 1 + m_half] = SubMod(u1, t1, q);\n     \n   }\n}\n\n\n\n#if (!defined(NTL_FFT_LAZYMUL) || defined(NTL_SINGLE_MUL) || \\\n     (!defined(NTL_SPMM_ULL) && !defined(NTL_SPMM_ASM)))\n\n// FFT with precomputed tables \n\n#define NTL_PIPELINE (1)\n\nstatic\nvoid PrecompFFTMultipliers(long k, long q, const long *root, FFTMultipliers& tab)\n{\n   if (k < 1) Error(\"PrecompFFTMultipliers: bad input\");\n\n   if (k <= tab.MaxK) return;\n\n   tab.wtab_precomp.SetLength(k+1);\n   tab.wqinvtab_precomp.SetLength(k+1);\n\n   double qinv = 1/((double) q);\n\n   if (tab.MaxK == -1) {\n      tab.wtab_precomp[1].SetLength(1);\n      tab.wqinvtab_precomp[1].SetLength(1);\n      tab.wtab_precomp[1][0] = 1;\n      tab.wqinvtab_precomp[1][0] = PrepMulModPrecon(1, q, qinv);\n      tab.MaxK = 1;\n   }\n\n   for (long s = tab.MaxK+1; s <= k; s++) {\n      tab.wtab_precomp[s].SetLength(1L << (s-1));\n      tab.wqinvtab_precomp[s].SetLength(1L << (s-1));\n\n      long m = 1L << s;\n      long m_half = 1L << (s-1);\n      long m_fourth = 1L << (s-2);\n\n      long *wtab_last = tab.wtab_precomp[s-1].elts();\n      mulmod_precon_t *wqinvtab_last = tab.wqinvtab_precomp[s-1].elts();\n\n      long *wtab = tab.wtab_precomp[s].elts();\n      mulmod_precon_t *wqinvtab = tab.wqinvtab_precomp[s].elts();\n\n      for (long i = 0; i < m_fourth; i++) {\n         wtab[i] = wtab_last[i];\n         wqinvtab[i] = wqinvtab_last[i];\n      } \n\n      long w = root[s];\n      mulmod_precon_t wqinv = PrepMulModPrecon(w, q, qinv);\n\n      // prepare wtab...\n\n      if (s == 2) {\n         wtab[1] = MulModPrecon(wtab[0], w, q, wqinv);\n         wqinvtab[1] = PrepMulModPrecon(wtab[1], q, qinv);\n      }\n      else {\n         // some software pipelining\n         long i, j;\n\n         i = m_half-1; j = m_fourth-1;\n         wtab[i-1] = wtab[j];\n         wqinvtab[i-1] = wqinvtab[j];\n         wtab[i] = MulModPrecon(wtab[i-1], w, q, wqinv);\n\n         i -= 2; j --;\n\n         for (; i >= 0; i -= 2, j --) {\n            long wp2 = wtab[i+2];\n            long wm1 = wtab[j];\n            wqinvtab[i+2] = PrepMulModPrecon(wp2, q, qinv);\n            wtab[i-1] = wm1;\n            wqinvtab[i-1] = wqinvtab[j];\n            wtab[i] = MulModPrecon(wm1, w, q, wqinv);\n         }\n\n         wqinvtab[1] = PrepMulModPrecon(wtab[1], q, qinv);\n      }\n   }\n\n   tab.MaxK = k;\n}\n\n\n\nvoid FFT(long* A, const long* a, long k, long q, const long* root, FFTMultipliers& tab)\n// performs a 2^k-point convolution modulo q\n\n{\n   if (k <= 1) {\n      if (k == 0) {\n\t A[0] = a[0];\n\t return;\n      }\n      if (k == 1) {\n\t long a0 = AddMod(a[0], a[1], q);\n\t long a1 = SubMod(a[0], a[1], q);\n         A[0] = a0;\n         A[1] = a1;\n\t return;\n      }\n   }\n\n\n\n   // assume k > 1\n\n   if (k > tab.MaxK) PrecompFFTMultipliers(k, q, root, tab);\n\n   static Vec<long> AA_store;\n   AA_store.SetLength(1L << k);\n   long *AA = AA_store.elts();\n\n   BitReverseCopy(AA, a, k);\n\n   long n = 1L << k;\n\n   long s, m, m_half, m_fourth, i, j, t, u, t1, u1, tt, tt1;\n\n   // s = 1\n\n   for (i = 0; i < n; i += 2) {\n      t = AA[i + 1];\n      u = AA[i];\n      AA[i] = AddMod(u, t, q);\n      AA[i+1] = SubMod(u, t, q);\n   }\n   \n  \n   for (s = 2; s < k; s++) {\n      m = 1L << s;\n      m_half = 1L << (s-1);\n      m_fourth = 1L << (s-2);\n\n      const long* wtab = tab.wtab_precomp[s].elts();\n      const mulmod_precon_t *wqinvtab = tab.wqinvtab_precomp[s].elts();\n\n      for (i = 0; i < n; i+= m) {\n\n         long *AA0 = &AA[i];\n         long *AA1 = &AA[i + m_half];\n\n#if (NTL_PIPELINE)\n\n// pipelining: seems to be faster\n          \n         t = AA1[0];\n         u = AA0[0];\n         t1 = MulModPrecon(AA1[1], wtab[1], q, wqinvtab[1]);\n         u1 = AA0[1];\n\n         for (j = 0; j < m_half-2; j += 2) {\n            long a02 = AA0[j+2];\n            long a03 = AA0[j+3];\n            long a12 = AA1[j+2];\n            long a13 = AA1[j+3];\n            long w2 = wtab[j+2];\n            long w3 = wtab[j+3];\n            mulmod_precon_t wqi2 = wqinvtab[j+2];\n            mulmod_precon_t wqi3 = wqinvtab[j+3];\n\n            tt = MulModPrecon(a12, w2, q, wqi2);\n            long b00 = AddMod(u, t, q);\n            long b10 = SubMod(u, t, q);\n\n            tt1 = MulModPrecon(a13, w3, q, wqi3);\n            long b01 = AddMod(u1, t1, q);\n            long b11 = SubMod(u1, t1, q);\n\n            AA0[j] = b00;\n            AA1[j] = b10;\n            AA0[j+1] = b01;\n            AA1[j+1] = b11;\n\n\n            t = tt;\n            u = a02;\n            t1 = tt1;\n            u1 = a03;\n         }\n\n\n         AA0[j] = AddMod(u, t, q);\n         AA1[j] = SubMod(u, t, q);\n         AA0[j + 1] = AddMod(u1, t1, q);\n         AA1[j + 1] = SubMod(u1, t1, q);\n      }\n#else\n         for (j = 0; j < m_half; j += 2) {\n            const long a00 = AA0[j];\n            const long a01 = AA0[j+1];\n            const long a10 = AA1[j];\n            const long a11 = AA1[j+1];\n\n            const long w0 = wtab[j];\n            const long w1 = wtab[j+1];\n            const mulmod_precon_t wqi0 = wqinvtab[j];\n            const mulmod_precon_t wqi1 = wqinvtab[j+1];\n\n            const long tt = MulModPrecon(a10, w0, q, wqi0);\n            const long uu = a00;\n            const long b00 = AddMod(uu, tt, q); \n            const long b10 = SubMod(uu, tt, q);\n\n            const long tt1 = MulModPrecon(a11, w1, q, wqi1);\n            const long uu1 = a01;\n            const long b01 = AddMod(uu1, tt1, q); \n            const long b11 = SubMod(uu1, tt1, q);\n\n            AA0[j] = b00;\n            AA0[j+1] = b01;\n            AA1[j] = b10;\n            AA1[j+1] = b11;\n         }\n      }\n#endif\n   }\n\n\n   // s == k, special case\n   {\n      m = 1L << s;\n      m_half = 1L << (s-1);\n      m_fourth = 1L << (s-2);\n\n      const long* wtab = tab.wtab_precomp[s].elts();\n      const mulmod_precon_t *wqinvtab = tab.wqinvtab_precomp[s].elts();\n\n      for (i = 0; i < n; i+= m) {\n\n         long *AA0 = &AA[i];\n         long *AA1 = &AA[i + m_half];\n         long *A0 = &A[i];\n         long *A1 = &A[i + m_half];\n\n#if (NTL_PIPELINE)\n\n// pipelining: seems to be faster\n          \n         t = AA1[0];\n         u = AA0[0];\n         t1 = MulModPrecon(AA1[1], wtab[1], q, wqinvtab[1]);\n         u1 = AA0[1];\n\n         for (j = 0; j < m_half-2; j += 2) {\n            long a02 = AA0[j+2];\n            long a03 = AA0[j+3];\n            long a12 = AA1[j+2];\n            long a13 = AA1[j+3];\n            long w2 = wtab[j+2];\n            long w3 = wtab[j+3];\n            mulmod_precon_t wqi2 = wqinvtab[j+2];\n            mulmod_precon_t wqi3 = wqinvtab[j+3];\n\n            tt = MulModPrecon(a12, w2, q, wqi2);\n            long b00 = AddMod(u, t, q);\n            long b10 = SubMod(u, t, q);\n\n            tt1 = MulModPrecon(a13, w3, q, wqi3);\n            long b01 = AddMod(u1, t1, q);\n            long b11 = SubMod(u1, t1, q);\n\n            A0[j] = b00;\n            A1[j] = b10;\n            A0[j+1] = b01;\n            A1[j+1] = b11;\n\n\n            t = tt;\n            u = a02;\n            t1 = tt1;\n            u1 = a03;\n         }\n\n\n         A0[j] = AddMod(u, t, q);\n         A1[j] = SubMod(u, t, q);\n         A0[j + 1] = AddMod(u1, t1, q);\n         A1[j + 1] = SubMod(u1, t1, q);\n      }\n#else\n         for (j = 0; j < m_half; j += 2) {\n            const long a00 = AA0[j];\n            const long a01 = AA0[j+1];\n            const long a10 = AA1[j];\n            const long a11 = AA1[j+1];\n\n            const long w0 = wtab[j];\n            const long w1 = wtab[j+1];\n            const mulmod_precon_t wqi0 = wqinvtab[j];\n            const mulmod_precon_t wqi1 = wqinvtab[j+1];\n\n            const long tt = MulModPrecon(a10, w0, q, wqi0);\n            const long uu = a00;\n            const long b00 = AddMod(uu, tt, q); \n            const long b10 = SubMod(uu, tt, q);\n\n            const long tt1 = MulModPrecon(a11, w1, q, wqi1);\n            const long uu1 = a01;\n            const long b01 = AddMod(uu1, tt1, q); \n            const long b11 = SubMod(uu1, tt1, q);\n\n            A0[j] = b00;\n            A0[j+1] = b01;\n            A1[j] = b10;\n            A1[j+1] = b11;\n         }\n      }\n#endif\n   }\n\n}\n\n\n#else\n\n// FFT with precomputed tables and David Harvey's lazy multiplication\n// strategy.\n\n\nstatic inline \nunsigned long LazyPrepMulModPrecon(long b, long n, double ninv)\n{\n   unsigned long q, r;\n\n   q = (long) ( (((double) b) * NTL_SP_FBOUND) * ninv ); \n   r = (((unsigned long) b) << NTL_SP_NBITS ) - q * ((unsigned long) n);\n\n   if (r >> (NTL_BITS_PER_LONG-1)) {\n      q--;\n      r += n;\n   }\n   else if (((long) r) >= n) {\n      q++;\n      r -=n;\n   }\n\n   unsigned long res = q << (NTL_BITS_PER_LONG - NTL_SP_NBITS);\n   long qq, rr;\n\n   rr = MulDivRem(qq, (long) r, 4, n, 4*ninv);\n\n   res = res + (qq << (NTL_BITS_PER_LONG - NTL_SP_NBITS-2));\n\n   return res;\n}\n\nstatic inline \nunsigned long LazyMulModPrecon(unsigned long a, unsigned long b, \n                               unsigned long n, unsigned long bninv)\n{\n   unsigned long q = MulHiUL(a, bninv);\n   unsigned long res = a*b - q*n;\n   return res;\n}\n\n\nstatic inline \nunsigned long LazyReduce(unsigned long a, unsigned long q)\n{\n  unsigned long res;\n#if (NTL_ARITH_RIGHT_SHIFT && defined(NTL_AVOID_BRANCHING) && !defined(NTL_CLEAN_INT))\n  res = a - q;\n  res  += (((long) res) >> (NTL_BITS_PER_LONG-1)) & q; \n#elif (defined(NTL_AVOID_BRANCHING))\n  res = a - q;\n  res  += (-(res >> (NTL_BITS_PER_LONG-1))) & q; \n#else\n  if (a >= q)\n    res = a - q;\n  else\n    res = a;\n#endif\n\n  return res;\n}\n\n\nstatic\nvoid LazyPrecompFFTMultipliers(long k, long q, const long *root, FFTMultipliers& tab)\n{\n   if (k < 1) Error(\"LazyPrecompFFTMultipliers: bad input\");\n\n   if (k <= tab.MaxK) return;\n\n   tab.wtab_precomp.SetLength(k+1);\n   tab.wqinvtab_precomp.SetLength(k+1);\n\n   double qinv = 1/((double) q);\n\n   if (tab.MaxK == -1) {\n      tab.wtab_precomp[1].SetLength(1);\n      tab.wqinvtab_precomp[1].SetLength(1);\n      tab.wtab_precomp[1][0] = 1;\n      tab.wqinvtab_precomp[1][0] = LazyPrepMulModPrecon(1, q, qinv);\n      tab.MaxK = 1;\n   }\n\n   for (long s = tab.MaxK+1; s <= k; s++) {\n      tab.wtab_precomp[s].SetLength(1L << (s-1));\n      tab.wqinvtab_precomp[s].SetLength(1L << (s-1));\n\n      long m = 1L << s;\n      long m_half = 1L << (s-1);\n      long m_fourth = 1L << (s-2);\n\n      long *wtab_last = tab.wtab_precomp[s-1].elts();\n      mulmod_precon_t *wqinvtab_last = tab.wqinvtab_precomp[s-1].elts();\n\n      long *wtab = tab.wtab_precomp[s].elts();\n      mulmod_precon_t *wqinvtab = tab.wqinvtab_precomp[s].elts();\n\n      for (long i = 0; i < m_fourth; i++) {\n         wtab[i] = wtab_last[i];\n         wqinvtab[i] = wqinvtab_last[i];\n      } \n\n      long w = root[s];\n      mulmod_precon_t wqinv = LazyPrepMulModPrecon(w, q, qinv);\n\n      // prepare wtab...\n\n      if (s == 2) {\n         wtab[1] = LazyReduce(LazyMulModPrecon(wtab[0], w, q, wqinv), q);\n         wqinvtab[1] = LazyPrepMulModPrecon(wtab[1], q, qinv);\n      }\n      else {\n         // some software pipelining\n         long i, j;\n\n         i = m_half-1; j = m_fourth-1;\n         wtab[i-1] = wtab[j];\n         wqinvtab[i-1] = wqinvtab[j];\n         wtab[i] = LazyReduce(LazyMulModPrecon(wtab[i-1], w, q, wqinv), q);\n\n         i -= 2; j --;\n\n         for (; i >= 0; i -= 2, j --) {\n            long wp2 = wtab[i+2];\n            long wm1 = wtab[j];\n            wqinvtab[i+2] = LazyPrepMulModPrecon(wp2, q, qinv);\n            wtab[i-1] = wm1;\n            wqinvtab[i-1] = wqinvtab[j];\n            wtab[i] = LazyReduce(LazyMulModPrecon(wm1, w, q, wqinv), q);\n         }\n\n         wqinvtab[1] = LazyPrepMulModPrecon(wtab[1], q, qinv);\n      }\n   }\n\n   tab.MaxK = k;\n}\n\n\n\n\nvoid FFT(long* A, const long* a, long k, long q, const long* root, FFTMultipliers& tab)\n\n// performs a 2^k-point convolution modulo q\n\n{\n   if (k <= 1) {\n      if (k == 0) {\n\t A[0] = a[0];\n\t return;\n      }\n      if (k == 1) {\n\t long a0 = AddMod(a[0], a[1], q);\n\t long a1 = SubMod(a[0], a[1], q);\n         A[0] = a0;\n         A[1] = a1;\n\t return;\n      }\n   }\n\n   // assume k > 1\n\n   if (k > tab.MaxK) LazyPrecompFFTMultipliers(k, q, root, tab);\n\n   static Vec<unsigned long> AA_store;\n   AA_store.SetLength(1L << k);\n   unsigned long *AA = AA_store.elts();\n\n\n\n   BitReverseCopy(AA, a, k);\n\n   long n = 1L << k;\n\n\n   /* we work with redundant representations, in the range [0, 4q) */\n\n\n\n   long s, m, m_half, m_fourth, i, j; \n   unsigned long t, u, t1, u1;\n\n   long two_q = 2 * q; \n\n   // s = 1\n\n   for (i = 0; i < n; i += 2) {\n      t = AA[i + 1];\n      u = AA[i];\n      AA[i] = u + t;\n      AA[i+1] = u - t + q;\n   }\n\n\n   // s = 2\n\n   {\n      const long * NTL_RESTRICT wtab = tab.wtab_precomp[2].elts();\n      const mulmod_precon_t * NTL_RESTRICT wqinvtab = tab.wqinvtab_precomp[2].elts();\n\n      for (i = 0; i < n; i += 4) {\n\n         unsigned long * NTL_RESTRICT AA0 = &AA[i];\n         unsigned long * NTL_RESTRICT AA1 = &AA[i + 2];\n\n         {\n            const long w1 = wtab[0];\n            const mulmod_precon_t wqi1 = wqinvtab[0];\n            const unsigned long a11 = AA1[0];\n            const unsigned long a01 = AA0[0];\n\n            const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\n            const unsigned long uu1 = LazyReduce(a01, two_q);\n            const unsigned long b01 = uu1 + tt1; \n            const unsigned long b11 = uu1 - tt1 + two_q;\n\n            AA0[0] = b01;\n            AA1[0] = b11;\n         }\n         {\n            const long w1 = wtab[1];\n            const mulmod_precon_t wqi1 = wqinvtab[1];\n            const unsigned long a11 = AA1[1];\n            const unsigned long a01 = AA0[1];\n\n            const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\n            const unsigned long uu1 = LazyReduce(a01, two_q);\n            const unsigned long b01 = uu1 + tt1; \n            const unsigned long b11 = uu1 - tt1 + two_q;\n\n            AA0[1] = b01;\n            AA1[1] = b11;\n         }\n      }\n   }\n\n\n   //  s = 3..k\n\n   for (s = 3; s <= k; s++) {\n      m = 1L << s;\n      m_half = 1L << (s-1);\n      m_fourth = 1L << (s-2);\n\n      const long* NTL_RESTRICT wtab = tab.wtab_precomp[s].elts();\n      const mulmod_precon_t * NTL_RESTRICT wqinvtab = tab.wqinvtab_precomp[s].elts();\n\n      for (i = 0; i < n; i += m) {\n\n         unsigned long * NTL_RESTRICT AA0 = &AA[i];\n         unsigned long * NTL_RESTRICT AA1 = &AA[i + m_half];\n\n         for (j = 0; j < m_half; j += 4) {\n            {\n               const long w1 = wtab[j+0];\n               const mulmod_precon_t wqi1 = wqinvtab[j+0];\n               const unsigned long a11 = AA1[j+0];\n               const unsigned long a01 = AA0[j+0];\n\n               const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\n               const unsigned long uu1 = LazyReduce(a01, two_q);\n               const unsigned long b01 = uu1 + tt1; \n               const unsigned long b11 = uu1 - tt1 + two_q;\n\n               AA0[j+0] = b01;\n               AA1[j+0] = b11;\n            }\n            {\n               const long w1 = wtab[j+1];\n               const mulmod_precon_t wqi1 = wqinvtab[j+1];\n               const unsigned long a11 = AA1[j+1];\n               const unsigned long a01 = AA0[j+1];\n\n               const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\n               const unsigned long uu1 = LazyReduce(a01, two_q);\n               const unsigned long b01 = uu1 + tt1; \n               const unsigned long b11 = uu1 - tt1 + two_q;\n\n               AA0[j+1] = b01;\n               AA1[j+1] = b11;\n            }\n            {\n               const long w1 = wtab[j+2];\n               const mulmod_precon_t wqi1 = wqinvtab[j+2];\n               const unsigned long a11 = AA1[j+2];\n               const unsigned long a01 = AA0[j+2];\n\n               const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\n               const unsigned long uu1 = LazyReduce(a01, two_q);\n               const unsigned long b01 = uu1 + tt1; \n               const unsigned long b11 = uu1 - tt1 + two_q;\n\n               AA0[j+2] = b01;\n               AA1[j+2] = b11;\n            }\n            {\n               const long w1 = wtab[j+3];\n               const mulmod_precon_t wqi1 = wqinvtab[j+3];\n               const unsigned long a11 = AA1[j+3];\n               const unsigned long a01 = AA0[j+3];\n\n               const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\n               const unsigned long uu1 = LazyReduce(a01, two_q);\n               const unsigned long b01 = uu1 + tt1; \n               const unsigned long b11 = uu1 - tt1 + two_q;\n\n               AA0[j+3] = b01;\n               AA1[j+3] = b11;\n            }\n         }\n      }\n   }\n\n   /* need to reduce redundant representations */\n\n   for (i = 0; i < n; i++) {\n      unsigned long tmp = LazyReduce(AA[i], two_q);\n      A[i] = LazyReduce(tmp, q);\n   }\n}\n\n\n#endif\n\n\n\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "0ef1a2247b6819ef39826994ebce70d42e4efd19", "size": 25776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ntl/FFT.cpp", "max_stars_repo_name": "av-elier/fast-exponentiation-algs", "max_stars_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-17T20:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T19:52:14.000Z", "max_issues_repo_path": "src/ntl/FFT.cpp", "max_issues_repo_name": "av-elier/fast-exponentiation-algs", "max_issues_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ntl/FFT.cpp", "max_forks_repo_name": "av-elier/fast-exponentiation-algs", "max_forks_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_forks_repo_licenses": ["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.1174887892, "max_line_length": 87, "alphanum_fraction": 0.4872749845, "num_tokens": 9094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5365382283648847}}
{"text": "#ifndef ROSE499_TYPES_HPP\n#define ROSE499_TYPES_HPP\n\n#include <Eigen/Core>\n#include <iostream>\n\nnamespace SimulatorTypes\n{\n    typedef long double ValueType;\n    typedef Eigen::Matrix<ValueType, Eigen::Dynamic, Eigen::Dynamic> MatrixXT;\n    typedef Eigen::Matrix<ValueType, Eigen::Dynamic, 1> VectorXT;\n    typedef Eigen::Matrix<ValueType, 2, 1> Vector2T;\n};\n\n#endif\n", "meta": {"hexsha": "8408ceac066c3e8b6092257a760b5578f6b6f38e", "size": 367, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "simulator/include/rose499/types.hpp", "max_stars_repo_name": "rollends/SE499", "max_stars_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulator/include/rose499/types.hpp", "max_issues_repo_name": "rollends/SE499", "max_issues_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulator/include/rose499/types.hpp", "max_forks_repo_name": "rollends/SE499", "max_forks_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_forks_repo_licenses": ["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.9375, "max_line_length": 78, "alphanum_fraction": 0.7493188011, "num_tokens": 92, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5365303854316598}}
{"text": "/* test_non_central_chi_squared_distribution.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Copyright Thijs van den Berg 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 * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/non_central_chi_squared_distribution.hpp>\r\n#include <limits>\r\n\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::non_central_chi_squared_distribution<>\r\n#define BOOST_RANDOM_ARG1 k\r\n#define BOOST_RANDOM_ARG2 lambda\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1.0\r\n#define BOOST_RANDOM_ARG2_DEFAULT 1.0\r\n#define BOOST_RANDOM_ARG1_VALUE 4.0\r\n#define BOOST_RANDOM_ARG2_VALUE 42.0\r\n\r\n#define BOOST_RANDOM_DIST0_MIN 0\r\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST1_MIN 0\r\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST2_MIN 0\r\n#define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<double>::infinity)()\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS\r\n#define BOOST_RANDOM_TEST1_MIN 0.0\r\n#define BOOST_RANDOM_TEST1_MAX 100.0\r\n\r\n#define BOOST_RANDOM_TEST2_PARAMS (10000.0)\r\n#define BOOST_RANDOM_TEST2_MIN 100.0\r\n\r\n#include \"test_distribution.ipp\"\r\n", "meta": {"hexsha": "fd77406fafcb48b8f080ea3135855c1e8166d548", "size": 1262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_non_central_chi_squared_distribution.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/random/test/test_non_central_chi_squared_distribution.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/random/test/test_non_central_chi_squared_distribution.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.55, "max_line_length": 88, "alphanum_fraction": 0.793977813, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745834049793373, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5365089955569706}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n#include <statistics.hpp>\n#include <date_parser.hpp>\n\n/*\n * XXX al -\n *\n * Unfortunately, Boost.Test does not have a direct support for parametrized test\n * fixture, as does GoogleTests. This would have allowed us to\n * write a generic set of test for the possible multiple implementation of the\n * statistics engine.\n */\nnamespace\n{\n\tstruct fixture {\n\t\tfixture() :\n\t\t\trecords(this->generic_map)\n\t\t{\n\t\t\tthis->records.emplace(this->parser(\"2018-01-01\").second, 1.0);\n\t\t\tthis->records.emplace(this->parser(\"2018-01-02\").second, 2.0);\n\t\t\tthis->records.emplace(this->parser(\"2018-01-03\").second, 3.0);\n\t\t\tthis->records.emplace(this->parser(\"2018-01-04\").second, 4.0);\n\t\t\tthis->records.emplace(this->parser(\"2018-01-05\").second, 5.0);\n\t\t}\n\n\t\tbpi::date_parser parser;\n\n\t\tbpi::records::map generic_map;\n\t\tbpi::records::map_t& records;\n\t};\n}\n\nBOOST_FIXTURE_TEST_SUITE( statistics, fixture )\n\nBOOST_AUTO_TEST_CASE( statistics )\n{\n#if 0\n{\n    \"lowest\": {\n        \"price\": \"1\",\n        \"date\": \"2018-01-01\"\n    },\n    \"highest\": {\n        \"price\": \"5\",\n        \"date\": \"2018-01-05\"\n    },\n    \"stddev\": \"1.58113883008418966598\",\n    \"average\": \"3\",\n    \"median\": \"3\",\n    \"sample_size\": \"5\"\n}\n#endif\n\n\tbpi::statistics::engine engine(this->records);\n\n\tauto results = engine.run();\n\n\tBOOST_CHECK(results.get<int>(\"sample_size\") == 5);\n\n\tBOOST_CHECK_CLOSE(results.get<double>(\"stddev\"), 1.581, 0.01);\n\tBOOST_CHECK_CLOSE(results.get<double>(\"average\"), 3.0, 0.01);\n\tBOOST_CHECK_CLOSE(results.get<double>(\"median\"), 3.0, 0.01);\n\n\tauto lowest = results.get_child(\"lowest\");\n\tBOOST_CHECK_CLOSE(lowest.get<double>(\"price\"), 1.0, 0.01);\n\tBOOST_CHECK(lowest.get<std::string>(\"date\") == \"2018-01-01\");\n\n\tauto highest = results.get_child(\"highest\");\n\tBOOST_CHECK_CLOSE(highest.get<double>(\"price\"), 5.0, 0.01);\n\tBOOST_CHECK(highest.get<std::string>(\"date\") == \"2018-01-05\");\n}\n\nBOOST_AUTO_TEST_CASE( median )\n{\n\t// Even number of records\n\tthis->records.emplace(this->parser(\"2018-01-06\").second, 6.0);\n\n\tbpi::statistics::engine engine(this->records);\n\n\tauto results = engine.run();\n\n\tBOOST_CHECK_CLOSE(results.get<double>(\"median\"), 3.5, 0.01);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "387b2846d07be21239a1ae0909a9608483f64b35", "size": 2279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/statistics.cpp", "max_stars_repo_name": "aerilon/bpistats", "max_stars_repo_head_hexsha": "2c53509cea3a84d87c0ae97c3622c6175fe5fd8c", "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": "tests/statistics.cpp", "max_issues_repo_name": "aerilon/bpistats", "max_issues_repo_head_hexsha": "2c53509cea3a84d87c0ae97c3622c6175fe5fd8c", "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": "tests/statistics.cpp", "max_forks_repo_name": "aerilon/bpistats", "max_forks_repo_head_hexsha": "2c53509cea3a84d87c0ae97c3622c6175fe5fd8c", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T06:48:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T06:48:33.000Z", "avg_line_length": 25.3222222222, "max_line_length": 81, "alphanum_fraction": 0.6726634489, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.536508988348502}}
{"text": "#pragma once\n\n#include <Discregrid/common.hpp>\n#include <Eigen/Dense>\n\nclass GaussQuadrature\n{\npublic:\n\n    using Integrand = std::function<Discregrid::Real(Discregrid::Vector3r const&)>;\n    using Domain = Discregrid::AlignedBox3r;\n\n    static Discregrid::Real integrate(Integrand integrand, Domain const& domain, unsigned int p);\n};\n\n\n\n", "meta": {"hexsha": "092067546b5942c97c2a1138fe9cf83ebb583588", "size": 338, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmd/generate_density_map/gauss_quadrature.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/gauss_quadrature.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/gauss_quadrature.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": 18.7777777778, "max_line_length": 97, "alphanum_fraction": 0.7396449704, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5365089736052632}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2001 - 2021 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: Wolfgang Bangerth, University of Heidelberg, 2001 \n */ \n\n\n\n// \u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u7a0b\u5e8f\u4ee5\u4e00\u4e2a\u76f8\u5f53\u957f\u7684\u5305\u542b\u6587\u4ef6\u5217\u8868\u5f00\u59cb\uff0c\u4f60\u73b0\u5728\u53ef\u80fd\u5df2\u7ecf\u4e60\u60ef\u4e86\u3002\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/table_handler.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/sparse_matrix.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/dofs/dof_handler.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/fe/mapping_q.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\n// \u53ea\u6709\u8fd9\u4e00\u6761\u662f\u65b0\u7684\uff1a\u5b83\u58f0\u660e\u4e86\u4e00\u4e2a\u52a8\u6001\u7a00\u758f\u6a21\u5f0f\uff08DynamicSparsityPattern\uff09\u7c7b\uff0c\u6211\u4eec\u5c06\u5728\u4e0b\u9762\u8fdb\u4e00\u6b65\u4f7f\u7528\u548c\u89e3\u91ca\u3002\n\n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n\n// \u6211\u4eec\u5c06\u4f7f\u7528C++\u6807\u51c6\u5e93\u4e2d\u7684 std::find \u7b97\u6cd5\uff0c\u6240\u4ee5\u6211\u4eec\u5fc5\u987b\u5305\u62ec\u4ee5\u4e0b\u6587\u4ef6\u6765\u58f0\u660e\u5b83\u3002\n\n#include <algorithm> \n#include <iostream> \n#include <iomanip> \n#include <cmath> \n\n// \u6700\u540e\u4e00\u6b65\u548c\u4ee5\u524d\u6240\u6709\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\n\nnamespace Step11 \n{ \n  using namespace dealii; \n\n// \u7136\u540e\u6211\u4eec\u58f0\u660e\u4e00\u4e2a\u8868\u793a\u62c9\u666e\u62c9\u65af\u95ee\u9898\u89e3\u51b3\u65b9\u6848\u7684\u7c7b\u3002\u7531\u4e8e\u8fd9\u4e2a\u4f8b\u5b50\u7a0b\u5e8f\u662f\u57fa\u4e8e step-5 \uff0c\u8fd9\u4e2a\u7c7b\u770b\u8d77\u6765\u76f8\u5f53\u76f8\u540c\uff0c\u552f\u4e00\u7684\u7ed3\u6784\u533a\u522b\u662f\u51fd\u6570 <code>assemble_system</code> now calls <code>solve</code> \u672c\u8eab\uff0c\u56e0\u6b64\u88ab\u79f0\u4e3a <code>assemble_and_solve</code> \uff0c\u800c\u4e14\u8f93\u51fa\u51fd\u6570\u88ab\u5220\u9664\uff0c\u56e0\u4e3a\u89e3\u51fd\u6570\u975e\u5e38\u65e0\u804a\uff0c\u4e0d\u503c\u5f97\u67e5\u770b\u3002\n\n// \u5176\u4ed6\u552f\u4e00\u503c\u5f97\u6ce8\u610f\u7684\u53d8\u5316\u662f\uff0c\u6784\u9020\u51fd\u6570\u53d6\u4e00\u4e2a\u503c\uff0c\u4ee3\u8868\u4ee5\u540e\u8981\u4f7f\u7528\u7684\u6620\u5c04\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\uff0c\u800c\u4e14\u5b83\u8fd8\u6709\u4e00\u4e2a\u6210\u5458\u53d8\u91cf\uff0c\u6b63\u597d\u4ee3\u8868\u8fd9\u4e2a\u6620\u5c04\u3002\u4e00\u822c\u6765\u8bf4\uff0c\u8fd9\u4e2a\u53d8\u91cf\u5728\u5b9e\u9645\u5e94\u7528\u4e2d\u4f1a\u51fa\u73b0\u5728\u58f0\u660e\u6216\u4f7f\u7528\u6709\u9650\u5143\u7684\u76f8\u540c\u5730\u65b9\u3002\n\n  template <int dim> \n  class LaplaceProblem \n  { \n  public: \n    LaplaceProblem(const unsigned int mapping_degree); \n    void run(); \n\n  private: \n    void setup_system(); \n    void assemble_and_solve(); \n    void solve(); \n    void write_high_order_mesh(const unsigned cycle); \n\n    Triangulation<dim> triangulation; \n    FE_Q<dim>          fe; \n    DoFHandler<dim>    dof_handler; \n    MappingQ<dim>      mapping; \n\n    SparsityPattern           sparsity_pattern; \n    SparseMatrix<double>      system_matrix; \n    AffineConstraints<double> mean_value_constraints; \n\n    Vector<double> solution; \n    Vector<double> system_rhs; \n\n    TableHandler output_table; \n  }; \n\n// \u6784\u5efa\u8fd9\u6837\u4e00\u4e2a\u5bf9\u8c61\uff0c\u901a\u8fc7\u521d\u59cb\u5316\u53d8\u91cf\u3002\u8fd9\u91cc\uff0c\u6211\u4eec\u4f7f\u7528\u7ebf\u6027\u6709\u9650\u5143\uff08 <code>fe</code> \u53d8\u91cf\u7684\u53c2\u6570\u8868\u793a\u591a\u9879\u5f0f\u7684\u5ea6\u6570\uff09\uff0c\u4ee5\u53ca\u7ed9\u5b9a\u9636\u6570\u7684\u6620\u5c04\u3002\u5c06\u6211\u4eec\u8981\u505a\u7684\u4e8b\u60c5\u6253\u5370\u5230\u5c4f\u5e55\u4e0a\u3002\n\n  template <int dim> \n  LaplaceProblem<dim>::LaplaceProblem(const unsigned int mapping_degree) \n    : fe(1) \n    , dof_handler(triangulation) \n    , mapping(mapping_degree) \n  { \n    std::cout << \"Using mapping with degree \" << mapping_degree << \":\" \n              << std::endl \n              << \"============================\" << std::endl; \n  } \n\n// \u7b2c\u4e00\u4e2a\u4efb\u52a1\u662f\u4e3a\u8fd9\u4e2a\u95ee\u9898\u8bbe\u7f6e\u53d8\u91cf\u3002\u8fd9\u5305\u62ec\u751f\u6210\u4e00\u4e2a\u6709\u6548\u7684 <code>DoFHandler</code> \u5bf9\u8c61\uff0c\u4ee5\u53ca\u77e9\u9635\u7684\u7a00\u758f\u6a21\u5f0f\uff0c\u548c\u4ee3\u8868\u8fb9\u754c\u4e0a\u81ea\u7531\u5ea6\u5e73\u5747\u503c\u4e3a\u96f6\u7684\u7ea6\u675f\u6761\u4ef6\u7684\u5bf9\u8c61\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::setup_system() \n  { \n\n// \u7b2c\u4e00\u4e2a\u4efb\u52a1\u5f88\u7b80\u5355\uff1a\u751f\u6210\u4e00\u4e2a\u81ea\u7531\u5ea6\u7684\u679a\u4e3e\uff0c\u5e76\u5c06\u89e3\u548c\u53f3\u624b\u5411\u91cf\u521d\u59cb\u5316\u4e3a\u6b63\u786e\u7684\u5927\u5c0f\u3002\n\n    dof_handler.distribute_dofs(fe); \n    solution.reinit(dof_handler.n_dofs()); \n    system_rhs.reinit(dof_handler.n_dofs()); \n\n// \u4e0b\u4e00\u4e2a\u4efb\u52a1\u662f\u6784\u5efa\u4ee3\u8868\u7ea6\u675f\u7684\u5bf9\u8c61\uff0c\u5373\u8fb9\u754c\u4e0a\u81ea\u7531\u5ea6\u7684\u5e73\u5747\u503c\u5e94\u8be5\u662f\u96f6\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u9700\u8981\u4e00\u4e2a\u5b9e\u9645\u5728\u8fb9\u754c\u4e0a\u7684\u8282\u70b9\u7684\u5217\u8868\u3002 <code>DoFTools</code> \u547d\u540d\u7a7a\u95f4\u6709\u4e00\u4e2a\u51fd\u6570\u53ef\u4ee5\u8fd4\u56de\u4e00\u4e2aIndexSet\u5bf9\u8c61\uff0c\u8be5\u5bf9\u8c61\u5305\u542b\u6240\u6709\u5728\u8fb9\u754c\u4e0a\u7684\u81ea\u7531\u5ea6\u7684\u6307\u6570\u3002\n\n// \u4e00\u65e6\u6211\u4eec\u6709\u4e86\u8fd9\u4e2a\u7d22\u5f15\u96c6\uff0c\u6211\u4eec\u60f3\u77e5\u9053\u54ea\u4e2a\u662f\u5bf9\u5e94\u4e8e\u8fb9\u754c\u4e0a\u7684\u81ea\u7531\u5ea6\u7684\u7b2c\u4e00\u4e2a\u7d22\u5f15\u3002\u6211\u4eec\u9700\u8981\u8fd9\u4e2a\uff0c\u56e0\u4e3a\u6211\u4eec\u60f3\u901a\u8fc7\u8fb9\u754c\u4e0a\u6240\u6709\u5176\u4ed6\u81ea\u7531\u5ea6\u7684\u503c\u6765\u7ea6\u675f\u8fb9\u754c\u4e0a\u7684\u4e00\u4e2a\u8282\u70b9\u3002\u4f7f\u7528IndexSet\u7c7b\u5f88\u5bb9\u6613\u5f97\u5230\u8fd9\u4e2a \"\u7b2c\u4e00\u4e2a \"\u81ea\u7531\u5ea6\u7684\u7d22\u5f15\u3002\n\n    const IndexSet boundary_dofs = DoFTools::extract_boundary_dofs(dof_handler); \n\n    const types::global_dof_index first_boundary_dof = \n      boundary_dofs.nth_index_in_set(0); \n\n// \u7136\u540e\u751f\u6210\u4e00\u4e2a\u53ea\u6709\u8fd9\u4e00\u4e2a\u7ea6\u675f\u7684\u7ea6\u675f\u5bf9\u8c61\u3002\u9996\u5148\u6e05\u9664\u6240\u6709\u4ee5\u524d\u7684\u5185\u5bb9\uff08\u8fd9\u4e9b\u5185\u5bb9\u53ef\u80fd\u6765\u81ea\u4ee5\u524d\u5728\u66f4\u7c97\u7684\u7f51\u683c\u4e0a\u7684\u8ba1\u7b97\uff09\uff0c\u7136\u540e\u6dfb\u52a0\u8fd9\u4e00\u884c\uff0c\u5c06 <code>first_boundary_dof</code> \u7ea6\u675f\u5230\u5176\u4ed6\u8fb9\u754cDoF\u7684\u603b\u548c\uff0c\u6bcf\u4e00\u4e2a\u6743\u91cd\u4e3a-1\u3002\u6700\u540e\uff0c\u5173\u95ed\u7ea6\u675f\u5bf9\u8c61\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5bf9\u5b83\u505a\u4e00\u4e9b\u5185\u90e8\u8bb0\u5f55\uff0c\u4ee5\u4fbf\u66f4\u5feb\u5730\u5904\u7406\u540e\u9762\u7684\u5185\u5bb9\u3002\n\n    mean_value_constraints.clear(); \n    mean_value_constraints.add_line(first_boundary_dof); \n    for (types::global_dof_index i : boundary_dofs) \n      if (i != first_boundary_dof) \n        mean_value_constraints.add_entry(first_boundary_dof, i, -1); \n    mean_value_constraints.close(); \n\n// \u4e0b\u4e00\u4e2a\u4efb\u52a1\u662f\u751f\u6210\u4e00\u4e2a\u7a00\u758f\u6a21\u5f0f\u3002\u8fd9\u7684\u786e\u662f\u4e00\u4e2a\u68d8\u624b\u7684\u4efb\u52a1\u3002\u901a\u5e38\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u53ea\u9700\u8c03\u7528 <code>DoFTools::make_sparsity_pattern</code> \u5e76\u4f7f\u7528\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u6765\u6d53\u7f29\u7ed3\u679c\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u6ca1\u6709\u60ac\u6302\u8282\u70b9\u7ea6\u675f\uff08\u56e0\u4e3a\u6211\u4eec\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\u53ea\u8fdb\u884c\u5168\u5c40\u7ec6\u5316\uff09\uff0c\u4f46\u662f\u6211\u4eec\u5728\u8fb9\u754c\u4e0a\u6709\u8fd9\u4e2a\u5168\u5c40\u7ea6\u675f\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u8fd9\u5e26\u6765\u4e86\u4e00\u4e2a\u4e25\u91cd\u7684\u95ee\u9898\uff1a <code>SparsityPattern</code> \u7c7b\u5e0c\u671b\u6211\u4eec\u4e8b\u5148\u8bf4\u660e\u6bcf\u884c\u7684\u6700\u5927\u6761\u76ee\u6570\uff0c\u53ef\u4ee5\u662f\u6240\u6709\u884c\u7684\uff0c\u4e5f\u53ef\u4ee5\u662f\u6bcf\u884c\u5355\u72ec\u7684\u3002\u5728\u5e93\u4e2d\u6709\u4e00\u4e9b\u51fd\u6570\u53ef\u4ee5\u544a\u8bc9\u4f60\u8fd9\u4e2a\u6570\u5b57\uff0c\u5982\u679c\u4f60\u53ea\u6709\u60ac\u7a7a\u7684\u8282\u70b9\u7ea6\u675f\u7684\u8bdd\uff08\u5373 DoFHandler::max_couplings_between_dofs), \uff0c\u4f46\u8fd9\u5bf9\u73b0\u5728\u7684\u60c5\u51b5\u6765\u8bf4\u662f\u600e\u6837\u7684\uff1f\u56f0\u96be\u7684\u51fa\u73b0\u662f\u56e0\u4e3a\u6d88\u9664\u7ea6\u675f\u7684\u81ea\u7531\u5ea6\u9700\u8981\u5728\u77e9\u9635\u4e2d\u589e\u52a0\u4e00\u4e9b\u6761\u76ee\uff0c\u800c\u8fd9\u4e9b\u6761\u76ee\u7684\u4f4d\u7f6e\u5e76\u4e0d\u90a3\u4e48\u5bb9\u6613\u786e\u5b9a\u3002\u56e0\u6b64\uff0c\u5982\u679c\u6211\u4eec\u5728\u8fd9\u91cc\u7ed9\u51fa\u6bcf\u884c\u7684\u6700\u5927\u6761\u76ee\u6570\uff0c\u6211\u4eec\u5c31\u4f1a\u6709\u4e00\u4e2a\u95ee\u9898\u3002\n\n// \u7531\u4e8e\u8fd9\u53ef\u80fd\u975e\u5e38\u56f0\u96be\uff0c\u4ee5\u81f3\u4e8e\u65e0\u6cd5\u7ed9\u51fa\u5408\u7406\u7684\u7b54\u6848\uff0c\u53ea\u80fd\u5206\u914d\u5408\u7406\u7684\u5185\u5b58\u91cf\uff0c\u6240\u4ee5\u6709\u4e00\u4e2aDynamicSparsityPattern\u7c7b\uff0c\u5b83\u53ef\u4ee5\u5e2e\u52a9\u6211\u4eec\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u3002\u5b83\u4e0d\u8981\u6c42\u6211\u4eec\u4e8b\u5148\u77e5\u9053\u884c\u53ef\u4ee5\u6709\u591a\u5c11\u4e2a\u6761\u76ee\uff0c\u800c\u662f\u5141\u8bb8\u4efb\u4f55\u957f\u5ea6\u3002\u56e0\u6b64\uff0c\u5728\u4f60\u5bf9\u884c\u7684\u957f\u5ea6\u6ca1\u6709\u5f88\u597d\u7684\u4f30\u8ba1\u7684\u60c5\u51b5\u4e0b\uff0c\u5b83\u660e\u663e\u66f4\u7075\u6d3b\uff0c\u4f46\u662f\u4ee3\u4ef7\u662f\u5efa\u7acb\u8fd9\u6837\u4e00\u4e2a\u6a21\u5f0f\u4e5f\u6bd4\u5efa\u7acb\u4e00\u4e2a\u4f60\u4e8b\u5148\u6709\u4fe1\u606f\u7684\u6a21\u5f0f\u8981\u6602\u8d35\u5f97\u591a\u3002\u5c3d\u7ba1\u5982\u6b64\uff0c\u7531\u4e8e\u6211\u4eec\u5728\u8fd9\u91cc\u6ca1\u6709\u5176\u4ed6\u9009\u62e9\uff0c\u6211\u4eec\u5c06\u5efa\u7acb\u8fd9\u6837\u4e00\u4e2a\u5bf9\u8c61\uff0c\u7528\u77e9\u9635\u7684\u5c3a\u5bf8\u521d\u59cb\u5316\u5b83\uff0c\u5e76\u8c03\u7528\u53e6\u4e00\u4e2a\u51fd\u6570 <code>DoFTools::make_sparsity_pattern</code> \u6765\u83b7\u5f97\u7531\u4e8e\u5fae\u5206\u7b97\u5b50\u5f15\u8d77\u7684\u7a00\u758f\u6a21\u5f0f\uff0c\u7136\u540e\u7528\u7ea6\u675f\u5bf9\u8c61\u6d53\u7f29\u5b83\uff0c\u5728\u7a00\u758f\u6a21\u5f0f\u4e2d\u589e\u52a0\u90a3\u4e9b\u6d88\u9664\u7ea6\u675f\u6240\u9700\u7684\u4f4d\u7f6e\u3002\n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp); \n    mean_value_constraints.condense(dsp); \n\n// \u6700\u540e\uff0c\u4e00\u65e6\u6211\u4eec\u6709\u4e86\u5b8c\u6574\u7684\u6a21\u5f0f\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u4ece\u4e2d\u521d\u59cb\u5316\u4e00\u4e2a <code>SparsityPattern</code> \u7c7b\u578b\u7684\u5bf9\u8c61\uff0c\u5e76\u53cd\u8fc7\u6765\u7528\u5b83\u521d\u59cb\u5316\u77e9\u9635\u3002\u8bf7\u6ce8\u610f\uff0c\u8fd9\u5b9e\u9645\u4e0a\u662f\u5fc5\u8981\u7684\uff0c\u56e0\u4e3a\u4e0e <code>SparsityPattern</code> \u7c7b\u76f8\u6bd4\uff0cDynamicSparsityPattern\u7684\u6548\u7387\u975e\u5e38\u4f4e\uff0c\u56e0\u4e3a\u5b83\u5fc5\u987b\u4f7f\u7528\u66f4\u7075\u6d3b\u7684\u6570\u636e\u7ed3\u6784\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u53ef\u80fd\u5c06\u7a00\u758f\u77e9\u9635\u7c7b\u5efa\u7acb\u5728\u5b83\u7684\u57fa\u7840\u4e0a\uff0c\u800c\u662f\u9700\u8981\u4e00\u4e2a <code>SparsityPattern</code> \u7c7b\u578b\u7684\u5bf9\u8c61\uff0c\u6211\u4eec\u901a\u8fc7\u590d\u5236\u4e2d\u95f4\u5bf9\u8c61\u4ea7\u751f\u8fd9\u4e2a\u5bf9\u8c61\u3002\n\n// \u4f5c\u4e3a\u8fdb\u4e00\u6b65\u7684\u9644\u5e26\u8bf4\u660e\uff0c\u4f60\u4f1a\u6ce8\u610f\u5230\u6211\u4eec\u5728\u8fd9\u91cc\u6ca1\u6709\u660e\u786e\u7684  <code>compress</code>  \u7a00\u758f\u6a21\u5f0f\u3002\u5f53\u7136\uff0c\u8fd9\u662f\u7531\u4e8e <code>copy_from</code> \u51fd\u6570\u4ece\u4e00\u5f00\u59cb\u5c31\u751f\u6210\u4e86\u4e00\u4e2a\u538b\u7f29\u5bf9\u8c61\uff0c\u4f60\u4e0d\u80fd\u518d\u5411\u5176\u6dfb\u52a0\u65b0\u7684\u6761\u76ee\u3002\u56e0\u6b64\uff0c <code>compress</code> \u7684\u8c03\u7528\u662f\u9690\u542b\u5728 <code>copy_from</code> \u7684\u8c03\u7528\u4e2d\u7684\u3002\n\n    sparsity_pattern.copy_from(dsp); \n    system_matrix.reinit(sparsity_pattern); \n  } \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u63a5\u7740\u7ec4\u88c5\u7ebf\u6027\u65b9\u7a0b\u7ec4\uff0c\u5bf9\u5176\u8fdb\u884c\u6c42\u89e3\uff0c\u5e76\u5bf9\u89e3\u8fdb\u884c\u8bc4\u4f30\u3002\u8fd9\u6837\u5c31\u6709\u4e86\u4e09\u4e2a\u52a8\u4f5c\uff0c\u6211\u4eec\u5c06\u628a\u5b83\u4eec\u653e\u5230\u516b\u4e2a\u771f\u5b9e\u7684\u8bed\u53e5\u4e2d\uff08\u4e0d\u5305\u62ec\u53d8\u91cf\u7684\u58f0\u660e\uff0c\u4ee5\u53ca\u4e34\u65f6\u5411\u91cf\u7684\u5904\u7406\uff09\u3002\u56e0\u6b64\uff0c\u8fd9\u4e2a\u51fd\u6570\u662f\u4e3a\u975e\u5e38\u61d2\u60f0\u7684\u4eba\u51c6\u5907\u7684\u3002\u5c3d\u7ba1\u5982\u6b64\uff0c\u6240\u8c03\u7528\u7684\u51fd\u6570\u662f\u76f8\u5f53\u5f3a\u5927\u7684\uff0c\u901a\u8fc7\u5b83\u4eec\uff0c\u8fd9\u4e2a\u51fd\u6570\u4f7f\u7528\u4e86\u6574\u4e2a\u5e93\u7684\u5927\u91cf\u5185\u5bb9\u3002\u4f46\u8ba9\u6211\u4eec\u6765\u770b\u770b\u6bcf\u4e00\u4e2a\u6b65\u9aa4\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::assemble_and_solve() \n  { \n\n// \u9996\u5148\uff0c\u6211\u4eec\u8981\u628a\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u5185\u5bb9\u7ec4\u5408\u8d77\u6765\u3002\u5728\u4e4b\u524d\u7684\u6240\u6709\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u5df2\u7ecf\u7814\u7a76\u4e86\u5982\u4f55\u624b\u52a8\u5b8c\u6210\u8fd9\u4e00\u5de5\u4f5c\u7684\u5404\u79cd\u65b9\u6cd5\u3002\u7136\u800c\uff0c\u7531\u4e8e\u62c9\u666e\u62c9\u65af\u77e9\u9635\u548c\u7b80\u5355\u7684\u53f3\u624b\u8fb9\u5728\u5e94\u7528\u4e2d\u51fa\u73b0\u7684\u9891\u7387\u5f88\u9ad8\uff0c\u5e93\u4e2d\u63d0\u4f9b\u7684\u51fd\u6570\u5b9e\u9645\u4e0a\u662f\u4e3a\u4f60\u505a\u8fd9\u4ef6\u4e8b\u7684\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5b83\u4eec\u5728\u6240\u6709\u5355\u5143\u683c\u4e0a\u8fdb\u884c\u5faa\u73af\uff0c\u8bbe\u7f6e\u5c40\u90e8\u7684\u77e9\u9635\u548c\u5411\u91cf\uff0c\u5e76\u5c06\u5b83\u4eec\u653e\u5728\u4e00\u8d77\uff0c\u5f97\u5230\u6700\u7ec8\u7ed3\u679c\u3002\n\n// \u4ee5\u4e0b\u662f\u4e24\u4e2a\u6700\u5e38\u7528\u7684\u51fd\u6570\uff1a\u521b\u5efa\u62c9\u666e\u62c9\u65af\u77e9\u9635\u548c\u521b\u5efa\u6765\u81ea\u4f53\u6216\u8fb9\u754c\u529b\u7684\u53f3\u4fa7\u5411\u91cf\u3002\u5b83\u4eec\u9700\u8981\u6620\u5c04\u5bf9\u8c61\u3001\u4ee3\u8868\u81ea\u7531\u5ea6\u548c\u4f7f\u7528\u4e2d\u7684\u6709\u9650\u5143\u7684 <code>DoFHandler</code> \u5bf9\u8c61\u3001\u8981\u4f7f\u7528\u7684\u6b63\u4ea4\u516c\u5f0f\u4ee5\u53ca\u8f93\u51fa\u5bf9\u8c61\u3002\u521b\u5efa\u53f3\u624b\u5411\u91cf\u7684\u51fd\u6570\u8fd8\u5fc5\u987b\u63a5\u53d7\u4e00\u4e2a\u63cf\u8ff0\uff08\u8fde\u7eed\uff09\u53f3\u624b\u5411\u91cf\u51fd\u6570\u7684\u51fd\u6570\u5bf9\u8c61\u3002\n\n// \u8ba9\u6211\u4eec\u6765\u770b\u770b\u77e9\u9635\u548c\u4f53\u529b\u7684\u96c6\u6210\u65b9\u5f0f\u3002\n\n    const unsigned int gauss_degree = \n      std::max(static_cast<unsigned int>( \n                 std::ceil(1. * (mapping.get_degree() + 1) / 2)), \n               2U); \n    MatrixTools::create_laplace_matrix(mapping, \n                                       dof_handler, \n                                       QGauss<dim>(gauss_degree), \n                                       system_matrix); \n    VectorTools::create_right_hand_side(mapping, \n                                        dof_handler, \n                                        QGauss<dim>(gauss_degree), \n                                        Functions::ConstantFunction<dim>(-2), \n                                        system_rhs); \n\n// \u8fd9\u5f88\u7b80\u5355\uff0c\u5bf9\u5417\uff1f\n\n// \u4e0d\u8fc7\uff0c\u6709\u4e24\u70b9\u9700\u8981\u6ce8\u610f\u3002\u9996\u5148\uff0c\u8fd9\u4e9b\u51fd\u6570\u5728\u5f88\u591a\u60c5\u51b5\u4e0b\u90fd\u4f1a\u7528\u5230\u3002\u4e5f\u8bb8\u4f60\u60f3\u4e3a\u4e00\u4e2a\u77e2\u91cf\u503c\u6709\u9650\u5143\u521b\u5efa\u4e00\u4e2a\u62c9\u666e\u62c9\u65af\u6216\u8d28\u91cf\u77e9\u9635\uff1b\u6216\u8005\u4f60\u60f3\u4f7f\u7528\u9ed8\u8ba4\u7684Q1\u6620\u5c04\uff1b\u6216\u8005\u4f60\u60f3\u7528\u62c9\u666e\u62c9\u65af\u7b97\u5b50\u7684\u4e00\u4e2a\u7cfb\u6570\u6765\u88c5\u914d\u77e9\u9635\u3002\u7531\u4e8e\u8fd9\u4e2a\u539f\u56e0\uff0c\u5728 <code>MatrixCreator</code> \u548c <code>MatrixTools</code> \u547d\u540d\u7a7a\u95f4\u4e2d\u6709\u76f8\u5f53\u591a\u7684\u8fd9\u4e9b\u51fd\u6570\u7684\u53d8\u79cd\u3002\u6bcf\u5f53\u4f60\u9700\u8981\u8fd9\u4e9b\u51fd\u6570\u7684\u4e00\u4e2a\u4e0e\u4e0a\u9762\u8c03\u7528\u7684\u7565\u6709\u4e0d\u540c\u7684\u7248\u672c\u65f6\uff0c\u5f53\u7136\u503c\u5f97\u770b\u4e00\u4e0b\u6587\u6863\uff0c\u5e76\u68c0\u67e5\u4e00\u4e9b\u4e1c\u897f\u662f\u5426\u9002\u5408\u4f60\u7684\u9700\u8981\u3002\n\n// \u7b2c\u4e8c\u70b9\u662f\u5173\u4e8e\u6211\u4eec\u4f7f\u7528\u7684\u6b63\u4ea4\u516c\u5f0f\uff1a\u6211\u4eec\u60f3\u5bf9\u53cc\u7ebf\u6027\u5f62\u72b6\u51fd\u6570\u8fdb\u884c\u79ef\u5206\uff0c\u6240\u4ee5\u6211\u4eec\u77e5\u9053\u6211\u4eec\u81f3\u5c11\u8981\u4f7f\u7528\u4e8c\u9636\u9ad8\u65af\u6b63\u4ea4\u516c\u5f0f\u3002\u53e6\u4e00\u65b9\u9762\uff0c\u6211\u4eec\u5e0c\u671b\u6b63\u4ea4\u89c4\u5219\u81f3\u5c11\u6709\u8fb9\u754c\u8fd1\u4f3c\u7684\u9636\u6570\u3002\u56e0\u4e3a\u6709 $r$ \u70b9\u7684\u9ad8\u65af\u89c4\u5219\u7684\u9636\u6570\u662f $2r -1$  \uff0c\u800c\u4f7f\u7528 $p$ \u5ea6\u7684\u591a\u9879\u5f0f\u7684\u8fb9\u754c\u8fd1\u4f3c\u7684\u9636\u6570\u662f $p+1$ \uff0c\u6211\u4eec\u77e5\u9053 $2r \\geq p$  \u3002\u7531\u4e8er\u5fc5\u987b\u662f\u4e00\u4e2a\u6574\u6570\uff0c\u5e76\u4e14\uff08\u5982\u4e0a\u6240\u8ff0\uff09\u5fc5\u987b\u81f3\u5c11\u662f $2$ \uff0c\u8fd9\u5c31\u5f25\u8865\u4e86\u4e0a\u8ff0\u516c\u5f0f\u8ba1\u7b97 <code>gauss_degree</code> \u3002\n\n// \u7531\u4e8e\u5bf9\u53f3\u4fa7\u5411\u91cf\u7684\u4f53\u529b\u8d21\u732e\u7684\u751f\u6210\u662f\u5982\u6b64\u7b80\u5355\uff0c\u6211\u4eec\u5bf9\u8fb9\u754c\u529b\u4e5f\u8981\u91cd\u65b0\u505a\u4e00\u904d\uff1a\u5206\u914d\u4e00\u4e2a\u5408\u9002\u5927\u5c0f\u7684\u5411\u91cf\u5e76\u8c03\u7528\u5408\u9002\u7684\u51fd\u6570\u3002\u8fb9\u754c\u51fd\u6570\u6709\u5e38\u91cf\u503c\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u4ece\u5e93\u4e2d\u5feb\u901f\u751f\u6210\u4e00\u4e2a\u5bf9\u8c61\uff0c\u6211\u4eec\u4f7f\u7528\u4e0e\u4e0a\u9762\u76f8\u540c\u7684\u6b63\u4ea4\u516c\u5f0f\uff0c\u4f46\u8fd9\u6b21\u7684\u7ef4\u5ea6\u8f83\u4f4e\uff0c\u56e0\u4e3a\u6211\u4eec\u73b0\u5728\u662f\u5728\u9762\u4e0a\u800c\u4e0d\u662f\u5728\u5355\u5143\u4e0a\u79ef\u5206\u3002\n\n    Vector<double> tmp(system_rhs.size()); \n    VectorTools::create_boundary_right_hand_side( \n      mapping, \n      dof_handler, \n      QGauss<dim - 1>(gauss_degree), \n      Functions::ConstantFunction<dim>(1), \n      tmp); \n\n// \u7136\u540e\u5c06\u8fb9\u754c\u7684\u8d21\u732e\u4e0e\u57df\u5185\u90e8\u7684\u8d21\u732e\u76f8\u52a0\u3002\n\n    system_rhs += tmp; \n\n// \u5728\u7ec4\u88c5\u53f3\u624b\u8fb9\u65f6\uff0c\u6211\u4eec\u5fc5\u987b\u4f7f\u7528\u4e24\u4e2a\u4e0d\u540c\u7684\u77e2\u91cf\u5bf9\u8c61\uff0c\u7136\u540e\u5c06\u5b83\u4eec\u52a0\u5728\u4e00\u8d77\u3002\u6211\u4eec\u4e0d\u5f97\u4e0d\u8fd9\u6837\u505a\u7684\u539f\u56e0\u662f\uff0c <code>VectorTools::create_right_hand_side</code> \u548c <code>VectorTools::create_boundary_right_hand_side</code> \u51fd\u6570\u9996\u5148\u6e05\u9664\u8f93\u51fa\u5411\u91cf\uff0c\u800c\u4e0d\u662f\u5c06\u5b83\u4eec\u7684\u7ed3\u679c\u4e0e\u4e4b\u524d\u7684\u5185\u5bb9\u76f8\u52a0\u3002\u8fd9\u53ef\u4ee5\u5408\u7406\u5730\u79f0\u4e3a\u5e93\u5728\u8d77\u6b65\u9636\u6bb5\u7684\u8bbe\u8ba1\u7f3a\u9677\uff0c\u4f46\u4e0d\u5e78\u7684\u662f\uff0c\u4e8b\u60c5\u73b0\u5728\u5df2\u7ecf\u662f\u8fd9\u6837\u4e86\uff0c\u5f88\u96be\u6539\u53d8\u8fd9\u79cd\u65e0\u58f0\u5730\u7834\u574f\u73b0\u6709\u4ee3\u7801\u7684\u4e8b\u60c5\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u5f97\u4e0d\u63a5\u53d7\u3002\n\n// \u73b0\u5728\uff0c\u7ebf\u6027\u7cfb\u7edf\u5df2\u7ecf\u5efa\u7acb\u8d77\u6765\u4e86\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u4ece\u77e9\u9635\u548c\u53f3\u624b\u5411\u91cf\u4e2d\u6d88\u9664\u6211\u4eec\u7ea6\u675f\u5230\u8fb9\u754c\u4e0a\u5176\u4ed6DoF\u7684\u4e00\u4e2a\u81ea\u7531\u5ea6\u7684\u5747\u503c\u7ea6\u675f\uff0c\u5e76\u89e3\u51b3\u8fd9\u4e2a\u7cfb\u7edf\u3002\u4e4b\u540e\uff0c\u518d\u6b21\u5206\u914d\u7ea6\u675f\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u8fd9\u610f\u5473\u7740\u5c06\u88ab\u7ea6\u675f\u7684\u81ea\u7531\u5ea6\u8bbe\u7f6e\u4e3a\u9002\u5f53\u7684\u503c\n\n    mean_value_constraints.condense(system_matrix); \n    mean_value_constraints.condense(system_rhs); \n\n    solve(); \n    mean_value_constraints.distribute(solution); \n\n// \u6700\u540e\uff0c\u8bc4\u4f30\u6211\u4eec\u5f97\u5230\u7684\u89e3\u51b3\u65b9\u6848\u3002\u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u8bf4\uff0c\u6211\u4eec\u5bf9\u89e3\u51b3\u65b9\u6848\u7684H1\u534a\u6b63\u6001\u611f\u5174\u8da3\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u5728\u5e93\u4e2d\u4e5f\u6709\u4e00\u4e2a\u51fd\u6570\u53ef\u4ee5\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u5c3d\u7ba1\u662f\u4ee5\u4e00\u79cd\u7a0d\u5fae\u4e0d\u660e\u663e\u7684\u65b9\u5f0f\uff1a <code>VectorTools::integrate_difference</code> \u51fd\u6570\u6574\u5408\u4e86\u4e00\u4e2a\u6709\u9650\u5143\u51fd\u6570\u548c\u4e00\u4e2a\u8fde\u7eed\u51fd\u6570\u4e4b\u95f4\u7684\u5dee\u503c\u7684\u89c4\u8303\u3002\u56e0\u6b64\uff0c\u5982\u679c\u6211\u4eec\u60f3\u8981\u4e00\u4e2a\u6709\u9650\u5143\u573a\u7684\u89c4\u8303\uff0c\u6211\u4eec\u53ea\u9700\u5c06\u8fde\u7eed\u51fd\u6570\u8bbe\u4e3a\u96f6\u3002\u8bf7\u6ce8\u610f\uff0c\u8fd9\u4e2a\u51fd\u6570\uff0c\u5c31\u50cf\u5e93\u4e2d\u7684\u8bb8\u591a\u5176\u4ed6\u51fd\u6570\u4e00\u6837\uff0c\u81f3\u5c11\u6709\u4e24\u4e2a\u7248\u672c\uff0c\u4e00\u4e2a\u662f\u4ee5\u6620\u5c04\u4e3a\u53c2\u6570\u7684\uff08\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\uff09\uff0c\u53e6\u4e00\u4e2a\u662f\u6211\u4eec\u5728\u4ee5\u524d\u7684\u4f8b\u5b50\u4e2d\u4f7f\u7528\u7684\u9690\u542b\u7684 <code>MappingQ1</code>  \u3002 \u8fd8\u8981\u6ce8\u610f\u7684\u662f\uff0c\u6211\u4eec\u91c7\u7528\u7684\u662f\u9ad8\u4e00\u7ea7\u7684\u6b63\u4ea4\u516c\u5f0f\uff0c\u4ee5\u907f\u514d\u51fa\u73b0\u8d85\u878d\u5408\u6548\u5e94\uff0c\u5373\u5728\u67d0\u4e9b\u70b9\u4e0a\u7684\u89e3\u7279\u522b\u63a5\u8fd1\u7cbe\u786e\u89e3\uff08\u6211\u4eec\u4e0d\u77e5\u9053\u8fd9\u91cc\u662f\u5426\u4f1a\u51fa\u73b0\u8fd9\u79cd\u60c5\u51b5\uff0c\u4f46\u6709\u5df2\u77e5\u7684\u6848\u4f8b\uff0c\u6211\u4eec\u53ea\u662f\u60f3\u786e\u8ba4\u4e00\u4e0b\uff09\u3002\n\n    Vector<float> norm_per_cell(triangulation.n_active_cells()); \n    VectorTools::integrate_difference(mapping, \n                                      dof_handler, \n                                      solution, \n                                      Functions::ZeroFunction<dim>(), \n                                      norm_per_cell, \n                                      QGauss<dim>(gauss_degree + 1), \n                                      VectorTools::H1_seminorm); \n\n// \u7136\u540e\uff0c\u521a\u521a\u8c03\u7528\u7684\u51fd\u6570\u5c06\u5176\u7ed3\u679c\u4f5c\u4e3a\u4e00\u4e2a\u503c\u7684\u5411\u91cf\u8fd4\u56de\uff0c\u6bcf\u4e2a\u503c\u8868\u793a\u4e00\u4e2a\u5355\u5143\u683c\u4e0a\u7684\u6cd5\u7ebf\u3002\u4e3a\u4e86\u5f97\u5230\u5168\u5c40\u6cd5\u7ebf\uff0c\u6211\u4eec\u8981\u505a\u4ee5\u4e0b\u5de5\u4f5c\u3002\n\n    const double norm = \n      VectorTools::compute_global_error(triangulation, \n                                        norm_per_cell, \n                                        VectorTools::H1_seminorm); \n\n// \u6700\u540e\u4e00\u9879\u4efb\u52a1--\u751f\u6210\u8f93\u51fa\u3002\n\n    output_table.add_value(\"cells\", triangulation.n_active_cells()); \n    output_table.add_value(\"|u|_1\", norm); \n    output_table.add_value(\"error\", \n                           std::fabs(norm - std::sqrt(3.14159265358 / 2))); \n  } \n\n// \u4e0b\u9762\u8fd9\u4e2a\u89e3\u7ebf\u6027\u65b9\u7a0b\u7ec4\u7684\u51fd\u6570\u662f\u4ece step-5 \u4e2d\u590d\u5236\u8fc7\u6765\u7684\uff0c\u5728\u90a3\u91cc\u6709\u8be6\u7ec6\u7684\u89e3\u91ca\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::solve() \n  { \n    SolverControl            solver_control(1000, 1e-12); \n    SolverCG<Vector<double>> cg(solver_control); \n\n    PreconditionSSOR<SparseMatrix<double>> preconditioner; \n    preconditioner.initialize(system_matrix, 1.2); \n\n    cg.solve(system_matrix, solution, system_rhs, preconditioner); \n  } \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u628a\u89e3\u51b3\u65b9\u6848\u4ee5\u53ca\u6750\u6599ID\u5199\u5230\u4e00\u4e2aVTU\u6587\u4ef6\u4e2d\u3002\u8fd9\u4e0e\u5176\u4ed6\u8bb8\u591a\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u7684\u505a\u6cd5\u76f8\u4f3c\u3002\u8fd9\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u63d0\u51fa\u7684\u65b0\u5185\u5bb9\u662f\uff0c\u6211\u4eec\u8981\u786e\u4fdd\u5199\u5230\u6587\u4ef6\u4e2d\u7528\u4e8e\u53ef\u89c6\u5316\u7684\u6570\u636e\u5b9e\u9645\u4e0a\u662fdeal.II\u5185\u90e8\u4f7f\u7528\u7684\u6570\u636e\u7684\u5fe0\u5b9e\u4ee3\u8868\u3002\u8fd9\u662f\u56e0\u4e3a\u5927\u591a\u6570\u53ef\u89c6\u5316\u6570\u636e\u683c\u5f0f\u53ea\u7528\u9876\u70b9\u5750\u6807\u8868\u793a\u5355\u5143\uff0c\u4f46\u6ca1\u6709\u529e\u6cd5\u8868\u793adeal.II\u4e2d\u4f7f\u7528\u9ad8\u9636\u6620\u5c04\u65f6\u7684\u66f2\u7ebf\u8fb9\u754c--\u6362\u53e5\u8bdd\u8bf4\uff0c\u4f60\u5728\u53ef\u89c6\u5316\u5de5\u5177\u4e2d\u770b\u5230\u7684\u4e1c\u897f\u5b9e\u9645\u4e0a\u4e0d\u662f\u4f60\u6b63\u5728\u8ba1\u7b97\u7684\u4e1c\u897f\u3002\u987a\u5e26\u4e00\u63d0\uff0c\u5728\u4f7f\u7528\u9ad8\u9636\u5f62\u72b6\u51fd\u6570\u65f6\u4e5f\u662f\u5982\u6b64\u3002\u5927\u591a\u6570\u53ef\u89c6\u5316\u5de5\u5177\u53ea\u5448\u73b0\u53cc\u7ebf\u6027/\u4e09\u7ebf\u6027\u7684\u8868\u793a\u3002\u8fd9\u5728 DataOut::build_patches().) \u4e2d\u6709\u8be6\u7ec6\u7684\u8ba8\u8bba\u3002\n\n// \u6240\u4ee5\u6211\u4eec\u9700\u8981\u786e\u4fdd\u9ad8\u9636\u8868\u793a\u88ab\u5199\u5165\u6587\u4ef6\u4e2d\u3002\u6211\u4eec\u9700\u8981\u8003\u8651\u4e24\u4e2a\u7279\u522b\u7684\u8bdd\u9898\u3002\u9996\u5148\uff0c\u6211\u4eec\u901a\u8fc7 DataOutBase::VtkFlags \u544a\u8bc9DataOut\u5bf9\u8c61\uff0c\u6211\u4eec\u6253\u7b97\u5c06\u5143\u7d20\u7684\u7ec6\u5206\u89e3\u91ca\u4e3a\u9ad8\u9636\u62c9\u683c\u6717\u65e5\u591a\u9879\u5f0f\uff0c\u800c\u4e0d\u662f\u53cc\u7ebf\u6027\u6591\u5757\u7684\u96c6\u5408\u3002\u6700\u8fd1\u7684\u53ef\u89c6\u5316\u7a0b\u5e8f\uff0c\u5982ParaView 5.5\u7248\u6216\u66f4\u65b0\u7248\uff0c\u7136\u540e\u53ef\u4ee5\u5448\u73b0\u9ad8\u9636\u89e3\u51b3\u65b9\u6848\uff08\u66f4\u591a\u7ec6\u8282\u89c1<a\n//  href=\"https:github.com/dealii/dealii/wiki/Notes-on-visualizing-high-order-output\">wiki\n//  page</a>\uff09\u3002\u5176\u6b21\uff0c\u6211\u4eec\u9700\u8981\u786e\u4fdd\u6620\u5c04\u88ab\u4f20\u9012\u7ed9 DataOut::build_patches() \u65b9\u6cd5\u3002\u6700\u540e\uff0cDataOut\u7c7b\u9ed8\u8ba4\u53ea\u6253\u5370<i>boundary</i>\u5355\u5143\u7684\u66f2\u9762\uff0c\u6240\u4ee5\u6211\u4eec\u9700\u8981\u786e\u4fdd\u901a\u8fc7\u6620\u5c04\u5c06\u5185\u90e8\u5355\u5143\u4e5f\u6253\u5370\u6210\u66f2\u9762\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::write_high_order_mesh(const unsigned cycle) \n  { \n    DataOut<dim> data_out; \n\n    DataOutBase::VtkFlags flags; \n    flags.write_higher_order_cells = true; \n    data_out.set_flags(flags); \n\n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \"solution\"); \n\n    data_out.build_patches(mapping, \n                           mapping.get_degree(), \n                           DataOut<dim>::curved_inner_cells); \n\n    std::ofstream file(\"solution-c=\" + std::to_string(cycle) + \n                       \".p=\" + std::to_string(mapping.get_degree()) + \".vtu\"); \n\n    data_out.write_vtu(file); \n  } \n\n// \u6700\u540e\u662f\u63a7\u5236\u8981\u6267\u884c\u7684\u4e0d\u540c\u6b65\u9aa4\u7684\u4e3b\u8981\u51fd\u6570\u3002\u5b83\u7684\u5185\u5bb9\u76f8\u5f53\u7b80\u5355\uff0c\u751f\u6210\u4e00\u4e2a\u5706\u7684\u4e09\u89d2\u5f62\uff0c\u7ed9\u5b83\u5173\u8054\u4e00\u4e2a\u8fb9\u754c\uff0c\u7136\u540e\u5728\u968f\u540e\u7684\u66f4\u7ec6\u7684\u7f51\u683c\u4e0a\u505a\u51e0\u4e2a\u5faa\u73af\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u5c06\u7f51\u683c\u7ec6\u5316\u653e\u5230\u4e86\u5faa\u73af\u5934\u4e2d\uff1b\u8fd9\u5bf9\u6d4b\u8bd5\u7a0b\u5e8f\u6765\u8bf4\u53ef\u80fd\u662f\u4ef6\u597d\u4e8b\uff0c\u4f46\u5bf9\u5b9e\u9645\u5e94\u7528\u6765\u8bf4\uff0c\u4f60\u5e94\u8be5\u8003\u8651\u5230\u8fd9\u610f\u5473\u7740\u7f51\u683c\u662f\u5728\u5faa\u73af\u6700\u540e\u4e00\u6b21\u6267\u884c\u540e\u88ab\u7ec6\u5316\u7684\uff0c\u56e0\u4e3a\u589e\u91cf\u5b50\u53e5\uff08\u4e09\u90e8\u5206\u5faa\u73af\u5934\u7684\u6700\u540e\u4e00\u90e8\u5206\uff09\u662f\u5728\u6bd4\u8f83\u90e8\u5206\uff08\u7b2c\u4e8c\u90e8\u5206\uff09\u4e4b\u524d\u6267\u884c\u7684\uff0c\u5982\u679c\u7f51\u683c\u5df2\u7ecf\u76f8\u5f53\u7ec6\u5316\u4e86\uff0c\u8fd9\u53ef\u80fd\u662f\u76f8\u5f53\u6602\u8d35\u7684\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u4f60\u5e94\u8be5\u5b89\u6392\u4ee3\u7801\uff0c\u4f7f\u7f51\u683c\u5728\u6700\u540e\u4e00\u6b21\u5faa\u73af\u8fd0\u884c\u540e\u4e0d\u518d\u88ab\u8fdb\u4e00\u6b65\u7ec6\u5316\uff08\u6216\u8005\u4f60\u5e94\u8be5\u5728\u6bcf\u6b21\u8fd0\u884c\u7684\u5f00\u59cb\u5c31\u8fd9\u6837\u505a\uff0c\u9664\u4e86\u7b2c\u4e00\u6b21\uff09\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::run() \n  { \n    GridGenerator::hyper_ball(triangulation); \n\n    for (unsigned int cycle = 0; cycle < 6; ++cycle) \n      { \n        setup_system(); \n        assemble_and_solve(); \n        write_high_order_mesh(cycle); \n\n        triangulation.refine_global(); \n      } \n\n// \u5728\u6240\u6709\u7684\u6570\u636e\u751f\u6210\u4e4b\u540e\uff0c\u5c06\u7ed3\u679c\u7684\u8868\u683c\u5199\u5230\u5c4f\u5e55\u4e0a\u3002\n\n    output_table.set_precision(\"|u|_1\", 6); \n    output_table.set_precision(\"error\", 6); \n    output_table.write_text(std::cout); \n    std::cout << std::endl; \n  } \n} // namespace Step11 \n\n// \u6700\u540e\u662f\u4e3b\u51fd\u6570\u3002\u5b83\u7684\u7ed3\u6784\u4e0e\u524d\u9762\u51e0\u4e2a\u4f8b\u5b50\u4e2d\u4f7f\u7528\u7684\u7ed3\u6784\u76f8\u540c\uff0c\u6240\u4ee5\u53ef\u80fd\u4e0d\u9700\u8981\u66f4\u591a\u89e3\u91ca\u3002\n\nint main() \n{ \n  try \n    { \n      std::cout.precision(5); \n\n// \u8fd9\u662f\u4e3b\u5faa\u73af\uff0c\u7528\u7ebf\u6027\u5230\u7acb\u65b9\u7684\u6620\u5c04\u505a\u8ba1\u7b97\u3002\u6ce8\u610f\uff0c\u7531\u4e8e\u6211\u4eec\u53ea\u9700\u8981\u4e00\u6b21 <code>LaplaceProblem@<2@></code> \u7c7b\u578b\u7684\u5bf9\u8c61\uff0c\u6211\u4eec\u751a\u81f3\u4e0d\u7ed9\u5b83\u547d\u540d\uff0c\u800c\u662f\u521b\u5efa\u4e00\u4e2a\u672a\u547d\u540d\u7684\u8fd9\u6837\u7684\u5bf9\u8c61\uff0c\u5e76\u8c03\u7528\u5b83\u7684 <code>run</code> \u51fd\u6570\uff0c\u968f\u540e\u5b83\u53c8\u7acb\u5373\u88ab\u9500\u6bc1\u3002\n\n      for (unsigned int mapping_degree = 1; mapping_degree <= 3; \n           ++mapping_degree) \n        Step11::LaplaceProblem<2>(mapping_degree).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\n  return 0; \n} \n\n\n", "meta": {"hexsha": "c5a706bc515f4891108c3f4dc54427b1518d843c", "size": 13754, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-11/step-11.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-11/step-11.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-11/step-11.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.7514450867, "max_line_length": 406, "alphanum_fraction": 0.6737676312, "num_tokens": 6385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833789613196, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5365089726213861}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2016 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/**\n * \\file\n * \\author Martin Weiser, modified by Felix Lehmann\n */\n\n#ifndef CONJUGATION_HH\n#define CONJUGATION_HH\n\n#include <cassert>\n#include <memory>\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/istl/bcrsmatrix.hh\"\n#include \"dune/istl/matrixindexset.hh\"\n\n#include \"linalg/localMatrices.hh\"\n#include \"linalg/threadedMatrix.hh\"\n\n#include \"utilities/timing.hh\"\n\nnamespace Kaskade\n{\n  /**\n   * \\brief Creates the sparsity pattern of \\f$ P^T A P\\f$.\n   *\n   * Out now: onlyLowerTriangle. If parameter is set true, we will only touch the lower triangle of A\n   * and only create the lower triangle of the resulting matrix P^T A P\n   */\n  template <class Scalar, class Entry>\n  std::unique_ptr<Dune::MatrixIndexSet> conjugationPattern(Dune::BCRSMatrix<Dune::FieldMatrix<Scalar,1,1> > const& P,\n\t\t\t\t\t\t\t   Dune::BCRSMatrix<Entry> const& A ,\n\t\t\t\t\t\t\t   bool onlyLowerTriangle = false)\n      {\n    assert(A.N()==A.M());\n    assert(A.N()==P.N());\n\n    typedef Dune::BCRSMatrix<Entry> MatA;\n    typedef Dune::BCRSMatrix<Dune::FieldMatrix<Scalar,1,1> > MatP;\n\n    // If C = P^T A P, we have that C_{ij} = \\sum_{k,l} P_{ki} P_{lj} A_{kl}. Hence, the entry A_{kl} contributes to\n    // all C_{ij} for which there are nonzero entries P_{ki} and P_{lj} in the rows k and l of P. Thus we can simply\n    // run through all nonzeros A_{kl} of A, look up the column indices i,j of rows k and l of P, and flag C_{ij}\n    // as nonzero.\n\n    std::unique_ptr<Dune::MatrixIndexSet> nzC(new Dune::MatrixIndexSet(P.M(),P.M()));\n\n\n    if(onlyLowerTriangle == false)\n    {\n      // Step through all entries of A\n      for (int k=0; k<A.N(); ++k)\n        for (typename MatA::ConstColIterator ca=A[k].begin(); ca!=A[k].end(); ++ca)\n        {\n          int const l = ca.index();\n          // Step through all entries of rows k and l of P and add entry\n          for (typename MatP::ConstColIterator cpk=P[k].begin(); cpk!=P[k].end(); ++cpk)\n            for (typename MatP::ConstColIterator cpl=P[l].begin(); cpl!=P[l].end(); ++cpl)\n              nzC->add(cpk.index(),cpl.index());\n        }\n    }\n    else\n    {\n      // Step through all entries of A\n      for (int k=0; k<A.N(); ++k)\n        for (typename MatA::ConstColIterator ca=A[k].begin(); ca!=A[k].end(); ++ca)\n        {\n          int const l = ca.index();\n          // Step through all entries of rows k and l of P and add entry\n          for (typename MatP::ConstColIterator cpk=P[k].begin(); cpk!=P[k].end(); ++cpk)\n            for (typename MatP::ConstColIterator cpl=P[l].begin(); cpl!=P[l].end(); ++cpl)\n            {\n              if( cpk.index() >= cpl.index() )\n                nzC->add(cpk.index(),cpl.index());\n              else\n                nzC->add(cpl.index(),cpk.index());\n            }\n        }\n    }\n\n    return nzC;\n\n    // An alternative way of computing the sparsity pattern would be to use that the nonzero entries j in column i\n    // of C are exactly those for which there is k with (nonzero P_{jk} and there is l with (nonzero P_{il} and A_{lk})).\n    // Hence we can obtain the column index set J directly by the following steps:\n    // (i) find all l with P_{li} nonzero -> L  [requires to access columns of P - compute the transpose patterns once]\n    // (ii) find all k with A_{lk} nonzero for some l in L -> K  [probably sorting K and removing doubled entries would be a good idea here]\n    // (iii) find all j with P_{kj} nonzero for some k in K -> J\n    // Compared to the above implementation this would have the following (dis)advantages\n    // + easy to do in parallel (since write operations are separated)\n    // + fewer scattered write accesses to memory\n    // - more complex implementation\n    // - requires the transpose pattern of P\n      }\n\n  /**\n   * \\brief Creates the conjugation product \\f$ P^T A P\\f$.\n   *\n   * Note that for typical multigrid Galerkin projections the memory access patterns of the conjugation are quite\n   * bad for performance. Consider assembling the projected matrix directly on the coarser discretization.\n   *\n   * \\param onlyLowerTriangle. If true, we will only touch the lower triangle of A\n   * and only create the lower triangle of the resulting matrix P^T A P\n   */\n  template <class IndexP, class EntryP, class IndexA, class EntryA>\n  NumaBCRSMatrix<EntryA,IndexA>\n  conjugation(NumaBCRSMatrix<EntryP,IndexP> const& P, NumaBCRSMatrix<EntryA,IndexA> const& A, bool onlyLowerTriangle = false)\n  {\n    assert(A.N()==A.M());\n    assert(A.N()==P.N());\n\n    Timings& timer = Timings::instance();\n\n\n    // First create the sparsity pattern\n    timer.start(\"conjugation pattern\");\n    NumaCRSPatternCreator<IndexA> creator(P.M(),P.M(),onlyLowerTriangle);\n\n    // If C = P^T A P, we have that C_{ij} = \\sum_{k,l} P_{ki} P_{lj} A_{kl}. Hence, the entry A_{kl} contributes to\n    // all C_{ij} for which there are nonzero entries P_{ki} and P_{lj} in the rows k and l of P. Thus we can simply\n    // run through all nonzeros A_{kl} of A, look up the column indices i,j of rows k and l of P, and flag C_{ij}\n    // as nonzero.\n\n    { // just a new scope\n      // helper routine for extracting all column indices of a row\n      auto getColumnIndices = [] (auto const& row, std::vector<IndexP>& ci)\n      {\n        ci.clear();\n        for (auto i=row.begin(); i!=row.end(); ++i)       // indices i for which Pki != 0\n          ci.push_back(i.index());\n      };\n      std::vector<IndexP> is, js;\n\n      // Step through all entries of A\n      for (IndexA k=0; k<A.N(); ++k)\n      {\n        getColumnIndices(P[k],is);                          // indices i for which Pki != 0\n\n        auto row = A[k];\n        for (auto ca=row.begin(); ca!=row.end(); ++ca)\n        {\n          IndexA const l = ca.index();\n          getColumnIndices(P[l],js);                        // indices j for which Plj != 0\n\n          // add all combinations i,j\n          creator.addElements(std::begin(is),std::end(is),std::begin(js),std::end(js));\n          if (onlyLowerTriangle && k>l)                     // subdiagonal entry (k,l) of A -> entry (l,k) must be treated implicitly:\n            // add all combinations (j,i)\n            creator.addElements(std::begin(js),std::end(js),std::begin(is),std::end(is));\n        }\n      }\n    }\n    timer.stop(\"conjugation pattern\");\n\n    // An alternative way of computing the sparsity pattern would be to use that the nonzero entries j in column i\n    // of C are exactly those for which there is k with (nonzero P_{jk} and there is l with (nonzero P_{il} and A_{lk})).\n    // Hence we can obtain the column index set J directly by the following steps:\n    // (i) find all l with P_{li} nonzero -> L  [requires to access columns of P - compute the transpose patterns once]\n    // (ii) find all k with A_{lk} nonzero for some l in L -> K  [probably sorting K and removing doubled entries would be a good idea here]\n    // (iii) find all j with P_{kj} nonzero for some k in K -> J\n    // Compared to the above implementation this would have the following (dis)advantages\n    // + easy to do in parallel (since write operations are separated)\n    // + fewer scattered write accesses to memory\n    // - more complex implementation\n    // - requires the transpose pattern of P\n\n    // Create the sparse matrix.\n    timer.start(\"matrix creation\");\n    NumaBCRSMatrix<EntryA,IndexA> pap(creator);\n    timer.stop(\"matrix creation\");\n\n    // Fill the sparse matrix PAP. This is done as before by stepping through all Akl entries and scatter\n    // Pki*Plj*Akl into PAPij.\n    //\n    // An alternative way of computing P^TAP would be a gather operation with inverted loop order:\n    // Cij = sum_kl Pki*Plj*Akl. This requires P^T for efficient determination of required kl indices.\n    // While the transpose construction is efficient, the gather implementation ist not (tested 2016-01-17),\n    // presumably because A is larger than PAP and the scattered accesses have a worse locality.\n    // Sequential performance was more than 10-fold slower than the scatter implementation below, so\n    // we stick to the scatter.\n    //\n    // A second alternative is to create a triplet matrix first. This appears to be a factor 3 slower in\n    // sequential implementation, and incurs a high memory footprint as several entries are duplicate.\n\n    auto getEntryValues = [] (auto const& row, std::vector<EntryP>& vi)\n    {\n      vi.clear();\n      for (auto i=row.begin(); i!=row.end(); ++i)       // indices i for which Pki != 0\n        vi.push_back(*i);\n    };\n\n    auto getColumnIndices = [] (auto const& row, auto& ci)     // computes (global,local) column index pairs of row k of P\n    {\n      ci.clear();\n      int idx = 0;\n      for (auto i=row.begin(); i!=row.end(); ++i, ++idx)       // indices i for which Pki != 0\n        ci.push_back(std::make_pair(i.index(),idx));\n    };\n\n    timer.start(\"conjugation scatter\");\n    parallelFor([&](size_t block, size_t nBlocks)\n    {\n      size_t rowStart = uniformWeightRangeStart(block,nBlocks,A.N());\n      size_t rowEnd   = uniformWeightRangeStart(block+1,nBlocks,A.N());\n      std::vector<EntryP> pki, plj;\n      using SortedIndices = std::vector<std::pair<IndexP,int>>;\n      SortedIndices is, js;\n      LocalMatrices<EntryA,false,SortedIndices,SortedIndices> localMatrices(pap);\n      for (IndexA k=rowStart; k<rowEnd; ++k)\n      {\n        auto Pk = P[k];\n        getColumnIndices(Pk,is);                          // indices i for which Pki != 0\n        getEntryValues(Pk,pki);\n\n        auto row = A[k];\n        for (auto ca=row.begin(); ca!=row.end(); ++ca)\n        {\n          IndexA const l = ca.index();                    // column index of Akl\n          auto Pl = P[l];\n          getColumnIndices(Pl,js);                        // indices j for which Plj != 0\n          getEntryValues(Pl,plj);\n\n          // For each entry Akl of A we have to create one local matrix.\n          localMatrices.push_back(is,js);\n\n          auto Akl = *ca;\n          for (int i=0; i<is.size(); ++i)                 // just scatter Akl to all affected PAP entries\n          {\n            auto Pki_Akl = transpose(pki[i]) * Akl;\n            for (int j=0; j<plj.size(); ++j)\n              localMatrices.back()(i,j) = Pki_Akl * plj[j];\n          }\n\n          if (onlyLowerTriangle && k>l)\n          {\n            // treat Alk entry\n            abort();\n          }\n        }\n      }\n    },8*NumaThreadPool::instance().cpus());\n\n    timer.stop(\"conjugation scatter\");\n\n    return pap;\n  }\n\n  /**\n   * \\brief Computes the triple sparse matrix product \\f$ C = C + P^T A P \\f$.\n   *\n   * \\param C has to have a sparsity pattern that is a superset of the sparsity pattern of \\f$ P^T A P \\f$.\n   *\n   */\n  template <class Scalar, class Entry>\n  void conjugation(Dune::BCRSMatrix<Entry>& C,\n\t\t   Dune::BCRSMatrix<Dune::FieldMatrix<Scalar,1,1> > const& P,\n\t\t   Dune::BCRSMatrix<Entry> const& A,\n\t\t   bool onlyLowerTriangle = false )\n  {\n    assert(A.N()==A.M());\n    assert(A.N()==P.N());\n    assert(C.N()==P.M());\n    assert(C.M()==P.M());\n\n    typedef Dune::BCRSMatrix<Entry> MatA;\n    typedef Dune::BCRSMatrix<Dune::FieldMatrix<Scalar,1,1> > MatP;\n\n    if(onlyLowerTriangle == false )\n    {\n      // Step through all entries of A\n      for (int k=0; k<A.N(); ++k)\n        for (typename MatA::ConstColIterator ca=A[k].begin(); ca!=A[k].end(); ++ca)\n        {\n          int const l = ca.index();\n          // Step through all entries of rows k and l of P and add entry\n          for (typename MatP::ConstColIterator cpk=P[k].begin(); cpk!=P[k].end(); ++cpk)\n            for (typename MatP::ConstColIterator cpl=P[l].begin(); cpl!=P[l].end(); ++cpl)\n              C[cpk.index()][cpl.index()].axpy((*cpl) * (*cpk),(*ca));\n        }\n    }\n    else\n    {\n      // Step through all entries of A\n      for (int k=0; k<A.N(); ++k)\n        for (typename MatA::ConstColIterator ca=A[k].begin(); ca!=A[k].end(); ++ca)\n        {\n          int const l = ca.index();\n          for (typename MatP::ConstColIterator cpk=P[k].begin(); cpk!=P[k].end(); ++cpk)\n            for (typename MatP::ConstColIterator cpl=P[l].begin(); cpl!=P[l].end(); ++cpl)\n            {\n              if( cpk.index() >= cpl.index() )\n                C[cpk.index()][cpl.index()].axpy((*cpl) * (*cpk), (*ca) );\n            }\n          if(k>l)\n          {\n            for (typename MatP::ConstColIterator cpl=P[l].begin(); cpl!=P[l].end(); ++cpl)\n              for (typename MatP::ConstColIterator cpk=P[k].begin(); cpk!=P[k].end(); ++cpk)\n                if( cpl.index() >= cpk.index() )\n                  C[cpl.index()][cpk.index()].axpy((*cpl) * (*cpk) , (*ca) );\n          }\n        }\n    }\n  }\n}\n#endif\n\n\n", "meta": {"hexsha": "afe2300f727fa3ab31a7c9b7929f2f8a91034d4d", "size": 13479, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/linalg/conjugation.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/linalg/conjugation.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/linalg/conjugation.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 42.121875, "max_line_length": 140, "alphanum_fraction": 0.5724460272, "num_tokens": 3622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5365089663967947}}
{"text": "//=======================================================================\n// Copyright (c) 2013 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 scheduling_jobs_on_identical_parallel_machines_long_test.cpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2013-09-06\n */\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/scheduling.hpp\"\n#include \"test_utils/test_result_check.hpp\"\n\n#include \"paal/greedy/scheduling_jobs_on_identical_parallel_machines/scheduling_jobs_on_identical_parallel_machines.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\n#include <numeric>\n#include <vector>\n\nconst long long MAX_TIME = 1000000000;\nconst long MIN_MACHINES = 10;\nconst long MAX_MACHINES = 1000000;\nconst long STEP_MACHINES = 10;\nconst double MIN_JOBS_ON_MACHINE_START = 1.0;\nconst double MIN_JOBS_ON_MACHINE_END = 5.0;\nconst double MIN_JOBS_ON_MACHINE_STEP = 0.33;\nconst long SEED = 42;\nusing Time = long long;\n\nBOOST_AUTO_TEST_CASE(scheduling_jobs_on_identical_parallel_machines_long) {\n    std::srand(SEED);\n    for (int number_of_machines = MIN_MACHINES;\n         number_of_machines <= MAX_MACHINES;\n         number_of_machines *= STEP_MACHINES) {\n        for (double min_jobs_on_machine = MIN_JOBS_ON_MACHINE_START;\n             min_jobs_on_machine < MIN_JOBS_ON_MACHINE_END;\n             min_jobs_on_machine += MIN_JOBS_ON_MACHINE_STEP) {\n            LOGLN(\"machines: \" << number_of_machines);\n\n            std::vector<int> machines(number_of_machines);\n            std::vector<Time> jobs = generate_job_loads(\n                machines, min_jobs_on_machine, MAX_TIME,\n                paal::utils::return_one_functor());\n            LOGLN(\"jobs: \" << jobs.size());\n\n            std::vector<std::pair<int, decltype(jobs)::iterator>> result;\n\n            paal::greedy::scheduling_jobs_on_identical_parallel_machines(\n                number_of_machines, jobs.begin(), jobs.end(),\n                back_inserter(result), paal::utils::identity_functor());\n            check_jobs(result, jobs);\n            std::vector<Time> sum_of_machine;\n            sum_of_machine.resize(number_of_machines);\n            for (auto job_machine_pair : result) {\n                sum_of_machine[job_machine_pair.first] +=\n                    *(job_machine_pair.second);\n            }\n\n            Time maximum_load =\n                *std::max_element(sum_of_machine.begin(), sum_of_machine.end());\n\n            Time sum_all_loads = std::accumulate(sum_of_machine.begin(),\n                                                 sum_of_machine.end(), 0.0);\n            // print result\n            check_result(double(maximum_load),\n                         double(sum_all_loads) / number_of_machines, 4.0 / 3.0);\n        }\n    }\n}\n", "meta": {"hexsha": "5d9bff8d5c30b34296fec33f714edc68547bcd14", "size": 2918, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/greedy/scheduling_jobs_on_identical_parallel_machines_long_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/greedy/scheduling_jobs_on_identical_parallel_machines_long_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/greedy/scheduling_jobs_on_identical_parallel_machines_long_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": 37.8961038961, "max_line_length": 120, "alphanum_fraction": 0.627827279, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577159, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5365089641027389}}
{"text": "//\n//  main.cpp\n//  Task\n//\n//  Created by Elizabeth Lorelei on 15.11.2019.\n//  Copyright \u00a9 2019 Yelyzaveta Losieva. All rights reserved.\n//\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <array>\n#include <vector>\n#include <string>\n#include <cstdio>\n#include <algorithm>\n#include <fstream>\n\nusing namespace std;\nusing namespace Eigen;\n\n\nMatrix3d calcHomography(const array<Vector2d,4>& oldPoints,\n                        const array<Vector2d,4>& newPoints);\nvector <unsigned char> readBMP(string filename);\n\nint main()\n{\n    auto bmp = readBMP(\"/Users/elizabethlorelei/Downloads/Girl.bmp\");\n    Vector2d X1{0,1};\n    Vector2d X2{1,1};\n    Vector2d X3{1,0};\n    Vector2d X4{0,0};\n    Vector2d U1{0,1};\n    Vector2d U2{2,1};\n    Vector2d U3{2,0};\n    Vector2d U4{0,0};\n    Matrix3d homography{calcHomography({X1, X2, X3, X4}, {U1, U2, U3, U4})};\n    cout << homography << endl;\n}\n\nMatrix3d calcHomography(const array<Vector2d,4>& oldPoints,\n                        const array<Vector2d,4>& newPoints)\n{\n    Matrix<double,9,9> A{Matrix<double,9,9>::Zero()};\n    for (size_t i{0}; i<4; ++i)\n    {\n        auto X = oldPoints[i];\n        auto U = newPoints[i];\n        \n        A(2*i,0) = -X[0];\n        A(2*i,1) = -X[1];\n        A(2*i,2) = -1;\n        A(2*i,6) =  X[0]*U[0];\n        A(2*i,7) =  X[1]*U[0];\n        A(2*i,8) =  U[0];\n        \n        A(2*i+1,3) =  -X[0];\n        A(2*i+1,4) =  -X[1];\n        A(2*i+1,5) =  -1;\n        A(2*i+1,6) =  X[0]*U[1];\n        A(2*i+1,7) =  X[1]*U[1];\n        A(2*i+1,8) =  U[1];\n    }\n    A(8,8) = 1;\n    cout << A << endl;\n    Matrix<double,9,1> b{Matrix<double,9,1>::Zero()};\n    b(8) = 1;\n    Matrix<double,9,1> flattenRes {A.colPivHouseholderQr().solve(b)};\n    cout << endl << flattenRes << endl << endl;\n    Matrix3d res;\n    for (size_t i{0}; i<9; ++i)\n    {\n        res(i/3, i%3) = flattenRes[i];\n    }\n    return res;\n}\n\nvector<unsigned char> readBMP(string filename)\n{\n    int i;\n    ifstream inputFilestream{filename, ios_base::binary};\n    char info[54];\n    inputFilestream.get(info,54); // read the 54-byte header\n\n    // extract image height and width from header\n    int width = *(int*)&info[18];\n    int height = *(int*)&info[22];\n\n    int size = 3 * width * height;\n    char* data = new char[size]; // allocate 3 bytes per pixel\n    inputFilestream.get(data,size); // read the rest of the data at once\n    inputFilestream.close();\n\n    for(i = 0; i < size; i += 3)\n    {\n            char tmp = data[i];\n            data[i] = data[i+2];\n            data[i+2] = tmp;\n    }\n    vector<unsigned char> res(size);\n    copy(data, data + size, res.begin());\n    return res;\n}\n", "meta": {"hexsha": "f9399d094a044921e35ef0a8a0dd42c2f86902aa", "size": 2647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homography from Point Pairs/main 1.cpp", "max_stars_repo_name": "ElizaLo/Computer-Vision", "max_stars_repo_head_hexsha": "d9c6d65997f0fdcbf9f26cca94f56e5ec7e38762", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-08-19T14:54:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T06:11:29.000Z", "max_issues_repo_path": "Homography from Point Pairs/main 1.cpp", "max_issues_repo_name": "ElizaLo/Computer-Vision", "max_issues_repo_head_hexsha": "d9c6d65997f0fdcbf9f26cca94f56e5ec7e38762", "max_issues_repo_licenses": ["MIT"], "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 from Point Pairs/main 1.cpp", "max_forks_repo_name": "ElizaLo/Computer-Vision", "max_forks_repo_head_hexsha": "d9c6d65997f0fdcbf9f26cca94f56e5ec7e38762", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-24T13:42:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-24T13:42:52.000Z", "avg_line_length": 25.2095238095, "max_line_length": 76, "alphanum_fraction": 0.5496788818, "num_tokens": 903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5365047720257231}}
{"text": "/*\n    This file is part of Nori, a simple educational ray tracer\n\n    Copyright (c) 2012 by Wenzel Jakob and Steve Marschner.\n\n    Nori is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License Version 3\n    as published by the Free Software Foundation.\n\n    Nori 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#include <nori/camera.h>\n#include <nori/rfilter.h>\n#include <Eigen/Geometry>\n\nNORI_NAMESPACE_BEGIN\n\n/**\n * \\brief Perspective camera with depth of field\n *\n * This class implements a simple perspective camera model. By default, \n * it uses an infinitesimally small aperture, creating an infinite depth \n * of field. Use the <tt>apertureRadius</tt> and <tt>focusDistance</tt>\n * parameters to change this behavior.\n */\nclass PerspectiveCamera : public Camera {\npublic:\n\tPerspectiveCamera(const PropertyList &propList) {\n\t\t/* Width and height in pixels. Default: 720p */\n\t\tm_outputSize.x() = propList.getInteger(\"width\", 1280);\n\t\tm_outputSize.y() = propList.getInteger(\"height\", 720);\n\t\tm_invOutputSize = m_outputSize.cast<float>().cwiseInverse();\n\n\t\t/* Specifies an optional camera-to-world transformation. Default: none */\n\t\tm_cameraToWorld = propList.getTransform(\"toWorld\", Transform());\n\n\t\t/* Horizontal field of view in degrees */\n\t\tm_fov = propList.getFloat(\"fov\", 30.0f);\n\n\t\t/* Denotes the radios of the camera in scene units.\n\t\t   Default: 0, i.e. no depth of field */\n\t\tm_apertureRadius = propList.getFloat(\"apertureRadius\", 0.0f);\n\n\t\t/* Near and far clipping planes in world-space units */\n\t\tm_nearClip = propList.getFloat(\"nearClip\", 1e-4f);\n\t\tm_farClip = propList.getFloat(\"farClip\", 1e4f);\n\n\t\t/* Denotes the world-space distance from the camera's aperture\n\t\t   to the focal plane */\n\t\tm_focusDistance = propList.getFloat(\"focusDistance\", m_farClip);\n\n\t\tm_rfilter = NULL;\n\t}\n\n\tvoid activate() {\n\t\tfloat aspect = m_outputSize.x() / (float) m_outputSize.y();\n\n\t\t/* Project vectors in camera space onto a plane at z=1:\n\t\t *\n\t\t *  xProj = cot * x / z\n\t\t *  yProj = cot * y / z\n\t\t *  zProj = (far * (z - near)) / (z * (far-near))\n\t\t *  The cotangent factor ensures that the field of view is \n\t\t *  mapped to the interval [-1, 1].\n\t\t */\n\t\tfloat recip = 1.0f / (m_farClip - m_nearClip),\n\t\t      cot = 1.0f / std::tan(degToRad(m_fov / 2.0f));\n\n\t\tEigen::Matrix4f perspective;\n\t\tperspective <<\n\t\t\tcot, 0,   0,   0,\n\t\t\t0, cot,   0,   0,\n\t\t\t0,   0,   m_farClip * recip, -m_nearClip * m_farClip * recip,\n\t\t\t0,   0,   1,   0;\n\n\t\t/**\n\t\t * Translation and scaling to shift the clip coordinates into the\n\t\t * range from zero to one. Also takes the aspect ratio into account.\n\t\t */\n\t\tm_sampleToCamera = Transform( \n\t\t\tEigen::DiagonalMatrix<float, 3>(Vector3f(0.5f, -0.5f * aspect, 1.0f)) *\n\t\t\tEigen::Translation<float, 3>(1.0f, -1.0f/aspect, 0.0f) * perspective).inverse();\n\n\t\t/* If no reconstruction filter was assigned, instantiate a Gaussian filter */\n\t\tif (!m_rfilter)\n\t\t\tm_rfilter = static_cast<ReconstructionFilter *>(\n\t\t\t\tNoriObjectFactory::createInstance(\"gaussian\", PropertyList()));\n\t}\n\n\tColor3f sampleRay(Ray3f &ray,\n\t\t\tconst Point2f &samplePosition,\n\t\t\tconst Point2f &apertureSample) const {\n\t\tPoint2f tmp = squareToUniformDiskConcentric(apertureSample)\n\t\t\t* m_apertureRadius;\n\t\n\t\t/* Compute the corresponding position on the \n\t\t   near plane (in local camera space) */\n\t\tPoint3f nearP = m_sampleToCamera * Point3f(\n\t\t\tsamplePosition.x() * m_invOutputSize.x(),\n\t\t\tsamplePosition.y() * m_invOutputSize.y(), 0.0f);\n\n\t\tPoint3f apertureP(tmp.x(), tmp.y(), 0.0f);\n\n\t\t/* Sampled position on the focal plane */\n\t\tPoint3f focusP = nearP * (m_focusDistance / nearP.z());\n\n\t\t/* Aperture position */\n\t\t/* Turn these into a normalized ray direction, and\n\t\t   adjust the ray interval accordingly */\n\t\tVector3f d = (focusP - apertureP).normalized();\n\t\tfloat invZ = 1.0f / d.z();\n\n\t\tray.o = m_cameraToWorld * apertureP;\n\t\tray.d = m_cameraToWorld * d;\n\t\tray.mint = m_nearClip * invZ;\n\t\tray.maxt = m_farClip * invZ;\n\t\tray.update();\n\n\t\treturn Color3f(1.0f);\n\t}\n\n\tvoid addChild(NoriObject *obj) {\n\t\tswitch (obj->getClassType()) {\n\t\t\tcase EReconstructionFilter:\n\t\t\t\tif (m_rfilter)\n\t\t\t\t\tthrow NoriException(\"Camera: tried to register multiple reconstruction filters!\");\n\t\t\t\tm_rfilter = static_cast<ReconstructionFilter *>(obj);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tthrow NoriException(QString(\"Camera::addChild(<%1>) is not supported!\").arg(\n\t\t\t\t\tclassTypeName(obj->getClassType())));\n\t\t}\n\t}\n        \n        /// Return fov as parameter\n        virtual QString getParameters() const {\n                return QString(\"%1\").arg(m_fov);\n        }\n        \n        virtual Transform getTransform() const {\n                return m_cameraToWorld;\n        }\n        \n\t/// Return a human-readable summary\n\tQString toString() const {\n\t\treturn QString(\n\t\t\t\"PerspectiveCamera[\\n\"\n\t\t\t\"  cameraToWorld = %1,\\n\"\n\t\t\t\"  outputSize = %2,\\n\"\n\t\t\t\"  fov = %3,\\n\"\n\t\t\t\"  apertureRadius = %4,\\n\"\n\t\t\t\"  focusDistance = %5,\\n\"\n\t\t\t\"  clip = [%6, %7],\\n\"\n\t\t\t\"  rfilter = %8\\n\"\n\t\t\t\"]\")\n\t\t.arg(indent(m_cameraToWorld.toString(), 18))\n\t\t.arg(m_outputSize.toString())\n\t\t.arg(m_fov)\n\t\t.arg(m_apertureRadius)\n\t\t.arg(m_focusDistance)\n\t\t.arg(m_nearClip)\n\t\t.arg(m_farClip)\n\t\t.arg(indent(m_rfilter->toString()));\n\t}\nprivate:\n\tVector2f m_invOutputSize;\n\tTransform m_sampleToCamera;\n\tTransform m_cameraToWorld;\n\tfloat m_fov;\n\tfloat m_apertureRadius;\n\tfloat m_focusDistance;\n\tfloat m_nearClip;\n\tfloat m_farClip;\n};\n\nNORI_REGISTER_CLASS(PerspectiveCamera, \"perspective\");\nNORI_NAMESPACE_END\n", "meta": {"hexsha": "949c2a50cb74fb680a7e7f94bd5d79c2471a48f7", "size": 5826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hw4/src/perspective.cpp", "max_stars_repo_name": "jrabasco/acg2015", "max_stars_repo_head_hexsha": "419fd0fdf5293dda95ea0231cf6c6f4af5331120", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw4/src/perspective.cpp", "max_issues_repo_name": "jrabasco/acg2015", "max_issues_repo_head_hexsha": "419fd0fdf5293dda95ea0231cf6c6f4af5331120", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw4/src/perspective.cpp", "max_forks_repo_name": "jrabasco/acg2015", "max_forks_repo_head_hexsha": "419fd0fdf5293dda95ea0231cf6c6f4af5331120", "max_forks_repo_licenses": ["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.3225806452, "max_line_length": 87, "alphanum_fraction": 0.678510127, "num_tokens": 1648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5364745300428245}}
{"text": "//\n// Copyright (c) 2015-2019 CNRS INRIA\n//\n\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/compute-all-terms.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/center-of-mass.hpp\"\n#include \"pinocchio/utils/timer.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE ( test_com )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  pinocchio::Data data(model);\n\n  VectorXd q = VectorXd::Ones(model.nq);\n  q.middleRows<4> (3).normalize();\n  VectorXd v = VectorXd::Ones(model.nv);\n  VectorXd a = VectorXd::Ones(model.nv);\n\n  crba(model,data,q);\n\n\n\t/* Test COM against CRBA*/\n  Vector3d com = centerOfMass(model,data,q);\n  BOOST_CHECK(data.com[0].isApprox(getComFromCrba(model,data), 1e-12));\n\n\t/* Test COM against Jcom (both use different way to compute the COM). */\n  com = centerOfMass(model,data,q);\n  jacobianCenterOfMass(model,data,q);\n  BOOST_CHECK(com.isApprox(data.com[0], 1e-12));\n\n\t/* Test COM against Jcom (both use different way to compute the COM). */\n  centerOfMass(model,data,q,v,a);\n  BOOST_CHECK(com.isApprox(data.com[0], 1e-12));\n\n  /* Test vCoM against nle algorithm without gravity field */\n  a.setZero();\n  model.gravity.setZero();\n  centerOfMass(model,data,q,v,a);\n  nonLinearEffects(model, data, q, v);\n\n  pinocchio::SE3::Vector3 acom_from_nle (data.nle.head <3> ()/data.mass[0]);\n  BOOST_CHECK((data.liMi[1].rotation() * acom_from_nle).isApprox(data.acom[0], 1e-12));\n\n\t/* Test Jcom against CRBA  */\n  Eigen::MatrixXd Jcom = jacobianCenterOfMass(model,data,q);\n  BOOST_CHECK(data.Jcom.isApprox(getJacobianComFromCrba(model,data), 1e-12));\n\n  /* Test CoM velocity againt jacobianCenterOfMass */\n  BOOST_CHECK((Jcom * v).isApprox(data.vcom[0], 1e-12));\n\n\n  centerOfMass(model,data,q,v);\n  /* Test CoM velocity againt jacobianCenterOfMass */\n  BOOST_CHECK((Jcom * v).isApprox(data.vcom[0], 1e-12));\n\n\n//  std::cout << \"com = [ \" << data.com[0].transpose() << \" ];\" << std::endl;\n//  std::cout << \"mass = [ \" << data.mass[0] << \" ];\" << std::endl;\n//  std::cout << \"Jcom = [ \" << data.Jcom << \" ];\" << std::endl;\n//  std::cout << \"M3 = [ \" << data.M.topRows<3>() << \" ];\" << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE ( test_mass )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n\n  double mass = computeTotalMass(model);\n\n  BOOST_CHECK(mass == mass); // checking it is not NaN\n\n  double mass_check = 0.0;\n  for(size_t i=1; i<(size_t)(model.njoints);++i)\n    mass_check += model.inertias[i].mass();\n\n  BOOST_CHECK_CLOSE(mass, mass_check, 1e-12);\n\n  pinocchio::Data data1(model);\n\n  double mass_data = computeTotalMass(model,data1);\n\n  BOOST_CHECK(mass_data == mass_data); // checking it is not NaN\n  BOOST_CHECK_CLOSE(mass, mass_data, 1e-12);\n  BOOST_CHECK_CLOSE(data1.mass[0], mass_data, 1e-12);\n\n  pinocchio::Data data2(model);\n  VectorXd q = VectorXd::Ones(model.nq);\n  q.middleRows<4> (3).normalize();\n  centerOfMass(model,data2,q);\n\n  BOOST_CHECK_CLOSE(data2.mass[0], mass, 1e-12);\n}\n\nBOOST_AUTO_TEST_CASE ( test_subtree_masses )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n\n  pinocchio::Data data1(model);\n\n  computeSubtreeMasses(model,data1);\n\n  pinocchio::Data data2(model);\n  VectorXd q = VectorXd::Ones(model.nq);\n  q.middleRows<4> (3).normalize();\n  centerOfMass(model,data2,q);\n\n  for(size_t i=0; i<(size_t)(model.njoints);++i)\n  {\n    BOOST_CHECK_CLOSE(data1.mass[i], data2.mass[i], 1e-12);\n  }\n}\n\n//BOOST_AUTO_TEST_CASE ( test_timings )\n//{\n//  using namespace Eigen;\n//  using namespace pinocchio;\n//\n//  pinocchio::Model model;\n//  pinocchio::buildModels::humanoidRandom(model);\n//  pinocchio::Data data(model);\n//\n//  long flag = BOOST_BINARY(1111);\n//  PinocchioTicToc timer(PinocchioTicToc::US);\n//  #ifdef NDEBUG\n//    #ifdef _INTENSE_TESTING_\n//      const size_t NBT = 1000*1000;\n//    #else\n//      const size_t NBT = 10;\n//    #endif\n//  #else\n//    const size_t NBT = 1;\n//    std::cout << \"(the time score in debug mode is not relevant)  \" ;\n//  #endif\n//\n//  bool verbose = flag & (flag-1) ; // True is two or more binaries of the flag are 1.\n//  if(verbose) std::cout <<\"--\" << std::endl;\n//  Eigen::VectorXd q = Eigen::VectorXd::Zero(model.nq);\n//\n//  if( flag >> 0 & 1 )\n//  {\n//    timer.tic();\n//    SMOOTH(NBT)\n//    {\n//      centerOfMass(model,data,q);\n//    }\n//    if(verbose) std::cout << \"COM =\\t\";\n//    timer.toc(std::cout,NBT);\n//  }\n//\n//  if( flag >> 1 & 1 )\n//  {\n//    timer.tic();\n//    SMOOTH(NBT)\n//    {\n//      centerOfMass(model,data,q,false);\n//    }\n//    if(verbose) std::cout << \"Without sub-tree =\\t\";\n//    timer.toc(std::cout,NBT);\n//  }\n//\n//  if( flag >> 2 & 1 )\n//  {\n//    timer.tic();\n//    SMOOTH(NBT)\n//    {\n//      jacobianCenterOfMass(model,data,q);\n//    }\n//    if(verbose) std::cout << \"Jcom =\\t\";\n//    timer.toc(std::cout,NBT);\n//  }\n//}\n\nBOOST_AUTO_TEST_CASE(test_subtree_com_jacobian)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  Model model;\n  buildModels::humanoidRandom(model);\n  Data data(model);\n  \n  model.upperPositionLimit.head<3>().fill(1000);\n  model.lowerPositionLimit.head<3>() = -model.upperPositionLimit.head<3>();\n  VectorXd q = pinocchio::randomConfiguration(model);\n  VectorXd v = VectorXd::Random(model.nv);\n  \n  Data data_ref(model);\n  jacobianCenterOfMass(model,data_ref,q,true);\n  \n  centerOfMass(model, data, q, v);\n  Data::Matrix3x Jcom(3,model.nv); Jcom.setZero();\n  jacobianSubtreeCenterOfMass(model, data, 0, Jcom);\n  \n  BOOST_CHECK(Jcom.isApprox(data_ref.Jcom));\n\n  centerOfMass(model, data_ref, q, v, true);\n  computeJointJacobians(model, data_ref, q);\n  Data::Matrix3x Jcom_extracted(3,model.nv), Jcom_fd(3,model.nv);\n  Data data_extracted(model), data_fd(model);\n  const double eps = 1e-8;\n  jacobianCenterOfMass(model,data_extracted,q);\n  \n  // Get subtree jacobian and check that it is consistent with the com velocity\n  for(JointIndex joint_id = 1; joint_id < (JointIndex)model.njoints; joint_id++)\n  {\n    SE3::Vector3 subtreeComVelocityInWorld_ref = data_ref.oMi[joint_id].rotation() * data_ref.vcom[joint_id];\n    Jcom.setZero();\n    data.J.setZero();\n    jacobianSubtreeCenterOfMass(model, data, joint_id, Jcom);\n    \n    BOOST_CHECK(data.J.middleCols(model.joints[joint_id].idx_v(),data.nvSubtree[joint_id]).isApprox(data_ref.J.middleCols(model.joints[joint_id].idx_v(),data.nvSubtree[joint_id])));\n    SE3::Vector3 subtreeComVelocityInWorld = Jcom * v;\n    \n    Jcom_extracted.setZero();\n    getJacobianSubtreeCenterOfMass(model,data_extracted,joint_id,Jcom_extracted);\n    \n    // Check with finite differences\n    Eigen::VectorXd v_plus(model.nv); v_plus.setZero();\n    centerOfMass(model,data_fd,q);\n    const SE3::Vector3 com = data_fd.oMi[joint_id].act(data_fd.com[joint_id]);\n    Jcom_fd.setZero();\n    for(Eigen::DenseIndex k = 0; k < model.nv; ++k)\n    {\n      v_plus[k] = eps;\n      Eigen::VectorXd q_plus = integrate(model,q,v_plus);\n      centerOfMass(model,data_fd,q_plus);\n      const SE3::Vector3 com_plus = data_fd.oMi[joint_id].act(data_fd.com[joint_id]);\n      Jcom_fd.col(k) = (com_plus - com)/eps;\n      v_plus[k] = 0.;\n    }\n    \n//    Eigen::VectorXd q_plus = integrate(model,q,v*eps);\n//    centerOfMass(model,data_fd,q_plus);\n//    const SE3::Vector3 com_plus = data_fd.oMi[joint_id].act(data_fd.com[joint_id]);\n//    \n//    const SE3::Vector3 vcom_subtree_fd = (com_plus - com)/eps;\n\n    BOOST_CHECK(Jcom.isApprox(Jcom_fd,sqrt(eps)));\n    BOOST_CHECK(Jcom_extracted.isApprox(Jcom_fd,sqrt(eps)));\n    BOOST_CHECK(Jcom_extracted.isApprox(Jcom));\n    \n    BOOST_CHECK(std::fabs(data.mass[joint_id] - data_ref.mass[joint_id]) <= 1e-12);\n    BOOST_CHECK(data.com[joint_id].isApprox(data_ref.oMi[joint_id].act(data_ref.com[joint_id])));\n    BOOST_CHECK(subtreeComVelocityInWorld.isApprox(subtreeComVelocityInWorld_ref));\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END ()\n", "meta": {"hexsha": "4254833c194c88fff422eeb3ba3808fa0f5d4f55", "size": 8354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/com.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/com.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/com.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": 30.4890510949, "max_line_length": 181, "alphanum_fraction": 0.6791955949, "num_tokens": 2522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5364745125171895}}
{"text": "#pragma once\n\n#include \"PolynomialBasisGen.hh\"\n#include \"RBFKernel.hh\"\n#include \"FiniteDifferentiator.hh\"\n#include <Eigen/Dense>\n#include <utility>\n#include <vector>\n\nnamespace kt84 {\n\ntemplate <int _DimIn, int _DimOut, class _RBFKernel_Core, int _DegreePolynomial>\nstruct MLS\n    : public FiniteDifferentiator<MLS<_DimIn, _DimOut, _RBFKernel_Core, _DegreePolynomial>, _DimIn, _DimOut>\n{\n    enum {\n        DimIn  = _DimIn,\n        DimOut = _DimOut,\n        DegreePolynomial = _DegreePolynomial,\n    };\n    \n    typedef Eigen::Matrix<double, DimIn , 1> Point;\n    typedef Eigen::Matrix<double, DimOut, 1> Value;\n    typedef Eigen::Matrix<double, DimOut, DimIn> Gradient;\n    typedef PolynomialBasisGen<DimIn, DegreePolynomial> PolynomialBasisGen;\n    typedef RBFKernel_Bivariate<DimIn, _RBFKernel_Core> Kernel;\n    typedef std::pair<Point, Value> Constraint;\n    \n    static_assert(Kernel::Decaying, \"MLS requires its kernel to be decaying!\");\n    \n    std::vector<Constraint> constraints;\n    Kernel kernel;\n    \n    void clear_constraints() {\n        constraints.clear();\n    }\n    void add_constraint(const Point& point, const Value& value) {\n        constraints.push_back(Constraint(point, value));\n    }\n    Value operator()(const Point& point) const {\n        const int P = PolynomialBasisGen::DimOut;\n        Eigen::Matrix<double, P, P> A;\n        Eigen::Matrix<double, P, DimOut> b;\n        A.setZero();\n        b.setZero();\n        for (size_t i = 0; i < constraints.size(); ++i) {\n            const Point& point_i = constraints[i].first;\n            const Value& value_i = constraints[i].second;\n            double w_i = kernel(point, point_i);\n            if (w_i == std::numeric_limits<double>::infinity())\n                return value_i;\n            w_i = w_i * w_i;\n            PolynomialBasisGen::Basis basis_i = PolynomialBasisGen::basis(point_i);\n            A += w_i * basis_i * basis_i.transpose();\n            b += w_i * basis_i * value_i.transpose();\n        }\n        Eigen::Matrix<double, P, DimOut> c = A.colPivHouseholderQr().solve(b);\n        return c.transpose() * PolynomialBasisGen::basis(point);\n    }\n};\n\n// template specialization for 0-degree polynomial due to Eigen's inability to handle 1x1 matrix (which is scalar) coherently\ntemplate <int _DimIn, int _DimOut, class _RBFKernel_Core>\nstruct MLS<_DimIn, _DimOut, _RBFKernel_Core, 0>\n    : public FiniteDifferentiator<MLS<_DimIn, _DimOut, _RBFKernel_Core, 0>, _DimIn, _DimOut>\n{\n    enum {\n        DimIn  = _DimIn,\n        DimOut = _DimOut,\n        DegreePolynomial = 0,\n    };\n    \n    typedef Eigen::Matrix<double, DimIn , 1> Point;\n    typedef Eigen::Matrix<double, DimOut, 1> Value;\n    typedef Eigen::Matrix<double, DimOut, DimIn> Gradient;\n    typedef PolynomialBasisGen<DimIn, 0> PolynomialBasisGen;\n    typedef RBFKernel_Bivariate<DimIn, _RBFKernel_Core> Kernel;\n    typedef std::pair<Point, Value> Constraint;\n    \n    static_assert(Kernel::Decaying, \"MLS requires its kernel to be decaying!\");\n    \n    std::vector<Constraint> constraints;\n    Kernel kernel;\n    \n    void clear_constraints() {\n        constraints.clear();\n    }\n    void add_constraint(const Point& point, const Value& value) {\n        constraints.push_back(Constraint(point, value));\n    }\n    Value operator()(const Point& point) const {\n        Eigen::Matrix<double, 1, DimOut> b;\n        double A = 0;\n        b.setZero();\n        for (size_t i = 0; i < constraints.size(); ++i) {\n            const Point& point_i = constraints[i].first;\n            const Value& value_i = constraints[i].second;\n            double w_i = kernel(point, point_i);\n            if (w_i == std::numeric_limits<double>::infinity())\n                return value_i;\n            w_i = w_i * w_i;\n            PolynomialBasisGen::Basis basis_i = PolynomialBasisGen::basis(point_i);\n            A += w_i * basis_i * basis_i.transpose();\n            b += w_i * basis_i * value_i.transpose();\n        }\n        Eigen::Matrix<double, 1, DimOut> c = b / A;\n        return c.transpose() * PolynomialBasisGen::basis(point);\n    }\n};\n\n\n}\n\n", "meta": {"hexsha": "b61ec18757c2f08978f5e6e8b51029d15028b0a2", "size": 4069, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/math/MLS.hh", "max_stars_repo_name": "honoriocassiano/skbar", "max_stars_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kt84/math/MLS.hh", "max_issues_repo_name": "honoriocassiano/skbar", "max_issues_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T12:16:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T12:21:41.000Z", "max_forks_repo_path": "src/kt84/math/MLS.hh", "max_forks_repo_name": "honoriocassiano/skbar", "max_forks_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6929824561, "max_line_length": 125, "alphanum_fraction": 0.6370115507, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5364734976861408}}
{"text": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\nnamespace mp = boost::multiprecision;\ntypedef mp::number<mp::cpp_dec_float<0>> cdouble;\ntypedef mp::cpp_int cint;", "meta": {"hexsha": "d8df93949b8747beec0d086059b113e98a305237", "size": 207, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "util/cpp_int.hpp", "max_stars_repo_name": "hotman78/cpplib", "max_stars_repo_head_hexsha": "c2f85c8741cdd0b731a5aa828b28b38c70c8d699", "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": "util/cpp_int.hpp", "max_issues_repo_name": "hotman78/cpplib", "max_issues_repo_head_hexsha": "c2f85c8741cdd0b731a5aa828b28b38c70c8d699", "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": "util/cpp_int.hpp", "max_forks_repo_name": "hotman78/cpplib", "max_forks_repo_head_hexsha": "c2f85c8741cdd0b731a5aa828b28b38c70c8d699", "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": 41.4, "max_line_length": 49, "alphanum_fraction": 0.8019323671, "num_tokens": 53, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5364734976861408}}
{"text": "/*\nCopyright 2017-2018 Lars Pastewka, Andreas Greiner\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| OPT1 |\n--------\n\nThis is an implementation of the D2Q9 Lattice Boltzmann lattice in the simple\nrelaxation time approximation. The code reports the amplitude of a decaying\nshear wave which can be used to measure viscosity.\n\nThe present implementation contains was optimized with respect to opt1.\nThe optimization is identical to the opt1 Python code.\n\nThis code requires pybind11, Eigen and boost. Compile with\nc++ -O3 -Wall -std=c++11 -I/usr/local/Cellar/pybind11/2.2.3/include -I/usr/local/Cellar/eigen/3.3.5/include/eigen3 shear_wave_opt0.cpp -o shear_wave_opt0\n*/\n\n#include <boost/range/combine.hpp>\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Dense>\n\nclass D2Q9 {\npublic:\n    using Density_t = double;\n    using Velocity_t = double;\n    using Probability_t = Eigen::Matrix<double, 9, 1>;\n\n    using ChannelVelocity_t = Eigen::Matrix<int, 2, 9>;\n    using Weight_t = Eigen::Array<double, 9, 1>;\n\n    using DensityField_t = std::vector<Density_t>;\n    using VelocityField_t = std::vector<Velocity_t>;\n    using ProbabilityField_t = std::vector<Probability_t>;\n\n    const ChannelVelocity_t c_ci;\n\n    static constexpr double w_0 = 4./9;\n    static constexpr double w_1234 = 1./9;\n    static constexpr double w_5678 = 1./36;\n\n    D2Q9(int nx, int ny, double omega):\n        c_ci((ChannelVelocity_t() << 0,  1,  0, -1,  0,  1, -1, -1,  1,\n                                     0,  0,  1,  0, -1,  1,  1, -1, -1).finished()) {\n        this->nx = nx;\n        this->ny = ny;\n        this->omega = omega;\n    }\n\n    Probability_t equilibrium(double rho, Velocity_t ux, Velocity_t uy) {\n        double cu5 = ux + uy;\n        double cu6 = -ux + uy;\n        double cu7 = -ux - uy;\n        double cu8 = ux - uy;\n        double uu = ux*ux + uy*uy;\n        return (Probability_t() <<\n            w_0*rho*(1 - 3./2*uu),\n            w_1234*rho*(1 + 3*ux + 9./2*ux*ux - 3./2*uu),\n            w_1234*rho*(1 + 3*uy + 9./2*uy*uy - 3./2*uu),\n            w_1234*rho*(1 - 3*ux + 9./2*ux*ux - 3./2*uu),\n            w_1234*rho*(1 - 3*uy + 9./2*uy*uy - 3./2*uu),\n            w_5678*rho*(1 + 3*cu5 + 9./2*cu5*cu5 - 3./2*uu),\n            w_5678*rho*(1 + 3*cu6 + 9./2*cu6*cu6 - 3./2*uu),\n            w_5678*rho*(1 + 3*cu7 + 9./2*cu7*cu7 - 3./2*uu),\n            w_5678*rho*(1 + 3*cu8 + 9./2*cu8*cu8 - 3./2*uu)).finished();\n    }\n\n    void equilibrium(DensityField_t &rho_kl,\n                     VelocityField_t &ux_kl, VelocityField_t &uy_kl,\n                     ProbabilityField_t &f_kli) {\n        for (auto && tup: boost::combine(rho_kl, ux_kl, uy_kl, f_kli)) {\n            auto && rho = tup.get<0>();\n            auto && ux = tup.get<1>();\n            auto && uy = tup.get<2>();\n            auto && f_i = tup.get<3>();\n            f_i = this->equilibrium(rho, ux, uy);\n        }\n    }\n\n    void equilibrium(double rho, Velocity_t &ux, Velocity_t &uy,\n                     ProbabilityField_t &f_kli) {\n        for (auto && f_i: f_kli) {\n            f_i = this->equilibrium(rho, ux, uy);\n        }\n    }\n\n    void collide(ProbabilityField_t &f_kli) {\n        for (auto && f_i: f_kli) {\n            double rho = f_i.sum();\n            Velocity_t ux = (f_i(1) - f_i(3) + f_i(5) - f_i(6) - f_i(7) + f_i(8))/rho;\n            Velocity_t uy = (f_i(2) - f_i(4) + f_i(5) + f_i(6) - f_i(7) - f_i(8))/rho;\n            f_i += this->omega*(equilibrium(rho, ux, uy) - f_i);\n        }\n    }\n\n    void stream(ProbabilityField_t &f_kli) {\n        ProbabilityField_t g_kli(f_kli.size());\n        auto f_i = f_kli.begin();\n        for (int l = 0; l < this->ny; ++l) {\n            for (int k = 0; k < this->nx; ++k, ++f_i) {\n                for (int i = 0; i < 9; i++) {\n                    int k1 = k + this->c_ci(0, i);\n                    while (k1 < 0) k1 += this->nx;\n                    while (k1 >= this->nx) k1 -= this->nx;\n                    int l1 = l + this->c_ci(1, i);\n                    while (l1 < 0) l1 += this->ny;\n                    while (l1 >= this->ny) l1 -= this->ny;\n                    g_kli[l1*this->nx + k1](i) = (*f_i)(i);\n                }\n            }\n        }\n        f_kli = g_kli;\n    }\nprivate:\n    int nx, ny;\n    double omega;\n};\n\nint main(int argc, char *argv[])\n{\n    int nx = 300;\n    int ny = 300;\n    int nsteps = 1000;\n    double omega = 0.3;\n    D2Q9 lb(nx, ny, omega);\n    D2Q9::ProbabilityField_t f_kli(nx*ny);\n\n    auto f_i = f_kli.begin();\n    for (int l = 0; l < ny; ++l) {\n        for (int k = 0; k < nx; ++k, ++f_i) {\n            D2Q9::Velocity_t uy = std::sin(2*M_PI/nx*k);\n            *f_i = lb.equilibrium(1.0, 0.0, uy);\n        }\n    }\n\n    for (int n = 0; n < nsteps; ++n) {\n        lb.stream(f_kli);\n        lb.collide(f_kli);\n\n        double accum = 0.0;\n        for (int k = 0; k < nx; ++k)\n            accum += (lb.c_ci.cast<double>()*f_kli[ny/2*nx+k])(1)*std::sin(2*M_PI/nx*k);\n        std::cout << accum*2/nx << std::endl;\n    }\n}\n", "meta": {"hexsha": "c8843cce703a76cbbb25a329cf9eca7bc085a3ad", "size": 5954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulators/serial_shear_wave/C++/shear_wave_opt1.cpp", "max_stars_repo_name": "pastewka/LBWithPython", "max_stars_repo_head_hexsha": "a913683afa55b77395189b4c5d95f836599a91cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-19T13:48:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:48:28.000Z", "max_issues_repo_path": "simulators/serial_shear_wave/C++/shear_wave_opt1.cpp", "max_issues_repo_name": "IMTEK-Simulation/LBWithPython", "max_issues_repo_head_hexsha": "a913683afa55b77395189b4c5d95f836599a91cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-08T09:24:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T09:24:42.000Z", "max_forks_repo_path": "simulators/serial_shear_wave/C++/shear_wave_opt1.cpp", "max_forks_repo_name": "IMTEK-Simulation/LBWithPython", "max_forks_repo_head_hexsha": "a913683afa55b77395189b4c5d95f836599a91cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T14:24:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-15T15:12:52.000Z", "avg_line_length": 35.8674698795, "max_line_length": 153, "alphanum_fraction": 0.5673496809, "num_tokens": 1871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5364734859326198}}
{"text": "// Flatten.cpp : Defines the entry point for the console application.\r\n//\r\n\r\n#include \"stdafx.h\"\r\n\r\n#include <time.h>\r\n#include <iostream>\r\n#include <vector>\r\n#include <fstream>\r\n#include <optional>\r\n#include <string>\r\n#include <algorithm>\r\n#include <Eigen/Core>\r\n#include <Eigen/Dense>\r\n#include <Eigen/Geometry> // For Quaternion\r\n\r\n#include \"FLAE.h\"\r\n#include \"GARotorEstimator.h\"\r\n#include \"ArunSVD.h\"\r\n#include \"Horn.h\"\r\n#include \"GAValkenburg.h\"\r\n#include \"FA3R.h\"\r\n#include \"Davenport.h\"\r\n#include \"Quest.h\"\r\n#include \"QuaternionDirect.h\"\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\nusing namespace std::placeholders;\r\n\r\nVector3d getRandomVector()\r\n{\r\n\tauto e0 = (double)rand() / (double)RAND_MAX;\r\n\tauto e1 = (double)rand() / (double)RAND_MAX;\r\n\tauto e2 = (double)rand() / (double)RAND_MAX;\r\n\r\n\tauto v = Vector3d(e0, e1, e2);\r\n\treturn v.normalized();\r\n}\r\n\r\ndouble getRandom()\r\n{\r\n\treturn (double)rand() / (double)RAND_MAX;\r\n}\r\n\r\ndouble WahbaError(const vector<Vector3d>& P, const vector<Vector3d>& Q, const Quaterniond& R)\r\n{\r\n\tconst size_t N = P.size();\r\n\tdouble error = 0;\r\n\tfor (size_t i = 0; i < N; ++i)\r\n\t{\r\n\t\terror += (R._transformVector(P[i]) - Q[i]).squaredNorm();\r\n\t}\r\n\treturn error;\r\n}\r\n\r\ndouble WahbaError(const vector<Vector3d>& P, const vector<Vector3d>& Q, const Matrix3d& R)\r\n{\r\n\tconst size_t N = P.size();\r\n\tdouble error = 0;\r\n\tfor (size_t i = 0; i < N; ++i)\r\n\t{\r\n\t\terror += (R*P[i] - Q[i]).squaredNorm();\r\n\t}\r\n\treturn error;\r\n}\r\n\r\ntemplate<typename ResultType>\r\ndouble benchmark(\r\n\tconst vector<Vector3d>& P, \r\n\tconst vector<Vector3d>& Q, \r\n\tconst vector<double>& weights, \r\n\tfunction<ResultType(const vector<Vector3d>&, const vector<Vector3d>&, const vector<double>&)> estimator)\r\n{\r\n\tResultType result;\r\n\tdouble total = 0;\r\n\tfor (int i = 0; i < 1000000; ++i) {\r\n\t\tclock_t time1 = clock();\r\n\t\tresult = estimator(P, Q, weights);\r\n\t\tclock_t time2 = clock();\r\n\t\ttotal += time2 - time1;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\n\r\nclass log_stream {\r\npublic:\r\n\tstd::ofstream log;\r\n\t\r\n\tlog_stream(const string& filename) : log(filename)\r\n\t{\r\n\t\tlog.precision(15);\r\n\t\tstd::cout.precision(15);\r\n\t}\r\n\r\n\tlog_stream& operator << (ostream& (*pfun)(ostream&)) {\r\n\t\tpfun(log);\r\n\t\tpfun(std::cout);\r\n\t\treturn *this;\r\n\t}\r\n};\r\n\r\ntemplate <typename T>\r\nlog_stream& operator << (log_stream& st, T val) {\r\n\tst.log << val;\r\n\tstd::cout << val;\r\n\treturn st;\r\n};\r\n\r\nenum class DataPlanes { NONE, X, Y, Z };\r\nclass CommandLineParams {\r\npublic:\r\n\tstring filename;\r\n\tDataPlanes dataPlane;\r\n\tsize_t N;\r\n\tbool noise;\r\n\toptional<double> norm;\r\n\toptional<Vector3d> axis;\r\n\toptional<double> angle;\r\n\r\n\tCommandLineParams(int argc, char* argv[]) {\r\n\t\tset_defaults();\r\n\t\tfor(size_t i = 1 ; i < argc ; ++i) {\r\n\t\t\tstring param(argv[i]);\r\n\t\t\tstring key, value;\r\n\t\t\tint pos = param.find('=', 0);\r\n\t\t\tif(pos > 0) {\r\n\t\t\t\tkey = param.substr(0, pos);\r\n\t\t\t\tstd::transform(key.begin(), key.end(), key.begin(), ::tolower);\r\n\t\t\t\tvalue = param.substr(pos+1, param.length()-pos-1);\r\n\t\t\t\tstd::transform(value.begin(), value.end(), value.begin(), ::tolower);\r\n\t\t\t} else {\r\n\t\t\t\tkey = param;\r\n\t\t\t}\r\n\t\t\tif(key == \"--name\") {\r\n\t\t\t\tfilename = value;\r\n\t\t\t} else if(key == \"--plane\") {\r\n\t\t\t\tif(value==\"x\") dataPlane = DataPlanes::X;\r\n\t\t\t\tif(value==\"y\") dataPlane = DataPlanes::Y;\r\n\t\t\t\tif(value==\"z\") dataPlane = DataPlanes::Z;\r\n\t\t\t} else if(key == \"--n\") {\r\n\t\t\t\t N = std::stoul(value);\r\n\t\t\t} else if(key == \"--noise\") {\r\n\t\t\t\tnoise = value == \"true\";\r\n\t\t\t} else if(key == \"--norm\") {\r\n\t\t\t\tnorm = std::stod(value);\t\t\t\t\r\n\t\t\t} else if(key == \"--axis\") {\r\n\t\t\t\tint prev = 0;\r\n\t\t\t\tpos = value.find(',', 0);\r\n\t\t\t\tdouble x = std::stod(value.substr(prev, pos));\r\n\t\t\t\tprev = pos;\r\n\t\t\t\tpos = value.find(',', pos+1);\r\n\t\t\t\tdouble y = std::stod(value.substr(prev+1, pos-prev-1));\r\n\t\t\t\tprev = pos;\r\n\t\t\t\tdouble z = std::stod(value.substr(prev+1, value.length()-prev-1));\r\n\t\t\t\taxis = Vector3d(x, y, z);\r\n\t\t\t} else if(key == \"--angle\") {\r\n\t\t\t\tangle = std::stod(value);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid set_defaults() {\r\n\t\tfilename = \"out.txt\";\r\n\t\tdataPlane = DataPlanes::NONE;\r\n\t\tN = 1000;\r\n\t\tnoise = true;\r\n\t}\r\n};\r\n\r\nvoid show_usage(log_stream& log, CommandLineParams& params)\r\n{\r\n\tlog << \"Params: \" << std::endl;\r\n\tlog << \"      \"\r\n\t\t<< \" --name=\" << params.filename\r\n\t\t<< \" --plane=\" << (params.dataPlane == DataPlanes::X ? \"x\" : params.dataPlane == DataPlanes::Y ? \"y\" : params.dataPlane == DataPlanes::Z ? \"z\" : \"[x|y|z]\")\r\n\t\t<< \" --n=\" << params.N\r\n\t\t<< \" --noise=\" << (params.noise ? \"true\" : \"false\");\r\n\tif(params.norm.has_value())\r\n\t\tlog << \" --norm=\" << params.norm.value_or(1);\r\n\telse\r\n\t\tlog << \" --norm=[double]\";\r\n\tif(params.axis.has_value()) {\r\n\t\tauto axis = params.axis.value_or(Vector3d(0,0,1));\r\n\t\tlog << \" --axis=\" << axis.x() << \",\" << axis.y() << \",\" << axis.z();\r\n\t}\r\n\telse\r\n\t\tlog << \" --axis=[double,double,double]\";\r\n\tif(params.angle.has_value())\r\n\t\tlog << \" --angle=\" << params.angle.value_or(EIGEN_PI);\r\n\telse\r\n\t\tlog << \" --angle=[double]\";\r\n\tlog << std::endl << std::endl;\r\n}\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\tsrand(static_cast<unsigned>(time(NULL)));\r\n\r\n\tCommandLineParams params(argc, argv);\r\n\r\n\tlog_stream log(params.filename);\r\n\r\n\tshow_usage(log, params);\r\n\t\r\n\tvector<Vector3d> pointsOriginal;\r\n\tvector<Vector3d> pointsTransformed;\r\n\tvector<double> weights;\r\n\tconst size_t N = params.N;\r\n\r\n\tdouble totalNorms = 0;\r\n\t// Initialize the lines\r\n\tfor(size_t i = 0 ; i < N ; ++i)\r\n\t{\r\n\t\tdouble norm = params.norm.value_or((rand() % 1000) + 1.0); // 1 to 1000 continuous\r\n\t\tEigen::Vector3d v = getRandomVector() * norm;\r\n\t\tswitch(params.dataPlane) {\r\n\t\t\tcase DataPlanes::X: v[0] = 0; break;\r\n\t\t\tcase DataPlanes::Y: v[1] = 0; break;\r\n\t\t\tcase DataPlanes::Z: v[2] = 0; break;\r\n\t\t\tcase DataPlanes::NONE:\r\n\t\t\tdefault: break;\r\n\t\t}\r\n\t\tpointsOriginal.push_back(v);\r\n\t\tweights.push_back(norm);\r\n\t\ttotalNorms += norm;\r\n\t}\r\n\tfor(size_t i = 0 ; i < N ; ++i)\r\n\t{\r\n\t\tweights[i] /= totalNorms;\r\n\t}\r\n\r\n\tEigen::Vector3d axis = params.axis.value_or(getRandomVector());\r\n\tauto angle = params.angle.value_or(4 * EIGEN_PI * getRandom());\r\n\tQuaterniond Q;\r\n\tQ = AngleAxisd(angle, axis);\r\n\r\n\tfor(size_t i = 0 ; i < N ; ++i)\r\n\t{\r\n\t\tif(params.noise)\r\n\t\t\tpointsTransformed.push_back((Q * AngleAxisd(2*EIGEN_PI * getRandom(), getRandomVector()))._transformVector(pointsOriginal[i]));\r\n\t\telse\r\n\t\t\tpointsTransformed.push_back(Q._transformVector(pointsOriginal[i]));\r\n\t}\r\n\r\n\tQuaterniond QI;\r\n\tQI.setIdentity();\r\n\r\n\tQuaterniond flaeQ = Flae(pointsOriginal, pointsTransformed, weights);\r\n\tQuaterniond flaeSymbolicQ = FlaeSymbolic(pointsOriginal, pointsTransformed, weights);\r\n\tQuaterniond flaeNewtonQ = FlaeNewton(pointsOriginal, pointsTransformed, weights);\r\n\tMatrix3d FA3EDoubleM = FA3R_double(pointsOriginal, pointsTransformed, weights);\r\n\tMatrix3d FA3EIntM = FA3R_int(pointsOriginal, pointsTransformed, weights);\r\n\tQuaterniond  GAQ = GARotorEstimator(pointsOriginal, pointsTransformed, weights);\r\n\tQuaterniond  LAQ = LARotorEstimator(pointsOriginal, pointsTransformed, weights);\r\n\tMatrix3d  svdM = SVDMcAdams(pointsOriginal, pointsTransformed, weights);\r\n\tMatrix3d  svdE = SVDEigen(pointsOriginal, pointsTransformed, weights);\r\n\tQuaterniond hornQ = Horn(pointsOriginal, pointsTransformed, weights);\r\n\tQuaterniond GAValkenburgQ = GAValkenburg(pointsOriginal, pointsTransformed, weights);\r\n\tQuaterniond davenportQ = Davenport(pointsOriginal, pointsTransformed, weights);\r\n\tQuaterniond questQ = Quest(pointsOriginal, pointsTransformed, weights);\r\n\tMatrix3d foamQ = Foam(pointsOriginal, pointsTransformed, weights);\r\n\tQuaterniond qDirect = QuaternionDirect(pointsOriginal, pointsTransformed, weights);\r\n\r\n\tdouble errorGroundTruth = WahbaError(pointsOriginal, pointsTransformed, Q);\r\n\tdouble errorFlae = WahbaError(pointsOriginal, pointsTransformed, flaeQ);\r\n\tdouble errorFlaeSymbolic = WahbaError(pointsOriginal, pointsTransformed, flaeSymbolicQ);\r\n\tdouble errorFlaeNewton = WahbaError(pointsOriginal, pointsTransformed, flaeNewtonQ);\r\n\tdouble errorFA3RDouble = WahbaError(pointsOriginal, pointsTransformed, FA3EDoubleM);\r\n\tdouble errorFA3RInt = WahbaError(pointsOriginal, pointsTransformed, FA3EIntM);\r\n\tdouble errorGA = WahbaError(pointsOriginal, pointsTransformed, GAQ);\r\n\tdouble errorLA = WahbaError(pointsOriginal, pointsTransformed, LAQ);\r\n\tdouble errorSVD = WahbaError(pointsOriginal, pointsTransformed, svdM);\r\n\tdouble errorSVDE = WahbaError(pointsOriginal, pointsTransformed, svdE);\r\n\tdouble errorHorn = WahbaError(pointsOriginal, pointsTransformed, hornQ);\r\n\tdouble errorGAValkenburg = WahbaError(pointsOriginal, pointsTransformed, GAValkenburgQ);\r\n\tdouble errorDavenport = WahbaError(pointsOriginal, pointsTransformed, davenportQ);\r\n\tdouble errorQuest = WahbaError(pointsOriginal, pointsTransformed, questQ);\r\n\tdouble errorFoam = WahbaError(pointsOriginal, pointsTransformed, foamQ);\r\n\tdouble errorQDirect = WahbaError(pointsOriginal, pointsTransformed, qDirect);\r\n\r\n\tlog << \"Axis                                      : \" << axis.x() << \", \" << axis.y() << \", \" << axis.z() << std::endl;\r\n\tlog << \"Angle                                     : \" << angle << std::endl;\r\n\r\n\tlog << \"Comparisons: \" << std::endl << std::endl;\r\n\t//log << \"Ground Truth error                        \" << errorGroundTruth << endl;\r\n\tlog << \"FLAE error                                \" << errorFlae << endl;\r\n\tlog << \"FLAE Symbolic error                       \" << errorFlaeSymbolic << endl;\r\n\tlog << \"FLAE Newton error                         \" << errorFlaeNewton << endl;\r\n\tlog << \"FA3R Double error                         \" << errorFA3RDouble << endl;\r\n\tlog << \"FA3R Int error                            \" << errorFA3RInt << endl;\r\n\tlog << \"GA Rotor Estimator error                  \" << errorGA << endl;\r\n\tlog << \"LA Rotor Estimator error                  \" << errorLA << endl;\r\n\tlog << \"Davenport error                           \" << errorDavenport << endl;\r\n\tlog << \"Quest error                               \" << errorQuest << endl;\r\n\tlog << \"Foam error                                \" << errorFoam << endl;\r\n\tlog << \"GA Valkenburg error                       \" << errorGAValkenburg << endl;\r\n\tlog << \"SVD McAdams error                         \" << errorSVD << endl;\r\n\tlog << \"SVD error                                 \" << errorSVDE << endl;\r\n\tlog << \"Horn error                                \" << errorHorn << endl;\r\n\tlog << \"Quaternion Direct error                   \" << errorQDirect << endl;\r\n\r\n\tdouble total;\r\n\ttotal = benchmark<Quaterniond>(pointsOriginal, pointsTransformed, weights, Flae);\r\n\tlog << \"Exec time FLAE:                           \"<< total / double(CLOCKS_PER_SEC) << \" sec.\" << endl;\r\n\r\n\ttotal = benchmark<Quaterniond>(pointsOriginal, pointsTransformed, weights, FlaeSymbolic);\r\n\tlog << \"Exec time FLAE Symbolic:                  \" << total / double(CLOCKS_PER_SEC) << \" sec.\" << endl;\r\n\r\n\ttotal = benchmark<Quaterniond>(pointsOriginal, pointsTransformed, weights, FlaeNewton);\r\n\tlog << \"Exec time FLAE Newton:                    \" << total / double(CLOCKS_PER_SEC) << \" sec.\" << endl;\r\n\r\n\ttotal = benchmark<Matrix3d>(pointsOriginal, pointsTransformed, weights, FA3R_double);\r\n\tlog << \"Exec time FA3R Double:                    \" << total / double(CLOCKS_PER_SEC) << \" sec.\" << endl;\r\n\r\n\ttotal = benchmark<Matrix3d>(pointsOriginal, pointsTransformed, weights, FA3R_int);\r\n\tlog << \"Exec time FA3R Int:                       \" << total / double(CLOCKS_PER_SEC) << \" sec.\" << endl;\r\n\r\n\ttotal = benchmark<Quaterniond>(pointsOriginal, pointsTransformed, weights, LARotorEstimator);\r\n\tlog << \"Exec time LARotorEstimator:               \" << total / double(CLOCKS_PER_SEC)  << \" sec.\" << endl;\r\n\r\n\ttotal = benchmark<Quaterniond>(pointsOriginal, pointsTransformed, weights, Davenport);\r\n\tlog << \"Exec time Davenport Q-Method:             \" << total / double(CLOCKS_PER_SEC) << \" sec.\" << endl;\r\n\r\n\ttotal = benchmark<Quaterniond>(pointsOriginal, pointsTransformed, weights, Quest);\r\n\tlog << \"Exec time QUEST:                          \" << total / double(CLOCKS_PER_SEC) << \" sec.\" << endl;\r\n\r\n\ttotal = benchmark<Matrix3d>(pointsOriginal, pointsTransformed, weights, Foam);\r\n\tlog << \"Exec time FOAM:                           \" << total / double(CLOCKS_PER_SEC) << \" sec.\" << endl;\r\n\r\n\ttotal = benchmark<Quaterniond>(pointsOriginal, pointsTransformed, weights, GAValkenburg);\r\n\tlog << \"Exec time GA Valkenburg:                  \" << total / double(CLOCKS_PER_SEC) << \" sec.\" << endl;\r\n\r\n\ttotal = benchmark<Matrix3d>(pointsOriginal, pointsTransformed, weights, SVDMcAdams);\r\n\tlog << \"Exec time SVD McAdams:                    \" << total / double(CLOCKS_PER_SEC) << \" sec.\" << endl;\r\n\r\n\ttotal = benchmark<Matrix3d>(pointsOriginal, pointsTransformed, weights, SVDEigen);\r\n\tlog << \"Exec time SVD:                            \" << total / double(CLOCKS_PER_SEC) << \" sec.\" << endl;\r\n\r\n\ttotal = benchmark<Quaterniond>(pointsOriginal, pointsTransformed, weights, Horn);\r\n\tlog << \"Exec time Horn:                           \" << total / double(CLOCKS_PER_SEC) << \" sec.\" << endl;\r\n\r\n\tlog << \"FINISHED...\" << endl;\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "c20a2c84e692eb68280b91087bb085c4128bbbad", "size": 12952, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "mauriciocele/fast-rotor-estimation", "max_stars_repo_head_hexsha": "1ee3f5a4aaee83f66e8ced209c2891b6e2045856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-28T15:34:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T06:04:03.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "mauriciocele/fast-rotor-estimation", "max_issues_repo_head_hexsha": "1ee3f5a4aaee83f66e8ced209c2891b6e2045856", "max_issues_repo_licenses": ["MIT"], "max_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": "mauriciocele/fast-rotor-estimation", "max_forks_repo_head_hexsha": "1ee3f5a4aaee83f66e8ced209c2891b6e2045856", "max_forks_repo_licenses": ["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.325648415, "max_line_length": 158, "alphanum_fraction": 0.6232242125, "num_tokens": 3390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5363764743553169}}
{"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 *      120530    M.I. Ganeff       Code created.\n *      121004    M.I. Ganeff       Input parameter types and variable-naming updated.\n *      121018    M.I. Ganeff       Added computeSphereOfInfluence().\n *      121123    D. Dirkx          Added computeSphereOfInfluence() function taking mass ratios;\n *                                  updated implementation of computeSphereOfInfluence() taking\n *                                  masses.\n *      130225    D. Dirkx          Added isOrbitRetrograde(...) functions taking inclination and\n *                                  Kepler vector.\n *      130227    D. Dirkx          Set isRetrograde at initialization to 0.\n *      130301    R.C.A. Boon       Minor textual changes, changed mathematics::PI to\n *      130305    R.C.A. Boon       Replaced Eigen::VectorXd by basic_mathematics::Vector6d\n *                                  mathematical_constants::PI.\n *      131212    S. Billemont      Fixed pass-by-reference error in isOrbitRetrograde()-function.\n *\n *    References\n *      Montebruck O, Gill E. Satellite Orbits, Corrected Third Printing, Springer, 2005.\n *      Bate R. Fundamentals of Astrodynamics, Courier Dover Publications, 1971.\n *\n *    Notes\n *\n */\n\n#include <Eigen/Core>\n#include <cmath>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/missionGeometry.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\n\nnamespace tudat\n{\n\nnamespace mission_geometry\n{\n\n//! Compute whether an orbit is retrograde based on inclination.\nbool isOrbitRetrograde( const double inclination )\n{\n    bool isRetrograde = false;\n\n    // Check which range inclination is in and return value accordingly.\n    if ( inclination < 0.0 || inclination > mathematical_constants::PI )\n    {\n        throw std::runtime_error(\n                    \"The inclination is in the wrong range when determining retrogradeness\" );\n    }\n    else if ( inclination <= mathematical_constants::PI / 2.0 )\n    {\n        isRetrograde = false;\n    }\n    else if ( inclination > mathematical_constants::PI / 2.0 )\n    {\n        isRetrograde = true;\n    }\n\n    return isRetrograde;\n}\n\n//! Compute whether an orbit is retrograde based on Keplerian state.\nbool isOrbitRetrograde( const basic_mathematics::Vector6d& keplerElements )\n{\n    // Get inclination from vector and call overloaded function.\n    return isOrbitRetrograde(\n                keplerElements(\n                    orbital_element_conversions::inclinationIndex ) );\n}\n\n//! Compute the shadow function.\ndouble computeShadowFunction( const Eigen::Vector3d& occultedBodyPosition,\n                              const double occultedBodyRadius,\n                              const Eigen::Vector3d& occultingBodyPosition,\n                              const double occultingBodyRadius,\n                              const Eigen::Vector3d& satellitePosition )\n{\n    // Calculate coordinates of the spacecraft with respect to the occulting body.\n    const Eigen::Vector3d satellitePositionRelativeToOccultingBody = satellitePosition\n            - occultingBodyPosition;\n\n    // Calculate apparent radius of occulted body.\n    const double occultedBodyApparentRadius\n            = std::asin( occultedBodyRadius\n                         / ( occultedBodyPosition - satellitePosition ).norm( ) );\n\n    // Calculate apparent radius of occulting body.\n    const double occultingBodyApparentRadius =\n            std::asin( occultingBodyRadius / satellitePositionRelativeToOccultingBody.norm( ) );\n\n    // Calculate apparent separation of the center of both bodies.\n    const double apparentSeparationPartOne = -satellitePositionRelativeToOccultingBody.transpose( )\n            * ( occultedBodyPosition - satellitePosition );\n    const double apparentSeparationPartTwo = satellitePositionRelativeToOccultingBody.norm( )\n            * ( occultedBodyPosition - satellitePosition ).norm( );\n    const double apparentSeparation = std::acos( apparentSeparationPartOne\n                                                 / apparentSeparationPartTwo );\n\n    // Set initial value for the shadow function.\n    double shadowFunction = 1.0;\n\n    // Check if partial occultation takes place\n    if ( std::fabs( occultedBodyApparentRadius - occultingBodyApparentRadius ) < apparentSeparation\n         && apparentSeparation < occultedBodyApparentRadius + occultingBodyApparentRadius )\n    {\n        // Pre-compute values for optimal computations.\n        const double apparentSeparationSquared = apparentSeparation * apparentSeparation;\n        const double occultedBodyApparentRadiusSquared = occultedBodyApparentRadius\n                * occultedBodyApparentRadius;\n        const double occultingBodyApparentRadiusSquared = occultingBodyApparentRadius\n                * occultingBodyApparentRadius;\n\n        // Partial occultation takes place, calculate the occulted area.\n        const double occultedAreaPartOne\n                = ( apparentSeparationSquared + occultedBodyApparentRadiusSquared\n                    - occultingBodyApparentRadiusSquared ) / ( 2.0 * apparentSeparation );\n        const double occultedAreaPartTwo = std::sqrt( occultedBodyApparentRadiusSquared\n                                                      - occultedAreaPartOne * occultedAreaPartOne );\n        const double occultedArea = occultedBodyApparentRadiusSquared\n                * std::acos( occultedAreaPartOne / occultedBodyApparentRadius )\n                + occultingBodyApparentRadiusSquared\n                * std::acos( ( apparentSeparation - occultedAreaPartOne )\n                             / occultingBodyApparentRadius )\n                - apparentSeparation * occultedAreaPartTwo;\n        shadowFunction = 1.0 - occultedArea / ( mathematical_constants::PI *\n                                                occultedBodyApparentRadiusSquared );\n    }\n\n    else\n    {\n        // Full or no occultation takes place.\n        // Check for type of occultation.\n        if ( apparentSeparation < occultingBodyApparentRadius - occultedBodyApparentRadius &&\n             occultedBodyApparentRadius < occultingBodyApparentRadius )\n        {\n            // Total occultation.\n            shadowFunction = 0.0;\n        }\n\n        else if ( apparentSeparation < occultedBodyApparentRadius - occultingBodyApparentRadius &&\n                  occultedBodyApparentRadius > occultingBodyApparentRadius )\n        {\n            // Maximum partial occultation.\n            shadowFunction = 0.0;\n        }\n\n        else if ( occultedBodyApparentRadius + occultingBodyApparentRadius <= apparentSeparation )\n        {\n            // No occultation\n            shadowFunction = 1.0;\n        }\n    }\n\n    // Return the shadow function\n    return shadowFunction;\n}\n\ndouble computeSphereOfInfluence( const double distanceToCentralBody,\n                                 const double ratioOfOrbitingToCentralBodyMass )\n{\n    // Return the radius of the sphere of influence.\n    return distanceToCentralBody * std::pow( ratioOfOrbitingToCentralBodyMass, 0.4 );\n}\n\n//! Compute the sphere of influence.\ndouble computeSphereOfInfluence( const double distanceToCentralBody,\n                                 const double massOrbitingBody,\n                                 const double massCentralBody )\n{\n    // Return the radius of the sphere of influence.\n    return computeSphereOfInfluence( distanceToCentralBody, massOrbitingBody / massCentralBody );\n}\n\n} // namespace mission_geometry\n\n} // namespace tudat\n", "meta": {"hexsha": "9632b8d30ee68ca5f770795426cde96e4761af58", "size": 9250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/missionGeometry.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/Astrodynamics/BasicAstrodynamics/missionGeometry.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/Astrodynamics/BasicAstrodynamics/missionGeometry.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": 46.25, "max_line_length": 100, "alphanum_fraction": 0.6700540541, "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7217432062975978, "lm_q1q2_score": 0.5363764613537729}}
{"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#define BOOST_TEST_MODULE TestRadixSort\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/algorithm/is_sorted.hpp>\n#include <boost/compute/algorithm/detail/radix_sort.hpp>\n#include <boost/compute/container/vector.hpp>\n\n#include \"check_macros.hpp\"\n#include \"context_setup.hpp\"\n\nnamespace bc = boost::compute;\n\nBOOST_AUTO_TEST_CASE(sort_char_vector)\n{\n    using boost::compute::char_;\n\n    char_ data[] = { 'c', 'a', '0', '7', 'B', 'F', '\\0', '$' };\n    boost::compute::vector<char_> vector(data, data + 8, queue);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(8));\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == false);\n\n    boost::compute::detail::radix_sort(vector.begin(), vector.end(), queue);\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == true);\n    CHECK_RANGE_EQUAL(char_, 8, vector, ('\\0', '$', '0', '7', 'B', 'F', 'a', 'c'));\n}\n\nBOOST_AUTO_TEST_CASE(sort_uchar_vector)\n{\n    using boost::compute::uchar_;\n\n    uchar_ data[] = { 0x12, 0x00, 0xFF, 0xB4, 0x80, 0x32, 0x64, 0xA2 };\n    boost::compute::vector<uchar_> vector(data, data + 8, queue);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(8));\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == false);\n\n    boost::compute::detail::radix_sort(vector.begin(), vector.end(), queue);\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == true);\n    CHECK_RANGE_EQUAL(uchar_, 8, vector, (0x00, 0x12, 0x32, 0x64, 0x80, 0xA2, 0xB4, 0xFF));\n}\n\nBOOST_AUTO_TEST_CASE(sort_short_vector)\n{\n    using boost::compute::short_;\n\n    short_ data[] = { -4, 152, -94, 963, 31002, -456, 0, -2113 };\n    boost::compute::vector<short_> vector(data, data + 8, queue);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(8));\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == false);\n\n    boost::compute::detail::radix_sort(vector.begin(), vector.end(), queue);\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == true);\n    CHECK_RANGE_EQUAL(short_, 8, vector, (-2113, -456, -94, -4, 0, 152, 963, 31002));\n}\n\nBOOST_AUTO_TEST_CASE(sort_ushort_vector)\n{\n    using boost::compute::ushort_;\n\n    ushort_ data[] = { 4, 152, 94, 963, 63202, 34560, 0, 2113 };\n    boost::compute::vector<ushort_> vector(data, data + 8, queue);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(8));\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == false);\n\n    boost::compute::detail::radix_sort(vector.begin(), vector.end(), queue);\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == true);\n    CHECK_RANGE_EQUAL(ushort_, 8, vector, (0, 4, 94, 152, 963, 2113, 34560, 63202));\n}\n\nBOOST_AUTO_TEST_CASE(sort_int_vector)\n{\n    int data[] = { -4, 152, -5000, 963, 75321, -456, 0, 1112 };\n    boost::compute::vector<int> vector(data, data + 8, queue);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(8));\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == false);\n\n    boost::compute::detail::radix_sort(vector.begin(), vector.end(), queue);\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == true);\n    CHECK_RANGE_EQUAL(int, 8, vector, (-5000, -456, -4, 0, 152, 963, 1112, 75321));\n}\n\nBOOST_AUTO_TEST_CASE(sort_uint_vector)\n{\n    using boost::compute::uint_;\n\n    uint_ data[] = { 500, 1988, 123456, 562, 0, 4000000, 9852, 102030 };\n    boost::compute::vector<uint_> vector(data, data + 8, queue);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(8));\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == false);\n\n    boost::compute::detail::radix_sort(vector.begin(), vector.end(), queue);\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == true);\n    CHECK_RANGE_EQUAL(uint_, 8, vector, (0, 500, 562, 1988, 9852, 102030, 123456, 4000000));\n}\n\nBOOST_AUTO_TEST_CASE(sort_long_vector)\n{\n    using boost::compute::long_;\n\n    long_ data[] = { 500, 1988, 123456, 562, 0, 4000000, 9852, 102030 };\n    boost::compute::vector<long_> vector(data, data + 8, queue);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(8));\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == false);\n\n    boost::compute::detail::radix_sort(vector.begin(), vector.end(), queue);\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == true);\n    CHECK_RANGE_EQUAL(long_, 8, vector, (0, 500, 562, 1988, 9852, 102030, 123456, 4000000));\n}\n\nBOOST_AUTO_TEST_CASE(sort_ulong_vector)\n{\n    using boost::compute::ulong_;\n\n    ulong_ data[] = { 500, 1988, 123456, 562, 0, 4000000, 9852, 102030 };\n    boost::compute::vector<ulong_> vector(data, data + 8, queue);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(8));\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == false);\n\n    boost::compute::detail::radix_sort(vector.begin(), vector.end(), queue);\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == true);\n    CHECK_RANGE_EQUAL(ulong_, 8, vector, (0, 500, 562, 1988, 9852, 102030, 123456, 4000000));\n}\n\nBOOST_AUTO_TEST_CASE(sort_float_vector)\n{\n    float data[] = { -6023.0f, 152.5f, -63.0f, 1234567.0f, 11.2f,\n                     -5000.1f, 0.0f, 14.0f, -8.25f, -0.0f };\n    boost::compute::vector<float> vector(data, data + 10, queue);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(10));\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == false);\n\n    boost::compute::detail::radix_sort(vector.begin(), vector.end(), queue);\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == true);\n    CHECK_RANGE_EQUAL(\n        float, 10, vector,\n        (-6023.0f, -5000.1f, -63.0f, -8.25f, -0.0f, 0.0f, 11.2f, 14.0f, 152.5f, 1234567.0f)\n    );\n\n    // copy data, sort, and check again (to check program caching)\n    boost::compute::copy(data, data + 10, vector.begin(), queue);\n    boost::compute::detail::radix_sort(vector.begin(), vector.end(), queue);\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == true);\n    CHECK_RANGE_EQUAL(\n        float, 10, vector,\n        (-6023.0f, -5000.1f, -63.0f, -8.25f, -0.0f, 0.0f, 11.2f, 14.0f, 152.5f, 1234567.0f)\n    );\n}\n\nBOOST_AUTO_TEST_CASE(sort_double_vector)\n{\n    if(!device.supports_extension(\"cl_khr_fp64\")){\n        std::cout << \"skipping test: device does not support double\" << std::endl;\n        return;\n    }\n\n    double data[] = { -6023.0, 152.5, -63.0, 1234567.0, 11.2,\n                     -5000.1, 0.0, 14.0, -8.25, -0.0 };\n    boost::compute::vector<double> vector(data, data + 10, queue);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(10));\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == false);\n\n    boost::compute::detail::radix_sort(vector.begin(), vector.end(), queue);\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == true);\n    CHECK_RANGE_EQUAL(\n        double, 10, vector,\n        (-6023.0, -5000.1, -63.0, -8.25, -0.0, 0.0, 11.2, 14.0, 152.5, 1234567.0)\n    );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ba1d0ad41a302a068ff5034d1b4927f4d0b99aaa", "size": 7634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_radix_sort.cpp", "max_stars_repo_name": "cwkx/compute", "max_stars_repo_head_hexsha": "86fb40da9f97ea014cd78aa3adba557bdd1a3528", "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": "test/test_radix_sort.cpp", "max_issues_repo_name": "cwkx/compute", "max_issues_repo_head_hexsha": "86fb40da9f97ea014cd78aa3adba557bdd1a3528", "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_radix_sort.cpp", "max_forks_repo_name": "cwkx/compute", "max_forks_repo_head_hexsha": "86fb40da9f97ea014cd78aa3adba557bdd1a3528", "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.1767955801, "max_line_length": 93, "alphanum_fraction": 0.6468430705, "num_tokens": 2296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5363764569057646}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2021 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: Tyler Anderson, Colorado State University, 2021 \n */ \n\n\n// @sect3{Include files}  \n\n// \u7a0b\u5e8f\u4ee5\u901a\u5e38\u7684\u5305\u542b\u6587\u4ef6\u5f00\u59cb\uff0c\u6240\u6709\u8fd9\u4e9b\u6587\u4ef6\u4f60\u73b0\u5728\u5e94\u8be5\u90fd\u89c1\u8fc7\u4e86\u3002\n\n#include <deal.II/base/convergence_table.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/utilities.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/grid/grid_generator.h> \n#include <deal.II/grid/grid_refinement.h> \n#include <deal.II/grid/grid_out.h> \n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/tria_accessor.h> \n#include <deal.II/grid/tria_iterator.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/precondition.h> \n#include <deal.II/lac/sparse_matrix.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/data_out_stack.h> \n#include <deal.II/numerics/error_estimator.h> \n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/solution_transfer.h> \n#include <deal.II/numerics/vector_tools.h> \n\n#include <fstream> \n#include <iostream> \n\n// \u7136\u540e\u7167\u4f8b\u5c06\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u6240\u6709\u5185\u5bb9\u653e\u5165\u4e00\u4e2a\u547d\u540d\u7a7a\u95f4\uff0c\u5e76\u5c06deal.II\u547d\u540d\u7a7a\u95f4\u5bfc\u5165\u5230\u6211\u4eec\u5c06\u8981\u5de5\u4f5c\u7684\u547d\u540d\u7a7a\u95f4\u4e2d\u3002\u6211\u4eec\u8fd8\u5b9a\u4e49\u4e86\u4e00\u4e2a\u6807\u8bc6\u7b26\uff0c\u4ee5\u4fbf\u5728 <code>MMS</code> \u88ab\u5b9a\u4e49\u65f6\u53ef\u4ee5\u8fd0\u884cMMS\u4ee3\u7801\u3002\u5426\u5219\uff0c\u8be5\u7a0b\u5e8f\u5c31\u4f1a\u89e3\u51b3\u539f\u6765\u7684\u95ee\u9898\u3002\n\nnamespace BlackScholesSolver \n{ \n  using namespace dealii; \n\n#define MMS \n// @sect3{Solution Class}  \n\n// \u5728\u4f7f\u7528MMS\u8fdb\u884c\u6d4b\u8bd5\u65f6\uff0c\u8fd9\u90e8\u5206\u4e3a\u5df2\u77e5\u7684\u89e3\u51b3\u65b9\u6848\u521b\u5efa\u4e00\u4e2a\u7c7b\u3002\u8fd9\u91cc\u6211\u4eec\u4f7f\u7528 $v(\\tau,S) = -\\tau^2 -S^2 + 6$ \u4f5c\u4e3a\u89e3\u51b3\u65b9\u6848\u3002\u6211\u4eec\u9700\u8981\u5305\u62ec\u6c42\u89e3\u65b9\u7a0b\u548c\u68af\u5ea6\uff0c\u4ee5\u4fbf\u8fdb\u884cH1\u534a\u89c4\u8303\u8ba1\u7b97\u3002\n\n  template <int dim> \n  class Solution : public Function<dim> \n  { \n  public: \n    Solution(const double maturity_time); \n\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  private: \n    const double maturity_time; \n  }; \n\n  template <int dim> \n  Solution<dim>::Solution(const double maturity_time) \n    : maturity_time(maturity_time) \n  { \n    Assert(dim == 1, ExcNotImplemented()); \n  } \n\n  template <int dim> \n  double Solution<dim>::value(const Point<dim> & p, \n                              const unsigned int component) const \n  { \n    return -Utilities::fixed_power<2, double>(p(component)) - \n           Utilities::fixed_power<2, double>(this->get_time()) + 6; \n  } \n\n  template <int dim> \n  Tensor<1, dim> Solution<dim>::gradient(const Point<dim> & p, \n                                         const unsigned int component) const \n  { \n    return Point<dim>(-2 * p(component)); \n  } \n\n//  @sect3{Equation Data}  \n\n// \u5728\u4e0b\u9762\u7684\u7c7b\u548c\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u5b9e\u73b0\u4e86\u5b9a\u4e49\u8fd9\u4e2a\u95ee\u9898\u7684\u53f3\u624b\u8fb9\u548c\u8fb9\u754c\u503c\uff0c\u4e3a\u6b64\u6211\u4eec\u9700\u8981\u51fd\u6570\u5bf9\u8c61\u3002\u53f3\u624b\u8fb9\u7684\u9009\u62e9\u662f\u5728\u4ecb\u7ecd\u7684\u6700\u540e\u8ba8\u8bba\u7684\u3002\n\n// \u9996\u5148\uff0c\u6211\u4eec\u5904\u7406\u521d\u59cb\u6761\u4ef6\u3002\n\n  template <int dim> \n  class InitialConditions : public Function<dim> \n  { \n  public: \n    InitialConditions(const double strike_price); \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n\n  private: \n    const double strike_price; \n  }; \n\n  template <int dim> \n  InitialConditions<dim>::InitialConditions(const double strike_price) \n    : strike_price(strike_price) \n  {} \n\n  template <int dim> \n  double InitialConditions<dim>::value(const Point<dim> & p, \n                                       const unsigned int component) const \n  { \n#ifdef MMS \n    return -Utilities::fixed_power<2, double>(p(component)) + 6; \n#else \n    return std::max(p(component) - strike_price, 0.); \n#endif \n  } \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5904\u7406\u5de6\u8fb9\u7684\u8fb9\u754c\u6761\u4ef6\u3002\n\n  template <int dim> \n  class LeftBoundaryValues : 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  template <int dim> \n  double LeftBoundaryValues<dim>::value(const Point<dim> &, \n                                        const unsigned int /*component*/) const \n  { \n#ifdef MMS \n    return -Utilities::fixed_power<2, double>(this->get_time()) + 6; \n#else \n    return 0.; \n#endif \n  } \n\n// \u7136\u540e\uff0c\u6211\u4eec\u5904\u7406\u53f3\u8fb9\u7684\u8fb9\u754c\u6761\u4ef6\u3002\n\n  template <int dim> \n  class RightBoundaryValues : public Function<dim> \n  { \n  public: \n    RightBoundaryValues(const double strike_price, const double interest_rate); \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n\n  private: \n    const double strike_price; \n    const double interest_rate; \n  }; \n\n  template <int dim> \n  RightBoundaryValues<dim>::RightBoundaryValues(const double strike_price, \n                                                const double interest_rate) \n    : strike_price(strike_price) \n    , interest_rate(interest_rate) \n  {} \n\n  template <int dim> \n  double RightBoundaryValues<dim>::value(const Point<dim> & p, \n                                         const unsigned int component) const \n  { \n#ifdef MMS \n    return -Utilities::fixed_power<2, double>(p(component)) - \n           Utilities::fixed_power<2, double>(this->get_time()) + 6; \n#else \n    return (p(component) - strike_price) * \n           exp((-interest_rate) * (this->get_time())); \n#endif \n  } \n\n// \u6700\u540e\uff0c\u6211\u4eec\u5904\u7406\u53f3\u8fb9\u7684\u95ee\u9898\u3002\n\n  template <int dim> \n  class RightHandSide : public Function<dim> \n  { \n  public: \n    RightHandSide(const double asset_volatility, const double interest_rate); \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n\n  private: \n    const double asset_volatility; \n    const double interest_rate; \n  }; \n\n  template <int dim> \n  RightHandSide<dim>::RightHandSide(const double asset_volatility, \n                                    const double interest_rate) \n    : asset_volatility(asset_volatility) \n    , interest_rate(interest_rate) \n  {} \n\n  template <int dim> \n  double RightHandSide<dim>::value(const Point<dim> & p, \n                                   const unsigned int component) const \n  { \n#ifdef MMS \n    return 2 * (this->get_time()) - \n           Utilities::fixed_power<2, double>(asset_volatility * p(component)) - \n           2 * interest_rate * Utilities::fixed_power<2, double>(p(component)) - \n           interest_rate * \n             (-Utilities::fixed_power<2, double>(p(component)) - \n              Utilities::fixed_power<2, double>(this->get_time()) + 6); \n#else \n    (void)p; \n    (void)component; \n    return 0.0; \n#endif \n  } \n\n//  @sect3{The <code>BlackScholes</code> Class}  \n\n// \u4e0b\u4e00\u5757\u662f\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u7684\u58f0\u660e\u3002\u8fd9\u4e0e Step-26 \u7684\u6559\u7a0b\u975e\u5e38\u76f8\u4f3c\uff0c\u53ea\u662f\u505a\u4e86\u4e00\u4e9b\u4fee\u6539\u3002\u5fc5\u987b\u6dfb\u52a0\u65b0\u7684\u77e9\u9635\u6765\u8ba1\u7b97A\u548cB\u77e9\u9635\uff0c\u4ee5\u53ca\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684 $V_{diff}$ \u5411\u91cf\u3002\u6211\u4eec\u8fd8\u5b9a\u4e49\u4e86\u95ee\u9898\u4e2d\u4f7f\u7528\u7684\u53c2\u6570\u3002\n\n\n\n// -  <code>maximum_stock_price</code>  \uff1a\u7a7a\u95f4\u57df\u7684\u5f3a\u52a0\u4e0a\u9650\u3002\u8fd9\u662f\u5141\u8bb8\u7684\u6700\u5927\u80a1\u7968\u4ef7\u683c\u3002\n\n// -  <code>maturity_time</code>  \uff1a\u65f6\u95f4\u57df\u7684\u4e0a\u9650\u3002\u8fd9\u662f\u671f\u6743\u5230\u671f\u7684\u65f6\u95f4\u3002\n\n// -  <code>asset_volatility</code>  \uff1a\u80a1\u7968\u4ef7\u683c\u7684\u6ce2\u52a8\u7387\u3002\n\n// -  <code>interest_rate</code>  : \u65e0\u98ce\u9669\u5229\u7387\u3002\n\n// -  <code>strike_price</code>  \uff1a\u4e70\u65b9\u5728\u5230\u671f\u65f6\u53ef\u4ee5\u9009\u62e9\u8d2d\u4e70\u80a1\u7968\u7684\u7ea6\u5b9a\u4ef7\u683c\u3002\n\n// \u672c\u7a0b\u5e8f\u4e0e step-26 \u4e4b\u95f4\u7684\u4e00\u4e9b\u7ec6\u5fae\u5dee\u522b\u662f\u521b\u5efa\u4e86 <code>a_matrix</code> and the <code>b_matrix</code>  \uff0c\u8fd9\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8bf4\u660e\u3002\u7136\u540e\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u5b58\u50a8\u5f53\u524d\u65f6\u95f4\u3001\u65f6\u95f4\u6b65\u957f\u548c\u5f53\u524d\u65f6\u95f4\u6b65\u957f\u7684\u6570\u5b57\u3002\u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5c06\u628a\u8f93\u51fa\u5b58\u50a8\u5230\u4e00\u4e2a <code>DataOutStack</code> \u7684\u53d8\u91cf\u4e2d\uff0c\u56e0\u4e3a\u6211\u4eec\u5c06\u628a\u6bcf\u4e2a\u65f6\u95f4\u7684\u89e3\u5206\u5c42\u5728\u4e0a\u9762\uff0c\u4ee5\u521b\u5efa\u89e3\u6d41\u5f62\u3002\u7136\u540e\uff0c\u6211\u4eec\u6709\u4e00\u4e2a\u53d8\u91cf\u6765\u5b58\u50a8\u5f53\u524d\u7684\u5468\u671f\u548c\u6211\u4eec\u5728\u8ba1\u7b97\u89e3\u51b3\u65b9\u6848\u65f6\u5c06\u8fd0\u884c\u7684\u5468\u671f\u6570\u3002\u5faa\u73af\u662f\u7ed9\u5b9a\u4e00\u4e2a\u7f51\u683c\u7684\u4e00\u4e2a\u5b8c\u6574\u7684\u89e3\u51b3\u65b9\u6848\u8ba1\u7b97\u3002\u6211\u4eec\u5728\u6bcf\u4e2a\u5468\u671f\u4e4b\u95f4\u7ec6\u5316\u4e00\u6b21\u7f51\u683c\uff0c\u4ee5\u5c55\u793a\u6211\u4eec\u7a0b\u5e8f\u7684\u6536\u655b\u7279\u6027\u3002\u6700\u540e\uff0c\u6211\u4eec\u5c06\u6536\u655b\u6570\u636e\u5b58\u50a8\u5230\u4e00\u4e2a\u6536\u655b\u8868\u4e2d\u3002\n\n// \u5c31\u6210\u5458\u51fd\u6570\u800c\u8a00\uff0c\u6211\u4eec\u6709\u4e00\u4e2a\u51fd\u6570\u53ef\u4ee5\u8ba1\u7b97\u6bcf\u4e2a\u5468\u671f\u7684\u6536\u655b\u4fe1\u606f\uff0c\u79f0\u4e3a  <code>process_solution</code>  \u3002\u8fd9\u5c31\u50cf\u5728  step-7  \u4e2d\u6240\u505a\u7684\u90a3\u6837\u3002\n\n  template <int dim> \n  class BlackScholes \n  { \n  public: \n    BlackScholes(); \n\n    void run(); \n\n  private: \n    void setup_system(); \n    void solve_time_step(); \n    void refine_grid(); \n    void process_solution(); \n    void add_results_for_output(); \n    void write_convergence_table(); \n\n    const double maximum_stock_price; \n    const double maturity_time; \n    const double asset_volatility; \n    const double interest_rate; \n    const double strike_price; \n\n    Triangulation<dim> triangulation; \n    FE_Q<dim>          fe; \n    DoFHandler<dim>    dof_handler; \n\n    AffineConstraints<double> constraints; \n\n    SparsityPattern      sparsity_pattern; \n    SparseMatrix<double> mass_matrix; \n    SparseMatrix<double> laplace_matrix; \n    SparseMatrix<double> a_matrix; \n    SparseMatrix<double> b_matrix; \n    SparseMatrix<double> system_matrix; \n\n    Vector<double> solution; \n    Vector<double> system_rhs; \n\n    double time; \n    double time_step; \n    \n    const double       theta;\n    const unsigned int n_cycles;\n    const unsigned int n_time_steps;\n\n    DataOutStack<dim>        data_out_stack; \n    std::vector<std::string> solution_names; \n\n    ConvergenceTable convergence_table; \n  }; \n\n// @sect3{The <code>BlackScholes</code> Implementation}  \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u8fdb\u5165\u4e3b\u7c7b\u7684\u5b9e\u73b0\u9636\u6bb5\u3002\u6211\u4eec\u5c06\u4e3a\u95ee\u9898\u4e2d\u4f7f\u7528\u7684\u5404\u79cd\u53c2\u6570\u8bbe\u7f6e\u6570\u503c\u3002\u9009\u62e9\u8fd9\u4e9b\u662f\u56e0\u4e3a\u5b83\u4eec\u662f\u8fd9\u4e9b\u53c2\u6570\u7684\u76f8\u5f53\u6b63\u5e38\u7684\u503c\u3002\u5c3d\u7ba1\u80a1\u7968\u4ef7\u683c\u5728\u73b0\u5b9e\u4e2d\u6ca1\u6709\u4e0a\u9650\uff08\u4e8b\u5b9e\u4e0a\u662f\u65e0\u9650\u7684\uff09\uff0c\u4f46\u6211\u4eec\u89c4\u5b9a\u4e86\u4e00\u4e2a\u4e0a\u9650\uff0c\u5373\u884c\u6743\u4ef7\u683c\u7684\u4e24\u500d\u3002\u4e24\u500d\u4e8e\u884c\u6743\u4ef7\u7684\u9009\u62e9\u6709\u4e9b\u6b66\u65ad\uff0c\u4f46\u5b83\u8db3\u591f\u5927\uff0c\u53ef\u4ee5\u770b\u5230\u89e3\u51b3\u65b9\u6848\u7684\u6709\u8da3\u90e8\u5206\u3002\n\n  template <int dim> \n  BlackScholes<dim>::BlackScholes() \n    : maximum_stock_price(1.) \n    , maturity_time(1.) \n    , asset_volatility(.2) \n    , interest_rate(0.05) \n    , strike_price(0.5) \n    , fe(1) \n    , dof_handler(triangulation) \n    , time(0.0) \n    , theta(0.5) \n    , n_cycles(4) \n    , n_time_steps(5000) \n  { \n    Assert(dim == 1, ExcNotImplemented()); \n  } \n// @sect4{<code>BlackScholes::setup_system</code>}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u8bbe\u7f6e\u4e86DoFHandler\u5bf9\u8c61\uff0c\u8ba1\u7b97\u4e86\u7ea6\u675f\u6761\u4ef6\uff0c\u5e76\u5c06\u7ebf\u6027\u4ee3\u6570\u5bf9\u8c61\u8bbe\u7f6e\u4e3a\u6b63\u786e\u7684\u5927\u5c0f\u3002\u6211\u4eec\u8fd8\u5728\u8fd9\u91cc\u901a\u8fc7\u8c03\u7528\u5e93\u4e2d\u7684\u4e00\u4e2a\u51fd\u6570\u6765\u8ba1\u7b97\u8d28\u91cf\u77e9\u9635\u3002\u63a5\u4e0b\u6765\u6211\u4eec\u5c06\u8ba1\u7b97\u5176\u4ed6\u4e09\u4e2a\u77e9\u9635\uff0c\u56e0\u4e3a\u8fd9\u4e9b\u77e9\u9635\u9700\u8981 \"\u624b\u5de5 \"\u8ba1\u7b97\u3002\n\n// \u6ce8\u610f\uff0c\u65f6\u95f4\u6b65\u957f\u5728\u8fd9\u91cc\u88ab\u521d\u59cb\u5316\uff0c\u56e0\u4e3a\u8ba1\u7b97\u65f6\u95f4\u6b65\u957f\u9700\u8981\u6210\u719f\u7684\u65f6\u95f4\u3002\n\n  template <int dim> \n  void BlackScholes<dim>::setup_system() \n  { \n    dof_handler.distribute_dofs(fe); \n\n    time_step = maturity_time / n_time_steps; \n\n    constraints.clear(); \n    DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n    constraints.close(); \n    DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, \n                                    dsp, \n                                    constraints, \n                                    /*keep_constrained_dofs =  */ true);\n    sparsity_pattern.copy_from(dsp); \n\n    mass_matrix.reinit(sparsity_pattern); \n    laplace_matrix.reinit(sparsity_pattern); \n    a_matrix.reinit(sparsity_pattern); \n    b_matrix.reinit(sparsity_pattern); \n    system_matrix.reinit(sparsity_pattern); \n\n    MatrixCreator::create_mass_matrix(dof_handler, \n                                      QGauss<dim>(fe.degree + 1), \n                                      mass_matrix); \n\n// \u4e0b\u9762\u662f\u521b\u5efa\u975e\u6052\u5b9a\u7cfb\u6570\u7684\u62c9\u666e\u62c9\u65af\u77e9\u9635\u7684\u4ee3\u7801\u3002\u8fd9\u4e0e\u4ecb\u7ecd\u4e2d\u7684\u77e9\u9635D\u76f8\u5bf9\u5e94\u3002\u8fd9\u4e2a\u975e\u6052\u5b9a\u7cfb\u6570\u5728 <code>current_coefficient</code> \u53d8\u91cf\u4e2d\u8868\u793a\u3002\n\n    const unsigned int dofs_per_cell = fe.dofs_per_cell; \n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n    QGauss<dim>        quadrature_formula(fe.degree + 1); \n    FEValues<dim>      fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | update_JxW_values); \n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        cell_matrix = 0.; \n        fe_values.reinit(cell); \n        for (const unsigned int q_index : fe_values.quadrature_point_indices()) \n          { \n            const double current_coefficient = \n              fe_values.quadrature_point(q_index).square(); \n            for (const unsigned int i : fe_values.dof_indices()) \n              { \n                for (const unsigned int j : fe_values.dof_indices()) \n                  cell_matrix(i, j) += \n                    (current_coefficient *              // (x_q)^2 \n                     fe_values.shape_grad(i, q_index) * // grad phi_i(x_q) \n                     fe_values.shape_grad(j, q_index) * // grad phi_j(x_q) \n                     fe_values.JxW(q_index));           // dx \n              } \n          } \n        cell->get_dof_indices(local_dof_indices); \n        for (const unsigned int i : fe_values.dof_indices()) \n          { \n            for (const unsigned int j : fe_values.dof_indices()) \n              laplace_matrix.add(local_dof_indices[i], \n                                 local_dof_indices[j], \n                                 cell_matrix(i, j)); \n          } \n      } \n\n// \u73b0\u5728\u6211\u4eec\u5c06\u521b\u5efaA\u77e9\u9635\u3002\u4e0b\u9762\u662f\u521b\u5efa\u77e9\u9635A\u7684\u4ee3\u7801\uff0c\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u3002\u975e\u6052\u5b9a\u7cfb\u6570\u518d\u6b21\u7528 <code>current_coefficient</code> \u8fd9\u4e2a\u53d8\u91cf\u8868\u793a\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        cell_matrix = 0.; \n        fe_values.reinit(cell); \n        for (const unsigned int q_index : fe_values.quadrature_point_indices()) \n          { \n            const Tensor<1, dim> current_coefficient = \n              fe_values.quadrature_point(q_index); \n            for (const unsigned int i : fe_values.dof_indices()) \n              { \n                for (const unsigned int j : fe_values.dof_indices()) \n                  { \n                    cell_matrix(i, j) += \n                      (current_coefficient *               // x_q \n                       fe_values.shape_grad(i, q_index) *  // grad phi_i(x_q) \n                       fe_values.shape_value(j, q_index) * // phi_j(x_q) \n                       fe_values.JxW(q_index));            // dx \n                  } \n              } \n          } \n        cell->get_dof_indices(local_dof_indices); \n        for (const unsigned int i : fe_values.dof_indices()) \n          { \n            for (const unsigned int j : fe_values.dof_indices()) \n              a_matrix.add(local_dof_indices[i], \n                           local_dof_indices[j], \n                           cell_matrix(i, j)); \n          } \n      } \n\n// \u6700\u540e\u6211\u4eec\u5c06\u521b\u5efa\u77e9\u9635B\u3002\u4e0b\u9762\u662f\u521b\u5efa\u77e9\u9635B\u7684\u4ee3\u7801\uff0c\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u3002\u975e\u6052\u5b9a\u7cfb\u6570\u518d\u6b21\u7528 <code>current_coefficient</code> \u8fd9\u4e2a\u53d8\u91cf\u8868\u793a\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        cell_matrix = 0.; \n        fe_values.reinit(cell); \n        for (const unsigned int q_index : fe_values.quadrature_point_indices()) \n          { \n            const Tensor<1, dim> current_coefficient = \n              fe_values.quadrature_point(q_index); \n            for (const unsigned int i : fe_values.dof_indices()) \n              { \n                for (const unsigned int j : fe_values.dof_indices()) \n                  cell_matrix(i, j) += \n                    (current_coefficient *               // x_q \n                     fe_values.shape_value(i, q_index) * // phi_i(x_q) \n                     fe_values.shape_grad(j, q_index) *  // grad phi_j(x_q) \n                     fe_values.JxW(q_index));            // dx \n              } \n          } \n        cell->get_dof_indices(local_dof_indices); \n        for (const unsigned int i : fe_values.dof_indices()) \n          { \n            for (const unsigned int j : fe_values.dof_indices()) \n              b_matrix.add(local_dof_indices[i], \n                           local_dof_indices[j], \n                           cell_matrix(i, j)); \n          } \n      } \n\n    solution.reinit(dof_handler.n_dofs()); \n    system_rhs.reinit(dof_handler.n_dofs()); \n  } \n// @sect4{<code>BlackScholes::solve_time_step</code>}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u89e3\u51b3\u5355\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u5b9e\u9645\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\u3002\u8fd9\u91cc\u552f\u4e00\u6709\u8da3\u7684\u662f\uff0c\u6211\u4eec\u5efa\u7acb\u7684\u77e9\u9635\u662f\u5bf9\u79f0\u6b63\u5b9a\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528\u5171\u8f6d\u68af\u5ea6\u6cd5\u3002\n\n  template <int dim> \n  void BlackScholes<dim>::solve_time_step() \n  { \n    SolverControl                          solver_control(1000, 1e-12); \n    SolverCG<Vector<double>>               cg(solver_control); \n    PreconditionSSOR<SparseMatrix<double>> preconditioner; \n    preconditioner.initialize(system_matrix, 1.0); \n    cg.solve(system_matrix, solution, system_rhs, preconditioner); \n    constraints.distribute(solution); \n  } \n// @sect4{<code>BlackScholes::add_results_for_output</code>}  \n\n// \u8fd9\u662f\u7b80\u5355\u5730\u5c06\u89e3\u51b3\u65b9\u6848\u7684\u788e\u7247\u62fc\u63a5\u8d77\u6765\u7684\u529f\u80fd\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u5728\u6bcf\u4e2a\u65f6\u95f4\u6bb5\u521b\u5efa\u4e00\u4e2a\u65b0\u7684\u5c42\uff0c\u7136\u540e\u6dfb\u52a0\u8be5\u65f6\u95f4\u6bb5\u7684\u89e3\u51b3\u65b9\u6848\u5411\u91cf\u3002\u7136\u540e\uff0c\u8be5\u51fd\u6570\u4f7f\u7528'build_patches'\u5c06\u5176\u4e0e\u65e7\u7684\u89e3\u51b3\u65b9\u6848\u7f1d\u5408\u5728\u4e00\u8d77\u3002\n\n  template <int dim> \n  void BlackScholes<dim>::add_results_for_output() \n  { \n    data_out_stack.new_parameter_value(time, time_step); \n    data_out_stack.attach_dof_handler(dof_handler); \n    data_out_stack.add_data_vector(solution, solution_names); \n    data_out_stack.build_patches(2); \n    data_out_stack.finish_parameter_value(); \n  } \n// @sect4{<code>BlackScholes::refine_grid</code>}  \n\n// \u5bf9\u4e8e\u6211\u4eec\u6240\u505a\u7684\u5168\u5c40\u7ec6\u5316\u6765\u8bf4\uff0c\u6709\u4e00\u4e2a\u51fd\u6570\u662f\u6709\u4e9b\u4e0d\u5fc5\u8981\u7684\u3002\u4e4b\u6240\u4ee5\u6709\u8fd9\u4e2a\u51fd\u6570\uff0c\u662f\u4e3a\u4e86\u5141\u8bb8\u4ee5\u540e\u6709\u53ef\u80fd\u8fdb\u884c\u9002\u5e94\u6027\u7ec6\u5316\u3002\n\n  template <int dim> \n  void BlackScholes<dim>::refine_grid() \n  { \n    triangulation.refine_global(1); \n  } \n// @sect4{<code>BlackScholes::process_solution</code>}  \n\n// \u8fd9\u5c31\u662f\u6211\u4eec\u8ba1\u7b97\u6536\u655b\u548c\u8bef\u5dee\u6570\u636e\u7684\u5730\u65b9\uff0c\u4ee5\u8bc4\u4f30\u7a0b\u5e8f\u7684\u6709\u6548\u6027\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u8ba1\u7b97 $L^2$  \u3001 $H^1$  \u548c $L^{\\infty}$ \u7684\u51c6\u5219\u3002\n\n  template <int dim> \n  void BlackScholes<dim>::process_solution() \n  { \n    Solution<dim> sol(maturity_time); \n    sol.set_time(time); \n    Vector<float> difference_per_cell(triangulation.n_active_cells()); \n    VectorTools::integrate_difference(dof_handler, \n                                      solution, \n                                      sol, \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    VectorTools::integrate_difference(dof_handler, \n                                      solution, \n                                      sol, \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    const QTrapezoid<1>  q_trapezoid; \n    const QIterated<dim> q_iterated(q_trapezoid, fe.degree * 2 + 1); \n    VectorTools::integrate_difference(dof_handler, \n                                      solution, \n                                      sol, \n                                      difference_per_cell, \n                                      q_iterated, \n                                      VectorTools::Linfty_norm); \n    const double Linfty_error = \n      VectorTools::compute_global_error(triangulation, \n                                        difference_per_cell, \n                                        VectorTools::Linfty_norm); \n    const unsigned int n_active_cells = triangulation.n_active_cells(); \n    const unsigned int n_dofs         = dof_handler.n_dofs(); \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    convergence_table.add_value(\"Linfty\", Linfty_error); \n  } \n// @sect4{<code>BlackScholes::write_convergence_table</code> }  \n\n// \u63a5\u4e0b\u6765\u7684\u90e8\u5206\u662f\u5efa\u7acb\u6536\u655b\u548c\u8bef\u5dee\u8868\u3002\u901a\u8fc7\u8fd9\u4e2a\uff0c\u6211\u4eec\u9700\u8981\u8bbe\u7f6e\u5982\u4f55\u8f93\u51fa\u5728  <code>BlackScholes::process_solution</code>  \u671f\u95f4\u8ba1\u7b97\u7684\u6570\u636e\u3002\u9996\u5148\uff0c\u6211\u4eec\u5c06\u521b\u5efa\u6807\u9898\u5e76\u6b63\u786e\u8bbe\u7f6e\u5355\u5143\u683c\u3002\u5728\u8fd9\u671f\u95f4\uff0c\u6211\u4eec\u8fd8\u5c06\u89c4\u5b9a\u7ed3\u679c\u7684\u7cbe\u5ea6\u3002\u7136\u540e\uff0c\u6211\u4eec\u5c06\u6839\u636e  $L^2$  \u3001  $H^1$  \u548c  $L^{\\infty}$  \u89c4\u8303\u628a\u8ba1\u7b97\u51fa\u6765\u7684\u8bef\u5dee\u5199\u5230\u63a7\u5236\u53f0\u548c\u9519\u8bef\u7684LaTeX\u6587\u4ef6\u4e2d\u3002\n\n  template <int dim> \n  void BlackScholes<dim>::write_convergence_table() \n  { \n    convergence_table.set_precision(\"L2\", 3); \n    convergence_table.set_precision(\"H1\", 3); \n    convergence_table.set_precision(\"Linfty\", 3); \n    convergence_table.set_scientific(\"L2\", true); \n    convergence_table.set_scientific(\"H1\", true); \n    convergence_table.set_scientific(\"Linfty\", true); \n    convergence_table.set_tex_caption(\"cells\", \"\\\\# cells\"); \n    convergence_table.set_tex_caption(\"dofs\", \"\\\\# dofs\"); \n    convergence_table.set_tex_caption(\"L2\", \"@f$L^2@f$-error\"); \n    convergence_table.set_tex_caption(\"H1\", \"@f$H^1@f$-error\"); \n    convergence_table.set_tex_caption(\"Linfty\", \"@f$L^\\\\infty@f$-error\"); \n    convergence_table.set_tex_format(\"cells\", \"r\"); \n    convergence_table.set_tex_format(\"dofs\", \"r\"); \n    std::cout << std::endl; \n    convergence_table.write_text(std::cout); \n    std::string error_filename = \"error\"; \n    error_filename += \"-global\"; \n    error_filename += \".tex\"; \n    std::ofstream error_table_file(error_filename); \n    convergence_table.write_tex(error_table_file); \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5c06\u5236\u4f5c\u6536\u655b\u8868\u3002\u6211\u4eec\u5c06\u518d\u6b21\u628a\u5b83\u5199\u5230\u63a7\u5236\u53f0\u548c\u6536\u655bLaTeX\u6587\u4ef6\u4e2d\u3002\n\n    convergence_table.add_column_to_supercolumn(\"cells\", \"n cells\"); \n    std::vector<std::string> new_order; \n    new_order.emplace_back(\"n cells\"); \n    new_order.emplace_back(\"H1\"); \n    new_order.emplace_back(\"L2\"); \n    convergence_table.set_column_order(new_order); \n    convergence_table.evaluate_convergence_rates( \n      \"L2\", ConvergenceTable::reduction_rate); \n    convergence_table.evaluate_convergence_rates( \n      \"L2\", ConvergenceTable::reduction_rate_log2); \n    convergence_table.evaluate_convergence_rates( \n      \"H1\", ConvergenceTable::reduction_rate); \n    convergence_table.evaluate_convergence_rates( \n      \"H1\", ConvergenceTable::reduction_rate_log2); \n    std::cout << std::endl; \n    convergence_table.write_text(std::cout); \n    std::string conv_filename = \"convergence\"; \n    conv_filename += \"-global\"; \n    switch (fe.degree) \n      { \n        case 1: \n          conv_filename += \"-q1\"; \n          break; \n        case 2: \n          conv_filename += \"-q2\"; \n          break; \n        default: \n          Assert(false, ExcNotImplemented()); \n      } \n    conv_filename += \".tex\"; \n    std::ofstream table_file(conv_filename); \n    convergence_table.write_tex(table_file); \n  } \n// @sect4{<code>BlackScholes::run</code>}  \n\n// \u73b0\u5728\u6211\u4eec\u8fdb\u5165\u4e86\u7a0b\u5e8f\u7684\u4e3b\u8981\u9a71\u52a8\u90e8\u5206\u3002\u5728\u8fd9\u91cc\u6211\u4eec\u8981\u505a\u7684\u662f\u5728\u65f6\u95f4\u6b65\u6570\u4e2d\u5faa\u73af\u5f80\u590d\uff0c\u5e76\u5728\u6bcf\u6b21\u8ba1\u7b97\u89e3\u5411\u91cf\u7684\u5de5\u4f5c\u3002\u5728\u8fd9\u91cc\u7684\u9876\u90e8\uff0c\u6211\u4eec\u8bbe\u7f6e\u521d\u59cb\u7ec6\u5316\u503c\uff0c\u7136\u540e\u521b\u5efa\u4e00\u4e2a\u7f51\u683c\u3002\u7136\u540e\u6211\u4eec\u5bf9\u8fd9\u4e2a\u7f51\u683c\u8fdb\u884c\u4e00\u6b21\u7ec6\u5316\u3002\u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u8bbe\u7f6e\u4e86data_out_stack\u5bf9\u8c61\u6765\u5b58\u50a8\u6211\u4eec\u7684\u89e3\u51b3\u65b9\u6848\u3002\u6700\u540e\uff0c\u6211\u4eec\u542f\u52a8\u4e00\u4e2afor\u5faa\u73af\u6765\u5faa\u73af\u5904\u7406\u8fd9\u4e9b\u5faa\u73af\u3002\u8fd9\u8ba9\u6211\u4eec\u4e3a\u6bcf\u4e00\u4e2a\u8fde\u7eed\u7684\u7f51\u683c\u7ec6\u5316\u91cd\u65b0\u8ba1\u7b97\u51fa\u4e00\u4e2a\u89e3\u51b3\u65b9\u6848\u3002\u5728\u6bcf\u6b21\u8fed\u4ee3\u5f00\u59cb\u65f6\uff0c\u6211\u4eec\u9700\u8981\u91cd\u65b0\u8bbe\u7f6e\u65f6\u95f4\u548c\u65f6\u95f4\u6b65\u957f\u3002\u6211\u4eec\u5f15\u5165\u4e00\u4e2aif\u8bed\u53e5\u6765\u5b8c\u6210\u8fd9\u4e2a\u4efb\u52a1\uff0c\u56e0\u4e3a\u6211\u4eec\u4e0d\u60f3\u5728\u7b2c\u4e00\u6b21\u8fed\u4ee3\u65f6\u5c31\u8fd9\u6837\u505a\u3002\n\n  template <int dim> \n  void BlackScholes<dim>::run() \n  { \n    GridGenerator::hyper_cube(triangulation, 0.0, maximum_stock_price, true); \n    triangulation.refine_global(0); \n\n    solution_names.emplace_back(\"u\"); \n    data_out_stack.declare_data_vector(solution_names, \n                                       DataOutStack<dim>::dof_vector); \n\n    Vector<double> vmult_result; \n    Vector<double> forcing_terms; \n\n    for (unsigned int cycle = 0; cycle < n_cycles; cycle++) \n      { \n        if (cycle != 0) \n          { \n            refine_grid(); \n            time = 0.0; \n          } \n\n        setup_system(); \n\n        std::cout << std::endl \n                  << \"===========================================\" << std::endl \n                  << \"Cycle \" << cycle << ':' << std::endl \n                  << \"Number of active cells: \" \n                  << triangulation.n_active_cells() << std::endl \n                  << \"Number of degrees of freedom: \" << dof_handler.n_dofs() \n                  << std::endl \n                  << std::endl; \n\n        VectorTools::interpolate(dof_handler, \n                                 InitialConditions<dim>(strike_price), \n                                 solution); \n\n        if (cycle == (n_cycles - 1)) \n          { \n            add_results_for_output(); \n          } \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u8fd0\u884c\u4e3b\u5faa\u73af\uff0c\u8be5\u5faa\u73af\u4e00\u76f4\u8fd0\u884c\u5230\u8d85\u8fc7\u6210\u719f\u65f6\u95f4\u3002\u6211\u4eec\u9996\u5148\u8ba1\u7b97\u65b9\u7a0b\u7684\u53f3\u4fa7\uff0c\u8fd9\u5728\u4ecb\u7ecd\u4e2d\u6709\u6240\u63cf\u8ff0\u3002\u56de\u987e\u4e00\u4e0b\uff0c\u5b83\u5305\u542b\u672f\u8bed $\\left[-\\frac{1}{4}k_n\\sigma^2\\mathbf{D}-k_nr\\mathbf{M}+k_n\\sigma^2 \\mathbf{B}-k_nr\\mathbf{A}+\\mathbf{M}\\right]V^{n-1}$  \u3002\u6211\u4eec\u628a\u8fd9\u4e9b\u9879\u653e\u5230\u53d8\u91cfsystem_rhs\u4e2d\uff0c\u501f\u52a9\u4e8e\u4e00\u4e2a\u4e34\u65f6\u5411\u91cf\u3002\n\n        vmult_result.reinit(dof_handler.n_dofs()); \n        forcing_terms.reinit(dof_handler.n_dofs()); \n        for (unsigned int timestep_number = 0; timestep_number < n_time_steps; \n             ++timestep_number) \n          { \n            time += time_step; \n\n            if (timestep_number % 1000 == 0) \n              std::cout << \"Time step \" << timestep_number << \" at t=\" << time \n                        << std::endl; \n\n            mass_matrix.vmult(system_rhs, solution); \n\n            laplace_matrix.vmult(vmult_result, solution); \n            system_rhs.add( \n              (-1) * (1 - theta) * time_step * \n                Utilities::fixed_power<2, double>(asset_volatility) * 0.5, \n              vmult_result); \n            mass_matrix.vmult(vmult_result, solution); \n\n            system_rhs.add((-1) * (1 - theta) * time_step * interest_rate * 2, \n                           vmult_result); \n\n            a_matrix.vmult(vmult_result, solution); \n            system_rhs.add((-1) * time_step * interest_rate, vmult_result); \n\n            b_matrix.vmult(vmult_result, solution); \n            system_rhs.add( \n              (-1) * Utilities::fixed_power<2, double>(asset_volatility) * \n                time_step * 1, \n              vmult_result); \n\n// \u7b2c\u4e8c\u5757\u662f\u8ba1\u7b97\u6e90\u9879\u7684\u8d21\u732e\u3002\u8fd9\u4e0e\u672f\u8bed  $-k_n\\left[\\frac{1}{2}F^{n-1} +\\frac{1}{2}F^n\\right]$  \u76f8\u5bf9\u5e94\u3002\u4e0b\u9762\u7684\u4ee3\u7801\u8c03\u7528  VectorTools::create_right_hand_side  \u6765\u8ba1\u7b97\u5411\u91cf  $F$  \uff0c\u5728\u8fd9\u91cc\u6211\u4eec\u5728\u8bc4\u4f30\u4e4b\u524d\u8bbe\u7f6e\u4e86\u53f3\u4fa7\uff08\u6e90\uff09\u51fd\u6570\u7684\u65f6\u95f4\u3002\u8fd9\u4e00\u5207\u7684\u7ed3\u679c\u6700\u7ec8\u90fd\u5728forcing_terms\u53d8\u91cf\u4e2d\u3002\n\n            RightHandSide<dim> rhs_function(asset_volatility, interest_rate); \n            rhs_function.set_time(time); \n            VectorTools::create_right_hand_side(dof_handler, \n                                                QGauss<dim>(fe.degree + 1), \n                                                rhs_function, \n                                                forcing_terms); \n            forcing_terms *= time_step * theta; \n            system_rhs -= forcing_terms; \n\n            rhs_function.set_time(time - time_step); \n            VectorTools::create_right_hand_side(dof_handler, \n                                                QGauss<dim>(fe.degree + 1), \n                                                rhs_function, \n                                                forcing_terms); \n            forcing_terms *= time_step * (1 - theta); \n            system_rhs -= forcing_terms; \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5c06\u5f3a\u8feb\u9879\u6dfb\u52a0\u5230\u6765\u81ea\u65f6\u95f4\u6b65\u957f\u7684\u5f3a\u8feb\u9879\u4e2d\uff0c\u540c\u65f6\u5efa\u7acb\u77e9\u9635 $\\left[\\mathbf{M}+ \\frac{1}{4}k_n\\sigma^2\\mathbf{D}+k_nr\\mathbf{M}\\right]$ \uff0c\u6211\u4eec\u5fc5\u987b\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u8fdb\u884c\u53cd\u8f6c\u3002\u8fd9\u4e9b\u64cd\u4f5c\u7684\u6700\u540e\u4e00\u5757\u662f\u6d88\u9664\u7ebf\u6027\u7cfb\u7edf\u4e2d\u60ac\u6302\u7684\u8282\u70b9\u7ea6\u675f\u81ea\u7531\u5ea6\u3002\n\n            system_matrix.copy_from(mass_matrix); \n            system_matrix.add( \n              (theta)*time_step * \n                Utilities::fixed_power<2, double>(asset_volatility) * 0.5, \n              laplace_matrix); \n            system_matrix.add((time_step)*interest_rate * theta * (1 + 1), \n                              mass_matrix); \n\n            constraints.condense(system_matrix, system_rhs); \n\n// \u5728\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u4e4b\u524d\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u505a\u4e00\u4e2a\u64cd\u4f5c\uff1a\u8fb9\u754c\u503c\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u521b\u5efa\u4e00\u4e2a\u8fb9\u754c\u503c\u5bf9\u8c61\uff0c\u5c06\u9002\u5f53\u7684\u65f6\u95f4\u8bbe\u7f6e\u4e3a\u5f53\u524d\u65f6\u95f4\u6b65\u957f\u7684\u65f6\u95f4\uff0c\u5e76\u50cf\u4ee5\u524d\u591a\u6b21\u90a3\u6837\u5bf9\u5176\u8fdb\u884c\u8bc4\u4f30\u3002\u5176\u7ed3\u679c\u4e5f\u88ab\u7528\u6765\u5728\u7ebf\u6027\u7cfb\u7edf\u4e2d\u8bbe\u7f6e\u6b63\u786e\u7684\u8fb9\u754c\u503c\u3002\n\n            { \n              RightBoundaryValues<dim> right_boundary_function(strike_price, \n                                                               interest_rate); \n              LeftBoundaryValues<dim>  left_boundary_function; \n              right_boundary_function.set_time(time); \n              left_boundary_function.set_time(time); \n              std::map<types::global_dof_index, double> boundary_values; \n              VectorTools::interpolate_boundary_values(dof_handler, \n                                                       0, \n                                                       left_boundary_function, \n                                                       boundary_values); \n              VectorTools::interpolate_boundary_values(dof_handler, \n                                                       1, \n                                                       right_boundary_function, \n                                                       boundary_values); \n              MatrixTools::apply_boundary_values(boundary_values, \n                                                 system_matrix, \n                                                 solution, \n                                                 system_rhs); \n            } \n\n// \u89e3\u51b3\u4e86\u8fd9\u4e2a\u95ee\u9898\uff0c\u6211\u4eec\u8981\u505a\u7684\u5c31\u662f\u6c42\u89e3\u7cfb\u7edf\uff0c\u751f\u6210\u6700\u540e\u4e00\u4e2a\u5468\u671f\u7684\u56fe\u5f62\u6570\u636e\uff0c\u5e76\u521b\u5efa\u6536\u655b\u8868\u6570\u636e\u3002\n\n            solve_time_step(); \n\n            if (cycle == (n_cycles - 1)) \n              { \n                add_results_for_output(); \n              } \n          } \n#ifdef MMS \n        process_solution(); \n#endif \n      } \n\n    const std::string filename = \"solution.vtk\"; \n    std::ofstream     output(filename); \n    data_out_stack.write_vtk(output); \n\n#ifdef MMS \n    write_convergence_table(); \n#endif \n  } \n\n} // namespace BlackScholesSolver \n// @sect3{The <code>main</code> Function}  \n\n// \u8d70\u5230\u8fd9\u4e00\u6b65\uff0c\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u51fd\u6570\u53c8\u6ca1\u6709\u4ec0\u4e48\u597d\u8ba8\u8bba\u7684\u4e86\uff1a\u770b\u8d77\u6765\u81ea step-6 \u4ee5\u6765\u7684\u6240\u6709\u6b64\u7c7b\u51fd\u6570\u3002\n\nint main() \n{ \n  try \n    { \n      using namespace BlackScholesSolver; \n\n      BlackScholes<1> black_scholes_solver; \n      black_scholes_solver.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\n", "meta": {"hexsha": "80d3b3a17f87df725529f3a56d03ed2813886ae7", "size": 29642, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-78/step-78.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-78/step-78.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-78/step-78.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.3259803922, "max_line_length": 304, "alphanum_fraction": 0.5800553269, "num_tokens": 8616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5363764524577561}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2013 Gauthier Brun <brun.gauthier@gmail.com>\n// Copyright (C) 2013 Nicolas Carre <nicolas.carre@ensimag.fr>\n// Copyright (C) 2013 Jean Ceccato <jean.ceccato@ensimag.fr>\n// Copyright (C) 2013 Pierre Zoppitelli <pierre.zoppitelli@ensimag.fr>\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// discard stack allocation as that too bypasses malloc\n#define EIGEN_STACK_ALLOCATION_LIMIT 0\n#define EIGEN_RUNTIME_NO_MALLOC\n\n#include \"main.h\"\n#include <Eigen/SVD>\n#include <iostream>\n#include <Eigen/LU>\n\n\n#define SVD_DEFAULT(M) BDCSVD<M>\n#define SVD_FOR_MIN_NORM(M) BDCSVD<M>\n#include \"svd_common.h\"\n\n// Check all variants of JacobiSVD\ntemplate<typename MatrixType>\nvoid bdcsvd(const MatrixType& a = MatrixType(), bool pickrandom = true)\n{\n  MatrixType m = a;\n  if(pickrandom)\n    svd_fill_random(m);\n\n  CALL_SUBTEST(( svd_test_all_computation_options<BDCSVD<MatrixType> >(m, false)  ));\n}\n\ntemplate<typename MatrixType>\nvoid bdcsvd_method()\n{\n  enum { Size = MatrixType::RowsAtCompileTime };\n  typedef typename MatrixType::RealScalar RealScalar;\n  typedef Matrix<RealScalar, Size, 1> RealVecType;\n  MatrixType m = MatrixType::Identity();\n  VERIFY_IS_APPROX(m.bdcSvd().singularValues(), RealVecType::Ones());\n  VERIFY_RAISES_ASSERT(m.bdcSvd().matrixU());\n  VERIFY_RAISES_ASSERT(m.bdcSvd().matrixV());\n  VERIFY_IS_APPROX(m.bdcSvd(ComputeFullU|ComputeFullV).solve(m), m);\n}\n\n// compare the Singular values returned with Jacobi and Bdc\ntemplate<typename MatrixType>\nvoid compare_bdc_jacobi(const MatrixType& a = MatrixType(), unsigned int computationOptions = 0)\n{\n  MatrixType m = MatrixType::Random(a.rows(), a.cols());\n  BDCSVD<MatrixType> bdc_svd(m);\n  JacobiSVD<MatrixType> jacobi_svd(m);\n  VERIFY_IS_APPROX(bdc_svd.singularValues(), jacobi_svd.singularValues());\n  if(computationOptions & ComputeFullU) VERIFY_IS_APPROX(bdc_svd.matrixU(), jacobi_svd.matrixU());\n  if(computationOptions & ComputeThinU) VERIFY_IS_APPROX(bdc_svd.matrixU(), jacobi_svd.matrixU());\n  if(computationOptions & ComputeFullV) VERIFY_IS_APPROX(bdc_svd.matrixV(), jacobi_svd.matrixV());\n  if(computationOptions & ComputeThinV) VERIFY_IS_APPROX(bdc_svd.matrixV(), jacobi_svd.matrixV());\n}\n\nvoid test_bdcsvd()\n{\n  CALL_SUBTEST_3(( svd_verify_assert<BDCSVD<Matrix3f>  >(Matrix3f()) ));\n  CALL_SUBTEST_4(( svd_verify_assert<BDCSVD<Matrix4d>  >(Matrix4d()) ));\n  CALL_SUBTEST_7(( svd_verify_assert<BDCSVD<MatrixXf>  >(MatrixXf(10,12)) ));\n  CALL_SUBTEST_8(( svd_verify_assert<BDCSVD<MatrixXcd> >(MatrixXcd(7,5)) ));\n\n  CALL_SUBTEST_101(( svd_all_trivial_2x2(bdcsvd<Matrix2cd>) ));\n  CALL_SUBTEST_102(( svd_all_trivial_2x2(bdcsvd<Matrix2d>) ));\n\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_3(( bdcsvd<Matrix3f>() ));\n    CALL_SUBTEST_4(( bdcsvd<Matrix4d>() ));\n    CALL_SUBTEST_5(( bdcsvd<Matrix<float,3,5> >() ));\n\n    int r = internal::random<int>(1, EIGEN_TEST_MAX_SIZE/2),\n        c = internal::random<int>(1, EIGEN_TEST_MAX_SIZE/2);\n\n    TEST_SET_BUT_UNUSED_VARIABLE(r)\n    TEST_SET_BUT_UNUSED_VARIABLE(c)\n\n    CALL_SUBTEST_6((  bdcsvd(Matrix<double,Dynamic,2>(r,2)) ));\n    CALL_SUBTEST_7((  bdcsvd(MatrixXf(r,c)) ));\n    CALL_SUBTEST_7((  compare_bdc_jacobi(MatrixXf(r,c)) ));\n    CALL_SUBTEST_10(( bdcsvd(MatrixXd(r,c)) ));\n    CALL_SUBTEST_10(( compare_bdc_jacobi(MatrixXd(r,c)) ));\n    CALL_SUBTEST_8((  bdcsvd(MatrixXcd(r,c)) ));\n    CALL_SUBTEST_8((  compare_bdc_jacobi(MatrixXcd(r,c)) ));\n\n    // Test on inf/nan matrix\n    CALL_SUBTEST_7(  (svd_inf_nan<BDCSVD<MatrixXf>, MatrixXf>()) );\n    CALL_SUBTEST_10( (svd_inf_nan<BDCSVD<MatrixXd>, MatrixXd>()) );\n  }\n\n  // test matrixbase method\n  CALL_SUBTEST_1(( bdcsvd_method<Matrix2cd>() ));\n  CALL_SUBTEST_3(( bdcsvd_method<Matrix3f>() ));\n\n  // Test problem size constructors\n  CALL_SUBTEST_7( BDCSVD<MatrixXf>(10,10) );\n\n  // Check that preallocation avoids subsequent mallocs\n  // Disbaled because not supported by BDCSVD\n  // CALL_SUBTEST_9( svd_preallocate<void>() );\n\n  CALL_SUBTEST_2( svd_underoverflow<void>() );\n}\n", "meta": {"hexsha": "4b2e3446e382332689d0db1bd19561b2c32e4d4f", "size": 4222, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/test/bdcsvd.cpp", "max_stars_repo_name": "eundersander/bps-nav", "max_stars_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-03-15T01:49:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T23:17:14.000Z", "max_issues_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/test/bdcsvd.cpp", "max_issues_repo_name": "eundersander/bps-nav", "max_issues_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-27T21:41:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T21:46:40.000Z", "max_forks_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/test/bdcsvd.cpp", "max_forks_repo_name": "eundersander/bps-nav", "max_forks_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-27T17:17:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T12:00:06.000Z", "avg_line_length": 37.6964285714, "max_line_length": 98, "alphanum_fraction": 0.7323543344, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5363764486947101}}
{"text": "#define BOOST_TEST_MODULE \"test_excluded_volume_potential\"\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 <mjolnir/forcefield/external/ExcludedVolumeWallPotential.hpp>\n\nBOOST_AUTO_TEST_CASE(ExcludedVolumeWallPotential_double)\n{\n    using real_type = double;\n    constexpr static std::size_t N = 10000;\n    constexpr static real_type h   = 1e-6;\n    constexpr static real_type tol = 1e-5;\n\n    const real_type epsilon = 1.0;\n    const real_type radius  = 1.0;\n    const std::vector<std::pair<std::size_t, real_type>> radii{{0, radius}};\n\n    mjolnir::ExcludedVolumeWallPotential<real_type> exvw(epsilon, 2.0, radii);\n\n    const real_type cutoff_length = exvw.max_cutoff_length();\n    const real_type z_max         = cutoff_length;\n    const real_type z_min         = radius * 0.5;\n    const real_type dz            = (z_max - z_min) / N;\n\n    real_type z = z_min;\n    for(std::size_t i = 0; i < N; ++i)\n    {\n        const real_type pot1 = exvw.potential(0, z + h);\n        const real_type pot2 = exvw.potential(0, z - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = exvw.derivative(0, z);\n\n        if(std::abs(deri) > tol)\n        {\n            BOOST_TEST(dpot == deri, boost::test_tools::tolerance(tol));\n        }\n        else\n        {\n            BOOST_TEST(deri == 0.0, boost::test_tools::tolerance(tol));\n        }\n        z += dz;\n    }\n}\n", "meta": {"hexsha": "f776b1e51cb7984a4a56f7c55deae0c43ff1d5fe", "size": 1474, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_excluded_volume_wall_potential.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_excluded_volume_wall_potential.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_excluded_volume_wall_potential.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": 30.7083333333, "max_line_length": 78, "alphanum_fraction": 0.6356852103, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5363702941788038}}
{"text": "#include <iostream>\n#include <fstream>\n#include <stack>\n#include <queue>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/assignment.hpp>\n\nnamespace stackqueueAlgorithms\n{      \n      using namespace std;\n\n      /*  print a stack in from bottom to top */\n      template <typename elementType>\n      void printStack(stack<elementType> &input)\n      {\n            stack<elementType> cache;\n            while (!input.empty())\n            {\n                  cache.push(input.top());\n                  input.pop();\n            }\n            while (!cache.empty())\n            {\n                  cout << \"|\" << cache.top();\n                  input.push(cache.top());\n                  cache.pop();\n            }\n            cout << endl;\n      };\n      \n      /* 3.2 \n            a stack class with O(1) return time for the minimum element\n      */\n      template <typename elementType>\n      class minStack\n      {\n            private:\n                  stack< pair<elementType,int> > mins;\n                  stack<elementType> elements;\n            public:\n                  bool empty() { return elements.empty(); };\n                  \n                  int size() { return elements.size(); };\n            \n                  elementType top() { return elements.top(); };\n                  \n                  void push(elementType newElement)\n                  {\n                        if (mins.empty() || newElement < (mins.top()).first ) \n                        { mins.push(make_pair(newElement,1)); }\n                        else\n                        {\n                              if (newElement == (mins.top()).first )\n                              { (mins.top()).second++; }\n                        }\n                        elements.push(newElement);\n                  };\n                  \n                  void pop()\n                  {\n                        if (elements.top() == (mins.top()).first)\n                        { (mins.top()).second--; }\n                        if ((mins.top()).second==0) {mins.pop();}\n                        elements.pop();\n                  };\n                  \n                  elementType min() { return (mins.top()).first; };\n                  \n                  void print() { printStack(elements); };\n      };\n      \n      /*3.3\n            a conventional stack, but as a stack of \"piles\" \n            which are sub-stacks that can also be poped.\n      */\n      template <typename elementType>\n      class pileStack\n      {\n            private: \n                  stack< stack<elementType> > superStack;\n                  int pileSize;\n                  int endPileSize;\n            public:\n                  pileStack(int pileSize) \n                  {\n                        this->pileSize = pileSize;\n                        stack<elementType> s;\n                        superStack.push(s);\n                        endPileSize = 0;\n                  };\n            \n                  int getPileSize() { return pileSize; };\n                  \n                  bool empty() { return superStack.empty(); };\n                  \n                  int size() { return (superStack.size()-1)*pileSize + endPileSize; };\n            \n                  elementType top() { return superStack.top().top(); };\n            \n                  void push(elementType newElement) \n                  {\n                        if (endPileSize<pileSize)\n                        {\n                              superStack.top().push(newElement);\n                              endPileSize++;\n                        }\n                        else\n                        {\n                              stack<elementType> s;\n                              superStack.push(s);\n                              superStack.top().push(newElement);\n                              endPileSize = 1;\n                        }\n                  };\n            \n                  void pop() \n                  {\n                        superStack.top().pop();\n                        endPileSize--;\n                        if (superStack.top().empty()) \n                        { \n                              superStack.pop(); \n                              endPileSize = pileSize;\n                        }\n                  };\n            \n                  void popPile()\n                  {\n                        superStack.pop();\n                        endPileSize = pileSize;\n                  };\n            \n                  void print() \n                  {\n                        stack< stack<elementType> > cache;\n                        while (!superStack.empty())\n                        {\n                              cache.push(superStack.top());\n                              superStack.pop();\n                        }\n                        \n                        while (!cache.empty())\n                        {\n                              printStack(cache.top());\n                              superStack.push(cache.top());\n                              cache.pop();\n                        }\n                        cout << \"--- end --- \" << endl;\n                  };\n      };\n      \n      /*3.5\n            a queue implemented using two stacks \n       */\n      template <typename elementType>\n      class dsQueue\n      {\n            private:\n                  stack<elementType> ls,rs;\n            \n                  void move(bool print)\n                  {\n                        stack<elementType> *fs,*es;\n                        if (ls.empty()) { es = &ls; fs = &rs; }\n                        else { es = &rs; fs = &ls; }\n                        \n                        while (!fs->empty())\n                        {\n                              elementType e = fs->top();\n                              es->push(e); fs->pop(); \n                              if (print) { cout << e << \"<\"; }\n                        }\n                        if (print) { cout << endl; }\n                  };\n            \n                  bool L() {return rs.empty() && !ls.empty();}\n                  bool R() {return ls.empty() && !rs.empty();}\n            \n            public:\n                  bool empty() { return ls.empty() && rs.empty() ;};\n                  \n                  int size() {return ls.size() + rs.size(); };\n                  \n                  void push(elementType newElement) \n                  {\n                        if (this->R()) { this->move(false); }\n                        ls.push(newElement);\n                  };\n            \n                  void pop() \n                  {\n                        if (this->L()) { this->move(false); }\n                        if (!this->empty()) { rs.pop(); }\n                  };\n            \n                  elementType front() \n                  {\n                        if (this->L()) { this->move(false); }\n                        return rs.top();\n                  };\n            \n                  elementType back()\n                  {\n                        if (this->R()) { this->move(false); }\n                        return ls.top();\n                  };\n            \n                  void print()\n                  {\n                        if (this->L()) { this->move(false); }\n                        this->move(true);\n                  };\n      };\n      \n      /* 3.6\n            an insertion-sort type sorting method ( O(N^2) )\n            for a stack using another stack of the same size\n      */\n      template <typename elementType>\n      void slowSort(stack<elementType> &s)\n      {\n            stack<elementType> cache;\n            stack<elementType> *si,*sf,*temp;\n            int iter = 0;\n            int totalLength;\n            \n            while (!s.empty()) { cache.push(s.top()); s.pop(); iter++; }\n            totalLength = iter;\n            \n            si = &cache; sf = &s; \n            while (iter!=0)\n            {\n                  si->push( filterMove(iter,(totalLength-iter)%2!=0,si,sf) );\n                  temp = si; si = sf; sf = temp;\n                  iter--;\n            }\n            \n           while (!cache.empty()) { s.push(cache.top()); cache.pop(); }\n      }\n      \n      // move N elements from si to sf, while taking out the \n      // min (max) if \"min\" = true (false)\n      template <typename elementType>\n      elementType filterMove(int N, bool min, stack<elementType> *si, stack<elementType> *sf)\n      {\n            elementType e,t;\n            e = si->top(); si->pop();\n            for (int j=0;j<N-1;j++) \n            {\n                  t = si->top();\n                  if ( (min && t<e) || (!min && t>e) ) { sf->push(e); e=t; }\n                  else { sf->push(t); }\n                  si->pop();\n            }\n            return e;\n      };      \n      \n      /*\n            print the last K lines of a file in a single run\n            all lines returned if there're fewer than K lines\n      */\n      void printLastKLines(int K, char* filename)\n      {\n            ifstream file(filename);\n            string line;\n            queue<string> q;\n            int count = 0;\n            \n            if (file.is_open())\n            {\n                  while (getline(file,line))\n                  {\n                        q.push(line);\n                        count++;\n                        if (count>K) { q.pop(); }\n                  }         \n                  file.close();\n            }\n            \n            while(!q.empty())\n            {\n                  cout << q.front() << endl;\n                  q.pop();\n            }\n            cout << \"total line count: \" << count << endl;\n      };\n};\n\n\nint main()\n{\n      using namespace stackqueueAlgorithms;\n      using namespace boost::numeric::ublas;\n      \n      matrix<int> input(12,1);\n      input <<= 1,0,1,2,2,1,3,3,3,0,10,11;\n      \n      // testing minStack\n      /*\n      minStack<int> s;\n      for (int j=0;j<input.size1();j++)\n      { s.push(input(j,0)); }\n      \n      while (!s.empty())\n      {\n            cout << \"current stack: \";\n            s.print();\n            cout << \"mininum is \" << s.min() << endl;\n            s.pop();\n      }\n      */\n      \n      // testing pileStack\n      /*\n      pileStack<int> pS = pileStack<int>(4);\n      for (int j=0;j<input.size1();j++)\n      { pS.push(input(j,0)); }\n      pS.print();\n      for (int j=0;j<3;j++)\n      { pS.popPile(); pS.print(); }\n      */\n      \n      // testing dsQueue\n      /*\n      dsQueue<int> dsq;\n      for (int j=0;j<input.size1();j++)\n      { dsq.push(input(j,0)); }\n      while (!dsq.empty())\n      { \n            cout << \"size= \" << dsq.size() << endl;\n            dsq.print();\n            dsq.pop(); \n      } \n      */\n      \n      // testing slowSort\n      /*\n      stack<int> s;\n      for (int j=0;j<input.size1();j++)\n      { s.push(input(j,0)); }\n      printStack(s);\n      slowSort(s);\n      printStack(s);\n      */\n      \n      // testing printLastKLines()\n      char filename[] = \"data.txt\";\n      printLastKLines(4,filename);\n      \n      \n      \n      return 0;\n}", "meta": {"hexsha": "3c3b3ff8b462223ba2a132cc8dd40e5a59c09295", "size": 11031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/stackqueueAlgorithms.cpp", "max_stars_repo_name": "chaohan/code-samples", "max_stars_repo_head_hexsha": "0ae7da954a36547362924003d56a8bece845802c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/stackqueueAlgorithms.cpp", "max_issues_repo_name": "chaohan/code-samples", "max_issues_repo_head_hexsha": "0ae7da954a36547362924003d56a8bece845802c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/stackqueueAlgorithms.cpp", "max_forks_repo_name": "chaohan/code-samples", "max_forks_repo_head_hexsha": "0ae7da954a36547362924003d56a8bece845802c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2492917847, "max_line_length": 93, "alphanum_fraction": 0.3489257547, "num_tokens": 2093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.5363702865006733}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <string.h>\n#include <chrono>\n#include <ctime>\n#include <iostream>\n#include <cmath>\n#include <cfloat>\n\n#include <posit/posit>\n#include <boost/range/combine.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#include \"defines.hpp\"\n#include \"utils.hpp\"\n\nusing namespace std;\nusing namespace sw::unum;\nusing boost::multiprecision::cpp_dec_float_100;\n\ncpp_dec_float_100 decimal_accuracy(cpp_dec_float_100 exact, cpp_dec_float_100 computed) {\n        if (boost::math::isnan(exact) || boost::math::isnan(computed) ||\n            (boost::math::sign(exact) != boost::math::sign(computed))) {\n                return std::numeric_limits<cpp_dec_float_100>::quiet_NaN();\n        } else if (exact == computed) {\n                return std::numeric_limits<cpp_dec_float_100>::infinity();\n        } else if ((exact == std::numeric_limits<cpp_dec_float_100>::infinity() &&\n                    computed != std::numeric_limits<cpp_dec_float_100>::infinity()) ||\n                   (exact != std::numeric_limits<cpp_dec_float_100>::infinity() &&\n                    computed == std::numeric_limits<cpp_dec_float_100>::infinity()) || (exact == 0 && computed != 0) ||\n                   (exact != 0 && computed == 0)) {\n                return -std::numeric_limits<cpp_dec_float_100>::infinity();\n        } else {\n                return -log10(abs(log10(computed / exact)));\n        }\n}\n\nvoid writeBenchmark(DebugValues<posit<NBITS, ES> > &hw_debug_values, DebugValues<posit<NBITS, ES> > &sw_debug_values, DebugValues<float> &float_debug_values,\n                    DebugValues<cpp_dec_float_100> &dec_debug_values, std::string filename) {\n        ofstream outfile(filename, ios::out);\n\n        auto dec_values = dec_debug_values.items;\n        auto hw_values = hw_debug_values.items;\n        auto sw_values = sw_debug_values.items;\n        auto float_values = float_debug_values.items;\n\n        outfile << \"name,dE_f,dE_sw,dE_hw,log(abs(dE_f)),log(abs(dE_sw)),log(abs(dE_hw)),E,E_f,E_sw,E_hw,da_F,da_SW,da_HW\" << endl;\n        for (int i = 0; i < dec_values.size(); i++) {\n                cpp_dec_float_100 E, E_f, E_p, E_hw, E_sw, dE_f, dE_p, dE_hw, dE_sw;\n                cpp_dec_float_100 da_F, da_HW, da_SW; // decimal accuracies\n\n                string name = dec_values[i].name;\n                E = dec_values[i].value;\n\n                auto E_f_entry = std::find_if(float_values.begin(), float_values.end(), find_entry(name));\n                E_f = E_f_entry->value;\n\n                auto E_hw_entry = std::find_if(hw_values.begin(), hw_values.end(), find_entry(name));\n                E_hw = E_hw_entry->value;\n\n                auto E_sw_entry = std::find_if(sw_values.begin(), sw_values.end(), find_entry(name));\n                E_sw = E_sw_entry->value;\n\n                if (name != E_f_entry->name || name != E_sw_entry->name || name != E_hw_entry->name) {\n                        cout << \"Error: mismatching names! Could not find name '\" << E_f_entry->name << endl;\n                }\n\n                cout << \"Decimal accuracy...\" << endl;\n                da_F = decimal_accuracy(E, E_f);\n                da_HW = decimal_accuracy(E, E_hw);\n                da_SW = decimal_accuracy(E, E_sw);\n\n                if (E == 0) {\n                        dE_f = 0;\n                        dE_sw = 0;\n                        dE_hw = 0;\n                } else {\n                        dE_f = (E_f - E) / E;\n                        dE_sw = (E_sw - E) / E;\n                        dE_hw = (E_hw - E) / E;\n                }\n\n                cout << \"Writing out...\" << endl;\n\n                // Relative error values\n                outfile << name << \",\";\n                outfile << setprecision(100) << fixed << dE_f << \",\" << dE_sw << \",\" << dE_hw << \",\" << flush;\n                outfile << setprecision(100) << fixed << log10(abs(dE_f)) << \",\" << log10(abs(dE_sw)) << \",\" << log10(abs(dE_hw)) << \",\" << flush;\n                outfile << setprecision(100) << fixed << E << \",\" << E_f << \",\" << E_sw << \",\" << E_hw << \",\" << flush;\n                outfile << setprecision(100) << fixed << da_F << \",\" << da_SW << \",\" << da_HW << endl << flush;\n        }\n        cout << \"Closing file...\" << endl;\n        outfile.close();\n}\n", "meta": {"hexsha": "fa1242744e7709d767da75d98573963cef0fa1d7", "size": 4298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/gram/src/utils.cpp", "max_stars_repo_name": "lvandam/posit_blas_hdl", "max_stars_repo_head_hexsha": "4427bcf13cede86f626772903c546cbeae42457e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-31T10:22:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-31T22:24:22.000Z", "max_issues_repo_path": "examples/test/src/utils.cpp", "max_issues_repo_name": "lvandam/posit_blas_hdl", "max_issues_repo_head_hexsha": "4427bcf13cede86f626772903c546cbeae42457e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-01T12:49:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-01T12:49:45.000Z", "max_forks_repo_path": "examples/test/src/utils.cpp", "max_forks_repo_name": "lvandam/posit_blas_hdl", "max_forks_repo_head_hexsha": "4427bcf13cede86f626772903c546cbeae42457e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3092783505, "max_line_length": 157, "alphanum_fraction": 0.5444392741, "num_tokens": 1050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5363702846686422}}
{"text": "/**\n * @file\n *\n * @brief Test the dlib library for fitting.\n *\n * @author Hendrix Demers <hendrix.demers@mail.mcgill.ca>\n * @since 1.0\n */\n\n// Copyright 2016 Hendrix Demers\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// C system headers\n// C++ system header\n#include <iostream>\n#include <vector>\n// Library headers\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n// Precompiled header\n#pragma hdrstop\n// Current declaration header file of this implementation file.\n#include <dlib/optimization.h>\n// Project headers\n// Project private headers\n\n// Global and constant variables/functions.\n\nusing namespace std;\nusing namespace dlib;\n\ntypedef matrix<double,2,1> input_vector;\ntypedef matrix<double,3,1> parameter_vector;\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\nBOOST_AUTO_TEST_SUITE(test_dlib)\n\n/**\n * @brief Test if this testcase file is included in the testsuite and run.\n */\nBOOST_AUTO_TEST_CASE(test_is_working)\n{\n    //BOOST_FAIL( \"Nothing to test\" );\n    BOOST_CHECK(true);\n}\n\n    /**\n     * @brief Test\n     */\n    BOOST_AUTO_TEST_CASE(test_least_square_example)\n    {\n        const double tolerance = 0.001;\n\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\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            BOOST_CHECK_SMALL(length(residual_derivative(data_samples[0], params) -\n                                                  derivative(residual)(data_samples[0], params) ), 1.0e-05);\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\n            x = 1;\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                                   data_samples,\n                                   x);\n\n            // Now x contains the solution.  If everything worked it will be equal to params.\n            BOOST_CHECK_CLOSE(params(0, 0), x(0, 0), tolerance);\n            BOOST_CHECK_CLOSE(params(1, 0), x(1, 0), tolerance);\n            BOOST_CHECK_CLOSE(params(2, 0), x(2, 0), tolerance);\n            BOOST_CHECK_SMALL(length(x - params), 3.0e-15);\n\n            x = 1;\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                                   derivative(residual),\n                                   data_samples,\n                                   x);\n\n            // Now x contains the solution.  If everything worked it will be equal to params.\n            BOOST_CHECK_CLOSE(params(0, 0), x(0, 0), tolerance);\n            BOOST_CHECK_CLOSE(params(1, 0), x(1, 0), tolerance);\n            BOOST_CHECK_CLOSE(params(2, 0), x(2, 0), tolerance);\n            BOOST_CHECK_SMALL(length(x - params), 5.0e-15);\n\n            x = 1;\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),\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            BOOST_CHECK_CLOSE(params(0, 0), x(0, 0), tolerance);\n            BOOST_CHECK_CLOSE(params(1, 0), x(1, 0), tolerance);\n            BOOST_CHECK_CLOSE(params(2, 0), x(2, 0), tolerance);\n            BOOST_CHECK_SMALL(length(x - params), 1.0e-14);\n\n            x = 1;\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),\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            BOOST_CHECK_CLOSE(params(0, 0), x(0, 0), tolerance);\n            BOOST_CHECK_CLOSE(params(1, 0), x(1, 0), tolerance);\n            BOOST_CHECK_CLOSE(params(2, 0), x(2, 0), tolerance);\n            BOOST_CHECK_SMALL(length(x - params), 1.0e-14);\n        }\n        catch (std::exception& e)\n        {\n            cout << e.what() << endl;\n        }\n\n        //BOOST_FAIL( \"Nothing to test\" );\n        BOOST_CHECK(true);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "8a5dfce78ec4c44f61b66600ea04a6bbe383dcba", "size": 8109, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/testing/test_dlib.cpp", "max_stars_repo_name": "drix00/xray_spectrum_analyzer", "max_stars_repo_head_hexsha": "fec0aee90ec051f7f517b5c81bf7ec6972dec3c6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T06:14:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T04:19:27.000Z", "max_issues_repo_path": "cpp/src/testing/test_dlib.cpp", "max_issues_repo_name": "drix00/xray_spectrum_analyzer", "max_issues_repo_head_hexsha": "fec0aee90ec051f7f517b5c81bf7ec6972dec3c6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2016-12-11T17:39:45.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-20T23:11:51.000Z", "max_forks_repo_path": "cpp/src/testing/test_dlib.cpp", "max_forks_repo_name": "drix00/xray_spectrum_analyzer", "max_forks_repo_head_hexsha": "fec0aee90ec051f7f517b5c81bf7ec6972dec3c6", "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.6923076923, "max_line_length": 108, "alphanum_fraction": 0.5863854976, "num_tokens": 1772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.5363702846686422}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    cpp_int a, k; cin >> a >> k;\n    if (k == 0) cout << (cpp_int)(2000000000000) - a << endl;\n    else {\n        cpp_int sum = a, cnt = 0;\n        while ((cpp_int)(2000000000000) > sum) {\n            cnt++;\n            sum += 1 + (k * sum);\n        }\n        cout << cnt << endl;\n    }\n}\n", "meta": {"hexsha": "2c222864b19b68bece4094d6eb9799144e208205", "size": 482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/arc057/a/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/arc057/a/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/arc057/a/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": 24.1, "max_line_length": 61, "alphanum_fraction": 0.5497925311, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5362724932214471}}
{"text": "// Copyright Oleg Maximenko 2014.\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://github.com/svgpp/svgpp for library home page.\n\n#pragma once\n\n#include <boost/cstdint.hpp>\n#include <boost/gil/channel_algorithm.hpp>\n#include <boost/gil/gray.hpp>\n#include <boost/gil/rgb.hpp>\n#include <boost/gil/rgba.hpp>\n\nnamespace svgpp \n{ \n\nnamespace gil_detail \n{\n\n/// red * 0.2125 + green * 0.7154 + blue * 0.0721\n\n// The default implementation of to_luminance uses float0..1 as the intermediate channel type\ntemplate <typename RedChannel, typename GreenChannel, typename BlueChannel, typename GrayChannelValue>\nstruct rgb_to_luminance_fn \n{\n  GrayChannelValue operator()(const RedChannel& red, const GreenChannel& green, const BlueChannel& blue) const \n  {\n    using namespace boost::gil;\n    return channel_convert<GrayChannelValue>(\n      channel_convert<float32_t>(red  )*0.2125f +\n      channel_convert<float32_t>(green)*0.7154f +\n      channel_convert<float32_t>(blue )*0.0721f);\n  }\n};\n\n// performance specialization for unsigned char\ntemplate <typename GrayChannelValue>\nstruct rgb_to_luminance_fn<boost::uint8_t, boost::uint8_t, boost::uint8_t, GrayChannelValue> \n{\n  GrayChannelValue operator()(boost::uint8_t red, boost::uint8_t green, boost::uint8_t blue) const \n  {\n    return boost::gil::channel_convert<GrayChannelValue>(boost::uint8_t(\n       (boost::uint32_t(red)   * boost::uint32_t(0.2125 * (1 << 14)) \n      + boost::uint32_t(green) * boost::uint32_t(0.7154 * (1 << 14)) \n      + boost::uint32_t(blue)  * boost::uint32_t(0.0721 * (1 << 14))) >> 14));\n  }\n};\n\ntemplate <typename GrayChannel, typename RedChannel, typename GreenChannel, typename BlueChannel>\ninline typename boost::gil::channel_traits<GrayChannel>::value_type rgb_to_luminance(\n  const RedChannel& red, const GreenChannel& green, const BlueChannel& blue) \n{\n  return rgb_to_luminance_fn<RedChannel,GreenChannel,BlueChannel,\n                              typename boost::gil::channel_traits<GrayChannel>::value_type>()(red,green,blue);\n}\n\n}   // namespace gil_detail\n\nnamespace gil_utility \n{\n\ntemplate<class DestChannel = boost::gil::gray_color_t>\nstruct rgb_to_luminance_color_converter \n{\n  template <typename P1, typename P2>\n  void operator()(const P1& src, P2& dst) const \n  {\n    using namespace boost::gil;\n    get_color(dst, DestChannel()) = \n      gil_detail::rgb_to_luminance<typename color_element_type<P2, DestChannel>::type>(\n          get_color(src, red_t()), \n          get_color(src, green_t()), \n          get_color(src, blue_t())\n      );\n  }\n};\n\ntemplate<class DestChannel = boost::gil::gray_color_t>\nstruct rgba_to_mask_color_converter \n{\n  template <typename P1, typename P2>\n  void operator()(const P1& src, P2& dst) const \n  {\n    using namespace boost::gil;\n    get_color(dst, DestChannel()) = \n      boost::gil::channel_convert<typename color_element_type<P2, DestChannel>::type>(\n        channel_multiply(\n          gil_detail::rgb_to_luminance<typename color_element_type<P1, alpha_t>::type>(\n              get_color(src, red_t()), \n              get_color(src, green_t()), \n              get_color(src, blue_t())\n          ),\n          get_color(src, alpha_t())\n        )\n      );\n  }\n};\n\n}}\n", "meta": {"hexsha": "415ca6d816ec8a6ce7df10661cce9fd331a3e66f", "size": 3317, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/svgpp/utility/gil/mask.hpp", "max_stars_repo_name": "magjac/svgpp", "max_stars_repo_head_hexsha": "536233cbf232c26a5a2d532b63b2c9ab7338bdc0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 428.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:25:47.000Z", "max_issues_repo_path": "include/svgpp/utility/gil/mask.hpp", "max_issues_repo_name": "andrew2015/svgpp", "max_issues_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T14:32:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T16:55:11.000Z", "max_forks_repo_path": "include/svgpp/utility/gil/mask.hpp", "max_forks_repo_name": "andrew2015/svgpp", "max_forks_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2015-05-19T04:56:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:42:50.000Z", "avg_line_length": 32.5196078431, "max_line_length": 111, "alphanum_fraction": 0.6964124209, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5362724932214471}}
{"text": "/**\n * \\file\n *\n * \\copyright\n * Copyright (c) 2012-2020, 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 <boost/math/special_functions/pow.hpp>\n#include <cmath>\n\n#include \"MaterialLib/MPL/Properties/Exponential.h\"\n\nnamespace MaterialPropertyLib\n{\nExponential::Exponential(std::string name,\n                         PropertyDataType const& property_reference_value,\n                         ExponentData const& v)\n    : exponent_data_(v)\n{\n    name_ = std::move(name);\n    auto const f = std::get<double>(exponent_data_.factor);\n    auto const v0 = std::get<double>(exponent_data_.reference_condition);\n    value_ = std::get<double>(property_reference_value) * std::exp(-f * v0);\n}\n\nPropertyDataType Exponential::value(\n    VariableArray const& variable_array,\n    ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/,\n    double const /*dt*/) const\n{\n    auto const f = std::get<double>(exponent_data_.factor);\n    auto const v =\n        std::get<double>(variable_array[static_cast<int>(exponent_data_.type)]);\n\n    return std::get<double>(value_) * std::exp(f * v);\n}\n\nPropertyDataType Exponential::dValue(\n    VariableArray const& variable_array, Variable const primary_variable,\n    ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/,\n    double const /*dt*/) const\n{\n    if (exponent_data_.type != primary_variable)\n    {\n        return 0.;\n    }\n\n    auto const f = std::get<double>(exponent_data_.factor);\n    auto const v =\n        std::get<double>(variable_array[static_cast<int>(exponent_data_.type)]);\n\n    return std::get<double>(value_) * f * std::exp(f * v);\n}\n\nPropertyDataType Exponential::d2Value(\n    VariableArray const& variable_array, Variable const pv1, Variable const pv2,\n    ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/,\n    double const /*dt*/) const\n{\n    if (exponent_data_.type != pv1 && exponent_data_.type != pv2)\n    {\n        return 0.;\n    }\n\n    auto const f = std::get<double>(exponent_data_.factor);\n    auto const v =\n        std::get<double>(variable_array[static_cast<int>(exponent_data_.type)]);\n\n    return std::get<double>(value_) * f * f * std::exp(f * v);\n}\n\n}  // namespace MaterialPropertyLib\n", "meta": {"hexsha": "dc9d0d50a950585487516f6bb4e2d4da7fd7c76d", "size": 2368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MaterialLib/MPL/Properties/Exponential.cpp", "max_stars_repo_name": "renchao-lu/ogs6", "max_stars_repo_head_hexsha": "0f30c514ac6d905302a453cb9928016c996d78e6", "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": "MaterialLib/MPL/Properties/Exponential.cpp", "max_issues_repo_name": "renchao-lu/ogs6", "max_issues_repo_head_hexsha": "0f30c514ac6d905302a453cb9928016c996d78e6", "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": "MaterialLib/MPL/Properties/Exponential.cpp", "max_forks_repo_name": "renchao-lu/ogs6", "max_forks_repo_head_hexsha": "0f30c514ac6d905302a453cb9928016c996d78e6", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-09T10:58:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-09T10:58:04.000Z", "avg_line_length": 31.1578947368, "max_line_length": 80, "alphanum_fraction": 0.6638513514, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5362688724846187}}
{"text": "// Copyright (c) 2020, Ryohei Sasaki\n// All rights reserved.\n//\n// Software License Agreement (BSD License 2.0)\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 {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 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#ifndef IMU_ESTIMATOR__EKF_HPP_\n#define IMU_ESTIMATOR__EKF_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iostream>\n\nclass EKFEstimator\n{\npublic:\n  EKFEstimator()\n  : Cov_(Eigen::Matrix<double, 7, 7>::Identity() * 1.0),\n    Q_(Eigen::Matrix3d::Identity() * 0.01),\n    R_(Eigen::Matrix3d::Identity() * 0.033),\n    gravity_vec_(Eigen::Vector3d(0.0, 0.0, 9.8067)),\n    tau_gyro_bias_{1.0}\n  {\n    /* x =[qw qx qy qz gyro_bias_x gyro_bias_y gyro_bias_z] */\n    x_ << 1, 0, 0, 0, 0, 0, 0;\n  }\n\n  void predictionUpdate(\n    Eigen::Matrix<double, 7, 1> & predeted_x,\n    Eigen::Matrix<double, 7, 7> & predeted_Cov,\n    const Eigen::Vector3d & gyro)\n  {\n    Eigen::Vector4d quat = x_.head<4>();\n    Eigen::Vector3d gyro_bias = x_.tail<3>();\n\n    /* gyro2omega */\n    Eigen::Vector3d w = gyro - gyro_bias;\n    Eigen::Matrix4d omega;\n    omega <<\n      0, -w[0], -w[1], -w[2],\n      w[0], 0, w[2], -w[1],\n      w[1], -w[2], 0, w[0],\n      w[2], w[1], -w[0], 0;\n\n    /* predeted_x = f(x, w) */\n    Eigen::Vector4d predeted_quat;\n    predeted_quat = quat + dt_ / 2 * omega * quat;\n    predeted_x.head<4>() = predeted_quat.normalized();\n    predeted_x.tail<3>() = gyro_bias;\n\n    /* predeted_Cov = F Cov_ Ft + L Q_ Lt */\n    /* F */\n    Eigen::Matrix<double, 7, 7> F;\n    F = Eigen::Matrix<double, 7, 7>::Identity();\n    F.block<4, 4>(0, 0) += dt_ / 2 * omega;\n    F.block<4, 3>(0, 4) <<\n      +quat[1], +quat[2], +quat[3],\n      -quat[0], +quat[3], -quat[2],\n      -quat[3], -quat[0], +quat[1],\n      +quat[2], -quat[1], -quat[0];\n    F.block<4, 3>(0, 4) *= dt_ / 2;\n    F.block<3, 3>(3, 3) -= Eigen::Matrix<double, 3, 3>::Identity() * dt_ / tau_gyro_bias_;\n    /* L */\n    Eigen::Matrix<double, 7, 3> L;\n    L <<\n      -quat[1], -quat[2], -quat[3],\n      +quat[0], -quat[3], +quat[2],\n      +quat[3], +quat[0], -quat[1],\n      -quat[2], +quat[1], +quat[0],\n      0, 0, 0,\n      0, 0, 0,\n      0, 0, 0;\n    L *= dt_ / 2;\n    predeted_Cov = F * Cov_ * F.transpose() + L * Q_ * L.transpose();\n  }\n\n  void observationUpdate(\n    const Eigen::Matrix<double, 7, 1> & predeted_x,\n    const Eigen::Matrix<double, 7, 7> & predeted_Cov,\n    const Eigen::Vector3d & z)\n  {\n    Eigen::Vector4d predeted_quat = predeted_x.head<4>();\n\n    /* y = z - h(x) */\n    Eigen::Vector3d acc;\n    Eigen::Quaternion<double> quat_tmp(predeted_quat[0], predeted_quat[1],\n      predeted_quat[2], predeted_quat[3]);\n    acc = quat_tmp.conjugate()._transformVector(gravity_vec_);\n    Eigen::Vector3d y = z - acc;\n\n    /* H */\n    Eigen::Matrix<double, 3, 7> H;\n    double qw = predeted_quat[0], qx = predeted_quat[1],\n      qy = predeted_quat[2], qz = predeted_quat[3];\n    H <<\n      -qy, +qz, -qw, +qx, 0, 0, 0,\n      +qx, +qw, +qz, +qy, 0, 0, 0,\n      +qw, -qx, -qy, +qz, 0, 0, 0;\n    H *= 2 * gravity_vec_[2];\n\n    /* x_ */\n    Eigen::Matrix<double, 7, 3> K = predeted_Cov * H.transpose() *\n      (H * predeted_Cov * H.transpose() + R_).inverse();\n    Eigen::Matrix<double, 7, 1> x_tmp = predeted_x + K * y;\n    x_.head<4>() = x_tmp.head<4>().normalized();\n    x_.tail<3>() = x_tmp.tail<3>();\n\n    /* Cov_ */\n    Cov_ = (Eigen::Matrix<double, 7, 7>::Identity() - K * H) * predeted_Cov;\n  }\n\n  void filterOneStep(\n    Eigen::Quaternion<double> & quat,\n    const double dt,\n    const Eigen::Vector3d & acc,\n    const Eigen::Vector3d & gyro)\n  {\n    setdt(dt);\n\n    Eigen::Matrix<double, 7, 1> predeted_x;\n    Eigen::Matrix<double, 7, 7> predeted_Cov;\n    predictionUpdate(predeted_x, predeted_Cov, gyro);\n\n    observationUpdate(predeted_x, predeted_Cov, acc);\n\n    Eigen::Quaternion<double> quat_tmp(x_[0], x_[1], x_[2], x_[3]);\n    quat = quat_tmp;\n  }\n\n  void setdt(const double dt)\n  {\n    dt_ = dt;\n  }\n\n  void setProcessNoize(const double process_noize)\n  {\n    Q_ = Eigen::Matrix3d::Identity() * process_noize;\n  }\n\n\n  void setObservationNoize(const double observation_noize)\n  {\n    R_ = Eigen::Matrix3d::Identity() * observation_noize;\n  }\n\nprivate:\n  Eigen::Matrix<double, 7, 1> x_;\n  Eigen::Matrix<double, 7, 7> Cov_;\n  double dt_;\n\n  Eigen::Matrix3d Q_, R_;\n  Eigen::Vector3d gravity_vec_;\n  double tau_gyro_bias_;\n};\n\n#endif  // IMU_ESTIMATOR__EKF_HPP_\n", "meta": {"hexsha": "85f42207c45083358095ecd22e67fbbcab28b719", "size": 5775, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/imu_estimator/ekf.hpp", "max_stars_repo_name": "rsasaki0109/imu_estimator", "max_stars_repo_head_hexsha": "876aff5250a0d74fbcf7bb3c3493cad2e70e4fe5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2020-03-31T08:08:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T17:00:02.000Z", "max_issues_repo_path": "include/imu_estimator/ekf.hpp", "max_issues_repo_name": "rsasaki0109/imu_estimator", "max_issues_repo_head_hexsha": "876aff5250a0d74fbcf7bb3c3493cad2e70e4fe5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-29T02:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-05T10:51:26.000Z", "max_forks_repo_path": "include/imu_estimator/ekf.hpp", "max_forks_repo_name": "rsasaki0109/imu_estimator", "max_forks_repo_head_hexsha": "876aff5250a0d74fbcf7bb3c3493cad2e70e4fe5", "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.7307692308, "max_line_length": 90, "alphanum_fraction": 0.6285714286, "num_tokens": 1875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5362688724846186}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <boost/assert.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include <iostream>\n\n\nconst double PI = boost::math::constants::pi<double>();\n\ntemplate <typename FT2, typename FT3>\ndouble\noverlap3_inner(const FT2 &ft2,\n               const FT3 &ft3,\n               int k1,\n               int k2,\n               double txp,\n               double txpp,\n               double tx,\n               double typ,\n               double typp,\n               double ty)\n{\n  // k' <=> ft2\n  // k'' <=> ft3\n  int Np = ft2.rows();\n  int Mp = ft2.cols();\n  int Npp = ft3.rows();\n  int Mpp = ft3.cols();\n\n  BOOST_VERIFY(Np % 2 == 0);\n  BOOST_VERIFY(Mp % 2 == 0);\n  BOOST_VERIFY(Npp % 2 == 0);\n  BOOST_VERIFY(Mpp % 2 == 0);\n\n  int np = Np / 2;\n  int mp = Mp / 2;\n  int npp = Npp / 2;\n  int mpp = Mpp / 2;\n\n  double vsum = 0;\n\n  for (int k1p = std::max(-npp + 1 - k1, -np); k1p <= std::min(npp - k1, np - 1); ++k1p) {\n    int i1p = k1p + np;\n    for (typename FT2::InnerIterator itp(ft2, i1p); itp; ++itp) {\n      int i2p = itp.col();\n      int k2p = i2p - mp;\n      int k1pp = -k1 - k1p;\n      int i1pp = k1pp + npp;\n      int k2pp = -k2 - k2p;\n      int i2pp = k2pp + mpp;\n\n      if (k2pp >= -mpp + 1 && k2pp <= mpp - 1)\n        vsum += itp.value() * ft3.coeff(i1pp, i2pp) *\n                std::cos(2 * PI *\n                         (k2p * typ + k2pp * typp + k2 * ty + k1p * txp + k1pp * txpp + k1 * tx));\n    }\n  }\n  // std::cout << \"hits: (\" << k1 << \", \" << k2 << \"): \" << hits << \"\\n\";\n  return vsum;\n}\n\n/**\n *\n *\n * @param ft1\n * @param ft2\n * @param ft3\n * @param tp    \\f$t' \\in [0,1] \\f$\n * @param tpp   \\f$t'' \\in [0,1] \\f$\n * @param t     \\f$t \\in [0,1] \\f$\n *\n * @return\n */\ntemplate <typename FT1, typename FT2, typename FT3>\ndouble\noverlap3(const FT1 &ft1,\n         const FT2 &ft2,\n         const FT3 &ft3,\n         const Eigen::Vector2d &tp = {0, 0},\n         const Eigen::Vector2d &tpp = {0, 0},\n         const Eigen::Vector2d &t = {0, 0})\n{\n  int N = ft1.rows();\n  int n = N / 2;\n  int M = ft1.cols();\n  int m = M / 2;\n\n  BOOST_VERIFY(N % 2 == 0);\n  BOOST_VERIFY(M % 2 == 0);\n\n  double txp = tp[0];\n  double typ = tp[1];\n  double txpp = tpp[0];\n  double typp = tpp[1];\n  double tx = t[0];\n  double ty = t[1];\n  double vsum = 0;\n  for (int i = 0; i < N; ++i) {\n    int k1 = i - n;\n    if (k1 >= 0)\n      for (typename FT1::InnerIterator it(ft1, i); it; ++it) {\n        int j = it.col();\n        int k2 = j - m;\n        double f1 = it.value();\n        if (k1 == 0)\n          vsum += f1 * overlap3_inner(ft2, ft3, k1, k2, txp, txpp, tx, typ, typp, ty);\n        else\n          vsum += 2 * f1 * overlap3_inner(ft2, ft3, k1, k2, txp, txpp, tx, typ, typp, ty);\n      }\n    else\n      continue;\n  }\n  return vsum;\n}\n\n// center ft1 on (0, 0) frequency at (ky, kx) in ft2 and compute cwise prod and\n// sum\ntemplate <typename FT>\ndouble\noverlap_simple_inner(const FT &ft1,\n                     const FT &ft2,\n                     int ky,  // row frequency\n                     int kx,  // col frequency\n                     const Eigen::Vector2d &t12,\n                     const Eigen::Vector2d &t23)\n{\n  // std::cout << \"overlap_simple_inner (ky, kx): \" << ky << \" \" << kx << \"\\n\";\n  int N1 = ft1.rows();\n  int M1 = ft1.cols();\n\n  int N2 = ft2.rows();\n  int M2 = ft2.cols();\n\n  static_assert(FT::IsRowMajor);\n\n  // assume n, m even!\n  assert(N1 % 2 == 0);\n  assert(M1 % 2 == 0);\n  assert(N2 % 2 == 0);\n  assert(M2 % 2 == 0);\n\n  int n1 = N1 / 2;\n  int m1 = M1 / 2;\n  int n2 = N2 / 2;\n  int m2 = M2 / 2;\n\n  // freq. range of ft1\n  int y1h_min = -n1;\n  int y1h_max = n1 - 1;\n  int x1h_min = -m1;\n  int x1h_max = m1 - 2;\n\n  // freq. range of ft2\n  int y2h_min = -n2;\n  int y2h_max = n2 - 1;\n  int x2h_min = -m2;\n  int x2h_max = m2 - 1;\n\n  // compute the minimum frequency range of ft1 that has to be considered\n  int y1h_beg = std::max(-n1, 1 - n2 + ky);\n  int y1h_end = std::min(n1 - 1, n2 + ky);\n  int x1h_beg = std::max(-m1, 1 - m2 + kx);\n  int x1h_end = std::min(m1 - 1, m2 + kx);\n\n  // define function which maps frequencies (yhat, xhat) to array indices (i,\n  // j).\n  auto to_i1 = [n1](int y1h) { return y1h + n1; };\n  auto to_j1 = [m1](int x1h) { return x1h + m1; };\n  auto to_i2 = [n2](int y2h) { return y2h + n2; };\n  auto to_j2 = [m2](int x2h) { return x2h + m2; };\n  // and their inverses:\n  auto to_y1 = [n1](int i1) { return i1 - n1; };\n  auto to_x1 = [m1](int j1) { return j1 - m1; };\n  auto to_y2 = [n2](int i2) { return i2 - n2; };\n  auto to_x2 = [m2](int j2) { return j2 - m2; };\n\n  // std::cout << \"y in [\" << y1h_beg << \", \" << y1h_end << \"]\"\n  //           << std::endl\n  //           << \"x in [\" << x1h_beg << \", \" << x1h_end << \"]\"\n  //           << std::endl;\n\n  const Eigen::Vector2d xh = {ky, kx};\n\n  typedef typename FT::InnerIterator it_t;\n  typedef typename FT::StorageIndex StorageIndex;\n  double vsum = 0;\n\n  const StorageIndex *ft2_cols = ft2.innerIndexPtr();\n  const StorageIndex *ft2_outer = ft2.outerIndexPtr();\n  const double *ft2_values = ft2.valuePtr();\n\n  // iterate over rows in ft1\n  for (int y1h = y1h_beg; y1h <= y1h_end; ++y1h) {\n    // obtain row of ft1\n    it_t ity1(ft1, to_i1(y1h));\n    int x1h = to_x1(ity1.col());\n\n    // std::cout << \"x1h (first nnz): \" << x1h << \"\\t\";\n    // std::cout << \"xbegin: \" << x1h_beg << \"\\n\";\n\n    // search forward in ft1\n    while (to_x1(ity1.col()) < x1h_beg) {\n      // std::cout << \" nnz... \" << to_x1(ity1.col()) << \"\\n\";\n      ++ity1;\n    }\n    if (!bool(ity1)) {\n      continue;  // skip, there are no entries in ft1(y1h, :) to consider\n    }\n\n    int y2h = ky - y1h;  // corresp. row freq. in ft2\n    // get raw Eigen pointers to current row in ft2\n    int ft2_col = to_i2(y2h);\n    int ft2_row_begin = ft2_outer[ft2_col];\n    int ft2_row_end = ft2_outer[ft2_col + 1];\n\n    // get last nonzero position in current row of ft2\n    int ft2_rindex = ft2_row_end - 1;\n    // iterate over columns in ft1\n    for (; bool(ity1) && to_x1(ity1) <= x1h_end; ++ity1) {\n      x1h = to_x1(ity1.col());\n      // search backward in ft2\n      // Note: to_x2(ft2_cols[ft2_rindex]) => x2h\n      while (to_x2(ft2_cols[ft2_rindex]) > kx - x1h && ft2_rindex >= ft2_row_begin) --ft2_rindex;\n      int x2h = to_x2(ft2_cols[ft2_rindex]);\n      if (x2h == kx - x1h) {\n        // matching position found, update\n        double ft2_value = ft2_values[ft2_rindex];\n        const Eigen::Vector2d xhp = {y1h, x1h};\n        vsum += std::cos(2 * PI * t12.dot(xhp) + 2 * PI * t23.dot(xh)) * ity1.value() * ft2_value;\n      } else if (x2h < kx - x1h_end) {\n        // x2h hast left the range of ft1,\n        // done with current row, continue with next row (y1h).\n        break;\n      }\n    }\n  }\n  return vsum;\n}\n\ntemplate <typename FT>\ndouble\noverlap3_simple(const FT &ft1,\n                const FT &ft2,\n                const FT &ft3,\n                const Eigen::Vector2d &t12 = {0, 0},\n                const Eigen::Vector2d &t23 = {0, 0})\n{\n  int N = ft1.rows();\n  int M = ft1.cols();\n\n  assert(N % 2 == 0);\n  assert(M % 2 == 0);\n\n  int n = N / 2;\n  int m = M / 2;\n  double vsum = 0;\n\n  for (int i = n; i < N; ++i) {\n    int k1 = i - n;\n    // std::cout << \"overlap3_simple::k1 \" << k1 << \"\\n\";\n\n    if (k1 >= 0)\n      for (typename FT::InnerIterator it(ft1, i); it; ++it) {\n        int j = it.col();\n        int k2 = j - m;\n        double f1 = it.value();\n\n        if (k1 == 0)\n          vsum += f1 * overlap_simple_inner(ft2, ft3, k1, k2, t12, t23);\n        else\n          vsum += 2 * f1 * overlap_simple_inner(ft2, ft3, k1, k2, t12, t23);\n      }\n    else\n      continue;\n  }\n  return vsum;\n}\n", "meta": {"hexsha": "b57d490dc0e4fbef2b815396f0344bf76df36de3", "size": 7589, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "matrices/tensor_entries.hpp", "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": "matrices/tensor_entries.hpp", "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": "matrices/tensor_entries.hpp", "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": 27.1035714286, "max_line_length": 98, "alphanum_fraction": 0.5164053235, "num_tokens": 2816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5362688608826295}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 2013 - 2017 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 at\n * the top level of the deal.II distribution.\n *\n * ---------------------------------------------------------------------\n\n *\n * Author: Wolfgang Bangerth, Texas A&M University, 2013\n */\n\n\n// The program starts with the usual include files, all of which you should\n// have seen before by now:\n#include <deal.II/base/utilities.h>\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/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/constraint_matrix.h>\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/grid_out.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/data_out.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/error_estimator.h>\n#include <deal.II/numerics/solution_transfer.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/base/conditional_ostream.h>\n#include <deal.II/lac/sparsity_tools.h>\n// MPI STUFF\n#include <deal.II/base/mpi.h>\n#include <deal.II/distributed/shared_tria.h>\n#include <deal.II/lac/petsc_parallel_vector.h>\n#include <deal.II/lac/petsc_parallel_sparse_matrix.h>\n#include <deal.II/lac/petsc_solver.h>\n#include <deal.II/lac/petsc_precondition.h>\n\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/dofs/dof_renumbering.h>\n\n\n#include <fstream>\n#include <iostream>\n\n\nnamespace DistributedHE\n{\n\tusing namespace dealii;\n\n\ttemplate<int dim>\n\t\tclass HeatEquation\n\t\t{\n\t\tpublic:\n\t\t\tHeatEquation();\n\t\t\tvoid increment_time();\n\t\t\tvoid run();\n\n\t\tprivate:\n\t\t\tvoid setup_system();\n\t\t\tdouble solve_time_step();\n\t\t\tvoid create_grid();\n\t\t\tvoid output_results() const;\n\t\t\tvoid assemble_system();\n\t\t\tvoid make_dirichlet_boundary_conditions();\n\n\t\t\tMPI_Comm mpi_communicator;\n\t\t\tconst unsigned int n_mpi_processes;\n\t\t\tconst unsigned int this_mpi_process;\n\n\t\t\tConditionalOStream pcout;\n\n\t\t\tparallel::shared::Triangulation<dim> triangulation;\n\t\t\tFE_Q<dim>            fe;\n\t\t\tDoFHandler<dim>      dof_handler;\n\n\t\t\tConstraintMatrix     constraints;\n\n\t\t\tPETScWrappers::MPI::SparseMatrix system_matrix;\n\n\t\t\tVector<double>                   solution;\n\t\t\tPETScWrappers::MPI::Vector       system_rhs;\n\n\t\t\tIndexSet locally_owned_dofs;\n\t\t\tIndexSet locally_relevant_dofs;\n\t\t\tstd::vector<types::global_dof_index> local_dofs_per_process;\n\t\t\tunsigned int n_local_cells;\n\n\t\t\tdouble               time = 0;\n\t\t\tdouble               time_step = 60;\n\t\t\tunsigned int         timestep_number = 0;\n\t\t\tconst double         theta = 0.5;\n\t\t}\n\t\t;\n\n\n\ttemplate <int dim>\n\t\tvoid HeatEquation<dim>::increment_time()\n\t\t{\n\t\t\ttimestep_number++;\n\t\t\ttime += time_step;\n\t\t}\n\n\ttemplate<int dim>\n\t\tvoid HeatEquation<dim>::create_grid()\n\t\t{\n\t\t\tconst double size = 0.1;   \t// meter\n\t\t\tGridGenerator::hyper_cube(triangulation, 0, size, true);\n\t\t\ttriangulation.refine_global(5);\n\t\t}\n\n\n\ttemplate<int dim>\n\t\tHeatEquation<dim>::HeatEquation()\n\t\t\t: mpi_communicator(MPI_COMM_WORLD)\n\t\t\t, n_mpi_processes(Utilities::MPI::n_mpi_processes(mpi_communicator))\n\t\t\t, this_mpi_process(Utilities::MPI::this_mpi_process(mpi_communicator))\n\t\t\t, pcout(std::cout, (this_mpi_process == 0))\n\t\t\t, triangulation(MPI_COMM_WORLD)\n\t\t\t, fe(1)\n\t\t\t, dof_handler(triangulation)\n\t\t\t, n_local_cells (numbers::invalid_unsigned_int)\n\t\t{\n\t\t\n\t\t}\n\n\n\ttemplate<int dim>\n\t\tvoid HeatEquation<dim>::setup_system()\n\t\t{\n\t\t\tdof_handler.distribute_dofs(fe);\n\t\t\tlocally_owned_dofs = dof_handler.locally_owned_dofs();\n\t\t\tDoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs);\n\t\t\tn_local_cells  = GridTools::count_cells_with_subdomain_association(triangulation, triangulation.locally_owned_subdomain());\n\t\t\tlocal_dofs_per_process = dof_handler.n_locally_owned_dofs_per_processor();\n\n\n\t\t\tconstraints.clear();\n\t\t\tDoFTools::make_hanging_node_constraints(dof_handler, constraints);\n\t\t\tmake_dirichlet_boundary_conditions();\n\t\t\tconstraints.close();\n\n\n\t\t\tDynamicSparsityPattern dsp(locally_relevant_dofs);\n\t\t\tDoFTools::make_sparsity_pattern(dof_handler, dsp, constraints, /*keep_constrained_dofs = */ false);\n\t\t\tSparsityTools::distribute_sparsity_pattern(dsp,\n\t\t\t\tlocal_dofs_per_process,\n\t\t\t\tmpi_communicator,\n\t\t\t\tlocally_relevant_dofs);\n\n\n\n\t\t\t\t\n\t\t\tsystem_matrix.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n\t\t\t\n\n\t\t\tif (timestep_number == 0) \n\t\t\t{\n\t\t\t\tsolution.reinit(dof_handler.n_dofs()); \n\t\t\t\tsolution = 800;\n\t\t\t}\n\n\t\t\tsystem_rhs.reinit(locally_owned_dofs, mpi_communicator);\n\t\t}\n\n\n\ttemplate<int dim>\n\t\tvoid HeatEquation<dim>::output_results() const\n\t\t{\n\t\t\tstd::string filename = \"solution-\" + Utilities::int_to_string(timestep_number, 4)\n\t\t\t                       + \".\" + Utilities::int_to_string(this_mpi_process, 3)\n\t\t\t                       + \".vtu\";\n\n\t\t\tstd::ofstream output(filename.c_str());\n\t\t\tDataOut<dim> data_out;\n\t\t\tdata_out.attach_dof_handler(dof_handler);\n\t\t\tdata_out.add_data_vector(solution, \"Temperature\");\n\t\t\tstd::vector<unsigned int> partition_int(triangulation.n_active_cells());\n\t\t\tGridTools::get_subdomain_association(triangulation, partition_int);\n\t\t\tconst Vector<double> partitioning(partition_int.begin(), partition_int.end());\n\t\t\tdata_out.add_data_vector(partitioning, \"Partitioning\");\n\t\t\tdata_out.build_patches();\n\t\t\tdata_out.write_vtu(output);\n\n\t\t\tif (this_mpi_process == 0)\n\t\t\t{\n\t\t\t\tstd::vector<std::string> filenames;\n\t\t\t\tfor (unsigned int i = 0; i < n_mpi_processes; ++i)\n\t\t\t\t\tfilenames.push_back(\"solution-\" + Utilities::int_to_string(timestep_number, 4)\n\t\t\t\t\t                     + \".\" + Utilities::int_to_string(i, 3)\n\t\t\t\t\t                     + \".vtu\");\n\t\t\t\t\n\t\t\t\tconst std::string pvtu_master_filename = (\"solution-\" +\n\t\t\t\t                        Utilities::int_to_string(timestep_number, 4) +\n\t\t\t\t                        \".pvtu\");\n\t\t\t\tstd::ofstream pvtu_master(pvtu_master_filename.c_str());\n\t\t\t\tdata_out.write_pvtu_record(pvtu_master, filenames);\n\t\t\t\tstatic std::vector<std::pair<double, std::string> > times_and_names;\n\t\t\t\ttimes_and_names.push_back(std::pair<double, std::string> (time, pvtu_master_filename));\n\t\t\t\tstd::ofstream pvd_output(\"solution.pvd\");\n\t\t\t\tDataOutBase::write_pvd_record(pvd_output, times_and_names);\n\t\t\t}\n\n\t\t\t\n\t\t}\n\n\n\ttemplate<int dim>\n\t\tvoid HeatEquation<dim>::assemble_system()\n\t\t{\n\t\t\tdouble temp_env_top = 20;\n\t\t\tdouble convection_top = 0;\n\t\t\tdouble temp_env_right = 20;\n\t\t\tdouble convection_right = 0;\n\n\t\t\tQGauss<dim> quadrature_formula(2);\n\t\t\tQGauss<dim - 1> face_quadrature_formula(3);\n\t\t\t\n\t\t\tQTrapez<3> quadrature;\n\n\t\t\tFEValues<dim> cell_fe_values(fe, quadrature_formula, update_values | update_gradients | update_JxW_values | update_quadrature_points);\n\t\t\tFEFaceValues<dim> face_fe_values(fe, face_quadrature_formula, update_values | update_quadrature_points | update_normal_vectors | update_JxW_values);\n\t\t\tFEValues<dim> fe_values(fe, quadrature, update_values);\n\n\t\t\tconst unsigned int dofs_per_cell = fe.dofs_per_cell;\n\n\t\t\tconst unsigned int cell_quadrature_points = quadrature_formula.size();\n\t\t\tconst unsigned int face_q_pts = face_quadrature_formula.size();\n\n\t\t\t// Auxiliary matrices\n\t\t\tFullMatrix<double> cell_h(dofs_per_cell, dofs_per_cell);\n\t\t\tFullMatrix<double> cell_hq(dofs_per_cell, dofs_per_cell);\n\t\t\tFullMatrix<double> cell_c(dofs_per_cell, dofs_per_cell);\n\t\t\tVector<double> cell_p(dofs_per_cell);\n\n\t\t\t// Resulting matrices\n\t\t\tFullMatrix<double> cell_a(dofs_per_cell, dofs_per_cell);\n\t\t\tVector<double> cell_rhs(dofs_per_cell);\n\n\t\t\ttypename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(), endc = dof_handler.end();\n\n\t\t\tconst double cond = 90;\n\t\t\tconst double cp = 490;\n\t\t\tconst double ro = 7820;\n\t\t\tdouble alpha = 0;\n\t\t\tdouble tenv = 0;\n\t\t\t\n\t\t\tfor (; cell != endc; ++cell) {\n\t\t\t\tif (cell->is_locally_owned())\n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\tcell_fe_values.reinit(cell);\n\t\t\t\t\tfe_values.reinit(cell);\n\n\t\t\t\t\tcell_h = 0;\n\t\t\t\t\tcell_c = 0;\n\t\t\t\t\tcell_p = 0;\n\t\t\t\t\tcell_hq = 0;\n\n\n\t\t\t\t\t// Reinit matrices by 0\n\t\t\t\t\tcell_a = 0;\n\t\t\t\t\tcell_rhs = 0;\n\n\t\t\t\t\tfor (unsigned int i = 0; i < dofs_per_cell; ++i) {\n\t\t\t\t\t\tfor (unsigned int j = 0; j < dofs_per_cell; ++j) {\n\t\t\t\t\t\t\tfor (unsigned int q_point = 0; q_point < cell_quadrature_points; ++q_point) {\n\n\t\t\t\t\t\t\t\tdouble dn_dx = cell_fe_values.shape_grad(i, q_point)[0];\n\t\t\t\t\t\t\t\tdouble dk_dx = cell_fe_values.shape_grad(j, q_point)[0];\n\n\t\t\t\t\t\t\t\tdouble dn_dy = cell_fe_values.shape_grad(i, q_point)[1];\n\t\t\t\t\t\t\t\tdouble dk_dy = cell_fe_values.shape_grad(j, q_point)[1];\n\n\t\t\t\t\t\t\t\tdouble n = cell_fe_values.shape_value(i, q_point);\n\t\t\t\t\t\t\t\tdouble k = cell_fe_values.shape_value(j, q_point);\n\n\t\t\t\t\t\t\t\tdouble jdet = cell_fe_values.JxW(q_point);\n\n\t\t\t\t\t\t\t\tcell_h(i, j) += cond * jdet * (dn_dx * dk_dx + dn_dy * dk_dy);\n\t\t\t\t\t\t\t\tcell_c(i, j) += cp * ro * n * k * jdet;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\n\t\t\t\t\t// Apply Neumann boundary condition\n\t\t\t\t\tfor(unsigned int face = 0 ; face < GeometryInfo<dim>::faces_per_cell ; ++face) {\n\t\t\t\t\t\tif (cell->face(face)->at_boundary() && (cell->face(face)->boundary_id() == 2 || cell->face(face)->boundary_id() == 3)) {\n\n\t\t\t\t\t\t\tif (cell->face(face)->boundary_id() == 2) {\n\t\t\t\t\t\t\t\talpha = convection_top;\n\t\t\t\t\t\t\t\ttenv = temp_env_top;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (cell->face(face)->boundary_id() == 3) {\n\t\t\t\t\t\t\t\talpha = convection_right;\n\t\t\t\t\t\t\t\ttenv = temp_env_right;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//Point<dim> debugpt = cell->face(face)->center();\n\t\t\t\t\t\t\tface_fe_values.reinit(cell, face);\n\n\t\t\t\t\t\t\tfor (unsigned int q = 0; q < face_q_pts; ++q) {\n\t\t\t\t\t\t\t\tdouble jdet = face_fe_values.JxW(q);\n\t\t\t\t\t\t\t\tfor (unsigned int ii = 0; ii < dofs_per_cell; ++ii) {\n\t\t\t\t\t\t\t\t\tdouble n = face_fe_values.shape_value(ii, q);\n\t\t\t\t\t\t\t\t\tcell_p(ii) += alpha * tenv * n * jdet;\n\n\t\t\t\t\t\t\t\t\tfor (unsigned int jj = 0; jj < dofs_per_cell; jj++) {\n\t\t\t\t\t\t\t\t\t\tdouble k = face_fe_values.shape_value(jj, q);\n\t\t\t\t\t\t\t\t\t\tcell_hq(ii, jj) += alpha * (n * k) * jdet;\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\n\t\t\t\t\t// Integration over time\n\t\t\t\t\t// values from previous time step\n\n\t\t\t\t\tstd::vector<double> local_values(dofs_per_cell);\n\t\t\t\t\tfe_values.get_function_values(solution, local_values);\n\n\t\t\t\t\t//\tstd::vector<double> local_values(dofs_per_cell);\n\t\t\t\t\t//\tcell_fe_values.get_function_values(solution, local_values);\n\t\t\t\t\t//\t\t\t\t\t\n\t\t\t\t\t//\tVector<double> local_values(dofs_per_cell);\n\t\t\t\t\t//\tcell->get_dof_values(solution, local_values);\n\n\t\t\t\t\t\t\t\t\t\tfor(unsigned int i = 0 ; i < dofs_per_cell ; ++i) {\n\t\t\t\t\t\tfor (unsigned int j = 0; j < dofs_per_cell; ++j) {\n\t\t\t\t\t\t\t// Galerkin\n\t\t\t\t\t\t\tdouble t0 = local_values[j];\n//\t\t\t\t\t\t\tcell_a(i, j) += 2.0 * cell_h(i,j) + (3.0/time_step) * cell_c(i,j) + cell_hq(i,j);\t\n//\t\t\t\t\t\t\tcell_rhs(i) += (-cell_h(i,j) + (3.0/time_step) * cell_c(i,j)) * t0;\n\n\t\t\t\t\t\t\t// Crank-Nicolson\n\t\t\t\t\t\t\t//cell_a(i, j) += cell_h(i, j) + 2.0*cell_c(i, j) / time_step + cell_hq(i, j);\t\n\t\t\t\t\t\t\t//cell_rhs(i) += (-cell_h(i, j) + 2.0*cell_c(i, j) / time_step) * t0;\t\t\t\t\n\n\t\t\t\t\t\t\t// Euler\n\t\t\t\t\t\t\tcell_a(i, j) += cell_h(i, j) + cell_hq(i, j) + cell_c(i, j) / time_step;\n\t\t\t\t\t\t\tcell_rhs(i) += (cell_c(i, j) / time_step) * t0;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Galerkin\n//\t\t\t\t\t\tcell_rhs(i) += 3.0 * cell_p(i);\n\n\t\t\t\t\t\t// Crank-Nicolson\n\t\t\t\t\t\t//cell_rhs(i) += 2.0 * cell_p(i);\n\n\t\t\t\t\t\t//Euler\n\t\t\t\t\t\tcell_rhs(i) += cell_p(i);\n\t\t\t\t\t}\n\n\t\t\t\t\t\n\t\t\t\t\t// Aggregation system of equation\n\t\t\t\t\t std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\t\t\t\t\tcell->get_dof_indices(local_dof_indices);\n\t\t\t\t\tconstraints.distribute_local_to_global(cell_a, cell_rhs, local_dof_indices, system_matrix, system_rhs);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsystem_matrix.compress(VectorOperation::add);\n\t\t\tsystem_rhs.compress(VectorOperation::add);\n\n\t\t}\n\n\ttemplate <int dim>\n\tvoid HeatEquation<dim>::make_dirichlet_boundary_conditions()\n\t{\n\t\tVectorTools::interpolate_boundary_values(dof_handler, 2, ConstantFunction<dim>(20), constraints);\n\t\tVectorTools::interpolate_boundary_values(dof_handler, 3, ConstantFunction<dim>(20), constraints);\n\t}\n\n\ttemplate<int dim>\n\t\tdouble HeatEquation<dim>::solve_time_step()\n\t\t{\n\t\t\tPETScWrappers::MPI::Vector distributed_solution(locally_owned_dofs, mpi_communicator);\n\t\t\tdistributed_solution = solution;\n\n\t\t\tSolverControl solver_control(dof_handler.n_dofs(), 1e-8*system_rhs.l2_norm());\n\t\t\tPETScWrappers::SolverCG cg(solver_control, mpi_communicator);\n\t\t\tPETScWrappers::PreconditionBlockJacobi preconditioner(system_matrix);\n\t\t\tcg.solve(system_matrix, distributed_solution, system_rhs, preconditioner);\n\t\t\tconstraints.distribute(distributed_solution);\n\t\t\tsolution = distributed_solution;\n\t\t\t\n\t\t\treturn solver_control.last_step();\n\t\t}\n\n\n\ttemplate<int dim>\n\t\tvoid HeatEquation<dim>::run()\n\t\t{\n\t\t\tfor (unsigned int time = 0; time < 10; ++time)\n\t\t\t{\n\t\t\t\tpcout << \"Time \" << time << ':' << std::endl;\n\t\t\t\tif (time == 0)\n\t\t\t\t{\n\t\t\t\t\tcreate_grid();\n\t\t\t\t}\n\n\t\t\t\tpcout << \"   Number of active cells:       \"\n\t\t\t\t      << triangulation.n_active_cells()\n\t\t\t\t      << std::endl;\n\t\t\t\tsetup_system();\n\t\t\t\tpcout << \"   Number of degrees of freedom: \"\n\t\t\t\t      << dof_handler.n_dofs()\n\t\t\t\t      << \" (by partition:\";\n\t\t\t\tfor (unsigned int p = 0; p < n_mpi_processes; ++p)\n\t\t\t\t\tpcout << (p == 0 ? ' ' : '+')\n\t\t\t\t\t      << (DoFTools::\n\t\t\t\t\t          count_dofs_with_subdomain_association(dof_handler, p));\n\n\t\t\t\tpcout << \")\" << std::endl;\n\t\t\t\tpcout << \"   Assembling.\" << std::endl;\n\t\t\t\tassemble_system();\n\t\t\t\tpcout << \"   Solving.\" << std::endl;\n\t\t\t\tconst unsigned int n_iterations = solve_time_step();\n\t\t\t\tpcout << \"   Solver converged in \" << n_iterations\n\t\t\t\t      << \" iterations.\" << std::endl;\n\t\t\t\toutput_results();\n\t\t\t\tincrement_time();\n\t\t\t}\n\t\t}\n}\n\t\n\nint main(int argc, char **argv)\n{\n\ttry\n\t{\n\t\tusing namespace dealii;\n\t\tusing namespace DistributedHE;\n\n\t\tUtilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);\n\t\tHeatEquation<3> heat_equation_solver;\n\t\theat_equation_solver.run();\n\n\t}\n\tcatch (std::exception &exc)\n\t{\n\t\tstd::cerr << std::endl << std::endl\n\t\t          << \"----------------------------------------------------\"\n\t\t          << std::endl;\n\t\tstd::cerr << \"Exception on processing: \" << std::endl << exc.what()\n\t\t          << std::endl << \"Aborting!\" << std::endl\n\t\t          << \"----------------------------------------------------\"\n\t\t          << std::endl;\n\n\t\treturn 1;\n\t}\n\tcatch (...)\n\t{\n\t\tstd::cerr << std::endl << std::endl\n\t\t          << \"----------------------------------------------------\"\n\t\t          << std::endl;\n\t\tstd::cerr << \"Unknown exception!\" << std::endl << \"Aborting!\"\n\t\t          << std::endl\n\t\t          << \"----------------------------------------------------\"\n\t\t          << std::endl;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}", "meta": {"hexsha": "f07c68ff69aba070a9f001eee878a4459dc3c6c9", "size": 15331, "ext": "cc", "lang": "C++", "max_stars_repo_path": "dhe.cc", "max_stars_repo_name": "kbzowski/MinimalDistributedHeatEq", "max_stars_repo_head_hexsha": "a2ec4491c3c1a7428e62df8d69243aa343c2e551", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dhe.cc", "max_issues_repo_name": "kbzowski/MinimalDistributedHeatEq", "max_issues_repo_head_hexsha": "a2ec4491c3c1a7428e62df8d69243aa343c2e551", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dhe.cc", "max_forks_repo_name": "kbzowski/MinimalDistributedHeatEq", "max_forks_repo_head_hexsha": "a2ec4491c3c1a7428e62df8d69243aa343c2e551", "max_forks_repo_licenses": ["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.2240325866, "max_line_length": 151, "alphanum_fraction": 0.6474463505, "num_tokens": 4164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5362688507708226}}
{"text": "#pragma once\r\n#ifndef OPTIMIZE_HPP\r\n#define OPTIMIZE_HPP\r\n\r\n// c++ libraries\r\n#include <iosfwd>\r\n// eigen libraries\r\n#include <Eigen/Dense>\r\n//serialization\r\n#include \"src/mem/serialize.hpp\"\r\n\r\nnamespace Opt{\r\n\t\r\n#ifndef OPT_PRINT_FUNC\r\n#define OPT_PRINT_FUNC 0\r\n#endif\r\n\r\n#ifndef OPT_PRINT_DATA\r\n#define OPT_PRINT_DATA 0\r\n#endif\r\n\r\n//***************************************************\r\n// optimization method\r\n//***************************************************\r\n\r\nclass Algo{\r\npublic:\r\n\tenum Type{\r\n\t\tUNKNOWN=0,\r\n\t\tSGD=1,\r\n\t\tSDM=2,\r\n\t\tNAG=3,\r\n\t\tADAGRAD=4,\r\n\t\tADADELTA=5,\r\n\t\tRMSPROP=6,\r\n\t\tADAM=7,\r\n\t\tNADAM=8,\r\n\t\tAMSGRAD=9,\r\n\t\tBFGS=10,\r\n\t\tRPROP=11,\r\n\t\tCG=12,\r\n\t};\r\n\t//constructor\r\n\tAlgo():t_(Type::UNKNOWN){}\r\n\tAlgo(Type t):t_(t){}\r\n\t//operators\r\n\toperator Type()const{return t_;}\r\n\t//member functions\r\n\tstatic Algo read(const char* str);\r\n\tstatic const char* name(const Algo& algo);\r\nprivate:\r\n\tType t_;\r\n\t//prevent automatic conversion for other built-in types\r\n\t//template<typename T> operator T() const;\r\n};\r\nstd::ostream& operator<<(std::ostream& out, const Algo& algo);\r\n\r\n//***************************************************\r\n// stopping criterion\r\n//***************************************************\r\n\r\nclass Stop{\r\npublic:\r\n\tenum Type{\r\n\t\tUNKNOWN=0,\r\n\t\tFABS=1,\r\n\t\tFREL=2,\r\n\t\tXABS=3,\r\n\t\tXREL=4\r\n\t};\r\n\t//constructor\r\n\tStop():t_(Type::UNKNOWN){}\r\n\tStop(Type t):t_(t){}\r\n\t//operators\r\n\toperator Type()const{return t_;}\r\n\t//member functions\r\n\tstatic Stop read(const char* str);\r\n\tstatic const char* name(const Stop& stop);\r\nprivate:\r\n\tType t_;\r\n\t//prevent automatic conversion for other built-in types\r\n\t//template<typename T> operator T() const;\r\n};\r\nstd::ostream& operator<<(std::ostream& out, const Stop& stop);\r\n\r\n//***************************************************\r\n// decay method\r\n//***************************************************\r\n\r\nclass Decay{\r\npublic:\r\n\tenum Type{\r\n\t\tUNKNOWN=0,\r\n\t\tCONST=1,\r\n\t\tEXP=2,\r\n\t\tSQRT=3,\r\n\t\tINV=4,\r\n\t\tPOW=5,\r\n\t\tSTEP=6\r\n\t};\r\n\t//constructor\r\n\tDecay():t_(Type::UNKNOWN){}\r\n\tDecay(Type t):t_(t){}\r\n\t//operators\r\n\toperator Type()const{return t_;}\r\n\t//member functions\r\n\tstatic Decay read(const char* str);\r\n\tstatic const char* name(const Decay& decay);\r\nprivate:\r\n\tType t_;\r\n\t//prevent automatic conversion for other built-in types\r\n\t//template<typename T> operator T() const;\r\n};\r\nstd::ostream& operator<<(std::ostream& out, const Decay& decay);\r\n\r\n//***************************************************\r\n// loss function\r\n//***************************************************\r\n\r\nstruct Loss{\r\npublic:\r\n\tenum Type{\r\n\t\tUNKNOWN=0,\r\n\t\tMSE=1,\r\n\t\tMAE=2,\r\n\t\tHUBER=3\r\n\t};\r\n\t//constructor\r\n\tLoss():t_(Type::UNKNOWN){}\r\n\tLoss(Type t):t_(t){}\r\n\t//operators\r\n\toperator Type()const{return t_;}\r\n\t//member functions\r\n\tstatic Loss read(const char* str);\r\n\tstatic const char* name(const Loss& loss);\r\n\t//error\r\n\tstatic double error(Loss loss, const Eigen::VectorXd& value, const Eigen::VectorXd& target);\r\n\tstatic double error(Loss loss, const Eigen::VectorXd& value, const Eigen::VectorXd& target, Eigen::VectorXd& grad);\r\nprivate:\r\n\tType t_;\r\n\t//prevent automatic conversion for other built-in types\r\n\t//template<typename T> operator T() const;\r\n};\r\nstd::ostream& operator<<(std::ostream& out, const Loss& loss);\r\n\r\n//***************************************************\r\n// Data\r\n//***************************************************\r\n\r\nclass Data{\r\nprivate:\r\n\t//count\r\n\t\tint nPrint_;//print data every n steps\r\n\t\tint nWrite_;//write data every n steps\r\n\t\tint step_;//current step\r\n\t\tint count_;//current count\r\n\t//stopping\r\n\t\tint max_;//max steps\r\n\t\tdouble tol_;//stop tolerance\r\n\t//status\r\n\t\tdouble val_,valOld_;//current, old value\r\n\t\tdouble dv_,dp_;//change in value, p\r\n\t//algorithm\r\n\t\tAlgo algo_;//optimization algorithm\r\n\t\tStop stop_;//the type of value determining the end condition\r\n\t//parameters\r\n\t\tint dim_;//dimension of problem\r\n\t\tEigen::VectorXd p_,pOld_;//current, old parameters\r\n\t\tEigen::VectorXd g_,gOld_;//current, old gradients\r\npublic:\r\n\t//==== constructors/destructors ====\r\n\tData(){defaults();}\r\n\tData(int dim){defaults();init(dim);}\r\n\t~Data(){}\r\n\t\r\n\t//==== operators ====\r\n\tfriend std::ostream& operator<<(std::ostream& out, const Data& data);\r\n\t\r\n\t//==== access ====\r\n\t//status\r\n\t\tdouble& val(){return val_;}\r\n\t\tconst double& val()const{return val_;}\r\n\t\tdouble& valOld(){return valOld_;}\r\n\t\tconst double& valOld()const{return valOld_;}\r\n\t\tdouble& dv(){return dv_;}\r\n\t\tconst double& dv()const{return dv_;}\r\n\t\tdouble& dp(){return dp_;}\r\n\t\tconst double& dp()const{return dp_;}\r\n\t//count\r\n\t\tint& nPrint(){return nPrint_;}\r\n\t\tconst int& nPrint()const{return nPrint_;}\r\n\t\tint& nWrite(){return nWrite_;}\r\n\t\tconst int& nWrite()const{return nWrite_;}\r\n\t\tint& step(){return step_;}\r\n\t\tconst int& step()const{return step_;}\r\n\t\tint& count(){return count_;}\r\n\t\tconst int& count()const{return count_;}\r\n\t//stopping\r\n\t\tdouble& tol(){return tol_;}\r\n\t\tconst double& tol()const{return tol_;}\r\n\t\tint& max(){return max_;}\r\n\t\tconst int& max()const{return max_;}\r\n\t//parameters\r\n\t\tint& dim(){return dim_;}\r\n\t\tconst int& dim()const{return dim_;}\r\n\t\tEigen::VectorXd& p(){return p_;}\r\n\t\tconst Eigen::VectorXd& p()const{return p_;}\r\n\t\tEigen::VectorXd& pOld(){return pOld_;}\r\n\t\tconst Eigen::VectorXd& pOld()const{return pOld_;}\r\n\t\tEigen::VectorXd& g(){return g_;}\r\n\t\tconst Eigen::VectorXd& g()const{return g_;}\r\n\t\tEigen::VectorXd& gOld(){return gOld_;}\r\n\t\tconst Eigen::VectorXd& gOld()const{return gOld_;}\r\n\t//algorithm\r\n\t\tAlgo& algo(){return algo_;}\r\n\t\tconst Algo& algo()const{return algo_;}\r\n\t\tStop& stop(){return stop_;}\r\n\t\tconst Stop& stop()const{return stop_;}\r\n\t\r\n\t//==== member functions ====\r\n\tvoid defaults();\r\n\tvoid clear(){defaults();}\r\n\tvoid init(int dim);\r\n};\r\n\r\n//***************************************************\r\n// Model\r\n//***************************************************\r\n\r\nclass Model{\r\nprotected:\r\n\tint dim_;//dimension of the problem\r\n\tint period_;//period of decay\r\n\tAlgo algo_;//optimization algorithm\r\n\tDecay decay_;//decay schedule\r\n\tdouble alpha_;//step decay constant\r\n\tdouble gamma_;//gradient step size\r\n\tdouble lambda_;//regularization parameter\r\n\tdouble power_;//step decay power\r\n\tdouble mix_;//mixing parameter\r\npublic:\r\n\t//==== constructors/destructors ====\r\n\tModel(){defaults();}\r\n\tvirtual ~Model(){}\r\n\t\r\n\t//==== operators ====\r\n\tfriend std::ostream& operator<<(std::ostream& out, const Model& model);\r\n\t\r\n\t//==== access ====\r\n\tint& dim(){return dim_;}\r\n\tconst int& dim()const{return dim_;}\r\n\tint& period(){return period_;}\r\n\tconst int& period()const{return period_;}\r\n\tAlgo& algo(){return algo_;}\r\n\tconst Algo& algo()const{return algo_;}\r\n\tDecay& decay(){return decay_;}\r\n\tconst Decay& decay()const{return decay_;}\r\n\tdouble& alpha(){return alpha_;}\r\n\tconst double& alpha()const{return alpha_;}\r\n\tdouble& gamma(){return gamma_;}\r\n\tconst double& gamma()const{return gamma_;}\r\n\tdouble& lambda(){return lambda_;}\r\n\tconst double& lambda()const{return lambda_;}\r\n\tdouble& power(){return power_;}\r\n\tconst double& power()const{return power_;}\r\n\tdouble& mix(){return mix_;}\r\n\tconst double& mix()const{return mix_;}\r\n\t\r\n\t//==== member functions ====\r\n\tvoid defaults();\r\n\tvoid clear();\r\n\tvoid update_step(int step);\r\n\t\r\n\t//==== virtual functions ====\r\n\tvirtual void step(Data& d)=0;\r\n\tvirtual void init(int dim);\r\n\t\r\n\t//==== static functions ====\r\n\tstatic std::ostream& print(std::ostream& out, const Model* model);\r\n};\r\n\r\n//steepest-desccent\r\nclass SGD final: public Model{\r\npublic:\r\n\t//constructors/destructors\r\n\tSGD(){defaults();}\r\n\tSGD(int dim){init(dim);}\r\n\t~SGD(){}\r\n\t//member functions\r\n\tvoid step(Data& d);\r\n\tvoid defaults();\r\n\tvoid init(int dim);\r\n\t//operators\r\n\tfriend std::ostream& operator<<(std::ostream& out, const SGD& sgd);\r\n};\r\n\r\n//steepest-descent + momentum\r\nclass SDM final: public Model{\r\nprivate:\r\n\tdouble eta_;//mixing term\r\n\tEigen::VectorXd dx_;//change in parameters\r\npublic:\r\n\t//constructors/destructors\r\n\tSDM(){defaults();}\r\n\tSDM(int dim){init(dim);}\r\n\t~SDM(){}\r\n\t//access\r\n\tdouble& eta(){return eta_;}\r\n\tconst double& eta()const{return eta_;}\r\n\tEigen::VectorXd& dx(){return dx_;}\r\n\tconst Eigen::VectorXd& dx()const{return dx_;}\r\n\t//member functions\r\n\tvoid step(Data& d);\r\n\tvoid defaults();\r\n\tvoid init(int dim);\r\n\t//operators\r\n\tfriend std::ostream& operator<<(std::ostream& out, const SDM& sdm);\r\n};\r\n\r\n//nesterov accelerated gradient\r\nclass NAG final: public Model{\r\nprivate:\r\n\tdouble eta_;//mixing term\r\n\tEigen::VectorXd dx_;\r\npublic:\r\n\t//constructors/destructors\r\n\tNAG(){defaults();}\r\n\tNAG(int dim){init(dim);}\r\n\t~NAG(){}\r\n\t//access\r\n\tdouble& eta(){return eta_;}\r\n\tconst double& eta()const{return eta_;}\r\n\tEigen::VectorXd& dx(){return dx_;}\r\n\tconst Eigen::VectorXd& dx()const{return dx_;}\r\n\t//member functions\r\n\tvoid step(Data& d);\r\n\tvoid defaults();\r\n\tvoid init(int dim);\r\n\t//operators\r\n\tfriend std::ostream& operator<<(std::ostream& out, const NAG& nag);\r\n};\r\n\r\n//adagrad\r\nclass ADAGRAD final: public Model{\r\nprivate:\r\n\tstatic const double eps_;//small term to prevent divergence\r\n\tEigen::VectorXd mgrad2_;//avg of square of gradient\r\npublic:\r\n\t//constructors/destructors\r\n\tADAGRAD(){defaults();}\r\n\tADAGRAD(int dim){init(dim);}\r\n\t~ADAGRAD(){}\r\n\t//access\r\n\tEigen::VectorXd& mgrad2(){return mgrad2_;}\r\n\tconst Eigen::VectorXd& mgrad2()const{return mgrad2_;}\r\n\t//member functions\r\n\tvoid step(Data& d);\r\n\tvoid defaults();\r\n\tvoid init(int dim);\r\n\t//operators\r\n\tfriend std::ostream& operator<<(std::ostream& out, const ADAGRAD& adagrad);\r\n};\r\n\r\n//adadelta\r\nclass ADADELTA final: public Model{\r\nprivate:\r\n\tstatic const double eps_;//small term to prevent divergence\r\n\tdouble eta_;//mixing fraction\r\n\tEigen::VectorXd mgrad2_;//avg of square of gradient\r\n\tEigen::VectorXd mdx2_;//avg of square of dx\r\n\tEigen::VectorXd dx_;//change in x\r\npublic:\r\n\t//constructors/destructors\r\n\tADADELTA(){defaults();}\r\n\tADADELTA(int dim){init(dim);}\r\n\t~ADADELTA(){}\r\n\t//access\r\n\tdouble& eta(){return eta_;}\r\n\tconst double& eta()const{return eta_;}\r\n\tEigen::VectorXd& mgrad2(){return mgrad2_;}\r\n\tconst Eigen::VectorXd& mgrad2()const{return mgrad2_;}\r\n\tEigen::VectorXd& mdx2(){return mdx2_;}\r\n\tconst Eigen::VectorXd& mdx2()const{return mdx2_;}\r\n\tEigen::VectorXd& dx(){return dx_;}\r\n\tconst Eigen::VectorXd& dx()const{return dx_;}\r\n\t//member functions\r\n\tvoid step(Data& d);\r\n\tvoid defaults();\r\n\tvoid init(int dim);\r\n\t//operators\r\n\tfriend std::ostream& operator<<(std::ostream& out, const ADADELTA& adadelta);\r\n};\r\n\r\n//rmsprop\r\nclass RMSPROP final: public Model{\r\nprivate:\r\n\tstatic const double eps_;//small term to prevent divergence\r\n\tEigen::VectorXd mgrad2_;//avg of square of gradient\r\npublic:\r\n\t//constructors/destructors\r\n\tRMSPROP(){defaults();}\r\n\tRMSPROP(int dim){init(dim);}\r\n\t~RMSPROP(){}\r\n\t//access\r\n\tEigen::VectorXd& mgrad2(){return mgrad2_;}\r\n\tconst Eigen::VectorXd& mgrad2()const{return mgrad2_;}\r\n\t//member functions\r\n\tvoid step(Data& d);\r\n\tvoid defaults();\r\n\tvoid init(int dim);\r\n\t//operators\r\n\tfriend std::ostream& operator<<(std::ostream& out, const RMSPROP& rmsprop);\r\n};\r\n\r\n//adam\r\nclass ADAM final: public Model{\r\nprivate:\r\n\tstatic const double eps_;//small term to prevent divergence\r\n\tstatic const double beta1_;\r\n\tstatic const double beta2_;\r\n\tdouble beta1i_;//power w.r.t i\r\n\tdouble beta2i_;//power w.r.t i\r\n\tEigen::VectorXd mgrad_;//avg of gradient\r\n\tEigen::VectorXd mgrad2_;//avg of square of gradient\r\npublic:\r\n\t//constructors/destructors\r\n\tADAM(){defaults();}\r\n\tADAM(int dim){init(dim);}\r\n\t~ADAM(){}\r\n\t//access\r\n\tdouble& beta1i(){return beta1i_;}\r\n\tconst double& beta1i()const{return beta1i_;}\r\n\tdouble& beta2i(){return beta2i_;}\r\n\tconst double& beta2i()const{return beta2i_;}\r\n\tEigen::VectorXd& mgrad(){return mgrad_;}\r\n\tconst Eigen::VectorXd& mgrad()const{return mgrad_;}\r\n\tEigen::VectorXd& mgrad2(){return mgrad2_;}\r\n\tconst Eigen::VectorXd& mgrad2()const{return mgrad2_;}\r\n\t//member functions\r\n\tvoid step(Data& d);\r\n\tvoid defaults();\r\n\tvoid init(int dim);\r\n\t//operators\r\n\tfriend std::ostream& operator<<(std::ostream& out, const ADAM& adam);\r\n};\r\n\r\n//nadam\r\nclass NADAM final: public Model{\r\nprivate:\r\n\tstatic const double eps_;//small term to prevent divergence\r\n\tstatic const double beta1_;\r\n\tstatic const double beta2_;\r\n\tdouble beta1i_;//power w.r.t i\r\n\tdouble beta2i_;//power w.r.t i\r\n\tEigen::VectorXd mgrad_;//avg of gradient\r\n\tEigen::VectorXd mgrad2_;//avg of square of gradient\r\npublic:\r\n\t//constructors/destructors\r\n\tNADAM(){defaults();}\r\n\tNADAM(int dim){init(dim);}\r\n\t~NADAM(){}\r\n\t//access\r\n\tdouble& beta1i(){return beta1i_;}\r\n\tconst double& beta1i()const{return beta1i_;}\r\n\tdouble& beta2i(){return beta2i_;}\r\n\tconst double& beta2i()const{return beta2i_;}\r\n\tEigen::VectorXd& mgrad(){return mgrad_;}\r\n\tconst Eigen::VectorXd& mgrad()const{return mgrad_;}\r\n\tEigen::VectorXd& mgrad2(){return mgrad2_;}\r\n\tconst Eigen::VectorXd& mgrad2()const{return mgrad2_;}\r\n\t//member functions\r\n\tvoid step(Data& d);\r\n\tvoid defaults();\r\n\tvoid init(int dim);\r\n\t//operators\r\n\tfriend std::ostream& operator<<(std::ostream& out, const NADAM& nadam);\r\n};\r\n\r\n//amsgrad\r\nclass AMSGRAD final: public Model{\r\nprivate:\r\n\tstatic const double eps_;//small term to prevent divergence\r\n\tstatic const double beta1_;\r\n\tstatic const double beta2_;\r\n\tdouble beta1i_;//power w.r.t i\r\n\tdouble beta2i_;//power w.r.t i\r\n\tEigen::VectorXd mgrad_;//avg of gradient\r\n\tEigen::VectorXd mgrad2_;//avg of square of gradient\r\n\tEigen::VectorXd mgrad2m_;\r\npublic:\r\n\t//constructors/destructors\r\n\tAMSGRAD(){defaults();}\r\n\tAMSGRAD(int dim){init(dim);}\r\n\t~AMSGRAD(){}\r\n\t//access\r\n\tdouble& beta1i(){return beta1i_;}\r\n\tconst double& beta1i()const{return beta1i_;}\r\n\tdouble& beta2i(){return beta2i_;}\r\n\tconst double& beta2i()const{return beta2i_;}\r\n\tEigen::VectorXd& mgrad(){return mgrad_;}\r\n\tconst Eigen::VectorXd& mgrad()const{return mgrad_;}\r\n\tEigen::VectorXd& mgrad2(){return mgrad2_;}\r\n\tconst Eigen::VectorXd& mgrad2()const{return mgrad2_;}\r\n\tEigen::VectorXd& mgrad2m(){return mgrad2m_;}\r\n\tconst Eigen::VectorXd& mgrad2m()const{return mgrad2m_;}\r\n\t//member functions\r\n\tvoid step(Data& d);\r\n\tvoid defaults();\r\n\tvoid init(int dim);\r\n\t//operators\r\n\tfriend std::ostream& operator<<(std::ostream& out, const AMSGRAD& amsgrad);\r\n};\r\n\r\n//bfgs\r\nclass BFGS final: public Model{\r\nprivate:\r\n\tEigen::MatrixXd B_,BOld_;\r\n\tEigen::VectorXd s_,y_;\r\npublic:\r\n\t//constructors/destructors\r\n\tBFGS(){defaults();}\r\n\tBFGS(int dim){init(dim);}\r\n\t~BFGS(){}\r\n\t//member functions\r\n\tvoid step(Data& d);\r\n\tvoid defaults();\r\n\tvoid init(int dim);\r\n\t//operators\r\n\tfriend std::ostream& operator<<(std::ostream& out, const BFGS& bfgs);\r\n};\r\n\r\n//rprop\r\nclass RPROP final: public Model{\r\nprivate:\r\n\tstatic const double etaP;\r\n\tstatic const double etaM;\r\n\tstatic const double deltaMax;\r\n\tstatic const double deltaMin;\r\n\tEigen::VectorXd delta_;\r\n\tEigen::VectorXd dx_;\r\npublic:\r\n\t//constructors/destructors\r\n\tRPROP(){defaults();}\r\n\tRPROP(int dim){init(dim);}\r\n\t~RPROP(){}\r\n\t//access\r\n\tEigen::VectorXd& delta(){return delta_;}\r\n\tconst Eigen::VectorXd& delta()const{return delta_;}\r\n\tEigen::VectorXd& dx(){return dx_;}\r\n\tconst Eigen::VectorXd& dx()const{return dx_;}\r\n\t//member functions\r\n\tvoid step(Data& d);\r\n\tvoid defaults();\r\n\tvoid init(int dim);\r\n\t//operators\r\n\tfriend std::ostream& operator<<(std::ostream& out, const RPROP& rprop);\r\n};\r\n/*\r\n\tChristian Igel and Michael H\u00fcsken. \r\n\t\tImproving the Rprop Learning Algorithm. \r\n\t\tSecond International Symposium on Neural Computation \r\n\t\t(NC 2000), pp. 115-121, ICSC Academic Press, 2000\r\n\tChristian Igel and Michael H\u00fcsken. \r\n\t\tEmpirical Evaluation of the Improved Rprop Learning Algorithm. \r\n\t\tNeurocomputing 50:105-123, 2003\r\n*/\r\n\r\n//cg\r\nclass CG final: public Model{\r\nprivate:\r\n\tstatic const double eps_;//small term to prevent divergence\r\n\tEigen::VectorXd cgd_;//cg direction\r\npublic:\r\n\t//constructors/destructors\r\n\tCG(){defaults();}\r\n\tCG(int dim){init(dim);}\r\n\t~CG(){}\r\n\t//access\r\n\tEigen::VectorXd& cgd(){return cgd_;}\r\n\tconst Eigen::VectorXd& cgd()const{return cgd_;}\r\n\t//member functions\r\n\tvoid step(Data& d);\r\n\tvoid defaults();\r\n\tvoid init(int dim);\r\n\t//operators\r\n\tfriend std::ostream& operator<<(std::ostream& out, const CG& cg);\r\n};\r\n\r\n//read from file\r\n\r\nModel& read(Model& model, const char* file);\r\nData& read(Data& data, const char* file);\r\nSGD& read(SGD& sdg, const char* file);\r\nSDM& read(SDM& sdm, const char* file);\r\nNAG& read(NAG& nag, const char* file);\r\nADAGRAD& read(ADAGRAD& adagrad, const char* file);\r\nADADELTA& read(ADADELTA& adadelta, const char* file);\r\nRMSPROP& read(RMSPROP& rmsprop, const char* file);\r\nADAM& read(ADAM& adam, const char* file);\r\nNADAM& read(NADAM& nadam, const char* file);\r\nBFGS& read(BFGS& bfgs, const char* file);\r\nRPROP& read(RPROP& rprop, const char* file);\r\n\r\n//read from file pointer\r\n\r\nModel& read(Model& model, FILE* reader);\r\nData& read(Data& data, FILE* reader);\r\nSGD& read(SGD& sdg, FILE* reader);\r\nSDM& read(SDM& sdm, FILE* reader);\r\nNAG& read(NAG& nag, FILE* reader);\r\nADAGRAD& read(ADAGRAD& adagrad, FILE* reader);\r\nADADELTA& read(ADADELTA& adadelta, FILE* reader);\r\nRMSPROP& read(RMSPROP& rmsprop, FILE* reader);\r\nADAM& read(ADAM& adam, FILE* reader);\r\nNADAM& read(NADAM& nadam, FILE* reader);\r\nBFGS& read(BFGS& bfgs, FILE* reader);\r\nRPROP& read(RPROP& rprop, FILE* reader);\r\n\r\n//opterators - comparison\r\n\r\nbool operator==(const SGD& obj1, const SGD& obj2);\r\nbool operator==(const SDM& obj1, const SDM& obj2);\r\nbool operator==(const NAG& obj1, const NAG& obj2);\r\nbool operator==(const ADAGRAD& obj1, const ADAGRAD& obj2);\r\nbool operator==(const ADADELTA& obj1, const ADADELTA& obj2);\r\nbool operator==(const RMSPROP& obj1, const RMSPROP& obj2);\r\nbool operator==(const ADAM& obj1, const ADAM& obj2);\r\nbool operator==(const NADAM& obj1, const NADAM& obj2);\r\nbool operator==(const BFGS& obj1, const BFGS& obj2);\r\nbool operator==(const RPROP& obj1, const RPROP& obj2);\r\n\r\n}\r\n\r\nnamespace serialize{\r\n\r\n\t//**********************************************\r\n\t// byte measures\r\n\t//**********************************************\r\n\t\r\n\ttemplate <> int nbytes(const Opt::Data& obj);\r\n\ttemplate <> int nbytes(const Opt::Model& obj);\r\n\ttemplate <> int nbytes(const Opt::SGD& obj);\r\n\ttemplate <> int nbytes(const Opt::SDM& obj);\r\n\ttemplate <> int nbytes(const Opt::NAG& obj);\r\n\ttemplate <> int nbytes(const Opt::ADAGRAD& obj);\r\n\ttemplate <> int nbytes(const Opt::ADADELTA& obj);\r\n\ttemplate <> int nbytes(const Opt::RMSPROP& obj);\r\n\ttemplate <> int nbytes(const Opt::ADAM& obj);\r\n\ttemplate <> int nbytes(const Opt::NADAM& obj);\r\n\ttemplate <> int nbytes(const Opt::AMSGRAD& obj);\r\n\ttemplate <> int nbytes(const Opt::BFGS& obj);\r\n\ttemplate <> int nbytes(const Opt::RPROP& obj);\r\n\ttemplate <> int nbytes(const Opt::CG& obj);\r\n\t\r\n\t//**********************************************\r\n\t// packing\r\n\t//**********************************************\r\n\t\r\n\ttemplate <> int pack(const Opt::Data& obj, char* arr);\r\n\ttemplate <> int pack(const Opt::Model& obj, char* arr);\r\n\ttemplate <> int pack(const Opt::SGD& obj, char* arr);\r\n\ttemplate <> int pack(const Opt::SDM& obj, char* arr);\r\n\ttemplate <> int pack(const Opt::NAG& obj, char* arr);\r\n\ttemplate <> int pack(const Opt::ADAGRAD& obj, char* arr);\r\n\ttemplate <> int pack(const Opt::ADADELTA& obj, char* arr);\r\n\ttemplate <> int pack(const Opt::RMSPROP& obj, char* arr);\r\n\ttemplate <> int pack(const Opt::ADAM& obj, char* arr);\r\n\ttemplate <> int pack(const Opt::NADAM& obj, char* arr);\r\n\ttemplate <> int pack(const Opt::AMSGRAD& obj, char* arr);\r\n\ttemplate <> int pack(const Opt::BFGS& obj, char* arr);\r\n\ttemplate <> int pack(const Opt::RPROP& obj, char* arr);\r\n\ttemplate <> int pack(const Opt::CG& obj, char* arr);\r\n\t\r\n\t//**********************************************\r\n\t// unpacking\r\n\t//**********************************************\r\n\t\r\n\ttemplate <> int unpack(Opt::Data& obj, const char* arr);\r\n\ttemplate <> int unpack(Opt::Model& obj, const char* arr);\r\n\ttemplate <> int unpack(Opt::SGD& obj, const char* arr);\r\n\ttemplate <> int unpack(Opt::SDM& obj, const char* arr);\r\n\ttemplate <> int unpack(Opt::NAG& obj, const char* arr);\r\n\ttemplate <> int unpack(Opt::ADAGRAD& obj, const char* arr);\r\n\ttemplate <> int unpack(Opt::ADADELTA& obj, const char* arr);\r\n\ttemplate <> int unpack(Opt::RMSPROP& obj, const char* arr);\r\n\ttemplate <> int unpack(Opt::ADAM& obj, const char* arr);\r\n\ttemplate <> int unpack(Opt::NADAM& obj, const char* arr);\r\n\ttemplate <> int unpack(Opt::AMSGRAD& obj, const char* arr);\r\n\ttemplate <> int unpack(Opt::BFGS& obj, const char* arr);\r\n\ttemplate <> int unpack(Opt::RPROP& obj, const char* arr);\r\n\ttemplate <> int unpack(Opt::CG& obj, const char* arr);\r\n\t\r\n}\r\n\r\n#endif", "meta": {"hexsha": "4f1b50601b4d5e99f862676381b56cc2bed3b9ff", "size": 20431, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/opt/optimize.hpp", "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/opt/optimize.hpp", "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/opt/optimize.hpp", "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": 29.3971223022, "max_line_length": 117, "alphanum_fraction": 0.64504919, "num_tokens": 5523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5361713054636075}}
{"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_VECTOR2D_HPP\n#define RW_MATH_VECTOR2D_HPP\n\n/**\n * @file Vector2D.hpp\n */\n\n#if !defined(SWIG)\n#include <rw/common/Serializable.hpp>\n\n#include <Eigen/Core>\n#endif\n\nnamespace rw { namespace math {\n    /** @addtogroup math */\n    /*@{*/\n\n    /**\n     * @brief A 2D vector @f$ \\mathbf{v}\\in \\mathbb{R}^2 @f$\n     *\n     * @f$ \\robabx{i}{j}{\\mathbf{v}} = \\left[\n     *  \\begin{array}{c}\n     *  v_x \\\\\n     *  v_y\n     *  \\end{array}\n     *  \\right]\n     *  @f$\n     *\n     *  In addition, Vector2D supports the cross product operator:\n     *  v3 = cross(v1, v2)\n     *\n     *  Usage example:\n     *  @code\n     *  using namespace rw::math;\n     *\n     *  Vector2D<> v1(1.0, 2.0);\n     *  Vector2D<> v2(6.0, 7.0);\n     *  Vector2D<> v3 = cross( v1, v2 );\n     *  Vector2D<> v4 = v2 - v1;\n     *  @endcode\n     */\n    template< class T = double > class Vector2D\n    {\n      public:\n        //! Eigen based Vector2D\n        typedef Eigen::Matrix< T, 2, 1 > EigenVector2D;\n\n        //! Value type.\n        typedef T value_type;\n\n        /**\n         * @brief Creates a 2D vector initialized with 0's\n         */\n        Vector2D ()\n        {\n            _vec[0] = 0;\n            _vec[1] = 0;\n        }\n\n        /**\n         * @brief Creates a 2D vector\n         *\n         * @param x [in] @f$ x @f$\n         *\n         * @param y [in] @f$ y @f$\n         */\n        Vector2D (T x, T y)\n        {\n            _vec[0] = x;\n            _vec[1] = y;\n        }\n\n        /**\n         * @brief Creates a 2D vector from Eigen Vector\n         * @param r [in] an Eigen Vector\n         */\n        template< class R > Vector2D (const Eigen::MatrixBase< R >& r)\n        {\n            EigenVector2D v (r);\n            _vec[0] = v (0);\n            _vec[1] = v (1);\n        }\n\n        /**\n         * @brief Copy Constructor\n         */\n        Vector2D (const Vector2D< T >& copy)\n        {\n            _vec[0] = copy[0];\n            _vec[1] = copy[1];\n        }\n\n        /**\n           @brief Returns Eigen vector equivalent to *this.\n         */\n        EigenVector2D e () const\n        {\n            EigenVector2D v;\n            v (0) = _vec[0];\n            v (1) = _vec[1];\n            return v;\n        }\n\n        /**\n           @brief The dimension of the vector (i.e. 2).\n\n           This method is provided to help support generic algorithms using\n           size() and operator[].\n        */\n        size_t size () const { return 2; }\n\n        // Various operators.\n#if !defined(SWIG)\n        /**\n         * @brief Returns reference to vector element\n         *\n         * @param i [in] index in the vector \\f$i\\in \\{0,1\\} \\f$\n         *\n         * @return const reference to element\n         */\n        const T& operator() (size_t i) const { return _vec[i]; }\n\n        /**\n         * @brief Returns reference to vector element\n         *\n         * @param i [in] index in the vector \\f$i\\in \\{0,1\\} \\f$\n         *\n         * @return reference to element\n         */\n        T& operator() (size_t i) { return _vec[i]; }\n\n        /**\n         * @brief Returns reference to vector element\n         * @param i [in] index in the vector \\f$i\\in \\{0,1,2\\} \\f$\n         * @return const reference to element\n         */\n        const T& operator[] (size_t i) const { return _vec[i]; }\n\n        /**\n         * @brief Returns reference to vector element\n         * @param i [in] index in the vector \\f$i\\in \\{0,1,2\\} \\f$\n         * @return reference to element\n         */\n        T& operator[] (size_t i) { return _vec[i]; }\n#else\n        ARRAYOPERATOR (T);\n#endif\n\n        /**\n           @brief Scalar division.\n         */\n        const Vector2D< T > operator/ (T s) const\n        {\n            return Vector2D< T > ((*this)[0] / s, (*this)[1] / s);\n        }\n\n        /**\n           @brief Scalar multiplication.\n         */\n        const Vector2D< T > operator* (T s) const\n        {\n            return Vector2D< T > ((*this)[0] * s, (*this)[1] * s);\n        }\n#if !defined(SWIGPYTHON)\n        /**\n           @brief Scalar multiplication.\n         */\n        friend const Vector2D< T > operator* (T s, const Vector2D< T >& v)\n        {\n            return Vector2D< T > (s * v[0], s * v[1]);\n        }\n#endif\n\n        /**\n           @brief Vector subtraction.\n         */\n        const Vector2D< T > operator- (const Vector2D< T >& b) const\n        {\n            return Vector2D< T > ((*this) (0) - b (0), (*this) (1) - b (1));\n        }\n\n        /**\n           @brief Vector addition.\n         */\n        const Vector2D< T > operator+ (const Vector2D< T >& b) const\n        {\n            return Vector2D< T > ((*this) (0) + b (0), (*this) (1) + b (1));\n        }\n\n        /**\n           @brief Scalar multiplication.\n         */\n        Vector2D< T >& operator*= (T s)\n        {\n            _vec[0] *= s;\n            _vec[1] *= s;\n            return *this;\n        }\n\n        /**\n           @brief Scalar division.\n         */\n        Vector2D< T >& operator/= (T s)\n        {\n            _vec[0] /= s;\n            _vec[1] /= s;\n            return *this;\n        }\n\n        /**\n           @brief Vector addition.\n         */\n        Vector2D< T >& operator+= (const Vector2D< T >& v)\n        {\n            _vec[0] += v (0);\n            _vec[1] += v (1);\n            return *this;\n        }\n\n        /**\n           @brief Vector subtraction.\n         */\n        Vector2D< T >& operator-= (const Vector2D< T >& v)\n        {\n            _vec[0] -= v (0);\n            _vec[1] -= v (1);\n            return *this;\n        }\n\n        /**\n           @brief Unary minus.\n         */\n        const Vector2D< T > operator- () const { return Vector2D< T > (-_vec[0], -_vec[1]); }\n\n        /**\n         * @brief Compares \\b a and \\b b for equality.\n         * @param b [in]\n         * @return True if a equals b, false otherwise.\n         */\n        bool operator== (const Vector2D< T >& b) const { return _vec[0] == b[0] && _vec[1] == b[1]; }\n\n        /**\n         *  @brief Compares \\b a and \\b b for inequality.\n         * @param b [in]\n         * @return True if a and b are different, false otherwise.\n         */\n        bool operator!= (const Vector2D< T >& b) const { return !(*this == b); }\n\n        /**\n         * @brief returns the counter clock-wise angle between\n         * this vector and the x-axis vector (1,0). The angle\n         * returned will be in the interval [-Pi,Pi]\n         */\n        double angle () { return atan2 (_vec[1], _vec[0]); }\n#if !defined(SWIG)\n        /**\n           @brief Streaming operator.\n         */\n        friend std::ostream& operator<< (std::ostream& out, const Vector2D< T >& v)\n        {\n            return out << \"Vector2D {\" << v[0] << \", \" << v[1] << \"}\";\n        }\n#else\n        TOSTRING (rw::math::Vector2D< T >);\n#endif\n\n        /**\n         * @brief Returns the Euclidean norm (2-norm) of the vector\n         * @return the norm\n         */\n        T norm2 () const { return sqrt (_vec[0] * _vec[0] + _vec[1] * _vec[1]); }\n\n        /**\n         * @brief Returns the Manhatten norm (1-norm) of the vector\n         * @return the norm\n         */\n        T norm1 () const { return fabs (_vec[0]) + fabs (_vec[1]); }\n\n        /**\n         * @brief Returns the infinte norm (\\f$\\inf\\f$-norm) of the vector\n         * @return the norm\n         */\n        T normInf () const\n        {\n            T res      = fabs (_vec[0]);\n            const T f1 = fabs (_vec[1]);\n            if (f1 > res)\n                res = f1;\n            return res;\n        }\n\n      private:\n        T _vec[2];\n    };\n\n    /**\n     * @brief Calculates the 2D vector cross product @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$\n     *\n     * @param v1 [in] @f$ \\mathbf{v1} @f$\n     *\n     * @param v2 [in] @f$ \\mathbf{v2} @f$\n     *\n     * @return the cross product @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$\n     *\n     * The 2D vector cross product is defined as:\n     *\n     * @f$\n     * \\mathbf{v1} \\times \\mathbf{v2} =  v1_x * v2_y - v1_y * v2_x\n     * @f$\n     */\n    template< class T > T cross (const Vector2D< T >& v1, const Vector2D< T >& v2)\n    {\n        return v1 (0) * v2 (1) - v1 (1) * v2 (0);\n    }\n\n    /**\n     * @brief Calculates the dot product @f$ \\mathbf{v1} . \\mathbf{v2} @f$\n     * @param v1 [in] @f$ \\mathbf{v1} @f$\n     * @param v2 [in] @f$ \\mathbf{v2} @f$\n     *\n     * @return the dot product @f$ \\mathbf{v1} . \\mathbf{v2} @f$\n     */\n    template< class T > double dot (const Vector2D< T >& v1, const Vector2D< T >& v2)\n    {\n        return v1 (0) * v2 (0) + v1 (1) * v2 (1);\n    }\n\n    /**\n     * @brief calculates the counter clock-wise angle from v1 to\n     * v2. the value returned will be in the interval [-2Pi,2Pi]\n     */\n    template< class T > double angle (const Vector2D< T >& v1, const Vector2D< T >& v2)\n    {\n        return atan2 (v2 (1), v2 (0)) - atan2 (v1 (1), v1 (0));\n    }\n\n    /**\n     * @brief Returns the normalized vector\n     * \\f$\\mathbf{n}=\\frac{\\mathbf{v}}{\\|\\mathbf{v}\\|} \\f$.\n     *\n     * If \\f$ \\| \\mathbf{v} \\| = 0\\f$ then the zero vector is returned.\n     *\n     * @param v [in] \\f$ \\mathbf{v} \\f$ which should be normalized\n     *\n     * @return the normalized vector \\f$ \\mathbf{n} \\f$\n     */\n    template< class T > const Vector2D< T > normalize (const Vector2D< T >& v)\n    {\n        T length = v.norm2 ();\n        if (length != 0)\n            return Vector2D< T > (v (0) / length, v (1) / length);\n        else\n            return Vector2D< T > (0, 0);\n    }\n\n    /**\n     * @brief Casts Vector2D<T> to Vector2D<Q>\n     *\n     * @param v [in] Vector2D with type T\n     *\n     * @return Vector2D with type Q\n     */\n    template< class Q, class T > const Vector2D< Q > cast (const Vector2D< T >& v)\n    {\n        return Vector2D< Q > (static_cast< Q > (v (0)), static_cast< Q > (v (1)));\n    }\n\n#if !defined(SWIG)\n    extern template class rw::math::Vector2D< double >;\n    extern template class rw::math::Vector2D< float >;\n#else\n    SWIG_DECLARE_TEMPLATE (Vector2Dd, rw::math::Vector2D< double >);\n    SWIG_DECLARE_TEMPLATE (Vector2Df, rw::math::Vector2D< float >);\n#endif\n    using Vector2Dd = Vector2D< double >;\n    using Vector2Df = Vector2D< float >;\n\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::Vector2D\n         */\n        template<>\n        void write (const rw::math::Vector2D< double >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::Vector2D\n         */\n        template<>\n        void write (const rw::math::Vector2D< float >& sobject, rw::common::OutputArchive& oarchive,\n                    const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Vector2D\n         */\n        template<>\n        void read (rw::math::Vector2D< double >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Vector2D\n         */\n        template<>\n        void read (rw::math::Vector2D< float >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n    }    // namespace serialization\n}}       // namespace rw::common\n\nnamespace boost { namespace serialization {\n    /**\n     * @brief Boost serialization.\n     * @param archive [in] the boost archive to read from or write to.\n     * @param vector [in/out] the vector to read/write.\n     * @param version [in] class version (currently version 0).\n     * @relatedalso rw::math::Vector2D\n     */\n    template< class Archive, class T >\n    void serialize (Archive& archive, rw::math::Vector2D< T >& vector, const unsigned int version)\n    {\n        archive& vector[0];\n        archive& vector[1];\n    }\n}}    // namespace boost::serialization\n\n#endif    // end include guard\n", "meta": {"hexsha": "02620a0b5eec916764cfcaec51d85afb2d14381d", "size": 12928, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/Vector2D.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/Vector2D.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/Vector2D.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": 28.5386313466, "max_line_length": 101, "alphanum_fraction": 0.4874690594, "num_tokens": 3675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5361712964703629}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\nusing namespace Eigen;\nusing namespace std;\nint main()\n{\n  Matrix3d A = Matrix3d::Random();\n  A = (A + Matrix3d::Constant(1.2)) * 50;\n  cout << \"A =\" << endl << A << endl;\n  Vector3d v(1,2,3);\n  cout << \"A * v =\" << endl << A * v << endl;\n  cout << \" (A * v)^T =\" << endl << (A * v).transpose() << endl;\n}\n", "meta": {"hexsha": "f831826ecb7ad2842bb65480d60800a3ce5ff35b", "size": 349, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_software/example_3_3.cpp", "max_stars_repo_name": "rrgalvan/cpp-intro", "max_stars_repo_head_hexsha": "d384fcdad677fae95bdb1983bd73081e385c6fd2", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_software/example_3_3.cpp", "max_issues_repo_name": "rrgalvan/cpp-intro", "max_issues_repo_head_hexsha": "d384fcdad677fae95bdb1983bd73081e385c6fd2", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_software/example_3_3.cpp", "max_forks_repo_name": "rrgalvan/cpp-intro", "max_forks_repo_head_hexsha": "d384fcdad677fae95bdb1983bd73081e385c6fd2", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9285714286, "max_line_length": 64, "alphanum_fraction": 0.5386819484, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5361561506906329}}
{"text": "/*\n    hg.cpp -- Henyey-Greenstein model evaluation routines\n\n    Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>\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*/\n\n#include <layer/microfacet.h>\n#include <layer/frame.h>\n#include <layer/math.h>\n#include <layer/fourier.h>\n#include <layer/fresnel.h>\n#include <Eigen/SVD>\n#include <numeric>\n\nNAMESPACE_BEGIN(layer)\n\nstatic int expcosCoefficientCount(Float B, Float relerr) {\n    Float prod = 1, invB = 1.0f / B;\n    if (B == 0)\n        return 1;\n\n    for (int i=0; ; ++i) {\n        prod /= 1 + i * invB;\n\n        if (prod < relerr)\n            return i+1;\n    }\n}\n\nstatic Float modBesselRatio(Float B, Float k) {\n    const Float eps = std::numeric_limits<Float>::epsilon(),\n                invTwoB = 2.0f / B;\n\n    Float i = (Float) k,\n           D = 1 / (invTwoB * i++),\n           Cd = D, C = Cd;\n\n    while (std::abs(Cd) > eps * std::abs(C)) {\n        Float coeff = invTwoB * i++;\n        D = 1 / (D + coeff);\n        Cd *= coeff*D - 1;\n        C += Cd;\n    }\n\n    return C;\n}\n\nvoid expCosFourierSeries(Float A, Float B, Float relerr, std::vector<Float> &coeffs) {\n    /* Determine the required number of coefficients and allocate memory */\n    int n = expcosCoefficientCount(B, relerr);\n    coeffs.resize(n);\n\n    /* Determine the last ratio and work downwards */\n    coeffs[n-1] = modBesselRatio(B, n - 1);\n    for (int i=n-2; i>0; --i)\n        coeffs[i] = B / (2*i + B*coeffs[i+1]);\n\n    /* Evaluate the exponentially scaled I0 and correct scaling */\n    coeffs[0] = math::i0e(B) * std::exp(A+B);\n\n    /* Apply the ratios & factor of two upwards */\n    Float prod = 2*coeffs[0];\n    for (int i=1; i<n; ++i) {\n        prod *= coeffs[i];\n        if (std::abs(prod) < coeffs[0] * relerr) {\n            coeffs.erase(coeffs.begin() + i, coeffs.end());\n            break;\n        }\n        coeffs[i] = prod;\n    }\n}\n\nFloat smithG1(const Vector3 &v, const Vector3 &m, Float alpha) {\n    const Float tanTheta = std::abs(Frame::tanTheta(v));\n\n    /* Can't see the back side from the front and vice versa */\n    if (v.dot(m) * Frame::cosTheta(v) <= 0)\n        return 0.0f;\n\n    Float a = 1.0f / (alpha * tanTheta);\n    if (a < 1.6f) {\n        /* Use a fast and accurate (<0.35% rel. error) rational\n           approximation to the shadowing-masking function */\n        const Float aSqr = a * a;\n        return (3.535f * a + 2.181f * aSqr)\n             / (1.0f + 2.276f * a + 2.577f * aSqr);\n    }\n\n    return 1.f;\n}\n\nFloat microfacet(Float mu_o, Float mu_i, std::complex<Float> eta_,\n                 Float alpha, Float phi_d) {\n    Float sinThetaI = math::safe_sqrt(1-mu_i*mu_i),\n          sinThetaO = math::safe_sqrt(1-mu_o*mu_o),\n          cosPhi = std::cos(phi_d),\n          sinPhi = std::sin(phi_d);\n\n    Vector wi(-sinThetaI, 0, -mu_i);\n    Vector wo(sinThetaO*cosPhi, sinThetaO*sinPhi, mu_o);\n    bool reflect = -mu_i*mu_o > 0;\n\n    if (mu_o == 0 || mu_i == 0)\n        return 0.f;\n    \n    bool conductor = eta_.imag() != 0.0f;\n    if (conductor && !reflect)\n        return 0.0f;\n    std::complex<Float> eta =\n        (-mu_i > 0 || conductor) ? eta_ : std::complex<Float>(1) / eta_;\n\n    Vector H = (wi + wo * (reflect ? 1.0f : eta.real())).normalized();\n    H *= math::signum(Frame::cosTheta(H));\n\n    Float cosThetaH2 = Frame::cosTheta2(H),\n          exponent = -Frame::tanTheta2(H) / (alpha*alpha),\n          D = std::exp(exponent) / (math::Pi * alpha*alpha * cosThetaH2*cosThetaH2),\n          F = !conductor ? fresnelDielectric(wi.dot(H), eta_.real())\n                         : fresnelConductor(std::abs(wi.dot(H)), eta),\n          G = smithG1(wi, H, alpha) * smithG1(wo, H, alpha);\n\n    if (reflect) {\n        return F * D * G / (4.0f * std::abs(mu_i*mu_o));\n    } else {\n        Float sqrtDenom = wi.dot(H) + eta.real() * wo.dot(H);\n\n        return std::abs(((1 - F) * D * G * eta.real() * eta.real() * wi.dot(H)\n            * wo.dot(H)) / (mu_i*mu_o * sqrtDenom * sqrtDenom));\n    }\n}\n\nFloat microfacetNoExp(Float mu_o, Float mu_i, std::complex<Float> eta_,\n                      Float alpha, Float phi_d) {\n    Float sinThetaI = math::safe_sqrt(1-mu_i*mu_i),\n          sinThetaO = math::safe_sqrt(1-mu_o*mu_o),\n          cosPhi = std::cos(phi_d),\n          sinPhi = std::sin(phi_d);\n\n    Vector wi(-sinThetaI, 0, -mu_i);\n    Vector wo(sinThetaO*cosPhi, sinThetaO*sinPhi, mu_o);\n    bool reflect = -mu_i*mu_o > 0;\n\n    if (mu_o == 0 || mu_i == 0)\n        return 0.f;\n\n    bool conductor = eta_.imag() != 0.0f;\n    if (conductor && !reflect)\n        return 0.0f;\n    std::complex<Float> eta =\n        (-mu_i > 0 || conductor) ? eta_ : std::complex<Float>(1) / eta_;\n\n    Vector H = (wi + wo * (reflect ? 1.0f : eta.real())).normalized();\n    H *= math::signum(Frame::cosTheta(H));\n\n    Float cosThetaH2 = Frame::cosTheta2(H),\n          D = (Float) 1 / (math::Pi * alpha*alpha * cosThetaH2*cosThetaH2),\n          F = !conductor ? fresnelDielectric(wi.dot(H), eta_.real())\n                         : fresnelConductor(std::abs(wi.dot(H)), eta),\n          G = smithG1(wi, H, alpha) * smithG1(wo, H, alpha);\n\n    if (reflect) {\n        return F * D * G / (4.0f * std::abs(mu_i*mu_o));\n    } else {\n        Float sqrtDenom = wi.dot(H) + eta.real() * wo.dot(H);\n\n        return std::abs(((1 - F) * D * G * eta.real() * eta.real() * wi.dot(H)\n            * wo.dot(H)) / (mu_i*mu_o * sqrtDenom * sqrtDenom));\n    }\n}\n\nstatic Float Bmax(size_t n, Float relerr) {\n    if (relerr >= 1e-1f)\n        return 0.1662f*std::pow((Float) n, (Float) 2.05039);\n    else if (relerr >= 1e-2f)\n        return 0.0818f*std::pow((Float) n, (Float) 2.04982);\n    else if (relerr >= 1e-3f)\n        return 0.0538f*std::pow((Float) n, (Float) 2.05001);\n    else if (relerr >= 1e-4f)\n        return 0.0406f*std::pow((Float) n, (Float) 2.04686);\n    else if (relerr >= 1e-5f)\n        return 0.0337f*std::pow((Float) n, (Float) 2.03865);\n    else if (relerr >= 1e-6f)\n        return 0.0299f*std::pow((Float) n, (Float) 2.02628);\n    else\n        throw std::runtime_error(\"Bmax(): unknown relative error bound!\");\n}\n\nvoid microfacetNoExpFourierSeries(Float mu_o, Float mu_i, std::complex<Float> eta_,\n                                  Float alpha, size_t n, Float phiMax,\n                                  std::vector<Float> &result) {\n\n    bool reflect = -mu_i * mu_o > 0;\n\n    Float sinMu2 = math::safe_sqrt((1 - mu_i * mu_i) * (1 - mu_o * mu_o)),\n          phiCritical = 0.0f;\n\n    bool conductor = (eta_.imag() != 0.0f);\n    std::complex<Float> eta =\n        (-mu_i > 0 || conductor) ? eta_ : std::complex<Float>(1) / eta_;\n\n    if (reflect) {\n        if (!conductor)\n            phiCritical = math::safe_acos((2*eta.real()*eta.real()-mu_i*mu_o-1)/sinMu2);\n    } else if (!reflect) {\n        if (conductor)\n            throw std::runtime_error(\"lowfreqFourierSeries(): encountered refraction case for a conductor\");\n        Float etaDenser = (eta.real() > 1 ? eta.real() : 1 / eta.real());\n        phiCritical = math::safe_acos((1 - etaDenser * mu_i * mu_o) /\n                                      (etaDenser * sinMu2));\n    }\n\n    if (!conductor && phiCritical > math::Epsilon &&\n        phiCritical < math::Pi - math::Epsilon &&\n        phiCritical < phiMax - math::Epsilon) {\n        /* Uh oh, some high frequency content leaked in the generally low frequency part.\n           Increase the number of coefficients so that we can capture it. Fortunately, this\n           happens very rarely. */\n        n = std::max(n, (size_t) 100);\n    }\n\n    VectorX coeffs(n);\n    coeffs.setZero();\n    std::function<Float(Float)> integrand = std::bind(\n        &microfacetNoExp, mu_o, mu_i, eta_, alpha, std::placeholders::_1);\n\n    const int nEvals = 200;\n    if (reflect) {\n        if (phiCritical > math::Epsilon && phiCritical < phiMax-math::Epsilon) {\n            filonIntegrate(integrand, coeffs.data(), n, nEvals, 0, phiCritical);\n            filonIntegrate(integrand, coeffs.data(), n, nEvals, phiCritical, phiMax);\n        } else {\n            filonIntegrate(integrand, coeffs.data(), n, nEvals, 0, phiMax);\n        }\n    } else {\n        filonIntegrate(integrand, coeffs.data(), n, nEvals, 0,\n                       std::min(phiCritical, phiMax));\n    }\n\n    if (phiMax < math::Pi - math::Epsilon) {\n        /* Precompute some sines and cosines */\n        VectorX cosPhi(n), sinPhi(n);\n        for (size_t i=0; i<n; ++i) {\n            sinPhi[i] = std::sin(i*phiMax);\n            cosPhi[i] = std::cos(i*phiMax);\n        }\n\n        /* The fit only occurs on a subset [0, phiMax], where the Fourier\n           Fourier basis functions are not orthogonal anymore! The following\n           then does a change of basis to proper Fourier coefficients. */\n        MatrixX A(n, n);\n\n        for (MatrixX::Index i=0; i < (MatrixX::Index) n; ++i) {\n            for (MatrixX::Index j=0; j <= (MatrixX::Index) i; ++j) {\n                if (i != j) {\n                    A(i, j) = A(j, i) = (i * cosPhi[j] * sinPhi[i] -\n                                         j * cosPhi[i] * sinPhi[j]) /\n                                        (i * i - j * j);\n                } else if (i != 0) {\n                    A(i, i) = (std::sin(2 * i * phiMax) + 2 * i * phiMax) / (4 * i);\n                } else {\n                    A(i, i) = phiMax;\n                }\n            }\n        }\n\n        auto svd = A.bdcSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);\n        const MatrixX &U = svd.matrixU();\n        const MatrixX &V = svd.matrixV();\n        const VectorX &sigma = svd.singularValues();\n\n        if (sigma[0] == 0) {\n            result.clear();\n            result.push_back(0);\n            return;\n        }\n\n        VectorX temp = VectorX::Zero(n);\n        coeffs[0] *= math::Pi;\n        coeffs.tail(n-1) *= 0.5 * math::Pi;\n        for (size_t i=0; i<n; ++i) {\n            if (sigma[i] < 1e-9f * sigma[0])\n                break;\n            temp += V.col(i) * U.col(i).dot(coeffs) / sigma[i];\n        }\n        coeffs = temp;\n    }\n\n    result.resize(coeffs.size());\n    memcpy(result.data(), coeffs.data(), sizeof(Float) * coeffs.size());\n}\n\nvoid microfacetFourierSeries(Float mu_o, Float mu_i, std::complex<Float> eta_,\n                             Float alpha, size_t n, Float relerr,\n                             std::vector<Float> &result) {\n    bool reflect = -mu_i * mu_o > 0;\n\n    /* Compute the 'A' and 'B' constants, as well as the critical azimuth */\n    Float A, B;\n    Float sinMu2 = math::safe_sqrt((1 - mu_i * mu_i) * (1 - mu_o * mu_o));\n\n    bool conductor = (eta_.imag() != 0.0f);\n    std::complex<Float> eta =\n        (-mu_i > 0 || conductor) ? eta_ : std::complex<Float>(1) / eta_;\n\n    if (reflect) {\n        Float temp = 1.0f / (alpha * (mu_i - mu_o));\n        A = (mu_i * mu_i + mu_o * mu_o - 2) * temp * temp;\n        B = 2 * sinMu2 * temp * temp;\n    } else {\n        if (conductor) {\n            /* No refraction in conductors */\n            result.clear();\n            result.push_back(0.0f);\n            return;\n        } else {\n            Float temp = 1.0f / (alpha * (mu_i - eta.real() * mu_o));\n            A = (mu_i * mu_i - 1 + eta.real() * eta.real() * (mu_o * mu_o - 1)) * temp * temp;\n            B = 2 * eta.real() * sinMu2 * temp * temp;\n        }\n    }\n\n    /* Minor optimization: don't even bother computing the Fourier series\n       if the contribution to the scattering model is miniscule */\n    if (math::i0e(B) * std::exp(A+B) < 1e-10) {\n        result.clear();\n        result.push_back(0.0f);\n        return;\n    }\n\n    Float B_max = Bmax(n, relerr);\n    if (B > B_max) {\n        A = A + B - B_max + std::log(math::i0e(B) / math::i0e(B_max));\n        B = B_max;\n    }\n\n    std::vector<Float> lowfreq_coeffs, expcos_coeffs;\n\n    /* Compute Fourier coefficients of the exponential term */\n    expCosFourierSeries(A, B, relerr, expcos_coeffs);\n\n    /* Compute Fourier coefficients of the low-frequency term\n       Only fit in the region where the result is actually\n       going to make some sort of difference given the convolution\n       with expcos_coeffs */\n    Float phiMax = math::safe_acos(1 + std::log(relerr) / B);\n\n    microfacetNoExpFourierSeries(mu_o, mu_i, eta_, alpha,\n                                 12, phiMax, lowfreq_coeffs);\n\n    /* Perform discrete circular convolution of the two series */\n    result.resize(lowfreq_coeffs.size() + expcos_coeffs.size() - 1);\n\n    convolveFourier(lowfreq_coeffs.data(), lowfreq_coeffs.size(),\n        expcos_coeffs.data(), expcos_coeffs.size(), result.data());\n\n    /* Truncate the series if error bounds are satisfied */\n    for (size_t i=0; i<result.size(); ++i) {\n        assert(std::isfinite(result[i]));\n        if (result[i] == 0 || std::abs(result[i]) < result[0] * relerr) {\n            result.erase(result.begin() + i, result.end());\n            break;\n        }\n    }\n}\n\nNAMESPACE_END(layer)\n", "meta": {"hexsha": "77109a741dbf2aa149609565533c86745544f681", "size": 12892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/microfacet.cpp", "max_stars_repo_name": "wjakob/layerlab", "max_stars_repo_head_hexsha": "3e5257e3076a7287d1da9bbd4ee3f05fe37d3ee3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 89.0, "max_stars_repo_stars_event_min_datetime": "2015-07-31T05:20:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T13:21:33.000Z", "max_issues_repo_path": "src/microfacet.cpp", "max_issues_repo_name": "wjakob/layerlab", "max_issues_repo_head_hexsha": "3e5257e3076a7287d1da9bbd4ee3f05fe37d3ee3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-08-17T20:50:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-07T11:27:04.000Z", "max_forks_repo_path": "src/microfacet.cpp", "max_forks_repo_name": "wjakob/layerlab", "max_forks_repo_head_hexsha": "3e5257e3076a7287d1da9bbd4ee3f05fe37d3ee3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2015-08-03T01:09:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T15:45:42.000Z", "avg_line_length": 34.8432432432, "max_line_length": 108, "alphanum_fraction": 0.5414210363, "num_tokens": 3836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5361539101410072}}
{"text": "#include <armadillo>\n\n#include <glm/lm.hpp>\n#include <glm/irls.hpp>\n\nusing namespace arma;\n\ndouble loglikelihood(const vec &residuals, double sigma_square, double n)\n{\n    return -n/2*log(2*datum::pi) - n/2*log( sigma_square ) - 1/(2*sigma_square) * accu( residuals % residuals );\n}\n\nvec\nlm(const mat &X, const vec &y, const uvec &missing, const glm_model &model, glm_info &output)\n{\n    vec w = ones<vec>( y.n_elem );\n    set_missing_to_zero( missing, w );\n    vec beta = weighted_least_squares( X, y, w );\n\n    double n = accu( w );\n    double k = X.n_cols;\n\n    vec mu = X * beta;\n    vec residuals = y - mu;\n    double sigma_square = as_scalar( trans( residuals ) * ( w % residuals ) / ( n - k ) );\n\n    mat cov = trans( X ) * ( diagmat( w ) * X );\n    mat cov_inv;\n    if( !inv( cov_inv, cov ) )\n    {\n        output.success = false;\n        return beta;\n    }\n\n    vec sd = arma::sqrt( sigma_square * diagvec( cov_inv ) );\n\n    output.se_beta = sd;\n    output.p_value = 1 - chi_square_cdf( beta % beta / ( sd % sd ), 1 );\n    output.mu = mu;\n    output.logl = loglikelihood( residuals % w, sigma_square, n );\n    output.success = true;\n    output.converged = true;\n\n    return beta;\n}\n", "meta": {"hexsha": "65ac0ce24baaaf5babcffa0ea297a5f1c3542227", "size": 1191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/glm/lm.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/lm.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/lm.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": 25.8913043478, "max_line_length": 112, "alphanum_fraction": 0.6070528967, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.5361539033219282}}
{"text": "#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <fmt/format.h>\n#include <string>\n#include <iomanip>\n#include <boost/variant.hpp>\n#include <unordered_map>\n#include <cstdint>\n#include <vector>\n#include <range/v3/algorithm.hpp>\nusing gint = std::int64_t;\nusing Coordinate = std::complex<gint>;\nenum Command {\n  TurnRight,\n  TurnLeft,\n  TurnUp,\n  TurnDown\n};\nclass Car\n{\n  std::complex<gint> pos_{ 1, 1 };\n  std::complex<gint> turn_[4]{\n    { 1, 0 },\n    { -1, 0 },\n    { 0, -1 },\n    { 0, 1 }\n  };\n  char map_[5][5] = {\n    '0',\n    '0',\n    '1',\n    '0',\n    '0',\n    '0',\n    '2',\n    '3',\n    '4',\n    '0',\n    '5',\n    '6',\n    '7',\n    '8',\n    '9',\n    '0',\n    'A',\n    'B',\n    'C',\n    '0',\n    '0',\n    '0',\n    'D',\n    '0',\n    '0'\n  };\n  std::vector<char> values_;\n  bool validpos(Coordinate pos) const\n  {\n    int i = pos.imag();\n    int j = pos.real();\n    return (0 <= pos.real() && pos.real() < 5 && 0 <= pos.imag() && pos.imag() < 5)\n           && (i + j) >= 2 && (i + j <= 6)\n           && (j - i) >= -2 && (j - i <= 2);\n  }\n\n  void process(Command command) noexcept\n  {\n    auto newpos = pos_ + turn_[command];\n    if (validpos(newpos)) {\n      pos_ = newpos;\n    }\n  }\n\npublic:\n  void process(std::vector<Command> const &commands) noexcept\n  {\n    for (auto command : commands) {\n      process(command);\n    }\n    values_.push_back(map_[pos_.imag()][pos_.real()]);\n  }\n  auto codes() const\n  {\n    return values_;\n  }\n};\n\n\nint main(int argc, char **argv)\n{\n  if (argc > 1) {\n    std::ifstream ifs(argv[1]);\n    char c;\n    int forward;\n    Car car;\n    std::string s;\n    while (std::getline(ifs, s)) {\n      std::vector<Command> coms;\n      ranges::transform(s, std::back_inserter(coms), [](char c) {\n        Command com[256];\n        com['L'] = Command::TurnLeft;\n        com['R'] = Command::TurnRight;\n        com['U'] = Command::TurnUp;\n        com['D'] = Command::TurnDown;\n        return com[c];\n      });\n      car.process(coms);\n    }\n    for (auto n : car.codes()) {\n      fmt::print(\"{},\", n);\n    }\n    fmt::print(\"\\n\");\n  }\n}", "meta": {"hexsha": "67e59acf80bc168fe4873bac3a5eda9bb29d2b79", "size": 2093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc2016/aoc160202.cpp", "max_stars_repo_name": "jiayuehua/adventOfCode", "max_stars_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "aoc2016/aoc160202.cpp", "max_issues_repo_name": "jiayuehua/adventOfCode", "max_issues_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "aoc2016/aoc160202.cpp", "max_forks_repo_name": "jiayuehua/adventOfCode", "max_forks_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": 18.2, "max_line_length": 83, "alphanum_fraction": 0.4978499761, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5360761827810671}}
{"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_TWOTO31_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_TWOTO31_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate  2 to the power 31 (\\f$2^{31}\\f$)\n\n    @par Semantic:\n\n    @code\n    T r = Twoto31<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = pow(2, 31);\n    @endcode\n\n    @return The Twoto31 constant for the proper type\n  **/\n  template<typename T> T Twoto31();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant twoto31.\n\n      @return The Twoto31 constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::twoto31_> twoto31 = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/twoto31.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": "448b1fbf3b05da25426bc2d139a09e32dfb8012a", "size": 1319, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/twoto31.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/twoto31.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/twoto31.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": 23.5535714286, "max_line_length": 100, "alphanum_fraction": 0.5860500379, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146847, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5360761765705047}}
{"text": "/*-----------------------------------------------------------------------------+\nCopyright (c) 2018-2018: Hagen Pache\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n#pragma once\n\n#include <boost/test/unit_test.hpp>\n\n#include <dil/pi/FunctionsMap.hpp>\n\nnamespace dil {\nnamespace pi {\n\ntemplate <typename T>\nclass TestHelper : public FunctionsMap<T>\n{     \n     public:\n     void test_exactly_relation(    const Relations& relation_in,\n                                    const T& lhs, \n                                    const Interval<T>& rhs)\n     {\n        for( auto const& [rel, fun] : this->_function_map )\n        {\n            if (relation_in == rel)\n                BOOST_TEST(fun(lhs, rhs) == true);\n            else\n                BOOST_TEST( fun(lhs, rhs) == false,\n                            \"expected \" << relation_in <<\n                            \" but also \" << rel <<\n                            \" with (lhs \" << lhs << \", rhs \" << rhs <<\") got true\");\n        }\n\n     }\n};\n\n}\n}", "meta": {"hexsha": "c7526b0c5cf2995dfeaa029eafe5402dcf82818d", "size": 1275, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/PointTestHelper.hpp", "max_stars_repo_name": "beardedN5rd/aia", "max_stars_repo_head_hexsha": "ffb11b3502410c32f23733f547f1ab4590408fc8", "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": "tests/PointTestHelper.hpp", "max_issues_repo_name": "beardedN5rd/aia", "max_issues_repo_head_hexsha": "ffb11b3502410c32f23733f547f1ab4590408fc8", "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": "tests/PointTestHelper.hpp", "max_forks_repo_name": "beardedN5rd/aia", "max_forks_repo_head_hexsha": "ffb11b3502410c32f23733f547f1ab4590408fc8", "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.875, "max_line_length": 84, "alphanum_fraction": 0.4054901961, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.5360761694948855}}
{"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    testSparseMatrix.cpp\n * @author  Mandy Xie\n * @author  Fan Jiang\n * @author  Gerry Chen\n * @author  Frank Dellaert\n * @date    Jan, 2021\n */\n\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/SparseEigen.h>\n\n#include <boost/assign/list_of.hpp>\nusing boost::assign::list_of;\n\n#include <gtsam/base/TestableAssertions.h>\n#include <CppUnitLite/TestHarness.h>\n\nusing namespace std;\nusing namespace gtsam;\n\n/* ************************************************************************* */\nTEST(SparseEigen, sparseJacobianEigen) {\n  GaussianFactorGraph gfg;\n  SharedDiagonal model = noiseModel::Isotropic::Sigma(2, 0.5);\n  const Key x123 = 0, x45 = 1;\n  gfg.add(x123, (Matrix(2, 3) << 1, 2, 3, 5, 6, 7).finished(),\n          Vector2(4, 8), model);\n  gfg.add(x123, (Matrix(2, 3) << 9, 10, 0, 0, 0, 0).finished(),\n          x45,  (Matrix(2, 2) << 11, 12, 14, 15.).finished(),\n          Vector2(13, 16), model);\n\n  // Sparse Matrix\n  auto sparseResult = sparseJacobianEigen(gfg);\n  EXPECT_LONGS_EQUAL(16, sparseResult.nonZeros());\n  EXPECT(assert_equal(4, sparseResult.rows()));\n  EXPECT(assert_equal(6, sparseResult.cols()));\n  EXPECT(assert_equal(gfg.augmentedJacobian(), Matrix(sparseResult)));\n\n  // Call sparseJacobian with optional ordering...\n  auto ordering = Ordering(list_of(x45)(x123));\n\n  // Eigen Sparse with optional ordering\n  EXPECT(assert_equal(gfg.augmentedJacobian(ordering),\n                      Matrix(sparseJacobianEigen(gfg, ordering))));\n\n  // Check matrix dimensions when zero rows / cols\n  gfg.add(x123, Matrix23::Zero(), Vector2::Zero(), model);  // zero row\n  gfg.add(2, Matrix21::Zero(), Vector2::Zero(), model);     // zero col\n  sparseResult = sparseJacobianEigen(gfg);\n  EXPECT_LONGS_EQUAL(16, sparseResult.nonZeros());\n  EXPECT(assert_equal(8, sparseResult.rows()));\n  EXPECT(assert_equal(7, sparseResult.cols()));\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "225e1dab22feb738e07a8dfde33a6695220b136a", "size": 2502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/tests/testSparseEigen.cpp", "max_stars_repo_name": "Alevs2R/gtsam", "max_stars_repo_head_hexsha": "6cef675e6eaeaf89f2462e8cfec4a4a9a497fac8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "gtsam/linear/tests/testSparseEigen.cpp", "max_issues_repo_name": "Alevs2R/gtsam", "max_issues_repo_head_hexsha": "6cef675e6eaeaf89f2462e8cfec4a4a9a497fac8", "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/linear/tests/testSparseEigen.cpp", "max_forks_repo_name": "Alevs2R/gtsam", "max_forks_repo_head_hexsha": "6cef675e6eaeaf89f2462e8cfec4a4a9a497fac8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 565.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T16:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:53:04.000Z", "avg_line_length": 34.2739726027, "max_line_length": 80, "alphanum_fraction": 0.5799360512, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5360761658794921}}
{"text": "\n// BLAS level 3\n// hermitian matrices, herk \n\n#include <stddef.h>\n#include <iostream>\n#include <boost/numeric/bindings/atlas/cblas3.hpp>\n#include <boost/numeric/bindings/traits/ublas_hermitian.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\nnamespace traits = boost::numeric::bindings::traits;\n\nusing std::cout;\nusing std::cin;\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::matrix<cmplx_t, ublas::row_major> rm_t;\ntypedef ublas::hermitian_adaptor<cm_t, ublas::upper> ucha_t; \ntypedef ublas::hermitian_adaptor<cm_t, ublas::lower> lcha_t; \ntypedef ublas::hermitian_adaptor<rm_t, ublas::upper> urha_t; \ntypedef ublas::hermitian_adaptor<rm_t, ublas::lower> lrha_t; \n\n#define N 3\n#define K 4\n\nint main() {\n\n  cm_t ac (N, K); \n  rm_t ar (N, K); \n\n  ac(0,0) = ar(0,0) = cmplx_t (1., 1.);\n  ac(1,0) = ar(1,0) = cmplx_t (2., 1.);\n  ac(2,0) = ar(2,0) = cmplx_t (3., 1.);\n#if (K > 1)\n  ac(0,1) = ar(0,1) = cmplx_t (1., 1.);\n  ac(1,1) = ar(1,1) = cmplx_t (2., 1.);\n  ac(2,1) = ar(2,1) = cmplx_t (3., 1.);\n#if (K > 2)\n  ac(0,2) = ar(0,2) = cmplx_t (1., 1.);\n  ac(1,2) = ar(1,2) = cmplx_t (2., 1.);\n  ac(2,2) = ar(2,2) = cmplx_t (3., 1.);\n#if (K > 3)\n  ac(0,3) = ar(0,3) = cmplx_t (1., 1.);\n  ac(1,3) = ar(1,3) = cmplx_t (2., 1.);\n  ac(2,3) = ar(2,3) = cmplx_t (3., 1.);\n#endif\n#endif\n#endif\n\n  print_m (ac, \"ac\"); \n  cout << endl; \n  print_m (ar, \"ar\"); \n  cout << endl << endl;\n\n  cm_t cmu (N, N); \n  cm_t cml (N, N); \n  rm_t rmu (N, N); \n  rm_t rml (N, N); \n  ucha_t ucha (cmu); \n  lcha_t lcha (cml); \n  urha_t urha (rmu); \n  lrha_t lrha (rml); \n\n  atlas::herk (CblasNoTrans, ac, ucha); \n  atlas::herk (CblasNoTrans, 1.0, ac, 0.0, lcha); \n  atlas::herk (CblasNoTrans, 1.0, ar, 0.0, urha); \n  atlas::herk (CblasNoTrans, ar, lrha); \n\n  print_m (ucha, \"ucha\");\n  cout << endl; \n  print_m (lcha, \"lcha\");\n  cout << endl; \n  print_m (urha, \"urha\");\n  cout << endl; \n  print_m (lrha, \"lrha\");\n  cout << endl << endl; \n\n  // part 2\n\n  cm_t act (ublas::herm (ac)); \n  rm_t art (ublas::herm (ar)); \n  print_m (act, \"act\"); \n  cout << endl; \n  print_m (art, \"art\"); \n  cout << endl << endl;\n\n  init_m (cmu, const_val<cmplx_t> (cmplx_t (0, 0)));\n  init_m (cml, const_val<cmplx_t> (cmplx_t (0, 0)));\n  init_m (rmu, const_val<cmplx_t> (cmplx_t (0, 0)));\n  init_m (rml, const_val<cmplx_t> (cmplx_t (0, 0)));\n\n  atlas::herk (CblasUpper, CblasConjTrans, 1.0, act, 0.0, cmu); \n  atlas::herk (CblasLower, CblasConjTrans, 1.0, act, 0.0, cml); \n  atlas::herk (CblasUpper, CblasConjTrans, 1.0, art, 0.0, rmu); \n  atlas::herk (CblasLower, CblasConjTrans, 1.0, art, 0.0, rml); \n\n  print_m (cmu, \"cmu\");\n  cout << endl; \n  print_m (cml, \"cml\");\n  cout << endl; \n  print_m (rmu, \"rmu\");\n  cout << endl; \n  print_m (rml, \"rml\");\n  cout << endl; \n}\n\n", "meta": {"hexsha": "7f8e1fab1a69d88c36d83de004d428b782ef7389", "size": 2892, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_herm3herk.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_herm3herk.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_herm3herk.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.592920354, "max_line_length": 64, "alphanum_fraction": 0.6002766252, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5360761658794921}}
{"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_DIVROUND2EVEN_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DIVROUND2EVEN_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing divround2even capabilities\n\n    Computes the round2even of the division.\n\n    @par semantic:\n    For any given value @c x,  @c y of type @c T:\n\n    @code\n    T r = divround2even(x, y);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    T r = round2even(x/y);\n    @endcode\n\n    for integral types, if y is null, it returns @ref Valmax or @ref Valmin\n    if x is positive (resp. negative) and 0 if x is null.\n    Take also care that dividing @ref Valmin by -1 for signed integral types has\n    undefined behaviour.\n\n    @see  divides, rec, divs, divfloor, divceil, divround, divfix\n\n  **/\n  const boost::dispatch::functor<tag::divround2even_> divround2even = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/divround2even.hpp>\n#include <boost/simd/function/simd/divround2even.hpp>\n\n#endif\n", "meta": {"hexsha": "c2a6c10cea06621e125ca71e6578208574eb83b4", "size": 1463, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/divround2even.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/divround2even.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/divround2even.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": 26.6, "max_line_length": 100, "alphanum_fraction": 0.6165413534, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5360761650144359}}
{"text": "#pragma once\n\n//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include \"mpfr/import_std_math.hpp\"\n\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/laguerre.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/tools/config.hpp>\n\nnamespace boost {\nnamespace math {\n\n// forward declarations\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type\nlaguerren(unsigned n, unsigned m, T x, const Policy& pol);\n\ntemplate <class T1, class T2>\ntypename laguerre_result<T1, T2>::type\nlaguerren(unsigned n, T1 m, T2 x);\n\nnamespace detail {\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type\nlaguerren(unsigned n, unsigned m, T x, const mpl::false_&)\n{\n  return boost::math::laguerren(n, m, x, policies::policy<>());\n}\n\n}  // namespace detail\n\n// Recurrence for associated polynomials:\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type\nlaguerren_next(unsigned n, unsigned l, T1 x, T2 Pl, T3 Plm1)\n{\n  typedef typename tools::promote_args<T1, T2, T3>::type result_type;\n\n\n  result_type nn = n;\n  result_type mm = l;\n  return (Pl * (mm + 2 * nn - x + 1) / ::math::sqrt((nn + 1) * (mm + nn + 1)) -\n          Plm1 * nn * (nn + mm) / ::math::sqrt(nn * (nn + 1) * (nn + mm) * (mm + nn + 1)));\n}\n\nnamespace detail {\n// Laguerre Associated Polynomial:\ntemplate <class T, class Policy>\nT\nlaguerren_imp(unsigned n, unsigned m, T x, const Policy& pol)\n{\n  // Special cases:\n  if (m == 0) return boost::math::laguerre(n, x, pol);\n\n  // normalization\n  T a = 1;\n  for (unsigned int i = m + n; i > n; --i) {\n    a *= i;\n  }\n\n  T p0 = 1 / ::math::sqrt(a);\n\n  if (n == 0) return p0;\n\n  T p1 = (m + 1 - x) / ::math::sqrt(a);\n\n  unsigned c = 1;\n\n  while (c < n) {\n    std::swap(p0, p1);\n    p1 = laguerren_next(c, m, x, p0, p1);\n    ++c;\n  }\n  return p1;\n}\n}\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type\nlaguerren(unsigned n, unsigned m, T x, const Policy& pol)\n{\n  typedef typename tools::promote_args<T>::type result_type;\n  typedef typename policies::evaluation<result_type, Policy>::type value_type;\n  // return policies::checked_narrowing_cast<result_type, Policy>(detail::laguerren_imp(n, m,\n  // static_cast<value_type>(x), pol),\n  //                                                              \"boost::math::laguerren<%1%>(unsigned,\n  //                                                              unsigned,\n  //                                                              %1%)\");\n\n  return detail::laguerren_imp(n, m, static_cast<value_type>(x), pol);\n}\n\ntemplate <class T1, class T2>\ninline typename laguerre_result<T1, T2>::type\nlaguerren(unsigned n, T1 m, T2 x)\n{\n  typedef typename policies::is_policy<T2>::type tag_type;\n  return detail::laguerren(n, m, x, tag_type());\n}\n\n}  // namespace math\n}  // namespace boost\n", "meta": {"hexsha": "28d06880b365913d719d7d303a7558d7c5bfec8a", "size": 3108, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/laguerren_impl.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/laguerren_impl.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/laguerren_impl.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": 28.0, "max_line_length": 104, "alphanum_fraction": 0.6354568855, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5360761596689297}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.                \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/basemeasure.hpp>\n#include <dpMM/distribution.hpp>\n#include <dpMM/normalSphere.hpp>\n#include <dpMM/iw.hpp>\n#include <dpMM/sphere.hpp>\n#include <dpMM/karcherMean.hpp>\n#include <dpMM/clGMMData.hpp>\n\nusing namespace Eigen;\nusing std::endl;\nusing std::cout;\n\n\ntemplate<typename T>\nclass NiwSphereFull : public BaseMeasure<T>\n{\npublic:\n\n  uint32_t D_;\n  IW<T> iw0_; // IW prior on the covariance of the normal in T_\\muS^D\n  Sphere<T> S_;\n  NormalSphere<T> normalS_; // sampled normal on sphere - distribution of data\n\n  NiwSphereFull(const IW<T>& iw, boost::mt19937* pRndGen);\n  ~NiwSphereFull();\n\n  virtual baseMeasureType getBaseMeasureType() const {return(NIW_SPHERE_FULL); }\n\n  virtual BaseMeasure<T>* copy();\n  virtual NiwSphereFull<T>* copyNative();\n\n  /* for any point on the sphere; maps into T_muS and rotates north first */\n  virtual T logLikelihood(const Matrix<T,Dynamic,1>& x) const ;\n  virtual T logLikelihood(const Matrix<T,Dynamic,Dynamic>& x, uint32_t i) const \n    {return logLikelihood(x.col(i));};\n  /* assumes x is already in T_northS */\n  virtual T logLikelihoodNorth(const Matrix<T,Dynamic,1>& x) const ;\n\n  void posterior(const Matrix<T,Dynamic,Dynamic>& x, const VectorXu& z, \n    uint32_t k);\n  void posterior(const shared_ptr<ClGMMData<T> >& cldp, uint32_t k);\n  /* assumes the x are already in T_northS correctly */\n  void posteriorFromPtsInTpS(const Matrix<T,Dynamic,Dynamic>& x, \n    const VectorXu& z, uint32_t k, uint32_t zDivider=1);\n\n  void sampleMergedParams();\n  /* samples Cov and then proposes means (covs are always accepted!) */\n  void sample();\n  /* proposes means and covariances jointly (and rejects them jointly as well)*/\n  void sample_2();\n\n  T logPdfUnderPrior() const;\n  T logPdfUnderPriorMarginalized() const;\n  T logPdfUnderPriorMarginalizedMerged(const shared_ptr<NiwSphereFull<T> >& other) const;\n  T qRandomMuProposal() const;\n\n  void print() const;\n\n  virtual NiwSphereFull<T>* merge(const NiwSphereFull<T>& other);\n  void fromMerge(const NiwSphereFull<T>& niwA, const NiwSphereFull<T>& niwB);\n\n  const Matrix<T,Dynamic,Dynamic>& scatter() const {return iw0_.scatter();};\n  Matrix<T,Dynamic,Dynamic>& scatter() {return iw0_.scatter();};\n  const Matrix<T,Dynamic,1>& mean() const {return iw0_.mean();};\n  Matrix<T,Dynamic,1>& mean() {return iw0_.mean();};\n  T count() const {return iw0_.count();};\n  T& count() {return iw0_.count();};\n\n  const Matrix<T,Dynamic,Dynamic>& Sigma() const {return normalS_.Sigma();};\n\n  const Matrix<T,Dynamic,1>& getMean() const {return normalS_.getMean();};\n  const Matrix<T,Dynamic,1>& getMeanKarch() const {return meanKarch_;};\n  // this is the sample mean\n  void setMeanKarch(const Matrix<T,Dynamic,1>& mean) {\n    meanKarch_ = mean; \n  };\n  void setMean(const Matrix<T,Dynamic,1>& mean) {normalS_.setMean(mean);};\n  virtual uint32_t getDim() const {return(D_);};\nprivate:\n\n  void computeMergedSS( const NiwSphereFull<T>& niwA, \n    const NiwSphereFull<T>& niwB, Matrix<T,Dynamic,Dynamic>& scatterM, \n    Matrix<T,Dynamic,1>& meanM,\n    Matrix<T,Dynamic,1>& muM, T& countM) const;\n\n  Matrix<T,Dynamic,1> meanKarch_;\n\n};\n\ntypedef NiwSphereFull<double> NiwSphereFulld;\ntypedef NiwSphereFull<float> NiwSphereFullf;\n\n", "meta": {"hexsha": "f52f3a95955cc72daab7b29e88d87297d102d886", "size": 3620, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/niwSphereFull.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/niwSphereFull.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/niwSphereFull.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": 34.1509433962, "max_line_length": 89, "alphanum_fraction": 0.7187845304, "num_tokens": 1018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5360761543234235}}
{"text": "//==============================================================================\n//         Copyright 2009 - 2013 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2014 MetaScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n\n#include <boost/fusion/include/at.hpp>\n#include <vector>\n#include <iostream>\n\n#include <nt2/sdk/bench/benchmark.hpp>\n#include <nt2/sdk/bench/protocol/max_duration.hpp>\n#include <nt2/sdk/bench/metric/cycles_per_element.hpp>\n#include <nt2/sdk/bench/stats/median.hpp>\n#include <nt2/sdk/bench/setup/geometric.hpp>\n#include <nt2/sdk/bench/setup/combination.hpp>\n#include <nt2/sdk/bench/setup/constant.hpp>\n\nusing namespace nt2::bench;\nusing namespace nt2;\n\nint mandelbrot_work(float a, float b, int max_iter)\n{\n  int iter = 0;\n  float x = 0;\n  float y = 0;\n  float t;\n  do {\n     t = x*x - y*y + a;\n     y = 2*x*y + b;\n     x = t;\n     iter++;\n    } while ((x*x+y*y<4) && (iter<max_iter));\n\n  return iter;\n}\n\ntemplate<typename T> struct mandelbrot_scalar\n{\n  typedef T value_type;\n  template<typename Setup>\n  mandelbrot_scalar(Setup const& s)\n                    :  h_(boost::fusion::at_c<0>(s))\n                    ,  w_(boost::fusion::at_c<1>(s))\n                    ,  a0_(boost::fusion::at_c<2>(s))\n                    ,  a1_(boost::fusion::at_c<3>(s))\n                    ,  b0_(boost::fusion::at_c<4>(s))\n                    ,  b1_(boost::fusion::at_c<5>(s))\n                    ,  max_iter_(boost::fusion::at_c<6>(s))\n  {\n    size_ = h_ * w_;\n\n    A.resize(size_);\n    B.resize(size_);\n    C.resize(size_);\n\n    T interval_A=(a1_-a0_)/(h_-1);\n    T new_val=a0_;\n    for (std::size_t jj=0;jj<w_;jj++){\n      for (std::size_t ii=0;ii<h_;ii++){\n        A[jj*h_+ii]=new_val;\n        new_val+=interval_A;\n      }\n      new_val=a0_;\n    }\n    new_val=b0_;\n    T interval_B=(b1_-b0_)/(w_-1);\n    for (std::size_t jj=0;jj<w_;jj++)\n    {\n      for (std::size_t ii=0;ii<h_;ii++)\n      {\n        B[jj*h_+ii]=new_val;\n      }\n      new_val+=interval_B;\n    }\n  }\n\n  void operator()()\n  {\n    std::size_t i, j;\n\n    for(i=0; i<h_; i++)\n    {\n      for(j=0; j<w_; j++)\n      {\n        C[j+w_*i] = mandelbrot_work(A[j+w_*i], B[j+w_*i], max_iter_);\n      }\n    }\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, mandelbrot_scalar<T> const& p)\n  {\n    return os << \"(\" << p.h_ << \" x \" << p.w_ << \")\";\n  }\n\n  std::size_t size() const { return size_; }\n\nprivate:\n  std::size_t h_, w_;\n  T a0_, a1_, b0_, b1_;\n  std::size_t max_iter_, size_;\n  std::vector<value_type> A, B;\n  std::vector<int> C;\n};\n\nNT2_REGISTER_BENCHMARK_TPL( mandelbrot_scalar, (float) )\n{\n  std::size_t hmin = args(\"hmin\", 100);\n  std::size_t hmax = args(\"hmax\", 1600);\n  std::size_t hstep = args(\"hstep\", 2);\n  std::size_t wmin = args(\"wmin\", 100);\n  std::size_t wmax = args(\"wmax\",1600);\n  std::size_t wstep = args(\"wstep\", 2);\n  T xmin = args(\"xmin\", -1.5);\n  T xmax = args(\"xmax\", 1.5);\n  T ymin = args(\"ymin\", -1.5);\n  T ymax = args(\"ymax\", 1.5);\n  T max_iter = args(\"max_iter\", 256);\n\n  run_during_with< mandelbrot_scalar<float> > ( 1.\n                                              , and_( geometric(hmin,hmax,hstep)\n                                                    , geometric(wmin,wmax,wstep)\n                                                    , constant(xmin)\n                                                    , constant(xmax)\n                                                    , constant(ymin)\n                                                    , constant(ymax)\n                                                    , constant(max_iter)\n                                                    )\n                                              , cycles_per_element<stats::median_>()\n                                              );\n}\n", "meta": {"hexsha": "83ccbba419c383afb2ea6d14ebb5a4fc44e842ff", "size": 3985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo/mandelbrot/scalar/mandelbrot_scalar.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "demo/mandelbrot/scalar/mandelbrot_scalar.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "demo/mandelbrot/scalar/mandelbrot_scalar.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 29.5185185185, "max_line_length": 84, "alphanum_fraction": 0.4777917189, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5360310157934746}}
{"text": "#include <sec/ShortestEdgeCollapse.h>\n\n#include <wmtk/utils/Logger.hpp>\n#include <wmtk/utils/ManifoldUtils.hpp>\n\n#include <igl/Timer.h>\n#include <igl/is_edge_manifold.h>\n#include <igl/is_vertex_manifold.h>\n#include <igl/read_triangle_mesh.h>\n\n#include <Eigen/Core>\n#include <catch2/catch.hpp>\n\n\nusing namespace sec;\nusing namespace wmtk;\n\nTEST_CASE(\"separate-manifold-patch\", \"[test_sec]\")\n{\n    std::vector<Eigen::Vector3d> v = {\n        {Eigen::Vector3d(0, 0, 0),\n         Eigen::Vector3d(1, 0, 0),\n         Eigen::Vector3d(0, 1, 0),\n         Eigen::Vector3d(0, 0, 1),\n         Eigen::Vector3d(0, -1, 0)}};\n    std::vector<std::array<size_t, 3>> tris = {{\n        {{0, 1, 2}},\n        {{0, 1, 3}},\n        {{0, 1, 4}},\n    }};\n\n    std::vector<Eigen::Vector3d> out_v;\n    std::vector<std::array<size_t, 3>> out_f;\n    std::vector<size_t> freeze_v;\n    wmtk::separate_to_manifold(v, tris, out_v, out_f, freeze_v);\n    REQUIRE(out_v.size() == 9);\n    REQUIRE(out_f.size() == 3);\n\n    // after extraction the output should be manifold\n    Eigen::VectorXi dummy;\n    Eigen::MatrixXd F(out_f.size(), 3);\n    for (int i = 0; i < out_f.size(); i++) {\n        F.row(i) << out_f[i][0], out_f[i][1], out_f[i][2];\n    }\n    REQUIRE(igl::is_edge_manifold(F));\n\n    ShortestEdgeCollapse m(out_v);\n    m.create_mesh(out_v.size(), out_f, freeze_v, 0);\n    m.collapse_shortest(-1);\n    Eigen::MatrixXi Fafter = Eigen::MatrixXi::Constant(m.tri_capacity(), 3, -1);\n    for (auto& t : m.get_faces()) {\n        auto i = t.fid(m);\n        auto vs = m.oriented_tri_vertices(t);\n        Fafter.row(i) << vs[0].vid(m), vs[1].vid(m), vs[2].vid(m);\n    }\n    // after operations the mesh is manifold\n    REQUIRE(igl::is_edge_manifold(Fafter));\n    REQUIRE(igl::is_vertex_manifold(Fafter, dummy));\n}\n\nTEST_CASE(\"manifold-separate-test-37989\", \"[test_sec]\")\n{\n    std::string filename = WMT_DATA_DIR \"/37989_sf.obj\";\n    wmtk::manifold_internal::Vertices V;\n    wmtk::manifold_internal::Facets F;\n    igl::read_triangle_mesh(filename, V, F);\n    REQUIRE_FALSE(igl::is_edge_manifold(F));\n    std::vector<size_t> modified_vertices;\n    wmtk::manifold_internal::resolve_nonmanifoldness(V, F, modified_vertices);\n    REQUIRE(modified_vertices.size() > 0);\n    REQUIRE(igl::is_edge_manifold(F));\n    Eigen::VectorXi VI;\n    REQUIRE(igl::is_vertex_manifold(F, VI));\n}\n\n\nTEST_CASE(\"shortest_edge_collapse\", \"[test_sec]\")\n{\n    // 0___1___2                *\n    // \\  /\\  /                 *\n    // 3\\/__\\/4  ==>    __      *\n    //   \\  /          \\  /     *\n    //    \\/5           \\/5     *\n    // 3-4 is shortest\n\n    std::vector<Eigen::Vector3d> v_positions(6);\n    v_positions[0] = Eigen::Vector3d(-3, 3, 0);\n    v_positions[1] = Eigen::Vector3d(0, 3, 0);\n    v_positions[2] = Eigen::Vector3d(3, 3, 0);\n    v_positions[3] = Eigen::Vector3d(0, 0, 0);\n    v_positions[4] = Eigen::Vector3d(0.5, 0, 0);\n    v_positions[5] = Eigen::Vector3d(0, -3, 0);\n    ShortestEdgeCollapse m(v_positions);\n    std::vector<std::array<size_t, 3>> tris = {{{0, 1, 3}}, {{1, 2, 4}}, {{1, 4, 3}}, {{3, 4, 5}}};\n    m.create_mesh_nofreeze(6, tris);\n    std::vector<TriMesh::Tuple> edges = m.get_edges();\n    // find the shortest edge\n    double shortest = std::numeric_limits<double>::max();\n    TriMesh::Tuple shortest_edge;\n    for (TriMesh::Tuple t : edges) {\n        size_t v1 = t.vid(m);\n        size_t v2 = m.switch_vertex(t).vid(m);\n        if ((v_positions[v1] - v_positions[v2]).squaredNorm() < shortest) {\n            shortest = (v_positions[v1] - v_positions[v2]).squaredNorm();\n            shortest_edge = t;\n        }\n    }\n\n    REQUIRE_FALSE(m.check_link_condition(shortest_edge));\n    m.collapse_shortest(-1);\n\n    REQUIRE_FALSE(shortest_edge.is_valid(m));\n\n    REQUIRE(m.get_vertices().size() == 3);\n    REQUIRE(m.get_faces().size() == 1);\n}\n\nTEST_CASE(\"shortest_edge_collapse_boundary_edge\", \"[test_sec]\")\n{\n    // 0___1___2    0 __1___2      0 __1\n    // \\  /\\  /      \\  |  /         \\ |\n    // 3\\/__\\/4  ==>  \\ | / ==>        6\n    //                 \\|/5\n    //\n\n    std::vector<Eigen::Vector3d> v_positions(6);\n    v_positions[0] = Eigen::Vector3d(-3, 3, 0);\n    v_positions[1] = Eigen::Vector3d(0, 3, 0);\n    v_positions[2] = Eigen::Vector3d(3, 3, 0);\n    v_positions[3] = Eigen::Vector3d(0, 0, 0);\n    v_positions[4] = Eigen::Vector3d(0.5, 0, 0);\n    ShortestEdgeCollapse m(v_positions);\n    std::vector<std::array<size_t, 3>> tris = {{{0, 1, 3}}, {{1, 2, 4}}, {{3, 1, 4}}};\n    m.create_mesh_nofreeze(5, tris);\n    std::vector<TriMesh::Tuple> edges = m.get_edges();\n    // find the shortest edge\n    double shortest = std::numeric_limits<double>::max();\n    TriMesh::Tuple shortest_edge;\n    for (TriMesh::Tuple t : edges) {\n        size_t v1 = t.vid(m);\n        size_t v2 = m.switch_vertex(t).vid(m);\n        if ((v_positions[v1] - v_positions[v2]).squaredNorm() < shortest) {\n            shortest = (v_positions[v1] - v_positions[v2]).squaredNorm();\n            shortest_edge = t;\n        }\n    }\n    m.collapse_shortest(100);\n    // the collapsed edge tuple is not valid anymore\n    REQUIRE_FALSE(shortest_edge.is_valid(m));\n\n    m.write_triangle_mesh(\"collapsed.obj\");\n    REQUIRE(m.get_vertices().size() == 3);\n    REQUIRE(m.get_faces().size() == 1);\n}\n\nTEST_CASE(\"shortest_edge_collapse_closed_mesh\", \"[test_sec]\")\n{\n    SECTION(\"test on tet\")\n    {\n        // create a tet and collapse can't happen\n        std::vector<Eigen::Vector3d> v_positions(6);\n        v_positions[0] = Eigen::Vector3d(-3, 3, 0);\n        v_positions[1] = Eigen::Vector3d(0, 3, 0);\n        v_positions[2] = Eigen::Vector3d(0, 0, 2);\n        v_positions[3] = Eigen::Vector3d(0, 0, 0);\n\n        ShortestEdgeCollapse m(v_positions);\n        std::vector<std::array<size_t, 3>> tris = {\n            {{0, 1, 3}},\n            {{1, 2, 3}},\n            {{0, 3, 2}},\n            {{0, 1, 2}}};\n        m.create_mesh_nofreeze(4, tris);\n        m.collapse_shortest(100);\n        REQUIRE(m.vert_capacity() == 4);\n\n        REQUIRE(m.tri_capacity() == 4);\n    }\n    SECTION(\"test on cube, end with tet\")\n    {\n        // then test on a cube\n        // will have a tet in the end\n        const std::string root(WMT_DATA_DIR);\n        const std::string path = root + \"/piece_0.obj\";\n\n        Eigen::MatrixXd V;\n        Eigen::MatrixXi F;\n        bool ok = igl::read_triangle_mesh(path, V, F);\n\n        REQUIRE(ok);\n\n        REQUIRE(V.rows() == 8);\n        REQUIRE(F.rows() == 12);\n\n        std::vector<Eigen::Vector3d> v(V.rows());\n        std::vector<std::array<size_t, 3>> tri(F.rows());\n        for (int i = 0; i < V.rows(); i++) {\n            v[i] = V.row(i);\n        }\n        for (int i = 0; i < F.rows(); i++) {\n            for (int j = 0; j < 3; j++) tri[i][j] = (size_t)F(i, j);\n        }\n        ShortestEdgeCollapse m(v);\n        m.create_mesh(V.rows(), tri);\n        REQUIRE(m.check_mesh_connectivity_validity());\n        REQUIRE(m.collapse_shortest(100));\n\n        std::vector<TriMesh::Tuple> edges = m.get_edges();\n        REQUIRE(m.get_vertices().size() == 4);\n\n        REQUIRE(m.get_faces().size() == 4);\n    }\n}\n\n\nTEST_CASE(\"shortest_edge_collapse_octocat\", \"[test_sec][.slow]\")\n{\n    const std::string root(WMT_DATA_DIR);\n    const std::string path = root + \"/Octocat.obj\";\n\n    Eigen::MatrixXd V;\n    Eigen::MatrixXi F;\n    bool ok = igl::read_triangle_mesh(path, V, F);\n\n    REQUIRE(ok);\n\n    std::vector<Eigen::Vector3d> v(V.rows());\n    std::vector<std::array<size_t, 3>> tri(F.rows());\n    for (int i = 0; i < V.rows(); i++) {\n        v[i] = V.row(i);\n    }\n    for (int i = 0; i < F.rows(); i++) {\n        for (int j = 0; j < 3; j++) tri[i][j] = (size_t)F(i, j);\n    }\n    ShortestEdgeCollapse m(v);\n    m.create_mesh(V.rows(), tri);\n    REQUIRE(m.collapse_shortest(2000));\n    REQUIRE(m.check_mesh_connectivity_validity());\n}\n\nTEST_CASE(\"edge_manifold\", \"[test_sec]\")\n{\n    const std::string root(WMT_DATA_DIR);\n    const std::string path = root + \"/circle.obj\";\n\n    Eigen::MatrixXd V;\n    Eigen::MatrixXi F;\n    bool ok = igl::read_triangle_mesh(path, V, F);\n\n    REQUIRE(ok);\n\n    std::vector<Eigen::Vector3d> v(V.rows());\n    std::vector<std::array<size_t, 3>> tri(F.rows());\n    for (int i = 0; i < V.rows(); i++) {\n        v[i] = V.row(i);\n    }\n    for (int i = 0; i < F.rows(); i++) {\n        for (int j = 0; j < 3; j++) tri[i][j] = (size_t)F(i, j);\n    }\n    ShortestEdgeCollapse m(v);\n    m.create_mesh(V.rows(), tri);\n    REQUIRE(m.check_mesh_connectivity_validity());\n    REQUIRE(igl::is_edge_manifold(F) == m.check_edge_manifold());\n}\n\nTEST_CASE(\"shortest_edge_collapse_circle\", \"[test_sec]\")\n{\n    const std::string root(WMT_DATA_DIR);\n    const std::string path = root + \"/circle.obj\";\n\n    Eigen::MatrixXd V;\n    Eigen::MatrixXi F;\n    bool ok = igl::read_triangle_mesh(path, V, F);\n\n    REQUIRE(ok);\n\n    std::vector<Eigen::Vector3d> v(V.rows());\n    std::vector<std::array<size_t, 3>> tri(F.rows());\n    for (int i = 0; i < V.rows(); i++) {\n        v[i] = V.row(i);\n    }\n    for (int i = 0; i < F.rows(); i++) {\n        for (int j = 0; j < 3; j++) tri[i][j] = (size_t)F(i, j);\n    }\n    ShortestEdgeCollapse m(v);\n    m.create_mesh(V.rows(), tri);\n    REQUIRE(m.check_mesh_connectivity_validity());\n    REQUIRE(igl::is_edge_manifold(F));\n    REQUIRE(m.check_edge_manifold());\n    REQUIRE(m.collapse_shortest(100));\n    m.consolidate_mesh();\n    m.write_triangle_mesh(\"collapsed.obj\");\n}\n\n\nTEST_CASE(\"metis_test_bigmesh\", \"[test_sec][.slow]\")\n{\n    const std::string root(WMT_DATA_DIR);\n    const std::string path = root + \"/circle.obj\";\n\n    Eigen::MatrixXd V;\n    Eigen::MatrixXi F;\n    bool ok = igl::read_triangle_mesh(path, V, F);\n    REQUIRE(ok);\n\n    // change this for max concurrency\n    int max_num_threads = 8;\n\n    std::vector<double> timecost;\n\n    for (int thread = 1; thread <= max_num_threads; thread *= 2) {\n        std::vector<Eigen::Vector3d> v(V.rows());\n        std::vector<std::array<size_t, 3>> tri(F.rows());\n        for (int i = 0; i < V.rows(); i++) {\n            v[i] = V.row(i);\n        }\n        for (int i = 0; i < F.rows(); i++) {\n            for (int j = 0; j < 3; j++) tri[i][j] = (size_t)F(i, j);\n        }\n\n        ShortestEdgeCollapse m(v, thread);\n        // m.print_num_attributes();\n        m.create_mesh(V.rows(), tri);\n        REQUIRE(m.check_mesh_connectivity_validity());\n        igl::Timer timer;\n        double time;\n        timer.start();\n\n        // change this for num of operations\n        m.collapse_shortest(20);\n        time = timer.getElapsedTimeInMilliSec();\n        timecost.push_back(time);\n    }\n}", "meta": {"hexsha": "f32d6e01d20e906ef3ebc3605c73fd3dfc6b7fe2", "size": 10532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/ShortestEdgeCollapse/tests/test_sec.cpp", "max_stars_repo_name": "wildmeshing/wildmeshing-toolkit", "max_stars_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T08:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:19:41.000Z", "max_issues_repo_path": "app/ShortestEdgeCollapse/tests/test_sec.cpp", "max_issues_repo_name": "wildmeshing/wildmeshing-toolkit", "max_issues_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 86.0, "max_issues_repo_issues_event_min_datetime": "2021-12-03T01:46:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T19:33:17.000Z", "max_forks_repo_path": "app/ShortestEdgeCollapse/tests/test_sec.cpp", "max_forks_repo_name": "wildmeshing/wildmeshing-toolkit", "max_forks_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-26T08:29:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T22:10:42.000Z", "avg_line_length": 31.5329341317, "max_line_length": 99, "alphanum_fraction": 0.5717812381, "num_tokens": 3261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5360310074402274}}
{"text": "#include <iostream>                  // std::cout/endl\n#include <stdint.h>                  // uint64_t\n#include <boost/coroutine2/all.hpp>  // boost::coroutines2\n\ntypedef boost::coroutines2::coroutine<const uint64_t> coro_t;\n\nvoid fibonacci(coro_t::push_type& yield)\n{\n    uint64_t a = 0;\n    uint64_t b = 1;\n    while (true) {\n        yield(b);\n        auto tmp = a;\n        a = b;\n        b += tmp;\n    }\n}\n\nint main()\n{\n    for (auto i : coro_t::pull_type(\n             boost::coroutines2::fixedsize_stack(),\n             fibonacci)) {\n        if (i >= 10000) {\n            break;\n        }\n        std::cout << i << std::endl;\n    }\n}\n", "meta": {"hexsha": "3bbdcbc7195dd738d38886ce0faea27a083d7817", "size": 640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "30/boost_coroutine2/fibonacci_coroutine2.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": "30/boost_coroutine2/fibonacci_coroutine2.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": "30/boost_coroutine2/fibonacci_coroutine2.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": 21.3333333333, "max_line_length": 61, "alphanum_fraction": 0.5046875, "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6825737214979746, "lm_q1q2_score": 0.5360310005808503}}
{"text": "/**\n * @file\n * @copyright 2020 Max Planck Gesellschaft. All rights reserved.\n * @license BSD 3-clause\n */\n#pragma once\n\n#include <Eigen/Eigen>\n#include <ostream>\n\nnamespace trifinger_cameras\n{\nstruct CameraParameters\n{\n    unsigned int image_width;\n    unsigned int image_height;\n\n    Eigen::Matrix3d camera_matrix;\n    Eigen::Matrix<double, 1, 5> distortion_coefficients;\n\n    Eigen::Matrix4d tf_world_to_camera;\n};\n\nstd::ostream& operator<<(std::ostream& os, const CameraParameters& cp);\n\n}  // namespace trifinger_cameras\n", "meta": {"hexsha": "0db7d60dbdbbe88d920d046e48fcf52996651bcc", "size": 526, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/trifinger_cameras/camera_parameters.hpp", "max_stars_repo_name": "open-dynamic-robot-initiative/trifinger_cameras", "max_stars_repo_head_hexsha": "f115aa84862c44f5a09b19eed38117cbdbdaac83", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T05:55:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T03:14:31.000Z", "max_issues_repo_path": "include/trifinger_cameras/camera_parameters.hpp", "max_issues_repo_name": "open-dynamic-robot-initiative/trifinger_cameras", "max_issues_repo_head_hexsha": "f115aa84862c44f5a09b19eed38117cbdbdaac83", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-03T10:06:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-03T10:06:33.000Z", "max_forks_repo_path": "include/trifinger_cameras/camera_parameters.hpp", "max_forks_repo_name": "open-dynamic-robot-initiative/trifinger_cameras", "max_forks_repo_head_hexsha": "f115aa84862c44f5a09b19eed38117cbdbdaac83", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-04T16:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T17:48:07.000Z", "avg_line_length": 19.4814814815, "max_line_length": 71, "alphanum_fraction": 0.7300380228, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5360310005808501}}
{"text": "#pragma once\n\n#include \"prx/simulation/plant.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\nnamespace prx\n{\n\tclass ackermann_FO : public plant_t\n\t{\n\tpublic:\n\t\tackermann_FO(const std::string& path);\n\t\tvirtual ~ackermann_FO();\n\n\t\tvirtual void propagate(const double simulation_step) override final;\n\n\t\tvirtual void update_configuration() override;\n\n\tprotected:\n\n\t\tvirtual void compute_derivative() override final;\n\n\t\tdouble x;\n\t\tdouble y;\n\t\tdouble theta;\n\n\t\tdouble x_dot;\n\t\tdouble y_dot;\n\t\tdouble theta_dot;\n\n\t\tdouble gamma;\n\t\tdouble V;\n\n\t\t// Distance between front and back wheels\n\t\tdouble L = 1.5; \n\n\t\tconst double max_delta_deg = 60;\n\t\tconst double max_delta_rad = max_delta_deg * PRX_PI / 180.0;\n\n\t\tstd::vector<double> min_ctrl_bound = {-max_delta_rad, -30};\n\t\tstd::vector<double> max_ctrl_bound = {max_delta_rad, 30};\n\n\t\tstd::vector<double> min_state_bound = {-10, -10, -PRX_PI};\n\t\tstd::vector<double> max_state_bound = { 10,  10, PRX_PI};\n\t};\n}\n\nPRX_REGISTER_SYSTEM(ackermann_FO, Ackermann_FO)\nPRX_REGISTER_VELOCITY_FN(Ackermann_FO, [](system_ptr_t s){return s -> input_control_space -> get_bounds()[1].second;})\n\n", "meta": {"hexsha": "5a7758e2b4e2807b18e15f6cf8b1432e407e0602", "size": 1123, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/prx/simulation/plants/ackermann_FO.hpp", "max_stars_repo_name": "aravindsiv/ML4KP", "max_stars_repo_head_hexsha": "064015a7545e1713cbcad3e79807b5cec0849f54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-05-31T11:28:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-31T13:49:30.000Z", "max_issues_repo_path": "src/prx/simulation/plants/ackermann_FO.hpp", "max_issues_repo_name": "aravindsiv/ML4KP", "max_issues_repo_head_hexsha": "064015a7545e1713cbcad3e79807b5cec0849f54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-03T09:39:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T22:17:56.000Z", "max_forks_repo_path": "src/prx/simulation/plants/ackermann_FO.hpp", "max_forks_repo_name": "aravindsiv/ML4KP", "max_forks_repo_head_hexsha": "064015a7545e1713cbcad3e79807b5cec0849f54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-03T09:17:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T15:52:58.000Z", "avg_line_length": 21.5961538462, "max_line_length": 118, "alphanum_fraction": 0.7257346394, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645723, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5359529436348444}}
{"text": "/*\n * CostFunctions1_2.hpp\n *\n *  Created on: Nov 18, 2015\n *      Author: atabb\n *      Updated on May25, 2018 to use Eigen instead of newmat by atabb\n *      Also resolved ambiguity between Eigen's enum quaterion type and this project's\n */\n\n#ifndef COSTFUNCTIONS_HPP_\n#define COSTFUNCTIONS_HPP_\n\n\n#include \"ceres/ceres.h\"\n#include \"ceres/rotation.h\"\n#include \"glog/logging.h\"\n#include \"Calibration2.hpp\"\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\nusing namespace Eigen;\n\nusing ceres::AutoDiffCostFunction;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solver;\nusing ceres::Solve;\n\nusing namespace std;\n\nenum PARAM_TYPE {Euler, AxisAngle, Cali_Quaternion };\n//enum COST_TYPE {c1, c2, rp1, rp2, dh1, dh2, z, li_dq, li_kp, hirsh, shah};\nenum COST_TYPE {c1, c2, rp1, rp2};\nenum SEPARABLE_TYPE {rotation_only, translation_only, simultaneous};\n\ntemplate <typename T>\nvoid Convert6ParameterEulerAngleRepresentationIntoMatrix(const T* X, T* XM){\n\tT RX[9];\n\tceres::EulerAnglesToRotationMatrix(X, 3, RX);\n\n\tXM[0] = RX[0];\n\tXM[1] = RX[1];\n\tXM[2] = RX[2];\n\tXM[3] = X[3];\n\n\tXM[4] = RX[3];\n\tXM[5] = RX[4];\n\tXM[6] = RX[5];\n\tXM[7] = X[4];\n\n\tXM[8] = RX[6];\n\tXM[9] = RX[7];\n\tXM[10] = RX[8];\n\tXM[11] = X[5];\n\n\tXM[12] = T(0);\n\tXM[13] = T(0);\n\tXM[14] = T(0);\n\tXM[15] = T(1);\n\n}\n\ntemplate <typename T>\nvoid Convert6ParameterAxisAngleRepresentationIntoMatrix(const T* X, T* XM){\n\tT RX[9];\n\n\tceres::AngleAxisToRotationMatrix(X, RX);\n\n\n\tXM[0] = RX[0];\n\tXM[1] = RX[1];\n\tXM[2] = RX[2];\n\tXM[3] = X[3];\n\n\tXM[4] = RX[3];\n\tXM[5] = RX[4];\n\tXM[6] = RX[5];\n\tXM[7] = X[4];\n\n\tXM[8] = RX[6];\n\tXM[9] = RX[7];\n\tXM[10] = RX[8];\n\tXM[11] = X[5];\n\n\tXM[12] = T(0);\n\tXM[13] = T(0);\n\tXM[14] = T(0);\n\tXM[15] = T(1);\n\n}\n\ntemplate <typename T>\nvoid Convert7ParameterQuaternionRepresentationIntoMatrix(const T* X, T* XM){\n\tT RX[9];\n\n\tceres::QuaternionToRotation(X, RX);\n\n\n\tXM[0] = RX[0];\n\tXM[1] = RX[1];\n\tXM[2] = RX[2];\n\tXM[3] = X[4];\n\n\tXM[4] = RX[3];\n\tXM[5] = RX[4];\n\tXM[6] = RX[5];\n\tXM[7] = X[5];\n\n\tXM[8] = RX[6];\n\tXM[9] = RX[7];\n\tXM[10] = RX[8];\n\tXM[11] = X[6];\n\n\tXM[12] = T(0);\n\tXM[13] = T(0);\n\tXM[14] = T(0);\n\tXM[15] = T(1);\n\n}\n\n\ntemplate <typename T>\nvoid MatrixMultiply(const T* X, const T* Y, T* M, int row_col){\n\n\t// assuming square matrices\n\tint xi, yi;\n\tT r;\n\tfor (int i = 0; i < row_col; i++){\n\t\tfor (int j = 0; j < row_col; j++){\n\t\t\t// dot product the ith row of X by the jth column of Y\n\n\t\t\tr= T(0);\n\t\t\tfor (int index = 0; index < row_col; index++){\n\t\t\t\txi = i*row_col + index;\n\t\t\t\tyi = index*row_col + j;\n\n\t\t\t\tr += X[xi]*Y[yi];\n\t\t\t}\n\t\t\tM[i*row_col + j] = r;\n\t\t}\n\t}\n}\n\ntemplate <typename T>\nvoid MatrixMultiply(const T* X, const T* Y, T* M, int row0, int col0, int row1, int col1){\n\n\t//\tcout << \"Args in Matrix Multiply: \" << endl;\n\t//\tcout << row0 << \", \" << col0 << \", \" << row1 << \", \" << col1 << endl;\n\t//\n\t//\tcout << \"First matrix \" << endl;\n\t//\tPrintMatrix(X, row0, col0);\n\t//\n\t//\tcout << \"Second matrix \" << endl;\n\t//\tPrintMatrix(Y, row1, col1);\n\n\n\t// not assuming square matrices\n\tif (col0 != row1){\n\t\tcout << \"Wrong args sent to Matrix Multiply: \" << endl;\n\t\tcout << row0 << \", \" << col0 << \", \" << row1 << \", \" << col1 << endl;\n\t}\n\n\tint xi, yi;\n\tT r;\n\tfor (int i = 0; i < row0; i++){\n\t\tfor (int j = 0; j < col1; j++){\n\t\t\t// dot product the ith row of X by the jth column of Y, results in the\n\t\t\t//cout << \"i, j \" << i << \", \" << j << endl;\n\n\t\t\tr= T(0);\n\t\t\tfor (int index = 0; index < col0; index++){\n\t\t\t\txi = i*col0 + index; // walk across the row\n\t\t\t\tyi = index*col1 + j; // walk down the columm\n\n\t\t\t\tr += X[xi]*Y[yi];\n\n\t\t\t\t//cout << \"Mult \" << xi << \" from first by \" << yi << \" from second\" << endl;\n\t\t\t}\n\t\t\t//cout << \"Result stored in \" << i*col1 + j << endl;\n\t\t\t//char ch; cin >> ch;\n\t\t\tM[i*col1 + j] = r;\n\t\t}\n\t}\n}\n\ntemplate <typename T>\nvoid PrintMatrix(const T* X, int row0, int col0){\n\n\tfor (int i = 0, index = 0; i < row0; i++){\n\t\tfor (int j = 0; j < col0; j++, index++){\n\t\t\tcout << X[index] << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\n}\n\n\n\n// one camera for now.\nstruct CF1_2 {\n\tCF1_2(double* A, double* B, PARAM_TYPE param_type, COST_TYPE cost_type): A(A), B(B), param_type(param_type), cost_type(cost_type){\n\t}\n\n\ttemplate <typename T>\n\tbool operator()(const T* const X,\n\t\t\tconst T* const Z,\n\t\t\tT* residuals) const {\n\t\t// X and Z are 6 parameters each, and our unknowns\n\t\t// need to represent these each as matrices\n\n\t\t//The {pitch,roll,yaw} Euler angles are rotations around the {x,y,z} axes, respectively.\n\t\t//They are applied in that same order, so the total rotation R is Rz * Ry * Rx.\n\n\t\tT XM[16];\n\t\tT ZM[16];\n\n\t\tswitch (param_type){\n\t\tcase Euler: {\n\t\t\tConvert6ParameterEulerAngleRepresentationIntoMatrix(X, XM);\n\t\t\tConvert6ParameterEulerAngleRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\tcase AxisAngle: {\n\t\t\tConvert6ParameterAxisAngleRepresentationIntoMatrix(X, XM);\n\t\t\tConvert6ParameterAxisAngleRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\tcase Cali_Quaternion: {\n\t\t\tConvert7ParameterQuaternionRepresentationIntoMatrix(X, XM);\n\t\t\tConvert7ParameterQuaternionRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\t}\n\n\t\tT term0[16];\n\t\tT term1[16];\n\n\t\t// ||AX-ZB||\n\t\t// have to convert to T\n\t\tT AT[16];\n\t\tT BT[16];\n\t\tfor (int i = 0; i < 16; i++){\n\t\t\tAT[i] = T(A[i]);\n\t\t\tBT[i] = T(B[i]);\n\t\t}\n\n\n\t\tswitch (cost_type){\n\t\tcase c1: {\n\t\t\tMatrixMultiply(AT, XM, term0, 4);\n\t\t\tMatrixMultiply(ZM, BT, term1, 4);\n\n\n\t\t\tfor (int i = 0; i < 12; i++){\n\t\t\t\tresiduals[i] = term1[i] - term0[i];\n\t\t\t}\n\t\t} break;\n\t\tcase c2: {\n\t\t\tMatrixMultiply(ZM, BT, term0, 4);\n\t\t\tMatrixMultiply(term0, XM, term1, 4);\n\n\t\t\tfor (int i = 0; i < 12; i++){\n\t\t\t\tresiduals[i] = AT[i] - term1[i];\n\t\t\t}\n\n\t\t}break;\n\t\tdefault: {\n\t\t\tcout << \"Cost type \" << cost_type << \"  not supported in CF1_2 \" << endl;\n\t\t}\n\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tstatic ceres::CostFunction* Create(double* A,\n\t\t\tdouble* B, PARAM_TYPE param_type, COST_TYPE cost_type) {\n\t\treturn (new ceres::AutoDiffCostFunction<CF1_2, 12, 7, 7>(\n\t\t\t\tnew CF1_2(&A[0], &B[0], param_type, cost_type)));\n\t}\n\n\tdouble* A;\n\tdouble* B;\n\tPARAM_TYPE param_type;\n\tCOST_TYPE cost_type;\n};\n\n\nstruct CF1_2_multi {\n\tCF1_2_multi(double* A, double* B, PARAM_TYPE param_type, COST_TYPE cost_type, int number_cameras, int this_camera, double* weighting):\n\t\tA(A), B(B), param_type(param_type), cost_type(cost_type), number_cameras(number_cameras), this_camera(this_camera), weighting(weighting){\n\t}\n\n\ttemplate <typename T>\n\t//\tbool operator()(const T* const X,\n\t//\t\t\tconst T* const Z,\n\t//\t\t\tT* residuals) const {\n\tbool operator()(T const* const* parameters,\n\t\t\tT* residuals) const {\n\t\t// X and Z are 6 parameters each, and our unknowns\n\t\t// need to represent these each as matrices\n\n\t\t//The {pitch,roll,yaw} Euler angles are rotations around the {x,y,z} axes, respectively.\n\t\t//They are applied in that same order, so the total rotation R is Rz * Ry * Rx.\n\n\t\tT XM[16];\n\t\tT ZM[16];\n\n\t\tT X[7];\n\t\tT Z[7];\n\n\t\tT w = T(sqrt(*weighting));\n\t\t//cout << \"Parameters for \" << this_camera << endl;\n\n\t\tfor (int i = 0; i < 7; i++){\n\t\t\tZ[i] = T(*parameters[(this_camera + 1)*7 + i]);\n\t\t\tX[i] = T(*parameters[0*7 + i]);\n\t\t\t//cout << \"X, Z: \" << X[i] << \", \" << Z[i] << endl;\n\t\t}\n\n\t\tswitch (param_type){\n\t\tcase Euler: {\n\t\t\tConvert6ParameterEulerAngleRepresentationIntoMatrix(X, XM);\n\t\t\tConvert6ParameterEulerAngleRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\tcase AxisAngle: {\n\t\t\tConvert6ParameterAxisAngleRepresentationIntoMatrix(X, XM);\n\t\t\tConvert6ParameterAxisAngleRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\tcase Cali_Quaternion: {\n\t\t\tConvert7ParameterQuaternionRepresentationIntoMatrix(X, XM);\n\t\t\tConvert7ParameterQuaternionRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\t}\n\n\t\tT term0[16];\n\t\tT term1[16];\n\n\t\t// ||AX-ZB||\n\t\t// have to convert to T\n\t\tT AT[16];\n\t\tT BT[16];\n\t\tfor (int i = 0; i < 16; i++){\n\t\t\tAT[i] = T(A[i]);\n\t\t\tBT[i] = T(B[i]);\n\t\t}\n\n\n\t\tswitch (cost_type){\n\t\tcase c1: {\n\t\t\tMatrixMultiply(AT, XM, term0, 4);\n\t\t\tMatrixMultiply(ZM, BT, term1, 4);\n\n\n\t\t\tfor (int i = 0; i < 12; i++){\n\t\t\t\tresiduals[i] = w*(term1[i] - term0[i]);\n\t\t\t}\n\t\t} break;\n\t\tcase c2: {\n\t\t\tMatrixMultiply(ZM, BT, term0, 4);\n\t\t\tMatrixMultiply(term0, XM, term1, 4);\n\n\t\t\tfor (int i = 0; i < 12; i++){\n\t\t\t\tresiduals[i] = (AT[i] - term1[i]);\n\t\t\t}\n\n\t\t}break;\n\t\tdefault: {\n\t\t\tcout << \"Cost type \" << cost_type << \"  not supported in CF1_2 \" << endl;\n\t\t}\n\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t//\tstatic ceres::CostFunction* Create(double* A,\n\t//\t\t\tdouble* B, PARAM_TYPE param_type, COST_TYPE cost_type) {\n\t//\t\treturn (new ceres::AutoDiffCostFunction<CF1_2, 12, 7, 7>(\n\t//\t\t\t\tnew CF1_2(&A[0], &B[0], param_type, cost_type)));\n\t//\t}\n\n\tstatic ceres::CostFunction* Create(double* A,\n\t\t\tdouble* B, PARAM_TYPE param_type, COST_TYPE cost_type, int number_cameras, int this_camera, double* weighting) {\n\n\n\t\tceres::DynamicAutoDiffCostFunction<CF1_2_multi, 7>* cost_function =\n\t\t\t\tnew ceres::DynamicAutoDiffCostFunction<CF1_2_multi, 7>(\n\t\t\t\t\t\tnew CF1_2_multi(A, B, param_type, cost_type, number_cameras, this_camera, weighting));\n\n\n\t\tfor (int i = 0; i < 7*(number_cameras + 1); i++){\n\t\t\t// one block for each X and the one Z\n\t\t\tcost_function->AddParameterBlock(1);\n\t\t}\n\t\tcost_function->SetNumResiduals(12);\n\n\t\treturn cost_function;\n\t}\n\n\tdouble* A;\n\tdouble* B;\n\tPARAM_TYPE param_type;\n\tCOST_TYPE cost_type;\n\tint number_cameras;\n\tint this_camera;\n\tdouble* weighting;\n};\n\n\nstruct CF1_2_multi_extended {\n\tCF1_2_multi_extended(double* A, double* B, double* param_copy, PARAM_TYPE param_type, COST_TYPE cost_type, SEPARABLE_TYPE sep_type,  int number_cameras, int this_camera, double* weighting):\n\t\tA(A), B(B), param_copy(param_copy), param_type(param_type), cost_type(cost_type), sep_type(sep_type), number_cameras(number_cameras), this_camera(this_camera), weighting(weighting){\n\t}\n\n\ttemplate <typename T>\n\t//\tbool operator()(const T* const X,\n\t//\t\t\tconst T* const Z,\n\t//\t\t\tT* residuals) const {\n\tbool operator()(T const* const* parameters,\n\t\t\tT* residuals) const {\n\t\t// X and Z are 6 parameters each, and our unknowns\n\t\t// need to represent these each as matrices\n\n\t\t//The {pitch,roll,yaw} Euler angles are rotations around the {x,y,z} axes, respectively.\n\t\t//They are applied in that same order, so the total rotation R is Rz * Ry * Rx.\n\n\t\tT XM[16];\n\t\tT ZM[16];\n\n\t\tT X[7];\n\t\tT Z[7];\n\n\t\tT w = T(sqrt(*weighting));\n\t\t//cout << \"Parameters for \" << this_camera << endl;\n\n\t\tswitch (sep_type){\n\t\tcase rotation_only: {\n\t\t\tfor (int i = 0; i < 7; i++){\n\t\t\t\tZ[i] = T(*parameters[(this_camera + 1)*7 + i]);\n\t\t\t\tX[i] = T(*parameters[0*7 + i]);\n\t\t\t\t//cout << \"X, Z: \" << X[i] << \", \" << Z[i] << endl;\n\t\t\t}\n\t\t}; break;\n\t\tcase translation_only: {\n\t\t\tif (param_type == Cali_Quaternion){\n\t\t\t\tfor (int i = 0; i < 7; i++){\n\t\t\t\t\tif (i < 4){\n\t\t\t\t\t\tZ[i] = T(param_copy[(this_camera + 1)*7 + i]);\n\t\t\t\t\t\tX[i] = T(param_copy[0*7 + i]);\n\t\t\t\t\t}\telse {\n\t\t\t\t\t\tZ[i] = T(*parameters[(this_camera + 1)*7 + i]);\n\t\t\t\t\t\tX[i] = T(*parameters[0*7 + i]);\n\t\t\t\t\t}\n\t\t\t\t\t//cout << \"X, Z: \" << X[i] << \", \" << Z[i] << endl;\n\t\t\t\t}\n\n\t\t\t}\telse {\n\t\t\t\tfor (int i = 0; i < 7; i++){\n\t\t\t\t\tif (i < 3){\n\t\t\t\t\t\tZ[i] = T(param_copy[(this_camera + 1)*7 + i]);\n\t\t\t\t\t\tX[i] = T(param_copy[0*7 + i]);\n\t\t\t\t\t}\telse {\n\t\t\t\t\t\tZ[i] = T(*parameters[(this_camera + 1)*7 + i]);\n\t\t\t\t\t\tX[i] = T(*parameters[0*7 + i]);\n\t\t\t\t\t}\n\t\t\t\t\t//cout << \"X, Z: \" << X[i] << \", \" << Z[i] << endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t} break;\n\t\tcase simultaneous: {\n\t\t\tcout << \"We don't let simultaneous currently use this function .... \" << endl;\n\t\t\texit(1);\n\t\t} break;\n\n\n\n\t\t}\n\t\t//\t\tfor (int i = 0; i < 7; i++){\n\t\t//\t\t\tZ[i] = T(*parameters[(this_camera + 1)*7 + i]);\n\t\t//\t\t\tX[i] = T(*parameters[0*7 + i]);\n\t\t//\t\t\t//cout << \"X, Z: \" << X[i] << \", \" << Z[i] << endl;\n\t\t//\t\t}\n\n\t\tswitch (param_type){\n\t\tcase Euler: {\n\t\t\tConvert6ParameterEulerAngleRepresentationIntoMatrix(X, XM);\n\t\t\tConvert6ParameterEulerAngleRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\tcase AxisAngle: {\n\t\t\tConvert6ParameterAxisAngleRepresentationIntoMatrix(X, XM);\n\t\t\tConvert6ParameterAxisAngleRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\tcase Cali_Quaternion: {\n\t\t\tConvert7ParameterQuaternionRepresentationIntoMatrix(X, XM);\n\t\t\tConvert7ParameterQuaternionRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\t}\n\n\t\tT term0[16];\n\t\tT term1[16];\n\n\t\t// ||AX-ZB||\n\t\t// have to convert to T\n\t\tT AT[16];\n\t\tT BT[16];\n\t\tfor (int i = 0; i < 16; i++){\n\t\t\tAT[i] = T(A[i]);\n\t\t\tBT[i] = T(B[i]);\n\t\t}\n\n\n\t\tswitch (cost_type){\n\t\tcase c1: {\n\t\t\tMatrixMultiply(AT, XM, term0, 4);\n\t\t\tMatrixMultiply(ZM, BT, term1, 4);\n\n\t\t\tswitch (sep_type){\n\t\t\tcase rotation_only: {\n\t\t\t\tfor (int i = 0; i < 12; i++){\n\t\t\t\t\tif ((i+ 1) % 4 == 0){\n\t\t\t\t\t\tresiduals[i] = T(0);\n\t\t\t\t\t}\telse {\n\t\t\t\t\t\tresiduals[i] = w*(term1[i] - term0[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} break;\n\t\t\tcase translation_only: {\n\t\t\t\tfor (int i = 0; i < 12; i++){\n\t\t\t\t\tif ((i+ 1) % 4 == 0){\n\t\t\t\t\t\tresiduals[i] = w*(term1[i] - term0[i]);\n\t\t\t\t\t}\telse {\n\t\t\t\t\t\tresiduals[i] = T(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} break;\n\t\t\tdefault: {\n\t\t\t\tfor (int i = 0; i < 12; i++){\n\t\t\t\t\tresiduals[i] = w*(term1[i] - term0[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\t}\n\n\t\t} break;\n\t\tcase c2: {\n\t\t\tMatrixMultiply(ZM, BT, term0, 4);\n\t\t\tMatrixMultiply(term0, XM, term1, 4);\n\n\n\t\t\tswitch (sep_type){\n\t\t\tcase rotation_only: {\n\t\t\t\tfor (int i = 0; i < 12; i++){\n\t\t\t\t\tif ((i+ 1) % 4 == 0){\n\t\t\t\t\t\tresiduals[i] = T(0);\n\t\t\t\t\t}\telse {\n\t\t\t\t\t\tresiduals[i] = w*(AT[i] - term1[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} break;\n\t\t\tcase translation_only: {\n\t\t\t\tfor (int i = 0; i < 12; i++){\n\t\t\t\t\tif ((i+ 1) % 4 == 0){\n\t\t\t\t\t\tresiduals[i] = w*(AT[i] - term1[i]);\n\t\t\t\t\t}\telse {\n\t\t\t\t\t\tresiduals[i] = T(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} break;\n\t\t\tdefault: {\n\t\t\t\tfor (int i = 0; i < 12; i++){\n\t\t\t\t\tresiduals[i] = w*(AT[i] - term1[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\t}\n\n\t\t}break;\n\t\tdefault: {\n\t\t\tcout << \"Cost type \" << cost_type << \"  not supported in CF1_2 \" << endl;\n\t\t}\n\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t//\tstatic ceres::CostFunction* Create(double* A,\n\t//\t\t\tdouble* B, PARAM_TYPE param_type, COST_TYPE cost_type) {\n\t//\t\treturn (new ceres::AutoDiffCostFunction<CF1_2, 12, 7, 7>(\n\t//\t\t\t\tnew CF1_2(&A[0], &B[0], param_type, cost_type)));\n\t//\t}\n\n\tstatic ceres::CostFunction* Create(double* A,\n\t\t\tdouble* B, double* param_copy, PARAM_TYPE param_type, COST_TYPE cost_type, SEPARABLE_TYPE sep_type, int number_cameras, int this_camera, double* weighting) {\n\n\n\t\tceres::DynamicAutoDiffCostFunction<CF1_2_multi_extended, 7>* cost_function =\n\t\t\t\tnew ceres::DynamicAutoDiffCostFunction<CF1_2_multi_extended, 7>(\n\t\t\t\t\t\tnew CF1_2_multi_extended(A, B, param_copy, param_type, cost_type, sep_type, number_cameras, this_camera, weighting));\n\n\n\t\tfor (int i = 0; i < 7*(number_cameras + 1); i++){\n\t\t\t// one block for each X and the one Z\n\t\t\tcost_function->AddParameterBlock(1);\n\t\t}\n\n\n\t\tcost_function->SetNumResiduals(12);\n\n\t\treturn cost_function;\n\t}\n\n\tdouble* A;\n\tdouble* B;\n\tdouble* param_copy;\n\tPARAM_TYPE param_type;\n\tCOST_TYPE cost_type;\n\tSEPARABLE_TYPE sep_type;\n\tint number_cameras;\n\tint this_camera;\n\tdouble* weighting;\n};\n\nstruct RP1_2_multi {\n\tRP1_2_multi(double* camera_parameters, double* B, double* twoDpoints, double* threeDpoints, PARAM_TYPE param_type, COST_TYPE cost_type, int number_points,\n\t\t\tint number_cameras, int this_camera, double* weighting):\n\t\t\t\tcamera_parameters(camera_parameters), B(B), twoDpoints(twoDpoints), threeDpoints(threeDpoints),\n\t\t\t\tparam_type(param_type), cost_type(cost_type), number_points(number_points),\n\t\t\t\tnumber_cameras(number_cameras), this_camera(this_camera), weighting(weighting){\n\t}\n\n\ttemplate <typename T>\n\t//\tbool operator()(const T* const X,\n\t//\t\t\tconst T* const Z,\n\t//\t\t\tT* residuals) const {\n\tbool operator()(T const* const* parameters,\n\t\t\tT* residuals) const {\n\t\t// X and Z are 7 parameters each, and our unknowns\n\t\t// need to represent these each as matrices\n\t\t// parameters: X0 (7) cam_parameters(12) X1(7) cam_parameters(12) Z(7)\n\n\t\t//The {pitch,roll,yaw} Euler angles are rotations around the {x,y,z} axes, respectively.\n\t\t//They are applied in that same order, so the total rotation R is Rz * Ry * Rx.\n\t\t//char ch;\n\n\t\tT XM[16];\n\t\tT ZM[16];\n\n\t\tT X[7];\n\t\tT Z[7];\n\n\t\tT w = T(sqrt(*weighting));\n\n\n\t\tfor (int i = 0; i < 7; i++){\n\t\t\tX[i] = T(*parameters[0*7 + i]);\n\t\t\tZ[i] = T(*parameters[7 + (this_camera)*19 + i]);\n\n\t\t}\n\n\t\tswitch (param_type){\n\t\tcase Euler: {\n\t\t\tConvert6ParameterEulerAngleRepresentationIntoMatrix(X, XM);\n\t\t\tConvert6ParameterEulerAngleRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\tcase AxisAngle: {\n\t\t\tConvert6ParameterAxisAngleRepresentationIntoMatrix(X, XM);\n\t\t\tConvert6ParameterAxisAngleRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\tcase Cali_Quaternion: {\n\t\t\tConvert7ParameterQuaternionRepresentationIntoMatrix(X, XM);\n\t\t\tConvert7ParameterQuaternionRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\t}\n\n\t\tT term0[16];\n\n\n\t\t// ||AX-ZB||\n\t\t// have to convert to T\n\t\tT A_hat_T[16];\n\t\tT BT[16];\n\t//\tT M[16];\n\t\tT K[9];\n\t\tT k1, k2, p1, p2, k3, k4, k5, k6;\n\t\tT r_sqr;\n\n\t\tT Xp[4];\n\t\tT xp[3];\n\t\tT xpp[3];\n\n\t\tfor (int i = 0; i < 16; i++){\n\n\t\t\tBT[i] = T(B[i]);\n\t\t}\n\n\t\tfor (int i = 0; i < 9; i++){\n\t\t\tK[i] = T(0);\n\t\t}\n\n\t\tK[8] = T(1);\n\n\t\t// set up A_hat\n\t\tMatrixMultiply(ZM, BT, term0, 4);\n\t\tMatrixMultiply(term0, XM, A_hat_T, 4);\n\n\n\t\t// copy over parameters\n\t\tswitch (cost_type){\n\t\tcase rp1: {\n\t\t\t// don't use the parameter version for camera cali -- this amtrix is sent all set up for use ....\n\t\t\tK[0] = T(camera_parameters[0]);\n\t\t\tK[2] = T(camera_parameters[1]);\n\t\t\tK[4] = T(camera_parameters[2]);\n\t\t\tK[5] = T(camera_parameters[3]);\n\t\t\tk1 = T(camera_parameters[4]);\n\t\t\tk2 = T(camera_parameters[5]);\n\t\t\tp1 = T(camera_parameters[6]);\n\t\t\tp2 = T(camera_parameters[7]);\n\t\t\tk3 = T(camera_parameters[8]);\n\t\t\tk4 = T(camera_parameters[9]);\n\t\t\tk5 = T(camera_parameters[10]);\n\t\t\tk6 = T(camera_parameters[11]);\n\t\t} break;\n\t\tcase rp2:{\n\t\t\tK[0] = *parameters[7 + (this_camera)*19 + 7];\n\t\t\tK[2] = *parameters[7 + (this_camera)*19 + 8];\n\t\t\tK[4] = *parameters[7 + (this_camera)*19 + 9];\n\t\t\tK[5] = *parameters[7 + (this_camera)*19 + 10];\n\t\t\tk1 = *parameters[7 + (this_camera)*19 + 11];\n\t\t\tk2 = *parameters[7 + (this_camera)*19 + 12];\n\t\t\tp1 = *parameters[7 + (this_camera)*19 + 13];\n\t\t\tp2 = *parameters[7 + (this_camera)*19 + 14];\n\t\t\tk3 = *parameters[7 + (this_camera)*19 + 15];\n\t\t\tk4 = *parameters[7 + (this_camera)*19 + 16];\n\t\t\tk5 = *parameters[7 + (this_camera)*19 + 17];\n\t\t\tk6 = *parameters[7 + (this_camera)*19 + 18];\n\t\t} break;\n\t\tdefault: {\n\n\t\t}\n\n\t\t}\n\n\t\tfor (int j = 0; j < 3; j++){\n\t\t\tXp[j] = T(threeDpoints[j]);\n\t\t}\n\t\tXp[3] = T(1);\n\n\t\tMatrixMultiply(A_hat_T, Xp, xp, 3, 4, 4, 1);\n\n\t\txp[0] = xp[0]/xp[2];\n\t\txp[1] = xp[1]/xp[2];\n\n\t\tr_sqr= xp[0]*xp[0] + xp[1]*xp[1];\n\n\t\tT numer = (T(1) + k1*r_sqr + k2*r_sqr*r_sqr + k3*r_sqr*r_sqr*r_sqr);\n\t\tT denom = (T(1) + k4*r_sqr + k5*r_sqr*r_sqr + k6*r_sqr*r_sqr*r_sqr);\n\n\t\txpp[0] = xp[0]*numer/denom + T(2)*p1*xp[0]*xp[1] + p2*(r_sqr + T(2)*xp[0]*xp[0]);\n\t\txpp[1] = xp[1]*numer/denom + T(2)*p2*xp[0]*xp[1] + p1*(r_sqr + T(2)*xp[1]*xp[1]);\n\n\t\tT predicted_x = (xpp[0]*K[0] + K[2]);\n\t\tT predicted_y = (xpp[1]*K[4] + K[5]);\n\n\t\tresiduals[0] = w*(predicted_x - T(twoDpoints[0]));\n\t\tresiduals[1] = w*(predicted_y - T(twoDpoints[1]));\n\n\t\treturn true;\n\t}\n\n\tstatic ceres::CostFunction* Create(double* camera_parameters, double* B, double* twoDpoints, double* threeDpoints,\n\t\t\tPARAM_TYPE param_type, COST_TYPE cost_type, int number_points, int number_cameras, int this_camera, double* weighting) {\n\n\n\t\tceres::DynamicAutoDiffCostFunction<RP1_2_multi, 10>* cost_function =\n\t\t\t\tnew ceres::DynamicAutoDiffCostFunction<RP1_2_multi, 10>(\n\t\t\t\t\t\tnew RP1_2_multi(camera_parameters, B, twoDpoints, threeDpoints, param_type, cost_type, number_points, number_cameras, this_camera, weighting));\n\n\n\t\tfor (int i = 0; i <19*(number_cameras) + 7; i++){\n\t\t\tcost_function->AddParameterBlock(1);\n\t\t}\n\t\tcost_function->SetNumResiduals(2);\n\n\t\treturn cost_function;\n\t}\n\n\tdouble* camera_parameters;\n\tdouble* B;\n\tdouble* twoDpoints;\n\tdouble* threeDpoints;\n\n\tPARAM_TYPE param_type;\n\tCOST_TYPE cost_type;\n\tint number_points;\n\tint number_cameras;\n\tint this_camera;\n\tdouble* weighting;\n};\n\n\nstruct RP1_2_multi_extended {\n\tRP1_2_multi_extended(double* camera_parameters, double* B, double* param_copy, double* twoDpoints, double* threeDpoints,\n\t\t\tPARAM_TYPE param_type, COST_TYPE cost_type, SEPARABLE_TYPE sep_type, int number_points,\n\t\t\tint number_cameras, int this_camera, double* weighting):\n\t\t\t\tcamera_parameters(camera_parameters), B(B), param_copy(param_copy), twoDpoints(twoDpoints), threeDpoints(threeDpoints),\n\t\t\t\tparam_type(param_type), cost_type(cost_type), sep_type(sep_type), number_points(number_points),\n\t\t\t\tnumber_cameras(number_cameras), this_camera(this_camera), weighting(weighting){\n\t}\n\n\ttemplate <typename T>\n\t//\tbool operator()(const T* const X,\n\t//\t\t\tconst T* const Z,\n\t//\t\t\tT* residuals) const {\n\tbool operator()(T const* const* parameters,\n\t\t\tT* residuals) const {\n\t\t// X and Z are 7 parameters each, and our unknowns\n\t\t// need to represent these each as matrices\n\t\t// parameters: X0 (7) cam_parameters(12) X1(7) cam_parameters(12) Z(7)\n\n\t\t//The {pitch,roll,yaw} Euler angles are rotations around the {x,y,z} axes, respectively.\n\t\t//They are applied in that same order, so the total rotation R is Rz * Ry * Rx.\n\t\t//char ch;\n\t\t//cout << \"Line 767 \" << endl; //cin >> ch;\n\t\tT XM[16];\n\t\tT ZM[16];\n\n\t\tT X[7];\n\t\tT Z[7];\n\n\t\tT w = T(sqrt(*weighting));\n\n\t\tint break_point = 3;\n\n\t\tif (param_type == Cali_Quaternion){\n\t\t\tbreak_point = 4;\n\t\t}\n\t\tswitch (sep_type){\n\t\tcase rotation_only: {\n\t\t\tfor (int i = 0; i < 7; i++){\n\t\t\t\tif (i < break_point){\n\t\t\t\t\tX[i] = T(*parameters[0*7 + i]);\n\t\t\t\t\tZ[i] = T(*parameters[7 + (this_camera)*19 + i]);\n\t\t\t\t}\telse {\n\t\t\t\t\tZ[i] = T(param_copy[(this_camera + 1)*7 + i]);\n\t\t\t\t\tX[i] = T(param_copy[0*7 + i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}; break;\n\t\tcase translation_only: {\n\t\t\tfor (int i = 0; i < 7; i++){\n\t\t\t\tif (i < break_point){\n\t\t\t\t\tZ[i] = T(param_copy[(this_camera + 1)*7 + i]);\n\t\t\t\t\tX[i] = T(param_copy[0*7 + i]);\n\n\t\t\t\t}\telse {\n\t\t\t\t\tX[i] = T(*parameters[0*7 + i]);\n\t\t\t\t\tZ[i] = T(*parameters[7 + (this_camera)*19 + i]);\n\t\t\t\t}\n\t\t\t}\n\t\t} break;\n\t\tcase simultaneous: {\n\t\t\tfor (int i = 0; i < 7; i++){\n\t\t\t\tX[i] = T(*parameters[0*7 + i]);\n\t\t\t\tZ[i] = T(*parameters[7 + (this_camera)*19 + i]);\n\t\t\t}\n\t\t} break;\n\t\t}\n\n\t\tswitch (param_type){\n\t\tcase Euler: {\n\t\t\tConvert6ParameterEulerAngleRepresentationIntoMatrix(X, XM);\n\t\t\tConvert6ParameterEulerAngleRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\tcase AxisAngle: {\n\t\t\tConvert6ParameterAxisAngleRepresentationIntoMatrix(X, XM);\n\t\t\tConvert6ParameterAxisAngleRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\tcase Cali_Quaternion: {\n\t\t\tConvert7ParameterQuaternionRepresentationIntoMatrix(X, XM);\n\t\t\tConvert7ParameterQuaternionRepresentationIntoMatrix(Z, ZM);\n\t\t}\tbreak;\n\t\t}\n\n\t\tT term0[16];\n\n\n\t\t// ||AX-ZB||\n\t\t// have to convert to T\n\t\tT A_hat_T[16];\n\t\tT BT[16];\n\t\t//T M[16];\n\t\tT K[9];\n\t\tT k1, k2, p1, p2, k3, k4, k5, k6;\n\t\tT r_sqr;\n\n\t\tT Xp[4];\n\t\tT xp[3];\n\t\tT xpp[3];\n\n\t\tfor (int i = 0; i < 16; i++){\n\n\t\t\tBT[i] = T(B[i]);\n\t\t}\n\n\t\tfor (int i = 0; i < 9; i++){\n\t\t\tK[i] = T(0);\n\t\t}\n\n\t\tK[8] = T(1);\n\n\t\t// set up A_hat\n\t\tMatrixMultiply(ZM, BT, term0, 4);\n\t\tMatrixMultiply(term0, XM, A_hat_T, 4);\n\n\n\t\t// copy over parameters\n\t\tswitch (cost_type){\n\t\tcase rp1: {\n\t\t\t// don't use the parameter version for camera cali -- this amtrix is sent all set up for use ....\n\t\t\tK[0] = T(camera_parameters[0]);\n\t\t\tK[2] = T(camera_parameters[1]);\n\t\t\tK[4] = T(camera_parameters[2]);\n\t\t\tK[5] = T(camera_parameters[3]);\n\t\t\tk1 = T(camera_parameters[4]);\n\t\t\tk2 = T(camera_parameters[5]);\n\t\t\tp1 = T(camera_parameters[6]);\n\t\t\tp2 = T(camera_parameters[7]);\n\t\t\tk3 = T(camera_parameters[8]);\n\t\t\tk4 = T(camera_parameters[9]);\n\t\t\tk5 = T(camera_parameters[10]);\n\t\t\tk6 = T(camera_parameters[11]);\n\t\t} break;\n\t\tcase rp2:{\n\t\t\tK[0] = *parameters[7 + (this_camera)*19 + 7];\n\t\t\tK[2] = *parameters[7 + (this_camera)*19 + 8];\n\t\t\tK[4] = *parameters[7 + (this_camera)*19 + 9];\n\t\t\tK[5] = *parameters[7 + (this_camera)*19 + 10];\n\t\t\tk1 = *parameters[7 + (this_camera)*19 + 11];\n\t\t\tk2 = *parameters[7 + (this_camera)*19 + 12];\n\t\t\tp1 = *parameters[7 + (this_camera)*19 + 13];\n\t\t\tp2 = *parameters[7 + (this_camera)*19 + 14];\n\t\t\tk3 = *parameters[7 + (this_camera)*19 + 15];\n\t\t\tk4 = *parameters[7 + (this_camera)*19 + 16];\n\t\t\tk5 = *parameters[7 + (this_camera)*19 + 17];\n\t\t\tk6 = *parameters[7 + (this_camera)*19 + 18];\n\t\t} break;\n\t\tdefault: {\n\n\t\t}\n\n\t\t}\n\n\t\tfor (int j = 0; j < 3; j++){\n\t\t\tXp[j] = T(threeDpoints[j]);\n\t\t}\n\t\tXp[3] = T(1);\n\n\t\tMatrixMultiply(A_hat_T, Xp, xp, 3, 4, 4, 1);\n\n\t\txp[0] = xp[0]/xp[2];\n\t\txp[1] = xp[1]/xp[2];\n\n\t\tr_sqr= xp[0]*xp[0] + xp[1]*xp[1];\n\n\t\tT numer = (T(1) + k1*r_sqr + k2*r_sqr*r_sqr + k3*r_sqr*r_sqr*r_sqr);\n\t\tT denom = (T(1) + k4*r_sqr + k5*r_sqr*r_sqr + k6*r_sqr*r_sqr*r_sqr);\n\n\t\txpp[0] = xp[0]*numer/denom + T(2)*p1*xp[0]*xp[1] + p2*(r_sqr + T(2)*xp[0]*xp[0]);\n\t\txpp[1] = xp[1]*numer/denom + T(2)*p2*xp[0]*xp[1] + p1*(r_sqr + T(2)*xp[1]*xp[1]);\n\n\t\tT predicted_x = (xpp[0]*K[0] + K[2]);\n\t\tT predicted_y = (xpp[1]*K[4] + K[5]);\n\n\t\tresiduals[0] = w*(predicted_x - T(twoDpoints[0]));\n\t\tresiduals[1] = w*(predicted_y - T(twoDpoints[1]));\n\n\t\t//cin >> ch;\n\t\treturn true;\n\t}\n\n\tstatic ceres::CostFunction* Create(double* camera_parameters, double* B, double* param_copy, double* twoDpoints, double* threeDpoints,\n\t\t\tPARAM_TYPE param_type, COST_TYPE cost_type, SEPARABLE_TYPE sep_type, int number_points, int number_cameras, int this_camera, double* weighting) {\n\n\n\t\tceres::DynamicAutoDiffCostFunction<RP1_2_multi_extended, 10>* cost_function =\n\t\t\t\tnew ceres::DynamicAutoDiffCostFunction<RP1_2_multi_extended, 10>(\n\t\t\t\t\t\tnew RP1_2_multi_extended(camera_parameters, B, param_copy, twoDpoints, threeDpoints, param_type, cost_type, sep_type, number_points, number_cameras, this_camera, weighting));\n\n\n\t\tfor (int i = 0; i <19*(number_cameras) + 7; i++){\n\t\t\tcost_function->AddParameterBlock(1);\n\t\t}\n\t\tcost_function->SetNumResiduals(2);\n\n\t\treturn cost_function;\n\t}\n\n\tdouble* camera_parameters;\n\tdouble* B;\n\tdouble* param_copy;\n\tdouble* twoDpoints;\n\tdouble* threeDpoints;\n\n\tPARAM_TYPE param_type;\n\tCOST_TYPE cost_type;\n\tSEPARABLE_TYPE sep_type;\n\tint number_points;\n\tint number_cameras;\n\tint this_camera;\n\tdouble* weighting;\n};\n\n// this is all per camera, we don't need to send out all items at once ....\nstruct ReconstructX {\n\tReconstructX(double* camera_parameters, double* transformation_matrix, double* twoDpoints, int number_points, bool individual, int this_point):\n\t\tcamera_parameters(camera_parameters), transformation_matrix(transformation_matrix), twoDpoints(twoDpoints),\n\t\tnumber_points(number_points), individual(individual), this_point(this_point){\n\t}\n\n\ttemplate <typename T>\n\t//\tbool operator()(const T* const X,\n\t//\t\t\tconst T* const Z,\n\t//\t\t\tT* residuals) const {\n\tbool operator()(T const* const* parameters,\n\t\t\tT* residuals) const {\n\t\t// the parameters are the threed points now\n\n\n\t\t// have to convert to T\n\t\tT A_hat_T[16];\n\n\t\tT K[9];\n\t\tT k1, k2, p1, p2, k3, k4, k5, k6;\n\t\tT r_sqr;\n\t\tT Xp[4];\n\t\tT xp[3];\n\t\tT xpp[3];\n\n\n\t\t// read in transformation matric\n\t\tfor (int i = 0; i < 16; i++){\n\t\t\tA_hat_T[i] = T(transformation_matrix[i]);\n\t\t}\n\n\t\t// Read in camera calibration matrix\n\t\tfor (int i = 0; i < 9; i++){\n\t\t\tK[i] = T(0);\n\t\t}\n\t\tK[8] = T(1);\n\n\t\t// don't use the parameter version for camera cali -- this amtrix is sent all set up for use ....\n\t\tK[0] = T(camera_parameters[0]);\n\t\tK[2] = T(camera_parameters[1]);\n\t\tK[4] = T(camera_parameters[2]);\n\t\tK[5] = T(camera_parameters[3]);\n\t\tk1 = T(camera_parameters[4]);\n\t\tk2 = T(camera_parameters[5]);\n\t\tp1 = T(camera_parameters[6]);\n\t\tp2 = T(camera_parameters[7]);\n\t\tk3 = T(camera_parameters[8]);\n\t\tk4 = T(camera_parameters[9]);\n\t\tk5 = T(camera_parameters[10]);\n\t\tk6 = T(camera_parameters[11]);\n\n\n\t\tif (!individual){\n\t\t\tfor (int i = 0; i < number_points; i++){\n\t\t\t\tfor (int j = 0; j < 3; j++){\n\t\t\t\t\tXp[j] = T(*parameters[3*i + j]);\n\t\t\t\t}\n\t\t\t\tXp[3] = T(1);\n\n\t\t\t\tMatrixMultiply(A_hat_T, Xp, xp, 3, 4, 4, 1);\n\n\t\t\t\txp[0] = xp[0]/xp[2];\n\t\t\t\txp[1] = xp[1]/xp[2];\n\n\t\t\t\tr_sqr= xp[0]*xp[0] + xp[1]*xp[1];\n\n\t\t\t\tT numer = (T(1) + k1*r_sqr + k2*r_sqr*r_sqr + k3*r_sqr*r_sqr*r_sqr);\n\t\t\t\tT denom = (T(1) + k4*r_sqr + k5*r_sqr*r_sqr + k6*r_sqr*r_sqr*r_sqr);\n\n\t\t\t\txpp[0] = xp[0]*numer/denom + T(2)*p1*xp[0]*xp[1] + p2*(r_sqr + T(2)*xp[0]*xp[0]);\n\t\t\t\txpp[1] = xp[1]*numer/denom + T(2)*p2*xp[0]*xp[1] + p1*(r_sqr + T(2)*xp[1]*xp[1]);\n\n\t\t\t\tT predicted_x = (xpp[0]*K[0] + K[2]);\n\t\t\t\tT predicted_y = (xpp[1]*K[4] + K[5]);\n\n\t\t\t\t//if (i < 1){\n\t\t\t\tresiduals[2*i] = (predicted_x - T(twoDpoints[2*i + 0]));\n\t\t\t\tresiduals[2*i + 1] = (predicted_y - T(twoDpoints[2*i + 1]));\n\n\t\t\t}\n\t\t}\telse {\n\t\t\tint i = this_point;\n\n\t\t\tfor (int j = 0; j < 3; j++){\n\t\t\t\tXp[j] = T(*parameters[j]);\n\t\t\t}\n\t\t\tXp[3] = T(1);\n\n\t\t\tMatrixMultiply(A_hat_T, Xp, xp, 3, 4, 4, 1);\n\n\t\t\txp[0] = xp[0]/xp[2];\n\t\t\txp[1] = xp[1]/xp[2];\n\n\t\t\tr_sqr= xp[0]*xp[0] + xp[1]*xp[1];\n\n\t\t\tT numer = (T(1) + k1*r_sqr + k2*r_sqr*r_sqr + k3*r_sqr*r_sqr*r_sqr);\n\t\t\tT denom = (T(1) + k4*r_sqr + k5*r_sqr*r_sqr + k6*r_sqr*r_sqr*r_sqr);\n\n\t\t\txpp[0] = xp[0]*numer/denom + T(2)*p1*xp[0]*xp[1] + p2*(r_sqr + T(2)*xp[0]*xp[0]);\n\t\t\txpp[1] = xp[1]*numer/denom + T(2)*p2*xp[0]*xp[1] + p1*(r_sqr + T(2)*xp[1]*xp[1]);\n\n\t\t\tT predicted_x = (xpp[0]*K[0] + K[2]);\n\t\t\tT predicted_y = (xpp[1]*K[4] + K[5]);\n\n\t\t\tresiduals[0] = (predicted_x - T(twoDpoints[2*i + 0]));\n\t\t\tresiduals[1] = (predicted_y - T(twoDpoints[2*i + 1]));\n\t\t}\n\n\n\t\treturn true;\n\t}\n\n\tstatic ceres::CostFunction* Create(double* camera_parameters, double* transformation_matrix, double* twoDpoints, int number_points) {\n\n\n\t\tceres::DynamicAutoDiffCostFunction<ReconstructX, 3>* cost_function =\n\t\t\t\tnew ceres::DynamicAutoDiffCostFunction<ReconstructX, 3>(\n\t\t\t\t\t\tnew ReconstructX(camera_parameters, transformation_matrix, twoDpoints, number_points, false, 0 ));\n\n\n\t\tfor (int i = 0; i <3*number_points; i++){\n\t\t\tcost_function->AddParameterBlock(1);\n\t\t}\n\t\tcost_function->SetNumResiduals(2*number_points);\n\n\t\treturn cost_function;\n\t}\n\n\tstatic ceres::CostFunction* CreateID(double* camera_parameters, double* transformation_matrix, double* twoDpoints, int number_points, int this_point) {\n\n\n\t\tceres::DynamicAutoDiffCostFunction<ReconstructX, 3>* cost_function =\n\t\t\t\tnew ceres::DynamicAutoDiffCostFunction<ReconstructX, 3>(\n\t\t\t\t\t\tnew ReconstructX(camera_parameters, transformation_matrix, twoDpoints, number_points, true, this_point));\n\n\n\t\tfor (int i = 0; i <3; i++){\n\t\t\tcost_function->AddParameterBlock(1);\n\t\t}\n\t\tcost_function->SetNumResiduals(2);\n\n\t\treturn cost_function;\n\t}\n\n\t// we need the camera parameters, transformation matrices (one per camera), and twoDpoints for each camera that can see the pattern.\n\t// for now, solve all together as one big cost function\n\t// result is the three d points for the pattern.\n\tdouble* camera_parameters;\n\tdouble* transformation_matrix;\n\tdouble* twoDpoints;\n\n\tint number_points;\n\tbool individual;\n\tint this_point;\n\n};\n\n\n\n\nvoid CF1_2_one_camera(vector< vector<Matrix4d> >& As, vector<Matrix4d>& Bs, double* x, double* z, std::ofstream& out, PARAM_TYPE param_type, COST_TYPE cost_type);\n\nvoid CF1_2_multi_camera(vector< vector<MatrixXd> >& As, vector<Matrix4d>& Bs, double* x, std::ofstream& out, PARAM_TYPE param_type, COST_TYPE cost_type);\n\nvoid CF1_2_multi_camera_separable(vector< vector<MatrixXd> >& As, vector<Matrix4d>& Bs, double* x, std::ofstream& out, PARAM_TYPE param_type, COST_TYPE cost_type, SEPARABLE_TYPE sep_type);\n\nvoid RP1_2_multi_camera(vector<CaliObjectOpenCV2>& COs, vector<Matrix4d>& Bs, double* camera_params, double* x,\n\t\tstd::ofstream& out, PARAM_TYPE param_type, COST_TYPE cost_type);\n\nvoid RP1_2_multi_camera_sparse(vector<CaliObjectOpenCV2>& COs, vector<Matrix4d>& Bs, double* camera_params, double* x,\n\t\tstd::ofstream& out, PARAM_TYPE param_type, COST_TYPE cost_type);\n\nvoid RP1_2_multi_camera_sparse_seperable(vector<CaliObjectOpenCV2>& COs, vector<Matrix4d>& Bs, double* camera_params, double* x,\n\t\tstd::ofstream& out, PARAM_TYPE param_type, COST_TYPE cost_type, SEPARABLE_TYPE sep_type);\n\nvoid CopyFromCalibration(vector<CaliObjectOpenCV2>& COs, double* camera_params);\n\nvoid CopyToCalibration(vector<CaliObjectOpenCV2>& COs, double* camera_parameters);\n\nvoid ReconstructXFunction(vector<CaliObjectOpenCV2>& COs, vector<Matrix4d>& Bs, Matrix4d& X, vector<Matrix4d>& Zs, double* threeDpoints, vector<double>& reprojection_errors,\n\t\tstd::ofstream& out);\n\ndouble ComputeSummedSquaredDistanceBetweenSets(double* set0, double* set1, int number_points);\n\nvoid Initialize3DPoints(vector<CaliObjectOpenCV2>& COs, double* threeDpoints, int number_points);\n\nvoid ReconstructXFunctionIndividuals(vector<CaliObjectOpenCV2>& COs, vector<Matrix4d>& Bs, Matrix4d& X, vector<Matrix4d>& Zs, double* threeDpoints, vector<double>& reprojection_errors,\n\t\tstd::ofstream& out);\n\n#endif /* COSTFUNCTIONS_HPP_ */\n", "meta": {"hexsha": "6144b0dc9c83ac43409a5e886c7ce352a50f2374", "size": 32309, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "code_src/CostFunctions.hpp", "max_stars_repo_name": "kyuhyoung/RWHEC-exp-2019", "max_stars_repo_head_hexsha": "6dfda0ee9fa85d5cffa79db94255eea64a7376da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2018-01-17T14:50:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T03:08:40.000Z", "max_issues_repo_path": "code_src/CostFunctions.hpp", "max_issues_repo_name": "kyuhyoung/RWHEC-exp-2019", "max_issues_repo_head_hexsha": "6dfda0ee9fa85d5cffa79db94255eea64a7376da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-01-20T13:33:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-16T03:55:43.000Z", "max_forks_repo_path": "code_src/CostFunctions.hpp", "max_forks_repo_name": "kyuhyoung/RWHEC-exp-2019", "max_forks_repo_head_hexsha": "6dfda0ee9fa85d5cffa79db94255eea64a7376da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2018-01-19T03:34:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T15:38:23.000Z", "avg_line_length": 26.7458609272, "max_line_length": 190, "alphanum_fraction": 0.6289578755, "num_tokens": 11230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6757646140788308, "lm_q1q2_score": 0.5359529370255554}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <stan/math/prim/mat.hpp>\n#include <math/prim/mat/prob/vector_rng_test_helper.hpp>\n#include <math/prim/mat/prob/VectorIntRNGTestRig.hpp>\n#include <limits>\n#include <vector>\n\nclass BernoulliTestRig : public VectorIntRNGTestRig {\n public:\n  BernoulliTestRig()\n      : VectorIntRNGTestRig(10000, 10, {0, 1}, {0.0, 0.1, 0.2, 0.7, 1.0},\n                            {0, 1}, {-2.0, -0.5, 1.1, 2.0}, {-2, -1, 2}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& theta, const T2&, const T3&,\n                        T_rng& rng) const {\n    return stan::math::bernoulli_rng(theta, rng);\n  }\n\n  template <typename T1>\n  double pmf(int y, T1 theta, double, double) const {\n    return std::exp(stan::math::bernoulli_lpmf(y, theta));\n  }\n};\n\nTEST(ProbDistributionsBernoulli, errorCheck) {\n  check_dist_throws_all_types(BernoulliTestRig());\n}\n\nTEST(ProbDistributionsBernoulli, distributionCheck) {\n  check_counts_real(BernoulliTestRig());\n}\n", "meta": {"hexsha": "4f3c9f6e2f1b74e3a5262ff9431e105ccda49582", "size": 1100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/mat/prob/bernoulli_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/prim/mat/prob/bernoulli_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/prim/mat/prob/bernoulli_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": 31.4285714286, "max_line_length": 75, "alphanum_fraction": 0.6827272727, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6757646010190477, "lm_q1q2_score": 0.5359529332770527}}
{"text": "//-----------------------------------------------------------------------------\n// Copyright (c) 2015-2018 Benjamin Buch\n//\n// https://github.com/bebuch/mitrax\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n//-----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE mitrax gauss_newton_algorithm\n#include <boost/test/unit_test.hpp>\n\n#include <mitrax/gauss_newton_algorithm.hpp>\n#include <mitrax/io/matrix.hpp>\n\n#include <iostream>\n\n\nusing boost::typeindex::type_id;\nusing boost::typeindex::type_id_runtime;\nusing namespace mitrax;\nusing namespace mitrax::literals;\n\n\ntemplate < typename T >\nauto rt_id(T&& v){\n\treturn type_id_runtime(static_cast< T&& >(v));\n}\n\ntemplate < typename T >\nauto const id = type_id< T >();\n\n\nBOOST_AUTO_TEST_SUITE(suite_gauss_newton_algorithm)\n\n\n// BOOST_AUTO_TEST_CASE(test_gauss_newton_algorithm_linear_fit){\n// \tauto f = [](\n// \t\t\traw_col_vector< double, 2 > const& p,\n// \t\t\tstd::tuple< double, double > const& v\n// \t\t){\n// \t\t\treturn std::get< 1 >(v) * p[0] + p[1] - std::get< 0 >(v);\n// \t\t};\n//\n// \tboost::container::vector< std::tuple< double, double > > data{\n// \t\tstd::make_tuple(2., 2.),\n// \t\tstd::make_tuple(3., 3.),\n// \t\tstd::make_tuple(4., 4.),\n// \t\tstd::make_tuple(5., 5.)\n// \t};\n//\n// \tconstexpr auto start = make_vector< double >(2_RS, 1);\n//\n// \tstd::cout << \"gauss-newton:\" << std::endl;\n// \tauto res = gauss_newton_algorithm(f, start, 1e-10, data);\n// \tstd::cout << res << std::endl;\n// }\n//\n// BOOST_AUTO_TEST_CASE(test_gauss_levenberg_marquardt_linear_fit){\n// \tauto f = [](\n// \t\t\traw_col_vector< double, 2 > const& p,\n// \t\t\tstd::tuple< double, double > const& v\n// \t\t){\n// \t\t\treturn std::get< 1 >(v) * p[0] + p[1] - std::get< 0 >(v);\n// \t\t};\n//\n// \tboost::container::vector< std::tuple< double, double > > data{\n// \t\tstd::make_tuple(2., 2.),\n// \t\tstd::make_tuple(3., 3.),\n// \t\tstd::make_tuple(4., 4.),\n// \t\tstd::make_tuple(5., 5.)\n// \t};\n//\n// \tconstexpr auto start = make_vector< double >(2_RS, 1);\n//\n// \tstd::cout << \"levenberg-marquardt:\" << std::endl;\n// \tauto res = levenberg_marquardt_algorithm(\n// \t\tf, start, 1e-10, 1., 0.3, 0.9, data\n// \t);\n// \tstd::cout << res << std::endl;\n// }\n//\n//\n// BOOST_AUTO_TEST_CASE(test_gauss_newton_algorithm_cycle_fit){\n// \tusing value_type = raw_col_vector< double, 2 >;\n//\n// \tauto f = [](\n// \t\t\traw_col_vector< double, 3 > const& p,\n// \t\t\tstd::tuple< value_type > const& v\n// \t\t){\n// \t\t\tauto x = std::get< 0 >(v)[0];\n// \t\t\tauto y = std::get< 0 >(v)[1];\n// \t\t\tauto px = p[0];\n// \t\t\tauto py = p[1];\n// \t\t\tauto pr = p[2];\n// \t\t\tauto xd = x - px;\n// \t\t\tauto yd = y - py;\n// \t\t\treturn std::sqrt(xd * xd + yd * yd) - pr;\n// \t\t};\n//\n// \tboost::container::vector< std::tuple< value_type > > data{\n// \t\tstd::make_tuple(make_vector< double >(2_RS, {2, 2})),\n// \t\tstd::make_tuple(make_vector< double >(2_RS, {4, 4})),\n// \t\tstd::make_tuple(make_vector< double >(2_RS, {2, 4})),\n// \t\tstd::make_tuple(make_vector< double >(2_RS, {4, 2}))\n// \t};\n//\n// \tconstexpr auto start = make_vector< double >(3_RS, 1);\n//\n// \tstd::cout << \"gauss-newton:\" << std::endl;\n// \tauto res = gauss_newton_algorithm(f, start, 1e-10, data);\n// \tstd::cout << res << std::endl;\n// }\n//\n// BOOST_AUTO_TEST_CASE(test_gauss_levenberg_marquardt_cycle_fit){\n// \tusing value_type = raw_col_vector< double, 2 >;\n//\n// \tauto f = [](\n// \t\t\traw_col_vector< double, 3 > const& p,\n// \t\t\tstd::tuple< value_type > const& v\n// \t\t){\n// \t\t\tauto x = std::get< 0 >(v)[0];\n// \t\t\tauto y = std::get< 0 >(v)[1];\n// \t\t\tauto px = p[0];\n// \t\t\tauto py = p[1];\n// \t\t\tauto pr = p[2];\n// \t\t\tauto xd = x - px;\n// \t\t\tauto yd = y - py;\n// // \t\t\treturn std::sqrt(xd * xd + yd * yd) - pr;\n// \t\t\treturn xd * xd + yd * yd - pr * pr;\n// \t\t};\n//\n// \tboost::container::vector< std::tuple< value_type > > data{\n// \t\tstd::make_tuple(make_vector< double >(2_RS, {2, 2})),\n// \t\tstd::make_tuple(make_vector< double >(2_RS, {4, 4})),\n// \t\tstd::make_tuple(make_vector< double >(2_RS, {2, 4})),\n// \t\tstd::make_tuple(make_vector< double >(2_RS, {4, 2}))\n// \t};\n//\n// \tconstexpr auto start = make_vector< double >(3_RS, 1);\n//\n// \tstd::cout << \"levenberg-marquardt:\" << std::endl;\n// \tauto res = levenberg_marquardt_algorithm(\n// \t\tf, start, 1e-10, 1., 0.1, 0.9, data\n// \t);\n// \tstd::cout << res << std::endl;\n//\n// \tstd::cout << f(res, data[0]) << std::endl;\n// \tstd::cout << f(res, data[1]) << std::endl;\n// \tstd::cout << f(res, data[2]) << std::endl;\n// \tstd::cout << f(res, data[3]) << std::endl;\n// }\n\n// BOOST_AUTO_TEST_CASE(test_gauss_newton_algorithm){\n// \tconstexpr auto start = make_vector< double >(8_RS, 1);\n//\n// \tauto f = [](\n// \t\t\traw_col_vector< double, 8 > const& p,\n// \t\t\traw_col_vector< double, 3 > const& y,\n// \t\t\traw_col_vector< double, 3 > const& v\n// \t\t){\n// \t\t\tauto const m = make_matrix< double >(3_DS, {\n// \t\t\t\t{p[0], p[1], p[2]},\n// \t\t\t\t{p[3], p[4], p[5]},\n// \t\t\t\t{p[6], p[7], 1}\n// \t\t\t});\n// \t\t\tauto r = m * v - y;\n// \t\t\tauto r2 = element_multiplies(r, r);\n// \t\t\tdouble res = 1;\n// \t\t\tfor(auto v: r2) res += v;\n// \t\t\treturn res;\n// \t\t};\n//\n// \tusing value_type = raw_col_vector< double, 3 >;\n//\n// \tboost::container::vector< std::pair< value_type, value_type > > data{\n// \t\tstd::make_tuple(\n// \t\t\tmake_vector< double >(3_RS, {5, 5, 1}),\n// \t\t\tmake_vector< double >(3_RS, {6, 6, 1})\n// \t\t),\n// \t\tstd::make_tuple(\n// \t\t\tmake_vector< double >(3_RS, {5, 3, 1}),\n// \t\t\tmake_vector< double >(3_RS, {6, 4, 1})\n// \t\t),\n// \t\tstd::make_tuple(\n// \t\t\tmake_vector< double >(3_RS, {3, 5, 1}),\n// \t\t\tmake_vector< double >(3_RS, {4, 6, 1})\n// \t\t),\n// \t\tstd::make_tuple(\n// \t\t\tmake_vector< double >(3_RS, {3, 3, 1}),\n// \t\t\tmake_vector< double >(3_RS, {4, 4, 1})\n// \t\t)\n// \t};\n//\n// \t{\n// \t\tusing namespace mitrax;\n// \t\tusing namespace mitrax::literals;\n//\n// \t\tauto x0 = data[0].second[0];\n// \t\tauto y0 = data[0].second[1];\n// \t\tauto x1 = data[1].second[0];\n// \t\tauto y1 = data[1].second[1];\n// \t\tauto x2 = data[2].second[0];\n// \t\tauto y2 = data[2].second[1];\n// \t\tauto x3 = data[3].second[0];\n// \t\tauto y3 = data[3].second[1];\n//\n// \t\tdouble tx0 = data[0].first[0];\n// \t\tdouble ty0 = data[0].first[1];\n// \t\tdouble tx1 = data[1].first[0];\n// \t\tdouble ty1 = data[1].first[1];\n// \t\tdouble tx2 = data[2].first[0];\n// \t\tdouble ty2 = data[2].first[1];\n// \t\tdouble tx3 = data[3].first[0];\n// \t\tdouble ty3 = data[3].first[1];\n//\n// \t\tauto b = make_matrix< double >(9_CS, 9_RS, {\n// \t\t\t{x0, y0, 1,  0,  0, 0, -tx0 * x0, -tx0 * y0, -tx0},\n// \t\t\t{ 0,  0, 0, x0, y0, 1, -ty0 * x0, -ty0 * y0, -ty0},\n// \t\t\t{x1, y1, 1,  0,  0, 0, -tx1 * x1, -tx1 * y1, -tx1},\n// \t\t\t{ 0,  0, 0, x1, y1, 1, -ty1 * x1, -ty1 * y1, -ty1},\n// \t\t\t{x2, y2, 1,  0,  0, 0, -tx2 * x2, -tx2 * y2, -tx2},\n// \t\t\t{ 0,  0, 0, x2, y2, 1, -ty2 * x2, -ty2 * y2, -ty2},\n// \t\t\t{x3, y3, 1,  0,  0, 0, -tx3 * x3, -tx3 * y3, -tx3},\n// \t\t\t{ 0,  0, 0, x3, y3, 1, -ty3 * x3, -ty3 * y3, -ty3},\n// \t\t\t{ 0,  0, 0,  0,  0, 0,         0,         0,    0}\n// \t\t});\n//\n// \t\tauto vec = matrix_kernel(b);\n//\n// \t\tauto res = make_matrix< double >(3_CS, 3_RS, {\n// \t\t\t{vec[0], vec[1], vec[2]},\n// \t\t\t{vec[3], vec[4], vec[5]},\n// \t\t\t{vec[6], vec[7], vec[8]}\n// \t\t});\n//\n// \t\tstd::cout << \"direkt:\" << std::endl;\n// \t\tstd::cout << res << std::endl;\n// \t}\n//\n// \tstd::cout << \"gauss-newton:\" << std::endl;\n// \tauto res = gauss_newton_algorithm(f, start, 0.00000000001, data);\n// \tstd::cout << res << std::endl;\n// // \tstd::cout << res << std::endl;\n// }\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4d9091f3badadda74d68d67107d7f830c122387b", "size": 7484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gauss_newton_algorithm.cpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/gauss_newton_algorithm.cpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/gauss_newton_algorithm.cpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1774193548, "max_line_length": 79, "alphanum_fraction": 0.53808124, "num_tokens": 2788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5359529266677636}}
{"text": "/*\n * hierarchical_optimizer2d.h\n *\n *  Created on: Dec 18, 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#pragma once\n\n// stdlib\n#include <vector>\n\n// libraries\n#include <Eigen/Eigen>\n\n// local\n#include \"../../math/typedefs.hpp\"\n#include \"../../math/container_traits.hpp\"\n\nnamespace eig = Eigen;\n\nnamespace nonrigid_optimization {\nnamespace hierarchical {\n\n// not thread-safe\n/**\n * Hierarchical non-rigid optimizer that constructs pyramids of the initial live (source) TSDF and canonical (target)\n * TSDF fields, and then constructs composite warp vectors level-by-level, upsampling the warp field at each new level.\n */\ntemplate<typename ScalarContainer, typename VectorContainer>\nclass Optimizer {\npublic:\n\ttypedef typename VectorContainer::Scalar VectorType;\n\ttypedef typename math::ContainerWrapper<ScalarContainer>::Coordinates Coordinates;\n\tenum ResamplingStrategy {\n\t\tNEAREST_AND_AVERAGE = 0,\n\t\tLINEAR = 1\n\t};\n\tOptimizer(\n\t\t\tbool tikhonov_term_enabled = true,\n\t\t\tbool gradient_kernel_enabled = true,\n\n\t\t\tint maximum_chunk_size = 8,\n\t\t\tfloat rate = 0.1f,\n\t\t\tint maximum_iteration_count = 100,\n\t\t\tfloat maximum_warp_update_threshold = 0.001f,\n\n\t\t\tfloat data_term_amplifier = 1.0f,\n\t\t\tfloat tikhonov_strength = 0.2f,\n\t\t\teig::VectorXf kernel = eig::VectorXf(0),\n\n\t\t\tResamplingStrategy resampling_strategy = ResamplingStrategy::NEAREST_AND_AVERAGE\n\t);\n\n\tvirtual ~Optimizer() = default;\n\n\tvirtual VectorContainer optimize(const ScalarContainer& canonical_field, const ScalarContainer& live_field);\n\nprotected:\n\t// parameters\n\tconst bool tikhonov_term_enabled = true;\n\tconst bool gradient_kernel_enabled = true;\n\tconst int maximum_chunk_size = 8;\n\tconst float rate = 0.1f;\n\tconst int maximum_iteration_count = 100;\n\tconst float maximum_warp_update_threshold = 0.001f;\n\tconst float data_term_amplifier = 1.0f;\n\tconst float tikhonov_strength = 0.2f;\n\tconst eig::VectorXf kernel_1d = eig::VectorXf(0);\n\tconst ResamplingStrategy resampling_strategy;\n\n\tvirtual void optimize_level(\n\t\t\tVectorContainer& warp_field,\n\t\t\tconst ScalarContainer& canonical_pyramid_level,\n\t\t\tconst ScalarContainer& live_pyramid_level,\n\t\t\tconst VectorContainer& live_gradient_level);\n\n\tvirtual void optimize_iteration(\n\t\t\tVectorContainer& gradient,\n\t\t\tVectorContainer& warp_field,\n\t\t\tScalarContainer& diff,\n\t\t\tVectorContainer& data_gradient,\n\t\t\tVectorContainer& tikhonov_gradient,\n\t\t\tfloat& maximum_warp_update_length,\n\t\t\tconst ScalarContainer& canonical_pyramid_level,\n\t\t\tconst ScalarContainer& live_pyramid_level,\n\t\t\tconst VectorContainer& live_gradient_level);\n\tinline int get_current_hierarchy_level() { return this->current_hierarchy_level; }\n\tinline int get_current_iteration() { return this->current_iteration; }\n\nprivate:\n\t// optimization state variables\n\tint current_hierarchy_level = 0;\n\tint current_iteration = 0;\n\tbool termination_conditions_reached(float maximum_warp_update_length, int completed_iteration_count);\n};\n\ntypedef Optimizer<Eigen::MatrixXf, math::MatrixXv2f> Optimizer2d;\n\n} /* namespace hierarchical */\n} /* namespace nonrigid_optimization */\n", "meta": {"hexsha": "c22e971bb1fcc8b61a8225e8c7b6ba2a025abe10", "size": 3646, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/nonrigid_optimization/hierarchical/optimizer.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/nonrigid_optimization/hierarchical/optimizer.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/nonrigid_optimization/hierarchical/optimizer.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": 31.9824561404, "max_line_length": 119, "alphanum_fraction": 0.7701590784, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5359529214888675}}
{"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//[point_type\r\n//` Examine the point type of a multi_polygon\r\n\r\n#include <iostream>\r\n#include <typeinfo>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/multi/geometries/multi_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    typedef boost::geometry::model::multi_polygon<polygon_type> mp_type;\r\n\r\n    typedef boost::geometry::point_type<mp_type>::type ptype;\r\n\r\n    std::cout << \"point type: \" << typeid(ptype).name() << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[point_type_output\r\n/*`\r\nOutput (in MSVC):\r\n[pre\r\npoint type: class boost::geometry::model::d2::point_xy<double,struct boost::geometry::cs::cartesian>\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "78b8f3c5b8d2d7f51dd58cc2ba3a4ccf9eebb02c", "size": 1214, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/core/point_type.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/point_type.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/point_type.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": 26.9777777778, "max_line_length": 101, "alphanum_fraction": 0.7034596376, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5359149712043008}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 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 analyticpdfhestonengine.cpp\n    \\brief Analytic engine for arbitrary European payoffs under the Heston model\n*/\n\n#include <ql/math/functional.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/experimental/exoticoptions/analyticpdfhestonengine.hpp>\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n\n#include <boost/bind.hpp>\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\n#include <cmath>\n\nnamespace QuantLib {\n\n    namespace {\n        struct Hestonp {\n            Real v0, kappa, theta, sigma, rho;\n        };\n\n        std::complex<Real> gamma(const Hestonp& p, Real p_x) {\n            return std::complex<Real>(p.kappa, p.rho*p.sigma*p_x);\n        }\n\n        std::complex<Real> omega(const Hestonp& p, Real p_x) {\n           const std::complex<Real> g = gamma(p, p_x);\n           return std::sqrt(g*g\n                  + p.sigma*p.sigma*std::complex<Real>(p_x*p_x, -p_x));\n        }\n\n        std::complex<Real> cpx_pv(const Hestonp& p, Real p_x, Real x, Time t){\n            const Real sigma2 = p.sigma*p.sigma;\n            const std::complex<Real> g = gamma(p, p_x);\n            const std::complex<Real> o = omega(p, p_x);\n\n            return\n                std::exp(std::complex<Real>(0.0, p_x*x)\n                         - p.v0*std::complex<Real>(p_x*p_x, -p_x)\n                           /(g+o*std::cosh(0.5*o*t)/std::sinh(0.5*o*t))\n                         + p.kappa*g*p.theta*t/sigma2)\n                /std::pow(std::cosh(0.5*o*t)+g/o*std::sinh(0.5*o*t),\n                          2.0*p.kappa*p.theta/sigma2);\n        }\n\n        Real zero_pv(const Hestonp& p, Real p_x, Real x, Time t){\n            return std::abs(cpx_pv(p, p_x, x, t))-QL_EPSILON;\n        }\n\n        Real pv(const Hestonp& p, Real p_x, Real x, Time t){\n            return cpx_pv(p, p_x, x, t).real();\n        }\n    }\n\n    AnalyticPDFHestonEngine::AnalyticPDFHestonEngine(\n        const boost::shared_ptr<HestonModel>& model,\n        Real eps, Size nIterations, Real xMax)\n    : eps_(eps), xMax_(xMax),\n      nIterations_(nIterations),\n      model_(model) {\n    }\n\n    void AnalyticPDFHestonEngine::calculate() const {\n        // this is an European option pricer\n        QL_REQUIRE(arguments_.exercise->type() == Exercise::European,\n                   \"not an European option\");\n\n        const boost::shared_ptr<HestonProcess>& process = model_->process();\n\n        const Time t = process->time(arguments_.exercise->lastDate());\n\n        const Real xMax = 10 * std::sqrt(process->theta()*t\n        \t+ (process->v0() - process->theta())*(1-std::exp(-process->kappa()*t)));\n\n        results_.value = GaussLobattoIntegral(nIterations_, eps_)\n            (boost::bind(&AnalyticPDFHestonEngine::weightedPayoff, this,_1, t),\n             -xMax, xMax);\n    }\n\n    Real AnalyticPDFHestonEngine::Pv(Real s_0, Real s_t, Time t) const {\n        const boost::shared_ptr<HestonProcess>& process = model_->process();\n        const DiscountFactor d=  process->riskFreeRate()->discount(t)\n                               / process->dividendYield()->discount(t);\n        const Real x_t = std::log(d * s_t/s_0);\n\n        return Pv(x_t, t);\n    }\n\n\n    Real AnalyticPDFHestonEngine::Pv(Real x_t, Time t) const {\n        const Hestonp p = { model_->v0(),\n                            model_->kappa(),\n                            model_->theta(),\n                            model_->sigma(),\n                            model_->rho() };\n        Real xMax = (xMax_ != Null<Real>()) ? xMax_\n            : Brent().solve(boost::bind(&zero_pv, p, _1, x_t, t),\n                            0.01, 1.0, 1.0);\n\n        return GaussLobattoIntegral(nIterations_, 0.1*eps_)\n               (boost::bind(&pv, p, _1, x_t, t), -xMax, xMax)/M_TWOPI;\n    }\n\n    Real AnalyticPDFHestonEngine::weightedPayoff(Real x_t, Time t) const {\n        const boost::shared_ptr<HestonProcess>& process = model_->process();\n\n        const Real s_0 = process->s0()->value();\n        const DiscountFactor rD = process->riskFreeRate()->discount(t);\n        const DiscountFactor dD = process->dividendYield()->discount(t);\n\n        const Real s_t = s_0*std::exp(x_t)*dD/rD;\n        const Real payoff = (*arguments_.payoff)(s_t);\n\n        return (payoff != 0.0) ? payoff*Pv(x_t, t)*rD : 0.0;\n    }\n}\n\n", "meta": {"hexsha": "295b60145366ae563713b401323a80a3009c784b", "size": 5298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLib/ql/experimental/exoticoptions/analyticpdfhestonengine.cpp", "max_stars_repo_name": "frannuca/quantlib", "max_stars_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "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": "QuantLib/ql/experimental/exoticoptions/analyticpdfhestonengine.cpp", "max_issues_repo_name": "frannuca/quantlib", "max_issues_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/ql/experimental/exoticoptions/analyticpdfhestonengine.cpp", "max_forks_repo_name": "frannuca/quantlib", "max_forks_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-24T04:54:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T04:54:18.000Z", "avg_line_length": 36.5379310345, "max_line_length": 87, "alphanum_fraction": 0.5955077388, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439707, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5358690975268529}}
{"text": "//\n//  Hubbard2D.hpp\n//\n//  Created by ryle on 1/15/17.\n//  Copyright \u00a9 2017 R L. All rights reserved.\n//\n\n#ifndef Hubbard2D_hpp\n#define Hubbard2D_hpp\n\n#include <stdio.h>\n#include <bitset>\n#include <complex>\n#include <fstream>\n#include <vector>\n#include <map>\n#include <unordered_map>\n#include <Eigen/SparseCore>\n#include <Eigen/Core>\n//**************************************c\n#define BASISSIZE 32 //(4*4)*2\n//**************************************c\ntypedef std::bitset<BASISSIZE> tbitset;\ntypedef tbitset lattice_t;\ntypedef std::vector<lattice_t> basis_t;\ntypedef std::complex<double> Complex;\n\ntypedef Eigen::SparseMatrix<double,Eigen::RowMajor,long> SpMat;\n\n///basis mapping\ntypedef std::unordered_map<lattice_t,unsigned long> dict_t;\ntypedef Eigen::MatrixXd rotation_t;\n\nEIGEN_STATIC_ASSERT(BASISSIZE%2==0, BASISSIZE_NEEDS_TO_BE_EVEN);\n\nclass HubbardModel2D{\nprotected:\n    int Lx,Ly,nUp,nDown,numParam;\n    double t,U;\n    basis_t basis;\n    \n    //Hamiltonian\n    SpMat H;\n    ///make a map of basis bitset to index\n    dict_t indexMap;\n\n    /// Hoping/Neighbor Matrix; should include -t,-t' etc\n    // TODO:allow for t' values that aren't 1\n    Eigen::MatrixXd HH;\n\n    //stores neighbors, currently unused beyond HH generation\n    std::vector<std::vector<int> > neighbors; \n    \npublic:\n    HubbardModel2D(int nUp_in,int nDown_in,double t_in, double U_in):\n    nUp(nUp_in),nDown(nDown_in),t(t_in),U(U_in){\n      init();};\n    \n    //setup matrices\n    void init();\n    ///construct a basis given Lx,Ly, nUp, nDown\n    void makeBasis();\n    ///build matrix given init bonds\n    void buildHubbard2D();\n    \n    //getter functions\n    \n    ///getter for the internal basis\n    const basis_t *getBasis() {return &basis;}\n    ///getter for last made Hamiltonian\n    SpMat *getH() {return &H;}\n\n    ///given a basis element return index\n    unsigned long getState(const lattice_t &psi){return indexMap[psi];}\n    \n};\n\n#endif /* Hubbard2D_hpp */\n", "meta": {"hexsha": "1c387f4d96ed5a4b0ea78e4257400874bf57ea2c", "size": 1947, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Hubbard2D.hpp", "max_stars_repo_name": "qftphys/A-Slow-Exact-Diagonalization-for-the-1D-2D-Hubbard-Model", "max_stars_repo_head_hexsha": "c8352681036e93fb83a56374c639075fea72e3af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-05-26T13:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T06:58:54.000Z", "max_issues_repo_path": "Hubbard2D.hpp", "max_issues_repo_name": "qftphys/A-Slow-Exact-Diagonalization-for-the-1D-2D-Hubbard-Model", "max_issues_repo_head_hexsha": "c8352681036e93fb83a56374c639075fea72e3af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hubbard2D.hpp", "max_forks_repo_name": "qftphys/A-Slow-Exact-Diagonalization-for-the-1D-2D-Hubbard-Model", "max_forks_repo_head_hexsha": "c8352681036e93fb83a56374c639075fea72e3af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-08-08T04:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-13T08:13:10.000Z", "avg_line_length": 24.6455696203, "max_line_length": 71, "alphanum_fraction": 0.6610169492, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5358342129544422}}
{"text": "/**\n * \\file SecondOrderFilter.hxx\n * @see http://abvolt.com/research/publications2.htm\n * @see http://www.music.mcgill.ca/~ich/classes/FiltersChap2.pdf for the allpass filter\n */\n\n#include \"SecondOrderFilter.h\"\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cassert>\n#include <cmath>\n\nnamespace ATK\n{\n  template <typename DataType_>\n  SecondOrderCoreCoefficients<DataType_>::SecondOrderCoreCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels, nb_channels)\n  {\n  }\n\n  template <typename DataType_>\n  SecondOrderBaseCoefficients<DataType_>::SecondOrderBaseCoefficients(gsl::index nb_channels)\n    : Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType_>\n  void SecondOrderBaseCoefficients<DataType_>::setup()\n  {\n    Parent::setup();\n\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n  }\n\n  template <typename DataType_>\n  void SecondOrderBaseCoefficients<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 SecondOrderBaseCoefficients<DataType_>::CoeffDataType  SecondOrderBaseCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n\n  template<typename DataType_>\n  SecondOrderBandPassCoefficients<DataType_>::SecondOrderBandPassCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType_>\n  void SecondOrderBandPassCoefficients<DataType_>::setup()\n  {\n    Parent::setup();\n    \n    CoeffDataType c = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\n    CoeffDataType d = (1 + std::sqrt(static_cast<CoeffDataType>(2.)) * c + c * c);\n    CoeffDataType Q_inv = 1 / Q;\n    \n    coefficients_in[2] = Q_inv * c / d;\n    coefficients_in[1] = 0;\n    coefficients_in[0] = -Q_inv * c / d;\n    coefficients_out[1] = - 2 * (c * c - 1) / d;\n    coefficients_out[0] = - (1 - std::sqrt(static_cast<CoeffDataType>(2.)) * c + c * c) / d;\n  }\n  \n  template <typename DataType_>\n  void SecondOrderBandPassCoefficients<DataType_>::set_Q(CoeffDataType Q)\n  {\n    if(Q <= 0)\n    {\n      throw std::out_of_range(\"Q can't be negative\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  typename SecondOrderBandPassCoefficients<DataType_>::CoeffDataType SecondOrderBandPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType_>\n  SecondOrderLowPassCoefficients<DataType_>::SecondOrderLowPassCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType_>\n  void SecondOrderLowPassCoefficients<DataType_>::setup()\n  {\n    Parent::setup();\n\n    CoeffDataType c = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\n    CoeffDataType d = (1 + std::sqrt(static_cast<CoeffDataType>(2.)) * c + c * c);\n    \n    coefficients_in[2] = c * c / d;\n    coefficients_in[1] = 2 * c * c / d;\n    coefficients_in[0] = c * c / d;\n    coefficients_out[1] = - 2 * (c * c - 1) / d;\n    coefficients_out[0] = - (1 - std::sqrt(static_cast<CoeffDataType>(2.)) * c + c * c) / d;\n  }\n\n  template<typename DataType_>\n  SecondOrderHighPassCoefficients<DataType_>::SecondOrderHighPassCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType_>\n  void SecondOrderHighPassCoefficients<DataType_>::setup()\n  {\n    Parent::setup();\n\n    CoeffDataType c = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\n    CoeffDataType d = (1 + std::sqrt(static_cast<CoeffDataType>(2.)) * c + c * c);\n    \n    coefficients_in[2] = 1;\n    coefficients_in[1] = -2;\n    coefficients_in[0] = 1;\n    coefficients_out[1] = - 2 * (c * c - 1) / d;\n    coefficients_out[0] = - (1 - std::sqrt(static_cast<CoeffDataType>(2.)) * c + c * c) / d;\n  }\n\n  template<typename DataType_>\n  SecondOrderBandPassPeakCoefficients<DataType_>::SecondOrderBandPassPeakCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType_>\n  void SecondOrderBandPassPeakCoefficients<DataType_>::setup()\n  {\n    Parent::setup();\n\n    CoeffDataType c = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\n    CoeffDataType Q_inv = 1 / Q;\n    if(gain <= 1)\n    {\n      CoeffDataType V0 = 1 / gain;\n      CoeffDataType d = 1 + V0 * Q_inv * c + c * c;\n      \n      coefficients_in[2] = (1 + Q_inv * c + c * c) / d;\n      coefficients_in[1] = 2 * (c * c - 1) / d;\n      coefficients_in[0] = (1 - Q_inv * c + c * c) / d;\n      coefficients_out[1] = -2 * (c * c - 1) / d;\n      coefficients_out[0] = -(1 - V0 * Q_inv * c + c * c) / d;\n    }\n    else\n    {\n      CoeffDataType V0 = gain;\n      CoeffDataType d = 1 + Q_inv * c + c * c;\n      \n      coefficients_in[2] = (1 + V0 * Q_inv * c + c * c) / d;\n      coefficients_in[1] = 2 * (c * c - 1) / d;\n      coefficients_in[0] = (1 - V0 * Q_inv * c + c * c) / d;\n      coefficients_out[1] = -2 * (c * c - 1) / d;\n      coefficients_out[0] = -(1 - Q_inv * c + c * c) / d;\n    }\n  }\n\n  template <typename DataType_>\n  void SecondOrderBandPassPeakCoefficients<DataType_>::set_Q(CoeffDataType Q)\n  {\n    if(Q <= 0)\n    {\n      throw std::out_of_range(\"Q can't be negative\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  typename SecondOrderBandPassPeakCoefficients<DataType_>::CoeffDataType SecondOrderBandPassPeakCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template <typename DataType_>\n  void SecondOrderBandPassPeakCoefficients<DataType_>::set_gain(CoeffDataType gain)\n  {\n    this->gain = gain;\n    setup();\n  }\n\n  template <typename DataType_>\n  typename SecondOrderBandPassPeakCoefficients<DataType_>::CoeffDataType SecondOrderBandPassPeakCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType_>\n  SecondOrderAllPassCoefficients<DataType_>::SecondOrderAllPassCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType_>\n  void SecondOrderAllPassCoefficients<DataType_>::setup()\n  {\n    Parent::setup();\n\n    CoeffDataType c = std::tan(boost::math::constants::pi<CoeffDataType>() * Q);\n    CoeffDataType d = -std::cos(2 * boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\n\n    coefficients_in[2] = -c;\n    coefficients_in[1] = d * (1 - c);\n    coefficients_in[0] = 1;\n    coefficients_out[1] = -d * (1 - c);\n    coefficients_out[0] = c;\n  }\n\n  template <typename DataType_>\n  void SecondOrderAllPassCoefficients<DataType_>::set_Q(CoeffDataType Q)\n  {\n    if(Q <= 0)\n    {\n      throw std::out_of_range(\"Q can't be negative\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  typename SecondOrderAllPassCoefficients<DataType_>::CoeffDataType SecondOrderAllPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType_>\n  SecondOrderLowShelvingCoefficients<DataType_>::SecondOrderLowShelvingCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType_>\n  void SecondOrderLowShelvingCoefficients<DataType_>::setup()\n  {\n    Parent::setup();\n\n    CoeffDataType c = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\n    if(gain <= 1)\n    {\n      CoeffDataType V0 = 1 / gain;\n      CoeffDataType d = (1 + std::sqrt(static_cast<CoeffDataType>(2.) * V0) * c + V0 * c * c);\n      \n      coefficients_in[2] = (1 + std::sqrt(static_cast<CoeffDataType>(2.)) * c + c * c) / d;\n      coefficients_in[1] = 2 * (c * c - 1) / d;\n      coefficients_in[0] = (1 - std::sqrt(static_cast<CoeffDataType>(2.)) * c + c * c) / d;\n      coefficients_out[1] = - 2 * (V0 * c * c - 1) / d;\n      coefficients_out[0] = - (1 - std::sqrt(static_cast<CoeffDataType>(2.) * V0) * c + V0 * c * c) / d;\n    }\n    else\n    {\n      CoeffDataType d = (1 + std::sqrt(static_cast<CoeffDataType>(2.)) * c + c * c);\n      \n      coefficients_in[2] = (1 + std::sqrt(static_cast<CoeffDataType>(2.) * gain) * c + gain * c * c) / d;\n      coefficients_in[1] = 2 * (gain * c * c - 1) / d;\n      coefficients_in[0] = (1 - std::sqrt(static_cast<CoeffDataType>(2.) * gain) * c + gain * c * c) / d;\n      coefficients_out[1] = - 2 * (c * c - 1) / d;\n      coefficients_out[0] = - (1 - std::sqrt(static_cast<CoeffDataType>(2.)) * c + c * c) / d;\n    }\n  }\n\n  template <typename DataType_>\n  void SecondOrderLowShelvingCoefficients<DataType_>::set_gain(CoeffDataType gain)\n  {\n    this->gain = gain;\n    setup();\n  }\n\n  template <typename DataType_>\n  typename SecondOrderLowShelvingCoefficients<DataType_>::CoeffDataType SecondOrderLowShelvingCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType_>\n  SecondOrderHighShelvingCoefficients<DataType_>::SecondOrderHighShelvingCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void SecondOrderHighShelvingCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    CoeffDataType c = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\n    if(gain <= 1)\n    {\n      CoeffDataType V0 = 1 / gain;\n      CoeffDataType d = (V0 + std::sqrt(static_cast<CoeffDataType>(2.) * V0) * c + c * c);\n      \n      coefficients_in[2] = -(1 + std::sqrt(static_cast<CoeffDataType>(2.0)) * c + c * c) / d;\n      coefficients_in[1] = -2 * (c * c - 1) / d;\n      coefficients_in[0] = -(1 - std::sqrt(static_cast<CoeffDataType>(2.0)) * c + c * c) / d;\n      coefficients_out[1] = - 2 * (c * c - V0) / d;\n      coefficients_out[0] = - (V0 - std::sqrt(static_cast<CoeffDataType>(2.0) * V0) * c + c * c) / d;\n    }\n    else\n    {\n      CoeffDataType d = (1 + std::sqrt(static_cast<CoeffDataType>(2.)) * c + c * c);\n      \n      coefficients_in[2] = -(gain + std::sqrt(static_cast<CoeffDataType>(2.0) * gain) * c + c * c) / d;\n      coefficients_in[1] = -2 * (c * c - gain) / d;\n      coefficients_in[0] = -(gain - std::sqrt(static_cast<CoeffDataType>(2.0) * gain) * c + c * c) / d;\n      coefficients_out[1] = - 2 * (c * c - 1) / d;\n      coefficients_out[0] = - (1 - std::sqrt(static_cast<CoeffDataType>(2.0)) * c + c * c) / d;\n    }\n  }\n  \n  template<typename DataType_>\n  void SecondOrderHighShelvingCoefficients<DataType_>::set_gain(CoeffDataType gain)\n  {\n    this->gain = gain;\n    setup();\n  }\n\n  template <typename DataType_>\n  typename SecondOrderHighShelvingCoefficients<DataType_>::CoeffDataType SecondOrderHighShelvingCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n}\n", "meta": {"hexsha": "073f63fce54e9a232355f2497bea854c01df578d", "size": 10758, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "ATK/EQ/SecondOrderFilter.hxx", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "ATK/EQ/SecondOrderFilter.hxx", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "ATK/EQ/SecondOrderFilter.hxx", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 32.0178571429, "max_line_length": 137, "alphanum_fraction": 0.6522587842, "num_tokens": 3186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443252, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.535828632112403}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n//\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n// Distance Example\n\n// This sample demonstrates the use of latlong-points, xy-points,\n// calculate distances between latlong points using different formulas,\n// calculate distance between points using pythagoras\n\n#include <iostream>\n\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/strategies/spherical/distance_cross_track.hpp>\n#include <boost/geometry/extensions/gis/latlong/latlong.hpp>\n#include <boost/geometry/extensions/gis/geographic/strategies/andoyer.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/sterea.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/laea.hpp>\n#include <boost/geometry/extensions/gis/projections/parameters.hpp>\n\n// BSG 28-10-2010\n// TODO: clear up this test\n// it is more a test than an example\n// the results are sometimes WRONG\n\nint main()\n{\n\n    using namespace boost::geometry;\n\n    typedef model::ll::point<degree> latlon_point;\n    typedef model::d2::point_xy<double> xy_point;\n\n    latlon_point city1;\n    // Amsterdam 52 22'23\"N 4 53'32\"E\n    std::string const city1_name = \"Amsterdam\";\n    city1.lat(dms<north>(52, 22, 23));\n    city1.lon(dms<east>(4, 53, 32));\n\n    // Rotterdam 51 55'51\"N 4 28'45\"E\n    // latlon_point city2(latitude<>(dms<north>(51, 55, 51)), longitude<>(dms<east>(4, 28, 45)));\n    // Paris 48 52' 0\" N, 2 19' 59\" E\n    std::string const city2_name = \"Paris\";\n    latlon_point city2(latitude<>(dms<north>(48, 52, 0)), longitude<>(dms<east>(2, 19, 59)));\n\n    // The Hague: 52 4' 48\" N, 4 18' 0\" E\n    //latlon_point city3(longitude<>(dms<east>(4, 18, 0)), latitude<>(dms<north>(52, 4, 48)));\n    // Barcelona\n    std::string const city3_name = \"Barcelona\";\n    latlon_point city3(longitude<>(dms<east>(2, 11, 0)), latitude<>(dms<north>(41, 23, 0)));\n\n\n    model::ll::point<radian> city1_rad, city2_rad, city3_rad;\n    transform(city1, city1_rad);\n    transform(city2, city2_rad);\n    transform(city3, city3_rad);\n\n    /*\n    projections::sterea_ellipsoid<model::ll::point<radian>, xy_point> proj\n        (projections::init(\n        \"+lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m\"));\n    */\n    projections::laea_ellipsoid<model::ll::point<radian>, xy_point> proj\n        (projections::init(\n        \" +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m\"));\n\n\n    xy_point city1_prj, city2_prj, city3_prj;\n    proj.forward(city1_rad, city1_prj);\n    proj.forward(city3_rad, city3_prj);\n    proj.forward(city2_rad, city2_prj);\n\n    // ------------------------------------------------------------------------------------------\n    // Distances\n    // ------------------------------------------------------------------------------------------\n\n    std::cout << \"Distance \" << city1_name << \"-\" << city2_name << \": \" << std::endl;\n    std::cout << \"haversine:              \" << 0.001 * distance(city1, city2) << \" km\" << std::endl;\n    std::cout << \"haversine rad:          \" << 0.001 * distance(city1_rad, city2_rad) << \" km\" << std::endl;\n    std::cout << \"haversine other radius: \" << distance(city1, city2, strategy::distance::haversine<latlon_point>(6371.0) ) << \" km\" << std::endl;\n    std::cout << \"andoyer:                \" << 0.001 * distance(city1, city2, strategy::distance::andoyer<latlon_point>() ) << \" km\" << std::endl;\n    std::cout << \"vincenty:               \" << 0.001 * distance(city1, city2, strategy::distance::vincenty<latlon_point>() ) << \" km\" << std::endl;\n    std::cout << \"vincenty rad:           \" << 0.001 * distance(city1_rad, city2_rad, strategy::distance::vincenty<model::ll::point<radian> >() ) << \" km\" << std::endl;\n    std::cout << \"Projected, pythagoras:  \" << 0.001 * distance(city1_prj, city2_prj) << \" km\" << std::endl;\n\n    std::cout << std::endl;\n    std::cout << \"Distance \" << city1_name << \"-\" << city3_name << \": \" << std::endl;\n    std::cout << \"andoyer:                \" << 0.001 * distance(city1, city3, strategy::distance::andoyer<latlon_point>()) << \" km\" << std::endl;\n    std::cout << \"Distance \" << city2_name << \"-\" << city3_name << \": \" << std::endl;\n    std::cout << \"andoyer:                \" << 0.001 * distance(city2, city3, strategy::distance::andoyer<latlon_point>()) << \" km\" << std::endl;\n\n    // ------------------------------------------------------------------------------------------\n    // Distances to segments\n    // ------------------------------------------------------------------------------------------\n    std::cout << std::endl << city3_name << \" - line \" << city1_name << \",\" << city2_name << std::endl;\n\n    model::segment<xy_point> ar_xy(city1_prj, city2_prj);\n\n    double dr = distance(city3_prj, ar_xy);\n    std::cout << \"projected: \" << 0.001 * dr << std::endl;\n\n    dr = distance(city3, model::segment<latlon_point>(city1, city2));\n    std::cout << \"in LL: \" << 0.001 * dr << std::endl;\n\n    std::cout << std::endl << city2_name << \" - line \" << city1_name << \",\" << city3_name << std::endl;\n    dr = distance(city2_prj, model::segment<xy_point>(city1_prj, city3_prj));\n    std::cout << \"projected: \" << 0.001 * dr << std::endl;\n    dr = distance(city2, model::segment<latlon_point>(city1, city3));\n    std::cout << \"in LL: \" << 0.001 * dr << std::endl;\n    std::cout << std::endl;\n\n\n    // ------------------------------------------------------------------------------------------\n    // Compilation\n    // ------------------------------------------------------------------------------------------\n    // Next line does not compile because Vincenty cannot work on xy-points\n    //std::cout << \"vincenty on xy:         \" << 0.001 * distance(city1_prj, city2_prj, formulae::distance::vincenty<>() ) << \" km\" << std::endl;\n\n    // Next line does not compile because you cannot (yet) assign degree to radian directly\n    //ll::point<radian> a_rad2 = city1;\n\n    // Next line does not compile because you cannot assign latlong to xy\n    // d2::point axy = city1;\n\n    // ------------------------------------------------------------------------------------------\n    // Length\n    // ------------------------------------------------------------------------------------------\n    // Length calculations use distances internally. The lines below take automatically the default\n    // formulae for distance. However, you can also specify city1 formula explicitly.\n\n    model::linestring<latlon_point> line1;\n    append(line1, city1);\n    append(line1, city2);\n    std::cout << \"length: \" << length(line1) << std::endl;\n    std::cout << \"length using Vincenty: \" << length(line1, strategy::distance::vincenty<latlon_point>()) << std::endl;\n\n    model::linestring<xy_point> line2;\n    append(line2, city1_prj);\n    append(line2, city2_prj);\n    std::cout << \"length: \" << length(line2) << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "e9f5c083456cabba514de474e3fcfdbd1dcd8dbc", "size": 7197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/example_extensions/gis/latlong/distance_example.cpp", "max_stars_repo_name": "juslee/boost-svn", "max_stars_repo_head_hexsha": "6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-07-03T22:12:18.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-03T22:12:18.000Z", "max_issues_repo_path": "libs/geometry/extensions/example/gis/latlong/distance_example.cpp", "max_issues_repo_name": "graehl/boost", "max_issues_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "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/extensions/example/gis/latlong/distance_example.cpp", "max_forks_repo_name": "graehl/boost", "max_forks_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "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": 48.3020134228, "max_line_length": 168, "alphanum_fraction": 0.5724607475, "num_tokens": 2016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.53581109897483}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n\n#include <boost/scope_exit.hpp>\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n#include <amgcl/mpi/direct_solver/runtime.hpp>\n#include <amgcl/profiler.hpp>\n\nnamespace amgcl {\n    profiler<> prof;\n}\n\nint main(int argc, char *argv[]) {\n    int provided;\n    MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);\n    BOOST_SCOPE_EXIT(void) {\n        MPI_Finalize();\n    } BOOST_SCOPE_EXIT_END\n\n    amgcl::mpi::communicator comm(MPI_COMM_WORLD);\n\n    if (comm.rank == 0)\n        std::cout << \"World size: \" << comm.size << std::endl;\n\n    namespace po = boost::program_options;\n    po::options_description desc(\"Options\");\n\n    desc.add_options()\n        (\"help,h\", \"show help\")\n        (\n         \"size,n\",\n         po::value<int>()->default_value(128),\n         \"domain size\"\n        )\n        (\"prm-file,P\",\n         po::value<std::string>(),\n         \"Parameter file in json format. \"\n        )\n        (\n         \"prm,p\",\n         po::value< std::vector<std::string> >()->multitoken(),\n         \"Parameters specified as name=value pairs. \"\n         \"May be provided multiple times. Examples:\\n\"\n         \"  -p solver.tol=1e-3\\n\"\n         \"  -p precond.coarse_enough=300\"\n        )\n        ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n        if (comm.rank == 0) std::cout << desc << std::endl;\n        return 0;\n    }\n\n    boost::property_tree::ptree prm;\n    if (vm.count(\"prm-file\")) {\n        read_json(vm[\"prm-file\"].as<std::string>(), prm);\n    }\n\n    if (vm.count(\"prm\")) {\n        for(const std::string &v : vm[\"prm\"].as<std::vector<std::string> >()) {\n            amgcl::put(prm, v);\n        }\n    }\n\n    const int n = vm[\"size\"].as<int>();\n    const int n2 = n * n;\n\n    using amgcl::prof;\n\n    int chunk       = (n2 + comm.size - 1) / comm.size;\n    int chunk_start = comm.rank * chunk;\n    int chunk_end   = std::min(chunk_start + chunk, n2);\n\n    chunk = chunk_end - chunk_start;\n\n    std::vector<int> domain(comm.size + 1);\n    MPI_Allgather(&chunk, 1, MPI_INT, &domain[1], 1, MPI_INT, comm);\n    std::partial_sum(domain.begin(), domain.end(), domain.begin());\n\n    prof.tic(\"assemble\");\n    amgcl::backend::crs<double> A;\n    A.set_size(chunk, domain.back(), true);\n    A.set_nonzeros(chunk * 5);\n    std::vector<double> rhs(chunk, 1);\n\n    const double h2i  = (n - 1) * (n - 1);\n    for(int idx = chunk_start, row = 0, head = 0; idx < chunk_end; ++idx, ++row) {\n        int j = idx / n;\n        int i = idx % n;\n\n        if (j > 0)  {\n            A.col[head] = idx - n;\n            A.val[head] = -h2i;\n            ++head;\n        }\n\n        if (i > 0) {\n            A.col[head] = idx - 1;\n            A.val[head] = -h2i;\n            ++head;\n        }\n\n        A.col[head] = idx;\n        A.val[head] = 4 * h2i;\n        ++head;\n\n        if (i + 1 < n) {\n            A.col[head] = idx + 1;\n            A.val[head] = -h2i;\n            ++head;\n        }\n\n        if (j + 1 < n) {\n            A.col[head] = idx + n;\n            A.val[head] = -h2i;\n            ++head;\n        }\n\n        A.ptr[row + 1] = head;\n    }\n    A.nnz = A.ptr[chunk];\n    prof.toc(\"assemble\");\n\n    prof.tic(\"setup\");\n    amgcl::runtime::mpi::direct::solver<double> solve(comm, A, prm);\n    prof.toc(\"setup\");\n\n    prof.tic(\"solve\");\n    std::vector<double> x(chunk);\n    solve(rhs, x);\n    solve(rhs, x);\n    prof.toc(\"solve\");\n\n    prof.tic(\"save\");\n    if (comm.rank == 0) {\n        std::vector<double> X(n2);\n        std::copy(x.begin(), x.end(), X.begin());\n\n        for(int i = 1; i < comm.size; ++i)\n            MPI_Recv(&X[domain[i]], domain[i+1] - domain[i], MPI_DOUBLE, i, 42, comm, MPI_STATUS_IGNORE);\n\n        std::ofstream f(\"out.dat\", std::ios::binary);\n        f.write((char*)&n2, sizeof(int));\n        f.write((char*)X.data(), n2 * sizeof(double));\n    } else {\n        MPI_Send(x.data(), chunk, MPI_DOUBLE, 0, 42, comm);\n    }\n    prof.toc(\"save\");\n\n    if (comm.rank == 0) {\n        std::cout << prof << std::endl;\n    }\n\n}\n", "meta": {"hexsha": "92d427cdc81f76d42e67abebfd3c15a2de49f325", "size": 4242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpi/check_direct.cpp", "max_stars_repo_name": "tenglongcong/amgcl", "max_stars_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 504.0, "max_stars_repo_stars_event_min_datetime": "2015-03-11T13:50:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:08:55.000Z", "max_issues_repo_path": "examples/mpi/check_direct.cpp", "max_issues_repo_name": "tenglongcong/amgcl", "max_issues_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 209.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T19:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:44:12.000Z", "max_forks_repo_path": "examples/mpi/check_direct.cpp", "max_forks_repo_name": "tenglongcong/amgcl", "max_forks_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 92.0, "max_forks_repo_forks_event_min_datetime": "2015-01-04T06:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T09:49:12.000Z", "avg_line_length": 25.4011976048, "max_line_length": 105, "alphanum_fraction": 0.5212164074, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.53579716519543}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Header file for the SE3 Lie Group types.\n/// \\details These types provide a standardized definition for various SE3 quantities.\n///\n/// \\author Kirk MacTavish\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef LGM_SE3_TYPES_HPP\n#define LGM_SE3_TYPES_HPP\n\n#include <Eigen/Core>\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// Lie Group Math - Special Orthogonal Group\n/////////////////////////////////////////////////////////////////////////////////////////////\nnamespace lgmath {\nnamespace se3 {\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// A translation vector, r_ba_ina, which translates points from the origin to b in frame a\n/////////////////////////////////////////////////////////////////////////////////////////////\ntypedef Eigen::Vector3d TranslationVector;\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// A Lie algebra vector composed of a stacked translation and axis-angle rotation.\n///\n///   xi_ba = [  rho_ba]\n///           [aaxis_ba]\n///\n/////////////////////////////////////////////////////////////////////////////////////////////\ntypedef Eigen::Matrix<double,6,1> LieAlgebra;\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// The covariance matrix of a Lie algebra vector\n/////////////////////////////////////////////////////////////////////////////////////////////\ntypedef Eigen::Matrix<double,6,6> LieAlgebraCovariance;\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// A transformation, T_ba, transforms points from frame a to frame b.\n///\n///   T_ba = [ C_ba, -C_ba*r_ba_ina]\n///          [0 0 0,              1]\n/////////////////////////////////////////////////////////////////////////////////////////////\ntypedef Eigen::Matrix4d TransformationMatrix;\n\n} // se3\n} // lgmath\n\n#endif // LGM_SE3_TYPES_HPP\n", "meta": {"hexsha": "2c210f4ca052fc311d3df6f24dba1306995a29e6", "size": 2137, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lgmath/se3/Types.hpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "include/lgmath/se3/Types.hpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "include/lgmath/se3/Types.hpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 42.74, "max_line_length": 94, "alphanum_fraction": 0.33224146, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5357971531221104}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\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 along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if !defined(PROBABILITY_DISTRIBUTION_HPP)\n#define PROBABILITY_DISTRIBUTION_HPP\n\n#if defined(_MSC_VER)\n#\tpragma warning(disable: 4267)\t// warning about loss of data when converting size_t to int\n#endif\n\n#include <cmath>\n#include \"ncl/nxsdefs.h\"\n\n#include \"states_patterns.hpp\"\n\n#include <boost/shared_ptr.hpp>\n#include <boost/format.hpp>\n#include \"basic_cdf.hpp\"\n#include \"basic_lot.hpp\"\n#include \"phycas_string.hpp\"\n#if defined(PYTHON_ONLY) && defined(USING_NUMARRAY)\n#\tinclude <boost/python/tuple.hpp>\n#\tinclude <boost/python/numeric.hpp>\n#\tinclude \"thirdparty/num_util/num_util.h\"\n#endif\n#include \"xprobdist.hpp\"\nclass XUnderflow{};\n\nnamespace phycas\n{\n\nstruct AdHocDensity\n\t{\n\tvirtual ~AdHocDensity()\n\t\t{\n\t\t//std::cerr << \"\\n>>>>> AdHocDensity dying...\" << std::endl;\n\t\t}\n    virtual double operator()(double) = 0;\n\t};\n\nclass ProbabilityDistribution : public AdHocDensity\n\t{\n\tpublic:\n\t\t\t\t\t\t\tProbabilityDistribution() {lot = &myLot;}\n\t\t\t\t\t\t\tvirtual ~ProbabilityDistribution();\n\n        double              LnGamma(double x);\n\n\t\tvirtual void\t\tSetLot(Lot * other); //@POL seems like this should be a shared pointer\n\t\tvirtual Lot *\t\tGetLot() {return lot;}\n\t\tvirtual void\t\tResetLot();\n\t\tvirtual void\t\tSetSeed(unsigned rnseed);\n\n\t\tvirtual\tbool\t\tIsDiscrete() const\t\t\t\t\t\t= 0;\n\t\tvirtual std::string GetDistributionName() const\t\t\t\t= 0;\n\t\tvirtual std::string GetDistributionDescription() const\t\t= 0;\n\t\tvirtual double \t\tGetMean() const\t\t\t\t\t\t\t= 0;\n\t\tvirtual double \t\tGetVar() const\t\t\t\t\t\t\t= 0;\n\t\tvirtual double \t\tGetStdDev() const\t\t\t\t\t\t= 0;\n\t\tvirtual double\t\tGetCDF(double x) const\t\t\t\t\t= 0;\n\t\tvirtual double\t\tSample() const\t\t\t\t\t\t\t= 0;\n\t\tvirtual double\t\tGetLnPDF(double x) const\t\t\t\t= 0;\n\t\tvirtual double\t\tGetRelativeLnPDF(double x) const\t\t= 0;\n\t\tdouble \t\t\t\tGetRelativeLnPDFArray(double *x, int arrLen) const;\n\t\tvirtual void \t\tSetMeanAndVariance(double m, double v)\t= 0;\n\n\t\tvirtual double\t\toperator()(double x);\n\n\t\tCDF\t\t\tcdf;\n\t\tLot\t\t\tmyLot;\n\t\tLot *\t\tlot;\n\t};\n\ntypedef boost::shared_ptr<ProbabilityDistribution> ProbDistShPtr;\n\n/*------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|\tEncapsulates the discrete bernoulli probability distribution with parameter p, the probability of success.\n*/\nclass BernoulliDistribution : public ProbabilityDistribution\n\t{\n\tprotected:\n\t\tdouble p;\t/* the probability of success on any given trial */\n\n\tpublic:\n\t\t\t\t\t\t\tBernoulliDistribution();\n\t\t\t\t\t\t\tBernoulliDistribution(double prob_success);\n\t\t\t\t\t\t\tBernoulliDistribution(const BernoulliDistribution & other);\n\t\t\t\t\t\t\t~BernoulliDistribution();\n\n        BernoulliDistribution * Clone() const;\n        BernoulliDistribution * cloneAndSetLot(Lot * other) const;\n\n\t\tvirtual\tbool\t\tIsDiscrete() const;\n\t\tvirtual std::string\tGetDistributionName() const;\n\t\tvirtual std::string\tGetDistributionDescription() const;\n\t\tvirtual double\t\tGetMean() const;\n\t\tvirtual double\t\tGetVar() const;\n\t\tvirtual double\t\tGetStdDev() const;\n\t\tvirtual double\t\tGetCDF(double x) const;\n\t\tvirtual double\t\tSample() const;\n\t\tvirtual double\t\tGetLnPDF(double x) const;\n\t\tvirtual double\t\tGetRelativeLnPDF(double x) const;\n\t\tvirtual void\t\tSetMeanAndVariance(double mean, double var);\n\t};\n\n/*------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|\tEncapsulates the discrete binomial probability distribution with parameter p, the probability of success.\n*/\nclass BinomialDistribution : public BernoulliDistribution\n\t{\n\tpublic:\n\t\t\t\t\t\t\tBinomialDistribution();\n\t\t\t\t\t\t\tBinomialDistribution(double sample_size, double prob_success);\n\t\t\t\t\t\t\tBinomialDistribution(const BinomialDistribution & other);\n\t\t\t\t\t\t\t~BinomialDistribution();\n\n        BinomialDistribution * cloneAndSetLot(Lot * other) const;\n        BinomialDistribution * Clone() const;\n\t\tvirtual\tbool\t\tIsDiscrete() const;\n\t\tvirtual std::string\tGetDistributionName() const;\n\t\tvirtual std::string\tGetDistributionDescription() const;\n\t\tvirtual double\t\tGetMean() const;\n\t\tvirtual double\t\tGetVar() const;\n\t\tvirtual double\t\tGetStdDev() const;\n\t\tvirtual double\t\tGetCDF(double x) const;\n\t\tvirtual double\t\tSample() const;\n\t\tvirtual double\t\tGetLnPDF(double x) const;\n\t\tvirtual double\t\tGetRelativeLnPDF(double x) const;\n\t\tvirtual void\t\tSetMeanAndVariance(double mean, double var);\n\n    private:\n\t\tdouble q;\n\t\tdouble lnp;\n\t\tdouble lnq;\n\n\tprotected:\n\t\tdouble n;\n\t};\n\n/*------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|\tEncapsulates the continuous Beta probability distribution with parameters alpha and beta.\n*/\nclass BetaDistribution  : public ProbabilityDistribution\n\t{\n\t\tdouble alphaParam;\n\t\tdouble betaParam;\n\n\tpublic:\n\t\t\t\t\t\tBetaDistribution() : alphaParam(1.0), betaParam(1.0) {}\n\t\t\t\t\t\tBetaDistribution(double a, double b);\n\t\t\t\t\t\tBetaDistribution(const BetaDistribution & other);\n\t\t\t\t\t\t~BetaDistribution();\n\n        BetaDistribution * cloneAndSetLot(Lot * other) const;\n        BetaDistribution * Clone() const;\n\t\tbool\t\t\tIsDiscrete() const;\n\t\tstd::string \tGetDistributionName() const;\n\t\tstd::string \tGetDistributionDescription() const;\n\t\tdouble \t\t\tGetMean() const;\n\t\tdouble \t\t\tGetVar() const;\n\t\tdouble \t\t\tGetStdDev() const;\n\t\tdouble\t\t\tGetCDF(double x) const;\n\t\tdouble\t\t\tGetQuantile(double p) const;\n\t\tdouble\t\t\tSample() const;\n\t\tdouble\t\t\tGetLnPDF(double x) const;\n\t\tdouble\t\t\tGetRelativeLnPDF(double x) const;\n\t\tvoid \t\t\tSetMeanAndVariance(double m, double v);\n\t};\n\n/*------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|\tEncapsulates the continuous Beta prime probability distribution with parameters alpha and beta.\n*/\nclass BetaPrimeDistribution  : public ProbabilityDistribution\n\t{\n\t\tdouble alphaParam;\n\t\tdouble betaParam;\n\n\tpublic:\n\t\t\t\t\t\tBetaPrimeDistribution() : alphaParam(1.0), betaParam(1.0) {}\n\t\t\t\t\t\tBetaPrimeDistribution(double a, double b);\n\t\t\t\t\t\tBetaPrimeDistribution(const BetaPrimeDistribution & other);\n\t\t\t\t\t\t~BetaPrimeDistribution();\n\n        BetaPrimeDistribution * cloneAndSetLot(Lot * other) const;\n        BetaPrimeDistribution * Clone() const;\n\t\tbool\t\t\tIsDiscrete() const;\n\t\tstd::string \tGetDistributionName() const;\n\t\tstd::string \tGetDistributionDescription() const;\n\t\tdouble \t\t\tGetMean() const;\n\t\tdouble \t\t\tGetVar() const;\n\t\tdouble \t\t\tGetStdDev() const;\n\t\tdouble\t\t\tGetCDF(double x) const;\n\t\tdouble\t\t\tGetQuantile(double p) const;\n\t\tdouble\t\t\tSample() const;\n\t\tdouble\t\t\tGetLnPDF(double x) const;\n\t\tdouble\t\t\tGetRelativeLnPDF(double x) const;\n\t\tvoid \t\t\tSetMeanAndVariance(double m, double v);\n\t};\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tA uniform probability distribution with left bound 0.0 and right bound infinity. This is an improper distribution\n|\t(the area under its density curve is infinite).\n*/\nclass ImproperUniformDistribution : public ProbabilityDistribution\n\t{\n\tpublic:\n\t\t\t\t\tImproperUniformDistribution();\n\t\t\t\t\tImproperUniformDistribution(const ImproperUniformDistribution & other);\n\t\t\t\t\t~ImproperUniformDistribution();\n\n        ImproperUniformDistribution * cloneAndSetLot(Lot * other) const;\n        ImproperUniformDistribution * Clone() const;\n\t\tbool\t\tIsDiscrete() const;\n\t\tstd::string\tGetDistributionName() const;\n\t\tstd::string\tGetDistributionDescription() const;\n\t\tdouble\t\tGetMean() const;\n\t\tdouble\t\tGetVar() const;\n\t\tdouble\t\tGetStdDev() const;\n\t\tdouble\t\tGetCDF(double x) const;\n\t\tdouble\t\tSample() const;\n\t\tdouble\t\tGetLnPDF(double x) const;\n\t\tdouble\t\tGetRelativeLnPDF(double x) const;\n\t\tvoid\t\tSetMeanAndVariance(double mean, double var);\n\t};\n\n/*------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|\tEncapsulates the continuous uniform probability distribution with left bound a and right bound b.\n*/\nclass UniformDistribution : public ProbabilityDistribution\n\t{\n\tpublic:\n\t\t\t\t\tUniformDistribution();\n\t\t\t\t\tUniformDistribution(double left_bound, double right_bound);\n\t\t\t\t\tUniformDistribution(const UniformDistribution & other);\n\t\t\t\t\t~UniformDistribution();\n\n        UniformDistribution * cloneAndSetLot(Lot * other) const;\n        UniformDistribution * Clone() const;\n\t\tbool\t\tIsDiscrete() const;\n\t\tstd::string\tGetDistributionName() const;\n\t\tstd::string\tGetDistributionDescription() const;\n\t\tdouble\t\tGetMean() const;\n\t\tdouble\t\tGetVar() const;\n\t\tdouble\t\tGetStdDev() const;\n\t\tdouble\t\tGetCDF(double x) const;\n\t\tdouble\t\tSample() const;\n\t\tdouble\t\tGetLnPDF(double x) const;\n\t\tdouble\t\tGetRelativeLnPDF(double x) const;\n\t\tvoid\t\tSetMeanAndVariance(double mean, double var);\n\n        virtual double GetLeftSupportBoundary() const;\n        virtual double GetRightSupportBoundary() const;\n\n\tprotected:\n\t\tdouble a;\t\t\t\t/**< the left bound */\n\t\tdouble b;\t\t\t\t/**< the right bound */\n\t\tdouble log_density;\t\t/**< the precalculated log of the density function */\n\n\t};\n\n/*------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|\tEncapsulates the gamma probability distribution with shape parameter (alpha) and scale parameter (beta).\n*/\nclass GammaDistribution : public ProbabilityDistribution\n\t{\n\tpublic:\n\t\t\t\t\t\tGammaDistribution();\n\t\t\t\t\t\tGammaDistribution(double shape, double scale);\n\t\t\t\t\t    GammaDistribution(const GammaDistribution & other);\n\t\t\t\t\t\t~GammaDistribution();\n\n        GammaDistribution * cloneAndSetLot(Lot * other) const;\n        GammaDistribution * Clone() const;\n\t\tbool\t\t\tIsDiscrete() const;\n\t\tstd::string\t\tGetDistributionName() const;\n\t\tstd::string\t\tGetDistributionDescription() const;\n\t\tdouble\t\t\tGetMean() const;\n\t\tdouble\t\t\tGetVar() const;\n\t\tdouble\t\t\tGetStdDev() const;\n\t\tdouble\t\t\tGetCDF(double x) const;\n\t\tdouble\t\t\tSample() const;\n\t\tvirtual double\tGetLnPDF(double x) const;\n\t\tdouble\t\t\tGetRelativeLnPDF(double x) const;\n\t\tvoid\t\t\tSetMeanAndVariance(double mean, double var);\n\n\tprotected:\n\t\tvoid\t\t\tComputeLnConst();\n\n    protected:\n\t\tdouble alpha;\t\t/* the shape parameter */\n\t\tdouble beta;\t\t/* the scale parameter */\n\t\tdouble ln_const;\t/* the natural logarithm of the constant part of the density function */\n\t};\n\n/*------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|\tThe inverse (or inverted) gamma distribution with parameters alpha and beta is the distribution of 1/X where X is a gamma distributed random variable with shape\n|\tparameter alpha and scale parameter beta.\n*/\nclass InverseGammaDistribution : public GammaDistribution\n\t{\n\tpublic:\n\t\t\t\t\tInverseGammaDistribution();\n\t\t\t\t\tInverseGammaDistribution(double shape, double scale);\n\t\t\t\t\tInverseGammaDistribution(const InverseGammaDistribution & other);\n\t\t\t\t\t~InverseGammaDistribution();\n\n        InverseGammaDistribution * cloneAndSetLot(Lot * other) const;\n        InverseGammaDistribution * Clone() const;\n\t\tbool\t\tIsDiscrete() const;\n\t\tstd::string\tGetDistributionName() const;\n\t\tstd::string\tGetDistributionDescription() const;\n\t\tdouble\t\tGetMean() const;\n\t\tdouble\t\tGetVar() const;\n\t\tdouble\t\tGetStdDev() const;\n\t\tdouble\t\tGetCDF(double x) const;\n\t\tdouble\t\tSample() const;\n\t\tdouble\t\tGetLnPDF(double x) const;\n\t\tdouble\t\tGetRelativeLnPDF(double x) const;\n\t\tvoid\t\tSetMeanAndVariance(double mean, double var);\n\t};\n\n/*------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|\tThis is a special case of the gamma distribution in which the shape parameter equals the mean and the scale parameter is 1.0.\n*/\nclass ExponentialDistribution : public GammaDistribution\n\t{\n\tpublic :\n\t\t\t\t\tExponentialDistribution();\n\t\t\t\t\tExponentialDistribution(double lambda);\n                    ExponentialDistribution(const ExponentialDistribution & other);\n\t\t\t\t\t~ExponentialDistribution();\n\n        ExponentialDistribution * cloneAndSetLot(Lot * other) const;\n        ExponentialDistribution * Clone() const;\n\t\tbool\t\tIsDiscrete() const;\n\t\tstd::string\tGetDistributionName() const;\n\t\tstd::string\tGetDistributionDescription() const;\n\t\tvoid\t\tSetMeanAndVariance(double mean, double var = 0.0);\n\t\tdouble\t\tGetLnPDF(double x) const;\n\t};\n\n/*------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|\tThe Normal distribution with two parameters, the mean and standard deviation.\n*/\nclass NormalDistribution : public ProbabilityDistribution\n\t{\n\tpublic:\n\t\t\t\t\tNormalDistribution();\n\t\t\t\t\tNormalDistribution(double mean, double stddev);\n\t\t\t\t\tNormalDistribution(const NormalDistribution & other);\n\t\t\t\t\t~NormalDistribution();\n\n        NormalDistribution * cloneAndSetLot(Lot * other) const;\n        NormalDistribution * Clone() const;\n\t\tbool\t\tIsDiscrete() const;\n\t\tstd::string\tGetDistributionName() const;\n\t\tstd::string\tGetDistributionDescription() const;\n\t\tdouble\t\tGetMean() const;\n\t\tdouble\t\tGetVar() const;\n\t\tdouble\t\tGetStdDev() const;\n\t\tdouble\t\tGetCDF(double x) const;\n\t\tdouble\t\tSample() const;\n\t\tdouble\t\tGetLnPDF(double x) const;\n\t\tdouble\t\tGetRelativeLnPDF(double x) const;\n\t\tvoid\t\tSetMeanAndVariance(double mean, double var);\n\n\tprotected:\n\t\tvoid\t\t\tComputeLnConst();\n\n\tprotected:\n\t\tdouble\t\tmean;\t\t\t/**< the mean parameter of the normal distribution */\n\t\tdouble\t\tsd;\t\t\t\t/**< the standard deviation parameter of the normal distribution */\n\t\tdouble\t\tln_const;\t\t/**< the natural logarithm of the constant part of the density function */\n\t\tdouble\t\tpi_const;\t\t/**< precalculated (in constructor) value of pi */\n\t\tdouble\t\tsqrt2_const;\t/**< precalculated (in constructor) value of sqrt(2.0) */\n\n\t};\n\n} // namespace phycas\n\n#endif\n", "meta": {"hexsha": "8cf997f49057a9e10ee1650f7e97f6ad9c4e8e7c", "size": 15355, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/probability_distribution.hpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/probability_distribution.hpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_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/probability_distribution.hpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 38.5804020101, "max_line_length": 164, "alphanum_fraction": 0.622403126, "num_tokens": 3252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5357971481609426}}
{"text": "#include <stan/math/prim.hpp>\n#include <test/unit/math/prim/prob/vector_rng_test_helper.hpp>\n#include <test/unit/math/prim/prob/util.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <limits>\n#include <vector>\n\nclass SkewDoubleExponentialTestRig : public VectorRNGTestRig {\n public:\n  SkewDoubleExponentialTestRig()\n      : VectorRNGTestRig(10000, 10, {-2.5, -1.7, -0.1, 0.1, 2.0},\n                         {-3, -2, -1, 0, 2, 6}, {}, {}, {0.1, 1.0, 2.5, 4.0},\n                         {1, 2, 3, 4}, {-2.7, -1.5, -0.5, 0.0}, {-3, -2, -1, 0},\n                         {0.5}, {0}, {-0.1, 1.1}, {}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& mu, const T2& sigma, const T3& tau,\n                        T_rng& rng) const {\n    return stan::math::skew_double_exponential_rng(mu, sigma, tau, rng);\n  }\n};\n\ndouble icdf(double z, double mu, double sigma, double tau) {\n  if (z < tau) {\n    return log(z / tau) * sigma / (2.0 * (1.0 - tau)) + mu;\n  } else {\n    return log((1.0 - z) / (1.0 - tau)) * (-sigma) / (2.0 * tau) + mu;\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential, errorCheck) {\n  check_dist_throws_all_types(SkewDoubleExponentialTestRig());\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential, error_check) {\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::skew_double_exponential_rng(10.0, 2.0, .1, rng));\n\n  EXPECT_THROW(stan::math::skew_double_exponential_rng(10.0, 2.0, -1.0, rng),\n               std::domain_error);\n  EXPECT_THROW(stan::math::skew_double_exponential_rng(\n                   10, 2, stan::math::positive_infinity(), rng),\n               std::domain_error);\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential, test_sampling_icdf) {\n  for (double p : {0.0, 0.1, 0.2, 0.5, 0.7, 0.9, 0.99}) {\n    for (double mu : {-1.11, 0.13, 1.2, 4.67}) {\n      for (double sigma : {0.11, 1.33}) {\n        for (double tau : {0.1, 0.4, 0.77, 0.89}) {\n          double x = icdf(p, mu, sigma, tau);\n          EXPECT_FLOAT_EQ(\n              stan::math::skew_double_exponential_cdf(x, mu, sigma, tau), p);\n        }\n      }\n    }\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int N = 10000;\n  int K = stan::math::round(2 * std::pow(N, 0.4));\n\n  std::vector<double> samples;\n  for (int i = 0; i < N; ++i) {\n    samples.push_back(\n        stan::math::skew_double_exponential_rng(2.0, 1.0, 0.25, rng));\n  }\n  std::vector<double> quantiles;\n  for (int i = 1; i < K; ++i) {\n    double frac = static_cast<double>(i) / K;\n    quantiles.push_back(icdf(frac, 2.0, 1.0, 0.25));\n  }\n  quantiles.push_back(std::numeric_limits<double>::max());\n\n  // Assert that they match\n  assert_matches_quantiles(samples, quantiles, 1e-6);\n}\n", "meta": {"hexsha": "3c9b27bc0a1634e587c77ec41af7110ca0c6cb08", "size": 2833, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/skew_double_exponential_test.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/math/prim/prob/skew_double_exponential_test.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": "test/unit/math/prim/prob/skew_double_exponential_test.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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.5487804878, "max_line_length": 80, "alphanum_fraction": 0.6092481468, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5356075671709931}}
{"text": "/* Copyright \u00a9 2017 Apple Inc. All rights reserved.\n *\n * Use of this source code is governed by a BSD-3-clause license that can\n * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n */\n#define BOOST_TEST_MODULE\n#include <boost/test/unit_test.hpp>\n#include <util/test_macros.hpp>\n#include <vector>\n#include <cmath>\n\n#include <iostream>\n#include <logger/logger.hpp>\n#include <logger/assertions.hpp>\n#include <util/bitops.hpp>\n#include <util/cityhash_tc.hpp>\n#include <util/fast_integer_power.hpp>\n\nusing namespace turi;\nusing namespace std;\n\nstruct fast_power_test  {\n public:\n  void _run_test(double v, const std::vector<size_t>& powers) {\n\n    fast_integer_power vp(v);\n\n    for(size_t n : powers) {\n      double v_ref = std::pow(v, n);\n      double v_check = vp.pow(n);\n\n      if(abs(v_ref - v_check) / (1.0 + ceil(v_ref + v_check) ) > 1e-8 ) {\n        std::ostringstream ss;\n        ss << \"Wrong value: \"\n           << v << \" ^ \" << n << \" = \" << v_ref\n           << \"; retrieved = \" << v_check << std::endl;\n\n        ASSERT_MSG(false, ss.str().c_str());\n      }\n    }\n  }\n\n  void test_low_powers() {\n    _run_test(0.75, {0, 1, 2, 3, 4, 5, 6, 7, 8});\n  }\n\n  void test_lots_of_powers() {\n    std::vector<size_t> v(5000);\n\n    for(size_t i = 0; i < 5000; ++i)\n      v[i] = i;\n\n    _run_test(0.99, v);\n    _run_test(1.02, v);\n  }\n\n  void test_many_random() {\n    std::vector<size_t> v(50000);\n\n    for(size_t i = 0; i < 50000; ++i)\n      v[i] = hash64(i);\n\n    _run_test(1 - 1e-6, v);\n    _run_test(1 + 1e-6, v);\n  }\n};\n\nBOOST_FIXTURE_TEST_SUITE(_fast_power_test, fast_power_test)\nBOOST_AUTO_TEST_CASE(test_low_powers) {\n  fast_power_test::test_low_powers();\n}\nBOOST_AUTO_TEST_CASE(test_lots_of_powers) {\n  fast_power_test::test_lots_of_powers();\n}\nBOOST_AUTO_TEST_CASE(test_many_random) {\n  fast_power_test::test_many_random();\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "998a8f6a30618a81c020a1a59015b554e24ed6af", "size": 1893, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/util/fast_power_test.cxx", "max_stars_repo_name": "LeeCenY/turicreate", "max_stars_repo_head_hexsha": "fb2f3bf313e831ceb42a2e10aacda6e472ea8d93", "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/util/fast_power_test.cxx", "max_issues_repo_name": "LeeCenY/turicreate", "max_issues_repo_head_hexsha": "fb2f3bf313e831ceb42a2e10aacda6e472ea8d93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-01-13T04:03:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T01:02:31.000Z", "max_forks_repo_path": "test/util/fast_power_test.cxx", "max_forks_repo_name": "ZeroInfinite/turicreate", "max_forks_repo_head_hexsha": "dd210c2563930881abd51fd69cb73007955b33fd", "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.9620253165, "max_line_length": 86, "alphanum_fraction": 0.6428948759, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5356075546606189}}
{"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, fma_double) {\n  using stan::math::fma;\n  EXPECT_FLOAT_EQ(1.0, fma(3.0, 2.0, -5));\n  EXPECT_FLOAT_EQ(0.0, fma(2.0, 3.0, -6));\n  EXPECT_FLOAT_EQ(46.9, fma(4.5, 2.0, 37.9));\n}\n\nTEST(MathFunctions, fma_int) {\n  using stan::math::fma;\n  EXPECT_FLOAT_EQ(\n      11.0, fma(static_cast<int>(3), static_cast<int>(2), static_cast<int>(5)));\n}\n\nTEST(MathFunctions, fma_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::fma(nan, 3.0, 2.7));\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::fma(3.0, nan, 1.5));\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::fma(2, -8.2, nan));\n}\n", "meta": {"hexsha": "8702b5f9e63c7a9882321334ca953e9995785830", "size": 804, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/fma.hpp", "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/fma.hpp", "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/fma.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": 32.16, "max_line_length": 80, "alphanum_fraction": 0.6766169154, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.5356075533906423}}
{"text": "#include <boost/assign/std/vector.hpp>\n#include <cradle/anonymous.hpp>\n#include <cradle/geometry/polygonal.hpp>\n\n#include <cradle/test.hpp>\n\nusing namespace cradle;\nusing namespace boost::assign;\n\n// polygon2\n\nTEST_CASE(\"simple_ccw_poly_test\")\n{\n    polygon2 poly;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(0, 0), make_vector<double>(5, 0),\n            make_vector<double>(2, 2), make_vector<double>(0, 2);\n        initialize(&poly.vertices, vertices);\n    }\n    CRADLE_CHECK_ALMOST_EQUAL(get_area(poly), 7.);\n    REQUIRE(!is_inside(poly, make_vector<double>(-1, 1)));\n    REQUIRE(is_inside(poly, make_vector<double>(1, 1)));\n}\n\nTEST_CASE(\"simple_cw_poly_test\")\n{\n    polygon2 poly;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(0, 0), make_vector<double>(0, 2),\n            make_vector<double>(2, 2), make_vector<double>(5, 0);\n        initialize(&poly.vertices, vertices);\n    }\n    CRADLE_CHECK_ALMOST_EQUAL(get_area(poly), 7.);\n    REQUIRE(!is_inside(poly, make_vector<double>(-1, 1)));\n    REQUIRE(is_inside(poly, make_vector<double>(1, 1)));\n}\n\nTEST_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), make_vector<double>(-1, 0, 0));\n}\n\nTEST_CASE(\"square_test\")\n{\n    polygon2 poly;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-2, -2), make_vector<double>(-2, 2),\n            make_vector<double>(2, 2), make_vector<double>(2, -2);\n        initialize(&poly.vertices, vertices);\n    }\n    CRADLE_CHECK_ALMOST_EQUAL(get_area(poly), 16.);\n    REQUIRE(!is_inside(poly, make_vector<double>(-3, 3)));\n    REQUIRE(is_inside(poly, make_vector<double>(-1, 1)));\n}\n\nTEST_CASE(\"concave_poly_test\")\n{\n    polygon2 poly;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-2, -2), make_vector<double>(-2, 2),\n            make_vector<double>(2, 2), 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    REQUIRE(!is_inside(poly, make_vector<double>(-3, 3)));\n    REQUIRE(!is_inside(poly, make_vector<double>(1, 0)));\n    REQUIRE(is_inside(poly, make_vector<double>(-1, 1)));\n}\n\nTEST_CASE(\"edge_view_test\")\n{\n    polygon2 poly;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(0, 0), make_vector<double>(0, 1),\n            make_vector<double>(1, 1);\n        initialize(&poly.vertices, vertices);\n    }\n\n    vertex2_array::const_iterator vertex_i = poly.vertices.begin(),\n                                  vertex_j = poly.vertices.end() - 1;\n    for (polygon2_edge_view ev(poly); !ev.done();\n         ev.advance(), vertex_j = vertex_i++)\n    {\n        REQUIRE(ev.p0() == *vertex_j);\n        REQUIRE(ev.p1() == *vertex_i);\n    }\n}\n\nTEST_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 += make_vector<double>(2, 0),\n        make_vector<double>(srt, srt), make_vector<double>(0, 2),\n        make_vector<double>(-srt, srt), make_vector<double>(-2, 0),\n        make_vector<double>(-srt, -srt), make_vector<double>(0, -2),\n        make_vector<double>(srt, -srt);\n\n    CRADLE_CHECK_RANGES_ALMOST_EQUAL(poly.vertices, correct_vertices);\n}\n\nTEST_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 += make_vector<double>(0, 0), make_vector<double>(2, 0),\n        make_vector<double>(2, 2), make_vector<double>(0, 2);\n\n    CRADLE_CHECK_RANGES_ALMOST_EQUAL(poly.vertices, correct_vertices);\n}\n\n// polyset\n\nstatic double const tolerance = 0.00001;\n\nTEST_CASE(\"two_polygons_test\")\n{\n    polygon2 poly0, poly1;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-2, -2), make_vector<double>(-2, 2),\n            make_vector<double>(2, 2), make_vector<double>(2, -2);\n        initialize(&poly0.vertices, vertices);\n    }\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(4, 4), make_vector<double>(4, 5),\n            make_vector<double>(5, 5), 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    REQUIRE(!is_inside(region, make_vector<double>(-3, 3)));\n    REQUIRE(!is_inside(region, make_vector<double>(3, 3)));\n    REQUIRE(!is_inside(region, make_vector<double>(6, 6)));\n    REQUIRE(is_inside(region, make_vector<double>(-1, 1)));\n    REQUIRE(is_inside(region, make_vector<double>(4.5, 4.5)));\n    REQUIRE(is_inside(region, make_vector<double>(0, 0)));\n}\n\nTEST_CASE(\"polygon_with_hole_test\")\n{\n    polygon2 poly, hole;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-2, -2), make_vector<double>(-2, 2),\n            make_vector<double>(2, 2), make_vector<double>(2, -2);\n        initialize(&poly.vertices, vertices);\n    }\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-1, -1), make_vector<double>(-1, 1),\n            make_vector<double>(1, 1), 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    REQUIRE(!is_inside(frame, make_vector<double>(-3, 3)));\n    REQUIRE(!is_inside(frame, make_vector<double>(0, 0)));\n    REQUIRE(is_inside(frame, make_vector<double>(-1.5, 1.5)));\n}\n\nTEST_CASE(\"polyset_as_polygon_list_test\")\n{\n    polygon2 outside, hole, inside;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-3, -3), make_vector<double>(-3, 3),\n            make_vector<double>(3, 3), make_vector<double>(3, -3);\n        initialize(&outside.vertices, vertices);\n    }\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-2, -2), make_vector<double>(-2, 2),\n            make_vector<double>(2, 2), make_vector<double>(2, -2);\n        initialize(&hole.vertices, vertices);\n    }\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-1, -1), make_vector<double>(-1, 1),\n            make_vector<double>(1, 1), 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    REQUIRE(polys.size() == 2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(\n        get_area(polys[0]) + get_area(polys[1]), 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(\n        get_area(reconstructed), get_area(frame), tolerance);\n}\n\nTEST_CASE(\"polyset_set_operations_test\")\n{\n    polygon2 p;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-6, -3), make_vector<double>(-6, 3),\n            make_vector<double>(6, 3), 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 += make_vector<double>(-3, -6), make_vector<double>(-3, 6),\n            make_vector<double>(3, 6), 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(\n        &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 += make_vector<double>(-1, -1), make_vector<double>(-1, 1),\n            make_vector<double>(1, 1), 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    REQUIRE(!is_inside(cross, make_vector<double>(0, 0)));\n    REQUIRE(is_inside(cross, make_vector<double>(2, 0)));\n    REQUIRE(!is_inside(cross, make_vector<double>(8, 0)));\n    REQUIRE(is_inside(cross, make_vector<double>(0, -5)));\n}\n\nTEST_CASE(\"polyset_comparisons_test\")\n{\n    polygon2 poly1, poly2;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-2, -2), make_vector<double>(-2, 2),\n            make_vector<double>(2, 2), make_vector<double>(2, -2);\n        initialize(&poly1.vertices, vertices);\n    }\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-1, -1), make_vector<double>(-1, 1),\n            make_vector<double>(1, 1), 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    REQUIRE(almost_equal(region1, region2, 0.001));\n    REQUIRE(!almost_equal(region1, region3, 0.001));\n}\n\n// structure_geometry\n\nTEST_CASE(\"structure_geometry_test0\")\n{\n    polyset area0, area1, area2;\n\n    add_polygon(\n        area0,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(0, 0),\n            make_vector<double>(0, 6),\n            make_vector<double>(3, 3))));\n    REQUIRE(area0.polygons.size() == 1);\n\n    add_polygon(\n        area1,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(1, 0),\n            make_vector<double>(0, 0),\n            make_vector<double>(0, 1))));\n    add_polygon(\n        area1,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(1, 3),\n            make_vector<double>(0, 3),\n            make_vector<double>(0, 4))));\n    REQUIRE(area1.polygons.size() == 2);\n\n    add_polygon(\n        area2,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(0, 0),\n            make_vector<double>(0, 1),\n            make_vector<double>(1, 0))));\n    add_polygon(\n        area2,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(2, 0),\n            make_vector<double>(2, 1),\n            make_vector<double>(3, 0))));\n    add_polygon(\n        area2,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(4, 0),\n            make_vector<double>(4, 1),\n            make_vector<double>(5, 0))));\n    REQUIRE(area2.polygons.size() == 3);\n\n    structure_geometry volume;\n    volume.slices += 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    REQUIRE(get_slice(volume, -0.8) == 0);\n    REQUIRE(get_slice(volume, -0.7) != 0);\n    REQUIRE(get_slice(volume, 3.7) != 0);\n    REQUIRE(get_slice(volume, 3.8) == 0);\n\n    REQUIRE(get_slice(volume, 1)->position == 1.5);\n    REQUIRE(get_slice(volume, 1)->region.polygons.size() == 2);\n    REQUIRE(get_slice(volume, 2.5)->position == 3);\n    REQUIRE(get_slice(volume, 2.5)->region.polygons.size() == 3);\n\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(volume), 17.25, tolerance);\n}\n\nTEST_CASE(\"structure_geometry_test1\")\n{\n    polyset area0, area1, area2, area3;\n\n    add_polygon(\n        area0,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(0, 0),\n            make_vector<double>(0, 6),\n            make_vector<double>(3, 3))));\n\n    add_polygon(\n        area1,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(1, 0),\n            make_vector<double>(0, 0),\n            make_vector<double>(0, 1))));\n    add_polygon(\n        area1,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(1, 3),\n            make_vector<double>(0, 3),\n            make_vector<double>(0, 4))));\n\n    add_polygon(\n        area2,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(0, 0),\n            make_vector<double>(0, 1),\n            make_vector<double>(1, 0))));\n    add_polygon(\n        area2,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(2, 0),\n            make_vector<double>(2, 1),\n            make_vector<double>(3, 0))));\n\n    add_polygon(\n        area3,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(4, 0),\n            make_vector<double>(4, 1),\n            make_vector<double>(5, 0))));\n\n    structure_geometry volume1;\n    volume1.slices += 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 += 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    REQUIRE(almost_equal(volume2, volume2, tolerance));\n    REQUIRE(!almost_equal(volume1, volume2, tolerance));\n}\n\nTEST_CASE(\"set_operation_test\")\n{\n    polyset area0, area1, area2, area3, area4, area5;\n\n    add_polygon(\n        area0,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(0, 0),\n            make_vector<double>(0, 5),\n            make_vector<double>(4, 5),\n            make_vector<double>(4, 0))));\n    add_polygon(\n        area1,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(0, 0),\n            make_vector<double>(0, 5),\n            make_vector<double>(4, 5),\n            make_vector<double>(4, 0))));\n    add_polygon(\n        area2,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(0, 0),\n            make_vector<double>(0, 5),\n            make_vector<double>(4, 5),\n            make_vector<double>(4, 0))));\n\n    add_polygon(\n        area3,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(6, 0),\n            make_vector<double>(6, 5),\n            make_vector<double>(10, 5),\n            make_vector<double>(10, 0))));\n    add_polygon(\n        area4,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(2, 0),\n            make_vector<double>(2, 5),\n            make_vector<double>(6, 5),\n            make_vector<double>(6, 0))));\n    add_polygon(\n        area5,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(0, 0),\n            make_vector<double>(0, 5),\n            make_vector<double>(4, 5),\n            make_vector<double>(4, 0))));\n\n    {\n        structure_geometry volume1;\n        volume1.slices += 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 += 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(\n            &intersection, set_operation::INTERSECTION, volume1, volume2);\n        CRADLE_CHECK_WITHIN_TOLERANCE(\n            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(\n            &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 += 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        REQUIRE_THROWS_AS(\n            do_set_operation(\n                &result, set_operation::UNION, 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        REQUIRE_THROWS_AS(\n            do_set_operation(\n                &result, set_operation::UNION, 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        REQUIRE_THROWS_AS(\n            do_set_operation(\n                &result, set_operation::UNION, volume, mismatched_volume3),\n            std::exception);\n    }\n\n    {\n        structure_geometry volume1;\n        volume1.slices += 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 += 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(\n            &intersection, set_operation::INTERSECTION, volume1, volume2);\n        CRADLE_CHECK_WITHIN_TOLERANCE(\n            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(\n            &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 += 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 += 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(\n            &intersection, set_operation::INTERSECTION, volume1, volume2);\n        CRADLE_CHECK_WITHIN_TOLERANCE(\n            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(\n            &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 += 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 += 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(\n            &intersection, set_operation::INTERSECTION, volume1, volume2);\n        CRADLE_CHECK_WITHIN_TOLERANCE(\n            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(\n            &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 += 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 += 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(\n            &intersection, set_operation::INTERSECTION, volume1, volume2);\n        CRADLE_CHECK_WITHIN_TOLERANCE(\n            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(\n            &difference, set_operation::DIFFERENCE, volume1, volume2);\n        CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(difference), 90., tolerance);\n    }\n}\n\nTEST_CASE(\"expansion_2d\")\n{\n    polyset area0, area1, area2, area3;\n\n    add_polygon(\n        area1,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(0, 0),\n            make_vector<double>(6, 0),\n            make_vector<double>(6, 6),\n            make_vector<double>(0, 6))));\n\n    add_polygon(\n        area2,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(0, 0),\n            make_vector<double>(1, 0),\n            make_vector<double>(1, 1),\n            make_vector<double>(0, 1))));\n\n    structure_geometry original;\n    original.slices += 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    REQUIRE(get_volume(expanded) > 65);\n    REQUIRE(get_volume(expanded) < 83);\n    REQUIRE(is_inside(expanded, make_vector<double>(6.9, 1, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(-0.9, 1, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(1, 6.9, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(1, -0.9, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(-0.7, -0.7, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(6.7, -0.7, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(6.7, 6.7, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(-0.7, 6.7, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(1.9, 1, 2)));\n    REQUIRE(is_inside(expanded, make_vector<double>(-0.9, 1, 2)));\n    REQUIRE(is_inside(expanded, make_vector<double>(1, 1.9, 2)));\n    REQUIRE(is_inside(expanded, make_vector<double>(1, -0.9, 2)));\n    REQUIRE(is_inside(expanded, make_vector<double>(-0.7, -0.7, 2)));\n    REQUIRE(is_inside(expanded, make_vector<double>(1.7, -0.7, 2)));\n    REQUIRE(is_inside(expanded, make_vector<double>(1.7, 1.7, 2)));\n    REQUIRE(is_inside(expanded, make_vector<double>(-0.7, 1.7, 2)));\n}\n\nTEST_CASE(\"expansion_3d\")\n{\n    polyset area0, area1, area2, area3;\n\n    add_polygon(\n        area1,\n        make_polygon2(anonymous<std::vector<vector2d>>(\n            make_vector<double>(0, 0),\n            make_vector<double>(6, 0),\n            make_vector<double>(6, 6),\n            make_vector<double>(0, 6))));\n\n    structure_geometry original;\n    original.slices += 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    REQUIRE(get_volume(expanded) > 136);\n    REQUIRE(get_volume(expanded) < 197);\n    REQUIRE(is_inside(expanded, make_vector<double>(6.9, 1, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(-0.9, 1, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(1, 6.9, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(1, -0.9, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(-0.7, -0.7, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(6.7, -0.7, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(6.7, 6.7, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(-0.7, 6.7, 1)));\n    REQUIRE(is_inside(expanded, make_vector<double>(0, 0, 0)));\n    REQUIRE(is_inside(expanded, make_vector<double>(6, 0, 0)));\n    REQUIRE(is_inside(expanded, make_vector<double>(6, 6, 0)));\n    REQUIRE(is_inside(expanded, make_vector<double>(0, 6, 0)));\n    REQUIRE(is_inside(expanded, make_vector<double>(0, 0, 2)));\n    REQUIRE(is_inside(expanded, make_vector<double>(6, 0, 2)));\n    REQUIRE(is_inside(expanded, make_vector<double>(6, 6, 2)));\n    REQUIRE(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\nTEST_CASE(\"polygon_bounding_box_test\")\n{\n    polygon2 poly;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(0, 0), make_vector<double>(-1, -1),\n            make_vector<double>(-3, 0), make_vector<double>(0, 7),\n            make_vector<double>(3, 3), make_vector<double>(3, 2);\n        initialize(&poly.vertices, vertices);\n    }\n    REQUIRE(\n        bounding_box(poly)\n        == box2d(make_vector<double>(-3, -1), make_vector<double>(6, 8)));\n}\n\nTEST_CASE(\"polyset_bounding_box_test\")\n{\n    polygon2 p;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-6, -3), make_vector<double>(-6, 3),\n            make_vector<double>(-4, 3), 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 += make_vector<double>(2, -6), make_vector<double>(2, -2),\n            make_vector<double>(4, -2), 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    REQUIRE(almost_equal(bb.corner, make_vector<double>(-6, -6), 0.00001));\n    REQUIRE(almost_equal(bb.size, make_vector<double>(10, 9), 0.00001));\n}\n", "meta": {"hexsha": "dd1fc7f3cac490cc150cee8dadb0a101f08cf565", "size": 30353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "disabled/unit_tests/geometry/polygonal.cpp", "max_stars_repo_name": "mghro/astroid-core", "max_stars_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "disabled/unit_tests/geometry/polygonal.cpp", "max_issues_repo_name": "mghro/astroid-core", "max_issues_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-10-26T18:45:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T18:46:06.000Z", "max_forks_repo_path": "disabled/unit_tests/geometry/polygonal.cpp", "max_forks_repo_name": "mghro/astroid-core", "max_forks_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3944844125, "max_line_length": 78, "alphanum_fraction": 0.6367410141, "num_tokens": 7986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5355670695538767}}
{"text": "/*\n * Copyright (c) 2011-2014 Burkhard Ritter\n * This code is distributed under the two-clause BSD License.\n */\n#ifndef __SYSTEM_HPP__\n#define __SYSTEM_HPP__\n\n#include <iostream>\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include \"basis.hpp\"\nusing namespace Eigen;\n\ntypedef SparseMatrix<double> SMatrix;\ntypedef MatrixXd DMatrix;\ntypedef VectorXd DVector;\n\nenum Spin {UP=0, DOWN=1};\n\n/**\n * Caching creator. \n *\n * Constructs one creator martrix for each orbital of the system and caches\n * them.\n *\n * @tparam System\n */\ntemplate<class System>\nclass Creator\n{\npublic:\n    Creator (const System& s_)\n    : s(s_)\n    {}\n\n    void construct ()\n    {\n        const size_t N_orbital = s.basis.numberOfOrbitals();\n        cs = std::vector<SMatrix>(N_orbital);\n        for (size_t i=0; i<N_orbital; i++)\n            constructMatrix(i);\n    }\n\n    /**\n     * Creator matrix for the given orbital.\n     *\n     * \\f$c^{\\dag}_i\\f$\n     *\n     * @param i orbital of the system\n     *\n     * @return \n     */\n    const SMatrix& operator() (int i) const\n    {\n        return cs[i];\n    }\n\nprivate:\n    // TODO: update to use Eigen's new SparseMatrix interface\n    void constructMatrix (int i)\n    {\n        cs[i] = SMatrix(s.basis.size(), s.basis.size());\n        // we expect one entry per column\n        cs[i].reserve(VectorXi::Constant(s.basis.size(),1));\n        for (size_t col=0; col<s.basis.size(); col++)\n        {\n            if (s.basis(col)[i] == 1)\n                continue;\n            State state(s.basis(col));\n            state[i] = 1;\n            const size_t row = s.basis(state);\n            const size_t sum = state.count(i);\n            const double sign = (sum%2==0)?1:-1; // probably faster than using (-1)^sum\n            cs[i].insert(row, col) = sign;\n        }\n        cs[i].makeCompressed();\n    }\n\n    const System& s;\n    std::vector<SMatrix> cs;\n};\n\n/**\n * Caching annihilator.\n *\n * Constructs one annihilator matrix for each orbital of the system and caches\n * them.\n *\n * @tparam System\n */\ntemplate<class System>\nclass Annihilator\n{\npublic:\n    Annihilator (const System& s_)\n    : s(s_)\n    {}\n\n    void construct ()\n    {\n        const size_t N_orbital = s.basis.numberOfOrbitals();\n        as = std::vector<SMatrix>(N_orbital);\n        for (size_t i=0; i<N_orbital; i++)\n            as[i] = SMatrix(s.creator(i).transpose());\n    }\n\n    /**\n     * Annihilator matrix for the given orbital.\n     *\n     * \\f$c_i\\f$\n     *\n     * @param i orbital of the system\n     *\n     * @return \n     */\n    const SMatrix& operator() (int i) const\n    {\n        return as[i];\n    }\n\nprivate:\n    const System& s;\n    std::vector<SMatrix> as;\n};\n\n/**\n * Hamiltonian of the system.\n *\n * The heart of the fermionic quantum system. Although it is an\n * operator it behaves a little bit different than the other operators, which\n * maybe doesn't entirely come as a surprise. It is\n * not a function object. It has to be subclassed and\n * overwritten for each different physical system. Typical usage:\n * @code\n * Hamiltonian H(mySystem);\n * H.construct();\n * H.diagonalize(); //here the real work happens\n * H.eigenvalues(); //use eigenenergies\n * @endcode\n *\n * @tparam System\n */\ntemplate<class System>\nclass Hamiltonian\n{\nprotected:\n    class SortIndicesAccordingToSizeOfRanges\n    {\n    public:\n        SortIndicesAccordingToSizeOfRanges (const std::vector<Range>& rs_)\n            : rs(rs_) \n        {}\n\n        bool operator() (size_t i, size_t j) const\n        {\n            return (rs[i].b-rs[i].a)>(rs[j].b-rs[j].a);\n        }\n\n    private:\n        const std::vector<Range>& rs;\n    };\n\n    System& s;\n    SMatrix H;\n    DVector es; // eigenvalues\n    // SMatrix vs; // eigenvalues, unused\n    std::vector<DVector> es_s; // eigenvalues, sector-wise\n    std::vector<DMatrix> vs_s; // eigenvectors, sector-wise\n    double E_min;\n\npublic:\n    Hamiltonian (System& s_)\n    : s(s_), H(), E_min(0)\n    {}\n\n    /**\n     * Construct the Hamiltonian matrix.\n     *\n     * Has to be overwritten by deriving classes.\n     */\n    void construct() {}\n\n    /**\n     * Diagonalizes the Hamiltonian matrix using symmetries.\n     *\n     * The Hamiltonian is diagonalized block-wise. Consequently, eigenvalues and\n     * eigenvectors should be accessed via the eigenvaluesBySector and\n     * eigenvectorsBySector methods.\n     */\n    void diagonalize ()\n    {\n        es.resize(0);\n        const std::vector<Range>& rs = s.basis.getRanges();\n        es_s.resize(rs.size());\n        vs_s.resize(rs.size());\n        std::vector<size_t> is(rs.size());\n        for (size_t i=0; i<is.size(); i++)\n            is[i] = i;\n        std::sort(is.begin(), is.end(), SortIndicesAccordingToSizeOfRanges(rs));\n\n        const size_t n_largest = rs[is[0]].b-rs[is[0]].a;\n        SelfAdjointEigenSolver<DMatrix> s(n_largest);\n        \n        for (size_t i=0; i<is.size(); i++)\n        {\n            const int a = rs[is[i]].a;\n            const int b = rs[is[i]].b;\n            // useful debug output when diagonalizing very large Hamiltonians\n            // std::cerr << \"-> \" << \"Diagonalizing range \" << is[i] << \" out of \" \n            //           << rs.size() << \" ranges.\" << std::endl\n            //           << \"-> Size of range \" << is[i] << \": \" << b-a << std::endl;\n            assert(4E9 > (b-a)*(b-a)*sizeof(double));\n            s.compute(H.block(a,a,b-a,b-a));\n            es_s[is[i]] = s.eigenvalues();\n            vs_s[is[i]] = s.eigenvectors();\n        }\n        E_min = es_s[0].minCoeff();\n        for (size_t i=1; i<es_s.size(); i++)\n            if (es_s[i].minCoeff() < E_min) \n                E_min = es_s[i].minCoeff();\n    }\n\n    const std::vector<DVector>& eigenvaluesBySector ()\n    {\n        return es_s;\n    }\n\n    const std::vector<DMatrix>& eigenvectorsBySector ()\n    {\n        return vs_s;\n    }\n\n    const DVector& eigenvalues ()\n    {\n        if (es.size() == 0 && es_s.size() > 0)\n        {\n            es.resize(H.rows());\n            int k=0;\n            for (size_t i=0; i<es_s.size(); i++)\n                for (int j=0; j<es_s[i].size(); j++)\n                {\n                    assert(k<es.size());\n                    es(k) = es_s[i](j);\n                    k++;\n                }\n        }\n        return es;\n    }\n\n    double Emin () const\n    {\n        return E_min;\n    }\n};\n\n/**\n * Calculate the ensemble average \"by sectors\".\n *\n * \"By sectors\" essentially means that the eigenvalues are accessed as an\n * std::vector of dense vectors and the eigenvectors are accessed as an\n * std::vector of dense matrices. Hence this class should be used whenever\n * Hamiltonian::diagonlize is used, for best performance. Example usage:\n * @code\n * EnsembleAverage ensembleAverage(mySystem);\n * MyFunkyOperator O(mySystem);\n * ensembleAverage(beta, O); //will expect and use mySystem.H\n * @endcode\n *\n * Dependencies: System.basis and System.H (Hamiltonian)\n *\n * @tparam System\n */\ntemplate<class System>\nclass EnsembleAverage\n{\npublic:\n    EnsembleAverage (System& s_)\n    : s(s_)\n    {}\n\n    /**\n     * Calculate the ensemble average for the given operator.\n     *\n     * @param beta = 1/T (temperature)\n     * @param O operator matrix\n     *\n     * @return \n     */\n    double operator() (double beta, const SMatrix& O) const\n    {\n        double sum = 0;\n        size_t index = 0;\n        const std::vector<DVector>& eigenvalues = s.H.eigenvaluesBySector();\n        const std::vector<DMatrix>& eigenvectors = s.H.eigenvectorsBySector();\n        for (size_t i=0; i<eigenvalues.size(); i++)\n        {\n            // note: usually O is very sparse, so it is essential to use a\n            // sparse matrix for the block\n            const int size = eigenvalues[i].size();\n            const SMatrix& O_block = O.block(index,index,size,size);\n            for (int j=0; j<size; j++)\n                sum += \n                    std::exp(-beta * (eigenvalues[i](j) - s.H.Emin())) * \n                    eigenvectors[i].col(j).adjoint() * O_block * eigenvectors[i].col(j);\n            index += size;\n        }\n        return sum / partitionFunction(beta);\n    }\n\n    /**\n     * Calculate the partition function at the given temperature.\n     *\n     * @param beta = 1/T (temperature)\n     *\n     * @return \n     */\n    double partitionFunction (double beta) const\n    {\n        double Z = 0;\n        const std::vector<DVector>& eigenvalues = s.H.eigenvaluesBySector();\n        for (size_t i=0; i<eigenvalues.size(); i++)\n            for (int j=0; j<eigenvalues[i].size(); j++)\n                Z += std::exp(-beta * (eigenvalues[i](j) - s.H.Emin()));\n        return Z;\n    }\n\nprivate:\n    System& s;\n};\n\n#endif // __SYSTEM_HPP__\n", "meta": {"hexsha": "966651131f9ae4a060943aa46ca244200ab15b03", "size": 8674, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/system.hpp", "max_stars_repo_name": "meznom/qca", "max_stars_repo_head_hexsha": "8b7cfa6f36ab17202fce5bb953321d33abdf9eb7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-07-11T01:56:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-03T09:13:07.000Z", "max_issues_repo_path": "src/system.hpp", "max_issues_repo_name": "meznom/qca", "max_issues_repo_head_hexsha": "8b7cfa6f36ab17202fce5bb953321d33abdf9eb7", "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/system.hpp", "max_forks_repo_name": "meznom/qca", "max_forks_repo_head_hexsha": "8b7cfa6f36ab17202fce5bb953321d33abdf9eb7", "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.048048048, "max_line_length": 88, "alphanum_fraction": 0.5598339866, "num_tokens": 2269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.5355670642688273}}
{"text": "/// NTL Wrappers\n///\n/// The functions in this module wrap a select few functions for lattice\n/// reduction in NTL. They take matrices with 'int64_t' elements, but use\n/// unlimited precision internally.\n\n#include <climits>\n#include <string>\n#include <fstream>\n#include <stdexcept>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include \"NTL/matrix.h\"\n#include \"NTL/ZZ.h\"\n#include \"NTL/LLL.h\"\n\n#include \"debug.h\"\n#include \"types.h\"\n\n#include \"ntl_wrapper.h\"\n\nusing std::string;\nusing std::ifstream;\nusing std::runtime_error;\nusing boost::numeric::ublas::matrix;\nusing NTL::Mat;\nusing NTL::Vec;\nusing NTL::ZZ;\n\n\n/////////////////////////////////////////////////////////////////////\n/// LLL reduction\n\n/// LLL reduction using exact arithmetic\n///\n/// This is the default used in BLT.\nint64 LLL(matrix<int64>& B, matrix<int64>& U) {\n    Mat<ZZ> ntlB;\n    Mat<ZZ> ntlU;\n    ZZ det2;\n\n    matrix_to_ntl(B, ntlB);\n    TRACE(\"lattice reduction method: LLL\");\n    int64 rank = NTL::LLL(det2, ntlB, ntlU);\n\n    ZZ det = SqrRoot(det2);\n    TRACE(\"reduced lattice det: \" << det);\n\n    ntl_to_matrix(ntlB, B);\n    ntl_to_matrix(ntlU, U);\n    return rank;\n}\n\n/// LLL_FP wrapper\n///\n/// This method is generally faster than 'LLL', but uses floating point\n/// arithmetic.\nint64 LLL_FP(matrix<int64>& B, matrix<int64>& U) {\n    Mat<ZZ> ntlB;\n    Mat<ZZ> ntlU;\n\n    matrix_to_ntl(B, ntlB);\n    TRACE(\"lattice reduction method: LLL_FP\");\n    int64 rank = NTL::LLL_FP(ntlB, ntlU);\n\n    ZZ det;\n    determinant(det, ntlB);\n    TRACE(\"reduced lattice det: \" << det);\n\n    ntl_to_matrix(ntlB, B);\n    ntl_to_matrix(ntlU, U);\n    return rank;\n}\n\n/// G_LLL_FP wrapper\n///\n/// This method is more stable than 'LLL_FP', but may take longer.\nint64 G_LLL_FP(matrix<int64>& B, matrix<int64>& U) {\n    Mat<ZZ> ntlB;\n    Mat<ZZ> ntlU;\n\n    matrix_to_ntl(B, ntlB);\n    TRACE(\"lattice reduction method: G_LLL_FP\");\n    int64 rank = NTL::G_LLL_FP(ntlB, ntlU);\n\n    ZZ det;\n    determinant(det, ntlB);\n    TRACE(\"reduced lattice det: \" << det);\n\n    ntl_to_matrix(ntlB, B);\n    ntl_to_matrix(ntlU, U);\n    return rank;\n}\n\n/////////////////////////////////////////////////////////////////////\n/// Utilities\n\n/// Estimate the number of solutions of a given lattice constraint pair.\n///\n/// If 'inv == true' then return value is ~1/expected_solns.\nlong expected_solns(const matrix<int64>& L, const matrix<int64>& C, bool& inv) {\n    Mat<ZZ> ntlL;\n    ZZ det;\n    matrix_to_ntl(L, ntlL);\n\n    // det computation must be done using unlimited precision\n    determinant(det, ntlL);\n    det = abs(det);\n\n    // volume computation must be done using unlimited precision\n    int64 r, maxr = 0;\n    ZZ vol(1L);\n    for (size_t i = 0; i < C.size1(); ++i) {\n        r = C(i,1) - C(i,0);\n        if (r <= 0)\n            TRACE(\"i=\" << i << \" C(i,0)=\" << C(i,0) << \" C(i,1)=\" << C(i,1));\n        assert(r > 0 && \"a constraint is inconsistent\");\n        vol *= r;\n        if (r > maxr)\n            maxr = r;\n    }\n    TRACE(\"orthotope radius: \" << (double)maxr/2.0);\n\n    ZZ q;\n    if (det <= vol) {\n        inv = false;\n        q = vol / det;\n    } else {\n        inv = true;\n        q = det / vol;\n    }\n    TRACE(\"NTL expected solutions = \" << (inv ? \"1 / \" : \"\") << q);\n    if (q >= LONG_MAX)\n        return LONG_MAX;\n    return to_long(q);\n}\n\n/////////////////////////////////////////////////////////////////////\n// Conversion\n\n// copy a matrix m into a mat_ZZ `n`; `n` is resized.\nvoid matrix_to_ntl(const matrix<int64>& m, Mat<ZZ>& n) {\n    size_t r = m.size1();  // num rows\n    size_t c = m.size2();  // num columns\n    if (r == 0 || c == 0) {\n        n.SetDims(0,0);\n        return;\n    }\n    n.SetDims(r, c);\n    for (size_t i=0; (int)i != n.NumRows(); i++) {\n        for (size_t j=0; (int)j != n.NumCols(); j++) {\n            n[i][j] = m(i, j);  // int64 -> ZZ coercion\n        }\n    }\n}\n\n// vice-versa: copy a Mat<ZZ> to a matrix<int64> with possible\n// loss of precision\nvoid ntl_to_matrix(const Mat<ZZ>& N, matrix<int64>& M) {\n    size_t r = N.NumRows();\n    size_t c = N.NumCols();\n    M.resize(r, c);\n    for (size_t i=0; i != M.size1(); i++) {\n        for (size_t j=0; j != M.size2(); j++) {\n            M(i, j) = to_long(N[i][j]);  // ZZ -> int64 coercion\n        }\n    }\n}\n\n\n/////////////////////////////////////////////////////////////////////\n// Misc\n\n\n// Return a view of n consisting of the first c columns\nMat<ZZ> take_cols(const Mat<ZZ>& n, size_t c) {\n    if ((int) c > n.NumCols())\n        return n;\n    size_t r = n.NumRows();\n    Mat<ZZ> ret;\n    ret.SetDims(r, c);\n    for (size_t i=0; i != r; i++) {\n        Vec<ZZ> t;\n        t.SetLength(c);\n        for (size_t j=0; j != c; j++) {\n            t[j] = n[i][j];\n        }\n        ret[i] = t;\n    }\n    return ret;\n}\n\n// Read a lattice from file into a Mat<ZZ> using NTLs >> operators\nMat<ZZ> read_lattice_ntl(string infile) {\n    ifstream in(infile.c_str());\n    if (!in)\n        throw runtime_error(\"could not open input file: \" + infile);\n    Mat<ZZ> N;\n    in >> N;\n    if (!in)\n        throw runtime_error(\"could not read matrix from input file: \" + infile);\n    return N;\n}\n", "meta": {"hexsha": "3145c4bea44c482ddfc305fc21082aa4bda7d15d", "size": 5105, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libblt/ntl_wrapper.cc", "max_stars_repo_name": "spazm/blt", "max_stars_repo_head_hexsha": "1bbe307309fa0090f6dd4240af65a18dd630e8ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2016-11-15T22:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T02:47:27.000Z", "max_issues_repo_path": "libblt/ntl_wrapper.cc", "max_issues_repo_name": "spazm/blt", "max_issues_repo_head_hexsha": "1bbe307309fa0090f6dd4240af65a18dd630e8ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-03-24T18:52:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T03:03:27.000Z", "max_forks_repo_path": "libblt/ntl_wrapper.cc", "max_forks_repo_name": "spazm/blt", "max_forks_repo_head_hexsha": "1bbe307309fa0090f6dd4240af65a18dd630e8ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T23:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T08:32:52.000Z", "avg_line_length": 25.0245098039, "max_line_length": 80, "alphanum_fraction": 0.5410381978, "num_tokens": 1524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5355670642688272}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\nusing Eigen::MatrixXd;\nusing Eigen::Vector3d;\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 << m << std::endl;\n\n Vector3d v(0,0,0);\n\n std::vector<Vector3d> vv;\n\n for(int i=0;i<10;i++){\n    v(0)=i;\n    vv.push_back(v);\n }\n\n    for(int i=0;i<10;i++){\n     std::cout << i << \":\" << vv[i] << std::endl;\n    }\n}", "meta": {"hexsha": "ff5561b7d98302bd0c29c94fc904eac17456cfe8", "size": 438, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/eigen/main.cpp", "max_stars_repo_name": "ashitani/cmake_example", "max_stars_repo_head_hexsha": "3631d8eabf7bde256181640df156127d58ce03d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/eigen/main.cpp", "max_issues_repo_name": "ashitani/cmake_example", "max_issues_repo_head_hexsha": "3631d8eabf7bde256181640df156127d58ce03d4", "max_issues_repo_licenses": ["MIT"], "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/eigen/main.cpp", "max_forks_repo_name": "ashitani/cmake_example", "max_forks_repo_head_hexsha": "3631d8eabf7bde256181640df156127d58ce03d4", "max_forks_repo_licenses": ["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.2222222222, "max_line_length": 49, "alphanum_fraction": 0.5114155251, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5355424382015425}}
{"text": "#ifndef BOOST_METAPARSE_GETTING_STARTED_5_2_4_HPP\r\n#define BOOST_METAPARSE_GETTING_STARTED_5_2_4_HPP\r\n\r\n// Automatically generated header file\r\n\r\n// Definitions before section 5.2.3\r\n#include \"5_2_3.hpp\"\r\n\r\n// Definitions of section 5.2.3\r\n#include <boost/metaparse/foldl.hpp>\r\n\r\nusing exp_parser10 = \r\n build_parser< \r\n   transform< \r\n     sequence< \r\n       int_token, \r\n       foldl< \r\n         sequence<plus_token, int_token>, \r\n         boost::mpl::int_<0>, \r\n         boost::mpl::quote2<sum_items> \r\n       > \r\n     >, \r\n     boost::mpl::quote1<sum_vector>> \r\n >;\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "4410806b4f66fbfd92c5d4f42dd95ccfef2d472c", "size": 583, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/getting_started/5_2_4.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": 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/metaparse/example/getting_started/5_2_4.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": "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/metaparse/example/getting_started/5_2_4.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": 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": 20.8214285714, "max_line_length": 50, "alphanum_fraction": 0.6380789022, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5355424324904752}}
{"text": "#pragma once\n\n#include \"loader.hpp\"\n#include <Eigen/Dense>\n#include <any>\n#include <chrono>\n#include <map>\n#include <random>\n#include <unordered_set>\n#include <vector>\n\nclass Config;\nclass SpTensor_Hash;\nclass SpTensor_dX;\nclass DataStream;\n\nclass TensorStream;\nTensorStream* generateTensorStream(DataStream& paperX, const Config& config); // Generate the tensor stream\n\nclass TensorStream {\npublic:\n    TensorStream(DataStream& paperX, const Config& config);\n    virtual ~TensorStream(void);\n\n    void updateTensor(const DataStream::Event& e);\n    void updateFactor(void);\n\n    double elapsedTime(void) const; // sec\n\n    double find_reconst(const std::vector<int>& coord) const;\n    double density(void) const;\n\n    /* Load matrix */\n    void saveFactor(std::string fileName) const;\n\n    /* Get errors */\n    double rmse(void) const;\n    double fitness(void) const;\n    double fitness_latest(void) const;\n    double error(const std::vector<int>& coord) const; // Error of the given entry\n\n    void updateAtA(void); // Update the AtA when _use_AtA is false\n\nprotected:\n    const Config* _config;\n\n    std::vector<int> _compute_order;\n\n    virtual void _updateAlgorithm(void) {} // It will change the current updateAlgorithm later\n\n    double _norm_frobenius_reconst(void) const;\n    double _innerprod_X_X_reconst(void) const;\n\n    SpTensor_Hash* _X = nullptr;\n    SpTensor_dX* _dX = nullptr;\n    DataStream* _paperX;\n\n    Eigen::ArrayXd _lambda;\n    std::vector<Eigen::MatrixXd> _A;\n    std::vector<Eigen::ArrayXXd> _AtA;\n\n    bool _use_AtA = true;\n\n    long long _nextTime;\n\n    std::chrono::nanoseconds _elapsed_time; // Elapsed time\n\n    void _rand_init_A(void); // Randomly initialize factor matrices\n\n    void _als_base(void); // Base code for ALS\n    void _unnormalize_A(void); // Unnormalize the factor matrices\n\n    /* Basic factor update algorithms */\n    void _als(void);\n    void _recurrent_als(void);\n};\n\n/* General ALS until the convergence */\nclass TensorStream_ALS : public TensorStream {\npublic:\n    TensorStream_ALS(DataStream& paperX, const Config& config)\n        : TensorStream(paperX, config)\n    {\n    }\n    virtual ~TensorStream_ALS(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override\n    {\n        _als();\n    }\n};\n\nclass TensorStream_GD : public TensorStream {\npublic:\n    TensorStream_GD(DataStream& paperX, const Config& config)\n        : TensorStream(paperX, config)\n        , _lr(_config->findAlgoSettings<double>(\"learningRate\"))\n    {\n    }\n    virtual ~TensorStream_GD(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override;\n\n    const double _lr; // learning rate\n};\n\nclass TensorStream_SGD : public TensorStream_GD {\npublic:\n    TensorStream_SGD(DataStream& paperX, const Config& config);\n    virtual ~TensorStream_SGD(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override;\n\n    // Sample entries with replacement including the currently updated entries.\n    // It returns the number of sampled entries.\n    int _sampleEntry(std::unordered_set<std::vector<int>>& sampledIdx) const;\n    void _compute_gradA(std::vector<std::unordered_map<int, Eigen::MatrixXd>>& gradA) const;\n\n    const int _numSample; // The number of samples\n};\n\nclass TensorStream_Momentum : public TensorStream_SGD {\npublic:\n    TensorStream_Momentum(DataStream& paperX, const Config& config);\n    virtual ~TensorStream_Momentum(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override;\n\n    const double _momentum;\n    const double _momentumNew;\n    std::vector<Eigen::MatrixXd> _V;\n};\n\nclass TensorStream_RMSProp : public TensorStream_SGD {\npublic:\n    TensorStream_RMSProp(DataStream& paperX, const Config& config);\n    virtual ~TensorStream_RMSProp(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override;\n\n    const double _decay;\n    std::vector<Eigen::VectorXd> _G;\n};\n\nclass TensorStream_Adam : public TensorStream_SGD {\npublic:\n    TensorStream_Adam(DataStream& paperX, const Config& config);\n    virtual ~TensorStream_Adam(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override;\n\n    const double _beta1;\n    const double _beta1New;\n    const double _beta2;\n\n    std::vector<Eigen::MatrixXd> _M;\n    std::vector<Eigen::VectorXd> _V;\n\n    std::vector<Eigen::VectorXd> _t; // The number of update\n};\n", "meta": {"hexsha": "63d9bac29be9574e1d91cec3d268f7c0d1f21f96", "size": 4304, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tensorStream.hpp", "max_stars_repo_name": "yunik1004/SliceNStitch-GD", "max_stars_repo_head_hexsha": "0d5e2013e55ffef2243da46bab01854ddd6b38b1", "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/tensorStream.hpp", "max_issues_repo_name": "yunik1004/SliceNStitch-GD", "max_issues_repo_head_hexsha": "0d5e2013e55ffef2243da46bab01854ddd6b38b1", "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/tensorStream.hpp", "max_forks_repo_name": "yunik1004/SliceNStitch-GD", "max_forks_repo_head_hexsha": "0d5e2013e55ffef2243da46bab01854ddd6b38b1", "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.7724550898, "max_line_length": 107, "alphanum_fraction": 0.7158457249, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5355369009699479}}
{"text": "//==============================================================================\n//          Copyright 2015 - J.T. Lapreste\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_SIGNIFICANTS_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_SIGNIFICANTS_HPP_INCLUDED\n\n#include <nt2/exponential/functions/significants.hpp>\n#include <nt2/include/functions/scalar/round.hpp>\n#include <nt2/include/functions/scalar/tenpower.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/if_zero_else.hpp>\n#include <nt2/include/functions/scalar/is_eqz.hpp>\n#include <nt2/include/functions/scalar/is_gtz.hpp>\n#include <nt2/include/functions/scalar/log10.hpp>\n#include <nt2/include/functions/scalar/minus.hpp>\n#include <nt2/include/functions/scalar/iceil.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/assert.hpp>\n#include <boost/simd/operator/functions/details/assert_utils.hpp>\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <nt2/include/functions/scalar/if_else.hpp>\n#include <nt2/include/functions/scalar/is_invalid.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT( significants_, tag::cpu_\n                          , (A0)(A1)\n                          , ((scalar_< floating_<A0>>))\n                            ((scalar_< integer_<A1>>))\n                          )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      BOOST_ASSERT_MSG( assert_all(is_gtz(a1))\n                      , \"Number of significant digits must be positive\"\n                      );\n      typedef typename boost::dispatch::meta::as_integer<A0>::type iA0;\n      if (is_eqz(a0)) return a0;\n      iA0 exp = a1 - iceil(log10(abs(a0)));\n      A0 fac = tenpower(exp);\n      A0 scaled = round(a0*fac);\n#ifndef BOOST_SIMD_NO_INVALIDS\n      A0 r = if_else(is_invalid(a0), a0, scaled/fac);\n#else\n      A0 r =  scaled/fac;\n#endif\n      return r;\n    }\n  };\n\n} }\n\n#endif\n", "meta": {"hexsha": "8f98bbb262962d686bc59355abb568ae4aaa298e", "size": 2260, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/functions/scalar/significants.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/exponential/include/nt2/exponential/functions/scalar/significants.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/exponential/include/nt2/exponential/functions/scalar/significants.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 36.4516129032, "max_line_length": 80, "alphanum_fraction": 0.6278761062, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5355368898410258}}
{"text": "/*\n * \n * Copyright (c) Andreas Kloeckner 2004\n *               Toon Knapen, Karl Meerbergen & Kresimir Fresl 2003\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 * KF acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_GEEV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_GEEV_HPP\n\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/traits/type.hpp>\n#include <boost/numeric/bindings/lapack/lapack.h>\n#include <boost/numeric/bindings/lapack/workspace.hpp>\n#include <boost/numeric/bindings/traits/detail/array.hpp>\n// #include <boost/numeric/bindings/traits/std_vector.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits.hpp>\n#endif \n\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace lapack {\n\n    ///////////////////////////////////////////////////////////////////\n    //\n    // Eigendecomposition of a general matrix A * V = V * D\n    // \n    ///////////////////////////////////////////////////////////////////\n\n    /* \n     * geev() computes the eigendecomposition of a N x N matrix,\n     * where V is a N x N matrix and D is a diagonal matrix. The \n     * diagonal element D(i,i) is an eigenvalue of A and Q(:,i) is \n     * a corresponding eigenvector.\n     *\n     *\n     * int geev (char jobz, char uplo, A& a, W& w, V* vl, V* vr, optimal_workspace);\n     *\n     * a is the matrix whose eigendecomposition you're interested in. (input)\n     *\n     * w contains the diagonal of D, above. w must always be complex. (output)\n     *\n     * vl is an N x N matrix containing the left eigenvectors of a in its\n     * columns. See remark on complex vs. real below. May be left NULL to indicate\n     * that you do not want left eigenvectors.\n     *\n     * vr is an N x N matrix containing the right (\"usual\") eigenvectors of a in its\n     * columns. See remark on complex vs. real below. As a matrix, vr fulfills\n     * A * VR = VR * D. (except if real, see below). May be left NULL to indicate\n     * that you do not want right eigenvectors.\n     *\n     *\n     * For real A, vr and vl may be either complex or real, at your option.\n     * If you choose to leave them real, you have to pick apart the complex-conjugate\n     * eigenpairs as per the LAPACK documentation. If you choose them complex,\n     * the code will do the picking-apart on your behalf, at the expense of 4*N\n     * extra storage. Only if vr is complex, it will really fulfill its invariant \n     * on exit to the code in all cases, since complex pairs spoil that relation.\n     */ \n\n    namespace detail {\n\n      inline\n      int geev_backend(const char* jobvl, const char* jobvr, const int* n, float* a,\n\t       const int* lda, float* wr, float* wi, float* vl, const int* ldvl,\n\t       float* vr, const int* ldvr, float* work, const int* lwork)\n      {\n\tint info;\n\tLAPACK_SGEEV(jobvl, jobvr, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, work, lwork, &info);\n\treturn info;\n      }\n\n      inline\n      int geev_backend(const char* jobvl, const char* jobvr, const int* n, double* a,\n\t       const int* lda, double* wr, double* wi, double* vl, const int* ldvl,\n\t       double* vr, const int* ldvr, double* work, const int* lwork)\n      {\n\tint info;\n\tLAPACK_DGEEV(jobvl, jobvr, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, work, lwork, &info);\n\treturn info;\n      }\n\n      inline\n      int geev_backend(const char* jobvl, const char* jobvr, const int* n, traits::complex_f* a,\n\t       const int* lda, traits::complex_f* w, traits::complex_f* vl, const int* ldvl,\n\t       traits::complex_f* vr, const int* ldvr, traits::complex_f* work, const int* lwork,\n\t       float* rwork)\n      {\n\tint info;\n\tLAPACK_CGEEV(jobvl, jobvr, n, \n\t\t     traits::complex_ptr(a), lda, \n\t\t     traits::complex_ptr(w), \n\t\t     traits::complex_ptr(vl), ldvl, \n\t\t     traits::complex_ptr(vr), ldvr, \n\t\t     traits::complex_ptr(work), lwork, \n\t\t     rwork, &info);\n\treturn info;\n      }\n\n      inline\n      int geev_backend(const char* jobvl, const char* jobvr, const int* n, traits::complex_d* a,\n\t       const int* lda, traits::complex_d* w, traits::complex_d* vl, const int* ldvl,\n\t       traits::complex_d* vr, const int* ldvr, traits::complex_d* work, const int* lwork,\n\t       double* rwork)\n      {\n\tint info;\n\tLAPACK_ZGEEV(jobvl, jobvr, n, \n\t\t     traits::complex_ptr(a), lda, \n\t\t     traits::complex_ptr(w), \n\t\t     traits::complex_ptr(vl), ldvl, \n\t\t     traits::complex_ptr(vr), ldvr, \n\t\t     traits::complex_ptr(work), lwork, \n\t\t     rwork, &info);\n\treturn info;\n      }\n\n\n      struct real_case {};\n      struct mixed_case {};\n      struct complex_case {};\n\n\n\n\n      // real case\n      template <typename A, typename W, typename V>\n      int geev(real_case, const char jobvl, const char jobvr, A& a, W& w, \n\t       V* vl, V *vr)\n      {\n\tint const n = traits::matrix_size1(a);\n\ttypedef typename A::value_type value_type;\n\ttraits::detail::array<value_type> wr(n);\n\ttraits::detail::array<value_type> wi(n);\n\n\ttraits::detail::array<value_type> vl2(vl ? 0 : n);\n\ttraits::detail::array<value_type> vr2(vr ? 0 : n);\n\tvalue_type* vl_real = vl ? traits::matrix_storage(*vl) : vl2.storage();\n\tconst int ldvl = vl ? traits::matrix_size2(*vl) : 1;\n\tvalue_type* vr_real = vr ? traits::matrix_storage(*vr) : vr2.storage();\n\tconst int ldvr = vr ? traits::matrix_size2(*vr) : 1;\n\n\n\t// workspace query\n\tint lwork = -1;\n\tvalue_type work_temp;\n\tint result = geev_backend(&jobvl, &jobvr, &n,\n\t\t\t\t  traits::matrix_storage(a), &n, \n\t\t\t\t  wr.storage(), wi.storage(), \n\t\t\t\t  vl_real, &ldvl, vr_real, &ldvr,\n\t\t\t\t  &work_temp, &lwork);\n\tif (result != 0)\n\t  return result;\n\n\tlwork = (int) work_temp;\n\ttraits::detail::array<value_type> work(lwork);\n\tresult = geev_backend(&jobvl, &jobvr, &n,\n\t\t\t      traits::matrix_storage(a), &n, \n\t\t\t      wr.storage(), wi.storage(), \n\t\t\t      vl_real, &ldvl, vr_real, &ldvr,\n\t\t\t      work.storage(), &lwork);\n\n\tfor (int i = 0; i < n; i++)\n\t  traits::vector_storage(w)[i] = std::complex<value_type>(wr[i], wi[i]);\n\treturn result;\n      }\n\n      // mixed (i.e. real with complex vectors) case\n      template <typename A, typename W, typename V>\n      int geev(mixed_case, const char jobvl, const char jobvr, A& a, W& w, \n\t       V* vl, V *vr)\n      {\n\tint const n = traits::matrix_size1(a);\n\ttypedef typename A::value_type value_type;\n\ttraits::detail::array<value_type> wr(n);\n\ttraits::detail::array<value_type> wi(n);\n\n\ttraits::detail::array<value_type> vl2(vl ? n*n : n);\n\ttraits::detail::array<value_type> vr2(vr ? n*n : n);\n\tconst int ldvl2 = vl ? n : 1;\n\tconst int ldvr2 = vr ? n : 1;\n\n\t// workspace query\n\tint lwork = -1;\n\tvalue_type work_temp;\n\tint result = geev_backend(&jobvl, &jobvr, &n,\n\t\t\t\t  traits::matrix_storage(a), &n, \n\t\t\t\t  wr.storage(), wi.storage(), \n\t\t\t\t  vl2.storage(), &ldvl2, vr2.storage(), &ldvr2,\n\t\t\t\t  &work_temp, &lwork);\n\tif (result != 0)\n\t  return result;\n\n\tlwork = (int) work_temp;\n\ttraits::detail::array<value_type> work(lwork);\n\tresult = geev_backend(&jobvl, &jobvr, &n,\n\t\t\t      traits::matrix_storage(a), &n, \n\t\t\t      wr.storage(), wi.storage(), \n\t\t\t      vl2.storage(), &ldvl2, vr2.storage(), &ldvr2,\n\t\t\t      work.storage(), &lwork);\n\n\ttypedef typename V::value_type vec_value_type;\n\tvec_value_type* vl_stor = NULL;\n\tvec_value_type* vr_stor = NULL;\n\tint ldvl = 0, ldvr = 0;\n\tif (vl)\n\t{\n\t  vl_stor = traits::matrix_storage(*vl);\n\t  ldvl = traits::matrix_size2(*vl);\n\t}\n\tif (vr)\n\t{\n\t  vr_stor = traits::matrix_storage(*vr);\n\t  ldvr = traits::matrix_size2(*vr);\n\t}\n\t\n\tfor (int i = 0; i < n; i++)\n        {\n          traits::vector_storage(w)[i] = std::complex<value_type>(wr[i], wi[i]);\n\t  if (wi[i] != 0)\n\t  {\n\t    assert(i+1 < n);\n\t    assert(wr[i+1] == wr[i]);\n\t    assert(wi[i+1] == -wi[i]);\n\n            traits::vector_storage(w)[i+1] = std::complex<value_type>(wr[i+1], wi[i+1]);\n\t    for (int j = 0; j < n; j++)\n\t    {\n\t      if (vl)\n\t      {\n\t\tvl_stor[i*ldvl+j] = std::complex<value_type>(vl2[i*n+j], vl2[(i+1)*n+j]);\n\t\tvl_stor[(i+1)*ldvl+j] = std::complex<value_type>(vl2[i*n+j], -vl2[(i+1)*n+j]);\n\t      }\n\t      if (vr)\n\t      {\n\t\tvr_stor[i*ldvr+j] = std::complex<value_type>(vr2[i*n+j], vr2[(i+1)*n+j]);\n\t\tvr_stor[(i+1)*ldvr+j] = std::complex<value_type>(vr2[i*n+j], -vr2[(i+1)*n+j]);\n\t      }\n\t    }\n\n\t    i++;\n\t  }\n\t  else\n\t  {\n\t    for (int j = 0; j < n; j++)\n\t    {\n\t      if (vl)\n\t\tvl_stor[i*ldvl+j] = vl2[i*n+j];\n\t      if (vr)\n\t\tvr_stor[i*ldvr+j] = vr2[i*n+j];\n\t    }\n\t  }\n\t}\n\treturn result;\n      }\n\n      // complex case\n      template <typename A, typename W, typename V>\n      int geev(complex_case, const char jobvl, const char jobvr, A& a, W& w, \n\t       V* vl, V *vr)\n      {\n\ttypedef typename A::value_type value_type;\n\ttypedef typename traits::type_traits<value_type>::real_type real_type;\n\n\tint const n = traits::matrix_size1(a);\n\ttraits::detail::array<real_type> rwork(2*n);\n\n\ttraits::detail::array<value_type> vl2(vl ? 0 : n);\n\ttraits::detail::array<value_type> vr2(vr ? 0 : n);\n\tvalue_type* vl_real = vl ? traits::matrix_storage(*vl) : vl2.storage();\n\tconst int ldvl = vl ? traits::matrix_size2(*vl) : 1;\n\tvalue_type* vr_real = vr ? traits::matrix_storage(*vr) : vr2.storage();\n\tconst int ldvr = vr ? traits::matrix_size2(*vr) : 1;\n\n\t// workspace query\n\tint lwork = -1;\n\tvalue_type work_temp;\n\tint result = geev_backend(&jobvl, &jobvr, &n,\n\t\t\t\t  traits::matrix_storage(a), &n, \n\t\t\t\t  traits::vector_storage(w),\n\t\t\t\t  vl_real, &ldvl, vr_real, &ldvr,\n\t\t\t\t  &work_temp, &lwork, rwork.storage());\n\tif (result != 0)\n\t  return result;\n\n\tlwork = (int) std::real(work_temp);\n\ttraits::detail::array<value_type> work(lwork);\n\tresult = geev_backend(&jobvl, &jobvr, &n,\n\t\t\t      traits::matrix_storage(a), &n, \n\t\t\t      traits::vector_storage(w),\n\t\t\t      vl_real, &ldvl, vr_real, &ldvr,\n\t\t\t      work.storage(), &lwork, \n\t\t\t      rwork.storage());\n\n\treturn result;\n      }\n\n    } // namespace detail\n\n\n    // gateway / dispatch routine\n    template <typename A, typename W, typename V>\n    int geev(A& a, W& w,  V* vl, V* vr, optimal_workspace) \n    {\n      // input checking\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n\t\t\t   typename traits::matrix_traits<A>::matrix_structure, \n\t\t\t   traits::general_t\n\t\t\t   >::value)); \n#endif \n\n#ifndef NDEBUG\n      int const n = traits::matrix_size1(a);\n#endif\n\n      assert(traits::matrix_size2(a)==n); \n      assert(traits::vector_size(w)==n); \n      assert(traits::vector_size(w)==n); \n      assert(!vr || traits::matrix_size1(*vr)==n); \n      assert(!vl || traits::matrix_size1(*vl)==n); \n\n      // preparation\n      typedef typename A::value_type value_type;\n      typedef typename V::value_type vec_value_type;\n      typedef typename traits::type_traits<value_type>::real_type real_type;\n\n      // dispatch\n      return detail::geev(typename boost::mpl::if_<\n\t\t\t  boost::is_same<value_type, real_type>,\n\t\t\t  typename boost::mpl::if_<\n\t\t\t  boost::is_same<vec_value_type, real_type>,\n\t\t\t  detail::real_case,\n\t\t\t  detail::mixed_case>::type,\n\t\t\t  detail::complex_case>::type(),\n\t\t\t  vl != 0 ? 'V' : 'N', \n\t\t\t  vr != 0 ? 'V' : 'N',\n\t\t\t  a, w, vl, vr);\n    }\n\n  }\n\n}}}\n\n#endif \n", "meta": {"hexsha": "10f7498d1c6038b1b2807a1928e6a57c675f09a1", "size": 11295, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/lapack/geev.hpp", "max_stars_repo_name": "inducer/boost-numeric-bindings", "max_stars_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-11-13T16:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T15:37:19.000Z", "max_issues_repo_path": "openrave/plugins/include/boost/numeric/bindings/lapack/geev.hpp", "max_issues_repo_name": "jdsika/holy", "max_issues_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-06-13T01:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-14T00:38:27.000Z", "max_forks_repo_path": "openrave/plugins/include/boost/numeric/bindings/lapack/geev.hpp", "max_forks_repo_name": "jdsika/holy", "max_forks_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "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": 31.7275280899, "max_line_length": 96, "alphanum_fraction": 0.6149623727, "num_tokens": 3350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650247, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5355368870031211}}
{"text": "#include <tiny_math_types.h>\n#include <tiny_coordsys_functions.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\nBOOST_AUTO_TEST_SUITE(tiny_coordsys_prod);\n\nBOOST_AUTO_TEST_CASE(simple_test)\n{\n  typedef tiny::MathTypes<double> math_types;\n\n  typedef math_types::value_traits     value_traits;\n  typedef math_types::vector3_type     V;\n  typedef math_types::quaternion_type  Q;\n  typedef math_types::coordsys_type    X;\n\n  {\n    X I;\n    I.identity();\n\n    X L;\n    L.T() = V::make(1.0,2.0,3.0);\n    L.Q() = Q::Ru( value_traits::pi(), V::make(1.0, 2.0, 3.0) );\n\n    X R = tiny::prod( L, I );\n\n    BOOST_CHECK( fabs( R.T()(0) - L.T()(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.T()(1) - L.T()(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.T()(2) - L.T()(2) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().real() - L.Q().real() ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().imag()(0) - L.Q().imag()(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().imag()(1) - L.Q().imag()(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().imag()(2) - L.Q().imag()(2) ) < 10e-10 );\n  }\n  {\n    X I;\n    I.identity();\n\n    X L;\n    L.T() = V::make(1.0,2.0,3.0);\n    L.Q() = Q::Ru( value_traits::pi(), V::make(1.0, 2.0, 3.0) );\n\n    X R = tiny::prod( I, L );\n\n    BOOST_CHECK( fabs( R.T()(0) - L.T()(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.T()(1) - L.T()(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.T()(2) - L.T()(2) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().real() - L.Q().real() ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().imag()(0) - L.Q().imag()(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().imag()(1) - L.Q().imag()(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().imag()(2) - L.Q().imag()(2) ) < 10e-10 );\n  }\n  {\n    X I;\n    I.identity();\n\n    X R = tiny::prod( I, I );\n\n    BOOST_CHECK( fabs( R.T()(0) - I.T()(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.T()(1) - I.T()(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.T()(2) - I.T()(2) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().real() - I.Q().real() ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().imag()(0) - I.Q().imag()(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().imag()(1) - I.Q().imag()(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().imag()(2) - I.Q().imag()(2) ) < 10e-10 );\n  }\n  {\n    X I;\n    I.identity();\n\n    X L;\n    L.T() = V::make(1.0,2.0,3.0);\n    L.Q() = Q::Ru( value_traits::pi(), V::make(1.0, 2.0, 3.0) );\n\n    X invL = tiny::inverse( L );\n    X R = tiny::prod( invL, L );\n\n    BOOST_CHECK( fabs( R.T()(0) - I.T()(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.T()(1) - I.T()(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.T()(2) - I.T()(2) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().real() - I.Q().real() ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().imag()(0) - I.Q().imag()(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().imag()(1) - I.Q().imag()(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( R.Q().imag()(2) - I.Q().imag()(2) ) < 10e-10 );\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "842f7fc03293fbfdc3818ddcdedd6efcb66c8f8e", "size": 3035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_coordsys_prod/tiny_coordsys_prod.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_coordsys_prod/tiny_coordsys_prod.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_coordsys_prod/tiny_coordsys_prod.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6344086022, "max_line_length": 70, "alphanum_fraction": 0.52092257, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.53544321851193}}
{"text": "// File: multi_vector.cpp\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    typedef dense_vector<double>   Vector;\n\n    Vector                      v(2, 3.4), w(3, 2.5);\n    mtl::multi_vector<Vector> \tA(2, 3);    \n    dense2D<double>\t\tB(2,2), C(3,2), D(3,3);\n\n    // Initialize matrices\n    A= 3.0; B= 4.0; C= 5.0; D= 6.0;\n\n    // vector= multi_vector * vector\n    v= A * w;\n\n    // vector= transposed multi_vector * vector\n    w= trans(A) * v;\n\n    // vector= matrix * vector \n    v= B * A.vector(1);\t\t\n\n    // vector= matrix * vector\n    A.vector(0)= B * A.vector(1);\t\n\n    // Orthogonalize multi_vector\n    orth(A);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "88c863c2fe3c72f403f4c3f04c8598762a3c60c8", "size": 700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/multi_vector.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/multi_vector.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/multi_vector.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": 18.9189189189, "max_line_length": 53, "alphanum_fraction": 0.5471428571, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5354432182237225}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Ilias Khairullin <ilias@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_PUBKEY_SHAMIR_SSS_HPP\n#define CRYPTO3_PUBKEY_SHAMIR_SSS_HPP\n\n#include <vector>\n#include <tuple>\n#include <type_traits>\n#include <unordered_map>\n#include <unordered_set>\n#include <iterator>\n\n#include <boost/assert.hpp>\n#include <boost/concept_check.hpp>\n\n#include <boost/range/concepts.hpp>\n\n#include <nil/crypto3/random/algebraic_random_device.hpp>\n\n#include <nil/crypto3/pubkey/operations/deal_shares_op.hpp>\n#include <nil/crypto3/pubkey/operations/reconstruct_secret_op.hpp>\n#include <nil/crypto3/pubkey/operations/reconstruct_public_secret_op.hpp>\n\n#include <nil/crypto3/pubkey/keys/share_sss.hpp>\n#include <nil/crypto3/pubkey/keys/secret_sss.hpp>\n#include <nil/crypto3/pubkey/keys/public_share_sss.hpp>\n#include <nil/crypto3/pubkey/keys/public_secret_sss.hpp>\n\n#include <nil/crypto3/pubkey/secret_sharing/weighted_basic_policy.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace pubkey {\n            template<typename Group>\n            struct shamir_sss : public sss_weighted_basic_policy<Group> {\n                typedef Group group_type;\n                typedef sss_basic_policy<group_type> basic_policy;\n\n                //===========================================================================\n                // secret sharing scheme output types\n\n                typedef std::vector<typename basic_policy::coeff_type> coeffs_type;\n                typedef std::vector<typename basic_policy::public_coeff_type> public_coeffs_type;\n\n                static inline typename basic_policy::private_element_type\n                    eval_basis_poly(const typename basic_policy::indexes_type &indexes, std::size_t i) {\n                    assert(basic_policy::check_participant_index(i));\n\n                    typename basic_policy::private_element_type e_i(i);\n                    typename basic_policy::private_element_type result = basic_policy::private_element_type::one();\n\n                    for (auto j : indexes) {\n                        if (j != i) {\n                            result = result * (typename basic_policy::private_element_type(j) /\n                                               (typename basic_policy::private_element_type(j) - e_i));\n                        }\n                    }\n                    return result;\n                }\n\n                //===========================================================================\n                // TODO: refactor\n                // polynomial generation functions\n\n                static inline coeffs_type get_poly(std::size_t t, std::size_t n) {\n                    assert(basic_policy::check_threshold_value(t, n));\n\n                    return get_poly(t);\n                }\n\n                template<\n                    typename Generator = random::algebraic_random_device<typename basic_policy::coeff_type::field_type>,\n                    typename Distribution = void>\n                static inline coeffs_type get_poly(std::size_t t) {\n                    assert(basic_policy::check_minimal_size(t));\n\n                    coeffs_type coeffs;\n                    Generator gen;\n                    for (std::size_t i = 0; i < t; i++) {\n                        coeffs.emplace_back(gen());\n                    }\n                    return coeffs;\n                }\n\n                //===========================================================================\n                // TODO: refactor\n                // general purposes functions\n\n                template<typename Coeffs>\n                static inline public_coeffs_type get_public_coeffs(const Coeffs &coeffs) {\n                    BOOST_RANGE_CONCEPT_ASSERT((boost::SinglePassRangeConcept<const Coeffs>));\n\n                    return get_public_coeffs(std::cbegin(coeffs), std::cend(coeffs));\n                }\n\n                template<typename CoeffsIt>\n                static inline public_coeffs_type get_public_coeffs(CoeffsIt first, CoeffsIt last) {\n                    BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<CoeffsIt>));\n                    assert(basic_policy::check_minimal_size(std::distance(first, last)));\n\n                    public_coeffs_type public_coeffs;\n                    for (auto it = first; it != last; it++) {\n                        public_coeffs.emplace_back(basic_policy::get_public_element(*it));\n                    }\n                    return public_coeffs;\n                }\n            };\n\n            template<typename Group>\n            struct public_share_sss<shamir_sss<Group>> {\n                typedef shamir_sss<Group> scheme_type;\n                typedef typename scheme_type::indexed_public_element_type public_share_type;\n                typedef public_share_type data_type;\n                typedef typename public_share_type::first_type index_type;\n                typedef typename public_share_type::second_type value_type;\n\n                public_share_sss() = default;\n\n                public_share_sss(std::size_t i) : public_share(i, public_share_type::second_type::zero()) {\n                    assert(scheme_type::check_participant_index(get_index()));\n                }\n\n                public_share_sss(const public_share_type &in_public_share) : public_share(in_public_share) {\n                    assert(scheme_type::check_participant_index(get_index()));\n                }\n\n                public_share_sss(std::size_t i, const typename public_share_type::second_type &ps) :\n                    public_share(i, ps) {\n                    assert(scheme_type::check_participant_index(get_index()));\n                }\n\n                inline index_type get_index() const {\n                    return public_share.first;\n                }\n\n                inline const value_type &get_value() const {\n                    return public_share.second;\n                }\n\n                inline const data_type &get_data() const {\n                    return public_share;\n                }\n\n                bool operator==(const public_share_sss &other) const {\n                    return this->public_share == other.public_share;\n                }\n\n                bool operator<(const public_share_sss &other) const {\n                    return this->get_index() < other.get_index();\n                }\n\n            protected:\n                public_share_type public_share;\n            };\n\n            template<typename Group>\n            struct share_sss<shamir_sss<Group>> {\n                typedef shamir_sss<Group> scheme_type;\n                typedef typename scheme_type::indexed_private_element_type share_type;\n                typedef share_type data_type;\n                typedef typename share_type::first_type index_type;\n                typedef typename share_type::second_type value_type;\n\n                share_sss() = default;\n\n                share_sss(std::size_t i) : share(i, share_type::second_type::zero()) {\n                    assert(scheme_type::check_participant_index(get_index()));\n                }\n\n                share_sss(const share_type &in_share) : share(in_share) {\n                    assert(scheme_type::check_participant_index(get_index()));\n                }\n\n                share_sss(std::size_t i, const typename share_type::second_type &s) : share(i, s) {\n                    assert(scheme_type::check_participant_index(get_index()));\n                }\n\n                inline index_type get_index() const {\n                    return share.first;\n                }\n\n                inline const value_type &get_value() const {\n                    return share.second;\n                }\n\n                inline const data_type &get_data() const {\n                    return share;\n                }\n\n                template<\n                    typename Scheme,\n                    typename std::enable_if<\n                        std::is_convertible<typename std::remove_cv<typename std::remove_reference<Scheme>::type>::type,\n                                            scheme_type>::value,\n                        bool>::type = true>\n                operator public_share_sss<Scheme>() const {\n                    using To = public_share_sss<Scheme>;\n\n                    return To(share.first, share.second * To::public_share_type::second_type::one());\n                }\n\n                bool operator==(const share_sss &other) const {\n                    return this->share == other.share;\n                }\n\n                bool operator<(const share_sss &other) const {\n                    return this->get_index() < other.get_index();\n                }\n\n                //\n                //  0 <= k < t\n                //\n                inline void update(const typename scheme_type::coeff_type &coeff, std::size_t exp) {\n                    assert(scheme_type::check_exp(exp));\n\n                    share.second =\n                        share.second + coeff * typename scheme_type::private_element_type(share.first).pow(exp);\n                }\n\n            protected:\n                share_type share;\n            };\n\n            template<typename Group>\n            struct public_secret_sss<shamir_sss<Group>> {\n                typedef shamir_sss<Group> scheme_type;\n                typedef typename scheme_type::public_element_type public_secret_type;\n                typedef typename scheme_type::indexes_type indexes_type;\n                typedef public_secret_type value_type;\n\n                template<typename PublicShares>\n                public_secret_sss(const PublicShares &public_shares) :\n                    public_secret_sss(std::cbegin(public_shares), std::cend(public_shares)) {\n                }\n\n                template<typename PublicShareIt>\n                public_secret_sss(PublicShareIt first, PublicShareIt last) :\n                    public_secret(reconstruct_public_secret(first, last)) {\n                }\n\n                template<typename PublicShares>\n                public_secret_sss(const PublicShares &public_shares, const indexes_type &indexes) :\n                    public_secret_sss(std::cbegin(public_shares), std::cend(public_shares), indexes) {\n                }\n\n                template<typename PublicShareIt>\n                public_secret_sss(PublicShareIt first, PublicShareIt last, const indexes_type &indexes) :\n                    public_secret(reconstruct_public_secret(first, last, indexes)) {\n                }\n\n                inline const value_type &get_value() const {\n                    return public_secret;\n                }\n\n                bool operator==(const public_secret_sss &other) const {\n                    return this->public_secret == other.public_secret;\n                }\n\n                bool operator<(const public_secret_sss &other) const {\n                    return this->public_secret < other.public_secret;\n                }\n\n            private:\n                template<\n                    typename PublicShareIt,\n                    typename std::enable_if<\n                        std::is_convertible<typename std::remove_cv<typename std::remove_reference<\n                                                typename std::iterator_traits<PublicShareIt>::value_type>::type>::type,\n                                            public_share_sss<scheme_type>>::value,\n                        bool>::type = true>\n                static inline public_secret_type reconstruct_public_secret(PublicShareIt first, PublicShareIt last) {\n                    BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<PublicShareIt>));\n\n                    return reconstruct_public_secret(first, last, scheme_type::get_indexes(first, last));\n                }\n\n                template<\n                    typename PublicShareIt,\n                    typename std::enable_if<\n                        std::is_convertible<typename std::remove_cv<typename std::remove_reference<\n                                                typename std::iterator_traits<PublicShareIt>::value_type>::type>::type,\n                                            public_share_sss<scheme_type>>::value,\n                        bool>::type = true>\n                static inline public_secret_type reconstruct_public_secret(PublicShareIt first, PublicShareIt last,\n                                                                           const indexes_type &indexes) {\n                    BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<PublicShareIt>));\n\n                    public_secret_type public_secret = public_secret_type::zero();\n                    for (auto it = first; it != last; it++) {\n                        public_secret =\n                            public_secret + it->get_value() * scheme_type::eval_basis_poly(indexes, it->get_index());\n                    }\n\n                    return public_secret;\n                }\n\n                public_secret_type public_secret;\n            };\n\n            template<typename Group>\n            struct secret_sss<shamir_sss<Group>> {\n                typedef shamir_sss<Group> scheme_type;\n                typedef typename scheme_type::private_element_type secret_type;\n                typedef typename scheme_type::indexes_type indexes_type;\n                typedef secret_type value_type;\n\n                template<typename Shares>\n                secret_sss(const Shares &shares) : secret_sss(std::cbegin(shares), std::cend(shares)) {\n                }\n\n                template<typename ShareIt>\n                secret_sss(ShareIt first, ShareIt last) : secret(reconstruct_secret(first, last)) {\n                }\n\n                template<typename Shares>\n                secret_sss(const Shares &shares, const indexes_type &indexes) :\n                    secret_sss(std::cbegin(shares), std::cend(shares), indexes) {\n                }\n\n                template<typename ShareIt>\n                secret_sss(ShareIt first, ShareIt last, const indexes_type &indexes) :\n                    secret(reconstruct_secret(first, last, indexes)) {\n                }\n\n                inline const value_type &get_value() const {\n                    return secret;\n                }\n\n                bool operator==(const secret_sss &other) const {\n                    return this->secret == other.secret;\n                }\n\n                bool operator<(const secret_sss &other) const {\n                    return this->secret < other.secret;\n                }\n\n                template<\n                    typename Scheme,\n                    typename std::enable_if<\n                        std::is_convertible<typename std::remove_cv<typename std::remove_reference<Scheme>::type>::type,\n                                            scheme_type>::value,\n                        bool>::type = true>\n                operator public_secret_sss<Scheme>() const {\n                    using To = public_secret_sss<Scheme>;\n\n                    return To(secret * To::public_secret_type::one());\n                }\n\n            protected:\n                template<typename ShareIt,\n                         typename std::enable_if<\n                             std::is_convertible<typename std::remove_cv<typename std::remove_reference<\n                                                     typename std::iterator_traits<ShareIt>::value_type>::type>::type,\n                                                 share_sss<scheme_type>>::value,\n                             bool>::type = true>\n                static inline secret_type reconstruct_secret(ShareIt first, ShareIt last) {\n                    BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<ShareIt>));\n\n                    return reconstruct_secret(first, last, scheme_type::get_indexes(first, last));\n                }\n\n                template<typename ShareIt,\n                         typename std::enable_if<\n                             std::is_convertible<typename std::remove_cv<typename std::remove_reference<\n                                                     typename std::iterator_traits<ShareIt>::value_type>::type>::type,\n                                                 share_sss<scheme_type>>::value,\n                             bool>::type = true>\n                static inline secret_type reconstruct_secret(ShareIt first, ShareIt last, const indexes_type &indexes) {\n                    BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<ShareIt>));\n\n                    secret_type secret = secret_type::zero();\n                    for (auto it = first; it != last; it++) {\n                        secret = secret + it->get_value() * scheme_type::eval_basis_poly(indexes, it->get_index());\n                    }\n\n                    return secret;\n                }\n\n                secret_type secret;\n            };\n\n            template<typename Group>\n            struct deal_shares_op<shamir_sss<Group>> {\n                typedef shamir_sss<Group> scheme_type;\n                typedef share_sss<scheme_type> share_type;\n                typedef std::vector<share_type> shares_type;\n                typedef shares_type internal_accumulator_type;\n                typedef shares_type result_type;\n\n            protected:\n                template<typename Share, typename InternalAccumulator>\n                static inline void _init_accumulator(InternalAccumulator &acc, std::size_t n, std::size_t t) {\n                    assert(scheme_type::check_threshold_value(t, n));\n\n                    std::size_t i = 1;\n                    std::generate_n(std::inserter(acc, std::end(acc)), n, [&i]() { return Share(i++); });\n                }\n\n                template<typename Scheme, typename InternalAccumulator>\n                static inline void _update(InternalAccumulator &acc, std::size_t exp,\n                                           const typename Scheme::coeff_type &coeff) {\n                    for (auto shares_iter = std::begin(acc); shares_iter != std::end(acc); ++shares_iter) {\n                        shares_iter->update(coeff, exp);\n                    }\n                }\n\n                template<typename ResultType, typename InternalAccumulator>\n                static inline ResultType _process(InternalAccumulator &acc) {\n                    return acc;\n                }\n\n            public:\n                static inline void init_accumulator(internal_accumulator_type &acc, std::size_t n, std::size_t t) {\n                    _init_accumulator<share_type>(acc, n, t);\n                }\n\n                static inline void update(internal_accumulator_type &acc, std::size_t exp,\n                                          const typename scheme_type::coeff_type &coeff) {\n                    _update<scheme_type>(acc, exp, coeff);\n                }\n\n                static inline result_type process(internal_accumulator_type &acc) {\n                    return _process<result_type>(acc);\n                }\n            };\n\n            template<typename Group>\n            struct reconstruct_public_secret_op<shamir_sss<Group>> {\n                typedef shamir_sss<Group> scheme_type;\n                typedef public_share_sss<scheme_type> public_share_type;\n                typedef public_secret_sss<scheme_type> public_secret_type;\n                typedef std::pair<typename scheme_type::indexes_type, std::set<public_share_type>>\n                    internal_accumulator_type;\n                typedef public_secret_type result_type;\n\n            protected:\n                template<typename InternalAccumulator, typename PublicShare>\n                static inline void _update(InternalAccumulator &acc, const PublicShare &public_share) {\n                    bool emplace_status = acc.first.emplace(public_share.get_index()).second;\n                    assert(emplace_status);\n                    // acc.second.push_back(public_share);\n                    emplace_status = acc.second.emplace(public_share).second;\n                    assert(emplace_status);\n                }\n\n                template<typename ResultType, typename InternalAccumulator>\n                static inline ResultType _process(InternalAccumulator &acc) {\n                    return ResultType(acc.second /*, acc.first*/);\n                }\n\n            public:\n                static inline void init_accumulator() {\n                }\n\n                static inline void update(internal_accumulator_type &acc, const public_share_type &public_share) {\n                    _update(acc, public_share);\n                }\n\n                static inline result_type process(internal_accumulator_type &acc) {\n                    return _process<result_type>(acc);\n                }\n            };\n\n            template<typename Group>\n            struct reconstruct_secret_op<shamir_sss<Group>> {\n                typedef shamir_sss<Group> scheme_type;\n                typedef share_sss<scheme_type> share_type;\n                typedef secret_sss<scheme_type> secret_type;\n                typedef std::pair<typename scheme_type::indexes_type, std::set<share_type>> internal_accumulator_type;\n                typedef secret_type result_type;\n\n            protected:\n                template<typename InternalAccumulator, typename Share>\n                static inline void _update(InternalAccumulator &acc, const Share &share) {\n                    bool emplace_status = acc.first.emplace(share.get_index()).second;\n                    assert(emplace_status);\n                    // acc.second.push_back(public_share);\n                    emplace_status = acc.second.emplace(share).second;\n                    assert(emplace_status);\n                }\n\n                template<typename ResultType, typename InternalAccumulator>\n                static inline ResultType _process(InternalAccumulator &acc) {\n                    return ResultType(acc.second /*, acc.first*/);\n                }\n\n            public:\n                static inline void init_accumulator() {\n                }\n\n                static inline void update(internal_accumulator_type &acc, const share_type &share) {\n                    _update(acc, share);\n                }\n\n                static inline result_type process(internal_accumulator_type &acc) {\n                    return _process<result_type>(acc);\n                }\n            };\n        }    // namespace pubkey\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_PUBKEY_SHAMIR_SSS_HPP\n", "meta": {"hexsha": "ebec24f412648cff416d5831ecc3ee5a981f51dd", "size": 23698, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/pubkey/secret_sharing/shamir.hpp", "max_stars_repo_name": "NilFoundation/pubkey", "max_stars_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T02:25:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T02:25:55.000Z", "max_issues_repo_path": "include/nil/crypto3/pubkey/secret_sharing/shamir.hpp", "max_issues_repo_name": "NilFoundation/pubkey", "max_issues_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-10-10T00:23:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T21:03:41.000Z", "max_forks_repo_path": "include/nil/crypto3/pubkey/secret_sharing/shamir.hpp", "max_forks_repo_name": "NilFoundation/pubkey", "max_forks_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:40:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T21:39:35.000Z", "avg_line_length": 44.9677419355, "max_line_length": 120, "alphanum_fraction": 0.5462486286, "num_tokens": 4164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5354432131228767}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EXPONENTIAL_FUNCTIONS_SCALAR_EXPX2_HPP_INCLUDED\n#define NT2_EXPONENTIAL_FUNCTIONS_SCALAR_EXPX2_HPP_INCLUDED\n#include <nt2/exponential/functions/expx2.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <nt2/include/constants/expx2c1.hpp>\n#include <nt2/include/constants/expx2c2.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/maxlog.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/exp.hpp>\n#include <nt2/include/functions/scalar/floor.hpp>\n#include <nt2/include/functions/scalar/fma.hpp>\n#include <nt2/include/functions/scalar/signnz.hpp>\n#include <nt2/include/functions/scalar/sqr.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/functions/scalar/is_inf.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( expx2_, tag::cpu_\n                            , (A0)\n                            , (scalar_< floating_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      if (nt2::is_inf(a0)) return nt2::Inf<A0>();\n      #endif\n      A0 x =  nt2::abs(a0);\n      /* Represent x as an exact multiple of 1/32 plus a residual.  */\n      A0 m = nt2::Expx2c1<A0>() * nt2::floor(nt2::Expx2c2<A0>() * x + Half<A0>());\n      x -= m;\n      /* x**2 = m**2 + 2mf + f**2 */\n      A0 u = sqr(m);\n      A0 u1 = nt2::Two<A0>() * m * x  +  nt2::sqr(x);\n      if ((u+u1) > nt2::Maxlog<A0>()) return nt2::Inf<A0>();\n      /* u is exact, u1 is small.  */\n      return nt2::exp(u) * nt2::exp(u1);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( expx2_, tag::cpu_\n                            , (A0)\n                            , ((scalar_<floating_<A0> >))\n                              ((scalar_<floating_<A0> >))\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE result_type operator()(const A0& a0,  const A0 & s) const\n    {\n      A0 sgn =  signnz(s);\n      A0 x =  a0*sgn;\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      if (nt2::is_inf(a0)) return nt2::Inf<A0>();\n      #endif\n      // Represent x as an exact multiple of 1/32 plus a residual.\n      A0 m = Expx2c1<A0>()*nt2::floor(fma(Expx2c2<A0>(), x, nt2::Half<A0>()));\n      A0 f =  x-m;\n      // x**2 = m**2 + 2mf + f**2\n      A0 u = sgn*nt2::sqr(m);\n      A0 u1 = sgn*fma(m+m,f,sqr(f));\n      // u is exact, u1 is small.\n      if (u+u1 >  nt2::Maxlog<A0>()) return nt2::Inf<A0>();\n      return nt2::exp(u)*nt2::exp(u1);\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "622390bd8acc34ffbac7b414f8d86cfde94f20fd", "size": 3098, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/functions/scalar/expx2.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/exponential/include/nt2/exponential/functions/scalar/expx2.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/exponential/include/nt2/exponential/functions/scalar/expx2.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 36.880952381, "max_line_length": 82, "alphanum_fraction": 0.5564880568, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.5354432128346693}}
{"text": "#include <Eigen/Dense>\n#include <fmt/core.h>\n\n#include <algorithm>\n#include <array>\n#include <fstream>\n#include <iostream>\n#include <ostream>\n#include <string>\n#include <vector>\n\nstruct Line {\n  std::array<int, 2> x = {};\n  std::array<int, 2> y = {};\n};\n\nstd::ostream &operator<<(std::ostream &os, Line const &l) {\n  os << \"[(\" << l.y[0] << \",\" << l.x[0] << \"),(\" << l.y[1] << \",\" << l.x[1]\n     << \")]\";\n  return os;\n}\n\nLine parseLine(std::string_view v) {\n  auto first_comma = v.find_first_of(',');\n  std::string first_int(v.data(), v.data() + first_comma);\n  Line l;\n  l.x[0] = std::stoi(first_int);\n\n  auto first_space = v.find_first_of(' ');\n  std::string second_int(v.data() + first_comma + 1, first_space);\n  l.y[0] = std::stoi(second_int);\n\n  auto last_space = v.find_last_of(' ');\n  auto last_comma = v.find_last_of(',');\n  std::string third_int(v.data() + last_space + 1, v.data() + last_comma);\n  l.x[1] = std::stoi(third_int);\n\n  std::string fourth_int(v.data() + last_comma + 1, v.data() + v.size());\n  l.y[1] = std::stoi(fourth_int);\n\n  return l;\n}\n\nauto parseFile(char const *file_name) {\n  auto file = std::ifstream(file_name);\n  std::string line;\n  std::vector<Line> out;\n  while (std::getline(file, line)) {\n    out.push_back(parseLine(line));\n  }\n\n  return out;\n}\n\nauto maxExtent(std::vector<Line> const &ls) {\n  auto const &l =\n      *std::max_element(ls.begin(), ls.end(), [](Line const &a, Line const &b) {\n        return std::max({a.x[0], a.x[1], a.y[0], a.y[1]}) <\n               std::max({b.x[0], b.x[1], b.y[0], b.y[1]});\n      });\n  return std::max({l.x[0], l.x[1], l.y[0], l.y[1]});\n}\n\nint main(int _, char **argv) {\n  auto input = parseFile(argv[1]);\n  auto max_extent = maxExtent(input);\n  fmt::print(\"Max extent {}\\n\", max_extent);\n  Eigen::MatrixXi M(max_extent + 1, max_extent + 1);\n  M.setZero();\n\n  for (auto const &l : input) {\n    if (l.x[0] == l.x[1]) {\n      auto col = M.col(l.x[0]);\n      auto y = l.y;\n      std::sort(y.begin(), y.end());\n      for (auto i = y[0]; i <= y[1]; ++i) {\n        ++col(i);\n      }\n    } else if (l.y[0] == l.y[1]) {\n      auto row = M.row(l.y[0]);\n      auto x = l.x;\n      std::sort(x.begin(), x.end());\n      for (auto i = x[0]; i <= x[1]; ++i) {\n        ++row(i);\n      }\n    } else {\n      auto len = std::max(l.x[0], l.x[1]) - std::min(l.x[0], l.x[1]) + 1;\n      auto ymove = (l.y[0] < l.y[1]) ? 1 : -1;\n      auto xmove = (l.x[0] < l.x[1]) ? 1 : -1;\n      auto x = l.x[0];\n      auto y = l.y[0];\n      for (auto i = 0; i < len; ++i) {\n        ++M(y, x);\n        x += xmove;\n        y += ymove;\n      }\n    }\n  }\n\n  if (max_extent < 20) {\n    for(auto r = 0; r < max_extent + 1; ++r){\n      for(auto c = 0; c < max_extent + 1; ++c){\n        if(M(r,c) == 0){\n          std::cout << \". \";\n        } else {\n          std::cout << M(r,c) << \" \";\n        }\n      }\n      std::cout << \"\\n\";\n    }\n  }\n\n  auto count = 0;\n  for (auto i = 0; i < M.size(); ++i) {\n    if (M.data()[i] > 1) {\n      ++count;\n    }\n  }\n\n  fmt::print(\"Num overlap {}\\n\", count);\n}\n", "meta": {"hexsha": "fc7ed30072b09e4cc7c389f91dfdea0510201875", "size": 3025, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/day5/day5.cpp", "max_stars_repo_name": "calewis/advent-of-code21", "max_stars_repo_head_hexsha": "a4efc4c551122c1a48f334c7ead237919586de35", "max_stars_repo_licenses": ["MIT"], "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/day5/day5.cpp", "max_issues_repo_name": "calewis/advent-of-code21", "max_issues_repo_head_hexsha": "a4efc4c551122c1a48f334c7ead237919586de35", "max_issues_repo_licenses": ["MIT"], "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/day5/day5.cpp", "max_forks_repo_name": "calewis/advent-of-code21", "max_forks_repo_head_hexsha": "a4efc4c551122c1a48f334c7ead237919586de35", "max_forks_repo_licenses": ["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.7950819672, "max_line_length": 80, "alphanum_fraction": 0.4961983471, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.6442250928250374, "lm_q1q2_score": 0.5354432125464617}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"math/algo/dp.h\" // header to test\n\nusing namespace biosim;\n\nsize_t fibonacci_function(math::tensor<size_t> const &__input, std::vector<size_t> const &__pos) {\n  if(__pos.size() != 1) {\n    throw std::invalid_argument(\"fibonacci numbers cannot be calculated for multidimensional positions\");\n  }\n  return __pos[0] < 2 ? 1 : __input({(__pos[0] - 1)}) + __input({(__pos[0] - 2)});\n}\n\nBOOST_AUTO_TEST_SUITE(suite_dp)\n\nBOOST_AUTO_TEST_CASE(dp_fib) {\n  math::algo::dp<size_t> fib;\n  math::tensor<size_t> fibonacci_numbers(fib.calculate(math::tensor<size_t>({10}), &fibonacci_function));\n  BOOST_CHECK(fibonacci_numbers({9}) == 55);\n  BOOST_REQUIRE_THROW(fib.calculate(math::tensor<size_t>({10, 3}), &fibonacci_function), std::invalid_argument);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4be1e68954447965cd052ab8af7aac19a00c7db5", "size": 817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/algo/dp.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/dp.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/dp.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": 34.0416666667, "max_line_length": 112, "alphanum_fraction": 0.7258261934, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5354403831032948}}
{"text": "#ifndef PARTICLE_HPP\n#define PARTICLE_HPP\n\n#define _USE_MATH_DEFINES\n#include <math.h>      \n\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n#include \"constants.hpp\"\n#include \"functions.hpp\"\n\nusing namespace Eigen;\n\nclass Particle {\n\tprivate:\n\t\n\tpublic:\t\n\n\t\tParticle(const int &N_LM);\n\n\t\tvoid AddNewLM(const MatrixXd &z, const MatrixXd &Q);\n\t\tdouble ComputeWeight(const MatrixXd &z, const MatrixXd &Q);\n\t\tvoid UpdateLM(const MatrixXd &z, const MatrixXd &Q);\n\n\t\tdouble w_ = 0.0;\n\t\tdouble x_ = 0.0;\n\t\tdouble y_ = 0.0;\n\t\tdouble yaw_ = 0.0;\n\n\t\t//landmark x-y postion\n\t\tMatrixXd lm_; \n\n\t\t//landmarks position covariance\n\t\tMatrixXd lmp_;\n};\n\nstd::array<MatrixXd,4> ComputeJacobian(const Particle* p, const MatrixXd &xf, const MatrixXd &pf, const MatrixXd &Q);\nvoid UpdateKF(MatrixXd &xf, MatrixXd &pf, const MatrixXd &v, const MatrixXd &Q, const MatrixXd &Hf);\n\n\n\n#endif // PARTICLE_HPP", "meta": {"hexsha": "291ec0c7d43e0bca942d18d74e08b94f569c27e0", "size": 882, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/particle.hpp", "max_stars_repo_name": "dskart/ROBO_fast_slam", "max_stars_repo_head_hexsha": "cde36b06288981b189baa463719bb2605ab28794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-19T21:36:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T14:20:26.000Z", "max_issues_repo_path": "inc/particle.hpp", "max_issues_repo_name": "dskart/ROBO_fast_slam", "max_issues_repo_head_hexsha": "cde36b06288981b189baa463719bb2605ab28794", "max_issues_repo_licenses": ["MIT"], "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/particle.hpp", "max_forks_repo_name": "dskart/ROBO_fast_slam", "max_forks_repo_head_hexsha": "cde36b06288981b189baa463719bb2605ab28794", "max_forks_repo_licenses": ["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": 117, "alphanum_fraction": 0.7131519274, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5354403712106193}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// cross_validation::example::k_fold.cpp                                    //\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#include <algorithm>\n#include <iterator>\n#include <boost/tuple/tuple.hpp>\n#include <boost/foreach.hpp>\n#include <boost/format.hpp>\n#include <boost/typeof/typeof.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <boost/math/tools/precision.hpp>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n\n#include <boost/statistics/detail/cross_validation/estimator/adaptor/include.hpp> \n#include <boost/statistics/detail/cross_validation/k_fold/include.hpp> \n#include <boost/statistics/detail/cross_validation/error/include.hpp> \n\n#include <libs/statistics/detail/cross_validation/example/k_fold.h>\n\nvoid example_k_fold(std::ostream& os)\n{\n\n    os << \"-> example_k_fold :\" << std::endl;\n\n    // This example shows how to perform K train/predict cycles.\n    // The estimator is built upon a Boost.Accumulator for the mean.\n    // The input (x) equals the input (y), in this case, and has type double\n    \n    using namespace boost;\n    namespace stat = boost::statistics::detail;\n    namespace cv = stat::cross_validation;\n    namespace cv_es = cv::estimator;\n    namespace cv_ex = cv::extractor;\n    namespace cv_kf = cv::k_fold;\n\n    typedef mt19937                                 urng_;\n    typedef double                                  val_;\n    typedef std::vector<val_>                       vals_;\n    typedef range_iterator<vals_>::type             vals_it_;\n    typedef boost::normal_distribution<val_>        nd_;\n    typedef boost::variate_generator<urng_&,nd_>    vg_;\n\n    // This comes up often, so this metafunction saves a bit of time\n    typedef accumulators::tag::mean tag_;\n    typedef accumulators::stats<\n        tag_\n    >  stat_;\n    typedef accumulators::accumulator_set<val_,stat_> acc_;\n\n    // Boost.Accumulators cannot be used directly. An adaptor is needed.\n    typedef cv_es::adaptor::meta::nullary_predictor<acc_,tag_>      meta_p_;\n    typedef cv_es::adaptor::joined<\n        cv_es::adaptor::unary_trainer,\n        meta_p_::apply,\n        acc_\n    > joined_;\n\n    typedef cv_kf::partition<val_,cv_ex::identity> kf_p_;\n\n    const unsigned n = 1e1;\n    const unsigned k = 5e0;\n    BOOST_ASSERT(n % k == 0);\n\n    nd_ nd;\n    urng_ urng;\n    vg_ vg(urng,nd);\n\n    vals_ vec_x;\n    std::generate_n(\n        std::back_inserter(vec_x), \n        n,\n        vg\n    );\n    \n    // vec_x is duplicated in kf_p, which is intenteded in this example. \n    // example_k_fold in sandbox/kernel shows how to avoid duplication\n    \n    kf_p_ kf_p( \n        k,\n        boost::begin(vec_x),\n        boost::end(vec_x)\n    );\n    \n    struct float_{\n            \n        static bool equal(const val_& a, const val_& b){\n            static val_ e = boost::math::tools::epsilon<val_>();;\n            return fabs(a-b)< e;\n        }\n    \n    };\n    \n    // Tests that concatenating the test-data over all k increments, is \n    // identical to vec_x.  \n    for(unsigned i = 0; i<2; i++){ \n        if(i>0){\n            // 2nd pass to check that resets properly\n            kf_p.initialize(); \n        }\n    \n        vals_it_ vec_x_it  = boost::begin( vec_x );\n        while(kf_p.index()<kf_p.n_folds()){\n            os << kf_p << std::endl;\n            BOOST_FOREACH(const val_& t,kf_p.subset2())\n            {\n                val_ t1 = *vec_x_it;\n                BOOST_ASSERT( float_::equal(t,t1) );\n                ++vec_x_it;\n            }; \n            kf_p.increment();\n        }\n    }\n    os << std::endl;\n\n    // Cross-Validation #1\n    vals_ preds(n);\n    vals_it_ preds_b = boost::begin(preds); \n    vals_it_ preds_e; \n    BOOST_ASSERT(n / k > 1);\n    kf_p.initialize();\n    while(kf_p.index()<kf_p.n_folds()){\n        acc_ acc;\n        joined_ joined(acc);\n        preds_e = train_predict(\n            kf_p,\n            joined,\n            preds_b\n        );\n        val_ tmp = *preds_b;\n        BOOST_AUTO(\n            r,\n            make_iterator_range(boost::next(preds_b),preds_e)\n        );\n        BOOST_FOREACH(const val_& v, r)\n        {\n            // Because we use a nullary_estimator \n            // a.k.a. marginal estimator in statistical terminology.\n            BOOST_ASSERT(tmp == v);\n        }\n        \n        preds_b = preds_e;\n        kf_p.increment();\n    }\n\n    // Cross-Validation #2\n    {\n        vals_ output(n);\n        acc_ acc;\n        joined_ joined(acc);\n        cross_validate(\n            kf_p,\n            joined,\n            boost::begin(preds),\n            boost::begin(output)\n        );\n\n        val_ sqrt_mse = cv::error::sqrt_mse(\n            boost::begin(preds),\n            boost::end(preds),\n            boost::begin(output)\n        );\n\n        val_ mae = cv::error::mean_abs_error(\n            boost::begin(preds),\n            boost::end(preds),\n            boost::begin(output)\n        );\n        \n        os << \"sqrt_mse = \" << sqrt_mse << std::endl;\n        os << \"mae = \" << mae << std::endl;\n\n    }\n\n    os << \"<-\" << std::endl;\n\n}\n\n\n", "meta": {"hexsha": "57e88078ea4033a37a85c269cd4de486310010e1", "size": 5725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cross_validation/libs/statistics/detail/cross_validation/example/k_fold.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": "cross_validation/libs/statistics/detail/cross_validation/example/k_fold.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": "cross_validation/libs/statistics/detail/cross_validation/example/k_fold.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": 30.1315789474, "max_line_length": 82, "alphanum_fraction": 0.5456768559, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5354252318941236}}
{"text": "#include \"drake/common/trajectories/piecewise_polynomial.h\"\n\n#include <random>\n#include <stdexcept>\n#include <vector>\n\n#include <Eigen/Core>\n#include <gtest/gtest.h>\n\n#include \"drake/common/drake_assert.h\"\n#include \"drake/common/test_utilities/eigen_matrix_compare.h\"\n#include \"drake/common/test_utilities/expect_throws_message.h\"\n#include \"drake/common/trajectories/test/random_piecewise_polynomial.h\"\n#include \"drake/math/autodiff_gradient.h\"\n\nusing drake::math::autoDiffToGradientMatrix;\nusing drake::math::DiscardGradient;\nusing Eigen::Matrix;\nusing std::default_random_engine;\nusing std::normal_distribution;\nusing std::runtime_error;\nusing std::uniform_int_distribution;\nusing std::uniform_real_distribution;\nusing std::vector;\n\nnamespace drake {\nnamespace trajectories {\nnamespace {\n\ntemplate<typename T>\nvoid testIntegralAndDerivative() {\n  int num_coefficients = 5;\n  int num_segments = 3;\n  int rows = 3;\n  int cols = 5;\n\n  default_random_engine generator;\n  vector<double> segment_times =\n      PiecewiseTrajectory<double>::RandomSegmentTimes(num_segments, generator);\n  PiecewisePolynomial<T> piecewise =\n      test::MakeRandomPiecewisePolynomial<T>(\n          rows, cols, num_coefficients, segment_times);\n\n  // derivative(0) should be same as original piecewise.\n  EXPECT_TRUE(\n      CompareMatrices(piecewise.value(piecewise.start_time()),\n                      piecewise.derivative(0).value(piecewise.start_time()),\n                      1e-10, MatrixCompareType::absolute));\n\n  // differentiate integral, get original back\n  PiecewisePolynomial<T> piecewise_back = piecewise.integral().derivative();\n  if (!piecewise.isApprox(piecewise_back, 1e-10)) throw runtime_error(\"wrong\");\n\n  // check value at start time\n  MatrixX<T> desired_value_at_t0 =\n      MatrixX<T>::Random(piecewise.rows(), piecewise.cols());\n  PiecewisePolynomial<T> integral = piecewise.integral(desired_value_at_t0);\n  auto value_at_t0 = integral.value(piecewise.start_time());\n  EXPECT_TRUE(CompareMatrices(desired_value_at_t0, value_at_t0, 1e-10,\n                              MatrixCompareType::absolute));\n\n  // check continuity at sample points\n  for (int i = 0; i < piecewise.get_number_of_segments() - 1; ++i) {\n    EXPECT_EQ(integral.getPolynomial(i)\n                  .EvaluateUnivariate(integral.duration(i)),\n              integral.getPolynomial(i + 1).EvaluateUnivariate(0.0));\n  }\n}\n\ntemplate<typename T>\nvoid testBasicFunctionality() {\n  int max_num_coefficients = 6;\n  int num_tests = 100;\n  default_random_engine generator;\n  uniform_int_distribution<> int_distribution(1, max_num_coefficients);\n\n  for (int i = 0; i < num_tests; ++i) {\n    int num_coefficients = int_distribution(generator);\n    int num_segments = int_distribution(generator);\n    int rows = int_distribution(generator);\n    int cols = int_distribution(generator);\n\n    vector<double> segment_times =\n        PiecewiseTrajectory<double>::RandomSegmentTimes(num_segments,\n                                                        generator);\n    PiecewisePolynomial<T> piecewise1 = test::MakeRandomPiecewisePolynomial<T>(\n        rows, cols, num_coefficients, segment_times);\n    PiecewisePolynomial<T> piecewise2 = test::MakeRandomPiecewisePolynomial<T>(\n        rows, cols, num_coefficients, segment_times);\n    PiecewisePolynomial<T> piecewise3_not_matching_rows =\n        test::MakeRandomPiecewisePolynomial<T>(rows + 1, cols, num_coefficients,\n                                               segment_times);\n    PiecewisePolynomial<T> piecewise4_not_matching_cols =\n        test::MakeRandomPiecewisePolynomial<T>(rows, cols + 1, num_coefficients,\n                                               segment_times);\n    PiecewisePolynomial<T> piecewise5 = test::MakeRandomPiecewisePolynomial<T>(\n        cols, rows, num_coefficients, segment_times);\n\n    normal_distribution<double> normal;\n    double shift = normal(generator);\n    MatrixX<T> offset =\n        MatrixX<T>::Random(piecewise1.rows(), piecewise1.cols());\n\n    PiecewisePolynomial<T> sum = piecewise1 + piecewise2;\n    PiecewisePolynomial<T> difference = piecewise2 - piecewise1;\n    PiecewisePolynomial<T> piecewise1_plus_offset = piecewise1 + offset;\n    PiecewisePolynomial<T> piecewise1_minus_offset = piecewise1 - offset;\n    PiecewisePolynomial<T> piecewise1_shifted = piecewise1;\n    piecewise1_shifted.shiftRight(shift);\n    PiecewisePolynomial<T> product = piecewise1 * piecewise5;\n    PiecewisePolynomial<T> unary_minus = -piecewise1;\n\n    const double total_time = segment_times.back() - segment_times.front();\n    PiecewisePolynomial<T> piecewise2_twice = piecewise2;\n    PiecewisePolynomial<T> piecewise2_shifted = piecewise2;\n    piecewise2_shifted.shiftRight(total_time);\n\n    // Checks that concatenation of trajectories that are not time\n    // aligned at the connecting ends is a failure.\n    PiecewisePolynomial<T> piecewise2_shifted_twice = piecewise2;\n    piecewise2_shifted_twice.shiftRight(2. * total_time);\n    EXPECT_THROW(piecewise2_twice.ConcatenateInTime(\n        piecewise2_shifted_twice), std::runtime_error);\n\n    // Checks that concatenation of trajectories that have different\n    // row counts is a failure.\n    PiecewisePolynomial<T> piecewise3_not_matching_rows_shifted =\n        piecewise3_not_matching_rows;\n    piecewise3_not_matching_rows_shifted.shiftRight(total_time);\n    EXPECT_THROW(piecewise2_twice.ConcatenateInTime(\n        piecewise3_not_matching_rows_shifted), std::runtime_error);\n\n    // Checks that concatenation of trajectories that have different\n    // col counts is a failure.\n    PiecewisePolynomial<T> piecewise4_not_matching_cols_shifted =\n        piecewise4_not_matching_cols;\n    piecewise4_not_matching_cols_shifted.shiftRight(total_time);\n    EXPECT_THROW(piecewise2_twice.ConcatenateInTime(\n        piecewise4_not_matching_cols_shifted), std::runtime_error);\n\n    piecewise2_twice.ConcatenateInTime(piecewise2_shifted);\n\n    uniform_real_distribution<double> uniform(piecewise1.start_time(),\n                                              piecewise1.end_time());\n    double t = uniform(generator);\n\n    EXPECT_TRUE(CompareMatrices(sum.value(t),\n                                piecewise1.value(t) + piecewise2.value(t), 1e-8,\n                                MatrixCompareType::absolute));\n\n    EXPECT_TRUE(CompareMatrices(difference.value(t),\n                                piecewise2.value(t) - piecewise1.value(t), 1e-8,\n                                MatrixCompareType::absolute));\n\n    EXPECT_TRUE(CompareMatrices(piecewise1_plus_offset.value(t),\n                                piecewise1.value(t) + offset, 1e-8,\n                                MatrixCompareType::absolute));\n\n    EXPECT_TRUE(CompareMatrices(piecewise1_minus_offset.value(t),\n                                piecewise1.value(t) - offset, 1e-8,\n                                MatrixCompareType::absolute));\n\n    EXPECT_TRUE(CompareMatrices(piecewise1_shifted.value(t),\n                                piecewise1.value(t - shift), 1e-8,\n                                MatrixCompareType::absolute));\n\n    EXPECT_TRUE(CompareMatrices(product.value(t),\n                                piecewise1.value(t) * piecewise5.value(t), 1e-8,\n                                MatrixCompareType::absolute));\n\n    EXPECT_TRUE(CompareMatrices(unary_minus.value(t), -(piecewise1.value(t))));\n\n    // Checks that `piecewise2_twice` is effectively the concatenation of\n    // `piecewise2` and a copy of `piecewise2` that is shifted to the right\n    // (i.e. towards increasing values of t) by an amount equal to its entire\n    // time length. To this end, it verifies that R(t\u2093) = R(t\u2093 + d), where\n    // R(t) = P(t) for t0 <= t <= t1, R(t) = Q(t) for t1 <= t <= t2,\n    // Q(t) = P(t - d) for t1 <= t <= t2, d = t1 - t0 = t2 - t1 and\n    // t0 < t\u2093 < t1, with P, Q and R functions being piecewise polynomials.\n    EXPECT_TRUE(CompareMatrices(\n        piecewise2_twice.value(t), piecewise2_twice.value(t + total_time),\n        1e-8, MatrixCompareType::absolute));\n  }\n}\n\ntemplate<typename T>\nvoid testValueOutsideOfRange() {\n  default_random_engine generator;\n  vector<double> segment_times =\n      PiecewiseTrajectory<double>::RandomSegmentTimes(6, generator);\n  PiecewisePolynomial<T> piecewise =\n      test::MakeRandomPiecewisePolynomial<T>(3, 4, 5, segment_times);\n\n  EXPECT_TRUE(CompareMatrices(piecewise.value(piecewise.start_time()),\n                              piecewise.value(piecewise.start_time() - 1.0),\n                              1e-10, MatrixCompareType::absolute));\n\n  EXPECT_TRUE(CompareMatrices(piecewise.value(piecewise.end_time()),\n                              piecewise.value(piecewise.end_time() + 1.0),\n                              1e-10, MatrixCompareType::absolute));\n}\n\n// Test the generation of cubic splines with first and second derivatives\n// continuous between the end of the last segment and the beginning of the\n// first.\nGTEST_TEST(testPiecewisePolynomial, CubicSplinePeriodicBoundaryConditionTest) {\n  Eigen::VectorXd breaks(5);\n  breaks << 0, 1, 2, 3, 4;\n\n  // Spline in 3d.\n  Eigen::MatrixXd samples(3, 5);\n  samples << 1, 1, 1,\n        2, 2, 2,\n        0, 3, 3,\n        -2, 2, 2,\n        1, 1, 1;\n  const bool periodic_endpoint = true;\n\n  PiecewisePolynomial<double> periodic_spline =\n      PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(\n          breaks, samples, periodic_endpoint);\n\n  std::unique_ptr<Trajectory<double>> spline_dt =\n      periodic_spline.MakeDerivative(1);\n  std::unique_ptr<Trajectory<double>> spline_ddt =\n      periodic_spline.MakeDerivative(2);\n\n  Eigen::VectorXd begin_dt = spline_dt->value(breaks(0));\n  Eigen::VectorXd end_dt = spline_dt->value(breaks(breaks.size() - 1));\n\n  Eigen::VectorXd begin_ddt = spline_ddt->value(breaks(0));\n  Eigen::VectorXd end_ddt = spline_ddt->value(breaks(breaks.size() - 1));\n\n  EXPECT_TRUE(CompareMatrices(end_dt, begin_dt, 1e-14));\n  EXPECT_TRUE(CompareMatrices(end_ddt, begin_ddt, 1e-14));\n\n  // Test that evaluating the derivative directly gives the same results.\n  const double t = 1.234;\n  EXPECT_TRUE(CompareMatrices(periodic_spline.EvalDerivative(t, 1),\n                              spline_dt->value(t), 1e-14));\n  EXPECT_TRUE(CompareMatrices(periodic_spline.EvalDerivative(t, 2),\n                              spline_ddt->value(t), 1e-14));\n}\n\n// Test various exception cases.  We want to check that these throw rather\n// than crash (or return potentially bad data).\nGTEST_TEST(testPiecewisePolynomial, ExceptionsTest) {\n  Eigen::VectorXd breaks(5);\n  breaks << 0, 1, 2, 3, 4;\n\n  // Spline in 3d.\n  Eigen::MatrixXd samples(3, 5);\n  samples << 1, 1, 1,\n        2, 2, 2,\n        0, 3, 3,\n        -2, 2, 2,\n        1, 1, 1;\n\n  // No throw with monotonic breaks.\n  PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(\n      breaks, samples, true);\n\n  // Throw when breaks are not strictly monotonic.\n  breaks[1] = 0;\n  DRAKE_EXPECT_THROWS_MESSAGE(\n      PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(\n          breaks, samples, true),\n      std::runtime_error, \"Times must be in increasing order.\");\n}\n\nGTEST_TEST(testPiecewisePolynomial, AllTests) {\n  testIntegralAndDerivative<double>();\n\n  testBasicFunctionality<double>();\n\n  testValueOutsideOfRange<double>();\n}\n\nGTEST_TEST(testPiecewisePolynomial, VectorValueTest) {\n  // Note: Keep one negative time to confirm that negative values can work for\n  // constant trajectories.\n  const std::vector<double> times = {-1.5, 0, .5, 1, 1.5};\n  const Eigen::Vector3d value(1, 2, 3);\n\n  const PiecewisePolynomial<double> col(value);\n  Eigen::MatrixXd out = col.vector_values(times);\n  EXPECT_EQ(out.rows(), 3);\n  EXPECT_EQ(out.cols(), 5);\n  for (int i = 0; i < 4; i++) {\n    EXPECT_TRUE(CompareMatrices(out.col(i), value, 0));\n  }\n\n  PiecewisePolynomial<double> row(value.transpose());\n  out = row.vector_values(times);\n  EXPECT_EQ(out.rows(), 5);\n  EXPECT_EQ(out.cols(), 3);\n  for (int i = 0; i < 4; i++) {\n    EXPECT_TRUE(CompareMatrices(out.row(i), value.transpose(), 0));\n  }\n\n  PiecewisePolynomial<double> mat(Eigen::Matrix3d::Identity());\n  DRAKE_EXPECT_THROWS_MESSAGE(\n      mat.vector_values(times), std::runtime_error,\n      \"This method only supports vector-valued trajectories.\");\n}\n\nGTEST_TEST(testPiecewisePolynomial, RemoveFinalSegmentTest) {\n  Eigen::VectorXd breaks(3);\n  breaks << 0, .5, 1.;\n  Eigen::MatrixXd samples(2, 3);\n  samples << 1, 1, 2,\n             2, 0, 3;\n\n  PiecewisePolynomial<double> pp =\n      PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(\n          breaks, samples);\n\n  EXPECT_EQ(pp.end_time(), 1.);\n  EXPECT_EQ(pp.get_number_of_segments(), 2);\n\n  pp.RemoveFinalSegment();\n  EXPECT_EQ(pp.end_time(), .5);\n  EXPECT_EQ(pp.get_number_of_segments(), 1);\n\n  pp.RemoveFinalSegment();\n  EXPECT_TRUE(pp.empty());\n}\n\nstd::unique_ptr<Trajectory<double>> TestReverseTime(\n    const PiecewisePolynomial<double>& pp_orig) {\n  std::unique_ptr<Trajectory<double>> pp_ptr = pp_orig.Clone();\n  PiecewisePolynomial<double>* pp =\n      dynamic_cast<PiecewisePolynomial<double>*>(pp_ptr.get());\n\n  pp->ReverseTime();\n  // Start time and end time have been switched.\n  EXPECT_NEAR(pp->start_time(), -pp_orig.end_time(), 1e-14);\n  EXPECT_NEAR(pp->end_time(), -pp_orig.start_time(), 1e-14);\n\n  for (const double t : {0.1, .2, .52, .77}) {\n    EXPECT_TRUE(CompareMatrices(pp->value(t), pp_orig.value(-t), 1e-14));\n  }\n  return pp_ptr;\n}\n\nvoid TestScaling(const PiecewisePolynomial<double>& pp_orig,\n                 const double scale) {\n  std::unique_ptr<Trajectory<double>> pp_ptr = pp_orig.Clone();\n  PiecewisePolynomial<double>* pp =\n      dynamic_cast<PiecewisePolynomial<double>*>(pp_ptr.get());\n\n  pp->ScaleTime(scale);\n  EXPECT_NEAR(pp->start_time(), scale * pp_orig.start_time(), 1e-14);\n  EXPECT_NEAR(pp->end_time(), scale * pp_orig.end_time(), 1e-14);\n  for (const double trel : {0.1, .2, .52, .77}) {\n    const double t = pp_orig.start_time() +\n                     trel * (pp_orig.end_time() - pp_orig.start_time());\n    EXPECT_TRUE(CompareMatrices(pp->value(scale * t), pp_orig.value(t), 1e-14));\n  }\n}\n\n\nGTEST_TEST(testPiecewisePolynomial, ReverseAndScaleTimeTest) {\n  Eigen::VectorXd breaks(3);\n  breaks << 0, .5, 1.;\n  Eigen::MatrixXd samples(2, 3);\n  samples << 1, 1, 2,\n             2, 0, 3;\n\n  const PiecewisePolynomial<double> zoh =\n      PiecewisePolynomial<double>::ZeroOrderHold(breaks, samples);\n  auto reversed_zoh = TestReverseTime(zoh);\n  // Confirm that the documentation is correct about the subtle behavior at the\n  // break-points due to the switch in the half-open interval (since zoh is\n  // discontinuous at the breaks).\n  EXPECT_FALSE(\n      CompareMatrices(reversed_zoh->value(-breaks(1)), zoh.value(breaks(1))));\n  EXPECT_TRUE(CompareMatrices(reversed_zoh->value(-breaks(1)),\n                              zoh.value(breaks(1) - 1e-14)));\n  TestScaling(zoh, 2.3);\n\n  const PiecewisePolynomial<double> foh =\n      PiecewisePolynomial<double>::FirstOrderHold(breaks, samples);\n  TestReverseTime(foh);\n  TestScaling(foh, 1.2);\n  TestScaling(foh, 3.6);\n\n  const PiecewisePolynomial<double> spline =\n      PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(\n          breaks, samples);\n  TestReverseTime(spline);\n  TestScaling(spline, 2.0);\n  TestScaling(spline, 4.3);\n}\n\nGTEST_TEST(testPiecewisePolynomial, ReshapeAndBlockTest) {\n  std::vector<double> breaks = {0, .5, 1.};\n  std::vector<Eigen::MatrixXd> samples(3);\n  samples[0].resize(2, 3);\n  samples[0] << 1, 1, 2, 2, 0, 3;\n  samples[1].resize(2, 3);\n  samples[1] << 3, 4, 5, 6, 7, 8;\n  samples[2].resize(2, 3);\n  samples[2] << -.2, 33., 5.4, -2.1, 52, 12;\n\n  PiecewisePolynomial<double> zoh =\n      PiecewisePolynomial<double>::ZeroOrderHold(breaks, samples);\n  EXPECT_EQ(zoh.rows(), 2);\n  EXPECT_EQ(zoh.cols(), 3);\n\n  zoh.Reshape(3, 2);\n  EXPECT_EQ(zoh.rows(), 3);\n  EXPECT_EQ(zoh.cols(), 2);\n\n  samples[0].resize(3, 2);\n  samples[1].resize(3, 2);\n  EXPECT_TRUE(CompareMatrices(zoh.value(0.25), samples[0]));\n  EXPECT_TRUE(CompareMatrices(zoh.value(0.75), samples[1]));\n\n  PiecewisePolynomial<double> block = zoh.Block(1, 1, 2, 1);\n  EXPECT_EQ(block.rows(), 2);\n  EXPECT_EQ(block.cols(), 1);\n  EXPECT_EQ(block.start_time(), zoh.start_time());\n  EXPECT_EQ(block.end_time(), zoh.end_time());\n  EXPECT_EQ(block.get_number_of_segments(), zoh.get_number_of_segments());\n\n  EXPECT_EQ(zoh.Block(0, 0, 1, 1).value(0.25), samples[0].block(0, 0, 1, 1));\n  EXPECT_EQ(zoh.Block(2, 1, 1, 1).value(0.75), samples[1].block(2, 1, 1, 1));\n  EXPECT_EQ(zoh.Block(1, 1, 2, 1).value(0.75), samples[1].block(1, 1, 2, 1));\n}\n\nGTEST_TEST(testPiecewisePolynomial, IsApproxTest) {\n  Eigen::VectorXd breaks(3);\n  breaks << 0, .5, 1.;\n  Eigen::MatrixXd samples(2, 3);\n  samples << 1, 2, 3, -5, -4, -3;\n  // Make the numbers bigger to exaggerate the tolerance test.\n  samples *= 1000;\n\n  const PiecewisePolynomial<double> pp1 =\n      PiecewisePolynomial<double>::FirstOrderHold(breaks, samples);\n  const PiecewisePolynomial<double> pp2 = pp1 + Eigen::Vector2d::Ones();\n  EXPECT_FALSE(pp1.isApprox(pp2, 0.1, ToleranceType::kAbsolute));\n  EXPECT_TRUE(pp1.isApprox(pp2, 0.1, ToleranceType::kRelative));\n}\n\ntemplate <typename T>\nvoid TestScalarType() {\n  VectorX<T> breaks(3);\n  breaks << 0, .5, 1.;\n  MatrixX<T> samples(2, 3);\n  samples << 1, 1, 2, 2, 0, 3;\n\n  const PiecewisePolynomial<T> spline =\n      PiecewisePolynomial<T>::CubicWithContinuousSecondDerivatives(\n          breaks, samples);\n\n  const MatrixX<T> value = spline.value(0.5);\n  EXPECT_NEAR(ExtractDoubleOrThrow(value(0)),\n              ExtractDoubleOrThrow(samples(0, 1)), 1e-14);\n  EXPECT_NEAR(ExtractDoubleOrThrow(value(1)),\n              ExtractDoubleOrThrow(samples(1, 1)), 1e-14);\n}\n\nGTEST_TEST(PiecewiseTrajectoryTest, ScalarTypes) {\n  TestScalarType<double>();\n  TestScalarType<AutoDiffXd>();\n  TestScalarType<symbolic::Expression>();\n}\n\n// Confirm the expected behavior of PiecewisePolynomial<Expression>.\nGTEST_TEST(PiecewiseTrajectoryTest, SymbolicValues) {\n  using symbolic::Expression;\n  using symbolic::Variable;\n\n  const Vector3<Expression> breaks(0, .5, 1.);\n  const RowVector3<Expression> samples(6, 5, 4);\n  const PiecewisePolynomial<Expression> foh =\n      PiecewisePolynomial<Expression>::FirstOrderHold(breaks, samples);\n\n  // value() works if breaks and coefficients are Expressions holding double\n  // values, evaluated at a double-valued time.\n  EXPECT_NEAR(ExtractDoubleOrThrow(foh.value(0.25)(0)), 5.5, 1e-14);\n\n  // Symbolic time throws (because GetSegmentIndex returns an int in the middle\n  // of the evaluation stack, breaking the Expression pipeline),\n  EXPECT_THROW(foh.value(Variable(\"t\")), std::runtime_error);\n\n  // Symbolic breaks causes the construction methods to throw.\n  const Vector3<Expression> symbolic_breaks(Variable(\"t0\"), Variable(\"t1\"),\n                                            Variable(\"t2\"));\n  EXPECT_THROW(\n      PiecewisePolynomial<Expression>::FirstOrderHold(symbolic_breaks, samples),\n      std::runtime_error);\n\n  // For symbolic samples (and therefore coefficients), value() returns the\n  // symbolic form at the specified time.\n  const Variable x0(\"x0\");\n  const Variable x1(\"x1\");\n  const Variable x2(\"x2\");\n  const RowVector3<Expression> symbolic_samples(x0, x1, x2);\n  const PiecewisePolynomial<Expression> foh_w_symbolic_coeffs =\n      PiecewisePolynomial<Expression>::FirstOrderHold(breaks, symbolic_samples);\n  EXPECT_TRUE(foh_w_symbolic_coeffs.value(0.25)(0).Expand().EqualTo(0.5 * x0 +\n                                                                    0.5 * x1));\n}\n\n// Verifies that the derivatives obtained by evaluating a\n// `PiecewisePolynomial<AutoDiffXd>` and extracting the gradient of the result\n// match those obtained by taking the derivative of the whole trajectory and\n// evaluating it at the same point.\nGTEST_TEST(PiecewiseTrajectoryTest, AutoDiffDerivativesTest) {\n  VectorX<AutoDiffXd> breaks(3);\n  breaks << 0, .5, 1.;\n  MatrixX<AutoDiffXd> samples(2, 3);\n  samples << 1, 1, 2, 2, 0, 3;\n\n  const PiecewisePolynomial<AutoDiffXd> trajectory =\n      PiecewisePolynomial<AutoDiffXd>::CubicWithContinuousSecondDerivatives(\n          breaks, samples);\n  std::unique_ptr<Trajectory<AutoDiffXd>> derivative_trajectory =\n      trajectory.MakeDerivative();\n  const int num_times = 100;\n  VectorX<double> t = VectorX<double>::LinSpaced(\n      num_times, ExtractDoubleOrThrow(trajectory.start_time()),\n      ExtractDoubleOrThrow(trajectory.end_time()));\n  const double tolerance = 20 * std::numeric_limits<double>::epsilon();\n  for (int k = 0; k < num_times; ++k) {\n    AutoDiffXd t_k = math::initializeAutoDiff(Vector1d{t(k)})[0];\n    MatrixX<double> derivative_value =\n        autoDiffToGradientMatrix(trajectory.value(t_k));\n    MatrixX<double> expected_derivative_value =\n        DiscardGradient(derivative_trajectory->value(t(k)));\n    EXPECT_TRUE(CompareMatrices(derivative_value, expected_derivative_value,\n                                tolerance));\n  }\n}\n\n}  // namespace\n}  // namespace trajectories\n}  // namespace drake\n\n", "meta": {"hexsha": "67c8191e4826015c3b84c175e64fcd5e9d456416", "size": 21035, "ext": "cc", "lang": "C++", "max_stars_repo_path": "common/trajectories/test/piecewise_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/trajectories/test/piecewise_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/trajectories/test/piecewise_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": 38.7384898711, "max_line_length": 80, "alphanum_fraction": 0.686665082, "num_tokens": 5588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5354252267023895}}
{"text": "///////////////////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::chi_squared::derivative_log_unnormalized_pdf.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_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_CHI_SQUARED_DERIVATIVE_LOG_UNNORMALIZED_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_CHI_SQUARED_DERIVATIVE_LOG_UNNORMALIZED_HPP_ER_2009\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/numeric/conversion/converter.hpp>\n#include <boost/math/policies/policy.hpp>\n\nnamespace boost{\nnamespace math{\n\n    template<typename T,typename P>\n    T\n    derivative_log_unnormalized_pdf(\n        const boost::math::chi_squared_distribution<T,P>& dist,\n        const T& x\n    ){\n        BOOST_MATH_STD_USING  // for ADL of std functions\n        T degrees_of_freedom = dist.degrees_of_freedom();\n        // Error check:\n        T error_result;\n\n        static const char* function = \n            \"log_unnormalized_pdf(const chi_squared_distribution<%1%>&, %1%)\";\n\n        if(false == boost::math::detail::check_df(\n            function, degrees_of_freedom, &error_result, P()))\n                return error_result;\n\n        if((x < 0) || !(boost::math::isfinite)(x))\n        {\n            return boost::math::policies::raise_domain_error<T>(\n            function, \"Chi Square parameter was %1%, but must be > 0 !\", \n            x, P());\n        }\n\n        // Lumped case x == 0 in x<=0 above\n\n        static T one = static_cast<T>(1);\n        static T two = static_cast<T>(2);\n        return (degrees_of_freedom/two-one) / x - one/two;\n    }\n\n}// math\n}// boost\n\n#endif\n", "meta": {"hexsha": "282479d68cae9eac8a467afa381821dadf7a373e", "size": 2235, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/chi_squared/derivative_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/chi_squared/derivative_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/chi_squared/derivative_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": 40.6363636364, "max_line_length": 104, "alphanum_fraction": 0.5521252796, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5354252208804926}}
{"text": "/*\n * filtered_statistics.hpp\n *\n *  Created on: Nov 16, 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//libraries\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n//local\n#include \"../math/typedefs.hpp\"\n\n#pragma once\n\nnamespace eig = Eigen;\n\n/**\n * Routines for computing the statistics of fields operating on filtered field regions, e.g. gather statistics only\n * over the span of live & canonical TSDF union or intersection\n */\n\nnamespace math {\n\ntemplate<typename Scalar>\ndouble ratio_of_vector_lengths_above_threshold_band_union(\n\t\tconst Eigen::Matrix<math::Vector2<Scalar>, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& vector_field,\n\t\tScalar threshold,\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& warped_live_field,\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& canonical_field);\n\ntemplate<typename Scalar>\ndouble ratio_of_vector_lengths_above_threshold_band_union(\n\t\tconst Eigen::Tensor<math::Vector3<Scalar>, 3, Eigen::ColMajor>& vector_field,\n\t\tScalar threshold,\n\t\tconst Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& warped_live_field,\n\t\tconst Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& canonical_field);\n\ntemplate<typename Scalar>\nvoid mean_and_std_vector_length_band_union(Scalar& mean, Scalar& standard_deviation,\n\t\tconst Eigen::Matrix<math::Vector2<Scalar>, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& vector_field,\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& warped_live_field,\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& canonical_field);\n\ntemplate<typename Scalar>\nvoid mean_and_std_vector_length_band_union(Scalar& mean, Scalar& standard_deviation,\n\t\tconst Eigen::Tensor<math::Vector3<Scalar>, 3, Eigen::ColMajor>& vector_field,\n\t\tconst Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& warped_live_field,\n\t\tconst  Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& canonical_field);\n\n} //namespace math\n", "meta": {"hexsha": "f685e48c9b64c4a31b141c45e24b366941eb908e", "size": 2577, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/filtered_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/filtered_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/filtered_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": 39.6461538462, "max_line_length": 115, "alphanum_fraction": 0.7590221187, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.535425220565411}}
{"text": "#ifndef __aarch64__\n#include <algorithm>\n#include <boost/lexical_cast.hpp>\n\n#include \"json.hpp\"\n#include \"jget.h\"\n\nusing json = nlohmann::json;\n\n#include \"vnxvideoimpl.h\"\n#include \"vnxvideologimpl.h\"\n#include \"GrayAnalyticsBase.h\"\n\n#include <ipp.h>\n#include <ippi.h>\n#include <ippcv.h>\n\nextern \"C\" {\n#include <libswscale/swscale.h>\n}\n\nvoid vnxHistogramBasic_8u(const uint8_t* data, int stride, int width, int height, int* histogram) {\n    memset(histogram, 0, 256*sizeof(int));\n    for (int y = 0; y < height; ++y) {\n        const uint8_t* ptr = data + stride*y;\n        for (int x = 0; x < width; ++x)\n            ++histogram[ptr[x]];\n    }\n}\nvoid vnxMeanVariance_8u(const uint8_t* data, int stride, int width, int height, double& mean, double& variance) {\n    uint64_t vari = 0;\n    uint32_t meani = 0;\n    for (int y = 0; y < height; ++y) {\n        const uint8_t* ptr = data + stride*y;\n        for (int x = 0; x < width; ++x) {\n            int val = ptr[x];\n            meani += val;\n            vari += val*val;\n        }\n    }\n    mean = double(meani)/double(width*height);\n    variance = double(vari) / double(width*height);\n    variance -= mean*mean;\n}\n\n\nconst int motionCellsH = 8;\nconst int motionCellsV = 6;\n\nstruct SBasicAnalyticsStatus {\n    bool alarmTooDark;\n    bool alarmTooBright;\n    bool alarmTooBlurry;\n    uint64_t motionMask;\n    bool alarmMotion;\n    bool alarmGlobalChange;\n    uint64_t timestamp;\n    SBasicAnalyticsStatus() {\n        memset(this, 0, sizeof *this);\n    }\n    int alertsMask() {\n        return (alarmTooDark << 0) + (alarmTooBright << 1) + (alarmTooBlurry << 2) + (alarmMotion << 3) + (alarmGlobalChange << 4);\n    }\n};\n\nclass CBasicAnalytics : public CGrayAnalyticsBase {\npublic:\n    CBasicAnalytics(const std::vector<float>& roi, float framerate, bool too_bright, bool too_dark, bool too_blurry, float motion, bool scene_change)\n        : CGrayAnalyticsBase(roi) \n        , detect_too_bright(too_bright)\n        , detect_too_dark(too_dark)\n        , detect_too_blurry(too_blurry)\n        , detect_motion(motion)\n        , detect_scene_change(scene_change)\n        , skip_rate(framerate_to_skip_rate(framerate))\n    {\n        m_histogram.resize(256);\n        m_histogramSum.resize(256);\n        m_motionCells.resize(motionCellsH * motionCellsV);\n    }\nprotected:\n    virtual void reset(int width, int height) {\n        m_ratio = std::max(1, std::min(width / 320, height/200));\n        m_width = width / m_ratio;\n        m_height = height / m_ratio;\n\n        m_bufferLaplace.reset();\n        m_bufferMorph.reset();\n        m_morphSpec.reset();\n\n        m_frameNumber = 0;\n        m_stride = (m_width % 16) ? ((m_width / 16 + 1) * 16) : m_width;\n        for (auto b : { &m_data, &m_buffer0, &m_buffer1, &m_motionBackground, &m_motionVariance, &m_motionLabel, &m_motionDelta }) {\n            b->reset((uint8_t*)ippMalloc(m_stride*height), ippFree);\n            memset(b->get(), 0, m_stride*height);\n        }\n        m_resizeCtx.reset(sws_getContext(width, height, AV_PIX_FMT_GRAY8,\n            m_width, m_height, AV_PIX_FMT_GRAY8, SWS_POINT, nullptr, nullptr, nullptr), sws_freeContext);\n    }\n    virtual void process(uint8_t* data, int width, int stride, int height, uint64_t timestamp) {\n        //auto b = ippGetCpuClocks();\n        \n        // here we assume timestamp is in 90kHz or 100 kHz units\n        //VNXVIDEO_LOG(VNXLOG_DEBUG, \"vnxvideo\") << \"timestamp diff: \" << timestamp - m_timestamp;\n        if (m_frameNumber != 0 && (skip_rate > 0) && timestamp - m_status.timestamp < 1000000 * (1 << skip_rate)) {\n            // uncomment to show result (on each frame)\n            //ippiCopy_8u_C1R(m_motionLabel.get(), m_stride, data + width / 2 + height*stride / 2, stride, { m_width, m_height });\n            return;\n        }\n        uint8_t* dst = m_data.get();\n        sws_scale(m_resizeCtx.get(), &data, &stride, 0, height, &dst, &m_stride);\n\n        if (detect_too_bright || detect_too_dark)\n            detectTooBrightDark(m_data.get(), m_width, m_stride, m_height);\n        if (detect_too_blurry)\n            detectTooBlurry(m_data.get(), m_width, m_stride, m_height);\n        if (detect_motion)\n            detectMotion(m_data.get(), m_width, m_stride, m_height);\n        //auto e = ippGetCpuClocks();\n        //VNXVIDEO_LOG(VNXLOG_DEBUG, \"vnxvideo\") << \"Clocks elapsed: \" << e-b;\n\n        // uncomment this to show the resulting motion labels right on the image.\n        //ippiCopy_8u_C1R(m_motionLabel.get(), m_stride, data + width / 2 + height*stride / 2, stride, { m_width, m_height });\n        m_status.timestamp = timestamp;\n        sendEvents();\n    }\n    void sendEvents() {\n        json j(json::object());\n        if (detect_motion && (m_status.alarmMotion || m_lastSentStatus.alarmMotion)) {\n            j[\"motion\"] = m_status.alarmMotion;\n            j[\"motion_mask\"] = m_status.motionMask;\n        }\n        if(detect_scene_change && (m_status.alarmGlobalChange || m_lastSentStatus.alarmGlobalChange))\n            j[\"scene_changed\"] = m_status.alarmGlobalChange;\n        if (detect_too_bright && (m_status.alarmTooBright || m_lastSentStatus.alarmTooBright))\n            j[\"too_bright\"] = m_status.alarmTooBright;\n        if(detect_too_dark && (m_status.alarmTooDark || m_lastSentStatus.alarmTooDark))\n            j[\"too_dark\"] = m_status.alarmTooDark;\n        if(detect_too_blurry && (m_status.alarmTooBlurry || m_lastSentStatus.alarmTooBlurry))\n            j[\"too_blurry\"] = m_status.alarmTooBlurry;\n\n        if ((m_status.alertsMask() != m_lastSentStatus.alertsMask()) ||\n            ((m_status.alertsMask() != 0) && (m_status.timestamp - m_lastSentStatus.timestamp >= 10000000))) {\n            sendJson(j, m_status.timestamp);\n            m_lastSentStatus = m_status;\n        }\n    }\nprivate:\n    const bool detect_too_bright;\n    const bool detect_too_dark;\n    const bool detect_too_blurry;\n    const float detect_motion;\n    const bool detect_scene_change;\n    const int skip_rate; // corresponds to 0 -> 25-30, 1 -> 10, 2 -> 5, 3 -> 2 or less FPS\n                        // frames are skipped IF actual framerate exceeds that values. Otherwise, nothing is actually skipped.\n                        // That is, if FPS is limited to 5 at source, and skip_rate=1, - each frame will be processed.\n\n    std::vector<int> m_histogram;\n    std::vector<int> m_histogramSum;\n    int m_stride;\n    int m_ratio;\n    int m_width;\n    int m_height;\n    std::shared_ptr<SwsContext> m_resizeCtx;\n    std::shared_ptr<uint8_t> m_data;\n    std::shared_ptr<uint8_t> m_buffer0;\n    std::shared_ptr<uint8_t> m_buffer1;\n    std::shared_ptr<uint8_t> m_bufferLaplace;\n    std::shared_ptr<uint8_t> m_bufferMorph;\n    std::shared_ptr<IppiMorphState> m_morphSpec;\n\n    std::shared_ptr<uint8_t> m_motionBackground;\n    std::shared_ptr<uint8_t> m_motionDelta;\n    std::shared_ptr<uint8_t> m_motionVariance;\n    std::shared_ptr<uint8_t> m_motionLabel;\n\n    std::vector<int> m_motionCells;\n\n    SBasicAnalyticsStatus m_status;\n    SBasicAnalyticsStatus m_lastSentStatus;\n\n    int m_frameNumber;\nprivate:\n    void detectTooBrightDark(uint8_t* data, int width, int stride, int height) {\n        vnxHistogramBasic_8u(data, stride, width, height, &m_histogram[0]);\n        int sum = 0;\n        for (int k = 0; k < 256; ++k) {\n            sum += m_histogram[k];\n            m_histogramSum[k] = sum;\n        }\n        const int histogramTotal = m_histogramSum[255];\n        const int histogram10perc = histogramTotal * 1 / 10;\n        const int histogram90perc = histogramTotal * 9 / 10;\n        if (m_histogramSum[256 * 1 / 3] > histogram90perc) {\n            //VNXVIDEO_LOG(VNXLOG_DEBUG, \"vnxvideo\") << \"Image too dark\";\n            if(detect_too_dark)\n                m_status.alarmTooDark = true;\n            m_status.alarmTooBright = false;\n        }\n        else if (m_histogramSum[256 * 2 / 3] < histogram10perc) {\n            //VNXVIDEO_LOG(VNXLOG_DEBUG, \"vnxvideo\") << \"Image too bright\";\n            if(detect_too_bright)\n                m_status.alarmTooBright = true;\n            m_status.alarmTooDark = false;\n        }\n        else\n            m_status.alarmTooBright = m_status.alarmTooDark = false;\n    }\n    void detectTooBlurry(uint8_t* data, int width, int stride, int height) {\n        IppStatus s;\n        if (m_bufferLaplace.get() == nullptr) {\n            int sz;\n            s=ippiFilterLaplaceBorderGetBufferSize({ width,height }, ippMskSize3x3, ipp8u, ipp8u, 1, &sz);\n            if(s!=ippStsNoErr)\n                throw std::runtime_error(\"ippiFilterLaplaceBorderGetBufferSize failed: \"+boost::lexical_cast<std::string>(s));\n            m_bufferLaplace.reset(reinterpret_cast<Ipp8u*>(ippMalloc(sz)), ippFree);\n        }\n        s = ippiFilterLaplaceBorder_8u_C1R(data, stride, m_buffer0.get(), m_stride, { width, height }, ippMskSize3x3,\n            ippBorderConst, 0, m_bufferLaplace.get());\n        if (s != ippStsNoErr)\n            throw std::runtime_error(\"Could not perform ippiFilterLaplace_8uC1R\");\n\n        vnxHistogramBasic_8u(m_buffer0.get(), m_stride, width, height, &m_histogram[0]);\n        if (s != ippStsNoErr)\n            throw std::runtime_error(\"Could not perform ippiHistogramRange_8u_C1R\");\n        int sum = 0;\n        for (int k = 0; k < 256; ++k) {\n            sum += m_histogram[k];\n            m_histogramSum[k] = sum;\n        }\n        int laplace90 = 0;\n        int laplace95 = 0;\n        for (int k = 0; k < 256; ++k) {\n            if (!laplace90 && (m_histogramSum[k] >= (m_histogramSum[255] * 90) / 100))\n                laplace90 = k;\n            if (!laplace95 && (m_histogramSum[k] >= (m_histogramSum[255] * 95) / 100))\n                laplace95 = k;\n        }\n        double d = double(laplace95 - laplace90) / double(laplace90 + 1);\n        if (d<0.45) {\n            m_status.alarmTooBlurry = true;\n        }\n        else\n            m_status.alarmTooBlurry = false;\n    }\n\n    static void sigmaDeltaAdjust(uint8_t* data, int dstride, // data, reference to update to\n        uint8_t* result, int rstride, // result - inout buffer to be updated/adjusted\n        uint8_t* mask, int mstride, // mask - where to update. optional, may be 0\n        uint8_t* buffer, int bstride, // temporary buffer\n        IppiSize size, uint8_t learningRate) \n    {\n        ippiCompare_8u_C1R(data, dstride, result, rstride, buffer, bstride, size, ippCmpGreater);\n        if (nullptr != mask)\n            ippiAnd_8u_C1IR(mask, mstride, buffer, bstride, size);\n        ippiAndC_8u_C1IR(learningRate, buffer, bstride, size);\n        ippiAdd_8u_C1IRSfs(buffer, bstride, result, rstride, size, 0);\n        ippiCompare_8u_C1R(data, dstride, result, rstride, buffer, bstride, size, ippCmpLess);\n        if (nullptr != mask)\n            ippiAnd_8u_C1IR(mask, mstride, buffer, bstride, size);\n        ippiAndC_8u_C1IR(learningRate, buffer, bstride, size);\n        ippiSub_8u_C1IRSfs(buffer, bstride, result, rstride, size, 0);\n    }\n    void detectMotion(uint8_t* data, int width, int stride, int height) {\n        //\"Zipfian estimation\"\n        //http://perso.ensta-paristech.fr/~manzaner/Publis/icip09.pdf\n        //MOTION DETECTION: FAST AND ROBUST ALGORITHMS FOR EMBEDDED SYSTEMS\n        //L. Lacassagne A.Manzanera\n        const IppiSize size = { width, height };\n        if(0 == m_frameNumber)\n            ippiCopy_8u_C1R(data, stride, m_motionBackground.get(), m_stride, size);\n        else {\n            int sigma=1;\n            int t = m_frameNumber % (64 >> skip_rate);\n            while (t / (sigma * 2) > 0)\n                sigma *= 2;\n            // mask - where background should be updated\n            IppStatus st;\n            st=ippiThreshold_LTVal_8u_C1R(m_motionVariance.get(), m_stride,\n                m_buffer1.get(), m_stride, size,\n                sigma, 0);\n            st = ippiThreshold_GTVal_8u_C1IR(m_buffer1.get(), m_stride, size,\n                sigma-1, 255); \n            sigmaDeltaAdjust(data, stride, m_motionBackground.get(), m_stride,\n                m_buffer1.get(), m_stride, // mask\n                m_buffer0.get(), m_stride, // temp buffer\n                size, skip_rate + 1);\n        }\n\n        ippiAbsDiff_8u_C1R(m_motionBackground.get(), m_stride, data, stride, m_motionDelta.get(), m_stride, size);\n\n        if (0 == (m_frameNumber % 4)) { // T_V\n            ippiMulC_8u_C1RSfs(m_motionDelta.get(), m_stride, 4, m_buffer1.get(), m_stride, size, 0);\n\n            if (0 == m_frameNumber)\n                ippiCopy_8u_C1R(m_buffer1.get(), m_stride, m_motionVariance.get(), m_stride, size);\n            else\n                sigmaDeltaAdjust(m_buffer1.get(), m_stride, m_motionVariance.get(), m_stride,\n                    0, 0, // no mask\n                    m_buffer0.get(), m_stride, size, skip_rate + 1);\n            ippiThreshold_LTVal_8u_C1IR(m_motionVariance.get(), m_stride, size, 2, 2);\n            ippiThreshold_GTVal_8u_C1IR(m_motionVariance.get(), m_stride, size, 64, 64);\n        }\n\n        ippiCompare_8u_C1R(m_motionDelta.get(), m_stride, m_motionVariance.get(), m_stride, m_motionLabel.get(), m_stride, size, ippCmpGreater);\n        \n        // spatial postprocessing\n        IppStatus s;\n        if (m_morphSpec.get() == nullptr || m_bufferMorph.get() == nullptr) {\n            int specSize, bufferSize;\n            s = ippiMorphologyBorderGetSize_8u_C1R(size, { 3,3 }, &specSize, &bufferSize);\n            if (ippStsNoErr != s)\n                std::runtime_error(\"ippiMorphologyBorderGetSize_8u_C1R failed: \"+boost::lexical_cast<std::string>(s));\n            m_morphSpec.reset(reinterpret_cast<IppiMorphState*>(ippMalloc(specSize)), ippFree);\n            m_bufferMorph.reset(reinterpret_cast<Ipp8u*>(ippMalloc(bufferSize)), ippFree);\n\n            static uint8_t strel[9] = { 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, };\n            ippiMorphologyBorderInit_8u_C1R(size, strel, {3,3}, m_morphSpec.get(), m_bufferMorph.get());\n\n        }\n\n        ippiErodeBorder_8u_C1R(m_motionLabel.get(), m_stride, m_buffer0.get(), m_stride, size,\n            ippBorderConst, 0, m_morphSpec.get(), m_bufferMorph.get());\n        ippiDilateBorder_8u_C1R(m_buffer0.get(), m_stride, m_motionLabel.get(), m_stride, size,\n            ippBorderConst, 0, m_morphSpec.get(), m_bufferMorph.get());\n\n        motionProcessFinal();\n\n        ++m_frameNumber;\n    }\n    void motionProcessFinal() {\n        int cellW = m_width / motionCellsH;\n        int cellH = m_height / motionCellsV;\n        int cellSize = cellW*cellH;\n        m_status.motionMask = 0;\n        int motionCellsActive = 0;\n        for (int y = 0; y < motionCellsV; ++y) {\n            for (int x = 0; x < motionCellsH; ++x) {\n                int count = 0;\n                ippiCountInRange_8u_C1R(m_motionLabel.get() + x*cellW + y*m_stride*cellH, m_stride, { cellW, cellH },\n                    &count, 1, 255);\n                m_motionCells[motionCellsH*y + x] = count;\n                const int cellCountThreshold = std::min<int>(cellSize/2, std::max<int>(1, (int)ceil(cellSize) * (1.0 - detect_motion) * 0.2));\n                if (count >= cellCountThreshold) {\n                    m_status.motionMask |= (1UL << x) << (y*motionCellsH);\n                    ++motionCellsActive;\n                }\n            }\n        }\n        if (m_status.motionMask > 0) {\n            if (motionCellsActive < 2 * motionCellsH*motionCellsV / 3) {\n                if(detect_motion)\n                    m_status.alarmMotion = true;\n                m_status.alarmGlobalChange = false;\n                //VNXVIDEO_LOG(VNXLOG_DEBUG, \"vnxvideo\") << \"Motion detector active, mask=\" << m_motionMask;\n            }\n            else {\n                if(detect_motion)\n                    m_status.alarmMotion = true;\n                if(detect_scene_change)\n                    m_status.alarmGlobalChange = true;\n                // todo: could it be just a lighting conditions change or camera exposure adjusted?\n                //VNXVIDEO_LOG(VNXLOG_DEBUG, \"vnxvideo\") << \"Global scene change detected\";\n            }\n        }\n        else {\n            m_status.alarmMotion = false;\n            m_status.alarmGlobalChange = false;\n        }\n    }\n    static int framerate_to_skip_rate(float fps) {\n        int skip_rate = 0; // corresponds to 0 -> 25-30, 1 -> 10, 2 -> 5, 3 -> 2 or less FPS\n        if (fps > 0) {\n            if (fps <= 2)\n                skip_rate = 3;\n            else if (fps <= 5)\n                skip_rate = 2;\n            else if (fps <= 10)\n                skip_rate = 1;\n        }\n        return skip_rate;\n    }\n};\n\nnamespace VnxVideo {\n    IAnalytics* CreateAnalytics_Basic(const std::vector<float>& roi, float framerate, bool too_bright, bool too_dark, bool too_blurry, float motion, bool scene_change) {\n        return new CBasicAnalytics(roi, framerate, too_bright, too_dark, too_blurry, motion, scene_change);\n    }\n\n}\n#endif // aarch64\n", "meta": {"hexsha": "4b16aa2c74180532e3203a20989b6e938ed83483", "size": 16817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AnalyticsBasic.cpp", "max_stars_repo_name": "viinex/vnxvideo", "max_stars_repo_head_hexsha": "77090213d5bb40c38dd63f2c8e7cbd4bb90341c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T14:32:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T10:38:26.000Z", "max_issues_repo_path": "src/AnalyticsBasic.cpp", "max_issues_repo_name": "viinex/vnxvideo", "max_issues_repo_head_hexsha": "77090213d5bb40c38dd63f2c8e7cbd4bb90341c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AnalyticsBasic.cpp", "max_forks_repo_name": "viinex/vnxvideo", "max_forks_repo_head_hexsha": "77090213d5bb40c38dd63f2c8e7cbd4bb90341c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-11T20:52:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-11T20:52:30.000Z", "avg_line_length": 42.9005102041, "max_line_length": 169, "alphanum_fraction": 0.609561753, "num_tokens": 4682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.817574471748733, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5354252176544624}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n#include <maplab-common/pose_types.h>\n#include <maplab-common/quaternion-math.h>\n#include <maplab-common/test/testing-entrypoint.h>\n#include <maplab-common/test/testing-predicates.h>\n\n#include \"ceres-error-terms/parameterization/unit3-param.h\"\n\nTEST(Unit3, TestUnit3CeresParametrization) {\n  // Initial state values.\n  Eigen::Quaterniond q(Eigen::Quaterniond::Identity().slerp(\n      0.10, Eigen::Quaterniond::FromTwoVectors(\n                Eigen::Vector3d(1, 0, 0), Eigen::Vector3d(0, 0, 1))));\n\n  Eigen::Quaterniond p(Eigen::Quaterniond::Identity().slerp(\n      0.20, Eigen::Quaterniond::FromTwoVectors(\n                Eigen::Vector3d(1, 0, 0), Eigen::Vector3d(0, 0, 1))));\n\n  Eigen::Vector2d u(0.2, 0.3);\n\n  // Check: (q boxplus u)\n  Eigen::Quaterniond q_rot;\n  Eigen::Quaterniond q_rot_ceres;\n  Eigen::Vector2d u_new;\n  ceres_error_terms::Unit3::Plus(q, u, &q_rot);\n\n  ceres_error_terms::Unit3Parameterization ceres_unit3_parametrization;\n\n  ceres_unit3_parametrization.Plus(\n      q.coeffs().data(), u.data(), q_rot_ceres.coeffs().data());\n\n  pose::Quaternion q_rot_(q_rot);\n  pose::Quaternion q_rot_ceres_(q_rot_ceres);\n  EXPECT_NEAR_KINDR_QUATERNION(q_rot_, q_rot_ceres_, 1e-5);\n\n  // Check: p boxminus q\n  Eigen::Vector2d theta;\n  Eigen::Vector2d theta_ceres;\n  Eigen::Quaterniond p_orig;\n  ceres_error_terms::Unit3::Minus(p, q, &theta);\n  ceres_unit3_parametrization.Minus(\n      p.coeffs().data(), q.coeffs().data(), theta_ceres.data());\n\n  EXPECT_NEAR_EIGEN(theta, theta_ceres, 1e-5);\n}\n\nTEST(Unit3, TestUnit3) {\n  // Initial state values.\n  Eigen::Quaterniond q(Eigen::Quaterniond::Identity().slerp(\n      0.10, Eigen::Quaterniond::FromTwoVectors(\n                Eigen::Vector3d(1, 0, 0), Eigen::Vector3d(0, 0, 1))));\n\n  Eigen::Quaterniond p(Eigen::Quaterniond::Identity().slerp(\n      0.20, Eigen::Quaterniond::FromTwoVectors(\n                Eigen::Vector3d(1, 0, 0), Eigen::Vector3d(0, 0, 1))));\n\n  Eigen::Vector2d u(0.2, 0.3);\n\n  // Check: (q boxplus u) boxminus q = u\n  Eigen::Quaterniond q_rot;\n  Eigen::Vector2d u_new;\n  ceres_error_terms::Unit3::Plus(q, u, &q_rot);\n  ceres_error_terms::Unit3::Minus(q_rot, q, &u_new);\n\n  EXPECT_NEAR_EIGEN(u, u_new, 1e-5);\n\n  // Check: (q boxplus u) boxplus -u = q\n  Eigen::Quaterniond q_orig;\n  Eigen::Vector2d u_neg = -1.0 * u;\n  ceres_error_terms::Unit3::Plus(q_rot, u_neg, &q_orig);\n\n  pose::Quaternion q_(q);\n  pose::Quaternion q_orig_(q_orig);\n  EXPECT_NEAR_KINDR_QUATERNION(q_, q_orig_, 1e-5);\n\n  // Check: q boxplus (p boxminus q) = p\n  Eigen::Vector2d theta;\n  Eigen::Quaterniond p_orig;\n  ceres_error_terms::Unit3::Minus(p, q, &theta);\n  ceres_error_terms::Unit3::Plus(q, theta, &p_orig);\n\n  pose::Quaternion p_(p);\n  pose::Quaternion p_orig_(p_orig);\n  EXPECT_NEAR_KINDR_QUATERNION(p_, p_orig_, 1e-5);\n}\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "fe95539d7aa782d4d2f078395a7cbaed3fa08029", "size": 2897, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/ceres-error-terms/test/test_unit3_parameterization.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": "algorithms/ceres-error-terms/test/test_unit3_parameterization.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": "algorithms/ceres-error-terms/test/test_unit3_parameterization.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": 31.4891304348, "max_line_length": 71, "alphanum_fraction": 0.6938211943, "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5354252156887581}}
{"text": "/*===========================================================================*\\\n *                                                                           *\n *                               CoMISo                                      *\n *      Copyright (C) 2008-2009 by Computer Graphics Group, RWTH Aachen      *\n *                           www.rwth-graphics.de                            *\n *                                                                           *\n *---------------------------------------------------------------------------* \n *  This file is part of CoMISo.                                             *\n *                                                                           *\n *  CoMISo 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 *  CoMISo 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 CoMISo.  If not, see <http://www.gnu.org/licenses/>.          *\n *                                                                           *\n\\*===========================================================================*/ \n\n#include <iostream>\n\n\n//== COMPILE-TIME PACKAGE REQUIREMENTS ========================================\n#include <CoMISo/Config/config.hh>\n#if (COMISO_ARPACK_AVAILABLE && COMISO_SUITESPARSE_AVAILABLE && COMISO_EIGEN3_AVAILABLE)\n//=============================================================================\n\n#include <CoMISo/Utils/StopWatch.hh>\n#include <vector>\n#include <CoMISo/EigenSolver/ArpackSolver.hh>\n#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n\n\n//------------------------------------------------------------------------------------------------------\n\n// Example main\nint main(void)\n{\n  // matrix types\n#if EIGEN_VERSION_AT_LEAST(3,1,0)\n  typedef Eigen::SparseMatrix<double,Eigen::ColMajor>           SMatrix;\n#else\n  typedef Eigen::DynamicSparseMatrix<double,Eigen::ColMajor>    SMatrix;\n#endif\n  typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>  Matrix;\n  \n  std::cout << \"---------- 1) Setting up matrix...\" << std::endl;\n  unsigned int n=5;\n  SMatrix A(n,n);\n  // 1D Laplacian\n  for(unsigned int i=0; i<n; ++i)\n  {\n    int count = 0;\n    if( i > 0)\n    {\n      A.coeffRef(i,i-1) = -1.0;\n      ++count;\n    }\n    if(i<n-1)\n    {\n      A.coeffRef(i,i+1) = -1.0;\n      ++count;\n    }\n\n    A.coeffRef(i,i) = count;\n  }\n  \n  \n  std::cout << \"---------- 2) Solving for m smallest eigenvalues and eigenvectors...\" << std::endl;\n  unsigned int m=3;\n  COMISO::ArpackSolver arsolv;\n  std::vector<double> evals;\n  Matrix evects;\n  arsolv.solve(A, evals, evects, m);\n  \n  std::cout << \"---------- 3) printing results...\" << std::endl;\n  std::cerr << \"********* eigenvalues: \";\n  for(unsigned int i=0; i<evals.size(); ++i)\n    std::cerr << evals[i] << \", \";\n  std::cerr << std::endl;\n  \n  std::cerr <<\"********* eigenvectors:\" << std::endl;\n  std::cerr << evects << std::endl;\n \n  return 0;\n}\n\n//=============================================================================\n#else\n//=============================================================================\n\n// Example main\nint main(void)\n{\n  std::cerr << \"Info: required dependencies are missing, abort...\\n\";\n  return 0;\n}\n//=============================================================================\n#endif // COMISO_SUITESPARSE_AVAILABLE\n//=============================================================================\n", "meta": {"hexsha": "d3609ac419b6e77d5851851318f9b5947311dec4", "size": 4171, "ext": "cc", "lang": "C++", "max_stars_repo_path": "3rdparty/meshlab-master/src/external/CoMISo/Examples/small_eigenproblem/main.cc", "max_stars_repo_name": "HoEmpire/slambook2", "max_stars_repo_head_hexsha": "96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 216.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T11:53:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:41:35.000Z", "max_issues_repo_path": "3rdparty/meshlab-master/src/external/CoMISo/Examples/small_eigenproblem/main.cc", "max_issues_repo_name": "HoEmpire/slambook2", "max_issues_repo_head_hexsha": "96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-23T08:29:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T06:45:34.000Z", "max_forks_repo_path": "ACAP_linux/3rd/CoMISo/Examples/small_eigenproblem/main.cc", "max_forks_repo_name": "shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer", "max_forks_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2018-09-13T08:50:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T00:33:54.000Z", "avg_line_length": 38.6203703704, "max_line_length": 104, "alphanum_fraction": 0.4051786142, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5354252092366985}}
{"text": "/*!\n * \\file hnf_impl_lll.hpp\n * \\author Jun Yoshida\n * \\copyright (c) 2020 Jun Yoshida.\n * The project is released under the 2-clause BSD License.\n * \\date August, 2020: created\n */\n\n#pragma once\n\n#include <valarray>\n#include <functional>\n#include <tuple>\n#include <cmath>\n#include <Eigen/Dense>\n\n#include \"utils.hpp\"\n#include \"matrixops.hpp\"\n\nnamespace khover {\n\nnamespace _impl_LLL {\n\nclass Lambda_t {\npublic:\n    using underlying_t = long double;\n    static inline constexpr double delta = 0.75;\n\nprivate:\n    std::size_t m_size;\n\n    //! Diagonal entries.\n    std::valarray<underlying_t> m_diag;\n\n    //! strictly lower trianglar matrix with row-major\n    std::valarray<underlying_t> m_offDiag;\n\nprotected:\n    static inline constexpr std::size_t rhead(std::size_t i) noexcept {\n        return i*(i-1)/2;\n    }\n\n    inline void rev(std::size_t &k) noexcept {\n        k = m_size - k - 1;\n    }\n\npublic:\n    Lambda_t(std::size_t n) noexcept\n        : m_size(n),\n          m_diag(static_cast<underlying_t>(1),n+1),\n          m_offDiag(static_cast<underlying_t>(0),n*(n-1)/2)\n    {}\n\n    //! Element access (R/W)\n    //! \\pre n >= i >= j >= 0\n    underlying_t& operator()(std::size_t i, std::size_t j) {\n        rev(i);\n        rev(j);\n        return i==j ? m_diag[i+1] : m_offDiag[rhead(i)+j];\n    }\n\n    //! Element access (Read only)\n    underlying_t const & operator()(std::size_t i, std::size_t j) const {\n        return const_cast<Lambda_t*>(this)->operator()(i,j);\n    }\n\n    //! \\pre isrc != itgt\n    void axpy(underlying_t coeff, std::size_t isrc, std::size_t itgt) noexcept {\n        rev(isrc);\n        rev(itgt);\n        auto imin = std::min(isrc,itgt);\n\n        if (imin <= 0) return;\n\n        std::slice_array<underlying_t> tgt\n            =  m_offDiag[std::slice(rhead(itgt),imin,1)];\n\n        std::valarray<underlying_t> qsrc(\n            m_offDiag[std::slice(rhead(isrc),imin,1)]);\n\n        tgt += std::valarray<underlying_t>(coeff,imin) * qsrc;\n    }\n\n    //! Update lambda in SWAP step in the HMM algorithm.\n    //! \\pre 0 < k < n\n    void swap(std::size_t k) noexcept {\n        rev(k);\n        std::swap_ranges(\n            std::begin(m_offDiag)+rhead(k),\n            std::begin(m_offDiag)+rhead(k)+k-1,\n            std::begin(m_offDiag)+rhead(k-1));\n\n        for (size_t i = k+1; i < m_size; ++i) {\n            underlying_t aux1 = m_offDiag[rhead(i)+k-1] / m_diag[k];\n            underlying_t aux2 = m_offDiag[rhead(i)+k] / m_diag[k];\n            m_offDiag[rhead(i)+k-1]\n                = std::fma(aux1, m_offDiag[rhead(k)+k-1], aux2 * m_diag[k-1]);\n            m_offDiag[rhead(i)+k]\n                = std::fma(aux1, m_diag[k+1], (-aux2) * m_offDiag[rhead(k)+k-1]);\n        }\n\n        //! Be careful on overflows.\n        m_diag[k] =\n            std::fma(m_diag[k-1] / m_diag[k], m_diag[k+1],\n                (m_offDiag[rhead(k)+k-1] / m_diag[k]) * m_offDiag[rhead(k)+k-1] );\n    }\n\n    //! Update lambda in MINUS step in the HMM algorithm.\n    void negate(std::size_t k) noexcept{\n        rev(k);\n        if (k <= 1) return;\n\n        // std::for_each(\n        //     std::begin(m_offDiag)+rhead(k),\n        //     std::begin(m_offDiag)+rhead(k)+k,\n        //     std::negate<underlying_t>{});\n        std::slice_array<underlying_t> sl = m_offDiag[std::slice(rhead(k),k,1)];\n        sl *= std::valarray<underlying_t>(-1,k);\n\n        for(size_t i = k+1; i < m_size; ++i)\n            m_offDiag[rhead(i)+k] *= -1;\n    }\n\n    //! Check if SWAP should be performed.\n    //! \\pre k >= 1 && k < n\n    int should_swap(size_t k) noexcept\n    {\n        rev(k);\n        return m_diag[k-1] * m_diag[k+1] + sqpow(m_offDiag[rhead(k)+k-1])\n            < delta * sqpow(m_diag[k]);\n    }\n\n};\n\n/*!\n * \"Swap\" operation in the algorithm.\n * \\pre 1 <= k < min(data->m.r, data->u.r)\n */\ntemplate<class Ops, class Derived, class...Us, class...Vs>\nvoid swap(\n    std::size_t k,\n    Eigen::MatrixBase<Derived> &m,\n    std::tuple<Us&...> &us, std::tuple<Vs&...> &vs,\n    Lambda_t &lambda\n    ) noexcept\n{\n    // Transform matrices\n    Ops::swap(m, k, k+1);\n    for_each_tuple(us, [k](auto& u){ Ops::dual_t::swap(u,k,k+1); });\n    for_each_tuple(vs, [k](auto& v){ Ops::swap(v,k,k+1); });\n\n    // Update lambda\n    lambda.swap(k);\n}\n\n/*!\n * \"Minus\" operation in the algorithm.\n */\ntemplate <class Ops, class Derived, class...Us, class...Vs>\nvoid negate(\n    std::size_t k,\n    Eigen::MatrixBase<Derived> &m,\n    std::tuple<Us&...> &us, std::tuple<Vs&...> &vs,\n    Lambda_t &lambda\n    ) noexcept\n{\n    // Negate k-th rows\n    Ops::scalar(m, k, -1);\n\n    for_each_tuple(us, [k](auto& u){ Ops::dual_t::scalar(u, k, -1); });\n    for_each_tuple(vs, [k](auto& v){ Ops::scalar(v, k, -1); });\n\n    // Update lambda\n    lambda.negate(k);\n}\n\n//! The type of the return value of \"Reduce2\" step.\nenum HowSwap : uint_fast8_t {\n    ShouldSwap  = 0b001,\n    ZeroReducer = 0b010,\n    ZeroReducee = 0b100,\n    BothZero    = 0b110,\n    // < 8bits\n};\n\n/*!\n * \"Reduce2\" operation in the algorithm.\n * \\pre k < i\n * \\tparam flag If true, swap check will be skipped.\n * \\return Whether \"Swap\" should be performed or not.\n */\ntemplate <class Ops, bool flag, class Derived, class...Us, class...Vs>\nauto reduce(\n    std::size_t k, std::size_t i,\n    Eigen::MatrixBase<Derived> &m,\n    std::tuple<Us&...> &us, std::tuple<Vs&...> &vs,\n    Lambda_t &lambda\n    ) noexcept\n    -> std::underlying_type_t<HowSwap>\n{\n    /* Find the first non-zero entry of the i-th and j-th vectors. */\n    std::size_t l1 = Ops::find_nonzero_unsafe(\n        m, i,\n        [&](std::size_t, auto x) {\n            if (std::signbit(x)) negate<Ops>(i, m, us, vs, lambda);\n        } );\n    std::size_t l2 = Ops::find_nonzero_unsafe(\n        m, k,\n        [&](std::size_t, auto x) {\n            if (std::signbit(x)) negate<Ops>(k, m, us, vs, lambda);\n        } );\n\n    // Scalar factor of the reduction\n    typename Eigen::MatrixBase<Derived>::Scalar q;\n\n    // Compute the scalar factor\n    if (l1 < Ops::size(m)) {\n        q = - floor_div(Ops::at(m,k)[l1], Ops::at(m,i)[l1]);\n    }\n    else if (2.0*std::abs(lambda(k,i)) > lambda(i,i))\n        q = - std::round( lambda(k,i)/ lambda(i,i) );\n    else\n        q = 0;\n\n    // Reduce the k-th vector by the i-th one.\n    if (q != 0) {\n        Ops::axpy(m, q, i, k);\n        for_each_tuple(us, [i,k,&q](auto& u){ Ops::dual_t::axpy(u,-q,k,i); });\n        for_each_tuple(vs, [i,k,&q](auto& v){ Ops::axpy(v,q,i,k); });\n\n        // Update lambda\n        lambda.axpy(q, i, k);\n    }\n\n    if constexpr(!flag) {\n        if (l1 < Ops::size(m)) {\n            if (l2 >= Ops::size(m))\n                return HowSwap::ShouldSwap | HowSwap::ZeroReducee;\n            else\n                return l1 <= l2 ? HowSwap::ShouldSwap : 0u;\n        }\n        else if (l2 < Ops::size(m))\n            return HowSwap::ZeroReducer;\n        else\n            return HowSwap::BothZero\n                | (lambda.should_swap(k) ? HowSwap::ShouldSwap : 0u);\n    }\n    else\n        return 0;\n}\n\n\n} // end namespace _impl_LLL\n\n} // end namespace khover\n", "meta": {"hexsha": "61804ac1216a91b429e22859314ff4e8ad4e16be", "size": 7003, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/hnf_impl_lll.hpp", "max_stars_repo_name": "Junology/khover", "max_stars_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T06:48:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T06:50:39.000Z", "max_issues_repo_path": "src/hnf_impl_lll.hpp", "max_issues_repo_name": "Junology/khover", "max_issues_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "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/hnf_impl_lll.hpp", "max_forks_repo_name": "Junology/khover", "max_forks_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.35546875, "max_line_length": 82, "alphanum_fraction": 0.5536198772, "num_tokens": 2192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5354252040449646}}
{"text": "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// @project        Open Space Toolkit \u25b8 Mathematics\n/// @file           OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Ellipsoid.cpp\n/// @author         Lucas Br\u00e9mond <lucas@loftorbital.com>\n/// @license        Apache License 2.0\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <OpenSpaceToolkit/Mathematics/Geometry/3D/Transformations/Rotations/RotationMatrix.hpp>\n#include <OpenSpaceToolkit/Mathematics/Geometry/3D/Transformation.hpp>\n#include <OpenSpaceToolkit/Mathematics/Geometry/3D/Intersection.hpp>\n#include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Cone.hpp>\n#include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Pyramid.hpp>\n#include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Ellipsoid.hpp>\n#include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Sphere.hpp>\n#include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Segment.hpp>\n#include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Ray.hpp>\n#include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Line.hpp>\n#include <OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/PointSet.hpp>\n#include <OpenSpaceToolkit/Mathematics/Objects/Interval.hpp>\n\n#include <OpenSpaceToolkit/Core/Error.hpp>\n#include <OpenSpaceToolkit/Core/Utilities.hpp>\n\n#include <Gte/Mathematics/GteIntrEllipsoid3Ellipsoid3.h>\n// #include <Gte/Mathematics/GteIntrHalfspace3Ellipsoid3.h>\n#include <Gte/Mathematics/GteIntrPlane3Ellipsoid3.h>\n#include <Gte/Mathematics/GteIntrSegment3Ellipsoid3.h>\n#include <Gte/Mathematics/GteIntrRay3Ellipsoid3.h>\n#include <Gte/Mathematics/GteIntrLine3Ellipsoid3.h>\n\n// Disable Eigen warnings\n\n#pragma GCC diagnostic push // Save diagnostic state\n\n#pragma GCC diagnostic ignored \"-Wshadow\"\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#pragma GCC diagnostic ignored \"-Wint-in-bool-context\"\n\n#include <Eigen/Eigenvalues>\n\n#pragma GCC diagnostic pop // Turn the warnings back on\n\n#include <math.h>\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nnamespace ostk\n{\nnamespace math\n{\nnamespace geom\n{\nnamespace d3\n{\nnamespace objects\n{\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\ngte::Vector3<double>            EllipsoidGteVectorFromPoint                 (   const   Point&                      aPoint                                      )\n{\n    return { aPoint.x(), aPoint.y(), aPoint.z() } ;\n}\n\ngte::Vector3<double>            EllipsoidGteVectorFromVector3d              (   const   Vector3d&                   aVector                                     )\n{\n    return { aVector.x(), aVector.y(), aVector.z() } ;\n}\n\nPoint                           EllipsoidPointFromGteVector                 (   const   gte::Vector3<double>&       aVector                                     )\n{\n    return { aVector[0], aVector[1], aVector[2] } ;\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n                                Ellipsoid::Ellipsoid                        (   const   Point&                      aCenter,\n                                                                                const   Real&                       aFirstPrincipalSemiAxis,\n                                                                                const   Real&                       aSecondPrincipalSemiAxis,\n                                                                                const   Real&                       aThirdPrincipalSemiAxis,\n                                                                                const   Quaternion&                 anOrientation                               )\n                                :   Object(),\n                                    center_(aCenter),\n                                    a_(aFirstPrincipalSemiAxis),\n                                    b_(aSecondPrincipalSemiAxis),\n                                    c_(aThirdPrincipalSemiAxis),\n                                    q_(anOrientation)\n{\n\n    if (a_.isDefined() && (a_ < 0.0))\n    {\n        throw ostk::core::error::RuntimeError(\"First principal semi-axis is negative.\") ;\n    }\n\n    if (b_.isDefined() && (b_ < 0.0))\n    {\n        throw ostk::core::error::RuntimeError(\"Second principal semi-axis is negative.\") ;\n    }\n\n    if (c_.isDefined() && (c_ < 0.0))\n    {\n        throw ostk::core::error::RuntimeError(\"Third principal semi-axis is negative.\") ;\n    }\n\n}\n\nEllipsoid*                      Ellipsoid::clone                            ( ) const\n{\n    return new Ellipsoid(*this) ;\n}\n\nbool                            Ellipsoid::operator ==                      (   const   Ellipsoid&                  anEllipsoid                                 ) const\n{\n\n    if ((!this->isDefined()) || (!anEllipsoid.isDefined()))\n    {\n        return false ;\n    }\n\n    if (center_ == anEllipsoid.center_)\n    {\n\n        if ((a_ == anEllipsoid.a_) && (b_ == anEllipsoid.b_) && (c_ == anEllipsoid.c_) && (q_ == anEllipsoid.q_))\n        {\n            return true ;\n        }\n\n        return this->getMatrix().isNear(anEllipsoid.getMatrix(), Real::Epsilon()) ;\n\n    }\n\n    return false ;\n\n}\n\nbool                            Ellipsoid::operator !=                      (   const   Ellipsoid&                  anEllipsoid                                 ) const\n{\n    return !((*this) == anEllipsoid) ;\n}\n\nbool                            Ellipsoid::isDefined                        ( ) const\n{\n    return center_.isDefined() && a_.isDefined() && b_.isDefined() && c_.isDefined() && q_.isDefined() ;\n}\n\nbool                            Ellipsoid::intersects                       (   const   Point&                      aPoint                                      ) const\n{\n    return this->contains(aPoint) ;\n}\n\nbool                            Ellipsoid::intersects                       (   const   PointSet&                   aPointSet                                   ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    return (!aPointSet.isEmpty()) && std::any_of(aPointSet.begin(), aPointSet.end(), [this] (const Point& aPoint) -> bool { return this->contains(aPoint) ; }) ;\n\n}\n\nbool                            Ellipsoid::intersects                       (   const   Line&                       aLine                                       ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    if (!aLine.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Line\") ;\n    }\n\n    // Line\n\n    const gte::Line3<double> line = { EllipsoidGteVectorFromPoint(aLine.getOrigin()), EllipsoidGteVectorFromVector3d(aLine.getDirection()) } ;\n\n    // Ellipsoid\n\n    const gte::Vector3<double> center = EllipsoidGteVectorFromPoint(center_) ;\n    const std::array<gte::Vector3<double>, 3> axes = { EllipsoidGteVectorFromVector3d(this->getFirstAxis()), EllipsoidGteVectorFromVector3d(this->getSecondAxis()), EllipsoidGteVectorFromVector3d(this->getThirdAxis()) } ;\n    const gte::Vector3<double> extent = { a_, b_, c_ } ;\n\n    const gte::Ellipsoid3<double> ellipsoid = { center, axes, extent } ;\n\n    // Intersection\n\n    gte::TIQuery<double, gte::Line3<double>, gte::Ellipsoid3<double>> intersectionQuery ;\n\n    auto intersectionResult = intersectionQuery(line, ellipsoid) ;\n\n    return intersectionResult.intersect ;\n\n}\n\nbool                            Ellipsoid::intersects                       (   const   Ray&                        aRay                                        ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    if (!aRay.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ray\") ;\n    }\n\n    // Ray\n\n    const gte::Ray3<double> ray = { EllipsoidGteVectorFromPoint(aRay.getOrigin()), EllipsoidGteVectorFromVector3d(aRay.getDirection()) } ;\n\n    // Ellipsoid\n\n    const gte::Vector3<double> center = EllipsoidGteVectorFromPoint(center_) ;\n    const std::array<gte::Vector3<double>, 3> axes = { EllipsoidGteVectorFromVector3d(this->getFirstAxis()), EllipsoidGteVectorFromVector3d(this->getSecondAxis()), EllipsoidGteVectorFromVector3d(this->getThirdAxis()) } ;\n    const gte::Vector3<double> extent = { a_, b_, c_ } ;\n\n    const gte::Ellipsoid3<double> ellipsoid = { center, axes, extent } ;\n\n    // Intersection\n\n    gte::TIQuery<double, gte::Ray3<double>, gte::Ellipsoid3<double>> intersectionQuery ;\n\n    auto intersectionResult = intersectionQuery(ray, ellipsoid) ;\n\n    return intersectionResult.intersect ;\n\n}\n\nbool                            Ellipsoid::intersects                       (   const   Segment&                    aSegment                                    ) const\n{\n\n    using ostk::math::obj::Interval ;\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    if (!aSegment.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Segment\") ;\n    }\n\n    // // Does not work for some reason... most likely a bug w/ gte::TIQuery<double, gte::Segment3<double>, gte::Ellipsoid3<double>>\n\n    // // Segment\n\n    // const gte::Segment3<double> segment = { EllipsoidGteVectorFromVector3d(aSegment.getFirstPoint()), EllipsoidGteVectorFromVector3d(aSegment.getSecondPoint()) } ;\n\n    // // Ellipsoid\n\n    // const gte::Vector3<double> center = EllipsoidGteVectorFromVector3d(center_) ;\n    // const std::array<gte::Vector3<double>, 3> axes = { EllipsoidGteVectorFromVector3d(this->getFirstAxis()), EllipsoidGteVectorFromVector3d(this->getSecondAxis()), EllipsoidGteVectorFromVector3d(this->getThirdAxis()) } ;\n    // const gte::Vector3<double> extent = { a_, b_, c_ } ;\n\n    // const gte::Ellipsoid3<double> ellipsoid = { center, axes, extent } ;\n\n    // // Intersection\n\n    // gte::TIQuery<double, gte::Segment3<double>, gte::Ellipsoid3<double>> intersectionQuery ;\n\n    // auto intersectionResult = intersectionQuery(segment, ellipsoid) ;\n\n    // return intersectionResult.intersect ;\n\n    if (aSegment.isDegenerate())\n    {\n        return this->contains(aSegment.getFirstPoint()) ;\n    }\n\n    // https://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrSegment3Ellipsoid3.h\n\n    const Vector3d segmentDirection = aSegment.getDirection() ;\n    const Vector3d segmentCenter = aSegment.getCenter().asVector() ;\n    const Real segmentHalfLength = aSegment.getLength() / 2.0 ;\n\n    const Matrix3d M = this->getMatrix() ;\n\n    const Vector3d diff = segmentCenter - center_.asVector() ;\n    const Vector3d matDir = M * segmentDirection ;\n    const Vector3d matDiff = M * diff ;\n\n    const Real a2 = segmentDirection.dot(matDir) ;\n    const Real a1 = segmentDirection.dot(matDiff) ;\n    const Real a0 = diff.dot(matDiff) - 1.0 ;\n\n    const Real discriminant = (a1 * a1) - (a0 * a2) ;\n\n    static const Real tolerance = 1e-25 ; // [TBM] Tolerance parameter should be dynamic\n\n    if (discriminant < -tolerance) // No real roots\n    {\n        return false ;\n    }\n    else if (discriminant > tolerance) // Two real roots\n    {\n\n        const Real discriminantRoot = std::sqrt(discriminant) ;\n        const Real a2_inverse = 1.0 / a2 ;\n\n        const Real t0 = (-a1 - discriminantRoot) * a2_inverse ;\n        const Real t1 = (-a1 + discriminantRoot) * a2_inverse ;\n\n        const Interval<Real> resultInterval = Interval<Real>::Open(t0, t1) ;\n        const Interval<Real> segmentInterval = Interval<Real>::Closed(-segmentHalfLength, +segmentHalfLength) ;\n\n        if (!resultInterval.contains(segmentInterval))\n        {\n\n            if (resultInterval.intersects(segmentInterval))\n            {\n                return true ;\n            }\n            else // No intersection\n            {\n                return false ;\n            }\n\n        }\n        else\n        {\n            return false ;\n        }\n\n    }\n    else // One real root\n    {\n\n        const Real t0 = -a1 / a2 ;\n\n        if (std::abs(t0) <= segmentHalfLength) // Single intersection\n        {\n            return true ;\n        }\n        else // No intersection\n        {\n            return false ;\n        }\n\n    }\n\n    return false ;\n\n}\n\nbool                            Ellipsoid::intersects                       (   const   Plane&                      aPlane                                      ) const\n{\n\n    // https://file.scirp.org/pdf/AM20121100009_89014420.pdf\n    // https://www.researchgate.net/publication/312384498_Intersection_of_an_Ellipsoid_and_a_Plane\n\n    if (!aPlane.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Plane\") ;\n    }\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    // Plane\n\n    const gte::Vector3<double> normal = EllipsoidGteVectorFromVector3d(aPlane.getNormalVector()) ;\n    const gte::Vector3<double> point = EllipsoidGteVectorFromPoint(aPlane.getPoint()) ;\n\n    const gte::Plane3<double> plane = { normal, point } ;\n\n    // Ellipsoid\n\n    const gte::Vector3<double> center = EllipsoidGteVectorFromPoint(center_) ;\n    const std::array<gte::Vector3<double>, 3> axes = { EllipsoidGteVectorFromVector3d(this->getFirstAxis()), EllipsoidGteVectorFromVector3d(this->getSecondAxis()), EllipsoidGteVectorFromVector3d(this->getThirdAxis()) } ;\n    const gte::Vector3<double> extent = { a_, b_, c_ } ;\n\n    const gte::Ellipsoid3<double> ellipsoid = { center, axes, extent } ;\n\n    // Intersection\n\n    gte::TIQuery<double, gte::Plane3<double>, gte::Ellipsoid3<double>> intersectionQuery ;\n\n    auto intersectionResult = intersectionQuery(plane, ellipsoid) ;\n\n    return intersectionResult.intersect ;\n\n}\n\n// bool                            Ellipsoid::intersects                       (   const   Sphere&                     aSphere                                     ) const\n// {\n\n//     if (!aSphere.isDefined())\n//     {\n//         throw ostk::core::error::runtime::Undefined(\"Sphere\") ;\n//     }\n\n//     if (!this->isDefined())\n//     {\n//         throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n//     }\n\n//     return this->intersects(Ellipsoid(aSphere.getCenter(), aSphere.getRadius(), aSphere.getRadius(), aSphere.getRadius())) ;\n\n// }\n\n// bool                            Ellipsoid::intersects                       (   const   Ellipsoid&                  anEllipsoid                                 ) const\n// {\n\n//     if (!anEllipsoid.isDefined())\n//     {\n//         throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n//     }\n\n//     if (!this->isDefined())\n//     {\n//         throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n//     }\n\n//     // Ellipsoid\n\n//     const gte::Vector3<double> center = EllipsoidGteVectorFromPoint(center_) ;\n//     const std::array<gte::Vector3<double>, 3> axes = { EllipsoidGteVectorFromVector3d(this->getFirstAxis()), EllipsoidGteVectorFromVector3d(this->getSecondAxis()), EllipsoidGteVectorFromVector3d(this->getThirdAxis()) } ;\n//     const gte::Vector3<double> extent = { a_, b_, c_ } ;\n\n//     const gte::Ellipsoid3<double> ellipsoid = { center, axes, extent } ;\n\n//     // Another ellipsoid\n\n//     const gte::Vector3<double> anotherCenter = EllipsoidGteVectorFromPoint(anEllipsoid.center_) ;\n//     const std::array<gte::Vector3<double>, 3> anotherAxes = { EllipsoidGteVectorFromVector3d(anEllipsoid.getFirstAxis()), EllipsoidGteVectorFromVector3d(anEllipsoid.getSecondAxis()), EllipsoidGteVectorFromVector3d(anEllipsoid.getThirdAxis()) } ;\n//     const gte::Vector3<double> anotherExtent = { anEllipsoid.a_, anEllipsoid.b_, anEllipsoid.c_ } ;\n\n//     const gte::Ellipsoid3<double> anotherEllipsoid = { anotherCenter, anotherAxes, anotherExtent } ;\n\n//     // Intersection\n\n//     gte::TIQuery<double, gte::Ellipsoid3<double>, gte::Ellipsoid3<double>> intersectionQuery ;\n\n//     auto intersectionResult = intersectionQuery(ellipsoid, anotherEllipsoid) ;\n\n//     return intersectionResult.intersect ;\n\n// }\n\nbool                            Ellipsoid::intersects                       (   const   Pyramid&                    aPyramid                                    ) const\n{\n    return aPyramid.intersects(*this) ;\n}\n\nbool                            Ellipsoid::intersects                       (   const   Cone&                       aCone                                       ) const\n{\n    return aCone.intersects(*this) ;\n}\n\nbool                            Ellipsoid::contains                         (   const   Point&                      aPoint                                      ) const\n{\n\n    using ostk::math::obj::Vector3d ;\n\n    if (!aPoint.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Point\") ;\n    }\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    Matrix3d dcm ;\n\n    dcm.row(0) = q_ * Vector3d::X() ;\n    dcm.row(1) = q_ * Vector3d::Y() ;\n    dcm.row(2) = q_ * Vector3d::Z() ;\n\n    const Vector3d point = dcm * (aPoint - center_) ;\n\n    const Real& x = point.x() ;\n    const Real& y = point.y() ;\n    const Real& z = point.z() ;\n\n    return std::abs((x * x) / (a_ * a_) + (y * y) / (b_ * b_) + (z * z) / (c_ * c_) - 1.0) < Real::Epsilon() ;\n\n}\n\nbool                            Ellipsoid::contains                         (   const   PointSet&                   aPointSet                                   ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    return (!aPointSet.isEmpty()) && std::all_of(aPointSet.begin(), aPointSet.end(), [this] (const Point& aPoint) -> bool { return this->contains(aPoint) ; }) ;\n\n}\n\nbool                            Ellipsoid::contains                         (   const   Segment&                    aSegment                                    ) const\n{\n    return this->contains(aSegment.getFirstPoint()) && this->contains(aSegment.getSecondPoint()) ;\n}\n\nPoint                           Ellipsoid::getCenter                        ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    return center_ ;\n\n}\n\nReal                            Ellipsoid::getFirstPrincipalSemiAxis        ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    return a_ ;\n\n}\n\nReal                            Ellipsoid::getSecondPrincipalSemiAxis       ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    return b_ ;\n\n}\n\nReal                            Ellipsoid::getThirdPrincipalSemiAxis        ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    return c_ ;\n\n}\n\nVector3d                        Ellipsoid::getFirstAxis                     ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    return q_.toConjugate() * Vector3d::X() ;\n\n}\n\nVector3d                        Ellipsoid::getSecondAxis                    ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    return q_.toConjugate() * Vector3d::Y() ;\n\n}\n\nVector3d                        Ellipsoid::getThirdAxis                     ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    return q_.toConjugate() * Vector3d::Z() ;\n\n}\n\nQuaternion                      Ellipsoid::getOrientation                   ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    return q_ ;\n\n}\n\nMatrix3d                        Ellipsoid::getMatrix                        ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    const Vector3d firstRatio = this->getFirstAxis() / a_ ;\n\tconst Vector3d secondRatio = this->getSecondAxis() / b_ ;\n\tconst Vector3d thirdRatio = this->getThirdAxis() / c_ ;\n\n    auto tensorProduct = [] (const Vector3d& aFirstVector, const Vector3d& aSecondVector) -> Matrix3d\n    {\n\n        Matrix3d tensorProductMatrix ;\n\n        tensorProductMatrix <<  aFirstVector(0) * aSecondVector(0), aFirstVector(0) * aSecondVector(1), aFirstVector(0) * aSecondVector(2),\n                                aFirstVector(1) * aSecondVector(0), aFirstVector(1) * aSecondVector(1), aFirstVector(1) * aSecondVector(2),\n                                aFirstVector(2) * aSecondVector(0), aFirstVector(2) * aSecondVector(1), aFirstVector(2) * aSecondVector(2) ;\n\n        return tensorProductMatrix ;\n\n    } ;\n\n\treturn tensorProduct(firstRatio, firstRatio) + tensorProduct(secondRatio, secondRatio) + tensorProduct(thirdRatio, thirdRatio) ;\n\n}\n\nIntersection                    Ellipsoid::intersectionWith                 (   const   Line&                       aLine                                       ) const\n{\n\n    using ostk::math::geom::d3::objects::PointSet ;\n\n    if (!aLine.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Line\") ;\n    }\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    // Line\n\n    const gte::Line3<double> segment = { EllipsoidGteVectorFromPoint(aLine.getOrigin()), EllipsoidGteVectorFromVector3d(aLine.getDirection()) } ;\n\n    // Ellipsoid\n\n    const gte::Vector3<double> center = EllipsoidGteVectorFromPoint(center_) ;\n    const std::array<gte::Vector3<double>, 3> axes = { EllipsoidGteVectorFromVector3d(this->getFirstAxis()), EllipsoidGteVectorFromVector3d(this->getSecondAxis()), EllipsoidGteVectorFromVector3d(this->getThirdAxis()) } ;\n    const gte::Vector3<double> extent = { a_, b_, c_ } ;\n\n    const gte::Ellipsoid3<double> ellipsoid = { center, axes, extent } ;\n\n    // Intersection\n\n    gte::FIQuery<double, gte::Line3<double>, gte::Ellipsoid3<double>> intersectionQuery ;\n\n    auto intersectionResult = intersectionQuery(segment, ellipsoid) ;\n\n    if (intersectionResult.intersect)\n    {\n\n        if (intersectionResult.numIntersections == 1)\n        {\n            return Intersection::Point(EllipsoidPointFromGteVector(intersectionResult.point[0])) ;\n        }\n        else if (intersectionResult.numIntersections == 2)\n        {\n            return Intersection::PointSet(PointSet({ Point(EllipsoidPointFromGteVector(intersectionResult.point[0])), Point(EllipsoidPointFromGteVector(intersectionResult.point[1])) })) ;\n        }\n        else\n        {\n            throw ostk::core::error::RuntimeError(\"Intersection algorithm has failed.\") ;\n        }\n\n    }\n\n    return Intersection::Empty() ;\n\n}\n\nIntersection                    Ellipsoid::intersectionWith                 (   const   Ray&                        aRay,\n                                                                                const   bool                        onlyInSight                                 ) const\n{\n\n    using ostk::math::geom::d3::objects::PointSet ;\n\n    if (!aRay.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ray\") ;\n    }\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    // Ray\n\n    const gte::Ray3<double> ray = { EllipsoidGteVectorFromPoint(aRay.getOrigin()), EllipsoidGteVectorFromVector3d(aRay.getDirection()) } ;\n\n    // Ellipsoid\n\n    const gte::Vector3<double> center = EllipsoidGteVectorFromPoint(center_) ;\n    const std::array<gte::Vector3<double>, 3> axes = { EllipsoidGteVectorFromVector3d(this->getFirstAxis()), EllipsoidGteVectorFromVector3d(this->getSecondAxis()), EllipsoidGteVectorFromVector3d(this->getThirdAxis()) } ;\n    const gte::Vector3<double> extent = { a_, b_, c_ } ;\n\n    const gte::Ellipsoid3<double> ellipsoid = { center, axes, extent } ;\n\n    // Intersection\n\n    gte::FIQuery<double, gte::Ray3<double>, gte::Ellipsoid3<double>> intersectionQuery ;\n\n    auto intersectionResult = intersectionQuery(ray, ellipsoid) ;\n\n    if (intersectionResult.intersect)\n    {\n\n        if (intersectionResult.numIntersections == 1)\n        {\n\n            const Point point = EllipsoidPointFromGteVector(intersectionResult.point[0]) ;\n\n            if ((point == aRay.getOrigin()) && (!this->contains(point))) // Discard ray origin, if returned by Gte\n            {\n                return Intersection::Empty() ;\n            }\n\n            return Intersection::Point(point) ;\n\n        }\n        else if (intersectionResult.numIntersections == 2)\n        {\n\n            const Point firstPoint = EllipsoidPointFromGteVector(intersectionResult.point[0]) ;\n            const Point secondPoint = EllipsoidPointFromGteVector(intersectionResult.point[1]) ;\n\n            if ((firstPoint == aRay.getOrigin()) || (secondPoint == aRay.getOrigin()))\n            {\n\n                if ((firstPoint == aRay.getOrigin()) && (!this->contains(firstPoint))) // Discard ray origin, if returned by Gte\n                {\n                    return Intersection::Point(secondPoint) ;\n                }\n\n                if ((secondPoint == aRay.getOrigin()) && (!this->contains(secondPoint))) // Discard ray origin, if returned by Gte\n                {\n                    return Intersection::Point(firstPoint) ;\n                }\n\n            }\n\n            if ((firstPoint - secondPoint).norm() < Real::Epsilon())\n            {\n                return Intersection::Point(firstPoint) ;\n            }\n\n            const PointSet pointSet = { { firstPoint, secondPoint } } ;\n\n            return onlyInSight ? Intersection::Point(pointSet.getPointClosestTo(aRay.getOrigin())) : Intersection::PointSet(pointSet) ;\n\n        }\n        else\n        {\n            throw ostk::core::error::RuntimeError(\"Intersection algorithm has failed.\") ;\n        }\n\n    }\n\n    return Intersection::Empty() ;\n\n}\n\nIntersection                    Ellipsoid::intersectionWith                 (   const   Segment&                    aSegment                                    ) const\n{\n\n    using ostk::math::geom::d3::objects::PointSet ;\n\n    if (!aSegment.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Segment\") ;\n    }\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    if (aSegment.isDegenerate() && this->contains(aSegment.getFirstPoint()))\n    {\n        return Intersection::Point(aSegment.getFirstPoint()) ;\n    }\n\n    // Segment\n\n    const gte::Segment3<double> segment = { EllipsoidGteVectorFromPoint(aSegment.getFirstPoint()), EllipsoidGteVectorFromPoint(aSegment.getSecondPoint()) } ; ;\n\n    // Ellipsoid\n\n    const gte::Vector3<double> center = EllipsoidGteVectorFromPoint(center_) ;\n    const std::array<gte::Vector3<double>, 3> axes = { EllipsoidGteVectorFromVector3d(this->getFirstAxis()), EllipsoidGteVectorFromVector3d(this->getSecondAxis()), EllipsoidGteVectorFromVector3d(this->getThirdAxis()) } ;\n    const gte::Vector3<double> extent = { a_, b_, c_ } ;\n\n    const gte::Ellipsoid3<double> ellipsoid = { center, axes, extent } ;\n\n    // Intersection\n\n    gte::FIQuery<double, gte::Segment3<double>, gte::Ellipsoid3<double>> intersectionQuery ;\n\n    auto intersectionResult = intersectionQuery(segment, ellipsoid) ;\n\n    if (intersectionResult.intersect)\n    {\n\n        if (intersectionResult.numIntersections == 1)\n        {\n\n            const Point point = EllipsoidPointFromGteVector(intersectionResult.point[0]) ;\n\n            if (isnan(point.x()) || isnan(point.y()) || isnan(point.z()))\n            {\n                return Intersection::Empty() ;\n            }\n\n            if ((!point.isDefined()) || ((point == aSegment.getFirstPoint() || (point == aSegment.getSecondPoint())) && (!this->contains(point)))) // Discard segment points, if returned by Gte\n            {\n                return Intersection::Empty() ;\n            }\n\n            return Intersection::Point(point) ;\n\n        }\n        else if (intersectionResult.numIntersections == 2)\n        {\n\n            const Point firstPoint = EllipsoidPointFromGteVector(intersectionResult.point[0]) ;\n            const Point secondPoint = EllipsoidPointFromGteVector(intersectionResult.point[1]) ;\n\n            if ((firstPoint == aSegment.getFirstPoint()) || (secondPoint == aSegment.getFirstPoint()) || (firstPoint == aSegment.getSecondPoint()) || (secondPoint == aSegment.getSecondPoint())) // Discard segment points, if returned by Gte\n            {\n\n                if ((firstPoint == aSegment.getFirstPoint()) && (!this->contains(firstPoint)))\n                {\n\n                    if ((secondPoint == aSegment.getSecondPoint()) && (!this->contains(secondPoint)))\n                    {\n                        return Intersection::Empty() ;\n                    }\n\n                    return Intersection::Point(secondPoint) ;\n\n                }\n\n                if ((firstPoint == aSegment.getSecondPoint()) && (!this->contains(firstPoint)))\n                {\n\n                    if ((secondPoint == aSegment.getFirstPoint()) && (!this->contains(secondPoint)))\n                    {\n                        return Intersection::Empty() ;\n                    }\n\n                    return Intersection::Point(secondPoint) ;\n\n                }\n\n                if ((secondPoint == aSegment.getFirstPoint()) && (!this->contains(secondPoint)))\n                {\n\n                    if ((firstPoint == aSegment.getSecondPoint()) && (!this->contains(firstPoint)))\n                    {\n                        return Intersection::Empty() ;\n                    }\n\n                    return Intersection::Point(firstPoint) ;\n\n                }\n\n                if ((secondPoint == aSegment.getSecondPoint()) && (!this->contains(secondPoint)))\n                {\n\n                    if ((firstPoint == aSegment.getFirstPoint()) && (!this->contains(firstPoint)))\n                    {\n                        return Intersection::Empty() ;\n                    }\n\n                    return Intersection::Point(firstPoint) ;\n\n                }\n\n            }\n\n            return Intersection::PointSet(PointSet({ firstPoint, secondPoint })) ;\n\n        }\n        else\n        {\n            throw ostk::core::error::RuntimeError(\"Intersection algorithm has failed.\") ;\n        }\n\n    }\n\n    return Intersection::Empty() ;\n\n}\n\nIntersection                    Ellipsoid::intersectionWith                 (   const   Pyramid&                    aPyramid,\n                                                                                const   bool                        onlyInSight                                 ) const\n{\n    return aPyramid.intersectionWith(*this, onlyInSight) ;\n}\n\nIntersection                    Ellipsoid::intersectionWith                 (   const   Cone&                       aCone,\n                                                                                const   bool                        onlyInSight                                 ) const\n{\n    return aCone.intersectionWith(*this, onlyInSight) ;\n}\n\nvoid                            Ellipsoid::print                            (           std::ostream&               anOutputStream,\n                                                                                        bool                        displayDecorators                           ) const\n{\n\n    displayDecorators ? ostk::core::utils::Print::Header(anOutputStream, \"Ellipsoid\") : void () ;\n\n    ostk::core::utils::Print::Line(anOutputStream) << \"Center:\"              << (center_.isDefined() ? center_.toString() : \"Undefined\") ;\n\n    ostk::core::utils::Print::Line(anOutputStream) << \"First principal semi-axis:\" << (a_.isDefined() ? a_.toString() : \"Undefined\") ;\n    ostk::core::utils::Print::Line(anOutputStream) << \"Second principal semi-axis:\" << (b_.isDefined() ? b_.toString() : \"Undefined\") ;\n    ostk::core::utils::Print::Line(anOutputStream) << \"Third principal semi-axis:\" << (c_.isDefined() ? c_.toString() : \"Undefined\") ;\n\n    ostk::core::utils::Print::Line(anOutputStream) << \"First axis:\"          << (q_.isDefined() ? this->getFirstAxis().toString() : \"Undefined\") ;\n    ostk::core::utils::Print::Line(anOutputStream) << \"Second axis:\"         << (q_.isDefined() ? this->getSecondAxis().toString() : \"Undefined\") ;\n    ostk::core::utils::Print::Line(anOutputStream) << \"Third axis:\"          << (q_.isDefined() ? this->getThirdAxis().toString() : \"Undefined\") ;\n\n    ostk::core::utils::Print::Line(anOutputStream) << \"Orientation:\"         << (q_.isDefined() ? q_.toString() : \"Undefined\") ;\n\n    displayDecorators ? ostk::core::utils::Print::Footer(anOutputStream) : void () ;\n\n}\n\nvoid                            Ellipsoid::applyTransformation              (   const   Transformation&             aTransformation                             )\n{\n\n    using ostk::math::geom::d3::trf::rot::RotationMatrix ;\n\n    if (!aTransformation.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Transformation\") ;\n    }\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Ellipsoid\") ;\n    }\n\n    if (aTransformation.isIdentity())\n    {\n        return ;\n    }\n\n    center_.applyTransformation(aTransformation) ;\n\n    const Matrix3d rotationMatrix = aTransformation.getMatrix().block<3, 3>(0, 0).inverse() ;\n    const Matrix3d transformedMatrix = rotationMatrix.transpose() * this->getMatrix() * rotationMatrix ;\n\n    Eigen::SelfAdjointEigenSolver<Matrix3d> eigenSolver(transformedMatrix) ;\n\n    if (eigenSolver.info() != Eigen::Success)\n    {\n        throw ostk::core::error::RuntimeError(\"Eigen vector calculation has failed.\") ;\n    }\n\n    a_ = std::sqrt(1.0 / eigenSolver.eigenvalues()(0)) ;\n    b_ = std::sqrt(1.0 / eigenSolver.eigenvalues()(1)) ;\n    c_ = std::sqrt(1.0 / eigenSolver.eigenvalues()(2)) ;\n\n    const Vector3d firstAxis = eigenSolver.eigenvectors().col(0) ;\n    const Vector3d secondAxis = eigenSolver.eigenvectors().col(1) ;\n    const Vector3d thirdAxis = firstAxis.cross(secondAxis) ;\n\n    q_ = Quaternion::RotationMatrix(RotationMatrix::Columns(firstAxis, secondAxis, thirdAxis)).conjugate() ;\n\n}\n\nEllipsoid                       Ellipsoid::Undefined                        ( )\n{\n    return { Point::Undefined(), Real::Undefined(), Real::Undefined(), Real::Undefined(), Quaternion::Undefined() } ;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n}\n}\n}\n}\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "81d5cc335b4b089fab3f831b460e47c67a83802a", "size": 35239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Ellipsoid.cpp", "max_stars_repo_name": "open-space-collective/open-space-toolkit-mathematics", "max_stars_repo_head_hexsha": "4b97f97f4aaa87bff848381a3519c6f764461378", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T02:22:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:26:35.000Z", "max_issues_repo_path": "src/OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Ellipsoid.cpp", "max_issues_repo_name": "open-space-collective/open-space-toolkit-mathematics", "max_issues_repo_head_hexsha": "4b97f97f4aaa87bff848381a3519c6f764461378", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-01-05T20:18:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-14T09:36:44.000Z", "max_forks_repo_path": "src/OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Ellipsoid.cpp", "max_forks_repo_name": "open-space-collective/open-space-toolkit-mathematics", "max_forks_repo_head_hexsha": "4b97f97f4aaa87bff848381a3519c6f764461378", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T18:18:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T17:42:24.000Z", "avg_line_length": 35.1335992024, "max_line_length": 248, "alphanum_fraction": 0.5433752377, "num_tokens": 7899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017536, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5353837309522063}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2020 Tinko Bartels, Berlin, Germany.\n\n// Contributed and/or modified by Tinko Bartels,\n//   as part of Google Summer of Code 2020 program.\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_GENERIC_ROBUST_PREDICATES_STRATEGIES_CARTESIAN_DETAIL_INTERVAL_ERROR_BOUND_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_GENERIC_ROBUST_PREDICATES_STRATEGIES_CARTESIAN_DETAIL_INTERVAL_ERROR_BOUND_HPP\n\n#include <boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/expression_tree.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace detail { namespace generic_robust_predicates\n{\n\ntemplate <typename Expression, std::size_t max_argn>\nstruct interval_min_impl\n{\n    using type = Expression;\n};\n\ntemplate <typename Expression, std::size_t max_argn>\nstruct interval_max_impl\n{\n    using type = Expression;\n};\n\ntemplate <typename Left, typename Right, std::size_t max_argn>\nstruct interval_min_impl<difference<Left, Right>, max_argn>\n{\nprivate:\n    using min_left = typename interval_min_impl<Left, max_argn>::type;\n    using max_right = typename interval_max_impl<Right, max_argn>::type;\npublic:\n    using type = difference<min_left, max_right>;\n};\n\ntemplate <typename Left, typename Right, std::size_t max_argn>\nstruct interval_min_impl<sum<Left, Right>, max_argn>\n{\nprivate:\n    using min_left = typename interval_min_impl<Left, max_argn>::type;\n    using min_right = typename interval_min_impl<Right, max_argn>::type;\npublic:\n    using type = sum<min_left, min_right>;\n};\n\ntemplate <typename Left, typename Right, std::size_t max_argn>\nstruct interval_max_impl<difference<Left, Right>, max_argn>\n{\nprivate:\n    using max_left = typename interval_max_impl<Left, max_argn>::type;\n    using min_right = typename interval_min_impl<Right, max_argn>::type;\npublic:\n    using type = difference<max_left, min_right>;\n};\n\ntemplate <typename Left, typename Right, std::size_t max_argn>\nstruct interval_max_impl<sum<Left, Right>, max_argn>\n{\nprivate:\n    using max_left = typename interval_max_impl<Left, max_argn>::type;\n    using max_right = typename interval_max_impl<Right, max_argn>::type;\npublic:\n    using type = sum<max_left, max_right>;\n};\n\ntemplate <typename Left, typename Right, std::size_t max_argn>\nstruct interval_min_impl<product<Left, Right>, max_argn>\n{\nprivate:\n    using min_left = typename interval_min_impl<Left, max_argn>::type;\n    using max_left = typename interval_max_impl<Left, max_argn>::type;\n    using min_right = typename interval_min_impl<Right, max_argn>::type;\n    using max_right = typename interval_max_impl<Right, max_argn>::type;\npublic:\n    using type = min\n        <\n            min\n                <\n                    product<min_left, min_right>,\n                    product<min_left, max_right>\n                >,\n            min\n                <\n                    product<max_left, min_right>,\n                    product<max_left, max_right>\n                >\n        >;\n};\n\ntemplate <typename Child, std::size_t max_argn>\nstruct interval_min_impl<product<Child, Child>, max_argn>\n{\nprivate:\n    using min_child = typename interval_min_impl<Child, max_argn>::type;\n    using max_child = typename interval_max_impl<Child, max_argn>::type;\npublic:\n    using type = min\n        <\n            product<min_child, min_child>,\n            product<max_child, max_child>\n        >;\n};\n\ntemplate <typename Left, typename Right, std::size_t max_argn>\nstruct interval_max_impl<product<Left, Right>, max_argn>\n{\nprivate:\n    using min_left = typename interval_min_impl<Left, max_argn>::type;\n    using max_left = typename interval_max_impl<Left, max_argn>::type;\n    using min_right = typename interval_min_impl<Right, max_argn>::type;\n    using max_right = typename interval_max_impl<Right, max_argn>::type;\npublic:\n    using type = max\n        <\n            max\n                <\n                    product<min_left, min_right>,\n                    product<min_left, max_right>\n                >,\n            max\n                <\n                    product<max_left, min_right>,\n                    product<max_left, max_right>\n                >\n        >;\n};\n\ntemplate <typename Child, std::size_t max_argn>\nstruct interval_max_impl<product<Child, Child>, max_argn>\n{\nprivate:\n    using min_child = typename interval_min_impl<Child, max_argn>::type;\n    using max_child = typename interval_max_impl<Child, max_argn>::type;\npublic:\n    using type = max\n        <\n            product<min_child, min_child>,\n            product<max_child, max_child>\n        >;\n};\n\ntemplate <typename Child, std::size_t max_argn>\nstruct interval_min_impl<abs<Child>, max_argn>\n{\nprivate:\n    using min_child = typename interval_min_impl<Child, max_argn>::type;\n    using max_child = typename interval_max_impl<Child, max_argn>::type;\npublic:\n    using type = min<abs<min_child>, abs<max_child>>;\n};\n\ntemplate <typename Child, std::size_t max_argn>\nstruct interval_max_impl<abs<Child>, max_argn>\n{\nprivate:\n    using min_child = typename interval_min_impl<Child, max_argn>::type;\n    using max_child = typename interval_max_impl<Child, max_argn>::type;\npublic:\n    using type = max<abs<min_child>, abs<max_child>>;\n};\n\ntemplate <std::size_t argn, std::size_t max_argn>\nstruct interval_min_impl<argument<argn>, max_argn>\n{\n    using type = argument<argn + max_argn>;\n};\n\ntemplate <std::size_t argn, std::size_t max_argn>\nstruct interval_max_impl<argument<argn>, max_argn>\n{\n    using type = argument<argn>;\n};\n\ntemplate <typename Expression, std::size_t max_argn>\nstruct interval_impl\n{\n    using type = Expression;\n};\n\ntemplate <typename Child, std::size_t max_argn>\nstruct interval_impl<abs<Child>, max_argn>\n{\nprivate:\n    using min_child = typename interval_min_impl<Child, max_argn>::type;\n    using max_child = typename interval_max_impl<Child, max_argn>::type;\npublic:\n    using type = max<abs<min_child>, abs<max_child>>;\n};\n\ntemplate <typename Left, typename Right, std::size_t max_argn>\nstruct interval_impl<difference<Left, Right>, max_argn>\n{\nprivate:\n    using left = typename interval_impl<Left, max_argn>::type;\n    using right = typename interval_impl<Right, max_argn>::type;\npublic:\n    using type = difference<left, right>;\n};\n\ntemplate <typename Left, typename Right, std::size_t max_argn>\nstruct interval_impl<sum<Left, Right>, max_argn>\n{\nprivate:\n    using left = typename interval_impl<Left, max_argn>::type;\n    using right = typename interval_impl<Right, max_argn>::type;\npublic:\n    using type = sum<left, right>;\n};\n\ntemplate <typename Left, typename Right, std::size_t max_argn>\nstruct interval_impl<product<Left, Right>, max_argn>\n{\nprivate:\n    using left = typename interval_impl<Left, max_argn>::type;\n    using right = typename interval_impl<Right, max_argn>::type;\npublic:\n    using type = product<left, right>;\n};\n\ntemplate <typename Expression, std::size_t max_argn>\nusing interval_min = typename interval_min_impl<Expression, max_argn>::type;\n\ntemplate <typename Expression, std::size_t max_argn>\nusing interval_max = typename interval_max_impl<Expression, max_argn>::type;\n\ntemplate <typename Expression>\nusing interval =\n    typename interval_impl<Expression, max_argn<Expression>::value>::type;\n\n}} // namespace detail::generic_robust_predicates\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_GENERIC_ROBUST_PREDICATES_STRATEGIES_CARTESIAN_DETAIL_INTERVAL_ERROR_BOUND_HPP\n", "meta": {"hexsha": "59e4d3f47b9d092327752bc344e3023adb7dad8a", "size": 7602, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/interval_error_bound.hpp", "max_stars_repo_name": "BoostGSoC20/geometry", "max_stars_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T20:30:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T08:14:05.000Z", "max_issues_repo_path": "include/boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/interval_error_bound.hpp", "max_issues_repo_name": "Srutip04/geometry", "max_issues_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "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/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/interval_error_bound.hpp", "max_forks_repo_name": "Srutip04/geometry", "max_forks_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:22:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T10:43:59.000Z", "avg_line_length": 31.1557377049, "max_line_length": 114, "alphanum_fraction": 0.7190213102, "num_tokens": 1851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587668, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5352902647288319}}
{"text": "#include <boost/math/quadrature/gauss.hpp>\n", "meta": {"hexsha": "496abe9d5582351607421815c2d0f6e56cc3fdbd", "size": 43, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_quadrature_gauss.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_quadrature_gauss.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_quadrature_gauss.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 21.5, "max_line_length": 42, "alphanum_fraction": 0.7906976744, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5352902420689094}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <cassert>\n#include <vector>\n\n#include <Eigen/Core>\n\n#include \"cho_util/core/random.hpp\"\n\nnamespace cho {\nnamespace core {\n\nvoid GenerateConvexPolygon(\n    const int n, std::vector<Eigen::Vector2f>* const points,\n    cho::core::RNG& rng = cho::core::RNG::GetInstance()) {\n  assert(n > 2);\n\n  std::vector<float> xv, yv;\n  for (auto& v_out : {&xv, &yv}) {\n    float v0{1}, v1{1};\n    v_out->clear();\n    v_out->reserve(n);\n    for (int i = 0; i < n - 2; ++i) {\n      const bool sel = rng.Uniform(0, 1) < 0.5f;\n      const float v = rng.Uniform(0, 1);\n      if (sel) {\n        v_out->emplace_back(v - v0);\n        v0 = v;\n      } else {\n        v_out->emplace_back(v1 - v);\n        v1 = v;\n      }\n    }\n    v_out->emplace_back(v1 - 0);\n    v_out->emplace_back(0 - v0);\n  }\n  std::shuffle(yv.begin(), yv.end(), rng.generator);\n\n  // Compute angles of each cumulative vector.\n  std::vector<float> hv(n);\n  for (int i = 0; i < n; ++i) {\n    hv[i] = std::atan2(yv[i], xv[i]);\n  }\n\n  // Argsort by angle.\n  std::vector<int> indices(n);\n  std::iota(indices.begin(), indices.end(), 0);\n  std::sort(indices.begin(), indices.end(),\n            [&hv](const int i0, const int i1) { return hv[i0] < hv[i1]; });\n\n  // Accumulative vector sum into output.\n  Eigen::Vector2f point{0, 0};\n  points->clear();\n  points->reserve(n);\n  for (int i = 0; i < xv.size(); ++i) {\n    point.x() += xv[indices[i]];\n    point.y() += yv[indices[i]];\n    points->emplace_back(point);\n  }\n}\n\n}  // namespace core\n}  // namespace cho\n", "meta": {"hexsha": "c62b1dea5c51ab0f88c2fff62225ff1d064d6dab", "size": 1542, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cho_util/core/include/cho_util/core/random_convex_polygon.hpp", "max_stars_repo_name": "yycho0108/ChoUtils", "max_stars_repo_head_hexsha": "ce701d4c7bb21c6b17e218d584ad68bbb63fba0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cho_util/core/include/cho_util/core/random_convex_polygon.hpp", "max_issues_repo_name": "yycho0108/ChoUtils", "max_issues_repo_head_hexsha": "ce701d4c7bb21c6b17e218d584ad68bbb63fba0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cho_util/core/include/cho_util/core/random_convex_polygon.hpp", "max_forks_repo_name": "yycho0108/ChoUtils", "max_forks_repo_head_hexsha": "ce701d4c7bb21c6b17e218d584ad68bbb63fba0a", "max_forks_repo_licenses": ["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.7230769231, "max_line_length": 75, "alphanum_fraction": 0.5648508431, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5352491700702708}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n//  Copyright (c) 2019 Prashant K. Jha\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#ifndef UTILS_H\n#define UTILS_H\n\n\n#include \"utilCompare.hpp\"\n#include \"utilIO.hpp\"\n#include \"utilLibs.hpp\"\n#include <boost/random.hpp>\n\n//#include \"../../external/gmm/gmm.h\"\n\n#define X_POSITIVE_BOUNDARY 0\n#define X_NEGATIVE_BOUNDARY 1\n#define Y_POSITIVE_BOUNDARY 2\n#define Y_NEGATIVE_BOUNDARY 3\n#define Z_POSITIVE_BOUNDARY 4\n#define Z_NEGATIVE_BOUNDARY 5\n\n#define OUTER_BOUNDARY_NODE 0\n#define INNER_BOUNDARY_NODE 1\n#define INNER_NETWORK_NODE 2\n\nnamespace util {\n\n/*!\n * @brief Return the Square of numbers and ignores values lower than 0 and\n * higher than 1\n *\n * @param x  Number\n * @return value Value between 0 and 1\n */\ndouble square(double x);\n\n/*!\n * @brief Ignores values lower than 0 and higher than 1\n *\n * @param x  Number\n * @return value Value between 0 and 1\n */\ndouble linear(double x);\n\n/*!\n * @brief Regularized Heaviside function\n *\n * @param x  Number\n * @return value Heaveside function\n */\ndouble heaviside(double x);\n\n/*!\n * @brief Modulus of a vector (norm)\n *\n * @param xg X coordinate\n * @param yg Y coordinate\n * @return value Norm\n */\ndouble modulus(double xg, double yg);\n\n/*!\n * @brief Determinant of matrix\n *\n * @param M Matrix\n * @return value Determinant of M\n */\ndouble determinant(const std::vector<std::vector<double>> &M);\n\n/*!\n * @brief Inverse of matrix\n *\n * @param M Matrix\n * @return Minv Inverse of matrix M\n */\nstd::vector<std::vector<double>> inverse(const std::vector<std::vector<double>> &M);\n\n/*!\n * @brief Transpose of matrix\n *\n * @param M Matrix\n * @return Mt Transpose of matrix M\n */\nstd::vector<std::vector<double>> transpose(const std::vector<std::vector<double>> &M);\n\n/*!\n * @brief Add element to list\n *\n * @param i Element to be added\n * @param data List\n * @return true True if i is added to list\n */\nbool addToList(unsigned int i, std::vector<unsigned int> *data);\n\n/*!\n * @brief compute the mass of the qoi\n *\n * @param es Equation system\n * @param system_name Name of system\n * @param var_name Name of variable\n * @param value_mass Value of mass\n */\nvoid computeMass(EquationSystems &es, const std::string &system_name,\n                 const std::string &var_name, double &value_mass);\n\n/*! @brief Position index of given point in 2d\n   * @param x X coordinate of point\n   * @param y Y coordinate of point\n   * @param Nelx Number of elements in along x-axis (and y-axis)\n   * @return Index Unique integer corresponding to the point\n */\nint positionIndex(double x, double y, int Nelx);\n\n/*!\n * @brief Projects concentration to physical range i.e. [0,1]\n *\n * @param x Number\n * @return value Value between 0 and 1\n */\ndouble project_concentration(double x);\n\n/*!\n * @brief Find node closer to given point\n *\n * @param x Point\n * @param mesh Mesh\n * @return id Id of node\n */\nunsigned int locate_node(const Point &x, const MeshBase &mesh);\n\n/*!\n * @brief Returns point in line formed by points p1 and p2\n *\n * @param p1 Point 1\n * @param p2 Point 2\n * @param s Parametric coordinate\n * @return p Point\n */\nPoint point_on_line(const Point &p1, const Point &p2, const double &s);\n\n/*!\n * @brief Returns direction from point 1 to 2\n *\n * @param p1 Point 1\n * @param p2 Point 2\n * @return p Unit vector pointing at point 2 from point 1\n */\nPoint get_direction(const Point &p1, const Point &p2);\n\n/*!\n * @brief Returns true if point is inside the box\n *\n * @param p Point\n * @param box Box\n * @return True If point inside box otherwise false\n */\nbool is_inside_box(const Point &p, const std::pair<Point, Point> &box, double tol = 0.);\nbool is_inside_box(const Point &p, const double &box_size, double tol = 0.);\n\n/*!\n * @brief Returns true if point is inside the cylinder\n *\n * @param p Point\n * @param length Length of cylinder\n * @param radius Radius of cylinder\n * @param axis Axis of cylinder\n * @return True If point inside cylinder otherwise false\n */\nbool is_inside_cylinder(const Point &p, const double &length, const double &radius, const Point &axis);\n\n/*!\n * @brief Returns true if point is inside the cylinder\n *\n * @param p Point\n * @param R Radius of cylinder\n * @param x1 Point at the center of cross-section at s=0\n * @param x2 Point at the center of cross-section at s=L\n * @param\n * @return True If point inside cylinder otherwise false\n */\nbool is_inside_cylinder(const Point &p, const double &radius, const Point &x1,\n                        const Point &x2);\n\n/*!\n * @brief Returns true if point is inside the ellipsoid\n *\n * @param p Point\n * @param center Center of ellipse\n * @param radius_vec Vector of radius describing ellipse\n * @param dim Dimension\n * @param d\n * @return True If point inside otherwise false\n */\nbool is_inside_ellipse(const Point &p, const Point &center, const std::vector<double> &radius_vec, unsigned int dim);\n\n/*!\n * @brief Returns true if point is inside the ellipsoid\n *\n * Also computes\n * d = x^2 / r1^2 + y^2 / r2^2 + z^2 / r3^2\n *\n * @param p Point\n * @param center Center of ellipse\n * @param radius_vec Vector of radius describing ellipse\n * @param dim Dimension\n * @param d\n * @return True If point inside otherwise false\n */\nbool is_inside_ellipse(const Point &p, const Point &center, const std::vector<double> &radius_vec, unsigned int dim, double &d);\n\n/*!\n * @brief Transforms point in ellipse to point in ball of given radius\n *\n * @param p Point\n * @param center Center of ellipse\n * @param radius_vec Vector of radius describing ellipse\n * @param dim Dimension\n * @param ball_r Radius of ball\n * @return Point Point in ball\n */\nPoint ellipse_to_ball(const Point &p, const Point &center, const std::vector<double> &radius_vec, unsigned int dim, const double &ball_r);\n\n/*!\n * @brief Returns the vector after rotating by desired angle\n *\n * @param p Vector\n * @param theta Angle of rotation\n * @param axis Axis of rotation\n */\nPoint rotate(const Point &p, const double &theta, const Point &axis);\n\n/*!\n * @brief Returns the unit vector corresponding to cross product\n *\n * Note: Better to use inbuilt function in Point - p1.cross(p2)\n *\n * @param p1 Vector 1\n * @param p2 Vector 2\n * @return vector Unit vector along the cross product\n */\nPoint cross_product(const Point &p1, const Point &p2);\n\n/*!\n * @brief Computes angle between two vectors\n * @param a Vector 1\n * @param b Vector 2\n */\ndouble angle(Point a, Point b);\n\n/*!\n * @brief Computes angle between two vectors\n * @param a Vector 1\n * @param b Vector 2\n * @param axis Axis of rotation\n * @param is_axis If true then axis is the axis of orientation, otherwise\n * axis specifies the +ve side of the plane in which a and b are\n */\ndouble angle(Point a, Point b, Point axis, bool is_axis = true);\n\n/*!\n * @brief Computes following function\n *\n * exp[1 - 1 / (1 - r^a)]\n *\n * @param r Argument of function\n * @param exponent Value of power a in above function\n */\ndouble exp_decay_function(double r, double exponent = 4.);\n\nstd::vector<Point> discretize_ball_surface(const unsigned int\n                                             &disc_num,\n                                           const double\n                                             &ball_r,\n                                           unsigned int dim);\n\nstd::vector<Point> discretize_cube(const unsigned int\n                                     &disc_num,\n                                   const double\n                                     &cube_size,\n                                   unsigned int dim);\n\n\n/*!\n * @brief Do lines intersect\n *\n * @param line_1 Line 1\n * @param line_2 Line 2\n * @return True If lines intersect, else false\n */\nbool lines_intersect(const std::pair<Point, Point> &line_1, const std::pair<Point,\n                                                                            Point> &line_2);\n\n/*!\n * @brief Compute distance between lines\n *\n * @param line_1 Line 1\n * @param line_2 Line 2\n * @return Value Distance\n */\ndouble distance_between_lines(const std::pair<Point, Point> &line_1,\n                              const std::pair<Point, Point> &line_2);\ndouble distance_between_segments(const std::pair<Point, Point> &line_1,\n                                 const std::pair<Point, Point> &line_2);\n\n/*!\n * @brief Compute distance between planes\n *\n * @param plane_1 Plane 1 given by pair of normal and one point which it\n * contains\n * @param plane_2 Plane 2 given by pair of normal and one point which it\n * contains\n * @return Value Distance\n */\ndouble distance_between_planes(const std::pair<Point, Point> &plane_1,\n                               const std::pair<Point, Point> &plane_2);\n\n/*!\n * @brief Compute distance between point and line\n *\n * @param p Point\n * @param line Line\n * @return Value Distance\n */\ndouble point_distance_line(const Point &p,\n                           const std::pair<Point, Point> &line);\ndouble point_distance_segment(const Point &p,\n                              const std::pair<Point, Point> &line);\n\n/*!\n * @brief Compute distance between point and plane\n *\n * @param p Point\n * @param plane Plane given by pair of normal and one point which it\n * contains\n * @return Value Distance\n */\ndouble point_distance_plane(const Point &p,\n                            const std::pair<Point, Point> &plane);\n\n/*!\n * @brief Get list of elements which have this node as vertex\n *\n * @param node_id Node id\n * @param mesh Mesh\n * @return List\n */\nstd::vector<unsigned int> find_elems(const unsigned int node_id,\n                                     const MeshBase &mesh);\n\n/*!\n * @brief Get list of elements which have this node as vertex\n *\n * @param node_id Node id\n * @param mesh Mesh\n * @return List\n */\nvoid add_unique(unsigned int dof, Real val,\n                std::vector<unsigned int> &list, std::vector<Real> &list_val);\n\n/*!\n * @brief Get the major axis which is parallel to given vector within some\n * tolerance\n *\n * @param vec Given vector\n * @return axis Parallel to vec\n */\nstd::string get_vec_major_axis(Point vec);\n\n/*!\n * @brief Get the length between two points\n *\n * @param p1\n * @param p2\n * @return distance\n */\n\ndouble dist_between_points(const std::vector<double> &p1, const std::vector<double> &p2);\n\nvoid get_unit_vector(std::vector<double> &p1);\n\nunsigned int get_elem_id(const std::vector<double> &p, const double &mesh_size,\n                         const unsigned int &num_elems, const unsigned int &dim);\nunsigned int get_elem_id(const Point &p, const double &mesh_size,\n                         const unsigned int &num_elems, const unsigned int &dim);\n\nPoint to_point(const std::vector<double> &p);\n\nstd::vector<double> cross_prod(std::vector<double> &p1, std::vector<double> &p2);\n\nstd::vector<double> rotate(std::vector<double> &p, double theta, std::vector<double> &axis);\n\nPoint determineRotator(const Point &dir);\nstd::vector<double> determineRotator(const std::vector<double> &dir);\n\ninline float time_diff(std::chrono::steady_clock::time_point begin,\n                       std::chrono::steady_clock::time_point end) {\n\n  return std::chrono::duration_cast<std::chrono::microseconds>(end -\n                                                               begin)\n    .count();\n}\n\ntemplate<class T>\ninline int locate_in_set(const T &key, const std::vector<T> &set) {\n\n  for (int i = 0; i < set.size(); i++)\n    if (set[i] == key)\n      return i;\n\n  return -1;\n}\n\ninline void clear_oss(std::ostringstream &oss) {\n  oss.str(\"\");\n  oss.clear();\n}\n\ntemplate<class T>\ninline T get_avg(const std::vector<T> &list) {\n\n  if (list.size() == 0)\n    return T(0);\n\n  T avg = 0.;\n  for (const auto &l : list)\n    avg += l;\n  avg = avg / (double(list.size()));\n\n  return avg;\n}\n\ntemplate<class T>\ninline T get_std_dev(const std::vector<T> &list, const T mean) {\n\n  if (list.size() == 0)\n    return T(0);\n\n  T dev = 0.;\n  for (const auto &l : list)\n    dev += (l - mean) * (l - mean);\n  dev = dev / (T(list.size()));\n\n  return std::sqrt(dev);\n}\n\ntemplate<class T>\ninline T get_std_dev(const std::vector<T> &list) {\n\n  if (list.size() == 0)\n    return T(0);\n\n  // get mean\n  auto mean = get_avg(list);\n\n  T dev = 0.;\n  for (const auto &l : list)\n    dev += (l - mean) * (l - mean);\n  dev = dev / (T(list.size()));\n\n  return std::sqrt(dev);\n}\n\ninline std::mt19937 get_random_generator(int seed) {\n  if (seed < 0) {\n    std::random_device rd;\n    return std::mt19937(rd());\n  } else {\n    return std::mt19937(seed);\n  }\n}\n\ninline boost::mt19937 get_random_generator_boost(int seed) {\n\n  if (seed < 0) {\n    auto rd = boost::mt19937();\n    return rd;\n  } else {\n    auto rd = boost::mt19937(seed);\n    return rd;\n  }\n}\n\ninline double proj(double x) {\n  auto y = 1. < x ? 1. : x;\n  return 0. > y ? 0. : y;\n}\n\n} // namespace util\n\n#endif // UTILS_H\n", "meta": {"hexsha": "b8e6e2e42dfd342196a8afeaecf1260fb0dd9e7a", "size": 12923, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "models/utils/utils.hpp", "max_stars_repo_name": "CancerModeling/Angiogenesis3D1D", "max_stars_repo_head_hexsha": "77527d3facd127e225ccb9e53874ddbba2096744", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-02T07:49:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T15:47:40.000Z", "max_issues_repo_path": "models/utils/utils.hpp", "max_issues_repo_name": "CancerModeling/Angiogenesis3D1D", "max_issues_repo_head_hexsha": "77527d3facd127e225ccb9e53874ddbba2096744", "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": "models/utils/utils.hpp", "max_forks_repo_name": "CancerModeling/Angiogenesis3D1D", "max_forks_repo_head_hexsha": "77527d3facd127e225ccb9e53874ddbba2096744", "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.1070707071, "max_line_length": 138, "alphanum_fraction": 0.641182388, "num_tokens": 3250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.7090191399336401, "lm_q1q2_score": 0.535249166892871}}
{"text": "#include <aikido/constraint/NewtonsMethodProjectable.hpp>\n#include <aikido/constraint/Satisfied.hpp>\n#include <aikido/constraint/dart/TSR.hpp>\n#include \"PolynomialConstraint.hpp\"\n\n#include <aikido/statespace/Rn.hpp>\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\nusing aikido::constraint::NewtonsMethodProjectable;\nusing aikido::constraint::Satisfied;\nusing aikido::constraint::dart::TSR;\nusing aikido::statespace::R1;\nusing aikido::statespace::R3;\n\nTEST(NewtonsMethodProjectableTest, ConstructorThrowsOnNullDifferentiable)\n{\n  EXPECT_THROW(\n      NewtonsMethodProjectable(nullptr, std::vector<double>{}, 1, 1),\n      std::invalid_argument);\n}\n\nTEST(NewtonsMethodProjectableTest, ConstructorThrowsOnBadToleranceDimension)\n{\n  auto ss = std::make_shared<R3>();\n  auto constraint = std::make_shared<Satisfied>(ss); // dimension = 0\n  EXPECT_THROW(\n      NewtonsMethodProjectable(constraint, std::vector<double>({0.1}), 1, 1e-4),\n      std::invalid_argument);\n}\n\nTEST(NewtonsMethodProjectableTest, ConstructorThrowsOnNegativeTolerance)\n{\n  auto constraint\n      = std::make_shared<PolynomialConstraint<1>>(Eigen::Vector3d(1, 2, 3));\n  EXPECT_THROW(\n      NewtonsMethodProjectable(\n          constraint, std::vector<double>({-0.1}), 1, 1e-4),\n      std::invalid_argument);\n}\n\nTEST(NewtonsMethodProjectableTest, ConstructorThrowsOnNegativeIteration)\n{\n  auto ss = std::make_shared<R3>();\n  auto constraint = std::make_shared<Satisfied>(ss); // dimension = 0\n  EXPECT_THROW(\n      NewtonsMethodProjectable(constraint, std::vector<double>(), 0, 1e-4),\n      std::invalid_argument);\n  EXPECT_THROW(\n      NewtonsMethodProjectable(constraint, std::vector<double>(), -1, 1e-4),\n      std::invalid_argument);\n}\n\nTEST(NewtonsMethodProjectableTest, ConstructorThrowsOnNegativeStepsize)\n{\n  auto ss = std::make_shared<R3>();\n  auto constraint = std::make_shared<Satisfied>(ss); // dimension = 0\n  EXPECT_THROW(\n      NewtonsMethodProjectable(constraint, std::vector<double>(), 1, 0),\n      std::invalid_argument);\n  EXPECT_THROW(\n      NewtonsMethodProjectable(constraint, std::vector<double>(), 1, -0.1),\n      std::invalid_argument);\n}\n\nTEST(NewtonsMethodProjectable, Constructor)\n{\n  // Constraint: x^2 - 1 = 0.\n  NewtonsMethodProjectable projector(\n      std::make_shared<PolynomialConstraint<1>>(Eigen::Vector3d(-1, 0, 1)),\n      std::vector<double>({0.1}),\n      10,\n      1e-4);\n}\n\nTEST(NewtonsMethodProjectable, ProjectPolynomialFirstOrder)\n{\n  NewtonsMethodProjectable projector(\n      std::make_shared<PolynomialConstraint<1>>(Eigen::Vector2d(1, 2)),\n      std::vector<double>({0.1}),\n      1,\n      1e-4);\n\n  Eigen::VectorXd v(1);\n  v(0) = -2;\n\n  R1 rvss;\n  auto s1 = rvss.createState();\n  s1.setValue(v);\n\n  auto out = rvss.createState();\n  ASSERT_TRUE(projector.project(s1, out));\n  Eigen::VectorXd projected = rvss.getValue(out);\n\n  Eigen::VectorXd expected(1);\n  expected(0) = -0.5;\n\n  EXPECT_TRUE(expected.isApprox(projected));\n}\n\nTEST(NewtonsMethodProjectable, ProjectPolynomialSecondOrder)\n{\n  // Constraint: x^2 - 1 = 0.\n  NewtonsMethodProjectable projector(\n      std::make_shared<PolynomialConstraint<1>>(Eigen::Vector3d(-1, 0, 1)),\n      std::vector<double>({1e-6}),\n      10,\n      1e-8);\n\n  // Project x = -2. Should get -1 as projected solution.\n  Eigen::VectorXd v(1);\n  v(0) = -2;\n\n  R1 rvss;\n  auto seedState = rvss.createState();\n  seedState.setValue(v);\n\n  auto out = rvss.createState();\n  EXPECT_TRUE(projector.project(seedState, out));\n  Eigen::VectorXd projected = rvss.getValue(out);\n\n  Eigen::VectorXd expected(1);\n  expected(0) = -1;\n\n  EXPECT_TRUE(expected.isApprox(projected, 1e-5));\n\n  // Project x = 1.5. Should get 1 as projected solution.\n  v(0) = 1.5;\n  seedState.setValue(v);\n\n  EXPECT_TRUE(projector.project(seedState, out));\n  projected = rvss.getValue(out);\n\n  expected(0) = 1;\n\n  EXPECT_TRUE(expected.isApprox(projected, 1e-5));\n\n  // Project x = 1. Should get 1 as projected solution.\n  v(0) = 1;\n  seedState.setValue(v);\n\n  EXPECT_TRUE(projector.project(seedState, out));\n  projected = rvss.getValue(out);\n\n  expected(0) = 1;\n\n  EXPECT_TRUE(expected.isApprox(projected, 1e-5));\n}\n\nTEST(NewtonsMethodProjectable, ProjectTSRTranslation)\n{\n  std::shared_ptr<TSR> tsr = std::make_shared<TSR>();\n\n  // non-trivial translation bounds\n  Eigen::MatrixXd Bw = Eigen::Matrix<double, 6, 2>::Zero();\n  Bw(0, 0) = 1;\n  Bw(0, 1) = 2;\n\n  tsr->mBw = Bw;\n\n  auto space = tsr->getSE3();\n\n  auto seedState = space->createState();\n\n  Eigen::Isometry3d isometry = Eigen::Isometry3d::Identity();\n  isometry.translation() = Eigen::Vector3d(-1, 0, 1);\n  seedState.setIsometry(isometry);\n\n  NewtonsMethodProjectable projector(\n      tsr, std::vector<double>(6, 1e-4), 1000, 1e-8);\n\n  auto out = space->createState();\n  EXPECT_TRUE(projector.project(seedState, out));\n  auto projected = space->getIsometry(out);\n\n  Eigen::Isometry3d expected = Eigen::Isometry3d::Identity();\n  expected.translation() = Eigen::Vector3d(1, 0, 0);\n\n  EXPECT_TRUE(expected.isApprox(projected, 5e-4));\n}\n\nTEST(NewtonsMethodProjectable, ProjectTSRRotation)\n{\n  std::shared_ptr<TSR> tsr = std::make_shared<TSR>();\n\n  // non-trivial rotation bounds\n  Eigen::MatrixXd Bw = Eigen::Matrix<double, 6, 2>::Zero();\n  Bw(3, 0) = M_PI_4;\n  Bw(3, 1) = M_PI_2;\n\n  tsr->mBw = Bw;\n\n  auto space = tsr->getSE3();\n  auto seedState = space->createState();\n\n  NewtonsMethodProjectable projector(\n      tsr, std::vector<double>(6, 1e-4), 1000, 1e-8);\n\n  auto out = space->createState();\n  EXPECT_TRUE(projector.project(seedState, out));\n  auto projected = space->getIsometry(out);\n\n  Eigen::Isometry3d expected = Eigen::Isometry3d::Identity();\n\n  Eigen::Matrix3d rotation;\n  rotation = Eigen::AngleAxisd(0, Eigen::Vector3d::UnitZ())\n             * Eigen::AngleAxisd(0, Eigen::Vector3d::UnitY())\n             * Eigen::AngleAxisd(M_PI_4, Eigen::Vector3d::UnitX());\n  expected.linear() = rotation;\n\n  EXPECT_TRUE(expected.isApprox(projected, 5e-4));\n}\n", "meta": {"hexsha": "95174568680c2dc4f1bbf5f0b1f254243bc9843a", "size": 5920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/constraint/test_NewtonsMethodProjectable.cpp", "max_stars_repo_name": "usc-csci-545/aikido", "max_stars_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "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/constraint/test_NewtonsMethodProjectable.cpp", "max_issues_repo_name": "usc-csci-545/aikido", "max_issues_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/constraint/test_NewtonsMethodProjectable.cpp", "max_forks_repo_name": "usc-csci-545/aikido", "max_forks_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "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.6635514019, "max_line_length": 80, "alphanum_fraction": 0.6952702703, "num_tokens": 1747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5352491654286405}}
{"text": "#include \"testsuite.h\"\n#include <blitz/array.h>\n#include <blitz/array/stencil-et.h>\n\nBZ_USING_NAMESPACE(blitz)\n\ntypedef blitz::Array<double,1> array_1;\ntypedef blitz::Array<double,2> array_2;\ntypedef blitz::Array<double,3> array_3;\n\n/* Test slicing functionality for expressions. */\n\n#define test_expr(d1,d2) BZTEST(all(abs(d1-d2)<1e-5));\n\n// test with functors\nclass doubler {\npublic:\n  double operator()(double x) const {return 2.0*x;}\n  BZ_DECLARE_FUNCTOR(doubler);\n};\n\nclass multiplier {\npublic:\n  double operator()(double a, double b) const {return a*b;}\n  BZ_DECLARE_FUNCTOR2(multiplier);\n};\n\n\nint main()\n{\n  array_2 a(5);\n  a=tensor::i+10.*tensor::j;\n\n  test_expr((2.*a)(1,Range::all()), array_2(2.*a)(1,Range::all()));\n  test_expr(sin(a)(1,Range::all()), array_2(sin(a))(1,Range::all()));\n  test_expr(where(a<5.,1./a,a)(1,Range::all()), \n\t    array_2(where(a<5.,1./a,a))(1,Range::all()));\n  // stencils can't be sliced down in rank, so integers are converted to unit ranges\n  test_expr(Laplacian2D(sin(a))(1,Range::all()),\n\t    array_2(Laplacian2D(sin(a)))(Range(1,1),Range::all()));\n  doubler d;\n  multiplier m;\n  test_expr(d(a)(1,Range::all()), array_2(d(a))(1,Range::all()));\n  test_expr(m(a,a)(1,Range::all()), array_2(m(a,a))(1,Range::all()));\n\n  //complete slicing to scalar\n  BZTEST((2.*a)(1,1)==array_2(2.*a)(1,1));\n  BZTEST((2.*a(1,Range::all())(1))==(array_1(2.*a(1,Range::all()))(1)));\n\n  //more dims\n  Array<double,5> big(2,3,4,5,6);\n  big=tensor::i+10.*tensor::j+100*tensor::k+1000.*tensor::l+10000.*tensor::m;\n  BZTEST(((2.*big)(1,2,3,4,5))==2.*big(1,2,3,4,5));\n  \n  test_expr((2.*big)(0,Range(0,1),1,Range::all(), Range(2,4,2)),\n\t    (Array<double,3>(2.*big(0,Range(0,1),1,Range::all(), Range(2,4,2)))));\n\n  // slicing reductions, index remappings and index placeholder\n  // expressions does not work.\n\n  return 0;\n}\n\n\n", "meta": {"hexsha": "c869cb1ff6213d79eefd8e2fe36ca970eb5de3e7", "size": 1842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/expression-slicing.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/expression-slicing.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/expression-slicing.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.3384615385, "max_line_length": 84, "alphanum_fraction": 0.6411509229, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5352478033079936}}
{"text": "/*\n * Copyright 2009-2018 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 *\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#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE bfgs_test\n#include <boost/test/unit_test.hpp>\n#include <votca/xtp/optimiser_costfunction.h>\n#include <votca/xtp/bfgs-trm.h>\n#include <votca/ctp/logger.h>\n#include <iostream>\n#include <boost/format.hpp>\nusing namespace votca::xtp;\nusing namespace votca;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(bfgs_test)\n\nBOOST_AUTO_TEST_CASE(parabola_test) {\n  class parabola : public Optimiser_costfunction{\n\n     double EvaluateCost(const Eigen::VectorXd& parameters) {\n      Eigen::VectorXd value=parameters;\n      value(0)-=2;\n      double cost = value.cwiseAbs2().sum();\n      return cost;\n    }\n     \n     Eigen::VectorXd EvaluateGradient(const Eigen::VectorXd& parameters){\n       Eigen::VectorXd gradient=2*parameters;\n       gradient(0)-=4;\n       return gradient;\n     }\n\n    bool Converged(const Eigen::VectorXd& delta_parameters,\n            double delta_cost, const Eigen::VectorXd& gradient){\n      if (gradient.cwiseAbs().maxCoeff() < 1e-9)return true;\n      else return false;\n    }\n\n    int NumParameters()const {\n      return 5;\n    }\n    \n  };\n  \n  parabola p5;\n  BFGSTRM bfgstrm(p5);\n  bfgstrm.setNumofIterations(100);\n  bfgstrm.setTrustRadius(0.1);\n  bfgstrm.Optimize(5*Eigen::VectorXd::Ones(5));\n  \n  Eigen::VectorXd ref=Eigen::VectorXd::Zero(5);\n  ref(0)=2;\n bool equal= bfgstrm.getParameters().isApprox(ref,0.00001);\n if(!equal){\n   cout<<\"minimum found:\"<<endl;\n   cout<<bfgstrm.getParameters()<<endl;\n   cout<<\"minimum ref:\"<<endl;\n   cout<<ref<<endl;\n }else{\n   cout<<bfgstrm.getIteration()<<endl;\n }\n  BOOST_CHECK_EQUAL(equal, 1);\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "2553c45b63ec51a92907d81a4265f254a7d9a6ff", "size": 2229, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_bfgs-trm.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "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_bfgs-trm.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "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_bfgs-trm.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "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.1829268293, "max_line_length": 75, "alphanum_fraction": 0.7012113055, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5352478033079935}}
{"text": "#include <iostream>\n#include <boost/chrono.hpp>\n//#include <chrono>\n#include <ctime>\n \nlong fibonacci(unsigned n)\n{\n    if (n < 2) return n;\n    return fibonacci(n-1) + fibonacci(n-2);\n}\n \nint main()\n{\n    boost::chrono::time_point<boost::chrono::system_clock> start, end;\n    start = boost::chrono::system_clock::now();\n    std::cout << \"f(42) = \" << fibonacci(42) << '\\n';\n    end = boost::chrono::system_clock::now();\n \n    boost::chrono::duration<double> elapsed_seconds = end-start;\n    std::time_t end_time = boost::chrono::system_clock::to_time_t(end);\n \n    std::cout << \"finished computation at \" << std::ctime(&end_time)\n              << \"elapsed time: \" << elapsed_seconds.count() << \"s\\n\";\n}\n", "meta": {"hexsha": "2758ba8de2d135e78dacb2c24307fb88f54b72b4", "size": 704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dev/radams/chrono/chronoTest.cpp", "max_stars_repo_name": "wvat/NTRTsim", "max_stars_repo_head_hexsha": "0443cbd542e12e23c04adf79ea0d8d003c428baa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 148.0, "max_stars_repo_stars_event_min_datetime": "2015-01-08T22:44:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T18:42:48.000Z", "max_issues_repo_path": "src/dev/radams/chrono/chronoTest.cpp", "max_issues_repo_name": "wvat/NTRTsim", "max_issues_repo_head_hexsha": "0443cbd542e12e23c04adf79ea0d8d003c428baa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 107.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T16:41:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-14T22:09:19.000Z", "max_forks_repo_path": "src/dev/radams/chrono/chronoTest.cpp", "max_forks_repo_name": "wvat/NTRTsim", "max_forks_repo_head_hexsha": "0443cbd542e12e23c04adf79ea0d8d003c428baa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 86.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T07:02:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T17:36:14.000Z", "avg_line_length": 28.16, "max_line_length": 71, "alphanum_fraction": 0.625, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.535247798458034}}
{"text": "\r\n#include <iostream>\r\n#include <boost/numeric/interval.hpp>\r\n\r\n\r\nint main()\r\n{\r\n\tboost::numeric::interval<int> range1(0, 100);\r\n\tstd::cout << boost::numeric::median(range1) << std::endl;\r\n\tstd::cout << boost::numeric::width(range1) << std::endl;\r\n\t\r\n\r\n\tboost::numeric::interval<int> range2(6, 7);\r\n\tboost::numeric::interval<int> range3(4, 8);\r\n\t\r\n\tauto range_min = boost::numeric::min(range2, range3);\r\n\r\n\tstd::cout << range_min.lower() << \" ~ \"\r\n\t\t<< range_min.upper() << std::endl;\r\n\r\n\tauto range_max = boost::numeric::max(range2, range3);\r\n\t\r\n\tstd::cout << range_max.lower() << \" ~ \"\r\n\t\t<< range_max.upper() << std::endl;\r\n\r\n\r\n\tboost::numeric::interval<int> range4(-4, 8);\r\n\t\r\n\tauto range_abs = boost::numeric::abs(range4);\r\n\t\r\n\tstd::cout << range_abs.lower() << \" ~ \"\r\n\t\t<< range_abs.upper() << std::endl;\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "f2cc1d37fde3c1dd9c07f767dd0ceabdfa6be611", "size": 833, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Boost_20140423/interval_06/interval_06.cpp", "max_stars_repo_name": "jacking75/book_semina_samples", "max_stars_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_stars_repo_licenses": ["MIT"], "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_20140423/interval_06/interval_06.cpp", "max_issues_repo_name": "jacking75/book_semina_samples", "max_issues_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_issues_repo_licenses": ["MIT"], "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_20140423/interval_06/interval_06.cpp", "max_forks_repo_name": "jacking75/book_semina_samples", "max_forks_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_forks_repo_licenses": ["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.9210526316, "max_line_length": 59, "alphanum_fraction": 0.600240096, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5352477961252069}}
{"text": "// Boost.Graph library isomorphism test\n\n// Copyright (C) 2001 Douglas Gregor (gregod@cs.rpi.edu)\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// For more information, see http://www.boost.org\n//\n// Revision History:\n//\n// 29 Nov 2001    Jeremy Siek\n//      Changed to use Boost.Random.\n// 29 Nov 2001    Doug Gregor\n//      Initial checkin.\n\n#define BOOST_INCLUDE_MAIN\n#include <boost/test/test_tools.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/isomorphism.hpp>\n//#include \"isomorphism-v3.hpp\"\n#include <boost/property_map/property_map.hpp>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n\nusing namespace boost;\n\nenum\n{\n    a,\n    b,\n    c,\n    d,\n    e,\n    f,\n    g,\n    h\n};\nenum\n{\n    _1,\n    _2,\n    _3,\n    _4,\n    _5,\n    _6,\n    _7,\n    _8\n};\n\nvoid test_isomorphism()\n{\n    typedef adjacency_list< vecS, vecS, bidirectionalS > GraphA;\n    typedef adjacency_list< vecS, vecS, bidirectionalS > GraphB;\n\n    char a_names[] = \"abcdefgh\";\n    char b_names[] = \"12345678\";\n\n    GraphA Ga(8);\n    add_edge(a, d, Ga);\n    add_edge(a, h, Ga);\n    add_edge(b, c, Ga);\n    add_edge(b, e, Ga);\n    add_edge(c, f, Ga);\n    add_edge(d, a, Ga);\n    add_edge(d, h, Ga);\n    add_edge(e, b, Ga);\n    add_edge(f, b, Ga);\n    add_edge(f, e, Ga);\n    add_edge(g, d, Ga);\n    add_edge(g, f, Ga);\n    add_edge(h, c, Ga);\n    add_edge(h, g, Ga);\n\n    GraphB Gb(8);\n    add_edge(_1, _6, Gb);\n    add_edge(_2, _1, Gb);\n    add_edge(_2, _5, Gb);\n    add_edge(_3, _2, Gb);\n    add_edge(_3, _4, Gb);\n    add_edge(_4, _2, Gb);\n    add_edge(_4, _3, Gb);\n    add_edge(_5, _4, Gb);\n    add_edge(_5, _6, Gb);\n    add_edge(_6, _7, Gb);\n    add_edge(_6, _8, Gb);\n    add_edge(_7, _8, Gb);\n    add_edge(_8, _1, Gb);\n    add_edge(_8, _7, Gb);\n\n    std::vector< std::size_t > in_degree_A(num_vertices(Ga));\n    boost::detail::compute_in_degree(Ga, &in_degree_A[0]);\n\n    std::vector< std::size_t > in_degree_B(num_vertices(Gb));\n    boost::detail::compute_in_degree(Gb, &in_degree_B[0]);\n\n    degree_vertex_invariant< std::size_t*, GraphA > invariantA(\n        &in_degree_A[0], Ga);\n    degree_vertex_invariant< std::size_t*, GraphB > invariantB(\n        &in_degree_B[0], Gb);\n\n    std::vector< graph_traits< GraphB >::vertex_descriptor > f(\n        num_vertices(Ga));\n\n    bool ret = isomorphism(Ga, Gb, &f[0], invariantA, invariantB,\n        (invariantB.max)(), get(vertex_index, Ga), get(vertex_index, Gb));\n    assert(ret == true);\n\n    for (std::size_t i = 0; i < num_vertices(Ga); ++i)\n        std::cout << \"f(\" << a_names[i] << \")=\" << b_names[f[i]] << std::endl;\n\n    BOOST_TEST(verify_isomorphism(Ga, Gb, &f[0]));\n}\n\nint test_main(int, char*[])\n{\n    test_isomorphism();\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "b16835c2df26d2cc4a08d77e1512e46a41aa647e", "size": 2891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/doc/eg1-iso.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.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": "3rdparty/boost_1_73_0/libs/graph/doc/eg1-iso.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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/graph/doc/eg1-iso.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": 23.128, "max_line_length": 78, "alphanum_fraction": 0.6153580076, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5352477912752472}}
{"text": "//\n// Copyright (c) 2016-2020 CNRS INRIA\n//\n\n#ifndef __pinocchio_math_matrix_hpp__\n#define __pinocchio_math_matrix_hpp__\n\n#include \"pinocchio/macros.hpp\"\n#include \"pinocchio/math/fwd.hpp\"\n\n#include <Eigen/Core>\n#include <boost/type_traits.hpp>\n\nnamespace pinocchio\n{\n\n  template<typename Derived>\n  inline bool hasNaN(const Eigen::DenseBase<Derived> & m) \n  {\n    return !((m.derived().array()==m.derived().array()).all());\n  }\n\n  template<typename M1, typename M2>\n  struct MatrixMatrixProduct\n  {\n#if EIGEN_VERSION_AT_LEAST(3,2,90)\n    typedef typename Eigen::Product<M1,M2> type;\n#else\n    typedef typename Eigen::ProductReturnType<M1,M2>::Type type;\n#endif\n  };\n  \n  template<typename Scalar, typename Matrix>\n  struct ScalarMatrixProduct\n  {\n#if EIGEN_VERSION_AT_LEAST(3,3,0)\n    typedef Eigen::CwiseBinaryOp<EIGEN_CAT(EIGEN_CAT(Eigen::internal::scalar_,product),_op)<Scalar,typename Eigen::internal::traits<Matrix>::Scalar>,\n    const typename Eigen::internal::plain_constant_type<Matrix,Scalar>::type, const Matrix> type;\n#elif EIGEN_VERSION_AT_LEAST(3,2,90)\n    typedef Eigen::CwiseUnaryOp<Eigen::internal::scalar_multiple_op<Scalar>, const Matrix> type;\n#else\n    typedef const Eigen::CwiseUnaryOp<Eigen::internal::scalar_multiple_op<Scalar>, const Matrix> type;\n#endif\n  };\n  \n  template<typename Matrix, typename Scalar>\n  struct MatrixScalarProduct\n  {\n#if EIGEN_VERSION_AT_LEAST(3,3,0)\n    typedef Eigen::CwiseBinaryOp<EIGEN_CAT(EIGEN_CAT(Eigen::internal::scalar_,product),_op)<typename Eigen::internal::traits<Matrix>::Scalar,Scalar>,\n    const Matrix, const typename Eigen::internal::plain_constant_type<Matrix,Scalar>::type> type;\n#elif EIGEN_VERSION_AT_LEAST(3,2,90)\n    typedef Eigen::CwiseUnaryOp<Eigen::internal::scalar_multiple_op<Scalar>, const Matrix> type;\n#else\n    typedef const Eigen::CwiseUnaryOp<Eigen::internal::scalar_multiple_op<Scalar>, const Matrix> type;\n#endif\n  };\n  \n  namespace internal\n  {\n    template<typename MatrixLike, bool value = boost::is_floating_point<typename MatrixLike::Scalar>::value>\n    struct isUnitaryAlgo\n    {\n      typedef typename MatrixLike::Scalar Scalar;\n      typedef typename MatrixLike::RealScalar RealScalar;\n      \n      static bool run(const Eigen::MatrixBase<MatrixLike> & mat,\n                      const RealScalar & prec =\n                      Eigen::NumTraits< Scalar >::dummy_precision())\n      {\n        return mat.isUnitary(prec);\n      }\n    };\n    \n    template<typename MatrixLike>\n    struct isUnitaryAlgo<MatrixLike,false>\n    {\n      typedef typename MatrixLike::Scalar Scalar;\n      typedef typename MatrixLike::RealScalar RealScalar;\n      \n      static bool run(const Eigen::MatrixBase<MatrixLike> & /*vec*/,\n                      const RealScalar & prec =\n                      Eigen::NumTraits< Scalar >::dummy_precision())\n      {\n        PINOCCHIO_UNUSED_VARIABLE(prec);\n        return true;\n      }\n    };\n  }\n  \n  ///\n  /// \\brief Check whether the input matrix is Unitary within the given precision.\n  ///\n  /// \\param[in] mat Input matrix\n  /// \\param[in] prec Required precision\n  ///\n  /// \\returns true if mat is unitary within the precision prec\n  ///\n  template<typename MatrixLike>\n  inline bool isUnitary(const Eigen::MatrixBase<MatrixLike> & mat,\n                        const typename MatrixLike::RealScalar & prec =\n                        Eigen::NumTraits< typename MatrixLike::Scalar >::dummy_precision())\n  {\n    return internal::isUnitaryAlgo<MatrixLike>::run(mat,prec);\n  }\n\n  namespace internal\n  {\n    template<typename VectorLike, bool value = boost::is_floating_point<typename VectorLike::Scalar>::value>\n    struct isNormalizedAlgo\n    {\n      typedef typename VectorLike::Scalar Scalar;\n      typedef typename VectorLike::RealScalar RealScalar;\n      \n      static bool run(const Eigen::MatrixBase<VectorLike> & vec,\n                      const RealScalar & prec =\n                      Eigen::NumTraits<RealScalar>::dummy_precision())\n      {\n        return math::fabs(vec.norm() - RealScalar(1)) <= prec;\n      }\n    };\n    \n    template<typename VectorLike>\n    struct isNormalizedAlgo<VectorLike,false>\n    {\n      typedef typename VectorLike::Scalar Scalar;\n      typedef typename VectorLike::RealScalar RealScalar;\n      \n      static bool run(const Eigen::MatrixBase<VectorLike> & /*vec*/,\n                      const RealScalar & prec =\n                      Eigen::NumTraits<RealScalar>::dummy_precision())\n      {\n        PINOCCHIO_UNUSED_VARIABLE(prec);\n        return true;\n      }\n    };\n  }\n\n  ///\n  /// \\brief Check whether the input vector is Normalized within the given precision.\n  ///\n  /// \\param[in] vec Input vector\n  /// \\param[in] prec Required precision\n  ///\n  /// \\returns true if vec is normalized within the precision prec.\n  ///\n  template<typename VectorLike>\n  inline bool isNormalized(const Eigen::MatrixBase<VectorLike> & vec,\n                           const typename VectorLike::RealScalar & prec =\n                           Eigen::NumTraits< typename VectorLike::Scalar >::dummy_precision())\n  {\n    EIGEN_STATIC_ASSERT_VECTOR_ONLY(VectorLike);\n    return internal::isNormalizedAlgo<VectorLike>::run(vec,prec);\n  }\n  \n  namespace internal\n  {\n    template<typename Scalar>\n    struct CallCorrectMatrixInverseAccordingToScalar\n    {\n      template<typename MatrixIn, typename MatrixOut>\n      static void run(const Eigen::MatrixBase<MatrixIn> & m_in,\n                      const Eigen::MatrixBase<MatrixOut> & dest)\n      {\n        MatrixOut & dest_ = PINOCCHIO_EIGEN_CONST_CAST(MatrixOut,dest);\n        dest_.noalias() = m_in.inverse();\n      }\n    };\n  \n  }\n  \n  template<typename MatrixIn, typename MatrixOut>\n  inline void inverse(const Eigen::MatrixBase<MatrixIn> & m_in,\n                      const Eigen::MatrixBase<MatrixOut> & dest)\n  {\n    MatrixOut & dest_ = PINOCCHIO_EIGEN_CONST_CAST(MatrixOut,dest);\n    internal::CallCorrectMatrixInverseAccordingToScalar<typename MatrixIn::Scalar>::run(m_in,dest_);\n  }\n\n}\n\n#endif //#ifndef __pinocchio_math_matrix_hpp__\n", "meta": {"hexsha": "b41376df6ccb8fc4ab1773dd4c88dbb17d339c2d", "size": 6025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/matrix.hpp", "max_stars_repo_name": "alexxlzhou/pinocchio", "max_stars_repo_head_hexsha": "8716079be29bdf1d707024fdfddc8d28107cf084", "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/math/matrix.hpp", "max_issues_repo_name": "alexxlzhou/pinocchio", "max_issues_repo_head_hexsha": "8716079be29bdf1d707024fdfddc8d28107cf084", "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/matrix.hpp", "max_forks_repo_name": "alexxlzhou/pinocchio", "max_forks_repo_head_hexsha": "8716079be29bdf1d707024fdfddc8d28107cf084", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-26T14:29:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T14:29:02.000Z", "avg_line_length": 32.9234972678, "max_line_length": 149, "alphanum_fraction": 0.6741908714, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.53524072097783}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include \"RealType.hxx\"\n#include \"MyTriDiagonalMatrix.hxx\"\n#include \"my_tbb_parallel_for.hxx\"\n#include \"TBBSSESolverOperator.hxx\"\n#include \"TBBSSESolverOperatorBis.hxx\"\n\nclass SIMDSolve{\n\n  static const int blockSize=4;\n\n  typedef Legolas::MultiVector<RealType,1> V1D;\n  \n  typedef Eigen::Array<RealType, blockSize, 1> BlockArray;\n  typedef Eigen::Map<BlockArray,Eigen::Aligned>  BlockArrayView;\n  typedef Eigen::Map<const BlockArray,Eigen::Aligned>  ConstBlockArrayView;\n\n  typedef Legolas::MultiVector<RealType,2>  V2D;\n\n  V2D  XI_;\n  V2D  BI_;\n  V2D  SI_;\n\n  V2D  DI_;  \n  V2D  LI_;\n  V2D  UI_;\n\n  Legolas::MultiVector<RealType,1>  S_;\n\n  int s1_,s2_;\n\n\npublic:\n  SIMDSolve(const MyDiagonalBlockMatrix & A):XI_(),BI_(),DI_(),LI_(),UI_(),S_(),s1_(),s2_(){\n    \n    s1_=A.nrows();\n    const MyTriDiagonalMatrix<RealType> & A00=static_cast<const  MyTriDiagonalMatrix<RealType> & >(A.diagonalGetElement(0));\n    s2_=A00.nrows();\n\n    Legolas::MultiVector<RealType,2>::Shape  shape(s1_/blockSize,s2_*blockSize);\n\n    XI_.reshape(shape);    \n    BI_.reshape(shape);    \n    SI_.reshape(shape);    \n\n    DI_.reshape(shape);    \n    LI_.reshape(shape);    \n    UI_.reshape(shape);    \n    \n    S_.reshape(s2_*blockSize);    \n    \n    for (int i=0 ; i<s1_/blockSize ; i++){\n      for (int j=0 ; j<s2_ ; j++){\n\tfor (int k=0 ; k<blockSize ; k++){\n\t  \n\t  const int newI=i;\n\t  const int newJ=blockSize*j+k;\n\t  const int oldI=blockSize*i+k;\n\t  const int oldJ=j;\n\t  \n\t  const MyTriDiagonalMatrix<RealType> & Aii=static_cast<const  MyTriDiagonalMatrix<RealType> & >(A.diagonalGetElement(oldI));\n\t  \n\t  DI_[newI][newJ]=Aii.diagonalGetElement(oldJ);\n\t  LI_[newI][newJ]=Aii.lowerDiagonalGetElement(oldJ);\n\t  UI_[newI][newJ]=Aii.upperDiagonalGetElement(oldJ);\n\t  \n\t}\n      }\n    }\n  }\n\n  void updateB(const V2D & B){\n\n    for (int i=0 ; i<s1_/blockSize ; i++){\n      for (int j=0 ; j<s2_ ; j++){\n\tfor (int k=0 ; k<blockSize ; k++){\n\t  \n\t  const int newI=i;\n\t  const int newJ=blockSize*j+k;\n\t  const int oldI=blockSize*i+k;\n\t  const int oldJ=j;\n\n\t  BI_[newI][newJ]=B[oldI][oldJ];\n\t}\n      }\n    }\n  }\n\n  void updateB(RealType value){\n    BI_=value;\n  }\n\n\n  void updateX(V2D & X) const {\n\n    for (int i=0 ; i<s1_/blockSize ; i++){\n      for (int j=0 ; j<s2_ ; j++){\n\tfor (int k=0 ; k<blockSize ; k++){\n\t  \n\t  const int newI=i;\n\t  const int newJ=blockSize*j+k;\n\t  const int oldI=blockSize*i+k;\n\t  const int oldJ=j;\n\n\t  X[oldI][oldJ]=XI_[newI][newJ];\n\t}\n      }\n    }\n  }\n  \n  \n  void solve( void ){\n\n    for (int b=0 ; b<s1_/blockSize ; b++){\n\t  \n      const V1D & D=DI_[b];\n      const V1D & U=UI_[b];\n      const V1D & L=LI_[b];\n\t\n      const V1D & B=BI_[b];\n\t\n      V1D & X=XI_[b];\n\t\n      ConstBlockArrayView D0(&D[0]);\n      BlockArray s(D0);\n\t\n      BlockArrayView X0(&X[0]);\n      ConstBlockArrayView B0(&B[0]);\n\t\n      //\t  X0=B0/s;\n      X0=B0;\n      X0/=s;\n\t\n\t\n      for (int i=1 ; i < s2_ ; i++ ){\n\t  \n\tconst int I=blockSize*i;\n\t  \n\t//S_[i]=A.upperDiagonalGetElement(i-1)/s;\n\tBlockArrayView Si(&S_[I]);\n\tSi=ConstBlockArrayView(&U[I-blockSize]);\n\tSi/=s;\n\t  \n\t//\t    Si=ConstBlockArrayView(&U[I])/s;\n\t  \n\tConstBlockArrayView Li(&L[I]);\n\t  \n\ts=ConstBlockArrayView(&D[I])-Li*Si;\n\t  \n\tBlockArrayView Xi(&X[I]);\n\tConstBlockArrayView Xim1(&X[I-blockSize]);\n\tConstBlockArrayView Bi(&B[I]);\n\tXi=Bi;\n\tXi-=Li*Xim1;\n\tXi/=s;\n\t  \n      }\n\t\n      for (int i=(s2_-2) ; i >= 0 ; i-- ){\n\t  \n\tconst int I=blockSize*i;\n\t//X[i]-=S_[i+1]*X[i+1];\n\tBlockArrayView Xi(&X[I]);\n\tConstBlockArrayView Sip1(&S_[I+blockSize]);\n\tConstBlockArrayView Xip1(&X[I+blockSize]);\n\tXi-=Sip1*Xip1;\n      }\n    }\n      \n  }\n\n\n  void parallelSolve( void ){\n    my_tbb::parallel_for(my_tbb::blocked_range<int>(0,s1_/blockSize),TBBSSESolverOperator(DI_,LI_,UI_,BI_,XI_));\n    //    my_tbb::parallel_for(my_tbb::blocked_range<int>(0,s1_/blockSize),TBBSSESolverOperatorBis(DI_,LI_,UI_,BI_,SI_,XI_));\n  }\n\n};\n    \n    \n", "meta": {"hexsha": "e8f2707433805a13ad33982aaed467312c167fa5", "size": 3897, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "Legolas/BlockMatrix/tst/DiagonalTriDiagonal/SIMDSolve.hxx", "max_stars_repo_name": "LaurentPlagne/Legolas", "max_stars_repo_head_hexsha": "fdf533528baf7ab5fcb1db15d95d2387b3e3723c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Legolas/BlockMatrix/tst/DiagonalTriDiagonal/SIMDSolve.hxx", "max_issues_repo_name": "LaurentPlagne/Legolas", "max_issues_repo_head_hexsha": "fdf533528baf7ab5fcb1db15d95d2387b3e3723c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Legolas/BlockMatrix/tst/DiagonalTriDiagonal/SIMDSolve.hxx", "max_forks_repo_name": "LaurentPlagne/Legolas", "max_forks_repo_head_hexsha": "fdf533528baf7ab5fcb1db15d95d2387b3e3723c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-11T14:43:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-11T14:43:25.000Z", "avg_line_length": 21.4120879121, "max_line_length": 126, "alphanum_fraction": 0.6099563767, "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5352407162131146}}
{"text": "#include <boost/random.hpp>\r\n#include <iostream>\r\n\r\nint main()\r\n{\r\n\tboost::mt19937 rng1(time(0));\r\n\tboost::random::random_number_generator<boost::mt19937, int> rand(rng1);\r\n\r\n\tfor (int i = 0; i < 7; ++i)\r\n\t{\r\n\t\tstd::cout << rand(30) << std::endl;\r\n\t}\r\n\r\n\tfor (int i = 0; i < 7; ++i)\r\n\t{\r\n\t\tstd::cout << rand(10) << std::endl;\r\n\t}\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "a5e486421fec86f566bfcc9af532eb1c08fe05a9", "size": 340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Boost_20140423/random_10/random_10.cpp", "max_stars_repo_name": "jacking75/book_semina_samples", "max_stars_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_stars_repo_licenses": ["MIT"], "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_20140423/random_10/random_10.cpp", "max_issues_repo_name": "jacking75/book_semina_samples", "max_issues_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_issues_repo_licenses": ["MIT"], "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_20140423/random_10/random_10.cpp", "max_forks_repo_name": "jacking75/book_semina_samples", "max_forks_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_forks_repo_licenses": ["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.4545454545, "max_line_length": 73, "alphanum_fraction": 0.5382352941, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5352407152454629}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <GL/glu.h>\n#include <GLFW/glfw3.h>\n#include <armadillo>\n#include <Class_Object.cpp>\n#include \"Transform.hpp\"\n\n\nvoid DibujaPlanetas(vector<Vertex> vl);\nvector <Vertex>  TranformaPlanetas(vector <Vertex> PlanetaVertices,arma::fmat transf);\n\nint main( void )\n{\n    arma::frowvec eye = {0.0, 0.0, 10.0};\n    arma::frowvec camera = {0.0, 0.0, 0.0};\n    \n    GLFWwindow* window;\n    \n       Object sol = Object();\n    sol.init(\"roca.obj\");\n\n    Object mercurio = Object();\n    mercurio.init(\"roca.obj\");\n\n    Object venus = Object();\n    venus.init(\"roca.obj\");\n\n    Object tierra = Object();\n    tierra.init(\"roca.obj\");\n\n    Object luna = Object();\n    luna.init(\"roca.obj\");\n\n    Object marte = Object();\n    marte.init(\"roca.obj\");\n\n    Object jupiter = Object();\n    jupiter.init(\"roca.obj\");\n\n    Object saturno = Object();\n    saturno.init(\"roca.obj\");\n\n    Object urano = Object();\n    urano.init(\"roca.obj\");\n\n    Object neptuno = Object();\n    neptuno.init(\"roca.obj\");\n\n    if( !glfwInit() )\n    {\n        fprintf( stderr, \"Fallo al inicializar GLFW\\n\" );\n        getchar();\n        return -1;\n    }\n\n    window = glfwCreateWindow(1024, 768, \"Sistema Solar\", NULL, NULL);\n    if( window == NULL ) {\n        fprintf( stderr, \"Fallo al abrir la ventana de GLFW.\\n\" );\n        getchar();\n        glfwTerminate();\n        return -1;\n    }\n    glfwMakeContextCurrent(window);\n    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);\n\n    glEnable(GL_DEPTH_TEST);\n    glDepthFunc(GL_LESS);\n\n    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n\n//  Proyecciones\n    glMatrixMode(GL_PROJECTION);\n    glLoadIdentity();\n\n    int width, height;\n    glfwGetFramebufferSize(window, &width, &height);\n\n    float ar = width / height;\n\n//  Proyecci\u00f3n en paralelo\n    glViewport(0, 0, width, height);\n    glOrtho(-ar, ar, -1.0, 1.0, -20.0, 20.0);\n\n//  Proyecci\u00f3n en perspectiva\n//    glFrustum(-ar, ar, -ar, ar, 2.0, 4.0);\n\n    glMatrixMode(GL_MODELVIEW);\n    glLoadIdentity();\n\n    Transform Tr = Transform();\n\tfloat m_angle = 0.0f;\n\tfloat v_angle = 40.0f;\n\tfloat t_angle = 80.0f;\n\tfloat l_angle = 120.0f;\n\tfloat mt_angle = 160.0f;\n\tfloat j_angle = 200.0f;\n\tfloat s_angle = 240.0f;\n\tfloat u_angle = 280.0f;\n\tfloat n_angle = 360.0f;\n\n    \n    do {\n        glClear( GL_COLOR_BUFFER_BIT  | GL_DEPTH_BUFFER_BIT );\n\n        glMatrixMode(GL_MODELVIEW);\n        glLoadIdentity();\n        gluLookAt(eye[0], eye[1], eye[2], \n                camera[0], camera[1], camera[2], \n                0.0, 1.0, 0.0);\n\n\n        // Dibujar el Sol\n        arma::fmat transf = Tr.S(0.3, 0.3, 0.3);\n        std::vector< Vertex > sol_vertices = TranformaPlanetas(sol.get_faces_verts(),transf); \n        glColor3f(1.0, 1.0, 0.0);\n        DibujaPlanetas(sol_vertices);\n        // Fin dibujado del Sol\n\t\n\t // Dibujar la Mercurio\n\tarma::fmat transf_mercurio = Tr.S(0.06, 0.06, 0.06);\n        m_angle = (t_angle < 360.0f) ? t_angle+1.0 : 0.0f;\n\n        transf_mercurio = Tr.R(0.0f, 1.0f, 0.0f, t_angle) * Tr.T(-0.20, 0.0, 0.0) * Tr.S(0.06, 0.06, 0.06) * transf;\n        \n        \n       std::vector< Vertex > Mercurio_vertices = TranformaPlanetas(venus.get_faces_verts(),transf_mercurio); \n        \n        glColor3f(1.0, 0.5, 0.0);\n      \t DibujaPlanetas(Mercurio_vertices);\n        // Fin dibujado de Mercurio \n\t \n\t// Dibujar la Venus\n\tarma::fmat transf_Venus = Tr.S(0.08, 0.08, 0.08);\n        v_angle = (t_angle < 360.0f) ? t_angle+1.6: 0.0f;\n\n        transf_Venus = Tr.R(0.0f, 1.0f, 0.0f, t_angle) * Tr.T(-0.30, 0.0, 0.0) * Tr.S(0.08, 0.08, 0.08) * transf;\n        \n       std::vector< Vertex > venus_vertices = TranformaPlanetas(venus.get_faces_verts(),transf_Venus); \n        \n        glColor3f(0.5, 0.5, 0.0);\n      \t DibujaPlanetas(venus_vertices);\n        // Fin dibujado de venus\n\n\t // Dibujar la Tierra\n\tarma::fmat transf_Tierra = Tr.S(0.1, 0.1, 0.1);\n        t_angle = (t_angle < 360.0f) ? t_angle+2.0 : 0.0f;\n\n        transf_Tierra = Tr.R(0.0f, 1.0f, 0.0f, t_angle) * Tr.T(-0.40, 0.0, 0.0) * Tr.S(0.1, 0.1, 0.1) * transf;\n        \n       std::vector< Vertex > tierra_vertices = TranformaPlanetas(tierra.get_faces_verts(),transf_Tierra); \n        \n        glColor3f(0.0, 0.0, 1.0);\n      \t DibujaPlanetas(tierra_vertices);\n\n        // Fin dibujado de la Tierra\n\n\t//Dibuja Luna\n\t    l_angle = (l_angle < 360.0f) ? l_angle + 12.8 : 0.0f;\n           arma::fmat transf_luna = transf_Tierra* Tr.R(0.0, 1.0, 0.0, l_angle) * Tr.T(-0.6, 0.0, 0.0) * Tr.S(0.2, 0.2, 0.2);\n\n        std::vector< Vertex >p_vertices = luna.get_faces_verts();\n        std::vector< Vertex > luna_vertices;\n        for (unsigned int i = 0; i < p_vertices.size(); i++) {\n            arma::fcolvec v = p_vertices[i].getHomg();\n            arma::fcolvec vp = transf_luna * v;\n            Vertex rv =Vertex();\n            rv.set_value2(arma::trans(vp));\n            luna_vertices.push_back(rv);\n        }\n\t\tglColor3f(1.0, 1.0, 1.0);\n        glBegin(GL_TRIANGLES);\n        for (unsigned int i = 0; i < luna_vertices.size(); i++) {\n            arma::frowvec vert = luna_vertices[i].get_value();\n            glVertex3f(vert[0], vert[1], vert[2]);\n        }\n        glEnd();\n\n\n\t//fin dibuja luna \n\n        // Dibujar la Marte\n\tarma::fmat transf_Marte = Tr.S(0.08, 0.08, 0.08);\n        mt_angle = (t_angle < 360.0f) ? t_angle+0.5: 0.0f;\n\n        transf_Marte = Tr.R(0.0f, 1.0f, 0.0f, t_angle) * Tr.T(-0.55, 0.0, 0.0) * Tr.S(0.08, 0.08, 0.08) * transf;\n        \n       std::vector< Vertex > marte_vertices = TranformaPlanetas(marte.get_faces_verts(),transf_Marte); \n        \n        glColor3f(1.0, 0.0, 0.0);\n      \t DibujaPlanetas(marte_vertices);\n        // Fin dibujado de la Marte\n\t\n\n\t // Dibujar la Jupiter\n\tarma::fmat transf_Jupiter = Tr.S(0.5, 0.5, 0.5);\n        j_angle = (t_angle < 360.0f) ? t_angle+0.082 : 0.0f;\n\n        transf_Jupiter = Tr.R(0.0f, 1.0f, 0.0f, t_angle) * Tr.T(-0.68, 0.0, 0.0) * Tr.S(0.5, 0.5, 0.5) * transf;\n        \n       std::vector< Vertex > jupiter_vertices = TranformaPlanetas(jupiter.get_faces_verts(),transf_Jupiter); \n        \n        glColor3f(1.0, 1.0, 0.5);\n      \t DibujaPlanetas(jupiter_vertices);\n        // Fin dibujado de la Jupiter\n\n\n\t // Dibujar la Saturno\n\tarma::fmat transf_Saturno = Tr.S(0.30, 0.30, 0.30);\n        s_angle = (t_angle < 360.0f) ? t_angle+0.0344 : 0.0f;\n\n        transf_Saturno = Tr.R(0.0f, 1.0f, 0.0f, t_angle) * Tr.T(-0.83, 0.0, 0.0) * Tr.S(0.35, 0.35, 0.35) * transf;\n        \n       std::vector< Vertex > Saturno_vertices = TranformaPlanetas(saturno.get_faces_verts(),transf_Saturno); \n        \n        glColor3f(0.2, 0.5, 0.2);\n      \t DibujaPlanetas(Saturno_vertices);\n        // Fin dibujado de la Saturno\n\n\n\n\t // Dibujar la Urano\n\tarma::fmat transf_Urano = Tr.S(0.16, 0.16, 0.16);\n        u_angle = (t_angle < 360.0f) ? t_angle+0.02 : 0.0f;\n\n        transf_Urano = Tr.R(0.0f, 1.0f, 0.0f, t_angle) * Tr.T(-0.90, 0.0, 0.0) * Tr.S(0.16, 0.16, 0.16) * transf;\n        \n       std::vector< Vertex > Urano_vertices = TranformaPlanetas(urano.get_faces_verts(),transf_Urano); \n        \n        glColor3f(1.0, 0.0, 0.5);\n      \t DibujaPlanetas(Urano_vertices);\n        // Fin dibujado de la urano\n\t\t\n\t // Dibujar la Neptuno\n\tarma::fmat transf_Neptuno = Tr.S(0.16, 0.16, 0.16);\n        n_angle = (t_angle < 360.0f) ? t_angle+0.01: 0.0f;\n\n        transf = Tr.R(0.0f, 1.0f, 0.0f, t_angle) * Tr.T(-0.95, 0.0, 0.0) * Tr.S(0.16, 0.16, 0.16) * transf;\n        \n       std::vector< Vertex > Neptuno_vertices = TranformaPlanetas(neptuno.get_faces_verts(),transf); \n        \n        glColor3f(0.0, 0.0, 0.8);\n      \t DibujaPlanetas(Neptuno_vertices);\n        // Fin dibujado de la Neptuno\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n        glfwSwapBuffers(window);\n        glfwPollEvents();\n\n    } while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&\n           glfwWindowShouldClose(window) == 0 );\n\n    glfwTerminate();\n\n    return 0;\n}\nvoid DibujaPlanetas(vector <Vertex> vl){\n   glBegin(GL_TRIANGLES);\n        for ( unsigned int i=0; i<vl.size(); i++ ) {\n            arma::frowvec vert = vl[i].get_value();\n            glVertex3f(vert[0], vert[1], vert[2]);\n        }\n        glEnd();\n\n}\n\n\tvector <Vertex> TranformaPlanetas(vector <Vertex> PlanetaVertices,arma::fmat transf){\n\n\n \tstd::vector< Vertex >planeta_vertices = PlanetaVertices;\n        std::vector< Vertex > planeta_vertices_trans; \n        for ( unsigned int i=0; i<planeta_vertices.size(); i++ ) {\n            arma::fcolvec v = planeta_vertices[i].getHomg();\n            arma::fcolvec vp = transf * v;\n            Vertex rv = Vertex();\n           //rv.set_value(vp[0],vp[1],vp[2]);\n\t\trv.set_value2(arma::trans(vp));\n            planeta_vertices_trans.push_back(rv);\n        }\n        \nreturn planeta_vertices_trans;\n}\n\n", "meta": {"hexsha": "079e7def2c2986061dcd757bda10623c15f669d0", "size": 8687, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ssolar (copy)/main.cpp", "max_stars_repo_name": "Pedejeca135/GRAFICACION_UASLP", "max_stars_repo_head_hexsha": "51674129cc3a853450509acc7e8c579bb167da11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ssolar (copy)/main.cpp", "max_issues_repo_name": "Pedejeca135/GRAFICACION_UASLP", "max_issues_repo_head_hexsha": "51674129cc3a853450509acc7e8c579bb167da11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ssolar (copy)/main.cpp", "max_forks_repo_name": "Pedejeca135/GRAFICACION_UASLP", "max_forks_repo_head_hexsha": "51674129cc3a853450509acc7e8c579bb167da11", "max_forks_repo_licenses": ["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.0535117057, "max_line_length": 125, "alphanum_fraction": 0.5825946817, "num_tokens": 3067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5352279481864087}}
{"text": "#pragma once\n#include \"mtao/types.hpp\"\n#include <Eigen/Sparse>\n\n\nnamespace mtao::geometry {\n    //A collection of simplicies, indices into simplices, and related barycentric coordinates\n    template <typename SimplexType, typename BType, typename SIType>\n        Eigen::SparseMatrix<typename BType::Scalar> \n        barycentric_matrix(int num_vertices, const Eigen::MatrixBase<SimplexType>& S, const Eigen::MatrixBase<SIType>& SI, const Eigen::MatrixBase<BType>& B) {\n            assert(SI.size() == B.cols());\n\n\n            using Scalar = typename BType::Scalar; \n            Eigen::SparseMatrix<Scalar> A(B.cols(), num_vertices);\n\n            std::vector<Eigen::Triplet<Scalar>> trips;\n            trips.reserve(S.rows()*SI.size());\n\n            for(int i = 0; i < B.cols(); ++i)\n            {\n                auto s = S.col(SI(i));\n                auto b = B.col(i);\n                for(int j = 0; j < b.rows(); ++j)\n                {\n                    trips.emplace_back(i,s(j),b(j));\n                }\n            }\n            A.setFromTriplets(trips.begin(),trips.end());\n            return A;\n        }\n    //A collection of simplicies, indices into simplices, and related barycentric coordinates\n    //piecewise constant per-face values\n    template <typename Scalar, typename SIType>\n        Eigen::SparseMatrix<Scalar> \n        barycentric_matrix_face(int num_faces, const Eigen::MatrixBase<SIType>& SI) {\n\n            Eigen::SparseMatrix<Scalar> A(SI.rows(), num_faces);\n\n            std::vector<Eigen::Triplet<Scalar>> trips;\n            trips.reserve(SI.size());\n\n            for(int i = 0; i < SI.cols(); ++i)\n            {\n                trips.emplace_back(i,SI(i),1);\n            }\n            A.setFromTriplets(trips.begin(),trips.end());\n            return A;\n        }\n}\n", "meta": {"hexsha": "584fe2ae3d2dbd55550d52f86740853577f8a1c5", "size": 1794, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/geometry/barycentric_matrix.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/geometry/barycentric_matrix.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/geometry/barycentric_matrix.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1764705882, "max_line_length": 159, "alphanum_fraction": 0.5602006689, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5352060785956381}}
{"text": "// third party includes\n#include <dlib/dnn.h>\n#include <dlib/global_optimization.h>\n#include <dlib/matrix.h>\n#include <dlib/svm.h>\n#include <dlib/svm_threaded.h>\n#include <plot.h>\n\n// stl includes\n#include <experimental/filesystem>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <regex>\n#include <streambuf>\n\n// application includes\n#include \"../ioutils.h\"\n#include \"../utils.h\"\n\n// Namespace and type aliases\nnamespace fs = std::experimental::filesystem;\nusing DType = double;  // DLib internally uses double - so in many cases it is\n                       // impossible to use float\nusing Matrix = dlib::matrix<DType>;\nusing DataSet = std::pair<std::vector<Matrix>, std::vector<DType>>;\n//  SVM types\nusing svm_kernel_type = dlib::radial_basis_kernel<Matrix>;\nusing svm_ova_trainer = dlib::one_vs_all_trainer<dlib::any_trainer<Matrix>>;\nusing svm_dec_funct_type = dlib::one_vs_all_decision_function<svm_ova_trainer>;\n// using svm_normalizer_type = dlib::vector_normalizer_pca<Matrix>;\nusing svm_normalizer_type = dlib::vector_normalizer<Matrix>;\nusing svm_funct_type =\n    dlib::normalized_function<svm_dec_funct_type, svm_normalizer_type>;\n\nstatic const std::string train_data_url =\n    \"https://raw.githubusercontent.com/pandas-dev/pandas/master/pandas/tests/\"\n    \"data/iris.csv\";\n\nDataSet LoadData() {\n  // ----------- Download the data\n  const std::string data_path{\"iris.csv\"};\n  if (!fs::exists(data_path)) {\n    if (!utils::DownloadFile(train_data_url, data_path)) {\n      std::cerr << \"Unable to download the file \" << train_data_url\n                << std::endl;\n      return {};\n    }\n  }\n  // ----------- Load data to string\n  std::ifstream data_file(data_path);\n  std::string train_data_str((std::istreambuf_iterator<char>(data_file)),\n                             std::istreambuf_iterator<char>());\n\n  // ----------- Remove first line - columns labels\n  train_data_str.erase(0, train_data_str.find_first_of(\"\\n\") + 1);\n\n  // ----------- Replace string labels with ints\n  train_data_str =\n      std::regex_replace(train_data_str, std::regex(\"Iris-setosa\"), \"0\");\n  train_data_str =\n      std::regex_replace(train_data_str, std::regex(\"Iris-versicolor\"), \"1\");\n  train_data_str =\n      std::regex_replace(train_data_str, std::regex(\"Iris-virginica\"), \"2\");\n\n  // ----------- Load data to matrix\n  Matrix train_data(150, 5);\n  std::stringstream ss(train_data_str);\n  ss >> train_data;\n  // ----------- Extract labels\n  Matrix labels = dlib::colm(train_data, 4);\n  // std::cout << dlib::csv << labels << std::endl;\n  // ----------- Extract and transpose samples\n  Matrix samples = dlib::subm_clipped(train_data, 0, 0, train_data.nr(),\n                                      train_data.nc() - 1);\n  // std::cout << dlib::csv << samples << std::endl;\n  // convert to matrices to vectors, because algorithms require such data types\n  DataSet ds;\n  for (long row = 0; row < samples.nr(); ++row) {\n    ds.first.push_back(dlib::reshape_to_column_vector(\n        dlib::subm_clipped(samples, row, 0, 1, samples.nc())));\n  }\n  ds.second.assign(labels.begin(), labels.end());\n  return ds;\n}\n\nsvm_funct_type TrainSVMClassifier(DataSet dataset) {\n  // based on http://dlib.net/model_selection_ex.cpp.html\n\n  auto& [samples, labels] = dataset;\n  // ----------- Pre-process data\n  // Here we normalize all the samples by subtracting their mean and\n  // dividing by their standard deviation.\n  svm_normalizer_type normalizer;\n  // Let the normalizer learn the mean and standard deviation of the samples\n  // normalizer.train(samples, 0.9); // configure how much dimensions will be\n  // left after PCA\n  normalizer.train(samples);\n  std::cout << \"Dimension of sample vector = \" << normalizer.out_vector_size()\n            << \" after PCA\" << std::endl;\n  // now normalize each sample\n  for (size_t i = 0; i < samples.size(); ++i) {\n    samples[i] = normalizer(samples[i]);\n  }\n\n  // ----------- Select best parameters for svm model\n\n  //  Here we define a function, that will do the cross-validation and return\n  //  a number indicating how good a particular setting of gamma, c1, and c2\n  //  is.\n  auto cross_validation_score = [&](const DType gamma, const DType c1,\n                                    const DType c2) {\n    // Make a RBF SVM trainer and tell it what the parameters are supposed to\n    // be.\n    dlib::svm_c_trainer<svm_kernel_type> svm_trainer;\n    svm_trainer.set_kernel(svm_kernel_type(gamma));\n    svm_trainer.set_c_class1(c1);\n    svm_trainer.set_c_class2(c2);\n\n    svm_ova_trainer trainer;\n    trainer.set_num_threads(4);\n    trainer.set_trainer(svm_trainer);\n\n    // Perform 10-fold cross validation and then print and return the\n    // results - confusion matrix.\n    Matrix result =\n        dlib::cross_validate_multiclass_trainer(trainer, samples, labels, 10);\n    auto accuracy = sum(diag(result)) / sum(result);\n    std::cout << \"gamma: \" << gamma << \"  c1: \" << c1 << \"  c2: \" << c2\n              << \"\\ncross validation accuracy: \" << accuracy\n              << \"\\nconfusion matrix:\\n\"\n              << dlib::csv << result << std::endl;\n\n    // Now return a number indicating how good the parameters are.  Bigger is\n    // better in this example.\n    return accuracy;\n  };\n\n  // Call this global optimizer that will search for the best\n  // parameters. It will call cross_validation_score() 50 times with different\n  // settings and return the best parameter setting it finds.\n  auto result = dlib::find_max_global(\n      cross_validation_score,\n      {1e-5, 1e-5,\n       1e-5},  // lower bound constraints on gamma, c1, and c2, respectively\n      {100, 1e6,\n       1e6},  // upper bound constraints on gamma, c1, and c2, respectively\n      dlib::max_function_calls(50));\n\n  double best_gamma = result.x(0);\n  double best_c1 = result.x(1);\n  double best_c2 = result.x(2);\n\n  std::cout << \" best cross-validation score: \" << result.y << std::endl;\n  std::cout << \" best gamma: \" << best_gamma << \"   best c1: \" << best_c1\n            << \"    best c2: \" << best_c2 << std::endl;\n\n  // ---------- Create final SVM model\n\n  dlib::svm_c_trainer<svm_kernel_type> svm_trainer;\n  svm_trainer.set_kernel(svm_kernel_type(best_gamma));\n  svm_trainer.set_c_class1(best_c1);\n  svm_trainer.set_c_class2(best_c2);\n  svm_ova_trainer trainer;\n  trainer.set_num_threads(4);\n  trainer.set_trainer(svm_trainer);\n\n  svm_funct_type learned_function;\n  learned_function.normalizer = normalizer;  // save normalization information\n  learned_function.function = trainer.train(\n      samples,\n      labels);  // perform the actual SVM training and save the results\n  return learned_function;\n}\n\nauto TrainNNClassifier(DataSet dataset) {\n  // based on http://dlib.net/dnn_introduction_ex.cpp.html\n  using namespace dlib;\n\n  auto& [samples, real_labels] = dataset;\n  std::vector<unsigned long> labels;\n  labels.assign(real_labels.begin(), real_labels.end());\n  // ----------- Pre-process data\n  // Here we normalize all the samples by subtracting their mean and\n  // dividing by their standard deviation.\n  vector_normalizer<Matrix> 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 (size_t i = 0; i < samples.size(); ++i) {\n    samples[i] = normalizer(samples[i]);\n  }\n\n  using net_type = loss_multiclass_log<\n      fc<3, relu<fc<10, relu<fc<5, input<matrix<DType>>>>>>>>;\n  net_type net;\n  dnn_trainer<net_type> trainer(net);\n  trainer.set_learning_rate(0.01);\n  trainer.set_min_learning_rate(0.00001);\n  trainer.set_mini_batch_size(8);\n  trainer.be_verbose();\n  trainer.train(samples, labels);\n  net.clean();\n  return std::make_pair(net, normalizer);\n}\n\n// ---------- Evaluate model on samples\ntemplate <typename Classfier>\nvoid TestSVMClassfier(const std::string& name,\n                      const Classfier& classifier,\n                      DataSet dataset) {\n  auto& [test_data, test_labels] = dataset;\n  DType matches_num = 0;\n  for (size_t i = 0; i < test_data.size(); ++i) {\n    auto predicted_class = classifier(test_data[i]);\n    auto true_class = test_labels[i];\n    if (predicted_class == true_class) {\n      ++matches_num;\n    }\n  }\n  std::cout << name << \" test accuracy = \" << matches_num / test_data.size()\n            << std::endl;\n}\n\ntemplate <typename Classfier>\nvoid TestNNClassfier(const std::string& name,\n                     Classfier& classifier,\n                     DataSet dataset) {\n  auto& [test_data, test_labels] = dataset;\n  for (auto& ts : test_data)\n    ts = classifier.second(ts);  // normalize\n\n  auto predicted_labels = classifier.first(test_data);\n  DType matches_num = 0;\n  for (size_t i = 0; i < test_data.size(); ++i) {\n    auto predicted_class = predicted_labels[i];\n    auto true_class = test_labels[i];\n    if (predicted_class == true_class) {\n      ++matches_num;\n    }\n  }\n  std::cout << name << \" test accuracy = \" << matches_num / test_data.size()\n            << std::endl;\n}\n\nint main(int, char* []) {\n  using namespace std::string_literals;\n  try {\n    auto [samples, labels] = LoadData();\n\n    // ----------- Pre-process data\n    // It have sense to compile DLib in debug mode with DLIB_ENABLE_ASSERTS\n    // CMake option enabled, to see inconvinience in data types\n\n    dlib::randomize_samples(samples, labels);\n\n    // exctract some samples as test data\n    std::vector<Matrix> test_data;\n    std::ptrdiff_t split_point = 135;\n    test_data.assign(samples.begin() + split_point, samples.end());\n    samples.erase(samples.begin() + split_point, samples.end());\n    std::vector<double> test_labels;\n    test_labels.assign(labels.begin() + split_point, labels.end());\n    labels.erase(labels.begin() + split_point, labels.end());\n\n    // ----------- SVM\n    auto svm_classifier = TrainSVMClassifier({samples, labels});\n    TestSVMClassfier(\"SVM\"s, svm_classifier, {test_data, test_labels});\n\n    // Decision trees and Random Forest algorithms are missed in DLib\n\n    // ----------- Neural Net\n    auto nn_classifier = TrainNNClassifier({samples, labels});\n    TestNNClassfier(\"NN\"s, nn_classifier, {test_data, test_labels});\n\n  } catch (const std::exception& err) {\n    std::cout << \"Program crashed : \" << err.what() << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "13bfade5ecc246da3957062b497587232b7c932c", "size": 10225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "classification_dlib/classify_dlib.cpp", "max_stars_repo_name": "yf225/mlcpp", "max_stars_repo_head_hexsha": "12d6f8224d7d6305a191c7afd2d5510e0a15299f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 268.0, "max_stars_repo_stars_event_min_datetime": "2018-04-11T15:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T08:18:03.000Z", "max_issues_repo_path": "classification_dlib/classify_dlib.cpp", "max_issues_repo_name": "soma2000-lang/mlcpp", "max_issues_repo_head_hexsha": "afb08c0c81bdd2c68710831e8d4b233005ab3750", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-02-10T22:19:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-23T05:55:50.000Z", "max_forks_repo_path": "classification_dlib/classify_dlib.cpp", "max_forks_repo_name": "soma2000-lang/mlcpp", "max_forks_repo_head_hexsha": "afb08c0c81bdd2c68710831e8d4b233005ab3750", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2018-04-19T21:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T17:11:00.000Z", "avg_line_length": 36.3879003559, "max_line_length": 79, "alphanum_fraction": 0.6639608802, "num_tokens": 2593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5352060612079133}}
{"text": "#include \"problem_generator.h\"\n\n#include \"macros.h\"\n\n#include <iostream>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nvector<problem::edge_descriptor> edge_order_by_occurrences(const vector<commodity>& commodities, const problem::graph_type& graph)\n{\n\tint V = num_vertices(graph);\n\tint K = commodities.size();\n\n\t// Occurences of each edge in the shortest path of each commodity\n\tmap<problem::edge_descriptor, int> occurrences;\n\n\tLOOP(k, K) {\n\t\t// Find the shortest path\n\t\tvector<int> parents(V);\n\t\tauto index_map = get(vertex_index, graph);\n\n\t\tboost::dijkstra_shortest_paths(graph, commodities[k].origin,\n\t\t\t\t\t\t\t\t\t   predecessor_map(make_iterator_property_map(parents.begin(), index_map)));\n\n\t\t// Count the occurences\n\t\tint current = commodities[k].destination;\n\t\twhile (current != commodities[k].origin) {\n\t\t\tint prev = parents[current];\n\t\t\tauto edge = boost::edge(prev, current, graph).first;\n\n\t\t\t++occurrences[edge];\n\n\t\t\tcurrent = prev;\n\t\t}\n\t}\n\n\t// Sort the edges\n\tauto edge_it = edges(graph);\n\tvector<problem::edge_descriptor> edge_order(edge_it.first, edge_it.second);\n\n\tsort(edge_order.begin(), edge_order.end(),\n\t\t [&](auto& a, auto& b) { return occurrences[a] < occurrences[b]; });\n\n\treturn edge_order;\n}\n\nvector<problem::edge_descriptor> edge_symmetric_order_by_occurrences(const vector<commodity>& commodities, const problem::graph_type& graph)\n{\n\tint V = num_vertices(graph);\n\tint K = commodities.size();\n\n\t// Occurences of each edge in the shortest path of each commodity\n\tmap<problem::edge_descriptor, int> occurrences;\n\n\tLOOP(k, K) {\n\t\t// Find the shortest path\n\t\tvector<int> parents(V);\n\t\tauto index_map = get(vertex_index, graph);\n\n\t\tboost::dijkstra_shortest_paths(graph, commodities[k].origin,\n\t\t\t\t\t\t\t\t\t   predecessor_map(make_iterator_property_map(parents.begin(), index_map)));\n\n\t\t// Count the occurences\n\t\tint current = commodities[k].destination;\n\t\twhile (current != commodities[k].origin) {\n\t\t\tint prev = parents[current];\n\t\t\tint a = min(prev, current);\n\t\t\tint b = max(prev, current);\n\t\t\tauto edge = boost::edge(a, b, graph).first;\n\n\t\t\t++occurrences[edge];\n\n\t\t\tcurrent = prev;\n\t\t}\n\t}\n\n\t// Sort the edges\n\tauto edge_it = edges(graph);\n\tvector<problem::edge_descriptor> edge_order(edge_it.first, edge_it.second);\n\n\t// Remove symmetric edges\n\tedge_order.erase(remove_if(edge_order.begin(), edge_order.end(),\n\t\t\t\t\t\t\t   [&](auto& e) {\n\t\t\t\t\t\t\t\t   return source(e, graph) > target(e, graph);\n\t\t\t\t\t\t\t   }),\n\t\t\t\t\t edge_order.end());\n\n\tsort(edge_order.begin(), edge_order.end(),\n\t\t [&](auto& a, auto& b) { return occurrences[a] < occurrences[b]; });\n\n\treturn edge_order;\n}\n\nbool is_removable(problem::graph_type& graph, problem::graph_type& toll_free_graph, problem::edge_descriptor& edge_desc, const vector<commodity>& commodities)\n{\n\tint src = source(edge_desc, graph);\n\tint dst = target(edge_desc, graph);\n\n\t// Try to remove edge and test for reachability\n\tremove_edge(src, dst, toll_free_graph);\n\n\tbool ok_to_remove = all_of(commodities.begin(), commodities.end(), [&toll_free_graph](const commodity& c) {\n\t\treturn is_reachable(c.origin, c.destination, toll_free_graph);\n\t\t\t\t\t\t\t   });\n\n\t// Otherwise, re-add the removed edge\n\tif (!ok_to_remove) {\n\t\tadd_edge(src, dst, toll_free_graph);\n\t}\n\n\treturn ok_to_remove;\n}\n\nbool is_symmetrically_removable(problem::graph_type& graph, problem::graph_type& toll_free_graph, problem::edge_descriptor& edge_desc, const vector<commodity>& commodities)\n{\n\tint src = source(edge_desc, graph);\n\tint dst = target(edge_desc, graph);\n\n\t// Try to remove edge and test for reachability\n\tremove_edge(src, dst, toll_free_graph);\n\tremove_edge(dst, src, toll_free_graph);\n\n\tbool ok_to_remove = all_of(commodities.begin(), commodities.end(), [&toll_free_graph](const commodity& c) {\n\t\treturn is_reachable(c.origin, c.destination, toll_free_graph);\n\t\t\t\t\t\t\t   });\n\n\t// Otherwise, re-add the removed edge\n\tif (!ok_to_remove) {\n\t\tadd_edge(src, dst, toll_free_graph);\n\t\tadd_edge(dst, src, toll_free_graph);\n\t}\n\n\treturn ok_to_remove;\n}\n\nboost::adjacency_list<> grid_graph(int width, int height) {\n\tusing graph_type = boost::adjacency_list<>;\n\n\tgraph_type graph(width * height);\n\n\tfor (int i = 0; i < height; ++i) {\n\t\tfor (int j = 0; j < width; ++j) {\n\t\t\t// Horizontal edges\n\t\t\tif (j + 1 < width) {\n\t\t\t\tboost::add_edge(i * width + j, i * width + j + 1, graph);\n\t\t\t\tboost::add_edge(i * width + j + 1, i * width + j, graph);\n\t\t\t}\n\t\t\t// Vertical edges\n\t\t\tif (i + 1 < height) {\n\t\t\t\tboost::add_edge(i * width + j, (i + 1) * width + j, graph);\n\t\t\t\tboost::add_edge((i + 1) * width + j, i * width + j, graph);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn graph;\n}\n\nbool pointSortPredicate(const Shx& a, const Shx& b)\n{\n\tif (a.r < b.r)\n\t\treturn true;\n\telse if (a.r > b.r)\n\t\treturn false;\n\telse if (a.c < b.c)\n\t\treturn true;\n\telse\n\t\treturn false;\n};\n", "meta": {"hexsha": "8525f84fbcc707d4fade209fbae666a4e81de653", "size": 4800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "netpricing/problem_generator.cpp", "max_stars_repo_name": "minhcly95/netpricing", "max_stars_repo_head_hexsha": "d2c88714b420ff21e99ebfa93ef6ae79adb438a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "netpricing/problem_generator.cpp", "max_issues_repo_name": "minhcly95/netpricing", "max_issues_repo_head_hexsha": "d2c88714b420ff21e99ebfa93ef6ae79adb438a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "netpricing/problem_generator.cpp", "max_forks_repo_name": "minhcly95/netpricing", "max_forks_repo_head_hexsha": "d2c88714b420ff21e99ebfa93ef6ae79adb438a0", "max_forks_repo_licenses": ["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.9069767442, "max_line_length": 172, "alphanum_fraction": 0.6908333333, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.535146096377502}}
{"text": "#include <iostream>\n\n#include <Eigen/Core>\n\n\nvoid printRandomMatrix() {\n    std::cout << Eigen::MatrixXd::Random(4, 4);\n}\n", "meta": {"hexsha": "8b9b30781ccdd7ae30d402c96e8905310911617c", "size": 122, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "checkpoint_3/src/functionality_eigen.cpp", "max_stars_repo_name": "OxfordRSE/IntroCMakeCourse", "max_stars_repo_head_hexsha": "3eba68b9955b194a9d432d066c6422ccb006402e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-18T16:08:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-18T16:08:40.000Z", "max_issues_repo_path": "checkpoint_3/src/functionality_eigen.cpp", "max_issues_repo_name": "OxfordRSE/IntroCMakeCourse", "max_issues_repo_head_hexsha": "3eba68b9955b194a9d432d066c6422ccb006402e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "checkpoint_3/src/functionality_eigen.cpp", "max_forks_repo_name": "OxfordRSE/IntroCMakeCourse", "max_forks_repo_head_hexsha": "3eba68b9955b194a9d432d066c6422ccb006402e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-24T14:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-24T14:53:27.000Z", "avg_line_length": 13.5555555556, "max_line_length": 47, "alphanum_fraction": 0.6557377049, "num_tokens": 32, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5351460777320537}}
{"text": "\n#include <string>\n#include <iostream>\n#include <memory>\n#include <vector>\n\n#include <boost/random.hpp>\n\n#include <Eigen/Dense>\n\n#include \"Kernel.h\"\n#include \"GaussianProcess.h\"\n#include \"SparseGaussianProcess.h\"\n\n#include \"Likelihood.h\"\n#include \"Prior.h\"\n#include \"SparseLikelihood.h\"\n\n#include \"GaussianProcessInference.h\"\n\n\n\n// setup sparse Gaussian process\ntypedef gpr::SparseGaussianProcess<double> SparseGaussianProcessType;\ntypedef gpr::GaussianProcess<double> GaussianProcessType;\ntypedef SparseGaussianProcessType::VectorType VectorType;\ntypedef SparseGaussianProcessType::MatrixType MatrixType;\ntypedef SparseGaussianProcessType::DiagMatrixType DiagMatrixType;\ntypedef SparseGaussianProcessType::VectorListType VectorListType;\n\ntypedef gpr::GaussianKernel<double>             GaussianKernelType;\ntypedef std::shared_ptr<GaussianKernelType>     GaussianKernelTypePointer;\n\n\n\n// test the efficient inversion resp. determinant\nvoid Test1(){\n    std::cout << \"Test 1.1 efficient inversion: ... \" << std::flush;\n\n    // generate a cool ground truth function\n    auto f = [](double x)->double { return (0.5*std::sin(x+10*x) + std::sin(4*x))*x*x; };\n    double noise = 0.1;\n    double jitter = 0.5;\n\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, noise);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n\n    // setup kernel\n    double sigma = 0.23;\n    double scale = 10;\n    GaussianKernelTypePointer gk(new GaussianKernelType(sigma, scale));\n\n    // setup sparse gaussian process\n    SparseGaussianProcessType::Pointer sgp(new SparseGaussianProcessType(gk));\n    //sgp->DebugOn();\n    sgp->SetSigma(noise);\n    sgp->SetJitter(jitter);\n\n\n    // large index set\n    unsigned n = 1000;\n    double start = -2;\n    double stop = 5;\n    VectorType Xn = VectorType::Zero(n);\n    for(unsigned i=0; i<n; i++){\n        Xn[i] = start + i*(stop-start)/n;\n    }\n    // fill up to sgp\n    std::vector<double> dense_y;\n    std::vector<double> sparse_y;\n    for(unsigned i=0; i<n; i++){\n        double v = f(Xn[i])+r();\n        dense_y.push_back(v);\n        sgp->AddSample(VectorType::Constant(1,Xn[i]), VectorType::Constant(1,v));\n    }\n\n    // small index set\n    unsigned m = 25;\n    VectorType Xm = VectorType::Zero(m);\n    for(unsigned i=0; i<m; i++){\n        Xm[i] = start + i*(stop-start)/m;\n    }\n    // fill up to sgp\n    for(unsigned i=0; i<m; i++){\n        double v = f(Xm[i])+r();\n        sparse_y.push_back(v);\n        sgp->AddInducingSample(VectorType::Constant(1,Xm[i]), VectorType::Constant(1,v));\n    }\n\n    // construct Gaussian log likelihood\n    typedef gpr::SparseGaussianLogLikelihood<double> SparseGaussianLogLikelihoodType;\n    typedef typename SparseGaussianLogLikelihoodType::Pointer SparseGaussianLogLikelihoodTypePointer;\n    SparseGaussianLogLikelihoodTypePointer sgl(new SparseGaussianLogLikelihoodType());\n\n    // get all the important matrices\n    MatrixType K;\n    MatrixType K_inv;\n    MatrixType Knm;\n    DiagMatrixType I_sigma;\n\n    sgl->GetCoreMatrices(sgp, K, K_inv, Knm, I_sigma);\n\n    //---------------------------------------------------------------------------\n    // inversion test\n    MatrixType D;\n    sgl->EfficientInversion(sgp, D, I_sigma, K_inv, K, Knm);\n\n    MatrixType T = (MatrixType(I_sigma)+Knm*K_inv*Knm.adjoint()).inverse();\n    double inv_error = (D-T).norm();\n\n    if(inv_error < 1e-7){\n        std::cout << \"[passed]\" << std::endl;\n    }\n    else{\n        std::stringstream ss; ss<<inv_error; throw ss.str();\n    }\n\n    std::cout << \"Test 1.2 efficient determinant: ... \" << std::flush;\n    //---------------------------------------------------------------------------\n    // determinant test\n    double determinant = sgl->EfficientDeterminant(I_sigma, K_inv, K, Knm);\n    double det_err = std::fabs(determinant-(MatrixType(I_sigma)+Knm*K_inv*Knm.adjoint()).determinant());\n\n    if(det_err < 1e-10){\n        std::cout << \"[passed]\" << std::endl;\n    }\n    else{\n        std::stringstream ss; ss<<det_err; throw ss.str();\n    }\n\n}\n\nvoid Test2(double jitter){\n    std::cout << \"Test 2.1 core matrix test (jitter=\" << jitter << \"): ... \" << std::flush;\n\n    // generate a cool ground truth function\n    auto f = [](double x)->double { return (0.5*std::sin(x+10*x) + std::sin(4*x))*x*x; };\n    double noise = 0.01;\n\n\n    // setup kernel\n    double sigma = 0.23;\n    double scale = 10;\n    GaussianKernelTypePointer gk(new GaussianKernelType(sigma, scale));\n\n    // setup sparse gaussian process\n    SparseGaussianProcessType::Pointer sgp(new SparseGaussianProcessType(gk));\n    //sgp->DebugOn();\n    sgp->SetSigma(noise);\n    sgp->SetJitter(jitter);\n\n\n    // large index set\n    unsigned n = 10;\n    double start = -2;\n    double stop = 5;\n    VectorType Xn = VectorType::Zero(n);\n    for(unsigned i=0; i<n; i++){\n        Xn[i] = start + i*(stop-start)/n;\n    }\n    // fill up to sgp\n    std::vector<double> dense_y;\n    std::vector<double> sparse_y;\n    for(unsigned i=0; i<n; i++){\n        double v = f(Xn[i]);\n        dense_y.push_back(v);\n        sgp->AddSample(VectorType::Constant(1,Xn[i]), VectorType::Constant(1,v));\n    }\n\n    // small index set\n    unsigned m = 10;\n    VectorType Xm = VectorType::Zero(m);\n    for(unsigned i=0; i<m; i++){\n        Xm[i] = start + i*(stop-start)/m;\n    }\n    // fill up to sgp\n    for(unsigned i=0; i<m; i++){\n        double v = f(Xm[i]);\n        sparse_y.push_back(v);\n        sgp->AddInducingSample(VectorType::Constant(1,Xm[i]), VectorType::Constant(1,v));\n    }\n\n    // construct Gaussian log likelihood\n    typedef gpr::SparseGaussianLogLikelihood<double> SparseGaussianLogLikelihoodType;\n    typedef typename SparseGaussianLogLikelihoodType::Pointer SparseGaussianLogLikelihoodTypePointer;\n    SparseGaussianLogLikelihoodTypePointer sgl(new SparseGaussianLogLikelihoodType());\n\n    // get all the important matrices\n    MatrixType K;\n    MatrixType K_inv;\n    MatrixType Kmn;\n    DiagMatrixType I_sigma;\n\n    sgl->GetCoreMatrices(sgp, K, K_inv, Kmn, I_sigma);\n\n\n    //---------------------------------------------------------------------------\n    // core matrix test\n    MatrixType C; //\n    sgl->GetCoreMatrix(sgp, C, K_inv, Kmn);\n\n    MatrixType M;\n    sgp->ComputeDenseKernelMatrix(M);\n\n    double err = (C-M).norm();\n\n    if((err < 1e-2 && jitter > 0) || (err < 2000 && jitter == 0)){\n        std::cout << \"[passed]\" << std::endl;\n    }\n    else{\n        std::stringstream ss; ss<<err; throw ss.str();\n    }\n\n\n    std::cout << \"Test 2.2 core matrix trace test (jitter=\" << jitter << \"): ... \" << std::flush;\n    if(M.trace() == sgl->GetKernelMatrixTrace(sgp)){\n        std::cout << \"[passed]\" << std::endl;\n    }\n    else{\n        throw std::string(\"error in calculating kernel matrix trace.\");\n    }\n}\n\nvoid Test3(){\n    std::cout << \"Test 3: sparse likelihood gradient test... \" << std::flush;\n\n    // generate a cool ground truth function\n    auto f = [](double x)->double { return (0.5*std::sin(x+10*x) + std::sin(4*x))*x*x; };\n    double noise = 0.2;\n    double jitter = 0.01;\n\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, noise);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n\n    double h = 0.0001;\n    bool passed = true;\n\n    for(unsigned iter=0; iter<10; iter++){\n\n        // setup kernel\n        double scale = 10;\n        double sigma = 0.1 + iter*0.02;\n\n\n        GaussianKernelTypePointer gk(new GaussianKernelType(sigma, scale));\n\n        // setup sparse gaussian process\n        SparseGaussianProcessType::Pointer sgp(new SparseGaussianProcessType(gk));\n        //sgp->DebugOn();\n        sgp->SetSigma(noise);\n        sgp->SetJitter(jitter);\n\n        // large index set\n        //unsigned n = 100;\n        unsigned n = 50 + iter;\n        double start = -2;\n        double stop = 5;\n        VectorType Xn = VectorType::Zero(n);\n        for(unsigned i=0; i<n; i++){\n            Xn[i] = start + i*(stop-start)/n;\n        }\n        // fill up to sgp\n        std::vector<double> dense_y;\n        std::vector<double> sparse_y;\n        for(unsigned i=0; i<n; i++){\n            double v = f(Xn[i])+r();\n            dense_y.push_back(v);\n            sgp->AddSample(VectorType::Constant(1,Xn[i]), VectorType::Constant(1,v));\n        }\n\n        // small index set\n        //unsigned m = 20;\n        unsigned m = 5 + iter;\n        VectorType Xm = VectorType::Zero(m);\n        for(unsigned i=0; i<m; i++){\n            Xm[i] = start + i*(stop-start)/m;\n        }\n        // fill up to sgp\n        for(unsigned i=0; i<m; i++){\n            double v = f(Xm[i])+r();\n            sparse_y.push_back(v);\n            sgp->AddInducingSample(VectorType::Constant(1,Xm[i]), VectorType::Constant(1,v));\n        }\n\n\n        // construct Gaussian log likelihood\n        typedef gpr::SparseGaussianLogLikelihood<double> SparseGaussianLogLikelihoodType;\n        typedef typename SparseGaussianLogLikelihoodType::Pointer SparseGaussianLogLikelihoodTypePointer;\n        SparseGaussianLogLikelihoodTypePointer sgl(new SparseGaussianLogLikelihoodType());\n\n        //sgl->DebugOn();\n\n\n        VectorType D = sgl->GetParameterDerivatives(sgp);\n\n        {\n            // central differences sigma\n            sgp->SetKernel(GaussianKernelTypePointer(new GaussianKernelType(sigma+h/2, scale)));\n            double plus = (*sgl)(sgp)[0];\n            sgp->SetKernel(GaussianKernelTypePointer(new GaussianKernelType(sigma-h/2, scale)));\n            double minus = (*sgl)(sgp)[0];\n\n            double d = (plus - minus)/h;\n\n            if(std::fabs(D[0] - d) > 1){\n                passed = false;\n                std::cout <<  \"central difference (sigma): \" << d << \", but is \" << D[0] <<   std::endl;\n            }\n        }\n        {\n            // central differences scale\n            sgp->SetKernel(GaussianKernelTypePointer(new GaussianKernelType(sigma, scale+h/2)));\n            double plus = (*sgl)(sgp)[0];\n            sgp->SetKernel(GaussianKernelTypePointer(new GaussianKernelType(sigma, scale-h/2)));\n            double minus = (*sgl)(sgp)[0];\n\n            double d = (plus - minus)/h;\n\n            if(std::fabs(D[1] - d) > 0.1){\n                passed = false;\n                std::cout <<  \"central difference (scale): \" << d << \", but is \" << D[1] <<   std::endl;\n            }\n        }\n    }\n\n    if(passed){\n        std::cout << \"[passed]\" << std::endl;\n    }\n    else{\n        throw std::string(\"errors in central differences calculation\");\n    }\n\n    return;\n}\n\n\nvoid Test4(){\n    //std::cout << \"Test 4: sparse maximum gaussian log likelihood with gradient descent test ...\" << std::flush;\n    std::cout.precision(8);\n\n    typedef gpr::GaussianExpKernel<double>           GaussianExpKernelType;\n    typedef GaussianExpKernelType::Pointer           GaussianExpKernelTypePointer;\n    typedef gpr::GaussianKernel<double>              GaussianKernelType;\n    typedef GaussianKernelType::Pointer              GaussianKernelTypePointer;\n    typedef gpr::SparseGaussianLogLikelihood<double>       LikelihoodType;\n    typedef LikelihoodType::Pointer                  LikelihoodTypePointer;\n    typedef gpr::GaussianProcessInference<double>    GaussianProcessInferenceType;\n    typedef GaussianProcessInferenceType::Pointer    GaussianProcessInferenceTypePointer;\n\n    typedef gpr::GaussianProcess<double> GaussianProcessType;\n    typedef GaussianProcessType::VectorType VectorType;\n    typedef GaussianProcessType::MatrixType MatrixType;\n    typedef GaussianProcessType::DiagMatrixType DiagMatrixType;\n    typedef GaussianProcessType::VectorListType VectorListType;\n\n    // global parameters\n    unsigned n = 300;\n    unsigned m = 50;\n    double noise = 0.1;\n\n    // construct training data\n    auto f = [](double x)->double { return (0.5*std::sin(x+10*x) + std::sin(4*x))*x*x; };\n\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, noise);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n    double start = -5;\n    double stop = 10;\n    VectorType Xn = VectorType::Zero(n);\n    VectorType Yn = VectorType::Zero(n);\n    for(unsigned i=0; i<n; i++){\n        Xn[i] = start + i*(stop-start)/n;\n        Yn[i] = f(Xn[i])+r();\n    }\n\n\n    GaussianExpKernelTypePointer gk(new GaussianExpKernelType(1, 1));\n    SparseGaussianProcessType::Pointer gp(new SparseGaussianProcessType(gk, 0.11));\n    //gp->DebugOn();\n    gp->SetSigma(noise);\n    for(unsigned i=0; i<n; i++){\n        gp->AddSample(VectorType::Constant(1,Xn[i]), VectorType::Constant(1,Yn[i]));\n    }\n\n    std::vector<unsigned> indices;\n    for(unsigned i=0; i<n; i++){\n        indices.push_back(i);\n    }\n    std::random_shuffle(indices.begin(), indices.end());\n\n    for(unsigned i=0; i<m; i++){\n        gp->AddInducingSample(VectorType::Constant(1,Xn[indices[i]]), VectorType::Constant(1,Yn[indices[i]]));\n    }\n\n    // setup likelihood\n    double step = 1e-1;\n    unsigned iterations = 100;\n\n    LikelihoodTypePointer lh(new LikelihoodType());\n    GaussianProcessInferenceTypePointer gpi(new GaussianProcessInferenceType(lh, gp, step, iterations));\n\n    bool exp_output = true;\n    gpi->Optimize(true, exp_output);\n\n\n    std::cout << \"print \\\"Parameters are: \";\n    GaussianProcessInferenceType::ParameterVectorType parameters = gpi->GetParameters();\n    for(unsigned i=0; i<parameters.size(); i++){\n        parameters[i] = std::exp(parameters[i]);\n        std::cout << parameters[i] << \", \";\n    }\n    std::cout << \"\\\"\" << std::endl;\n\n\n    GaussianKernelTypePointer k(new GaussianKernelType(1,1));\n    k->SetParameters(parameters);\n    gp->SetKernel(k);\n\n\n    // evaluate error\n    double error = 0;\n    unsigned gt_n = 1000;\n    for(unsigned i=0; i<gt_n; i++){\n        double x = start + i*(stop-start)/gt_n;\n        double p = gp->Predict(VectorType::Constant(1,x))[0];\n        error += std::fabs(p-f(x));\n    }\n\n\n//    if(error/gt_n > 2){\n//        std::cout << \"[failed] with an avg error of \" << error/gt_n << std::endl;\n//    }\n//    else{\n//        std::cout << \"[passed]\" << std::endl;\n//    }\nreturn;\n\n    std::cout << \"import numpy as np\" << std::endl;\n    std::cout << \"import pylab as plt\" << std::endl;\n\n    std::cout << \"x = np.array([\" << std::endl;\n    for(unsigned i=0; i<gt_n; i++){\n        std::cout << start + i*(stop-start)/gt_n << \", \";\n    }\n    std::cout << \"])\" << std::endl;\n\n    std::cout << \"y = np.array([\" << std::endl;\n    for(unsigned i=0; i<gt_n; i++){\n        std::cout << f(start + i*(stop-start)/gt_n) << \", \";\n    }\n    std::cout << \"])\" << std::endl;\n    std::cout << \"plt.plot(x,y)\" << std::endl;\n\n    std::cout << \"xp = np.array([\" << std::endl;\n    for(unsigned i=0; i<m; i++){\n        std::cout << Xn[indices[i]] << \", \";\n    }\n    std::cout << \"])\" << std::endl;\n\n    std::cout << \"yp = np.array([\" << std::endl;\n    for(unsigned i=0; i<m; i++){\n        std::cout << Yn[indices[i]] << \", \";\n    }\n    std::cout << \"])\" << std::endl;\n    std::cout << \"plt.plot(xp,yp, '.k')\" << std::endl;\n\n    std::cout << \"Y = np.array([\" << std::endl;\n    for(unsigned i=0; i<gt_n; i++){\n        std::cout << gp->Predict(VectorType::Constant(1,(start + i*(stop-start)/gt_n)))[0] << \", \";\n    }\n    std::cout << \"])\" << std::endl;\n    std::cout << \"plt.plot(x,Y, '-r')\" << std::endl;\n\n\n    std::cout << \"plt.show()\" << std::endl;\n}\n\nint main (int argc, char *argv[]){\n    //std::cout << \"Sparse Gaussian Process test: \" << std::endl;\n    try{\n//        Test1();\n//        Test2(0); // jitter 0\n//        Test2(0.001); // jitter 0.001\n//        Test3();\n        Test4();\n    }\n    catch(std::string& s){\n        std::cout << \"[failed] Error: \" << s << std::endl;\n        return -1;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "2cccf3194010fa3aa2b477b6fc1d876c4a51f46a", "size": 15863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/SparseInferenceTest.cpp", "max_stars_repo_name": "ChristophJud/GPR", "max_stars_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-20T14:30:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T21:44:06.000Z", "max_issues_repo_path": "tests/SparseInferenceTest.cpp", "max_issues_repo_name": "ChristophJud/GPR", "max_issues_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "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/SparseInferenceTest.cpp", "max_forks_repo_name": "ChristophJud/GPR", "max_forks_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-11-16T00:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T02:00:18.000Z", "avg_line_length": 31.7895791583, "max_line_length": 113, "alphanum_fraction": 0.5958519826, "num_tokens": 4298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5351057299148726}}
{"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 <cmath>\n#include <cfloat>\n#include <cstdint>\n#include <limits>\n#include <type_traits>\n#include <boost/math/ccmath/hypot.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n#include <boost/math/ccmath/sqrt.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\n#if !defined(BOOST_MATH_NO_CONSTEXPR_DETECTION) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\ntemplate <typename T>\nconstexpr void test()\n{\n    // Error Handling\n    if constexpr (std::numeric_limits<T>::has_quiet_NaN)\n    {\n        static_assert(boost::math::ccmath::isnan(boost::math::ccmath::hypot(std::numeric_limits<T>::quiet_NaN(), T(1))), \"If x is NaN, NaN is returned\");\n        static_assert(boost::math::ccmath::isnan(boost::math::ccmath::hypot(T(1), std::numeric_limits<T>::quiet_NaN())), \"If y is NaN, NaN is returned\");\n    }\n\n    static_assert(boost::math::ccmath::isinf(boost::math::ccmath::hypot(std::numeric_limits<T>::infinity(), T(1))));\n    static_assert(boost::math::ccmath::isinf(boost::math::ccmath::hypot(-std::numeric_limits<T>::infinity(), T(1))));\n    static_assert(boost::math::ccmath::isinf(boost::math::ccmath::hypot(T(1), std::numeric_limits<T>::infinity())));\n    static_assert(boost::math::ccmath::isinf(boost::math::ccmath::hypot(T(1), -std::numeric_limits<T>::infinity())));\n\n    // Correct promoted types\n    if constexpr (!std::is_same_v<T, float>)\n    {\n        constexpr auto test_type = boost::math::ccmath::hypot(T(1), 1.0f);\n        static_assert(std::is_same_v<T, std::remove_cv_t<decltype(test_type)>>);\n    }\n    else\n    {\n        constexpr auto test_type = boost::math::ccmath::hypot(1.0f, 1);\n        static_assert(std::is_same_v<double, std::remove_cv_t<decltype(test_type)>>);\n    }\n\n    // Functionality\n    static_assert(boost::math::ccmath::hypot(T(1), T(1)) == boost::math::ccmath::sqrt(T(2)));\n    static_assert(boost::math::ccmath::hypot(T(-1), T(1)) == boost::math::ccmath::sqrt(T(2)));\n    static_assert(boost::math::ccmath::hypot(T(-1), T(-1)) == boost::math::ccmath::sqrt(T(2)));\n    static_assert(boost::math::ccmath::hypot(T(1), T(-1)) == boost::math::ccmath::sqrt(T(2)));\n    static_assert(boost::math::ccmath::hypot(T(1), T(2)) == boost::math::ccmath::sqrt(T(5)));\n    static_assert(boost::math::ccmath::hypot(T(2), T(2)) == boost::math::ccmath::sqrt(T(8)));\n}\n\nint main()\n{\n    test<float>();\n    test<double>();\n\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test<long double>();\n    #endif\n    \n    #ifdef BOOST_HAS_FLOAT128\n    test<boost::multiprecision::float128>();\n    #endif\n\n    return 0;\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "bc85b65962f4156b7cd4b31cfe258d4b384c714b", "size": 2880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ccmath_hypot_test.cpp", "max_stars_repo_name": "twLQCD/math", "max_stars_repo_head_hexsha": "4e74c1251ec4ead2ab0e953d5e59b2de96a439ef", "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/ccmath_hypot_test.cpp", "max_issues_repo_name": "twLQCD/math", "max_issues_repo_head_hexsha": "4e74c1251ec4ead2ab0e953d5e59b2de96a439ef", "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/ccmath_hypot_test.cpp", "max_forks_repo_name": "twLQCD/math", "max_forks_repo_head_hexsha": "4e74c1251ec4ead2ab0e953d5e59b2de96a439ef", "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": 36.9230769231, "max_line_length": 153, "alphanum_fraction": 0.6708333333, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.535105718724886}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2014, 2016, 2017.\n// Modifications copyright (c) 2014-2017 Oracle and/or its affiliates.\n\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#ifndef BOOST_GEOMETRY_FORMULAS_VINCENTY_DIRECT_HPP\n#define BOOST_GEOMETRY_FORMULAS_VINCENTY_DIRECT_HPP\n\n\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/geometry/core/radius.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/formulas/differential_quantities.hpp>\n#include <boost/geometry/formulas/flattening.hpp>\n#include <boost/geometry/formulas/result_direct.hpp>\n\n\n#ifndef BOOST_GEOMETRY_DETAIL_VINCENTY_MAX_STEPS\n#define BOOST_GEOMETRY_DETAIL_VINCENTY_MAX_STEPS 1000\n#endif\n\n\nnamespace boost { namespace geometry { namespace formula\n{\n\n/*!\n\\brief The solution of the direct problem of geodesics on latlong coordinates, after Vincenty, 1975\n\\author See\n    - http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf\n    - http://www.icsm.gov.au/gda/gdav2.3.pdf\n\\author Adapted from various implementations to get it close to the original document\n    - http://www.movable-type.co.uk/scripts/LatLongVincenty.html\n    - http://exogen.case.edu/projects/geopy/source/geopy.distance.html\n    - http://futureboy.homeip.net/fsp/colorize.fsp?fileName=navigation.frink\n\n*/\ntemplate <\n    typename CT,\n    bool EnableCoordinates = true,\n    bool EnableReverseAzimuth = false,\n    bool EnableReducedLength = false,\n    bool EnableGeodesicScale = false\n>\nclass vincenty_direct\n{\n    static const bool CalcQuantities = EnableReducedLength || EnableGeodesicScale;\n    static const bool CalcCoordinates = EnableCoordinates || CalcQuantities;\n    static const bool CalcRevAzimuth = EnableReverseAzimuth || CalcQuantities;\n\npublic:\n    typedef result_direct<CT> result_type;\n\n    template <typename T, typename Dist, typename Azi, typename Spheroid>\n    static inline result_type apply(T const& lo1,\n                                    T const& la1,\n                                    Dist const& distance,\n                                    Azi const& azimuth12,\n                                    Spheroid const& spheroid)\n    {\n        result_type result;\n\n        CT const lon1 = lo1;\n        CT const lat1 = la1;\n\n        if ( math::equals(distance, Dist(0)) || distance < Dist(0) )\n        {\n            result.lon2 = lon1;\n            result.lat2 = lat1;\n            return result;\n        }\n\n        CT const radius_a = CT(get_radius<0>(spheroid));\n        CT const radius_b = CT(get_radius<2>(spheroid));\n        CT const flattening = formula::flattening<CT>(spheroid);\n\n        CT const sin_azimuth12 = sin(azimuth12);\n        CT const cos_azimuth12 = cos(azimuth12);\n\n        // U: reduced latitude, defined by tan U = (1-f) tan phi\n        CT const one_min_f = CT(1) - flattening;\n        CT const tan_U1 = one_min_f * tan(lat1);\n        CT const sigma1 = atan2(tan_U1, cos_azimuth12); // (1)\n\n        // may be calculated from tan using 1 sqrt()\n        CT const U1 = atan(tan_U1);\n        CT const sin_U1 = sin(U1);\n        CT const cos_U1 = cos(U1);\n\n        CT const sin_alpha = cos_U1 * sin_azimuth12; // (2)\n        CT const sin_alpha_sqr = math::sqr(sin_alpha);\n        CT const cos_alpha_sqr = CT(1) - sin_alpha_sqr;\n\n        CT const b_sqr = radius_b * radius_b;\n        CT const u_sqr = cos_alpha_sqr * (radius_a * radius_a - b_sqr) / b_sqr;\n        CT const A = CT(1) + (u_sqr/CT(16384)) * (CT(4096) + u_sqr*(CT(-768) + u_sqr*(CT(320) - u_sqr*CT(175)))); // (3)\n        CT const B = (u_sqr/CT(1024))*(CT(256) + u_sqr*(CT(-128) + u_sqr*(CT(74) - u_sqr*CT(47)))); // (4)\n\n        CT s_div_bA = distance / (radius_b * A);\n        CT sigma = s_div_bA; // (7)\n\n        CT previous_sigma;\n        CT sin_sigma;\n        CT cos_sigma;\n        CT cos_2sigma_m;\n        CT cos_2sigma_m_sqr;\n\n        int counter = 0; // robustness\n\n        do\n        {\n            previous_sigma = sigma;\n\n            CT const two_sigma_m = CT(2) * sigma1 + sigma; // (5)\n\n            sin_sigma = sin(sigma);\n            cos_sigma = cos(sigma);\n            CT const sin_sigma_sqr = math::sqr(sin_sigma);\n            cos_2sigma_m = cos(two_sigma_m);\n            cos_2sigma_m_sqr = math::sqr(cos_2sigma_m);\n\n            CT const delta_sigma = B * sin_sigma * (cos_2sigma_m\n                                        + (B/CT(4)) * ( cos_sigma * (CT(-1) + CT(2)*cos_2sigma_m_sqr)\n                                            - (B/CT(6) * cos_2sigma_m * (CT(-3)+CT(4)*sin_sigma_sqr) * (CT(-3)+CT(4)*cos_2sigma_m_sqr)) )); // (6)\n\n            sigma = s_div_bA + delta_sigma; // (7)\n\n            ++counter; // robustness\n\n        } while ( geometry::math::abs(previous_sigma - sigma) > CT(1e-12)\n               //&& geometry::math::abs(sigma) < pi\n               && counter < BOOST_GEOMETRY_DETAIL_VINCENTY_MAX_STEPS ); // robustness\n\n        if (BOOST_GEOMETRY_CONDITION(CalcCoordinates))\n        {\n            result.lat2\n                = atan2( sin_U1 * cos_sigma + cos_U1 * sin_sigma * cos_azimuth12,\n                         one_min_f * math::sqrt(sin_alpha_sqr + math::sqr(sin_U1 * sin_sigma - cos_U1 * cos_sigma * cos_azimuth12))); // (8)\n\n            CT const lambda = atan2( sin_sigma * sin_azimuth12,\n                                     cos_U1 * cos_sigma - sin_U1 * sin_sigma * cos_azimuth12); // (9)\n            CT const C = (flattening/CT(16)) * cos_alpha_sqr * ( CT(4) + flattening * ( CT(4) - CT(3) * cos_alpha_sqr ) ); // (10)\n            CT const L = lambda - (CT(1) - C) * flattening * sin_alpha\n                            * ( sigma + C * sin_sigma * ( cos_2sigma_m + C * cos_sigma * ( CT(-1) + CT(2) * cos_2sigma_m_sqr ) ) ); // (11)\n\n            result.lon2 = lon1 + L;\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(CalcRevAzimuth))\n        {\n            result.reverse_azimuth\n                = atan2(sin_alpha, -sin_U1 * sin_sigma + cos_U1 * cos_sigma * cos_azimuth12); // (12)\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(CalcQuantities))\n        {\n            typedef differential_quantities<CT, EnableReducedLength, EnableGeodesicScale, 2> quantities;\n            quantities::apply(lon1, lat1, result.lon2, result.lat2,\n                              azimuth12, result.reverse_azimuth,\n                              radius_b, flattening,\n                              result.reduced_length, result.geodesic_scale);\n        }\n\n        return result;\n    }\n\n};\n\n}}} // namespace boost::geometry::formula\n\n\n#endif // BOOST_GEOMETRY_FORMULAS_VINCENTY_DIRECT_HPP\n", "meta": {"hexsha": "8b20a8734e1038c2b8b74d89e3e089f24ab465fb", "size": 6815, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/formulas/vincenty_direct.hpp", "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/boost/geometry/formulas/vincenty_direct.hpp", "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/boost/geometry/formulas/vincenty_direct.hpp", "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": 37.0380434783, "max_line_length": 146, "alphanum_fraction": 0.6093910492, "num_tokens": 1823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.5351057127040965}}
{"text": "//\n// Copyright 2013 Christian Henning\n// Copyright 2013 Davide Anastasia <davideanastasia@users.sourceforge.net>\n// Copyright 2020 Mateusz Loskot <mateusz at loskot dot net>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#include <boost/gil.hpp>\n#include <boost/gil/extension/toolbox/color_spaces/lab.hpp>\n\n#include <boost/core/lightweight_test.hpp>\n\n#include <cmath>\n\nnamespace gil = boost::gil;\n\n// FIXME: Remove when https://github.com/boostorg/core/issues/38 happens\n#define BOOST_GIL_TEST_IS_CLOSE(a, b) BOOST_TEST_LT(std::fabs((a) - (b)), (0.0005f))\n\nvoid test_lab_to_xyz()\n{\n    {\n        gil::lab32f_pixel_t lab_pixel(40.366198f, 53.354489f, 26.117702f);\n        gil::xyz32f_pixel_t xyz_pixel;\n        gil::color_convert(lab_pixel, xyz_pixel);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(xyz_pixel[0]), 0.197823f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(xyz_pixel[1]), 0.114731f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(xyz_pixel[2]), 0.048848f);\n    }\n    {\n        gil::lab32f_pixel_t lab_pixel(50, 0, 0);\n        gil::xyz32f_pixel_t xyz_pixel;\n        gil::color_convert(lab_pixel, xyz_pixel);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(xyz_pixel[0]), 0.175064f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(xyz_pixel[1]), 0.184187f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(xyz_pixel[2]), 0.200548f);\n    }\n}\n\nvoid test_xyz_to_lab()\n{\n    gil::lab32f_pixel_t lab_pixel;\n    gil::xyz32f_pixel_t xyz_pixel(0.085703f, 0.064716f, 0.147082f);\n    gil::color_convert(xyz_pixel, lab_pixel);\n    BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[0]), 30.572438f);\n    BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[1]), 23.4674f);\n    BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[2]), -22.322275f);\n}\n\nvoid test_rgb_to_lab()\n{\n    {\n        gil::rgb32f_pixel_t rgb_pixel(0.75f, 0.5f, 0.25f);\n        gil::lab32f_pixel_t lab_pixel;\n        gil::color_convert(rgb_pixel, lab_pixel);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[0]), 58.7767f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[1]), 18.5851f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[2]), 43.7975f);\n    }\n    {\n        gil::rgb32f_pixel_t rgb_pixel(1.f, 0.f, 0.f);\n        gil::lab32f_pixel_t lab_pixel;\n        gil::color_convert(rgb_pixel, lab_pixel);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[0]), 53.2408f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[1]), 80.0925f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[2]), 67.2032f);\n    }\n    {\n        gil::rgb32f_pixel_t rgb_pixel(0.f, 1.f, 0.f);\n        gil::lab32f_pixel_t lab_pixel;\n        gil::color_convert(rgb_pixel, lab_pixel);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[0]), 87.7347f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[1]), -86.1827f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[2]), 83.1793f);\n    }\n    {\n        gil::rgb32f_pixel_t rgb_pixel(0.f, 0.f, 1.f);\n        gil::lab32f_pixel_t lab_pixel;\n        gil::color_convert(rgb_pixel, lab_pixel);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[0]), 32.2970f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[1]), 79.1875f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[2]), -107.8602f);\n    }\n    {\n        gil::rgb32f_pixel_t rgb_pixel(1.f, 1.f, 1.f);\n        gil::lab32f_pixel_t lab_pixel;\n        gil::color_convert(rgb_pixel, lab_pixel);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[0]), 100.f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[1]), 0.f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(lab_pixel[2]), 0.f);\n    }\n}\n\nvoid test_lab_to_rgb()\n{\n    {\n        gil::lab32f_pixel_t lab_pixel(75.f, 20.f, 40.f);\n        gil::rgb32f_pixel_t rgb_pixel;\n        gil::color_convert(lab_pixel, rgb_pixel);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(rgb_pixel[0]), 0.943240f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(rgb_pixel[1]), 0.663990f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(rgb_pixel[2]), 0.437893f);\n    }\n    {\n        gil::lab32f_pixel_t lab_pixel(100.f, 0.f, 0.f);\n        gil::rgb32f_pixel_t rgb_pixel;\n        gil::color_convert(lab_pixel, rgb_pixel);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(rgb_pixel[0]), 1.f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(rgb_pixel[1]), 1.f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(rgb_pixel[2]), 1.f);\n    }\n    {\n        gil::lab32f_pixel_t lab_pixel(56.8140f, -42.3665f, 10.6728f);\n        gil::rgb32f_pixel_t rgb_pixel;\n        gil::color_convert(lab_pixel, rgb_pixel);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(rgb_pixel[0]), 0.099999f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(rgb_pixel[1]), 0.605568f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(rgb_pixel[2]), 0.456662f);\n    }\n    {\n        gil::lab32f_pixel_t lab_pixel(50.5874f, 4.0347f, 50.5456f);\n        gil::rgb32f_pixel_t rgb_pixel;\n        gil::color_convert(lab_pixel, rgb_pixel);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(rgb_pixel[0]), 0.582705f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(rgb_pixel[1]), 0.454891f);\n        BOOST_GIL_TEST_IS_CLOSE(static_cast<float>(rgb_pixel[2]), 0.1f);\n    }\n}\n\nint main()\n{\n    test_lab_to_xyz();\n    test_xyz_to_lab();\n    test_rgb_to_lab();\n    test_lab_to_rgb();\n\n    return ::boost::report_errors();\n}\n", "meta": {"hexsha": "0bd2f31dcb60bb415b77b36c202acbc087fa5e51", "size": 5587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/gil/test/extension/toolbox/color_convert_lab.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.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": "3rdparty/boost_1_73_0/libs/gil/test/extension/toolbox/color_convert_lab.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "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": "3rdparty/boost_1_73_0/libs/gil/test/extension/toolbox/color_convert_lab.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "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": 39.6241134752, "max_line_length": 84, "alphanum_fraction": 0.6899946304, "num_tokens": 1717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5350357098471963}}
{"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/Ray.h>\n#include <shared/Output.h>\n#include <shared/Position.h>\n#include <shared/Scaling.h>\n\nBOOST_AUTO_TEST_SUITE(rays_suite)\n\n    BOOST_AUTO_TEST_CASE(creating_and_querying_a_ray_test) {\n        auto origin = Point(1, 2, 3);\n        auto direction = Vector(4,5,6);\n\n        auto ray = Ray(origin, direction);\n\n        BOOST_CHECK_EQUAL(ray.origin, origin);\n        BOOST_CHECK_EQUAL(ray.direction, direction);\n\n    }\n\n    BOOST_AUTO_TEST_CASE(computing_a_point_from_a_distance_test) {\n\n        auto r = Ray(Point(2, 3,4), Vector(1,0,0));\n\n\n        BOOST_CHECK_EQUAL(Position(r,0),Point(2,3,4));\n        BOOST_CHECK_EQUAL(Position(r,1),Point(3,3,4));\n        BOOST_CHECK_EQUAL(Position(r,-1),Point(1,3,4));\n        BOOST_CHECK_EQUAL(Position(r,2.5),Point(4.5,3,4));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(translating_a_ray_test) {\n\n        auto ray = Ray(Point(1,2,3), Vector(0,1,0));\n        auto m = Translation(3,4,5);\n\n        auto r2 = ray.transform(m);\n\n        BOOST_CHECK_EQUAL(r2.origin, Point(4,6,8));\n        BOOST_CHECK_EQUAL(r2.direction, Vector(0,1,0));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(scaling_a_ray_test) {\n\n        auto ray = Ray(Point(1,2,3), Vector(0,1,0));\n        auto m = Scaling(2,3,4);\n\n        auto r2 = ray.transform(m);\n\n        BOOST_CHECK_EQUAL(r2.origin, Point(2,6,12));\n        BOOST_CHECK_EQUAL(r2.direction, Vector(0,3,0));\n\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "e8ec9836ed419c39d25bc75e433da07d18eb8c31", "size": 1565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_rays.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_rays.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_rays.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.2419354839, "max_line_length": 66, "alphanum_fraction": 0.654313099, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5350356998319319}}
{"text": "/*\n * Copyright 2015 Christoph Jud (christoph.jud@unibas.ch)\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 <iostream>\n#include <memory>\n#include <ctime>\n#include <cmath>\n\n#include <boost/random.hpp>\n\n#include \"GaussianProcess.h\"\n#include \"Kernel.h\"\n#include \"MatrixIO.h\"\n\nusing namespace gpr;\n\ntypedef RationalQuadraticKernel<double> RationalQuadraticKernelType;\ntypedef std::shared_ptr<RationalQuadraticKernelType> RationalQuadraticKernelTypePointer;\ntypedef GaussianKernel<double> GaussianKernelType;\ntypedef std::shared_ptr<GaussianKernelType> GaussianKernelTypePointer;\ntypedef GaussianProcess<double> GaussianProcessType;\ntypedef std::shared_ptr<GaussianProcessType> GaussianProcessTypePointer;\n\ntypedef GaussianProcessType::VectorType VectorType;\ntypedef GaussianProcessType::MatrixType MatrixType;\n\n\nvoid Test1(){\n    /*\n     * Test 1: regression test 1D\n     */\n    std::cout << \"Test 1: equal to gaussian kernel with large alpha test...\" << std::flush;\n\n    // ground truth periodic variable\n    auto f = [](double x)->double { return 0.5*x*std::sin(x)+std::sin(4*x); };\n\n    double interval_start = -10;\n    double interval_end = 10; // full interval\n    double interval_step = 0.1;\n\n    //--------------------------------------------------------------------------------\n    // generating ground truth\n    unsigned gt_size = (interval_end-interval_start) / interval_step;\n    VectorType y(gt_size);\n    for(unsigned i=0; i<gt_size; i++){\n        y[i] = f(interval_start + i*interval_step);\n    }\n\n    //--------------------------------------------------------------------------------\n    // perform training\n    double noise = std::sqrt(0.01);\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, noise);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n    double interval_training_end = 5; // interval to train\n    unsigned number_of_samples = 50;\n\n    // kernels\n    RationalQuadraticKernelTypePointer rq(new RationalQuadraticKernelType(4, 1, 1e10)); // scale, period, smoothness\n    GaussianKernelTypePointer gk(new GaussianKernelType(1,4));\n\n    // gps\n    GaussianProcessTypePointer rq_gp(new GaussianProcessType(rq));\n    rq_gp->SetSigma(noise); // noise\n    GaussianProcessTypePointer gk_gp(new GaussianProcessType(gk));\n    gk_gp->SetSigma(noise); // noise\n\n    // add samples\n    double training_step_size = (interval_training_end - interval_start) / number_of_samples;\n    for(unsigned i=0; i<number_of_samples; i++){\n        VectorType x(1);\n        x(0) = interval_start + i*training_step_size;\n\n        VectorType y(1);\n        y(0) = f(x(0)) + r();\n\n        rq_gp->AddSample(x, y);\n        gk_gp->AddSample(x, y);\n    }\n    rq_gp->Initialize();\n    gk_gp->Initialize();\n\n    //--------------------------------------------------------------------------------\n    // predict full intervall\n    VectorType y_predict_rq(gt_size);\n    VectorType y_predict_gk(gt_size);\n    for(unsigned i=0; i<gt_size; i++){\n        VectorType x(1);\n        x(0) = interval_start + i*interval_step;\n        y_predict_rq[i] = rq_gp->Predict(x)(0);\n        y_predict_gk[i] = gk_gp->Predict(x)(0);\n    }\n\n    double err = (y_predict_gk-y_predict_rq).norm();\n    if(err>0.01){\n        std::stringstream ss; ss<<err; throw ss.str();\n    }\n    else{\n        std::cout << \" [passed].\" << std::endl;\n    }\n\n}\n\nvoid Test2(){\n    /*\n     * Test 2: regression test 1D\n     */\n    std::cout << \"Test 2: perform standard regression...\" << std::flush;\n\n    // ground truth periodic variable\n    auto f = [](double x)->double { return 0.5*x*std::sin(x)+std::sin(4*x); };\n\n    double interval_start = -10;\n    double interval_end = 10; // full interval\n    double interval_step = 0.1;\n\n    //--------------------------------------------------------------------------------\n    // generating ground truth\n    unsigned gt_size = (interval_end-interval_start) / interval_step;\n    VectorType y(gt_size);\n    for(unsigned i=0; i<gt_size; i++){\n        y[i] = f(interval_start + i*interval_step);\n    }\n\n    //--------------------------------------------------------------------------------\n    // perform training\n    double noise = 0.01;\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, noise);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n    double interval_training_end = 10; // interval to train\n    unsigned number_of_samples = 50;\n\n    // kernels\n    RationalQuadraticKernelTypePointer rq(new RationalQuadraticKernelType(4, 2.5, 0.01)); // scale, period, smoothness\n\n    // gps\n    GaussianProcessTypePointer rq_gp(new GaussianProcessType(rq));\n    rq_gp->SetSigma(noise); // noise\n\n    // add samples\n    double training_step_size = (interval_training_end - interval_start) / number_of_samples;\n    for(unsigned i=0; i<number_of_samples; i++){\n        VectorType x(1);\n        x(0) = interval_start + i*training_step_size;\n\n        VectorType y(1);\n        y(0) = f(x(0)) + r();\n\n        rq_gp->AddSample(x, y);\n    }\n    rq_gp->Initialize();\n\n\n    //--------------------------------------------------------------------------------\n    // predict full intervall\n    VectorType y_predict_rq(gt_size);\n    for(unsigned i=0; i<gt_size; i++){\n        VectorType x(1);\n        x(0) = interval_start + i*interval_step;\n        y_predict_rq[i] = rq_gp->Predict(x)(0);\n    }\n\n\n    double err = (y-y_predict_rq).norm();\n    if(err>3){\n        std::stringstream ss; ss<<err; throw ss.str();\n    }\n    else{\n        std::cout << \" [passed].\" << std::endl;\n    }\n\n}\n\nvoid Test3(){\n    std::cout << \"Test 3: parameter test...\" << std::flush;\n\n    RationalQuadraticKernelTypePointer k(new RationalQuadraticKernelType(4, 2.5, 0.01)); // scale, period, smoothness\n    RationalQuadraticKernelTypePointer k2(new RationalQuadraticKernelType(1, 1, 1)); // scale, period, smoothness\n\n    k2->SetParameters(k->GetParameters());\n\n    if((*k) != (*k2)){\n        throw std::string(\"kernels are not equal\");\n    }\n    else{\n        std::cout << \" [passed].\" << std::endl;\n    }\n}\n\nint main (int argc, char *argv[]){\n    std::cout << \"Rational quadratic kernel test: \" << std::endl;\n    try{\n    \tTest1();\n    \tTest2();\n    \tTest3();\n    }\n    catch(std::string& s){\n        std::cout << \"[failed] Error: \" << s << std::endl;\n        return -1;\n    }\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "bd842c0e5ab2c111bb41edcbda71735b5728d9a7", "size": 7017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/RationalQuadraticKernelTest.cpp", "max_stars_repo_name": "ChristophJud/GPR", "max_stars_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-20T14:30:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T21:44:06.000Z", "max_issues_repo_path": "tests/RationalQuadraticKernelTest.cpp", "max_issues_repo_name": "ChristophJud/GPR", "max_issues_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "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/RationalQuadraticKernelTest.cpp", "max_forks_repo_name": "ChristophJud/GPR", "max_forks_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-11-16T00:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T02:00:18.000Z", "avg_line_length": 31.466367713, "max_line_length": 118, "alphanum_fraction": 0.6099472709, "num_tokens": 1732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5350356998319318}}
{"text": "#include <eve/function/jacobi_zeta.hpp>\n#include <boost/math/special_functions/jacobi_zeta.hpp>\n#include <eve/wide.hpp>\n#include <iostream>\n#include <eve/constant/pio_2.hpp>\n\nusing wide_ft = eve::wide<float, eve::fixed<4>>;\n\nint main()\n{\n  wide_ft k   = {1.0f, 0.0f, 0.75f, 0.5f};\n  wide_ft phi = {0.2f, 1.0e-30f, 0.5f, 0.0f};\n  std::cout << \"---- simd\" << '\\n'\n             << \"<- phi                  = \" << phi << '\\n'\n             << \"<- k                    = \" << k << '\\n'\n             << \"-> jacobi_zeta(phi, k) = \" << eve::jacobi_zeta(phi, k) << '\\n';\n\n  float kf = 0.1f;\n  float phif = 1.1f;\n\n  std::cout << \"---- scalar\" << '\\n'\n            << \"<- xf                    = \" << kf << '\\n'\n            << \"<- phif                  = \" << phif<< '\\n'\n            << \"-> jacobi_zeta(phif, kf) = \" << eve::jacobi_zeta(phif, kf) << '\\n';\n\n  return 0;\n}\n", "meta": {"hexsha": "8aba8cea401f5611419dea15be895a53be79dc0f", "size": 858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/core/jacobi_zeta.cpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "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/doc/core/jacobi_zeta.cpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "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/doc/core/jacobi_zeta.cpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["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.6428571429, "max_line_length": 83, "alphanum_fraction": 0.4358974359, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5350356948242996}}
{"text": "/*\n*   Greedy Search\n*   by R. Falque\n*   29/11/2018\n*/\n\n#ifndef GETMINMAX_HPP\n#define GETMINMAX_HPP\n\n#include <Eigen/Core>\n\nstatic inline void getMinMax(const Eigen::MatrixXd & in_cloud, Eigen::Vector3d & min_point, Eigen::Vector3d & max_point){\n    max_point = in_cloud.colwise().maxCoeff();\n    min_point = in_cloud.colwise().minCoeff();\n};\n\ninline void getScale(const Eigen::MatrixXd & in_cloud, double & scale){\n    Eigen::Vector3d min_point;\n    Eigen::Vector3d max_point;\n\n    getMinMax(in_cloud, min_point, max_point);\n\n    scale = (max_point - min_point).norm();\n};\n\n#endif\n", "meta": {"hexsha": "ef5e6a982a9f62cf0b5253d448e8bea8f926912f", "size": 583, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "embedded_deformation/include/embedded_deformation/getMinMax.hpp", "max_stars_repo_name": "jessemorris/embedded_deformation", "max_stars_repo_head_hexsha": "ae961994e022c04772b1304aac24d0ae13fc3610", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-09-07T06:23:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T23:42:04.000Z", "max_issues_repo_path": "embedded_deformation/include/embedded_deformation/getMinMax.hpp", "max_issues_repo_name": "jessemorris/embedded_deformation", "max_issues_repo_head_hexsha": "ae961994e022c04772b1304aac24d0ae13fc3610", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-24T11:57:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-29T02:11:05.000Z", "max_forks_repo_path": "embedded_deformation/include/embedded_deformation/getMinMax.hpp", "max_forks_repo_name": "jessemorris/embedded_deformation", "max_forks_repo_head_hexsha": "ae961994e022c04772b1304aac24d0ae13fc3610", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-01-17T10:08:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:38:35.000Z", "avg_line_length": 21.5925925926, "max_line_length": 121, "alphanum_fraction": 0.6998284734, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5350356948242995}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\nusing namespace boost;\nusing namespace std;\n\ntypedef boost::adjacency_list<\n                                listS, //std::list is a container that supports constant time insertion and removal of elements from anywhere\n                                vecS, //std::vector is a sequence container that encapsulates dynamic size arrays.\n                                undirectedS //undirected_selector \n                             > mygraph; \n\nint main()\n{\n    mygraph g;\n    //Adds edge (u,v) to the graph and returns the edge descriptor for the new edge. \n    add_edge (0, 1, g);\n    add_edge (0, 3, g);\n    add_edge (1, 2, g);\n    add_edge (2, 3, g);\n\n    // vertex_iterator provides access to all of the vertices in a graph. \n    mygraph::vertex_iterator vertexIt, vertexEnd;\n    // adjacency_iterator implements the member functions and operators required of the Random Access Iterator concep\n    mygraph::adjacency_iterator neighbourIt, neighbourEnd; \n    //The adjacency iterator adaptor transforms an out_edge_iterator into an adjacency iterator.\n    tie(vertexIt, vertexEnd) = vertices(g);\n\n    for (; vertexIt != vertexEnd; ++vertexIt)\n    {\n        cout << *vertexIt << \" is connected with \";\n        tie(neighbourIt, neighbourEnd) = adjacent_vertices(*vertexIt, g);\n        for (; neighbourIt != neighbourEnd; ++neighbourIt) cout << *neighbourIt << \" \";\n        cout << \"\\n\";\n    }\n}\n", "meta": {"hexsha": "dd29e6cb9ae9320b27a8e5f4a2ef9959d850b769", "size": 1456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2Traversing_the_graph_using_BGL.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": "2Traversing_the_graph_using_BGL.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": "2Traversing_the_graph_using_BGL.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": 40.4444444444, "max_line_length": 141, "alphanum_fraction": 0.6407967033, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5349461636728234}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE SinogramCreatorTest\n#include <boost/test/unit_test.hpp>\n\n#include \"SinogramCreatorTools.h\"\n#include <iostream>\n\nBOOST_AUTO_TEST_SUITE(FirstSuite)\n\nBOOST_AUTO_TEST_CASE(roundToNearesMultiplicity_test)\n{\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.0f, 1.f), 0u);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.4f, 1.f), 0u);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.5f, 1.f), 1u);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(30.f, 1.f), 30u);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.00f, 0.01f), 0u);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.01f, 0.01f), 1u);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.02f, 0.01f), 2u);\n}\n\nBOOST_AUTO_TEST_CASE(test_angle_middle)\n{\n  const float EPSILON = 0.01f;\n  const float r = 10;\n  const float maxDistance = 20.f;\n  const float accuracy = 0.1f;\n\n  for (int i = 0; i < 360; i++)\n  {\n    const float x1 = r * std::cos((i) * (M_PI / 180.f));\n    const float y1 = r * std::sin((i) * (M_PI / 180.f));\n    const float x2 = r * std::cos((i + 180) * (M_PI / 180.f));\n    const float y2 = r * std::sin((i + 180) * (M_PI / 180.f));\n    const auto result =\n        SinogramCreatorTools::getSinogramRepresentation(x1, y1, x2, y2, maxDistance, accuracy, std::ceil(maxDistance * 2.f * (1.f / accuracy)), 180);\n    int resultAngle = i < 90 ? 90 + i : i < 180 ? i - 90 : i < 270 ? i - 90 : i - 270;\n    BOOST_REQUIRE_EQUAL(result.second, resultAngle);\n    const float distanceResult = SinogramCreatorTools::roundToNearesMultiplicity(maxDistance, accuracy);\n    BOOST_REQUIRE_CLOSE(result.first, distanceResult, EPSILON);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_lor_slice)\n{\n  const float EPSILON = 0.0001f;\n\n  float x1 = 0.f;\n  float y1 = 0.f;\n  float z1 = 0.f;\n  float t1 = 0.f;\n  float x2 = 0.f;\n  float y2 = 0.f;\n  float z2 = 0.f;\n  float t2 = 0.f;\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateLORSlice(x1, y1, z1, t1, x2, y2, z2, t2), 0.f, EPSILON);\n  x1 = 1.f;\n  x2 = -1.f;\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateLORSlice(x1, y1, z1, t1, x2, y2, z2, t2), 0.f, EPSILON);\n  t1 = 10 * 3.33564095; // speed-of-light * 10 * 3.33564095 ~= 1\n  t2 = 10 * 3.33564095;\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateLORSlice(x1, y1, z1, t1, x2, y2, z2, t2), 0.f, EPSILON);\n  x1 = 0.f;\n  x2 = 0.f;\n  z1 = 1.f;\n  z2 = -1.f;\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateLORSlice(x1, y1, z1, t1, x2, y2, z2, t2), 0.f, EPSILON);\n  z1 = -1.f;\n  z2 = 1.f;\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateLORSlice(x1, y1, z1, t1, x2, y2, z2, t2), 0.f, EPSILON);\n}\n\nBOOST_AUTO_TEST_CASE(remap_to_single_layer)\n{\n  const float EPSILON = 0.1f;\n  float x1 = 0.f;\n  float y1 = 0.f;\n  float z1 = 0.f;\n  float x2 = 1.f;\n  float y2 = 0.f;\n  float z2 = 0.f;\n\n  float radius = 40.f;\n\n  auto result = SinogramCreatorTools::remapToSingleLayer(TVector3(x1, y1, z1), TVector3(x2, y2, z2), radius);\n  BOOST_REQUIRE_CLOSE(result.first.X(), radius, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Y(), 0.f, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Z(), 0.f, EPSILON);\n\n  BOOST_REQUIRE_CLOSE(result.second.X(), -radius, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Y(), 0.f, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Z(), 0.f, EPSILON);\n\n  radius = 45.75f;\n  result = SinogramCreatorTools::remapToSingleLayer(TVector3(x1, y1, z1), TVector3(x2, y2, z2), radius);\n  BOOST_REQUIRE_CLOSE(result.first.X(), radius, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Y(), 0.f, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Z(), 0.f, EPSILON);\n\n  BOOST_REQUIRE_CLOSE(result.second.X(), -radius, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Y(), 0.f, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Z(), 0.f, EPSILON);\n\n  x1 = 0.f; \n  y1 = 30.f;\n  x2 = 0.f;\n  y2 = -30.f;\n\n  result = SinogramCreatorTools::remapToSingleLayer(TVector3(x1, y1, z1), TVector3(x2, y2, z2), radius);\n  BOOST_REQUIRE_CLOSE(result.first.X(), 0.f, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Y(), radius, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Z(), 0.f, EPSILON);\n\n  BOOST_REQUIRE_CLOSE(result.second.X(), 0.f, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Y(), -radius, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Z(), 0.f, EPSILON);\n\n  x1 = 10.f; \n  y1 = 30.f;\n  x2 = 10.f;\n  y2 = -30.f;\n\n  result = SinogramCreatorTools::remapToSingleLayer(TVector3(x1, y1, z1), TVector3(x2, y2, z2), radius);\n  BOOST_REQUIRE_CLOSE(result.first.X(), 10.f, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Y(), radius, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Z(), 0.f, EPSILON);\n\n  BOOST_REQUIRE_CLOSE(result.second.X(), 10.f, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Y(), -radius, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Z(), 0.f, EPSILON);\n\n  x1 = 10.f; \n  y1 = 30.f;\n  x2 = -10.f;\n  y2 = -30.f;\n  result = SinogramCreatorTools::remapToSingleLayer(TVector3(x1, y1, z1), TVector3(x2, y2, z2), radius);\n  BOOST_REQUIRE_CLOSE(result.first.X(), 14.4674, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Y(), 43.4023, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Z(), 0.f, EPSILON);\n\n  BOOST_REQUIRE_CLOSE(result.second.X(), -14.4674, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Y(), -43.4023, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Z(), 0.f, EPSILON);\n\n  x1 = 0.f; \n  y1 = 30.f;\n  z1 = 10.f;\n\n  x2 = 0.f;\n  y2 = -30.f;\n  z2 = 10.f;\n\n  result = SinogramCreatorTools::remapToSingleLayer(TVector3(x1, y1, z1), TVector3(x2, y2, z2), radius);\n  BOOST_REQUIRE_CLOSE(result.first.X(), 0.f, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Y(), radius, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Z(), z1, EPSILON);\n\n  BOOST_REQUIRE_CLOSE(result.second.X(), 0.f, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Y(), -radius, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Z(), z2, EPSILON);\n\n\n  x1 = 0.f; \n  y1 = 30.f;\n  z1 = -25.f;\n\n  x2 = 0.f;\n  y2 = -30.f;\n  z2 = 25.f;\n  \n  result = SinogramCreatorTools::remapToSingleLayer(TVector3(x1, y1, z1), TVector3(x2, y2, z2), radius);\n  BOOST_REQUIRE_CLOSE(result.first.X(), 0.f, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Y(), radius, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.first.Z(), z1, EPSILON);\n\n  BOOST_REQUIRE_CLOSE(result.second.X(), 0.f, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Y(), -radius, EPSILON);\n  BOOST_REQUIRE_CLOSE(result.second.Z(), z2, EPSILON);\n\n}\n\nBOOST_AUTO_TEST_CASE(polyfit_test)\n{\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::getPolyFit({std::sqrt((9.39 * 9.39) + (-10.75 * -10.75)), -std::abs(3.39)}), 4.367437643607859e-01,\n                      kEPSILON);\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::getPolyFit({std::sqrt((9.57 * 9.57) + (-0.87 * -0.87)), -std::abs(2.49)}), 7.197118953414579e-01,\n                      kEPSILON);\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::getPolyFit({std::sqrt((-11.83 * -11.83) + (2.66 * 2.66)), -std::abs(-2.72)}), 5.820874582833866e-01,\n                      kEPSILON);\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::getPolyFit({std::sqrt((1.84 * 1.84) + (-8.89 * -8.89)), -std::abs(-4.77)}), 7.430144030486940e-01,\n                      kEPSILON);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "49c02f22f7aef1d04b4a8f7a145d356207e68695", "size": 7237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ImageReconstruction/SinogramCreatorToolsTest.cpp", "max_stars_repo_name": "kdulski/j-pet-framework-examples", "max_stars_repo_head_hexsha": "ab2592a2c6cf8f901f5732f8878b750b9a7b6a49", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-12T16:51:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T08:01:34.000Z", "max_issues_repo_path": "ImageReconstruction/SinogramCreatorToolsTest.cpp", "max_issues_repo_name": "kdulski/j-pet-framework-examples", "max_issues_repo_head_hexsha": "ab2592a2c6cf8f901f5732f8878b750b9a7b6a49", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 89.0, "max_issues_repo_issues_event_min_datetime": "2016-07-23T22:12:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T13:21:29.000Z", "max_forks_repo_path": "ImageReconstruction/SinogramCreatorToolsTest.cpp", "max_forks_repo_name": "kdulski/j-pet-framework-examples", "max_forks_repo_head_hexsha": "ab2592a2c6cf8f901f5732f8878b750b9a7b6a49", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2016-06-18T17:47:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T12:18:00.000Z", "avg_line_length": 37.4974093264, "max_line_length": 149, "alphanum_fraction": 0.6875777256, "num_tokens": 2459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5349461506418278}}
{"text": "//\n// Copyright (c) 2019-2020 CNRS\n//\n// This file has been imported from eiquadprog and stripped from Boost.\n//\n// eiquadprog is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Lesser 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// eiquadprog 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 Lesser General Public License for more details.\n\n// You should have received a copy of the GNU Lesser General Public License\n// along with eiquadprog.  If not, see <https://www.gnu.org/licenses/>.\n\n#include <iostream>\n\n#include <Eigen/Core>\n\n#include \"eiquadprog/eiquadprog.hpp\"\n\n// The problem is in the form:\n// min 0.5 * x G x + g0 x\n// s.t.\n// CE^T x + ce0 = 0\n// CI^T x + ci0 >= 0\n// The matrix and vectors dimensions are as follows:\n// G: n * n\n// g0: n\n// CE: n * p\n// ce0: p\n// CI: n * m\n// ci0: m\n// x: n\n\n// min ||x||^2\n\nint test_unbiased() {\n    int ret = 0;\n    Eigen::MatrixXd Q(2, 2);\n    Q.setZero();\n    Q(0, 0) = 1.0;\n    Q(1, 1) = 1.0;\n\n    Eigen::VectorXd C(2);\n    C.setZero();\n\n    Eigen::MatrixXd Aeq(2, 0);\n\n    Eigen::VectorXd Beq(0);\n\n    Eigen::MatrixXd Aineq(2, 0);\n\n    Eigen::VectorXd Bineq(0);\n\n    Eigen::VectorXd x(2);\n    Eigen::VectorXi activeSet(0);\n    size_t activeSetSize;\n\n    Eigen::VectorXd solution(2);\n    solution.setZero();\n\n    double val = 0.0;\n\n    double out = Eigen::solve_quadprog(Q, C, Aeq, Beq, Aineq, Bineq, x, activeSet, activeSetSize);\n\n    if (fabs(out - val) > 1e-6) ret++;\n    if (!x.isApprox(solution)) ret++;\n    return ret;\n}\n\n// min ||x-x_0||^2, x_0 = (1 1)^T\n\nint test_biased() {\n    int ret=0;\n    Eigen::MatrixXd Q(2, 2);\n    Q.setZero();\n    Q(0, 0) = 1.0;\n    Q(1, 1) = 1.0;\n\n    Eigen::VectorXd C(2);\n    C(0) = -1.;\n    C(1) = -1.;\n\n    Eigen::MatrixXd Aeq(2, 0);\n\n    Eigen::VectorXd Beq(0);\n\n    Eigen::MatrixXd Aineq(2, 0);\n\n    Eigen::VectorXd Bineq(0);\n\n    Eigen::VectorXd x(2);\n    Eigen::VectorXi activeSet(0);\n    size_t activeSetSize;\n\n    Eigen::VectorXd solution(2);\n    solution(0) = 1.;\n    solution(1) = 1.;\n\n    double val = -1.;\n\n    double out = Eigen::solve_quadprog(Q, C, Aeq, Beq, Aineq, Bineq, x, activeSet, activeSetSize);\n\n    if (fabs(out - val) > 1e-6) ret++;\n    if (!x.isApprox(solution)) ret++;\n    return ret;\n}\n\n// min ||x||^2\n//    s.t.\n// x[1] = 1 - x[0]\n\nint test_equality_constraints() {\n    int ret=0;\n    Eigen::MatrixXd Q(2, 2);\n    Q.setZero();\n    Q(0, 0) = 1.0;\n    Q(1, 1) = 1.0;\n\n    Eigen::VectorXd C(2);\n    C.setZero();\n\n    Eigen::MatrixXd Aeq(2, 1);\n    Aeq(0, 0) = 1.;\n    Aeq(1, 0) = 1.;\n\n    Eigen::VectorXd Beq(1);\n    Beq(0) = -1.;\n\n    Eigen::MatrixXd Aineq(2, 0);\n\n    Eigen::VectorXd Bineq(0);\n\n    Eigen::VectorXd x(2);\n    Eigen::VectorXi activeSet(1);\n    size_t activeSetSize;\n\n    Eigen::VectorXd solution(2);\n    solution(0) = 0.5;\n    solution(1) = 0.5;\n\n    double val = 0.25;\n\n    double out = Eigen::solve_quadprog(Q, C, Aeq, Beq, Aineq, Bineq, x, activeSet, activeSetSize);\n\n    if (fabs(out - val) > 1e-6) ret++;\n    if (!x.isApprox(solution)) ret++;\n    return ret;\n}\n\n// min ||x||^2\n//    s.t.\n// x[i] >= 1\n\nint test_inequality_constraints() {\n    int ret = 0;\n    Eigen::MatrixXd Q(2, 2);\n    Q.setZero();\n    Q(0, 0) = 1.0;\n    Q(1, 1) = 1.0;\n\n    Eigen::VectorXd C(2);\n    C.setZero();\n\n    Eigen::MatrixXd Aeq(2, 0);\n\n    Eigen::VectorXd Beq(0);\n\n    Eigen::MatrixXd Aineq(2, 2);\n    Aineq.setZero();\n    Aineq(0, 0) = 1.;\n    Aineq(1, 1) = 1.;\n\n    Eigen::VectorXd Bineq(2);\n    Bineq(0) = -1.;\n    Bineq(1) = -1.;\n\n    Eigen::VectorXd x(2);\n    Eigen::VectorXi activeSet(2);\n    size_t activeSetSize;\n\n    Eigen::VectorXd solution(2);\n    solution(0) = 1.;\n    solution(1) = 1.;\n\n    double val = 1.;\n\n    double out = Eigen::solve_quadprog(Q, C, Aeq, Beq, Aineq, Bineq, x, activeSet, activeSetSize);\n\n    if (fabs(out - val) > 1e-6) ret++;\n    if (!x.isApprox(solution)) ret++;\n    return ret;\n}\n\n// min ||x-x_0||^2, x_0 = (1 1)^T\n//    s.t.\n// x[1] = 5 - x[0]\n// x[1] >= 3\n\nint test_full() {\n    int ret=0;\n    Eigen::MatrixXd Q(2, 2);\n    Q.setZero();\n    Q(0, 0) = 1.0;\n    Q(1, 1) = 1.0;\n\n    Eigen::VectorXd C(2);\n    C(0) = -1.;\n    C(1) = -1.;\n\n    Eigen::MatrixXd Aeq(2, 1);\n    Aeq(0, 0) = 1.;\n    Aeq(1, 0) = 1.;\n\n    Eigen::VectorXd Beq(1);\n    Beq(0) = -5.;\n\n    Eigen::MatrixXd Aineq(2, 1);\n    Aineq.setZero();\n    Aineq(1, 0) = 1.;\n\n    Eigen::VectorXd Bineq(1);\n    Bineq(0) = -3.;\n\n    Eigen::VectorXd x(2);\n    Eigen::VectorXi activeSet(2);\n    size_t activeSetSize;\n\n    Eigen::VectorXd solution(2);\n    solution(0) = 2.;\n    solution(1) = 3.;\n\n    double val = 1.5;\n\n    double out = Eigen::solve_quadprog(Q, C, Aeq, Beq, Aineq, Bineq, x, activeSet, activeSetSize);\n\n    if (fabs(out - val) > 1e-6) ret++;\n    if (!x.isApprox(solution)) ret++;\n    return ret;\n}\n\n// min ||x||^2\n//    s.t.\n// x[0] =  1\n// x[0] = -1\n// DOES NOT WORK!\n\nint test_unfeasible_equalities() {\n    int ret=0;\n    Eigen::MatrixXd Q(2, 2);\n    Q.setZero();\n    Q(0, 0) = 1.0;\n    Q(1, 1) = 1.0;\n\n    Eigen::VectorXd C(2);\n    C.setZero();\n\n    Eigen::MatrixXd Aeq(2, 2);\n    Aeq.setZero();\n    Aeq(0, 0) = 1.;\n    Aeq(0, 1) = 1.;\n\n    Eigen::VectorXd Beq(2);\n    Beq(0) = -1.;\n    Beq(1) = 1.;\n\n    Eigen::MatrixXd Aineq(2, 0);\n\n    Eigen::VectorXd Bineq(0);\n\n    Eigen::VectorXd x(2);\n    Eigen::VectorXi activeSet(2);\n    size_t activeSetSize;\n\n    double out = Eigen::solve_quadprog(Q, C, Aeq, Beq, Aineq, Bineq, x, activeSet, activeSetSize);\n\n    // DOES NOT WORK!?\n    if (!std::isinf(out)) ret++;\n    return ret;\n}\n\n// min ||x||^2\n//    s.t.\n// x[0] >=  1\n// x[0] <= -1\n\nint test_unfeasible_inequalities() {\n    int ret =0;\n    Eigen::MatrixXd Q(2, 2);\n    Q.setZero();\n    Q(0, 0) = 1.0;\n    Q(1, 1) = 1.0;\n\n    Eigen::VectorXd C(2);\n    C.setZero();\n\n    Eigen::MatrixXd Aeq(2, 0);\n\n    Eigen::VectorXd Beq(0);\n\n    Eigen::MatrixXd Aineq(2, 2);\n    Aineq.setZero();\n    Aineq(0, 0) = 1.;\n    Aineq(0, 1) = -1.;\n\n    Eigen::VectorXd Bineq(2);\n    Bineq(0) = -1;\n    Bineq(1) = -1;\n\n    Eigen::VectorXd x(2);\n    Eigen::VectorXi activeSet(2);\n    size_t activeSetSize;\n\n    double out = Eigen::solve_quadprog(Q, C, Aeq, Beq, Aineq, Bineq, x, activeSet, activeSetSize);\n\n    if (!std::isinf(out)) ret++;\n    return ret;\n}\n\n// min ||x-x_0||^2, x_0 = (1 1)^T\n//    s.t.\n// x[1] = 1 - x[0]\n// x[0] <= 0\n// x[1] <= 0\n\nint test_unfeasible_constraints() {\n    int ret=0;\n    Eigen::MatrixXd Q(2, 2);\n    Q.setZero();\n    Q(0, 0) = 1.0;\n    Q(1, 1) = 1.0;\n\n    Eigen::VectorXd C(2);\n    C(0) = -1.;\n    C(1) = -1.;\n\n    Eigen::MatrixXd Aeq(2, 1);\n    Aeq(0, 0) = 1.;\n    Aeq(1, 0) = 1.;\n\n    Eigen::VectorXd Beq(1);\n    Beq(0) = -1.;\n\n    Eigen::MatrixXd Aineq(2, 2);\n    Aineq.setZero();\n    Aineq(0, 0) = -1.;\n    Aineq(1, 1) = -1.;\n\n    Eigen::VectorXd Bineq(2);\n    Bineq.setZero();\n\n    Eigen::VectorXd x(2);\n    Eigen::VectorXi activeSet(3);\n    size_t activeSetSize;\n\n    double out = Eigen::solve_quadprog(Q, C, Aeq, Beq, Aineq, Bineq, x, activeSet, activeSetSize);\n\n    if (!std::isinf(out)) ret++;\n    return ret;\n}\n\n// min -||x||^2\n// DOES NOT WORK!\n\nint test_unbounded() {\n    int ret=0;\n    Eigen::MatrixXd Q(2, 2);\n    Q.setZero();\n    Q(0, 0) = -1.0;\n    Q(1, 1) = -1.0;\n\n    Eigen::VectorXd C(2);\n    C.setZero();\n\n    Eigen::MatrixXd Aeq(2, 0);\n\n    Eigen::VectorXd Beq(0);\n\n    Eigen::MatrixXd Aineq(2, 0);\n\n    Eigen::VectorXd Bineq(0);\n\n    Eigen::VectorXd x(2);\n    Eigen::VectorXi activeSet(0);\n    size_t activeSetSize;\n\n    double out = Eigen::solve_quadprog(Q, C, Aeq, Beq, Aineq, Bineq, x, activeSet, activeSetSize);\n\n    // DOES NOT WORK!?\n    if (!std::isinf(out)) ret++;\n    return ret;\n}\n\n// min -||x||^2\n//    s.t.\n// 0<= x[0] <= 1\n// 0<= x[1] <= 1\n// DOES NOT WORK!\n\nint test_nonconvex() {\n    int ret=0;\n    Eigen::MatrixXd Q(2, 2);\n    Q.setZero();\n    Q(0, 0) = -1.0;\n    Q(1, 1) = -1.0;\n\n    Eigen::VectorXd C(2);\n    C.setZero();\n\n    Eigen::MatrixXd Aeq(2, 0);\n\n    Eigen::VectorXd Beq(0);\n\n    Eigen::MatrixXd Aineq(2, 4);\n    Aineq.setZero();\n    Aineq(0, 0) = 1.;\n    Aineq(0, 1) = -1.;\n    Aineq(1, 2) = 1.;\n    Aineq(1, 3) = -1.;\n\n    Eigen::VectorXd Bineq(4);\n    Bineq(0) = 0.;\n    Bineq(1) = 1.;\n    Bineq(2) = 0.;\n    Bineq(3) = 1.;\n\n    Eigen::VectorXd x(2);\n    Eigen::VectorXi activeSet(4);\n    size_t activeSetSize;\n\n    Eigen::VectorXd solution(2);\n    solution(0) = 1.;\n    solution(1) = 1.;\n\n    double val = -1.;\n\n    double out = Eigen::solve_quadprog(Q, C, Aeq, Beq, Aineq, Bineq, x, activeSet, activeSetSize);\n\n    // DOES NOT WORK!?\n    if (fabs(out - val) > 1e-6) ret++;\n    if (!x.isApprox(solution)) ret++;\n    return ret;\n}\n\n\nint main() {\n    int unbiased = test_unbiased();\n    int biased = test_biased();\n    int equality_constraints = test_equality_constraints();\n    int inequality_constraints = test_inequality_constraints();\n    int full = test_full();\n    int unfeasible_equalities = test_unfeasible_equalities();\n    int unfeasible_inequalities = test_unfeasible_inequalities();\n    int unfeasible_constraints = test_unfeasible_constraints();\n    int unbounded = test_unbounded();\n    int nonconvex = test_nonconvex();\n\n    std::cout << \"unbiased: 0/\" << unbiased << std::endl;\n    std::cout << \"biased: 0/\" << biased << std::endl;\n    std::cout << \"equality_constraints: 0/\" << equality_constraints << std::endl;\n    std::cout << \"inequality_constraints: 0/\" << inequality_constraints << std::endl;\n    std::cout << \"full: 0/\" << full << std::endl;\n    std::cout << \"unfeasible_equalities: 1/\" << unfeasible_equalities << std::endl;\n    std::cout << \"unfeasible_inequalities: 0/\" << unfeasible_inequalities << std::endl;\n    std::cout << \"unfeasible_constraints: 0/\" << unfeasible_constraints << std::endl;\n    std::cout << \"unbounded: 1/\" << unbounded << std::endl;\n    std::cout << \"nonconvex: 2/\" << nonconvex << std::endl;\n\n    return unbiased + biased + equality_constraints + inequality_constraints + full + unfeasible_inequalities + unfeasible_constraints;\n}\n", "meta": {"hexsha": "43c000d2ed9c1b4205ab18d52052227859e20a7a", "size": 10149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eiquadprog-basic.cpp", "max_stars_repo_name": "nim65s/eiquadprog-test", "max_stars_repo_head_hexsha": "38e6117bbec9492701c3a722c1de828972361446", "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": "eiquadprog-basic.cpp", "max_issues_repo_name": "nim65s/eiquadprog-test", "max_issues_repo_head_hexsha": "38e6117bbec9492701c3a722c1de828972361446", "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": "eiquadprog-basic.cpp", "max_forks_repo_name": "nim65s/eiquadprog-test", "max_forks_repo_head_hexsha": "38e6117bbec9492701c3a722c1de828972361446", "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": 21.3663157895, "max_line_length": 135, "alphanum_fraction": 0.5671494729, "num_tokens": 3717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5349461506418278}}
{"text": "/**\n * Copyright (c) 2018, The Akatsuki(Jacob.lsx). All rights reserved.\n */\n\n\n#include <iostream>\n#include <fstream>\n#include <list>\n#include <vector>\n#include <chrono>\n#include <ctime>\n#include <climits>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include <Eigen/Core>\n\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n\nusing namespace std;\nusing namespace cv;\n\n// TODO Warning!!!!! The result of using this method for bundle adjustment optimization is incorrect!!!!!!!\n\n/**\n * TODO \n * The result of using this method for bundle adjustment optimization is incorrect, \n * and I don\u2019t understand it for the time being.\n */\n#define USED_ISOMETRY3D_IN_BA       0\n\n/**\n * \u4e00\u6b21\u6d4b\u91cf\u7684\u503c\uff0c\u5305\u62ec\u4e00\u4e2a\u4e16\u754c\u5750\u6807\u7cfb\u4e0b\u4e09\u7ef4\u70b9\u4e0e\u4e00\u4e2a\u7070\u5ea6\u503c\n */\nstruct Measurement {\n    Measurement(Eigen::Vector3d p, float g) : pos_world(p), grayscale(g) {}\n    Eigen::Vector3d pos_world;\n    float grayscale;\n};\n\n/**\n * \u4ece\u50cf\u7d20\u5750\u6807\u7cfb\u8f6c\u6362\u6210\u4e16\u754c\u5750\u6807\u7cfb\n */\ninline Eigen::Vector3d project2Dto3D(int x, int y, int d, float fx, float fy, float cx, float cy, float scale)\n{\n    float zz = float(d) / scale;\n    float xx = zz * (x-cx) / fx;\n    float yy = zz * (y-cy) / fy;\n    return Eigen::Vector3d(xx, yy, zz);\n}\n\n/**\n * \u4ece\u4e16\u754c\u5750\u6807\u7cfb\u8f6c\u6362\u6210\u50cf\u7d20\u5750\u6807\u7cfb\n */\ninline Eigen::Vector2d project3Dto2D(float x, float y, float z, float fx, float fy, float cx, float cy)\n{\n    float u = fx * x / z + cx;\n    float v = fy * y / z + cy;\n    return Eigen::Vector2d(u, v);\n}\n\n/**\n * \u76f4\u63a5\u6cd5\u4f30\u8ba1\u4f4d\u59ff\n * input:\n *   \u6d4b\u91cf\u503c(\u7a7a\u95f4\u70b9\u7684\u7070\u5ea6), \u65b0\u7684\u7070\u5ea6\u56fe, \u76f8\u673a\u5185\u53c2;\n * output:\n *   \u76f8\u673a\u4f4d\u59ff\n * return:\n *   true\u4e3a\u6210\u529f, false\u5931\u8d25\n */\nbool poseEstimationDirect(const vector<Measurement>&, cv::Mat*, Eigen::Matrix3f&, Eigen::Isometry3d&);\n\n#if USED_ISOMETRY3D_IN_BA\n/**\n * project a 3d point into an image plane, the error is photometric error\n */\nclass EdgeSE3ProjectDirect\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    EdgeSE3ProjectDirect(const Eigen::Vector3d &p_world, const float &grayscale, cv::Mat* const image)\n     : x_world_(p_world), grayscale_(grayscale), image_(image) {}\n    \n    static void addCameraIntrinsics(const Eigen::Matrix3f &K)\n    {\n        fx_ = K(0, 0);\n        fy_ = K(1, 1);\n        cx_ = K(0, 2);\n        cy_ = K(1, 2);\n    }\n    \n    template<typename T>\n    bool operator() (const T* const T_, T* residuals) const;\n    \n    static ceres::CostFunction* create(const Eigen::Vector3d &p_world, const float &grayscale, cv::Mat* image)\n    {\n//         return (new ceres::AutoDiffCostFunction<EdgeSE3ProjectDirect, 1, 16>(new EdgeSE3ProjectDirect(p_world, grayscale, image)));\n        return (new ceres::NumericDiffCostFunction<EdgeSE3ProjectDirect, ceres::CENTRAL, 1, 16>(new EdgeSE3ProjectDirect(p_world, grayscale, image)));\n    }\n    \nprotected:\n    /* get a gray scale value from reference image (bilinear interpolated) */\n    inline float getPixelValue(float x, float y) const\n    {\n        uchar* data = &image_->data[(int)(y) * image_->step + (int)(x)];\n        float xx = x - floor(x);\n        float yy = y - floor(y);\n        \n        /* \u6c42\u53d6\u5206\u5e03\u5728\u96c6\u4e2d\u76f8\u90bb\uff14\u4e2a\u50cf\u7d20\u70b9\u8986\u76d6\u9762\u79ef\u7684\u50cf\u7d20\u7070\u5ea6\u503c */\n        return float((1 - xx) * (1 - yy) * data[0] + \\\n                     xx * (1 - yy) * data[1] + \\\n                     (1 - xx) * yy * data[image_->step] + \\\n                     xx * yy * data[image_->step + 1]);\n    }\n    \nprivate:\n    Eigen::Vector3d x_world_;                   // 3D point in world frame\n    float grayscale_;                           // Measurement grayscale\n    static float cx_, cy_, fx_, fy_;            // Camera intrinsics\n    cv::Mat* image_ = nullptr;                  // reference image\n};\n\nfloat EdgeSE3ProjectDirect::cx_ = 0.f;\nfloat EdgeSE3ProjectDirect::cy_ = 0.f;\nfloat EdgeSE3ProjectDirect::fx_ = 0.f;\nfloat EdgeSE3ProjectDirect::fy_ = 0.f;\n\ntemplate<typename T>\nbool EdgeSE3ProjectDirect::operator() (const T* const T_,  T* residuals) const\n{\n    Eigen::Isometry3d transformationMatrix;\n    transformationMatrix.matrix() << T_[0],  T_[1],  T_[2],  T_[3],\n                                     T_[4],  T_[5],  T_[6],  T_[7],\n                                     T_[8],  T_[9],  T_[10], T_[11],\n                                     T_[12], T_[13], T_[14], T_[15];\n    \n    Eigen::Vector3d p3d = transformationMatrix * x_world_; \n  \n    Eigen::Vector2d p2d = project3Dto2D(p3d.x(), p3d.y(), p3d.z(), fx_, fy_, cx_, cy_);\n    \n    residuals[0] = (T)grayscale_ - (T)getPixelValue(p2d.x(), p2d.y());\n    \n    return true;\n}\n\n#else\n\n/**\n * project a 3d point into an image plane, the error is photometric error\n */\nclass EdgeSE3ProjectDirect\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    EdgeSE3ProjectDirect(const Eigen::Vector3d &p_world, const float &grayscale, cv::Mat* const image)\n     : x_world_(p_world), grayscale_(grayscale), image_(image) {}\n    \n    static void addCameraIntrinsics(const Eigen::Matrix3f &K)\n    {\n        fx_ = K(0, 0);\n        fy_ = K(1, 1);\n        cx_ = K(0, 2);\n        cy_ = K(1, 2);\n    }\n    \n    template<typename T>\n    bool operator() (const T* const r_vec, const T* const t, T* residuals) const;\n    \n    static ceres::CostFunction* create(const Eigen::Vector3d &p_world, const float &grayscale, cv::Mat* image)\n    {\n//         return (new ceres::AutoDiffCostFunction<EdgeSE3ProjectDirect, 1, 16>(new EdgeSE3ProjectDirect(p_world, grayscale, image)));\n        return (new ceres::NumericDiffCostFunction<EdgeSE3ProjectDirect, ceres::CENTRAL, 1, 3, 3>(new EdgeSE3ProjectDirect(p_world, grayscale, image)));\n    }\n    \nprotected:\n    /* get a gray scale value from reference image (bilinear interpolated) */\n    inline float getPixelValue(float x, float y) const\n    {\n        uchar* data = &image_->data[(int)(y) * image_->step + (int)(x)];\n        float xx = x - floor(x);\n        float yy = y - floor(y);\n        \n        /* \u6c42\u53d6\u5206\u5e03\u5728\u96c6\u4e2d\u76f8\u90bb\uff14\u4e2a\u50cf\u7d20\u70b9\u8986\u76d6\u9762\u79ef\u7684\u50cf\u7d20\u7070\u5ea6\u503c */\n        return float((1 - xx) * (1 - yy) * data[0] + \\\n                     xx * (1 - yy) * data[1] + \\\n                     (1 - xx) * yy * data[image_->step] + \\\n                     xx * yy * data[image_->step + 1]);\n    }\n    \nprivate:\n    Eigen::Vector3d x_world_;                   // 3D point in world frame\n    float grayscale_;                           // Measurement grayscale\n    static float cx_, cy_, fx_, fy_;            // Camera intrinsics\n    cv::Mat* image_ = nullptr;                  // reference image\n};\n\nfloat EdgeSE3ProjectDirect::cx_ = 0.f;\nfloat EdgeSE3ProjectDirect::cy_ = 0.f;\nfloat EdgeSE3ProjectDirect::fx_ = 0.f;\nfloat EdgeSE3ProjectDirect::fy_ = 0.f;\n\ntemplate<typename T>\nbool EdgeSE3ProjectDirect::operator() (const T* const r_vec, const T* const t, T* residuals) const\n{\n    T p_world[3] = {(T)x_world_.x(), (T)x_world_.y(), (T)x_world_.z()};\n    T p_cam[3];\n    ceres::AngleAxisRotatePoint(r_vec, p_world, p_cam);\n    p_cam[0] += t[0];\n    p_cam[1] += t[1];\n    p_cam[2] += t[2];\n    \n    Eigen::Vector2d p2d = project3Dto2D(p_cam[0], p_cam[1], p_cam[2], fx_, fy_, cx_, cy_);\n    \n    residuals[0] = (T)grayscale_ - (T)getPixelValue(p2d.x(), p2d.y());\n    \n    return true;\n}\n#endif\n\nint main(int argc, char** argv)\n{\n    if (argc != 2) {\n        cout << \"usage: direct_sparse path_to_dataset\" << endl;\n        return 1;\n    }\n    \n    srand((unsigned int) time(0));\n    string path_to_dataset = argv[1];\n    string associate_file = path_to_dataset + \"/associate.txt\";\n    \n    ifstream fin(associate_file);\n    \n    string rgb_file, depth_file, time_rgb, time_depth;\n    cv::Mat color, depth, gray;\n    std::vector<Measurement> measurements;\n    \n    // Camera intrinsics\n    float cx = 325.5;\n    float cy = 253.5;\n    float fx = 518.0;\n    float fy = 519.0;\n    float depth_scale = 1000.0;\n    Eigen::Matrix3f K;\n    K << fx, 0.f, cx, 0.f, fy, cy, 0.f, 0.f, 1.0f;\n    \n    Eigen::Isometry3d Tcw = Eigen::Isometry3d::Identity();\n    \n    cv::Mat prev_color;\n   \n    // \u6211\u4eec\u4ee5\u7b2c\u4e00\u4e2a\u56fe\u50cf\u4e3a\u53c2\u8003\uff0c\u5bf9\u540e\u7eed\u56fe\u50cf\u548c\u53c2\u8003\u56fe\u50cf\u505a\u76f4\u63a5\u6cd5\n    for (int index = 0; index < 10; index ++) {\n        cout << \"**************** loop \" << index << \" **************** \\r\\n\";\n        fin >> time_rgb >> rgb_file >> time_depth >> depth_file;\n        color = cv::imread(path_to_dataset + \"/\" + rgb_file);\n        depth = cv::imread(path_to_dataset + \"/\" + depth_file, cv::IMREAD_UNCHANGED);\n        if (color.data == nullptr || depth.data == nullptr) {\n            continue;\n        }\n        cv::cvtColor(color, gray, cv::COLOR_BGR2GRAY);  // change rgb photo to gray photo\n        if (index == 0) {\n            // detect Oriented FAST KeyPoint for 1st photo\n            std::vector<cv::KeyPoint> keypoints;\n            cv::Ptr<cv::FastFeatureDetector> detector = cv::FastFeatureDetector::create();\n            detector->detect(color, keypoints);\n            for (auto kp : keypoints) {\n                // \u53bb\u6389\u90bb\u8fd1\u8fb9\u7f18\u5904\u7684\u70b9\n                if (kp.pt.x < 20 || kp.pt.y < 20 || (kp.pt.x + 20) > color.cols || (kp.pt.y + 20) > color.rows) {\n                    continue;\n                }\n                ushort d = depth.ptr<ushort>(cvRound(kp.pt.y))[cvRound(kp.pt.x)];\n                if (d == 0) {\n                    continue;\n                }\n                Eigen::Vector3d p3d = project2Dto3D(kp.pt.x, kp.pt.y, d, fx, fy, cx, cy, depth_scale);\n                float grayscale = float(gray.ptr<uchar>(cvRound(kp.pt.y))[cvRound(kp.pt.x)]);\n                measurements.push_back(Measurement(p3d, grayscale));\n            }\n            prev_color = color.clone();\n            continue;\n        }\n        \n        // \u4f7f\u7528\u76f4\u63a5\u6cd5\u8ba1\u7b97\u76f8\u673a\u8fd0\u52a8\n        chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n        poseEstimationDirect(measurements, &gray, K, Tcw);\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 << \"direct method costs time: \" << time_used.count() << \"secound. \\r\\n\";\n        cout << \"Tcw = \" << Tcw.matrix() << endl;\n        \n        // plot the feature points\n        cv::Mat img_show(color.rows * 2, color.cols, CV_8UC3);\n        prev_color.copyTo(img_show(cv::Rect(0, 0, color.cols, color.rows)));\n        color.copyTo(img_show(cv::Rect(0, color.rows, color.cols, color.rows)));\n        \n        for (Measurement m : measurements) {\n            if (rand() > RAND_MAX / 5) {\n                continue;\n            }\n            Eigen::Vector3d p = m.pos_world;\n            Eigen::Vector2d pixel_prev = project3Dto2D(p(0, 0), p(1, 0), p(2, 0), fx, fy, cx, cy);\n            Eigen::Vector3d p2 = Tcw * m.pos_world;\n            Eigen::Vector2d pixel_now = project3Dto2D(p2(0, 0), p2(1, 0), p2(2, 0), fx, fy, cx, cy);\n            if (pixel_now(0, 0) < 0 || pixel_now(0, 0) >= color.cols || pixel_now(1, 0) < 0 || pixel_now(1, 0) >= color.rows) {\n                continue;\n            }\n            \n            float b = 255 * float(rand()) / RAND_MAX;\n            float g = 255 * float(rand()) / RAND_MAX;\n            float r = 255 * float(rand()) / RAND_MAX;\n            \n            cv::circle(img_show, cv::Point2d(pixel_prev(0, 0), pixel_prev(1, 0)), 8, cv::Scalar(b, g, r), 2);\n            cv::circle(img_show, cv::Point2d(pixel_now(0, 0), pixel_now(1, 0) + color.rows), 8, cv::Scalar(b, g, r), 2);\n            cv::line(img_show, cv::Point2d(pixel_prev(0, 0), pixel_prev(1, 0)), cv::Point2d(pixel_now(0, 0), pixel_now(1, 0) + color.rows), cv::Scalar(b, g, r), 1);\n        }\n        \n        cv::imshow(\"result\", img_show);\n        cv::waitKey(0);\n    }\n    \n    return 0;\n}\n\n/**\n * \u76f4\u63a5\u6cd5\u4f30\u8ba1\u4f4d\u59ff\n */\nbool poseEstimationDirect(const vector<Measurement>& measurements, cv::Mat* gray, Eigen::Matrix3f& K, Eigen::Isometry3d& Tcw)\n{\n    EdgeSE3ProjectDirect::addCameraIntrinsics(K);\n    \n#if USED_ISOMETRY3D_IN_BA\n    ceres::Problem problem;\n    for (auto m : measurements) {\n        ceres::CostFunction *costFunction = EdgeSE3ProjectDirect::create(m.pos_world, m.grayscale, gray);\n        problem.AddResidualBlock(costFunction, nullptr, Tcw.data());\n    }\n    \n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_SCHUR;\n    options.minimizer_progress_to_stdout = true;\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n#else\n    double r_vec[3] = {0.f}, t[3] = {0.f};\n    ceres::Problem problem;\n    for (auto m : measurements) {\n        ceres::CostFunction *costFunction = EdgeSE3ProjectDirect::create(m.pos_world, m.grayscale, gray);\n        problem.AddResidualBlock(costFunction, nullptr, r_vec, t);\n    }\n    \n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_SCHUR;\n    options.minimizer_progress_to_stdout = true;\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    \n    cv::Mat R_vec = (cv::Mat_<double>(3, 1) << r_vec[0], r_vec[1], r_vec[2]);\n    cv::Mat R_matrix;\n    cv::Rodrigues(R_vec, R_matrix);\n    \n    Eigen::Matrix3d R;\n    R << R_matrix.at<double>(0, 0), R_matrix.at<double>(0, 1), R_matrix.at<double>(0, 2),\n         R_matrix.at<double>(1, 0), R_matrix.at<double>(1, 1), R_matrix.at<double>(1, 2),\n         R_matrix.at<double>(2, 0), R_matrix.at<double>(2, 1), R_matrix.at<double>(2, 2);\n    \n    Tcw.prerotate(R);\n    Tcw.pretranslate(Eigen::Vector3d(t[0], t[1], t[2]));    \n#endif\n    \n    return true;\n}\n", "meta": {"hexsha": "01cd50458c5ff961569cb76557e617a0394aed6a", "size": 13240, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "direct_sparse/src/direct_sparse_ceres.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": "direct_sparse/src/direct_sparse_ceres.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": "direct_sparse/src/direct_sparse_ceres.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": 35.0264550265, "max_line_length": 164, "alphanum_fraction": 0.5884441088, "num_tokens": 4015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5349364030415393}}
{"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 <Eigen/Core>\n#include \"test_case.hpp\"\n#include \"metro/likelihood/MultivariateT.hpp\"\n#include \"metro/ValueStabilisesStoppingCondition.hpp\"\n\ntypedef Eigen::MatrixXd Matrix ;\ntypedef Eigen::VectorXd Vector ;\n\ndouble const infinity = std::numeric_limits< double >::infinity() ;\n\n#define DEBUG_MULTIVARIATE_T 1\n\nBOOST_AUTO_TEST_SUITE( test_multivariate_t )\n\nAUTO_TEST_CASE( test_loglikelihood ) {\n\t{\n\t\tMatrix data( 1, 1 ) ;\n\t\tdata(0,0) = 0 ;\n\n\t\t{\n\t\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, infinity ) ;\n\t\t\tT.evaluate_at( Vector::Constant( 1, 0 ), Matrix::Constant( 1, 1, 1 )) ;\n\t\t\tdouble ll = T.get_value_of_function() ;\n\t\t\t// Tested against mvtnorm's mvt() function in R\n\t\t\tBOOST_CHECK_CLOSE( ll, -0.9189385332046727, 0.000001 ) ;\n\t\t}\n\t\t{\n\t\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, 100 ) ;\n\t\t\tT.evaluate_at( Vector::Constant( 1, 0 ), Matrix::Constant( 1, 1, 1 )) ;\n\t\t\tdouble ll = T.get_value_of_function() ;\n\t\t\t// Tested against mvtnorm's mvt() function in R\n\t\t\tBOOST_CHECK_CLOSE( ll, -0.9214384915429719, 0.000001 ) ;\n\t\t}\n\t\t{\n\t\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, 5 ) ;\n\t\t\tT.evaluate_at( Vector::Constant( 1, 0 ), Matrix::Constant( 1, 1, 1 )) ;\n\t\t\tdouble ll = T.get_value_of_function() ;\n\t\t\t// Tested against mvtnorm's mvt() function in R\n\t\t\tBOOST_CHECK_CLOSE( ll, -0.9686195890547241, 0.000001 ) ;\n\t\t}\n\t}\n\n\t{\n\t\tMatrix data( 4, 2 ) ;\n\t\tdata <<\n\t\t\t0.5, 0.1,\n\t\t\t0.4, 0.2,\n\t\t\t0.3, 0.1,\n\t\t\t0.35, 0.15\n\t\t;\n\n\t\t{\n\t\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, infinity ) ;\n\t\t\tT.evaluate_at( Vector::Constant( 2, 0 ), Matrix::Identity( 2, 2 )) ;\n\t\t\tdouble ll = T.get_value_of_function() ;\n\t\t\t// data = matrix( c( 0.5, 0.1, 0.4, 0.2, 0.3, 0.1, 0.35, 0.15 ), nrow = 4, byrow = T )\n\t\t\t// format( sum( dmvnorm( data, sigma = diag(2), log = TRUE ) ), digits = 16 )\n\t\t\tBOOST_CHECK_CLOSE( ll, -7.704008265637381, 0.000001 ) ;\n\t\t}\n\n\t\t{\n\t\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, 100 ) ;\n\t\t\tT.evaluate_at( Vector::Constant( 2, 0 ), Matrix::Identity( 2, 2 )) ;\n\t\t\tdouble ll = T.get_value_of_function() ;\n\t\t\t// data = matrix( c( 0.5, 0.1, 0.4, 0.2, 0.3, 0.1, 0.35, 0.15 ), nrow = 4, byrow = T )\n\t\t\t// format( sum( dmvt( data, sigma = diag(2), df = 100 ) ), digits = 16 )\n\t\t\tBOOST_CHECK_CLOSE( ll, -7.710705274651815, 0.000001 ) ;\n\t\t}\n\n\t\t{\n\t\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, 5 ) ;\n\t\t\tT.evaluate_at( Vector::Constant( 2, 0 ), Matrix::Identity( 2, 2 )) ;\n\t\t\tdouble ll = T.get_value_of_function() ;\n\t\t\t// data = matrix( c( 0.5, 0.1, 0.4, 0.2, 0.3, 0.1, 0.35, 0.15 ), nrow = 4, byrow = T )\n\t\t\t// format( sum( dmvt( data, sigma = diag(2), df = 5 ) ), digits = 16 )\n\t\t\tBOOST_CHECK_CLOSE( ll, -7.835571956296502, 0.000001 ) ;\n\t\t}\n\t}\n}\n\nAUTO_TEST_CASE( test_weighted_loglikelihood ) {\n\n\tdouble ll1 = 0, ll2 = 0, ll3 = 0 ;\n\t{\n\t\tMatrix data( 4, 2 ) ;\n\t\tdata <<\n\t\t\t0.5, 0.1,\n\t\t\t0.4, 0.2,\n\t\t\t0.3, 0.1,\n\t\t\t0.3, 0.1\n\t\t;\n\n\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, 3 ) ;\n\t\tT.evaluate_at( Vector::Constant( 2, 0 ), Matrix::Identity( 2, 2 )) ;\n\t\tll1 = T.get_value_of_function() ;\n\t}\n\n\t{\n\t\tMatrix data( 4, 2 ) ;\n\t\tdata <<\n\t\t\t0.5, 0.1,\n\t\t\t0.4, 0.2,\n\t\t\t0.3, 0.1,\n\t\t\t0.3, 0.1\n\t\t;\n\n\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T(\n\t\t\tdata,\n\t\t\tVector::Constant( 4, 1 ),\n\t\t\t3\n\t\t) ;\n\t\tT.evaluate_at( Vector::Constant( 2, 0 ), Matrix::Identity( 2, 2 )) ;\n\t\tll2 = T.get_value_of_function() ;\n\t}\n\n\t{\n\t\tMatrix data( 3, 2 ) ;\n\t\tdata <<\n\t\t\t0.5, 0.1,\n\t\t\t0.4, 0.2,\n\t\t\t0.3, 0.1\n\t\t;\n\t\tVector weights = Vector::Constant( 3, 1 ) ;\n\t\tweights(2) = 2 ;\n\n\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T(\n\t\t\tdata,\n\t\t\tweights,\n\t\t\t3\n\t\t) ;\n\t\tT.evaluate_at( Vector::Constant( 2, 0 ), Matrix::Identity( 2, 2 )) ;\n\t\tll3 = T.get_value_of_function() ;\n\t}\n\t\n\tBOOST_CHECK_CLOSE( ll1, ll2, 0.0000001 ) ;\n\tBOOST_CHECK_CLOSE( ll1, ll3, 0.0000001 ) ;\n}\n\nAUTO_TEST_CASE( test_loglikelihood_range ) {\n\t{\n\t\tdouble ll1 = 0, ll2 = 0 ;\n\t\tmetro::ValueStabilisesStoppingCondition stoppingCondition( 0.0000001 ) ;\n\t\t{\n\t\t\tMatrix data( 2, 2 ) ;\n\t\t\tdata <<\n\t\t\t\t0.5, 0.1,\n\t\t\t\t0.4, 0.2\n\t\t\t;\n\n\t\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, 3 ) ;\n\t\t\tT.evaluate_at( Vector::Constant( 2, 0 ), Matrix::Identity( 2, 2 )) ;\n\t\t\tll1 = T.get_value_of_function() ;\n\t\t\t\n\t\t\tstoppingCondition.reset() ;\n\t\t\tT.estimate_by_em( stoppingCondition ) ;\n\t\t}\n\n\t\t{\n\t\t\tMatrix data( 5, 2 ) ;\n\t\t\tdata <<\n\t\t\t\t0.5, 0.1,\n\t\t\t\t0.3, 0.1,\n\t\t\t\t0.4, 0.2,\n\t\t\t\t0.45, -100,\n\t\t\t\t10000, 100000\n\t\t\t;\n\t\t\tmetro::DataSubset ranges ;\n\t\t\tranges.add( metro::DataRange( 0, 1 )) ;\n\t\t\tranges.add( metro::DataRange( 2, 3 )) ;\n\n\t\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, 3 ) ;\n\t\t\tT.evaluate_at( Vector::Constant( 2, 0 ), Matrix::Identity( 2, 2 ), ranges ) ;\n\t\t\tll2 = T.get_value_of_function() ;\n\t\t}\n\n\t\t// Nominally exactly the same, the computation has slight rounding\n\t\t// errors so gets a different value.\n\t\tBOOST_CHECK_CLOSE( ll1, ll2, 1E-10 ) ;\n\t}\n}\n\n\nAUTO_TEST_CASE( test_em ) {\n\n\tdouble const likelihoodTolerance = 0.0000001 ;\n\tmetro::ValueStabilisesStoppingCondition stoppingCondition( likelihoodTolerance ) ;\n\tdouble const relativeTolerancePercent = 1E-3 ; // Expect values to differ by no more than 0.001%.\n\t\n\t{\n#if DEBUG_MULTIVARIATE_T\n\t\tstd::cerr << \"==================================\\n\" ;\n\t\tstd::cerr << \"test_multivariate_t_em(): 1d test:\\n\" ;\n#endif\t\t\n\t\tMatrix data( 3, 1 ) ;\n\t\tdata <<\n\t\t\t0.25,\n\t\t\t0.75,\n\t\t\t0.2\n\t\t;\n\t\t\n\t\t// mean = 0.5\n\t\t// var = 0.125\n\t\t// weights should equal 1.\n\t\t\n\t\t// data = matrix( c( 0.25, 0.75, 0.2 ), ncol = 1, byrow = T )\n\t\t// nu = 3\n\t\t/* f <- function( params ) {\n\t\t\tmu = params[1] ;\n\t\t\tsigma = matrix( params[2], nrow = 1, ncol = 1 );\n\t\t\tmu = matrix( rep( mu, nrow( data )), nrow = nrow( data ), ncol = ncol( data ), byrow = T )\n\t\t\tD = data - mu\n\t\t\tcat( \"-----\\n\" ) ;\n\t\t\tprint( mu );\n\t\t\tprint( sigma ) ;\n\t\t\tll = sum( dmvt( D, sigma = sigma, df = nu, log = T ) )\n\t\t\treturn( -ll )\n\t\t}\n\t\tsigma = var( data )\n\t\tmu = colSums( data ) / nrow( data )\n\t\tstarting.params = c( mu, sigma[1,1] )\n\t\tf( starting.params )\n\t\tparams = optim( starting.params, fn = f, control = list( trace = TRUE ) )\n\t\tprint( params )\n\t\tmu = params$par[1]\n\t\tsigma = matrix( params$par[c(2)], nrow = 1 )\n\t\tformat( mu, digits = 16 )\n\t\tformat( sigma, digits = 16 )\n\t\tformat( params$value, digits = 16 )\n\t\t\t*/\n\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, 3 ) ;\n\t\n\t\tstoppingCondition.reset() ;\n\t\tBOOST_CHECK_EQUAL( T.estimate_by_em( stoppingCondition ), true ) ;\n\t\tBOOST_CHECK_CLOSE( T.get_value_of_function(), -0.3457225488574268, relativeTolerancePercent ) ;\n\n#if DEBUG_MULTIVARIATE_T\n\t\tstd::cerr << \"test_multivariate_t_em(): data is:\\n\"\n\t\t\t<< data << \", estimated parameters are:\\n\"\n\t\t\t<< \"nu = \" << T.degrees_of_freedom() << \",\\n\"\n\t\t\t<< \"mean = \" << T.mean().transpose() << \",\\n\"\n\t\t\t<< \"sigma =\\n\" << T.sigma() << \".\\n\"\n\t\t\t<< \"log-likelihood = \" << T.get_value_of_function() << \".\\n\" ;\n\t\t\n#endif\n\t}\n\n\t{\n\t// data = matrix( c( 0.5, 0.5, 0.5, 0.6, 0.6, 0.5, 0.6, 0.6, 0.7, 0.54, 0.9, 0.4 ), ncol = 2, byrow = T )\n\t// nu = 3\n\t/* f <- function( params ) {\n\t\tmu = params[1:2] ;\n\t\tsigma = matrix( params[c(3,4,4,5)], nrow = 2, ncol = 2, byrow = T );\n\t\tmu = matrix( rep( mu, nrow( data )), nrow = nrow( data ), ncol = ncol( data ), byrow = T )\n\t\tD = data - mu\n\t\tcat( \"-----\\n\" ) ;\n\t\tprint( mu );\n\t\tprint( sigma ) ;\n\t\tll = sum( dmvt( D, sigma = sigma, df = nu, log = T ) )\n\t\treturn( -ll )\n\t}\n\tsigma = var( data )\n\tmu = colSums( data ) / nrow( data )\n\tstarting.params = c( mu, c( sigma[1,1], sigma[1,2], sigma[2,2] ) )\n\tf( starting.params )\n\tparams = optim( starting.params, fn = f, control = list( trace = TRUE ) )\n\tprint( params )\n\tmu = params$par[1]\n\tsigma = matrix( params$par[c(2)], nrow = 1 )\n\tformat( mu, digits = 16 )\n\tformat( sigma, digits = 16 )\n\tformat( params$value, digits = 16 )\n\t\t*/\n\n\t\tMatrix data( 6, 2 ) ;\n\t\tdata <<\n\t\t\t0.5, 0.5,\n\t\t\t0.5, 0.6,\n\t\t\t0.6, 0.5,\n\t\t\t0.6, 0.6,\n\t\t\t0.7, 0.54,\n\t\t\t0.9, 0.4\n\t\t;\n\t\t\n\t\t{\n#if DEBUG_MULTIVARIATE_T\n\t\t\tstd::cerr << \"==================================\\n\" ;\n#endif\n\t\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, infinity ) ;\n\t\t\tstoppingCondition.reset() ;\n\t\t\tT.estimate_by_em( stoppingCondition ) ;\n\n#if DEBUG_MULTIVARIATE_T\n\t\t\tstd::cerr << \"test_multivariate_t_em(): data is:\\n\"\n\t\t\t\t<< data << \", estimated parameters are:\\n\"\n\t\t\t\t<< \"nu = \" << T.degrees_of_freedom() << \",\\n\"\n\t\t\t\t<< \"mean = \" << T.mean().transpose() << \",\\n\"\n\t\t\t\t<< \"sigma =\\n\" << T.sigma() << \".\\n\"\n\t\t\t\t<< \"log-likelihood = \" << T.get_value_of_function() << \".\\n\" ;\n#endif\n\t\t}\n\n\t\t{\n#if DEBUG_MULTIVARIATE_T\n\t\t\tstd::cerr << \"==================================\\n\" ;\n#endif\n\t\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, 25 ) ;\n\n\t\t\tstoppingCondition.reset() ;\n\t\t\tbool converged = T.estimate_by_em( stoppingCondition ) ;\n\t\t\tBOOST_CHECK( converged ) ;\n\n#if DEBUG_MULTIVARIATE_T\n\t\t\tstd::cerr << \"test_multivariate_t_em(): data is:\\n\"\n\t\t\t\t<< data << \", estimated parameters are:\\n\"\n\t\t\t\t<< \"nu = \" << T.degrees_of_freedom() << \",\\n\"\n\t\t\t\t<< \"mean = \" << T.mean().transpose() << \",\\n\"\n\t\t\t\t<< \"sigma =\\n\" << T.sigma() << \".\\n\" ;\n#endif\n\t\t}\n\n\t\t{\n\t\t\t// data = matrix( c( 0.5, 0.5, 0.5, 0.6, 0.6, 0.5, 0.6, 0.6, 0.7, 0.54, 0.9, 0.4), ncol = 2, byrow = T )\n\t\t\t// nu = 3\n\t\t\t/* f <- function( params ) {\n\t\t\t\tmu = params[1:2] ;\n\t\t\t\tsigma = matrix( NA, nrow = 2, ncol = 2 );\n\t\t\t\tsigma[ lower.tri( sigma, diag = T) ] = params[3:5] ;\n\t\t\t\tsigma[upper.tri(sigma)] = t(sigma)[ upper.tri(sigma) ] ;\n\t\t\t\tmu = matrix( rep( mu, nrow( data )), nrow = nrow( data ), ncol = ncol( data ), byrow = T )\n\t\t\t\tD = data - mu\n\t\t\t\tprint( mu );\n\t\t\t\tprint( D );\n\t\t\t\tprint( sigma ) ;\n\t\t\t\tll = sum( dmvt( D, sigma = sigma, df = nu, log = T ) )\n\t\t\t\treturn( ll )\n\t\t\t}\n\t\t\tsigma = var( data )\n\t\t\tmu = colSums( data ) / nrow( data )\n\t\t\tstarting.params = c( mu, sigma[1,1], sigma[2,1], sigma[2,2] )\n\t\t\tf( starting.params )\n\t\t\tresult = optim( starting.params, fn = f, control = list( fnscale = -1, trace = TRUE, reltol = 1E-16 ) )\n\t\t\tparams = result$par\n\t\t\tprint( result )\n\t\t\tmu = params[1:2]\n\t\t\tsigma = matrix( params[c(3,4,4,5)], nrow = 2 )\n\t\t\tformat( mu, digits = 16 )\n\t\t\tformat( sigma, digits = 16 )\n\t\t\tformat( result$value, digits = 16 )\n\t\t\t*/\n\n#if DEBUG_MULTIVARIATE_T\n\t\t\tstd::cerr << \"==================================\\n\" ;\n#endif\n\t\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, 3 ) ;\n\t\t\tstoppingCondition.reset() ;\n\t\t\tbool converged = T.estimate_by_em( stoppingCondition ) ;\n\t\t\tBOOST_CHECK_EQUAL( converged, true ) ;\n\t\t\tBOOST_CHECK_CLOSE( T.get_value_of_function(), 12.11434601771716, relativeTolerancePercent ) ;\n\n#if DEBUG_MULTIVARIATE_T\n\t\t\tstd::cerr << \"test_multivariate_t_em(): data is:\\n\"\n\t\t\t\t<< data << \", estimated parameters are:\\n\"\n\t\t\t\t<< \"nu = \" << T.degrees_of_freedom() << \",\\n\"\n\t\t\t\t<< \"mean = \" << T.mean().transpose() << \",\\n\"\n\t\t\t\t<< \"sigma =\\n\" << T.sigma() << \".\\n\"\n\t\t\t\t<< \"log-likelihood= \" << T.get_value_of_function() << \".\\n\" ;\n#endif\t\t\t\n\t\t\tBOOST_CHECK_EQUAL( T.degrees_of_freedom(), 3 ) ;\n\t\t\tBOOST_CHECK_CLOSE( T.mean()(0), 0.6114408499165083, 1 ) ;\n\t\t\tBOOST_CHECK_CLOSE( T.mean()(1), 0.5378066642845329, 1 ) ;\n\t\t\tBOOST_CHECK_CLOSE( T.sigma()(0,0), 0.011982129787457576, 1 ) ;\n\t\t\tBOOST_CHECK_CLOSE( T.sigma()(0,1), -0.003818628929149581, 1 ) ;\n\t\t\tBOOST_CHECK_CLOSE( T.sigma()(1,0), -0.003818628929149581, 1 ) ;\n\t\t\tBOOST_CHECK_CLOSE( T.sigma()(1,1), 0.003392185410464222, 1 ) ;\n\t\t}\n\t}\n}\n\nstruct MonotonicCheck {\n\tMonotonicCheck( std::size_t max_iterations = 10000 ):\n\t\tm_max_iterations( max_iterations )\n\t{\n\t\treset() ;\n\t}\n\t\t\n\t// Return\n\tbool operator()( double value ) {\n\t\tBOOST_CHECK_GE( value, m_value ) ;\n\t\t++m_iteration ;\n\t\treturn( m_iteration > m_max_iterations ) ;\n\t}\n\n\tbool converged() const {\n\t\treturn false ;\n\t}\n\n\tvoid reset() {\n\t\tm_iteration = 0 ;\n\t\tm_value = -std::numeric_limits< double >::infinity() ;\n\t}\n\nprivate:\n\tstd::size_t const m_max_iterations ;\n\tstd::size_t m_iteration ;\n\tdouble m_value ;\n} ;\n\nAUTO_TEST_CASE( test_em_is_monotonic ) {\n\tMonotonicCheck monotonicCheck( 1000 ) ;\n\tMatrix data( 16, 2 ) ;\n\tdata <<\n\t\t0.5, 0.5,\n\t\t0.5, 0.6,\n\t\t0.6, 0.5,\n\t\t0.6, 0.6,\n\t\t0.7, 0.54,\n\t\t0.9, 0.4,\n\t\t0.1, 0.5,\n\t\t0.25, 0.7,\n\t\t0.1, 0.1,\n\t\t0.15, 0.9,\n\t\t0.2, 0.3,\n\t\t0.5, 0.55,\n\t\t0.4, 0.44,\n\t\t0.3, 0.33,\n\t\t0.2, 1,\n\t\t0.1, 0.15\n\t;\n\t\n\tfor( std::size_t nu = 1; nu < 10; ++nu ) {\n\t\tmonotonicCheck.reset() ;\n\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, nu ) ;\n\t\tT.estimate_by_em( monotonicCheck ) ;\n\t}\n}\n\nAUTO_TEST_CASE( test_regularised_em ) {\n\tdouble const likelihoodTolerance = 0.0000001 ;\n\tMatrix data( 1, 2 ) ;\n\tdata <<\n\t\t0.5, 0.5\n\t;\n\t{\n\t\tmetro::ValueStabilisesStoppingCondition stoppingCondition( likelihoodTolerance ) ;\n\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, 1 ) ;\n\t\tbool converged = T.estimate_by_em( stoppingCondition ) ;\n\t\t// will not converge because only one observation\n\t\tBOOST_CHECK( converged == false ) ;\n\t}\n\n\t{\n\t\tmetro::ValueStabilisesStoppingCondition stoppingCondition( likelihoodTolerance ) ;\n\t\t// try regularised EM.\n\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, 1 ) ;\n\t\tbool converged = T.estimate_by_em(\n\t\t\tstoppingCondition,\n\t\t\tMatrix::Identity( 2, 2 ),\n\t\t\t1\n\t\t) ;\n\t\tBOOST_CHECK( converged == true ) ;\n\n\t\t// In effect two observations, one with identity sigma, one with sigma = 0.\n\t\tBOOST_CHECK_CLOSE( T.sigma()(0,0), 0.5, 0.01 ) ;\n\t\tBOOST_CHECK_CLOSE( T.sigma()(0,1), 0, 0.01 ) ;\n\t\tBOOST_CHECK_CLOSE( T.sigma()(1,1), 0.5, 0.01 ) ;\n#if DEBUG_MULTIVARIATE_T\n\t\t\tstd::cerr << \"test_multivariate_t_regularised_em(): data is:\\n\"\n\t\t\t\t<< data << \", estimated parameters are:\\n\"\n\t\t\t\t<< \"nu = \" << T.degrees_of_freedom() << \",\\n\"\n\t\t\t\t<< \"mean = \" << T.mean().transpose() << \",\\n\"\n\t\t\t\t<< \"sigma =\\n\" << T.sigma() << \".\\n\"\n\t\t\t\t<< \"log-likelihood= \" << T.get_value_of_function() << \".\\n\" ;\n#endif\t\t\t\n\t}\n\n\t// test a massive weight.\n\t{\n\t\tmetro::ValueStabilisesStoppingCondition stoppingCondition( likelihoodTolerance ) ;\n\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, 1 ) ;\n\t\tbool converged = T.estimate_by_em(\n\t\t\tstoppingCondition,\n\t\t\tMatrix::Identity( 2, 2 ),\n\t\t\t100000000\n\t\t) ;\n\t\tBOOST_CHECK( converged == true ) ;\n\t\t// Weight is so strong we should get back the prior\n\t\tBOOST_CHECK_CLOSE( T.sigma()(0,0), 1, 0.01 ) ;\n\t\tBOOST_CHECK_CLOSE( T.sigma()(0,1), 0, 0.01 ) ;\n\t\tBOOST_CHECK_CLOSE( T.sigma()(1,1), 1, 0.01 ) ;\n\t}\n}\n\nAUTO_TEST_CASE( test_loglikelihood_em_range ) {\n\tstd::vector< double > nu_values ;\n\tnu_values.push_back( 1 ) ;\n\tnu_values.push_back( 3 ) ;\n\tnu_values.push_back( std::numeric_limits< double >::infinity() ) ;\n\t\n\tfor( std::size_t i = 0; i < nu_values.size(); ++i ) {\n\t\tdouble nu = nu_values[i] ;\n\t\tdouble ll1 = 0, ll2 = 0 ;\n\t\tmetro::ValueStabilisesStoppingCondition stoppingCondition( 0.0000001 ) ;\n\t\t{\n\t\t\tMatrix data( 3, 2 ) ;\n\t\t\tdata <<\n\t\t\t\t0.5, 0.1,\n\t\t\t\t0.4, 0.2,\n\t\t\t\t0.2, 0.3\n\t\t\t;\n\n\t\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, nu ) ;\n\t\t\tstoppingCondition.reset() ;\n\t\t\tBOOST_CHECK( T.estimate_by_em( stoppingCondition ) ) ;\n\t\t\n\t\t\tll1 = T.get_value_of_function() ;\n\t\t}\n\n\t\t{\n\t\t\tMatrix data( 6, 2 ) ;\n\t\t\tdata <<\n\t\t\t\t0.5, 0.1,\n\t\t\t\t0.3, 0.1,\n\t\t\t\t0.4, 0.2,\n\t\t\t\t0.2, 0.3,\n\t\t\t\t0.45, -100,\n\t\t\t\t10000, 100000\n\t\t\t\n\t\t\t;\n\t\t\tmetro::DataSubset ranges ;\n\t\t\tranges.add( metro::DataRange( 0, 1 )) ;\n\t\t\tranges.add( metro::DataRange( 2, 4 )) ;\n\n\t\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T( data, nu ) ;\n\t\t\tstoppingCondition.reset() ;\n\t\t\tT.estimate_by_em( ranges, stoppingCondition ) ;\n\t\t\tll2 = T.get_value_of_function() ;\n\n#if DEBUG_MULTIVARIATE_T\n\t\t\tstd::cerr << \"test_multivariate_t_em_range ): data is:\\n\"\n\t\t\t\t<< data << \", estimated parameters are:\\n\"\n\t\t\t\t<< \"nu = \" << T.degrees_of_freedom() << \",\\n\"\n\t\t\t\t<< \"mean = \" << T.mean().transpose() << \",\\n\"\n\t\t\t\t<< \"sigma =\\n\" << T.sigma() << \".\\n\"\n\t\t\t\t<< \"log-likelihood= \" << T.get_value_of_function() << \".\\n\" ;\n#endif\n\t\t}\n\n\t\t// Nominally exactly the same, the computation has slight rounding\n\t\t// errors so gets a different value.\n\t\tBOOST_CHECK_CLOSE( ll1, ll2, 1E-10 ) ;\n\t}\n}\n\nAUTO_TEST_CASE( test_weighted_em ) {\n\tdouble const likelihoodTolerance = 0.0000001 ;\n\tmetro::ValueStabilisesStoppingCondition stoppingCondition( 0.0000001 ) ;\n\t{\n\t\tMatrix data1( 4, 2 ) ;\n\t\tdata1 <<\n\t\t\t0.5, 0.1,\n\t\t\t0.4, 0.2,\n\t\t\t0.3, 0.1,\n\t\t\t0.3, 0.1\n\t\t;\n\n\t\tMatrix data2( 3, 2 ) ;\n\t\tdata2 <<\n\t\t\t0.5, 0.1,\n\t\t\t0.4, 0.2,\n\t\t\t0.3, 0.1\n\t\t;\n\t\tVector weights = Vector::Constant( 3, 1 ) ;\n\t\tweights(2) = 2 ;\n\n\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T1( data1, 3 ) ;\n\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T2( data1, Vector::Constant( 4, 1 ), 3 ) ;\n\t\tmetro::likelihood::MultivariateT< double, Vector, Matrix > T3( data2, weights, 3 ) ;\n\n\t\tT1.estimate_by_em( stoppingCondition ) ;\n\t\tstoppingCondition.reset() ;\n\t\tT2.estimate_by_em( stoppingCondition ) ;\n\t\tstoppingCondition.reset() ;\n\t\tT3.estimate_by_em( stoppingCondition ) ;\n\t\tstoppingCondition.reset() ;\n\n\t\tBOOST_CHECK_CLOSE( T1.get_value_of_function(), T2.get_value_of_function(), likelihoodTolerance ) ;\n\t\tBOOST_CHECK_CLOSE( T1.get_value_of_function(), T3.get_value_of_function(), likelihoodTolerance ) ;\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f73a00a2c55bf4bff50995afa8e6b73a2813b90b", "size": 17365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metro/test/test_multivariate_t.cpp", "max_stars_repo_name": "CreRecombinase/qctool", "max_stars_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "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_multivariate_t.cpp", "max_issues_repo_name": "CreRecombinase/qctool", "max_issues_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "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_multivariate_t.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": 29.0384615385, "max_line_length": 107, "alphanum_fraction": 0.6024186582, "num_tokens": 6337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5349364030415393}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n\nusing Vec2f = Eigen::Vector2f;\nusing Vec3f = Eigen::Vector3f;\nusing Vec4f = Eigen::Vector4f;\n\nusing Mat2f = Eigen::Matrix2f;\nusing Mat3f = Eigen::Matrix3f;\nusing Mat4f = Eigen::Matrix4f;\n\nusing Vec2d = Eigen::Vector2d;\nusing Vec3d = Eigen::Vector3d;\nusing Vec4d = Eigen::Vector4d;\n\nusing Mat2d = Eigen::Matrix2d;\nusing Mat3d = Eigen::Matrix3d;\nusing Mat4d = Eigen::Matrix4d;\n\nMat4d perspectiveMatrix(double fovRad, double near, double far);\n\nMat4d cameraMatrix(Vec3d from, Vec3d to, Vec3d up);\n\nMat4d transformationMatrix(const Vec3d& pos, const Vec3d& eulerAngles = Vec3d(0.0, 0.0, 0.0));", "meta": {"hexsha": "7afbd7dbc54bf2f63dba821ba66674005089cc54", "size": 628, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "glfw-test/matutils.hpp", "max_stars_repo_name": "Hyrtsi/glxblt", "max_stars_repo_head_hexsha": "3ca54a5b83e69e4d429ef22226d258296df14c23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "glfw-test/matutils.hpp", "max_issues_repo_name": "Hyrtsi/glxblt", "max_issues_repo_head_hexsha": "3ca54a5b83e69e4d429ef22226d258296df14c23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "glfw-test/matutils.hpp", "max_forks_repo_name": "Hyrtsi/glxblt", "max_forks_repo_head_hexsha": "3ca54a5b83e69e4d429ef22226d258296df14c23", "max_forks_repo_licenses": ["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.1538461538, "max_line_length": 94, "alphanum_fraction": 0.7420382166, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5349363965784111}}
{"text": "#include <boost/graph/adjacency_list.hpp> \nusing namespace boost; \ntypedef boost::adjacency_list<\n\t\t\t\t\t\t\t\tlistS, //std::list is a container that supports constant time insertion and removal of elements from anywhere\n \t\t\t\t\t\t\t\tvecS, //std::vector is a sequence container that encapsulates dynamic size arrays.\n\t\t\t\t\t\t\t \tdirectedS //directed_selector \n\t\t\t\t\t\t\t > mygraph; \n\nint main() \n{ \n\tmygraph g; \n\t//Adds edge (u,v) to the graph and returns the edge descriptor for the new edge. \n\tadd_edge(0, 1, g); \n\tadd_edge (0, 3, g); \n\tadd_edge (1, 2, g); \n\tadd_edge (2, 3, g); \n}", "meta": {"hexsha": "9096be683590df3e6170e9ce36ead57bfb1370cd", "size": 568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "1Creating_a_directed_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": "1Creating_a_directed_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": "1Creating_a_directed_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": 33.4117647059, "max_line_length": 117, "alphanum_fraction": 0.6795774648, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6370307806984445, "lm_q1q2_score": 0.5349363747851821}}
{"text": "//#include <cmath>\n#include <stdexcept>\n#include <fstream>\n#include <ostream>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/vector.hpp>\n\n#include <algorithm>\n#include <ext/algorithm> // is_sorted\n#include <iterator>\n#include <functional>\n\n#include <boost/typeof/typeof.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/type_traits.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/timer.hpp>\n#include <boost/range.hpp>\n#include <boost/utility.hpp>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <boost/math/tools/precision.hpp>\n#include <boost/standard_distribution/distributions/normal.hpp>         //prior\n#include <boost/standard_distribution/distributions/exponential.hpp>    //data\n\n#include <boost/statistics/empirical_cdf/algorithm/sequential_kolmogorov_smirnov_distance.hpp>\n\n#include <boost/dist_random/include.hpp>\n\n#include <boost/statistics/model/include.hpp>\n#include <boost/statistics/survival/data/include.hpp>\n#include <boost/statistics/survival/model/models/exponential/include.hpp>\n\n#include <libs/statistics/survival/data/example/random.h>\n\nvoid example_random(\n    const unsigned&      n_records,          // = 1e2;\n    const unsigned&      n_batches,           // = 5e4;\n    const double&        mu,                // = 0.0;\n    const double&        sigma,             // = 5.0;\n    const double&        t,                 // = 0.0\n    const double&        delta_t,           // = 0.0\n    const std::string&   out_path,\n    std::ostream& out\n){\n    out << \"-> example_random : \"; \n    out.flush();\n    \n    using namespace boost;\n    using namespace statistics;\n    namespace surv = survival;\n\n    // Generates batches of iid random records as follows:\n    // 1) The parameter is generated, for each batch, given a prior.\n    // 2) The covariates are generated in cyclic fashion within each batch\n    // 3) Data is generated given model, parameter, covariate, entry time.\n    // KS distances are computed for each batch of data\n    // Each batch is saved using serialization\n\n    // Types \n    typedef std::string                                     str_;\n    typedef double                                          val_;\n    typedef std::vector<val_>                               vals_;\n    typedef boost::mt19937                                  urng_;\n\n    // Covariates values\n    typedef val_                                            x_;\n\n    // Model\n    typedef math::normal_distribution<val_>                 mprior_;\n    typedef val_                                            par_;\n    typedef surv::model::exponential::model<val_>           model_;\n    typedef model::model_covariate_parameter_<model_,x_,par_> mcp_;\n\n    // Output\n    typedef boost::archive::text_oarchive                   oa_;\n    typedef std::ofstream                                   ofs_;\n\n    // [Constants]\n    const unsigned      k                   = 2;        // # number x values\n    const unsigned      n_ks_data           = n_records/k;\n\n    BOOST_ASSERT( n_records % k == 0 );\n    BOOST_ASSERT( n_ks_data % (n_records/k) == 0 );\n    \n    // [ os ]\n    const str_ prior_path      = out_path + \"prior\";\n    const str_ ks_path         = out_path + \"ks_data\";\n    const str_ xpm_mngr_path   = out_path + \"covariates_prior_model_mngr\";\n    const str_ pr_mngrs_path   = out_path + \"par_records_mngrs_path\";\n    \n    // [ covariates - model ]\n     typedef surv::data::default_covariates_model_mngr<x_,model_>  \n        xm_mngr_;\n     typedef surv::data::default_covariates_prior_model_mngr<x_,mprior_,model_>  \n        xpm_mngr_;\n    typedef surv::data::default_parameter_records_mngr<val_,par_> \n        pr_mngr_;\n\n    mprior_     mprior( mu, sigma ); \n        \n    xm_mngr_ xm_mngr;\n    xpm_mngr_ xpm_mngr;\n    {\n        vals_ x_vals;\n        {\n            using namespace boost::assign;\n            x_vals += -0.5, 0.5;\n        }\n        BOOST_ASSERT(size(x_vals) == k);\n        typedef xpm_mngr_::prior_model_wrapper_type pm_;\n        xpm_mngr =  xpm_mngr_(\n            boost::begin( x_vals ),\n            boost::end( x_vals ),\n            pm_(mprior,model_())\n        );\n    }\n    {\n        ofs_    ofs(xpm_mngr_path.c_str());\n        oa_     oa(ofs);\n        oa      << xpm_mngr;\n        ofs.flush();\n        ofs.close();\n    }\n\n    // [ par_records_mngr ]\n    pr_mngr_ pr_mngr;\n    \n    // [ Initialization ]\n    urng_       urng;\n\n    // Buffers\n    vals_ kss; \n    kss.reserve(n_ks_data);                             // kolmogorov-smirnov \n    vals_ fts; fts.reserve(n_records / k);              // failure times\n\n    {\n        ofs_    ofs_pr_mngrs(pr_mngrs_path.c_str());\n        surv::data::simulate_batches(\n            ofs_pr_mngrs,  \n            xpm_mngr, \n            n_batches,\n            n_records,\n            t,\n            delta_t,\n            urng\n        );\n    }\n\n/*\n    {\n        // Simulate batches of records\n        ofs_    ofs_ks(ks_path.c_str());\n        ofs_    ofs_pr_mngrs(pr_mngrs_path.c_str());\n        oa_     oa_pr_mngrs(ofs_pr_mngrs);\n        ofs_ks << \"first and last ks of the failure times : \" << std::endl;\n        for(unsigned i = 0; i<n_batches; i++){\n            //records.clear();\n            par_ par = boost::sample(mprior,urng);\n\n            pr_mngr.clear_records();\n            pr_mngr.set_parameter( par );\n            pr_mngr.back_generate(\n                n_records,\n                xm_mngr,\n                t,\n                delta_t,\n                urng\n            );\n\n            {\n                oa_pr_mngrs << pr_mngr; \n            }\n            \n            // Verify that the empirical distribution of failure times agrees\n            // with their assumed distribution\n            typedef surv::data::meta_failure_distribution<model_>   meta_fd_;\n            typedef meta_fd_::type                                  fd_;\n            if(n_ks_data>0){   \n                ofs_ks << (format(\"batch %1%, \")%i).str() << std::endl;\n                for(unsigned i = 0; i<k; i++){\n                    ofs_ks << (format(\"x[%1%] : \")%i).str();\n                    fts.clear();\n                    \n                    surv::data::failure_times<k>(\n                        boost::begin(pr_mngr.records()),\n                        boost::end(pr_mngr.records()),\n                        i,\n                        std::back_inserter(fts)\n                    );\n                    mcp_ mcp(\n                        xm_mngr.model_wrapper(),\n                        xm_mngr.x_values()[i],\n                        par\n                    );\n                    fd_ fail_dist = surv::data::make_failure_distribution(mcp);\n\n                    kss.clear();\n                    statistics::empirical_cdf\n                     ::sequential_kolmogorov_smirnov_distance(\n                        fail_dist,\n                        boost::begin( fts ),\n                        boost::end( fts ),\n                        n_ks_data,\n                        std::back_inserter( kss )\n                    );\n \n                    if(n_ks_data>1){\n                        // Desired result: kss[0] > kss.back();\n                        ofs_ks << kss[0] << ',' << kss.back();\n                    }\n                    ofs_ks << std::endl;\n                    ofs_ks.flush();\n                }\n            }\n        } // batch loop\n        ofs_ks.close();\n        ofs_pr_mngrs.close();\n    } // records generation\n*/\n    \n}", "meta": {"hexsha": "8083df87e743a44423e22e4eea77152c20614a46", "size": 7570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "survival_data copy/libs/statistics/survival/data/example/random.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": "survival_data copy/libs/statistics/survival/data/example/random.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": "survival_data copy/libs/statistics/survival/data/example/random.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.3480176211, "max_line_length": 94, "alphanum_fraction": 0.5180977543, "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5348781853831446}}
{"text": "// Run like this\n// ./loglikelihood4 competition/S1a/dataset13_training.csv  --use_ldl\n// This code will forecast 4 unknown parameters of the Matern covariance matrix\n// Developed by Alexander Litvinenko (RWTH Aachen) and Ronald Kriemann (MIS MPG Leipzig)\n// Based on the HLIBPro library (v. 2.9) www.hlibpro.com\n// No warranties.\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <stdio.h>\n#include <stdlib.h>\n\n\n#include <boost/format.hpp>\n#include <boost/program_options.hpp>\n\n#include <gsl/gsl_multimin.h>\n\n#include \"hlib.hh\"\n\nusing namespace HLIB;\nusing namespace boost::program_options;\n\nenum {\n    IDX_SIGMA  = 0,\n    IDX_LENGTH = 1,\n    IDX_NU     = 2,\n    IDX_TAU     = 3\n};\n\n// global options\nint        nmin      = CFG::Cluster::nmin;\ndouble     eps       = 1e-6;\ndouble     fac_eps   = 1e-6;\ndouble     shift     = 1e-8;\nbool       use_ldl   = false;\n\n//\n// read dataset from file\n//\nvoid\nread_data ( const std::string &       datafile,\n            std::vector< T2Point > &  vertices,\n            BLAS::Vector< double > &  Z_data )\n{\n    std::ifstream  in( datafile );\n    \n    if ( ! in ) // error\n        exit( 1 );\n\n    size_t  N_vtx = 0;\n    \n    #if 1\n\n    std::string  line;\n    \n    std::getline( in, line );\n\n    if ( line == \"x,y,values\" )\n    {\n        std::list< T2Point >  pos;\n        std::list< double >   vals;\n\n        while ( std::getline( in, line ) )\n        {\n            auto    parts = split( line, \",\" );\n            double  x = atof( parts[0].c_str() );\n            double  y = atof( parts[1].c_str() );\n            double  v = atof( parts[2].c_str() );\n            \n            pos.push_back( T2Point( x, y ) );\n            vals.push_back( v );\n        }// while\n\n        N_vtx = pos.size();\n\n        std::cout << N_vtx << std::endl;\n        \n        vertices.resize( N_vtx );\n        Z_data = BLAS::Vector< double >( N_vtx );\n\n        int  i = 0;\n\n        for ( auto  p : pos )\n            vertices[ i++ ] = p;\n\n        i = 0;\n        \n        for ( auto  v : vals )\n            Z_data( i++ ) = v;\n    }// if\n    else\n        HERROR( ERR_NOT_IMPL, \"\", \"\" );\n    \n    #else\n    \n    in >> N_vtx;\n\n    std::cout << \"reading \" << N_vtx << \" datapoints\" << std::endl;\n    \n    vertices.resize( N_vtx );\n    Z_data = BLAS::Vector< double >( N_vtx );\n        \n    for ( idx_t  i = 0; i < idx_t(N_vtx); ++i )\n    {\n        int     index = i;\n        double  x, y, z;\n        double  v     = 0.0;\n\n        in >> index >> x >> y >> z >> v;\n\n        vertices[ index ] = T2Point( x, y );\n        Z_data( index )   = v;\n    }// for\n\n    #endif\n    \n    //\n    // for visualization of data, export 2D points with v value in csv file\n    //\n\n    std::ofstream  out( \"data.csv\" );\n\n    out << \"x,y,z,v\" << std::endl;\n    \n    for ( uint  i = 0; i < N_vtx; ++i )\n        out << vertices[i].x() << \",\" << vertices[i].y() << \",0,\" << Z_data( i ) << std::endl;\n}\n\n//\n// define LogLikeliHood Problem to be evaluated at theta by minimization function\n//\nstruct LogLikeliHoodProblem\n{\n    std::vector< T2Point >                vertices;\n    std::unique_ptr< TCoordinate >        coord;\n    std::unique_ptr< TClusterTree >       ct;\n    std::unique_ptr< TBlockClusterTree >  bct;\n    std::unique_ptr< TVector >            Z;\n\n    LogLikeliHoodProblem ( const std::string &  datafile )\n    {\n        init( datafile );\n    }\n\n    void\n    init ( const std::string &  datafile )\n    {\n        BLAS::Vector< double >  Z_data;\n\n        read_data( datafile, vertices, Z_data );\n\n        coord = std::make_unique< TCoordinate >( vertices );\n\n        TAutoBSPPartStrat  part_strat;\n        TBSPCTBuilder      ct_builder( & part_strat, nmin );\n    \n        ct = ct_builder.build( coord.get() );\n    \n        TStdGeomAdmCond    adm_cond( 2.0, use_min_diam );\n        TBCBuilder         bct_builder;\n    \n        bct = bct_builder.build( ct.get(), ct.get(), & adm_cond );\n\n        Z   = std::make_unique< TScalarVector >( *ct->root(), std::move( Z_data ) );\n\n        ct->perm_e2i()->permute( Z.get() );\n    }\n    \n  \n\n    double\n    eval ( const double  sigma,\n           const double  length,\n           const double  nu,\n           const double tau )\n    {\n        TMaternCovCoeffFn< T2Point >  matern_coefffn( 2.0/pow(1.1,sigma), 1.0/pow(1.5,length), 1.0/pow(1.2, nu),  vertices );\n       // TMaternCovCoeffFn< T2Point >  matern_coefffn( sigma, length, nu,  vertices );\n        TPermCoeffFn< double >        coefffn( & matern_coefffn, ct->perm_i2e(), ct->perm_i2e() );\n\n        TACAPlus< double >            aca( & coefffn );\n        auto                          acc = fixed_prec( eps );\n        TDenseMatBuilder< double >    h_builder( & coefffn, & aca );\n    \n        auto                          C        = h_builder.build( bct.get(), acc );\n\n        if ( shift != 0.0 )\n        {\n           // std::cout << \"Diagonal is added!!!!!!!!!!\" << std::endl;\n            add_identity( C.get(), 1/pow(2.0,tau) );\n        }\n\n        auto                          fac_acc  = fixed_prec( fac_eps );\n        auto                          C_fac    = C->copy();\n        auto                          fac_opts = fac_options_t{ point_wise, CFG::Arith::storage_type, false };\n    \n        if ( use_ldl )\n            ldl( C_fac.get(), fac_acc, fac_opts );\n        else\n            chol( C_fac.get(), fac_acc );\n    \n        std::unique_ptr< TFacInvMatrix >   C_inv;\n\n        if ( use_ldl )\n            C_inv = std::make_unique< TLDLInvMatrix >( C_fac.get(), symmetric, point_wise );\n        else\n            C_inv = std::make_unique< TLLInvMatrix >( C_fac.get(), symmetric );\n        \n        const size_t                  N     = vertices.size();\n        double                        log_det_C = 0.0;\n    \n        for ( idx_t  i = 0; i < idx_t(N); ++i )\n        {\n            if ( use_ldl ) log_det_C +=   std::log( C_fac->entry( i, i ) );\n            else           log_det_C += 2*std::log( C_fac->entry( i, i ) ); // two factors L!\n        }// if\n        \n        TStopCriterion                sstop( 250, 1e-16, 0.0 );\n        TCG                           solver( sstop );\n        auto                          sol = C->row_vector();\n    \n        solver.solve( C.get(), sol.get(), Z.get(), C_inv.get() );\n        \n        auto                          ZdotCZ = std::real( Z->dot( sol.get() ) );\n        const double                  log2pi = std::log( 2.0 * Math::pi<double>() );\n        auto                          LL     = -0.5 * ( N * log2pi + log_det_C + ZdotCZ );\n\n        return LL;\n    }\n};\n\n//\n// wrapper from GSL to LogLikeliHoodProblem\n//\ndouble\neval_logli ( const gsl_vector *  param,\n             void *              data )\n{\n    double sigma  = gsl_vector_get( param, IDX_SIGMA );\n    double length = gsl_vector_get( param, IDX_LENGTH );\n    double nu     = gsl_vector_get( param, IDX_NU );\n    double tau    = gsl_vector_get( param, IDX_TAU );\n\n    LogLikeliHoodProblem *  problem = static_cast< LogLikeliHoodProblem * >( data );\n\n    return - problem->eval( sigma, length, nu, tau );\n}\n\n//\n// optimization function using GSL\n//\ndouble\nmaximize_likelihood ( double &                sigma,\n                      double &                length,\n                      double &                nu,\n                      double &                tau,\n                      LogLikeliHoodProblem &  problem )\n{\n    int        status   = 0;\n    const int  max_iter = 500;\n\n    const gsl_multimin_fminimizer_type *  T = gsl_multimin_fminimizer_nmsimplex2;\n    gsl_multimin_fminimizer *             s = NULL;\n    gsl_vector *                          ss;\n    gsl_vector *                          x;\n    gsl_multimin_function                 minex_func;\n    double                                size;\n\n    x = gsl_vector_alloc( 4 );        // start value\n    gsl_vector_set( x, IDX_SIGMA,  sigma );\n    gsl_vector_set( x, IDX_LENGTH, length );\n    gsl_vector_set( x, IDX_NU,     nu );\n    gsl_vector_set( x, IDX_TAU,    tau );\n\n    ss = gsl_vector_alloc( 4 );       // step sizes\n    gsl_vector_set( ss, IDX_SIGMA,  1.0 );\n    gsl_vector_set( ss, IDX_LENGTH, 1.0 );\n    gsl_vector_set( ss, IDX_NU,     1.0 );\n    gsl_vector_set( ss, IDX_TAU,    1.0 );\n    //gsl_vector_set( ss, IDX_SIGMA,  0.05 );\n    //gsl_vector_set( ss, IDX_LENGTH, 0.005 );\n    //gsl_vector_set( ss, IDX_NU,     0.01 );\n    //gsl_vector_set( ss, IDX_TAU,    1 );\n\n    // Initialize method and iterate\n    minex_func.n      = 4;\n    minex_func.f      = & eval_logli;\n    minex_func.params = & problem;\n\n    s = gsl_multimin_fminimizer_alloc( T, 4 );\n    gsl_multimin_fminimizer_set(s, & minex_func, x, ss );\n\n    int     iter = 0;\n    double  LL = 0;\n\n    do\n    {\n        iter++;\n        status = gsl_multimin_fminimizer_iterate( s );\n\n        if ( status != 0 )\n            break;\n\n        size   = gsl_multimin_fminimizer_size( s );    // return eps for stopping criteria\n        status = gsl_multimin_test_size( size, 1e-3 ); // This function tests the minimizer specific characteristic size \n\n        if ( status == GSL_SUCCESS )\n        {\n            std::cout << \"converged to minimum\" << std::endl;\n            FILE* f4 = fopen( \"111_S2b_results.txt\", \"a+\");\n           // fprintf(f4, \"sigma, ell, nu, tau\\n\"); //2.0/pow(1.1,sigma), 1.0/pow(1.5,length), 1.0/pow(1.2, nu),\n            fprintf(f4, \"& %.6f & %.6f & %.6f & %.6f & %.6f \\\\\\\\ \\\\hline \\n\", 2.0/pow(1.1, sigma), 1.0/pow(1.5,length), 1.0/pow(1.2,nu), 1.0/pow(2.0, tau), LL );\n            fclose(f4);\n        }\n\n        sigma  = gsl_vector_get( s->x, IDX_SIGMA );\n        length = gsl_vector_get( s->x, IDX_LENGTH );\n        nu     = gsl_vector_get( s->x, IDX_NU );\n        tau    = gsl_vector_get( s->x, IDX_TAU );\n        LL     = -s->fval;\n\n        std::cout << \"  loglikelihood at\" //2.0/pow(1.1,sigma), 1.0/pow(1.5,length), 1.0/pow(1.2, nu),\n                  << \"  \u03c3 = \" << 2.0/pow(1.1, sigma)\n                  << \", \u2113 = \" << 1.0/pow(1.5, length)\n                  << \", \u03bd = \" << 1.0/pow(1.2, nu)\n                  << \", tau = \" << 1.0/pow(2.0, tau)\n                  << \"   is \" << LL\n                  << std::endl;\n    } while (( status == GSL_CONTINUE ) && ( iter < max_iter ));\n\n    gsl_multimin_fminimizer_free( s );\n    gsl_vector_free( ss );\n    gsl_vector_free( x );\n\n    return LL;\n}\n\n//\n// main function\n//\nint\nmain ( int      argc,\n       char **  argv )\n{\n    INIT();\n    \n    std::string  datafile = \"datafile.txt\";\n    //Important ! sigma= 2.0/pow(1.1,sigma), length = 1.0/pow(1.5,length), 1.0/pow(1.2, nu),\n    double  sigma  = 1.0; //take these values from previous experiments (Part 1a)\n    double  length = 7.0; //means, cov length = 1/pow(1.5, 7)\n    double  nu     = 4.0; //means, nu = 1/pow(1.2, 2)\n    double  tau    = 20;\n    \n    //\n    // define command line options\n    //\n\n    options_description             all_opts;\n    options_description             vis_opts( \"usage: loglikelihood [options] datafile\\n  where options include\" );\n    options_description             hid_opts( \"Hidden options\" );\n    positional_options_description  pos_opts;\n    variables_map                   vm;\n\n    // standard options\n    vis_opts.add_options()\n        ( \"help,h\",                       \": print this help text\" )\n        ( \"threads,t\",   value<int>(),    \": number of parallel threads\" )\n        ( \"verbosity,v\", value<int>(),    \": verbosity level\" )\n        ( \"nmin\",        value<int>(),    \": set minimal cluster size\" )\n        ( \"eps,e\",       value<double>(), \": set H accuracy\" )\n        ( \"epslu\",       value<double>(), \": set only H factorization accuracy\" )\n        ( \"shift\",       value<double>(), \": regularization parameter\" )\n        ( \"ldl\",                          \": use LDL factorization\" )\n        ( \"sigma\",       value<double>(), \": sigma parameter\" )\n        ( \"nu\",          value<double>(), \": nu parameter\" )\n        ( \"length\",      value<double>(), \": length parameter\" )\n        ( \"tau\",         value<double>(), \": tau paramater\" )\n        ;\n    \n    hid_opts.add_options()\n        ( \"data\",        value<std::string>(), \": datafile defining problem\" )\n        ;\n\n    // options for command line parsing\n    all_opts.add( vis_opts ).add( hid_opts );\n\n    // all \"non-option\" arguments should be \"--data\" arguments\n    pos_opts.add( \"data\", -1 );\n\n    //\n    // parse command line options\n    //\n\n    try\n    {\n        store( command_line_parser( argc, argv ).options( all_opts ).positional( pos_opts ).run(), vm );\n        notify( vm );\n    }// try\n    catch ( required_option &  e )\n    {\n        std::cout << e.get_option_name() << \" requires an argument, try \\\"-h\\\"\" << std::endl;\n        exit( 1 );\n    }// catch\n    catch ( unknown_option &  e )\n    {\n        std::cout << e.what() << \", try \\\"-h\\\"\" << std::endl;\n        exit( 1 );\n    }// catch\n\n    //\n    // eval command line options\n    //\n\n    if ( vm.count( \"help\") )\n    {\n        std::cout << vis_opts << std::endl;\n        exit( 1 );\n    }// if\n\n    if ( vm.count( \"nmin\"      ) ) nmin     = vm[\"nmin\"].as<int>();\n    if ( vm.count( \"eps\"       ) ) eps      = vm[\"eps\"].as<double>();\n    if ( vm.count( \"epslu\"     ) ) fac_eps  = vm[\"epslu\"].as<double>();\n    if ( vm.count( \"shift\"     ) ) shift    = vm[\"shift\"].as<double>();\n    if ( vm.count( \"threads\"   ) ) CFG::set_nthreads( vm[\"threads\"].as<int>() );\n    if ( vm.count( \"verbosity\" ) ) CFG::set_verbosity( vm[\"verbosity\"].as<int>() );\n    if ( vm.count( \"ldl\"       ) ) use_ldl  = true;\n    if ( vm.count( \"sigma\"     ) ) sigma    = vm[\"sigma\"].as<double>();\n    if ( vm.count( \"nu\"        ) ) nu       = vm[\"nu\"].as<double>();\n    if ( vm.count( \"length\"    ) ) length   = vm[\"length\"].as<double>();\n    if ( vm.count( \"tau\"       ) ) tau      = vm[\"tau\"].as<double>();\n\n    // default to general eps\n    if ( fac_eps == -1 )\n        fac_eps = eps;\n    \n    if ( vm.count( \"data\" ) )\n        datafile = vm[\"data\"].as<std::string>();\n    else\n    {\n        std::cout << \"usage: loglikelihood [options] datafile\" << std::endl;\n        exit( 1 );\n    }// if\n\n\n    std::cout << \"initial parameters : \" << sigma << \", \" << nu << \", \" << length << \", \" << tau << std::endl;\n    \n    LogLikeliHoodProblem  problem( datafile );\n\n    auto  LL = maximize_likelihood( sigma, length, nu, tau, problem );\n\n    DONE();\n    \n}\n", "meta": {"hexsha": "df345dcaaa52e28eea013b8891323719499fd0bf", "size": 14254, "ext": "cc", "lang": "C++", "max_stars_repo_path": "loglikelihood4.cc", "max_stars_repo_name": "litvinen/large_random_fields", "max_stars_repo_head_hexsha": "c6eb60ee53171d296c02dd73d26476e072360f6c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-03T05:25:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T23:04:12.000Z", "max_issues_repo_path": "loglikelihood4.cc", "max_issues_repo_name": "litvinen/large_random_fields", "max_issues_repo_head_hexsha": "c6eb60ee53171d296c02dd73d26476e072360f6c", "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": "loglikelihood4.cc", "max_forks_repo_name": "litvinen/large_random_fields", "max_forks_repo_head_hexsha": "c6eb60ee53171d296c02dd73d26476e072360f6c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T11:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T11:27:29.000Z", "avg_line_length": 31.3274725275, "max_line_length": 161, "alphanum_fraction": 0.5009821804, "num_tokens": 4066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5348781785341964}}
{"text": "// http://www.boost.org/doc/libs/1_46_0/libs/graph/doc/topology.html\n\n//DistanceMetricConcept\n#include <cmath>\n\n#include <iostream>\n\n#include <boost/graph/grid_graph.hpp>\n\n#include \"NearestNeighbor/topological_search.hpp\"\n\nclass custom_topology\n{\npublic:\n  typedef float point_type;\n  typedef float point_difference_type;\n\n  /**\n    * Returns the distance between two points.\n    */\n  double distance(const point_type& a, const point_type& b) const \n  {\n    return fabs(a-b);\n  }\n\n};\n\nint main(int argc, char *argv[])\n{\n  typedef boost::grid_graph<2> GraphType;\n\n  const unsigned int dimension = 5;\n  boost::array<std::size_t, 2> lengths = { { dimension, dimension } };\n  GraphType graph(lengths);\n\n  typedef boost::graph_traits<GraphType>::vertex_descriptor VertexDescriptor;\n\n  typedef custom_topology TopologyType;\n  TopologyType myTopology;\n  typedef TopologyType::point_type PointType;\n\n  std::vector<PointType> vertexData(dimension * dimension);\n\n  // This is an \"exterior property\" of the grid_graph\n  typedef boost::property_map<GraphType, boost::vertex_index_t>::const_type IndexMapType;\n\n  IndexMapType indexMap(get(boost::vertex_index, graph));\n\n  typedef boost::iterator_property_map<std::vector<PointType>::iterator, IndexMapType> MapType;\n  MapType myMap(vertexData.begin(), indexMap);\n\n  typedef linear_neighbor_search<> SearchType;\n\n  // Add integer positions to the graph vertices.\n  // The experiment here is to query the nearest neighbor of a point like 5.2\n  // and ensure we get back 5.\n  unsigned int numberOfVertices = 10;\n  for(unsigned int vertexId = 0; vertexId < numberOfVertices; ++vertexId)\n  {\n    VertexDescriptor v = vertex(vertexId, graph);\n    std::cout << \"adding \" << vertexId << \" to \" << v[0] << \" \" << v[1] << std::endl;\n    PointType p = vertexId;\n\n    boost::put(myMap, v, p);\n  };\n\n  PointType queryPoint = 5.2;\n\n  SearchType search;\n\n  VertexDescriptor nearestNeighbor = search(queryPoint, graph, myTopology, myMap);\n\n  std::cout << \"nearestNeighbor: \" << nearestNeighbor[0] << \" \" << nearestNeighbor[1] << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "2621975d9338a0f8c47243a78a4869895f82000f", "size": 2076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NearestNeighbor/Tests/TestCustomTopology.cpp", "max_stars_repo_name": "jingtangliao/ff", "max_stars_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T07:59:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T18:11:46.000Z", "max_issues_repo_path": "NearestNeighbor/Tests/TestCustomTopology.cpp", "max_issues_repo_name": "jingtangliao/ff", "max_issues_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-24T09:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-24T14:45:46.000Z", "max_forks_repo_path": "NearestNeighbor/Tests/TestCustomTopology.cpp", "max_forks_repo_name": "jingtangliao/ff", "max_forks_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-01-11T15:10:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:02:10.000Z", "avg_line_length": 26.961038961, "max_line_length": 99, "alphanum_fraction": 0.7157996146, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6619228758499941, "lm_q1q2_score": 0.5348781738749364}}
{"text": "/* \n\nCopyright (c) 2020   Michael Borinsky\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \n\n*/\n\n#pragma once\n\n#include <vector>\n#include <Eigen/Dense>\n\n#include \"graph.hpp\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::LDLT;\n\ndouble get_laplacian( \n        MatrixXd& L,\n        const graph& g, \n        const vector<double>& X,\n        const edge_subgraph_type& contracted_subgraph,\n        int num_components,\n        const vector<int>& contracted_subgraph_components_map\n        )\n{\n    assert( X.size() == g._E );\n    assert( contracted_subgraph_components_map.size() == g._V );\n\n    int E = g._E;\n    int V = num_components;\n    \n    assert( L.rows() == V-1 && L.cols() == V-1 );\n\n    L.setZero( V-1, V-1 );\n\n    double Lambda = 1.;\n    for ( int j = 0; j < E; j++ )\n    {\n        if( contracted_subgraph[j] )\n            continue;\n\n        pair<int, int> edge;\n        int k,l,c;\n        tie(edge, c) = g._edges[j];\n        tie(k,l) = edge;\n\n        Lambda *= X[j];\n\n        k = contracted_subgraph_components_map[k];\n        l = contracted_subgraph_components_map[l];\n\n        if( k == l )\n            continue;\n\n        if ( k < l )\n            tie(k, l) = make_pair(l, k); \n\n        double x = 1. / X[j];\n\n        L(l,l) += x;\n\n        if( k == V - 1 ) // delete last row\n            continue;\n\n        L(k,k) +=  x;\n        L(k,l) += -x;\n        // only lower triangular part of the laplacian matters for ldlt. => Fill only lower triangular part.\n    }\n\n    return Lambda;\n}\n\nvoid get_P_matrix( \n        MatrixXd& P,\n        const graph& g, \n        const vector< VectorXd >& momenta,\n        int num_components,\n        const vector<int>& contracted_subgraph_components_map\n        )\n{\n    assert( contracted_subgraph_components_map.size() == g._V );\n    if( momenta.size() != g._V )\n    {\n        stringstream s;\n        s << \"P-matrix calculation - the graph \" << g << \" has \" << g._V << \" vertices, but only \" << momenta.size() << \" momenta were provided. An incoming momentum for each vertex is needed. Give a zero incoming momentum for internal vertices.)\";\n        throw domain_error(s.str());\n    }\n\n    int V = num_components;\n    P.setZero( V - 1, momenta[0].size() );\n    \n    for( int i = 0; i < g._V; i++ )\n    {\n        int v = contracted_subgraph_components_map[i];\n\n        if( v == V-1 )\n            continue;\n\n        P.row(v) += momenta[i].transpose();\n    }\n}\n\ndouble eval_psi_polynomial( \n        double Lambda, \n        const LDLT< MatrixXd >& ldlt \n        )\n{\n    double detL = ldlt.matrixL().determinant();\n    double detD = ldlt.vectorD().prod();\n\n    return detL * detL * detD * Lambda;\n}\n\ndouble eval_pphi_polynomial(\n        const MatrixXd& P,\n        const LDLT< MatrixXd >& ldlt\n        )\n{\n    return ( P.transpose() * ldlt.solve( P ) ).trace();\n}\n\ndouble eval_M_polynomial( \n        const graph& g, \n        const vector<double>& masses_sqr,\n        const vector<double>& X,\n        const edge_subgraph_type& contracted_subgraph\n        )\n{\n    if( masses_sqr.size() != g._E )\n    {\n        stringstream s;\n        s << \"m polynomial calculation - the graph \" << g << \" has \" << g._E << \" edges, but only \" << masses_sqr.size() << \" squared masses were given. A mass for each edge is needed. (It can be zero.)\";\n        throw domain_error(s.str());\n    }\n    \n    assert( g._E == X.size() );\n\n    double M = 0.;\n\n    for( int j = 0; j < g._E; j++ )\n    {\n        if( !contracted_subgraph[j] )\n            M += X[j] * masses_sqr[j];\n    }\n\n    return M;\n}\n\n\n", "meta": {"hexsha": "68be0244910b8c5df0edf501c02a07346bc8bbdf", "size": 4490, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "symanzik_polynomials.hpp", "max_stars_repo_name": "michibo/tropical-feynman-quadrature", "max_stars_repo_head_hexsha": "03553210637bb77bfb835ef41b79d14b37147413", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-08-31T11:14:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T14:26:49.000Z", "max_issues_repo_path": "symanzik_polynomials.hpp", "max_issues_repo_name": "michibo/tropical-feynman-quadrature", "max_issues_repo_head_hexsha": "03553210637bb77bfb835ef41b79d14b37147413", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "symanzik_polynomials.hpp", "max_forks_repo_name": "michibo/tropical-feynman-quadrature", "max_forks_repo_head_hexsha": "03553210637bb77bfb835ef41b79d14b37147413", "max_forks_repo_licenses": ["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.5987261146, "max_line_length": 461, "alphanum_fraction": 0.6031180401, "num_tokens": 1131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5348781731450403}}
{"text": "/*\n * This file is part of the Geneva library collection.\n *\n * See the NOTICE file in the top-level directory of the Geneva library\n * collection for a list of contributors and copyright information.\n *\n * The following license applies to the code IN THIS FILE:\n *\n * ***************************************************************************\n *\n * Boost Software License - Version 1.0 - August 17th, 2003\n *\n * Permission is hereby granted, free of charge, to any person or organization\n * obtaining a copy of the software and accompanying documentation covered by\n * this license (the \"Software\") to use, reproduce, display, distribute,\n * execute, and transmit the Software, and to prepare derivative works of the\n * Software, and to permit third-parties to whom the Software is furnished to\n * do so, all subject to the following:\n *\n * The copyright notices in the Software and this entire statement, including\n * the above license grant, this restriction and the following disclaimer,\n * must be included in all copies of the Software, in whole or in part, and\n * all derivative works of the Software, unless such copies or derivative\n * works are solely in the form of machine-executable object code generated by\n * a source language processor.\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, TITLE AND NON-INFRINGEMENT. IN NO EVENT\n * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE\n * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n * ***************************************************************************\n *\n * NOTE THAT THE BOOST-LICENSE DOES NOT APPLY TO ANY OTHER FILES OF THE\n * GENEVA LIBRARY, UNLESS THIS IS EXPLICITLY STATED IN THE CORRESPONDING FILE!\n */\n\n#pragma once\n\n// Global checks, defines and includes needed for all of Geneva\n#include \"common/GGlobalDefines.hpp\"\n\n// Standard headers go here\n#include <cmath>\n#include <cstdlib>\n\n// Boost headers go here\n#include <boost/math/special_functions.hpp>\n\n// Geneva headers go here\n#include \"common/GExceptions.hpp\"\n#include \"common/GLogger.hpp\"\n#include \"common/GErrorStreamer.hpp\"\n\nnamespace Gem {\nnamespace Common {\n\n/******************************************************************************/\n\n/** @brief Calculates the acos value of a float value */\nG_API_COMMON float gacos(const float &);\n/** @brief Calculates the acos value of a double value */\nG_API_COMMON double gacos(const double &);\n\n/** @brief Calculates the asin value of a float value */\nG_API_COMMON float gasin(const float &);\n/** @brief Calculates the asin value of a double value */\nG_API_COMMON double gasin(const double &);\n\n/** @brief Calculates the tan value of a float value */\nG_API_COMMON float gtan(const float &);\n/** @brief Calculates the tan value of a double value */\nG_API_COMMON double gtan(const double &);\n\n/** @brief Calculates the tanh value of a float value */\nG_API_COMMON float gtanh(const float &);\n/** @brief Calculates the tanh value of a double value */\nG_API_COMMON double gtanh(const double &);\n\n/** @brief Calculates the atan value of a float value */\nG_API_COMMON float gatan(const float &);\n/** @brief Calculates the atan value of a double value */\nG_API_COMMON double gatan(const double &);\n\n/** @brief Calculates the sinh value of a float value */\nG_API_COMMON float gsinh(const float &);\n/** @brief Calculates the sinh value of a double value */\nG_API_COMMON double gsinh(const double &);\n\n/** @brief Calculates the cosh value of a float value */\nG_API_COMMON float gcosh(const float &);\n/** @brief Calculates the cosh value of a double value */\nG_API_COMMON double gcosh(const double &);\n\n/** @brief Calculates the ceil value of a float value */\nG_API_COMMON float gceil(const float &);\n/** @brief Calculates the ceil value of a double value */\nG_API_COMMON double gceil(const double &);\n\n/** @brief Calculates the maximum value of two float values */\nG_API_COMMON float gmax(const float &, const float &);\n/** @brief Calculates the maximum value of two double values */\nG_API_COMMON double gmax(const double &, const double &);\n\n/** @brief Calculates the minimum value of two float values */\nG_API_COMMON float gmin(const float &, const float &);\n/** @brief Calculates the minimum value of two double values */\nG_API_COMMON double gmin(const double &, const double &);\n\n/** @brief Calculates the floor value of a float value */\nG_API_COMMON float gfloor(const float &);\n/** @brief Calculates the floor value of a double value */\nG_API_COMMON double gfloor(const double &);\n/** @brief Calculates the floor value of a double value */\nG_API_COMMON long double gfloor(const long double &);\n\n/** @brief Calculates the fabs value of a float value */\nG_API_COMMON float gfabs(const float &);\n/** @brief Calculates the fabs value of a double value */\nG_API_COMMON double gfabs(const double &);\n/** @brief Calculates the fabs value of a long double value */\nG_API_COMMON long double gfabs(const long double &);\n\n/** @brief Calculates the abs value of an int value */\nG_API_COMMON int giabs(const int &);\n/** @brief Calculates the abs value of a long int value */\nG_API_COMMON long giabs(const long &);\n\n/** @brief Calculates the sqrt value of a float value */\nG_API_COMMON float gsqrt(const float &);\n/** @brief Calculates the sqrt value of a double value */\nG_API_COMMON double gsqrt(const double &);\n\n/** @brief Calculates the sin value of a float value */\nG_API_COMMON float gsin(const float &);\n/** @brief Calculates the sin value of a double value */\nG_API_COMMON double gsin(const double &);\n\n/** @brief Calculates the cos value of a float value */\nG_API_COMMON float gcos(const float &);\n/** @brief Calculates the cos value of a double value */\nG_API_COMMON double gcos(const double &);\n\n/** @brief Calculates the log value of a float value */\nG_API_COMMON float glog(const float &);\n/** @brief Calculates the log value of a double value */\nG_API_COMMON double glog(const double &);\n\n/** @brief Calculates the log10 value of a float value */\nG_API_COMMON float glog10(const float &);\n/** @brief Calculates the log10 value of a double value */\nG_API_COMMON double glog10(const double &);\n\n/** @brief Calculates the pow value of a float value */\nG_API_COMMON float gpow(const float &, const float &);\n/** @brief Calculates the pow value of a double value */\nG_API_COMMON double gpow(const double &, const double &);\n\n/** @brief Calculates the hypot value of a float value */\nG_API_COMMON float ghypot(const float &, const float &);\n/** @brief Calculates the hypot value of a double value */\nG_API_COMMON double ghypot(const double &, const double &);\n\n/** @brief Performs alpha blending for floats */\nG_API_COMMON float gmix(const float &, const float &, const float &);\n/** @brief Performs alpha blending for doubles */\nG_API_COMMON double gmix(const double &, const double &, const double &);\n\n/** @brief Calculates the exp value of a float value */\nG_API_COMMON float gexp(const float &);\n/** @brief Calculates the exp value of a double value */\nG_API_COMMON double gexp(const double &);\n\n/** @brief Calculates the sign value of a float value */\nG_API_COMMON float gsign(const float &);\n/** @brief Calculates the sign value of a double value */\nG_API_COMMON double gsign(const double &);\n\n/** @brief A sigmoid function with user-defined minimum / maximum values (float version) */\nG_API_COMMON float gsigmoid(const float &, const float &, const float &);\n/** @brief A sigmoid function with user-defined minimum / maximum values (double version) */\nG_API_COMMON double gsigmoid(const double &, const double &, const double &);\n\n} /* namespace Common */\n} /* namespace Gem */\n", "meta": {"hexsha": "810487f6931e2aad66c83e5ca082fd7dd9de43a9", "size": 7871, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common/GCommonMathHelperFunctions.hpp", "max_stars_repo_name": "denisbertini/geneva", "max_stars_repo_head_hexsha": "eff76fc489001512022d1a20c5561623d73efc32", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-05-20T07:23:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T23:12:21.000Z", "max_issues_repo_path": "include/common/GCommonMathHelperFunctions.hpp", "max_issues_repo_name": "denisbertini/geneva", "max_issues_repo_head_hexsha": "eff76fc489001512022d1a20c5561623d73efc32", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-05-05T13:24:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-27T13:23:17.000Z", "max_forks_repo_path": "include/common/GCommonMathHelperFunctions.hpp", "max_forks_repo_name": "denisbertini/geneva", "max_forks_repo_head_hexsha": "eff76fc489001512022d1a20c5561623d73efc32", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-09T10:33:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T12:24:55.000Z", "avg_line_length": 41.6455026455, "max_line_length": 92, "alphanum_fraction": 0.7187142676, "num_tokens": 1649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5348781715453063}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/9/problem9.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem9 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem9::solve(12);\n        BOOST_CHECK_EQUAL(res, 60);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem9::solve();\n        BOOST_CHECK_EQUAL(res, 31875000);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "edae54ee504b42519dedbbea862d08372d817571", "size": 491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem9.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": "tests/1-50/test_problem9.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": "tests/1-50/test_problem9.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.380952381, "max_line_length": 49, "alphanum_fraction": 0.6741344196, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943822145997, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5348399244564307}}
{"text": "#ifndef MATRIX_DEFINITIONS_H_\n#define MATRIX_DEFINITIONS_H_\n\n#include <Eigen/Core>\n\nusing Matrix = Eigen::MatrixXd;\nusing Vector = Eigen::VectorXd;\nusing DiagonalMatrix = Eigen::DiagonalMatrix<double, Eigen::Dynamic>;\n\n#endif", "meta": {"hexsha": "cb2949ce95e4518378fad3affb02c89a3b0bbed2", "size": 225, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/chapter_nine/relu_convolution/include/matrix_definitions.hpp", "max_stars_repo_name": "PacktPublishing/Hands-On-Neural-Network-Programming-with-CPP", "max_stars_repo_head_hexsha": "c6b5041bc2beb6d0bf978095ee986b4239b43b28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-04-17T16:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T13:11:09.000Z", "max_issues_repo_path": "examples/chapter_three/backprop_example/include/matrix_definitions.hpp", "max_issues_repo_name": "PacktPublishing/Hands-On-Neural-Network-Programming-with-CPP", "max_issues_repo_head_hexsha": "c6b5041bc2beb6d0bf978095ee986b4239b43b28", "max_issues_repo_licenses": ["MIT"], "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/chapter_three/backprop_example/include/matrix_definitions.hpp", "max_forks_repo_name": "PacktPublishing/Hands-On-Neural-Network-Programming-with-CPP", "max_forks_repo_head_hexsha": "c6b5041bc2beb6d0bf978095ee986b4239b43b28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T11:56:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T01:13:39.000Z", "avg_line_length": 22.5, "max_line_length": 69, "alphanum_fraction": 0.7955555556, "num_tokens": 48, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5348399197667993}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 NumScale SAS\n  Copyright 2015 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#include <boost/simd/function/scalar/sinc.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/constant/mindenormal.hpp>\n\nSTF_CASE_TPL(\" sinc\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::sinc;\n\n  STF_EXPR_IS(sinc(T()),T);\n\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(sinc(bs::Inf<T>()), bs::Zero<T>(), 0.5);\n  STF_ULP_EQUAL(sinc(bs::Minf<T>()), bs::Zero<T>(), 0.5);\n  STF_ULP_EQUAL(sinc(bs::Nan<T>()), bs::Nan<T>(), 0.5);\n#endif\n  STF_ULP_EQUAL(sinc(-bs::Pio_2<T>()), T(2)/(bs::Pi<T>()), 0.5);\n  STF_ULP_EQUAL(sinc(-bs::Pio_4<T>()), bs::sin(bs::Pio_4<T>())/(bs::Pio_4<T>()), 0.5);\n  STF_ULP_EQUAL(sinc(bs::Pio_2<T>()),  T(2)/(bs::Pi<T>()), 0.5);\n  STF_ULP_EQUAL(sinc(bs::Pio_4<T>()), bs::sin(bs::Pio_4<T>())/(bs::Pio_4<T>()), 0.5);\n  STF_ULP_EQUAL(sinc(bs::Eps<T>()), bs::One<T>(), 0.5);\n  STF_ULP_EQUAL(sinc(bs::Mindenormal<T>()), bs::One<T>(), 0.5);\n  STF_ULP_EQUAL(sinc(bs::Zero<T>()), bs::One<T>(), 0.5);\n}\n", "meta": {"hexsha": "16729a924cd43a831cf1e1ef932d6d05656c1b1d", "size": 1723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/sinc.cpp", "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": "test/function/scalar/sinc.cpp", "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": "test/function/scalar/sinc.cpp", "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": 37.4565217391, "max_line_length": 100, "alphanum_fraction": 0.5873476494, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7057850216484837, "lm_q1q2_score": 0.5348399167351713}}
{"text": "#include \"testsuite.h\"\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n    Array<double,1> F(4);\n\n    F = -1.0, -2.0, -3.0, -4.0;\n\n    TinyVector<int,1> i = maxIndex(F);\n    double f = max(F);\n\n    BZTEST(i[0] == 0);\n    BZTEST(f == -1.0);\n    return 0;\n}\n\n", "meta": {"hexsha": "c966e7155af4c2cfbf1f51285348099a03290c18", "size": 275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/theodore-papadopoulo-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/theodore-papadopoulo-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/theodore-papadopoulo-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": 13.75, "max_line_length": 38, "alphanum_fraction": 0.5381818182, "num_tokens": 107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.5348399137035429}}
{"text": "// File       : gemm.cpp\n// Created    : Tue Oct 16 2018 10:45:45 AM (+0200)\n// Description: General Matrix-Matrix multiplication with ISPC\n// Copyright 2018 ETH Zurich. All Rights Reserved.\n#include <cassert>\n#include <iostream>\n#include <chrono>\n#include <string>\n#include <random>\n#include <cassert>\n#include <cstring>\n#include <cmath>\nusing namespace std;\n\n#include \"common.h\"\n#ifdef _USE_ISPC_\n#include \"gemm_sse2.h\" // kernel signature for the ISPC SSE2 code\n#include \"gemm_avx2.h\" // kernel signature for the ISPC AVX2 code\nusing namespace ispc;\n#endif /* _USE_ISPC_ */\n\n#ifdef _WITH_EIGEN_\n#include <Eigen/Core>\n\ntemplate <typename T>\nusing EMat = Eigen::Map< Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic, Eigen::RowMajor> >;\n\n// compiled in separate compilation unit with optimization flags tuned for\n// Haswell architecture, see the gemm_eigen.o target in the Makefile\nvoid gemm_eigen(const EMat<Real>&, const EMat<Real>&, EMat<Real>&);\n#endif /* _WITH_EIGEN_ */\n\n/**\n * @brief General matrix-matrix multiplication kernel (GEMM). Computes C = AB.\n * Naive implementation.\n *\n * @tparam T Real type parameter\n * @param A Matrix dimension p x r\n * @param B Matrix dimension r x q\n * @param C Matrix dimension p x q\n * @param p Dimensional parameter\n * @param r Dimensional parameter\n * @param q Dimensional parameter\n */\ntemplate <typename T>\nstatic void gemm_serial(const T* const A, const T* const B, T* const C,\n        const int p, const int r, const int q)\n{\n    for (int i = 0; i < p; ++i)\n        for (int j = 0; j < q; ++j)\n        {\n            T sum = 0.0;\n            for (int k = 0; k < r; ++k)\n                sum += A[i*r + k] * B[k*q + j]; // Note: The access pattern\n                                                // into matrix B is bad!\n            C[i*q + j] = sum;\n        }\n}\n\n/**\n * @brief General matrix-matrix multiplication kernel (GEMM). Computes C = AB.\n * Implementation with optimized memory access.\n *\n * @tparam T Real type parameter\n * @param A Matrix dimension p x r\n * @param B Matrix dimension r x q\n * @param C Matrix dimension p x q\n * @param p Dimensional parameter\n * @param r Dimensional parameter\n * @param q Dimensional parameter\n */\ntemplate <typename T>\nstatic void gemm_serial_tile(const T* const A, const T* const B, T* const C,\n        const int p, const int r, const int q)\n{\n    assert(q%_HTILE_ == 0);\n    assert(p%_VTILE_ == 0);\n    T tile[_VTILE_][_HTILE_]; // tmp storage to exploit temporal locality.\n                              // This must fit into L1 cache, otherwise\n                              // performance will degrade\n\n    // outer loops over dimension of matrix C.  Note the necessary stride on\n    // the loop counters because of our cached data structure tile (above).\n    for (int i = 0; i < p; i += _VTILE_)\n        for (int j = 0; j < q; j += _HTILE_)\n        {\n            // initialize tile to zero\n            for (int tv = 0; tv < _VTILE_; ++tv)\n                for (int th = 0; th < _HTILE_; ++th)\n                    tile[tv][th] = (T)0.0;\n\n            // start of inner product\n            for (int k = 0; k < r; ++k)\n            {\n                for (int tv = 0; tv < _VTILE_; ++tv)\n                {\n                    const T Aik = A[(i+tv)*r + k];\n                    for (int th = 0; th < _HTILE_; ++th)\n                        tile[tv][th] += Aik * B[k*q + j + th]; // Optimized memory access\n                                                               // for matrix B!\n                }\n            }\n\n            for (int tv = 0; tv < _VTILE_; ++tv)\n                for (int th = 0; th < _HTILE_; ++th)\n                    C[(i+tv)*q + j + th] = tile[tv][th]; // Optimized writes\n                                                         // into C also\n        }\n}\n\n/**\n * @brief Compute the Frobenius norm between the difference of two input\n * matrices\n *\n * @tparam T Real type parameter\n * @param M Test matrix dimension p x q\n * @param truth Reference matrix dimension p x q\n * @param p Dimensional parameter\n * @param q Dimensional parameter\n *\n * @return\n */\ntemplate <typename T>\nstatic T validate(const T* const M, const T* const truth,\n        const int p, const int q)\n{\n    T res = 0.0;\n    for (int i = 0; i < p; ++i)\n        for (int j = 0; j < q; ++j)\n        {\n            const T diff = M[i*q + j] - truth[i*q + j];\n            res += diff * diff;\n        }\n    return std::sqrt(res/(p*q));\n}\n\n/**\n * @brief Initialize matrices A and B to uniform random values\n *\n * @tparam T Real type parameter\n * @param A Matrix dimension p x r\n * @param B Matrix dimension r x q\n * @param p Dimensional parameter\n * @param r Dimensional parameter\n * @param q Dimensional parameter\n * @param seed Used for random number generator\n */\ntemplate <typename T>\nstatic void initialize(T* const A, T* const B,\n        const int p, const int r, const int q, const int seed=101)\n{\n    default_random_engine gen(seed);\n    uniform_real_distribution<T> dist(0.0, 1.0);\n    for (int i = 0; i < p; ++i)\n        for (int k = 0; k < r; ++k)\n            A[i*r + k] = dist(gen);\n\n    for (int k = 0; k < r; ++k)\n        for (int j = 0; j < q; ++j)\n            B[k*q + j] = dist(gen);\n}\n\n/**\n * @brief Benchmark a test kernel versus a baseline kernel\n *\n * @tparam T Real type parameter\n * @tparam MEMORY_OPTIMIZED Flag to switch between naive and memory optimized\n * base kernel\n * @tparam WITH_EIGEN Flag to enable Eigen kernel for benchmarking\n * @param p Dimensional parameter\n * @param r Dimensional parameter\n * @param q Dimensional parameter\n * @param func Function pointer to test kernel\n * @param test_name String to describe additional output\n */\ntemplate <typename T, bool MEMORY_OPTIMIZED=false, bool WITH_EIGEN=false>\nvoid benchmark(const int p, const int r, const int q,\n        void (*func)(const T* const, const T* const, T* const, const int, const int, const int),\n        const string test_name)\n{\n    T *A, *B, *C, *truth;\n    posix_memalign((void**)&A, 32, p*r*sizeof(T));\n    posix_memalign((void**)&B, 32, r*q*sizeof(T));\n    posix_memalign((void**)&C, 32, p*q*sizeof(T));\n    posix_memalign((void**)&truth, 32, p*q*sizeof(T));\n    typedef chrono::steady_clock Clock;\n\n    // initialize random matrices\n    initialize(A, B, p, r, q);\n    memset(C, 0, p*q*sizeof(T));\n    memset(truth, 0, p*q*sizeof(T));\n\n    // compute truth\n    auto t1 = Clock::now();\n    if (WITH_EIGEN)\n    {\n        (*func)(A, B, truth, p, r, q);\n    }\n    else\n    {\n        if (MEMORY_OPTIMIZED)\n            gemm_serial_tile(A, B, truth, p, r, q);\n        else\n            gemm_serial(A, B, truth, p, r, q);\n    }\n    auto t2 = Clock::now();\n    const double t_gold = chrono::duration_cast<chrono::nanoseconds>(t2 - t1).count();\n    const T norm_truth = validate(truth, C, p, q);\n\n    // test kernel\n#ifdef _WITH_EIGEN_\n    // Matrix wrappers\n    const EMat<T> Ap(A, p, r);\n    const EMat<T> Bp(B, r, q);\n    EMat<T> Cp(C, p, q);\n#endif /* _WITH_EIGEN_ */\n\n    auto tt1 = Clock::now();\n#ifdef _WITH_EIGEN_\n    if (WITH_EIGEN)\n        gemm_eigen(Ap, Bp, Cp);\n    else\n#endif /* _WITH_EIGEN_ */\n        (*func)(A, B, C, p, r, q);\n    auto tt2 = Clock::now();\n    const double t = chrono::duration_cast<chrono::nanoseconds>(tt2 - tt1).count();\n\n    // validate\n    const T diff = validate(C, truth, p, q);\n\n    cout << test_name << \":\" << endl;\n    cout << \"  Data type size:     \" << sizeof(T) << \" byte\" << endl;\n    cout << \"  Number of elements: A=\" << p*r << \"; B=\" << r*q << \"; C=\" << p*q << endl;\n    cout << \"  Norm of truth:      \" << norm_truth << endl;\n    cout << \"  Error:              \" << diff << endl;\n    cout << \"  Time reference:     \" << t_gold*1.0e-6 << \" millisec\" << endl;\n    cout << \"  Time test kernel:   \" << t*1.0e-6 << \" millisec\" << endl;\n    cout << \"  Speedup:            \" << t_gold/t << endl;\n\n    // clean up\n    free(A);\n    free(B);\n    free(C);\n    free(truth);\n}\n\n\nint main(void)\n{\n    // problem size:\n    // Matrix $A \\in\\mathbb{R}^{ p \\times r }$\n    // Matrix $B \\in\\mathbb{R}^{ r \\times q }$\n    // Matrix $C \\in\\mathbb{R}^{ p \\times q }$\n    //\n    // We solve C = A * B\n    constexpr int p = 512;\n    constexpr int r = 1024;\n    constexpr int q = 1024;\n\n    // benchmark serial case naive vs. memory optimized\n    benchmark<Real>(p, r, q, gemm_serial_tile, \"GEMM serial access optimized\");\n\n#ifdef _USE_ISPC_\n    // to be fair, we must use our best serial implementation to benchmark\n    // against the vectorized implementations --> use memory optimized version\n    // of serial GEMM\n    constexpr bool MEMORY_OPTIMIZED = true;\n    benchmark<Real,MEMORY_OPTIMIZED>(p, r, q, gemm_sse2, \"GEMM ISPC SSE2\");\n    benchmark<Real,MEMORY_OPTIMIZED>(p, r, q, gemm_avx2, \"GEMM ISPC AVX2\");\n#endif /* _USE_ISPC_ */\n\n#ifdef _WITH_EIGEN_\n    // benchmark against the Eigen library\n    constexpr bool USE_EIGEN = true;\n    benchmark<Real,true,USE_EIGEN>(p, r, q, gemm_avx2, \"GEMM Eigen vs. ISPC AVX2\");\n#endif /* _WITH_EIGEN_ */\n\n    return 0;\n}\n", "meta": {"hexsha": "eb8420b86000eb2d98bf93b46b5bc111f10e6306", "size": 8960, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HPCI/exercises/ex04/solution_code/ispc_gemm/gemm.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": "HPCI/exercises/ex04/solution_code/ispc_gemm/gemm.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": "HPCI/exercises/ex04/solution_code/ispc_gemm/gemm.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0, "max_line_length": 96, "alphanum_fraction": 0.5792410714, "num_tokens": 2572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.5348399043242805}}
{"text": "#include <boost/math/complex/asin.hpp>\n", "meta": {"hexsha": "31aa2c73abaf6d59e346796df8f73f6e2b0e7e71", "size": 39, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_complex_asin.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_complex_asin.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_complex_asin.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 19.5, "max_line_length": 38, "alphanum_fraction": 0.7692307692, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5346554317812959}}
{"text": "//\n// Copyright (c) 2018-2020 CNRS INRIA\n//\n\n#include \"pinocchio/spatial/fwd.hpp\"\n#include \"pinocchio/spatial/explog.hpp\"\n#include \"pinocchio/algorithm/regressor.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/frames.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/center-of-mass.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_kinematic_regressor_joint)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model; buildModels::humanoidRandom(model);\n  \n  pinocchio::Data data(model);\n  pinocchio::Data data_ref(model);\n  \n  model.lowerPositionLimit.head<7>().fill(-1.);\n  model.upperPositionLimit.head<7>().fill(1.);\n  \n//  const std::string joint_name = \"larm5_joint\";\n//  const JointIndex joint_id = model.getJointId(joint_name);\n  \n  const VectorXd q = randomConfiguration(model);\n  \n  forwardKinematics(model,data,q);\n  \n  const double eps = 1e-8;\n  for(JointIndex joint_id = 1; joint_id < (JointIndex)model.njoints; ++joint_id)\n  {\n    Data::Matrix6x kinematic_regressor_L(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_LWA(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_W(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    \n    Data::Matrix6x kinematic_regressor_L_fd(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_LWA_fd(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_W_fd(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    \n    computeJointKinematicRegressor(model, data, joint_id, LOCAL, kinematic_regressor_L);\n    computeJointKinematicRegressor(model, data, joint_id, LOCAL_WORLD_ALIGNED, kinematic_regressor_LWA);\n    computeJointKinematicRegressor(model, data, joint_id, WORLD, kinematic_regressor_W);\n    \n    Model model_plus = model; Data data_plus(model_plus);\n    const SE3 & oMi = data.oMi[joint_id];\n    const SE3 Mi_LWA = SE3(oMi.rotation(),SE3::Vector3::Zero());\n    const SE3 & oMi_plus = data_plus.oMi[joint_id];\n    for(int i = 1; i < model.njoints; ++i)\n    {\n      Motion::Vector6 v = Motion::Vector6::Zero();\n      const SE3 & M_placement = model.jointPlacements[(JointIndex)i];\n      SE3 & M_placement_plus = model_plus.jointPlacements[(JointIndex)i];\n      for(Eigen::DenseIndex k = 0; k < 6; ++k)\n      {\n        v[k] = eps;\n        M_placement_plus = M_placement * exp6(Motion(v));\n        \n        forwardKinematics(model_plus,data_plus,q);\n        \n        const Motion diff_L = log6(oMi.actInv(oMi_plus));\n        kinematic_regressor_L_fd.middleCols<6>(6*(i-1)).col(k) = diff_L.toVector()/eps;\n        const Motion diff_LWA = Mi_LWA.act(diff_L);\n        kinematic_regressor_LWA_fd.middleCols<6>(6*(i-1)).col(k) = diff_LWA.toVector()/eps;\n        const Motion diff_W = oMi.act(diff_L);\n        kinematic_regressor_W_fd.middleCols<6>(6*(i-1)).col(k) = diff_W.toVector()/eps;\n        v[k] = 0.;\n      }\n      \n      M_placement_plus = M_placement;\n    }\n    \n    BOOST_CHECK(kinematic_regressor_L.isApprox(kinematic_regressor_L_fd,sqrt(eps)));\n    BOOST_CHECK(kinematic_regressor_LWA.isApprox(kinematic_regressor_LWA_fd,sqrt(eps)));\n    BOOST_CHECK(kinematic_regressor_W.isApprox(kinematic_regressor_W_fd,sqrt(eps)));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_kinematic_regressor_joint_placement)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model; buildModels::humanoidRandom(model);\n  \n  pinocchio::Data data(model);\n  pinocchio::Data data_ref(model);\n  \n  model.lowerPositionLimit.head<7>().fill(-1.);\n  model.upperPositionLimit.head<7>().fill(1.);\n  \n  const VectorXd q = randomConfiguration(model);\n  \n  forwardKinematics(model,data,q);\n  forwardKinematics(model,data_ref,q);\n  \n  for(JointIndex joint_id = 1; joint_id < (JointIndex)model.njoints; ++joint_id)\n  {\n    Data::Matrix6x kinematic_regressor_L(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_LWA(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_W(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    \n    computeJointKinematicRegressor(model, data, joint_id, LOCAL, SE3::Identity(), kinematic_regressor_L);\n    computeJointKinematicRegressor(model, data, joint_id, LOCAL_WORLD_ALIGNED, SE3::Identity(), kinematic_regressor_LWA);\n    computeJointKinematicRegressor(model, data, joint_id, WORLD, SE3::Identity(), kinematic_regressor_W);\n    \n    Data::Matrix6x kinematic_regressor_L_ref(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_LWA_ref(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_W_ref(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    \n    computeJointKinematicRegressor(model, data_ref, joint_id, LOCAL, kinematic_regressor_L_ref);\n    computeJointKinematicRegressor(model, data_ref, joint_id, LOCAL_WORLD_ALIGNED, kinematic_regressor_LWA_ref);\n    computeJointKinematicRegressor(model, data_ref, joint_id, WORLD, kinematic_regressor_W_ref);\n    \n    BOOST_CHECK(kinematic_regressor_L.isApprox(kinematic_regressor_L_ref));\n    BOOST_CHECK(kinematic_regressor_LWA.isApprox(kinematic_regressor_LWA_ref));\n    BOOST_CHECK(kinematic_regressor_W.isApprox(kinematic_regressor_W_ref));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_kinematic_regressor_frame)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model; buildModels::humanoidRandom(model);\n  \n  model.lowerPositionLimit.head<7>().fill(-1.);\n  model.upperPositionLimit.head<7>().fill(1.);\n  \n  const std::string joint_name = \"larm5_joint\";\n  const JointIndex joint_id = model.getJointId(joint_name);\n  model.addBodyFrame(\"test_body\", joint_id, SE3::Random(), -1);\n  \n  pinocchio::Data data(model);\n  pinocchio::Data data_ref(model);\n  \n  const VectorXd q = randomConfiguration(model);\n  \n  forwardKinematics(model,data,q);\n  updateFramePlacements(model,data);\n  forwardKinematics(model,data_ref,q);\n  \n  const double eps = 1e-8;\n  for(FrameIndex frame_id = 1; frame_id < (FrameIndex)model.nframes; ++frame_id)\n  {\n    const Frame & frame = model.frames[frame_id];\n    \n    Data::Matrix6x kinematic_regressor_L(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_LWA(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_W(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    \n    computeFrameKinematicRegressor(model, data, frame_id, LOCAL, kinematic_regressor_L);\n    computeFrameKinematicRegressor(model, data, frame_id, LOCAL_WORLD_ALIGNED, kinematic_regressor_LWA);\n    computeFrameKinematicRegressor(model, data, frame_id, WORLD, kinematic_regressor_W);\n    \n    Data::Matrix6x kinematic_regressor_L_ref(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_LWA_ref(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_W_ref(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    \n    computeJointKinematicRegressor(model, data_ref, frame.parent, LOCAL, frame.placement, kinematic_regressor_L_ref);\n    computeJointKinematicRegressor(model, data_ref, frame.parent, LOCAL_WORLD_ALIGNED, frame.placement, kinematic_regressor_LWA_ref);\n    computeJointKinematicRegressor(model, data_ref, frame.parent, WORLD, frame.placement, kinematic_regressor_W_ref);\n    \n    BOOST_CHECK(kinematic_regressor_L.isApprox(kinematic_regressor_L_ref));\n    BOOST_CHECK(kinematic_regressor_LWA.isApprox(kinematic_regressor_LWA_ref));\n    BOOST_CHECK(kinematic_regressor_W.isApprox(kinematic_regressor_W_ref));\n    \n    Data::Matrix6x kinematic_regressor_L_fd(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_LWA_fd(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    Data::Matrix6x kinematic_regressor_W_fd(Data::Matrix6x::Zero(6,6*(model.njoints-1)));\n    \n    Model model_plus = model; Data data_plus(model_plus);\n    const SE3 & oMf = data.oMf[frame_id];\n    const SE3 Mf_LWA = SE3(oMf.rotation(),SE3::Vector3::Zero());\n    const SE3 & oMf_plus = data_plus.oMf[frame_id];\n    for(int i = 1; i < model.njoints; ++i)\n    {\n      Motion::Vector6 v = Motion::Vector6::Zero();\n      const SE3 & M_placement = model.jointPlacements[(JointIndex)i];\n      SE3 & M_placement_plus = model_plus.jointPlacements[(JointIndex)i];\n      for(Eigen::DenseIndex k = 0; k < 6; ++k)\n      {\n        v[k] = eps;\n        M_placement_plus = M_placement * exp6(Motion(v));\n        \n        forwardKinematics(model_plus,data_plus,q);\n        updateFramePlacements(model_plus,data_plus);\n        \n        const Motion diff_L = log6(oMf.actInv(oMf_plus));\n        kinematic_regressor_L_fd.middleCols<6>(6*(i-1)).col(k) = diff_L.toVector()/eps;\n        const Motion diff_LWA = Mf_LWA.act(diff_L);\n        kinematic_regressor_LWA_fd.middleCols<6>(6*(i-1)).col(k) = diff_LWA.toVector()/eps;\n        const Motion diff_W = oMf.act(diff_L);\n        kinematic_regressor_W_fd.middleCols<6>(6*(i-1)).col(k) = diff_W.toVector()/eps;\n        v[k] = 0.;\n      }\n      \n      M_placement_plus = M_placement;\n    }\n    \n    BOOST_CHECK(kinematic_regressor_L.isApprox(kinematic_regressor_L_fd,sqrt(eps)));\n    BOOST_CHECK(kinematic_regressor_LWA.isApprox(kinematic_regressor_LWA_fd,sqrt(eps)));\n    BOOST_CHECK(kinematic_regressor_W.isApprox(kinematic_regressor_W_fd,sqrt(eps)));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_static_regressor)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model; buildModels::humanoidRandom(model);\n  \n  pinocchio::Data data(model);\n  pinocchio::Data data_ref(model);\n  \n  model.lowerPositionLimit.head<7>().fill(-1.);\n  model.upperPositionLimit.head<7>().fill(1.);\n  \n  VectorXd q = randomConfiguration(model);\n  computeStaticRegressor(model,data,q);\n  \n  VectorXd phi(4*(model.njoints-1));\n  for(int k = 1; k < model.njoints; ++k)\n  {\n    const Inertia & Y = model.inertias[(size_t)k];\n    phi.segment<4>(4*(k-1)) << Y.mass(), Y.mass() * Y.lever();\n  }\n  \n  Vector3d com = centerOfMass(model,data_ref,q);\n  Vector3d static_com_ref;\n  static_com_ref <<  com;\n  \n  Vector3d static_com = data.staticRegressor * phi;\n  \n  BOOST_CHECK(static_com.isApprox(static_com_ref)); \n}\n\nBOOST_AUTO_TEST_CASE(test_body_regressor)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  Inertia I(Inertia::Random());\n  Motion v(Motion::Random());\n  Motion a(Motion::Random());\n\n  Force f = I*a + I.vxiv(v);\n\n  Inertia::Vector6 f_regressor = bodyRegressor(v,a) * I.toDynamicParameters();\n\n  BOOST_CHECK(f_regressor.isApprox(f.toVector()));\n}\n\nBOOST_AUTO_TEST_CASE(test_joint_body_regressor)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  buildModels::manipulator(model);\n  pinocchio::Data data(model);\n\n  JointIndex JOINT_ID = JointIndex(model.njoints) - 1;\n\n  VectorXd q = randomConfiguration(model);\n  VectorXd v = Eigen::VectorXd::Random(model.nv);\n  VectorXd a = Eigen::VectorXd::Random(model.nv);\n\n  rnea(model,data,q,v,a);\n\n  Force f = data.f[JOINT_ID];\n\n  Inertia::Vector6 f_regressor = jointBodyRegressor(model,data,JOINT_ID) * model.inertias[JOINT_ID].toDynamicParameters();\n\n  BOOST_CHECK(f_regressor.isApprox(f.toVector()));\n}\n\nBOOST_AUTO_TEST_CASE(test_frame_body_regressor)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  buildModels::manipulator(model);\n\n  JointIndex JOINT_ID = JointIndex(model.njoints) - 1;\n\n  const SE3 & framePlacement = SE3::Random();\n  FrameIndex FRAME_ID = model.addBodyFrame (\"test_body\", JOINT_ID, framePlacement, -1);\n\n  pinocchio::Data data(model);\n\n  VectorXd q = randomConfiguration(model);\n  VectorXd v = Eigen::VectorXd::Random(model.nv);\n  VectorXd a = Eigen::VectorXd::Random(model.nv);\n\n  rnea(model,data,q,v,a);\n\n  Force f = framePlacement.actInv(data.f[JOINT_ID]);\n  Inertia I = framePlacement.actInv(model.inertias[JOINT_ID]);\n\n  Inertia::Vector6 f_regressor = frameBodyRegressor(model,data,FRAME_ID) * I.toDynamicParameters();\n\n  BOOST_CHECK(f_regressor.isApprox(f.toVector()));\n}\n\nBOOST_AUTO_TEST_CASE(test_joint_torque_regressor)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  buildModels::humanoidRandom(model);\n\n  model.lowerPositionLimit.head<7>().fill(-1.);\n  model.upperPositionLimit.head<7>().fill(1.);\n\n  pinocchio::Data data(model);\n  pinocchio::Data data_ref(model);\n\n  VectorXd q = randomConfiguration(model);\n  VectorXd v = Eigen::VectorXd::Random(model.nv);\n  VectorXd a = Eigen::VectorXd::Random(model.nv);\n\n  rnea(model,data_ref,q,v,a);\n\n  Eigen::VectorXd params(10*(model.njoints-1));\n  for(JointIndex i=1; i<(Model::JointIndex)model.njoints; ++i)\n      params.segment<10>((int)((i-1)*10)) = model.inertias[i].toDynamicParameters();\n\n  computeJointTorqueRegressor(model,data,q,v,a);\n\n  Eigen::VectorXd tau_regressor = data.jointTorqueRegressor * params;\n\n  BOOST_CHECK(tau_regressor.isApprox(data_ref.tau));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c8fcfb1292175bf24d1fa8d2dc90abf14efe1739", "size": 13117, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/regressor.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/regressor.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/regressor.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": 37.2642045455, "max_line_length": 133, "alphanum_fraction": 0.7288251887, "num_tokens": 3691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5346554079519866}}
{"text": "//=======================================================================\n// Copyright 2007 Aaron Windsor\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#include <iostream>\n#include <vector>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/copy.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n\n#include <boost/graph/planar_canonical_ordering.hpp>\n#include <boost/graph/is_straight_line_drawing.hpp>\n#include <boost/graph/chrobak_payne_drawing.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n#include <boost/graph/make_connected.hpp>\n#include <boost/graph/make_biconnected_planar.hpp>\n#include <boost/graph/make_maximal_planar.hpp>\n\n#include \"graph.hpp\"\n#include \"range.hpp\"\n\n//a class to hold the coordinates of the straight line embedding\nstruct coord_t {\n  std::size_t x;\n  std::size_t y;\n};\n\ntemplate<class G>\nstd::vector<coord_t> straight_line_drawing(G const & gIn) {\n  using namespace boost;\n\n  typedef adjacency_list<vecS, vecS, undirectedS, property<vertex_index_t, int>,\n      property<edge_index_t, int> > Graph;\n\n  Graph g;\n  copy_edges(gIn, g);\n\n  //Define the storage type for the planar embedding\n  typedef std::vector<std::vector<graph_traits<Graph>::edge_descriptor>> embedding_storage_t;\n  typedef iterator_property_map<embedding_storage_t::iterator,\n      property_map<Graph, vertex_index_t>::type> embedding_t;\n\n  // Create the planar embedding\n  embedding_storage_t embedding_storage(num_vertices(g));\n  embedding_t embedding(embedding_storage.begin(), get(vertex_index, g));\n\n  boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n                               boyer_myrvold_params::embedding = embedding);\n\n  make_connected(g);\n  make_biconnected_planar(g, embedding);\n  make_maximal_planar(g, embedding);\n\n  // Find a canonical ordering\n  std::vector<typename graph_traits<Graph>::vertex_descriptor> ordering;\n  planar_canonical_ordering(g, embedding, std::back_inserter(ordering));\n\n  //Set up a property map to hold the mapping from vertices to coord_t's\n  typedef std::vector<coord_t> drawing_storage_t;\n  typedef boost::iterator_property_map<drawing_storage_t::iterator,\n      property_map<Graph, vertex_index_t>::type> drawing_t;\n\n  drawing_storage_t drawing_storage(num_vertices(g));\n  drawing_t drawing(drawing_storage.begin(), get(vertex_index, g));\n\n  // Compute the straight line drawing\n  chrobak_payne_straight_line_drawing(g, embedding, ordering.begin(),\n                                      ordering.end(), drawing);\n\n  return drawing_storage;\n}\n\nint main(int argc, char** argv) {\n  typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> graph;\n\n  // you can use the functions make_connected, make_biconnected_planar,\n  // and make_maximal planar in sequence to add a set of edges\n  // to any undirected planar graph to make it maximal planar.\n\n  graph g(7);\n  add_edge(0, 1, g);\n  add_edge(1, 2, g);\n  add_edge(2, 3, g);\n  add_edge(3, 0, g);\n  //add_edge(3, 4, g);\n  add_edge(4, 5, g);\n  add_edge(5, 6, g);\n  //add_edge(6, 3, g);\n  add_edge(0, 4, g);\n  add_edge(1, 3, g);\n  add_edge(3, 5, g);\n  add_edge(2, 6, g);\n  add_edge(1, 4, g);\n  add_edge(1, 5, g);\n  add_edge(1, 6, g);\n\n  auto coords = straight_line_drawing(g);\n\n  std::cout << \"The straight line drawing is: \" << std::endl;\n  for (auto v : ::range(vertices(g))) {\n    coord_t coord(coords[v]);\n    std::cout << v << \" -> (\" << coord.x << \", \" << coord.y << \")\" << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "eeca92841ac65cce655edb79eca66b3bf422a403", "size": 3717, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "prototype/planar.cpp", "max_stars_repo_name": "arekolek/MaxIST", "max_stars_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prototype/planar.cpp", "max_issues_repo_name": "arekolek/MaxIST", "max_issues_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prototype/planar.cpp", "max_forks_repo_name": "arekolek/MaxIST", "max_forks_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_forks_repo_licenses": ["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.8938053097, "max_line_length": 93, "alphanum_fraction": 0.6892655367, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5346112159099375}}
{"text": "#include <igl/readOBJ.h>\n#include <igl/readMESH.h>\n#include <igl/viewer/Viewer.h>\n#include <igl/edge_flaps.h>\n#include <Eigen/Core>\n#include <Eigen/StdVector>\n#include <igl/tetrahedron_tetrahedron_adjacency.h>\n#include \"../src/igl_dev/tetrahedron_tetrahedron_adjacency.h\"\n#include \"../src/igl_dev/tetrahedron_tuple.h\"\n#include \"../src/igl_dev/retain_tetrahedral_adjacency.h\"\n#include \"../src/igl_dev/edge_removal.h\"\n#include \"../src/igl_dev/multi_face_removal.h\"\n#include \"../src/util/tetrahedral_improvement.h\"\n\n#include <iostream>\n#include <list>\nusing vecV2d = std::vector<Eigen::RowVector2d>;\n//                           Eigen::aligned_allocator<Eigen::RowVector2d>>;\nusing vecV3d = std::vector<Eigen::RowVector3d>;\nusing vecV3i = std::vector<Eigen::RowVector3i>;\nusing vecV4i = std::vector<Eigen::RowVector4i>;\nusing T_t = vecV4i;\nusing TT_t = T_t;\nusing TTie_t = std::vector<Eigen::Matrix<int, 4, 3>>;\n\n\n// https://github.com/janba/DSC/blob/master/is_mesh/util.h#L415\nstruct test_utils {\n  using vec3 = Eigen::RowVector3d;\n  inline static double ms_length(const vec3 &a,\n                                 const vec3 &b,\n                                 const vec3 &c,\n                                 const vec3 &d) {\n    double result = 0.;\n    result += (a - b).squaredNorm();\n    result += (a - c).squaredNorm();\n    result += (a - d).squaredNorm();\n    result += (b - c).squaredNorm();\n    result += (b - d).squaredNorm();\n    result += (c - d).squaredNorm();\n    return result / 6.;\n  }\n\n  inline static double rms_length(const vec3 &a,\n                                  const vec3 &b,\n                                  const vec3 &c,\n                                  const vec3 &d) {\n    return sqrt(ms_length(a, b, c, d));\n  }\n\n  inline static double signed_volume(const vec3 &a,\n                                     const vec3 &b,\n                                     const vec3 &c,\n                                     const vec3 &d) {\n    return (a - d).dot((b - d).cross(c - d)) / 6.;\n  }\n\n// https://hal.inria.fr/inria-00518327\n  inline static double quality(const vec3 &a,\n                               const vec3 &b,\n                               const vec3 &c,\n                               const vec3 &d) {\n    double v = signed_volume(a, b, c, d);\n    double lrms = rms_length(a, b, c, d);\n\n    double q = 8.48528 * v / (lrms * lrms * lrms);\n#ifdef DEBUG\n    assert(!isnan(q));\n#endif\n    return q;\n  }\n};\n\n\ntemplate <int enable=1>\nint test_tetrahedron_adjacency() {\n  using namespace std;\n  using namespace Eigen;\n\n  vecV3d V(9);\n  vecV4i T(7);\n  V[0] << 0, 0, -1;\n  V[1] << 0, 0, 1;\n  V[2] << 0, 1, 0;\n  V[3] << -1, 0, 0;\n  V[4] << -0.8, -0.5, 0;\n  V[5] << -0.2, -0.8, 0;\n  V[6] << 0.2, -0.8, 0;\n  V[7] << 0.8, -0.5, 0;\n  V[8] << 1, 0, 0;\n\n  T[0] << 0, 2, 3, 1;\n  T[1] << 0, 3, 4, 1;\n  T[2] << 0, 4, 5, 1;\n  T[3] << 0, 5, 6, 1;\n  T[4] << 0, 6, 7, 1;\n  T[5] << 0, 7, 8, 1;\n  T[6] << 0, 8, 2, 1;\n\n  MatrixXi\n      mT = Eigen::Map<Matrix<int, -1, 4, RowMajor>>(T[0].data(), T.size(), 4);\n  MatrixXi mTT, mTTif, mTTie;\n  vecV4i TT, TTif;\n  TTie_t TTie;\n  igl::tetrahedron_tetrahedron_adjacency(mT, mTT, mTTif, mTTie);\n  igl::dev::tetrahedron_tetrahedron_adjacency(T, TT, TTif, TTie);\n\n//  std::cout << mT << std::endl << endl\n//            << mTT << endl << endl\n//            << mTTie << endl;\n//  std::cout << \"Here goes our new function\" << endl;\n//  for (auto r:T) cout << r << endl;\n//  for (auto r:TT) cout << r << endl;\n//  for (auto r:TTif) cout << r << endl;\n//  for (auto r:TTie) cout << r << endl;\n\n  return 0;\n}\n\ntemplate <int enable=1>\nint test_retain_tetrahedron_adjacency() {\n  using namespace Eigen;\n  using namespace std;\n\n  // test a 2-3 flip\n  vecV4i T(7);\n  T[0] << 0, 2, 3, 1;\n  T[1] << 0, 3, 4, 1;\n  T[2] << 0, 4, 5, 1;\n  T[3] << 0, 5, 6, 1;\n  T[4] << 0, 6, 7, 1;\n  T[5] << 0, 7, 8, 1;\n  T[6] << 0, 8, 2, 1;\n\n  auto manual_T = T;\n  manual_T.resize(8);\n  manual_T[0] << 0, 8, 3, 1;\n  manual_T[6] << 8, 2, 3, 1;\n  manual_T[7] << 0, 2, 3, 8;\n  T_t new_T;\n  new_T.push_back(manual_T[0]);\n  new_T.push_back(manual_T[6]);\n  new_T.push_back(manual_T[7]);\n\n  vecV4i TT, TTif;\n  TTie_t TTie;\n  igl::dev::tetrahedron_tetrahedron_adjacency(T, TT, TTif, TTie);\n//  std::cout << \"raw: T,TT,TTi:\" << endl;\n//  for (auto r:T) cout << r << endl;cout<<endl;\n//  for (auto r:TT) cout << r << endl;cout<<endl;\n//  for (auto r:TTif) cout << r << endl;cout<<endl;\n//  for (auto r:TTie) cout << r << endl;cout<<endl;\n  vecV4i mTT, mTTif;\n  TTie_t mTTie;\n  igl::dev::tetrahedron_tetrahedron_adjacency(manual_T, mTT, mTTif, mTTie);\n//  std::cout << \"manual: T,TT,TTi:\" << endl;\n//  for (auto r:manual_T) cout << r << endl;cout<<endl;\n//  for (auto r:TT) cout << r << endl;cout<<endl;\n//  for (auto r:TTif) cout << r << endl;cout<<endl;\n//  for (auto r:TTie) cout << r << endl<<endl;cout<<endl;\n\n  std::set<int> delete_id {0,6};\n  std::set<int> surround_id {1,5};\n\n  retain_tetrahedral_adjacency(delete_id, surround_id,new_T, T,TT,TTif,TTie);\n  for (int i = 0; i < T.size(); i++) {\n    assert(mTT[i] == TT[i]);\n    assert(mTTif[i] == TTif[i]);\n    assert(mTTie[i] == TTie[i]);\n  }\n//  std::cout << \"modified: T,TT,TTi:\" << endl;\n//  for (auto r:T) cout << r << endl;cout<<endl;\n//  for (auto r:TT) cout << r << endl;cout<<endl;\n//  for (auto r:TTif) cout << r << endl;cout<<endl;\n//  for (auto r:TTie) cout << r << endl<<endl;cout<<endl;\n\n  return 0;\n}\n\n\ntemplate <int enable=1>\nint test_retain_fix_end() {\n\n  using namespace Eigen;\n  using namespace std;\n  using vecV2d = std::vector<Eigen::RowVector2d>;\n  using vecV3d = std::vector<Eigen::RowVector3d>;\n  using vecV3i = std::vector<Eigen::RowVector3i>;\n  using vecV4i = std::vector<Eigen::RowVector4i>;\n  using T_t = vecV4i;\n  using TT_t = T_t;\n  using TTie_t = std::vector<Eigen::Matrix<int, 4, 3>>;\n\n  vecV3d V(9);\n  vecV4i T(7);\n  V[0] << 0, -0, 1;\n  V[1] << 0, -0, -1;\n  V[2] << 0, 1, 0;\n  V[3] << -1, 0, 0;\n  V[4] << -0.8, -0.5, 0;\n  V[5] << -0.2, -0.8, 0;\n  V[6] << 0.2, -0.8, 0;\n  V[7] << 0.8, -0.5, 0;\n  V[8] << 1, 0, 0;\n\n  T[0] << 1, 2, 3, 0;\n  T[1] << 1, 3, 4, 0;\n  T[2] << 1, 4, 5, 0;\n  T[3] << 1, 5, 6, 0;\n  T[4] << 1, 6, 7, 0;\n  T[5] << 1, 7, 8, 0;\n  T[6] << 1, 8, 2, 0;\n\n  std::set<int> delete_id, influence_id;\n  delete_id.insert(0);\n  delete_id.insert(1);\n  delete_id.insert(3);\n  delete_id.insert(5);\n\n\n  vecV4i TT, TTif;\n  TTie_t TTie;\n  igl::dev::tetrahedron_tetrahedron_adjacency(T, TT, TTif, TTie);\n\n  for (auto t:delete_id)\n    for (auto f:{0, 1, 2, 3})\n      influence_id.insert(TT[t][f]);\n  influence_id.erase(-1);\n\n  // retain_connectivity.\n  std::set<int> surround_id;\n  std::set_difference(influence_id.begin(), influence_id.end(),\n                      delete_id.begin(), delete_id.end(),\n                      std::inserter(surround_id, surround_id.end()));\n\n\n  vecV4i new_tets(2);\n//  new_tets[2] << 1, 2, 3, 0;\n  new_tets[0] << 1, 3, 4, 0;\n  new_tets[1] << 1, 7, 8, 0;\n\n\n  retain_tetrahedral_adjacency(delete_id, surround_id,new_tets, T,TT,TTif,TTie);\n  return 0;\n}\n\ntemplate <int enable=1>\nint test_extraction_recurse()\n{\n  using namespace Eigen;\n  using namespace std;\n\n  static MatrixXi K_table(4,6);\n  K_table << 0,0,2,3,4,4,\n  0,0,0,3,4,3,\n  0,0,0,0,4,4,\n  0,0,0,0,0,5;\n  K_table -= MatrixXi::Ones(4,6);\n\n  static std::vector<Eigen::RowVector3i> new_tri;\n  struct recurse_extract {\n    static void op(int i,int j){\n      if(j>= i+2) {\n        int k=K_table(i,j);\n        recurse_extract::op(i,k);\n        recurse_extract::op(k,j);\n        new_tri.emplace_back(i,j,k);\n      }\n    };\n  };\n  recurse_extract::op(0,5);\n//  std::cout<<K_table<<std::endl;\n//  for(auto r:new_tri) cout<<r<<endl;\n  return 0;\n}\n\n\n\ntemplate <int enable=1>\nint test_single_edge_removal() {\n  using namespace Eigen;\n  using namespace std;\n\n  vecV3d V(9);\n  vecV4i T(7);\n  V[0] << 0, 0, 1;\n  V[1] << 0, 0, -1;\n  V[2] << 0, 10, 0;\n  V[3] << -1, 0, 0;\n  V[4] << -0.8, -0.5, 0;\n  V[5] << -0.2, -0.8, 0;\n  V[6] << 0.2, -0.8, 0;\n  V[7] << 0.8, -0.5, 0;\n  V[8] << 1, 0, 0;\n\n  T[0] << 0, 2, 3, 1;\n  T[1] << 0, 3, 4, 1;\n  T[2] << 0, 4, 5, 1;\n  T[3] << 0, 5, 6, 1;\n  T[4] << 0, 6, 7, 1;\n  T[5] << 0, 7, 8, 1;\n  T[6] << 0, 8, 2, 1;\n\n  vecV4i TT, TTif; TTie_t TTie;\n  igl::dev::tetrahedron_tetrahedron_adjacency(T, TT, TTif, TTie);\n\n  auto tet_quality = [&V](int a, int b, int c, int d) {\n    return test_utils::quality(V[a],V[b],V[c],V[d]);\n  };\n\n  igl::dev::tet_tuple_edge_removal(0,\n                                   1,\n                                   1,\n                                   true,\n                                   tet_quality,\n                                   T,\n                                   TT,\n                                   TTif,\n                                   TTie );\n//  for (auto r:T) cout << r << endl;cout<<endl;\n  decltype(TT) nTT;\n  decltype(TTif) nTTif;\n  decltype(TTie) nTTie;\n  igl::dev::tetrahedron_tetrahedron_adjacency(T, nTT, nTTif, nTTie);\n  for (int i = 0; i < T.size(); i++) {\n    assert(nTT[i] == TT[i]);\n    assert(nTTif[i] == TTif[i]);\n    assert(nTTie[i] == TTie[i]);\n  }\n  return 0;\n}\n\n\ntemplate <int enable=1>\nint test_simple_face_removal() {\n\n\n  using namespace std;\n  using namespace Eigen;\n\n  std::list<std::tuple<int, int>> dt;\n  dt.emplace_back(8, 0);\n  std::vector<std::tuple<int, int>> vdt(dt.begin(), dt.end());\n  using vecV2d = std::vector<Eigen::RowVector2d>;\n//                           Eigen::aligned_allocator<Eigen::RowVector2d>>;\n  using vecV3d = std::vector<Eigen::RowVector3d>;\n  using vecV3i = std::vector<Eigen::RowVector3i>;\n  using vecV4i = std::vector<Eigen::RowVector4i>;\n  using T_t = vecV4i;\n  using TT_t = T_t;\n  using TTie_t = std::vector<Eigen::Matrix<int, 4, 3>>;\n\n  vecV3d V(9);\n  vecV4i T(10);\n  V[0] << 0.7, -0.1, 1;\n  V[1] << 0.7, -0.1, -1;\n  V[2] << 0, 1, 0;\n  V[3] << -1, 0, 0;\n  V[4] << -0.8, -0.5, 0;\n  V[5] << -0.2, -0.8, 0;\n  V[6] << 0.2, -0.8, 0;\n  V[7] << 0.8, -0.5, 0;\n  V[8] << 1, 0, 0;\n\n  T[0] << 1, 3, 5, 4;\n  T[1] << 3, 5, 4, 0;\n  T[2] << 1, 3, 6, 5;\n  T[3] << 3, 6, 5, 0;\n  T[4] << 1, 3, 7, 6;\n  T[5] << 3, 7, 6, 0;\n  T[6] << 1, 3, 8, 7;\n  T[7] << 3, 8, 7, 0;\n  T[8] << 1, 3, 2, 8;\n  T[9] << 3, 2, 8, 0;\n\n  vecV4i TT, TTif;\n  TTie_t TTie;\n  igl::dev::tetrahedron_tetrahedron_adjacency(T, TT, TTif, TTie);\n\n  auto tet_quality = [&V](int a, int b, int c, int d) -> double {\n    return -test_utils::quality(V[a], V[b], V[c], V[d]);\n  };\n  auto correct_orientation = [&V](int a, int b, int c, int d) -> bool {\n    return -test_utils::signed_volume(V[a], V[b], V[c], V[d]) > 0;\n  };\n  std::vector<int> dummy;\n  igl::dev::tet_tuple_multi_face_removal(7,\n                                         3,\n                                         0,\n                                         true,\n                                         tet_quality,\n                                         correct_orientation,\n                                         T,\n                                         TT,\n                                         TTif,\n                                         TTie,\n                                         dummy);\n  decltype(TT) nTT;\n  decltype(TTif) nTTif;\n  decltype(TTie) nTTie;\n  igl::dev::tetrahedron_tetrahedron_adjacency(T, nTT, nTTif, nTTie);\n  for (int i = 0; i < T.size(); i++) {\n    assert(nTT[i] == TT[i]);\n    assert(nTTif[i] == TTif[i]);\n    assert(nTTie[i] == TTie[i]);\n  }\n  return 0;\n}\n\n// topological improvement\ntemplate <int enable=1>\nint test_edge_removal_pass() {\n\n\n  using namespace std;\n  using namespace Eigen;\n\n  std::list<std::tuple<int, int>> dt;\n  dt.emplace_back(8, 0);\n  std::vector<std::tuple<int, int>> vdt(dt.begin(), dt.end());\n  using vecV2d = std::vector<Eigen::RowVector2d>;\n//                           Eigen::aligned_allocator<Eigen::RowVector2d>>;\n  using vecV3d = std::vector<Eigen::RowVector3d>;\n  using vecV3i = std::vector<Eigen::RowVector3i>;\n  using vecV4i = std::vector<Eigen::RowVector4i>;\n  using T_t = vecV4i;\n  using TT_t = T_t;\n  using TTie_t = std::vector<Eigen::Matrix<int, 4, 3>>;\n\n  vecV3d V(9);\n  vecV4i T(7);\n  V[0] << 0, -0, 10;\n  V[1] << 0, -0, -1;\n  V[2] << 0, 1, 0;\n  V[3] << -1, 0, 0;\n  V[4] << -0.8, -0.5, 0;\n  V[5] << -0.2, -0.8, 0;\n  V[6] << 0.2, -0.8, 0;\n  V[7] << 0.8, -0.5, 0;\n  V[8] << 1, 0, 0;\n\n\n  T[0] << 0, 2, 3, 1;\n  T[1] << 0, 3, 4, 1;\n  T[2] << 0, 4, 5, 1;\n  T[3] << 0, 5, 6, 1;\n  T[4] << 0, 6, 7, 1;\n  T[5] << 0, 7, 8, 1;\n  T[6] << 0, 8, 2, 1;\n\n  vecV4i TT, TTif;\n  TTie_t TTie;\n  igl::dev::tetrahedron_tetrahedron_adjacency(T, TT, TTif, TTie);\n\n  auto tet_quality = [&V](int a, int b, int c, int d) -> double {\n    return test_utils::quality(V[a], V[b], V[c], V[d]);\n  };\n  auto correct_orientation = [&V](int a, int b, int c, int d) -> bool {\n    return test_utils::signed_volume(V[a], V[b], V[c], V[d]) > 0;\n  };\n\n//  for(auto r:T) cout<<r<<\":\"<<tet_quality(r(0),r(1),r(2),r(3)) <<endl;\n//  cout<<endl;\n  edge_removal_pass(tet_quality, correct_orientation, T,TT,TTif,TTie);\n\n//  for(auto r:T) cout<<r<<\":\"<<tet_quality(r(0),r(1),r(2),r(3)) <<endl;\n}\n\n// topological improvement\ntemplate <int enable=1>\nint test_tetmesh_topology_improvement() {\n\n// https://github.com/janba/DSC/blob/master/is_mesh/util.h#L415\n  struct test_utils {\n    using vec3 = Eigen::RowVector3d;\n    inline static double ms_length(const vec3 &a,\n                                   const vec3 &b,\n                                   const vec3 &c,\n                                   const vec3 &d) {\n      double result = 0.;\n      result += (a - b).squaredNorm();\n      result += (a - c).squaredNorm();\n      result += (a - d).squaredNorm();\n      result += (b - c).squaredNorm();\n      result += (b - d).squaredNorm();\n      result += (c - d).squaredNorm();\n      return result / 6.;\n    }\n\n    inline static double rms_length(const vec3 &a,\n                                    const vec3 &b,\n                                    const vec3 &c,\n                                    const vec3 &d) {\n      return sqrt(ms_length(a, b, c, d));\n    }\n\n    inline static double signed_volume(const vec3 &a,\n                                       const vec3 &b,\n                                       const vec3 &c,\n                                       const vec3 &d) {\n      return (a - d).dot((b - d).cross(c - d)) / 6.;\n    }\n\n// https://hal.inria.fr/inria-00518327\n    inline static double quality(const vec3 &a,\n                                 const vec3 &b,\n                                 const vec3 &c,\n                                 const vec3 &d) {\n      double v = signed_volume(a, b, c, d);\n      double lrms = rms_length(a, b, c, d);\n\n      double q = 8.48528 * v / (lrms * lrms * lrms);\n#ifdef DEBUG\n      assert(!isnan(q));\n#endif\n      return q;\n    }\n  };\n\n\n  using namespace std;\n  using namespace Eigen;\n\n  std::list<std::tuple<int, int>> dt;\n  dt.emplace_back(8, 0);\n  std::vector<std::tuple<int, int>> vdt(dt.begin(), dt.end());\n  using vecV2d = std::vector<Eigen::RowVector2d>;\n//                           Eigen::aligned_allocator<Eigen::RowVector2d>>;\n  using vecV3d = std::vector<Eigen::RowVector3d>;\n  using vecV3i = std::vector<Eigen::RowVector3i>;\n  using vecV4i = std::vector<Eigen::RowVector4i>;\n  using T_t = vecV4i;\n  using TT_t = T_t;\n  using TTie_t = std::vector<Eigen::Matrix<int, 4, 3>>;\n\n  MatrixXd TV; MatrixXi TTo,TF;\n  igl::readMESH(\"../models/bumpy.mesh\",TV,TTo,TF);\n\n  vecV3d V(TV.rows());\n  vecV4i T(TTo.rows());\n\n  for(int i=0; i< V.size(); i++) V[i]<<TV.row(i);\n  for(int i=0; i< T.size(); i++) T[i]<<TTo.row(i);\n\n  auto tet_quality = [&V](int a, int b, int c, int d) -> double {\n    return -test_utils::quality(V[a], V[b], V[c], V[d]);\n  };\n  auto correct_orientation = [&V](int a, int b, int c, int d) -> bool {\n    return -test_utils::signed_volume(V[a], V[b], V[c], V[d]) > 0;\n  };\n\n  vecV4i TT, TTif;\n  TTie_t TTie;\n  igl::dev::tetrahedron_tetrahedron_adjacency(T, TT, TTif, TTie);\n//  {double old_q= INFINITY;\n//    for(auto r:T) old_q = std::min(old_q, tet_quality(r(0),r(1),r(2),r(3)));\n//    cout<<old_q<<endl;}\n  // let's try to perturb this.\n  int perturb = 0;\n  for(auto t=0; t<T.size(); t++)\n    for (auto f:{0,1,2,3})\n      for(auto e:{0,1,2}) {\n        if (igl::dev::tet_tuple_edge_removal_force(t,\n                                                   f,\n                                                   e,\n                                                   true,\n                                                   tet_quality,\n//                                                         correct_orientation,\n                                                   T,\n                                                   TT,\n                                                   TTif,\n                                                   TTie)) {\n          perturb++; //t+=10;\n          if(perturb == 3)\n            goto out;\n          break;\n        }\n      }\nout: ;\n  /*{\n    MatrixXd iV(8,3);\n    MatrixXi F(8,3);\n    int x=0;\n    for (auto t:{0,1398}) {\n      for(auto v:{0,1,2,3})\n        iV.row(x++) = V[T[t](v)];\n    }\n    F<< 3, 2, 1,\n        2, 3, 0,\n        1, 0, 3,\n        0, 1, 2,\n        7, 6, 5,\n        6, 7, 4,\n        5, 4, 7,\n        4, 5, 6;\n    igl::viewer::Viewer vvvv;\n    vvvv.data.set_mesh(iV, F);\n    igl::writeOBJ(\"temp.obj\",iV,F);\n    vvvv.launch();\n  }*/\n\n  double old_q = INFINITY, new_q= INFINITY;\n  for(auto r:T) old_q = std::min(old_q, tet_quality(r(0),r(1),r(2),r(3)));\n//  cout<<old_q<<endl;\n  face_removal_pass(tet_quality, correct_orientation, T,TT,TTif,TTie);\n  for(auto r:T) new_q = std::min(new_q, tet_quality(r(0),r(1),r(2),r(3)));\n//  cout<<new_q<<endl;\n}\n\n\ntemplate <int enable=1>\nint test_bumpy_vert_tet_query() {\n  using namespace std;\n  using namespace Eigen;\n\n  MatrixXd V, Vall; MatrixXi F;\n  MatrixXd TV;\n  MatrixXi T,TF;\n\n  igl::readMESH(\"../models/bumpy.mesh\", TV,T,TF);\n\n  std::vector<RowVector4i> vT(T.rows()),vTT,vTTif;\n  std::vector<Matrix<int,4,3>> vTTie;\n  for(int i=0; i<T.rows(); i++) vT[i] = T.row(i);\n\n  igl::dev::tetrahedron_tetrahedron_adjacency(vT,vTT,vTTif,vTTie);\n\n  for(int ti = 0; ti<T.rows(); ti++) {\n    for (int fi:{0, 1, 2, 3}) {\n      int ei = 0;\n\n      int query_v =\n          igl::dev::tet_tuple_get_vert(ti, fi, ei, true, vT, vTT, vTTif, vTTie);\n\n      auto get_neighbor =\n          igl::dev::tet_tuple_get_tets_with_vert(ti, fi, ei, true,\n                                                 vT, vTT, vTTif, vTTie);\n\n      std::set<int> test_neighbor;\n      for (int i = 0; i < T.rows(); i++) {\n        for (int j:{0, 1, 2, 3})\n          if (T(i, j) == query_v)\n            test_neighbor.insert(i);\n      }\n\n      assert(get_neighbor == test_neighbor);\n    }\n  }\n  return 0;\n}\n\n#include \"../src/igl_dev/tet_refine_operations.h\"\ntemplate <int enable=1>\nint test_edge_split()\n{\n  using namespace Eigen;\n  using namespace std;\n\n  using vecV2d = std::vector<Eigen::RowVector2d>;\n  using vecV3d = std::vector<Eigen::RowVector3d>;\n  using vecV3i = std::vector<Eigen::RowVector3i>;\n  using vecV4i = std::vector<Eigen::RowVector4i>;\n  using T_t = vecV4i;\n  using TT_t = T_t;\n  using TTie_t = std::vector<Eigen::Matrix<int, 4, 3>>;\n\n  vecV3d V(9);\n  vecV4i T(7);\n  V[0] << 0, -0, 1;\n  V[1] << 0, -0, -1;\n  V[2] << 0, 1, 0;\n  V[3] << -1, 0, 0;\n  V[4] << -0.8, -0.5, 0;\n  V[5] << -0.2, -0.8, 0;\n  V[6] << 0.2, -0.8, 0;\n  V[7] << 0.8, -0.5, 0;\n  V[8] << 1, 0, 0;\n\n\n  T[0] << 1, 2, 3, 0;\n  T[1] << 1, 3, 4, 0;\n  T[2] << 1, 4, 5, 0;\n  T[3] << 1, 5, 6, 0;\n  T[4] << 1, 6, 7, 0;\n  T[5] << 1, 7, 8, 0;\n  T[6] << 1, 8, 2, 0;\n\n  auto tet_quality = [&V](int a, int b, int c, int d) -> double {\n    return -test_utils::quality(V[a], V[b], V[c], V[d]);\n  };\n//  for(auto r:T) cout<<r<<\":\"<<tet_quality(r(0),r(1),r(2),r(3)) <<endl;\n\n  vecV4i TT, TTif;\n  TTie_t TTie;\n  igl::dev::tetrahedron_tetrahedron_adjacency(T, TT, TTif, TTie);\n\n//  cout<< igl::dev::tet_tuple_get_vert(0, 1, 1, true,\n//                                      T,TT, TTif, TTie)\n//      <<\"->\"\n//      << igl::dev::tet_tuple_get_vert(0, 1, 1, false,\n//                                      T,TT, TTif, TTie)<<endl;\n\n\n  igl::dev::tet_tuple_edge_split(0, 1, 1, true, tet_quality,[](int){return\n                                     true;}, V,T,TT, TTif,\n                                 TTie);\n//  for(auto r:T) cout<<r<<\":\"<<tet_quality(r(0),r(1),r(2),r(3)) <<endl;\n  return 0;\n}\n\ntemplate <int enable = 1>\nint test_edge_contraction() {\n\n  using namespace Eigen;\n  using namespace std;\n\n  using vecV2d = std::vector<Eigen::RowVector2d>;\n  using vecV3d = std::vector<Eigen::RowVector3d>;\n  using vecV3i = std::vector<Eigen::RowVector3i>;\n  using vecV4i = std::vector<Eigen::RowVector4i>;\n  using T_t = vecV4i;\n  using TT_t = T_t;\n  using TTie_t = std::vector<Eigen::Matrix<int, 4, 3>>;\n\n  vecV3d V(9);\n  vecV4i T(7);\n  V[0] << 0, -0, 1;\n  V[1] << 0, -0, -1;\n  V[2] << 0, 1, 0;\n  V[3] << -1, 0, 0;\n  V[4] << -0.8, -0.5, 0;\n  V[5] << -0.2, -0.8, 0;\n  V[6] << 0.2, -0.8, 0;\n  V[7] << 0.8, -0.5, 0;\n  V[8] << 1, 0, 0;\n\n\n  T[0] << 1, 2, 3, 0;\n  T[1] << 1, 3, 4, 0;\n  T[2] << 1, 4, 5, 0;\n  T[3] << 1, 5, 6, 0;\n  T[4] << 1, 6, 7, 0;\n  T[5] << 1, 7, 8, 0;\n  T[6] << 1, 8, 2, 0;\n\n  auto tet_quality = [&V](int a, int b, int c, int d) -> double {\n    return -test_utils::quality(V[a], V[b], V[c], V[d]);\n  };\n//   for(auto r:T) cout<<r<<\":\"<<tet_quality(r(0),r(1),r(2),r(3)) <<endl;\n\n  vecV4i TT, TTif;\n  TTie_t TTie;\n  igl::dev::tetrahedron_tetrahedron_adjacency(T, TT, TTif, TTie);\n//\n//   cout<< igl::dev::tet_tuple_get_vert(0, 1, 1, true,\n//                                       T,TT, TTif, TTie)\n//       <<\"->\"\n//       << igl::dev::tet_tuple_get_vert(0, 1, 1, false,\n//                                       T,TT, TTif, TTie)<<endl;\n\n  std::vector<int> dummy;\n\n  igl::dev::tet_tuple_edge_split(0, 1, 1, true, tet_quality,[](int){return\n      true;}, V,T,TT, TTif,\n                                 TTie, dummy);\n//   for(auto r:T) cout<<r<<\":\"<<tet_quality(r(0),r(1),r(2),r(3)) <<endl;\n\n  V[1](2) -= 9;\n  V[9](2) -= 1;\n//   cout<< igl::dev::tet_tuple_get_vert(7, 1, 1, true,\n//                                       T,TT, TTif, TTie)\n//       <<\"->\"\n//       << igl::dev::tet_tuple_get_vert(7, 1, 1, false,\n//                                       T,TT, TTif, TTie)<<endl;\n  igl::dev::tet_tuple_edge_split(7, 1, 1, true, tet_quality,[](int){return\n                                     true;}, V,T,TT, TTif,\n                                 TTie,dummy);\n\n  V[9](2) += 0.9;\n  V[1](2) += 9;\n//  for(auto r:T) cout<<r<<endl;\n  igl::dev::tet_tuple_edge_contraction(7,\n                                       1,\n                                       1,\n                                       true,\n                                       tet_quality,[](int){return\n          true;},\n                                       T,\n                                       TT,\n                                       TTif,\n                                       TTie,\n                                       dummy);\n\n//  for(auto r:T) cout<<r<<\":\"<<tet_quality(r(0),r(1),r(2),r(3)) <<endl;\n  return 0;\n}\n/*\nint test_all() {\n  test_edge_split<1>();\n  test_edge_contraction();\n  test_bumpy_vert_tet_query();\n  test_tetmesh_topology_improvement();\n  test_simple_face_removal();\n  test_edge_removal_pass();\n  test_single_edge_removal();\n  test_extraction_recurse();\n  test_retain_fix_end();\n  test_retain_tetrahedron_adjacency();\n  test_tetrahedron_adjacency();\n}\n*/", "meta": {"hexsha": "3b9d9f51c16491f4af31b234bfc812dfd4c526ae", "size": 23257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_tet.cpp", "max_stars_repo_name": "squarefk/Scaffold-Map", "max_stars_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2018-04-04T19:50:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T00:56:10.000Z", "max_issues_repo_path": "test/test_tet.cpp", "max_issues_repo_name": "squarefk/Scaffold-Map", "max_issues_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-04-27T05:01:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-21T19:07:28.000Z", "max_forks_repo_path": "test/test_tet.cpp", "max_forks_repo_name": "squarefk/Scaffold-Map", "max_forks_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-04-05T10:50:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T14:26:09.000Z", "avg_line_length": 28.6769420469, "max_line_length": 80, "alphanum_fraction": 0.4994625274, "num_tokens": 8651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5345540263220758}}
{"text": "#include <iostream>\r\n#include <ros/ros.h>\r\n#include <ros/console.h>\r\n#include <sensor_msgs/Imu.h>\r\n#include <sensor_msgs/Range.h>\r\n#include <nav_msgs/Odometry.h>\r\n#include <Eigen/Eigen>\r\n#include <Eigen/Geometry> \r\n#include <math.h> \r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\nros::Publisher odom_pub;\r\nMatrixXd Q = MatrixXd::Identity(12, 12);\r\nMatrixXd Rt = MatrixXd::Identity(6,6);\r\n//Define some para\r\nint img_checktemp=0;\r\nint temp_ff=0;\r\nEigen::Vector3d p,q,p_dot,b_g,b_a;\r\nEigen::Vector3d u_a,u_g;\r\nEigen::VectorXd ut(6);\r\nEigen::VectorXd x_dot_prev(15),x_prev(15);\r\nEigen::VectorXd x_dot(15)     ,x(15);\r\nEigen::VectorXd Mu(15) ,Mu_bar(15), Mu_prev(15);\r\nEigen::MatrixXd Sigma(15,15) ,Sigma_bar(15,15), Sigma_prev(15,15);\r\nEigen::VectorXd process_model(15);\r\nEigen::Matrix3d R_WorldinCAM;\r\nEigen::Vector3d T_WorldinCAM;\r\nEigen::VectorXd Q_WorldinCAM(4);\r\nEigen::Matrix3d R_IMUinWorld;\r\nEigen::Vector3d T_IMUinWorld;\r\nEigen::VectorXd Q_IMUinWorld(4);\r\ndouble dt, time_old,grav;\r\n//Define some Matrix\r\nEigen::MatrixXd At(15,15);\r\nEigen::MatrixXd Ut(15,12);\r\nEigen::MatrixXd Ft(15,15);\r\nEigen::MatrixXd Vt(15,12);\r\nEigen::MatrixXd Ct(6,15);\r\nEigen::MatrixXd Kt(15,6);\r\nEigen::MatrixXd H_CAMinIMU(4,4);\r\nEigen::MatrixXd H_WorldinCAM(4,4);\r\nEigen::MatrixXd H_IMUinWorld(4,4);\r\nvoid imu_callback(const sensor_msgs::Imu::ConstPtr &msg)\r\n{\r\n    //your code for propagation\r\n\t//Get process model\r\n/*Get Row Data as u*/\r\n\tu_a(0) = msg->linear_acceleration.x;\r\n\tu_a(1) = msg->linear_acceleration.y;\r\n\tu_a(2) = msg->linear_acceleration.z;\r\n\t//cout << \"u_a(0):\" << u_a(0) << \"u_a(1):\" << u_a(1) << \"u_a(2):\" << u_a(2) << endl;\r\n\tu_g(0) = msg->angular_velocity.x;//as roll\r\n\tu_g(1) = msg->angular_velocity.y;//as pitch\r\n\tu_g(2) = msg->angular_velocity.z;//as yaw\r\n/*Get Row Data as u*/\r\n}\r\n\r\n//Rotation from the camera frame to the IMU frame\r\nEigen::Matrix3d Rcam;\r\nvoid odom_callback(const nav_msgs::Odometry::ConstPtr &msg)\r\n{\r\n    //your code for update\r\n    //camera position in the IMU frame = (0, -0.04, -0.02)\r\n    //camera orientaion in the IMU frame = Quaternion(0, 0, 1, 0); w x y z, respectively\r\n    //\t\t\t\t\t   RotationMatrix << -1, 0, 0,\r\n    //\t\t\t\t\t\t\t      0, 1, 0,\r\n    //                                                        0, 0, -1;\t\r\n/*Get the dt from stamp*/\r\n{\r\n\tif (!img_checktemp) \r\n    {\r\n\ttime_old = msg->header.stamp.toSec()-0.03;\r\n\tMu.setZero();\r\n\tSigma.setIdentity();\r\n\t//img_checktemp = 1;\r\n\t//cout << \"Mu_prev\" << endl << Mu_prev << endl;\r\n    }\r\n    dt=msg->header.stamp.toSec() - time_old;\r\n    time_old = msg->header.stamp.toSec();\r\n    //cout << \"dt\" << endl << sin(1.5) << endl;\r\n}\r\n/*Get the dt from stamp*/\r\n/*Prediction Step*/\r\n{\r\n\t//move forward\r\n\tx_prev     = x;\r\n\tx_dot_prev = x_dot;\r\n\tMu_prev    = Mu;\r\n\tSigma_prev = Sigma;\r\n\t//get ut from IMU\r\n\tut        << u_a , u_g;\r\n\t//cout << \"u_a(0):\" << u_a(0) << \"u_a(1):\" << u_a(1) << \"u_a(2):\" << u_a(2) << endl;\r\n\t//cout << \"Rcam:\"   << Rcam   << endl;\r\n\t{//three matrix\r\n\t//get matrix At\r\n\tAt            <<0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,\r\n\t\t\t\t\t0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,\r\n                    0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,\r\n  0, 0, 0,0,Mu_prev(9)*sin(Mu_prev(4)) - Mu_prev(11)*cos(Mu_prev(4)) + ut(5)*cos(Mu_prev(4)) - ut(3)*sin(Mu_prev(4)),                                                                                                                                                                                                                                                                                                                                                                                         0, 0, 0, 0,                                               -cos(Mu_prev(4)),  0,                                              -sin(Mu_prev(4)),                                                                                                                 0,                                            0,                                                                                                                 0,\r\n  0, 0, 0,(Mu_prev(11)*cos(Mu_prev(4)) - Mu_prev(9)*sin(Mu_prev(4)) - ut(5)*cos(Mu_prev(4)) + ut(3)*sin(Mu_prev(4)))/pow(cos(Mu_prev(3)),2),                                                                                                 -(sin(Mu_prev(3))*(Mu_prev(9)*cos(Mu_prev(4)) + Mu_prev(11)*sin(Mu_prev(4)) - ut(3)*cos(Mu_prev(4)) - ut(5)*sin(Mu_prev(4))))/cos(Mu_prev(3)),                                                                                                                                                                                                                                                                                                                                                                                         0, 0, 0, 0, -(sin(Mu_prev(3))*sin(Mu_prev(4)))/cos(Mu_prev(3)), -1, (cos(Mu_prev(4))*sin(Mu_prev(3)))/cos(Mu_prev(3)),                                                                                                                 0,                                            0,                                                                                                                 0,\r\n  0, 0, 0,-(sin(Mu_prev(3))*(Mu_prev(11)*cos(Mu_prev(4)) - Mu_prev(9)*sin(Mu_prev(4)) - ut(5)*cos(Mu_prev(4)) + ut(3)*sin(Mu_prev(4))))/pow(cos(Mu_prev(3)),2),                                                                                                                          (Mu_prev(9)*cos(Mu_prev(4)) + Mu_prev(11)*sin(Mu_prev(4)) - ut(3)*cos(Mu_prev(4)) - ut(5)*sin(Mu_prev(4)))/cos(Mu_prev(3)),                                                                                                                                                                                                                                                                                                                                                                                         0, 0, 0, 0,                          sin(Mu_prev(4))/cos(Mu_prev(3)),  0,                        -cos(Mu_prev(4))/cos(Mu_prev(3)),                                                                                                                 0,                                            0,                                                                                                                 0,\r\n  0, 0, 0, cos(Mu_prev(3))*sin(Mu_prev(4))*sin(Mu_prev(5))*(Mu_prev(12) - ut(0)) - cos(Mu_prev(3))*cos(Mu_prev(4))*sin(Mu_prev(5))*(Mu_prev(14) - ut(2)) - sin(Mu_prev(3))*sin(Mu_prev(5))*(Mu_prev(13) - ut(1)), (Mu_prev(12) - ut(0))*(cos(Mu_prev(5))*sin(Mu_prev(4)) + cos(Mu_prev(4))*sin(Mu_prev(3))*sin(Mu_prev(5))) - (Mu_prev(14) - ut(2))*(cos(Mu_prev(4))*cos(Mu_prev(5)) - sin(Mu_prev(3))*sin(Mu_prev(4))*sin(Mu_prev(5))), (Mu_prev(12) - ut(0))*(cos(Mu_prev(4))*sin(Mu_prev(5)) + cos(Mu_prev(5))*sin(Mu_prev(3))*sin(Mu_prev(4))) + (Mu_prev(14) - ut(2))*(sin(Mu_prev(4))*sin(Mu_prev(5)) - cos(Mu_prev(4))*cos(Mu_prev(5))*sin(Mu_prev(3))) + cos(Mu_prev(3))*cos(Mu_prev(5))*(Mu_prev(13) - ut(1)), 0, 0, 0,                                                                    0,  0,                                                                   0,   sin(Mu_prev(3))*sin(Mu_prev(4))*sin(Mu_prev(5)) - cos(Mu_prev(4))*cos(Mu_prev(5)),  cos(Mu_prev(3))*sin(Mu_prev(5)), - cos(Mu_prev(5))*sin(Mu_prev(4)) - cos(Mu_prev(4))*sin(Mu_prev(3))*sin(Mu_prev(5)),\r\n  0, 0, 0, cos(Mu_prev(5))*sin(Mu_prev(3))*(Mu_prev(13) - ut(1)) - cos(Mu_prev(3))*cos(Mu_prev(5))*sin(Mu_prev(4))*(Mu_prev(12) - ut(0)) + cos(Mu_prev(3))*cos(Mu_prev(4))*cos(Mu_prev(5))*(Mu_prev(14) - ut(2)), (Mu_prev(12) - ut(0))*(sin(Mu_prev(4))*sin(Mu_prev(5)) - cos(Mu_prev(4))*cos(Mu_prev(5))*sin(Mu_prev(3))) - (Mu_prev(14) - ut(2))*(cos(Mu_prev(4))*sin(Mu_prev(5)) + cos(Mu_prev(5))*sin(Mu_prev(3))*sin(Mu_prev(4))), cos(Mu_prev(3))*sin(Mu_prev(5))*(Mu_prev(13) - ut(1)) - (Mu_prev(14) - ut(2))*(cos(Mu_prev(5))*sin(Mu_prev(4)) + cos(Mu_prev(4))*sin(Mu_prev(3))*sin(Mu_prev(5))) - (Mu_prev(12) - ut(0))*(cos(Mu_prev(4))*cos(Mu_prev(5)) - sin(Mu_prev(3))*sin(Mu_prev(4))*sin(Mu_prev(5))), 0, 0, 0,                                                                    0,  0,                                                                   0, - cos(Mu_prev(4))*sin(Mu_prev(5)) - cos(Mu_prev(5))*sin(Mu_prev(3))*sin(Mu_prev(4)), -cos(Mu_prev(3))*cos(Mu_prev(5)),   cos(Mu_prev(4))*cos(Mu_prev(5))*sin(Mu_prev(3)) - sin(Mu_prev(4))*sin(Mu_prev(5)),\r\n  0, 0, 0,cos(Mu_prev(4))*sin(Mu_prev(3))*(Mu_prev(14) - ut(2)) - cos(Mu_prev(3))*(Mu_prev(13) - ut(1)) - sin(Mu_prev(3))*sin(Mu_prev(4))*(Mu_prev(12) - ut(0)),                                                                                                                                             cos(Mu_prev(3))*cos(Mu_prev(4))*(Mu_prev(12) - ut(0)) + cos(Mu_prev(3))*sin(Mu_prev(4))*(Mu_prev(14) - ut(2)),                                                                                                                                                                                                                                                                                                                                                                                         0, 0, 0, 0,                                                                    0,  0,                                                                   0,                                                                       cos(Mu_prev(3))*sin(Mu_prev(4)),                       -sin(Mu_prev(3)),                                                                      -cos(Mu_prev(3))*cos(Mu_prev(4)),\r\n                    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\r\n                    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\r\n                    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\r\n                    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\r\n\t\t\t\t\t0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\r\n\t\t\t\t\t0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;\r\n\t//get matrix Ut\r\n\tUt            <<0,                                            0,                                                                                                                 0,                                                                    0,  0,                                                                   0, 0, 0, 0, 0, 0, 0,\r\n                                                                                                                  0,                                            0,                                                                                                                 0,                                                                    0,  0,                                                                   0, 0, 0, 0, 0, 0, 0,\r\n                                                                                                                  0,                                            0,                                                                                                                 0,                                                                    0,  0,                                                                   0, 0, 0, 0, 0, 0, 0,\r\n                                                                                                                  0,                                            0,                                                                                                                 0,                                               -cos(Mu_prev(4)),  0,                                              -sin(Mu_prev(4)), 0, 0, 0, 0, 0, 0,\r\n                                                                                                                  0,                                            0,                                                                                                                 0, -(sin(Mu_prev(3))*sin(Mu_prev(4)))/cos(Mu_prev(3)), -1, (cos(Mu_prev(4))*sin(Mu_prev(3)))/cos(Mu_prev(3)), 0, 0, 0, 0, 0, 0,\r\n                                                                                                                  0,                                            0,                                                                                                                 0,                          sin(Mu_prev(4))/cos(Mu_prev(3)),  0,                        -cos(Mu_prev(4))/cos(Mu_prev(3)), 0, 0, 0, 0, 0, 0,\r\n    sin(Mu_prev(3))*sin(Mu_prev(4))*sin(Mu_prev(5)) - cos(Mu_prev(4))*cos(Mu_prev(5)),  cos(Mu_prev(3))*sin(Mu_prev(5)), - cos(Mu_prev(5))*sin(Mu_prev(4)) - cos(Mu_prev(4))*sin(Mu_prev(3))*sin(Mu_prev(5)),                                                                    0,  0,                                                                   0, 0, 0, 0, 0, 0, 0,\r\n  - cos(Mu_prev(4))*sin(Mu_prev(5)) - cos(Mu_prev(5))*sin(Mu_prev(3))*sin(Mu_prev(4)), -cos(Mu_prev(3))*cos(Mu_prev(5)),   cos(Mu_prev(4))*cos(Mu_prev(5))*sin(Mu_prev(3)) - sin(Mu_prev(4))*sin(Mu_prev(5)),                                                                    0,  0,                                                                   0, 0, 0, 0, 0, 0, 0,\r\n                                                                        cos(Mu_prev(3))*sin(Mu_prev(4)),                       -sin(Mu_prev(3)),                                                                      -cos(Mu_prev(3))*cos(Mu_prev(4)),                                                                    0,  0,                                                                   0, 0, 0, 0, 0, 0, 0,\r\n                                                                                                                  0,                                            0,                                                                                                                 0,                                                                    0,  0,                                                                   0, 0, 0, 0, 1, 0, 0,\r\n                                                                                                                  0,                                            0,                                                                                                                 0,                                                                    0,  0,                                                                   0, 0, 0, 0, 0, 1, 0,\r\n                                                                                                                  0,                                            0,                                                                                                                 0,                                                                    0,  0,                                                                   0, 0, 0, 0, 0, 0, 1,\r\n                                                                                                                  0,                                            0,                                                                                                                 0,                                                                    0,  0,                                                                   0, 1, 0, 0, 0, 0, 0,\r\n                                                                                                                  0,                                            0,                                                                                                                 0,                                                                    0,  0,                                                                   0, 0, 1, 0, 0, 0, 0,\r\n                                                                                                                  0,                                            0,                                                                                                                 0,                                                                    0,  0,                                                                   0, 0, 0, 1, 0, 0, 0;\r\n \r\n\t//get Mu_bar\r\n\tgrav = 9.8;\r\n\tprocess_model << Mu_prev(6),\r\n                     Mu_prev(7),\r\n                     Mu_prev(8),\r\n  ut(3)*cos(Mu_prev(4)) - Mu_prev(11)*sin(Mu_prev(4)) - Mu_prev(9)*cos(Mu_prev(4)) + ut(5)*sin(Mu_prev(4)),\r\n-(Mu_prev(10)*cos(Mu_prev(3)) - ut(4)*cos(Mu_prev(3)) - Mu_prev(11)*cos(Mu_prev(4))*sin(Mu_prev(3)) + Mu_prev(9)*sin(Mu_prev(3))*sin(Mu_prev(4)) + ut(5)*cos(Mu_prev(4))*sin(Mu_prev(3)) - ut(3)*sin(Mu_prev(3))*sin(Mu_prev(4)))/cos(Mu_prev(3)),\r\n-(Mu_prev(11)*cos(Mu_prev(4)) - Mu_prev(9)*sin(Mu_prev(4)) - ut(5)*cos(Mu_prev(4)) + ut(3)*sin(Mu_prev(4)))/cos(Mu_prev(3)),\r\n  - (Mu_prev(12) - ut(0))*(cos(Mu_prev(4))*cos(Mu_prev(5)) - sin(Mu_prev(3))*sin(Mu_prev(4))*sin(Mu_prev(5))) - (Mu_prev(14) - ut(2))*(cos(Mu_prev(5))*sin(Mu_prev(4)) + cos(Mu_prev(4))*sin(Mu_prev(3))*sin(Mu_prev(5))) + cos(Mu_prev(3))*sin(Mu_prev(5))*(Mu_prev(13) - ut(1)),\r\n  - (Mu_prev(12) - ut(0))*(cos(Mu_prev(4))*sin(Mu_prev(5)) + cos(Mu_prev(5))*sin(Mu_prev(3))*sin(Mu_prev(4))) - (Mu_prev(14) - ut(2))*(sin(Mu_prev(4))*sin(Mu_prev(5)) - cos(Mu_prev(4))*cos(Mu_prev(5))*sin(Mu_prev(3))) - cos(Mu_prev(3))*cos(Mu_prev(5))*(Mu_prev(13) - ut(1)),\r\ngrav - sin(Mu_prev(3))*(Mu_prev(13) - ut(1)) - cos(Mu_prev(3))*cos(Mu_prev(4))*(Mu_prev(14) - ut(2)) + cos(Mu_prev(3))*sin(Mu_prev(4))*(Mu_prev(12) - ut(0)),\r\n                     0,\r\n                     0,\r\n                     0,\r\n\t\t\t\t\t 0,\r\n\t\t\t\t\t 0,\r\n\t\t\t\t\t 0;\r\n\t}\r\n\tMu_bar     = Mu_prev + dt * process_model;\r\n\t//get Sigma_bar\r\n\tFt         = MatrixXd::Identity(15, 15) + dt * At;\r\n\tVt         = dt * Ut;\r\n\tSigma_bar  = Ft * Sigma_prev * Ft.transpose() + Vt * Q * Vt.transpose();\r\n\r\n\t//cout << \"process_model\" << endl << process_model << endl;\r\n}\r\n/*Prediction Step*/\r\n/*Updata Step*/\r\n{\r\n\t//transform imu to world using camera\r\n\t/*H_CAMinIMU\t<<\r\n\t-1,0,0 ,0    ,\r\n\t0 ,1,0 ,-0.04,\r\n\t0 ,0,-1,-0.02,\r\n\t0 ,0,0 ,1    ;*/\r\n\tH_CAMinIMU.col(0) << Rcam.col(0)  , 0;\r\n\tH_CAMinIMU.col(1) << Rcam.col(1)  , 0;\r\n\tH_CAMinIMU.col(2) << Rcam.col(2)  , 0;\r\n\tH_CAMinIMU.col(3) << 0,-0.04,-0.02, 1;\r\n\tT_WorldinCAM(0) = msg->pose.pose.position.x;\r\n\tT_WorldinCAM(1) = msg->pose.pose.position.y;\r\n\tT_WorldinCAM(2) = msg->pose.pose.position.z;\r\n\tQ_WorldinCAM(0) = msg->pose.pose.orientation.w;\r\n\tQ_WorldinCAM(1) = msg->pose.pose.orientation.x;\r\n\tQ_WorldinCAM(2) = msg->pose.pose.orientation.y;\r\n\tQ_WorldinCAM(3) = msg->pose.pose.orientation.z;\r\n    R_WorldinCAM = Quaterniond(Q_WorldinCAM(0),Q_WorldinCAM(1),Q_WorldinCAM(2),Q_WorldinCAM(3)).toRotationMatrix();\r\n\t\r\n\tH_WorldinCAM.col(0) << R_WorldinCAM.col(0), 0;\r\n\tH_WorldinCAM.col(1) << R_WorldinCAM.col(1), 0;\r\n\tH_WorldinCAM.col(2) << R_WorldinCAM.col(2), 0;\r\n\tH_WorldinCAM.col(3) << T_WorldinCAM       , 1;\r\n\t\r\n\tH_IMUinWorld = H_WorldinCAM.inverse() * H_CAMinIMU.inverse()  ;//????????????????\r\n\tR_IMUinWorld = H_IMUinWorld.topLeftCorner(3, 3);\r\n\tT_IMUinWorld = H_IMUinWorld.topRightCorner(3, 1);\r\n\t//cout << \"H_IMUinWorld\" << endl << H_IMUinWorld << endl;\r\n\t//get matrix Ct\r\n\tCt   << MatrixXd::Identity(6, 15);\r\n\t//get matrix Kt\r\n\tKt   =  Sigma_bar * Ct.transpose() * ((Ct * Sigma_bar * Ct.transpose() + MatrixXd::Identity(6, 6) * Rt * MatrixXd::Identity(6, 6)).inverse());\r\n\t//get Mu & Sigma\r\n\tx.head(3) = T_IMUinWorld;\r\n\tx(3) = asin(R_IMUinWorld(2,1));\r\n\t//x(4) = atan(-R_IMUinWorld(2,0)/R_IMUinWorld(2,2));\r\n\t//x(5) = atan(-R_IMUinWorld(0,1)/R_IMUinWorld(1,1));\r\n\t//x(4) = acos(R_IMUinWorld(2,2)/cos(x(3)));\r\n\tx(4) = asin(-R_IMUinWorld(0,2)/cos(x(3)));\r\n\tif ((R_IMUinWorld(0,2)/cos(x(3)))>1)\r\n\t{\r\n\t\tx(4) = asin(1);\r\n\t}\r\n\tif ((R_IMUinWorld(0,2)/cos(x(3)))<-1)\r\n\t{\r\n\t\tx(4) = asin(-1);\r\n\t}\r\n\tx(5) = acos(R_IMUinWorld(1,1)/cos(x(3)));\r\n\t//x(5) = asin(-R_IMUinWorld(0,1)/cos(x(3)));\r\n\t//x.segment(3,3) = R_IMUinWorld.eulerAngles(1, 2, 0);\r\n\t\r\n\t\r\n\tMu   =  Mu_bar + Kt * (Ct*x - Ct*Mu_bar);\r\n\tSigma=  Sigma_bar - Kt*Ct*Sigma_bar;\r\n\r\n\t\r\n\tif(std::isnan(Mu(0))&&temp_ff==0)\r\n\t{\r\n\t\tcout << \"asin(-R_IMUinWorld(0,2)/cos(x(3)))\" << endl << asin(-R_IMUinWorld(0,2)/cos(x(3))) << endl;\r\n\t\tcout << \"R_IMUinWorld(0,2)\" << endl << R_IMUinWorld(0,2) << endl;\r\n\t\tcout << \"cos(x(3))\" << endl << cos(x(3)) << endl;\r\n\t\tcout << \"x\" << endl << x << endl;\r\n\t\tcout << \"Kt\" << endl << Kt << endl;\r\n\t\tcout << \"Mu_bar\" << endl << Mu_prev << endl;\r\n\t\t/*cout << \"Mu_prev\" << endl << Mu_prev << endl;\r\n\t\tcout << \"Ft\" << endl << Ft << endl;\r\n\t\tcout << \"Sigma_prev\" << endl << Sigma_prev << endl;\r\n\t\tcout << \"Sigma_bar\" << endl << Sigma_bar << endl;*/\r\n\t\tcout << \"dt\" << endl << dt << endl;\r\n\t\tcout << \"img_checktemp\" << endl << img_checktemp << endl;\r\n\t\ttemp_ff = 1;\r\n\t}\r\n\t//cout << \"Mu\" << endl << Mu << endl;\r\n\tif (img_checktemp>=0&&img_checktemp<=1) \r\n    {\r\n\t//cout << \"Sigma_bar\" << endl << Sigma_bar << endl;\r\n\t//cout << \"Mu_bar\" << endl << Mu_bar << endl;\r\n\t//cout << \"Ut\" << endl << Mu_prev << endl;\r\n   // cout << \"At\" << endl << At << endl;\r\n    //cout << \"H_WorldinCAM\" << endl << H_WorldinCAM << endl;\r\n\tcout << \"H_CAMinIMU * H_WorldinCAM\" << endl << H_CAMinIMU * H_WorldinCAM << endl;\r\n\tcout << \"H_WorldinCAM * H_CAMinIMU\" << endl << H_WorldinCAM * H_CAMinIMU << endl;\r\n    cout << \"H_IMUinWorld\" << endl << H_IMUinWorld << endl;\r\n\t//cout << \"H_IMUinWorld.topRightCorner(3, 1)\" << endl << H_IMUinWorld.topRightCorner(3, 1) << endl;\r\n\t//cout << \"H_IMUinWorld.topLeftCorner(3, 3)\"  << endl << H_IMUinWorld.topLeftCorner(3, 3)  << endl;\r\n\t//cout << \"(Ct * Sigma_bar * Ct.transpose())\" << endl << (Ct * Sigma_bar * Ct.transpose()) << endl;\r\n\t//cout << \"Kt\" << endl << Kt << endl;\r\n\tcout <<endl<< \"***********************************\"<<endl;\t\r\n    }\r\n\timg_checktemp ++;\r\n\t//cout << \"Kt\" << endl << Kt << endl;\r\n\tMatrix3d m_temp;//??????????????\r\n\tm_temp << \r\n\tcos(Mu(4))*cos(Mu(5))-sin(Mu(3))*sin(Mu(4))*sin(Mu(5)), -cos(Mu(3))*sin(Mu(5)), sin(Mu(4))*cos(Mu(5))+sin(Mu(3))*cos(Mu(4))*sin(Mu(5)),\r\n    cos(Mu(4))*sin(Mu(5))+sin(Mu(3))*sin(Mu(4))*cos(Mu(5)), cos(Mu(3))*cos(Mu(5)) , sin(Mu(4))*sin(Mu(5))-sin(Mu(3))*cos(Mu(4))*cos(Mu(5)),\r\n    -cos(Mu(3))*sin(Mu(4))                                , sin(Mu(3))            , cos(Mu(3))*cos(Mu(4))                                 ;\r\n\tQuaterniond Q_ekf;\r\n    Q_ekf = m_temp;\r\n    nav_msgs::Odometry odom_ekf;\r\n    odom_ekf.header.stamp = msg->header.stamp;\r\n    odom_ekf.header.frame_id = \"world\";\r\n    odom_ekf.pose.pose.position.x = Mu(0);\r\n    odom_ekf.pose.pose.position.y = Mu(1);\r\n    odom_ekf.pose.pose.position.z = Mu(2);\r\n    odom_ekf.pose.pose.orientation.w = Q_ekf.w();\r\n    odom_ekf.pose.pose.orientation.x = Q_ekf.x();\r\n    odom_ekf.pose.pose.orientation.y = Q_ekf.y();\r\n    odom_ekf.pose.pose.orientation.z = Q_ekf.z();\r\n\todom_ekf.twist.twist.linear.x    = Mu(6);\r\n\todom_ekf.twist.twist.linear.y    = Mu(7);\r\n\todom_ekf.twist.twist.linear.z    = Mu(8);\r\n    odom_pub.publish(odom_ekf);\r\n}\r\n/*Updata Step*/\t\r\n}\r\n\r\nint main(int argc, char **argv)\r\n{\r\n    ros::init(argc, argv, \"ekf\");\r\n    ros::NodeHandle n(\"~\");\r\n    ros::Subscriber s1 = n.subscribe(\"imu\", 1000, imu_callback);\r\n    ros::Subscriber s2 = n.subscribe(\"tag_odom\", 1000, odom_callback);\r\n    odom_pub = n.advertise<nav_msgs::Odometry>(\"ekf_odom\", 100);\r\n    Rcam = Quaterniond(0, 0, -1, 0).toRotationMatrix();\r\n    cout << \"R_cam\" << endl << Rcam << endl;\r\n    // Q imu covariance matrix; Rt visual odomtry covariance matrix\r\n    Q.topLeftCorner(6, 6) = 0.01 * Q.topLeftCorner(6, 6);   \r\n    Q.bottomRightCorner(6, 6) = 0.01 * Q.bottomRightCorner(6, 6); \r\n    Rt.topLeftCorner(3, 3) = 0.5 * Rt.topLeftCorner(3, 3);  \r\n    Rt.bottomRightCorner(3, 3) = 0.5 * Rt.bottomRightCorner(3, 3); \r\n    Rt.bottomRightCorner(1, 1) = 0.1 * Rt.bottomRightCorner(1, 1); \r\n\r\n    ros::spin();\r\n}", "meta": {"hexsha": "e7ea5055bf97a713bcf4cc48c0526ddd1b435126", "size": 23793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ekf_node.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_node.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_node.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": 81.7628865979, "max_line_length": 1189, "alphanum_fraction": 0.372966839, "num_tokens": 6646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.534538254537233}}
{"text": "// this example shows how to compute elastic model energy, energy gradient and energy hessian\n\n#include <iostream>\n#include <math.h>\n#include <time.h>\n#include <fstream>\n\n#include \"MCSFD/MCSFDCore.h\"\n#include \"LoboVolumtricMesh/LoboTetMesh.h\"\n#include \"ElasticModel/HyperelasticModel.h\"\n\n#include \"Utils/pugixml/pugixml.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include \"Utils/SparseMatrix/SparseMatrixTopology.h\"\n#include <omp.h>\n\nLOBO_MAKE_TYPEDEFS(double, t);\n\nusing namespace Lobo;\n\nvoid loadmaterial(Lobo::HyperelasticModel *elasticmodel, const char *xmlfile)\n{\n    pugi::xml_document xml_doc;\n    pugi::xml_parse_result result = xml_doc.load_file(xmlfile);\n    pugi::xml_node model_node = xml_doc.child(\"Scene\").child(\"HyperelasticModel\");\n    elasticmodel->runXMLscript(model_node);\n    elasticmodel->precompute();\n    elasticmodel->useMCSFD = false;\n    elasticmodel->isinvertible = false;\n}\n\nint main()\n{\n    omp_set_dynamic(0); // Explicitly disable dynamic teams\n    omp_set_num_threads(\n        1); // Use 4 threads for all consecutive parallel regions\n\n    Lobo::LoboTetMesh *tetmesh = new Lobo::LoboTetMesh();\n    tetmesh->loadTetMeshAscii(\"2tet\");\n    std::cout << tetmesh->tet_indices.size() << std::endl;\n    Lobo::HyperelasticModel *stvkmodel = new Lobo::HyperelasticModel(tetmesh);\n    loadmaterial(stvkmodel, \"FEM_stvk.xml\");\n    Lobo::HyperelasticModel *stvkmodel_csfd = new Lobo::HyperelasticModel(tetmesh);\n    loadmaterial(stvkmodel_csfd, \"FEM_stvkCSFD.xml\");\n\n    Lobo::HyperelasticModel *neohookeanmodel = new Lobo::HyperelasticModel(tetmesh);\n    loadmaterial(neohookeanmodel, \"FEM_neohookean.xml\");\n    Lobo::HyperelasticModel *neohookeanmodel_csfd = new Lobo::HyperelasticModel(tetmesh);\n    loadmaterial(neohookeanmodel_csfd, \"FEM_neohookeanCSFD.xml\");\n\n    int num_dofs = tetmesh->getNumVertex() * 3;\n    Eigen::VectorXd u(num_dofs);\n    Eigen::VectorXd internalforce(num_dofs);\n\n    int flags_all = 0;\n    flags_all |= Computeflags_energy | Computeflags_fisrt | Computeflags_second;\n\n    srand(time(NULL));\n    u.setRandom();\n\n    stvkmodel->currentdisplacement = u;\n    stvkmodel_csfd->currentdisplacement = u;\n    neohookeanmodel->currentdisplacement = u;\n    neohookeanmodel_csfd->currentdisplacement = u;\n\n    int numtest = 10000;\n    clock_t t1 = clock();\n\n    //compute energy, energy gradient, energy hessian with analytical function\n    for (int i = 0; i < numtest; i++)\n    {\n        stvkmodel->getTetForceMatrix(0, stvkmodel->internalforce_list[0], stvkmodel->stiffness_list[0], flags_all);\n    }\n\n    clock_t t2 = clock();\n    //std::cout << *stvkmodel->stiffness_list[0] << std::endl;\n    std::cout << \"no MSCFD stvk \" << (double)(t2 - t1) / CLOCKS_PER_SEC << \"s\" << std::endl;\n\n    t1 = clock();\n\n    //compute energy, energy gradient, energy hessian with MSCFD\n    for (int i = 0; i < numtest; i++)\n    {\n        stvkmodel_csfd->getTetForceMatrix(0, stvkmodel_csfd->internalforce_list[0], stvkmodel_csfd->stiffness_list[0], flags_all);\n    }\n\n    t2 = clock();\n\n    //std::cout << *stvkmodel_csfd->stiffness_list[0] << std::endl;\n    std::cout << \"MSCFD stvk \" << (double)(t2 - t1) / CLOCKS_PER_SEC << \"s\" << std::endl;\n\n    t1 = clock();\n\n    //compute energy, energy gradient, energy hessian with MSCFD\n    for (int i = 0; i < numtest; i++)\n    {\n        stvkmodel_csfd->getTetForceMatrixCSFD(0, stvkmodel_csfd->internalforce_list[0], stvkmodel_csfd->stiffness_list[0]);\n    }\n\n    t2 = clock();\n\n    //std::cout << *stvkmodel_csfd->stiffness_list[0] << std::endl;\n    std::cout << \"no image MSCFD stvk \" << (double)(t2 - t1) / CLOCKS_PER_SEC << \"s\" << std::endl;\n\n\n    t1 = clock();\n\n    //compute energy, energy gradient, energy hessian with MSCFD\n    for (int i = 0; i < numtest; i++)\n    {\n        neohookeanmodel->getTetForceMatrix(0, neohookeanmodel->internalforce_list[0], neohookeanmodel->stiffness_list[0], flags_all);\n    }\n\n    t2 = clock();\n\n    //std::cout << *neohookeanmodel->stiffness_list[0] << std::endl;\n    std::cout << \"no MSCFD neohookean \" << (double)(t2 - t1) / CLOCKS_PER_SEC << \"s\" << std::endl;\n\n\n    t1 = clock();\n\n    //compute energy, energy gradient, energy hessian with MSCFD\n    for (int i = 0; i < numtest; i++)\n    {\n        neohookeanmodel_csfd->getTetForceMatrix(0, neohookeanmodel_csfd->internalforce_list[0], neohookeanmodel_csfd->stiffness_list[0], flags_all);\n    }\n\n    t2 = clock();\n\n    //std::cout << *neohookeanmodel_csfd->stiffness_list[0] << std::endl;\n    std::cout << \"MSCFD neohookean \" << (double)(t2 - t1) / CLOCKS_PER_SEC << \"s\" << std::endl;\n    //delete tetmesh;\n    //delete hyperelasticmodel_csfd;\n    //delete hyperelasticmodel;\n\n    return 0;\n}\n", "meta": {"hexsha": "5f79b3fdda7a61cbfcf2bb8841ce60de2bce8d77", "size": 4665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example1.cpp", "max_stars_repo_name": "lrquad/MCSFD", "max_stars_repo_head_hexsha": "a06ddda308334eb43e69524f6f03fac77de7992e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-11-26T03:06:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T02:42:27.000Z", "max_issues_repo_path": "example1.cpp", "max_issues_repo_name": "lrquad/MCSFD", "max_issues_repo_head_hexsha": "a06ddda308334eb43e69524f6f03fac77de7992e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example1.cpp", "max_forks_repo_name": "lrquad/MCSFD", "max_forks_repo_head_hexsha": "a06ddda308334eb43e69524f6f03fac77de7992e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-11T06:16:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-11T09:56:23.000Z", "avg_line_length": 33.3214285714, "max_line_length": 148, "alphanum_fraction": 0.6825294748, "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.534531831105272}}
{"text": "// Copyright (c) 2019 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 \"pyinterp/detail/gsl/interpolate1d.hpp\"\n#include \"pyinterp/detail/math.hpp\"\n#include <Eigen/Core>\n\nnamespace pyinterp {\nnamespace detail {\nnamespace math {\n\n/// Set of coordinates/values used for interpolation\n///  * q11 = (x1, y1)\n///  * q12 = (x1, y2)\n///  * .../...\n///  * q1n = (x1, yn)\n///  * q21 = (x2, y1)\n///  * q22 = (x2, y2).\n///  * .../...\n///  * q2n = (x2, yn)\n///  * .../...\n///  * qnn = (xn, yn)\n///\n/// @code\n/// Array({{x1, x2, ..., xn}, {y1, y2, ..., yn}},\n///        {q11, q12, ..., q21, q22, ...., qnn})\n/// @endcode\nclass XArray {\n public:\n  /// Default constructor\n  XArray() = delete;\n\n  /// Creates a new Array\n  XArray(const size_t x_size, const size_t y_size) {\n    auto nx = x_size << 1U;\n    auto ny = y_size << 1U;\n    x_.resize(nx);\n    y_.resize(ny);\n    q_.resize(nx, ny);\n  }\n\n  /// Default destructor\n  virtual ~XArray() = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  XArray(const XArray &rhs) = default;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  XArray(XArray &&rhs) noexcept = default;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  XArray &operator=(const XArray &rhs) = default;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  XArray &operator=(XArray &&rhs) noexcept = default;\n\n  /// Get the half size of the window in abscissa.\n  inline size_t nx() const noexcept {\n    return static_cast<size_t>(x_.size()) >> 1U;\n  }\n\n  /// Get the half size of the window in ordinate.\n  inline size_t ny() const noexcept {\n    return static_cast<size_t>(y_.size()) >> 1U;\n  }\n\n  /// Get x-coordinates\n  inline Eigen::VectorXd &x() noexcept { return x_; }\n\n  /// Get x-coordinates\n  inline const Eigen::VectorXd &x() const noexcept { return x_; }\n\n  /// Get y-coordinates\n  inline Eigen::VectorXd &y() noexcept { return y_; }\n\n  /// Get y-coordinates\n  inline const Eigen::VectorXd &y() const noexcept { return y_; }\n\n  /// Get the values from the array for all x and y coordinates.\n  inline Eigen::MatrixXd &q() noexcept { return q_; }\n\n  /// Get the values from the array for all x and y coordinates.\n  inline const Eigen::MatrixXd &q() const noexcept { return q_; }\n\n  /// Get the ith x-axis.\n  inline double x(const size_t ix) const { return x_(ix); }\n\n  /// Get the ith y-axis.\n  inline double y(const size_t jx) const { return y_(jx); }\n\n  /// Get the value at coordinate (ix, jx).\n  inline double z(const size_t ix, const size_t jx) const { return q_(ix, jx); }\n\n  /// Set the ith x-axis.\n  inline double &x(const size_t ix) { return x_(ix); }\n\n  /// Get the ith y-axis.\n  inline double &y(const size_t jx) { return y_(jx); }\n\n  /// Get the value at coordinate (ix, jx).\n  inline double &z(const size_t ix, const size_t jx) { return q_(ix, jx); }\n\n  /// Normalizes the angle with respect to the first value of the X axis of this\n  /// array.\n  inline double normalize_angle(const double xi) const {\n    return math::normalize_angle(xi, x(0));\n  }\n\n  /// Returns true if this instance does not contains at least one Not A Number\n  /// (NaN).\n  inline bool is_valid() const { return !q_.hasNaN(); }\n\n private:\n  Eigen::VectorXd x_{};\n  Eigen::VectorXd y_{};\n  Eigen::MatrixXd q_{};\n};\n\n/// Extension of cubic interpolation for interpolating data points on a\n/// two-dimensional regular grid. The interpolated surface is smoother than\n/// corresponding surfaces obtained by bilinear interpolation or\n/// nearest-neighbor interpolation.\nclass Bicubic {\n public:\n  /// Default constructor\n  ///\n  /// @param type method of calculation\n  explicit Bicubic(const gsl_interp_type *type = gsl_interp_cspline)\n      : type_(type) {}\n\n  /// Return the interpolated value of y for a given point x\n  double interpolate(const double x, const double y, const XArray &xr,\n                     gsl::Accelerator acc = gsl::Accelerator()) const {\n    return evaluate(&gsl::Interpolate1D::interpolate, x, y, xr, std::move(acc));\n  }\n\n  /// Return the derivative for a given point x\n  double derivative(const double x, const double y, const XArray &xr,\n                    gsl::Accelerator acc = gsl::Accelerator()) const {\n    return evaluate(&gsl::Interpolate1D::derivative, x, y, xr, std::move(acc));\n  }\n\n  /// Return the second derivative for a given point x\n  double second_derivative(const double x, const double y, const XArray &xr,\n                           gsl::Accelerator acc = gsl::Accelerator()) const {\n    return evaluate(&gsl::Interpolate1D::second_derivative, x, y, xr,\n                    std::move(acc));\n  }\n\n private:\n  using InterpolateFunction =\n      double (gsl::Interpolate1D::*)(const double) const;\n  const gsl_interp_type *type_;\n\n  /// Evaluation of the GSL function performing the calculation.\n  double evaluate(\n      const std::function<double(const gsl::Interpolate1D &, double)> &function,\n      const double x, const double y, const XArray &xr,\n      gsl::Accelerator &&acc) const {\n    Eigen::VectorXd fy(xr.x().size());\n\n    // Spline interpolation as function of Y-coordinate\n    for (auto ix = 0; ix < xr.x().size(); ++ix) {\n      // The block containing the processed row must be copied into a new\n      // memory block.\n      Eigen::VectorXd row = xr.q().row(ix);\n      auto interpolator = gsl::Interpolate1D(type_, xr.y(), row, acc);\n      fy(ix) = function(interpolator, y);\n    }\n    auto interpolator = gsl::Interpolate1D(type_, xr.x(), fy, acc);\n    return function(interpolator, x);\n  }\n};\n\n}  // namespace math\n}  // namespace detail\n}  // namespace pyinterp\n", "meta": {"hexsha": "afefe2d36d022438173f7b80d51b982a5d08d6d1", "size": 5684, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/bicubic.hpp", "max_stars_repo_name": "apatlpo/pangeo-pyinterp", "max_stars_repo_head_hexsha": "b5242c6869d7e601a5695b304c81992deb63367d", "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/bicubic.hpp", "max_issues_repo_name": "apatlpo/pangeo-pyinterp", "max_issues_repo_head_hexsha": "b5242c6869d7e601a5695b304c81992deb63367d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/bicubic.hpp", "max_forks_repo_name": "apatlpo/pangeo-pyinterp", "max_forks_repo_head_hexsha": "b5242c6869d7e601a5695b304c81992deb63367d", "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.2340425532, "max_line_length": 80, "alphanum_fraction": 0.6396903589, "num_tokens": 1540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5345318293726953}}
{"text": "// Copyright (c) 2019 fortiss GmbH, Julian Bernhard, Klemens Esterle, Patrick Hart, 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\n#include <math.h>\n#include <limits>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include \"modules/world/opendrive/plan_view.hpp\"\n#include \"modules/world/opendrive/lane.hpp\"\n#include \"modules/world/opendrive/odrSpiral.hpp\"\n\nnamespace modules {\nnamespace world {\nnamespace opendrive {\n\nnamespace bg = boost::geometry;\n\nbool PlanView::add_line(geometry::Point2d start_point,\n                        float heading,\n                        float length) {\n  //! straight line\n  reference_line_.add_point(start_point);\n  geometry::Point2d end_point(\n    bg::get<0>(start_point) + length * cos(heading),\n    bg::get<1>(start_point) + length * sin(heading));\n  reference_line_.add_point(end_point);\n  //! calculate overall length\n  length_ = bg::length(reference_line_.obj_);\n  return true;\n}\n\nbool PlanView::add_spiral(\n  geometry::Point2d start_point,\n  float heading,\n  float length,\n  float curvature_start,\n  float curvature_end,\n  float s_inc) {\n  double x = bg::get<0>(start_point);\n  double y = bg::get<1>(start_point);\n  double t = heading, cDot = (curvature_end - curvature_start) / length;\n  double x_old = bg::get<0>(start_point), y_old = bg::get<1>(start_point);\n\n  double s = 0.0;\n  for (; s <= length;) {\n    odrSpiral(s, x_old, y_old, cDot, curvature_start, heading, &x, &y, &t);\n    reference_line_.add_point(geometry::Point2d(x, y));\n    if ((length - s < s_inc) && (length - s > 0.))\n      s_inc = length - s;\n    s += s_inc;\n  }\n  length_ = bg::length(reference_line_.obj_);\n  return true;\n}\n\nvoid PlanView::calc_arc_position(\n  const float s,\n  float initial_heading,\n  float curvature,\n  float &dx,\n  float &dy) {\n  initial_heading = fmod(initial_heading, 2 * M_PI);\n  float hdg = initial_heading - M_PI / 2;\n  float a = 2 / curvature * sin(s * curvature / 2);\n  float alpha = (M_PI - s * curvature) / 2 - hdg;\n  dx = -1 * a * cos(alpha);\n  dy = a * sin(alpha);\n  // tangent = initial_heading + s * initial_curvature;\n}\n\nbool PlanView::add_arc(\n  geometry::Point2d start_point,\n  float heading,\n  float length,\n  float curvature,\n  float s_inc) {\n  // add_spiral(start_point, heading, length, curvature, curvature, s_inc);\n\n  float dx, dy;\n  double x_old = bg::get<0>(start_point), y_old = bg::get<1>(start_point);\n  double s = 0.0;\n  for (; s <= length;) {\n    calc_arc_position(s, heading, curvature, dx, dy);\n    reference_line_.add_point(geometry::Point2d(x_old + dx, y_old + dy));\n    if (length - s < s_inc && length - s > 0.)\n      s_inc = length - s;\n    s += s_inc;\n  }\n  return true;\n}\n\nbool PlanView::apply_offset_transform(float x, float y, float hdg) {\n  geometry::Line rotated_line = rotate(reference_line_, hdg);\n  geometry::Line transformed_line = translate(rotated_line, x, y);\n  reference_line_ = transformed_line;\n\n  return true;\n}\n\n}  // namespace opendrive\n}  // namespace world\n}  // namespace modules\n", "meta": {"hexsha": "cb300ba649e94bedacb10233bd6af32d1c5205e0", "size": 3099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/world/opendrive/plan_view.cpp", "max_stars_repo_name": "AKreutz/bark", "max_stars_repo_head_hexsha": "46c01339172b978fabc37aedebb7a67b7fa04449", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/world/opendrive/plan_view.cpp", "max_issues_repo_name": "AKreutz/bark", "max_issues_repo_head_hexsha": "46c01339172b978fabc37aedebb7a67b7fa04449", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/world/opendrive/plan_view.cpp", "max_forks_repo_name": "AKreutz/bark", "max_forks_repo_head_hexsha": "46c01339172b978fabc37aedebb7a67b7fa04449", "max_forks_repo_licenses": ["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.2358490566, "max_line_length": 98, "alphanum_fraction": 0.6757018393, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5345318185592224}}
{"text": "/*\n   Implementation of \"Highly efficient incremental estimation of Gaussian mixture models for online data stream clustering.\"\n\n   Used to merge multiple mixture models\n\n   Author: Ryan Watson\n\n */\n\n#include <omp.h>\n#include <vector>\n#include <numeric>\n#include <stdexcept>\n#include <iostream>\n#include <Eigen/Dense>\n\n\n#include \"merge.h\"\n#include \"libcluster.h\"\n#include \"probutils.h\"\n#include \"comutils.h\"\n#include \"distributions.h\"\n\n\n#include <boost/math/distributions/fisher_f.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace boost;\nusing namespace comutils;\nusing namespace probutils;\nusing namespace libcluster;\nusing namespace boost::math;\nusing namespace distributions;\n\nusing boost::math::chi_squared;\nusing boost::math::quantile;\nusing boost::math::complement;\n\n//\n// /*! \\brief Merge similar mixture components as specified in the reference provided below.\n//\n//    REF ::\n//    [1] Song, Mingzhou, and Hongbin Wang. \"Highly efficient incremental estimation of Gaussian mixture models for online data stream clustering.\" Intelligent Computing: Theory and Applications III. Vol. 5803. International Society for Optics and Photonics, 2005.\n//  */\n//\n//\n// Author: Ryan Watson\n//\n\n\n\nbool merge::checkCov(Eigen::MatrixXd data, Eigen::MatrixXd qZ, mixtureComponents priorModel, GaussWish currModel, double currWeight, int currModelIdx, double alpha)\n{\n        Eigen::MatrixXd transObs, chol, chol_inv, tmp;\n\n        chol = (priorModel.get<4>()).llt().matrixL();\n        chol_inv = chol.inverse();\n\n        int n = currModel.getN() + 1;\n        int d = (currModel.getmean()).size() + 1;\n\n        chi_squared dist((d*(d+1))/2);\n        double ucv = quantile(complement(dist, alpha));\n        double ucv2 = quantile(complement(dist, alpha/2.0));\n        double lcv = quantile(dist, alpha);\n        double lcv2 = quantile(dist, alpha/2.0);\n\n        ArrayXi mapidx = partobs(data, (qZ.col(currModelIdx).array()>0.5), tmp);\n        transObs.setZero(tmp.rows(),d);\n        for (int k = 0; k < tmp.rows(); k++)\n        {\n                transObs.row(k) = chol_inv * tmp.row(k);\n        }\n\n        if (transObs.rows() < 3) {return false; }\n        auto transCov = probutils::cov(transObs);\n        auto covDiff = transCov - Eigen::MatrixXd::Identity(d,d);\n        auto covDiff_sq = covDiff * covDiff;\n        double dd = static_cast<double>(d);\n        double nn = static_cast<double>(n);\n        double f = (1.0/dd) * ( (covDiff_sq).trace() );\n        double s = (dd/nn) * pow( (1.0/dd)*(transCov.trace()),2 );\n        double W = f - s + dd/nn;\n        double t_stat = ((nn*W*dd)/2.0);\n        if ( t_stat < ucv2 || t_stat > lcv2 ) { return true; }\n        return false;\n}\n\nbool merge::checkCovGMM(mixtureComponents prior, mixtureComponents test, double alpha)\n{\n        Eigen::MatrixXd test_cov, chol, chol_inv;\n\n        chol = (test.get<4>()).llt().matrixL();\n        chol_inv = chol.inverse();\n        test_cov = chol_inv * test.get<4>() * chol_inv.transpose();\n\n        int n = prior.get<1>() + 1;\n        int d = (prior.get<3>()).size() + 1;\n\n        chi_squared dist((d*(d+1))/2);\n        double ucv = quantile(complement(dist, alpha));\n        double ucv2 = quantile(complement(dist, alpha/2.0));\n        double lcv = quantile(dist, alpha);\n        double lcv2 = quantile(dist, alpha/2.0);\n\n        auto covDiff = test_cov - Eigen::MatrixXd::Identity(d,d);\n        auto covDiff_sq = covDiff * covDiff;\n        double dd = static_cast<double>(d);\n        double nn = static_cast<double>(n);\n        double f = (1.0/dd) * ( (covDiff_sq).trace() );\n        double s = (dd/nn) * pow( (1.0/dd)*(test_cov.trace()),2 );\n        double W = f - s + dd/nn;\n        double t_stat = ((nn*W*dd)/2.0);\n        if ( t_stat < ucv2 || t_stat > lcv2 ) { return true; }\n        return false;\n}\n\nbool merge::checkMean(mixtureComponents priorModel, GaussWish currModel, double alpha)\n{\n\n        int n = currModel.getN() + 1;\n        int d = (currModel.getmean()).size() + 1;\n        if (n-d <= 1) {return false; }\n        fisher_f dist(d, n-d);\n\n        double ucv = quantile(complement(dist, alpha));\n        double ucv2 = quantile(complement(dist, alpha/2.0));\n        double lcv = quantile(dist, alpha);\n        double lcv2 = quantile(dist, alpha/2.0);\n\n\n        Eigen::RowVectorXd meanDiff = currModel.getmean() - priorModel.get<3>();\n        double t = (meanDiff * currModel.getcov() * meanDiff.transpose());\n        double t_stat = (double)(n-d)/(double)(d*(n-1)) * pow(t,2.0);\n        if (t_stat < ucv) {  return true; }\n        return false;\n}\n\nbool merge::checkMeanGMM(mixtureComponents prior, mixtureComponents test, double alpha)\n{\n\n        int n = test.get<1>() + 1;\n        int d = (test.get<3>()).size() + 1;\n        if (n-d <= 1) {return false; }\n\n        fisher_f dist(d, n-d);\n\n        double ucv = quantile(complement(dist, alpha));\n        double ucv2 = quantile(complement(dist, alpha/2.0));\n        double lcv = quantile(dist, alpha);\n        double lcv2 = quantile(dist, alpha/2.0);\n\n\n        Eigen::RowVectorXd meanDiff = prior.get<3>() - test.get<3>();\n        double t = (meanDiff * test.get<4>() * meanDiff.transpose());\n        double t_stat = (double)(n-d)/(double)(d*(n-1)) * pow(t,2.0);\n        if (t_stat < ucv) {  return true; }\n        return false;\n}\n\n\nvector<double> merge::getPriorWeights(vector<mixtureComponents> gmm)\n{\n        vector<double> weights;\n        for (unsigned int i=0; i<gmm.size(); i++)\n        {\n                weights.push_back(gmm[i].get<2>());\n        }\n        return weights;\n}\n\nbool merge::checkComponent(Eigen::MatrixXd data, Eigen::MatrixXd qZ, mixtureComponents priorModel, GaussWish currModel, double currWeight, int currModelIdx, double alpha)\n{\n        if (checkCov(data, qZ, priorModel, currModel, currWeight, currModelIdx, alpha))\n        {\n                if (checkMean(priorModel, currModel, alpha))\n                        return true;\n                else\n                        return false;\n        }\n        return false;\n}\n\nbool merge::checkComponentGMM(mixtureComponents prior, mixtureComponents test, double alpha)\n{\n        if (checkCovGMM(prior, test, alpha))\n        {\n                if (checkMeanGMM(prior, test, alpha))\n                        return true;\n                else\n                        return false;\n        }\n        return false;\n}\n\n\nbool merge::sortbyobs(merge::mixtureComponents a, merge::mixtureComponents b)\n{\n        return (a.get<1>() < b.get<1>());\n}\n\n\nvector<merge::mixtureComponents> merge::updateObs(vector<merge::mixtureComponents> gmm, vector<int> numObs)\n{\n        unsigned int N(0);\n        for (unsigned int i=0; i<gmm.size(); i++)\n        {\n                N += numObs.at(i);\n        }\n\n        for (unsigned int i=0; i<gmm.size(); i++)\n        {\n                // update total num of obs.\n                gmm[i].get<0>() += N;\n                if (numObs.at(i) != 0 )\n                {\n                        // update num of obs in component\n                        gmm[i].get<1>() += numObs.at(i);\n                        // update components weight.\n                        gmm[i].get<2>() = gmm[i].get<1>() / double(gmm[i].get<0>());\n                }\n        }\n        return gmm;\n}\n\nvector<merge::mixtureComponents> merge::pruneMixtureModel(vector<merge::mixtureComponents> gmm, int truncLevel)\n{\n        if (gmm.size() < truncLevel)\n                return gmm;\n\n        merge::mixtureComponents currComponent;\n        sort(gmm.begin(), gmm.end(), sortbyobs);\n        while (gmm.size() > truncLevel)\n        {\n                currComponent = gmm[0];\n                int n = currComponent.get<1>();\n                for (unsigned int i=1; i<gmm.size(); i++)\n                {\n                        // update number of obs. for each component\n                        gmm[i].get<0>() = gmm[i].get<0>() - n;\n                        // update weight for each component\n                        gmm[i].get<2>() = (double)gmm[i].get<1>() / (double)gmm[i].get<0>();\n                }\n                gmm.erase(gmm.begin());\n        }\n\n        return gmm;\n}\n\nvector<merge::mixtureComponents> merge::mergeMixtureModel(Eigen::MatrixXd data, Eigen::MatrixXd qZ, vector<merge::mixtureComponents> priorModel, vector<GaussWish> currModel, StickBreak currWeight, double alpha, int truncLevel)\n{\n        vector<merge::mixtureComponents> gmm;\n        int dataCard = data.rows();\n\n        auto pWeights =  getPriorWeights(priorModel);\n        auto cWeights =  currWeight.Elogweight().exp().transpose();\n        int cc = 0;\n        vector<int> pModelMatches;\n        vector<int> cModelMatches;\n\n        if ( priorModel.size() == 0)\n        {\n                for (vector<GaussWish>::iterator j = currModel.begin(); j < currModel.end(); ++j)\n                {\n                        // num obs.\n                        int n = j->getN();\n                        // cluster weights\n                        double w = cWeights[cc];\n                        // cluster mean\n                        auto m = j->getmean();\n                        // cluster cov\n                        auto c = j->getcov();\n                        // add new component to mixture model\n                        gmm.push_back(boost::make_tuple(dataCard, n, w, m, c));\n                        cc+=1;\n                }\n                return gmm;\n        }\n\n        // remove cluster without sufficient obs.\n        int m_inc = 0;\n        for (vector<GaussWish>::iterator j = currModel.begin(); j < currModel.end(); ++j)\n        {\n                if (j->getN() < 2.0) {\n                        currModel.erase(currModel.begin() + m_inc);\n                }\n                m_inc++;\n        }\n\n        for (unsigned int i=0; i<priorModel.size(); i++)\n        {\n\n                for (vector<GaussWish>::iterator j = currModel.begin(); j < currModel.end(); ++j)\n                {\n                        if( checkComponent(data, qZ, priorModel[i], *j, cWeights[cc], cc, alpha)\n                            && !(std::find(pModelMatches.begin(), pModelMatches.end(), i) != pModelMatches.end())\n                            && !(std::find(cModelMatches.begin(), cModelMatches.end(), cc) != cModelMatches.end()) )\n                        {\n                                // merge components\n                                mixtureComponents pModel = priorModel[i];\n                                // update mean and cov based on eq.\n\n                                int NP = pModel.get<0>();\n                                int n = pModel.get<1>() +j->getN();\n                                double WP = pModel.get<2>();\n                                Eigen::RowVectorXd MP = pModel.get<3>();\n                                Eigen::MatrixXd CM = pModel.get<4>();\n                                double NPWP = NP*WP;\n\n                                Eigen::RowVectorXd MC = j->getmean();\n                                Eigen::MatrixXd CC = j->getcov();\n                                int NC = j->getN();\n\n                                auto denom = NPWP + NC;\n\n                                /// update mean --> REF:: [1] Eq. 6\n                                Eigen::RowVectorXd n_mean = (NPWP*MP + NC*MC )*(1/denom);\n\n                                Eigen::MatrixXd A = (NPWP*CM + NC*CC)*(1/denom);\n\n                                Eigen::MatrixXd cov_p = MP.transpose()*MP;\n                                Eigen::MatrixXd cov_c = MC.transpose()*MC;\n\n                                Eigen::MatrixXd B = ( NPWP*cov_p + NC*cov_c )*(1/denom);\n\n                                Eigen::MatrixXd C = n_mean.transpose() * n_mean;\n\n                                /// update cov --> REF:: [1] Eq. 7\n                                Eigen::MatrixXd n_cov = A + B - C;\n\n                                double w =  (NPWP + NC) /(double) (NP + dataCard);\n\n                                gmm.push_back(boost::make_tuple(NP+dataCard, n, w, n_mean, n_cov));\n                                pModelMatches.push_back(i);\n                                cModelMatches.push_back(cc);\n                        }\n                        cc+=1;\n                }\n                cc=0;\n        }\n\n        // Add all unmerged components from new GMM\n        int idx = 0;\n        for (vector<GaussWish>::iterator j = currModel.begin(); j < currModel.end(); ++j)\n        {\n                if (!(std::find(cModelMatches.begin(), cModelMatches.end(), idx) != cModelMatches.end()))\n                {\n                        Eigen::RowVectorXd MC = j->getmean();\n                        Eigen::MatrixXd CC = j->getcov();\n                        int NC = j->getN();\n                        int n = priorModel[0].get<0>() + dataCard;\n\n\n                        double w = NC/(double)n;\n\n                        gmm.push_back(boost::make_tuple(n, NC, w, MC, CC));\n                }\n\n                idx+=1;\n        }\n\n        // Add all unmerged components from previous GMM\n        idx = 0;\n        for (unsigned int i=0; i<priorModel.size(); i++)\n        {\n                mixtureComponents pModel;\n                pModel = priorModel[i];\n                if (!(std::find(pModelMatches.begin(), pModelMatches.end(), idx) != pModelMatches.end()))\n                {\n                        int NP = pModel.get<1>();\n                        int n = pModel.get<0>() + dataCard;\n                        double w = NP/(double)n;\n                        Eigen::RowVectorXd MP = pModel.get<3>();\n                        Eigen::MatrixXd CM = pModel.get<4>();\n\n                        gmm.push_back(boost::make_tuple(n, NP, w, MP, CM));\n                }\n\n                idx+=1;\n        }\n\n        // Merge equilavent components in new GMM\n        for (unsigned int i=0; i<gmm.size(); i++)\n        {\n                for (unsigned int j=0; j<gmm.size(); j++)\n                {\n                        if (i==j) {continue; }\n                        if (checkComponentGMM(gmm[i], gmm[j], alpha))\n                        {\n\n                                int NP = gmm[i].get<0>();\n                                int n = gmm[i].get<1>();\n                                double WP = gmm[i].get<2>();\n                                Eigen::RowVectorXd MP = gmm[i].get<3>();\n                                Eigen::MatrixXd CM = gmm[i].get<4>();\n                                double NPWP = NP*WP;\n\n                                int NH = gmm[j].get<0>();\n                                int nh = gmm[j].get<1>();\n                                double WH = gmm[j].get<2>();\n                                Eigen::RowVectorXd MH = gmm[j].get<3>();\n                                Eigen::MatrixXd CH = gmm[j].get<4>();\n                                double NHWH = NH*WH;\n\n                                auto denom = NPWP + NHWH;\n\n                                /// update mean --> REF:: [1] Eq. 6\n                                Eigen::RowVectorXd n_mean = (NPWP*MP + NHWH*MH )*(1/denom);\n\n                                Eigen::MatrixXd A = (NPWP*CM + NHWH*CH)*(1/denom);\n\n                                Eigen::MatrixXd cov_p = MP.transpose()*MP;\n                                Eigen::MatrixXd cov_c = MH.transpose()*MH;\n\n                                Eigen::MatrixXd B = ( NPWP*cov_p + NHWH*cov_c )*(1/denom);\n\n                                Eigen::MatrixXd C = n_mean.transpose() * n_mean;\n\n\n                                gmm[i].get<1>() = (n + nh);\n                                gmm[i].get<2>() = gmm[i].get<1>()/(double) (NP);\n                                gmm[i].get<3>() = n_mean;\n                                /// update cov --> REF:: [1] Eq. 7\n                                gmm[i].get<4>() = A + B - C;\n\n                                // remove merged component from global GMM\n                                gmm.erase(gmm.begin() + j);\n                        }\n                }\n\n        }\n\n        // prune the model to specified truncation level\n        gmm = pruneMixtureModel(gmm, truncLevel);\n\n        return gmm;\n}\n\n\nmerge::observationModel merge::getMixtureComponent(vector<merge::mixtureComponents> gmm, Eigen::VectorXd observation)\n{\n\n        int idx = 0;\n        double minProb = 0, modelProb;\n        Eigen::RowVectorXd mean;\n        Eigen::RowVectorXd obs = observation.transpose();\n        Eigen::MatrixXd cov;\n        double doublePi = M_PI * 2.0;\n\n        for (int i=0; i<gmm.size(); i++)\n        {\n\n                mean = gmm[i].get<3>();\n                cov = gmm[i].get<4>();\n                double err = (obs-mean)*cov.inverse()*(observation-mean.transpose());\n                modelProb = -1 * log(err);\n\n                if (modelProb < minProb)\n                {\n                        minProb = modelProb;\n                        idx = i;\n                }\n        }\n\n        merge::mixtureComponents gmmComp = gmm[idx];\n        merge::observationModel obsModel = boost::make_tuple(gmmComp, minProb);\n\n        return obsModel;\n}\n", "meta": {"hexsha": "b14633406c592f950c0c175e7af61759f0665e9a", "size": 16961, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/LibCluster/src/merge.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/merge.cpp", "max_issues_repo_name": "mfkiwl/ICE", "max_issues_repo_head_hexsha": "e660d031bb1bcea664db1de4946fd8781be5b627", "max_issues_repo_licenses": ["MIT"], "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/merge.cpp", "max_forks_repo_name": "mfkiwl/ICE", "max_forks_repo_head_hexsha": "e660d031bb1bcea664db1de4946fd8781be5b627", "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": 35.9343220339, "max_line_length": 264, "alphanum_fraction": 0.4836389364, "num_tokens": 3982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5345318094783255}}
{"text": "//==============================================================================\n//         Copyright 2015 J.T.Lapreste\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/euler/include/functions/betaln.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n\n#include <nt2/include/functions/splat.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/inf.hpp>\n\nNT2_TEST_CASE_TPL ( betaln_real,  NT2_SIMD_REAL_TYPES)\n{\n  using nt2::betaln;\n  using nt2::tag::betaln_;\n  using boost::simd::native;\n  using nt2::splat;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n  typedef typename nt2::meta::call<betaln_(vT,vT)>::type r_t;\n  typedef vT wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_ULP_EQUAL(betaln(nt2::Nan<vT>(), nt2::Nan<vT>()), nt2::Nan<r_t>(), 0);\n  NT2_TEST_ULP_EQUAL(betaln(nt2::Inf<vT>(), nt2::Inf<vT>()), nt2::Nan<r_t>(), 0);\n#endif\n  T r[5] = {T(-1.609437912434100),  T(-2.995732273553991),  T(-3.401197381662155),  T(-2.995732273553991),  T(  -1.609437912434100)};\n\n  for(int i = 1; i <= 5 ; i+= 1)\n  {\n    vT v1 =  splat<vT>(i);\n    vT v2 =  splat<vT>(6-i);\n    NT2_TEST_ULP_EQUAL(betaln(v1, v2), splat<vT>(r[i-1]), 0.5);\n  }\n\n}\n", "meta": {"hexsha": "a2d7e2bba231dd3b8ec181dba1b4d9f33506696f", "size": 1829, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/euler/unit/simd/betaln.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/euler/unit/simd/betaln.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/euler/unit/simd/betaln.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 34.5094339623, "max_line_length": 133, "alphanum_fraction": 0.612356479, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489892, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5344466453885227}}
{"text": "\ufeff/*! \\file hydrogen_fem.cpp\n    \\brief FEM\u3067\u6c34\u7d20\u539f\u5b50\u306b\u5bfe\u3059\u308bSchr\u00f6dinger\u65b9\u7a0b\u5f0f\u3092\u89e3\u304f\u30af\u30e9\u30b9\u306e\u5b9f\u88c5\n\n    Copyright \u00a9 2019 @dc1394 All Rights Reserved.\n    (but this is originally adapted by sunsetyuhi for fem1d_poisson.py from https://github.com/sunsetyuhi/fem_py/blob/master/fem1d_poisson )\n    This software is released under the BSD 2-Clause License.\n*/\n\n#include \"hydrogen_fem.h\"\n#include <cmath>                // for std::exp\n#include <cstdio>               // for FILE, std::fclose, std::fopen, std::fprintf \n#include <memory>               // for std::unique_ptr\n#include <boost/assert.hpp>     // for BOOST_ASSERT\n#include <Eigen/Eigenvalues>    // for Eigen::GeneralizedSelfAdjointEigenSolver\n\nnamespace hydrogen_fem {\n    // #region \u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\n\n    Hydrogen_FEM::Hydrogen_FEM()\n        :   hg_(Eigen::MatrixXd::Zero(NODE_TOTAL, NODE_TOTAL)),\n            length_(ELE_TOTAL),\n            mat_A_ele_(boost::extents[ELE_TOTAL][2][2]),\n            mat_B_ele_(boost::extents[ELE_TOTAL][2][2]),\n            node_num_seg_(boost::extents[ELE_TOTAL][2]),\n            node_r_ele_(boost::extents[ELE_TOTAL][2]),\n            node_r_glo_(NODE_TOTAL),\n            ug_(Eigen::MatrixXd::Zero(NODE_TOTAL, NODE_TOTAL))\n    {\n    }\n\n    // #endregion \u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\n\n    // #region public\u30e1\u30f3\u30d0\u95a2\u6570 \n\n    double Hydrogen_FEM::do_run()\n    {\n        // \u5404\u7a2e\u30c7\u30fc\u30bf\u306e\u751f\u6210\n        make_data();\n\n        // \u8981\u7d20\u884c\u5217\u306e\u751f\u6210\n        make_element_matrix();\n\n        // \u5168\u4f53\u884c\u5217\u3092\u751f\u6210\n        make_global_matrix();\n        \n        // \u5883\u754c\u6761\u4ef6\u51e6\u7406\u3092\u884c\u3046\n        boundary_conditions();\n\n        // \u4e00\u822c\u5316\u56fa\u6709\u5024\u554f\u984c\u3092\u89e3\u304f\n        Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> es(hg_, ug_);\n\n        // \u30a8\u30cd\u30eb\u30ae\u30fc\u56fa\u6709\u5024\u3092\u53d6\u5f97\n        eigenval_ = es.eigenvalues();\n\n        // \u57fa\u5e95\u72b6\u614b\u306e\u56fa\u6709\u95a2\u6570\uff08\u6ce2\u52d5\u95a2\u6570\uff09\uff08\u6ce2\u52d5\u95a2\u6570\uff09\u3092\u53d6\u5f97\n        phi_ = es.eigenvectors().col(0);\n\n        // \u56fa\u6709\u30d9\u30af\u30c8\u30eb\uff08\u6ce2\u52d5\u95a2\u6570\uff09\u306eN\u8981\u7d20\u76ee\u3092\u8ffd\u52a0\n        phi_.resize(NODE_TOTAL);\n\n        // \u56fa\u6709\u30d9\u30af\u30c8\u30eb\uff08\u6ce2\u52d5\u95a2\u6570\uff09\u3092\u898f\u683c\u5316\n        normalize();\n\n        return eigenval_[0];\n    }\n\n    void Hydrogen_FEM::save_result() const\n    {\n        std::unique_ptr<FILE, decltype(&std::fclose)> fp_eigenfunc(std::fopen(Hydrogen_FEM::EIGENFUNC_FILENAME, \"w\"), std::fclose);\n        \n        for (auto i = 0; i < NODE_TOTAL; i++) {\n            auto const r = node_r_glo_[i];\n            // \u53b3\u5bc6\u306a\u7d50\u679c\u3068\u6bd4\u8f03\n            std::fprintf(fp_eigenfunc.get(), \"%.14f, %.14f, %.14f\\n\", r, phi_[i], 2.0 * std::exp(-r));\n        }\n\n        std::unique_ptr<FILE, decltype(&std::fclose)> fp_eigenval(std::fopen(Hydrogen_FEM::EIGENVAL_FILENAME, \"w\"), std::fclose);\n        \n        for (auto i = 0; i < NODE_TOTAL - 1; i++) {\n            // \u53b3\u5bc6\u306a\u7d50\u679c\u3068\u6bd4\u8f03\n            std::fprintf(fp_eigenval.get(), \"%d, %.14f, %.14f\\n\", i + 1, eigenval_[i], - 0.5 / static_cast<double>((i + 1) * (i + 1)));\n        }\n\n    }\n        \n    // #endregion public\u30e1\u30f3\u30d0\u95a2\u6570\n\n    // #region private\u30e1\u30f3\u30d0\u95a2\u6570\n\n    void Hydrogen_FEM::boundary_conditions()\n    {\n        // \u5de6\u8fba\u306e\u5168\u4f53\u884c\u5217\u306eN + 1\u884c\u3068N + 1\u5217\u3092\u524a\u308b\n        hg_.conservativeResize(hg_.rows() - 1, hg_.cols() - 1);\n\n        // \u53f3\u8fba\u306e\u5168\u4f53\u884c\u5217\u306eN + 1\u884c\u3068N + 1\u5217\u3092\u524a\u308b\n        ug_.conservativeResize(ug_.rows() - 1, ug_.cols() - 1);\n    }\n\n    double Hydrogen_FEM::get_A_matrix_element(std::int32_t e, double le, std::int32_t p, std::int32_t q) const\n    {\n        auto const ed = static_cast<double>(e);\n        switch (p) {\n        case 0:\n            switch (q) {\n            case 0:\n                return 0.5 * le * (ed * ed + ed + 1.0 / 3.0) - le * le * (ed / 3.0 + 1.0 / 12.0);\n\n            case 1:\n                return -0.5 * le * (ed * ed + ed + 1.0 / 3.0) - le * le * (ed / 6.0 + 1.0 / 12.0);\n\n            default:\n                BOOST_ASSERT(!\"he\u306e\u6dfb\u5b57\u304c2\u4ee5\u4e0a\uff01\");\n                return 0.0;\n            }\n\n        case 1:\n            switch (q) {\n            case 0:\n                return -0.5 * le * (ed * ed + ed + 1.0 / 3.0) - le * le * (ed / 6.0 + 1.0 / 12.0);\n\n            case 1:\n                return 0.5 * le * (ed * ed + ed + 1.0 / 3.0) - le * le * (ed / 3.0 + 0.25);\n\n            default:\n                BOOST_ASSERT(!\"he\u306e\u6dfb\u5b57\u304c2\u4ee5\u4e0a\uff01\");\n                return 0.0;\n            }\n\n        default:\n            BOOST_ASSERT(!\"he\u306e\u6dfb\u5b57\u304c2\u4ee5\u4e0a\uff01\");\n            return 0.0;\n        }\n    }\n    \n    double Hydrogen_FEM::get_B_matrix_element(std::int32_t e, double le, std::int32_t p, std::int32_t q) const\n    {\n        auto const ed = static_cast<double>(e);\n        switch (p) {\n        case 0:\n            switch (q) {\n            case 0:\n                return le * le * le * (ed * ed / 3.0 + ed / 6.0 + 1.0 / 30.0);\n\n            case 1:\n                return le * le * le * (ed * ed / 6.0 + ed / 6.0 + 0.05);\n\n            default:\n                BOOST_ASSERT(!\"ue\u306e\u6dfb\u5b57\u304c2\u4ee5\u4e0a\uff01\");\n                return 0.0;\n            }\n\n        case 1:\n            switch (q) {\n            case 0:\n                return le * le * le * (ed * ed / 6.0 + ed / 6.0 + 0.05);\n\n            case 1:\n                return le * le * le * (ed * ed / 3.0 + ed / 2.0 + 0.2);\n\n            default:\n                BOOST_ASSERT(!\"ue\u306e\u6dfb\u5b57\u304c2\u4ee5\u4e0a\uff01\");\n                return 0.0;\n            }\n\n        default:\n            BOOST_ASSERT(!\"ue\u306e\u6dfb\u5b57\u304c2\u4ee5\u4e0a\uff01\");\n            return 0.0;\n        }\n    }\n\n    void Hydrogen_FEM::make_element_matrix()\n    {\n        // \u5404\u7dda\u5206\u8981\u7d20\u306e\u9577\u3055\u3092\u8a08\u7b97\n        for (auto e = 0; e < ELE_TOTAL; e++) {\n            length_[e] = std::fabs(node_r_ele_[e][1] - node_r_ele_[e][0]);\n        }\n\n        // \u8981\u7d20\u884c\u5217\u306e\u5404\u6210\u5206\u3092\u8a08\u7b97\n        for (auto e = 0; e < ELE_TOTAL; e++) {\n            auto const le = length_[e];\n            for (auto i = 0; i < 2; i++) {\n                for (auto j = 0; j < 2; j++) {\n                    mat_A_ele_[e][i][j] = get_A_matrix_element(e, le, i, j);\n                    mat_B_ele_[e][i][j] = get_B_matrix_element(e, le, i, j);\n                }\n            }\n        }\n    }\n\n    void Hydrogen_FEM::make_data()\n    {\n        // Global\u7bc0\u70b9\u306ex\u5ea7\u6a19\u3092\u5b9a\u7fa9(R_MIN\uff5eR_MAX\uff09\n        auto const dr = (R_MAX - R_MIN) / static_cast<double>(ELE_TOTAL);\n        for (auto i = 0; i <= ELE_TOTAL; i++) {\n            // \u8a08\u7b97\u9818\u57df\u3092\u7b49\u5206\u5272\n            node_r_glo_[i] = R_MIN + static_cast<double>(i) * dr;\n        }\n\n        for (auto e = 0; e < ELE_TOTAL; e++) {\n            node_num_seg_[e][0] = e;\n            node_num_seg_[e][1] = e + 1;\n        }\n        \n        for (auto e = 0; e < ELE_TOTAL; e++) {\n            for (auto i = 0; i < 2; i++) {\n                node_r_ele_[e][i] = node_r_glo_[node_num_seg_[e][i]];\n            }\n        }\n    }\n    \n    void Hydrogen_FEM::make_global_matrix()\n    {\n        for (auto e = 0; e < ELE_TOTAL; e++) {\n            for (auto i = 0; i < 2; i++) {\n                for (auto j = 0; j < 2; j++) {\n                    hg_(node_num_seg_[e][i], node_num_seg_[e][j]) += mat_A_ele_[e][i][j];\n                    ug_(node_num_seg_[e][i], node_num_seg_[e][j]) += mat_B_ele_[e][i][j];\n                }\n            }\n        }\n    }\n\n    void Hydrogen_FEM::normalize()\n    {\n        auto sum = 0.0;\n        auto const size = phi_.size();\n        auto const max = size - 2;\n\n        // Simpson\u306e\u516c\u5f0f\u306b\u3088\u3063\u3066\u6570\u5024\u7a4d\u5206\u3059\u308b\n        for (auto i = 0; i < max; i += 2) {\n            auto const f0 = phi_[i] * phi_[i] * node_r_glo_[i] * node_r_glo_[i];\n            auto const f1 = phi_[i + 1] * phi_[i + 1] * node_r_glo_[i + 1] * node_r_glo_[i + 1];\n            auto const f2 = phi_[i + 2] * phi_[i + 2] * node_r_glo_[i + 2] * node_r_glo_[i + 2];\n            sum += (f0 + 4.0 * f1 + f2);\n        }\n        \n        auto const a_1 = 1.0 / std::sqrt(sum * length_[0] / 3.0);\n\n        for (auto i = 0; i < size; i++) {\n            phi_[i] *= -a_1;\n        }\n    }\n\n    // #endregion private\u30e1\u30f3\u30d0\u95a2\u6570\n}\n", "meta": {"hexsha": "78a6926df9d11f48822c94d9ce6337fdd8a0d01b", "size": 7442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hydrogen_fem/hydrogen_fem.cpp", "max_stars_repo_name": "dc1394/hydrogen_fem", "max_stars_repo_head_hexsha": "d50d5bb3614ba2b462e214ba7ec7fce355083ef5", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T09:22:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-19T01:43:01.000Z", "max_issues_repo_path": "src/hydrogen_fem/hydrogen_fem.cpp", "max_issues_repo_name": "dc1394/hydrogen_fem", "max_issues_repo_head_hexsha": "d50d5bb3614ba2b462e214ba7ec7fce355083ef5", "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/hydrogen_fem/hydrogen_fem.cpp", "max_forks_repo_name": "dc1394/hydrogen_fem", "max_forks_repo_head_hexsha": "d50d5bb3614ba2b462e214ba7ec7fce355083ef5", "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.2520325203, "max_line_length": 140, "alphanum_fraction": 0.4813222252, "num_tokens": 2573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.53444032993384}}
{"text": "/*\r\n\r\n// Struct_definition.h defines different types of sturctures being used in the implementation of MSCKF\r\n\r\n*/\r\n\r\n#ifndef STRUCT_DEF_H\r\n\r\n#define STRUCT_DEF_H\r\n\r\n\r\n\r\n#include <Eigen/Dense>\r\n\r\n\r\n#include <map>\r\n\r\n#include <set>\r\n\r\n#include \"Parameters.hpp\"\r\n\r\n#include <deque>\r\n\r\n\r\n#define PI 3.1415926535\r\n\r\n#define NaN -1\r\n\r\ntypedef Eigen::Matrix<double, 15, 15> Matrix15;\r\n\r\ntypedef Eigen::Matrix<double, 16, 16> Matrix16;\r\n\r\ntypedef Eigen::Matrix<double,4,1> quaternion;\r\n\r\n\r\n\r\nstruct Feature\r\n\r\n{\r\n\r\n\t/* ----- Structure to store Camera Feature Points ----- */\r\n\r\n\tdouble u;\r\n\r\n\tdouble v;\r\n\r\n};\r\n\r\n\r\n\r\nstruct IMURawData\r\n\r\n{\r\n\r\n\tEigen::Vector3d imuData;\r\n\r\n\tdouble timeStamp;\r\n\r\n};\r\n\r\n\r\n\r\nstruct IMUdata\r\n\r\n{\r\n\r\n\t/* --------- Structure to store Raw IMU Data ---------- */\r\n\r\n\tEigen::Vector3d a;\r\n\r\n\tEigen::Vector3d g;\r\n\r\n\r\n\r\n\t/* -------- Operator to copy structure members -------- */\r\n\r\n\tIMUdata& operator=(const IMUdata& old)\r\n\r\n\t{\r\n\r\n\t\ta = old.a;\r\n\r\n\t\tg = old.g;\r\n\r\n\r\n\r\n\t\treturn *this;\r\n\r\n\t}\r\n\r\n};\r\n\r\nstruct StampedIMUData\r\n\r\n{\r\n\r\n\tdouble timestamp;\r\n\r\n\tIMUdata imudata;\r\n\r\n\r\n\r\n};\r\n\r\n\r\n\r\nstruct StampedAccData{\r\n\r\n\tdouble timestamp;\r\n\r\n\tEigen::Vector3d accdata;\r\n\r\n\r\n\r\n\r\n\r\n};\r\n\r\n\r\n\r\nstruct StampedGyroData{\r\n\r\n\r\n\r\n\tdouble timestamp;\r\n\r\n\tEigen::Vector3d gyrodata;\r\n\r\n\r\n\r\n};\r\n\r\n\r\n\r\nstruct CalibrationParameter{\r\n\r\n\tfloat  Td;\r\n\r\n\tCalibrationParameter()\r\n\r\n\t{\r\n\r\n\t\t Td = 0;\r\n\r\n\t}\r\n\r\n};\r\n\r\n\r\n\r\nstruct IMUstate\r\n\r\n{\r\n\r\n\t/* ------ Structure of IMU Part of State Vector ------- */\r\n\r\n\tEigen::Vector3d p_b_G;\r\n\r\n\tEigen::Vector3d v_b_G;\r\n\r\n\tquaternion q_B_G;\r\n\r\n\tEigen::Vector3d ba;\r\n\r\n\tEigen::Vector3d bg;\r\n\r\n\tCalibrationParameter calibParam;\r\n\r\n\r\n\r\n\tEigen::Vector3d w_b;\r\n\r\n\t/* ------------------- Constructor -------------------- */\r\n\r\n\tIMUstate()\r\n\r\n\t{\r\n\r\n\t\tp_b_G.setZero();\r\n\r\n\t\tv_b_G.setZero();\r\n\r\n\t\tq_B_G.setIdentity();\r\n\r\n\t\tba.setZero();\r\n\r\n\t\tbg.setZero();\r\n\r\n\t\tcalibParam. Td = 0;\r\n\r\n\t\tw_b.setZero();\r\n\r\n\t}\r\n\r\n\r\n\r\n\t/* -------- Operator to copy structure members -------- */\r\n\r\n\tIMUstate& operator=(const IMUstate& old)\r\n\r\n\t{\r\n\r\n\t\tp_b_G = old.p_b_G;\r\n\r\n\t\tv_b_G = old.v_b_G;\r\n\r\n\t\tq_B_G = old.q_B_G;\r\n\r\n\t\tba = old.ba;\r\n\r\n\t\tbg = old.bg;\r\n\r\n\t\tw_b = old.w_b;\r\n\r\n\t\tcalibParam = old.calibParam;\r\n\r\n\r\n\r\n\t\treturn *this;\r\n\r\n\t}\r\n\r\n};\r\n\r\n\r\n\r\nstruct IMUGroundTruth\r\n\r\n{\r\n\r\n\t/* ------ Structure of IMU Part of State Vector ------- */\r\n\r\n\tdouble timeStamp;\r\n\r\n\tEigen::Vector3d p_b_G;\r\n\r\n\tEigen::Vector3d v_b_G;\r\n\r\n\tquaternion q_B_G;\r\n\r\n\tEigen::Vector3d bias_w;\r\n\r\n\tEigen::Vector3d bias_a;\r\n\r\n\t/* ------------------- Constructor -------------------- */\r\n\r\n\tIMUGroundTruth()\r\n\r\n\t{\r\n\r\n\t\ttimeStamp = 0.0;\r\n\r\n\t\tp_b_G.setZero();\r\n\r\n\t\tv_b_G.setZero();\r\n\r\n\t\tq_B_G.setIdentity();\r\n\r\n\t\tbias_a.setZero();\r\n\r\n\t\tbias_w.setZero();\r\n\r\n\t}\r\n\r\n\r\n\r\n\t/* -------- Operator to copy structure members -------- */\r\n\r\n\tIMUGroundTruth& operator=(const IMUGroundTruth& old)\r\n\r\n\t{\r\n\r\n\t\tp_b_G = old.p_b_G;\r\n\r\n\t\tv_b_G = old.v_b_G;\r\n\r\n\t\tq_B_G = old.q_B_G;\r\n\r\n\t\tbias_a = old.bias_a;\r\n\r\n\t\tbias_w = old.bias_w;\r\n\r\n\t\ttimeStamp = old.timeStamp;\r\n\r\n\t\treturn *this;\r\n\r\n\t}\r\n\r\n};\r\n\r\n\r\n\r\nstruct Bodystate\r\n\r\n{\r\n\r\n\t/* --- Structure of Camera/Body Part of State Vector -- */\r\n\r\n\tint state_k;\r\n\r\n\r\n\r\n\tEigen::Vector3d p_b_G;\r\n\r\n\tEigen::Vector3d v_b_G;\r\n\r\n\tquaternion q_B_G;\r\n\r\n\r\n\r\n\tEigen::Vector3d w_b;\r\n\r\n\tstd::set<int> trackedFeatureID;   // TODO:: need to be modified as a set\r\n\r\n\r\n\r\n\t/* -------- Operator to copy structure members -------- */\r\n\r\n\tBodystate& operator=(const Bodystate& old)\r\n\r\n\t{\r\n\r\n\t\tstate_k = old.state_k;\r\n\r\n\t\tp_b_G = old.p_b_G;\r\n\r\n\t\tv_b_G = old.v_b_G;\r\n\r\n\t\tq_B_G = old.q_B_G;\r\n\r\n\t\ttrackedFeatureID = old.trackedFeatureID;\r\n\r\n\r\n\r\n\t\treturn *this;\r\n\r\n\t}\r\n\r\n\r\n\r\n\tBodystate()\r\n\r\n\t{\r\n\r\n\t\tstate_k = 0;\r\n\r\n\t\tp_b_G.setZero();\r\n\r\n\t\tv_b_G.setZero();\r\n\r\n\t\tq_B_G.setIdentity();\r\n\r\n\t\ttrackedFeatureID.clear();\r\n\r\n\t}\r\n\r\n};\r\n\r\n\r\n\r\nstruct Camstate{\r\n\r\n\tEigen::Vector3d p_c_G;\r\n\r\n\tquaternion q_C_G;\r\n\r\n\tCamstate(){\r\n\r\n\t\tp_c_G.setZero();\r\n\r\n\t\tq_C_G.setIdentity();\r\n\r\n\t}\r\n\r\n};\r\n\r\nstruct FeatureTrack\r\n\r\n{\r\n\r\n\t/* - Structure of Features and corresponding Body States - */\r\n\r\n\tint featureID;\r\n\r\n\tstd::vector<Feature> observations;\r\n\r\n\tstd::map<int, std::vector<Feature>, std::less<int>, Eigen::aligned_allocator<std::pair<int, std::vector<Feature>>>> featureTracks;\r\n\r\n\tstd::vector<int> bodyStateID;\r\n\r\n\tstd::vector<Bodystate, Eigen::aligned_allocator<Bodystate>> bodyStateBuffer;\r\n\r\n\r\n\r\n\t/* -------- Operator to copy structure members -------- */\r\n\r\n\tFeatureTrack& operator=(const FeatureTrack& old)\r\n\r\n\t{\r\n\r\n\t\tfeatureID = old.featureID;\r\n\r\n\t\tobservations = old.observations;\r\n\r\n\t\tfeatureTracks = old.featureTracks;\r\n\r\n\t\tbodyStateID = old.bodyStateID;\r\n\r\n\t\tbodyStateBuffer = old.bodyStateBuffer;\r\n\r\n\r\n\r\n\t\treturn *this;\r\n\r\n\t}\r\n\r\n\tFeatureTrack(){\r\n\r\n\t\tfeatureID = 0;\r\n\r\n\t\tobservations.clear();\r\n\r\n\t\tfeatureTracks.clear();\r\n\r\n\t\tbodyStateID.clear();\r\n\r\n\t\tbodyStateBuffer.clear();\r\n\r\n\t}\r\n\r\n};\r\n\r\n\r\n\r\nstruct StateVector\r\n\r\n{\r\n\t/* -------- Structure of Complete State Vector -------- */\r\n\r\n\tIMUstate imuState;\r\n\r\n\t\r\n\r\n\tEigen::Matrix<double, 16, 16> imuCovariance; // imu + calib\r\n\r\n\tEigen::MatrixXd bodyCovariance;\r\n\r\n\tEigen::MatrixXd imuBodyCovariance;\r\n\r\n\tstd::vector<Bodystate, Eigen::aligned_allocator<Bodystate>> bodyStateBuffer;\r\n\r\n\t//CalibrationParameter camCalibState;\r\n\r\n\t//Eigen::MatrixXd camCalibCovariance;\r\n\r\n\t/* -------- Operator to copy structure members -------- */\r\n\r\n\tStateVector& operator=(const StateVector& old)\r\n\r\n\t{\r\n\r\n\t\timuState = old.imuState;\r\n\r\n\t\timuCovariance = old.imuCovariance;\r\n\r\n\t\tbodyCovariance = old.bodyCovariance;\r\n\r\n\t\timuBodyCovariance = old.imuBodyCovariance;\r\n\r\n\t\tbodyStateBuffer = old.bodyStateBuffer;\r\n\r\n\t\t//camCalibState = old.camCalibState;\r\n\r\n\t\t//camCalibCovariance = old.camCalibCovariance;\r\n\r\n\t\treturn *this;\r\n\r\n\t}\r\n\r\n\r\n\r\n\tStateVector(){\r\n\r\n\t\timuCovariance.setZero();\r\n\r\n\t\tbodyCovariance.setZero();\r\n\r\n\t\timuBodyCovariance.setZero();\r\n\r\n\t\t//bodyStateBuffer.clear();\r\n\r\n\t\t//camCalibCovariance.setZero();\r\n\r\n\t}\r\n\r\n};\r\n\r\nstruct ImageNameStruct{\r\n\r\n\tstd::string imageName;\r\n\r\n\tdouble imageTimeStamp;\r\n\r\n};\r\ntypedef struct IMUMeanData_{\r\n\r\n\tdouble gx_mean;\r\n\tdouble gy_mean;\r\n\tdouble gz_mean;\r\n\r\n\tdouble ax_mean;\r\n\tdouble ay_mean;\r\n\tdouble az_mean;\r\n\r\n}IMUMeanData;\r\n\r\nvoid getParameter(std::string cameParam,std::string imuParam,cameraParameters & camParam,\tnoiseParameters & initNoiseParam);\r\n\r\nstd::vector<ImageNameStruct> getImageList( std::ifstream& imageListFile);\r\n\r\nstd::vector<StampedIMUData> getIMUReading(std::ifstream& IMURecordFile);\r\nstd::vector<StampedIMUData> getIMUReadingEuroc(std::ifstream& IMURecordFile);\r\n\r\nstd::vector<StampedIMUData> getIMUReadingDvt(std::ifstream& IMURecordFile);\r\n\r\nstd::vector<ImageNameStruct> getImageListDvt( std::ifstream& imageListFile);\r\n\r\nstd::vector<StampedAccData> getAccReading(std::ifstream & AccRecordFile);\r\n\r\nstd::vector<StampedGyroData> getGyroReading(std::ifstream & gyroRecordFile);\r\nstd::vector<IMUGroundTruth> getGroundTruthEuroc(std::ifstream & groundTruthFile);\r\n\r\n#endif", "meta": {"hexsha": "f7024e77f4add96b37b2fd38dc2c4f420c96b947", "size": 6920, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rovio/Struct_definition.hpp", "max_stars_repo_name": "YJCITA/rovio_noros", "max_stars_repo_head_hexsha": "89d80c5696afd0dff72650216fcb145d276abcd4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2017-04-26T02:54:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T19:12:52.000Z", "max_issues_repo_path": "include/rovio/Struct_definition.hpp", "max_issues_repo_name": "YJCITA/rovio_noros", "max_issues_repo_head_hexsha": "89d80c5696afd0dff72650216fcb145d276abcd4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-02-16T17:13:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-24T07:42:25.000Z", "max_forks_repo_path": "include/rovio/Struct_definition.hpp", "max_forks_repo_name": "YJCITA/rovio_noros", "max_forks_repo_head_hexsha": "89d80c5696afd0dff72650216fcb145d276abcd4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-05-17T13:47:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T06:09:20.000Z", "avg_line_length": 12.9831144465, "max_line_length": 132, "alphanum_fraction": 0.6150289017, "num_tokens": 1777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5344403299338399}}
{"text": "#include <map>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n\n#include \"DatasetAR.h\"\n#include \"GaussSeq.h\"\n#include \"ARSeq.h\"\n#include \"utils.h\"\n\nusing utils::my_float;\n\nint main() {\n    using boost::multiprecision::cpp_bin_float_50;\n    using boost::random::uniform_real_distribution;\n\n    boost::random::mt19937 gen {};\n    uniform_real_distribution<my_float> u (0, 4);\n\n    // prepare target\n    std::map<int, my_float> coeff {\n        {3, 0.2},\n        {20, 0.5},\n    };\n    std::vector<my_float> v;\n    for (auto i = 0; i < 20; i++) {\n        v.push_back(u(gen));\n    }\n\n    // AR process\n    ARSeq targ_seq(coeff, 0);\n    targ_seq.seed_prev_vals(v);\n\n    // Dataset write\n    DatasetAR dat_0(\"testing_zero_background\", targ_seq, 0);\n    DatasetAR dat_1(\"testing_one_background\", targ_seq, 1);\n    DatasetAR dat_2(\"testing_two_background\", targ_seq, 2);\n    DatasetAR dat_3(\"testing_three_background\", targ_seq, 3);\n    DatasetAR dat_4(\"testing_four_background\", targ_seq, 4);\n\n    dat_0.write_csv();\n    dat_1.write_csv();\n    dat_2.write_csv();\n    dat_3.write_csv();\n    dat_4.write_csv();\n    \n    return 0;\n}\n", "meta": {"hexsha": "170cc59b7390b6ce310401a8202c32d133ab2082", "size": 1333, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gen-data/test/csv-write-AR.cpp", "max_stars_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_stars_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gen-data/test/csv-write-AR.cpp", "max_issues_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_issues_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gen-data/test/csv-write-AR.cpp", "max_forks_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_forks_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_forks_repo_licenses": ["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.1509433962, "max_line_length": 61, "alphanum_fraction": 0.6759189797, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5344403299338399}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/svd.hpp\n *\n * \\brief Singular Value Decomposition problem.\n *\n * The <em>singular value decomposition</em> (SVD) of a m-by-n real/complex\n * matrix \\f$A\\f$ is:\n * \\f[\n *   A = U \\Sigma V^{H}\n * \\f]\n * where \\f$\\Sigma\\f$ is an m-by-n matrix which is zero except for its\n * \\f$\\min(m,n)\\f$ diagonal elements, \\f$U\\f$ is an m-by-m unitary matrix, and\n * \\f$V\\f$ is an n-by-n unitary matrix.\n * The diagonal elements of \\f$\\Sigma\\f$ are the <em>singular values</em> of\n * \\f$A\\f$; they are real and non-negative, and are returned in descending order.\n * The first \\f$\\min(m,n)\\f$ columns of \\f$U\\f$ and \\f$V\\f$ are the left and\n * right singular vectors of \\f$A\\f$.\n *\n * When an economy-size SVD is requested, if \\f$k=\\min(m.n)\\f$, it results that\n * \\f$\\Sigma\\f$ is a k-by-k diagonal matrix, \\f$U\\f$ is an m-by-k unitary matrix\n * and \\f$V\\f$ is an n-by-k unitary matrix.\n * In this case the original matrix \\f$A\\f$ cannot be reconstructed.\n *\n * \\note\n *  For real m-by-n matrix \\f$A\\f$ the associated SVD is:\n * \\f[\n *   A = U \\Sigma V^{T}\n * \\f]\n *\n * <hr/>\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_SVD_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_SVD_HPP\n\n\n#include <algorithm>\n#include <boost/numeric/bindings/lapack/driver/gesvd.hpp>\n#include <boost/numeric/bindings/ublas.hpp>\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/detail/lapack.hpp>\n#include <boost/numeric/ublasx/operation/diag.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/utility/enable_if.hpp>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\nnamespace detail { namespace /*<unnamed>*/ {\n\ntemplate <\n\ttypename AMatrixT,\n\ttypename SVectorT,\n\ttypename UMatrixT,\n\ttypename VTMatrixT\n>\nvoid svd_impl(AMatrixT const& A, SVectorT& s, bool want_U, bool full_U, UMatrixT& U, bool want_VT, bool full_VT, VTMatrixT& VT, column_major_tag)\n{\n\ttypedef typename matrix_traits<AMatrixT>::value_type value_type;\n\ttypedef typename matrix_traits<AMatrixT>::size_type size_type;\n\ttypedef matrix<value_type, column_major> work_matrix_type;\n\n\tchar jobu = 'N';\n\tchar jobvt = 'N';\n\tsize_type m = num_rows(A);\n\tsize_type n = num_columns(A);\n\tsize_type k = ::std::min(m, n);\n\tsize_type U_nr = detail::lapack::min_array_size;\n\tsize_type U_nc = detail::lapack::min_array_size;\n\tsize_type VT_nr = detail::lapack::min_array_size;\n\tsize_type VT_nc = detail::lapack::min_array_size;\n\n\tif (want_U)\n\t{\n\t\tU_nr = m;\n\t\tif (full_U)\n\t\t{\n\t\t\tjobu = 'A';\n\t\t\tU_nc = m;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tjobu = 'S';\n\t\t\tU_nc = k;\n\t\t}\n\t}\n\tif (want_VT)\n\t{\n\t\tVT_nc = n;\n\t\tif (full_VT)\n\t\t{\n\t\t\tjobvt = 'A';\n\t\t\tVT_nr = n;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tjobvt = 'S';\n\t\t\tVT_nr = k;\n\t\t}\n\t}\n\n\tif (size(s) != k)\n\t{\n\t\ts.resize(k, false);\n\t}\n\tif (num_rows(U) != U_nr || num_columns(U) != U_nc)\n\t{\n\t\tU.resize(U_nr, U_nc, false);\n\t}\n\tif (num_rows(VT) != VT_nr || num_columns(VT) != VT_nc)\n\t{\n\t\tVT.resize(VT_nr, VT_nc, false);\n\t}\n\n\twork_matrix_type tmp_A(A);\n\n\t::boost::numeric::bindings::lapack::gesvd(\n\t\tjobu,\n\t\tjobvt,\n\t\ttmp_A,\n\t\ts,\n\t\tU,\n\t\tVT\n\t);\n}\n\n\ntemplate <\n\ttypename AMatrixT,\n\ttypename SVectorT,\n\ttypename UMatrixT,\n\ttypename VTMatrixT\n>\nvoid svd_impl(AMatrixT const& A, SVectorT& s, bool want_U, bool full_U, UMatrixT& U, bool want_VT, bool full_VT, VTMatrixT& VT, row_major_tag)\n{\n\ttypedef typename matrix_traits<AMatrixT>::value_type value_type;\n\ttypedef matrix<value_type, column_major> colmaj_matrix_type;\n\n\tcolmaj_matrix_type tmp_A(A);\n\tcolmaj_matrix_type tmp_U;\n\tcolmaj_matrix_type tmp_VT;\n\n\tsvd_impl(tmp_A, s, want_U, full_U, tmp_U, want_VT, full_VT, tmp_VT, column_major_tag());\n\n\tif (want_U)\n\t{\n\t\tU = tmp_U;\n\t}\n\tif (want_VT)\n\t{\n\t\tVT = tmp_VT;\n\t}\n}\n\n\ntemplate <typename MatrixT>\ntypename ::boost::enable_if<\n\t::boost::is_complex<typename matrix_traits<MatrixT>::value_type>,\n\tMatrixT\n>::type make_V(MatrixT const& VH)\n{\n\treturn herm(VH);\n}\n\n\ntemplate <typename MatrixT>\ntypename ::boost::disable_if<\n\t::boost::is_complex<typename matrix_traits<MatrixT>::value_type>,\n\tMatrixT\n>::type make_V(MatrixT const& VT)\n{\n\treturn trans(VT);\n}\n\n}} // Namespace detail::<unnamed>\n\n\n/**\n * \\brief Computes the singular value decomposition (SVD) of a matrix.\n *\n * Computes the <em>singular value decomposition</em> (SVD) of a m-by-n matrix,\n * optionally computing the left and/or right singular vectors.\n * The SVD is written as:\n * \\f[\n *   A = U \\Sigma V^{H}\n * \\f]\n * where \\f$\\Sigma\\f$ is an m-by-n matrix which is zero except for its\n * \\f$\\min(m,n)\\f$ diagonal elements, \\f$U\\f$ is an m-by-m unitary matrix, and\n * \\f$V\\f$ is an n-by-n unitary matrix.\n * The diagonal elements of \\f$\\Sigma\\f$ are the <em>singular values</em> of\n * \\f$A\\f$; they are real and non-negative, and are returned in descending order.\n * The first \\f$\\min(m,n)\\f$ columns of \\f$U\\f$ and \\f$V\\f$ are the left and\n * right singular vectors of \\f$A\\f$.\n *\n * When <em>full mode</em> is disabled, an economy-size SVD is computed, such\n * that, if \\f$k=\\min(m.n)\\f$, \\f$\\Sigma\\f$ is a k-by-k diagonal matrix,\n * \\f$U\\f$ is an m-by-k unitary matrix and \\f$V\\f$ is an n-by-k unitary matrix.\n *\n * \\author Marco Guazzone, marco.guazzoe@gmail.com\n */\ntemplate <typename ValueT>\nclass svd_decomposition\n{\n\tpublic: typedef ValueT value_type;\n\tpublic: typedef typename type_traits<value_type>::real_type real_type;\n\tpublic: typedef vector<real_type> vector_type;\n\tpublic: typedef matrix<value_type, column_major> matrix_type;\n\tpublic: typedef matrix<real_type, column_major> real_matrix_type;\n\tprivate: typedef typename matrix_traits<matrix_type>::size_type size_type;\n\n\n\t/// Default constructor\n\tpublic: svd_decomposition()\n\t\t: full_(false),\n\t\t  m_(0),\n\t\t  n_(0),\n\t\t  k_(0)\n\t{\n\t}\n\n\n\t/// A constructor.\n\tpublic: template <typename MatrixExprT>\n\t\tsvd_decomposition(matrix_expression<MatrixExprT> const& A, bool full = true)\n\t{\n\t\tdecompose(A, full);\n\t}\n\n\n\t/// Compute the SVD \\f$A=U \\Sigma V^H\\f$\n\tpublic: template <typename MatrixExprT>\n\t\tvoid decompose(matrix_expression<MatrixExprT> const& A, bool full = true)\n\t{\n\t\t// Cache some values (useful for later info retrieval)\n\t\tfull_ = full;\n\t\tm_ = num_rows(A);\n\t\tn_ = num_columns(A);\n\t\tk_ = ::std::min(m_, n_);\n\n\t\tdetail::svd_impl(A(), s_, true, full, U_, true, full, VH_, column_major_tag());\n\t}\n\n\n\t/// Return the U matrix of the SVD \\f$U \\Sigma V^H\\f$.\n\tpublic: matrix_type const& U() const\n\t{\n\t\treturn U_;\n\t}\n\n\n\t/// Return the \\f$\\operatorname{diag}(\\Sigma)\\f$ vector of the SVD \\f$U \\Sigma V^H\\f$.\n\tpublic: vector_type const& s() const\n\t{\n\t\treturn s_;\n\t}\n\n\n\t/// Return the \\f$\\Sigma\\f$ matrix of the SVD \\f$U \\Sigma V^H\\f$.\n\tpublic: real_matrix_type S() const\n\t{\n\t\tif (full_)\n\t\t{\n\t\t\t//return diag(s_, m_, n_);\n\t\t\treturn diag<vector_type,column_major>(s_, m_, n_);\n\t\t}\n\t\t//return diag(s_, k_, k_);\n\t\treturn diag<vector_type,column_major>(s_, k_, k_);\n\t}\n\n\n\t/// Return the \\f$V^H\\f$ matrix (\\f$V^T\\f$ for real types) of the SVD\n\t/// \\f$U \\Sigma V^H\\f$.\n\tpublic: matrix_type const& VH() const\n\t{\n\t\treturn VH_;\n\t}\n\n\n\t/// Return the \\f$V\\f$ matrix of the SVD \\f$U \\Sigma V^H\\f$.\n\tpublic: matrix_type V() const\n\t{\n\t\treturn detail::make_V(VH_);\n\t}\n\n\n//\tTODO: interesting but not urgent.\n//\t/**\n//\t * \\brief  Compute the approximate error bound for the computed singular\n//\t *  values.\n//\t * \\note\n//\t *  For the 2-norm, \\f$\\Sigma(1,1) = \\operatorname{norm}(A)\\f$.\n//\t */\n//\tpublic: real_type s_error() const\n//\t{\n//\t\treturn ::std::numeric_limits<real_type>::epsilon()*s_(0);\n//\t}\n\n\n//\tTODO: interesting but not urgent.\n//\t/**\n//\t * \\brief  Compute the approximate error bound for the computed singular\n//\t *  values.\n//\t * \\note\n//\t *  For the 2-norm, \\f$\\Sigma(1,1) = \\operatorname{norm}(A)\\f$.\n//\t */\n//\tpublic: vector_type U_error() const\n//\t{\n//\t\t// Estimate reciprocal condition numbers for the singular vectors\n//\t\tvector_type rcond(n);\n//\t\tDDISNA('Left',M,N,s_,rcond)\n//\t\t// Compute the error estimates for the singular vectors\n//\t\treal_type s_err = s_error();\n//\t\tvector_type err(n);\n//\t\tfor (size_type i = 0; i < n; ++i)\n//\t\t{\n//\t\t\terr(i) = s_err/rcond(i)\n//\t\t}\n//\n//\t\treturn err;\n//\t}\n\n\n//\tTODO: interesting but not urgent.\n//\t/**\n//\t * \\brief  Compute the approximate error bound for the computed singular\n//\t *  values.\n//\t * \\note\n//\t *  For the 2-norm, \\f$\\Sigma(1,1) = \\operatorname{norm}(A)\\f$.\n//\t */\n//\tpublic: vector_type VH_error() const\n//\t{\n//\t\t// Estimate reciprocal condition numbers for the singular vectors\n//\t\tvector_type rcond(n);\n//\t\tDDISNA('Right',M,N,s_,rcond)\n//\t\t// Compute the error estimates for the singular vectors\n//\t\treal_type s_err = s_error();\n//\t\tvector_type err(n);\n//\t\tfor (size_type i = 0; i < n; ++i)\n//\t\t{\n//\t\t\terr(i) = s_err/rcond(i)\n//\t\t}\n//\n//\t\treturn err;\n//\t}\n\n\n\t/// Tell if the current SVD is in full or economy mode.\n\tbool full_;\n\t/// The number of rows of the original decomposed matrix.\n\tsize_type m_;\n\t/// The number of columns of the original decomposed matrix.\n\tsize_type n_;\n\t/// The minimum between the number of rows and columns of the original\n\t/// decomposed matrix.\n\tsize_type k_;\n\t/// The vector of singular values.\n\tprivate: vector_type s_;\n\t/// The matrix containing the left singular vectors.\n\tprivate: matrix_type U_;\n\t/// The matrix containing the right singular vectors.\n\tprivate: matrix_type VH_;\n};\n\n\n/// Compute the singular values of matrix \\a A.\ntemplate <typename MatrixExprT>\nvector<\n\ttypename type_traits<\n\t\ttypename matrix_traits<MatrixExprT>::value_type\n\t>::real_type\n> svd_values(matrix_expression<MatrixExprT> const& A)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::orientation_category orientation_category;\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\ttypedef typename type_traits<value_type>::real_type real_type;\n\ttypedef vector<real_type> vector_type;\n\ttypedef typename layout_type<MatrixExprT>::type layout_type;\n\ttypedef matrix<value_type, layout_type> work_matrix_type;\n\n\tvector_type s;\n\twork_matrix_type dummy_U;\n\twork_matrix_type dummy_VT;\n\n\tdetail::svd_impl(A(), s, false, false, dummy_U, false, false, dummy_VT, orientation_category());\n\n\treturn s;\n}\n\n\n/// Compute the singular value decomposition of matrix \\a A.\ntemplate <typename MatrixExprT>\nsvd_decomposition<typename matrix_traits<MatrixExprT>::value_type> svd_decompose(matrix_expression<MatrixExprT> const& A, bool full = true)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\n\treturn svd_decomposition<value_type>(A, full);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_SVD_HPP\n", "meta": {"hexsha": "a47dd409ced8ad8d8af7c629ad91638527c91466", "size": 11034, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/svd.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/svd.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/svd.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": 26.2714285714, "max_line_length": 145, "alphanum_fraction": 0.6899583107, "num_tokens": 3344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5344403246046456}}
{"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/optimization/optimization_projected_gauss_seidel.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\ntemplate <typename vector_type>\nclass BoundFunction\n{\npublic:\n\n  typedef typename vector_type::size_type          size_type;\n  typedef typename vector_type::value_type         real_type;\n  typedef OpenTissue::math::ValueTraits<real_type> value_traits;\n\n\n  bool m_is_lower;\n\npublic:\n\n  BoundFunction(bool const & is_lower)\n    : m_is_lower(is_lower)\n  {}\n\n  real_type operator()(vector_type const & x, size_type const & i) const\n  {\n    size_type r = (i%3);\n\n    if(r==0)\n      return m_is_lower ? value_traits::zero() : value_traits::infinity();\n\n    real_type mu_i = value_traits::one();\n    size_type j = i - r;\n    return m_is_lower ?  -mu_i*x(j) : mu_i*x(j);\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  typedef typename matrix_type::value_type real_type;\n  typedef typename matrix_type::size_type  size_type;\n\n  BoundFunction<vector_type> l(true);\n  BoundFunction<vector_type> u(false);\n\n  size_type max_iterations       = 1000;\n  real_type absolute_tolerance   = boost::numeric_cast<real_type>(0.025);\n  real_type relative_tolerance   = boost::numeric_cast<real_type>(0.00001);\n  real_type stagnation_tolerance = boost::numeric_cast<real_type>(0.00001);\n  size_t status = 0;\n  size_type iteration = 0;\n  real_type accuracy = boost::numeric_cast<real_type>(0.0);\n  real_type relative_accuracy = boost::numeric_cast<real_type>(0.0);\n\n  OpenTissue::math::optimization::projected_gauss_seidel( \n    A, b, l , u, x \n    ,  max_iterations\n    ,  absolute_tolerance\n    ,  relative_tolerance\n    ,  stagnation_tolerance\n    ,  status\n    ,  iteration\n    ,  accuracy\n    ,  relative_accuracy\n    );\n\n  if(status==OpenTissue::math::optimization::ABSOLUTE_CONVERGENCE)\n  {\n    BOOST_CHECK( accuracy < absolute_tolerance );\n    BOOST_CHECK( iteration <= max_iterations );\n  }\n  else\n  {\n    std::cout << std::endl;\n    std::cout << \"absolute \" << accuracy << \" iter \" << iteration << \" status \" << status << \" relative \" << relative_accuracy << std::endl;\n    std::cout << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_projected_gauss_seidel);\n\nBOOST_AUTO_TEST_CASE(random_test_case)\n{\n\n  typedef ublas::compressed_matrix<double> matrix_type;\n  typedef ublas::vector<double>            vector_type;\n  typedef vector_type::size_type           size_type;\n\n  for(size_type tst=0;tst<1000;++tst)\n  {\n    size_type N = 20;\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\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    x.clear();\n    test(A,x,b,y);\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "a2540dd00a3fdf2b4ee22efc262f36a85c6548aa", "size": 3827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/projected_gauss_seidel/src/unit_projected_gauss_seidel.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/projected_gauss_seidel/src/unit_projected_gauss_seidel.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/projected_gauss_seidel/src/unit_projected_gauss_seidel.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.5763888889, "max_line_length": 140, "alphanum_fraction": 0.6869610661, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.53444032021618}}
{"text": "#include \"Vector3d.hpp\"\n#include \"utils.hpp\"\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n\nnamespace fragdock {\n  void getNormalizeRot(const Vector3d& v1, const Vector3d& _v2, fltype& theta, fltype& phi, fltype& psi) {\n    theta = 0;\n    phi = 0;\n    psi = 0;\n    Vector3d vec1 = v1;\n    Vector3d vec2 = v1.cross(_v2);\n    psi = Vector3d(0, 1, 0).getAngle(Vector3d(vec2.x, vec2.y, 0));\n    phi = Vector3d(0, 0, 1).getAngle(Vector3d(0, sqrt(vec2.x * vec2.x + vec2.y * vec2.y), vec2.z));\n    if (vec2.x < 0) psi = -psi;\n    vec1.rotate(0, phi, psi);\n    theta = -Vector3d(1, 0, 0).getAngle(vec1);\n    if (vec1.y < 0) theta = -theta;\n    // rotate(theta, phi, psi);\n  }\n\n  Vector3d getRot(const Vector3d& v1, const Vector3d& _v2) {\n    fltype theta, phi, psi;\n    getNormalizeRot(v1, _v2, theta, phi, psi);\n    return Vector3d(-psi, -phi, -theta);\n  }\n\n  void Vector3d::axisRotate(const Vector3d &axis, double th) {\n    Vector3d n = axis/axis.abs();\n    fltype B = cos(th), C = sin(th);\n    fltype A = 1-B;\n    fltype ox = x, oy = y, oz = z;\n    x = (n.x*n.x*A +     B)*ox + (n.x*n.y*A - n.z*C)*oy + (n.z*n.x*A + n.y*C)*oz;\n    y = (n.x*n.y*A + n.z*C)*ox + (n.y*n.y*A +     B)*oy + (n.y*n.z*A - n.x*C)*oz;\n    z = (n.z*n.x*A - n.y*C)*ox + (n.y*n.z*A + n.x*C)*oy + (n.z*n.z*A +     B)*oz;\n  }\n\n  // zxz rotation\n  void Vector3d::rotate(fltype theta, fltype phi, fltype psi) {\n    const fltype cosT = cos(theta), sinT = sin(theta), cosH = cos(phi), sinH = sin(phi), cosS = cos(psi), sinS = sin(psi);\n    fltype ox = x, oy = y, oz = z;\n\n    x = (cosT*cosS  - sinT*cosH*sinS) * ox + (-cosT*sinS - sinT*cosH*cosS) * oy + (sinT*sinH ) * oz;\n    y = (sinT*cosS  + cosT*cosH*sinS) * ox + (-sinT*sinS + cosT*cosH*cosS) * oy + (-cosT*sinH) * oz;\n    z = (sinH*sinS                  ) * ox + (sinH*cosS                  ) * oy + (cosH      ) * oz;\n  }\n  void Vector3d::rotate(const Vector3d& v) {\n    rotate(v.x, v.y, v.z);\n  }\n\n  const std::vector<Vector3d> makeRotations60() {\n    const fltype phi = (1.0 + sqrt(5.0)) / 2.0;\n    const fltype pi = acos(-1.0);\n\n    fragdock::Vector3d poleA(0, phi*phi*phi, phi*phi);\n    fragdock::Vector3d poleB(0, 1.0, phi*phi);\n    poleA = poleA.unit();\n    poleB = poleB.unit();\n    fltype p = poleA.getAngle(poleB);\n    poleA = Vector3d(1, 0, 0);\n    poleB = Vector3d(cos(p), sin(p), 0);\n\n    const int ORDER_NUM = 12;\n    const int order[ORDER_NUM] = {0, 0, 1, 1, 1, 2, 1, 2, 2, 2, 3, -1};\n\n    std::vector<Vector3d> rots;\n    for(int ord_id = 0; ord_id < ORDER_NUM; ord_id++) {\n      int o = order[ord_id];\n      for(int i = 0; i < 5; i++) {\n        // fltype theta = getAxisAngle(poleA, poleB);\n        rots.push_back(getRot(poleA, poleB));\n        poleB.axisRotate(poleA, 2.0*pi/5.0);\n      }\n      poleB.axisRotate(poleA, 2.0*o*pi/5.0);\n      poleA.axisRotate(poleB, 4.0*pi/3.0);\n    }\n    return rots;\n  }\n\n  const std::vector<Vector3d> readRotations(const std::string& filename) {\n    std::ifstream ifs(filename);\n    if (ifs.fail()){\n      std::cerr << \"opening grid file failed:\" << filename << std::endl;\n      abort();\n    }\n    std::vector<Vector3d> rots;\n    while (!ifs.eof()) {\n      std::string str;\n      std::getline(ifs, str);\n      std::vector<std::string> vals;\n      boost::algorithm::split(vals, str, boost::algorithm::is_any_of(\",\"));\n      if ((int)vals.size() < 3) continue;\n      boost::algorithm::trim(vals[0]);\n      boost::algorithm::trim(vals[1]);\n      boost::algorithm::trim(vals[2]);\n      rots.push_back(Vector3d(boost::lexical_cast<fltype>(vals[0]),\n                              boost::lexical_cast<fltype>(vals[1]),\n                              boost::lexical_cast<fltype>(vals[2])));\n    }\n    return rots;\n  }\n}\n", "meta": {"hexsha": "f4174cd68586c624bad6b08ac5699a68b3c6d079", "size": 3704, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Vector3d.cc", "max_stars_repo_name": "akiyamalab/restretto", "max_stars_repo_head_hexsha": "bc683bbb06fc5c1e4eb9f8c8d32ddddaac8f6c5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Vector3d.cc", "max_issues_repo_name": "akiyamalab/restretto", "max_issues_repo_head_hexsha": "bc683bbb06fc5c1e4eb9f8c8d32ddddaac8f6c5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-11T21:48:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-11T22:02:04.000Z", "max_forks_repo_path": "src/Vector3d.cc", "max_forks_repo_name": "akiyamalab/restretto", "max_forks_repo_head_hexsha": "bc683bbb06fc5c1e4eb9f8c8d32ddddaac8f6c5b", "max_forks_repo_licenses": ["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.9611650485, "max_line_length": 122, "alphanum_fraction": 0.5588552916, "num_tokens": 1333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5344403192754512}}
{"text": "\n#pragma once\n\n/// @file\n\n#define EIGEN_SPARSEMATRIX_PLUGIN \"numeric/thread_safe_plugin.hpp\"\n\n#include <Eigen/Sparse>\n\n#include <complex>\n\nnamespace neon\n{\n/// Type alias for row major real-valued sparse matrix\nusing sparse_matrix = Eigen::SparseMatrix<double, Eigen::RowMajor>;\n/// Type alias for row major complex-valued sparse matrix\nusing complex_sparse_matrix = Eigen::SparseMatrix<std::complex<double>, Eigen::RowMajor>;\n/// Type alias for the permutation matrix\nusing permutation_matrix = Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic, sparse_matrix::StorageIndex>;\n}\n", "meta": {"hexsha": "e7fa44a89d329a3d68d96153dcc1c4ae64ee1e0d", "size": 585, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/numeric/sparse_matrix.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/sparse_matrix.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/sparse_matrix.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.8571428571, "max_line_length": 113, "alphanum_fraction": 0.7811965812, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5344403139462568}}
{"text": "#include \"test_ntl.hpp\"\n#include <NTL/GF2X.h>\n#define LINEARITY_CHECK\n#include \"tinymt32.h\"\n#include <string>\n#include <stdio.h>\n#include <inttypes.h>\n#include <ctype.h>\n\nusing namespace NTL;\nusing namespace std;\n\ntinymt32_t tiny32;\n\nunsigned int dummy()\n{\n    return tinymt32_generate_uint32(&tiny32);\n}\n\nvoid ntl_exeuclid2(GF2X& a, GF2X& c, GF2X& x, GF2X& y, long m)\n{\n    PUTS(\"f2p_exeuclid2 start\\n\");\n    assert(!IsZero(x));\n    assert(!IsZero(y));\n    GF2X q1;\n    GF2X r0(x);\n    GF2X r1(y);\n    GF2X r2;\n    GF2X a0;\n    GF2X a1;\n    GF2X a2;\n    GF2X tmp;\n    PRT(\"x= \", x);\n    PRT(\"y= \", y);\n    a0 = 1;\n    a1 = 0;\n    PRT(\"r0 = \", r0);\n    PRT(\"r1 = \", r1);\n    PRT(\"a0 = \", a0);\n    PRT(\"a1 = \", a1);\n    long dr = deg(r0);\n    while (dr >= m) {\n        DivRem(q1, r2, r0, r1);\n        tmp = q1 * a1;\n        a2 = a0 + tmp;\n        PRT(\"q1 = \", q1);\n        PRT(\"tmp = \", tmp);\n        PRT(\"r0 = \", r0);\n        PRT(\"r1 = \", r1);\n        PRT(\"r2 = \", r2);\n        PRT(\"a0 = \", a0);\n        PRT(\"a1 = \", a1);\n        PRT(\"a2 = \", a2);\n        r0 = r1;\n        r1 = r2;\n        a0 = a1;\n        a1 = a2;\n        dr = deg(r0);\n        PUTS(\"loop last\\n\");\n    }\n    PUTS(\"loop end\\n\");\n    PRT(\"a0 = \", a0);\n    a = a0;\n    PRT(\"r0 = \", r0);\n    c = r0;\n    PUTS(\"f2p_exeuclid2 end\\n\");\n}\n\n#if 0\nvoid ntl_minpoly(GF2X& poly, f2rng gen, int mexp)\n{\n    Vec<GF2> v;\n    v.SetLength(2 * mexp);\n    for (int i = 0; i < 2 * mexp; i++) {\n        v[i] = gen() & 1;\n    }\n    MinPolySeq(poly, v, mexp);\n}\n#endif\n\nvoid ntl_minpoly(GF2X& poly, tinymt32_t * tiny32, int mexp)\n{\n    GF2X v;\n    v.SetLength(2 * mexp);\n    //for (int i = 0; i < 2 * mexp; i++) {\n    for (int i = 2 * mexp - 1; i >= 0; i--) {\n        v[i] = tinymt32_generate_uint32(tiny32) & 1;\n    }\n    PRT(\"seq = \", v);\n    //MinPolySeq(poly, v, mexp);\n    GF2X x2m;\n    GF2X c;\n    SetCoeff(x2m, 2 * mexp, 1);\n    ntl_exeuclid2(poly, c, v, x2m, mexp);\n    printf(\"deg(c) = %ld\\n\", deg(c));\n}\n\nvoid ntl_minpoly(char * minpoly, tinymt32_t * tiny32, int mexp)\n{\n    GF2X poly;\n    ntl_minpoly(poly, tiny32, mexp);\n    string str;\n    to_hexstring(str, poly);\n    strcpy(minpoly, str.c_str());\n}\n\nint ntl_annihilate(const GF2X& poly, tinymt32_t * tiny32, int mexp)\n{\n    int bit = 0;\n    for (int i = 0; i <= mexp; i++) {\n        if (IsOne(poly[i])) {\n            bit ^= tinymt32_generate_uint32(tiny32) & 1;\n        }\n    }\n    if (bit == 0) {\n        return 1;\n    } else {\n        return 0;\n    }\n}\n\nint test_minpoly(tinymt32_t * tiny32)\n{\n    GF2X poly;\n    ntl_minpoly(poly, tiny32, 127);\n    int ok = 1;\n    for (int i = 0; i < 100; i++) {\n        int r = ntl_annihilate(poly, tiny32, 127);\n        ok &= r;\n        dummy();\n        if (r == 1) {\n            printf(\"o\");\n        } else {\n            printf(\"x\");\n        }\n    }\n    printf(\"\\n\");\n    if (ok) {\n        printf(\"annihilate OK\\n\");\n    } else {\n        printf(\"annihilate NG\\n\");\n    }\n    //char polystr[200];\n    string str;\n    to_hexstring(str, poly);\n    printf(\"poly = %ld,%s\\n\", deg(poly), str.c_str());\n    hexto_poly(poly, str);\n    to_hexstring(str, poly);\n    printf(\"poly = %s\\n\", str.c_str());\n    printf(\"minpoly end\\n\");\n    //int deg = f2p_degree(poly);\n    //printf(\"deg(poly) = %d\\n\", deg);\n    return 0;\n}\n\nint main(int argc, char * argv[])\n{\n    int verbose = 0;\n    int r = 0;\n    if (argc > 1 && argv[1][0] == 'v') {\n        verbose = 1;\n    }\n    tiny32.mat1 = 0x8f7011ee;\n    tiny32.mat2 = 0xfc78ff1f;\n    tiny32.tmat = 0x3793fdff;\n\n    tinymt32_init(&tiny32, 1);\n    r += test_minpoly(&tiny32);\n    if (r == 0) {\n        return 0;\n    } else {\n        return -1;\n    }\n}\n", "meta": {"hexsha": "0706006f09a3a2199a36eedd12fbf160a22c885f", "size": 3631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_minpoly_ntl.cpp", "max_stars_repo_name": "MSaito/f2p-gmp", "max_stars_repo_head_hexsha": "64d4d7d3d1f7b246b59fee519c69c9c2db8ccbad", "max_stars_repo_licenses": ["MIT"], "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_minpoly_ntl.cpp", "max_issues_repo_name": "MSaito/f2p-gmp", "max_issues_repo_head_hexsha": "64d4d7d3d1f7b246b59fee519c69c9c2db8ccbad", "max_issues_repo_licenses": ["MIT"], "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_minpoly_ntl.cpp", "max_forks_repo_name": "MSaito/f2p-gmp", "max_forks_repo_head_hexsha": "64d4d7d3d1f7b246b59fee519c69c9c2db8ccbad", "max_forks_repo_licenses": ["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.7485714286, "max_line_length": 67, "alphanum_fraction": 0.4913247039, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5344403120647983}}
{"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 * @brief wraps Rot3 class to python\n * @author Andrew Melim\n * @author Ellon Paiva Mendes (LAAS-CNRS)\n **/\n\n#include <boost/python.hpp>\n\n#define NO_IMPORT_ARRAY\n#include <numpy_eigen/NumpyEigenConverter.hpp>\n\n#include \"gtsam/geometry/Rot3.h\"\n\nusing namespace boost::python;\nusing namespace gtsam;\n\nstatic Rot3 Quaternion_0(const Vector4& q)\n{\n    return Rot3::Quaternion(q[0],q[1],q[2],q[3]);\n}\n\nstatic Rot3 Quaternion_1(double w, double x, double y, double z)\n{\n    return Rot3::Quaternion(w,x,y,z);\n}\n\n// Prototypes used to perform overloading\n// See: http://www.boost.org/doc/libs/1_59_0/libs/python/doc/tutorial/doc/html/python/functions.html\ngtsam::Rot3  (*AxisAngle_0)(const gtsam::Point3&, double) = &Rot3::AxisAngle;\ngtsam::Rot3  (*AxisAngle_1)(const gtsam::Unit3&, double) = &Rot3::AxisAngle;\ngtsam::Rot3  (*Rodrigues_0)(const Vector3&) = &Rot3::Rodrigues;\ngtsam::Rot3  (*Rodrigues_1)(double, double, double) = &Rot3::Rodrigues;\ngtsam::Rot3  (*RzRyRx_0)(double, double, double) = &Rot3::RzRyRx;\ngtsam::Rot3  (*RzRyRx_1)(const Vector&) = &Rot3::RzRyRx;\nVector (Rot3::*quaternion_0)() const = &Rot3::quaternion;\n\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(print_overloads, Rot3::print, 0, 1)\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(equals_overloads, Rot3::equals, 1, 2)\n\nvoid exportRot3(){\n\n  class_<Rot3>(\"Rot3\")\n    .def(init<Point3,Point3,Point3>())\n    .def(init<double,double,double,double,double,double,double,double,double>())\n    .def(init<double,double,double,double>())\n    .def(init<const Quaternion &>())\n    .def(init<const Matrix3 &>())\n    .def(init<const Matrix &>())\n    .def(\"Quaternion\", Quaternion_0, arg(\"q\"), \"Creates a Rot3 from an array [w,x,y,z] representing a quaternion\")\n    .def(\"Quaternion\", Quaternion_1, (arg(\"w\"),arg(\"x\"),arg(\"y\"),arg(\"z\")) )\n    .staticmethod(\"Quaternion\")\n    .def(\"Expmap\", &Rot3::Expmap)\n    .staticmethod(\"Expmap\")\n    .def(\"ExpmapDerivative\", &Rot3::ExpmapDerivative)\n    .staticmethod(\"ExpmapDerivative\")\n    .def(\"Logmap\", &Rot3::Logmap)\n    .staticmethod(\"Logmap\")\n    .def(\"LogmapDerivative\", &Rot3::LogmapDerivative)\n    .staticmethod(\"LogmapDerivative\")\n    .def(\"AxisAngle\", AxisAngle_0)\n    .def(\"AxisAngle\", AxisAngle_1)\n    .staticmethod(\"AxisAngle\")\n    .def(\"Rodrigues\", Rodrigues_0)\n    .def(\"Rodrigues\", Rodrigues_1)\n    .staticmethod(\"Rodrigues\")\n    .def(\"Rx\", &Rot3::Rx)\n    .staticmethod(\"Rx\")\n    .def(\"Ry\", &Rot3::Ry)\n    .staticmethod(\"Ry\")\n    .def(\"Rz\", &Rot3::Rz)\n    .staticmethod(\"Rz\")\n    .def(\"RzRyRx\", RzRyRx_0, (arg(\"x\"),arg(\"y\"),arg(\"z\")), \"Rotations around Z, Y, then X axes as in http://en.wikipedia.org/wiki/Rotation_matrix, counterclockwise when looking from unchanging axis\" )\n    .def(\"RzRyRx\", RzRyRx_1, arg(\"xyz\"), \"Rotations around Z, Y, then X axes as in http://en.wikipedia.org/wiki/Rotation_matrix, counterclockwise when looking from unchanging axis\" )\n    .staticmethod(\"RzRyRx\")\n    .def(\"Ypr\", &Rot3::Ypr)\n    .staticmethod(\"Ypr\")\n    .def(\"identity\", &Rot3::identity)\n    .staticmethod(\"identity\")\n    .def(\"AdjointMap\", &Rot3::AdjointMap)\n    .def(\"column\", &Rot3::column)\n    .def(\"conjugate\", &Rot3::conjugate)\n    .def(\"equals\", &Rot3::equals, equals_overloads(args(\"q\",\"tol\")))\n#ifndef GTSAM_USE_QUATERNIONS\n    .def(\"localCayley\", &Rot3::localCayley)\n    .def(\"retractCayley\", &Rot3::retractCayley)\n#endif\n    .def(\"matrix\", &Rot3::matrix)\n    .def(\"print\", &Rot3::print, print_overloads(args(\"s\")))\n    .def(\"r1\", &Rot3::r1)\n    .def(\"r2\", &Rot3::r2)\n    .def(\"r3\", &Rot3::r3)\n    .def(\"rpy\", &Rot3::rpy)\n    .def(\"slerp\", &Rot3::slerp)\n    .def(\"transpose\", &Rot3::transpose)\n    .def(\"xyz\", &Rot3::xyz)\n    .def(\"quaternion\", quaternion_0)\n    .def(self * self)\n    .def(self * other<Point3>())\n    .def(self * other<Unit3>())\n    .def(self_ns::str(self)) // __str__\n    .def(repr(self))         // __repr__\n  ;\n\n}\n", "meta": {"hexsha": "440559e3e29644adb9734a22294458b7efbc6715", "size": 4229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "python/handwritten/geometry/Rot3.cpp", "max_stars_repo_name": "karamach/gtsam", "max_stars_repo_head_hexsha": "35f9b710163a1d14d8dc4fcf50b8dce6e0bf7e5b", "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/python/handwritten/geometry/Rot3.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/python/handwritten/geometry/Rot3.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": 36.4568965517, "max_line_length": 200, "alphanum_fraction": 0.6419957437, "num_tokens": 1336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.5344209880089863}}
{"text": "// Copyright (C) 2013  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n#include <dlib/statistics.h>\r\n#include <dlib/sparse_vector.h>\r\n#include <map>\r\n\r\n#include \"tester.h\"\r\n\r\nnamespace  \r\n{\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n\r\n    logger dlog(\"test.cca\");\r\n\r\n    dlib::rand rnd;\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    /*\r\n    std::vector<std::map<unsigned long, double> > make_really_big_test_matrix (\r\n    )\r\n    {\r\n        std::vector<std::map<unsigned long,double> > temp(30000);\r\n        for (unsigned long i = 0; i < temp.size(); ++i)\r\n        {\r\n            for (int k = 0; k < 30; ++k)\r\n                temp[i][rnd.get_random_32bit_number()%10000] = 1;\r\n        }\r\n        return temp;\r\n    }\r\n    */\r\n\r\n    template <typename T>\r\n    std::vector<std::map<unsigned long, T> > mat_to_sparse (\r\n        const matrix<T>& A\r\n    )\r\n    {\r\n        std::vector<std::map<unsigned long,T> > temp(A.nr());\r\n        for (long r = 0; r < A.nr(); ++r)\r\n        {\r\n            for (long c = 0; c < A.nc(); ++c)\r\n            {\r\n                temp[r][c] = A(r,c);\r\n            }\r\n        }\r\n        return temp;\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    template <typename EXP>\r\n    matrix<typename EXP::type> rm_zeros (\r\n        const matrix_exp<EXP>& m\r\n    )\r\n    {\r\n        // Do this to avoid trying to correlate super small numbers that are really just\r\n        // zero.  Doing this avoids some potential false alarms in the unit tests below.\r\n        return round_zeros(m, max(abs(m))*1e-14);\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    /*\r\n    void check_correlation (\r\n        matrix<double> L,\r\n        matrix<double> R,\r\n        const matrix<double>& Ltrans,\r\n        const matrix<double>& Rtrans,\r\n        const matrix<double,0,1>& correlations\r\n    )\r\n    {\r\n        // apply the transforms\r\n        L = L*Ltrans;\r\n        R = R*Rtrans;\r\n\r\n        // compute the real correlation values. Store them in A.\r\n        matrix<double> A = compute_correlations(L, R);\r\n\r\n        for (long i = 0; i < correlations.size(); ++i)\r\n        {\r\n            // compare what the measured correlation values are (in A) to the \r\n            // predicted values.\r\n            cout << \"error: \"<< A(i) - correlations(i);\r\n        }\r\n    }\r\n    */\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    void test_cca3()\r\n    {\r\n        print_spinner();\r\n        const unsigned long rank = rnd.get_random_32bit_number()%10 + 1;\r\n        const unsigned long m = rank + rnd.get_random_32bit_number()%15;\r\n        const unsigned long n = rank + rnd.get_random_32bit_number()%15;\r\n        const unsigned long n2 = rank + rnd.get_random_32bit_number()%15;\r\n        const unsigned long rank2 = rank + rnd.get_random_32bit_number()%5;\r\n\r\n        dlog << LINFO << \"m:  \" << m;\r\n        dlog << LINFO << \"n:  \" << n;\r\n        dlog << LINFO << \"n2: \" << n2;\r\n        dlog << LINFO << \"rank:  \" << rank;\r\n        dlog << LINFO << \"rank2: \" << rank2;\r\n\r\n\r\n        matrix<double> L = randm(m,rank, rnd)*randm(rank,n, rnd);\r\n        //matrix<double> R = randm(m,rank, rnd)*randm(rank,n2, rnd);\r\n        matrix<double> R = L*randm(n,n2);\r\n        //matrix<double> L = randm(m,n, rnd);\r\n        //matrix<double> R = randm(m,n2, rnd);\r\n\r\n        matrix<double> Ltrans, Rtrans;\r\n        matrix<double,0,1> correlations;\r\n\r\n        {\r\n            correlations = cca(L, R, Ltrans, Rtrans, min(m,n), max(n,n2));\r\n            DLIB_TEST(Ltrans.nc() == Rtrans.nc());\r\n            dlog << LINFO << \"correlations: \"<< trans(correlations);\r\n\r\n            const double corr_error = max(abs(compute_correlations(rm_zeros(L*Ltrans), rm_zeros(R*Rtrans)) - correlations));\r\n            dlog << LINFO << \"correlation error: \"<< corr_error;\r\n            DLIB_TEST_MSG(corr_error < 1e-13, Ltrans << \"\\n\\n\" << Rtrans);\r\n\r\n            const double trans_error = max(abs(L*Ltrans - R*Rtrans));\r\n            dlog << LINFO << \"trans_error: \"<< trans_error;\r\n            DLIB_TEST(trans_error < 1e-9);\r\n        }\r\n        {\r\n            correlations = cca(mat_to_sparse(L), mat_to_sparse(R), Ltrans, Rtrans, min(m,n), max(n,n2)+6, 4);\r\n            DLIB_TEST(Ltrans.nc() == Rtrans.nc());\r\n            dlog << LINFO << \"correlations: \"<< trans(correlations);\r\n            dlog << LINFO << \"computed cors: \" << trans(compute_correlations(rm_zeros(L*Ltrans), rm_zeros(R*Rtrans)));\r\n\r\n            const double trans_error = max(abs(L*Ltrans - R*Rtrans));\r\n            dlog << LINFO << \"trans_error: \"<< trans_error;\r\n            const double corr_error = max(abs(compute_correlations(rm_zeros(L*Ltrans), rm_zeros(R*Rtrans)) - correlations));\r\n            dlog << LINFO << \"correlation error: \"<< corr_error;\r\n            DLIB_TEST_MSG(corr_error < 1e-13, Ltrans << \"\\n\\n\" << Rtrans);\r\n\r\n            DLIB_TEST(trans_error < 1e-9);\r\n        }\r\n\r\n        dlog << LINFO << \"*****************************************************\";\r\n    }\r\n\r\n    void test_cca2()\r\n    {\r\n        print_spinner();\r\n        const unsigned long rank = rnd.get_random_32bit_number()%10 + 1;\r\n        const unsigned long m = rank + rnd.get_random_32bit_number()%15;\r\n        const unsigned long n = rank + rnd.get_random_32bit_number()%15;\r\n        const unsigned long n2 = rank + rnd.get_random_32bit_number()%15;\r\n\r\n        dlog << LINFO << \"m:  \" << m;\r\n        dlog << LINFO << \"n:  \" << n;\r\n        dlog << LINFO << \"n2: \" << n2;\r\n        dlog << LINFO << \"rank:  \" << rank;\r\n\r\n\r\n        matrix<double> L = randm(m,n, rnd);\r\n        matrix<double> R = randm(m,n2, rnd);\r\n\r\n        matrix<double> Ltrans, Rtrans;\r\n        matrix<double,0,1> correlations;\r\n\r\n        {\r\n            correlations = cca(L, R, Ltrans, Rtrans, min(n,n2), max(n,n2)-min(n,n2));\r\n            DLIB_TEST(Ltrans.nc() == Rtrans.nc());\r\n            dlog << LINFO << \"correlations: \"<< trans(correlations);\r\n\r\n            if (Ltrans.nc() > 1)\r\n            {\r\n                // The CCA projection directions are supposed to be uncorrelated for\r\n                // non-matching pairs of projections.\r\n                const double corr_rot1_error = max(abs(compute_correlations(rm_zeros(L*rotate<0,1>(Ltrans)), rm_zeros(R*Rtrans))));\r\n                dlog << LINFO << \"corr_rot1_error: \"<< corr_rot1_error;\r\n                DLIB_TEST(std::abs(corr_rot1_error) < 1e-10);\r\n            }\r\n            // Matching projection directions should be correlated with the amount of\r\n            // correlation indicated by the return value of cca().\r\n            const double corr_error = max(abs(compute_correlations(rm_zeros(L*Ltrans), rm_zeros(R*Rtrans)) - correlations));\r\n            dlog << LINFO << \"correlation error: \"<< corr_error;\r\n            DLIB_TEST(corr_error < 1e-13);\r\n        }\r\n        {\r\n            correlations = cca(mat_to_sparse(L), mat_to_sparse(R), Ltrans, Rtrans, min(n,n2), max(n,n2)-min(n,n2));\r\n            DLIB_TEST(Ltrans.nc() == Rtrans.nc());\r\n            dlog << LINFO << \"correlations: \"<< trans(correlations);\r\n\r\n            if (Ltrans.nc() > 1)\r\n            {\r\n                // The CCA projection directions are supposed to be uncorrelated for\r\n                // non-matching pairs of projections.\r\n                const double corr_rot1_error = max(abs(compute_correlations(rm_zeros(L*rotate<0,1>(Ltrans)), rm_zeros(R*Rtrans))));\r\n                dlog << LINFO << \"corr_rot1_error: \"<< corr_rot1_error;\r\n                DLIB_TEST(std::abs(corr_rot1_error) < 1e-10);\r\n            }\r\n            // Matching projection directions should be correlated with the amount of\r\n            // correlation indicated by the return value of cca().\r\n            const double corr_error = max(abs(compute_correlations(rm_zeros(L*Ltrans), rm_zeros(R*Rtrans)) - correlations));\r\n            dlog << LINFO << \"correlation error: \"<< corr_error;\r\n            DLIB_TEST(corr_error < 1e-13);\r\n        }\r\n\r\n        dlog << LINFO << \"*****************************************************\";\r\n    }\r\n\r\n    void test_cca1()\r\n    {\r\n        print_spinner();\r\n        const unsigned long rank = rnd.get_random_32bit_number()%10 + 1;\r\n        const unsigned long m = rank + rnd.get_random_32bit_number()%15;\r\n        const unsigned long n = rank + rnd.get_random_32bit_number()%15;\r\n\r\n        dlog << LINFO << \"m: \" << m;\r\n        dlog << LINFO << \"n: \" << n;\r\n        dlog << LINFO << \"rank: \" << rank;\r\n\r\n        matrix<double> T = randm(n,n, rnd);\r\n\r\n        matrix<double> L = randm(m,rank, rnd)*randm(rank,n, rnd);\r\n        //matrix<double> L = randm(m,n, rnd);\r\n        matrix<double> R = L*T;\r\n\r\n        matrix<double> Ltrans, Rtrans;\r\n        matrix<double,0,1> correlations;\r\n\r\n        {\r\n            correlations = cca(L, R, Ltrans, Rtrans, rank);\r\n            DLIB_TEST(Ltrans.nc() == Rtrans.nc());\r\n            if (Ltrans.nc() > 1)\r\n            {\r\n                // The CCA projection directions are supposed to be uncorrelated for\r\n                // non-matching pairs of projections.\r\n                const double corr_rot1_error = max(abs(compute_correlations(rm_zeros(L*rotate<0,1>(Ltrans)), rm_zeros(R*Rtrans))));\r\n                dlog << LINFO << \"corr_rot1_error: \"<< corr_rot1_error;\r\n                DLIB_TEST(std::abs(corr_rot1_error) < 1e-10);\r\n            }\r\n            // Matching projection directions should be correlated with the amount of\r\n            // correlation indicated by the return value of cca().\r\n            const double corr_error = max(abs(compute_correlations(rm_zeros(L*Ltrans), rm_zeros(R*Rtrans)) - correlations));\r\n            dlog << LINFO << \"correlation error: \"<< corr_error;\r\n            DLIB_TEST(corr_error < 1e-13);\r\n\r\n            const double trans_error = max(abs(L*Ltrans - R*Rtrans));\r\n            dlog << LINFO << \"trans_error: \"<< trans_error;\r\n            DLIB_TEST(trans_error < 1e-10);\r\n\r\n            dlog << LINFO << \"correlations: \"<< trans(correlations);\r\n        }\r\n        {\r\n            correlations = cca(mat_to_sparse(L), mat_to_sparse(R), Ltrans, Rtrans, rank);\r\n            DLIB_TEST(Ltrans.nc() == Rtrans.nc());\r\n            if (Ltrans.nc() > 1)\r\n            {\r\n                // The CCA projection directions are supposed to be uncorrelated for\r\n                // non-matching pairs of projections.\r\n                const double corr_rot1_error = max(abs(compute_correlations(rm_zeros(L*rotate<0,1>(Ltrans)), rm_zeros(R*Rtrans))));\r\n                dlog << LINFO << \"corr_rot1_error: \"<< corr_rot1_error;\r\n                DLIB_TEST(std::abs(corr_rot1_error) < 1e-10);\r\n            }\r\n            // Matching projection directions should be correlated with the amount of\r\n            // correlation indicated by the return value of cca().\r\n            const double corr_error = max(abs(compute_correlations(rm_zeros(L*Ltrans), rm_zeros(R*Rtrans)) - correlations));\r\n            dlog << LINFO << \"correlation error: \"<< corr_error;\r\n            DLIB_TEST(corr_error < 1e-13);\r\n\r\n            const double trans_error = max(abs(L*Ltrans - R*Rtrans));\r\n            dlog << LINFO << \"trans_error: \"<< trans_error;\r\n            DLIB_TEST(trans_error < 1e-9);\r\n\r\n            dlog << LINFO << \"correlations: \"<< trans(correlations);\r\n        }\r\n\r\n        dlog << LINFO << \"*****************************************************\";\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    void test_svd_fast(\r\n        long rank,\r\n        long m,\r\n        long n\r\n    )\r\n    {\r\n        print_spinner();\r\n        matrix<double> A = randm(m,rank,rnd)*randm(rank,n,rnd);\r\n        matrix<double> u,v;\r\n        matrix<double,0,1> w;\r\n\r\n        dlog << LINFO << \"rank: \"<< rank;\r\n        dlog << LINFO << \"m: \"<< m;\r\n        dlog << LINFO << \"n: \"<< n;\r\n\r\n        svd_fast(A, u, w, v, rank, 2);\r\n        DLIB_TEST(u.nr() == m);\r\n        DLIB_TEST(u.nc() == rank);\r\n        DLIB_TEST(w.nr() == rank);\r\n        DLIB_TEST(w.nc() == 1);\r\n        DLIB_TEST(v.nr() == n);\r\n        DLIB_TEST(v.nc() == rank);\r\n        DLIB_TEST(max(abs(trans(u)*u - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(trans(v)*v - identity_matrix<double>(u.nc()))) < 1e-13);\r\n\r\n        DLIB_TEST(max(abs(tmp(A - u*diagm(w)*trans(v)))) < 1e-13);\r\n        svd_fast(mat_to_sparse(A), u, w, v, rank, 2);\r\n        DLIB_TEST(u.nr() == m);\r\n        DLIB_TEST(u.nc() == rank);\r\n        DLIB_TEST(w.nr() == rank);\r\n        DLIB_TEST(w.nc() == 1);\r\n        DLIB_TEST(v.nr() == n);\r\n        DLIB_TEST(v.nc() == rank);\r\n        DLIB_TEST(max(abs(trans(u)*u - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(trans(v)*v - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(tmp(A - u*diagm(w)*trans(v)))) < 1e-13);\r\n\r\n        svd_fast(A, u, w, v, rank, 0);\r\n        DLIB_TEST(u.nr() == m);\r\n        DLIB_TEST(u.nc() == rank);\r\n        DLIB_TEST(w.nr() == rank);\r\n        DLIB_TEST(w.nc() == 1);\r\n        DLIB_TEST(v.nr() == n);\r\n        DLIB_TEST(v.nc() == rank);\r\n        DLIB_TEST(max(abs(trans(u)*u - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(trans(v)*v - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST_MSG(max(abs(tmp(A - u*diagm(w)*trans(v)))) < 1e-9,max(abs(tmp(A - u*diagm(w)*trans(v)))));\r\n        svd_fast(mat_to_sparse(A), u, w, v, rank, 0);\r\n        DLIB_TEST(u.nr() == m);\r\n        DLIB_TEST(u.nc() == rank);\r\n        DLIB_TEST(w.nr() == rank);\r\n        DLIB_TEST(w.nc() == 1);\r\n        DLIB_TEST(v.nr() == n);\r\n        DLIB_TEST(v.nc() == rank);\r\n        DLIB_TEST(max(abs(trans(u)*u - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(trans(v)*v - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(tmp(A - u*diagm(w)*trans(v)))) < 1e-10);\r\n\r\n        svd_fast(A, u, w, v, rank+5, 0);\r\n        DLIB_TEST(max(abs(trans(u)*u - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(trans(v)*v - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(tmp(A - u*diagm(w)*trans(v)))) < 1e-11);\r\n        svd_fast(mat_to_sparse(A), u, w, v, rank+5, 0);\r\n        DLIB_TEST(max(abs(trans(u)*u - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(trans(v)*v - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(tmp(A - u*diagm(w)*trans(v)))) < 1e-11);\r\n        svd_fast(A, u, w, v, rank+5, 1);\r\n        DLIB_TEST(max(abs(trans(u)*u - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(trans(v)*v - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(tmp(A - u*diagm(w)*trans(v)))) < 1e-12);\r\n        svd_fast(mat_to_sparse(A), u, w, v, rank+5, 1);\r\n        DLIB_TEST(max(abs(trans(u)*u - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(trans(v)*v - identity_matrix<double>(u.nc()))) < 1e-13);\r\n        DLIB_TEST(max(abs(tmp(A - u*diagm(w)*trans(v)))) < 1e-12);\r\n    }\r\n\r\n    void test_svd_fast()\r\n    {\r\n        for (int iter = 0; iter < 1000; ++iter)\r\n        {\r\n            const unsigned long rank = rnd.get_random_32bit_number()%10 + 1;\r\n            const unsigned long m = rank + rnd.get_random_32bit_number()%10;\r\n            const unsigned long n = rank + rnd.get_random_32bit_number()%10;\r\n\r\n            test_svd_fast(rank, m, n);\r\n\r\n        }\r\n        test_svd_fast(1, 1, 1);\r\n        test_svd_fast(1, 2, 2);\r\n        test_svd_fast(1, 1, 2);\r\n        test_svd_fast(1, 2, 1);\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    class test_cca : public tester\r\n    {\r\n    public:\r\n        test_cca (\r\n        ) :\r\n            tester (\"test_cca\",\r\n                \"Runs tests on the cca() and svd_fast() routines.\")\r\n        {}\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            for (int i = 0; i < 200; ++i)\r\n            {\r\n                test_cca1();\r\n                test_cca2();\r\n                test_cca3();\r\n            }\r\n            test_svd_fast();\r\n        }\r\n    } a;\r\n\r\n\r\n\r\n}\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "0ee2895fbd7ae6328f344d2030a008a7cef80fe8", "size": 16272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/cca.cpp", "max_stars_repo_name": "ytobah/dlib-mod", "max_stars_repo_head_hexsha": "f1ddeb506b59c8b49f744323301b7f22fd3a25e0", "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": "dlib/test/cca.cpp", "max_issues_repo_name": "ytobah/dlib-mod", "max_issues_repo_head_hexsha": "f1ddeb506b59c8b49f744323301b7f22fd3a25e0", "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/cca.cpp", "max_forks_repo_name": "ytobah/dlib-mod", "max_forks_repo_head_hexsha": "f1ddeb506b59c8b49f744323301b7f22fd3a25e0", "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": 40.078817734, "max_line_length": 132, "alphanum_fraction": 0.5068829892, "num_tokens": 4174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5344209878132732}}
{"text": "#include \"caffe/util/prediction.hpp\"\n\n#include <vector>\n#include <Eigen/Core>\n\n#include <opencv2/core/core.hpp>\n\n// #include <cv.h>\n// #include <highgui.h>\n\nnamespace caffe {\n\t\ntemplate <typename Dtype>\nGrid<Dtype> rotate_voxels_prediction(const Grid<Dtype> &vox,\n\t\t\t\t\t\t\t\t   const Eigen::Matrix<Dtype,4,4> &model1,\n\t\t\t\t\t\t\t\t   const Eigen::Matrix<Dtype,4,4> &view1,\n\t\t\t\t\t\t\t\t   const Eigen::Matrix<Dtype,4,4> &model2,\n\t\t\t\t\t\t\t\t   const Eigen::Matrix<Dtype,4,4> &view2,\n\t\t\t\t\t\t\t\t   const Eigen::Matrix<Dtype,4,4> &proj)\n{\nint size = vox[0].rows();\n//std::cout<<size<<std::endl;\n\tGrid<Dtype> rot_vox(size);\n\tfor(int c = 0; c < size; c++)\n\t{\n\t\trot_vox[c] = Slice<Dtype>(size, size);\n\t\tfor(int i = 0; i <size; i++)\n\t\t{\n\t\t\tfor(int j = 0; j < size; j++)\n\t\t\t{\n\t\t\t\trot_vox[c](i,j) = rotated_proba_value<Dtype>(vox, model1, view1,model2, view2, proj, c, i, j);\n\t\t\t}\n\t\t}\n\t}\n\treturn rot_vox;\t\n}\n\n\ttemplate <typename Dtype>\nDtype rotated_proba_value(const Grid<Dtype> &vox,\n\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &model1,\n\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &view1,\n\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &model2,\n\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &view2,\n\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &proj,\n\t\t\t\t\t\t  Dtype z,Dtype x, Dtype y)\n{\n\tint size = vox[0].rows();\n\t//pass coord in the unit cube and rotate it\n\t// std::cout<<x<<\" \"<<y<<\" \"<<z<<\" -> \";\n\tDtype depth = z_to_depth(z, size, proj);;\n\t// std::cout<<depth<<std::endl;\n\tEigen::Matrix<Dtype,3,1> rotated =\n\t\trotate_coords<Dtype>((y+0.5)/(size), 1-(x+0.5)/(size),\n\t\t\t\t\t  depth, model1, view1,model2, view2, proj);\n\t// std::cout<<rotated<<std::endl;\n\n\tint new_i = (int)std::floor((1-rotated.y())*(size));\n\tint new_j = (int)std::floor(rotated.x()*(size));\n\tint new_z = depth_to_z(rotated.z(), size, proj);\n\tnew_z = std::min<int>(size - 1,std::max<int>(0,new_z));\n\t// std::cout<<new_i<<\" \"<<new_j<<\" \"<<new_z<<std::endl;\n\tDtype v0 = vox[new_z](new_i, new_j);\n\treturn v0;\n}\n\n\ttemplate <typename Dtype>\n\tDtype z_to_depth(int z, int size, const Eigen::Matrix<Dtype,4,4> &proj)\n{\n\tDtype zf=z*0.8+(size/16);\n\tDtype depth = -(zf+0.5)/size*5.5-2.5;\n\tdepth = -proj(2,3)/depth-proj(2,2);\n\tdepth=depth/2+0.5;\n\treturn depth;\n}\n\n\ttemplate <typename Dtype>\nint depth_to_z(Dtype depth, int size, const Eigen::Matrix<Dtype,4,4> &proj)\n{\n\tdepth = depth * 2 - 1;\n\tdepth = -proj(2,3)/(depth+proj(2,2));\n\tDtype z = (-(depth+2.5)/5.5)*size-0.5;\n\treturn (int)std::round((z-(size/16))/0.8);\n}\n\n\ttemplate <typename Dtype>\nEigen::Matrix<Dtype,3,1> rotate_coords(Dtype x, Dtype y, Dtype z,\n\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &model1,\n\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &view1,\n\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &model2,\n\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &view2,\n\t\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &proj)\n{\n\tEigen::Matrix<Dtype,4,1> NDC(x*2-1, y*2-1, z*2-1, 1.0);\n\tEigen::Matrix<Dtype,4,1> position = (proj*view2*model2).inverse()*NDC;\n\t//rotate\n\tEigen::Matrix<Dtype,4,1> coords = proj * view1 * model1 * position;\n\tcoords /= coords.w();\n\t//goes back into (0,1)\n\tcoords = coords.array()/2+0.5;\n\t//make sure\n\tcoords.x() = std::min<Dtype>(0.99,std::max<Dtype>(0.01,coords.x()));\n\tcoords.y() = std::min<Dtype>(0.99,std::max<Dtype>(0.01,coords.y()));\n\tcoords.z() = std::min<Dtype>(0.99,std::max<Dtype>(0.01,coords.z()));\n\treturn coords.head(3);\n}\n\n\n\nfloat interpolate( float val, float y0, float x0, float y1, float x1 ) {\n    return (val-x0)*(y1-y0)/(x1-x0) + y0;\n}\n\nfloat base( float val ) {\n    if ( val <= -0.75 ) return 0;\n    else if ( val <= -0.25 ) return interpolate( val, 0.0, -0.75, 1.0, -0.25 );\n    else if ( val <= 0.25 ) return 1.0;\n    else if ( val <= 0.75 ) return interpolate( val, 1.0, 0.25, 0.0, 0.75 );\n    else return 0.0;\n}\n\ncv::Vec3b jetColor(float gray)\n{\n\treturn cv::Vec3b(base( gray + 0.5 )*255,base( gray )*255, base( gray - 0.5 )*255);\n}\n\n\ttemplate <typename Dtype>\ncv::Mat iso_surface(const  Grid<Dtype> &vox,\n\t\t\t\t\tfloat threshold)\n{\n\tint size = vox[0].rows();\n\tcv::Mat img(size, size,CV_8UC3);\n\tfor(int i = 0; i <size; i++)\n\t{\n\t\tfor(int j = 0; j < size; j++)\n\t\t{\n\t\t\tint c_depth = -1;\n\t\t\tfor(int c = 0; c < size; c++)\n\t\t\t{\nfloat val_depth= vox[c](i,j);\n\t\t\t\tif (val_depth > threshold)\n\t\t\t\t{\n\t\t\t\t\tc_depth = c;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfloat depth = (c_depth+0.5)/(size);\n\t\t\tcv::Vec3b color = jetColor(depth*2-1);\n\t\t\timg.at<cv::Vec3b>(i, j)=color;\n\t\t}\n\t}\n\n\treturn img;\n}\n\t\n\n//takes only blobs and do the work (go to eigen and rotate) AVOID COPYING!\n\ttemplate <typename Dtype>\n\tvoid rotate_blobs(const Blob<Dtype> * pred,\n\t\t\t\t\t  const Dtype* model1,\n\t\t\t\t\t  const Dtype* view_mat1,\n\t\t\t\t\t  const Dtype* model2,\n\t\t\t\t\t  const Dtype* view_mat2,\n\t\t\t\t\t  const Dtype* proj_mat,\n\t\t\t\t\t  Dtype * output)  //WARNING a voir\n\t{\n\t\t//go from pred to a Grid<Dtype>\n\t\tint output_channels=pred->channels();\n\t\tint output_width = pred->width();\n\t\tint output_height = pred->height();\n\t\tint size = output_width;\n\t\t\n\n\t\tGrid<Dtype> grid(size);\n\t\tconst Dtype* output_data=pred->cpu_data();\n\t\t//chenger methode selon taille du blob  (unfold ou 3d)\n\t\tif (output_height == size*size) //if pred from a net, skip first classif layer\n\t\t\toutput_data+=output_width * output_height;\n\n\t\tfor(int c = 0; c < size; c++)\n\t\t{\n\t\t\tSlice<Dtype> channel(size, size);\n\t\t\tstd::memcpy(channel.data(), output_data, size*size* sizeof(Dtype));\n\t\t\toutput_data += size*size;\n\t\t\tgrid[c] = channel;\n\t\t}\n\t\t//transform viewpoint, view_mat, proj_mat into eigen matrices\n\t\tEigen::Map<const Eigen::Matrix<Dtype,4,4> > view1(view_mat1);\n\t\tEigen::Map<const Eigen::Matrix<Dtype,4,4> > view2(view_mat2);\n\t\tEigen::Map<const Eigen::Matrix<Dtype,4,4> > proj(proj_mat);\n\t\tEigen::Map<const Eigen::Matrix<Dtype,4,4> > mv1(model1);\n\t\tEigen::Map<const Eigen::Matrix<Dtype,4,4> > mv2(model2);\n\t\t// std::cout<<view1<<std::endl<<std::endl;\n\t\t// std::cout<<view2<<std::endl<<std::endl;\n\t\t// std::cout<<mv1<<std::endl<<std::endl;\n\t\t// std::cout<<mv2<<std::endl<<std::endl;\n\t\t//compute model\n\t\t// Eigen::Matrix<Dtype,4,4> model;\n\t\t// model = new_view*model_old.inverse();\n\t\t// model=model.inverse();\n\n\t\t//rotate\n\t\tGrid<Dtype> gt12 = rotate_voxels_prediction<Dtype>(grid, mv1, view1, mv2, view2, proj);\n\t\t// std::cout<<\"rotate ok\"<<std::endl;\n\t\t// cv::Mat pred1 = iso_surface(grid, 0.3);\n\t\t// cv::namedWindow( \"pred1\", CV_WINDOW_NORMAL );\n\t\t// cv::imshow(\"pred1\",pred1);\n\t\t// cv::Mat pred2 = iso_surface(gt12, 0.3);\n\t\t// cv::namedWindow( \"pred2\", CV_WINDOW_NORMAL );\n\t\t// cv::imshow(\"pred2\",pred2);\n\t\t// cv::waitKey(0);\n\t\t//put into output\n\n\t\tfor(int c = 0; c < size; c++)\n\t\t{\n\t\t\tstd::memcpy(output, gt12[c].data() ,size * size * sizeof(Dtype));\n\t\t\toutput += size*size;\n\t\t}\n\t}\n\n\ttemplate <typename Dtype>\n\tGrid<Dtype> unpack_pred_in_image( cv::Mat &image, int grid_rows, int grid_cols)\n{\n\t//assert(grid_rows*grid_cols == grid.size()/4);\n\tint nrows = image.rows/grid_rows;\n\tint ncols = image.cols/grid_cols;\n\tint nchannels = nrows/4;//std::min<int>(grid.size(), grid_rows*grid_cols);\n\t//cv::Mat img(nrows*grid_rows, ncols*grid_cols,CV_8UC4);\n\t//std::cout<<\"start to unpack\\n\";\n\tstd::vector<cv::Mat> imgs;\n\tint from_to[4*2] = {0,2,1,1,2,0,3,3};\n\tstd::vector<cv::Mat> img;\n\timg.push_back(image);\n\t// std::cout<<img[0].type()<<std::endl;\n\t//std::cout<<img[0].channels()<<std::endl;\n\tfor(int i = 0; i<4; i++)\n\t{\n\t\timgs.push_back(cv::Mat(image.size(),CV_8UC1));\n\t}\n\tcv::mixChannels(img,imgs,from_to,4);\n\t// for(int i = 0; i<4; i++)\n\t// \timShow::show(imgs[i],\"img\"+std::to_string(i));\n\t// imShow::wait();\n\t// cv::namedWindow(\"grid\");\n\t\n\tGrid<Dtype> grid(nrows);\n\tfor(int c = 0; c<nchannels; c++)\n\t{\n\t\tint i_cell = c/grid_cols*nrows;\n\t\tint j_cell = c%grid_cols*ncols;\n\t\t//std::cout<<\"c = \"<<c<<\", icell = \"<<i_cell<<\", jcell = \"<<j_cell<<std::endl;\n\t\tfor(int i = 0; i<4; i++)\n\t\t{\n\t\t\tint channel = c*4 + i;\n\t\t\t//std::cout<<\"copying channel \"<<channel<<std::endl;\n\t\t\tcv::Mat part = imgs[i](cv::Rect(j_cell,i_cell,nrows,ncols)),partF;\n\t\t\tpart.convertTo(partF, CV_type<Dtype>(), 1.0/255);\n\n\t\t\tEigen::Map<Slice<Dtype> > chan(reinterpret_cast<Dtype*>(partF.data),nrows,ncols);\n\t\t\tgrid[channel] =chan;\n\t\t\n\t\t}\n\t}\n\t// cv::imshow(\"grid\",pred_to_grid(grid,8,8));\n\t// cv::waitKey(0);\n\treturn grid;\n}\n\ntemplate <typename Dtype>\nint CV_type()\n{\n\treturn 0;\n}\n\ttemplate <>\n\tint CV_type<float>()\n\t{\n\t\treturn CV_32F;\n\t}\n\ttemplate <>\n\tint CV_type<double>()\n\t{\n\t\treturn CV_64F;\n\t}\n\n\ttemplate \tGrid<float> unpack_pred_in_image( cv::Mat &image, int grid_rows, int grid_cols);\n\ttemplate \tGrid<double> unpack_pred_in_image( cv::Mat &image, int grid_rows, int grid_cols);\n\n\t\n\ttemplate void rotate_blobs(const Blob<double> * pred, const double* model1, const double* model2, const double* view_mat1, const double* view_mat2,  const double* proj_mat, double * output);\n\ttemplate void rotate_blobs(const Blob<float> * pred, const float* model1, const float* model2, const float* view_mat1, const float* view_mat2,  const float* proj_mat, float * output);\n}\n", "meta": {"hexsha": "4969aa1c4ff9f91ce884c34427161934a467ac73", "size": 8809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/prediction.cpp", "max_stars_repo_name": "antonymarion/caffe", "max_stars_repo_head_hexsha": "0c9f2e500c6f971b2de45d08021c26d55cabc91b", "max_stars_repo_licenses": ["Intel", "BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-09T03:46:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T18:12:59.000Z", "max_issues_repo_path": "src/caffe/util/prediction.cpp", "max_issues_repo_name": "antonymarion/caffe", "max_issues_repo_head_hexsha": "0c9f2e500c6f971b2de45d08021c26d55cabc91b", "max_issues_repo_licenses": ["Intel", "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/caffe/util/prediction.cpp", "max_forks_repo_name": "antonymarion/caffe", "max_forks_repo_head_hexsha": "0c9f2e500c6f971b2de45d08021c26d55cabc91b", "max_forks_repo_licenses": ["Intel", "BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-04T13:47:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-31T19:23:59.000Z", "avg_line_length": 30.2714776632, "max_line_length": 191, "alphanum_fraction": 0.6277670564, "num_tokens": 3015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5344048069678053}}
{"text": "\n#include <CGAL/Surface_mesh_segmentation/internal/Expectation_maximization.h>\n\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n/**\n * Generates sample points using a few gauissians.\n * Then applies gmm fitting on these generated points.\n * Provides a heuristic score for each gmm fitting result.\n *\n */\nint main(void)\n{\n    boost::mt19937 engine;\n    engine.seed(1340818006);\n\n    // generate random data using gauissians below\n    std::vector< boost::normal_distribution<double> > distributions;\n    distributions.push_back(boost::normal_distribution<double>(0.1, 0.05));\n    distributions.push_back(boost::normal_distribution<double>(0.4, 0.1));\n    distributions.push_back(boost::normal_distribution<double>(0.55, 0.05));\n    distributions.push_back(boost::normal_distribution<double>(0.7, 0.1));\n    distributions.push_back(boost::normal_distribution<double>(0.9, 0.05));\n    distributions.push_back(boost::normal_distribution<double>(1.0, 0.05));\n\n    std::vector<double> data;\n    for(std::vector< boost::normal_distribution<double> >::iterator it = distributions.begin();\n      it != distributions.end(); ++it)\n    {\n        boost::variate_generator<boost::mt19937&, boost::normal_distribution<double> > var_nor(engine, *it);\n\n        for(std::size_t i = 0; i < 300; ++i) { data.push_back(var_nor()); }\n    }\n\n    // calculate closest center (using above gauissians) for each generated points\n    // we will compare it with gmm fitting results\n    // also we might want to compute mixing coef for each center and select centers according to mixing_coef * prob(data)\n    std::vector<std::size_t> data_centers;\n    for(std::vector<double>::iterator it = data.begin(); it != data.end(); ++it)\n    {\n        std::size_t center_id = (std::numeric_limits<std::size_t>::max)(), center_counter = 0;;\n        double min_distance = (std::numeric_limits<double>::max)();\n        for(std::vector< boost::normal_distribution<double> >::iterator dis_it = distributions.begin();\n          dis_it != distributions.end(); ++dis_it, ++center_counter)\n        {\n            double distance = std::abs(*it - dis_it->mean());\n            if(min_distance > distance)\n            {\n                min_distance = distance;\n                center_id = center_counter;\n            }\n        }\n        data_centers.push_back(center_id);\n    }\n\n    // apply gmm fitting clustering\n    typedef CGAL::internal::Expectation_maximization E_M;\n    std::vector<E_M> gmm_fitters;\n    gmm_fitters.push_back(E_M(distributions.size(), data, E_M::PLUS_INITIALIZATION));\n    gmm_fitters.push_back(E_M(distributions.size(), data, E_M::RANDOM_INITIALIZATION));\n    gmm_fitters.push_back(E_M(distributions.size(), data, E_M::K_MEANS_INITIALIZATION));\n\n    std::vector< std::vector<std::size_t> > calculated_centers(gmm_fitters.size());\n    std::vector< std::vector<std::size_t> >::iterator calc_centers_it = calculated_centers.begin();\n    for(std::vector<E_M>::iterator it = gmm_fitters.begin(); it != gmm_fitters.end(); ++it, ++calc_centers_it)\n    {\n        it->fill_with_center_ids(*calc_centers_it);\n    }\n\n    std::cout << \"Compare results of EM with 'expected' (but be aware, it is not optimal result in terms of likelihood)\" << std::endl;\n    std::cout << \"Another words a clustering which has higher likelihood can result in worse score in here\" << std::endl;\n    for(std::vector< std::vector<std::size_t> >::iterator calc_centers_it = calculated_centers.begin();\n        calc_centers_it != calculated_centers.end(); ++calc_centers_it)\n    {\n        std::size_t true_count = 0;\n        std::vector<std::size_t>::iterator calculated_it = calc_centers_it->begin();\n        for(std::vector<std::size_t>::iterator it = data_centers.begin(); it != data_centers.end(); ++it, ++calculated_it)\n        {\n            if( (*it) == (*calculated_it) ) { ++true_count; }\n        }\n        double app_fit = static_cast<double>(true_count) / data_centers.size();\n        std::cout << \"[0,1]: \" << app_fit << std::endl;\n        if(app_fit < 0.7) {\n            std::cerr << \"There might be a problem if above printed comparison is too low.\" << std::endl;\n            return EXIT_FAILURE;\n        }\n    }\n}\n", "meta": {"hexsha": "1b311f02c0685f4cb291e4741770e05f2de1100f", "size": 4192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh_segmentation/test/Surface_mesh_segmentation/Expectation_maximization_test.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_segmentation/test/Surface_mesh_segmentation/Expectation_maximization_test.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_segmentation/test/Surface_mesh_segmentation/Expectation_maximization_test.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": 47.1011235955, "max_line_length": 134, "alphanum_fraction": 0.6667461832, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5344047986112822}}
{"text": "#include <vector>\n#include <type_traits>\n#include <iterator>\n\n#include <Eigen/Core>\n#include <iostream>\n\n#include \"utils.hpp\"\n\nnamespace tridiagonal {\n    using std::vector;\n    using Eigen::MatrixBase;\n\n    namespace internal {\n\n        // #####################################################################################\n        //\n        //                                   SOLVER\n        //\n        // #####################################################################################\n\n        template <typename IterA, typename IterB, typename IterC, typename IterD,\n                typename A = typename std::iterator_traits<IterA>::value_type,\n                typename B = typename std::iterator_traits<IterB>::value_type,\n                typename C = typename std::iterator_traits<IterC>::value_type,\n                typename D = typename std::iterator_traits<IterD>::value_type,\n                typename std::enable_if<std::is_base_of<MatrixBase<A>, A>::value, int>::type = 0,\n                typename std::enable_if<std::is_base_of<MatrixBase<B>, B>::value, int>::type = 0,\n                typename std::enable_if<std::is_base_of<MatrixBase<C>, C>::value, int>::type = 0,\n                typename std::enable_if<std::is_base_of<MatrixBase<D>, D>::value, int>::type = 0\n        >\n        vector<D> solve_off_tridiagonal(IterA lower_diagonal_begin, IterA lower_diagonal_end,\n                                        IterB diagonal_begin, IterB diagonal_end,\n                                        IterC upper_diagonal_begin, IterC upper_diagonal_end,\n                                        IterD rhs_begin, IterD rhs_end){\n\n            long n = std::distance(diagonal_begin, diagonal_end);\n\n            if(n == 1){\n                //\n                //  | B_0 | | x_0 | = | D_0 |\n                //\n                D x = (*diagonal_begin).fullPivHouseholderQr().solve(*rhs_begin);\n                return {x};\n            }\n\n\n            A const & a0 = *lower_diagonal_begin;\n            B const & b0 = *diagonal_begin;\n            C const & c0 = *upper_diagonal_begin;\n            D const & d0 = *rhs_begin;\n\n\n            auto b0inv_c0 = b0.inverse() * c0;\n            auto b0inv_d0 = b0.inverse() * d0;\n\n            ++lower_diagonal_begin; ++diagonal_begin; ++upper_diagonal_begin; ++rhs_begin;\n\n            if(n == 2){\n                //\n                //  | B_0 C_0 | | x_0 | = | D_0 |\n                //  | A_0 B_1 | | x_1 | = | D_1 |\n                //\n\n                // B_1' = B_1 - A_0 * B_0.inv() * C_0\n                *diagonal_begin = *diagonal_begin - a0 * b0inv_c0;\n\n                // D_1' = D_1 - A_0 * B_0.inv() * D_0\n                *rhs_begin = *rhs_begin - a0 * b0inv_d0;\n\n                vector<D> x_list = solve_off_tridiagonal(lower_diagonal_begin, lower_diagonal_end,\n                                                         diagonal_begin, diagonal_end,\n                                                         upper_diagonal_begin, upper_diagonal_end,\n                                                         rhs_begin, rhs_end);\n\n                D x = b0inv_d0 - b0inv_c0 * x_list[0];\n\n                x_list.insert(x_list.begin(), x);\n\n                return x_list;\n            }\n\n            --lower_diagonal_end; --diagonal_end; --upper_diagonal_end; --rhs_end;\n            auto b0inv_a0 = b0.inverse() * a0;\n\n            // B_1' = B_1 - A_1 * B_0.inv() * C_0\n            *diagonal_begin = *diagonal_begin - *lower_diagonal_begin * b0inv_c0;\n\n            // B_{n-1}' = B_{n-1} - C_{n-1} * B_0.inv() * A_0\n            *diagonal_end = *diagonal_end - *upper_diagonal_end * b0inv_a0;\n\n            // D_1' = D_1 - A_1 * B_0.inv() * D_0\n            *rhs_begin = *rhs_begin - *lower_diagonal_begin * b0inv_d0;\n\n            // D_{n-1}' = D_{n-1} - C_{n-1} * B_0.inv() * D_0\n            *rhs_end = *rhs_end - *upper_diagonal_end * b0inv_d0;\n\n            if(n == 3){\n                //\n                //  | B_0 C_0 A_0 | | x_0 | = | D_0 |\n                //  | A_1 B_1 C_1 | | x_1 | = | D_1 |\n                //  | C_2 A_2 B_2 | | x_2 | = | D_2 |\n                //\n\n                // C_1' = C_1 - A_1 * B_0.inv() * A_0\n                *upper_diagonal_begin = *upper_diagonal_begin - *lower_diagonal_begin * b0inv_a0;\n\n                // A_2' = A_2 - C_2 * B_0.inv() * C_0\n                *lower_diagonal_end = *lower_diagonal_end - *upper_diagonal_end * b0inv_c0;\n\n                ++lower_diagonal_begin; --upper_diagonal_end;\n            }\n            else{\n                // A_1' = - A_1 * B_0.inv() * A_0\n                *lower_diagonal_begin = -1 * *lower_diagonal_begin * b0inv_a0;\n\n                // C_{n-1}' = - C_{n-1} * B_0*inv() * C_0\n                *upper_diagonal_end = -1 * *upper_diagonal_end * b0inv_c0;\n            }\n\n            ++lower_diagonal_end; ++diagonal_end; ++upper_diagonal_end; ++rhs_end;\n            vector<D> x_list = solve_off_tridiagonal(lower_diagonal_begin, lower_diagonal_end,\n                                                     diagonal_begin, diagonal_end,\n                                                     upper_diagonal_begin, upper_diagonal_end,\n                                                     rhs_begin, rhs_end);\n\n            // X_0 = B_0.inv() * (D_0 - C_0 * X_1 - A_0 * X_{n-1})\n            D x = b0inv_d0 - b0inv_c0 * x_list[0] - b0inv_a0 * x_list[x_list.size() - 1];\n\n            x_list.insert(x_list.begin(), x);\n\n            return x_list;\n        }\n\n\n        // #####################################################################################\n        //\n        //                                  INPUT CHECKING\n        //\n        // #####################################################################################\n\n        template <typename A, typename B, typename C, typename D,\n                typename std::enable_if<std::is_base_of<MatrixBase<A>, A>::value, int>::type = 0,\n                typename std::enable_if<std::is_base_of<MatrixBase<B>, B>::value, int>::type = 0,\n                typename std::enable_if<std::is_base_of<MatrixBase<C>, C>::value, int>::type = 0,\n                typename std::enable_if<std::is_base_of<MatrixBase<D>, D>::value, int>::type = 0\n        >\n        void check_valid_off_tridiagonal_number_of_matrices(vector<A> const &lower_diagonal,\n                                                            vector<B> const &diagonal,\n                                                            vector<C> const &upper_diagonal,\n                                                            vector<D> const &rhs) {\n\n            if(diagonal.size() != rhs.size()){\n                throw std::invalid_argument(invalid_number_of_elements_message(lower_diagonal,\n                                                                               diagonal,\n                                                                               upper_diagonal,\n                                                                               rhs));\n            }\n\n            if(diagonal.empty()){\n                throw std::invalid_argument(invalid_number_of_elements_message(lower_diagonal,\n                                                                               diagonal,\n                                                                               upper_diagonal,\n                                                                               rhs));\n            }\n            else if(diagonal.size() == 1){\n                if(lower_diagonal.empty() and !upper_diagonal.empty()) {\n                    throw std::invalid_argument(invalid_number_of_elements_message(lower_diagonal,\n                                                                                   diagonal,\n                                                                                   upper_diagonal,\n                                                                                   rhs));\n                }\n            }\n            else if(diagonal.size() == 2){\n                if(lower_diagonal.size() != 1 and upper_diagonal.size() != 1) {\n                    throw std::invalid_argument(invalid_number_of_elements_message(lower_diagonal,\n                                                                                   diagonal,\n                                                                                   upper_diagonal,\n                                                                                   rhs));\n                }\n            }\n            else if(diagonal.size() != lower_diagonal.size() or diagonal.size() != upper_diagonal.size()){\n                throw std::invalid_argument(invalid_number_of_elements_message(lower_diagonal,\n                                                                               diagonal,\n                                                                               upper_diagonal,\n                                                                               rhs));\n            }\n        }\n\n\n        template <typename A, typename B, typename C, typename D,\n                typename std::enable_if<std::is_base_of<MatrixBase<A>, A>::value, int>::type = 0,\n                typename std::enable_if<std::is_base_of<MatrixBase<B>, B>::value, int>::type = 0,\n                typename std::enable_if<std::is_base_of<MatrixBase<C>, C>::value, int>::type = 0,\n                typename std::enable_if<std::is_base_of<MatrixBase<D>, D>::value, int>::type = 0\n        >\n        void check_valid_off_tridiagonal_matrix_dimensions(vector<A> const &lower_diagonal,\n                                                           vector<B> const &diagonal,\n                                                           vector<C> const &upper_diagonal,\n                                                           vector<D> const &rhs) {\n            unsigned long n = diagonal.size();\n\n            if (n == 1){\n                if (diagonal[0].rows() != rhs[0].rows()){\n                    throw std::invalid_argument(\"Invalid matrix dimensions\");\n                }\n            }\n            else if(n == 2){\n                // upper left corner\n                if(diagonal[0].cols() != lower_diagonal[0].cols() or\n                   diagonal[0].rows() != upper_diagonal[0].rows() or\n                   diagonal[0].rows() != rhs[0].rows()) {\n                    throw std::invalid_argument(\"Invalid matrix dimensions\");\n                }\n\n                // bottom right corner\n                if(diagonal[1].cols() != upper_diagonal[0].cols() or\n                   diagonal[1].rows() != lower_diagonal[0].rows() or\n                   diagonal[1].rows() != rhs[1].rows()){\n                    throw std::invalid_argument(\"Invalid matrix dimensions\");\n                }\n            }\n            else{\n                // upper left corner\n                if(diagonal[0].cols() != lower_diagonal[1].cols() or\n                   diagonal[0].cols() != upper_diagonal[n-1].cols() or\n                   diagonal[0].rows() != upper_diagonal[0].rows() or\n                   diagonal[0].rows() != lower_diagonal[0].rows() or\n                   diagonal[0].rows() != rhs[0].rows()) {\n                    throw std::invalid_argument(\"Invalid matrix dimensions\");\n                }\n\n                // middle\n                for(int i = 1; i < diagonal.size()-1; i++){\n                    if(diagonal[i].cols() != upper_diagonal[i-1].cols() or\n                       diagonal[i].cols() != lower_diagonal[i+1].cols() or\n                       diagonal[i].rows() != upper_diagonal[i].rows() or\n                       diagonal[i].rows() != lower_diagonal[i].rows() or\n                       diagonal[i].rows() != rhs[i].rows()){\n                        throw std::invalid_argument(\"Invalid matrix dimensions\");\n                    }\n                }\n\n                // bottom right corner\n                if(diagonal[n-1].cols() != upper_diagonal[n-2].cols() or\n                   diagonal[n-1].cols() != lower_diagonal[0].cols() or\n                   diagonal[n-1].rows() != lower_diagonal[n-1].rows() or\n                   diagonal[n-1].rows() != upper_diagonal[n-1].rows() or\n                   diagonal[n-1].rows() != rhs[n-1].rows()){\n                    throw std::invalid_argument(\"Invalid matrix dimensions\");\n                }\n            }\n\n            // check that all diagonal matrices are square\n            for (auto const & d : diagonal){\n                if (d.cols() != d.rows()){\n                    throw std::invalid_argument(\"All diagonal matrices must be square\");\n                }\n            }\n\n            // check that all rhs matrices have same number of columns\n            long col_size = rhs[0].cols();\n            for (auto const & r : rhs) {\n                if (r.cols() != col_size){\n                    throw std::invalid_argument(\"All right-hand-side matrices must have the same number of columns.\");\n                }\n            }\n        }\n\n\n    }\n\n\n    // #####################################################################################\n    //\n    //                                INTERFACE FUNCTIONS\n    //\n    // #####################################################################################\n\n    template <typename A, typename B, typename C, typename D,\n            typename std::enable_if<!is_dynamic<A>::value, int>::type,\n            typename std::enable_if<!is_dynamic<B>::value, int>::type,\n            typename std::enable_if<!is_dynamic<C>::value, int>::type,\n            typename std::enable_if<!is_dynamic<D>::value, int>::type,\n            typename std::enable_if<A::RowsAtCompileTime == A::ColsAtCompileTime, int>::type,\n            typename std::enable_if<A::RowsAtCompileTime == B::RowsAtCompileTime, int>::type,\n            typename std::enable_if<A::ColsAtCompileTime == B::ColsAtCompileTime, int>::type,\n            typename std::enable_if<A::RowsAtCompileTime == C::RowsAtCompileTime, int>::type,\n            typename std::enable_if<A::ColsAtCompileTime == C::ColsAtCompileTime, int>::type,\n            typename std::enable_if<A::RowsAtCompileTime == D::RowsAtCompileTime, int>::type\n    >\n    vector<D> solve_off_tridiagonal(vector<A> const & lower_diagonal,\n                                    vector<B> const & diagonal,\n                                    vector<C> const & upper_diagonal,\n                                    vector<D> const & rhs) {\n\n        internal::check_valid_off_tridiagonal_number_of_matrices(lower_diagonal, diagonal, upper_diagonal, rhs);\n\n        vector<A> _lower_diagonal = lower_diagonal;\n        vector<B> _diagonal = diagonal;\n        vector<C> _upper_diagonal = upper_diagonal;\n        vector<D> _rhs = rhs;\n\n        return internal::solve_off_tridiagonal(_lower_diagonal.begin(), _lower_diagonal.end(),\n                                               _diagonal.begin(), _diagonal.end(),\n                                               _upper_diagonal.begin(), _upper_diagonal.end(),\n                                               _rhs.begin(), _rhs.end());\n    }\n\n\n    template <typename A, typename B, typename C, typename D,\n            typename std::enable_if<is_dynamic<A>::value or\n                                    is_dynamic<B>::value or\n                                    is_dynamic<C>::value or\n                                    is_dynamic<D>::value, int>::type\n    >\n    vector<D> solve_off_tridiagonal(vector<A> const & lower_diagonal,\n                                    vector<B> const & diagonal,\n                                    vector<C> const & upper_diagonal,\n                                    vector<D> const & rhs) {\n\n        internal::check_valid_off_tridiagonal_number_of_matrices(lower_diagonal, diagonal, upper_diagonal, rhs);\n        internal::check_valid_off_tridiagonal_matrix_dimensions(lower_diagonal, diagonal, upper_diagonal, rhs);\n\n        vector<A> _lower_diagonal = lower_diagonal;\n        vector<B> _diagonal = diagonal;\n        vector<C> _upper_diagonal = upper_diagonal;\n        vector<D> _rhs = rhs;\n\n        return internal::solve_off_tridiagonal(_lower_diagonal.begin(), _lower_diagonal.end(),\n                                               _diagonal.begin(), _diagonal.end(),\n                                               _upper_diagonal.begin(), _upper_diagonal.end(),\n                                               _rhs.begin(), _rhs.end());\n    }\n\n\n}\n\n", "meta": {"hexsha": "182620b35fc40a755aaa2c7cb67bc865ff254263", "size": 16343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tridiagonal/off_tridiagonal_solver.cpp", "max_stars_repo_name": "kit71717/tridiagonal", "max_stars_repo_head_hexsha": "672fef309fbcc66d75f9678eeb20a47ea546ed55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tridiagonal/off_tridiagonal_solver.cpp", "max_issues_repo_name": "kit71717/tridiagonal", "max_issues_repo_head_hexsha": "672fef309fbcc66d75f9678eeb20a47ea546ed55", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tridiagonal/off_tridiagonal_solver.cpp", "max_forks_repo_name": "kit71717/tridiagonal", "max_forks_repo_head_hexsha": "672fef309fbcc66d75f9678eeb20a47ea546ed55", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.209439528, "max_line_length": 118, "alphanum_fraction": 0.446857982, "num_tokens": 3392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5344047944330204}}
{"text": "// Copyright Oleg Maximenko 2014.\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://github.com/svgpp/svgpp for library home page.\n\n#pragma once\n\n#include <svgpp/definitions.hpp>\n#include <svgpp/utility/gil/common.hpp>\n#include <boost/gil/channel_algorithm.hpp>\n#include <boost/gil/color_base_algorithm.hpp>\n\nnamespace svgpp \n{ \n\nnamespace gil_detail \n{\n\nnamespace gil = boost::gil;\n\ntemplate<class CompositeModeTag, class ChannelValue>\nstruct composite_channel_fn;\n\ntemplate<class CompositeModeTag, class ChannelValue>\nstruct composite_alpha_fn;\n\ntemplate<class ChannelValue>\nstruct composite_arithmetic_channel_fn;\n\n// TODO: default implementation for non-8 bit channels\n\n// For signed channels we call unsigned analog, converting forward and back\ntemplate<class CompositeModeTag>\nstruct composite_channel_fn<CompositeModeTag, boost::int8_t>\n{\n  boost::int8_t operator()(boost::int8_t channel_a, boost::int8_t channel_b, boost::int8_t alpha_a, boost::int8_t alpha_b) const\n  {\n    typedef gil::detail::channel_convert_to_unsigned<boost::int8_t> to_unsigned;\n    typedef gil::detail::channel_convert_from_unsigned<boost::int8_t> from_unsigned;\n    composite_channel_fn<CompositeModeTag, boost::uint8_t> converter_unsigned;\n    return from_unsigned()(converter_unsigned(\n      to_unsigned()(channel_a), to_unsigned()(channel_b), to_unsigned()(alpha_a), to_unsigned()(alpha_b)));\n  }\n};\n\n// Dca' = Sca + Dca x (1 - Sa)\ntemplate<>\nstruct composite_channel_fn<tag::value::over, boost::uint8_t>\n{\n  boost::uint8_t operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8(channel_a + channel_b * (255 - alpha_a) / 255);\n  }\n};\n\n// Da'  = Sa + Da - Sa x Da\ntemplate<>\nstruct composite_alpha_fn<tag::value::over, boost::uint8_t>\n{\n  boost::uint8_t operator()(int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8(alpha_a + alpha_b - alpha_a * alpha_b / 255);\n  }\n};\n\n// Dca' = Sca x Da\ntemplate<>\nstruct composite_channel_fn<tag::value::in, boost::uint8_t>\n{\n  boost::uint8_t operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return channel_a * alpha_b / 255;\n  }\n};\n\n// Da'  = Sa x Da\ntemplate<>\nstruct composite_alpha_fn<tag::value::in, boost::uint8_t>\n{\n  boost::uint8_t operator()(int alpha_a, int alpha_b) const\n  {\n    return alpha_a * alpha_b / 255;\n  }\n};\n\n// Dca' = Sca x (1 - Da)\ntemplate<>\nstruct composite_channel_fn<tag::value::out, boost::uint8_t>\n{\n  boost::uint8_t operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return channel_a * alpha_a * (255 - alpha_b) / 65535;\n  }\n};\n\n// Da'  = Sa x (1 - Da)\ntemplate<>\nstruct composite_alpha_fn<tag::value::out, boost::uint8_t>\n{\n  boost::uint8_t operator()(int alpha_a, int alpha_b) const\n  {\n    return alpha_a * (255 - alpha_b) / 255;\n  }\n};\n\n// Dca' = Sca x Da + Dca x (1 - Sa)\ntemplate<>\nstruct composite_channel_fn<tag::value::atop, boost::uint8_t>\n{\n  boost::uint8_t operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return (channel_a * alpha_a + channel_b * (255 - alpha_a)) * alpha_b / 65535;\n  }\n};\n\n// Da'  = Da\ntemplate<>\nstruct composite_alpha_fn<tag::value::atop, boost::uint8_t>\n{\n  boost::uint8_t operator()(boost::uint8_t alpha_a, boost::uint8_t alpha_b) const\n  {\n    return alpha_b;\n  }\n};\n\n// Dca' = Sca x (1 - Da) + Dca x (1 - Sa)\ntemplate<>\nstruct composite_channel_fn<tag::value::xor_, boost::uint8_t>\n{\n  boost::uint8_t operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8((channel_a * alpha_a * (255 - alpha_b) + channel_b * alpha_b * (255 - alpha_a)) / 65535);\n  }\n};\n\n// Da'  = Sa + Da - 2 x Sa x Da\ntemplate<>\nstruct composite_alpha_fn<tag::value::xor_, boost::uint8_t>\n{\n  boost::uint8_t operator()(int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8((alpha_a + alpha_b - 2 * alpha_a * alpha_b) / 255);\n  }\n};\n\n// result = k1*i1*i2 + k2*i1 + k3*i2 + k4\ntemplate<>\nstruct composite_arithmetic_channel_fn<boost::uint8_t>\n{\n  template<class Coefficient>\n  composite_arithmetic_channel_fn(Coefficient k1, Coefficient k2, Coefficient k3, Coefficient k4)\n    : k1_(k1 * 255), k2_(k2 * 255), k3_(k3 * 255), k4_(k4 * 255)\n  {}\n\n  boost::uint8_t operator()(int channel_a, int channel_b) const \n  {\n    return clamp_channel_bits8(k1_ * channel_a * channel_b / 65535 + k2_ * channel_a / 255 + k3_ * channel_b / 255 + k4_);\n  }\n\nprivate:\n  int k1_, k2_, k3_, k4_;\n};\n\n} // namespace gil_detail \n\nnamespace gil_utility \n{\n\nnamespace gil = boost::gil;\n  \ntemplate<class CompositeModeTag>\nstruct composite_pixel\n{\n  template<class Color>\n  Color operator()(const Color & pixa, const Color & pixb) const \n  {\n    typename gil::color_element_type<Color, gil::alpha_t>::type \n      alpha_a = gil::get_color(pixa, gil::alpha_t()),\n      alpha_b = gil::get_color(pixb, gil::alpha_t());\n\n    Color result;\n\n    gil::get_color(result, gil::red_t()) \n      = gil_detail::composite_channel_fn<CompositeModeTag, typename gil::color_element_type<Color, gil::red_t>::type>()(\n        gil::get_color(pixa, gil::red_t()), gil::get_color(pixb, gil::red_t()),\n        alpha_a, alpha_b);\n\n    gil::get_color(result, gil::green_t()) \n      = gil_detail::composite_channel_fn<CompositeModeTag, typename gil::color_element_type<Color, gil::green_t>::type>()(\n        gil::get_color(pixa, gil::green_t()), gil::get_color(pixb, gil::green_t()),\n        alpha_a, alpha_b);\n\n    gil::get_color(result, gil::blue_t()) \n      = gil_detail::composite_channel_fn<CompositeModeTag, typename gil::color_element_type<Color, gil::blue_t>::type>()(\n        gil::get_color(pixa, gil::blue_t()), gil::get_color(pixb, gil::blue_t()),\n        alpha_a, alpha_b);\n\n    gil::get_color(result, gil::alpha_t()) = \n      gil_detail::composite_alpha_fn<CompositeModeTag, typename gil::color_element_type<Color, gil::alpha_t>::type>()(alpha_a, alpha_b);\n\n    return result;\n  }\n};\n\ntemplate<class Color>\nstruct composite_pixel_arithmetic\n{\n  template<class Coefficient>\n  composite_pixel_arithmetic(Coefficient k1, Coefficient k2, Coefficient k3, Coefficient k4)\n    : r_(k1, k2, k3, k4)\n    , g_(k1, k2, k3, k4)\n    , b_(k1, k2, k3, k4)\n    , a_(k1, k2, k3, k4)\n  {}\n\n  Color operator()(const Color & pixa, const Color & pixb) const \n  {\n    Color result;\n    gil::get_color(result, gil::red_t())   = r_(gil::get_color(pixa, gil::red_t())   , gil::get_color(pixb, gil::red_t())   );\n    gil::get_color(result, gil::green_t()) = r_(gil::get_color(pixa, gil::green_t()) , gil::get_color(pixb, gil::green_t()) );\n    gil::get_color(result, gil::blue_t())  = r_(gil::get_color(pixa, gil::blue_t())  , gil::get_color(pixb, gil::blue_t())  );\n    gil::get_color(result, gil::alpha_t()) = r_(gil::get_color(pixa, gil::alpha_t()) , gil::get_color(pixb, gil::alpha_t()) );\n    return result;\n  }\n\nprivate:\n  gil_detail::composite_arithmetic_channel_fn<typename gil::color_element_type<Color, gil::red_t  >::type> r_;\n  gil_detail::composite_arithmetic_channel_fn<typename gil::color_element_type<Color, gil::green_t>::type> g_;\n  gil_detail::composite_arithmetic_channel_fn<typename gil::color_element_type<Color, gil::blue_t >::type> b_;\n  gil_detail::composite_arithmetic_channel_fn<typename gil::color_element_type<Color, gil::alpha_t>::type> a_;\n};\n\n}}\n", "meta": {"hexsha": "b350d115cb0c89fec87fc52887edd219ffb93073", "size": 7419, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/svgpp/utility/gil/composite.hpp", "max_stars_repo_name": "RichardCory/svgpp", "max_stars_repo_head_hexsha": "801e0142c61c88cf2898da157fb96dc04af1b8b0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 428.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:25:47.000Z", "max_issues_repo_path": "include/svgpp/utility/gil/composite.hpp", "max_issues_repo_name": "andrew2015/svgpp", "max_issues_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T14:32:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T16:55:11.000Z", "max_forks_repo_path": "include/svgpp/utility/gil/composite.hpp", "max_forks_repo_name": "andrew2015/svgpp", "max_forks_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2015-05-19T04:56:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:42:50.000Z", "avg_line_length": 31.436440678, "max_line_length": 136, "alphanum_fraction": 0.6994204071, "num_tokens": 2233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5343950648465926}}
{"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   testSubgraphConditioner.cpp\n *  @brief  Unit tests for SubgraphPreconditioner\n *  @author Frank Dellaert\n **/\n\n#include <CppUnitLite/TestHarness.h>\n\n#if 0\n\n#include <tests/smallExample.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/linear/iterative.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/SubgraphPreconditioner.h>\n#include <gtsam/inference/Ordering.h>\n#include <gtsam/base/numericalDerivative.h>\n\n#include <boost/tuple/tuple.hpp>\n#include <boost/assign/std/list.hpp>\nusing namespace boost::assign;\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace example;\n\n// define keys\n// Create key for simulated planar graph\nSymbol key(int x, int y) {\n  return symbol_shorthand::X(1000*x+y);\n}\n\n/* ************************************************************************* */\nTEST( SubgraphPreconditioner, planarOrdering ) {\n  // Check canonical ordering\n  Ordering expected, ordering = planarOrdering(3);\n  expected +=\n      key(3, 3), key(2, 3), key(1, 3),\n      key(3, 2), key(2, 2), key(1, 2),\n      key(3, 1), key(2, 1), key(1, 1);\n  CHECK(assert_equal(expected,ordering));\n}\n\n/* ************************************************************************* */\n/** unnormalized error */\nstatic double error(const GaussianFactorGraph& fg, const VectorValues& x) {\n  double total_error = 0.;\n  for(const GaussianFactor::shared_ptr& factor: fg)\n    total_error += factor->error(x);\n  return total_error;\n}\n\n/* ************************************************************************* */\nTEST( SubgraphPreconditioner, planarGraph )\n  {\n  // Check planar graph construction\n  GaussianFactorGraph A;\n  VectorValues xtrue;\n  boost::tie(A, xtrue) = planarGraph(3);\n  LONGS_EQUAL(13,A.size());\n  LONGS_EQUAL(9,xtrue.size());\n  DOUBLES_EQUAL(0,error(A,xtrue),1e-9); // check zero error for xtrue\n\n  // Check that xtrue is optimal\n  GaussianBayesNet::shared_ptr R1 = GaussianSequentialSolver(A).eliminate();\n  VectorValues actual = optimize(*R1);\n  CHECK(assert_equal(xtrue,actual));\n}\n\n/* ************************************************************************* */\nTEST( SubgraphPreconditioner, splitOffPlanarTree )\n{\n  // Build a planar graph\n  GaussianFactorGraph A;\n  VectorValues xtrue;\n  boost::tie(A, xtrue) = planarGraph(3);\n\n  // Get the spanning tree and constraints, and check their sizes\n  GaussianFactorGraph T, C;\n  boost::tie(T, C) = splitOffPlanarTree(3, A);\n  LONGS_EQUAL(9,T.size());\n  LONGS_EQUAL(4,C.size());\n\n  // Check that the tree can be solved to give the ground xtrue\n  GaussianBayesNet::shared_ptr R1 = GaussianSequentialSolver(T).eliminate();\n  VectorValues xbar = optimize(*R1);\n  CHECK(assert_equal(xtrue,xbar));\n}\n\n/* ************************************************************************* */\n\nTEST( SubgraphPreconditioner, system )\n{\n  // Build a planar graph\n  GaussianFactorGraph Ab;\n  VectorValues xtrue;\n  size_t N = 3;\n  boost::tie(Ab, xtrue) = planarGraph(N); // A*x-b\n\n  // Get the spanning tree and corresponding ordering\n  GaussianFactorGraph Ab1_, Ab2_; // A1*x-b1 and A2*x-b2\n  boost::tie(Ab1_, Ab2_) = splitOffPlanarTree(N, Ab);\n  SubgraphPreconditioner::sharedFG Ab1(new GaussianFactorGraph(Ab1_));\n  SubgraphPreconditioner::sharedFG Ab2(new GaussianFactorGraph(Ab2_));\n\n  // Eliminate the spanning tree to build a prior\n  SubgraphPreconditioner::sharedBayesNet Rc1 = GaussianSequentialSolver(Ab1_).eliminate(); // R1*x-c1\n  VectorValues xbar = optimize(*Rc1); // xbar = inv(R1)*c1\n\n  // Create Subgraph-preconditioned system\n  VectorValues::shared_ptr xbarShared(new VectorValues(xbar)); // TODO: horrible\n  SubgraphPreconditioner system(Ab2, Rc1, xbarShared);\n\n  // Create zero config\n  VectorValues zeros = VectorValues::Zero(xbar);\n\n  // Set up y0 as all zeros\n  VectorValues y0 = zeros;\n\n  // y1 = perturbed y0\n  VectorValues y1 = zeros;\n  y1[1] = Vector2(1.0, -1.0);\n\n  // Check corresponding x  values\n  VectorValues expected_x1 = xtrue, x1 = system.x(y1);\n  expected_x1[1] = Vector2(2.01, 2.99);\n  expected_x1[0] = Vector2(3.01, 2.99);\n  CHECK(assert_equal(xtrue, system.x(y0)));\n  CHECK(assert_equal(expected_x1,system.x(y1)));\n\n  // Check errors\n  DOUBLES_EQUAL(0,error(Ab,xtrue),1e-9);\n  DOUBLES_EQUAL(3,error(Ab,x1),1e-9);\n  DOUBLES_EQUAL(0,error(system,y0),1e-9);\n  DOUBLES_EQUAL(3,error(system,y1),1e-9);\n\n  // Test gradient in x\n  VectorValues expected_gx0 = zeros;\n  VectorValues expected_gx1 = zeros;\n  CHECK(assert_equal(expected_gx0,gradient(Ab,xtrue)));\n  expected_gx1[2] = Vector2(-100., 100.);\n  expected_gx1[4] = Vector2(-100., 100.);\n  expected_gx1[1] = Vector2(200., -200.);\n  expected_gx1[3] = Vector2(-100., 100.);\n  expected_gx1[0] = Vector2(100., -100.);\n  CHECK(assert_equal(expected_gx1,gradient(Ab,x1)));\n\n  // Test gradient in y\n  VectorValues expected_gy0 = zeros;\n  VectorValues expected_gy1 = zeros;\n  expected_gy1[2] = Vector2(2., -2.);\n  expected_gy1[4] = Vector2(-2., 2.);\n  expected_gy1[1] = Vector2(3., -3.);\n  expected_gy1[3] = Vector2(-1., 1.);\n  expected_gy1[0] = Vector2(1., -1.);\n  CHECK(assert_equal(expected_gy0,gradient(system,y0)));\n  CHECK(assert_equal(expected_gy1,gradient(system,y1)));\n\n  // Check it numerically for good measure\n  // TODO use boost::bind(&SubgraphPreconditioner::error,&system,_1)\n  //  Vector numerical_g1 = numericalGradient<VectorValues> (error, y1, 0.001);\n  //  Vector expected_g1 = (Vector(18) << 0., 0., 0., 0., 2., -2., 0., 0., -2., 2.,\n  //      3., -3., 0., 0., -1., 1., 1., -1.);\n  //  CHECK(assert_equal(expected_g1,numerical_g1));\n}\n\n/* ************************************************************************* */\nTEST( SubgraphPreconditioner, conjugateGradients )\n{\n  // Build a planar graph\n  GaussianFactorGraph Ab;\n  VectorValues xtrue;\n  size_t N = 3;\n  boost::tie(Ab, xtrue) = planarGraph(N); // A*x-b\n\n  // Get the spanning tree and corresponding ordering\n  GaussianFactorGraph Ab1_, Ab2_; // A1*x-b1 and A2*x-b2\n  boost::tie(Ab1_, Ab2_) = splitOffPlanarTree(N, Ab);\n  SubgraphPreconditioner::sharedFG Ab1(new GaussianFactorGraph(Ab1_));\n  SubgraphPreconditioner::sharedFG Ab2(new GaussianFactorGraph(Ab2_));\n\n  // Eliminate the spanning tree to build a prior\n  Ordering ordering = planarOrdering(N);\n  SubgraphPreconditioner::sharedBayesNet Rc1 = GaussianSequentialSolver(Ab1_).eliminate(); // R1*x-c1\n  VectorValues xbar = optimize(*Rc1); // xbar = inv(R1)*c1\n\n  // Create Subgraph-preconditioned system\n  VectorValues::shared_ptr xbarShared(new VectorValues(xbar)); // TODO: horrible\n  SubgraphPreconditioner system(Ab2, Rc1, xbarShared);\n\n  // Create zero config y0 and perturbed config y1\n  VectorValues y0 = VectorValues::Zero(xbar);\n\n  VectorValues y1 = y0;\n  y1[1] = Vector2(1.0, -1.0);\n  VectorValues x1 = system.x(y1);\n\n  // Solve for the remaining constraints using PCG\n  ConjugateGradientParameters parameters;\n  VectorValues actual = conjugateGradients<SubgraphPreconditioner,\n      VectorValues, Errors>(system, y1, parameters);\n  CHECK(assert_equal(y0,actual));\n\n  // Compare with non preconditioned version:\n  VectorValues actual2 = conjugateGradientDescent(Ab, x1, parameters);\n  CHECK(assert_equal(xtrue,actual2,1e-4));\n}\n\n#endif\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr); }\n/* ************************************************************************* */\n", "meta": {"hexsha": "accf9a65eaa25b577050c0c6ce86bdbf92aaee8c", "size": 7759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testSubgraphPreconditioner.cpp", "max_stars_repo_name": "karamach/gtsam", "max_stars_repo_head_hexsha": "35f9b710163a1d14d8dc4fcf50b8dce6e0bf7e5b", "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/testSubgraphPreconditioner.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/testSubgraphPreconditioner.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": 34.4844444444, "max_line_length": 101, "alphanum_fraction": 0.6410619925, "num_tokens": 2180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5343799637815898}}
{"text": "// Copyright Louis Dionne 2013-2016\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/mpl/equal_to.hpp>\r\n#include <boost/mpl/int.hpp>\r\n#include <boost/mpl/integral_c.hpp>\r\n#include <boost/mpl/minus.hpp>\r\n#include <boost/mpl/multiplies.hpp>\r\n#include <boost/mpl/pair.hpp>\r\n#include <boost/mpl/plus.hpp>\r\n\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/concept/constant.hpp>\r\n#include <boost/hana/equal.hpp>\r\n#include <boost/hana/integral_constant.hpp>\r\n#include <boost/hana/minus.hpp>\r\n#include <boost/hana/mult.hpp>\r\n#include <boost/hana/pair.hpp>\r\n#include <boost/hana/plus.hpp>\r\n\r\n#include <type_traits>\r\nnamespace hana = boost::hana;\r\n\r\n\r\ntemplate <typename T, typename = std::enable_if_t<\r\n  !hana::Constant<T>::value\r\n>>\r\nconstexpr T sqrt(T x) {\r\n  T inf = 0, sup = (x == 1 ? 1 : x/2);\r\n  while (!((sup - inf) <= 1 || ((sup*sup <= x) && ((sup+1)*(sup+1) > x)))) {\r\n    T mid = (inf + sup) / 2;\r\n    bool take_inf = mid*mid > x ? 1 : 0;\r\n    inf = take_inf ? inf : mid;\r\n    sup = take_inf ? mid : sup;\r\n  }\r\n\r\n  return sup*sup <= x ? sup : inf;\r\n}\r\n\r\ntemplate <typename T, typename = std::enable_if_t<\r\n  hana::Constant<T>::value\r\n>>\r\nconstexpr auto sqrt(T const&) {\r\n  return hana::integral_c<typename T::value_type, sqrt(T::value)>;\r\n}\r\n\r\n\r\nnamespace then {\r\nnamespace mpl = boost::mpl;\r\n\r\ntemplate <typename N>\r\nstruct sqrt\r\n  : mpl::integral_c<typename N::value_type, ::sqrt(N::value)>\r\n{ };\r\n\r\ntemplate <typename X, typename Y>\r\nstruct point {\r\n  using x = X;\r\n  using y = Y;\r\n};\r\n\r\n//! [distance-mpl]\r\ntemplate <typename P1, typename P2>\r\nstruct distance {\r\n  using xs = typename mpl::minus<typename P1::x,\r\n                                 typename P2::x>::type;\r\n  using ys = typename mpl::minus<typename P1::y,\r\n                                 typename P2::y>::type;\r\n  using type = typename sqrt<\r\n    typename mpl::plus<\r\n      typename mpl::multiplies<xs, xs>::type,\r\n      typename mpl::multiplies<ys, ys>::type\r\n    >::type\r\n  >::type;\r\n};\r\n\r\nstatic_assert(mpl::equal_to<\r\n  distance<point<mpl::int_<3>, mpl::int_<5>>,\r\n           point<mpl::int_<7>, mpl::int_<2>>>::type,\r\n  mpl::int_<5>\r\n>::value, \"\");\r\n//! [distance-mpl]\r\n}\r\n\r\n\r\nnamespace now {\r\nnamespace hana = boost::hana;\r\nusing namespace hana::literals;\r\n\r\ntemplate <typename X, typename Y>\r\nstruct _point {\r\n  X x;\r\n  Y y;\r\n};\r\ntemplate <typename X, typename Y>\r\nconstexpr _point<X, Y> point(X x, Y y) { return {x, y}; }\r\n\r\n//! [distance-hana]\r\ntemplate <typename P1, typename P2>\r\nconstexpr auto distance(P1 p1, P2 p2) {\r\n  auto xs = p1.x - p2.x;\r\n  auto ys = p1.y - p2.y;\r\n  return sqrt(xs*xs + ys*ys);\r\n}\r\n\r\nBOOST_HANA_CONSTANT_CHECK(distance(point(3_c, 5_c), point(7_c, 2_c)) == 5_c);\r\n//! [distance-hana]\r\n\r\nvoid test() {\r\n\r\n//! [distance-dynamic]\r\nauto p1 = point(3, 5); // dynamic values now\r\nauto p2 = point(7, 2); //\r\nBOOST_HANA_RUNTIME_CHECK(distance(p1, p2) == 5); // same function works!\r\n//! [distance-dynamic]\r\n\r\n}\r\n}\r\n\r\n\r\nint main() {\r\n  now::test();\r\n}\r\n", "meta": {"hexsha": "0ee5bd7633766af1faad23ee24ea3b2a7d06064a", "size": 3074, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/tutorial/integral.cpp", "max_stars_repo_name": "nxplatform/nx-mobile", "max_stars_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_stars_repo_licenses": ["Apache-2.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/hana/example/tutorial/integral.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/hana/example/tutorial/integral.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": 24.592, "max_line_length": 82, "alphanum_fraction": 0.6138581653, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5343799561579475}}
{"text": "/* ScaFES\n * Copyright (c) 2011-2016, ZIH, TU Dresden, Federal Republic of Germany.\n * For details, see the files COPYING and LICENSE in the base directory\n * of the package.\n */\n\n/**\n *  @file ScaFES_Complex.hpp\n *  @brief Contains the class template Complex.\n */\n\n#ifndef SCAFES_COMPLEX_HPP_\n#define SCAFES_COMPLEX_HPP_\n\n#include <iostream>\n#include <iomanip>\n#include <ios>\n#include <cmath>\n#include <cstdlib>\n#include <type_traits>\n#include <stdexcept>\n\n#ifdef SCAFES_HAVE_BOOST\n#include <boost/version.hpp>\n#endif\n\n#ifdef SCAFES_HAVE_BOOST_SERIALIZATION\nnamespace boost\n{\nnamespace serialization\n{\n    class access;\n}\n}\n#include <boost/serialization/version.hpp>\n#if BOOST_VERSION < 105900\n    #include <boost/serialization/pfto.hpp>\n#endif\n//#include <boost/serialization/complex.hpp>\n#endif\n\nnamespace ScaFES\n{\n/*******************************************************************************\n ******************************************************************************/\n/** \\class Complex\n * @brief The class template \\c Complex represents a complex number\n * of a given type \\c TT (usually of type \\c double).\n *\n * All important unary and binary operators are implemented resp. overloaded\n * and behave as expected. Especially, many operators work componentwise.\n */\ntemplate <typename TT> class Complex\n{\npublic:\n    /*----------------------------------------------------------------------\n    | TYPE DEFINITIONS.\n    ----------------------------------------------------------------------*/\n    /** Re-export typename TT STL-like. */\n    typedef TT value_type;\n\n#ifdef SCAFES_HAVE_BOOST_SERIALIZATION\n    /*----------------------------------------------------------------------\n    | FRIEND CLASSES.\n    ----------------------------------------------------------------------*/\n    friend class boost::serialization::access;\n#endif\n\n    /*----------------------------------------------------------------------\n    | LIFE CYCLE METHODS.\n    ----------------------------------------------------------------------*/\n    /** Creates the default constructor. */\n    Complex<TT>();\n\n    /** Creates a special constructor for threedimensional vectors:\n     *  Both parts are initialized by given values. */\n    Complex<TT>(TT const&, TT const&);\n\n    /** Creates own constructor:\n     *  \\remark Only The REAL PART is initalized by the given value,\n     *  the imaginary part remains ZERO! */\n    Complex<TT>(TT const& re);\n\n    /** Creates copy constructor. */\n    Complex<TT>(ScaFES::Complex<TT> const& rhs);\n\n    /** Creates the destructor. */\n    ~Complex();\n\n    /** Creates copy assignment operator using the copy-and-swap idiom. */\n    ScaFES::Complex<TT>& operator=(ScaFES::Complex<TT> rhs);\n\n    /*----------------------------------------------------------------------\n    | GETTER METHODS.\n    ----------------------------------------------------------------------*/\n    /** Returns the real part of this complex number. */\n    const TT& real() const;\n\n    /** Returns the imaginary part of this complex number. */\n    const TT& imag() const;\n\n    /** Returns the element at position \\c idx in the complex number. */\n    const TT& operator[](std::size_t const& idx) const;\n\n    /*----------------------------------------------------------------------\n    | SETTER METHODS.\n    ----------------------------------------------------------------------*/\n    /** Returns a reference to the element at position \\c idx in the complex\n     * number.\n     */\n    TT& operator[](std::size_t const& idx);\n\n    /*----------------------------------------------------------------------\n    | COMPARISON METHODS.\n    ----------------------------------------------------------------------*/\n    /** Compares elementwise if this complex number is smaller\n     *  than a given rhs complex number. */\n    bool operator<(ScaFES::Complex<TT> const& rhs) const;\n\n    /** Compares elementwise if this complex number is greater or equal\n     *  than a a given rhs complex number. */\n    bool operator>=(ScaFES::Complex<TT> const& rhs) const;\n\n    /** Compares elementwise if this complex number is smaller or equal\n     *  than a a given rhs complex number. */\n    bool operator<=(ScaFES::Complex<TT> const& rhs) const;\n\n    /** Compares elementwise if this complex number is greater than\n     *  a given rhs complex number. */\n    bool operator>(ScaFES::Complex<TT> const& rhs) const;\n\n    /** Compares elementwise if this complex number is equal to a given rhs\n     *  complex number. */\n    bool operator==(ScaFES::Complex<TT> const& rhs) const;\n\n    /** Compares elementwise if this complex number is unequal to\n     * a given rhs complex number. */\n    bool operator!=(ScaFES::Complex<TT> const& rhs) const;\n\n    /*----------------------------------------------------------------------\n    | WORK METHODS\n    ----------------------------------------------------------------------*/\n    /** Computes the dimension of the complex number,\n     * i.e., all elements will be multiplied.\n     */\n    TT size() const;\n\n    /** Returns the absolute value. */\n    double fabs() const;\n\n#ifdef SCAFES_HAVE_BOOST_SERIALIZATION\n    /** Serializes this class. */\n    template <class Archive>\n    void serialize(Archive& ar, unsigned int const version);\n#endif\n\n    /*----------------------------------------------------------------------\n    | ARITHMETIC METHODS.\n    ----------------------------------------------------------------------*/\n    /** Creates an assignment operator.\n     * Only the REAL part will be assigned to the given scalar.\n     */\n    ScaFES::Complex<TT>& operator=(TT const& re);\n\n    /** Computes the additive inverse of this complex number. */\n    ScaFES::Complex<TT>& operator-();\n\n    /** Adds this complex number to a given scalar (elementwise). */\n    ScaFES::Complex<TT>& operator+=(TT const& sca);\n\n    /** Subtracts this complex number from a given scalar (elementwise). */\n    ScaFES::Complex<TT>& operator-=(TT const& sca);\n\n    /** Multiplies this complex number by a given scalar (elementwise). */\n    ScaFES::Complex<TT>& operator*=(TT const& sca);\n\n    /** Divides this complex number by a given scalar (elementwise). */\n    ScaFES::Complex<TT>& operator/=(TT const& sca);\n\n    /** Adds a given rhs complex number to this complex number. */\n    ScaFES::Complex<TT>& operator+=(ScaFES::Complex<TT> const& rhs);\n\n    /** Subtracts a given rhs complex number from this complex number. */\n    ScaFES::Complex<TT>& operator-=(ScaFES::Complex<TT> const& rhs);\n\n    /** Multiplies this complex number by a given rhs complex number. */\n    ScaFES::Complex<TT>& operator*=(ScaFES::Complex<TT> const& rhs);\n\n    /** Divides this complex number by a given rhs complex number. */\n    ScaFES::Complex<TT>& operator/=(ScaFES::Complex<TT> const& rhs);\n\n    /*----------------------------------------------------------------------\n    | FREE METHODS WHICH ARE FRIENDS OF THIS CLASS.\n    ----------------------------------------------------------------------*/\n    /** Prints a complex number in the way: '(re, im})'. */\n    template <typename RR>\n    friend std::ostream& operator<<(std::ostream& output,\n                                    ScaFES::Complex<RR> const& t);\n\n    /** Method to swap two complex numbers. */\n    template <typename RR>\n    friend void swap(ScaFES::Complex<RR>& first, ScaFES::Complex<RR>& second);\n\nprivate:\n    /*----------------------------------------------------------------------\n    | MEMBER VARIABLES.\n    ----------------------------------------------------------------------*/\n    /** Real part of complex number. */\n    TT mReal;\n\n    /** Imaginary part of complex number. */\n    TT mImag;\n}; // End of class //\n\n/*******************************************************************************\n * FREE METHODS.\n ******************************************************************************/\n/** Swaps two objects of the class \\c Complex. */\ntemplate <typename TT>\nvoid swap(ScaFES::Complex<TT>& first, ScaFES::Complex<TT>& second);\n/*----------------------------------------------------------------------------*/\n/** Preprares writing a complex number to output. */\ntemplate <typename TT>\nstd::ostream& operator<<(std::ostream& output, ScaFES::Complex<TT> const& rhs);\n\n/*******************************************************************************\n * LIFE CYCLE METHODS.\n ******************************************************************************/\ntemplate <typename TT>\ninline Complex<TT>::Complex()\n: mReal(static_cast<TT>(0)), mImag(static_cast<TT>(0))\n{\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline Complex<TT>::Complex(TT const& re, TT const& im)\n: mReal(re), mImag(im)\n{\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline Complex<TT>::Complex(TT const& re)\n: mReal(re), mImag(static_cast<TT>(0))\n{\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline ScaFES::Complex<TT>& Complex<TT>::operator=(ScaFES::Complex<TT> rhs)\n{\n    swap(*this, rhs);\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline Complex<TT>::Complex(ScaFES::Complex<TT> const& rhs)\n: mReal(rhs.real()), mImag(rhs.imag())\n{\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT> inline Complex<TT>::~Complex()\n{\n}\n\n/*******************************************************************************\n * GETTER METHODS.\n ******************************************************************************/\ntemplate <typename TT> inline const TT& Complex<TT>::real() const\n{\n    return this->mReal;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT> inline const TT& Complex<TT>::imag() const\n{\n    return this->mImag;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline const TT& Complex<TT>::operator[](std::size_t const& position) const\n{\n    if (0 == position)\n    {\n        return this->mReal;\n    }\n    else\n    {\n        return this->mImag;\n    }\n}\n\n/*******************************************************************************\n * SETTER METHODS.\n ******************************************************************************/\ntemplate <typename TT>\ninline TT& Complex<TT>::operator[](std::size_t const& pos)\n{\n    return const_cast<TT&>(static_cast<const ScaFES::Complex<TT>&>(*this)[pos]);\n}\n\n/*******************************************************************************\n * WORK METHODS.\n ******************************************************************************/\ntemplate <typename TT> inline TT Complex<TT>::size() const\n{\n    return (this->mReal * this->mImag);\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT> inline double Complex<TT>::fabs() const\n{\n    return (this->mReal * this->mReal + this->mImag * this->mImag);\n}\n#ifdef SCAFES_HAVE_BOOST_SERIALIZATION\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ntemplate <class Archive>\ninline void Complex<TT>::serialize(Archive& ar, unsigned int const version)\n{\n    if (1 <= version)\n    {\n        ar&(this->mReal);\n        ar&(this->mImag);\n    }\n}\n#endif\n/*******************************************************************************\n * ARITHMETIC METHODS.\n ******************************************************************************/\ntemplate <typename TT> inline ScaFES::Complex<TT>& Complex<TT>::operator-()\n{\n    this->mReal *= static_cast<TT>(-1);\n    this->mImag *= static_cast<TT>(-1);\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline ScaFES::Complex<TT>& Complex<TT>::operator=(TT const& sca)\n{\n    this->mReal = sca;\n    this->mImag = sca;\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline ScaFES::Complex<TT>& Complex<TT>::operator+=(TT const& sca)\n{\n    this->mReal += sca;\n    this->mImag += sca;\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline ScaFES::Complex<TT>& Complex<TT>::operator-=(TT const& sca)\n{\n    this->mReal -= sca;\n    this->mImag -= sca;\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline ScaFES::Complex<TT>& Complex<TT>::operator*=(TT const& sca)\n{\n    this->mReal *= sca;\n    this->mImag *= sca;\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\n// TODO: Throw an exception if the given scalar is near to zero.\ntemplate <typename TT>\ninline ScaFES::Complex<TT>& Complex<TT>::operator/=(TT const& sca)\n{\n    this->mReal /= sca;\n    this->mImag /= sca;\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline ScaFES::Complex<TT>& Complex<TT>::\noperator+=(ScaFES::Complex<TT> const& rhs)\n{\n    this->mReal += rhs.real();\n    this->mImag += rhs.imag();\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline ScaFES::Complex<TT>& Complex<TT>::\noperator-=(ScaFES::Complex<TT> const& rhs)\n{\n    this->mReal -= rhs.real();\n    this->mImag -= rhs.imag();\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline ScaFES::Complex<TT>& Complex<TT>::\noperator*=(ScaFES::Complex<TT> const& rhs)\n{\n    const TT tmpRe = this->mReal * rhs.real() - this->mImag * rhs.imag();\n    this->mReal = tmpRe;\n    const TT tmpIm = this->mReal * rhs.imag() + this->mImag * rhs.real();\n    this->mImag = tmpIm;\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline ScaFES::Complex<TT>& Complex<TT>::\noperator/=(ScaFES::Complex<TT> const& rhs)\n{\n    const TT denom = rhs.imag() * rhs.imag() + rhs.real() * rhs.real();\n    if (::fabs(denom) < 2.2e-12)\n    {\n        throw std::runtime_error(\"Denominator is very near to zero.\");\n    }\n    const TT tmpRe =\n        (this->mReal * rhs.real() + this->mImag * rhs.imag()) / denom;\n    this->mReal = tmpRe;\n    const TT tmpIm =\n        (this->mImag * rhs.real() - this->mReal * rhs.imag()) / denom;\n    this->mImag = tmpIm;\n    return *this;\n}\n\n/*******************************************************************************\n * COMPARISON METHODS.\n ******************************************************************************/\ntemplate <typename TT>\ninline bool Complex<TT>::operator==(ScaFES::Complex<TT> const& rhs) const\n{\n    bool res = true;\n\n    if (!(::fabs(this->mReal - rhs.real()) < 2.2e-15))\n    {\n        res = false;\n    }\n\n    if (!(::fabs(this->mImag - rhs.imag()) < 2.2e-15))\n    {\n        res = false;\n    }\n\n    return res;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline bool Complex<TT>::operator!=(ScaFES::Complex<TT> const& rhs) const\n{\n    return !(*this == rhs);\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline bool Complex<TT>::operator<(ScaFES::Complex<TT> const& rhs) const\n{\n    bool res = true;\n\n    if (!(this->mReal < rhs.real()))\n    {\n        res = false;\n    }\n\n    if (!(this->mImag < rhs.imag()))\n    {\n        res = false;\n    }\n\n    return res;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline bool Complex<TT>::operator<=(ScaFES::Complex<TT> const& rhs) const\n{\n    bool res = true;\n\n    if ((this->mReal > rhs.real()))\n    {\n        res = false;\n    }\n\n    if ((this->mImag > rhs.imag()))\n    {\n        res = false;\n    }\n\n    return res;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline bool Complex<TT>::operator>=(ScaFES::Complex<TT> const& rhs) const\n{\n    bool res = true;\n\n    if ((this->mReal < rhs.real()))\n    {\n        res = false;\n    }\n\n    if ((this->mImag < rhs.imag()))\n    {\n        res = false;\n    }\n\n    return res;\n    // return !(*this < rhs); Does not work because we are working elementwise!\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline bool Complex<TT>::operator>(ScaFES::Complex<TT> const& rhs) const\n{\n    bool res = true;\n\n    if (!(mReal > rhs.real()))\n    {\n        res = false;\n    }\n\n    if (!(this->mImag > rhs.imag()))\n    {\n        res = false;\n    }\n\n    return res;\n    // return !(*this <= rhs); Does not work because we are working elementwise!\n}\n\n/*******************************************************************************\n * FREE METHODS WHICH ARE FRIENDS OF THIS CLASS.\n ******************************************************************************/\ntemplate <typename TT>\ninline void swap(ScaFES::Complex<TT>& first, ScaFES::Complex<TT>& second)\n{\n    std::swap(first.mReal, second.mReal);\n    std::swap(first.mImag, second.mImag);\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT>\ninline std::ostream& operator<<(std::ostream& output,\n                                ScaFES::Complex<TT> const& rhs)\n{\n    const TT EPSILON = static_cast<TT>(2.2e-12);\n\n    if (fabs(rhs.real()) < EPSILON)\n    {\n        output << \"[    0,\";\n    }\n    else\n    {\n        output << \"[\" << ::std::setw(4) << ::std::right << rhs.real() << \";\";\n    }\n\n    if (fabs(rhs.imag()) < EPSILON)\n    {\n        output << \"    0i]\";\n    }\n    else\n    {\n        output << ::std::setw(4) << ::std::right << rhs.imag() << \"i]\";\n    }\n\n    return output;\n}\n\n} // End of namespace. //\n\n/*******************************************************************************\n ******************************************************************************/\n#ifdef SCAFES_HAVE_BOOST_SERIALIZATION\nnamespace boost\n{\nnamespace serialization\n{\n    /** Designed to set the boost serialization version of a class template. */\n    template <typename TT> struct version<ScaFES::Complex<TT>>\n    {\n        /** Sets the version number for serialization. */\n        BOOST_STATIC_CONSTANT(unsigned long int, value = 2);\n    };\n}\n}\n#endif\n\n#endif\n", "meta": {"hexsha": "d500944ed6e3a356a00406c85bb4a4c8d8c2f441", "size": 18528, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ScaFES_Complex.hpp", "max_stars_repo_name": "nih23/MRIDrivenHeatSimulation", "max_stars_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "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": "src/ScaFES_Complex.hpp", "max_issues_repo_name": "nih23/MRIDrivenHeatSimulation", "max_issues_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "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": "src/ScaFES_Complex.hpp", "max_forks_repo_name": "nih23/MRIDrivenHeatSimulation", "max_forks_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9448275862, "max_line_length": 80, "alphanum_fraction": 0.4581714162, "num_tokens": 3831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.5343799390594335}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n  Array22f m;\n  m << 1, 2,\n      3, 4;\n  Array44f a = Array44f::Constant(0.6);\n  cout << \"Here is the array a:\" << endl << a << endl << endl;\n  a.block<2, 2>(1, 1) = m;\n  cout << \"Here is now a with m copied into its central 2x2 block:\" << endl << a << endl << endl;\n  a.block(0, 0, 2, 3) = a.block(2, 1, 2, 3);\n  cout << \"Here is now a with bottom-right 2x3 block copied into top-left 2x2 block:\" << endl << a << endl << endl;\n}\n", "meta": {"hexsha": "3e51a19d75cfc3a16926e3c023601b8f882a2016", "size": 532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen-3.3/doc/examples/Tutorial_BlockOperations_block_assignment.cpp", "max_stars_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_stars_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Eigen-3.3/doc/examples/Tutorial_BlockOperations_block_assignment.cpp", "max_issues_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_issues_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Eigen-3.3/doc/examples/Tutorial_BlockOperations_block_assignment.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": 29.5555555556, "max_line_length": 115, "alphanum_fraction": 0.5902255639, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5343799372082038}}
{"text": "#define NDEBUG\n#include \"ETL.h\"\n\n#include <iostream>\n#include <string>\n#include <Eigen/Dense>\n#include <boost/algorithm/string.hpp>\n\n#include <vector>\n\nint main(int argc, char *argv[]) {\n\tETL etl(argv[1], argv[2], argv[3]); \n\n\tvector<vector<string>> dataset = etl.readCSV();\n\tint rows = dataset.size(); \n\tint cols = dataset[0].size(); \n  \n\tEigen::MatrixXd dataMat = etl.CSVtoEigen(dataset,rows,cols);\n\n\tcout << dataMat << endl; \n\treturn EXIT_SUCCESS; \n}\n\n", "meta": {"hexsha": "5edc510adae668dcedd0a87e13c5bfbd2faa6cab", "size": 455, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C/C++/main.cpp", "max_stars_repo_name": "arcelioeperez/arcelioeperez", "max_stars_repo_head_hexsha": "105775426e018c0d07238a78a7ceaef29cc715ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-10-31T17:30:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T02:29:15.000Z", "max_issues_repo_path": "C/C++/main.cpp", "max_issues_repo_name": "arcelioeperez/arcelioeperez", "max_issues_repo_head_hexsha": "105775426e018c0d07238a78a7ceaef29cc715ed", "max_issues_repo_licenses": ["MIT"], "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/C++/main.cpp", "max_forks_repo_name": "arcelioeperez/arcelioeperez", "max_forks_repo_head_hexsha": "105775426e018c0d07238a78a7ceaef29cc715ed", "max_forks_repo_licenses": ["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.9583333333, "max_line_length": 61, "alphanum_fraction": 0.6747252747, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5343799372082038}}
{"text": "// OptionData.hpp\n//\n// Encapsulate option data.\n//\n// (C) Datasim Education BV 2008-2016\n\n#ifndef OptionData_HPP\n#define OptionData_HPP\n#include <iostream>\n#include <algorithm> // for max()\n#include <boost/parameter.hpp>\n\nnamespace OptionParams\n{\n\t\n\t\tBOOST_PARAMETER_KEYWORD(Tag, strike)\n\t\tBOOST_PARAMETER_KEYWORD(Tag, expiration)\n\t\tBOOST_PARAMETER_KEYWORD(Tag, interestRate)\n\t\tBOOST_PARAMETER_KEYWORD(Tag, volatility)\n\t\tBOOST_PARAMETER_KEYWORD(Tag, dividend)\n\t\tBOOST_PARAMETER_KEYWORD(Tag, optionType)\n\t\tBOOST_PARAMETER_KEYWORD(Tag, Stockprice)\n\t\tBOOST_PARAMETER_KEYWORD(Tag, Beta)\n\t\tBOOST_PARAMETER_KEYWORD(Tag, Barrier)\n\t\tBOOST_PARAMETER_KEYWORD(Tag, Rebate)\n}\n\n// Encapsulate all data in one place\nstruct OptionData\n{ // Option data + behaviour\n\tdouble S; //Stockprice\n\tdouble K;\t//Strike price\n\tdouble T;\t//Time to expiration \n\tdouble r;\t//interest rate \n\tdouble sig;\t//Volatility\n\tdouble l;\t\n\t// Extra data\n\tdouble D;\t\t// dividend\n\tdouble beta;\t//Beta\n\tdouble rebate;\t//Rebate \n\tint type;\t\t// 1 == call, -1 == put\n\tOptionData() : S(0.0), K(0.0), T(0.0), r(0.0), sig(0.0), D(0.0), beta(0.0), l(0.0), rebate(0.0), type(-1)\n\t{\n\t}\n\texplicit constexpr OptionData(double strike, double expiration, double interestRate,\n\t\tdouble volatility, double dividend, double b, double StockPrice, double barrier, double rebate, int PC)\n\t\t: K(strike), T(expiration), r(interestRate), sig(volatility), S(StockPrice), D(dividend), beta(b), l(barrier), rebate(rebate), type(PC)\n\t{}\n\t//The best way to instantiate the Optiondat class. Use Named parameter idiom to instantiate the optiondata\n\ttemplate <typename ArgPack> OptionData(const ArgPack& args)\n\t{\n\t\tK = args[OptionParams::strike];\n\t\tT = args[OptionParams::expiration];\n\t\tr = args[OptionParams::interestRate];\n\t\tsig = args[OptionParams::volatility];\n\t\tD = args[OptionParams::dividend];\n\t\ttype = args[OptionParams::optionType];\n\t\tbeta = args[OptionParams::Beta];\n\t\tS = args[OptionParams::Stockprice];\n\t\tl = args[OptionParams::Barrier];\n\t\trebate = args[OptionParams::Rebate];\n\t}\n};\n\n#endif", "meta": {"hexsha": "71ca9214eb761e27b16dd78c36e0a46a4d218694", "size": 2029, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "OptionData.hpp", "max_stars_repo_name": "jetpotion/MonteCarloOptionPricer", "max_stars_repo_head_hexsha": "0024c9c900d1c968fca8946aa438ba07453272d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-13T00:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T00:40:33.000Z", "max_issues_repo_path": "OptionData.hpp", "max_issues_repo_name": "jetpotion/MonteCarloOptionPricer", "max_issues_repo_head_hexsha": "0024c9c900d1c968fca8946aa438ba07453272d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OptionData.hpp", "max_forks_repo_name": "jetpotion/MonteCarloOptionPricer", "max_forks_repo_head_hexsha": "0024c9c900d1c968fca8946aa438ba07453272d8", "max_forks_repo_licenses": ["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.2153846154, "max_line_length": 137, "alphanum_fraction": 0.7269590931, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639792, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5343440496933674}}
{"text": "\n// solving A * X = B\n// A symmetric in packed format \n// sytrf() & sytrs() \n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/lapack/computational/sptrf.hpp>\n#include <boost/numeric/bindings/lapack/computational/sptri.hpp>\n#include <boost/numeric/bindings/lapack/computational/sptrs.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/symmetric.hpp>\n#include <boost/numeric/bindings/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<real_t, ublas::column_major> m_t;\ntypedef ublas::matrix<cmplx_t, ublas::column_major> cm_t;\n\ntypedef \n  ublas::symmetric_matrix<real_t, ublas::lower, ublas::column_major> symml_t; \ntypedef \n  ublas::symmetric_matrix<cmplx_t, ublas::lower, ublas::column_major> csymml_t;\n\ntypedef \n  ublas::symmetric_matrix<real_t, ublas::upper, ublas::column_major> symmu_t; \ntypedef \n  ublas::symmetric_matrix<cmplx_t, ublas::upper, ublas::column_major> csymmu_t;\n\n\ntemplate <typename M>\nvoid init_symm2 (M& m) {\n  for (int i = 0; i < m.size1(); ++i) \n    for (int j = i; j < m.size1(); ++j)\n      m (i, j) = m (j, i) = 1 + j - i; \n}\n\nint main (int argc, char **argv) {\n  size_t n = 0;\n  if (argc > 1) {\n    n = atoi(argv [1]);\n  }\n\n  cout << endl; \n\n  cout << \"real symmetric\\n\" << endl; \n\n  if (n <= 0) {\n    cout << \"n -> \";\n    cin >> n;\n  }\n  if (n < 5) n = 5; \n  cout << \"min n = 5\" << endl << endl; \n  size_t nrhs = 2; \n  symml_t sal (n, n);   // symmetric matrix\n  symmu_t sau (n, n);   // symmetric matrix\n  m_t x (n, nrhs);\n  m_t bl (n, nrhs), bu (n, nrhs);  // RHS matrices\n\n  init_symm2 (sal); \n  print_m (sal, \"sal\"); \n  cout << endl; \n\n  init_symm2 (sau); \n  print_m (sau, \"sau\"); \n  cout << endl; \n\n  for (int i = 0; i < x.size1(); ++i) {\n    x (i, 0) = 1.;\n    x (i, 1) = 2.; \n  }\n  bl = prod (sal, x); \n  bu = prod (sau, x); \n\n  print_m (bl, \"bl\"); \n  cout << endl; \n  print_m (bu, \"bu\"); \n  cout << endl; \n\n  std::vector<fortran_int_t> ipiv (n); \n  \n  int err = lapack::sptrf (sal, ipiv);  \n  if (err == 0) {\n    symml_t isal (sal);\n    lapack::sptrs (sal, ipiv, bl); \n    print_m (bl, \"xl\"); \n    lapack::sptri (isal, ipiv);\n    print_m (isal, \"isal\"); \n  } \n  cout << endl; \n\n  err = lapack::sptrf (sau, ipiv);  \n  if (err == 0) {\n    symmu_t isau (sau);\n    lapack::sptrs (sau, ipiv, bu); \n    print_m (bu, \"xu\"); \n    lapack::sptri (isau, ipiv);\n    print_m (isau, \"isau\"); \n  } \n  else \n    cout << \"?\" << endl; \n  cout << endl; \n\n  //////////////////////////////////////////////////////////\n  cout << \"\\n==========================================\\n\" << endl; \n  cout << \"complex symmetric\\n\" << endl; \n\n  csymml_t scal (n, n);   // symmetric matrix \n  csymmu_t scau (n, n);   // symmetric matrix\n  cm_t cx (n, 1); \n  cm_t cbl (n, 1), cbu (n, 1);  // RHS\n\n  init_symm2 (scal); \n  init_symm2 (scau); \n  scal *= cmplx_t (0.1, 0.25); \n  scau *= cmplx_t (-1, -0.5); \n\n  print_m (scal, \"scal\"); \n  cout << endl; \n  print_m (scau, \"scau\"); \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 (scal, cx);\n  cbu = prod (scau, cx);\n  print_m (cbl, \"cbl\"); \n  cout << endl; \n  print_m (cbu, \"cbu\"); \n  cout << endl; \n\n  int ierr = lapack::sptrf (scal, ipiv); \n  if (ierr == 0) {\n    csymml_t iscal (scal);\n    lapack::sptrs (scal, ipiv, cbl); \n    print_m (cbl, \"cxl\"); \n    lapack::sptri (iscal, ipiv);\n    print_m (iscal, \"iscal\"); \n  }\n  else \n    cout << \"?\" << endl;\n  cout << endl; \n\n  ierr = lapack::sptrf (scau, ipiv); \n  if (ierr == 0) {\n    csymmu_t iscau (scau);\n    lapack::sptrs (scau, ipiv, cbu); \n    print_m (cbu, \"cxu\"); \n    lapack::sptri (iscau, ipiv);\n    print_m (iscau, \"iscau\"); \n  }\n  else \n    cout << \"?\" << endl;\n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "ff8c567113b7133c2a7aee7db6cf0906640c9edb", "size": 4010, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_sptrf_sptrs.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_sptrf_sptrs.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_sptrf_sptrs.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": 23.4502923977, "max_line_length": 79, "alphanum_fraction": 0.5613466334, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.534224856097102}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    double                array[][5]= {{1., 2., 3., 4., 5.}, {4., 5., 6., 7., 8.}, \n\t\t\t\t       {7., 8., 9., 8., 7.}, {6., 5., 4., 3., 2.}};\n    dense2D<double>       A(array), B;\n    compressed2D<double>  T;\n\n    B= bands(A, 1, 3);\n    std::cout << \"\\nbands(A, 1, 3) = \\n\" << B;\n\n    T= bands(A, -1, 2);\n    std::cout << \"\\ntri_diagonal(A):= bands(A, -1, 2) = \\n\" << T;\n        \n    return 0;\n}\n", "meta": {"hexsha": "e5ae2907297b275b904dad208b385e8d9dba04e3", "size": 503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/bands.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/bands.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/bands.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.9523809524, "max_line_length": 83, "alphanum_fraction": 0.435387674, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.534224856097102}}
{"text": "/* test_non_central_chi_squared.cpp\n *\n * Copyright Steven Watanabe 2011\n * Copyright Thijs van den Berg 2014\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$\n *\n */\n \n#include <boost/random/non_central_chi_squared_distribution.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/math/distributions/non_central_chi_squared.hpp>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::non_central_chi_squared_distribution<>\n#define BOOST_RANDOM_DISTRIBUTION_NAME non_central_chi_squared\n#define BOOST_MATH_DISTRIBUTION boost::math::non_central_chi_squared\n#define BOOST_RANDOM_ARG1_TYPE double\n#define BOOST_RANDOM_ARG1_NAME k\n#define BOOST_RANDOM_ARG1_DEFAULT 1000.0\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(k) boost::uniform_real<>(0.00001, k)\n#define BOOST_RANDOM_ARG2_TYPE double\n#define BOOST_RANDOM_ARG2_NAME lambda\n#define BOOST_RANDOM_ARG2_DEFAULT 1000.0\n#define BOOST_RANDOM_ARG2_DISTRIBUTION(lambda) boost::uniform_real<>(0.00001, lambda)\n\n#include \"test_real_distribution.ipp\"\n", "meta": {"hexsha": "914b7752ec5d876375265816fbe11405c9f0f570", "size": 1107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/random/test/test_non_central_chi_squared.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/random/test/test_non_central_chi_squared.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/random/test/test_non_central_chi_squared.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": 36.9, "max_line_length": 87, "alphanum_fraction": 0.8274616079, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5342248529100478}}
{"text": "#include <iostream>\n#include <vector>\n#include <map>\n#include <numeric>\n\n#include <Eigen/Dense>\n\nusing HouseProperties = std::map<std::string, double>;\n\nstruct House\n{\n    double price;\n\n    HouseProperties properties;\n};\n\nstruct Model\n{\n    double constant;\n    std::map<std::string, double> coefs;\n\n    Model() : constant(0.), coefs() {}\n};\n\nint main()\n{\n    std::cout << \"Linear regression example\\n\";\n\n    //selling price of houses\n    //from: http://people.sc.fsu.edu/~jburkardt/datasets/regression/x26.txt\n    std::vector<House> houses_data_set {\n        { 25.9,{ { \"bathroom\",1.0 },{ \"area\", 3.4720 },{ \"livingArea\", 0.998 },{ \"garage\", 1.0 },{ \"room\",  7. },{ \"bedroom\", 4. },{ \"age\", 42. } } },\n        { 29.5,{ { \"bathroom\",1.0 },{ \"area\", 3.5310 },{ \"livingArea\", 1.500 },{ \"garage\", 2.0 },{ \"room\",  7. },{ \"bedroom\", 4. },{ \"age\", 62. } } },\n        { 27.9,{ { \"bathroom\",1.0 },{ \"area\", 2.2750 },{ \"livingArea\", 1.175 },{ \"garage\", 1.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 40. } } },\n        { 25.9,{ { \"bathroom\",1.0 },{ \"area\", 4.0500 },{ \"livingArea\", 1.232 },{ \"garage\", 1.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 54. } } },\n        { 29.9,{ { \"bathroom\",1.0 },{ \"area\", 4.4550 },{ \"livingArea\", 1.121 },{ \"garage\", 1.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 42. } } },\n        { 29.9,{ { \"bathroom\",1.0 },{ \"area\", 4.4550 },{ \"livingArea\", 0.988 },{ \"garage\", 1.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 56. } } },\n        { 30.9,{ { \"bathroom\",1.0 },{ \"area\", 5.8500 },{ \"livingArea\", 1.240 },{ \"garage\", 1.0 },{ \"room\",  7. },{ \"bedroom\", 3. },{ \"age\", 51. } } },\n        { 28.9,{ { \"bathroom\",1.0 },{ \"area\", 9.5200 },{ \"livingArea\", 1.501 },{ \"garage\", 0.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 32. } } },\n        { 84.9,{ { \"bathroom\",2.5 },{ \"area\", 9.8000 },{ \"livingArea\", 3.420 },{ \"garage\", 2.0 },{ \"room\", 10. },{ \"bedroom\", 5. },{ \"age\", 42. } } },\n        { 82.9,{ { \"bathroom\",2.5 },{ \"area\",12.8000 },{ \"livingArea\", 3.000 },{ \"garage\", 2.0 },{ \"room\",  9. },{ \"bedroom\", 5. },{ \"age\", 14. } } },\n        { 35.9,{ { \"bathroom\",1.0 },{ \"area\", 6.4350 },{ \"livingArea\", 1.225 },{ \"garage\", 2.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 32. } } },\n        { 31.5,{ { \"bathroom\",1.0 },{ \"area\", 4.9883 },{ \"livingArea\", 1.552 },{ \"garage\", 1.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 30. } } },\n        { 31.0,{ { \"bathroom\",1.0 },{ \"area\", 5.5200 },{ \"livingArea\", 0.975 },{ \"garage\", 1.0 },{ \"room\",  5. },{ \"bedroom\", 2. },{ \"age\", 30. } } },\n        { 30.9,{ { \"bathroom\",1.0 },{ \"area\", 6.6660 },{ \"livingArea\", 1.121 },{ \"garage\", 2.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 32. } } },\n        { 30.0,{ { \"bathroom\",1.0 },{ \"area\", 5.0000 },{ \"livingArea\", 1.020 },{ \"garage\", 0.0 },{ \"room\",  5. },{ \"bedroom\", 2. },{ \"age\", 46. } } },\n        { 28.9,{ { \"bathroom\",1.0 },{ \"area\", 9.5200 },{ \"livingArea\", 1.501 },{ \"garage\", 0.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 32. } } },\n        { 36.9,{ { \"bathroom\",1.5 },{ \"area\", 5.1500 },{ \"livingArea\", 1.664 },{ \"garage\", 2.0 },{ \"room\",  8. },{ \"bedroom\", 4. },{ \"age\", 50. } } },\n        { 41.9,{ { \"bathroom\",1.5 },{ \"area\", 6.9020 },{ \"livingArea\", 1.488 },{ \"garage\", 1.5 },{ \"room\",  7. },{ \"bedroom\", 3. },{ \"age\", 22. } } },\n        { 40.5,{ { \"bathroom\",1.5 },{ \"area\", 7.1020 },{ \"livingArea\", 1.376 },{ \"garage\", 1.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 17. } } },\n        { 43.9,{ { \"bathroom\",1.0 },{ \"area\", 7.8000 },{ \"livingArea\", 1.500 },{ \"garage\", 1.5 },{ \"room\",  7. },{ \"bedroom\", 3. },{ \"age\", 23. } } },\n        { 37.5,{ { \"bathroom\",1.0 },{ \"area\", 5.5200 },{ \"livingArea\", 1.256 },{ \"garage\", 2.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 40. } } },\n        { 37.9,{ { \"bathroom\",1.5 },{ \"area\", 4.0000 },{ \"livingArea\", 1.690 },{ \"garage\", 1.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 22. } } },\n        { 44.5,{ { \"bathroom\",1.5 },{ \"area\", 9.8900 },{ \"livingArea\", 1.820 },{ \"garage\", 2.0 },{ \"room\",  8. },{ \"bedroom\", 4. },{ \"age\", 50. } } },\n        { 37.9,{ { \"bathroom\",1.5 },{ \"area\", 6.7265 },{ \"livingArea\", 1.652 },{ \"garage\", 1.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 44. } } },\n        { 38.9,{ { \"bathroom\",1.5 },{ \"area\", 9.1500 },{ \"livingArea\", 1.777 },{ \"garage\", 2.0 },{ \"room\",  8. },{ \"bedroom\", 4. },{ \"age\", 48. } } },\n        { 36.9,{ { \"bathroom\",1.0 },{ \"area\", 8.0000 },{ \"livingArea\", 1.504 },{ \"garage\", 2.0 },{ \"room\",  7. },{ \"bedroom\", 3. },{ \"age\",  3. } } },\n        { 45.8,{ { \"bathroom\",1.5 },{ \"area\", 7.3262 },{ \"livingArea\", 1.831 },{ \"garage\", 1.5 },{ \"room\",  8. },{ \"bedroom\", 4. },{ \"age\", 31. } } }\n        //this observation is not added to the list\n        //it will be used to test the linear model\n        //{ 41.0,{ { \"bathroom\",1.5 },{ \"area\", 5.0000 },{ \"livingArea\", 1.200 },{ \"garage\", 2.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 30. } } }\n    };\n\n    std::cout << houses_data_set.size() << \" observations\\n\";\n\n    //function to evaluate the price of a house knowing its properties and using a linear model\n    const auto evaluatePrice = [&](const Model& model, const HouseProperties& house)\n    {\n        double price = model.constant;\n\n        for (const auto& c : model.coefs)\n        {\n            auto hIt = house.find(c.first);\n            if (hIt != house.end())\n            {\n                price += c.second * hIt->second;\n            }\n        }\n        return price;\n    };\n\n    //function to evaluate the error of a model based on the training data\n    const auto evaluateError = [&houses_data_set, &evaluatePrice](const Model& model)\n    {\n        double error = 0.;\n        for (const auto& d : houses_data_set)\n        {\n            const auto p = evaluatePrice(model, d.properties);\n            error += std::pow(d.price - p, 2);\n        }\n        return error / static_cast<double>(houses_data_set.size());\n    };\n\n    //consider a model\n    Model model; //the model is empty\n    model.constant = 3.; //a constant is set\n    model.coefs[\"room\"] = 1.; //a coefficient is set for the \"room\" property\n    std::cout << \"Error: \" << evaluateError(model) << '\\n'; //the error of the model is printed\n\n    //definition of the predictors\n    std::vector<std::string> variables{ \"bathroom\", \"area\", \"livingArea\", \"garage\", \"room\", \"bedroom\", \"age\" };\n\n    //definition of the design matrix\n    Eigen::MatrixXd X(houses_data_set.size(), variables.size() + 1);\n    //definition of the observation vector\n    Eigen::VectorXd Y(houses_data_set.size());\n\n    int i = 0;\n    for (const auto& d : houses_data_set)\n    {\n        int j = 0;\n        //the first line of the matrix is set to 1 to compute the constant term of the linear model\n        X(i, j++) = 1.;\n\n        for (const auto& var : variables)\n        {\n            auto pIt = d.properties.find(var);\n            if (pIt != d.properties.end())\n                X(i, j) = pIt->second;\n            j++;\n        }\n\n        Y(i) = d.price;\n        ++i;\n    }\n    \n    //solving the normal equation\n    const Eigen::VectorXd B = (X.transpose() * X).ldlt().solve(X.transpose() * Y);\n\n    i = 0;\n\n    //convert the computation result into the model data structure\n    model.constant = B(i++);\n    std::cout << \"Model constant: \" << model.constant << '\\n';\n    model.coefs.clear();\n    for (const auto& var : variables)\n    {\n        model.coefs[var] = B(i++);\n        std::cout << \"Model (\" << var << \"): \" << model.coefs[var] << '\\n';\n    }\n\n    //compute the mean price of the observation data\n    double meanPrice = std::accumulate(std::begin(houses_data_set), std::end(houses_data_set), 0.,\n        [](double a, const House& h) {return a + h.price; }) / static_cast<double>(houses_data_set.size());\n    \n    std::cout << \"Mean price: \" << meanPrice << '\\n';\n\n    //compute the residual error of the model considering the observation data\n    double ssres = evaluateError(model);\n    std::cout << \"Residual: \" << ssres << '\\n';\n\n    //compute the total sum of squares (compared to the mean price)\n    double sstot = std::accumulate(std::begin(houses_data_set), std::end(houses_data_set), 0.,\n        [&meanPrice](double a, const House& h) {return a + std::pow(h.price - meanPrice, 2); }) / static_cast<double>(houses_data_set.size());\n    std::cout << \"Total sum of squares: \" << sstot << '\\n';\n\n    //compute the coefficient of determination\n    double rSquared = 1. - ssres / sstot;\n    std::cout << \"Coefficient of determination R^2: \" << rSquared << '\\n';\n\n    //let's consider another observation, not used to train our model\n    const House anotherObservation = { 41., { { \"bathroom\",1.5 },{ \"area\", 5.0000 },{ \"livingArea\", 1.200 },{ \"garage\", 2.0 },{ \"room\",  6. },{ \"bedroom\", 3. },{ \"age\", 30. } } };\n\n    //estimate its price and compare to the real price\n    double estimatedPrice = evaluatePrice(model, anotherObservation.properties);\n    std::cout << \"Estimate price of a house: \" << estimatedPrice << \", compared to \" << anotherObservation.price << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "4d74bad09e29651950e1fe62cbc95c02385396c3", "size": 8990, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LinearRegression/main.cpp", "max_stars_repo_name": "alxbilger/machinelearningeducation", "max_stars_repo_head_hexsha": "38107124a77506ef5232f054660b1249795807d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LinearRegression/main.cpp", "max_issues_repo_name": "alxbilger/machinelearningeducation", "max_issues_repo_head_hexsha": "38107124a77506ef5232f054660b1249795807d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LinearRegression/main.cpp", "max_forks_repo_name": "alxbilger/machinelearningeducation", "max_forks_repo_head_hexsha": "38107124a77506ef5232f054660b1249795807d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.8823529412, "max_line_length": 179, "alphanum_fraction": 0.510567297, "num_tokens": 3133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5342248510433137}}
{"text": "// Copyright (c) 2016 Till Kolditz\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:   TestModuloInverseComputation.cpp\n * Author: Till Kolditz <till.kolditz@gmail.com>\n *\n * Created on 20. Februar 2017, 18:21\n */\n\n#include <cstdlib>\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <Util/AlignedBlock.hpp>\n#include <Util/Euclidean.hpp>\n#include <Util/Stopwatch.hpp>\n\nint main(\n        int argc,\n        char ** argv) {\n    if (argc != 7) {\n        std::cerr << \"Usage: \" << argv[0] << \" <size [Bytes]> <totalnum [#values]> <A16 <= 2^15> <A32 <= 2^31> <A64 <= 2^63> <A128 <= 2^127>\" << std::endl;\n        return 1;\n    }\n\n    typedef boost::multiprecision::uint128_t uint128_t;\n\n    const uint16_t MASK16 = 0x7FFF;\n    const uint32_t MASK32 = 0x7FFFFFFFul;\n    const uint64_t MASK64 = 0x7FFFFFFFFFFFFFFFull;\n    const uint128_t MASK128(\"0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\");\n\n    size_t SIZE = strtoll(argv[1], nullptr, 0);\n    size_t TOTALNUM = strtoll(argv[2], nullptr, 0);\n    uint16_t A16 = MASK16 & static_cast<uint16_t>(strtol(argv[3], nullptr, 0)); // test for code widths up to 15 bits\n    uint32_t A32 = MASK32 & static_cast<uint32_t>(strtol(argv[4], nullptr, 0)); // test for code widths up to 31 bits\n    uint64_t A64 = MASK64 & static_cast<uint64_t>(strtoll(argv[5], nullptr, 0)); // test for code widths up to 63 bits\n    uint128_t A128(argv[6]); // test for code widths up to 127 bits\n\n    const size_t NUM16 = SIZE / sizeof(uint16_t);\n    const size_t NUM32 = SIZE / sizeof(uint32_t);\n    const size_t NUM64 = SIZE / sizeof(uint64_t);\n    const size_t NUM128 = SIZE / sizeof(uint128_t);\n    TOTALNUM += (NUM16 - (TOTALNUM & (NUM16 - 1)));\n    AlignedBlock data(SIZE, SIZE);\n\n    std::cout << std::fixed << std::setprecision(1);\n\n#ifdef DEBUG\n    std::cout << TOTALNUM << \" numbers.\" << std::endl;\n#endif\n\n#ifdef DEBUG\n    std::cout << \"16-bit: \" << (TOTALNUM / NUM16) << \" iterations, each on \" << NUM16 << \" uint16_t.\" << std::endl;\n#endif\n    auto data16 = data.template begin<uint16_t>();\n    Stopwatch sw;\n    for (size_t k = 0; k < (TOTALNUM / NUM16); k++) {\n        for (size_t i = 0; i < NUM16; ++i) {\n            data16[0] = ext_euclidean(A16, 15);\n        }\n    }\n    auto nanoseconds = sw.Current();\n#ifdef DEBUG\n    std::cout << \"Computing \" << TOTALNUM << \" inverses for 1..15-bit codewords took \" << nanoseconds << \" ns.\" << std::endl;\n    std::cout << \"\\t\" << (static_cast<double>(nanoseconds) / static_cast<double>(TOTALNUM)) << \" ns / inverse.\" << std::endl;\n    std::cout << \"\\t\" << A16 << \" * \" << data16[0] << \" = \" << ((A16 * data16[0]) & MASK16) << std::endl;\n#else\n    std::cout << A16 << '\\t' << nanoseconds << '\\t' << (static_cast<double>(nanoseconds) / static_cast<double>(TOTALNUM));\n#endif\n\n#ifdef DEBUG\n    std::cout << \"32-bit: \" << (TOTALNUM / NUM32) << \" iterations, each on \" << NUM32 << \" uint32_t.\" << std::endl;\n#endif\n    auto data32 = data.template begin<uint32_t>();\n    sw.Reset();\n    for (size_t k = 0; k < (TOTALNUM / NUM32); k++) {\n        for (size_t i = 0; i < NUM32; ++i) {\n            data32[i] = ext_euclidean(A32, 31);\n        }\n    }\n    nanoseconds = sw.Current();\n#ifdef DEBUG\n    std::cout << \"Computing \" << TOTALNUM << \" inverses for 16..31-bit codewords took \" << nanoseconds << \" ns.\" << std::endl;\n    std::cout << \"\\t \" << (static_cast<double>(nanoseconds) / static_cast<double>(TOTALNUM)) << \" ns / inverse.\" << std::endl;\n    std::cout << \"\\t\" << A32 << \" * \" << data32[0] << \" = \" << ((A32 * data32[0]) & MASK32) << std::endl;\n#else\n    std::cout << '\\t' << A32 << '\\t' << nanoseconds << '\\t' << (static_cast<double>(nanoseconds) / static_cast<double>(TOTALNUM));\n#endif\n\n#ifdef DEBUG\n    std::cout << \"64-bit: \" << (TOTALNUM / NUM64) << \" iterations, each on \" << NUM64 << \" uint64_t.\" << std::endl;\n#endif\n    auto data64 = data.template begin<uint64_t>();\n    sw.Reset();\n    for (size_t k = 0; k < (TOTALNUM / NUM64); k++) {\n        for (size_t i = 0; i < NUM64; ++i) {\n            data64[i] = ext_euclidean(A64, 63);\n        }\n    }\n    nanoseconds = sw.Current();\n#ifdef DEBUG\n    std::cout << \"Computing \" << TOTALNUM << \" inverses for 32..63-bit codewords took \" << nanoseconds << \" ns.\" << std::endl;\n    std::cout << \"\\t \" << (static_cast<double>(nanoseconds) / static_cast<double>(TOTALNUM)) << \" ns / inverse.\" << std::endl;\n    std::cout << \"\\t\" << A64 << \" * \" << data64[0] << \" = \" << ((A64 * data64[0]) & MASK64) << std::endl;\n#else\n    std::cout << '\\t' << A64 << '\\t' << nanoseconds << '\\t' << (static_cast<double>(nanoseconds) / static_cast<double>(TOTALNUM));\n#endif\n\n#ifdef DEBUG\n    std::cout << \"128-bit: \" << (TOTALNUM / NUM64) << \" iterations, each on \" << NUM128 << \" uint128_t.\" << std::endl;\n#endif\n    auto data128 = data.template begin<uint128_t>();\n    sw.Reset();\n    for (size_t k = 0; k < (TOTALNUM / NUM128); k++) {\n        for (size_t i = 0; i < NUM128; ++i) {\n            data128[i] = ext_euclidean(A128, 127);\n        }\n    }\n    nanoseconds = sw.Current();\n#ifdef DEBUG\n    std::cout << \"Computing \" << TOTALNUM << \" inverses for 64..127-bit codewords took \" << nanoseconds << \" ns.\" << std::endl;\n    std::cout << \"\\t \" << (static_cast<double>(nanoseconds) / static_cast<double>(TOTALNUM)) << \" ns / inverse.\" << std::endl;\n    std::cout << \"\\t\" << A128 << \" * \" << data128[0] << \" = \" << ((A128 * data128[0]) & MASK128) << std::endl;\n#else\n    std::cout << '\\t' << A128 << '\\t' << nanoseconds << '\\t' << (static_cast<double>(nanoseconds) / static_cast<double>(TOTALNUM)) << std::endl;\n#endif\n}\n", "meta": {"hexsha": "e93d16d1c5f8ee11d3d0a3cf6998c48ce735dcd7", "size": 6093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TestModuloInverseComputation.cpp", "max_stars_repo_name": "tuddbresilience/coding_benchmark", "max_stars_repo_head_hexsha": "f4bab7b57fcb57d98d94a4efc3b8adad2bad6767", "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/TestModuloInverseComputation.cpp", "max_issues_repo_name": "tuddbresilience/coding_benchmark", "max_issues_repo_head_hexsha": "f4bab7b57fcb57d98d94a4efc3b8adad2bad6767", "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/TestModuloInverseComputation.cpp", "max_forks_repo_name": "tuddbresilience/coding_benchmark", "max_forks_repo_head_hexsha": "f4bab7b57fcb57d98d94a4efc3b8adad2bad6767", "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.3125, "max_line_length": 155, "alphanum_fraction": 0.5977351059, "num_tokens": 1870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5342248510433136}}
{"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 *      121105    K. Kumar          File created from content in other files.\n *      121210    D. Dirkx          Added function implementations for class.\n *\n *    References\n *\n *    Notes\n *\n */\n\n#include <cmath>\n#include <stdexcept>\n\n#include <boost/exception/all.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\n#include \"Tudat/Astrodynamics/Gravitation/centralJ2J3J4GravityModel.h\"\n\nnamespace tudat\n{\nnamespace gravitation\n{\n\n//! Compute gravitational acceleration due to J4.\nEigen::Vector3d computeGravitationalAccelerationDueToJ4(\n        const Eigen::Vector3d& positionOfBodySubjectToAcceleration,\n        const double gravitationalParameterOfBodyExertingAcceleration,\n        const double equatorialRadiusOfBodyExertingAcceleration,\n        const double j4CoefficientOfGravityField,\n        const Eigen::Vector3d& positionOfBodyExertingAcceleration )\n{\n    // Set constant values reused for optimal computation of acceleration components.\n    const double distanceBetweenBodies = ( positionOfBodySubjectToAcceleration\n                                           - positionOfBodyExertingAcceleration ).norm( );\n\n    const double preMultiplier = gravitationalParameterOfBodyExertingAcceleration\n            / std::pow( distanceBetweenBodies, 6.0 ) * 4.375 * j4CoefficientOfGravityField\n            * std::pow( equatorialRadiusOfBodyExertingAcceleration, 4.0 );\n\n    const double scaledZCoordinate = ( positionOfBodySubjectToAcceleration.z( )\n                                       - positionOfBodyExertingAcceleration.z( ) )\n            / distanceBetweenBodies;\n\n    const double scaledZCoordinateSquared = scaledZCoordinate * scaledZCoordinate;\n\n    const double scaledZCoordinateToPower4 = scaledZCoordinateSquared * scaledZCoordinateSquared;\n\n    const double factorForXAndYDirections = ( 3.0 / 7.0 - 6.0 * scaledZCoordinateSquared\n                                              + 9.0 * scaledZCoordinateToPower4 )\n            / distanceBetweenBodies;\n\n    // Compute components of acceleration due to J4-effect.\n    Eigen::Vector3d gravitationalAccelerationDueToJ4 = Eigen::Vector3d::Constant( preMultiplier );\n\n    gravitationalAccelerationDueToJ4( orbital_element_conversions::xCartesianPositionIndex )\n            *= ( positionOfBodySubjectToAcceleration.x( )\n                 - positionOfBodyExertingAcceleration.x( ) ) * factorForXAndYDirections;\n\n    gravitationalAccelerationDueToJ4( orbital_element_conversions::yCartesianPositionIndex )\n            *= ( positionOfBodySubjectToAcceleration.y( )\n                 - positionOfBodyExertingAcceleration.y( ) ) * factorForXAndYDirections;\n\n    gravitationalAccelerationDueToJ4( orbital_element_conversions::zCartesianPositionIndex )\n            *= ( 15.0 / 7.0 - 10.0 * scaledZCoordinateSquared + 9.0 * scaledZCoordinateToPower4 )\n            * scaledZCoordinate;\n\n    return gravitationalAccelerationDueToJ4;\n}\n\n//! Compute gravitational acceleration zonal sum.\nEigen::Vector3d computeGravitationalAccelerationZonalSum(\n        const Eigen::Vector3d& positionOfBodySubjectToAcceleration,\n        const double gravitationalParameterOfBodyExertingAcceleration,\n        const double equatorialRadiusOfBodyExertingAcceleration,\n        const std::map< int, double > zonalCoefficientsOfGravityField,\n        const Eigen::Vector3d& positionOfBodyExertingAcceleration )\n{\n    // Check that only coefficients for the gravity field are given up to J2 (i.e., size of\n    // vector is 3 at max), else throw an error.\n    if ( zonalCoefficientsOfGravityField.size( ) > 3 )\n    {\n        boost::throw_exception(\n                    boost::enable_error_info(\n                        std::runtime_error(\n                            \"Currently, accelerations can only be computed up to J4.\" ) ) );\n    }\n\n    // Check if position of body subject to acceleration falls within the effective radius of\n    // the central body. If so, throw an error.\n    if ( ( positionOfBodySubjectToAcceleration - positionOfBodyExertingAcceleration ).norm( )\n         < equatorialRadiusOfBodyExertingAcceleration )\n    {\n        boost::throw_exception(\n                    boost::enable_error_info(\n                        std::runtime_error(\n                            \"Position of body subject to acceleration is within effective radius.\"\n                            ) ) );\n    }\n\n    // Set gravitational acceleration sum equal to central term contribution.\n    Eigen::Vector3d gravitationalAccelerationSum\n            = computeGravitationalAcceleration(\n                positionOfBodySubjectToAcceleration,\n                gravitationalParameterOfBodyExertingAcceleration,\n                positionOfBodyExertingAcceleration );\n\n    // Add contributions from zonal terms. The switch statement checks\n    for ( std::map< int, double >::const_iterator mapIterator\n          = zonalCoefficientsOfGravityField.begin( );\n          mapIterator != zonalCoefficientsOfGravityField.end( ); mapIterator++ )\n    {\n        switch ( mapIterator->first )\n        {\n        case 2:\n\n            gravitationalAccelerationSum += computeGravitationalAccelerationDueToJ2(\n                        positionOfBodySubjectToAcceleration,\n                        gravitationalParameterOfBodyExertingAcceleration,\n                        equatorialRadiusOfBodyExertingAcceleration,\n                        mapIterator->second,\n                        positionOfBodyExertingAcceleration );\n\n            break;\n\n        case 3:\n\n            gravitationalAccelerationSum += computeGravitationalAccelerationDueToJ3(\n                        positionOfBodySubjectToAcceleration,\n                        gravitationalParameterOfBodyExertingAcceleration,\n                        equatorialRadiusOfBodyExertingAcceleration,\n                        mapIterator->second,\n                        positionOfBodyExertingAcceleration );\n\n            break;\n\n        case 4:\n\n            gravitationalAccelerationSum += computeGravitationalAccelerationDueToJ4(\n                        positionOfBodySubjectToAcceleration,\n                        gravitationalParameterOfBodyExertingAcceleration,\n                        equatorialRadiusOfBodyExertingAcceleration,\n                        mapIterator->second,\n                        positionOfBodyExertingAcceleration );\n\n            break;\n\n        default:\n\n            boost::throw_exception(\n                        boost::enable_error_info(\n                            std::runtime_error(\n                                \"Degree must be 2, 3, or 4 in current implementation.\" ) ) );\n        };\n    }\n\n    // Return total gravitational acceleration computed.\n    return gravitationalAccelerationSum;\n}\n\n//! Get gravitational acceleration.\nEigen::Vector3d CentralJ2J3J4GravitationalAccelerationModel::getAcceleration( )\n{\n    // Sum and return constituent acceleration terms.\n    return computeGravitationalAcceleration(\n                this->positionOfBodySubjectToAcceleration,\n                this->gravitationalParameter,\n                this->positionOfBodyExertingAcceleration )\n            + computeGravitationalAccelerationDueToJ2(\n                this->positionOfBodySubjectToAcceleration,\n                this->gravitationalParameter,\n                this->equatorialRadius,\n                this->j2GravityCoefficient,\n                this->positionOfBodyExertingAcceleration )\n            + computeGravitationalAccelerationDueToJ3(\n                this->positionOfBodySubjectToAcceleration,\n                this->gravitationalParameter,\n                this->equatorialRadius,\n                this->j3GravityCoefficient,\n                this->positionOfBodyExertingAcceleration )\n            + computeGravitationalAccelerationDueToJ4(\n                this->positionOfBodySubjectToAcceleration,\n                this->gravitationalParameter,\n                this->equatorialRadius,\n                this->j4GravityCoefficient,\n                this->positionOfBodyExertingAcceleration );\n}\n\n} // namespace gravitation\n} // namespace tudat\n", "meta": {"hexsha": "c4793d395da942ce02fec8f2a5a813fd4db46c1c", "size": 9753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Gravitation/centralJ2J3J4GravityModel.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/Astrodynamics/Gravitation/centralJ2J3J4GravityModel.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/Astrodynamics/Gravitation/centralJ2J3J4GravityModel.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": 45.3627906977, "max_line_length": 99, "alphanum_fraction": 0.6726135548, "num_tokens": 1939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5342248491765791}}
{"text": "#include <gtest/gtest.h>\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <functional>\n\n#include \"../locallaplaceqfe.h\"\n#include \"../qfeinterpolator.h\"\n#include \"../qfeprovidertester.h\"\n\nnamespace DebuggingFEM::test {\n\nconstexpr double Square(double x) { return x * x; }\n\nstruct TestPair {\n  typedef Eigen::Matrix<double, 6, 1> Vector6d;\n\n  TestPair(const Vector6d &a) {\n    function = [a](Eigen::Vector2d x) {\n      return a(0) * Square(x(0)) + a(1) * Square(x(1)) + a(2) * x(0) * x(1) +\n             a(3) * x(0) + a(4) * x(1) + a(5);\n    };\n    // coefficients of quadratic polynomial |grad function|^2\n    Vector6d b;\n    b << 4.0 * Square(a(0)) + Square(a(2)), 4.0 * Square(a(1)) + Square(a(2)),\n        4.0 * a(2) * (a(0) + a(1)), 2.0 * (2.0 * a(0) * a(3) + a(2) * a(4)),\n        2.0 * (2.0 * a(1) * a(4) + a(2) * a(3)), Square(a(3)) + Square(a(4));\n    // monomials integrated over [0, 1]^2\n    Eigen::VectorXd integrated_monomials(6);\n    integrated_monomials << 1.0 / 3.0, 1.0 / 3.0, 0.25, 0.5, 0.5, 1.0;\n    // reference value for energy (H_1 seminorm)\n    energy = integrated_monomials.dot(b);\n  }\n\n  std::function<double(Eigen::Vector2d x)> function;\n  double energy;\n};\n\nTEST(DebuggingFEM, interpolateOntoQuadFE) {\n  // reference\n  Eigen::VectorXd a(6);\n  a << 1.0, 4.0, 2.0, 3.0, 2.0, 1.0;\n  TestPair test_pair(a);\n  auto p = test_pair.function;\n  double energy_ref = test_pair.energy;\n\n  // to test\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3, 1.0 / 3.0);\n  lf::assemble::UniformFEDofHandler dofh(mesh_p,\n                                         {{lf::base::RefEl::kPoint(), 1},\n                                          {lf::base::RefEl::kSegment(), 1},\n                                          {lf::base::RefEl::kTria(), 0},\n                                          {lf::base::RefEl::kQuad(), 1}});\n\n  const lf::base::size_type N_dofs(dofh.NumDofs());\n  lf::assemble::COOMatrix<double> mat(N_dofs, N_dofs);\n  auto element_matrix_provider = DebuggingFEM::LocalLaplaceQFE2();\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, element_matrix_provider,\n                                      mat);\n\n  const Eigen::SparseMatrix<double> A(mat.makeSparse());\n  Eigen::VectorXd eta = DebuggingFEM::interpolateOntoQuadFE(dofh, p);\n  double energy = eta.dot(A * eta);\n\n  EXPECT_NEAR(energy, energy_ref, 1.0e-8);\n}\n\nTEST(DebuggingFEM, QFEProviderTester) {\n  // reference\n  Eigen::VectorXd a(6);\n  a << 1.0, 4.0, 2.0, 3.0, 2.0, 1.0;\n  TestPair test_pair(a);\n  auto p = test_pair.function;\n  double energy_ref = test_pair.energy;\n\n  // to test\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3, 1.0 / 3.0);\n  lf::assemble::UniformFEDofHandler dofh(mesh_p,\n                                         {{lf::base::RefEl::kPoint(), 1},\n                                          {lf::base::RefEl::kSegment(), 1},\n                                          {lf::base::RefEl::kTria(), 0},\n                                          {lf::base::RefEl::kQuad(), 1}});\n\n  auto element_matrix_provider = DebuggingFEM::LocalLaplaceQFE2();\n  QFEProviderTester qfe_provider_tester(dofh, element_matrix_provider);\n  double energy = qfe_provider_tester.energyOfInterpolant(p);\n\n  EXPECT_NEAR(energy, energy_ref, 1.0e-8);\n}\n\n}  // namespace DebuggingFEM::test\n", "meta": {"hexsha": "01dfb456cbe94da50a31a7107650921cb40c1f42", "size": 3396, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/DebuggingFEM/templates/test/debuggingfem_test.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/DebuggingFEM/templates/test/debuggingfem_test.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/DebuggingFEM/templates/test/debuggingfem_test.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 35.7473684211, "max_line_length": 78, "alphanum_fraction": 0.5809776207, "num_tokens": 1093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5342248459895251}}
{"text": "/*-----------------------------------------------------------------------------+\nCopyright (c) 2008-2009: Joachim Faulhaber\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n#define BOOST_TEST_MODULE icl::interval unit test\n#include <libs/icl/test/disable_test_warnings.hpp>\n#include <string>\n#include <boost/mpl/list.hpp>\n#include \"../unit_test_unwarned.hpp\"\n\n// interval instance types\n#include \"../test_type_lists.hpp\"\n#include \"../test_value_maker.hpp\"\n#include \"../test_interval_laws.hpp\"\n\n#include <boost/icl/right_open_interval.hpp>\n#include <boost/icl/left_open_interval.hpp>\n#include <boost/icl/closed_interval.hpp>\n#include <boost/icl/open_interval.hpp>\n\n#include <boost/icl/discrete_interval.hpp>\n#include <boost/icl/continuous_interval.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace unit_test;\nusing namespace boost::icl;\n\n#include \"../test_icl_interval_shared.hpp\"\n#include \"../test_icl_interval.hpp\"\n#include \"../test_icl_dynamic_interval.hpp\"\n#include \"../test_icl_discrete_interval.hpp\"\n#include \"../test_icl_continuous_interval.hpp\"\n#include \"../test_icl_static_interval.hpp\"\n\n//==============================================================================\n//= Traits\n//==============================================================================\nBOOST_AUTO_TEST_CASE\n(fastest_icl_discrete_interval_traits)\n{            discrete_interval_traits<discrete_type_1, discrete_interval<discrete_type_1> >(); }\n\n//==============================================================================\n\n//- sta.asy.{dis|con} ----------------------------------------------------------\nBOOST_AUTO_TEST_CASE\n(fastest_icl_right_open_interval_ctor_4_ordered_types)\n{                       interval_ctor_4_ordered_types<right_open_interval<ordered_type_1> >(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_right_open_interval_4_ordered_types)\n{          singelizable_interval_4_ordered_types<right_open_interval<discrete_type_1> >(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_right_open_interval_4_bicremental_types)\n{          singelizable_interval_4_bicremental_types<right_open_interval<discrete_type_2> >(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_left_open_interval_ctor_4_ordered_types)\n{                      interval_ctor_4_ordered_types<left_open_interval<ordered_type_2> >(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_left_open_interval_4_ordered_types_singelizable)\n{         singelizable_interval_4_ordered_types<left_open_interval<signed_discrete_type_1> >(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_left_open_interval_4_bicremental_types)\n{         singelizable_interval_4_bicremental_types<left_open_interval<discrete_type_4> >(); }\n\n//- coverables -----------------------------------------------------------------\nBOOST_AUTO_TEST_CASE\n(fastest_cover_right_open_interval_4_bicremental_types)\n{    coverable_asymmetric_interval_4_bicremental_types<right_open_interval<numeric_continuous_type_1> >(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_cover_left_open_interval_4_bicremental_types)\n{    coverable_asymmetric_interval_4_bicremental_types<left_open_interval<numeric_continuous_type_3> >(); }\n\n//- dyn.dis --------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE\n(fastest_icl_discrete_interval_ctor_4_discrete_types_base)\n{                     interval_ctor_4_ordered_types<discrete_interval<discrete_type_1> >(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_discrete_interval_ctor_4_discrete_types_dynamic)\n{             dynamic_interval_ctor_4_ordered_types<discrete_interval<discrete_type_2> >(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_discrete_interval_4_ordered_types)\n{        singelizable_interval_4_ordered_types<discrete_interval<discrete_type_3> >(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_discrete_interval_4_bicremental_types)\n{        singelizable_interval_4_bicremental_types<discrete_interval<discrete_type_3> >(); }\n\n//- dyn.con --------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE\n(fastest_icl_continuous_interval_ctor_4_continuous_types_base)\n{                       interval_ctor_4_ordered_types<continuous_interval<continuous_type_1> >(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_continuous_interval_ctor_4_continuous_types_dynamic)\n{               dynamic_interval_ctor_4_ordered_types<continuous_interval<continuous_type_2> >(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_continuous_interval_4_continuous_types_singelizable)\n{          singelizable_interval_4_ordered_types<continuous_interval<continuous_type_3> >(); }\n\n//------------------------------------------------------------------------------\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_distant_intervals_4_discrete_types)\n{            distant_intervals_4_discrete_types<discrete_type_1, std::less>(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_distant_intervals_4_numeric_continuous_types)\n{            distant_intervals_4_numeric_continuous_types<numeric_continuous_type_1, std::less>(); }\n\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE\n(fastest_icl_dynamic_interval_bounds_4_bicremental_types)\n{            dynamic_interval_bounds_4_bicremental_types<bicremental_type_2>(); }\n\n//==============================================================================\n//==============================================================================\nBOOST_AUTO_TEST_CASE\n(fastest_icl_interval_equal_4_integral_types)\n{            interval_equal_4_integral_types<integral_type_2>(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_interval_less_4_integral_types)\n{            interval_less_4_integral_types<integral_type_3>(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_interval_touches_4_bicremental_types)\n{            interval_touches_4_bicremental_types<bicremental_type_1>(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_interval_touches_4_integral_types)\n{            interval_touches_4_integral_types<integral_type_4>(); }\n\n#ifndef BOOST_ICL_USE_STATIC_BOUNDED_INTERVALS\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_interval_ctor_specific)\n{            interval_ctor_specific(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_interval_equal_4_bicremental_continuous_types)\n{            interval_equal_4_bicremental_continuous_types<bicremental_continuous_type_1>(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_interval_infix_intersect_4_bicremental_types)\n{            interval_infix_intersect_4_bicremental_types<bicremental_type_4>(); }\n\n#else\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_interval_infix_intersect_4_bicremental_types)\n{            interval_infix_intersect_4_bicremental_types<discrete_type_2>(); }\n\nBOOST_AUTO_TEST_CASE\n(fastest_icl_interval_subtract_4_bicremental_types)\n{            interval_subtract_4_bicremental_types<bicremental_type_5>(); }\n\n#endif // ndef BOOST_ICL_USE_STATIC_BOUNDED_INTERVALS\n", "meta": {"hexsha": "14572648e1fb4a47f231d6787ec39483a3656030", "size": 7004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/icl/test/fastest_icl_interval_/fastest_icl_interval.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/icl/test/fastest_icl_interval_/fastest_icl_interval.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/icl/test/fastest_icl_interval_/fastest_icl_interval.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.2, "max_line_length": 108, "alphanum_fraction": 0.6901770417, "num_tokens": 1495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5342158217074094}}
{"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_INVLOG_10_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_INVLOG_10_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    Generates constant 1/log(10).\n\n\n    @par Header <boost/simd/constant/invlog_10.hpp>\n\n    @par Semantic:\n\n    @code\n    T r = Invlog_10<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    r =  T(0.4342944819032518276511289189166050822943970058036666);\n    @endcode\n\n\n**/\n  template<typename T> T Invlog_10();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Generates constant 1/log(10).\n\n      Generate the  constant invlog_10.\n\n      @return The Invlog_10 constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::invlog_10_> invlog_10 = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/scalar/invlog_10.hpp>\n#include <boost/simd/constant/simd/invlog_10.hpp>\n\n#endif\n", "meta": {"hexsha": "44e0f712b8080db8a33f5d3f3ab6ec64a239aaba", "size": 1320, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/invlog_10.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "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/invlog_10.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "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/invlog_10.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 20.9523809524, "max_line_length": 100, "alphanum_fraction": 0.5909090909, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.5342158214139694}}
{"text": "/**\n * test_multshiftround_shiftround_run.cpp\n * Unit tests for the multshiftround and shiftround functions that\n * evaluate the shift argument at runtime. These functions are tested\n * separately from those that require the shift argument at compile\n * time because they can be conditionally compiled to use rounding masks\n * based on array lookups (ARRAY_MASKS) or shift operations (COMPUTED_MASKS).\n * Consequently, this file will be compiled into two executables, one\n * to test each type of rounding mask.\n *\n * Full coverage is provided on the num and shift inputs for the\n * int8_t, int16_t, int32_t, uint8_t, uint16_t, and uint32_t types.\n *\n * The coverage of the num input for 64-bit types is only partial in\n * order to acheive a reasonable test time, especially since the\n * extended precision floating point calculations required to test the\n * 64-bit routines are slow.\n * The num input tested with an increment of 2^35-1 across the\n * range of each 64-bit type for about 536,870,912 tests at every shift\n * value.\n * \n * Written in 2019 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 <cstdio>\n#include <cmath>\n#include <limits>\n#include <vector>\n#include <utility>\n#include <thread>\n#include <chrono>\n#include <mutex>\n#include <atomic>\n#include \"multshiftround_run.hpp\"\n#include \"shiftround_run.hpp\"\n\n#ifdef __cplusplus\n  extern \"C\"\n  {\n#endif\n    #include \"multshiftround_run.h\"\n    #include \"shiftround_run.h\"\n#ifdef __cplusplus\n  }\n#endif\n\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 * Setting the mul argument of multshiftround to 1 for various types.\n * This is for testing the shift and round portions of multshiftround.\n * The multiplication operation in multshiftround\n *     type prod = num * mul;\n * is tested separately.\n */\nconst int8_t   mul_i8 = 1;\nconst double   dbl_mul_i8 = static_cast<double>(mul_i8);\nconst int16_t  mul_i16 = 1;\nconst double   dbl_mul_i16 = static_cast<double>(mul_i16);\nconst int32_t  mul_i32 = 1;\nconst double   dbl_mul_i32 = static_cast<double>(mul_i32);\nconst int64_t  mul_i64 = 1ll;\nconst cpp_bin_float_80 ldbl_mul_i64(mul_i64);\nconst uint8_t  mul_u8 = 1u;\nconst double   dbl_mul_u8 = static_cast<double>(mul_u8);\nconst uint16_t mul_u16 = 1u;\nconst double   dbl_mul_u16 = static_cast<double>(mul_u16);\nconst uint32_t mul_u32 = 1u;\nconst double   dbl_mul_u32 = static_cast<double>(mul_u32);\nconst uint64_t mul_u64 = 1ull;\nconst cpp_bin_float_80 ldbl_mul_u64(mul_u64);\n\n/**\n * There is one atomic bool for each thread, set to true upon\n * thread initiation and set to false as the last computation \n * in the thread.\n * This helps decide when to join a thread and replace it with\n * a new thread.\n * Plain C array because atomics don't have move or copy constructors.\n */\nstd::atomic<bool> *thread_running;\n\n/**\n * Mutex for stdout when running multithreaded.\n */\nstd::mutex print_mutex;\n\n/**\n * Test c++ style runtime int32_t multshiftround for num on [-2147483648, 2147483647].\n * shift should range from 0 to 30.\n */\nvoid test_multshiftround_i32_run_cpp(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing multshiftround<int32_t>(num, mul, %u)\\n\", shift);\n  }\n  \n  if (shift > 30u)\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"ERROR: multshiftround<int32_t>(num, mul, ?\"\"?): invalid shift value %u\\n\", shift);\n  }\n  else\n  {\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    int32_t num = std::numeric_limits<int32_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      int32_t ms_res = multshiftround<int32_t>(num, mul_i32, shift);\n      int32_t dbl_res = static_cast<int32_t>(std::round(dbl_num * dbl_mul_i32 * dbl_inv_twoexp));\n      if (ms_res != dbl_res) {\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"ERROR: multshiftround<int32_t>(num, mul, %u): ms_res %i, dbl_res %i, dbl %.16f, num %i, mul %i\\n\", shift, ms_res, dbl_res, dbl_num * dbl_mul_i32 * dbl_inv_twoexp, num, mul_i32);\n      } \n      if (num == std::numeric_limits<int32_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  multshiftround<int32_t>(num, mul, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c style runtime int32_t multshiftround for num on [-2147483648, 2147483647].\n * shift should range from 0 to 30.\n */\nvoid test_multshiftround_i32_run_c(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing multshiftround_i32(num, mul, %u)\\n\", shift);\n  }\n\n  if (shift > 30u)\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"ERROR: multshiftround_i32(num, mul, ?\"\"?): invalid shift value %u\\n\", shift);\n  }\n  else\n  {\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    int32_t num = std::numeric_limits<int32_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      int32_t ms_res = multshiftround_i32(num, mul_i32, shift);\n      int32_t dbl_res = static_cast<int32_t>(std::round(dbl_num * dbl_mul_i32 * dbl_inv_twoexp));\n      if (ms_res != dbl_res) {\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"ERROR: multshiftround_i32(num, mul, %i): ms_res %i, dbl_res %i, dbl %.16f, num %i, mul %i\\n\", shift, ms_res, dbl_res, dbl_num * dbl_mul_i32 * dbl_inv_twoexp, num, mul_i32);\n      }\n      if (num == std::numeric_limits<int32_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  multshiftround_i32(num, mul, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c++ style runtime int32_t shiftround for num on [-2147483648, 2147483647].\n * shift should range from 0 to 30.\n */\nvoid test_shiftround_i32_run_cpp(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing shiftround<int32_t>(num, %u)\\n\", shift);\n  }\n\n  double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n  int32_t num = std::numeric_limits<int32_t>::lowest();\n  double dbl_num = static_cast<double>(num);\n  while (true)\n  {\n    int32_t s_res = shiftround<int32_t>(num, shift);\n    int32_t dbl_res = static_cast<int32_t>(std::round(dbl_num * dbl_inv_twoexp));\n    if (s_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: shiftround<int32_t>(num, %u): s_res %i, dbl_res %i, dbl %.16f, num %i\\n\", shift, s_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n    }\n    if (num == std::numeric_limits<int32_t>::max()) break;\n    num++;\n    dbl_num += 1.0;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  shiftround<int32_t>(mul, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c style runtime int32_t shiftround for num on [-2147483648, 2147483647].\n * shift should range from 0 to 30.\n */\nvoid test_shiftround_i32_run_c(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing shiftround_i32(num, %u)\\n\", shift);\n  }\n\n  double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n  int32_t num = std::numeric_limits<int32_t>::lowest();\n  double dbl_num = static_cast<double>(num);\n  while (true)\n  {\n    int32_t s_res = shiftround_i32(num, shift);\n    int32_t dbl_res = static_cast<int32_t>(std::round(dbl_num * dbl_inv_twoexp));\n    if (s_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: shiftround_i32(num, %u): s_res %i, dbl_res %i, dbl %.16f, num %i\\n\", shift, s_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n    }\n    if (num == std::numeric_limits<int32_t>::max()) break;\n    num++;\n    dbl_num += 1.0;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  shiftround_i32(mul, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c++ style runtime uint32_t multshiftround for num on [0, 4294967295].\n * shift should range from 0 to 31.\n */\nvoid test_multshiftround_u32_run_cpp(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing multshiftround<uint32_t>(num, mul, %u)\\n\", shift);\n  }\n\n  double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n  uint32_t num = std::numeric_limits<uint32_t>::lowest();\n  double dbl_num = static_cast<double>(num);\n  while (true)\n  {\n    uint32_t ms_res = multshiftround<uint32_t>(num, mul_u32, shift);\n    uint32_t dbl_res = static_cast<uint32_t>(std::round(dbl_num * dbl_mul_u32 * dbl_inv_twoexp));\n    if (ms_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: multshiftround<uint32_t>(num, mul, %u): ms_res %u, dbl_res %u, dbl %.16f, num %u, mul %u\\n\", shift, ms_res, dbl_res, dbl_num * dbl_mul_u32 * dbl_inv_twoexp, num, mul_u32);\n    }\n    if (num == std::numeric_limits<uint32_t>::max()) break;\n    num++;\n    dbl_num += 1.0;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  multshiftround<uint32_t>(num, mul, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c style runtime uint32_t multshiftround for num on [0, 4294967295].\n * shift should range from 0 to 31.\n */\nvoid test_multshiftround_u32_run_c(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing multshiftround_u32(num, mul, %u)\\n\", shift);\n  }\n\n  double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n  uint32_t num = std::numeric_limits<uint32_t>::lowest();\n  double dbl_num = static_cast<double>(num);\n  while (true)\n  {\n    uint32_t ms_res = multshiftround_u32(num, mul_u32, shift);\n    uint32_t dbl_res = static_cast<uint32_t>(std::round(dbl_num * dbl_mul_u32 * dbl_inv_twoexp));\n    if (ms_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: multshiftround_u32(num, mul, %u): ms_res %u, dbl_res %u, dbl %.16f, num %u, mul %u\\n\", shift, ms_res, dbl_res, dbl_num * dbl_mul_u32 * dbl_inv_twoexp, num, mul_u32);\n    }\n    if (num == std::numeric_limits<uint32_t>::max()) break;\n    num++;\n    dbl_num += 1.0;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  multshiftround_u32(num, mul, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c++ style runtime uint32_t shiftround for num on [0, 4294967295].\n * shift should range from 0 to 31.\n */\nvoid test_shiftround_u32_run_cpp(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing shiftround<uint32_t>(num, %u)\\n\", shift);\n  }\n    \n  double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n  uint32_t num = std::numeric_limits<uint32_t>::lowest();\n  double dbl_num = static_cast<double>(num);\n  while (true)\n  {\n    uint32_t s_res = shiftround<uint32_t>(num, shift);\n    uint32_t dbl_res = static_cast<uint32_t>(std::round(dbl_num * dbl_inv_twoexp));\n    if (s_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: shiftround<uint32_t>(num, %u): s_res %u, dbl_res %u, dbl %.16f, num %u\\n\", shift, s_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n    }\n    if (num == std::numeric_limits<uint32_t>::max()) break;\n    num++;\n    dbl_num += 1.0;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  shiftround<uint32_t>(num, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c style runtime uint32_t shiftround for num on [0, 4294967295].\n * shift should range from 0 to 31.\n */\nvoid test_shiftround_u32_run_c(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing shiftround_u32(num, %u)\\n\", shift);\n  }\n\n  double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n  uint32_t num = std::numeric_limits<uint32_t>::lowest();\n  double dbl_num = static_cast<double>(num);\n  while (true)\n  {\n    uint32_t s_res = shiftround_u32(num, shift);\n    uint32_t dbl_res = static_cast<uint32_t>(std::round(dbl_num * dbl_inv_twoexp));\n    if (s_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: shiftround_u32(num, %u): s_res %u, dbl_res %u, dbl %.16f, num %u\\n\", shift, s_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n    }\n    if (num == std::numeric_limits<uint32_t>::max()) break;\n    num++;\n    dbl_num += 1.0;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  shiftround_u32(num, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c++ style runtime int64_t multshiftround for num on\n * [-9223372036854775808, 9223372036854775807]\n * in steps of 34359738367 for approximately 536,870,912 tests.\n * shift should range from 0 to 62.\n */\nvoid test_multshiftround_i64_run_cpp(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing multshiftround<int64_t>(num, mul, %u)\\n\", shift);\n  }\n\n  cpp_bin_float_80 ldbl_inv_twoexp = cpp_bin_float_80(1.0) / cpp_bin_float_80(1ull << shift);\n  int64_t increment = (1ll << 35) - 1ll;\n  cpp_bin_float_80 ldbl_increment(increment);\n  int64_t num = std::numeric_limits<int64_t>::lowest();\n  cpp_bin_float_80 ldbl_num(num);\n  while (true)\n  {\n    int64_t ms_res = multshiftround<int64_t>(num, mul_i64, shift);\n    int64_t dbl_res = boost::math::round(ldbl_num * ldbl_mul_i64 * ldbl_inv_twoexp).convert_to<int64_t>();\n    if (ms_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: multshiftround<int64_t>(num, mul, %u): ms_res %\" PRIi64 \", dbl_res %\" PRIi64 \", dbl %.16f, num %\" PRIi64 \", mul %\" PRIi64 \"\\n\", shift, ms_res, dbl_res, (ldbl_num * ldbl_mul_i64 * ldbl_inv_twoexp).convert_to<double>(), num, mul_i64);\n    }\n    if (num > 0ll && std::numeric_limits<int64_t>::max() - num < increment) break;\n    num += increment;\n    ldbl_num += ldbl_increment;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  multshiftround<int64_t>(num, mul, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c style runtime int64_t multshiftround for num on\n * [-9223372036854775808, 9223372036854775807]\n * in steps of 34359738367 for approximately 536,870,912 tests.\n * shift should range from 0 to 62.\n */\nvoid test_multshiftround_i64_run_c(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing multshiftround_i64(num, mul, %u)\\n\", shift);\n  }\n\n  cpp_bin_float_80 ldbl_inv_twoexp = cpp_bin_float_80(1.0) / cpp_bin_float_80(1ull << shift);\n  int64_t increment = (1ll << 35) - 1ll;\n  cpp_bin_float_80 ldbl_increment(increment);\n  int64_t num = std::numeric_limits<int64_t>::lowest();\n  cpp_bin_float_80 ldbl_num(num);\n  while (true)\n  {\n    int64_t ms_res = multshiftround_i64(num, mul_i64, shift);\n    int64_t dbl_res = boost::math::round(ldbl_num * ldbl_mul_i64 * ldbl_inv_twoexp).convert_to<int64_t>();\n    if (ms_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: multshiftround_i64(num, mul, %u): ms_res %\" PRIi64 \", dbl_res %\" PRIi64 \", dbl %.16f, num %\" PRIi64 \", mul %\" PRIi64 \"\\n\", shift, ms_res, dbl_res, (ldbl_num * ldbl_mul_i64 * ldbl_inv_twoexp).convert_to<double>(), num, mul_i64);\n    }\n    if (num > 0ll && std::numeric_limits<int64_t>::max() - num < increment) break;\n    num += increment;\n    ldbl_num += ldbl_increment;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  multshiftround_i64(num, mul, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c++ style runtime int64_t shiftround for num on\n * [-9223372036854775808, 9223372036854775807]\n * in steps of 34359738367 for approximately 536,870,912 tests.\n * shift should range from 0 to 62.\n */\nvoid test_shiftround_i64_run_cpp(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing shiftround<int64_t>(num, %u)\\n\", shift);\n  }\n\n  cpp_bin_float_80 ldbl_inv_twoexp = cpp_bin_float_80(1.0) / cpp_bin_float_80(1ull << shift);\n  int64_t increment = (1ll << 35) - 1ll;\n  cpp_bin_float_80 ldbl_increment(increment);\n  int64_t num = std::numeric_limits<int64_t>::lowest();\n  cpp_bin_float_80 ldbl_num(num);\n  while (true)\n  {\n    int64_t ms_res = shiftround<int64_t>(num, shift);\n    int64_t dbl_res = boost::math::round(ldbl_num * ldbl_inv_twoexp).convert_to<int64_t>();\n    if (ms_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: shiftround<int64_t>(num, %u): ms_res %\" PRIi64 \", dbl_res %\" PRIi64 \", dbl %.16f, num %\" PRIi64 \"\\n\", shift, ms_res, dbl_res, (ldbl_num * ldbl_inv_twoexp).convert_to<double>(), num);\n    }\n    if (num > 0ll && std::numeric_limits<int64_t>::max() - num < increment) break;\n    num += increment;\n    ldbl_num += ldbl_increment;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  shiftround<int64_t>(num, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c style runtime int64_t shiftround for num on\n * [-9223372036854775808, 9223372036854775807]\n * in steps of 34359738367 for approximately 536,870,912 tests.\n * shift should range from 0 to 62.\n */\nvoid test_shiftround_i64_run_c(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing shiftround<int64_t>(num, %u)\\n\", shift);\n  }\n\n  cpp_bin_float_80 ldbl_inv_twoexp = cpp_bin_float_80(1.0) / cpp_bin_float_80(1ull << shift);\n  int64_t increment = (1ll << 35) - 1ll;\n  cpp_bin_float_80 ldbl_increment(increment);\n  int64_t num = std::numeric_limits<int64_t>::lowest();\n  cpp_bin_float_80 ldbl_num(num);\n  while (true)\n  {\n    int64_t ms_res = shiftround_i64(num, shift);\n    int64_t dbl_res = boost::math::round(ldbl_num * ldbl_inv_twoexp).convert_to<int64_t>();\n    if (ms_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: shiftround_i64(num, %i): ms_res %\" PRIi64 \", dbl_res %\" PRIi64 \", dbl %.16f, num %\" PRIi64 \"\\n\", shift, ms_res, dbl_res, (ldbl_num * ldbl_inv_twoexp).convert_to<double>(), num);\n    }\n    if (num > 0ll && std::numeric_limits<int64_t>::max() - num < increment) break;\n    num += increment;\n    ldbl_num += ldbl_increment;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  shiftround_i64(num, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c++ style runtime uint64_t multshiftround for num on\n * [0, 18446744073709551615] in steps of 34359738367 for\n * approximately 536,870,912 tests.\n * shift should range from 0 to 63.\n */\nvoid test_multshiftround_u64_run_cpp(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing multshiftround<uint64_t>(num, mul, %u)\\n\", shift);\n  }\n\n  cpp_bin_float_80 ldbl_inv_twoexp = cpp_bin_float_80(1.0) / cpp_bin_float_80(1ull << shift);\n  uint64_t increment = (1ll << 35) - 1ll;\n  cpp_bin_float_80 ldbl_increment(increment);\n  uint64_t num = std::numeric_limits<uint64_t>::lowest();\n  cpp_bin_float_80 ldbl_num(num);\n  while (true)\n  {\n    uint64_t ms_res = multshiftround<uint64_t>(num, mul_u64, shift);\n    uint64_t dbl_res = boost::math::round(ldbl_num * ldbl_mul_u64 * ldbl_inv_twoexp).convert_to<uint64_t>();\n    if (ms_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: multshiftround<uint64_t>(num, mul, %u): ms_res %\" PRIu64 \", dbl_res %\" PRIu64 \", dbl %.16f, num %\" PRIu64 \", mul %\" PRIu64 \"\\n\", shift, ms_res, dbl_res, (ldbl_num * ldbl_mul_u64 * ldbl_inv_twoexp).convert_to<double>(), num, mul_u64);\n    }\n    if (std::numeric_limits<uint64_t>::max() - num < increment) break;\n    num += increment;\n    ldbl_num += ldbl_increment;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  multshiftround<uint64_t>(num, mul, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c style runtime uint64_t multshiftround for num on\n * [0, 18446744073709551615] in steps of 34359738367 for\n * approximately 536,870,912 tests.\n * shift should range from 0 to 63.\n */\nvoid test_multshiftround_u64_run_c(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing multshiftround_u64(num, mul, %u)\\n\", shift);\n  }\n\n  cpp_bin_float_80 ldbl_inv_twoexp = cpp_bin_float_80(1.0) / cpp_bin_float_80(1ull << shift);\n  uint64_t increment = (1ll << 35) - 1ll;\n  cpp_bin_float_80 ldbl_increment(increment);\n  uint64_t num = std::numeric_limits<uint64_t>::lowest();\n  cpp_bin_float_80 ldbl_num(num);\n  while (true)\n  {\n    uint64_t ms_res = multshiftround_u64(num, mul_u64, shift);\n    uint64_t dbl_res = boost::math::round(ldbl_num * ldbl_mul_u64 * ldbl_inv_twoexp).convert_to<uint64_t>();\n    if (ms_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: multshiftround_u64(num, mul, %u): ms_res %\" PRIu64 \", dbl_res %\" PRIu64 \", dbl %.16f, num %\" PRIu64 \", mul %\" PRIu64 \"\\n\", shift, ms_res, dbl_res, (ldbl_num * ldbl_mul_u64 * ldbl_inv_twoexp).convert_to<double>(), num, mul_u64);\n    }\n    if (std::numeric_limits<uint64_t>::max() - num < increment) break;\n    num += increment;\n    ldbl_num += ldbl_increment;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  multshiftround_u64(num, mul, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c++ style runtime uint64_t shiftround for num on\n * [0, 18446744073709551615] in steps of 34359738367 for\n * approximately 536,870,912 tests.\n * shift should range from 0 to 63.\n */\nvoid test_shiftround_u64_run_cpp(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing shiftround<uint64_t>(num, %u)\\n\", shift);\n  }\n\n  cpp_bin_float_80 ldbl_inv_twoexp = cpp_bin_float_80(1.0) / cpp_bin_float_80(1ull << shift);\n  uint64_t increment = (1ll << 35) - 1ll;\n  cpp_bin_float_80 ldbl_increment(increment);\n  uint64_t num = std::numeric_limits<uint64_t>::lowest();\n  cpp_bin_float_80 ldbl_num(num);\n  while (true)\n  {\n    uint64_t ms_res = shiftround<uint64_t>(num, shift);\n    uint64_t dbl_res = boost::math::round(ldbl_num * ldbl_inv_twoexp).convert_to<uint64_t>();\n    if (ms_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: shiftround<uint64_t>(num, %u): ms_res %\" PRIu64 \", dbl_res %\" PRIu64 \", dbl %.16f, num %\" PRIu64 \"\\n\", shift, ms_res, dbl_res, (ldbl_num * ldbl_inv_twoexp).convert_to<double>(), num);\n    }\n    if (std::numeric_limits<uint64_t>::max() - num < increment) break;\n    num += increment;\n    ldbl_num += ldbl_increment;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  shiftround<uint64_t>(num, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\n/**\n * Test c style runtime uint64_t shiftround for num on\n * [0, 18446744073709551615] in steps of 34359738367 for\n * approximately 536,870,912 tests.\n * shift should range from 0 to 63.\n */\nvoid test_shiftround_u64_run_c(uint8_t shift, size_t thread_index) {\n  std::chrono::high_resolution_clock::time_point test_start = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"testing shiftround_u64(num, %u)\\n\", shift);\n  }\n\n  cpp_bin_float_80 ldbl_inv_twoexp = cpp_bin_float_80(1.0) / cpp_bin_float_80(1ull << shift);\n  uint64_t increment = (1ll << 35) - 1ll;\n  cpp_bin_float_80 ldbl_increment(increment);\n  uint64_t num = std::numeric_limits<uint64_t>::lowest();\n  cpp_bin_float_80 ldbl_num(num);\n  while (true)\n  {\n    uint64_t ms_res = shiftround_u64(num, shift);\n    uint64_t dbl_res = boost::math::round(ldbl_num * ldbl_inv_twoexp).convert_to<uint64_t>();\n    if (ms_res != dbl_res) {\n      std::lock_guard<std::mutex> print_lock(print_mutex);\n      std::printf(\"ERROR: shiftround_u64(num, %u): ms_res %\" PRIu64 \", dbl_res %\" PRIu64 \", dbl %.16f, num %\" PRIu64 \"\\n\", shift, ms_res, dbl_res, (ldbl_num * ldbl_inv_twoexp).convert_to<double>(), num);\n    }\n    if (std::numeric_limits<uint64_t>::max() - num < increment) break;\n    num += increment;\n    ldbl_num += ldbl_increment;\n  }\n\n  std::chrono::high_resolution_clock::time_point test_end = std::chrono::high_resolution_clock::now();\n  {\n    std::lock_guard<std::mutex> print_lock(print_mutex);\n    std::printf(\"  shiftround_u64(num, %u) took %\" PRIu64 \" ms\\n\", shift, static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(test_end-test_start).count()));\n  }\n\n  thread_running[thread_index].store(false);\n}\n\nint main()\n{\n  /**\n   * Result variables for initial quick multiplication and rounding tests.\n   */\n  int8_t msr_i8;\n  uint8_t msr_u8;\n  int16_t msr_i16;\n  uint16_t msr_u16;\n  int32_t msr_i32;\n  uint32_t msr_u32;\n  int64_t msr_i64;\n  uint64_t msr_u64;\n\n  std::printf(\"\\nTesting multiplication operation in multshiftround routines.\\n\");\n\n  for (uint8_t shift = 0u; shift <= 6u; shift++) {\n    uint8_t half_shift = shift >> 1;\n    int8_t result = 1;\n    int8_t num = static_cast<int8_t>(1) << half_shift;\n    if (num < 2) {\n      num = 2;\n      result = 2;\n    }\n    int8_t mul = static_cast<int8_t>(1) << (shift - half_shift);\n    \n    msr_i8 = multshiftround_i8(num, mul, shift);\n    if (msr_i8 != result) std::printf(\"\\nERROR: multshiftround_i8(%i, %i, %u) returned %i. expected %i.\\n\\n\", num, mul, shift, msr_i8, result);\n\n    msr_i8 = multshiftround<int8_t>(num, mul, shift);\n    if (msr_i8 != result) std::printf(\"\\nERROR: multshiftround<int8_t>(%i, %i, %u) returned %i. expected %i.\\n\\n\", num, mul, shift, msr_i8, result);\n  }\n\n  for (uint8_t shift = 0u; shift <= 7u; shift++) {\n    uint8_t half_shift = shift >> 1;\n    uint8_t result = 1u;\n    uint8_t num = static_cast<uint8_t>(1) << half_shift;\n    if (num < 2u) {\n      num = 2u;\n      result = 2u;\n    }\n    uint8_t mul = static_cast<uint8_t>(1) << (shift - half_shift);\n    \n    msr_u8 = multshiftround_u8(num, mul, shift);\n    if (msr_u8 != result) std::printf(\"\\nERROR: multshiftround_u8(%u, %u, %u) returned %u. expected %u.\\n\\n\", num, mul, shift, msr_u8, result);\n\n    msr_u8 = multshiftround<uint8_t>(num, mul, shift);\n    if (msr_u8 != result) std::printf(\"\\nERROR: multshiftround<uint8_t>(%u, %u, %u) returned %u. expected %u.\\n\\n\", num, mul, shift, msr_u8, result);\n  }\n  \n  for (uint8_t shift = 0u; shift <= 14u; shift++) {\n    uint8_t half_shift = shift >> 1;\n    int16_t result = 1;\n    int16_t num = static_cast<int16_t>(1) << half_shift;\n    if (num < 2) {\n      num = 2;\n      result = 2;\n    }\n    int16_t mul = static_cast<int16_t>(1) << (shift - half_shift);\n    \n    msr_i16 = multshiftround_i16(num, mul, shift);\n    if (msr_i16 != result) std::printf(\"\\nERROR: multshiftround_i16(%i, %i, %u) returned %i. expected %i.\\n\\n\", num, mul, shift, msr_i16, result);\n\n    msr_i16 = multshiftround<int16_t>(num, mul, shift);\n    if (msr_i16 != result) std::printf(\"\\nERROR: multshiftround<int16_t>(%i, %i, %u) returned %i. expected %i.\\n\\n\", num, mul, shift, msr_i16, result);\n  }\n\n  for (uint8_t shift = 0u; shift <= 15u; shift++) {\n    uint8_t half_shift = shift >> 1;\n    uint16_t result = 1u;\n    uint16_t num = static_cast<uint16_t>(1) << half_shift;\n    if (num < 2u) {\n      num = 2u;\n      result = 2u;\n    }\n    uint16_t mul = static_cast<uint16_t>(1) << (shift - half_shift);\n    \n    msr_u16 = multshiftround_u16(num, mul, shift);\n    if (msr_u16 != result) std::printf(\"\\nERROR: multshiftround_u16(%u, %u, %u) returned %u. expected %u.\\n\\n\", num, mul, shift, msr_u16, result);\n\n    msr_u16 = multshiftround<uint16_t>(num, mul, shift);\n    if (msr_u16 != result) std::printf(\"\\nERROR: multshiftround<uint16_t>(%u, %u, %u) returned %u. expected %u.\\n\\n\", num, mul, shift, msr_u16, result);\n  }\n\n  for (uint8_t shift = 0u; shift <= 30u; shift++) {\n    uint8_t half_shift = shift >> 1;\n    int32_t result = 1;\n    int32_t num = 1 << half_shift;\n    if (num < 2) {\n      num = 2;\n      result = 2;\n    }\n    int32_t mul = 1 << (shift - half_shift);\n    \n    msr_i32 = multshiftround_i32(num, mul, shift);\n    if (msr_i32 != result) std::printf(\"\\nERROR: multshiftround_i32(%i, %i, %u) returned %i. expected %i.\\n\\n\", num, mul, shift, msr_i32, result);\n\n    msr_i32 = multshiftround<int32_t>(num, mul, shift);\n    if (msr_i32 != result) std::printf(\"\\nERROR: multshiftround<int32_t>(%i, %i, %u) returned %i. expected %i.\\n\\n\", num, mul, shift, msr_i32, result);\n  }\n\n  for (uint8_t shift = 0u; shift <= 31u; shift++) {\n    uint8_t half_shift = shift >> 1;\n    uint32_t result = 1u;\n    uint32_t num = 1u << half_shift;\n    if (num < 2u) {\n      num = 2u;\n      result = 2u;\n    }\n    uint32_t mul = 1u << (shift - half_shift);\n    \n    msr_u32 = multshiftround_u32(num, mul, shift);\n    if (msr_u32 != result) std::printf(\"\\nERROR: multshiftround_u32(%u, %u, %u) returned %u. expected %u.\\n\\n\", num, mul, shift, msr_u32, result);\n\n    msr_u32 = multshiftround<uint32_t>(num, mul, shift);\n    if (msr_u32 != result) std::printf(\"\\nERROR: multshiftround<uint32_t>(%u, %u, %u) returned %u. expected %u.\\n\\n\", num, mul, shift, msr_u32, result);\n  }\n\n  for (uint8_t shift = 0u; shift <= 62u; shift++) {\n    uint8_t half_shift = shift >> 1;\n    int64_t result = 1ll;\n    int64_t num = 1ll << half_shift;\n    if (num < 2ll) {\n      num = 2ll;\n      result = 2ll;\n    }\n    int64_t mul = 1ll << (shift - half_shift);\n    \n    msr_i64 = multshiftround_i64(num, mul, shift);\n    if (msr_i64 != result) std::printf(\"\\nERROR: multshiftround_i64(%\" PRIi64 \", %\" PRIi64 \", %u) returned %\" PRIi64 \". expected %\" PRIi64 \".\\n\\n\", num, mul, shift, msr_i64, result);\n\n    msr_i64 = multshiftround<int64_t>(num, mul, shift);\n    if (msr_i64 != result) std::printf(\"\\nERROR: multshiftround<int64_t>(%\" PRIi64 \", %\" PRIi64 \", %u) returned %\" PRIi64 \". expected %\" PRIi64 \".\\n\\n\", num, mul, shift, msr_i64, result);\n  }\n\n  for (uint8_t shift = 0u; shift <= 63u; shift++) {\n    uint8_t half_shift = shift >> 1;\n    uint64_t result = 1ull;\n    uint64_t num = 1ull << half_shift;\n    if (num < 2ull) {\n      num = 2ull;\n      result = 2ull;\n    }\n    uint64_t mul = 1ull << (shift - half_shift);\n    \n    msr_u64 = multshiftround_u64(num, mul, shift);\n    if (msr_u64 != result) std::printf(\"\\nERROR: multshiftround_u64(%\" PRIu64 \", %\" PRIu64 \", %u) returned %\" PRIu64 \". expected %\" PRIu64 \".\\n\\n\", num, mul, shift, msr_u64, result);\n\n    msr_u64 = multshiftround<uint64_t>(num, mul, shift);\n    if (msr_u64 != result) std::printf(\"\\nERROR: multshiftround<uint64_t>(%\" PRIu64 \", %\" PRIu64 \", %u) returned %\" PRIu64 \". expected %\" PRIu64 \".\\n\\n\", num, mul, shift, msr_u64, result);\n  }\n  \n  std::printf(\"Multiplication tests finished.\\n\\n\");\n  \n  std::printf(\"Running quick tests of rounding operation in multshiftround and shiftround routines.\\n\");\n\n  for (uint8_t shift = 1u; shift <= 6u; shift++) {\n    int8_t num = -(1 << (shift-1u));\n    msr_i8 = multshiftround_i8(num, 1, shift);\n    if (msr_i8 != -1) std::printf(\"\\nERROR: multshiftround_i8(%i, 1, %u) returned %i. expected -1.\\n\\n\", num, shift, msr_i8);\n    msr_i8 = multshiftround<int8_t>(num, 1, shift);\n    if (msr_i8 != -1) std::printf(\"\\nERROR: multshiftround<int8_t>(%i, 1, %u) returned %i. expected -1.\\n\\n\", num, shift, msr_i8);\n\n    num = -(1 << (shift-1u)) + 1;\n    msr_i8 = multshiftround_i8(num, 1, shift);\n    if (msr_i8 != 0) std::printf(\"\\nERROR: multshiftround_i8(%i, 1, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i8);\n    msr_i8 = multshiftround<int8_t>(num, 1, shift);\n    if (msr_i8 != 0) std::printf(\"\\nERROR: multshiftround<int8_t>(%i, 1, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i8);\n\n    num = (1 << (shift-1u)) - 1;\n    msr_i8 = multshiftround_i8(num, 1, shift);\n    if (msr_i8 != 0) std::printf(\"\\nERROR: multshiftround_i8(%i, 1, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i8);\n    msr_i8 = multshiftround<int8_t>(num, 1, shift);\n    if (msr_i8 != 0) std::printf(\"\\nERROR: multshiftround<int8_t>(%i, 1, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i8);\n\n    num = 1 << (shift-1u);\n    msr_i8 = multshiftround_i8(num, 1, shift);\n    if (msr_i8 != 1) std::printf(\"\\nERROR: multshiftround_i8(%i, 1, %u) returned %i. expected 1.\\n\\n\", num, shift, msr_i8);\n    msr_i8 = multshiftround<int8_t>(num, 1, shift);\n    if (msr_i8 != 1) std::printf(\"\\nERROR: multshiftround<int8_t>(%i, 1, %u) returned %i. expected 1.\\n\\n\", num, shift, msr_i8);\n  }\n\n  for (uint8_t shift = 1u; shift <= 14u; shift++) {\n    int16_t num = -(1 << (shift-1u));\n    msr_i16 = multshiftround_i16(num, 1, shift);\n    if (msr_i16 != -1) std::printf(\"\\nERROR: multshiftround_i16(%i, 1, %u) returned %i. expected -1.\\n\\n\", num, shift, msr_i16);\n    msr_i16 = multshiftround<int16_t>(num, 1, shift);\n    if (msr_i16 != -1) std::printf(\"\\nERROR: multshiftround<int16_t>(%i, 1, %u) returned %i. expected -1.\\n\\n\", num, shift, msr_i16);\n\n    num = -(1 << (shift-1u)) + 1;\n    msr_i16 = multshiftround_i16(num, 1, shift);\n    if (msr_i16 != 0) std::printf(\"\\nERROR: multshiftround_i16(%i, 1, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i16);\n    msr_i16 = multshiftround<int16_t>(num, 1, shift);\n    if (msr_i16 != 0) std::printf(\"\\nERROR: multshiftround<int16_t>(%i, 1, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i16);\n\n    num = (1 << (shift-1u)) - 1;\n    msr_i16 = multshiftround_i16(num, 1, shift);\n    if (msr_i16 != 0) std::printf(\"\\nERROR: multshiftround_i16(%i, 1, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i16);\n    msr_i16 = multshiftround<int16_t>(num, 1, shift);\n    if (msr_i16 != 0) std::printf(\"\\nERROR: multshiftround<int16_t>(%i, 1, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i16);\n\n    num = 1 << (shift-1u);\n    msr_i16 = multshiftround_i16(num, 1, shift);\n    if (msr_i16 != 1) std::printf(\"\\nERROR: multshiftround_i16(%i, 1, %u) returned %i. expected 1.\\n\\n\", num, shift, msr_i16);\n    msr_i16 = multshiftround<int16_t>(num, 1, shift);\n    if (msr_i16 != 1) std::printf(\"\\nERROR: multshiftround<int16_t>(%i, 1, %u) returned %i. expected 1.\\n\\n\", num, shift, msr_i16);\n  }\n\n  for (uint8_t shift = 1u; shift <= 30u; shift++) {\n    int32_t num = -(1 << (shift-1u));\n    msr_i32 = multshiftround_i32(num, 1, shift);\n    if (msr_i32 != -1) std::printf(\"\\nERROR: multshiftround_i32(%i, 1, %u) returned %i. expected -1.\\n\\n\", num, shift, msr_i32);\n    msr_i32 = multshiftround<int32_t>(num, 1, shift);\n    if (msr_i32 != -1) std::printf(\"\\nERROR: multshiftround<int32_t>(%i, 1, %u) returned %i. expected -1.\\n\\n\", num, shift, msr_i32);\n\n    num = -(1 << (shift-1u)) + 1;\n    msr_i32 = multshiftround_i32(num, 1, shift);\n    if (msr_i32 != 0) std::printf(\"\\nERROR: multshiftround_i32(%i, 1, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i32);\n    msr_i32 = multshiftround<int32_t>(num, 1, shift);\n    if (msr_i32 != 0) std::printf(\"\\nERROR: multshiftround<int32_t>(%i, 1, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i32);\n\n    num = (1 << (shift-1u)) - 1;\n    msr_i32 = multshiftround_i32(num, 1, shift);\n    if (msr_i32 != 0) std::printf(\"\\nERROR: multshiftround_i32(%i, 1, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i32);\n    msr_i32 = multshiftround<int32_t>(num, 1, shift);\n    if (msr_i32 != 0) std::printf(\"\\nERROR: multshiftround<int32_t>(%i, 1, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i32);\n\n    num = 1 << (shift-1u);\n    msr_i32 = multshiftround_i32(num, 1, shift);\n    if (msr_i32 != 1) std::printf(\"\\nERROR: multshiftround_i32(%i, 1, %u) returned %i. expected 1.\\n\\n\", num, shift, msr_i32);\n    msr_i32 = multshiftround<int32_t>(num, 1, shift);\n    if (msr_i32 != 1) std::printf(\"\\nERROR: multshiftround<int32_t>(%i, 1, %u) returned %i. expected 1.\\n\\n\", num, shift, msr_i32);\n  }\n\n  for (uint8_t shift = 1u; shift <= 62u; shift++) {\n    int64_t num = -(1ll << (shift-1u));\n    msr_i64 = multshiftround_i64(num, 1ll, shift);\n    if (msr_i64 != -1ll) std::printf(\"\\nERROR: multshiftround_i64(%\" PRIi64 \", 1, %u) returned %\" PRIi64 \". expected -1.\\n\\n\", num, shift, msr_i64);\n    msr_i64 = multshiftround<int64_t>(num, 1ll, shift);\n    if (msr_i64 != -1ll) std::printf(\"\\nERROR: multshiftround<int64_t>(%\" PRIi64 \", 1, %u) returned %\" PRIi64 \". expected -1.\\n\\n\", num, shift, msr_i64);\n\n    num = -(1ll << (shift-1u)) + 1ll;\n    msr_i64 = multshiftround_i64(num, 1ll, shift);\n    if (msr_i64 != 0ll) std::printf(\"\\nERROR: multshiftround_i64(%\" PRIi64 \", 1, %u) returned %\" PRIi64 \". expected 0.\\n\\n\", num, shift, msr_i64);\n    msr_i64 = multshiftround<int64_t>(num, 1ll, shift);\n    if (msr_i64 != 0ll) std::printf(\"\\nERROR: multshiftround<int64_t>(%\" PRIi64 \", 1, %u) returned %\" PRIi64 \". expected 0.\\n\\n\", num, shift, msr_i64);\n\n    num = (1ll << (shift-1u)) - 1ll;\n    msr_i64 = multshiftround_i64(num, 1ll, shift);\n    if (msr_i64 != 0ll) std::printf(\"\\nERROR: multshiftround_i64(%\" PRIi64 \", 1, %u) returned %\" PRIi64 \". expected 0.\\n\\n\", num, shift, msr_i64);\n    msr_i64 = multshiftround<int64_t>(num, 1ll, shift);\n    if (msr_i64 != 0ll) std::printf(\"\\nERROR: multshiftround<int64_t>(%\" PRIi64 \", 1, %u) returned %\" PRIi64 \". expected 0.\\n\\n\", num, shift, msr_i64);\n\n    num = 1ll << (shift-1u);\n    msr_i64 = multshiftround_i64(num, 1ll, shift);\n    if (msr_i64 != 1ll) std::printf(\"\\nERROR: multshiftround_i64(%\" PRIi64 \", 1, %u) returned %\" PRIi64 \". expected 1.\\n\\n\", num, shift, msr_i64);\n    msr_i64 = multshiftround<int64_t>(num, 1ll, shift);\n    if (msr_i64 != 1ll) std::printf(\"\\nERROR: multshiftround<int64_t>(%\" PRIi64 \", 1, %u) returned %\" PRIi64 \". expected 1.\\n\\n\", num, shift, msr_i64);\n  }\n\n  for (uint8_t shift = 1u; shift <= 7u; shift++) {\n    uint8_t num = (1u << (shift-1u)) - 1u;\n    msr_u8 = multshiftround_u8(num, 1u, shift);\n    if (msr_u8 != 0u) std::printf(\"\\nERROR: multshiftround_u8(%u, 1, %u) returned %u. expected 0.\\n\\n\", num, shift, msr_u8);\n    msr_u8 = multshiftround<uint8_t>(num, 1u, shift);\n    if (msr_u8 != 0u) std::printf(\"\\nERROR: multshiftround<uint8_t>(%u, 1, %u) returned %u. expected 0.\\n\\n\", num, shift, msr_u8);\n\n    num = 1u << (shift-1u);\n    msr_u8 = multshiftround_u8(num, 1u, shift);\n    if (msr_u8 != 1u) std::printf(\"\\nERROR: multshiftround_u8(%u, 1, %u) returned %u. expected 1.\\n\\n\", num, shift, msr_u8);\n    msr_u8 = multshiftround<uint8_t>(num, 1u, shift);\n    if (msr_u8 != 1u) std::printf(\"\\nERROR: multshiftround<uint8_t>(%u, 1, %u) returned %u. expected 1.\\n\\n\", num, shift, msr_u8);\n  }\n\n  for (uint8_t shift = 1u; shift <= 15u; shift++) {\n    uint16_t num = (1u << (shift-1u)) - 1u;\n    msr_u16 = multshiftround_u16(num, 1u, shift);\n    if (msr_u16 != 0u) std::printf(\"\\nERROR: multshiftround_u16(%u, 1, %u) returned %u. expected 0.\\n\\n\", num, shift, msr_u16);\n    msr_u16 = multshiftround<uint16_t>(num, 1u, shift);\n    if (msr_u16 != 0u) std::printf(\"\\nERROR: multshiftround<uint16_t>(%u, 1, %u) returned %u. expected 0.\\n\\n\", num, shift, msr_u16);\n\n    num = 1u << (shift-1u);\n    msr_u16 = multshiftround_u16(num, 1u, shift);\n    if (msr_u16 != 1u) std::printf(\"\\nERROR: multshiftround_u16(%u, 1, %u) returned %u. expected 1.\\n\\n\", num, shift, msr_u16);\n    msr_u16 = multshiftround<uint16_t>(num, 1u, shift);\n    if (msr_u16 != 1u) std::printf(\"\\nERROR: multshiftround<uint16_t>(%u, 1, %u) returned %u. expected 1.\\n\\n\", num, shift, msr_u16);\n  }\n\n  for (uint8_t shift = 1u; shift <= 31u; shift++) {\n    uint32_t num = (1u << (shift-1u)) - 1u;\n    msr_u32 = multshiftround_u32(num, 1u, shift);\n    if (msr_u32 != 0u) std::printf(\"\\nERROR: multshiftround_u32(%u, 1, %u) returned %u. expected 0.\\n\\n\", num, shift, msr_u32);\n    msr_u32 = multshiftround<uint32_t>(num, 1u, shift);\n    if (msr_u32 != 0u) std::printf(\"\\nERROR: multshiftround<uint32_t>(%u, 1, %u) returned %u. expected 0.\\n\\n\", num, shift, msr_u32);\n\n    num = 1u << (shift-1u);\n    msr_u32 = multshiftround_u32(num, 1u, shift);\n    if (msr_u32 != 1u) std::printf(\"\\nERROR: multshiftround_u32(%u, 1, %u) returned %u. expected 1.\\n\\n\", num, shift, msr_u32);\n    msr_u32 = multshiftround<uint32_t>(num, 1u, shift);\n    if (msr_u32 != 1u) std::printf(\"\\nERROR: multshiftround<uint32_t>(%u, 1, %u) returned %u. expected 1.\\n\\n\", num, shift, msr_u32);\n  }\n\n  for (uint8_t shift = 1u; shift <= 63u; shift++) {\n    uint64_t num = (1ull << (shift-1u)) - 1ull;\n    msr_u64 = multshiftround_u64(num, 1ull, shift);\n    if (msr_u64 != 0ull) std::printf(\"\\nERROR: multshiftround_u64(%\" PRIu64 \", 1, %u) returned %\" PRIu64 \". expected 0.\\n\\n\", num, shift, msr_u64);\n    msr_u64 = multshiftround<uint64_t>(num, 1ull, shift);\n    if (msr_u64 != 0ull) std::printf(\"\\nERROR: multshiftround<uint64_t>(%\" PRIu64 \", 1, %u) returned %\" PRIu64 \". expected 0.\\n\\n\", num, shift, msr_u64);\n\n    num = 1ull << (shift-1u);\n    msr_u64 = multshiftround_u64(num, 1ull, shift);\n    if (msr_u64 != 1ull) std::printf(\"\\nERROR: multshiftround_u64(%\" PRIu64 \", 1, %u) returned %\" PRIu64 \". expected 1.\\n\\n\", num, shift, msr_u64);\n    msr_u64 = multshiftround<uint64_t>(num, 1ull, shift);\n    if (msr_u64 != 1ull) std::printf(\"\\nERROR: multshiftround<uint64_t>(%\" PRIu64 \", 1, %u) returned %\" PRIu64 \". expected 1.\\n\\n\", num, shift, msr_u64);\n  }\n\n  for (uint8_t shift = 1u; shift <= 6u; shift++) {\n    int8_t num = -(1 << (shift-1u));\n    msr_i8 = shiftround_i8(num, shift);\n    if (msr_i8 != -1) std::printf(\"\\nERROR: shiftround_i8(%i, %u) returned %i. expected -1.\\n\\n\", num, shift, msr_i8);\n    msr_i8 = shiftround<int8_t>(num, shift);\n    if (msr_i8 != -1) std::printf(\"\\nERROR: shiftround<int8_t>(%i, %u) returned %i. expected -1.\\n\\n\", num, shift, msr_i8);\n\n    num = -(1 << (shift-1u)) + 1;\n    msr_i8 = shiftround_i8(num, shift);\n    if (msr_i8 != 0) std::printf(\"\\nERROR: shiftround_i8(%i, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i8);\n    msr_i8 = shiftround<int8_t>(num, shift);\n    if (msr_i8 != 0) std::printf(\"\\nERROR: shiftround<int8_t>(%i, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i8);\n\n    num = (1 << (shift-1u)) - 1;\n    msr_i8 = shiftround_i8(num, shift);\n    if (msr_i8 != 0) std::printf(\"\\nERROR: shiftround_i8(%i, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i8);\n    msr_i8 = shiftround<int8_t>(num, shift);\n    if (msr_i8 != 0) std::printf(\"\\nERROR: shiftround<int8_t>(%i, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i8);\n\n    num = 1 << (shift-1u);\n    msr_i8 = shiftround_i8(num, shift);\n    if (msr_i8 != 1) std::printf(\"\\nERROR: shiftround_i8(%i, %u) returned %i. expected 1.\\n\\n\", num, shift, msr_i8);\n    msr_i8 = shiftround<int8_t>(num, shift);\n    if (msr_i8 != 1) std::printf(\"\\nERROR: shiftround<int8_t>(%i, %u) returned %i. expected 1.\\n\\n\", num, shift, msr_i8);\n  }\n\n  for (uint8_t shift = 1u; shift <= 14u; shift++) {\n    int16_t num = -(1 << (shift-1u));\n    msr_i16 = shiftround_i16(num, shift);\n    if (msr_i16 != -1) std::printf(\"\\nERROR: shiftround_i16(%i, %u) returned %i. expected -1.\\n\\n\", num, shift, msr_i16);\n    msr_i16 = shiftround<int16_t>(num, shift);\n    if (msr_i16 != -1) std::printf(\"\\nERROR: shiftround<int16_t>(%i, %u) returned %i. expected -1.\\n\\n\", num, shift, msr_i16);\n\n    num = -(1 << (shift-1u)) + 1;\n    msr_i16 = shiftround_i16(num, shift);\n    if (msr_i16 != 0) std::printf(\"\\nERROR: shiftround_i16(%i, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i16);\n    msr_i16 = shiftround<int16_t>(num, shift);\n    if (msr_i16 != 0) std::printf(\"\\nERROR: shiftround<int16_t>(%i, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i16);\n\n    num = (1 << (shift-1u)) - 1;\n    msr_i16 = shiftround_i16(num, shift);\n    if (msr_i16 != 0) std::printf(\"\\nERROR: shiftround_i16(%i, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i16);\n    msr_i16 = shiftround<int16_t>(num, shift);\n    if (msr_i16 != 0) std::printf(\"\\nERROR: shiftround<int16_t>(%i, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i16);\n\n    num = 1 << (shift-1u);\n    msr_i16 = shiftround_i16(num, shift);\n    if (msr_i16 != 1) std::printf(\"\\nERROR: shiftround_i16(%i, %u) returned %i. expected 1.\\n\\n\", num, shift, msr_i16);\n    msr_i16 = shiftround<int16_t>(num, shift);\n    if (msr_i16 != 1) std::printf(\"\\nERROR: shiftround<int16_t>(%i, %u) returned %i. expected 1.\\n\\n\", num, shift, msr_i16);\n  }\n\n  for (uint8_t shift = 1u; shift <= 30u; shift++) {\n    int32_t num = -(1 << (shift-1u));\n    msr_i32 = shiftround_i32(num, shift);\n    if (msr_i32 != -1) std::printf(\"\\nERROR: shiftround_i32(%i, %u) returned %i. expected -1.\\n\\n\", num, shift, msr_i32);\n    msr_i32 = shiftround<int32_t>(num, shift);\n    if (msr_i32 != -1) std::printf(\"\\nERROR: shiftround<int32_t>(%i, %u) returned %i. expected -1.\\n\\n\", num, shift, msr_i32);\n\n    num = -(1 << (shift-1u)) + 1;\n    msr_i32 = shiftround_i32(num, shift);\n    if (msr_i32 != 0) std::printf(\"\\nERROR: shiftround_i32(%i, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i32);\n    msr_i32 = shiftround<int32_t>(num, shift);\n    if (msr_i32 != 0) std::printf(\"\\nERROR: shiftround<int32_t>(%i, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i32);\n\n    num = (1 << (shift-1u)) - 1;\n    msr_i32 = shiftround_i32(num, shift);\n    if (msr_i32 != 0) std::printf(\"\\nERROR: shiftround_i32(%i, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i32);\n    msr_i32 = shiftround<int32_t>(num, shift);\n    if (msr_i32 != 0) std::printf(\"\\nERROR: shiftround<int32_t>(%i, %u) returned %i. expected 0.\\n\\n\", num, shift, msr_i32);\n\n    num = 1 << (shift-1u);\n    msr_i32 = shiftround_i32(num, shift);\n    if (msr_i32 != 1) std::printf(\"\\nERROR: shiftround_i32(%i, %u) returned %i. expected 1.\\n\\n\", num, shift, msr_i32);\n    msr_i32 = shiftround<int32_t>(num, shift);\n    if (msr_i32 != 1) std::printf(\"\\nERROR: shiftround<int32_t>(%i, %u) returned %i. expected 1.\\n\\n\", num, shift, msr_i32);\n  }\n\n  for (uint8_t shift = 1u; shift <= 62u; shift++) {\n    int64_t num = -(1ll << (shift-1u));\n    msr_i64 = shiftround_i64(num, shift);\n    if (msr_i64 != -1ll) std::printf(\"\\nERROR: shiftround_i64(%\" PRIi64 \", %u) returned %\" PRIi64 \". expected -1.\\n\\n\", num, shift, msr_i64);\n    msr_i64 = shiftround<int64_t>(num, shift);\n    if (msr_i64 != -1ll) std::printf(\"\\nERROR: shiftround<int64_t>(%\" PRIi64 \", %u) returned %\" PRIi64 \". expected -1.\\n\\n\", num, shift, msr_i64);\n\n    num = -(1ll << (shift-1u)) + 1ll;\n    msr_i64 = shiftround_i64(num, shift);\n    if (msr_i64 != 0ll) std::printf(\"\\nERROR: shiftround_i64(%\" PRIi64 \", %u) returned %\" PRIi64 \". expected 0.\\n\\n\", num, shift, msr_i64);\n    msr_i64 = shiftround<int64_t>(num, shift);\n    if (msr_i64 != 0ll) std::printf(\"\\nERROR: shiftround<int64_t>(%\" PRIi64 \", %u) returned %\" PRIi64 \". expected 0.\\n\\n\", num, shift, msr_i64);\n\n    num = (1ll << (shift-1u)) - 1ll;\n    msr_i64 = shiftround_i64(num, shift);\n    if (msr_i64 != 0ll) std::printf(\"\\nERROR: shiftround_i64(%\" PRIi64 \", %u) returned %\" PRIi64 \". expected 0.\\n\\n\", num, shift, msr_i64);\n    msr_i64 = shiftround<int64_t>(num, shift);\n    if (msr_i64 != 0ll) std::printf(\"\\nERROR: shiftround<int64_t>(%\" PRIi64 \", %u) returned %\" PRIi64 \". expected 0.\\n\\n\", num, shift, msr_i64);\n\n    num = 1ll << (shift-1u);\n    msr_i64 = shiftround_i64(num, shift);\n    if (msr_i64 != 1ll) std::printf(\"\\nERROR: shiftround_i64(%\" PRIi64 \", %u) returned %\" PRIi64 \". expected 1.\\n\\n\", num, shift, msr_i64);\n    msr_i64 = shiftround<int64_t>(num, shift);\n    if (msr_i64 != 1ll) std::printf(\"\\nERROR: shiftround<int64_t>(%\" PRIi64 \", %u) returned %\" PRIi64 \". expected 1.\\n\\n\", num, shift, msr_i64);\n  }\n\n  for (uint8_t shift = 1u; shift <= 7u; shift++) {\n    uint8_t num = (1u << (shift-1u)) - 1u;\n    msr_u8 = shiftround_u8(num, shift);\n    if (msr_u8 != 0u) std::printf(\"\\nERROR: shiftround_u8(%u, %u) returned %u. expected 0.\\n\\n\", num, shift, msr_u8);\n    msr_u8 = shiftround<uint8_t>(num, shift);\n    if (msr_u8 != 0u) std::printf(\"\\nERROR: shiftround<uint8_t>(%u, %u) returned %u. expected 0.\\n\\n\", num, shift, msr_u8);\n\n    num = 1u << (shift-1u);\n    msr_u8 = shiftround_u8(num, shift);\n    if (msr_u8 != 1u) std::printf(\"\\nERROR: shiftround_u8(%u, %u) returned %u. expected 1.\\n\\n\", num, shift, msr_u8);\n    msr_u8 = shiftround<uint8_t>(num, shift);\n    if (msr_u8 != 1u) std::printf(\"\\nERROR: shiftround<uint8_t>(%u, %u) returned %u. expected 1.\\n\\n\", num, shift, msr_u8);\n  }\n\n  for (uint8_t shift = 1u; shift <= 15u; shift++) {\n    uint16_t num = (1u << (shift-1u)) - 1u;\n    msr_u16 = shiftround_u16(num, shift);\n    if (msr_u16 != 0u) std::printf(\"\\nERROR: shiftround_u16(%u, %u) returned %u. expected 0.\\n\\n\", num, shift, msr_u16);\n    msr_u16 = shiftround<uint16_t>(num, shift);\n    if (msr_u16 != 0u) std::printf(\"\\nERROR: shiftround<uint16_t>(%u, %u) returned %u. expected 0.\\n\\n\", num, shift, msr_u16);\n\n    num = 1u << (shift-1u);\n    msr_u16 = shiftround_u16(num, shift);\n    if (msr_u16 != 1u) std::printf(\"\\nERROR: shiftround_u16(%u, %u) returned %u. expected 1.\\n\\n\", num, shift, msr_u16);\n    msr_u16 = shiftround<uint16_t>(num, shift);\n    if (msr_u16 != 1u) std::printf(\"\\nERROR: shiftround<uint16_t>(%u, %u) returned %u. expected 1.\\n\\n\", num, shift, msr_u16);\n  }\n\n  for (uint8_t shift = 1u; shift <= 31u; shift++) {\n    uint32_t num = (1u << (shift-1u)) - 1u;\n    msr_u32 = shiftround_u32(num, shift);\n    if (msr_u32 != 0u) std::printf(\"\\nERROR: shiftround_u32(%u, %u) returned %u. expected 0.\\n\\n\", num, shift, msr_u32);\n    msr_u32 = shiftround<uint32_t>(num, shift);\n    if (msr_u32 != 0u) std::printf(\"\\nERROR: shiftround<uint32_t>(%u, %u) returned %u. expected 0.\\n\\n\", num, shift, msr_u32);\n\n    num = 1u << (shift-1u);\n    msr_u32 = shiftround_u32(num, shift);\n    if (msr_u32 != 1u) std::printf(\"\\nERROR: shiftround_u32(%u, %u) returned %u. expected 1.\\n\\n\", num, shift, msr_u32);\n    msr_u32 = shiftround<uint32_t>(num, shift);\n    if (msr_u32 != 1u) std::printf(\"\\nERROR: shiftround<uint32_t>(%u, %u) returned %u. expected 1.\\n\\n\", num, shift, msr_u32);\n  }\n\n  for (uint8_t shift = 1u; shift <= 63u; shift++) {\n    uint64_t num = (1ull << (shift-1u)) - 1ull;\n    msr_u64 = shiftround_u64(num, shift);\n    if (msr_u64 != 0ull) std::printf(\"\\nERROR: shiftround_u64(%\" PRIu64 \", %u) returned %\" PRIu64 \". expected 0.\\n\\n\", num, shift, msr_u64);\n    msr_u64 = shiftround<uint64_t>(num, shift);\n    if (msr_u64 != 0ull) std::printf(\"\\nERROR: shiftround<uint64_t>(%\" PRIu64 \", %u) returned %\" PRIu64 \". expected 0.\\n\\n\", num, shift, msr_u64);\n\n    num = 1ull << (shift-1u);\n    msr_u64 = shiftround_u64(num, shift);\n    if (msr_u64 != 1ull) std::printf(\"\\nERROR: shiftround_u64(%\" PRIu64 \", %u) returned %\" PRIu64 \". expected 1.\\n\\n\", num, shift, msr_u64);\n    msr_u64 = shiftround<uint64_t>(num, shift);\n    if (msr_u64 != 1ull) std::printf(\"\\nERROR: shiftround<uint64_t>(%\" PRIu64 \", %u) returned %\" PRIu64 \". expected 1.\\n\\n\", num, shift, msr_u64);\n  }\n\n  std::printf(\"Quick tests of rounding operation finished.\\n\\n\");\n\n  /**\n   * Test int8_t multshiftround for num on [-128, 127] and shift on [0, 6].\n   */\n  for (uint8_t shift = 0u; shift <= 6u; shift++)\n  {\n    std::printf(\"testing multshiftround<int8_t>(num, mul, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    int8_t num = std::numeric_limits<int8_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      int8_t ms_res = multshiftround<int8_t>(num, mul_i8, shift);\n      int8_t dbl_res = static_cast<int8_t>(std::round(dbl_num * dbl_mul_i8 * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: multshiftround<int8_t>(num, mul, %u): ms_res %i, dbl_res %i, dbl %.16f, num %i, mul %i\\n\", shift, ms_res, dbl_res, dbl_num * dbl_mul_i8 * dbl_inv_twoexp, num, mul_i8);\n      if (num == std::numeric_limits<int8_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test multshiftround_i8 for num on [-128, 127] and shift on [0, 6].\n   */\n  for (uint8_t shift = 0u; shift <= 6u; shift++)\n  {\n    std::printf(\"testing multshiftround_i8(num, mul, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    int8_t num = std::numeric_limits<int8_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      int8_t ms_res = multshiftround_i8(num, mul_i8, shift);\n      int8_t dbl_res = static_cast<int8_t>(std::round(dbl_num * dbl_mul_i8 * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: multshiftround_i8(num, mul, %u): ms_res %i, dbl_res %i, dbl %.16f, num %i, mul %i\\n\", shift, ms_res, dbl_res, dbl_num * dbl_mul_i8 * dbl_inv_twoexp, num, mul_i8);\n      if (num == std::numeric_limits<int8_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test int8_t shiftround for num on [-128, 127] and shift on [0, 6].\n   */\n  for (uint8_t shift = 0u; shift <= 6u; shift++)\n  {\n    std::printf(\"testing shiftround<int8_t>(num, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    int8_t num = std::numeric_limits<int8_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      int8_t ms_res = shiftround<int8_t>(num, shift);\n      int8_t dbl_res = static_cast<int8_t>(std::round(dbl_num * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: shiftround<int8_t>(num, %u): ms_res %i, dbl_res %i, dbl %.16f, num %i\\n\", shift, ms_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n      if (num == std::numeric_limits<int8_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test shiftround_i8 for num on [-128, 127] and shift on [0, 6].\n   */\n  for (uint8_t shift = 0u; shift <= 6u; shift++)\n  {\n    std::printf(\"testing shiftround_i8(num, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    int8_t num = std::numeric_limits<int8_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      int8_t ms_res = shiftround_i8(num, shift);\n      int8_t dbl_res = static_cast<int8_t>(std::round(dbl_num * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: shiftround_i8(num, %u): ms_res %i, dbl_res %i, dbl %.16f, num %i\\n\", shift, ms_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n      if (num == std::numeric_limits<int8_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test int16_t multshiftround for num on [-32768, 32767] and shift on [0, 14].\n   */\n  for (uint8_t shift = 0u; shift <= 14u; shift++)\n  {\n    std::printf(\"testing multshiftround<int16_t>(num, mul, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    int16_t num = std::numeric_limits<int16_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      int16_t ms_res = multshiftround<int16_t>(num, mul_i16, shift);\n      int16_t dbl_res = static_cast<int16_t>(std::round(dbl_num * dbl_mul_i16 * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: multshiftround<int16_t>(num, mul, %u): ms_res %i, dbl_res %i, dbl %.16f, num %i, mul %i\\n\", shift, ms_res, dbl_res, dbl_num * dbl_mul_i16 * dbl_inv_twoexp, num, mul_i16);\n      if (num == std::numeric_limits<int16_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test multshiftround_i16 for num on [-32768, 32767] and shift on [0, 14].\n   */\n  for (uint8_t shift = 0u; shift <= 14u; shift++)\n  {\n    std::printf(\"testing multshiftround_i16(num, mul, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    int16_t num = std::numeric_limits<int16_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      int16_t ms_res = multshiftround_i16(num, mul_i16, shift);\n      int16_t dbl_res = static_cast<int16_t>(std::round(dbl_num * dbl_mul_i16 * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: multshiftround_i16(num, mul, %u): ms_res %i, dbl_res %i, dbl %.16f, num %i, mul %i\\n\", shift, ms_res, dbl_res, dbl_num * dbl_mul_i16 * dbl_inv_twoexp, num, mul_i16);\n      if (num == std::numeric_limits<int16_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test int16_t shiftround for num on [-32768, 32767] and shift on [0, 14].\n   */\n  for (uint8_t shift = 0u; shift <= 14u; shift++)\n  {\n    std::printf(\"testing shiftround<int16_t>(num, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    int16_t num = std::numeric_limits<int16_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      int16_t s_res = shiftround<int16_t>(num, shift);\n      int16_t dbl_res = static_cast<int16_t>(std::round(dbl_num * dbl_inv_twoexp));\n      if (s_res != dbl_res) std::printf(\"ERROR: shiftround<int16_t>(num, %u): s_res %i, dbl_res %i, dbl %.16f, num %i\\n\", shift, s_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n      if (num == std::numeric_limits<int16_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test shiftround_i16 for num on [-32768, 32767] and shift on [0, 14].\n   */\n  for (uint8_t shift = 0u; shift <= 14u; shift++)\n  {\n    std::printf(\"testing shiftround_i16(num, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    int16_t num = std::numeric_limits<int16_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      int16_t s_res = shiftround_i16(num, shift);\n      int16_t dbl_res = static_cast<int16_t>(std::round(dbl_num * dbl_inv_twoexp));\n      if (s_res != dbl_res) std::printf(\"ERROR: shiftround_i16(num, %u): s_res %i, dbl_res %i, dbl %.16f, num %i\\n\", shift, s_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n      if (num == std::numeric_limits<int16_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test uint8_t multshiftround for num on [0, 255] and shift on [0, 7].\n   */\n  for (uint8_t shift = 0u; shift <= 7u; shift++)\n  {\n    std::printf(\"testing multshiftround<uint8_t>(num, mul, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    uint8_t num = std::numeric_limits<uint8_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      uint8_t ms_res = multshiftround<uint8_t>(num, mul_u8, shift);\n      uint8_t dbl_res = static_cast<uint8_t>(std::round(dbl_num * dbl_mul_u8 * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: multshiftround<uint8_t>(num, mul, %u): ms_res %u, dbl_res %u, dbl %.16f, num %u, mul %u\\n\", shift, ms_res, dbl_res, dbl_num * dbl_mul_u8 * dbl_inv_twoexp, num, mul_u8);\n      if (num == std::numeric_limits<uint8_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test multshiftround_u8 for num on [0, 255] and shift on [0, 7].\n   */\n  for (uint8_t shift = 0u; shift <= 7u; shift++)\n  {\n    std::printf(\"testing multshiftround_u8(num, mul, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    uint8_t num = std::numeric_limits<uint8_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      uint8_t ms_res = multshiftround_u8(num, mul_u8, shift);\n      uint8_t dbl_res = static_cast<uint8_t>(std::round(dbl_num * dbl_mul_u8 * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: multshiftround_u8(num, mul, %u): ms_res %u, dbl_res %u, dbl %.16f, num %u, mul %u\\n\", shift, ms_res, dbl_res, dbl_num * dbl_mul_u8 * dbl_inv_twoexp, num, mul_u8);\n      if (num == std::numeric_limits<uint8_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test uint8_t shiftround for num on [0, 255] and shift on [0, 7].\n   */\n  for (uint8_t shift = 0u; shift <= 7u; shift++)\n  {\n    std::printf(\"testing shiftround<uint8_t>(num, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    uint8_t num = std::numeric_limits<uint8_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      uint8_t ms_res = shiftround<uint8_t>(num, shift);\n      uint8_t dbl_res = static_cast<uint8_t>(std::round(dbl_num * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: shiftround<uint8_t>(num, %u): ms_res %u, dbl_res %u, dbl %.16f, num %u\\n\", shift, ms_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n      if (num == std::numeric_limits<uint8_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test shiftround_u8 for num on [0, 255] and shift on [0, 7].\n   */\n  for (uint8_t shift = 0u; shift <= 7u; shift++)\n  {\n    std::printf(\"testing shiftround_u8(num, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    uint8_t num = std::numeric_limits<uint8_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      uint8_t ms_res = shiftround_u8(num, shift);\n      uint8_t dbl_res = static_cast<uint8_t>(std::round(dbl_num * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: shiftround_u8(num, %u): ms_res %u, dbl_res %u, dbl %.16f, num %u\\n\", shift, ms_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n      if (num == std::numeric_limits<uint8_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test uint8_t shiftround for num on [0, 255] and shift on [0, 7].\n   */\n  for (uint8_t shift = 0u; shift <= 7u; shift++)\n  {\n    std::printf(\"testing shiftround<uint8_t>(num, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    uint8_t num = std::numeric_limits<uint8_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      uint8_t ms_res = shiftround<uint8_t>(num, shift);\n      uint8_t dbl_res = static_cast<uint8_t>(std::round(dbl_num * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: shiftround<uint8_t>(num, %u): ms_res %u, dbl_res %u, dbl %.16f, num %u\\n\", shift, ms_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n      if (num == std::numeric_limits<uint8_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test shiftround_u8 for num on [0, 255] and shift on [0, 7].\n   */\n  for (uint8_t shift = 0u; shift <= 7u; shift++)\n  {\n    std::printf(\"testing shiftround_u8(num, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    uint8_t num = std::numeric_limits<uint8_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      uint8_t ms_res = shiftround_u8(num, shift);\n      uint8_t dbl_res = static_cast<uint8_t>(std::round(dbl_num * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: shiftround_u8(num, %u): ms_res %u, dbl_res %u, dbl %.16f, num %u\\n\", shift, ms_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n      if (num == std::numeric_limits<uint8_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test uint16_t multshiftround for num on [0, 65535] and shift on [0, 15].\n   */\n  for (uint8_t shift = 0u; shift <= 15u; shift++)\n  {\n    std::printf(\"testing multshiftround<uint16_t>(num, mul, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    uint16_t num = std::numeric_limits<uint16_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      uint16_t ms_res = multshiftround<uint16_t>(num, mul_u16, shift);\n      uint16_t dbl_res = static_cast<uint16_t>(std::round(dbl_num * dbl_mul_u16 * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: multshiftround<uint16_t>(num, mul, %u): ms_res %u, dbl_res %u, dbl %.16f, num %u, mul %u\\n\", shift, ms_res, dbl_res, dbl_num * dbl_mul_u16 * dbl_inv_twoexp, num, mul_u16);\n      if (num == std::numeric_limits<uint16_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test multshiftround_u16 for num on [0, 65535] and shift on [0, 15].\n   */\n  for (uint8_t shift = 0u; shift <= 15u; shift++)\n  {\n    std::printf(\"testing multshiftround_u16(num, mul, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    uint16_t num = std::numeric_limits<uint16_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      uint16_t ms_res = multshiftround_u16(num, mul_u16, shift);\n      uint16_t dbl_res = static_cast<uint16_t>(std::round(dbl_num * dbl_mul_u16 * dbl_inv_twoexp));\n      if (ms_res != dbl_res) std::printf(\"ERROR: multshiftround_u16(num, mul, %u): ms_res %u, dbl_res %u, dbl %.16f, num %u, mul %u\\n\", shift, ms_res, dbl_res, dbl_num * dbl_mul_u16 * dbl_inv_twoexp, num, mul_u16);\n      if (num == std::numeric_limits<uint16_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test uint16_t shiftround for num on [0, 65535] and shift on [0, 15].\n   */\n  for (uint8_t shift = 0u; shift <= 15u; shift++)\n  {\n    std::printf(\"testing shiftround<uint16_t>(num, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    uint16_t num = std::numeric_limits<uint16_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      uint16_t s_res = shiftround<uint16_t>(num, shift);\n      uint16_t dbl_res = static_cast<uint16_t>(std::round(dbl_num * dbl_inv_twoexp));\n      if (s_res != dbl_res) std::printf(\"ERROR: shiftround<uint16_t>(num, %u): ms_res %u, dbl_res %u, dbl %.16f, num %u\\n\", shift, s_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n      if (num == std::numeric_limits<uint16_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * Test shiftround_u16 for num on [0, 65535] and shift on [0, 15].\n   */\n  for (uint8_t shift = 0u; shift <= 15u; shift++)\n  {\n    std::printf(\"testing shiftround_u16(num, %u)\\n\", shift);\n    double dbl_inv_twoexp = 1.0 / static_cast<double>(1ull << shift);\n    uint16_t num = std::numeric_limits<uint16_t>::lowest();\n    double dbl_num = static_cast<double>(num);\n    while (true)\n    {\n      uint16_t s_res = shiftround_u16(num, shift);\n      uint16_t dbl_res = static_cast<uint16_t>(std::round(dbl_num * dbl_inv_twoexp));\n      if (s_res != dbl_res) std::printf(\"ERROR: shiftround_u16(num, %u): ms_res %u, dbl_res %u, dbl %.16f, num %u\\n\", shift, s_res, dbl_res, dbl_num * dbl_inv_twoexp, num);\n      if (num == std::numeric_limits<uint16_t>::max()) break;\n      num++;\n      dbl_num += 1.0;\n    }\n  }\n  std::printf(\"\\n\");\n\n  /**\n   * vTests stores the list of tests to run multithreaded.\n   * The first pair element function pointer should point to one of the \n   * test_...(uint8_t shift, size_t thread_index) functions.\n   * The second pair element uint8_t is the shift argument value to use\n   * when running the test.\n   */\n  std::vector<std::pair<void (*)(uint8_t, size_t), uint8_t> > vTests;\n\n  /**\n   * Queue all the tests that will be run multithreaded.\n   */\n  for (uint8_t shift = 0u; shift <= 63u; shift++)\n    vTests.push_back(std::make_pair(test_shiftround_u64_run_cpp, shift));\n\n  for (uint8_t shift = 0u; shift <= 63u; shift++)\n    vTests.push_back(std::make_pair(test_shiftround_u64_run_c, shift));\n\n  for (uint8_t shift = 0u; shift <= 63u; shift++)\n    vTests.push_back(std::make_pair(test_multshiftround_u64_run_cpp, shift));\n\n  for (uint8_t shift = 0u; shift <= 63u; shift++)\n    vTests.push_back(std::make_pair(test_multshiftround_u64_run_c, shift));\n\n  for (uint8_t shift = 0u; shift <= 62u; shift++)\n    vTests.push_back(std::make_pair(test_shiftround_i64_run_cpp, shift));\n\n  for (uint8_t shift = 0u; shift <= 62u; shift++)\n    vTests.push_back(std::make_pair(test_shiftround_i64_run_c, shift));\n\n  for (uint8_t shift = 0u; shift <= 62u; shift++)\n    vTests.push_back(std::make_pair(test_multshiftround_i64_run_cpp, shift));\n\n  for (uint8_t shift = 0u; shift <= 62u; shift++)\n    vTests.push_back(std::make_pair(test_multshiftround_i64_run_c, shift));\n\n  for (uint8_t shift = 0u; shift <= 31u; shift++)\n    vTests.push_back(std::make_pair(test_shiftround_u32_run_cpp, shift));\n\n  for (uint8_t shift = 0u; shift <= 31u; shift++)\n    vTests.push_back(std::make_pair(test_shiftround_u32_run_c, shift));\n\n  for (uint8_t shift = 0u; shift <= 31u; shift++)\n    vTests.push_back(std::make_pair(test_multshiftround_u32_run_cpp, shift));\n\n  for (uint8_t shift = 0u; shift <= 31u; shift++)\n    vTests.push_back(std::make_pair(test_multshiftround_u32_run_c, shift));\n\n  for (uint8_t shift = 0u; shift <= 30u; shift++)\n    vTests.push_back(std::make_pair(test_shiftround_i32_run_cpp, shift));\n\n  for (uint8_t shift = 0u; shift <= 30u; shift++)\n    vTests.push_back(std::make_pair(test_shiftround_i32_run_c, shift));\n\n  for (uint8_t shift = 0u; shift <= 30u; shift++)\n    vTests.push_back(std::make_pair(test_multshiftround_i32_run_cpp, shift));\n\n  for (uint8_t shift = 0u; shift <= 30u; shift++)\n    vTests.push_back(std::make_pair(test_multshiftround_i32_run_c, shift));\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  std::printf(\"Starting multithreaded tests with %u threads.\\n\\n\", nThreads);\n\n  /**\n   * Allocate and initialize the atomic bools for checking\n   * when threads are done running tests.\n   */\n  thread_running = new std::atomic<bool>[nThreads];\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    thread_running[jThread].store(false);\n  }\n\n  /**\n   * Start all threads running with some test.\n   */\n  std::vector<std::thread> vThreads;\n  for (uint32_t jThread = 0u; jThread < nThreads && !vTests.empty(); jThread++) {\n    thread_running[jThread].store(true);\n    vThreads.push_back(std::move(std::thread(vTests.back().first, vTests.back().second, jThread)));\n    vTests.pop_back();\n  }\n\n  while (!vTests.empty()) {\n    /**\n     * Replace finished threads with new ones until there are no more\n     * tests to run.\n     */\n    for (size_t jThread = 0ull; jThread < vThreads.size() && !vTests.empty(); jThread++) {\n      if (!thread_running[jThread].load() && vThreads.at(jThread).joinable()) {\n        vThreads.at(jThread).join();\n        thread_running[jThread].store(true);\n        vThreads.at(jThread) = std::move(std::thread(vTests.back().first, vTests.back().second, jThread));\n        vTests.pop_back();\n      }\n    }\n    /**\n     * Sleep so as not to spam the CPU.\n     */\n    std::this_thread::sleep_for(std::chrono::milliseconds(100));\n  }\n\n  /**\n   * Wait until all threads are finished.\n   */\n  bool any_joinable = true;\n  while (any_joinable) {\n    any_joinable = false;\n    for (size_t jThread = 0ull; jThread < vThreads.size(); jThread++) {\n      if (vThreads.at(jThread).joinable()) {\n        any_joinable = true;\n        if (!thread_running[jThread].load())\n          vThreads.at(jThread).join();\n      }\n    }\n    /**\n     * Sleep so as not to spam the CPU.\n     */\n    std::this_thread::sleep_for(std::chrono::milliseconds(100));\n  }\n\n  delete[] thread_running;\n\n  std::printf(\"\\nFinished running multithreaded code.\\n\\n\");\n  std::printf(\"\\n\");\n  std::printf(\"Testing succeeded if there are no errors above.\\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*/\n", "meta": {"hexsha": "2b1e15c5ec5b34435a548e50194688c29859dd7c", "size": 84671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "integer/test_multshiftround_shiftround_run.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_multshiftround_shiftround_run.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_multshiftround_shiftround_run.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": 46.167393675, "max_line_length": 259, "alphanum_fraction": 0.6704184432, "num_tokens": 27862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5342158172773187}}
{"text": "/*\n   This header file defines a set of mathematics utility \n   functions. Additionally, other header files which define\n   further utility functions such as representation transformations,\n   lidar data processing. The user should include this header file\n   to benefit from all the utiity function while keeping in mind\n   the namespace structure.\n */\n\n#ifndef PI\n#define PI 3.14159265359\n#endif\n\n#include <cmath>\n#include <limits>\n#include <vector>\n#include <cassert>\n#include <iostream>\n\n#include <ros/ros.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <nav_msgs/Odometry.h>\n#include <sensor_msgs/Imu.h>\n#include <sensor_msgs/LaserScan.h>\n#include <sensor_msgs/PointCloud2.h>\n\n#include <opencv2/opencv.hpp>\n\n#include \"trans_utils.hh\"\n#include \"laser_utils.hh\"\n#include \"color_utils.hh\"\n\n#include <armadillo>\n\nusing namespace std;\nusing namespace Eigen;\n//using namespace arma;\n\n// Putting this header lock at the beginning of the file prevents\n// including the library headers in the preamble of this file.\n// However functions in the \"trans_utils\" and \"laser_utils\" headers\n// utilizes these libraries.\n\n#ifndef _UTILS_HH_\n#define _UTILS_HH_\n\n// Define new Eigen matrix and vector types\nnamespace Eigen{\n  typedef Eigen::Matrix<double, 6, 6> Matrix6d;\n  typedef Eigen::Matrix<double, 6, 1> Vector6d;\n  typedef Eigen::Matrix<double, 5, 1> Vector5d;\n}\n\nnamespace utils{\n  // This macro provides an efficient way to raise exceptions with\n  // very informative command line messages.\n#define ASSERT(condition, message) \\\n  if (! (condition)) { \\\n    std::cerr << \"Assertion `\" #condition \"` failed in \" << __FILE__ \\\n    << \" line \" << __LINE__ << \": \" << message << std::endl; \\\n    std::exit(EXIT_FAILURE); \\\n  } \\\n\n#define PRINT_FLF {cout << \"File : \" << __FILE__ << \" Line # : \" << __LINE__ << \" Func : \" << __func__ << endl;}\n\n#define SGN(x) ((x) == 0 ? 0 : ((x) < 0 ? -1 : +1))\n\n#define DEBUG_MSGS_ON 0\n#define DEBUG_MSG(text) {if(DEBUG_MSGS_ON){cout << \"DEBUG_MSG : \" << text << endl; fflush(NULL);}}\n\n#ifndef DEG2RAD\n#define DEG2RAD(x) ((x) / 180.0 * PI)\n#endif\n#ifndef RAD2DEG\n#define RAD2DEG(x) ((x) / PI * 180.0)\n#endif\n\nextern std::map<string, ros::Time> __timers__;\n#define TIC(text) {utils::__timers__[(text)] = ros::Time::now();}\n#define TOC(text) {auto it = utils::__timers__.find(text); \\\n                   if(it != utils::__timers__.end()) \\\n                    cout << \"Timer <\" << it->first << \"> : \" << (ros::Time::now() - it->second).toSec() << endl; \\\n                   else \\\n                    cout << \"No timer <\" << (text) << \">\" << endl;}\n\n  // The 'utils' namespace implements utility functions which cannot\n  // be categorized into a specific class of helper routines. However\n  // functions such as rotation transformations and ROS-Eigen data\n  // structure conversions are collected under the 'utils::trans'\n  // namespace in its specific header and source files. Similarly\n  // laser processing routines are grouped under 'utils::laser'\n  // namespace. As new functions are required, they should be added\n  // directly under 'utils' namespace unless they intuitively form\n  // a group/set of functions.\n\n  class Timer{\n    private:\n      ros::Time _start;\n      bool _print_on;\n      string _label;\n    public:\n      Timer(bool print_on = true, string label = \"\"){\n        _print_on = print_on;\n        _label    = label;\n      }\n\n      void tic(){\n        _start = ros::Time::now();\n      }\n\n      void print_on() {_print_on = true ;}\n      void print_off(){_print_on = false;}\n\n      double toc(string sublabel = \"\"){\n        double dt = (ros::Time::now() - _start).toSec();\n        if(_print_on == true)\n          cout << \"<\" << _label << sublabel << \" Time elapsed : \" << dt << \">\" << endl;\n        return dt;\n      }\n  };\n\n  // Clamps the given value in between the extrema\n  inline double clamp(double val, double min, double max){\n    return val > max ? max : val < min ? min : val;\n  }\n\n  /*\n     inline void clamp(double &val, double min, double max){\n     val = val > max ? max : val < min ? min : val;\n     }\n   */\n\n  // This function returns the 2*PI modula shifted by -PI\n  // of an angle in radians\n  inline double fix_angle(double ang){\n    while(ang > PI)\n      ang -= PI;\n    while(ang <= -PI)\n      ang += PI;\n    return ang;\n  }\n\n  inline void fix_angle(double *ang){\n    while(*ang > PI)\n      *ang -= PI;\n    while(*ang <= -PI)\n      *ang += PI;\n  }\n\n  inline void generate_colors(vector<Eigen::Vector3i> &colors){\n    static int temp_colors[] = {\n      0x000000, 0x00FF00, 0x0000FF, 0xFF0000,\n      0x01FFFE, 0xFFA6FE, 0xFFDB66, 0x006401,\n      0x010067, 0x95003A, 0x007DB5, 0xFF00F6,\n      0xFFEEE8, 0x774D00, 0x90FB92, 0x0076FF,\n      0xD5FF00, 0xFF937E, 0x6A826C, 0xFF029D,\n      0xFE8900, 0x7A4782, 0x7E2DD2, 0x85A900,\n      0xFF0056, 0xA42400, 0x00AE7E, 0x683D3B,\n      0xBDC6FF, 0x263400, 0xBDD393, 0x00B917,\n      0x9E008E, 0x001544, 0xC28C9F, 0xFF74A3,\n      0x01D0FF, 0x004754, 0xE56FFE, 0x788231,\n      0x0E4CA1, 0x91D0CB, 0xBE9970, 0x968AE8,\n      0xBB8800, 0x43002C, 0xDEFF74, 0x00FFC6,\n      0xFFE502, 0x620E00, 0x008F9C, 0x98FF52,\n      0x7544B1, 0xB500FF, 0x00FF78, 0xFF6E41,\n      0x005F39, 0x6B6882, 0x5FAD4E, 0xA75740,\n      0xA5FFD2, 0xFFB167, 0x009BFF, 0xE85EBE};\n    colors.clear();\n    colors.resize(64);\n    for(int i = 0 ; i < 64 ; i++){\n      colors[i](0) = (temp_colors[i] & 0xFF0000) >> 16;\n      colors[i](1) = (temp_colors[i] & 0x00FF00) >> 8;\n      colors[i](2) = (temp_colors[i] & 0x0000FF);\n    }\n  }  \n\n  typedef struct Ellipse\n  {\n    arma::vec::fixed<2> center;\n    arma::vec::fixed<2> major_axis;\n    arma::vec::fixed<2> minor_axis;\n    float len_major, len_minor;\n    float theta;\n    bool success;\n  } Ellipse;\n\n  // Output is A = [a b c d e f]' such that 'ax^2 + bxy + cy^2 +dx + ey + f = 0'\n  bool fit_ellipse_ransac(vector<double> &xs, vector<double> &ys, vector<double> &fit, int num_trials = 200);\n  void fit_ellipse(vector<double> &xs, vector<double> &ys, vector<double> &fit);\n  void get_ellipse_parameters(vector<double> &fit, Ellipse &ell);\n\n}\n\n#endif\n\n", "meta": {"hexsha": "d3d60208cd5afb738449bd776f24dbf4ad5379a8", "size": 6096, "ext": "hh", "lang": "C++", "max_stars_repo_path": "utils/include/utils.hh", "max_stars_repo_name": "ozaslan/basics", "max_stars_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_stars_repo_licenses": ["MIT"], "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/include/utils.hh", "max_issues_repo_name": "ozaslan/basics", "max_issues_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_issues_repo_licenses": ["MIT"], "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/include/utils.hh", "max_forks_repo_name": "ozaslan/basics", "max_forks_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_forks_repo_licenses": ["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.6331658291, "max_line_length": 114, "alphanum_fraction": 0.6405839895, "num_tokens": 1911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5342158172773187}}
{"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(MathsFunctions, square) {\n  double y = 2.0;\n  EXPECT_FLOAT_EQ(y * y, stan::math::square(y));\n\n  y = 0.0;\n  EXPECT_FLOAT_EQ(y * y, stan::math::square(y));\n\n  y = -32.7;\n  EXPECT_FLOAT_EQ(y * y, stan::math::square(y));\n}\n\nTEST(MathFunctions, square_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::square(nan));\n}\n", "meta": {"hexsha": "c0c58c6e9a09eb657de464470c266cfa2977d26c", "size": 522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/square_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/square_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/square_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.7272727273, "max_line_length": 68, "alphanum_fraction": 0.6819923372, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5342158134341078}}
{"text": "\ufeff/*! \\file scfloop.cpp\n    \\brief SCF\u3092\u884c\u3046\u30af\u30e9\u30b9\u306e\u5b9f\u88c5\n\n    Copyright \u00a9  2015 @dc1394 All Rights Reserved.\n    This software is released under the BSD 2-Clause License.\n*/\n\n#include \"eigenvaluesearch.h\"\n#include \"normalization.h\"\n#include \"readinputfile.h\"\n#include \"scfloop.h\"\n#include \"simpson.h\"\n#include <iomanip>                              // for std::setw    \n#include <iostream>                             // for std::cout\n#include <stdexcept>                            // for std::runtime_error\n#include <boost/math/constants/constants.hpp>   // for boost::math::constants\n\nnamespace schrac {\n    // #region \u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\n\n    ScfLoop::ScfLoop(std::pair<std::string, bool> const & arg) :\n        PData([this]{ return std::cref(pdata_); }, nullptr),\n        PDiffData([this]{ return std::cref(pdiffdata_); }, nullptr),\n        PEhartree([this]{ return std::cref(ehartree_); }, nullptr),\n        ehartree_(std::nullopt)\n    {\n        ReadInputFile rif(arg);         // \u30d5\u30a1\u30a4\u30eb\u3092\u8aad\u307f\u8fbc\u3080\n        rif.readFile();\n        pdata_ = rif.PData;\n\n        initialize();\n        \n        if (pdata_->chemical_symbol_ == Data::Chemical_Symbol[0]) {\n            pdiffsolver_ = std::make_shared<DiffSolver>(pdata_, pdiffdata_);\n        }\n        else {\n            prho_ = std::make_shared<Rho>(pdiffdata_);\n            pvh_ = std::make_shared<Vhartree>(pdiffdata_->r_mesh_);\n            pdiffsolver_ = std::make_shared<DiffSolver>(pdata_, pdiffdata_, prho_, pvh_);\n        }\n\n        message();\n    }\n\n    // #endregion \u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\n\n    // #region public\u30e1\u30f3\u30d0\u95a2\u6570\n\n    void ScfLoop::message() const\n    {\n        std::cout << pdata_->chemical_symbol_\n            << \"\u539f\u5b50\u306e\"\n            << pdata_->orbital_\n            << \"\u8ecc\u9053\";\n\n        if (pdata_->eq_type_ == Data::Eq_type::DIRAC && pdata_->spin_orbital_ == Data::ALPHA) {\n            std::cout << \"\u3001\u30b9\u30d4\u30f3\u4e0a\u5411\u304d\";\n        }\n        else if (pdata_->eq_type_ == Data::Eq_type::DIRAC && pdata_->spin_orbital_ == Data::BETA) {\n            std::cout << \"\u3001\u30b9\u30d4\u30f3\u4e0b\u5411\u304d\";\n        }\n\n        std::cout << \"\u306e\u6ce2\u52d5\u95a2\u6570\u3068\u56fa\u6709\u5024\u3092\u8a08\u7b97\u3057\u307e\u3059\u3002\\n\";\n    }\n\n    ScfLoop::mypair ScfLoop::operator()()\n    {\n        if (pdata_->chemical_symbol_ == Data::Chemical_Symbol[0]) {\n            return std::make_pair(std::move(pdiffdata_), run());\n        }\n        else {\n            return std::make_pair(std::move(pdiffdata_), scfrun());\n        }\n    }\n\n    // #endregion public\u30e1\u30f3\u30d0\u95a2\u6570\n\n    // #region private\u30e1\u30f3\u30d0\u95a2\u6570\n    \n    bool ScfLoop::check_converge(dvector const & newrho, std::int32_t scfloop)\n    {\n        auto const normrd = std::abs(req_normrd(newrho, prho_->PRho));\n\n        req_hartree_energy(newrho, pvh_->Vhart);\n        std::cout << std::setw(2) << \"Iteration # \"\n            << scfloop\n            << \": NormRD = \" << normrd\n            << \", Energy = \" << req_energy(pdiffdata_->E_)\n            << std::endl;\n\n        return normrd < pdata_->scf_criterion_;\n    }\n\n    void ScfLoop::initialize()\n    {        \n        pdiffdata_ = std::make_shared<DiffData>(pdata_);\n\n        pdiffdata_->r_mesh_.reserve(pdata_->grid_num_ + 1);\n        for (auto i = 0; i <= pdata_->grid_num_; i++) {\n            pdiffdata_->r_mesh_.push_back(std::exp(pdata_->xmin_ + static_cast<double>(i) * pdiffdata_->dx_));\n        }\n    }\n\n    void ScfLoop::make_vhartree()\n    {\n        pdiffsolver_->solve_poisson();\n        pvh_->set_vhartree_boundary_condition(pdata_->Z_);\n        pvh_->vhart_init();\n    }\n\n    void ScfLoop::req_hartree_energy(dvector const & rho, dvector const & vhartree)\n    {\n        dvector u2;\n        u2.reserve(pdata_->grid_num_ + 1);\n        for (auto i = 0; i <= pdata_->grid_num_; i++) {\n            u2.push_back(sqr(pdiffdata_->r_mesh_[i]) * rho[i]);\n        }\n\n        Simpson simpson(pdiffdata_->dx_);\n        ehartree_.emplace(simpson(vhartree, u2, pdiffdata_->r_mesh_, 1));\n    }\n\n    double ScfLoop::req_energy(double eigen) const\n    {\n        return 2.0 * eigen - *ehartree_;\n    }\n\n    double ScfLoop::req_normrd(dvector const & newrho, dvector const & oldrho) const\n    {\n        using namespace boost::math::constants;\n        BOOST_ASSERT(newrho.size() == oldrho.size());\n\n        dvector residual;\n        residual.reserve(newrho.size());\n\n        for (auto i = 0; i <= pdata_->grid_num_; i++) {\n            residual.push_back(newrho[i] - oldrho[i]);\n        }\n\n        Simpson const simpson(pdiffdata_->dx_);\n        return 4.0 * pi<double>() * simpson(residual, residual, pdiffdata_->r_mesh_, 3);\n    }\n\n    dvector ScfLoop::req_newrho(dvector const & rf) const\n    {\n        dvector newrho;\n        newrho.reserve(pdata_->grid_num_ + 1);\n        for (auto i = 0; i <= pdata_->grid_num_; i++) {\n            newrho.push_back(sqr(rf[i]));\n        }\n\n        return newrho;\n    }\n\n    ScfLoop::mymap ScfLoop::run()\n    {\n        EigenValueSearch evs(pdata_, pdiffdata_, prho_, pvh_);\n\n        if (!evs.search()) {\n            throw std::runtime_error(\"\u56fa\u6709\u5024\u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093\u3067\u3057\u305f\u3002\u7d42\u4e86\u3057\u307e\u3059\u3002\");\n        }\n\n        return nomalization(evs.PDiffSolver);\n    }\n\n    ScfLoop::mymap ScfLoop::scfrun()\n    {\n        auto scfloop = 1;\n        ScfLoop::mymap wavefunctions;\n        for (; scfloop <= pdata_->scf_maxiter_; scfloop++) {\n            prho_->init();\n            make_vhartree();\n\n            EigenValueSearch evs(pdata_, pdiffdata_, prho_, pvh_);\n\n            if (!evs.search()) {\n                throw std::runtime_error(\"\u56fa\u6709\u5024\u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093\u3067\u3057\u305f\u3002\u7d42\u4e86\u3057\u307e\u3059\u3002\");\n            }\n\n            wavefunctions = nomalization(evs.PDiffSolver);\n            auto const newrho = req_newrho(wavefunctions.at(\"2 Eigen function\"));\n            if (check_converge(newrho, scfloop)) {\n                break;\n            }\n            prho_->rhomix(newrho);\n        }\n\n        if (scfloop == pdata_->scf_maxiter_) {\n            throw std::runtime_error(\"SCF\u304c\u53ce\u675f\u3057\u307e\u305b\u3093\u3067\u3057\u305f\u3002\u7d42\u4e86\u3057\u307e\u3059\u3002\");\n        }\n\n        return wavefunctions;\n    }\n\n    // #endregion private\u30e1\u30f3\u30d0\u95a2\u6570\n}\n", "meta": {"hexsha": "a4a810ede3d50094c5bc4b84835d67f81c81d277", "size": 5817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/scfloop.cpp", "max_stars_repo_name": "dc1394/Schrac", "max_stars_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-31T23:35:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T07:10:30.000Z", "max_issues_repo_path": "src/scfloop.cpp", "max_issues_repo_name": "dc1394/schrac", "max_issues_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "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/scfloop.cpp", "max_forks_repo_name": "dc1394/schrac", "max_forks_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "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.5279187817, "max_line_length": 110, "alphanum_fraction": 0.5604263366, "num_tokens": 1675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6757646010190477, "lm_q1q2_score": 0.5342124120591106}}
{"text": "\n#include <iostream>\n#include <cmath>\n#include <random>\n#include <stdexcept>\n#include <fstream>\n#include <cstdlib>\n#include <string>\n#include <Eigen/Dense>\n#include \"aggregate_gen_CCA.hpp\"\nusing namespace Eigen;\nusing namespace std;\n\ndefault_random_engine re(random_device{}()); // random seed\n//default_random_engine re; //default fixed seed\nuniform_real_distribution<double> urf {0,1.0};\n\n\nint main(int argc, char *argv[]){\n\n    // argv[0] == program name\n    // argv[1] == num_sph_SA\n    // argv[2] == levels\n    // argv[3] == fractal prefactor kf\n    // argv[4] == fractal dimension Df\n    // argv[5] == error tolerance of attached distance\n\n    double a= {1.0}; // radius of spherule\n    double tol= {1.0e-2}; // error torelance of the distance between attached spherules\n    int num_sph_SA;\n    int levels;\n    double kf;\n    double Df;\n    int num_agg;\n\n    switch (argc)\n    {\n    case 1:\n        // use default parameter_list\n        num_sph_SA= {4}; // number of spherule in aggregate generated given by SA\n        levels= {10}; //number of hierarchical coagulation\n        kf= {1.0}; // fractal prefactor\n        Df= {2.5}; // fractal dimension\n        tol= {1.0e-3}; // error torelance of the distance between attached spherules\n        num_agg= {1}; // number of aggregate\n        break;\n    case 6:\n        // parameter_list from the command line arguments\n        num_sph_SA= atoi(argv[1]); // number of spherule in aggregate generated given by SA\n        levels= atoi(argv[2]); //number of hierarchical coagulation\n        kf= atof(argv[3]); // fractal prefactor\n        Df= atof(argv[4]); // fractal dimension\n        num_agg= atoi(argv[5]); // number of aggregate\n        break;\n    default:\n        runtime_error(\"incorrect parameter_list\");\n        break;\n    }\n\n    cout << \"num_sph_SA: \" << num_sph_SA << endl;\n    cout << \"levels: \" << levels << endl;\n    cout << \"kf: \" << kf << endl;\n    cout << \"Df: \" << Df << endl;\n    cout << \"tol: \" << tol << endl;\n    cout << \"num_agg: \" << num_agg << endl;\n\n    for(int ind_agg=0; ind_agg < num_agg; ++ind_agg){\n      vector<MatrixXd> pos_sph_levels= aggregate_gen_CCA(a,num_sph_SA,levels,kf,Df,tol);\n\n      for(int k=0; k<pos_sph_levels.size(); ++k){\n          int num_sph = num_sph_SA*pow(2,k);\n          cout << \"writing \" << k << \"th level aggregate, num_sph= \" << num_sph << endl;\n          MatrixXd pos_sph  {pos_sph_levels[k]};\n          string oname = \"agg\"+to_string(ind_agg)+\"_N\"+to_string(num_sph)+\"_kf\"+to_string(kf).erase(3)+\"_Df\"+to_string(Df).erase(3)+\".out\";\n          ofstream ost {oname};\n          for(int i=0; i<num_sph; ++i){\n              ost << scientific << showpoint\n               << a << ' '\n               << pos_sph(0,i) << ' '\n               << pos_sph(1,i) << ' '\n               << pos_sph(2,i) << endl;\n          }\n          ost.close();\n      }\n    }\n\n\n\n\n\n\n\n}\n", "meta": {"hexsha": "18bdd37a8376b0607c5bb6501c8bb03a0d9a0206", "size": 2859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aggregate_gen_main.cpp", "max_stars_repo_name": "nmoteki/aggregate_generator", "max_stars_repo_head_hexsha": "93ce7699405ba42e4d4dbdd78d48cdd1db8f3344", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-10-27T08:12:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T14:22:46.000Z", "max_issues_repo_path": "aggregate_gen_main.cpp", "max_issues_repo_name": "nmoteki/aggregate_generator", "max_issues_repo_head_hexsha": "93ce7699405ba42e4d4dbdd78d48cdd1db8f3344", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aggregate_gen_main.cpp", "max_forks_repo_name": "nmoteki/aggregate_generator", "max_forks_repo_head_hexsha": "93ce7699405ba42e4d4dbdd78d48cdd1db8f3344", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-23T09:40:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T20:13:32.000Z", "avg_line_length": 30.414893617, "max_line_length": 139, "alphanum_fraction": 0.5834207765, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5342124105513506}}
{"text": "//\n// Copyright (c) 2018 Sho Hirose\n//\n// Distributed under the MIT License. (See accompanying file LICENSE.txt or copy\n// at https://opensource.org/licenses/MIT)\n//\n#ifndef SOLVER_INTERFACE_HPP\n#define SOLVER_INTERFACE_HPP\n\n#include <Eigen/Core>\n\n/// Interface class to solve a system of linear equation, Ax = b, using Eigen\n/// solvers.\ntemplate <class MatrixType>\nclass solver_interface {\n public:\n  virtual ~solver_interface()                                   = default;\n  virtual void decompose(const Eigen::Ref<const MatrixType>& A) = 0;\n  virtual Eigen::VectorXd solve(const Eigen::Ref<const Eigen::VectorXd>& b) = 0;\n};\n\n#endif\n", "meta": {"hexsha": "b60fc521c1344aea30d6263d81e952b049bce184", "size": 637, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "shohirose/eigen_solvers/solver_interface.hpp", "max_stars_repo_name": "shohirose/qiita", "max_stars_repo_head_hexsha": "ff8548762e1587b17eee32d3733283b8b1cc937b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shohirose/eigen_solvers/solver_interface.hpp", "max_issues_repo_name": "shohirose/qiita", "max_issues_repo_head_hexsha": "ff8548762e1587b17eee32d3733283b8b1cc937b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shohirose/eigen_solvers/solver_interface.hpp", "max_forks_repo_name": "shohirose/qiita", "max_forks_repo_head_hexsha": "ff8548762e1587b17eee32d3733283b8b1cc937b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-15T08:47:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:47:39.000Z", "avg_line_length": 27.6956521739, "max_line_length": 80, "alphanum_fraction": 0.6954474097, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.534212403881513}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed 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#include <boost/hana/comparable/equal_mcd.hpp>\n#include <boost/hana/core/datatype.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/list/instance.hpp>\n#include <boost/hana/logical/logical.hpp>\n\n#include <stdexcept>\n\n\nnamespace boost { namespace hana {\n    struct Function;\n\n    template <typename Domain, typename Codomain, typename F,\n        typename = operators<Comparable>\n    >\n    struct function_type {\n        using hana_datatype = Function;\n\n        Domain dom;\n        Codomain cod;\n        F def;\n\n        friend constexpr auto domain(function_type f)\n        { return f.dom; }\n\n        friend constexpr auto codomain(function_type f)\n        { return f.cod; }\n\n        template <typename X>\n        constexpr auto operator()(X x) const {\n            if (!elem(domain(*this), x))\n                throw std::domain_error{\"use of a hana::function with an argument out of the domain\"};\n            return def(x);\n        }\n    };\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto function = [](auto domain, auto codomain) {\n        return [=](auto definition) {\n            return function_type<decltype(domain), decltype(codomain), decltype(definition)>{\n                domain, codomain, definition\n            };\n        };\n    };\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto frange = [](auto f) {\n        // Note: that would be better handled by a set data structure, but\n        // whatever for now.\n        return foldl(fmap(f, domain(f)), list(), [](auto xs, auto x) {\n            return if_(elem(xs, x), xs, cons(x, xs));\n        });\n    };\n\n\n    template <>\n    struct Comparable::instance<Function, Function> : Comparable::equal_mcd {\n        template <typename F, typename G>\n        static constexpr auto equal_impl(F f, G g) {\n            return domain(f) == domain(g) && all(domain(f), demux(equal, f, g));\n        }\n    };\n}} // end namespace boost::hana\n\n\n// BOOST_HANA_CONSTEXPR_LAMBDA auto is_injective = [](auto f) {\n//     auto check = [](auto x, auto y) {\n//         return (x != y)     ^implies^   (f(x) != f(y));\n//     };\n//     return all(product(domain(f), domain(f)), check);\n// };\n\n// BOOST_HANA_CONSTEXPR_LAMBDA auto is_onto = [](auto f) {\n//     return codomain(f) == range(g);\n// };\n\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/integral.hpp>\n#include <boost/hana/list/instance.hpp>\n#include <boost/hana/range.hpp>\nusing namespace boost::hana;\nusing namespace literals;\n\n\nint main() {\n    auto f = function(list(1_c, 2_c, 3_c), list(1_c, 2_c, 3_c, 4_c, 5_c, 6_c))(\n        [](auto x) { return x + 1_c; }\n    );\n\n    auto g = function(list(1_c, 2_c, 3_c), list(2_c, 3_c, 4_c))(\n        [](auto x) { return x + 1_c; }\n    );\n\n    auto h = function(list(1_c, 2_c, 3_c), list(0_c, 1_c, 2_c))(\n        [](auto x) { return x - 1_c; }\n    );\n\n    BOOST_HANA_CONSTANT_ASSERT(f == g);\n    BOOST_HANA_CONSTANT_ASSERT(f != h);\n    BOOST_HANA_CONSTEXPR_ASSERT(f(1) == 2);\n    try { f(6); throw; } catch (std::domain_error) { }\n\n\n    BOOST_HANA_CONSTANT_ASSERT(frange(f) == list(4_c, 3_c, 2_c));\n    (void)frange;\n}\n", "meta": {"hexsha": "0b8f0a882e4b3e4412bfdeb6bbe95f6ebf014295", "size": 3271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/sandbox/function.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/sandbox/function.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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/sandbox/function.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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.9469026549, "max_line_length": 102, "alphanum_fraction": 0.6086823601, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5342123883952812}}
{"text": "/*! \n * @file\n * Calculating displaced atoms at each frame from a lammps simulation.\n *\n * default run cmd from project directory:\n * `mpirun -n 1 ./bin/displaced \"data/lammps/dump6000.txt\" \"data/lammps/dump.txt\" 3.165\n * \n * ![displaced data-flow](../doc/displaced.png)\n *\n * benchmarks at the bottom\n * */\n#include <array>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <tuple>\n#include <vector>\n#include <boost/unordered_map.hpp>\n\n#include <ezl.hpp>\n#include <ezl/algorithms/predicates.hpp>\n#include <ezl/algorithms/reduces.hpp>\n#include <ezl/algorithms/fromFile.hpp>\n\nauto calcDist(std::array<float, 3> p1, std::array<float, 3> p2) {\n  auto diff = 0.0F;\n  for (auto i : {0, 1, 2}) {\n    diff += (p1[i] - p2[i]) * (p1[i] - p2[i]);\n  }\n  return sqrt(diff);\n}\n\nvoid displaced(int argc, char* argv[]) {\n  using std::vector;\n  using std::tuple;\n  using std::array;\n\n  const std::string outFile = \"data/output/nDisp.txt\";\n  const float toleranceRatio = 0.3;\n  \n  if (argc < 4) {\n    ezl::Karta::inst().print0(\"provide file for 1st time_step, file glob for all frames, \"\n                 \"lattice constant as arguments. Continuing with defaults.\");\n  }\n  std::string firstFile = \"data/lammps/dump6000.txt\";\n  if (argc > 1) firstFile = std::string(argv[1]);\n  std::string allFiles = \"data/lammps/dump.txt\";\n  if (argc > 2) allFiles = std::string(argv[2]);\n  auto latConst = 3.165F;\n  if (argc > 3) latConst = float(std::stof(argv[3]));;\n\n  auto partitionFn = [] (const std::tuple<const int&>& x) -> std::size_t {\n    return std::get<0>(x)/100;\n  };\n\n  // loading first frame atoms in the memory partitioned on atoms-id.\n  auto buffer = ezl::rise(ezl::fromFile<int, array<float, 3>, int>(firstFile)\n                            .cols({1, 3, 4, 5, 6})  // id, coords\n                            .lammps())\n                  .filter(ezl::tautology()).partitionBy<1>().prll(1.)\n                  .get();\n\n  boost::unordered_map<int, array<float, 3>> firstFrame;\n  for(const auto& it :buffer) firstFrame[std::get<0>(it)] = std::get<1>(it);\n\n  ezl::rise(ezl::fromFile<int, array<float, 3>, int>(allFiles)\n                .cols({1, 3, 4, 5, 6}) // id, coords, timestep\n                .lammps())\n      .map<1, 2>([&firstFrame](int id, array<float, 3> coords) {\n        return calcDist(coords, firstFrame[id]);\n      }).partitionBy<1>().prll(1.).colsTransform()\n      .filter<1>(ezl::gt(latConst * toleranceRatio))\n      .reduce<2>(ezl::count(), 0).inprocess()\n      .reduce<1>(ezl::sum(), 0).partitionBy(partitionFn)\n      .reduceAll([](vector<tuple<int, int>> a) {\n        sort(a.begin(), a.end());\n        return a;\n      }).dump(outFile)\n      .run();\n  ezl::Karta::inst().print0(\"Output file written in data/output/disp\");      \n}\n\nint main(int argc, char *argv[]) {\n  // boost::mpi::environment env(argc, argv, false);\n  ezl::Env env{argc, argv, false};\n  try {\n    displaced(argc, argv);\n  } catch (const std::exception& ex) {\n    std::cerr<<\"error: \"<<ex.what()<<'\\n';\n    env.abort(1);  \n  } catch (...) {\n    std::cerr<<\"unknown exception\\n\";\n    env.abort(2);  \n  }\n  return 0;\n}\n\n/*!\n * benchmark results: i7(hdd); input: 25000 atoms/frame (bcc-50x50) 11-frames\n *  *nprocs* | 1   | 2   | 4    |\n *  ---      |---  |---  |---   |\n *  *time(s)*| 46  | 29  | 19   |\n * \n * benchmark results: Linux(nfs-3); input: 25000 atoms/frame (bcc-50x50) 22-frames\n *  *nprocs* | 1x12      | 2x12      |\n *  ---      |---        |---        |\n *  *time(s)*| 169       | 249       |\n */\n", "meta": {"hexsha": "fe9d43fbe1549c136813a6105d9a45d75daeffb9", "size": 3492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/displaced.cpp", "max_stars_repo_name": "haptork/easyLambda", "max_stars_repo_head_hexsha": "2a8cae9c6e26517e301b5aa6f9c1518aa5a22417", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 537.0, "max_stars_repo_stars_event_min_datetime": "2016-03-15T09:26:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T02:44:56.000Z", "max_issues_repo_path": "examples/displaced.cpp", "max_issues_repo_name": "haptork/easyLambda", "max_issues_repo_head_hexsha": "2a8cae9c6e26517e301b5aa6f9c1518aa5a22417", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2016-03-15T11:56:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-14T20:01:47.000Z", "max_forks_repo_path": "examples/displaced.cpp", "max_forks_repo_name": "haptork/easyLambda", "max_forks_repo_head_hexsha": "2a8cae9c6e26517e301b5aa6f9c1518aa5a22417", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2016-03-15T11:53:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-27T02:53:21.000Z", "avg_line_length": 32.0366972477, "max_line_length": 90, "alphanum_fraction": 0.5770332188, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5342123883952812}}
{"text": "// ---------------------------------------------------------\n//\n//  trianglequality.cpp\n//  Tyson Brochu 2011\n//  Christopher Batty, Fang Da 2014\n//\n//  Functions for getting various triangle mesh measures.\n//\n// ---------------------------------------------------------\n\n#include <trianglequality.h>\n\n#include <limits>\n#include <surftrack.h>\n#include <set>\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n// ---------------------------------------------------------\n///\n/// Determine the \"mixed\" voronoi and barycentric area of the vertex within the given triangle.\n///\n// ---------------------------------------------------------\n\nnamespace LosTopos {\n\ndouble mixed_area( size_t vertex_index, size_t triangle_index, const SurfTrack& surf )\n{\n    const Vec3st& tri = surf.m_mesh.get_triangle(triangle_index);\n    \n    Vec2st opposite_edge;\n    if ( vertex_index == tri[0] )\n    {\n        opposite_edge = Vec2st( tri[1], tri[2] );\n    }\n    else if ( vertex_index == tri[1] )\n    {\n        opposite_edge = Vec2st( tri[2], tri[0] );\n    }\n    else\n    {\n        opposite_edge = Vec2st( tri[0], tri[1] );\n    }\n    \n    const Vec3d& a = surf.get_position(vertex_index);\n    const Vec3d& b = surf.get_position(opposite_edge[0]);\n    const Vec3d& c = surf.get_position(opposite_edge[1]);\n    \n    bool obtuse_triangle = ( ( dot(b-a, c-a) < 0.0 ) || ( dot(a-b, c-b) < 0.0 ) || ( dot(a-c, b-c) < 0.0 ) );\n    \n    if ( obtuse_triangle )\n    {\n        //std::cout << \"obtuse_triangle \" << triangle_index << \": \" << tri << std::endl;\n        \n        if ( dot(b-a, c-a) < 0.0 )\n        {\n            // obtuse at a\n            return 0.5 * surf.get_triangle_area( triangle_index );\n        }\n        else\n        {\n            // obtuse somewhere else\n            return 0.25 * surf.get_triangle_area( triangle_index );\n        }\n    }\n    else\n    {\n        // not obtuse, use voronoi area\n        \n        double cross_c = mag( cross( a-c, b-c ) );      \n        double cot_c = dot( a-c, b-c) / cross_c;      \n        \n        double cross_b = mag( cross( a-b, c-b ) );      \n        double cot_b = dot( a-b, c-b) / cross_b;      \n        \n        return 1.0 / 8.0 * (mag2(b-a) * cot_c + mag2(c-a) * cot_b);\n    }\n    \n}\n\n// ---------------------------------------------------------\n///\n/// Get Kappa * n, the surface normal multiplied by mean curvature at the specified vertex.\n///\n// ---------------------------------------------------------\n\nvoid vertex_mean_curvature_normal( size_t vertex_index, const SurfTrack& surf, Vec3d& out, double& weight_sum )\n{\n    Vec3d mean_curvature_normal( 0, 0, 0 );\n    weight_sum = 0;\n    \n    double edge_length_sum = 0.0;\n    \n    for ( size_t i = 0; i < surf.m_mesh.m_vertex_to_edge_map[vertex_index].size(); ++i )\n    {\n        size_t e = surf.m_mesh.m_vertex_to_edge_map[vertex_index][i];\n        const Vec2st& curr_edge = surf.m_mesh.m_edges[e];\n        Vec3d edge_vector;\n        if ( curr_edge[0] == vertex_index )\n        {\n            edge_vector = surf.get_position( curr_edge[1] ) - surf.get_position( vertex_index );\n        }\n        else\n        {\n            assert( curr_edge[1] == vertex_index );\n            edge_vector = surf.get_position( curr_edge[0] ) - surf.get_position( vertex_index );\n        }\n        \n        edge_length_sum += mag( edge_vector );\n        \n        if ( surf.m_mesh.m_edge_to_triangle_map[e].size() != 2 )\n        {\n            // TODO: properly handle more than 2 incident triangles\n            out = Vec3d(0,0,0);\n            return;\n        }\n        \n        size_t tri0 = surf.m_mesh.m_edge_to_triangle_map[e][0];\n        size_t tri1 = surf.m_mesh.m_edge_to_triangle_map[e][1];\n        \n        size_t third_vertex_0 = surf.m_mesh.get_third_vertex( curr_edge[0], curr_edge[1], surf.m_mesh.get_triangle(tri0) );\n        size_t third_vertex_1 = surf.m_mesh.get_third_vertex( curr_edge[0], curr_edge[1], surf.m_mesh.get_triangle(tri1) );\n        \n        Vec3d v00 = surf.get_position( curr_edge[0] ) - surf.get_position( third_vertex_0 );\n        Vec3d v10 = surf.get_position( curr_edge[1] ) - surf.get_position( third_vertex_0 );\n        \n        double cross_0 = mag( cross( v00, v10 ) );\n        if ( cross_0 < 1e-10 )\n        {\n            continue;\n        }\n        double cot_0 = dot(v00, v10) / cross_0;\n        \n        Vec3d v01 = surf.get_position( curr_edge[0] ) - surf.get_position( third_vertex_1 );\n        Vec3d v11 = surf.get_position( curr_edge[1] ) - surf.get_position( third_vertex_1 );\n        \n        double cross_1 = mag( cross( v01, v11 ) );\n        if ( cross_1 < 1e-10 )\n        {\n            continue;\n        }\n        \n        double cot_1 = dot(v01, v11) / cross_1;\n        \n        double weight = cot_0 + cot_1;\n        weight_sum += weight;\n        \n        mean_curvature_normal += weight * edge_vector;\n        \n    }\n    \n    double vertex_area = 0.0;\n    for ( size_t i = 0; i < surf.m_mesh.m_vertex_to_triangle_map[vertex_index].size(); ++i )\n    {\n        vertex_area += mixed_area( vertex_index, surf.m_mesh.m_vertex_to_triangle_map[vertex_index][i], surf );\n    }\n    \n    double coeff = 1.0 / (2.0 * vertex_area);\n    \n    weight_sum *= coeff;\n    \n    out = coeff * mean_curvature_normal;\n    \n}\n\n\n// ---------------------------------------------------------\n///\n/// Return an estimate for mean curvature at the given vertex, computed using the Kappa * n estimate above.\n///\n// ---------------------------------------------------------\n\ndouble unsigned_vertex_mean_curvature( size_t vertex_index, const SurfTrack& surf )\n{\n    Vec3d mc_normal;\n    double weight_sum;\n    \n    vertex_mean_curvature_normal( vertex_index, surf, mc_normal, weight_sum );\n    \n    return mag( mc_normal );\n}\n\n\n// ---------------------------------------------------------\n///\n/// Return an estimate for curvature by computing the minimum radius of a sphere defined by the edge neighbourhood around a vertex,\n/// and taking the reciprocal.\n///\n// ---------------------------------------------------------\n\ndouble inv_min_radius_curvature( const SurfTrack& surf, size_t vertex )\n{\n    \n    Vec3d normal = surf.get_vertex_normal( vertex );\n    \n    //   double min_radius = BIG_DOUBLE;\n    \n    double inv_min_radius = -BIG_DOUBLE;\n    \n    for ( size_t i = 0; i < surf.m_mesh.m_vertex_to_edge_map[vertex].size(); ++i )\n    {\n        size_t edge_index = surf.m_mesh.m_vertex_to_edge_map[vertex][i];\n        \n        assert( edge_index < surf.m_mesh.m_edges.size() );\n        \n        const Vec2st& edge = surf.m_mesh.m_edges[ edge_index ];\n        \n        Vec3d P;\n        if ( edge[0] == vertex )\n        {\n            P = surf.get_position( edge[1] ) - surf.get_position( vertex );\n        }\n        else\n        {\n            P = surf.get_position( edge[0] ) - surf.get_position( vertex );\n        }\n        \n        //      double radius = 0.5 * dot( P, P ) / dot( normal, P );\n        //      min_radius = min( min_radius, radius );\n        \n        double inv_radius = 2.0 * dot( normal, P ) / dot( P, P );\n        inv_min_radius = max( inv_min_radius, inv_radius );\n        \n    }\n    \n    return inv_min_radius;\n    \n}\n\n\n// ---------------------------------------------------------\n///\n/// Compute curvature at a vertex using quadric fitting\n///\n// ---------------------------------------------------------\n\ndouble estimated_max_curvature(const SurfTrack& surf, size_t vertex) {\n    \n    Vec3d normal = surf.get_vertex_normal(vertex);\n\n    Vec3d seed(0,0,0);\n    if(abs(normal[0]) < 0.5)\n        seed[0] = 1.0;\n    else\n        seed[1] = 1.0;\n    Vec3d u = cross(normal, seed);\n    normalize(u);\n    Vec3d v = cross(normal, u);\n\n    std::set<size_t> twoneighbors;\n    twoneighbors.insert(vertex);\n    for(int i=0; i<2; i++)\n    {\n        std::set<size_t> toadd;\n        for(std::set<size_t>::iterator it = twoneighbors.begin(); it != twoneighbors.end(); ++it)\n        {\n            size_t curVert = *it;\n            const std::vector<size_t>& nbrEdges = surf.m_mesh.m_vertex_to_edge_map[curVert];\n            for(unsigned int nbrIdx = 0; nbrIdx < nbrEdges.size(); ++nbrIdx) \n            {\n                size_t edge_id = nbrEdges[nbrIdx];\n                Vec2st edge = surf.m_mesh.m_edges[edge_id];\n                size_t fv = edge[0];\n                if(fv == curVert)\n                    toadd.insert(edge[1]);\n                else\n                    toadd.insert(fv);\n            }\n        }\n        for(std::set<size_t>::iterator it = toadd.begin(); it != toadd.end(); ++it)\n            twoneighbors.insert(*it);\n    }\n\n    \n    int numneighbors = (int)twoneighbors.size();\n    if(numneighbors < 6)\n        return 0;\n    //TODO I havn't fully verified this after porting to Eigen, so user beware!\n\n    //a u^2 + b v^2 + c uv + d u + e v + f\n    Eigen::MatrixXd Mat_Eigen(numneighbors, 6);\n    Eigen::VectorXd Rhs_Eigen(numneighbors);\n    \n    Vec3d centpt = surf.get_position(vertex);\n    int row=0;\n    for(std::set<size_t>::iterator it = twoneighbors.begin(); it != twoneighbors.end(); ++it)\n    {\n        size_t curVert = *it;\n        Vec3d adjpt = surf.get_position(curVert);\n        Vec3d diff;\n        for(int i=0; i<3; i++)\n            diff[i] = adjpt[i]-centpt[i];\n        double uval = dot(diff,u);\n        double vval = dot(diff,v);\n        Rhs_Eigen[row] = dot(diff, normal);\n    \n        Mat_Eigen(row, 0) = uval*uval;\n        Mat_Eigen(row, 1) = vval*vval;\n        Mat_Eigen(row, 2) = uval*vval;\n        Mat_Eigen(row, 3) = uval;\n        Mat_Eigen(row, 4) = vval;\n        Mat_Eigen(row, 5) = 1;\n\n        row++;\n    }\n    assert(row == numneighbors);\n\n    Eigen::VectorXd soln_Eigen = Mat_Eigen.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(Rhs_Eigen);\n\n    std::vector<double> coeffs(6);\n    for(int id = 0; id < 6; ++id) coeffs[id] = Rhs_Eigen[id];\n  \n    double areaElt = sqrt(1+coeffs[3]*coeffs[3]+coeffs[4]*coeffs[4]);\n    Vec3d newnormal = (normal - coeffs[3]*u - coeffs[4]*v) / areaElt;\n\n    double E = 1 + coeffs[3]*coeffs[3];\n    double F = coeffs[3]*coeffs[4];\n    double G = 1 + coeffs[4]*coeffs[4];\n\n    //double fac = normal.dot(newnormal);\n    double L = 2*coeffs[0]/areaElt;\n    double M = coeffs[2]/areaElt;\n    double N = 2*coeffs[1]/areaElt;\n\n    double det = E*G-F*F;\n    if(abs(det) < 1e-6)\n        return 0;\n\n    Mat22d H(L, M, M, N);\n    \n    //LosTopos stores things in column major rather than row major, I believe, hence the transposing\n    Mat33d U(u[0], v[0], normal[0], \n        u[1], v[1], normal[1], \n        u[2], v[2], normal[2]); \n    U = U.transpose();\n\n    Mat32d J(1, 0, coeffs[3], \n             0, 1, coeffs[4]);\n\n\n    J = U*J;\n    \n    Mat22d shapeOperator = 1/areaElt * inverse(J.transpose()*J) * H;\n\n    //now do an eigensolve on the shape operator to find the principal curvatures/directions\n    Eigen::Matrix2d shape_Eigen;\n    shape_Eigen << shapeOperator(0, 0), shapeOperator(0, 1), shapeOperator(1, 0), shapeOperator(1, 1);\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> es;\n    es.compute(shape_Eigen, false);\n    if (es.info() != Eigen::Success) assert(0);\n    auto eigenvalues_Eigen = es.eigenvalues();\n    \n    double max_curvature = max(std::fabs(eigenvalues_Eigen[0]), std::fabs(eigenvalues_Eigen[1]));\n    \n    return max_curvature;\n    \n}\n\n// ---------------------------------------------------------\n///\n/// Compute curvatures at all vertices using inv_min_radius_curvature.\n///\n// ---------------------------------------------------------\n\nvoid compute_vertex_curvatures( const SurfTrack& surf, std::vector<double>& vertex_curvatures )\n{\n    \n    vertex_curvatures.resize( surf.get_num_vertices() );\n    \n    for ( size_t i = 0; i < surf.get_num_vertices(); ++i )\n    {\n        \n        if ( surf.m_mesh.m_is_boundary_vertex[i] ) \n        { \n            vertex_curvatures[i] = 1.0;\n            continue; \n        }\n        \n        vertex_curvatures[i] = inv_min_radius_curvature( surf, i );\n    }   \n}\n\n\n#define USE_INV_MIN_RADIUS\n\n// ---------------------------------------------------------\n///\n/// Get the length of the specified edge, scaled by an estimate of curvature at each of the vertices.\n///\n// ---------------------------------------------------------\n\ndouble get_curvature_scaled_length(const SurfTrack& surf, \n                                   size_t vertex_a, \n                                   size_t vertex_b, \n                                   double min_curvature_multiplier,\n                                   double max_curvature_multiplier,\n                                   double rest_curvature )\n{\n    \n    assert( vertex_a < surf.get_num_vertices() );\n    assert( vertex_b < surf.get_num_vertices() );\n    \n    double length = dist(  surf.get_position( vertex_a ), surf.get_position( vertex_b ) );\n    \n    //std::cout << \"\\n\\nTrue length: \" << length << std::endl;\n#ifdef USE_INV_MIN_RADIUS\n    double curv_a = std::fabs( inv_min_radius_curvature( surf, vertex_a ) );\n#else\n    double curv_a = unsigned_vertex_mean_curvature( vertex_a, surf );\n#endif\n    \n    \n\n    curv_a /= rest_curvature;\n    curv_a = std::max( min_curvature_multiplier, curv_a );\n    curv_a = std::min( max_curvature_multiplier, curv_a );\n    \n    //std::cout << \"Curv a: \" << curv_a << std::endl;\n\n#ifdef USE_INV_MIN_RADIUS\n    double curv_b = std::fabs( inv_min_radius_curvature( surf, vertex_b ) );\n#else\n    double curv_b = unsigned_vertex_mean_curvature( vertex_b, m_surf );\n#endif\n    \n    curv_b /= rest_curvature;\n    curv_b = std::max( min_curvature_multiplier, curv_b );\n    curv_b = std::min( max_curvature_multiplier, curv_b );\n    \n    //std::cout << \"Curv b: \" << curv_b << std::endl;\n\n    length *= 0.5 * ( curv_a + curv_b );\n    \n    //std::cout << \"Multiplier: \" << 0.5*(curv_a+curv_b) << std::endl;\n\n    return length;\n    \n}\n\n\n// ---------------------------------------------------------\n///\n/// Get the length of the specified edge, scaled by an estimate of curvature at each of the vertices.\n///\n// ---------------------------------------------------------\n\ndouble get_edge_curvature(const SurfTrack& surf, \n  size_t vertex_a, \n  size_t vertex_b)\n{\n\n  assert( vertex_a < surf.get_num_vertices() );\n  assert( vertex_b < surf.get_num_vertices() );\n\n#ifdef USE_INV_MIN_RADIUS\n  double curv_a = estimated_max_curvature( surf, vertex_a );\n  //double curv_a = std::fabs( inv_min_radius_curvature( surf, vertex_a ) );\n#else\n  double curv_a = unsigned_vertex_mean_curvature( vertex_a, surf );\n#endif\n\n#ifdef USE_INV_MIN_RADIUS\n  double curv_b = estimated_max_curvature( surf, vertex_b );\n  //double curv_b = std::fabs( inv_min_radius_curvature( surf, vertex_b ) );\n#else\n  double curv_b = unsigned_vertex_mean_curvature( vertex_b, surf );\n#endif\n\n  return max(curv_a, curv_b);//0.5 * ( curv_a + curv_b );\n\n}\n\n\n// ---------------------------------------------------------\n///\n/// Return the minimum triangle area in the specified surface.\n///\n// ---------------------------------------------------------\n\ndouble min_triangle_area( const SurfTrack& surf )\n{\n    double min_area = BIG_DOUBLE;\n    for ( size_t i = 0; i < surf.m_mesh.num_triangles(); ++i )\n    {\n        if ( surf.m_mesh.triangle_is_deleted(i) ) { continue; }\n        if ( surf.triangle_is_all_solid(i) ) { continue; }\n        \n        double area = surf.get_triangle_area(i);\n        min_area = std::min( area, min_area );\n    }\n    \n    return min_area;\n    \n}\n\n\n// ---------------------------------------------------------\n///\n/// Return the minimun triangle angle in the specified surface.\n///\n// ---------------------------------------------------------\n\ndouble min_triangle_angle( const SurfTrack& surf )\n{\n    double min_angle = BIG_DOUBLE;\n    for ( size_t i = 0; i < surf.m_mesh.num_triangles(); ++i )\n    {\n        if ( surf.m_mesh.triangle_is_deleted(i) ) { continue; }\n        \n        const Vec3d& a = surf.get_position( surf.m_mesh.get_triangle(i)[0] );\n        const Vec3d& b = surf.get_position( surf.m_mesh.get_triangle(i)[1] );\n        const Vec3d& c = surf.get_position( surf.m_mesh.get_triangle(i)[2] );\n        \n        double curr_min_angle = min_triangle_angle( a, b, c );\n        \n        min_angle = std::min( curr_min_angle, min_angle );\n    }\n    \n    return min_angle;\n    \n}\n\n\n// ---------------------------------------------------------\n///\n/// Return the maximum triangle angle in the specified surface.\n///\n// ---------------------------------------------------------\n\ndouble max_triangle_angle( const SurfTrack& surf )\n{\n    double max_angle = -BIG_DOUBLE;\n    \n    for ( size_t i = 0; i < surf.m_mesh.num_triangles(); ++i )\n    {\n        if ( surf.m_mesh.triangle_is_deleted(i) ) { continue; }\n        \n        const Vec3d& a = surf.get_position( surf.m_mesh.get_triangle(i)[0] );\n        const Vec3d& b = surf.get_position( surf.m_mesh.get_triangle(i)[1] );\n        const Vec3d& c = surf.get_position( surf.m_mesh.get_triangle(i)[2] );\n        \n        double curr_max_angle = max_triangle_angle( a, b, c );\n        \n        max_angle = std::max( curr_max_angle, max_angle );\n    }\n    \n    return max_angle;\n}   \n\n\n// ---------------------------------------------------------\n///\n/// Count the number of triangle angles below the given threshold.\n///\n// ---------------------------------------------------------\n\nsize_t num_angles_below_threshold( const SurfTrack& surf, double low_threshold )\n{\n    size_t num_small_angles = 0;\n    \n    for ( size_t i = 0; i < surf.m_mesh.num_triangles(); ++i )\n    {\n        if ( surf.m_mesh.triangle_is_deleted(i) ) { continue; }\n        \n        const Vec3d& a = surf.get_position( surf.m_mesh.get_triangle(i)[0] );\n        const Vec3d& b = surf.get_position( surf.m_mesh.get_triangle(i)[1] );\n        const Vec3d& c = surf.get_position( surf.m_mesh.get_triangle(i)[2] );\n        \n        double angle_a, angle_b, angle_c;\n        triangle_angles( a, b, c, angle_a, angle_b, angle_c );\n        \n        if ( angle_a < low_threshold ) { ++num_small_angles; }\n        if ( angle_b < low_threshold ) { ++num_small_angles; }\n        if ( angle_c < low_threshold ) { ++num_small_angles; }\n    }\n    \n    return num_small_angles;\n    \n}\n\n// ---------------------------------------------------------\n///\n/// Count the number of triangle angles above the given threshold.\n///\n// ---------------------------------------------------------\n\nsize_t num_angles_above_threshold( const SurfTrack& surf, double high_threshold )\n{\n    size_t num_large_angles = 0;\n    \n    for ( size_t i = 0; i < surf.m_mesh.num_triangles(); ++i )\n    {\n        if ( surf.m_mesh.triangle_is_deleted(i) ) { continue; }\n        \n        const Vec3d& a = surf.get_position( surf.m_mesh.get_triangle(i)[0] );\n        const Vec3d& b = surf.get_position( surf.m_mesh.get_triangle(i)[1] );\n        const Vec3d& c = surf.get_position( surf.m_mesh.get_triangle(i)[2] );\n        \n        double angle_a, angle_b, angle_c;\n        triangle_angles( a, b, c, angle_a, angle_b, angle_c );\n        \n        if ( angle_a > high_threshold ) { ++num_large_angles; }\n        if ( angle_b > high_threshold ) { ++num_large_angles; }\n        if ( angle_c > high_threshold ) { ++num_large_angles; }\n    }\n    \n    return num_large_angles;\n    \n}\n\n\n// ---------------------------------------------------------\n///\n/// Compute the aspect ratio of the given triangle\n///\n// ---------------------------------------------------------\n\ndouble triangle_aspect_ratio( const SurfTrack& surf, size_t triangle_index )\n{\n    const Vec3st& tri = surf.m_mesh.get_triangle(triangle_index);\n    assert( tri[0] != tri[1] );\n    return triangle_aspect_ratio( surf.get_position(tri[0]), surf.get_position(tri[1]), surf.get_position(tri[2]) );   \n}\n\n// ---------------------------------------------------------\n///\n/// Find the smallest triangle aspect ratio in the given mesh\n///\n// ---------------------------------------------------------\n\ndouble min_triangle_aspect_ratio( const SurfTrack& surf, size_t& output_triangle_index )\n{\n    double min_ratio = std::numeric_limits<double>::max();\n    output_triangle_index = (size_t)~0;\n    \n    for ( size_t i = 0; i < surf.m_mesh.num_triangles(); ++i )\n    {\n        double a_ratio = triangle_aspect_ratio( surf, i );\n        if ( a_ratio < min_ratio )\n        {\n            output_triangle_index = i;\n            min_ratio = a_ratio;\n        }\n    }\n    return min_ratio;\n}\n\n\n// ---------------------------------------------------------\n///\n/// Find the greatest triangle aspect ratio in the given mesh\n///\n// ---------------------------------------------------------\n\ndouble max_triangle_aspect_ratio( const SurfTrack& surf, size_t& output_triangle_index )\n{\n    double max_ratio = -1.0;\n    output_triangle_index = (size_t)~0;\n    \n    for ( size_t i = 0; i < surf.m_mesh.num_triangles(); ++i )\n    {\n        double a_ratio = triangle_aspect_ratio( surf, i );\n        if ( a_ratio > max_ratio )\n        {\n            output_triangle_index = i;\n            max_ratio = a_ratio;\n        }\n    }\n    return max_ratio;\n}\n\n}\n", "meta": {"hexsha": "fdb5f06670f2aaf5c2e2013ec2ff923a1cfcc540", "size": 20951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LosTopos/LosTopos3D/trianglequality.cpp", "max_stars_repo_name": "xchern/MultiTracker", "max_stars_repo_head_hexsha": "06cdad3e1b2e24f1a87de07f64b9aab2807b129e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-10-31T20:51:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T15:56:40.000Z", "max_issues_repo_path": "LosTopos/LosTopos3D/trianglequality.cpp", "max_issues_repo_name": "xchern/MultiTracker", "max_issues_repo_head_hexsha": "06cdad3e1b2e24f1a87de07f64b9aab2807b129e", "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": "LosTopos/LosTopos3D/trianglequality.cpp", "max_forks_repo_name": "xchern/MultiTracker", "max_forks_repo_head_hexsha": "06cdad3e1b2e24f1a87de07f64b9aab2807b129e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-03-19T12:29:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-22T12:04:46.000Z", "avg_line_length": 31.1770833333, "max_line_length": 131, "alphanum_fraction": 0.5385900434, "num_tokens": 5220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5340849610701204}}
{"text": "#include <scitbx/lstbx/normal_equations.h>\n#include <scitbx/constants.h>\n#include <scitbx/array_family/ref_reductions.h>\n#include <scitbx/array_family/simple_io.h>\n#include <boost/lexical_cast.hpp>\n#include <scitbx/random/mersenne_twister.h>\n#include <boost/random/uniform_real.hpp>\n#include <scitbx/random/variate_generator.h>\n#include <tbxx/time_accu.hpp>\n\nusing namespace scitbx::lstbx::normal_equations;\nnamespace af = scitbx::af;\nusing scitbx::constants::pi;\n\ntemplate<typename T, template<typename> class SumOfRank1Updates>\nvoid exercise(int m, int n) {\n  typedef scitbx::boost_random::mt19937 engine_t;\n  typedef boost::uniform_real<T> distribution_t;\n  typedef scitbx::random::variate_generator<engine_t, distribution_t> variate_t;\n\n  engine_t engine(0);\n  distribution_t distribution(-10., 10.);\n  variate_t variate(engine, distribution);\n\n  af::shared<T> grad_yc(n);\n  non_linear_ls_with_separable_scale_factor<T,\n                                            SumOfRank1Updates> nls(n);\n  tbxx::time_accu building, solving;\n  for(int i=0; i<m; i++) {\n    af::ref<T> g = grad_yc.ref();\n    for(int j=0; j<n; j++) g[j] = variate();\n    //SCITBX_EXAMINE(g);\n    T yc = i, yo = 2*i;\n    building.set_mark();\n    nls.add_equation(yc, g, yo, 1.);\n    building.accumulate();\n  }\n  building.set_mark();\n  nls.finalise();\n  building.accumulate();\n  std::cout << \"scale factor = \" << nls.optimal_scale_factor() << \"\\n\";\n  std::cout << \"chi^2 = \" << nls.chi_sq() << \"\\n\";\n  linear_ls<T> step = nls.step_equations();\n  solving.set_mark();\n  step.solve();\n  solving.accumulate();\n  af::const_ref<T> s = step.solution().const_ref();\n  std::cout << \"step = [ \" << s[0];\n  for(int j=1; j<n; j++) {\n    if(j % 50) continue;\n    std::cout << \" .. \" << s[j];\n  }\n  std::cout << \" ]\\n\";\n  std::cout << \"\\n*** \"\n            << 8*sizeof(T) << \"-bit floats, \"\n            << m << \"x\" << n << \", \"\n            << \"building: \" << building.as_double()\n            << \", solving: \" << solving.as_double() << \" ***\\n\";\n}\n\nvoid help() {\n  std::cerr << \"bench [BLAS-2 | BLAS-3] [single | double] #data #parameters\\n\";\n}\n\nint main(int argc, char * argv[]) {\n  using boost::lexical_cast;\n  using boost::bad_lexical_cast;\n\n  if(argc != 5) {\n    help();\n    return 1;\n  }\n  std::string lvl(argv[1]), precision(argv[2]);\n  bool single_precision;\n  if(precision == \"single\") single_precision = true;\n  else if (precision == \"double\") single_precision = false;\n  else {\n    help();\n    return 1;\n  }\n  try {\n    int m = lexical_cast<int>(argv[3]);\n    int n = lexical_cast<int>(argv[4]);\n    if(lvl == \"BLAS-2\") {\n      std::cout << \"Level 2 BLAS implementation\\n\";\n      std::cout << \"===========================\\n\";\n      if(single_precision)\n        exercise<float, scitbx::matrix::sum_of_symmetric_rank_1_updates>(m, n);\n      else\n        exercise<double, scitbx::matrix::sum_of_symmetric_rank_1_updates>(m, n);\n    }\n    else if (lvl == \"BLAS-3\"){\n      std::cout << \"Level 3 BLAS implementation\\n\";\n      std::cout << \"===========================\\n\";\n      if(single_precision)\n        exercise<float, scitbx::matrix::rank_n_update>(m, n);\n      else\n        exercise<double, scitbx::matrix::rank_n_update>(m, n);\n    }\n    else {\n      help();\n      return 1;\n    }\n  }\n  catch(const bad_lexical_cast &) {\n    help();\n    return 1;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "7f85b587482797648d52b3188bca551a16105752", "size": 3329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/lstbx/benchmarks/bench.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/lstbx/benchmarks/bench.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/lstbx/benchmarks/bench.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 29.990990991, "max_line_length": 80, "alphanum_fraction": 0.5995794533, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5340849554999674}}
{"text": "\n// solving A * X = B\n// A symmetric/hermitian positive definite in packed format \n// factor (potrf()) and solve (potrs())\n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/lapack/computational/pptrf.hpp>\n#include <boost/numeric/bindings/lapack/computational/pptri.hpp>\n#include <boost/numeric/bindings/lapack/computational/pptrs.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/symmetric.hpp>\n#include <boost/numeric/bindings/ublas/hermitian.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 float real_t; \ntypedef std::complex<real_t> cmplx_t; \n\ntypedef ublas::matrix<real_t, ublas::column_major> m_t;\ntypedef ublas::matrix<cmplx_t, ublas::column_major> cm_t;\n\ntypedef \n  ublas::symmetric_matrix<real_t, ublas::lower, ublas::column_major> symml_t; \ntypedef \n  ublas::hermitian_matrix<cmplx_t, ublas::lower, ublas::column_major> herml_t; \n\ntypedef \n  ublas::symmetric_matrix<real_t, ublas::upper, ublas::column_major> symmu_t; \ntypedef \n  ublas::hermitian_matrix<cmplx_t, ublas::upper, ublas::column_major> hermu_t; \n\nint main() {\n\n  // for more descriptive comments see ublas_ppsv.cc \n  cout << endl; \n\n  // symmetric \n  cout << \"real symmetric\\n\" << endl; \n\n  size_t n = 5; \n  size_t nrhs = 2; \n  symml_t sal (5, 5);   // symmetric matrix\n  symmu_t sau (5, 5);   // symmetric matrix\n  m_t x (n, nrhs);\n  m_t bl (n, nrhs), bu (n, nrhs);  // RHS matrices\n\n  init_symm (sal, 'l'); \n  init_symm (sau, 'u'); \n\n  print_m (sal, \"sal\"); \n  cout << endl; \n  print_m (sau, \"sau\"); \n  cout << endl; \n\n  for (int i = 0; i < x.size1(); ++i) {\n    x (i, 0) = 1.;\n    x (i, 1) = 2.; \n  }\n  bl = prod (sal, x); \n  bu = prod (sau, x); \n\n  print_m (bl, \"bl\"); \n  cout << endl; \n  print_m (bu, \"bu\"); \n  cout << endl; \n\n  int ierr = lapack::pptrf (sal);  \n  if (!ierr) {\n    symml_t isal (sal);\n    lapack::pptrs (sal, bl); \n    print_m (bl, \"xl\"); \n    cout << endl; \n    lapack::pptri (isal);\n    print_m (isal, \"isal\");\n  }\n  cout << endl; \n\n  ierr = lapack::pptrf (sau);  \n  if (!ierr) {\n    symmu_t isau (sau);\n    lapack::pptrs (sau, bu); \n    print_m (bu, \"xu\"); \n    cout << endl; \n    lapack::pptri (isau);\n    print_m (isau, \"isau\");\n  }\n  cout << endl; \n\n  //////////////////////////////////////////////////////////\n  // hermitian \n  cout << \"\\n==========================================\\n\" << endl; \n  cout << \"complex hermitian\\n\" << endl; \n\n  herml_t hal (3, 3);   // hermitian matrix \n  hermu_t hau (3, 3);   // hermitian matrix\n  cm_t cx (3, 1); \n  cm_t cbl (3, 1), cbu (3, 1);  // RHS\n\n  hal (0, 0) = cmplx_t (25, 0);\n  hal (1, 0) = cmplx_t (-5, 5);\n  hal (1, 1) = cmplx_t (51, 0);\n  hal (2, 0) = cmplx_t (10, -5);\n  hal (2, 1) = cmplx_t (4, 6);\n  hal (2, 2) = cmplx_t (71, 0);\n\n  hau (0, 0) = cmplx_t (25, 0);\n  hau (0, 1) = cmplx_t (-5, -5);\n  hau (0, 2) = cmplx_t (10, 5);\n  hau (1, 1) = cmplx_t (51, 0);\n  hau (1, 2) = cmplx_t (4, -6);\n  hau (2, 2) = cmplx_t (71, 0);\n\n  print_m (hal, \"hal\"); \n  cout << endl; \n  print_m (hau, \"hau\"); \n  cout << endl; \n\n  cm_t cbl2 (3, 2); \n  cbl2 (0, 0) = cmplx_t (60, -55);\n  cbl2 (1, 0) = cmplx_t (34, 58);\n  cbl2 (2, 0) = cmplx_t (13, -152);\n  cbl2 (0, 1) = cmplx_t (70, 10);\n  cbl2 (1, 1) = cmplx_t (-51, 110);\n  cbl2 (2, 1) = cmplx_t (75, 63);\n  cm_t cbu2 (cbl2); \n  print_m (cbl2, \"cbl\"); \n  cout << endl; \n  \n  ierr = lapack::pptrf (hal); \n  if (ierr == 0) {\n    herml_t ihal (hal);\n    lapack::pptrs (hal, cbl2); \n    print_m (cbl2, \"cxl\"); \n    cout << endl; \n    lapack::pptri (ihal);\n    print_m (ihal, \"ihal\");\n  }\n  else \n    cout << \"matrix is not positive definite: ierr = \" \n         << ierr << endl << endl; \n  cout << endl; \n\n  ierr = lapack::pptrf (hau); \n  if (ierr == 0) {\n    hermu_t ihau (hau);\n    ierr = lapack::pptrs (hau, cbu2); \n    print_m (cbu2, \"cxu\"); \n    cout << endl; \n    lapack::pptri (ihau);\n    print_m (ihau, \"ihau\");\n  }\n  else \n    cout << \"matrix is not positive definite: ierr = \" \n         << ierr << endl << endl; \n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "92280a9bbb8eb303275821d1fc0ba000e63030ff", "size": 4144, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_pptrf_pptrs.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_pptrf_pptrs.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_pptrf_pptrs.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.8143712575, "max_line_length": 79, "alphanum_fraction": 0.5678088803, "num_tokens": 1594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5340415243206389}}
{"text": "#include <cmath>\n#include <armadillo>\n\n#include \"double_pendulum.hpp\"\n\n/*\n* Default constructor for a system with two identical pendulums of size (20, 200), uniforn weight distribution (cenmter of mass at (10, 100))\n* and initial thetas of 90\u00ba with respect to the downward vertical position.\n* The pivots are placed so that both the pivots the center of mass are colinear (one at the top, the other at the bottom of pendulum 1).\n*/\nDoublePendulum::DoublePendulum() {\n\n    gravity = 9.81;\n\n    theta1 = M_PI / 2;\n    theta2 = M_PI / 2;\n\n    R1Length = 200;\n    R2Length = 200;\n\n    m1 = 10;\n    m2 = 10;\n\n    R1 = { R1Length * sin(theta1), -R1Length * cos(theta1) };\n    R2 = { R2Length * sin(theta2), -R2Length * cos(theta2) };\n\n    // Offset of the pivot (y axis)\n    double offset = 15;\n\n    // Place pivots exactly at the pendulum's x axis center, and respecting the offset in the y axis\n    P1 = { R1Length * 0.05, offset };\n    P2 = { R1Length * 0.05, R1Length - offset };\n\n    L1 = { fabs(P1[0] - P2[0]), fabs(P1[1] - P2[1]) };\n    L1Length = arma::norm(L1);\n\n    X1 = { R1Length * 0.1 / 2, R1Length / 2 };\n    X2 = L1 + R2;\n\n    phi = acos(arma::dot(L1, R1) / (arma::norm(L1) * arma::norm(R1)));\n\n    X1 = R1;\n    X2 = L1 + R2;\n\n    I1 = 0;\n    I2 = 0;\n\n    sf::Color colorGray(128, 128, 128);\n\n    // Initialize graphical elements that represent the system\n    pend1.setSize(sf::Vector2f(R1Length * 0.1, R1Length));\n    pend1.setOrigin(P1[0], P1[1]);\n    pend1.setFillColor(colorGray);\n    pend1.setPosition(1280 / 2, 720 / 2);\n    pend1.setOutlineColor(sf::Color::Black);\n    pend1.setOutlineThickness(2);\n\n    pivot1.setRadius(3);\n    pivot1.setOutlineThickness(1.25);\n    pivot1.setFillColor(colorGray);\n    pivot1.setOutlineColor(sf::Color::Black);\n    pivot1.setOrigin(pivot1.getRadius(), pivot1.getRadius());\n\n    pivot2.setRadius(3);\n    pivot2.setOutlineThickness(1.25);\n    pivot2.setFillColor(colorGray);\n    pivot2.setOutlineColor(sf::Color::Black);\n    pivot2.setOrigin(pivot2.getRadius(), pivot2.getRadius());\n\n    pend2.setSize(sf::Vector2f(R2Length * 0.1, R2Length));\n    pend2.setOrigin(P2[0], R1Length - P2[1]);\n    pend2.setFillColor(colorGray);\n    pend2.setOutlineColor(sf::Color::Black);\n    pend2.setOutlineThickness(2);\n\n}\n\nvoid DoublePendulum::draw(sf::RenderWindow *window) {\n    \n    // Change positions according to attributes\n    pend1.setRotation(-theta1 * 180 / M_PI); // Negative angles to match the references' illustration\n    pend2.setRotation(-theta2 * 180 / M_PI);\n    pivot1.setPosition(pend1.getTransform().transformPoint(P1[0], P1[1]));\n    pivot2.setPosition(pend1.getTransform().transformPoint(P2[0], P2[1]));\n    pend2.setPosition(pend1.getTransform().transformPoint(P2[0], P2[1]));\n\n    // Draw new state on `window`\n    window->draw(pend1);\n    window->draw(pend2);\n    window->draw(pivot1);\n    window->draw(pivot2);\n}\n", "meta": {"hexsha": "978fb16fb323e1bd45dd364020f463b2d14f3837", "size": 2872, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/double_pendulum.cpp", "max_stars_repo_name": "vcoutasso/Double-Pendulum", "max_stars_repo_head_hexsha": "cce43003eea9ceec3f36d522e00f12ecf0ef5ebc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T20:21:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T20:21:58.000Z", "max_issues_repo_path": "src/double_pendulum.cpp", "max_issues_repo_name": "vcoutasso/Double-Pendulum", "max_issues_repo_head_hexsha": "cce43003eea9ceec3f36d522e00f12ecf0ef5ebc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/double_pendulum.cpp", "max_forks_repo_name": "vcoutasso/Double-Pendulum", "max_forks_repo_head_hexsha": "cce43003eea9ceec3f36d522e00f12ecf0ef5ebc", "max_forks_repo_licenses": ["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.8817204301, "max_line_length": 141, "alphanum_fraction": 0.6556406685, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5340415239524079}}
{"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/Core>\n#include <Eigen/Cholesky>\n#include \"metro/ModifiedCholesky.hpp\"\n\n// #define DEBUG 1\n\nAUTO_TEST_CASE( test_modified_cholesky_positive_definite ) {\n\ttypedef Eigen::VectorXd Vector ;\n\ttypedef Eigen::MatrixXd Matrix ;\n    metro::ModifiedCholesky< Matrix > comp ;\n\tEigen::LDLT< Matrix > ldlt ;\n\tMatrix const identity = Matrix::Identity( 2, 2 ) ;\n\n\t\n\t{\n\t\tMatrix const identity = Matrix::Identity( 1, 1 ) ;\n\t\tMatrix test( 1, 1 ) ;\n\t\ttest << 1 ;\n\t\tcomp.compute( test ) ;\n\t\tldlt.compute( test ) ;\n\t\tBOOST_CHECK_EQUAL( comp.matrixP() * identity, ldlt.transpositionsP() * identity ) ;\n\t\tBOOST_CHECK_EQUAL( comp.vectorD(), ldlt.vectorD() ) ;\n\t\tBOOST_CHECK_EQUAL( comp.matrixL() * identity, ldlt.matrixL() * identity ) ;\n\t\tBOOST_CHECK_EQUAL( comp.solve( identity ) * test, identity ) ;\n\t}\n\n\t{\n\t\tMatrix test( 2, 2 ) ;\n\t\ttest << 1, 0, 0, 1 ;\n\t\tcomp.compute( test ) ;\n\t\tldlt.compute( test ) ;\n\t\tBOOST_CHECK_EQUAL( comp.matrixP() * identity, ldlt.transpositionsP() * identity ) ;\n\t\tBOOST_CHECK_EQUAL( comp.vectorD(), ldlt.vectorD() ) ;\n\t\tBOOST_CHECK_EQUAL( comp.matrixL() * identity, ldlt.matrixL() * identity ) ;\n\t\tBOOST_CHECK_EQUAL( comp.solve( identity ) * test, identity ) ;\n\t}\n\n\t{\n\t\tMatrix test( 2, 2 ) ;\n\t\ttest << 1, 0.5, 0.5, 1 ;\n\t\tcomp.compute( test ) ;\n\t\tldlt.compute( test ) ;\n\t\tBOOST_CHECK_EQUAL( comp.matrixP() * identity, ldlt.transpositionsP() * identity ) ;\n\t\tBOOST_CHECK_EQUAL( comp.vectorD(), ldlt.vectorD() ) ;\n\t\tBOOST_CHECK_EQUAL( comp.matrixL() * identity, ldlt.matrixL() * identity ) ;\n\t\tBOOST_CHECK_EQUAL( comp.solve( identity ) * test, identity ) ;\n\t}\n}\n\nAUTO_TEST_CASE( test_modified_cholesky_nonpositive_definite ) {\n\ttypedef Eigen::VectorXd Vector ;\n\ttypedef Eigen::MatrixXd Matrix ;\n    metro::ModifiedCholesky< Matrix > comp ;\n\tEigen::LDLT< Matrix > ldlt ;\n\n\tMatrix const identity = Matrix::Identity( 2, 2 ) ;\n\n\tMatrix test( 2, 2 ) ;\n\ttest << 1, 2, 2, 1 ;\n\n\t{\n\t\tdouble offs[9] = { 0, 0.5, 0.9, 0.99, 1.0, 1.01, 1.05, 1.1, 2 } ;\n\t\tfor( std::size_t i = 0; i < 9; ++i ) {\n\t\t\ttest(0,1) = test(1,0) = offs[i] ;\n\t\t\tcomp.compute( test ) ;\n\t\t\tBOOST_CHECK_EQUAL( comp.matrixP() * identity, identity ) ;\n\t\t\t// Diagonal should be strictly positive.\n\t\t\tfor( int j = 0; j < 2; ++j ) {\n\t\t\t\tTEST_ASSERT( comp.vectorD()(j) >= std::numeric_limits< double >::epsilon() ) ;\n\t\t\t}\n\n#if DEBUG\n\t\t\tstd::cerr << \"---------\\n\" ;\n\t\t\tstd::cerr << \"test_modified_cholesky_nonpositive_definite(): off-diagonal = \" << test(0,1) << \",\\n\" ;\n\t\t\tstd::cerr << \"test_modified_cholesky_nonpositive_definite(): original matrix is:\\n\"\n\t\t\t\t<< test << \".\\n\" ;\n#endif\n\t\t\tMatrix reconstructed = comp.matrixL() * Matrix( Vector( comp.vectorD() ).asDiagonal() ) * comp.matrixL().transpose() ;\n#if DEBUG\n\t\t\tstd::cerr << \"test_modified_cholesky_nonpositive_definite(): reconstructed matrix is:\\n\"\n\t\t\t\t<< reconstructed << \".\\n\" ;\n#endif\n\t\t\t// Modified cholesky is cholesky of a modified matrix with additions of +ve elements\n\t\t\t// to the diagonal.  Check changes are +ve\n\t\t\tBOOST_CHECK( (reconstructed.diagonal() - test.diagonal()).minCoeff() >= 0 ) ;\n\t\t\t// Check that diagonal changes are within error bound\n\t\t\t// (as in Fang & Leary (2006), formula (3)):\n\t\t\tdouble const beta = std::sqrt( std::max( 1.0, offs[i] / std::sqrt( test.rows() * test.rows() - 1 )) ) ;\n\t\t\tdouble const errorBound = (\n\t\t\t\tstd::pow( offs[i] / beta + ( test.rows() - 1.0 ) * beta, 2 )\n\t\t\t\t\t+ 2 * ( test.diagonal().maxCoeff() + ( test.rows() - 1.0 ) * beta*beta )\n\t\t\t\t\t+ std::numeric_limits< double >::epsilon()\n\t\t\t) ;\n\t\t\tBOOST_CHECK( (reconstructed.diagonal() - test.diagonal()).maxCoeff() <= errorBound ) ;\n#if DEBUG\n\t\t\tstd::cerr << \"test_modified_cholesky_nonpositive_definite(): bound is \" << errorBound << \".\\n\" ;\n#endif\t\t\t\n\t\t\t// Check that error is confined to diagonal\n\t\t\t{\n\t\t\t\tMatrix a = reconstructed.triangularView< Eigen::UnitLower >() ;\n\t\t\t\tMatrix b = test.triangularView< Eigen::UnitLower >() ;\n\t\t\t\tMatrix c = reconstructed.triangularView< Eigen::UnitUpper >() ;\n\t\t\t\tMatrix d = test.triangularView< Eigen::UnitUpper >() ;\n\t\t\t\tBOOST_CHECK( a == b ) ;\n\t\t\t\tBOOST_CHECK( c == d ) ;\n\t\t\t}\n\t\t\t\t\n\t\t\tif( test(0,1) < 1.0 ) {\n\t\t\t\t// Matrix is +ve definite, we should be able to reconstruct original matrix exactly\n\t\t\t\tBOOST_CHECK( (reconstructed.diagonal() - test.diagonal()).minCoeff() == 0 ) ;\n\t\t\t\tMatrix solved = comp.solve( identity ) ;\n\t\t\t\tBOOST_CHECK_EQUAL( solved * test, identity ) ;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nAUTO_TEST_CASE( test_modified_cholesky_special_test_cases ) {\n\ttypedef Eigen::VectorXd Vector ;\n\ttypedef Eigen::MatrixXd Matrix ;\n\tEigen::LDLT< Matrix > ldlt ;\n\n\tMatrix const identity = Matrix::Identity( 2, 2 ) ;\n\n\tMatrix test( 4, 4 ) ;\n\t\n\t// This is a problematic 4x4 matrix identified by Schnabel and Eskow.\n\t// It is discussed in section 6.2 of Fang & Leary (2006), who list\n\t// its smallest eigenvalue as -0.378 and the maximum error / min eigenvalue\n\t// as 2.733 for the GMW method.\n\ttest <<\n\t\t 1890.3, -1705.6, -315.8,  3000.3,\n\t\t-1705.6,  1538.3,  284.9, -2706.6,\n\t\t -315.8,   284.9,   52.5,  -501.2,\n\t\t 3000.3, -2706.6, -501.2,  4760.8 ;\n\n\t{\n\t\tmetro::ModifiedCholesky< Matrix > comp ;\n\t\tcomp.compute( test ) ;\n\t\t\n\t\t// Check diagonal is strictly positive.\n\t\tfor( int j = 0; j < 2; ++j ) {\n\t\t\tTEST_ASSERT( comp.vectorD()(j) >= std::numeric_limits< double >::epsilon() ) ;\n\t\t}\n\n#if DEBUG\n\t\tstd::cerr << \"---------\\n\" ;\n\t\tstd::cerr << \"test_modified_cholesky_special_test_cases(): off-diagonal = \" << test(0,1) << \",\\n\" ;\n\t\tstd::cerr << \"test_modified_cholesky_special_test_cases(): original matrix is:\\n\"\n\t\t\t<< test << \".\\n\" ;\n#endif\n\t\tMatrix reconstructed =\n\t\t\tcomp.matrixL()\n\t\t\t* Matrix( Vector( comp.vectorD() ).asDiagonal() )\n\t\t\t* comp.matrixL().transpose() ;\n#if DEBUG\n\t\tstd::cerr << \"test_modified_cholesky_special_test_cases(): reconstructed matrix (1) is:\\n\"\n\t\t\t<< reconstructed << \".\\n\" ;\n#endif\n\t\treconstructed = comp.matrixP().transpose() * reconstructed ;\n#if DEBUG\n\t\tstd::cerr << \"test_modified_cholesky_special_test_cases(): reconstructed matrix (2) is:\\n\"\n\t\t\t<< reconstructed << \".\\n\" ;\n#endif\n\t\treconstructed = reconstructed * comp.matrixP() ;\n#if DEBUG\n\t\tstd::cerr << \"test_modified_cholesky_special_test_cases(): reconstructed matrix (full) is:\\n\"\n\t\t\t<< reconstructed << \".\\n\" ;\n\t\tstd::cerr << \"test_modified_cholesky_special_test_cases(): permutation matrix is:\\n\"\n\t\t\t<< ( comp.matrixP() * Matrix::Identity( test.rows(), test.rows() ) ) << \".\\n\" ;\n#endif\t\t\n\t\t// Modified cholesky is cholesky of a modified matrix with additions of +ve elements\n\t\t// to the diagonal.  Check changes are +ve\n\t\tBOOST_CHECK( (reconstructed.diagonal() - test.diagonal()).minCoeff() >= 0 ) ;\n\t\t// Check that diagonal changes are within error bound\n\t\t// (as in Fang & Leary (2006), formula (3)):\n\t\tdouble const beta = std::sqrt( std::max( 4760.8, 3000.3 / std::sqrt( test.rows() * test.rows() - 1 )) ) ;\n\t\tdouble const errorBound = (\n\t\t\tstd::pow( 3000.3 / beta + ( test.rows() - 1.0 ) * beta, 2 )\n\t\t\t\t+ 2 * ( 4760.8 + ( test.rows() - 1.0 ) * beta*beta )\n\t\t\t\t+ std::numeric_limits< double >::epsilon()\n\t\t) ;\n\t\tdouble const fangLearyR2 = 2.7335 ; // Add 0.0005 for rounding\n\t\tMatrix const E = reconstructed - test ;\n#if DEBUG\n\t\tstd::cerr << \"test_modified_cholesky_special_test_cases(): bound is \" << errorBound << \", predicted r2 is: \" << fangLearyR2 << \"\\n\" ;\n\t\tstd::cerr << \"test_modified_cholesky_special_test_cases(): max error is \" << E.maxCoeff() << \".\\n\" ;\n#endif\n\t\tBOOST_CHECK( E.maxCoeff() <= errorBound ) ;\n\t\tBOOST_CHECK( E.maxCoeff() / 0.3780759 <= fangLearyR2 ) ;\n\t\t\n\t\t// Check that error is confined to diagonal\n\t\t{\n\t\t\tMatrix a = reconstructed.triangularView< Eigen::UnitLower >() ;\n\t\t\tMatrix b = test.triangularView< Eigen::UnitLower >() ;\n\t\t\tMatrix c = reconstructed.triangularView< Eigen::UnitUpper >() ;\n\t\t\tMatrix d = test.triangularView< Eigen::UnitUpper >() ;\n\t\t\tBOOST_CHECK( (a - b).array().abs().maxCoeff() < 1E-9 ) ;\n\t\t\tBOOST_CHECK( (c - d).array().abs().maxCoeff() < 1E-9 ) ;\n\t\t}\n\t}\n}\n\n\n", "meta": {"hexsha": "43b821bde6c223e927ce1c90da90e8d5ac09ce1e", "size": 8197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metro/test/test_modified_cholesky.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_cholesky.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_cholesky.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": 37.9490740741, "max_line_length": 135, "alphanum_fraction": 0.6459680371, "num_tokens": 2553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5340415239524078}}
{"text": "//\n// Created by chen-tian on 7/26/17.\n//\n\n#include \"EdgeSE3ProjectDirect.h\"\n#include <Eigen/Core>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/types/sba/types_sba.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n\n\nusing namespace cv;\nusing namespace g2o;\n\nEdgeSE3ProjectDirect::EdgeSE3ProjectDirect(Eigen::Vector3d point, float fx, float fy, float cx, float cy, Mat *image)\n        :x_world_( point ), fx_( fx ), fy_( fy ), cx_( cx ), cy_(cy), image_(image) {};\n\nvoid EdgeSE3ProjectDirect::computeError()\n{\n    const VertexSE3Expmap* v = static_cast<const VertexSE3Expmap*> (_vertices[0]);\n    Eigen::Vector3d x_local = v->estimate().map( x_world_ );\n    float x = x_local[0]*fx_/x_local[2] + cx_;\n    float y = x_local[1]*fy_/x_local[2] + cy_;\n    //check x,y is in the image\n    if ( x-4<0 || (x+4)>image_->cols || (y-4)<0 || (y+4)>image_->rows )\n    {\n        _error( 0, 0 ) = 0.0;\n        this->setLevel(1);\n    }\n\n    else\n    {\n        _error( 0,0 ) = getPixelValue(x, y) - _measurement;\n    }\n\n    //plus in manifold\n}\n\nvoid EdgeSE3ProjectDirect::linearizeOplus()\n{\n    if ( level() == 1 )\n    {\n        _jacobianOplusXi = Eigen::Matrix< double , 1, 6>::Zero();\n        return;\n    }\n\n    VertexSE3Expmap* vtx = static_cast<VertexSE3Expmap*>(_vertices[0] );\n    Eigen::Vector3d xyz_trans = vtx->estimate().map( x_world_ ); //q in book\n\n    double x = xyz_trans[0];\n    double y = xyz_trans[1];\n    double invz = 1.0/xyz_trans[2];\n    double invz_2 = invz*invz;\n\n    float u = x*fx_*invz + cx_;\n    float v = y*fy_*invz + cy_;\n\n    //jacobian from se3 to u,v\n    //NOTE that in g2o the Lie algebra is(\\omega, \\epsilon), where \\omega is so(3) and \\epsilon the transilation\n\n    Eigen::Matrix<double, 2, 6> jacobian_uv_ksai;\n\n    jacobian_uv_ksai ( 0,0 ) = - x*y*invz_2 *fx_;\n    jacobian_uv_ksai ( 0,1 ) = ( 1+ ( x*x*invz_2 ) ) *fx_;\n    jacobian_uv_ksai ( 0,2 ) = - y*invz *fx_;\n    jacobian_uv_ksai ( 0,3 ) = x*invz *fx_;\n    jacobian_uv_ksai ( 0,4 ) = 0;\n    jacobian_uv_ksai ( 0,5 ) = - x*invz_2 *fx_;\n\n    jacobian_uv_ksai ( 1,0 ) = - ( 1+y*y*invz_2 ) *fy_;\n    jacobian_uv_ksai ( 1,1 ) = ( 1+ ( x*x*invz_2 ) ) *fx_;\n    jacobian_uv_ksai ( 1,2 ) = x*invz *fx_;\n    jacobian_uv_ksai ( 1,3 ) = 0;\n    jacobian_uv_ksai ( 1,4 ) = - invz *fy_;\n    jacobian_uv_ksai ( 1,5 ) = -y*invz_2*fy_;\n\n    Eigen::Matrix<double, 1, 2> jacobian_pixel_uv;\n\n\n    jacobian_pixel_uv ( 0,0 ) = ( getPixelValue( u+1,v )-getPixelValue(u-1,v))/2;\n    jacobian_pixel_uv ( 0,1 ) = ( getPixelValue( u,v+1 )-getPixelValue(u,v-1))/2;\n\n    _jacobianOplusXi = jacobian_pixel_uv*jacobian_uv_ksai;\n}\n\n//Bilinear interpolation\ninline float EdgeSE3ProjectDirect::getPixelValue(float x, float y)\n{\n    uchar* data = & image_->data[ int ( y ) * image_->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[ image_->step ] +\n            xx*yy*data[image_->step+1]\n    );\n}", "meta": {"hexsha": "8c02c1ab8e38d3e755a0661fb790821c3a8deb79", "size": 3004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch8_VO2/src/EdgeSE3ProjectDirect.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": "ch8_VO2/src/EdgeSE3ProjectDirect.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": "ch8_VO2/src/EdgeSE3ProjectDirect.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": 30.6530612245, "max_line_length": 117, "alphanum_fraction": 0.603861518, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5340415132227916}}
{"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_ASECD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASECD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing asecd capabilities\n\n     inverse secant in degree.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = asecd(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r =  acosd(rec(x));;\n    @endcode\n\n    @see asec\n\n  **/\n  const boost::dispatch::functor<tag::asecd_> asecd = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/asecd.hpp>\n#include <boost/simd/function/simd/asecd.hpp>\n\n#endif\n", "meta": {"hexsha": "89b5dc7cd909131473829c83f11042b755727a4a", "size": 1077, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/asecd.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/asecd.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/asecd.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": 21.1176470588, "max_line_length": 100, "alphanum_fraction": 0.5673166202, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.534041512854561}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// CircularSector.cc\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//      Generates a triangle mesh of a unit square with a circular sector cut\n//      out. By default the circle is defined by the 2-norm, but a different\n//      p-norm can be chosen by the optional p argument.\n*/ \n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Company:  New York University\n//  Created:  10/19/2015 13:59:08\n////////////////////////////////////////////////////////////////////////////////\n#include <Triangulate.h>\n#include <MeshIO.hh>\n#include <iostream>\n\n#include <cmath>\n\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n\nusing namespace MeshIO;\nusing namespace std;\nnamespace po = boost::program_options;\n\n\nvoid usage(int exitVal, const po::options_description &visible_opts) {\n    cerr << \"Usage: CircularSector.cc [options] mesh\" << endl;\n    cerr << visible_opts << endl;\n    exit(exitVal);\n}\n\npo::variables_map parseCmdLine(int argc, const char *argv[])\n{\n    po::options_description hidden_opts(\"Hidden Arguments\");\n    hidden_opts.add_options()\n        (\"outMesh\",       po::value<string>(),                     \"output mesh\")\n        ;\n    po::positional_options_description p;\n    p.add(\"outMesh\",                1);\n\n    po::options_description visible_opts;\n\n    visible_opts.add_options()(\"help\", \"Produce this help message\")\n        (\"sector,s\",  po::value<size_t>(),                       \"Angular size of sector in units of 2PI/nsubdiv (defaults to full circle)\")\n        (\"radius,r\",  po::value<double>()->default_value(0.5),   \"Hole radius in (0, 1)\")\n        (\"nsubdiv,n\", po::value<size_t>()->default_value(64),    \"Number of circle subdivisions\")\n        (\"area,a\",    po::value<double>()->default_value(0.001), \"Minimum triangle area (for meshing)\")\n        (\"pnorm,p\",   po::value<double>()->default_value(2),     \"Which lp norm to use in defining circle\")\n        (\"centerx,x\", po::value<double>()->default_value(0),     \"Allows reloation of 'center' point of sector\")\n        (\"centery,y\", po::value<double>()->default_value(0),     \"Allows reloation of 'center' point of sector\")\n        (\"skip,S\",    po::value<size_t>()->default_value(0),     \"number of vertices to skip clockwise and counterclockwise of start (hack to get shape with single reentrant corner)\")\n        ;\n\n    po::options_description cli_opts;\n    cli_opts.add(visible_opts).add(hidden_opts);\n\n    po::variables_map vm;\n    try {\n        po::store(po::command_line_parser(argc, argv).\n                  options(cli_opts).positional(p).run(), vm);\n        po::notify(vm);\n    }\n    catch (std::exception &e) {\n        cerr << \"Error: \" << e.what() << endl << endl;\n        usage(1, visible_opts);\n    }\n\n    bool fail = false;\n    if (vm.count(\"outMesh\") == 0) {\n        cerr << \"Error: must specify output mesh\" << endl;\n        fail = true;\n    }\n\n    if (fail || vm.count(\"help\"))\n        usage(fail, visible_opts);\n\n    return vm;\n}\n\nint main(int argc, const char *argv[])\n{\n    po::variables_map args = parseCmdLine(argc, argv);\n\n    vector<IOVertex> holes, outVertices;\n    vector<IOElement> outTriangles;\n\n    // Create the square\n    vector<IOVertex> inVertices = { {-1, -1, 0},\n                                    { 1, -1, 0},\n                                    { 1,  1, 0},\n                                    {-1,  1, 0} };\n    vector<pair<size_t, size_t>> inEdges = { {0, 1}, {1, 2}, {2, 3}, {3, 0} };\n\n    size_t nsubdivs = args[\"nsubdiv\"].as<size_t>();\n    double radius = args[\"radius\"].as<double>();\n    double p = args[\"pnorm\"].as<double>();\n    double degreesPerSubdiv = 2 * M_PI / nsubdivs;\n    size_t holeBoundarySegments = nsubdivs; // default to a full circle\n    if (args.count(\"sector\"))\n        holeBoundarySegments = args[\"sector\"].as<size_t>();\n\n    size_t firstHoleVertex = inVertices.size();\n    size_t nskip = args[\"skip\"].as<size_t>();\n    // Add the hole if it exists (at least one hole segment).\n    if (holeBoundarySegments > 0) {\n        inVertices.emplace_back(radius, 0);\n        // Add all segments 1..holeBoundarySegments, but if we're drawing a full\n        // circle (holeBoundarySegments == nsubdivs), omit the last segment\n        for (size_t i = 1 + nskip; i <= (size_t) std::max(int(holeBoundarySegments) - int(nskip), 0) && i < nsubdivs; ++i) {\n            double theta = degreesPerSubdiv * i;\n            // https://www.mathworks.com/matlabcentral/newsreader/view_thread/279050\n            double x = radius * copysign(pow(fabs(cos(theta)), 2 / p), cos(theta)),\n                   y = radius * copysign(pow(fabs(sin(theta)), 2 / p), sin(theta));\n            inVertices.emplace_back(x, y);\n            inEdges.push_back({inVertices.size() - 2,\n                               inVertices.size() - 1});\n        }\n        // If it's not a full circle, we need to add the point at the origin and\n        // a segment to it.\n        if (holeBoundarySegments < nsubdivs) {\n            inVertices.emplace_back(args[\"centerx\"].as<double>(), args[\"centery\"].as<double>());\n            inEdges.push_back({inVertices.size() - 2, inVertices.size() - 1});\n        }\n\n        // Close the path (draw the last segment in the full circle case, or\n        // the last sector edge in the sector case).\n        inEdges.push_back({inVertices.size() - 1, firstHoleVertex});\n\n        // Pick a point in the hole: the first segment forms a triangle with the\n        // origin that lies entirely within the hole. Choose its barycenter.\n        holes.emplace_back(((1 / 3.0) * (inVertices.at(firstHoleVertex    ).point +\n                                         inVertices.at(firstHoleVertex + 1).point)).eval());\n    }\n    // If there's a full circle (except for \"skips\"), report the corner angle at\n    // the first vertex.\n    if (holeBoundarySegments == nsubdivs) {\n        auto p1 = inVertices.at(firstHoleVertex).point;\n        auto p2 = inVertices.at(firstHoleVertex + 1).point;\n        auto p3 = inVertices.back().point;\n        VectorND<3> e1(p3 - p1), e2(p2 - p1);\n        double angle = acos(e1.dot(e2) / (e1.norm() * e2.norm()));\n        std::cerr << \"corner angle:\\t\" << angle * (180.0 / M_PI) << std::endl;\n    }\n    // // Remove holes ourselves--if we have triangle do it, it won't subdivide the\n    // // hole boundary...\n    // holes.clear();\n\n    // triangulatePSLC(inVertices, inEdges, holes, outVertices, outTriangles, args[\"area\"].as<double>(), \"Y\");\n    triangulatePSLC(inVertices, inEdges, holes, outVertices, outTriangles, args[\"area\"].as<double>(), \"Q\");\n    save(args[\"outMesh\"].as<string>(), outVertices, outTriangles);\n\n    return 0;\n}\n", "meta": {"hexsha": "62b6d2afb2dfd5501bffe8d00477def7e3a64674", "size": 6734, "ext": "cc", "lang": "C++", "max_stars_repo_path": "experiments/circular_sector_homog/CircularSector.cc", "max_stars_repo_name": "pbedenbaugh/MeshFEM", "max_stars_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T10:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:41:50.000Z", "max_issues_repo_path": "experiments/circular_sector_homog/CircularSector.cc", "max_issues_repo_name": "pbedenbaugh/MeshFEM", "max_issues_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-01T15:58:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:31:09.000Z", "max_forks_repo_path": "experiments/circular_sector_homog/CircularSector.cc", "max_forks_repo_name": "pbedenbaugh/MeshFEM", "max_forks_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T09:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T03:02:39.000Z", "avg_line_length": 43.4451612903, "max_line_length": 183, "alphanum_fraction": 0.5794475794, "num_tokens": 1697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5340415074897529}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2006 - 2020 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: Wolfgang Bangerth, Texas A&M University, 2006 \n */ \n\n\n// @sect3{Include files}  \n\n// \u6211\u4eec\u4ece\u901a\u5e38\u7684\u5404\u79cd\u5404\u6837\u7684\u5305\u542b\u6587\u4ef6\u5f00\u59cb\uff0c\u6211\u4eec\u5728\u4ee5\u524d\u7684\u8bb8\u591a\u6d4b\u8bd5\u4e2d\u90fd\u770b\u5230\u8fc7\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n\n#include <deal.II/lac/vector.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\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_q.h> \n\n#include <deal.II/numerics/data_out.h> \n\n#include <fstream> \n#include <iostream> \n\n// \u8fd9\u91cc\u662f\u4ec5\u6709\u7684\u4e09\u4e2a\u6709\u4e00\u4e9b\u65b0\u5174\u8da3\u7684\u5305\u542b\u6587\u4ef6\u3002\u7b2c\u4e00\u4e2a\u6587\u4ef6\u5df2\u7ecf\u88ab\u4f7f\u7528\u4e86\uff0c\u4f8b\u5982\uff0c\u7528\u4e8e VectorTools::interpolate_boundary_values \u548c MatrixTools::apply_boundary_values \u51fd\u6570\u3002\u7136\u800c\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u8be5\u7c7b\u4e2d\u7684\u53e6\u4e00\u4e2a\u51fd\u6570\uff0c VectorTools::project \u6765\u8ba1\u7b97\u6211\u4eec\u7684\u521d\u59cb\u503c\uff0c\u4f5c\u4e3a\u8fde\u7eed\u521d\u59cb\u503c\u7684 $L^2$ \u6295\u5f71\u3002\u6b64\u5916\uff0c\u6211\u4eec\u4f7f\u7528  VectorTools::create_right_hand_side  \u6765\u751f\u6210\u79ef\u5206  $(f^n,\\phi^n_i)$  \u3002\u8fd9\u4e9b\u4ee5\u524d\u603b\u662f\u7531 <code>assemble_system</code> \u6216\u5e94\u7528\u7a0b\u5e8f\u4ee3\u7801\u4e2d\u7684\u7c7b\u4f3c\u51fd\u6570\u624b\u5de5\u751f\u6210\u3002\u7136\u800c\uff0c\u6211\u4eec\u592a\u61d2\u4e86\uff0c\u4e0d\u80fd\u5728\u8fd9\u91cc\u8fd9\u4e48\u505a\uff0c\u6240\u4ee5\u5e72\u8106\u4f7f\u7528\u5e93\u51fd\u6570\u3002\n\n#include <deal.II/numerics/vector_tools.h> \n\n// \u4e0e\u6b64\u975e\u5e38\u76f8\u4f3c\uff0c\u6211\u4eec\u4e5f\u61d2\u5f97\u5199\u4ee3\u7801\u6765\u7ec4\u88c5\u8d28\u91cf\u77e9\u9635\u548c\u62c9\u666e\u62c9\u65af\u77e9\u9635\uff0c\u5c3d\u7ba1\u8fd9\u53ea\u9700\u8981\u4ece\u4ee5\u524d\u7684\u4efb\u4f55\u4e00\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u590d\u5236\u76f8\u5173\u4ee3\u7801\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u60f3\u628a\u91cd\u70b9\u653e\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u771f\u6b63\u65b0\u7684\u4e1c\u897f\u4e0a\uff0c\u56e0\u6b64\u4f7f\u7528\u4e86 MatrixCreator::create_mass_matrix \u548c MatrixCreator::create_laplace_matrix \u51fd\u6570\u3002\u5b83\u4eec\u88ab\u58f0\u660e\u5728\u8fd9\u91cc\u3002\n\n#include <deal.II/numerics/matrix_tools.h> \n\n// \u6700\u540e\uff0c\u8fd9\u91cc\u6709\u4e00\u4e2ainclude\u6587\u4ef6\uff0c\u5b83\u5305\u542b\u4e86\u4eba\u4eec\u6709\u65f6\u9700\u8981\u7684\u5404\u79cd\u5de5\u5177\u51fd\u6570\u3002\u7279\u522b\u662f\uff0c\u6211\u4eec\u9700\u8981 Utilities::int_to_string \u7c7b\uff0c\u8be5\u7c7b\u5728\u7ed9\u5b9a\u4e00\u4e2a\u6574\u6570\u53c2\u6570\u540e\uff0c\u8fd4\u56de\u5b83\u7684\u5b57\u7b26\u4e32\u8868\u793a\u3002\u5b83\u7279\u522b\u6709\u7528\uff0c\u56e0\u4e3a\u5b83\u5141\u8bb8\u7b2c\u4e8c\u4e2a\u53c2\u6570\uff0c\u8868\u660e\u6211\u4eec\u5e0c\u671b\u7ed3\u679c\u7528\u524d\u5bfc\u96f6\u586b\u5145\u7684\u6570\u5b57\u6570\u3002\u6211\u4eec\u5c06\u7528\u5b83\u6765\u5199\u8f93\u51fa\u6587\u4ef6\uff0c\u5176\u5f62\u5f0f\u4e3a <code>solution-XXX.vtu</code> where <code>XXX</code> \u8868\u793a\u65f6\u95f4\u6b65\u6570\uff0c\u5e76\u4e14\u603b\u662f\u7531\u4e09\u4f4d\u6570\u7ec4\u6210\uff0c\u5373\u4f7f\u6211\u4eec\u4ecd\u7136\u5904\u4e8e\u4e2a\u4f4d\u6216\u4e24\u4f4d\u6570\u7684\u65f6\u95f4\u6b65\u6570\u4e2d\u3002\n\n#include <deal.II/base/utilities.h> \n\n// \u6700\u540e\u4e00\u6b65\u548c\u4ee5\u524d\u6240\u6709\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\n\nnamespace Step23 \n{ \n  using namespace dealii; \n// @sect3{The <code>WaveEquation</code> class}  \n\n// \u63a5\u4e0b\u6765\u662f\u4e3b\u7c7b\u7684\u58f0\u660e\u3002\u5b83\u7684\u516c\u5171\u51fd\u6570\u63a5\u53e3\u4e0e\u5176\u4ed6\u5927\u591a\u6570\u6559\u7a0b\u7a0b\u5e8f\u4e00\u6837\u3002\u503c\u5f97\u4e00\u63d0\u7684\u662f\uff0c\u6211\u4eec\u73b0\u5728\u5fc5\u987b\u5b58\u50a8\u56db\u4e2a\u77e9\u9635\uff0c\u800c\u4e0d\u662f\u4e00\u4e2a\uff1a\u8d28\u91cf\u77e9\u9635  $M$  \uff0c\u62c9\u666e\u62c9\u65af\u77e9\u9635  $A$  \uff0c\u7528\u4e8e\u6c42\u89e3  $U^n$  \u7684\u77e9\u9635  $M+k^2\\theta^2A$  \uff0c\u4ee5\u53ca\u7528\u4e8e\u6c42\u89e3  $V^n$  \u7684\u5e26\u6709\u8fb9\u754c\u6761\u4ef6\u7684\u8d28\u91cf\u77e9\u9635\u526f\u672c\u3002\u8bf7\u6ce8\u610f\uff0c\u5728\u5468\u56f4\u6709\u4e00\u4e2a\u989d\u5916\u7684\u8d28\u91cf\u77e9\u9635\u526f\u672c\u662f\u6709\u70b9\u6d6a\u8d39\u7684\u3002\u6211\u4eec\u5c06\u5728\u53ef\u80fd\u7684\u6539\u8fdb\u90e8\u5206\u8ba8\u8bba\u5982\u4f55\u907f\u514d\u8fd9\u79cd\u60c5\u51b5\u7684\u7b56\u7565\u3002\n\n// \u540c\u6837\uff0c\u6211\u4eec\u9700\u8981 $U^n,V^n$ \u7684\u89e3\u5411\u91cf\uff0c\u4ee5\u53ca\u524d\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4 $U^{n-1},V^{n-1}$ \u7684\u76f8\u5e94\u5411\u91cf\u3002 <code>system_rhs</code> \u5c06\u7528\u4e8e\u6211\u4eec\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u6c42\u89e3\u4e24\u4e2a\u7ebf\u6027\u7cfb\u7edf\u4e4b\u4e00\u65f6\u7684\u4efb\u4f55\u53f3\u624b\u5411\u91cf\u3002\u8fd9\u4e9b\u5c06\u5728\u4e24\u4e2a\u51fd\u6570  <code>solve_u</code>  \u548c  <code>solve_v</code>  \u4e2d\u89e3\u51b3\u3002\n\n// \u6700\u540e\uff0c\u53d8\u91cf <code>theta</code> \u7528\u6765\u8868\u793a\u53c2\u6570 $\\theta$ \uff0c\u8be5\u53c2\u6570\u7528\u4e8e\u5b9a\u4e49\u4f7f\u7528\u54ea\u79cd\u65f6\u95f4\u6b65\u8fdb\u65b9\u6848\uff0c\u8fd9\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8bf4\u660e\u3002\u5269\u4e0b\u7684\u5c31\u4e0d\u8a00\u800c\u55bb\u4e86\u3002\n\n  template <int dim> \n  class WaveEquation \n  { \n  public: \n    WaveEquation(); \n    void run(); \n\n  private: \n    void setup_system(); \n    void solve_u(); \n    void solve_v(); \n    void output_results() const; \n\n    Triangulation<dim> triangulation; \n    FE_Q<dim>          fe; \n    DoFHandler<dim>    dof_handler; \n\n    AffineConstraints<double> constraints; \n\n    SparsityPattern      sparsity_pattern; \n    SparseMatrix<double> mass_matrix; \n    SparseMatrix<double> laplace_matrix; \n    SparseMatrix<double> matrix_u; \n    SparseMatrix<double> matrix_v; \n\n    Vector<double> solution_u, solution_v; \n    Vector<double> old_solution_u, old_solution_v; \n    Vector<double> system_rhs; \n\n    double       time_step; \n    double       time; \n    unsigned int timestep_number; \n    const double theta; \n  }; \n\n//  @sect3{Equation data}  \n\n// \u5728\u6211\u4eec\u7ee7\u7eed\u586b\u5199\u4e3b\u7c7b\u7684\u7ec6\u8282\u4e4b\u524d\uff0c\u8ba9\u6211\u4eec\u5b9a\u4e49\u4e0e\u95ee\u9898\u76f8\u5bf9\u5e94\u7684\u65b9\u7a0b\u6570\u636e\uff0c\u5373\u89e3 $u$ \u53ca\u5176\u65f6\u95f4\u5bfc\u6570 $v$ \u7684\u521d\u59cb\u503c\u548c\u8fb9\u754c\u503c\uff0c\u4ee5\u53ca\u4e00\u4e2a\u53f3\u624b\u7c7b\u3002\u6211\u4eec\u4f7f\u7528\u4eceFunction\u7c7b\u6a21\u677f\u6d3e\u751f\u51fa\u6765\u7684\u7c7b\u6765\u505a\u8fd9\u4ef6\u4e8b\uff0c\u8fd9\u4e2a\u6a21\u677f\u4ee5\u524d\u5df2\u7ecf\u7528\u8fc7\u5f88\u591a\u6b21\u4e86\uff0c\u6240\u4ee5\u4e0b\u9762\u7684\u5185\u5bb9\u4e0d\u5e94\u8be5\u662f\u4e00\u4e2a\u60ca\u559c\u3002\n\n// \u6211\u4eec\u4ece\u521d\u59cb\u503c\u5f00\u59cb\uff0c\u5bf9\u6570\u503c $u$ \u4ee5\u53ca\u5b83\u7684\u65f6\u95f4\u5bfc\u6570\uff0c\u5373\u901f\u5ea6 $v$ \u90fd\u9009\u62e9\u96f6\u3002\n\n  template <int dim> \n  class InitialValuesU : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & /*p*/, \n                         const unsigned int component = 0) const override \n    { \n      (void)component; \n      Assert(component == 0, ExcIndexRange(component, 0, 1)); \n      return 0; \n    } \n  }; \n\n  template <int dim> \n  class InitialValuesV : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & /*p*/, \n                         const unsigned int component = 0) const override \n    { \n      (void)component; \n      Assert(component == 0, ExcIndexRange(component, 0, 1)); \n      return 0; \n    } \n  }; \n\n// \u5176\u6b21\uff0c\u6211\u4eec\u6709\u53f3\u624b\u8fb9\u7684\u5f3a\u5236\u9879\u3002\u65e0\u804a\u7684\u662f\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u4e5f\u9009\u62e9\u96f6\u3002\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      (void)component; \n      Assert(component == 0, ExcIndexRange(component, 0, 1)); \n      return 0; \n    } \n  }; \n\n// \u6700\u540e\uff0c\u6211\u4eec\u6709  $u$  \u548c  $v$  \u7684\u8fb9\u754c\u503c\u3002\u5b83\u4eec\u4e0e\u4ecb\u7ecd\u4e2d\u63cf\u8ff0\u7684\u4e00\u6837\uff0c\u4e00\u4e2a\u662f\u53e6\u4e00\u4e2a\u7684\u65f6\u95f4\u5bfc\u6570\u3002\n\n  template <int dim> \n  class BoundaryValuesU : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override \n    { \n      (void)component; \n      Assert(component == 0, ExcIndexRange(component, 0, 1)); \n\n      if ((this->get_time() <= 0.5) && (p[0] < 0) && (p[1] < 1. / 3) && \n          (p[1] > -1. / 3)) \n        return std::sin(this->get_time() * 4 * numbers::PI); \n      else \n        return 0; \n    } \n  }; \n\n  template <int dim> \n  class BoundaryValuesV : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override \n    { \n      (void)component; \n      Assert(component == 0, ExcIndexRange(component, 0, 1)); \n\n      if ((this->get_time() <= 0.5) && (p[0] < 0) && (p[1] < 1. / 3) && \n          (p[1] > -1. / 3)) \n        return (std::cos(this->get_time() * 4 * numbers::PI) * 4 * numbers::PI); \n      else \n        return 0; \n    } \n  }; \n\n//  @sect3{Implementation of the <code>WaveEquation</code> class}  \n\n// \u5b9e\u9645\u903b\u8f91\u7684\u5b9e\u73b0\u5b9e\u9645\u4e0a\u662f\u76f8\u5f53\u77ed\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u628a\u7ec4\u88c5\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u5411\u91cf\u7b49\u4e8b\u60c5\u4ea4\u7ed9\u4e86\u5e93\u3002\u5176\u4f59\u7684\u5b9e\u9645\u4ee3\u7801\u4e0d\u8d85\u8fc7130\u884c\uff0c\u5176\u4e2d\u76f8\u5f53\u4e00\u90e8\u5206\u662f\u53ef\u4ee5\u4ece\u4ee5\u524d\u7684\u4f8b\u5b50\u7a0b\u5e8f\u4e2d\u83b7\u53d6\u7684\u6a21\u677f\u4ee3\u7801\uff08\u4f8b\u5982\uff0c\u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\uff0c\u6216\u751f\u6210\u8f93\u51fa\u7684\u51fd\u6570\uff09\u3002\n\n// \u6211\u4eec\u4ece\u6784\u9020\u51fd\u6570\u5f00\u59cb\uff08\u5173\u4e8e\u65f6\u95f4\u6b65\u957f\u7684\u9009\u62e9\u7684\u89e3\u91ca\uff0c\u8bf7\u53c2\u89c1\u4ecb\u7ecd\u4e2d\u5173\u4e8eCourant, Friedrichs, and Lewy\u7684\u90e8\u5206\uff09\u3002\n\n  template <int dim> \n  WaveEquation<dim>::WaveEquation() \n    : fe(1) \n    , dof_handler(triangulation) \n    , time_step(1. / 64) \n    , time(time_step) \n    , timestep_number(1) \n    , theta(0.5) \n  {} \n// @sect4{WaveEquation::setup_system}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u5728\u7a0b\u5e8f\u5f00\u59cb\u65f6\uff0c\u4e5f\u5c31\u662f\u5728\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e4b\u524d\uff0c\u8bbe\u7f6e\u7f51\u683c\u3001DoFHandler\u4ee5\u53ca\u77e9\u9635\u548c\u5411\u91cf\u3002\u5982\u679c\u4f60\u5df2\u7ecf\u9605\u8bfb\u4e86\u81f3\u5c11\u5230 step-6 \u4e3a\u6b62\u7684\u6559\u7a0b\u7a0b\u5e8f\uff0c\u90a3\u4e48\u524d\u51e0\u884c\u662f\u76f8\u5f53\u6807\u51c6\u7684\u3002\n\n  template <int dim> \n  void WaveEquation<dim>::setup_system() \n  { \n    GridGenerator::hyper_cube(triangulation, -1, 1); \n    triangulation.refine_global(7); \n\n    std::cout << \"Number of active cells: \" << triangulation.n_active_cells() \n              << std::endl; \n\n    dof_handler.distribute_dofs(fe); \n\n    std::cout << \"Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << std::endl \n              << std::endl; \n\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\n// \u7136\u540e\uff0c\u6211\u4eec\u5fc5\u987b\u521d\u59cb\u5316\u7a0b\u5e8f\u8fc7\u7a0b\u4e2d\u9700\u8981\u76843\u4e2a\u77e9\u9635\uff1a\u8d28\u91cf\u77e9\u9635\u3001\u62c9\u666e\u62c9\u65af\u77e9\u9635\u548c\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u6c42\u89e3 $M+k^2\\theta^2A$ \u65f6\u4f7f\u7528\u7684\u77e9\u9635 $U^n$ \u3002\n\n// \u5728\u8bbe\u7f6e\u8fd9\u4e9b\u77e9\u9635\u65f6\uff0c\u8bf7\u6ce8\u610f\u5b83\u4eec\u90fd\u662f\u5229\u7528\u4e86\u76f8\u540c\u7684\u7a00\u758f\u6a21\u5f0f\u5bf9\u8c61\u3002\u6700\u540e\uff0c\u5728deal.II\u4e2d\u77e9\u9635\u548c\u7a00\u758f\u6a21\u5f0f\u662f\u72ec\u7acb\u5bf9\u8c61\u7684\u539f\u56e0\uff08\u4e0e\u5176\u4ed6\u8bb8\u591a\u6709\u9650\u5143\u6216\u7ebf\u6027\u4ee3\u6570\u7c7b\u4e0d\u540c\uff09\u53d8\u5f97\u5f88\u6e05\u695a\uff1a\u5728\u76f8\u5f53\u4e00\u90e8\u5206\u5e94\u7528\u4e2d\uff0c\u6211\u4eec\u5fc5\u987b\u6301\u6709\u51e0\u4e2a\u6070\u597d\u5177\u6709\u76f8\u540c\u7a00\u758f\u6a21\u5f0f\u7684\u77e9\u9635\uff0c\u5b83\u4eec\u6ca1\u6709\u7406\u7531\u4e0d\u5171\u4eab\u8fd9\u4e00\u4fe1\u606f\uff0c\u800c\u4e0d\u662f\u91cd\u65b0\u5efa\u7acb\u5e76\u591a\u6b21\u6d6a\u8d39\u5185\u5b58\u3002\n\n// \u5728\u521d\u59cb\u5316\u6240\u6709\u8fd9\u4e9b\u77e9\u9635\u540e\uff0c\u6211\u4eec\u8c03\u7528\u5e93\u51fd\u6570\u6765\u5efa\u7acb\u62c9\u666e\u62c9\u65af\u548c\u8d28\u91cf\u77e9\u9635\u3002\u5b83\u4eec\u6240\u9700\u8981\u7684\u53ea\u662f\u4e00\u4e2aDoFHandler\u5bf9\u8c61\u548c\u4e00\u4e2a\u5c06\u7528\u4e8e\u6570\u503c\u79ef\u5206\u7684\u6b63\u4ea4\u516c\u5f0f\u5bf9\u8c61\u3002\u8bf7\u6ce8\u610f\uff0c\u5728\u8bb8\u591a\u65b9\u9762\uff0c\u8fd9\u4e9b\u51fd\u6570\u6bd4\u6211\u4eec\u901a\u5e38\u5728\u5e94\u7528\u7a0b\u5e8f\u4e2d\u505a\u7684\u8981\u597d\uff0c\u4f8b\u5982\uff0c\u5982\u679c\u4e00\u53f0\u673a\u5668\u6709\u591a\u4e2a\u5904\u7406\u5668\uff0c\u5b83\u4eec\u4f1a\u81ea\u52a8\u5e76\u884c\u6784\u5efa\u77e9\u9635\uff1a\u66f4\u591a\u4fe1\u606f\u89c1WorkStream\u7684\u6587\u6863\u6216 @ref threads \"\u591a\u5904\u7406\u5668\u5e76\u884c\u8ba1\u7b97 \"\u6a21\u5757\u3002\u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u7684\u77e9\u9635\u5c06\u5728run()\u65b9\u6cd5\u4e2d\u88ab\u586b\u5145\uff0c\u56e0\u4e3a\u6211\u4eec\u9700\u8981\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u91cd\u65b0\u5e94\u7528\u8fb9\u754c\u6761\u4ef6\u3002\n\n    mass_matrix.reinit(sparsity_pattern); \n    laplace_matrix.reinit(sparsity_pattern); \n    matrix_u.reinit(sparsity_pattern); \n    matrix_v.reinit(sparsity_pattern); \n\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\n// \u8be5\u51fd\u6570\u7684\u5176\u4f59\u90e8\u5206\u7528\u4e8e\u5c06\u77e2\u91cf\u5927\u5c0f\u8bbe\u7f6e\u4e3a\u6b63\u786e\u7684\u503c\u3002\u6700\u540e\u4e00\u884c\u5173\u95ed\u4e86\u60ac\u6302\u7684\u8282\u70b9\u7ea6\u675f\u5bf9\u8c61\u3002\u7531\u4e8e\u6211\u4eec\u5728\u4e00\u4e2a\u5747\u5300\u7ec6\u5316\u7684\u7f51\u683c\u4e0a\u5de5\u4f5c\uff0c\u6240\u4ee5\u4e0d\u5b58\u5728\u6216\u6ca1\u6709\u8ba1\u7b97\u8fc7\u7ea6\u675f\u6761\u4ef6\uff08\u5373\u6ca1\u6709\u5fc5\u8981\u50cf\u5176\u4ed6\u7a0b\u5e8f\u90a3\u6837\u8c03\u7528 DoFTools::make_hanging_node_constraints \uff09\uff0c\u4f46\u65e0\u8bba\u5982\u4f55\uff0c\u6211\u4eec\u9700\u8981\u5728\u4e0b\u9762\u7684\u4e00\u4e2a\u5730\u65b9\u8fdb\u4e00\u6b65\u8bbe\u7f6e\u4e00\u4e2a\u7ea6\u675f\u5bf9\u8c61\u3002\n\n    solution_u.reinit(dof_handler.n_dofs()); \n    solution_v.reinit(dof_handler.n_dofs()); \n    old_solution_u.reinit(dof_handler.n_dofs()); \n    old_solution_v.reinit(dof_handler.n_dofs()); \n    system_rhs.reinit(dof_handler.n_dofs()); \n\n    constraints.close(); \n  } \n\n//  @sect4{WaveEquation::solve_u and WaveEquation::solve_v}  \n\n// \u63a5\u4e0b\u6765\u7684\u4e24\u4e2a\u51fd\u6570\u662f\u89e3\u51b3\u4e0e  $U^n$  \u548c  $V^n$  \u7684\u65b9\u7a0b\u6709\u5173\u7684\u7ebf\u6027\u7cfb\u7edf\u3002\u8fd9\u4e24\u4e2a\u51fd\u6570\u5e76\u4e0d\u7279\u522b\u6709\u8da3\uff0c\u56e0\u4e3a\u5b83\u4eec\u57fa\u672c\u6cbf\u7528\u4e86\u524d\u9762\u6240\u6709\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u7684\u65b9\u6848\u3002\n\n// \u6211\u4eec\u53ef\u4ee5\u5bf9\u6211\u4eec\u8981\u53cd\u8f6c\u7684\u4e24\u4e2a\u77e9\u9635\u7684\u9884\u5904\u7406\u7a0b\u5e8f\u505a\u4e00\u4e9b\u5c0f\u5b9e\u9a8c\u3002\u7136\u800c\uff0c\u4e8b\u5b9e\u8bc1\u660e\uff0c\u5bf9\u4e8e\u8fd9\u91cc\u7684\u77e9\u9635\uff0c\u4f7f\u7528\u96c5\u53ef\u6bd4\u6216SSOR\u9884\u5904\u7406\u5668\u53ef\u4ee5\u7a0d\u5fae\u51cf\u5c11\u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u6240\u9700\u7684\u8fed\u4ee3\u6b21\u6570\uff0c\u4f46\u7531\u4e8e\u5e94\u7528\u9884\u5904\u7406\u5668\u7684\u6210\u672c\uff0c\u5728\u8fd0\u884c\u65f6\u95f4\u65b9\u9762\u5e76\u4e0d\u5360\u4f18\u52bf\u3002\u8fd9\u4e5f\u4e0d\u662f\u4ec0\u4e48\u635f\u5931\uff0c\u4f46\u8ba9\u6211\u4eec\u4fdd\u6301\u7b80\u5355\uff0c\u53ea\u505a\u4e0d\u505a\u3002\n\n  template <int dim> \n  void WaveEquation<dim>::solve_u() \n  { \n    SolverControl            solver_control(1000, 1e-8 * system_rhs.l2_norm()); \n    SolverCG<Vector<double>> cg(solver_control); \n\n    cg.solve(matrix_u, solution_u, system_rhs, PreconditionIdentity()); \n\n    std::cout << \"   u-equation: \" << solver_control.last_step() \n              << \" CG iterations.\" << std::endl; \n  } \n\n  template <int dim> \n  void WaveEquation<dim>::solve_v() \n  { \n    SolverControl            solver_control(1000, 1e-8 * system_rhs.l2_norm()); \n    SolverCG<Vector<double>> cg(solver_control); \n\n    cg.solve(matrix_v, solution_v, system_rhs, PreconditionIdentity()); \n\n    std::cout << \"   v-equation: \" << solver_control.last_step() \n              << \" CG iterations.\" << std::endl; \n  } \n\n//  @sect4{WaveEquation::output_results}  \n\n// \u540c\u6837\u5730\uff0c\u4e0b\u9762\u7684\u51fd\u6570\u4e5f\u548c\u6211\u4eec\u4e4b\u524d\u505a\u7684\u5dee\u4e0d\u591a\u3002\u552f\u4e00\u503c\u5f97\u4e00\u63d0\u7684\u662f\uff0c\u8fd9\u91cc\u6211\u4eec\u4f7f\u7528 Utilities::int_to_string \u51fd\u6570\u7684\u7b2c\u4e8c\u4e2a\u53c2\u6570\uff0c\u751f\u6210\u4e86\u4e00\u4e2a\u7528\u524d\u5bfc\u96f6\u586b\u5145\u7684\u65f6\u95f4\u6b65\u957f\u7684\u5b57\u7b26\u4e32\u8868\u793a\uff0c\u957f\u5ea6\u4e3a3\u4e2a\u5b57\u7b26\u3002\n\n  template <int dim> \n  void WaveEquation<dim>::output_results() const \n  { \n    DataOut<dim> data_out; \n\n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution_u, \"U\"); \n    data_out.add_data_vector(solution_v, \"V\"); \n\n    data_out.build_patches(); \n\n    const std::string filename = \n      \"solution-\" + Utilities::int_to_string(timestep_number, 3) + \".vtu\"; \n\n// \u50cf  step-15  \u4e00\u6837\uff0c\u7531\u4e8e\u6211\u4eec\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u5199\u8f93\u51fa\uff08\u800c\u4e14\u6211\u4eec\u8981\u89e3\u51b3\u7684\u7cfb\u7edf\u76f8\u5bf9\u7b80\u5355\uff09\uff0c\u6211\u4eec\u6307\u793aDataOut\u4f7f\u7528zlib\u538b\u7f29\u7b97\u6cd5\uff0c\u8be5\u7b97\u6cd5\u9488\u5bf9\u901f\u5ea6\u800c\u4e0d\u662f\u78c1\u76d8\u4f7f\u7528\u8fdb\u884c\u4e86\u4f18\u5316\uff0c\u56e0\u4e3a\u5426\u5219\u7ed8\u5236\u8f93\u51fa\u4f1a\u6210\u4e3a\u4e00\u4e2a\u74f6\u9888\u3002\n\n    DataOutBase::VtkFlags vtk_flags; \n    vtk_flags.compression_level = \n      DataOutBase::VtkFlags::ZlibCompressionLevel::best_speed; \n    data_out.set_flags(vtk_flags); \n    std::ofstream output(filename); \n    data_out.write_vtu(output); \n  } \n\n//  @sect4{WaveEquation::run}  \n\n// \u4e0b\u9762\u662f\u7a0b\u5e8f\u4e2d\u552f\u4e00\u6709\u8da3\u7684\u529f\u80fd\u3002\u5b83\u5305\u542b\u4e86\u6240\u6709\u65f6\u95f4\u6b65\u9aa4\u7684\u5faa\u73af\uff0c\u4f46\u5728\u8fd9\u4e4b\u524d\u6211\u4eec\u5fc5\u987b\u8bbe\u7f6e\u7f51\u683c\u3001DoFHandler\u548c\u77e9\u9635\u3002\u6b64\u5916\uff0c\u6211\u4eec\u5fc5\u987b\u4ee5\u67d0\u79cd\u65b9\u5f0f\u4ece\u521d\u59cb\u503c\u5f00\u59cb\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u4f7f\u7528 VectorTools::project \u51fd\u6570\uff0c\u8be5\u51fd\u6570\u63a5\u6536\u4e00\u4e2a\u63cf\u8ff0\u8fde\u7eed\u51fd\u6570\u7684\u5bf9\u8c61\uff0c\u5e76\u8ba1\u7b97\u8be5\u51fd\u6570\u5728DoFHandler\u5bf9\u8c61\u6240\u63cf\u8ff0\u7684\u6709\u9650\u5143\u7a7a\u95f4\u7684 $L^2$ \u6295\u5f71\u3002\u6ca1\u6709\u6bd4\u8fd9\u66f4\u7b80\u5355\u7684\u4e86\u3002\n\n  template <int dim> \n  void WaveEquation<dim>::run() \n  { \n    setup_system(); \n\n    VectorTools::project(dof_handler, \n                         constraints, \n                         QGauss<dim>(fe.degree + 1), \n                         InitialValuesU<dim>(), \n                         old_solution_u); \n    VectorTools::project(dof_handler, \n                         constraints, \n                         QGauss<dim>(fe.degree + 1), \n                         InitialValuesV<dim>(), \n                         old_solution_v); \n\n// \u63a5\u4e0b\u6765\u662f\u5faa\u73af\u6240\u6709\u7684\u65f6\u95f4\u6b65\u9aa4\uff0c\u76f4\u5230\u6211\u4eec\u5230\u8fbe\u7ed3\u675f\u65f6\u95f4\uff08\u672c\u4f8b\u4e2d\u4e3a $T=5$ \uff09\u3002\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\uff0c\u6211\u4eec\u9996\u5148\u8981\u89e3\u51b3 $U^n$ \uff0c\u4f7f\u7528\u65b9\u7a0b  $(M^n + k^2\\theta^2 A^n)U^n =$  \u3002\n// $(M^{n,n-1} - k^2\\theta(1-\\theta) A^{n,n-1})U^{n-1} + kM^{n,n-1}V^{n-1} +$  \n// $k\\theta \\left[k \\theta F^n + k(1-\\theta) F^{n-1} \\right]$  . \u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u5728\u6240\u6709\u7684\u65f6\u95f4\u6b65\u9aa4\u4e2d\u4f7f\u7528\u76f8\u540c\u7684\u7f51\u683c\uff0c\u56e0\u6b64\uff0c $M^n=M^{n,n-1}=M$  \u548c  $A^n=A^{n,n-1}=A$  \u3002\u56e0\u6b64\uff0c\u6211\u4eec\u9996\u5148\u8981\u505a\u7684\u662f\u5c06 $MU^{n-1} - k^2\\theta(1-\\theta) AU^{n-1} + kMV^{n-1}$ \u548c\u5f3a\u5236\u9879\u76f8\u52a0\uff0c\u5e76\u5c06\u7ed3\u679c\u653e\u5165 <code>system_rhs</code> \u5411\u91cf\u4e2d\u3002(\u5bf9\u4e8e\u8fd9\u4e9b\u52a0\u6cd5\uff0c\u6211\u4eec\u9700\u8981\u5728\u5faa\u73af\u4e4b\u524d\u58f0\u660e\u4e00\u4e2a\u4e34\u65f6\u5411\u91cf\uff0c\u4ee5\u907f\u514d\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u91cd\u590d\u5206\u914d\u5185\u5b58)\u3002\n\n// \u8fd9\u91cc\u9700\u8981\u610f\u8bc6\u5230\u7684\u662f\u6211\u4eec\u5982\u4f55\u5c06\u65f6\u95f4\u53d8\u91cf\u4f20\u8fbe\u7ed9\u63cf\u8ff0\u53f3\u624b\u8fb9\u7684\u5bf9\u8c61\uff1a\u6bcf\u4e2a\u4ece\u51fd\u6570\u7c7b\u6d3e\u751f\u51fa\u6765\u7684\u5bf9\u8c61\u90fd\u6709\u4e00\u4e2a\u65f6\u95f4\u5b57\u6bb5\uff0c\u53ef\u4ee5\u7528 Function::set_time \u6765\u8bbe\u7f6e\uff0c\u7528 Function::get_time. \u6765\u8bfb\u53d6\u3002 \u5b9e\u8d28\u4e0a\uff0c\u4f7f\u7528\u8fd9\u79cd\u673a\u5236\uff0c\u6240\u6709\u7a7a\u95f4\u548c\u65f6\u95f4\u7684\u51fd\u6570\u56e0\u6b64\u88ab\u8ba4\u4e3a\u662f\u5728\u67d0\u4e2a\u7279\u5b9a\u65f6\u95f4\u8bc4\u4f30\u7684\u7a7a\u95f4\u7684\u51fd\u6570\u3002\u8fd9\u4e0e\u6211\u4eec\u5728\u6709\u9650\u5143\u7a0b\u5e8f\u4e2d\u7684\u5178\u578b\u9700\u6c42\u975e\u5e38\u543b\u5408\uff0c\u5728\u6709\u9650\u5143\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u51e0\u4e4e\u603b\u662f\u5728\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u4e0a\u5de5\u4f5c\uff0c\u800c\u4e14\u4ece\u6765\u6ca1\u6709\u53d1\u751f\u8fc7\uff0c\u4f8b\u5982\uff0c\u4eba\u4eec\u60f3\u5728\u4efb\u4f55\u7ed9\u5b9a\u7684\u7a7a\u95f4\u4f4d\u7f6e\u4e0a\u4e3a\u6240\u6709\u65f6\u95f4\u8bc4\u4f30\u4e00\u4e2a\u65f6\u7a7a\u51fd\u6570\u3002\n\n    Vector<double> tmp(solution_u.size()); \n    Vector<double> forcing_terms(solution_u.size()); \n\n    for (; time <= 5; time += time_step, ++timestep_number) \n      { \n        std::cout << \"Time step \" << timestep_number << \" at t=\" << time \n                  << std::endl; \n\n        mass_matrix.vmult(system_rhs, old_solution_u); \n\n        mass_matrix.vmult(tmp, old_solution_v); \n        system_rhs.add(time_step, tmp); \n\n        laplace_matrix.vmult(tmp, old_solution_u); \n        system_rhs.add(-theta * (1 - theta) * time_step * time_step, tmp); \n\n        RightHandSide<dim> rhs_function; \n        rhs_function.set_time(time); \n        VectorTools::create_right_hand_side(dof_handler, \n                                            QGauss<dim>(fe.degree + 1), \n                                            rhs_function, \n                                            tmp); \n        forcing_terms = tmp; \n        forcing_terms *= theta * time_step; \n\n        rhs_function.set_time(time - time_step); \n        VectorTools::create_right_hand_side(dof_handler, \n                                            QGauss<dim>(fe.degree + 1), \n                                            rhs_function, \n                                            tmp); \n\n        forcing_terms.add((1 - theta) * time_step, tmp); \n\n        system_rhs.add(theta * time_step, forcing_terms); \n\n// \u5982\u6b64\u6784\u5efa\u4e86\u7b2c\u4e00\u4e2a\u65b9\u7a0b\u7684\u53f3\u624b\u5411\u91cf\u540e\uff0c\u6211\u4eec\u8981\u505a\u7684\u5c31\u662f\u5e94\u7528\u6b63\u786e\u7684\u8fb9\u754c\u503c\u3002\u81f3\u4e8e\u53f3\u624b\u8fb9\uff0c\u8fd9\u662f\u4e00\u4e2a\u5728\u7279\u5b9a\u65f6\u95f4\u8bc4\u4f30\u7684\u65f6\u7a7a\u51fd\u6570\uff0c\u6211\u4eec\u5728\u8fb9\u754c\u8282\u70b9\u63d2\u503c\uff0c\u7136\u540e\u50cf\u901a\u5e38\u90a3\u6837\u7528\u7ed3\u679c\u6765\u5e94\u7528\u8fb9\u754c\u503c\u3002\u7136\u540e\u5c06\u7ed3\u679c\u4ea4\u7ed9solve_u()\u51fd\u6570\u3002\n\n        { \n          BoundaryValuesU<dim> boundary_values_u_function; \n          boundary_values_u_function.set_time(time); \n\n          std::map<types::global_dof_index, double> boundary_values; \n          VectorTools::interpolate_boundary_values(dof_handler, \n                                                   0, \n                                                   boundary_values_u_function, \n                                                   boundary_values); \n\n// solve_u()\u7684\u77e9\u9635\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u90fd\u662f\u76f8\u540c\u7684\uff0c\u6240\u4ee5\u4eba\u4eec\u53ef\u4ee5\u8ba4\u4e3a\u53ea\u5728\u6a21\u62df\u5f00\u59cb\u65f6\u505a\u4e00\u6b21\u5c31\u8db3\u591f\u4e86\u3002\u7136\u800c\uff0c\u7531\u4e8e\u6211\u4eec\u9700\u8981\u5bf9\u7ebf\u6027\u7cfb\u7edf\u5e94\u7528\u8fb9\u754c\u503c\uff08\u6d88\u9664\u4e86\u4e00\u4e9b\u77e9\u9635\u7684\u884c\u548c\u5217\uff0c\u5e76\u5bf9\u53f3\u624b\u8fb9\u505a\u51fa\u4e86\u8d21\u732e\uff09\uff0c\u5728\u5b9e\u9645\u5e94\u7528\u8fb9\u754c\u6570\u636e\u4e4b\u524d\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u91cd\u65b0\u586b\u5145\u8be5\u77e9\u9635\u3002\u5b9e\u9645\u5185\u5bb9\u975e\u5e38\u7b80\u5355\uff1a\u5b83\u662f\u8d28\u91cf\u77e9\u9635\u548c\u52a0\u6743\u62c9\u666e\u62c9\u65af\u77e9\u9635\u7684\u603b\u548c\u3002\n\n          matrix_u.copy_from(mass_matrix); \n          matrix_u.add(theta * theta * time_step * time_step, laplace_matrix); \n          MatrixTools::apply_boundary_values(boundary_values, \n                                             matrix_u, \n                                             solution_u, \n                                             system_rhs); \n        } \n        solve_u(); \n\n// \u7b2c\u4e8c\u6b65\uff0c\u5373\u6c42\u89e3 $V^n$ \uff0c\u5de5\u4f5c\u539f\u7406\u7c7b\u4f3c\uff0c\u53ea\u662f\u8fd9\u6b21\u5de6\u8fb9\u7684\u77e9\u9635\u662f\u8d28\u91cf\u77e9\u9635\uff08\u6211\u4eec\u518d\u6b21\u590d\u5236\uff0c\u4ee5\u4fbf\u80fd\u591f\u5e94\u7528\u8fb9\u754c\u6761\u4ef6\uff0c\u800c\u53f3\u8fb9\u662f $MV^{n-1} - k\\left[ \\theta A U^n + (1-\\theta) AU^{n-1}\\right]$ \u52a0\u4e0a\u5f3a\u5236\u9879\u3002\u8fb9\u754c\u503c\u7684\u5e94\u7528\u65b9\u5f0f\u4e0e\u4e4b\u524d\u76f8\u540c\uff0c\u53ea\u662f\u73b0\u5728\u6211\u4eec\u5fc5\u987b\u4f7f\u7528BoundaryValuesV\u7c7b\u3002\n\n        laplace_matrix.vmult(system_rhs, solution_u); \n        system_rhs *= -theta * time_step; \n\n        mass_matrix.vmult(tmp, old_solution_v); \n        system_rhs += tmp; \n\n        laplace_matrix.vmult(tmp, old_solution_u); \n        system_rhs.add(-time_step * (1 - theta), tmp); \n\n        system_rhs += forcing_terms; \n\n        { \n          BoundaryValuesV<dim> boundary_values_v_function; \n          boundary_values_v_function.set_time(time); \n\n          std::map<types::global_dof_index, double> boundary_values; \n          VectorTools::interpolate_boundary_values(dof_handler, \n                                                   0, \n                                                   boundary_values_v_function, \n                                                   boundary_values); \n          matrix_v.copy_from(mass_matrix); \n          MatrixTools::apply_boundary_values(boundary_values, \n                                             matrix_v, \n                                             solution_v, \n                                             system_rhs); \n        } \n        solve_v(); \n\n// \u6700\u540e\uff0c\u5728\u8ba1\u7b97\u5b8c\u4e24\u4e2a\u89e3\u7684\u7ec4\u6210\u90e8\u5206\u540e\uff0c\u6211\u4eec\u8f93\u51fa\u7ed3\u679c\uff0c\u8ba1\u7b97\u89e3\u4e2d\u7684\u80fd\u91cf\uff0c\u5e76\u5728\u5c06\u73b0\u5728\u7684\u89e3\u79fb\u5165\u6301\u6709\u4e0a\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u89e3\u7684\u5411\u91cf\u540e\uff0c\u7ee7\u7eed\u4e0b\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u3002\u6ce8\u610f\u51fd\u6570 SparseMatrix::matrix_norm_square \u53ef\u4ee5\u5728\u4e00\u4e2a\u6b65\u9aa4\u4e2d\u8ba1\u7b97 $\\left<V^n,MV^n\\right>$ \u548c $\\left<U^n,AU^n\\right>$ \uff0c\u4e3a\u6211\u4eec\u8282\u7701\u4e86\u4e00\u4e2a\u4e34\u65f6\u5411\u91cf\u548c\u51e0\u884c\u4ee3\u7801\u7684\u8d39\u7528\u3002\n\n        output_results(); \n\n        std::cout << \"   Total energy: \" \n                  << (mass_matrix.matrix_norm_square(solution_v) + \n                      laplace_matrix.matrix_norm_square(solution_u)) / \n                       2 \n                  << std::endl; \n\n        old_solution_u = solution_u; \n        old_solution_v = solution_v; \n      } \n  } \n} // namespace Step23 \n// @sect3{The <code>main</code> function}  \n\n//\u5269\u4e0b\u7684\u5c31\u662f\u7a0b\u5e8f\u7684\u4e3b\u8981\u529f\u80fd\u4e86\u3002\u8fd9\u91cc\u6ca1\u6709\u4ec0\u4e48\u662f\u5728\u524d\u9762\u51e0\u4e2a\u7a0b\u5e8f\u4e2d\u6ca1\u6709\u5c55\u793a\u8fc7\u7684\u3002\n\nint main() \n{ \n  try \n    { \n      using namespace Step23; \n\n      WaveEquation<2> wave_equation_solver; \n      wave_equation_solver.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\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\n\n", "meta": {"hexsha": "06aae4a643e431512543e6828fb3054b4d45f53e", "size": 17568, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-23/step-23.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-23/step-23.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-23/step-23.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.7073170732, "max_line_length": 347, "alphanum_fraction": 0.6035405282, "num_tokens": 6728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680143008301, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5340363767720296}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu) 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 <mpllibs/metamonad/lazy_metafunction.hpp>\n#include <mpllibs/metamonad/lazy.hpp>\n#include <mpllibs/metamonad/returns.hpp>\n#include <mpllibs/metamonad/if_.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/times.hpp>\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/less.hpp>\n#include <boost/mpl/apply_wrap.hpp>\n#include <boost/mpl/assert.hpp>\n\nusing boost::mpl::int_;\nusing boost::mpl::minus;\nusing boost::mpl::times;\nusing boost::mpl::equal_to;\nusing boost::mpl::less;\n\nusing mpllibs::metamonad::lazy;\nusing mpllibs::metamonad::returns;\nusing mpllibs::metamonad::if_;\n\nnamespace\n{\n  MPLLIBS_LAZY_METAFUNCTION(not_using_arg, (T)) ((int_<13>));\n\n  MPLLIBS_LAZY_METAFUNCTION(double_value, (N)) ((times<N, int_<2> >));\n\n  MPLLIBS_LAZY_METAFUNCTION(fact, (N))\n  ((\n    if_<\n      less<N, int_<1> >,\n      int_<1>,\n      lazy<times<fact<minus<N, int_<1> > >, N> >\n    >\n  ));\n\n  MPLLIBS_LAZY_METAFUNCTION(mult, (A)(B)) ((times<A, B>));\n}\n\nBOOST_AUTO_TEST_CASE(test_lazy_metafunction)\n{\n  using boost::mpl::apply_wrap1;\n  using boost::mpl::apply_wrap2;\n\n  // test_lazy_metafunction\n  BOOST_MPL_ASSERT((equal_to<int_<6>, double_value<int_<3> >::type>));\n\n  // test_lazy_metafunction_with_two_arguments\n  BOOST_MPL_ASSERT((equal_to<int_<6>, mult<int_<2>, int_<3> >::type>));\n\n  // test_currying\n  BOOST_MPL_ASSERT((\n    equal_to<int_<6>, apply_wrap1<mult<int_<2> >::type, int_<3> >::type>\n  ));\n\n  // test_using_metafunction_as_metafunction_class\n  BOOST_MPL_ASSERT((\n    equal_to<int_<6>, apply_wrap2<mult<>, int_<2>, int_<3> >::type>\n  ));\n\n  // test_nested_lazy_metafunction_call\n  BOOST_MPL_ASSERT((\n    equal_to<int_<24>, mult<mult<int_<2>, int_<3> >, int_<4> >::type>\n  ));\n\n  // test_lazy_rec_metafunction\n  BOOST_MPL_ASSERT((equal_to<int_<6>, fact<int_<3> >::type>));\n\n  // test_lazy_mf_not_using_arg\n  BOOST_MPL_ASSERT((equal_to<int_<13>, not_using_arg<int_<8> >::type>));\n}\n\n\n", "meta": {"hexsha": "a8ab0f19dee9bd7db509da9299cb883a552960d3", "size": 2186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/metamonad/test/lazy_metafunction.cpp", "max_stars_repo_name": "sabel83/mpllibs", "max_stars_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-01-15T09:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T15:49:31.000Z", "max_issues_repo_path": "libs/metamonad/test/lazy_metafunction.cpp", "max_issues_repo_name": "sabel83/mpllibs", "max_issues_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-06-18T19:25:34.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-13T19:49:51.000Z", "max_forks_repo_path": "libs/metamonad/test/lazy_metafunction.cpp", "max_forks_repo_name": "sabel83/mpllibs", "max_forks_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-07-10T08:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T07:17:57.000Z", "avg_line_length": 26.3373493976, "max_line_length": 72, "alphanum_fraction": 0.7026532479, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.534036359248261}}
{"text": "#ifndef VI_PID_CONTROLLER_HPP\n#define VI_PID_CONTROLLER_HPP\n\n// Component\n#include \"PIDConfig.hpp\"\n#include \"VehicleInterfaceData.hpp\"\n\n// Libraries\n#include <boost/cstdfloat.hpp>\n#include <boost/circular_buffer.hpp>\n\n// Ros\n#include <geometry_msgs/Twist.h>\n#include <ros/ros.h>\n\n// Standard\n#include <cstdint>\n#include <string>\n\nnamespace vi\n{\n\nusing float64_t = boost::float64_t; ///< Alias for 64 bit float\n\n/// @brief Class to store config values for vehicle interface\nclass PIDController\n{\npublic:\n   /// @brief Default constructor\n   explicit PIDController(const PIDConfig& cfg);\n\n   /// @brief Destructor for forward declares\n   ~PIDController();\n\n   /// @brief Main driving function\n   /// @param now_s Current program time\n   void update(const ros::Time& now_s);\n\n   /// @brief Accessor for command\n   /// @return Command\n   float64_t getOutput() const noexcept {return m_output;}\n\n   /// @brief Mutator\n   /// @param val Val\n   /// @{\n   void setFeedback(const float64_t val)        noexcept {m_feedback = val;}\n   void setCommandSetpoint(const float64_t val) noexcept {m_setpoint = val;}\n   /// @}\n\nprivate:\n    /// @brief Helper function to update the delta in time\n    /// @param now_s Current real time\n    void updateDtS(const ros::Time& now_s) noexcept;\n\n    /// @brief Helper function to update the error\n    void updateError() noexcept;\n\n    /// @brief Helpers to calculate various components of the controller\n    /// @return Component value\n    /// @{\n    float64_t calculateP() const noexcept;\n    float64_t calculateI()       noexcept;\n    float64_t calculateD() const noexcept;\n    /// @}\n\n    /// @brief ctl filter helper function\n    /// @param input The input to filter into output\n    float64_t filterOutput(const float64_t input);\n\n\n    float64_t m_setpoint{0.0}; ///< Setpoint\n    float64_t m_feedback{0.0}; ///< Feedback\n    float64_t m_output{0.0};   ///< Output\n\n    ros::Duration m_dt_s;          ///< Current delta time, in seconds\n    ros::Time     m_last_time_s;   ///< Last timestamp, used to track deltas\n\n    float64_t m_error{0.0};         ///< Current error\n    float64_t m_integral{0.0};      ///< Integral\n    float64_t m_last_error{0.0};    ///< Last error (previous iteration)\n\n    boost::circular_buffer<float64_t> m_ctl_buffer; ///< Circular buffer for ctl filter\n\n    PIDConfig m_cfg;           ///< PID Config\n};\n\n} // namespace vi\n\n#endif // VI_PID_controller_HPP\n", "meta": {"hexsha": "65eda3170a2b1af598015f7de5414ea7471a6be3", "size": 2414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/vehicle_interface/include/vehicle_interface/types/core/PIDController.hpp", "max_stars_repo_name": "WPI-Capstone-Project-Team-1-2020/Capstone-Final-Mile", "max_stars_repo_head_hexsha": "60cf6be95305ec720f001bf18327ae881168443c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/vehicle_interface/include/vehicle_interface/types/core/PIDController.hpp", "max_issues_repo_name": "WPI-Capstone-Project-Team-1-2020/Capstone-Final-Mile", "max_issues_repo_head_hexsha": "60cf6be95305ec720f001bf18327ae881168443c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/vehicle_interface/include/vehicle_interface/types/core/PIDController.hpp", "max_forks_repo_name": "WPI-Capstone-Project-Team-1-2020/Capstone-Final-Mile", "max_forks_repo_head_hexsha": "60cf6be95305ec720f001bf18327ae881168443c", "max_forks_repo_licenses": ["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.8222222222, "max_line_length": 87, "alphanum_fraction": 0.6768848384, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5340363510730296}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <cassert>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int>> Graph;\n\nvoid testcase()\n{\n  int n, m, k, x, y;\n  std::cin >> n >> m >> k >> x >> y;\n  assert(n >= 1 && n <= 1e4 && m >= 0 && m <= 1e5 && k >= 1 && k <= 10);\n  assert(x >= 0 && x < n && y >= 0 && y < n);\n\n  int total_nodes = n * (k + 1);\n  auto node_at = [n, k](int index, int layer) {\n    assert(index >= 0 && index < n && layer >= 0 && layer <= k);\n    return n * layer + index;\n  };\n\n  Graph G(total_nodes);\n  auto weights = boost::get(boost::edge_weight, G);\n  auto add_or_shorten_edge = [&G, weights](int from, int to, int weight) {\n    Graph::edge_descriptor test;\n    auto existing = boost::edge(from, to, G);\n    if (!existing.second || weights[existing.first] > weight)\n    {\n      boost::add_edge(from, to, weight, G);\n    }\n  };\n\n  for (int i = 0; i < m; i++)\n  {\n    int a, b, c, d;\n    std::cin >> a >> b >> c >> d;\n    assert(a != b && a >= 0 && a < n && b >= 0 && b < n && c >= 1 && c < (2 << 9) && (d == 0 || d == 1));\n\n    for (int j = 0; j <= k; j++)\n    {\n      if (d == 0 || j == k) // normal road or extra river\n      {\n        add_or_shorten_edge(node_at(a, j), node_at(b, j), c);\n      }\n      else // required river\n      {\n        add_or_shorten_edge(node_at(a, j), node_at(b, j + 1), c);\n        add_or_shorten_edge(node_at(a, j + 1), node_at(b, j), c);\n      }\n    }\n  }\n\n  std::vector<int> distances(total_nodes);\n  boost::dijkstra_shortest_paths(G, boost::vertex(node_at(x, 0), G), boost::distance_map(boost::make_iterator_property_map(distances.begin(), boost::get(boost::vertex_index, G))));\n\n  std::cout << distances.at(node_at(y, k)) << \"\\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": "b7297b95b7e9203e818957f2b44e5c4be8333e21", "size": 2000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "potw/tracking/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": "potw/tracking/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": "potw/tracking/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": 28.5714285714, "max_line_length": 180, "alphanum_fraction": 0.5525, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5340285718025449}}
{"text": "//\n// Created by dch on 21/02/18.\n//\n\n#include \"ImageIOAnalyze.h\"\n#include \"GadgetronTimer.h\"\n#include \"hoNDHarrWavelet.h\"\n#include \"hoNDRedundantWavelet.h\"\n#include \"hoNDArray_math.h\"\n#include \"simplexLagariaSolver.h\"\n#include \"twoParaExpDecayOperator.h\"\n#include \"twoParaExpRecoveryOperator.h\"\n#include \"curveFittingCostFunction.h\"\n#include \"cmr_t1_mapping.h\"\n#include <gtest/gtest.h>\n#include <boost/random.hpp>\n#include <chrono>\n\n#include <dlib/optimization.h>\n\n#include <ceres/ceres.h>\n#include <numeric>\n#define ITERATIONS 10000\n\n\nclass twoParaExpRecovery  {\npublic:\n\n    twoParaExpRecovery(std::vector<double> x,std::vector<double> y) : x_(x), y_(y) {}\n    template <typename T>\n            bool operator()(const T* const b, T* e) const {\n\n\n//        T sign_b1 = (b[1])/ceres::abs(b[1]);\n//        T rb = 1.0 / ( (ceres::abs(b[1])< T(FLT_EPSILON)) ? sign_b1*T(FLT_EPSILON) : b[1] );\n        T rb = 1.0 /b[1];\n\n        size_t ii;\n\n//        T result = T(0);\n        for (ii=0; ii< x_.size(); ii++)\n        {\n            T tmp = b[0] - b[0] * exp( -1 * x_[ii] * rb);\n            tmp -= y_[ii];\n//            result += tmp*tmp;\n            e[ii] = tmp;\n//            e[ii] = tmp*tmp;\n        }\n//        e[0] = result/T(x_.size());\n        return true;\n    }\n\nprivate:\n    std::vector<double> x_;\n    std::vector<double> y_;\n};\n\n\nvoid time_ceres(){\n    std::vector<double> b;\n\n auto start = std::chrono::high_resolution_clock::now();\n    for (int  i = 0; i < ITERATIONS; i++) {\n        ceres::Problem problem;\n\n        std::vector<double> y = {178, 185, 182, 189, 178, 180, 187, 179, 177, 177, 471};\n        auto x = std::vector<double>(11, 545);\n        x[10] = 10000;\n        b = {*std::max_element(y.begin(), y.end()), x[5]};\n        auto cost_function = new ceres::AutoDiffCostFunction<twoParaExpRecovery, 11, 2>(\n                new twoParaExpRecovery(x, y));\n//        auto cost_function = new ceres::NumericDiffCostFunction<twoParaExpRecovery,ceres::RIDDERS,ceres::DYNAMIC,2>(\n//                new twoParaExpRecovery(x,y),ceres::DO_NOT_TAKE_OWNERSHIP,1);\n        problem.AddResidualBlock(cost_function, NULL, b.data());\n\n        ceres::Solver::Options options;\n//        options.max_num_iterations = 15000;\n        options.linear_solver_type = ceres::DENSE_QR;\n//        options.use_explicit_schur_complement = true;\n    options.function_tolerance = 1e-4;\n    options.gradient_tolerance = 1e-4;\n        options.parameter_tolerance = 1e-4;\n//        options.preconditioner_type = ceres::IDENTITY;\n//    options.minimizer_type = ceres::LINE_SEARCH;\n//        options.line_search_direction_type = ceres::BFGS;\n//        options.trust_region_strategy_type = ceres::DOGLEG;\n//    options.dogleg_type = ceres::SUBSPACE_DOGLEG;\n\n\n        ceres::Solver::Summary summary;\n        ceres::Solve(options, &problem, &summary);\n//    std::cout << summary.FullReport() << std::endl;\n\n//        std::cout << \"B\" << b[0] << \" \" << b[1] << std::endl;\n\n    }\n\n     typedef Gadgetron::twoParaExpRecoveryOperator<std::vector<double> > SignalType;\n        typedef Gadgetron::leastSquareErrorCostFunction<std::vector<double> > CostType;\n\n        // define solver\n\n        // define signal model\n        SignalType t1_sr;\n\n        // define cost function\n        CostType lse;\n std::vector<double> y = {178, 185, 182, 189, 178, 180, 187, 179, 177, 177, 471};\n        auto x = std::vector<double>(11, 545);\n        x[10] = 10000;\n      auto cost_function2 = [&y, &x, &t1_sr,&lse](std::vector<double> b) {\n//            auto b2 = std::vector<double>{b(0), b(1)};\n            auto result = std::vector<double>(2);\n            t1_sr.magnitude(x, b, result);\n\n            double tmp = lse.eval(y,result);\n            return tmp;\n\n\n        };\n\n    std::cout <<\"Cost \" <<  cost_function2(b) << std::endl;\n\n    auto end = std::chrono::high_resolution_clock::now();\n\n    std::cout << \"Fitting tookz \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << std::endl;\n    std::cout << \"B \" << b[0] << \" \" << b[1] << std::endl;\n\n}\nvoid time_dlib(){\n\n    double best_cost;\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    dlib::matrix<double, 2, 1> b;\n    for (auto i  = 0; i < ITERATIONS; i++) {\n        typedef Gadgetron::twoParaExpRecoveryOperator<std::vector<double> > SignalType;\n        typedef Gadgetron::leastSquareErrorCostFunction<std::vector<double> > CostType;\n\n        // define solver\n\n        // define signal model\n        SignalType t1_sr;\n\n        // define cost function\n        CostType lse;\n//\n//    solver.signal_model_ = &t1_sr;\n//    solver.cf_ = &lse;\n//\n//    solver.max_iter_ = 150;\n//    solver.max_fun_eval_ = 1000;\n//    solver.thres_fun_ = 1e-4;\n//\n//    // set measured points\n//    solver.x_.resize(11, 545); // echo time, in ms\n//    solver.x_[10] = 10000;\n\n        std::vector<double> y = {178, 185, 182, 189, 178, 180, 187, 179, 177, 177, 471};\n        auto x = std::vector<double>(11, 545);\n        x[10] = 10000;\n\n\n        auto cost_function = [&y, &x, &t1_sr,&lse](const dlib::matrix<double, 2, 1> b) {\n            auto b2 = std::vector<double>{b(0), b(1)};\n            auto result = std::vector<double>(2);\n            t1_sr.magnitude(x, b2, result);\n\n            double tmp = lse.eval(y,result);\n            return tmp;\n\n\n        };\n\n        b(0) = *std::max_element(y.begin(), y.end());\n        b(1) = x[5];\n\n//        dlib::find_min_bobyqa(cost_function, b, 4, dlib::uniform_matrix<double>(2, 1, 0),\n//                              dlib::uniform_matrix<double>(2, 1, 1e5), 100, 1e-4, 150);\n        dlib::find_min_using_approximate_derivatives(dlib::bfgs_search_strategy(),dlib::objective_delta_stop_strategy(1e-4),cost_function,b,-1);\n//        dlib::find_min_\n//        auto result = dlib::find_min_global(cost_function,{0,0},{1e5,1e5},dlib::max_function_calls(10000));\n        best_cost = cost_function(b);\n\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n\n    std::cout << \"Fitting tookz \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << std::endl;\n\n    std::cout << \"Best cost \" << best_cost << \" \" << b << std::endl;\n}\nvoid time_gadgetron(){\n\n    double best_cost;\n    std::vector<float> b(2);\n    auto start = std::chrono::system_clock::now();\n    for (auto i = 0; i < ITERATIONS; i++) {\n        typedef Gadgetron::twoParaExpRecoveryOperator<std::vector<float> > SignalType;\n        typedef Gadgetron::leastSquareErrorCostFunction<std::vector<float> > CostType;\n\n        // define solver\n        Gadgetron::simplexLagariaSolver<std::vector<float>, SignalType, CostType> solver;\n\n        // define signal model\n        SignalType t1_sr;\n\n        // define cost function\n        CostType lse;\n\n        solver.signal_model_ = &t1_sr;\n        solver.cf_ = &lse;\n\n        solver.max_iter_ = 1500;\n        solver.max_fun_eval_ = 10000;\n        solver.thres_fun_ = 1e-6;\n\n        // set measured points\n        solver.x_.resize(11, 545); // echo time, in ms\n        solver.x_[10] = 10000;\n\n        solver.y_.resize(11); // intensity\n        solver.y_[0] = 178;\n        solver.y_[1] = 185;\n        solver.y_[2] = 182;\n        solver.y_[3] = 189;\n        solver.y_[4] = 178;\n        solver.y_[5] = 180;\n        solver.y_[6] = 187;\n        solver.y_[7] = 179;\n        solver.y_[8] = 177;\n        solver.y_[9] = 177;\n        solver.y_[10] = 471;\n\n        std::vector<float> guess(2, 0);\n        b[0] = 0;\n        b[1] = 0;\n\n        guess[0] = *std::max_element(solver.y_.begin(), solver.y_.end());\n        guess[1] = solver.x_[solver.x_.size() / 2];\n\n        solver.solve(b, guess);\n        best_cost = solver.best_cost_;\n    }\n    auto end = std::chrono::system_clock::now();\n\n    std::cout << \"Fitting tookz \" << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << std::endl;\n    std::cout << \"Best cost \" << best_cost << \" \" << b[0] << \" \" << b[1] <<  std::endl;\n}\nusing namespace Gadgetron;\nint main(){\n    time_gadgetron();\n    time_dlib();\n    time_ceres();\n}\n", "meta": {"hexsha": "24125dc99f3393e0b2aea582d01b8cd55b9e53f6", "size": 7992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/performance/benchmark_curvefitting.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "test/performance/benchmark_curvefitting.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "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/performance/benchmark_curvefitting.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["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.21875, "max_line_length": 144, "alphanum_fraction": 0.5850850851, "num_tokens": 2387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5340285621239957}}
{"text": "/*\r\n This program is free software; you can redistribute it and/or modify it under\r\n the terms of the European Union Public Licence - EUPL v.1.1 as published by\r\n the European Commission.\r\n\r\n This program is distributed in the hope that it will be useful, but WITHOUT\r\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r\n FOR A PARTICULAR PURPOSE. See the European Union Public Licence - EUPL v.1.1\r\n for more details.\r\n\r\n You should have received a copy of the European Union Public Licence - EUPL v.1.1\r\n along with this program.\r\n\r\n Further information about the European Union Public Licence - EUPL v.1.1 can\r\n also be found on the world wide web at http://ec.europa.eu/idabc/eupl\r\n\r\n*/\r\n\r\n/*\r\n ------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ----\r\n*/\r\n/*\r\n------------------ Author: Valentino Zuccarelli  -------------------------------------------------\r\n ------------------ E-mail: (Valentino.Zuccarelli@gmail.com) ----------------------------\r\n */\r\n\r\n#include \"math.h\"\r\n#include \"Astro-Core/propagateTHREEbody.h\"\r\n#include \"Astro-Core/threebodyParametersComputation.h\"\r\n#include \"halorbitcomputation.h\"\r\n#include \"trajectoryprinting.h\"\r\n#include \"Astro-Core/EODE/eode.h\"\r\n#include <QDebug>\r\n#include <QString>\r\n#include <ctime>\r\n#include <QFile>\r\n#include <QTextStream>\r\n#include <Eigen/LU>\r\n#include <Eigen/QR>\r\n\r\nusing namespace Eigen;\r\nextern double Grav_Param, bodies_distance;\r\nint halo_num_positions;\r\n#define Pi 3.14159265358979\r\nQString halo_input_data;\r\n\r\nvoid HaloOrbit::lpointsComputation ()\r\n{\r\n    double ni, csi_1, csi_2;\r\n\r\n    ni=pow(Grav_Param/(3*(1-Grav_Param)), 1.0/3.0);\r\n    csi_1=ni*(1-ni/3.0-(pow(ni,2.0))/9.0-23*(pow(ni,3.0))/81.0+151*(pow(ni,4.0))/243.0-(pow(ni,5.0))/9.0);\r\n    L1_xposition=(1-Grav_Param-csi_1);\t\t//L1 coordinate\r\n    csi_2=ni*(1+ni/3.0-(pow(ni,2.0))/9.0-31*(pow(ni,3.0))/81.0-119*(pow(ni,4.0))/243.0-(pow(ni,5.0))/9.0);\r\n    L2_xposition=(1+csi_2-Grav_Param);\t//L2 coordinate\r\n}\r\n\r\n\r\nvoid HaloOrbit::getAnalyticalApprox ()\r\n\r\n{\r\n        double gammaL, c[4], r1; int i;\r\n        r1=trajectory.Lpoint_Xposition/bodies_distance;\r\n        ////qdebug()<<bodies_distance;\r\n\r\n        if (trajectory.Lpoint_selected==1)\r\n                {\r\n                double oi=1.0-Grav_Param-r1;\r\n                gammaL=fabs(oi);\r\n                for (i=2;i<5;i++)\r\n                        c[i]=(pow(1.0,i)*Grav_Param+pow(-1.0,i)*(1-Grav_Param)*pow(gammaL,i+1)/pow(1.0-gammaL,i+1))/pow(gammaL,3);\r\n                }\r\n        else if (trajectory.Lpoint_selected==2)\r\n                {\r\n                gammaL=fabs(1-Grav_Param-r1);\r\n                for (i=2;i<5;i++)\r\n                        c[i]=(pow(-1.0,i)*Grav_Param+pow(-1.0,i)*(1-Grav_Param)*pow(gammaL,i+1)/pow(1.0+gammaL,i+1))/pow(gammaL,3);\r\n                }\r\n        else if (trajectory.Lpoint_selected==3)\r\n                {\r\n                gammaL=fabs(Grav_Param+r1);\r\n                for (i=2;i<5;i++)\r\n                        c[i]=(1-Grav_Param+(Grav_Param)*pow(gammaL,i+1)/pow(1.0+gammaL,i+1))/pow(gammaL,3);\r\n                }\r\n\r\n        double b, cc, lambda, k, delta, d1, d2;\r\n\r\n        b=c[2]-2; cc=-(c[2]-1)*(c[2]*2+1);\r\n        lambda=sqrt((-b+sqrt(pow(b,2.0)-4*cc))/2);\r\n        k=(pow(lambda,2)+1+2*c[2])/(2*lambda);\r\n        delta=pow(lambda,2)-c[2];\r\n        d1=3*pow(lambda,2)*(k*(6*pow(lambda,2.0)-1)-2*lambda)/k;\r\n        d2=8*pow(lambda,2)*(k*(11*pow(lambda,2.0)-1)-2*lambda)/k;\r\n\r\n        double a21, a22, a23, a24, a31, a32, b21, b22, b31, b32, d21, d31, d32;\r\n\r\n        a21=3*c[3]*(pow(k,2.0)-2)/(4*(1+2*c[2]));\r\n        a22=3*c[3]/(4*(1+2*c[2]));\r\n        a23=-3*c[3]*lambda*(3*lambda*pow(k,3.0)-6*k*(k-lambda)+4)/(4*k*d1);\r\n        a24=-3*c[3]*lambda*(3*lambda*k+2)/(4*k*d1);\r\n\r\n        b21=-3*c[3]*lambda*(3*k*lambda-4)/(2*d1);\r\n        b22=3*c[3]*lambda/d1;\r\n        a31=-9*lambda*(4*c[3]*(k*a23-b21)+k*c[4]*(4+pow(k,2)))/(4*d2)+((9*pow(lambda,2)+1-c[2])/(2*d2))*(3*c[3]*(2*a23-k*b21)+c[4]*(2+3*pow(k,2)));\r\n        d21=-c[3]/(2*pow(lambda,2));\r\n        a32=-(9*lambda*(4*c[3]*(k*a24-b22)+k*c[4])/4+3*(9*pow(lambda,2)+1-c[2])*(c[3]*(k*b22+d21-2*a24)-c[4])/2)/d2;\r\n        b31=3*(8*lambda*(3*c[3]*(k*b21-2*a23)-c[4]*(2+3*pow(k,2)))+(9*pow(lambda,2)+1+2*c[2])*(4*c[3]*(k*a23-b21)+k*c[4]*(4+pow(k,2))))/(8*d2);\r\n        b32=(9*lambda*(c[3]*(k*b22+d21-2*a24)-c[4])+3*(9*pow(lambda,2)+1+2*c[2])*(4*c[3]*(k*a24-b22)+k*c[4])/8)/d2;\r\n        d31=3*(4*c[3]*a24+c[4])/(64*pow(lambda,2));\r\n        d32=3*(4*c[3]*(a23-d21)+c[4]*(4+pow(k,2)))/(64*pow(lambda,2));\r\n\r\n        double teta, s1, s2, l1, l2, a1, a2;\r\n\r\n        a1=-3*c[3]*(2*a21+a23+5*d21)/2-3*c[4]*(12-pow(k,2))/8;\r\n        a2=3*c[3]*(a24-2*a22)/2+9*c[4]/8;\r\n        s1=(3*c[3]*(2*a21*(pow(k,2)-2)-a23*(pow(k,2)+2)-2*k*b21)/2-3*c[4]*(3*pow(k,4)-8*pow(k,2)+8)/8)/(2*lambda*(lambda*(1+pow(k,2))-2*k));\r\n        s2=(3*c[3]*(2*a22*(pow(k,2)-2)+a24*(pow(k,2)+2)+2*k*b22+5*d21)/2+3*c[4]*(12-pow(k,2))/8)/(2*lambda*(lambda*(1+pow(k,2))-2*k));\r\n        l1=a1+2*s1*pow(lambda,2);\r\n        l2=a2+2*s2*pow(lambda,2);\r\n\r\n        double Axmin, R1;\r\n\r\n        R1=bodies_distance*gammaL;\r\n        Axmin=(sqrt(fabs(delta/l1)))*R1;\r\n\r\n        if (trajectory.init_data.Ax_amplitude<Axmin)\r\n                trajectory.init_data.Ax_amplitude=Axmin;\r\n        double Ax, Az;\r\n        Az=trajectory.init_data.Az_amplitude/R1;\r\n        Ax=trajectory.init_data.Ax_amplitude/R1;\r\n\r\n        teta=0; i=0;\r\n\r\n        double temporary_Zposition=((Az*cos(teta)+d21*Ax*Az*(cos(2*teta)-3)+cos(3*teta)*(d32*Az*pow(Ax,2)-d31*pow(Az,3)))*R1)/bodies_distance;\r\n        if (temporary_Zposition<0)\r\n                i=20;\r\n        teta=Pi*0.05*i;\r\n        double temporary_Xposition=((a21*pow(Ax,2)+a22*pow(Az,2)-Ax*cos(teta)+(a23*pow(Ax,2)-a24*pow(Az,2))*cos(2*teta)+(a31*pow(Ax,3)-a32*Ax*pow(Az,2))*cos(3*teta))*R1)/bodies_distance;\r\n\r\n        trajectory.init_data.State.position.x()=r1+temporary_Xposition;\r\n        trajectory.init_data.State.position.z()=((Az*cos(teta)+d21*Ax*Az*(cos(2*teta)-3)+cos(3*teta)*(d32*Az*pow(Ax,2)-d31*pow(Az,3)))*R1)/bodies_distance;\r\n        trajectory.init_data.State.velocity.y()=((k*Ax*cos(teta)*lambda+(b21*pow(Ax,2)-b22*pow(Az,2))*cos(teta*2)*2*lambda+(b31*pow(Ax,3)-b32*Ax*pow(Az,2))*cos(3*teta)*3*lambda))*R1/bodies_distance;\r\n}\r\n\r\n\r\n\r\nMatrixXd STM(6,6);\r\n\r\nvoid HaloOrbit::getNumericalApprox (int system, int &MAX_integration_time)//, const Eigen::MatrixXd STM)\r\n\r\n{\r\n    clock_t start, end;\r\n    start= clock();\r\n    time_t t0, t1, diff;\r\n    double time_elapsed;\r\n\r\n    double paramv[1]={0}; double deriv[42]; double state[42];\r\n    trajectory.init_data.State.velocity.x()=trajectory.init_data.State.velocity.z()=trajectory.init_data.State.position.y()=trajectory.init_data.period=0;\r\n    trajectory.final_data.State.velocity.x()=trajectory.final_data.State.velocity.z()=1;\r\n\r\n    double timein, timefin, initialtimefin, relerr, abserr, accuracy, count, count2, T, step; int flag, k, q, p, l=0;\r\n    relerr=abserr=accuracy=1E-9; timefin=0; initialtimefin=0.25; //period   // 0.25!!!!!!!!!!!!!!!!!!!!!!! per velocizzare 1.0\r\n\r\n    double correction[6]; double z_correction, x_correction; double deriv_vel[3];\r\n\r\n    if (trajectory.init_data.State.velocity.y()<0) //check the initial y-velocity sign\r\n    {l=1;}\r\n\r\n    while (fabs(trajectory.final_data.State.velocity.x())>10e-8 || fabs( trajectory.final_data.State.velocity.z())>10e-8) //stop condition\r\n    {\r\n        T=0; step=0.01;\r\n        ////qdebug()<<\"before change\"<<timefin;\r\n        //if (timefin>initialtimefin)\r\n            //timefin=timefin-0.8;\r\n        //else\r\n//            timefin=initialtimefin;\r\n        timefin=0.3;\r\n        count=1;\r\n\r\n       while (count>0)\r\n       {\r\n           flag=1; timein=0; timefin=timefin+step;\r\n           for (p=0; p<42; p++)\r\n           {\r\n               state[p]=0;\r\n               deriv[p]=0;\r\n           }\r\n               state[1]=trajectory.init_data.State.velocity.y(); state[5]=trajectory.init_data.State.position.z();\r\n               state[0]=trajectory.init_data.State.velocity.x(); state[2]=trajectory.init_data.State.velocity.z();\r\n               state[3]=trajectory.init_data.State.position.x(); state[4]=trajectory.init_data.State.position.y();\r\n\r\n               state[41]=state[6]=state[13]=state[20]=state[27]=state[34]=1;\r\n               //qDebug()<<\"step0\"<<state[0]<<state[1]<<state[2]<<state[3]<<state[4]<<state[5];\r\n\r\n               while (flag!=2)\r\n               {\r\n                   flag=Runge_Kutta_Fehlberg(halorbit_EOM, 42, state, paramv, deriv, &timein, timefin, &relerr, abserr, flag);\r\n                   if (flag==4)\r\n                       flag=Runge_Kutta_Fehlberg(halorbit_EOM, 42, state, paramv, deriv, &timein, timefin, &relerr, abserr, flag);\r\n               }\r\n               //qDebug()<<\"step1\"<<state[0]<<state[1]<<state[2]<<state[3]<<state[4]<<state[5];\r\n               count=state[4];\r\n               if (l==1)\r\n                   count=-state[4];\r\n       }\r\n\r\n       count2=1;\r\n       end= clock(); time_elapsed=(double(end-start))/CLOCKS_PER_SEC;\r\n\r\n       if (time_elapsed>MAX_integration_time)\r\n       {\r\n           ////qdebug()<<\"Max time allowed:\"<<MAX_integration_time<<\"time elapsed\"<<time_elapsed;\r\n           trajectory.error=1;\r\n           return;\r\n       }\r\n\r\n       while (fabs(count2)>10e-12)\r\n       {\r\n           timefin=timefin-step;\r\n           step=step/10.0;\r\n           count2=1;\r\n           while (count2>0)\r\n           {\r\n               for (p=0; p<42; p++)\r\n               {\r\n                   state[p]=0;\r\n                   deriv[p]=0;\r\n               }\r\n                   flag=1; timein=0; timefin=timefin+step;\r\n                   state[1]=trajectory.init_data.State.velocity.y(); state[5]=trajectory.init_data.State.position.z();\r\n                   state[0]=trajectory.init_data.State.velocity.x(); state[2]=trajectory.init_data.State.velocity.z();\r\n                   state[3]=trajectory.init_data.State.position.x(); state[4]=trajectory.init_data.State.position.y();\r\n                   state[41]=state[6]=state[13]=state[20]=state[27]=state[34]=1;\r\n                   //qDebug()<<\"step2\"<<state[0]<<state[1]<<state[2]<<state[3]<<state[4]<<state[5];\r\n\r\n\r\n                   while (flag!=2)\r\n                   {\r\n                       flag=Runge_Kutta_Fehlberg(halorbit_EOM, 42, state, paramv, deriv, &timein, timefin, &relerr, abserr, flag);\r\n                       if (flag==4)\r\n                           flag=Runge_Kutta_Fehlberg(halorbit_EOM, 42, state, paramv, deriv, &timein, timefin, &relerr, abserr, flag);\r\n                   }\r\n                   //qDebug()<<\"step3\"<<state[0]<<state[1]<<state[2]<<state[3]<<state[4]<<state[5];\r\n\r\n                   count2=state[4];\r\n                   if (l==1)\r\n                       count2=-state[4];\r\n\r\n                   end=clock(); time_elapsed=(double(end-start))/CLOCKS_PER_SEC;\r\n\r\n                   if (time_elapsed>MAX_integration_time)\r\n                   {\r\n                       ////qdebug()<<\"Max time allowed:\"<<MAX_integration_time<<\"time elapsed\"<<time_elapsed;\r\n                       trajectory.error=1;\r\n                       return;\r\n                   }\r\n            }\r\n\r\n           trajectory.final_data.State.velocity.x()=state[0]; trajectory.final_data.State.velocity.y()=state[1]; trajectory.final_data.State.velocity.z()=state[2];\r\n           trajectory.final_data.State.position.x()=state[3]; trajectory.final_data.State.position.y()=state[4]; trajectory.final_data.State.position.z()=state[5];\r\n           trajectory.final_data.period=T=2*timefin;\r\n           correction[0]=state[12]; correction[1]=state[14]; correction[2]=state[24]; correction[3]=state[26]; correction[4]=state[36]; correction[5]=state[38];\r\n       }\r\n\r\n       ////qdebug()<<\"initial state\"<<trajectory.init_data.State.position.x()<<trajectory.init_data.State.position.z()<<trajectory.init_data.State.velocity.y();\r\n       ////qdebug()<<\"final state\"<<trajectory.final_data.State.position.y()<<trajectory.final_data.State.velocity.x()<<trajectory.final_data.State.velocity.z()<<timefin;\r\n       double C;\r\n       Jacobi (Grav_Param, trajectory.final_data.State.position.x(), trajectory.final_data.State.position.y(), trajectory.final_data.State.position.z(), trajectory.final_data.State.velocity.x(), trajectory.final_data.State.velocity.y(), trajectory.final_data.State.velocity.z(),C);\r\n       ////qdebug()<<\"C\"<<C;\r\n       if (fabs(trajectory.final_data.State.velocity.x())<10e-8 && fabs(trajectory.final_data.State.velocity.z())<10e-8)\r\n       {\r\n           for (k=0;k<6;k++)\r\n           {\r\n               for (p=0;p<6;p++)\r\n               {\r\n                   STM(k,p)=state[6*(k+1)+p];\r\n               }\r\n           }\r\n       }\r\n       else\r\n       {\r\n           double r1, r2;\r\n           r1=sqrt(pow(trajectory.final_data.State.position.x()+Grav_Param,2)+pow(trajectory.final_data.State.position.y(),2)+pow(trajectory.final_data.State.position.z(),2));\r\n           r2=sqrt(pow(trajectory.final_data.State.position.x()-1+Grav_Param,2)+pow(trajectory.final_data.State.position.y(),2)+pow(trajectory.final_data.State.position.z(),2));\r\n           deriv_vel[0]=2*trajectory.final_data.State.velocity.y()+trajectory.final_data.State.position.x()-(1-Grav_Param)*(trajectory.final_data.State.position.x()+Grav_Param)/(pow(r1,3))+ Grav_Param*(1-Grav_Param-trajectory.final_data.State.position.x())/(pow(r2,3));\r\n           deriv_vel[2]=-(1-Grav_Param)*trajectory.final_data.State.position.z()/(pow(r1,3))-Grav_Param*trajectory.final_data.State.position.z()/(pow(r2,3));\r\n\r\n           MatrixXd correction_matrix(2,2);\r\n           for (k=0; k<4; k++)\r\n           {\r\n               q=(k+2)/2;\r\n               int col = (k+1)/2-(q-1);\r\n               correction_matrix(q-1,col)=correction[k+2]-deriv_vel[2*(q-1)]*correction[k-2*(q-1)]/trajectory.final_data.State.velocity.y();\r\n               //correction_matrix[k]=correction[k+2]-deriv_vel[2*(q-1)]*correction[k-2*(q-1)]/trajectory.final_data.State.velocity.y();\r\n           }\r\n           //correction_matrix.inverse();\r\n           ////qdebug()<<\"inverse!\"<<correction_matrix.inverse()(0,0)<<correction_matrix.inverse()(0,1)<<correction_matrix.inverse()(1,0)<<correction_matrix.inverse()(1,1);\r\n           //determinant= correction_matrix[0]*correction_matrix[3]-correction_matrix[2]*correction_matrix[1];\r\n           //inverse_correction_matrix[0]=correction_matrix[3]/determinant;\r\n           //inverse_correction_matrix[1]=-correction_matrix[1]/determinant;\r\n           //inverse_correction_matrix[2]=-correction_matrix[2]/determinant;\r\n           //inverse_correction_matrix[3]=correction_matrix[0]/determinant;\r\n\r\n               //x_correction=-inverse_correction_matrix[0]*trajectory.final_data.State.velocity.x()-inverse_correction_matrix[1]*trajectory.final_data.State.velocity.z();\r\n               //z_correction=-inverse_correction_matrix[2]*trajectory.final_data.State.velocity.x()-inverse_correction_matrix[3]*trajectory.final_data.State.velocity.z();\r\n           x_correction=-correction_matrix.inverse()(0,0)*trajectory.final_data.State.velocity.x()-correction_matrix.inverse()(0,1)*trajectory.final_data.State.velocity.z();\r\n           z_correction=-correction_matrix.inverse()(1,0)*trajectory.final_data.State.velocity.x()-correction_matrix.inverse()(1,1)*trajectory.final_data.State.velocity.z();\r\n               trajectory.init_data.State.position.x()=trajectory.init_data.State.position.x()+x_correction;\r\n               trajectory.init_data.State.position.z()=trajectory.init_data.State.position.z()+z_correction;\r\n       }\r\n\r\n       }\r\n\r\n//qdebug()<<\"here|\";\r\n        int trajectory_error=0;\r\n        state[6]=T; state[0]=trajectory.init_data.State.velocity.x(); state[1]=trajectory.init_data.State.velocity.y(); state[2]=trajectory.init_data.State.velocity.z();\r\n        state[3]=trajectory.init_data.State.position.x(); state[4]=trajectory.init_data.State.position.y(); state[5]=trajectory.init_data.State.position.z();\r\n        QString save_path = \"3BMhalorbit\";\r\n        halo_input_data=save_path=save_path+QString::number(trajectory.init_data.Ax_amplitude,'f',0)+QString::number(trajectory.init_data.Az_amplitude,'f',0)+\".stae\";\r\n        halo_num_positions=trajectory.Num_positions;\r\n        trajectory_integration(state, trajectory.Num_positions, save_path, trajectory_error);\r\n        ////qdebug() << \"halo file: \" << save_path;\r\n\r\n        if (trajectory_error==2) //if the halo trajectory.txt has been not opened a message error must be given\r\n        {\r\n            trajectory.error=trajectory_error;\r\n            return;\r\n        }\r\n\r\n        //file 3BMsystem.stam\r\n        QString file = \"3BMsystem.stam\";\r\n        QFile threeBMsystemFile(file);\r\n        threeBMsystemFile.open(QIODevice::WriteOnly | QIODevice::Text);\r\n\r\n        QTextStream outsys(&threeBMsystemFile);\r\n        outsys.setRealNumberNotation(QTextStream::FixedNotation);\r\n        outsys.setRealNumberPrecision(16);\r\n        if (system==12)\r\n            system=30; //user system, as ICD states\r\n\r\n        outsys<<system<<\"\\n\";\r\n        outsys<<Grav_Param<<\"\\n\";\r\n        outsys<<bodies_distance<<\"\\n\";\r\n        outsys<<L1_xposition<<\"\\n\";\r\n        outsys<<L2_xposition<<\"\\n\";\r\n        threeBMsystemFile.close();\r\n        ////qdebug()<<file;\r\n\r\n        //computation of the real amplitudes obtained for the halo orbit\r\n        QFile haloFile1(save_path);\r\n        if (!haloFile1.open(QIODevice::ReadOnly | QIODevice::Text))\r\n            {trajectory.error=3;\r\n                return;\r\n            }\r\n\r\n        QTextStream in(&haloFile1);\r\n        double t,Vx,Vy,Vz,x,y,z,X_max=0, X_min=10,Z_max=0, Z_min=10;\r\n        for (p=0;p<trajectory.Num_positions;p++) //search for the maximum and minimum values of x and z coordinates\r\n                {\r\n                in>>t>>x>>y>>z>>Vx>>Vy>>Vz;\r\n                //qDebug()<<x<<z;\r\n                if (x<X_min)\r\n                        X_min=x;\r\n                if (x>X_max)\r\n                        X_max=x;\r\n                if (z<Z_min)\r\n                        Z_min=z;\r\n                if (z>Z_max)\r\n                        Z_max=z;\r\n                }\r\n        haloFile1.close();\r\n\r\n        trajectory.final_data.Ax_amplitude=(fabs(X_max)-fabs(X_min))/2;\ttrajectory.final_data.Az_amplitude=(fabs(Z_max)+fabs(Z_min))/2; //computation of the amplitudes obtained\r\n        if (trajectory.init_data.Az_amplitude<0)\r\n            trajectory.final_data.Az_amplitude=-trajectory.final_data.Az_amplitude;\r\n        //qDebug()<<trajectory.final_data.Az_amplitude<<trajectory.final_data.Ax_amplitude<<bodies_distance;\r\n        \r\n        //check on the real amplitudes obtained, if too different the manifolds computation will be not allowed\r\n        if (fabs((trajectory.final_data.Az_amplitude*bodies_distance-trajectory.init_data.Az_amplitude)/trajectory.init_data.Az_amplitude)>15 || fabs((trajectory.final_data.Ax_amplitude*bodies_distance-trajectory.init_data.Ax_amplitude)/trajectory.init_data.Ax_amplitude)>15)\r\n            trajectory.error=4;\r\n}\r\n\r\n\r\n\r\nvoid HaloOrbit::getManifolds (double eigen, int points_number, double period_manifolds, int &first)\r\n\r\n{\r\n        double initial_condition_perturbed[7], initial_condition_0[7]; const char * manifolds_save_path;\r\n        initial_condition_perturbed[6]=period_manifolds;\r\n\r\n        QFile file_manifolds_settings (\"3BMmanifolds_settings.stam\");\r\n        if (first==1)\r\n                {if (!file_manifolds_settings.open(QIODevice::WriteOnly | QIODevice::Text))\r\n                        {manifolds.error=3;\r\n                        return;}\r\n                }\r\n        else\r\n                {if (!file_manifolds_settings.open(QIODevice::Append | QIODevice::Text))\r\n                        {manifolds.error=3;\r\n                        return;}\r\n                }\r\n\r\n        QTextStream settings(&file_manifolds_settings);\r\n\r\n        if (manifolds.kind==1)\t//information about the manifolds required\r\n                manifolds_save_path=\"3BMmanifold_rightStable.stae\";\r\n        else if (manifolds.kind==2)\r\n                manifolds_save_path=\"3BMmanifold_rightUnstable.stae\";\r\n        else if (manifolds.kind==3)\r\n                manifolds_save_path=\"3BMmanifold_leftStable.stae\";\r\n        else if (manifolds.kind==4)\r\n                manifolds_save_path=\"3BMmanifold_leftUnstable.stae\";\r\n        else\r\n                {manifolds.error=5;\r\n                return;\r\n                }\r\n        settings<<manifolds.kind<<\"\\n\"<<trajectory.Num_positions<<\"\\n\";\t//the kind of manifold and the number of orbits are printed\r\n\r\n        if (period_manifolds!=0)\r\n                settings<<points_number<<\"\\n\";\t//the number of positions per orbit is printed in case a time of integration has been specified\r\n        file_manifolds_settings.close();\r\n\r\n        int i;\r\n       /////// if(trajectory.Num_positions>0) //normal manifolds computation\r\n\r\n\r\n             QString halo_data = \"3BMhalorbit\";\r\n        halo_data=halo_data+QString::number(trajectory.init_data.Ax_amplitude,'f',0)+QString::number(trajectory.init_data.Az_amplitude,'f',0)+\".stae\";\r\n        QFile file_halo2(halo_data);\r\n        if (!file_halo2.open(QIODevice::ReadOnly | QIODevice::Text))\r\n        {\r\n            manifolds.error=1;\r\n            return;\r\n        }\r\n        QTextStream in(&file_halo2);\r\n        for (i=1;i<trajectory.Num_positions+1;i++)\r\n                {\r\n                in>>initial_condition_0[6]>>initial_condition_0[3]>>initial_condition_0[4]>>initial_condition_0[5]>>initial_condition_0[0]>>initial_condition_0[1]>>initial_condition_0[2];\r\n\r\n                for (int j=0;j<6;j++)\r\n                        {initial_condition_perturbed[j]=initial_condition_0[j]-manifolds.epsilon*eigen*initial_condition_0[j];}\r\n                if (eigen<1) //condition in case of stable manifolds\r\n                {\r\n                    initial_condition_perturbed[0]=-initial_condition_perturbed[0];\r\n                    initial_condition_perturbed[4]=-initial_condition_perturbed[4];\r\n                    initial_condition_perturbed[5]=-initial_condition_perturbed[5];\r\n                    i=-i;\r\n                }\r\n                ////qdebug()<<\"Debug| Bon\"<<initial_condition_perturbed[0]<<initial_condition_perturbed[1]<<initial_condition_perturbed[2]<<initial_condition_perturbed[3]<<initial_condition_perturbed[4]<<initial_condition_perturbed[5]<<initial_condition_perturbed[6]<<points_number<<manifolds_save_path<<manifolds.error<<i<<trajectory.Lpoint_Xposition<<manifolds.kind;\r\n                manifolds_integration(initial_condition_perturbed, points_number, manifolds_save_path, manifolds.error, i, trajectory.Lpoint_Xposition, manifolds.kind);\r\n                i=abs(i);\r\n                if (manifolds.error!=0)\r\n                    return;\r\n                }\r\n\r\n                file_halo2.close();\r\n                if (i!=trajectory.Num_positions+1)\r\n                manifolds.error=5;\r\n\r\n        /* manifolds computation in case of transfer optimization\r\n           in this case only on trajectory is randomly computed\r\n        */\r\n\r\n       /*\r\n else\r\n\r\n        {\r\n            double paramv[1]={0}; double deriv[5]; double timefin, timein=0;\r\n            double relerr, abserr, accuracy; abserr=relerr=accuracy=1E-9;\r\n\r\n            for (int p=0; p<6; p++)\r\n                deriv[p]=0;\r\n            int flag=1;\r\n\r\n            extern double fractionOrbit;\r\n            timefin=trajectory.final_data.period*fractionOrbit;\r\n            //qdebug()<<\"time\"<<timefin<<trajectory.final_data.period<<fractionOrbit;\r\n            initial_condition_0[3]=trajectory.final_data.State.position.x();\r\n            initial_condition_0[4]=trajectory.final_data.State.position.y();\r\n            initial_condition_0[5]=trajectory.final_data.State.position.z();\r\n            initial_condition_0[0]=trajectory.final_data.State.velocity.x();\r\n            initial_condition_0[1]=trajectory.final_data.State.velocity.y();\r\n            initial_condition_0[2]=trajectory.final_data.State.velocity.z();\r\n//qdebug()<<\"Debug| 1\"<<initial_condition_0[0]<<initial_condition_0[1]<<initial_condition_0[2]<<initial_condition_0[3]<<initial_condition_0[4]<<initial_condition_0[5];\r\n//qdebug()<<timein;\r\ndouble initial_condition_1[5];\r\n        while (flag!=2)\r\n        {\r\n            flag=Runge_Kutta_Fehlberg(threebody_EOM, 6, initial_condition_0, paramv, deriv, &timein, timefin, &relerr, abserr, flag );\r\n            if (flag==4)\r\n                flag=Runge_Kutta_Fehlberg(threebody_EOM, 6, initial_condition_0, paramv, deriv, &timein, timefin, &relerr, abserr, flag );\r\n        //qdebug()<<timein;\r\n        }\r\n        for (int u=0; u<6; u++)\r\n            initial_condition_1[u]=initial_condition_0[u];\r\n\r\n\r\n//qdebug()<<\"Debug| 2\"<<initial_condition_1[0]<<initial_condition_1[1]<<initial_condition_1[2]<<initial_condition_1[3]<<initial_condition_1[4]<<initial_condition_1[5];\r\n        initial_condition_1[6]=0; //required intersection with a main body\r\n                for (int j=0;j<6;j++)\r\n                        {initial_condition_perturbed[j]=initial_condition_1[j]-manifolds.epsilon*eigen*initial_condition_1[j];}\r\n                i=1;\r\n                //qdebug()<<\"Debug| 3\"<<initial_condition_perturbed[0]<<initial_condition_perturbed[1]<<initial_condition_perturbed[2]<<initial_condition_perturbed[3]<<initial_condition_perturbed[4]<<initial_condition_perturbed[5];\r\n                if (eigen<1) //condition in case of stable manifolds\r\n                {\r\n                    initial_condition_perturbed[0]=-initial_condition_perturbed[0];\r\n                    initial_condition_perturbed[4]=-initial_condition_perturbed[4];\r\n                    initial_condition_perturbed[5]=-initial_condition_perturbed[5];\r\n                    i=-1;\r\n                }\r\n                //qdebug()<<\"Debug| final\"<<initial_condition_perturbed[0]<<initial_condition_perturbed[1]<<initial_condition_perturbed[2]<<initial_condition_perturbed[3]<<initial_condition_perturbed[4]<<initial_condition_perturbed[5]<<initial_condition_perturbed[6]<<points_number<<manifolds_save_path<<manifolds.error<<i<<trajectory.Lpoint_Xposition<<manifolds.kind;\r\n                manifolds_integration(initial_condition_perturbed, points_number, manifolds_save_path, manifolds.error, i, trajectory.Lpoint_Xposition, manifolds.kind);\r\n                if (manifolds.error!=0)\r\n                    return;\r\n        }\r\n        */\r\n\r\n        //qdebug()<<manifolds_save_path;\r\n        //qdebug()<<\"deviation:\"<<manifolds.epsilon;\r\n\r\n        ////qdebug()<<manifolds_save_path;\r\n        ////qdebug()<<\"deviation:\"<<manifolds.epsilon;\r\n\r\n}\r\n\r\n\r\n//subroutine to compute Eigenvalues\r\nvoid HaloOrbit::getEigenvalues ()\r\n\r\n{\r\n        MatrixXd mat1(6,6), mat2(6,6), mat3(6,6), fi(6,6);//, STM_inv(6,6);\r\n        mat2.setZero();\r\n        mat3.setZero();\r\n        mat1.setIdentity();\r\n        mat1=-mat1;\r\n\r\n        mat2(0,3)=mat2(1,4)=mat2(2,5)=-1;\r\n        mat2(3,0)=mat2(4,1)=mat2(5,2)=1;\r\n        mat2(3,4)=-2; mat2(4,3)=2;\r\n\r\n        mat3(0,1)=-2; mat3(1,0)=2;\r\n        mat3(0,3)=mat3(1,4)=mat3(2,5)=1;\r\n        mat3(3,0)=mat3(4,1)=mat3(5,2)=-1;\r\n        fi=mat1*STM.inverse()*mat2*mat3;\r\n\r\n\r\n        //Eigen libray doesn't support the eigenvalues computation of any matrix, but only of selfAdjoint matrix.\r\n        //because the STM is not such a matrix, the eigenvalues are computed in an alternative way.\r\n        //When the eigenvalues computation will be available also for this kind of matrix, it's stronly recommended\r\n        //to change this subroutine, by using the Eigen library.\r\n        //the following hidden part is the code able to compute eigenvalues for selfAdjoint matrix. By replacing that\r\n        //specific line, it will be possible to use the new subroutine of the Eigen library, when available.\r\n#if 0\r\n        //\r\n        VectorXd eigenvalues_vector(6);\r\n        eigenvalues_vector=fi.marked<SelfAdjoint>().eigenvalues();\r\n        //VectorXd eigenvalues(6);\r\n//cout<<fi;\r\n\r\n        //fi.eigenvalues();\r\n        //qdebug()<<\"fi\";\r\n        //qdebug()<<fi(0,0)<<fi(0,1)<<fi(0,2)<<fi(0,3)<<fi(0,4)<<fi(0,5);\r\n        //qdebug()<<fi(1,0)<<fi(1,1)<<fi(1,2)<<fi(1,3)<<fi(1,4)<<fi(1,5);\r\n        //qdebug()<<fi(2,0)<<fi(2,1)<<fi(2,2)<<fi(2,3)<<fi(2,4)<<fi(2,5);\r\n        //qdebug()<<fi(3,0)<<fi(3,1)<<fi(3,2)<<fi(3,3)<<fi(3,4)<<fi(3,5);\r\n        //qdebug()<<fi(4,0)<<fi(4,1)<<fi(4,2)<<fi(4,3)<<fi(4,4)<<fi(4,5);\r\n        //qdebug()<<fi(5,0)<<fi(5,1)<<fi(5,2)<<fi(5,3)<<fi(5,4)<<fi(5,5);\r\n        //qdebug()<<\"eigen\";\r\n        //qdebug()<<evve(0)<<evve(1)<<evve(2)<<evve(3)<<evve(4)<<evve(5);\r\n        ////qdebug()<<eigenvalues(0)<<eigenvalues(1)<<eigenvalues(2)<<eigenvalues(3)<<eigenvalues(4)<<eigenvalues(5);\r\n\r\n#endif\r\n\r\n         MatrixXd mm1(6,6);\r\n         mm1=fi;\r\n         double step=0.001;\r\n         double l=0; double h=1; int i;\r\n\r\n         while (abs(h)>0.00001)\r\n         {\r\n             if (l>1)\r\n             {\r\n                 l=0;\r\n                 step=step/10;}\r\n                 l=step+l;\r\n                 for (i=0;i<6;i++)\r\n                 {\r\n                     mm1(i,i)=fi(i,i)-l;}\r\n                     h=mm1.determinant();\r\n                     if (step<0.0000000001)\r\n                     {\r\n                         manifolds.error=4;\r\n                         return;}\r\n                     }\r\n\r\n         manifolds.eigen1=l;\r\n         manifolds.eigen2=1/l;\r\n         //double index=0.5*(manifolds.eigen1+1/manifolds.eigen1); //stability index\r\n}\r\n\r\n", "meta": {"hexsha": "006620e049206433d738f06cc221ae66064ab08c", "size": 29398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Lagrangian/halorbitcomputation.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "sta-src/Lagrangian/halorbitcomputation.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "sta-src/Lagrangian/halorbitcomputation.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 48.9151414309, "max_line_length": 369, "alphanum_fraction": 0.5860262603, "num_tokens": 8029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5340285572847208}}
{"text": "//#include \"Aggregate_Gen.hpp\"\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <Eigen/Dense>\n#include <omp.h>\n#include \"aggregate_gen_SA.hpp\"\nusing namespace Eigen;\nusing namespace std;\n\n\n//return pos_sph matrix\nvector<MatrixXd> aggregate_gen_CCA(const double& a, const int& num_sph_SA, const int& levels, const double& kf, const double& Df, const double& tol){\n\n  vector<MatrixXd> pos_sph_agg_output; // vector of aggregate geometry from level 0 to \"levels\".\n  int iter1max {1000};\n  int iter2max {10000};\n\n  int num_SA_agg= pow(2,levels);\n  int final_totnum_sph= num_SA_agg*num_sph_SA;\n  cout << \"final totnum_sph= \" << final_totnum_sph << endl;\n\n  vector<MatrixXd> pos_sph_SAagg;\n  for(int i= 0; i<num_SA_agg; ++i ) pos_sph_SAagg.push_back(aggregate_gen_SA(a,num_sph_SA,kf,Df,tol));\n\n  pos_sph_agg_output.push_back(pos_sph_SAagg[0]); // level 0 aggregate\n\n\n  vector<MatrixXd> pos_sph_agg_old;\n\n  // start time\n  chrono::time_point<chrono::steady_clock> CCA_start_time= chrono::steady_clock::now();\n\n  for(int k= 1; k <= levels; ++k){\n      cout << \"Generating aggregates in \" << k << \"th level ... please wait ...\" << endl;\n      vector<MatrixXd> pos_sph_agg;\n\n      for(int L= 1; L <= pow(2,levels-k); ++L){\n          //cout << \"generating \" << L << \" th \" << \"aggregate in level\" << k << endl;\n          int N1= num_sph_SA*pow(2,k-1);\n          int N2= N1;\n\n          // aggregation process in k-th level\n          MatrixXd pos_sph_agg1(3,N1);\n          MatrixXd pos_sph_agg2(3,N2);\n\n          if(k==1){\n            pos_sph_agg1= pos_sph_SAagg[2*L-2];\n            pos_sph_agg2= pos_sph_SAagg[2*L-1];\n          } else {\n            pos_sph_agg1= pos_sph_agg_old[2*L-2];\n            pos_sph_agg2= pos_sph_agg_old[2*L-1];\n          }\n\n          // random rotation of aggregate 1 around the centroid (origin)\n          double theta,phi; // polar angles\n          theta= acos(2.0f*urf(re)-1.0f);\n          phi= 2*M_PI*urf(re);\n\n          Vector3d nvec; // unit vector of rotation axis\n          nvec << sin(theta)*cos(phi),sin(theta)*sin(phi),cos(theta); //axis of rotation randomly choosen over unit sphere\n\n          double psi; // angle of rotation\n          psi= 2*M_PI*urf(re); // randomly choosen rotation angle\n\n          Matrix3d rot_mat; // 3D rotation matrix\n          rot_mat= AngleAxisd(psi,nvec);\n\n          for(int i= 0; i < pos_sph_agg1.cols(); ++i) pos_sph_agg1.col(i)=rot_mat*pos_sph_agg1.col(i); // random rotation of agg1\n\n          double R1_2; // square of gyration radius of agg1\n          double R2_2; // square of gyration radius of agg2\n          R1_2= a*a + pos_sph_agg1.colwise().squaredNorm().mean();\n          R2_2= a*a + pos_sph_agg2.colwise().squaredNorm().mean();\n\n          double rN;\n          rN= a*a*(N1+N2)*(N1+N2)/(N1*N2)*pow((N1+N2)/kf,2/Df)-(N1+N2)/N2*R1_2-(N1+N2)/N1*R2_2;\n          rN= sqrt(rN);\n\n          bool found {false};\n\n          //--- translation of agg1 to random position on the sphere of radius rN\n          for(int iter1= 0; iter1 != iter1max; ++iter1){\n\n              pos_sph_agg1.colwise() -= pos_sph_agg1.rowwise().mean(); // translate the centroid of agg1 to origin\n\n              double phi;\n              phi= 2*M_PI*urf(re);\n              double u; // uniform random number [-1.0,1.0)\n              u= 2*urf(re)-1.0;\n\n              Vector3d cen_pos_agg1; // centroid of agg1\n              cen_pos_agg1 << sqrt(1.0-u*u)*cos(phi), sqrt(1.0-u*u)*sin(phi), u;\n              cen_pos_agg1 *= rN; // cen_pos_agg1 is set to a uniform random cartesian position (x,y,z) over the spherical surface of radius rN\n              pos_sph_agg1.colwise() += cen_pos_agg1;\n\n              double theta;\n              theta= acos(2.0*urf(re)-1.0);\n              phi= 2*M_PI*urf(re);\n              Vector3d nvec; // unit vector of rotation axis\n              nvec << sin(theta)*cos(phi),sin(theta)*sin(phi),cos(theta); //axis of rotation randomly choosen over unit sphere\n\n              // random rotation of aggregate 2 around the centroid (origin)\n              #pragma omp parallel for\n              for(int iter2= 0; iter2 < iter2max; ++iter2){\n                  bool found_local;\n                  #pragma omp atomic read\n                  found_local= found;\n                  if(found) continue;\n\n                  MatrixXd pos_sph_agg1_thread(3,N1); // thread local copy of pos_sph_agg1\n                  MatrixXd pos_sph_agg2_thread(3,N2); // thread local copy of pos_sph_agg2\n                  pos_sph_agg1_thread= pos_sph_agg1;\n                  pos_sph_agg2_thread= pos_sph_agg2;\n\n                  double psi; // angle of rotation\n\n                  #pragma omp critical\n                  {\n                     psi= 2*M_PI*urf(re);\n                  }\n\n                  Matrix3d rot_mat; // 3D rotation matrix\n                  rot_mat= AngleAxisd(psi,nvec);\n                  for(int i= 0; i < N2; ++i) pos_sph_agg2_thread.col(i)=rot_mat*pos_sph_agg2_thread.col(i); // random rotation of agg2\n                  //  cout << \"iter2 pos_sph_agg2 \" << endl << pos_sph_agg2 << endl;\n\n                  bool attached {false};\n                  for(int i= 0; i < N2; ++i){\n                      RowVectorXd dist_pair(N1);\n                      dist_pair=(pos_sph_agg1_thread.colwise()-pos_sph_agg2_thread.col(i)).colwise().norm();\n                    //  cout << \"dist_pair\" << endl << dist_pair << endl;\n                      double mindist= dist_pair.minCoeff();\n                      //cout << \"2*a, mindist \" << 2*a << ' ' << mindist << endl;\n                      bool overrapped {mindist <= 2*a};\n                      if(overrapped) {\n                        //exit; // 20180813 removed\n                        attached= false; // 20180813 added\n                        break; // 20180813 added\n                      } else {\n                        attached= attached || (mindist < 2*a+tol);\n                      }\n                  }\n\n                  // construction of new aggregate if attached condition is satisfied\n                  if(attached){\n                      //cout << \"attached \" << attached << endl;\n                      MatrixXd pos_sph_agg_tmp(3,N1+N2);\n                      pos_sph_agg_tmp.block(0,0,3,N1)= pos_sph_agg1_thread;\n                      pos_sph_agg_tmp.block(0,N1,3,N2)= pos_sph_agg2_thread;\n                      pos_sph_agg_tmp.colwise() -= pos_sph_agg_tmp.rowwise().mean(); // translate the centroid of new agg to origin\n                      #pragma omp critical\n                      {\n                          pos_sph_agg.push_back(pos_sph_agg_tmp); // update the aggregate\n                          found = true;\n                          //break; // exit iter2 loop\n                          if(k==levels)  cout << \"number of threads for parallel search: \" << omp_get_num_threads() << endl;\n                      }\n\n                  }\n              }// iter2 loop\n\n              if(found) break; // exit iter1 loop\n\n              if(iter1 == iter1max){\n                  cout << \"calculation failed: iter1 reachs iter1max! \" << endl;\n                  abort();\n              }\n          }// iter1 loop\n      }// L loop\n\n      pos_sph_agg_old= move(pos_sph_agg);\n      pos_sph_agg_output.push_back(pos_sph_agg_old[0]);\n\n  }// k loop\n\n  auto CCA_end_time= chrono::steady_clock::now();\n\n  cout << \"CCA computation time: \"\n  << chrono::duration_cast<chrono::milliseconds>(CCA_end_time - CCA_start_time).count() << \" milliseconds\" << endl;\n\n  // geometry check for output\n  bool non_overlapped_all {true};\n  bool attached_at_least_1pair_all {true};\n\n  for(int k= 0; k <= levels; ++k){\n      MatrixXd pos_sph_agg_k_out {pos_sph_agg_output[k]};\n      int num_sph = num_sph_SA*pow(2,k);\n      assert(num_sph == pos_sph_agg_k_out.cols());\n      // final check of the attached condition\n      bool non_overlapped;\n      ArrayXd min_diff_from2a(num_sph);\n      for(int i= 0; i< num_sph; ++i){\n          ArrayXd distance_from_this_sph(num_sph);\n          distance_from_this_sph= (pos_sph_agg_k_out.colwise()-pos_sph_agg_k_out.col(i)).colwise().norm().array();\n          non_overlapped= {(distance_from_this_sph-2*a >= 0)(i) == false};\n          for(int j= 0; j< num_sph; ++j){\n              if(j != i) {\n                non_overlapped= non_overlapped && ((distance_from_this_sph-2*a > 0)(j) == true);\n              }\n          }\n         //cout << i << \", \" << (distance_from_this_sph-(2*a-buf_factor*tol) >= 0).transpose() << endl ;\n          min_diff_from2a(i)=((pos_sph_agg_k_out.colwise()-pos_sph_agg_k_out.col(i)).colwise().norm().array()-2*a).array().abs().minCoeff();\n      }\n      bool attached_at_least_1pair {min_diff_from2a.maxCoeff() < tol};\n      string non_overlapped_test= {non_overlapped ? \"Success\" : \"Failed\"};\n      string attached_at_least_1pair_test= {attached_at_least_1pair ? \"Success\" : \"Failed\"};\n      cout << k << \"th level, non_overlapped_check         : \" << non_overlapped_test << endl;\n      cout << k << \"th level, attached_at_least_1pair_check: \" << attached_at_least_1pair_test << endl;\n\n      non_overlapped_all = non_overlapped_all && non_overlapped;\n      attached_at_least_1pair_all = attached_at_least_1pair_all && attached_at_least_1pair;\n  }\n\n  if(non_overlapped_all && attached_at_least_1pair_all){\n    return pos_sph_agg_output;\n  }else{\n    cout << \"Geometry check failed! Please change tol.\" << endl;\n    exit(1);\n  }\n\n\n\n}\n", "meta": {"hexsha": "7ae0b21e9b1105e6cb2d36574812c9e09a556c16", "size": 9413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aggregate_gen_CCA.cpp", "max_stars_repo_name": "nmoteki/aggregate_generator", "max_stars_repo_head_hexsha": "93ce7699405ba42e4d4dbdd78d48cdd1db8f3344", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-10-27T08:12:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T14:22:46.000Z", "max_issues_repo_path": "aggregate_gen_CCA.cpp", "max_issues_repo_name": "nmoteki/aggregate_generator", "max_issues_repo_head_hexsha": "93ce7699405ba42e4d4dbdd78d48cdd1db8f3344", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aggregate_gen_CCA.cpp", "max_forks_repo_name": "nmoteki/aggregate_generator", "max_forks_repo_head_hexsha": "93ce7699405ba42e4d4dbdd78d48cdd1db8f3344", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-23T09:40:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T20:13:32.000Z", "avg_line_length": 41.4669603524, "max_line_length": 149, "alphanum_fraction": 0.569531499, "num_tokens": 2525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5340285524454456}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2016-2017 Oracle and/or its affiliates.\r\n// Contributed and/or modified by Vissarion Fisikopoulos, 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_STRATEGIES_GEOGRAPHIC_AREA_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_AREA_HPP\r\n\r\n\r\n#include <boost/geometry/core/srs.hpp>\r\n\r\n#include <boost/geometry/formulas/area_formulas.hpp>\r\n#include <boost/geometry/formulas/flattening.hpp>\r\n\r\n#include <boost/geometry/strategies/geographic/parameters.hpp>\r\n\r\n#include <boost/math/special_functions/atanh.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace area\r\n{\r\n\r\n/*!\r\n\\brief Geographic area calculation\r\n\\ingroup strategies\r\n\\details Geographic area calculation by trapezoidal rule plus integral\r\n         approximation that gives the ellipsoidal correction\r\n\\tparam PointOfSegment \\tparam_segment_point\r\n\\tparam FormulaPolicy Formula used to calculate azimuths\r\n\\tparam SeriesOrder The order of approximation of the geodesic integral\r\n\\tparam Spheroid The spheroid model\r\n\\tparam CalculationType \\tparam_calculation\r\n\\author See\r\n- Danielsen JS, The area under the geodesic. Surv Rev 30(232): 61\u201366, 1989\r\n- Charles F.F Karney, Algorithms for geodesics, 2011 https://arxiv.org/pdf/1109.4448.pdf\r\n\r\n\\qbk{\r\n[heading See also]\r\n[link geometry.reference.algorithms.area.area_2_with_strategy area (with strategy)]\r\n}\r\n*/\r\ntemplate\r\n<\r\n    typename PointOfSegment,\r\n    typename FormulaPolicy = strategy::andoyer,\r\n    std::size_t SeriesOrder = strategy::default_order<FormulaPolicy>::value,\r\n    typename Spheroid = srs::spheroid<double>,\r\n    typename CalculationType = void\r\n>\r\nclass geographic\r\n{\r\n    // Switch between two kinds of approximation(series in eps and n v.s.series in k ^ 2 and e'^2)\r\n    static const bool ExpandEpsN = true;\r\n    // LongSegment Enables special handling of long segments\r\n    static const bool LongSegment = false;\r\n\r\n    //Select default types in case they are not set\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 coordinate_type<PointOfSegment>::type,\r\n                double\r\n            >::type,\r\n        CalculationType\r\n    >::type CT;\r\n\r\nprotected :\r\n    struct spheroid_constants\r\n    {\r\n        Spheroid m_spheroid;\r\n        CT const m_a2;  // squared equatorial radius\r\n        CT const m_e2;  // squared eccentricity\r\n        CT const m_ep2; // squared second eccentricity\r\n        CT const m_ep;  // second eccentricity\r\n        CT const m_c2;  // squared authalic radius\r\n\r\n        inline spheroid_constants(Spheroid const& spheroid)\r\n            : m_spheroid(spheroid)\r\n            , m_a2(math::sqr(get_radius<0>(spheroid)))\r\n            , m_e2(formula::flattening<CT>(spheroid)\r\n                 * (CT(2.0) - CT(formula::flattening<CT>(spheroid))))\r\n            , m_ep2(m_e2 / (CT(1.0) - m_e2))\r\n            , m_ep(math::sqrt(m_ep2))\r\n            , m_c2(authalic_radius(spheroid, m_a2, m_e2))\r\n        {}\r\n    };\r\n\r\n    static inline CT authalic_radius(Spheroid const& sph, CT const& a2, CT const& e2)\r\n    {\r\n        CT const c0 = 0;\r\n\r\n        if (math::equals(e2, c0))\r\n        {\r\n            return a2;\r\n        }\r\n\r\n        CT const sqrt_e2 = math::sqrt(e2);\r\n        CT const c2 = 2;\r\n\r\n        return (a2 / c2) +\r\n                  ((math::sqr(get_radius<2>(sph)) * boost::math::atanh(sqrt_e2))\r\n                   / (c2 * sqrt_e2));\r\n    }\r\n\r\n    struct area_sums\r\n    {\r\n        CT m_excess_sum;\r\n        CT m_correction_sum;\r\n\r\n        // Keep track if encircles some pole\r\n        std::size_t m_crosses_prime_meridian;\r\n\r\n        inline area_sums()\r\n            : m_excess_sum(0)\r\n            , m_correction_sum(0)\r\n            , m_crosses_prime_meridian(0)\r\n        {}\r\n        inline CT area(spheroid_constants spheroid_const) const\r\n        {\r\n            CT result;\r\n\r\n            CT sum = spheroid_const.m_c2 * m_excess_sum\r\n                   + spheroid_const.m_e2 * spheroid_const.m_a2 * m_correction_sum;\r\n\r\n            // If encircles some pole\r\n            if (m_crosses_prime_meridian % 2 == 1)\r\n            {\r\n                std::size_t times_crosses_prime_meridian\r\n                        = 1 + (m_crosses_prime_meridian / 2);\r\n\r\n                result = CT(2.0)\r\n                         * geometry::math::pi<CT>()\r\n                         * spheroid_const.m_c2\r\n                         * CT(times_crosses_prime_meridian)\r\n                         - geometry::math::abs(sum);\r\n\r\n                if (geometry::math::sign<CT>(sum) == 1)\r\n                {\r\n                    result = - result;\r\n                }\r\n\r\n            }\r\n            else\r\n            {\r\n                result = sum;\r\n            }\r\n\r\n            return result;\r\n        }\r\n    };\r\n\r\npublic :\r\n    typedef CT return_type;\r\n    typedef PointOfSegment segment_point_type;\r\n    typedef area_sums state_type;\r\n\r\n    explicit inline geographic(Spheroid const& spheroid = Spheroid())\r\n        : m_spheroid_constants(spheroid)\r\n    {}\r\n\r\n    inline void apply(PointOfSegment const& p1,\r\n                      PointOfSegment const& p2,\r\n                      area_sums& state) const\r\n    {\r\n\r\n        if (! geometry::math::equals(get<0>(p1), get<0>(p2)))\r\n        {\r\n\r\n            typedef geometry::formula::area_formulas\r\n                <\r\n                    CT, SeriesOrder, ExpandEpsN\r\n                > area_formulas;\r\n\r\n            typename area_formulas::return_type_ellipsoidal result =\r\n                     area_formulas::template ellipsoidal<FormulaPolicy::template inverse>\r\n                                             (p1, p2, m_spheroid_constants);\r\n\r\n            state.m_excess_sum += result.spherical_term;\r\n            state.m_correction_sum += result.ellipsoidal_term;\r\n\r\n            // Keep track whenever a segment crosses the prime meridian\r\n            geometry::formula::area_formulas<CT>\r\n                    ::crosses_prime_meridian(p1, p2, state);\r\n        }\r\n    }\r\n\r\n    inline return_type result(area_sums const& state) const\r\n    {\r\n        return state.area(m_spheroid_constants);\r\n    }\r\n\r\nprivate:\r\n    spheroid_constants m_spheroid_constants;\r\n\r\n};\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\nnamespace services\r\n{\r\n\r\n\r\ntemplate <typename Point>\r\nstruct default_strategy<geographic_tag, Point>\r\n{\r\n    typedef strategy::area::geographic<Point> type;\r\n};\r\n\r\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\n}\r\n\r\n}} // namespace strategy::area\r\n\r\n\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_AREA_HPP\r\n", "meta": {"hexsha": "9c1c342cb4ed63ed70d1aa8d44bc39653fc00a84", "size": 6930, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Service/jni/boost/x86_64/include/boost-1_65_1/boost/geometry/strategies/geographic/area.hpp", "max_stars_repo_name": "Mattlk13/innoextract-android", "max_stars_repo_head_hexsha": "5a69382ac9104d47383c1af0aaa0bc8a336c9744", "max_stars_repo_licenses": ["Apache-2.0"], "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": "Service/jni/boost/x86_64/include/boost-1_65_1/boost/geometry/strategies/geographic/area.hpp", "max_issues_repo_name": "Mattlk13/innoextract-android", "max_issues_repo_head_hexsha": "5a69382ac9104d47383c1af0aaa0bc8a336c9744", "max_issues_repo_licenses": ["Apache-2.0"], "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": "Service/jni/boost/x86_64/include/boost-1_65_1/boost/geometry/strategies/geographic/area.hpp", "max_forks_repo_name": "Mattlk13/innoextract-android", "max_forks_repo_head_hexsha": "5a69382ac9104d47383c1af0aaa0bc8a336c9744", "max_forks_repo_licenses": ["Apache-2.0"], "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": 29.8706896552, "max_line_length": 99, "alphanum_fraction": 0.6047619048, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5340232088308792}}
{"text": "#include <iostream>\n\n#include \"sandbox/external/NanoGUI.h\"\n#include <nanogui/opengl.h>\n#include <nanogui/window.h>\n#include <nanogui/layout.h>\n#include <nanogui/slider.h>\n#include <nanogui/combobox.h>\n#include <nanogui/textbox.h>\n#include <nanogui/glcanvas.h>\n#include <nanogui/opengl.h>\n#include <nanogui/glutil.h>\n#include \"sandbox/SceneNode.h\"\n#include \"sandbox/base/RenderCallback.h\"\n#include \"sandbox/base/Transform.h\"\n#include \"sandbox/base/Camera.h\"\n#include \"sandbox/base/NodeRenderer.h\"\n#include \"sandbox/geometry/algorithms/SmoothNormals.h\"\n#include \"sandbox/geometry/shapes/Cylinder.h\"\n#include \"sandbox/geometry/shapes/Grid.h\"\n#include \"sandbox/geometry/Material.h\"\n#include \"sandbox/graphics/MeshRenderer.h\"\n#include \"sandbox/graphics/shaders/MaterialShader.h\"\n#include \"sandbox/graphics/Viewport.h\"\n#include \"sandbox/graphics/Window.h\"\n#include \"sandbox/graphics/RenderState.h\"\n#include \"sandbox/data/KdTree.h\"\n#include \"glm/glm.hpp\"\n#include <glm/gtc/matrix_access.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n#include <glm/gtc/type_ptr.hpp>\n#include <glm/gtc/quaternion.hpp>\n#include <cstdlib>\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"src/LeastSquares.h\" \n#include <algorithm>\n\nusing namespace sandbox;\n\nfloat xFrequency = 1.0;\n\nfloat function(float x, float y, float t) {\n\treturn 0.5*std::cos(2.0f*3.1415*y)*std::cos(xFrequency*2.0f*3.1415*(x+t));\n}\n\nfloat fx(float x, float y) {\n\treturn 0.5*std::cos(2.0f*3.1415*y)*std::sin(xFrequency*2.0f*3.1415*x)*-xFrequency*2.0f*3.1415;\n}\n\nfloat fy(float x, float y) {\n\treturn 0.5*std::sin(2.0f*3.1415*y)*std::cos(xFrequency*2.0f*3.1415*x)*-xFrequency*3.1415;\n}\n\nclass TestApp : public NanoguiScreen {\npublic:\n\n\t//TestApp() : NanoguiScreen(Eigen::Vector2i(1180, 980), \"Test App\") {\n\tTestApp() : NanoguiScreen(Eigen::Vector2i(1150, 600), \"Test App\") {\n\t\tusing namespace nanogui;\n\n\t\tGrid* grid = new Grid(30, 30);\n\t\tGrid* estGrid = new Grid(30, 30);\n\t\t\n\t\tSceneNode* eventNode = new SceneNode(&scene);\n\t\t\tNanoguiResizeEvent* resize = new NanoguiResizeEvent(this);\n\t\t\teventNode->addComponent(resize);\n\t\t\tResizeEventHandler* resizeCallback = (new ResizeCallback())->init(this);\n\t\t\tresize->subscribe(resizeCallback);\n\t\t\teventNode->addComponent(resizeCallback);\n\t\tSceneNode* geometryNode = new SceneNode(&scene);\n\t\t\tSceneNode* arrowNode = new SceneNode(geometryNode);\n\t\t\t\tarrowNode->addComponent(new Transform(glm::scale(glm::mat4(1.0f),glm::vec3(1.0f/1.25))*glm::translate(glm::mat4(1.0f),glm::vec3(0,2.0,0))));\n\t\t\t\tSceneNode* arrowTipNode = new SceneNode(arrowNode);\n\t\t\t\t\tglm::mat4 tipTrans = glm::translate(glm::mat4(1.0f),glm::vec3(0,0.25,0));\n\t\t\t\t\ttipTrans = glm::scale(tipTrans,glm::vec3(0.25f));\n\t\t\t\t\tarrowTipNode->addComponent(new Transform(tipTrans));\n\t\t\t\t\tarrowTipNode->addComponent(new Cylinder(20, 1.0f, 0.0f));\n\t\t\t\t\tarrowTipNode->addComponent(new MeshRenderer());\n\t\t\t\t\tMaterial* material = new Material();\n\t\t\t\t\tmaterial->setColor(glm::vec4(1.0f, 0, 0, 1));\n\t\t\t\t\tarrowTipNode->addComponent(material);\n\t\t\t\tSceneNode* cylNode = new SceneNode(arrowNode);\n\t\t\t\t\tglm::mat4 cylTrans = glm::translate(glm::mat4(1.0f),glm::vec3(0,-1.0,0));\n\t\t\t\t\tcylTrans = glm::scale(cylTrans,glm::vec3(0.1f, 1.0f, 0.1f));\n\t\t\t\t\tcylNode->addComponent(new Transform(cylTrans));\n\t\t\t\t\tcylNode->addComponent(new Cylinder(20));\n\t\t\t\t\tcylNode->addComponent(new MeshRenderer());\n\t\t\t\t\tmaterial = new Material();\n\t\t\t\t\tmaterial->setColor(glm::vec4(1.0f, 0, 0, 1));\n\t\t\t\t\tcylNode->addComponent(material);\n\t\t\tSceneNode* gridNode = new SceneNode(geometryNode);\n\t\t\t\tgridNode->addComponent(grid);\n\t\t\t\tgridNode->addComponent(new SmoothNormals());\n\t\t\t\tgridNode->addComponent(new MeshRenderer());\n\t\t\t\tgridNode->addComponent(new Material());\n\t\t\tSceneNode* estGridNode = new SceneNode(geometryNode);\n\t\t\t\testGridNode->addComponent(estGrid);\n\t\t\t\testGridNode->addComponent(new SmoothNormals());\n\t\t\t\testGridNode->addComponent(new MeshRenderer());\n\t\t\t\testGridNode->addComponent(new Material());\n\t\t\tSceneNode* sampleNode = new SceneNode(geometryNode);\n\t\t\t\tMesh* sampleMesh = new Mesh();\n\t\t\t\tsampleNode->addComponent(sampleMesh);\n\t\t\t\tsampleNode->addComponent(new MeshRenderer(GL_POINTS));\n\t\t\t\tMaterial* sampleMaterial = new Material();\n\t\t\t\tsampleMaterial->setColor(glm::vec4(1.0f,0,0,1));\n\t\t\t\tsampleNode->addComponent(sampleMaterial);\n\n\t\tgraphicsNode = new SceneNode(&scene);\n\t\t\tgraphicsNode->addComponent(new sandbox::Window(eventNode));\n\t\t\tgraphicsNode->addComponent((new OpenGLCallback())->init(this));\n\t\t\tSceneNode* functionViewNode = new SceneNode(graphicsNode);\t\t\t\t\n\t\t\t\tfunctionViewNode->addComponent(new PercentViewport(glm::vec4(0.0, 0.0, 0.5, 1.0)));\n\t\t\t\tfunctionViewNode->addComponent(new Transform(glm::translate(glm::mat4(1.0f),glm::vec3(0,2.5,5.0))));\n\t\t\t\tfunctionViewNode->addComponent(new Camera());\n\t\t\t\tfunctionViewNode->addComponent(new MaterialShader());\n\t\t\t\tSceneNode* functionNode = new SceneNode(functionViewNode);\n\t\t\t\t\tfunctionNode->addComponent(new Transform(glm::rotate(glm::mat4(1.0f), -3.1415f*1.0f/2.0f, glm::vec3(1.0f,0.0,0))*glm::scale(glm::mat4(1.0f), glm::vec3(3.0f,3.0f,1.0f*3.0f))));\n\t\t\t\t\tfunctionNode->addComponent(new NodeRenderer(gridNode));\n\t\t\t\tSceneNode* pointsNode = new SceneNode(functionViewNode);\n\t\t\t\t\tpointsNode->addComponent(new Transform(glm::rotate(glm::mat4(1.0f), -3.1415f*1.0f/2.0f, glm::vec3(1.0f,0.0,0))*glm::scale(glm::mat4(1.0f), glm::vec3(3.0f,3.0f,1.0f*3.0f))));\n\t\t\t\t\t//pointsNode->addComponent(new NodeRenderer(sampleNode));\n\t\t\tSceneNode* flatGraph = new SceneNode(graphicsNode);\n\t\t\t\tflatGraph->addComponent(new PercentViewport(glm::vec4(0.0, 0.5, 0.5, 0.5)));\n\t\t\t\tflatGraph->addComponent(new Transform(glm::translate(glm::mat4(1.0f),glm::vec3(0,0,3))));\n\t\t\t\tflatGraph->addComponent(new Camera());\n\t\t\t\tflatGraph->addComponent(new MaterialShader());\n\t\t\t\tSceneNode* flatPointsNode = new SceneNode(flatGraph);\n\t\t\t\t\tflatPointsNode->addComponent(new Transform(glm::rotate(glm::mat4(1.0f), 3.1415f*4.0f/2.0f, glm::vec3(1.0f,0.0,0))*glm::scale(glm::mat4(1.0f), glm::vec3(2.0f,2.0f,0.0f*2.0f))));\n\t\t\tfunctionViewNode = new SceneNode(graphicsNode);\t\t\t\t\n\t\t\t\t//functionViewNode->addComponent(new PercentViewport(glm::vec4(0.5, 0.0, 0.5, 0.5)));\n\t\t\t\tfunctionViewNode->addComponent(new PercentViewport(glm::vec4(0.5, 0.0, 0.5, 1.0)));\n\t\t\t\tfunctionViewNode->addComponent(new Transform(glm::translate(glm::mat4(1.0f),glm::vec3(0,2.5,5.0))));\n\t\t\t\tfunctionViewNode->addComponent(new Camera());\n\t\t\t\tfunctionViewNode->addComponent(new MaterialShader());\n\t\t\t\tfunctionNode = new SceneNode(functionViewNode);\n\t\t\t\t\tfunctionNode->addComponent(new Transform(glm::rotate(glm::mat4(1.0f), -3.1415f/2.0f, glm::vec3(1.0f,0.0,0))*glm::scale(glm::mat4(1.0f), glm::vec3(3.0f))));\n\t\t\t\t\tfunctionNode->addComponent(new NodeRenderer(estGridNode));\n\t\t\t\tSceneNode* estPointsNode = new SceneNode(functionViewNode);\n\t\t\t\t\testPointsNode->addComponent(new Transform(glm::rotate(glm::mat4(1.0f), -3.1415f*1.0f/2.0f, glm::vec3(1.0f,0.0,0))*glm::scale(glm::mat4(1.0f), glm::vec3(3.0f,3.0f,1.0f*3.0f))));\n\t\t\tSceneNode* estFlatGraph = new SceneNode(graphicsNode);\n\t\t\t\testFlatGraph->addComponent(new PercentViewport(glm::vec4(0.5, 0.5, 0.5, 0.5)));\n\t\t\t\testFlatGraph->addComponent(new Transform(glm::translate(glm::mat4(1.0f),glm::vec3(0,0,3))));\n\t\t\t\testFlatGraph->addComponent(new Camera());\n\t\t\t\testFlatGraph->addComponent(new MaterialShader());\n\t\t\t\tSceneNode* estFlatPointsNode = new SceneNode(estFlatGraph);\n\t\t\t\t\testFlatPointsNode->addComponent(new Transform(glm::rotate(glm::mat4(1.0f), 3.1415f*4.0f/2.0f, glm::vec3(1.0f,0.0,0))*glm::scale(glm::mat4(1.0f), glm::vec3(2.0f,2.0f,0.0f*2.0f))*glm::rotate(glm::mat4(1.0f), 3.1415f*0.0f/2.0f, glm::vec3(0.0f,0.0f,1.0f))));\n\n\n\t\tfloat time = 0.25;\n\n\t\tfor (int x = 0; x < grid->getWidth(); x++) {\n\t\t\tfor (int y = 0; y < grid->getHeight(); y++) {\n\t\t\t\tgrid->getNode(x,y).z = function(1.0f*x/(grid->getWidth()-1), 1.0f*y/(grid->getHeight()-1), time);\n\t\t\t}\n\t\t}\n\n\t\tint numSamples = 4000;\n\t\tstd::vector<glm::vec4> samplePoints;\n\n\t\t/*std::vector<int> xDim;\n\t\tfor (int f = 0; f < 10; f++) {\n\t\t\tcards.push_back(f);\n\t\t}\n\t\tstd::random_shuffle(cards.begin(), cards.end());\n\t\tfor (int f = 0; f < 10; f++) {\n\t\t\tstd::cout << cards[f] << std::endl;\n\t\t}*/\n\n\t\tstd::vector<float> xDim;\n\t\tstd::vector<float> yDim;\n\t\tstd::vector<float> tDim;\n\n\t\tint numSplits = 10;//grid->getWidth();\n\t\tfloat step = 1.0f/numSplits;\n\n\t\tfor (int f = 0; f < numSamples/numSplits; f++) {\n\t\t\tfor (int i = 0; i < numSplits; i++) {\n\t\t\t\txDim.push_back(step*i + step*float(std::rand())/RAND_MAX);\n\t\t\t\tyDim.push_back(step*i + step*float(std::rand())/RAND_MAX);\n\t\t\t\ttDim.push_back(step*i + step*float(std::rand())/RAND_MAX);\n\t\t\t}\n\t\t\tstd::random_shuffle(xDim.begin(), xDim.end());\n\t\t\tstd::random_shuffle(yDim.begin(), yDim.end());\n\t\t\tstd::random_shuffle(tDim.begin(), tDim.end());\n\n\t\t\tfor (int i = 0; i < numSplits; i++) {\n\t\t\t\tfloat x = xDim[i];\n\t\t\t\tfloat y = yDim[i];\n\t\t\t\tfloat t = tDim[i];\n\t\t\t\tfloat z = function(x,y,t);\n\t\t\t\tsamplePoints.push_back(glm::vec4(x,y,t,z));\n\t\t\t}\n\t\t\t/* random sampling\n\t\t\tfloat x = float(std::rand())/RAND_MAX;\n\t\t\tfloat y = float(std::rand())/RAND_MAX;\n\t\t\tfloat t = float(std::rand())/RAND_MAX;\n\t\t\tfloat z = function(x,y,t);\n\t\t\tsamplePoints.push_back(glm::vec4(x,y,t,z));*/\n\t\t}\n\n\n\t\tfor (int iteration = 0; iteration < 1; iteration++) {\n\n\t\t\tPointCollection pc(samplePoints);\n\n\t\t\tfor (int x = 0; x < grid->getWidth(); x++) {\n\t\t\t\tfor (int y = 0; y < grid->getHeight(); y++) {\n\t\t\t\t\t//estGrid->getNode(x,y).z = function(1.0f*x/(grid->getWidth()-1), 1.0f*y/(grid->getHeight()-1));\n\t\t\t\t\tfloat residual;\n\t\t\t\t\testGrid->getNode(x,y).z = calculateFromSamples(pc, glm::vec3(1.0f*x/(grid->getWidth()-1), 1.0f*y/(grid->getHeight()-1), time), &residual);\n\t\t\t\t\testGrid->getCoord(x,y).x = residual;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tglm::vec2 minMax;\n\t\t\tfor (int f = 0; f < pc.getPoints().size(); f++) {\n\t\t\t\tif (f == 0) {\n\t\t\t\t\tminMax = glm::vec2(pc.getEstResiduals()[f]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tminMax.x = minMax.x < pc.getEstResiduals()[f] ? minMax.x : pc.getEstResiduals()[f];\n\t\t\t\t\tminMax.y = minMax.y > pc.getEstResiduals()[f] ? minMax.y : pc.getEstResiduals()[f];\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tstd::cout << minMax.x << \", \"<< minMax.y << std::endl;\n\n\t\t\tfor (int x = 0; x < grid->getWidth(); x++) {\n\t\t\t\tfor (int y = 0; y < grid->getHeight(); y++) {\n\t\t\t\t\testGrid->getCoord(x,y).x = (estGrid->getCoord(x,y).x - minMax.x)/(minMax.y-minMax.x);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::vector<float> splits;\n\t\t\tstd::vector<int> splitSizes;\n\t\t\tfor (int f = 0; f < numSplits*numSplits*numSplits; f++) {\n\t\t\t\tsplits.push_back(0.0f);\n\t\t\t\tsplitSizes.push_back(0);\n\t\t\t}\n\n\t\t\tfor (int f = 0; f < pc.getPoints().size(); f++) {\n\t\t\t\tglm::vec4 splitIndex = pc.getActualPoints()[f];\n\t\t\t\tsplitIndex = splitIndex / step;\n\t\t\t\tint index = (int(splitIndex.x)*numSplits+int(splitIndex.y))*numSplits+int(splitIndex.z);\n\t\t\t\tsplits[index] += pc.getEstResiduals()[f];\n\t\t\t\tsplitSizes[index]++;\n\t\t\t}\n\n\t\t\tfloat totalResidual = 0.0f;\n\t\t\tfor (int f = 0; f < splits.size(); f++) {\n\t\t\t\tif (splitSizes[f] > 0) {\n\t\t\t\t\tsplits[f] = splits[f]/splitSizes[f];\n\t\t\t\t}\n\t\t\t\ttotalResidual += splits[f];\n\t\t\t}\n\n\t\t\tint numS = 0;\n\t\t\tfor (int f = 0; f < splits.size(); f++) {\n\t\t\t\tsplits[f] /= totalResidual;\n\t\t\t\t//std::cout << splits[f]*numSamples << std::endl;\n\t\t\t\tnumS += std::round(splits[f]*numSamples);\n\t\t\t}\n\n\t\t\t//std::cout << numS << std::endl;\n\n\t\t\t/*for (int x = 0; x < numSplits; x++) {\n\t\t\t\tfor (int y = 0; y < numSplits; y++) {\n\t\t\t\t\tfor (int t = 0; t < numSplits; 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\tfor (int x = 0; x < numSplits; x++) {\n\t\t\t\tfor (int y = 0; y < numSplits; y++) {\n\t\t\t\t\tfor (int t = 0; t < numSplits; t++) {\n\t\t\t\t\t\tint index = (x*numSplits+y)*numSplits+t;\n\t\t\t\t\t\tfor (int f = 0; f < std::round(1.0f*splits[index]*numSamples); f++) {\n\t\t\t\t\t\t\tfloat x2 = 1.0f*step*x + step*float(std::rand())/RAND_MAX;\n\t\t\t\t\t\t\tfloat y2 = 1.0f*step*y + step*float(std::rand())/RAND_MAX;\n\t\t\t\t\t\t\tfloat t2 = 1.0f*step*t + step*float(std::rand())/RAND_MAX;\n\t\t\t\t\t\t\tfloat z2 = function(x2,y2,t2);\n\t\t\t\t\t\t\t//std::cout << samplePoints.size() << \" \" << x << \" \" << x2 << \" \" << y2 << \" \" << t2 << \" \" << z2 << \" \" << splits[index] << \" \" << step << std::endl;\n\t\t\t\t\t\t\tsamplePoints.push_back(glm::vec4(x2,y2,t2,z2));\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\t// vector estimate\n\t\t\t/*std::vector<glm::vec4> newPoints;\n\t\t\tfor (int f = 0; f < pc.getPoints().size(); f++) {\n\t\t\t\tfloat randPercent = 2.0f*(float(std::rand())/RAND_MAX - 0.5);\n\t\t\t\tglm::vec4 newPoint = pc.getActualPoints()[f] + glm::vec4(pc.getEstGradients()[f]*randPercent,0.0);\n\t\t\t\tnewPoint.w = function(newPoint.x, newPoint.y, newPoint.z);\n\t\t\t\tnewPoints.push_back(newPoint);\n\t\t\t}\n\n\t\t\tfor (int f = 0; f < newPoints.size(); f++) {\n\t\t\t\tsamplePoints.push_back(newPoints[f]);\n\t\t\t}*/\n\n\t\t\t/*for (int f = 0; f < numSamples; f++) {\n\t\t\t\tfloat x = float(std::rand())/RAND_MAX;\n\t\t\t\tfloat y = float(std::rand())/RAND_MAX;\n\t\t\t\tfloat t = float(std::rand())/RAND_MAX;\n\t\t\t\tfloat z = function(x,y,t);\n\t\t\t\tsamplePoints.push_back(glm::vec4(x,y,t,z));\n\t\t\t}*/\n\n\t\t\t/*float totalResidual = 0.0f;\n\t\t\tfloat dr = 1.0f/pc.getPoints().size();\n\t\t\tfor (int f = 0; f < pc.getPoints().size(); f++) {\n\t\t\t\ttotalResidual += (pc.getEstResiduals()[f]-minMax.x)/(pc.getEstResiduals()[f]-minMax.y - pc.getEstResiduals()[f]-minMax.x);\n\t\t\t}*/\n\n\t\t\t/*splits.clear();\n\t\t\ttotalResidual = 0.0f;\n\t\t\tfor (int x = 0; x < numSplits; x++) {\n\t\t\t\tfor (int y = 0; y < numSplits; y++) {\n\t\t\t\t\tfor (int t = 0; t < numSplits; t++) {\n\t\t\t\t\t\tfloat newX = 1.0f*step*x + 0.5*step;\n\t\t\t\t\t\tfloat newY = 1.0f*step*y + 0.5*step;\n\t\t\t\t\t\tfloat newT = 1.0f*step*t + 0.5*step;\n\t\t\t\t\t\t//estGrid->getNode(x,y).z = function(1.0f*x/(grid->getWidth()-1), 1.0f*y/(grid->getHeight()-1));\n\n\t\t\t\t\t\tint numNearest = 1;\n\t\t\t\t\t\tstd::vector<float> point;\n\t\t\t\t\t\tpoint.push_back(newX);\n\t\t\t\t\t\tpoint.push_back(newY);\n\t\t\t\t\t\tpoint.push_back(newT);\n\t\t\t\t\t\tstd::vector<KdTree<float>::KdValue> nearest = pc.getKdTree().getNearestSorted(point, numNearest);\n\n\t\t\t\t\t\tfloat residual = pc.getEstResiduals()[nearest[0].index];\n\t\t\t\t\t\t//std::cout << newX << \" \" << newY << \" \" << newT << \" \" << pc.getEstResiduals()[nearest[0].index] << std::endl;\n\t\t\t\t\t\tsplits.push_back(residual);\n\t\t\t\t\t\ttotalResidual += residual;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int f = 0; f < splits.size(); f++) {\n\t\t\t\tsplits[f] /= totalResidual;\n\t\t\t}\n\n\t\t\tint splitIndex = 0;\n\t\t\tfor (int x = 0; x < numSplits; x++) {\n\t\t\t\tfor (int y = 0; y < numSplits; y++) {\n\t\t\t\t\tfor (int t = 0; t < numSplits; t++) {\n\t\t\t\t\t\tfor (int f = 0; f < int(splits[splitIndex]*numSamples); f++) {\n\t\t\t\t\t\t\tfloat newX = 1.0f*step*x + step*float(std::rand())/RAND_MAX;\n\t\t\t\t\t\t\tfloat newY = 1.0f*step*y + step*float(std::rand())/RAND_MAX;\n\t\t\t\t\t\t\tfloat newT = 1.0f*step*t + step*float(std::rand())/RAND_MAX;\n\t\t\t\t\t\t\tfloat newZ = function(newX, newY, newT);\n\t\t\t\t\t\t\tsamplePoints.push_back(glm::vec4(newX, newY, newT, newZ));\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsplitIndex++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*for (int f = 0; f < numSamples; f++) {\n\t\t\t\tfloat x = float(std::rand())/RAND_MAX;\n\t\t\t\tfloat y = float(std::rand())/RAND_MAX;\n\t\t\t\tfloat t = float(std::rand())/RAND_MAX;\n\t\t\t\tfloat z = function(x,y,t);\n\t\t\t\tsamplePoints.push_back(glm::vec4(x,y,t,z));\n\t\t\t}*/\n\t\t\tstd::cout << samplePoints.size() << std::endl;\n\t\t}\n\n\t\t\n    \tresizeEvent(Eigen::Vector2i(width(), height()));\n\t}\n\n\tclass PointCollection : public KdSearchable<float> {\n\tpublic:\n\n\t\tclass ObjectiveFunction {\n\t\tpublic:\n\t\t\tvirtual ~ObjectiveFunction() {}\n\t\t\tvirtual float getValue(int sampleNum, const glm::vec4& point) const {\n\t\t\t\treturn point.w;\n\t\t\t}\n\t\t};\n\n\t\tclass GradObjectiveFunction : public ObjectiveFunction {\n\t\tpublic:\n\t\t\tGradObjectiveFunction(int dim, PointCollection* pc) : dim(dim), pc(pc) {}\n\t\t\tvirtual ~GradObjectiveFunction() {}\n\t\t\tvirtual float getValue(int sampleNum, const glm::vec4& point) const {\n\t\t\t\treturn pc->estGradients[sampleNum][dim];\n\t\t\t}\n\t\tprivate:\n\t\t\tint dim;\n\t\t\tPointCollection* pc;\n\t\t};\n\n\t\tconst glm::vec3 calculateGradient(int numNearest, glm::vec4 estPoint, float value, bool pointIsSample, const ObjectiveFunction* objFunction, float* residual = NULL) const {\n\t\t\tint startNearest = pointIsSample ? 1 : 0;\n\n\t\t\tEigen::MatrixXf A = Eigen::MatrixXf(numNearest-startNearest, 3);\n\t\t\tEigen::VectorXf b = Eigen::VectorXf(numNearest-startNearest);\n\n\t\t\tstd::vector<float> point;\n\t\t\tpoint.push_back(estPoint[0]);\n\t\t\tpoint.push_back(estPoint[1]);\n\t\t\tpoint.push_back(estPoint[2]);\n\t\t\t//point.push_back(estPoint[3]);\n\n\t\t\tstd::vector<KdTree<float>::KdValue> nearest = kdTree->getNearestSorted(point, numNearest);\n\n\t\t\tfor (int f = startNearest; f < nearest.size(); f++) {\n\t\t\t\tglm::vec3 diff = glm::vec3(points[nearest[f].index]-estPoint);\n\t\t\t\tglm::vec3 dir = normalize(diff);\n\t\t\t\tfloat dirDeriv = (objFunction->getValue(nearest[f].index, points[nearest[f].index])-value)/(glm::length(diff));\n\n\t\t\t\tEigen::VectorXf d(3);\n\t\t\t\td[0] = dir[0];\n\t\t\t\td[1] = dir[1];\n\t\t\t\td[2] = dir[2];\n\n\t\t\t\tb[f-startNearest] = dirDeriv;\n\t\t\t\tA.block(f-startNearest, 0, 1, 3) = d.transpose();\n\t\t\t}\n\n\t\t\tEigen::VectorXf sol = calculateLeastSquares(A,b);\n\t\t\tif (residual) {\n\t\t\t\t*residual = (A * sol - b).norm();\n\t\t\t}\n\t\t\t\n\t\t\treturn glm::vec3(sol[0], sol[1], sol[2]);\n\t\t}\n\n\t\tPointCollection(const std::vector<glm::vec4>& points) : points(points) {\n\t\t\tfor (int f = 0; f < points.size(); f++) {\n\t\t\t\tindices.push_back(f);\n\t\t\t}\n\n\t\t\tstd::vector<unsigned int> dimensions;\n\t\t\tdimensions.push_back(0);\n\t\t\tdimensions.push_back(1);\n\t\t\tdimensions.push_back(2);\n\t\t\t//dimensions.push_back(3);\n\t\t\tkdTree = new KdTree<float>(dimensions, *this, new EuclideanDistance<float>());\n\n\t\t\tint numNearest = 11;\n//\t\t\tEigen::MatrixXf A = Eigen::MatrixXf(numNearest-1, 3);\n//\t\t\tEigen::VectorXf b = Eigen::VectorXf(numNearest-1);\n\n\t\t\tObjectiveFunction fun;\n\n\t\t\tfor (int sampleNum = 0; sampleNum < points.size(); sampleNum++) {\t\n\t\t\t\tfloat residual;\n\t\t\t\tglm::vec3 gradient = calculateGradient(numNearest, points[sampleNum], points[sampleNum].w, true, &fun, &residual);\n\t\t\t\testGradients.push_back(gradient);\n\t\t\t\testResiduals.push_back(residual);\n\t\t\t\n\t\t\t\t/*std::vector<float> point;\n\t\t\t\tpoint.push_back(points[sampleNum][0]);\n\t\t\t\tpoint.push_back(points[sampleNum][1]);\n\t\t\t\tpoint.push_back(points[sampleNum][2]);\n\t\t\t\tpoint.push_back(points[sampleNum][3]);\n\t\t\t\tstd::vector<KdTree<float>::KdValue> nearest = kdTree->getNearestSorted(point, numNearest);\n\n\t\t\t\tfor (int f = 1; f < nearest.size(); f++) {\n\t\t\t\t\tglm::vec4 diff = points[nearest[f].index]-points[sampleNum];\n\t\t\t\t\tglm::vec3 dir = normalize(glm::vec3(diff));\n\t\t\t\t\tfloat dirDeriv = diff.w/(glm::length(glm::vec3(diff)));\n\n\t\t\t\t\tEigen::VectorXf d(3);\n\t\t\t\t\td[0] = dir[0];\n\t\t\t\t\td[1] = dir[1];\n\t\t\t\t\td[2] = dir[2];\n\n\t\t\t\t\tb[f-1] = dirDeriv;\n\t\t\t\t\tA.block(f-1, 0, 1, 3) = d.transpose();\n\t\t\t\t}\n\n\n\t\t\t\tEigen::VectorXf sol = calculateLeastSquares(A,b);\n\t\t\t\tfloat residual = (A * sol - b).norm();\n\t\t\t\testGradients.push_back(glm::vec3(sol[0], sol[1], sol[2]));\n\t\t\t\testResiduals.push_back(residual);*/\n\t\t\t}\n\n\t\t\t// calculate Hessians\n\t\t\tstd::vector<GradObjectiveFunction> dimFunctions;\n\t\t\tdimFunctions.push_back(GradObjectiveFunction(0, this));\n\t\t\tdimFunctions.push_back(GradObjectiveFunction(1, this));\n\t\t\tdimFunctions.push_back(GradObjectiveFunction(2, this));\n\t\t\tfor (int sampleNum = 0; sampleNum < points.size(); sampleNum++) {\n\t\t\t\tglm::mat3 hessian(1.0f);\n\t\t\t\tfor (int f = 0; f < 3; f++) {\n\t\t\t\t\tglm::vec3 gradient = calculateGradient(numNearest, points[sampleNum], estGradients[sampleNum][f], true, &(dimFunctions[f]));\n\t\t\t\t\thessian = glm::row(hessian, f, gradient);\n\t\t\t\t\t//std::cout << \"Grad: \" << f << \" \"  << gradient[0] << \" \" << gradient[1] << \" \" << gradient[2] << std::endl;\n\t\t\t\t\t//std::cout << \"Hessian: \" << f << \" \"  << glm::row(hessian, f)[0] << \" \" << glm::row(hessian, f)[1] << \" \" << glm::row(hessian, f)[2] << std::endl;\n\t\t\t\t}\n\n\t\t\t\testHessians.push_back(hessian);\n\t\t\t}\n\n\t\t\tdimensions.clear();\n\t\t\tdimensions.push_back(0);\n\t\t\tdimensions.push_back(1);\n\t\t\tdimensions.push_back(2);\n\t\t\tqueryKdTree = new KdTree<float>(dimensions, *this, new EuclideanDistance<float>());\n\n\t\t}\n\t\t~PointCollection() {\n\t\t\tdelete kdTree;\n\t\t\tdelete queryKdTree;\n\t\t}\n\n\t\tconst std::vector<unsigned int>& getPoints() const { return indices; }\n\t\tfloat getDimension(unsigned int index, unsigned int dimension) const { return points[index][dimension]; }\n\t\tconst std::vector<glm::vec4>& getActualPoints() const { return points; }\n\t\tconst std::vector<glm::vec3>& getEstGradients() const { return estGradients; }\n\t\tconst std::vector<float>& getEstResiduals() const { return estResiduals; }\n\t\tconst std::vector<glm::mat3>& getEstHessians() const { return estHessians; }\n\t\tconst KdTree<float>& getKdTree() const { return *queryKdTree; }\n\tprivate:\n\t\tstd::vector<glm::vec4> points;\n\t\tstd::vector<unsigned int> indices;\n\t\tstd::vector<glm::vec3> estGradients;\n\t\tstd::vector<float> estResiduals;\n\t\tstd::vector<glm::mat3> estHessians;\n\t\tKdTree<float>* kdTree;\n\t\tKdTree<float>* queryKdTree;\n\t};\n\n\n\tfloat calculateFromSamples(const PointCollection& pc, const glm::vec3& pos, float* residual) {\n\t\t//return 0.0f;\n\t\t\t\t/*if (true) {//recalculateZ_FirstHalf) { // nearest directional deriv\n\t\t\t\t\tnumAlgorithms++;\n\t\t\t\t\tglm::vec3 diff = samplePoints[sampleNum]-samplePoints[nearest[0].index];\n\t\t\t\t\tglm::vec2 dir = normalize(glm::vec2(diff));\n\t\t\t\t\tfloat dirDeriv = glm::dot(estGradients[nearest[0].index],dir);\n\t\t\t\t\tzEstimate = samplePoints[nearest[0].index].z + dirDeriv*glm::length(glm::vec2(diff));\n\n\t\t\t\t\tfinalEstimate += zEstimate;\n\t\t\t\t}*/\n\t\tint numNearest = 10;\n\n\t\tstd::vector<float> point;\n\t\tpoint.push_back(pos[0]);\n\t\tpoint.push_back(pos[1]);\n\t\tpoint.push_back(pos[2]);\n\n\t\tstd::vector<KdTree<float>::KdValue> nearest = pc.getKdTree().getNearestSorted(point, numNearest);\n\n\t\tglm::vec3 diff = pos-glm::vec3(pc.getActualPoints()[nearest[0].index]);\n\t\tglm::vec3 dir = normalize(diff);\n\t\tfloat dirDeriv = glm::dot(pc.getEstGradients()[nearest[0].index],dir);\n\n\t\t*residual = pc.getEstResiduals()[nearest[0].index];\n\n\t\t//return pc.getActualPoints()[nearest[0].index].w + dirDeriv*glm::length(diff);\n\n\t\tglm::vec3 gradient = pc.getEstGradients()[nearest[0].index];\n\t\tglm::vec4 newPoint = pc.getActualPoints()[nearest[0].index];\n\n\t\tfloat integrationSteps = 1.0f;\n\t\tglm::vec3 intDiff = diff/integrationSteps;\n\t\tPointCollection::ObjectiveFunction fun;\n\n\t\tfor (int f = 0; f < integrationSteps; f++) {\n\t\t\t//float hessCalc =  0.5*glm::dot(diff, pc.getEstHessians()[nearest[0].index]*diff)\n\t\t\tnewPoint += glm::vec4(intDiff, glm::dot(gradient, intDiff));\n\n\t\t\tgradient = pc.calculateGradient(5, newPoint, newPoint.w, false, &fun);\n\t\t}\n\n\t\t//return newPoint.w;\n\n\n\t\t//return pc.getActualPoints()[nearest[0].index].w;\n\n\t\treturn pc.getActualPoints()[nearest[0].index].w + glm::dot(pc.getEstGradients()[nearest[0].index],diff);\n\n\n\n\t\t//return f(x+dx) ~= f(x) + df(x)*dx + (1/2)*dx*H(x)*dx\n\t\treturn pc.getActualPoints()[nearest[0].index].w + glm::dot(pc.getEstGradients()[nearest[0].index],diff)\n\t\t + 0.5*glm::dot(diff, pc.getEstHessians()[nearest[0].index]*diff);\n\n\t\t// mean gradient\n\t\tfloat value = 0.0f;\n\t\tfor (int f = 0; f < nearest.size(); f++) {\n\t\t\tdiff = pos-glm::vec3(pc.getActualPoints()[nearest[f].index]);\n\t\t\tvalue += (pc.getActualPoints()[nearest[f].index].w + glm::dot(pc.getEstGradients()[nearest[f].index],diff));\n\t\t}\t\t\n\t\treturn value/nearest.size();\n\n\t\t// inverse weighted \n\t\tfloat totalWeight = 0.0f;\n\t\tfor (int f = 0; f < nearest.size(); f++) {\n\t\t\ttotalWeight += 1.0f/nearest[f].distance;\n\t\t}\n\n\t\t// inverse weighted gradient\n\t\tvalue = 0.0f;\n\t\tfor (int f = 0; f < nearest.size(); f++) {\n\t\t\tdiff = pos-glm::vec3(pc.getActualPoints()[nearest[f].index]);\n\t\t\tvalue += (pc.getActualPoints()[nearest[f].index].w + glm::dot(pc.getEstGradients()[nearest[f].index],diff)) * ((1.0f/nearest[f].distance)/totalWeight);\n\t\t}\t\t\n\t\treturn value;\n\n\t\t// inverse weighted distance\n\t\tvalue = 0.0f;\n\t\tfor (int f = 0; f < nearest.size(); f++) {\n\t\t\tvalue += pc.getActualPoints()[nearest[f].index].w * ((1.0f/nearest[f].distance)/totalWeight);\n\t\t}\t\t\n\t\treturn value;\n\t}\n\n\tglm::quat rotationBetweenVectors(glm::vec3 start, glm::vec3 dest){\n\t\tstart = normalize(start);\n\t\tdest = normalize(dest);\n\n\t\tfloat cosTheta = dot(start, dest);\n\t\tglm::vec3 rotationAxis;\n\n\t\tif (cosTheta < -1 + 0.001f){\n\t\t\t// special case when vectors in opposite directions:\n\t\t\t// there is no \"ideal\" rotation axis\n\t\t\t// So guess one; any will do as long as it's perpendicular to start\n\t\t\trotationAxis = glm::cross(glm::vec3(0.0f, 0.0f, 1.0f), start);\n\t\t\tif (glm::length(rotationAxis) < 0.01 ) // bad luck, they were parallel, try again!\n\t\t\t\trotationAxis = glm::cross(glm::vec3(1.0f, 0.0f, 0.0f), start);\n\n\t\t\trotationAxis = glm::normalize(rotationAxis);\n\t\t\treturn glm::angleAxis(glm::radians(180.0f), rotationAxis);\n\t\t}\n\n\t\trotationAxis = glm::cross(start, dest);\n\n\t\tfloat s = sqrt( (1+cosTheta)*2 );\n\t\tfloat invs = 1 / s;\n\n\t\treturn glm::quat(\n\t\t\ts * 0.5f, \n\t\t\trotationAxis.x * invs,\n\t\t\trotationAxis.y * invs,\n\t\t\trotationAxis.z * invs\n\t\t);\n\n\t}\n\n\t~TestApp() {\n\t}\n\n\n\tvoid drawContents() {\n\t\tscene.updateModel();\n\t\tscene.updateSharedContext(context);\n\t\tscene.updateContext(context);\n\t\tgraphicsNode->render(context);\n\t}\n\nprivate:\n\n\tclass ResizeCallback : public StateEventHandlerCallback<ResizeState, TestApp> {\n\t\tvoid onEvent(const ResizeState& state, TestApp* app) {\n\t\t\tstd::cout << state.width << \" \" << state.height << \" \" << app << std::endl;\n\t\t}\n\t};\n\n\tclass OpenGLCallback : public RenderCallback<TestApp> {\n\t\tvoid renderCallback(const SceneContext& sceneContext, TestApp* app) {\n\t\t\t//std::cout << \"Clear screen\" << std::endl;\n\t\t\tglClearColor(0.75,0.75,0.75,1);\n            //glClearDepth(1.0f);\n\t\t\tglPointSize(10);\n\t\t\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);\n\t\t\tglEnable(GL_DEPTH_TEST);\n            glDepthFunc(GL_LESS);\n            //glDepthFunc(GL_LEQUAL);\n            glPatchParameteri(GL_PATCH_VERTICES, 3);\n            glEnable(GL_CULL_FACE);\n            glDisable(GL_BLEND);\n            glCullFace(GL_BACK);\n            glDisable(GL_CULL_FACE);\n\t\t}\n\t};\n\n\tclass TestCallback : public RenderCallback<TestApp> {\n\tpublic:\n\t\tTestCallback(std::string name) : name(name) {}\n\t\tvoid renderCallback(const SceneContext& sceneContext, TestApp* app) {\n\t\t\tRenderState& renderState = RenderState::get(sceneContext);\n\t\t\tglm::mat4 model = renderState.getModelMatrix().get();\n\t\t\tglm::vec3 v(1.0);\n\t\t\t//glm::vec3 v(0.0f);\n\t\t\tv = model*glm::vec4(v, 1.0);\n\t\t\tstd::cout << name << \": \" << v.x << \" \" << v.y << \" \" << v.z << std::endl;\n\t\t}\n\t\tstd::string name;\n\t};\n\n\tSceneContext context;\n\tSceneNode scene;\n\tSceneNode* graphicsNode;\n};\n\nint main(int argc, char**argv) {\n\tnanogui::init();\n\n\tnanogui::Screen* screen = new TestApp();\n\n\tscreen->performLayout();\n\tscreen->drawAll();\n\tscreen->setVisible(true);\n\n\tnanogui::mainloop();\n\tnanogui::shutdown();\n\n\treturn 0;\n}\n\n\n", "meta": {"hexsha": "eec368f995ad29c30c1289c7b6ea76c7d7b0b793", "size": 26395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/FunctionView/src/main.cpp", "max_stars_repo_name": "OpenSpace-VisLink/sandbox", "max_stars_repo_head_hexsha": "cb8a42facc3afe73794e2e4405aab13531ccbcb2", "max_stars_repo_licenses": ["MIT"], "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/FunctionView/src/main.cpp", "max_issues_repo_name": "OpenSpace-VisLink/sandbox", "max_issues_repo_head_hexsha": "cb8a42facc3afe73794e2e4405aab13531ccbcb2", "max_issues_repo_licenses": ["MIT"], "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/FunctionView/src/main.cpp", "max_forks_repo_name": "OpenSpace-VisLink/sandbox", "max_forks_repo_head_hexsha": "cb8a42facc3afe73794e2e4405aab13531ccbcb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T18:17:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T18:17:58.000Z", "avg_line_length": 36.3067400275, "max_line_length": 259, "alphanum_fraction": 0.6455389278, "num_tokens": 8510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.534023203168675}}
{"text": "#include <iostream>\n#include <cassert>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.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 boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> GraphTraits;\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, GraphTraits::edge_descriptor>>>>\n    Graph;\ntypedef Graph::vertex_descriptor Vertex;\n\ntemplate <typename T>\nvoid print_vec(std::vector<T> &vec, std::ostream &stream)\n{\n  for (int i = 0; i < int(vec.size()); i++)\n  {\n    if (i > 0)\n    {\n      stream << \" \";\n    }\n    stream << vec.at(i);\n  }\n  stream << \"\\n\";\n}\n\nvoid testcase()\n{\n  int l, p;\n  std::cin >> l >> p;\n  assert(l >= 1 && l <= 500 && p >= 1 && p <= l * l);\n\n  std::vector<int> start_pops_by_town(l), end_pops_by_town(l);\n  int total_start_pops = 0, total_end_pops = 0;\n  for (int i = 0; i < l; i++)\n  {\n    int g, d;\n    std::cin >> g >> d;\n    assert(g >= 1 && g <= 1e6 && d >= 1 && d <= 1e6);\n    start_pops_by_town.at(i) = g;\n    total_start_pops += g;\n    end_pops_by_town.at(i) = d;\n    total_end_pops += d;\n  }\n  DEBUG(2, \"total_start_pops \" << total_start_pops << \" total_end_pops \" << total_end_pops);\n\n  std::vector<int> starts_by_path(p), ends_by_path(p), min_caps_by_path(p), max_caps_by_path(p);\n  for (int i = 0; i < p; i++)\n  {\n    int f, t, c, C;\n    std::cin >> f >> t >> c >> C;\n    assert(f >= 0 && f < l && t >= 0 && t < l);\n    assert(c >= 0 && c <= C && C <= 1e6);\n    starts_by_path.at(i) = f;\n    ends_by_path.at(i) = t;\n    min_caps_by_path.at(i) = c;\n    max_caps_by_path.at(i) = C;\n  }\n\n  if (total_end_pops > total_start_pops)\n  {\n    std::cout << \"no\\n\";\n    return;\n  }\n\n  int num_nodes = l + p + 2, next_free_node = 0;\n  Vertex source = next_free_node++;\n  Vertex sink = next_free_node++;\n  auto town_at = [l, next_free_node](int i) { assert(i >= 0 && i < l);  return next_free_node + i; };\n  next_free_node += l;\n  auto path_mid_node_at = [p, next_free_node](int i) { assert(i >= 0 && i < p);  return next_free_node + i; };\n  next_free_node += p;\n  assert(next_free_node == num_nodes);\n  Graph G(num_nodes);\n\n  auto add_edge = [&G](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;\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n  };\n\n  std::vector<int> demands_by_town(l);\n  for (int i = 0; i < l; i++)\n  {\n    demands_by_town.at(i) = end_pops_by_town.at(i) - start_pops_by_town.at(i);\n  }\n  if (debug_level >= 2)\n  {\n    std::cerr << \"demands_by_town before adjustment \";\n    print_vec(demands_by_town, std::cerr);\n  }\n\n  for (int i = 0; i < p; i++)\n  {\n    int s = starts_by_path.at(i), e = ends_by_path.at(i), mid = path_mid_node_at(i), min = min_caps_by_path.at(i), max = max_caps_by_path.at(i);\n    demands_by_town.at(s) += min;\n    demands_by_town.at(e) -= min;\n    add_edge(town_at(s), mid, max - min);\n    add_edge(mid, town_at(e), max - min);\n  }\n  if (debug_level >= 2)\n  {\n    std::cerr << \"demands_by_town after adjustment \";\n    print_vec(demands_by_town, std::cerr);\n  }\n\n  for (int i = 0; i < l; i++)\n  {\n    int d = demands_by_town.at(i);\n    if (d > 0)\n    {\n      add_edge(town_at(i), sink, d);\n    }\n    else if (d < 0)\n    {\n      add_edge(source, town_at(i), -d);\n    }\n  }\n\n  int target_flow = 0;\n  for (int d : demands_by_town)\n  {\n    if (d > 0)\n    {\n      target_flow += d;\n    }\n  }\n  DEBUG(2, \"target_flow \" << target_flow);\n\n  long flow = boost::push_relabel_max_flow(G, source, sink);\n  DEBUG(2, \"flow \" << flow);\n  assert(flow >= 0 && flow <= target_flow);\n  std::cout << (flow == target_flow ? \"yes\\n\" : \"no\\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": "365dfa1062c5bd7326b80beec2ba071d7a7b4ee7", "size": 4412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-06/kingdom-defence/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-06/kingdom-defence/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-06/kingdom-defence/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": 27.2345679012, "max_line_length": 144, "alphanum_fraction": 0.570942883, "num_tokens": 1408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.534023197289189}}
{"text": "\n/*\n * Copyright (c) 2015-2021 Agalmic Ventures LLC (www.agalmicventures.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\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Werk/Math/SimpleLinearRegression.hpp\"\n\nBOOST_AUTO_TEST_SUITE(SimpleLinearRegressionTest)\n\nBOOST_AUTO_TEST_CASE(TestEmpty)\n{\n\twerk::SimpleLinearRegression r;\n\tBOOST_REQUIRE_EQUAL(r.count(), 0);\n\tBOOST_REQUIRE(std::isnan(r.beta()));\n\tBOOST_REQUIRE(std::isnan(r.correlation()));\n\tBOOST_REQUIRE(std::isnan(r.predict(2.0)));\n}\n\nBOOST_AUTO_TEST_CASE(TestLinear)\n{\n\twerk::SimpleLinearRegression r;\n\n\tr.sample(1.0, 4.0);\n\tBOOST_REQUIRE_EQUAL(r.count(), 1);\n\tBOOST_REQUIRE(std::isnan(r.beta()));\n\tBOOST_REQUIRE(std::isnan(r.correlation()));\n\tBOOST_REQUIRE(std::isnan(r.predict(2.0)));\n\n\tr.sample(3.0, 8.0);\n\tBOOST_REQUIRE_EQUAL(r.count(), 2);\n\tBOOST_REQUIRE_EQUAL(r.beta(), 2.0);\n\tBOOST_REQUIRE_EQUAL(r.correlation(), 1.0);\n\tBOOST_REQUIRE_EQUAL(r.predict(2.0), 6.0);\n\n\tr.sample(5.0, 12.0);\n\tBOOST_REQUIRE_EQUAL(r.count(), 3);\n\tBOOST_REQUIRE_EQUAL(r.correlation(), 1.0);\n\tBOOST_REQUIRE_CLOSE(r.beta(), 2.0, 0.000000001);\n\tBOOST_REQUIRE_CLOSE(r.alpha(), 2.0, 0.000000001);\n\tBOOST_REQUIRE_CLOSE(r.predict(2.0), 6.0, 0.000000001);\n\n\tr.sample(6.0, 14.0);\n\tBOOST_REQUIRE_EQUAL(r.count(), 4);\n\tBOOST_REQUIRE_EQUAL(r.correlation(), 1.0);\n\tBOOST_REQUIRE_CLOSE(r.beta(), 2.0, 0.000000001);\n\tBOOST_REQUIRE_CLOSE(r.alpha(), 2.0, 0.000000001);\n\tBOOST_REQUIRE_CLOSE(r.predict(2.0), 6.0, 0.000000001);\n\n\tr.reset();\n\tBOOST_REQUIRE_EQUAL(r.count(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(TestZeroCorrelation)\n{\n\twerk::SimpleLinearRegression r;\n\n\tr.sample(-1.0, 3.0);\n\tr.sample(0.0, 0.0);\n\tr.sample(1.0, 3.0);\n\tBOOST_REQUIRE_EQUAL(r.count(), 3);\n\tBOOST_REQUIRE_EQUAL(r.correlation(), 0.0);\n\tBOOST_REQUIRE_EQUAL(r.beta(), 0.0);\n\tBOOST_REQUIRE_CLOSE(r.alpha(), 2.0, 0.000000001);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f4d8df5bb826acb757da78293cabeaa0617aabf1", "size": 2876, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/WerkTest/Math/SimpleLinearRegression.cpp", "max_stars_repo_name": "AgalmicVentures/Werk", "max_stars_repo_head_hexsha": "99afecb310aadb90d941a3a1031bc91b33edac59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-04-22T22:46:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:14:16.000Z", "max_issues_repo_path": "src/WerkTest/Math/SimpleLinearRegression.cpp", "max_issues_repo_name": "AgalmicVentures/Werk", "max_issues_repo_head_hexsha": "99afecb310aadb90d941a3a1031bc91b33edac59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/WerkTest/Math/SimpleLinearRegression.cpp", "max_forks_repo_name": "AgalmicVentures/Werk", "max_forks_repo_head_hexsha": "99afecb310aadb90d941a3a1031bc91b33edac59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2017-02-26T09:28:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T16:33:47.000Z", "avg_line_length": 33.0574712644, "max_line_length": 79, "alphanum_fraction": 0.7402642559, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5340231920615484}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \r\n// unit/quantity manipulation and conversion\r\n//\r\n// Copyright (C) 2003-2008 Matthias Christian Schabel\r\n// Copyright (C) 2008 Steven Watanabe\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/** \r\n\\file\r\n    \r\n\\brief radar_beam_height.cpp\r\n\r\n\\details\r\nDemonstrate library usage for user test cases suggested by Michael Fawcett.\r\n\r\nOutput:\r\n@verbatim\r\n\r\n//[radar_beam_height_output\r\nradar range        : 300 nmi\r\nearth radius       : 6.37101e+06 m\r\nbeam height 1      : 18169.7 m\r\nbeam height 2      : 9.81085 nmi\r\nbeam height 3      : 18169.7 m\r\nbeam height 4      : 9.81085 nmi\r\nbeam height approx : 59488.4 ft\r\nbeam height approx : 18132.1 m\r\n//]\r\n\r\n@endverbatim\r\n**/\r\n\r\n#include <iostream>\r\n\r\n#include <boost/units/conversion.hpp>\r\n#include <boost/units/io.hpp>\r\n#include <boost/units/pow.hpp>\r\n#include <boost/units/systems/si.hpp>\r\n#include <boost/units/systems/si/prefixes.hpp>\r\n\r\nusing boost::units::length_dimension;\r\nusing boost::units::pow;\r\nusing boost::units::root;\r\nusing boost::units::quantity;\r\nusing boost::units::unit;\r\n\r\n//[radar_beam_height_class_snippet_1\r\nnamespace nautical {\r\n\r\nstruct length_base_unit : \r\n    boost::units::base_unit<length_base_unit, length_dimension, 1>\r\n{\r\n    static std::string name()       { return \"nautical mile\"; }\r\n    static std::string symbol()     { return \"nmi\"; }\r\n};\r\n\r\ntypedef boost::units::make_system<length_base_unit>::type system;\r\n\r\n/// unit typedefs\r\ntypedef unit<length_dimension,system>    length;\r\n\r\nstatic const length mile,miles;\r\n\r\n} // namespace nautical\r\n\r\n// helper for conversions between nautical length and si length\r\nBOOST_UNITS_DEFINE_CONVERSION_FACTOR(nautical::length_base_unit,\r\n                                     boost::units::si::meter_base_unit,\r\n                                     double, 1.852e3);\r\n//]\r\n\r\n//[radar_beam_height_class_snippet_2\r\nnamespace imperial {\r\n\r\nstruct length_base_unit : \r\n    boost::units::base_unit<length_base_unit, length_dimension, 2>\r\n{\r\n    static std::string name()       { return \"foot\"; }\r\n    static std::string symbol()     { return \"ft\"; }\r\n};\r\n\r\ntypedef boost::units::make_system<length_base_unit>::type system;\r\n\r\n/// unit typedefs\r\ntypedef unit<length_dimension,system>    length;\r\n\r\nstatic const length foot,feet;\r\n\r\n} // imperial\r\n\r\n// helper for conversions between imperial length and si length\r\nBOOST_UNITS_DEFINE_CONVERSION_FACTOR(imperial::length_base_unit,\r\n                                     boost::units::si::meter_base_unit,\r\n                                     double, 1.0/3.28083989501312);\r\n//]\r\n\r\n// radar beam height functions\r\n//[radar_beam_height_function_snippet_1\r\ntemplate<class System,typename T>\r\nconstexpr\r\nquantity<unit<boost::units::length_dimension,System>,T>\r\nradar_beam_height(const quantity<unit<length_dimension,System>,T>& radar_range,\r\n                  const quantity<unit<length_dimension,System>,T>& earth_radius,\r\n                  T k = 4.0/3.0)\r\n{\r\n    return quantity<unit<length_dimension,System>,T>\r\n        (pow<2>(radar_range)/(2.0*k*earth_radius));\r\n}\r\n//]\r\n\r\n//[radar_beam_height_function_snippet_2\r\ntemplate<class return_type,class System1,class System2,typename T>\r\nconstexpr\r\nreturn_type\r\nradar_beam_height(const quantity<unit<length_dimension,System1>,T>& radar_range,\r\n                  const quantity<unit<length_dimension,System2>,T>& earth_radius,\r\n                  T k = 4.0/3.0)\r\n{\r\n    // need to decide which system to use for calculation\r\n    return pow<2>(static_cast<return_type>(radar_range))\r\n            / (2.0*k*static_cast<return_type>(earth_radius));\r\n}\r\n//]\r\n\r\n//[radar_beam_height_function_snippet_3\r\nconstexpr\r\nquantity<imperial::length>\r\nradar_beam_height(const quantity<nautical::length>& range)\r\n{\r\n    return quantity<imperial::length>\r\n        (pow<2>(range/(1.23*nautical::miles/root<2>(imperial::feet))));\r\n}\r\n//]\r\n\r\nint main(void)\r\n{\r\n    using namespace boost::units;\r\n    using namespace boost::units::si;\r\n    using namespace nautical;\r\n\r\n    //[radar_beam_height_snippet_1\r\n    const quantity<nautical::length> radar_range(300.0*miles);\r\n    const quantity<si::length>       earth_radius(6371.0087714*kilo*meters);\r\n    \r\n    const quantity<si::length>       beam_height_1(radar_beam_height(quantity<si::length>(radar_range),earth_radius));\r\n    const quantity<nautical::length> beam_height_2(radar_beam_height(radar_range,quantity<nautical::length>(earth_radius)));\r\n    const quantity<si::length>       beam_height_3(radar_beam_height< quantity<si::length> >(radar_range,earth_radius));\r\n    const quantity<nautical::length> beam_height_4(radar_beam_height< quantity<nautical::length> >(radar_range,earth_radius));\r\n    //]\r\n    \r\n    std::cout << \"radar range        : \" << radar_range << std::endl\r\n              << \"earth radius       : \" << earth_radius << std::endl\r\n              << \"beam height 1      : \" << beam_height_1 << std::endl\r\n              << \"beam height 2      : \" << beam_height_2 << std::endl\r\n              << \"beam height 3      : \" << beam_height_3 << std::endl\r\n              << \"beam height 4      : \" << beam_height_4 << std::endl\r\n              << \"beam height approx : \" << radar_beam_height(radar_range)\r\n              << std::endl\r\n              << \"beam height approx : \"\r\n              << quantity<si::length>(radar_beam_height(radar_range))\r\n              << std::endl << std::endl;\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "059587ee9f4791093338b698a2d68b16f8420c70", "size": 5549, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/units/example/radar_beam_height.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/units/example/radar_beam_height.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/units/example/radar_beam_height.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": 33.0297619048, "max_line_length": 127, "alphanum_fraction": 0.6545323482, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5340231809544215}}
{"text": "#pragma once\n\n#include <cslibs_indexed_storage/utility/index_sequence.hpp>\n#include <boost/integer.hpp>\n#include <array>\n#include <valarray>\n\nnamespace cslibs_indexed_storage\n{\nnamespace operations\n{\nnamespace clustering\n{\n\nnamespace detail\n{\n\ntemplate <typename Seq1, std::size_t Offset, typename Seq2> struct concat_seq;\n\ntemplate <std::size_t ... Is1, std::size_t Offset, std::size_t ... Is2>\nstruct concat_seq<utility::index_sequence<Is1...>, Offset, utility::index_sequence<Is2...>>\n{\n    using type = utility::index_sequence<Is1..., (Offset + Is2)...>;\n};\n\ntemplate<typename T>\nconstexpr T pow(T base, std::size_t exp)\n{\n    return exp == 0 ? T(1) : base * pow(base, exp - 1);\n}\n\ntemplate<typename T>\nconstexpr T get_bit(std::size_t base, std::size_t bit, std::size_t value)\n{\n    return bit == 0 ? T(value % base) : get_bit<T>(base, bit - 1, value / base);\n}\n\ntemplate<typename offset_t, std::size_t... breaks>\nconstexpr offset_t generate_offset(std::size_t base, std::size_t counter, utility::index_sequence<breaks...>)\n{\n    using value_type = typename offset_t::value_type;\n    return {value_type(get_bit<value_type>(base, breaks, counter) - base / 2)...};\n}\n\ntemplate<typename offset_t>\nconstexpr offset_t generate_offset(std::size_t base, std::size_t counter)\n{\n    return generate_offset<offset_t>(base, counter, utility::make_index_sequence<std::tuple_size<offset_t>::value>{});\n}\n\ntemplate<typename list_t, std::size_t... counter>\nconstexpr list_t generate_all(std::size_t base, utility::index_sequence<counter...>)\n{\n    return {generate_offset<typename list_t::value_type>(base, counter)...};\n}\n\ntemplate<typename list_t, std::size_t skip>\nconstexpr list_t generate(std::size_t base, bool skip_self)\n{\n    return skip_self ?\n           generate_all<list_t>(base,\n                                typename concat_seq<\n                                        typename utility::make_index_sequence<skip>::type,\n                                        skip + 1,\n                                        typename utility::make_index_sequence<std::tuple_size<list_t>::value - skip>::type\n                                >::type{}) :\n           generate_all<list_t>(base, utility::make_index_sequence<std::tuple_size<list_t>::value>{});\n}\n\n//! \\todo can be increased when unsing a log2 approach in make_index_sequence\nconstexpr std::size_t MAX_STATIC_SIZE = pow(9ul, 5);\n\n}\n\ntemplate<std::size_t dimensions_, std::size_t size_, bool skip_self_ = true>\nclass GridNeighborhoodStatic\n{\npublic:\n    static constexpr std::size_t dimensions = dimensions_;\n    static constexpr std::size_t size = size_;\n    static constexpr bool skip_self = skip_self_;\n\n    static_assert((size % 2) == 1, \"size must be odd\");\n\n    static constexpr std::size_t count = detail::pow(size, dimensions) - (skip_self ? 1 : 0);\n    static constexpr std::size_t skip_index = count / 2;\n    static constexpr std::size_t shift = size / 2;\n\n    static_assert(count <= detail::MAX_STATIC_SIZE, \"static mask size exceeded, use GridNeighborhoodDynamic instead\");\n\n    using offset_value_t = typename boost::int_max_value_t<size>::fast;\n    using offset_t = std::array<offset_value_t, dimensions>;\n    using offset_list_t = std::array<offset_t, count>;\n\n    template<typename visitor_t>\n    static inline void visit(const visitor_t& visitor)\n    {\n        static constexpr offset_list_t offsets = detail::generate<offset_list_t, skip_index>(size, skip_self);\n        for (const auto& offset : offsets)\n            visitor(offset);\n    }\n};\n\nclass GridNeighborhoodDynamic\n{\npublic:\n    using offset_value_t = int64_t;\n    using offset_t = std::valarray<offset_value_t>;\n\n    size_t get_dimensions() const\n    {\n        return dimensions_;\n    }\n\n    void set_dimensions(size_t dimensions)\n    {\n        dimensions_ = dimensions;\n    }\n\n    size_t get_size() const\n    {\n        return size_;\n    }\n\n    void set_size(size_t size)\n    {\n        size_ = size;\n    }\n\n    bool is_skip_self() const\n    {\n        return skip_self_;\n    }\n\n    void set_skip_self(bool skip_self)\n    {\n        skip_self_ = skip_self;\n    }\n\n    template<typename visitor_t>\n    inline void visit(const visitor_t& visitor)\n    {\n        const std::size_t count = std::pow<long double>(size_, dimensions_) - (skip_self_ ? 1 : 0);\n        const std::size_t skip_index = count / 2;\n        const std::size_t shift = size_ / 2;\n\n        for (std::size_t i = 0; i <= count; ++i)\n        {\n            if (skip_self_ && i == skip_index)\n                continue;\n\n            offset_t offset(dimensions_);\n            std::size_t value = i;\n            for (std::size_t dim = 0; dim < dimensions_; ++dim)\n            {\n                offset[dim] = offset_value_t(offset_value_t(value % size_) - shift);\n                value /= size_;\n            }\n\n            visitor(offset);\n        }\n    }\n\nprivate:\n    std::size_t dimensions_;\n    std::size_t size_;\n    bool skip_self_;\n};\n\n}\n}\n}\n", "meta": {"hexsha": "275074bd4e357019617bd62f5f53e4d6d5016d2c", "size": 4930, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cslibs_indexed_storage/operations/clustering/grid_neighborhood.hpp", "max_stars_repo_name": "doge-of-the-day/cslibs_indexed_storage", "max_stars_repo_head_hexsha": "044a5e60cc1a1c0ac41631b1e6c0a79db7aa4c84", "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/cslibs_indexed_storage/operations/clustering/grid_neighborhood.hpp", "max_issues_repo_name": "doge-of-the-day/cslibs_indexed_storage", "max_issues_repo_head_hexsha": "044a5e60cc1a1c0ac41631b1e6c0a79db7aa4c84", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/cslibs_indexed_storage/operations/clustering/grid_neighborhood.hpp", "max_forks_repo_name": "doge-of-the-day/cslibs_indexed_storage", "max_forks_repo_head_hexsha": "044a5e60cc1a1c0ac41631b1e6c0a79db7aa4c84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-05T07:13:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-22T16:39:11.000Z", "avg_line_length": 28.4971098266, "max_line_length": 122, "alphanum_fraction": 0.6448275862, "num_tokens": 1178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5339257729734481}}
{"text": "/* Boost example/rational.cpp\n * example program of how to use interval< rational<> >\n *\n * Copyright 2002-2003 Guillaume Melquiond, Sylvain Pion\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// it would have been enough to only include:\n//   <boost/numeric/interval.hpp>\n// but it's a bit overkill to include processor intrinsics\n// and transcendental functions, so we do it by ourselves\n\n#include <boost/numeric/interval/interval.hpp>      // base class\n#include <boost/numeric/interval/rounded_arith.hpp> // default arithmetic rounding policy\n#include <boost/numeric/interval/checking.hpp>      // default checking policy\n#include <boost/numeric/interval/arith.hpp>         // += *= -= etc\n#include <boost/numeric/interval/policies.hpp>      // default policy\n\n#include <boost/rational.hpp>\n#include <iostream>\n\ntypedef boost::rational<int> Rat;\ntypedef boost::numeric::interval<Rat> Interval;\n\nstd::ostream& operator<<(std::ostream& os, const Interval& r) {\n  os << \"[\" << r.lower() << \",\" << r.upper() << \"]\";\n  return os;\n}\n\nint main() {\n  Rat p(2, 3), q(3, 4);\n  Interval z(4, 5);\n  Interval a(p, q);\n  a += z;\n  z *= q;\n  a -= p;\n  a /= q;\n  std::cout << z << std::endl;\n  std::cout << a << std::endl;\n}\n", "meta": {"hexsha": "937171df9de6a85c385c7968f24b903f40152c18", "size": 1330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/numeric/interval/examples/rational.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/rational.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/rational.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": 30.2272727273, "max_line_length": 89, "alphanum_fraction": 0.6676691729, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5339257609584221}}
{"text": "#include <cmath>\n#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <sys/time.h>\n#include <chrono>\n#include <sys/resource.h>   // check the memory usage\n#include <stdio.h>\n#include <thread>\n#include <fstream>\n#include <sstream>\n\n#include <NTL/RR.h>\n#include <NTL/xdouble.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include <NTL/BasicThreadPool.h>\n\n\n#include \"../src/CZZ.h\"\n#include \"../src/Params.h\"\n#include \"../src/PubKey.h\"\n#include \"../src/Scheme.h\"\n#include \"../src/SchemeAlgo.h\"\n#include \"../src/SecKey.h\"\n#include \"../src/TestScheme.h\"\n#include \"../src/TimeUtils.h\"\n#include \"../src/Ring2Utils.h\"\n#include \"../src/StringUtils.h\"\n#include \"../src/EvaluatorUtils.h\"\n\n#include \"Database.h\"\n#include \"LRtest.h\"\n#include \"HELR.h\"\n\n\nusing namespace NTL;\nusing namespace std;\n\n\n\nint main(int Argc, char** Argv) {\n\n    \n    if(Argc != 2){\n        cout << \"-------------------------------------------------------------\" << endl;\n        cerr << \"Enter the File and degree of approximation \\t\"  << \"(e.g. $test edin.txt 3) \\n \";\n    }\n    \n    char* filename  =  Argv[1];\n    \n    \n    \n    dMat  zData;\n    dMat* zTest = new dMat[5];\n    dMat* zTrain = new dMat[5];\n    \n    \n    int nLine= readData(zData, filename);\n    \n    cout << \"Sample the learning and test data ...\" << endl;\n    cvRandomSamplingData(zTrain, zTest, zData, filename);\n\n    \n    //----------------------------------------------------------------\n    // Parameters for Logistic regression\n    //----------------------------------------------------------------\n\n    long logN= 11;\n    long logp= 28;\n    long logl= 10;\n    long logq, cBit1, cBit2;\n    int max_iter;\n    long dim ;\n\n    \n    dMat mtheta3_list;\n    dMat mtheta7_list;\n    dMat mtheta_sig_list;\n    \n    ofstream fout;\n    fout.open(\"beta.txt\");\n\n    \n    for(int k = 0; k < 5; ++k){\n        \n        \n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"HELR_3 \" << endl;\n        \n        int polydeg = 3;  // degree of approximation polynomial\n        \n        struct LRpar LRparams;\n        ReadLRparams(LRparams, max_iter, zTrain[0], polydeg, logp);\n        \n        dVec mtheta3(LRparams.dim1, 0.0);\n        for(int i= 0; i< LRparams.max_iter; i++){\n            LR_poly(mtheta3, zTrain[k], LRparams);\n        }\n        \n        for(int i= 0; i< LRparams.dim1; i++)\n            cout << \"[\" << mtheta3[i] << \"] \" ;\n        cout  << endl;\n        \n        getAUC(mtheta3, zTest[k]);\n        mtheta3_list.push_back(mtheta3);\n        \n        \n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"HELR_7 \" << endl;\n        \n        polydeg = 7;  // degree of approximation polynomial\n        \n        struct LRpar LRparams7;\n        ReadLRparams(LRparams7, max_iter, zTrain[0], polydeg, logp);\n        \n        dVec mtheta7(LRparams7.dim1, 0.0);\n        for(int i= 0; i< LRparams7.max_iter; i++){\n            LR_poly(mtheta7, zTrain[k], LRparams7);\n        }\n        \n        for(int i= 0; i< LRparams7.dim1; i++)\n            cout << \"[\" << mtheta7[i] << \"] \" ;\n        cout  << endl;\n        \n        getAUC(mtheta7, zTest[k]);\n        mtheta7_list.push_back(mtheta7);\n        \n        dim = LRparams7.dim1;\n        \n        \n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"sigmoid LR \" << endl;\n        dVec mtheta_sig(LRparams.dim1, 0.0);\n        \n        for(int i= 0; i< LRparams.max_iter; i++){\n            LR_sigmoid(mtheta_sig, zTrain[k], LRparams);\n        }\n        \n        for(int i= 0; i< LRparams.dim1; i++)\n            cout << \"[\" << mtheta_sig[i] << \"] \" ;\n        cout  << endl;\n        \n        getAUC(mtheta_sig, zTest[k]);\n        mtheta_sig_list.push_back(mtheta_sig);\n        \n        \n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"MSE (HELR/non-HELR): \" << getMSE(mtheta3, mtheta_sig) << endl;\n        cout << \"MSE (HELR/non-HELR): \" << getMSE(mtheta7, mtheta_sig) << endl;\n\n    }\n \n    \n    //! write the beta results in the text file\n    //fout << \"-------------------------------------------------------------\" << endl;\n    //fout << \"HELR_3\" << endl;\n    for(int i = 0; i < dim; ++i){\n        for(int k = 0; k < 4; ++k){\n            fout << mtheta3_list[k][i] << \",\" ;\n        }\n        fout << mtheta3_list[4][i] << \";\" << endl;\n    }\n    \n    \n    //fout << \"-------------------------------------------------------------\" << endl;\n    //fout << \"HELR_7\" << endl;\n    for(int i = 0; i < dim; ++i){\n        for(int k = 0; k < 4; ++k){\n            fout << mtheta7_list[k][i] << \",\" ;\n        }\n        fout << mtheta7_list[4][i] << \";\" << endl;\n    }\n    \n    \n    //fout << \"-------------------------------------------------------------\" << endl;\n    //fout << \"LR\" << endl;\n    for(int i = 0; i < dim; ++i){\n        for(int k = 0; k < 4; ++k){\n            fout << mtheta_sig_list[k][i] << \",\" ;\n        }\n        fout << mtheta_sig_list[4][i] << \";\" << endl;\n    }\n\n    fout.close();\n    \n \n    \n    delete[] zTest;\n    delete[] zTrain;\n\n    return 0;\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "1eec43a65573767465af0f1b99a74b1fd0c2c47f", "size": 5161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Test_LR.cpp", "max_stars_repo_name": "K-miran/HELR", "max_stars_repo_head_hexsha": "c94951f2691d55defc82f95d3144c831eb6c8796", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:56:15.000Z", "max_issues_repo_path": "Test_LR.cpp", "max_issues_repo_name": "yuejiayang/HELR", "max_issues_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-25T02:54:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-09T10:48:39.000Z", "max_forks_repo_path": "Test_LR.cpp", "max_forks_repo_name": "yuejiayang/HELR", "max_forks_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-01-20T13:31:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T02:20:39.000Z", "avg_line_length": 25.805, "max_line_length": 98, "alphanum_fraction": 0.4365433056, "num_tokens": 1370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.5339257398904904}}
{"text": "/*\n * StereoCalib.cpp\n *\n *  Created on: 3 Jan 2015\n *      Author: link\n */\n\n#include <iostream>\n#include <list>\n\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <StorageFunctions.hpp>\n#include <boost/program_options.hpp>\n\n#include \"ConvenienceFunctions.hpp\"\n\nconst int USER_TRIGGERED_EXIT = 0;\n\nvoid parseCommandline(const int& argc,\n                      char** argv,\n                      std::string& input,\n                      std::string& output)\n{\n\n  boost::program_options::options_description desc;\n\n  desc.add_options()(\"help,h\", \"this help message\")(\n    \"input,i\",\n    boost::program_options::value<std::string>(),\n    \"Input directory containing imageList.xml\")(\n    \"output,o\",\n    boost::program_options::value<std::string>(),\n    \"Output file with calibration values for cameras\")(\n    \"length,l\",\n    boost::program_options::value<double>(),\n    \"Legth of side of a single chessboard field in chosen units.\"\n    \"These units will be used later as measure unit for all calculations\");\n  boost::program_options::variables_map vm;\n  boost::program_options::store(\n    boost::program_options::parse_command_line(argc, argv, desc), vm);\n  boost::program_options::notify(vm);\n\n  if (vm.count(\"help\"))\n  {\n    std::cout << desc << std::endl;\n    throw USER_TRIGGERED_EXIT;\n  }\n\n  if (vm.count(\"output\"))\n  {\n    output = vm[\"output\"].as<std::string>();\n  }\n\n  if (vm.count(\"input\"))\n  {\n    input = vm[\"input\"].as<std::string>();\n  }\n}\n\nbool getCorners(const cv::Mat& image,\n                const cv::Size& chessboardSize,\n                std::vector<cv::Point2f>& corners)\n{\n\n  if (cv::findChessboardCorners(image, chessboardSize, corners, 0))\n  {\n    cv::cornerSubPix(\n      image,\n      corners,\n      cv::Size(11, 11),\n      cv::Size(-1, -1),\n      cv::TermCriteria(\n        cv::TermCriteria::EPS + cv::TermCriteria::COUNT, 30, 0.1));\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\nint main(int argc, char** argv)\n{\n  std::string input, output;\n  double sideLength;\n\n  parseCommandline(argc, argv, input, output);\n\n  cv::Size imageSize, chessboardSize;\n  std::list<std::pair<cv::Mat, cv::Mat>> imageList;\n\n  loadImageList(input, imageSize, chessboardSize, sideLength, imageList);\n\n  std::vector<std::vector<cv::Point3f>> modelPoints(1);\n\n  for (int i = 0; i < chessboardSize.height; ++i)\n  {\n    for (int j = 0; j < chessboardSize.width; ++j)\n    {\n      modelPoints[0].push_back(sideLength * cv::Point3f(j, i, 0));\n    }\n  }\n\n  std::vector<std::vector<cv::Point2f>> leftPoints, rightPoints;\n  {\n    int i = 0;\n    for (auto it = imageList.begin(); imageList.end() != it; ++it, ++i)\n    {\n      std::pair<cv::Mat, cv::Mat> pair = *it;\n      std::cerr << i << std::endl;\n      std::vector<cv::Point2f> lP, rP;\n      if (getCorners(pair.first, chessboardSize, lP) &&\n          getCorners(pair.second, chessboardSize, rP))\n      {\n        leftPoints.push_back(lP);\n        rightPoints.push_back(rP);\n      }\n      else\n      {\n        it = imageList.erase(it);\n        continue;\n      }\n    }\n  }\n\n  modelPoints.resize(leftPoints.size(), modelPoints[0]);\n\n  cv::Mat lCM, rCM, lDC, rDC, R, T, E, F;\n\n  std::vector<cv::Mat> rvecs, tvecs;\n\n  double leftReprojectionError = cv::calibrateCamera(\n    modelPoints, leftPoints, imageSize, lCM, lDC, rvecs, tvecs);\n  rvecs.clear();\n  tvecs.clear();\n  double rightReprojectionError = cv::calibrateCamera(\n    modelPoints, rightPoints, imageSize, rCM, rDC, rvecs, tvecs);\n\n  std::cerr << \"left rms\" << leftReprojectionError << std::endl;\n  std::cerr << \"right rms\" << rightReprojectionError << std::endl;\n\n  double reprojectionError = cv::stereoCalibrate(\n    modelPoints,\n    leftPoints,\n    rightPoints,\n    lCM,\n    lDC,\n    rCM,\n    rDC,\n    imageSize,\n    R,\n    T,\n    E,\n    F,\n    cv::CALIB_FIX_INTRINSIC,\n    cv::TermCriteria(\n      cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 50, 1e-6));\n  std::cerr << reprojectionError << std::endl;\n\n  saveCalibParameters(output,\n                      lCM,\n                      rCM,\n                      lDC,\n                      rDC,\n                      R,\n                      T,\n                      E,\n                      F,\n                      chessboardSize,\n                      imageSize,\n                      sideLength);\n}\n", "meta": {"hexsha": "5f02764a2bfad9a646f99827c041c680d7824a9c", "size": 4372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/StereoCalib.cpp", "max_stars_repo_name": "morynicz/ace-of-space", "max_stars_repo_head_hexsha": "cb1983e58b52d704854f79b230eeba8ac261d954", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/StereoCalib.cpp", "max_issues_repo_name": "morynicz/ace-of-space", "max_issues_repo_head_hexsha": "cb1983e58b52d704854f79b230eeba8ac261d954", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/StereoCalib.cpp", "max_forks_repo_name": "morynicz/ace-of-space", "max_forks_repo_head_hexsha": "cb1983e58b52d704854f79b230eeba8ac261d954", "max_forks_repo_licenses": ["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.7005649718, "max_line_length": 75, "alphanum_fraction": 0.590347667, "num_tokens": 1178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5339246894911367}}
{"text": "#pragma once\n\n#include <boost/assert.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n\nnamespace polar {\n\nnamespace detail {\n\ntemplate<class Matrix>\nbool invert(Matrix const& input, Matrix& inverse)\n{\n    using namespace boost::numeric::ublas;\n\n    typedef permutation_matrix<std::size_t> pmatrix;\n\n    BOOST_ASSERT(input.size1() == input.size2());\n\n    Matrix A(input);\n    pmatrix pm(A.size1());\n\n    if (lu_factorize(A, pm) != 0)\n        return false;\n\n    inverse.assign(identity_matrix<typename Matrix::value_type>(A.size1()));\n    lu_substitute(A, pm, inverse);\n\n    return true;\n}\n\n} // namespace detail\n\ntemplate<typename Matrix_in, typename Matrix_out>\nvoid polar_decomposition(Matrix_in const& A, Matrix_out& U, Matrix_out& H,\n        double rtol = 1.0e-8, std::size_t max_iter = 0)\n{\n    typedef typename Matrix_out::value_type value_type;\n\n    BOOST_ASSERT(A.size1() == A.size2());\n\n    U.resize(A.size1(), A.size2());\n    U.assign(A);\n    H.resize(A.size1(), A.size2());\n    Matrix_out X(A.size1(), A.size2());\n\n    std::size_t count = 0;\n    bool close_to_convergence = false;\n\n    while (true)\n    {\n        X.assign(U);\n        detail::invert(X, H);\n        value_type gamma = 1.0;\n\n        if (!close_to_convergence)\n        {\n            value_type alpha = std::sqrt(norm_1(X) * norm_inf(X));\n            value_type beta  = std::sqrt(norm_1(H) * norm_inf(H));\n            gamma = std::sqrt(beta / alpha);\n        }\n\n        U.assign(0.5 * (gamma * X + 1.0 / gamma * trans(H)));\n\n        if (norm_1(X - U) < rtol * norm_1(X))\n            break;\n\n        if (max_iter != 0 && ++count == max_iter)\n            break;\n\n        if (!close_to_convergence && norm_frobenius(X - U) < 1.0e-2)\n            close_to_convergence = true;\n    }\n\n    H.assign(0.5 * (prod(trans(U), A) + prod(trans(A), U)));\n}\n\n} // namespace polar\n", "meta": {"hexsha": "8a0049b5f8971fa6031a9c2d006f62b27d87e31a", "size": 1924, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "polar_decomposition.hpp", "max_stars_repo_name": "vladimir-ch/polar-decomposition", "max_stars_repo_head_hexsha": "cbcb8b13cb5b7676112db15935f3b95cd3f9bd85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-09-03T05:54:47.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-11T13:06:12.000Z", "max_issues_repo_path": "polar_decomposition.hpp", "max_issues_repo_name": "vladimir-ch/polar-decomposition", "max_issues_repo_head_hexsha": "cbcb8b13cb5b7676112db15935f3b95cd3f9bd85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "polar_decomposition.hpp", "max_forks_repo_name": "vladimir-ch/polar-decomposition", "max_forks_repo_head_hexsha": "cbcb8b13cb5b7676112db15935f3b95cd3f9bd85", "max_forks_repo_licenses": ["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.05, "max_line_length": 76, "alphanum_fraction": 0.6065488565, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5339246872612199}}
{"text": "/**\n * @file lbfgs_test.cpp\n *\n * Tests the L-BFGS optimizer on a couple test functions.\n *\n * @author Ryan Curtin (gth671b@mail.gatech.edu)\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/optimizers/lbfgs/lbfgs.hpp>\n\n#include <mlpack/core/optimizers/problems/rosenbrock_function.hpp>\n#include <mlpack/core/optimizers/problems/rosenbrock_wood_function.hpp>\n#include <mlpack/core/optimizers/problems/colville_function.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack::optimization;\nusing namespace mlpack::optimization::test;\n\nBOOST_AUTO_TEST_SUITE(LBFGSTest);\n\n/**\n * Tests the L-BFGS optimizer using the Rosenbrock Function.\n */\nBOOST_AUTO_TEST_CASE(RosenbrockFunctionTest)\n{\n  RosenbrockFunction f;\n  L_BFGS lbfgs;\n  lbfgs.MaxIterations() = 10000;\n\n  arma::vec coords = f.GetInitialPoint();\n  if (!lbfgs.Optimize(f, coords))\n    BOOST_FAIL(\"L-BFGS optimization reported failure.\");\n\n  double finalValue = f.Evaluate(coords);\n\n  BOOST_REQUIRE_SMALL(finalValue, 1e-5);\n  BOOST_REQUIRE_CLOSE(coords[0], 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(coords[1], 1.0, 1e-5);\n}\n\n/**\n * Tests the L-BFGS optimizer using the Colville Function.\n */\nBOOST_AUTO_TEST_CASE(ColvilleFunctionTest)\n{\n  ColvilleFunction f;\n  L_BFGS lbfgs;\n  lbfgs.MaxIterations() = 10000;\n\n  arma::vec coords = f.GetInitialPoint();\n  if (!lbfgs.Optimize(f, coords))\n    BOOST_FAIL(\"L-BFGS optimization reported failure.\");\n\n  BOOST_REQUIRE_CLOSE(coords[0], 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(coords[1], 1.0, 1e-5);\n}\n\n/**\n * Tests the L-BFGS optimizer using the Wood Function.\n */\nBOOST_AUTO_TEST_CASE(WoodFunctionTest)\n{\n  WoodFunction f;\n  L_BFGS lbfgs;\n  lbfgs.MaxIterations() = 10000;\n\n  arma::vec coords = f.GetInitialPoint();\n  if (!lbfgs.Optimize(f, coords))\n    BOOST_FAIL(\"L-BFGS optimization reported failure.\");\n\n  double finalValue = f.Evaluate(coords);\n\n  BOOST_REQUIRE_SMALL(finalValue, 1e-5);\n  BOOST_REQUIRE_CLOSE(coords[0], 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(coords[1], 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(coords[2], 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(coords[3], 1.0, 1e-5);\n}\n\n/**\n * Tests the L-BFGS optimizer using the generalized Rosenbrock function.  This\n * is actually multiple tests, increasing the dimension by powers of 2, from 4\n * dimensions to 1024 dimensions.\n */\nBOOST_AUTO_TEST_CASE(GeneralizedRosenbrockFunctionTest)\n{\n  for (int i = 2; i < 10; i++)\n  {\n    // Dimension: powers of 2\n    int dim = std::pow(2.0, i);\n\n    GeneralizedRosenbrockFunction f(dim);\n    L_BFGS lbfgs(20);\n    lbfgs.MaxIterations() = 10000;\n\n    arma::vec coords = f.GetInitialPoint();\n    if (!lbfgs.Optimize(f, coords))\n      BOOST_FAIL(\"L-BFGS optimization reported failure.\");\n\n    double finalValue = f.Evaluate(coords);\n\n    // Test the output to make sure it is correct.\n    BOOST_REQUIRE_SMALL(finalValue, 1e-5);\n    for (int j = 0; j < dim; j++)\n      BOOST_REQUIRE_CLOSE(coords[j], 1.0, 1e-5);\n  }\n}\n\n/**\n * Tests the L-BFGS optimizer using the Rosenbrock-Wood combined function.  This\n * is a test on optimizing a matrix of coordinates.\n */\nBOOST_AUTO_TEST_CASE(RosenbrockWoodFunctionTest)\n{\n  RosenbrockWoodFunction f;\n  L_BFGS lbfgs;\n  lbfgs.MaxIterations() = 10000;\n\n  arma::mat coords = f.GetInitialPoint();\n  if (!lbfgs.Optimize(f, coords))\n    BOOST_FAIL(\"L-BFGS optimization reported failure.\");\n\n  double finalValue = f.Evaluate(coords);\n\n  BOOST_REQUIRE_SMALL(finalValue, 1e-5);\n  for (int row = 0; row < 4; row++)\n  {\n    BOOST_REQUIRE_CLOSE((coords(row, 0)), 1.0, 1e-5);\n    BOOST_REQUIRE_CLOSE((coords(row, 1)), 1.0, 1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "dc95ae0f241bc2afe9a9bee279798b4cd265de7b", "size": 3880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/lbfgs_test.cpp", "max_stars_repo_name": "chigur/mlpack", "max_stars_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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-05-02T21:10:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T21:10:55.000Z", "max_issues_repo_path": "src/mlpack/tests/lbfgs_test.cpp", "max_issues_repo_name": "chigur/mlpack", "max_issues_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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/lbfgs_test.cpp", "max_forks_repo_name": "chigur/mlpack", "max_forks_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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": 27.5177304965, "max_line_length": 80, "alphanum_fraction": 0.7146907216, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5339246773735604}}
{"text": "#include <iostream>\r\n#include <fstream>\r\n\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <opencv2/imgproc/imgproc.hpp>\r\n\r\n#include <geometry/draw.hpp>\r\n#include <imgproc/gradient_adapter.hpp>\r\n#include <imgproc/derivative_gradient.hpp>\r\n#include <imgproc/susan.hpp>\r\n#include <imgproc/rcmg.hpp>\r\n#include <imgproc/quadratureG2.hpp>\r\n#include <imgproc/quadratureS.hpp>\r\n#include <imgproc/quadratureSF.hpp>\r\n#include <imgproc/quadratureLGF.hpp>\r\n#include <imgproc/pc_sqf.hpp>\r\n#include <imgproc/pc_lgf.hpp>\r\n#include <imgproc/pc_matlab.hpp>\r\n#include <imgproc/image_operator.hpp>\r\n#include <utility/matlab_helpers.hpp>\r\n\r\n#include <edge/nms.hpp>\r\n#include <edge/zc.hpp>\r\n#include <edge/spe.hpp>\r\n\r\n#include <boost/filesystem.hpp>\r\n#include <boost/algorithm/string.hpp>  \r\n#include <boost/format.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n\r\n\r\n#define WRITE_IMAGE_FILES\r\n//#define SHOW_IMAGES\r\n\r\nusing namespace lsfm;\r\nusing namespace std;\r\n\r\ntemplate<class FT, template<class> class PT = cv::Point_>\r\nstruct GroundTruth {\r\n    GroundTruth() {\r\n        cv::Mat tmp(32000, 32000, CV_8U);\r\n        tmp.setTo(0);\r\n\r\n        Polygon<FT, PT> poly;\r\n        poly.push_back(PT<FT>(5089, 2023));\r\n        poly.push_back(PT<FT>(29947, 2023));\r\n        poly.push_back(PT<FT>(20971, 16007));\r\n        poly.push_back(PT<FT>(29947, 29959));\r\n        poly.push_back(PT<FT>(5089, 29959));\r\n        poly.push_back(PT<FT>(2017, 16007));\r\n\r\n        double scale = 0.01;\r\n        poly.fill(tmp, 180);\r\n\r\n        //cv::resize(tmp, img, cv::Size(), scale, scale, cv::INTER_AREA); //-> large error, even with sub precision \r\n        //cv::GaussianBlur(tmp, tmp, cv::Size(101, 101),20); // long runtime\r\n        cv::blur(tmp, tmp, cv::Size(100, 100));\r\n        cv::resize(tmp, img, cv::Size(), scale, scale, cv::INTER_NEAREST);\r\n        poly.scale(scale);\r\n        segments = poly.edges();\r\n    }\r\n\r\n    LineSegment2Vector<FT,PT> segments;\r\n    cv::Mat img;\r\n\r\n    FT error(const PT<FT> &p) const {\r\n        FT e = std::numeric_limits<FT>::max();\r\n        for_each(segments.begin(), segments.end(), [&](const LineSegment2<FT, PT> &seg) {\r\n            if (!seg.inRangeTol(p, 1))\r\n                return;\r\n            e = std::min(e, std::abs(seg.distance(p)));\r\n        });\r\n        return e;\r\n    }\r\n\r\n    size_t line(const PT<FT> &p, FT &err = FT()) const {\r\n        size_t ret = 0;\r\n        err = std::numeric_limits<FT>::max();\r\n        for (size_t i = 0; i != segments.size(); ++i) {\r\n            if (!segments[i].inRangeTol(p, 1))\r\n                continue;\r\n            FT dist = std::abs(segments[i].distance(p));\r\n            if (dist < err) {\r\n                err = dist;\r\n                ret = i;\r\n            }\r\n        }\r\n        return ret;\r\n    }\r\n\r\n    void draw(cv::Mat &out, const PT<FT> &p, size_t l, FT err) const {\r\n        static cv::Vec3b color[] = { cv::Vec3b(255, 0, 0), cv::Vec3b(0, 255, 0), cv::Vec3b(255, 255, 0), cv::Vec3b(255, 0, 255), cv::Vec3b(0, 255, 255), cv::Vec3b(255, 255, 255), cv::Vec3b(0, 0, 255) };\r\n        if (err > 1 || l > 5)\r\n            lsfm::set(out, cv::Point(getX(p), getY(p)), color[6]);\r\n        else\r\n            lsfm::set(out, cv::Point(getX(p), getY(p)), color[l]);\r\n    }\r\n};\r\n\r\ntemplate<class FT, template<class> class PT>\r\nvoid outputSet(const std::string &name, const GroundTruth<FT, PT> &gt, const std::vector<PT<FT>> &points, bool show = true) {\r\n\r\n    cv::Mat out(gt.img.size(), CV_8UC3);\r\n    out.setTo(0);\r\n\r\n    int outlier = 0;\r\n    FT err = 0, errSqr = 0;\r\n    for_each(points.begin(), points.end(), [&](const PT<FT> &p) {\r\n        FT e;\r\n        size_t l = gt.line(p, e);\r\n        if (e > 1)\r\n            ++outlier;\r\n        else {\r\n            err += e;\r\n            errSqr += e*e;\r\n        }\r\n        if (getX(p) > -1 && getX(p) < gt.img.cols && getY(p) > -1 && getY(p) < gt.img.rows)\r\n            gt.draw(out, p, l, e);\r\n    });\r\n    err /= (points.size() - outlier);\r\n    errSqr /= (points.size() - outlier);\r\n    std::cout << name << \" - points: \" << points.size() << \", outlier: \" << outlier << \", mean error: \" << err << \", std deviation: \" << sqrt(errSqr - err*err) << std::endl;\r\n    if (show)\r\n        cv::imshow(name.c_str(), out);\r\n}\r\n\r\nint main(int argc, char** argv)\r\n{  \r\n    typedef double FT;\r\n    DerivativeGradient<uchar, FT, FT, FT, ScharrDerivative> grad(0,255);\r\n    LaplaceCV<uchar,FT> laplace(5,0,255);\r\n    //LoG<uchar, FT> laplace(5, 1,1,0, 255);\r\n    NonMaximaSuppression<FT, FT, FT, FastNMS8<FT, FT, FT>> nms;\r\n    NonMaximaSuppression<FT, FT, FT, PreciseNMS<FT, FT, false,FT,EMap8, CubicInterpolator,Polar>> pnms;\r\n    ZeroCrossing<FT, FT, FT, FastZC<FT, FT, FT>> zc;\r\n    ZeroCrossing<FT, FT, FT, PreciseZC<FT, FT, FT, NCC_BASIC, EZCMap8, CubicInterpolator, Polar>> pzc;\r\n    PixelEstimator<FT,cv::Point_<FT>> pe;\r\n    // CoGEstimate, LinearEstimate, QuadraticEstimate, SobelEstimate, LinearInterpolator, CubicInterpolator\r\n    PixelEstimator<FT, cv::Point_<FT>, SubPixelEstimator<FT,FT,cv::Point_, QuadraticEstimate, CubicInterpolator>> spe;\r\n    PixelEstimator<FT, cv::Point_<FT>, SubPixelEstimator<FT, FT, cv::Point_, SobelZCEstimate, CubicInterpolator>> spezc;\r\n    GroundTruth<FT, cv::Point_> gt;\r\n    \r\n    grad.process(gt.img);\r\n    nms.process(grad);\r\n    IndexVector idxs = nms.hysteresis_edgels();\r\n    std::vector<cv::Point_<FT>> points, pointsSp, pointsSpDir;\r\n    pe.convert(idxs, points, grad.magnitude(),nms.directionMap());\r\n    spe.convert(idxs, pointsSp, grad.magnitude(), nms.directionMap());\r\n    spe.convertDir(idxs, pointsSpDir, grad.magnitude(), grad.direction());\r\n\r\n    \r\n    outputSet(\"fnms_pe\", gt, points);\r\n    outputSet(\"fnms_spe\", gt, pointsSp);\r\n    outputSet(\"fnms_spe_dir\", gt, pointsSpDir);\r\n\r\n    cv::waitKey();\r\n\r\n    pnms.process(grad);\r\n    idxs = pnms.hysteresis_edgels();\r\n    pe.convert(idxs, points, grad.magnitude(), pnms.directionMap());\r\n    spe.convert(idxs, pointsSp, grad.magnitude(), pnms.directionMap());\r\n    spe.convertDir(idxs, pointsSpDir, grad.magnitude(), grad.direction());\r\n\r\n    outputSet(\"pnms_pe\", gt, points);\r\n    outputSet(\"pnms_spe\", gt, pointsSp);\r\n    outputSet(\"pnms_spe_dir\", gt, pointsSpDir);\r\n\r\n    cv::waitKey();\r\n\r\n    laplace.process(gt.img);\r\n    zc.process(laplace);\r\n    idxs = zc.hysteresis_edgels();\r\n    pe.convert(idxs, points, laplace.laplace(), zc.directionMap());\r\n    spezc.convert(idxs, pointsSp, laplace.laplace(), zc.directionMap());\r\n    spezc.convertDir(idxs, pointsSpDir, laplace.laplace(), grad.direction());\r\n\r\n    //cv::imshow(\"gt\", gt.img);\r\n    outputSet(\"fzc_pe\", gt, points);\r\n    outputSet(\"fzc_spe\", gt, pointsSp);\r\n    outputSet(\"fzc_spe_dir\", gt, pointsSpDir);\r\n\r\n    cv::waitKey();\r\n\r\n    zc.processG(laplace,grad);\r\n    idxs = zc.hysteresis_edgels();\r\n    pe.convert(idxs, points, laplace.laplace(), zc.directionMap());\r\n    spezc.convert(idxs, pointsSp, laplace.laplace(), zc.directionMap());\r\n    spezc.convertDir(idxs, pointsSpDir, laplace.laplace(), grad.direction());\r\n\r\n    //cv::imshow(\"gt\", gt.img);\r\n    outputSet(\"fzcg_pe\", gt, points);\r\n    outputSet(\"fzcg_spe\", gt, pointsSp);\r\n    outputSet(\"fzcg_spe_dir\", gt, pointsSpDir);\r\n    cv::waitKey();\r\n\r\n    pzc.process(laplace);\r\n    idxs = pzc.hysteresis_edgels();\r\n    pe.convert(idxs, points, laplace.laplace(), pzc.directionMap());\r\n    spezc.convert(idxs, pointsSp, laplace.laplace(), pzc.directionMap());\r\n    spezc.convertDir(idxs, pointsSpDir, laplace.laplace(), grad.direction());\r\n\r\n    //cv::imshow(\"gt\", gt.img);\r\n    outputSet(\"pzc_pe\", gt, points);\r\n    outputSet(\"pzc_spe\", gt, pointsSp);\r\n    outputSet(\"pzc_spe_dir\", gt, pointsSpDir);\r\n\r\n    cv::waitKey();\r\n\r\n    pzc.processG(laplace, grad);\r\n    idxs = pzc.hysteresis_edgels();\r\n    pe.convert(idxs, points, laplace.laplace(), pzc.directionMap());\r\n    spezc.convert(idxs, pointsSp, laplace.laplace(), pzc.directionMap());\r\n    spezc.convertDir(idxs, pointsSpDir, laplace.laplace(), grad.direction());\r\n\r\n    //cv::imshow(\"gt\", gt.img);\r\n    outputSet(\"pzcg_pe\", gt, points);\r\n    outputSet(\"pzcg_spe\", gt, pointsSp);\r\n    outputSet(\"pzcg_spe_dir\", gt, pointsSpDir);\r\n\r\n    cv::imshow(\"gt\", gt.img);\r\n    cv::waitKey();\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "61d933bdac2542147bb1ade7be782092cf69e753", "size": 8144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/edge/edge_precision.cpp", "max_stars_repo_name": "waterben/LineExtraction", "max_stars_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T13:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T13:30:56.000Z", "max_issues_repo_path": "examples/edge/edge_precision.cpp", "max_issues_repo_name": "waterben/LineExtraction", "max_issues_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_issues_repo_licenses": ["MIT"], "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/edge/edge_precision.cpp", "max_forks_repo_name": "waterben/LineExtraction", "max_forks_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_forks_repo_licenses": ["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.1955555556, "max_line_length": 203, "alphanum_fraction": 0.603388998, "num_tokens": 2430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5339246603121546}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <stan/math/prim/mat.hpp>\n#include <math/prim/mat/prob/vector_rng_test_helper.hpp>\n#include <math/prim/mat/prob/VectorIntRNGTestRig.hpp>\n#include <limits>\n#include <vector>\n\nclass BinomialTestRig : public VectorIntRNGTestRig {\n public:\n  BinomialTestRig()\n      : VectorIntRNGTestRig(10000, 10, {0, 1, 2, 3, 4, 5, 6}, {}, {0, 1, 3, 8},\n                            {}, {-1, -5, -7}, {0.0, 0.1, 0.7, 0.99}, {0},\n                            {-0.1, 1.2}, {-1, 2}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& N, const T2& theta, const T3&,\n                        T_rng& rng) const {\n    return stan::math::binomial_rng(N, theta, rng);\n  }\n\n  template <typename T1>\n  double pmf(int y, T1 N, double theta, double) const {\n    if (y <= N) {\n      return std::exp(stan::math::binomial_lpmf(y, N, theta));\n    } else {\n      return 0.0;\n    }\n  }\n};\n\nTEST(ProbDistributionsBinomial, errorCheck) {\n  check_dist_throws_int_first_argument(BinomialTestRig());\n}\n\nTEST(ProbDistributionsBinomial, distributionCheck) {\n  check_counts_int_real(BinomialTestRig());\n}\n", "meta": {"hexsha": "179df1820975a0d605ad42f4976ce158cf39ed1b", "size": 1229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/mat/prob/binomial_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/prim/mat/prob/binomial_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/prim/mat/prob/binomial_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": 30.725, "max_line_length": 79, "alphanum_fraction": 0.6354759967, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5338914829620939}}
{"text": "/**\n * @file eigenray_extra_test.cc\n *\n * Perform eigenrays tests that run too slow to be included\n * in the normal suite of regression tests.\n */\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <usml/waveq3d/waveq3d.h>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n\nBOOST_AUTO_TEST_SUITE(eigenray_extra_test)\n\nusing namespace boost::unit_test;\nusing namespace usml::waveq3d;\n\nstatic const double time_step = 0.100 ;\nstatic const double f0 = 2000 ;\nstatic const double src_lat = 45.0;        // location = mid-Atlantic\nstatic const double src_lng = -45.0;\nstatic const double c0 = 1500.0;           // constant sound speed\nstatic const double bot_depth = 1e5 ;\n\n/**\n * Tests the model's ability to accurately estimate geometric terms for\n * Lloyd's Mirror eigenrays on a spherical earth.  Performing this test in\n * spherical coordinates eliminates potential sources of error for the\n * proploss_test.cc suite, which compares its results to Cartesian test cases.\n *\n * - Scenario parameters\n *   - Profile: constant 1500 m/s sound speed, no absorption\n *   - Bottom: \"infinitely\" deep\n *   - Source: 200 meters deep, 2000 Hz\n *   - Target: WOA5 depths from 1-500 meters, range is 5-45 nmi\n *   - Time Step: 100 msec\n *   - Launch D/E: 181 tangent spaced rays from -90 to 90 degrees\n *\n * This test computes travel times and eigenray angles for a combination\n * of direct and surface-reflected paths in an isovelocity ocean on a\n * round earth. It searches for zones of inaccuracies in the the wavefront\n * model by comparing the modeled results to analytic solutions at a\n * variety of depths and ranges.\n *\n * To compute the analytic solution we start with:\n *\n *  - R = earth's radius\n *  - \\f$ c_0 \\f$ = speed of sound in the ocean\n *  - \\f$ d_1 \\f$ = source depth\n *  - \\f$ d_2 \\f$ = target depth\n *  - \\f$ \\xi \\f$ = latitude change from source to receiver\n *\n * The laws of sines and cosines are then used to compute an analytic\n * solution for all direct-path eigenray terms:\n * \\f[\n *      L^2 = D_1^2 + D_2^2 - 2 D_1 D_2 cos( \\xi )\n * \\f]\\f[\n *      \\mu_{source} = arccos \\left( \\frac{L^2+D_1^2+D_2^2}{2 L D_1} \\right) - 90\n * \\f]\\f[\n *      \\mu_{target} = arccos \\left( \\frac{L^2+D_2^2+D_1^2}{2 L D_2} \\right) - 90\n * \\f]\\f[\n *      \\tau_{direct} = L / c_0\n * \\f]\n * where:\n *  - \\f$ L \\f$ = length of direct-path (meters)\n *  - \\f$ D_1 = R - d_1 \\f$ = distance from earth center to source (meters)\n *  - \\f$ D_2 = R - d_2 \\f$ = distance from earth center to target (meters)\n *  - \\f$ \\mu_{source} \\f$ = direct-path D/E angle at source (degrees)\n *  - \\f$ \\mu_{target} \\f$ = direct-path D/E angle at target (degrees)\n *  - \\f$ \\tau_{direct} \\f$ = direct-path travel time from source to target (sec)\n *\n * The surface-reflected path is very complicated in spherical coordinates.\n * One way to find it is to search for the roots to the transcendental equation:\n * \\f[\n *      f( \\xi_1 ) = D_1 sin( \\xi_1 ) - D_2 sin( \\xi - \\xi_1 ) + \\frac{D_1 D_2}{R} sin( \\xi - 2 \\xi_1 ) = 0\n * \\f]\n * where\n *  - \\f$ \\xi_1 \\f$ = latitude change from source to point of reflection\n *  - \\f$ \\xi_2 = \\xi -\\xi_1 \\f$ = latitude change from reflection point to target\n *\n * This test uses the Newton-Raphson method to iterate over successive values of\n * \\f$ \\xi_1 \\f$ until a solution \\f$ f( \\xi_1 ) \\approx 0 \\f$ is found.\n * \\f[\n *      f'( \\xi_1 ) = D_1 cos( \\xi_1 ) + D_2 cos( \\xi - \\xi_1 ) - 2 \\frac{D_1 D_2}{R} cos( \\xi - 2 \\xi_1 )\n * \\f]\\f[\n *      \\xi_{1 new} = \\xi_1 - \\frac{ f( \\xi_1 ) }{ f'( \\xi_1 ) }\n * \\f]\n *\n * Plots of the transcendental equation indicate that the solution for\n * \\f$ \\xi_1 \\f$ can have up to three roots, at long ranges, for depths near\n * that of the source.  For the purposes of analytic solution computation,\n * we will limit the range to an area where only one root is supported.\n * For a source at 200 meters, that corresponds to ranges below\n * approximately 0.8 degrees.\n *\n * Once \\f$ \\xi_1 \\f$ and \\f$ \\xi_2 \\f$ are known, the laws of sines and\n * cosines are used to compute an analytic solution for all surface\n * reflected eigenray terms:\n * \\f[\n *      a_1^2 = R^2 + D_1^2 - 2 R D_1 cos( \\xi_1 )\n * \\f]\\f[\n *      a_2^2 = R^2 + D_2^2 - 2 R D_2 cos( \\xi_2 )\n * \\f]\\f[\n *      \\eta_{source} = arccos \\left( \\frac{a_1^2+D_1^2-R^2}{2 a_1 D_1} \\right) - 90\n * \\f]\\f[\n *      \\eta_{target} = arccos \\left( \\frac{a_2^2+D_2^2-R^2}{2 a_2 D_2} \\right) - 90\n * \\f]\\f[\n *      \\tau_{surface} = ( a_1 + a_2 ) / c_0\n * \\f]\n * where:\n *  - \\f$ a_1 \\f$ = distance from source to point of reflection (meters)\n *  - \\f$ a_2 \\f$ = distance from point of reflection to target  (meters)\n *  - \\f$ \\eta_{source} \\f$ = surface-reflected D/E angle at source (degrees)\n *  - \\f$ \\eta_{target} \\f$ = surface-reflected D/E angle at target (degrees)\n *  - \\f$ \\tau_{surface} \\f$ = surface-reflected travel time from source to target (sec)\n *\n * Errors are automatically generated if the modeled eigenrays\n * deviate from the analytic results by more than 0.5 millisecs in time or\n * 0.2 degrees in angle.\n *\n * When the wave_queue::compute_offsets() fallback calculation of\n * offset(n) = -gradient(n) / hessian(n,n) is not limited to 1/2 of the\n * beamwidth.  This test has large erorrs in D/E angle.  This illustrates\n * the importance of this limitation.\n *\n * @xref Weisstein, Eric W. \"Newton's Method.\" From MathWorld--A Wolfram\n *       Web Resource. http://mathworld.wolfram.com/NewtonsMethod.html\n */\nBOOST_AUTO_TEST_CASE( eigenray_lloyds ) {\n    cout << \"=== eigenray_test: eigenray_lloyds ===\" << endl;\n    const char* ncname_wave = USML_STUDIES_DIR \"/eigenray_extra/eigenray_lloyds_wave.nc\";\n    const char* ncname1 = USML_STUDIES_DIR \"/eigenray_extra/eigenray_lloyds1.nc\";\n    const char* ncname2 = USML_STUDIES_DIR \"/eigenray_extra/eigenray_lloyds2.nc\";\n    const char* analytic_name = USML_STUDIES_DIR \"/eigenray_extra/eigenray_lloyds_analytic.nc\";\n\n    const double src_alt = -200.0;      // source depth = 200 meters\n    const double time_max = 120.0 ;     // let rays plots go into region w/ 2 roots\n\n    const double rmax = 45.0/60.0 ;     // limit targets to area where N/R converges\n    const double rmin = 1.0/60.0 ;      // 1 nmi min range\n    const double rinc = 1.0/60.0 ;      // 1 nmi range inc\n    const seq_linear range( rmin, rinc, rmax );   // range in latitude\n\n    static double depth[] = { 0, 10, 100, 1000 } ;\n    size_t num_depths = sizeof(depth) / sizeof(double) ;\n\n    //*********************************************************************\n    // compute eigenrays for this ocean\n\n    wposition::compute_earth_radius( src_lat );\t\t\t// init area of ops\n    attenuation_model* attn = new attenuation_constant(0.0);    // no absorption\n    profile_model* profile = new profile_linear(c0,attn);\t// iso-velocity\n    boundary_model* surface = new boundary_flat();\t\t// default surface\n    boundary_model* bottom = new boundary_flat(bot_depth);\t// flat bottom\n    ocean_model ocean( surface, bottom, profile );\n\n    seq_log freq( f0, 1.0, 1 );\n    wposition1 pos( src_lat, src_lng, src_alt );\t\t// build ray source\n    seq_rayfan de ;\n//    seq_linear de(0.0, 1.0, 50.0) ;\n    seq_linear az( -4.0, 1.0, 4.0 );\n\n    // build a grid of targets at different ranges and depths\n\n    wposition target( range.size(), num_depths, src_lat, src_lng, src_alt );\n    for ( size_t t1=0; t1 < range.size(); ++t1 ) {\n        for ( size_t t2=0; t2 < num_depths; ++t2 ) {\n            target.latitude( t1, t2, src_lat + range(t1) );\n            target.altitude( t1, t2, -depth[t2] );\n        }\n    }\n\n    eigenray_collection loss1(freq, pos, de, az, time_step, &target);\n\n    eigenray_collection loss2(freq, pos, de, az, time_step, &target);\n\n\twave_queue wave( ocean, freq, pos, de, az, time_step, &target ) ;\n\n\t// adding eigenray_collection listener 1\n\twave.add_eigenray_listener(&loss1);\n\n    //adding eigenray_collection listener 2\n\twave.add_eigenray_listener(&loss2);\n\n    // propagate rays & record to log files\n\n    cout << \"propagate wavefronts\" << endl;\n    cout << \"writing wavefronts to \" << ncname_wave << endl;\n    wave.init_netcdf(ncname_wave);  // open a log file for wavefront data\n    wave.save_netcdf();             // write ray data to log file\n    while (wave.time() < time_max) {\n        wave.step();\n        wave.save_netcdf();         // write ray data to log file\n    }\n    wave.close_netcdf();            // close log file for wavefront data\n\n    loss1.sum_eigenrays();\n    loss2.sum_eigenrays();\n\n    cout << \"writing eigenrays to \" << ncname1 << endl;\n    loss1.write_netcdf(ncname1);\n    cout << \"writing eigenrays to \" << ncname2 << endl;\n    loss2.write_netcdf(ncname2);\n\n    //*********************************************************************\n    // compare each target location to analytic results\n\n    cout << \"testing eigenrays\" << endl;\n    for ( size_t t1=0; t1 < range.size(); ++t1 ) {\n        for ( size_t t2=0; t2 < num_depths; ++t2 ) {\n            double time, sde, tde, phase ;\n\n            // setup analytic equations for this target\n\n            const double R = wposition::earth_radius;\n            const double xi = to_radians( target.latitude(t1,t2) - src_lat ) ;\n            const double d1 = - src_alt;\n            const double d2 = - target.altitude(t1,t2) ;\n            const double D1 = R - d1 ;\n            const double D2 = R - d2 ;\n\n            eigenray_list *raylist = loss1.eigenrays(t1,t2);\n            for ( eigenray_list::iterator iter=raylist->begin();\n                  iter != raylist->end(); ++iter )\n            {\n                eigenray ray = *iter ;\n\n                //*************************************************************\n                // compare direct-path model to analytic results\n\n                if ( ray.surface == 0 || depth[t2] < 1e-3 ) {\n\n                    // compute analytic results\n\n                    const double L = sqrt( D1*D1 + D2*D2 - 2.0*D1*D2*cos(xi) );\n                    time = L/c0 ;\n                    sde = to_degrees( -asin( (L*L+D1*D1-D2*D2) / (2.0*L*D1) ) ) ;\n                    tde = to_degrees( asin( (L*L+D2*D2-D1*D1) / (2.0*L*D2) ) ) ;\n                    phase = 0.0 ;\n                    if ( ray.surface == 1 ) {\n                        tde *= -1.0 ;\n                        phase = -M_PI ;\n                    }\n\n                //*************************************************************\n                // compare surface-reflected model to analytic results\n\n                } else {\n\n                    // find reflection point using root of transindental equation\n                    // warning: xi2 = 0 for depths < 1e-3, and this makes solution unstable\n\n                    double xi1 = xi ;\n                    double xi2 = xi - xi1 ;\n                    if ( abs(d2) > 0.5 ) {\n                        xi1 = xi / 2.0 ;\n                        xi2 = xi - xi1 ;\n                        double f,g,delta ;\n                        do {\n                            f = D1*sin(xi1) - D2*sin(xi2) + D1*D2/R*sin(xi2-xi1) ;\n                            g = D1*cos(xi1) + D2*cos(xi2) - 2.0*D1*D2/R*cos(xi2-xi1) ;\n                            delta = - f / g ;\n                            xi1 += delta ;\n                            xi2 = xi - xi1 ;\n                        } while ( abs(delta) > 1e-6 ) ;\n                    }\n\n                    // compute analytic results\n\n                    const double a1 = sqrt( R*R + D1*D1 - 2.0*R*D1*cos(xi1) );\n                    const double a2 = sqrt( R*R + D2*D2 - 2.0*R*D2*cos(xi2) );\n                    time = (a1+a2)/c0 ;\n                    sde = to_degrees( -asin( (a1*a1+D1*D1-R*R) / (2.0*a1*D1) ) ) ;\n                    tde = to_degrees( asin( (a2*a2+D2*D2-R*R) / (2.0*a2*D2) ) ) ;\n                    phase = -M_PI ;\n                }\n\n                //*************************************************************\n                // test the accuracy of the model\n                // acknowledge that there will be bigger errors at short range\n\n                if ( range(t1) >= 0.1 ) {\n                    BOOST_CHECK_SMALL( ray.time - time, 0.0005 );\n                    BOOST_CHECK_SMALL( ray.phase(0)-phase, 1e-6 );\n                    BOOST_CHECK_SMALL( ray.source_de - sde, 0.3 );\n                    BOOST_CHECK_SMALL( ray.source_az, 1e-6 );\n                    BOOST_CHECK_SMALL( ray.target_de - tde, 0.3 );\n                    BOOST_CHECK_SMALL( ray.target_az, 1e-6 );\n                }\n\n                //*************************************************************\n                // replace modeled values with analytic results\n\n                (*iter).time = time ;\n                (*iter).source_de = sde ;\n                (*iter).source_az = 0.0 ;\n                (*iter).target_de = tde ;\n                (*iter).target_az = 0.0 ;\n\n//                cout << \"lat=\" << range[t1] << \" depth=\" << depth[t2] << \" path=\" << ray.surface ;\n//                cout << \" time=\" << time << \" sd=\" << sde << \" tde=\" << tde << endl ;\n            }   // loop through eigenrays for each target\n        }   // loop through target depths\n    }   // loop through target ranges\n\n    loss1.write_netcdf(analytic_name);\n\n}\n\n/// @}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3ae4171f63fe746020dd457b607e68ac0c795fe6", "size": 13190, "ext": "cc", "lang": "C++", "max_stars_repo_path": "studies/eigenray_extra/eigenray_extra_test.cc", "max_stars_repo_name": "fraclipe/UnderSeaModelingLibrary", "max_stars_repo_head_hexsha": "52ef9dd03c7cbe548749e4527190afe7668ff4e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-07T14:48:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T14:48:22.000Z", "max_issues_repo_path": "studies/eigenray_extra/eigenray_extra_test.cc", "max_issues_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_issues_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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": "studies/eigenray_extra/eigenray_extra_test.cc", "max_forks_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_forks_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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": 42.0063694268, "max_line_length": 107, "alphanum_fraction": 0.5595147839, "num_tokens": 3858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410784, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5338914686514318}}
{"text": "//Author: Dr. Shantanu Shahane\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <float.h>\n#include <string.h>\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/SparseExtra>\n#include <Eigen/SparseLU>\n#include <Eigen/OrderingMethods>\n#include <Eigen/Core>\n#include \"_hypre_utilities.h\"\n#include \"HYPRE_krylov.h\"\n#include \"HYPRE.h\"\n#include \"HYPRE_parcsr_ls.h\"\n#include \"general_functions.hpp\"\n#include \"class.hpp\"\n\nFRACTIONAL_STEP_1::FRACTIONAL_STEP_1(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, vector<bool> &u_dirichlet_flag1, vector<bool> &v_dirichlet_flag1, vector<bool> &p_dirichlet_flag1, int temporal_order1)\n{\n    temporal_order = temporal_order1;\n    u_dirichlet_flag = u_dirichlet_flag1, v_dirichlet_flag = v_dirichlet_flag1, p_dirichlet_flag = p_dirichlet_flag1;\n    check_bc(points, parameters);\n    clock_t clock_t1 = clock(), clock_t2 = clock();\n    solver_p.init(points, cloud, parameters, p_dirichlet_flag, 0.0, 0.0, 1.0, true);\n    parameters.factoring_timer = ((double)(clock() - clock_t1)) / CLOCKS_PER_SEC;\n\n    zero_vector = Eigen::VectorXd::Zero(points.nv);\n    zero_vector_1 = Eigen::VectorXd::Zero(points.nv + 1);\n    uh = zero_vector, vh = zero_vector;\n\n    p_bc_full_neumann = true;\n    for (int iv = 0; iv < points.nv; iv++)\n        if (points.boundary_flag[iv] && p_dirichlet_flag[iv])\n        { //boundary point found with dirichlet BC\n            p_bc_full_neumann = false;\n            break;\n        }\n\n    if (p_bc_full_neumann)\n        p_source = zero_vector_1; //this is full Neumann for pressure\n    else\n        p_source = zero_vector;\n    u_source_old = zero_vector, v_source_old = zero_vector;\n    if (temporal_order == 2)\n        u_source_old_old = zero_vector, v_source_old_old = zero_vector;\n}\n\nvoid FRACTIONAL_STEP_1::single_timestep_2d(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old, int it1)\n{\n    it = it1;\n    if (p_source.size() != p_new.size())\n        p_new = Eigen::VectorXd::Zero(p_source.size());\n    if (p_source.size() != p_old.size())\n        p_old = Eigen::VectorXd::Zero(p_source.size());\n    calc_vel_hat(points, parameters, u_old, v_old, p_old);\n    calc_pressure(points, parameters, u_new, v_new, p_new, u_old, v_old, p_old);\n    calc_vel_corr(points, cloud, parameters, u_new, v_new, p_new, u_old, v_old);\n    extras(points, parameters, u_new, v_new, p_new, u_old, v_old, p_old);\n}\n\nvoid FRACTIONAL_STEP_1::single_timestep_2d(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old, Eigen::VectorXd &body_force_x, Eigen::VectorXd &body_force_y, int it1)\n{\n    it = it1;\n    if (p_source.size() != p_new.size())\n        p_new = Eigen::VectorXd::Zero(p_source.size());\n    if (p_source.size() != p_old.size())\n        p_old = Eigen::VectorXd::Zero(p_source.size());\n    calc_vel_hat(points, parameters, u_old, v_old, p_old, body_force_x, body_force_y);\n    calc_pressure(points, parameters, u_new, v_new, p_new, u_old, v_old, p_old);\n    calc_vel_corr(points, cloud, parameters, u_new, v_new, p_new, u_old, v_old);\n    extras(points, parameters, u_new, v_new, p_new, u_old, v_old, p_old);\n}\n\nvoid FRACTIONAL_STEP_1::check_bc(POINTS &points, PARAMETERS &parameters)\n{\n    int u_dirichlet_flag_sum = accumulate(u_dirichlet_flag.begin(), u_dirichlet_flag.end(), 0);\n    if (u_dirichlet_flag_sum == 0)\n    {\n        printf(\"\\n\\nERROR from FRACTIONAL_STEP_1::check_bc Setting u_dirichlet_flag to full Neumann BC is not permitted; sum of u_dirichlet_flag: %i\\n\\n\", u_dirichlet_flag_sum);\n        throw bad_exception();\n    }\n    int v_dirichlet_flag_sum = accumulate(v_dirichlet_flag.begin(), v_dirichlet_flag.end(), 0);\n    if (v_dirichlet_flag_sum == 0)\n    {\n        printf(\"\\n\\nERROR from FRACTIONAL_STEP_1::check_bc Setting v_dirichlet_flag to full Neumann BC is not permitted; sum of v_dirichlet_flag: %i\\n\\n\", v_dirichlet_flag_sum);\n        throw bad_exception();\n    }\n    if (parameters.rho < 0 || parameters.mu < 0)\n    {\n        printf(\"\\n\\nERROR from FRACTIONAL_STEP_1::check_bc Some parameters are not set; parameters.rho: %g, parameters.mu: %g\\n\\n\", parameters.rho, parameters.mu);\n        throw bad_exception();\n    }\n    if (temporal_order != 1 && temporal_order != 2)\n    {\n        printf(\"\\n\\nERROR from FRACTIONAL_STEP_1::check_bc temporal_order should be either '1' or '2'; current value: %i\\n\\n\", temporal_order);\n        throw bad_exception();\n    }\n}\n\nvoid FRACTIONAL_STEP_1::calc_vel_hat(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old, Eigen::VectorXd &body_force_x, Eigen::VectorXd &body_force_y)\n{\n    u_source_old = (parameters.rho * (-u_old.cwiseProduct(points.grad_x_matrix_EIGEN * u_old) - v_old.cwiseProduct(points.grad_y_matrix_EIGEN * u_old))) + (parameters.mu * points.laplacian_matrix_EIGEN * u_old) + body_force_x;\n    v_source_old = (parameters.rho * (-u_old.cwiseProduct(points.grad_x_matrix_EIGEN * v_old) - v_old.cwiseProduct(points.grad_y_matrix_EIGEN * v_old))) + (parameters.mu * points.laplacian_matrix_EIGEN * v_old) + body_force_y;\n    if (temporal_order == 1 || it == 0)\n    { //Euler method for first timestep of multistep method\n        uh = u_old + ((parameters.dt / parameters.rho) * u_source_old);\n        vh = v_old + ((parameters.dt / parameters.rho) * v_source_old);\n    }\n    else\n    { //Second order Adam-Bashforth for subsequent timesteps\n        uh = u_old + ((parameters.dt / parameters.rho) * (1.5 * u_source_old - 0.5 * u_source_old_old));\n        vh = v_old + ((parameters.dt / parameters.rho) * (1.5 * v_source_old - 0.5 * v_source_old_old));\n    }\n}\n\nvoid FRACTIONAL_STEP_1::calc_vel_hat(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old)\n{\n    u_source_old = (parameters.rho * (-u_old.cwiseProduct(points.grad_x_matrix_EIGEN * u_old) - v_old.cwiseProduct(points.grad_y_matrix_EIGEN * u_old))) + (parameters.mu * points.laplacian_matrix_EIGEN * u_old);\n    v_source_old = (parameters.rho * (-u_old.cwiseProduct(points.grad_x_matrix_EIGEN * v_old) - v_old.cwiseProduct(points.grad_y_matrix_EIGEN * v_old))) + (parameters.mu * points.laplacian_matrix_EIGEN * v_old);\n    if (temporal_order == 1 || it == 0)\n    { //Euler method for first timestep of multistep method\n        uh = u_old + ((parameters.dt / parameters.rho) * u_source_old);\n        vh = v_old + ((parameters.dt / parameters.rho) * v_source_old);\n    }\n    else\n    { //Second order Adam-Bashforth\n        uh = u_old + ((parameters.dt / parameters.rho) * (1.5 * u_source_old - 0.5 * u_source_old_old));\n        vh = v_old + ((parameters.dt / parameters.rho) * (1.5 * v_source_old - 0.5 * v_source_old_old));\n    }\n}\n\nvoid FRACTIONAL_STEP_1::calc_pressure(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old)\n{\n    int dim = parameters.dimension;\n    p_source.head(points.nv) = ((points.grad_x_matrix_EIGEN_internal * uh) + (points.grad_y_matrix_EIGEN_internal * vh)) * parameters.rho / parameters.dt;\n    for (int iv = 0; iv < points.nv; iv++)\n        if (points.boundary_flag[iv])\n        {\n            if (p_dirichlet_flag[iv]) //dirichlet BC\n                p_source[iv] = p_old[iv];\n            else //normal momentum\n                p_source[iv] = -parameters.rho * ((u_old[iv] - uh[iv]) * points.normal[dim * iv] + (v_old[iv] - vh[iv]) * points.normal[dim * iv + 1]) / parameters.dt;\n        }\n    if (p_source.rows() == points.nv + 1)\n        p_source[points.nv] = 0.0;\n    solver_p.general_solve(points, parameters, p_new, p_old, p_source);\n}\n\nvoid FRACTIONAL_STEP_1::calc_vel_corr(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old)\n{\n    u_new = uh - (parameters.dt * (points.grad_x_matrix_EIGEN_internal * p_new.head(points.nv)) / parameters.rho);\n    v_new = vh - (parameters.dt * (points.grad_y_matrix_EIGEN_internal * p_new.head(points.nv)) / parameters.rho);\n    double diag_coeff, rhs, off_diag_coeff;\n    int ivnb, dim = parameters.dimension;\n    for (int iv = 0; iv < points.nv; iv++)\n        if (points.boundary_flag[iv])\n        {\n            if (!p_dirichlet_flag[iv])\n            { //for dirichlet pressure, u_new comes from velocity correction above\n                if (u_dirichlet_flag[iv])\n                    u_new[iv] = u_old[iv]; //dirichlet BC\n                else\n                { //neumann BC\n                    rhs = 0.0;\n                    for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n                    {\n                        ivnb = cloud.nb_points_col[i1];\n                        if (iv == ivnb)\n                            diag_coeff = (cloud.grad_x_coeff[i1] * points.normal[dim * iv]) + (cloud.grad_y_coeff[i1] * points.normal[dim * iv + 1]);\n                        else\n                        {\n                            off_diag_coeff = (cloud.grad_x_coeff[i1] * points.normal[dim * iv]) + (cloud.grad_y_coeff[i1] * points.normal[dim * iv + 1]);\n                            rhs = rhs - (off_diag_coeff * u_new[ivnb]);\n                        }\n                    }\n                    u_new[iv] = (rhs / diag_coeff);\n                }\n            }\n        }\n    for (int iv = 0; iv < points.nv; iv++)\n        if (points.boundary_flag[iv])\n        {\n            if (!p_dirichlet_flag[iv])\n            { //for dirichlet pressure, v_new comes from velocity correction above\n                if (v_dirichlet_flag[iv])\n                    v_new[iv] = v_old[iv]; //dirichlet BC\n                else\n                { //neumann BC\n                    rhs = 0.0;\n                    for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n                    {\n                        ivnb = cloud.nb_points_col[i1];\n                        if (iv == ivnb)\n                            diag_coeff = (cloud.grad_x_coeff[i1] * points.normal[dim * iv]) + (cloud.grad_y_coeff[i1] * points.normal[dim * iv + 1]);\n                        else\n                        {\n                            off_diag_coeff = (cloud.grad_x_coeff[i1] * points.normal[dim * iv]) + (cloud.grad_y_coeff[i1] * points.normal[dim * iv + 1]);\n                            rhs = rhs - (off_diag_coeff * v_new[ivnb]);\n                        }\n                    }\n                    v_new[iv] = (rhs / diag_coeff);\n                }\n            }\n        }\n}\n\nvoid FRACTIONAL_STEP_1::extras(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old)\n{\n    // double total_steady_err, max_err, l1_err;\n    // calc_max_l1_error(u_old, u_new, max_err, l1_err);\n    // total_steady_err = l1_err / parameters.dt;\n    // calc_max_l1_error(v_old, v_new, max_err, l1_err);\n    // total_steady_err += l1_err / parameters.dt;\n    if (temporal_order == 2)\n        u_source_old_old = u_source_old, v_source_old_old = v_source_old;\n    // parameters.steady_error_log.push_back(total_steady_err);\n    // return total_steady_err;\n}", "meta": {"hexsha": "3b92f1739cf1aa303d7a75addf519578e10013b9", "size": 11548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "header_files/fractional_step_1.cpp", "max_stars_repo_name": "shahaneshantanu/memphys", "max_stars_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "header_files/fractional_step_1.cpp", "max_issues_repo_name": "shahaneshantanu/memphys", "max_issues_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "header_files/fractional_step_1.cpp", "max_forks_repo_name": "shahaneshantanu/memphys", "max_forks_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-07T00:32:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:32:37.000Z", "avg_line_length": 52.018018018, "max_line_length": 311, "alphanum_fraction": 0.6409767925, "num_tokens": 3200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5338914547294763}}
{"text": "#define BOOST_TEST_MODULE TestFFTW\n\n#include <fftw3.h>\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n\nBOOST_AUTO_TEST_CASE( FFT1DSingle, * boost::unit_test::tolerance(0.0001f) )\n{\n  static const int N = 32;\n  fftwf_complex in[N], out[N], in2[N];\n  fftwf_plan fwd, bwd;\n  int i;\n  for (i = 0; i < N; i++) {\n    in[i][0] = static_cast<float>(i%7)/6;\n    in[i][1] = 0;\n  }\n\n  fwd = fftwf_plan_dft_1d(N, in, out, FFTW_FORWARD, FFTW_ESTIMATE);\n  fftwf_execute(fwd);\n  fftwf_destroy_plan(fwd);\n\n  bwd = fftwf_plan_dft_1d(N, out, in2, FFTW_BACKWARD, FFTW_ESTIMATE);\n  fftwf_execute(bwd);\n\n  for (i = 0; i < N; i++) {\n    in2[i][0] *= 1.f/N;\n    in2[i][1] *= 1.f/N;\n\n    BOOST_TEST( in[i][0] == in2[i][0] );\n    BOOST_TEST( in[i][1] == in2[i][1] );\n  }\n\n  fftwf_destroy_plan(bwd);\n  fftwf_cleanup();\n}\n\n\nBOOST_AUTO_TEST_CASE( FFT1D, * boost::unit_test::tolerance(0.0001) )\n{\n  static const int N = 32;\n  fftw_complex in[N], out[N], in2[N];\n  fftw_plan fwd, bwd;\n  int i;\n  for (i = 0; i < N; i++) {\n    in[i][0] = static_cast<double>(i%7)/6;\n    in[i][1] = 0;\n  }\n\n  fwd = fftw_plan_dft_1d(N, in, out, FFTW_FORWARD, FFTW_ESTIMATE);\n  fftw_execute(fwd);\n  fftw_destroy_plan(fwd);\n\n  bwd = fftw_plan_dft_1d(N, out, in2, FFTW_BACKWARD, FFTW_ESTIMATE);\n  fftw_execute(bwd);\n\n  for (i = 0; i < N; i++) {\n    in2[i][0] *= 1./N;\n    in2[i][1] *= 1./N;\n\n    BOOST_TEST( in[i][0] == in2[i][0] );\n    BOOST_TEST( in[i][1] == in2[i][1] );\n  }\n\n  fftw_destroy_plan(bwd);\n  fftw_cleanup();\n}\n\n#if defined(GEARSHIFFT_FFTW_USE_THREADS) && GEARSHIFFT_FFTW_USE_THREADS==1\nBOOST_AUTO_TEST_CASE( FFT1D2Threads, * boost::unit_test::tolerance(0.0001) )\n{\n  static const int N = 32;\n  fftw_complex in[N], out[N], in2[N];\n  fftw_plan fwd, bwd;\n  int i;\n  for (i = 0; i < N; i++) {\n    in[i][0] = static_cast<double>(i%7)/6;\n    in[i][1] = 0;\n  }\n\n  int res = fftw_init_threads();\n  if(res==0)\n    BOOST_ERROR(\"fftw thread initialization failed.\");\n  fftw_plan_with_nthreads(2);\n\n  fwd = fftw_plan_dft_1d(N, in, out, FFTW_FORWARD, FFTW_ESTIMATE);\n  if(!fwd)\n    BOOST_ERROR(\"forward plan could not be created.\");\n  fftw_execute(fwd);\n  fftw_destroy_plan(fwd);\n\n  bwd = fftw_plan_dft_1d(N, out, in2, FFTW_BACKWARD, FFTW_ESTIMATE);\n  if(!bwd)\n    BOOST_ERROR(\"backward plan could not be created.\");\n  fftw_execute(bwd);\n\n  for (i = 0; i < N; i++) {\n    in2[i][0] *= 1./N;\n    in2[i][1] *= 1./N;\n\n    BOOST_TEST( in[i][0] == in2[i][0] );\n    BOOST_TEST( in[i][1] == in2[i][1] );\n  }\n\n  fftw_destroy_plan(bwd);\n  fftw_cleanup_threads();\n  fftw_cleanup();\n}\n#endif\n", "meta": {"hexsha": "56ad0808b8b50286a4a31069f902b24d6eb55feb", "size": 2538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_fftw.cpp", "max_stars_repo_name": "psteinb/gearshifft", "max_stars_repo_head_hexsha": "fea380554a898191b57a1c0922174f5dd64c04db", "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/test_fftw.cpp", "max_issues_repo_name": "psteinb/gearshifft", "max_issues_repo_head_hexsha": "fea380554a898191b57a1c0922174f5dd64c04db", "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/test_fftw.cpp", "max_forks_repo_name": "psteinb/gearshifft", "max_forks_repo_head_hexsha": "fea380554a898191b57a1c0922174f5dd64c04db", "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.2844036697, "max_line_length": 76, "alphanum_fraction": 0.6158392435, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5338914539520622}}
{"text": "#include <iostream>\r\n#include <fstream>\r\n#include <cmath>\r\n#include <vector>\r\n#include <math.h>\r\n#include \"SpaceAdaptiveSolver.hpp\"\r\n#include \"GeneralizedHeat.hpp\"\r\n#include \"APDE.hpp\"\r\n#include \"PDE_Q2.hpp\"\r\n#include \"originalPDE.hpp\"\r\n#include \"EllipticPDE_Q1.hpp\"\r\n#include \"EllipticPDE2.hpp\"\r\n#include \"Nonanalytic_1.hpp\"\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 printTime(SpaceMesh a_smesh, TimeMesh a_tmesh);\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\r\nSpaceMesh smesh;\r\nstd::vector<double> mesh = {0, 0.15, 0.25, 0.5, 1};\r\n//smesh.GenerateSpaceMesh(mesh);\r\nsmesh.GenerateUniformMesh(1, 5);\r\n//smesh.InsertArray(mesh);\r\n//smesh.PrintSpaceNodes();\r\n\r\nTimeMesh tmesh;\r\ntmesh.GenerateUniformTimeMesh(pow(smesh.meshsize(), 2), 1.0);\r\n\r\n\r\nPDE_Q2 anotherpde;\r\noriginalPDE firstpde;\r\nEllipticPDE_Q1 Q1;\r\nEllipticPDE2 elliptic2;\r\nNonanalytic NA_1;\r\n\r\nAdaptiveSolver adapt;\r\n\r\nadapt.SetSpaceTimeMesh(smesh, tmesh, firstpde);\r\n\r\n\r\nadapt.SetSpaceTimeMesh(smesh, tmesh, anotherpde);\r\nadapt.SetTolerances(0.2,0.05);\r\nadapt.AdaptiveSolve();\r\nadapt.PrintSolution();\r\n\r\nadapt.SetSpaceTimeMesh(smesh, tmesh, anotherpde);\r\nadapt.SolveWithBCs();\r\nadapt.PrintSolution();\r\n}\r\n\r\n\r\nvoid printTime(SpaceMesh a_smesh, TimeMesh a_tmesh)\r\n{\r\n    ofstream myfile2;\r\n    myfile2.open (\"Y.csv\");\r\n    for(int j=1;j<a_tmesh.NumberOfTimeSteps()+1;j++ )\r\n    {\r\n    for(int i = 0; i<a_smesh.meshsize()+1; i++)\r\n    {\r\n        myfile2 << a_tmesh.ReadTimeStep(j) << \", \";\r\n    }\r\n    myfile2 << \"\\n\";\r\n    }\r\n    myfile2.close();\r\n}\r\n\r\n", "meta": {"hexsha": "a7d01b5d550ab149b18080d3f81d43bad9bf6c3e", "size": 1599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solver class with methods to adapt in space/Driver.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": "Solver class with methods to adapt in space/Driver.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": "Solver class with methods to adapt in space/Driver.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": 22.2083333333, "max_line_length": 62, "alphanum_fraction": 0.6885553471, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867969424067, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5338913925635383}}
{"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 dirMM test\n#include <boost/test/unit_test.hpp>\n\n#include <dpMM/dirMM.hpp>\n#include <dpMM/niwBaseMeasure.hpp>\n#include <dpMM/niwSphere.hpp>\n#include <dpMM/dirMMcld.hpp>\n#include <dpMM/clTGMMDataGpu.hpp>\n#include <dpMM/distribution.hpp>\n#include <dpMM/vmfBaseMeasure.hpp>\n#include <dpMM/vmfBaseMeasure3D.hpp>\n\nBOOST_AUTO_TEST_CASE(niwBaseMeasure_test)\n{\n  MatrixXd Delta(3,3);\n  Delta << 1.0,0.0,0.0,\n        0.0,1.0,0.0,\n        0.0,0.0,1.0;\n  VectorXd theta(3);\n  theta << 1.0,1.0,1.0;\n  double nu = 100.0;\n  double kappa = 100.0;\n\n  boost::mt19937 rndGen(1);\n  NIW<double> niw(Delta,theta,nu,kappa,&rndGen);\n\n  NiwMarginalized<double> niwMargBase(niw);\n\n  VectorXd x(3);\n  x << 1.0,1.0,1.0;\n  cout<< niwMargBase.logLikelihood(x)<< endl;\n\n  NiwSampled<double> niwSampledBase(niw);\n\n  x << 1.0,1.0,1.0;\n  cout<< niwSampledBase.logLikelihood(x)<< endl;\n};\n\nBOOST_AUTO_TEST_CASE(dirMM_test)\n{\n\n  double nu = 4.0;\n  double kappa = 4.0;\n  MatrixXd Delta(3,3);\n  Delta << .1,0.0,0.0,\n        0.0,.1,0.0,\n        0.0,0.0,.1;\n  VectorXd theta(3);\n  theta << 0.0,0.0,0.0;\n\n  boost::mt19937 rndGen(9191);\n  NIW<double> niw(Delta,theta,nu,kappa,&rndGen);\n\n  shared_ptr<NiwMarginalized<double> > niwMargBase(\n      new NiwMarginalized<double>(niw));\n  VectorXd alpha(2);\n  alpha << 10.,10.;\n  Dir<Cat<double>, double> dir(alpha,&rndGen); \n  DirMM<double> dirGMM_marg(dir,niwMargBase,2);\n  \n  uint32_t N=20;\n  MatrixXd x(3,N);\n  for(uint32_t i=0; i<N; ++i)\n    if(i<N/2)\n      x.col(i) << 0.0,0.0,0.0;\n    else\n      x.col(i) << 10.0,10.0,10.0;\n  dirGMM_marg.initialize(x);\n  cout<<\"------ sampling -- NIW marginalized\"<<endl;\n  cout<<dirGMM_marg.labels().transpose()<<endl;\n  for(uint32_t t=0; t<30; ++t)\n  {\n    dirGMM_marg.sampleLabels();\n    dirGMM_marg.sampleParameters();\n    cout<<dirGMM_marg.labels().transpose()\n      <<\" logJoint=\"<<dirGMM_marg.logJoint()<<endl;\n  }\n\n  shared_ptr<NiwSampled<double> > niwSampled(\n      new NiwSampled<double>(niw));\n  DirMM<double> dirGMM_samp(dir,niwSampled,2);\n  \n  dirGMM_samp.initialize(x);\n  cout<<\"------ sampling -- NIW sampled\"<<endl;\n  cout<<dirGMM_samp.labels().transpose()<<endl;\n  for(uint32_t t=0; t<30; ++t)\n  {\n    dirGMM_samp.sampleLabels();\n    dirGMM_samp.sampleParameters();\n    cout<<dirGMM_samp.labels().transpose()\n      <<\" logJoint=\"<<dirGMM_samp.logJoint()<<endl;\n  }\n};\n\n\nBOOST_AUTO_TEST_CASE(dirMM_Sphere_test)\n{\n  cout<<\"------ sampling -- NIW sphere\"<<endl;\n\n  double nu = 20.0;\n  MatrixXd Delta(2,2);\n  Delta << .01,0.0,\n        0.0,.01;\n  Delta *= nu;\n\n  boost::mt19937 rndGen(9191);\n  IW<double> iw(Delta,nu,&rndGen);\n  shared_ptr<NiwSphere<double> > niwSp( new NiwSphere<double>(iw,&rndGen));\n\n  VectorXd alpha(2);\n  alpha << 10.,10.;\n  Dir<Cat<double>, double> dir(alpha,&rndGen); \n  DirMM<double> dirGMM_sp(dir,niwSp,2);\n  \n  uint32_t N=20;\n  uint32_t K=2;\n  MatrixXd x(3,N);\n  MatrixXd mus = sampleClustersOnSphere<double>(x, K);\n\n  dirGMM_sp.initialize(x);\n\n  cout<<\"true means: \"<<endl<<mus<<endl;\n  cout<<dirGMM_sp.labels().transpose()<<endl;\n  for(uint32_t t=0; t<10; ++t)\n  {\n    dirGMM_sp.sampleParameters();\n//    for(uint32_t k=0; k<dirGMM_sp.getK(); ++k)\n//    {\n//      cout<<\"  k: \"<<k<<\" \"<<endl; \n//      dirGMM_sp.getTheta(k)->print();\n//    }\n    dirGMM_sp.sampleLabels();\n    cout<<\"@t=\"<<t<<\" \"<<dirGMM_sp.labels().transpose()\n      <<\" logJoint=\"<<dirGMM_sp.logJoint()<<endl;\n  }\n  MatrixXd logLikes;\n  MatrixXu inds = dirGMM_sp.mostLikelyInds(5,logLikes);\n  cout<<\"most likely indices\"<<endl;\n  cout<<inds<<endl;\n  cout<<\"----------------------------------------\"<<endl;\n};\n\ntypedef double myFlt;\n\nBOOST_AUTO_TEST_CASE(dirMMcld_Sphere_test)\n{\n  cout<<\"------ sampling -- NIW sphere using CLD\"<<endl;\n\n  uint32_t N=30; //640*480;\n  uint32_t K=6;\n  uint32_t D=3;\n  boost::mt19937 rndGen(9191);\n  // sample datapoints\n  shared_ptr<Matrix<myFlt,Dynamic,Dynamic> > sx(new \n      Matrix<myFlt,Dynamic,Dynamic>(D,N));\n  Matrix<myFlt,Dynamic,Dynamic> mus =  sampleClustersOnSphere(*sx, 3);\n\n  // alpha\n  Matrix<myFlt,Dynamic,1> alpha(K);\n  alpha << 1.,1.,.1,.1,.1,.1;\n  alpha *= 1;\n  \n  // niw\n  double nu = (1.0)+D+N/100.;\n  Matrix<myFlt,Dynamic,Dynamic> Delta(2,2);\n  Delta << .01,0.0,\n        0.0,.01;\n  Delta *= nu;\n\n  IW<myFlt> iw(Delta,nu,&rndGen);\n  shared_ptr<NiwSphere<myFlt> > niwSp( new NiwSphere<myFlt>(iw,&rndGen));\n//  shared_ptr<NiwSphere<double> > niwSp2( new NiwSphere<double>(iw,&rndGen));\n\n  Dir<Cat<myFlt>, myFlt> dir(alpha,&rndGen); \n  DirMMcld<NiwSphere<myFlt>,myFlt> dirGMM_sp(dir,niwSp);\n\n//  DirMM<myFlt> dirGMM_cpu(dir,niwSp2);\n\n  shared_ptr<ClTGMMDataGpu<myFlt> > clsp(\n      new ClTGMMDataGpu<myFlt>(sx, spVectorXu(new VectorXu(N)),K));\n\n  MatrixXd ps(D,K);\n  Sphere<double> sphere(D);\n  for(uint32_t k=0; k<K; ++k)\n    ps.col(k) = sphere.sampleUnif(&rndGen);\n  clsp->init(ps);\n\n  Matrix<myFlt,Dynamic,1> mu(D);\n  mu<<0.0,0.0,1.0;\n  Matrix<myFlt,Dynamic,Dynamic> Sigma = Matrix<myFlt,Dynamic,Dynamic>::Identity(D,D);\n\n  dirGMM_sp.initialize(clsp);\n//  dirGMM_cpu.initialize(*sx);\n  cout<<counts<myFlt,uint32_t>(dirGMM_sp.labels(),K).transpose()<<endl;\n  Timer t;\n  for(uint32_t i=0; i<5; ++i)\n  {\n//    t.tic();\n//    dirGMM_cpu.sampleLabels();\n//    dirGMM_cpu.sampleParameters();\n//    cout<<dirGMM_cpu.labels().transpose()<<endl;\n//    t.toctic(\" -----------------CPU------------------- fullIteration\");\n    t.tic();\n    dirGMM_sp.sampleParameters();\n    dirGMM_sp.sampleLabels();\n    cout<<dirGMM_sp.z().transpose()<<endl;\n    cout<<dirGMM_sp.counts().transpose()<<endl;\n    cout<<dirGMM_sp.means()<<endl;\n    t.toctic(\" -----------------GPU------------------- fullIteration\");\n//        <<\" logJoint=\"<<dirGMM_sp.logJoint()<<endl;\n  }\n  cout<<\"true mus: \"<<endl;\n  cout <<mus<<endl;\n};\n\n\nBOOST_AUTO_TEST_CASE(dirMM_vMFsampled_test)\n{\n  cout<<\"------ sampling -- Dir-vMF (old, monte carlo estimation for marginalization)\"<<endl;\n\n  double a0 = 5.0;\n  double b0 = 4.7;\n  double t0 = 0.1;\n  VectorXd m0(3);\n  m0 << 1.0,0.0,0.0;\n\n  boost::mt19937 rndGen(9191);\n\n  vMFpriorFull<double> vMFprior(m0,t0,a0,b0,&rndGen);\n  shared_ptr<vMFbase<double> > vMFsampled( new vMFbase<double>(vMFprior));\n\n  VectorXd alpha(2);\n  alpha << 10.,10.;\n  Dir<Cat<double>, double> dir(alpha,&rndGen); \n  DirMM<double> dirvMF_sp(dir,vMFsampled,2);\n  \n  uint32_t N=20;\n  uint32_t K=2;\n  MatrixXd x(3,N);\n  MatrixXd mus = sampleClustersOnSphere<double>(x, K);\n\n  dirvMF_sp.initialize(x);\n\n  cout<<\"true means: \"<<endl<<mus<<endl;\n  cout<<dirvMF_sp.labels().transpose()<<endl;\n  for(uint32_t t=0; t<10; ++t)\n  {\n    dirvMF_sp.sampleParameters();\n//    for(uint32_t k=0; k<dirvMF_sp.getK(); ++k)\n//    {\n//      cout<<\"  k: \"<<k<<\" \"<<endl; \n//      dirvMF_sp.getTheta(k)->print();\n//    }\n    dirvMF_sp.sampleLabels();\n    cout<<\"@t=\"<<t<<\" \"<<dirvMF_sp.labels().transpose()\n      <<\" logJoint=\"<<dirvMF_sp.logJoint()<<endl;\n  }\n//  MatrixXd logLikes;\n//  MatrixXu inds = dirvMF_sp.mostLikelyInds(5,logLikes);\n//  cout<<\"most likely indices\"<<endl;\n//  cout<<inds<<endl;\n  cout<<\"true means: \"<<endl<<mus<<endl;\n    for(uint32_t k=0; k<dirvMF_sp.getK(); ++k) \n    { \n      cout<<\"  k: \"<<k<<endl; \n      dirvMF_sp.getTheta(k)->print(); \n    }\n  cout<<\"----------------------------------------\"<<endl;\n};\n\n\nBOOST_AUTO_TEST_CASE(dirMM_vMF_test)\n{\n  cout<<\"------ sampling -- Dir-vMF (new, analytic marginalization for 3D)\"<<endl;\n\n  double a0 = 1.0;\n  double b0 = 0.99;\n  VectorXd m0(3);\n  m0 << 1.0,0.0,0.0;\n\n  boost::mt19937 rndGen(9191);\n\n  vMFprior<double> vMFprior(m0,a0,b0,&rndGen);\n  shared_ptr<vMFbase3D<double> > vMFbase( new vMFbase3D<double>(vMFprior));\n\n//  VectorXd alpha(1);\n//  alpha << 10.;\n//  Dir<Cat<double>, double> dir(alpha,&rndGen); \n//  DirMM<double> dirvMF_sp(dir,vMFbase,1);\n\n  VectorXd alpha(2);\n  alpha << 10.,10.;\n  Dir<Cat<double>, double> dir(alpha,&rndGen); \n  DirMM<double> dirvMF_sp(dir,vMFbase,2);\n  \n  uint32_t N=200;\n  uint32_t K=2;\n  MatrixXd x(3,N);\n  MatrixXd mus = sampleClustersOnSphere<double>(x, K);\n\n  dirvMF_sp.initialize(x);\n\n  cout<<\"true means: \"<<endl<<mus<<endl;\n  cout<<dirvMF_sp.labels().transpose()<<endl;\n  for(uint32_t t=0; t<100; ++t)\n  {\n    dirvMF_sp.sampleParameters();\n//    for(uint32_t k=0; k<dirvMF_sp.getK(); ++k)\n//    {\n//      cout<<\"  k: \"<<k<<\" \"<<endl; \n//      dirvMF_sp.getTheta(k)->print();\n//    }\n    dirvMF_sp.sampleLabels();\n    cout<<\"@t=\"<<t<<\" \"<<dirvMF_sp.labels().transpose()\n      <<\" logJoint=\"<<dirvMF_sp.logJoint()<<endl;\n  }\n//  MatrixXd logLikes;\n//  MatrixXu inds = dirvMF_sp.mostLikelyInds(5,logLikes);\n//  cout<<\"most likely indices\"<<endl;\n//  cout<<inds<<endl;\n  cout<<\"true means: \"<<endl<<mus<<endl;\n    for(uint32_t k=0; k<dirvMF_sp.getK(); ++k) \n    { \n      cout<<\"  k: \"<<k<<endl; \n      dirvMF_sp.getTheta(k)->print(); \n    }\n  cout<<\"----------------------------------------\"<<endl;\n\n//  vMF<double> vmf(m0, 100, &rndGen);\n//  std::cout << m0.transpose() << std::endl << \" -- \" << std::endl;\n//  for (size_t i=0; i<100; ++i) {\n//    Eigen::VectorXd x = vmf.sample();\n//    std::cout << x.transpose()  << \" || \" << x.norm() << std::endl;\n//  }\n//\n//  std::cout << \" -- \" << std::endl;\n//  for (size_t i=0; i<100; ++i) {\n//    vmf = vMFprior.sample();\n//    vmf.print();\n////    std::cout << vmf.mu_.transpose()  << \" tau \" << vmf.tau_ << std::endl;\n//  }\n\n};\n", "meta": {"hexsha": "d9d9afb2f7b269cf3911976d406bc4e32889be4b", "size": 9445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/dirMM.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/dirMM.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/dirMM.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": 26.9857142857, "max_line_length": 93, "alphanum_fraction": 0.6099523557, "num_tokens": 3307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5338913861413563}}
{"text": "#include <memory>\n#include <cassert>\n#include <limits>\n#include <algorithm>\n#include <vector>\n#include <iostream>\n\n#include <boost/iterator/iterator_facade.hpp>\n\n#include <cs.h>\n\nstruct CSparseShim {\n    using index_t = CS_INT;     // for options, refer to CS_LONG and CS_COMPLEX in cs.h\n    using value_t = CS_ENTRY;\n\n    struct triplet_t {\n        index_t row;\n        index_t col;\n        value_t value;\n    };\n\n    // RAII memory management for C data\n    struct cs_deleter {\n        void operator()(cs *p) {\n            cs_spfree(p);\n        }\n        void operator()(csn *p) {\n            cs_nfree(p);\n        }\n        void operator()(css *p) {\n            cs_sfree(p);\n        }\n        template<typename T>\n        void operator()(T *p) {\n            cs_free(p);\n        }\n    };\n\n    template<typename T> using cs_unique_ptr = std::unique_ptr<T, cs_deleter>;\n    template<typename T> using cs_shared_ptr = std::shared_ptr<T>;\n    template<typename T>\n    static cs_shared_ptr<T>\n    make_cs_shared_ptr(T* p) { return cs_shared_ptr<T>(p, cs_deleter()); }\n\n\n    // create a forward iterator for nonzeros within a CSparse matrix\n    struct sparse_entry_iterator\n        : boost::iterator_facade<sparse_entry_iterator,\n                                 triplet_t const,\n                                 boost::forward_traversal_tag> {\n        sparse_entry_iterator() {}\n        sparse_entry_iterator( cs_shared_ptr<cs> mat )\n            : mat_(std::move(mat)), entry_{index_t(0), index_t(0), value_t(0)} {\n            advance_to_valid();\n        }\n\n    private:\n\n        // iterator_facade requirements\n\n        friend class boost::iterator_core_access;\n\n        void increment();\n\n        bool equal( sparse_entry_iterator const& other ) const;\n\n        triplet_t const & dereference() const {\n            return entry_;\n        }\n\n        // find the next nonzero entry and set the dereference value\n        void advance_to_valid();\n\n        cs_shared_ptr<cs> mat_;\n        triplet_t entry_;     // for supplying references\n    };\n\n\n    struct sparsemat_t;\n\n    static sparsemat_t\n    dense_to_sparse( std::vector<value_t> const& d, index_t rows, index_t cols );\n\n    struct sparsemat_t {\n        template<typename Iter>\n        sparsemat_t(index_t rows, index_t cols, Iter start, Iter end) {\n            // create a triplet matrix\n            auto TG = cs_unique_ptr<cs>(cs_spalloc(rows, cols, std::distance(start, end), 1, 1));\n            for ( auto it = start; it < end; ++it ) {\n                assert(cs_entry(TG.get(), it->row, it->col, it->value));\n            }\n                \n            // create a \"cs\" structure from the triplet matrix\n            mat_ = make_cs_shared_ptr(cs_compress(TG.get()));\n        }\n\n        sparsemat_t( cs_shared_ptr<cs> mat_cs ) : mat_(std::move(mat_cs)) {}\n\n        index_t rows() const { return wrapped()->m; }\n        index_t cols() const { return wrapped()->n; }\n\n        sparse_entry_iterator nonzero_begin() const {\n            return sparse_entry_iterator(mat_);\n        }\n        sparse_entry_iterator nonzero_end() const {\n            return sparse_entry_iterator();\n        }\n\n        friend sparsemat_t operator*(sparsemat_t const& a, sparsemat_t const& b);\n        friend std::ostream& operator<<(std::ostream& os, sparsemat_t const & m);\n\n        cs_shared_ptr<const cs> wrapped() const {\n            return mat_;\n        }\n\n    private:\n        cs_shared_ptr<cs> mat_;      // we have to share this structure with LU and QR objects\n    };\n\n    struct lu_t {\n        lu_t( sparsemat_t const & mat )\n            : symbolic_( cs_sqr( 3, mat.wrapped().get(), 0 )),\n              numeric_ ( cs_lu ( mat.wrapped().get(), symbolic_.get(),\n                                 std::numeric_limits<value_t>::epsilon() )) {}\n\n        sparsemat_t solve(sparsemat_t const& rhs) const;\n\n    private:\n        cs_unique_ptr<css> symbolic_;\n        cs_unique_ptr<csn> numeric_;\n\n    };\n\n    struct qr_t {\n        qr_t( sparsemat_t const & mat )\n            : symbolic_( cs_sqr( 3, mat.wrapped().get(), 1 ) ),\n              numeric_ ( cs_qr ( mat.wrapped().get(), symbolic_.get() ) ),\n              rows_    ( mat.wrapped()->m ),\n              cols_    ( mat.wrapped()->n ) {}\n\n        sparsemat_t Q() const;\n\n    private:\n\n        cs_unique_ptr<css> symbolic_;\n        cs_unique_ptr<csn> numeric_;\n\n        index_t rows_, cols_;\n\n    };\n\n};\n", "meta": {"hexsha": "8a7240b354c3271e85f504b1eeb7be9366f0140e", "size": 4385, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "policies/csparse_shim.hpp", "max_stars_repo_name": "jefftrull/SparseMatrixLibraries", "max_stars_repo_head_hexsha": "0eeb36e56dc78566f093531d2718d168d788a708", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-04-30T10:29:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T23:31:34.000Z", "max_issues_repo_path": "policies/csparse_shim.hpp", "max_issues_repo_name": "jefftrull/SparseMatrixLibraries", "max_issues_repo_head_hexsha": "0eeb36e56dc78566f093531d2718d168d788a708", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "policies/csparse_shim.hpp", "max_forks_repo_name": "jefftrull/SparseMatrixLibraries", "max_forks_repo_head_hexsha": "0eeb36e56dc78566f093531d2718d168d788a708", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-22T23:44:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-22T23:44:34.000Z", "avg_line_length": 28.660130719, "max_line_length": 97, "alphanum_fraction": 0.5735461802, "num_tokens": 1028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5338913808728428}}
{"text": "// Copyright (C) 2012  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <cmath>\n#include <dlib/statistics.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.sammon\");\n\n\n    std::vector<matrix<double,4,1> > make_test_data4(\n    )\n    {\n        std::vector<matrix<double,4,1> > data;\n\n        matrix<double,4,1> m;\n\n        m = 0,0,0, 0; data.push_back(m);\n        m = 1,0,0, 0; data.push_back(m);\n        m = 0,1,0, 0; data.push_back(m);\n        m = 0,0,1, 0; data.push_back(m);\n\n        return data;\n    }\n\n    std::vector<matrix<double,3,1> > make_test_data3(\n    )\n    {\n        std::vector<matrix<double,3,1> > data;\n\n        matrix<double,3,1> m;\n\n        m = 0,0,0; data.push_back(m);\n        m = 1,0,0; data.push_back(m);\n        m = 0,1,0; data.push_back(m);\n        m = 0,0,1; data.push_back(m);\n\n        return data;\n    }\n\n    std::vector<matrix<double> > make_test_data3d(\n    )\n    {\n        std::vector<matrix<double> > data;\n\n        matrix<double,3,1> m;\n\n        m = 0,0,0; data.push_back(m);\n        m = 1,0,0; data.push_back(m);\n        m = 0,1,0; data.push_back(m);\n        m = 0,0,1; data.push_back(m);\n\n        return data;\n    }\n\n\n    void runtest()\n    {\n        sammon_projection s;\n        std::vector<matrix<double, 0, 1> >  projs = s(make_test_data3(),2);\n        running_stats<double> rs1, rs2;\n\n        rs1.add(length(projs[0] - projs[1]));\n        rs1.add(length(projs[0] - projs[2]));\n        rs1.add(length(projs[0] - projs[3]));\n\n        rs2.add(length(projs[1] - projs[2]));\n        rs2.add(length(projs[2] - projs[3]));\n        rs2.add(length(projs[3] - projs[1]));\n\n        DLIB_TEST(rs1.stddev()/rs1.mean() < 1e-4);\n        DLIB_TEST(rs2.stddev()/rs2.mean() < 1e-4);\n\n\n\n        projs = s(make_test_data4(),2);\n        rs1.clear();\n        rs2.clear();\n\n        rs1.add(length(projs[0] - projs[1]));\n        rs1.add(length(projs[0] - projs[2]));\n        rs1.add(length(projs[0] - projs[3]));\n\n        rs2.add(length(projs[1] - projs[2]));\n        rs2.add(length(projs[2] - projs[3]));\n        rs2.add(length(projs[3] - projs[1]));\n\n        DLIB_TEST(rs1.stddev()/rs1.mean() < 1e-4);\n        DLIB_TEST(rs2.stddev()/rs2.mean() < 1e-4);\n\n        projs = s(make_test_data3d(),2);\n        rs1.clear();\n        rs2.clear();\n\n        rs1.add(length(projs[0] - projs[1]));\n        rs1.add(length(projs[0] - projs[2]));\n        rs1.add(length(projs[0] - projs[3]));\n\n        rs2.add(length(projs[1] - projs[2]));\n        rs2.add(length(projs[2] - projs[3]));\n        rs2.add(length(projs[3] - projs[1]));\n\n        DLIB_TEST(rs1.stddev()/rs1.mean() < 1e-4);\n        DLIB_TEST(rs2.stddev()/rs2.mean() < 1e-4);\n    }\n\n    void runtest2()\n    {\n        sammon_projection s;\n        std::vector<matrix<double, 0, 1> >  projs, temp;\n\n        DLIB_TEST(s(projs,3).size() == 0);\n\n        matrix<double,2,1> m;\n        m = 1,2;\n        projs.push_back(m);\n        temp = s(projs,2);\n        DLIB_TEST(temp.size() == 1);\n        DLIB_TEST(temp[0].size() == 2);\n\n        projs.push_back(m);\n        temp = s(projs,1);\n        DLIB_TEST(temp.size() == 2);\n        DLIB_TEST(temp[0].size() == 1);\n        DLIB_TEST(temp[1].size() == 1);\n    }\n\n    void runtest3(int num_dims)\n    {\n        sammon_projection s;\n        std::vector<matrix<double, 0, 1> >  projs;\n        matrix<double,3,1> m;\n        m = 1, 1, 1;\n        projs.push_back(m);\n\n        m = 1, 2, 1;\n        projs.push_back(m);\n\n        m = 1, 3, 1;\n        projs.push_back(m);\n\n        projs = s(projs,num_dims);\n\n        const double d1a = length(projs[0] - projs[1]);\n        const double d1b = length(projs[1] - projs[2]);\n        const double d2  = length(projs[0] - projs[2]);\n\n        DLIB_TEST(std::abs(d1a-d1b)/d1a < 1e-8);\n        DLIB_TEST(std::abs(d2/d1a-2) < 1e-8);\n    }\n\n    void runtest4(int num_dims)\n    {\n        sammon_projection s;\n        std::vector<matrix<double, 0, 1> >  projs;\n        matrix<double,3,1> m;\n        m = 1, 1, 1;\n        projs.push_back(m);\n\n        m = 1, 2, 1;\n        projs.push_back(m);\n\n\n        projs = s(projs,num_dims);\n\n        DLIB_TEST(length(projs[0] - projs[1]) > 1e-5); \n    }\n\n    class sammon_tester : public tester\n    {\n    public:\n        sammon_tester (\n        ) :\n            tester (\"test_sammon\",\n                    \"Runs tests on the sammon_projection component.\")\n        {}\n\n        void perform_test (\n        )\n        {\n            print_spinner();\n            runtest();\n            print_spinner();\n            runtest2();\n            print_spinner();\n            runtest3(2);\n            print_spinner();\n            runtest4(2);\n            runtest3(1);\n            print_spinner();\n            runtest4(1);\n        }\n    } a;\n\n}\n\n\n\n", "meta": {"hexsha": "5328bd1f637d2268084b63070c622872abd36772", "size": 4917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dlib/test/sammon.cpp", "max_stars_repo_name": "prathyusha12924/eye-gaze", "max_stars_repo_head_hexsha": "a80ad54b46e9cef4e743b53aaff035de83f27154", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "dlib/test/sammon.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "dlib/test/sammon.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 23.1933962264, "max_line_length": 75, "alphanum_fraction": 0.5086434818, "num_tokens": 1569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5338913797191742}}
{"text": "#include <opencv2/opencv.hpp>\n#include <iostream>\n#include <boost/filesystem.hpp>\n#include \"derivatives.h\"\n#include \"labelconnect.hpp\"\n#include \"region.h\"\n#include \"link.h\"\n#include \"utils.hpp\"\n#include <iostream>\n#include <iomanip>\n#include \"strands.h\"\n#include <cmath>\n#include \"version.h\"\n#include <exception> \n#include <time.h>\n\n#include <chrono>\n\nstring NowToString()\n{\n\tchrono::system_clock::time_point p = chrono::system_clock::now();\n\ttime_t t = chrono::system_clock::to_time_t(p);\n//\tchar str[26];\n//\tctime_s(str, sizeof str, &t);\n\treturn ctime(&t);\n}\n\nusing namespace cv;\nusing namespace std;\nusing namespace boost;\nnamespace fs = boost::filesystem;\nusing namespace stegers;\nusing namespace timer;\n\n\nvoid strands::run(){\n\n\tassert(labelConnect::test());\n\tassert(region::test());\n\n\tauto polarity = strands::line_polarity::light;\n\tfloat sigma = 1.5;\n\tfloat low_thr = 1.0;\n\tfloat high_thr = 6.0;\n\n\tstd::string version_string(VERSION);\n\tversion_string = NowToString() + \"build \" + version_string + \"\\nimage file: \" + m_input_file.stem().string();\n\tauto filename = m_input_file.stem();\n\tfilename = \"histogram_output_\" + filename.string() + \".csv\";\n\tfilename = m_output_dir / filename;\n\t\n\tMat image = imread(m_input_file.string(), cv::IMREAD_GRAYSCALE);\n\n\tMat display;\n\tstring screen(\"display\");\n\tif (show() || graphics()) {\n\t\tstd::vector<Mat> triple{ image, image, image };\n\t\tmerge(triple, display);\n\t}\n\t// Show our image inside a window.\n\tif (show())\n\t\tnamedWindow(screen.c_str(), cv::WINDOW_GUI_EXPANDED);\n\n\tstd::map<int32_t, int32_t> lm;\n\n\ttry {\n\n\n\t\t// Convert to flat vector of doubles\t\n\t\t// @todo have cv::Mat api\n\t\tcv::Mat dst;\n\t\timage.convertTo(dst, CV_64F);\n\t\tstd::vector<double> dimg(size_t(image.rows * image.cols));\n\t\tassert(dst.isContinuous());\n\t\tstd::memcpy(dimg.data(), dst.ptr(0), image.total() * sizeof(double));\n\t\tconvol conv(image.cols, image.rows);\n\t\tconv.debug(debug());\n\n\t\tstd::vector<std::vector<float>> out;\n\t\tconv.get_all_derivatives(dimg, sigma, out);\n\t\tstd::vector<int32_t> ismax;\n\t\tstd::vector<std::vector<double>> line_out;\n\t\tclass link lnk(image.cols, image.rows, 1.5, strands::line_polarity::light);\n\t\tlnk.debug(debug());\n\t\tlnk.compute_line_points(out, ismax, line_out, low_thr, high_thr);\n\t\tconst cv::Mat& esp = lnk.eSpace();\n\t\tlnk.compute_contours(ismax, line_out[0], line_out[5], line_out[6], line_out[1], line_out[2], line_out[3], line_out[5]);\n\n\t\tfloat length_total = 0;\n\t\tfor (auto cc = 0; cc < lnk.results().size(); cc++) {\n\t\t\tconst contour& ct = lnk.results()[cc];\n\t\t\tauto length = ct.compute_length();\n\t\t\tint ilength = (int)length;\n\t\t\tauto miter = lm.find(ilength);\n\t\t\tif (miter == lm.end())\n\t\t\t\tlm[ilength] = 0;\n\t\t\tauto current = lm[ilength];\n\t\t\tlm[ilength] = current + 1;\n\t\t\tlength_total += length;\n\t\t}\n\n\t\tfloat avg_node_count = lnk.results().empty() ? 0 : length_total / float(lnk.results().size());\n\t\tstd::string output = \"AvgLength: \" + std::to_string(avg_node_count);\n\t\tstd::string output2 = \"Count: \" + std::to_string(lnk.results().size());\n\n\t\tif (debug()) {\n\t\t\tstd::cout << output << std::endl;\n\t\t\tstd::cout << output2 << std::endl;\n\t\t}\n\n\t\tstring total_string = version_string + \"\\n\" + output + \"\\n\" + output2 + \"\\n\";\n\t\tif (lnk.is_crowded())\n\t\t\ttotal_string = total_string + \"is Crowded \\n\";\n\n\t\tsave_csv(lm, filename.string(), total_string);\n\n\n\n\n\t\tif (show() || graphics()) {\n\t\t\tint factor = 8;\n\t\t\tfor (auto cc = 0; cc < lnk.results().size(); cc++) {\n\t\t\t\tconst contour& ct = lnk.results()[cc];\n\t\t\t\tstd::vector<Point> pts;\n\t\t\t\tstd::vector<float>::const_iterator rowItr = ct.row.begin();\n\t\t\t\tstd::vector<float>::const_iterator colItr = ct.col.begin();\n\t\t\t\tfor (auto pp = 0; pp < ct.row.size(); pp++, rowItr++, colItr++) {\n\t\t\t\t\tpts.emplace_back(static_cast<int>(*colItr * factor), static_cast<int>(*rowItr * factor));\n\t\t\t\t}\n\t\t\t\tpolylines(display, pts, false, Scalar(0, 0, 255), 2, LINE_AA, int(std::log2(factor)));\n\t\t\t}\n\n\n\t\t\tif (lnk.is_crowded())\n\t\t\t\tputText(display, \"Is Crowded \", Point(1000, 900), FONT_HERSHEY_SIMPLEX, 3.0, Scalar(0, 255, 0), 2);\n\n\n\t\t\tstd::string output = \" Average Length \" + std::to_string(avg_node_count);\n\t\t\tputText(display, output.c_str(), Point(1000, 1000), FONT_HERSHEY_SIMPLEX, 3.0, Scalar(0, 255, 0), 2);\n\t\t\tstd::string output2 = \" Count \" + std::to_string(lnk.results().size());\n\t\t\tputText(display, output2.c_str(), Point(1000, 1200), FONT_HERSHEY_SIMPLEX, 3.0, Scalar(0, 255, 0), 2);\n\n\t\t\tint start = 100;\n\t\t\tauto it = lm.begin();\n\t\t\twhile (it != lm.end()) {\n\t\t\t\tstd::string hout = \"histogram [\" + std::to_string(it->first) + \"] = \" + std::to_string(it->second);\n\t\t\t\tputText(display, hout.c_str(), Point(500, start), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(255, 0, 0), 2);\n\t\t\t\tstart += 30;\n\t\t\t\tit++;\n\t\t\t}\n\n\t\t\tif (show()) {\n\t\t\t\timshow(screen.c_str(), display);\n\t\t\t\t// Wait for any keystroke in the window\n\t\t\t\twaitKey(0);\n\t\t\t}\n\n\t\t\tif (graphics()) {\n\t\t\t\tauto filename = m_input_file.filename();\n\t\t\t\tfilename = \"output_\" + filename.string();\n\t\t\t\tfilename = m_output_dir / filename;\n\t\t\t\tcv::imwrite(filename.string(), display);\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tcatch (std::exception& e) {\n\t\tversion_string = version_string + \" error \" + e.what();\n\t\tlm.clear();\n\t\tsave_csv(lm, filename.string(), version_string);\n\t}\n\n}\n\n", "meta": {"hexsha": "ad71c72f1c2cde9209260ad757bff0ab4bade0e2", "size": 5170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xcode/strands/strands/strands.cpp", "max_stars_repo_name": "DarisaLLC/ridge_strands", "max_stars_repo_head_hexsha": "50766c05a40c41f7934e7fef73ae1114fccbe9dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T10:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T03:39:28.000Z", "max_issues_repo_path": "xcode/strands/strands/strands.cpp", "max_issues_repo_name": "DarisaLLC/ridge_strands", "max_issues_repo_head_hexsha": "50766c05a40c41f7934e7fef73ae1114fccbe9dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-10T06:11:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T06:11:05.000Z", "max_forks_repo_path": "xcode/strands/strands/strands.cpp", "max_forks_repo_name": "DarisaLLC/ridge_strands", "max_forks_repo_head_hexsha": "50766c05a40c41f7934e7fef73ae1114fccbe9dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-30T10:57:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-30T10:57:48.000Z", "avg_line_length": 29.209039548, "max_line_length": 121, "alphanum_fraction": 0.6529980658, "num_tokens": 1520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5338913797191741}}
{"text": "#include \"utils/data_generator.cpp\"\n#include \"../src/numerical/evolutionary_algorithm/ea_solver.h\"\n#include \"../src/numerical/evolutionary_algorithm/robust_ea_solver.h\"\n#include \"../src/logging/easylogging++.h\"\n#include <armadillo>\n\nusing arma::mat;\n\nINITIALIZE_EASYLOGGINGPP\n\nmat WEIGHTS = {100, -20, 50, -0.5};\n\narma::mat quadratic_model(arma::mat x, arma::mat L)\n{\n    return x * arma::pow(L, 2);\n}\n\nint main(int argc, char *argv[])\n{\n    el::Configurations conf(\"./logging-config.conf\");\n    el::Loggers::reconfigureLogger(\"default\", conf);\n\n    auto data_generator = DataGenerator();\n    auto L = data_generator.generate_library();\n    auto s = data_generator.generate_signal(WEIGHTS);\n    std::vector<int> outlier_channels = {5, 10};\n    auto s_with_outliers = data_generator.generate_signal(WEIGHTS, outlier_channels);\n\n    LOG(INFO) << \"True: \" << WEIGHTS;\n\n    EASolver ea_solver = EASolver(L);\n    ea_solver.set_initial_guess(arma::mat{50, -10, 5, 0});\n    mat result1 = ea_solver.solve(s);\n    LOG(INFO) << \"EA fit: \" << result1;\n\n    RobustEASolver robust_ea_solver = RobustEASolver(L);\n    mat result2 = robust_ea_solver.solve(s_with_outliers);\n    LOG(INFO) << \"Robust EA fit: \" << result2;\n\n    return 0;\n}", "meta": {"hexsha": "804c16c99e140125727e5631ce0ca5e1787bd08a", "size": 1221, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/ea_solver.cpp", "max_stars_repo_name": "omyllymaki/math", "max_stars_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T03:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T09:12:24.000Z", "max_issues_repo_path": "samples/ea_solver.cpp", "max_issues_repo_name": "omyllymaki/math", "max_issues_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_issues_repo_licenses": ["MIT"], "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/ea_solver.cpp", "max_forks_repo_name": "omyllymaki/math", "max_forks_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_forks_repo_licenses": ["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.7804878049, "max_line_length": 85, "alphanum_fraction": 0.6936936937, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5338913732969918}}
{"text": "#include <util_coo_matrix.h>\n#include <util_coo_pcg.h>\n#include <util_coo_bicg.h>\n#include <util_coo_cr.h>\n#include <util_coo_bicgstab.h>\n#include <util_coo_gmres.h>\n\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\n#include <boost/random.hpp>\n#include <boost/cast.hpp>\n\n\ntemplate<typename T>\nclass Random\n{\npublic:\n\n  typedef boost::minstd_rand  generator_type;\n\nprotected:\n\n  static generator_type &  generator()\n  {\n    static generator_type tmp(static_cast<unsigned int>(std::time(0)));\n    return tmp;\n  }\n\npublic:\n\n  typedef boost::uniform_real<T>                                         distribution_type;\n  typedef boost::variate_generator<generator_type&, distribution_type >  random_type;\n\n  distribution_type       m_distribution;\n  random_type             m_random;\n\npublic:\n\n  Random()\n  : m_distribution(  boost::numeric_cast<T>(0.0)\n                   , boost::numeric_cast<T>(1.0)\n                   )\n  , m_random(generator(), m_distribution)\n  {}\n\n  Random(T const & lower,T const & upper)\n  : m_distribution(lower,upper)\n  , m_random(generator(), m_distribution)\n  {}\n\nprivate:\n\n  Random(Random const & rnd){}\n\n  Random & operator=(Random const & rnd){return *this;}\n\npublic:\n\n  T operator()() { return m_random();  }\n\n  bool operator==(Random const & rnd) const { return m_distribution == rnd.m_distribution; }\n\n};\n\ntemplate<typename T>\ninline util::COOMatrix<T>  make_random_matrix( unsigned int const & m, unsigned int const & n )\n{\n  typedef util::COOMatrix<T>   matrix_type;\n\n  matrix_type A;\n\n  Random<T>  value( T(0.0), T(1.0));\n\n  A.init(m,n,n);\n\n  for(unsigned int i=0u;i<m;++i)\n  {\n    for(unsigned int j=0u;j<n;++j)\n    {\n      T const val = value();\n      A.insert(i,j,val);\n    }\n  }\n  return A;\n\n}\n\ntemplate<typename T>\ninline std::vector<T> make_random_vector( unsigned int const & n)\n{\n  Random<T>  value( T(0.0), T(1.0));\n\n  std::vector<T> v(n, T(0.0));\n\n  for(unsigned int i=0u; i<n; ++i)\n  {\n    v[i] = value();\n  }\n\n  return v;\n}\n\ntemplate<typename T>\ninline util::COOMatrix<T>  make_hilbert_matrix( unsigned int const & n )\n{\n  util::COOMatrix<T> A;\n\n  A.init(n,n,n);\n\n  for(unsigned int i=0u;i<n;++i)\n  {\n    for(unsigned int j=0u;j<n;++j)\n    {\n      T const val = T(1.0) / (   T(i+j+1u) );\n      A.insert(i,j,val);\n    }\n  }\n  return A;\n\n}\n\n/**\n * Factory function for creating a tri diagonal matrix (special case of a banded matrix).\n *\n * @param n       The size of the matrix to make. The resulting matrix will be of size (n X n)\n * @param a       The value to store on the diagonal of the matrix\n * @param b       The value to store above the diagonal.\n * @param c       The value to store below the diagonal.\n *\n */\ntemplate<typename T>\ninline util::COOMatrix<T>  make_triadiagonal_matrix( unsigned int const & n\n                                                    , T const & a = T(4.0)\n                                                    , T const & b = T(1.0)\n                                                    , T const & c = T(1.0)\n                                                    )\n{\n  util::COOMatrix<T> A;\n\n  A.init(n,n,3u);\n\n  for(unsigned int i=0u;i<n;++i)\n  {\n    for(unsigned int j=0u;j<n;++j)\n    {\n      T val = 0.0;\n\n      if( i==j)\n      {\n        val = a;\n      }\n      if( i==j+1u)\n      {\n        val = b;\n      }\n      if( i==j-1u)\n      {\n        val = c;\n      }\n      if (fabs(val)> T(0.0))\n      {\n        A.insert(i,j,val);\n      }\n\n    }\n  }\n  return A;\n}\n\ntemplate<typename T>\ninline util::COOMatrix<T>  make_diagonal_dominant_matrix( unsigned int const & n )\n{\n  util::COOMatrix<T> A;\n\n  A.init(n,n,n);\n\n  for(unsigned int i=0u;i<n;++i)\n  {\n    for(unsigned int j=0u;j<n;++j)\n    {\n      if(i==j)\n      {\n        A.insert(i,j,T(n*n) );\n      }\n      else if (fabs( T(j) - T(i) ) <= 2.0 )\n      {\n        T const val = fabs(  T(j) - T(i) );\n        A.insert(i,j,val);\n      }\n    }\n  }\n  return A;\n}\n\ntemplate<typename T>\nclass Problem\n{\npublic:\n\n  util::COOMatrix<T>    m_A;   ///< System matrix (assumed non-singular at least)\n  std::vector<T>        m_x;   ///< The known solution\n  std::vector<T>        m_b;   ///< Right hand side vector\n\n};\n\ntemplate<typename T>\ninline Problem<T> make_problem(unsigned int const & n)\n{\n  Problem<T> problem;\n\n  // problem.m_A = make_hilbert_matrix<T>(n); // Hilbert matrices seems to be badly conditioned as n goes up\n  problem.m_A = make_triadiagonal_matrix<T>(n);\n  // problem.m_A = make_diagonal_dominant_matrix<T>(n);\n  problem.m_x = make_random_vector<T>(n);\n  problem.m_b = util::mul(problem.m_A, problem.m_x);\n\n  return problem;\n}\n\nBOOST_AUTO_TEST_SUITE(coo_solve_equation);\n\nBOOST_AUTO_TEST_CASE(pcg_testing)\n{\n  typedef double T;\n\n  util::COOMatrix<T> A  = util::make_identity<T>(4u);\n  util::COOMatrix<T> M  = util::make_identity<T>(4u);\n\n  unsigned int    const   max_iterations = 10u;\n  unsigned int    const   restart        = 5u;\n  T               const   tolerance      = 1e-10;\n  bool            const   verbose        = true;\n  std::vector<T>          residual;\n\n  std::vector<T> b(4u);\n\n  b[0u] = 1.0;\n  b[1u] = 2.0;\n  b[2u] = 3.0;\n  b[3u] = 4.0;\n\n  std::vector<T> x(4u, 0.0);\n\n  bool success = util::pcg(M, A, x, b, max_iterations, restart, tolerance, verbose, &residual);\n\n  BOOST_CHECK(success);\n\n  BOOST_CHECK_CLOSE(x[0u], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(x[1u], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(x[2u], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(x[3u], 4.0, 0.01);\n}\n\nBOOST_AUTO_TEST_CASE(pcg_random_testing)\n{\n  typedef double T;\n\n  unsigned int    const   max_samples    = 10u;      ///< Maximum number of random problems to solve.\n  unsigned int    const   n              = 10u;      ///< Problem size\n  unsigned int    const   max_iterations = 100u;\n  unsigned int    const   restart        = 1u;\n  T               const   tolerance      = 1e-10;\n  bool            const   verbose        = true;\n  std::vector<T>          residual;\n\n  for (unsigned int sample=0u; sample < max_samples; ++sample)\n  {\n    Problem<T> problem = make_problem<T>(n);\n\n    util::COOMatrix<T> M  = util::make_identity<T>(n);\n\n    std::vector<T> x(n, 0.0);\n\n    bool success = util::pcg(\n                             M\n                             , problem.m_A\n                             , x\n                             , problem.m_b\n                             , max_iterations\n                             , restart\n                             , tolerance\n                             , verbose\n                             , &residual\n                             );\n\n    BOOST_CHECK(success);\n\n    if(success)\n    {\n      for (unsigned int i=0u; i < n; ++i)\n      {\n        BOOST_CHECK_CLOSE(x[i], problem.m_x[i], 0.1);\n      }\n    }\n\n  }\n}\n\nBOOST_AUTO_TEST_CASE(bicg_testing)\n{\n  typedef double T;\n\n  util::COOMatrix<T> A  = util::make_identity<T>(4u);\n  util::COOMatrix<T> At = util::transpose(A);\n\n  util::COOMatrix<T> M  = util::make_identity<T>(4u);\n  util::COOMatrix<T> Mt = util::transpose(M);\n\n  unsigned int    const   max_iterations = 10u;\n  T               const   tolerance      = 1e-10;\n  bool            const   verbose        = true;\n  std::vector<T>          residual;\n\n  std::vector<T> b(4u);\n\n  b[0u] = 1.0;\n  b[1u] = 2.0;\n  b[2u] = 3.0;\n  b[3u] = 4.0;\n\n  std::vector<T> x(4u, 0.0);\n\n  bool success = util::bicg(A, At, x, b, M, Mt, max_iterations, tolerance, verbose, &residual);\n\n  BOOST_CHECK(success);\n\n  BOOST_CHECK_CLOSE(x[0u], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(x[1u], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(x[2u], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(x[3u], 4.0, 0.01);\n}\n\nBOOST_AUTO_TEST_CASE(bicg_random_testing)\n{\n  typedef double T;\n\n  unsigned int    const   max_samples    = 10u;   ///< Maximum number of random problems to solve.\n  unsigned int    const   n              = 10u;   ///< Problem size\n  unsigned int    const   max_iterations = 100u;\n  T               const   tolerance      = 1e-10;\n  bool            const   verbose        = true;\n  std::vector<T>          residual;\n\n  for (unsigned int sample=0u; sample < max_samples; ++sample)\n  {\n    Problem<T> problem = make_problem<T>(n);\n\n    util::COOMatrix<T> At = util::transpose(problem.m_A);\n    util::COOMatrix<T> M  = util::make_identity<T>(n);\n    util::COOMatrix<T> Mt = util::transpose(M);\n\n    std::vector<T> x(n, 0.0);\n\n    bool success = util::bicg(\n                              problem.m_A\n                              , At\n                              , x\n                              , problem.m_b\n                              , M\n                              , Mt\n                              , max_iterations\n                              , tolerance\n                              , verbose\n                              , &residual\n                              );\n\n    BOOST_CHECK(success);\n\n    if(success)\n    {\n      for (unsigned int i=0u; i < n; ++i)\n      {\n        BOOST_CHECK_CLOSE(x[i], problem.m_x[i], 0.1);\n      }\n    }\n\n  }\n}\n\nBOOST_AUTO_TEST_CASE(cr_testing)\n{\n  typedef double T;\n\n  util::COOMatrix<T> A  = util::make_identity<T>(4u);\n  util::COOMatrix<T> M  = util::make_identity<T>(4u);\n\n  unsigned int    const   max_iterations = 10u;\n  unsigned int    const   restart       = 5u;\n  T               const   tolerance      = 1e-10;\n  bool            const   verbose        = true;\n  std::vector<T>          residual;\n\n  std::vector<T> b(4u);\n\n  b[0u] = 1.0;\n  b[1u] = 2.0;\n  b[2u] = 3.0;\n  b[3u] = 4.0;\n\n  std::vector<T> x(4u, 0.0);\n\n  bool success = util::cr(M, A, x, b, max_iterations, restart, tolerance, verbose, &residual);\n\n  BOOST_CHECK(success);\n\n  BOOST_CHECK_CLOSE(x[0u], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(x[1u], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(x[2u], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(x[3u], 4.0, 0.01);\n}\n\nBOOST_AUTO_TEST_CASE(cr_random_testing)\n{\n  typedef double T;\n\n  unsigned int    const   max_samples    = 10u;    ///< Maximum number of random problems to solve.\n  unsigned int    const   n              = 10u;    ///< Problem size\n  unsigned int    const   max_iterations = 100u;\n  unsigned int    const   restart        = 1u;\n  T               const   tolerance      = 1e-10;\n  bool            const   verbose        = true;\n  std::vector<T>          residual;\n\n  for (unsigned int sample=0u; sample < max_samples; ++sample)\n  {\n    Problem<T> problem = make_problem<T>(n);\n\n    util::COOMatrix<T> M  = util::make_identity<T>(n);\n\n    std::vector<T> x(n, 0.0);\n\n    bool success = util::cr(\n                             M\n                             , problem.m_A\n                             , x\n                             , problem.m_b\n                             , max_iterations\n                             , restart\n                             , tolerance\n                             , verbose\n                             , &residual\n                             );\n\n    BOOST_CHECK(success);\n\n    if(success)\n    {\n      for (unsigned int i=0u; i < n; ++i)\n      {\n        BOOST_CHECK_CLOSE(x[i], problem.m_x[i], 0.1);\n      }\n    }\n\n  }\n}\n\nBOOST_AUTO_TEST_CASE(bicgstab_testing)\n{\n  typedef double T;\n\n  util::COOMatrix<T> A  = util::make_identity<T>(4u);\n  util::COOMatrix<T> M  = util::make_identity<T>(4u);\n\n  unsigned int    const   max_iterations = 10u;\n  T               const   tolerance      = 1e-10;\n  bool            const   verbose        = true;\n  std::vector<T>          residual;\n\n  std::vector<T> b(4u);\n\n  b[0u] = 1.0;\n  b[1u] = 2.0;\n  b[2u] = 3.0;\n  b[3u] = 4.0;\n\n  std::vector<T> x(4u, 0.0);\n\n  bool success = util::bicgstab(M, A, x, b, max_iterations, tolerance, verbose, &residual);\n\n  BOOST_CHECK(success);\n\n  BOOST_CHECK_CLOSE(x[0u], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(x[1u], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(x[2u], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(x[3u], 4.0, 0.01);\n}\n\nBOOST_AUTO_TEST_CASE(bicgstab_random_testing)\n{\n  typedef double T;\n\n  unsigned int    const   max_samples    = 10u;      ///< Maximum number of random problems to solve.\n  unsigned int    const   n              = 10u;      ///< Problem size\n  unsigned int    const   max_iterations = 100u;\n  T               const   tolerance      = 1e-10;\n  bool            const   verbose        = true;\n  std::vector<T>          residual;\n\n  for (unsigned int sample=0u; sample < max_samples; ++sample)\n  {\n    Problem<T> problem = make_problem<T>(n);\n\n    util::COOMatrix<T> M  = util::make_identity<T>(n);\n\n    std::vector<T> x(n, 0.0);\n\n    bool success = util::bicgstab(\n                            M\n                            , problem.m_A\n                            , x\n                            , problem.m_b\n                            , max_iterations\n                            , tolerance\n                            , verbose\n                            , &residual\n                            );\n\n    BOOST_CHECK(success);\n\n    if(success)\n    {\n      for (unsigned int i=0u; i < n; ++i)\n      {\n        BOOST_CHECK_CLOSE(x[i], problem.m_x[i], 0.1);\n      }\n    }\n\n  }\n}\n\nBOOST_AUTO_TEST_CASE(gmres_testing)\n{\n  typedef double T;\n\n  util::COOMatrix<T> A  = util::make_identity<T>(4u);\n  util::COOMatrix<T> M  = util::make_identity<T>(4u);\n\n  unsigned int    const   max_iterations = 10u;\n  unsigned int    const   restart        = 5u;\n  T               const   tolerance      = 1e-10;\n  bool            const   verbose        = true;\n  std::vector<T>          residual;\n\n  std::vector<T> b(4u);\n\n  b[0u] = 1.0;\n  b[1u] = 2.0;\n  b[2u] = 3.0;\n  b[3u] = 4.0;\n\n  std::vector<T> x(4u, 0.0);\n\n  bool success = util::gmres(M, A, x, b, max_iterations, restart, tolerance, verbose, &residual);\n\n  BOOST_CHECK(success);\n\n  BOOST_CHECK_CLOSE(x[0u], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(x[1u], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(x[2u], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(x[3u], 4.0, 0.01);\n}\n\nBOOST_AUTO_TEST_CASE(gmres_random_testing)\n{\n  typedef double T;\n\n  unsigned int    const   max_samples    = 10u;      ///< Maximum number of random problems to solve.\n  unsigned int    const   n              = 10u;      ///< Problem size\n  unsigned int    const   max_iterations = 100u;\n  unsigned int    const   restart        = 1u;\n\n  // 2015-05-08 Marek: the tolerance 1e-10 was probably a bit too much for gmres.\n  //                   It seems to have a tendency to get \"stuck\" at a certain residual value.\n  T               const   tolerance      = 1e-7;\n  bool            const   verbose        = true;\n  std::vector<T>          residual;\n\n\n  for (unsigned int sample=0u; sample < max_samples; ++sample)\n  {\n    Problem<T> problem = make_problem<T>(n);\n\n    util::COOMatrix<T> M  = util::make_identity<T>(n);\n\n    std::vector<T> x(n, 0.0);\n\n    bool success = util::gmres(\n                             M\n                             , problem.m_A\n                             , x\n                             , problem.m_b\n                             , max_iterations\n                             , restart\n                             , tolerance\n                             , verbose\n                             , &residual\n                             );\n\n    BOOST_CHECK(success);\n\n    if(success)\n    {\n      for (unsigned int i=0u; i < n; ++i)\n      {\n        BOOST_CHECK_CLOSE(x[i], problem.m_x[i], 0.1);\n      }\n    }\n\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "1e30239daf0f75fa17eaa8809dce24d1b8a3fff5", "size": 15259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GRIT/unit_tests/util_coo_solve_equation/util_coo_solve_equation.cpp", "max_stars_repo_name": "H2020-MSCA-ITN-rainbow/GRIT", "max_stars_repo_head_hexsha": "1bdfb0735515e9d462214f66b88a71aabf836d76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-28T19:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T19:57:26.000Z", "max_issues_repo_path": "GRIT/unit_tests/util_coo_solve_equation/util_coo_solve_equation.cpp", "max_issues_repo_name": "H2020-MSCA-ITN-rainbow/GRIT", "max_issues_repo_head_hexsha": "1bdfb0735515e9d462214f66b88a71aabf836d76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2018-05-06T21:08:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-11T17:59:00.000Z", "max_forks_repo_path": "GRIT/unit_tests/util_coo_solve_equation/util_coo_solve_equation.cpp", "max_forks_repo_name": "misztal/GRIT", "max_forks_repo_head_hexsha": "6850fec967c9de7c6c501f5067d021ef5288b88e", "max_forks_repo_licenses": ["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.6510500808, "max_line_length": 108, "alphanum_fraction": 0.5246739629, "num_tokens": 4324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.5338693970719187}}
{"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/**\n * @file fft.cpp - computing the canonical embedding and related norms\n **/\n#include <complex>\n#include <cmath>\n#include <numeric> // std::accumulate\n#include <NTL/BasicThreadPool.h>\n#include \"NumbTh.h\"\n#include \"timing.h\"\n#include \"norms.h\"\n#include \"PAlgebra.h\"\nNTL_CLIENT\n\nconst double pi = 4 * std::atan(1);\n\n#ifdef FFT_ARMA\n#warning \"canonicalEmbedding implemented via Armadillo\"\n#include <armadillo>\nvoid convert(zzX& to, const arma::vec& from)\n{\n  to.SetLength(from.size());\n  NTL_EXEC_RANGE(to.length(), first, last)\n  for (long i=first; i<last; i++)\n    to[i] = std::round(from[i]);\n  NTL_EXEC_RANGE_END\n}\n\nvoid convert(arma::vec& to, const zzX& from)\n{\n  to.resize(from.length());\n  NTL_EXEC_RANGE(from.length(), first, last)\n  for (long i=first; i<last; i++)\n    to[i] = from[i];\n  NTL_EXEC_RANGE_END\n}\n\nvoid convert(arma::vec& to, const ZZX& from)\n{\n  to.resize(from.rep.length());\n  NTL_EXEC_RANGE(from.rep.length(), first, last)\n  for (long i=first; i<last; i++) {\n    double x = conv<double>(from[i]);\n    to[i] = x;\n  }\n  NTL_EXEC_RANGE_END\n}\n\n#if 0\n\n//======================\n\nnamespace arma {\n\n  template<> \n  struct is_supported_elem_type<RR> {\n    enum {value = 1};\n  }; \n\n  template<> \n  struct is_supported_elem_type<cx_RR> {\n    enum {value = 1};\n  }; \n\n  template<> \n  struct is_real<RR> {\n    enum {value = 1};\n  }; \n\n}\n\n\nvoid convert(zzX& to, const arma::Col<RR>& from)\n{\n  to.SetLength(from.size());\n  for (long i: range(to.length()))\n    to[i] = conv<long>(RoundToZZ(from[i]));\n}\n\nvoid convert(arma::Col<RR>& to, const zzX& from)\n{\n  to.resize(from.length());\n  for (long i: range(from.length()))\n    to[i] = from[i];\n}\n\nvoid convert(arma::Col<RR>& to, const ZZX& from)\n{\n  to.resize(from.rep.length());\n  for (long i: range(from.rep.length())) {\n    RR x = conv<RR>(from[i]);\n    to[i] = x;\n  }\n}\n\n#endif\n\n// Computing the canonical embedding. This function returns in v only\n// the first half of the entries, the others are v[phi(m)-i]=conj(v[i])\nvoid canonicalEmbedding(std::vector<cx_double>& v,\n                        const zzX& f, const PAlgebra& palg)\n{\n  FHE_TIMER_START;\n  long m = palg.getM();\n  long phimBy2 = divc(palg.getPhiM(),2);\n  arma::vec av; // convert to vector of doubles\n  convert(av, f);\n  arma::cx_vec avv = arma::fft(av,m); // compute the full FFT\n\n  v.resize(phimBy2); // the first half of Zm*\n\n  if (palg.getNSlots()==phimBy2) // order roots by the palg order\n    for (long i=0; i<phimBy2; i++)\n      v[phimBy2-i-1] = avv[palg.ith_rep(i)];\n  else                           // order roots sequentially\n    for (long i=1, idx=0; i<=m/2; i++)\n      if (palg.inZmStar(i)) v[idx++] = avv[i];\n}\n\nvoid canonicalEmbedding(std::vector<cx_double>& v,\n                        const ZZX& f, const PAlgebra& palg)\n{\n  FHE_TIMER_START;\n  long m = palg.getM();\n  long phimBy2 = divc(palg.getPhiM(),2);\n  arma::vec av; // convert to vector of doubles\n  convert(av, f);\n  arma::cx_vec avv = arma::fft(av,m); // compute the full FFT\n\n  v.resize(phimBy2); // the first half of Zm*\n\n  if (palg.getNSlots()==phimBy2) // order roots by the palg order\n    for (long i=0; i<phimBy2; i++)\n      v[phimBy2-i-1] = avv[palg.ith_rep(i)];\n  else                           // order roots sequentially\n    for (long i=1, idx=0; i<=m/2; i++)\n      if (palg.inZmStar(i)) v[idx++] = avv[i];\n}\n\n\n#if 0\nvoid canonicalEmbedding(std::vector<cx_RR>& v,\n                        const ZZX& f, const PAlgebra& palg)\n{\n  FHE_TIMER_START;\n  long m = palg.getM();\n  long phimBy2 = divc(palg.getPhiM(),2);\n  arma::Col<RR> av; // convert to vector of doubles\n  convert(av, f);\n  arma::Col<cx_RR> avv = arma::fft(av,m); // compute the full FFT\n\n  v.resize(phimBy2); // the first half of Zm*\n\n  if (palg.getNSlots()==phimBy2) // order roots by the palg order\n    for (long i=0; i<phimBy2; i++)\n      v[phimBy2-i-1] = avv[palg.ith_rep(i)];\n  else                           // order roots sequentially\n    for (long i=1, idx=0; i<=m/2; i++)\n      if (palg.inZmStar(i)) v[idx++] = avv[i];\n}\n#endif\n\n// Roughly the inverse of canonicalEmbedding, except for scaling and\n// rounding issues. Calling embedInSlots(f,v,palg,1.0,strictInverse=true)\n// after setting canonicalEmbedding(v, f, palg), is sure to recover the\n// same f, but embedInSlots(f,v,palg,1.0,strictInverse=false) may return\n// a different \"nearby\" f.\nvoid embedInSlots(zzX& f, const std::vector<cx_double>& v,\n                  const PAlgebra& palg, double scaling, bool strictInverse)\n{\n  FHE_TIMER_START;\n  long m = palg.getM();\n  long phimBy2 = divc(palg.getPhiM(),2);\n  arma::cx_vec avv(m);\n  for (auto& x: avv) x = 0.0;\n\n  if (palg.getNSlots()==phimBy2) // roots ordered by the palg order\n    for (long i=0; i<palg.getNSlots(); i++) {\n      long j = palg.ith_rep(i);\n      long ii = palg.getNSlots()-i-1;\n      if (ii < lsize(v)) {\n        avv[j] = scaling*v[ii];\n        avv[m-j] = std::conj(avv[j]);\n      }\n    }\n  else                           // roots ordered sequentially\n    for (long i=1, idx=0; i<=m/2 && idx<lsize(v); i++) {\n      if (palg.inZmStar(i)) {\n        avv[i] = scaling*v[idx++];\n        avv[m-i] = std::conj(avv[i]);\n      }\n    }\n  arma::vec av = arma::real(arma::ifft(avv,m)); // compute the inverse FFT\n\n  // If v was obtained by canonicalEmbedding(v,f,palg,1.0) then we have\n  // the guarantee that m*av is an integral polynomial, and moreover\n  // m*av mod Phi_m(x) is in m*Z[X].\n  if (strictInverse) av *= m; // scale up by m\n  convert(f, av);    // round to an integer polynomial\n  reduceModPhimX(f, palg);\n  if (strictInverse) f /= m;  // scale down by m\n  normalize(f);\n}\n#else\n#ifdef FFT_NATIVE\n#warning \"canonicalEmbedding implemented via slow DFT, expect very slow key-generation\"\n// An extremely lame implementation of the canonical embedding\n\n// evaluate poly(x) using Horner's rule\ncx_double complexEvalPoly(const zzX& poly, const cx_double& x)\n{\n  if (lsize(poly)<=0) return cx_double(0.0,0.0);\n  cx_double res(double(poly[0]), 0.0);\n  for (long i=1; i<lsize(poly); i++) {\n    res *= x;\n    res += cx_double(double(poly[i]));\n  }\n  return res;\n}\n\nvoid canonicalEmbedding(std::vector<cx_double>& v, const zzX& f, const PAlgebra& palg)\n{\n  FHE_TIMER_START;\n  long m = palg.getM();\n  long phimBy2 = divc(palg.getPhiM(),2);\n  vector<long> zmstar(phimBy2); // the first half of Zm*\n\n  if (palg.getNSlots()==phimBy2) // order roots by the palg order\n    for (long i=0; i<phimBy2; i++)\n      zmstar[phimBy2-i-1] = palg.ith_rep(i);\n  else                           // order roots sequentially\n    for (long i=1, idx=0; i<=m/2; i++)\n      if (palg.inZmStar(i)) zmstar[idx++] = i;\n\n  v.resize(phimBy2);\n  NTL_EXEC_RANGE(phimBy2, first, last)\n  for (long i=first; i < last; ++i) {\n    auto rou = std::polar<double>(1.0, -(2*pi*zmstar[i])/m); // root of unity\n    v[i] = complexEvalPoly(f,rou);\n  }\n  NTL_EXEC_RANGE_END\n  FHE_TIMER_STOP;\n}\n\n// evaluate poly(x) using Horner's rule\n// FIXME: this is actually evaluating the reverse polynomial\ncx_double complexEvalPoly(const Vec<double>& poly, const cx_double& x)\n{\n  if (poly.length()<=0) return cx_double(0.0,0.0);\n  cx_double res(poly[0], 0.0);\n  for (long i: range(1, poly.length())) {\n    res *= x;\n    res += cx_double(poly[i]);\n  }\n  return res;\n}\n\nvoid canonicalEmbedding(std::vector<cx_double>& v, const ZZX& f, const PAlgebra& palg)\n{\n  FHE_TIMER_START;\n  long m = palg.getM();\n  long phimBy2 = divc(palg.getPhiM(),2);\n  vector<long> zmstar(phimBy2); // the first half of Zm*\n\n  Vec<double> ff;\n  conv(ff, f.rep);\n\n  if (palg.getNSlots()==phimBy2) // order roots by the palg order\n    for (long i=0; i<phimBy2; i++)\n      zmstar[phimBy2-i-1] = palg.ith_rep(i);\n  else                           // order roots sequentially\n    for (long i=1, idx=0; i<=m/2; i++)\n      if (palg.inZmStar(i)) zmstar[idx++] = i;\n\n  v.resize(phimBy2);\n  NTL_EXEC_RANGE(phimBy2, first, last)\n  for (long i=first; i < last; ++i) {\n    auto rou = std::polar<double>(1.0, -(2*pi*zmstar[i])/m); // root of unity\n    v[i] = complexEvalPoly(ff,rou);\n  }\n  NTL_EXEC_RANGE_END\n  FHE_TIMER_STOP;\n}\n\nvoid embedInSlots(zzX& f, const std::vector<cx_double>& v,\n                  const PAlgebra& palg, double scaling, bool strictInverse)\n{\n  NTL::Error(\"embedInSlots not implemented\\n\");\n}\n#endif // ifdef FFT_NATIVE\n#endif // ifdef FFT_ARMA\n", "meta": {"hexsha": "1ddbaa4d58ba87318e73d3650301499f9ce30e17", "size": 8900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fft.cpp", "max_stars_repo_name": "usafchn/DiPSI", "max_stars_repo_head_hexsha": "bb834532df3ae5b6ebc963aac6b3a43d9b31c830", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-01-29T09:29:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T13:32:07.000Z", "max_issues_repo_path": "src/fft.cpp", "max_issues_repo_name": "usafchn/DiPSI", "max_issues_repo_head_hexsha": "bb834532df3ae5b6ebc963aac6b3a43d9b31c830", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-29T10:01:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-26T02:38:01.000Z", "max_forks_repo_path": "src/fft.cpp", "max_forks_repo_name": "usafchn/DiPSI", "max_forks_repo_head_hexsha": "bb834532df3ae5b6ebc963aac6b3a43d9b31c830", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-01-30T08:15:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T12:21:00.000Z", "avg_line_length": 29.4701986755, "max_line_length": 87, "alphanum_fraction": 0.6284269663, "num_tokens": 2801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5338693922868918}}
{"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\ntypedef OpenTissue::spline::NUBSpline<knot_container, point_container>                NUBSpline;\r\n\r\nknot_container init_knots(int const & k, int const & M)\r\n{\r\n  int m = M - 1;\r\n  int const n = m-k;\r\n\r\n  knot_container U;\r\n\r\n  double knot_value = 0.0;\r\n  int i = 0;\r\n  for(;i<k;++i)\r\n   U.push_back(knot_value);\r\n\r\n  for(;i<=n;++i)\r\n  {\r\n    knot_value += 1.0;\r\n     U.push_back(knot_value);\r\n  }\r\n  knot_value += 1.0;\r\n  for(;i<M;++i)\r\n   U.push_back(knot_value);\r\n  return U;\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_spline_compute_knot_span);\r\n\r\nBOOST_AUTO_TEST_CASE(test_compute_knot_span)\r\n{\r\n  // Create knot vector: U = 0 0 0 1 2 3 4 5 5 5\r\n  knot_container U = init_knots(3,10);\r\n  {\r\n    double u = -0.5;\r\n    int idx = OpenTissue::spline::detail::compute_knot_span(u,3,U);\r\n    BOOST_CHECK( idx == 2 );\r\n  }\r\n  {\r\n    double u = 0.0;\r\n    int idx = OpenTissue::spline::detail::compute_knot_span(u,3,U);\r\n    BOOST_CHECK( idx == 2 );\r\n  }\r\n  {\r\n    double u = 0.5;\r\n    int idx = OpenTissue::spline::detail::compute_knot_span(u,3,U);\r\n    BOOST_CHECK( idx == 2 );\r\n  }\r\n  {\r\n    double u = 1.0;\r\n    int idx = OpenTissue::spline::detail::compute_knot_span(u,3,U);\r\n    BOOST_CHECK( idx == 3 );\r\n  }\r\n  {\r\n    double u = 1.5;\r\n    int idx = OpenTissue::spline::detail::compute_knot_span(u,3,U);\r\n    BOOST_CHECK( idx == 3 );\r\n  }\r\n  {\r\n    double u = 2.0;\r\n    int idx = OpenTissue::spline::detail::compute_knot_span(u,3,U);\r\n    BOOST_CHECK( idx == 4 );\r\n  }\r\n  {\r\n    double u = 2.5;\r\n    int idx = OpenTissue::spline::detail::compute_knot_span(u,3,U);\r\n    BOOST_CHECK( idx == 4 );\r\n  }\r\n  {\r\n    double u = 3.0;\r\n    int idx = OpenTissue::spline::detail::compute_knot_span(u,3,U);\r\n    BOOST_CHECK( idx == 5 );\r\n  }\r\n  {\r\n    double u = 3.5;\r\n    int idx = OpenTissue::spline::detail::compute_knot_span(u,3,U);\r\n    BOOST_CHECK( idx == 5 );\r\n  }\r\n  {\r\n    double u = 4.0;\r\n    int idx = OpenTissue::spline::detail::compute_knot_span(u,3,U);\r\n    BOOST_CHECK( idx == 6 );\r\n  }\r\n  {\r\n    double u = 4.5;\r\n    int idx = OpenTissue::spline::detail::compute_knot_span(u,3,U);\r\n    BOOST_CHECK( idx == 6 );\r\n  }\r\n  {\r\n    double u = 5.0;\r\n    int idx = OpenTissue::spline::detail::compute_knot_span(u,3,U);\r\n    BOOST_CHECK( idx == 6 );\r\n  }\r\n  {\r\n    double u = 5.5;\r\n    int idx = OpenTissue::spline::detail::compute_knot_span(u,3,U);\r\n    BOOST_CHECK( idx == 6 );\r\n  }\r\n  // Illegal order\r\n  {\r\n    double u = 2.5;\r\n    BOOST_CHECK_THROW( OpenTissue::spline::detail::compute_knot_span(u,0,U), std::invalid_argument );\r\n  }\r\n  // Too few element in U\r\n  {\r\n    double u = 2.5;\r\n    BOOST_CHECK_THROW( OpenTissue::spline::detail::compute_knot_span(u,6,U), std::invalid_argument );\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "a1b5e16c0b3b9910d1e2e5505b22f646c75899d4", "size": 3624, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/spline/compute_knot_span/src/unit_compute_knot_span.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_knot_span/src/unit_compute_knot_span.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_knot_span/src/unit_compute_knot_span.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.3125, "max_line_length": 103, "alphanum_fraction": 0.5932671082, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5338693875018649}}
{"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 *    References\n *      Burden, R.L., Faires, J.D. Numerical Analysis, 7th Edition, Books/Cole, 2001.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <cmath>\n#include <limits>\n#include <map>\n\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/Statistics/simpleLinearRegression.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_simple_linear_regression )\n\n//! Test if simple linear regression method computes fit correctly.\nBOOST_AUTO_TEST_CASE( testSimpleLinearRegressionBF )\n{\n    // Test 1: Test implementation of simple linear regression method against benchmark data from\n    //         pg. 487, example 1 of (Burden and Faires, 2001). Standard deviations were benchmarked\n    //         using MATLAB's lscov() function.\n\n    // Benchmark data.\n    std::map< double, double > benchmarkInputData;\n    benchmarkInputData[ 1.0 ] = 1.3;\n    benchmarkInputData[ 2.0 ] = 3.5;\n    benchmarkInputData[ 3.0 ] = 4.2;\n    benchmarkInputData[ 4.0 ] = 5.0;\n    benchmarkInputData[ 5.0 ] = 7.0;\n    benchmarkInputData[ 6.0 ] = 8.8;\n    benchmarkInputData[ 7.0 ] = 10.1;\n    benchmarkInputData[ 8.0 ] = 12.5;\n    benchmarkInputData[ 9.0 ] = 13.0;\n    benchmarkInputData[ 10.0 ] = 15.6;\n\n    // Expected coefficients of linear fit.\n    const double expectedCoefficientOfConstantTerm = -0.359999999999999999;\n    const double expectedCoefficientOfLinearTerm = 1.5381818181818181818;\n\n    // Expected standard deviations of fit coefficients.\n    const double expectedStandardDeviationOfCoefficientOfConstantTerm = 0.369832066721825;\n    const double expectedStandardDeviationOfCoefficientOfLinearTerm = 0.059603834439483;\n\n    // Expected chi-squared value.\n    const double expectedChiSquared = 2.344727272727272;\n\n    // Declare simple linear regression object and set input data.\n    statistics::SimpleLinearRegression simpleLinearRegression( benchmarkInputData );\n\n    // Compute linear fit.\n    simpleLinearRegression.computeFit( );\n\n    // Check that computed coefficient of constant term matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( expectedCoefficientOfConstantTerm,\n                                simpleLinearRegression.getCoefficientOfConstantTerm( ),\n                                1.0e-14 );\n\n    // Check that computed coefficient of linear term matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( expectedCoefficientOfLinearTerm,\n                                simpleLinearRegression.getCoefficientOfLinearTerm( ),\n                                1.0e-15 );\n\n    // Compute linear fit errors.\n    simpleLinearRegression.computeFitErrors( );\n\n    // Check that computed standard deviation of coefficient of constant term matches expected\n    // value.\n    BOOST_CHECK_CLOSE_FRACTION( expectedStandardDeviationOfCoefficientOfConstantTerm,\n                                simpleLinearRegression\n                                .getStandardDeviationOfCoefficientOfConstantTerm( ),\n                                1.0e-13 );\n\n    // Check that computed standard deviation of coefficient of linear term matches expected\n    // value.\n    BOOST_CHECK_CLOSE_FRACTION( expectedStandardDeviationOfCoefficientOfLinearTerm,\n                                simpleLinearRegression\n                                .getStandardDeviationOfCoefficientOfLinearTerm( ),\n                                1.0e-13 );\n\n    // Check that computed chi-squared fit matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( expectedChiSquared,\n                                simpleLinearRegression.getChiSquared( ),\n                                1.0e-15 );\n}\n\nBOOST_AUTO_TEST_CASE( testSimpleLinearRegressionHorizontal )\n{\n    // Test 2: Test implementation of simple linear regression method in case of sample points\n    // coinciding with the x-axis.\n\n    std::map< double, double > benchmarkInputData;\n    benchmarkInputData[ 1.0 ] = 0.0;\n    benchmarkInputData[ 2.0 ] = 0.0;\n    benchmarkInputData[ 3.0 ] = 0.0;\n    benchmarkInputData[ 4.0 ] = 0.0;\n    benchmarkInputData[ 5.0 ] = 0.0;\n    benchmarkInputData[ 6.0 ] = 0.0;\n    benchmarkInputData[ 7.0 ] = 0.0;\n    benchmarkInputData[ 8.0 ] = 0.0;\n    benchmarkInputData[ 9.0 ] = 0.0;\n    benchmarkInputData[ 10.0 ] = 0.0;\n\n    // Declare simple linear regression object and set input data.\n    statistics::SimpleLinearRegression simpleLinearRegression( benchmarkInputData );\n\n    // Compute linear fit.\n    simpleLinearRegression.computeFit( );\n\n    // Check that computed coefficient of constant term is zero.\n    BOOST_CHECK_SMALL( simpleLinearRegression.getCoefficientOfConstantTerm( ),\n                       std::numeric_limits< double >::min( ) );\n\n    // Check that computed coefficient of linear term matches is zero.\n    BOOST_CHECK_SMALL( simpleLinearRegression.getCoefficientOfLinearTerm( ),\n                       std::numeric_limits< double >::min( ) );\n\n    // Compute linear fit errors.\n    simpleLinearRegression.computeFitErrors( );\n\n    // Check that computed standard deviation of coefficient of constant term is zero.\n    BOOST_CHECK_SMALL( simpleLinearRegression.getStandardDeviationOfCoefficientOfConstantTerm( ),\n                       std::numeric_limits< double >::min( ) );\n\n\n    // Check that computed standard deviation of coefficient of linear term is zero.\n    BOOST_CHECK_SMALL( simpleLinearRegression.getStandardDeviationOfCoefficientOfLinearTerm( ),\n                       std::numeric_limits< double >::min( ) );\n\n    // Check that computed chi-squared fit is zero.\n    BOOST_CHECK_SMALL( simpleLinearRegression.getChiSquared( ),\n                       std::numeric_limits< double >::min( ) );\n}\n\nBOOST_AUTO_TEST_CASE( testSimpleLinearRegressionVertical )\n{\n    // Test 3: Test implementation of simple linear regression method in case of sample points\n    // coinciding with the y-axis.\n\n    std::map< double, double > benchmarkInputData;\n    benchmarkInputData[ 0.0 ] = 1.3;\n    benchmarkInputData[ 0.0 ] = 3.5;\n    benchmarkInputData[ 0.0 ] = 4.2;\n    benchmarkInputData[ 0.0 ] = 5.0;\n    benchmarkInputData[ 0.0 ] = 7.0;\n    benchmarkInputData[ 0.0 ] = 8.8;\n    benchmarkInputData[ 0.0 ] = 10.1;\n    benchmarkInputData[ 0.0 ] = 12.5;\n    benchmarkInputData[ 0.0 ] = 13.0;\n    benchmarkInputData[ 0.0 ] = 15.6;\n\n    // Declare simple linear regression object and set input data.\n    statistics::SimpleLinearRegression simpleLinearRegression( benchmarkInputData );\n\n    // Compute linear fit.\n    simpleLinearRegression.computeFit( );\n\n    // Check that computed coefficient of constant term matches expected value.\n    BOOST_CHECK( boost::math::isnan( simpleLinearRegression.getCoefficientOfConstantTerm( ) ) );\n\n    // Check that computed coefficient of linear term matches expected value.\n    BOOST_CHECK( boost::math::isnan( simpleLinearRegression.getCoefficientOfLinearTerm( ) ) );\n\n    // Compute linear fit errors.\n    simpleLinearRegression.computeFitErrors( );\n\n    // Check that computed standard deviation of coefficient of constant term matches expected\n    // value.\n    BOOST_CHECK( boost::math::isnan( simpleLinearRegression\n                             .getStandardDeviationOfCoefficientOfConstantTerm( ) ) );\n\n    // Check that computed standard deviation of coefficient of linear term matches expected\n    // value.\n    BOOST_CHECK( boost::math::isnan(simpleLinearRegression\n                            .getStandardDeviationOfCoefficientOfLinearTerm( ) ) );\n\n    // Check that computed chi-squared fit matches expected value.\n    BOOST_CHECK( boost::math::isnan(simpleLinearRegression.getChiSquared( ) ) );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "6d0397d0181617fa4199c359649930bfd9e49943", "size": 8154, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/Statistics/UnitTests/unitTestSimpleLinearRegression.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/Mathematics/Statistics/UnitTests/unitTestSimpleLinearRegression.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/Mathematics/Statistics/UnitTests/unitTestSimpleLinearRegression.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": 40.3663366337, "max_line_length": 100, "alphanum_fraction": 0.6911945058, "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.5338576308017381}}
{"text": "#include <catch2/catch.hpp>\n\n#include <Eigen/Dense>\n\n#include <cannon/ml/rls.hpp>\n#include <cannon/log/registry.hpp>\n#include <cannon/math/nearly_equal.hpp>\n\nusing namespace Eigen;\n\nusing namespace cannon::ml;\nusing namespace cannon::log;\nusing namespace cannon::math;\n\nTEST_CASE(\"RLS\", \"[ml]\") {\n  // Basic correctness\n  RLSFilter f(1, 1);\n\n  VectorXd xs = VectorXd::LinSpaced(10, 0.0, 1.0);\n  VectorXd ys = 5.0 * xs;\n\n  log_info(\"xs is\", xs, \"ys is\", ys);\n\n  for (int i = 0; i < 10; i++) {\n    VectorXd tmp_x(1);\n    tmp_x << xs[i];\n    VectorXd tmp_y(1);\n    tmp_y << ys[i];\n    f.process_datum(tmp_x, tmp_y);\n  }\n\n  for (int i = 0; i < 10; i++) {\n    VectorXd tmp_x(1);\n    tmp_x << xs[i];\n    VectorXd tmp_y(1);\n    tmp_y << ys[i];\n    log_info(\"Predicted\", f.predict(tmp_x), \"for actual\", tmp_y);\n    REQUIRE((f.predict(tmp_x) - tmp_y).norm() < 0.01);\n  }\n\n  f.reset();\n  MatrixXd t;\n  VectorXd i;\n  std::tie(t, i) = f.get_identified_mats();\n\n  REQUIRE(t(0,0) == 0.0);\n  REQUIRE(i[0] == 0.0);\n}\n", "meta": {"hexsha": "f99e907d6c85aba85ab48c92dd1268c84f318df6", "size": 1001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cannon/ml/rls.test.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": "cannon/ml/rls.test.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": "cannon/ml/rls.test.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": 20.4285714286, "max_line_length": 65, "alphanum_fraction": 0.6013986014, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5338576197805069}}
{"text": "//\n//  ShamirGenerator.cpp\n//  edgeRuntime\n//\n//  Created by Abdelrahaman Aly on 20/11/13.\n//  Copyright (c) 2013 Abdelrahaman Aly. All rights reserved.\n//\n\n//Generic Headers\n#include <iostream>\n\n//Library Headers\n#include <NTL/ZZ_p.h>\n#include <NTL/ZZ.h>\n\n//Custom Headers\n#include \"List.h\"\n#include \"Constants.h\"\n#include \"StandardPlayer.h\"\n#include \"StandardShare.h\"\n#include \"ShamirGenerator.h\"\n\nusing namespace NTL;\nnamespace ShareGenerators\n{\n    //Method implementation of ShamirGenerator\n    \n    //Constructor\n    ShareGenerators::ShamirGenerator::ShamirGenerator(Players::StandardPlayer * player, long p)\n    {\n        //Initialize the Random number generator's seed using the system clocks\n        srand((unsigned)time(0));\n        //Initialize variables\n        player_=player;\n        this->p_=p;\n    };\n    \n    //Destructor\n    ShareGenerators::ShamirGenerator::~ShamirGenerator(){\n    \n    };\n    \n    //generate the shares\n    int ShamirGenerator::generateShares(long secret, int players, Utils::List<Shares::StandardShare> *list)\n    {\n        //Gets the slope for the equation randomically\n        ZZ_p slope= conv<ZZ_p>(rand()% this->p_-1);\n        //TODO: The process to obtain the shares should be based on the T-1 paradigm.\n        // hence the construction of the shares will depend on the number of players. there is a formula to do that to build polinomials of n deegree.\n        for (ZZ i=conv<ZZ>(0); i< players;i++)\n        {\n            //creates the share TODO: take the process to the constructor\n            Shares::StandardShare * aux =new Shares::StandardShare();\n            \n            aux->setPlayerId(player_->getPlayer());            \n            aux->setValue(conv<long>(slope*(conv<ZZ_p>(i)+ conv<ZZ_p>(1)) +conv<ZZ_p>(secret) ));\n\n            list->add(aux);\n            \n        } \n       \n        return 1;\n            \n    };\n    //generates the multiplication Regenerations\n     int ShamirGenerator::multiplicationRegeneration(Shares::StandardShare * share, int players,Utils::List<Shares::StandardShare> * list)\n    {\n        //TODO: Add modulus operation that is why is here\n        //TODO: modify this to make it authomatic in the number of players maybe slower though\n        ZZ_p result=3*(conv<ZZ_p>(list->get(0)->getValue())) -3*conv<ZZ_p>((list->get(1)->getValue()))+conv<ZZ_p>((list->get(2)->getValue()));\n        long value= conv<long>(result);\n        share->setValue(value);\n        return  1;\n    };\n\n}", "meta": {"hexsha": "9472d397d8daa930fad2f29d4355d393a9df3f04", "size": 2463, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "edgeRuntime/ShamirGenerator.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/ShamirGenerator.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/ShamirGenerator.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": 32.4078947368, "max_line_length": 150, "alphanum_fraction": 0.6362159968, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5338576144768301}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"testing_functions.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n// This function checks the equality of two doubles to make sure they are within some epsilon\n// It will output a 0 or a 1. \n// 0 means not equal\n// 1 means equal\nbool isEqualDouble(double a, double b, double epsilon) {   // Works as intended. 2021/11/14\n    return abs(a - b) <= epsilon;\n} // Tested. Works correctly. 2021/11/14\n\n\n// This function checks the equality of two 1D arrays of doubles to make sure they are within some epsilon\n// It will output a same size array of booleans\n// 0 means not equal\n// 1 means equal\nArray<bool,Dynamic,1> isEqualArray1D(ArrayXd &a, ArrayXd &b, double epsilon) {\n    // Get the size of a\n    // This function assumes a and b have the same number of elements\n    int N = a.size();\n    \n    // Initialize boolean array\n    Array<bool,Dynamic,1> testEquality(N);\n\n    // Iterate through entire array\n    // Use isEqualDouble function to determine if each individual element is equal in the double sense\n    for (int i = 0; i < N; i++){\n        testEquality(i) = isEqualDouble( a(i), b(i), epsilon );\n    }\n    return testEquality;\n} // Tested. Works correctly. 2021/11/16\n\n\n// This function checks the equality of two 2D arrays of doubles to make sure they are within some epsilon\n// It will output a same size array of booleans\n// 0 means not equal\n// 1 means equal\nArray<bool,Dynamic,Dynamic> isEqualArray2D(ArrayXXd &a, ArrayXXd &b, double epsilon) {\n    // Get the size of a\n    // This function assumes a and b have the same number of elements\n    int NR = a.rows();\n    int NC = a.cols();\n    \n    // Initialize boolean array\n    Array<bool,Dynamic,Dynamic> testEquality(NR,NC);\n\n    // Iterate through entire array\n    // Use isEqualDouble function to determine if each individual element is equal in the double sense\n    for (int i = 0; i < NR; i++){\n        for (int j = 0; j < NC; j++){\n            testEquality(i,j) = isEqualDouble( a(i,j), b(i,j), epsilon );\n        }        \n    }\n    return testEquality;\n} // Tested. Works correctly. 2021/11/16\n\n\n// This function checks the equality of two 1D arrays of 1D arrays of doubles to make sure they are within some epsilon\n// It will output a same size array of arrays of booleans\n// 0 means not equal\n// 1 means equal\nArray<Array<bool,Dynamic,1>, 3, 1> isEqualArray1D_of_Array1D(Array<ArrayXd, 3, 1> &a, Array<ArrayXd, 3, 1> &b, double epsilon) {\n    // This function assumes a and b have the same number of elements for each internal array    \n\n    // Initialize the boolean array of arrays     \n    Array<Array<bool,Dynamic,1>, 3, 1> testEquality;\n\n    // We know that these arrays have a size of 3. \n    // Iterate through top array\n    for (int i = 0; i < 3; i++) {\n        // Can use the isEqualArray1D function for the internal arrays\n        testEquality(i) = isEqualArray1D(a(i), b(i), epsilon);\n    }\n    return testEquality;\n} // Tested. Works correctly. 2021/11/21\n", "meta": {"hexsha": "d02bbe2f11df7a8186ca8b505f606575be4c3d4d", "size": 2995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FVM_1D/main/testing_functions.cpp", "max_stars_repo_name": "Aquadorf/computational-skolar", "max_stars_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FVM_1D/main/testing_functions.cpp", "max_issues_repo_name": "Aquadorf/computational-skolar", "max_issues_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FVM_1D/main/testing_functions.cpp", "max_forks_repo_name": "Aquadorf/computational-skolar", "max_forks_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4375, "max_line_length": 128, "alphanum_fraction": 0.6767946578, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.8333245973817159, "lm_q1q2_score": 0.5338576043676408}}
{"text": "/**\n * @file\n * @brief NPDE homework ConvBLFMatrixProvider\n * @author Ralf Hiptmair\n * @date May 2021\n * @copyright Developed at SAM, ETH Zurich\n */\n\n#include \"../convblfmatrixprovider.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <iostream>\n\nnamespace cblfdemo::test {\n\nTEST(ConvBLFMatrixProvider, Test) {\n  /* Macros available in the Google test framework:\n     EXPECT_EQ(x,y), EXPECT_NE(x,y), EXPECT_LT(x,y), EXPECT_LE(x,y),\n     EXPECT_GT(x,y), EXPECT_GE(x,y) EXPECT_STREQ(x,y), EXPECT_STRNE(x,y) -> for\n     C-strings only ! EXPECT_NEAR(x,y,abs_tol) All testing macros can output a\n     message by a trailing << ....\n   */\n  // Obtain a purely triangular mesh from the collection of LehrFEM++'s\n  // built-in meshes\n  std::shared_ptr<lf::mesh::Mesh> mesh_p{\n      lf::mesh::test_utils::GenerateHybrid2DTestMesh(3)};\n  // vectors for testing\n  const Eigen::Vector2d a(1.0, 2.0);\n  const Eigen::Vector2d b(3.0, 2.0);\n  // Run test computation\n  const double itg = cblfdemo::testCDBLF(mesh_p, a, b);\n  EXPECT_NEAR(itg, 63, 1E-6);\n}\n}  // namespace cblfdemo::test\n", "meta": {"hexsha": "a53ad397f9ec261201317c7b5200af87c21bb2b6", "size": 1080, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/ConvBLFMatrixProvider/mastersolution/test/convblfmatrixprovider_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": "developers/ConvBLFMatrixProvider/mastersolution/test/convblfmatrixprovider_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": "developers/ConvBLFMatrixProvider/mastersolution/test/convblfmatrixprovider_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": 29.1891891892, "max_line_length": 79, "alphanum_fraction": 0.6851851852, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5338057488583575}}
{"text": "//\n//  Meshrectangular.hpp\n//  hybrid_fem_bie\n//\n//  Created by Max on 2/5/18.\n//\n//\n\n#ifndef Meshrectangular_hpp\n#define Meshrectangular_hpp\n\n#include <stdio.h>\n#include <Eigen/Eigen>\n#include \"share_header.hpp\"\nusing namespace Eigen;\n\nvoid Meshrectangular(double x_min, double x_max, double y_min, double y_max, double dx ,double dy ,int nx, int ny , MatrixXd &Node, MatrixXi_rm &Element);\n\n\n#endif /* Meshrectangular_hpp */\n", "meta": {"hexsha": "f47a41bbbf240bc90c636e7897039b2d7c61b994", "size": 427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/fem/Meshrectangular.hpp", "max_stars_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_stars_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T19:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:12:57.000Z", "max_issues_repo_path": "src/fem/Meshrectangular.hpp", "max_issues_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_issues_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fem/Meshrectangular.hpp", "max_forks_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_forks_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-07T07:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T07:23:58.000Z", "avg_line_length": 20.3333333333, "max_line_length": 154, "alphanum_fraction": 0.7353629977, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5338057488583575}}
{"text": "// Author(s): Wieger Wesselink\n// Copyright: see the accompanying file COPYING or copy at\n// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n/// \\file normalize_test.cpp\n/// \\brief Test for normalization functions.\n\n#include <functional>\n#include <iostream>\n#include <boost/test/minimal.hpp>\n#include \"mcrl2/utilities/detail/test_operation.h\"\n#include \"mcrl2/lps/specification.h\"\n#include \"mcrl2/lps/linearise.h\"\n#include \"mcrl2/modal_formula/parse.h\"\n#include \"mcrl2/pbes/pbes.h\"\n#include \"mcrl2/pbes/lps2pbes.h\"\n#include \"mcrl2/pbes/normalize.h\"\n#include \"mcrl2/pbes/parse.h\"\n#include \"mcrl2/pbes/rewriter.h\"\n#include \"mcrl2/pbes/detail/normalize_and_or.h\"\n\nusing namespace mcrl2;\nusing namespace mcrl2::pbes_system;\n\nvoid test_normalize1()\n{\n  pbes_expression x = propositional_variable_instantiation(\"x:X\");\n  pbes_expression y = propositional_variable_instantiation(\"y:Y\");\n  pbes_expression z = propositional_variable_instantiation(\"z:Z\");\n  pbes_expression f;\n  pbes_expression f1;\n  pbes_expression f2;\n\n  f = not_(x);\n  f = not_(f); // N.B. not_(not_(x)) does not work!\n  f1 = pbes_system::normalize(f);\n  f2 = x;\n  std::cout << \"f  = \" << f  << std::endl;\n  std::cout << \"f1 = \" << f1 << std::endl;\n  std::cout << \"f2 = \" << f2 << std::endl;\n  BOOST_CHECK(f1 == f2);\n\n  f = imp(not_(x), y);\n  f1 = pbes_system::normalize(f);\n  f2 = or_(x, y);\n  std::cout << \"f  = \" << f  << std::endl;\n  std::cout << \"f1 = \" << f1 << std::endl;\n  std::cout << \"f2 = \" << f2 << std::endl;\n  BOOST_CHECK(f1 == f2);\n\n  f  = not_(and_(not_(x), not_(y)));\n  f1 = pbes_system::normalize(f);\n  f2 = or_(x, y);\n  std::cout << \"f  = \" << f << std::endl;\n  std::cout << \"f1 = \" << f1 << std::endl;\n  std::cout << \"f2 = \" << f2 << std::endl;\n  BOOST_CHECK(f1 == f2);\n\n  f  = imp(and_(not_(x), not_(y)), z);\n  f1 = pbes_system::normalize(f);\n  f2 = or_(or_(x, y), z);\n  std::cout << \"f  = \" << f << std::endl;\n  std::cout << \"f1 = \" << f1 << std::endl;\n  std::cout << \"f2 = \" << f2 << std::endl;\n  BOOST_CHECK(f1 == f2);\n\n  x = data::variable(\"x\", data::sort_bool::bool_());\n  y = data::variable(\"y\", data::sort_bool::bool_());\n  z = data::variable(\"z\", data::sort_bool::bool_());\n  const data::data_expression& x1 = atermpp::down_cast<data::data_expression>(x);\n  const data::data_expression& y1 = atermpp::down_cast<data::data_expression>(y);\n\n  f  = not_(x);\n  f1 = pbes_system::normalize(f);\n  f2 = data::sort_bool::not_(x1);\n  std::cout << \"f  = \" << f << std::endl;\n  std::cout << \"f1 = \" << f1 << std::endl;\n  std::cout << \"f2 = \" << f2 << std::endl;\n  BOOST_CHECK(f1 == f2);\n\n  f  = imp(and_(x, y), z);\n  f1 = pbes_system::normalize(f);\n  f2 = or_(or_(data::sort_bool::not_(x1), data::sort_bool::not_(y1)), z);\n  std::cout << \"f  = \" << f << std::endl;\n  std::cout << \"f1 = \" << f1 << std::endl;\n  std::cout << \"f2 = \" << f2 << std::endl;\n  BOOST_CHECK(f1 == f2);\n\n  pbes_expression T = true_();\n  pbes_expression F = false_();\n  x = pbes_expression(atermpp::aterm_appl(core::detail::function_symbol_PBESImp(), T, F));\n  y = pbes_system::normalize(x);\n  std::cout << \"x = \" << x << std::endl;\n  std::cout << \"y = \" << y << std::endl;\n\n  data::variable_list ab = { data::variable(\"s\", data::basic_sort(\"S\")) };\n  x = propositional_variable_instantiation(\"x:X\");\n  y = and_(x, imp(pbes_expression(atermpp::aterm_appl(core::detail::function_symbol_PBESAnd(), false_(), false_())), false_()));\n  z = pbes_system::normalize(y);\n  std::cout << \"y = \" << y << std::endl;\n  std::cout << \"z = \" << z << std::endl;\n}\n\nvoid test_normalize2()\n{\n  // test case from Aad Mathijssen, 2/11/2008\n  lps::specification spec=remove_stochastic_operators(lps::linearise(\"init tau + tau;\"));\n  state_formulas::state_formula formula  = state_formulas::parse_state_formula(\"nu X. [true]X\", spec);\n  bool timed = false;\n  pbes_system::pbes p = pbes_system::lps2pbes(spec, formula, timed);\n  pbes_system::normalize(p);\n}\n\nvoid test_normalize3()\n{\n  // test case from Aad Mathijssen, 1-4-2008\n  lps::specification spec=remove_stochastic_operators(lps::linearise(\n                              \"proc P = tau.P;\\n\"\n                              \"init P;        \\n\"));\n  state_formulas::state_formula formula = state_formulas::parse_state_formula(\"![true*]<true>true\", spec);\n  bool timed = false;\n  pbes_system::pbes p = pbes_system::lps2pbes(spec, formula, timed);\n  pbes_system::normalize(p);\n}\n\nconst std::string VARIABLE_SPECIFICATION =\n  \"datavar         \\n\"\n  \"  b:  Bool;     \\n\"\n  \"  b1: Bool;     \\n\"\n  \"  b2: Bool;     \\n\"\n  \"  b3: Bool;     \\n\"\n  \"                \\n\"\n  \"  n:  Nat;      \\n\"\n  \"  n1: Nat;      \\n\"\n  \"  n2: Nat;      \\n\"\n  \"  n3: Nat;      \\n\"\n  \"                \\n\"\n  \"  p:  Pos;      \\n\"\n  \"  p1: Pos;      \\n\"\n  \"  p2: Pos;      \\n\"\n  \"  p3: Pos;      \\n\"\n  \"                \\n\"\n  \"predvar         \\n\"\n  \"  X;            \\n\"\n  \"  Y: Nat;       \\n\"\n  \"  Z: Bool, Pos; \\n\"\n  ;\n\ninline\npbes_system::pbes_expression expr(const std::string& text)\n{\n  return pbes_system::parse_pbes_expression(text, VARIABLE_SPECIFICATION);\n}\n\ninline\npbes_expression parse(const std::string& expr)\n{\n  std::string var_decl =\n    \"datavar    \\n\"\n    \"  m: Nat;  \\n\"\n    \"  n: Nat;  \\n\"\n    \"           \\n\"\n    \"predvar    \\n\"\n    \"  X;       \\n\"\n    \"  Y;       \\n\"\n    \"  Z;       \\n\"\n    ;\n\n  std::string data_spec = \"\";\n  return pbes_system::parse_pbes_expression(expr, var_decl, data_spec);\n}\n\ninline\npbes_expression norm(const pbes_expression& x)\n{\n  return pbes_system::detail::normalize_and_or(x);\n}\n\nvoid test_normalize_and_or_equality(const std::string& expr1, const std::string& expr2)\n{\n  BOOST_CHECK(utilities::detail::test_operation(\n    expr1,\n    expr2,\n    parse,\n    std::equal_to<pbes_expression>(),\n    norm,\n    \"normalize_and_or\",\n    norm,\n    \"normalize_and_or\"\n  ));\n}\n\nvoid test_normalize_and_or()\n{\n  test_normalize_and_or_equality(\"X && Y\", \"Y && X\");\n  test_normalize_and_or_equality(\"X && X && Y\", \"X && Y && X\");\n  test_normalize_and_or_equality(\"X && X && Y\", \"Y && X && X\");\n}\n\nint test_main(int argc, char** argv)\n{\n  test_normalize1();\n  test_normalize2();\n  test_normalize3();\n  test_normalize_and_or();\n\n  return 0;\n}\n", "meta": {"hexsha": "fecf051f302a6649e2947a9681e13b84bdd210fb", "size": 6291, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/pbes/test/normalize_test.cpp", "max_stars_repo_name": "gijskant/mcrl2-pmc", "max_stars_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/pbes/test/normalize_test.cpp", "max_issues_repo_name": "gijskant/mcrl2-pmc", "max_issues_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/pbes/test/normalize_test.cpp", "max_forks_repo_name": "gijskant/mcrl2-pmc", "max_forks_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "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.5352112676, "max_line_length": 128, "alphanum_fraction": 0.6011762836, "num_tokens": 2073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5338057388266484}}
{"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//! \\file\r\n//!\\brief Tests round-trip for fixed_point negatable with 999 decimal digits.\r\n\r\n#define BOOST_TEST_MODULE test_negatable_round_trip_digits10_999\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/cstdint.hpp>\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/generator_iterator.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/random.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 999 decimal digits of precision.\r\n  typedef\r\n  boost::fixed_point::negatable<0,\r\n                                -3320,\r\n                                boost::fixed_point::round::nearest_even>\r\n  fixed_point_type;\r\n\r\n  BOOST_CONSTEXPR_OR_CONST std::string::size_type digits10_string_length =\r\n    ((long(std::numeric_limits<fixed_point_type>::digits) - 1L) * 301L) / 1000L;\r\n\r\n  bool round_trip(const fixed_point_type& x);\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 << std::setprecision(std::numeric_limits<fixed_point_type>::digits10)\r\n      << 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_digits10_999)\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  typedef boost::mt19937 random_generator_type;\r\n\r\n  const boost::uniform_int<boost::uint_fast8_t> uniform_bit_range(UINT8_C(0), UINT8_C(1));\r\n\r\n  boost::variate_generator<random_generator_type,\r\n                           boost::uniform_int<boost::uint_fast8_t>>\r\n  radom_bit_maker(random_generator_type(), uniform_bit_range);\r\n\r\n  boost::uint_fast32_t count = UINT32_C(0);\r\n\r\n  BOOST_CONSTEXPR_OR_CONST boost::uint_fast32_t number_of_test_cases = UINT16_C(2000);\r\n\r\n  bool b = true;\r\n\r\n  // Test random values with 999 decimal digits of precision.\r\n  for( ; ((count < number_of_test_cases) && b); ++count)\r\n  {\r\n    typedef\r\n      boost::fixed_point::detail::integer_type_helper<fixed_point_type::all_bits>::exact_unsigned_type\r\n    unsigned_integral_type;\r\n\r\n    unsigned_integral_type u(0);\r\n\r\n    for(int i = 0; i < int((-fixed_point_type::resolution - 2)); ++i)\r\n    {\r\n      u |= unsigned_integral_type(radom_bit_maker()) << i;\r\n    }\r\n\r\n    std::stringstream ss1;\r\n\r\n    ss1 << u;\r\n\r\n    std::string str(ss1.str());\r\n\r\n    str.insert(std::string::size_type(0U),\r\n               local::digits10_string_length - (std::min)(local::digits10_string_length, str.length()),\r\n               char('0'));\r\n\r\n    str.insert(std::string::size_type(0U), \"0.\");\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": "602c344e901f50ff3090264a7e87129de0763c0b", "size": 3424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_round_trip_digits10_999.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_digits10_999.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_digits10_999.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.5333333333, "max_line_length": 104, "alphanum_fraction": 0.6661799065, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.7154239957834734, "lm_q1q2_score": 0.5338057317267448}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, abs) {\n  using stan::math::abs;\n\n  double y = 2.0;\n  EXPECT_FLOAT_EQ(2.0, abs(y));\n\n  y = 128745.72;\n  EXPECT_FLOAT_EQ(128745.72, abs(y));\n\n  y = -y;\n  EXPECT_FLOAT_EQ(128745.72, abs(y));\n\n  y = -1.3;\n  EXPECT_FLOAT_EQ(1.3, abs(y));\n\n  int z = 10; // promoted to double by abs(double)\n  EXPECT_FLOAT_EQ(10.0, abs(z));\n\n}\n\nTEST(MathFunctions, abs2){\n  double yy=0;\n  yy=0;\n  EXPECT_FLOAT_EQ(0, stan::math::abs(yy));\n}\n\nTEST(MathFunctions, abs_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::abs(nan));\n}\n", "meta": {"hexsha": "fed6818f1177d11dcaeeb4679ac597f9d35c3a50", "size": 728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/abs_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/abs_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/abs_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": 19.6756756757, "max_line_length": 56, "alphanum_fraction": 0.6497252747, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5338057307494765}}
{"text": "#include <Eigen/Dense>\n#include <math.h>\n#include <optimization.h>\n\nnamespace al = alglib;\n\nclass LieMPC {\n\n  public:\n  Eigen::Matrix<double, 18, 1> x; // State vector\n  Eigen::Matrix<double, 6, 1> y;  // Output vector\n  Eigen::Vector4d u;              // Control input vector\n  Eigen::Vector4d u_lin;          // Linearization control input\n  Eigen::VectorXd Y;              // Target trajectory\n\n  private:\n  // MPC parameters\n  int _nx = 12; // Number of states\n  int _ny = 6;  // Number of outputs\n  int _nu = 4;  // Number of control inputs\n  int _np;      // Prediction steps\n  double _ts;   // Time step (s)\n\n  // Linear system Matrices\n  Eigen::Matrix<double, 12, 12> _Ac = Eigen::Matrix<double, 12, 12>::Zero(); // Continuous state matrix\n  Eigen::Matrix<double, 12, 4> _Bc = Eigen::Matrix<double, 12, 4>::Zero();   // Continuous input matrix\n  Eigen::Matrix<double, 12, 4> _Bcg;                                         // Input matrix with direct allocation\n  Eigen::Matrix<double, 12, 1> _f;                                           // Constant offset matrix\n  Eigen::Matrix<double, 12, 1> _f_t;                                         // Time-variant offset matrix\n  Eigen::Matrix<double, 12, 12> _A;                                          // Discrete state matrix\n  Eigen::Matrix<double, 12, 4> _B;                                           // Discrete input matrix\n  Eigen::Matrix<double, 6, 12> _C = Eigen::Matrix<double, 6, 12>::Zero();    // Discrete output matrix\n\n  // Misc matrix definitions\n  Eigen::Matrix<double, 4, 4> _Gamma;               // Control allocation matrix\n  Eigen::Matrix3d _I = Eigen::Matrix3d::Identity(); // 3x3 identity matrix\n  Eigen::Vector3d _1_3 = Eigen::Vector3d(0, 0, 1);  // Z-axis vector\n  Eigen::Matrix3d _J = Eigen::Matrix3d::Zero();     // Inertia matrix (kg.m^2)\n  Eigen::Matrix3d _J_inv;                           // Inverse of inertia matrix\n\n  // Partial state matrices\n  Eigen::Matrix3d _A_rv = _I;\n  Eigen::Matrix3d _A_vp;\n  Eigen::Matrix3d _A_pp;\n  Eigen::Matrix3d _A_pw = _I;\n  Eigen::Matrix3d _A_ww;\n\n  // Partial input matrices\n  Eigen::Vector3d _B_vt;\n  Eigen::Matrix3d _B_wm;\n\n  // Partial offset matrices\n  Eigen::Vector3d _f_r;\n  Eigen::Vector3d _f_v;\n  Eigen::Vector3d _f_p;\n  Eigen::Vector3d _f_p_t;\n  Eigen::Vector3d _f_w;\n\n  // MPC Matrices\n  Eigen::MatrixXd _H;\n  Eigen::VectorXd _F;\n  Eigen::MatrixXd _H_f;\n  Eigen::VectorXd _F_f;\n  Eigen::MatrixXd _G;\n  Eigen::MatrixXd _C_bar;\n  Eigen::VectorXd _dY;\n  Eigen::VectorXd _U_lin;\n\n  // Optimization variables\n  al::real_1d_array _U;             // Control input prediction\n  al::real_1d_array _U0;            // Initial control input\n  al::real_1d_array _Uc;            // Intermediate control input sequence\n  al::real_2d_array _MPC_H;         // Quadratic program H matrix\n  al::real_1d_array _MPC_F;         // Quadratic program F matrix\n  Eigen::MatrixXd _MPC_H_Eig;       // Eigen Quadratic program H matrix\n  Eigen::MatrixXd _MPC_H_Eig_Sym;   // Eigen Symmetric Quadratic program H matrix\n  Eigen::VectorXd _MPC_F_Eig;       // Eigen Quadratic program F matrixi\n  Eigen::Matrix<double, 6, 6> _q;   // Output weighting matrix\n  Eigen::Matrix<double, 4, 4> _r;   // Control input weighting matrix\n  Eigen::Matrix<double, 6, 6> _q_f; // Terminal output weighting matrix\n  Eigen::MatrixXd _Q;               // General output weighting matrix\n  Eigen::MatrixXd _R;               // General input weighting matrix\n  al::minqpstate _qpstate;          // State for Quadratic Program\n  al::minqpreport _qpreport;        // Report for QP solver\n\n  // Constraint handling\n  double _t_input;           // Time for thrust constraint\n  al::real_1d_array _u_bndl; // Lower bound on thrusts\n  al::real_1d_array _u_bndh; // Upper bound on thrusts\n  double _T_scaled;\n  double _time;\n\n  // Constants\n  double _m = 1.0;       // Mass (kg)\n  double _g = 9.81;      // Gravity (m/s)\n  double _j_xx = 0.0122; // x-axis principle moment\n  double _j_yy = 0.0126; // y-axis principle moment\n  double _j_zz = 0.0239; // z-axis principle moment\n  double _k = 1.8;       // Propeller yaw moment ratio\n  double _c = 0.166;     // Propeller thrust to moment\n  double _T_max = 7.0;   // Maximum thrust (N)\n  double _t_ramp = 0.2;  // Thrust ramp time (s)\n\n  // Calculation Variables;\n  Eigen::Matrix3d _Rotm;\n  Eigen::Vector3d _gamma;\n  Eigen::Vector4d _u_tm;\n  double _phi;\n  double _sphi;\n  Eigen::Matrix<double, 12, 12> _E;\n  Eigen::Matrix<double, 12, 12> _Ek;\n  Eigen::Matrix<double, 12, 12> _Ak;\n  Eigen::Matrix<double, 12, 4> _ABk;\n  Eigen::Matrix<double, 12, 1> _Afk;\n  Eigen::Matrix<double, 6, 6> _A_dare;\n  Eigen::Matrix<double, 6, 4> _B_dare;\n  Eigen::Matrix<double, 6, 6> _Ad;\n  Eigen::Matrix<double, 6, 6> _Adk;\n  Eigen::Matrix<double, 6, 6> _Gd;\n  Eigen::Matrix<double, 6, 6> _Gdk;\n  Eigen::Matrix<double, 6, 6> _Hd;\n  Eigen::Matrix<double, 6, 6> _Hdk = Eigen::Matrix<double, 6, 6>::Identity();\n  Eigen::Matrix<double, 6, 6> _W;\n  Eigen::Matrix<double, 6, 6> _V1;\n  Eigen::Matrix<double, 6, 6> _V2;\n\n  public:\n  // Default constructor\n  LieMPC()\n  {\n    // Set default parameter values\n    _np = 8;\n    _ts = 0.04;\n    _J(0, 0) = _j_xx;\n    _J(1, 1) = _j_yy;\n    _J(2, 2) = _j_zz;\n    _J_inv = _J.inverse();\n    _B_wm = _J_inv;\n\n    //Build control allocation matrix;\n    _Gamma << 1, 1, 1, 1,\n        -_c, _c, _c, -_c,\n        _c, -_c, _c, -_c,\n        _k, _k, -_k, -_k;\n\n    // Set default cost weights\n    Eigen::Matrix<double, 6, 1> y_weight;\n    y_weight << 1.e-2, 1.e-2, 1.e-2, 100., 100., 100.;\n    _q = y_weight.asDiagonal();\n\n    Eigen::Matrix<double, 4, 1> u_weight;\n    u_weight << 1.e-7, 1.e-7, 1.e-7, 1.e-7;\n    _r = u_weight.asDiagonal();\n\n    // Assign constant state matrix parts\n    _Ac.block(0, 3, 3, 3) = _A_rv;\n    _Ac.block(6, 9, 3, 3) = _A_pw;\n    _Bc.block(9, 1, 3, 3) = _B_wm;\n\n    // Assign output matrix parts;\n    _C.block(0, 0, 3, 3) = _I;\n    _C.block(3, 6, 3, 3) = _I;\n\n    // Set matrix sizes\n    Y.resize(12 * _np);\n    _H.resize(_nx * _np, _nu * _np);\n    _F.resize(_nx * _np);\n    _G.resize(_nx * _np, _nx);\n    _C_bar.resize(_ny * _np, _nx * _np);\n    _Q.resize(_ny * _np, _ny * _np);\n    _R.resize(_nu * _np, _nu * _np);\n    _H_f.resize(_nx, _nu * _np);\n    _F_f.resize(_nx);\n    _dY.resize(_ny * _np);\n    _U_lin.resize(_nu * _np);\n    _MPC_H_Eig.resize(_np * _nu, _np * _nu);\n    _MPC_H_Eig_Sym.resize(_np * _nu, _np * _nu);\n    _MPC_F_Eig.resize(_np * _nu);\n    _U.setlength(_np * _nu);\n    _U0.setlength(_np * _nu);\n    _Uc.setlength(_np * _nu);\n    _u_bndl.setlength(_np * _nu);\n    _u_bndh.setlength(_np * _nu);\n\n    // Initialize matrix values\n    _H = Eigen::MatrixXd::Zero(_nx * _np, _nu * _np);\n    _H_f = Eigen::MatrixXd::Zero(_nx, _nu * _np);\n    _G = Eigen::MatrixXd::Zero(_nx * _np, _nx);\n    _C_bar = Eigen::MatrixXd::Zero(_ny * _np, _nx * _np);\n    _Q = Eigen::MatrixXd::Zero(_ny * _np, _ny * _np);\n    _R = Eigen::MatrixXd::Zero(_nu * _np, _nu * _np);\n\n    // Initialize QP Solver\n    al::minqpcreate(_nu * _np, _qpstate);\n    for (int i = 0; i < _np * _nu; i++) {\n      _U0(i) = _m * _g / 4;\n    }\n    al::minqpsetscale(_qpstate, _U0);\n    al::minqpsetalgoquickqp(_qpstate, 1e-10, 1e-10, 1e-10, 100, true);\n  };\n\n  // Constructor used to specify prediction horizon, timestep, and weights\n  LieMPC(int n_p, double timestep, Eigen::MatrixXd y_weight, Eigen::MatrixXd u_weight)\n  {\n    // Fetch paramter values\n    _np = n_p;\n    _ts = timestep;\n    _q = y_weight;\n    _r = u_weight;\n    _J(0, 0) = _j_xx;\n    _J(1, 1) = _j_yy;\n    _J(2, 2) = _j_zz;\n    _J_inv = _J.inverse();\n    _B_wm = _J_inv;\n\n    //Build control allocation matrix;\n    _Gamma << 1, 1, 1, 1,\n        -_c, _c, _c, -_c,\n        _c, -_c, _c, -_c,\n        _k, _k, -_k, -_k;\n\n    // Assign constant state matrix parts\n    _Ac.block(0, 3, 3, 3) = _A_rv;\n    _Ac.block(6, 9, 3, 3) = _A_pw;\n    _Bc.block(9, 1, 3, 3) = _B_wm;\n\n    // Assign output matrix parts;\n    _C.block(0, 0, 3, 3) = _I;\n    _C.block(3, 6, 3, 3) = _I;\n\n    // Set matrix sizeis\n    Y.resize(12 * _np);\n    _H.resize(_nx * _np, _nu * _np);\n    _F.resize(_nx * _np);\n    _G.resize(_nx * _np, _nx);\n    _C_bar.resize(_ny * _np, _nx * _np);\n    _Q.resize(_ny * _np, _ny * _np);\n    _R.resize(_nu * _np, _nu * _np);\n    _H_f.resize(_nx, _nu * _np);\n    _F_f.resize(_nx);\n    _dY.resize(_ny * _np);\n    _U_lin.resize(_nu * _np);\n    _MPC_H_Eig.resize(_np * _nu, _np * _nu);\n    _MPC_H_Eig.resize(_np * _nu, _np * _nu);\n    _MPC_F_Eig.resize(_np * _nu);\n    _U.setlength(_np * _nu);\n    _u_bndl.setlength(_np * _nu);\n    _u_bndh.setlength(_np * _nu);\n\n    // Initialize matrix values\n    _H = Eigen::MatrixXd::Zero(_nx * _np, _nu * _np);\n    _H_f = Eigen::MatrixXd::Zero(_nx, _nu * _np);\n    _G = Eigen::MatrixXd::Zero(_nx * _np, _nx);\n    _C_bar = Eigen::MatrixXd::Zero(_ny * _np, _nx * _np);\n    _Q = Eigen::MatrixXd::Zero(_ny * _np, _ny * _np);\n    _R = Eigen::MatrixXd::Zero(_nu * _np, _nu * _np);\n  };\n\n  void linearize()\n  {\n    // Build rotation matrix\n    _Rotm = Eigen::Map<Eigen::Matrix3d>((x.segment(6, 9)).data()).transpose();\n\n    // Calculate forces and moments;\n    _u_tm = _Gamma * u_lin;\n\n    // Build state matrix components\n    _A_vp.noalias() = (1. / _m) * _Rotm * _cross_op(_1_3 * _u_tm(0));\n    _A_pp.noalias() = -_cross_op(x.segment(15, 3));\n    _A_ww.noalias() = _J_inv * (_cross_op(_J * x.segment(15, 3)) - (_cross_op(x.segment(15, 3)) * _J));\n\n    // Build input matrix components\n    _B_vt.noalias() = -(1. / _m) * _Rotm * _1_3;\n\n    // Build offset matrix componenets\n    _f_r = -x.segment(3, 3);\n    _f_v.noalias() = (1. / _m) * _Rotm * _1_3 * _u_tm(0) - _1_3 * _g;\n    _f_p = -x.segment(15, 3);\n    _gamma.noalias() = (-_cross_op(x.segment(15, 3)) * _J * x.segment(15, 3) + _u_tm.segment(1, 3));\n    _f_p_t.noalias() = -_J_inv * _gamma;\n    _f_w = _f_p_t;\n\n    // Build matrices\n    _Ac.block(3, 6, 3, 3) = _A_vp;\n    _Ac.block(6, 6, 3, 3) = _A_pp;\n    _Ac.block(9, 9, 3, 3) = _A_ww;\n\n    _Bc.block(3, 0, 3, 1) = _B_vt;\n    _Bcg = _Bc * _Gamma;\n\n    _f.segment(0, 3) = _f_r;\n    _f.segment(3, 3) = _f_v;\n    _f.segment(6, 3) = _f_p;\n    _f.segment(9, 3) = _f_w;\n\n    _f_t.segment(6, 3) = _f_p_t;\n  };\n\n  void discretize()\n  {\n    // Obtain discrete A and B matrices using a ZOH discretization\n    _Ek = Eigen::Matrix<double, 12, 12>::Identity();\n    _E = _Ek;\n\n    for (int i = 1; i < 16; i++) {\n      _Ek = _Ek * (_Ac * _ts) / (i + 1);\n      _E += _Ek;\n    }\n\n    _A = Eigen::Matrix<double, 12, 12>::Identity() + _E * _Ac * _ts;\n    _B = _E * _Bcg * _ts;\n\n    // Solve for terminal cost from discrete-time algebraic Ricatti equation\n    _q_f = _solve_dare(_C * _A * _C.transpose(), _C * _B, _q, _r);\n  };\n\n  void build_mpc()\n  {\n    // Build prediction matrices for MPC\n    _Ak = Eigen::MatrixXd::Identity(_nx, _nx);\n    _ABk = _B;\n    _Afk = _ts * (_f + (_ts / 2.) * _f_t);\n    _F = Eigen::VectorXd::Zero(_nx * _np);\n    _F_f = Eigen::VectorXd::Zero(_nx);\n\n    for (int i = 0; i < _np; i++) {\n\n      if (i != 0) {\n        _Ak *= _A;\n        _ABk.noalias() = _Ak * _B;\n        _Afk.noalias() = _Ak * _ts * (_f + i * (_ts / 2) * _f_t);\n      }\n\n      _C_bar.block(i * _ny, i * _nx, _ny, _nx) = _C;\n      _Q.block(i * _ny, i * _ny, _ny, _ny) = _q;\n      _R.block(i * _nu, i * _nu, _nu, _nu) = _r;\n      // _G.block(i * _nx, 0, _nx, _nx) = _Ak;\n\n      _dY.segment(i * _ny, 3) = x.segment(0, 3) - Y.segment(i * 12, 3);\n      _dY.segment(i * _ny + 3, 3) = _vee_SO3(_Rotm.transpose() * Eigen::Map<Eigen::Matrix3d>((Y.segment(i * 12 + 3, 9)).data()));\n\n      _U_lin.segment(i * _nu, _nu) = u_lin;\n\n      for (int j = 0; j + i < _np - 1; j++) {\n        _F.segment(_nx * (_np - 1 - j), _nx) += _Afk;\n        _H.block((j + i + 1) * _nx, j * _nu, _nx, _nu) = _ABk;\n      }\n\n      _H_f.block(0, (_np - i - 1) * _nu, _nx, _nu) = _ABk;\n      _F_f += _Afk;\n    }\n\n    _MPC_H_Eig.noalias() = (_C_bar * _H).transpose() * _Q * (_C_bar * _H) + (_C * _H_f).transpose() * _q_f * (_C * _H_f) + _R;\n    _MPC_H_Eig_Sym = _MPC_H_Eig + _MPC_H_Eig.transpose();\n    _MPC_F_Eig.noalias() = 2. * (_C_bar * _F - _dY).transpose() * _Q * (_C_bar * _H) + 2. * (_C * _F_f - 2. * _dY.segment((_np - 1) * _ny, _ny)).transpose() * _q_f * (_C * _H_f) - _U_lin.transpose() * _R;\n  };\n\n  void solve()\n  {\n    // Solve QP to obtain optimal control inputs\n    for (int i = 0; i < _np; i++) {\n      for (int j = 0; j < _nu; j++) {\n        _U0(i * _nu + j) = u_lin(j);\n      }\n    }\n\n    _eigen_to_al(_MPC_H_Eig_Sym, &_MPC_H);\n    _eigen_to_al(_MPC_F_Eig, &_MPC_F);\n    al::minqpsetquadraticterm(_qpstate, _MPC_H);\n    al::minqpsetlinearterm(_qpstate, _MPC_F);\n    _init_constraints();\n    _U = _U0;\n\n    for (int i = 0; i < 5; i++) {\n      al::minqpsetbc(_qpstate, _u_bndl, _u_bndh);\n      al::minqpsetstartingpoint(_qpstate, _U);\n      al::minqpoptimize(_qpstate);\n      al::minqpresults(_qpstate, _U, _qpreport);\n      for (int j = 0; j < (_np * _nu); j++) {\n        _Uc(j) = _U0(j) - _U(j);\n      }\n      _build_constraints();\n      if (_check_bounds(_U, _u_bndl, _u_bndh)) {\n        break;\n      }\n    }\n\n    u(0) = u_lin(0) - _U(0);\n    u(1) = u_lin(1) - _U(1);\n    u(2) = u_lin(2) - _U(2);\n    u(3) = u_lin(3) - _U(3);\n  };\n\n  private:\n  Eigen::Matrix3d _cross_op(Eigen::Vector3d _v)\n  {\n    // Calculate cross operator matrix from vector\n    Eigen::MatrixXd _M = Eigen::MatrixXd::Zero(3, 3);\n    _M(0, 1) = -_v(2);\n    _M(0, 2) = _v(1);\n    _M(1, 2) = -_v(0);\n    _M(1, 0) = _v(2);\n    _M(2, 0) = -_v(1);\n    _M(2, 1) = _v(0);\n    return _M;\n  };\n\n  Eigen::Vector3d _vee_SO3(Eigen::Matrix3d _rotMatrix)\n  {\n    _phi = acos((_rotMatrix.trace() - 1) / 2);\n    if (_phi == 0.0) {\n      return (Eigen::VectorXd(3) << 0,0,0).finished();\n    } else {\n    _sphi = _phi / sin(_phi);\n    return (Eigen::VectorXd(3) << _sphi * (_rotMatrix(1, 2) - _rotMatrix(2, 1)) / 2., _sphi * (-_rotMatrix(0, 2) + _rotMatrix(2, 0)) / 2., _sphi * (_rotMatrix(0, 1) - _rotMatrix(1, 0)) / 2.).finished();\n    }\n  };\n\n  double _constraint(double _init_time, int _timesteps)\n  {\n    // Calculate thrust limits after number of timesteps\n    _time = _init_time + _timesteps * _ts;\n    if (_time > 0.) {\n      return _T_max / (1 + std::exp(-12. / _t_ramp * (_time - (_t_ramp / 2.))));\n    } else if (_time < 0.) {\n      return -_T_max / (1 + std::exp(12. / _t_ramp * (_time + (_t_ramp / 2.))));\n    } else {\n      return 0.;\n    }\n  };\n\n  double _inv_constraint(double _thrust)\n  {\n    // Calculate time associated with thrust value on constraint curve\n    _T_scaled = _thrust / _T_max;\n\n    if (std::abs(_T_scaled) > 0.98) {\n      _T_scaled = ((_thrust > 0.) - (_thrust < 0.)) * 0.98;\n    }\n\n    if (_thrust > 0.) {\n      return (std::log(_T_scaled / (1. - _T_scaled)) * _t_ramp / 12.) + _t_ramp / 2.;\n    } else if (_thrust < 0.) {\n      return -(std::log(-_T_scaled / (1. - _T_scaled)) * _t_ramp / 12.) - _t_ramp / 2.;\n    } else {\n      return 0.;\n    }\n  };\n\n  Eigen::Matrix<double, 6, 6> _solve_dare(Eigen::Matrix<double, 6, 6> _Adare, Eigen::Matrix<double, 6, 4> _Bdare, Eigen::Matrix<double, 6, 6> _Qdare, Eigen::Matrix<double, 4, 4> _Rdare)\n  {\n    // Solve discrete-time algebraic Ricatti equation\n    _Ad = _Adare;\n    _Gd.noalias() = _Bdare * (_Rdare.householderQr().solve(_Bdare.transpose()));\n    _Hd = _Qdare;\n\n    while ((_Hd - _Hdk).squaredNorm() > 1e-10 * _Hd.squaredNorm()) {\n      _Adk = _Ad;\n      _Gdk = _Gd;\n      _Hdk = _Hd;\n\n      _W = Eigen::Matrix<double, 6, 6>::Identity() + _Gdk * _Hdk;\n      _V1 = _W.householderQr().solve(_Adk);\n      _V2 = (_W.householderQr().solve(_Gdk.transpose())).transpose();\n\n      _Ad.noalias() = _Adk * _V1;\n      _Gd.noalias() = _Gdk + _Adk * _V2 * _Adk.transpose();\n      _Hd.noalias() = _Hdk + _V1.transpose() * _Hdk * _Adk;\n    }\n    return _Hd;\n  };\n\n  void _eigen_to_al(Eigen::MatrixXd emat, al::real_2d_array* almat)\n  {\n    almat->setlength(emat.rows(), emat.cols());\n    for (int i = 0; i < emat.rows(); i++) {\n      for (int j = 0; j < emat.cols(); j++) {\n        almat->operator()(i, j) = emat(i, j);\n      }\n    }\n  };\n\n  void _eigen_to_al(Eigen::VectorXd emat, al::real_1d_array* almat)\n  {\n    almat->setlength(emat.rows());\n    for (int i = 0; i < emat.rows(); i++) {\n      almat->operator()(i) = emat(i);\n    }\n  };\n\n  bool _check_bounds(al::real_1d_array _U_ctrl, al::real_1d_array _U_low, al::real_1d_array _U_upp)\n  {\n    for (int i = 0; i < _np; i++) {\n      if (_U_ctrl(i) < _U_low(i) || _U_ctrl(i) > _U_upp(i)) {\n        return 0;\n      }\n    }\n    return 1;\n  };\n\n  void _init_constraints()\n  {\n    // Build constraint matrices for MPC\n    for (int i = 0; i < 4; i++) {\n      _t_input = _inv_constraint(_U0(i));\n     for (int j = 1; j <= _np; j++) {\n        _u_bndh(i + _nu * (j - 1)) = _U0(i + _nu * (j - 1)) - _constraint(_t_input, -j);\n        _u_bndl(i + _nu * (j - 1)) = _U0(i + _nu * (j - 1)) - _constraint(_t_input, j);\n      }\n    }\n  };\n\n  void _build_constraints()\n  {\n    // Build constraint matrices for MPC\n    for (int i = 0; i < 4; i++) {\n      _t_input = _inv_constraint(_U0(i));\n      _u_bndh(i) = _U0(i) - _constraint(_t_input, -1);\n      _u_bndl(i) = _U0(i) - _constraint(_t_input, 1);\n      for (int j = 2; j <= _np; j++) {\n        _t_input = _inv_constraint(_Uc(i + _nu * (j - 2)));\n        _u_bndh(i + _nu * (j - 1)) = _U0(i + _nu * (j - 1)) - _constraint(_t_input, -1);\n        _u_bndl(i + _nu * (j - 1)) = _U0(i + _nu * (j - 1)) - _constraint(_t_input, 1);\n      }\n    }\n  };\n};\n", "meta": {"hexsha": "62dd20c457b22931767a225631b2c75cd4974877", "size": 17335, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lie_mpc_bidirectional.hpp", "max_stars_repo_name": "JadWehbeh/lie_mpc_bidirectional", "max_stars_repo_head_hexsha": "ad609da4a6c4e12e0436ee5b7f0078b7086ed32b", "max_stars_repo_licenses": ["MIT"], "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/lie_mpc_bidirectional.hpp", "max_issues_repo_name": "JadWehbeh/lie_mpc_bidirectional", "max_issues_repo_head_hexsha": "ad609da4a6c4e12e0436ee5b7f0078b7086ed32b", "max_issues_repo_licenses": ["MIT"], "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/lie_mpc_bidirectional.hpp", "max_forks_repo_name": "JadWehbeh/lie_mpc_bidirectional", "max_forks_repo_head_hexsha": "ad609da4a6c4e12e0436ee5b7f0078b7086ed32b", "max_forks_repo_licenses": ["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.8314393939, "max_line_length": 204, "alphanum_fraction": 0.5703490049, "num_tokens": 6605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5336820881451335}}
{"text": "#include <geometry.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 <vector>\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(closest_point_test)\n{\n  typedef tiny::MathTypes<float> MT;\n  typedef MT::vector3_type       V;\n\n  {\n    geometry::Line<V> const L = geometry::Line<V>( V::make(0,0,0), V::make(1,0,0));  // x-axis line\n    \n    V const q = geometry::closest_point_on_line( V::make(10,4,5), L );\n    \n    BOOST_CHECK_CLOSE( q(0), 10.0f, 0.01f );\n    BOOST_CHECK_CLOSE( q(1), 0.0f, 0.01f );\n    BOOST_CHECK_CLOSE( q(2), 0.0f, 0.01f );\n  }\n  {\n    geometry::Plane<V> const P = geometry::make_plane( V::make(1,0,0), 0);  // y-z plane\n\n    V const q = geometry::closest_point_on_plane( V::make(10,4,5), P );\n    \n    BOOST_CHECK_CLOSE( q(0), 0.0f, 0.01f );\n    BOOST_CHECK_CLOSE( q(1), 4.0f, 0.01f );\n    BOOST_CHECK_CLOSE( q(2), 5.0f, 0.01f );\n  }\n  {\n    geometry::Line<V> const L1 = geometry::Line<V>( V::make(0,0,1), V::make(0,1,0));  // y-axis line\n    geometry::Line<V> const L2 = geometry::Line<V>( V::make(0,0,0), V::make(1,0,0));  // x-axis line\n\n    V p1, p2;\n\n    geometry::closest_points_line_line( L1, L2, p1, p2 );\n\n    BOOST_CHECK_CLOSE( p1(0), 0.0f, 0.01f );\n    BOOST_CHECK_CLOSE( p1(1), 0.0f, 0.01f );\n    BOOST_CHECK_CLOSE( p1(2), 1.0f, 0.01f );\n\n    BOOST_CHECK_CLOSE( p2(0), 0.0f, 0.01f );\n    BOOST_CHECK_CLOSE( p2(1), 0.0f, 0.01f );\n    BOOST_CHECK_CLOSE( p2(2), 0.0f, 0.01f );\n\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "0525c7134a4d9781c2a76acc4780131e5e7672c6", "size": 1632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_closest_point/geometry_closest_point.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_closest_point/geometry_closest_point.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_closest_point/geometry_closest_point.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1379310345, "max_line_length": 100, "alphanum_fraction": 0.6323529412, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5336335202256084}}
{"text": "// Boost.Signals library\r\n//\r\n// Copyright (C) 2001 Doug Gregor (gregod@cs.rpi.edu)\r\n//\r\n// Permission to copy, use, sell and distribute this software is granted\r\n// provided this copyright notice appears in all copies.\r\n// Permission to modify the code and to distribute modified code is granted\r\n// provided this copyright notice appears in all copies, and a notice\r\n// that the code was modified is included with the copyright notice.\r\n//\r\n// This software is provided \"as is\" without express or implied warranty,\r\n// and with no claim as to its suitability for any purpose.\r\n \r\n// For more information, see http://www.boost.org\r\n\r\n#include <algorithm>\r\n#include <iostream>\r\n#include <boost/signals/signal2.hpp>\r\n\r\ntemplate<typename T>\r\nstruct maximum {\r\n  typedef T result_type;\r\n\r\n  template<typename InputIterator>\r\n  T operator()(InputIterator first, InputIterator last) const\r\n  {\r\n    if (first == last)\r\n      throw std::runtime_error(\"Cannot compute maximum of zero elements!\");\r\n    return *std::max_element(first, last);\r\n  }\r\n};\r\n\r\nint main()\r\n{\r\n  boost::signal2<int, int, int, maximum<int> > sig_max;\r\n  sig_max.connect(std::plus<int>());\r\n  sig_max.connect(std::multiplies<int>());\r\n  sig_max.connect(std::minus<int>());\r\n  sig_max.connect(std::divides<int>());\r\n\r\n  std::cout << sig_max(5, 3) << std::endl; // prints 15\r\n  \r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "3f682643762b87df24e9866e2bb60b2d66f27622", "size": 1359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/signals/example/maximum.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/signals/example/maximum.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/libs/signals/example/maximum.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "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": 76, "alphanum_fraction": 0.6902133922, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789269812082, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5336335147932452}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EXPONENTIAL_FUNCTIONS_SIMD_COMMON_POW2_HPP_INCLUDED\n#define NT2_EXPONENTIAL_FUNCTIONS_SIMD_COMMON_POW2_HPP_INCLUDED\n#include <nt2/exponential/functions/pow2.hpp>\n#include <nt2/include/functions/simd/ldexp.hpp>\n#include <nt2/include/functions/simd/toint.hpp>\n#include <nt2/include/functions/simd/twopower.hpp>\n#include <nt2/include/functions/simd/is_nan.hpp>\n#include <nt2/include/functions/simd/is_inf.hpp>\n#include <nt2/include/functions/simd/if_allbits_else.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/is_inf.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow2_, tag::cpu_\n                            , (A0)(A1)(X)\n                            , ((simd_< floating_<A0>,X >))\n                              ((simd_< integer_<A1>,X >))\n                            )\n  {\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      return nt2::ldexp(a0, a1);\n    }\n  };\n} }\n\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow2_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_< floating_<A0>,X >))\n                              ((simd_< floating_<A0>,X >))\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL_REPEAT(2)\n    {\n      return nt2::ldexp(a0, nt2::toint(a1));\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow2_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_< integer_<A0>,X >))\n                              ((simd_< integer_<A0>,X >))\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL_REPEAT(2)\n    {\n      return nt2::ldexp(a0, a1);\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow2_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_< integer_<A0>,X >))\n                            )\n  {\n\n    typedef typename  boost::dispatch::meta::as_floating<A0>::type result_type;\n\n    NT2_FUNCTOR_CALL_REPEAT(1)\n    {\n      return nt2::ldexp(One<A0>(), a0);\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow2_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_< floating_<A0>,X >))\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL_REPEAT(1)\n    {\n      return nt2::if_allbits_else(is_nan(a0),\n                                  nt2::if_else(is_inf(a0),\n                                               if_else(is_gtz(a0), a0, Zero<result_type>()),\n                                               nt2::ldexp(One<A0>(), nt2::toint(a0))\n                                               )\n                                  );\n    }\n  };\n\n} }\n\n\n#endif\n", "meta": {"hexsha": "695f871cc09505f51294547fe1d9d087b634d7f1", "size": 3328, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/functions/simd/common/pow2.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/core/exponential/include/nt2/exponential/functions/simd/common/pow2.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/core/exponential/include/nt2/exponential/functions/simd/common/pow2.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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.2545454545, "max_line_length": 92, "alphanum_fraction": 0.4873798077, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5336335141975047}}
{"text": "/*\n * Copyright (c) 2016 Abhishek Agrawal (abhishek.agrawal@protonmail.com)\n * Distributed under the MIT License.\n * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT\n */\n\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <exception>\n#include <cstdlib>\n#include <execinfo.h>\n\n#include <boost/exception/info.hpp>\n\n#include <gsl/gsl_multiroots.h>\n#include <gsl/gsl_vector.h>\n \t\n#include <libsgp4/DateTime.h>\n#include <libsgp4/Eci.h>\n#include <libsgp4/Globals.h>\n#include <libsgp4/SGP4.h>\n#include <libsgp4/Tle.h>\n\n#include <Astro/astro.hpp>\n#include <SML/sml.hpp>\n#include <SML/constants.hpp>\n#include <SML/basicFunctions.hpp>\n\n#include <Atom/printFunctions.hpp>\n\n#include <Astro/orbitalElementConversions.hpp>\n#include <Atom/convertCartesianStateToTwoLineElements.hpp>\n\n#include \"/media/abhishek/work/TU delft/INTERNSHIP at DINAMICA/work/github/pykep/src/core_functions/par2ic.h\"\n\n#include \"CppProject/TleGen.hpp\"\n\n\nnamespace TleGen{\n\n\ttypedef double Real;\n\ttypedef std::vector< Real > Vector6;\n\ttypedef std::vector< Real > Vector3;\n\ttypedef std::vector< Real > Vector2;\n\ttypedef std::vector < std::vector < Real > > Vector2D;\n\n\tvoid TleGen( Vector6 randKepElem, std::string& SolverStatus, int& IterationCount )\n\t{\n\t\t// grav. parameter 'mu' of earth\n    \tconst double muEarth = kMU*( pow( 10, 9 ) ); // unit m^3/s^2\n\t    // generate sets of cartesian elements corresponding to each of the psuedo random orbital element set. \n\t    // The conversion from keplerian elements to the cartesian elements is done using the PyKep library from ESA.\n\t    Vector3 CartPos( 3 ); // empty vector to store position coordinates\n\t    Vector3 CartVel( 3 ); // empty vector to store velocity components\n\t    // Real rangeMag = 0; // magnitude range\n\t    // Real velocityMag = 0; // velocity magnitude\n\t    kep_toolbox::par2ic( randKepElem, muEarth, CartPos, CartVel );\n\t   \n\t    // verification of the conversion process using Ron Noomen's lecture notes from TUDelft\n\t    // Document ID ae4878.basics.v4-16.pdf\n\t    // Vector6 testKep = { 6787746.891, 0.000731104, sml::convertDegreesToRadians( 51.68714486 ), \n\t    //     sml::convertDegreesToRadians( 127.5486706 ), sml::convertDegreesToRadians( 74.21987137 ), sml::convertDegreesToRadians( 24.08317766 ) };\n\t    // Vector3 testPos( 3 );\n\t    // Vector3 testVel( 3 );\n\t    // kep_toolbox::par2ic( testKep, muEarth, testPos, testVel );    \n\t    // std::cout << testPos[ 0 ] << std::endl;\n\t    // std::cout << testPos[ 1 ] << std::endl;\n\t    // std::cout << testPos[ 2 ] << std::endl;\n\t    // std::cout << testVel[ 0 ] << std::endl;\n\t    // std::cout << testVel[ 1 ] << std::endl;\n\t    // std::cout << testVel[ 2 ] << std::endl;\n\n\t    // convert the cartesian elements to the corresponding TLE format using the ATOM toolbox\n\t    Vector6 cartesianState( 6 );\n\t    // cartesianState[ 0 ] = -7.1e3;\n\t    // cartesianState[ 1 ] = 2.7e3;\n\t    // cartesianState[ 2 ] = 1.3e3;\n\t    // cartesianState[ 3 ] = -2.5;\n\t    // cartesianState[ 4 ] = -5.5;\n\t    // cartesianState[ 5 ] = 5.5;\n\t    Tle convertedTle;\n\t    Tle referenceTle = Tle(); // empty TLE for reference\n\t    // std::cout << referenceTle << std::endl << std::endl;\n\t    const Real absTol = 1.0e-10; // absolute tolerance\n\t    const Real relTol = 1.0e-5; // relative tolerance\n\t    const int maxItr = 100; // maximum allowed iterations per conversion run\n\t    \n\t    // important note, the atom function converting cartesian to TLEs takes in values in km and km/s.\n\t    cartesianState[ 0 ] = CartPos[ 0 ]/1000;\n\t    cartesianState[ 1 ] = CartPos[ 1 ]/1000;\n\t    cartesianState[ 2 ] = CartPos[ 2 ]/1000;\n\t    cartesianState[ 3 ] = CartVel[ 0 ]/1000;\n\t    cartesianState[ 4 ] = CartVel[ 1 ]/1000;\n\t    cartesianState[ 5 ] = CartVel[ 2 ]/1000;\n\t\tconvertedTle = atom::convertCartesianStateToTwoLineElements< Real, Vector6 >( cartesianState, DateTime( ), SolverStatus, \n\t    \tIterationCount, referenceTle, kMU, kXKMPER, absTol, relTol, maxItr );\n\t}\n}", "meta": {"hexsha": "e5f30d3e76a4bfb8ccf1515c63b3b7d6a3be1c16", "size": 4031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TleGen.cpp", "max_stars_repo_name": "abhi-agrawal/ATOM_ADR", "max_stars_repo_head_hexsha": "b3bfe9f0ff75bd188a06422342b3eec391942db9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TleGen.cpp", "max_issues_repo_name": "abhi-agrawal/ATOM_ADR", "max_issues_repo_head_hexsha": "b3bfe9f0ff75bd188a06422342b3eec391942db9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TleGen.cpp", "max_forks_repo_name": "abhi-agrawal/ATOM_ADR", "max_forks_repo_head_hexsha": "b3bfe9f0ff75bd188a06422342b3eec391942db9", "max_forks_repo_licenses": ["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.5196078431, "max_line_length": 148, "alphanum_fraction": 0.6772513024, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5336335027370375}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n#include <vector>\n#include <map>\n#include <valarray>\n#include <boost/algorithm/string.hpp>\n\nusing namespace std;\n\nmap<string, valarray<int>> DIRECTIONS = {\n    // x, y, z\n    // Hex cubic labeling\n    {\"e\", {1, -1, 0}},\n    {\"w\", {-1, 1, 0}},\n    {\"se\", {1, 0, -1}},\n    {\"ne\", {0, -1, 1}},\n    {\"sw\", {0, 1, -1}},\n    {\"nw\", {-1, 0, 1}},\n};\n\nstring hash_loc(valarray<int> loc){\n  return (to_string(loc[0]) + \",\"+\n          to_string(loc[1]) + \",\"+\n          to_string(loc[2]));\n}\n\nvalarray<int> unhash_loc(string hloc) {\n  vector<string> split_str;\n  boost::split(split_str, hloc, boost::is_any_of(\",\"));\n  valarray<int> out = {\n      stoi(split_str[0]),\n      stoi(split_str[1]),\n      stoi(split_str[2]),\n  };\n  return out;\n}\n\nint count_black(map<string, int> tile_flips){\n  int num_black = 0;\n  for (auto [sloc, flips] : tile_flips) {\n    num_black += flips % 2;\n  }\n  return num_black;\n}\n\nint main() {\n\n  map<string, int> tile_flips; // 1 if black\n\n  for (string line; getline(cin, line);){\n    // cout << line << endl;\n    vector<string> directions;\n    int curr_loc=0;\n    while (curr_loc < line.size()){\n      if ((line[curr_loc] == 'n') ||\n          (line[curr_loc] == 's')) {\n        directions.push_back(line.substr(curr_loc, 2));\n        curr_loc += 2;\n      } else{\n        directions.push_back(line.substr(curr_loc, 1));\n        curr_loc += 1;\n      }\n    }\n    valarray<int> loc = {0,0,0}; // Reference tile\n    for (string dir : directions){\n      loc += DIRECTIONS[dir];\n    }\n    tile_flips[hash_loc(loc)] += 1;\n  }\n\n  cout << \"Part 1: \" << count_black(tile_flips) << endl;\n  cout << endl;\n\n  // Part 2\n  int num_days = 100;\n  for (int i=1; i<=num_days; i++){\n    auto start_flips = tile_flips;\n    // Map of white tiles to num black adjacent\n    // Only gets evaluated for tiles with atleast 1 black neighbour\n    map<string,int> blackn_count;\n    // Look over all known tiles;\n    for (auto [hloc, flips] : start_flips){\n      bool black = flips % 2;\n      valarray<int> loc = unhash_loc(hloc);\n      if (black){\n        // If a black tile, count adjacent black tiles\n        int blackn = 0;\n        for (auto [dir, mdir] : DIRECTIONS){\n          string nhash = hash_loc(loc + mdir);\n          bool is_blackn = (start_flips[nhash] % 2);\n          blackn += is_blackn;\n          // If neighbour is white, increment\n          // the number of black adjacents that\n          // that white tile has.\n          if (not is_blackn){\n            blackn_count[nhash] += 1;\n          }\n        }\n        // Flip if matches rule for black tile\n        if ((blackn == 0) || (blackn > 2)){\n          tile_flips[hloc]++;\n        }\n      }\n    }\n\n    // Find white tiles with 2 black adjacent.\n    for (auto [hloc, nblackn] : blackn_count){\n      if (nblackn == 2){\n        tile_flips[hloc]++;\n      }\n    }\n    cout << \"Day \" << i << \": \" << count_black(tile_flips) << endl;\n  }\n  cout << endl;\n  cout << \"Part 2: \" << count_black(tile_flips) << endl;\n}\n", "meta": {"hexsha": "e6dec352a4e0b1b293d10e298fb1ec43fbb5bd5a", "size": 3039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "24/aoc24.cpp", "max_stars_repo_name": "GreyGooClub/Advent2020-DTC", "max_stars_repo_head_hexsha": "b1ff37ef9a3c8272513cf6d7eba66dae11680d60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "24/aoc24.cpp", "max_issues_repo_name": "GreyGooClub/Advent2020-DTC", "max_issues_repo_head_hexsha": "b1ff37ef9a3c8272513cf6d7eba66dae11680d60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "24/aoc24.cpp", "max_forks_repo_name": "GreyGooClub/Advent2020-DTC", "max_forks_repo_head_hexsha": "b1ff37ef9a3c8272513cf6d7eba66dae11680d60", "max_forks_repo_licenses": ["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.5378151261, "max_line_length": 67, "alphanum_fraction": 0.5508390918, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5336335027370374}}
{"text": "/* test_lognormal_distribution.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$\n *\n */\n\n#include <boost/random/lognormal_distribution.hpp>\n#include <limits>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::lognormal_distribution<>\n#define BOOST_RANDOM_ARG1 m\n#define BOOST_RANDOM_ARG2 s\n#define BOOST_RANDOM_ARG1_DEFAULT 0.0\n#define BOOST_RANDOM_ARG2_DEFAULT 1.0\n#define BOOST_RANDOM_ARG1_VALUE 7.5\n#define BOOST_RANDOM_ARG2_VALUE 0.25\n\n#define BOOST_RANDOM_DIST0_MIN 0.0\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()\n#define BOOST_RANDOM_DIST1_MIN 0.0\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()\n#define BOOST_RANDOM_DIST2_MIN 0.0\n#define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<double>::infinity)()\n\n#define BOOST_RANDOM_TEST1_PARAMS (-100.0)\n#define BOOST_RANDOM_TEST1_MAX 1\n\n#define BOOST_RANDOM_TEST2_PARAMS (100.0)\n#define BOOST_RANDOM_TEST2_MIN 1\n\n#include \"test_distribution.ipp\"\n", "meta": {"hexsha": "707d355e7019f50dc70f78507b50338e638dc015", "size": 1108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_lognormal_distribution.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/random/test/test_lognormal_distribution.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/random/test/test_lognormal_distribution.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": 29.9459459459, "max_line_length": 73, "alphanum_fraction": 0.8086642599, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5336334967089333}}
{"text": "//Author: Dr. Shantanu Shahane\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <float.h>\n#include <string.h>\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/SparseExtra>\n#include <Eigen/SparseLU>\n#include <Eigen/OrderingMethods>\n#include <Eigen/Core>\n#include \"_hypre_utilities.h\"\n#include \"HYPRE_krylov.h\"\n#include \"HYPRE.h\"\n#include \"HYPRE_parcsr_ls.h\"\n#include \"general_functions.hpp\"\n#include \"class.hpp\"\n\nIMPLICIT_SCALAR_TRANSPORT_SOLVER::IMPLICIT_SCALAR_TRANSPORT_SOLVER(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, vector<bool> &dirichlet_flag1, int precond_freq_it1, double unsteady_coeff1, double conv_coeff1, double diff_coeff1, bool solver_log_flag1)\n{\n    dirichlet_flag = dirichlet_flag1, solver_log_flag = solver_log_flag1;\n    unsteady_coeff = unsteady_coeff1, conv_coeff = conv_coeff1, diff_coeff = diff_coeff1;\n    precond_freq_it = precond_freq_it1;\n\n    zero_vector = Eigen::VectorXd::Zero(points.nv);\n    bc_full_neumann = true;\n    for (int iv = 0; iv < points.nv; iv++)\n        if (points.boundary_flag[iv] && dirichlet_flag[iv])\n        { //boundary point found with dirichlet BC\n            bc_full_neumann = false;\n            break;\n        }\n    if (bc_full_neumann)\n    {\n        printf(\"\\n\\nERROR from IMPLICIT_SCALAR_TRANSPORT_SOLVER::IMPLICIT_SCALAR_TRANSPORT_SOLVER Setting  full Neumann BC is not permitted\\n\\n\");\n        throw bad_exception();\n    }\n    source = zero_vector, phi_old_old = zero_vector;\n}\n\nvoid IMPLICIT_SCALAR_TRANSPORT_SOLVER::set_matrix(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new)\n{\n    matrix.resize(0, 0);\n    vector<Eigen::Triplet<double>> triplet;\n    int ivnb, dim = parameters.dimension;\n    double value, unsteady_factor;\n    if (it == 0)\n        unsteady_factor = 1.0; //BDF1: implicit Euler\n    else\n        unsteady_factor = bdf2_alpha_1;\n    for (int iv = 0; iv < points.nv; iv++)\n    {\n        if (points.boundary_flag[iv])\n        {\n            if (dirichlet_flag[iv])\n                triplet.push_back(Eigen::Triplet<double>(iv, iv, 1.0));\n            else\n            {\n                for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n                {\n                    ivnb = cloud.nb_points_col[i1];\n                    value = points.normal[dim * iv] * cloud.grad_x_coeff[i1] + points.normal[dim * iv + 1] * cloud.grad_y_coeff[i1];\n                    triplet.push_back(Eigen::Triplet<double>(iv, ivnb, value));\n                }\n            }\n        }\n        else\n        {\n            for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n            {\n                ivnb = cloud.nb_points_col[i1];\n                value = diff_coeff * cloud.laplacian_coeff[i1];                    //diffusion\n                value = value + (u_new[iv] * conv_coeff * cloud.grad_x_coeff[i1]); //convection\n                value = value + (v_new[iv] * conv_coeff * cloud.grad_y_coeff[i1]); //convection\n                if (ivnb == iv)\n                    value = value + (unsteady_factor * unsteady_coeff); //diagonal term\n                triplet.push_back(Eigen::Triplet<double>(iv, ivnb, value));\n            }\n        }\n    }\n    matrix.resize(points.nv, points.nv);\n    matrix.setFromTriplets(triplet.begin(), triplet.end());\n    matrix.makeCompressed();\n    triplet.clear();\n}\n\nvoid IMPLICIT_SCALAR_TRANSPORT_SOLVER::modify_matrix(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new)\n{\n    int ivnb, dim = parameters.dimension, index;\n    double value, unsteady_factor;\n    if (it == 0)\n        unsteady_factor = 1.0; //BDF1: implicit Euler\n    else\n        unsteady_factor = bdf2_alpha_1;\n    for (int iv = 0; iv < points.nv; iv++)\n        if (!points.boundary_flag[iv])\n        { //coefficients of boundary points never updated for velocities\n            for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n            {\n                ivnb = cloud.nb_points_col[i1];\n                value = diff_coeff * cloud.laplacian_coeff[i1];                    //diffusion\n                value = value + (u_new[iv] * conv_coeff * cloud.grad_x_coeff[i1]); //convection\n                value = value + (v_new[iv] * conv_coeff * cloud.grad_y_coeff[i1]); //convection\n                if (ivnb == iv)\n                    value = value + (unsteady_factor * unsteady_coeff); //diagonal term\n                index = nb_points_col_matrix[i1];\n                matrix.valuePtr()[index] = value;\n            }\n        }\n}\n\nvoid IMPLICIT_SCALAR_TRANSPORT_SOLVER::calc_nb_points_col_matrix(POINTS &points, CLOUD &cloud, PARAMETERS &parameters)\n{\n    int ivnb, index;\n    nb_points_col_matrix.clear();\n    for (int i1 = 0; i1 < cloud.nb_points_col.size(); i1++) //initialize to -1\n        nb_points_col_matrix.push_back(-1);\n    for (int iv = 0; iv < points.nv; iv++)\n        if (!points.boundary_flag[iv])\n        { //coefficients of boundary points never updated for velocities; nb_points_col_matrix ahas value of [-1] at bounday points\n            for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n            {\n                index = -1;\n                ivnb = cloud.nb_points_col[i1];\n                for (int i2 = matrix.outerIndexPtr()[iv]; i2 < matrix.outerIndexPtr()[iv + 1]; i2++)\n                    if (matrix.innerIndexPtr()[i2] == ivnb)\n                    {\n                        index = i2;\n                        break;\n                    }\n                if (index < 0)\n                {\n                    cout << \"\\n\\nError from SEMI_IMPLICIT_SPLIT_SOLVER::calc_nb_points_col_matrix in matrix_u, unable to find ivnb: \" << ivnb << \" for iv: \" << iv << \", points.boundary_flag[iv]: \" << points.boundary_flag[iv] << \"\\n\\n\";\n                    throw bad_exception();\n                }\n                nb_points_col_matrix[i1] = index;\n            }\n        }\n}\n\nvoid IMPLICIT_SCALAR_TRANSPORT_SOLVER::single_timestep_2d(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &phi_new, Eigen::VectorXd &phi_old, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, int it1)\n{\n    it = it1;\n    if (it % precond_freq_it == 0 || it == 0 || it == 1)\n    {\n        set_matrix(points, cloud, parameters, u_new, v_new);\n        solver_eigen.setTolerance(parameters.solver_tolerance); //default is machine precision (https://eigen.tuxfamily.org/dox/classEigen_1_1IterativeSolverBase.html#ac160a444af8998f93da9aa30e858470d)\n        solver_eigen.setMaxIterations(parameters.n_iter);       //default is twice number of columns (https://eigen.tuxfamily.org/dox/classEigen_1_1IterativeSolverBase.html#af83de7a7d31d9d4bd1fef6222b07335b)\n        solver_eigen.preconditioner().setDroptol(parameters.precond_droptol);\n        solver_eigen.compute(matrix);\n        if (it == 0)\n            calc_nb_points_col_matrix(points, cloud, parameters);\n    }\n    modify_matrix(points, cloud, parameters, u_new, v_new);\n\n    if (it == 0) //BDF1: implicit Euler\n        source = (unsteady_coeff * phi_old);\n    else //BDF2\n        source = -((bdf2_alpha_2 * unsteady_coeff) * phi_old) - ((bdf2_alpha_3 * unsteady_coeff) * phi_old_old);\n\n    for (int iv = 0; iv < points.nv; iv++)\n        if (points.boundary_flag[iv])\n        { //retain boundary condition from \"_old\"\n            if (dirichlet_flag[iv])\n                source[iv] = phi_old[iv];\n            else\n                source[iv] = 0.0;\n        }\n    phi_new = solver_eigen.solveWithGuess(source, phi_old);\n    if (solver_log_flag)\n    {\n        double absolute_residual = (matrix * phi_new - source).norm();\n        double relative_residual = absolute_residual / source.norm();\n        parameters.rel_res_log.push_back(relative_residual);\n        parameters.abs_res_log.push_back(absolute_residual);\n        parameters.n_iter_actual.push_back(solver_eigen.iterations());\n    }\n    phi_old_old = phi_old;\n}", "meta": {"hexsha": "557f92587cd637b3c154e7d19f5108ad35fb9a22", "size": 8022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "header_files/implicit_scalar_transport_solver.cpp", "max_stars_repo_name": "shahaneshantanu/memphys", "max_stars_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "header_files/implicit_scalar_transport_solver.cpp", "max_issues_repo_name": "shahaneshantanu/memphys", "max_issues_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "header_files/implicit_scalar_transport_solver.cpp", "max_forks_repo_name": "shahaneshantanu/memphys", "max_forks_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-07T00:32:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:32:37.000Z", "avg_line_length": 44.0769230769, "max_line_length": 260, "alphanum_fraction": 0.6171777612, "num_tokens": 2085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262968, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5335897113224443}}
{"text": "//==================================================================================================\n/*\n  Copyright 2017 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//! [inverse_trigonometric]\n#include <boost/simd/trigonometric.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/enumerate.hpp>\n#include <iostream>\n\nnamespace bs =  boost::simd;\nusing pack_ft =  bs::pack <float, 8>;\n\nint main()\n{\n  pack_ft p = bs::enumerate<pack_ft>(-1.0f, 0.25f);\n  std::cout << \" p =  \" << p << std::endl\n            << \" -> bs::acos(p) =   \" << bs::acos(p)   << std::endl\n            << \" -> bs::acospi(p) = \" << bs::acospi(p) << std::endl\n            << \" -> bs::acosd(p) =  \" << bs::acosd(p)  << std::endl;\n  return 0;\n}\n//! [inverse_trigonometric]\n", "meta": {"hexsha": "109e61540e63f89e4b95fc5b383bed390d153a6f", "size": 968, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/trigonometric/inverse_trigonometric.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/doc/trigonometric/inverse_trigonometric.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/doc/trigonometric/inverse_trigonometric.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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": 34.5714285714, "max_line_length": 100, "alphanum_fraction": 0.4731404959, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5335897107148345}}
{"text": "/*\n * baseframe.cc\n * Copyright (C) 2017 roman <roman.podolski@tum.de>\n *\n * Distributed under terms of the MIT license.\n */\n\n#include \"planner/baseframe.h\"\n#include <gflags/gflags.h>\n#include <boost/math/interpolators/cubic_b_spline.hpp>\n#include <boost/math/quadrature/trapezoidal.hpp>\n#include <boost/math/tools/minima.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <utility>\n#include <vector>\n#include \"planner/map.h\"\n\nnamespace planner {\n\nusing boost::math::quadrature::trapezoidal;\nusing boost::math::cubic_b_spline;\nusing boost::math::tools::bisect;\nusing boost::math::tools::eps_tolerance;\nusing boost::math::tools::newton_raphson_iterate;\n\nBaseframe::Baseframe(const Map &map) {\n  const auto vx = map.get_waypoints_x();\n  const auto vy = map.get_waypoints_y();\n  init(vx, vy);\n}\n\nBaseframe::Baseframe(const std::vector<std::pair<double, double>> &wp) {\n  std::vector<double> vx, vy;\n  for (const auto &p : wp) {\n    vx.push_back(p.first);\n    vy.push_back(p.second);\n  }\n  init(vx, vy);\n}\n\nBaseframe::Baseframe(const std::vector<point> &wp) {\n  std::vector<double> vx, vy;\n  for (const auto &p : wp) {\n    vx.push_back(p.x());\n    vy.push_back(p.y());\n  }\n  init(vx, vy);\n}\n\nvoid Baseframe::init(const std::vector<double> vx,\n                     const std::vector<double> vy) {\n  CHECK_EQ(vx.size(), vy.size());\n  _N = vx.size() - 1;\n  _x = cubic_b_spline<double>(vx.begin(), vx.end(), 0, 1.0);\n  _y = cubic_b_spline<double>(vy.begin(), vy.end(), 0, 1.0);\n}\n\npoint Baseframe::Q(const double t) const {\n  if (t < 0 || t > _N)\n    throw std::domain_error(\"t = \" + std::to_string(t) +\n                            \" not within the domain [0,N]\");\n  return point(_x(t), _y(t));\n}\n\npoint Baseframe::Q_prime(const double t) const {\n  if (t < 0 || t > _N)\n    throw std::domain_error(\"t = \" + std::to_string(t) +\n                            \" not within the domain [0,N]\");\n  return point(_x.prime(t), _y.prime(t));\n}\n\npoint Baseframe::Q_pprime(const double t) const {\n  const double ddt_x =\n      derivative(t, 0.001, [this](const double t) { return _x.prime(t); });\n  const double ddt_y =\n      derivative(t, 0.001, [this](const double t) { return _y.prime(t); });\n  return point(ddt_x, ddt_y);\n}\n\ndouble Baseframe::theta_Q(const double t) const {\n  auto p = Q_prime(t);\n  // return atan2(p.y(), p.x());\n  return atan(p.y() / p.x());\n}\n\nstatic std::map<double, double> _A_lut{{0, 0}};\nstatic std::vector<double> _segment_lut;\ndouble Baseframe::A(const double t) const {\n  if (t < 0 || t > _N)\n    throw std::domain_error(\"t = \" + std::to_string(t) +\n                            \" not within the domain [0,N]\");\n  if (_A_lut.find(t) != _A_lut.end()) {\n    return _A_lut[t];\n  }\n\n  double result = 0.0;\n  if (t == 0) return result;\n\n  auto f = [this](double t) {\n    return sqrt(pow(_x.prime(t), 2) + pow(_y.prime(t), 2));\n  };\n\n  // The 8 and 1e-5 are a little borderline, but help performance.\n  size_t max_refinements = 8;\n  result = trapezoidal(f, 0.0, t, 1e-5, max_refinements);\n\n  _A_lut[t] = result;\n\n  return result;\n}\n\nstatic std::map<double, double> _inv_A_lut{{0, 0}};\ndouble Baseframe::inv_A(const double s) const {\n  if (s < 0 || s > length())\n    throw std::domain_error(\"s = \" + std::to_string(s) +\n                            \" not within the domain [0,L]\");\n\n  if (_segment_lut.empty()) {\n    for (int t = 0; t < _N; ++t) {\n      _segment_lut.push_back(A(t));\n    }\n  }\n\n  if (_inv_A_lut.find(s) != _inv_A_lut.end()) {\n    return _inv_A_lut[s];\n  }\n\n  std::uintmax_t iterations = 1000;\n  auto low = std::lower_bound(_segment_lut.begin(), _segment_lut.end(), s);\n  const double segment = low - _segment_lut.begin();\n  double result = 0.0;\n  result = bisect([this, s](double t) { return A(t) - s; }, segment - 1,\n                  segment, eps_tolerance<float>(), iterations)\n               .first;\n\n  _inv_A_lut[s] = result;\n\n  return result;\n}\n\nstatic std::map<double, double> _curvature_lut;\ndouble Baseframe::curvature(const double s) {\n  if (_curvature_lut.find(s) != _curvature_lut.end()) {\n    return _curvature_lut[s];\n  }\n\n  const auto d_P = P_prime(s);\n  double d_x = d_P.x();\n  double d_y = d_P.y();\n\n  if (d_x == 0.0 && d_y == 0.0) {  // avoid division by 0.0\n    d_x = std::numeric_limits<double>::denorm_min();\n    d_y = std::numeric_limits<double>::denorm_min();\n  }\n\n  const auto dd_P = P_pprime(s);\n  const double dd_x = dd_P.x();\n  const double dd_y = dd_P.y();\n\n  const double kappa =\n      (d_x * dd_y - dd_x * d_y) / pow((pow(d_x, 2) + pow(d_y, 2)), 3.0 / 2.0);\n\n  _curvature_lut[s] = kappa;\n\n  return kappa;\n}\n\n// TODO(roman): check for numerical problems\nstd::pair<double, double> Baseframe::localize(const point position,\n                                              const double v,\n                                              const double heading,\n                                              const double dt,\n                                              const double last_known_s) const {\n  auto D_prime = [ this, x_0 = position.x(), y_0 = position.y() ](double s) {\n    auto p = P(s);\n    double x = p.x();\n    double y = p.y();\n\n    auto p_prime = P_prime(s);\n    double x_prime = p_prime.x();\n    double y_prime = p_prime.y();\n\n    auto p_pprime = P_pprime(s);\n    double x_pprime = p_pprime.x();\n    double y_pprime = p_pprime.y();\n\n    double dist_prime = 2 * (x - x_0) * x_prime + 2 * (y - y_0) * y_prime;\n    double dist_pprime = 2 * ((x - x_0) * x_pprime + pow(x_prime, 2) +\n                              (y - y_0) * y_pprime + pow(y_prime, 2));\n\n    return std::pair<double, double>(dist_prime, dist_pprime);\n  };\n\n  std::uintmax_t iterations = 1000;\n  double minimum_extra_offset = 10;\n  double lower_barrier = last_known_s - minimum_extra_offset / 4; // added /4\n  if (lower_barrier <= 0.0) lower_barrier = 0.0;\n\n  double initial_guess = last_known_s + v * dt;\n  if (initial_guess > length()) initial_guess = length();\n  double upper_barrier = initial_guess + minimum_extra_offset;\n  if (upper_barrier > length()) upper_barrier = length();\n\n  //std::cout << lower_barrier << ' ' << initial_guess << ' ' << upper_barrier << '\\n';\n\n  auto result = newton_raphson_iterate(\n      D_prime, lower_barrier, initial_guess, upper_barrier,\n      std::numeric_limits<double>::digits / 4, iterations); // was /2\n\n  //std::cout <<  result << '\\n';\n\n  auto p = P(result);\n\n  return std::pair<double, double>(result, bg::distance(p, position));\n}\n\n}  // namespace planner\n", "meta": {"hexsha": "d5ecba58134b2859789c0fe0704137bfa30edad9", "size": 6475, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/planner/baseframe.cc", "max_stars_repo_name": "draget/global_planner", "max_stars_repo_head_hexsha": "ca31d6631d28026376b3f280849e2ffc53daec20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-08T03:21:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-20T12:05:58.000Z", "max_issues_repo_path": "src/planner/baseframe.cc", "max_issues_repo_name": "draget/global_planner", "max_issues_repo_head_hexsha": "ca31d6631d28026376b3f280849e2ffc53daec20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/planner/baseframe.cc", "max_forks_repo_name": "draget/global_planner", "max_forks_repo_head_hexsha": "ca31d6631d28026376b3f280849e2ffc53daec20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-20T12:06:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-10T15:42:43.000Z", "avg_line_length": 29.2986425339, "max_line_length": 87, "alphanum_fraction": 0.6055598456, "num_tokens": 1938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5335897055504307}}
{"text": "#include <vector>\n#include <iostream>\n#include <functional>\n#include <solver.hpp>\n#include <math.h>\n#include <complex>\n\n#include <Eigen/Dense>\n\n#include <boost/multiprecision/eigen.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <boost/multiprecision/mpc.hpp>\n\ntypedef boost::multiprecision::mpc_complex_500 C;\ntypedef boost::multiprecision::mpfr_float_500 R;\n\nint main() {\n    std::function<C(Eigen::Matrix<C,2,1>&)> f, g;\n\n    f = [] (Eigen::Matrix<C,2,1> &x) -> C {\n        return x(0)*x(1) - C(6)/10;\n    };\n\n    g = [] (Eigen::Matrix<C,2,1> &x) -> C {\n        return x(0)*x(0) + x(1)*x(1) - C(2);\n    };\n\n    std::vector<decltype(f)> vf;\n\n    vf.push_back(f);\n    vf.push_back(g);\n\n    Eigen::Matrix<C,2,1> x0, x;\n\n    x0(0) = 1;\n    x0(1) = 1;\n\n    auto s = solver::Solver2<C,R,2>(vf);\n    s.set_h(R(\"1e-200\"));\n    s.set_tol(R(\"1e-100\"));\n    x = s.solve(x0);\n\n    return 0;\n}\n", "meta": {"hexsha": "9a270ba361bfe65b033811d143c83e90dcc0a1db", "size": 891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test.cpp", "max_stars_repo_name": "javierelpianista/solver", "max_stars_repo_head_hexsha": "85dd0757ffeec73620f5c69701ce9be51df70ab1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test.cpp", "max_issues_repo_name": "javierelpianista/solver", "max_issues_repo_head_hexsha": "85dd0757ffeec73620f5c69701ce9be51df70ab1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test.cpp", "max_forks_repo_name": "javierelpianista/solver", "max_forks_repo_head_hexsha": "85dd0757ffeec73620f5c69701ce9be51df70ab1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8, "max_line_length": 49, "alphanum_fraction": 0.5824915825, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5335275548205095}}
{"text": "// Copyright \u00a9 2016-2021 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 <Eigen/Dense>\n#include <limits>\n#include <vinecopulib/misc/nlohmann_json.hpp>\n#include <vinecopulib/misc/triangular_array.hpp>\n\nnamespace vinecopulib {\n\n//! @brief A class for R-vine structures.\n//!\n//! RVineStructure objects encode the tree structure of the vine, i.e. the\n//! conditioned/conditioning variables of each edge. It is represented by a\n//! triangular array. An exemplary array is\n//! ```\n//! 4 4 4 4\n//! 3 3 3\n//! 2 2\n//! 1\n//! ```\n//! which encodes the following pair-copulas:\n//! ```\n//! | tree | edge | pair-copulas   |\n//! |------|------|----------------|\n//! | 0    | 0    | `(1, 4)`       |\n//! |      | 1    | `(2, 4)`       |\n//! |      | 2    | `(3, 4)`       |\n//! | 1    | 0    | `(1, 3; 4)`    |\n//! |      | 1    | `(2, 3; 4)`    |\n//! | 2    | 0    | `(1, 2; 3, 4)` |\n//! ```\n//! Denoting by `M[i, j]` the array entry in row `i` and column `j`,\n//! the pair-copula index for edge `e` in tree `t` of a `d` dimensional vine\n//! is `(M[d - 1 - e, e], M[t, e]; M[t - 1, e], ..., M[0, e])`. Less\n//! formally,\n//! 1. Start with the counter-diagonal element of column `e` (first conditioned\n//!    variable).\n//! 2. Jump up to the element in row `t` (second conditioned variable).\n//! 3. Gather all entries further up in column `e` (conditioning set).\n//!\n//! A valid R-vine array must satisfy several conditions which are checked\n//! when `RVineStructure()` is called:\n//! 1. It only contains numbers between 1 and d.\n//! 2. The diagonal must contain the numbers 1, ..., d.\n//! 3. The diagonal entry of a column must not be contained in any\n//!    column further to the right.\n//! 4. The entries of a column must be contained in all columns to the left.\n//! 5. The proximity condition must hold: For all t = 1, ..., d - 2 and\n//!    e = 0, ..., d - t - 1 there must exist an index j > d, such that\n//!    `(M[t, e], {M[0, e], ..., M[t-1, e]})` equals either\n//!    `(M[d-j-1, j], {M[0, j], ..., M[t-1, j]})` or\n//!    `(M[t-1, j], {M[d-j-1, j], M[0, j], ..., M[t-2, j]})`.\n//!\n//! An R-vine array is said to be in natural order when the anti-diagonal\n//! entries are \\f$ 1, \\dots, d \\f$ (from left to right). The exemplary arrray\n//! above is in natural order. Any R-vine array can be characterized by the\n//! diagonal entries (called order) and the entries below the diagonal of the\n//! corresponding R-vine array in natural order. Since most algorithms work\n//! with the structure in natural order, this is how RVineStructure stores the\n//! structure internally.\nclass RVineStructure\n{\npublic:\n  explicit RVineStructure(\n    const size_t& d = static_cast<size_t>(1),\n    const size_t& trunc_lvl = std::numeric_limits<size_t>::max());\n  explicit RVineStructure(\n    const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& mat,\n    bool check = true);\n  explicit RVineStructure(\n    const std::vector<size_t>& order,\n    const size_t& trunc_lvl = std::numeric_limits<size_t>::max(),\n    bool check = true);\n  RVineStructure(const std::vector<size_t>& order,\n                 const TriangularArray<size_t>& struct_array,\n                 bool natural_order = false,\n                 bool check = true);\n  explicit RVineStructure(const std::string& filename, const bool check = true);\n  explicit RVineStructure(const nlohmann::json& input, const bool check = true);\n\n  nlohmann::json to_json() const;\n  void to_file(const std::string& filename) const;\n\n  size_t get_dim() const;\n  size_t get_trunc_lvl() const;\n  std::vector<size_t> get_order() const;\n  TriangularArray<size_t> get_struct_array(bool natural_order = false) const;\n  TriangularArray<size_t> get_min_array() const;\n  TriangularArray<short unsigned> get_needed_hfunc1() const;\n  TriangularArray<short unsigned> get_needed_hfunc2() const;\n  Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic> get_matrix() const;\n\n  size_t struct_array(size_t tree,\n                      size_t edge,\n                      bool natural_order = false) const;\n  size_t min_array(size_t tree, size_t edge) const;\n  bool needed_hfunc1(size_t tree, size_t edge) const;\n  bool needed_hfunc2(size_t tree, size_t edge) const;\n\n  void truncate(size_t trunc_lvl);\n  std::string str() const;\n\n  static RVineStructure simulate(size_t d,\n                                 bool natural_order = false,\n                                 std::vector<int> seeds = std::vector<int>());\n\nprotected:\n  size_t find_trunc_lvl(\n    const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& mat) const;\n  std::vector<size_t> get_order(\n    const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& mat) const;\n  TriangularArray<size_t> to_rvine_array(\n    const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& mat) const;\n\n  TriangularArray<size_t> to_natural_order() const;\n  static TriangularArray<size_t> make_dvine_struct_array(size_t d,\n                                                         size_t trunc_lvl);\n  static TriangularArray<size_t> make_cvine_struct_array(size_t d,\n                                                         size_t trunc_lvl);\n  TriangularArray<size_t> compute_min_array() const;\n  TriangularArray<short unsigned> compute_needed_hfunc1() const;\n  TriangularArray<short unsigned> compute_needed_hfunc2() const;\n\n  void check_if_quadratic(\n    const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& mat) const;\n  void check_lower_tri(\n    const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& mat) const;\n  void check_upper_tri() const;\n  void check_columns() const;\n  void check_antidiagonal() const;\n  void check_proximity_condition() const;\n\n  std::vector<size_t> order_;\n  size_t d_;\n  size_t trunc_lvl_;\n  TriangularArray<size_t> struct_array_;\n  TriangularArray<size_t> min_array_;\n  // can't use bool b/c the comittee messed up std::vector<bool>\n  TriangularArray<short unsigned> needed_hfunc1_;\n  TriangularArray<short unsigned> needed_hfunc2_;\n};\n\nstd::ostream&\noperator<<(std::ostream& os, const RVineStructure& rvs);\n\n//! @brief A class for D-vine structures.\n//!\n//! D-vines are a special class of R-vines where each tree is a path. A D-vine\n//! structure is determined entirely by the order of variables. For example, if\n//! the order is `(1, 2, 3, 4)`, the first tree in the vine is 1-2-3-4 and all\n//! further trees are unique due to the proximity condition.\n//!\n//! Note that `DVineStructure` objects inherit the methods and attributes of\n//! `RVineStructure` objects.\nclass DVineStructure : public RVineStructure\n{\npublic:\n  explicit DVineStructure(const std::vector<size_t>& order);\n  DVineStructure(const std::vector<size_t>& order, size_t trunc_lvl);\n};\n\n//! @brief A class for C-vine structures.\n//!\n//! C-vines are a special class of R-vines where each tree is a star. A C-vine\n//! structure is determined entirely by the order of variables. For example, if\n//! the order is `{1, 2, 3, 4}`, the first tree in the vine connects variable\n//! 4 with all others, the second tree connects variable 3 with all others,\n//! etc.\n//!\n//! Note that `CVineStructure` objects inherit the methods and attributes of\n//! `RVineStructure` objects.\nclass CVineStructure : public RVineStructure\n{\npublic:\n  explicit CVineStructure(const std::vector<size_t>& order);\n  CVineStructure(const std::vector<size_t>& order, size_t trunc_lvl);\n};\n}\n\n#include <vinecopulib/vinecop/implementation/rvine_structure.ipp>\n", "meta": {"hexsha": "fb45e1104784f517571526d6f43552391cad9ec4", "size": 7622, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/vinecopulib/vinecop/rvine_structure.hpp", "max_stars_repo_name": "tvatter/vinecoplib", "max_stars_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-05-05T13:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T23:40:01.000Z", "max_issues_repo_path": "include/vinecopulib/vinecop/rvine_structure.hpp", "max_issues_repo_name": "vinecopulib/vinecopulib", "max_issues_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 264.0, "max_issues_repo_issues_event_min_datetime": "2017-03-28T10:07:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T10:04:39.000Z", "max_forks_repo_path": "include/vinecopulib/vinecop/rvine_structure.hpp", "max_forks_repo_name": "tvatter/vinecoplib", "max_forks_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-04-24T13:54:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T16:56:17.000Z", "avg_line_length": 40.7593582888, "max_line_length": 80, "alphanum_fraction": 0.668590921, "num_tokens": 2055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177519, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5335240345369041}}
{"text": "//\n//  tmesh.hpp\n//\n//  Created by r. on 09/05/14\n//\n\n#ifndef round1_tmesh_hpp\n#define round1_tmesh_hpp\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <vector>\n\nnamespace spacetime\n{\n\tnamespace ublas = boost::numeric::ublas;\n\t\n\tclass tmesh : public ublas::vector<double>\n\t{\n\tpublic:\n\t\ttypedef ublas::vector<double> parent_type;\n\tpublic:\n\t\tstruct interval\n\t\t{\n\t\tpublic:\n\t\t\t// Should be hidden\n\t\t\tdouble a, b, len, mid;\n\t\tpublic:\n\t\t\tinterval(double a, double b) : a(a), b(b), len(b-a), mid((a+b)/2) {}\n\t\t};\n\tpublic:\n\t\tvoid\n\t\toperator=(const tmesh& m) {\n\t\t\tparent_type::resize(m.size());\n\t\t\tparent_type::assign(m);\n\t\t}\n\tpublic:\n\t\tbool isvalid() const\n\t\t{\n\t\t\tconst parent_type& x = (parent_type)(*this);\n\t\t\tif (x.empty()) return false;\n\t\t\tif (x.size() <= 1) return false;\n\t\t\tfor (unsigned int i = 1; i != x.size(); ++i)\n\t\t\t{\n\t\t\t\tif (!(x(i-1) <= x(i))) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\tpublic:\n\t\tunsigned int getni() const\n\t\t// Get the number of intervals\n\t\t{\n\t\t\tassert(isvalid());\n\t\t\tassert(size() >= 1);\n\t\t\treturn (unsigned int)(size() - 1);\n\t\t}\n\tpublic:\n\t\tvoid makeuniform(double a, double b, unsigned int nodes)\n\t\t{\n\t\t\tassert(nodes >= 2);\n\t\t\tparent_type y(nodes);\n\t\t\tfor (unsigned int n = 0; n != nodes; ++n)\n\t\t\t\ty[n] = a + n * ((b - a) / (nodes - 1));\n\t\t\tthis->swap(y);\n\t\t}\n\t\t\n\t\tvoid refine()\n\t\t{\n\t\t\tassert(isvalid());\n\t\t\tparent_type vrefd(1 + 2 * getni());\n\t\t\t{\n\t\t\t\tconst parent_type& x = (parent_type)(*this);\n\t\t\t\tunsigned int j = 0;\n\t\t\t\tvrefd(j++) = x(0);\n\t\t\t\tfor (unsigned int i = 1; i != x.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tvrefd(j++) = 0.5 * (x(i-1) + x(i));\n\t\t\t\t\tvrefd(j++) = x(i);\n\t\t\t\t}\n\t\t\t\tassert(j == vrefd.size());\n\t\t\t}\n\t\t\tthis->swap(vrefd);\n\t\t}\n\t\t\n\t\tinterval getI(unsigned int n) const\n\t\t// n-th subinterval, n >= 1\n\t\t{\n\t\t\tassert(isvalid());\n\t\t\tconst parent_type& x = (parent_type)(*this);\n\t\t\tassert((1 <= n) && (n < x.size()));\n\t\t\treturn interval(x(n-1), x(n));\n\t\t}\n\t\t\n\t\tstd::vector<interval> getIs() const\n\t\t// vector of all subintervals, canonically ordered\n\t\t{\n\t\t\tassert(isvalid());\n\t\t\tstd::vector<interval> Is;\n\t\t\t{\n\t\t\t\tconst parent_type& x = (parent_type)(*this);\n\t\t\t\tfor (unsigned int n = 1; n != x.size(); ++n)\n\t\t\t\t\tIs.push_back(interval(x(n-1), x(n)));\n\t\t\t}\n\t\t\treturn Is;\n\t\t}\n\t\n\t\t//namespace ublas = boost::numeric::ublas;\n\t\ttypedef ublas::compressed_matrix<double, ublas::row_major> sparse_matrix;\n\t\t//\n\t\tsparse_matrix\n\t\tnaive_prolongation_to() {\n\t\t\tconst tmesh& m = (*this);\n\t\t\t// Number of elements\n\t\t\tunsigned K = (m.size() - 1);\n\t\t\t// ... should be even\n\t\t\tassert((K % 2) == 0);\n\t\t\t// Number of elements on coarse mesh\n\t\t\tunsigned k = K / 2;\n\t\t\t\n\t\t\tunsigned nf = K+1;\n\t\t\tunsigned nc = k+1;\n\t\t\t\n\t\t\tublas::mapped_matrix<double> P(nf, nc);\n\t\t\t\n\t\t\t// Find coarse nodes\n\t\t\tfor (unsigned j = 0; j != nc; ++j) {\n\t\t\t\tunsigned i = 2 * j;\n\t\t\t\tif (j != 0) P(i-1, j) = 0.5;\n\t\t\t\tP(i+0, j) = 1;\n\t\t\t\tif (j+1 != nc) P(i+1, j) = 0.5;\n\t\t\t}\n\t\t\t\n\t\t\treturn P;\n\t\t}\n\t};\n}\n\n\n#endif\n", "meta": {"hexsha": "f889b738bbd31f1338801f528c9cab92d10ad2e0", "size": 2935, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "parawt/c++/include/tmesh.hpp", "max_stars_repo_name": "numpde/parabolic", "max_stars_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "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": "parawt/c++/include/tmesh.hpp", "max_issues_repo_name": "numpde/parabolic", "max_issues_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "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": "parawt/c++/include/tmesh.hpp", "max_forks_repo_name": "numpde/parabolic", "max_forks_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "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": 20.9642857143, "max_line_length": 75, "alphanum_fraction": 0.5649063032, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.533524034536904}}
{"text": "#ifndef MODEL_DISTRIBUTION_HPP\n#define MODEL_DISTRIBUTION_HPP\n\n#include \"gtest/gtest_prod.h\"\n#include \"types.hpp\"\n\n#include <algorithm>\n#include <boost/log/trivial.hpp>\n#include <numeric>\n#include <random>\n#include <unordered_map>\n#include <utility>\n\nnamespace FilterModel {\n\n/**\n * Represents the probability distribution encoded by the latent variable model adapted from in\n * Perkins et al.\n */\nclass ModelDistribution {\n   public:\n    /**\n     * Constructs a new ModelDistribution object from a vector of category counts.\n     *\n     * Arguments:\n     *  data - vector of category counts\n     *  generator - random number generator\n     *  comparison - test parameter, should usually ignore. If true, runs both exact and approximate\n     *    methods for evaluating the probability, compares them, and stops the program if the\n     *    estimates are too far apart.\n     */\n    ModelDistribution(const std::vector<category_counts_t> &data,\n                      std::default_random_engine &generator, const Options &options);\n\n    /**\n     * Calculates log(p(k | alpha, epsilon, delta)) for every object in the data for every value\n     * of alpha in alphas_per_object for that object. Returns a vector over objects of vectors\n     * over log conditional probabilities per value of alpha.\n     *\n     * For example, if alphas_per_object = {{{1,0}}, {0,1}}, {{1,0}},\n     * {{1,0}, {0,1}, {1, 1}} then the output might be {{-2, -8}, {-7}, {-1.2,\n     * -2.1, -5.7}} where {-2, -8} are the log conditional probabilities for alpha={1,0} and\n     * alpha={0,1} for the first object.\n     */\n    std::vector<std::vector<double>> distribution(\n        const std::vector<std::vector<alpha_t>> &alphas_per_object, double epsilon,\n        const delta_t &delta) const;\n\n    /**\n     * Calculates log(p(k | alpha, epsilon, delta)) for every object in the data for the given\n     * alpha. Returns a vector over objects of vectors over log conditional probabilities per value\n     * of alpha.\n     *\n     * For example, if alphas = {{0,1,0}, {1,1,1}} then the output might be {{-2, -7}, {-4, -5}}\n     * where log(p(k | alpha={0,1,0}, ...)) = -2 for the first object,\n     * log(p(k | alpha={0,1,0}, ...)) = -4 for the second obect, log(p(k | alpha={1,1,1}, ...)) = -7\n     * for the first object, and so on.\n     */\n    std::vector<std::vector<double>> distribution(const std::vector<alpha_t> &alphas,\n                                                  double epsilon, const delta_t &delta) const;\n\n    // The following are public only so I can test them easier. FRIEND_TEST exists, but it doesn't\n    // work right for static methods.\n\n    static double calculate_log_p_k_positive_given_alpha_n_positive(int n_positive,\n                                                                    const alpha_t &alpha);\n    // This is non-static only so it has access to the comparison testing parameter.\n    double calculate_log_sum_over_k_negative(int n_positive, int n_negative, const alpha_t &alpha,\n                                             const delta_t &delta,\n                                             const category_counts_t &object_counts) const;\n    static double calculate_sum_over_k_negative_exact(int n_positive, int n_negative,\n                                                      const alpha_t &alpha, const delta_t &delta,\n                                                      const category_counts_t &object_counts);\n\n    // Uses MVI3 integration\n    static double calculate_sum_over_k_negative_approx(int n_positive, int n_negative,\n                                                       const alpha_t &alpha, const delta_t &delta,\n                                                       const category_counts_t &object_counts);\n    /**\n     * Given n^+, n^-, alpha, and k, loop over all possible values for k^-, and call f() on each.\n     *\n     * This is hard-coded for |alpha|=3. Doing this in a generic way was incredibly slow.\n     */\n    static void iterate_over_k_negatives(std::function<void(int, int, int)> f, int n_positive,\n                                         int n_negative, const alpha_t &alpha,\n                                         const category_counts_t &object_counts);\n\n    /**\n     * Removes components of v for which alpha_i has the wrong value.\n     */\n    template <class T>\n    static std::vector<T> filter_by_alpha(const alpha_t &alpha, const std::vector<T> &v,\n                                          const bool value = true) {\n        assert(alpha.size() == v.size());\n\n        std::vector<T> filtered;\n        for (int i = 0; i < alpha.size(); ++i) {\n            if (alpha.at(i) == value) {\n                filtered.push_back(v.at(i));\n            }\n        }\n        return filtered;\n    }\n\n   private:\n    const std::vector<category_counts_t> &data;\n    const Options options;\n    std::default_random_engine &generator;\n\n    /**\n     * Test for if using a normal approximation (and mvi3 integration) is permissible.\n     *\n     * There is no real standard for when the multinomial to multivariate guassian approximation\n     * is valid, so we adapt the standard binomial to guassian rule, which is that there is a\n     * mean of at least 5 elements in every dimension.\n     *\n     * TODO(joschnei): Verify experimentally that this is a good heuristic.\n     */\n    bool can_use_normal_approx(int n_negative, const delta_t &delta) const;\n\n    // The below are currently not in use beacuse of randomness problems.\n\n    // Uses naive Monte-Carlo integration\n    double calculate_sum_over_k_negative_approx_2(int n_positive, int n_negative,\n                                                  const alpha_t &alpha, const delta_t &delta,\n                                                  const category_counts_t &object_counts);\n    /**\n     * Creates a hyperplane array representing the constraints on k_minus for use in mvi3\n     * integration.\n     *\n     * Each of the four constraints on k_negative can be represented as a set of linear\n     * inequalities in the values of k_negative. This function creates those linear equalities\n     * so that they can be passed as constraints to mvi3, a method for integrating a multinomial\n     * pdf over a convex set. See function defintion for details of the exact constraints.\n     */\n    static std::vector<std::vector<double>> get_hyperplanes(int n_negative,\n                                                            category_counts_t object_counts);\n};\n}  // namespace FilterModel\n\n#endif", "meta": {"hexsha": "14c27e99717e0d1a3b7f5548551da4ccbed4378b", "size": 6481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/model_distribution.hpp", "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++/model_distribution.hpp", "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++/model_distribution.hpp", "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": 45.9645390071, "max_line_length": 100, "alphanum_fraction": 0.6102453325, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.533524021982168}}
{"text": "// Copyright Andr\u00e1s Vukics 2006\u20132020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n/*\n\nThe example demonstrates the use of LAPACK (via FLENS) with different\nstorage orders. Note that column major ordering of A is equivalent to\nrow major ordering of A^T.\n\nright eigen:\n\nA v = lambda v\n\nleft eigen:\n\nu^H A = lambda u^H\n\n\n      | A | A^T\n----------------\nleft  | u | v^* \n----------------\nright | v | u^* \n----------------\n\n*/\n\n\n#include \"Blitz2FLENS.h\"\n\n#include \"MathExtensions.h\"\n#include \"BlitzTiny.h\"\n#include \"ComplexArrayExtensions.tcc\"\n#include \"Randomized.h\"\n\n#include \"Range.h\"\n\n#define BOOST_TEST_MODULE Blitz2FLENS test\n#include <boost/test/unit_test.hpp>\n\n#include <boost/bind.hpp>\n\n\nusing namespace std;\nusing namespace randomized;\nusing namespace blitz2flens;\nusing namespace blitzplusplus;\nusing namespace mathutils;\n\nusing blitz::ColumnMajorArray;\n\nconst double epsilonCmp=1e-12;\n\nconst int RANK=3;\n\n\ntypedef CArray<  RANK> CAR ;\ntypedef DArray<  RANK> DAR ;\ntypedef CArray<2*RANK> CA2R;\n\n\ntypedef DenseVectorMF<dcomp >::type CDenseVector;\ntypedef DenseVectorMF<double>::type DDenseVector;\ntypedef GeMatrixMF<dcomp,RowMajor>::type GeMatrixRM;\ntypedef GeMatrixMF<dcomp,ColMajor>::type GeMatrixCM;\n\ntypedef HeMatrixMF<RowMajor>::type HeMatrixRM;\n\n\nRandomized::Ptr ran(MakerGSL()(1001));\n\nExtTiny<RANK> dims(6,4,5);\n\n\n// RowMajor, C/C++Array\n\nBOOST_AUTO_TEST_CASE( RowMajorTest )\n{\n  CAR  vecBlitz(dims);\n  CA2R matBlitz(concatenateTinies(dims,dims));\n  CA2R vlBlitz(matBlitz.shape()), vrBlitz(matBlitz.shape());\n\n  CDenseVector vecFLENS(blitz2flens::vector(vecBlitz));\n\n  GeMatrixRM\n    vlFLENS(matrix<RowMajor>(vlBlitz)),\n    vrFLENS(matrix<RowMajor>(vrBlitz));\n\n\n  fillWithRandom(matBlitz,ran);\n\n  {\n    CA2R a(matBlitz.copy());\n    GeMatrixRM aFLENS(matrix<RowMajor>(a));\n    cerr<<\"Entering ev routine ... \"; BOOST_CHECK(!ev(true,true,aFLENS,vecFLENS,vlFLENS,vrFLENS)); cerr<<\"exiting, checking result ... \";\n  }\n\n  {\n    CA2R resTensor(matBlitz.shape());\n    CArray<9> temp9(concatenateTinies(matBlitz.shape(),dims));\n    {\n      using namespace blitz::tensor;\n      temp9=matBlitz(i,j,k,o,p,q)*conj(vlBlitz(l,m,n,o,p,q))/vecBlitz(l,m,n);\n      resTensor=CA2R(sum(sum(sum(temp9,q),p),o));\n\n      BOOST_CHECK(!fcmp(1-max(abs(vlBlitz.transpose(3,4,5,0,1,2)-conj(resTensor))),1,epsilonCmp));\n\n      temp9=matBlitz(o,p,q,i,j,k)*vrBlitz(l,m,n,o,p,q)/vecBlitz(l,m,n);\n      resTensor=CA2R(sum(sum(sum(temp9,q),p),o));\n    }\n    BOOST_CHECK(!fcmp(1-max(abs(vrBlitz.transpose(3,4,5,0,1,2)-resTensor)),1,epsilonCmp));\n\n    cerr<<\"Nonsymmetric eigenproblem in RowMajor OK!\\n\";\n\n  }\n}\n\n\n// ColMajor, FortranArray\n\nBOOST_AUTO_TEST_CASE( ColMajorTest )\n{\n  CAR  vecBlitz(dims,ColumnMajorArray<RANK>());\n  CA2R matBlitz(concatenateTinies(dims,dims),ColumnMajorArray<2*RANK>());\n  CA2R vlBlitz(matBlitz.shape(),ColumnMajorArray<2*RANK>()), vrBlitz(matBlitz.shape(),ColumnMajorArray<2*RANK>());\n\n  CDenseVector vecFLENS(blitz2flens::vector(vecBlitz));\n\n  GeMatrixCM\n    vlFLENS(matrix<ColMajor>(vlBlitz)),\n    vrFLENS(matrix<ColMajor>(vrBlitz));\n\n\n  fillWithRandom(matBlitz,ran);\n    \n  {\n    CA2R a(matBlitz.copy());\n    GeMatrixCM aFLENS(matrix<ColMajor>(a));\n    \n    cerr<<\"Entering ev routine ... \"; BOOST_CHECK(!ev(true,true,aFLENS,vecFLENS,vlFLENS,vrFLENS)); cerr<<\"exiting, checking result ... \";\n  }\n\n  {\n    CA2R resTensor(matBlitz.shape());\n    CArray<9> temp9(concatenateTinies(matBlitz.shape(),dims));\n    {\n      using namespace blitz::tensor;\n      temp9=matBlitz(i,j,k,o,p,q)*vrBlitz(o,p,q,l,m,n)/vecBlitz(l,m,n);\n      resTensor=CA2R(sum(sum(sum(temp9,q),p),o));\n\n      BOOST_CHECK(!fcmp(1-max(abs(vrBlitz-resTensor)),1,epsilonCmp));\n\n      temp9=matBlitz(o,p,q,i,j,k)*conj(vlBlitz(o,p,q,l,m,n))/vecBlitz(l,m,n);\n      resTensor=CA2R(sum(sum(sum(temp9,q),p),o));\n    }\n\n    BOOST_CHECK(!fcmp(1-max(abs(vlBlitz-conj(resTensor))),1,epsilonCmp));\n\n    cerr<<\"\\\"                            ColMajor OK!\\n\";\n\n  }\n}\n\n\n\nBOOST_AUTO_TEST_CASE( HermitianTest )\n{\n  CAR  vecBlitz1(dims);\n  DAR  vecBlitz2(dims);\n  CA2R matBlitz(concatenateTinies(dims,dims));\n\n  fillWithRandom(matBlitz,ran);\n\n  matBlitz+=hermitianConjugate(matBlitz);\n    \n  {\n    CA2R a(matBlitz.copy());\n\n    CDenseVector vecFLENS(blitz2flens::vector(vecBlitz1));\n    GeMatrixRM aFLENS(matrix<RowMajor>(a));\n    \n    cerr<<\"Entering ev routine ... \"; ev(false,false,aFLENS,vecFLENS,aFLENS,aFLENS); cerr<<\"exiting, checking result ... \";\n  }\n  BOOST_CHECK(!fcmp(1-max(abs(imag(vecBlitz1))),1,epsilonCmp));\n  cerr<<\"Hermitian eigenproblem eigenvalues all real.\\n\";\n\n  {\n    CA2R a(matBlitz.copy());\n\n    DDenseVector vecFLENS(blitz2flens::vector(vecBlitz2));\n    HeMatrixRM aFLENS(hermitianMatrix<RowMajor>(a));\n    \n    cerr<<\"Entering ev routine ... \"; ev(true,aFLENS,vecFLENS); cerr<<\"exiting, checking result ... \";\n\n    {\n      CA2R resTensor(matBlitz.shape());\n      CArray<9> temp9(concatenateTinies(matBlitz.shape(),dims));\n      {\n        using namespace blitz::tensor;\n        temp9=matBlitz(o,p,q,i,j,k)*a(l,m,n,o,p,q)/vecBlitz2(l,m,n);\n        resTensor=CA2R(sum(sum(sum(temp9,q),p),o));\n          \n        BOOST_CHECK(!fcmp(1-max(abs(a.transpose(3,4,5,0,1,2)-resTensor)),1,epsilonCmp));\n          \n      }\n\n    }\n\n  }\n\n  cerr<<\"\\\"                      eigenproblem OK.\\n\";\n\n  std::sort(vecBlitz1.data(),vecBlitz1.data()+vecBlitz1.size(),realCompare);\n\n  // note: vecBlitz2 is already sorted\n\n  BOOST_CHECK(!fcmp(1-max(abs(vecBlitz2-real(vecBlitz1))),1,epsilonCmp));\n\n  cerr<<\"Hermitian eigenproblem eigenvalues match.\\n\";\n\n}\n\n", "meta": {"hexsha": "37f1c24445b2e6f5cd867fcab575f393208aecba", "size": 5563, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CPPQEDutils/testsuite/Blitz2FLENS.cc", "max_stars_repo_name": "bartoszek/cppqed", "max_stars_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T14:00:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T15:12:11.000Z", "max_issues_repo_path": "CPPQEDutils/testsuite/Blitz2FLENS.cc", "max_issues_repo_name": "bartoszek/cppqed", "max_issues_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-04-14T11:18:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T20:11:23.000Z", "max_forks_repo_path": "CPPQEDutils/testsuite/Blitz2FLENS.cc", "max_forks_repo_name": "bartoszek/cppqed", "max_forks_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T10:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T18:29:01.000Z", "avg_line_length": 25.1719457014, "max_line_length": 137, "alphanum_fraction": 0.6717598418, "num_tokens": 1744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5335240174065862}}
{"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// *** System\n//\n#include <iostream>\n\n//\n// *** Boost\n//\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n//\n// *** ViennaCL\n//\n//#define VIENNACL_DEBUG_ALL\n#define VIENNACL_WITH_UBLAS 1\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n#include \"viennacl/linalg/direct_solve.hpp\"\n#include \"viennacl/linalg/lu.hpp\"\n#include \"examples/tutorial/Random.hpp\"\n\n//\n// -------------------------------------------------------------\n//\nusing namespace boost::numeric;\n//\n// -------------------------------------------------------------\n//\ntemplate<typename ScalarType>\nScalarType diff(ScalarType & s1, viennacl::scalar<ScalarType> & s2)\n{\n   viennacl::backend::finish();\n   if (s1 != s2)\n      return 1;\n   return 0;\n}\n\ntemplate<typename ScalarType, typename VCLVectorType>\nScalarType diff(ublas::vector<ScalarType> const & v1, VCLVectorType const & v2)\n{\n   ublas::vector<ScalarType> v2_cpu(v2.size());\n   viennacl::backend::finish();  //workaround for a bug in APP SDK 2.7 on Trinity APUs (with Catalyst 12.8)\n   viennacl::copy(v2.begin(), v2.end(), v2_cpu.begin());\n\n   for (unsigned int i=0;i<v1.size(); ++i)\n   {\n      if (v2_cpu[i] != v1[i])\n        return 1;\n   }\n\n   return 0;\n}\n\ntemplate<typename ScalarType, typename VCLMatrixType>\nScalarType diff(ublas::matrix<ScalarType> const & mat1, VCLMatrixType const & mat2)\n{\n   ublas::matrix<ScalarType> mat2_cpu(mat2.size1(), mat2.size2());\n   viennacl::backend::finish();  //workaround for a bug in APP SDK 2.7 on Trinity APUs (with Catalyst 12.8)\n   viennacl::copy(mat2, mat2_cpu);\n\n    for (unsigned int i = 0; i < mat2_cpu.size1(); ++i)\n    {\n      for (unsigned int j = 0; j < mat2_cpu.size2(); ++j)\n      {\n         if (mat2_cpu(i,j) != mat1(i,j))\n           return 1;\n      }\n    }\n   //std::cout << ret << std::endl;\n   return 0;\n}\n//\n// -------------------------------------------------------------\n//\n\ntemplate<typename NumericT,\n          typename UblasMatrixType, typename UblasVectorType,\n          typename VCLMatrixType, typename VCLVectorType1, typename VCLVectorType2>\nint test_prod_rank1(UblasMatrixType & ublas_m1, UblasVectorType & ublas_v1, UblasVectorType & ublas_v2,\n                    VCLMatrixType & vcl_m1, VCLVectorType1 & vcl_v1, VCLVectorType2 & vcl_v2)\n{\n   int retval = EXIT_SUCCESS;\n\n   // sync data:\n   ublas_v1 = ublas::scalar_vector<NumericT>(ublas_v1.size(), NumericT(2));\n   ublas_v2 = ublas::scalar_vector<NumericT>(ublas_v2.size(), NumericT(3));\n   viennacl::copy(ublas_v1.begin(), ublas_v1.end(), vcl_v1.begin());\n   viennacl::copy(ublas_v2.begin(), ublas_v2.end(), vcl_v2.begin());\n   viennacl::copy(ublas_m1, vcl_m1);\n\n   // --------------------------------------------------------------------------\n   std::cout << \"Rank 1 update\" << std::endl;\n\n   ublas_m1 += ublas::outer_prod(ublas_v1, ublas_v2);\n   vcl_m1 += viennacl::linalg::outer_prod(vcl_v1, vcl_v2);\n   if ( diff(ublas_m1, vcl_m1) != 0 )\n   {\n      std::cout << \"# Error at operation: rank 1 update\" << std::endl;\n      std::cout << \"  diff: \" << diff(ublas_m1, vcl_m1) << std::endl;\n      return EXIT_FAILURE;\n   }\n\n\n\n   // --------------------------------------------------------------------------\n   std::cout << \"Scaled rank 1 update - CPU Scalar\" << std::endl;\n   ublas_m1 += NumericT(4) * ublas::outer_prod(ublas_v1, ublas_v2);\n   vcl_m1 += NumericT(2) * viennacl::linalg::outer_prod(vcl_v1, vcl_v2);\n   vcl_m1 += viennacl::linalg::outer_prod(vcl_v1, vcl_v2) * NumericT(2);  //check proper compilation\n   if ( diff(ublas_m1, vcl_m1) != 0 )\n   {\n      std::cout << \"# Error at operation: scaled rank 1 update - CPU Scalar\" << std::endl;\n      std::cout << \"  diff: \" << diff(ublas_m1, vcl_m1) << std::endl;\n      return EXIT_FAILURE;\n   }\n\n      // --------------------------------------------------------------------------\n   std::cout << \"Scaled rank 1 update - GPU Scalar\" << std::endl;\n   ublas_m1 += NumericT(4) * ublas::outer_prod(ublas_v1, ublas_v2);\n   vcl_m1 += viennacl::scalar<NumericT>(2) * viennacl::linalg::outer_prod(vcl_v1, vcl_v2);\n   vcl_m1 += viennacl::linalg::outer_prod(vcl_v1, vcl_v2) * viennacl::scalar<NumericT>(2);  //check proper compilation\n   if ( diff(ublas_m1, vcl_m1) != 0 )\n   {\n      std::cout << \"# Error at operation: scaled rank 1 update - GPU Scalar\" << std::endl;\n      std::cout << \"  diff: \" << diff(ublas_m1, vcl_m1) << std::endl;\n      return EXIT_FAILURE;\n   }\n\n   //reset vcl_matrix:\n   viennacl::copy(ublas_m1, vcl_m1);\n\n   // --------------------------------------------------------------------------\n   std::cout << \"Matrix-Vector product\" << std::endl;\n   ublas_v1 = viennacl::linalg::prod(ublas_m1, ublas_v2);\n   vcl_v1   = viennacl::linalg::prod(vcl_m1, vcl_v2);\n\n   if ( diff(ublas_v1, vcl_v1) != 0 )\n   {\n      std::cout << \"# Error at operation: matrix-vector product\" << std::endl;\n      std::cout << \"  diff: \" << diff(ublas_v1, vcl_v1) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n   // --------------------------------------------------------------------------\n   std::cout << \"Matrix-Vector product with scaled add\" << std::endl;\n   NumericT alpha = static_cast<NumericT>(2);\n   NumericT beta = static_cast<NumericT>(3);\n   viennacl::copy(ublas_v1.begin(), ublas_v1.end(), vcl_v1.begin());\n   viennacl::copy(ublas_v2.begin(), ublas_v2.end(), vcl_v2.begin());\n\n   ublas_v1 = alpha * viennacl::linalg::prod(ublas_m1, ublas_v2) + beta * ublas_v1;\n   vcl_v1   = alpha * viennacl::linalg::prod(vcl_m1, vcl_v2) + beta * vcl_v1;\n\n   if ( diff(ublas_v1, vcl_v1) != 0 )\n   {\n      std::cout << \"# Error at operation: matrix-vector product with scaled additions\" << std::endl;\n      std::cout << \"  diff: \" << diff(ublas_v1, vcl_v1) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n   // --------------------------------------------------------------------------\n\n   viennacl::copy(ublas_v1.begin(), ublas_v1.end(), vcl_v1.begin());\n   viennacl::copy(ublas_v2.begin(), ublas_v2.end(), vcl_v2.begin());\n\n   std::cout << \"Transposed Matrix-Vector product\" << std::endl;\n   ublas_v2 = alpha * viennacl::linalg::prod(trans(ublas_m1), ublas_v1);\n   vcl_v2   = alpha * viennacl::linalg::prod(trans(vcl_m1), vcl_v1);\n\n   if ( diff(ublas_v2, vcl_v2) != 0 )\n   {\n      std::cout << \"# Error at operation: transposed matrix-vector product\" << std::endl;\n      std::cout << \"  diff: \" << diff(ublas_v2, vcl_v2) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n\n   std::cout << \"Transposed Matrix-Vector product with scaled add\" << std::endl;\n   ublas_v2 = alpha * viennacl::linalg::prod(trans(ublas_m1), ublas_v1) + beta * ublas_v2;\n   vcl_v2   = alpha * viennacl::linalg::prod(trans(vcl_m1), vcl_v1) + beta * vcl_v2;\n\n   if ( diff(ublas_v2, vcl_v2) != 0 )\n   {\n      std::cout << \"# Error at operation: transposed matrix-vector product with scaled additions\" << std::endl;\n      std::cout << \"  diff: \" << diff(ublas_v2, vcl_v2) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n   // --------------------------------------------------------------------------\n\n   return retval;\n}\n\n\n//\n// -------------------------------------------------------------\n//\ntemplate< typename NumericT, typename F>\nint test()\n{\n   int retval = EXIT_SUCCESS;\n\n   std::size_t num_rows = 141;\n   std::size_t num_cols = 103;\n\n   // --------------------------------------------------------------------------\n   ublas::vector<NumericT> ublas_v1(num_rows);\n   for (std::size_t i = 0; i < ublas_v1.size(); ++i)\n     ublas_v1(i) = NumericT(i);\n   ublas::vector<NumericT> ublas_v2 = ublas::scalar_vector<NumericT>(num_cols, NumericT(3));\n\n\n   ublas::matrix<NumericT> ublas_m1(ublas_v1.size(), ublas_v2.size());\n   ublas::matrix<NumericT> ublas_m2(ublas_v1.size(), ublas_v1.size());\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n\n   for (std::size_t i = 0; i < ublas_m2.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m2.size2(); ++j)\n       ublas_m2(i,j) = NumericT(j - i*j + i);\n\n\n   viennacl::vector<NumericT> vcl_v1_native(ublas_v1.size());\n   viennacl::vector<NumericT> vcl_v1_large(4 * ublas_v1.size());\n   viennacl::vector_range< viennacl::vector<NumericT> > vcl_v1_range(vcl_v1_large, viennacl::range(3, ublas_v1.size() + 3));\n   viennacl::vector_slice< viennacl::vector<NumericT> > vcl_v1_slice(vcl_v1_large, viennacl::slice(2, 3, ublas_v1.size()));\n\n   viennacl::vector<NumericT> vcl_v2_native(ublas_v2.size());\n   viennacl::vector<NumericT> vcl_v2_large(4 * ublas_v2.size());\n   viennacl::vector_range< viennacl::vector<NumericT> > vcl_v2_range(vcl_v2_large, viennacl::range(8, ublas_v2.size() + 8));\n   viennacl::vector_slice< viennacl::vector<NumericT> > vcl_v2_slice(vcl_v2_large, viennacl::slice(6, 2, ublas_v2.size()));\n\n   viennacl::matrix<NumericT, F> vcl_m1_native(ublas_m1.size1(), ublas_m1.size2());\n   viennacl::matrix<NumericT, F> vcl_m1_large(4 * ublas_m1.size1(), 4 * ublas_m1.size2());\n   viennacl::matrix_range< viennacl::matrix<NumericT, F> > vcl_m1_range(vcl_m1_large,\n                                                                        viennacl::range(8, ublas_m1.size1() + 8),\n                                                                        viennacl::range(ublas_m1.size2(), 2 * ublas_m1.size2()) );\n   viennacl::matrix_slice< viennacl::matrix<NumericT, F> > vcl_m1_slice(vcl_m1_large,\n                                                                        viennacl::slice(6, 2, ublas_m1.size1()),\n                                                                        viennacl::slice(ublas_m1.size2(), 2, ublas_m1.size2()) );\n\n   viennacl::matrix<NumericT, F> vcl_m2_native(ublas_m2.size1(), ublas_m2.size2());\n   viennacl::matrix<NumericT, F> vcl_m2_large(4 * ublas_m2.size1(), 4 * ublas_m2.size2());\n   viennacl::matrix_range< viennacl::matrix<NumericT, F> > vcl_m2_range(vcl_m2_large,\n                                                                        viennacl::range(8, ublas_m2.size1() + 8),\n                                                                        viennacl::range(ublas_m2.size2(), 2 * ublas_m2.size2()) );\n   viennacl::matrix_slice< viennacl::matrix<NumericT, F> > vcl_m2_slice(vcl_m2_large,\n                                                                        viennacl::slice(6, 2, ublas_m2.size1()),\n                                                                        viennacl::slice(ublas_m2.size2(), 2, ublas_m2.size2()) );\n\n\n   //\n   // Run a bunch of tests for rank-1-updates, matrix-vector products\n   //\n   std::cout << \"------------ Testing rank-1-updates and matrix-vector products ------------------\" << std::endl;\n\n   std::cout << \"* m = full, v1 = full, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_native, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = full, v1 = full, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_native, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = full, v1 = full, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_native, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   // v1 = range\n\n\n   std::cout << \"* m = full, v1 = range, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_range, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = full, v1 = range, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_range, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = full, v1 = range, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_range, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n\n   // v1 = slice\n\n   std::cout << \"* m = full, v1 = slice, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_slice, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = full, v1 = slice, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_slice, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = full, v1 = slice, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_slice, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   ///////////////////////////// matrix_range\n\n   std::cout << \"* m = range, v1 = full, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_native, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = range, v1 = full, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_native, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = range, v1 = full, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_native, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   // v1 = range\n\n\n   std::cout << \"* m = range, v1 = range, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_range, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = range, v1 = range, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_range, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = range, v1 = range, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_range, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n\n   // v1 = slice\n\n   std::cout << \"* m = range, v1 = slice, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_slice, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = range, v1 = slice, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_slice, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = range, v1 = slice, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_slice, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   ///////////////////////////// matrix_slice\n\n   std::cout << \"* m = slice, v1 = full, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_native, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = slice, v1 = full, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_native, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = slice, v1 = full, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_native, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   // v1 = range\n\n\n   std::cout << \"* m = slice, v1 = range, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_range, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = slice, v1 = range, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_range, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = slice, v1 = range, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_range, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   // v1 = slice\n\n   std::cout << \"* m = slice, v1 = slice, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_slice, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n\n   std::cout << \"* m = slice, v1 = slice, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_slice, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n    for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n      ublas_m1(i,j) = NumericT(i+j);\n\n   std::cout << \"* m = slice, v1 = slice, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_slice, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   return retval;\n}\n//\n// -------------------------------------------------------------\n//\nint main()\n{\n   std::cout << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << \"## Test :: Matrix\" << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << std::endl;\n\n   int retval = EXIT_SUCCESS;\n\n   std::cout << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << std::endl;\n   {\n      typedef int NumericT;\n      std::cout << \"# Testing setup:\" << std::endl;\n      std::cout << \"  numeric: int\" << std::endl;\n      std::cout << \"  layout: row-major\" << std::endl;\n      retval = test<NumericT, viennacl::row_major>();\n      if ( retval == EXIT_SUCCESS )\n         std::cout << \"# Test passed\" << std::endl;\n      else\n         return retval;\n   }\n   std::cout << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << std::endl;\n   {\n      typedef int NumericT;\n      std::cout << \"# Testing setup:\" << std::endl;\n      std::cout << \"  numeric: int\" << std::endl;\n      std::cout << \"  layout: column-major\" << std::endl;\n      retval = test<NumericT, viennacl::column_major>();\n      if ( retval == EXIT_SUCCESS )\n         std::cout << \"# Test passed\" << std::endl;\n      else\n         return retval;\n   }\n   std::cout << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << std::endl;\n\n\n#ifdef VIENNACL_WITH_OPENCL\n   if ( viennacl::ocl::current_device().double_support() )\n#endif\n   {\n      {\n         typedef long NumericT;\n         std::cout << \"# Testing setup:\" << std::endl;\n         std::cout << \"  numeric: double\" << std::endl;\n         std::cout << \"  layout: row-major\" << std::endl;\n         retval = test<NumericT, viennacl::row_major>();\n            if ( retval == EXIT_SUCCESS )\n               std::cout << \"# Test passed\" << std::endl;\n            else\n              return retval;\n      }\n      std::cout << std::endl;\n      std::cout << \"----------------------------------------------\" << std::endl;\n      std::cout << std::endl;\n      {\n         typedef long NumericT;\n         std::cout << \"# Testing setup:\" << std::endl;\n         std::cout << \"  numeric: double\" << std::endl;\n         std::cout << \"  layout: column-major\" << std::endl;\n         retval = test<NumericT, viennacl::column_major>();\n            if ( retval == EXIT_SUCCESS )\n               std::cout << \"# Test passed\" << std::endl;\n            else\n              return retval;\n      }\n      std::cout << std::endl;\n      std::cout << \"----------------------------------------------\" << std::endl;\n      std::cout << std::endl;\n   }\n\n   std::cout << std::endl;\n   std::cout << \"------- Test completed --------\" << std::endl;\n   std::cout << std::endl;\n\n\n   return retval;\n}\n", "meta": {"hexsha": "0ce31580afe60aa204e861f85b06d1b3bb8e02c1", "size": 29326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/matrix_vector_int.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": "tests/src/matrix_vector_int.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": "tests/src/matrix_vector_int.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": 35.5898058252, "max_line_length": 130, "alphanum_fraction": 0.5221987315, "num_tokens": 9100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5335240140030132}}
{"text": "// Copyright John Maddock 2014.\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// Caution: this file contains Quickbook markup as well as code\r\n// and comments, don't change any of the special comment markups!\r\n\r\n#ifdef _MSC_VER\r\n#  pragma warning (disable : 4996) // disable -D_SCL_SECURE_NO_WARNINGS C++ 'Checked Iterators'\r\n#endif\r\n\r\n#include <boost/math/distributions/hyperexponential.hpp>\r\n#include <iostream>\r\n\r\n#ifndef BOOST_NO_CXX11_HDR_ARRAY\r\n#include <array>\r\n#endif\r\n\r\nint main()\r\n{\r\n   {\r\n//[hyperexponential_snip1\r\n//=#include <boost/math/distributions/hyperexponential.hpp>\r\n//=#include <iostream>\r\n//=int main()\r\n//={\r\n   const double rates[] = { 1.0 / 10.0, 1.0 / 12.0 };\r\n\r\n   boost::math::hyperexponential he(rates);\r\n\r\n   std::cout << \"Average lifetime: \"\r\n      << boost::math::mean(he)\r\n      << \" years\" << std::endl;\r\n   std::cout << \"Probability that the appliance will work for more than 15 years: \"\r\n      << boost::math::cdf(boost::math::complement(he, 15.0))\r\n      << std::endl;\r\n//=}\r\n//]\r\n   }\r\n   using namespace boost::math;\r\n#ifndef BOOST_NO_CXX11_HDR_ARRAY\r\n   {\r\n   //[hyperexponential_snip2\r\n   std::array<double, 2> phase_prob = { 0.5, 0.5 };\r\n   std::array<double, 2> rates = { 1.0 / 10, 1.0 / 12 };\r\n\r\n   hyperexponential he(phase_prob.begin(), phase_prob.end(), rates.begin(), rates.end());\r\n   //]\r\n   }\r\n\r\n   {\r\n   //[hyperexponential_snip3\r\n   // We could be using any standard library container here... vector, deque, array, list etc:\r\n   std::array<double, 2> phase_prob = { 0.5, 0.5 };\r\n   std::array<double, 2> rates      = { 1.0 / 10, 1.0 / 12 };\r\n\r\n   hyperexponential he1(phase_prob, rates);    // Construct from standard library container.\r\n\r\n   double phase_probs2[] = { 0.5, 0.5 };\r\n   double rates2[]       = { 1.0 / 10, 1.0 / 12 };\r\n\r\n   hyperexponential he2(phase_probs2, rates2);  // Construct from native C++ array.\r\n   //]\r\n   }\r\n   {\r\n   //[hyperexponential_snip4\r\n   // We could be using any standard library container here... vector, deque, array, list etc:\r\n   std::array<double, 2> rates = { 1.0 / 10, 1.0 / 12 };\r\n\r\n   hyperexponential he(rates.begin(), rates.end());\r\n\r\n   assert(he.probabilities()[0] == 0.5); // Phase probabilities will be equal and normalised to unity.\r\n   //]\r\n   }\r\n   {\r\n   //[hyperexponential_snip5\r\n   std::array<double, 2> rates = { 1.0 / 10, 1.0 / 12 };\r\n\r\n   hyperexponential he(rates);\r\n\r\n   assert(he.probabilities()[0] == 0.5); // Phase probabilities will be equal and normalised to unity.\r\n   //]\r\n   }\r\n#endif\r\n#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST) && !(defined(BOOST_GCC_VERSION) && (BOOST_GCC_VERSION < 40500))\r\n   {\r\n   //[hyperexponential_snip6\r\n   hyperexponential he = { { 0.5, 0.5 }, { 1.0 / 10, 1.0 / 12 } };\r\n   //]\r\n   }\r\n   {\r\n   //[hyperexponential_snip7\r\n   hyperexponential he = { 1.0 / 10, 1.0 / 12 };\r\n\r\n   assert(he.probabilities()[0] == 0.5);\r\n   //]\r\n   }\r\n#endif\r\n   return 0;\r\n}\r\n", "meta": {"hexsha": "6051c0678998e1700cad3092ed70cb4405051bfe", "size": 3066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/hyperexponential_snips.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/hyperexponential_snips.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/hyperexponential_snips.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 29.4807692308, "max_line_length": 114, "alphanum_fraction": 0.6193737769, "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.5335240128310046}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2018-2019, LAAS-CNRS\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_UTILS_MATH_HPP_\n#define CROCODDYL_CORE_UTILS_MATH_HPP_\n\n#include <boost/type_traits.hpp>\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <limits>\n\n// fwd\n\ntemplate <typename MatrixLike, bool value = boost::is_floating_point<typename MatrixLike::Scalar>::value>\nstruct pseudoInverseAlgo {\n  typedef typename MatrixLike::Scalar Scalar;\n  typedef typename MatrixLike::RealScalar RealScalar;\n\n  static MatrixLike run(const Eigen::MatrixBase<MatrixLike>& a, const RealScalar& epsilon) {\n    using std::max;\n    Eigen::JacobiSVD<MatrixLike> svd(a, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    RealScalar tolerance =\n        epsilon * static_cast<Scalar>(max(a.cols(), a.rows())) * svd.singularValues().array().abs()(0);\n    return svd.matrixV() *\n           (svd.singularValues().array().abs() > tolerance)\n               .select(svd.singularValues().array().inverse(), 0)\n               .matrix()\n               .asDiagonal() *\n           svd.matrixU().adjoint();\n  }\n};\n\ntemplate <typename MatrixLike>\nstruct pseudoInverseAlgo<MatrixLike, false> {\n  typedef typename MatrixLike::Scalar Scalar;\n  typedef typename MatrixLike::RealScalar RealScalar;\n\n  static MatrixLike run(const Eigen::MatrixBase<MatrixLike>& a, const RealScalar&) {\n    return Eigen::MatrixBase<MatrixLike>::Zero(a.rows(), a.cols());\n  }\n};\n\ntemplate <typename MatrixLike>\nMatrixLike pseudoInverse(const Eigen::MatrixBase<MatrixLike>& a,\n                         const typename MatrixLike::RealScalar& epsilon =\n                             Eigen::NumTraits<typename MatrixLike::Scalar>::dummy_precision()) {\n  return pseudoInverseAlgo<MatrixLike>::run(a, epsilon);\n}\n\n#endif  // CROCODDYL_CORE_UTILS_MATH_HPP_\n", "meta": {"hexsha": "14422034ff1391a4b0ae2f4310fdb7fa43d24bc0", "size": 2026, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/utils/math.hpp", "max_stars_repo_name": "nyu-locomotion/crocoddyl", "max_stars_repo_head_hexsha": "b0eeaa5713166d7e6955454b90aedf0fc940baa1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-23T12:57:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T16:27:14.000Z", "max_issues_repo_path": "include/crocoddyl/core/utils/math.hpp", "max_issues_repo_name": "nyu-locomotion/crocoddyl", "max_issues_repo_head_hexsha": "b0eeaa5713166d7e6955454b90aedf0fc940baa1", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/crocoddyl/core/utils/math.hpp", "max_forks_repo_name": "nyu-locomotion/crocoddyl", "max_forks_repo_head_hexsha": "b0eeaa5713166d7e6955454b90aedf0fc940baa1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-26T14:31:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T14:31:17.000Z", "avg_line_length": 35.5438596491, "max_line_length": 105, "alphanum_fraction": 0.6456071076, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6261241911813149, "lm_q1q2_score": 0.5334282684713256}}
{"text": "#include <math.h>\n#include <stdlib.h>\n#include <string>\n\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/opencv.hpp>\n//#include <opencv2/legacy/compat.hpp>\n\n#include \"dlib/opencv.h\"\n#include \"dlib/image_processing/frontal_face_detector.h\"\n#include \"dlib/image_processing/render_face_detections.h\"\n#include \"dlib/gui_widgets.h\"\n#include <dlib/image_processing.h>\n\n#include \"util.h\"\n#include \"constants.h\"\n#include \"faceDetection.h\"\n\nusing namespace std;\nusing namespace dlib;\n\nvoid FaceFeatures::assign(cv::Point c_face_centre, cv::Point c_left_eye, cv::Point c_right_eye, cv::Point c_nose_tip, cv::Point c_mouth)\n{\n\tface_centre = c_face_centre;\n\tleft_eye = c_left_eye;\n\tright_eye = c_right_eye;\n\tnose_tip = c_nose_tip;\n\tmouth = c_mouth;\n\n\tmid_eye.x = (left_eye.x + right_eye.x) / 2.0;\n\tmid_eye.y = (left_eye.y + right_eye.y) / 2.0;\n\n\t//Find the nose base along the symmetry axis\n\tnose_base.x = mouth.x + (mid_eye.x - mouth.x) * Rm;\n\tnose_base.y = mouth.y - (mouth.y - mid_eye.y) * Rm;\n}\n\nvoid FaceData::assign(FaceFeatures *f)\n{\n\tleft_eye_nose_distance = get_distance(f->left_eye, f->nose_base);\n\tright_eye_nose_distance = get_distance(f->right_eye, f->nose_base);\n\tleft_eye_right_eye_distance = get_distance(f->left_eye, f->right_eye);\n\tnose_mouth_distance = get_distance(f->nose_base, f->mouth);\n\n\tmid_eye_mouth_distance = get_distance(f->mid_eye, f->mouth);\n\tnose_base_nose_tip_distance = get_distance(f->nose_tip, f->nose_base);\n}\n\nvoid FacePose::assign(FaceFeatures *f, FaceData *d)\n{\n\troll = get_angle_between(f->left_eye, f->right_eye);\n\tif (roll > 180.0)\n\t{\n\t\troll = roll - 360.0;\n\t}\n\tsymm_x = get_angle_between(f->nose_base, f->mid_eye);\n\t//symm angle - angle between the symmetry axis and the 'x' axis\n\ttau = get_angle_between(f->nose_base, f->nose_tip);\n\t//tilt angle - angle between normal in image and 'x' axis\n\ttheta = (abs(tau - symm_x)) * (PI / 180.0);\n\t//theta angle - angle between the symmetry axis and the image normal\n\tsigma = find_sigma(d->nose_base_nose_tip_distance, d->mid_eye_mouth_distance, Rn, theta);\n\t//std::cout<<\"symm : \"<<symm_x<<\" tau : \"<<tau<<\" theta : \"<<theta<<\" sigma : \"<<sigma<<\" \";\n\n\tnormal[0] = (sin(sigma)) * (cos((360 - tau) * (PI / 180.0)));\n\tnormal[1] = (sin(sigma)) * (sin((360 - tau) * (PI / 180.0)));\n\tnormal[2] = -cos(sigma);\n\n\tkalman_pitch_pre = pitch;\n\tpitch = acos(sqrt((normal[0] * normal[0] + normal[2] * normal[2]) / (normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2])));\n\tif ((f->nose_tip.y - f->nose_base.y) < 0)\n\t{\n\t\tpitch = -pitch;\n\t}\n\n\tkalman_yaw_pre = yaw;\n\tyaw = acos((abs(normal[2])) / (sqrt(normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2])));\n\tif ((f->nose_tip.x - f->nose_base.x) < 0)\n\t{\n\t\tyaw = -yaw;\n\t}\n\n\tpointer_2d.x = ((f->nose_base.x + cvRound(500 * (tan((double)yaw)))));\n\tpointer_2d.y = ((f->nose_base.y + cvRound(500 * (tan((double)pitch)))));\n}\n\nvoid draw_facial_normal(cv::Mat &img, dlib::full_object_detection shape, std::vector<double> normal, double mag)\n{\n\n\tdouble del_x = mag * normal[0];\n\tdouble del_y = mag * normal[1];\n\n\tcv::line(img, cv::Point(shape.part(30).x(), shape.part(30).y()),\n\t\t\t cv::Point(shape.part(30).x() + del_x, shape.part(30).y() + del_y), cv::Scalar(0), 3);\n\n\t//std::cout<<\"magnitude : \"<<vectorMagnitude(f->normal, 3)<<\" \";\n\t//std::cout<<f->normal[0]<<\", \"<<f->normal[1]<<\", \"<<f->normal[2];\n}\n\nvoid draw_crosshair(cv::Mat img, CvPoint centre, int circle_radius, int line_radius)\n{\n\tcv::Point pt1, pt2, pt3, pt4;\n\tcv::Scalar colour(255);\n\n\tpt1.x = centre.x;\n\tpt2.x = centre.x;\n\tpt1.y = centre.y - line_radius;\n\tpt2.y = centre.y + line_radius;\n\tpt3.x = centre.x - line_radius;\n\tpt4.x = centre.x + line_radius;\n\tpt3.y = centre.y;\n\tpt4.y = centre.y;\n\n\tcv::circle(img, centre, circle_radius, colour, 2, 4, 0);\n\n\tcv::line(img, pt1, pt2, colour, 1, 4, 0);\n\tcv::line(img, pt3, pt4, colour, 1, 4, 0);\n}\n\nvoid project_facial_pose(cv::Mat img, double normal[3], double sigma, double theta)\n{\n\n\tcv::Point origin = cv::Point(50, 50);\n\tcv::Scalar colour = cv::Scalar(255);\n\n\tcv::Point projection_2d;\n\tprojection_2d.x = origin.x + cvRound(60 * (normal[0]));\n\tprojection_2d.y = origin.y + cvRound(60 * (normal[1]));\n\n\tif (normal[0] > 0 && normal[1] < 0)\n\t{\n\t\tcv::ellipse(img, origin, cv::Size(25, std::abs(cvRound(25 - sigma * (180 / (2 * PI))))), std::abs(180 - (theta * (180 / PI))), 0, 360, colour, 2, 4, 0);\n\t}\n\telse\n\t{\n\t\tcv::ellipse(img, origin, cv::Size(25, std::abs(cvRound(25 - sigma * (180 / (2 * PI))))), std::abs(theta * (180 / PI)), 0, 360, colour, 2, 4, 0);\n\t}\n\n\tcv::line(img, origin, projection_2d, colour, 2, 4, 0);\n}\n\ndouble find_sigma(int ln, int lf, double Rn, double theta)\n{\n\tdouble dz = 0;\n\tdouble sigma;\n\tdouble m1 = ((double)ln * ln) / ((double)lf * lf);\n\tdouble m2 = (cos(theta)) * (cos(theta));\n\n\tif (m2 == 1)\n\t{\n\t\tdz = sqrt((Rn * Rn) / (m1 + (Rn * Rn)));\n\t}\n\tif (m2 >= 0 && m2 < 1)\n\t{\n\t\tdz = sqrt(((Rn * Rn) - m1 - 2 * m2 * (Rn * Rn) + sqrt(((m1 - (Rn * Rn)) * (m1 - (Rn * Rn))) + 4 * m1 * m2 * (Rn * Rn))) / (2 * (1 - m2) * (Rn * Rn)));\n\t}\n\tsigma = acos(dz);\n\treturn sigma;\n}\n", "meta": {"hexsha": "1755746f1f570f590fbeb4fde652e89b957c0d41", "size": 5043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/faceDetection.cpp", "max_stars_repo_name": "vmthanh/Eye-Tracking", "max_stars_repo_head_hexsha": "0004fb2e29d90fdcc986cc52e335fa5fe2c0f88d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/faceDetection.cpp", "max_issues_repo_name": "vmthanh/Eye-Tracking", "max_issues_repo_head_hexsha": "0004fb2e29d90fdcc986cc52e335fa5fe2c0f88d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/faceDetection.cpp", "max_forks_repo_name": "vmthanh/Eye-Tracking", "max_forks_repo_head_hexsha": "0004fb2e29d90fdcc986cc52e335fa5fe2c0f88d", "max_forks_repo_licenses": ["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.51875, "max_line_length": 154, "alphanum_fraction": 0.6402934761, "num_tokens": 1752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5334226855811721}}
{"text": "// [[Rcpp::depends(RcppArmadillo)]]\n#define ARMA_DONT_PRINT_ERRORS\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <armadillo>\n#include <errno.h>\n#include <RcppArmadillo.h>\n\n//' Compute hazard of detection (Hayes-Buckland isotropic hazard)\n//' \n//' @param x x distance \n//' @param y y distance \n//' @param dt time step\n//' @param observer_speed observer speed\n//' @param parameter detection parameters \n//' @param w truncation width \n//' @param type transect type 0 = point, 1 = line\n//' @return hazard of detection  \ndouble CalcHazard2(double x, double y, double dt, double observer_speed, \n                   arma::vec parameter, double w = 0, int type = 0) {\n  double hazard = 0; \n  if (type == 1) {\n    double r = x * x + y * y; \n    hazard = dt * parameter(0) / pow(r, 0.5 * parameter(1));  \n  }\n  if (type == 0) {\n    if (y < 0) return 0; \n    double abeta = 0.5 * (parameter(1) - 1.0); \n    double r0 = x * x  + y * y;\n    double y1 = y - observer_speed * dt; \n    if (y1 < 0) y1 = 0;  \n    double r1 = x * x  + y1 * y1;\n    if (r1 < 1e-10) return arma::datum::inf; \n    if (fabs(x) < 1e-10) {\n      if (fabs(parameter(1) - 1) < 1e-10) {\n        hazard = log(sqrt(r1)) - log(sqrt(r0));\n        hazard *= parameter(0); \n      } else {\n        hazard = 1.0 / pow(r1, abeta) - 1.0 / pow(r0, abeta); \n        hazard *= parameter(0) / (parameter(1) - 1.0); \n      }\n    } else {\n      hazard = R::pbeta(x * x / r1, abeta, 0.5, 1, 0) - R::pbeta(x * x / r0, \n                        abeta, 0.5, 1, 0); \n      hazard *= R::beta(abeta, 0.5) * parameter(0) / (2.0 * pow(fabs(x), \n                                                parameter(1) - 1.0)); \n    } \n  }\n  return hazard;   \n}\n\n//' Get Recorded forward distance once detection occurs \n//' \n//' @param x recorded x location \n//' @param y recorded y location\n//' @param accu_hazard hazard accumulated up to that time \n//' @param u log random deviate \n//' @param parameter detection parameters \n//' \n//' @return recorded forward distance \ndouble GetRecordedYPosition(double x, double y, double accu_hazard, \n                            double u, arma::vec parameter) {\n  double r = x * x + y * y; \n  double y1;\n  double abeta =  0.5 * (parameter(1) - 1.0); \n  if (fabs(x) < 1e-10) {\n    if (fabs(parameter(1) - 1) < 1e-10) {\n      y1 = sqrt(exp(2.0 * (u - accu_hazard) / parameter(0) + log(r)) - x * x);       \n    } else {\n      y1 = sqrt(pow((u - accu_hazard) * (parameter(1) - 1.0) / parameter(0) + \n        1 / pow(r, abeta), -1.0 / abeta) - x * x); \n    }\n  } else {\n    y1 = R::pbeta(x * x / r, abeta, 0.5, 1, 0) + 2 * pow(fabs(x), \n                  parameter(1) - 1.0) * (u - accu_hazard) / (parameter(0) * R::beta(abeta, 0.5)); \n    y1 = R::qbeta(y1, abeta, 0.5, 1, 0); \n    y1 = fabs(x) * sqrt(1.0 / y1 - 1.0);  \n  }\n  return y1; \n}\n\n//' Get Recorded time once detection occurs \n//' \n//' @param x recorded x location \n//' @param y recorded y location\n//' @param accu_hazard hazard accumulated up to that time \n//' @param u log random deviate \n//' @param parameter detection parameters \n//' \n//' @return recorded forward distance \ndouble GetRecordedT(double x, double y, double accu_hazard, \n                    double u, arma::vec parameter) {\n  double r = x * x + y * y; \n  double t_add = (u - accu_hazard) * pow(r, 0.5 * parameter(1)) / parameter(0);\n  return t_add; \n}\n\n//' Simulate distance sampling survey\n//' \n//' @param true_parameter (detection shape, scale, diffusion sd) \n//' @param N number of animals \n//' @param auxiliary_info (region x-extent ,region y-extent, survey time, dt, \n//' transect type (0 = point, 1 = line), observer_speed, number of transects, half width of transects)\n//' @param dt time step \n//' @param move = 0 no mvoement, 1 Brownian motion \n//' @return Outputs csv data file \n// [[Rcpp::export]]\nint SimulateDsData(arma::vec true_parameter, \n                   int N, \n                   arma::vec auxiliary_info, \n                   double dt,\n                   int move = 0) {\n  arma::vec area = auxiliary_info.rows(0, 1); \n  double half_width = auxiliary_info(2) * 0.5; \n  double survey_time = auxiliary_info(4);\n  double transect_type = auxiliary_info(7); \n  double observer_speed = auxiliary_info(5); \n  int num_transects = auxiliary_info(6); \n  arma::vec parameter(true_parameter); \n  if (transect_type == 0) {\n    parameter(0) = 2.0 * pow(parameter(0), parameter(1)) / R::beta(0.5 * parameter(1), 0.5);\n  } else {\n    parameter(0) = pow(parameter(0), parameter(1));\n  }\n  if (transect_type == 0) ++parameter(1); \n  arma::vec observer_position(2);\n  observer_position(0) = area(0) * 0.5; \n  observer_position(1) = area(1) * 0.5; \n  arma::vec detection_parameter(parameter.rows(0,1)); \n  double sd = parameter(2);\n  // open data file \n  std::ofstream data(\"./simulated_dsdata.csv\"); \n  arma::vec x(N);\n  arma::vec y(N);  \n  arma::vec u(N); \n  arma::vec detected(N); \n  arma::vec accu_hazard(N);\n  double recorded_y; \n  double recorded_t; \n  double recorded_r; \n  double hazard;  \n  bool include; \n  for (int transect = 0; transect < num_transects; ++transect) {\n    if (transect_type == 0) observer_position(1) = 0.0;\n    x = arma::randu(N) * area(0); \n    y = arma::randu(N) * area(1); \n    u = -log(arma::randu(N)); \n    detected.zeros(); \n    accu_hazard.zeros(); \n    for (int t = 0; t < floor(survey_time / dt); ++t) {\n      for (int i = 0; i < N; ++i) {\n        hazard = CalcHazard2(x(i) - observer_position(0), y(i) - \n          observer_position(1), dt, observer_speed, parameter, half_width, transect_type);\n        if ((accu_hazard(i) + hazard >= u(i)) & (accu_hazard(i) < u(i))) {\n          include = false; \n          if (transect_type == 0) {\n            recorded_y = GetRecordedYPosition(x(i) - observer_position(0), \n                                              y(i) - observer_position(1), accu_hazard(i), u(i), \n                                              parameter); \n            recorded_t = t * dt + (y(i) - observer_position(1) - recorded_y) / \n              observer_speed;\n            if ((recorded_t < survey_time) & (fabs(x(i) - observer_position(0)) < half_width)) include = true; \n          } else {\n            recorded_y = y(i) - observer_position(1); \n            recorded_t = t * dt + GetRecordedT(x(i) - observer_position(0), \n                                               y(i) - observer_position(1), \n                                               accu_hazard(i), \n                                               u(i), \n                                               parameter);\n            recorded_r = pow(x(i) - observer_position(0), 2) + recorded_y * recorded_y; \n            if (recorded_r <= half_width * half_width) include = true; \n          }\n          if (include) {\n            data << transect + 1 << \",\" << x(i) - observer_position(0) << \",\" << recorded_y << \",\" <<\n              recorded_t << \"\\n\"; \n          }\n        }\n        accu_hazard(i) += hazard; \n        // assume uniform initial behaviour distribution \n        if (move == 1) {\n          x(i) += sd * sqrt(dt) * R::rnorm(0, 1);\n          y(i) += sd * sqrt(dt) * R::rnorm(0, 1);\n        }  \n      }\n      observer_position(1) += observer_speed * dt; \n      arma::uvec outside = find(x < 0 || x > area(0) || y < 0 || y > area(1)); \n      arma::vec u2(arma::randu(N)); \n      u(outside) = u2(outside);\n      accu_hazard(outside).fill(0.0);  \n      x(find(x < 0)) += area(0); \n      x(find(x > area(0))) -= area(0); \n      y(find(y < 0)) += area(1); \n      y(find(y > area(1))) -= area(1);  \n    }  \n  }\n  data.close(); \n  return 0; \n}", "meta": {"hexsha": "6a31aed849cc91e232e69ca72bde29f1139b2ab2", "size": 7560, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/simulate.cc", "max_stars_repo_name": "r-glennie/moveds", "max_stars_repo_head_hexsha": "3fb04969cd0548e65b230ee4dcfb750ee1560b46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulate.cc", "max_issues_repo_name": "r-glennie/moveds", "max_issues_repo_head_hexsha": "3fb04969cd0548e65b230ee4dcfb750ee1560b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulate.cc", "max_forks_repo_name": "r-glennie/moveds", "max_forks_repo_head_hexsha": "3fb04969cd0548e65b230ee4dcfb750ee1560b46", "max_forks_repo_licenses": ["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.9899497487, "max_line_length": 111, "alphanum_fraction": 0.5419312169, "num_tokens": 2335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5333374552707366}}
{"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_FREXP_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FREXP_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing frexp capabilities\n\n    Computes a mantissa and an exponent pair for the input\n\n    @code\n    m = frexp(x, e);\n    @endcode\n\n    is similar to:\n\n    @code\n    as_integer_t<T> e = exponent(x)+1;\n    T m = mantissa(x)/2;\n    @endcode\n\n    The call\n\n    @code\n    std:pair<T,as_integer_t<T>> p = frexp(x);\n    @endcode\n\n    can also be used.\n\n    @par Note:\n\n    @c frexp splits a floating point value @c v f in a signed mantissa @c m and\n    an exponent @c e so that:  @f$v = m\\times 2^e@f$, with absolute value of @c m\n    between 0.5 (included) and 1 (excluded)\n\n    Take care that these results differ from the returns of the functions @ref mantissa\n    and @ref exponent\n\n    @see exponent,  mantissa\n\n  **/\n  const boost::dispatch::functor<tag::frexp_> frexp = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/frexp.hpp>\n#include <boost/simd/function/scalar/frexp.hpp>\n#include <boost/simd/function/simd/frexp.hpp>\n\n#endif\n", "meta": {"hexsha": "0f009856318b014b9f533b35e5f1af97d9a58a92", "size": 1574, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/frexp.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/frexp.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/frexp.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": 23.8484848485, "max_line_length": 100, "alphanum_fraction": 0.5984752224, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5333084451582735}}
{"text": "/**\n * @file \tMyDijkstra.cpp\n * @author \tFabian Wegscheider\n * @date \tJul 10, 2017\n */\n\n\n#include <boost/heap/fibonacci_heap.hpp>\n#include \"MyDijkstra.h\"\n\nusing std::pair;\n\nusing Pair = pair<int, double>;\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\n\ntypename graph_traits<Graph>::out_edge_iterator out_i, out_end;\n\n\n/**\n * Data that is stored in one node of a heap. Contains an integer and a double.\n * Comparisons are made by the double, smaller has higher priority\n */\nstruct heap_data\n{\n    heap::fibonacci_heap<heap_data>::handle_type handle;\n    Pair pair;\n\n    heap_data(Pair p):\n        pair(p)\n    {}\n\n    bool operator<(heap_data const & rhs) const {\n        return pair.second > rhs.pair.second;\n    }\n};\n\nusing Heap = heap::fibonacci_heap<heap_data>;\n\n\nvoid MyDijkstra::computeShortestPaths(Graph& g, int numVertices, int source,\n\t\tdouble distances[], int predecessors[]) {\n\n\n\tpredecessors[source] = source;\n\n\tHeap heap;\n\n\tHeap::handle_type *handles = new Heap::handle_type[numVertices];\n\n\t//initialization of the heap\n\tfor (int i = 0; i < numVertices; ++i) {\n\t\tif (i == source) {\n\t\t\thandles[i] = heap.push(std::make_pair(i,0.));\n\t\t\tdistances[i] = 0.;\n\t\t} else {\n\t\t\thandles[i] = heap.push(std::make_pair(i, std::numeric_limits<double>::infinity()));\n\t\t\tdistances[i] = std::numeric_limits<double>::infinity();\n\t\t}\n\t}\n\n\tproperty_map<Graph, edge_weight_t>::type weights = get(edge_weight, g);\n\tproperty_map<Graph, vertex_index_t>::type index = get(vertex_index, g);\n\n\n\t//the actual algorithm\n\twhile (!heap.empty()) {\n\t\tPair min = heap.top().pair;\n\t\theap.pop();\n\t\tfor (tie(out_i, out_end) = out_edges(*(vertices(g).first+min.first), g);\n\t\t\t\tout_i != out_end; ++out_i) {\n\t\t\tdouble tmp = min.second + weights[*out_i];\n\t\t\tint targetIndex = index[target(*out_i, g)];\n\t\t\tif (tmp < distances[targetIndex]) {\n\t\t\t\tdistances[targetIndex] = tmp;\n\t\t\t\tpredecessors[targetIndex] = min.first;\n\t\t\t\t(*handles[targetIndex]).pair.second = tmp;\n\t\t\t\theap.increase(handles[targetIndex]);\n\t\t\t}\n\t\t}\n\t}\n\n\tdelete[] handles;\n}\n\n", "meta": {"hexsha": "e3bd9f87cfda722b2201c6cc144a0cd35e7971f7", "size": 2020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Wegscheider/Ex8/MyDijkstra.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": "Wegscheider/Ex8/MyDijkstra.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": "Wegscheider/Ex8/MyDijkstra.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": 23.7647058824, "max_line_length": 86, "alphanum_fraction": 0.6737623762, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5333084354935}}
{"text": "/*\n * types.hpp\n *\n *  Created on: Feb 23, 2018\n *      Author: graffy\n */\n\n#ifndef TYPES_HPP_\n#define TYPES_HPP_\n\n#include <Eigen/Dense>\nnamespace scefig\n{\n\t/*\n\tclass Vector3f\n\t{\n\n\t};\n\t*/\n\n\ttypedef Eigen::Vector3f Vector3;\n\ttypedef Eigen::Vector4f Vector4;\n\n\tclass AxisAlignedBoundingBox\n\t{\n\tpublic:\n\t\tAxisAlignedBoundingBox(const Vector3 & min, const Vector3 & max)\n\t\t: m_min(min)\n\t\t, m_max(max)\n\t\t{\n\n\t\t}\n\t\tconst Vector3 & getMin(void) const {return m_min;}\n\t\tconst Vector3 & getMax(void) const {return m_max;}\n\tprotected:\n\t\tVector3 m_min;\n\t\tVector3 m_max;\n\t};\n}\n\n\n\n#endif /* TYPES_HPP_ */\n", "meta": {"hexsha": "041853318c2298039103800eaf5f157f63c3f960", "size": 592, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "types.hpp", "max_stars_repo_name": "g-raffy/scefig", "max_stars_repo_head_hexsha": "47d1b1594d22d93f0fa0e6d8d2f1d235248a6ce5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "types.hpp", "max_issues_repo_name": "g-raffy/scefig", "max_issues_repo_head_hexsha": "47d1b1594d22d93f0fa0e6d8d2f1d235248a6ce5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "types.hpp", "max_forks_repo_name": "g-raffy/scefig", "max_forks_repo_head_hexsha": "47d1b1594d22d93f0fa0e6d8d2f1d235248a6ce5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.4545454545, "max_line_length": 66, "alphanum_fraction": 0.6655405405, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5333084354935}}
{"text": "/* +---------------------------------------------------------------------------+\n|                     Mobile Robot Programming Toolkit (MRPT)               |\n|                          http://www.mrpt.org/                             |\n|                                                                           |\n| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file        |\n| See: http://www.mrpt.org/Authors - All rights reserved.                   |\n| Released under BSD License. See details in http://www.mrpt.org/License    |\n+---------------------------------------------------------------------------+ */\n\n#include \"vision-precomp.h\"   // Precompiled headers\n\n#include <iostream>\n#include <mrpt/utils/types_math.h> // Eigen must be included first via MRPT to enable the plugin system\n#include <Eigen/Dense>\n#include <Eigen/SVD> \n\n#include \"ppnp.h\"\n\nmrpt::vision::pnp::ppnp::ppnp(const Eigen::MatrixXd& obj_pts, const Eigen::MatrixXd& img_pts, const Eigen::MatrixXd& cam_intrinsic)\n{\n\tP = img_pts;\n\tS = obj_pts;\n\tC = cam_intrinsic;\n}\n\nbool mrpt::vision::pnp::ppnp::compute_pose(Eigen::Matrix3d& R, Eigen::Vector3d& t, int n)\n{\n\tdouble tol=0.00001;\n\t\n\tEigen::MatrixXd I=Eigen::MatrixXd::Identity(n, n), A(n,n), Y(n,3), E(n,3), E_old(n,3), U,V, I3 =Eigen::MatrixXd::Identity(3, 3), PR, Z=Eigen::MatrixXd::Zero(n, n);\n\tEigen::VectorXd e(n), II(n), c(3), Zmindiag(n);\n\t\n\te.fill(1);\n\tII.fill(1.0/((double)n));\n\t\n\tA=I-e*e.transpose()/n;\n\t\n\tdouble err=std::numeric_limits<double>::infinity();\n\t\n\tE_old.fill(1000);\n\t\n    int cnt =0;\n\n\twhile(err>tol)\n\t{\n\t\t\n\t\tEigen::JacobiSVD<Eigen::MatrixXd> svd(P.transpose()*Z*A*S, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\t\tU=svd.matrixU();\n\t\tV=svd.matrixV();\n\t\t\n\t\tI3(2,2) = (U*V.transpose()).determinant();\n\t\tR=U*I3*V.transpose();\n\t\tPR = P*R;\n\t\t\n\t\tc=(S-Z*PR).transpose()*II;\n\n\t\tY=S-e*c.transpose();\n\n\t\tZmindiag=((PR*Y.transpose()).diagonal()).array() / ((P.array()*P.array()).rowwise().sum()).array();\n\t\t\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tif (Zmindiag(i) < 0)\n\t\t\t\tZmindiag(i) = 0;\n\n\n\t\tZ=Zmindiag.asDiagonal();\n\t\t\n\t\tE=Y-Z*PR;\n\n\t\terr=(E-E_old).norm();\n\n\t\tE_old=E;\n        \n        cnt ++;\n    \n\t}\n\n\tt=-R*c;\n\t\n\treturn 1;\n\t\n\t\n}\n", "meta": {"hexsha": "b82670c9b2264357867c8cbda7e991f88c11557f", "size": 2179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/vision/src/pnp/ppnp.cpp", "max_stars_repo_name": "feroze/mrpt-shivang", "max_stars_repo_head_hexsha": "95bf524c5e10ed2e622bd199f1b0597951b45370", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-25T18:09:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-22T08:14:48.000Z", "max_issues_repo_path": "libs/vision/src/pnp/ppnp.cpp", "max_issues_repo_name": "feroze/mrpt-shivang", "max_issues_repo_head_hexsha": "95bf524c5e10ed2e622bd199f1b0597951b45370", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/vision/src/pnp/ppnp.cpp", "max_forks_repo_name": "feroze/mrpt-shivang", "max_forks_repo_head_hexsha": "95bf524c5e10ed2e622bd199f1b0597951b45370", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-29T09:40:46.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-29T09:40:46.000Z", "avg_line_length": 25.9404761905, "max_line_length": 164, "alphanum_fraction": 0.5263882515, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5333031746056207}}
{"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_SINH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SINH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-hyperbolic\n    This function object returns the hyperbolic sine: \\f$(e^{x}-e^{-x})/2\\f$.\n\n    @par Header <boost/simd/function/sinh.hpp>\n\n    @see tanh, cosh, sech, csch, sinhcosh\n\n    @par Example:\n\n      @snippet sinh.cpp sinh\n\n    @par Possible output:\n\n      @snippet sinh.txt sinh\n  **/\n  IEEEValue sinh(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sinh.hpp>\n#include <boost/simd/function/simd/sinh.hpp>\n\n#endif\n", "meta": {"hexsha": "a95e4dfc0f0faf96acbebfe2cf2698b483e0a288", "size": 1017, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sinh.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/function/sinh.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/function/sinh.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": 23.6511627907, "max_line_length": 100, "alphanum_fraction": 0.5663716814, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5333031576992996}}
{"text": "#ifndef DTREE_H\n#define DTREE_H\n\n#include <iostream>\n#include <fstream>  //\u8bfb\u53d6\u6587\u4ef6\u5185\u5bb9\n#include <map>\n#include <vector>\n#include <string>\n#include <Eigen/Dense>\n#include <cmath>\n\nusing std::cout; using std::cin; using std::cerr; using std::endl;\nusing std::string; using std::ifstream; using std::istringstream;\nusing std::vector; using std::map; using std::ios;\n\nusing Eigen::MatrixXf;   //Eigen Matrix float \u5b58\u50a8\u6570\u636e  \u8bad\u7ec3\u6570\u636e\nusing Eigen::MatrixXi;  //Eigen Matrix int \u5b58\u50a8\u6570\u636e  \u8bad\u7ec3\u6570\u636e\u548c\u6807\u7b7e\nusing Eigen::VectorXi;\nusing Eigen::VectorXf;\n\n\nclass DTree\n{\npublic:\n\tstruct TreeNode\n\t{   //\u8282\u70b9\u4fe1\u606f\n\t\tstring Attribute;   //\u6b64\u8282\u70b9\u5bf9\u5e94\u7684\u5c5e\u6027\n\t\tbool LeafNode; //\u5982\u679c\u662f\u53f6\u5b50\u8282\u70b9\uff0c\u6b64\u503c\u53cd\u6620\u5206\u7c7b\u7ed3\u679c\u3002 //\u5176\u4ed6\u60c5\u51b5\u90fd\u662f0;\n\t\tvector<TreeNode*> children; //\u5b69\u5b50\u8282\u70b9\u7684\u5730\u5740\u3002\n\t\tmap<string, TreeNode*> AttributeLinkChildren;  //\u5c5e\u6027\u6307\u5411\u5b69\u5b50\u8282\u70b9\uff0c\u4e5f\u5c31\u662f\u5bf9\u5e94\u7684\u6811\u5f62\u7ed3\u6784\u4e2d\u7684\u6811\u679d\n\n\t};\n\tstruct Attr    //\u6bcf\u4e00\u5217\u7684\u5c5e\u6027\n\t{\n\t\tint colIndex;\n\t\tstring Attribute;\n\t\tint typeNum;   //\u5c5e\u6027\u53d6\u503c\u7684\u4e2a\u6570\n\t\tvector<string> AttributeValue;\n\t\tmap<string, unsigned char>  typeMap; //\u5c5e\u6027\u53d6\u503c\u5bf9\u5e94\u7684\u6574\u6570\u503c;\n\t};\n    \nprivate:\n\tstruct MatInfo\n\t{\n\t\tint cols;\n\t\tint rows;\n\n\t};\t\t\n\tstruct entropyInfo\n\t{\n\t\tvector<int> labelValue;\n\t\tvector<int> labelValueNum;\n\t};\npublic:\n\t//MatrixXi trainDataMat;\n    MatrixXi trainDataMat;\n\tvector<vector<string>> predictedDataMat;\n\tMatInfo trainMatrixInfo;\n\tTreeNode *root;  //\u6839\u8282\u70b9\n\tvector<Attr> vectorAttr; //\u5b58\u50a8\u6240\u6709\u7684\u77e9\u9635\u4fe1\u606f\uff0c\u4f46\u4e0d\u5b58\u50a8\u77e9\u9635\u3002\n\tDTree();\n    DTree(string csvfilename);\n\tMatrixXi ReadTrainDataFile(string fileAddress);  //\u6570\u636e\u9884\u5904\u7406\n\t//TreeNode* BuildTree(MatrixXi &data, vector<Attr> &dataAttr, string AlgorithmName);  // \u6307\u5b9a\u662f\u54ea\u79cd\u7b97\u6cd5\n    int BuildTree(MatrixXi &data, vector<Attr> &dataAttr, string AlgorithmName);\n\tvector<vector<string>> ReadPredictedDataFile(string fileAddreess);\n\t//vector<string> Predicted(TreeNode* root, vector<vector<string>> &pData);  //\u8fd4\u56de\u503c\u4e3aint\u7c7b\u578b\u8868\u793a\u6570\u636e\u7684\u5206\u7c7b\u3002\n    vector<string> Predicted(vector<vector<string>> &pData);\n    ~DTree();\n\t\nprivate:\n    int stringDataToInt(const vector<vector<string>> &src, MatrixXi &dataMat, vector<Attr> &headAttrInfo);\n\tbool StringExistInVector(string aa, vector<string> A);\n\tTreeNode* AlgorithmID3(MatrixXi &data, vector<Attr> &a);\n\tTreeNode* AlgorithmC4_5(MatrixXi &data, vector<Attr> &a);\n\tTreeNode* AlgorithmCART(MatrixXi &data, vector<Attr> &a);\n\t//vector<float> CalculateEntropy(MatrixXi a);\n\tvector<float> CalculateInfGain(MatrixXi &a);\n\tint FindMaxInformationGain(vector<float> s);\n\tbool TheSameLabel(MatrixXi &a);\n\tMatrixXi GetNewMat(MatrixXi &a, vector<Attr> &properties, int maxIndex, string oneAttributeValue);\n\tint IntExistInVector(int a, vector<int> b);\n\tfloat GetDataEntropy(MatrixXi &data);\n\tfloat InformationGain(vector<int> value, map<int, entropyInfo> b, float dataEntropy, int rows);\n\tfloat Entropy(vector<float> ratio); // \u8ba1\u7b97\u71b5\n\t//\u5224\u65ad\u77e9\u9635\u4e2d\u662f\u5426\u6709\u8be5\u5c5e\u6027\n\tbool DataExistAttribute(MatrixXi &data, vector<Attr> &properties, int maxIndex, string oneAttributeValue);\n\tint IndexOFAttribute(string nodeString, vector<Attr> &vectorAttr);\n\tstring PredictedRecursion(TreeNode* nodeAddress, vector<string> &rowData, vector<Attr> &vecAttr);\n\tstring FindAttrString(int a, Attr b);\n\tstring MostInMatLabel(MatrixXi &data, vector<Attr> &properties);\n    int destroyTree(TreeNode *root);\n};\n\n#endif", "meta": {"hexsha": "1b2f1c3e686cc0e3c1a0e0eb022a031abb287e31", "size": 3107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "C++ source Code/Discrete/DTree.hpp", "max_stars_repo_name": "PiggyGaGa/MachineLearning-DecisionTree", "max_stars_repo_head_hexsha": "3c063024405021739509e6cdb3655d5ebf417ebd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2018-07-21T15:18:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T10:09:52.000Z", "max_issues_repo_path": "C++ source Code/Discrete/DTree.hpp", "max_issues_repo_name": "PiggyGaGa/MachineLearning-DecisionTree", "max_issues_repo_head_hexsha": "3c063024405021739509e6cdb3655d5ebf417ebd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-18T07:38:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T02:51:01.000Z", "max_forks_repo_path": "C++ source Code/Discrete/DTree.hpp", "max_forks_repo_name": "PiggyGaGa/MachineLearning-DecisionTree", "max_forks_repo_head_hexsha": "3c063024405021739509e6cdb3655d5ebf417ebd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-04-01T05:18:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-20T13:11:47.000Z", "avg_line_length": 32.7052631579, "max_line_length": 107, "alphanum_fraction": 0.7421950435, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.533266381585809}}
{"text": "//  (C) 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#ifndef BOOST_MATH_SPECIAL_CHEBYSHEV_HPP\n#define BOOST_MATH_SPECIAL_CHEBYSHEV_HPP\n#include <cmath>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/promotion.hpp>\n\n#if (__cplusplus > 201103) || (defined(_CPPLIB_VER) && (_CPPLIB_VER >= 610))\n#  define BOOST_MATH_CHEB_USE_STD_ACOSH\n#endif\n\n#ifndef BOOST_MATH_CHEB_USE_STD_ACOSH\n#  include <boost/math/special_functions/acosh.hpp>\n#endif\n\nnamespace boost { namespace math {\n\ntemplate<class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type chebyshev_next(T1 const & x, T2 const & Tn, T3 const & Tn_1)\n{\n    return 2*x*Tn - Tn_1;\n}\n\nnamespace detail {\n\ntemplate<class Real, bool second, class Policy>\ninline Real chebyshev_imp(unsigned n, Real const & x, const Policy&)\n{\n#ifdef BOOST_MATH_CHEB_USE_STD_ACOSH\n    using std::acosh;\n#define BOOST_MATH_ACOSH_POLICY\n#else\n   using boost::math::acosh;\n#define BOOST_MATH_ACOSH_POLICY , Policy()\n#endif\n    using std::cosh;\n    using std::pow;\n    using std::sqrt;\n    Real T0 = 1;\n    Real T1;\n    if (second)\n    {\n        if (x > 1 || x < -1)\n        {\n            Real t = sqrt(x*x -1);\n            return static_cast<Real>((pow(x+t, (int)(n+1)) - pow(x-t, (int)(n+1)))/(2*t));\n        }\n        T1 = 2*x;\n    }\n    else\n    {\n        if (x > 1)\n        {\n            return cosh(n*acosh(x BOOST_MATH_ACOSH_POLICY));\n        }\n        if (x < -1)\n        {\n            if (n & 1)\n            {\n                return -cosh(n*acosh(-x BOOST_MATH_ACOSH_POLICY));\n            }\n            else\n            {\n                return cosh(n*acosh(-x BOOST_MATH_ACOSH_POLICY));\n            }\n        }\n        T1 = x;\n    }\n\n    if (n == 0)\n    {\n        return T0;\n    }\n\n    unsigned l = 1;\n    while(l < n)\n    {\n       std::swap(T0, T1);\n       T1 = boost::math::chebyshev_next(x, T0, T1);\n       ++l;\n    }\n    return T1;\n}\n} // namespace detail\n\ntemplate <class Real, class Policy>\ninline typename tools::promote_args<Real>::type\nchebyshev_t(unsigned n, Real const & x, const Policy&)\n{\n   typedef typename tools::promote_args<Real>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::chebyshev_imp<value_type, false>(n, static_cast<value_type>(x), forwarding_policy()), \"boost::math::chebyshev_t<%1%>(unsigned, %1%)\");\n}\n\ntemplate<class Real>\ninline typename tools::promote_args<Real>::type chebyshev_t(unsigned n, Real const & x)\n{\n    return chebyshev_t(n, x, policies::policy<>());\n}\n\ntemplate <class Real, class Policy>\ninline typename tools::promote_args<Real>::type\nchebyshev_u(unsigned n, Real const & x, const Policy&)\n{\n   typedef typename tools::promote_args<Real>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::chebyshev_imp<value_type, true>(n, static_cast<value_type>(x), forwarding_policy()), \"boost::math::chebyshev_u<%1%>(unsigned, %1%)\");\n}\n\ntemplate<class Real>\ninline typename tools::promote_args<Real>::type chebyshev_u(unsigned n, Real const & x)\n{\n    return chebyshev_u(n, x, policies::policy<>());\n}\n\ntemplate <class Real, class Policy>\ninline typename tools::promote_args<Real>::type\nchebyshev_t_prime(unsigned n, Real const & x, const Policy&)\n{\n   typedef typename tools::promote_args<Real>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n   if (n == 0)\n   {\n      return result_type(0);\n   }\n   return policies::checked_narrowing_cast<result_type, Policy>(n * detail::chebyshev_imp<value_type, true>(n - 1, static_cast<value_type>(x), forwarding_policy()), \"boost::math::chebyshev_t_prime<%1%>(unsigned, %1%)\");\n}\n\ntemplate<class Real>\ninline typename tools::promote_args<Real>::type chebyshev_t_prime(unsigned n, Real const & x)\n{\n   return chebyshev_t_prime(n, x, policies::policy<>());\n}\n\n/*\n * This is Algorithm 3.1 of\n * Gil, Amparo, Javier Segura, and Nico M. Temme.\n * Numerical methods for special functions.\n * Society for Industrial and Applied Mathematics, 2007.\n * https://www.siam.org/books/ot99/OT99SampleChapter.pdf\n * However, our definition of c0 differs by a factor of 1/2, as stated in the docs. . .\n */\ntemplate<class Real, class T2>\ninline Real chebyshev_clenshaw_recurrence(const Real* const c, size_t length, const T2& x)\n{\n    using boost::math::constants::half;\n    if (length < 2)\n    {\n        if (length == 0)\n        {\n            return 0;\n        }\n        return c[0]/2;\n    }\n    Real b2 = 0;\n    Real b1 = c[length -1];\n    for(size_t j = length - 2; j >= 1; --j)\n    {\n        Real tmp = 2*x*b1 - b2 + c[j];\n        b2 = b1;\n        b1 = tmp;\n    }\n    return x*b1 - b2 + half<Real>()*c[0];\n}\n\n\n\nnamespace detail {\ntemplate<class Real>\ninline Real unchecked_chebyshev_clenshaw_recurrence(const Real* const c, size_t length, const Real & a, const Real & b, const Real& x)\n{\n    Real t;\n    Real u;\n    // This cutoff is not super well defined, but it's a good estimate.\n    // See \"An Error Analysis of the Modified Clenshaw Method for Evaluating Chebyshev and Fourier Series\"\n    // J. OLIVER, IMA Journal of Applied Mathematics, Volume 20, Issue 3, November 1977, Pages 379\u2013391\n    // https://doi.org/10.1093/imamat/20.3.379\n    const Real cutoff = 0.6;\n    if (x - a < b - x)\n    {\n        u = 2*(x-a)/(b-a);\n        t = u - 1;\n        if (t > -cutoff)\n        {\n            Real b2 = 0;\n            Real b1 = c[length -1];\n            for(size_t j = length - 2; j >= 1; --j)\n            {\n                Real tmp = 2*t*b1 - b2 + c[j];\n                b2 = b1;\n                b1 = tmp;\n            }\n            return t*b1 - b2 + c[0]/2;\n        }\n        else\n        {\n            Real b = c[length -1];\n            Real d = b;\n            Real b2 = 0;\n            for (size_t r = length - 2; r >= 1; --r)\n            {\n                d = 2*u*b - d + c[r];\n                b2 = b;\n                b = d - b;\n            }\n            return t*b - b2 + c[0]/2;\n        }\n    }\n    else\n    {\n        u = -2*(b-x)/(b-a);\n        t = u + 1;\n        if (t < cutoff)\n        {\n            Real b2 = 0;\n            Real b1 = c[length -1];\n            for(size_t j = length - 2; j >= 1; --j)\n            {\n                Real tmp = 2*t*b1 - b2 + c[j];\n                b2 = b1;\n                b1 = tmp;\n            }\n            return t*b1 - b2 + c[0]/2;\n        }\n        else\n        {\n            Real b = c[length -1];\n            Real d = b;\n            Real b2 = 0;\n            for (size_t r = length - 2; r >= 1; --r)\n            {\n                d = 2*u*b + d + c[r];\n                b2 = b;\n                b = d + b;\n            }\n            return t*b - b2 + c[0]/2;\n        }\n    }\n}\n\n} // namespace detail\n\ntemplate<class Real>\ninline Real chebyshev_clenshaw_recurrence(const Real* const c, size_t length, const Real & a, const Real & b, const Real& x)\n{\n    if (x < a || x > b)\n    {\n        throw std::domain_error(\"x in [a, b] is required.\");\n    }\n    if (length < 2)\n    {\n        if (length == 0)\n        {\n            return 0;\n        }\n        return c[0]/2;\n    }\n    return detail::unchecked_chebyshev_clenshaw_recurrence(c, length, a, b, x);\n}\n\n\n}}\n#endif\n", "meta": {"hexsha": "885020a29e6fc47ca77e6205ea8d764134410c51", "size": 8320, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/special_functions/chebyshev.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/special_functions/chebyshev.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": 61.0, "max_issues_repo_issues_event_min_datetime": "2017-01-22T20:35:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-13T14:48:46.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/special_functions/chebyshev.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": 54.0, "max_forks_repo_forks_event_min_datetime": "2017-03-02T06:55:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T01:12:20.000Z", "avg_line_length": 28.6896551724, "max_line_length": 219, "alphanum_fraction": 0.5860576923, "num_tokens": 2363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812552, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5332663700348819}}
{"text": "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n#include <cmath>\n#include <iostream>\n\n#include <lagrange/testing/common.h>\n\n#include <Eigen/Geometry>\n\n#include <lagrange/common.h>\n#include <lagrange/compute_mesh_centroid.h>\n#include <lagrange/create_mesh.h>\n#include <lagrange/utils/safe_cast.h>\n\nTEST_CASE(\"ComputeMeshCentroid\", \"[mesh][centroid]\")\n{\n    using namespace lagrange;\n\n    Vertices3D ref_vertices(6 + 3, 3);\n    Triangles facets(4 + 1, 3);\n\n    const double a = 0.5;\n    const double b = 2.0;\n    const double large_number = 1000;\n\n    ref_vertices.row(0) << -a / 2., -b / 2., 0;\n    ref_vertices.row(1) << +a / 2., -b / 2., 0;\n    ref_vertices.row(2) << +a / 2., 0, 0;\n    ref_vertices.row(3) << +a / 2., b / 4., 0;\n    ref_vertices.row(4) << +a / 2., b / 2., 0;\n    ref_vertices.row(5) << -a / 2., b / 2., 0;\n    // Don't include in computation\n    ref_vertices.row(6) << large_number, large_number, large_number;\n    ref_vertices.row(7) << -large_number, -large_number, -large_number;\n    ref_vertices.row(8) << 2 * large_number, 2 * large_number, 2 * large_number;\n\n\n    facets.row(0) << 0, 1, 2;\n    // Don't include in computation\n    facets.row(1) << 6, 7, 8;\n    //\n    facets.row(2) << 0, 2, 3;\n    facets.row(3) << 0, 3, 4;\n    facets.row(4) << 0, 4, 5;\n\n    // Reference values without transformations\n    const double ref_area = a * b;\n    Eigen::Vector3d ref_center(0, 0, 0);\n\n    // Translate\n    Eigen::Vector3d tr(-1, 3, 4);\n    Eigen::Matrix3d rot =\n        Eigen::AngleAxisd(1.2365, Eigen::Vector3d(-1, 2, 5.1).normalized()).toRotationMatrix();\n\n    // Create the vertices\n    Vertices3D vertices = (ref_vertices * rot.transpose()).rowwise() + tr.transpose();\n\n    auto mesh_unique = lagrange::create_mesh(vertices, facets);\n    auto out = compute_mesh_centroid(*mesh_unique, {0, 2, 3, 4});\n\n    CHECK(out.area == Approx(ref_area));\n    CHECK((out.centroid.transpose() - ref_center - tr).norm() == Approx(0.).margin(1e-10));\n\n\n} // end of TEST\n", "meta": {"hexsha": "5377c375cc3a6c16b3534d6390dac64133e55342", "size": 2548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/tests/test_compute_mesh_centroid.cpp", "max_stars_repo_name": "LaudateCorpus1/lagrange", "max_stars_repo_head_hexsha": "2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 156.0, "max_stars_repo_stars_event_min_datetime": "2021-01-08T19:53:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T18:32:52.000Z", "max_issues_repo_path": "modules/core/tests/test_compute_mesh_centroid.cpp", "max_issues_repo_name": "LaudateCorpus1/lagrange", "max_issues_repo_head_hexsha": "2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T20:18:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T15:53:57.000Z", "max_forks_repo_path": "modules/core/tests/test_compute_mesh_centroid.cpp", "max_forks_repo_name": "LaudateCorpus1/lagrange", "max_forks_repo_head_hexsha": "2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2021-01-11T21:03:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T06:27:44.000Z", "avg_line_length": 33.9733333333, "max_line_length": 95, "alphanum_fraction": 0.6558084772, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5332302783645315}}
{"text": "// This file is part of OpenCV project.\r\n// It is subject to the license terms in the LICENSE file found in the top-level directory\r\n// of this distribution and at http://opencv.org/license.html.\r\n\r\n#include \"../precomp.hpp\"\r\n#include \"../usac.hpp\"\r\n#if defined(HAVE_EIGEN)\r\n#include <Eigen/Eigen>\r\n#elif defined(HAVE_LAPACK)\r\n#include \"opencv_lapack.h\"\r\n#endif\r\n\r\nnamespace cv { namespace usac {\r\n// Essential matrix solver:\r\n/*\r\n* H. Stewenius, C. Engels, and D. Nister. Recent developments on direct relative orientation.\r\n* ISPRS J. of Photogrammetry and Remote Sensing, 60:284,294, 2006\r\n* http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.61.9329&rep=rep1&type=pdf\r\n*/\r\nclass EssentialMinimalSolverStewenius5ptsImpl : public EssentialMinimalSolverStewenius5pts {\r\nprivate:\r\n    // Points must be calibrated K^-1 x\r\n    const Mat * points_mat;\r\n#if defined(HAVE_EIGEN) || defined(HAVE_LAPACK)\r\n    const float * const pts;\r\n#endif\r\npublic:\r\n    explicit EssentialMinimalSolverStewenius5ptsImpl (const Mat &points_) :\r\n        points_mat(&points_)\r\n#if defined(HAVE_EIGEN) || defined(HAVE_LAPACK)\r\n        , pts((float*)points_.data)\r\n#endif\r\n        {}\r\n\r\n#if defined(HAVE_LAPACK) || defined(HAVE_EIGEN)\r\n    int estimate (const std::vector<int> &sample, std::vector<Mat> &models) const override {\r\n        // (1) Extract 4 null vectors from linear equations of epipolar constraint\r\n        std::vector<double> coefficients(45); // 5 pts=rows, 9 columns\r\n        auto *coefficients_ = &coefficients[0];\r\n        for (int i = 0; i < 5; i++) {\r\n            const int smpl = 4 * sample[i];\r\n            const auto x1 = pts[smpl], y1 = pts[smpl+1], x2 = pts[smpl+2], y2 = pts[smpl+3];\r\n            (*coefficients_++) = x2 * x1;\r\n            (*coefficients_++) = x2 * y1;\r\n            (*coefficients_++) = x2;\r\n            (*coefficients_++) = y2 * x1;\r\n            (*coefficients_++) = y2 * y1;\r\n            (*coefficients_++) = y2;\r\n            (*coefficients_++) = x1;\r\n            (*coefficients_++) = y1;\r\n            (*coefficients_++) = 1;\r\n        }\r\n\r\n        const int num_cols = 9, num_e_mat = 4;\r\n        double ee[36]; // 9*4\r\n        // eliminate linear equations\r\n        if (!Math::eliminateUpperTriangular(coefficients, 5, num_cols))\r\n            return 0;\r\n        for (int i = 0; i < num_e_mat; i++)\r\n            for (int j = 5; j < num_cols; j++)\r\n                ee[num_cols * i + j] = (i + 5 == j) ? 1 : 0;\r\n        // use back-substitution\r\n        for (int e = 0; e < num_e_mat; e++) {\r\n            const int curr_e = num_cols * e;\r\n            // start from the last row\r\n            for (int i = 4; i >= 0; i--) {\r\n                const int row_i = i * num_cols;\r\n                double acc = 0;\r\n                for (int j = i + 1; j < num_cols; j++)\r\n                    acc -= coefficients[row_i + j] * ee[curr_e + j];\r\n                ee[curr_e + i] = acc / coefficients[row_i + i];\r\n                // due to numerical errors return 0 solutions\r\n                if (std::isnan(ee[curr_e + i]))\r\n                    return 0;\r\n            }\r\n        }\r\n\r\n        const Matx<double, 4, 9> null_space(ee);\r\n        const Matx<double, 4, 1> null_space_mat[3][3] = {\r\n                {null_space.col(0), null_space.col(3), null_space.col(6)},\r\n                {null_space.col(1), null_space.col(4), null_space.col(7)},\r\n                {null_space.col(2), null_space.col(5), null_space.col(8)}};\r\n\r\n        // (2) Use the rank constraint and the trace constraint to build ten third-order polynomial\r\n        // equations in the three unknowns. The monomials are ordered in GrLex order and\r\n        // represented in a 10\u00d720 matrix, where each row corresponds to an equation and each column\r\n        // corresponds to a monomial\r\n        Matx<double, 1, 10> eet[3][3];\r\n        for (int i = 0; i < 3; i++)\r\n            for (int j = 0; j < 3; j++)\r\n                // compute EE Transpose\r\n                // Shorthand for multiplying the Essential matrix with its transpose.\r\n                eet[i][j] = 2 * (multPolysDegOne(null_space_mat[i][0].val, null_space_mat[j][0].val) +\r\n                                 multPolysDegOne(null_space_mat[i][1].val, null_space_mat[j][1].val) +\r\n                                 multPolysDegOne(null_space_mat[i][2].val, null_space_mat[j][2].val));\r\n\r\n        const Matx<double, 1, 10> trace = eet[0][0] + eet[1][1] + eet[2][2];\r\n        Mat_<double> constraint_mat(10, 20);\r\n        // Trace constraint\r\n        for (int i = 0; i < 3; i++)\r\n            for (int j = 0; j < 3; j++)\r\n                Mat(multPolysDegOneAndTwo(eet[i][0].val, null_space_mat[0][j].val) +\r\n                    multPolysDegOneAndTwo(eet[i][1].val, null_space_mat[1][j].val) +\r\n                    multPolysDegOneAndTwo(eet[i][2].val, null_space_mat[2][j].val) -\r\n                    0.5 * multPolysDegOneAndTwo(trace.val, null_space_mat[i][j].val))\r\n                        .copyTo(constraint_mat.row(3 * i + j));\r\n\r\n        // Rank = zero determinant constraint\r\n        Mat(multPolysDegOneAndTwo(\r\n                (multPolysDegOne(null_space_mat[0][1].val, null_space_mat[1][2].val) -\r\n                 multPolysDegOne(null_space_mat[0][2].val, null_space_mat[1][1].val)).val,\r\n                 null_space_mat[2][0].val) +\r\n                multPolysDegOneAndTwo(\r\n                    (multPolysDegOne(null_space_mat[0][2].val, null_space_mat[1][0].val) -\r\n                     multPolysDegOne(null_space_mat[0][0].val, null_space_mat[1][2].val)).val,\r\n                     null_space_mat[2][1].val) +\r\n                multPolysDegOneAndTwo(\r\n                    (multPolysDegOne(null_space_mat[0][0].val, null_space_mat[1][1].val) -\r\n                     multPolysDegOne(null_space_mat[0][1].val, null_space_mat[1][0].val)).val,\r\n                     null_space_mat[2][2].val)).copyTo(constraint_mat.row(9));\r\n\r\n#ifdef HAVE_EIGEN\r\n        const Eigen::Matrix<double, 10, 20, Eigen::RowMajor> constraint_mat_eig((double *) constraint_mat.data);\r\n        // (3) Compute the Gro\u0308bner basis. This turns out to be as simple as performing a\r\n        // Gauss-Jordan elimination on the 10\u00d720 matrix\r\n        const Eigen::Matrix<double, 10, 10> eliminated_mat_eig = constraint_mat_eig.block<10, 10>(0, 0)\r\n                .fullPivLu().solve(constraint_mat_eig.block<10, 10>(0, 10));\r\n\r\n        // (4) Compute the 10\u00d710 action matrix for multiplication by one of the un-knowns.\r\n        // This is a simple matter of extracting the correct elements fromthe eliminated\r\n        // 10\u00d720 matrix and organising them to form the action matrix.\r\n        Eigen::Matrix<double, 10, 10> action_mat_eig = Eigen::Matrix<double, 10, 10>::Zero();\r\n        action_mat_eig.block<3, 10>(0, 0) = eliminated_mat_eig.block<3, 10>(0, 0);\r\n        action_mat_eig.block<2, 10>(3, 0) = eliminated_mat_eig.block<2, 10>(4, 0);\r\n        action_mat_eig.row(5) = eliminated_mat_eig.row(7);\r\n        action_mat_eig(6, 0) = -1.0;\r\n        action_mat_eig(7, 1) = -1.0;\r\n        action_mat_eig(8, 3) = -1.0;\r\n        action_mat_eig(9, 6) = -1.0;\r\n\r\n        // (5) Compute the left eigenvectors of the action matrix\r\n        Eigen::EigenSolver<Eigen::Matrix<double, 10, 10>> eigensolver(action_mat_eig);\r\n        const Eigen::VectorXcd &eigenvalues = eigensolver.eigenvalues();\r\n        const auto * const eig_vecs_ = (double *) eigensolver.eigenvectors().real().data();\r\n#else\r\n        Matx<double, 10, 10> A = constraint_mat.colRange(0, 10),\r\n                         B = constraint_mat.colRange(10, 20), eliminated_mat;\r\n        if (!solve(A, B, eliminated_mat, DECOMP_LU)) return 0;\r\n\r\n        Mat eliminated_mat_dyn = Mat(eliminated_mat);\r\n        Mat action_mat = Mat_<double>::zeros(10, 10);\r\n        eliminated_mat_dyn.rowRange(0,3).copyTo(action_mat.rowRange(0,3));\r\n        eliminated_mat_dyn.rowRange(4,6).copyTo(action_mat.rowRange(3,5));\r\n        eliminated_mat_dyn.row(7).copyTo(action_mat.row(5));\r\n        auto * action_mat_data = (double *) action_mat.data;\r\n        action_mat_data[60] = -1.0; // 6 row, 0 col\r\n        action_mat_data[71] = -1.0; // 7 row, 1 col\r\n        action_mat_data[83] = -1.0; // 8 row, 3 col\r\n        action_mat_data[96] = -1.0; // 9 row, 6 col\r\n\r\n        int mat_order = 10, info, lda = 10, ldvl = 10, ldvr = 1, lwork = 100;\r\n        double wr[10], wi[10] = {0}, eig_vecs[100], work[100]; // 10 = mat_order, 100 = lwork\r\n        char jobvl = 'V', jobvr = 'N'; // only left eigen vectors are computed\r\n        dgeev_(&jobvl, &jobvr, &mat_order, action_mat_data, &lda, wr, wi, eig_vecs, &ldvl,\r\n                nullptr, &ldvr, work, &lwork, &info);\r\n        if (info != 0) return 0;\r\n#endif\r\n\r\n        models = std::vector<Mat>(); models.reserve(10);\r\n\r\n        // Read off the values for the three unknowns at all the solution points and\r\n        // back-substitute to obtain the solutions for the essential matrix.\r\n        for (int i = 0; i < 10; i++)\r\n            // process only real solutions\r\n#ifdef HAVE_EIGEN\r\n            if (eigenvalues(i).imag() == 0) {\r\n                Mat_<double> model(3, 3);\r\n                auto * model_data = (double *) model.data;\r\n                const int eig_i = 20 * i + 12; // eigen stores imaginary values too\r\n                for (int j = 0; j < 9; j++)\r\n                    model_data[j] = ee[j   ] * eig_vecs_[eig_i  ] + ee[j+9 ] * eig_vecs_[eig_i+2] +\r\n                                    ee[j+18] * eig_vecs_[eig_i+4] + ee[j+27] * eig_vecs_[eig_i+6];\r\n#else\r\n            if (wi[i] == 0) {\r\n                Mat_<double> model (3,3);\r\n                auto * model_data = (double *) model.data;\r\n                const int eig_i = 10 * i + 6;\r\n                for (int j = 0; j < 9; j++)\r\n                    model_data[j] = ee[j   ]*eig_vecs[eig_i  ] + ee[j+9 ]*eig_vecs[eig_i+1] +\r\n                                    ee[j+18]*eig_vecs[eig_i+2] + ee[j+27]*eig_vecs[eig_i+3];\r\n#endif\r\n                models.emplace_back(model);\r\n            }\r\n        return static_cast<int>(models.size());\r\n#else\r\n    int estimate (const std::vector<int> &/*sample*/, std::vector<Mat> &/*models*/) const override {\r\n        CV_Error(cv::Error::StsNotImplemented, \"To use essential matrix solver LAPACK or Eigen has to be installed!\");\r\n#endif\r\n    }\r\n\r\n    // number of possible solutions is 0,2,4,6,8,10\r\n    int getMaxNumberOfSolutions () const override { return 10; }\r\n    int getSampleSize() const override { return 5; }\r\n    Ptr<MinimalSolver> clone () const override {\r\n        return makePtr<EssentialMinimalSolverStewenius5ptsImpl>(*points_mat);\r\n    }\r\nprivate:\r\n    /*\r\n     * Multiply two polynomials of degree one with unknowns x y z\r\n     * @p = (p1 x + p2 y + p3 z + p4) [p1 p2 p3 p4]\r\n     * @q = (q1 x + q2 y + q3 z + q4) [q1 q2 q3 a4]\r\n     * @result is a new polynomial in x^2 xy y^2 xz yz z^2 x y z 1 of size 10\r\n     */\r\n    static inline Matx<double,1,10> multPolysDegOne(const double * const p,\r\n                                                    const double * const q) {\r\n        return\r\n            {p[0]*q[0], p[0]*q[1]+p[1]*q[0], p[1]*q[1], p[0]*q[2]+p[2]*q[0], p[1]*q[2]+p[2]*q[1],\r\n             p[2]*q[2], p[0]*q[3]+p[3]*q[0], p[1]*q[3]+p[3]*q[1], p[2]*q[3]+p[3]*q[2], p[3]*q[3]};\r\n    }\r\n\r\n    /*\r\n     * Multiply two polynomials with unknowns x y z\r\n     * @p is of size 10 and @q is of size 4\r\n     * @p = (p1 x^2 + p2 xy + p3 y^2 + p4 xz + p5 yz + p6 z^2 + p7 x + p8 y + p9 z + p10)\r\n     * @q = (q1 x + q2 y + q3 z + a4) [q1 q2 q3 q4]\r\n     * @result is a new polynomial of size 20\r\n     * x^3 x^2y xy^2 y^3 x^2z xyz y^2z xz^2 yz^2 z^3 x^2 xy y^2 xz yz z^2 x y z 1\r\n     */\r\n    static inline Matx<double, 1, 20> multPolysDegOneAndTwo(const double * const p,\r\n                                                            const double * const q) {\r\n        return Matx<double, 1, 20>\r\n           ({p[0]*q[0], p[0]*q[1]+p[1]*q[0], p[1]*q[1]+p[2]*q[0], p[2]*q[1], p[0]*q[2]+p[3]*q[0],\r\n                  p[1]*q[2]+p[3]*q[1]+p[4]*q[0], p[2]*q[2]+p[4]*q[1], p[3]*q[2]+p[5]*q[0],\r\n                  p[4]*q[2]+p[5]*q[1], p[5]*q[2], p[0]*q[3]+p[6]*q[0], p[1]*q[3]+p[6]*q[1]+p[7]*q[0],\r\n                  p[2]*q[3]+p[7]*q[1], p[3]*q[3]+p[6]*q[2]+p[8]*q[0], p[4]*q[3]+p[7]*q[2]+p[8]*q[1],\r\n                  p[5]*q[3]+p[8]*q[2], p[6]*q[3]+p[9]*q[0], p[7]*q[3]+p[9]*q[1], p[8]*q[3]+p[9]*q[2],\r\n                  p[9]*q[3]});\r\n    }\r\n};\r\nPtr<EssentialMinimalSolverStewenius5pts> EssentialMinimalSolverStewenius5pts::create\r\n        (const Mat &points_) {\r\n    return makePtr<EssentialMinimalSolverStewenius5ptsImpl>(points_);\r\n}\r\n\r\nclass EssentialNonMinimalSolverImpl : public EssentialNonMinimalSolver {\r\nprivate:\r\n    const Mat * points_mat;\r\n    const float * const points;\r\npublic:\r\n    /*\r\n     * Input calibrated points K^-1 x.\r\n     * Linear 8 points algorithm is used for estimation.\r\n     */\r\n    explicit EssentialNonMinimalSolverImpl (const Mat &points_) :\r\n        points_mat(&points_), points ((float *) points_.data) {}\r\n\r\n    int estimate (const std::vector<int> &sample, int sample_size, std::vector<Mat>\r\n            &models, const std::vector<double> &weights) const override {\r\n        if (sample_size < getMinimumRequiredSampleSize())\r\n            return 0;\r\n\r\n        // ------- 8 points algorithm with Eigen and covariance matrix --------------\r\n        double a[9] = {0, 0, 0, 0, 0, 0, 0, 0, 1};\r\n        double AtA[81] = {0}; // 9x9\r\n\r\n        if (weights.empty()) {\r\n            for (int i = 0; i < sample_size; i++) {\r\n                const int pidx = 4*sample[i];\r\n                const double x1 = points[pidx  ], y1 = points[pidx+1],\r\n                             x2 = points[pidx+2], y2 = points[pidx+3];\r\n                a[0] = x2*x1;\r\n                a[1] = x2*y1;\r\n                a[2] = x2;\r\n                a[3] = y2*x1;\r\n                a[4] = y2*y1;\r\n                a[5] = y2;\r\n                a[6] = x1;\r\n                a[7] = y1;\r\n\r\n                // calculate covariance for eigen\r\n                for (int row = 0; row < 9; row++)\r\n                    for (int col = row; col < 9; col++)\r\n                        AtA[row*9+col] += a[row]*a[col];\r\n            }\r\n        } else {\r\n            for (int i = 0; i < sample_size; i++) {\r\n                const int smpl = 4*sample[i];\r\n                const double weight = weights[i];\r\n                const double x1 = points[smpl  ], y1 = points[smpl+1],\r\n                             x2 = points[smpl+2], y2 = points[smpl+3];\r\n                const double weight_times_x2 = weight * x2,\r\n                             weight_times_y2 = weight * y2;\r\n\r\n                a[0] = weight_times_x2 * x1;\r\n                a[1] = weight_times_x2 * y1;\r\n                a[2] = weight_times_x2;\r\n                a[3] = weight_times_y2 * x1;\r\n                a[4] = weight_times_y2 * y1;\r\n                a[5] = weight_times_y2;\r\n                a[6] = weight * x1;\r\n                a[7] = weight * y1;\r\n                a[8] = weight;\r\n\r\n                // calculate covariance for eigen\r\n                for (int row = 0; row < 9; row++)\r\n                    for (int col = row; col < 9; col++)\r\n                        AtA[row*9+col] += a[row]*a[col];\r\n            }\r\n        }\r\n\r\n        // copy symmetric part of covariance matrix\r\n        for (int j = 1; j < 9; j++)\r\n            for (int z = 0; z < j; z++)\r\n                AtA[j*9+z] = AtA[z*9+j];\r\n\r\n#ifdef HAVE_EIGEN\r\n        models = std::vector<Mat>{ Mat_<double>(3,3) };\r\n        const Eigen::JacobiSVD<Eigen::Matrix<double, 9, 9>> svd((Eigen::Matrix<double, 9, 9>(AtA)),\r\n                Eigen::ComputeFullV);\r\n        // extract the last nullspace\r\n        Eigen::Map<Eigen::Matrix<double, 9, 1>>((double *)models[0].data) = svd.matrixV().col(8);\r\n#else\r\n        Matx<double, 9, 9> AtA_(AtA), U, Vt;\r\n        Vec<double, 9> W;\r\n        SVD::compute(AtA_, W, U, Vt, SVD::FULL_UV + SVD::MODIFY_A);\r\n        models = std::vector<Mat> { Mat_<double>(3, 3, Vt.val + 72 /*=8*9*/) };\r\n#endif\r\n        FundamentalDegeneracy::recoverRank(models[0], false /*E*/);\r\n        return 1;\r\n    }\r\n    int getMinimumRequiredSampleSize() const override { return 8; }\r\n    int getMaxNumberOfSolutions () const override { return 1; }\r\n    Ptr<NonMinimalSolver> clone () const override {\r\n        return makePtr<EssentialNonMinimalSolverImpl>(*points_mat);\r\n    }\r\n};\r\nPtr<EssentialNonMinimalSolver> EssentialNonMinimalSolver::create (const Mat &points_) {\r\n    return makePtr<EssentialNonMinimalSolverImpl>(points_);\r\n}\r\n}}", "meta": {"hexsha": "381fa07d53b143da6c70fd8bc5453df0f47f8d59", "size": 16450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencv/sources/modules/calib3d/src/usac/essential_solver.cpp", "max_stars_repo_name": "vrushank-agrawal/opencv-x64-cmake", "max_stars_repo_head_hexsha": "3f9486510d706c8ac579ac82f5d58f667f948124", "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": "opencv/sources/modules/calib3d/src/usac/essential_solver.cpp", "max_issues_repo_name": "vrushank-agrawal/opencv-x64-cmake", "max_issues_repo_head_hexsha": "3f9486510d706c8ac579ac82f5d58f667f948124", "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": "opencv/sources/modules/calib3d/src/usac/essential_solver.cpp", "max_forks_repo_name": "vrushank-agrawal/opencv-x64-cmake", "max_forks_repo_head_hexsha": "3f9486510d706c8ac579ac82f5d58f667f948124", "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": 48.3823529412, "max_line_length": 119, "alphanum_fraction": 0.5333738602, "num_tokens": 5012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5332302769959587}}
{"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_REM_PIO2_MEDIUM_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REM_PIO2_MEDIUM_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object computes the remainder modulo\n    \\f$\\pi/2\\f$ with medium algorithm, and the angle quadrant between 0 and 3.\n\n\n    @par Header <boost/simd/function/rem_pio2_medium.hpp>\n\n    @par Note:\n\n\n    - This is a medium version accurate if the input is in:\n     \\f$[-2^6\\pi,2^6\\pi]\\f$ for float,\n     \\f$[-2^{18}\\pi,2^{18}\\pi]\\f$ for double.\n    \\par\n\n    The reduction of the argument modulo \\f$\\pi/2\\f$ is generally\n    the most difficult part of trigonometric evaluations.\n    The accurate algorithm @ref rem_pio2 is over costly and implies the knowledge\n    of a few hundred \\f$\\pi\\f$ decimals\n    some simpler algorithms as this one\n    can be used, but the precision is only insured on smaller intervals.\n\n    @see rem_pio2, rem_pio2_straight,rem_2pi,  rem_pio2_cephes,\n\n\n    @par Example:\n\n      @snippet rem_pio2_medium.cpp rem_pio2_medium\n\n    @par Possible output:\n\n      @snippet rem_pio2_medium.txt rem_pio2_medium\n\n  **/\n  std::pair<IEEEValue, IEEEValue> rem_pio2_medium(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/rem_pio2_medium.hpp>\n#include <boost/simd/function/simd/rem_pio2_medium.hpp>\n\n#endif\n", "meta": {"hexsha": "394017f8981afc964040915135672fcda4e02df8", "size": 1764, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/rem_pio2_medium.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/function/rem_pio2_medium.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/function/rem_pio2_medium.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": 28.9180327869, "max_line_length": 100, "alphanum_fraction": 0.6445578231, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5332302717888179}}
{"text": "#include \"Hungarian.h\"\n#include <iostream>\n#include <cmath>\n#include <vector>\n#include <opencv2/opencv.hpp>\n#include <string>\n#include <pangolin/pangolin.h>  //\u57fa\u4e8eopenGL\u7684\u753b\u56fe\u5de5\u5177Pangolin\u5934\u6587\u4ef6\n#include <unistd.h>             // C++\u4e2d\u63d0\u4f9b\u5bf9\u64cd\u4f5c\u7cfb\u7edf\u8bbf\u95ee\u529f\u80fd\u7684\u5934\u6587\u4ef6\uff0c\u5982fork/pipe/\u5404\u79cdI/O\uff08read/write/close\u7b49\u7b49\uff09\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <sophus/se3.hpp>\n#include <boost/format.hpp>   // \u5177\u6709\u683c\u5f0f\u5316\u8f93\u51fa\u529f\u80fd\n\nusing namespace std;\nusing namespace Eigen;\n//using Eigen::MatrixXd;\nint testEigen1()\n{\n\n  // [12  7  9  /7  9]\n  // [ 8  9  6  6  /6]\n  // [ 7 17 12 14  9]\n  // [15 14  /6 11 10]\n  // [ /4 10  7 10  9]\n  // [ 1  /2  3  4  5]\n\n  MatrixXd m(2, 2);            //MatrixXd\u8868\u793a\u662f\u4efb\u610f\u5c3a\u5bf8\u7684\u77e9\u9635ixj, m(2,2)\u4ee3\u8868\u4e00\u4e2a2x2\u7684\u65b9\u5757\u77e9\u9635\n  m(0, 0) = 3;                 //\u4ee3\u8868\u77e9\u9635\u5143\u7d20a11\n  m(1, 0) = 2.5;               //a21\n  m(0, 1) = -1;                //a12\n  m(1, 1) = m(1, 0) + m(0, 1); //a22=a21+a12\n  cout << m << endl;           //\u8f93\u51fa\u77e9\u9635m\n\n  std::vector<std::vector<double>> DistMatrix(6);\n  std::vector<int> Assignment;\n  DistMatrix[0] = {12, 7, 9, 7, 9};\n  DistMatrix[1] = {8, 9, 6, 6, 6};\n  DistMatrix[2] = {7, 17, 12, 14, 9};\n  DistMatrix[3] = {15, 14, 6, 11, 10};\n  DistMatrix[4] = {4, 10, 7, 10, 9};\n  DistMatrix[5] = {1, 2, 3, 4, 5};\n  HungarianAlgorithm algo;\n  algo.Solve(DistMatrix, Assignment);\n  for (auto &&value : Assignment)\n  {\n    std::cout << value << std::endl;\n  }\n  return 0;\n}\n\nint testEigen5()\n{\n    Matrix3d rotation_matrix = Matrix3d::Identity();\n //\u65cb\u8f6c\u5411\u91cf\u4f7f\u7528AngleAxis\uff0c\u8fd0\u7b97\u53ef\u4ee5\u5f53\u505a\u77e9\u9635\n    AngleAxisd rotation_vector(M_PI / 4, Vector3d(0,0,1));     //\u773cZ\u8f74\u65cb\u8f6c45\u00b0\n    cout.precision(3);                                         //\u8f93\u51fa\u7cbe\u5ea6\u4e3a\u5c0f\u6570\u70b9\u540e\u4e24\u4f4d\n    cout << \"rotation matrix = \\n\" << rotation_vector.matrix() << endl;\n    //\u7528matrix\u8f6c\u6362\u6210\u77e9\u9635\u53ef\u4ee5\u76f4\u63a5\u8d4b\u503c\n    rotation_matrix = rotation_vector.toRotationMatrix();\n\n    //\u4f7f\u7528Amgleanxis\u53ef\u4ee5\u8fdb\u884c\u5750\u6807\u53d8\u6362\n    Vector3d v(1, 0, 0);\n    Vector3d v_rotated = rotation_vector * v;\n    cout << \"(1,0,0) after rotation (by angle axis) = \" << v_rotated.transpose() << endl;\n\n    //\u4f7f\u7528\u65cb\u8f6c\u77e9\u9635\n    v_rotated = rotation_matrix * v;\n    cout << \"(1,0,0) after rotation (by matrix) = \" << v_rotated.transpose() << endl;\n\n    //\u6b27\u62c9\u89d2\uff1a\u53ef\u4ee5\u5c06\u77e9\u9635\u76f4\u63a5\u8f6c\u6362\u6210\u6b27\u62c9\u89d2\n    Vector3d euler_angles = rotation_matrix.eulerAngles(2, 1, 0);       //\u6309\u7167ZYX\u987a\u5e8f\n    cout << \"yaw pitch row = \"<< euler_angles.transpose() << endl;\n\n    //\u6b27\u5f0f\u53d8\u6362\u77e9\u9635\u4f7f\u7528Eigen::Isometry\n    Isometry3d T = Isometry3d::Identity();      //\u5b9e\u8d28\u4e3a4*4\u7684\u77e9\u9635\n    T.rotate(rotation_vector);                  //\u6309\u7167rotation_vector\u8fdb\u884c\u8f6c\u5316\n    T.pretranslate(Vector3d(1, 3, 4));          //\u5e73\u79fb\u5411\u91cf\u8bbe\u4e3a\uff081\uff0c 3\uff0c 4\uff09\n    cout << \"Transform matrix = \\n\" << T.matrix() <<endl;\n\n    //\u53d8\u6362\u77e9\u9635\u8fdb\u884c\u5750\u6807\u53d8\u6362\n    Vector3d v_transformed = T *v;\n    cout << \"v transormed =\" << v_transformed.transpose() << endl;\n\n    //\u56db\u5143\u6570\n    //\u76f4\u63a5\u628aAngleAxis\u8d4b\u503c\u7ed9\u56db\u5143\u6570\uff0c\u53cd\u4e4b\u4ea6\u7136\n    Quaterniond q = Quaterniond(rotation_vector);\n    cout << \"quaternion from rotation vector = \" << q.coeffs().transpose() << endl;\n    q = Quaterniond(rotation_matrix);\n    cout << \"quaternion from rotation matrix = \"<< q.coeffs().transpose() << 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;\n    cout << \"(1,0,0) after rotation = \" << v_rotated.transpose() << endl;\n    cout << \"should be equal to \" << (q * Quaterniond(0, 1, 0, 0) * q.inverse()).coeffs().transpose() << endl;\n    cout << \".......................\" << endl;\n//   // 1 \u5b9a\u4e49\u65cb\u8f6c\u77e9\u9635\u4e0e\u5e73\u79fb\u5411\u91cf\u3000R t\n//   // \u6cbfZ\u8f74\u8f6c90\u5ea6\u7684\u65cb\u8f6c\u77e9\u9635\n//   Eigen::Matrix3f R = Eigen::AngleAxisf(M_PI / 2, Eigen::Vector3f(0.707106781, 0, 0.707106781)).toRotationMatrix();\n//   //\u5b9a\u4e49\u5e73\u79fb\u5411\u91cf\n//   Eigen::Vector3f t(1, 0, 0); // \u6cbfX\u8f74\u5e73\u79fb1\n//   cout << R << endl;\n//   cout << t << endl;\n//   // SO(3) \u65cb\u8f6c\u77e9\u9635\u674e\u7fa4\u4e0e\u674e\u4ee3\u6570\n//   //\u65cb\u8f6c\u77e9\u9635\u674e\u7fa4SO(3)\u53ef\u4ee5\u7531\u3000\u65cb\u8f6c\u77e9\u9635/\u65cb\u8f6c\u5411\u91cf/\u56db\u5143\u7d20\u5f97\u5230,\u5e76\u4e14\u90fd\u662f\u7b49\u6548\u7684\u3000\n//   //(\u6ce8\u610f\u674e\u7fa4\u7684\u8868\u793a\u5f62\u5f0f    Sophus::SO3)\n//   Sophus::SO3f SO3_R(R);                             // Sophus::SO(3)\u53ef\u4ee5\u76f4\u63a5\u4ece\u65cb\u8f6c\u77e9\u9635\u6784\u9020\n//   cout << \"SO(3) from VECTOR: \" << SO3_R.log().transpose() << endl;\n//   Sophus::SO3f SO3_V = Sophus::SO3f::rotZ(M_PI / 2); // \u4ea6\u53ef\u4ece\u65cb\u8f6c\u5411\u91cf\u6784\u9020(\u6ce8\u610f\u6b64\u65f6\u65cb\u8f6c\u53d8\u91cf\u7684\u5f62\u5f0f)\n//   cout << \"SO(3) from vector: \" << SO3_V.log().transpose() << endl;\n//   Eigen::Quaternionf q(R);                           // \u6216\u8005\u56db\u5143\u6570\n//   Sophus::SO3f SO3_q(q);\n//   cout << \"SO(3) from quaternion :\" << SO3_q.log().transpose() << endl;\n\n//   //\u65cb\u8f6c\u77e9\u9635\u674e\u4ee3\u6570\u3000\uff08\u674e\u7fa4\u7684\u5bf9\u6570\u6620\u5c04\uff09\n//   //(SO(3)\u674e\u4ee3\u6570\u8868\u793a\u5f62\u5f0f    Eigen::Vector3d\n//   Eigen::Vector3f so3 = SO3_R.log();\n//   cout << \"so3 = \" << so3.transpose() << endl;\n//   // hat \u4e3a\u5411\u91cf==>\u53cd\u5bf9\u79f0\u77e9\u9635 (\u674e\u4ee3\u6570\u5411\u91cf\u3000\u5bf9\u5e94\u7684\u53cd\u5bf9\u79f0\u77e9\u9635)\n//   cout << \"so3 hat=\\n\"\n//        << Sophus::SO3f::hat(so3) << endl;\n//   // \u76f8\u5bf9\u7684\uff0cvee\u4e3a\u53cd\u5bf9\u79f0==>\u5411\u91cf\n//   cout << \"so3 hat vee= \" << Sophus::SO3f::vee(Sophus::SO3f::hat(so3)).transpose() << endl; // transpose\u7eaf\u7cb9\u662f\u4e3a\u4e86\u8f93\u51fa\u7f8e\u89c2\u4e00\u4e9b\n\n//   //\u65cb\u8f6c\u77e9\u9635\u674e\u4ee3\u6570\u7684 \u589e\u91cf\u6270\u52a8\u6a21\u578b\u7684\u66f4\u65b0\n//   Eigen::Vector3f update_so3(1e-4, 0, 0); //\u5047\u8bbe\u66f4\u65b0\u91cf\u4e3a\u8fd9\u4e48\u591a\n//   Sophus::SO3f SO3_updated = Sophus::SO3f::exp(update_so3) * SO3_R;\n//   cout << \"SO3 updated = \" << SO3_updated.log() << endl;\n\n//   //SE(3) \u53d8\u6362\u77e9\u9635\u674e\u7fa4\u4e0e\u674e\u4ee3\u6570\n//   //\u53d8\u6362\u77e9\u9635\u674e\u7fa4SE(3)\u53ef\u4ee5\u7531\u3000\u65cb\u8f6c\u77e9\u9635/\u56db\u5143\u7d20 + \u5e73\u79fb\u5411\u91cf\u5f97\u5230,\u5e76\u4e14\u90fd\u662f\u7b49\u6548\u7684\u3000\n//   Sophus::SE3f SE3_Rt(R, t); // \u4eceR,t\u6784\u9020SE(3)\n//   Sophus::SE3f SE3_qt(q, t); // \u4eceq,t\u6784\u9020SE(3)\n//   cout << \"SE3 from R,t= \" << endl\n//        << SE3_Rt.log() << endl;\n//   cout << \"SE3 from q,t= \" << endl\n//        << SE3_qt.log() << endl;\n\n//   //\u53d8\u6362\u77e9\u9635\u674e\u4ee3\u6570\u3000\uff08\u674e\u7fa4\u7684\u5bf9\u6570\u6620\u5c04\uff09\n//   //(SE(3)\u674e\u4ee3\u6570\u8868\u793a\u5f62\u5f0f    Eigen::Matrix<double,6,1>   sophus\u4e2d\u65cb\u8f6c\u5728\u524d\uff0c\u5e73\u79fb\u5728\u540e\n//   typedef Eigen::Matrix<float, 6, 1> Vector6f;\n//   Vector6f se3 = SE3_Rt.log();\n//   cout << \"se3 = \" << se3.transpose() << endl;\n//   //\u5411\u91cf\u7684\u53cd\u5bf9\u79f0\u77e9\u9635\u8868\u793a\u5f62\u5f0f\u7684\u53d8\u6362\n//   cout << \"se3 hat = \" << endl\n//        << Sophus::SE3f::hat(se3) << endl;\n//   cout << \"se3 hat vee = \" << Sophus::SE3f::vee(Sophus::SE3f::hat(se3)).transpose() << endl;\n//   //\u53d8\u6362\u77e9\u9635\u674e\u4ee3\u6570\u7684 \u589e\u91cf\u6270\u52a8\u6a21\u578b\u7684\u66f4\u65b0\n//   Vector6f update_se3; //\u66f4\u65b0\u91cf\n//   update_se3.setZero();\n//   update_se3(0, 0) = 1e-4;\n//   cout << \"se3_update =  \" << update_se3.transpose() << endl;\n//   Sophus::SE3f SE3_updated = Sophus::SE3f::exp(update_se3) * SE3_Rt;\n//   cout << \"SE3 updated = \" << endl\n//        << SE3_updated.matrix() << endl;\n  return 0;\n}\n\nint testEigen6()\n{\n    //\u8bfb\u53d6\u56fe\u50cf\n   cv::Mat img_1 = cv::imread(\"/home/chenzhengxi/study/slam/aloeL.jpg\", cv::IMREAD_COLOR);\n   cv::Mat img_2 = cv::imread(\"/home/chenzhengxi/study/slam/aloeR.jpg\", cv::IMREAD_COLOR);\n   assert(img_1.data != nullptr && img_2.data != nullptr);\n   //\u5728\u7a0b\u5e8f\u8fd0\u884c\u65f6cv::assert()\u8ba1\u7b97\u62ec\u53f7\u5185\u7684\u8868\u8fbe\u5f0f\uff0c\u5982\u679c\u8868\u8fbe\u5f0f\u4e3aFALSE (\u62160), \u7a0b\u5e8f\u5c06\u62a5\u544a\u9519\u8bef\uff0c\u5e76\u7ec8\u6b62\u6267\u884c\u3002\n   //\u5982\u679c\u8868\u8fbe\u5f0f\u4e0d\u4e3a0\uff0c\u5219\u7ee7\u7eed\u6267\u884c\u540e\u9762\u7684\u8bed\u53e5\u3002\n\n   //\u521d\u59cb\u5316\n   vector<cv::KeyPoint> keypoints_1, keypoints_2;   //\u5173\u952e\u70b9/\u89d2\u70b9\n   /**\n   opencv\u4e2dkeypoint\u7c7b\u7684\u9ed8\u8ba4\u6784\u9020\u51fd\u6570\u4e3a\uff1a\n   CV_WRAP KeyPoint() : pt(0,0), size(0), angle(-1), response(0), octave(0), class_id(-1) {}\n   pt(x,y):\u5173\u952e\u70b9\u7684\u70b9\u5750\u6807\uff1b // size():\u8be5\u5173\u952e\u70b9\u90bb\u57df\u76f4\u5f84\u5927\u5c0f\uff1b // angle:\u89d2\u5ea6\uff0c\u8868\u793a\u5173\u952e\u70b9\u7684\u65b9\u5411\uff0c\u503c\u4e3a[0,360)\uff0c\u8d1f\u503c\u8868\u793a\u4e0d\u4f7f\u7528\u3002\n   response:\u54cd\u5e94\u5f3a\u5ea6\uff0c\u9009\u62e9\u54cd\u5e94\u6700\u5f3a\u7684\u5173\u952e\u70b9;   octacv:\u4ece\u54ea\u4e00\u5c42\u91d1\u5b57\u5854\u5f97\u5230\u7684\u6b64\u5173\u952e\u70b9\u3002\n   class_id:\u5f53\u8981\u5bf9\u56fe\u7247\u8fdb\u884c\u5206\u7c7b\u65f6\uff0c\u7528class_id\u5bf9\u6bcf\u4e2a\u5173\u952e\u70b9\u8fdb\u884c\u533a\u5206\uff0c\u9ed8\u8ba4\u4e3a-1\u3002\n   **/\n   cv::Mat descriptors_1, descriptors_2;      //\u63cf\u8ff0\u5b50\n   //\u521b\u5efaORB\u5bf9\u8c61\uff0c\u53c2\u6570\u4e3a\u9ed8\u8ba4\u503c\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   \u201cPtr<FeatureDetector> detector = \u201d\u7b49\u4ef7\u4e8e \u201cFeatureDetector * detector =\u201d\n   Ptr\u662fOpenCV\u4e2d\u4f7f\u7528\u7684\u667a\u80fd\u6307\u9488\u6a21\u677f\u7c7b\uff0c\u53ef\u4ee5\u8f7b\u677e\u7ba1\u7406\u5404\u79cd\u7c7b\u578b\u7684\u6307\u9488\u3002\n   \u7279\u5f81\u68c0\u6d4b\u5668FeatureDetetor\u662f\u865a\u7c7b\uff0c\u901a\u8fc7\u5b9a\u4e49FeatureDetector\u7684\u5bf9\u8c61\u53ef\u4ee5\u4f7f\u7528\u591a\u79cd\u7279\u5f81\u68c0\u6d4b\u53ca\u5339\u914d\u65b9\u6cd5\uff0c\u901a\u8fc7create()\u51fd\u6570\u8c03\u7528\u3002\n   \u63cf\u8ff0\u5b50\u63d0\u53d6\u5668DescriptorExtractor\u662f\u63d0\u53d6\u5173\u952e\u70b9\u7684\u63cf\u8ff0\u5411\u91cf\u7c7b\u62bd\u8c61\u57fa\u7c7b\u3002\n   \u63cf\u8ff0\u5b50\u5339\u914d\u5668DescriptorMatcher\u7528\u4e8e\u7279\u5f81\u5339\u914d\uff0c\"Brute-force-Hamming\"\u8868\u793a\u4f7f\u7528\u6c49\u660e\u8ddd\u79bb\u8fdb\u884c\u5339\u914d\u3002\n   **/\n\n   //\u7b2c\u4e00\u6b65\uff0c\u68c0\u6d4bOriented Fast\u89d2\u70b9\u4f4d\u7f6e\n   chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n   detector->detect(img_1, keypoints_1);     //\u5bf9\u53c2\u65701\u56fe\u50cf\u8fdb\u884c\u7279\u5f81\u7684\u63d0\u53d6\uff0c\u5e76\u5b58\u653e\u5165\u53c2\u65702\u7684\u6570\u7ec4\u4e2d\n   detector->detect(img_2, keypoints_2);\n\n   //\u7b2c\u4e8c\u6b65\uff0c\u6839\u636e\u89d2\u70b9\u8ba1\u7b97BREIF\u63cf\u8ff0\u5b50\n   descriptor->compute(img_1, keypoints_1, descriptors_1);   //computer()\u8ba1\u7b97\u5173\u952e\u70b9\u7684\u63cf\u8ff0\u5b50\u5411\u91cf\uff08\u6ce8\u610f\u601d\u8003\u53c2\u6570\u8bbe\u7f6e\u7684\u5408\u7406\u6027\uff09\n   descriptor->compute(img_2, keypoints_2, descriptors_2);\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 << \"extract ORB cost = \" << time_used.count() << \" seconds. \" << endl;\n   cv::Mat outimg1;\n   drawKeypoints(img_1, keypoints_1, outimg1, cv::Scalar::all(-1), cv::DrawMatchesFlags::DEFAULT);\n   cv::imshow(\"ORB features\", outimg1);\n   cv::imwrite(\"feaure1.png\", outimg1);\n\n   //\u7b2c\u4e09\u6b65\uff0c \u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528hamming\u8ddd\u79bb\n   vector<cv::DMatch> matches;    //DMatch\u662f\u5339\u914d\u5173\u952e\u70b9\u63cf\u8ff0\u5b50 \u7c7b, matches\u7528\u4e8e\u5b58\u653e\u5339\u914d\u9879\n   t1 = chrono::steady_clock::now();\n   matcher->match(descriptors_1, descriptors_2, matches); //\u5bf9\u53c2\u65701 2\u7684\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u5e76\u5c06\u5339\u914d\u9879\u5b58\u653e\u4e8ematches\u4e2d\n   t2 = chrono::steady_clock::now();\n   time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n   cout << \"match the ORB cost: \" << time_used.count() << \"seconds. \" << endl;\n\n   //\u7b2c\u56db\u6b65\uff0c\u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n   //\u8ba1\u7b97\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb\n   auto min_max = minmax_element(matches.begin(), matches.end(),\n       [](const cv::DMatch &m1, const cv::DMatch &m2){ return m1.distance < m2.distance; });\n   // auto \u53ef\u4ee5\u5728\u58f0\u660e\u53d8\u91cf\u7684\u65f6\u5019\u6839\u636e\u53d8\u91cf\u521d\u59cb\u503c\u7684\u7c7b\u578b\u81ea\u52a8\u4e3a\u6b64\u53d8\u91cf\u9009\u62e9\u5339\u914d\u7684\u7c7b\u578b\n   // minmax_element()\u8fd4\u56de\u6307\u5411\u8303\u56f4\u5185\u6700\u5c0f\u548c\u6700\u5927\u5143\u7d20\u7684\u4e00\u5bf9\u8fed\u4ee3\u5668\u3002\u53c2\u65701 2\u4e3a\u8d77\u6b62\u8fed\u4ee3\u5668\u8303\u56f4\n   // \u53c2\u65703\u662f\u4e8c\u8fdb\u5236\u51fd\u6570\uff0c\u8be5\u51fd\u6570\u63a5\u53d7\u8303\u56f4\u5185\u7684\u4e24\u4e2a\u5143\u7d20\u4f5c\u4e3a\u53c2\u6570\uff0c\u5e76\u8fd4\u56de\u53ef\u8f6c\u6362\u4e3abool\u7684\u503c\u3002\n   // \u8fd4\u56de\u7684\u503c\u6307\u793a\u4f5c\u4e3a\u7b2c\u4e00\u4e2a\u53c2\u6570\u4f20\u9012\u7684\u5143\u7d20\u662f\u5426\u5c0f\u4e8e\u7b2c\u4e8c\u4e2a\u3002\u8be5\u51fd\u6570\u4e0d\u5f97\u4fee\u6539\u5176\u4efb\u4f55\u53c2\u6570\u3002\n   double min_dist = min_max.first->distance;  // min_max\u5b58\u50a8\u4e86\u4e00\u5806\u8fed\u4ee3\u5668\uff0cfirst\u6307\u5411\u6700\u5c0f\u5143\u7d20\n   double max_dist = min_max.second->distance; // second\u6307\u5411\u6700\u5927\u5143\u7d20\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\u6700\u5c0f\u8ddd\u79bb\u65f6\uff0c\u5c31\u8ba4\u4e3a\u5339\u914d\u6709\u8bef\u3002\u4f46\u6709\u65f6\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f\uff0c\u6240\u4ee5\u8981\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650\u3002\n   vector<cv::DMatch> good_matches;  //\u5b58\u653e\u826f\u597d\u7684\u5339\u914d\u9879\n   for(int i = 0; i < descriptors_1.rows; ++i){\n       if(matches[i].distance <= max(2 * min_dist, 30.0)){\n           good_matches.push_back(matches[i]);\n       }\n   }\n\n   //\u7b2c\u4e94\u6b65\uff0c\u7ed8\u5236\u5339\u914d\u7ed3\u679c\n   cv::Mat img_match;         //\u5b58\u653e\u6240\u6709\u5339\u914d\u70b9\n   cv::Mat img_goodmatch;     //\u5b58\u653e\u597d\u7684\u5339\u914d\u70b9\n   // drawMatches\u7528\u4e8e\u7ed8\u5236\u4e24\u5e45\u56fe\u50cf\u7684\u5339\u914d\u5173\u952e\u70b9\u3002\n   // \u53c2\u65701\u662f\u7b2c\u4e00\u4e2a\u6e90\u56fe\u50cf\uff0c\u53c2\u65702\u662f\u5176\u5173\u952e\u70b9\u6570\u7ec4\uff1b\u53c2\u65703\u662f\u7b2c\u4e8c\u5f20\u539f\u56fe\u50cf\uff0c\u53c2\u65704\u662f\u5176\u5173\u952e\u70b9\u6570\u7ec4\n   // \u53c2\u65705\u662f\u4e24\u5f20\u56fe\u50cf\u7684\u5339\u914d\u5173\u952e\u70b9\u6570\u7ec4,\u53c2\u65706\u7528\u4e8e\u5b58\u653e\u51fd\u6570\u7684\u7ed8\u5236\u7ed3\u679c\n   drawMatches(img_1, keypoints_1, img_2, keypoints_2, matches, img_match);\n   drawMatches(img_1, keypoints_1, img_2, keypoints_2, good_matches, img_goodmatch);\n   imshow(\"all matches\", img_match);\n   imshow(\"good matches\", img_goodmatch);\n   imwrite(\"match1.png\", img_match);\n   imwrite(\"goodmatch1.png\", img_goodmatch);\n\n   cv::waitKey(0);\n    return 0;\n}\n// \u8bb0\u5f55\u51c6\u786e\u6587\u4ef6\u8def\u5f84\nstring left_file = \"/home/chenzhengxi/study/slam/left.png\";\nstring right_file = \"/home/chenzhengxi/study/slam/right.jpg\";\nstring disparity_file = \"/home/chenzhengxi/study/slam/disparity.png\";\nboost::format fmt_others(\"/home/chenzhengxi/study/slam/%01d.png\");    // other files\n\n// \u5728pangolin\u4e2d\u753b\u56fe\nvoid showPointCloud(const vector<Vector4d, Eigen::aligned_allocator<Vector4d>> &pointcloud);\n\nint testEigen4()\n{\n    // \u76f8\u673a\u5185\u53c2\uff0c\u4e00\u822c\u4e3a\u5df2\u77e5\u6570\u636e\n    double fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n    // \u53cc\u76ee\u76f8\u673a\u57fa\u7ebf\uff0c\u4e00\u822c\u5df2\u77e5\n    double b = 0.573;\n\n    // \u8bfb\u53d6\u56fe\u50cf\n    cv::Mat left = cv::imread(left_file, 0);   //imread()\u53c2\u65702\u4e3a0\u65f6\uff0c\u8868\u793a\u8fd4\u56de\u7070\u5ea6\u56fe\u50cf\uff0c\u9ed8\u8ba4\u503c\u4e3a1\uff0c\u4ee3\u8868\u8fd4\u56de\u5f69\u8272\u56fe\u50cf\n    cv::Mat right = cv::imread(right_file, 0); //\u4ece\u6587\u4ef6\u8def\u5f84\u4e2d\u8bfb\u53d6\u4e24\u5e45\u56fe\u50cf\uff0c\u8fd4\u56de\u7070\u5ea6\u56fe\u50cf\n    cv::Ptr<cv::StereoSGBM> sgbm = cv::StereoSGBM::create(\n        0, 96, 9, 8 * 9 * 9, 32 * 9 * 9, 1, 63, 10, 100, 32);    // \u8c03\u7528OpenCv\u4e2d\u7684SGBM\u7b97\u6cd5\uff0c\u7528\u4e8e\u8ba1\u7b97\u5de6\u53f3\u56fe\u50cf\u7684\u89c6\u5dee\n    cv::Mat disparity_sgbm, disparity;\n    sgbm->compute(left, right, disparity_sgbm);   //\u5c06\u89c6\u5dee\u7684\u8ba1\u7b97\u7ed3\u679c\u653e\u5165disparity_sgbm\u77e9\u9635\u4e2d\n    disparity_sgbm.convertTo(disparity, CV_32F, 1.0 / 16.0f); //\u5c06\u77e9\u9635disparity_sgbm\u8f6c\u6362\u4e3a\u62ec\u53f7\u4e2d\u7684\u683c\u5f0f(32\u4f4d\u7a7a\u95f4\u7684\u5355\u7cbe\u5ea6\u6d6e\u70b9\u578b\u77e9\u9635)\n\n    // \u751f\u6210\u70b9\u4e91\n    vector<Vector4d, Eigen::aligned_allocator<Vector4d>> pointcloud; //\u58f0\u660e\u4e00\u4e2a4\u7ef4\u7684\u53cc\u7cbe\u5ea6\u6d6e\u70b9\u578b\u53ef\u53d8\u957f\u52a8\u6001\u6570\u7ec4\n\n    // \u5982\u679c\u81ea\u5df1\u7684\u673a\u5668\u6162\uff0c\u53ef\u4ee5\u628a++v\u548c++u\u6539\u6210v+=2, u+=2\n    for (int v = 0; v < left.rows; ++v)\n        for (int u = 0; u < left.cols; ++u) {\n            if (disparity.at<float>(v, u) <= 0.0 || disparity.at<float>(v, u) >= 96.0) continue;\n            //Mat.at<\u5b58\u50a8\u7c7b\u578b\u540d\u79f0>(\u884c\uff0c\u5217)[\u901a\u9053]\uff0c\u7528\u4ee5\u904d\u5386\u50cf\u7d20\u3002\u7701\u7565\u901a\u9053\u90e8\u5206\u65f6\uff0c\u53ef\u4ee5\u770b\u505a\u4e8c\u7ef4\u6570\u7ec4\u7b80\u5355\u904d\u5386\uff0c\u4f8b\u5982M.at<uchar>(512-1,512*3-1)\uff1b\n\n            Vector4d point(0, 0, 0, left.at<uchar>(v, u) / 255.0); // \u524d\u4e09\u7ef4\u4e3axyz,\u7b2c\u56db\u7ef4\u4e3a\u989c\u8272\u3002\u7b2c\u56db\u7ef4\u6570\u503c\u5f52\u4e00\u5316\u3002\n\n            // \u6839\u636e\u53cc\u76ee\u6a21\u578b\u8ba1\u7b97 point \u7684\u4f4d\u7f6e\n            double x = (u - cx) / fx;      //\u50cf\u7d20\u5750\u6807\u8f6c\u6362\u4e3a\u5f52\u4e00\u5316\u5750\u6807\n            double y = (v - cy) / fy;\n            double depth = fx * b / (disparity.at<float>(v, u));  //\u8ba1\u7b97\u5404\u50cf\u7d20\u70b9\u6df1\u5ea6\n            //\u8ba1\u7b97\u5e26\u6df1\u5ea6\u4fe1\u606f\u7684\u5404\u70b9\u5750\u6807\n            point[0] = x * depth;\n            point[1] = y * depth;\n            point[2] = depth;\n\n            pointcloud.push_back(point);   //\u5c06\u5404\u70b9\u4fe1\u606f\u538b\u5165\u70b9\u4e91\u6570\u7ec4\n        }\n\n    cv::imshow(\"disparity\", disparity / 96.0); //\u8f93\u51fa\u663e\u793adisparuty\uff0c\u663e\u793a\u7a97\u53e3\u547d\u540d\u4e3a\u5f15\u53f7\u4e2d\u7684\u5185\u5bb9\n    cv::waitKey(0);           //\u7b49\u5f85\u5173\u95ed\u663e\u793a\u7a97\u53e3\uff0c\u62ec\u53f7\u5185\u53c2\u6570\u4e3a\u96f6\u5219\u8868\u793a\u7b49\u5f85\u8f93\u5165\u4e00\u4e2a\u6309\u952e\u624d\u4f1a\u5173\u95ed\uff0c\u4e3a\u6570\u503c\u5219\u8868\u793a\u7b49\u5f85X\u6beb\u79d2\u540e\u5173\u95ed\n    // \u753b\u51fa\u70b9\u4e91\n    showPointCloud(pointcloud);\n    return 0;\n}\n    //\u5b9a\u4e49\u753b\u51fa\u70b9\u4e91\u7684\u51fd\u6570,\u51fd\u6570\u53c2\u6570\u4e3a\u56db\u7ef4\u52a8\u6001\u6570\u7ec4\u7684\u5f15\u7528\nvoid showPointCloud(const vector<Vector4d, Eigen::aligned_allocator<Vector4d>> &pointcloud) {\n\n    if (pointcloud.empty()) {\n        cerr << \"Point cloud is empty!\" << endl;\n        return;\n    }\n\n    pangolin::CreateWindowAndBind(\"Point Cloud Viewer\", 1024, 768);   //\u521b\u5efa\u4e00\u4e2aPangolin\u7684\u753b\u56fe\u7a97\u53e3,\u58f0\u660e\u547d\u540d\u4ee5\u53ca\u663e\u793a\u7684\u5206\u8fa8\u7387\n    glEnable(GL_DEPTH_TEST);    //\u542f\u7528\u6df1\u5ea6\u7f13\u5b58\u3002\n    glEnable(GL_BLEND);         //\u542f\u7528gl_blend\u6df7\u5408\u3002Blend\u6df7\u5408\u662f\u5c06\u6e90\u8272\u548c\u76ee\u6807\u8272\u4ee5\u67d0\u79cd\u65b9\u5f0f\u6df7\u5408\u751f\u6210\u7279\u6548\u7684\u6280\u672f\u3002\n    //\u6df7\u5408\u5e38\u7528\u6765\u7ed8\u5236\u900f\u660e\u6216\u534a\u900f\u660e\u7684\u7269\u4f53\u3002\u5728\u6df7\u5408\u4e2d\u8d77\u5173\u952e\u4f5c\u7528\u7684\u03b1\u503c\u5b9e\u9645\u4e0a\u662f\u5c06\u6e90\u8272\u548c\u76ee\u6807\u8272\u6309\u7ed9\u5b9a\u6bd4\u7387\u8fdb\u884c\u6df7\u5408\uff0c\u4ee5\u8fbe\u5230\u4e0d\u540c\u7a0b\u5ea6\u7684\u900f\u660e\u3002\n    //\u03b1\u503c\u4e3a0\u5219\u5b8c\u5168\u900f\u660e\uff0c\u03b1\u503c\u4e3a1\u5219\u5b8c\u5168\u4e0d\u900f\u660e\u3002\u6df7\u5408\u64cd\u4f5c\u53ea\u80fd\u5728RGBA\u6a21\u5f0f\u4e0b\u8fdb\u884c\uff0c\u989c\u8272\u7d22\u5f15\u6a21\u5f0f\u4e0b\u65e0\u6cd5\u6307\u5b9a\u03b1\u503c\u3002\n    //\u7269\u4f53\u7684\u7ed8\u5236\u987a\u5e8f\u4f1a\u5f71\u54cd\u5230OpenGL\u7684\u6df7\u5408\u5904\u7406\u3002\n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);  //\u6df7\u5408\u51fd\u6570\u3002\u53c2\u65701\u662f\u6e90\u6df7\u5408\u56e0\u5b50\uff0c\u53c2\u65702\u65f6\u76ee\u6807\u6df7\u5408\u56e0\u5b50\u3002\u672c\u547d\u4ee4\u9009\u62e9\u4e86\u6700\u5e38\u4f7f\u7528\u7684\u53c2\u6570\u3002\n\n    //\u5b9a\u4e49\u6295\u5f71\u548c\u521d\u59cb\u6a21\u578b\u89c6\u56fe\u77e9\u9635\n    pangolin::OpenGlRenderState s_cam(\n        pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n        //\u5bf9\u5e94\u4e3agluLookAt,\u6444\u50cf\u673a\u4f4d\u7f6e,\u53c2\u8003\u70b9\u4f4d\u7f6e,up vector(\u4e0a\u5411\u91cf)\n        pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n    );\n    //\u7ba1\u7406OpenGl\u89c6\u53e3\u7684\u4f4d\u7f6e\u548c\u5927\u5c0f\n    pangolin::View &d_cam = pangolin::CreateDisplay()\n        //\u4f7f\u7528\u6df7\u5408\u5206\u6570/\u50cf\u7d20\u5750\u6807\uff08OpenGl\u89c6\u56fe\u5750\u6807\uff09\u8bbe\u7f6e\u89c6\u56fe\u7684\u8fb9\u754c\n        .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f)\n        //\u6307\u5b9a\u7528\u4e8e\u63a5\u53d7\u952e\u76d8\u6216\u9f20\u6807\u8f93\u5165\u7684\u5904\u7406\u7a0b\u5e8f\n        .SetHandler(new pangolin::Handler3D(s_cam));\n\n    while (pangolin::ShouldQuit() == false) {\n        //\u6e05\u9664\u5c4f\u5e55\n        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n        //\u6fc0\u6d3b\u8981\u6e32\u67d3\u5230\u89c6\u56fe\n        d_cam.Activate(s_cam);\n        //glClearColor\uff1ared\u3001green\u3001blue\u3001alpha\u5206\u522b\u662f\u7ea2\u3001\u7eff\u3001\u84dd\u3001\u4e0d\u900f\u660e\u5ea6\uff0c\u503c\u57df\u5747\u4e3a[0,1]\u3002\n        //\u5373\u8bbe\u7f6e\u989c\u8272\uff0c\u4e3a\u540e\u9762\u7684glClear\u505a\u51c6\u5907\uff0c\u9ed8\u8ba4\u503c\u4e3a\uff080,0,0,0\uff09\u3002\u5207\u8bb0\uff1a\u6b64\u51fd\u6570\u4ec5\u4ec5\u8bbe\u5b9a\u989c\u8272\uff0c\u5e76\u4e0d\u6267\u884c\u6e05\u9664\u5de5\u4f5c\u3002\n        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n        //glPointSize \u51fd\u6570\u6307\u5b9a\u6805\u683c\u5316\u70b9\u7684\u76f4\u5f84\u3002\u4e00\u5b9a\u8981\u5728\u8981\u5728glBegin\u524d,\u6216\u8005\u5728\u753b\u4e1c\u897f\u4e4b\u524d\u3002\n        glPointSize(2);\n        //glBegin()\u8981\u548cglEnd()\u7ec4\u5408\u4f7f\u7528\u3002\u5176\u53c2\u6570\u8868\u793a\u521b\u5efa\u56fe\u5143\u7684\u7c7b\u578b\uff0cGL_POINTS\u8868\u793a\u628a\u6bcf\u4e2a\u9876\u70b9\u4f5c\u4e3a\u4e00\u4e2a\u70b9\u8fdb\u884c\u5904\u7406\n        glBegin(GL_POINTS);\n        for (auto &p: pointcloud) {\n            glColor3f(p[3], p[3], p[3]);  //\u5728OpenGl\u4e2d\u8bbe\u7f6e\u989c\u8272\n            glVertex3d(p[0], p[1], p[2]); //\u8bbe\u7f6e\u9876\u70b9\u5750\u6807\n        }\n        glEnd();\n        pangolin::FinishFrame();    //\u7ed3\u675f\n        usleep(5000);   // sleep 5 ms\n    }\n    return;\n}\n\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;  // \u5b58\u653e\u50cf\u7d20\u70b9\u5750\u6807\u7684\u6570\u7ec4\n\n// Camera intrinsics\ndouble fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n// baseline   \u53cc\u76ee\u76f8\u673a\u57fa\u7ebf\ndouble baseline = 0.573;\n// paths\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\n// \u5b9a\u4e49\u6c42\u96c5\u514b\u6bd4\u7684\u7c7b\nclass JacobianAccumulator {\npublic:\n    // \u6784\u9020\u51fd\u6570\n    JacobianAccumulator(\n        const cv::Mat &img1_,             // \u56fe\u50cf 1\n        const cv::Mat &img2_,             // \u56fe\u50cf 2\n        const VecVector2d &px_ref_,       //  \u53c2\u8003\u70b9\u50cf\u7d20\u5750\u6807 \u6570\u7ec4\n        const vector<double> depth_ref_,  // \u53c2\u8003\u70b9\u6df1\u5ea6 \u6570\u7ec4\n        Sophus::SE3d &T21_) :   // \u5750\u6807\u7cfb1\u5230\u5750\u6807\u7cfb2\u7684\u53d8\u6362\u77e9\u9635\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;\n    Sophus::SE3d &T21;\n    VecVector2d projection; // projected points\n\n    std::mutex hessian_mutex;   // \u6807\u51c6\u4e92\u65a5\u7c7b\u578b\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  \u53cc\u7ebf\u6027\u63d2\u503c\n// \u53cc\u7ebf\u6027\u5185\u63d2\u6cd5\u5229\u7528\u5f85\u6c42\u50cf\u7d20\u56db\u4e2a\u76f8\u90bb\u50cf\u7d20\u7684\u7070\u5ea6\u5728\u4e24\u4e2a\u65b9\u5411\u4e0a\u505a\u7ebf\u6027\u5185\u63d2\uff0c\u5728\u5149\u6d41\u6cd5\u6c42\u53d6\u67d0\u50cf\u7d20\u4f4d\u7f6e\u7684\u7070\u5ea6\u503c\u65f6\u540c\u6837\u7528\u5230\u4e86\u4e8c\u7ef4\u7ebf\u6027\u63d2\u503c\u3002\ninline float GetPixelValue(const cv::Mat &img, float x, float y) {\n    // boundary check \u8fb9\u754c\u68c0\u6d4b\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)]; // data\u4e3a\u6307\u9488\uff0c\u6307\u5411\u5b9a\u4f4d\u7684\u50cf\u7d20\u4f4d\u7f6e\n    // step()\u51fd\u6570\uff0c\u8fd4\u56de\u50cf\u7d20\u884c\u7684\u5b9e\u9645\u5bbd\u5ea6\n    float xx = x - floor(x);   // floor()\u51fd\u6570\u8fd4\u56de\u4e0d\u5927\u4e8ex\u7684\u6700\u5927\u6574\u6570\n    float yy = y - floor(y);   // xx \u548c yy \u5c31\u662f\u5c0f\u6570\u90e8\u5206\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\n\n///////////  \u4e3b\u51fd\u6570\nint testEigen7()\n {\n\n    cv::Mat left_img = cv::imread(left_file, 0);  // \u8bfb\u53d6\u7070\u5ea6\u56fe\u50cf\n    cv::Mat disparity_img = cv::imread(disparity_file, 0);  // \u8bfb\u53d6\u89c6\u5dee\u56fe\u50cf\n\n    // 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;   // \u70b9\u7684\u6570\u91cf\n    int boarder = 20;     // \u8fb9\u754c\u7684\u50cf\u7d20\u6570 \uff0c\u5728\u8fd9\u91cc\u8868\u793a\u7559\u7a7a\u8fb9\u4e0a\u7684\u4e00\u90e8\u5206\u533a\u57df\uff0c\u4e0d\u5728\u8fb9\u4e0a\u53d6\u70b9\n    VecVector2d pixels_ref;\n    vector<double> depth_ref;\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        // rng.uniform()\u51fd\u6570\u8fd4\u56de\u533a\u95f4\u5185\u5747\u5300\u5206\u5e03\u7684\u968f\u673a\u6570\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);   // \u50cf\u7d20\u7684\u89c6\u5dee\n        double depth = fx * baseline / disparity; // \u53cc\u76ee\u89c6\u89c9\u4e2d\u7531\u89c6\u5dee\u5230\u6df1\u5ea6\u7684\u8ba1\u7b97\n        depth_ref.push_back(depth);\n        pixels_ref.push_back(Eigen::Vector2d(x, y));\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        std::string filestr = (fmt_others % i).str();\n        cout << filestr << endl;\n        cv::Mat img = cv::imread(filestr, cv::IMREAD_COLOR);\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\n\n///////  \u6c42\u89e3\u56fe\u50cf\u5757\u7684\u96c5\u514b\u6bd4\u77e9\u9635\u548c\u589e\u91cf\u65b9\u7a0b\nvoid JacobianAccumulator::accumulate_jacobian(const cv::Range &range) {\n    // \u6c42\u4e00\u4e2a\u56fe\u50cf\u5757\u5185\u7684\u96c5\u514b\u6bd4\u77e9\u9635\u7684\u7d2f\u79ef\uff0c\u4e3a\u4e86\u89e3\u51b3\u5355\u4e2a\u50cf\u7d20\u5728\u76f4\u63a5\u6cd5\u4e2d\u4e0d\u5177\u6709\u4ee3\u8868\u6027\u7684\u7f3a\u70b9\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        // \u8ba1\u7b97\u53c2\u8003\u70b9(\u7b2c\u4e00\u5e45\u56fe\u50cf)\u7684\u4e09\u7ef4\u5750\u6807\uff1a ((x_i - c_x )/ fx), (y_i - c_y)/ fy, 1) * depth\n\n        // \u8ba1\u7b97\u5f53\u524d\u76ee\u6807\u70b9(\u7b2c\u4e8c\u5e45\u56fe\u50cf)\u7684\u4e09\u7ef4\u5750\u6807\n        Eigen::Vector3d point_cur = T21 * point_ref;\n\n        if (point_cur[2] < 0)   // depth invalid\n            continue;\n        // \u8ba1\u7b97\u7b2ci\u4e2a\u53c2\u8003\u70b9\u5bf9\u5e94\u7684\u76ee\u6807\u70b9\u7684\u50cf\u7d20\u5750\u6807\n        float u = fx * point_cur[0] / point_cur[2] + cx;  // u = c_x + fx * (x / z)\n        float v = fy * point_cur[1] / point_cur[2] + cy;  // v = c_y + fy * (y / z)\n\n        // \u820d\u5f03\u8d8a\u754c\u7684\u50cf\u7d20\u70b9\u5750\u6807\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        // prijection \u5b58\u653e\u7684\u662f\u50cf\u7d20\u70b9\u5750\u6807\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\n        // \u8ba1\u6570\u5171\u6709\u591a\u5c11\u4e2a\u826f\u597d\u7684\u76ee\u6807\u70b9\n        cnt_good++;\n\n        // 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;   // \u50cf\u7d20\u5750\u6807\u5bf9\u76f8\u673a\u4f4d\u59ff\u674e\u4ee3\u6570\u7684\u4e00\u9636\u53d8\u5316\u5173\u7cfb : \\frac{\\partial u}{\\partial \\Delta epslon}\n                Eigen::Vector2d J_img_pixel;  // \u5bf9\u5e94\u4f4d\u7f6e\u7684\u50cf\u7d20\u68af\u5ea6 \uff1a \\frac{\\partial I}{\\partial u}\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();  // H \u77e9\u9635 \uff1a 2*2\n                bias += -error * J;            // b \u77e9\u9635 \uff1a - e * J (\u6709\u65f6\u4e5f\u5199\u4f5c b = - f * J )\n                cost_tmp += error * error;     // \u8bef\u5dee\u7684\u4e8c\u8303\u6570 (\u7d2f\u52a0\u540e\u662f\u6240\u6709\u597d\u7684\u5339\u914d\u70b9\u7684\u8bef\u5dee\u4e8c\u8303\u6570\u4e4b\u548c)\n            }\n    }\n\n    if (cnt_good) {  // \u5982\u679c\u597d\u7684\u76ee\u6807\u70b9\u4e0d\u4e3a0\uff0c\u4e5f\u5c31\u662fJ\u548cb\u90fd\u6709\u8ba1\u7b97\uff0c\u90a3\u4e48\u8fdb\u884c\u4ee5\u4e0b\u64cd\u4f5c\n        // \u8ba1\u7b97\u6700\u7ec8\u7684 H\u77e9\u9635\u3001b\u77e9\u9635\u548c\u8bef\u5dee\u4e8c\u8303\u6570\n\n        unique_lock<mutex> lck(hessian_mutex);\n        // unique_lock \u662f\u4e3a\u4e86\u907f\u514d mutex \u5fd8\u8bb0\u91ca\u653e\u9501\u3002\u5728\u5bf9\u8c61\u521b\u5efa\u65f6\u81ea\u52a8\u52a0\u9501\uff0c\u5bf9\u8c61\u91ca\u653e\u65f6\u81ea\u52a8\u89e3\u9501\u3002\n        // std::mutex\u7c7b\u662f\u4e00\u4e2a\u540c\u6b65\u539f\u8bed\uff0c\u53ef\u7528\u4e8e\u4fdd\u62a4\u5171\u4eab\u6570\u636e\u88ab\u540c\u65f6\u7531\u591a\u4e2a\u7ebf\u7a0b\u8bbf\u95ee\u3002std::mutex\u63d0\u4f9b\u72ec\u7279\u7684\uff0c\u975e\u9012\u5f52\u7684\u6240\u6709\u6743\u8bed\u4e49\u3002\n        // std::mutex\u662fC++11\u4e2d\u6700\u57fa\u672c\u7684\u4e92\u65a5\u91cf\uff0cstd::mutex\u5bf9\u8c61\u63d0\u4f9b\u4e86\u72ec\u5360\u6240\u6709\u6743\u7684\u7279\u6027\uff0c\u4e0d\u652f\u6301\u9012\u5f52\u5730\u5bf9std::mutex\u5bf9\u8c61\u4e0a\u9501\u3002\n\n        H += hessian;\n        b += bias;\n        cost += cost_tmp / cnt_good; // \u672c\u56fe\u50cf\u5757\u7684\u50cf\u7d20\u5e73\u5747\u8bef\u5dee\u4e8c\u8303\u6570\n    }\n}\n\n//////////////// \u5355\u5c42\u76f4\u63a5\u6cd5\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    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_\u662fopencv\u5c01\u88c5\u7684\u4e00\u4e2a\u591a\u7ebf\u7a0b\u63a5\u53e3\uff0c\u5229\u7528\u8fd9\u4e2a\u63a5\u53e3\u53ef\u4ee5\u65b9\u4fbf\u5b9e\u73b0\u591a\u7ebf\u7a0b\uff0c\u4e0d\u7528\u8003\u8651\u5e95\u5c42\u7ec6\u8282\n        // \u4e0b\u9762\u8fd9\u6761\u8bed\u53e5\u76f8\u5f53\u4e8e\u662f\u6b64\u6b21\u8fed\u4ee3\u4e2d\u7684jacobian\u90e8\u5206\u5e76\u884c\u8ba1\u7b97\u5b8c\u4e86\n        cv::parallel_for_(cv::Range(0, px_ref.size()),\n                          std::bind(&JacobianAccumulator::accumulate_jacobian, &jaco_accu, std::placeholders::_1));\n                          // bind()\u51fd\u6570\u8d77\u7ed1\u5b9a\u6548\u679c\uff0c\u5360\u4f4d\u7b26std::placeholders::_1\u8868\u793a\u7b2c\u4e00\u4e2a\u53c2\u6570\u5bf9\u5e94jaco.accu::accumulate_jacobian\u7684\u7b2c\u4e00\u4e2a\u53c2\u6570\n        Matrix6d H = jaco_accu.hessian();\n        Vector6d b = jaco_accu.bias();\n\n        // \u6c42\u89e3\u589e\u91cf\u65b9\u7a0b\n        Vector6d update = H.ldlt().solve(b);;\n        T21 = Sophus::SE3d::exp(update) * T21;   // \u66f4\u65b0\u4f4d\u59ff\n        cost = jaco_accu.cost_func();\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::imshow(\"222\", img2);\n    cv::waitKey(0);\n    cv::cvtColor(img2, img2_show, cv::COLOR_BGR2GRAY);\n    cout << \"!!!!!!!!!!! 1\" << endl;\n    VecVector2d projection = jaco_accu.projected_points();\n    cout << \"!!!!!!!!!!! 2\" << endl;\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\n\n///////////////// \u591a\u5c42\u76f4\u63a5\u6cd5\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    // \u8bbe\u7f6e\u56fe\u50cf\u91d1\u5b57\u5854\u53c2\u6570\n    int pyramids = 4;   // \u91d1\u5b57\u5854\u5171\u67094\u5c42\n    double pyramid_scale = 0.5;  // \u6bcf\u4e00\u5c42\u7f29\u653e\u6bd4\u7387\u662f0.5\n    double scales[] = {1.0, 0.5, 0.25, 0.125};\n    cout << \"......1\" << endl;\n    // \u521b\u5efa\u56fe\u50cf\u91d1\u5b57\u5854\n    vector<cv::Mat> pyr1, pyr2; // image pyramids\n    for (int i = 0; i < pyramids; i++) {\n        if (i == 0) {\n            // \u7b2c\u4e00\u5c42\uff0c\u5e95\u5c42\u662f\u539f\u56fe\u50cf\n            pyr1.push_back(img1);\n            pyr2.push_back(img2);\n        } else {\n            // \u4e0a\u9762\u7684\u5c42\u4f7f\u7528resize()\u51fd\u6570\u8fdb\u884c\u521b\u5efa\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            \n            pyr1.push_back(img1_pyr);\n            pyr2.push_back(img2_pyr);\n        }\n    }\n    double fxG = fx, fyG = fy, cxG = cx, cyG = cy;  // backup the old values\n    // \u7531\u7c97\u81f3\u7cbe\u8fdb\u884c\u6c42\u89e3\n    for (int level = pyramids - 1; level >= 0; level--) {\n        VecVector2d px_ref_pyr; // \u5b58\u653e\u8be5\u5c42\u7684\u76ee\u6807\u70b9\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        // \u4e0d\u540c\u7684\u5c42\u4e0a\u9762\u7531\u4e8e\u8fdb\u884c\u4e86\u7f29\u653e\uff0c\u76f8\u673a\u5185\u53c2\u4e5f\u76f8\u5e94\u7684\u8fdb\u884c\u4e86\u6539\u53d8\n        fx = fxG * scales[level];\n        fy = fyG * scales[level];\n        cx = cxG * scales[level];\n        cy = cyG * scales[level];\n        // \u8c03\u7528\u5355\u5c42\u76f4\u63a5\u6cd5\u8fdb\u884c\u6c42\u89e3\n        \n        DirectPoseEstimationSingleLayer(pyr1[level], pyr2[level], px_ref_pyr, depth_ref, T21);\n    }\n\n}\n\n\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing namespace Eigen;\n\n#include <pangolin/pangolin.h>\n\nstruct RotationMatrix {\n  Matrix3d matrix = Matrix3d::Identity();\n};\n\nostream &operator<<(ostream &out, const RotationMatrix &r) {\n  out.setf(ios::fixed);\n  Matrix3d matrix = r.matrix;\n  out << '=';\n  out << \"[\" << setprecision(2) << matrix(0, 0) << \",\" << matrix(0, 1) << \",\" << matrix(0, 2) << \"],\"\n      << \"[\" << matrix(1, 0) << \",\" << matrix(1, 1) << \",\" << matrix(1, 2) << \"],\"\n      << \"[\" << matrix(2, 0) << \",\" << matrix(2, 1) << \",\" << matrix(2, 2) << \"]\";\n  return out;\n}\n\nistream &operator>>(istream &in, RotationMatrix &r) {\n  return in;\n}\n\nstruct TranslationVector {\n  Vector3d trans = Vector3d(0, 0, 0);\n};\n\nostream &operator<<(ostream &out, const TranslationVector &t) {\n  out << \"=[\" << t.trans(0) << ',' << t.trans(1) << ',' << t.trans(2) << \"]\";\n  return out;\n}\n\nistream &operator>>(istream &in, TranslationVector &t) {\n  return in;\n}\n\nstruct QuaternionDraw {\n  Quaterniond q;\n};\n\nostream &operator<<(ostream &out, const QuaternionDraw quat) {\n  auto c = quat.q.coeffs();\n  out << \"=[\" << c[0] << \",\" << c[1] << \",\" << c[2] << \",\" << c[3] << \"]\";\n  return out;\n}\n\nistream &operator>>(istream &in, const QuaternionDraw quat) {\n  return in;\n}\n\nint testEigen() {\n  pangolin::CreateWindowAndBind(\"visualize geometry\", 1000, 600);\n  glEnable(GL_DEPTH_TEST);\n  pangolin::OpenGlRenderState s_cam(\n    pangolin::ProjectionMatrix(1000, 600, 420, 420, 500, 300, 0.1, 1000),\n    pangolin::ModelViewLookAt(3, 3, 3, 0, 0, 0, pangolin::AxisY)\n  );\n\n  const int UI_WIDTH = 500;\n\n  pangolin::View &d_cam = pangolin::CreateDisplay().\n    SetBounds(0.0, 1.0, pangolin::Attach::Pix(UI_WIDTH), 1.0, -1000.0f / 600.0f).\n    SetHandler(new pangolin::Handler3D(s_cam));\n\n  // ui\n  pangolin::Var<RotationMatrix> rotation_matrix(\"ui.R\", RotationMatrix());\n  pangolin::Var<TranslationVector> translation_vector(\"ui.t\", TranslationVector());\n  pangolin::Var<TranslationVector> euler_angles(\"ui.rpy\", TranslationVector());\n  pangolin::Var<QuaternionDraw> quaternion(\"ui.q\", QuaternionDraw());\n  pangolin::CreatePanel(\"ui\").SetBounds(0.0, 1.0, 0.0, pangolin::Attach::Pix(UI_WIDTH));\n\n  while (!pangolin::ShouldQuit()) {\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n    d_cam.Activate(s_cam);\n\n    pangolin::OpenGlMatrix matrix = s_cam.GetModelViewMatrix();\n    Matrix<double, 4, 4> m = matrix;\n\n    RotationMatrix R;\n    for (int i = 0; i < 3; i++)\n      for (int j = 0; j < 3; j++)\n        R.matrix(i, j) = m(j, i);\n    rotation_matrix = R;\n\n    TranslationVector t;\n    t.trans = Vector3d(m(0, 3), m(1, 3), m(2, 3));\n    t.trans = -R.matrix * t.trans;\n    translation_vector = t;\n\n    TranslationVector euler;\n    euler.trans = R.matrix.eulerAngles(2, 1, 0);\n    euler_angles = euler;\n\n    QuaternionDraw quat;\n    quat.q = Quaterniond(R.matrix);\n    quaternion = quat;\n\n    glColor3f(1.0, 1.0, 1.0);\n\n    pangolin::glDrawColouredCube();\n    // draw the original axis\n    glLineWidth(3);\n    glColor3f(0.8f, 0.f, 0.f);\n    glBegin(GL_LINES);\n    glVertex3f(0, 0, 0);\n    glVertex3f(10, 0, 0);\n    glColor3f(0.f, 0.8f, 0.f);\n    glVertex3f(0, 0, 0);\n    glVertex3f(0, 10, 0);\n    glColor3f(0.2f, 0.2f, 1.f);\n    glVertex3f(0, 0, 0);\n    glVertex3f(0, 0, 10);\n    glEnd();\n\n    pangolin::FinishFrame();\n  }\n}", "meta": {"hexsha": "2fe2d44727b80eeafd1adbe344debc0ebfa8e09b", "size": 30481, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Eigen/testEigen.cpp", "max_stars_repo_name": "chenzhengxi/example", "max_stars_repo_head_hexsha": "07a8436e92ccab8e330d2a77e2cca23b8a540df3", "max_stars_repo_licenses": ["MIT"], "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/testEigen.cpp", "max_issues_repo_name": "chenzhengxi/example", "max_issues_repo_head_hexsha": "07a8436e92ccab8e330d2a77e2cca23b8a540df3", "max_issues_repo_licenses": ["MIT"], "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/testEigen.cpp", "max_forks_repo_name": "chenzhengxi/example", "max_forks_repo_head_hexsha": "07a8436e92ccab8e330d2a77e2cca23b8a540df3", "max_forks_repo_licenses": ["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.6502923977, "max_line_length": 118, "alphanum_fraction": 0.5972573078, "num_tokens": 12245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5332302717888178}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2008, 2009 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 creditdefaultswap.cpp file from test-suite.\n\n#ifndef cl_adjoint_creditdefaultswap_impl_hpp\n#define cl_adjoint_creditdefaultswap_impl_hpp\n#pragma once\n\n#include <ql/quantlib.hpp>\n#include \"utilities.hpp\"\n#include \"adjointcreditdefaultswaptest.hpp\"\n#include \"adjointtestutilities.hpp\"\n#include \"adjointtestbase.hpp\"\n#include <boost/shared_ptr.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\n\n#define OUTPUT_FOLDER_NAME \"AdjointCreditDefaultSwap\"\n\nnamespace\n{\n    // Support structure for plotting\n    struct RealPair\n    {\n        static std::deque<std::string> get_columns()\n        {\n            static std::deque<std::string> columns = { \" \", \"\" };\n            return columns;\n        }\n\n        template <typename stream_type>\n        friend inline stream_type& operator << (stream_type& stm, RealPair& p)\n        {\n            stm << p.x << \";\" << p.y << std::endl;\n            return stm;\n        }\n\n        Real x, y;\n    };\n\n    struct SwapData\n    {\n        SwapData()\n        : calendar_()\n        , discountCurve_()\n        , curveDayCounter_()\n        , backup_()\n        , discountDates_()\n        , discountFactors_()\n        , defaultProbabilities_()\n        {\n            Settings::instance().evaluationDate() = Date(9, June, 2006);\n            evalDate_ = Settings::instance().evaluationDate();\n        }\n\n        void setDefaultProbabilitiesData()\n        {\n            calendar_ = UnitedStates();\n\n            discountDates_ = {\n                evalDate_,\n                calendar_.advance(evalDate_, 1, Weeks, ModifiedFollowing),\n                calendar_.advance(evalDate_, 1, Months, ModifiedFollowing),\n                calendar_.advance(evalDate_, 2, Months, ModifiedFollowing),\n                calendar_.advance(evalDate_, 3, Months, ModifiedFollowing),\n                calendar_.advance(evalDate_, 6, Months, ModifiedFollowing),\n                calendar_.advance(evalDate_, 1, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 2, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 3, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 4, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 5, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 6, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 7, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 8, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 9, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 10, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 15, Years, ModifiedFollowing)\n            };\n\n            discountFactors_ = {\n                1.0,\n                0.99901513757687310,\n                0.99570502636871183,\n                0.99118260474528685,\n                0.98661167950906203,\n                0.97325929533593880,\n                0.94724424481038083,\n                0.89844996737120875,\n                0.85216647839921411,\n                0.80775477692556874,\n                0.76517289234200347,\n                0.72401019553182933,\n                0.68503909569219212,\n                0.64797499814013748,\n                0.61263171936255534,\n                0.57919423507487910,\n                0.43518868769953606\n            };\n\n            // Build the discount curve\n            curveDayCounter_ = Actual360();\n            discountCurve_.linkTo(boost::make_shared<DiscountCurve>(discountDates_\n                                                                    , discountFactors_\n                                                                    , curveDayCounter_));\n\n        }\n\n        std::vector<Real> calculateDefaultProbabilitiesFunction(std::vector<Real> defaultProbabilities)\n        {\n            Size size = defaultProbabilities.size();\n\n            std::vector<Date> dates(size);\n            for (Size i = 0; i < size; i++)\n                dates[i] = evalDate_ + i * Weeks;\n\n            std::vector<Real> hazardRates;\n            DayCounter dayCounter = Thirty360();\n            hazardRates.push_back(0.0);\n\n            for (Size i = 1; i < size; ++i)\n            {\n                Time t1 = dayCounter.yearFraction(dates[0], dates[i - 1]);\n                Time t2 = dayCounter.yearFraction(dates[0], dates[i]);\n                Probability S1 = 1.0 - defaultProbabilities[i - 1];\n                Probability S2 = 1.0 - defaultProbabilities[i];\n                hazardRates.push_back(std::log(S1 / S2) / (t2 - t1));\n            }\n\n            // Build the hazard rates structure\n            RelinkableHandle<DefaultProbabilityTermStructure> piecewiseFlatHazardRate;\n            piecewiseFlatHazardRate.linkTo(\n                boost::make_shared<InterpolatedHazardRateCurve<BackwardFlat>>(dates, hazardRates, Thirty360()));\n\n            // Build the schedule\n            Date issueDate(20, March, 2006);\n            Date maturity = issueDate + size * Weeks;\n            Frequency cdsFrequency = Weekly;\n            BusinessDayConvention cdsConvention = ModifiedFollowing;\n            Schedule schedule(issueDate\n                              , maturity\n                              , Period(cdsFrequency)\n                              , calendar_\n                              , cdsConvention\n                              , cdsConvention\n                              , DateGeneration::Forward\n                              , false);\n\n            // Build the credit default swap\n            Real recoveryRate = 0.25;\n            Rate fixedRate = 0.0224;\n            DayCounter dayCount = Actual360();\n            Real cdsNotional = 100.0;\n            CreditDefaultSwap cds(Protection::Seller\n                                  , cdsNotional\n                                  , fixedRate\n                                  , schedule\n                                  , cdsConvention\n                                  , dayCount\n                                  , true\n                                  , true);\n\n            cds.setPricingEngine(\n                boost::make_shared<MidPointCdsEngine>(piecewiseFlatHazardRate, recoveryRate, discountCurve_));\n\n            // Compute NPV and fair spread of the credit default swap\n            return std::vector<Real>{cds.NPV(), cds.fairSpread() };\n        }\n\n        void setDiscountFactorData()\n        {\n            calendar_ = UnitedStates();\n\n            // Set dates for default probabilities\n            discountDates_ = {\n                evalDate_,\n                calendar_.advance(evalDate_, 6, Months, ModifiedFollowing),\n                calendar_.advance(evalDate_, 1, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 2, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 3, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 4, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 5, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 7, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 10, Years, ModifiedFollowing),\n                calendar_.advance(evalDate_, 12, Years, ModifiedFollowing)\n            };\n\n            defaultProbabilities_ = {\n                0.0000, 0.0047, 0.0093, 0.0286, 0.0619, 0.0953, 0.1508, 0.2288, 0.3666, 0.5 };\n\n            curveDayCounter_ = Actual360();\n        }\n\n        std::vector<Real> getDiscountFactors(std::vector<Real> dfs)\n        {\n            int size = dfs.size() + 1;\n            std::vector<Date> discountDates(size);\n            for (Size i = 0; i < size; i++)\n                discountDates[i] = evalDate_ + i * Weeks;\n\n            std::vector<DiscountFactor> discountFactors;\n            discountFactors.push_back(1.0);\n            discountFactors.insert(discountFactors.end(), dfs.begin(), dfs.end());\n            return discountFactors;\n        }\n\n        std::vector<Date> getDiscountDates(int size)\n        {\n            std::vector<Date> discountDates(size);\n            for (Size i = 0; i < size; i++)\n                discountDates[i] = evalDate_ + i * Weeks;\n            return discountDates;\n        }\n\n        RelinkableHandle<DefaultProbabilityTermStructure> getHazardRates(std::vector<Date> discountDates)\n        {\n            std::vector<Real> hazardRates;\n            hazardRates.push_back(0.0);\n            DayCounter dayCounter = Thirty360();\n            for (Size i = 1; i < discountDates_.size(); ++i)\n            {\n                Time t1 = dayCounter.yearFraction(discountDates_[0], discountDates_[i - 1]);\n                Time t2 = dayCounter.yearFraction(discountDates_[0], discountDates_[i]);\n                Probability S1 = 1.0 - defaultProbabilities_[i - 1];\n                Probability S2 = 1.0 - defaultProbabilities_[i];\n                hazardRates.push_back(std::log(S1 / S2) / (t2 - t1));\n            }\n\n            RelinkableHandle<DefaultProbabilityTermStructure> piecewiseFlatHazardRate;\n            piecewiseFlatHazardRate.linkTo(\n                boost::make_shared<InterpolatedHazardRateCurve<BackwardFlat>>(discountDates_, hazardRates, Thirty360()));\n            return piecewiseFlatHazardRate;\n        }\n\n        Schedule getSchedule(int size)\n        {\n            Date issueDate(20, March, 2006);\n            Date maturity = issueDate + size * Weeks;\n            Frequency cdsFrequency = Weekly;\n            BusinessDayConvention cdsConvention = ModifiedFollowing;\n            return Schedule(issueDate\n                              , maturity\n                              , Period(cdsFrequency)\n                              , calendar_\n                              , cdsConvention\n                              , cdsConvention\n                              , DateGeneration::Forward\n                              , false);\n        }\n\n        std::vector<Real> calculateDiscountFactorFunction(std::vector<Real> dfs)\n        {\n            Size size = dfs.size() + 1;\n\n            std::vector<Date> discountDates = getDiscountDates(size);\n\n            // Build the discount curve\n            discountCurve_.linkTo(boost::make_shared<DiscountCurve>(discountDates, \n                getDiscountFactors(dfs), curveDayCounter_));\n\n            // Set hazard rates\n            RelinkableHandle<DefaultProbabilityTermStructure> piecewiseFlatHazardRate = getHazardRates(discountDates);\n\n            // Build the credit default swap\n            Real recoveryRate = 0.25;\n            Rate fixedRate = 0.0224;\n            DayCounter dayCount = Actual360();\n            Real cdsNotional = 100.0;\n            CreditDefaultSwap cds(Protection::Seller\n                                  , cdsNotional\n                                  , fixedRate\n                                  , getSchedule(size)\n                                  , BusinessDayConvention::ModifiedFollowing\n                                  , dayCount\n                                  , true\n                                  , true);\n\n            cds.setPricingEngine(\n                boost::make_shared<MidPointCdsEngine>(piecewiseFlatHazardRate, recoveryRate, discountCurve_));\n\n            // Compute NPV and fair spread of the credit default swap\n            return std::vector<Real>{cds.NPV(), cds.fairSpread() };\n        }\n\n        std::vector<Real> calculateNotionalSpreadRateFunction(std::vector<Real> parameters)\n        {\n            Date today = Settings::instance().evaluationDate();\n            calendar_ = TARGET();\n\n            // Build the default probability curve\n            RelinkableHandle<DefaultProbabilityTermStructure> probabilityCurve;\n            Handle<Quote> hazardRate = Handle<Quote>(boost::make_shared<SimpleQuote>(0.01234));\n            probabilityCurve.linkTo(\n                boost::make_shared<FlatHazardRate>(0, calendar_, hazardRate, Actual360()));\n\n            // Build the discount curve\n            discountCurve_.linkTo(boost::make_shared<FlatForward>(today, 0.06, Actual360()));\n\n            // Build the schedule\n            Date issueDate = calendar_.advance(today, -1, Years);\n            Date maturity = calendar_.advance(issueDate, 10, Years);\n            Frequency frequency = Semiannual;\n            BusinessDayConvention convention = ModifiedFollowing;\n            Schedule schedule(issueDate\n                              , maturity\n                              , Period(frequency)\n                              , calendar_\n                              , convention\n                              , convention\n                              , DateGeneration::Forward\n                              , false);\n\n\n            // Build the credit default swap\n            Real notional = parameters[0];\n            Rate spread = parameters[1];\n            Real recoveryRate = parameters[2];\n            DayCounter dayCount = Actual360();\n            CreditDefaultSwap cds(Protection::Seller\n                                  , notional\n                                  , spread\n                                  , schedule\n                                  , convention\n                                  , dayCount\n                                  , true\n                                  , true);\n\n            // Compute NPV and fair spread of the credit default swap for the first pricing engine\n            auto midPointCdsEngine = boost::make_shared<MidPointCdsEngine>(probabilityCurve, recoveryRate, discountCurve_);\n            cds.setPricingEngine(midPointCdsEngine);\n            std::vector<Real> function(2);\n            function[0] = cds.NPV();\n\n            // Compute NPV and fair spread of the credit default swap for the second pricing engine\n            auto integralCdsEngine = boost::make_shared<IntegralCdsEngine>(1 * Days, probabilityCurve, recoveryRate, discountCurve_);\n            cds.setPricingEngine(integralCdsEngine);\n            function[1] = cds.NPV();\n            return function;\n        }\n\n        template <class Func>\n        void calculateFinDiff(std::vector<Real>& X\n                              , Real h\n                              , std::vector<Real>& sf_Finite\n                              , Func function)\n        {\n            Size sizeX = X.size();\n\n            std::vector<Real> totalfunction = function(X);\n\n            Size sizeY = totalfunction.size();\n\n            sf_Finite.resize(sizeX * sizeY);\n\n            for (Size i = 0; i < sizeX; i++)\n            {\n                X[i] += h;\n                std::vector<Real> finiteTotalfunction = function(X);\n                X[i] -= h;\n\n                for (Size j = 0; j < sizeY; j++)\n                {\n                    sf_Finite[sizeX*j + i] = (finiteTotalfunction[j] - totalfunction[j]) / h;\n                }\n            }\n        }\n\n        SavedSettings backup_;\n\n        Date evalDate_;\n        Calendar calendar_;\n\n        std::vector<Date> discountDates_;\n        std::vector<DiscountFactor> discountFactors_;\n        std::vector<Probability> defaultProbabilities_;\n\n        RelinkableHandle<YieldTermStructure> discountCurve_;\n        DayCounter curveDayCounter_;\n    };\n\n    struct DefaultProbabilitiesTestData\n        : public SwapData\n    {\n        struct Test\n        : public cl::AdjointTest<Test>\n        {\n            static const CalcMethod default_method = other;\n\n            Test(Size size, DefaultProbabilitiesTestData* data)\n            : size_(size)\n            , data_(data)\n            , probability_(size)\n            , doubleProbability_(size)\n            , iterNumFactor_(1000)\n            {\n                setLogger(&data_->outPerform_);\n\n                for (Size i = 0; i < size_; i++)\n                    doubleProbability_[i] = (double)(0.4 * i / size_);\n\n                std::copy(doubleProbability_.begin(), doubleProbability_.end(), probability_.begin());\n\n                data->setDefaultProbabilitiesData();\n            }\n\n            Size indepVarNumber() { return size_; }\n\n            Size depVarNumber() { return 2; }\n\n            Size minPerfIteration() { return iterNumFactor_; }\n\n            void recordTape()\n            {\n                cl::Independent(probability_);\n                calculateFunction();\n                f_ = std::make_unique<cl::tape_function<double>>(probability_, calculatedFunction_);\n            }\n\n            void calculateFunction()\n            {\n                calculatedFunction_ = data_->calculateDefaultProbabilitiesFunction(probability_);\n            }\n\n            // Calculates derivatives using adjoint.\n            void calcAdjoint()\n            {\n                adjointResults_ = f_->Jacobian(doubleProbability_);\n            }\n\n            // Calculates derivatives using finite difference method.\n            void calcAnalytical()\n            {\n                double h = 1.0e-6;  // shift for finite diff. method\n                analyticalResults_.resize(size_);\n                data_->calculateFinDiff(probability_\n                                        , h\n                                        , analyticalResults_\n                                        , [this] (std::vector<Real>& v) -> std::vector<Real>\n                {\n                    return data_->calculateDefaultProbabilitiesFunction(v);\n                });\n            }\n\n            double relativeTol() const { return 1e-4; }\n\n            double absTol() const { return 1e-5; }\n\n            Size size_;\n            Size iterNumFactor_;\n            DefaultProbabilitiesTestData* data_;\n            std::vector<cl::tape_double> probability_;\n            std::vector<double> doubleProbability_;\n            std::vector<cl::tape_double> calculatedFunction_;\n        };\n\n        DefaultProbabilitiesTestData()\n            : SwapData()\n\n            , outPerform_(OUTPUT_FOLDER_NAME \"//DefaultProbabilities\"\n            , { { \"filename\", \"AdjointPerformance\" }\n              , { \"not_clear\", \"Not\" }\n              , { \"cleanlog\", \"true\" }\n              , { \"title\", \"Credit default swap NPV and fair spread differentiation performance with respect to default probability\" }\n              , { \"xlabel\", \"Number of default probabilities\" }\n              , { \"ylabel\", \"Time (s)\" }\n              , { \"smooth\", \"12\" }\n              , { \"line_box_width\", \"-5\" }})\n\n            , outAdjoint_(OUTPUT_FOLDER_NAME \"//DefaultProbabilities\"\n            , { { \"filename\", \"Adjoint\" }\n              , { \"not_clear\", \"Not\" }\n              , { \"cleanlog\", \"false\" }\n              , { \"title\", \"Credit default swap NPV and fair spread adjoint differentiation performance with respect to default probability\" }\n              , { \"xlabel\", \"Number of default probabilities\" }\n              , { \"ylabel\", \"Time (s)\" }\n              , { \"smooth\", \"12\" }\n              })\n\n            , outSize_(OUTPUT_FOLDER_NAME \"//DefaultProbabilities\"\n            , { { \"filename\", \"TapeSize\" }\n              , { \"not_clear\", \"Not\" }\n              , { \"cleanlog\", \"false\" }\n              , { \"title\", \"Tape size dependence on number of default probabilities\" }\n              , { \"xlabel\", \"Number of default probabilities\" }\n              , { \"ylabel\", \"Size (MB)\" } })\n\n            , outNpv_(OUTPUT_FOLDER_NAME \"//DefaultProbabilities//output\"\n            , { { \"filename\", \"NPV on default probability\" }\n              , { \"not_clear\", \"Not\" }\n              , { \"title\", \"Credit default swap NPV dependence on default probability\" }\n              , { \"xlabel\", \"Default probability\" }\n              , { \"ylabel\", \"NPV\" } })\n\n            , outFairSpread_(OUTPUT_FOLDER_NAME \"//DefaultProbabilities//output\"\n            , { { \"filename\", \"Fair spread on default probability\" }\n              , { \"not_clear\", \"Not\" }\n              , { \"title\", \"Credit default swap fair spread dependence on default probability\" }\n              , { \"xlabel\", \"Default probability\" }\n              , { \"ylabel\", \"Fair spread\" }\n              })\n\n#if defined CL_GRAPH_GEN\n            , pointNo_(50)\n            , iterNo_(50)\n            , step_(12)\n#else\n            , pointNo_(1)\n            , iterNo_(1)\n            , step_(1)\n#endif\n        {\n        }\n\n        bool makeOutput()\n        {\n            bool ok = true;\n            if (pointNo_ > 0)\n            {\n                ok &= recordDependencePlot();\n            }\n            ok &= cl::recordPerformance(*this, iterNo_, step_);\n            return ok;\n        }\n\n        std::shared_ptr<Test> getTest(Size size)\n        {\n            return std::make_shared<Test>(size + 12, this);\n        }\n\n        // Makes plots for strike sensitivity dependence.\n        bool recordDependencePlot()\n        {\n            std::vector<RealPair> outNpv(pointNo_);\n            std::vector<RealPair> outFairSpread(pointNo_);\n            auto test = getTest(0);\n            Real dpDelta = (test->probability_[2] - test->probability_[0]) / (pointNo_ + 1);\n            test->probability_[1] = test->probability_[0];\n\n            for (Size i = 0; i < pointNo_; i++)\n            {\n                test->probability_[1] += dpDelta;\n                std::vector<Real> out = test->data_->calculateDefaultProbabilitiesFunction(test->probability_);\n                outNpv[i] = { test->probability_[1], out[0] };\n                outFairSpread[i] = { test->probability_[1], out[1] };\n            }\n            outNpv_ << outNpv;\n            outFairSpread_ << outFairSpread;\n            return true;\n        }\n\n        Size pointNo_;\n        Size iterNo_;\n        Size step_;\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 outNpv_;\n        cl::tape_empty_test_output outFairSpread_;\n    };\n    typedef DefaultProbabilitiesTestData::Test DefaultProbabilitiesTest;\n\n    struct DiscountFactorTestData\n        : public SwapData\n    {\n        struct Test\n        : public cl::AdjointTest<Test>\n        {\n            static const CalcMethod default_method = other;\n\n            Test(Size size, DiscountFactorTestData* data)\n                : size_(size)\n                , data_(data)\n                , discountFactor_(size)\n                , doubleDiscountFactor_(size)\n                , iterNumFactor_(1000)\n            {\n                setLogger(&data_->outPerform_);\n\n                double coef = -1.0 / size_;\n                for (Size i = 0; i < size_; i++)\n                    doubleDiscountFactor_[i] = (double)(std::exp(coef * (i + 1)));\n\n                std::copy(doubleDiscountFactor_.begin(), doubleDiscountFactor_.end(), discountFactor_.begin());\n\n                data->setDiscountFactorData();\n            }\n\n            Size indepVarNumber() { return size_; }\n\n            Size depVarNumber() { return 2; }\n\n            Size minPerfIteration() { return iterNumFactor_; }\n\n            void recordTape()\n            {\n                cl::Independent(discountFactor_);\n                calculateFunction();\n                f_ = std::make_unique<cl::tape_function<double>>(discountFactor_, calculatedFunction_);\n            }\n\n            void calculateFunction()\n            {\n                calculatedFunction_ = data_->calculateDiscountFactorFunction(discountFactor_);\n            }\n\n            // Calculates derivatives using adjoint.\n            void calcAdjoint()\n            {\n                adjointResults_ = f_->Jacobian(doubleDiscountFactor_);\n            }\n\n            // Calculates derivatives using finite difference method.\n            void calcAnalytical()\n            {\n                double h = 1.0e-6;  // shift for finite diff. method\n                analyticalResults_.resize(size_);\n                data_->calculateFinDiff(discountFactor_\n                                        , h\n                                        , analyticalResults_\n                                        , [this] (std::vector<Real>& v) -> std::vector<Real>\n                {\n                    return data_->calculateDiscountFactorFunction(v);\n                });\n            }\n\n            double relativeTol() const { return 1e-4; }\n\n            double absTol() const { return 1e-5; }\n\n            Size size_;\n            Size iterNumFactor_;\n            DiscountFactorTestData* data_;\n            std::vector<cl::tape_double> discountFactor_;\n            std::vector<double> doubleDiscountFactor_;\n            std::vector<cl::tape_double> calculatedFunction_;\n        };\n\n        DiscountFactorTestData()\n            : SwapData()\n\n            , outPerform_(OUTPUT_FOLDER_NAME \"//DiscountFactor\"\n            , { { \"filename\", \"AdjointPerformance\" }\n              , { \"not_clear\", \"Not\" }\n              , { \"cleanlog\", \"true\"}\n              , { \"title\", \"Credit default swap NPV and fair spread differentiation performance with respect to discount factors\" }\n              , { \"xlabel\", \"Number of discount factors\" }\n              , { \"ylabel\", \"Time (s)\" }\n              , { \"smooth\", \"12\" }\n              , { \"line_box_width\", \"-5\" } })\n\n            , outAdjoint_(OUTPUT_FOLDER_NAME \"//DiscountFactor\"\n            , { { \"filename\", \"Adjoint\" }\n              , { \"not_clear\", \"Not\" }\n              , { \"cleanlog\", \"false\" }\n              , { \"title\", \"Credit default swap NPV and fair spread adjoint differentiation performance with respect to discount factors\" }\n              , { \"xlabel\", \"Number of discount factors\" }\n              , { \"ylabel\", \"Time (s)\" }\n              , { \"smooth\", \"12\" } })\n\n            , outSize_(OUTPUT_FOLDER_NAME \"//DiscountFactor\"\n            , { { \"filename\", \"TapeSize\" }\n              , { \"not_clear\", \"Not\" }\n              , { \"cleanlog\", \"false\" }\n              , { \"title\", \"Tape size dependence on number of discount factors\" }\n              , { \"xlabel\", \"Number of discount factors\" }\n              , { \"ylabel\", \"Size (MB)\" } })\n\n            , outNpv_(OUTPUT_FOLDER_NAME \"//DiscountFactor//output\"\n            , { { \"filename\", \"NPV on discount factor\" }\n              , { \"not_clear\", \"Not\" }\n              , { \"cleanlog\", \"false\" }\n              , { \"title\", \"Credit default swap NPV dependence on discount factor\" }\n              , { \"xlabel\", \"Discount factor\" }\n              , { \"ylabel\", \"NPV\" } })\n\n           , outFairSpread_(OUTPUT_FOLDER_NAME \"//DiscountFactor//output\"\n           , { { \"filename\", \"Fair spread on discount factor\" }\n             , { \"not_clear\", \"Not\" }\n             , { \"cleanlog\", \"false\" }\n             , { \"title\", \"Credit default swap fair spread dependence on discount factor\" }\n             , { \"xlabel\", \"Discount factor\" }\n             , { \"ylabel\", \"Fair spread\" } })\n\n#if defined CL_GRAPH_GEN\n            , pointNo_(50)\n            , iterNo_(50)\n            , step_(12)\n#else\n            , pointNo_(1)\n            , iterNo_(1)\n            , step_(1)\n#endif\n        {\n        }\n\n        bool makeOutput()\n        {\n            bool ok = true;\n            if (pointNo_ > 0)\n            {\n                ok &= recordDependencePlot();\n            }\n            ok &= cl::recordPerformance(*this, iterNo_, step_);\n            return ok;\n        }\n\n        std::shared_ptr<Test> getTest(Size size)\n        {\n            return std::make_shared<Test>(size + 12, this);\n        }\n\n        // Makes plots for strike sensitivity dependence.\n        bool recordDependencePlot()\n        {\n            std::vector<RealPair> outNpv(pointNo_);\n            std::vector<RealPair> outFairSpread(pointNo_);\n            auto test = getTest(0);\n\n            Real dfsDelta = (test->discountFactor_[0] - test->discountFactor_[2]) / (pointNo_ + 1);\n            test->discountFactor_[1] = test->discountFactor_[2];\n            for (Size i = 0; i < pointNo_; i++)\n            {\n                test->discountFactor_[1] += dfsDelta;\n                std::vector<Real> out = test->data_->calculateDiscountFactorFunction(test->discountFactor_);\n                outNpv[i] = { test->discountFactor_[1], out[0] };\n                outFairSpread[i] = { test->discountFactor_[1], out[1] };\n            }\n            outNpv_ << outNpv;\n            outFairSpread_ << outFairSpread;\n            return true;\n        }\n\n        Size pointNo_;\n        Size iterNo_;\n        Size step_;\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 outNpv_;\n        cl::tape_empty_test_output outFairSpread_;\n    };\n    typedef DiscountFactorTestData::Test DiscountFactorTest;\n\n    struct NotionalSpreadRateTest\n        : public cl::AdjointTest<NotionalSpreadRateTest>\n    {\n        static const CalcMethod default_method = other;\n\n        NotionalSpreadRateTest()\n            : iterNumFactor_(1)\n            , parameters_(3)\n        {\n            doubleParameters_ = { 10000.0, 0.012, 0.4 };\n            std::copy(doubleParameters_.begin(), doubleParameters_.end(), parameters_.begin());\n        }\n\n        Size indepVarNumber() { return 3; }\n\n        Size depVarNumber() { return 3; }\n\n        Size minPerfIteration() { return iterNumFactor_; }\n\n        void recordTape()\n        {\n            cl::Independent(parameters_);\n            calculateFunction();\n            f_ = std::make_unique<cl::tape_function<double>>(parameters_, calculatedFunction_);\n        }\n\n        void calculateFunction()\n        {\n            calculatedFunction_ = swapData_.calculateNotionalSpreadRateFunction(parameters_);\n        }\n\n        // Calculates derivatives using adjoint.\n        void calcAdjoint()\n        {\n            adjointResults_ = f_->Jacobian(doubleParameters_);\n        }\n\n        // Calculates derivatives using finite difference method.\n        void calcAnalytical()\n        {\n            double h = 1e-4;\n            analyticalResults_.resize(indepVarNumber() * depVarNumber());\n            swapData_.calculateFinDiff(parameters_\n                                , h\n                                , analyticalResults_\n                                , [this] (std::vector<Real>& v) -> std::vector<Real>\n            {\n                return swapData_.calculateNotionalSpreadRateFunction(v);\n            });\n\n        }\n\n        double relativeTol() const { return 1e-4; }\n\n        double absTol() const { return 1e-5; }\n\n        Size size_;\n        Size iterNumFactor_;\n        std::vector<cl::tape_double> parameters_;\n        std::vector<double> doubleParameters_;\n        std::vector<cl::tape_double> calculatedFunction_;\n        SwapData swapData_;\n    };\n}\n\n#endif", "meta": {"hexsha": "f15fd7abf7d32bc0fad68da44676dc6a2f6bf9d7", "size": 31296, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointcreditdefaultswapimpl.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/adjointcreditdefaultswapimpl.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/adjointcreditdefaultswapimpl.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.7060240964, "max_line_length": 142, "alphanum_fraction": 0.5317292945, "num_tokens": 6560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5332302717888178}}
{"text": "// Copyright Louis Dionne 2013-2017\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/concept/group.hpp>\r\n#include <boost/hana/minus.hpp>\r\n#include <boost/hana/negate.hpp>\r\n#include <boost/hana/tuple.hpp>\r\n\r\n#include <laws/group.hpp>\r\nnamespace hana = boost::hana;\r\n\r\n\r\nint main() {\r\n    hana::test::TestGroup<int>{hana::make_tuple(0,1,2,3,4,5)};\r\n    hana::test::TestGroup<long>{hana::make_tuple(0l,1l,2l,3l,4l,5l)};\r\n\r\n    // minus\r\n    static_assert(hana::minus(6, 4) == 6 - 4, \"\");\r\n\r\n    // negate\r\n    static_assert(hana::negate(6) == -6, \"\");\r\n}\r\n", "meta": {"hexsha": "b48f1f53d8bb1a9e3b8637373655a1ee41891a20", "size": 708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/test/group.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/hana/test/group.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/hana/test/group.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": 28.32, "max_line_length": 82, "alphanum_fraction": 0.6553672316, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059316231899, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5332302586373899}}
{"text": "#include \"LogisticRegression.h\"\"\r\n#include \"matrix.h\"\r\n#include <iostream>\r\n#include <fstream>\r\n#include <cmath>\r\n#include <boost/algorithm/string.hpp>\r\nusing namespace std;\r\nvoid LogisticRegressionProblem::LoadFeature(const char* featureFile){\r\n\tint cur_row = 0;\r\n\tifstream ifs(featureFile);\r\n\tstring line;\r\n\twhile(getline(ifs, line)) {\r\n\r\n\t\tconst char* pos = line.c_str();\r\n\t\tint i = 0;\r\n\r\n\t\tdVector feature = dVector(num_feas);\r\n\r\n\t\tfor(; pos - 1 != NULL && pos[0] != '\\0' && pos[0] != '#';\r\n\t\t\t\tpos = strchr(pos, ',') + 1) {\r\n\t\t\tfloat value = atof(pos);\r\n\t\t\tfeature[i++] = value;\r\n\t\t}\r\n\r\n\t\tfeatures[cur_row] = feature;\r\n\r\n\t\tcur_row++;\r\n\t}\r\n}\r\n\r\nvoid LogisticRegressionProblem::LoadLabel(const char* labelFile) {\r\n\tint cur_row = 0;\r\n\tifstream ifs(labelFile);\r\n\tdouble temp = 0;\r\n\twhile(ifs >> temp) {\r\n\t\tlabels[cur_row++] = temp;\r\n\t}\r\n}\r\n\r\n\r\nvoid LogisticRegressionProblem::LoadInstance(const char* featureFile, const char* labelFile) {\r\n\tLoadFeature(featureFile);\r\n\tLoadLabel(labelFile);\r\n}\r\n\r\nvoid LogisticRegressionProblem::DumpFeature(const char* featureFile) {\r\n\tofstream ofs(featureFile);\r\n\tfor(size_t i = 0; i < num_ins; i++) {\r\n\t\tfor (size_t j = 0; j < num_feas; j++) {\r\n\t\t\tofs << features[i][j] << \",\";\r\n\t\t}\r\n\t\tofs << endl;\r\n\t}\r\n}\r\n\r\nvoid LogisticRegressionProblem::DumpLabel(const char* labelFile){\r\n\tofstream ofs(labelFile);//target 0 or 1\r\n\tfor(size_t i = 0; i < num_ins; i++) {\r\n\t\tofs << labels[i] << endl;\r\n\t}\r\n}\r\n\r\ndouble LogisticRegressionProblem::LearningGD(double alpha, double l2, double l1){\r\n\tint max_iters = 4000;\r\n\t//    memset(&weights, .0, sizeof(double)* num_feas);\r\n\tdVector prev_weights = weights;\r\n\tdVector predicts = dVector(num_ins);\r\n\tdouble prev_bias = .0;\r\n\tdouble last_mrse = 1e10;\r\n\r\n\tfor(int iter = 0; iter < max_iters; ++iter) {\r\n\t\tdouble mrse = 0;\r\n\t\tfor(int i = 0; i < num_ins; ++i) {\r\n\t\t\tpredicts[i] = Predict(features[i]);\r\n\t\t\tmrse += (labels[i] - predicts[i]) * (labels[i] - predicts[i]);\r\n\t\t}\r\n\t\tif (last_mrse - mrse < 0.0001){\r\n\t\t\treturn mrse;\r\n\t\t}\r\n\t\tlast_mrse = mrse;\r\n\t\tstd::swap(prev_weights, weights);\r\n\r\n\t\tbias = prev_bias;\r\n\t\t//update each weight\r\n\t\tfor(int k = 0; k < num_feas; ++k) {\r\n\t\t\tdouble gradient = 0.0;\r\n\t\t\tfor(int i = 0; i < num_ins; ++i) {\r\n\t\t\t\tgradient += (predicts[i] - labels[i]) * features[i][k];\r\n\t\t\t}\r\n\r\n\t\t\tif (prev_weights[k] > 0)\r\n\t\t\t\tweights[k] = prev_weights[k] - alpha * gradient/num_ins - l2;\r\n\t\t\telse if (prev_weights[k] < 0) {\r\n\t\t\t\tweights[k] = prev_weights[k] - alpha * gradient/num_ins + l2;\r\n\t\t\t} else {\r\n\t\t\t\tweights[k] = prev_weights[k] - alpha * gradient/num_ins;\r\n\t\t\t}\r\n\t\t}\r\n\t\t//update bias\r\n\t\tdouble g = 0.0;\r\n\t\tfor(int i = 0; i < num_ins; ++i) {\r\n\t\t\tg += (predicts[i] - labels[i]);\r\n\t\t}\r\n\t\tprev_bias = bias - alpha * g/num_ins - l2 * bias;\r\n\t}\r\n\r\n\tdouble sum = 0;\r\n\tfor(int i = 0; i < num_feas; ++i) {\r\n\t\tdouble minus = prev_weights[i] - weights[i];\r\n\t\tdouble r = minus * minus;\r\n\t\tsum += r;\r\n\t}\r\n\treturn sqrt(sum);\r\n}\r\n\r\ndouble LogisticRegressionProblem::LearningSGD(double alpha, double l2, double l1){\r\n\tint max_iters = 10000;\r\n\tdouble lambda = 0.1;\r\n\r\n\tfor(int iter = 0; iter < max_iters; ++iter) {\r\n\t\tint id = rand() % num_ins;\r\n\t\tdouble pred = Predict(features[id]);\r\n\t\tdouble lrate = alpha / (1.0 + alpha *lambda * iter);\r\n\t\tfor (int i = 0; i < num_feas; i++) {\r\n\t\t\tdouble gradient = (pred - labels[id]) * features[id][i];\r\n\t\t\tweights[i] -= (lrate * gradient + l2 * weights[i]); \r\n\t\t}\r\n\t\tbias -= (lrate * (pred - labels[id]) + l2 * bias);\r\n\t}\r\n\treturn Eval();\r\n}\r\n\r\ndouble LogisticRegressionProblem::Logloss(const double p, const double y) {\r\n\treturn -y * log(p) - (1-y) * log(1-p);\r\n}\r\n\r\ndouble LogisticRegressionProblem::Sigmoid(const double x) {\r\n\tif (x >= 10){\r\n\t\treturn 1.0 / (1.0 + exp(-10));\r\n\t}else if (x <= -10){\r\n\t\treturn 1.0 / (1.0 + exp(10));\r\n\t}\r\n\treturn 1.0 / (1.0 + exp(-x));\r\n}\r\n\r\ndouble LogisticRegressionProblem::Predict(const dVector& feature) {\r\n\tdouble x = inner_dot(feature, weights);\r\n\treturn Sigmoid(x) + bias;\r\n}\r\n\r\ndouble LogisticRegressionProblem::Eval() {\r\n\tdouble ls = .0;\r\n\tfor (int i = 0; i < num_ins; i++) {\r\n\t\tls += Logloss(Predict(features[i]), labels[i]);\t\r\n\t}\r\n\treturn ls;\r\n}\r\n\r\nvoid LogisticRegressionProblem::SaveModel(std::ostream& os) {\r\n\tos << \"b:\" << bias << \" \";\r\n\tfor(int i = 0; i < num_feas; ++i)\r\n\t\tos <<  i << \":\" << weights[i] << \" \" ;\r\n\tos << endl;\r\n}\r\n", "meta": {"hexsha": "1166a0f29869e14f848ae57e2d95e90e1074023e", "size": 4298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LogisticRegression.cpp", "max_stars_repo_name": "irwenqiang/luna", "max_stars_repo_head_hexsha": "d79421b6a0ad93792284fd36767a76cc56b1862b", "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": "LogisticRegression.cpp", "max_issues_repo_name": "irwenqiang/luna", "max_issues_repo_head_hexsha": "d79421b6a0ad93792284fd36767a76cc56b1862b", "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": "LogisticRegression.cpp", "max_forks_repo_name": "irwenqiang/luna", "max_forks_repo_head_hexsha": "d79421b6a0ad93792284fd36767a76cc56b1862b", "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.0484848485, "max_line_length": 95, "alphanum_fraction": 0.5986505351, "num_tokens": 1309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5332210102235525}}
{"text": "#include \"order_facets_around_edge.h\"\n#include <Eigen/Geometry>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n\n#include <stdexcept>\n\n// adj_faces contains signed index starting from +- 1.\ntemplate<\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedI >\nvoid igl::copyleft::cgal::order_facets_around_edge(\n    const Eigen::PlainObjectBase<DerivedV>& V,\n    const Eigen::PlainObjectBase<DerivedF>& F,\n    size_t s,\n    size_t d, \n    const std::vector<int>& adj_faces,\n    Eigen::PlainObjectBase<DerivedI>& order, bool debug)\n{\n  // Although we only need exact predicates in the algorithm,\n  // exact constructions are needed to avoid degeneracies due to\n  // casting to double.\n  typedef CGAL::Exact_predicates_exact_constructions_kernel K;\n  typedef K::Point_3 Point_3;\n  typedef K::Plane_3 Plane_3;\n\n  auto get_face_index = [&](int adj_f)->size_t\n  {\n    return abs(adj_f) - 1;\n  };\n\n  auto get_opposite_vertex = [&](size_t fid)->size_t\n  {\n    typedef typename DerivedF::Scalar Index;\n    if (F(fid, 0) != (Index)s && F(fid, 0) != (Index)d) return F(fid, 0);\n    if (F(fid, 1) != (Index)s && F(fid, 1) != (Index)d) return F(fid, 1);\n    if (F(fid, 2) != (Index)s && F(fid, 2) != (Index)d) return F(fid, 2);\n    assert(false);\n    return -1;\n  };\n\n  // Handle base cases\n  if (adj_faces.size() == 0) \n  {\n    order.resize(0, 1);\n    return;\n  } else if (adj_faces.size() == 1)\n  {\n    order.resize(1, 1);\n    order(0, 0) = 0;\n    return;\n  } else if (adj_faces.size() == 2)\n  {\n    const size_t o1 = get_opposite_vertex(get_face_index(adj_faces[0]));\n    const size_t o2 = get_opposite_vertex(get_face_index(adj_faces[1]));\n    const Point_3 ps(V(s, 0), V(s, 1), V(s, 2));\n    const Point_3 pd(V(d, 0), V(d, 1), V(d, 2));\n    const Point_3 p1(V(o1, 0), V(o1, 1), V(o1, 2));\n    const Point_3 p2(V(o2, 0), V(o2, 1), V(o2, 2));\n    order.resize(2, 1);\n    switch (CGAL::orientation(ps, pd, p1, p2))\n    {\n      case CGAL::POSITIVE:\n        order(0, 0) = 1;\n        order(1, 0) = 0;\n        break;\n      case CGAL::NEGATIVE:\n        order(0, 0) = 0;\n        order(1, 0) = 1;\n        break;\n      case CGAL::COPLANAR:\n        {\n          switch (CGAL::coplanar_orientation(ps, pd, p1, p2)) {\n            case CGAL::POSITIVE:\n              // Duplicated face, use index to break tie.\n              order(0, 0) = adj_faces[0] < adj_faces[1] ? 0:1;\n              order(1, 0) = adj_faces[0] < adj_faces[1] ? 1:0;\n              break;\n            case CGAL::NEGATIVE:\n              // Coplanar faces, one on each side of the edge.\n              // It is equally valid to order them (0, 1) or (1, 0).\n              // I cannot think of any reason to prefer one to the\n              // other.  So just use (0, 1) ordering by default.\n              order(0, 0) = 0;\n              order(1, 0) = 1;\n              break;\n            case CGAL::COLLINEAR:\n              std::cerr << \"Degenerated triangle detected.\" <<\n                std::endl;\n              assert(false);\n              break;\n            default:\n              assert(false);\n          }\n        }\n        break;\n      default:\n        assert(false);\n    }\n    return;\n  }\n\n  const size_t num_adj_faces = adj_faces.size();\n  const size_t o = get_opposite_vertex( get_face_index(adj_faces[0]));\n  const Point_3 p_s(V(s, 0), V(s, 1), V(s, 2));\n  const Point_3 p_d(V(d, 0), V(d, 1), V(d, 2));\n  const Point_3 p_o(V(o, 0), V(o, 1), V(o, 2));\n  const Plane_3 separator(p_s, p_d, p_o);\n  if (separator.is_degenerate()) {\n    throw std::runtime_error(\n        \"Cannot order facets around edge due to degenerated facets\");\n  }\n\n  std::vector<Point_3> opposite_vertices;\n  for (size_t i=0; i<num_adj_faces; i++)\n  {\n    const size_t o = get_opposite_vertex( get_face_index(adj_faces[i]));\n    opposite_vertices.emplace_back(\n        V(o, 0), V(o, 1), V(o, 2));\n  }\n\n  std::vector<int> positive_side;\n  std::vector<int> negative_side;\n  std::vector<int> tie_positive_oriented;\n  std::vector<int> tie_negative_oriented;\n\n  std::vector<size_t> positive_side_index;\n  std::vector<size_t> negative_side_index;\n  std::vector<size_t> tie_positive_oriented_index;\n  std::vector<size_t> tie_negative_oriented_index;\n\n  for (size_t i=0; i<num_adj_faces; i++)\n  {\n    const int f = adj_faces[i];\n    const Point_3& p_a = opposite_vertices[i];\n    auto orientation = separator.oriented_side(p_a);\n    switch (orientation) {\n      case CGAL::ON_POSITIVE_SIDE:\n        positive_side.push_back(f);\n        positive_side_index.push_back(i);\n        break;\n      case CGAL::ON_NEGATIVE_SIDE:\n        negative_side.push_back(f);\n        negative_side_index.push_back(i);\n        break;\n      case CGAL::ON_ORIENTED_BOUNDARY:\n        {\n          auto inplane_orientation = CGAL::coplanar_orientation(\n              p_s, p_d, p_o, p_a);\n          switch (inplane_orientation) {\n            case CGAL::POSITIVE:\n              tie_positive_oriented.push_back(f);\n              tie_positive_oriented_index.push_back(i);\n              break;\n            case CGAL::NEGATIVE:\n              tie_negative_oriented.push_back(f);\n              tie_negative_oriented_index.push_back(i);\n              break;\n            case CGAL::COLLINEAR:\n            default:\n              throw std::runtime_error(\n                  \"Degenerated facet detected.\");\n              break;\n          }\n        }\n        break;\n      default:\n        // Should not be here.\n        throw std::runtime_error(\"Unknown CGAL state detected.\");\n    }\n  }\n  if (debug) {\n    std::cout << \"tie positive: \" << std::endl;\n    for (auto& f : tie_positive_oriented) {\n      std::cout << get_face_index(f) << \" \";\n    }\n    std::cout << std::endl;\n    std::cout << \"positive side: \" << std::endl;\n    for (auto& f : positive_side) {\n      std::cout << get_face_index(f) << \" \";\n    }\n    std::cout << std::endl;\n    std::cout << \"tie negative: \" << std::endl;\n    for (auto& f : tie_negative_oriented) {\n      std::cout << get_face_index(f) << \" \";\n    }\n    std::cout << std::endl;\n    std::cout << \"negative side: \" << std::endl;\n    for (auto& f : negative_side) {\n      std::cout << get_face_index(f) << \" \";\n    }\n    std::cout << std::endl;\n  }\n\n  auto index_sort = [](std::vector<int>& data) -> std::vector<size_t>{\n    const size_t len = data.size();\n    std::vector<size_t> order(len);\n    for (size_t i=0; i<len; i++) { order[i] = i; }\n    auto comp = [&](size_t i, size_t j) { return data[i] < data[j]; };\n    std::sort(order.begin(), order.end(), comp);\n    return order;\n  };\n\n  DerivedI positive_order, negative_order;\n  order_facets_around_edge(V, F, s, d, positive_side, positive_order, debug);\n  order_facets_around_edge(V, F, s, d, negative_side, negative_order, debug);\n  std::vector<size_t> tie_positive_order = index_sort(tie_positive_oriented);\n  std::vector<size_t> tie_negative_order = index_sort(tie_negative_oriented);\n\n  // Copy results into order vector.\n  const size_t tie_positive_size = tie_positive_oriented.size();\n  const size_t tie_negative_size = tie_negative_oriented.size();\n  const size_t positive_size = positive_order.size();\n  const size_t negative_size = negative_order.size();\n\n  order.resize(\n      tie_positive_size + positive_size + tie_negative_size + negative_size,1);\n\n  size_t count=0;\n  for (size_t i=0; i<tie_positive_size; i++)\n  {\n    order(count+i, 0) = tie_positive_oriented_index[tie_positive_order[i]];\n  }\n  count += tie_positive_size;\n\n  for (size_t i=0; i<negative_size; i++) \n  {\n    order(count+i, 0) = negative_side_index[negative_order(i, 0)];\n  }\n  count += negative_size;\n\n  for (size_t i=0; i<tie_negative_size; i++)\n  {\n    order(count+i, 0) = tie_negative_oriented_index[tie_negative_order[i]];\n  }\n  count += tie_negative_size;\n\n  for (size_t i=0; i<positive_size; i++)\n  {\n    order(count+i, 0) = positive_side_index[positive_order(i, 0)];\n  }\n  count += positive_size;\n  assert(count == num_adj_faces);\n\n  // Find the correct start point.\n  size_t start_idx = 0;\n  for (size_t i=0; i<num_adj_faces; i++)\n  {\n    const Point_3& p_a = opposite_vertices[order(i, 0)];\n    const Point_3& p_b =\n      opposite_vertices[order((i+1)%num_adj_faces, 0)];\n    auto orientation = CGAL::orientation(p_s, p_d, p_a, p_b);\n    if (orientation == CGAL::POSITIVE)\n    {\n      // Angle between triangle (p_s, p_d, p_a) and (p_s, p_d, p_b) is\n      // more than 180 degrees.\n      start_idx = (i+1)%num_adj_faces;\n      break;\n    } else if (orientation == CGAL::COPLANAR &&\n        Plane_3(p_s, p_d, p_a).orthogonal_direction() !=\n        Plane_3(p_s, p_d, p_b).orthogonal_direction())\n    {\n      // All 4 points are coplanar, but p_a and p_b are on each side of\n      // the edge (p_s, p_d).  This means the angle between triangle\n      // (p_s, p_d, p_a) and (p_s, p_d, p_b) is exactly 180 degrees.\n      start_idx = (i+1)%num_adj_faces;\n      break;\n    }\n  }\n  DerivedI circular_order = order;\n  for (size_t i=0; i<num_adj_faces; i++)\n  {\n    order(i, 0) = circular_order((start_idx + i)%num_adj_faces, 0);\n  }\n}\n\ntemplate<\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedI>\nIGL_INLINE\nvoid igl::copyleft::cgal::order_facets_around_edge(\n  const Eigen::PlainObjectBase<DerivedV>& V,\n  const Eigen::PlainObjectBase<DerivedF>& F,\n  size_t s,\n  size_t d, \n  const std::vector<int>& adj_faces,\n  const Eigen::PlainObjectBase<DerivedV>& pivot_point,\n  Eigen::PlainObjectBase<DerivedI>& order)\n{\n  assert(V.cols() == 3);\n  assert(F.cols() == 3);\n  assert(pivot_point.cols() == 3);\n  auto signed_index_to_index = [&](int signed_idx)\n  {\n      return abs(signed_idx) -1;\n  };\n  auto get_opposite_vertex_index = [&](size_t fid) -> typename DerivedF::Scalar\n  {\n      typedef typename DerivedF::Scalar Index;\n      if (F(fid, 0) != (Index)s && F(fid, 0) != (Index)d) return F(fid, 0);\n      if (F(fid, 1) != (Index)s && F(fid, 1) != (Index)d) return F(fid, 1);\n      if (F(fid, 2) != (Index)s && F(fid, 2) != (Index)d) return F(fid, 2);\n      assert(false);\n      // avoid warning\n      return -1;\n  };\n\n  {\n    // Check if s, d and pivot are collinear.\n    typedef CGAL::Exact_predicates_exact_constructions_kernel K;\n    K::Point_3 ps(V(s,0), V(s,1), V(s,2));\n    K::Point_3 pd(V(d,0), V(d,1), V(d,2));\n    K::Point_3 pp(pivot_point(0,0), pivot_point(0,1), pivot_point(0,2));\n    if (CGAL::collinear(ps, pd, pp)) {\n        throw std::runtime_error(\n                \"Pivot point is collinear with the outer edge!\");\n    }\n  }\n\n  const size_t N = adj_faces.size();\n  const size_t num_faces = N + 1; // N adj faces + 1 pivot face\n\n  // Because face indices are used for tie breaking, the original face indices\n  // in the new faces array must be ascending.\n  auto comp = [&](int i, int j) \n  {\n    return signed_index_to_index(adj_faces[i]) <\n      signed_index_to_index(adj_faces[j]);\n  };\n  std::vector<size_t> adj_order(N);\n  for (size_t i=0; i<N; i++) adj_order[i] = i;\n  std::sort(adj_order.begin(), adj_order.end(), comp);\n\n  DerivedV vertices(num_faces + 2, 3);\n  for (size_t i=0; i<N; i++) \n  {\n    const size_t fid = signed_index_to_index(adj_faces[adj_order[i]]);\n    vertices.row(i) = V.row(get_opposite_vertex_index(fid));\n  }\n  vertices.row(N  ) = pivot_point;\n  vertices.row(N+1) = V.row(s);\n  vertices.row(N+2) = V.row(d);\n\n  DerivedF faces(num_faces, 3);\n  for (size_t i=0; i<N; i++)\n  {\n    if (adj_faces[adj_order[i]] < 0) \n    {\n      faces(i,0) = N+1; // s\n      faces(i,1) = N+2; // d\n      faces(i,2) = i  ;\n    } else \n    {\n      faces(i,0) = N+2; // d\n      faces(i,1) = N+1; // s\n      faces(i,2) = i  ;\n    }\n  }\n  // Last face is the pivot face.\n  faces(N, 0) = N+1;\n  faces(N, 1) = N+2;\n  faces(N, 2) = N;\n\n  std::vector<int> adj_faces_with_pivot(num_faces);\n  for (size_t i=0; i<num_faces; i++)\n  {\n    if ((size_t)faces(i,0) == N+1 && (size_t)faces(i,1) == N+2)\n    {\n        adj_faces_with_pivot[i] = int(i+1) * -1;\n    } else\n    {\n        adj_faces_with_pivot[i] = int(i+1);\n    }\n  }\n\n  DerivedI order_with_pivot;\n  order_facets_around_edge(\n    vertices, faces, N+1, N+2, adj_faces_with_pivot, order_with_pivot);\n\n  assert((size_t)order_with_pivot.size() == num_faces);\n  order.resize(N);\n  size_t pivot_index = num_faces + 1;\n  for (size_t i=0; i<num_faces; i++)\n  {\n    if ((size_t)order_with_pivot[i] == N)\n    {\n      pivot_index = i;\n      break;\n    }\n  }\n  assert(pivot_index < num_faces);\n\n  for (size_t i=0; i<N; i++)\n  {\n    order[i] = adj_order[order_with_pivot[(pivot_index+i+1)%num_faces]];\n  }\n}\n\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate void igl::copyleft::cgal::order_facets_around_edge<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, unsigned long, unsigned long, std::vector<int, std::allocator<int> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, bool);\ntemplate void igl::copyleft::cgal::order_facets_around_edge<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, unsigned long, unsigned long, std::vector<int, std::allocator<int> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, bool);\ntemplate void igl::copyleft::cgal::order_facets_around_edge<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, unsigned long, unsigned long, std::vector<int, std::allocator<int> > const&, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);\ntemplate void igl::copyleft::cgal::order_facets_around_edge<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, unsigned long, unsigned long, std::vector<int, std::allocator<int> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);\ntemplate void igl::copyleft::cgal::order_facets_around_edge<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, unsigned long, unsigned long, std::vector<int, std::allocator<int> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);\ntemplate void igl::copyleft::cgal::order_facets_around_edge<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, unsigned long, unsigned long, std::vector<int, std::allocator<int> > const&, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);\n#endif\n", "meta": {"hexsha": "a7c7f2994a2f9a3492805da9b184e3299ef48d58", "size": 15752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ThirdParty/Libigl/igl/copyleft/cgal/order_facets_around_edge.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": "ThirdParty/Libigl/igl/copyleft/cgal/order_facets_around_edge.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": "ThirdParty/Libigl/igl/copyleft/cgal/order_facets_around_edge.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": 38.4195121951, "max_line_length": 613, "alphanum_fraction": 0.6154773997, "num_tokens": 5095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5332210102235525}}
{"text": "#include \"mex.h\"\n#include <igl/matlab/parse_rhs.h>\n#include <igl/matlab/prepare_lhs.h>\n#include <igl/matlab/MexStream.h>\n#include <igl/matlab/mexErrMsgTxt.h>\n#include <Eigen/Core>\n\ntemplate <int _N>\nvoid psd_project_rows(Eigen::MatrixXd & H)\n{\n  const Eigen::Index m = H.rows();\n  const int N = _N==Eigen::Dynamic ? round(sqrt(H.cols())) : _N;\n  static_assert( _N == Eigen::Dynamic || _N == N,\"\");\n  for(Eigen::Index r = 0;r<m;r++)\n  {\n    typedef Eigen::Matrix<double,_N,_N> Matrix;\n    Matrix Hr(N,N);\n    for(int i=0;i<N;i++)\n    {\n      for(int j=i;j<N;j++)\n      {\n        Hr(i,j) = H(r,i+N*j);\n        Hr(j,i) = H(r,i+N*j);\n      }\n    }\n    Eigen::SelfAdjointEigenSolver<Matrix> es(Hr);\n    Hr = \n      (es.eigenvectors()*\n      es.eigenvalues().cwiseMax(0).asDiagonal() *\n      es.eigenvectors().transpose()).eval();\n    for(int i=0;i<N;i++)\n    {\n      for(int j=i;j<N;j++)\n      {\n        H(r,i+N*j) = Hr(i,j);\n        H(r,j+N*i) = Hr(i,j);\n      }\n    }\n\n  }\n}\n\n// https://stackoverflow.com/a/1549960/148668\nbool is_perfect_square(int n) {\n    if (n < 0)\n        return false;\n    int root(round(sqrt(n)));\n    return n == root * root;\n}\n\n\nvoid mexFunction(\n  int          nlhs,\n  mxArray      *plhs[],\n  int          nrhs,\n  const mxArray *prhs[]\n  )\n{\n  //mexPrintf(\"Compiled at %s on %s\\n\",__TIME__,__DATE__);\n  using namespace igl;\n  using namespace igl::matlab;\n  using namespace Eigen;\n  igl::matlab::MexStream mout;        \n  std::streambuf *outbuf = std::cout.rdbuf(&mout);\n\n  mexErrMsgTxt(nrhs>=1,\"nrhs should be == 1\");\n  Eigen::MatrixXd H;\n  parse_rhs_double(prhs+0,H);\n\n  mexErrMsgTxt(is_perfect_square(H.cols()),\"size(H,2) must be perfect square\");\n\n  const int N(round(sqrt(H.cols())));\n  switch(N)\n  {\n    case  2: psd_project_rows< 2>(H); break;\n    case  3: psd_project_rows< 3>(H); break;\n    case  4: psd_project_rows< 4>(H); break;\n    case  5: psd_project_rows< 5>(H); break;\n    case  6: psd_project_rows< 6>(H); break;\n    case  7: psd_project_rows< 7>(H); break;\n    case  8: psd_project_rows< 8>(H); break;\n    case  9: psd_project_rows< 9>(H); break;\n    case 10: psd_project_rows<10>(H); break;\n    case 11: psd_project_rows<11>(H); break;\n    case 12: psd_project_rows<12>(H); break;\n    default:\n      psd_project_rows<Eigen::Dynamic>(H);\n      break;\n  }\n\n\n  switch(nlhs)\n  {\n    case 1:\n      prepare_lhs_double(H,plhs+0);\n    default:break;\n  }\n  std::cout.rdbuf(outbuf);\n}\n\n", "meta": {"hexsha": "ec80f2bb84efd6ec34baebe0aa1a43dd3d4c8417", "size": 2418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gplottoolbox/mex/psd_project_rows.cpp", "max_stars_repo_name": "karlic-luka/Spectral-clustering", "max_stars_repo_head_hexsha": "711042281c9fbedea1f12be822c9f55b629cc854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gplottoolbox/mex/psd_project_rows.cpp", "max_issues_repo_name": "karlic-luka/Spectral-clustering", "max_issues_repo_head_hexsha": "711042281c9fbedea1f12be822c9f55b629cc854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gplottoolbox/mex/psd_project_rows.cpp", "max_forks_repo_name": "karlic-luka/Spectral-clustering", "max_forks_repo_head_hexsha": "711042281c9fbedea1f12be822c9f55b629cc854", "max_forks_repo_licenses": ["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.9405940594, "max_line_length": 79, "alphanum_fraction": 0.5889164599, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5332210051963844}}
{"text": "#define _USE_MATH_DEFINES\n\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\n#include <climits>\n#include <cfloat>\n#include <cmath>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"externals.h\"\n#include \"typedValue.h\"\n#include \"stack.h\"\n#include \"word.h\"\n#include \"context.h\"\n#include \"mathMacro.h\"\n\nconst BigInt kBigInt_FLT_MAX(FLT_MAX);\nconst BigInt kBigInt_Minus_FLT_MAX(-FLT_MAX);\nconst BigInt kBigInt_DBL_MAX(DBL_MAX);\nconst BigInt kBigInt_Minus_DBL_MAX(-DBL_MAX);\n\nstatic double deg2rad(double inTheta) { return inTheta/180.0*M_PI; }\nstatic BigFloat deg2rad(BigFloat inTheta) { return inTheta/180.0*M_PI; }\nstatic double rad2deg(double inTheta) { return inTheta/M_PI*180.0; }\nstatic BigFloat rad2deg(BigFloat inTheta) { return inTheta/M_PI*180.0; }\n\nvoid InitDict_Math() {\n\tInstall(new Word(\"true\",WORD_FUNC {\n\t\tinContext.DS.emplace_back(true);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"false\",WORD_FUNC {\n\t\tinContext.DS.emplace_back(false);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"+\",WORD_FUNC { TwoOp(+); }));\n\tInstall(new Word(\"-\",WORD_FUNC { TwoOp(-); }));\n\n\tInstall(new Word(\"*\",WORD_FUNC { TwoOp(*); }));\n\tInstall(new Word(\"/\",WORD_FUNC { TwoOp(/); }));\n\n\tInstall(new Word(\"%\",WORD_FUNC {\n\t\tStack& ds=inContext.DS;\n\t\tif(ds.size()<2) { return inContext.Error(E_DS_AT_LEAST_2); }\n\n\t\tTypedValue tos=Pop(ds);\n\t\tTypedValue& second=ds.back();\n\n\t\t// second %= tos;\n\t\tModAssign(second,tos);\n\t\tNEXT;\n   }));\n\n\tInstall(new Word(\"&\",WORD_FUNC { BitOp(&); }));\n\tInstall(new Word(\"|\",WORD_FUNC { BitOp(|); }));\n\tInstall(new Word(\"^\",WORD_FUNC { BitOp(^); }));\n\tInstall(new Word(\">>\",WORD_FUNC { BitShiftOp(>>); }));\n\tInstall(new Word(\"<<\",WORD_FUNC { BitShiftOp(<<); }));\n\n\t// bitwise NOT.\n\tInstall(new Word(\"~\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_AT_LEAST_2); }\n\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase kTypeInt: \t\ttos.intValue=~tos.intValue;\t\tbreak;\n\t\t\tcase kTypeLong:\t\ttos.longValue=~tos.longValue;\tbreak;\n\t\t\tcase kTypeBigInt:\t*tos.bigIntPtr=~*tos.bigIntPtr;\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error_InvalidType(E_TOS_INT_OR_LONG_OR_BIGINT,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">\",WORD_FUNC { CmpOp(>); }));\n\tInstall(new Word(\"<\",WORD_FUNC { CmpOp(<); }));\n\t\n\tInstall(new Word(\">=\",WORD_FUNC { CmpOp(>=); }));\n\tInstall(new Word(\"<=\",WORD_FUNC { CmpOp(<=); }));\n\n\tInstall(new Word(\"==\",WORD_FUNC { CmpOp(==); }));\n\tInstall(new Word(\"!=\",WORD_FUNC { CmpOp(!=); }));\n\n\tInstall(new Word(\"and\",WORD_FUNC { BoolOp(&&); }));\n\tInstall(new Word(\"or\",WORD_FUNC { BoolOp(||); }));\n\tInstall(new Word(\"xor\",WORD_FUNC { BoolOp(!=); }));\n\tInstall(new Word(\"not\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_AT_LEAST_2); }\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tif(tos.dataType!=kTypeBool) {\n\t\t\treturn inContext.Error_InvalidType(E_TOS_BOOL,tos);\n\t\t}\n\t\ttos.boolValue = tos.boolValue != true;\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"&&\",WORD_FUNC {\n\t\tif(inContext.DS.size()<2) { return inContext.Error(E_DS_AT_LEAST_2); }\n\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tif(tos.dataType!=kTypeBool && tos.dataType!=kTypeWord) {\n\t\t\treturn inContext.Error_InvalidType(E_TOS_BOOL_OR_WP,tos);\n\t\t}\n\n\t\tTypedValue second=Pop(inContext.DS);\n\t\tif(second.dataType!=kTypeBool && second.dataType!=kTypeWord) {\n\t\t\treturn inContext.Error_InvalidType(E_SECOND_BOOL_OR_WP,second);\n\t\t}\n\n\t\tif(tos.dataType==kTypeBool) {\n\t\t\tif(tos.boolValue==false) {\n\t\t\t\tinContext.DS.emplace_back(false);\n\t\t\t\tgoto next;\n\t\t\t}\n\t\t} else {\n\t\t\tif(inContext.Exec(tos)==false) { return false; }\n\t\t\ttos=Pop(inContext.DS);\n\t\t\tif(tos.dataType!=kTypeBool) {\n\t\t\t\treturn inContext.Error(E_WP_AT_TOS_SHOULD_PUSH_A_BOOL);\n\t\t\t}\n\t\t\tif(tos.boolValue==false) {\n\t\t\t\tinContext.DS.emplace_back(false);\n\t\t\t\tgoto next;\n\t\t\t}\n\t\t}\n\n\t\tif(second.dataType==kTypeBool) {\n\t\t\tif(second.boolValue==false) {\n\t\t\t\tinContext.DS.emplace_back(false);\n\t\t\t\tgoto next;\n\t\t\t}\n\t\t} else {\n\t\t\tif(inContext.Exec(second)==false) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tsecond=Pop(inContext.DS);\n\t\t\tif(second.dataType!=kTypeBool) {\n\t\t\t\treturn inContext.Error(E_WP_AT_SECOND_SHOULD_PUSH_A_BOOL);\n\t\t\t}\n\t\t\tif(second.boolValue==false) {\n\t\t\t\tinContext.DS.emplace_back(false);\n\t\t\t\tgoto next;\n\t\t\t}\n\t\t}\n\t\tinContext.DS.emplace_back(true);\nnext:\n\t\tNEXT;\n\t}));\n\tInstall(new Word(\"||\",WORD_FUNC {\n\t\tif(inContext.DS.size()<2) { return inContext.Error(E_DS_AT_LEAST_2); }\n\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tif(tos.dataType!=kTypeBool && tos.dataType!=kTypeWord) {\n\t\t\treturn inContext.Error_InvalidType(E_TOS_BOOL_OR_WP,tos);\n\t\t}\n\n\t\tTypedValue second=Pop(inContext.DS);\n\t\tif(second.dataType!=kTypeBool && second.dataType!=kTypeWord) {\n\t\t\treturn inContext.Error_InvalidType(E_SECOND_BOOL_OR_WP,tos);\n\t\t}\n\n\t\tif(tos.dataType==kTypeBool) {\n\t\t\tif(tos.boolValue==true) {\n\t\t\t\tinContext.DS.emplace_back(true);\n\t\t\t\tgoto next;\n\t\t\t}\n\t\t} else {\n\t\t\tif(inContext.Exec(tos)==false) { return false; }\n\t\t\ttos=Pop(inContext.DS);\n\t\t\tif(tos.dataType!=kTypeBool) {\n\t\t\t\treturn inContext.Error(E_WP_AT_TOS_SHOULD_PUSH_A_BOOL);\n\t\t\t}\n\t\t\tif(tos.boolValue==true) {\n\t\t\t\tinContext.DS.emplace_back(true);\n\t\t\t\tgoto next;\n\t\t\t}\n\t\t}\n\n\t\tif(second.dataType==kTypeBool) {\n\t\t\tif(second.boolValue==true) {\n\t\t\t\tinContext.DS.emplace_back(true);\n\t\t\t\tgoto next;\n\t\t\t}\n\t\t} else {\n\t\t\tif(inContext.Exec(second)==false) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tsecond=Pop(inContext.DS);\n\t\t\tif(second.dataType!=kTypeBool) {\n\t\t\t\treturn inContext.Error(E_WP_AT_SECOND_SHOULD_PUSH_A_BOOL);\n\t\t\t}\n\t\t\tif(second.boolValue==true) {\n\t\t\t\tinContext.DS.emplace_back(true);\n\t\t\t\tgoto next;\n\t\t\t}\n\t\t}\n\t\tinContext.DS.emplace_back(false);\nnext:\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"sqrt\",WORD_FUNC { OneArgFloatingFunc(sqrt); }));\n\tInstall(new Word(\"exp\", WORD_FUNC { OneParamFunc(exp);  }));\n\tInstall(new Word(\"log\", WORD_FUNC { OneParamFunc(log);  }));\n\tInstall(new Word(\"log10\", WORD_FUNC { OneParamFunc(log10);  }));\n\n\tInstall(new Word(\"sin\",WORD_FUNC { OneParamFunc(sin); }));\n\tInstall(new Word(\"cos\",WORD_FUNC { OneParamFunc(cos); }));\n\tInstall(new Word(\"tan\",WORD_FUNC { OneParamFunc(tan); }));\n\n\tInstall(new Word(\"asin\",WORD_FUNC { OneParamFunc(asin); }));\n\tInstall(new Word(\"acos\",WORD_FUNC { OneParamFunc(acos); }));\n\tInstall(new Word(\"atan\",WORD_FUNC { OneParamFunc(atan); }));\n\n\tInstall(new Word(\"floor\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tFloorOrCeil(floor,tos);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"ceil\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tFloorOrCeil(ceil,tos);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"deg-to-rad\",WORD_FUNC { OneParamFunc(deg2rad); }));\n\tInstall(new Word(\"rad-to-deg\",WORD_FUNC { OneParamFunc(rad2deg); }));\n\n\tInstall(new Word(\"pow\",WORD_FUNC { \n\t\tusing namespace boost::multiprecision;\n\n\t\tif(inContext.DS.size()<2) { return inContext.Error(E_DS_AT_LEAST_2); }\n\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tTypedValue& second=ReadTOS(inContext.DS);\n\t\tif(second.dataType==kTypeDouble) {\n\t\t\tswitch(tos.dataType) {\n\t\t\t\tcase kTypeInt: /* double x int -> double */\n\t\t\t\t\tsecond.doubleValue=pow(second.doubleValue,(double)tos.intValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeLong: /* double x long -> double */\n\t\t\t\t\tsecond.doubleValue=pow(second.doubleValue,(double)tos.longValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeFloat: /* double x float -> double */\n\t\t\t\t\tsecond.doubleValue=pow(second.doubleValue,(double)tos.floatValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeDouble: /* double x double -> dobule */\n\t\t\t\t\tsecond.doubleValue=pow(second.doubleValue,tos.doubleValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeBigInt: { /* double x bigInt -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(second.doubleValue),\n\t\t\t\t\t\t\t\t\t  BigFloat(*tos.bigIntPtr)); \n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeBigFloat: { /* double x bigFloat -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(second.doubleValue),*tos.bigFloatPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: goto onError;\n\t\t\t}\n\t\t} else if(second.dataType==kTypeBigInt) {\n\t\t\tswitch(tos.dataType) {\n\t\t\t\tcase kTypeInt:\t/* bigInt x int -> bigInt */\n\t\t\t\t\t*second.bigIntPtr=pow(*second.bigIntPtr,tos.intValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeLong:\t/* bigInt x long -> bigInt */\n\t\t\t\t\t*second.bigIntPtr=pow(*second.bigIntPtr,tos.longValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeFloat: {\t/* bigInt x float -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(*second.bigIntPtr),\n\t\t\t\t\t\t\t\t\t  BigFloat(tos.floatValue));\n\t\t\t\t\t\tdelete(second.bigIntPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeDouble: {\t/* bigInt x double -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(*second.bigIntPtr),\n\t\t\t\t\t\t\t\t\t  BigFloat(tos.doubleValue));\n\t\t\t\t\t\tdelete(second.bigIntPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeBigInt: /* bigInt x bigInt -> bigInt */\n\t\t\t\t\treturn inContext.Error_InvalidType(E_OUT_OF_SUPPORT_TOS_SECOND,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   tos,second);\n\t\t\t\tcase kTypeBigFloat: { /* bigInt x bigFloat -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(*second.bigIntPtr),*tos.bigFloatPtr);\n\t\t\t\t\t\tdelete(second.bigIntPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: goto onError;\n\t\t\t}\n\t\t} else if(second.dataType==kTypeBigFloat) {\n\t\t\tswitch(tos.dataType) {\n\t\t\t\tcase kTypeInt: /* bigFloat x int -> bigFloat */\n\t\t\t\t\t*second.bigFloatPtr=pow(*second.bigFloatPtr,\n\t\t\t\t\t\t\t\t\t\t\tBigFloat(tos.intValue));\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeLong: /* bigFloat x long -> bigFloat */\n\t\t\t\t\t*second.bigFloatPtr=pow(*second.bigFloatPtr,\n\t\t\t\t\t\t\t\t\t\t\t BigFloat(tos.longValue));\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeFloat: /* bigFloat x float -> bigFloat */\n\t\t\t\t\t*second.bigFloatPtr=pow(*second.bigFloatPtr,\n\t\t\t\t\t\t\t\t\t\t\tBigFloat(tos.floatValue));\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeDouble: /* bigFloat x double -> bigFloat */\n\t\t\t\t\t*second.bigFloatPtr=pow(*second.bigFloatPtr,\n\t\t\t\t\t\t\t\t\t\t\tBigFloat(tos.doubleValue));\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeBigInt: /* bigFloat x bigInt -> bigFloat */\n\t\t\t\t\t*second.bigFloatPtr=pow(*second.bigFloatPtr,\n\t\t\t\t\t\t\t\t\t\t\tBigFloat(*tos.bigIntPtr));\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeBigFloat: /* bigFloat x bigFloat -> bigFloat */\n\t\t\t\t\t*second.bigFloatPtr=pow(*second.bigFloatPtr,*tos.bigFloatPtr);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: goto onError;\n\t\t\t}\n\t\t} else if(second.dataType==kTypeInt) {\n\t\t\tswitch(tos.dataType) {\n\t\t\t\tcase kTypeInt:\t/* int x int -> int */\n\t\t\t\t\tsecond.intValue=(int)pow(second.intValue,tos.intValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeLong:\t/* int x long -> long */\n\t\t\t\t\tsecond.longValue=(long)pow((long)second.intValue,tos.longValue);\n\t\t\t\t\tsecond.dataType=kTypeLong;\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeFloat: /* int x float -> float */\n\t\t\t\t\tsecond.floatValue=(float)pow((float)second.intValue,\n\t\t\t\t\t\t\t\t\t\t\t\t tos.floatValue);\n\t\t\t\t\tsecond.dataType=kTypeFloat;\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeDouble: /* int x double -> double */\n\t\t\t\t\tsecond.doubleValue=(double)pow((double)second.intValue,\n\t\t\t\t\t\t\t\t\t\t\t\t   tos.doubleValue);\n\t\t\t\t\tsecond.dataType=kTypeDouble;\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeBigInt: /* int x bigInt -> OutOfSupport */\n\t\t\t\t\treturn inContext.Error_InvalidType(E_OUT_OF_SUPPORT_TOS_SECOND,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   tos,second);\n\t\t\t\tcase kTypeBigFloat: { /* int x bigFloat -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(second.intValue),*tos.bigFloatPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\t\t\t\t\n\t\t\t\tdefault: goto onError;\n\t\t\t}\n\t\t} else if(second.dataType==kTypeLong) {\n\t\t\tswitch(tos.dataType) {\n\t\t\t\tcase kTypeInt:\t/* long x int -> long */\n\t\t\t\t\tsecond.longValue=(long)pow(second.longValue,(long)tos.intValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeLong:\t/* long x long -> long */\n\t\t\t\t\tsecond.longValue=(long)pow(second.longValue,tos.longValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeFloat:\t/* long x float -> float */\n\t\t\t\t\tsecond.floatValue=(float)pow((float)second.longValue,\n\t\t\t\t\t\t\t\t\t\t\t\t tos.floatValue);\n\t\t\t\t\tsecond.dataType=kTypeFloat;\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeDouble:\t/* long x double -> double */\n\t\t\t\t\tsecond.doubleValue=(double)pow((double)second.longValue,\n\t\t\t\t\t\t\t\t\t\t\t\t   tos.doubleValue);\n\t\t\t\t\tsecond.dataType=kTypeDouble;\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeBigInt: /* long x bigInt -> OutOfSupport */\n\t\t\t\t\treturn inContext.Error_InvalidType(E_OUT_OF_SUPPORT_TOS_SECOND,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   tos,second);\n\t\t\t\tcase kTypeBigFloat: { /* long x bigFloat -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(second.longValue),*tos.bigFloatPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: goto onError;\n\t\t\t}\n\t\t} else if(second.dataType==kTypeFloat) {\n\t\t\tswitch(tos.dataType) {\n\t\t\t\tcase kTypeInt: /* float x int -> float */\n\t\t\t\t\tsecond.floatValue=(float)pow((double)second.floatValue,\n\t\t\t\t\t\t\t\t\t\t\t\t (double)tos.intValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeLong: /* float x long -> float*/\n\t\t\t\t\tsecond.floatValue=(float)pow((double)second.floatValue,\n\t\t\t\t\t\t\t\t\t\t\t\t (double)tos.longValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeFloat: /* float x float -> float */\n\t\t\t\t\tsecond.floatValue=(float)pow((double)second.floatValue,\n\t\t\t\t\t\t\t\t\t\t\t\t (double)tos.floatValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeDouble: /* float x double -> dobule */\n\t\t\t\t\tsecond.doubleValue=pow((double)second.floatValue,tos.doubleValue);\n\t\t\t\t\tsecond.dataType=kTypeDouble;\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeBigInt: { /* float x bigInt -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(second.floatValue),\n\t\t\t\t\t\t\t\t\t  BigFloat(*tos.bigIntPtr));\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase kTypeBigFloat: { /* float x bigFloat -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(second.floatValue),*tos.bigFloatPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: goto onError;\n\t\t\t}\n\t\t} else { \nonError: \n\t\t\treturn inContext.Error_InvalidType(E_INVALID_DATA_TYPE_TOS_SECOND,\n\t\t\t\t\t\t\t\t\t\t\t   tos,second);\n\t\t} \n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"0?\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase kTypeInt:\n\t\t\t\ttos.dataType=kTypeBool;\n\t\t\t\ttos.boolValue=tos.intValue==0;\n\t\t\t\tbreak;\n\t\t\tcase kTypeLong:\n\t\t\t\ttos.dataType=kTypeBool;\n\t\t\t\ttos.boolValue=tos.longValue==0;\n\t\t\t\tbreak;\n\t\t\tcase kTypeBigInt: {\n\t\t\t\t\tBigInt *biPtr=tos.bigIntPtr;\n\t\t\t\t\ttos.dataType=kTypeBool;\n\t\t\t\t\ttos.boolValue=*biPtr==0;\n\t\t\t\t\tdelete(biPtr);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase kTypeFloat:\n\t\t\t\ttos.dataType=kTypeBool;\n\t\t\t\ttos.boolValue=tos.floatValue==0;\n\t\t\t\tbreak;\n\t\t\tcase kTypeDouble:\n\t\t\t\ttos.dataType=kTypeBool;\n\t\t\t\ttos.boolValue=tos.doubleValue==0;\n\t\t\t\tbreak;\n\t\t\tcase kTypeBigFloat: {\n\t\t\t\t\tBigFloat *bfPtr=tos.bigFloatPtr;\n\t\t\t\t\ttos.dataType=kTypeBool;\n\t\t\t\t\ttos.boolValue=*bfPtr==0;\n\t\t\t\t\tdelete(bfPtr);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error_InvalidType(E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\t// equivalent to '1 +'.\n\tInstall(new Word(\"1+\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase kTypeInt:\t\ttos.intValue+=1;\t\tbreak;\n\t\t\tcase kTypeFloat:\ttos.floatValue+=1;\t\tbreak;\n\t\t\tcase kTypeDouble:\ttos.doubleValue+=1;\t\tbreak;\n\t\t\tcase kTypeBigInt:\t*tos.bigIntPtr+=1;\t\tbreak;\n\t\t\tcase kTypeBigFloat:\t*tos.bigFloatPtr+=1;\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error_InvalidType(E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\t// equivalent to '1 -'.\n\tInstall(new Word(\"1-\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase kTypeInt:\t\ttos.intValue-=1;\tbreak;\n\t\t\tcase kTypeFloat:\ttos.floatValue-=1;\tbreak;\n\t\t\tcase kTypeDouble:\ttos.doubleValue-=1;\tbreak;\n\t\t\tcase kTypeBigInt:\t*tos.bigIntPtr-=1;\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error_InvalidType(E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"2/\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase kTypeInt:\t\ttos.intValue/=2;\t\tbreak;\n\t\t\tcase kTypeFloat:\ttos.floatValue/=2.0f;\tbreak;\n\t\t\tcase kTypeDouble:\ttos.doubleValue/=2.0;\tbreak;\n\t\t\tcase kTypeBigInt:\t*tos.bigIntPtr/=2;\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error_InvalidType(E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"rand-max\",WORD_FUNC {\n\t\tinContext.DS.emplace_back(RAND_MAX);\n\t\tNEXT;\n\t}));\n\n\t// [0,RAND_MAX]\n\tInstall(new Word(\"rand\",WORD_FUNC {\n\t\tinContext.DS.emplace_back(rand());\n\t\tNEXT;\n\t}));\n\n\t// [0,1]\n\tInstall(new Word(\"random\",WORD_FUNC {\n\t\tinContext.DS.emplace_back((float)rand()/(float)RAND_MAX);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"randomize\",WORD_FUNC {\n\t\tsrand((unsigned int)time(NULL));\n\t\tNEXT;\n\t}));\n\n\t// \u6574\u6570 --- \u6570\u5024\n\t// n --- t \n\t// s.t. t is an integer and t in [0,n).\n\tInstall(new Word(\"rand-to\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tif(tos.dataType!=kTypeInt) {\n\t\t\treturn inContext.Error_InvalidType(E_TOS_INT,tos);\n\t\t}\n\n\t\tconst int n=tos.intValue;\n\t\tif(n<0 || RAND_MAX<n) { return inContext.Error(E_TOS_POSITIVE_INT,n); }\n\t\tint t=(int)(rand()/((float)RAND_MAX+1)*n);\n\t\tinContext.DS.emplace_back(t);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"pi\",WORD_FUNC {\n\t\tinContext.DS.emplace_back(M_PI);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">int\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tif(tos.dataType==kTypeFloat) {\n\t\t\tif(tos.floatValue<INT_MIN || INT_MAX<tos.floatValue) {\n\t\t\t\treturn inContext.Error(E_CAN_NOT_CONVERT_TO_INT_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.intValue=(int)tos.floatValue;\n\t\t} else if(tos.dataType==kTypeDouble) {\n\t\t\tif(tos.doubleValue<INT_MIN || INT_MAX<tos.doubleValue) {\n\t\t\t\treturn inContext.Error(E_CAN_NOT_CONVERT_TO_INT_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.intValue=(int)tos.doubleValue;\n\t\t} else if(tos.dataType==kTypeLong) {\n\t\t\tif(tos.longValue<(long)INT_MIN || (long)INT_MAX<tos.longValue) {\n\t\t\t\treturn inContext.Error(E_CAN_NOT_CONVERT_TO_INT_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.intValue=(int)tos.longValue;\n\t\t} else if(tos.dataType==kTypeBigInt) {\n\t\t\tif(*tos.bigIntPtr<INT_MIN || INT_MAX<*tos.bigIntPtr) {\n\t\t\t\treturn inContext.Error(E_CAN_NOT_CONVERT_TO_INT_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.intValue=static_cast<int>(*tos.bigIntPtr);\n\t\t} else if(tos.dataType==kTypeAddress) {\n\t\t\ttos.dataType=kTypeInt;\n\t\t} else if(tos.dataType!=kTypeInt) {\n\t\t\treturn inContext.Error_InvalidType(E_TOS_NUMBER,tos);\n\t\t}\n\t\ttos.dataType=kTypeInt;\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">long\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tif(tos.dataType==kTypeFloat) {\n\t\t\tif(tos.floatValue<LONG_MIN || LONG_MAX<tos.floatValue) {\n\t\t\t\treturn inContext.Error(E_CAN_NOT_CONVERT_TO_LONG_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.longValue=(long)tos.floatValue;\n\t\t} else if(tos.dataType==kTypeDouble) {\n\t\t\tif(tos.doubleValue<LONG_MIN || LONG_MAX<tos.doubleValue) {\n\t\t\t\treturn inContext.Error(E_CAN_NOT_CONVERT_TO_LONG_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.longValue=(long)tos.doubleValue;\n\t\t} else if(tos.dataType==kTypeInt) {\n\t\t\ttos.longValue=(long)tos.intValue;\n\t\t} else if(tos.dataType==kTypeBigInt) {\n\t\t\tif(*tos.bigIntPtr<LONG_MIN || LONG_MAX<*tos.bigIntPtr) {\n\t\t\t\treturn inContext.Error(E_CAN_NOT_CONVERT_TO_LONG_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.longValue=static_cast<long>(*tos.bigIntPtr);\n\t\t} else if(tos.dataType!=kTypeLong) {\n\t\t\treturn inContext.Error_InvalidType(E_TOS_NUMBER,tos);\n\t\t}\n\t\ttos.dataType=kTypeLong;\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">INT\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tBigInt bigInt;\n\t\tswitch(tos.dataType) {\n\t\t\tcase kTypeInt:\t  bigInt=tos.intValue;\t\tbreak;\n\t\t\tcase kTypeLong:\t  bigInt=tos.longValue;\t\tbreak;\n\t\t\tcase kTypeFloat:  bigInt=static_cast<BigInt>(tos.floatValue);\tbreak;\n\t\t\tcase kTypeDouble: bigInt=static_cast<BigInt>(tos.doubleValue);\tbreak;\n\t\t\tcase kTypeString: bigInt=BigInt(*tos.stringPtr); break;\n\t\t\tcase kTypeBigInt:\n\t\t\t\t// do nothing\n\t\t\t\tbreak;\n\t\t\tcase kTypeBigFloat: bigInt=static_cast<BigInt>(*tos.bigFloatPtr); break;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error_InvalidType(E_TOS_NUMBER_OR_STRING,tos);\n\t\t}\n\t\tif(tos.dataType!=kTypeBigInt) {\n\t\t\tinContext.DS.emplace_back(bigInt);\n\t\t} else {\n\t\t\tinContext.DS.emplace_back(*tos.bigIntPtr);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">float\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase kTypeInt:\n\t\t\t\ttos.floatValue=(float)tos.intValue;\n\t\t\t\ttos.dataType=kTypeFloat;\n\t\t\t\tbreak;\n\t\t\tcase kTypeLong:\n\t\t\t\ttos.floatValue=(float)tos.longValue;\n\t\t\t\ttos.dataType=kTypeFloat;\n\t\t\t\tbreak;\n\t\t\tcase kTypeBigInt: {\n\t\t\t\t\tif(*tos.bigIntPtr>kBigInt_FLT_MAX\n\t\t\t\t\t  || *tos.bigIntPtr<kBigInt_Minus_FLT_MAX) {\n\t\t\t\t\t\treturn inContext.Error(\n\t\t\t\t\t\t\t\tE_CAN_NOT_CONVERT_TO_FLOAT_DUE_TO_OVERFLOW);\n\t\t\t\t\t}\n\t\t\t\t\tfloat f=tos.ToFloat(inContext);\n\t\t\t\t\tdelete tos.bigIntPtr;\n\t\t\t\t\ttos.floatValue=f;\n\t\t\t\t\ttos.dataType=kTypeFloat;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase kTypeFloat:\n\t\t\t\t// do nothing\n\t\t\t\tbreak;\n\t\t\tcase kTypeDouble:\n\t\t\t\tif(tos.doubleValue>FLT_MAX || tos.doubleValue<-FLT_MAX) {\n\t\t\t\t\treturn inContext.Error(E_CAN_NOT_CONVERT_TO_FLOAT_DUE_TO_OVERFLOW);\n\t\t\t\t}\n\t\t\t\ttos.floatValue=(float)tos.doubleValue;\n\t\t\t\ttos.dataType=kTypeFloat;\n\t\t\t\tbreak;\n\t\t\tcase kTypeBigFloat: {\n\t\t\t\t\tif(*tos.bigFloatPtr>FLT_MAX || *tos.bigFloatPtr<-FLT_MAX) {\n\t\t\t\t\t\treturn inContext.Error(\n\t\t\t\t\t\t\t\tE_CAN_NOT_CONVERT_TO_FLOAT_DUE_TO_OVERFLOW);\n\t\t\t\t\t}\n\t\t\t\t\tfloat f=tos.ToFloat(inContext);\n\t\t\t\t\tdelete tos.bigFloatPtr;\n\t\t\t\t\ttos.floatValue=f;\n\t\t\t\t\ttos.dataType=kTypeFloat;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error_InvalidType(E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">double\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase kTypeInt:\n\t\t\t\ttos.doubleValue=(double)tos.intValue;\n\t\t\t\ttos.dataType=kTypeDouble;\n\t\t\t\tbreak;\n\t\t\tcase kTypeLong:\n\t\t\t\ttos.doubleValue=(double)tos.longValue;\n\t\t\t\ttos.dataType=kTypeDouble;\n\t\t\t\tbreak;\n\t\t\tcase kTypeBigInt: {\n\t\t\t\t\tif(*tos.bigIntPtr>kBigInt_DBL_MAX\n\t\t\t\t\t  || *tos.bigIntPtr<kBigInt_Minus_DBL_MAX) {\n\t\t\t\t\t\treturn inContext.Error(\n\t\t\t\t\t\t\t\tE_CAN_NOT_CONVERT_TO_DOUBLE_DUE_TO_OVERFLOW);\n\t\t\t\t\t}\n\t\t\t\t\tdouble t=tos.ToDouble(inContext);\n\t\t\t\t\tdelete tos.bigIntPtr;\n\t\t\t\t\ttos.doubleValue=t;\n\t\t\t\t\ttos.dataType=kTypeDouble;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase kTypeFloat:\n\t\t\t\ttos.doubleValue=(double)tos.floatValue;\n\t\t\t\ttos.dataType=kTypeDouble;\n\t\t\t\tbreak;\n\t\t\tcase kTypeDouble:\n\t\t\t\t// do nothing\n\t\t\t\tbreak;\n\t\t\tcase kTypeBigFloat: {\n\t\t\t\t\tif(*tos.bigFloatPtr>DBL_MAX || *tos.bigFloatPtr<-DBL_MAX) {\n\t\t\t\t\t\treturn inContext.Error(\n\t\t\t\t\t\t\t\tE_CAN_NOT_CONVERT_TO_DOUBLE_DUE_TO_OVERFLOW);\n\t\t\t\t\t}\n\t\t\t\t\tdouble t=tos.ToDouble(inContext);\n\t\t\t\t\tdelete tos.bigFloatPtr;\n\t\t\t\t\ttos.doubleValue=t;\n\t\t\t\t\ttos.dataType=kTypeDouble;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error_InvalidType(E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">FLOAT\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tBigFloat bigFloat;\n\t\tswitch(tos.dataType) {\n\t\t\tcase kTypeInt:\t  bigFloat=tos.intValue;\tbreak;\n\t\t\tcase kTypeLong:\t  bigFloat=tos.longValue;\tbreak;\n\t\t\tcase kTypeFloat:  bigFloat=tos.floatValue;\tbreak;\n\t\t\tcase kTypeDouble: bigFloat=tos.doubleValue;\tbreak;\n\t\t\tcase kTypeString: bigFloat=BigFloat(*tos.stringPtr); break;\n\t\t\tcase kTypeBigInt: bigFloat=static_cast<BigFloat>(*tos.bigIntPtr); break;\n\t\t\tcase kTypeBigFloat: /* do nothing */ \t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error_InvalidType(E_TOS_NUMBER_OR_STRING,tos);\n\t\t}\n\t\tif(tos.dataType!=kTypeBigFloat) {\n\t\t\tinContext.DS.emplace_back(bigFloat);\n\t\t} else {\n\t\t\tinContext.DS.emplace_back(*tos.bigFloatPtr);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">address\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tif(tos.dataType!=kTypeInt && tos.dataType!=kTypeAddress) {\n\t\t\treturn inContext.Error_InvalidType(E_TOS_INT,tos);\n\t\t}\n\t\ttos.dataType=kTypeAddress;\n\t\tNEXT;\n\t}));\n}\n\n", "meta": {"hexsha": "e5f8ba680e495b45e910fe7436e53014f3aeeccf", "size": 24577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dict/dictMath.cpp", "max_stars_repo_name": "objectx/Paraphrase", "max_stars_repo_head_hexsha": "02c44405efc8604428ed362893ace50104298021", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dict/dictMath.cpp", "max_issues_repo_name": "objectx/Paraphrase", "max_issues_repo_head_hexsha": "02c44405efc8604428ed362893ace50104298021", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dict/dictMath.cpp", "max_forks_repo_name": "objectx/Paraphrase", "max_forks_repo_head_hexsha": "02c44405efc8604428ed362893ace50104298021", "max_forks_repo_licenses": ["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.8756281407, "max_line_length": 75, "alphanum_fraction": 0.6764047687, "num_tokens": 7268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5332209943436562}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2015-2015 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n#include <iostream>\n\n#include \"dune/common/fvector.hh\"\n\n#include \"linalg/numaMatrix.hh\"\n\nusing namespace Kaskade;\n\n#ifdef UNITTEST \n#include <boost/timer/timer.hpp>\n \nint main(void)\n{ \n  using namespace std;\n  \n  std::cout << \"8x8 matrix a_ij = i+j\\n\";\n  NumaDenseMatrix<Dune::FieldVector<double,1>> mat(8,8);\n  for (auto ri=mat.begin(); ri!=mat.end(); ++ri)\n    for (auto ci=ri->begin(); ci!=ri->end(); ++ci)\n      *ci = ri.index()+ci.index();\n    \n  std::cout << mat << \"\\nFrobenius norm: \" << mat.frobenius_norm() << \"\\n\";\n  \n  std::cout << \"Timing test of 100 additions of two 60000x100 matrices\\n\";\n  NumaDenseMatrix<Dune::FieldMatrix<double,1,1>> m2(60000,100);\n  for (auto ri=m2.begin(); ri!=m2.end(); ++ri)\n    for (auto ci=ri->begin(); ci!=ri->end(); ++ci)\n      *ci = ri.index()+ci.index();\n  boost::timer::cpu_timer timer;\n  for (int i=0; i<100; ++i)\n  {\n    m2 += m2; // these two are a no-op\n    m2 /= 2;\n  }\n  std::cout << timer.format() << \"\\n\";\n  // subtract original data - should be zero.\n  for (auto ri=m2.begin(); ri!=m2.end(); ++ri) \n    for (auto ci=ri->begin(); ci!=ri->end(); ++ci)\n      *ci -= ri.index()+ci.index();\n  std::cout << \"Frobenius norm (should be 0): \" << m2.frobenius_norm() << \"\\n\";\n  \n  \n  NumaVector<double> vec(12);\n  for (auto i=begin(vec); i!=end(vec); ++i)\n    *i = i.index();\n  std::cout << \"vec 12: \" << vec << \"\\ndot product (should be 506): \" << vec.dot(vec) << \"\\n2-norm (should be 22.4944): \" << vec.two_norm() << \"\\n\";\n  \n  vec.axpy(1.0,vec);\n  std::cout << \"twice vec: \" << vec << \"\\n\";\n  \n  return 0;\n}\n\n#endif\n", "meta": {"hexsha": "7e97b83e9755a4648bb5ff64a444f9cebb0dc3c3", "size": 2445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/linalg/numaMatrix.cpp", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/linalg/numaMatrix.cpp", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/linalg/numaMatrix.cpp", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 37.0454545455, "max_line_length": 148, "alphanum_fraction": 0.4466257669, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5331913128902391}}
{"text": "#include <gtest/gtest.h>\n#include <ros/package.h>\n\n#include \"mwoibn/eigen_utils/eigen_utils.h\"\n#include <Eigen/Core>\n\n#include <iostream>\n#include <fstream>\n\nbool skipLine(std::ifstream* myfile, int skip)\n{\n  std::string line;\n  try\n  {\n    for (int i = 0; i < skip; i++)\n      getline(*myfile, line);\n  }\n  catch (const std::exception& exc)\n  {\n    ADD_FAILURE() << exc.what(); // add proper throws\n  }\n  return true;\n}\n\nEigen::MatrixXd readMatrix(std::ifstream* myfile, int rows, int cols)\n{\n\n  std::string line;\n\n  std::vector<double> data;\n  std::vector<double> new_data;\n  for (int i = 0; i < rows; i++)\n  {\n    getline(*myfile, line);\n    std::istringstream is(line);\n    new_data = std::vector<double>(std::istream_iterator<double>(is),\n                                   std::istream_iterator<double>());\n    data.insert(data.end(), new_data.begin(), new_data.end());\n  }\n\n  Eigen::Map<\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>\n      J(&data[0], rows,\n        cols); // requires c++11, \"cannot-appear-in-a-constant-expression\"\n\n  return J;\n}\n\n::testing::AssertionResult compareMatrices(Eigen::MatrixXd m1,\n                                           Eigen::MatrixXd m2, double eps)\n{\n\n  if (!m1.rows() == m2.rows())\n    return ::testing::AssertionFailure()\n           << \" matrices has diffrenet row numbers\"\n           << \"m1: \" << m1.rows() << \", m2: \" << m2.rows();\n  if (!m1.cols() == m2.cols())\n    return ::testing::AssertionFailure()\n           << \" matrices has diffrenet columns numbers\"\n           << \"m1: \" << m1.cols() << \", m2: \" << m2.cols();\n\n  for (int i = 0; i < m1.rows(); i++)\n  {\n    for (int j = 0; j < m1.cols(); j++)\n    {\n      if (fabs(m1(i, j) - m2(i, j)) > eps)\n        return ::testing::AssertionFailure() << \"row \" << i << \", columns \" << j\n                                             << \", value a \" << m1(i, j)\n                                             << \", value b \" << m2(i, j);\n    }\n  }\n\n  return ::testing::AssertionSuccess();\n}\n\n// Check if class initialization works correctly\n\n// Check all class methods, orientation is not fully supported therefore it is\n// not checked during tests\nTEST(EigenUtilsTest, methods)\n{\n\n  // READ FILE\n  std::string path = ros::package::getPath(\"eigen_utils\");\n  std::string file_name = path + \"/test/resources/eigen_test.txt\";\n  std::ifstream myfile(file_name);\n  if (!myfile.is_open())\n    FAIL() << \"couldn't open the file, abort\";\n\n  // Prepare variables\n  float eps = 0.0001;\n  Eigen::MatrixXd J_test;\n  Eigen::MatrixXd J;\n\n  // READ TEST MATRICES\n  Eigen::MatrixXd m_square;\n  Eigen::MatrixXd m_nonsquare;\n\n  try\n  {\n    // read square matrix\n    if (!skipLine(&myfile, 1))\n      FAIL() << \"couldn't continue, file finished prematurely\";\n    m_square = readMatrix(&myfile, 3, 3);\n\n    // read non-sqaure\n    if (!skipLine(&myfile, 1))\n      FAIL() << \"couldn't continue, file finished prematurely\";\n    m_nonsquare = readMatrix(&myfile, 5, 9);\n  }\n  catch (const std::exception& exc)\n  {\n    ADD_FAILURE() << exc.what();\n  }\n  catch (...)\n  {\n    ADD_FAILURE()\n        << \"Unknown exception, while getting PointHandling information\";\n  }\n\n  // CHECK_METHODS\n  try\n  {\n    // FIRST MATRIX TEST: pseudoInverse for square matrix with too low damping\n    // Skip to first line\n    if (!skipLine(&myfile, 1))\n      FAIL() << \"couldn't continue, file finished prematurely\";\n    // Read first matrix\n    J = readMatrix(&myfile, 3, 3);\n    // Compute test matrix\n    J_test = mwoibn::eigen_utils::pseudoInverse(m_square, 1e-18);\n    // Test first matrix\n    EXPECT_TRUE(compareMatrices(J, J_test, 1));\n\n    // SECOND MATRIX TEST: pseudoInverse for square matrix with correct damping\n    if (!skipLine(&myfile, 1))\n      FAIL() << \"couldn't continue, file finished prematurely\";\n    J = readMatrix(&myfile, 3, 3);\n    J_test = mwoibn::eigen_utils::pseudoInverse(m_square, 1e-8);\n    EXPECT_TRUE(compareMatrices(J, J_test, eps));\n\n    // THIRD MATRIX TEST: pseudoInverse for non-square matrix with defult\n    // damping\n    if (!skipLine(&myfile, 1))\n      FAIL() << \"couldn't continue, file finished prematurely\";\n    J = readMatrix(&myfile, 9, 5);\n    J_test = Eigen::MatrixXd::Zero(9, 5);\n    J_test = mwoibn::eigen_utils::pseudoInverse(m_nonsquare);\n    EXPECT_TRUE(compareMatrices(J, J_test, eps));\n\n    // FOURTH MATRIX TEST: agumented Null Space Projection Matrix\n    Eigen::MatrixXd P;\n    if (!skipLine(&myfile, 1))\n      FAIL() << \"couldn't continue, file finished prematurely\";\n    Eigen::MatrixXd P0 = readMatrix(&myfile, 9, 9);\n\n    if (!skipLine(&myfile, 1))\n      FAIL() << \"couldn't continue, file finished prematurely\";\n    J = readMatrix(&myfile, 9, 5);\n    J_test = Eigen::MatrixXd::Zero(9, 5);\n    J_test = mwoibn::eigen_utils::agumentedNullSpaceProjection(m_nonsquare, P0, P);\n    EXPECT_TRUE(compareMatrices(J, J_test, eps));\n  }\n  catch (const std::exception& exc)\n  {\n    ADD_FAILURE() << exc.what();\n  }\n  catch (...)\n  {\n    ADD_FAILURE()\n        << \"Unknown exception, while getting PointHandling information\";\n  }\n}\n\nint main(int argc, char** argv)\n{\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "5842616d5a81476ddca4c87a7b84eb164f3210e4", "size": 5163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "locomotion_framework/utils/eigen_utils/test/src/test_eigen_utils.cpp", "max_stars_repo_name": "ADVRHumanoids/DrivingFramework", "max_stars_repo_head_hexsha": "34715c37bfe3c1f2bd92aeacecc12704a1a7820e", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-02T07:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-02T07:10:42.000Z", "max_issues_repo_path": "locomotion_framework/utils/eigen_utils/test/src/test_eigen_utils.cpp", "max_issues_repo_name": "ADVRHumanoids/DrivingFramework", "max_issues_repo_head_hexsha": "34715c37bfe3c1f2bd92aeacecc12704a1a7820e", "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": "locomotion_framework/utils/eigen_utils/test/src/test_eigen_utils.cpp", "max_forks_repo_name": "ADVRHumanoids/DrivingFramework", "max_forks_repo_head_hexsha": "34715c37bfe3c1f2bd92aeacecc12704a1a7820e", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-22T19:06:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T03:32:52.000Z", "avg_line_length": 28.6833333333, "max_line_length": 83, "alphanum_fraction": 0.6070114275, "num_tokens": 1403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5331913082664546}}
{"text": "/**\n * @file radauthreetimestepping.cc\n * @brief NPDE homework RadauThreeTimestepping\n * @author Erick Schulz, edited by Oliver Rietmann\n * @date 08/04/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"radauthreetimestepping.h\"\n\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseLU>\n#include <cmath>\n#include <iostream>\n#include <unsupported/Eigen/KroneckerProduct>\n\nnamespace RadauThreeTimestepping {\n\n/**\n * @brief Implementation of the right hand side (time dependent) source vector\n * for the parabolic heat equation\n * @param dofh A reference to the DOFHandler\n * @param time The time at which to evaluate the source vector\n * @returns The source vector at time `time`\n */\n/* SAM_LISTING_BEGIN_1 */\nEigen::VectorXd rhsVectorheatSource(const lf::assemble::DofHandler &dofh,\n                                    double time) {\n  // Dimension of finite element space\n  const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n  // Right-hand side vector has to be set to zero initially\n  Eigen::VectorXd phi(N_dofs);\n  //====================\n  // Your code goes here\n  //====================\n  return phi;\n}\n/* SAM_LISTING_END_1 */\n\n/**\n * @brief Heat evolution solver: the solver obtains the\n * discrete evolution operator from the Radau3MOLTimestepper class and\n * repeatedly iterates its applicaiton starting from the initial condition\n * @param dofh The DOFHandler object\n * @param m is total number of steps until final time final_time (double)\n * @param final_time The duration for which to solve the PDE\n * @returns The solution at the final timestep\n */\n/* SAM_LISTING_BEGIN_6 */\nEigen::VectorXd solveHeatEvolution(const lf::assemble::DofHandler &dofh,\n                                   unsigned int m, double final_time) {\n  Eigen::VectorXd discrete_heat_sol(dofh.NumDofs());\n  //====================\n  // Your code goes here\n  //====================\n  return discrete_heat_sol;\n}\n/* SAM_LISTING_END_6 */\n\n/* Implementing member function Eval of class LinFEMassMatrixProvider*/\nEigen::Matrix<double, 3, 3> LinFEMassMatrixProvider::Eval(\n    const lf::mesh::Entity &tria) {\n  Eigen::Matrix<double, 3, 3> elMat;\n  //====================\n  // Your code goes here\n  //====================\n  return elMat;  // return the local mass element matrix\n}\n\n/* Implementing constructor of class Radau3MOLTimestepper */\n/* SAM_LISTING_BEGIN_4 */\nRadau3MOLTimestepper::Radau3MOLTimestepper(const lf::assemble::DofHandler &dofh)\n    : dofh_(dofh) {\n  //====================\n  // Your code goes here\n  // Add any additional members you need in the header file\n  //====================\n}\n/* SAM_LISTING_END_4 */\n\n/* Implementation of Radau3MOLTimestepper member functions */\n// The function discreteEvolutionOperator() returns the discretized evolution\n// operator as obtained from the Runge-Kutta Radau IIA 2-stages method using the\n// Butcher table as stored in the Radau3MOLTimestepper class\n/* SAM_LISTING_BEGIN_5 */\nEigen::VectorXd Radau3MOLTimestepper::discreteEvolutionOperator(\n    double time, double tau, const Eigen::VectorXd &mu) const {\n  Eigen::VectorXd discrete_evolution_operator(dofh_.NumDofs());\n  //====================\n  // Your code goes here\n  //====================\n  return discrete_evolution_operator;\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace RadauThreeTimestepping\n", "meta": {"hexsha": "cca0ef2fdf103eaeb86535ea000c56d8c70d9ea3", "size": 3444, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/RadauThreeTimestepping/templates/radauthreetimestepping.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/RadauThreeTimestepping/templates/radauthreetimestepping.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/RadauThreeTimestepping/templates/radauthreetimestepping.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 33.4368932039, "max_line_length": 80, "alphanum_fraction": 0.6881533101, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5331912943951005}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <cmath>\n#include <vector>\n#include <chrono>\n#include <string>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n#include \"../src/markovchains/MarkovChain.h\"\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace MarkovChain;\n\n// Eigen Flags\n//#define EIGEN_NDEBUG\n//#define EIGEN_NO_STATIC_ASSERT\n\n\n//// ENUMERATED CLASS FOR POLICY TYPE\nenum class Policies\n{\n    IDLE,\n    HIRE_LOW_WAGE,\n    HIRE_HIGH_WAGE,\n    LAYOFF_LOW_WAGE,\n    LAYOFF_HIGH_WAGE,\n    EXIT,\n};\n\n//// FUNCTION PHI THAT RETURNS SCALING OF HIRING ENTRY BY FIRM SIZE (PART OF THE PARAMETERS OF THE MODEL!!!)\ndouble phi(int total_employment){\n    return total_employment + 1;\n}\n\n\n//// MAIN PROGRAM\nint main()\n{\n    const bool verbose = true;\n    const bool graphs = true;\n    const bool tables = false;\n    const bool load_guess_from_file = false;\n    const bool save_guess_to_file = false;\n\n    // Greetings\n    if (verbose) {\n        cout <<\"----------------------------------------------\\n\";\n        cout <<\"------| SOLVING THE PROBLEM OF THE FIRM |-----\\n\";\n        cout <<\"----------------------------------------------\\n\\n\";\n    }\n\n    // Start Clock\n    auto t0 = std::chrono::high_resolution_clock::now();\n\n    // Endogenous Variables (should be passed as arguments of the function)\n    double hiring_rate_low = 0.1;\n    double hiring_rate_high = 3.0;\n    double quit_rate_low = 0.07;\n\n    // Parameters of the state space\n    const int nw = 2;       // ASSUME N_w = 2 for the time being\n    const int nz = 4;       // For now fix it at nz = 4\n    const int nbar = 60;\n    const double wl = 1.0;\n    const double wh = 1.25;\n\n    // Parameters of the model (read from file)\n    const double decreasing_returns = 0.666666666;\n    const double real_rate = 0.01;\n    const double discount_rate = log(1.0 + real_rate);\n    const double fixed_cost = 1.5;\n    const double exit_rate = 1e5;\n    const double layoff_rate = 13.0;\n    const double layoff_cost = 1.0;\n    const double exogenous_separations_rate = 1.0/16.0;\n    const double aggregate_productivity = 1.0;\n\n    // Parameters for HJB\n    const double hjb_criterion = 1e-10;\n    const int hjb_maxit = 100;\n    const double hjb_step_size = 1e8;\n    const double hjb_criterion_BiCGSTAB = 1e-6; // Must be relative to criterion_hjb\n\n    // Parameters for KFE\n    const double kfe_criterion = 1e-10;\n//    const int kfe_maxit = 100;\n    const double kfe_step_size = 1e8;\n    const double criterion_kfe_BiCGSTAB = 1e-6; // Must be relative to criterion_hjb\n\n    // Infinitesimal Generator of Poisson Process for Productivity and set \\mathcal{Z}.\n    Matrix4d Q;\n    Q(0,0) = -0.00; Q(0,1) =  0.00; Q(0,2) =  0.00; Q(0,3) =  0.00;\n    Q(1,0) =  0.10; Q(1,1) = -0.55; Q(1,2) =  0.30; Q(1,3) =  0.15;\n    Q(2,0) =  0.10; Q(2,1) =  0.25; Q(2,2) = -0.60; Q(2,3) =  0.25;\n    Q(3,0) =  0.10; Q(3,1) =  0.15; Q(3,2) =  0.30; Q(3,3) = -0.55;\n\n    Vector4d productivity;\n    productivity(0) = 0.00;\n    productivity(1) = 2.00;\n    productivity(2) = 2.75;\n    productivity(3) = 3.50;\n\n    // Entrants\n    Vector4d distribution_of_entrants;\n    distribution_of_entrants(0) = 0.00;\n    distribution_of_entrants(1) = 0.25;\n    distribution_of_entrants(2) = 0.50;\n    distribution_of_entrants(3) = 0.25;\n\n    // ADD PRINTING OF PARAMETERS\n    if (verbose){\n        // PRINT PARAMETERS HERE\n    }\n\n    // Type Definitions for Clarity\n    typedef Triplet<double> T;\n    typedef SparseMatrix<double, ColMajor> SM;\n    typedef SparseMatrix<double, RowMajor> SMr;\n\n    //// STEP 1: CREATE SPARSE MATRICES & PROFIT VECTORS\n    // NOTE: formulation removes for the first time all states such that n_l(omega) + n_h(omega) > n_bar.\n\n    if (verbose){\n        cout <<\"--------| CREATING SPARSE MATRICES... |-------\\n\";\n    }\n\n    const int num_endog_states = (nbar + 1) * (nbar + 2) / 2;\n    const int num_tot_states = nz * num_endog_states;\n\n    // Create matrix for lookup between idx and labor force (not trivial mapping, will try to fix this in the future)\n    MatrixX3i table_of_states(num_endog_states, 3);\n    MatrixXi table_of_states_inv = MatrixXi::Zero(nbar+1, nbar+1);\n    int k = 0;\n    for (int j = 0; j <= nbar; j += 1) {\n        for (int i = 0; i <= nbar; i += 1) {\n            if (i + j <= nbar) {\n                table_of_states(k,0) = k;\n                table_of_states(k,1) = i;\n                table_of_states(k,2) = j;\n                table_of_states_inv(i,j) = k;\n                k += 1;\n            }\n        }\n    }\n\n\n    // Define triplets + sparse matrices, and vectors for profits and severance pay\n    vector<T> triplet_stay; triplet_stay.reserve(num_tot_states * (2 * nz + 6));\n//    vector<T> triplet_layoff_low; triplet_layoff_low.reserve(2 * num_tot_states);\n//    vector<T> triplet_layoff_high; triplet_layoff_high.reserve(2 * num_tot_states);\n//    vector<T> triplet_hire_low; triplet_hire_low.reserve(2 * num_tot_states);\n//    vector<T> triplet_hire_high; triplet_hire_high.reserve(2 * num_tot_states);\n//    vector<T> triplet_exit; triplet_exit.reserve(num_tot_states);\n//    SM stay(num_tot_states,num_tot_states);\n//    SM endog_sep(num_tot_states,num_tot_states);\n//    SM layoff_low(num_tot_states,num_tot_states);\n//    SM layoff_high(num_tot_states,num_tot_states);\n//    SM hire_low(num_tot_states,num_tot_states);\n//    SM hire_high(num_tot_states,num_tot_states);\n//    SM exit(num_tot_states,num_tot_states);\n    VectorXd profits(num_tot_states);\n    VectorXd severance_pay_low(num_tot_states);\n    VectorXd severance_pay_high(num_tot_states);\n\n    // Populate objects by looping over all states, endogenous and exogenous.\n    for (int i = 0; i < num_tot_states; i += 1) {\n        int idx_endog = i % num_endog_states;\n        int nl = table_of_states(idx_endog, 1);\n        int nh = table_of_states(idx_endog, 2);\n        int n = nl + nh;\n        int z = i / num_endog_states;\n        if ( nl != 0) {\n            triplet_stay.emplace_back(T(i, i, - (exogenous_separations_rate + quit_rate_low) * nl));\n            triplet_stay.emplace_back(T(i, i - 1, (exogenous_separations_rate + quit_rate_low) * nl));\n//            triplet_layoff_low[2 * i] = T(i, i, -layoff_rate * nl);\n//            triplet_layoff_low[2 * i + 1] = T(i, i - 1, layoff_rate * nl);\n        }\n        if (nh != 0) {\n            triplet_stay.emplace_back(T(i, i, - exogenous_separations_rate * nh));\n            triplet_stay.emplace_back(T(i, i - (nbar - nh + 2), exogenous_separations_rate * nh));\n//            triplet_layoff_high[2 * i] = T(i, i  , -layoff_rate * nh);\n//            triplet_layoff_high[2 * i + 1] = T(i, i - (nbar - nh + 2), layoff_rate * nh);\n        }\n        if (n != nbar) {\n//            triplet_hire_low[2 * i] = T(i, i, - hiring_rate_low * phi(n));\n//            triplet_hire_low[2 * i + 1] = T(i, i + 1, hiring_rate_low * phi(n));\n//            triplet_hire_high[2 * i] = T(i, i, - hiring_rate_high * phi(n));\n//            triplet_hire_high[2 * i + 1] = T(i, i + (nbar - nh + 1), hiring_rate_high * phi(n));\n        }\n//        triplet_exit[i] = T(i, i, - exit_rate);\n        for (int k = 0; k < nz; k += 1) {\n            triplet_stay.emplace_back(T(i, i + (k - z) * num_endog_states, Q(z,k)));\n        }\n        profits(i) = productivity(z) * pow(n, decreasing_returns) - wl * nl - wh * nh - fixed_cost;\n        severance_pay_low(i) = -layoff_cost * layoff_rate * wl * nl;\n        severance_pay_high(i) = -layoff_cost * layoff_rate * wh * nh;\n    }\n//    triplet_layoff_low.insert(triplet_layoff_low.end(), triplet_stay.begin(), triplet_stay.end());\n//    triplet_layoff_high.insert(triplet_layoff_high.end(), triplet_stay.begin(), triplet_stay.end());\n//    triplet_hire_low.insert(triplet_hire_low.end(), triplet_stay.begin(), triplet_stay.end());\n//    triplet_hire_high.insert(triplet_hire_high.end(), triplet_stay.begin(), triplet_stay.end());\n//    triplet_exit.insert(triplet_exit.end(), triplet_stay.begin(), triplet_stay.end());\n//    stay.setFromTriplets(triplet_stay.begin(), triplet_stay.end());\n//    endog_sep.setFromTriplets(triplet_endog_sep.begin(),triplet_endog_sep.end());\n//    layoff_low.setFromTriplets(triplet_layoff_low.begin(), triplet_layoff_low.end());\n//    layoff_high.setFromTriplets(triplet_layoff_high.begin(), triplet_layoff_high.end());\n//    hire_low.setFromTriplets(triplet_hire_low.begin(), triplet_hire_low.end());\n//    hire_high.setFromTriplets(triplet_hire_high.begin(), triplet_hire_high.end());\n//    exit.setFromTriplets(triplet_exit.begin(), triplet_exit.end());\n\n    // Matrices for Hiring are h * matrix!\n//    hire_low = hiring_rate_low * hire_low;\n//    hire_high = hiring_rate_high * hire_high;\n//    endog_sep = quit_rate_low * endog_sep;\n//    for (int i = 0; i < triplet_endog_sep.size(); i += 1){\n//        triplet_endog_sep[i].value() = quit_rate_low * triplet_endog_sep[i].value();\n//    }\n\n\n\n    // Time\n    auto t1 = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> elapsed_sparse = t1 - t0;\n    if (verbose) {\n        cout <<\"Sparse Matrices Computed in: \" << elapsed_sparse.count() << \"\\n\\n\";\n        cout <<\"--------| SOLVING THE HJB EQUATION... |-------\\n\";\n    }\n\n    //// STEP 2: SOLVE HJB EQUATION\n\n\n    // Set guess of value function or try loading it from file.\n    VectorXd value = VectorXd::LinSpaced(num_tot_states, 0, 1);\n    if (load_guess_from_file) {\n        ifstream inf(\"value_guess.dat\", ios::binary);\n        if (!inf) {\n            ;\n        } else {\n            int nbar_file;\n            int nz_file;\n            inf >> nbar_file;\n            inf >> nz_file;\n            if (nbar_file == nbar && nz_file == nz){\n                int i = 0;\n                while (inf && i < num_tot_states) {\n                    inf >> value(i);\n                    i += 1;\n                }\n            }\n        }\n    }\n\n    // Preallocate objects for HJB equation loop\n    VectorXd value_next(num_tot_states);\n    vector<Policies> policy;\n    policy.reserve(num_tot_states);\n//    VectorXd profits_vector_for_hjb(num_tot_states);\n//    MatrixXi::Index maxRow, maxCol;\n//    Matrix<double, Dynamic, Dynamic> alternatives(num_tot_states, 6);\n\n\n\n    // Identity Matrix\n    SMr speye(num_tot_states,num_tot_states);\n    speye.setIdentity();\n\n    // Auxiliary Matrix for Linear System\n\n    vector<T> triplet_sparse_matrix_for_hjb;\n//    triplet_sparse_matrix_for_hjb.reserve(num_tot_states * (nz * 2 + 6));\n\n    // Solver Definition\n    // BiCGSTAB\n    BiCGSTAB<SMr> hjb_solver;\n    hjb_solver.setTolerance(hjb_criterion_BiCGSTAB * hjb_criterion);\n\n    // SparseLU\n//    SparseLU<SM, COLAMDOrdering<int>> hjb_solver;\n\n    // While Loop\n    double max_diff = -1;\n    double diff = -1;\n    int iteration_hjb = 0;\n    double supnorm_hjb = 1e100;\n    while (iteration_hjb < hjb_maxit && supnorm_hjb > hjb_criterion) {\n\n//        profits_vector_for_hjb = profits;\n        VectorXd profits_vector_for_hjb = profits;\n\n        vector<T> triplet_update_infinitesimal_generator;\n        triplet_update_infinitesimal_generator.insert(triplet_update_infinitesimal_generator.end(),\n                                                      triplet_stay.begin(),\n                                                      triplet_stay.end());\n\n\n        // Infinitesimal Generator (no entry)\n        SMr infinitesimal_generator(num_tot_states,num_tot_states);\n//        infinitesimal_generator.reserve(VectorXi::Constant(num_tot_states, 3 + nz));\n\n        SMr A(num_tot_states,num_tot_states);\n\n        // Populate objects by looping over all states, endogenous and exogenous.\n        for (int i = 0; i < num_tot_states; i += 1) {\n            int idx_endog = i % num_endog_states;\n            int nl = table_of_states(idx_endog, 1);\n            int nh = table_of_states(idx_endog, 2);\n            int n = nl + nh;\n            int z = i / num_endog_states;\n\n            ArrayXd alternatives = ArrayXd::Constant(6, -1);\n\n            alternatives(0) = 0;\n            if (nl != 0) {\n                alternatives(3) = layoff_rate * nl * (value(i - 1) - layoff_cost * wl - value(i));\n            }\n            if (nh != 0) {\n                alternatives(4) = layoff_rate * nh * (value(i - (nbar - nh + 2)) - layoff_cost * wh - value(i));\n            }\n            if (n != nbar) {\n                alternatives(1) = hiring_rate_low * phi(n) * (value(i + 1) - value(i));\n                alternatives(2) = hiring_rate_high * phi(n) * (value(i + (nbar - nh + 1)) - value(i));\n            }\n            alternatives(5) = -exit_rate * value(i);\n\n            ArrayXd::Index maxIdx;\n            alternatives.maxCoeff(&maxIdx);\n            policy[i] = static_cast<Policies>(maxIdx);\n\n            switch (policy[i])\n            {\n                case Policies::IDLE:\n                    break;\n\n                case Policies::HIRE_LOW_WAGE:\n                    triplet_update_infinitesimal_generator.emplace_back(T(i, i, -hiring_rate_low * phi(n)));\n                    triplet_update_infinitesimal_generator.emplace_back(T(i, i + 1, hiring_rate_low * phi(n)));\n                    break;\n\n                case Policies::HIRE_HIGH_WAGE:\n                    triplet_update_infinitesimal_generator.emplace_back(T(i, i, -hiring_rate_high * phi(n)));\n                    triplet_update_infinitesimal_generator.emplace_back(T(i, i + (nbar - nh + 1), hiring_rate_high * phi(n)));\n                    break;\n\n                case Policies::LAYOFF_LOW_WAGE:\n                    triplet_update_infinitesimal_generator.emplace_back(T(i, i, -layoff_rate * nl));\n                    triplet_update_infinitesimal_generator.emplace_back(T(i, i - 1, layoff_rate * nl));\n                    profits_vector_for_hjb(i) += severance_pay_low(i);\n                    break;\n\n                case Policies::LAYOFF_HIGH_WAGE:\n                    triplet_update_infinitesimal_generator.emplace_back(T(i, i, -layoff_rate * nh));\n                    triplet_update_infinitesimal_generator.emplace_back(T(i, i - (nbar - nh + 2), layoff_rate * nh));\n                    profits_vector_for_hjb(i) += severance_pay_high(i);\n                    break;\n\n                case Policies::EXIT:\n                    triplet_update_infinitesimal_generator.emplace_back(T(i, i, -exit_rate));\n                    break;\n            }\n        }\n\n        VectorXd b(num_tot_states);\n\n        b = profits_vector_for_hjb + (1 / hjb_step_size) * value;\n        infinitesimal_generator.setFromTriplets(triplet_update_infinitesimal_generator.begin(),\n                                                triplet_update_infinitesimal_generator.end());\n        A = (1 / hjb_step_size + discount_rate) * speye - infinitesimal_generator;\n\n\n//        cout << A;\n//        cout <<\"\\n\"<< b;\n//        for (int i = 0; i < num_tot_states; i += 1){\n//            cout << \"\\n\" << static_cast<int>(policy[i]);\n//        }\n\n\n        // BiCGSTAB\n        hjb_solver.compute(A);\n        value_next = hjb_solver.solveWithGuess(b,value);\n\n\n        // SparseLU\n//        hjb_solver.analyzePattern(A);\n//        hjb_solver.factorize(A);\n//        value_next = hjb_solver.solve(b);\n\n        // Compute Supnorm\n        max_diff = -1;\n        diff = -1;\n        for (int i = 0; i < num_tot_states; i += 1){\n            diff = abs(value(i) - value_next(i));\n            if (diff > max_diff) {\n                max_diff = diff;\n            }\n        }\n        supnorm_hjb = max_diff;\n\n        // Update value function\n        value = value_next;\n\n        // Update iteration count and display advancement\n        iteration_hjb += 1;\n        if (verbose) {\n            if (iteration_hjb % 5 == 0 || iteration_hjb ==1){\n                cout <<\"Iteration = \"<<iteration_hjb<<\", SupNorm = \"<<supnorm_hjb<<\"\\n\";\n            }\n        }\n\n        // Save vector of triplets for fast creation of final sparse matrix\n        if (supnorm_hjb < hjb_criterion) {\n            triplet_sparse_matrix_for_hjb.insert(triplet_sparse_matrix_for_hjb.end(),\n                                                 triplet_update_infinitesimal_generator.begin(),\n                                                 triplet_update_infinitesimal_generator.end());\n        }\n    }\n\n    // Add entrants to the Sparse Infinitesimal Generator\n    for (int i = 0; i < num_tot_states; i += 1) {\n        switch (policy[i])\n        {\n            case Policies::IDLE:break;\n            case Policies::HIRE_LOW_WAGE:break;\n            case Policies::HIRE_HIGH_WAGE:break;\n            case Policies::LAYOFF_LOW_WAGE:break;\n            case Policies::LAYOFF_HIGH_WAGE:break;\n            case Policies::EXIT:\n                for (int k = 0; k < nz; k += 1) {\n                    triplet_sparse_matrix_for_hjb.emplace_back(T(i, num_endog_states * k, exit_rate * distribution_of_entrants(k)));\n                }\n                break;\n        }\n    }\n//    sparse_matrix_for_hjb.setZero()\n    SMr sparse_matrix_for_hjb(num_tot_states,num_tot_states);\n    sparse_matrix_for_hjb.setFromTriplets(triplet_sparse_matrix_for_hjb.begin(), triplet_sparse_matrix_for_hjb.end());\n\n\n    // Save Value Function to File\n    if (save_guess_to_file) {\n        ofstream outf(\"value_guess.dat\", ios::binary);\n        if (!outf) {\n            ;\n        } else {\n            std::streamsize ss = std::cout.precision();\n            outf.precision(16);\n            outf << nbar << endl;\n            outf << nz << endl;\n            for(int i =0; i < num_tot_states; i += 1) {\n                outf << value(i) << endl;\n            }\n            outf.precision(ss);\n        }\n    }\n\n    // Time\n    auto t2 = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> elapsed_hjb = t2 - t1;\n    if (verbose) {\n        if (iteration_hjb % 5 != 0) {\n            cout << \"Iteration = \" << iteration_hjb << \", SupNorm = \" << supnorm_hjb << \"\\n\";\n        }\n        cout <<\"----------------------------------------------\\n\";\n        cout <<\"HJB Equations solved in: \" << elapsed_hjb.count() << \"\\n\\n\";\n        cout <<\"--------| SOLVING THE KF EQUATIONS... |-------\\n\";\n    }\n\n\n    //// STEP 3: SOLVE KF EQUATIONS\n\n    // Solve KF Equations using Sparse CTMC Class (REMEMBER!! A is the infinitesimal generator, SparseCTMC takes care\n    // of getting the adjoint).\n    SparseCTMC endogenous_ctmc = SparseCTMC(sparse_matrix_for_hjb);\n    VectorXd distribution;\n    distribution = endogenous_ctmc.getStationaryDistribution(kfe_step_size);\n    cout << \"Check Sum to 1:\" << distribution.sum() << \"\\n\";\n\n    // Polish distribution trimming low values\n    double cumsum = 0.0;\n    for (int i = 0; i < num_tot_states; i += 1){\n        if (abs(distribution(i)) < kfe_criterion) {\n            distribution(i) = 0.0;\n        }\n        cumsum += distribution(i);\n    }\n    distribution = distribution / cumsum;\n\n\n    // Time\n    auto t3 = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> elapsed_kfe = t3 - t2;\n    if (verbose) {\n        cout <<\"KF Equations solved in: \" << elapsed_kfe.count() << \"\\n\\n\";\n        cout <<\"--------|   COMPUTING AGGREGATES...   |-------\\n\";\n    }\n\n    //// STEP 4: COMPUTE AGGREGATES\n    //TODO: Add aggregates\n    // Aggregates: Demand Intensities and Employment Shares\n    double agg_hiring_flow_low_wage = 0;\n    double agg_hiring_flow_high_wage = 0;\n    double agg_demand_intensity_low_wage = 0;\n    double agg_demand_intensity_high_wage = 0;\n    double agg_employment_low_wage = 0;\n    double agg_employment_high_wage = 0;\n\n    // Statistics by Firm Size\n    VectorXd firm_size_distribution = VectorXd::Zero(nbar + 1);\n    VectorXd mean_wage_by_firm_size_temp = VectorXd::Zero(nbar + 1);\n    VectorXd layoffs_low_wage_by_firm_size = VectorXd::Zero(nbar + 1);\n    VectorXd layoffs_high_wage_by_firm_size = VectorXd::Zero(nbar + 1);\n    VectorXd layoffs_total_by_firm_size = VectorXd::Zero(nbar + 1);\n    VectorXd mass_layoffs_low_wage_by_firm_size = VectorXd::Zero(nbar + 1);\n    VectorXd mass_layoffs_high_wage_by_firm_size = VectorXd::Zero(nbar + 1);\n    VectorXd mass_layoffs_total_by_firm_size = VectorXd::Zero(nbar + 1);\n    VectorXd endogenous_separations_by_firm_size = VectorXd::Zero(nbar + 1);\n    VectorXd poaching_by_firm_size = VectorXd::Zero(nbar + 1);\n\n    // Poaching\n    VectorXd poaching_by_state(num_tot_states);\n    double agg_fraction_poached;\n    double agg_flow_of_quits;\n    // TODO ADD POACHING\n\n\n    // NL - NH graph unconditional on productivity level\n    VectorXd unconditional_distribution = VectorXd::Zero(num_endog_states);\n\n    for (int i = 0; i < num_tot_states; i += 1){\n        int idx_endog = i % num_endog_states;\n        int nl = table_of_states(idx_endog, 1);\n        int nh = table_of_states(idx_endog, 2);\n        int n = nl + nh;\n        int z = i / num_endog_states;\n\n        agg_employment_low_wage += nl * distribution(i);\n        agg_employment_high_wage += nh * distribution(i);\n\n        unconditional_distribution(idx_endog) += distribution(i);\n\n        firm_size_distribution(n) += distribution(i);\n\n        mean_wage_by_firm_size_temp(n) += (wl * nl + wh * nh) * distribution(i) / n;\n\n        endogenous_separations_by_firm_size(n) += quit_rate_low * nl * distribution(i);\n\n\n        switch (policy[i]){\n            case Policies::HIRE_HIGH_WAGE:\n                agg_demand_intensity_high_wage += distribution(i) * phi(n) * hiring_rate_high;\n                break;\n            case Policies::HIRE_LOW_WAGE:\n                agg_demand_intensity_low_wage += distribution(i) * phi(n) * hiring_rate_low;\n                break;\n            case Policies::IDLE:break;\n            case Policies::LAYOFF_LOW_WAGE:\n                layoffs_low_wage_by_firm_size(n) += distribution(i) * nl * layoff_rate;\n                layoffs_total_by_firm_size(n) += distribution(i) * nl * layoff_rate;\n                break;\n            case Policies::LAYOFF_HIGH_WAGE:\n                layoffs_high_wage_by_firm_size(n) += distribution(i) * nh * layoff_rate;\n                layoffs_total_by_firm_size(n) += distribution(i) * nh * layoff_rate;\n                break;\n            case Policies::EXIT:\n                mass_layoffs_low_wage_by_firm_size(n) += distribution(i) * nl * exit_rate;\n                mass_layoffs_high_wage_by_firm_size(n) += distribution(i) * nh * exit_rate;\n                break;\n        }\n\n\n\n    }\n    mass_layoffs_total_by_firm_size = mass_layoffs_low_wage_by_firm_size + mass_layoffs_high_wage_by_firm_size;\n    agg_demand_intensity_low_wage = agg_hiring_flow_high_wage / hiring_rate_high;\n    agg_demand_intensity_low_wage = agg_hiring_flow_low_wage / hiring_rate_low;\n\n\n    int max_firm_size = 0;\n    for (int i = 0; i <= nbar; i += 1){\n        if (firm_size_distribution(i) > kfe_criterion) {\n            max_firm_size = i;\n        }\n    }\n    VectorXd mean_wage_by_firm_size(max_firm_size + 1);\n    mean_wage_by_firm_size = mean_wage_by_firm_size_temp.head(max_firm_size + 1);\n    for (int i = 0; i <= max_firm_size; i += 1){\n        mean_wage_by_firm_size(i) = mean_wage_by_firm_size(i) / firm_size_distribution(i);\n    }\n\n    // Time\n    auto t4 = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> elapsed_agg = t4 - t3;\n    if (verbose) {\n        cout <<\"Aggregates computed in: \" << elapsed_agg.count() << \"\\n\\n\";\n    }\n\n    //// TOTAL TIME ELAPSED\n    auto t_end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> elapsed_tot = t_end - t0;\n    if (verbose) {\n        cout <<\"--------|            DONE!            |-------\\n\";\n        cout << \"Total Execution Time = \" << elapsed_tot.count() << endl;\n        cout <<\" \\n\\n\";\n    }\n\n\n    //// DISPLAY RESULTS FOR CLARITY\n\n    //// TABLES\n    if (tables) {\n        cout << \"----------------------------------------------\\n\";\n        cout << \"--------|    STATISTICS OF INTEREST   |-------\\n\";\n        cout << \"----------------------------------------------\\n\\n\";\n\n        cout << \"Aggregate Employment:\\n\";\n        cout << \"Low Wage\\t\" << agg_employment_low_wage << \"\\n\";\n        cout << \"High Wage\\t\" << agg_employment_high_wage << \"\\n\";\n\n\n\n        cout << \"\\n\\n\";\n    }\n\n    //// GRAPHS\n    if (graphs) {\n        cout << \"----------------------------------------------\\n\";\n        cout << \"--------|            PLOTS            |-------\\n\";\n        cout << \"----------------------------------------------\\n\\n\";\n\n        //// POLICY FUNCTIONS\n        cout << \"--------|       POLICY FUNCTIONS      |-------\\n\\n\";\n        cout << \"\\033[1mLegend\\033[0m\\n\";\n        cout << \"Color\\t\\tCode\\tPolicy\\n\";\n        cout << \"\\033[1;34mBlue\\t\\t2\\t\\tHire at High Wage\\033[0m\\n\";\n        cout << \"\\033[1;36mCyan\\t\\t1\\t\\tHire at Low Wage\\033[0m\\n\";\n        cout << \"\\033[1;32mGreen\\t\\t0\\t\\tStay\\033[0m\\n\";\n        cout << \"\\033[1;35mMagenta\\t\\t3\\t\\tLay Off at Low Wage\\033[0m\\n\";\n        cout << \"\\033[1;31mRed\\t\\t\\t4\\t\\tLay Off at High Wage\\033[0m\\n\";\n        cout << \"\\033[1;30mWhite\\t\\t5\\t\\tExit\\033[0m\\n\";\n\n        for (int z = 0; z < nz; z += 1){\n            cout << \"\\n\\n\";\n            cout << \"Productivity is: \" << productivity(z) << \"\\n\";\n            for (int row = nbar; row >= 0; row -= 1){\n                if (row == nbar) {\n                    cout << \"NH\\t\" << row << \"\\t\";\n                } else {\n                    cout << \"\\n\\t\" << row <<\"\\t\";\n                }\n                for (int col = 0; col <= nbar; col += 1){\n                    if (row + col <= nbar) {\n                        int index_endog = table_of_states_inv(col,row);\n                        int i = z * num_endog_states + index_endog;\n                        switch (policy[i]) {\n                            case Policies::IDLE:\n                                cout << \"\\033[1;32m\" << static_cast<int>(policy[i]) << \"\\033[0m\\t\"; break;\n                            case Policies::HIRE_LOW_WAGE:\n                                cout << \"\\033[1;36m\" << static_cast<int>(policy[i]) << \"\\033[0m\\t\"; break;\n                            case Policies::HIRE_HIGH_WAGE:\n                                cout << \"\\033[1;34m\" << static_cast<int>(policy[i]) << \"\\033[0m\\t\"; break;\n                            case Policies::LAYOFF_LOW_WAGE:\n                                cout << \"\\033[1;35m\" << static_cast<int>(policy[i]) << \"\\033[0m\\t\"; break;\n                            case Policies::LAYOFF_HIGH_WAGE:\n                                cout << \"\\033[1;31m\" << static_cast<int>(policy[i]) << \"\\033[0m\\t\"; break;\n                            case Policies::EXIT:\n                                cout << \"\\033[1;30m\" << static_cast<int>(policy[i]) << \"\\033[0m\\t\"; break;\n                        }\n                    } else if (col < nbar){\n                        cout << \"\\t\";\n                    }\n                }\n            }\n            cout << \"\\n\\t\\t\";\n            for (int col = 0; col <= nbar; col += 1){\n                cout << col << \"\\t\";\n            }\n            cout << \"\\n\\t\\tNL\\n\";\n        }\n\n        //// UNCONDITIONAL DISTRIBUTION\n        cout << \"\\n\\n\";\n\n        cout << \"--------| UNCONDITIONAL DISTRIBUTION  |-------\\n\\n\";\n        double graph_max = unconditional_distribution.maxCoeff();\n        VectorXd graph_cutoffs = VectorXd::LinSpaced(7,kfe_criterion,graph_max+1e-6);\n        string colors[7] = {\"35\", \"31\", \"33\", \"32\", \"36\", \"34\", \"30\"};\n\n        cout << \"\\033[1mLegend\\033[0m\\n\";\n        cout << \"Color\\t\\tInterval\\n\";\n        cout << \"\\033[1;34mBlue\\t\\t[ \" << graph_cutoffs(5) << \", \" << graph_cutoffs(6) << \" ]\\033[0m\\n\";\n        cout << \"\\033[1;36mCyan\\t\\t[ \" << graph_cutoffs(4) << \", \" << graph_cutoffs(5) << \" )\\033[0m\\n\";\n        cout << \"\\033[1;32mGreen\\t\\t[ \" << graph_cutoffs(3) << \", \" << graph_cutoffs(4) << \" )\\033[0m\\n\";\n        cout << \"\\033[1;33mYellow\\t\\t[ \" << graph_cutoffs(2) << \", \" << graph_cutoffs(3) << \" )\\033[0m\\n\";\n        cout << \"\\033[1;31mRed\\t\\t\\t[ \" << graph_cutoffs(1) << \", \" << graph_cutoffs(2) << \" )\\033[0m\\n\";\n        cout << \"\\033[1;35mMagenta\\t\\t( \" << \"0\" << \", \" << graph_cutoffs(1) << \" )\\033[0m\\n\";\n        cout << \"\\033[1;30mWhite\\t\\tLess than tolerance (essentially zero).\\033[0m\\n\\n\";\n\n        for (int row = nbar; row >= 0; row -= 1){\n            if (row == nbar) {\n                cout << \"NH\\t\" << row << \"\\t\";\n            } else {\n                cout << \"\\n\\t\" << row << \"\\t\";\n            }\n            for (int col = 0; col <= nbar; col += 1){\n                if (row + col <= nbar) {\n                    int index_endog = table_of_states_inv(col,row);\n                    for (int j = 1; j < 7; j += 1){\n                        if (unconditional_distribution(index_endog) >= kfe_criterion && unconditional_distribution(index_endog) < graph_cutoffs(j)){\n                            cout << \"\\033[1;\"<< colors[j-1] <<\"mx\\033[0m\\t\";\n                            break;\n                        } else if (unconditional_distribution(index_endog) < kfe_criterion){\n                            cout << \"\\033[1;\"<< colors[6] <<\"mx\\033[0m\\t\";\n                            break;\n                        }\n                    }\n                } else if (col < nbar){\n                    cout << \"\\t\";\n                }\n            }\n        }\n        cout << \"\\n\\t\\t\";\n        for (int col = 0; col <= nbar; col += 1){\n            cout << col << \"\\t\";\n        }\n        cout << \"\\n\\t\\tNL\\n\";\n\n\n\n        //// FIRM SIZE DISTRIBUTION\n        cout << \"\\n\\n\";\n        cout << \"--------|    FIRM SIZE DISTRIBUTION   |-------\\n\\n\";\n\n        graph_max = firm_size_distribution.maxCoeff();\n        graph_cutoffs = VectorXd::LinSpaced(21,kfe_criterion,graph_max);\n        for (int row = 21; row > 0; row -= 1){\n            std::streamsize ss = std::cout.precision();\n            if (row == 21) {\n                cout.precision(2);\n                cout << \"f(x)\" << std::fixed << graph_cutoffs(20) << \"\\t\";\n                cout.precision(ss);\n            } else {\n                cout.precision(2);\n                cout << \"\\n\\t\" << std::fixed << graph_cutoffs(row-1) <<\"\\t\";\n                cout.precision(ss);\n            }\n            for (int col = 0; col <= nbar; col += 1){\n                if (firm_size_distribution(col) < graph_cutoffs(row-1)){\n                    cout << \"\\t\";\n                } else {\n                    cout << \"\\033[1;34mx\\033[0m\\t\";\n                }\n            }\n        }\n        cout << \"\\n\\t\\t\\t\";\n        for (int col = 0; col <= nbar; col += 1){\n            cout << col << \"\\t\";\n        }\n        cout << \"\\n\\t\\t\\tTotal Employees\\n\";\n\n\n\n        //// MEAN WAGE BY FIRM SIZE\n        cout << \"\\n\\n\";\n        cout << \"--------|    MEAN WAGE BY FIRM SIZE   |-------\\n\\n\";\n\n        graph_cutoffs = VectorXd::LinSpaced(21,wl,wh);\n        for (int row = 21; row > 1; row -= 1){\n            std::streamsize ss = std::cout.precision();\n            if (row == 21) {\n                cout.precision(2);\n                cout << \"f(x)\" << std::fixed << graph_cutoffs(20) << \"\\t\";\n                cout.precision(ss);\n            } else {\n                cout.precision(2);\n                cout << \"\\n\\t\" << std::fixed << graph_cutoffs(row-1) <<\"\\t\";\n                cout.precision(ss);\n            }\n            for (int col = 1; col <= max_firm_size; col += 1){\n                if (mean_wage_by_firm_size(col) > graph_cutoffs(row-1) || mean_wage_by_firm_size(col) <= graph_cutoffs(row-2)){\n                    cout << \"\\t\";\n                } else {\n                    cout << \"\\033[1;34mx\\033[0m\\t\";\n                }\n            }\n        }\n        cout << \"\\n\\t\\t\\t\";\n        for (int col = 1; col <= max_firm_size; col += 1){\n            cout << col << \"\\t\";\n        }\n        cout << \"\\n\\t\\t\\tTotal Employees\\n\";\n\n\n        //// TODO ADD OTHER GRAPHS\n\n\n    }\n}", "meta": {"hexsha": "b08258b9359a1d696722450b6b127b131683e95d", "size": 31580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/ForninoSartori18/old/main_full_trial.cpp", "max_stars_repo_name": "mfornino/showcase", "max_stars_repo_head_hexsha": "892d14b9d440c90835a8838b7a9db9c4f232d58b", "max_stars_repo_licenses": ["MIT"], "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/ForninoSartori18/old/main_full_trial.cpp", "max_issues_repo_name": "mfornino/showcase", "max_issues_repo_head_hexsha": "892d14b9d440c90835a8838b7a9db9c4f232d58b", "max_issues_repo_licenses": ["MIT"], "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/ForninoSartori18/old/main_full_trial.cpp", "max_forks_repo_name": "mfornino/showcase", "max_forks_repo_head_hexsha": "892d14b9d440c90835a8838b7a9db9c4f232d58b", "max_forks_repo_licenses": ["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.5244055069, "max_line_length": 148, "alphanum_fraction": 0.5500316656, "num_tokens": 8471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5331884332089314}}
{"text": "#include \"case.hpp\"\n#include \"catch.hpp\"\n#include \"quadeigs.hpp\"\n#include \"timer.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <cmath>\n#include <fmt/format.h>\n#include <iostream>\n#include <vector>\n\nusing namespace Eigen;\nusing Td = Triplet<double>;\n\nTEST_CASE(\"random (4, 4)\", \"[quadeigs]\") {\n  int ndim = 4;\n  MatrixXd matM = MatrixXd::Random(ndim, ndim);\n  MatrixXd matD = MatrixXd::Random(ndim, ndim);\n  MatrixXd matK = MatrixXd::Random(ndim, ndim);\n  Case1 c1(matM, matD, matK);\n  fmt::print(\"{:>30s}, {:>15s}\\n\", \"alphas\", \"betas\");\n  for (int i = 0; i < ndim; ++i) {\n    fmt::print(\"{:14.5f}+{:14.5f}i, {:15.5f}\\n\", c1.alphas(i).real(),\n               c1.alphas(i).imag(), c1.betas(i));\n  }\n\n  QuadEigs qe(matM, matD, matK);\n  int m = 4;\n  VectorXcd ev = qe.eigenvalues(m);\n}\n\nTEST_CASE(\"random (10, 10)\", \"[quadeigs]\") {\n  int ndim = 10;\n  MatrixXd matM = MatrixXd::Random(ndim, ndim);\n  MatrixXd matD = MatrixXd::Random(ndim, ndim);\n  MatrixXd matK = MatrixXd::Random(ndim, ndim);\n  Case1 c1(matM, matD, matK);\n  for (int i = 0; i < ndim; ++i) {\n    if (std::abs(c1.betas(i)) > 1.0e-8) {\n      fmt::print(\"{:14.5f}+{:14.5f}i\\n\", c1.alphas(i).real() / c1.betas(i),\n                 c1.alphas(i).imag() / c1.betas(i));\n    }\n  }\n  fmt::print(\"---------------------------------------------------\\n\");\n\n  QuadEigs qe(matM, matD, matK);\n  int m = 4;\n  VectorXcd ev = qe.eigenvalues(m);\n}\n\nTEST_CASE(\"Identity (20, 20)\", \"[quadeigs]\") {\n  int ndim = 20;\n  MatrixXd matM = MatrixXd::Identity(ndim, ndim);\n  MatrixXd matD = MatrixXd::Identity(ndim, ndim);\n  MatrixXd matK = MatrixXd::Identity(ndim, ndim) * 0.2;\n  for (int i = 1; i < ndim; ++i) {\n    matK(i, i - 1) = -0.1;\n    matK(i - 1, i) = -0.1;\n  }\n  std::cout << matK.inverse() << std::endl;\n  Case1 c1(matM, matD, matK);\n  for (int i = 0; i < ndim; ++i) {\n    if (std::abs(c1.betas(i)) > 1.0e-8) {\n      fmt::print(\"{:14.5f}+{:14.5f}i\\n\", c1.alphas(i).real() / c1.betas(i),\n                 c1.alphas(i).imag() / c1.betas(i));\n    }\n  }\n  fmt::print(\"---------------------------------------------------\\n\");\n\n  QuadEigs qe(matM, matD, matK);\n  int m = 4;\n  VectorXcd ev = qe.eigenvalues(m);\n}\n\nTEST_CASE(\"inverse benchmark\", \"[quadeigs]\") {\n  int ndim = 20;\n  MatrixXd matD = MatrixXd::Identity(ndim, ndim) * 2;\n  for (int i = 1; i < ndim; ++i) {\n    matD(i, i - 1) = -1.0;\n    matD(i - 1, i) = -1.0;\n  }\n  MatrixXd matId = MatrixXd::Identity(ndim, ndim);\n  Timer::begin(\"inv-dense\");\n  MatrixXd matDi = matD.ldlt().solve(matId);\n  Timer::end(\"inv-dense\");\n\n  SparseMatrix<double> matS(ndim, ndim);\n  std::vector<Td> tl;\n  for (int i = 0; i < ndim; ++i) {\n    tl.push_back(Td(i, i, 2.0));\n  }\n  for (int i = 1; i < ndim; ++i) {\n    tl.push_back(Td(i, i - 1, -1.0));\n    tl.push_back(Td(i - 1, i, -1.0));\n  }\n  matS.setFromTriplets(tl.begin(), tl.end());\n  SparseMatrix<double> matI(ndim, ndim);\n  matI.setIdentity();\n\n  Timer::begin(\"inv-sparse\");\n  SimplicialLDLT<SparseMatrix<double>> solver;\n  solver.compute(matS);\n  SparseMatrix<double> matSi = solver.solve(matI);\n  Timer::end(\"inv-sparse\");\n\n  std::cout << Timer::summery() << std::endl;\n}", "meta": {"hexsha": "db8c13fe8c30cf5fcac0420b70771745d0cb6bce", "size": 3120, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test_quadeigs.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/test_quadeigs.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/test_quadeigs.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": 28.8888888889, "max_line_length": 75, "alphanum_fraction": 0.5621794872, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5331884261314083}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, 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#include <cstddef>\n#include <string>\n\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/algorithms/convex_hull.hpp>\n\n\n#include <boost/geometry/algorithms/area.hpp>\n#include <boost/geometry/algorithms/num_points.hpp>\n\n#include <boost/geometry/io/wkt/read.hpp>\n#include <boost/geometry/io/wkt/write.hpp>\n\n#include <boost/geometry/strategies/strategies.hpp>\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n#include <boost/geometry/util/as_range.hpp>\n\n\ntemplate <typename Geometry>\nvoid test_geometry(std::string const& wkt,\n                      std::size_t size_original, std::size_t size_hull,\n                      double expected_area)\n{\n\n    Geometry geometry;\n    bg::read_wkt(wkt, geometry);\n\n    typedef typename bg::point_type<Geometry>::type P;\n    typename bg::strategy::side::services::default_strategy\n        <\n            typename bg::cs_tag<P>::type\n        >::type side;\n\n    boost::ignore_unused(side);\n\n    typedef typename bg::range_type<Geometry>::type range_type;\n    typedef typename boost::range_const_iterator<range_type>::type iterator;\n\n    range_type const& range = bg::as_range<range_type>(geometry);\n\n    iterator it1 = boost::begin(range);\n    iterator it3 = it1++;\n    iterator it2 = it1++;\n\n    for (;\n        it2 != boost::end(range);\n        ++it1, ++it2, ++it3)\n    {\n       // Last/closing point\n       if (it1 == boost::end(range))\n       {\n           it1 = boost::begin(range) + 1;\n       }\n       int s = side.apply(*it1, *it2, *it3);\n\n       if (s != 1)\n       {\n          std::cout << \"NOT CONVEX!\";\n       }\n       if (s == 0)\n       {\n          std::cout << \" COLLINEAR!\";\n       }\n\n       std::cout\n           << \" \" << bg::wkt(*it3)\n           << \" \" << bg::wkt(*it2)\n           << \" \" << bg::wkt(*it1)\n           << \" \" << s\n           << std::endl;\n    }\n\n    std::cout << bg::area(geometry) << \" \" << bg::wkt(geometry) << std::endl;\n}\n\ntemplate <typename P>\nvoid test_all()\n{\n    // rectangular, with concavity\n    test_geometry<bg::model::polygon<P> >(\n        \"polygon((1 1, 1 4, 3 4, 3 3, 4 3, 4 4, 5 4, 5 1, 1 1))\",\n                9, 5, 12.0);\n\n\n   // concavity at start/closing point\n   test_geometry<bg::model::polygon<P> >(\n        \"polygon((1 1,0 2,3 3,1 0,1 1))\", 9, 5, 12.0);\n\n    // from sample polygon, with concavity\n    test_geometry<bg::model::polygon<P> >(\n        \"polygon((2.0 1.3, 2.4 1.7, 2.8 1.8, 3.4 1.2, 3.7 1.6,3.4 2.0, 4.1 3.0\"\n        \", 5.3 2.6, 5.4 1.2, 4.9 0.8, 2.9 0.7,2.0 1.3))\",\n                12, 8, 5.245);\n}\n\nint test_main(int, char* [])\n{\n    //test_all<bg::model::d2::point_xy<int> >();\n    //test_all<bg::model::d2::point_xy<float> >();\n    test_all<bg::model::d2::point_xy<double> >();\n\n#if defined(HAVE_TTMATH)\n    test_all<bg::model::d2::point_xy<ttmath_big> >();\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "86f3dbef8415be5444a2f450514459005fb6f44e", "size": 3439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/algorithms/is_convex.cpp", "max_stars_repo_name": "tinko92/geometry", "max_stars_repo_head_hexsha": "56a9f79036dc3bce8dcd0483cfa728a196997f81", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T20:30:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T08:14:05.000Z", "max_issues_repo_path": "extensions/test/algorithms/is_convex.cpp", "max_issues_repo_name": "barendgehrels/geometry", "max_issues_repo_head_hexsha": "1998db08d6037681768c4e8dfc9f2593df0c32fa", "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": "extensions/test/algorithms/is_convex.cpp", "max_forks_repo_name": "barendgehrels/geometry", "max_forks_repo_head_hexsha": "1998db08d6037681768c4e8dfc9f2593df0c32fa", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:22:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T10:43:59.000Z", "avg_line_length": 27.0787401575, "max_line_length": 79, "alphanum_fraction": 0.5995929049, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5331884211410657}}
{"text": "#define BOOST_TEST_MODULE matrix\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/matrix/all.h++>\n#include <mla/vector/all.h++>\n#include <mla/matrix/convert.h++>\n\n#include <mla/operations/level3/syrk.h++>\n\n\ntypedef boost::mpl::list<\n\tmla::matrix::DenseRowMajor<float>,\n\tmla::matrix::DenseRowMajor<double>\n> matrix_type_list;\n\n\nBOOST_AUTO_TEST_SUITE(test_operations)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( matrix_level3_syrk_ones, MatrixType, matrix_type_list )\n{\n\tsize_t matrix_size = 6;\n\n\ttypedef typename MatrixType::scalar_type Scalar;\n\n\tmla::matrix::DenseRowMajor<Scalar> from(matrix_size, 1);\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tfrom.setValue( i, 0, (Scalar)1.0f );\n\t}\n\n\tMatrixType A(matrix_size, 1);\n\tmla::matrix::convert(from, A);\n\n\tMatrixType C(matrix_size, matrix_size);\n\n\tScalar const alfa = 1.0;\n\tScalar const beta = 1.0;\n\tmla::syrk(alfa, A, beta, C);\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tfor(unsigned int j = 0; j < matrix_size; j++)\n\t\t{\n\t\t\tBOOST_CHECK_CLOSE( C.getValue(i,j), (Scalar)1.0f, 0.001f);\n\t\t}\n\t}\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "79e0bfefbd817088273a098f346030744cde4f8d", "size": 1158, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_blas_level3_syrk.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "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": "unit_tests/test_blas_level3_syrk.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/test_blas_level3_syrk.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "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.9655172414, "max_line_length": 86, "alphanum_fraction": 0.7115716753, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925404, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5331884182379035}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2014-2015, Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\r\n\r\n// Licensed under the Boost Software License version 1.0.\r\n// http://www.boost.org/users/license.html\r\n\r\n#include <iostream>\r\n\r\n#ifndef BOOST_TEST_MODULE\r\n#define BOOST_TEST_MODULE test_distance_pointlike_linear\r\n#endif\r\n\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\n#include \"test_distance_common.hpp\"\r\n\r\n\r\ntypedef bg::model::point<double,2,bg::cs::cartesian>  point_type;\r\ntypedef bg::model::multi_point<point_type>            multi_point_type;\r\ntypedef bg::model::segment<point_type>                segment_type;\r\ntypedef bg::model::linestring<point_type>             linestring_type;\r\ntypedef bg::model::multi_linestring<linestring_type>  multi_linestring_type;\r\n\r\nnamespace services = bg::strategy::distance::services;\r\ntypedef bg::default_distance_result<point_type>::type return_type;\r\n\r\ntypedef bg::strategy::distance::pythagoras<> point_point_strategy;\r\ntypedef bg::strategy::distance::projected_point<> point_segment_strategy;\r\n\r\n\r\n//===========================================================================\r\n\r\n\r\ntemplate <typename Strategy>\r\nvoid test_distance_point_segment(Strategy const& strategy)\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl;\r\n    std::cout << \"point/segment distance tests\" << std::endl;\r\n#endif\r\n    typedef test_distance_of_geometries<point_type, segment_type> tester;\r\n\r\n    tester::apply(\"point(0 0)\", \"segment(2 0,3 0)\", 2, 4, strategy);\r\n    tester::apply(\"point(2.5 3)\", \"segment(2 0,3 0)\", 3, 9, strategy);\r\n    tester::apply(\"point(2 0)\", \"segment(2 0,3 0)\", 0, 0, strategy);\r\n    tester::apply(\"point(3 0)\", \"segment(2 0,3 0)\", 0, 0, strategy);\r\n    tester::apply(\"point(2.5 0)\", \"segment(2 0,3 0)\", 0, 0, strategy);\r\n\r\n    // distance is a NaN\r\n    tester::apply(\"POINT(4.297374e+307 8.433875e+307)\",\r\n                  \"SEGMENT(26 87,13 95)\",\r\n                  0, 0, strategy, false);\r\n}\r\n\r\n//===========================================================================\r\n\r\ntemplate <typename Strategy>\r\nvoid test_distance_point_linestring(Strategy const& strategy)\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl;\r\n    std::cout << \"point/linestring distance tests\" << std::endl;\r\n#endif\r\n    typedef test_distance_of_geometries<point_type, linestring_type> tester;\r\n\r\n    tester::apply(\"point(0 0)\", \"linestring(2 0,3 0)\", 2, 4, strategy);\r\n    tester::apply(\"point(2.5 3)\", \"linestring(2 0,3 0)\", 3, 9, strategy);\r\n    tester::apply(\"point(2 0)\", \"linestring(2 0,3 0)\", 0, 0, strategy);\r\n    tester::apply(\"point(3 0)\", \"linestring(2 0,3 0)\", 0, 0, strategy);\r\n    tester::apply(\"point(2.5 0)\", \"linestring(2 0,3 0)\", 0, 0, strategy);\r\n\r\n    // linestring with a single point\r\n    tester::apply(\"point(0 0)\", \"linestring(2 0)\", 2, 4, strategy);\r\n\r\n    // distance is a NaN\r\n    tester::apply(\"POINT(4.297374e+307 8.433875e+307)\",\r\n                  \"LINESTRING(26 87,13 95)\",\r\n                  0, 0, strategy, false);\r\n}\r\n\r\n//===========================================================================\r\n\r\ntemplate <typename Strategy>\r\nvoid test_distance_point_multilinestring(Strategy const& strategy)\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl;\r\n    std::cout << \"point/multilinestring distance tests\" << std::endl;\r\n#endif\r\n    typedef test_distance_of_geometries\r\n        <\r\n            point_type, multi_linestring_type\r\n        > tester;\r\n\r\n    tester::apply(\"point(0 0)\",\r\n                  \"multilinestring((-5 0,-3 0),(2 0,3 0))\",\r\n                  2, 4, strategy);\r\n    tester::apply(\"point(2.5 3)\",\r\n                  \"multilinestring((-5 0,-3 0),(2 0,3 0))\",\r\n                  3, 9, strategy);\r\n    tester::apply(\"point(2 0)\",\r\n                  \"multilinestring((-5 0,-3 0),(2 0,3 0))\",\r\n                  0, 0, strategy);\r\n    tester::apply(\"point(3 0)\",\r\n                  \"multilinestring((-5 0,-3 0),(2 0,3 0))\",\r\n                  0, 0, strategy);\r\n    tester::apply(\"point(2.5 0)\",\r\n                  \"multilinestring((-5 0,-3 0),(2 0,3 0))\",\r\n                  0, 0, strategy);\r\n    tester::apply(\"POINT(0 0)\",\r\n                  \"MULTILINESTRING((10 10,10 0),(0.0 -0.0,0.0 -0.0))\",\r\n                  0, 0, strategy);\r\n    tester::apply(\"POINT(0 0)\",\r\n                  \"MULTILINESTRING((10 10,10 0),(1 1,1 1))\",\r\n                  sqrt(2.0), 2, strategy);\r\n    tester::apply(\"POINT(0 0)\",\r\n                  \"MULTILINESTRING((10 10,10 0),(1 1,2 2))\",\r\n                  sqrt(2.0), 2, strategy);\r\n    tester::apply(\"POINT(0 0)\",\r\n                  \"MULTILINESTRING((10 10,10 0),(20 20,20 20))\",\r\n                  10, 100, strategy);\r\n\r\n    // multilinestrings containing an empty linestring\r\n    tester::apply(\"POINT(0 0)\",\r\n                  \"MULTILINESTRING((),(10 0),(20 20,20 20))\",\r\n                  10, 100, strategy);\r\n    tester::apply(\"POINT(0 0)\",\r\n                  \"MULTILINESTRING((),(10 0),(),(20 20,20 20))\",\r\n                  10, 100, strategy);\r\n\r\n    // multilinestrings containing a linestring with a single point\r\n    tester::apply(\"POINT(0 0)\",\r\n                  \"MULTILINESTRING((10 0),(20 20,20 20))\",\r\n                  10, 100, strategy);\r\n    tester::apply(\"POINT(0 0)\",\r\n                  \"MULTILINESTRING((20 20,20 20),(10 0))\",\r\n                  10, 100, strategy);\r\n\r\n    // multilinestring with a single-point linestring and empty linestrings\r\n    tester::apply(\"POINT(0 0)\",\r\n                  \"MULTILINESTRING((),(20 20,20 20),(),(10 0))\",\r\n                  10, 100, strategy);\r\n}\r\n\r\n//===========================================================================\r\n\r\ntemplate <typename Strategy>\r\nvoid test_distance_linestring_multipoint(Strategy const& strategy)\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl;\r\n    std::cout << \"linestring/multipoint distance tests\" << std::endl;\r\n#endif\r\n    typedef test_distance_of_geometries\r\n        <\r\n            linestring_type, multi_point_type\r\n        > tester;\r\n\r\n    tester::apply(\"linestring(2 0,0 2,100 100)\",\r\n                  \"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  0, 0, strategy);\r\n    tester::apply(\"linestring(4 0,0 4,100 100)\",\r\n                  \"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  sqrt(2.0), 2, strategy);\r\n    tester::apply(\"linestring(1 1,2 2,100 100)\",\r\n                  \"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  0, 0, strategy);\r\n    tester::apply(\"linestring(3 3,4 4,100 100)\",\r\n                  \"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  sqrt(8.0), 8, strategy);\r\n\r\n    // linestring with a single point\r\n    tester::apply(\"linestring(1 8)\",\r\n                  \"multipoint(0 0,3 0,4 -7,10 100)\",\r\n                  sqrt(65.0), 65, strategy);\r\n}\r\n\r\n//===========================================================================\r\n\r\ntemplate <typename Strategy>\r\nvoid test_distance_multipoint_multilinestring(Strategy const& strategy)\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl;\r\n    std::cout << \"multipoint/multilinestring distance tests\" << std::endl;\r\n#endif\r\n    typedef test_distance_of_geometries\r\n        <\r\n            multi_point_type, multi_linestring_type\r\n        > tester;\r\n\r\n    tester::apply(\"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  \"multilinestring((2 0,0 2),(2 2,3 3))\",\r\n                  0, 0, strategy);\r\n    tester::apply(\"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  \"multilinestring((3 0,0 3),(4 4,5 5))\",\r\n                  0.5 * sqrt(2.0), 0.5, strategy);\r\n    tester::apply(\"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  \"multilinestring((4 4,5 5),(1 1,2 2))\",\r\n                  0, 0, strategy);\r\n    tester::apply(\"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  \"multilinestring((3 3,4 4),(4 4,5 5))\",\r\n                  sqrt(8.0), 8, strategy);\r\n\r\n    // multilinestring with empty linestring\r\n    tester::apply(\"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  \"multilinestring((),(3 3,4 4),(4 4,5 5))\",\r\n                  sqrt(8.0), 8, strategy);\r\n    tester::apply(\"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  \"multilinestring((3 3,4 4),(),(4 4,5 5))\",\r\n                  sqrt(8.0), 8, strategy);\r\n\r\n    // multilinestrings with a single-point linestrings\r\n    tester::apply(\"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  \"multilinestring((3 3),(4 4,5 5))\",\r\n                  sqrt(8.0), 8, strategy);\r\n    tester::apply(\"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  \"multilinestring((4 4,5 5),(3 3))\",\r\n                  sqrt(8.0), 8, strategy);\r\n\r\n    // multilinestring with a single-point linestring and empty linestring\r\n    tester::apply(\"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  \"multilinestring((4 4,5 5),(),(3 3))\",\r\n                  sqrt(8.0), 8, strategy);\r\n\r\n    // 21890717 - assertion failure in distance(Pt, Box)\r\n    {\r\n        multi_point_type mpt;\r\n        bg::read_wkt(\"multipoint(1 1,1 1,1 1,1 1,1 1,1 1,1 1,1 1,1 1)\", mpt);\r\n        multi_linestring_type mls;\r\n        linestring_type ls;\r\n        point_type pt(std::numeric_limits<double>::quiet_NaN(), 1.0);\r\n        ls.push_back(pt);\r\n        ls.push_back(pt);\r\n        mls.push_back(ls);\r\n        bg::distance(mpt, mls);\r\n    }\r\n}\r\n\r\n//===========================================================================\r\n\r\ntemplate <typename Strategy>\r\nvoid test_distance_multipoint_segment(Strategy const& strategy)\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl;\r\n    std::cout << \"multipoint/segment distance tests\" << std::endl;\r\n#endif\r\n    typedef test_distance_of_geometries<multi_point_type, segment_type> tester;\r\n\r\n    tester::apply(\"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  \"segment(2 0,0 2)\",\r\n                  0, 0, strategy);\r\n    tester::apply(\"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  \"segment(4 0,0 4)\",\r\n                  sqrt(2.0), 2, strategy);\r\n    tester::apply(\"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  \"segment(1 1,2 2)\",\r\n                  0, 0, strategy);\r\n    tester::apply(\"multipoint(0 0,1 0,0 1,1 1)\",\r\n                  \"segment(3 3,4 4)\",\r\n                  sqrt(8.0), 8, strategy);\r\n    tester::apply(\"multipoint(4 4,5 5,2 2,3 3)\",\r\n                  \"segment(0 0,1 1)\",\r\n                  sqrt(2.0), 2, strategy);\r\n}\r\n\r\n//===========================================================================\r\n\r\ntemplate <typename Point, typename Strategy>\r\nvoid test_more_empty_input_pointlike_linear(Strategy const& strategy)\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl;\r\n    std::cout << \"testing on empty inputs... \" << std::flush;\r\n#endif\r\n    bg::model::linestring<Point> line_empty;\r\n    bg::model::multi_point<Point> multipoint_empty;\r\n    bg::model::multi_linestring<bg::model::linestring<Point> > multiline_empty;\r\n\r\n    Point point = from_wkt<Point>(\"point(0 0)\");\r\n    bg::model::linestring<Point> line =\r\n        from_wkt<bg::model::linestring<Point> >(\"linestring(0 0,1 1)\");\r\n\r\n    // 1st geometry is empty\r\n    test_empty_input(multipoint_empty, line, strategy);\r\n\r\n    // 2nd geometry is empty\r\n    test_empty_input(point, line_empty, strategy);\r\n    test_empty_input(point, multiline_empty, strategy);\r\n\r\n    // both geometries are empty\r\n    test_empty_input(multipoint_empty, line_empty, strategy);\r\n    test_empty_input(multipoint_empty, multiline_empty, strategy);\r\n\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << \"done!\" << std::endl;\r\n#endif\r\n}\r\n\r\n\r\n//===========================================================================\r\n//===========================================================================\r\n//===========================================================================\r\n\r\nBOOST_AUTO_TEST_CASE( test_all_point_segment )\r\n{\r\n    test_distance_point_segment(point_point_strategy()); // back-compatibility\r\n    test_distance_point_segment(point_segment_strategy());\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_all_point_linestring )\r\n{\r\n    test_distance_point_linestring(point_point_strategy()); // back-compatibility\r\n    test_distance_point_linestring(point_segment_strategy());\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_all_point_multilinestring )\r\n{\r\n    test_distance_point_multilinestring(point_point_strategy()); // back-compatibility\r\n    test_distance_point_multilinestring(point_segment_strategy());\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_all_linestring_multipoint )\r\n{\r\n    test_distance_linestring_multipoint(point_point_strategy()); // back-compatibility\r\n    test_distance_linestring_multipoint(point_segment_strategy());\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_all_multipoint_multilinestring )\r\n{\r\n    test_distance_multipoint_multilinestring(point_point_strategy()); // back-compatibility\r\n    test_distance_multipoint_multilinestring(point_segment_strategy());\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_all_multipoint_segment )\r\n{\r\n    test_distance_multipoint_segment(point_segment_strategy());\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_all_empty_input_pointlike_linear )\r\n{\r\n    test_more_empty_input_pointlike_linear\r\n        <\r\n            point_type\r\n        >(point_segment_strategy());\r\n}\r\n", "meta": {"hexsha": "9c3101983a140e52911a1d9f88d2b99a08a3c9b8", "size": 13157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/distance/distance_pointlike_linear.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/distance/distance_pointlike_linear.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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/distance/distance_pointlike_linear.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": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T11:06:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-08T11:06:22.000Z", "avg_line_length": 37.3778409091, "max_line_length": 92, "alphanum_fraction": 0.5574979099, "num_tokens": 3617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5331884090732}}
{"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_ASINH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASINH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-hyperbolic\n    This function object returns the hyperbolic sine argument: \\f$\\log(x+\\sqrt{x^2+1})\\f$.\n\n    @par Header <boost/simd/function/asinh.hpp>\n\n    @see log, sqrt, sinh, inc\n\n    @par Example:\n\n      @snippet asinh.cpp asinh\n\n    @par Possible output:\n\n      @snippet asinh.txt asinh\n\n  **/\n  IEEEValue asinh(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/asinh.hpp>\n#include <boost/simd/function/simd/asinh.hpp>\n\n#endif\n", "meta": {"hexsha": "7bcc109130857b12fe9ad060c5770bf0cd6fcb76", "size": 1030, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/asinh.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/function/asinh.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/function/asinh.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": 23.4090909091, "max_line_length": 100, "alphanum_fraction": 0.572815534, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5331029825189553}}
{"text": "/**\n * \\file PedalToneStackFilter.cpp\n */\n\n#include <boost/math/tools/polynomial.hpp>\n\n#include \"PedalToneStackFilter.h\"\n#include \"IIRFilter.h\"\n\nnamespace ATK\n{\n  template<typename DataType>\n  SD1ToneCoefficients<DataType>::SD1ToneCoefficients(int nb_channels)\n  :TypedBaseFilter<DataType>(nb_channels, nb_channels), R1(10e3), R2(22e3), R3(470), R4(10e3),\n    C1(static_cast<DataType>(0.018e-6)), C2(static_cast<DataType>(0.027e-6)), C3(static_cast<DataType>(0.01e-6)), alpha(1)\n  {\n  }\n\n  template<typename DataType>\n  void SD1ToneCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n\n    DataType tempm[2] = {static_cast<DataType>(-2 * input_sampling_rate), static_cast<DataType>(2 * input_sampling_rate)};\n    DataType tempp[2] = {static_cast<DataType>(1), static_cast<DataType>(1)};\n    boost::math::tools::polynomial<DataType> poly1(tempm, 1);\n    boost::math::tools::polynomial<DataType> poly2(tempp, 1);\n\n    boost::math::tools::polynomial<DataType> b;\n    boost::math::tools::polynomial<DataType> a;\n    \n    b += poly2 * poly2;\n    b += poly2 * poly1 * (C2*R3+R4*C3+alpha*(1-alpha)*R2*C2+alpha*C2*R4);\n    b += poly1 * poly1 * (C3*R4*(R3*C2+alpha*(1-alpha)*R2*C2));\n\n    a += poly2 * poly2;\n    a += poly2 * poly1 * (C2*R3+R1*C1+alpha*(1-alpha)*R2*C2+(1-alpha)*C2*R1);\n    a += poly1 * poly1 * (C1*R1*(R3*C2+alpha*(1-alpha)*R2*C2));\n\n    for(int i = 0; i < in_order + 1; ++i)\n    {\n      coefficients_in[i] = b[i] / a[out_order];\n    }\n    for(int i = 0; i < out_order; ++i)\n    {\n      coefficients_out[i] = -a[i] / a[out_order];\n    }\n  }\n\n  template<typename DataType_>\n  void SD1ToneCoefficients<DataType_>::set_tone(DataType_ alpha)\n  {\n    if(alpha < 0 || alpha > 1)\n    {\n      throw std::out_of_range(\"Tone is outside the interval [0,1]\");\n    }\n    this->alpha = alpha;\n\n    setup();\n  }\n  \n  template<typename DataType_>\n  DataType_ SD1ToneCoefficients<DataType_>::get_tone() const\n  {\n    return alpha;\n  }\n\n  template<typename DataType>\n  TS9ToneCoefficients<DataType>::TS9ToneCoefficients(int nb_channels)\n  :TypedBaseFilter<DataType>(nb_channels, nb_channels), R1(1e3), R2(10e3), R3(1e3), R4(220), P(22e3),\n  C1(static_cast<DataType>(0.022e-6)), C2(static_cast<DataType>(0.022e-6)), alpha(1)\n  {\n  }\n  \n  template<typename DataType>\n  void TS9ToneCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    DataType tempm[2] = {static_cast<DataType>(-2 * input_sampling_rate), static_cast<DataType>(2 * input_sampling_rate)};\n    DataType tempp[2] = {static_cast<DataType>(1), static_cast<DataType>(1)};\n    boost::math::tools::polynomial<DataType> poly1(tempm, 1);\n    boost::math::tools::polynomial<DataType> poly2(tempp, 1);\n    \n    boost::math::tools::polynomial<DataType> b;\n    boost::math::tools::polynomial<DataType> a;\n    \n    b += R2 * poly2 * poly2;\n    b += poly2 * poly1 * (alpha * C2 * R2 * R3 + alpha * (1-alpha) * C2 * P * R2 + R2 * R4 * C2);\n    \n    a += (R2 + R1) * poly2 * poly2;\n    a += poly2 * poly1 * ((1-alpha) * C2 * (alpha * P * R2 + R1 * alpha * P + R1 * R2) + R4 * C2 * (R2 + R1) + R1 * C1 * R2);\n    a += poly1 * poly1 * (C2 * R4 * C1 * R2 * R1 + (1-alpha) * C2 * R1 * P * C1 * R2);\n    \n    for(int i = 0; i < in_order + 1; ++i)\n    {\n      coefficients_in[i] = b[i] / a[out_order];\n    }\n    for(int i = 0; i < out_order; ++i)\n    {\n      coefficients_out[i] = -a[i] / a[out_order];\n    }\n  }\n  \n  template<typename DataType_>\n  void TS9ToneCoefficients<DataType_>::set_tone(DataType_ alpha)\n  {\n    if(alpha < 0 || alpha > 1)\n    {\n      throw std::out_of_range(\"Tone is outside the interval [0,1]\");\n    }\n    this->alpha = alpha;\n    \n    setup();\n  }\n  \n  template<typename DataType_>\n  DataType_ TS9ToneCoefficients<DataType_>::get_tone() const\n  {\n    return alpha;\n  }\n\n  template class SD1ToneCoefficients<float>;\n  template class SD1ToneCoefficients<double>;\n  \n  template class IIRFilter<SD1ToneCoefficients<float> >;\n  template class IIRFilter<SD1ToneCoefficients<double> >;\n\n  template class TS9ToneCoefficients<float>;\n  template class TS9ToneCoefficients<double>;\n  \n  template class IIRFilter<TS9ToneCoefficients<float> >;\n  template class IIRFilter<TS9ToneCoefficients<double> >;\n}\n", "meta": {"hexsha": "0940f1754672e340f2454cca7ac9e856d3becbef", "size": 4347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/PedalToneStackFilter.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/PedalToneStackFilter.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/PedalToneStackFilter.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.829787234, "max_line_length": 125, "alphanum_fraction": 0.641131815, "num_tokens": 1431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.5328792096125977}}
{"text": "/*\n * MIT License\n * \n * Copyright (c) 2019 Camille Schreck\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 * definition.hpp\n */\n\n#ifndef DEFINITIONS_HPP\n#define DEFINITIONS_HPP\n\n#include <Eigen/Core>\n\nusing namespace Eigen;\n\n//#define DOUBLE_PRECISION\n\n#ifdef DOUBLE_PRECISION\n\n#define FLOAT double\n#define VEC2 Vector2d\n#define VEC3 Vector3d\n#define VEC4 Vector4d\n#define VECX VectorXd\n#define MAT2 Matrix2d\n#define MAT3 Matrix3d\n#define MAT4 Matrix4d\n#define MATX MatrixXd\n#define ANGLE_AXIS AngleAxisd\n#define QUATERNION Quaterniond\n#define COMPLEX std::complex<double>\n#define VEC2C Vector2cd\n#define VECXC VectorXcd\n#define MATXC MatrixXcd\n\n#else\n\n#define FLOAT float\n#define VEC2 Vector2f\n#define VEC3 Vector3f\n#define VEC4 Vector4f\n#define VECX VectorXf\n#define MAT2 Matrix2f\n#define MAT3 Matrix3f\n#define MAT4 Matrix4f\n#define MATX MatrixXf\n#define ANGLE_AXIS AngleAxisf\n#define QUATERNION Quaternionf\n#define COMPLEX std::complex<float>\n#define VEC2C Vector2cf\n#define VECXC VectorXcf\n#define MATXC MatrixXcf\n\n#endif\n\ninline FLOAT damping(FLOAT d_coef, FLOAT x, FLOAT k) {\n  return exp(-d_coef*k*k*x); \n}\n  \n\n\ninline COMPLEX fund_solution(FLOAT x) {\n  return COMPLEX(0, -1)/(FLOAT)4.0*sqrtf(2.0f/(M_PI*x))*exp(COMPLEX(0, 1)*(x - (FLOAT)M_PI/4.0f));\n}\n\ninline FLOAT omega(FLOAT k) {\n  return sqrtf(9.81*k + 0.074/1000*pow(k, 3));\n}\n\ninline FLOAT velocity(FLOAT k) {\n  return 0.5*omega(k)/k;\n}\ninline FLOAT velocity(FLOAT k, FLOAT omega) {\n  return 0.5*omega/k;\n}\n\n// linear interpolation 1 if x = p1, 0 if x = p2\ninline FLOAT interpolation(float x, float p1, float p2) {\n  float d = p2 - p1;\n  float dx = x - p1;\n  return 1-dx/d;\n}\n\n#endif\n", "meta": {"hexsha": "60400db2c9511c668f36b1b357b17e6711e78ec8", "size": 2683, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/definitions.hpp", "max_stars_repo_name": "schreckc/FSWW_houdini", "max_stars_repo_head_hexsha": "c5766304f35e2f3d9e159953aebeea5079e27f90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-11-05T08:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T08:05:46.000Z", "max_issues_repo_path": "src/definitions.hpp", "max_issues_repo_name": "schreckc/FSWW_houdini", "max_issues_repo_head_hexsha": "c5766304f35e2f3d9e159953aebeea5079e27f90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/definitions.hpp", "max_forks_repo_name": "schreckc/FSWW_houdini", "max_forks_repo_head_hexsha": "c5766304f35e2f3d9e159953aebeea5079e27f90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-22T09:56:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T04:58:04.000Z", "avg_line_length": 26.0485436893, "max_line_length": 98, "alphanum_fraction": 0.7491613865, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.53280770280431}}
{"text": "#pragma once\n\n#include <stdexcept>\n#include <vector>\n\n#include <Eigen/Core>\n\n#include \"LineSegment/linesegment.hh\"\n\nnamespace bold\n{\n  template <typename T,int dim>\n  class Bounds\n  {\n  public:\n    typedef Eigen::Matrix<T,dim,1> Point;\n\n    Bounds(Point min, Point max)\n    : d_min(min),\n      d_max(max)\n    {\n      if ((max - min).minCoeff() < 0)\n        throw std::runtime_error(\"Max must be greater than min.\");\n    }\n\n    bool operator==(Bounds<T,dim> const& other) const\n    {\n      return d_min == other.d_min && d_max == other.d_max;\n    }\n\n    friend std::ostream& operator<<(std::ostream& stream, Bounds<T,dim> const& line)\n    {\n      return stream << \"Bounds (min=\" << line.d_min.transpose() << \" max=\" << line.d_max.transpose() << \")\";\n    }\n\n    Point min() const { return d_min; }\n    Point max() const { return d_max; }\n\n    Point mid() const\n    {\n      Eigen::Matrix<T,dim,1> mid;\n      for (int i = 0; i < dim; i++)\n        mid[i] = (d_min[i] + d_max[i]) / 2;\n      return mid;\n    }\n\n    bool contains(Point const& v) const\n    {\n      return (v - d_min).minCoeff() >= 0 && (d_max - v).minCoeff() >= 0;\n    }\n\n    bool overlaps(Bounds<T,dim> const& other) const\n    {\n      for (int i = 0; i < dim; i++)\n      {\n        if (d_max[i] <= other.d_min[i] ||\n            d_min[i] >= other.d_max[i])\n          return false;\n      }\n\n      return true;\n    }\n\n    /** True if the any dimension of this bounding box are zero. */\n    bool isEmpty() const\n    {\n      return (d_max - d_min).cwiseAbs().minCoeff() == 0;\n    }\n\n  protected:\n    Point d_min;\n    Point d_max;\n  };\n\n  template<typename T>\n  class Bounds2 : public Bounds<T,2>\n  {\n  public:\n    typedef Eigen::Matrix<T,2,1> Point;\n    typedef LineSegment<T,2> LineSegmentType;\n\n    static Bounds2<T> merge(Bounds2<T> const& a, Bounds2<T> const& b)\n    {\n      return Bounds2<T>(\n        std::min(a.min().x(), b.min().x()),\n        std::min(a.min().y(), b.min().y()),\n        std::max(a.max().x(), b.max().x()),\n        std::max(a.max().y(), b.max().y()));\n    }\n\n    Bounds2(T minX, T minY, T maxX, T maxY)\n      : Bounds<T,2>::Bounds(Point(minX, minY), Point(maxX, maxY))\n    {}\n\n    Bounds2(Point minPoint, Point maxPoint)\n      : Bounds<T,2>::Bounds(minPoint, maxPoint)\n    {}\n\n    T minDimension() const\n    {\n      return std::min(width(), height());\n    }\n\n    T maxDimension() const\n    {\n      return std::max(width(), height());\n    }\n\n    T width() const\n    {\n      return this->d_max.x() - this->d_min.x();\n    }\n\n    T height() const\n    {\n      return this->d_max.y() - this->d_min.y();\n    }\n\n    /** Returns corners in clockwise order, starting at 'min'. */\n    std::vector<Point> getCorners() const\n    {\n      std::vector<Point> corners = {\n        this->d_min, Point(this->d_min.x(), this->d_max.y()),\n        this->d_max, Point(this->d_max.x(), this->d_min.y())\n      };\n\n      return corners;\n    }\n\n    std::vector<LineSegmentType, Eigen::aligned_allocator<LineSegmentType>> getEdges() const\n    {\n      auto corners = getCorners();\n      std::vector<LineSegmentType, Eigen::aligned_allocator<LineSegmentType>> edges;\n      for (unsigned i = 0, lastIndex = 3; i < 4; lastIndex = i++)\n      {\n        if (corners[lastIndex] != corners[i])\n          edges.emplace_back(corners[lastIndex], corners[i]);\n      }\n\n      return edges;\n    }\n  };\n\n  typedef Bounds2<int> Bounds2i;\n  typedef Bounds2<double> Bounds2d;\n  typedef Bounds<double,3> Bounds3d;\n}\n", "meta": {"hexsha": "f16c82debd2230445cbe2b1f395a3706e9006087", "size": 3443, "ext": "hh", "lang": "C++", "max_stars_repo_path": "geometry/Bounds.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/Bounds.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/Bounds.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": 23.2635135135, "max_line_length": 108, "alphanum_fraction": 0.5582340982, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.532807699692758}}
{"text": "//\n\n#include <string>\n#include <vector>\n//#include <tuple>\n#include <cstdio>\n\n#include <Eigen/Sparse>\n\n#include \"SparseMatrix.hpp\"\n#include \"SparseVector.hpp\"\n#include \"DenseVector.hpp\"\n#include \"KernelComposer.hpp\"\n#include \"KernelComposerHelpers.hpp\"\n\n#include \"gtest/gtest.h\"\n\nclass KernelComposerTest: public ::testing::Test{\n    protected:\n    //KernelComposerTest(){};\n    //~KernelComposerTest(){};\n    \n    void SetUp() override{\n        std::string dnv1name(\"dnv_name_1\");\n        std::string dnv2name(\"dnv_name_2\");\n        std::string spvname(\"spv_name\");\n        std::string spmname(\"spm_name\");\n        std::vector<double> dnv1;\n        std::vector<double> dnv2;\n        Eigen::SparseVector<double> spv;\n        Eigen::SparseMatrix<double,1> spm;\n        \n        for(int k=0;k<Nv;k++){\n            dnv1.push_back(10.0*((double)(k)));\n        };\n        DnV1.setName(dnv1name);\n        DnV1.setVector(dnv1);\n        \n        for(int k=0;k<Nv;k++){\n            dnv2.push_back(10.0);\n        };\n        DnV2.setName(dnv2name);\n        DnV2.setVector(dnv2);\n        \n        spv.resize(Nv);\n        for(int k=Nv/4;k<(3*Nv/4);k++){\n            spv.coeffRef(k)=10.0;\n        };\n        SpV.setName(spvname);\n        SpV.vec=spv;\n        \n        spm.resize(Nv,Nv);\n        for(int k=0;k<Nv;k++){\n            spm.coeffRef(k,k)=1.0;\n        };\n        spm.makeCompressed();\n        SpM.setName(spmname);\n        SpM.mat=spm;\n\n        for(int k=0;k<NtSig;k++){\n            ft.push_back(1.0);\n        };\n    };\n    //void TearDown() override{};\n    swSim::DenseVector DnV1;\n    swSim::DenseVector DnV2;\n    swSim::SparseVector SpV;\n    swSim::SparseMatrix SpM;\n    std::vector<double> ft;\n    \n    int Nv=20;\n    int NtSig=10;\n};\n\nTEST_F(KernelComposerTest,committed){\n    swSim::KernelComposer KC;\n    EXPECT_FALSE(KC.isCommitted());\n};\n\nTEST_F(KernelComposerTest,setDnV){\n    swSim::KernelComposer KC;\n    EXPECT_EQ(KC.setDenseVector(&DnV1),swSim::KC_OK);\n};\n\nTEST_F(KernelComposerTest,setSpV){\n    swSim::KernelComposer KC;\n    EXPECT_EQ(KC.setSparseVector(&SpV),swSim::KC_OK);\n};\n\nTEST_F(KernelComposerTest,setSpM){\n    swSim::KernelComposer KC;\n    EXPECT_EQ(KC.setSparseMatrix(&SpM),swSim::KC_OK);\n};\n\nTEST_F(KernelComposerTest,setSpM2){\n    swSim::KernelComposer KC;\n    EXPECT_EQ(KC.setSparseMatrix(&SpM),swSim::KC_OK);\n    ASSERT_FALSE(KC.isCommitted());\n    ASSERT_EQ(KC.kernelCommit(),swSim::KC_OK);\n    ASSERT_TRUE(KC.isCommitted());\n    ASSERT_EQ(KC.kernelDecommit(),swSim::KC_OK);\n    ASSERT_FALSE(KC.isCommitted());\n};\n\nTEST_F(KernelComposerTest,Commit){\n    swSim::KernelComposer KC;\n    ASSERT_FALSE(KC.isCommitted());\n    ASSERT_EQ(KC.kernelCommit(),swSim::KC_OK);\n    ASSERT_TRUE(KC.isCommitted());\n    ASSERT_EQ(KC.kernelDecommit(),swSim::KC_OK);\n    ASSERT_FALSE(KC.isCommitted());\n};\n\nTEST_F(KernelComposerTest,SpMVstaging){\n    swSim::KernelComposer KC;\n    KC.setSparseMatrix(&SpM);\n    KC.setDenseVector(&DnV1);\n    KC.setDenseVector(&DnV2);\n   \n    //Configure test, ensure configuration is correct\n    ASSERT_FALSE(KC.isCommitted());\n    ASSERT_EQ(KC.setSPMV(SpM.getName(),DnV1.getName(),DnV2.getName(),1.0,1.0),\n              swSim::KC_OK);\n    ASSERT_EQ(KC.kernelCommit(),swSim::KC_OK);\n    ASSERT_TRUE(KC.isCommitted());\n    ASSERT_EQ(KC.run(1),swSim::KC_OK);\n    ASSERT_EQ(KC.kernelDecommit(),swSim::KC_OK);\n    ASSERT_FALSE(KC.isCommitted());\n};\n\nTEST_F(KernelComposerTest,SPMV){\n    swSim::KernelComposer KC;\n    KC.setSparseMatrix(&SpM);\n    KC.setDenseVector(&DnV1);\n    KC.setDenseVector(&DnV2);\n    \n    //Configure test, ensure configuration is correct\n    ASSERT_FALSE(KC.isCommitted());\n    ASSERT_EQ(KC.setSPMV(SpM.getName(),DnV1.getName(),DnV2.getName(),1.0,1.0),\n              swSim::KC_OK);\n    ASSERT_EQ(KC.kernelCommit(),swSim::KC_OK);\n    ASSERT_TRUE(KC.isCommitted());\n    ASSERT_EQ(KC.run(1),swSim::KC_OK);\n    ASSERT_EQ(KC.getDeviceData(DnV2.getName()),swSim::KC_OK);\n    ASSERT_EQ(KC.kernelDecommit(),swSim::KC_OK);\n    ASSERT_FALSE(KC.isCommitted());\n    \n    //test values\n    for(int k=0;k<Nv;k++){\n        EXPECT_FLOAT_EQ(DnV2.getValueArray()[k],10.0+((double)(k))*10.0);\n    };\n};\nTEST_F(KernelComposerTest,SPMV2){\n    swSim::KernelComposer KC;\n    KC.setSparseMatrix(&SpM);\n    KC.setDenseVector(&DnV1);\n    KC.setDenseVector(&DnV2);\n    \n    //Configure test, ensure configuration is correct\n    ASSERT_FALSE(KC.isCommitted());\n    ASSERT_EQ(KC.setSPMV(SpM.getName(),DnV1.getName(),DnV2.getName(),1.0,1.0),\n              swSim::KC_OK);\n    ASSERT_EQ(KC.kernelCommit(),swSim::KC_OK);\n    ASSERT_TRUE(KC.isCommitted());\n    ASSERT_EQ(KC.run(0,1),swSim::KC_OK);\n    ASSERT_EQ(KC.getDeviceData(DnV2.getName()),swSim::KC_OK);\n    ASSERT_EQ(KC.kernelDecommit(),swSim::KC_OK);\n    ASSERT_FALSE(KC.isCommitted());\n    \n    //test values\n    for(int k=0;k<Nv;k++){\n        EXPECT_FLOAT_EQ(DnV2.getValueArray()[k],10.0+((double)(k))*10.0);\n    };\n};\n\nTEST_F(KernelComposerTest,SPaXPY){\n    swSim::KernelComposer KC;\n    KC.setDenseVector(&DnV2);\n    KC.setSparseVector(&SpV);\n    \n    //Configure test, ensure configuration is correct\n    ASSERT_FALSE(KC.isCommitted());\n    ASSERT_EQ(KC.setSPaXPY(SpV.getName(),DnV2.getName(),&ft),\n              swSim::KC_OK);\n    ASSERT_EQ(KC.kernelCommit(),swSim::KC_OK);\n    ASSERT_TRUE(KC.isCommitted());\n    ASSERT_EQ(KC.run(1),swSim::KC_OK);\n    ASSERT_EQ(KC.getDeviceData(DnV2.getName()),swSim::KC_OK);\n    ASSERT_EQ(KC.kernelDecommit(),swSim::KC_OK);\n    ASSERT_FALSE(KC.isCommitted());\n    \n    //test values\n    for(int k=0;k<Nv;k++){\n        EXPECT_FLOAT_EQ(DnV2.getValueArray()[k],10.0\n                    +10.0*((double)((k>=(Nv/4)) && (k<(3*Nv/4)))));\n    };\n};\nTEST_F(KernelComposerTest,SPaXPY2){\n    swSim::KernelComposer KC;\n    KC.setDenseVector(&DnV2);\n    KC.setSparseVector(&SpV);\n    \n    //Configure test, ensure configuration is correct\n    ASSERT_FALSE(KC.isCommitted());\n    ASSERT_EQ(KC.setSPaXPY(SpV.getName(),DnV2.getName(),&ft),\n              swSim::KC_OK);\n    ASSERT_EQ(KC.kernelCommit(),swSim::KC_OK);\n    ASSERT_TRUE(KC.isCommitted());\n    ASSERT_EQ(KC.run(0,1),swSim::KC_OK);\n    ASSERT_EQ(KC.getDeviceData(DnV2.getName()),swSim::KC_OK);\n    ASSERT_EQ(KC.kernelDecommit(),swSim::KC_OK);\n    ASSERT_FALSE(KC.isCommitted());\n    \n    //test values\n    for(int k=0;k<Nv;k++){\n        EXPECT_FLOAT_EQ(DnV2.getValueArray()[k],10.0\n                    +10.0*((double)((k>=(Nv/4)) && (k<(3*Nv/4)))));\n    };\n};\n\nTEST_F(KernelComposerTest,AXPY){\n    swSim::KernelComposer KC;\n    KC.setDenseVector(&DnV1);\n    KC.setDenseVector(&DnV2);\n    \n    //Configure test, ensure configuration is correct\n    ASSERT_FALSE(KC.isCommitted());\n    ASSERT_EQ(KC.setAXPY(DnV1.getName(),DnV2.getName(),1.0),\n              swSim::KC_OK);\n    ASSERT_EQ(KC.kernelCommit(),swSim::KC_OK);\n    ASSERT_TRUE(KC.isCommitted());\n    ASSERT_EQ(KC.run(1),swSim::KC_OK);\n    ASSERT_EQ(KC.getDeviceData(DnV2.getName()),swSim::KC_OK);\n    ASSERT_EQ(KC.kernelDecommit(),swSim::KC_OK);\n    ASSERT_FALSE(KC.isCommitted());\n    \n    //test values\n    for(int k=0;k<Nv;k++){\n        EXPECT_FLOAT_EQ(DnV2.getValueArray()[k],10.0+10.0*((double)(k)));\n    };\n};\n\nTEST_F(KernelComposerTest,SPMVandSPaXPY){\n    swSim::KernelComposer KC;\n    KC.setSparseMatrix(&SpM);\n    KC.setDenseVector(&DnV1);\n    KC.setDenseVector(&DnV2);\n    KC.setSparseVector(&SpV);\n    \n    //Configure test, ensure configuration is correct\n    ASSERT_FALSE(KC.isCommitted());\n    ASSERT_EQ(KC.setSPMV(SpM.getName(),DnV1.getName(),DnV2.getName(),1.0,1.0),\n              swSim::KC_OK);\n    ASSERT_EQ(KC.setSPaXPY(SpV.getName(),DnV2.getName(),&ft),\n              swSim::KC_OK);\n    ASSERT_EQ(KC.kernelCommit(),swSim::KC_OK);\n    ASSERT_TRUE(KC.isCommitted());\n    ASSERT_EQ(KC.run(1),swSim::KC_OK);\n    ASSERT_EQ(KC.getDeviceData(DnV2.getName()),swSim::KC_OK);\n    ASSERT_EQ(KC.kernelDecommit(),swSim::KC_OK);\n    ASSERT_FALSE(KC.isCommitted());\n    \n    //test values\n    for(int k=0;k<Nv;k++){\n        EXPECT_FLOAT_EQ(DnV2.getValueArray()[k],10.0+((double)(k))*10.0\n                        +10.0*((double)((k>=(Nv/4)) && (k<(3*Nv/4)))));\n    };\n};\n\nTEST_F(KernelComposerTest,SPMVandSPaXPYandAXPY){\n    swSim::KernelComposer KC;\n    KC.setSparseMatrix(&SpM);\n    KC.setDenseVector(&DnV1);\n    KC.setDenseVector(&DnV2);\n    KC.setSparseVector(&SpV);\n    \n    //Configure test, ensure configuration is correct\n    ASSERT_FALSE(KC.isCommitted());\n    ASSERT_EQ(KC.setSPMV(SpM.getName(),DnV1.getName(),DnV2.getName(),1.0,1.0),\n              swSim::KC_OK);\n    ASSERT_EQ(KC.setSPaXPY(SpV.getName(),DnV2.getName(),&ft),\n              swSim::KC_OK);\n    ASSERT_EQ(KC.setAXPY(DnV1.getName(),DnV2.getName(),1.0),\n              swSim::KC_OK);\n    ASSERT_EQ(KC.kernelCommit(),swSim::KC_OK);\n    ASSERT_TRUE(KC.isCommitted());\n    ASSERT_EQ(KC.run(1),swSim::KC_OK);\n    ASSERT_EQ(KC.getDeviceData(DnV2.getName()),swSim::KC_OK);\n    ASSERT_EQ(KC.kernelDecommit(),swSim::KC_OK);\n    ASSERT_FALSE(KC.isCommitted());\n    \n    //test values\n    for(int k=0;k<Nv;k++){\n        EXPECT_FLOAT_EQ(DnV2.getValueArray()[k],10.0+((double)(k))*10.0\n                        +((double)(k))*10.0\n                        +10.0*((double)((k>=(Nv/4)) && (k<(3*Nv/4)))));\n    };\n};\n\nTEST_F(KernelComposerTest,updateSpVfromHost){\n    swSim::KernelComposer KC;\n    KC.setSparseMatrix(&SpM);\n    KC.setDenseVector(&DnV1);\n    KC.setDenseVector(&DnV2);\n    KC.setSparseVector(&SpV);\n    \n    //Configure test, ensure configuration is correct\n    ASSERT_FALSE(KC.isCommitted());\n    //ASSERT_EQ(KC.setUpdateSparseVectorFromHost(SpV.getName()),swSim::KC_OK);\n    ASSERT_EQ(KC.setSPaXPY(SpV.getName(),DnV2.getName(),&ft),\n              swSim::KC_OK);\n    ASSERT_EQ(KC.kernelCommit(),swSim::KC_OK);\n    ASSERT_TRUE(KC.isCommitted());\n    ASSERT_EQ(KC.run(1),swSim::KC_OK);\n    ASSERT_EQ(KC.getDeviceData(DnV2.getName()),swSim::KC_OK);\n    ASSERT_EQ(KC.kernelDecommit(),swSim::KC_OK);\n    ASSERT_FALSE(KC.isCommitted());\n    \n    //test values\n    for(int k=0;k<Nv;k++){\n        EXPECT_FLOAT_EQ(DnV2.getValueArray()[k],\n                10.0+(10.0)*(k>=Nv/4 && k<3*Nv/4));\n    };\n};\n\nTEST_F(KernelComposerTest,setDeviceData){\n    swSim::KernelComposer KC;\n    KC.setSparseMatrix(&SpM);\n    KC.setDenseVector(&DnV1);\n    KC.setDenseVector(&DnV2);\n    ASSERT_EQ(KC.setSPMV(SpM.getName(),DnV1.getName(),DnV2.getName(),1.0,1.0),\n              swSim::KC_OK);\n    \n    ASSERT_EQ(KC.kernelCommit(),swSim::KC_OK);\n    ASSERT_TRUE(KC.isCommitted());\n    for(int k=0;k<Nv;k++){\n        DnV1.getValueArray()[k]=1.0;\n    };\n    ASSERT_EQ(KC.setDeviceData(DnV1.getName()),swSim::KC_OK);\n    ASSERT_TRUE(KC.isCommitted());\n    ASSERT_EQ(KC.run(1),swSim::KC_OK);\n    ASSERT_EQ(KC.getDeviceData(DnV2.getName()),swSim::KC_OK);\n    ASSERT_EQ(KC.kernelDecommit(),swSim::KC_OK);\n    ASSERT_FALSE(KC.isCommitted());\n    \n    //test values\n    for(int k=0;k<Nv;k++){\n        EXPECT_FLOAT_EQ(DnV2.getValueArray()[k],11.0);\n    };\n};\n", "meta": {"hexsha": "3c1ff8ca07c9c159b9c3434ab09f4bec58f8c135", "size": 10914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/src/KernelComposerTest.cpp", "max_stars_repo_name": "nasa/swSim", "max_stars_repo_head_hexsha": "348ba39ea149711a2285916a2dcddc2c71da4859", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T09:49:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T09:54:54.000Z", "max_issues_repo_path": "testing/src/KernelComposerTest.cpp", "max_issues_repo_name": "ElsevierSoftwareX/SOFTX-D-21-00042", "max_issues_repo_head_hexsha": "348ba39ea149711a2285916a2dcddc2c71da4859", "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": "testing/src/KernelComposerTest.cpp", "max_forks_repo_name": "ElsevierSoftwareX/SOFTX-D-21-00042", "max_forks_repo_head_hexsha": "348ba39ea149711a2285916a2dcddc2c71da4859", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-04-27T09:52:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:22:16.000Z", "avg_line_length": 31.094017094, "max_line_length": 78, "alphanum_fraction": 0.6300164926, "num_tokens": 3387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.532807695020946}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu> Licensed\n * under the MIT license. See the license file LICENSE.\n */\n#pragma once\n\n#include <stdint.h>\n#include <string>\n#include <vector>\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/QR>\n#include <unsupported/Eigen/MatrixFunctions>\n\n// CUDA runtime\n#include <cuda_runtime.h>\n// Utilities and system includes\n//#include <mmf/defines.h>\n#include <nvidia/helper_cuda.h>\n\n#include <jsCore/clDataGpu.hpp>\n#include <jsCore/timer.hpp>\n\n#include <mmf/optimizationSO3.hpp>\n#include <manifold/SO3.h>\n\nusing namespace Eigen;\nusing namespace std;\n\nextern void directSquaredAngleCostFctGPU(float *h_cost, float *d_cost,\n    float *d_x, float* d_weights, uint32_t *d_z, float *d_mu,\n    int N);\n\nextern void directSquaredAngleCostFctAssignmentGPU(float *h_cost, float *d_cost,\n  uint32_t *h_W, uint32_t *d_W, float *d_x, float* d_weights, \n  uint32_t *d_z, float *d_mu, int N);\n\nextern void directSquaredAngleCostFctJacobianGPU(float *h_J, float *d_J,\n    float *d_x, float *d_weights, uint32_t *d_z, float *d_mu, int N);\n\nextern void meanInTpS2GPU(float *h_p, float *d_p, float *h_mu_karch,\n    float *d_mu_karch, float *d_q, uint32_t *d_z, float* d_weights, int N);\n\nextern void sufficientStatisticsOnTpS2GPU(float *h_p, float *d_p, float\n    *h_Rnorths, float *d_Rnorths, float *d_q, uint32_t *d_z ,int N, float\n    *h_SSs, float *d_SSs);\n\nextern void loadRGBvaluesForMFaxes();\n\nnamespace mmf{\n\n/// Implements Conjugate Gradient Optimization on SO3 using GPU\n/// optimizations\nclass OptSO3GD : public OptSO3\n{\npublic:\n  OptSO3GD(float *d_weights =NULL)\n    : OptSO3(1.,1.,1.,d_weights), thr_(1.e-6), c_(0.1), ddelta_(0.1), tauR_(1.)\n  {};\n\n  virtual ~OptSO3GD() {};\n\nprotected:\n  SO3f theta_;\n  SO3f thetaPrev_;\n  float thr_; // threshold for gradient descent\n  float c_;\n  float ddelta_;\n  float tauR_;\n\n  void ComputeJacobian(const SO3f& thetaPrev, const SO3f& theta,\n      uint32_t N, Eigen::Vector3f* J, float* f);\n  void LineSearch(uint32_t N, Eigen::Vector3f* J, float* f);\n\n  virtual float conjugateGradientPreparation_impl(Matrix3f& R, uint32_t& N);\n  virtual float conjugateGradientCUDA_impl(Matrix3f& R, float res0, uint32_t N, uint32_t maxIter=100);\n  virtual void conjugateGradientPostparation_impl(Matrix3f& R){;};\n  /* recompute assignment based on rotation R and return residual as well */\n  virtual float computeAssignment(Matrix3f& R, uint32_t& N);\n  /* mainly init GPU arrays */\n  virtual void init();\n};\n}\n", "meta": {"hexsha": "3e04f8550c456b0b2847be48cf1075eb1ccef7cf", "size": 2512, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mmf/optimizationSO3_gd.hpp", "max_stars_repo_name": "jstraub/mmf", "max_stars_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-06-02T04:17:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T05:44:53.000Z", "max_issues_repo_path": "include/mmf/optimizationSO3_gd.hpp", "max_issues_repo_name": "jstraub/mmf", "max_issues_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "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/mmf/optimizationSO3_gd.hpp", "max_forks_repo_name": "jstraub/mmf", "max_forks_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-06T04:34:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-28T06:35:00.000Z", "avg_line_length": 29.9047619048, "max_line_length": 102, "alphanum_fraction": 0.7332802548, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5327889241408644}}
{"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__TN_HPP_\n#define SMOOTH__INTERNAL__TN_HPP_\n\n#include <Eigen/Core>\n\n#include \"common.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief T(n) Lie Group represented as R^n\n *\n * Memory layout\n * -------------\n * Group:    x1 x2 ... xn\n * Tangent:  v1 v2 ... vn\n *\n * Lie group Matrix form\n * ---------------------\n * [ I T ]\n * [ 0 1 ]\n *\n * where T = [x1 ... xn]'\n *\n * Lie algebra Matrix form\n * -----------------------\n * [ 0 V ]\n * [ 0 0 ]\n *\n * where V = [v1 ... vn]'\n */\ntemplate<int N, typename _Scalar>\nstruct TnImpl\n{\n  using Scalar = _Scalar;\n\n  static constexpr Eigen::Index Dim     = N + 1;\n  static constexpr Eigen::Index Dof     = N;\n  static constexpr Eigen::Index RepSize = N;\n  static constexpr bool IsCommutative   = true;\n\n  SMOOTH_DEFINE_REFS;\n\n  static void setIdentity(GRefOut g_out) { g_out.setZero(); }\n\n  static void setRandom(GRefOut g_out) { g_out.setRandom(); }\n\n  static void matrix(GRefIn g_in, MRefOut m_out)\n  {\n    m_out.setIdentity();\n    m_out.template topRightCorner<Dof, 1>() = g_in;\n  }\n  static void composition(GRefIn g_in1, GRefIn g_in2, GRefOut g_out) { g_out = g_in1 + g_in2; }\n\n  static void inverse(GRefIn g_in, GRefOut g_out) { g_out = -g_in; }\n\n  static void log(GRefIn g_in, TRefOut a_out) { a_out = g_in; }\n\n  static void exp(TRefIn a_in, GRefOut g_out) { g_out = a_in; }\n\n  static void hat(TRefIn a_in, MRefOut A_out)\n  {\n    A_out.setZero();\n    A_out.template topRightCorner<N, 1>() = a_in;\n  }\n\n  static void vee(MRefIn A_in, TRefOut a_out) { a_out = A_in.template topRightCorner<N, 1>(); }\n\n  static void ad(TRefIn, TMapRefOut A_out) { A_out.setZero(); }\n};\n\n}  // namespace smooth\n\n#endif  // SMOOTH__INTERNAL__TN_HPP_\n", "meta": {"hexsha": "60b93b164e3f4cf7cdf7cae1b4879ada084b53e3", "size": 2947, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/internal/tn.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/tn.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/tn.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": 29.47, "max_line_length": 95, "alphanum_fraction": 0.687478792, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5327889231242285}}
{"text": "// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n// Copyright (c) 2018 Pierre MOULON.\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 http://mozilla.org/MPL/2.0/.\n\n#ifndef OPENMVG_SFM_STELLAR_STELLAR_DEFINITIONS_HPP\n#define OPENMVG_SFM_STELLAR_STELLAR_DEFINITIONS_HPP\n\n#include \"openMVG/sfm/pipelines/stellar/relative_scale.hpp\"\n#include \"openMVG/numeric/l1_solver_admm.hpp\"\n\n#include <Eigen/Sparse>\n\nnamespace openMVG{\nnamespace sfm{\n\n/// Mode that can be used to solve to rescale the relative translation of a stellar pod\nenum class Stellar_Translation_Averaging_Solver_Type\n{\n  SCALING_SOLVER_L1,\n  SCALING_SOLVER_L2,\n  SCALING_SOLVER_L2_FULL\n};\n\n/// Check if a stellar pod defined by some relative scale is one CC or not\ninline bool Relative_scales_are_one_cc\n(\n  const std::vector<Relative_Scale> & relative_scales\n)\n{\n  // Iterate along the pairs:\n  // - check if everytime at least one of the pair id was listed before\n  std::set<uint32_t> previous_ids;\n  const Pair_Set used_pairs = Relative_Scale::Get_pairs(relative_scales);\n  for (const Pair & pair_it : used_pairs)\n  {\n    if (previous_ids.empty())\n    {\n      previous_ids = {pair_it.first, pair_it.second};\n    }\n    else\n      if (previous_ids.count(pair_it.first) == 0 &&\n          previous_ids.count(pair_it.second) == 0)\n        return false;\n  }\n  return !relative_scales.empty();\n}\n\n/// Solve the relative scale to a common coordinate system\n/// Since ratios of depth are used, the found solution is an approximation\n/// Solving equation (4) from \u201cGlobal Structure-from-Motion by Similarity Averaging\"\n/// Zhaopeng Cui and Ping Tan. (ICCV 2015).\u201d\n///\ninline\nbool\nSolve_stellar_translation_scales_averaging\n(\n  const size_t node_id, // Central node\n  const std::vector<Relative_Scale> & vec_relative_scales,\n  const Hash_Map<Pair, geometry::Pose3> & relative_poses,\n  Hash_Map<IndexT, geometry::Pose3> & triplet_pose,\n  const Stellar_Translation_Averaging_Solver_Type e_used_solver =\n    Stellar_Translation_Averaging_Solver_Type::SCALING_SOLVER_L2_FULL\n)\n{\n  const Pair_Set used_pairs = Relative_Scale::Get_pairs(vec_relative_scales);\n  std::cout << \"Stellar reconstruction with center node: \" << node_id << \"\\n\"\n    << \"#relative scales: \" << vec_relative_scales.size() << \"\\n\"\n    << \"#pairs : \" << used_pairs.size() << std::endl;\n\n  // Assert that the relative scales pose ids defined a unique connected component\n  if (!Relative_scales_are_one_cc(vec_relative_scales))\n  {\n    std::cerr << \"The stellar edges are not giving a single connected component.\" << std::endl;\n    return false;\n  }\n\n  // Compute a contiguous indexes mapping\n  std::map<Pair, unsigned int> pair_to_index;\n  {\n    unsigned int i = 0;\n    for (const Pair & pair_it: used_pairs)\n    {\n      pair_to_index[pair_it] = i++;\n    }\n  }\n\n  // Solve the scale to put all the pair in a common global coordinate system\n  Vec x_scales;\n  switch (e_used_solver)\n  {\n    case Stellar_Translation_Averaging_Solver_Type::SCALING_SOLVER_L2_FULL:\n    {\n      // Setup the linear system: lhx X = rhs\n      std::vector< Eigen::Triplet<double> > vec_triplets;\n      Vec rhs(vec_relative_scales.size());\n      unsigned int i = 0;\n      for (const Relative_Scale & relative_scales : vec_relative_scales)\n      {\n        // Write:\n        // S_ij / S_il = factor_ijl\n        // as the following linear constraint:\n        // S_ij - S_il = log(factor_ijl)\n        vec_triplets.emplace_back(i, pair_to_index.at(relative_scales.pairs[0]), 1); // row, col, value\n        vec_triplets.emplace_back(i, pair_to_index.at(relative_scales.pairs[1]), -1);\n        rhs[i] = std::log(relative_scales.ratio);\n        ++i;\n      }\n\n      sMat lhs;\n      lhs.resize(vec_relative_scales.size(), pair_to_index.size());\n      lhs.setFromTriplets(vec_triplets.cbegin(), vec_triplets.cend());\n\n      // Use QR\n      Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int> > solver(lhs);\n      if (solver.info() != Eigen::Success)\n      {\n        std::cerr << \"Sparse matrix cannot be factorized\" << std::endl;\n        return false;\n      }\n      const Vec x = solver.solve(rhs);\n      if (solver.info() != Eigen::Success)\n      {\n        std::cerr << \"Sparse system cannot be solved\" << std::endl;\n        return false;\n      }\n\n      // Make the log of the distances negative, such that all distances are <= 1\n      const double maxLogDistance = x.maxCoeff();\n      x_scales = (x.array() - maxLogDistance).array().exp();\n    }\n    break;\n\n    case Stellar_Translation_Averaging_Solver_Type::SCALING_SOLVER_L2:\n    {\n      // Setup the linear system: lhx X = rhs\n      std::vector< Eigen::Triplet<double> > vec_triplets;\n      Vec rhs(vec_relative_scales.size());\n      unsigned int i = 0;\n      for (const Relative_Scale & relative_scales : vec_relative_scales)\n      {\n        // Write:\n        // S_ij / S_il = factor_ijl\n        // as the following linear constraint:\n        // S_ij - S_il = log(factor_ijl)\n        if (pair_to_index[relative_scales.pairs[0]]!=0)\n          vec_triplets.emplace_back(i, pair_to_index.at(relative_scales.pairs[0])-1, 1); // row, col, value\n        if (pair_to_index[relative_scales.pairs[1]]!=0)\n          vec_triplets.emplace_back(i, pair_to_index.at(relative_scales.pairs[1])-1, -1);\n        rhs[i] = std::log(relative_scales.ratio);\n        ++i;\n      }\n\n      sMat lhs;\n      lhs.resize(vec_relative_scales.size(), pair_to_index.size()-1);\n      lhs.setFromTriplets(vec_triplets.cbegin(), vec_triplets.cend());\n\n      // Use QR\n      Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int> > solver(lhs);\n      if (solver.info() != Eigen::Success)\n      {\n        std::cerr << \"Sparse matrix cannot be factorized\" << std::endl;\n        return false;\n      }\n      const Vec x = solver.solve(rhs);\n      if (solver.info() != Eigen::Success)\n      {\n        std::cerr << \"Sparse system cannot be solved\" << std::endl;\n        return false;\n      }\n\n      // Make the log of the distances negative, such that all distances are <= 1\n      Vec xCpy(x.size()+1);\n      xCpy << 0.0, x;\n      const double maxLogDistance = xCpy.maxCoeff();\n      x_scales = (xCpy.array() - maxLogDistance).array().exp();\n    }\n      break;\n\n    case Stellar_Translation_Averaging_Solver_Type::SCALING_SOLVER_L1:\n    {\n      // Setup the linear system: lhx X = rhs\n      std::vector< Eigen::Triplet<double> > vec_triplets;\n      Vec rhs(vec_relative_scales.size());\n      unsigned int i = 0;\n      for (const Relative_Scale & relative_scales : vec_relative_scales)\n      {\n        // Write:\n        // S_ij / S_il = factor_ijl\n        // as the following linear constraint:\n        // S_ij - S_il = log(factor_ijl)\n        if (pair_to_index[relative_scales.pairs[0]]!=0)\n          vec_triplets.emplace_back(i, pair_to_index.at(relative_scales.pairs[0])-1, 1); // row, col, value\n        if (pair_to_index[relative_scales.pairs[1]]!=0)\n          vec_triplets.emplace_back(i, pair_to_index.at(relative_scales.pairs[1])-1, -1);\n        rhs[i] = std::log(relative_scales.ratio);\n        ++i;\n      }\n\n      sMat lhs;\n      lhs.resize(vec_relative_scales.size(), pair_to_index.size()-1);\n      lhs.setFromTriplets(vec_triplets.cbegin(), vec_triplets.cend());\n\n      // Try to solve under L1 norm\n      openMVG::L1Solver<sMat>::Options opt;\n      openMVG::L1Solver<sMat> l1solver(opt, lhs);\n\n      Vec l1solution_vec(pair_to_index.size());\n      l1solution_vec.setZero();\n      if (l1solver.Solve(rhs, &l1solution_vec))\n      {\n        // Make the log of the distances negative, such that all distances are <= 1\n        Vec x(l1solution_vec.size()+1);\n        x << 0.0, l1solution_vec;\n        const double maxLogDistance = x.maxCoeff();\n        x_scales = (x.array() - maxLogDistance).array().exp();\n      }\n      else\n      {\n        std::cerr << \"Sparse system cannot be solved\" << std::endl;\n        return false;\n      }\n    }\n    break;\n    default:\n      std::cerr << \"Unsupported solver\" << std::endl;\n      return false;\n  }\n\n  if (x_scales.size() == 0)\n  {\n    return false;\n  }\n\n  // Upgrade the found stellar reconstruction\n  triplet_pose.clear();\n  triplet_pose[node_id] = geometry::Pose3(); // Identity\n\n  std::set<unsigned int> stellar_ids;\n  for (unsigned int i = 0 ; i < x_scales.size(); ++i)\n  {\n    // Retrieve the original pair (inverse mapping)\n    Pair selected_pair;\n    for (const Pair & pair_it: used_pairs)\n    {\n      if (pair_to_index[pair_it] == i)\n      {\n        selected_pair = pair_it;\n        break;\n      }\n    }\n    std::cout << \"Pair: \" << selected_pair.first << \",\" << selected_pair.second << \"; scaling: \" << x_scales[i] << std::endl;\n    stellar_ids.insert(selected_pair.first);\n    stellar_ids.insert(selected_pair.second);\n\n    if (relative_poses.count(selected_pair) == 0)\n    {\n      return false;\n    }\n\n    if (selected_pair.first == node_id)\n    {\n      geometry::Pose3 relative_pose = relative_poses.at(selected_pair);\n      relative_pose.center() /= x_scales[i];\n      triplet_pose[selected_pair.second] = relative_pose;\n    }\n    else\n    {\n      geometry::Pose3 relative_pose = relative_poses.at(selected_pair).inverse();\n      relative_pose.center() /= x_scales[i];\n      triplet_pose[selected_pair.first] = relative_pose;\n    }\n  }\n  return true;\n}\n\n} // namespace sfm\n} // namespace openMVG\n\n\n#endif // OPENMVG_SFM_STELLAR_STELLAR_DEFINITIONS_HPP\n", "meta": {"hexsha": "951de54bedf0953f59643ed65b1a537a5d7de7cb", "size": 9500, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/sfm/pipelines/stellar/stellar_definitions.hpp", "max_stars_repo_name": "Aurelio93/satellite-pose-estimation", "max_stars_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2019-05-19T03:48:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:20:49.000Z", "max_issues_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/sfm/pipelines/stellar/stellar_definitions.hpp", "max_issues_repo_name": "Aurelio93/satellite-pose-estimation", "max_issues_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-05-22T07:45:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T01:48:26.000Z", "max_forks_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/sfm/pipelines/stellar/stellar_definitions.hpp", "max_forks_repo_name": "Aurelio93/satellite-pose-estimation", "max_forks_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-05-19T03:48:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-29T18:19:16.000Z", "avg_line_length": 33.3333333333, "max_line_length": 125, "alphanum_fraction": 0.6548421053, "num_tokens": 2500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.5327889231242285}}
{"text": "/**\n * \\ file TanFilter.cpp\n */\n\n#include <array>\n#include <fstream>\n\n#include <ATK/config.h>\n\n#include <ATK/Tools/TanFilter.h>\n#include <ATK/Mock/SimpleSinusGeneratorFilter.h>\n\n#include <boost/math/constants/constants.hpp>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\nconstexpr gsl::index PROCESSSIZE = 1000;\nconstexpr gsl::index SAMPLING_RATE = 1024*64;\n\nBOOST_AUTO_TEST_CASE( TanFilter_const_sin1k )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(SAMPLING_RATE);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::TanFilter<double> filter;\n  filter.set_input_sampling_rate(SAMPLING_RATE);\n  filter.set_output_sampling_rate(SAMPLING_RATE);\n  \n  filter.set_input_port(0, generator, 0);\n  filter.process(PROCESSSIZE);\n  \n  auto sin = generator.get_output_array(0);\n  auto array = filter.get_output_array(0);\n  \n  for(size_t i = 0; i < PROCESSSIZE; ++i)\n  {\n    BOOST_CHECK_CLOSE(array[i], std::tan(sin[i] * boost::math::constants::pi<double>() / SAMPLING_RATE), 0.00001);\n  }\n}\n", "meta": {"hexsha": "ac9918c85f285686c494b8ef04ababfd43d4e3a2", "size": 1093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Tools/TanFilter.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": "tests/Tools/TanFilter.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": "tests/Tools/TanFilter.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.8409090909, "max_line_length": 114, "alphanum_fraction": 0.7483989021, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5327889188281372}}
{"text": "//#include \"ps/ps.h\"\n#include <iostream>\n#include <vector>\n#include \"softmax.h\"\n#include \"prox_l1.h\"\n#include \"prox_l2.h\"\n\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::VectorXi;\nusing Eigen::ArrayXd;\n\nusing namespace std;\n//using namespace ps;\n\nint main() {\n  MatrixXd X(3, 4);\n  VectorXi y(3);\n  vector<double> a = {1, -1, 1};\n  X << 1,2,3,4,5,6,7,8,9,10,11,12;\n  X = X / 10;\n  for (int i = 0; i < a.size(); i++) {\n    y(i) = a[i];\n  }\n  cout << X << endl;\n  cout << y << endl;\n\n  // test data copy\n  vector<double> vecx(X.rows()*X.cols());\n  for (int i = 0; i < X.cols(); i++) {\n    VectorXd::Map(&vecx[i*X.rows()], X.rows()) = X.col(i);\n  }\n  cout << \"---------\" << endl;\n  for (int i = 0; i < vecx.size(); i++) {\n    cout << vecx[i] << \" \";\n  }\n  cout << endl;\n\n  // test data copy back\n  cout << \"---------\" << endl;\n  for (int i = 0; i < vecx.size(); i++) {\n    vecx[i] = vecx[i] * 2;\n  }\n  for (int i = 0; i < X.cols(); i++) {\n    X.col(i) = VectorXd::Map(&vecx[i*X.rows()], X.rows());\n  }\n  cout << X << endl;\n\n  // test replicate\n  cout << \"---------\" << endl;\n  cout << X.rowwise().sum() << endl;\n  cout << X.rowwise().sum().replicate(1, X.cols()) << endl;\n\n  // test transpose\n  cout << \"---------\" << endl;\n  cout << X.transpose() << endl;\n  cout << \"---------\" << endl;\n  cout << X << endl;\n\n  // test softmax\n  lrprox::SOFTMAX softmax = lrprox::SOFTMAX(4, 2);\n  // one-hot\n  MatrixXi y_onehot = softmax.onehot_encoder(y);\n//  y_onehot << 0, 1, 0, 1, 0, 1;\n//  y_onehot.transposeInPlace();\n  cout << \"---------\" << endl;\n  X << 1,2,3,4,5,6,7,8,9,10,11,12;\n  X = X / 10;\n  cout << X << endl;\n  cout << y_onehot << endl;\n  for (int i = 1; i <= 3; i++) {\n    cout << \"--\" << endl;\n    MatrixXd w(4, 2);\n    w.col(0) << 1, 2, 3, 4;\n    w.col(1) << 5, 6, 7, 8;\n    w = (-w.eval().array()/10 *i).matrix();\n    softmax.updateWeight(w);\n    cout << softmax.getWeight() << endl;\n    cout << softmax.cost(X, y_onehot) << endl;\n    cout << softmax.grad(X, y_onehot) << endl;\n  }\n\n  // test proximal\n  lrprox::prox_l1 prox_op1 = lrprox::prox_l1(0.1);\n  lrprox::prox_l2 prox_op2 = lrprox::prox_l2(0.1);\n  double gamma = 0.3;\n  cout << \"---------\" << endl;\n  VectorXd x(Eigen::Map<VectorXd>(X.data(), X.cols()*X.rows()));\n  cout << prox_op1.cost(X) << endl;\n  cout << prox_op1.cost(x) << endl;\n  cout << prox_op1.proximal(X, gamma) << endl;\n  cout << prox_op1.proximal(x, gamma) << endl;\n  cout << prox_op2.cost(X) << endl;\n  cout << prox_op2.cost(x) << endl;\n  cout << prox_op2.proximal(X, gamma) << endl;\n  cout << prox_op2.proximal(x, gamma) << endl;\n\n  // test outputWeight\n  vector<double> w_vec;\n  cout << \"---------\" << endl;\n  softmax.outputWeight(*(&w_vec));\n  cout << softmax.getWeight() << endl;\n  for (int i = 0; i < w_vec.size(); i++) {\n    cout << w_vec[i] << \" \";\n  }\n  cout << endl;\n  w_vec[2] = 100;\n  softmax.updateWeight(w_vec);\n  cout << softmax.getWeight() << endl;\n  for (int i = 0; i < w_vec.size(); i++) {\n    cout << w_vec[i] << \" \";\n  }\n  cout << endl;\n  MatrixXd xtmp = softmax.getWeight();\n  xtmp.data()[0] = -100;\n  for (int i = 0; i < w_vec.size(); i++) {\n    cout << xtmp.data()[i] << \" \";\n  }\n  cout << endl;\n\n  return 0;\n}", "meta": {"hexsha": "d6ce599301fc4f694c6aa95a035a5ac3159ff1ec", "size": 3192, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/LR_proximal/main/test_softmax.cc", "max_stars_repo_name": "xcgoner/ps-lite-new", "max_stars_repo_head_hexsha": "39754e97b4b23dc6f90ab6fc22b3e1a918f48093", "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/LR_proximal/main/test_softmax.cc", "max_issues_repo_name": "xcgoner/ps-lite-new", "max_issues_repo_head_hexsha": "39754e97b4b23dc6f90ab6fc22b3e1a918f48093", "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/LR_proximal/main/test_softmax.cc", "max_forks_repo_name": "xcgoner/ps-lite-new", "max_forks_repo_head_hexsha": "39754e97b4b23dc6f90ab6fc22b3e1a918f48093", "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.7419354839, "max_line_length": 64, "alphanum_fraction": 0.5253759398, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5327889188281371}}
{"text": "//  ================================================================\n//  Created by Gregory Kramida on 11/2/18.\n//  Copyright (c) 2018 Gregory Kramida\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#pragma once\n\n//stdlib\n#include <vector>\n\n//libraries\n#include <Eigen/Eigen>\n#include <boost/property_tree/ptree.hpp>\n\n//local\n#include \"../../math/stacking.hpp\"\n#include \"../../math/typedefs.hpp\"\n#include \"../../telemetry/convergence_report.hpp\"\n#include \"optimizer2d.hpp\"\n\nnamespace pt = boost::property_tree;\nnamespace eig = Eigen;\n\nnamespace nonrigid_optimization {\nnamespace slavcheva{\nclass SobolevOptimizer2d:\n\t\tpublic Optimizer2d {\npublic:\n\tclass SobolevParameters {\n\tpublic:\n\t\tstatic SobolevParameters& get_instance() {\n\t\t\tstatic SobolevParameters instance;\n\t\t\treturn instance;\n\t\t}\n\n\t\tSobolevParameters(const SobolevParameters&) = delete;\n\t\tvoid operator=(SobolevParameters const&) = delete;\n\n\t\tvoid set_from_json(pt::ptree root);\n\n\t\teig::VectorXf sobolev_kernel = [] {\n\t\t\teig::VectorXf sobolev_kernel(7);\n\t\t\tsobolev_kernel << 2.995900285895913839e-04f,\n\t\t\t4.410949535667896271e-03f,\n\t\t\t6.571318954229354858e-02f,\n\t\t\t9.956527948379516602e-01f,\n\t\t\t6.571318954229354858e-02f,\n\t\t\t4.410949535667896271e-03f,\n\t\t\t2.995900285895913839e-04f;\n\t\t\treturn sobolev_kernel;\n\t\t}();\n\n\t\teig::VectorXf get_sobolev_kernel();\n\t\tvoid set_sobolev_kernel(eig::VectorXf);\n\n\t\tfloat smoothing_term_weight = 0.2f;\n\n\tprivate:\n\t\tSobolevParameters() = default;\n\t};\n\n\t// *** parameters ***\n\tstatic SobolevParameters& sobolev_parameters();\n\tstatic SharedParameters& shared_parameters();\n\n\tvirtual eig::MatrixXf optimize(const eig::MatrixXf& live_field, const eig::MatrixXf& canonical_field) override;\n\ttelemetry::ConvergenceReport2d get_convergence_report();\n\teig::MatrixXf get_warp_statistics_as_matrix();\n\nprivate:\n\tfloat perform_optimization_iteration_and_return_max_warp(eig::MatrixXf& warped_live_field,\n\t\t\tmath::Vector2i& max_warp_location, const eig::MatrixXf& canonical_field, math::MatrixXv2f& warp_field);\n\t// *** Logging ***\n\ttelemetry::ConvergenceReport2d convergence_report;\n\tstd::vector<telemetry::WarpDeltaStatistics2d> warp_statistics;\n\n\tvoid clean_out_logs();\n};\n} //namespace slavcheva\n} //namespace nonrigid_optimization\n", "meta": {"hexsha": "c90af574ae61b3429fe0587155480b72660b5a32", "size": 2793, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/nonrigid_optimization/slavcheva/sobolev_optimizer2d.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/nonrigid_optimization/slavcheva/sobolev_optimizer2d.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/nonrigid_optimization/slavcheva/sobolev_optimizer2d.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": 30.6923076923, "max_line_length": 112, "alphanum_fraction": 0.7218045113, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5327889178115013}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, 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\n#include <geometry_test_common.hpp>\n\n#include <boost/concept/requires.hpp>\n#include <boost/concept_check.hpp>\n\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/strategies/spherical/distance_haversine.hpp>\n#include <boost/geometry/strategies/concepts/distance_concept.hpp>\n\n\n#include <boost/geometry/geometries/point.hpp>\n\n#ifdef HAVE_TTMATH\n#  include <boost/geometry/extensions/contrib/ttmath_stub.hpp>\n#endif\n\n\n\ndouble const average_earth_radius = 6372795.0;\n\n\ntemplate <typename Point, typename LatitudePolicy>\nstruct test_distance\n{\n    typedef bg::strategy::distance::haversine<double> haversine_type;\n    typedef typename bg::strategy::distance::services::return_type<haversine_type, Point, Point>::type return_type;\n\n    BOOST_CONCEPT_ASSERT\n        (\n            (bg::concept::PointDistanceStrategy<haversine_type, Point, Point>)\n        );\n\n\n    static void test(double lon1, double lat1, double lon2, double lat2,\n                       double radius, double expected, double tolerance)\n    {\n        haversine_type strategy(radius);\n\n        Point p1, p2;\n        bg::assign_values(p1, lon1, LatitudePolicy::apply(lat1));\n        bg::assign_values(p2, lon2, LatitudePolicy::apply(lat2));\n        return_type d = strategy.apply(p1, p2);\n\n        BOOST_CHECK_CLOSE(d, expected, tolerance);\n    }\n};\n\ntemplate <typename Point, typename LatitudePolicy>\nvoid test_all()\n{\n    // earth to unit-sphere -> divide by earth circumference, then it is from 0-1,\n    // then multiply with 2 PI, so effectively just divide by earth radius\n    double e2u = 1.0 / average_earth_radius;\n\n    // ~ Amsterdam/Paris, 467 kilometers\n    double const a_p = 467.2704 * 1000.0;\n    test_distance<Point, LatitudePolicy>::test(4, 52, 2, 48, average_earth_radius, a_p, 1.0);\n    test_distance<Point, LatitudePolicy>::test(2, 48, 4, 52, average_earth_radius, a_p, 1.0);\n    test_distance<Point, LatitudePolicy>::test(4, 52, 2, 48, 1.0, a_p * e2u, 0.001);\n\n    // ~ Amsterdam/Barcelona\n    double const a_b = 1232.9065 * 1000.0;\n    test_distance<Point, LatitudePolicy>::test(4, 52, 2, 41, average_earth_radius, a_b, 1.0);\n    test_distance<Point, LatitudePolicy>::test(2, 41, 4, 52, average_earth_radius, a_b, 1.0);\n    test_distance<Point, LatitudePolicy>::test(4, 52, 2, 41, 1.0, a_b * e2u, 0.001);\n}\n\n\ntemplate <typename P1, typename P2, typename CalculationType, typename LatitudePolicy>\nvoid test_services()\n{\n    namespace bgsd = bg::strategy::distance;\n    namespace services = bg::strategy::distance::services;\n\n    {\n\n        // Compile-check if there is a strategy for this type\n        typedef typename services::default_strategy<bg::point_tag, P1, P2>::type haversine_strategy_type;\n    }\n\n    P1 p1;\n    bg::assign_values(p1, 4, 52);\n\n    P2 p2;\n    bg::assign_values(p2, 2, 48);\n\n    // ~ Amsterdam/Paris, 467 kilometers\n    double const km = 1000.0;\n    double const a_p = 467.2704 * km;\n    double const expected = a_p;\n\n    double const expected_lower = 460.0 * km;\n    double const expected_higher = 470.0 * km;\n\n    // 1: normal, calculate distance:\n\n    typedef bgsd::haversine<double, CalculationType> strategy_type;\n    typedef typename bgsd::services::return_type<strategy_type, P1, P2>::type return_type;\n\n    strategy_type strategy(average_earth_radius);\n    return_type result = strategy.apply(p1, p2);\n    BOOST_CHECK_CLOSE(result, return_type(expected), 0.001);\n\n    // 2: the strategy should return the same result if we reverse parameters\n    result = strategy.apply(p2, p1);\n    BOOST_CHECK_CLOSE(result, return_type(expected), 0.001);\n\n\n    // 3: \"comparable\" to construct a \"comparable strategy\" for P1/P2\n    //    a \"comparable strategy\" is a strategy which does not calculate the exact distance, but\n    //    which returns results which can be mutually compared (e.g. avoid sqrt)\n\n    // 3a: \"comparable_type\"\n    typedef typename services::comparable_type<strategy_type>::type comparable_type;\n\n    // 3b: \"get_comparable\"\n    comparable_type comparable = bgsd::services::get_comparable<strategy_type>::apply(strategy);\n\n    // Check vice versa:\n    // First the result of the comparable strategy\n    return_type c_result = comparable.apply(p1, p2);\n    // Second the comparable result of the expected distance\n    return_type c_expected = services::result_from_distance<comparable_type, P1, P2>::apply(comparable, expected);\n    // And that one should be equa.\n    BOOST_CHECK_CLOSE(c_result, return_type(c_expected), 0.001);\n\n    // 4: the comparable_type should have a distance_strategy_constructor as well,\n    //    knowing how to compare something with a fixed distance\n    return_type c_dist_lower = services::result_from_distance<comparable_type, P1, P2>::apply(comparable, expected_lower);\n    return_type c_dist_higher = services::result_from_distance<comparable_type, P1, P2>::apply(comparable, expected_higher);\n\n    // If this is the case:\n    BOOST_CHECK(c_dist_lower < c_result && c_result < c_dist_higher);\n\n    // Calculate the Haversine by hand here:\n    return_type c_check = return_type(2.0) * asin(sqrt(c_result)) * average_earth_radius;\n    BOOST_CHECK_CLOSE(c_check, expected, 0.001);\n\n    // This should also be the case\n    return_type dist_lower = services::result_from_distance<strategy_type, P1, P2>::apply(strategy, expected_lower);\n    return_type dist_higher = services::result_from_distance<strategy_type, P1, P2>::apply(strategy, expected_higher);\n    BOOST_CHECK(dist_lower < result && result < dist_higher);\n}\n\n/****\ntemplate <typename P, typename Strategy>\nvoid time_compare_s(int const n)\n{\n    boost::timer t;\n    P p1, p2;\n    bg::assign_values(p1, 1, 1);\n    bg::assign_values(p2, 2, 2);\n    Strategy strategy;\n    typename Strategy::return_type s = 0;\n    for (int i = 0; i < n; i++)\n    {\n        for (int j = 0; j < n; j++)\n        {\n            s += strategy.apply(p1, p2);\n        }\n    }\n    std::cout << \"s: \" << s << \" t: \" << t.elapsed() << std::endl;\n}\n\ntemplate <typename P>\nvoid time_compare(int const n)\n{\n    time_compare_s<P, bg::strategy::distance::haversine<double> >(n);\n    time_compare_s<P, bg::strategy::distance::comparable::haversine<double> >(n);\n}\n\n#include <time.h>\ndouble time_sqrt(int n)\n{\n    clock_t start = clock();\n\n    double v = 2.0;\n    double s = 0.0;\n    for (int i = 0; i < n; i++)\n    {\n        for (int j = 0; j < n; j++)\n        {\n            s += sqrt(v);\n            v += 1.0e-10;\n        }\n    }\n    clock_t end = clock();\n    double diff = double(end - start) / CLOCKS_PER_SEC;\n\n    std::cout << \"Check: \" << s << \" Time: \" << diff << std::endl;\n    return diff;\n}\n\ndouble time_normal(int n)\n{\n    clock_t start = clock();\n\n    double v = 2.0;\n    double s = 0.0;\n    for (int i = 0; i < n; i++)\n    {\n        for (int j = 0; j < n; j++)\n        {\n            s += v;\n            v += 1.0e-10;\n        }\n    }\n    clock_t end = clock();\n    double diff = double(end - start) / CLOCKS_PER_SEC;\n\n    std::cout << \"Check: \" << s << \" Time: \" << diff << std::endl;\n    return diff;\n}\n***/\n\nint test_main(int, char* [])\n{\n    test_all<bg::model::point<int, 2, bg::cs::spherical_equatorial<bg::degree> >, geographic_policy>();\n    test_all<bg::model::point<float, 2, bg::cs::spherical_equatorial<bg::degree> >, geographic_policy>();\n    test_all<bg::model::point<double, 2, bg::cs::spherical_equatorial<bg::degree> >, geographic_policy>();\n\n    // NYI: haversine for mathematical spherical coordinate systems\n    // test_all<bg::model::point<double, 2, bg::cs::spherical<bg::degree> >, mathematical_policy>();\n\n    //double t1 = time_sqrt(20000);\n    //double t2 = time_normal(20000);\n    //std::cout << \"Factor: \" << (t1 / t2) << std::endl;\n    //time_compare<bg::model::point<double, 2, bg::cs::spherical<bg::radian> > >(10000);\n\n#if defined(HAVE_TTMATH)\n    typedef ttmath::Big<1,4> tt;\n    test_all<bg::model::point<tt, 2, bg::cs::spherical_equatorial<bg::degree> >, geographic_policy>();\n#endif\n\n\n    test_services\n        <\n            bg::model::point<double, 2, bg::cs::spherical_equatorial<bg::degree> >,\n            bg::model::point<double, 2, bg::cs::spherical_equatorial<bg::degree> >,\n            double, \n            geographic_policy \n        >();\n\n    return 0;\n}\n", "meta": {"hexsha": "b95ed9a0fb2891b5bbac7d2293cc6d90ad0a27d6", "size": 8798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/strategies/haversine.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.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": "libs/geometry/test/strategies/haversine.cpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.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": "libs/geometry/test/strategies/haversine.cpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-17T15:37:11.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-10T14:06:31.000Z", "avg_line_length": 33.7088122605, "max_line_length": 124, "alphanum_fraction": 0.6670834281, "num_tokens": 2467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.5327889124987742}}
{"text": "/*\n *  Simulate the real boundary of the region of attraction (ROA) \n *  for the reversed VDP example.\n *\n *  Created by Yinan Li on May 19, 2018.\n *\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n\n\n#include <iostream>\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n\n#include \"src/definitions.h\"\n#include \"src/matlabio.h\"\n\n\n/* user defined dynamics */\nvoid vdp(const rocs::Rn &x, rocs::Rn &dxdt, double t) {\n    dxdt[0] = -x[1];\n    dxdt[1] = x[0] + x[1]*(x[0]*x[0]-1);\n}\n\n\n\nint main()\n{\n    double xlb[] = {-4, -4};\n    double xub[] = {4, 4};\n    double eta[] = {0.001, 0.001};\n    double T = 10.0;\n    double dt = 0.01;\n\n    rocs::grid xg(2, eta, xlb, xub);\n    xg.gridding();\n    \n    /* ROA computation by running simulations */\n    boost::numeric::odeint::runge_kutta_cash_karp54<rocs::Rn> rk45;\n    std::vector<bool> roa(xg._nv);\n    rocs::Rn x;\n    bool stable;\n    for (int i = 0; i < xg._nv; ++i) {\n\t\n\tx = xg._data[i];\n\t\n\t// boost::numeric::odeint::integrate(vdp, x, 0.0, T);\n\t// boost::numeric::odeint::integrate_adaptive(make_controlled(1E-12, 1E-12, dopri5()), vdp, x, 0.0, T, dt);\n\tboost::numeric::odeint::integrate_const(rk45, vdp, x, 0.0, T, dt);\n\n\tstable = true;\n\tfor (int j = 0; j < xg._dim; ++j) {\n\t    // std::cout << x[j] << \", \"; \n\t    stable = stable & (x[j] < 0.5) & (x[j] > -0.5);\n\t}\n\t// std::cout <<'\\n';\n\n\tif (stable) \n\t    roa[i] = true;\n    }\n    \n    \n\n    /* write roa boundary to a mat file */\n    rocs::matWriter wtr(\"data_roavdp_real.mat\");\n    wtr.open();\n\n    wtr.write_boundary(xg, roa, \"bd0\");\n    wtr.close();\n    \n    return 0;\n}\n", "meta": {"hexsha": "ea4625d8533715ad993d5181aa2146f41b922fda", "size": 1593, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/vdp/roa_real.cpp", "max_stars_repo_name": "yinanl/rocs", "max_stars_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "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/vdp/roa_real.cpp", "max_issues_repo_name": "yinanl/rocs", "max_issues_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/vdp/roa_real.cpp", "max_forks_repo_name": "yinanl/rocs", "max_forks_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "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.527027027, "max_line_length": 108, "alphanum_fraction": 0.5668549906, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5327889124987741}}
{"text": "// This example is heavily based on the tutorial at https://open.gl\n\n// OpenGL Helpers to reduce the clutter\n#include \"Helpers.h\"\n\n// GLFW is necessary to handle the OpenGL context\n#include <GLFW/glfw3.h>\n\n// Linear Algebra Library\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n// Timer\n#include <chrono>\n\n// VertexBufferObject wrapper\nVertexBufferObject VBO;\n\n// Contains the vertex positions\nEigen::MatrixXf V(2,3);\n\n// Contains the view transformation\nEigen::Matrix4f view(4,4);\n\nvoid mouse_button_callback(GLFWwindow* window, int button, int action, int mods)\n{\n    // Get the position of the mouse in the window\n    double xpos, ypos;\n    glfwGetCursorPos(window, &xpos, &ypos);\n\n    // Get the size of the window\n    int width, height;\n    glfwGetWindowSize(window, &width, &height);\n\n    // Convert screen position to world coordinates\n    Eigen::Vector4f p_screen(xpos,height-1-ypos,0,1);\n    Eigen::Vector4f p_canonical((p_screen[0]/width)*2-1,(p_screen[1]/height)*2-1,0,1);\n    Eigen::Vector4f p_world = view.inverse()*p_canonical;\n\n    // Update the position of the first vertex if the left button is pressed\n    if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS)\n        V.col(0) << p_world[0], p_world[1];\n\n    // Upload the change to the GPU\n    VBO.update(V);\n}\n\nvoid key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)\n{\n    // Update the position of the first vertex if the keys 1,2, or 3 are pressed\n    switch (key)\n    {\n        case  GLFW_KEY_1:\n            V.col(0) << -0.5,  0.5;\n            break;\n        case GLFW_KEY_2:\n            V.col(0) << 0,  0.5;\n            break;\n        case  GLFW_KEY_3:\n            V.col(0) << 0.5,  0.5;\n            break;\n        default:\n            break;\n    }\n\n    // Upload the change to the GPU\n    VBO.update(V);\n}\n\nint main(void)\n{\n    GLFWwindow* window;\n\n    // Initialize the library\n    if (!glfwInit())\n        return -1;\n\n    // Activate supersampling\n    glfwWindowHint(GLFW_SAMPLES, 8);\n\n    // Ensure that we get at least a 3.2 context\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);\n\n    // On apple we have to load a core profile with forward compatibility\n#ifdef __APPLE__\n    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n#endif\n\n    // Create a windowed mode window and its OpenGL context\n    window = glfwCreateWindow(640, 480, \"Hello World\", NULL, NULL);\n    if (!window)\n    {\n        glfwTerminate();\n        return -1;\n    }\n\n    // Make the window's context current\n    glfwMakeContextCurrent(window);\n\n    #ifndef __APPLE__\n      glewExperimental = true;\n      GLenum err = glewInit();\n      if(GLEW_OK != err)\n      {\n        /* Problem: glewInit failed, something is seriously wrong. */\n       fprintf(stderr, \"Error: %s\\n\", glewGetErrorString(err));\n      }\n      glGetError(); // pull and savely ignonre unhandled errors like GL_INVALID_ENUM\n      fprintf(stdout, \"Status: Using GLEW %s\\n\", glewGetString(GLEW_VERSION));\n    #endif\n\n    int major, minor, rev;\n    major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);\n    minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);\n    rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);\n    printf(\"OpenGL version recieved: %d.%d.%d\\n\", major, minor, rev);\n    printf(\"Supported OpenGL is %s\\n\", (const char*)glGetString(GL_VERSION));\n    printf(\"Supported GLSL is %s\\n\", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));\n\n    // Initialize the VAO\n    // A Vertex Array Object (or VAO) is an object that describes how the vertex\n    // attributes are stored in a Vertex Buffer Object (or VBO). This means that\n    // the VAO is not the actual object storing the vertex data,\n    // but the descriptor of the vertex data.\n    VertexArrayObject VAO;\n    VAO.init();\n    VAO.bind();\n\n    // Initialize the VBO with the vertices data\n    // A VBO is a data container that lives in the GPU memory\n    VBO.init();\n\n    V.resize(2,3);\n    V << 0,  0.5, -0.5, 0.5, -0.5, -0.5;\n    VBO.update(V);\n\n    // Initialize the OpenGL Program\n    // A program controls the OpenGL pipeline and it must contains\n    // at least a vertex shader and a fragment shader to be valid\n    Program program;\n    const GLchar* vertex_shader =\n            \"#version 150 core\\n\"\n                    \"in vec2 position;\"\n                    \"uniform mat4 view;\"\n                    \"void main()\"\n                    \"{\"\n                    \"    gl_Position = view * vec4(position, 0.0, 1.0);\"\n                    \"}\";\n    const GLchar* fragment_shader =\n            \"#version 150 core\\n\"\n                    \"out vec4 outColor;\"\n                    \"uniform vec3 triangleColor;\"\n                    \"void main()\"\n                    \"{\"\n                    \"    outColor = vec4(triangleColor, 1.0);\"\n                    \"}\";\n\n    // Compile the two shaders and upload the binary to the GPU\n    // Note that we have to explicitly specify that the output \"slot\" called outColor\n    // is the one that we want in the fragment buffer (and thus on screen)\n    program.init(vertex_shader,fragment_shader,\"outColor\");\n    program.bind();\n\n    // The vertex shader wants the position of the vertices as an input.\n    // The following line connects the VBO we defined above with the position \"slot\"\n    // in the vertex shader\n    program.bindVertexAttribArray(\"position\",VBO);\n\n    // Save the current time --- it will be used to dynamically change the triangle color\n    auto t_start = std::chrono::high_resolution_clock::now();\n\n    // Register the keyboard callback\n    glfwSetKeyCallback(window, key_callback);\n\n    // Register the mouse callback\n    glfwSetMouseButtonCallback(window, mouse_button_callback);\n\n    // Loop until the user closes the window\n    while (!glfwWindowShouldClose(window))\n    {\n        // Bind your VAO (not necessary if you have only one)\n        VAO.bind();\n\n        // Bind your program\n        program.bind();\n\n        // Set the uniform value depending on the time difference\n        auto t_now = std::chrono::high_resolution_clock::now();\n        float time = std::chrono::duration_cast<std::chrono::duration<float>>(t_now - t_start).count();\n        glUniform3f(program.uniform(\"triangleColor\"), (float)(sin(time * 4.0f) + 1.0f) / 2.0f, 0.0f, 0.0f);\n\n        // Get size of the window\n        int width, height;\n        glfwGetWindowSize(window, &width, &height);\n        float aspect_ratio = float(height)/float(width); // corresponds to the necessary width scaling\n\n        view <<\n        aspect_ratio,0, 0, 0,\n        0,           1, 0, 0,\n        0,           0, 1, 0,\n        0,           0, 0, 1;\n\n        glUniformMatrix4fv(program.uniform(\"view\"), 1, GL_FALSE, view.data());\n\n        // Clear the framebuffer\n        glClearColor(0.5f, 0.5f, 0.5f, 1.0f);\n        glClear(GL_COLOR_BUFFER_BIT);\n\n        // Draw a triangle\n        glDrawArrays(GL_TRIANGLES, 0, 3);\n\n        // Swap front and back buffers\n        glfwSwapBuffers(window);\n\n        // Poll for and process events\n        glfwPollEvents();\n    }\n\n    // Deallocate opengl memory\n    program.free();\n    VAO.free();\n    VBO.free();\n\n    // Deallocate glfw internals\n    glfwTerminate();\n    return 0;\n}\n", "meta": {"hexsha": "0f9c0f12366daea42d6a4e39972e19b4b67f7f14", "size": 7305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "App/extra/main_view.cpp", "max_stars_repo_name": "rachitmehrotra1/triangle-soup-editor", "max_stars_repo_head_hexsha": "e5b18827523e97e09a826a4dd0cf03f8f978834b", "max_stars_repo_licenses": ["MIT"], "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/extra/main_view.cpp", "max_issues_repo_name": "rachitmehrotra1/triangle-soup-editor", "max_issues_repo_head_hexsha": "e5b18827523e97e09a826a4dd0cf03f8f978834b", "max_issues_repo_licenses": ["MIT"], "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/extra/main_view.cpp", "max_forks_repo_name": "rachitmehrotra1/triangle-soup-editor", "max_forks_repo_head_hexsha": "e5b18827523e97e09a826a4dd0cf03f8f978834b", "max_forks_repo_licenses": ["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.7608695652, "max_line_length": 107, "alphanum_fraction": 0.6280629706, "num_tokens": 1836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5327530829910754}}
{"text": "\n#pragma once\n\n// Some standard functions for dealing with rotation matrices and quaternions \n\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\nusing namespace Eigen;\n\nconst MatrixXd H = (MatrixXd() << MatrixXd::Zero(1, 3), MatrixXd::Identity(3, 3)).finished();\nconst MatrixXd T = (MatrixXd()  << 1, MatrixXd::Zero(1, 3), MatrixXd::Zero(3, 1), -MatrixXd::Identity(3, 3)).finished();\n\nMatrixXd hat(VectorXd omega);\nMatrixXd L(VectorXd Q);\nMatrixXd R(VectorXd Q);\nMatrixXd G(VectorXd Q);\nMatrixXd G_tilde(VectorXd q);\nMatrixXd rho(VectorXd phi);", "meta": {"hexsha": "15e65c169625192c3a26961575180c7430344702", "size": 578, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/dynamics/rotation.hpp", "max_stars_repo_name": "brysonjones/dynamics_sim", "max_stars_repo_head_hexsha": "201bdf0a93d00addc585ffa47f280cffacebb9b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dynamics/rotation.hpp", "max_issues_repo_name": "brysonjones/dynamics_sim", "max_issues_repo_head_hexsha": "201bdf0a93d00addc585ffa47f280cffacebb9b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dynamics/rotation.hpp", "max_forks_repo_name": "brysonjones/dynamics_sim", "max_forks_repo_head_hexsha": "201bdf0a93d00addc585ffa47f280cffacebb9b3", "max_forks_repo_licenses": ["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.5238095238, "max_line_length": 120, "alphanum_fraction": 0.723183391, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443252, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5327530820049332}}
{"text": "//#########################################################//\n//#                                                       #//\n//# gaussian_mixture_models  gaussian.cpp                 #//\n//# Roberto Capobianco  <capobianco@dis.uniroma1.it>      #//\n//#                                                       #//\n//#########################################################//\n\n#include <Eigen/Eigenvalues>\n#include <cmath>\n\n\n#include <particle_filter/gaussian.h>\n\nnamespace gmms {\ndouble Gaussian::evaluate_point(const Eigen::VectorXd& pt) const {\n    if (pt.size() != dimensionality_) {\n        throw std::runtime_error(dimensionality_mismatch());\n    }\n\n    Eigen::VectorXd dist = pt - mean_;\n\n    double factor = std::sqrt(\n            std::pow(2 * M_PI, dimensionality_) * cov_abs_determinant_);\n    double exp = std::exp(-0.5 * dist.transpose() * inv_covariance_ * dist);\n\n    double result = exp / factor;\n\n    if (result == 0) {\n        srand(time(NULL));\n        double random = ((double) rand() / (RAND_MAX));\n        result = random * 1e-15;\n    }\n\n    return result;\n}\n\nvoid Gaussian::setCovariance(const Eigen::MatrixXd& covariance) {\n    if (covariance.rows() != covariance.cols() ||\n            covariance.rows() != dimensionality_) {\n        throw std::runtime_error(dimensionality_mismatch());\n    }\n\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(covariance.cols());\n    solver.compute(covariance);\n\n    Eigen::VectorXd eigenvalues = solver.eigenvalues();\n    Eigen::MatrixXd eigenvectors = solver.eigenvectors();\n\n    for (int i = 0; i < eigenvalues.rows(); ++i) {\n        if (eigenvalues(i) < M_EPS) {\n            eigenvalues(i) = M_EPS;\n        }\n    }\n\n    covariance_ =\n            eigenvectors * eigenvalues.asDiagonal() * eigenvectors.inverse();\n    double abs_determinant = std::fabs(covariance_.determinant());\n\n    inv_covariance_ = covariance_.inverse();\n    cov_abs_determinant_ = abs_determinant;\n}\n\nvoid Gaussian::setMeanCovariance(const Eigen::VectorXd& mean,\n        const Eigen::MatrixXd& covariance) {\n    int dimensionality = mean.size();\n    dimensionality_ = dimensionality;\n    setMean(mean);\n    setCovariance(covariance);\n}\n\nstd::string Gaussian::toString() const {\n    Eigen::IOFormat mean_format(\n            5, 0, \", \", \"\\n\", \"[\", \"]\", \"Mean:       \", \"\\n\");\n    Eigen::IOFormat cov_format(\n            5, 0, \", \", \"\\n\", \"[\", \"]\", \"Covariance: \", \"\\n\");\n    std::stringstream gaussian_string;\n    gaussian_string << \"Gaussian: \\n\";\n    gaussian_string << mean_.format(mean_format);\n    gaussian_string << covariance_.format(cov_format);\n    return gaussian_string.str();\n}\n\nvoid Gaussian::addToEigenMatrix(Eigen::MatrixXd& matrix,\n        float x0,\n        float y0,\n        float x1,\n        float y1,\n        int stepcount) const {\n    assert(x0 < x1);\n    assert(y0 < y1);\n    float x_delta = std::abs(x1 - x0);\n    float y_delta = std::abs(y1 - y0);\n    float x, y;\n    float x_mean = mean_(0, 0);\n    float y_mean = mean_(1, 0);\n    // TODO: save stepsize\n\n    for (int y_step = 0; y_step < stepcount; y_step++) {\n        y = y0 + (y_delta / stepcount * y_step);\n        for (int x_step = 0; x_step < stepcount; x_step++) {\n            x = x0 + (x_delta / stepcount * x_step);\n            // Function taken from\n            // https://en.wikipedia.org/wiki/Gaussian_function#Two-dimensional_Gaussian_function\n            // matrix(y_step, x_step) += 1 * std::exp(-(std::pow(x - x_mean, 2)\n            // / covariance_(0, 0)  + 2 * (x - x_mean) * (y - y_mean) /\n            // covariance_(1, 0) + std::pow(y - y_mean, 2) / covariance_(1,\n            // 1)));\n            matrix(y_step, x_step) +=\n                    1 * std::exp(-((std::pow(x - x_mean, 2) /\n                                           (2 * covariance_(0, 0))) +\n                                   (std::pow(y - y_mean, 2) /\n                                           (2 * covariance_(1, 1)))));\n        }\n    }\n}\n\ndouble Gaussian::calcDistance(const Eigen::VectorXd& mean) const {\n    if (mean.size() != dimensionality_) {\n        throw std::runtime_error(dimensionality_mismatch());\n    }\n    Eigen::VectorXd diff_vec = mean_ - mean;\n    return diff_vec.cwiseAbs().sum() / static_cast<double>(dimensionality_);\n}\n\n\n}  // namespace gmms\n", "meta": {"hexsha": "013e4e48f302d75a4abe61d64d57a55ebba5a601", "size": 4259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/particle_filter/src/gaussian.cpp", "max_stars_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_stars_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-02-23T18:18:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T16:59:55.000Z", "max_issues_repo_path": "lib/particle_filter/src/gaussian.cpp", "max_issues_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_issues_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-03-16T22:05:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T14:21:53.000Z", "max_forks_repo_path": "lib/particle_filter/src/gaussian.cpp", "max_forks_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_forks_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-29T10:20:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-20T16:36:47.000Z", "avg_line_length": 33.5354330709, "max_line_length": 96, "alphanum_fraction": 0.5475463724, "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5327530496943291}}
{"text": "#ifndef MCMC_UTILS_CPP_UPDATES_HPP\n#define MCMC_UTILS_CPP_UPDATES_HPP\n\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\n#include <Eigen/Dense>\n\n\nnamespace updates {\n/*\n * Computes the posterior parameters for a model\n *     x_1, ... x_n ~ N(mu, 1 / tau)\n *     \\mu | tau ~ N(mu0, 1 / (lambda * tau))\n *     \\tau ~ Gamma(a, b)\n *\n * returns an std::vector{mu0_post, a_post, b_post, lambda_post}\n */\nstd::vector<double> normalGammaUpdate(\n    std::vector<double> data, double priorMean, double priorA,\n    double priorB, double priorLambda);\n\n\n/*\n * Computes the posterior parameters of the parameter \\beta\n * for a linear regression model (univariate)\n *\n *          y_i = x_i^T \\beta + \\epsilon_i\n *          epsilon_i ~ N(0, \\sigma^2)\n *          \\beta ~ N(\\mu0, \\Lambda)\n *\n * where \\Lambda is the precision matrix\n *\n * Then \\beta | \\sigma^2, y ~ N(mu_post, Lambda_post)\n * where\n *          Lambda_post = \\Lambda + X^t X\n *          mu_post = Lambda_post^{-1} (X^t y + \\Lambda \\mu0)\n */\nstd::tuple<Eigen::VectorXd, Eigen::MatrixXd> simpleLinearRegressionUpdate(\n    Eigen::VectorXd y, Eigen::MatrixXd X, Eigen::VectorXd betaMean,\n    Eigen::MatrixXd betaPrec);\n\n\n/*\n * Computes the posterior parameters of the parameter \\beta\n * for a linear regression model (univariate)\n *\n *          y_i = x_i^T \\beta + \\epsilon_i\n *          epsilon_i ~ N(\\mu_i, \\sigma_i^2)\n *          \\beta ~ N(\\mu0, \\Lambda)\n *\n * where \\Lambda is the precision matrix\n *\n * Then \\beta | \\sigma^2, y ~ N(mu_post, Lambda_post)\n * where, being V = diag(sigma^2_i)^{-1}\n *\n *          Lambda_post = \\Lambda + X^t V X\n *          mu_post = Lambda_post^{-1} (X^t y + \\Lambda \\mu0)\n */\nstd::tuple<Eigen::VectorXd, Eigen::MatrixXd> heteroSchedLinearRegressionUpdate(\n    Eigen::VectorXd y, Eigen::MatrixXd X, Eigen::VectorXd betaMean,\n    Eigen::MatrixXd betaPrec, Eigen::VectorXd mu,\n    Eigen::VectorXd V);\n\n}\n\n#endif\n", "meta": {"hexsha": "fcd7e4806abbf1b838c544e72b407c47c0616689", "size": 1936, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mcmc_utils/cpp/updates.hpp", "max_stars_repo_name": "mberaha/utils", "max_stars_repo_head_hexsha": "9be102383d0288f08bd3ccfc4c46ecaf958987ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mcmc_utils/cpp/updates.hpp", "max_issues_repo_name": "mberaha/utils", "max_issues_repo_head_hexsha": "9be102383d0288f08bd3ccfc4c46ecaf958987ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mcmc_utils/cpp/updates.hpp", "max_forks_repo_name": "mberaha/utils", "max_forks_repo_head_hexsha": "9be102383d0288f08bd3ccfc4c46ecaf958987ac", "max_forks_repo_licenses": ["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.2676056338, "max_line_length": 79, "alphanum_fraction": 0.6399793388, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5327325325495804}}
{"text": "#include \"setup_modes.h\"\n#include \"to_triplets.h\"\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <igl/writeDMAT.h>\n#include <unsupported/Eigen/KroneckerProduct>\n#include <json.hpp>\n\n// #include <MatOp/SparseSymMatProd.h>\n// #include <MatOp/SparseCholesky.h>\n// #include <SymGEigsSolver.h>\n// #include <GenEigsSolver.h>\n#include <igl/cotmatrix.h>\n\nusing namespace Eigen;\nusing namespace std;\ntypedef Eigen::Triplet<double> Trip;\n\nusing json = nlohmann::json;\n\nvoid setup_modes(json& j_input, int nummodes, bool reduced, SparseMatrix<double>& mP, SparseMatrix<double>& mA, SparseMatrix<double> mConstrained, SparseMatrix<double> mFree, SparseMatrix<double> mY, MatrixXd& mV, const MatrixXi& mT, VectorXd& mmass_diag, MatrixXd& mG){\n        if(nummodes==0 && reduced==false){\n            //Unreduced just dont use G\n            return;\n        }\n        if(nummodes==0){\n            //reduced, but no modes\n            cout<<\"reduced, but no modes?\"<<endl;\n            mG = MatrixXd::Identity(3*mV.rows(), 3*mV.rows());\n            return;\n        }\n        nummodes = std::min(nummodes+25, mA.cols());\n        // SparseMatrix<double> L;\n        // igl::cotmatrix(mV, mT, L);\n        // Eigen::kroneckerProduct(L, Matrix3d::Identity());\n\n        cout<<\"+EIG SOLVE\"<<endl;\n        SparseMatrix<double> K = (mP*mA).transpose()*mP*mA;\n        SparseMatrix<double> M(3*mV.rows(), 3*mV.rows());\n        for(int i=0; i<mmass_diag.size(); i++){\n            M.coeffRef(i,i) = mmass_diag[i];\n        }\n\n\n        cout<<\"     eig1\"<<endl;\n        //Spectra seems to freak out if you use row storage, this copy just ensures everything is setup the way the solver likes\n        Eigen::SparseMatrix<double> A = mY.transpose()*K*mY;\n        Eigen::SparseMatrix<double> B = mY.transpose()*M*mY;\n\n        cout<<\"here1\"<<endl;\n        double shift = 1e-6;\n        Eigen::SparseMatrix<double> K1 = A + shift*B;\n        Eigen::SparseMatrix<double> M1 = B;\n        cout<<\"here2\"<<endl;\n\n        Spectra::SparseSymMatProd<double>Aop(M1);\n        SparseMatrix<double> Kt = K1.transpose();\n        // SparseMatrix<double> symK = -.5*(K1+Kt);\n        Spectra::SparseCholesky<double> Bop(K1);\n        cout<<\"here3\"<<endl;\n \n\n        Spectra::SymGEigsSolver<double, Spectra::LARGEST_MAGN, Spectra::SparseSymMatProd<double>, Spectra::SparseCholesky<double>, Spectra::GEIGS_CHOLESKY>geigs(&Aop, &Bop, nummodes, std::min(5*nummodes, A.rows()));\n        geigs.init();\n        cout<<\"     eig2\"<<endl;\n        int nconv = geigs.compute();\n        cout<<\"     eig3\"<<endl;\n \n        VectorXd eigsCorrected;\n        eigsCorrected.resize(geigs.eigenvalues().rows());\n        MatrixXd evsCorrected = geigs.eigenvectors();\n        cout<<\"     eig3.5\"<<endl;\n        if(geigs.info() == Spectra::SUCCESSFUL)\n        {\n            for(unsigned int ii=0; ii<geigs.eigenvalues().rows(); ++ii) {\n                eigsCorrected[ii] = -(static_cast<double>(1)/(geigs.eigenvalues()[ii]) + shift);\n                evsCorrected.col(ii) /= sqrt(geigs.eigenvectors().col(ii).transpose()*M1*geigs.eigenvectors().col(ii));\n            }\n\n        }\n        else\n        {\n            cout<<\"EIG SOLVE FAILED: \"<<endl<<geigs.info()<<endl;\n            exit(0);\n        }\n\n        cout<<\"     eig4\"<<endl;\n        // eigenvalues.head(eigenvalues.size() - 3));\n        mG = evsCorrected.leftCols(nummodes-25);\n        std::string outputfile = j_input[\"output\"];\n        igl::writeDMAT(outputfile+\"/\"+to_string((int)j_input[\"number_modes\"])+\"modes.dmat\", evsCorrected);\n        cout<<\"-EIG SOLVE\"<<endl;\n        return;\n\n        // //############handle modes KKT solve#####\n        // cout<<\"+ModesForHandles\"<<endl;\n        // SparseMatrix<double> C = mConstrained.transpose();\n        // SparseMatrix<double> HandleModesKKTmat(K.rows()+C.rows(), K.rows()+C.rows());\n        // HandleModesKKTmat.setZero();\n        // std::vector<Trip> KTrips = to_triplets(K);\n        // std::vector<Trip> CTrips = to_triplets(C);\n        // cout<<\"     eig5\"<<endl;\n        // for(int i=0; i<CTrips.size(); i++){\n        //     int row = CTrips[i].row();\n        //     int col = CTrips[i].col();\n        //     int val = CTrips[i].value();\n        //     KTrips.push_back(Trip(row+K.rows(), col, val));\n        //     KTrips.push_back(Trip(col, row+K.cols(), val));\n        // }\n        // KTrips.insert(KTrips.end(),CTrips.begin(), CTrips.end());\n        // HandleModesKKTmat.setFromTriplets(KTrips.begin(), KTrips.end());\n\n        // cout<<\"     eig6\"<<endl;\n        // SparseMatrix<double>eHconstrains(K.rows()+C.rows(), C.rows());\n        // eHconstrains.setZero();\n        // std::vector<Trip> eHTrips;\n        // for(int i=0; i<C.rows(); i++){\n        //     eHTrips.push_back(Trip(i+K.rows(), i, 1));\n        // }\n        // eHconstrains.setFromTriplets(eHTrips.begin(), eHTrips.end());\n        \n        // cout<<\"     eig7\"<<endl;\n        // SparseLU<SparseMatrix<double>> solver;\n        // solver.compute(HandleModesKKTmat);\n        // SparseMatrix<double> eHsparse = solver.solve(eHconstrains);\n        // MatrixXd eH = MatrixXd(eHsparse).topRows(K.rows());\n        // cout<<\"-ModesForHandles\"<<endl;\n\n        // //###############QR get orth basis of Modes, eH#######\n        // MatrixXd eHeV(eH.rows(), eH.cols()+eV.cols());\n        // eHeV<<eV,eH;\n        // igl::writeDMAT(\"TOQR.dmat\", eHeV);\n        // HouseholderQR<MatrixXd> QR(eHeV);\n        // cout<<\"     eig8\"<<endl;\n        // MatrixXd thinQ = MatrixXd::Identity(eHeV.rows(), eHeV.cols());\n        // //SET Q TO G\n        // mG = QR.householderQ()*thinQ; \n        // return;\n        // cout<<\"     eig9\"<<endl;       \n}", "meta": {"hexsha": "0cbbdb6ced500b89afd3c332f31d8b14d3db24a0", "size": 5645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PreProcessing/setup_modes.cpp", "max_stars_repo_name": "itsvismay/fast_muscles", "max_stars_repo_head_hexsha": "86c9d93bd14da92ce2140bf47857810b579e7b2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T22:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T01:38:52.000Z", "max_issues_repo_path": "PreProcessing/setup_modes.cpp", "max_issues_repo_name": "alecjacobson/fast_muscles", "max_issues_repo_head_hexsha": "92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-08T21:10:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-08T21:10:36.000Z", "max_forks_repo_path": "PreProcessing/setup_modes.cpp", "max_forks_repo_name": "alecjacobson/fast_muscles", "max_forks_repo_head_hexsha": "92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-08T21:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-08T21:11:10.000Z", "avg_line_length": 40.0354609929, "max_line_length": 270, "alphanum_fraction": 0.5666961913, "num_tokens": 1574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5327325279723738}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nnamespace boost_int = boost::multiprecision;\nusing booint = boost_int::cpp_int;\nusing namespace std;\nint main() {\n    long long int N, A, B; cin >> N >> A >> B;\n    booint ans = (B - A) * (N - 2) + 1;\n    if ((N == 1 && A != B) || A > B) cout << 0 << endl;\n    else if (N == 1) cout << 1 << endl;\n    else cout << ans << endl;\n}\n", "meta": {"hexsha": "b478aaf147501ef774bc16cf0655588cc2ebffe4", "size": 449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/agc015/a/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/agc015/a/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/agc015/a/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": 28.0625, "max_line_length": 55, "alphanum_fraction": 0.5857461024, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5326972654738998}}
{"text": "/*******************************************************************************\n *         Copyright 2003-2012 LASMEA UMR 6602 CNRS/U.B.P\n *         Copyright 2011-2012 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n *\n *          Distributed under the Boost Software License, Version 1.0.\n *                 See accompanying file LICENSE.txt or copy at\n *                     http://www.boost.org/LICENSE_1_0.txt\n ******************************************************************************/\n#ifndef NT2_TOOLBOX_LINALG_FUNCTIONS_DETAILS_LU_HPP_INCLUDED\n#define NT2_TOOLBOX_LINALG_FUNCTIONS_DETAILS_LU_HPP_INCLUDED\n\n#include <nt2/sdk/error/warning.hpp>\n#include <nt2/include/functions/triu.hpp>\n#include <nt2/include/functions/tri1l.hpp>\n#include <nt2/include/functions/height.hpp>\n#include <nt2/include/functions/width.hpp>\n#include <nt2/include/functions/numel.hpp>\n#include <nt2/include/functions/diag_of.hpp>\n#include <nt2/include/functions/eye.hpp>\n#include <nt2/include/functions/expand.hpp>\n#include <nt2/include/functions/rif.hpp>\n#include <nt2/include/functions/max.hpp>\n#include <nt2/include/functions/rec.hpp>\n#include <nt2/include/functions/norm.hpp>\n#include <nt2/include/functions/prod.hpp>\n#include <nt2/include/functions/eps.hpp>\n#include <nt2/include/functions/frexp.hpp>\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/sb2b.hpp>\n#include <nt2/include/functions/is_eqz.hpp>\n#include <nt2/include/functions/isempty.hpp>\n#include <nt2/include/functions/issquare.hpp>\n#include <nt2/include/functions/if_one_else_zero.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/toolbox/linalg/details/utility/options.hpp>\n#include <nt2/toolbox/linalg/details/utility/workspace.hpp>\n#include <nt2/toolbox/linalg/details/lapack/getrf.hpp>\n#include <nt2/toolbox/linalg/details/lapack/gecon.hpp>\n#include <nt2/toolbox/linalg/details/lapack/getri.hpp>\n#include <nt2/toolbox/linalg/details/lapack/gesvx.hpp>\n#include <nt2/toolbox/linalg/details/lapack/lange.hpp>\n#include <boost/dispatch/details/ignore_unused.hpp>\n#include <nt2/core/container/table/table.hpp>\n\n// TODO:\n// these are the kind of syntaxes to be enforced by nt2::chol\n//  lu     lu factorization.\n//     [l,u] = lu(a) stores an upper triangular matrix in u and a\n//     \"psychologically lower triangular matrix\" (i.e. a product of lower\n//     triangular and permutation matrices) in l, so that a = l*u. a can be\n//     rectangular.\n// -> {pl, u]\n\n//     [l,u,p] = lu(a) returns unit lower triangular matrix l, upper\n//     triangular matrix u, and permutation matrix p so that p*a = l*u.\n// -> {l, u, p]\n\n//     [l,u,p] = lu(a,'vector') returns the permutation information as a\n//     vector instead of a matrix.  that is, p is a row vector such that\n//     a(p,:) = l*u.  similarly, [l,u,p] = lu(a,'matrix') returns a\n//     permutation matrix p.  this is the default behavior.\n// -> {l, u, ip]\n\n////////////////////////////////////////////////////////////////////////////////////////\n// The class provides:\n// constructor from an expression or matrix a\n//\n// accesors to l, u, p, pl and ip\n//\n// l is lower unittriangular part of lu_\n// u is upper triangular part of lu_\n// p is a permutation matrix\n// pl is l permuted by p\n// ip is the permutation index vector defining p\n// we have l*u =  p*a\n//         pl*u =  a\n/////////////////////////////////////////////////// TODO  perhaps l and u could return an expresiion rather than a matrix\n//\n// the class allow to compute\n//\n// status the plu status from lapack\n//\n// rank the matrix rank\n//\n// When a is square\n// det and absdet determinant and absolute value of the determinant\n// They have two syntaxes\n//  1 - d =  f.det()   or d =  f.absdet()\n//  2 - m =  f.det(e)  or m =  f.absdet(e)\n// In the second case m is a mantissa and e and exponent\n// If there is no overflow or undeflow in e the determinant is then equal to ldexp(m, e)\n//\n// rcond the reciprocal condition number of a\n//\n// Two solvers\n// solve and inplace_solve\n//\n// a matrix inversion\n// inv\n// inv() can emit a warning if rcond is bad\n// inv(false) never warns\n//     please avoid using inv if you need not the inverse coefficients.\n\nnamespace nt2 { namespace details\n{\n  template<class T> struct lu_result\n  {\n    typedef typename meta::strip<T>::type                   source_t;\n    typedef typename source_t::value_type                     type_t;\n    typedef typename meta::as_integer<type_t, signed>::type  itype_t;\n    typedef typename source_t::index_type                    index_t;\n    typedef typename meta::as_real<type_t>::type              base_t;\n    typedef T                                                 data_t;\n    typedef nt2::table<type_t,nt2::matlab_index_>              tab_t;\n    typedef nt2::table<base_t,nt2::matlab_index_>             btab_t;\n    typedef nt2::table<itype_t,nt2::matlab_index_>            itab_t;\n    typedef nt2::details::workspace<type_t>              workspace_t;\n    typedef nt2::table<nt2_la_int,nt2::matlab_index_>         ibuf_t;\n    typedef nt2::table<type_t,index_t>                   result_type;\n\n    template<class Input>\n    lu_result ( Input& xpr\n                , typename boost::\n                disable_if_c<boost::is_same<lu_result,Input>::value>::type* = 0\n      )\n      : a_(xpr)\n      , lu_(xpr)\n      , m_( nt2::height(xpr) )\n      , n_( nt2::width(xpr)  )\n      , ldlu_( lu_.leading_size() )\n      , ipiv_(nt2::of_size(nt2::min(n_, m_), 1))\n      , info_(0)\n      , p_(of_size(0, 1))\n      , ip_(of_size(0, 1))\n      , pl_(of_size(0, 1))\n      , invt_(of_size(0, 1))\n    {\n      nt2::details::getrf(&m_, &n_, lu_.raw(), &ldlu_, ipiv_.raw(), &info_, w_);\n    }\n\n    lu_result(lu_result const& src)\n      : a_(src.a_) , lu_(src.lu_), m_( src.m_ ), n_( src.n_ )\n      , ldlu_( src.ldlu_ ) , ipiv_(src.ipiv_)\n      , info_(src.info_) , w_(src.w_)\n      , p_(src.p_), ip_(src.ip_), pl_(src.pl_), invt_(src.invt_)\n    {}\n\n    lu_result& operator=(lu_result const& src)\n    {\n      a_      = src.a_;\n      lu_     = src.lu_;\n      m_      = src.m_;\n      n_      = src.n_;\n      ldlu_   = src.ldlu_;\n      ipiv_   = src.ipiv_;\n      info_   = src.info_;\n      w_      = src.w_;\n      p_      = src.p_;\n      ip_     = src.ip_;\n      pl_     = src.pl_;\n      invt_   = src.invt_;\n      return *this;\n    }\n\n    //==========================================================================\n    // Return raw values\n    //==========================================================================\n    const tab_t& values() const { return lu_; }\n\n    //==========================================================================\n    // Return raw values\n    //==========================================================================\n    const tab_t& original() const { return a_; }\n\n    //==========================================================================\n    // Return u part of the decomposition\n    //==========================================================================\n    typedef typename meta::call < tag::colon_(ptrdiff_t, ptrdiff_t)>::type                          u_T2;\n    typedef typename meta::call < tag::function_(tab_t const&, u_T2, nt2::container::colon_)>::type u_T0;\n    typedef typename meta::call < tag::triu_(u_T0)>::type                                           u_result;\n    u_result u() const\n    {\n      ptrdiff_t mm =  std::min(n_, m_);\n      return nt2::triu(lu_(_(ptrdiff_t(1), mm),_));\n    }\n    //==========================================================================\n    // Return l part of the decomposition\n    //==========================================================================\n    typedef typename meta::call < tag::colon_(ptrdiff_t, ptrdiff_t)>::type                          l_T2;\n    typedef typename meta::call < tag::function_(tab_t const&, nt2::container::colon_, l_T2)>::type l_T0;\n    typedef typename meta::call < tag::tri1l_(l_T0)>::type                                          l_result;\n    l_result l() const\n    {\n      ptrdiff_t mm =  std::min(n_, m_);\n      return nt2::tri1l(lu_(_,_(ptrdiff_t(1), mm)));\n    }\n\n    //==========================================================================\n    // Return p part of the decomposition as a matrix such that p*a = l*u\n    //==========================================================================\n    const tab_t& p()\n    {\n      if (isempty(p_))\n      {\n        std::size_t mm = nt2::numel(ipiv_);\n        p_ = nt2::eye(mm, mm, meta::as_<type_t>());\n        for(size_t i=1; i <= mm; ++i)\n          // p_({i, ipiv_(i)}, _) =  p_({ipiv_(i),i}, _)\n        {\n          tab_t c = p_(i, _);\n          p_(i,_) = p_(ipiv_(i),_);\n          p_(ipiv_(i),_) = c;\n        }\n      }\n      return p_;\n    }\n    //==========================================================================\n    // Return p part of the decomposition as a vector\n    //==========================================================================\n    const itab_t& ip()\n    {\n      if (isempty(ip_))\n      {\n        //      itab_t ip = itab_t(ipiv_.raw(), ipiv_.raw()+numel(ipiv_));\n        ip_.resize(of_size(1, numel(ipiv_)));\n        for(size_t i=1; i <= numel(ipiv_); ++i) ip_(i) = ipiv_(i);\n      }\n      return ip_;\n    }\n\n    //==========================================================================\n    // Return tpl part of the decomposition  a =  tpl*u (pl = tp *l)\n    //==========================================================================\n    const tab_t& pl()\n    {\n      if (isempty(pl_))\n      {\n        //    return trans(p())*l;\n        std::size_t mm = nt2::numel(ipiv_); //incorrect\n        pl_ = l();\n        for(size_t i=1; i <= mm; ++i)\n          // pp({i, ipiv_(i)}, _) =  pp({ipiv_(i),i}, _)\n        {\n          tab_t c = pl_(ipiv_(i), _);\n          pl_(ipiv_(i),_) = pl_(i,_);\n          pl_(i,_) = c;\n        }\n      }\n      return pl_;\n    }\n\n    //==========================================================================\n    // Return post-computation status\n    //==========================================================================\n    nt2_la_int  status() const { return info_; }\n\n    //==========================================================================\n    // Reverse conditioning evaluation\n    //==========================================================================\n    base_t rcond(char c = '1')\n    {\n      /* this method which is presumably faster provides results that depend on\n      // the lapack used version\n      // it seems that gecon is buggy (J.T.L. 28/2/2013)\n      //\n      //   base_t rc = 0;\n      //   tab_t aa = a_;\n      //   char norm = (c == 1) ? '1' : ((c == 0) ? 'o' : c);\n      //   base_t anorm = nt2::details::lange(&norm,  &n_,  &n_, aa.raw(), &ldlu_);\n      //   nt2::details::gecon(&norm, &n_,  lu_.raw(), &ldlu_, &anorm, &rc, &info_);\n      //   return rc;\n      //\n        So we switch to a direct computation\n      */\n      return nt2::rec(nt2::norm(a_, c)*nt2::norm(this->inv(false), c));\n    }\n\n    //==========================================================================\n    // system rank\n    //==========================================================================\n    size_t rank(base_t epsi = nt2::Eps<base_t>()) //provisouare\n    {\n      //int32_t r = 0;\n      base_t thresh = nt2::max(n_, m_)*epsi*nt2::max(nt2::abs(nt2::diag_of(lu_)(_)));\n      return  size_t(sum(if_one_else_zero(gt(nt2::diag_of(lu_), thresh))(_)));\n\n      //       for(int i=1; i <= nt2::min(n_, m_); ++i)\n      //         {\n      //           if(nt2::abs(lu_(i, i)) > thresh) ++r;\n      //         }\n      //       return r;\n      //      nt2::inbtrue(nt2::abs(diag_of(lu_)) > nt2::max(n_, m_)*epsi*nt2::max(abs(diag_of(lu_()))) );\n    }\n\n    base_t absdet()\n    {\n      BOOST_ASSERT_MSG(m_ == n_, \"non square matrix in determinant computation\");\n      return nt2::prod(nt2::abs(nt2::diag_of(lu_)(_)));\n    }\n\n    type_t signdet(bool check = true){\n      BOOST_ASSERT_MSG(m_ == n_, \"non square matrix in determinant computation\");\n      boost::dispatch::ignore_unused(check);\n      //if (check)     BOOST_ASSERT_MSG(is_real<type_t>::value, \"determinant sign is not avalaible for complex matrices\");\n      //count modulo 2 the number of ipiv_ elements such that ipiv_(i) !=  i\n      //return nt2::sum(nt2::sb2b(ipiv_ != cif(numel(ipiv_), 1, meta::as_<itype_t>())))&1 ? Mone<type_t>() : One<type_t>();\n      type_t s = One<type_t>();\n      const nt2_la_int num = numel(ipiv_);\n      for(nt2_la_int i=1; i < num ; ++i)\n      {\n        if (ipiv_(i) !=  i) s = -s;\n      }\n      return s;\n    }\n\n    type_t det(){\n      BOOST_ASSERT_MSG(m_ == n_, \"non square matrix in determinant computation\");\n      //     BOOST_ASSERT_MSG(is_real<type_t>::value, \"determinant sign is not avalaible for complex matrices\");\n      //count modulo 2 the number of ipiv_ elements such that ipiv_(i) !=  i\n      return  nt2::prod(nt2::diag_of(lu_)(_))*signdet(false);\n    }\n\n    type_t absdet(itype_t & exponent)\n    {\n      BOOST_ASSERT_MSG(m_ ==  n_, \"non square matrix in determinant computation\");\n      // compute e and return m for matrix determinant such that |det| = ldexp(m, e)\n      // if no overflow or underflow can occur,  with 0.5 < abs(m) < 1\n      // the exponent result is enough to know the order of magnitude of the determinant\n      // (between 0.5*2^e and 2^e if the mantissa is non zero)\n      // This routine is inspired from linpack http://www.netlib.org/linpack/dgedi.f\n      // that use ten power factor instead\n      type_t   m1 = One<type_t>();\n      exponent = Zero<itype_t>();\n      for(size_t i = 1;  i <= size_t(n_); ++i)\n      {\n        itype_t e;\n        m1 *=  nt2::abs(nt2::frexp(nt2::abs(lu_(i, i)), e));\n        exponent+= e;\n      }\n      if (is_eqz(m1)){\n        exponent = Zero<itype_t>();\n      }\n      return m1;\n    }\n\n    type_t det(itype_t & exponent)\n    {\n      BOOST_ASSERT_MSG(m_ ==  n_, \"non square matrix in determinant computation\");\n      // compute e and m for matrix determinant such that det = ldexp(m, e)\n      // if no overflow or underflow can occur,  with 0.5 < abs(m) < 1\n      // the exponent result is enough to know the order of magnitude of the determinant\n      // (between 0.5*2^e and 2^e if the mantissa is non zero)\n      // This routine is inspired from linpack http://www.netlib.org/linpack/dgedi.f\n      // that use ten power factor instead\n      type_t   m1 = One<type_t>();\n      exponent = Zero<itype_t>();\n      for(size_t i = 1;  i <= size_t(n_); ++i)\n      {\n        itype_t e;\n        m1 *=  nt2::frexp(nt2::abs(lu_(i, i)), e);\n        exponent+= e;\n      }\n      if (is_eqz(m1)){\n        exponent = Zero<itype_t>();\n      }\n      return m1*signdet(false);\n    }\n\n    //==========================================================================\n    // Solver interface\n    //==========================================================================\n    template<class XPR> result_type solve(const XPR& b )\n    {\n      result_type bb = b;\n      inplace_solve(bb);\n      return bb;\n    }\n\n    //==========================================================================\n    // inverse matrix: DO NOT USE THAT TO SOLVE A SYSTEM\n    //==========================================================================\n    const tab_t& inv(bool warn = true)\n    {\n      if(isempty(invt_))\n      {\n        if (warn)\n        {\n          base_t rc = rcond();\n          NT2_WARNING ( (rc >= nt2::Eps<base_t>())\n                        , \"Matrix is close to singular or badly scaled.\"\n                        \" Results may be inaccurate.\"\n            );\n          return invt_;  /* it has been calculated by rcond */\n        }\n        invt_ = lu_;\n        nt2::details::getri(&n_, invt_.raw(), &ldlu_, ipiv_.raw(), &info_, w_);\n      }\n      return invt_;\n    }\n\n    template<class Xpr> void inplace_solve(Xpr& b )\n    {\n      BOOST_ASSERT_MSG(issquare(a_), \"matrix must be square to use the lu solver\");\n      nt2_la_int nrhs = nt2::size(b, 2);\n      nt2_la_int ldb  = b.leading_size();\n      tab_t x(b);\n      nt2_la_int ldx  = x.leading_size();\n      btab_t ferr(of_size(nrhs, 1)), berr(of_size(nrhs, 1));\n      btab_t r_(of_size(n_, 1)), c_(of_size(n_, 1));\n      char equed = 'N';\n      base_t rc = rcond();\n      nt2::details::gesvx(nt2::details::lapack_option('F'),\n                          nt2::details::lapack_option('N'),\n                          &n_, &nrhs,\n                          a_.raw(), &ldlu_,\n                          lu_.raw(), &ldlu_,\n                          ipiv_.raw(),\n                          &equed,\n                          r_.raw(),\n                          c_.raw(),\n                          b.raw(), &ldb,\n                          x.raw(), &ldx,\n                          &rc,\n                          ferr.raw(),\n                          berr.raw(),\n                          &info_,\n                          w_);\n      b = x;\n    }\n\n  private:\n    data_t                            a_;\n    tab_t                            lu_;\n    nt2_la_int                     m_,n_;\n    nt2_la_int                     ldlu_;\n    ibuf_t                         ipiv_;\n    nt2_la_int                     info_;\n    workspace_t                       w_;\n    tab_t                             p_;\n    itab_t                           ip_;\n    tab_t                            pl_;\n    tab_t                          invt_;\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "2962ff12452899d6f533e99955e4a8930a8951cb", "size": 17438, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/toolbox/linalg/functions/details/lu.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/linalg/include/nt2/toolbox/linalg/functions/details/lu.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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": "modules/core/linalg/include/nt2/toolbox/linalg/functions/details/lu.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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.8374164811, "max_line_length": 123, "alphanum_fraction": 0.488932217, "num_tokens": 4392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.532697263046891}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_SSE_SSE2_AVERAGE_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_SSE_SSE2_AVERAGE_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT\n#include <boost/simd/arithmetic/functions/average.hpp>\n#include <boost/simd/include/functions/simd/bitwise_and.hpp>\n#include <boost/simd/include/functions/simd/bitwise_xor.hpp>\n#include <boost/simd/include/functions/simd/plus.hpp>\n#include <boost/simd/include/functions/simd/multiplies.hpp>\n#include <boost/simd/include/functions/simd/shrai.hpp>\n#include <boost/simd/include/constants/half.hpp>\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::average_, boost::simd::tag::sse2_,\n                          (A0),\n                          ((simd_<arithmetic_<A0>,boost::simd::tag::sse_>))\n                          ((simd_<arithmetic_<A0>,boost::simd::tag::sse_>))\n                         )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return b_and(a0, a1)+shrai(b_xor(a0, a1),1);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::average_, boost::simd::tag::sse2_,\n                          (A0),\n                          ((simd_<uint16_<A0>,boost::simd::tag::sse_>))\n                          ((simd_<uint16_<A0>,boost::simd::tag::sse_>))\n                         )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return b_and(a0, a1)+shrai(b_xor(a0, a1),1);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::average_, boost::simd::tag::sse2_,\n                          (A0),\n                          ((simd_<uint8_<A0>,boost::simd::tag::sse_>))\n                          ((simd_<uint8_<A0>,boost::simd::tag::sse_>))\n                         )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return b_and(a0, a1)+shrai(b_xor(a0, a1),1);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::average_, boost::simd::tag::sse2_,\n                          (A0),\n                          ((simd_<floating_<A0>,boost::simd::tag::sse_>))\n                          ((simd_<floating_<A0>,boost::simd::tag::sse_>))\n                         )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n       return (a0+a1)*boost::simd::Half<A0>();\n    }\n  };\n} } }\n#endif\n#endif\n", "meta": {"hexsha": "c8425700cde40478d23689f6bd69cd8ff5021235", "size": 3087, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/simd/sse/sse2/average.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/simd/sse/sse2/average.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/simd/sse/sse2/average.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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.0759493671, "max_line_length": 88, "alphanum_fraction": 0.5332037577, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5326126647527784}}
{"text": "#include \"energies.h\"\n\n#include \"bond.h\"\n\n#include <Eigen/Dense>\n#include <memory>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n\n\ndouble calculate_kinetic_energy(const Eigen::MatrixXd& velocities, const Eigen::MatrixXd& masses) {\n    return (masses.transpose()  * velocities.rowwise().squaredNorm()).sum() / 2.0;\n}\n\ndouble calculate_potential_energy(const std::vector<std::unique_ptr<Bond>>& bonds, const Eigen::MatrixXd& positions) {\n    std::vector<double> potential_energies;\n    potential_energies.reserve(bonds.size());\n    std::transform(bonds.begin(), bonds.end(), std::back_inserter(potential_energies),\n    [positions](const auto& bond){ return bond->energy(positions);});\n    \n    return std::accumulate(potential_energies.begin(),\n                                                  potential_energies.end(),\n                                                    0.0\n                                                   );\n}\n", "meta": {"hexsha": "cfc4de54862f47817a2806abd85394dd6b72bc22", "size": 943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/energies.cpp", "max_stars_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_stars_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/energies.cpp", "max_issues_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_issues_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/energies.cpp", "max_forks_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_forks_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_forks_repo_licenses": ["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.9259259259, "max_line_length": 118, "alphanum_fraction": 0.6097560976, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5326126592165317}}
{"text": "#ifndef RADIUMENGINE_VECTOR_HPP\n#define RADIUMENGINE_VECTOR_HPP\n\n/// This file contains definitions of aliases for basic vector classes and functions\n\n#include <Core/RaCore.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Sparse>\n#include <functional>\n#include <unsupported/Eigen/AlignedVector3>\n\n#include <Core/Math/Math.hpp>\n\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 {\nnamespace Core {\nnamespace Math {\n//\n// Common vector types\n//\nusing VectorN = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\nusing VectorNf = Eigen::VectorXf;\nusing VectorNd = Eigen::VectorXd;\n\nusing Vector4 = Eigen::Matrix<Scalar, 4, 1>;\nusing Vector4f = Eigen::Vector4f;\nusing Vector4d = Eigen::Vector4d;\n\n#ifndef CORE_USE_ALIGNED_VEC3\nusing Vector3 = Eigen::Matrix<Scalar, 3, 1>;\nusing Vector3f = Eigen::Vector3f;\nusing Vector3d = Eigen::Vector3d;\n#else\nusing Vector3 = Eigen::AlignedVector3<Scalar>;\nusing Vector3f = Eigen::AlignedVector3<float>;\nusing Vector3d = Eigen::AlignedVector3<double>;\n#endif\n\nusing Vector2 = Eigen::Matrix<Scalar, 2, 1>;\nusing Vector2f = Eigen::Vector2f;\nusing Vector2d = Eigen::Vector2d;\n\nusing VectorNi = Eigen::VectorXi;\nusing Vector2i = Eigen::Vector2i;\nusing Vector3i = Eigen::Vector3i;\nusing Vector4i = Eigen::Vector4i;\n\nusing VectorNui = Eigen::Matrix<uint, Eigen::Dynamic, 1>;\nusing Vector2ui = Eigen::Matrix<uint, 2, 1>;\nusing Vector3ui = Eigen::Matrix<uint, 3, 1>;\nusing Vector4ui = Eigen::Matrix<uint, 4, 1>;\n\n//\n// Common matrix types\n//\n\nusing MatrixN = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\nusing Matrix4 = Eigen::Matrix<Scalar, 4, 4>;\nusing Matrix3 = Eigen::Matrix<Scalar, 3, 3>;\nusing Matrix2 = Eigen::Matrix<Scalar, 2, 2>;\n\nusing MatrixNf = Eigen::MatrixXf;\nusing Matrix4f = Eigen::Matrix4f;\nusing Matrix3f = Eigen::Matrix3f;\nusing Matrix2f = Eigen::Matrix2f;\n\nusing MatrixNd = Eigen::MatrixXd;\nusing Matrix4d = Eigen::Matrix4d;\nusing Matrix3d = Eigen::Matrix3d;\nusing Matrix2d = Eigen::Matrix2d;\n\nusing MatrixNui = Eigen::Matrix<uint, Eigen::Dynamic, Eigen::Dynamic>;\n\n// using Diagonal = Eigen::DiagonalMatrix< Scalar, Eigen::Dynamic >;\nusing Diagonal =\n    Eigen::SparseMatrix<Scalar>; // Not optimized for Diagonal matrices, but the operations between\n                                 // Sparse and Diagonal are not defined\nusing Sparse = Eigen::SparseMatrix<Scalar>;\n\n//\n// Transforms and rotations\n//\n\nusing Quaternion = Eigen::Quaternion<Scalar>;\nusing Quaternionf = Eigen::Quaternionf;\nusing Quaterniond = Eigen::Quaterniond;\n\nusing Transform = Eigen::Transform<Scalar, 3, Eigen::Affine>;\nusing Transformf = Eigen::Affine3f;\nusing Transformd = Eigen::Affine3d;\n\nusing Aabb = Eigen::AlignedBox<Scalar, 3>;\nusing Aabbf = Eigen::AlignedBox3f;\nusing Aabbd = Eigen::AlignedBox3d;\n\nusing AngleAxis = Eigen::AngleAxis<Scalar>;\nusing AngleAxisf = Eigen::AngleAxisf;\nusing AngleAxisd = Eigen::AngleAxisd;\n\nusing Translation = Eigen::Translation<Scalar, 3>;\nusing Translationf = Eigen::Translation3f;\nusing Translationd = Eigen::Translation3d;\n\ninline void print( const MatrixN& matrix );\n\n//\n// Geometry types\n//\n\nusing Line2 = Eigen::ParametrizedLine<Scalar, 2>;\nusing Line3 = Eigen::ParametrizedLine<Scalar, 3>;\nusing Plane3 = Eigen::Hyperplane<Scalar, 3>;\n\n// Todo : storage transform using quaternions ?\n\n//\n// Misc types\n//\nusing Color = Vector4;\nusing Colorf = Vector4f;\nusing Colord = Vector4d;\n\n//\n// Vector Functions\n//\nnamespace Vector {\n\n/// Component-wise floor() function on a floating-point vector.\ntemplate <typename Vector>\ninline Vector floor( const Vector& v );\n\n/// Component-wise ceil() function on a floating-point vector.\ntemplate <typename Vector>\ninline Vector ceil( const Vector& v );\n\n/// Component-wise trunc() function on a floating-point vector\ntemplate <typename Vector>\ninline Vector trunc( const Vector& v );\n\n/// Component-wise clamp() function on a floating-point vector.\ntemplate <typename Vector>\ninline Vector clamp( const Vector& v, const Vector& min, const Vector& max );\n\n/// Component-wise clamp() function on a floating-point vector.\ntemplate <typename Vector>\ninline Vector clamp( const Vector& v, const Scalar& min, const Scalar& max );\n\n/// Vector range check, works for any numeric vector.\ntemplate <typename Vector_>\ninline bool checkRange( const Vector_& v, const Scalar& min, const Scalar& max );\n\n/// Call std::isnormal on vector entries.\ntemplate <typename Vector_>\ninline bool checkInvalidNumbers( Eigen::Ref<const Vector_> v, const bool FAIL_ON_ASSERT = false );\n\n/// Get two vectors orthogonal to a given vector.\ninline void getOrthogonalVectors( const Vector3& fx, Eigen::Ref<Vector3> fy,\n                                  Eigen::Ref<Vector3> fz );\n\n/// Get the angle between two vectors. Works for types where the cross product is\n/// defined (i.e. 2D and 3D vectors).\ntemplate <typename Vector_>\ninline Scalar angle( const Vector_& v1, const Vector_& v2 );\n\n/// Get the spherical linear interpolation between two unit non-colinear vectors.\n/// works for types where the cross-product is defined (i.e. 2D and 3D vectors).\ntemplate <typename Vector_>\ninline Vector_ slerp( const Vector_& v1, const Vector_& v2, Scalar t );\n\n/// @return the projection of point on the plane define by plane and planeNormal\ninline Vector3 projectOnPlane( const Vector3& planePos, const Vector3& planeNormal,\n                               const Vector3& point );\n\n/// Get the cotangent of the angle between two vectors. Works for vector types where\n/// dot and cross product is defined (2D or 3D vectors).\ntemplate <typename Vector_>\ninline Scalar cotan( const Vector_& v1, const Vector_& v2 );\n\n/// Get the cosine of the angle between two vectors.\ntemplate <typename Vector_>\ninline Scalar cos( const Vector_& v1, const Vector_& v2 );\n\n/// Normalize a vector and returns its norm before normalization.\n/// If the vector's norm is 0, the vector's components will be overwritten by NaNs\ntemplate <typename Vector_>\ninline Scalar getNormAndNormalize( Vector_& v );\n\n/// Normalize a vector and returns its norm before normalization.\n/// If the vector's norm is 0, the vector remains null\ntemplate <typename Vector_>\ninline Scalar getNormAndNormalizeSafe( Vector_& v );\n\n} // namespace Vector\n\nnamespace MatrixUtils {\ninline Matrix4 lookAt( const Vector3& position, const Vector3& target, const Vector3& up );\ninline Matrix4 perspective( Scalar fovy, Scalar aspect, Scalar near, Scalar zfar );\ninline Matrix4 orthographic( Scalar left, Scalar right, Scalar bottom, Scalar top, Scalar near,\n                             Scalar zfar );\n\n/// Call std::isnormal on matrix entry.\n/// Dense version\ntemplate <typename Matrix_>\ninline bool checkInvalidNumbers( Eigen::Ref<const Matrix_> matrix,\n                                 const bool FAIL_ON_ASSERT = false );\n\n} // namespace MatrixUtils\n\n//\n// Quaternion functions\n//\nnamespace QuaternionUtils {\n// Define functions for multiplying a quaternion by a scalar\n// and adding two quaternions. While Quaternion is supposed to\n// represent a unit quaternion (thus a valid rotation), these functions\n// are useful for linear interpolation of quaternions.\n\n/// Returns the quaternion q multipled by a scalar factor of k.\ninline Quaternion scale( const Quaternion& q, const Scalar k );\n\n/// Returns the sum of two quaternions.\ninline Quaternion add( const Quaternion& q1, const Quaternion& q2 );\n\n/// Returns the sum of two quaternions, resolving antipodality by flipping\n/// the sign of q2 if q1.q2 is negative. This operation is usually\n/// denoted as a circled + sign, forming the basis of the QLERP algorithm.\n/// See \"Spherical Blend Skinning\" (Kavan & Zara 2005) for more details.\ninline Quaternion addQlerp( const Quaternion& q1, const Quaternion& q2 );\n\n// Note : the .inl file also define operator+ for quaternions\n// and operator * and / between quaternions and scalar.\n\n/// Decompose a given rotation Qin into a swing rotation and a twist rotation.\n/// Qswing is a rotation whose axis lies in the XY plane and Qtwist is a rotation about axis Z.\n/// such as Qin = Qswing * Qtwist\n/// If the rotation is already around axis z, Qswing will be set to identity\n/// and Qtwist equal to Qin\ninline void getSwingTwist( const Quaternion& in, Quaternion& swingOut, Quaternion& twistOut );\n\n/// Call std::isnormal on quaternion entries.\ntemplate <typename Quaternion_>\ninline 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} // namespace QuaternionUtils\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} // namespace Math\n} // namespace Core\n} // namespace Ra\n\n#include <Core/Math/LinearAlgebra.inl>\n\n#endif // RADIUMENGINE_VECTOR_HPP\n", "meta": {"hexsha": "a10b9fcc06d9ad22f6df3881d266d5a718a31f8b", "size": 9148, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/Math/LinearAlgebra.hpp", "max_stars_repo_name": "sylvaindeker/Radium-Engine", "max_stars_repo_head_hexsha": "64164a258b3f7864c73a07c070e49b7138488d62", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-04-16T13:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-16T13:55:45.000Z", "max_issues_repo_path": "src/Core/Math/LinearAlgebra.hpp", "max_issues_repo_name": "sylvaindeker/Radium-Engine", "max_issues_repo_head_hexsha": "64164a258b3f7864c73a07c070e49b7138488d62", "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": "sylvaindeker/Radium-Engine", "max_forks_repo_head_hexsha": "64164a258b3f7864c73a07c070e49b7138488d62", "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.2621722846, "max_line_length": 99, "alphanum_fraction": 0.73972453, "num_tokens": 2213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5326126423363652}}
{"text": "#include \"setup_skinning_handles.h\"\n#include \"kmeans_clustering.h\"\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <iostream>\n#include <igl/boundary_conditions.h>\n#include <igl/lbs_matrix.h>\n#include <igl/bbw.h>\n#include <unsupported/Eigen/KroneckerProduct>\n#include <igl/slice_into.h>\n#include <igl/remove_unreferenced.h>\n#include <igl/normalize_row_sums.h>\n#include <igl/writeOBJ.h>\n\nusing namespace Eigen;\nusing namespace std;\nMatrixXd bbw_strain_skinning_matrix(VectorXi& handles, const MatrixXd& mV, MatrixXi& mT){\n    std::set<int> unique_vertex_handles;\n    std::set<int>::iterator it;\n    //from the tet handle indexes, get the unique verts that can act as handles\n    for(int i=0; i<handles.size(); i++){\n        unique_vertex_handles.insert(mT(handles[i], 0));\n        unique_vertex_handles.insert(mT(handles[i], 1));\n        unique_vertex_handles.insert(mT(handles[i], 2));\n        unique_vertex_handles.insert(mT(handles[i], 3));\n    }\n\n    int i=0;\n    it = unique_vertex_handles.end();\n    VectorXi map_verts_to_unique_verts = VectorXi::Zero(*(--it)+1).array() -1;\n    for (it=unique_vertex_handles.begin(); it!=unique_vertex_handles.end(); ++it){\n        map_verts_to_unique_verts[*it] = i;\n        i++;\n    }\n\n    MatrixXi vert_to_tet = MatrixXi::Zero(handles.size(), 4);\n    i=0;\n    for(i=0; i<handles.size(); i++){\n        vert_to_tet.row(i)[0] = map_verts_to_unique_verts[mT.row(handles[i])[0]];\n        vert_to_tet.row(i)[1] = map_verts_to_unique_verts[mT.row(handles[i])[1]];\n        vert_to_tet.row(i)[2] = map_verts_to_unique_verts[mT.row(handles[i])[2]];\n        vert_to_tet.row(i)[3] = map_verts_to_unique_verts[mT.row(handles[i])[3]];\n    }\n    \n    MatrixXd C = MatrixXd::Zero(unique_vertex_handles.size(), 3);\n    VectorXi P = VectorXi::Zero(unique_vertex_handles.size());\n    i=0;\n    for (it=unique_vertex_handles.begin(); it!=unique_vertex_handles.end(); ++it){\n        C.row(i) = mV.row(*it);\n        P(i) = i;\n        i++;\n    }\n\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    cout<<\"---------0--------\"<<endl;\n    igl::boundary_conditions(mV, mT, C, P, MatrixXi(), MatrixXi(), b, bc);\n    // compute BBW weights matrix\n    igl::BBWData bbw_data;\n    // only a few iterations for sake of demo\n    bbw_data.active_set_params.max_iter = 100;\n    bbw_data.verbosity = 2;\n    \n    MatrixXd W, M;\n    cout<<\"---------1--------\"<<endl;\n    if(!igl::bbw(mV, mT, b, bc, bbw_data, W))\n    {\n        std::cout<<\"EXIT: Error here\"<<std::endl;\n        exit(0);\n        return MatrixXd();\n    }\n    cout<<\"---------2--------\"<<endl;\n\n    // Normalize weights to sum to one\n    igl::normalize_row_sums(W,W);\n    cout<<\"---------3--------\"<<endl;\n\n    // precompute linear blend skinning matrix\n    igl::lbs_matrix(mV,W,M);\n    cout<<\"---------4--------\"<<endl;\n\n    MatrixXd tW = MatrixXd::Zero(mT.rows(), handles.size());\n    for(int t =0; t<mT.rows(); t++){\n        VectorXi e = mT.row(t);\n        for(int h=0; h<handles.size(); h++){\n            if(t==handles[h]){\n                tW.row(t) *= 0;\n                tW(t,h) = 1;\n                break;\n            }\n            double p0 = 0;\n            double p1 = 0;\n            double p2 = 0;\n            double p3 = 0;\n            for(int j=0; j<vert_to_tet.cols(); ++j){\n                p0 += W(e[0], vert_to_tet(h, j));\n                p1 += W(e[1], vert_to_tet(h, j));\n                p2 += W(e[2], vert_to_tet(h, j));\n                p3 += W(e[3], vert_to_tet(h, j));\n            }\n            tW(t, h) = (p0+p1+p2+p3)/4;  \n        }\n    }\n    cout<<\"---------5--------\"<<endl;\n    igl::normalize_row_sums(tW, tW);\n\n    cout<<\"---------6--------\"<<endl;\n    return tW;\n}\n\nVector3d tet_center(MatrixXi& T, MatrixXd& V, int ind){\n    Vector3d v1 = V.row(T.row(ind)[0]);\n    Vector3d v2 = V.row(T.row(ind)[1]);\n    Vector3d v3 = V.row(T.row(ind)[2]);\n    Vector3d v4 = V.row(T.row(ind)[3]);\n\n    return (v1 + v2 + v3 + v4)/4;\n}\n\nMatrixXd setup_skinning_helper(int indx, \n    int nsh_on_component, \n    MatrixXi& mT, \n    MatrixXd& mV, \n    SparseMatrix<double>& mC, \n    SparseMatrix<double>& mA, \n    VectorXd& mx0, \n    std::map<int, std::vector<int>>& ms_handle_elem_map){\n\n\n    VectorXi handles_ind = VectorXi::Zero(nsh_on_component);\n    VectorXd CAx0 = mC*mA*mx0;\n\n\n    for(int k=0; k<nsh_on_component; k++){\n        std::vector<int> els = ms_handle_elem_map[indx-k];\n        double centx = 0;//= VectorXd::Zero(els.size());\n        double centy = 0;//= VectorXd::Zero(els.size());\n        double centz = 0;//= VectorXd::Zero(els.size());\n        Vector3d avg_cent;\n        for(int i=0; i<els.size(); i++){\n            centx += CAx0[12*els[i]];\n            centy += CAx0[12*els[i]+1];\n            centz += CAx0[12*els[i]+2];\n        }\n        \n        avg_cent<<centx/els.size(), centy/els.size(), centz/els.size();\n        int minind = 0;\n        double mindist = (avg_cent - tet_center(mT, mV, 0)).norm();\n        for(int i=1; i<mT.rows(); i++){\n            double dist = (avg_cent - tet_center(mT, mV, i)).norm();\n            if(dist<mindist){\n                mindist = dist;\n                minind = i;\n            }\n        }\n      \n        handles_ind[k] = minind;\n    }\n\n\n    for(int i =0; i<handles_ind.size(); i++){\n        std::cout<<tet_center(mT, mV, handles_ind[i])<<std::endl;\n    }\n  \n    return bbw_strain_skinning_matrix(handles_ind, mV, mT);\n\n}\n\nvoid setup_skinning_handles(int nsh, bool reduced, const MatrixXi& mT, const MatrixXd& mV, std::vector<VectorXi>& ibones, std::vector<VectorXi>& imuscle,\n\tSparseMatrix<double>& mC, SparseMatrix<double>& mA, MatrixXd& mG, VectorXd& mx0, VectorXd& mred_s, MatrixXd& msW, std::map<int, std::vector<int>>& ms_handle_elem_map){\n    \n    std::cout<<\"+ Skinning Handles\"<<std::endl;\n    VectorXi skinning_elem_cluster_map;\n    std::map<int, std::vector<int>> skinning_cluster_elem_map;\n\n    if(nsh<(ibones.size()+imuscle.size())){\n        std::cout<<\"Too few skinning handles, too many components\"<<std::endl;\n        exit(0);\n    }\n\n    if(nsh==0){\n        nsh = mT.rows();\n    } \n    \n\n    //-----------------------------------------------------\n    if(nsh==mT.rows() && reduced==false){\n    //unreduced\n        for(int i=0; i<mT.rows(); i++){\n            skinning_elem_cluster_map[i] = i;\n        }   \n    }else{\n        kmeans_clustering(skinning_elem_cluster_map, nsh, ibones, imuscle, mG, mC, mA, mx0);\n    }\n\n\n    for(int i=0; i<mT.rows(); i++){\n        ms_handle_elem_map[skinning_elem_cluster_map[i]].push_back(i);\n    }\n    //------------------------------------------------------\n\n    if(reduced==false){\n        mred_s.resize(6*mT.rows());\n        for(int i=0; i<mT.rows(); i++){\n            mred_s[6*i+0] = 1; \n            mred_s[6*i+1] = 1; \n            mred_s[6*i+2] = 1; \n            mred_s[6*i+3] = 0; \n            mred_s[6*i+4] = 0; \n            mred_s[6*i+5] = 0;\n        }\n        return;\n    \n    }\n    if(nsh==mT.rows()){\n        std::cout<<\"Too many skinning handles. \"<<std::endl;\n        exit(0);\n    }\n\n    mred_s.resize(6*nsh);\n    for(int i=0; i<nsh; i++){\n        mred_s[6*i+0] = 1; \n        mred_s[6*i+1] = 1; \n        mred_s[6*i+2] = 1; \n        mred_s[6*i+3] = 0; \n        mred_s[6*i+4] = 0; \n        mred_s[6*i+5] = 0;\n    }\n\n\n    //blocked construction of full skinning weights matrix\n    MatrixXd sW = MatrixXd::Zero(mT.rows(), nsh);\n    sW.setZero();\n    int maxnsh = nsh;\n    cout<<\"----------Bone HANDLES------------\"<<maxnsh<<\"--\"<<ms_handle_elem_map.size()<<endl;\n    int insert_index = 0;\n    for(int b=0; b<ibones.size(); b++){\n        MatrixXi subT(ms_handle_elem_map[maxnsh - 1 - insert_index].size(), 4);\n        MatrixXi componentT;\n        MatrixXd componentV;\n        VectorXi J;\n\n        for(int i=0; i<ms_handle_elem_map[maxnsh -1 - insert_index].size() ; i++){\n            subT.row(i) = mT.row(ms_handle_elem_map[maxnsh -1 - insert_index][i]);\n        }\n\n        igl::remove_unreferenced(mV, subT, componentV, componentT, J);\n\n        std::string nam = \"bone\"+to_string(b)+\".obj\";\n\n        igl::writeOBJ(nam, componentV, componentT);\n\n        MatrixXd sWi = setup_skinning_helper(maxnsh-1- insert_index , 1, componentT, componentV, mC, mA, mx0, ms_handle_elem_map);\n        \n        MatrixXd sWslice = MatrixXd::Zero(mT.rows(), sWi.cols());\n        igl::slice_into(sWi , ibones[b], 1, sWslice);\n        sW.block(0,insert_index, mT.rows(), sWi.cols()) = sWslice;\n        nsh = nsh - 1; //bone skinning handle has been made, so decrease nsh by 1\n        insert_index += 1;\n    }\n\n    cout<<\"----------MUSCLE HANDLES----\"<<nsh<<\"---\"<<insert_index<<\"-----\"<<endl;\n    int number_handles_per_muscle = nsh/imuscle.size();\n    for(int m=0; m<imuscle.size(); m++){ //through muscle vector\n        MatrixXi componentT;\n        MatrixXd componentV;\n        MatrixXi subT(imuscle[m].size(), 4);\n        VectorXi J;\n        for(int i=0; i<imuscle[m].size() ; i++){\n            subT.row(i) = mT.row(imuscle[m][i]);\n        }\n        igl::remove_unreferenced(mV, subT, componentV, componentT, J);\n        std::string nam = \"muscle\"+to_string(m)+\".obj\";\n        igl::writeOBJ(nam, componentV, componentT);\n        MatrixXd sWi;\n        if(m==imuscle.size()-1){\n            //Deal with remainder handles\n            sWi = setup_skinning_helper(maxnsh - 1 - insert_index, nsh, componentT, componentV, mC, mA, mx0, ms_handle_elem_map);\n        }else{\n            sWi = setup_skinning_helper(maxnsh - 1 - insert_index, number_handles_per_muscle, componentT, componentV, mC, mA, mx0, ms_handle_elem_map );\n        }\n\n        MatrixXd sWslice = MatrixXd::Zero(mT.rows(), sWi.cols());\n        \n        igl::slice_into(sWi , imuscle[m], 1, sWslice);\n        sW.block(0,insert_index, mT.rows(), sWi.cols()) = sWslice;\n        insert_index += number_handles_per_muscle;\n        nsh =  nsh - number_handles_per_muscle;\n    }\n    assert(nsh==0);\n\n    MatrixXd Id6 = MatrixXd::Identity(6, 6);\n    msW =  Eigen::kroneckerProduct(sW, Id6);\n \n    std::cout<<\"- Skinning Handles\"<<std::endl;\n}\n\n", "meta": {"hexsha": "63cae62a3221f88e7079275adb72dd9ba918118a", "size": 10077, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PreProcessing/setup_skinning_handles.cpp", "max_stars_repo_name": "alecjacobson/fast_muscles", "max_stars_repo_head_hexsha": "92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-09T08:28:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T08:28:39.000Z", "max_issues_repo_path": "PreProcessing/setup_skinning_handles.cpp", "max_issues_repo_name": "alecjacobson/fast_muscles", "max_issues_repo_head_hexsha": "92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PreProcessing/setup_skinning_handles.cpp", "max_forks_repo_name": "alecjacobson/fast_muscles", "max_forks_repo_head_hexsha": "92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4", "max_forks_repo_licenses": ["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.59, "max_line_length": 168, "alphanum_fraction": 0.5598888558, "num_tokens": 3006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5326126367458331}}
{"text": "// -------------------------------------------------------------------\n// $ProjectName     : DiagramDistanceRunner_D64\n// $FileName        : DiagramDistanceRunner_D64.cpp$\n// $Programmer      : Tran Quoc Hoan$\n// -------------------------------------------------------------------\n\n#include \"stdafx.h\"\n#include \"fstream\"\n#include <ostream>\n#include <filesystem>\n\n#include \"DiagramDistanceRunner_D64.h\"\n#include \"../KernelStatsUtils_D64/KernelFisherDA.h\"\n#include \"../KernelStatsUtils_D64/MultiScaleKernel.h\"\n#include \"../KernelStatsUtils_D64/RiemannianManifoldKernel.h\"\n#include \"../PersistenceUtils_D64/PersistenceBarcodes.h\"\n#include \"../PersistenceUtils_D64/PersistenceDeclarations.h\"\n#include \"../PersistenceUtils_D64/PersistenceUtils_D64.h\"\n\n#include \"../TopoUtils_D64/FileUtils.h\"\n#include \"../TopoUtils_D64/StringUtils.h\"\n\n#include <boost/program_options.hpp>\n#include <boost/iostreams/device/file.hpp>\n#include <boost/iostreams/stream.hpp>\n#include <Eigen/Dense>\n\nusing namespace boost::program_options;\nusing namespace NPersistenceUtils;\nusing namespace NKernelStatsUtils;\nusing namespace Eigen;\nnamespace fs = std::experimental::filesystem;\n\nnamespace NDiagramDistanceRunner {\n    using namespace NMultiScaleKernelUtils;\n    typedef Eigen::Matrix<FType, Dynamic, Dynamic> MaxtrixFType;\n\n    enum KernelType {\n        L2_INNER_MULTI_SCALE_SSE,\n        L2_SQUARE_DIST,\n        SLICE_WASS,\n        L2_INNER_MULTI_SCALE_NOSSE,\n        RIEMANNIAN_METRIC,\n    };\n\n    template <class Dtype>\n    struct KernelPrm {\n        KernelType kertype = KernelType::L2_INNER_MULTI_SCALE_SSE;\n        Dtype T1 = (Dtype)1.0;\n        Dtype T2 = (Dtype)1.0; // T_2 = time_hole * time_rate\n        size_t theta_ndirs = 1;\n        size_t phi_ndirs = 1;\n        Dtype gamma = (Dtype)1.0;\n        std::wstring postfix = L\"\";\n    };\n\n    bool KernelProduct(FType &result, CPersistenceBarcodesPtr<FType> &bar1, CPersistenceBarcodesPtr<FType> &bar2, KernelPrm<FType>& prm) {\n        auto T1 = prm.T1;\n        auto T2 = prm.T2;\n\n        switch (prm.kertype)\n        {\n        case KernelType::L2_INNER_MULTI_SCALE_SSE:\n            L2DiagramMskInnerProductSSE(result, bar1->barcodes(), bar2->barcodes(), T1, T2);\n            break;\n        case KernelType::L2_SQUARE_DIST:\n            L2DiagramMskDistanceSquare(result, bar1->barcodes(), bar2->barcodes(), T1);\n            break;\n        case KernelType::L2_INNER_MULTI_SCALE_NOSSE:\n            L2DiagramMskInnerProduct(result, bar1->barcodes(), bar2->barcodes(), T1, T2);\n            break;\n        case KernelType::RIEMANNIAN_METRIC:\n            NRiemannianManifoldKernelUtils::RiemannGeodesicMetric(result, bar1->barcodes(), bar2->barcodes(), T1, T2);\n            break;\n        default:\n            break;\n        }\n        return true;\n    }\n\n    MaxtrixFType KernelVecsProduct(TypeBarcodesPtrVec<FType> diagram_vecs, KernelPrm<FType>& prm) {\n        std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n\n        size_t num_diagrams = diagram_vecs.size();\n        MaxtrixFType gram_mat(num_diagrams, num_diagrams);\n\n        for (size_t i = 0; i < num_diagrams; ++i) {\n            auto total = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - begin).count();\n            auto hours = total / 3600;\n            auto mins = (total - hours * 3600) / 60;\n            auto secs = total - hours * 3600 - mins * 60;\n            std::cout << \"Ellapsed time (h:m:s)= \" << hours << \":\" << mins << \":\" << secs << \n                \", Index of diagram: \" << i << \" per total of \" << num_diagrams << std::endl;\n\n            // multi-threads\n            concurrency::parallel_for(i, num_diagrams, [&](size_t j) {\n                FType result(0);\n                KernelProduct(result, diagram_vecs[i], diagram_vecs[j], prm);\n                gram_mat(i, j) = result;\n                //std::cout << i << \" \" << j << \" \" << diagram_vecs[i]->numbars() \n                //    << \" \" << diagram_vecs[j]->numbars() << std::endl;\n                return true;\n            });\n        }\n        // gram matrix should be symmetric\n        for (int i = 0; i < num_diagrams; ++i) {\n            for (int j = 0; j < i; ++j) {\n                gram_mat(i, j) = gram_mat(j, i);\n            }\n        }\n        return gram_mat;\n    }\n\n    MaxtrixFType KernelVecsProduct(TypeBarcodesPtrVec<FType> dvecs1, TypeBarcodesPtrVec<FType> dvecs2, KernelPrm<FType>& prm) {\n        std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n        size_t nums1 = dvecs1.size();\n        size_t nums2 = dvecs2.size();\n        if (nums1 == 0) return KernelVecsProduct(dvecs2, prm);\n        if (nums2 == 0) return KernelVecsProduct(dvecs1, prm);\n\n        MaxtrixFType gram_mat(nums1, nums2);\n\n        for (size_t i = 0; i < nums1; ++i) {\n            auto total = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - begin).count();\n            auto hours = total / 3600;\n            auto mins = (total - hours * 3600) / 60;\n            auto secs = total - hours * 3600 - mins * 60;\n            std::cout << \"Ellapsed time (h:m:s)= \" << hours << \":\" << mins << \":\" << secs <<\n                \", Index of diagram: \" << i << \" per total of \" << nums1 << std::endl;\n            \n            // multi-threads\n            concurrency::parallel_for((size_t)0, nums2, [&](size_t j) {\n                FType result(0);\n                KernelProduct(result, dvecs1[i], dvecs2[j], prm);\n                gram_mat(i, j) = result;\n                return true;\n            });\n        }\n        return gram_mat;\n    }\n\n    // Get the median of an unordered set of numbers of arbitrary \n    // type without modifying the underlying dataset.\n    template <typename It>\n    auto GetMedian(It begin, It end)\n    {\n        using T = typename std::iterator_traits<It>::value_type;\n        std::vector<T> data(begin, end);\n        std::nth_element(data.begin(), data.begin() + data.size() / 2, data.end());\n        return data[data.size() / 2];\n    }\n\n    bool FindOptimalTimeHole(TypeBarcodesPtrVec<FType> dvecs, FType &tHole) {\n        if(dvecs.empty())\n            return false;\n        auto N = dvecs.size();\n        std::vector<FType> time_hole(N, (FType)0.0);\n        concurrency::parallel_for((size_t)0, N, [&](size_t z) {\n            time_hole[z] = dvecs[z]->GetOptimalTimeHole();\n        });\n\n        tHole = GetMedian(time_hole.begin(), time_hole.end());\n        return true;\n    }\n    bool FindOptimalTimeHole(TypeBarcodesPtrVec<FType> dvecs1, TypeBarcodesPtrVec<FType> dvecs2, FType &tHole) {\n        TypeBarcodesPtrVec<FType> dvecs = dvecs1;\n        dvecs.insert(dvecs.end(), dvecs2.begin(), dvecs2.end());\n        FindOptimalTimeHole(dvecs, tHole);\n        return true;\n    }\n\n    bool MakeGramMatAndSaveResultToFile(TypeBarcodesPtrVec<FType> dvecs1, TypeBarcodesPtrVec<FType> dvecs2,\n        std::wstring& output_path, KernelPrm<FType>& prm) {\n        std::cout << \"Computing gram matrix and save to file: \" << NStringUtil::_w2s(output_path) << std::endl;\n        fs::path opath(output_path);\n        if (prm.kertype == KernelType::L2_INNER_MULTI_SCALE_NOSSE ||\n            prm.kertype == KernelType::L2_INNER_MULTI_SCALE_SSE ||\n            prm.kertype == KernelType::L2_SQUARE_DIST ||\n            prm.kertype == KernelType::RIEMANNIAN_METRIC) {\n            if (prm.T1 == 0.0) FindOptimalTimeHole(dvecs1, dvecs2, prm.T1);\n            std::cout << \"Optimal T1 = \" << prm.T1 << \", T2 = \" << prm.T2 << std::endl;\n        }\n\n        MaxtrixFType gram_mat = KernelVecsProduct(dvecs1, dvecs2, prm);\n\n        const size_t rows = gram_mat.rows();\n        const size_t cols = gram_mat.cols();\n\n        std::wstring outfile = output_path;\n        if (fs::is_directory(opath)) {\n            fs::path file(prm.postfix + L\".txt\");\n            outfile = (opath / file).c_str();\n        }\n\n        // create folder if not exist\n        fs::path p(outfile);\n        fs::path dir = p.parent_path();\n        auto dst_folder = dir.wstring();\n        if (!fs::exists(dst_folder))\n            fs::create_directory(dst_folder);\n\n        // write result\n        std::ofstream outf(outfile);\n        Eigen::IOFormat fmt(FullPrecision, DontAlignCols, \"\\t\");\n        if (outf.is_open()) {\n            outf << gram_mat.format(fmt) << std::endl;\n        }\n        outf.close();\n        return true;\n    }\n\n    bool SaveKernelResultFromBarcodeListFile(std::wstring& barcodes_path, std::wstring& output_path, KernelPrm<FType>& prm,\n        const SHoleParam<FType> rprms, const SKerParam<FType> kpm) {\n        TypeBarcodesPtrVec<FType> dvecs1, dvecs2;\n        MakeDiagramVec(dvecs1, barcodes_path, rprms, kpm);\n        if(dvecs1.empty()) \n            return false;\n        MakeGramMatAndSaveResultToFile(dvecs1, dvecs2, output_path, prm);\n        return true;\n    }\n\n    bool SaveKernelResultFromBarcodeListFile(std::wstring& barcodes_lpath, std::wstring& barcodes_rpath,\n        std::wstring& output_path, KernelPrm<FType>& prm,\n        const SHoleParam<FType> rprms, const SKerParam<FType> kpm) {\n        TypeBarcodesPtrVec<FType> dvecs1, dvecs2;\n        std::cout << \"Making barcodes for left path\" << std::endl;\n        MakeDiagramVec(dvecs1, barcodes_lpath, rprms, kpm);\n        std::cout << \"Making barcodes for right path\" << std::endl;\n        MakeDiagramVec(dvecs2, barcodes_rpath, rprms, kpm);\n        if(dvecs1.empty() == true && dvecs2.empty() == true)\n            return false;\n        MakeGramMatAndSaveResultToFile(dvecs1, dvecs2, output_path, prm);\n        return true;\n    }\n\n    bool SaveKFDRFromGrammatToFile(const std::wstring& outfile, const MaxtrixFType gram_mat, std::vector<double> gammas) {\n        // create folder if not exist\n        fs::path p(outfile);\n        fs::path dir = p.parent_path();\n        auto dst_folder = dir.wstring();\n        if (!fs::exists(dst_folder))\n            fs::create_directory(dst_folder);\n\n        namespace io = boost::iostreams;\n        io::stream_buffer<io::file_sink> buf(NStringUtil::_w2s(outfile));\n        std::ostream out(&buf);\n        for (auto &gamma : gammas) {\n            auto kfdrs = ComputeKFDRs((int)gram_mat.rows(), gram_mat, gamma);\n            out << gamma << ' ';\n            for (auto val : kfdrs) {\n                out << val << ' ';\n            }\n            out << std::endl;\n        }\n        return true;\n    }\n\n\n    bool SaveKFDRFromBarcodeListFile(std::wstring& barcodes_path, std::wstring& kernel_outfile, KernelPrm<FType>& prm,\n        const SHoleParam<FType>& rprms, const SKerParam<FType>& kpm, std::vector<double> gammas) {\n        TypeBarcodesPtrVec<FType> dvecs1, dvecs2;\n        MakeDiagramVec(dvecs1, barcodes_path, rprms, kpm);\n        if(dvecs1.empty())\n            return false;\n\n        if (prm.kertype == KernelType::L2_INNER_MULTI_SCALE_NOSSE ||\n            prm.kertype == KernelType::L2_INNER_MULTI_SCALE_SSE ||\n            prm.kertype == KernelType::L2_SQUARE_DIST ||\n            prm.kertype == KernelType::RIEMANNIAN_METRIC) {\n            if (prm.T1 == 0.0) FindOptimalTimeHole(dvecs1, dvecs2, prm.T1);\n        }\n\n        MaxtrixFType gram_mat = KernelVecsProduct(dvecs1, dvecs2, prm);\n        // save gram_mat file\n        // write result\n        std::ofstream outf(kernel_outfile);\n        Eigen::IOFormat fmt(FullPrecision, DontAlignCols, \"\\t\");\n        if (outf.is_open()) {\n            outf << gram_mat.format(fmt) << std::endl;\n        }\n        outf.close();\n        fs::path p(kernel_outfile);\n        std::wstring kfdr_outfile = p.parent_path().c_str();\n        kfdr_outfile = kfdr_outfile + L\"/kfdr_\" + p.filename().c_str(); // des.wstring();\n        \n        return SaveKFDRFromGrammatToFile(kfdr_outfile, gram_mat, gammas);\n    }\n\n    bool ReadKernelFileFromFileList(std::vector<std::wstring>&kernel_list, std::wstring& kernel_list_file)\n    {\n        std::wifstream read_op;\n        read_op.open(kernel_list_file);\n        if (!read_op.good()) {\n            return false;\n        }\n        else {\n            while (read_op.good()) {\n                std::wstring line;\n                std::getline(read_op, line);\n\n                if (!line.empty()) {\n                    kernel_list.push_back(line);\n                }\n            }\n        }\n        return true;\n    }\n    bool SaveKFDRFromKernelList(std::wstring& kernel_list_file, std::wstring& dst_folder, size_t nbegin, size_t nend, std::vector<double> gammas) {\n        if (!fs::exists(dst_folder))\n            fs::create_directory(dst_folder);\n\n        std::vector<std::wstring> kernel_list;\n        ReadKernelFileFromFileList(kernel_list, kernel_list_file);\n        for (auto kf : kernel_list) {\n            std::vector<FType> xs;\n            std::wifstream in(kf);\n            std::wstring line;\n            if (in.is_open()) {\n                while (std::getline(in, line)) {\n                    std::wstringstream wstream(line);\n                    while (!wstream.eof()) {\n                        FType tmp = (FType)0.0;\n                        wstream >> tmp;\n                        xs.push_back(tmp);\n                    }\n                }\n            }\n            in.close();\n            size_t rows = (size_t)(std::sqrt(xs.size()));\n            size_t cols = (size_t)(std::sqrt(xs.size()));\n            if (rows*cols != xs.size())\n                continue;\n            size_t rs = rows;\n            size_t cs = cols;\n            if (nbegin < nend) {\n                rs = std::min(rows, nend - nbegin + 1);\n                cs = rs;\n            }\n            MaxtrixFType grammat = MaxtrixFType(rs, cs);\n            for (size_t i = 0; i < rows; ++i) {\n                if (i < nbegin) continue;\n                if (i >= nbegin + rs) continue;\n                for (size_t j = 0; j < cols; ++j) {\n                    if (j < nbegin) continue;\n                    if (j >= nbegin + rs) continue;\n                    grammat(i - nbegin, j - nbegin) = xs[i*cols + j];\n                }\n            }\n            fs::path p(kf);\n            std::wstring outfile = dst_folder + L\"/kfdr_\" + p.filename().c_str();\n            if (nbegin < nend)\n                outfile = dst_folder + L\"/kfdr_bg_\" + std::to_wstring(nbegin) + L\"_ed_\"+ std::to_wstring(nend) + L\"_\" + p.filename().c_str(); // des.wstring();\n            return SaveKFDRFromGrammatToFile(outfile, grammat, gammas);\n        }\n        return true;\n    }\n}\n\nint main(int argc, char** argv)\n{\n    using namespace NDiagramDistanceRunner;\n    int nRetCode = 0;\n\n    options_description description(\"DiagramDistance\");\n    description.add_options()\n        (\"T1\", value<double>()->default_value(0.0), \"Parameter T1 in the kernel (=0 for optimal value)\")\n        (\"T2\", value<double>()->default_value(1.0),  \"Parameter T2 in the kernel\")\n        (\"left,l\", value<std::string>()->default_value(\"\"), \"(left) Input as List of barcodes\")\n        (\"right,r\", value<std::string>()->default_value(\"\"), \"(right) Input as List of barcodes\")\n        (\"dim,d\", value<unsigned>()->default_value(0), \"Dimension of holes to compute kernel\")\n        (\"infval\", value<double>()->default_value(0.0), \n            \"If infval<=0.0 skip holes with infinity death-scale, otherwise replace these death-scales with a default value\")\n        (\"thres\", value<double>()->default_value(0.0), \"Threshold to skip holes with death-birth < thres (default=0 to use all holes)\")\n        (\"output,o\", value<std::string>()->default_value(\"grammat.txt\"), \"Output file of gram matrix\")\n        (\"posfix\", value<std::string>()->default_value(\"\"), \"postfix for output file\")\n        (\"method\", value<int>()->default_value(0),\n            \"0: L2_inner_multi_sse, 1: L2_squared_distance, 2: Slice Wasserstein, 3:L2_inner_multi_nosse, 4:riemmannian_metric\")\n        (\"single_tau\", value<double>()->default_value(-1.0), \"Specify for single tau, < 0: take all tau\")\n        (\"max_tau\", value<double>()->default_value(0.0), \n            \"Maximum of scale when calculating kernel, max_tau = 0 means that taking all possible tau\")\n\t\t(\"interval\", value<double>()->default_value(1.0),\n\t\t\t\t\"Interval to skip tau when calculating kernel with all taus\")\n        (\"kfdr\", value<bool>()->default_value(false), \"option to calculate kfdr, 1: kfdr, 0:kernel\")\n        (\"kfdrout\", value<std::string>()->default_value(\"kfdr\"), \"Output folder for kfdr\")\n        (\"nbegin\", value<unsigned>()->default_value(0))\n        (\"nend\", value<unsigned>()->default_value(0))\n        (\"kerls\", value<std::string>()->default_value(\"\"), \"Input as list of kernel for kfdr\")\n        (\"help,H\", \"Help: Diagram Distance to compute kernel of diagrams\")\n        (\"version,v\", \"v1.0\")\n        ;\n    variables_map vm;\n    store(parse_command_line(argc, argv, description), vm);\n    notify(vm);\n    if (vm.count(\"help\")) {\n        std::cout << description << std::endl;\n        return nRetCode;\n    }\n    \n    auto T1 = static_cast<FType>(vm[\"T1\"].as<double>());\n    auto T2 = static_cast<FType>(vm[\"T2\"].as<double>());\n\n    auto nbegin = static_cast<size_t>(vm[\"nbegin\"].as<unsigned>());\n    auto nend = static_cast<size_t>(vm[\"nend\"].as<unsigned>());\n    auto dim = vm[\"dim\"].as<unsigned>();\n    auto single_tau = vm[\"single_tau\"].as<double>();\n    auto max_tau = static_cast<FType>(vm[\"max_tau\"].as<double>());\n\tauto interval = static_cast<FType>(vm[\"interval\"].as<double>());\n\tif (interval <= 0.0) interval = 1.0;\n\n    bool skip = true;\n    auto infval = static_cast<FType>(vm[\"infval\"].as<double>());\n    if (infval > 0.0) skip = false;\n\n    auto threshold = static_cast<FType>(vm[\"thres\"].as<double>());\n    \n    auto kernel_list_path = NStringUtil::_s2w(vm[\"kerls\"].as<std::string>());\n    auto left_path = NStringUtil::_s2w(vm[\"left\"].as<std::string>());\n    auto right_path = NStringUtil::_s2w(vm[\"right\"].as<std::string>());\n\n    auto output_kfdr = NStringUtil::_s2w(vm[\"kfdrout\"].as<std::string>());\n    auto output_path = NStringUtil::_s2w(vm[\"output\"].as<std::string>());\n    auto posfix = NStringUtil::_s2w(vm[\"posfix\"].as<std::string>());\n\n    auto method = vm[\"method\"].as<int>();\n\n    KernelType kertype;\n    switch (method) {\n    case 0:\n        kertype = KernelType::L2_INNER_MULTI_SCALE_SSE;\n        break;\n    case 1:\n        kertype = KernelType::L2_SQUARE_DIST;\n        break;\n    case 2:\n        kertype = KernelType::SLICE_WASS;\n        break;\n    case 3:\n        kertype = KernelType::L2_INNER_MULTI_SCALE_NOSSE;\n        break;\n    case 4:\n        kertype = KernelType::RIEMANNIAN_METRIC;\n        break;\n    default:\n        std::cout << \"Kernel method is not defined!\" << std::endl;\n        std::cout << description;\n        return nRetCode;\n    }\n    \n    KernelPrm<FType> prm;\n    prm.kertype = kertype;\n    prm.T1 = T1;\n    prm.T2 = T2 * interval * interval;\n    prm.postfix = posfix + L\"_T1_\" + std::to_wstring(T1) +\n        L\"_T2_\" + std::to_wstring(T2);\n\n    const SHoleParam<FType> rprms(dim, infval, skip, threshold);\n    const SKerParam<FType> kpm(single_tau, max_tau, interval);\n\n    auto kfdr = vm[\"kfdr\"].as<bool>();\n    if (kfdr == TRUE) {\n        std::vector<double> gammas = {\n            1e-6, 2e-6, 3e-6, 4e-6, 5e-6, 6e-6, 7e-6, 8e-6, 9e-6,\n            1e-5, 2e-5, 3e-5, 4e-5, 5e-5, 6e-5, 7e-5, 8e-5, 9e-5,\n            1e-4, 2e-4, 3e-4, 4e-4, 5e-4, 6e-4, 7e-4, 8e-4, 9e-4,\n            1e-3, 2e-3, 3e-3, 4e-3, 5e-3, 6e-3, 7e-3, 8e-3, 9e-3,\n            1e-2, 2e-2, 3e-2, 4e-2, 5e-2, 6e-2, 7e-2, 8e-2, 9e-2,\n            1e-1, 2e-1, 3e-1, 4e-1, 5e-1, 6e-1, 7e-1, 8e-1, 9e-1,\n            1e+0, 2e+0, 3e+0, 4e+0, 5e+0, 6e+0, 7e+0, 8e+0, 9e+0,\n            1e+1, 2e+1, 3e+1, 4e+1, 5e+1, 6e+1, 7e+1, 8e+1, 9e+1,\n            1e+2, 2e+2, 3e+2, 4e+2, 5e+2, 6e+2, 7e+2, 8e+2, 9e+2,\n            1e+3, 2e+3, 3e+3, 4e+3, 5e+3, 6e+3, 7e+3, 8e+3, 9e+3,\n            1e+4, 2e+4, 3e+4, 4e+4, 5e+4, 6e+4, 7e+4, 8e+4, 9e+4,\n            1e+5, 2e+5, 3e+5, 4e+5, 5e+5, 6e+5, 7e+5, 8e+5, 9e+5\n        };\n        if (kernel_list_path == L\"\") {\n            SaveKFDRFromBarcodeListFile(left_path, output_path, prm, rprms, kpm, gammas);\n        }\n        else {\n            SaveKFDRFromKernelList(kernel_list_path, output_kfdr, nbegin, nend, gammas);\n        }\n    }\n    else {\n        if (left_path != L\"\" && !fs::exists(left_path)) {\n            std::cout << \"Not found left path for calculating kernel: \" << NStringUtil::_w2s(left_path) << std::endl;\n            return nRetCode;\n        }\n        if (right_path != L\"\" && !fs::exists(right_path)) {\n            std::cout << \"Not found right path for calculating kernel: \" << NStringUtil::_w2s(right_path) << std::endl;\n            return nRetCode;\n        }\n        SaveKernelResultFromBarcodeListFile(left_path, right_path, output_path, prm, rprms, kpm);\n    }\n    return nRetCode;\n}\n", "meta": {"hexsha": "f6676a5a46aad1072538a68120f2ea67aaee50cc", "size": 20658, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ph-compute/ScaleVariantTopo/DiagramDistanceRunner_D64/DiagramDistanceRunner_D64.cpp", "max_stars_repo_name": "OminiaVincit/scale-variant-topo", "max_stars_repo_head_hexsha": "6945bc42aacd0d71a6fb472c87e09da223821e1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-11-09T21:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T19:02:10.000Z", "max_issues_repo_path": "ph-compute/ScaleVariantTopo/DiagramDistanceRunner_D64/DiagramDistanceRunner_D64.cpp", "max_issues_repo_name": "OminiaVincit/scale-variant-topo", "max_issues_repo_head_hexsha": "6945bc42aacd0d71a6fb472c87e09da223821e1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ph-compute/ScaleVariantTopo/DiagramDistanceRunner_D64/DiagramDistanceRunner_D64.cpp", "max_forks_repo_name": "OminiaVincit/scale-variant-topo", "max_forks_repo_head_hexsha": "6945bc42aacd0d71a6fb472c87e09da223821e1e", "max_forks_repo_licenses": ["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.7333333333, "max_line_length": 159, "alphanum_fraction": 0.5775486494, "num_tokens": 5882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5326126367458331}}
{"text": "#include \"geometry.h\"\n\n#include <limits>\n#include <math.h>\n#include <vector>\n#include <map>\n#include <iostream>\n#include <vector_functions.h>\n#include <util/helper_math.h>\n#include <Eigen/Eigen>\n\nnamespace dart {\n\ntemplate <typename Real>\nReal distancePointEllipseSpecial (const Real e[2], const Real y[2], Real x[2])\n{\n    Real distance;\n    if (y[1] > (Real)0)\n    {\n        if (y[0] > (Real)0)\n        {\n            // Bisect to compute the root of F(t) for t >= -e1*e1.\n            Real esqr[2] = { e[0]*e[0], e[1]*e[1] };\n            Real ey[2] = { e[0]*y[0], e[1]*y[1] };\n            Real t0 = -esqr[1] + ey[1];\n            Real t1 = -esqr[1] + sqrt(ey[0]*ey[0] + ey[1]*ey[1]);\n            Real t = t0;\n            const int imax = 2*std::numeric_limits<Real>::max_exponent;\n            for (int i = 0; i < imax; ++i)\n            {\n                t = ((Real)0.5)*(t0 + t1);\n                if (t == t0 || t == t1)\n                {\n                    break;\n                }\n                Real r[2] = { ey[0]/(t + esqr[0]), ey[1]/(t + esqr[1]) };\n                Real f = r[0]*r[0] + r[1]*r[1] - (Real)1;\n                if (f > (Real)0)\n                {\n                    t0 = t;\n                }\n                else if (f < (Real)0)\n                {\n                    t1 = t;\n                }\n                else\n                {\n                    break;\n                }\n            }\n            x[0] = esqr[0]*y[0]/(t + esqr[0]);\n            x[1] = esqr[1]*y[1]/(t + esqr[1]);\n            Real d[2] = { x[0] - y[0], x[1] - y[1] };\n            distance = sqrt(d[0]*d[0] + d[1]*d[1]);\n        }\n        else // y0 == 0\n        {\n            x[0] = (Real)0;\n            x[1] = e[1];\n            distance = fabs(y[1] - e[1]);\n        }\n    }\n    else // y1 == 0\n    {\n        Real denom0 = e[0]*e[0] - e[1]*e[1];\n        Real e0y0 = e[0]*y[0];\n        if (e0y0 < denom0)\n        {\n            // y0 is inside the subinterval.\n            Real x0de0 = e0y0/denom0;\n            Real x0de0sqr = x0de0*x0de0;\n            x[0] = e[0]*x0de0;\n            x[1] = e[1]*sqrt(fabs((Real)1 - x0de0sqr));\n            Real d0 = x[0] - y[0];\n            distance = sqrt(d0*d0 + x[1]*x[1]);\n        }\n        else\n        {\n            // y0 is outside the subinterval. The closest ellipse point has\n            // x1 == 0 and is on the domain-boundary interval (x0/e0)^2 = 1.\n            x[0] = e[0];\n            x[1] = (Real)0;\n            distance = fabs(y[0] - e[0]);\n        }\n    }\n    return distance;\n}\n\ntemplate <typename Real>\nReal distancePointEllipse (const Real e[2], const Real y[2], Real x[2])\n{\n    // Determine reflections for y to the first quadrant.\n    bool reflect[2];\n    int i, j;\n    for (i = 0; i < 2; ++i)\n    {\n        reflect[i] = (y[i] < (Real)0);\n    }\n    // Determine the axis order for decreasing extents.\n    int permute[2];\n    if (e[0] < e[1])\n    {\n        permute[0] = 1; permute[1] = 0;\n    }\n    else\n    {\n        permute[0] = 0; permute[1] = 1;\n    }\n    int invpermute[2];\n    for (i = 0; i < 2; ++i)\n    {\n        invpermute[permute[i]] = i;\n    }\n    Real locE[2], locY[2];\n    for (i = 0; i < 2; ++i)\n    {\n        j = permute[i];\n        locE[i] = e[j];\n        locY[i] = y[j];\n        if (reflect[j])\n        {\n            locY[i] = -locY[i];\n        }\n    }\n    Real locX[2];\n    Real distance = distancePointEllipseSpecial(locE, locY, locX);\n    // Restore the axis order and reflections.\n    for (i = 0; i < 2; ++i)\n    {\n        j = invpermute[i];\n        if (reflect[j])\n        {\n            locX[j] = -locX[j];\n        }\n        x[i] = locX[j];\n    }\n    return distance;\n}\n\ntemplate <typename Real>\nReal distancePointEllipsoidSpecial(const Real e[3], const Real y[3], Real x[3])\n{\n    Real distance;\n    if (y[2] > (Real)0)\n    {\n        if (y[1] > (Real)0)\n        {\n            if (y[0] > (Real)0)\n            {\n                // Bisect to compute the root of F(t) for t >= -e2*e2.\n                Real esqr[3] = { e[0]*e[0], e[1]*e[1], e[2]*e[2] };\n                Real ey[3] = { e[0]*y[0], e[1]*y[1], e[2]*y[2] };\n                Real t0 = -esqr[2] + ey[2];\n                Real t1 = -esqr[2] + sqrt(ey[0]*ey[0] + ey[1]*ey[1] +\n                                          ey[2]*ey[2]);\n                Real t = t0;\n                const int imax = 2*std::numeric_limits<Real>::max_exponent;\n                for (int i = 0; i < imax; ++i)\n                {\n                    t = ((Real)0.5)*(t0 + t1);\n                    if (t == t0 || t == t1)\n                    {\n                        break;\n                    }\n                    Real r[3] = { ey[0]/(t + esqr[0]), ey[1]/(t + esqr[1]),\n                                  ey[2]/(t + esqr[2]) };\n                    Real f = r[0]*r[0] + r[1]*r[1] + r[2]*r[2] - (Real)1;\n                    if (f > (Real)0)\n                    {\n                        t0 = t;\n                    }\n                    else if (f < (Real)0)\n                    {\n                        t1 = t;\n                    }\n                    else\n                    {\n                        break;\n                    }\n                }\n                x[0] = esqr[0]*y[0]/(t + esqr[0]);\n                x[1] = esqr[1]*y[1]/(t + esqr[1]);\n                x[2] = esqr[2]*y[2]/(t + esqr[2]);\n                Real d[3] = { x[0] - y[0], x[1] - y[1], x[2] - y[2] };\n                distance = sqrt(d[0]*d[0] + d[1]*d[1] + d[2]*d[2]);\n            }\n            else // y0 == 0\n            {\n                x[0] = (Real)0;\n                Real etmp[2] = { e[1], e[2] };\n                Real ytmp[2] = { y[1], y[2] };\n                Real xtmp[2];\n                distance = distancePointEllipseSpecial<Real>(etmp, ytmp, xtmp);\n                x[1] = xtmp[0];\n                x[2] = xtmp[1];\n            }\n        }\n        else // y1 == 0\n        {\n            x[1] = (Real)0;\n            if (y[0] > (Real)0)\n            {\n                Real etmp[2] = { e[0], e[2] };\n                Real ytmp[2] = { y[0], y[2] };\n                Real xtmp[2];\n                distance = distancePointEllipseSpecial<Real>(etmp, ytmp, xtmp);\n                x[0] = xtmp[0];\n                x[2] = xtmp[1];\n            }\n            else // y0 == 0\n            {\n                x[0] = (Real)0;\n                x[2] = e[2];\n                distance = fabs(y[2] - e[2]);\n            }\n        }\n    }\n    else // y2 == 0\n    {\n        Real denom[2] = { e[0]*e[0] - e[2]*e[2], e[1]*e[1] - e[2]*e[2] };\n        Real ey[2] = { e[0]*y[0], e[1]*y[1] };\n        if (ey[0] < denom[0] && ey[1] < denom[1])\n        {\n            // (y0,y1) is inside the axis-aligned bounding rectangle of the\n            // subellipse. This intermediate test is designed to guard\n            // against the division by zero when e0 == e2 or e1 == e2.\n            Real xde[2] = { ey[0]/denom[0], ey[1]/denom[1] };\n            Real xdesqr[2] = { xde[0]*xde[0], xde[1]*xde[1] };\n            Real discr = (Real)1 - xdesqr[0] - xdesqr[1];\n            if (discr > (Real)0)\n            {\n                // (y0,y1) is inside the subellipse. The closest ellipsoid\n                // point has x2 > 0.\n                x[0] = e[0]*xde[0];\n                x[1] = e[1]*xde[1];\n                x[2] = e[2]*sqrt(discr);\n                Real d[2] = { x[0] - y[0], x[1] - y[1] };\n                distance = sqrt(d[0]*d[0] + d[1]*d[1] + x[2]*x[2]);\n            }\n            else\n            {\n                // (y0,y1) is outside the subellipse. The closest ellipsoid\n                // point has x2 == 0 and is on the domain-boundary ellipse\n                // (x0/e0)^2 + (x1/e1)^2 = 1.\n                x[2] = (Real)0;\n                distance = distancePointEllipseSpecial<Real>(e, y, x);\n            }\n        }\n        else\n        {\n            // (y0,y1) is outside the subellipse. The closest ellipsoid\n            // point has x2 == 0 and is on the domain-boundary ellipse\n            // (x0/e0)^2 + (x1/e1)^2 = 1.\n            x[2] = (Real)0;\n            distance = distancePointEllipseSpecial<Real>(e, y, x);\n        }\n    }\n    return distance;\n}\n\ntemplate <typename Real>\nReal distancePointEllipsoid(const Real e[3], const Real y[3], Real x[3])\n{\n    // Determine reflections for y to the first octant.\n    bool reflect[3];\n    int i, j;\n    for (i = 0; i < 3; ++i)\n    {\n        reflect[i] = (y[i] < (Real)0);\n    }\n    // Determine the axis order for decreasing extents.\n    int permute[3];\n    if (e[0] < e[1])\n    {\n        if (e[2] < e[0])\n        {\n            permute[0] = 1; permute[1] = 0; permute[2] = 2;\n        }\n        else if (e[2] < e[1])\n        {\n            permute[0] = 1; permute[1] = 2; permute[2] = 0;\n        }\n        else\n        {\n            permute[0] = 2; permute[1] = 1; permute[2] = 0;\n        }\n    }\n    else\n    {\n        if (e[2] < e[1])\n        {\n            permute[0] = 0; permute[1] = 1; permute[2] = 2;\n        }\n        else if (e[2] < e[0])\n        {\n            permute[0] = 0; permute[1] = 2; permute[2] = 1;\n        }\n        else\n        {\n            permute[0] = 2; permute[1] = 0; permute[2] = 1;\n        }\n    }\n\n    int invpermute[3];\n    for (i = 0; i < 3; ++i)\n    {\n        invpermute[permute[i]] = i;\n    }\n    Real locE[3], locY[3];\n    for (i = 0; i < 3; ++i)\n    {\n        j = permute[i];\n        locE[i] = e[j];\n        locY[i] = y[j];\n        if (reflect[j])\n        {\n            locY[i] = -locY[i];\n        }\n    }\n    Real locX[3];\n    Real distance = distancePointEllipsoidSpecial(locE, locY, locX);\n\n    // Restore the axis order and reflections.\n    for (i = 0; i < 3; ++i)\n    {\n        j = invpermute[i];\n        if (reflect[j])\n        {\n            locX[j] = -locX[j];\n        }\n        x[i] = locX[j];\n    }\n    return distance;\n}\n\nfloat distancePointTriangle(const float3 P, const float3 A, const float3 B, const float3 C) {\n    float3 D;\n    return distancePointTriangle(P,A,B,C,D);\n}\n\nfloat distancePointTriangle(const float3 P, const float3 A, const float3 B, const float3 C, float3 & point) {\n\n    float3 E0 = A-B;\n    float3 E1 = C-B;\n\n    float3 D = B-P;\n    float a = dot(E0,E0);\n    float b = dot(E0,E1);\n    float c = dot(E1,E1);\n    float d = dot(E0,D);\n    float e = dot(E1,D);\n    float f = dot(D,D);\n\n    float det = a*c-b*b;\n    float s = b*e - c*d;\n    float t = b*d - a*e;\n\n    int region;\n    if ( s+t <= det) {\n        if ( s < 0 ) {\n            if ( t < 0 ) {\n                region = 4;\n            } else {\n                region = 3;\n            }\n        } else if ( t < 0 ) {\n            region = 5;\n        } else {\n            region = 0;\n        }\n    } else {\n        if ( s < 0 ) {\n            region = 2;\n        } else if ( t < 0) {\n            region = 6;\n        } else {\n            region = 1;\n        }\n    }\n\n//    std::cout << region << std::endl;\n\n    switch (region) {\n        case 0:\n            {\n                float invDet = 1/det;\n                s*= invDet;\n                t*= invDet;\n            }\n            break;\n        case 1:\n            {\n                float numer = c + e - b - d;\n                if (numer <= 0) {\n                    s = 0;\n                } else {\n                    float denom = a - 2*b + c;\n                    s = ( numer >= denom ? 1 : numer/denom );\n                }\n                t = 1-s;\n            }\n            break;\n        case 2:\n            {\n                float tmp0 = b+d;\n                float tmp1 = c+e;\n                if ( tmp1 > tmp0 ) { // min on edge s+1=1\n                    float numer = tmp1 - tmp0;\n                    float denom = a - 2*b + c;\n                    s = ( numer >= denom ? 1 : numer/denom );\n                    t = 1-s;\n                } else { // min on edge s=0\n                    s = 0;\n                    t = ( tmp1 <= 0 ? 1 : ( e >= 0 ? 0 : -e/c ) );\n                }\n            }\n            break;\n        case 3:\n            s = 0;\n            t = ( e >= 0 ? 0 :\n                           ( -e >= c ? 1 : -e/c ) );\n            break;\n        case 4:\n            if ( d < 0 ) { // min on edge t=0\n                t = 0;\n                s = ( d >= 0 ? 0 :\n                               ( -d >= a ? 1 : -d/a ) );\n            } else { // min on edge s = 0\n                s = 0;\n                t = ( e >= 0 ? 0 :\n                               ( -e >= c ? 1 : -e/c ) );\n            }\n            break;\n        case 5:\n            t = 0;\n            s = ( d >= 0 ? 0 :\n                           ( -d >= a ? 1 : -d/a ) );\n            break;\n        case 6:\n            {\n                float tmp0 = a+d;\n                float tmp1 = b+e;\n                if (tmp0 > tmp1) { // min on edge s+1=1\n                    float numer = c + e - b - d;\n                    float denom = a -2*b + c;\n                    s = ( numer >= denom ? 1 : numer/denom );\n                    t = 1-s;\n                } else { // min on edge t=1\n                    t = 0;\n                    s = ( tmp0 <= 0 ? 1 : ( d >= 0 ? 0 : -d/a ));\n                }\n            }\n            break;\n    }\n    point = B + s*E0 + t*E1;\n    float3 v = point-P;\n    return dot(v,v);\n}\n\ntemplate <typename Real>\nReal distancePointLineSegment2D(const typename VectorTypeTemplate<Real>::type2 p,\n                                const typename VectorTypeTemplate<Real>::type2 a,\n                                const typename VectorTypeTemplate<Real>::type2 b ) {\n\n    typedef typename VectorTypeTemplate<Real>::type2 T2;\n\n    const T2 v = b - a;\n    const T2 w = p - a;\n\n    float c1 = dot(w,v);\n    if (c1 <= 0) {\n        return length(w);\n    }\n\n    float c2 = dot(v,v);\n    if (c2 <= c1) {\n        return length(p - b);\n    }\n\n    float t = c1 / c2;\n    T2 closest = a + t*v;\n    return length(p - closest);\n\n}\n\ntemplate <typename Real>\nReal signedDistancePointLineSegment2D(const typename VectorTypeTemplate<Real>::type2 p,\n                                      const typename VectorTypeTemplate<Real>::type2 a,\n                                      const typename VectorTypeTemplate<Real>::type2 b ) {\n\n    typedef typename VectorTypeTemplate<Real>::type2 T2;\n\n    const T2 v = b - a;\n    const T2 w = p - a;\n    T2 n;\n    n.x = v.y;\n    n.y = -v.x;\n\n    int sign = dot(n,w) > 0 ? 1 : -1;\n\n    float c1 = dot(w,v);\n    if (c1 <= 0) {\n        return sign*length(w);\n    }\n\n    float c2 = dot(v,v);\n    if (c2 <= c1) {\n        return sign*length(p - b);\n    }\n\n    float t = c1 / c2;\n    T2 closest = a + t*v;\n    return sign*length(p - closest);\n\n}\n\n\ntemplate float distancePointLineSegment2D<float>(const float2, const float2, const float2);\n\ntemplate float signedDistancePointLineSegment2D<float>(const float2, const float2, const float2);\n\n\ntemplate <typename Real, typename Derived>\ninline void rotationMatrixFromRodrigues(const Real w[3], Eigen::MatrixBase<Derived> const & R) {\n\n    Real theta = sqrt(w[0]*w[0] + w[1]*w[1] + w[2]*w[2]);\n    typedef typename Derived::Scalar Scalar;\n\n    if (theta == 0) {\n        const_cast< Eigen::MatrixBase<Derived>& >(R) = Eigen::Matrix<Scalar,3,3>::Identity(3,3);\n        return;\n    }\n\n    Real rx = w[0] / theta;\n    Real ry = w[1] / theta;\n    Real rz = w[2] / theta;\n\n    Eigen::Matrix<Scalar,3,3> H;\n    H << 0, -rz, ry, rz, 0, -rx, -ry, rx, 0;\n\n    Eigen::Matrix<Scalar,3,3> H2;\n    H2 << rx*rx-1, rx*ry, rx*rz, rx*ry, ry*ry-1, ry*rz, rx*rz, ry*rz, rz*rz-1;\n\n    const_cast< Eigen::MatrixBase<Derived> &>(R) = Eigen::Matrix<Scalar,3,3>::Identity(3,3) + sin(theta)*H + (1-cos(theta))*H2;\n\n}\n\ntemplate <typename Real, typename Derived>\ninline void rodriguesFromRotationMatrix(Real w[3], Eigen::MatrixBase<Derived> const & R) {\n\n    Real x = R(2,1) - R(1,2);\n    Real y = R(0,2) - R(2,0);\n    Real z = R(1,0) - R(0,1);\n\n    Real r = sqrt(x*x + y*y + z*z);\n\n    if (r == 0) {\n        memset(w,0,3*sizeof(Real));\n        return;\n    }\n\n    Real t = R(0,0) + R(1,1) + R(2,2);\n\n    Real theta = atan2(r,t-1);\n\n    w[0] = x/r*theta;\n    w[1] = y/r*theta;\n    w[2] = z/r*theta;\n\n}\n\ntemplate <typename Real>\nvoid rotationMatrixJacobianFromRodrigues(const Real w[3], Eigen::Matrix<Real,9,3> & J) {\n\n    Real theta = sqrt(w[0]*w[0] + w[1]*w[1] + w[2]*w[2]); \n\n    if (theta == 0) {\n        J <<    0, 0, 0, 0, 0, -1, 0, 1, 0,\n                0, 0, 1, 0, 0, 0, -1, 0, 0,\n                0, -1, 0, 1, 0, 0, 0, 0, 0;\n        return;\n    }\n\n    Real rx = w[0] / theta;\n    Real ry = w[1] / theta;\n    Real rz = w[2] / theta;\n\n    Eigen::Matrix<Real,3,3> H;\n    H << 0, -rz, ry, rz, 0, -rx, -ry, rx, 0;\n\n    Eigen::Matrix<Real,3,3> H2;\n    H2 << rx*rx-1, rx*ry, rx*rz, rx*ry, ry*ry-1, ry*rz, rx*rz, ry*rz, rz*rz-1;\n\n    Eigen::Matrix<Real,3,3> dH_drx, dH_dry, dH_drz;\n    dH_drx << 0, 0, 0, 0, 0, -1, 0, 1, 0;\n    dH_dry << 0, 0, 1, 0, 0, 0, -1, 0, 0;\n    dH_drz << 0, -1, 0, 1, 0, 0, 0, 0, 0;\n\n    Eigen::Matrix<Real,3,3> dH2_drx, dH2_dry, dH2_drz;\n    dH2_drx << 2*rx, ry, rz, ry, 0, 0, rz, 0, 0;\n    dH2_dry << 0, rx, 0, rx, 2*ry, rz, 0, rz, 0;\n    dH2_drz << 0, 0, rx, 0, 0, ry, rx, ry, 2*rz;\n\n    J.block(0,0,3,3) = H*rx*(cos(theta) - sin(theta)/theta) + dH_drx*sin(theta)/theta +\n            H*H*rx*(sin(theta)-2*(1-cos(theta))/theta) + (1-cos(theta))/theta*(dH2_drx - 2*rx*Eigen::Matrix<Real,3,3>::Identity(3,3));\n    J.block(3,0,3,3) = H*ry*(cos(theta) - sin(theta)/theta) + dH_dry*sin(theta)/theta +\n            H*H*ry*(sin(theta)-2*(1-cos(theta))/theta) + (1-cos(theta))/theta*(dH2_dry - 2*ry*Eigen::Matrix<Real,3,3>::Identity(3,3));\n    J.block(6,0,3,3) = H*rz*(cos(theta) - sin(theta)/theta) + dH_drz*sin(theta)/theta +\n            H*H*rz*(sin(theta)-2*(1-cos(theta))/theta) + (1-cos(theta))/theta*(dH2_drz - 2*rz*Eigen::Matrix<Real,3,3>::Identity(3,3));\n\n}\n\ntemplate <typename Real>\nvoid aabbEllipsoid(const Real e[3], const Real c[3], const Real w[3], Real o[3], Real s[3]) {\n\n    Eigen::Matrix<Real,3,3> R;\n    rotationMatrixFromRodrigues<Real>(w,R);\n\n    Real deltax = sqrt(e[0]*e[0]*R(0,0)*R(0,0) + e[1]*e[1]*R(0,1)*R(0,1) + e[2]*e[2]*R(0,2)*R(0,2));\n    Real deltay = sqrt(e[0]*e[0]*R(1,0)*R(1,0) + e[1]*e[1]*R(1,1)*R(1,1) + e[2]*e[2]*R(1,2)*R(1,2));\n    Real deltaz = sqrt(e[0]*e[0]*R(2,0)*R(2,0) + e[1]*e[1]*R(2,1)*R(2,1) + e[2]*e[2]*R(2,2)*R(2,2));\n\n    o[0] = c[0] - deltax;\n    o[1] = c[1] - deltay;\n    o[2] = c[2] - deltaz;\n\n    s[0] = 2*deltax;\n    s[1] = 2*deltay;\n    s[2] = 2*deltaz;\n}\n\ntemplate <typename Real>\nvoid aabbEllipticCylinder(const Real e[2], const Real h, const Real c[3], const Real w[3], Real o[3], Real s[3]) {\n\n    Eigen::Matrix<Real,3,3> R;\n    rotationMatrixFromRodrigues<Real>(w,R);\n\n    Eigen::Matrix<Real,3,1> u, v, c2;\n    u << e[0], 0, 0;\n    v << 0, e[1], 0;\n    c2 << 0, 0, h;\n\n    u = R*u;\n    v = R*v;\n    c2 = R*c2;\n\n    Real rx = sqrt(u(0)*u(0) + v(0)*v(0));\n    Real ry = sqrt(u(1)*u(1) + v(1)*v(1));\n    Real rz = sqrt(u(2)*u(2) + v(2)*v(2));\n\n    o[0] = std::min(c[0]-rx, c[0]+c2(0)-rx);\n    o[1] = std::min(c[1]-ry, c[1]+c2(1)-ry);\n    o[2] = std::min(c[2]-rz, c[2]+c2(2)-rz);\n\n    s[0] = std::max(c[0]+rx, c[0]+c2(0)+rx) - o[0];\n    s[1] = std::max(c[1]+ry, c[1]+c2(1)+ry) - o[1];\n    s[2] = std::max(c[2]+rz, c[2]+c2(2)+rz) - o[2];\n}\n\ntemplate <typename Real>\nvoid aabbRectangularPrism(const Real l[3], const Real c[3], const Real w[3], Real o[3], Real s[3]) {\n\n    Eigen::Matrix<Real,3,3> R;\n    rotationMatrixFromRodrigues<Real>(w,R);\n\n    Eigen::Matrix<Real,3,1> corners[8];\n    corners[0] << -l[0], -l[1], -l[2];\n    corners[1] << -l[0], -l[1],  l[2];\n    corners[2] << -l[0],  l[1], -l[2];\n    corners[3] << -l[0],  l[1],  l[2];\n    corners[4] <<  l[0], -l[1], -l[2];\n    corners[5] <<  l[0], -l[1],  l[2];\n    corners[6] <<  l[0],  l[1], -l[2];\n    corners[7] <<  l[0],  l[1],  l[2];\n\n    for (int i=0; i<8; i++)\n        corners[i] = R*corners[i];\n\n    o[0] = s[0] = corners[0](0);\n    o[1] = s[1] = corners[0](1);\n    o[2] = s[2] = corners[0](2);\n\n    for (int i=1; i<8; i++) {\n        o[0] = std::min(o[0],corners[i](0));\n        o[1] = std::min(o[1],corners[i](1));\n        o[2] = std::min(o[2],corners[i](2));\n        s[0] = std::max(s[0],corners[i](0));\n        s[1] = std::max(s[1],corners[i](1));\n        s[2] = std::max(s[2],corners[i](2));\n    }\n\n    s[0] -= o[0];\n    s[1] -= o[1];\n    s[2] -= o[2];\n\n    o[0] += c[0];\n    o[1] += c[1];\n    o[2] += c[2];\n}\n\nvoid generateUnitIcosphere(float3 * &verts, int3 * & indxs, int & nverts, int & nfaces, const int splits) {\n\n    std::vector<float3> * vertVec = new std::vector<float3>();\n    std::vector<int3> * faceVec = new std::vector<int3>();\n\n    // generate initial 12 vertices\n    float t = (1.0f + sqrtf(5.0f)) / 2.0f;\n\n    vertVec->push_back(normalize(make_float3(-1, t, 0)));\n    vertVec->push_back(normalize(make_float3( 1, t, 0)));\n    vertVec->push_back(normalize(make_float3(-1,-1, 0)));\n    vertVec->push_back(normalize(make_float3( 1,-t, 0)));\n\n    vertVec->push_back(normalize(make_float3( 0,-1, t)));\n    vertVec->push_back(normalize(make_float3( 0, 1, t)));\n    vertVec->push_back(normalize(make_float3( 0,-1,-t)));\n    vertVec->push_back(normalize(make_float3( 0, 1,-t)));\n\n    vertVec->push_back(normalize(make_float3( t, 0,-1)));\n    vertVec->push_back(normalize(make_float3( t, 0, 1)));\n    vertVec->push_back(normalize(make_float3(-t, 0,-1)));\n    vertVec->push_back(normalize(make_float3(-t, 0, 1)));\n\n    // generate intitial 20 faces\n    faceVec->push_back(make_int3( 0,11, 5));\n    faceVec->push_back(make_int3( 0, 5, 1));\n    faceVec->push_back(make_int3( 0, 1, 7));\n    faceVec->push_back(make_int3( 0, 7,10));\n    faceVec->push_back(make_int3( 0,10,11));\n\n    faceVec->push_back(make_int3( 1, 5, 9));\n    faceVec->push_back(make_int3( 5,11, 4));\n    faceVec->push_back(make_int3(11,10, 2));\n    faceVec->push_back(make_int3(10, 7, 6));\n    faceVec->push_back(make_int3( 7, 1, 8));\n\n    faceVec->push_back(make_int3( 3, 9, 4));\n    faceVec->push_back(make_int3( 3, 4, 2));\n    faceVec->push_back(make_int3( 3, 2, 6));\n    faceVec->push_back(make_int3( 3, 6, 8));\n    faceVec->push_back(make_int3( 3, 8, 9));\n\n    faceVec->push_back(make_int3( 4, 9, 5));\n    faceVec->push_back(make_int3( 2, 4,11));\n    faceVec->push_back(make_int3( 6, 2,10));\n    faceVec->push_back(make_int3( 8, 6, 7));\n    faceVec->push_back(make_int3( 9, 8, 1));\n\n    // map of already split vertices\n    std::map<int64_t,int> split_verts;\n\n    for (int i=0; i<splits; i++) {\n        std::vector<int3>* new_faces = new std::vector<int3>();\n\n        for (unsigned int f = 0; f < faceVec->size(); f++) {\n\n            const int v1 = faceVec->at(f).x;\n            const int v2 = faceVec->at(f).y;\n            const int v3 = faceVec->at(f).z;\n            int64_t key;\n            std::map<int64_t,int>::iterator it;\n            int p12, p23, p31;\n\n            // edge 12\n            key = (v1 < v2) ? (((int64_t)v1 << 32) | v2) : (((int64_t)v2 << 32) | v1);\n            it = split_verts.find(key);\n            if (it != split_verts.end()) { // check if we've already split this edge\n                p12 = it->second;\n            }\n            else {\n                p12 = vertVec->size();\n                split_verts[key] = p12;\n                vertVec->push_back(normalize(vertVec->at(v1) + vertVec->at(v2)));\n            }\n\n            // edge 23\n            key = (v2 < v3) ? (((int64_t)v2 << 32) | v3) : (((int64_t)v3 << 32) | v2);\n            it = split_verts.find(key);\n            if (it != split_verts.end()) { // check if we've already split this edge\n                p23 = it->second;\n            }\n            else {\n                p23 = vertVec->size();\n                split_verts[key] = p23;\n                vertVec->push_back(normalize(vertVec->at(v2) + vertVec->at(v3)));\n            }\n\n            // edge 31\n            key = (v3 < v1) ? (((int64_t)v3 << 32) | v1) : (((int64_t)v1 << 32) | v3);\n            it = split_verts.find(key);\n            if (it != split_verts.end()) { // check if we've already split this edge\n                p31 = it->second;\n            }\n            else {\n                p31 = vertVec->size();\n                split_verts[key] = p31;\n                vertVec->push_back(normalize(vertVec->at(v3) + vertVec->at(v1)));\n            }\n\n            // add new faces\n            new_faces->push_back(make_int3(v1,p12,p31));\n            new_faces->push_back(make_int3(v2,p23,p12));\n            new_faces->push_back(make_int3(v3,p31,p23));\n            new_faces->push_back(make_int3(p12,p23,p31));\n\n        }\n\n        delete faceVec;\n        faceVec = new_faces;\n    }\n\n    // convert STL containers to raw arrays\n    verts = new float3[vertVec->size()];\n    memcpy(verts,vertVec->data(),vertVec->size()*sizeof(float3));\n    nverts = vertVec->size();\n\n    indxs = new int3[faceVec->size()];\n    memcpy(indxs,faceVec->data(),faceVec->size()*sizeof(int3));\n    nfaces = faceVec->size();\n\n    // memory cleanup\n    delete vertVec;\n    delete faceVec;\n\n}\n\n// generate functions from template for the linker (just float or double for now)\ntemplate double distancePointEllipse<double>(const double[], const double[], double[]);\ntemplate float distancePointEllipse<float>(const float[], const float[], float[]);\n\ntemplate double distancePointEllipsoid<double>(const double[], const double[], double[]);\ntemplate float distancePointEllipsoid<float>(const float[], const float[], float[]);\n\ntemplate void aabbEllipsoid<double>(const double e[3], const double c[3], const double w[3], double o[3], double s[3]);\ntemplate void aabbEllipsoid<float>(const float e[3], const float c[3], const float w[3], float o[3], float s[3]);\n\ntemplate void aabbEllipticCylinder<double>(const double e[2], const double h, const double c[3], const double w[3], double o[3], double s[3]);\ntemplate void aabbEllipticCylinder<float>(const float e[2], const float h, const float c[3], const float w[3], float o[3], float s[3]);\n\ntemplate void aabbRectangularPrism<double>(const double l[3], const double c[3], const double w[3], double o[3], double s[3]);\ntemplate void aabbRectangularPrism<float>(const float l[3], const float c[3], const float w[3], float o[3], float s[3]);\n\n}\n", "meta": {"hexsha": "6e027c678a7e27eb5525e7af187a1b440d2573ea", "size": 25985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/geometry.cpp", "max_stars_repo_name": "bartyang9/dart", "max_stars_repo_head_hexsha": "f99746acef3eeaef377f671d40b347d08fe4fd2d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2016-04-29T08:42:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T11:04:53.000Z", "max_issues_repo_path": "src/geometry/geometry.cpp", "max_issues_repo_name": "bartyang9/dart", "max_issues_repo_head_hexsha": "f99746acef3eeaef377f671d40b347d08fe4fd2d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-06-30T07:40:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T03:14:11.000Z", "max_forks_repo_path": "src/geometry/geometry.cpp", "max_forks_repo_name": "bartyang9/dart", "max_forks_repo_head_hexsha": "f99746acef3eeaef377f671d40b347d08fe4fd2d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2016-04-04T09:12:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T06:34:29.000Z", "avg_line_length": 30.7879146919, "max_line_length": 142, "alphanum_fraction": 0.4507600539, "num_tokens": 8900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5325884990697076}}
{"text": "#ifndef TEST_UNIT_TORSTEN_PK_CPT_MODEL_TEST_FIXTURE\n#define TEST_UNIT_TORSTEN_PK_CPT_MODEL_TEST_FIXTURE\n\n//\n#include <gtest/gtest.h>\n#include <boost/numeric/odeint.hpp>\n#include <stan/math/torsten/pmx_onecpt_model.hpp>\n#include <stan/math/torsten/pmx_twocpt_model.hpp>\n#include <stan/math/torsten/pmx_linode_model.hpp>\n#include <stan/math/torsten/pmx_ode_model.hpp>\n#include <stan/math/torsten/test/unit/pmx_ode_test_fixture.hpp>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <string>\n\nstruct TorstenTwoCptModelTest : public TorstenOdeTest {\n\n  std::vector<double> ts;\n  torsten::PKRec<double> y0;\n  std::vector<double> rate;\n  double CL;\n  double Q;\n  double V2;\n  double V3;\n  double ka;\n  std::vector<double> par;\n  Eigen::MatrixXd linode_par;      // LinOdeModel parameters\n\n  TorstenTwoCptModelTest() :\n    ts{0.1, 0.5, 1.0},\n    y0(3),\n    rate(3, 0.0),\n    CL(10.0),\n    Q(28.0),\n    V2(80.0),\n    V3(70.0),\n    ka(1.2),\n    par{CL, Q, V2, V3, ka},\n    linode_par(3, 3) {\n      y0 << 0.0, 0.0, 0.0;\n\n      // to test LinOdeModel, we generate 2-cpt model's\n      // linear system.\n      double k10 = CL / V2;\n      double k12 = Q / V2;\n      double k21 = Q / V3;\n\n      /* two-cpt linear system\n       * | -ka            0,         0 |\n       * |  ka    -(k10 + k12)     k21 |\n       * |   0            k12     -k21 |\n       */\n      linode_par << -ka, 0.0, 0.0, ka, -(k10 + k12), k21, 0.0, k12, -k21;\n  }\n};\n\n#endif\n", "meta": {"hexsha": "4d75cde6ce8765e75c67d04bb4df68d8b49815bb", "size": 1443, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/pmx_cpt_model_test_fixture.hpp", "max_stars_repo_name": "metrumresearchgroup/torsten_math", "max_stars_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "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/pmx_cpt_model_test_fixture.hpp", "max_issues_repo_name": "metrumresearchgroup/torsten_math", "max_issues_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-27T23:53:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T23:57:43.000Z", "max_forks_repo_path": "test/unit/pmx_cpt_model_test_fixture.hpp", "max_forks_repo_name": "metrumresearchgroup/torsten_math", "max_forks_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "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.4576271186, "max_line_length": 73, "alphanum_fraction": 0.6091476091, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117812622843, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5325884853172315}}
{"text": "#ifndef DIRICHLET_SAMPLER_HPP\n#define DIRICHLET_SAMPLER_HPP\n\n#include <Eigen/Dense>\n#include <random>\n#include <iostream>\n\nnamespace kmers {\n  \n/**\n * Return Dirichlet random variate with specified positive vector of\n * values.  \n */\ntemplate <class RNG>\nEigen::VectorXd dirichlet_rng(const Eigen::VectorXd& alpha, RNG& rng) {\n  int N = alpha.size();\n  Eigen::VectorXd theta(N);\n  for (int n = 0; n < N; ++n) {\n    std::gamma_distribution<double> gamma_d(alpha(n), 1);\n    theta(n) = gamma_d(rng);\n  }\n  return theta / theta.array().sum();\n}\n\ntemplate <class RNG>\nEigen::VectorXd\nnormal_rng(uint64_t N, double mu, double sigma, RNG& rng) {\n  std::normal_distribution<double> normal_d(mu, sigma);\n  Eigen::VectorXd y;\n  for (int n = 0; n < N; ++n) {\n    y(n) = normal_d(rng);\n  }\n  return y;\n}\n\ntemplate <class RNG>\nstd::vector<uint64_t> multinomial_rng(uint64_t N, const std::vector<double>& theta, RNG& rng) {\n  std::vector<uint64_t> y(N, 0);\n  std::discrete_distribution<uint64_t> discrete_d(theta.begin(), theta.end());\n  for (uint64_t n = 0; n < N; ++n) {\n    uint64_t z = discrete_d(rng);\n    ++y[z];\n  }\n  return y;\n}\n}\n\n#endif\n", "meta": {"hexsha": "56f7e65f5dcf0cb31d1316d8d7d5340a4d95f433", "size": 1134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kmers/src/kmers/dirichlet-sampler.hpp", "max_stars_repo_name": "bob-carpenter/case-studies", "max_stars_repo_head_hexsha": "d9ac886989b08629f5fcedf6c9e06f3f1f1faff8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-04-25T15:24:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T03:18:12.000Z", "max_issues_repo_path": "kmers/src/kmers/dirichlet-sampler.hpp", "max_issues_repo_name": "bob-carpenter/case-studies", "max_issues_repo_head_hexsha": "d9ac886989b08629f5fcedf6c9e06f3f1f1faff8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kmers/src/kmers/dirichlet-sampler.hpp", "max_forks_repo_name": "bob-carpenter/case-studies", "max_forks_repo_head_hexsha": "d9ac886989b08629f5fcedf6c9e06f3f1f1faff8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T01:16:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-17T19:55:00.000Z", "avg_line_length": 23.1428571429, "max_line_length": 95, "alphanum_fraction": 0.6631393298, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5325884825667361}}
{"text": "#pragma once\n#include \"lue/framework/algorithm/aspect.hpp\"\n#include \"lue/framework/algorithm/focal_operation_export.hpp\"\n#include \"lue/framework/algorithm/definition/focal_operation.hpp\"\n#include \"lue/framework/algorithm/serialize/kernel.hpp\"\n#include \"lue/macro.hpp\"\n#include <boost/math/constants/constants.hpp>\n\n\nnamespace lue {\n    namespace detail {\n\n        template<\n            typename T>\n        T radians_to_compass_direction(\n            T angle)\n        {\n#ifndef NDEBUG\n            static T const pi = boost::math::constants::pi<T>();\n#endif\n            static T const half_pi = boost::math::constants::half_pi<T>();\n            static T const two_pi = boost::math::constants::two_pi<T>();\n\n            assert(angle >= -pi && angle <= pi);\n\n            // Input angle, in radians:\n            // east :  0.0 pi\n            // north:  0.5 pi\n            // west :  1.0 pi\n            // south: -0.5 pi\n\n            // Output angle, in radians:\n            // north: 0.0 pi\n            // east : 0.5 pi\n            // south: 1.0 pi\n            // west : 1.5 pi\n\n            if(angle < T{0})\n            {\n                angle = half_pi - angle;\n            }\n            else if(angle > half_pi)\n            {\n                angle = two_pi - angle + half_pi;\n            }\n            else\n            {\n                angle = half_pi - angle;\n            }\n\n            assert(angle >= T{0} && angle < T{2} * pi);\n\n            return angle;\n        }\n\n\n        template<\n            typename Element>\n        class Aspect\n        {\n\n            public:\n\n                using OutputElement = Element;\n\n\n                template<\n                    typename Kernel,\n                    typename OutputPolicies,\n                    typename InputPolicies,\n                    typename Subspan>\n                OutputElement operator()(\n                    [[maybe_unused]] Kernel const& kernel,\n                    OutputPolicies const& output_policies,\n                    InputPolicies const& input_policies,\n                    Subspan const& elevation_window) const\n                {\n                    static_assert(rank<Kernel> == 2);\n                    lue_hpx_assert(kernel.radius() == 1);\n\n                    auto const& indp{input_policies.input_no_data_policy()};\n                    auto const& ondp{output_policies.output_no_data_policy()};\n\n                    Element aspect;\n\n                    if(indp.is_no_data(elevation_window(1, 1)))\n                    {\n                        ondp.mark_no_data(aspect);\n                    }\n                    else\n                    {\n                        // TODO: all surrounding cells must have a valid value!!!\n                        //       Once done, no-data tests can be removed here. Temp variables\n                        //       can be remove too.\n\n                        // west - east\n                        // dz_dx = (w[0, 0] + 2 * w[1, 0] + w[2, 0]) - (w[0, 2] + 2 * w[1, 2] + w[2, 2])\n                        //       = tmp1 - tmp2\n\n                        // south - north\n                        // dz_dy = (w[2, 0] + 2 * w[2, 1] + w[2, 2]) - (w[0, 0] + 2 * w[0, 1] + w[0, 2])\n                        //       = tmp3 - tmp4\n\n                        Element tmp1{0};\n\n                        if(!indp.is_no_data(elevation_window(0, 0)))\n                        {\n                            tmp1 += elevation_window(0, 0);\n                        }\n\n                        if(!indp.is_no_data(elevation_window(1, 0)))\n                        {\n                            tmp1 += 2 * elevation_window(1, 0);\n                        }\n\n                        if(!indp.is_no_data(elevation_window(2, 0)))\n                        {\n                            tmp1 += elevation_window(2, 0);\n                        }\n\n                        Element tmp2{0};\n\n                        if(!indp.is_no_data(elevation_window(0, 2)))\n                        {\n                            tmp2 += elevation_window(0, 2);\n                        }\n\n                        if(!indp.is_no_data(elevation_window(1, 2)))\n                        {\n                            tmp2 += 2 * elevation_window(1, 2);\n                        }\n\n                        if(!indp.is_no_data(elevation_window(2, 2)))\n                        {\n                            tmp2 += elevation_window(2, 2);\n                        }\n\n                        Element tmp3{0};\n\n                        if(!indp.is_no_data(elevation_window(2, 0)))\n                        {\n                            tmp3 += elevation_window(2, 0);\n                        }\n\n                        if(!indp.is_no_data(elevation_window(2, 1)))\n                        {\n                            tmp3 += 2 * elevation_window(2, 1);\n                        }\n\n                        if(!indp.is_no_data(elevation_window(2, 2)))\n                        {\n                            tmp3 += elevation_window(2, 2);\n                        }\n\n                        Element tmp4{0};\n\n                        if(!indp.is_no_data(elevation_window(0, 0)))\n                        {\n                            tmp4 += elevation_window(0, 0);\n                        }\n\n                        if(!indp.is_no_data(elevation_window(0, 1)))\n                        {\n                            tmp4 += 2 * elevation_window(0, 1);\n                        }\n\n                        if(!indp.is_no_data(elevation_window(0, 2)))\n                        {\n                            tmp4 += elevation_window(0, 2);\n                        }\n\n                        Element const dz_dx = tmp1 - tmp2;\n                        Element const dz_dy = tmp3 - tmp4;\n\n                        aspect = (dz_dx == Element{0} && dz_dy == Element{0})\n                            ? -1  // Flat cell, pointing upwards\n                            : radians_to_compass_direction(std::atan2(dz_dy, dz_dx))\n                            ;\n                    }\n\n                    return aspect;\n                }\n\n        };\n\n    }  // namespace detail\n\n\n    template<\n        typename Policies,\n        typename Element,\n        Rank rank>\n    PartitionedArray<Element, rank> aspect(\n        Policies const& policies,\n        PartitionedArray<Element, rank> const& elevation)\n    {\n        using Functor = detail::Aspect<Element>;\n\n        // Only used for its radius. Weights are not used.\n        auto kernel{box_kernel<bool, 2>(1, true)};\n\n        return focal_operation(policies, elevation, std::move(kernel), Functor{});\n    }\n\n}  // namespace lue\n\n\n#define LUE_INSTANTIATE_ASPECT(                         \\\n    Policies, Element)                                  \\\n                                                        \\\n    template LUE_FOCAL_OPERATION_EXPORT                 \\\n    PartitionedArray<Element, 2> aspect<                \\\n            ArgumentType<void(Policies)>, Element, 2>(  \\\n        ArgumentType<void(Policies)> const&,            \\\n        PartitionedArray<Element, 2> const&);\n", "meta": {"hexsha": "1bcfaa76c680a866831448a44edb12c561f3369b", "size": 7047, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/framework/algorithm/include/lue/framework/algorithm/definition/aspect.hpp", "max_stars_repo_name": "pcraster/lue", "max_stars_repo_head_hexsha": "e64c18f78a8b6d8a602b7578a2572e9740969202", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-14T15:51:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-14T15:51:12.000Z", "max_issues_repo_path": "source/framework/algorithm/include/lue/framework/algorithm/definition/aspect.hpp", "max_issues_repo_name": "pcraster/lue", "max_issues_repo_head_hexsha": "e64c18f78a8b6d8a602b7578a2572e9740969202", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 262.0, "max_issues_repo_issues_event_min_datetime": "2016-08-11T10:12:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-13T18:09:16.000Z", "max_forks_repo_path": "source/framework/algorithm/include/lue/framework/algorithm/definition/aspect.hpp", "max_forks_repo_name": "pcraster/lue", "max_forks_repo_head_hexsha": "e64c18f78a8b6d8a602b7578a2572e9740969202", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-11T09:49:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T09:49:41.000Z", "avg_line_length": 32.625, "max_line_length": 104, "alphanum_fraction": 0.4024407549, "num_tokens": 1441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5325884712727518}}
{"text": "#include <so_linterp.h>\n#include <pybindings.h>\n\n#include <cmath>\n#include <boost/python.hpp>\nnamespace bp = boost::python;\n\ndouble test_trig(int table_size, int verbose)\n{\n    // Report maximimum absolute discrepancy in angle.\n    double worst = 0.;\n    double lo = -1., hi = 1., step = .01;\n\n    asinTable asin_lt(table_size);\n    for (double x = lo; x < hi; x += step) {\n        double y0 = asin(x);\n        double y1 = asin_lt.get(x);\n        worst = std::max(worst, std::abs(y1 - y0));\n        if (verbose)\n            std::cout << \"asin(\" << x << \")\" << \" \"\n                      << y0 << \" \" << y1 << \" \" << y1 - y0 << \"\\n\";\n    }\n\n    atan2Table atan2_lt(table_size);\n    for (double _x = -3; _x < 3.1; _x += 0.5) {\n        for (double _y = lo; _y < hi; _y += step) {\n            double y0 = atan2(_y, _x);\n            double y1 = atan2_lt.get(_y, _x);\n            worst = std::max(worst, std::abs(y1 - y0));\n            if (verbose)\n                std::cout << \"atan2(\" << _y << \", \" << _x << \") \"\n                          << y0 << \" \" << y1 << \" \" << y1 - y0 << \"\\n\";\n        }\n    }\n\n    return worst;\n}\n\nPYBINDINGS(\"so3g\")\n{\n    bp::def(\"test_trig\", test_trig,\n        \"For use in test suite -- determines worst arctrig discrepancy, in radians.\");\n}\n", "meta": {"hexsha": "2758f4e014e3932eb9c9fe25047fa207e3f55397", "size": 1264, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/so_linterp.cxx", "max_stars_repo_name": "tskisner/so3g", "max_stars_repo_head_hexsha": "75c1d8dea84f862bdd2c9fa2c2f9d1c5b8da5eec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-09-02T14:17:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T16:43:14.000Z", "max_issues_repo_path": "src/so_linterp.cxx", "max_issues_repo_name": "tskisner/so3g", "max_issues_repo_head_hexsha": "75c1d8dea84f862bdd2c9fa2c2f9d1c5b8da5eec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 70.0, "max_issues_repo_issues_event_min_datetime": "2019-05-16T23:42:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T14:35:35.000Z", "max_forks_repo_path": "src/so_linterp.cxx", "max_forks_repo_name": "tskisner/so3g", "max_forks_repo_head_hexsha": "75c1d8dea84f862bdd2c9fa2c2f9d1c5b8da5eec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-17T18:20:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T20:35:44.000Z", "avg_line_length": 28.7272727273, "max_line_length": 86, "alphanum_fraction": 0.4841772152, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5325311122955309}}
{"text": "#include <Eigen/Core>\n#include <deque>\n#include <iostream>\n#include <map>\n#include <opencv2/calib3d.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc.hpp>\n#include <set>\n#include <unordered_set>\n\n#include \"tag_detection/timer.h\"\n\ndouble rad2deg(double rad) {\n  return rad * 180.0 / M_PI;\n}\n\ndouble rad2posdeg(double rad) {\n  auto deg = rad2deg(rad);\n  while (deg < 0) {\n    deg += 360.0;\n  }\n  return deg;\n}\n\nstruct ImageGradients {\n  cv::Mat abs;\n  cv::Mat direction;\n};\n\ncv::Vec3b HSVtoBGR(const cv::Vec3f &hsv) {\n  cv::Mat_<cv::Vec3f> hsv_vec(hsv);\n  cv::Mat_<cv::Vec3f> bgr_vec;\n\n  cv::cvtColor(hsv_vec, bgr_vec, cv::COLOR_HSV2BGR);\n\n  bgr_vec *= 255;\n\n  return bgr_vec(0);\n}\n\ncv::Mat VisualizeGradientDirections(const ImageGradients &gradients) {\n  std::vector<double> vals;\n  for (int y = 0; y < gradients.abs.rows; ++y) {\n    for (int x = 0; x < gradients.abs.cols; ++x) {\n      vals.push_back(gradients.abs.at<double>(y, x));\n    }\n  }\n  std::sort(vals.begin(), vals.end());\n  const auto max_gradient = vals[vals.size() * 0.8];\n  std::cout << \" max grad \" << max_gradient << std::endl;\n\n  cv::Mat grad_dir_viz(gradients.abs.rows, gradients.abs.cols, CV_8UC3, cv::Scalar::all(0));\n  for (int y = 0; y < gradients.direction.rows; ++y) {\n    for (int x = 0; x < gradients.direction.cols; ++x) {\n      cv::Vec3f hsv{float(rad2posdeg(gradients.direction.at<double>(y, x))),  //\n                    1.0,                                                      //\n                    float(std::min(gradients.abs.at<double>(y, x) / max_gradient, 1.0))};\n      auto &bgr = grad_dir_viz.at<cv::Vec3b>(y, x);\n      bgr = HSVtoBGR(hsv);\n    }\n  }\n  return grad_dir_viz;\n}\n\n// TODO:: Missing: Non maxima suppression\nImageGradients CalculateImageGradients(const cv::Mat &mat, const bool debug) {\n  ImageGradients gradients;\n  cv::Mat grad_x, grad_y;\n  cv::Sobel(mat, grad_x, CV_32F, 1, 0);  // Opt: try 16S (short int)\n  cv::Sobel(mat, grad_y, CV_32F, 0, 1);\n\n  gradients.abs = cv::Mat(mat.rows, mat.cols, CV_64F, cv::Scalar(0));  // Opt: use short\n  gradients.direction = cv::Mat(mat.rows, mat.cols, CV_64F,\n                                cv::Scalar(0));  // Opt: use short? (when int atan2 possible)\n  for (int y = 0; y < mat.rows; ++y) {\n    for (int x = 0; x < mat.cols; ++x) {\n      const auto &dx = grad_x.at<float>(y, x);\n      const auto &dy = grad_y.at<float>(y, x);\n      gradients.abs.at<double>(y, x) = std::sqrt(dx * dx + dy * dy);  // Opt: remove sqrt\n      gradients.direction.at<double>(y, x) = std::atan2(dy, dx);\n    }\n  }\n  if (debug) {\n    cv::imwrite(\"01_img_grad.png\", gradients.abs);\n    cv::imwrite(\"02_img_dir.png\", VisualizeGradientDirections(gradients));\n  }\n  return gradients;\n}\n\nclass LinePoints {\n public:\n  void AddPoint(const Eigen::Vector2i &point, const double gradient_direction) {\n    points_.push_back(point);\n    angles_.push_back(gradient_direction);\n    x_sum_ += std::cos(gradient_direction);\n    y_sum_ += std::sin(gradient_direction);\n  }\n\n  double GetMeanDirection() const {\n    const auto ave_y = y_sum_ / points_.size();\n    const auto ave_x = x_sum_ / points_.size();\n    const auto ave = std::atan2(ave_y, ave_x);\n    return ave;\n  }\n\n  std::size_t Size() const { return points_.size(); }\n  bool Empty() const { return points_.empty(); }\n  const std::vector<Eigen::Vector2i> &Points() const { return points_; }\n\n private:\n  std::vector<Eigen::Vector2i> points_;\n  std::vector<double> angles_;\n  double x_sum_{};\n  double y_sum_{};\n};\n\nconst std::vector<Eigen::Vector2i> CONNECT_FOUR{{-1, 0}, {0, -1}, {1, 0}, {0, 1}};\nconst std::vector<Eigen::Vector2i> CONNECT_EIGHT{{-1, -1}, {0, -1}, {1, -1}, {1, 0},\n                                                 {1, 1},   {0, 1},  {-1, 1}, {-1, 0}};\n\nnamespace Eigen {\nbool operator<(const Eigen::Vector2i &a, const Eigen::Vector2i &b) {\n  return a.x() < b.x() || (a.x() == b.x() && a.y() < b.y());\n}\n}  // namespace Eigen\n\ndouble DeltaAngle(const double ang_1, const double ang_2) {\n  auto delta = std::abs(ang_1 - ang_2);\n  if (delta > M_PI) {\n    delta -= 2 * M_PI;\n  }\n  return std::abs(delta);\n}\n\nLinePoints ClusterPoints(const Eigen::Vector2i &start_pt, const double abs_thresh,\n                         const double ang_thresh, const ImageGradients &gradients,\n                         std::set<Eigen::Vector2i> *processed_points) {\n  LinePoints points{};\n  std::deque<Eigen::Vector2i> open_points;\n  open_points.push_back(start_pt);\n  while (not open_points.empty()) {\n    auto current_point = open_points.back();\n    auto current_dir = gradients.direction.at<double>(current_point.y(), current_point.x());\n    open_points.pop_back();\n\n    points.AddPoint(current_point, current_dir);\n    processed_points->insert(current_point);\n\n    for (const auto &dir : CONNECT_FOUR) {\n      const auto &candidate = current_point + dir;\n      if (candidate.x() < 0 || candidate.x() >= gradients.abs.cols || candidate.y() < 0 ||\n          candidate.y() >= gradients.abs.rows) {\n        continue;\n      }\n      if (processed_points->count(candidate) == 1) {\n        continue;\n      }\n\n      auto abs = gradients.abs.at<double>(candidate.y(), candidate.x());\n      auto grad_dir = gradients.direction.at<double>(candidate.y(), candidate.x());\n      if (abs > abs_thresh && DeltaAngle(points.GetMeanDirection(), grad_dir) < ang_thresh) {\n        open_points.push_back(candidate);\n      }\n    }\n  }\n\n  return points;\n}\n\nstd::vector<LinePoints> ClusterGradientDirections(const ImageGradients &gradients,\n                                                  const double abs_thresh, const double ang_thresh,\n                                                  const int min_cluster_size) {\n  std::vector<LinePoints> lines;\n  std::set<Eigen::Vector2i> processed_points;\n\n  for (int y = 0; y < gradients.abs.rows; ++y) {\n    for (int x = 0; x < gradients.abs.cols; ++x) {\n      if (processed_points.count({x, y}) == 1) {\n        continue;\n      }\n      const auto &abs_val = gradients.abs.at<double>(y, x);\n      if (abs_val < abs_thresh) {\n        continue;\n      }\n      const auto cluster = ClusterPoints(Eigen::Vector2i{x, y}, abs_thresh, ang_thresh, gradients,\n                                         &processed_points);\n      if (cluster.Size() >= min_cluster_size) {\n        lines.push_back(cluster);\n      }\n    }\n  }\n\n  return lines;\n}\n\ncv::Mat GetThresholdedGradient(const ImageGradients &img_gradients, const double threshold) {\n  cv::Mat grad_abs_thresh(img_gradients.abs.rows, img_gradients.abs.cols, CV_8U, cv::Scalar(0));\n  for (int y = 0; y < grad_abs_thresh.rows; ++y) {\n    for (int x = 0; x < grad_abs_thresh.cols; ++x) {\n      if (img_gradients.abs.at<double>(y, x) > threshold) {\n        grad_abs_thresh.at<uchar>(y, x) = 255;\n      }\n    }\n  }\n  return grad_abs_thresh;\n}\n\ncv::Mat VisualizeLinePoints(const std::vector<LinePoints> &lines, const int rows, const int cols) {\n  cv::Mat viz_clusters(rows, cols, CV_8UC3, cv::Scalar::all(0));\n  for (const auto &line : lines) {\n    const float rand_h = rand() % 360;\n    const auto bgr = HSVtoBGR({rand_h, 1.0, 1.0});\n    for (const auto &point : line.Points()) {\n      viz_clusters.at<cv::Vec3b>(point.y(), point.x()) = bgr;\n    }\n  }\n  return viz_clusters;\n}\n\nstruct Line {\n  Eigen::Vector2i start;\n  Eigen::Vector2i end;\n};\n\nEigen::Vector2i GetFurthestPoint(const Eigen::Vector2i &compare_pt, const LinePoints &line_points) {\n  Eigen::Vector2i ret_val = compare_pt;\n  double max_dist = 0;\n  for (const auto &pt : line_points.Points()) {\n    const double dist = (compare_pt - pt).squaredNorm();\n    if (dist > max_dist) {\n      ret_val = pt;\n      max_dist = dist;\n    }\n  }\n  return ret_val;\n}\n\nLine MakeLine(const LinePoints &line_points) {\n  auto any_pt = line_points.Points()[line_points.Size() / 2];\n  Line line{};\n  line.start = GetFurthestPoint(any_pt, line_points);\n  line.end = GetFurthestPoint(line.start, line_points);\n  return line;\n}\n\nstd::vector<Line> MakeLines(const std::vector<LinePoints> &lines_points,\n                            const double min_line_length) {\n  const double min_line_length_squared = min_line_length * min_line_length;\n  std::vector<Line> lines;\n  lines.reserve(lines_points.size());\n  for (const auto &line_points : lines_points) {\n    auto line = MakeLine(line_points);\n    if ((line.start - line.end).squaredNorm() < min_line_length_squared) {\n      continue;\n    }\n    lines.push_back(std::move(line));\n  }\n  return lines;\n}\n\ncv::Mat VisualizeLines(const cv::Mat &img, const std::vector<Line> &lines) {\n  cv::Mat viz_lines = img.clone();\n  for (const auto &line : lines) {\n    cv::line(viz_lines, {line.start.x(), line.start.y()}, {line.end.x(), line.end.y()}, {0, 255, 0},\n             1);\n  }\n  return viz_lines;\n}\n\nbool LinesAreConnected(const Line &line_a, const Line &line_b, const double squared_distance) {\n  return (line_a.start - line_b.start).squaredNorm() < squared_distance ||\n         (line_a.start - line_b.end).squaredNorm() < squared_distance ||\n         (line_a.end - line_b.start).squaredNorm() < squared_distance ||\n         (line_a.end - line_b.end).squaredNorm() < squared_distance;\n}\n\nstruct LineEnds {\n  Eigen::Vector2i line_end_a;\n  Eigen::Vector2i line_end_b;\n};\n\ndouble GetDistance(const LineEnds &line_ends) {\n  return (line_ends.line_end_a - line_ends.line_end_b).squaredNorm();\n}\n\nbool operator<(const LineEnds &lhs, const LineEnds &rhs) {\n  return GetDistance(lhs) < GetDistance(rhs);\n}\n\nLineEnds GetConnectedLineEnds(const Line &line_a, const Line &line_b) {\n  std::vector<LineEnds> all_line_connections;\n  all_line_connections.push_back({line_a.start, line_b.start});\n  all_line_connections.push_back({line_a.start, line_b.end});\n  all_line_connections.push_back({line_a.end, line_b.start});\n  all_line_connections.push_back({line_a.end, line_b.end});\n  return std::min(all_line_connections[0],\n                  std::min(all_line_connections[1],\n                           std::min(all_line_connections[2], all_line_connections[3])));\n}\n\nstd::map<int, std::set<int>> MakeLineConnectivity(const std::vector<Line> &lines,\n                                                  const double &distance) {\n  const auto distance_squared = distance * distance;\n  std::map<int, std::set<int>> line_connectivity;\n  for (int i = 0; i < lines.size(); ++i) {\n    for (int j = i + 1; j < lines.size(); ++j) {\n      if (LinesAreConnected(lines[i], lines[j], distance_squared)) {\n        line_connectivity[i].insert(j);\n        line_connectivity[j].insert(i);\n      }\n    }\n  }\n  return line_connectivity;\n}\n\ncv::Mat VisualizeLineConnectivity(const cv::Mat &img, const std::vector<Line> &lines,\n                                  const std::map<int, std::set<int>> &line_connectivity) {\n  cv::Mat viz_lines = img.clone();\n  for (const auto &[line_id, other_lines] : line_connectivity) {\n    for (const auto &other_line_id : other_lines) {\n      const auto &line = lines[line_id];\n      const auto &other_line = lines[other_line_id];\n\n      const Eigen::Vector2i line_centroid = (line.start + line.end) / 2;\n      const Eigen::Vector2i other_line_centroid = (other_line.start + other_line.end) / 2;\n\n      const auto connection_points = GetConnectedLineEnds(line, other_line);\n\n      const Eigen::Vector2i line_pt = (line_centroid + connection_points.line_end_a) / 2;\n      const Eigen::Vector2i other_line_pt =\n          (other_line_centroid + connection_points.line_end_b) / 2;\n\n      cv::line(viz_lines, {line_pt.x(), line_pt.y()}, {other_line_pt.x(), other_line_pt.y()},\n               {255, 0, 255}, 1);\n    }\n  }\n  return viz_lines;\n}\n\nstruct Quad {\n  std::array<Eigen::Vector2d, 4> corners{};\n};\n\n// TODO:: Missing:: subpix refine\nQuad CreateQuad(const std::vector<int> &quad_line_ids, const std::vector<Line> &lines) {\n  Quad quad{};\n  for (int i = 0; i < 4; ++i) {\n    auto line_ends =\n        GetConnectedLineEnds(lines[quad_line_ids[i]], lines[quad_line_ids[(i + 1) % 4]]);\n    quad.corners[i] =\n        (line_ends.line_end_a.cast<double>() + line_ends.line_end_b.cast<double>()) / 2.0;\n  }\n  // TODO:: put corner ordering in a function\n  // Calculate centroid. (put in function)\n  Eigen::Vector2d centroid{0, 0};\n  for (const auto &corner : quad.corners) {\n    centroid += corner;\n  }\n  centroid /= 4.0;\n\n  struct CornerWithAngle {\n    Eigen::Vector2d corner;\n    double angle;\n  };\n\n  // Get the angle of each point from the center.\n  std::vector<CornerWithAngle> corners;\n  corners.reserve(4);\n  for (const auto &corner : quad.corners) {\n    auto &corner_with_angle = corners.emplace_back();\n    corner_with_angle.corner = corner;\n    auto &angle = corner_with_angle.angle;\n    angle = std::atan2(centroid.y() - corner.y(), centroid.x() - corner.x());\n    if (angle < 0) {\n      angle += 2 * M_PI;\n    }\n  }\n\n  // Sort the points by angle, descending to get them in clockwise order.\n  std::sort(corners.begin(), corners.end(), [](const auto &corner_1, const auto &corner_2) {\n    return corner_1.angle > corner_2.angle;\n  });\n\n  for (int i = 0; i < 4; ++i) {\n    quad.corners[i] = corners[i].corner;\n  }\n\n  return quad;\n}\n\nstruct UniqueQuad {\n  UniqueQuad(const std::vector<int> &quad_line_ids) {\n    assert(quad_line_ids.size() == 4);\n    for (int i = 0; i < 4; ++i) {\n      line_ids[i] = quad_line_ids[i];\n    }\n    std::sort(line_ids.begin(), line_ids.end());\n  }\n\n  std::array<int, 4> line_ids{};\n};\n\nbool operator<(const UniqueQuad &lhs, const UniqueQuad &rhs) {\n  for (int i = 0; i < 4; ++i) {\n    if (lhs.line_ids[i] < rhs.line_ids[i]) {\n      return true;\n    }\n    if (lhs.line_ids[i] > rhs.line_ids[i]) {\n      return false;\n    }\n  }\n  return false;\n}\n\nbool LinesConnected(const int id_1, const int id_2,\n                    const std::map<int, std::set<int>> &line_connectivity) {\n  return line_connectivity.count(id_1) == 1 && line_connectivity.at(id_1).count(id_2) == 1;\n}\n\ntemplate <typename T>\nbool VectorContainsVal(const std::vector<T> &vec, const T &val) {\n  return std::find(vec.begin(), vec.end(), val) != vec.end();\n}\n\nstd::vector<std::vector<int>> FindQuadsFromStartLine(\n    const std::vector<Line> &lines,                         //\n    const std::map<int, std::set<int>> &line_connectivity,  //\n    const int start_line_id) {                              //\n  std::vector<std::vector<int>> quads;\n  std::deque<std::vector<int>> potential_quads;\n  potential_quads.push_back({start_line_id});\n  while (not potential_quads.empty()) {\n    const auto potential_quad = potential_quads.back();\n    potential_quads.pop_back();\n\n    if (potential_quad.size() == 4 &&\n        LinesConnected(potential_quad.front(), potential_quad.back(), line_connectivity)) {\n      quads.push_back(potential_quad);\n    }\n    if (potential_quad.size() < 4) {\n      for (const auto &new_edge : line_connectivity.at(potential_quad.back())) {\n        if (VectorContainsVal(potential_quad, new_edge)) {\n          continue;\n        }\n\n        auto new_potential_quad = potential_quad;\n        new_potential_quad.push_back(new_edge);\n        potential_quads.push_back(new_potential_quad);\n      }\n    }\n  }\n\n  return quads;\n}\n\nbool CheckQuadSideLengths(const Quad &quad, const double side_length) {\n  const double side_length_squared = side_length * side_length;\n  for (int i = 0; i < 4; ++i) {\n    const auto pt_a = quad.corners[i];\n    const auto pt_b = quad.corners[(i + 1) % 4];\n    if ((pt_a - pt_b).squaredNorm() < side_length_squared) {\n      return false;\n    }\n  }\n  return true;\n}\n\ntemplate <typename EigenPointContainer>\nstd::vector<cv::Point2f> ToCvPoints(const EigenPointContainer &points) {\n  std::vector<cv::Point2f> cv_points;\n  for (const auto &pt : points) {\n    cv_points.push_back({float(pt.x()), float(pt.y())});\n  }\n  return cv_points;\n}\n\nvoid RefineEdges(const cv::Mat &image, Quad *quad) {\n  constexpr int kWinSize = 2;\n  auto corners = ToCvPoints(quad->corners);\n  auto term_criteria = cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::COUNT, 40, 0.001);\n  cv::cornerSubPix(image, corners, {kWinSize, kWinSize}, {-1, -1}, term_criteria);\n  for (int i = 0; i < 4; ++i) {\n    quad->corners[i] = {corners[i].x, corners[i].y};\n  }\n}\n\nstd::vector<Quad> FindQuads(const std::vector<Line> &lines,\n                            const std::map<int, std::set<int>> &line_connectivity,\n                            const double min_side_length) {\n  std::vector<Quad> quads;\n  std::set<UniqueQuad> unique_quads;\n  for (const auto &[line_id, other_line_ids] : line_connectivity) {\n    auto potential_quads =\n        FindQuadsFromStartLine(lines, line_connectivity, line_id);  // TODO:: fix var name\n    for (const auto &quad_line_ids : potential_quads) {\n      const auto [itr, success] = unique_quads.insert(UniqueQuad(quad_line_ids));\n      if (success) {\n        auto quad = CreateQuad(quad_line_ids, lines);\n        if (CheckQuadSideLengths(quad, min_side_length)) {\n          quads.push_back(std::move(quad));\n        }\n      }\n    }\n  }\n  return quads;\n}\n\ncv::Mat VisualizeQuads(const cv::Mat &img, const std::vector<Quad> &quads) {\n  cv::Mat viz = img.clone();\n  int quad_counter{};\n  for (const auto &quad : quads) {\n    for (int i = 0; i < 4; ++i) {\n      // std::cout << \"  \" << quad.corners[i].x() << \", \" << quad.corners[i].y() << std::endl;\n      const auto pt_a = quad.corners[i].cast<int>();\n      const auto pt_b = quad.corners[(i + 1) % 4].cast<int>();\n      cv::line(viz, {pt_a.x(), pt_a.y()}, {pt_b.x(), pt_b.y()}, {0, 255, 0}, 1);\n    }\n  }\n  return viz;\n}\n\nint quad_counter = 0;\n\ntemplate <typename T>\nT GetMatMedian(const cv::Mat &mat) {\n  std::vector<T> vals;\n  vals.reserve(mat.cols * mat.rows);\n  for (int y = 0; y < mat.rows; ++y) {\n    for (int x = 0; x < mat.cols; ++x) {\n      vals.push_back(mat.at<T>(y, x));\n    }\n  }\n  std::nth_element(vals.begin(), vals.begin() + (vals.size() / 2), vals.end());\n  return vals[vals.size() / 2];\n}\n\n// TODO::rename function\nEigen::MatrixXd DecodeTag(const cv::Mat &tag_img, const int width, const int height,\n                          const int border, const int intensity_thresh) {\n  const int cell_width = tag_img.cols / width;\n  const int cell_height = tag_img.rows / height;\n  Eigen::MatrixXd tag_matrix(height, width);  // TODO:: double check constructor order\n  for (int i = 0; i < width; ++i) {\n    for (int j = 0; j < height; ++j) {\n      cv::Rect roi(i * cell_width, j * cell_height, cell_width, cell_height);\n      cv::Mat cell(tag_img, roi);\n      const int cell_val = GetMatMedian<uchar>(cell);\n      tag_matrix(j, i) = cell_val > intensity_thresh;\n    }\n  }\n  return tag_matrix;\n}\n\nint DecodeQuad(const cv::Mat &img, const Quad &quad) {\n  constexpr int tag_width = 8;\n  constexpr int tag_height = 8;\n  std::vector<cv::Point2d> corner_pts;\n  corner_pts.reserve(4);\n  for (const auto &corner : quad.corners) {  // TODO:: range based/transform\n    corner_pts.push_back({corner.x(), corner.y()});\n  }\n  const int rectified_size_x = tag_width * 8;\n  const int rectified_size_y = tag_width * 8;\n  std::vector<cv::Point2d> rectified_pts{\n      {0, 0}, {0, rectified_size_y}, {rectified_size_x, rectified_size_y}, {rectified_size_x, 0}};\n  const auto H = cv::findHomography(corner_pts, rectified_pts);\n  cv::Mat tag_rectified;\n  cv::warpPerspective(img, tag_rectified, H, {rectified_size_x, rectified_size_y});\n  std::cout << \"Quad \" << quad_counter << std::endl;\n  cv::imwrite(\"quad_\" + std::to_string(quad_counter++) + \".png\", tag_rectified);\n  const auto tag_matrix = DecodeTag(tag_rectified, tag_width, tag_height, 1, 110);\n  std::cout << \"Quad matrix: \" << std::endl << tag_matrix << std::endl;\n  return -1;\n}\n\nstd::vector<int> DecodeQuads(const cv::Mat &img, const std::vector<Quad> &quads) {\n  std::vector<int> quad_values;\n  quad_values.reserve(quads.size());\n  DecodeQuad(img, quads.front());\n   for (const auto &quad : quads) {\n   quad_values.push_back(DecodeQuad(img, quad));\n  }\n  return quad_values;\n}\n\nvoid RunDetection(const cv::Mat &mat) {\n  time_logger::TimeLogger timer;\n  time_logger::TimeLogger full_timer;\n  const bool debug = true;\n  cv::Mat bw_mat;\n  cv::cvtColor(mat, bw_mat, cv::COLOR_BGR2GRAY);\n  timer.logEvent(\"01_convert color\");\n  const auto img_gradients = CalculateImageGradients(bw_mat, debug);\n\n  timer.logEvent(\"02_Image gradients\");\n\n  constexpr double kAbsImgGradientThresh = 100;\n  constexpr double kMaxAngleClusterDiff = M_PI / 8;\n  constexpr int kMinLineClusterSize = 10;\n\n  const auto lines_points = ClusterGradientDirections(img_gradients, kAbsImgGradientThresh,\n                                                      kMaxAngleClusterDiff, kMinLineClusterSize);\n  timer.logEvent(\"03_Cluster gradients\");\n  std::cout << lines_points.size() << \" clusters found.\" << std::endl;\n  if (debug) {\n    cv::imwrite(\"03_gradient_thresh.png\",\n                GetThresholdedGradient(img_gradients, kAbsImgGradientThresh));\n    const auto viz_clusters = VisualizeLinePoints(lines_points, mat.rows, mat.cols);\n    cv::imwrite(\"04_clusters.png\", viz_clusters);\n  }\n\n  constexpr double kMinLineLength = 8;\n  const auto lines = MakeLines(lines_points, kMinLineLength);\n  timer.logEvent(\"04_Make lines\");\n  if (debug) {\n    cv::imwrite(\"05_lines.png\", VisualizeLines(mat, lines));\n  }\n\n  constexpr double kMaxInterLineDistance = 4;\n  const auto line_connectivity = MakeLineConnectivity(lines, kMaxInterLineDistance);\n  timer.logEvent(\"05_Make line connectivity\");\n  if (debug) {\n    const auto base_img = VisualizeLines(mat, lines);\n    cv::imwrite(\"06_line_connectivity.png\",\n                VisualizeLineConnectivity(base_img, lines, line_connectivity));\n  }\n\n  auto quads = FindQuads(lines, line_connectivity, kMinLineLength);\n  timer.logEvent(\"06_Find quads\");\n  if (debug) {\n    cv::imwrite(\"07_quads.png\", VisualizeQuads(mat, quads));\n  }\n  cv::Mat mat_bw;\n  cv::cvtColor(mat, mat_bw, cv::COLOR_BGR2GRAY);\n  for (auto &quad : quads) {\n    RefineEdges(mat_bw, &quad);\n  }\n  std::cout << \"Found \" << quads.size() << \" quads.\" << std::endl;\n  if (debug) {\n    cv::imwrite(\"08_quads_refined.png\", VisualizeQuads(mat, quads));\n  }\n\n  auto codes = DecodeQuads(bw_mat, quads);\n  timer.logEvent(\"09_Decode quads\");\n  timer.printLoggedEvents();\n  full_timer.logEvent(\"everything\");\n  full_timer.printLoggedEvents();\n}\n\n// TODO\n//\n// 1. Use canny instead of sobel for edges extraction for non max suppress. Connect 4 -> 8\n// 2. Fit lines to get line equation. Edges from line intersections\n//\n\nint main() {\n  std::string image_path = \"image.jpeg\";\n  cv::Mat img = cv::imread(image_path, cv::IMREAD_COLOR);\n  if (img.empty()) {\n    std::cout << \"Could not read the image: \" << image_path << std::endl;\n    return 1;\n  }\n\n  RunDetection(img);\n  std::cout << \"all good\" << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "f495227e482e465685cd5b1ad1da849357a80e9a", "size": 22608, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/pipeline.cc", "max_stars_repo_name": "rosskidson/tag_detection", "max_stars_repo_head_hexsha": "e0d1f0b99fa02b216222962e83fe366edcbd54d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pipeline.cc", "max_issues_repo_name": "rosskidson/tag_detection", "max_issues_repo_head_hexsha": "e0d1f0b99fa02b216222962e83fe366edcbd54d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pipeline.cc", "max_forks_repo_name": "rosskidson/tag_detection", "max_forks_repo_head_hexsha": "e0d1f0b99fa02b216222962e83fe366edcbd54d0", "max_forks_repo_licenses": ["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.8443113772, "max_line_length": 100, "alphanum_fraction": 0.6399946921, "num_tokens": 6364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5325311067623012}}
{"text": "\n//\u6b64\u6e90\u7801\u88ab\u6e05\u534e\u5b66\u795e\u5c39\u6210\u5927\u9b54\u738b\u4e13\u4e1a\u7ffb\u8bd1\u5206\u6790\u5e76\u4fee\u6539\n//\u5c39\u6210QQ77025077\n//\u5c39\u6210\u5fae\u4fe118510341407\n//\u5c39\u6210\u6240\u5728QQ\u7fa4721929980\n//\u5c39\u6210\u90ae\u7bb1 yinc13@mails.tsinghua.edu.cn\n//\u5c39\u6210\u6bd5\u4e1a\u4e8e\u6e05\u534e\u5927\u5b66,\u5fae\u8f6f\u533a\u5757\u94fe\u9886\u57df\u5168\u7403\u6700\u6709\u4ef7\u503c\u4e13\u5bb6\n//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620\n//\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\n/*\n    \u6b64\u6587\u4ef6\u662fRippled\u7684\u4e00\u90e8\u5206\uff1ahttps://github.com/ripple/rippled\n    \u7248\u6743\u6240\u6709\uff08c\uff092012-2015 Ripple Labs Inc.\n\n    \u4f7f\u7528\u3001\u590d\u5236\u3001\u4fee\u6539\u548c/\u6216\u5206\u53d1\u672c\u8f6f\u4ef6\u7684\u6743\u9650\n    \u7279\u6b64\u6388\u4e88\u514d\u8d39\u6216\u4e0d\u6536\u8d39\u7684\u76ee\u7684\uff0c\u524d\u63d0\u662f\n    \u7248\u6743\u58f0\u660e\u548c\u672c\u8bb8\u53ef\u58f0\u660e\u51fa\u73b0\u5728\u6240\u6709\u526f\u672c\u4e2d\u3002\n\n    \u672c\u8f6f\u4ef6\u6309\u201c\u539f\u6837\u201d\u63d0\u4f9b\uff0c\u4f5c\u8005\u4e0d\u4f5c\u4efb\u4f55\u4fdd\u8bc1\u3002\n    \u5173\u4e8e\u672c\u8f6f\u4ef6\uff0c\u5305\u62ec\n    \u9002\u9500\u6027\u548c\u9002\u7528\u6027\u3002\u5728\u4efb\u4f55\u60c5\u51b5\u4e0b\uff0c\u4f5c\u8005\u90fd\u4e0d\u5bf9\n    \u4efb\u4f55\u7279\u6b8a\u3001\u76f4\u63a5\u3001\u95f4\u63a5\u6216\u540e\u679c\u6027\u635f\u5bb3\u6216\u4efb\u4f55\u635f\u5bb3\n    \u56e0\u4f7f\u7528\u3001\u6570\u636e\u6216\u5229\u6da6\u635f\u5931\u800c\u5bfc\u81f4\u7684\u4efb\u4f55\u60c5\u51b5\uff0c\u65e0\u8bba\u662f\u5728\n    \u5408\u540c\u884c\u4e3a\u3001\u758f\u5ffd\u6216\u5176\u4ed6\u4fb5\u6743\u884c\u4e3a\n    \u6216\u4e0e\u672c\u8f6f\u4ef6\u7684\u4f7f\u7528\u6216\u6027\u80fd\u6709\u5173\u3002\n**/\n\n//==============================================================\n\n#include <ripple/basics/mulDiv.h>\n#include <ripple/basics/contract.h>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <limits>\n#include <utility>\n\nnamespace ripple\n{\n\nstd::pair<bool, std::uint64_t>\nmulDiv(std::uint64_t value, std::uint64_t mul, std::uint64_t div)\n{\n    using namespace boost::multiprecision;\n\n    uint128_t result;\n    result = multiply(result, value, mul);\n\n    result /= div;\n\n    auto const limit = std::numeric_limits<std::uint64_t>::max();\n\n    if (result > limit)\n        return { false, limit };\n\n    return { true, static_cast<std::uint64_t>(result) };\n}\n\n} //\u6d9f\u6f2a\n", "meta": {"hexsha": "a7ec62f2bfb8116bec9cc1c5af42081c3f47318c", "size": 1300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ripple/basics/impl/mulDiv.cpp", "max_stars_repo_name": "yinchengtsinghua/RippleCPPChinese", "max_stars_repo_head_hexsha": "a32a38a374547bdc5eb0fddcd657f45048aaad6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:36:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T07:10:39.000Z", "max_issues_repo_path": "src/ripple/basics/impl/mulDiv.cpp", "max_issues_repo_name": "yinchengtsinghua/RippleCPPChinese", "max_issues_repo_head_hexsha": "a32a38a374547bdc5eb0fddcd657f45048aaad6a", "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/ripple/basics/impl/mulDiv.cpp", "max_forks_repo_name": "yinchengtsinghua/RippleCPPChinese", "max_forks_repo_head_hexsha": "a32a38a374547bdc5eb0fddcd657f45048aaad6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-14T07:26:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T07:25:01.000Z", "avg_line_length": 22.8070175439, "max_line_length": 114, "alphanum_fraction": 0.6076923077, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5325311062479035}}
{"text": "//\n// Copyright 2019 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n// Copyright 2021 Scramjet911 <36035352+Scramjet911@users.noreply.github.com>\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_HESSIAN_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_HESSIAN_HPP\n\n#include <boost/gil/image_view.hpp>\n#include <boost/gil/typedefs.hpp>\n#include <boost/gil/extension/numeric/kernel.hpp>\n#include <stdexcept>\n\nnamespace boost { namespace gil {\n\n/// \\brief Computes Hessian response\n///\n/// Computes Hessian response based on computed entries of Hessian matrix, e.g. second order\n/// derivates in x and y, and derivatives in both x, y.\n/// d stands for derivative, and x or y stand for derivative direction. For example,\n/// ddxx means taking two derivatives (gradients) in horizontal direction.\n/// Weights change perception of surroinding pixels.\n/// Additional filtering is strongly advised.\ntemplate <typename GradientView, typename T, typename Allocator, typename OutputView>\ninline void compute_hessian_responses(\n    GradientView ddxx,\n    GradientView dxdy,\n    GradientView ddyy,\n    const detail::kernel_2d<T, Allocator>& weights,\n    OutputView dst)\n{\n    if (ddxx.dimensions() != ddyy.dimensions()\n        || ddyy.dimensions() != dxdy.dimensions()\n        || dxdy.dimensions() != dst.dimensions()\n        || weights.center_x() != weights.center_y())\n    {\n        throw std::invalid_argument(\"dimensions of views are not the same\"\n            \" or weights don't have equal width and height\"\n            \" or weights' dimensions are not odd\");\n    }\n    // Use pixel type of output, as values will be written to output\n    using pixel_t = typename std::remove_reference<decltype(std::declval<OutputView>()(0, 0))>::type;\n\n    using channel_t = typename std::remove_reference\n        <\n            decltype(std::declval<pixel_t>().at(std::integral_constant<int, 0>{}))\n        >::type;\n\n\n    auto center = weights.center_y();\n    for (auto y = center; y < dst.height() - center; ++y)\n    {\n        for (auto x = center; x < dst.width() - center; ++x)\n        {\n            auto ddxx_i = channel_t();\n            auto ddyy_i = channel_t();\n            auto dxdy_i = channel_t();\n            for (typename OutputView::coord_t w_y = 0; w_y < static_cast<std::ptrdiff_t>(weights.size()); ++w_y)\n            {\n                for (typename OutputView::coord_t w_x = 0; w_x < static_cast<std::ptrdiff_t>(weights.size()); ++w_x)\n                {\n                    ddxx_i += ddxx(x + w_x - center, y + w_y - center)\n                        .at(std::integral_constant<int, 0>{}) * weights.at(w_x, w_y);\n                    ddyy_i += ddyy(x + w_x - center, y + w_y - center)\n                        .at(std::integral_constant<int, 0>{}) * weights.at(w_x, w_y);\n                    dxdy_i += dxdy(x + w_x - center, y + w_y - center)\n                        .at(std::integral_constant<int, 0>{}) * weights.at(w_x, w_y);\n                }\n            }\n            auto determinant = ddxx_i * ddyy_i - dxdy_i * dxdy_i;\n            dst(x, y).at(std::integral_constant<int, 0>{}) = determinant;\n        }\n    }\n}\n\n}} // namespace boost::gil\n\n#endif\n", "meta": {"hexsha": "f37c0ffdd554ec49ba52ca9e625b9739105a2558", "size": 3314, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/hessian.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/hessian.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/hessian.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": 40.9135802469, "max_line_length": 116, "alphanum_fraction": 0.630054315, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5324898694311871}}
{"text": "/*\n * Copyright Nick Thompson, 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n#include <cstdint>\n#include <cmath>\n#include <boost/math/quadrature/wavelet_transforms.hpp>\n#include <Eigen/Dense>\n\n\nint main()\n{\n    using boost::math::quadrature::daubechies_wavelet_transform;\n    double a = 1.3;\n    auto f = [&a](double t) {\n        if(t==0) {\n            return double(0);\n        }\n        return std::sin(a/t);\n    };\n\n    auto Wf = daubechies_wavelet_transform<decltype(f), double, 8>(f);\n\n    Eigen::MatrixXd grid(512, 512);\n    double s = 7;\n    double t = 0;\n    grid(0,0) = Wf(s, t);\n\n    auto g = [&a](double t)->std::complex<double> {\n        if (t==0) {\n            return {0.0, 0.0};\n        }\n        return std::exp(std::complex<double>(0.0, a/t));\n    };\n\n    auto Wg = daubechies_wavelet_transform<decltype(g), double, 8>(g);\n    std::cout << \"W[f](s,t) = \" << Wf(s,t) << \"\\n\";\n    std::cout << \"W[g](s,t) = \" << Wg(s, t) << \"\\n\";\n    std::cout << Wg(0.0, 3.5) << \"\\n\";\n    std::cout << Wf(0.0, 4.8) << \"\\n\";\n    std::cout << \"W[f](-s,t) = \" << Wf(-s, t) << \"\\n\";\n    std::cout << \"W[g](-s,t) = \" << Wg(-s, t) << \"\\n\";\n\n}\n", "meta": {"hexsha": "67cdde80349c3aacbfd3d2e0ac56e9effb356cf4", "size": 1286, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/example/daubechies_wavelets/wavelet_transform.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/example/daubechies_wavelets/wavelet_transform.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/example/daubechies_wavelets/wavelet_transform.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": 27.3617021277, "max_line_length": 70, "alphanum_fraction": 0.5357698289, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5324898658511883}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#include <type_traits>\n#include <algorithm>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/banded.hpp>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include <boost/numeric/bindings/lapack/driver.hpp>\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\nnamespace lapack=boost::numeric::bindings::lapack;\n\nint main(int argc, char *argv[]) {\n  typedef std::complex<double> complex;\n  typedef ublas::vector<complex> vector;\n  typedef ublas::vector<int> p_vector;\n  typedef ublas::banded_matrix<complex, ublas::column_major> matrix;\n  typedef typename std::make_signed<vector::size_type>::type size_type;\n\n  rand_normal<complex>::reset();\n  size_type n=1024, kl=3, ku=2;\n  matrix A(n, n, kl, ku+kl);\n  for (size_type j=0; j<n; ++j) {\n    for (size_type i=std::max(size_type(0), j-ku-kl); i<std::max(size_type(0), j-ku); ++i)\n      A(i, j)=complex(0);\n    for (size_type i=std::max(size_type(0), j-ku); i<std::min(n, j+kl+1); ++i)\n      A(i, j)=rand_normal<complex>::get();\n  }\n  vector b(n);\n  for (size_type i=0; i<n; ++i)\n    b(i)=rand_normal<complex>::get();\n  matrix A_bak(A);\n  vector x(b);\n  p_vector p(n);  // pivots\n  int info=lapack::gbsv(A, p, x); // solve\n  if (info==0) {\n    // res <- A*x - b\n    vector res(b);\n    blas::gbmv(complex(1, 0), A_bak, x, complex(-1, 0), res);\n    std::cout << \"norm of residual : \" << blas::nrm2(res) << '\\n';\n  } else\n    if (info>0)\n      std::cout << \"singular matrix\\n\";\n    else \n      std::cout << \"illegal arguments\\n\";\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "b9e1944394a2cc86fc8ab017805e27a1386e35de", "size": 1789, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/lapack/gbsv.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/lapack/gbsv.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/lapack/gbsv.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.5272727273, "max_line_length": 90, "alphanum_fraction": 0.6623812186, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5324600537231522}}
{"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/collision/collision_ray_aabb.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\nBOOST_AUTO_TEST_SUITE(opentissue_collision_ray_aabb);\n\nBOOST_AUTO_TEST_CASE(simple_test)\n{\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n  typedef math_types::vector3_type                         vector3_type;\n  \n\n  vector3_type min_coord( -1.0, -1.0, -1.0 );\n  vector3_type max_coord(  1.0,  1.0,  1.0 );\n  vector3_type r;\n  vector3_type p;\n  bool collision = false;\n  \n  // x-faces are separating planes\n\n  r = vector3_type(1.0, 0.0, 0.0 ) ;\n  p = vector3_type(2.0, 0.0, 0.0 ) ;\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( !collision );\n\n  r = vector3_type(-1.0, 0.0, 0.0 ) ;\n  p = vector3_type(2.0, 0.0, 0.0 ) ;\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( collision );\n\n  r = vector3_type(1.0, 0.0, 0.0 ) ;\n  p = vector3_type(0.0, 0.0, 0.0 ) ;\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( collision );\n\n  r = vector3_type(-1.0, 0.0, 0.0 ) ;\n  p = vector3_type(0.0, 0.0, 0.0 ) ;\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( collision );\n\n  // y-faces are separating planes\n\n  r = vector3_type(0.0, 1.0, 0.0 ) ;\n  p = vector3_type(0.0, 2.0, 0.0 ) ;\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( !collision );\n\n  r = vector3_type(0.0, -1.0, 0.0 ) ;\n  p = vector3_type(0.0,  2.0, 0.0 ) ;\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( collision );\n\n  r = vector3_type(0.0, 1.0, 0.0 ) ;\n  p = vector3_type(0.0, 0.0, 0.0 ) ;\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( collision );\n\n  r = vector3_type(0.0, -1.0, 0.0 ) ;\n  p = vector3_type(0.0, 0.0, 0.0 ) ;\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( collision );\n\n  // z-faces are separating planes\n\n  r = vector3_type(0.0, 0.0, 1.0 ) ;\n  p = vector3_type(0.0, 0.0, 2.0 ) ;\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( !collision );\n\n  r = vector3_type(0.0, 0.0, -1.0 ) ;\n  p = vector3_type(0.0, 0.0,  2.0 ) ;\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( collision );\n\n  r = vector3_type(0.0, 0.0, 1.0) ;\n  p = vector3_type(0.0, 0.0, 0.0 ) ;\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( collision );\n\n  r = vector3_type(0.0, 0.0, -1.0) ;\n  p = vector3_type(0.0, 0.0, 0.0 ) ;\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( collision );\n\n\n  // cross-produces are separating planes\n  r = vector3_type(0.01, 0.01,   1.0) ;\n  p = vector3_type(-2.0, -2.0, 0.0 ) ;\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( !collision );\n\n  r = vector3_type(0.01, 1.0, 0.01);\n  p = vector3_type(-2.0, 0.0, -2.0);\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( !collision );\n\n  r = vector3_type(1.0, 0.01, 0.01);\n  p = vector3_type(0.0, -2.0, -2.0);\n  collision = OpenTissue::collision::ray_aabb(p,r,min_coord,max_coord);\n  BOOST_CHECK( !collision );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "6de0caea27b6b740efd4903d36a8235515d74102", "size": 3854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/collision/ray_aabb/src/unit_ray_aabb.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/collision/ray_aabb/src/unit_ray_aabb.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/collision/ray_aabb/src/unit_ray_aabb.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": 32.3865546218, "max_line_length": 78, "alphanum_fraction": 0.684743124, "num_tokens": 1340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931455, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5324600373025087}}
{"text": "#pragma once\n\n#include <deal.II/base/function.h>\n#include <deal.II/base/tensor_function.h>\n\n#include \"aux/tensor_helpers.hpp\"\n#include \"var_form/polar_var_form_rhs.hpp\"\n\n\nnamespace boltzmann {\n\ntemplate <int dimX, typename APP, typename SOURCE = typename APP::source_function_t>\nclass RhsVarForm : public PolarXVarFormRhs<dimX, SOURCE::rank>\n{\n private:\n  typedef PolarXVarFormRhs<dimX, SOURCE::rank> base_class;\n  typedef SOURCE source_xv_t;\n  typedef typename source_xv_t::SX_t source_function_t;\n\n public:\n  // is S(x,v) = s(x) . s(v) ?s(x),s(v) scalar or vector valued?\n  static const int rank = source_function_t::rank;\n\n public:\n  template <typename FE>\n  RhsVarForm(const FE& fe)\n      : base_class(fe)\n  { /* empty */\n  }\n\n  template <typename cell_iterator>\n  void calc(const cell_iterator& cell);\n\n private:\n  //@{\n  /// functions\n  source_function_t source_;\n  //@}\n  //@{\n  /// working storage\n  std::vector<typename base_class::Sx_t> source_values_;\n  //@}\n};\n\n/**\n * @brief Weighted least squares var form in X-domain\n \\f[\n \\int_D s^x(x) \\otimes \\nabla \\alpha(x) \\epsilon(x) \\mathrm{d} x\n + \\int_D s^x \\times \\alpha(x) \\sigma(x) \\epsilon(x) \\mathrm{d} x\n \\f]\n Note that \\f$ s^x (x) \\f$ can be \\f$ \\mathbb{R}^2 \\rightarrow \\mathbb{R} \\f$\n or \\f$ \\mathbb{R}^2 \\rightarrow \\mathbb{R}^2 \\f$\n *\n *\n * @param cell\n *\n * @return\n */\ntemplate <int dimX, typename APP, typename SOURCE>\ntemplate <typename cell_iterator>\nvoid\nRhsVarForm<dimX, APP, SOURCE>::calc(const cell_iterator& cell)\n{\n  // update fevalues\n  this->init_cell(cell);\n  // clear\n  base_class::clear_storage();\n  const int nqpoints = this->quad.size();\n  const int dofs_per_cell = this->fe_values.dofs_per_cell;\n  // resize storage\n  source_.value_list(this->fe_values.get_quadrature_points(), source_values_);\n\n  for (int ix = 0; ix < dofs_per_cell; ++ix) {\n    for (int q = 0; q < nqpoints; ++q) {\n      auto shape = this->fe_values.shape_value(ix, q);\n      auto grad = this->fe_values.shape_grad(ix, q);\n      double weight = this->fe_values.JxW(q);\n      /// mass part\n      /// stabilization part i.e multiplied with grad\n      typename base_class::Tx_t Tx_tmp;\n      outer_product(Tx_tmp, source_values_[q], grad);\n\n      this->Tx_vec[ix] += Tx_tmp * weight;\n    }\n  }\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "737a2775f7caae4b3e156c732a8fad03f75b469f", "size": 2281, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/var_form/least_squares/least_squares_rhs.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/var_form/least_squares/least_squares_rhs.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/var_form/least_squares/least_squares_rhs.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": 25.6292134831, "max_line_length": 84, "alphanum_fraction": 0.6738272687, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.532460036958951}}
{"text": "#ifndef COMPILER_QUBIT_TAPERING_HPP_\n#define COMPILER_QUBIT_TAPERING_HPP_\n\n#include \"IRTransformation.hpp\"\n#include \"PauliOperator.hpp\"\n#include \"OptionsProvider.hpp\"\n#include <Eigen/Dense>\n\nusing namespace xacc::quantum;\n\nnamespace xacc {\nnamespace vqe {\n\n/**\n * QubitTapering is an IRTransformation that implements\n * the Hamiltonian reduction scheme for discrete\n * Z2 symmetries as described in https://arxiv.org/pdf/1701.08213.pdf.\n */\nclass QubitTapering : public IRTransformation, public OptionsProvider {\n\npublic:\n  QubitTapering() {}\n\n  virtual std::shared_ptr<IR> transform(std::shared_ptr<IR> ir);\n\n  virtual const std::string name() const { return \"qubit-tapering\"; }\n  virtual const std::string description() const {\n    return \"Reduce number of qubits required by exploiting Z2 symmetries.\";\n  }\n\n  virtual OptionPairs getOptions() {\n    OptionPairs desc {{\"phase-sector\",\n                        \"Provide the +-1 vector.\"},{\n        \"qubit-tapering-show\",\n        \"Create and display reduced hamiltonian, but then exit.\"}};\n    return desc;\n  }\n\nprivate:\n  Eigen::MatrixXi computeTableaux(PauliOperator &H, const int nQubits);\n  std::vector<std::vector<int>> generateCombinations(\n      const int nQubits, std::function<void(std::vector<int> &)> &&f =\n                             [](std::vector<int> &tmp) { return; });\n  int binaryVectorInnerProduct(std::vector<int> &bv1, std::vector<int> &bv2);\n  const double computeGroundStateEnergy(PauliOperator &op, const int n);\n\n  Eigen::MatrixXi gauss(Eigen::MatrixXi& A, std::vector<int> &pivotCols) {\n     int n = A.rows();\n     int m = A.cols();\n\n     int sc = 0;\n\n     for (int i = 0; i < m; i++) {\n         bool found_row = false;\n         int ip = i-sc;\n         for (int k = ip; k < n; k++) {\n             if (A(k,i) == 1) {\n                 found_row = true;\n\n                 if (k > ip) {\n                     for (int j = i; j < m; j++) {\n                         auto tmp = A(k,j);\n                         A(k,j) = A(ip,j);\n                         A(ip,j) = tmp;\n                     }\n                 }\n\n                 for (int l = ip+1; l < n; l++) {\n                     if (A(l,i) != 0) {\n                         for (int j = ip; j < m; j++) {\n                             A(l,j) = (A(l,j)+A(ip,j)) %2;\n                         }\n                     }\n                 }\n                 break;\n             }\n         }\n         if (!found_row) sc += 1;\n     }\n\n    unsigned row2 = 0;\n    for (unsigned col = 0; col < A.cols() && row2 < A.rows(); col++) {\n      if (std::fabs(A(row2, col)) < 1e-12)\n        continue;\n\n      pivotCols.push_back(col);\n      row2++;\n    }\n\n     return A;\n\n  }\n};\n} // namespace vqe\n} // namespace xacc\n\n#endif\n", "meta": {"hexsha": "4a71b20942bf2dd9aa5feccdead96e019159ea7d", "size": 2725, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "compiler/optimizers/QubitTapering.hpp", "max_stars_repo_name": "zpparks314/xacc-vqe", "max_stars_repo_head_hexsha": "37aaadb12d856324532c42ca9f7e56147edbd2e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:05:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T05:24:51.000Z", "max_issues_repo_path": "compiler/optimizers/QubitTapering.hpp", "max_issues_repo_name": "zpparks314/xacc-vqe", "max_issues_repo_head_hexsha": "37aaadb12d856324532c42ca9f7e56147edbd2e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2017-08-08T16:03:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T12:18:27.000Z", "max_forks_repo_path": "compiler/optimizers/QubitTapering.hpp", "max_forks_repo_name": "zpparks314/xacc-vqe", "max_forks_repo_head_hexsha": "37aaadb12d856324532c42ca9f7e56147edbd2e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2018-06-25T20:20:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-03T18:31:44.000Z", "avg_line_length": 27.806122449, "max_line_length": 77, "alphanum_fraction": 0.5262385321, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5324560151991872}}
{"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#include <iostream>\nusing std::cout;  using std::endl;\n\n//[policy_ref_snip2\n\n#include <boost/math/distributions/normal.hpp>\nusing boost::math::normal_distribution;\n\nusing namespace boost::math::policies;\n\n// Define a specific policy:\ntypedef policy<\n      overflow_error<ignore_error>\n      > my_policy;\n\n// Define the distribution, using my_policy:\ntypedef normal_distribution<double, my_policy> my_norm;\n\n// Construct a my_norm distribution, using default mean and standard deviation,\n// and get a 0.05 or 5% quantile:\ndouble q = quantile(my_norm(), 0.05); // = -1.64485\n\n//] //[/policy_ref_snip2]\n\nint main()\n{\n  my_norm n; // Construct a my_norm distribution,\n  // using default mean zero and standard deviation unity.\n  double q = quantile(n, 0.05); // and get a quantile.\n  cout << \"quantile(my_norm(), 0.05) = \" << q << endl;\n}\n\n/*\n\nOutput:\n\n  quantile(my_norm(), 0.05) = -1.64485\n*/\n", "meta": {"hexsha": "dc6d02c0c578ad5f776abc1d4f91e89a07f50eff", "size": 1285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/policy_ref_snip2.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_snip2.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_snip2.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": 26.7708333333, "max_line_length": 79, "alphanum_fraction": 0.7128404669, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5324560049089765}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\n#include <memory>\n#include <utility>\n#include <vector>\n\nnamespace eq {\n    const int INIT_TIME       = 0;\n    const double MAX_MIN_DIFF = 10e-10;\n    const double DEFAULT_STEP = 0.1;\n\n    const double TASK_DIFF_STEP = 0.001;\n    const double MAX_TIME_RUNGE = 0.2;\n    const double MAX_TIME_DP    = 10;\n\n    struct task_answer {\n        double answer_max_diff_runge{-1};\n        double answer_step_runge{-1};\n        double answer_min_step_dp{-1};\n        int answer_total_steps_dp{-1};\n    };\n\n    class EquationSolver;\n\n    class Solver {\n    public:\n        virtual ~Solver() = default;\n        explicit Solver(EquationSolver &eq_solver, double step) : _solver(eq_solver), _step(step) {}\n\n        Solver() = delete;\n        Solver(const Solver&) = delete;\n        void operator=(const Solver&) = delete;\n\n        virtual void Calculate() = 0;\n        virtual void Solver_set_matrix() = 0;\n\n        Eigen::MatrixXd Generate_mat();\n\n        double Get_step() const { return _step; }\n        void Set_step(double step) {_step = step; }\n\n    protected:\n        EquationSolver &_solver;\n        double _step;\n    };\n\n    class RungeSolver : public Solver {\n    public:\n        explicit RungeSolver(EquationSolver &eq_solver, double step = DEFAULT_STEP) : Solver(eq_solver, step) {}\n\n        RungeSolver() = delete;\n        RungeSolver(const RungeSolver&) = delete;\n        void operator=(const RungeSolver&) = delete;\n\n        void Calculate() override;\n        void Solver_set_matrix() override;\n\n    private:\n        void calc_step();\n    };\n\n    class DPSolver : public Solver {\n    public:\n        explicit DPSolver(EquationSolver &eq_solver, double max_diff = MAX_MIN_DIFF, double min_diff = MAX_MIN_DIFF,\n                          double step = DEFAULT_STEP) :\n                          Solver(eq_solver, step), _max_diff(max_diff), _min_diff(min_diff) {}\n\n        DPSolver() = delete;\n        DPSolver(const DPSolver&) = delete;\n        void operator=(const DPSolver&) = delete;\n\n        void Calculate() override;\n        void Solver_set_matrix() override;\n\n    private:\n        void calc_step();\n\n    private:\n        double _max_diff;\n        double _min_diff;\n    };\n\n    class EquationSolver {\n    public:\n        explicit EquationSolver(std::function<Eigen::VectorXd(double, const Eigen::VectorXd &)> recalc_function,\n                        Eigen::VectorXd start_vals, double start_time, std::function<Eigen::VectorXd(double)> result_function) :\n                        _recalc_function(std::move(recalc_function)), _values(std::move(start_vals)), _time(start_time),\n                        _result_function(std::move(result_function)) {}\n\n        EquationSolver() = delete;\n        EquationSolver(const EquationSolver&) = delete;\n        void operator=(const EquationSolver&) = delete;\n\n        void Set_solver(std::unique_ptr<Solver>&& solver);\n        void Reload_values(const Eigen::VectorXd &init_vals, double init_time);\n\n        void Solve();\n        task_answer Get_answer() const;\n\n        double Get_time() const { return _time; }\n        Eigen::VectorXd& Get_values() { return _values; }\n\n    public:\n        friend Solver;\n        friend RungeSolver;\n        friend DPSolver;\n\n    private:\n        std::unique_ptr<Solver> _solver;\n\n        std::function<Eigen::VectorXd(double, const Eigen::VectorXd &)> _recalc_function;\n        Eigen::VectorXd _values;\n        Eigen::VectorXd _steps;\n        std::function<Eigen::VectorXd(double)> _result_function;\n\n        Eigen::MatrixXd _a;\n        std::vector<Eigen::MatrixXd> _b;\n\n        double _time{0};\n\n    private:\n        double _answer_max_diff_runge{-1};\n        double _answer_step_runge{-1};\n        double _answer_min_step_dp{-1};\n        int _answer_total_steps_dp{-1};\n    };\n\n    task_answer Calculate(std::function<Eigen::VectorXd(double, const Eigen::VectorXd &)> src_function,\n                   std::function<Eigen::VectorXd(double)> result_function, const Eigen::VectorXd& init_val);\n}\n", "meta": {"hexsha": "a6e3e61a754c013ccaa5bebbcefe423328c6b366", "size": 4007, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/task_3/lib/Solver.hpp", "max_stars_repo_name": "TimasTT/vision_system_hw", "max_stars_repo_head_hexsha": "04ec728954943bf8dc20ceaa64af103f7ca315c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/task_3/lib/Solver.hpp", "max_issues_repo_name": "TimasTT/vision_system_hw", "max_issues_repo_head_hexsha": "04ec728954943bf8dc20ceaa64af103f7ca315c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/task_3/lib/Solver.hpp", "max_forks_repo_name": "TimasTT/vision_system_hw", "max_forks_repo_head_hexsha": "04ec728954943bf8dc20ceaa64af103f7ca315c8", "max_forks_repo_licenses": ["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.1278195489, "max_line_length": 128, "alphanum_fraction": 0.6271524832, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311757235431, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5324560017383944}}
{"text": "\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <functional>\n#include <limits>\n#include <ctime>\n#include <cmath>\n#include <cassert>\n\n#include <boost/timer.hpp>\n#include <boost/random.hpp>\n\n#include \"StochasticFunctionMinimization.h\"\n\nnamespace Grante {\n\ndouble StochasticFunctionMinimization::StochasticSubgradientMethodMinimize(\n\tStochasticFunctionMinimizationProblem& prob, std::vector<double>& x_opt,\n\tdouble conv_tol, unsigned int max_epochs, bool verbose) {\n\tunsigned int dim = prob.Dimensions();\n\tstd::vector<double> grad(dim, 0.0);\n\n\t// Initialize x\n\tstd::vector<double> x(dim);\n\tprob.ProvideStartingPoint(x);\n\n\t// Random instance generator\n\tsize_t N = prob.NumberOfElements();\n\tassert(N > 0);\n\tboost::mt19937 rgen(static_cast<const boost::uint32_t>(std::time(0))+1);\n\tboost::uniform_int<unsigned int> rdestd(0, static_cast<unsigned int>(N-1));\n\tboost::variate_generator<boost::mt19937,\n\t\tboost::uniform_int<unsigned int> > rand_n(rgen, rdestd);\n\n\t// Optimize a given number of epochs\n\tboost::timer total_timer;\n\tstd::vector<double> avg_grad(dim, 0.0);\n\tdouble lambda = 1.0;\t// (should be lambda=1/C)\n\tdouble avg_obj = 0.0;\n\tfor (unsigned int epoch = 0; max_epochs == 0 || epoch < max_epochs;\n\t\t++epoch) {\n\t\tavg_obj = 0.0;\n\t\tstd::fill(avg_grad.begin(), avg_grad.end(), 0.0);\n\n\t\t// Choose epoch-wide step size\n\t\tdouble alpha = 1.0 / (static_cast<double>(epoch + 1) * lambda);\n\n\t\t// Optimize by sampling instances\n\t\tfor (size_t n = 0; n < N; ++n) {\n\t\t\tunsigned int id = rand_n();\n\t\t\t// Update average objective and averaged gradient of this epoch\n\t\t\tavg_obj += prob.Eval(id, x, grad);\n\t\t\tstd::transform(grad.begin(), grad.end(), avg_grad.begin(),\n\t\t\t\tavg_grad.begin(), std::plus<double>());\n\n\t\t\t// Perform incremental subgradient update\n\t\t\tfor (unsigned int d = 0; d < dim; ++d)\n\t\t\t\tx[d] -= alpha * grad[d];\n\t\t}\n\t\t// Compute mean gradient and estimated objective\n\t\tdouble avg_grad_norm = 0.0;\n\t\tfor (unsigned int d = 0; d < dim; ++d)\n\t\t\tavg_grad_norm += avg_grad[d]*avg_grad[d];\n\t\tavg_grad_norm = std::sqrt(avg_grad_norm);\n\n\t\t// Output statistics\n\t\tif (verbose && (epoch % 20 == 0)) {\n\t\t\tstd::cout << std::endl;\n\t\t\tstd::cout << \"  iter     time        avg_obj  |avg_grad|\" << std::endl;\n\t\t}\n\t\tif (verbose) {\n\t\t\tstd::ios_base::fmtflags original_format = std::cout.flags();\n\t\t\tstd::streamsize original_prec = std::cout.precision();\n\n\t\t\t// Iteration\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setw(6) << epoch << \"  \";\n\t\t\t// Total runtime\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::resetiosflags(std::ios::scientific)\n\t\t\t\t<< std::setiosflags(std::ios::fixed)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setprecision(1)\n\t\t\t\t<< std::setw(6) << total_timer.elapsed() << \"s  \";\n\t\t\tstd::cout << std::resetiosflags(std::ios::fixed);\n\n\t\t\t// Objective function\n\t\t\tstd::cout << std::setiosflags(std::ios::scientific)\n\t\t\t\t<< std::setprecision(5)\n\t\t\t\t<< std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::showpos)\n\t\t\t\t<< std::setw(7) << avg_obj << \"   \";\n\t\t\t// Gradient norm\n\t\t\tstd::cout << std::setiosflags(std::ios::scientific)\n\t\t\t\t<< std::setprecision(2)\n\t\t\t\t<< std::resetiosflags(std::ios::showpos)\n\t\t\t\t<< std::setiosflags(std::ios::left) << avg_grad_norm;\n\t\t\tstd::cout << std::endl;\n\n\t\t\tstd::cout.precision(original_prec);\n\t\t\tstd::cout.flags(original_format);\n\t\t}\n\n\t\t// Convergence check\n\t\tif (avg_grad_norm < conv_tol)\n\t\t\tbreak;\n\t}\n\n\tx_opt = x;\n\treturn (avg_obj);\t// This is not exact, but stochastic anyway\n}\n\n}\n\n", "meta": {"hexsha": "9447d1fe7da5b48fbc777972e24c3ef4eb2042a2", "size": 3547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grante/StochasticFunctionMinimization.cpp", "max_stars_repo_name": "pantonante/grante-bazel", "max_stars_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_stars_repo_licenses": ["DOC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grante/StochasticFunctionMinimization.cpp", "max_issues_repo_name": "pantonante/grante-bazel", "max_issues_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_issues_repo_licenses": ["DOC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grante/StochasticFunctionMinimization.cpp", "max_forks_repo_name": "pantonante/grante-bazel", "max_forks_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_forks_repo_licenses": ["DOC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3162393162, "max_line_length": 76, "alphanum_fraction": 0.659712433, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5324559997638709}}
{"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/bessel.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n#include <eve/detail/diff_div.hpp>\n\n//==================================================================================================\n//== Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of sph_bessel_yn\"\n              , eve::test::simd::ieee_reals\n              )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  using i_t = eve::as_integer_t<v_t>;\n  using I_t = eve::wide<i_t, eve::cardinal_t<T>>;\n  TTS_EXPR_IS( eve::sph_bessel_yn(T(), T())  ,  T);\n  TTS_EXPR_IS( eve::sph_bessel_yn(v_t(),v_t()), v_t);\n  TTS_EXPR_IS( eve::sph_bessel_yn(i_t(),T()),   T);\n  TTS_EXPR_IS( eve::sph_bessel_yn(I_t(),T()),   T);\n  TTS_EXPR_IS( eve::sph_bessel_yn(i_t(),v_t()), v_t);\n//  TTS_EXPR_IS( eve::sph_bessel_yn(I_t(),v_t()), T);\n };\n\n//==================================================================================================\n//== integral orders\n//==================================================================================================\nEVE_TEST( \"Check behavior of sph_bessel_yn on wide with integral order\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::ramp(0), eve::test::randoms(0.0, 20000.0))\n        )\n  <typename T>(T n, T a0)\n{\n  using v_t = eve::element_type_t<T>;\n  auto eve__sph_bessel_yn =  [](auto n, auto x) { return eve::sph_bessel_yn(n, x); };\n  auto std__sph_bessel_yn =  [](auto n, auto x)->v_t { return boost::math::sph_neumann(unsigned(n), double(x)); };\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__sph_bessel_yn(2, eve::inf(eve::as<v_t>())), v_t(0), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_yn(3, eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n  }\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(3, v_t(1500)), std__sph_bessel_yn(3u, v_t(1500)), 2.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(2, v_t(500)), std__sph_bessel_yn(2u, v_t(500)), 2.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(2, v_t(10)), std__sph_bessel_yn(2u, v_t(10))  , 5.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(3, v_t(5)),  std__sph_bessel_yn(3u, v_t(5))   , 40.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(2, v_t(0.1)), std__sph_bessel_yn(2u, v_t(0.1))  , 2.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(3, v_t(0.2)),  std__sph_bessel_yn(3u, v_t(0.2))   , 2.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(10, v_t(8)), std__sph_bessel_yn(10u, v_t(8))  , 2.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(10, v_t(8)),  std__sph_bessel_yn(10u, v_t(8))   , 2.0);\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__sph_bessel_yn(2, eve::inf(eve::as<T>())), T(0), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_yn(3, eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(3, T(1500)),  T(std__sph_bessel_yn(3u, v_t(1500))),  2.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(2, T(500)),   T(std__sph_bessel_yn(2u, v_t(500))),   2.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(2, T(10)),    T(std__sph_bessel_yn(2u, v_t(10)))   , 5.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(3, T(5)),     T(std__sph_bessel_yn(3u, v_t(5)))    , 40.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(2, T(0.1)),   T(std__sph_bessel_yn(2u, v_t(0.1)))  , 2.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(3, T(0.2)),   T(std__sph_bessel_yn(3u, v_t(0.2)))  , 2.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(10, T(8)),   T(std__sph_bessel_yn(10u, v_t(8)))   , 2.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(10, T(8)),   T(std__sph_bessel_yn(10u, v_t(8)))   , 2.0);\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__sph_bessel_yn(T(2), eve::inf(eve::as<T>())), T(0), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_yn(T(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(T(3), T(1500)),  T(std__sph_bessel_yn(3u, v_t(1500))),  2.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(T(2), T(500)),   T(std__sph_bessel_yn(2u, v_t(500))),   2.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(T(2), T(10)),    T(std__sph_bessel_yn(2u, v_t(10)))   , 5.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(T(3), T(5)),     T(std__sph_bessel_yn(3u, v_t(5)))    , 40.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(T(2), T(0.1)),   T(std__sph_bessel_yn(2u, v_t(0.1)))  , 2.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(T(3), T(0.2)),   T(std__sph_bessel_yn(3u, v_t(0.2)))  , 2.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(T(10), T(8)),   T(std__sph_bessel_yn(10u, v_t(8)))   , 2.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(T(10), T(8)),   T(std__sph_bessel_yn(10u, v_t(8)))   , 2.0);\n\n  using i_t = eve::as_integer_t<v_t>;\n  using I_t = eve::wide<i_t, eve::cardinal_t<T>>;\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__sph_bessel_yn(I_t(2), eve::inf(eve::as<T>())), T(0), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_yn(I_t(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(I_t(3), T(1500)),  T(std__sph_bessel_yn(3u, v_t(1500))),  2.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(I_t(2), T(500)),   T(std__sph_bessel_yn(2u, v_t(500))),   2.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(I_t(2), T(10)),    T(std__sph_bessel_yn(2u, v_t(10)))   , 5.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(I_t(3), T(5)),     T(std__sph_bessel_yn(3u, v_t(5)))    , 40.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(I_t(2), T(0.1)),   T(std__sph_bessel_yn(2u, v_t(0.1)))  , 2.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(I_t(3), T(0.2)),   T(std__sph_bessel_yn(3u, v_t(0.2)))  , 2.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(I_t(10), T(8)),   T(std__sph_bessel_yn(10u, v_t(8)))   , 2.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_yn(I_t(10), T(8)),   T(std__sph_bessel_yn(10u, v_t(8)))   , 2.0);\n\n  TTS_RELATIVE_EQUAL(eve__sph_bessel_yn(n, a0),   map(std__sph_bessel_yn, n, a0)   , 0.0025);\n};\n\nEVE_TEST( \"Check behavior of diff(sph_bessel_j1) on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(1.0, 10.0))\n        )\n  <typename T>(T a0 )\n{\n  auto eve__diff_bessel_yn =  [](auto n, auto x) { return eve::diff(eve::sph_bessel_yn)(n, x); };\n  auto y3 = [](auto x){ return eve::sph_bessel_yn(3, x); };\n  auto df = [y3](auto x){return eve::detail::centered_diffdiv(y3, x); };\n\n  TTS_RELATIVE_EQUAL(eve__diff_bessel_yn(3, a0),   df(a0), 5.0e-2);\n  TTS_RELATIVE_EQUAL(eve__diff_bessel_yn(1, a0),   eve::diff(eve::sph_bessel_y1)(a0), 5.0e-2);\n};\n", "meta": {"hexsha": "222de83ab40665807890b3bf9ded9c0a25f486b6", "size": 6787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/bessel/sph_bessel_yn.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/bessel/sph_bessel_yn.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/bessel/sph_bessel_yn.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": 49.9044117647, "max_line_length": 114, "alphanum_fraction": 0.6036540445, "num_tokens": 2756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5324559930334749}}
{"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_one_geometry\n//` Checks if a geometry has at least one touching point (self-tangency)\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 geometry has self-tangency.\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly1;\n    bg::read_wkt(\"POLYGON((0 0,0 3,2 3,2 2,1 2,1 1,2 1,2 2,3 2,3 0,0 0))\", poly1);\n    bool check_touches = bg::touches(poly1);\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> > poly2;\n    bg::read_wkt(\"POLYGON((0 0,0 4,4 4,4 0,2 3,0 0))\", poly2);\n    check_touches = bg::touches(poly2);\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_one_geometry_output\n/*`\nOutput:\n[pre\nTouches: Yes\n\n[$img/algorithms/touches_one_geometry.png]\n\nTouches: No\n]\n*/\n//]\n", "meta": {"hexsha": "2604f9bd7bb6ffed28cd662a59ba9050d072e6ff", "size": 1501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/algorithms/touches_one_geometry.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_one_geometry.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_one_geometry.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.0166666667, "max_line_length": 82, "alphanum_fraction": 0.6502331779, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.5324026737231781}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/include/functions/acoth.hpp>\n\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <complex>\n#include <nt2/sdk/complex/complex.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#include <nt2/include/constants/mzero.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/pio_2.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/i.hpp>\n\n#include <nt2/include/functions/rec.hpp>\n#include <nt2/include/functions/atanh.hpp>\n#include <boost/math/complex/atanh.hpp>\n\nNT2_TEST_CASE_TPL ( acoth_real, NT2_REAL_TYPES)\n{\n  using nt2::acoth;\n  using nt2::tag::acoth_;\n  typedef typename std::complex<T> cT;\n  typedef typename nt2::meta::call<acoth_(cT)>::type r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, cT);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_ULP_EQUAL(nt2::acoth(cT(nt2::One<T>(), nt2::Zero<T>())),  cT(nt2::Inf<T>(), nt2::Zero<T>()), 0.75);\n#endif\n  NT2_TEST_ULP_EQUAL(nt2::acoth(cT(nt2::Zero<T>(), nt2::Zero<T>())),  cT(nt2::Zero<T>(), nt2::Pio_2<T>()), 0.75);\n  NT2_TEST_ULP_EQUAL(nt2::acoth(cT(nt2::Mzero<T>(), nt2::Zero<T>())), cT(nt2::Zero<T>(), nt2::Pio_2<T>()), 0.75);\n  NT2_TEST_ULP_EQUAL(nt2::acoth(cT(1, 1)),   boost::math::atanh(nt2::rec(cT(1, 1))), 0.75);\n  NT2_TEST_ULP_EQUAL(nt2::acoth(cT(1, 10)),  boost::math::atanh(nt2::rec(cT(1, 10))), 0.75);\n  NT2_TEST_ULP_EQUAL(nt2::acoth(cT(10, 10)), boost::math::atanh(nt2::rec(cT(10, 10))), 1);\n  NT2_TEST_ULP_EQUAL(nt2::acoth(cT(10, 1)),  boost::math::atanh(nt2::rec(cT(10, 1))), 1);\n}\n", "meta": {"hexsha": "c37cb21c53f7236f3aa18f736c5b41de021043d4", "size": 2341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/hyperbolic/unit/scalar/acoth.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/type/complex/hyperbolic/unit/scalar/acoth.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/type/complex/hyperbolic/unit/scalar/acoth.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 43.3518518519, "max_line_length": 113, "alphanum_fraction": 0.6369073046, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5324026717780955}}
{"text": "#include \"fieldtrack/AdaptiveCovarianceEstimator.h\"\n#include \"argus_utils/utils/ParamUtils.h\"\n#include \"argus_utils/utils/MatrixUtils.h\"\n#include <boost/foreach.hpp>\n#include <sstream>\n#include <Eigen/SVD>\n\nusing namespace argus_msgs;\nusing namespace argus;\n\nnamespace argus\n{\nAdaptiveTransCovEstimator::AdaptiveTransCovEstimator() {}\n\nvoid AdaptiveTransCovEstimator::Initialize( ros::NodeHandle& ph )\n{\n\tGetParamRequired( ph, \"max_window_samples\", _maxSamples );\n\n\tdouble dur;\n\tGetParamRequired( ph, \"max_sample_age\", dur );\n\t_maxAge = ros::Duration( dur );\n\n\tunsigned int dim;\n\tGetParamRequired( ph, \"dim\", dim );\n\t_priorCov = MatrixType( dim, dim );\n\tGetParam( ph, \"prior_cov\", _priorCov, 1E-3 * MatrixType::Identity( dim, dim ) );\n\tGetParam( ph, \"prior_age\", _priorAge, 1.0 );\n\tGetParam( ph, \"prior_dt\", _priorDt, 1.0 );\n\n\tGetParam( ph, \"use_diag\", _useDiag, true );\n\tGetParam( ph, \"decay_rate\", _decayRate, 1.0 );\n\t_decayRate = std::log( _decayRate );\n}\n\nunsigned int AdaptiveTransCovEstimator::NumSamples() const\n{\n\treturn _innoProds.size();\n}\n\nMatrixType AdaptiveTransCovEstimator::GetQ( const ros::Time& time )\n{\n\tCheckBuffer( time );\n\n\tdouble wAcc = std::exp( _decayRate * _priorAge );\n\tMatrixType Qacc = _priorCov * wAcc;\n\tfor( unsigned int i = 0; i < _innoProds.size(); ++i )\n\t{\n\t\tdouble t = ( time - _innoProds[i].first ).toSec();\n\t\tdouble w = std::exp( _decayRate * t );\n\t\tQacc += _innoProds[i].second * w;\n\t\twAcc += w;\n\t}\n\n\t// Version using single adjusted state deltas\n\t// MatrixType adaptQ = Qacc / wAcc + _currSpost - _lastFSpostFT;\n\n\t// Version using innovations or pre-adjusted state deltas\n\tMatrixType adaptQ = Qacc / wAcc;\n\n\tdouble timeSpan;\n\tif( _innoProds.size() < 2 )\n\t{\n\t\ttimeSpan = 0;\n\t}\n\telse\n\t{\n\t\ttimeSpan = ( _innoProds.front().first - _innoProds.back().first ).toSec();\n\t}\n\ttimeSpan += _priorDt;\n\tdouble averageDt = timeSpan / ( NumSamples() + 1 );\n\tMatrixType adaptQRate = adaptQ / averageDt;\n\n\t// Check for diagonal\n\tif( _useDiag )\n\t{\n\t\tadaptQRate = Eigen::DiagonalMatrix<double, Eigen::Dynamic>( adaptQRate.diagonal() );\n\t}\n\treturn adaptQRate;\n}\n\nvoid AdaptiveTransCovEstimator::Update( const ros::Time& time,\n                                                    const PredictInfo& predict,\n                                                    const UpdateInfo& update )\n{\n\t// Initialization catch\n\tif( _lastFSpostFT.size() == 0 )\n\t{\n\t\tunsigned int dim = update.state_delta.size();\n\t\t_currSpost = MatrixType::Zero( dim, dim );\n\t}\n\n\t// Version using state deltas\n\t// MatrixType op = update.state_delta * update.state_delta.transpose();\n\n\t// Version incorporating estimate covariance adjustment\n\t// MatrixType op = update.state_delta * update.state_delta.transpose() + _currSpost - _lastFSpostFT;\n\n\t// Version using innovations\n\tVectorType Kv = update.kalman_gain * update.prior_obs_error;\n\tMatrixType op = Kv * Kv.transpose();\n\n\t_innoProds.emplace_front( time, op );\n\t_lastFSpostFT = predict.trans_jacobian * _currSpost *\n\t                predict.trans_jacobian.transpose();\n\t_currSpost = update.post_state_cov;\n}\n\nvoid AdaptiveTransCovEstimator::Reset()\n{\n\t_lastFSpostFT = MatrixType();\n\t_currSpost = MatrixType();\n\t_innoProds.clear();\n}\n\nvoid AdaptiveTransCovEstimator::CheckBuffer( const ros::Time& now )\n{\n\twhile( !_innoProds.empty() &&\n\t       ( NumSamples() > _maxSamples ||\n\t         ( now - _innoProds.back().first ) > _maxAge ) )\n\t{\n\t\t_innoProds.pop_back();\n\t}\n}\n\nAdaptiveObsCovEstimator::AdaptiveObsCovEstimator() {}\n\nvoid AdaptiveObsCovEstimator::Initialize( unsigned int dim,\n                                                         ros::NodeHandle& ph )\n{\n\tGetParamRequired( ph, \"max_window_samples\", _maxSamples );\n\tGetParam( ph, \"min_window_samples\", _minSamples, (unsigned int) 0 );\n\n\tdouble dur;\n\tGetParamRequired( ph, \"max_sample_age\", dur );\n\t_maxAge = ros::Duration( dur );\n\n\t_dim = dim;\n\t_priorCov = MatrixType( _dim, _dim );\n\tGetParam( ph, \"prior_cov\", _priorCov, 1E-3 * MatrixType::Identity( _dim, _dim ) );\n\tGetParam( ph, \"prior_age\", _priorAge, 1.0 );\n\tGetParam( ph, \"use_diag\", _useDiag, true );\n\tGetParam( ph, \"decay_rate\", _decayRate, 1.0 );\n\t_decayRate = std::log( _decayRate );\n}\n\nunsigned int AdaptiveObsCovEstimator::NumSamples() const\n{\n\treturn _innoProds.size();\n}\n\nMatrixType AdaptiveObsCovEstimator::GetR( const ros::Time& time )\n{\n\tCheckBuffer( time );\n\n\tMatrixType adaptR;\n\tif( _innoProds.size() >= _minSamples )\n\t{\n\t\tdouble priorW = std::exp( _decayRate * _priorAge );\n\t\tdouble wAcc = priorW;\n\t\tMatrixType Racc = _priorCov * priorW;\n\t\tfor( unsigned int i = 0; i < _innoProds.size(); ++i )\n\t\t{\n\t\t\tconst InnoStamped& data = _innoProds[i];\n\t\t\tconst ros::Time& stamp = data.first;\n\t\t\tconst MatrixType& Rhat = data.second;\n\n\t\t\tdouble dt = ( time - stamp ).toSec();\n\t\t\tdouble w = std::exp( _decayRate * dt );\n\t\t\tRacc += Rhat * w;\n\t\t\twAcc += w;\n\t\t}\n\t\tadaptR = Racc / wAcc;\n\t}\n\telse\n\t{\n\t\tadaptR = _priorCov;\n\t}\n\n\t// Check for diagonal\n\tif( _useDiag )\n\t{\n\t\tadaptR = Eigen::DiagonalMatrix<double, Eigen::Dynamic>( adaptR.diagonal() );\n\t}\n\n\t//ROS_INFO_STREAM( \"R: \" << adaptR.diagonal().transpose() );\n\n\treturn adaptR;\n}\n\nconst MatrixType& AdaptiveObsCovEstimator::GetPriorCov() const\n{\n\treturn _priorCov;\n}\n\n\n// MatrixType AdaptiveObsCovEstimator::GetR( const ros::Time& time,\n//                                                          const UpdateInfo& preview )\n// {\n//  CheckBuffer( time );\n\n//  double wAcc = std::exp( _decayRate * _priorAge );\n//  MatrixType Racc = _priorCov * wAcc;\n//  for( unsigned int i = 0; i < _innoProds.size(); ++i )\n//  {\n//      const InnoStamped& data = _innoProds[i];\n//      const ros::Time& stamp = data.first;\n//      const MatrixType& Rhat = data.second;\n\n//      double dt = ( time - stamp ).toSec();\n//      double w = std::exp( _decayRate * dt );\n//      Racc += Rhat * w;\n//      wAcc += w;\n//  }\n\n//  // Add current preview in\n//  // Update is R = Cv- + H * P- * H^T\n//  MatrixType HPHT = update.obs_jacobian * update.pre_state_cov *\n//                    update.obs_jacobian.transpose();\n//  MatrixType op = update.pre_obs_error * update.pre_obs_error.transpose();\n//  wAcc += 1.0;\n//  Racc += op - HPHT;\n\n//  MatrixType adaptR = Racc / wAcc;\n\n//  // Check for diagonal\n//  if( _useDiag )\n//  {\n//      adaptR = Eigen::DiagonalMatrix<double, Eigen::Dynamic>( adaptR.diagonal() );\n//  }\n//  return adaptR;\n// }\n\nvoid AdaptiveObsCovEstimator::Update( const UpdateInfo& update )\n{\n\t// Update is R = Cv+ + H * P+ * H^T\n\tMatrixType HPHT = update.obs_jacobian * update.post_state_cov *\n\t                  update.obs_jacobian.transpose();\n\tMatrixType op = update.post_obs_error * update.post_obs_error.transpose();\n        MatrixType Rest = HPHT + op;\n\n        // Update is R = Cv- - H * P- * H^T\n        //MatrixType HPHT = update.obs_jacobian * update.prior_state_cov *\n        //         \t  update.obs_jacobian.transpose();\n        //MatrixType op = update.prior_obs_error * update.prior_obs_error.transpose();\n        //MatrixType Rest = Eigen::DiagonalMatrix<double, Eigen::Dynamic>( ( op - HPHT ).diagonal() );\n        //for( unsigned int i =0; i < Rest.rows(); ++i )\n\t//  {\n\t//    if( Rest(i,i) < 0.0 ) { Rest(i,i) = 0.0; }\n\t//  }\n\t_innoProds.emplace_front( update.time, Rest );\n}\n\nvoid AdaptiveObsCovEstimator::Reset()\n{\n\t_innoProds.clear();\n}\n\nvoid AdaptiveObsCovEstimator::CheckBuffer( const ros::Time& now )\n{\n\twhile( !_innoProds.empty() &&\n\t       ( NumSamples() > _maxSamples ||\n\t         ( now - _innoProds.back().first ) > _maxAge ) )\n\t{\n\t\t_innoProds.pop_back();\n\t}\n}\n}\n", "meta": {"hexsha": "fb47d41e44b127e80c481d43ebea81d8100bfa22", "size": 7482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AdaptiveCovarianceEstimator.cpp", "max_stars_repo_name": "Humhu/fieldtrack", "max_stars_repo_head_hexsha": "78f787e08c14ebbb102efbfb7bf1cffcb81fb099", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-15T09:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T09:32:18.000Z", "max_issues_repo_path": "src/AdaptiveCovarianceEstimator.cpp", "max_issues_repo_name": "Humhu/fieldtrack", "max_issues_repo_head_hexsha": "78f787e08c14ebbb102efbfb7bf1cffcb81fb099", "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": "src/AdaptiveCovarianceEstimator.cpp", "max_forks_repo_name": "Humhu/fieldtrack", "max_forks_repo_head_hexsha": "78f787e08c14ebbb102efbfb7bf1cffcb81fb099", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-24T18:42:35.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-24T18:42:35.000Z", "avg_line_length": 27.9179104478, "max_line_length": 102, "alphanum_fraction": 0.6483560545, "num_tokens": 2182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5324026667415451}}
{"text": "/*\n * Copyright (C) 2021, unclearness\n * All rights reserved.\n */\n\n#include \"ugu/optimizer/optimizer.h\"\n\n#include <Eigen/LU>\n#include <iostream>\n\nnamespace {\n\nusing UpdateFunc = std::function<void(const ugu::OptimizerInput& in,\n                                      ugu::OptimizerOutput& out)>;\n\ndouble LineSearchBacktracking(const ugu::GradVec& update_direc,\n                              const ugu::OptimizerInput& in,\n                              ugu::OptimizerOutput& out) {\n  // BACK_TRACKING\n  double a = in.line_search_max;\n  double r = 0.5;\n  while (true) {\n    // Armijo rule\n    double c1 = 1e-4;\n    auto new_param = out.best_param + a * update_direc;\n    double new_val = in.loss_func(new_param);\n\n    double constraint = out.best + c1 * a * out.best_grad.dot(update_direc);\n\n    if (new_val <= constraint) {\n      return a;\n    }\n\n    a *= r;\n  }\n}\n\ndouble LineSearch(const ugu::GradVec& update_direc,\n                  const ugu::OptimizerInput& in, ugu::OptimizerOutput& out) {\n  if (in.line_search_method == ugu::LineSearchMethod::BACK_TRACKING) {\n    return LineSearchBacktracking(update_direc, in, out);\n  }\n\n  throw std::invalid_argument(\"This type is not implemented\");\n\n  //return 0.0;\n}\n\nvoid LoopBody(const ugu::OptimizerInput& input, ugu::OptimizerOutput& output,\n              UpdateFunc update_func) {\n  output.Clear();\n  output.best_param = input.init_param;\n  output.best = input.loss_func(output.best_param);\n  output.best_grad = input.grad_func(output.best_param);\n\n  output.val_history.push_back(output.best);\n  output.param_history.push_back(output.best_param);\n  output.grad_history.push_back(output.best_grad);\n\n  double prev = output.best;\n  double diff = std::numeric_limits<double>::max();\n  size_t max_size = static_cast<size_t>(input.LBFGS_memoery_num);\n  while (!input.terminate_criteria.isTerminated(output.best_iter, diff)) {\n    prev = output.best;\n\n    update_func(input, output);\n\n    output.best = input.loss_func(output.best_param);\n    output.best_grad = input.grad_func(output.best_param);\n\n    output.val_history.push_back(output.best);\n    output.param_history.push_back(output.best_param);\n    output.grad_history.push_back(output.best_grad);\n    while (max_size < output.val_history.size()) {\n      output.val_history.erase(output.val_history.begin());\n      output.param_history.erase(output.param_history.begin());\n      output.grad_history.erase(output.grad_history.begin());\n    }\n\n    // output.best = input.loss_func(output.best_param);\n    diff = prev - output.best;\n    output.best_iter++;\n    // std::cout << prev << std::endl;\n  }\n}\n\nvoid GradientDescentUdpateFunc(const ugu::OptimizerInput& in,\n                               ugu::OptimizerOutput& out) {\n  // Eval grad\n  auto grad = in.grad_func(out.best_param);\n\n  double lr = in.lr;\n\n  if (in.use_line_search) {\n    lr = LineSearch(-grad, in, out);\n  }\n\n  out.best_param += (lr * -grad);\n}\n\n// http://www.dais.is.tohoku.ac.jp/~shioura/teaching/mp13/mp13-13.pdf\nvoid NewtonUpdateFunc(const ugu::OptimizerInput& in,\n                      ugu::OptimizerOutput& out) {\n  ugu::GradVec grad = in.grad_func(out.best_param);\n  // out.best_grad = grad;\n  ugu::Hessian hessian = in.hessian_func(out.best_param);\n  ugu::OptParams delta = (-hessian.inverse() * grad);\n\n  double lr = in.lr;\n\n  if (in.use_line_search) {\n    lr = LineSearch(delta, in, out);\n  }\n\n  out.best_param += (lr * delta);\n}\n\n// https://en.wikipedia.org/wiki/Limited-memory_BFGS\n// https://abicky.net/2010/06/22/114613/\nvoid LBFGSUpdateFunc(const ugu::OptimizerInput& in, ugu::OptimizerOutput& out) {\n  ugu::GradVec grad = in.grad_func(out.best_param);\n  // out.best_grad = grad;\n  ugu::GradVec q = grad;\n\n  if (out.grad_history.size() < 2) {\n    // Initialize by GradientDescent\n    GradientDescentUdpateFunc(in, out);\n    return;\n  }\n\n  ugu::OptIndex k = static_cast<ugu::OptIndex>(out.grad_history.size() - 1);\n  std::vector<ugu::GradVec> y_list;\n  std::vector<ugu::GradVec> s_list;\n  std::vector<double> rho_list;\n\n  for (ugu::OptIndex i = k; i >= 1; i--) {\n    ugu::GradVec y = out.grad_history[i] - out.grad_history[i - 1];\n    ugu::GradVec s = out.param_history[i] - out.param_history[i - 1];\n    double dot = y.dot(s);\n\n#if 0\n    // Guard\n    if (std::abs(dot) < 1e-10) {\n      if (dot > 0) {\n        dot = 1e-10;\n      } else {\n        dot = -1e-10;\n      }\n    }\n    if (std::abs(dot) < 1e10) {\n      if (dot > 0) {\n        dot = 1e10;\n      } else {\n        dot = -1e10;\n      }\n    }\n#endif\n\n    double rho = 1.0 / dot;\n#if 0\n    if (std::isnan(rho)) {\n        rho = 0;\n    }\n    std::cout << y << std::endl;\n    std::cout << s << std::endl;\n    std::cout << rho << std::endl;\n    std::cout << std::endl;\n\n    if (std::abs(rho) < 1e-10) {\n      if (rho > 0) {\n        rho = 1e-10;\n      } else {\n        rho = -1e-10;\n      }\n    }\n#endif\n    y_list.push_back(y);\n    s_list.push_back(s);\n    rho_list.push_back(rho);\n  }\n\n  std::vector<double> alpha_list;\n\n  for (ugu::OptIndex i = 0; i < k; i++) {\n    double alpha = rho_list[i] * s_list[i].dot(q);\n    q = q - alpha * y_list[i];\n    alpha_list.push_back(alpha);\n  }\n\n  double gamma = s_list[0].dot(y_list[0]) / y_list[0].dot(y_list[0]);\n  Eigen::SparseMatrix<double> I(in.init_param.rows(), in.init_param.rows());\n  I.setIdentity();\n  Eigen::SparseMatrix<double> H = gamma * I;\n\n  // std::cout << H << std::endl;\n\n  ugu::GradVec z = H * q;\n\n  for (ugu::OptIndex i = k - 1; i >= 0; i--) {\n    double beta = rho_list[i] * y_list[i].dot(z);\n    z = z + s_list[i] * (alpha_list[i] - beta);\n  }\n\n  z = -z;\n\n  double lr = in.lr;\n\n  if (in.use_line_search) {\n    lr = LineSearch(z, in, out);\n  }\n\n  out.best_param += (lr * z);\n}\n\n}  // namespace\n\nnamespace ugu {\n\nGradFunc GenNumericalGrad(LossFunc loss_func, double h) {\n  return [loss_func, h](const OptParams& params) {\n    GradVec grad(params.size());\n    const double inv_2h = 1.0 / (2 * h);\n    for (OptIndex i = 0; i < params.size(); i++) {\n      auto params_plus = params;\n      params_plus[i] += h;\n      auto params_minus = params;\n      params_minus[i] -= h;\n      grad[i] = (loss_func(params_plus) - loss_func(params_minus)) * inv_2h;\n    }\n    return grad;\n  };\n}\n\nHessianFunc GenNumericalHessian(LossFunc loss_func, double h) {\n  return [loss_func, h](const OptParams& params) {\n    Hessian hessian(params.rows(), params.rows());\n    const double inv_2h = 1.0 / (2 * h);\n    for (OptIndex i = 0; i < params.size(); i++) {\n      auto params_i_p = params;\n      params_i_p[i] += h;\n      auto params_i_n = params;\n      params_i_n[i] -= h;\n      for (OptIndex j = 0; j < params.size(); j++) {\n        auto params_i_p_j_p = params_i_p;\n        params_i_p_j_p[j] += h;\n        auto params_i_p_j_n = params_i_p;\n        params_i_p_j_n[j] -= h;\n\n        auto grad_ij_p =\n            (loss_func(params_i_p_j_p) - loss_func(params_i_p_j_n)) * inv_2h;\n\n        auto params_i_n_j_p = params_i_n;\n        params_i_n_j_p[j] += h;\n        auto params_i_n_j_n = params_i_n;\n        params_i_n_j_n[j] -= h;\n\n        auto grad_ij_n =\n            (loss_func(params_i_n_j_p) - loss_func(params_i_n_j_n)) * inv_2h;\n\n        hessian(i, j) = (grad_ij_p - grad_ij_n) * inv_2h;\n        // std::cout << grad_ij_p << \" \" << grad_ij_n << \" \" << hessian(i, j)\n        //          << std::endl;\n      }\n    }\n    return hessian;\n  };\n}\n\nvoid GradientDescent(const OptimizerInput& input, OptimizerOutput& output) {\n  LoopBody(input, output, GradientDescentUdpateFunc);\n}\n\nvoid Newton(const OptimizerInput& input, OptimizerOutput& output) {\n  LoopBody(input, output, NewtonUpdateFunc);\n}\n\nvoid QuasiNewton(const OptimizerInput& input, OptimizerOutput& output,\n                 QuasiNewtonMethod method) {\n  if (method == QuasiNewtonMethod::LBFGS) {\n    LoopBody(input, output, LBFGSUpdateFunc);\n  } else {\n    throw std::invalid_argument(\"This method is not supported\");\n  }\n}\n\n}  // namespace ugu\n", "meta": {"hexsha": "08babd67368f670e51ec3aec5ea02c94c4d37d12", "size": 7868, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/optimizer/optimizer.cc", "max_stars_repo_name": "unclearness/ugu", "max_stars_repo_head_hexsha": "641c5170147091e82578fa6bcd84f3484172f487", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2019-12-29T17:27:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T11:02:35.000Z", "max_issues_repo_path": "src/optimizer/optimizer.cc", "max_issues_repo_name": "unclearness/ugu", "max_issues_repo_head_hexsha": "641c5170147091e82578fa6bcd84f3484172f487", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T12:04:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-22T12:04:53.000Z", "max_forks_repo_path": "src/optimizer/optimizer.cc", "max_forks_repo_name": "unclearness/ugu", "max_forks_repo_head_hexsha": "641c5170147091e82578fa6bcd84f3484172f487", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-26T06:58:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T12:24:09.000Z", "avg_line_length": 27.4146341463, "max_line_length": 80, "alphanum_fraction": 0.6201067616, "num_tokens": 2259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5323733231453368}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2012 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#include <iostream>\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n#include \"dune/grid/uggrid.hh\"\n\n#include \"fem/assemble.hh\"\n#include \"fem/hierarchicErrorEstimator.hh\"\n#include \"fem/lagrangespace.hh\"\n#include \"fem/hierarchicspace.hh\"\n#include \"linalg/direct.hh\"\n#include \"linalg/jacobiPreconditioner.hh\"\n#include \"linalg/cg.hh\"\n#include \"utilities/enums.hh\"\n#include \"utilities/gridGeneration.hh\" //  createUnitSquare, createUnitCube\n#include \"io/vtk.hh\"\n//#include \"io/amira.hh\"\n#include \"utilities/kaskopt.hh\"\n\n#include \"mg/pcg.hh\"\n#include \"mg/apcg.hh\"\n\n#include \"utilities/kaskopt.hh\"\n\nusing namespace Kaskade;\n#include \"poisson.hh\"\n\n\nbool compareAbs(const double x1, const double  x2)\n{\n  return fabs(x1)>fabs(x2);\n}\n\nint main(int argc, char *argv[])\n{\n  using namespace boost::fusion;\n\n  std::cout << \"Start heat transfer tutorial program using HB error estimation (SpaceDimension=3)\"\n            << std::endl;\n\n  boost::timer::cpu_timer totalTimer;\n\n  int verbosityOpt = 1;\n  bool dump = true; \n  std::unique_ptr<boost::property_tree::ptree> pt = getKaskadeOptions(argc, argv, verbosityOpt, dump);\n\n  int refinements   = getParameter(pt, \"refinements\", 2),\n      order         = getParameter(pt, \"order\", 1),\n      maxAdaptSteps = getParameter(pt, \"maxAdaptSteps\", 2),\n      verbosity     = getParameter(pt, \"verbosity\", 1);\n  std::cout << \"original mesh shall be refined : \" << refinements << \" times\" << std::endl;\n  std::cout << \"discretization order           : \" << order << std::endl;\n  std::cout << \"max. adaptive refine steps     : \" << maxAdaptSteps << std::endl;\n  std::cout << \"output level (verbosity)       : \" << verbosity << std::endl << std::endl;\n\n  int  direct, onlyLowerTriangle = false;\n  \n  DirectType directType;\n  IterateType iterateType = IterateType::PCG;\n  PrecondType precondType = PrecondType::NONE;\n  MatrixProperties property;\n  std::string empty, geoFile(\"cube.am\");\n\n  geoFile = getParameter(pt, \"file\", geoFile);\n\n  std::string s(\"names.type.\");\n  s += getParameter(pt, \"solver.type\", empty);\n  direct = getParameter(pt, s, 0);\n\n  std::cout << \"Solver type is \" << (direct ? \"direct\" : \"iterative\") << std::endl;\n\n  s = \"names.direct.\" + getParameter(pt, \"solver.direct\", empty);\n  directType = static_cast<DirectType>(getParameter(pt, s, 2));\n\n  s = \"names.iterate.\" + getParameter(pt, \"solver.iterate\", empty);\n  iterateType = static_cast<IterateType>(getParameter(pt, s, 0));\n\n  property = MatrixProperties::SYMMETRIC;\n\n  if ( (directType == DirectType::MUMPS)||(directType == DirectType::PARDISO) || ( (precondType == PrecondType::ICC) && !direct ) )\n  {\n    onlyLowerTriangle = true;\n    std::cout << \n      \"Note: direct solver MUMPS/PARADISO or ICC preconditioner ===> onlyLowerTriangle is set to true!\" \n      << std::endl << std::endl;\n  }\n\n  //   three-dimensional space: dim=3\n  constexpr int dim=3; \n  using Grid = Dune::UGGrid<dim>;\n  using LeafView = Grid::LeafGridView;\n  using H1Space = FEFunctionSpace<ContinuousLagrangeMapper<double,LeafView> >;\n  using Spaces = boost::fusion::vector<H1Space const*>;\n  using VariableDescriptions = boost::fusion::vector<VariableDescription<0,1,0> >;\n  using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;\n  using Functional = PoissonFunctional<double,VariableSet>;\n  using Assembler = VariationalFunctionalAssembler<LinearizationAt<Functional> >;\n  constexpr int neq = Functional::TestVars::noOfVariables;\n  using CoefficientVectors = VariableSet::CoefficientVectorRepresentation<0,neq>::type;\n  using H1ExSpace = FEFunctionSpace<ContinuousHierarchicExtensionMapper<double,LeafView> >;\n  using H1ExSpaces = boost::fusion::vector<H1Space const*,H1ExSpace const*>;\n  using ExVariableDescriptions = boost::fusion::vector<VariableDescription<1,1,0> >;\n  using ExVariableSet = VariableSetDescription<H1ExSpaces,ExVariableDescriptions>;\n  using ErrorEstimator = HierarchicErrorEstimator<LinearizationAt<Functional>,ExVariableSet>;\n  using EstAssembler = VariationalFunctionalAssembler<ErrorEstimator>;\n  using ExCoefficientVectors = ExVariableSet::CoefficientVectorRepresentation<0,1>::type;\n  using LinearSpace = VariableSet::CoefficientVectorRepresentation<0,neq>::type;\n  using AssOperator = AssembledGalerkinOperator<Assembler,0,1,0,1>;\n  using AssEstOperator = AssembledGalerkinOperator<EstAssembler>;\n\n  GridManager<Grid> gridManager( createUnitCube<Grid>(0.5) );\n\n  gridManager.globalRefine(refinements);\n  std::cout << std::endl << \"Grid: \" << gridManager.grid().size(0) << \" tetrahedra, \" << std::endl;\n  std::cout << \"      \" << gridManager.grid().size(1) << \" triangles, \" << std::endl;\n  std::cout << \"      \" << gridManager.grid().size(dim-1) << \" edges, \" << std::endl;\n  std::cout << \"      \" << gridManager.grid().size(dim) << \" points\" << std::endl;\n  // a gridmanager is constructed \n  // as connector between geometric and algebraic information\n  gridManager.setVerbosity(verbosity);\n\n\n  // construction of finite element space for the scalar solution T\n  H1Space temperatureSpace(gridManager,gridManager.grid().leafGridView(),order);\n  Spaces spaces(&temperatureSpace);\n  // VariableDescription<int spaceId, int components, int Id>\n  // spaceId: number of associated FEFunctionSpace\n  // components: number of components in this variable\n  // Id: number of this variable\n  std::string varNames[1] = { \"T\" };\n  VariableSet variableSet(spaces,varNames);\n\n  Functional F;\n  constexpr int nvars = Functional::AnsatzVars::noOfVariables;\n  std::cout << \"no of variables = \" << nvars << std::endl;\n  std::cout << \"no of equations = \" << neq   << std::endl;\n\n  Assembler assembler(gridManager,spaces);\n\n  H1ExSpace spaceEx(gridManager,gridManager.grid().leafGridView(), order+1);\n\n  H1ExSpaces exSpaces(&temperatureSpace,&spaceEx);\n\n  std::string exVarNames[2] = { \"l\", \"e\"};\n  ExVariableSet exVariableSet(exSpaces, exVarNames);\n\n  EstAssembler estAssembler(gridManager,exSpaces);\n\n  auto const& is = gridManager.grid().leafIndexSet();\n\n  VariableSet::VariableSet x(variableSet), dx(variableSet), tmp(variableSet);\n\n  double rTolX = 2.0e-3, aTolX = 2.0e-3, minRefine = 0.2;\n    \n  std::vector<std::pair<double,double> > tolX(variableSet.noOfVariables);\n  std::vector<std::pair<double,double> > tolXC(variableSet.noOfVariables);\n  for (int i=0; i<tolX.size(); ++i)\n  {\n    tolX[i] = std::make_pair(aTolX,rTolX);\n    tolXC[i] = std::make_pair(aTolX/100,rTolX/100);\n  }\n  std::cout << \"Accuracy: rTol = \" << rTolX << \", aTol = \" << aTolX << std::endl;\n  std::cout << \"Minimal number of cells to refine in an adaptive step: \" << minRefine *100\n            << \" % of all\" << std::endl << std::endl;\n\n  int refSteps = -1;\n  bool accurate = false;\n  int iteSteps = getParameter(pt, \"solver.iteMax\", 1000);\n  double iteEps = getParameter(pt, \"solver.iteEps\", 1.0e-6);\n  if (!direct)\n  {\n    std::cout << \"max. number of iterations in iterative solver = \" << iteSteps << std::endl;\n    std::cout << \"requested accuracy in iterate solver = \" << iteEps << std::endl << std::endl;\n  };\n  Dune::InverseOperatorResult res;\n  double errNorm = 0;\n\n  size_t size = variableSet.degreesOfFreedom(0,1);\n  double gamma = 1.0, d = dim;\n  double beta = 1.0/sqrt(d*gamma);\n  double alpha = (d*gamma-1.0)/(d*(1.0+gamma));\n  double qk = 1.0, dNk = size, zk = 0.0;\n  double requested = sqrt(1-beta*beta)*tolX[0].first;\n  double safety = 1.0;\n  double yk = pow(dNk,alpha);\n  //printf(\"gamma=%e, d=%e, beta=%e, alpha=%e, requested=%e, safety=%e\\n\",\n  //        gamma,d,beta,alpha,requested,safety);\n\n  do\n  {\n    refSteps++;\n\n    CoefficientVectors solution(VariableSet::CoefficientVectorRepresentation<0,neq>::init(spaces));\n    solution = 0;\n    CoefficientVectors hilfe(VariableSet::CoefficientVectorRepresentation<0,neq>::init(spaces));\n    hilfe = 0;\n    assembler.assemble(linearization(F,x));\n    CoefficientVectors rhs(assembler.rhs());\n    AssembledGalerkinOperator<Assembler,0,1,0,1> A(assembler, onlyLowerTriangle);\n\n    if (direct)\n    {\n      directInverseOperator(A,directType,property).applyscaleadd(-1.0,rhs,solution);\n    }\n    else\n    {\n      switch (iterateType)\n      {\n      case IterateType::CG:\n      {\n        if ( verbosity>0 ) std::cout << \"preconditioned cg solver is used\" << std::endl;\n        JacobiPreconditioner<AssOperator> jacobi(A,1.0);\n        const DefaultDualPairing<LinearSpace,LinearSpace> defaultScalarProduct{};\n        StrakosTichyPTerminationCriterion<double> termination(iteEps,iteSteps);\n        int lookAhead = getParameter(pt, \"solver.lookAhead\", 3);\n        termination.setLookAhead(lookAhead);\n        CG<LinearSpace,LinearSpace> cg(A,jacobi,defaultScalarProduct,termination,verbosity-1);\n        cg.apply(hilfe,rhs,res);\n      }\n      break;\n      case IterateType::PCG:\n      {\n        if ( verbosity>0) std::cout << \"   preconditioned cascadic multigrid solver I is used\" << std::endl;\n        JacobiPreconditioner<AssOperator> jacobi(A,1.0);\n        NMIIIPCGSolver<LinearSpace> pcg(A,jacobi,iteEps,iteSteps,verbosity-1);\n        pcg.apply(hilfe,rhs,res);\n      }\n      break;\n      case IterateType::APCG:\n      {\n        if ( verbosity>0) std::cout << \"   preconditioned cascadic multigrid solver II is used\" << std::endl;\n        int addedIterations = getParameter(pt, \"solver.APCG.addedIterations\", 10);\n        JacobiPreconditioner<AssOperator> jacobiPCG(A,1.0);\n        NMIIIAPCGSolver<LinearSpace> apcg(A,jacobiPCG,iteEps,iteSteps,verbosity-1,addedIterations);\n        apcg.apply(hilfe,rhs,res);\n      }\n      break;\n      default:\n        std::cout << \"Solver not available\" << std::endl;\n        throw -111;\n      }\n      solution.axpy(-1,hilfe);\n    }\n    dx.data = solution.data;\n\n\n    // Do hierarchical error estimation. Remember to provide the very same underlying problem to the\n    // error estimator functional as has been used to compute dx (do not modify x!).\n    std::vector<double> errorDistribution(is.size(0),0.0);\n    double maxErr = 0.0;\n    double errLevel = 0.0;\n      \n    if (!tolX.empty())\n    {\n      tmp *= 0 ;\n      estAssembler.assemble(ErrorEstimator(LinearizationAt<Functional>(F,x),dx));\n      constexpr int estNvars = ErrorEstimator::AnsatzVars::noOfVariables;\n      constexpr int estNeq = ErrorEstimator::TestVars::noOfVariables;\n      size_t  estNnz = estAssembler.nnz(0,estNeq,0,estNvars,false);\n      size_t  estSize = exVariableSet.degreesOfFreedom(0,estNvars);\n\n      std::vector<int> estRidx(estNnz), estCidx(estNnz);\n      std::vector<double> estData(estNnz), estRhs(estSize), estSolVec(estSize);\n      estAssembler.toSequence(0,estNeq,estRhs.begin());\n\n      // iterative solution of error estimator\n\n      AssEstOperator agro(estAssembler);\n      Dune::InverseOperatorResult estRes;\n      ExCoefficientVectors estRhside(estAssembler.rhs());\n      ExCoefficientVectors estSol(ExVariableSet::CoefficientVectorRepresentation<0,1>::init(exSpaces));\n      estSol = 1.0 ;\n      JacobiPreconditioner<AssEstOperator> jprec(agro, 1.0);\n      jprec.apply(estSol,estRhside); //single Jacobi iteration\n      estSol.write(estSolVec.begin());\n\n      // Transfer error indicators to cells.\n      for (auto ci=variableSet.gridView.begin<0>(); ci!=variableSet.gridView.end<0>(); ++ci)\n      {\n        double err = 0;\n        auto gix = spaceEx.mapper().globalIndices(*ci);\n        for (auto j=gix.begin(); j!=gix.end(); ++j)\n          err += fabs(component<0>(estSol)[*j]);\n        errorDistribution[is.index(*ci)] = err;\n        if (fabs(err)>maxErr) maxErr = fabs(err);\n      }\n\n      errLevel = 0.5*maxErr;\n      if (minRefine>0.0)\n      {\n        std::vector<double> eSort(errorDistribution);\n        std::sort(eSort.begin(),eSort.end(),compareAbs);\n        int minRefineIndex = minRefine*(eSort.size()-1);\n        double minErrLevel = fabs(eSort[minRefineIndex])+1.0e-15;\n        if (minErrLevel<errLevel)\n          errLevel = minErrLevel;\n      }\n\n      errNorm = 0 ;\n      for (int k=0; k < estRhs.size() ; k++ )\n        errNorm +=  estRhs[k]*estSolVec[k] ;\n    }\n    errNorm = sqrt(errNorm) ;\n    // apply the Newton correction here\n    x += dx;\n\n    if ( verbosity>0) \n            std::cout << \"step = \" << refSteps << \": \" << size << \" points,   ||estim. err|| = \" << std::scientific << std::setprecision(3) << errNorm << std::resetiosflags( ::std::ios::scientific ) << std::setprecision(6) << std::endl;\n\n\n\t// graphical output of solution, mesh is not yet refined\n    std::ostringstream fn;\n    fn << \"graph3d/peak-grid\";\n    fn.width(3);\n    fn.fill('0');\n    fn.setf(std::ios_base::right,std::ios_base::adjustfield);\n    fn << refSteps;\n    fn.flush();\n    writeVTKFile(x,fn.str(),IoOptions().setOrder(order).setPrecision(7));\n    std::cout << \"   output written to file \" << fn.str() << std::endl;\n\n\n    if (refSteps>maxAdaptSteps) \n    {\n      std::cout << \"max. number of refinement steps is reached\" << std::endl;\n      break;\n    }\n\n\t// Evaluation of (global/local) error estimator information \n    if (!tolX.empty())\n    {\n      if (errNorm<requested)\n      {\n        accurate = true ;\n        std::cout << \"||estim. error|| is smaller than requested\" << std::endl;\n      }\n      else\n      {\n        // Refine mesh.\n\n        int noToRefine = 0;\n        double alphaSave = 1.0 ;\n        std::vector<bool> toRefine( is.size(0), false ) ; //for adaptivity in compression\n        std::vector< std::vector<bool> > refinements;\n        for (auto ci=variableSet.gridView.begin<0>(); ci!=variableSet.gridView.end<0>(); ++ci)\n          if (fabs(errorDistribution[is.index(*ci)]) >= alphaSave*errLevel)\n          {\n            noToRefine++;\n            toRefine[is.index(*ci)] = true ;\n            gridManager.mark(1,*ci);\n          }\n\n        refinements.push_back(toRefine);\n        accurate = !gridManager.adaptAtOnce();\n      }\n    }\n    \n    size = variableSet.degreesOfFreedom(0,1);\n    qk = size/dNk;\n    dNk = size;\n    yk += pow(dNk,alpha);\n    zk = pow(dNk,alpha)*(pow(errNorm/requested,d*alpha)-pow(qk,alpha))/(pow(qk,alpha)-1.0);\n    iteEps = safety*beta*errNorm*yk/(yk+zk);\n    \n  } while (!accurate);     \n\n  std::cout << \"total computing time: \" << boost::timer::format(totalTimer.elapsed()) << \"\\n\";\n  std::cout << \"End peak source problem\" << std::endl;\n}\n", "meta": {"hexsha": "cf11815651d1077c51fda92948109b36d51fee19", "size": 15058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/HB_errorEstimation/heat3d.cpp", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/tutorial/HB_errorEstimation/heat3d.cpp", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:33.000Z", "max_forks_repo_path": "Kaskade/tutorial/HB_errorEstimation/heat3d.cpp", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 39.315926893, "max_line_length": 236, "alphanum_fraction": 0.6361402577, "num_tokens": 4185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.53237331842569}}
{"text": "#include <matplotlibcpp.h>\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n\nnamespace plt = matplotlibcpp;\nusing namespace Eigen;\n\nint main(){\n    using std::cout;\n    using std::endl;\n    using std::vector;\n\n    VectorXd x = Eigen::VectorXd::LinSpaced(200, 0, 6);\n    VectorXd y;\n\n    y = x.array().sin().exp().matrix();\n\n    vector<double> x_vec(200), y_vec(200);\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], 200) = x;\n    Map<VectorXd>(&y_vec[0], 200) = y;\n\n    plt::named_plot(\"sample\", x_vec, y_vec, \"--b\");\n    plt::grid(true);\n    plt::legend();\n    plt::save(\"./ch3/sample_eigen.png\");\n\n    return 0;\n}", "meta": {"hexsha": "ed3bd542bfbfc31f7d385cb0346f1247bae1aa7e", "size": 654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/visualize_eigen_vector.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_eigen_vector.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_eigen_vector.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.0967741935, "max_line_length": 55, "alphanum_fraction": 0.623853211, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.532373306020393}}
{"text": "#include \"Circle2D.h\"\n#include \"Line2D.h\"\n#include \"Pose2D.h\"\n#include \"Geometry.h\"\n\n#include <cmath>\n#include <boost/concept_check.hpp>\n\nusing namespace A2O;\nusing namespace Eigen;\n\n\n\nCircle2D::Circle2D()\n      : _origin(0, 0), _radius(1)\n{\n}\n\n\nCircle2D::Circle2D(const double& xOrigin,\n\t       const double& yOrigin,\n\t       const double& radius)\n      : _origin(xOrigin, yOrigin), _radius(radius >= 0 ? radius : -radius)\n{\n}\n\nCircle2D::Circle2D(const Vector2d& origin,\n\t       const double& radius)\n      : Circle2D(origin(0), origin(1), radius)\n{\n}\n\nCircle2D::Circle2D(const Vector2d& origin,\n\t\t   const Vector2d& point)\n      : _origin(origin), _radius(Geometry::getDistance(origin, point))\n{\n}\n\nCircle2D::Circle2D(const double& xOrigin,\n\t       const double& yOrigin,\n\t       const double& px,\n\t       const double& py)\n      : _origin(xOrigin, yOrigin), _radius(Geometry::getDistance(xOrigin, yOrigin, px, py))\n{\n}\n\nCircle2D::Circle2D(const Pose2D tangent, Vector2d point)\n{\n  // transform point in to an tangent touching point local coordinate system (tangent angle = x-axis + pi)\n  Eigen::Vector2d tmpVector = point - tangent.getPosition();\n  Eigen::Vector2d rotatedVector(0,0);\n  Angle::rotate(tmpVector, - tangent.getAngle().rad(), rotatedVector);\n  // calculate y-coordinate of the circle origin\n  double my = (- pow(rotatedVector(0), 2) - pow(rotatedVector(1), 2) ) / (-2 * rotatedVector(1));\n  // transform back to world coordinate system\n  Eigen::Vector2d shiftedCircleOrigin(0,0);\n  Angle::rotate(Eigen::Vector2d(0, my), tangent.getAngle().rad(), shiftedCircleOrigin);\n  _origin = shiftedCircleOrigin + tangent.getPosition();\n  _radius = Geometry::getDistance(_origin, tangent.getPosition());\n}\n\nCircle2D::~Circle2D()\n{\n}\n\nconst Vector2d& Circle2D::origin() const\n{\n  return _origin;\n}\n\nconst double& Circle2D::radius() const\n{\n  return _radius;\n}\n\nconst bool Circle2D::checkInnerTouching(const Circle2D& other) const\n{\n  double distance = getDistanceTo(other);\n  \n  return distance > 0\n      && (_radius == distance + other._radius || other._radius == distance + _radius);\n}\n\nconst bool Circle2D::checkOuterTouching(const Circle2D& other) const\n{\n  double distance = getDistanceTo(other);\n  \n  return _radius + other._radius == distance;\n}\n\nconst bool Circle2D::checkIntersect(const Circle2D& other) const\n{\n  double distance = getDistanceTo(other);\n  \n  return distance > 0\n      && distance < _radius + other._radius\n      && _radius < distance + other._radius\n      && other._radius < distance + _radius;\n}\n\nconst bool Circle2D::checkInnerCircle(const Circle2D& other) const\n{\n  double distance = getDistanceTo(other);\n  \n  return _radius > distance + other._radius || other._radius > distance + _radius;\n}\n\nconst double Circle2D::getDistanceTo(const Circle2D& other) const\n{\n  return Geometry::getDistance(_origin, other._origin);\n}\n\nconst Vector2d Circle2D::getPointOnCircle(const Angle& angle) const\n{\n  return Vector2d(_origin(0) + (std::cos(angle.rad()) * _radius),\n\t\t  _origin(1) + (std::sin(angle.rad()) * _radius));\n}\n\nconst bool Circle2D::isOnCircle(const Vector2d& point) const\n{\n  double distance = Geometry::getDistance(_origin, point);\n  double diff = std::abs(distance - _radius);\n  return (diff < 0.000001);\n}\n\nconst Angle Circle2D::getAngle(const Vector2d& point)\n{\n  Vector2d shiftedPoint = point - _origin;\n  // point is equal to origin\n  if(std::fabs(point(0)- _origin(0)) < 0.001 && std::fabs(point(1)- _origin(1)) < 0.001)\n    return Angle(0);\n  // threshold x = 0\n  if(std::fabs<double>(shiftedPoint(0)) < 0.0001)\n  {\n    if(shiftedPoint(1) > 0)\n      return Angle(M_PI * 0.5);\n    else\n      return Angle(-M_PI * 0.5);\n  }\n\n  double angle = atan2(shiftedPoint(1), shiftedPoint(0));\n  return Angle(angle); \n}\n\n\nconst Angle Circle2D::getAngle(const double& segmentLength)\n{\n  return Angle(segmentLength / _radius);\n}\n\nPose2D Circle2D::getClosestPose(const Vector2d& point)\n{\n Angle angle = Angle::to(point - _origin);\n Vector2d closestPoint = getPointOnCircle(angle);\n return Pose2D(closestPoint, slope(closestPoint));\n}\n\nAngle Circle2D::slope(const Vector2d& point)\n{    \n  // calculate slope on upper semicircle\n  double slope = -0.5 * sqrt(1 / (pow(_radius, 2) - pow(point(0) - _origin(0), 2))) * (2 * point(0) - 2 * _origin(0));\n  // check if point is on lower semicircle\n  if(_origin(1) > point(1))\n  {\n    slope *= -1;\n  }\n  return Angle(atan(slope));\n}\n\nshort Circle2D::getDirectionOfRotation(const Vector2d& point, const Angle& angle)\n{\n  Angle angle2 = getAngle(point);\n  angle2 += Angle(M_PI * 0.5); \n  double angleResult  = std::fabs<double>(angle2.rad() - angle.rad()) + M_PI * 0.5;\n  \n  if(angleResult < M_PI || angleResult > 2 * M_PI)\n    return 1;\n  else\n    return -1;\n}\n\nshort int Circle2D::getDirectionOfRotation(const Pose2D pose)\n{\n  return getDirectionOfRotation(pose.getPosition(), pose.getAngle());\n}\n\n\nstd::vector< Vector2d > Circle2D::getTrail(const Vector2d& start, const Vector2d& end)\n{\n  Angle startAngle = getAngle(start);\n  Angle endAngle = getAngle(end);\n  Angle diff = endAngle - startAngle;\n  Angle delta =  Angle(diff.rad() / 10);\n  Vector2d point;\n  std::vector<Vector2d> points;\n  int i = 0;\n  do{\n    startAngle += delta;\n    point = getPointOnCircle(startAngle);\n    points.push_back(point);\n  } while(++i < 10);\n  return points;\n}\n\nbool Circle2D::operator==(const Circle2D& other) const\n{\n  return _origin == other._origin && _radius == other._radius;\n}\n\nbool Circle2D::operator!=(const Circle2D& other) const\n{\n  return !(*this == other);\n}\n\nconst Circle2D Circle2D::avg(const Circle2D& c1,\n\t\t\t     const Circle2D& c2,\n\t\t\t     const double& weight1,\n\t\t\t     const double& weight2)\n{\n  Vector2d avgOrigin = Geometry::avg(c1._origin, c2._origin, weight1, weight2);\n  \n  return Circle2D(avgOrigin, c1._radius * weight1 + c2._radius * weight2);\n}\n\nconst Circle2D Circle2D::avg(const std::vector<Circle2D>& circles)\n{\n  size_t size = circles.size();\n  if (size == 0) {\n    return Circle2D(0, 0, 1);\n  } else if (size == 1) {\n    return circles[0];\n  }\n  \n  double x = 0;\n  double y = 0;\n  double radius = 0;\n  \n  for (Circle2D circle : circles) {\n    x += circle._origin(0);\n    y += circle._origin(1);\n    radius += circle._radius;\n  }\n  \n  return Circle2D(x / size, y / size, radius / size);\n}\n", "meta": {"hexsha": "d12436222ca90a9041df2c322386cae16e936420", "size": 6273, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/aadcUser/src/HSOG_Runtime/a2o/utils/geometry/Circle2D.cpp", "max_stars_repo_name": "AppliedAutonomyOffenburg/AADC_2015_A2O", "max_stars_repo_head_hexsha": "19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T21:39:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-09T21:39:29.000Z", "max_issues_repo_path": "src/aadcUser/src/HSOG_Runtime/a2o/utils/geometry/Circle2D.cpp", "max_issues_repo_name": "TeamAutonomousCarOffenburg/A2O_2015", "max_issues_repo_head_hexsha": "19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac", "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": "src/aadcUser/src/HSOG_Runtime/a2o/utils/geometry/Circle2D.cpp", "max_forks_repo_name": "TeamAutonomousCarOffenburg/A2O_2015", "max_forks_repo_head_hexsha": "19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-04-05T06:34:08.000Z", "max_forks_repo_forks_event_max_datetime": "2016-04-05T06:34:08.000Z", "avg_line_length": 25.5, "max_line_length": 118, "alphanum_fraction": 0.6791009087, "num_tokens": 1837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.81286730877087, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5323425268749223}}
{"text": "#include <benchmark/benchmark.h>\n\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include <mitrax/dim.hpp>\n\n#include <random>\n#include <string>\n\n#include \"../../../include/get_binaryop.hpp\"\n\n\nusing namespace mitrax;\nusing namespace mitrax::literals;\n\n\ntemplate < typename T, typename Op >\n[[gnu::noinline]]\nvoid bm(benchmark::State& state, Op op, rt_dim_pair_t d1, rt_dim_pair_t d2){\n\tstd::random_device rd;\n\tstd::mt19937 gen(rd());\n\tstd::uniform_int_distribution< T > dis(\n\t\tstd::numeric_limits< T >::min(),\n\t\tstd::numeric_limits< T >::max()\n\t);\n\n\tboost::numeric::ublas::matrix< T > m1(size_t(d1.cols()), size_t(d1.rows()));\n\tfor(size_t y = 0; y < m1.size2(); ++y){\n\t\tfor(size_t x = 0; x < m1.size1(); ++x){\n\t\t\tm1(x, y) = dis(gen);\n\t\t}\n\t}\n\n\tboost::numeric::ublas::matrix< T > m2(size_t(d2.cols()), size_t(d2.rows()));\n\tfor(size_t y = 0; y < m2.size2(); ++y){\n\t\tfor(size_t x = 0; x < m2.size1(); ++x){\n\t\t\tm2(x, y) = dis(gen);\n\t\t}\n\t}\n\n\twhile(state.KeepRunning()){\n\t\tboost::numeric::ublas::matrix< T > res = op(m1, m2);\n\t\tbenchmark::DoNotOptimize(res);\n\t}\n}\n\n\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/for_each.hpp>\n\n\nnamespace init{\n\n\tconstexpr auto dimensions = boost::hana::make_tuple(\n\t\t\tdim_pair(2_CS, 2_RS),\n\t\t\tdim_pair(4_CS, 2_RS),\n\t\t\tdim_pair(8_CS, 2_RS),\n\t\t\tdim_pair(8_CS, 4_RS),\n\t\t\tdim_pair(8_CS, 8_RS),\n\t\t\tdim_pair(8_CS, 16_RS),\n\t\t\tdim_pair(8_CS, 32_RS),\n\t\t\tdim_pair(8_CS, 64_RS),\n\t\t\tdim_pair(16_CS, 64_RS),\n\t\t\tdim_pair(32_CS, 64_RS),\n\t\t\tdim_pair(64_CS, 64_RS),\n\t\t\tdim_pair(128_CS, 64_RS),\n\t\t\tdim_pair(256_CS, 64_RS),\n\t\t\tdim_pair(256_CS, 128_RS),\n\t\t\tdim_pair(256_CS, 256_RS)\n\t\t);\n\n\tusing plus = std::plus<>;\n\tstruct multiplies{\n\t\ttemplate < typename T, typename U>\n\t\tconstexpr decltype(auto) operator()(T&& lhs, U&& rhs)const{\n\t\t\treturn boost::numeric::ublas::prod(\n\t\t\t\tstatic_cast< T&& >(lhs),\n\t\t\t\tstatic_cast< U&& >(rhs)\n\t\t\t);\n\t\t}\n\t};\n\n}\n\n#include \"main.hpp\"\n\n", "meta": {"hexsha": "f9b9c9a5a3d407fe73a38b1fe8a2f794c4bc07a5", "size": 1878, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/benchmark/binary_op/size/uBLAS_rt_heap.cpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmark/benchmark/binary_op/size/uBLAS_rt_heap.cpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark/benchmark/binary_op/size/uBLAS_rt_heap.cpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5862068966, "max_line_length": 77, "alphanum_fraction": 0.6405750799, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5323425218624386}}
{"text": "#include \"clear/Hungarian.h\"\n#include \"clear/blockSVD.hpp\"\n#include \"clear/MultiwayMatcher.hpp\"\n\n#include <cassert>\n#include <fstream>\n#include <ros/console.h>\n#include <Eigen/SVD>\n#include <Eigen/SparseLU>\n#include <ctime>\n#include <ratio>\n#include <chrono>\n\nusing std::vector;\nusing namespace std::chrono;\nusing Eigen::MatrixXf;\n\nMultiwayMatcher::MultiwayMatcher(){}\n\nMultiwayMatcher::~MultiwayMatcher(){}\n\nvoid MultiwayMatcher::initialize(Eigen::MatrixXf A, vector<unsigned> numSmp){\n\thigh_resolution_clock::time_point t1,t2;\n\tduration<double, std::milli> elapsed_time;\n\n\tt1 = high_resolution_clock::now();\n\tA_sp = A.sparseView();\n\n\t// A_ = A;\n\tnumSmp_ = numSmp;\n\t\n\t// compute cumsum_\n\tcumSum_.resize(numSmp_.size(), 0);\n\tstd::partial_sum(numSmp_.begin(), numSmp_.end(), cumSum_.begin());\n\tassert(cumSum_.back() == A.rows());\n\n\t// compute other matrices needed\n\tconstruct_D();\n\tconstruct_L();\n\tconstruct_Lnrm();\n\tt2 = high_resolution_clock::now();\n\telapsed_time = t2-t1;\n\tif(verbose_) ROS_INFO_STREAM(\"Initialization time: \" << (float) elapsed_time.count() / 1000.0 << \" seconds.\");\n\n}\n\nvoid MultiwayMatcher::set_verbose(bool verbose){\n\tverbose_ = verbose;\n}\n\nvoid MultiwayMatcher::estimate_universe_size(){\n\n\t// singular value decomposition on Lnrm_\n\t// Eigen::JacobiSVD<MatrixXf> svd(Lnrm_, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\t// Vl_ = svd.matrixV();\n\t// sl_ = svd.singularValues(); // a column vector of singular values in decreasing order\n\n\tblockSVD(MatrixXf(A_sp), Lnrm_, Vl_, sl_);\n\n\tm_ = 0;\n\tfor(unsigned i = 0; i < sl_.rows(); ++i){\n\t\tif (sl_(i) < thresh_) m_++;\n\t}\n\n\tvector<unsigned>::iterator max_iterator;\n\tmax_iterator = std::max_element(numSmp_.begin(), numSmp_.end());\n\t// Minimum # of objects must not be less than max # of samples\n\tm_ = std::max(*max_iterator, m_); \n\n\tif (verbose_) ROS_INFO_STREAM(\"Estimated size of universe: \" << m_);\n\n\tfused_counts_.resize(m_, 0);\n\n}\n\nvoid MultiwayMatcher::CLEAR(){\n\t// runtime analysis\n\thigh_resolution_clock::time_point t1,t2;\n\tduration<double, std::milli> elapsed_time;\n\n\tt1 = high_resolution_clock::now();\n\testimate_universe_size();\n\tt2 = high_resolution_clock::now();\n\telapsed_time = t2-t1;\n\tif(verbose_) ROS_INFO_STREAM(\"SVD elapsed time: \" << (float) elapsed_time.count() / 1000.0 << \" seconds.\");\n\n\n\t// recover embedding matrix\n\tN_ = Vl_.block(0, Vl_.cols()-m_, Vl_.rows(), m_);\n\tassert(N_.rows() == Vl_.rows());\n\tassert(N_.cols() == m_);\n\n\t// L2 normalize each row\n\tfor (unsigned i = 0 ; i < N_.rows(); ++i){\n\t\tN_.row(i) = N_.row(i) / N_.row(i).norm();\n\t}\n\n\n\tif(verbose_) ROS_INFO_STREAM(\"Finding cluster centers...\");\n\t// find cluster centers (LU)\n\t// t1 = high_resolution_clock::now();\n\t// Eigen::FullPivLU<MatrixXf> LUsolver(N_);\n\t// C_ = LUsolver.permutationP() * N_;\n\t// C_ = C_.block(0, 0, m_, m_); // each row is a cluster center\n\t// t2 = high_resolution_clock::now();\n\t// elapsed_time = t2-t1;\n\t// if(verbose_) ROS_INFO_STREAM(\"LU elapsed time: \" << (float) elapsed_time.count() / 1000.0 << \" seconds.\");\n\n\t// find cluster centers (greedy)\n\tt1 = high_resolution_clock::now();\n\tC_ = MatrixXf::Zero(m_,m_);\n\tvector<bool> is_pivot(N_.rows(), false);\n\tvector<unsigned> pivots;\n\tC_.row(0) = N_.row(0);\n\tis_pivot[0] = true;\n\tpivots.push_back(0);\n\tMatrixXf X = N_ * N_.transpose();\n\tX = X.array().abs().matrix(); // compute coefficient-wise absolute values\n\tMatrixXf scores = MatrixXf::Zero(N_.rows(),1); // initialize score vector\n\tfor (unsigned k = 1; k < m_; ++k){\n\t\t// incremental update to scores\n\t\tscores = scores + X.col(pivots[k-1]);\n\t\t// find k-th cluster center\n\t\tdouble min_score = N_.rows();\n\t\tint min_idx = -1;\n\t\t// find row with best score\n\t\tfor (unsigned i = 0; i < N_.rows(); ++i){\n\t\t\tif (is_pivot[i]) continue;\n\t\t\tif(scores(i) < min_score){\n\t\t\t\tmin_score = scores(i);\n\t\t\t\tmin_idx = i;\n\t\t\t}\n\t\t}\n\t\tassert(min_idx >= 0);\n\t\tC_.row(k) = N_.row(min_idx);\n\t\tis_pivot[min_idx] = true;\n\t\tpivots.push_back(min_idx);\n\t}\n\tt2 = high_resolution_clock::now();\n\telapsed_time = t2-t1;\n\tif(verbose_) ROS_INFO_STREAM(\"Greedy elapsed time: \" << (float) elapsed_time.count() / 1000.0 << \" seconds.\");\n\n\n\t// scores based on dot product \n\tMatrixXf F = - N_ * C_.transpose(); \n\n\tassignments_.resize(N_.rows(), -1);\n\n\t// go through each agent\n\tt1 = high_resolution_clock::now();\n\tif(verbose_) ROS_INFO_STREAM(\"Clustering...\");\n\tfor (unsigned agent = 0; agent < numSmp_.size(); ++agent){\n\t\tunsigned size = numSmp_[agent]; \n\t\tunsigned start_idx = 0;\n\t\tif(agent > 0) start_idx = cumSum_[agent-1]; \n\t\tMatrixXf cost = F.block(start_idx,0,size,m_);\n\n\t\t// convert from Matrix to std::vector (TODO: improve)\n\t\tvector<vector<double>> costMatrix;\n\t\tfor (unsigned i = 0; i < size; ++i){\n\t\t\t// copy row i\n\t\t\tvector<double> row;\n\t\t\tfor (unsigned j = 0; j < m_; ++j){\n\t\t\t\trow.push_back(cost(i,j));\n\t\t\t}\n\t\t\tcostMatrix.push_back(row);\n\t\t}\n\n\t\t// assign to universe using Hungarian\n\t\t/*\n\t\tvector<int> a;\n\t\tHungarianAlgorithm Hungarian;\n\t\tHungarian.Solve(costMatrix, a);\n\n\t\t// copy results to assignments vector\n\t\tfor (unsigned i = 0; i < size; ++i){\n\t\t\tassert(a[i] >= 0);\n\t\t\tassignments_[start_idx + i] = a[i];\n\t\t\tfused_counts_[a[i]] = fused_counts_[a[i]] + 1;\n\t\t}\n\t\t*/\n\n\t\tfor (unsigned i = 0; i < size; ++i) {\n\t\t\tEigen::Index minIdx;\n\t\t\tauto const best_match = cost.row(i).minCoeff(&minIdx);\n\t\t\tassignments_[start_idx + i] = minIdx;\n\t\t\tfused_counts_[minIdx] += 1;\n\t\t}\n\t}\n\tt2 = high_resolution_clock::now();\n\telapsed_time = t2-t1;\n\tif(verbose_) ROS_INFO_STREAM (\"Hungarian elapsed time: \" << (float) elapsed_time.count() / 1000.0 << \" seconds.\");\n\n\t// recover lifting permutation\n\t// if(verbose_) ROS_INFO_STREAM(\"Recovering lifting permutation...\");\n\t// Y_ = MatrixXf::Zero(N_.rows(), m_);\n\t// // go through each observation\n\t// for (unsigned i = 0; i < Y_.rows(); ++i){\n\t// \tY_(i, assignments_[i]) = 1;\n\t// }\n\n\t// // recover pairwise matches\n\t// if(verbose_) ROS_INFO_STREAM(\"Recovering pairwise associations...\");\n\t// X_ = Y_ * Y_.transpose();\n}\n\nvoid MultiwayMatcher::get_X(Eigen::MatrixXf& X){\n\tX = X_;\n}\n\nvoid MultiwayMatcher::get_Y(Eigen::MatrixXf& Y){\n\tY = Y_;\n}\n\nvoid MultiwayMatcher::get_assignments(vector<int>& assignments){\n\tassignments = assignments_;\n}\n\nvoid MultiwayMatcher::get_fused_counts(vector<unsigned>& fused_counts){\n\tfused_counts = fused_counts_;\n}\n\nvoid MultiwayMatcher::construct_D(){\n\t// D_ = MatrixXf::Zero(A_.rows(), A_.cols());\n\t// for (unsigned i = 0; i < A_.rows(); ++i){\n\t// \tD_(i,i) = A_.row(i).sum();\n\t// }\n\n\tD_sp.resize(A_sp.rows(),A_sp.cols());\n\tD_sp.reserve(A_sp.rows());\n\tfor (int i = 0; i < A_sp.rows(); ++i){\n\t\tD_sp.insert(i,i) = A_sp.col(i).sum();\n\t}\t\n}\n\nvoid MultiwayMatcher::construct_L(){\n\t// L_ = D_ - A_;\n\tL_sp = D_sp - A_sp;\n\t// make symmetric\n\t// L_ = (L_ + L_.transpose())/2.0;\n}\n\nvoid MultiwayMatcher::construct_Lnrm(){\n\t// MatrixXf N = D_;\n\t// for (unsigned i = 0; i < D_.rows(); ++i){\n\t// \tdouble degree = D_(i,i);\n\t// \tassert(degree >= 0);\n\t// \tN(i,i) = 1 / std::sqrt((degree + 1)); // plus one to avoid dividing by zeros\n\t// }\n\t// Lnrm_ = N * L_ * N;\n\n\n\tEigen::SparseMatrix<float> N_sp;\n\tN_sp.resize(L_sp.rows(), L_sp.cols());\n\tN_sp.reserve(L_sp.rows());\n\tfor (int i = 0; i < D_sp.rows(); ++i){\n\t\tN_sp.insert(i,i) = 1 / std::sqrt((D_sp.coeffRef(i,i) + 1)); // plus one to avoid dividing by zeros\n\t}\n\tLnrm_sp = N_sp * L_sp * N_sp;\n\tLnrm_ = MatrixXf(Lnrm_sp);\n}\n\n\n/*\nY.T.\nDump all data for debugging purpose\n*/\nvoid MultiwayMatcher::save_data(){\n\t\n\t// std::string adj_filename = \"/home/yulun/srtc/src/srtc_map_merge/CLEARA.txt\";\n\t// std::ofstream A_file(adj_filename.c_str());\n\t// if (A_file.is_open()){\n\t// \tA_file << A_;\n\t//     A_file.close();\n\t// }\n\n\t// std::string numsmp_filename = \"/home/yulun/srtc/src/srtc_map_merge/CLEARnumsmp.txt\";\n\t// std::ofstream nsmp_file(numsmp_filename.c_str());\n\t// if (nsmp_file.is_open()){\n\t// \tfor (const auto &e : numSmp_) nsmp_file << e << \"\\n\";\n\t//     nsmp_file.close();\n\t// }\n\n\t// std::string lnrm_filename = \"/home/yulun/srtc/src/srtc_map_merge/CLEARLnrm.txt\";\n\t// std::ofstream Lnrm_file(lnrm_filename.c_str());\n\t// if (Lnrm_file.is_open()){\n\t// \tLnrm_file << Lnrm_;\n\t//     Lnrm_file.close();\n\t// }\n\n\t// std::string clearsl_filename = \"/home/yulun/srtc/src/srtc_map_merge/CLEARsl.txt\";\n\t// std::ofstream sl_file(clearsl_filename.c_str());\n\t// if (sl_file.is_open()){\n\t// \tsl_file << sl_;\n\t//     sl_file.close();\n\t// }\n\n\t// std::string clearVl_filename = \"/home/yulun/srtc/src/srtc_map_merge/CLEARVl.txt\";\n\t// std::ofstream vl_file(clearVl_filename.c_str());\n\t// if (vl_file.is_open()){\n\t// \tvl_file << Vl_;\n\t//     vl_file.close();\n\t// }\n\n\t// std::string clearx_filename = \"/home/yulun/srtc/src/srtc_map_merge/CLEARX.txt\";\n\t// std::ofstream X_file(clearx_filename.c_str());\n\t// if (X_file.is_open()){\n\t// \tX_file << X_;\n\t//     X_file.close();\n\t// }\n\t// std::string cleary_filename = \"/home/yulun/srtc/src/srtc_map_merge/CLEARY.txt\";\n\t// std::ofstream Y_file(cleary_filename.c_str());\n\t// if (Y_file.is_open()){\n\t// \tY_file << Y_;\n\t//     Y_file.close();\n\t// }\n\t// std::string clearc_filename = \"/home/yulun/srtc/src/srtc_map_merge/CLEARC.txt\";\n\t// std::ofstream C_file(clearc_filename.c_str());\n\t// if (C_file.is_open()){\n\t// \tC_file << C_;\n\t//     C_file.close();\n\t// }\n\t// std::string clearn_filename = \"/home/yulun/srtc/src/srtc_map_merge/CLEARN.txt\";\n\t// std::ofstream N_file(clearn_filename.c_str());\n\t// if (N_file.is_open()){\n\t// \tN_file << N_;\n\t//     N_file.close();\n\t// }\n}\n", "meta": {"hexsha": "6a4cd9210d5d9053fc37ccad888bf23cd7200173", "size": 9336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/clear/MultiwayMatcher.cpp", "max_stars_repo_name": "NamDinhRobotics/clear-fusion", "max_stars_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:53.000Z", "max_issues_repo_path": "src/clear/MultiwayMatcher.cpp", "max_issues_repo_name": "NamDinhRobotics/clear-fusion", "max_issues_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/clear/MultiwayMatcher.cpp", "max_forks_repo_name": "NamDinhRobotics/clear-fusion", "max_forks_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_forks_repo_licenses": ["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.2909090909, "max_line_length": 115, "alphanum_fraction": 0.6529562982, "num_tokens": 2900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5323425163873284}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SIMD_COMMON_FAST_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SIMD_COMMON_FAST_HYPOT_HPP_INCLUDED\n#include <boost/simd/toolbox/arithmetic/functions/fast_hypot.hpp>\n#include <boost/simd/include/functions/simd/tofloat.hpp>\n#include <boost/simd/include/functions/simd/abs.hpp>\n#include <boost/simd/include/functions/simd/if_else.hpp>\n#include <boost/simd/include/functions/simd/is_greater.hpp>\n#include <boost/simd/include/functions/simd/is_greater_equal.hpp>\n#include <boost/simd/include/functions/simd/sqrt.hpp>\n#include <boost/simd/include/functions/simd/sqr.hpp>\n#include <boost/simd/include/functions/simd/plus.hpp>\n#include <boost/simd/include/functions/simd/multiplies.hpp>\n#include <boost/simd/include/functions/simd/divides.hpp>\n#include <boost/simd/include/constants/eps.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::fast_hypot_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<arithmetic_<A0>,X>))((simd_<arithmetic_<A0>,X>))\n                            )\n  {\n\n    typedef typename dispatch::meta::as_floating<A0>::type result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return boost::simd::fast_hypot(tofloat(a0), tofloat(a1));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::fast_hypot_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<floating_<A0>,X>))((simd_<floating_<A0>,X>))\n                            )\n  {\n\n    typedef typename dispatch::meta::as_floating<A0>::type result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename meta::as_logical<A0>::type bA0;\n      A0 x =  boost::simd::abs(a0);\n      A0 y =  boost::simd::abs(a1);\n      bA0 gtyx = gt(y,x);\n      A0 xx = select(gtyx,y,x);\n      A0 yy = select(gtyx,x,y);\n      A0 r =  xx*sqrt(One<A0>()+sqr(yy/xx));\n      return select(ge(xx*Eps<A0>(), yy), xx, r);\n   }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "aaa297928e3f9c70c59f8073bedc6df2adf5d006", "size": 2623, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/fast_hypot.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/fast_hypot.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/fast_hypot.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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.7424242424, "max_line_length": 86, "alphanum_fraction": 0.6191383912, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5323425154620756}}
{"text": "\n// Before doing anything else, grab in the definitions of the test\n// space and trial spaces that make up the finite element system.\n#include <qdove/base/test_space.h>\n#include <qdove/base/trial_space.h>\n#include <qdove/materials/constants.h>\n\n// Start by solving Schroedinger's problem \n#include <qdove/models/schroedinger.h>\n\n// Let's use a function from the qdove library for a psudo potential.\n#include <qdove/psuedopotentials/function_library.h>\n\n// Also make use of the predefined generalised eigenspectrum system -\n// we need this for the Schroedinger problem.\n#include <qdove/generic_linear_algebra/eigenspectrum_system.h>\n\n// Next up are some deal.II objects that have not been generalised\n// away yet...\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/numerics/data_out.h>\n\n// C++\n#include <cassert>\n#include <iostream>\n#include <fstream>\n\n// The purpose of this example is to solve a problem with a known\n// analytical solution.\ntemplate<int dim>\nclass SchroedingerProblem\n{\npublic:\n  SchroedingerProblem (dealii::Triangulation<dim> &triangulation);\n  ~SchroedingerProblem ();\n\n  void write_gnuplot (const dealii::PETScWrappers::Vector &vector,\n\t\t      const std::string                   &name);\n  void run ();\n\nprivate:\n  // The description of the finite element basis\n  qdove::TrialSpace<dim> trial_space;\n\n  // Geometry description and boundary constraints\n  qdove::TestSpace<dim> test_space;\n\n  // The eigenspectrum system that will be solved by SLEPc\n  qdove::Schroedinger::Problem<dim> schroedinger_problem;\n\n  // The eigenpairs from schroedinger's problem\n  std::vector<dealii::PETScWrappers::Vector> eigenvectors;\n  std::vector<double>                        eigenvalues;\n};\n\ntemplate<int dim>\nSchroedingerProblem<dim>::SchroedingerProblem (dealii::Triangulation<dim> &triangulation)\n  :\n  trial_space (triangulation),\n  test_space (trial_space),\n  schroedinger_problem (trial_space, test_space)\n{}\n\ntemplate<int dim>\nSchroedingerProblem<dim>::~SchroedingerProblem ()\n{}\n\ntemplate<int dim>\nvoid\nSchroedingerProblem<dim>::write_gnuplot (const dealii::PETScWrappers::Vector &vector,\n\t\t\t\t\t const std::string                   &name)\n{\n  // Output a vector to gnuplot style file. \n  std::ostringstream filename;\n  filename << \"solution-\" << name << \".gpl\";\n  std::ofstream output (filename.str ().c_str ());\n\n  dealii::DataOut<dim> data_out;\n  data_out.attach_dof_handler (test_space.dofs ());\n  data_out.add_data_vector (vector, name);\n\n  // generate default patches and output.\n  data_out.build_patches ();\n  data_out.write_gnuplot (output);\n}\n\n\ntemplate<int dim>\nvoid\nSchroedingerProblem<dim>::run ()\n{\n  std::cout << \"Test space:\" << std::endl\n\t    << \"   Finite element type:          \"\n\t    << test_space.fe ().get_name ()\n\t    << std::endl\n\t    << \"   Number of degrees of freedom: \" \n\t    << test_space.n_dofs ()\n\t    << std::endl;\n\n  const double radius = 50e-10;\n\n  dealii::PETScWrappers::Vector material_function (test_space.n_dofs ());\n  for (unsigned int i=0; i<material_function.size (); ++i)\n    material_function[i] = 1.;\n  write_gnuplot (material_function, \"material_function\");\n\n  // Get started on Schroedinger's problem  \n  std::cout << \"Schroedinger's problem:\" \n\t    << std::endl;\n  schroedinger_problem.reinit ();\n\n  // set up the effective mass\n  dealii::PETScWrappers::Vector eff_mass (test_space.n_dofs ());\n  const double ke_term = (qdove::HBAR*qdove::HBAR) / (2.*qdove::mstar_p_CdTe*qdove::M0);\n  std::cout << \"   Kinetic energy term:          \" \n\t    << ke_term << std::endl;\n  eff_mass.add (ke_term, material_function);\n  write_gnuplot (eff_mass, \"effective_mass\");\n\n  // set up the potential\n  dealii::PETScWrappers::Vector potential (test_space.n_dofs ());\n\n  schroedinger_problem.assemble (eff_mass, potential);\n  schroedinger_problem.solve ();\n  schroedinger_problem.get_solution_eigenpairs (eigenvalues, eigenvectors);\n  write_gnuplot (eigenvectors[0], \"electron_function\");\n\n  // output\n  std::cout << \"   Eigenvalues:                  \";\n  for (unsigned int i=0; i<eigenvalues.size (); ++i)\n    std::cout << eigenvalues[i] << \" \";\n  std::cout << std::endl;\n\n  std::cout << \"   Scaled values (eV):           \";\n  for (unsigned int i=0; i<eigenvalues.size (); ++i)\n    std::cout << eigenvalues[i]/(1e-03*qdove::E0) << \" \";\n  std::cout << std::endl;\n\n  std::cout << \"   Scaled analytic values:       \";\n  for (unsigned int i=0; i<eigenvalues.size (); ++i)\n    {\n      // This equation is equation 3.13 in Harrisson's book. It reads:\n      // E_n = (hbar*pi*n)^2 / (2mL^2)\n      const unsigned int n          = i+1;\n      const double L                = 2.*radius;\n      const double analytical_value = (qdove::HBAR*qdove::HBAR*qdove::PI*qdove::PI*n*n) / (2*qdove::mstar_p_CdTe*qdove::M0*L*L);\n      std::cout << analytical_value/(1e-03*qdove::E0) << \" \";\n    }\n  std::cout << std::endl;\n}\n\nint main (int argc, char **argv)\n{\n  try\n    {\n      dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);\n      {\n\t// Create a grid\n\tdealii::Triangulation<1> triangulation;\n\tdealii::GridGenerator::hyper_cube (triangulation, -50e-10, 50e-10);\n\ttriangulation.refine_global (9);\n\n\t// Run Schroedinger's problem on that grid\n\tSchroedingerProblem<1> schroedinger_problem (triangulation);\n\tschroedinger_problem.run ();\n      }\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << 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      \n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << 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": "9966380b58e8db38493dbcb0df06aa4b187da303", "size": 6200, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/step-0/step-0.cc", "max_stars_repo_name": "QuantumDove/QuantumDove", "max_stars_repo_head_hexsha": "6220570364d953fdecd0173a35a6b59976239cbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-09-03T01:56:17.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-03T01:56:17.000Z", "max_issues_repo_path": "examples/step-0/step-0.cc", "max_issues_repo_name": "QuantumDove/QuantumDove", "max_issues_repo_head_hexsha": "6220570364d953fdecd0173a35a6b59976239cbb", "max_issues_repo_licenses": ["MIT"], "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/step-0/step-0.cc", "max_forks_repo_name": "QuantumDove/QuantumDove", "max_forks_repo_head_hexsha": "6220570364d953fdecd0173a35a6b59976239cbb", "max_forks_repo_licenses": ["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.6326530612, "max_line_length": 128, "alphanum_fraction": 0.6229032258, "num_tokens": 1672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5322674759040014}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nnamespace vision_filter {\n/**\n * Abstract class that should be inherited from to create specific\n * kalman filters\n *\n * Must initialize:\n *  x_k1_k1, x_k_k1, x_k_k,\n *  P_k1_k1, P_k_k1, P_k_k,\n *  F_k, B_k, H_k,\n *  Q_k, R_k\n *\n * Every predict, must update:\n *  u_k\n *\n * Every PredictWithUpdate, must update:\n *  u_k, z_k\n *\n * The most recently updated values\n *  x_k_k, P_k_k\n *\n * Taken from https://en.wikipedia.org/wiki/Kalman_filter\n *\n * Conversion between code notation and wiki notation is...\n * x_k1_k1 is X_(k-1, k-1)\n * x_k_k is X_(k, k)\n * etc\n */\nclass KalmanFilter {\npublic:\n    /**\n     * Creates a general kalman filter with the given sizes\n     * Use a child class to setup the specific state matricies\n     * Assumes 1 input\n     *\n     * @param state_size The size of the state vector\n     * @param observation_size The size of the observation vector\n     */\n    KalmanFilter(unsigned int state_size, unsigned int observation_size)\n        : x_k1_k1_(state_size),\n          x_k_k1_(state_size),\n          x_k_k_(state_size),\n          u_k_(1),\n          z_k_(observation_size),\n          y_k_k1_(observation_size),\n          y_k_k_(observation_size),\n          P_k1_k1_(state_size, state_size),\n          P_k_k1_(state_size, state_size),\n          P_k_k_(state_size, state_size),\n          S_k_(observation_size, observation_size),\n          K_k_(state_size, observation_size),\n          F_k_(state_size, state_size),\n          B_k_(state_size, 1),\n          H_k_(observation_size, state_size),\n          Q_k_(state_size, state_size),\n          R_k_(observation_size, observation_size),\n          identity_(Eigen::MatrixXd::Identity(state_size, state_size)) {}\n\n    /**\n     * Predicts without update\n     */\n    void predict();\n\n    /**\n     * Predicts with update\n     * z_k must be set with the observation\n     */\n    void predict_with_update();\n\nprotected:\n    Eigen::VectorXd x_k1_k1_;\n    Eigen::VectorXd x_k_k1_;\n    Eigen::VectorXd x_k_k_;\n\n    Eigen::VectorXd u_k_;\n    Eigen::VectorXd z_k_;\n\n    Eigen::VectorXd y_k_k1_;\n    Eigen::VectorXd y_k_k_;\n\n    // NOLINTNEXTLINE(readability-identifier-naming)\n    Eigen::MatrixXd P_k1_k1_;\n    // NOLINTNEXTLINE(readability-identifier-naming)\n    Eigen::MatrixXd P_k_k1_;\n    // NOLINTNEXTLINE(readability-identifier-naming)\n    Eigen::MatrixXd P_k_k_;\n\n    // NOLINTNEXTLINE(readability-identifier-naming)\n    Eigen::MatrixXd S_k_;\n    // NOLINTNEXTLINE(readability-identifier-naming)\n    Eigen::MatrixXd K_k_;\n\n    // NOLINTNEXTLINE(readability-identifier-naming)\n    Eigen::MatrixXd F_k_;\n    // NOLINTNEXTLINE(readability-identifier-naming)\n    Eigen::MatrixXd B_k_;\n    // NOLINTNEXTLINE(readability-identifier-naming)\n    Eigen::MatrixXd H_k_;\n\n    // NOLINTNEXTLINE(readability-identifier-naming)\n    Eigen::MatrixXd Q_k_;\n    // NOLINTNEXTLINE(readability-identifier-naming)\n    Eigen::MatrixXd R_k_;\n\n    Eigen::MatrixXd identity_;\n};\n}  // namespace vision_filter", "meta": {"hexsha": "03c913c30d479a044b5c3696752aa8de6de5b653", "size": 2988, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "soccer/include/rj_vision_filter/filter/kalman_filter.hpp", "max_stars_repo_name": "xiaoqingyu0113/robocup-software", "max_stars_repo_head_hexsha": "6127d25fc455051ef47610d0e421b2ca7330b4fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 200.0, "max_stars_repo_stars_event_min_datetime": "2015-01-26T01:45:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:05:31.000Z", "max_issues_repo_path": "soccer/include/rj_vision_filter/filter/kalman_filter.hpp", "max_issues_repo_name": "xiaoqingyu0113/robocup-software", "max_issues_repo_head_hexsha": "6127d25fc455051ef47610d0e421b2ca7330b4fa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1254.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T01:57:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T06:32:21.000Z", "max_forks_repo_path": "soccer/include/rj_vision_filter/filter/kalman_filter.hpp", "max_forks_repo_name": "xiaoqingyu0113/robocup-software", "max_forks_repo_head_hexsha": "6127d25fc455051ef47610d0e421b2ca7330b4fa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 206.0, "max_forks_repo_forks_event_min_datetime": "2015-01-21T02:03:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T17:57:46.000Z", "avg_line_length": 27.1636363636, "max_line_length": 73, "alphanum_fraction": 0.6696787149, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5322674717986203}}
{"text": "#include <iostream>\n#include <boost/program_options.hpp>\n#include \"vptree.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\n/* Functions taken from Laurens van der Maaten's original implementation of t-SNE */\n/* Source: https://github.com/lvdmaaten/bhtsne                                    */\nstatic void computeGaussianPerplexity(double* X, int N, int D, unsigned int** _row_P, unsigned int** _col_P, double** _val_P, double perplexity, int K);\nstatic void symmetrizeMatrix(unsigned int** _row_P, unsigned int** _col_P, double** _val_P, int N);\nstatic void computeSquaredEuclideanDistance(double* X, int N, int D, double* DD);\nstatic void zeroMean(double* X, int N, int D);\n/**********************************************************************************/\n\nstatic bool load_data(string infile, double **data, int &num_instances, int &num_features) {\n\n  FILE *fp = fopen(infile.c_str(), \"rb\");\n\tif (fp == NULL) {\n\t\tcout << \"Error: could not open data file \" << infile << endl;\n\t\treturn false;\n\t}\n\n  uint64_t ret;\n\tret = fread(&num_instances, sizeof(int), 1, fp);\n\tret = fread(&num_features, sizeof(int), 1, fp);\n\n\t*data = (double *)malloc(num_instances * num_features * sizeof(double));\n  if (*data == NULL) {\n    cout << \"Error: memory allocation of \" << num_instances << \" by \" \n         << num_features << \" matrix failed\" << endl;\n    return false;\n  }\n\n  uint64_t nelem = (uint64_t)num_instances * num_features;\n\n  size_t batch_size = 1e8;\n  double *ptr = *data;\n  ret = 0;\n  for (uint64_t remaining = nelem; remaining > 0; remaining -= batch_size) {\n    if (remaining < batch_size) {\n      batch_size = remaining;\n    }\n    ret += fread(ptr, sizeof(double), batch_size, fp);\n    ptr += batch_size;\n  }\n  \n  if (ret != nelem) {\n    cout << \"Error: reading input returned incorrect number of elements (\" << ret\n         << \", expected \" << nelem << \")\" << endl;\n    return false;\n  }\n  \n\tfclose(fp);\n\n\treturn true;\n}\n\nstatic void truncate_data(double *X, int num_instances, int num_features, int target_dims) {\n  size_t i_old = 0;\n  size_t i_new = 0;\n  for (int r = 0; r < num_instances; r++) {\n    for (int c = 0; c < num_features; c++) {\n      if (c < target_dims) {\n        X[i_new++] = X[i_old];\n      }\n      i_old++;\n    }\n  }\n}\n\nstatic bool run(double *X, int num_instances, int num_features, double perplexity, string outfile) {\n\n  // Apply lower bound on perplexity from original t-SNE implementation\n  if (num_instances - 1 < 3 * perplexity) {\n    cout << \"Error: target perplexity (\" << perplexity << \") is too large \"\n         << \"for the number of data points (\" << num_instances << \")\" << endl;\n    return false;\n  }\n\n  printf(\"Processing %d data points, %d features with target perplexity %f\\n\",\n         num_instances, num_features, perplexity);\n\n  // Normalize input data (to prevent numerical problems)\n  zeroMean(X, num_instances, num_features);\n  cout << \"Normalizing the features\" << endl;\n  double max_X = 0;\n  for (size_t i = 0; i < num_instances * num_features; i++) {\n    if (fabs(X[i]) > max_X) {\n      max_X = fabs(X[i]);\n    }\n  }\n\n  for (size_t i = 0; i < num_instances * num_features; i++) {\n    X[i] /= max_X;\n  }\n\n  // Compute input similarities for exact t-SNE\n  double* P; unsigned int* row_P; unsigned int* col_P; double* val_P;\n\n  // Compute asymmetric pairwise input similarities\n  cout << \"Computing conditional distributions\" << endl;\n  computeGaussianPerplexity(X, num_instances, num_features,\n    &row_P, &col_P, &val_P, perplexity, (int) (3 * perplexity));\n\n  // Symmetrize input similarities\n  cout << \"Symmetrizing matrix\" << endl;\n  symmetrizeMatrix(&row_P, &col_P, &val_P, num_instances);\n  double sum_P = .0;\n  for (int i = 0; i < row_P[num_instances]; i++) {\n    sum_P += val_P[i];\n  }\n  for (int i = 0; i < row_P[num_instances]; i++) {\n    val_P[i] /= sum_P;\n  }\n\n  cout << \"Saving to \" << outfile << endl;\n\tFILE *fp = fopen(outfile.c_str(), \"wb\");\n\tif (fp == NULL) {\n\t\tcout << \"Error: could not open output file \" << outfile << endl;\n    return false;\n\t}\n\n\tfwrite(&num_instances, sizeof(int), 1, fp);\n  fwrite(row_P, sizeof(unsigned int), num_instances + 1, fp);\n\tfwrite(col_P, sizeof(unsigned int), row_P[num_instances], fp);\n  fwrite(val_P, sizeof(double), row_P[num_instances], fp);\n\n  free(row_P);\n  free(col_P);\n  free(val_P);\n\n  return true;\n}\n\nint main(int argc, char **argv) {\n  // Declare the supported options.\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help\", \"produce help message\")\n    (\"input-file\", po::value<string>()->value_name(\"FILE\")->default_value(\"data.dat\"), \"name of binary input file (see prepare_input.m)\")\n    (\"output-file\", po::value<string>()->value_name(\"FILE\")->default_value(\"P.dat\"), \"name of output file to be created\")\n    (\"perp\", po::value<double>()->value_name(\"NUM\")->default_value(30, \"30\"), \"set target perplexity for conditional distributions\")\n    (\"num-dims\", po::value<int>()->value_name(\"NUM\"), \"if provided, only the first NUM features in the input will be used\")\n  ;\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).\n                options(desc).run(), vm);\n  po::notify(vm);    \n  \n  if (vm.count(\"help\")) {\n    cout << \"Usage: ComputeP [options]\" << endl;\n    cout << desc << \"\\n\";\n    return 1;\n  }\n\n\tdouble perplexity = vm[\"perp\"].as<double>();\n  string infile = vm[\"input-file\"].as<string>();\n  string outfile = vm[\"output-file\"].as<string>();\n\n  double *data;\n  int num_instances;\n  int num_features;\n\n\tif (!load_data(infile, &data, num_instances, num_features)) {\n    return 1;\n  }\n\n  cout << infile << \" successfully loaded\" << endl;\n\n  if (vm.count(\"num-dims\")) {\n    int num_dims = vm[\"num-dims\"].as<int>();\n    cout << \"Using only the first \" << num_dims << \" dimensions\" << endl;\n    truncate_data(data, num_instances, num_features, num_dims);\n    num_features = num_dims;\n  }\n  \n  if (!run(data, num_instances, num_features, perplexity, outfile)) {\n    return 1;\n  }\n\n  cout << \"Done\" << endl;\n\n  return 0;\n}\n\n// Compute input similarities with a fixed perplexity using ball trees (this function allocates memory another function should free)\n// Source: https://github.com/lvdmaaten/bhtsne\nstatic void computeGaussianPerplexity(double* X, int N, int D, unsigned int** _row_P, unsigned int** _col_P, double** _val_P, double perplexity, int K) {\n\n    if(perplexity > K) printf(\"Perplexity should be lower than K!\\n\");\n\n    // Allocate the memory we need\n    *_row_P = (unsigned int*)    malloc((N + 1) * sizeof(unsigned int));\n    *_col_P = (unsigned int*)    calloc(N * K, sizeof(unsigned int));\n    *_val_P = (double*) calloc(N * K, sizeof(double));\n    if(*_row_P == NULL || *_col_P == NULL || *_val_P == NULL) { printf(\"Memory allocation failed!\\n\"); exit(1); }\n    unsigned int* row_P = *_row_P;\n    unsigned int* col_P = *_col_P;\n    double* val_P = *_val_P;\n    double* cur_P = (double*) malloc((N - 1) * sizeof(double));\n    if(cur_P == NULL) { printf(\"Memory allocation failed!\\n\"); exit(1); }\n    row_P[0] = 0;\n    for(int n = 0; n < N; n++) row_P[n + 1] = row_P[n] + (unsigned int) K;\n\n    // Build ball tree on data set\n    VpTree<DataPoint, euclidean_distance>* tree = new VpTree<DataPoint, euclidean_distance>();\n    vector<DataPoint> obj_X(N, DataPoint(D, -1, X));\n    for(int n = 0; n < N; n++) obj_X[n] = DataPoint(D, n, X + n * D);\n    tree->create(obj_X);\n\n    // Loop over all points to find nearest neighbors\n    printf(\"Building tree...\\n\");\n    vector<DataPoint> indices;\n    vector<double> distances;\n    for(int n = 0; n < N; n++) {\n\n        if(n % 10000 == 0) printf(\" - point %d of %d\\n\", n, N);\n\n        // Find nearest neighbors\n        indices.clear();\n        distances.clear();\n        tree->search(obj_X[n], K + 1, &indices, &distances);\n\n        // Initialize some variables for binary search\n        bool found = false;\n        double beta = 1.0;\n        double min_beta = -DBL_MAX;\n        double max_beta =  DBL_MAX;\n        double tol = 1e-5;\n\n        // Iterate until we found a good perplexity\n        int iter = 0; double sum_P;\n        while(!found && iter < 200) {\n\n            // Compute Gaussian kernel row\n            for(int m = 0; m < K; m++) cur_P[m] = exp(-beta * distances[m + 1] * distances[m + 1]);\n\n            // Compute entropy of current row\n            sum_P = DBL_MIN;\n            for(int m = 0; m < K; m++) sum_P += cur_P[m];\n            double H = .0;\n            for(int m = 0; m < K; m++) H += beta * (distances[m + 1] * distances[m + 1] * cur_P[m]);\n            H = (H / sum_P) + log(sum_P);\n\n            // Evaluate whether the entropy is within the tolerance level\n            double Hdiff = H - log(perplexity);\n            if(Hdiff < tol && -Hdiff < tol) {\n                found = true;\n            }\n            else {\n                if(Hdiff > 0) {\n                    min_beta = beta;\n                    if(max_beta == DBL_MAX || max_beta == -DBL_MAX)\n                        beta *= 2.0;\n                    else\n                        beta = (beta + max_beta) / 2.0;\n                }\n                else {\n                    max_beta = beta;\n                    if(min_beta == -DBL_MAX || min_beta == DBL_MAX)\n                        beta /= 2.0;\n                    else\n                        beta = (beta + min_beta) / 2.0;\n                }\n            }\n\n            // Update iteration counter\n            iter++;\n        }\n\n        // Row-normalize current row of P and store in matrix\n        for(unsigned int m = 0; m < K; m++) cur_P[m] /= sum_P;\n        for(unsigned int m = 0; m < K; m++) {\n            col_P[row_P[n] + m] = (unsigned int) indices[m + 1].index();\n            val_P[row_P[n] + m] = cur_P[m];\n        }\n    }\n\n    // Clean up memory\n    obj_X.clear();\n    free(cur_P);\n    delete tree;\n}\n\n// Symmetrizes a sparse matrix\n// Source: https://github.com/lvdmaaten/bhtsne\nstatic void symmetrizeMatrix(unsigned int** _row_P, unsigned int** _col_P, double** _val_P, int N) {\n\n    // Get sparse matrix\n    unsigned int* row_P = *_row_P;\n    unsigned int* col_P = *_col_P;\n    double* val_P = *_val_P;\n\n    // Count number of elements and row counts of symmetric matrix\n    int* row_counts = (int*) calloc(N, sizeof(int));\n    if(row_counts == NULL) { printf(\"Memory allocation failed!\\n\"); exit(1); }\n    for(int n = 0; n < N; n++) {\n        for(int i = row_P[n]; i < row_P[n + 1]; i++) {\n\n            // Check whether element (col_P[i], n) is present\n            bool present = false;\n            for(int m = row_P[col_P[i]]; m < row_P[col_P[i] + 1]; m++) {\n                if(col_P[m] == n) present = true;\n            }\n            if(present) row_counts[n]++;\n            else {\n                row_counts[n]++;\n                row_counts[col_P[i]]++;\n            }\n        }\n    }\n    int no_elem = 0;\n    for(int n = 0; n < N; n++) no_elem += row_counts[n];\n\n    // Allocate memory for symmetrized matrix\n    unsigned int* sym_row_P = (unsigned int*) malloc((N + 1) * sizeof(unsigned int));\n    unsigned int* sym_col_P = (unsigned int*) malloc(no_elem * sizeof(unsigned int));\n    double* sym_val_P = (double*) malloc(no_elem * sizeof(double));\n    if(sym_row_P == NULL || sym_col_P == NULL || sym_val_P == NULL) { printf(\"Memory allocation failed!\\n\"); exit(1); }\n\n    // Construct new row indices for symmetric matrix\n    sym_row_P[0] = 0;\n    for(int n = 0; n < N; n++) sym_row_P[n + 1] = sym_row_P[n] + (unsigned int) row_counts[n];\n\n    // Fill the result matrix\n    int* offset = (int*) calloc(N, sizeof(int));\n    if(offset == NULL) { printf(\"Memory allocation failed!\\n\"); exit(1); }\n    for(int n = 0; n < N; n++) {\n        for(unsigned int i = row_P[n]; i < row_P[n + 1]; i++) {                                  // considering element(n, col_P[i])\n\n            // Check whether element (col_P[i], n) is present\n            bool present = false;\n            for(unsigned int m = row_P[col_P[i]]; m < row_P[col_P[i] + 1]; m++) {\n                if(col_P[m] == n) {\n                    present = true;\n                    if(n <= col_P[i]) {                                                 // make sure we do not add elements twice\n                        sym_col_P[sym_row_P[n]        + offset[n]]        = col_P[i];\n                        sym_col_P[sym_row_P[col_P[i]] + offset[col_P[i]]] = n;\n                        sym_val_P[sym_row_P[n]        + offset[n]]        = val_P[i] + val_P[m];\n                        sym_val_P[sym_row_P[col_P[i]] + offset[col_P[i]]] = val_P[i] + val_P[m];\n                    }\n                }\n            }\n\n            // If (col_P[i], n) is not present, there is no addition involved\n            if(!present) {\n                sym_col_P[sym_row_P[n]        + offset[n]]        = col_P[i];\n                sym_col_P[sym_row_P[col_P[i]] + offset[col_P[i]]] = n;\n                sym_val_P[sym_row_P[n]        + offset[n]]        = val_P[i];\n                sym_val_P[sym_row_P[col_P[i]] + offset[col_P[i]]] = val_P[i];\n            }\n\n            // Update offsets\n            if(!present || (present && n <= col_P[i])) {\n                offset[n]++;\n                if(col_P[i] != n) offset[col_P[i]]++;\n            }\n        }\n    }\n\n    // Divide the result by two\n    for(int i = 0; i < no_elem; i++) sym_val_P[i] /= 2.0;\n\n    // Return symmetrized matrices\n    free(*_row_P); *_row_P = sym_row_P;\n    free(*_col_P); *_col_P = sym_col_P;\n    free(*_val_P); *_val_P = sym_val_P;\n\n    // Free up some memery\n    free(offset); offset = NULL;\n    free(row_counts); row_counts  = NULL;\n}\n\n// Compute squared Euclidean distance matrix\n// Source: https://github.com/lvdmaaten/bhtsne\nstatic void computeSquaredEuclideanDistance(double* X, int N, int D, double* DD) {\n    const double* XnD = X;\n    for(int n = 0; n < N; ++n, XnD += D) {\n        const double* XmD = XnD + D;\n        double* curr_elem = &DD[n*N + n];\n        *curr_elem = 0.0;\n        double* curr_elem_sym = curr_elem + N;\n        for(int m = n + 1; m < N; ++m, XmD+=D, curr_elem_sym+=N) {\n            *(++curr_elem) = 0.0;\n            for(int d = 0; d < D; ++d) {\n                *curr_elem += (XnD[d] - XmD[d]) * (XnD[d] - XmD[d]);\n            }\n            *curr_elem_sym = *curr_elem;\n        }\n    }\n}\n\n// Makes data zero-mean\n// Source: https://github.com/lvdmaaten/bhtsne\nstatic void zeroMean(double* X, int N, int D) {\n\n\t// Compute data mean\n\tdouble* mean = (double*) calloc(D, sizeof(double));\n    if(mean == NULL) { printf(\"Memory allocation failed!\\n\"); exit(1); }\n    int nD = 0;\n\tfor(int n = 0; n < N; n++) {\n\t\tfor(int d = 0; d < D; d++) {\n\t\t\tmean[d] += X[nD + d];\n\t\t}\n        nD += D;\n\t}\n\tfor(int d = 0; d < D; d++) {\n\t\tmean[d] /= (double) N;\n\t}\n\n\t// Subtract data mean\n    nD = 0;\n\tfor(int n = 0; n < N; n++) {\n\t\tfor(int d = 0; d < D; d++) {\n\t\t\tX[nD + d] -= mean[d];\n\t\t}\n        nD += D;\n\t}\n    free(mean); mean = NULL;\n}\n", "meta": {"hexsha": "e6c8b9295ce417d786e22cf604c96f46f74cd759", "size": 14839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ComputeP.cpp", "max_stars_repo_name": "hhcho/netsne", "max_stars_repo_head_hexsha": "d928b7f514efe68e91984ba0a51428a30beed647", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-04-15T18:25:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-05T13:30:37.000Z", "max_issues_repo_path": "ComputeP.cpp", "max_issues_repo_name": "hhcho/netsne", "max_issues_repo_head_hexsha": "d928b7f514efe68e91984ba0a51428a30beed647", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-24T01:38:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-06T00:48:47.000Z", "max_forks_repo_path": "ComputeP.cpp", "max_forks_repo_name": "hhcho/netsne", "max_forks_repo_head_hexsha": "d928b7f514efe68e91984ba0a51428a30beed647", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-23T13:10:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-28T18:00:59.000Z", "avg_line_length": 35.0803782506, "max_line_length": 153, "alphanum_fraction": 0.5578543029, "num_tokens": 4137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5322287529308658}}
{"text": "// Copyright (c) 2006-2007 Michael B. Edwin Rickert\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// $LastChangedBy$ - $LastChangedDate$\n//\n// Dec 25, 2006 - industry.math.vector.hpp => industry/math/vector.hpp\n// Dec  1, 2006 - Created\n\n#ifndef BOOST_PP_IS_ITERATING\n\t#ifndef IG_INDUSTRY_MATH_VECTOR\n\t#define IG_INDUSTRY_MATH_VECTOR\n\n\t#ifndef INDUSTRY_MATH_VECTOR_DN_LIMIT\n\t#define INDUSTRY_MATH_VECTOR_DN_LIMIT 3\n\t#endif //ndef  INDUSTRY_MATH_VECTOR_DN_LIMIT\n\n\t#include <boost/preprocessor/iteration.hpp>\n\t#include <boost/preprocessor/repetition.hpp>\n\t#include <boost/static_assert.hpp>\n\t#include <cassert>\n\t#include <cmath>\n\t#include <numeric>\n\nnamespace industry {\n\tnamespace math {\n\t\ttemplate < typename T , unsigned Dn >\n\t\tclass vector;\n\t\t\n\t\ttemplate < typename T , unsigned Dn >\n\t\tstruct vector_base;\n\t\t\n\t\ttemplate < typename T >\n\t\tstruct vector_base< T , 0 >; //no implementation\n\t\t\n\t\ttemplate < typename T >\n\t\tstruct vector_base< T , 1 > {\n\t\t\tT x;\n\t\t\t      T & operator[]( unsigned n )       { assert(n<1); return x; }\n\t\t\tconst T & operator[]( unsigned n ) const { assert(n<1); return x; }\n\t\t};\n\t\ttemplate < typename T >\n\t\tstruct vector_base< T , 2 > {\n\t\t\tT x,y;\n\t\t\t      T & operator[]( unsigned n )       { assert(n<2); return *(&x+n); }\n\t\t\tconst T & operator[]( unsigned n ) const { assert(n<2); return *(&x+n); }\n\t\t};\n\t\ttemplate < typename T >\n\t\tstruct vector_base< T , 3 > {\n\t\t\tT x,y,z;\n\t\t\t      T & operator[]( unsigned n )       { assert(n<3); return *(&x+n); }\n\t\t\tconst T & operator[]( unsigned n ) const { assert(n<3); return *(&x+n); }\n\t\t};\n\t\ttemplate < typename T , unsigned Dn >\n\t\tstruct vector_base {\n\t\t\tBOOST_STATIC_ASSERT(( Dn > 3 ));\n\t\t\tT x,y,z;\n\t\tprotected:\n\t\t\tT etc[ Dn-3 ];\n\t\t\t      T & operator[]( unsigned n )       { assert(n<Dn); return (n<=3) ? *(&x+n) : (etc[n-3]); }\n\t\t\tconst T & operator[]( unsigned n ) const { assert(n<Dn); return (n<=3) ? *(&x+n) : (etc[n-3]); }\n\t\t};\n\t\t\n\t\t#define BOOST_PP_ITERATION_LIMITS (1,INDUSTRY_MATH_VECTOR_DN_LIMIT)\n\t\t#define BOOST_PP_FILENAME_1 <industry/math/vector.hpp>\n\t\t#include BOOST_PP_ITERATE()\n\t\t\n\t\ttemplate < typename T , unsigned N >\n\t\tbool operator==( const vector<T,N> & lhs , const vector<T,N> & rhs ) {\n\t\t\tfor ( unsigned i = 0 ; i < N ; ++i ) {\n\t\t\t\tif ( lhs[i] != rhs[i] ) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\ttemplate < typename T , unsigned N >\n\t\tbool operator!=( const vector<T,N> & lhs , const vector<T,N> & rhs ) {\n\t\t\treturn !(lhs==rhs);\n\t\t}\n\t}\n}\n\t\n\t#endif //ndef IG_INDUSTRY_MATH_VECTOR\n\t\n#else //BOOST_PP_IS_ITERATING\n\t#define DN                                             BOOST_PP_ITERATION()\n\t#define INDUSTRY_MATH_VECTOR_FILL_THIS_ARGS(z,n,src)   (*this)[n]  = src ## n;\n\ntemplate < typename T >\nclass vector< T , DN > : public vector_base< T , DN > {\npublic:\n\tvector() { std::fill_n(&(*this)[0], DN, T()); }\n\tvector( BOOST_PP_ENUM_PARAMS(DN,T elem) ) { BOOST_PP_REPEAT(DN,INDUSTRY_MATH_VECTOR_FILL_THIS_ARGS,elem); }\n\t\n\tvector& operator+=( const vector & other ) { for ( unsigned i = 0 ; i < DN ; ++i ) (*this)[i] += other[i]; return *this; }\n\tvector& operator-=( const vector & other ) { for ( unsigned i = 0 ; i < DN ; ++i ) (*this)[i] -= other[i]; return *this; }\n\tvector& operator*=( const T &      value ) { for ( unsigned i = 0 ; i < DN ; ++i ) (*this)[i] *= value; return *this; }\n\tvector& operator/=( const T &      value ) { for ( unsigned i = 0 ; i < DN ; ++i ) (*this)[i] /= value; return *this; }\n\t\n\tfriend vector operator+( const vector & lhs , const vector & rhs ) { vector c(lhs); c += rhs; return c; }\n\tfriend vector operator-( const vector & lhs , const vector & rhs ) { vector c(lhs); c -= rhs; return c; }\n\tfriend vector operator*( const vector & lhs , const T      & rhs ) { vector c(lhs); c *= rhs; return c; }\n\tfriend vector operator/( const vector & lhs , const T      & rhs ) { vector c(lhs); c /= rhs; return c; }\n\t\n\tfriend T square_magnitude( const vector & v ) { return std::inner_product(&v[0], &v[0] + DN, &v[0], T()); }\n\tfriend T magnitude ( const vector & v ) { return T( std::sqrt( square_magnitude( v ) ) ); }\n\t\n\ttemplate < typename U > friend U square_magnitude( const vector & v ) { return static_cast<U>(square_magnitude(v)); }\n\ttemplate < typename U > friend U magnitude ( const vector & v ) { return U( std::sqrt( square_magnitude/*<U>*/(v) ) ); }\n};\n\n\n\t#undef DN\n\t#undef INDUSTRY_MATH_VECTOR_FILL_THIS_ARGS\n#endif //BOOST_PP_IS_ITERATING\n", "meta": {"hexsha": "e44e14c1d183dc414478049662625a3e53ab4ef8", "size": 4489, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "industry/math/vector.hpp", "max_stars_repo_name": "MaulingMonkey/libindustry", "max_stars_repo_head_hexsha": "575c61caaa6a43822b7a74a95345563e8da20201", "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": "industry/math/vector.hpp", "max_issues_repo_name": "MaulingMonkey/libindustry", "max_issues_repo_head_hexsha": "575c61caaa6a43822b7a74a95345563e8da20201", "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": "industry/math/vector.hpp", "max_forks_repo_name": "MaulingMonkey/libindustry", "max_forks_repo_head_hexsha": "575c61caaa6a43822b7a74a95345563e8da20201", "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.3675213675, "max_line_length": 123, "alphanum_fraction": 0.6241924705, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835534888481, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5322287518542946}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_ENERGYMODEL_HPP\n#define MCL_ENERGYMODEL_HPP 1\n\n#include <memory>\n#include <Eigen/Dense>\n#include \"MCL/Lame.hpp\"\n#include \"MCL/XuSpline.hpp\"\n\nnamespace mcl\n{\n\nenum\n{\n\tENERGY_MODEL_INVALID = -1,\n\tENERGY_MODEL_ARAP,\n\tENERGY_MODEL_XUSPLINE_NH, // Xu spline (neo-Hookean)\n\tENERGY_MODEL_XUSPLINE_STVK, // Xu spline (St. VK)\n\tENERGY_MODEL_XUSPLINE_COROTATE, // Xu spline (CR)\n\tENERGY_MODEL_STABLE_NH, // Stable neo-Hookean\n\tENERGY_MODEL_NH, // iso log-barrier neo-Hookean\n\tENERGY_MODEL_SYMM_DIR, // Symmetric Dirichlet\n\tENERGY_MODEL_NUM\n};\n\n// Nonlinear Material Design Using Principal Stretches, Xu et al. 2015.\ntemplate <int DIM>\nclass XuSplineModel\n{\nprotected:\ntypedef Eigen::Matrix<double,DIM,1> VecD;\ntypedef Eigen::Matrix<double,DIM,DIM> MatD;\npublic:\n\tstatic double energy_density(const XuSpline<double> *s, const VecD &x);\n\tstatic double gradient(const XuSpline<double> *s, const VecD &x, VecD &g);\n\tstatic void hessian(const XuSpline<double> *s, const VecD &x, MatD &H);\n};\n\n// Simplified stable Neo-Hookean (similar to Smith et al. '17)\ntemplate <int DIM>\nclass StableNeoHookean\n{\nprotected:\ntypedef Eigen::Matrix<double,DIM,1> VecD;\ntypedef Eigen::Matrix<double,DIM,DIM> MatD;\npublic:\n\tstatic double energy_density(const Lame &lame, const VecD &x);\n\tstatic double gradient(const Lame &lame, const VecD &x, VecD &g);\n\tstatic void hessian(const Lame &lame, const VecD &x, MatD &H);\n};\n\n// Classic (isotropic) Neo-Hookean\ntemplate <int DIM>\nclass IsoNeoHookean\n{\nprotected:\ntypedef Eigen::Matrix<double,DIM,1> VecD;\ntypedef Eigen::Matrix<double,DIM,DIM> MatD;\npublic:\n\tstatic double energy_density(const Lame &lame, const VecD &x);\n\tstatic double gradient(const Lame &lame, const VecD &x, VecD &g);\n\tstatic void hessian(const Lame &lame, const VecD &x, MatD &H);\n};\n\n// SLIM Symmetric Dirichlet\n// f(x) = (||F||^2 + ||F^-1||^2)/2\ntemplate <int DIM>\nclass SymmDirichlet\n{\nprotected:\ntypedef Eigen::Matrix<double,DIM,1> VecD;\ntypedef Eigen::Matrix<double,DIM,DIM> MatD;\npublic:\n\tstatic double energy_density(const VecD &x);\n\tstatic double gradient(const VecD &x, VecD &g);\n\tstatic void hessian(const VecD &x, MatD &H);\n};\n\n//\n//\tImplementation\n//\n\n//================================================\n//\tXuSpline\n//================================================\n\ntemplate <int DIM>\ndouble XuSplineModel<DIM>::energy_density(const XuSpline<double> *s, const VecD &x)\n{\n\tif (DIM==3)\n\t{\n\t\treturn s->f(x[0]) + s->f(x[1]) + s->f(x[2]) +\n\t\t\ts->g(x[0]*x[1]) + s->g(x[1]*x[2]) + s->g(x[2]*x[0]) +\n\t\t\ts->h(x[0]*x[1]*x[2]);\n\t}\n\treturn s->f(x[0]) + s->f(x[1]) + s->g(x[0]*x[1]) + s->h(x[0]*x[1]);\n}\n\ntemplate <int DIM>\ndouble XuSplineModel<DIM>::gradient(const XuSpline<double> *s, const VecD &x, VecD &g)\n{\n\tif (g.size() != x.size()) { g.resize(x.size()); }\n\tif (DIM==3)\n\t{\n\t\tdouble hprime = s->dh(x[0]*x[1]*x[2]);\n\t\tg[0] = s->df(x[0]) + s->dg(x[0]*x[1])*x[1] + s->dg(x[2]*x[0])*x[2] + hprime*x[1]*x[2];\n\t\tg[1] = s->df(x[1]) + s->dg(x[1]*x[2])*x[2] + s->dg(x[0]*x[1])*x[0] + hprime*x[2]*x[0];\n\t\tg[2] = s->df(x[2]) + s->dg(x[2]*x[0])*x[0] + s->dg(x[1]*x[2])*x[1] + hprime*x[0]*x[1];\n\t\treturn energy_density(s, x);\n\t}\n\tdouble hprime = s->dh(x[0]*x[1]);\n\tg[0] = s->df(x[0]) + s->dg(x[0]*x[1])*x[1] + hprime*x[1];\n\tg[1] = s->df(x[1]) + s->dg(x[0]*x[1])*x[0] + hprime*x[0];\n\treturn energy_density(s, x);\n}\n\ntemplate <int DIM>\nvoid XuSplineModel<DIM>::hessian(const XuSpline<double> *s, const VecD &x, MatD &H)\n{\n\tif (DIM==3)\n\t{\n\t\tdouble hprime = s->dh(x[0]*x[1]*x[2]);\n\t\tdouble hprimeprime = s->ddh(x[0]*x[1]*x[2]);\n\t\tH(0,0) = s->ddf(x[0]) + s->ddg(x[0]*x[1])*x[1]*x[1] + s->ddg(x[2]*x[0])*x[2]*x[2] + hprimeprime*x[1]*x[1]*x[2]*x[2];\n\t\tH(1,1) = s->ddf(x[1]) + s->ddg(x[1]*x[2])*x[2]*x[2] + s->ddg(x[0]*x[1])*x[0]*x[0] + hprimeprime*x[2]*x[2]*x[0]*x[0];\n\t\tH(2,2) = s->ddf(x[2]) + s->ddg(x[2]*x[0])*x[0]*x[0] + s->ddg(x[1]*x[2])*x[1]*x[1] + hprimeprime*x[0]*x[0]*x[1]*x[1];\n\t\tH(0,1) = s->ddg(x[0]*x[1])*x[0]*x[1] + s->dg(x[0]*x[1]) + hprimeprime*x[0]*x[1]*x[2]*x[2] + hprime*x[2];\n\t\tH(1,0) = H(0,1);\n\t\tH(0,2) = s->ddg(x[0]*x[2])*x[0]*x[2] + s->dg(x[0]*x[2]) + hprimeprime*x[0]*x[2]*x[1]*x[1] + hprime*x[1];\n\t\tH(2,0) = H(0,2);\n\t\tH(1,2) = s->ddg(x[1]*x[2])*x[1]*x[2] + s->dg(x[1]*x[2]) + hprimeprime*x[1]*x[2]*x[0]*x[0] + hprime*x[0];\n\t\tH(2,1) = H(1,2);\n\t\treturn;\n\t}\n\tdouble hprimeprime = s->ddh(x[0]*x[1]);\n\tH(0,0) = s->ddf(x[0]) + s->ddg(x[0]*x[1])*x[1]*x[1] + hprimeprime*x[1]*x[1];\n\tH(1,1) = s->ddf(x[1]) + s->ddg(x[0]*x[1])*x[0]*x[0] + hprimeprime*x[0]*x[0];\n\tH(0,1) = s->ddg(x[0]*x[1])*x[0]*x[1] + s->dg(x[0]*x[1]) + hprimeprime*x[0]*x[1];\n\tH(1,0) = H(0,1);\n}\n\n//================================================\n//\tStable Neo-Hookean\n//================================================\n\ntemplate <int DIM>\ndouble StableNeoHookean<DIM>::energy_density(const Lame &lame, const VecD &x)\n{\n\tif (!x.allFinite() || x.minCoeff() <= 0)\n\t\treturn std::numeric_limits<float>::max();\n\n\tdouble alpha = 1.0 + lame.mu()/lame.lambda();\n\tconstexpr double d = double(DIM);\n\tdouble I_1 = x.squaredNorm();\n\tdouble J = x.prod();\n\treturn 0.5*lame.lambda()*(J-alpha)*(J-alpha) + 0.5*lame.mu()*(I_1-d);\n}\n\ntemplate <int DIM>\ndouble StableNeoHookean<DIM>::gradient(const Lame &lame, const VecD &x, VecD &grad)\n{\n\tdouble alpha = 1.0 + lame.mu()/lame.lambda();\n\tdouble J = x.prod();\n\tVecD x_inv = x.cwiseInverse();\n\tgrad = lame.mu()*x + lame.lambda()*(J-alpha)*J*x_inv;\n\treturn energy_density(lame, x);\n}\n\ntemplate <int DIM>\nvoid StableNeoHookean<DIM>::hessian(const Lame &lame, const VecD &x, MatD &hess)\n{\n\tdouble alpha = 1.0 + lame.mu()/lame.lambda();\n\tdouble J = x.prod();\n\tif(DIM == 3)\n\t{\n\t\tVecD coeffs;\n\t\tcoeffs[0] = x[1]*x[2];\n\t\tcoeffs[1] = x[0]*x[2];\n\t\tcoeffs[2] = x[0]*x[1];\n\t\tMatD coeffsMat;\n\t\tcoeffsMat.setZero();\n\t\tcoeffsMat(0,1) = x[2];\n\t\tcoeffsMat(1,0) = x[2];\n\t\tcoeffsMat(0,2) = x[1];\n\t\tcoeffsMat(2,0) = x[1];\n\t\tcoeffsMat(1,2) = x[0];\n\t\tcoeffsMat(2,1) = x[0];\n\t\thess = lame.mu()*MatD::Identity() +\n\t\t\tlame.lambda()*coeffs*coeffs.transpose() +\n\t\t\tlame.lambda()*(J-alpha)*coeffsMat;\n\t\treturn;\n\t}\n\thess(0,0) = lame.lambda()*x[1]*x[1] + lame.mu();\n\thess(1,1) = lame.lambda()*x[0]*x[0] + lame.mu();\n\thess(0,1) = lame.lambda()*(J-alpha) + lame.lambda()*J;\n\thess(1,0) = hess(0,1);\n}\n\n//================================================\n//\tIsotropic Neo-Hookean\n//================================================\n\ntemplate <int DIM>\ndouble IsoNeoHookean<DIM>::energy_density(const Lame &lame, const VecD &x)\n{\n\tif (!x.allFinite() || x.minCoeff() <= 0)\n\t\treturn std::numeric_limits<float>::max();\n\n\tdouble J = x.prod();\n\tdouble I_1 = x.squaredNorm();\n\tdouble I_3 = J*J;\n\tdouble log_I3 = std::log( I_3 );\n\tdouble t1 = 0.5 * lame.mu() * ( I_1 - log_I3 - 3.0 );\n\tdouble t2 = 0.125 * lame.lambda() * log_I3 * log_I3;\n\tdouble r = t1 + t2;\n\treturn r;\n}\n\ntemplate <int DIM>\ndouble IsoNeoHookean<DIM>::gradient(const Lame &lame, const VecD &x, VecD &grad)\n{\n\tdouble J = x.prod();\n\tVecD x_inv = x.cwiseInverse();\n\tgrad = (lame.mu() * (x - x_inv) + lame.lambda() * std::log(J) * x_inv);\n\treturn energy_density(lame, x);\n}\n\ntemplate <int DIM>\nvoid IsoNeoHookean<DIM>::hessian(const Lame &lame, const VecD &x, MatD &hess)\n{\n\tstatic const MatD Iden = MatD::Identity();\n\tdouble J = x.prod();\n\tVecD x_inv = x.cwiseInverse();\n\tMatD invXmat;\n\tinvXmat.setZero();\n\tinvXmat(0,0) = 1.0 / (x[0]*x[0]);\n\tinvXmat(1,1) = 1.0 / (x[1]*x[1]);\n\tif(DIM == 3){ invXmat(2,2) = 1.0 / (x[2]*x[2]); }\n\thess = lame.mu()*(Iden - 2.0*invXmat) +\n\t\tlame.lambda()*std::log(J)*invXmat +\n\t\tlame.lambda() * x_inv * x_inv.transpose();\n}\n\n//================================================\n//\tSymmetric Dirichlet\n//================================================\n\ntemplate <int DIM>\ndouble SymmDirichlet<DIM>::energy_density(const VecD &x)\n{\n\tdouble e = 0;\n\tfor (int i=0; i<DIM; ++i)\n\t\te += x[i]*x[i] + std::pow(x[i],-2.0);\n\n\treturn e;\n}\n\ntemplate <int DIM>\ndouble SymmDirichlet<DIM>::gradient(const VecD &x, VecD &grad)\n{\n\tdouble e = 0;\n\tVecD pow_x;\n\tfor(int i=0; i<DIM; ++i)\n\t{\n\t\tpow_x[i] = std::pow(x[i], -3.0);\n\t\te += x[i]*x[i] + std::pow(x[i],-2.0);\n\t}\n\tgrad = 2.0 * (x - pow_x);\n\treturn e;\n}\n\ntemplate <int DIM>\nvoid SymmDirichlet<DIM>::hessian(const VecD &x, MatD &H)\n{\n\tH.setZero();\n\tfor(int i=0; i<DIM; ++i)\n\t\tH(i,i) = 2.0 + 6.0 * std::pow(x[i],-4.0);\n}\n\n} // end namespace mcl\n\n#endif\n", "meta": {"hexsha": "1c907cb835fe68665b235d7a0dde71ff29852390", "size": 8297, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/EnergyModel.hpp", "max_stars_repo_name": "mattoverby/mclgeom", "max_stars_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/MCL/EnergyModel.hpp", "max_issues_repo_name": "mattoverby/mclgeom", "max_issues_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-26T22:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T02:54:23.000Z", "max_forks_repo_path": "include/MCL/EnergyModel.hpp", "max_forks_repo_name": "mattoverby/mclgeom", "max_forks_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1122807018, "max_line_length": 118, "alphanum_fraction": 0.5800891889, "num_tokens": 3259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5322287518542945}}
{"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_ARCH_COMMON_SIMD_FUNCTION_SIGNIFICANTS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SIGNIFICANTS_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/detail/assert_utils.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/iceil.hpp>\n#include <boost/simd/function/if_zero_else.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_gtz.hpp>\n#include <boost/simd/function/log10.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/round.hpp>\n#include <boost/simd/function/tenpower.hpp>\n#include <boost/assert.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_invalid.hpp>\n#endif\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n\n//   WARNING AN \"IMPLEMENT_IF\" WAS PRESENT IN THE ORIGINAL FILE\n\n   BOOST_DISPATCH_OVERLOAD_IF( significants_\n                          , (typename A0, typename A1, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::floating_<A0>, X>\n                          , bs::pack_< bd::integer_<A1>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0, const  A1&  a1) const BOOST_NOEXCEPT\n      {\n        BOOST_ASSERT_MSG( assert_all(is_gtz(a1))\n                        , \"Number of significant digits must be positive\"\n                        );\n        using iA0 =  bd::as_integer_t<A0>;\n        iA0 exp = a1 - iceil(log10(abs(a0)));\n        A0 fac = tenpower(exp);\n        A0 scaled = round(a0*fac);\n  #ifndef BOOST_SIMD_NO_INVALIDS\n        A0 r = if_else(is_invalid(a0), a0, scaled/fac);\n  #else\n        A0 r =  scaled/fac;\n  #endif\n        return if_zero_else(is_eqz(a0), r);\n      }\n   };\n\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "c81de54c2a2c72ba8715ad16a545a28e38af519e", "size": 2502, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/significants.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/arch/common/simd/function/significants.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/arch/common/simd/function/significants.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": 33.8108108108, "max_line_length": 100, "alphanum_fraction": 0.6055155875, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6370307806984445, "lm_q1q2_score": 0.5322287351207059}}
{"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_ACSCD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACSCD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing acscd capabilities\n\n    inverse cosecant in degree: \\f$(180/\\pi) \\arcsin(1/x)\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = acscd(x);\n    @endcode\n\n    @see acsc, acscpi, asind, sind\n\n  **/\n  Value acscd(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acscd.hpp>\n#include <boost/simd/function/simd/acscd.hpp>\n\n#endif\n", "meta": {"hexsha": "bd464560f939fb831d8ff76363a562f175ea15f9", "size": 1002, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acscd.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/acscd.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/acscd.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": 22.7727272727, "max_line_length": 100, "alphanum_fraction": 0.5708582834, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5322287351207059}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <search-manager/CustomRanker.h>\r\n\nusing namespace sf1r;\n \r\nBOOST_AUTO_TEST_SUITE( CustomRanker_Suite )\r\n\n \r\nBOOST_AUTO_TEST_CASE(customranker_test)\r\n{\n    {\r\n        std::string exp(\"param1 + param2 * price + log(x)\");\r\n        CustomRanker customRanker(exp);\r\r\n        bool ret = customRanker.parse();\r\n        BOOST_CHECK_EQUAL(ret, true);\r\n    }\n    {\r\n        std::string exp(\"param1 - (param2 / price) * pow(x,2)\");\r\n        CustomRanker customRanker(exp);\r\n        bool ret = customRanker.parse();\r\n        BOOST_CHECK_EQUAL(ret, true);\r\n    }\n}\r\n\nBOOST_AUTO_TEST_SUITE_END()\n\r\n", "meta": {"hexsha": "c3b2acc430d132230617020b67f452e78e684d18", "size": 630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/search-manager/t_CustomRanker.cpp", "max_stars_repo_name": "izenecloud/sf1r-lite", "max_stars_repo_head_hexsha": "8de9aa83c38c9cd05a80b216579552e89609f136", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T20:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T18:40:49.000Z", "max_issues_repo_path": "test/search-manager/t_CustomRanker.cpp", "max_issues_repo_name": "fytzzh/sf1r-lite", "max_issues_repo_head_hexsha": "8de9aa83c38c9cd05a80b216579552e89609f136", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-28T08:55:47.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-10T10:10:53.000Z", "max_forks_repo_path": "test/search-manager/t_CustomRanker.cpp", "max_forks_repo_name": "fytzzh/sf1r-lite", "max_forks_repo_head_hexsha": "8de9aa83c38c9cd05a80b216579552e89609f136", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 33.0, "max_forks_repo_forks_event_min_datetime": "2015-01-05T03:03:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T04:22:46.000Z", "avg_line_length": 22.5, "max_line_length": 65, "alphanum_fraction": 0.6301587302, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5322000076401896}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 1999 - 2021 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: Wolfgang Bangerth, University of Heidelberg, 1999 \n */ \n\n\n\n// \u524d\u9762\u51e0\u4e2a\u5305\u62ec\u7684\u5185\u5bb9\u548c\u524d\u9762\u7684\u7a0b\u5e8f\u4e00\u6837\uff0c\u6240\u4ee5\u4e0d\u9700\u8981\u989d\u5916\u7684\u6ce8\u91ca\u3002\n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n\n// \u7136\u800c\uff0c\u4e0b\u4e00\u4e2a\u6587\u4ef6\u662f\u65b0\u7684\u3002\u6211\u4eec\u9700\u8981\u8fd9\u4e2a\u5305\u542b\u6587\u4ef6\u6765\u5c06\u81ea\u7531\u5ea6\uff08DoF\uff09\u4e0e\u9876\u70b9\u3001\u76f4\u7ebf\u548c\u5355\u5143\u8054\u7cfb\u8d77\u6765\u3002\n\n#include <deal.II/dofs/dof_handler.h> \n\n// \u4ee5\u4e0b\u6587\u4ef6\u5305\u542b\u4e86\u5bf9\u53cc\u7ebf\u6027\u6709\u9650\u5143\u7684\u63cf\u8ff0\uff0c\u5305\u62ec\u5b83\u5728\u4e09\u89d2\u5f62\u7684\u6bcf\u4e2a\u9876\u70b9\u4e0a\u6709\u4e00\u4e2a\u81ea\u7531\u5ea6\uff0c\u4f46\u5728\u9762\u548c\u5355\u5143\u5185\u90e8\u6ca1\u6709\u81ea\u7531\u5ea6\u3002\n\n// (\u4e8b\u5b9e\u4e0a\uff0c\u8be5\u6587\u4ef6\u5305\u542b\u4e86\u5bf9\u62c9\u683c\u6717\u65e5\u5143\u7d20\u7684\u4e00\u822c\u63cf\u8ff0\uff0c\u5373\u8fd8\u6709\u4e8c\u6b21\u3001\u4e09\u6b21\u7b49\u7248\u672c\uff0c\u800c\u4e14\u4e0d\u4ec5\u662f2d\uff0c\u8fd8\u67091d\u548c3d\u3002)\n\n#include <deal.II/fe/fe_q.h> \n\n// \u5728\u4e0b\u9762\u7684\u6587\u4ef6\u4e2d\uff0c\u53ef\u4ee5\u627e\u5230\u51e0\u4e2a\u64cd\u4f5c\u81ea\u7531\u5ea6\u7684\u5de5\u5177\u3002\n\n#include <deal.II/dofs/dof_tools.h> \n\n// \u6211\u4eec\u5c06\u4f7f\u7528\u4e00\u4e2a\u7a00\u758f\u77e9\u9635\u6765\u53ef\u89c6\u5316\u81ea\u7531\u5ea6\u5728\u7f51\u683c\u4e0a\u7684\u5206\u5e03\u6240\u4ea7\u751f\u7684\u975e\u96f6\u6761\u76ee\u6a21\u5f0f\u3002\u8fd9\u4e2a\u7c7b\u53ef\u4ee5\u5728\u8fd9\u91cc\u627e\u5230\u3002\n\n#include <deal.II/lac/sparse_matrix.h> \n\n// \u6211\u4eec\u8fd8\u9700\u8981\u4f7f\u7528\u4e00\u4e2a\u4e2d\u95f4\u7684\u7a00\u758f\u6a21\u5f0f\u7ed3\u6784\uff0c\u53ef\u4ee5\u5728\u8fd9\u4e2a\u6587\u4ef6\u4e2d\u627e\u5230\u3002\n\n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n\n// \u6211\u4eec\u5e0c\u671b\u4f7f\u7528\u4e00\u79cd\u7279\u6b8a\u7684\u7b97\u6cd5\u6765\u91cd\u65b0\u8ba1\u7b97\u81ea\u7531\u5ea6\u3002\u5b83\u88ab\u58f0\u660e\u5728\u8fd9\u91cc\u3002\n\n#include <deal.II/dofs/dof_renumbering.h> \n\n// \u800c\u8fd9\u53c8\u662fC++\u8f93\u51fa\u6240\u9700\u8981\u7684\u3002\n\n#include <fstream> \n\n// \u6700\u540e\uff0c\u548c step-1 \u4e00\u6837\uff0c\u6211\u4eec\u5c06deal.II\u547d\u540d\u7a7a\u95f4\u5bfc\u5165\u5230\u5168\u5c40\u8303\u56f4\u3002\n\nusing namespace dealii; \n// @sect3{Mesh generation}  \n\n// \u8fd9\u5c31\u662f\u524d\u9762 step-1 \u4f8b\u5b50\u7a0b\u5e8f\u4e2d\u4ea7\u751f\u5706\u5f62\u7f51\u683c\u7684\u51fd\u6570\uff0c\u7ec6\u5316\u6b65\u9aa4\u8f83\u5c11\u3002\u552f\u4e00\u4e0d\u540c\u7684\u662f\uff0c\u5b83\u901a\u8fc7\u5176\u53c2\u6570\u8fd4\u56de\u5b83\u6240\u4ea7\u751f\u7684\u7f51\u683c\u3002\n\nvoid make_grid(Triangulation<2> &triangulation) \n{ \n  const Point<2> center(1, 0); \n  const double   inner_radius = 0.5, outer_radius = 1.0; \n  GridGenerator::hyper_shell( \n    triangulation, center, inner_radius, outer_radius, 5); \n\n  for (unsigned int step = 0; step < 3; ++step) \n    { \n      for (auto &cell : triangulation.active_cell_iterators()) \n        for (const auto v : cell->vertex_indices()) \n          { \n            const double distance_from_center = \n              center.distance(cell->vertex(v)); \n\n            if (std::fabs(distance_from_center - inner_radius) <= \n                1e-6 * inner_radius) \n              { \n                cell->set_refine_flag(); \n                break; \n              } \n          } \n\n      triangulation.execute_coarsening_and_refinement(); \n    } \n} \n// @sect3{Creation of a DoFHandler}  \n\n// \u5230\u76ee\u524d\u4e3a\u6b62\uff0c\u6211\u4eec\u53ea\u6709\u4e00\u4e2a\u7f51\u683c\uff0c\u5373\u4e00\u4e9b\u51e0\u4f55\u4fe1\u606f\uff08\u9876\u70b9\u7684\u4f4d\u7f6e\uff09\u548c\u4e00\u4e9b\u62d3\u6251\u4fe1\u606f\uff08\u9876\u70b9\u5982\u4f55\u4e0e\u7ebf\u76f8\u8fde\uff0c\u7ebf\u4e0e\u5355\u5143\u683c\u76f8\u8fde\uff0c\u4ee5\u53ca\u54ea\u4e9b\u5355\u5143\u683c\u4e0e\u54ea\u4e9b\u5176\u4ed6\u5355\u5143\u683c\u76f8\u90bb\uff09\u3002\u8981\u4f7f\u7528\u6570\u503c\u7b97\u6cd5\uff0c\u8fd8\u9700\u8981\u4e00\u4e9b\u903b\u8f91\u4fe1\u606f\uff1a\u6211\u4eec\u5e0c\u671b\u5c06\u81ea\u7531\u5ea6\u6570\u5b57\u4e0e\u6bcf\u4e2a\u9876\u70b9\uff08\u6216\u7ebf\uff0c\u6216\u5355\u5143\uff0c\u5982\u679c\u6211\u4eec\u4f7f\u7528\u9ad8\u9636\u5143\u7d20\u7684\u8bdd\uff09\u8054\u7cfb\u8d77\u6765\uff0c\u4ee5\u4fbf\u4ee5\u540e\u751f\u6210\u63cf\u8ff0\u4e09\u89d2\u5f62\u4e0a\u6709\u9650\u5143\u573a\u7684\u77e9\u9635\u548c\u77e2\u91cf\u3002\n\n// \u8fd9\u4e2a\u51fd\u6570\u663e\u793a\u4e86\u5982\u4f55\u505a\u5230\u8fd9\u4e00\u70b9\u3002\u8981\u8003\u8651\u7684\u5bf9\u8c61\u662f <code>DoFHandler</code> \u7c7b\u6a21\u677f\u3002 \u7136\u800c\uff0c\u5728\u8fd9\u4e4b\u524d\uff0c\u6211\u4eec\u9996\u5148\u9700\u8981\u4e00\u4e9b\u4e1c\u897f\u6765\u63cf\u8ff0\u8fd9\u4e9b\u5bf9\u8c61\u4e2d\u7684\u6bcf\u4e00\u4e2a\u8981\u4e0e\u591a\u5c11\u4e2a\u81ea\u7531\u5ea6\u76f8\u5173\u8054\u3002\u7531\u4e8e\u8fd9\u662f\u6709\u9650\u5143\u7a7a\u95f4\u5b9a\u4e49\u7684\u4e00\u4e2a\u65b9\u9762\uff0c\u6709\u9650\u5143\u57fa\u7c7b\u5b58\u50a8\u4e86\u8fd9\u4e2a\u4fe1\u606f\u3002\u5728\u76ee\u524d\u7684\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u56e0\u6b64\u521b\u5efa\u4e86\u4e00\u4e2a\u63cf\u8ff0\u62c9\u683c\u6717\u65e5\u5143\u7d20\u7684\u6d3e\u751f\u7c7b <code>FE_Q</code> \u7684\u5bf9\u8c61\u3002\u5b83\u7684\u6784\u9020\u51fd\u6570\u9700\u8981\u4e00\u4e2a\u53c2\u6570\uff0c\u8bf4\u660e\u5143\u7d20\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\uff0c\u8fd9\u91cc\u662f1\uff08\u8868\u793a\u4e00\u4e2a\u53cc\u7ebf\u6027\u5143\u7d20\uff09\uff1b\u8fd9\u5c31\u5bf9\u5e94\u4e8e\u6bcf\u4e2a\u9876\u70b9\u7684\u4e00\u4e2a\u81ea\u7531\u5ea6\uff0c\u800c\u7ebf\u548c\u56db\u8fb9\u5f62\u5185\u90e8\u6ca1\u6709\u81ea\u7531\u5ea6\u3002\u5982\u679c\u7ed9\u6784\u9020\u51fd\u6570\u7684\u503c\u662f3\uff0c\u6211\u4eec\u5c31\u4f1a\u5f97\u5230\u4e00\u4e2a\u53cc\u7acb\u65b9\u4f53\u5143\u7d20\uff0c\u6bcf\u4e2a\u9876\u70b9\u6709\u4e00\u4e2a\u81ea\u7531\u5ea6\uff0c\u6bcf\u6761\u7ebf\u6709\u4e24\u4e2a\u81ea\u7531\u5ea6\uff0c\u5355\u5143\u5185\u6709\u56db\u4e2a\u81ea\u7531\u5ea6\u3002\u4e00\u822c\u6765\u8bf4\uff0c <code>FE_Q</code> \u8868\u793a\u5177\u6709\u5b8c\u6574\u591a\u9879\u5f0f\uff08\u5373\u5f20\u91cf\u79ef\u591a\u9879\u5f0f\uff09\u7684\u8fde\u7eed\u5143\u7d20\u5bb6\u65cf\uff0c\u76f4\u5230\u6307\u5b9a\u7684\u987a\u5e8f\u3002\n\n// \u6211\u4eec\u9996\u5148\u9700\u8981\u521b\u5efa\u4e00\u4e2a\u8fd9\u4e2a\u7c7b\u7684\u5bf9\u8c61\uff0c\u7136\u540e\u628a\u5b83\u4f20\u9012\u7ed9 <code>DoFHandler</code> \u5bf9\u8c61\uff0c\u4e3a\u81ea\u7531\u5ea6\u5206\u914d\u5b58\u50a8\u7a7a\u95f4\uff08\u7528deal.II\u7684\u884c\u8bdd\u8bf4\uff1a\u6211\u4eec<i>distribute degrees of freedom</i>\uff09\u3002\n\nvoid distribute_dofs(DoFHandler<2> &dof_handler) \n{ \n  const FE_Q<2> finite_element(1); \n  dof_handler.distribute_dofs(finite_element); \n\n// \u73b0\u5728\u6211\u4eec\u5df2\u7ecf\u5c06\u81ea\u7531\u5ea6\u4e0e\u6bcf\u4e2a\u9876\u70b9\u7684\u5168\u5c40\u6570\u5b57\u8054\u7cfb\u8d77\u6765\uff0c\u6211\u4eec\u60f3\u77e5\u9053\u5982\u4f55\u5c06\u5176\u53ef\u89c6\u5316\uff1f \u6ca1\u6709\u7b80\u5355\u7684\u65b9\u6cd5\u53ef\u4ee5\u76f4\u63a5\u5c06\u4e0e\u6bcf\u4e2a\u9876\u70b9\u76f8\u5173\u7684\u81ea\u7531\u5ea6\u6570\u5b57\u53ef\u89c6\u5316\u3002\u7136\u800c\uff0c\u8fd9\u6837\u7684\u4fe1\u606f\u51e0\u4e4e\u4e0d\u4f1a\u771f\u6b63\u91cd\u8981\uff0c\u56e0\u4e3a\u7f16\u53f7\u672c\u8eab\u6216\u591a\u6216\u5c11\u662f\u4efb\u610f\u7684\u3002\u8fd8\u6709\u66f4\u91cd\u8981\u7684\u56e0\u7d20\uff0c\u6211\u4eec\u5c06\u5728\u4e0b\u6587\u4e2d\u5c55\u793a\u5176\u4e2d\u4e00\u4e2a\u3002\n\n// \u4e0e\u4e09\u89d2\u5f62\u7684\u6bcf\u4e2a\u9876\u70b9\u76f8\u5173\u7684\u662f\u4e00\u4e2a\u5f62\u72b6\u51fd\u6570\u3002\u5047\u8bbe\u6211\u4eec\u60f3\u89e3\u51b3\u7c7b\u4f3c\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\u7684\u95ee\u9898\uff0c\u90a3\u4e48\u4e0d\u540c\u7684\u77e9\u9635\u6761\u76ee\u5c06\u662f\u6bcf\u5bf9\u8fd9\u6837\u7684\u5f62\u72b6\u51fd\u6570\u7684\u68af\u5ea6\u7684\u79ef\u5206\u3002\u663e\u7136\uff0c\u7531\u4e8e\u5f62\u72b6\u51fd\u6570\u53ea\u5728\u4e0e\u5b83\u4eec\u76f8\u5173\u7684\u9876\u70b9\u76f8\u90bb\u7684\u5355\u5143\u683c\u4e0a\u662f\u975e\u96f6\u7684\uff0c\u6240\u4ee5\u53ea\u6709\u5f53\u4e0e\u8be5\u5217\u548c\u884c%\u53f7\u76f8\u5173\u7684\u5f62\u72b6\u51fd\u6570\u7684\u652f\u6301\u76f8\u4ea4\u65f6\uff0c\u77e9\u9635\u6761\u76ee\u624d\u662f\u975e\u96f6\u7684\u3002\u8fd9\u53ea\u662f\u76f8\u90bb\u5f62\u72b6\u51fd\u6570\u7684\u60c5\u51b5\uff0c\u56e0\u6b64\u4e5f\u53ea\u662f\u76f8\u90bb\u9876\u70b9\u7684\u60c5\u51b5\u3002\u73b0\u5728\uff0c\u7531\u4e8e\u9876\u70b9\u88ab\u4e0a\u8ff0\u51fd\u6570 (DoFHandler::distribute_dofs), \u6216\u591a\u6216\u5c11\u5730\u968f\u673a\u7f16\u53f7\uff0c\u77e9\u9635\u4e2d\u975e\u96f6\u9879\u7684\u6a21\u5f0f\u5c06\u6709\u4e9b\u53c2\u5dee\u4e0d\u9f50\uff0c\u6211\u4eec\u73b0\u5728\u5c31\u6765\u770b\u770b\u5b83\u3002\n\n// \u9996\u5148\uff0c\u6211\u4eec\u8981\u521b\u5efa\u4e00\u4e2a\u7ed3\u6784\uff0c\u7528\u6765\u5b58\u50a8\u975e\u96f6\u5143\u7d20\u7684\u4f4d\u7f6e\u3002\u7136\u540e\uff0c\u8fd9\u4e2a\u7ed3\u6784\u53ef\u4ee5\u88ab\u4e00\u4e2a\u6216\u591a\u4e2a\u7a00\u758f\u77e9\u9635\u5bf9\u8c61\u4f7f\u7528\uff0c\u8fd9\u4e9b\u5bf9\u8c61\u5728\u8fd9\u4e2a\u7a00\u758f\u6a21\u5f0f\u6240\u5b58\u50a8\u7684\u4f4d\u7f6e\u4e0a\u5b58\u50a8\u6761\u76ee\u7684\u503c\u3002\u5b58\u50a8\u8fd9\u4e9b\u4f4d\u7f6e\u7684\u7c7b\u662fSparsityPattern\u7c7b\u3002\u7136\u800c\uff0c\u4e8b\u5b9e\u8bc1\u660e\uff0c\u5f53\u6211\u4eec\u8bd5\u56fe\u7acb\u5373\u586b\u5145\u8fd9\u4e2a\u7c7b\u65f6\uff0c\u5b83\u6709\u4e00\u4e9b\u7f3a\u70b9\uff1a\u5b83\u7684\u6570\u636e\u7ed3\u6784\u7684\u8bbe\u7f6e\u65b9\u5f0f\u662f\uff0c\u6211\u4eec\u9700\u8981\u5bf9\u6211\u4eec\u53ef\u80fd\u5e0c\u671b\u5728\u6bcf\u4e00\u884c\u7684\u6700\u5927\u6761\u76ee\u6570\u6709\u4e00\u4e2a\u4f30\u8ba1\u3002\u5728\u4e24\u4e2a\u7a7a\u95f4\u7ef4\u5ea6\u4e0a\uff0c\u901a\u8fc7 DoFHandler::max_couplings_between_dofs() \u51fd\u6570\u53ef\u4ee5\u5f97\u5230\u5408\u7406\u7684\u4f30\u8ba1\u503c\uff0c\u4f46\u662f\u5728\u4e09\u4e2a\u7ef4\u5ea6\u4e0a\uff0c\u8be5\u51fd\u6570\u51e0\u4e4e\u603b\u662f\u4e25\u91cd\u9ad8\u4f30\u771f\u5b9e\u7684\u6570\u5b57\uff0c\u5bfc\u81f4\u5927\u91cf\u7684\u5185\u5b58\u6d6a\u8d39\uff0c\u6709\u65f6\u5bf9\u4e8e\u6240\u4f7f\u7528\u7684\u673a\u5668\u6765\u8bf4\u592a\u591a\uff0c\u5373\u4f7f\u672a\u4f7f\u7528\u7684\u5185\u5b58\u53ef\u4ee5\u5728\u8ba1\u7b97\u7a00\u758f\u6a21\u5f0f\u540e\u7acb\u5373\u91ca\u653e\u3002\u4e3a\u4e86\u907f\u514d\u8fd9\u79cd\u60c5\u51b5\uff0c\u6211\u4eec\u4f7f\u7528\u4e86\u4e00\u4e2a\u4e2d\u95f4\u5bf9\u8c61DynamicSparsityPattern\uff0c\u8be5\u5bf9\u8c61\u4f7f\u7528\u4e86\u4e00\u4e2a\u4e0d\u540c\u7684%\u5185\u90e8\u6570\u636e\u7ed3\u6784\uff0c\u6211\u4eec\u53ef\u4ee5\u968f\u540e\u5c06\u5176\u590d\u5236\u5230SparsityPattern\u5bf9\u8c61\u4e2d\uff0c\u800c\u4e0d\u9700\u8981\u592a\u591a\u7684\u5f00\u9500\u3002\u5173\u4e8e\u8fd9\u4e9b\u6570\u636e\u7ed3\u6784\u7684\u4e00\u4e9b\u66f4\u591a\u4fe1\u606f\u53ef\u4ee5\u5728 @ref Sparsity \u6a21\u5757\u4e2d\u627e\u5230\uff09\u3002\u4e3a\u4e86\u521d\u59cb\u5316\u8fd9\u4e2a\u4e2d\u95f4\u6570\u636e\u7ed3\u6784\uff0c\u6211\u4eec\u5fc5\u987b\u7ed9\u5b83\u63d0\u4f9b\u77e9\u9635\u7684\u5927\u5c0f\uff0c\u5728\u6211\u4eec\u7684\u4f8b\u5b50\u4e2d\uff0c\u77e9\u9635\u662f\u6b63\u65b9\u5f62\u7684\uff0c\u884c\u548c\u5217\u7684\u6570\u91cf\u4e0e\u7f51\u683c\u4e0a\u7684\u81ea\u7531\u5ea6\u76f8\u540c\u3002\n\n  DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs(), \n                                                  dof_handler.n_dofs()); \n\n// \u7136\u540e\u6211\u4eec\u5728\u8fd9\u4e2a\u5bf9\u8c61\u4e2d\u586b\u5165\u975e\u96f6\u5143\u7d20\u7684\u4f4d\u7f6e\uff0c\u8003\u8651\u5230\u76ee\u524d\u81ea\u7531\u5ea6\u7684\u7f16\u53f7\u3002\n\n  DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern); \n\n// \u73b0\u5728\u6211\u4eec\u5df2\u7ecf\u51c6\u5907\u597d\u521b\u5efa\u5b9e\u9645\u7684\u7a00\u758f\u6a21\u5f0f\u4e86\uff0c\u4ee5\u540e\u6211\u4eec\u53ef\u4ee5\u7528\u5728\u6211\u4eec\u7684\u77e9\u9635\u4e0a\u3002\u5b83\u5c06\u5305\u542b\u5df2\u7ecf\u5728DynamicSparsityPattern\u4e2d\u96c6\u5408\u7684\u6570\u636e\u3002\n\n  SparsityPattern sparsity_pattern; \n  sparsity_pattern.copy_from(dynamic_sparsity_pattern); \n\n// \u6709\u4e86\u8fd9\u4e2a\uff0c\u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u628a\u7ed3\u679c\u5199\u5230\u4e00\u4e2a\u6587\u4ef6\u91cc\u3002\n\n  std::ofstream out(\"sparsity_pattern1.svg\"); \n  sparsity_pattern.print_svg(out); \n\n// \u7ed3\u679c\u88ab\u5b58\u50a8\u5728\u4e00\u4e2a <code>.svg</code> \u6587\u4ef6\u4e2d\uff0c\u77e9\u9635\u4e2d\u7684\u6bcf\u4e2a\u975e\u96f6\u6761\u76ee\u90fd\u5bf9\u5e94\u4e8e\u56fe\u50cf\u4e2d\u7684\u4e00\u4e2a\u7ea2\u8272\u65b9\u5757\u3002\u8f93\u51fa\u7ed3\u679c\u5c06\u663e\u793a\u5982\u4e0b\u3002\n\n// \u5982\u679c\u4f60\u770b\u4e00\u4e0b\uff0c\u4f60\u4f1a\u6ce8\u610f\u5230\u7a00\u758f\u6027\u6a21\u5f0f\u662f\u5bf9\u79f0\u7684\u3002\u8fd9\u4e0d\u5e94\u8be5\u662f\u4e00\u4e2a\u60ca\u559c\uff0c\u56e0\u4e3a\u6211\u4eec\u6ca1\u6709\u7ed9 <code>DoFTools::make_sparsity_pattern</code> \u4efb\u4f55\u4fe1\u606f\uff0c\u8868\u660e\u6211\u4eec\u7684\u53cc\u7ebf\u6027\u5f62\u5f0f\u53ef\u80fd\u4ee5\u975e\u5bf9\u79f0\u7684\u65b9\u5f0f\u8026\u5408\u5f62\u72b6\u51fd\u6570\u3002\u4f60\u8fd8\u4f1a\u6ce8\u610f\u5230\u5b83\u6709\u51e0\u4e2a\u660e\u663e\u7684\u533a\u57df\uff0c\u8fd9\u6e90\u4e8e\u7f16\u53f7\u4ece\u6700\u7c97\u7684\u5355\u5143\u5f00\u59cb\uff0c\u7136\u540e\u5230\u8f83\u7ec6\u7684\u5355\u5143\uff1b\u7531\u4e8e\u5b83\u4eec\u90fd\u662f\u56f4\u7ed5\u539f\u70b9\u5bf9\u79f0\u5206\u5e03\u7684\uff0c\u8fd9\u5728\u7a00\u758f\u6a21\u5f0f\u4e2d\u518d\u6b21\u663e\u793a\u51fa\u6765\u3002\n\n} \n// @sect3{Renumbering of DoFs}  \n\n// \u5728\u4e0a\u9762\u4ea7\u751f\u7684\u7a00\u758f\u6a21\u5f0f\u4e2d\uff0c\u975e\u96f6\u6761\u76ee\u5728\u5bf9\u89d2\u7ebf\u4e0a\u5ef6\u4f38\u5f97\u5f88\u8fdc\u3002\u5bf9\u4e8e\u67d0\u4e9b\u7b97\u6cd5\u6765\u8bf4\uff0c\u4f8b\u5982\u4e0d\u5b8c\u5168LU\u5206\u89e3\u6216Gauss-Seidel\u9884\u5904\u7406\uff0c\u8fd9\u662f\u4e0d\u5229\u7684\uff0c\u6211\u4eec\u5c06\u5c55\u793a\u4e00\u4e2a\u7b80\u5355\u7684\u65b9\u6cd5\u6765\u6539\u5584\u8fd9\u79cd\u60c5\u51b5\u3002\n\n// \u8bf7\u8bb0\u4f4f\uff0c\u4e3a\u4e86\u4f7f\u77e9\u9635\u4e2d\u7684\u4e00\u4e2a\u6761\u76ee $(i,j)$ \u4e0d\u4e3a\u96f6\uff0c\u5f62\u72b6\u51fd\u6570i\u548cj\u7684\u652f\u6301\u9700\u8981\u76f8\u4ea4\uff08\u5426\u5219\u5728\u79ef\u5206\u4e2d\uff0c\u79ef\u5206\u5c06\u5230\u5904\u4e3a\u96f6\uff0c\u56e0\u4e3a\u5728\u67d0\u4e2a\u70b9\u4e0a\uff0c\u4e00\u4e2a\u6216\u53e6\u4e00\u4e2a\u5f62\u72b6\u51fd\u6570\u4e3a\u96f6\uff09\u3002\u7136\u800c\uff0c\u5f62\u72b6\u51fd\u6570\u7684\u652f\u6491\u70b9\u53ea\u6709\u5728\u5f7c\u6b64\u76f8\u90bb\u7684\u60c5\u51b5\u4e0b\u624d\u4f1a\u76f8\u4ea4\uff0c\u6240\u4ee5\u4e3a\u4e86\u4f7f\u975e\u96f6\u6761\u76ee\u805a\u96c6\u5728\u5bf9\u89d2\u7ebf\u5468\u56f4\uff08\u5176\u4e2d $i$ \u7b49\u4e8e $j$ \uff09\uff0c\u6211\u4eec\u5e0c\u671b\u76f8\u90bb\u7684\u5f62\u72b6\u51fd\u6570\u7684\u7d22\u5f15\uff08DoF\u7f16\u53f7\uff09\u76f8\u5dee\u4e0d\u5927\u3002\n\n// \u8fd9\u53ef\u4ee5\u901a\u8fc7\u4e00\u4e2a\u7b80\u5355\u7684\u524d\u884c\u7b97\u6cd5\u6765\u5b9e\u73b0\uff0c\u5373\u4ece\u4e00\u4e2a\u7ed9\u5b9a\u7684\u9876\u70b9\u5f00\u59cb\uff0c\u7ed9\u5b83\u7684\u7d22\u5f15\u4e3a0\u3002\u7136\u540e\uff0c\u4f9d\u6b21\u5bf9\u5176\u90bb\u5c45\u8fdb\u884c\u7f16\u53f7\uff0c\u4f7f\u5176\u6307\u6570\u63a5\u8fd1\u4e8e\u539f\u59cb\u6307\u6570\u3002\u7136\u540e\uff0c\u4ed6\u4eec\u7684\u90bb\u5c45\uff0c\u5982\u679c\u8fd8\u6ca1\u6709\u88ab\u7f16\u53f7\uff0c\u4e5f\u88ab\u7f16\u53f7\uff0c\u4ee5\u6b64\u7c7b\u63a8\u3002\n\n// \u6709\u4e00\u79cd\u7b97\u6cd5\u6cbf\u7740\u8fd9\u4e9b\u601d\u8def\u589e\u52a0\u4e86\u4e00\u70b9\u590d\u6742\u6027\uff0c\u90a3\u5c31\u662fCuthill\u548cMcKee\u7684\u7b97\u6cd5\u3002\u6211\u4eec\u5c06\u5728\u4e0b\u9762\u7684\u51fd\u6570\u4e2d\u4f7f\u7528\u5b83\u6765\u5bf9\u81ea\u7531\u5ea6\u8fdb\u884c\u91cd\u65b0\u7f16\u53f7\uff0c\u4ece\u800c\u4f7f\u4ea7\u751f\u7684\u7a00\u758f\u6a21\u5f0f\u5728\u5bf9\u89d2\u7ebf\u5468\u56f4\u66f4\u52a0\u672c\u5730\u5316\u3002\u8be5\u51fd\u6570\u552f\u4e00\u6709\u8da3\u7684\u90e8\u5206\u662f\u5bf9 <code>DoFRenumbering::Cuthill_McKee</code> \u7684\u7b2c\u4e00\u6b21\u8c03\u7528\uff0c\u5176\u4f59\u90e8\u5206\u57fa\u672c\u4e0a\u4e0e\u4ee5\u524d\u4e00\u6837\u3002\n\nvoid renumber_dofs(DoFHandler<2> &dof_handler) \n{ \n  DoFRenumbering::Cuthill_McKee(dof_handler); \n\n  DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs(), \n                                                  dof_handler.n_dofs()); \n  DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern); \n\n  SparsityPattern sparsity_pattern; \n  sparsity_pattern.copy_from(dynamic_sparsity_pattern); \n\n  std::ofstream out(\"sparsity_pattern2.svg\"); \n  sparsity_pattern.print_svg(out); \n} \n\n// \u518d\u6b21\uff0c\u8f93\u51fa\u5982\u4e0b\u3002\u8bf7\u6ce8\u610f\uff0c\u975e\u96f6\u9879\u5728\u5bf9\u89d2\u7ebf\u9644\u8fd1\u7684\u805a\u7c7b\u60c5\u51b5\u8981\u6bd4\u4ee5\u524d\u597d\u5f97\u591a\u3002\u8fd9\u79cd\u6548\u679c\u5bf9\u4e8e\u8f83\u5927\u7684\u77e9\u9635\u6765\u8bf4\u66f4\u52a0\u660e\u663e\uff08\u76ee\u524d\u7684\u77e9\u9635\u67091260\u884c\u548c\u5217\uff0c\u4f46\u662f\u5927\u7684\u77e9\u9635\u5f80\u5f80\u6709\u51e0\u5341\u4e07\u884c\uff09\u3002\n\n// \u503c\u5f97\u6ce8\u610f\u7684\u662f\uff0c <code>DoFRenumbering</code> \u7c7b\u4e5f\u63d0\u4f9b\u4e86\u4e00\u4e9b\u5176\u4ed6\u7684\u7b97\u6cd5\u6765\u91cd\u65b0\u7f16\u53f7\u81ea\u7531\u5ea6\u3002\u4f8b\u5982\uff0c\u5982\u679c\u6240\u6709\u7684\u8026\u5408\u90fd\u5728\u77e9\u9635\u7684\u4e0b\u4e09\u89d2\u6216\u4e0a\u4e09\u89d2\u90e8\u5206\uff0c\u90a3\u5f53\u7136\u662f\u6700\u7406\u60f3\u7684\uff0c\u56e0\u4e3a\u8fd9\u6837\u7684\u8bdd\uff0c\u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u5c31\u53ea\u9700\u8981\u5411\u524d\u6216\u5411\u540e\u66ff\u6362\u3002\u5f53\u7136\uff0c\u8fd9\u5bf9\u4e8e\u5bf9\u79f0\u7a00\u758f\u6a21\u5f0f\u6765\u8bf4\u662f\u65e0\u6cd5\u5b9e\u73b0\u7684\uff0c\u4f46\u5728\u4e00\u4e9b\u6d89\u53ca\u4f20\u8f93\u65b9\u7a0b\u7684\u7279\u6b8a\u60c5\u51b5\u4e0b\uff0c\u901a\u8fc7\u5217\u4e3e\u4ece\u6d41\u5165\u8fb9\u754c\u6cbf\u6d41\u7ebf\u5230\u6d41\u51fa\u8fb9\u754c\u7684\u81ea\u7531\u5ea6\uff0c\u8fd9\u662f\u53ef\u80fd\u7684\u3002\u6beb\u4e0d\u5947\u602a\uff0c <code>DoFRenumbering</code> \u4e5f\u6709\u8fd9\u65b9\u9762\u7684\u7b97\u6cd5\u3002\n\n//  @sect3{The main function}  \n\n// \u6700\u540e\uff0c\u8fd9\u662f\u4e3b\u7a0b\u5e8f\u3002\u5b83\u6240\u505a\u7684\u552f\u4e00\u4e00\u4ef6\u4e8b\u5c31\u662f\u5206\u914d\u548c\u521b\u5efa\u4e09\u89d2\u5f62\uff0c\u7136\u540e\u521b\u5efa\u4e00\u4e2a <code>DoFHandler</code> \u5bf9\u8c61\u5e76\u5c06\u5176\u4e0e\u4e09\u89d2\u5f62\u76f8\u5173\u8054\uff0c\u6700\u540e\u5bf9\u5176\u8c03\u7528\u4e0a\u8ff0\u4e24\u4e2a\u51fd\u6570\u3002\n\nint main() \n{ \n  Triangulation<2> triangulation; \n  make_grid(triangulation); \n\n  DoFHandler<2> dof_handler(triangulation); \n\n  distribute_dofs(dof_handler); \n  renumber_dofs(dof_handler); \n} \n\n\n", "meta": {"hexsha": "411d4c72ee5129b2c168ae4a231f5761423e061b", "size": 6634, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-2/step-2.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-2/step-2.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-2/step-2.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.4802259887, "max_line_length": 515, "alphanum_fraction": 0.74781429, "num_tokens": 3816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.5322000019980822}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// kernel::multivariate::mono_bw.hpp                                         //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICEMSE_1_0.txt or copy at http://www.boost.org/LICEMSE_1_0.txt)         //\n/////////////////////////////////////////////////////////////////////////////// \n#ifndef BOOST_STATISTICS_DETAIL_KERNEL_KERNELS_MULTIVARIATE_MONO_BW_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_KERNEL_KERNELS_MULTIVARIATE_MONO_BW_HPP_ER_2009\n#include <cmath>\n#include <numeric>\n#include <boost/lambda/lambda.hpp>\n#include <boost/vector_space/data/lazy_difference.hpp>\n#include <boost/statistics/detail/kernel/kernels/multivariate/crtp.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace kernel{\nnamespace multivariate{\n\n// Overview: Multivariate kernel, common bandwidth across coordinates.\n//\n// Notation: Let x denote a vector of size M,\n//\n// Usage:\n// typedef mono_bw_kernel<scalar::gaussian_kernel<T>,M> mult_;\n// typedef mult_::result_type result_;\n// mult_ mult(bandwidth);\n// result_ r = mult(x);\ntemplate<typename K,unsigned M>\nclass mono_bw_kernel : K{\n    public:\n    typedef typename K::result_type result_type;\n\n    //Construction\n    mono_bw_kernel();\n    template<typename K1> mono_bw_kernel(K1 k1); //pass bandwith, or kernel\n    \n    // Evaluate\n    template<typename X> result_type profile(const X& x)const;    \n    template<typename X> result_type operator()(const X& x)const;    \n    template<typename X,typename X1> \n    result_type operator()(const X& x,const X1& x1)const;\n    \n    // Access\n    static unsigned dimension;\n    result_type radius()const;\n    result_type normalizing_constant()const;\n    \n    private:\n    result_type normalizing_constant_; //no ambiguity because inherit K privately\n    result_type comp_nc()const; \n};\n\n// Construction\ntemplate<typename K,unsigned M> \nmono_bw_kernel<K,M>::mono_bw_kernel():K(),normalizing_constant_(comp_nc()){}\n\ntemplate<typename K,unsigned M> \ntemplate<typename K1>\nmono_bw_kernel<K,M>::mono_bw_kernel(K1 k1):K(k1),normalizing_constant_(comp_nc()){}\n        \n// Evaluate\ntemplate<typename K,unsigned M> \ntemplate<typename X> \ntypename mono_bw_kernel<K,M>::result_type \nmono_bw_kernel<K,M>::profile(const X& x)const{\n    static result_type init = static_cast<result_type>(0);\n    const K& k = static_cast<const K&>(*this);\n    result_type norm = std::accumulate(\n        boost::begin(x),\n        boost::end(x),\n        init,\n        ( lambda::_1 + (lambda::_2 * lambda::_2 ) )\n    );   \n    norm = std::sqrt(norm);\n    return k.profile(norm);\n}\n\ntemplate<typename K,unsigned M> \ntemplate<typename X> \ntypename mono_bw_kernel<K,M>::result_type \nmono_bw_kernel<K,M>::operator()(const X& x)const{\n    return this->profile(x) / this->normalizing_constant();\n}\n\ntemplate<typename K,unsigned M> \ntemplate<typename X,typename X1> \ntypename mono_bw_kernel<K,M>::result_type \nmono_bw_kernel<K,M>::operator()(const X& x,const X1& x1)const{\n    typedef vector_space::lazy_difference<X,X1> diff_;\n    typedef typename range_size<X>::type size_type;\n    BOOST_ASSERT(size(x) == static_cast<size_type>(size(x1)));\n    BOOST_ASSERT(size(x) == static_cast<size_type>(M));\n    diff_ diff(x,x1);\n    return (*this)(diff);\n}\n        \n// Access\ntemplate<typename K,unsigned M> unsigned mono_bw_kernel<K,M>::dimension = M;\n\ntemplate<typename K,unsigned M>\ntypename mono_bw_kernel<K,M>::result_type \nmono_bw_kernel<K,M>::radius()const{ \n    const K& k = static_cast<const K&>(*this);\n    return k.radius();\n}\n\ntemplate<typename K,unsigned M>\ntypename mono_bw_kernel<K,M>::result_type \nmono_bw_kernel<K,M>::normalizing_constant()const{ return normalizing_constant_; }\n    \ntemplate<typename K,unsigned M>\ntypename mono_bw_kernel<K,M>::result_type \nmono_bw_kernel<K,M>::comp_nc()const{\n    const K& k = static_cast<const K&>(*this);\n    static result_type m = static_cast<result_type>(M);\n    result_type nc = k.normalizing_constant();\n    return std::pow(nc,m);\n}\n \n}// multivariate\n}// kernel\n}// detail\n}// statistics\n}// boost   \n\n#endif", "meta": {"hexsha": "1238ec58ed17fc77fc1f359c6a3159f03a82be6b", "size": 4291, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kernel/boost/statistics/detail/kernel/kernels/multivariate/mono_bw.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/multivariate/mono_bw.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/multivariate/mono_bw.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.2635658915, "max_line_length": 83, "alphanum_fraction": 0.6662782568, "num_tokens": 989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5321999971365445}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  (C) Copyright Jeremy William Murphy 2015.\n\n\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_TOOLS_POLYNOMIAL_HPP\n#define BOOST_MATH_TOOLS_POLYNOMIAL_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/assert.hpp>\n#include <boost/config.hpp>\n#ifdef BOOST_NO_CXX11_LAMBDAS\n#include <boost/lambda/lambda.hpp>\n#endif\n#include <boost/math/tools/rational.hpp>\n#include <boost/math/tools/real_cast.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/core/enable_if.hpp>\n\n#include <vector>\n#include <ostream>\n#include <algorithm>\n#ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n#include <initializer_list>\n#endif\n\nnamespace boost{ namespace math{ namespace tools{\n\ntemplate <class T>\nT chebyshev_coefficient(unsigned n, unsigned m)\n{\n   BOOST_MATH_STD_USING\n   if(m > n)\n      return 0;\n   if((n & 1) != (m & 1))\n      return 0;\n   if(n == 0)\n      return 1;\n   T result = T(n) / 2;\n   unsigned r = n - m;\n   r /= 2;\n\n   BOOST_ASSERT(n - 2 * r == m);\n\n   if(r & 1)\n      result = -result;\n   result /= n - r;\n   result *= boost::math::binomial_coefficient<T>(n - r, r);\n   result *= ldexp(1.0f, m);\n   return result;\n}\n\ntemplate <class Seq>\nSeq polynomial_to_chebyshev(const Seq& s)\n{\n   // Converts a Polynomial into Chebyshev form:\n   typedef typename Seq::value_type value_type;\n   typedef typename Seq::difference_type difference_type;\n   Seq result(s);\n   difference_type order = s.size() - 1;\n   difference_type even_order = order & 1 ? order - 1 : order;\n   difference_type odd_order = order & 1 ? order : order - 1;\n\n   for(difference_type i = even_order; i >= 0; i -= 2)\n   {\n      value_type val = s[i];\n      for(difference_type k = even_order; k > i; k -= 2)\n      {\n         val -= result[k] * chebyshev_coefficient<value_type>(static_cast<unsigned>(k), static_cast<unsigned>(i));\n      }\n      val /= chebyshev_coefficient<value_type>(static_cast<unsigned>(i), static_cast<unsigned>(i));\n      result[i] = val;\n   }\n   result[0] *= 2;\n\n   for(difference_type i = odd_order; i >= 0; i -= 2)\n   {\n      value_type val = s[i];\n      for(difference_type k = odd_order; k > i; k -= 2)\n      {\n         val -= result[k] * chebyshev_coefficient<value_type>(static_cast<unsigned>(k), static_cast<unsigned>(i));\n      }\n      val /= chebyshev_coefficient<value_type>(static_cast<unsigned>(i), static_cast<unsigned>(i));\n      result[i] = val;\n   }\n   return result;\n}\n\ntemplate <class Seq, class T>\nT evaluate_chebyshev(const Seq& a, const T& x)\n{\n   // Clenshaw's formula:\n   typedef typename Seq::difference_type difference_type;\n   T yk2 = 0;\n   T yk1 = 0;\n   T yk = 0;\n   for(difference_type i = a.size() - 1; i >= 1; --i)\n   {\n      yk2 = yk1;\n      yk1 = yk;\n      yk = 2 * x * yk1 - yk2 + a[i];\n   }\n   return a[0] / 2 + yk * x - yk1;\n}\n\n\ntemplate <typename T>\nclass polynomial;\n\nnamespace detail {\n\n/**\n* Knuth, The Art of Computer Programming: Volume 2, Third edition, 1998\n* Chapter 4.6.1, Algorithm D: Division of polynomials over a field.\n*\n* @tparam  T   Coefficient type, must be not be an integer.\n*\n* Template-parameter T actually must be a field but we don't currently have that\n* subtlety of distinction.\n*/\ntemplate <typename T, typename N>\nBOOST_DEDUCED_TYPENAME disable_if_c<std::numeric_limits<T>::is_integer, void >::type\ndivision_impl(polynomial<T> &q, polynomial<T> &u, const polynomial<T>& v, N n, N k)\n{\n    q[k] = u[n + k] / v[n];\n    for (N j = n + k; j > k;)\n    {\n        j--;\n        u[j] -= q[k] * v[j - k];\n    }\n}\n\ntemplate <class T, class N>\nT integer_power(T t, N n)\n{\n   switch(n)\n   {\n   case 0:\n      return static_cast<T>(1u);\n   case 1:\n      return t;\n   case 2:\n      return t * t;\n   case 3:\n      return t * t * t;\n   }\n   T result = integer_power(t, n / 2);\n   result *= result;\n   if(n & 1)\n      result *= t;\n   return result;\n}\n\n\n/**\n* Knuth, The Art of Computer Programming: Volume 2, Third edition, 1998\n* Chapter 4.6.1, Algorithm R: Pseudo-division of polynomials.\n*\n* @tparam  T   Coefficient type, must be an integer.\n*\n* Template-parameter T actually must be a unique factorization domain but we\n* don't currently have that subtlety of distinction.\n*/\ntemplate <typename T, typename N>\nBOOST_DEDUCED_TYPENAME enable_if_c<std::numeric_limits<T>::is_integer, void >::type\ndivision_impl(polynomial<T> &q, polynomial<T> &u, const polynomial<T>& v, N n, N k)\n{\n    q[k] = u[n + k] * integer_power(v[n], k);\n    for (N j = n + k; j > 0;)\n    {\n        j--;\n        u[j] = v[n] * u[j] - (j < k ? T(0) : u[n + k] * v[j - k]);\n    }\n}\n\n\n/**\n * Knuth, The Art of Computer Programming: Volume 2, Third edition, 1998\n * Chapter 4.6.1, Algorithm D and R: Main loop.\n *\n * @param   u   Dividend.\n * @param   v   Divisor.\n */\ntemplate <typename T>\nstd::pair< polynomial<T>, polynomial<T> >\ndivision(polynomial<T> u, const polynomial<T>& v)\n{\n    BOOST_ASSERT(v.size() <= u.size());\n    BOOST_ASSERT(v);\n    BOOST_ASSERT(u);\n\n    typedef typename polynomial<T>::size_type N;\n    \n    N const m = u.size() - 1, n = v.size() - 1;\n    N k = m - n;\n    polynomial<T> q;\n    q.data().resize(m - n + 1);\n\n    do\n    {\n        division_impl(q, u, v, n, k);\n    }\n    while (k-- != 0);\n    u.data().resize(n);\n    u.normalize(); // Occasionally, the remainder is zeroes.\n    return std::make_pair(q, u);\n}\n\n//\n// These structures are the same as the void specializations of the functors of the same name\n// in the std lib from C++14 onwards:\n//\nstruct negate\n{\n   template <class T>\n   T operator()(T const &x) const\n   {\n      return -x;\n   }\n};\n\nstruct plus\n{\n   template <class T, class U>\n   T operator()(T const &x, U const& y) const\n   {\n      return x + y;\n   }\n};\n\nstruct minus\n{\n   template <class T, class U>\n   T operator()(T const &x, U const& y) const\n   {\n      return x - y;\n   }\n};\n\n} // namespace detail\n\n/**\n * Returns the zero element for multiplication of polynomials.\n */\ntemplate <class T>\npolynomial<T> zero_element(std::multiplies< polynomial<T> >)\n{\n    return polynomial<T>();\n}\n\ntemplate <class T>\npolynomial<T> identity_element(std::multiplies< polynomial<T> >)\n{\n    return polynomial<T>(T(1));\n}\n\n/* Calculates a / b and a % b, returning the pair (quotient, remainder) together\n * because the same amount of computation yields both.\n * This function is not defined for division by zero: user beware.\n */\ntemplate <typename T>\nstd::pair< polynomial<T>, polynomial<T> >\nquotient_remainder(const polynomial<T>& dividend, const polynomial<T>& divisor)\n{\n    BOOST_ASSERT(divisor);\n    if (dividend.size() < divisor.size())\n        return std::make_pair(polynomial<T>(), dividend);\n    return detail::division(dividend, divisor);\n}\n\n\ntemplate <class T>\nclass polynomial\n{\npublic:\n   // typedefs:\n   typedef typename std::vector<T>::value_type value_type;\n   typedef typename std::vector<T>::size_type size_type;\n\n   // construct:\n   polynomial(){}\n\n   template <class U>\n   polynomial(const U* data, unsigned order)\n      : m_data(data, data + order + 1)\n   {\n       normalize();\n   }\n\n   template <class I>\n   polynomial(I first, I last)\n   : m_data(first, last)\n   {\n       normalize();\n   }\n\n   template <class U>\n   explicit polynomial(const U& point)\n   {\n       if (point != U(0))\n          m_data.push_back(point);\n   }\n\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   // move:\n   polynomial(polynomial&& p) BOOST_NOEXCEPT\n      : m_data(std::move(p.m_data)) { }\n#endif\n\n   // copy:\n   polynomial(const polynomial& p)\n      : m_data(p.m_data) { }\n\n   template <class U>\n   polynomial(const polynomial<U>& p)\n   {\n      for(unsigned i = 0; i < p.size(); ++i)\n      {\n         m_data.push_back(boost::math::tools::real_cast<T>(p[i]));\n      }\n   }\n   \n#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST) && !BOOST_WORKAROUND(BOOST_GCC_VERSION, < 40500)\n    polynomial(std::initializer_list<T> l) : polynomial(std::begin(l), std::end(l))\n    {\n    }\n    \n    polynomial&\n    operator=(std::initializer_list<T> l)\n    {\n        m_data.assign(std::begin(l), std::end(l));\n        normalize();\n        return *this;\n    }\n#endif\n\n\n   // access:\n   size_type size() const { return m_data.size(); }\n   size_type degree() const\n   {\n       if (size() == 0)\n           throw std::logic_error(\"degree() is undefined for the zero polynomial.\");\n       return m_data.size() - 1;\n   }\n   value_type& operator[](size_type i)\n   {\n      return m_data[i];\n   }\n   const value_type& operator[](size_type i) const\n   {\n      return m_data[i];\n   }\n   T evaluate(T z) const\n   {\n      return m_data.size() > 0 ? boost::math::tools::evaluate_polynomial(&m_data[0], z, m_data.size()) : 0;\n   }\n   std::vector<T> chebyshev() const\n   {\n      return polynomial_to_chebyshev(m_data);\n   }\n\n   std::vector<T> const& data() const\n   {\n       return m_data;\n   }\n\n   std::vector<T> & data()\n   {\n       return m_data;\n   }\n\n   // operators:\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   polynomial& operator =(polynomial&& p) BOOST_NOEXCEPT\n   {\n       m_data = std::move(p.m_data);\n       return *this;\n   }\n#endif\n   polynomial& operator =(const polynomial& p)\n   {\n       m_data = p.m_data;\n       return *this;\n   }\n\n   template <class U>\n   typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial&>::type operator +=(const U& value)\n   {\n       addition(value);\n       normalize();\n       return *this;\n   }\n\n   template <class U>\n   typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial&>::type operator -=(const U& value)\n   {\n       subtraction(value);\n       normalize();\n       return *this;\n   }\n\n   template <class U>\n   typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial&>::type operator *=(const U& value)\n   {\n      multiplication(value);\n      normalize();\n      return *this;\n   }\n\n   template <class U>\n   typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial&>::type operator /=(const U& value)\n   {\n       division(value);\n       normalize();\n       return *this;\n   }\n\n   template <class U>\n   typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial&>::type operator %=(const U& /*value*/)\n   {\n       // We can always divide by a scalar, so there is no remainder:\n       this->set_zero();\n       return *this;\n   }\n\n   template <class U>\n   polynomial& operator +=(const polynomial<U>& value)\n   {\n      addition(value);\n      normalize();\n      return *this;\n   }\n\n   template <class U>\n   polynomial& operator -=(const polynomial<U>& value)\n   {\n       subtraction(value);\n       normalize();\n       return *this;\n   }\n\n   template <typename U, typename V>\n   void multiply(const polynomial<U>& a, const polynomial<V>& b) {\n       if (!a || !b)\n       {\n           this->set_zero();\n           return;\n       }\n       std::vector<T> prod(a.size() + b.size() - 1, T(0));\n       for (unsigned i = 0; i < a.size(); ++i)\n           for (unsigned j = 0; j < b.size(); ++j)\n               prod[i+j] += a.m_data[i] * b.m_data[j];\n       m_data.swap(prod);\n   }\n\n   template <class U>\n   polynomial& operator *=(const polynomial<U>& value)\n   {\n      this->multiply(*this, value);\n      return *this;\n   }\n\n   template <typename U>\n   polynomial& operator /=(const polynomial<U>& value)\n   {\n       *this = quotient_remainder(*this, value).first;\n       return *this;\n   }\n\n   template <typename U>\n   polynomial& operator %=(const polynomial<U>& value)\n   {\n       *this = quotient_remainder(*this, value).second;\n       return *this;\n   }\n\n   template <typename U>\n   polynomial& operator >>=(U const &n)\n   {\n       BOOST_ASSERT(n <= m_data.size());\n       m_data.erase(m_data.begin(), m_data.begin() + n);\n       return *this;\n   }\n\n   template <typename U>\n   polynomial& operator <<=(U const &n)\n   {\n       m_data.insert(m_data.begin(), n, static_cast<T>(0));\n       normalize();\n       return *this;\n   }\n   \n   // Convenient and efficient query for zero.\n   bool is_zero() const\n   {\n       return m_data.empty();\n   }\n   \n   // Conversion to bool.\n#ifdef BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS\n   typedef bool (polynomial::*unmentionable_type)() const;\n\n   BOOST_FORCEINLINE operator unmentionable_type() const\n   {\n       return is_zero() ? false : &polynomial::is_zero;\n   }\n#else\n   BOOST_FORCEINLINE explicit operator bool() const\n   {\n       return !m_data.empty();\n   }\n#endif\n\n   // Fast way to set a polynomial to zero.\n   void set_zero()\n   {\n       m_data.clear();\n   }\n    \n    /** Remove zero coefficients 'from the top', that is for which there are no\n    *        non-zero coefficients of higher degree. */\n   void normalize()\n   {\n#ifndef BOOST_NO_CXX11_LAMBDAS\n      m_data.erase(std::find_if(m_data.rbegin(), m_data.rend(), [](const T& x)->bool { return x != 0; }).base(), m_data.end());\n#else\n       using namespace boost::lambda;\n       m_data.erase(std::find_if(m_data.rbegin(), m_data.rend(), _1 != T(0)).base(), m_data.end());\n#endif\n   }\n\nprivate:\n    template <class U, class R>\n    polynomial& addition(const U& value, R op)\n    {\n        if(m_data.size() == 0)\n            m_data.resize(1, 0);\n        m_data[0] = op(m_data[0], value);\n        return *this;\n    }\n\n    template <class U>\n    polynomial& addition(const U& value)\n    {\n        return addition(value, detail::plus());\n    }\n\n    template <class U>\n    polynomial& subtraction(const U& value)\n    {\n        return addition(value, detail::minus());\n    }\n\n    template <class U, class R>\n    polynomial& addition(const polynomial<U>& value, R op)\n    {\n        if (m_data.size() < value.size())\n            m_data.resize(value.size(), 0);\n        for(size_type i = 0; i < value.size(); ++i)\n            m_data[i] = op(m_data[i], value[i]);\n        return *this;\n    }\n\n    template <class U>\n    polynomial& addition(const polynomial<U>& value)\n    {\n        return addition(value, detail::plus());\n    }\n\n    template <class U>\n    polynomial& subtraction(const polynomial<U>& value)\n    {\n        return addition(value, detail::minus());\n    }\n\n    template <class U>\n    polynomial& multiplication(const U& value)\n    {\n#ifndef BOOST_NO_CXX11_LAMBDAS\n       std::transform(m_data.begin(), m_data.end(), m_data.begin(), [&](const T& x)->T { return x * value; });\n#else\n        using namespace boost::lambda;\n        std::transform(m_data.begin(), m_data.end(), m_data.begin(), ret<T>(_1 * value));\n#endif\n        return *this;\n    }\n\n    template <class U>\n    polynomial& division(const U& value)\n    {\n#ifndef BOOST_NO_CXX11_LAMBDAS\n       std::transform(m_data.begin(), m_data.end(), m_data.begin(), [&](const T& x)->T { return x / value; });\n#else\n        using namespace boost::lambda;\n        std::transform(m_data.begin(), m_data.end(), m_data.begin(), ret<T>(_1 / value));\n#endif\n        return *this;\n    }\n\n    std::vector<T> m_data;\n};\n\n\ntemplate <class T>\ninline polynomial<T> operator + (const polynomial<T>& a, const polynomial<T>& b)\n{\n   polynomial<T> result(a);\n   result += b;\n   return result;\n}\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\ntemplate <class T>\ninline polynomial<T> operator + (polynomial<T>&& a, const polynomial<T>& b)\n{\n   a += b;\n   return a;\n}\ntemplate <class T>\ninline polynomial<T> operator + (const polynomial<T>& a, polynomial<T>&& b)\n{\n   b += a;\n   return b;\n}\ntemplate <class T>\ninline polynomial<T> operator + (polynomial<T>&& a, polynomial<T>&& b)\n{\n   a += b;\n   return a;\n}\n#endif\n\ntemplate <class T>\ninline polynomial<T> operator - (const polynomial<T>& a, const polynomial<T>& b)\n{\n   polynomial<T> result(a);\n   result -= b;\n   return result;\n}\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\ntemplate <class T>\ninline polynomial<T> operator - (polynomial<T>&& a, const polynomial<T>& b)\n{\n   a -= b;\n   return a;\n}\ntemplate <class T>\ninline polynomial<T> operator - (const polynomial<T>& a, polynomial<T>&& b)\n{\n   b -= a;\n   return -b;\n}\ntemplate <class T>\ninline polynomial<T> operator - (polynomial<T>&& a, polynomial<T>&& b)\n{\n   a -= b;\n   return a;\n}\n#endif\n\ntemplate <class T>\ninline polynomial<T> operator * (const polynomial<T>& a, const polynomial<T>& b)\n{\n   polynomial<T> result;\n   result.multiply(a, b);\n   return result;\n}\n\ntemplate <class T>\ninline polynomial<T> operator / (const polynomial<T>& a, const polynomial<T>& b)\n{\n   return quotient_remainder(a, b).first;\n}\n\ntemplate <class T>\ninline polynomial<T> operator % (const polynomial<T>& a, const polynomial<T>& b)\n{\n   return quotient_remainder(a, b).second;\n}\n\ntemplate <class T, class U>\ninline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator + (polynomial<T> a, const U& b)\n{\n   a += b;\n   return a;\n}\n\ntemplate <class T, class U>\ninline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator - (polynomial<T> a, const U& b)\n{\n   a -= b;\n   return a;\n}\n\ntemplate <class T, class U>\ninline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator * (polynomial<T> a, const U& b)\n{\n   a *= b;\n   return a;\n}\n\ntemplate <class T, class U>\ninline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator / (polynomial<T> a, const U& b)\n{\n   a /= b;\n   return a;\n}\n\ntemplate <class T, class U>\ninline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator % (const polynomial<T>&, const U&)\n{\n   // Since we can always divide by a scalar, result is always an empty polynomial:\n   return polynomial<T>();\n}\n\ntemplate <class U, class T>\ninline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator + (const U& a, polynomial<T> b)\n{\n   b += a;\n   return b;\n}\n\ntemplate <class U, class T>\ninline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator - (const U& a, polynomial<T> b)\n{\n   b -= a;\n   return -b;\n}\n\ntemplate <class U, class T>\ninline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator * (const U& a, polynomial<T> b)\n{\n   b *= a;\n   return b;\n}\n\ntemplate <class T>\nbool operator == (const polynomial<T> &a, const polynomial<T> &b)\n{\n    return a.data() == b.data();\n}\n\ntemplate <class T>\nbool operator != (const polynomial<T> &a, const polynomial<T> &b)\n{\n    return a.data() != b.data();\n}\n\ntemplate <typename T, typename U>\npolynomial<T> operator >> (polynomial<T> a, const U& b)\n{\n    a >>= b;\n    return a;\n}\n\ntemplate <typename T, typename U>\npolynomial<T> operator << (polynomial<T> a, const U& b)\n{\n    a <<= b;\n    return a;\n}\n\n// Unary minus (negate).\ntemplate <class T>\npolynomial<T> operator - (polynomial<T> a)\n{\n    std::transform(a.data().begin(), a.data().end(), a.data().begin(), detail::negate());\n    return a;\n}\n\ntemplate <class T>\nbool odd(polynomial<T> const &a)\n{\n    return a.size() > 0 && a[0] != static_cast<T>(0);\n}\n\ntemplate <class T>\nbool even(polynomial<T> const &a)\n{\n    return !odd(a);\n}\n\ntemplate <class T>\npolynomial<T> pow(polynomial<T> base, int exp)\n{\n    if (exp < 0)\n        return policies::raise_domain_error(\n                \"boost::math::tools::pow<%1%>\",\n                \"Negative powers are not supported for polynomials.\",\n                base, policies::policy<>());\n        // if the policy is ignore_error or errno_on_error, raise_domain_error\n        // will return std::numeric_limits<polynomial<T>>::quiet_NaN(), which\n        // defaults to polynomial<T>(), which is the zero polynomial\n    polynomial<T> result(T(1));\n    if (exp & 1)\n        result = base;\n    /* \"Exponentiation by squaring\" */\n    while (exp >>= 1)\n    {\n        base *= base;\n        if (exp & 1)\n            result *= base;\n    }\n    return result;\n}\n\ntemplate <class charT, class traits, class T>\ninline std::basic_ostream<charT, traits>& operator << (std::basic_ostream<charT, traits>& os, const polynomial<T>& poly)\n{\n   os << \"{ \";\n   for(unsigned i = 0; i < poly.size(); ++i)\n   {\n      if(i) os << \", \";\n      os << poly[i];\n   }\n   os << \" }\";\n   return os;\n}\n\n} // namespace tools\n} // namespace math\n} // namespace boost\n\n//\n// Polynomial specific overload of gcd algorithm:\n//\n#include <boost/math/tools/polynomial_gcd.hpp>\n\n#endif // BOOST_MATH_TOOLS_POLYNOMIAL_HPP\n\n\n\n", "meta": {"hexsha": "f6c7ef11eed2d1c2aaa0c3535b3442e3c4c87ce1", "size": 20412, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/boost/math/tools/polynomial.hpp", "max_stars_repo_name": "alexhenrie/poedit", "max_stars_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "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": "deps/boost/boost/math/tools/polynomial.hpp", "max_issues_repo_name": "alexhenrie/poedit", "max_issues_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "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": "deps/boost/boost/math/tools/polynomial.hpp", "max_forks_repo_name": "alexhenrie/poedit", "max_forks_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "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": 24.3, "max_line_length": 138, "alphanum_fraction": 0.6185577112, "num_tokens": 5579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5321999971365445}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2017 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/distance_functions.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Points_off_io.h>\n\n#include <CGAL/Epick_d.h>\n#include <CGAL/Min_sphere_of_spheres_d.h>\n#include <CGAL/Min_sphere_of_points_d_traits_d.h>\n\n#include <boost/program_options.hpp>\n\n#include <string>\n#include <vector>\n#include <limits>   // infinity\n#include <utility>  // for pair\n#include <map>\n\n// -------------------------------------------------------------------------------\n// cech_complex_cgal_mini_sphere_3d is an example of each step that is required to\n// build a Cech over a Simplex_tree. Please refer to cech_persistence to see\n// how to do the same thing with the Cech_complex wrapper for less detailed\n// steps.\n// -------------------------------------------------------------------------------\n\n// Types definition\nusing Simplex_tree = Gudhi::Simplex_tree<>;\nusing Vertex_handle = Simplex_tree::Vertex_handle;\nusing Simplex_handle = Simplex_tree::Simplex_handle;\nusing Filtration_value = Simplex_tree::Filtration_value;\nusing Siblings = Simplex_tree::Siblings;\nusing Graph_t = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,\n                                      boost::property<Gudhi::vertex_filtration_t, Filtration_value>,\n                                      boost::property<Gudhi::edge_filtration_t, Filtration_value> >;\nusing Edge_t = std::pair<Vertex_handle, Vertex_handle>;\n\nusing Kernel = CGAL::Epick_d<CGAL::Dimension_tag<3> >;\nusing Point = Kernel::Point_d;\nusing Traits = CGAL::Min_sphere_of_points_d_traits_d<Kernel, Filtration_value, 3>;\nusing Min_sphere = CGAL::Min_sphere_of_spheres_d<Traits>;\n\nusing Points_off_reader = Gudhi::Points_off_reader<Point>;\n\nclass Cech_blocker {\n public:\n  bool operator()(Simplex_handle sh) {\n    std::vector<Point> points;\n#if DEBUG_TRACES\n    std::clog << \"Cech_blocker on [\";\n#endif  // DEBUG_TRACES\n    for (auto vertex : simplex_tree_.simplex_vertex_range(sh)) {\n      points.push_back(point_cloud_[vertex]);\n#if DEBUG_TRACES\n      std::clog << vertex << \", \";\n#endif  // DEBUG_TRACES\n    }\n    Min_sphere ms(points.begin(), points.end());\n    Filtration_value radius = ms.radius();\n#if DEBUG_TRACES\n    std::clog << \"] - radius = \" << radius << \" - returns \" << (radius > threshold_) << std::endl;\n#endif  // DEBUG_TRACES\n    simplex_tree_.assign_filtration(sh, radius);\n    return (radius > threshold_);\n  }\n  Cech_blocker(Simplex_tree& simplex_tree, Filtration_value threshold, const std::vector<Point>& point_cloud)\n      : simplex_tree_(simplex_tree), threshold_(threshold), point_cloud_(point_cloud) {}\n\n private:\n  Simplex_tree simplex_tree_;\n  Filtration_value threshold_;\n  std::vector<Point> point_cloud_;\n};\n\ntemplate <typename InputPointRange>\nGraph_t compute_proximity_graph(InputPointRange& points, Filtration_value threshold);\n\nvoid program_options(int argc, char* argv[], std::string& off_file_points, Filtration_value& threshold, int& dim_max);\n\nint main(int argc, char* argv[]) {\n  std::string off_file_points;\n  Filtration_value threshold;\n  int dim_max;\n\n  program_options(argc, argv, off_file_points, threshold, dim_max);\n\n  // Extract the points from the file filepoints\n  Points_off_reader off_reader(off_file_points);\n\n  // Compute the proximity graph of the points\n  Graph_t prox_graph = compute_proximity_graph(off_reader.get_point_cloud(), threshold);\n\n  // Min_sphere sph1(off_reader.get_point_cloud()[0], off_reader.get_point_cloud()[1], off_reader.get_point_cloud()[2]);\n  // Construct the Rips complex in a Simplex Tree\n  Simplex_tree st;\n  // insert the proximity graph in the simplex tree\n  st.insert_graph(prox_graph);\n  // expand the graph until dimension dim_max\n  st.expansion_with_blockers(dim_max, Cech_blocker(st, threshold, off_reader.get_point_cloud()));\n\n  std::clog << \"The complex contains \" << st.num_simplices() << \" simplices \\n\";\n  std::clog << \"   and has dimension \" << st.dimension() << \" \\n\";\n\n  // Sort the simplices in the order of the filtration\n  st.initialize_filtration();\n\n#if DEBUG_TRACES\n  std::clog << \"********************************************************************\\n\";\n  // Display the Simplex_tree - Can not be done in the middle of 2 inserts\n  std::clog << \"* The complex contains \" << st.num_simplices() << \" simplices - dimension=\" << st.dimension() << \"\\n\";\n  std::clog << \"* Iterator on Simplices in the filtration, with [filtration value]:\\n\";\n  for (auto f_simplex : st.filtration_simplex_range()) {\n    std::clog << \"   \"\n              << \"[\" << st.filtration(f_simplex) << \"] \";\n    for (auto vertex : st.simplex_vertex_range(f_simplex)) {\n      std::clog << static_cast<int>(vertex) << \" \";\n    }\n    std::clog << std::endl;\n  }\n#endif  // DEBUG_TRACES\n  return 0;\n}\n\nvoid program_options(int argc, char* argv[], std::string& off_file_points, Filtration_value& threshold, int& dim_max) {\n  namespace po = boost::program_options;\n  po::options_description hidden(\"Hidden options\");\n  hidden.add_options()(\"input-file\", po::value<std::string>(&off_file_points),\n                       \"Name of an OFF file containing a 3d point set.\\n\");\n\n  po::options_description visible(\"Allowed options\", 100);\n  visible.add_options()(\"help,h\", \"produce help message\")(\n      \"max-edge-length,r\",\n      po::value<Filtration_value>(&threshold)->default_value(std::numeric_limits<Filtration_value>::infinity()),\n      \"Maximal length of an edge for the Cech complex construction.\")(\n      \"cpx-dimension,d\", po::value<int>(&dim_max)->default_value(1),\n      \"Maximal dimension of the Cech complex we want to compute.\");\n\n  po::positional_options_description pos;\n  pos.add(\"input-file\", 1);\n\n  po::options_description all;\n  all.add(visible).add(hidden);\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(all).positional(pos).run(), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\") || !vm.count(\"input-file\")) {\n    std::clog << std::endl;\n    std::clog << \"Construct a Cech complex defined on a set of input points.\\n \\n\";\n\n    std::clog << \"Usage: \" << argv[0] << \" [options] input-file\" << std::endl << std::endl;\n    std::clog << visible << std::endl;\n    exit(-1);\n  }\n}\n\n/** Output the proximity graph of the points.\n *\n * If points contains n elements, the proximity graph is the graph\n * with n vertices, and an edge [u,v] iff the distance function between\n * points u and v is smaller than threshold.\n *\n * The type PointCloud furnishes .begin() and .end() methods, that return\n * iterators with value_type Point.\n */\ntemplate <typename InputPointRange>\nGraph_t compute_proximity_graph(InputPointRange& points, Filtration_value threshold) {\n  std::vector<Edge_t> edges;\n  std::vector<Filtration_value> edges_fil;\n\n  Kernel k;\n  Vertex_handle idx_u, idx_v;\n  Filtration_value fil;\n  idx_u = 0;\n  for (auto it_u = points.begin(); it_u != points.end(); ++it_u) {\n    idx_v = idx_u + 1;\n    for (auto it_v = it_u + 1; it_v != points.end(); ++it_v, ++idx_v) {\n      fil = k.squared_distance_d_object()(*it_u, *it_v);\n      // For Cech Complex, threshold is a radius (distance /2)\n      fil = std::sqrt(fil) / 2.;\n      if (fil <= threshold) {\n        edges.emplace_back(idx_u, idx_v);\n        edges_fil.push_back(fil);\n      }\n    }\n    ++idx_u;\n  }\n\n  Graph_t skel_graph(edges.begin(), edges.end(), edges_fil.begin(),\n                     idx_u);  // number of points labeled from 0 to idx_u-1\n\n  auto vertex_prop = boost::get(Gudhi::vertex_filtration_t(), skel_graph);\n\n  boost::graph_traits<Graph_t>::vertex_iterator vi, vi_end;\n  for (std::tie(vi, vi_end) = boost::vertices(skel_graph); vi != vi_end; ++vi) {\n    boost::put(vertex_prop, *vi, 0.);\n  }\n\n  return skel_graph;\n}\n", "meta": {"hexsha": "0e7e382b14debcbba9d036510c74f70b312781ac", "size": 8043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Simplex_tree/example/cech_complex_cgal_mini_sphere_3d.cpp", "max_stars_repo_name": "m0baxter/gudhi-devel", "max_stars_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "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/Simplex_tree/example/cech_complex_cgal_mini_sphere_3d.cpp", "max_issues_repo_name": "m0baxter/gudhi-devel", "max_issues_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "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/Simplex_tree/example/cech_complex_cgal_mini_sphere_3d.cpp", "max_forks_repo_name": "m0baxter/gudhi-devel", "max_forks_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "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": 38.3, "max_line_length": 120, "alphanum_fraction": 0.6742509014, "num_tokens": 2072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.5321999971365444}}
{"text": "/*\n *  shortest_path.cpp\n *  consensusmap\n *\n *  Created by yonghui on 11/9/07.\n *  Copyright 2007 __MyCompanyName__. All rights reserved.\n *\n */\n\n#include \"shortest_path.h\"\n#include <limits>\n#include <iostream>\n#include <stdio.h>\n#include <cmath>\n#include <map>\n#include <cstdlib>\n#include <boost/graph/strong_components.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/adjacency_list.hpp>\nusing namespace boost;\n\nnamespace consensus_map {\n    CG::~CG(){\n        if (g_ != NULL) {\n            assert(n_vertex_ != 0);\n            for (int ii = 0; ii < n_vertex_; ii++) {\n                delete[] g_[ii].edges;\n            }\n            delete[] g_;\n            g_ = NULL;\n            n_vertex_ = 0;\n        }\n    } // end of CG::~CG()\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    void CG::solve_lp(double epsilon){\n        bool no_delete = valid_solution();\n        if (no_delete) { // if there is no need to delete nodes\n            cout << \"CG::solve_lp() no need to delete nodes\" << endl;\n            return;\n        }\n        cout << \"problem size: \" << n_vertex_ << endl;\n        double max_weight = 0;\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            if (g_[ii].weight > max_weight) {\n                max_weight = g_[ii].weight;\n            }\n        }\n        // find the initial solution, which is the longest path in terms of the weights assigned\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            g_[ii].dual_val = 1 + max_weight - g_[ii].weight;\n        }\n        double dummy1;\n        vector<int> initial_path;\n        find_shortest_path(dummy1, initial_path);\n        for (vector<int>::iterator iter1 = initial_path.begin(); iter1 != initial_path.end(); ++iter1) {\n            g_[*iter1].total_flow = 1;\n        }\n        \n        double lambda = compute_lambda();\n        double alpha = (4 / (lambda * epsilon)) * log(2 * n_vertex_ / epsilon);\n        double delta = epsilon / (4 * alpha);\n\n        double crt_left = 0.0;\n        double crt_lambda = lambda;\n        int iteration = -1;\n\n        while (true) {\n            iteration++;\n            compute_dual_vals(alpha);\n\n            double middle = 0; // middle corresponds to \\vec{z}^tA\\vec{y}\n            for (int ii = 0; ii < n_vertex_; ii++) {\n                middle = middle + g_[ii].dual_val * g_[ii].total_flow;\n            }\n            \n            double right = 0; // right corresponds to \\lambda\\vec{z}^t\\vec{b}\n            for (int ii = 0; ii < n_vertex_; ii++) {\n                right = right + crt_lambda * g_[ii].dual_val * g_[ii].weight;\n            }\n            \n            vector<int> opt_path;\n            double left; // left corresponds to \\vec{z}^tA\\vec{y}\n            find_shortest_path(left, opt_path);\n            crt_left = left;\n            \n            if (iteration % 1000 == 0) {\n                cout << \"iteration \" << iteration \n                     << \"  left:\" << left \n                     << \"  middle:\" << middle \n                     << \"  right:\" << right\n                     << \"  sol:\" << 1 / crt_lambda \n                     << endl;\n            }\n\n            // check if the following condition is met or not\n            // \\vec{z}^tA\\vec{y} - C(\\vec{z}) \\le \\epsilon(\\vec{z}^tA\\vec{y} + \\lambda\\vec{z}^t\\vec{b})\n            if ((middle - left) < epsilon * (middle + right) ) {\n                cout << \"converged!\" << endl;\n                cout << \"iteration \" << iteration \n                     << \"  left:\" << left \n                     << \"  middle:\" << middle \n                     << \"  right:\" << right\n                     << \"  sol:\" << 1 / crt_lambda \n                     << endl;\n                break;\n            } else {\n                update_solution(delta, opt_path);\n                crt_lambda = compute_lambda();\n                if (crt_lambda < 0.5 * lambda) {\n                    lambda = crt_lambda;\n                    alpha = 4 / (lambda * epsilon) * log(2 * n_vertex_ / epsilon);\n                    delta = epsilon / (4 * alpha);\n                }\n            }\n        }\n        \n        // compute the normalized dual solution\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            g_[ii].nor_dual_val = g_[ii].dual_val / crt_left;\n            if (g_[ii].nor_dual_val > 1) {\n                g_[ii].nor_dual_val = 1;            \n            }\n        }\n        // as the last step, round the fractional solution to integral solutions\n        round_lp();    \n    }\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    void CG::dump(){\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            printf(\"weight: %.3f, dual_val: %.3f, total_flow: %.3f, nor_dual_val:%.3f, n_edges:%d, to_delete:%d\", \n                   g_[ii].weight,\n                   g_[ii].dual_val,\n                   g_[ii].total_flow,\n                   g_[ii].nor_dual_val,\n                   g_[ii].num_edges,\n                   g_[ii].to_delete);\n            for (int jj = 0; jj < g_[ii].num_edges; jj++) {\n                cout << \";\" << g_[ii].edges[jj].to_id << \" \" << g_[ii].edges[jj].special;\n            }\n            cout << endl;\n        }\n    }\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    V_Satellite* CG::construct_sub_graph(const vector<int>& vertices) const{\n        map<int,int> old_new;\n        int sub_size = vertices.size();\n        for (int ii = 0; ii < sub_size; ii++) {\n            old_new[vertices[ii]] = ii;\n        }\n        V_Satellite* sub_g = new V_Satellite[sub_size];\n        vector<vector<E_Satellite> > edges;\n        edges.resize(sub_size);\n        for (int ii = 0; ii < sub_size; ii++){\n            int node_id = vertices[ii];\n            for (int jj = 0; jj < g_[node_id].num_edges; jj++) {\n                int to_id = g_[node_id].edges[jj].to_id;\n                if (old_new.find(to_id) != old_new.end()) {\n                    int new_to_id = old_new[to_id];\n                    bool is_special = g_[node_id].edges[jj].special;\n                    E_Satellite new_edge = {new_to_id, is_special};\n                    edges[ii].push_back(new_edge);\n                }\n            }\n        }\n        for (int ii = 0; ii < sub_size; ii++) {\n            sub_g[ii] = g_[vertices[ii]];\n            sub_g[ii].dual_val = 0.0;\n            sub_g[ii].total_flow = 0.0;\n            sub_g[ii].nor_dual_val = 0.0;\n            sub_g[ii].to_delete = false;\n            sub_g[ii].num_edges = edges[ii].size();\n            sub_g[ii].edges = new E_Satellite[edges[ii].size()];\n            for (int jj = 0; jj < edges[ii].size(); jj++) {\n                sub_g[ii].edges[jj] = edges[ii][jj];\n            }\n        }\n        \n        return sub_g;\n    };\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    void CG::compute_dual_vals(double alpha) {\n        // compute on the log-scale first to avoid overflow\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            double dual_val = log(1 / g_[ii].weight) + (alpha * g_[ii].total_flow / g_[ii].weight);\n            g_[ii].dual_val = dual_val;\n        }\n        double max_dual = 0;\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            if (g_[ii].dual_val > max_dual) {\n                max_dual = g_[ii].dual_val;\n            }\n        }\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            g_[ii].dual_val = g_[ii].dual_val - max_dual + 50;\n            g_[ii].dual_val = exp(g_[ii].dual_val);\n        }\n    };\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    double CG::compute_lambda() {\n        double max_lambda = 0;\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            double lambda = g_[ii].total_flow / g_[ii].weight;\n            if (lambda > max_lambda) {\n                max_lambda = lambda;\n            }\n        }\n        return max_lambda;\n    };\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    \n    void CG::update_solution(double delta, vector<int> & path) {\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            g_[ii].total_flow = (1 - delta) * g_[ii].total_flow;\n        }\n        for (vector<int>::iterator iter1 = path.begin(); iter1 != path.end(); ++iter1) {\n            g_[*iter1].total_flow = g_[*iter1].total_flow + delta;\n        }\n    };\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n        \n    void CG::find_shortest_path(double& crt_cost, vector<int>& opt_path){\n        vector<int> crt_shortest_path;\n        double cost = numeric_limits<double>::max();\n        \n        DJ_node* node_status = new DJ_node[n_vertex_];\n        // run dijastra's algorithm starting from every node\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            // initialize the node_status array\n            for (int jj = 0; jj < n_vertex_; jj++) {\n                node_status[jj].parent = -1;\n                node_status[jj].visited = false;\n                node_status[jj].reachable = false;\n                node_status[jj].distance = numeric_limits<double>::max();\n            }\n            // special vertices\n            vector<int> sinks;\n            // initialize the first node;\n            node_status[ii].visited = true;\n            node_status[ii].reachable = true;\n            node_status[ii].distance = g_[ii].dual_val;\n            for (int jj = 0; jj < g_[ii].num_edges; jj++) {\n                int dest_id = g_[ii].edges[jj].to_id;\n                if (g_[ii].edges[jj].special) {\n                    sinks.push_back(dest_id);\n                } else {\n                    node_status[dest_id].distance = node_status[ii].distance + g_[dest_id].dual_val;\n                    node_status[dest_id].parent = ii;\n                    node_status[dest_id].reachable = true;\n                }\n            }\n            \n            \n            while (true) {\n                // find the closest node that still has not been visited\n                double min_dist = numeric_limits<double>::max();\n                int dest_id = -1;\n                for (int kk = 0; kk < n_vertex_; kk++) {\n                    if ((not node_status[kk].visited) and \n                        (node_status[kk].reachable) and \n                        (node_status[kk].distance < min_dist)) {\n                        min_dist = node_status[kk].distance;\n\t\t\tdest_id = kk;\n                    }\n                }\n                if (dest_id != -1) {\n                    node_status[dest_id].visited = true;\n                    for (int ll = 0; ll < g_[dest_id].num_edges; ll++) {\n                        int ll_id = g_[dest_id].edges[ll].to_id;\n                        if (not node_status[ll_id].visited) {\n                            if (node_status[ll_id].distance > (node_status[dest_id].distance + g_[ll_id].dual_val)) {\n                                node_status[ll_id].distance = node_status[dest_id].distance + g_[ll_id].dual_val;\n                                node_status[ll_id].parent = dest_id;\n                                node_status[ll_id].reachable = true;\n                            }\n                        }\n                    }\n                } else {\n                    break;\n                }\n            }\n            \n            double min_dist1 = numeric_limits<double>::max();\n            int closest_dest = -1;\n            for (vector<int>::iterator sink = sinks.begin();\n                 sink != sinks.end();\n                 ++sink) {\n                if (node_status[*sink].distance <= min_dist1) {\n                    min_dist1 = node_status[*sink].distance;\n                    closest_dest = *sink;\n                }\n            }\n            assert(closest_dest != -1);\n            if (min_dist1 < cost) {\n                cost = min_dist1;\n                crt_shortest_path.clear();\n                crt_shortest_path.push_back(closest_dest);\n                int parent = node_status[closest_dest].parent;\n                while (parent > -1) {\n                    crt_shortest_path.push_back(parent);\n                    parent = node_status[parent].parent;\n                }\n            }\n                        \n        } // end of for (dijastra to find shortest path from each node)\n        \n        crt_cost = cost;\n        assert(cost < numeric_limits<double>::max());\n        delete[] node_status;\n        opt_path = crt_shortest_path;\n        return;\n    }\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    void CG::initialize_lp_round() {\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            g_[ii].to_delete = false;\n        }\n    };\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    void CG::round_lp_randomized(vector<int> nodes){ \n        // step0 decide if the sub-problem is solved already\n\n        map<int, int> ori_2_new_map;\n        for (int ii = 0; ii < nodes.size(); ii++) {\n            ori_2_new_map[nodes[ii]] = ii;\n        }\n        \n        double total_probs = 0.0; // care should be taken when dealing with nodes that have been deleted already\n        vector<double> probs;\n        probs.resize(nodes.size());\n        for (int ii = 0; ii < nodes.size(); ii++) {\n            if (g_[nodes[ii]].to_delete) {\n                probs[ii] = 0.0;\n            } else {\n                probs[ii] = g_[nodes[ii]].nor_dual_val;\n                total_probs = total_probs + probs[ii];\n            }\n        }\n        \n        bool exist_none_special_edges = exist_no_special_edge(nodes);\n        \n        if (not exist_none_special_edges) {\n            return;\n        }\n\n        // step1: sample one node to delete\n        // random_double is a number between 0 and total_probs        \n        double random_double = ((rand() + 0.5) / (double(RAND_MAX) + 1)) * total_probs;\n        cout << \"dbg print:random_double\" << random_double / total_probs << endl;\n        double accumulated_probs = 0.0;\n        int delete_index;\n        for (int ii = 0; ii < nodes.size(); ii++) {\n            delete_index = ii;\n            if (probs[ii] == 0.0) continue;\n            accumulated_probs = accumulated_probs + probs[ii];\n            if (accumulated_probs > random_double) break;\n        }\n        \n        // step2: delete the vertex\n        g_[nodes[delete_index]].to_delete = true;\n\n        \n        // step 3: construct a graph. Find out the strongly connected components\n        typedef boost::adjacency_list<vecS,vecS,directedS> Graph;\n        Graph G(nodes.size());\n        for (int ii = 0; ii < nodes.size(); ii++) {\n            if (not g_[nodes[ii]].to_delete) {\n                for (int jj = 0; jj < g_[nodes[ii]].num_edges; jj++) {\n                    int to_id = g_[nodes[ii]].edges[jj].to_id;\n                    if ((ori_2_new_map.find(to_id) != ori_2_new_map.end()) and \n                        (not g_[to_id].to_delete)) {\n                        add_edge(ii, ori_2_new_map[to_id], G);                    \n                    }\n                }\n            }\n        }        \n        vector<int> components(nodes.size(),-1);\n        int num = strong_components(G,&components[0]);\n\n        // step4: recurse\n        vector<vector<int> > sccs;\n        sccs.resize(num);\n        for (int ii = 0; ii < nodes.size(); ii++){\n            assert(components[ii] < num);\n            assert(components[ii] >= 0);\n            sccs[components[ii]].push_back(nodes[ii]);\n        }\n        for (int ii = 0; ii < num; ii++) {\n            round_lp_randomized(sccs[ii]);\n        }\n        \n    };\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    void CG::round_lp_greedy(vector<int> nodes){ \n        // step0 decide if the sub-problem is solved already\n\n        map<int, int> ori_2_new_map;\n        for (int ii = 0; ii < nodes.size(); ii++) {\n            ori_2_new_map[nodes[ii]] = ii;\n        }\n        \n        double total_probs = 0.0; // care should be taken when dealing with nodes that have been deleted already\n        vector<double> probs;\n        probs.resize(nodes.size());\n        for (int ii = 0; ii < nodes.size(); ii++) {\n            if (g_[nodes[ii]].to_delete) {\n                probs[ii] = 0.0;\n            } else {\n                probs[ii] = g_[nodes[ii]].nor_dual_val;\n                total_probs = total_probs + probs[ii];\n            }\n        }\n        \n        bool exist_none_special_edges = exist_no_special_edge(nodes);\n        \n        if (not exist_none_special_edges) {\n            return;\n        }\n\n        // step1: sample one node to delete\n        // use a greedy approach to decide which node to delete\n        int delete_index = -1;\n        double max_prob = 0.0;\n        for (int ii = 0; ii < nodes.size(); ii++) {\n            if (probs[ii] > max_prob) {\n                delete_index = ii;\n                max_prob = probs[ii];\n            }\n        }\n        assert(delete_index != -1);\n        \n        // step2: delete the vertex\n        g_[nodes[delete_index]].to_delete = true;\n\n        \n        // step 3: construct a graph. Find out the strongly connected components\n        typedef boost::adjacency_list<vecS,vecS,directedS> Graph;\n        Graph G(nodes.size());\n        for (int ii = 0; ii < nodes.size(); ii++) {\n            if (not g_[nodes[ii]].to_delete) {\n                for (int jj = 0; jj < g_[nodes[ii]].num_edges; jj++) {\n                    int to_id = g_[nodes[ii]].edges[jj].to_id;\n                    if ((ori_2_new_map.find(to_id) != ori_2_new_map.end()) and \n                        (not g_[to_id].to_delete)) {\n                        add_edge(ii, ori_2_new_map[to_id], G);                    \n                    }\n                }\n            }\n        }        \n        vector<int> components(nodes.size(),-1);\n        int num = strong_components(G,&components[0]);\n\n        // step4: recurse\n        vector<vector<int> > sccs;\n        sccs.resize(num);\n        for (int ii = 0; ii < nodes.size(); ii++){\n            assert(components[ii] < num);\n            assert(components[ii] >= 0);\n            sccs[components[ii]].push_back(nodes[ii]);\n        }\n        for (int ii = 0; ii < num; ii++) {\n            round_lp_greedy(sccs[ii]);\n        }\n        \n    };\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    bool CG::exist_no_special_edge(const vector<int>& nodes){\n        map<int, int> ori_2_new_map;\n        for (int ii = 0; ii < nodes.size(); ii++) {\n            ori_2_new_map[nodes[ii]] = ii;\n        }\n        bool exist_none_special_edges = false;\n        for (int ii = 0; ii < nodes.size(); ii++) {\n            if (not g_[nodes[ii]].to_delete) {\n                for (int jj = 0; jj < g_[nodes[ii]].num_edges; jj++) {\n                    int to_id = g_[nodes[ii]].edges[jj].to_id;\n                    if ((ori_2_new_map.find(to_id) != ori_2_new_map.end()) and \n                        (not g_[to_id].to_delete)) {\n                        if (not g_[nodes[ii]].edges[jj].special) {\n                            exist_none_special_edges = true;\n                        }\n                    }\n                }\n            }\n        }\n        return exist_none_special_edges;\n    }\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    bool CG::valid_solution(){\n        typedef boost::adjacency_list<vecS, vecS, directedS> Graph;\n        Graph G(n_vertex_);\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            if (not g_[ii].to_delete) {\n                for (int jj = 0; jj < g_[ii].num_edges; jj++) {\n                    int to_id = g_[ii].edges[jj].to_id;\n                    if (not g_[to_id].to_delete) {\n                        add_edge(ii, to_id, G);                    \n                    }\n                }\n            }\n        }        \n        vector<int> components(n_vertex_, -1);\n        int num = strong_components(G, &components[0]);\n\n        // check each connected component being a simple component\n        vector<vector<int> > sccs;\n        sccs.resize(num);\n        for (int ii = 0; ii < n_vertex_; ii++){\n            assert(components[ii] < num);\n            assert(components[ii] >= 0);\n            sccs[components[ii]].push_back(ii);\n        }\n        for (int ii = 0; ii < num; ii++) {\n            bool none_special_edges = exist_no_special_edge(sccs[ii]);\n            if (none_special_edges) {\n                return false;\n            }\n        } \n        return true;       \n    };\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    \n    void CG::minimize_sol(){\n        bool exist_redundent = true;\n        int count = 0;\n        while (exist_redundent) {\n            exist_redundent = false;\n            for (int ii = 0; ii < n_vertex_; ii++) {\n                if (g_[ii].to_delete) {\n                    // test to put back the node\n                    g_[ii].to_delete = false;\n                    bool valid = valid_solution();\n                    if (valid) {\n                        exist_redundent = true;\n                        count++;\n                    } else {\n                        g_[ii].to_delete = true;\n                    }\n                }\n            }\n        }\n        cout << \"removed \" << count << \" redundent nodes\" << endl;\n    };\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////    \n    void CG::round_lp() {\n        vector<int> entire_set;\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            entire_set.push_back(ii);\n        }\n        initialize_lp_round();\n        round_lp_greedy(entire_set);\n        minimize_sol();\n        vector<int> greedy_sol;\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            if (g_[ii].to_delete) {\n                greedy_sol.push_back(ii);\n            }\n        }\n        initialize_lp_round();\n        round_lp_randomized(entire_set);\n        minimize_sol();\n        vector<int> randomized_sol;\n        for (int ii = 0; ii < n_vertex_; ii++) {\n            if (g_[ii].to_delete) {\n                randomized_sol.push_back(ii);\n            }\n        }\n        \n        cout << \"randomized solution size:\" << randomized_sol.size() << endl;\n        cout << \"greedy solution size:\" << greedy_sol.size() << endl;\n        initialize_lp_round();\n        if (greedy_sol.size() < randomized_sol.size()) {\n            for (int ii = 0; ii < greedy_sol.size(); ii++) {\n                g_[greedy_sol[ii]].to_delete = true;\n            }\n        } else {\n            for (int ii = 0; ii < randomized_sol.size(); ii++) {\n                g_[randomized_sol[ii]].to_delete = true;\n            }\n        }\n        \n    }\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n}\n", "meta": {"hexsha": "39bbb82af10f4556403028290a626507a2280322", "size": 23280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shortest_path.cpp", "max_stars_repo_name": "ucrbioinfo/MergeMap", "max_stars_repo_head_hexsha": "4d6caa860f66ca383c70846ac8298b65dfdc8f8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shortest_path.cpp", "max_issues_repo_name": "ucrbioinfo/MergeMap", "max_issues_repo_head_hexsha": "4d6caa860f66ca383c70846ac8298b65dfdc8f8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shortest_path.cpp", "max_forks_repo_name": "ucrbioinfo/MergeMap", "max_forks_repo_head_hexsha": "4d6caa860f66ca383c70846ac8298b65dfdc8f8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5918367347, "max_line_length": 124, "alphanum_fraction": 0.4363402062, "num_tokens": 5238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.532188834043603}}
{"text": "/* ================================================================\n *\n * PyCA Project\n *\n * Copyright (c) J. Samuel Preston, Linh K. Ha, Sarang C. Joshi. All\n * rights reserved.  See Copyright.txt or for details.\n *\n * This software is distributed WITHOUT ANY WARRANTY; without even the\n * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n * PURPOSE.  See the above copyright notice for more information.\n *\n * ================================================================ */\n\n#include <FluidKernelFFTBase.h>\n\n#include <FOpers.h>\n#include <CudaUtils.h>\n#include <boost_mem.h>\n\n// MSVC lacks a few constants and math functions\n#ifdef _MSC_VER\n#define M_PI 3.141592653589793\n#endif\n\nnamespace PyCA {\n\n// ================================================================\n// FFTLookupTable3D\n// ================================================================\n\ntemplate<class T>\nvoid \nFFTLookupTable3D<T>::\nInitTable(){\n\n    //\n    // Test that MAX_FFT_TABLE_LENGTH is big enough\n    //\n    if(mSize.x > MAX_FFT_TABLE_LENGTH || \n       mSize.y > MAX_FFT_TABLE_LENGTH || \n       mSize.z > MAX_FFT_TABLE_LENGTH)\n    {\n       throw PyCAException(__FILE__,__LINE__,\"Error, not enough static memory allocated!\");\n    }\n\n    //\n    // precompute some values\n    //\n    double sX = 2.0 * M_PI / mSize.x; \n    double sY = 2.0 * M_PI / mSize.y; \n    double sZ = 2.0 * M_PI / mSize.z; \n\n    double deltaXSq = mSp.x * mSp.x;\n    double deltaYSq = mSp.y * mSp.y;\n    double deltaZSq = mSp.z * mSp.z;\n\n    //\n    // fill in luts\n    //\n    for (size_t x = 0; x < (size_t)mSize.x; ++x) {\n        mCosWX[x] = (2.0 * cos(sX * static_cast<float>(x)) - 2.0) / deltaXSq;\n        mSinWX[x] = sin(sX * static_cast<float>(x)) / mSp.x;\n    }\n\n    for (size_t y = 0; y < (size_t)mSize.y; ++y) {\n        mCosWY[y] = (2.0 * cos(sY * static_cast<float>(y)) - 2.0) / deltaYSq;\n        mSinWY[y] = sin(sY * static_cast<float>(y)) / mSp.y;\n    }\n\n    for (size_t z = 0; z < (size_t)mSize.z; ++z) {\n        mCosWZ[z] = (2.0 * cos(sZ * static_cast<float>(z)) - 2.0) / deltaZSq;\n        mSinWZ[z] = sin(sZ * static_cast<float>(z)) / mSp.z;\n    }\n}\n    \ntemplate<class T>\nvoid \nFFTLookupTable3D<T>::\nAllocate(){\n    mCosWX = new T [MAX_FFT_TABLE_LENGTH];\n    mCosWY = new T [MAX_FFT_TABLE_LENGTH];\n    mCosWZ = new T [MAX_FFT_TABLE_LENGTH];\n  \n    mSinWX = new T [MAX_FFT_TABLE_LENGTH];\n    mSinWY = new T [MAX_FFT_TABLE_LENGTH];\n    mSinWZ = new T [MAX_FFT_TABLE_LENGTH];\n}\n\ntemplate<class T>\nvoid \nFFTLookupTable3D<T>::\nsetSize(const Vec3Di& size, \n\tconst Vec3Df& spacing)\n{\n    mSize = size;\n    mSp   = spacing;\n    InitTable();\n}\n\ntemplate<class T>\nvoid \nFFTLookupTable3D<T>::\nClear(){\n    delete []mCosWX;\n    delete []mCosWY;\n    delete []mCosWZ;\n\n    delete []mSinWX;\n    delete []mSinWY;\n    delete []mSinWZ;\n}\n\n// ================================================================\n// FluidKernelFFTBase\n// ================================================================\n\ntemplate<int mode, MemoryType mType, class T>\nFluidKernelFFTBase<mode, mType, T>::\nFluidKernelFFTBase()\n  :mAlpha(1.0), mBeta(0.0), mGamma(0.0), mLPow(1.0),\n   mDivergenceFree(false),\n   mHasFFTPlan(false),\n   mSize(0,0,0), mSpacing(0,0,0),\n   mComplexSize(0),\n   mAllocateSize(0),\n   mFFTArrayX(NULL),\n   mFFTArrayY(NULL),\n   mFFTArrayZ(NULL)\n{\n    \n}\n\n\ntemplate<int mode, MemoryType mType, class T>\nFluidKernelFFTBase<mode, mType, T>::\n~FluidKernelFFTBase()\n{\n}\n\ntemplate<int mode, MemoryType mType, class T>\nvoid \nFluidKernelFFTBase<mode, mType, T>::\nsetGrid(const GridInfo& grid)\n{\n    this->setSize(grid);\n}\n\ntemplate<int mode, MemoryType mType, class T>\nvoid\nFluidKernelFFTBase<mode, mType, T>::setSize(const GridInfo& g)\n{\n  \n    Vec3Di newSize   = g.size();\n    Vec3Df newSpacing= g.spacing();\n\n    bool changeSize    = (mSize    != newSize);\n    bool changeSpacing = (mSpacing != newSpacing);\n\n    // TEST\n    if(mType != MEM_HOST){\n\tCudaUtils::CheckCUDAError(__FILE__, __LINE__);\n    }\n    // END TEST\n\n    if (changeSize) {\n        mSize = newSize;\n\n        mComplexSize   = mSize;\n        mComplexSize.x = mSize.x/2+1;\n\n        size_t n = mComplexSize.prod();\n        if ( n > mAllocateSize)\n            Alloc(n);\n    }\n\n    if (changeSpacing) {\n        mSpacing  = newSpacing;\n    }\n    \n    // recompute the lookup table\n    if (changeSize || changeSpacing)\n        mLookupTable.setSize(mSize, mSpacing);\n\n    // TEST\n    if(mType != MEM_HOST){\n\tCudaUtils::CheckCUDAError(__FILE__, __LINE__);\n    }\n    // END TEST\n\n    // create FFT plan\n    if (changeSize) {\n        if (mHasFFTPlan)\n            DestroyFFTPlan();\n        CreateFFTPlan();\n    }\n}\n\ntemplate<int mode, MemoryType mType, class T>\nvoid \nFluidKernelFFTBase<mode, mType, T>::\nAlloc(size_t n){\n    mFFTArray = CreateSharedArray<mType, ComplexT<T> >(3*n);\n    mFFTArrayX = &(mFFTArray.get()[0]);\n    mFFTArrayY = &(mFFTArray.get()[n]);\n    mFFTArrayZ = &(mFFTArray.get()[2*n]);\n    mAllocateSize = n;\n}\n\ntemplate<int mode, MemoryType mType, class T>\nvoid \nFluidKernelFFTBase<mode, mType, T>::\nApplyImpl(T* dataX, T* dataY, T* dataZ, bool inverseOp, StreamT stream)\n{\n    //1. Compute FFT of the data, store result in mFFTArray buffers\n    // convert the input from real to frequency(complex image)\n    toFrequencyDomain(dataX, dataY, dataZ, stream);\n\n    //2. Solve system\n    if (mLPow == floor(mLPow)) {\n        size_t nPow = (size_t) mLPow;\n        for (size_t i=0; i < nPow; ++i)\n            frequencyDomainApply(inverseOp, stream);\n    }\n\n    //3. convert the output back to time domain\n    toSpaceDomain(dataX, dataY, dataZ, stream);\n\n};\n\ntemplate<int mode, MemoryType mType, class T>\nvoid \nFluidKernelFFTBase<mode, mType, T>::\nApply(Field3D& out, const Field3D& in, \n      bool inverseOp, StreamT stream)\n{\n    MK_CHECK_REFSIZE_2(mSize, out, in);\n    //size_t nElems = mSize.prod();\n    //FieldOpers<mode>::MulC(out, in, 1.f / nElems, stream);\n    Opers::Copy(out, in, NULL);\n    ApplyImpl(out.x, out.y, out.z, inverseOp, stream);\n}\n\ntemplate<int mode, MemoryType mType, class T>\nvoid \nFluidKernelFFTBase<mode, mType, T>::\nApply(Field3D& out, bool inverseOp, StreamT stream){\n    MK_CHECK_REFSIZE_1(mSize, out);\n    //size_t nElems = mSize.prod();\n    //FieldOpers<mode>::MulC_I(out, 1.f / nElems, stream);\n    ApplyImpl(out.x, out.y, out.z, inverseOp, stream);\n}\n\n//--------------------------------------------------------------------------------\n/**\n * f = Lv\n * \n * v field is overwritten in this operation\n */\ntemplate<int mode, MemoryType mType, class T>\nvoid \nFluidKernelFFTBase<mode, mType, T>::\napplyOperator(Field3D& f, const Field3D& v, StreamT stream){\n    Apply(f, v, false, stream);\n}\n\n/**\n * v = Kf\n * \n * f field is overwritten in this operation\n */\ntemplate<int mode, MemoryType mType, class T>\nvoid \nFluidKernelFFTBase<mode, mType, T>::\napplyInverseOperator(Field3D& v, const Field3D& f, StreamT stream){\n    Apply(v, f, true, stream);\n}\n    \n\n/**\n * f = Lv\n * \n * v field is overwritten in this operation (holds f).\n */\ntemplate<int mode, MemoryType mType, class T>\nvoid \nFluidKernelFFTBase<mode, mType, T>::\napplyOperator(Field3D& f, StreamT stream){\n    Apply(f, false, stream);\n}\n\n/**\n * v = Kf\n * \n * f field is overwritten in this operation (holds v).\n */\ntemplate<int mode, MemoryType mType, class T>\nvoid \nFluidKernelFFTBase<mode, mType, T>::\napplyInverseOperator(Field3D& v, StreamT stream){\n    Apply(v, true, stream);\n}\n\n// template instantiations\ntemplate class FluidKernelFFTBase<EXEC_CPU, MEM_HOST, float>;\n#ifdef CUDA_ENABLED\ntemplate class FluidKernelFFTBase<EXEC_GPU, MEM_DEVICE, float>;\n#endif\n\n}; // end namespace PyCA\n", "meta": {"hexsha": "3ec85533ff3102d06177421b87f778ea6c1e719e", "size": 7597, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "3rd_party_software/pyca/Code/Cxx/src/alg/FluidKernelFFTBase.cxx", "max_stars_repo_name": "ninamiolane/quicksilver", "max_stars_repo_head_hexsha": "1baf251360dadea0afa3daaa09942d9d2d7c71fb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 126.0, "max_stars_repo_stars_event_min_datetime": "2017-04-06T03:19:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T07:44:09.000Z", "max_issues_repo_path": "3rd_party_software/pyca/Code/Cxx/src/alg/FluidKernelFFTBase.cxx", "max_issues_repo_name": "ninamiolane/quicksilver", "max_issues_repo_head_hexsha": "1baf251360dadea0afa3daaa09942d9d2d7c71fb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-09-22T01:46:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-29T07:22:44.000Z", "max_forks_repo_path": "3rd_party_software/pyca/Code/Cxx/src/alg/FluidKernelFFTBase.cxx", "max_forks_repo_name": "ninamiolane/quicksilver", "max_forks_repo_head_hexsha": "1baf251360dadea0afa3daaa09942d9d2d7c71fb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2017-04-03T17:14:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T16:00:03.000Z", "avg_line_length": 24.5064516129, "max_line_length": 91, "alphanum_fraction": 0.6031328156, "num_tokens": 2222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.6150878414043816, "lm_q1q2_score": 0.532188809008183}}
{"text": "/**\n * @file sgd_test.cpp\n * @author Ryan Curtin\n *\n * Test file for SGD (stochastic gradient descent).\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/optimizers/sgd/sgd.hpp>\n#include <mlpack/core/optimizers/problems/generalized_rosenbrock_function.hpp>\n#include <mlpack/core/optimizers/problems/sgd_test_function.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace std;\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::optimization;\nusing namespace mlpack::optimization::test;\n\nBOOST_AUTO_TEST_SUITE(SGDTest);\n\nBOOST_AUTO_TEST_CASE(SimpleSGDTestFunction)\n{\n  SGDTestFunction f;\n  StandardSGD s(0.0003, 1, 5000000, 1e-9, true);\n\n  arma::mat coordinates = f.GetInitialPoint();\n  double result = s.Optimize(f, coordinates);\n\n  BOOST_REQUIRE_CLOSE(result, -1.0, 0.05);\n  BOOST_REQUIRE_SMALL(coordinates[0], 1e-3);\n  BOOST_REQUIRE_SMALL(coordinates[1], 1e-7);\n  BOOST_REQUIRE_SMALL(coordinates[2], 1e-7);\n}\n\nBOOST_AUTO_TEST_CASE(GeneralizedRosenbrockTest)\n{\n  // Loop over several variants.\n  for (size_t i = 10; i < 50; i += 5)\n  {\n    // Create the generalized Rosenbrock function.\n    GeneralizedRosenbrockFunction f(i);\n\n    StandardSGD s(0.001, 1, 0, 1e-15, true);\n\n    arma::mat coordinates = f.GetInitialPoint();\n    double result = s.Optimize(f, coordinates);\n\n    BOOST_REQUIRE_SMALL(result, 1e-10);\n    for (size_t j = 0; j < i; ++j)\n      BOOST_REQUIRE_CLOSE(coordinates[j], (double) 1.0, 1e-3);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b4015daef053ca847babb84a2c7e8f420955c4ed", "size": 1788, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/sgd_test.cpp", "max_stars_repo_name": "chigur/mlpack", "max_stars_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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-05-02T21:10:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T21:10:55.000Z", "max_issues_repo_path": "src/mlpack/tests/sgd_test.cpp", "max_issues_repo_name": "chigur/mlpack", "max_issues_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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/sgd_test.cpp", "max_forks_repo_name": "chigur/mlpack", "max_forks_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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.8387096774, "max_line_length": 78, "alphanum_fraction": 0.7321029083, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5321875077854141}}
{"text": "#include <algorithm>\n#include <queue>\n#include <boost/math/constants/constants.hpp>\n#include <Eigen/Sparse>\n#include <Euclid/Geometry/TriMeshGeometry.h>\n#include <Euclid/Math/Numeric.h>\n#include <Euclid/Topology/MeshTopology.h>\n\nnamespace Euclid\n{\n\nnamespace _impl\n{\n\ntemplate<typename Mesh, typename VertexCurvatureMap>\nbool check_gauss_bonnet(const Mesh& mesh, VertexCurvatureMap vcm)\n{\n    using Scalar =\n        typename boost::property_traits<VertexCurvatureMap>::value_type;\n    Scalar sum = 0;\n    for (auto v : vertices(mesh)) {\n        sum += get(vcm, v);\n    }\n    auto chi = euler_characteristic(mesh);\n    return eq_almost(sum, boost::math::constants::two_pi<Scalar>() * chi);\n}\n\ntemplate<typename Mesh, typename VertexRadiusMap, typename EdgeWeightMap>\ndecltype(auto) elen_from_circle_packing_metric(\n    const Mesh& mesh,\n    typename boost::graph_traits<Mesh>::edge_descriptor e,\n    VertexRadiusMap vrm,\n    EdgeWeightMap ewm)\n{\n    auto h = halfedge(e, mesh);\n    auto s = source(h, mesh);\n    auto t = target(h, mesh);\n    auto rs = get(vrm, s);\n    auto rt = get(vrm, t);\n    auto cosw = get(ewm, e);\n    auto l2 = rs * rs + rt * rt + 2 * rs * rt * cosw;\n    l2 = std::max(l2, static_cast<decltype(l2)>(0));\n    return std::sqrt(l2);\n}\n\ntemplate<typename T>\nT cos12(T l1, T l2, T l3)\n{\n    auto cos = (l1 * l1 + l2 * l2 - l3 * l3) / (2 * l1 * l2);\n    cos = std::min(cos, static_cast<T>(1));\n    cos = std::max(cos, static_cast<T>(-1));\n    return cos;\n}\n\ntemplate<typename Mesh, typename T, typename EIMap>\nT corner_angle(const Mesh& mesh,\n               typename boost::graph_traits<Mesh>::halfedge_descriptor h1,\n               const std::vector<T>& lengths,\n               EIMap eimap)\n{\n    auto h2 = next(h1, mesh);\n    auto h3 = prev(h1, mesh);\n    auto e1 = edge(h1, mesh);\n    auto e2 = edge(h2, mesh);\n    auto e3 = edge(h3, mesh);\n    auto l1 = lengths[get(eimap, e1)];\n    auto l2 = lengths[get(eimap, e2)];\n    auto l3 = lengths[get(eimap, e3)];\n    auto c = _impl::cos12(l1, l2, l3);\n    return std::acos(c);\n}\n\ntemplate<typename Mesh, typename T, typename EIMap>\nT gaussian(const Mesh& mesh,\n           typename boost::graph_traits<Mesh>::vertex_descriptor v,\n           const std::vector<T>& lengths,\n           EIMap eimap)\n{\n    T k;\n    if (CGAL::is_border(v, mesh)) {\n        k = boost::math::constants::pi<T>();\n    }\n    else {\n        k = boost::math::constants::two_pi<T>();\n    }\n    for (auto h : halfedges_around_target(v, mesh)) {\n        if (!CGAL::is_border(h, mesh)) {\n            k -= corner_angle(mesh, h, lengths, eimap);\n        }\n    }\n    return k;\n}\n\ntemplate<typename Mesh,\n         typename VertexRadiusMap,\n         typename EdgeIndexMap,\n         typename T>\nvoid solve_power_circle(const Mesh& mesh,\n                        typename boost::graph_traits<Mesh>::face_descriptor f,\n                        VertexRadiusMap vrm,\n                        EdgeIndexMap eim,\n                        const std::vector<T>& lengths,\n                        std::vector<T>& weights)\n{\n    // construct local coordinates for a triangle\n    auto h = *(halfedges_around_face(halfedge(f, mesh), mesh).first);\n    auto v = target(h, mesh);\n    T l1 = lengths[get(eim, edge(h, mesh))];\n    T x1 = 0;\n    T y1 = 0;\n    T r1 = get(vrm, v);\n\n    h = next(h, mesh);\n    v = target(h, mesh);\n    T l2 = lengths[get(eim, edge(h, mesh))];\n    T x2 = l2;\n    T y2 = 0;\n    T r2 = get(vrm, v);\n\n    h = next(h, mesh);\n    v = target(h, mesh);\n    T l3 = lengths[get(eim, edge(h, mesh))];\n    T cos = cos12(l1, l2, l3);\n    T sin = std::sqrt(1 - cos * cos);\n    T x3 = cos * l1;\n    T y3 = sin * l1;\n    T r3 = get(vrm, v);\n\n    // solve the power circle in local coordinates\n    auto x1_2 = x1 * x1;\n    auto y1_2 = y1 * y1;\n    auto r1_2 = r1 * r1;\n    auto x2_2 = x2 * x2;\n    auto y2_2 = y2 * y2;\n    auto r2_2 = r2 * r2;\n    auto x3_2 = x3 * x3;\n    auto y3_2 = y3 * y3;\n    auto r3_2 = r3 * r3;\n    auto a = -x1_2 + x2_2 - y1_2 + y2_2 + r1_2 - r2_2;\n    auto b = -x1_2 + x3_2 - y1_2 + y3_2 + r1_2 - r3_2;\n    auto c = 2 * ((y1 - y2) * (x3 - x1) - (y1 - y3) * (x2 - x1));\n\n    auto y = ((x2 - x1) * b - (x3 - x1) * a) / c;\n    auto x = (2 * (y1 - y3) * y + b) / (2 * (x3 - x1));\n\n    // calculate the height from the center to each edge\n    auto d1 = std::sqrt((x1 - x) * (x1 - x) + (y1 - y) * (y1 - y));\n    auto d2 = std::sqrt((x2 - x) * (x2 - x) + (y2 - y) * (y2 - y));\n    auto d3 = std::sqrt((x3 - x) * (x3 - x) + (y3 - y) * (y3 - y));\n\n    auto cos1 = cos12(d3, l1, d1);\n    auto sin1 = std::sqrt(1 - cos1 * cos1);\n    auto height1 = d3 * sin1;\n    h = next(h, mesh);\n    weights[get(eim, edge(h, mesh))] += height1;\n\n    auto cos2 = cos12(d1, l2, d2);\n    auto sin2 = std::sqrt(1 - cos2 * cos2);\n    auto height2 = d1 * sin2;\n    h = next(h, mesh);\n    weights[get(eim, edge(h, mesh))] += height2;\n\n    auto cos3 = cos12(d2, l3, d3);\n    auto sin3 = std::sqrt(1 - cos3 * cos3);\n    auto height3 = d2 * sin3;\n    h = next(h, mesh);\n    weights[get(eim, edge(h, mesh))] += height3;\n}\n\ntemplate<typename Mesh,\n         typename VertexRadiusMap,\n         typename EdgeWeightMap,\n         typename VertexIndexMap,\n         typename EdgeIndexMap,\n         typename T>\nvoid hessian(const Mesh& mesh,\n             VertexRadiusMap vrm,\n             EdgeWeightMap ewm,\n             VertexIndexMap vim,\n             EdgeIndexMap eim,\n             const std::vector<T>& lengths,\n             Eigen::SparseMatrix<T>& H)\n{\n    using Triplet = Eigen::Triplet<T>;\n    using Triplets = std::vector<Triplet>;\n\n    std::vector<T> weights(num_edges(mesh), 0);\n    for (auto f : faces(mesh)) {\n        solve_power_circle(mesh, f, vrm, eim, lengths, weights);\n    }\n\n    Triplets triplets;\n    triplets.reserve(num_halfedges(mesh) + num_vertices(mesh));\n    for (auto v : vertices(mesh)) {\n        T sum = 0;\n        auto vi_idx = get(vim, v);\n        for (auto h : halfedges_around_target(v, mesh)) {\n            auto vj_idx = get(vim, source(h, mesh));\n            auto eidx = get(eim, edge(h, mesh));\n            auto w = weights[eidx] / lengths[eidx];\n            sum += w;\n            triplets.emplace_back(vi_idx, vj_idx, -w);\n        }\n        triplets.emplace_back(vi_idx, vi_idx, sum);\n    }\n\n    H.resize(num_vertices(mesh), num_vertices(mesh));\n    H.setFromTriplets(triplets.begin(), triplets.end());\n    H.makeCompressed();\n}\n\ntemplate<typename Mesh,\n         typename VertexRadiusMap,\n         typename EdgeWeightMap,\n         typename SEM,\n         typename SVM,\n         typename VertexUVMap,\n         typename VertexParameterizedMap>\nvoid embed_circle_packing_metric(const Mesh& mesh,\n                                 VertexRadiusMap vrm,\n                                 EdgeWeightMap ewm,\n                                 CGAL::Seam_mesh<Mesh, SEM, SVM>& seam_mesh,\n                                 VertexUVMap uvm,\n                                 VertexParameterizedMap vpm)\n{\n    using Seam_mesh = CGAL::Seam_mesh<Mesh, SEM, SVM>;\n    using fd = typename boost::graph_traits<Seam_mesh>::face_descriptor;\n    using Point_2 = typename boost::property_traits<VertexUVMap>::value_type;\n    using Point_3 = typename CGAL::Kernel_traits<Point_2>::Kernel::Point_3;\n    using FT = typename CGAL::Kernel_traits<Point_2>::Kernel::FT;\n\n    // mesh and seam_mesh have the same number of faces\n    // seam_mesh does not have face_index, use mesh's\n    auto fimap = get(boost::face_index, mesh);\n    std::vector<bool> visited(num_faces(seam_mesh), false);\n    std::queue<fd> queue;\n\n    // flatten the root face\n    auto froot = *(faces(seam_mesh).first);\n    auto hroot = halfedge(froot, seam_mesh);\n    auto vroot = target(hroot, seam_mesh);\n    auto l0 = _impl::elen_from_circle_packing_metric(\n        mesh, edge(hroot.tmhd, mesh), vrm, ewm);\n    put(uvm, vroot, Point_2(0, 0));\n    put(vpm, vroot, true);\n    hroot = next(hroot, seam_mesh);\n    vroot = target(hroot, seam_mesh);\n    auto l1 = _impl::elen_from_circle_packing_metric(\n        mesh, edge(hroot.tmhd, mesh), vrm, ewm);\n    put(uvm, vroot, Point_2(l1, 0));\n    put(vpm, vroot, true);\n    hroot = next(hroot, seam_mesh);\n    vroot = target(hroot, seam_mesh);\n    auto l2 = _impl::elen_from_circle_packing_metric(\n        mesh, edge(hroot.tmhd, mesh), vrm, ewm);\n    auto cos0 = _impl::cos12(l0, l1, l2);\n    auto sin0 = std::sqrt(1 - cos0 * cos0);\n    put(uvm, vroot, Point_2(cos0 * l0, sin0 * l0));\n    put(vpm, vroot, true);\n    visited[get(fimap, face(hroot.tmhd, mesh))] = true;\n    queue.push(froot);\n    size_t nv = 3;\n    size_t nf = 1;\n\n    // propogate the flattening\n    while (!queue.empty()) {\n        auto f = queue.front();\n        queue.pop();\n        for (auto h :\n             halfedges_around_face(halfedge(f, seam_mesh), seam_mesh)) {\n            auto hoppo = opposite(h, seam_mesh);\n            if (!CGAL::is_border(hoppo, seam_mesh)) {\n                auto foppo_idx = get(fimap, face(hoppo.tmhd, mesh));\n                if (visited[foppo_idx]) {\n                    continue;\n                }\n                visited[foppo_idx] = true;\n                queue.push(face(hoppo, seam_mesh));\n                ++nf;\n\n                auto vk = target(next(hoppo, seam_mesh), seam_mesh);\n                if (get(vpm, vk)) {\n                    continue;\n                }\n                put(vpm, vk, true);\n                ++nv;\n\n                // use the intersection point of two circles as the next\n                // flattened vertex's uv-coordinate\n                auto vs = source(hoppo, seam_mesh);\n                auto vt = target(hoppo, seam_mesh);\n                auto ps = get(uvm, vs);\n                auto pt = get(uvm, vt);\n                auto ls = _impl::elen_from_circle_packing_metric(\n                    mesh, edge(prev(hoppo.tmhd, mesh), mesh), vrm, ewm);\n                auto lt = _impl::elen_from_circle_packing_metric(\n                    mesh, edge(next(hoppo.tmhd, mesh), mesh), vrm, ewm);\n                auto d = std::sqrt((pt - ps).squared_length());\n                auto a = (ls * ls - lt * lt + d * d) / (2 * d);\n                auto h =\n                    std::sqrt(std::max(ls * ls - a * a, static_cast<FT>(0)));\n                auto pm = ps + a * (pt - ps) / d;\n                auto u = pm.x() + h * (pt.y() - ps.y()) / d;\n                auto v = pm.y() - h * (pt.x() - ps.x()) / d;\n                assert(!std::isnan(u));\n                assert(!std::isnan(v));\n\n                // check orientation\n                Point_3 pi(ps.x(), ps.y(), 0);\n                Point_3 pj(pt.x(), pt.y(), 0);\n                Point_3 pk(u, v, 0);\n                if (CGAL::cross_product(pj - pi, pk - pi).z() > 0) {\n                    put(uvm, vk, Point_2(u, v));\n                }\n                else {\n                    u = pm.x() - h * (pt.y() - ps.y()) / d;\n                    v = pm.y() + h * (pt.x() - ps.x()) / d;\n                    put(uvm, vk, Point_2(u, v));\n                }\n            }\n        }\n    }\n    assert(nv == num_vertices(seam_mesh));\n    assert(nf == num_faces(seam_mesh));\n}\n\n} // namespace _impl\n\ntemplate<typename Mesh, typename VertexRadiusMap, typename EdgeWeightMap>\nvoid circle_packing_metric(Mesh& mesh, VertexRadiusMap vrm, EdgeWeightMap ewm)\n{\n    using Scalar = typename boost::property_traits<VertexRadiusMap>::value_type;\n    auto eimap = get(boost::edge_index, mesh);\n\n    // compute edge lengths\n    std::vector<Scalar> lens;\n    lens.reserve(num_edges(mesh));\n    for (auto e : edges(mesh)) {\n        auto l = edge_length(e, mesh);\n        lens.push_back(l);\n    }\n\n    // compute vertex radii\n    for (auto v : vertices(mesh)) {\n        Scalar radius;\n        bool initialized = false;\n        for (auto h : halfedges_around_target(v, mesh)) {\n            if (!CGAL::is_border(h, mesh)) {\n                auto e1 = get(eimap, edge(h, mesh));\n                auto e2 = get(eimap, edge(next(h, mesh), mesh));\n                auto e3 = get(eimap, edge(prev(h, mesh), mesh));\n                auto r = (lens[e1] + lens[e2] - lens[e3]) / 2;\n                if (!initialized) {\n                    radius = r;\n                    initialized = true;\n                }\n                else {\n                    radius = std::min(radius, r);\n                }\n            }\n        }\n        put(vrm, v, radius);\n    }\n\n    // compute edge weights\n    for (auto e : edges(mesh)) {\n        auto h = halfedge(e, mesh);\n        auto s = source(h, mesh);\n        auto t = target(h, mesh);\n        auto rs = get(vrm, s);\n        auto rt = get(vrm, t);\n        auto l = lens[get(eimap, e)];\n        // don't use cos12 since it's okay if cosw > 1\n        auto cosw = (l * l - rs * rs - rt * rt) / (2 * rs * rt);\n        put(ewm, e, cosw);\n    }\n}\n\ntemplate<typename Mesh,\n         typename VertexRadiusMap,\n         typename EdgeWeightMap,\n         typename SEM,\n         typename SVM,\n         typename VertexUVMap>\nvoid embed_circle_packing_metric(const Mesh& mesh,\n                                 VertexRadiusMap vrm,\n                                 EdgeWeightMap ewm,\n                                 CGAL::Seam_mesh<Mesh, SEM, SVM>& seam_mesh,\n                                 VertexUVMap uvm)\n{\n    using Seam_mesh = CGAL::Seam_mesh<Mesh, SEM, SVM>;\n    using Vertex = typename boost::graph_traits<Seam_mesh>::vertex_descriptor;\n    using VPM = std::map<Vertex, bool>;\n\n    VPM vpm;\n    _impl::embed_circle_packing_metric(\n        mesh,\n        vrm,\n        ewm,\n        seam_mesh,\n        uvm,\n        boost::associative_property_map<VPM>(vpm));\n}\n\ntemplate<typename Mesh,\n         typename VertexRadiusMap,\n         typename EdgeWeightMap,\n         typename VertexCurvatureMap>\nRicciFlowSolverStatus ricci_flow(Mesh& mesh,\n                                 VertexRadiusMap vrm,\n                                 EdgeWeightMap ewm,\n                                 VertexCurvatureMap vcm,\n                                 const RicciFlowSolverSettings& settings)\n{\n    std::cout << \"==========Ricci flow==========\" << std::endl\n              << \"solver type: \";\n    if (settings.type == RicciFlowSolverType::GradientDescent) {\n        std::cout << \"gradient descent\" << std::endl;\n    }\n    else {\n        std::cout << \"Newton\" << std::endl;\n    }\n    std::cout << \"step: \" << settings.step << std::endl\n              << \"eps: \" << settings.eps << std::endl\n              << \"max iters: \" << settings.max_iters << std::endl\n              << \"==============================\" << std::endl;\n\n    if (!_impl::check_gauss_bonnet(mesh, vcm)) {\n        std::cerr << \"Error: target curvatures are not admissible.\"\n                  << std::endl;\n        return RicciFlowSolverStatus::InvalidInput;\n    }\n\n    using Scalar = typename boost::property_traits<VertexRadiusMap>::value_type;\n    using SpMat = Eigen::SparseMatrix<Scalar>;\n    using Vec = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    auto vimap = get(boost::vertex_index, mesh);\n    auto eimap = get(boost::edge_index, mesh);\n    std::vector<Scalar> lengths(num_edges(mesh));\n    auto type = settings.type;\n\n    Eigen::SimplicialLDLT<SpMat> solver;\n    if (settings.type == RicciFlowSolverType::Newton) {\n        // prefactor the solver using graph Laplacian\n        auto L = graph_laplacian_matrix(mesh);\n        solver.analyzePattern(L);\n    }\n\n    for (auto iter = 0; iter < settings.max_iters; ++iter) {\n        // update edge lengths from current vertex radii and edge weights\n        for (auto e : edges(mesh)) {\n            lengths[get(eimap, e)] =\n                _impl::elen_from_circle_packing_metric(mesh, e, vrm, ewm);\n        }\n\n        // compute the gradients based on solver type\n        Scalar kdiff_max = 0;\n        Vec grads = Vec::Zero(num_vertices(mesh));\n        if (type == RicciFlowSolverType::Newton) {\n            // FIXME: Newton is not working\n            assert(type == RicciFlowSolverType::GradientDescent);\n            // SpMat H;\n            // _impl::hessian(mesh, vrm, ewm, vimap, eimap, lengths, H);\n            // solver.factorize(H);\n            // Vec b(num_vertices(mesh));\n            // for (auto v : vertices(mesh)) {\n            //     auto kdiff =\n            //         get(vcm, v) - _impl::gaussian(mesh, v, lengths, eimap);\n            //     b(get(vimap, v)) = kdiff;\n            //     kdiff_max = std::max(std::abs(kdiff), kdiff_max);\n            // }\n            // grads = solver.solve(b);\n        }\n        else { // GradientDescent\n            for (auto v : vertices(mesh)) {\n                auto kdiff =\n                    get(vcm, v) - _impl::gaussian(mesh, v, lengths, eimap);\n                grads(get(vimap, v)) = kdiff * settings.step;\n                kdiff_max = std::max(std::abs(kdiff), kdiff_max);\n            }\n        }\n\n        // optimize the Ricci energy\n        for (auto v : vertices(mesh)) {\n            auto u = std::log(get(vrm, v)); // convert radius to scaling factor\n            u += grads(get(vimap, v));      // Ricci flow\n            put(vrm, v, std::exp(u));       // convert back to vertex radius\n        }\n\n        // stopping criterion\n        if (settings.verbose) {\n            std::cout << \"iter: \" << iter << \", error: \" << kdiff_max\n                      << std::endl;\n        }\n        if (kdiff_max < settings.eps) {\n            std::cout << \"Optimization done.\" << std::endl;\n            return RicciFlowSolverStatus::Optimal;\n        }\n    }\n    std::cout << \"Max iterations reached.\" << std::endl;\n    return RicciFlowSolverStatus::Suboptimal;\n}\n\ntemplate<typename Mesh, typename SEM, typename SVM>\nRicci_flow_parameterizer3<Mesh, SEM, SVM>::Ricci_flow_parameterizer3(\n    const Mesh& mesh)\n    : _underlying_mesh(mesh), _vrpm(_vrm), _ewpm(_ewm), _vcpm(_vcm)\n{\n    circle_packing_metric(_underlying_mesh, _vrpm, _ewpm);\n    for (auto v : vertices(mesh)) {\n        put(_vcpm, v, static_cast<Scalar>(0));\n    }\n}\n\ntemplate<typename Mesh, typename SEM, typename SVM>\nvoid Ricci_flow_parameterizer3<Mesh, SEM, SVM>::set_solver_settings(\n    const RicciFlowSolverSettings& settings)\n{\n    _settings = settings;\n}\n\ntemplate<typename Mesh, typename SEM, typename SVM>\nvoid Ricci_flow_parameterizer3<Mesh, SEM, SVM>::add_cone(\n    typename boost::graph_traits<Mesh>::vertex_descriptor v,\n    Scalar k)\n{\n    put(_vcpm, v, k * boost::math::constants::pi<Scalar>());\n}\n\ntemplate<typename Mesh, typename SEM, typename SVM>\ntemplate<typename VertexUVMap,\n         typename VertexIndexMap,\n         typename VertexParameterizedMap>\nCGAL::Surface_mesh_parameterization::Error_code\nRicci_flow_parameterizer3<Mesh, SEM, SVM>::parameterize(\n    TriangleMesh& mesh,\n    halfedge_descriptor,\n    VertexUVMap uvmap,\n    VertexIndexMap,\n    VertexParameterizedMap vpmap)\n{\n    auto status = ricci_flow(_underlying_mesh, _vrpm, _ewpm, _vcpm, _settings);\n    _impl::embed_circle_packing_metric(\n        _underlying_mesh, _vrpm, _ewpm, mesh, uvmap, vpmap);\n    if (status == RicciFlowSolverStatus::InvalidInput) {\n        return CGAL::Surface_mesh_parameterization::ERROR_WRONG_PARAMETER;\n    }\n    else {\n        return CGAL::Surface_mesh_parameterization::OK;\n    }\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "8f1a25ce114e4b0cc0ff98a3365234c8f218bc75", "size": 19093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/Parameterization/src/RicciFlow.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/Parameterization/src/RicciFlow.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/Parameterization/src/RicciFlow.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": 34.463898917, "max_line_length": 80, "alphanum_fraction": 0.5520871524, "num_tokens": 5212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5321875077854141}}
{"text": "#include \"mtf/SSM//HomographyEstimator.h\"\n#include \"mtf/Utilities/miscUtils.h\"\n#include \"opencv2/core/core_c.h\"\n#include \"opencv2/calib3d/calib3d.hpp\"\n#include <boost/random/uniform_int_distribution.hpp>\n\n\n_MTF_BEGIN_NAMESPACE\n\nHomographyEstimator::HomographyEstimator(int _modelPoints, bool _use_boost_rng)\n\t: SSMEstimator(_modelPoints, cvSize(3, 3), 1, _use_boost_rng) {\n\tassert(_modelPoints >= 4);\n\tcheckPartialSubsets = false;\n}\n\nint HomographyEstimator::runKernel(const CvMat* m1, const CvMat* m2, CvMat* H) {\n\tint i, count = m1->rows * m1->cols;\n\tconst CvPoint2D64f* M = (const CvPoint2D64f*)m1->data.ptr;\n\tconst CvPoint2D64f* m = (const CvPoint2D64f*)m2->data.ptr;\n\n\tdouble LtL[9][9], W[9][1], V[9][9];\n\tCvMat _LtL = cvMat(9, 9, CV_64F, LtL);\n\tCvMat matW = cvMat(9, 1, CV_64F, W);\n\tCvMat matV = cvMat(9, 9, CV_64F, V);\n\tCvMat _H0 = cvMat(3, 3, CV_64F, V[8]);\n\tCvMat _Htemp = cvMat(3, 3, CV_64F, V[7]);\n\tCvPoint2D64f cM = { 0, 0 }, cm = { 0, 0 }, sM = { 0, 0 }, sm = { 0, 0 };\n\n\tfor(i = 0; i < count; i++) {\n\t\tcm.x += m[i].x;\n\t\tcm.y += m[i].y;\n\t\tcM.x += M[i].x;\n\t\tcM.y += M[i].y;\n\t}\n\n\tcm.x /= count;\n\tcm.y /= count;\n\tcM.x /= count;\n\tcM.y /= count;\n\n\tfor(i = 0; i < count; i++) {\n\t\tsm.x += fabs(m[i].x - cm.x);\n\t\tsm.y += fabs(m[i].y - cm.y);\n\t\tsM.x += fabs(M[i].x - cM.x);\n\t\tsM.y += fabs(M[i].y - cM.y);\n\t}\n\n\tif(fabs(sm.x) < DBL_EPSILON || fabs(sm.y) < DBL_EPSILON ||\n\t\tfabs(sM.x) < DBL_EPSILON || fabs(sM.y) < DBL_EPSILON)\n\t\treturn 0;\n\tsm.x = count / sm.x;\n\tsm.y = count / sm.y;\n\tsM.x = count / sM.x;\n\tsM.y = count / sM.y;\n\n\tdouble invHnorm[9] = { 1. / sm.x, 0, cm.x, 0, 1. / sm.y, cm.y, 0, 0, 1 };\n\tdouble Hnorm2[9] = { sM.x, 0, -cM.x * sM.x, 0, sM.y, -cM.y * sM.y, 0, 0, 1 };\n\tCvMat _invHnorm = cvMat(3, 3, CV_64FC1, invHnorm);\n\tCvMat _Hnorm2 = cvMat(3, 3, CV_64FC1, Hnorm2);\n\n\tcvZero(&_LtL);\n\tfor(i = 0; i < count; i++) {\n\t\tdouble x = (m[i].x - cm.x) * sm.x, y = (m[i].y - cm.y) * sm.y;\n\t\tdouble X = (M[i].x - cM.x) * sM.x, Y = (M[i].y - cM.y) * sM.y;\n\t\tdouble Lx[] = { X, Y, 1, 0, 0, 0, -x * X, -x * Y, -x };\n\t\tdouble Ly[] = { 0, 0, 0, X, Y, 1, -y * X, -y * Y, -y };\n\t\tint j, k;\n\t\tfor(j = 0; j < 9; j++)\n\t\t\tfor(k = j; k < 9; k++)\n\t\t\t\tLtL[j][k] += Lx[j] * Lx[k] + Ly[j] * Ly[k];\n\t}\n\tcvCompleteSymm(&_LtL);\n\n\t//cvSVD( &_LtL, &matW, 0, &matV, CV_SVD_MODIFY_A + CV_SVD_V_T );\n\tcvEigenVV(&_LtL, &matV, &matW);\n\tcvMatMul(&_invHnorm, &_H0, &_Htemp);\n\tcvMatMul(&_Htemp, &_Hnorm2, &_H0);\n\tcvConvertScale(&_H0, H, 1. / _H0.data.db[8]);\n\n\treturn 1;\n}\n\n\nvoid HomographyEstimator::computeReprojError(const CvMat* m1, const CvMat* m2,\n\tconst CvMat* model, CvMat* _err) {\n\tint i, count = m1->rows * m1->cols;\n\tconst CvPoint2D64f* M = (const CvPoint2D64f*)m1->data.ptr;\n\tconst CvPoint2D64f* m = (const CvPoint2D64f*)m2->data.ptr;\n\tconst double* H = model->data.db;\n\tfloat* err = _err->data.fl;\n\n\tfor(i = 0; i < count; i++) {\n\t\tdouble ww = 1. / (H[6] * M[i].x + H[7] * M[i].y + 1.);\n\t\tdouble dx = (H[0] * M[i].x + H[1] * M[i].y + H[2]) * ww - m[i].x;\n\t\tdouble dy = (H[3] * M[i].x + H[4] * M[i].y + H[5]) * ww - m[i].y;\n\t\terr[i] = (float)(dx * dx + dy * dy);\n\t}\n}\n\nbool HomographyEstimator::refine(const CvMat* m1, const CvMat* m2,\n\tCvMat* model, int maxIters) {\n\tLevMarq solver(8, 0, cvTermCriteria(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS, maxIters, DBL_EPSILON));\n\tint i, j, k, count = m1->rows * m1->cols;\n\tconst CvPoint2D64f* M = (const CvPoint2D64f*)m1->data.ptr;\n\tconst CvPoint2D64f* m = (const CvPoint2D64f*)m2->data.ptr;\n\tCvMat modelPart = cvMat(solver.param->rows, solver.param->cols, model->type, model->data.ptr);\n\tcvCopy(&modelPart, solver.param);\n\n\tfor(;;) {\n\t\tconst CvMat* _param = 0;\n\t\tCvMat *_JtJ = 0, *_JtErr = 0;\n\t\tdouble* _errNorm = 0;\n\n\t\tif(!solver.updateAlt(_param, _JtJ, _JtErr, _errNorm))\n\t\t\tbreak;\n\n\t\tfor(i = 0; i < count; i++) {\n\t\t\tconst double* h = _param->data.db;\n\t\t\tdouble Mx = M[i].x, My = M[i].y;\n\t\t\tdouble ww = h[6] * Mx + h[7] * My + 1.;\n\t\t\tww = fabs(ww) > DBL_EPSILON ? 1. / ww : 0;\n\t\t\tdouble _xi = (h[0] * Mx + h[1] * My + h[2]) * ww;\n\t\t\tdouble _yi = (h[3] * Mx + h[4] * My + h[5]) * ww;\n\t\t\tdouble err[] = { _xi - m[i].x, _yi - m[i].y };\n\t\t\tif(_JtJ || _JtErr) {\n\t\t\t\tdouble J[][8] = {\n\t\t\t\t\t{ Mx * ww, My * ww, ww, 0, 0, 0, -Mx*ww * _xi, -My*ww * _xi },\n\t\t\t\t\t{ 0, 0, 0, Mx * ww, My * ww, ww, -Mx*ww * _yi, -My*ww * _yi }\n\t\t\t\t};\n\n\t\t\t\tfor(j = 0; j < 8; j++) {\n\t\t\t\t\tfor(k = j; k < 8; k++)\n\t\t\t\t\t\t_JtJ->data.db[j * 8 + k] += J[0][j] * J[0][k] + J[1][j] * J[1][k];\n\t\t\t\t\t_JtErr->data.db[j] += J[0][j] * err[0] + J[1][j] * err[1];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(_errNorm)\n\t\t\t\t*_errNorm += err[0] * err[0] + err[1] * err[1];\n\t\t}\n\t}\n\n\tcvCopy(solver.param, &modelPart);\n\treturn true;\n}\n\ncv::Mat estimateHomography(cv::InputArray _points1, cv::InputArray _points2,\n\tcv::OutputArray _mask, const SSMEstimatorParams &params){\n\tcv::Mat points1 = _points1.getMat(), points2 = _points2.getMat();\n\tint n_pts = points1.checkVector(2);\n\tCV_Assert(n_pts >= 0 && points2.checkVector(2) == n_pts &&\n\t\tpoints1.type() == points2.type());\n\n\tcv::Mat H(3, 3, CV_64F);\n\tCvMat _pt1 = points1, _pt2 = points2;\n\tCvMat matH = H, c_mask, *p_mask = 0;\n\tif(_mask.needed()){\n\t\t_mask.create(n_pts, 1, CV_8U, -1, true);\n\t\tp_mask = &(c_mask = _mask.getMat());\n\t}\n\tbool ok = estimateHomography(&_pt1, &_pt2, &matH, p_mask, params) > 0;\n\tif(!ok)\n\t\tH = cv::Scalar(0);\n\treturn H;\n}\n\nint estimateHomography(const CvMat* objectPoints, const CvMat* imagePoints,\n\tCvMat* __H, CvMat* mask, const SSMEstimatorParams &params){\n\tbool result = false;\n\tcv::Ptr<CvMat> m, M, tempMask;\n\n\tdouble H[9];\n\tCvMat matH = cvMat(3, 3, CV_64FC1, H);\n\n\tCV_Assert(CV_IS_MAT(imagePoints) && CV_IS_MAT(objectPoints));\n\n\tint n_pts = MAX(imagePoints->cols, imagePoints->rows);\n\tCV_Assert(n_pts >= params.n_model_pts);\n\n\tm = cvCreateMat(1, n_pts, CV_64FC2);\n\tcvConvertPointsHomogeneous(imagePoints, m);\n\n\tM = cvCreateMat(1, n_pts, CV_64FC2);\n\tcvConvertPointsHomogeneous(objectPoints, M);\n\n\tif(mask){\n\t\tCV_Assert(CV_IS_MASK_ARR(mask) && CV_IS_MAT_CONT(mask->type) &&\n\t\t\t(mask->rows == 1 || mask->cols == 1) &&\n\t\t\tmask->rows*mask->cols == n_pts);\n\t}\n\tif(mask || n_pts > params.n_model_pts)\n\t\ttempMask = cvCreateMat(1, n_pts, CV_8U);\n\tif(!tempMask.empty())\n\t\tcvSet(tempMask, cvScalarAll(1.));\n\n\tHomographyEstimator estimator(params.n_model_pts, params.use_boost_rng);\n\tint method = n_pts == params.n_model_pts ? 0 : params.method_cv;\n\tif(method == CV_LMEDS)\n\t\tresult = estimator.runLMeDS(M, m, &matH, tempMask, params.confidence, \n\t\tparams.max_iters, params.max_subset_attempts);\n\telse if(method == CV_RANSAC)\n\t\tresult = estimator.runRANSAC(M, m, &matH, tempMask, params.ransac_reproj_thresh,\n\t\tparams.confidence, params.max_iters, params.max_subset_attempts);\n\telse\n\t\tresult = estimator.runKernel(M, m, &matH) > 0;\n\n\tif(result && n_pts > params.n_model_pts){\n\t\tutils::icvCompressPoints((CvPoint2D64f*)M->data.ptr, tempMask->data.ptr, 1, n_pts);\n\t\tn_pts = utils::icvCompressPoints((CvPoint2D64f*)m->data.ptr, tempMask->data.ptr, 1, n_pts);\n\t\tM->cols = m->cols = n_pts;\n\t\tif(method == CV_RANSAC)\n\t\t\testimator.runKernel(M, m, &matH);\n\t\tif(params.refine){\n\t\t\testimator.refine(M, m, &matH, params.lm_max_iters);\n\t\t}\n\t}\n\n\tif(result)\n\t\tcvConvert(&matH, __H);\n\n\tif(mask && tempMask){\n\t\tif(CV_ARE_SIZES_EQ(mask, tempMask))\n\t\t\tcvCopy(tempMask, mask);\n\t\telse\n\t\t\tcvTranspose(tempMask, mask);\n\t}\n\n\treturn (int)result;\n}\n\n\n\n//int\tcvFindHomography(const PtsT &objectPoints, const PtsT &imagePoints,\n//\tProjWarpT & __H, EstimatorMethod method, double ransacReprojThreshold,\n//\tVectorXb &mask){\n//\tint count = objectPoints.cols();\n//\tassert(count >= 4);\n//\tassert(mask.size() == count);\n\n//\tconst double confidence = 0.995;\n//\tconst int maxIters = 2000;\n//\tconst double defaultRANSACReprojThreshold = 3;\n//\tbool result = false;\n\n//\tHomPtsT m, M;\n//\tProjWarpT matH;\n//\tif(ransacReprojThreshold <= 0)\n//\t\transacReprojThreshold = defaultRANSACReprojThreshold;\n\n//\thomogenize(imagePoints, m);\n//\thomogenize(objectPoints, M);\n//\n//\tmask.fill(1);\n\n//\tAffineEstimator estimator(4);\n//\tif(count == 4)\n//\t\tmethod = EstimatorMethod::LSTSQR;\n\n//\tif(method == EstimatorMethod::LMEDS)\n//\t\tresult = estimator.runLMeDS(M, m, matH, mask, confidence, maxIters);\n//\telse if(method == EstimatorMethod::RANSAC)\n//\t\tresult = estimator.runRANSAC(M, m, matH, mask, ransacReprojThreshold, confidence, maxIters);\n//\telse\n//\t\tresult = estimator.runKernel(M, m, matH) > 0;\n\n//\tif(result && count > 4){\n//\t\tcompressPoints(m, mask, 1, count);\n//\t\tcount = compressPoints(M, mask, 1, count);\n//\t\tif(method == EstimatorMethod::RANSAC)\n//\t\t\testimator.runKernel(M, m, matH);\n//\t\testimator.refine(M, m, matH, 10);\n//\t}\n\n//\tif(result)\n//\t\t__H = matH;\n\n//\treturn result;\n//}\n\n\n_MTF_END_NAMESPACE\n", "meta": {"hexsha": "0f42b388b96f2aa5cd2af5376fd35b4ae485b1ab", "size": 8574, "ext": "cc", "lang": "C++", "max_stars_repo_path": "SSM/src/HomographyEstimator.cc", "max_stars_repo_name": "abhineet123/MTF", "max_stars_repo_head_hexsha": "6cb45c88d924fb2659696c3375bd25c683802621", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2016-12-11T00:34:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T23:03:40.000Z", "max_issues_repo_path": "SSM/src/HomographyEstimator.cc", "max_issues_repo_name": "siqiyan/MTF", "max_issues_repo_head_hexsha": "9a76388c907755448bb7223420fe74349130f636", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2017-09-04T06:27:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T19:07:23.000Z", "max_forks_repo_path": "SSM/src/HomographyEstimator.cc", "max_forks_repo_name": "siqiyan/MTF", "max_forks_repo_head_hexsha": "9a76388c907755448bb7223420fe74349130f636", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2017-02-19T02:12:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-23T03:47:55.000Z", "avg_line_length": 30.512455516, "max_line_length": 97, "alphanum_fraction": 0.6203638908, "num_tokens": 3356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5321874911667149}}
{"text": "#ifndef TRIUMF_NMR_NUCLEI_HPP\n#define TRIUMF_NMR_NUCLEI_HPP\n\n#include <boost/math/constants/constants.hpp>\n\n#include <triumf/nmr/utilities.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// nuclear magnetic resonance (NMR)\nnamespace nmr {\n\n// NMR probe nuclei and their properties\nnamespace nuclei {\n\n// niobium-93\ntemplate <typename T = double> struct niobium_93 {\n  // radioactive half-life (s)\n  static inline constexpr T half_life() {\n    return std::numeric_limits<T>::infinity();\n  }\n  // radioactive lifetime (s)\n  static inline constexpr T lifetime() {\n    return half_life() / boost::math::constants::ln_two<T>();\n  }\n  // spin quantum number\n  static inline constexpr T spin() { return 9.0 / 2.0; }\n  // magnetic dipole moment (nm)\n  static inline constexpr T magnetic_dipole_moment() { return 6.163; }\n  // electric dipole moment (b)\n  static inline constexpr T electric_quadrupole_moment() { return -0.32; }\n  // gyromagnetic ratio (s^-1 T^-1)\n  static inline constexpr T gyromagnetic_ratio() {\n    return triumf::nmr::utilities::calculate_gamma<T>(magnetic_dipole_moment(),\n                                                      spin());\n  }\n  // gyromagnetic ratio (MHz / T)\n  static inline constexpr T gyromagnetic_ratio_in_MHz_T() {\n    return gyromagnetic_ratio() / 1e6 / boost::math::constants::two_pi<T>();\n  }\n};\n\n} // namespace nuclei\n\n} // namespace nmr\n\n} // namespace triumf\n\n#endif // TRIUMF_NMR_NUCLEI_HPP\n", "meta": {"hexsha": "bc48a667ba0c2b3d7a77de6fc564a6f08190be88", "size": 1457, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/nmr/nuclei.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/nuclei.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/nuclei.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.568627451, "max_line_length": 79, "alphanum_fraction": 0.6884008236, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5321835073234275}}
{"text": "#include \"sv/llol/match.h\"\n\n#include <Eigen/Geometry>  // inverse\n\nnamespace sv {\n\nvoid PointMatch::ResetGrid() {\n  px_g = {kBadPx, kBadPx};\n  mc_g.Reset();\n}\n\nvoid PointMatch::ResetPano() {\n  px_p = {kBadPx, kBadPx};\n  mc_p.Reset();\n}\n\nvoid PointMatch::Reset() {\n  ResetGrid();\n  ResetPano();\n  U.setZero();\n  scale = 0.0;\n}\n\nvoid PointMatch::CalcSqrtInfo(float lambda) {\n  auto cov = mc_p.Covar();\n  if (lambda > 0) cov.diagonal().array() += lambda;\n  U = MatrixSqrtUtU(cov.inverse().eval());\n}\n\nvoid PointMatch::CalcSqrtInfo(const Eigen::Matrix3f& R_p_g, float lambda) {\n  auto cov = mc_p.Covar();\n  cov.noalias() += R_p_g * mc_g.Covar() * R_p_g.transpose();\n  if (lambda > 0) cov.diagonal().array() += lambda;\n  U = MatrixSqrtUtU(cov.inverse().eval());\n}\n\n}  // namespace sv\n", "meta": {"hexsha": "16c5688ec35bc5880c8657b8a5ce8c16ccd0aeec", "size": 779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sv/llol/match.cpp", "max_stars_repo_name": "iandouglas96/llol", "max_stars_repo_head_hexsha": "028fe73d4f4f9214b4534cbedb9b53dff039e84f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2021-10-10T00:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:09:40.000Z", "max_issues_repo_path": "sv/llol/match.cpp", "max_issues_repo_name": "iandouglas96/llol", "max_issues_repo_head_hexsha": "028fe73d4f4f9214b4534cbedb9b53dff039e84f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-01-14T15:22:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T20:07:44.000Z", "max_forks_repo_path": "sv/llol/match.cpp", "max_forks_repo_name": "iandouglas96/llol", "max_forks_repo_head_hexsha": "028fe73d4f4f9214b4534cbedb9b53dff039e84f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-12-01T14:04:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T02:37:14.000Z", "avg_line_length": 20.5, "max_line_length": 75, "alphanum_fraction": 0.6431322208, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5321834994432035}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n#include <boost/python/enum.hpp>\n#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/dict.hpp>\n#include <boost/python/list.hpp>\n#include <scitbx/array_family/flex_types.h>\n#include <scitbx/array_family/shared.h>\n#include <scitbx/math/mean_and_variance.h>\n#include <scitbx/array_family/boost_python/shared_wrapper.h>\n#include <cctbx/examples/merging/xscale_prototype_core.h>\n#include <cctbx/examples/merging/postrefine_base.h>\n#include <Eigen/Sparse>\n#include <boost/python/return_internal_reference.hpp>\n#include <boost/math/tools/precision.hpp>\n\nusing namespace boost::python;\nnamespace cctbx{ namespace merging {\n\ndouble d_product (double const&A, double const&B, double const&dA, double const&dB){\n  return dA * B + A * dB;\n}\n\nstatic const double logmax = boost::math::tools::log_max_value<double>()/2.;\nstatic const double logmin = boost::math::tools::log_min_value<double>()/2.;\n\nstatic boost::python::tuple\ntask6c_f_g(intensity_data::vecd const& x,\n           const int& N_I, const int& N_G,\n           const intensity_data & FSIM,\n           bool compute_curv) {\n  double f = 0.;\n  const double* Iptr = x.begin(); // indices into the array of parameters\n  const double* Gptr = Iptr + N_I;\n  const double* Bptr = Gptr + N_G;\n\n  intensity_data::vecd g(x.size(),0);\n  intensity_data::vecd c(x.size(),0);\n  double* Iptrg = g.begin(); // indices into the array of derivatives\n  double* Gptrg = Iptrg + N_I;\n  double* Bptrg = Gptrg + N_G;\n  double* Iptrc = c.begin(); // indices into the array of curvatures\n  double* Gptrc = Iptrc + N_I;\n  double* Bptrc = Gptrc + N_G;\n\n  for (size_t i = 0; i<FSIM.raw_obs.size(); ++i){\n      double weight = 1./FSIM.exp_var[i];\n      double Gitem  = Gptr[ FSIM.frame[i] ];\n      double Bargument = -2.* Bptr[ FSIM.frame[i] ] * FSIM.stol_sq[i];\n\n      if (logmax < Bargument){\n        throw SCITBX_ERROR(\"exp argument greater than logmax\");\n      }\n      if (logmin > Bargument){\n        throw SCITBX_ERROR(\"exp argument less than logmin\");\n      }\n\n      double Bitem  = std::exp(Bargument); // :=exp(beta)\n      double Iitem  = Iptr[ FSIM.miller[i] ];\n\n      double residual = - FSIM.raw_obs[i] +\n                        Gitem *\n                        Bitem *\n                        Iitem;\n\n      f += weight * residual * residual;\n\n      Gptrg[ FSIM.frame[i] ] += weight * residual * Bitem * Iitem;\n      Iptrg[ FSIM.miller[i] ]+= weight * residual * Bitem * Gitem;\n\n      double d_Bitem_d_B =    Bitem * ( -2. * FSIM.stol_sq[i] );\n      double d_residual_d_B = Gitem * Iitem * d_Bitem_d_B;\n\n      Bptrg[ FSIM.frame[i] ] += weight * residual * d_residual_d_B;\n\n      if (compute_curv) {\n        Gptrc[ FSIM.frame[i] ] +=  weight * Bitem * Bitem * Iitem * Iitem;\n        Iptrc[ FSIM.miller[i] ]+=  weight * Bitem * Bitem * Gitem * Gitem;\n        Bptrc[ FSIM.frame[i] ] +=  weight * d_residual_d_B * d_residual_d_B;\n      }\n  }\n\n  return (boost::python::make_tuple(f/2., g, c));\n}\n\nvoid f_g_error(std::string const& message){\n  throw SCITBX_ERROR(message);\n}\n\nnamespace boost_python { namespace {\n\n  void\n  large_scale_merging_init_module() {\n    using namespace boost::python;\n\n\n    def(\"task6c_f_g\", &cctbx::merging::task6c_f_g);\n    def(\"f_g_error\", &cctbx::merging::f_g_error);\n\n    typedef return_value_policy<return_by_value> rbv;\n    typedef default_call_policies dcp;\n\n    typedef cctbx::merging::intensity_data cmid;\n    class_<cmid>(\"intensity_data\", init<>())\n      .add_property(\"frame\",\n                    make_getter(&cmid::frame, rbv()),\n                    make_setter(&cmid::frame, dcp()))\n      .add_property(\"miller\",\n                    make_getter(&cmid::miller, rbv()),\n                    make_setter(&cmid::miller, dcp()))\n      .add_property(\"raw_obs\",\n                    make_getter(&cmid::raw_obs, rbv()),\n                    make_setter(&cmid::raw_obs, dcp()))\n      .add_property(\"exp_var\",\n                    make_getter(&cmid::exp_var, rbv()),\n                    make_setter(&cmid::exp_var, dcp()))\n      .add_property(\"stol_sq\",\n                    make_getter(&cmid::stol_sq, rbv()),\n                    make_setter(&cmid::stol_sq, dcp()))\n      .add_property(\"origHKL\",\n                    make_getter(&cmid::origHKL, rbv()),\n                    make_setter(&cmid::origHKL, dcp()))\n      .def(\"estimate_G\", &cmid::estimate_G,(arg(\"Nframes\"),arg(\"inv_d_sq_max\")=0.,arg(\"inv_d_sq_min\")=0.))\n      .def(\"estimate_I\", &cmid::estimate_I,(arg(\"Gframes\"),arg(\"inv_d_sq_max\")=0.,arg(\"inv_d_sq_min\")=0.))\n      .def(\"reset_mem\", &cmid::reset_mem)\n    ;\n\n    enum_<ParameterFlags>(\"ParameterFlags\")\n      .value(\"PartialityDeff\", PartialityDeff)\n      .value(\"PartialityEtaDeff\", PartialityEtaDeff)\n      .value(\"Bfactor\", Bfactor)\n      .value(\"Deff\", Deff)\n      .value(\"Eta\", Eta)\n      .value(\"Rxy\", Rxy)\n    ;\n\n    typedef scaling_common_functions scf;\n    class_<scf >(\n      \"scaling_common_functions\", no_init)\n      .def(\"set_cpp_data\",&scf::set_cpp_data,\n        (arg(\"fsim\")))\n      .def(\"set_parameter_flags\", &scf::set_parameter_flags)\n      .def(\"set_wavelength\", &scf::set_wavelength)\n      .def(\"set_domain_size\", &scf::set_domain_size)\n      .def(\"set_Astar_matrix\", &scf::set_Astar_matrix)\n      .def(\"get_rh_rs_ratio\", &scf::get_rh_rs_ratio)\n    ;\n\n    typedef scitbx::example::non_linear_ls_eigen_wrapper nllsew;\n    typedef xscale6e wt6e;\n    class_<wt6e,\n           bases<nllsew, scf  > >(\n      \"xscale6e\", no_init)\n      .def(init<int>(arg(\"n_parameters\")))\n      .def(\"access_cpp_build_up_directly_eigen_eqn\",&wt6e::access_cpp_build_up_directly_eigen_eqn,\n        (arg(\"objective_only\"),arg(\"current_values\")))\n      .def(\"reset_mem\", &wt6e::reset_mem)\n    ;\n\n    typedef postrefine_base prb;\n    class_<prb,\n           bases<wt6e  > >(\n      \"postrefine_base\", no_init)\n      .def(init<int>(arg(\"n_parameters\")))\n      .def(\"access_cpp_build_up_directly_eigen_eqn\",&prb::access_cpp_build_up_directly_eigen_eqn,\n        (arg(\"objective_only\"),arg(\"current_values\")))\n    ;\n\n\n  }\n\n}}\n}} // namespace xfel::boost_python::<anonymous>\n\nBOOST_PYTHON_MODULE(cctbx_large_scale_merging_ext)\n{\n  cctbx::merging::boost_python::large_scale_merging_init_module();\n\n}\n", "meta": {"hexsha": "6a589d3e30f8bc1c747d58228e92ffe8369d7cb2", "size": 6259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/examples/merging/large_scale_merging_ext.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "cctbx/examples/merging/large_scale_merging_ext.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "cctbx/examples/merging/large_scale_merging_ext.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 34.5801104972, "max_line_length": 106, "alphanum_fraction": 0.6328486979, "num_tokens": 1812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5321834994432034}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <vector>\n#include <sstream>\n#include <math.h>\n#include \"testing.h\"\n\n\nclass Suspension \n{\n\n\t// variables\nprivate:\n\t// suffix ref stands for ref, so reference/initial coordinates can be easily\n\t// differentiated from coordinates of the same points during wheel movement\n\t// hardpoints\n\t// LCA\n\tEigen::Vector3f lca1ref;\n\tEigen::Vector3f lca2ref;\n\tEigen::Vector3f lca3ref;\n\n\tEigen::Vector3f uca1ref;\n\tEigen::Vector3f uca2ref;\n\tEigen::Vector3f uca3ref;\n\n\tEigen::Vector3f tr1ref;\n\tEigen::Vector3f tr2ref;\n\n\tEigen::Vector3f wcnref;\n\tEigen::Vector3f spnref;\n\n\n\t// wheel radius\n\tfloat wRadius=210;\n\t// wheel vertical movement\n\tfloat wVert=30;\n\t// wheel steering movement\n\tfloat wSteer=30;\n\t// number of increments between reference position and\n\t// downmost/upmost/leftmost/rightmost position\n\tint vertIncr=30;\n\tint steerIncr=0;\n\t// precision- at what value has the iterator converged, in percentage- 0...1\n\tfloat precision;\n\n\t// derived values\n\n\tEigen::Vector3f lca12;\n\tEigen::Vector3f uca12;\n\n\n\n\t/* initializers */\n\npublic:\n\n\tSuspension() \n\t{\n\t\tstd::vector<float> hps;\n\t\tstd::string userArrayInput;\n\t\tstd::cout << \"enter numbers: \";\n\t\tstd::cin >> userArrayInput;\n\n\t\tstd::istringstream iss(userArrayInput);\n\t\tstd::string item;\n\n\t\twhile (std::getline(iss, item, ','))\n\t\t{\n\t\t\thps.push_back(std::stof(item));\n\t\t}\n\n\t\tstd::cout << \"for loop vector output\" << std::endl;\n\n\t\tfor (auto i = hps.begin(); i != hps.end(); i++)\n\t\t\tstd::cout << *i << std::endl;\n\n\t\tlca1ref << hps[0], hps[1], hps[2];\n\t\tlca2ref << hps[3], hps[4], hps[5];\n\t\tlca3ref << hps[6], hps[7], hps[8];\n\n\t\tuca1ref << hps[9], hps[10], hps[11];\n\t\tuca2ref << hps[12], hps[13], hps[14];\n\t\tuca3ref << hps[15], hps[16], hps[17];\n\n\t\ttr1ref << hps[18], hps[19], hps[20];\n\t\ttr2ref << hps[21], hps[22], hps[23];\n\n\t\twcnref << hps[24], hps[25], hps[26];\n\t\tspnref << hps[27], hps[28], hps[29];\n\n\t}\n\n\tSuspension(float lca1xin, float lca1yin, float lca1zin, // in suffix stands for input\n\t\tfloat lca2xin, float lca2yin, float lca2zin,\n\t\tfloat lca3xin, float lca3yin, float lca3zin,\n\t\tfloat uca1xin, float uca1yin, float uca1zin,\n\t\tfloat uca2xin, float uca2yin, float uca2zin,\n\t\tfloat uca3xin, float uca3yin, float uca3zin,\n\t\tfloat tr1xin, float tr1yin, float tr1zin,\n\t\tfloat tr2xin, float tr2yin, float tr2zin,\n\t\tfloat wcnxin, float wcnyin, float wcnzin,\n\t\tfloat spnxin, float spnyin, float spnzin,\n\t\tfloat wRadiusin, float wVertin, float wSteerin,\n\t\tint vertIncrin, int steerIncrin, float precisionin)\n\t{\n\t\tlca1ref << lca1xin, lca1yin, lca1zin;\n\t\tlca2ref << lca2xin, lca2yin, lca2zin;\n\t\tlca3ref << lca3xin, lca3yin, lca3zin;\n\n\t\tuca1ref << uca1xin, uca1yin, uca1zin;\n\t\tuca2ref << uca2xin, uca2yin, uca2zin;\n\t\tuca3ref << uca3xin, uca3yin, uca3zin;\n\n\t\ttr1ref << tr1xin, tr1yin, tr1zin;\n\t\ttr2ref << tr2xin, tr2yin, tr2zin;\n\n\t\twcnref << wcnxin, wcnyin, wcnzin;\n\t\tspnref << spnxin, spnyin, spnzin;\n\t\t\n\t\twRadius = wRadiusin;\n\t\twVert = wVertin;\n\t\twSteer = wSteerin;\n\t\tvertIncr = vertIncrin;\n\t\tsteerIncr = steerIncrin;\n\t\tprecision = precisionin;\n\n\t}\n\n\n\t// FUNCTIONS\nprivate:\n\n\t// place as inputs variables rLCA, rUCA, uca12, lca12, etc. so those can be only temporary\n\t// values and not use up stack memory\n\t\n\t\tvoid CalculateConstants(Eigen::Matrix3f& _rotLCA, Eigen::Matrix3f& _rotUCA, float& _rLCA, float& _rUCA, float& _rCA, Eigen::ArrayXf& _zLocLca, float& _rST, float& _t_param, float& _rTR, Eigen::Vector3f& _wcnlocTRk, Eigen::Vector3f& _spnlocTRk)\n\t{\n\n\t\t// create line connecting lca1 and lca2\n\t\tEigen::ParametrizedLine<float, 3> lca1lca2 = Eigen::ParametrizedLine<float, 3>::Through(lca1ref, lca2ref);\n\n\t\t// local LCA plane for determining max z value of wheel parameters\n\t\tEigen::Vector4f abcd;\n\t\tEigen::Vector3f _tr2prref;\n\n\t\t// z local maximum value\n\t\tfloat zLocHi;\n\t\t// z local minimum value\n\t\tfloat zLocLo;\n\n\t\tlca12 = lca1lca2.projection(lca3ref);\n\t\t_rLCA = lca1lca2.distance(lca3ref);\n\n\t\t// create rotation matrix for LCA cs\n\t\t_rotLCA << \n\t\t\t(lca1ref - lca2ref).normalized(),\n\t\t\t(lca12 - lca3ref).normalized(),\n\t\t\t((lca1ref - lca2ref).cross(lca12 - lca3ref)).normalized();\n\n\t\t// calculate parameters for plane in LCA cs\n\t\tabcd << \n\t\t\t_rotLCA.row(2)(0),\n\t\t\t_rotLCA.row(2)(1),\n\t\t\t_rotLCA.row(2)(2),\n\t\t\t-_rotLCA.row(2) * (_rotLCA.transpose() * Eigen::Vector3f{ -lca12(0),-lca12(1),lca3ref(2) - wVert - lca12(2) });\n\n\t\t// calculates z value for upmost movement of wheel for intersection of plane and circle in LCA\n\t\tzLocHi = \n\t\t\t(-abcd(2) * abcd(3) + abcd(1) * \n\t\t\tsqrt(abcd(2) * abcd(2) * _rLCA * _rLCA + \n\t\t\t\tabcd(1) * abcd(1) * _rLCA * _rLCA - \n\t\t\t\tabcd(3) * abcd(3))) /\n\t\t\t(abcd(1) * abcd(1) + abcd(2) * abcd(2));\n\n\t\t// reuses previous parameters for LCA plane, only 4th parameter is changed\n\t\tabcd(3) = \n\t\t\t-_rotLCA.row(2) *\n\t\t\t_rotLCA.transpose() *\n\t\t\tEigen::Vector3f{ -lca12(0),-lca12(1),lca3ref(2) + wVert - lca12(2) };\n\n\t\t// calculates z value for downmost movement of wheel for intersection of plane and circle in LCA\n\t\tzLocLo = \n\t\t\t(-abcd(2) * abcd(3) + \n\t\t\tabcd(1) * sqrt(abcd(2) * abcd(2) * _rLCA * _rLCA + \n\t\t\t\tabcd(1) * abcd(1) * _rLCA * _rLCA - \n\t\t\t\tabcd(3) * abcd(3))) /\n\t\t\t(abcd(1) * abcd(1) + abcd(2) * abcd(2));\n\n\n\t\t_zLocLca << \n\t\t\tEigen::VectorXf::LinSpaced(vertIncr, zLocLo, zLocLo / vertIncr), \n\t\t\t0, \n\t\t\tEigen::VectorXf::LinSpaced(vertIncr, zLocHi / vertIncr, zLocHi);\n\n\n\t\t// create line connecting uca1 and uca2\n\t\tEigen::ParametrizedLine<float, 3> uca1uca2 = Eigen::ParametrizedLine<float, 3>::Through(uca1ref, uca2ref);\n\n\t\tuca12 = uca1uca2.projection(uca3ref);\n\t\t_rUCA = uca1uca2.distance(uca3ref);\n\n\t\t_rCA = (uca3ref - lca3ref).norm();\n\n\t\t// create rotation matrix for UCA cs\n\t\t_rotUCA << \n\t\t\t(uca1ref - uca2ref).normalized(), \n\t\t\t(uca12 - uca3ref).normalized(), \n\t\t\t((uca1ref - uca2ref).cross(uca12 - uca3ref)).normalized();\n\n\n\t\t// calculate TR2 projection point and rTR\n\t\tEigen::ParametrizedLine<float, 3> lca3uca3 = Eigen::ParametrizedLine<float, 3>::Through(lca3ref, uca3ref);\n\n\t\t_tr2prref = lca3uca3.projection(tr2ref);\n\n\t\t_rST = (tr2ref - _tr2prref).norm();\n\n\t\t_rTR = (tr2ref - tr1ref).norm();\n\n\t\t_t_param = (_tr2prref(0) - lca3ref(0)) / (uca3ref(0) - lca3ref(0));\n\n\n\t\tEigen::Matrix3f _rotTRk; // TR rotation matrix defined by TR2ref\n\n\t\tEigen::Vector3f _xCol{ _tr2prref - tr2ref };\n\t\tEigen::Vector3f _zCol{ lca3ref - uca3ref };\n\t\tEigen::Vector3f _yCol{ _zCol.cross(_xCol) };\n\n\n\t\t_rotTRk.col(0) << _xCol / _xCol.norm();\n\t\t_rotTRk.col(1) << _yCol / _yCol.norm();\n\t\t_rotTRk.col(2) << _zCol / _zCol.norm();\n\n\t\t_wcnlocTRk << _rotTRk.transpose() * (wcnref - _tr2prref);\n\t\t_spnlocTRk << _rotTRk.transpose() * (spnref - _tr2prref);\n\n\t\tstd::cout << \"spnlocTRk\" << std::endl;\n\t\tstd::cout << _spnlocTRk << std::endl;\n\t}\n\npublic:\n\n\tint CalculateMovement()\n\t{\n\t\tEigen::Matrix3f rotLCA;\n\t\tEigen::Matrix3f rotUCA;\n\t\tEigen::MatrixXf tr2prGlob;\n\t\tfloat rLCA;\n\t\tfloat rUCA;\n\t\tfloat rCA;   // distance between LCA3 and UCA3\n\t\tfloat rST;   // distance between TR2 and UCA3LCA3 axis\n\t\tfloat rTR;   // distance between TR2 and TR1 axis\n\t\tfloat t_param;   // parameter to determine position of TR2pr on uca3lca3 line\n\t\t// coordinates of wcn and spn in TR cs defined by tr2ref\n\t\tEigen::Vector3f wcnlocTRk;\n\t\tEigen::Vector3f spnlocTRk;\n\n\t\tEigen::ArrayXf zLCA3LocLCA(vertIncr * 2 + 1);\n\n\t\tSuspension::CalculateConstants(rotLCA, rotUCA, rLCA, rUCA, rCA, zLCA3LocLCA, rST, t_param, rTR, wcnlocTRk, spnlocTRk);\n\n\t\tEigen::MatrixXf lca3LocLCA(vertIncr * 2 + 1, 3);\n\t\tEigen::MatrixXf lca3Glob(vertIncr * 2 + 1, 3);\n\n\t\t// populating positions of local LCA3 in a matrix\n\t\tlca3LocLCA.col(0) << Eigen::VectorXf::Zero(vertIncr * 2 + 1);\n\t\tlca3LocLCA.col(1) << -(rLCA*rLCA - zLCA3LocLCA * zLCA3LocLCA).sqrt();\n\t\tlca3LocLCA.col(2) << zLCA3LocLCA;\n\n\t\t// global positions of LCA3 for whole wheel movement\n\t\tlca3Glob = (lca3LocLCA * rotLCA.transpose()).array().rowwise() + lca12.array().transpose();\n\n\t\t// global position of UCA3 for whole wheel movement\n\t\tEigen::MatrixXf uca3Glob(vertIncr * 2 + 1, 3);\n\t\tEigen::MatrixXf uca3LocUCA(vertIncr * 2 + 1, 3);\n\t\tEigen::MatrixXf lca3LocUCA(vertIncr * 2 + 1, 3);\n\n\t\tlca3LocUCA = lca3Glob.rowwise() - uca12.transpose();\n\t\tlca3LocUCA = lca3LocUCA * rotUCA;\n\n\n\t\t// temporary values for calculating UCA3 in UCA cs, correspond to chunks of expression in word\n\t\tEigen::ArrayXf temp1UCA3 =\n\t\t\t-rCA * rCA + rUCA * rUCA + \n\t\t\tlca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() +\n\t\t\tlca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() + \n\t\t\tlca3LocUCA.col(2).array() * lca3LocUCA.col(2).array();\n\n\t\tEigen::ArrayXf temp2UCA3 =\n\t\t\t2 * (lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() +\n\t\t\tlca3LocUCA.col(2).array() * lca3LocUCA.col(2).array());\n\n\t\tEigen::ArrayXf temp3UCA3 =\n\t\t\t-rCA * rCA * rCA * rCA + 2 * rCA * rCA * rUCA * rUCA +\n\t\t\t2 * rCA * rCA * lca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() +\n\t\t\t2 * rCA * rCA * lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() +\n\t\t\t2 * rCA * rCA * lca3LocUCA.col(2).array() * lca3LocUCA.col(2).array();\n\n\t\tEigen::ArrayXf temp4UCA3 = \n\t\t\t-rUCA * rUCA * rUCA * rUCA -\n\t\t\t2 * rUCA * rUCA * lca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() +\n\t\t\t2 * rUCA * rUCA * lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() + \n\t\t\t2 * rUCA * rUCA * lca3LocUCA.col(2).array() * lca3LocUCA.col(2).array();\n\n\t\tEigen::ArrayXf temp5UCA3 = \n\t\t\t-lca3LocUCA.col(0).array() * lca3LocUCA.col(0).array()* lca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() -\n\t\t\t2 * lca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() * lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() -\n\t\t\t2 * lca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() * lca3LocUCA.col(2).array() * lca3LocUCA.col(2).array();\n\n\t\tEigen::ArrayXf temp6UCA3 = \n\t\t\t-lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array()* lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() -\n\t\t\t2 * lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() * lca3LocUCA.col(2).array() * lca3LocUCA.col(2).array() -\n\t\t\tlca3LocUCA.col(2).array() * lca3LocUCA.col(2).array() * lca3LocUCA.col(2).array() * lca3LocUCA.col(2).array();\n\n\t\tEigen::ArrayXf temp7UCA3 = (temp3UCA3 + temp4UCA3 + temp5UCA3 + temp6UCA3).sqrt();\n\n\t\tuca3LocUCA.col(0) << Eigen::VectorXf::Zero(vertIncr * 2 + 1);\n\t\tuca3LocUCA.col(1) << (lca3LocUCA.col(1).array() * temp1UCA3 - lca3LocUCA.col(2).array() * temp7UCA3) / temp2UCA3;\n\t\tuca3LocUCA.col(2) << (lca3LocUCA.col(2).array() * temp1UCA3 + lca3LocUCA.col(1).array() * temp7UCA3) / temp2UCA3;\n\n\t\t\n\t\tuca3Glob = (uca3LocUCA * rotUCA.transpose()).array().rowwise() + uca12.array().transpose();\n\n\n\n\n\t\t// calculating TR2, WCN, SPN and CP\n\t\t// steering is not enabled, for optimization\n\t\tif (steerIncr!=0 || wSteer!=0)\n\t\t{ \n\n\t\t\tstd::cout << \"no steer movement\" << std::endl;\n\t\t\t// calculating TR2 position\n\t\t\tEigen::MatrixXf tr2Glob(vertIncr * 2 + 1, 3);\n\t\t\tEigen::MatrixXf wcnGlob(vertIncr * 2 + 1, 3);\n\t\t\tEigen::MatrixXf spnGlob(vertIncr * 2 + 1, 3);\n\n\t\t\ttr2prGlob = (uca3Glob - lca3Glob) * t_param + lca3Glob;\n\n\t\t\tfor (int i = 0; i < vertIncr * 2 + 1; i++)\n\t\t\t{\n\t\t\t\tEigen::Matrix3f rotTR;\n\t\t\t\tEigen::Vector3f tr2locTR;\n\n\t\t\t\tEigen::Vector3f xCol{ 30, 0, -30 * (uca3Glob(i, 0) - lca3Glob(i, 0)) / (uca3Glob(i, 2) - lca3Glob(i, 2)) };\n\t\t\t\tEigen::Vector3f zCol{ (lca3Glob.row(i) - uca3Glob.row(i)).transpose() };\n\t\t\t\tEigen::Vector3f yCol{ zCol.cross(xCol) };\n\n\n\t\t\t\trotTR.col(0) << xCol / xCol.norm();\n\t\t\t\trotTR.col(1) << yCol / yCol.norm();\n\t\t\t\trotTR.col(2) << zCol / zCol.norm();\n\n\n\t\t\t\t// calculate local position of TR1\n\t\t\t\tEigen::Vector3f tr1locTR;\n\n\t\t\t\t//lca3LocUCA = lca3Glob.rowwise() - uca12.transpose();\n\t\t\t\t//lca3LocUCA = lca3LocUCA * rotUCA;\n\n\t\t\t\ttr1locTR = -tr2prGlob.row(i) + tr1ref.transpose();\n\t\t\t\ttr1locTR = rotTR.transpose() * tr1locTR;\n\n\n\t\t\t\t// calculate local position of TR2\n\t\t\t\tfloat temp1TR2 =\n\t\t\t\t\trST * rST - rTR * rTR +\n\t\t\t\t\ttr1locTR(0) * tr1locTR(0) + \n\t\t\t\t\ttr1locTR(1) * tr1locTR(1) + \n\t\t\t\t\ttr1locTR(2) * tr1locTR(2);\n\n\t\t\t\tfloat temp2TR2 = 2 * (tr1locTR(0) * tr1locTR(0) + tr1locTR(1) * tr1locTR(1));\n\n\t\t\t\tfloat temp3TR2 =\n\t\t\t\t\t-rST * rST * rST * rST +\n\t\t\t\t\t2 * rTR * rTR * rST * rST + \n\t\t\t\t\t2 * rST * rST * tr1locTR(0) * tr1locTR(0) + \n\t\t\t\t\t2 * rST * rST * tr1locTR(1) * tr1locTR(1) -\n\t\t\t\t\t2 * rST * rST * tr1locTR(2) * tr1locTR(2);\n\n\t\t\t\tfloat temp4TR2 =\n\t\t\t\t\t-rTR * rTR * rTR * rTR +\n\t\t\t\t\t2 * rTR * rTR * tr1locTR(0) * tr1locTR(0) + \n\t\t\t\t\t2 * rTR * rTR * tr1locTR(1) * tr1locTR(1) + \n\t\t\t\t\t2 * rTR * rTR * tr1locTR(2) * tr1locTR(2);\n\n\t\t\t\tfloat temp5TR2 = \n\t\t\t\t\t-tr1locTR(0) * tr1locTR(0) * tr1locTR(0) * tr1locTR(0) - \n\t\t\t\t\t2 * tr1locTR(0) * tr1locTR(0) * tr1locTR(1) * tr1locTR(1) - \n\t\t\t\t\t2 * tr1locTR(0) * tr1locTR(0) * tr1locTR(2) * tr1locTR(2);\n\n\t\t\t\tfloat temp6TR2 =\n\t\t\t\t\t-2 * tr1locTR(1) * tr1locTR(1) * tr1locTR(2) * tr1locTR(2) - \n\t\t\t\t\ttr1locTR(1) * tr1locTR(1) * tr1locTR(1) * tr1locTR(1) -\n\t\t\t\t\ttr1locTR(2) * tr1locTR(2) * tr1locTR(2) * tr1locTR(2);\n\n\t\t\t\tfloat temp7TR2 = std::sqrt(temp3TR2 + temp4TR2 + temp5TR2 + temp6TR2);\n\n\n\t\t\t\ttr2locTR(0) = (tr1locTR(0) * temp1TR2 - tr1locTR(1) * temp7TR2) / temp2TR2;\n\t\t\t\ttr2locTR(1) = (tr1locTR(1) * temp1TR2 + tr1locTR(0) * temp7TR2) / temp2TR2;\n\t\t\t\ttr2locTR(2) = 0;\n\n\t\t\t\ttr2Glob.row(i) << (rotTR * tr2locTR).transpose() + tr2prGlob.row(i);\n\n\t\t\t\t// calculating WCN and SPN \n\t\t\t\tEigen::Matrix3f _rotTRk; // TR rotation matrix defined by TR2ref\n\n\t\t\t\tEigen::Vector3f _xCol{ tr2prGlob.row(i) - tr2Glob.row(i) };\n\t\t\t\tEigen::Vector3f _zCol{ lca3Glob.row(i) - uca3Glob.row(i) };\n\t\t\t\tEigen::Vector3f _yCol{ _zCol.cross(_xCol) };\n\n\n\t\t\t\t_rotTRk.col(0) << _xCol / _xCol.norm();\n\t\t\t\t_rotTRk.col(1) << _yCol / _yCol.norm();\n\t\t\t\t_rotTRk.col(2) << _zCol / _zCol.norm();\n\n\t\t\t\twcnGlob.row(i) << (_rotTRk * wcnlocTRk).transpose() + tr2prGlob.row(i);\n\t\t\t\tspnGlob.row(i) << (_rotTRk * spnlocTRk).transpose() + tr2prGlob.row(i);\n\n\t\t\t}\n\n\t\t\t// CP calculation\n\t\t\tfloat temp1cp{ -20 }; // this is actually vector 0,0,-20\n\t\t\tEigen::MatrixXf temp2cp(vertIncr * 2 + 1, 3);\n\t\t\tEigen::MatrixXf temp3cp(vertIncr * 2 + 1, 3);\n\n\t\t\ttemp2cp << spnGlob - wcnGlob;\n\n\t\t\tstd::cout << \"temp2cp  \" << std::endl;\n\t\t\tstd::cout << temp2cp << std::endl;\n\n\t\t\ttemp3cp.col(0) << -temp2cp.col(0).array() * temp2cp.col(2).array() * temp1cp;\n\t\t\ttemp3cp.col(1) << -temp2cp.col(1).array() * temp2cp.col(2).array() * temp1cp;\n\t\t\ttemp3cp.col(2) << \n\t\t\t\ttemp2cp.col(1).array() * temp2cp.col(1).array() * temp1cp + \n\t\t\t\ttemp2cp.col(0).array() * temp2cp.col(0).array() * temp1cp;\n\n\t\t\ttemp3cp.rowwise().normalize();\n\n\t\t\tEigen::MatrixXf cpGlob(vertIncr * 2 + 1, 3);\n\n\t\t\tcpGlob << -temp3cp * wRadius + wcnGlob;\n\n\n\t\t\tstd::cout << \"cp  \" << std::endl;\n\t\t\tstd::cout << cpGlob << std::endl;\n\t\t\treturn 123;\n\n\t\t}\n\n\t\t// steering is enabled\n\t\telse\n\t\t{\n\t\treturn 456;\n\t\t}\n\n\n\t}\n\n\n};\n\nint main()\n{\n\tSuspension susp{ \n\t\t-2038.666, -411.709, -132.316,\n\t\t-2241.147, -408.195, -126.205,\n\t\t-2135, -600, -140,\n\t\t-2040.563, -416.249, -275.203,\n\t\t-2241.481, -417.314, -270.739,\n\t\t-2153, -578, -315,\n\t\t-2234.8, -411.45, -194.6,\n\t\t-2225, -582, -220,\n\t\t-2143.6, -620.5, -220.07,\n\t\t-2143.6, -595.5, -219.34,\n\t\t210, 30, 30, 1,\n\t\t10, 0.01\n\t};\n\n\tint i = susp.CalculateMovement();\n\tstd::cout << i << std::endl;\n\n\tstd::cout << addition(15,20) << std::endl;\n\n\n\tSuspension susp2{};\n\n\tsusp2.CalculateMovement();\n\n\n\t/*\n\t-2038.666,-411.709,-132.316,-2241.147,-408.195,-126.205,-2135,-600,-140,-2040.563,-416.249,-275.203,-2241.481,-417.314,-270.739,-2153,-578,-315,-2234.8,-411.45,-194.6,-2225,-582,-220,-2143.6,-620.5,-220.07,-2143.6,-595.5,-219.34\n\t\n\t\n\t*/\n\n}", "meta": {"hexsha": "03e88ef569f7deb0e4712ceca480eb681ffc2e81", "size": 15287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FS-BMK/src/Main.cpp", "max_stars_repo_name": "brunomraz/FS-BMK", "max_stars_repo_head_hexsha": "793f41d0aebaaa6ce3539b31e82bf179780d05ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-26T16:26:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T16:26:16.000Z", "max_issues_repo_path": "FS-BMK/src/Main.cpp", "max_issues_repo_name": "brunomraz/FS-BMK", "max_issues_repo_head_hexsha": "793f41d0aebaaa6ce3539b31e82bf179780d05ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FS-BMK/src/Main.cpp", "max_forks_repo_name": "brunomraz/FS-BMK", "max_forks_repo_head_hexsha": "793f41d0aebaaa6ce3539b31e82bf179780d05ca", "max_forks_repo_licenses": ["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.6352705411, "max_line_length": 245, "alphanum_fraction": 0.6442729116, "num_tokens": 6450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5321834955030911}}
{"text": "#include <cmath>\n#include <functional>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include <boost/functional/hash.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <CGAL/boost/graph/helpers.h>\n#include <CGAL/boost/graph/Dual.h>\n#include <Euclid/Math/Vector.h>\n#include <Euclid/Util/Assert.h>\n\nnamespace Euclid\n{\n\ntemplate<typename Mesh>\nVector_3_t<Mesh> vertex_normal(vertex_t<Mesh> v,\n                               const Mesh& mesh,\n                               const VertexNormal& weight)\n{\n    Vector_3_t<Mesh> normal(0.0, 0.0, 0.0);\n    for (auto he : CGAL::halfedges_around_source(v, mesh)) {\n        if (!CGAL::is_border(he, mesh)) {\n            auto f = face(he, mesh);\n            auto fn = face_normal(f, mesh);\n\n            if (weight == VertexNormal::uniform) {\n                normal += fn;\n            }\n            else if (weight == VertexNormal::face_area) {\n                auto area = face_area(f, mesh);\n                normal += area * fn;\n            }\n            else { // incident_angle\n                auto angle = corner_angle(he, mesh);\n                normal += angle * fn;\n            }\n        }\n    }\n    return Euclid::normalized(normal);\n}\n\ntemplate<typename Mesh>\nVector_3_t<Mesh> vertex_normal(\n    vertex_t<Mesh> v,\n    const Mesh& mesh,\n    const std::vector<Vector_3_t<Mesh>>& face_normals,\n    const VertexNormal& weight)\n{\n    auto fimap = get(boost::face_index, mesh);\n    Vector_3_t<Mesh> normal(0.0, 0.0, 0.0);\n    for (auto he : CGAL::halfedges_around_source(v, mesh)) {\n        if (!CGAL::is_border(he, mesh)) {\n            auto f = face(he, mesh);\n            auto fi = get(fimap, f);\n            auto fn = face_normals[fi];\n\n            if (weight == VertexNormal::uniform) {\n                normal += fn;\n            }\n            else if (weight == VertexNormal::face_area) {\n                auto area = face_area(f, mesh);\n                normal += area * fn;\n            }\n            else { // incident_angle\n                auto angle = corner_angle(he, mesh);\n                normal += angle * fn;\n            }\n        }\n    }\n    return Euclid::normalized(normal);\n}\n\ntemplate<typename Mesh>\nstd::vector<Vector_3_t<Mesh>> vertex_normals(\n    const Mesh& mesh,\n    const std::vector<Vector_3_t<Mesh>>& face_normals,\n    const VertexNormal& weight)\n{\n    std::vector<Vector_3_t<Mesh>> vnormals;\n    vnormals.reserve(num_vertices(mesh));\n    for (auto v : vertices(mesh)) {\n        vnormals.push_back(vertex_normal(v, mesh, face_normals, weight));\n    }\n    return vnormals;\n}\n\ntemplate<typename Mesh>\nFT_t<Mesh> vertex_area(vertex_t<Mesh> v,\n                       const Mesh& mesh,\n                       const VertexArea& method)\n{\n    using T = FT_t<Mesh>;\n    auto vpmap = get(boost::vertex_point, mesh);\n    auto va = T(0);\n    if (method == VertexArea::barycentric) {\n        const auto one_third = boost::math::constants::third<T>();\n        for (auto he : CGAL::halfedges_around_target(v, mesh)) {\n            if (!CGAL::is_border(he, mesh)) {\n                auto p1 = get(vpmap, source(he, mesh));\n                auto p2 = get(vpmap, target(he, mesh));\n                auto p3 = get(vpmap, target(next(he, mesh), mesh));\n                va += area(p1, p2, p3);\n            }\n        }\n        va *= one_third;\n    }\n    else if (method == VertexArea::voronoi) {\n        for (auto he : CGAL::halfedges_around_target(v, mesh)) {\n            if (!CGAL::is_border(he, mesh)) {\n                auto p1 = get(vpmap, source(he, mesh));\n                auto p2 = get(vpmap, target(he, mesh));\n                auto p3 = get(vpmap, target(next(he, mesh), mesh));\n                auto mid1 = CGAL::midpoint(p2, p1);\n                auto mid2 = CGAL::midpoint(p2, p3);\n                auto center = CGAL::circumcenter(p1, p2, p3);\n                if (CGAL::angle(p2, p1, p3) == CGAL::OBTUSE) {\n                    va += area(mid1, p2, center) - area(mid2, center, p2);\n                }\n                else if (CGAL::angle(p2, p3, p1) == CGAL::OBTUSE) {\n                    va += area(mid2, center, p2) - area(mid1, p2, center);\n                }\n                else {\n                    va += area(mid1, p2, center) + area(mid2, center, p2);\n                }\n            }\n        }\n    }\n    else { // method == VertexArea::mixed_voronoi\n        for (auto he : CGAL::halfedges_around_target(v, mesh)) {\n            if (!CGAL::is_border(he, mesh)) {\n                auto p1 = get(vpmap, source(he, mesh));\n                auto p2 = get(vpmap, target(he, mesh));\n                auto p3 = get(vpmap, target(next(he, mesh), mesh));\n                if (CGAL::angle(p1, p2, p3) == CGAL::OBTUSE) {\n                    va += area(p1, p2, p3) * 0.5;\n                }\n                else if (CGAL::angle(p3, p1, p2) == CGAL::OBTUSE ||\n                         CGAL::angle(p1, p3, p2) == CGAL::OBTUSE) {\n                    va += area(p1, p2, p3) * 0.25;\n                }\n                else { // triangle is acute or right\n                    auto mid1 = CGAL::midpoint(p2, p1);\n                    auto mid2 = CGAL::midpoint(p2, p3);\n                    auto center = CGAL::circumcenter(p1, p2, p3);\n                    va += area(mid1, p2, center) + area(mid2, center, p2);\n                }\n            }\n        }\n    }\n    return va;\n}\n\ntemplate<typename Mesh>\nstd::vector<FT_t<Mesh>> vertex_areas(const Mesh& mesh, const VertexArea& method)\n{\n    std::vector<FT_t<Mesh>> vareas;\n    vareas.reserve(num_vertices(mesh));\n    for (auto v : vertices(mesh)) {\n        vareas.push_back(vertex_area(v, mesh, method));\n    }\n    return vareas;\n}\n\n// partial specialization for dual mesh\ntemplate<typename Mesh>\nFT_t<Mesh> edge_length(halfedge_t<Mesh> h, const CGAL::Dual<Mesh>& dual)\n{\n    auto primal = dual.primal();\n    auto f0 = source(h, dual);\n    auto f1 = target(h, dual);\n    auto p0 = barycenter(f0, primal);\n    auto p1 = barycenter(f1, primal);\n    return length(p1 - p0);\n}\n\ntemplate<typename Mesh>\nFT_t<Mesh> edge_length(halfedge_t<Mesh> he, const Mesh& mesh)\n{\n    auto vpmap = get(boost::vertex_point, mesh);\n    auto p1 = get(vpmap, source(he, mesh));\n    auto p2 = get(vpmap, target(he, mesh));\n    return length(p2 - p1);\n}\n\ntemplate<typename Mesh>\nFT_t<Mesh> edge_length(edge_t<Mesh> e, const Mesh& mesh)\n{\n    auto he = halfedge(e, mesh);\n    return edge_length(he, mesh);\n}\n\ntemplate<typename Mesh>\nstd::vector<FT_t<Mesh>> edge_lengths(const Mesh& mesh)\n{\n    std::vector<FT_t<Mesh>> elens;\n    elens.reserve(num_edges(mesh));\n    for (auto he : edges(mesh)) {\n        elens.push_back(edge_length(he, mesh));\n    }\n    return elens;\n}\n\n// partial specialization for dual mesh\ntemplate<typename Mesh>\nFT_t<Mesh> squared_edge_length(edge_t<Mesh> e, const CGAL::Dual<Mesh>& dual)\n{\n    auto primal = dual.primal();\n    auto h = halfedge(e, dual);\n    auto f0 = source(h, dual);\n    auto f1 = target(h, dual);\n    auto p0 = barycenter(f0, primal);\n    auto p1 = barycenter(f1, primal);\n    return (p1 - p0).squared_length();\n}\n\ntemplate<typename Mesh>\nFT_t<Mesh> squared_edge_length(halfedge_t<Mesh> he, const Mesh& mesh)\n{\n    auto vpmap = get(boost::vertex_point, mesh);\n    auto p1 = get(vpmap, source(he, mesh));\n    auto p2 = get(vpmap, target(he, mesh));\n    return (p1 - p2).squared_length();\n}\n\ntemplate<typename Mesh>\nFT_t<Mesh> squared_edge_length(edge_t<Mesh> e, const Mesh& mesh)\n{\n    auto he = halfedge(e, mesh);\n    return squared_edge_length(he, mesh);\n}\n\ntemplate<typename Mesh>\nstd::vector<FT_t<Mesh>> squared_edge_lengths(const Mesh& mesh)\n{\n    std::vector<FT_t<Mesh>> elens;\n    elens.reserve(num_edges(mesh));\n    for (auto he : edges(mesh)) {\n        elens.push_back(squared_edge_length(he, mesh));\n    }\n    return elens;\n}\n\ntemplate<typename Mesh>\nFT_t<Mesh> dihedral_angle(edge_t<Mesh> e, const Mesh& mesh)\n{\n    auto h1 = halfedge(e, mesh);\n    auto h2 = opposite(h1, mesh);\n    auto f1 = face(h1, mesh);\n    auto f2 = face(h2, mesh);\n    auto n1 = face_normal(f1, mesh);\n    auto n2 = face_normal(f2, mesh);\n    return boost::math::constants::pi<FT_t<Mesh>>() - std::acos(cosine(n1, n2));\n}\n\ntemplate<typename Mesh>\nFT_t<Mesh> corner_angle(halfedge_t<Mesh> h, const Mesh& mesh)\n{\n    auto vpmap = get(boost::vertex_point, mesh);\n    auto p1 = get(vpmap, source(h, mesh));\n    auto p2 = get(vpmap, target(h, mesh));\n    auto p3 = get(vpmap, target(next(h, mesh), mesh));\n    return CGAL::approximate_angle(p1, p2, p3);\n}\n\ntemplate<typename Mesh>\nVector_3_t<Mesh> face_normal(face_t<Mesh> f, const Mesh& mesh)\n{\n    using Vector_3 = Vector_3_t<Mesh>;\n    auto vpmap = get(boost::vertex_point, mesh);\n    auto he = halfedge(f, mesh);\n    auto p1 = get(vpmap, source(he, mesh));\n    auto p2 = get(vpmap, target(he, mesh));\n    auto p3 = get(vpmap, target(next(he, mesh), mesh));\n\n    Vector_3 result;\n    if (CGAL::collinear(p1, p2, p3)) {\n        EWARNING(\"Degenerate face, normal is set to zero vector\");\n        result = Vector_3(0.0, 0.0, 0.0);\n    }\n    else {\n        result = normalized(CGAL::normal(p1, p2, p3));\n    }\n    return result;\n}\n\ntemplate<typename Mesh>\nstd::vector<Vector_3_t<Mesh>> face_normals(const Mesh& mesh)\n{\n    std::vector<Vector_3_t<Mesh>> fnormals;\n    fnormals.reserve(num_faces(mesh));\n    for (auto f : faces(mesh)) {\n        fnormals.push_back(face_normal(f, mesh));\n    }\n    return fnormals;\n}\n\ntemplate<typename Mesh>\nFT_t<Mesh> face_area(face_t<Mesh> f, const Mesh& mesh)\n{\n    auto vpmap = get(boost::vertex_point, mesh);\n    auto he = halfedge(f, mesh);\n    auto p1 = get(vpmap, source(he, mesh));\n    auto p2 = get(vpmap, target(he, mesh));\n    auto p3 = get(vpmap, target(next(he, mesh), mesh));\n    return area(p1, p2, p3);\n}\n\ntemplate<typename Mesh>\nstd::vector<FT_t<Mesh>> face_areas(const Mesh& mesh)\n{\n    std::vector<FT_t<Mesh>> fareas;\n    fareas.reserve(num_faces(mesh));\n    for (auto f : faces(mesh)) {\n        fareas.push_back(face_area(f, mesh));\n    }\n    return fareas;\n}\n\ntemplate<typename Mesh>\nPoint_3_t<Mesh> barycenter(face_t<Mesh> f, const Mesh& mesh)\n{\n    auto vpmap = get(boost::vertex_point, mesh);\n    auto [vbeg, vend] = CGAL::vertices_around_face(halfedge(f, mesh), mesh);\n    auto p0 = get(vpmap, *vbeg++);\n    auto p1 = get(vpmap, *vbeg++);\n    auto p2 = get(vpmap, *vbeg);\n    return CGAL::centroid(p0, p1, p2);\n}\n\ntemplate<typename Mesh>\nstd::vector<Point_3_t<Mesh>> barycenters(const Mesh& mesh)\n{\n    std::vector<Point_3_t<Mesh>> centroids;\n    centroids.reserve(num_faces(mesh));\n    for (auto f : faces(mesh)) {\n        centroids.push_back(barycenter(f, mesh));\n    }\n    return centroids;\n}\n\ntemplate<typename Mesh>\nFT_t<Mesh> gaussian_curvature(vertex_t<Mesh> v, const Mesh& mesh)\n{\n    auto angle_defect = boost::math::constants::two_pi<FT_t<Mesh>>();\n    for (auto he : CGAL::halfedges_around_target(v, mesh)) {\n        if (!CGAL::is_border(he, mesh)) {\n            angle_defect -= corner_angle(he, mesh);\n        }\n    }\n    return angle_defect / vertex_area(v, mesh);\n}\n\ntemplate<typename Mesh>\nstd::vector<FT_t<Mesh>> gaussian_curvatures(const Mesh& mesh)\n{\n    std::vector<FT_t<Mesh>> curvatures;\n    curvatures.reserve(num_vertices(mesh));\n    for (auto v : vertices(mesh)) {\n        curvatures.push_back(gaussian_curvature(v, mesh));\n    }\n    return curvatures;\n}\n\ntemplate<typename Mesh>\nstd::tuple<Eigen::SparseMatrix<FT_t<Mesh>>, Eigen::SparseMatrix<FT_t<Mesh>>>\nadjacency_matrix(const Mesh& mesh)\n{\n    using T = FT_t<Mesh>;\n    using Triplet = Eigen::Triplet<T>;\n    auto vimap = get(boost::vertex_index, mesh);\n    const auto nv = num_vertices(mesh);\n\n    std::vector<Triplet> adj, degree;\n    for (auto vi : vertices(mesh)) {\n        int i = get(vimap, vi);\n        int d = 0;\n        for (auto he : CGAL::halfedges_around_target(vi, mesh)) {\n            auto vj = source(he, mesh);\n            int j = get(vimap, vj);\n            adj.emplace_back(i, j, 1);\n            ++d;\n        }\n        degree.emplace_back(i, i, d);\n    }\n\n    Eigen::SparseMatrix<T> adj_mat(nv, nv), degree_mat(nv, nv);\n    adj_mat.setFromTriplets(adj.begin(), adj.end());\n    adj_mat.makeCompressed();\n    degree_mat.setFromTriplets(degree.begin(), degree.end());\n    degree_mat.makeCompressed();\n    return std::make_tuple(adj_mat, degree_mat);\n}\n\ntemplate<typename Mesh>\nEigen::SparseMatrix<FT_t<Mesh>> graph_laplacian_matrix(const Mesh& mesh)\n{\n    using T = FT_t<Mesh>;\n    using Triplet = Eigen::Triplet<T>;\n    auto vimap = get(boost::vertex_index, mesh);\n    const auto nv = num_vertices(mesh);\n\n    std::vector<Triplet> triplets;\n    for (auto vi : vertices(mesh)) {\n        int i = get(vimap, vi);\n        int d = 0;\n        for (auto he : CGAL::halfedges_around_target(vi, mesh)) {\n            auto vj = source(he, mesh);\n            int j = get(vimap, vj);\n            triplets.emplace_back(i, j, -1);\n            ++d;\n        }\n        triplets.emplace_back(i, i, d);\n    }\n\n    Eigen::SparseMatrix<T> L(nv, nv);\n    L.setFromTriplets(triplets.begin(), triplets.end());\n    L.makeCompressed();\n    return L;\n}\n\ntemplate<typename Mesh>\nFT_t<Mesh> cotangent_weight(halfedge_t<Mesh> he, const Mesh& mesh)\n{\n    auto vpmap = get(boost::vertex_point, mesh);\n    auto vi = source(he, mesh);\n    auto vj = target(he, mesh);\n    auto va = target(next(he, mesh), mesh);\n    auto vb = target(next(opposite(he, mesh), mesh), mesh);\n    auto pi = get(vpmap, vi);\n    auto pj = get(vpmap, vj);\n    auto pa = get(vpmap, va);\n    auto pb = get(vpmap, vb);\n    auto cota = cotangent(pi, pa, pj);\n    auto cotb = cotangent(pi, pb, pj);\n    return (cota + cotb) * static_cast<FT_t<Mesh>>(0.5);\n}\n\ntemplate<typename Mesh>\nFT_t<Mesh> cotangent_weight(edge_t<Mesh> e, const Mesh& mesh)\n{\n    auto he = halfedge(e, mesh);\n    return cotangent_weight(he, mesh);\n}\n\ntemplate<typename Mesh>\nEigen::SparseMatrix<FT_t<Mesh>> cotangent_matrix(const Mesh& mesh)\n{\n    using T = FT_t<Mesh>;\n    using Triplet = Eigen::Triplet<T>;\n    auto vimap = get(boost::vertex_index, mesh);\n    const auto nv = num_vertices(mesh);\n\n    auto hash_fcn = [](const Triplet& t) {\n        size_t seed = 0;\n        boost::hash_combine(seed, t.col());\n        boost::hash_combine(seed, t.row());\n        return seed;\n    };\n    auto eq_fcn = [](const Triplet& t1, const Triplet& t2) {\n        return (t1.col() == t2.col()) && (t1.row() == t2.row());\n    };\n    std::unordered_set<Triplet, decltype(hash_fcn), decltype(eq_fcn)> values(\n        nv, hash_fcn, eq_fcn);\n\n    for (auto vi : vertices(mesh)) {\n        int i = get(vimap, vi);\n        T row_sum = 0.0;\n        for (auto he : CGAL::halfedges_around_target(vi, mesh)) {\n            auto vj = source(he, mesh);\n            int j = get(vimap, vj);\n            auto existing = values.find(Triplet(j, i, 0.0));\n            if (existing != values.end()) {\n                values.emplace(i, j, existing->value());\n                row_sum -= existing->value();\n            }\n            else {\n                auto value = cotangent_weight(he, mesh);\n                values.emplace(i, j, -value);\n                row_sum += value;\n            }\n        }\n        values.emplace(i, i, row_sum);\n    }\n\n    Eigen::SparseMatrix<T> mat(nv, nv);\n    mat.setFromTriplets(values.begin(), values.end());\n    mat.makeCompressed();\n    return mat;\n}\n\ntemplate<typename Mesh>\nEigen::SparseMatrix<FT_t<Mesh>> mass_matrix(const Mesh& mesh,\n                                            const VertexArea& method)\n{\n    using T = FT_t<Mesh>;\n    const auto nv = num_vertices(mesh);\n    Eigen::SparseMatrix<T> mass(nv, nv);\n    std::vector<Eigen::Triplet<T>> values;\n\n    int i = 0;\n    for (auto v : vertices(mesh)) {\n        auto area = vertex_area(v, mesh, method);\n        values.emplace_back(i, i, area);\n        ++i;\n    }\n\n    mass.setFromTriplets(values.begin(), values.end());\n    mass.makeCompressed();\n    return mass;\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "a129ed2abd67533c268e59ac48b20c2724c502b3", "size": 15853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/Geometry/src/TriMeshGeometry.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/Geometry/src/TriMeshGeometry.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/Geometry/src/TriMeshGeometry.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": 30.7825242718, "max_line_length": 80, "alphanum_fraction": 0.5835488551, "num_tokens": 4345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5321834935330348}}
{"text": "#include \"gru_cell_old.hpp\"\n#include \"generic/activity.hpp\"\n#include \"generic/utils.hpp\"\n#include <Eigen/SVD>\n\nnamespace rnn {\ngru_cell_old::gru_cell_old(const int inputDim, const int hiddenDim) {\n  this->Wxr = MatD(hiddenDim, inputDim);\n  this->Whr = MatD(hiddenDim, hiddenDim);\n  this->br = VecD::Zero(hiddenDim);\n\n  this->Wxz = MatD(hiddenDim, inputDim);\n  this->Whz = MatD(hiddenDim, hiddenDim);\n  this->bz = VecD::Zero(hiddenDim);\n\n  this->Wxu = MatD(hiddenDim, inputDim);\n  this->Whu = MatD(hiddenDim, hiddenDim);\n  this->bu = VecD::Zero(hiddenDim);\n}\n\nvoid gru_cell_old::init(rnn::generic::rand &rnd, const real scale) {\n  rnd.uniform(this->Wxr, scale);\n  rnd.uniform(this->Whr, scale);\n\n  rnd.uniform(this->Wxz, scale);\n  rnd.uniform(this->Whz, scale);\n\n  rnd.uniform(this->Wxu, scale);\n  rnd.uniform(this->Whu, scale);\n\n  this->Whr = Eigen::JacobiSVD<MatD>(this->Whr, Eigen::ComputeFullV |\n      Eigen::ComputeFullU).matrixU();\n  this->Whz = Eigen::JacobiSVD<MatD>(this->Whz, Eigen::ComputeFullV |\n      Eigen::ComputeFullU).matrixU();\n  this->Whu = Eigen::JacobiSVD<MatD>(this->Whu, Eigen::ComputeFullV |\n      Eigen::ComputeFullU).matrixU();\n}\n\ngru_cell_old::State gru_cell_old::forward(const VecD &xt, const gru_cell_old::State &prev) {\n//U=Wx, W=Wh, h^=u\n  gru_cell_old::State cur;\n  cur.r = br + Wxr * xt + Whr * prev.h;\n  cur.z = bz + Wxz * xt + Whz * prev.h;\n\n  activity::logistic(cur.r);\n  activity::logistic(cur.z);\n\n  cur.rh = cur.r.array() * prev.h.array();\n  cur.u = bu + Wxu * xt + Whu * cur.rh;\n  activity::tanh(cur.u);\n  cur.h = (1.0 - cur.z.array()) * cur.u.array() +\n      cur.z.array() * prev.h.array();\n  return cur;\n}\n\nvoid gru_cell_old::backward(gru_cell_old::State *prev, gru_cell_old::State *cur, gru_cell_old::Grad &grad,\n                        const VecD &xt) {\n  VecD delr, delz, delu, delrh;\n  //d7=delz\n  delz = activity::logisticPrime(cur->z).array() * cur->delh.array() *\n      (cur->u - prev->h).array();\n  delu =\n      activity::tanhPrime(cur->u).array() * cur->delh.array() * cur->z.array();\n  delrh = Whu.transpose() * delu;\n  delr =\n      activity::logisticPrime(cur->r).array() * delrh.array() * prev->h.array();\n\n  cur->delx = Wxr.transpose() * delr\n      + Wxz.transpose() * delz\n      + Wxu.transpose() * delu;\n\n  prev->delh.noalias() += Whr.transpose() * delr + Whz.transpose() * delz;\n  prev->delh.array() += delrh.array() * cur->r.array() +\n          cur->delh.array() * (1.0 - cur->z.array());\n\n  grad.Wxr.noalias() += delr * xt.transpose();\n  grad.Whr.noalias() += delr * prev->h.transpose();\n\n  grad.Wxz.noalias() += delz * xt.transpose();\n  grad.Whz.noalias() += delz * prev->h.transpose();\n\n  grad.Wxu.noalias() += delu * xt.transpose();\n  grad.Whu.noalias() += delu * cur->rh.transpose();\n\n  grad.br += delr;\n  grad.bz += delz;\n  grad.bu += delu;\n}\n\nvoid gru_cell_old::sgd(const gru_cell_old::Grad &grad, const real learningRate) {\n  Wxr -= learningRate * grad.Wxr;\n  Whr -= learningRate * grad.Whr;\n  br -= learningRate * grad.br;\n\n  Wxz -= learningRate * grad.Wxz;\n  Whz -= learningRate * grad.Whz;\n  bz -= learningRate * grad.bz;\n\n  Wxu -= learningRate * grad.Wxu;\n  Whu -= learningRate * grad.Whu;\n  bu -= learningRate * grad.bu;\n}\n\nvoid gru_cell_old::save(std::ofstream &ofs) {\n  rnn::generic::save(ofs, Wxr);\n  rnn::generic::save(ofs, Whr);\n  rnn::generic::save(ofs, br);\n  rnn::generic::save(ofs, Wxz);\n  rnn::generic::save(ofs, Whz);\n  rnn::generic::save(ofs, bz);\n  rnn::generic::save(ofs, Wxu);\n  rnn::generic::save(ofs, Whu);\n  rnn::generic::save(ofs, bu);\n}\n\nvoid gru_cell_old::load(std::ifstream &ifs) {\n  rnn::generic::load(ifs, Wxr);\n  rnn::generic::load(ifs, Whr);\n  rnn::generic::load(ifs, br);\n  rnn::generic::load(ifs, Wxz);\n  rnn::generic::load(ifs, Whz);\n  rnn::generic::load(ifs, bz);\n  rnn::generic::load(ifs, Wxu);\n  rnn::generic::load(ifs, Whu);\n  rnn::generic::load(ifs, bu);\n}\n\nvoid gru_cell_old::State::clear() {\n  this->h = VecD();\n  this->u = VecD();\n  this->r = VecD();\n  this->z = VecD();\n  this->rh = VecD();\n  this->delh = VecD();\n  this->delx = VecD();\n}\n\ngru_cell_old::Grad::Grad(const gru_cell_old &gru) {\n  this->Wxr = MatD::Zero(gru.Wxr.rows(), gru.Wxr.cols());\n  this->Whr = MatD::Zero(gru.Whr.rows(), gru.Whr.cols());\n  this->br = VecD::Zero(gru.br.rows());\n\n  this->Wxz = MatD::Zero(gru.Wxz.rows(), gru.Wxz.cols());\n  this->Whz = MatD::Zero(gru.Whz.rows(), gru.Whz.cols());\n  this->bz = VecD::Zero(gru.bz.rows());\n\n  this->Wxu = MatD::Zero(gru.Wxu.rows(), gru.Wxu.cols());\n  this->Whu = MatD::Zero(gru.Whu.rows(), gru.Whu.cols());\n  this->bu = VecD::Zero(gru.bu.rows());\n};\n\nvoid gru_cell_old::Grad::init() {\n  this->Wxr.setZero();\n  this->Whr.setZero();\n  this->br.setZero();\n  this->Wxz.setZero();\n  this->Whz.setZero();\n  this->bz.setZero();\n  this->Wxu.setZero();\n  this->Whu.setZero();\n  this->bu.setZero();\n}\n\nreal gru_cell_old::Grad::norm() {\n  return\n      this->Wxr.squaredNorm() + this->Whr.squaredNorm() +\n          this->br.squaredNorm() +\n          this->Wxz.squaredNorm() + this->Whz.squaredNorm() +\n          this->bz.squaredNorm() +\n          this->Wxu.squaredNorm() + this->Whu.squaredNorm() +\n          this->bu.squaredNorm();\n}\n\nvoid gru_cell_old::Grad::operator+=(const gru_cell_old::Grad &grad) {\n  this->Wxr += grad.Wxr;\n  this->Whr += grad.Whr;\n  this->br += grad.br;\n  this->Wxz += grad.Wxz;\n  this->Whz += grad.Whz;\n  this->bz += grad.bz;\n  this->Wxu += grad.Wxu;\n  this->Whu += grad.Whu;\n  this->bu += grad.bu;\n}\n}", "meta": {"hexsha": "40f85191d75622056fcc36828a7e714971033e64", "size": 5440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RNN/gru_cell_old.cpp", "max_stars_repo_name": "suiyili/projects", "max_stars_repo_head_hexsha": "29b4ab0435c8994809113c444b3dea4fff60b75c", "max_stars_repo_licenses": ["MIT"], "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/gru_cell_old.cpp", "max_issues_repo_name": "suiyili/projects", "max_issues_repo_head_hexsha": "29b4ab0435c8994809113c444b3dea4fff60b75c", "max_issues_repo_licenses": ["MIT"], "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/gru_cell_old.cpp", "max_forks_repo_name": "suiyili/projects", "max_forks_repo_head_hexsha": "29b4ab0435c8994809113c444b3dea4fff60b75c", "max_forks_repo_licenses": ["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.4054054054, "max_line_length": 106, "alphanum_fraction": 0.6189338235, "num_tokens": 1842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5321834915629787}}
{"text": "#include <iostream>\n#include <cstdlib>\n#include <algorithm>\n#include <chrono>\n\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"../src/FloatMatrix.hpp\"\n#include \"../src/MatrixMultiply.hpp\"\n\nvoid initRandomMatrix(scottgs::FloatMatrix& m);\n\nint main(int argc, char * argv[])\n{\n\n\t// ---------------------------------------------\n\t// BEGIN: Timing Analysis\n\t// ---------------------------------------------\n\tstd::cout << \"Running Timing Analysis\" << std::endl\n\t\t  << \"-----------------------\" << std::endl;\n\tsrand(123456);\t// use a constant number to seed the pseudo random number generator\n\t\t\t// this way your results at least have the same input on a given system\n\n\tconst unsigned int ITR=100;\n\n\t// ---------------------------------------------\n\t// Build up a set of test matrix-pair sizes\n\t// ---------------------------------------------\n\tstd::vector<std::pair<std::pair<unsigned short,unsigned short>, std::pair<unsigned short,unsigned short> > > testList;\n\ttestList.push_back( std::make_pair(std::pair<unsigned short,unsigned short>(50,40),\n\t\t\t\t\t   std::pair<unsigned short,unsigned short>(40,60)) );\n\n\n\ttestList.push_back( std::make_pair(std::pair<unsigned short,unsigned short>(60,50),\n\t\t\t\t\t   std::pair<unsigned short,unsigned short>(50,70)) );\n\n\ttestList.push_back( std::make_pair(std::pair<unsigned short,unsigned short>(70,60),\n\t\t\t\t\t   std::pair<unsigned short,unsigned short>(60,80)) );\n\n\ttestList.push_back( std::make_pair(std::pair<unsigned short,unsigned short>(80,70),\n\t\t\t\t\t   std::pair<unsigned short,unsigned short>(70,90)) );\n\n// Change this to 1 to enable larger matrices\n#if 0\n\ttestList.push_back( std::make_pair(std::pair<unsigned short,unsigned short>(90,80),\n\t\t\t\t\t   std::pair<unsigned short,unsigned short>(80,100)) );\n\n\ttestList.push_back( std::make_pair(std::pair<unsigned short,unsigned short>(100,90),\n\t\t\t\t\t   std::pair<unsigned short,unsigned short>(90,110)) );\n\n\ttestList.push_back( std::make_pair(std::pair<unsigned short,unsigned short>(200,90),\n\t\t\t\t\t   std::pair<unsigned short,unsigned short>(90,220)) );\n\n\ttestList.push_back( std::make_pair(std::pair<unsigned short,unsigned short>(200,180),\n\t\t\t\t\t   std::pair<unsigned short,unsigned short>(180,220)) );\n\n\ttestList.push_back( std::make_pair(std::pair<unsigned short,unsigned short>(400,360),\n\t\t\t\t\t   std::pair<unsigned short,unsigned short>(360,240)) );\n\n#endif\n\t// ***********************************\n\t// Test functor : Your implementation\n\t// ***********************************\n\n\tscottgs::MatrixMultiply mm;\n\n\tfor (std::vector<std::pair<std::pair<unsigned short,unsigned short>, std::pair<unsigned short,unsigned short> > >::const_iterator t=testList.begin();\n\t\tt!=testList.end();++t)\n\t{\n\t\t// Get matrix size pairs from iterator\n\t\t// instantiate matrices, then randomize\n\t\tstd::pair<unsigned short,unsigned short> lp = t->first;\n\t\tstd::pair<unsigned short,unsigned short> rp = t->second;\n\t\tscottgs::FloatMatrix l(lp.first,lp.second);\n\t\tscottgs::FloatMatrix r(rp.first,rp.second);\n\t\tinitRandomMatrix(l);\n\t\tinitRandomMatrix(r);\n\n\t\t// Run Timing Experiment\n                std::chrono::high_resolution_clock c;\n                std::chrono::high_resolution_clock::time_point start = c.now();\n\t\tfor (unsigned int i = 0; i < ITR; ++i)\n\t\t{\n\t\t\t// This is an assignemnt of a call to a object functor;\n\t\t\tscottgs::FloatMatrix p = mm(l,r);\n\t\t}\n                std::chrono::high_resolution_clock::time_point stop = c.now();\n\t\tdouble avgMs = (double) std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count() / (1000000 * ITR);\n\n\t\t// Compute Ops and Elements\n\t\t// Log timing statistics\n\t\tconst unsigned long opsMaybe = l.size1() * r.size2() * l.size2() + l.size1() + r.size2();\n\t\tconst unsigned long elements = l.size1() * r.size2();\n\t\tstd::cout << \"------------------------------------------------------------------\" << std::endl\n\t\t\t  << ITR << \" iterations of matrix multiplication (functor) ran using (\"\n\t\t\t  << l.size1() <<\",\"<< l.size2() <<\")*(\"\n\t\t\t  << r.size1() <<\",\"<< r.size2() <<\") = (\"\n\t\t\t  << l.size1() <<\",\"<< r.size2() <<\")\" << std::endl\n\t\t\t  << \"      :Method:Average Time (s):approximate ops:computed elements\" << std::endl\n\t\t\t  << \"Data  Point:f:\" << avgMs << \":\" << opsMaybe<< \":\" << elements << std::endl;\n\t}\n\n\n#if 1\n\t// ***********************************\n\t// Test built-in Boost prod()\n\t// ***********************************\n\n\tfor (std::vector<std::pair<std::pair<unsigned short,unsigned short>, std::pair<unsigned short,unsigned short> > >::const_iterator t=testList.begin();\n\t\tt!=testList.end();++t)\n\t{\n\t\t// Get matrix size pairs from iterator\n\t\t// instantiate matrices, then randomize\n\t\tstd::pair<unsigned short,unsigned short> lp = t->first;\n\t\tstd::pair<unsigned short,unsigned short> rp = t->second;\n\t\tscottgs::FloatMatrix l(lp.first,lp.second);\n\t\tscottgs::FloatMatrix r(rp.first,rp.second);\n\t\tinitRandomMatrix(l);\n\t\tinitRandomMatrix(r);\n\n\t\t// Run Timing Experiment\n                std::chrono::high_resolution_clock c;\n                std::chrono::high_resolution_clock::time_point start = c.now();\n                for (unsigned int i = 0; i < ITR; ++i)\n\t\t{\n\t\t\tscottgs::FloatMatrix p = mm.multiply(l,r);\n\t\t}\n                std::chrono::high_resolution_clock::time_point stop = c.now();\n\t\tdouble avgMs = (double) std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count() / (1000000 * ITR);\n\n\t\t// Compute Ops and Elements\n\t\t// Log timing statistics\n\t\tconst unsigned long opsMaybe = l.size1() * r.size2() * l.size2() + l.size1() + r.size2();\n\t\tconst unsigned long elements = l.size1() * r.size2();\n\t\tstd::cout << \"------------------------------------------------------------------\" << std::endl\n\t\t\t  << ITR << \" iterations of matrix multiplication boost (method) ran using (\"\n\t\t\t  << l.size1() <<\",\"<< l.size2() <<\")*(\"\n\t\t\t  << r.size1() <<\",\"<< r.size2() <<\") = (\"\n\t\t\t  << l.size1() <<\",\"<< r.size2() <<\")\" << std::endl\n\t\t\t  << \"      :Method:Average Time (s):approximate ops:computed elements\" << std::endl\n\t\t\t  << \"Data Point:m1:\" << avgMs << \":\" << opsMaybe<< \":\" << elements << std::endl;\n\n\t}\n#endif\n\n\n\n\tstd::cout << \"Timing Analysis Completed\" << std::endl\n\t\t  << \"=========================\" << std::endl;\n\t// ---------------------------------------------\n\t// END: Timing Analysis\n\t// ---------------------------------------------\n}\n\nvoid initRandomMatrix(scottgs::FloatMatrix& m)\n{\n\t// Initialize each element.\n\t// See discussion board for better way,\n\t// this was originally posted to be a\n\t// simple example of per-element access into the matric\n\tfor (unsigned i = 0; i < m.size1(); ++ i)\n\t        for (unsigned j = 0; j < m.size2(); ++ j)\n\t\t            m (i, j) = (static_cast<float>(rand()) / RAND_MAX) * 100.0;\n}\n\n", "meta": {"hexsha": "43b95999e3adf96da1532697f017b40ee534f1db", "size": 6661, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Matrix-Multiplication-Speedup/analyze/hw1_analyze.cpp", "max_stars_repo_name": "samkreter/High-Performance-Computing", "max_stars_repo_head_hexsha": "cb8c944fa0ed39aaea41ee4ecb202dd2c18a52a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Matrix-Multiplication-Speedup/analyze/hw1_analyze.cpp", "max_issues_repo_name": "samkreter/High-Performance-Computing", "max_issues_repo_head_hexsha": "cb8c944fa0ed39aaea41ee4ecb202dd2c18a52a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Matrix-Multiplication-Speedup/analyze/hw1_analyze.cpp", "max_forks_repo_name": "samkreter/High-Performance-Computing", "max_forks_repo_head_hexsha": "cb8c944fa0ed39aaea41ee4ecb202dd2c18a52a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1265060241, "max_line_length": 150, "alphanum_fraction": 0.5856478006, "num_tokens": 1660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7341195210831258, "lm_q1q2_score": 0.5321414199943237}}
{"text": "//---------------------------------------------------------------------------//\r\n// Copyright (c) 2016 Jakub Szuppe <j.szuppe@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 TestMergeSortOnGPU\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <iostream>\r\n\r\n#include <boost/compute/system.hpp>\r\n#include <boost/compute/algorithm/is_sorted.hpp>\r\n#include <boost/compute/algorithm/detail/merge_sort_on_gpu.hpp>\r\n#include <boost/compute/container/vector.hpp>\r\n\r\n#include \"quirks.hpp\"\r\n#include \"check_macros.hpp\"\r\n#include \"context_setup.hpp\"\r\n\r\nnamespace bc = boost::compute;\r\n\r\nBOOST_AUTO_TEST_CASE(sort_small_vector_char)\r\n{\r\n    if(is_apple_cpu_device(device)) {\r\n        std::cerr\r\n            << \"skipping all merge_sort_on_gpu tests due to Apple platform\"\r\n            << \" behavior when local memory is used on a CPU device\"\r\n            << std::endl;\r\n        return;\r\n    }\r\n\r\n    using boost::compute::char_;\r\n    ::boost::compute::greater<char_> greater;\r\n    ::boost::compute::less<char_> less;\r\n\r\n    char_ data[] = { 'c', 'a', '0', '7', 'B', 'F', '\\0', '$' };\r\n    boost::compute::vector<char_> vector(data, data + 8, queue);\r\n    BOOST_CHECK_EQUAL(vector.size(), size_t(8));\r\n    BOOST_CHECK(boost::compute::is_sorted(vector.begin(), vector.end(), queue) == false);\r\n\r\n    // <\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), less, queue\r\n    );\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), less, queue)\r\n    );\r\n    CHECK_RANGE_EQUAL(char_, 8, vector, ('\\0', '$', '0', '7', 'B', 'F', 'a', 'c'));\r\n\r\n    // >\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), greater, queue\r\n    );\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), greater, queue)\r\n    );\r\n    CHECK_RANGE_EQUAL(char_, 8, vector, ('c', 'a', 'F', 'B', '7', '0', '$', '\\0'));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(sort_mid_vector_int)\r\n{\r\n    if(is_apple_cpu_device(device)) {\r\n        return;\r\n    }\r\n\r\n    using boost::compute::int_;\r\n    ::boost::compute::greater<int_> greater;\r\n    ::boost::compute::less<int_> less;\r\n\r\n    const int_ size = 748;\r\n    std::vector<int_> data(size);\r\n    for(int_ i = 0; i < size; i++){\r\n        data[i] = i%2 ? i : -i;\r\n    }\r\n\r\n    boost::compute::vector<int_> vector(data.begin(), data.end(), queue);\r\n    BOOST_CHECK_EQUAL(vector.size(), size);\r\n    BOOST_CHECK(!boost::compute::is_sorted(vector.begin(), vector.end(), queue));\r\n\r\n    // <\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), less, queue\r\n    );\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), less, queue)\r\n    );\r\n\r\n    // >\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), greater, queue\r\n    );\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), greater, queue)\r\n    );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(sort_mid_vector_ulong)\r\n{\r\n    if(is_apple_cpu_device(device)) {\r\n        return;\r\n    }\r\n\r\n    using boost::compute::ulong_;\r\n    ::boost::compute::greater<ulong_> greater;\r\n    ::boost::compute::less<ulong_> less;\r\n\r\n    const ulong_ size = 260;\r\n    std::vector<ulong_> data(size);\r\n    for(ulong_ i = 0; i < size; i++){\r\n        data[i] = i%2 ? i : i * i;\r\n    }\r\n\r\n    boost::compute::vector<ulong_> vector(data.begin(), data.end(), queue);\r\n    BOOST_CHECK_EQUAL(vector.size(), size);\r\n    BOOST_CHECK(!boost::compute::is_sorted(vector.begin(), vector.end(), queue));\r\n\r\n    // <\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), less, queue\r\n    );\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), less, queue)\r\n    );\r\n\r\n    // >\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), greater, queue\r\n    );\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), greater, queue)\r\n    );\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(sort_mid_vector_float)\r\n{\r\n    if(is_apple_cpu_device(device)) {\r\n        return;\r\n    }\r\n\r\n    using boost::compute::float_;\r\n    ::boost::compute::greater<float_> greater;\r\n    ::boost::compute::less<float_> less;\r\n\r\n    const int size = 513;\r\n    std::vector<float_> data(size);\r\n    for(int i = 0; i < size; i++){\r\n        data[i] = float_(i%2 ? i : -i);\r\n    }\r\n\r\n    boost::compute::vector<float_> vector(data.begin(), data.end(), queue);\r\n    BOOST_CHECK_EQUAL(vector.size(), size);\r\n    BOOST_CHECK(!boost::compute::is_sorted(vector.begin(), vector.end(), queue));\r\n\r\n    // <\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), less, queue\r\n    );\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), less, queue)\r\n    );\r\n\r\n    // >\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), greater, queue\r\n    );\r\n    queue.finish();\r\n\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), greater, queue)\r\n    );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(sort_mid_vector_double)\r\n{\r\n    if(is_apple_cpu_device(device)) {\r\n        return;\r\n    }\r\n\r\n    if(!device.supports_extension(\"cl_khr_fp64\")){\r\n        std::cout << \"skipping test: device does not support double\" << std::endl;\r\n        return;\r\n    }\r\n\r\n    using boost::compute::double_;\r\n    ::boost::compute::greater<double_> greater;\r\n    ::boost::compute::less<double_> less;\r\n\r\n    const int size = 1023;\r\n    std::vector<double_> data(size);\r\n    for(int i = 0; i < size; i++){\r\n        data[i] = double_(i%2 ? i : -i);\r\n    }\r\n\r\n    boost::compute::vector<double_> vector(data.begin(), data.end(), queue);\r\n    BOOST_CHECK_EQUAL(vector.size(), size);\r\n    BOOST_CHECK(!boost::compute::is_sorted(vector.begin(), vector.end(), queue));\r\n\r\n    // <\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), less, queue\r\n    );\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), less, queue)\r\n    );\r\n\r\n    // >\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), greater, queue\r\n    );\r\n    queue.finish();\r\n\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), greater, queue)\r\n    );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(sort_mid_vector_int_custom_comparison_func)\r\n{\r\n    if(is_apple_cpu_device(device)) {\r\n        return;\r\n    }\r\n\r\n    using boost::compute::int_;\r\n    ::boost::compute::greater<int_> greater;\r\n    ::boost::compute::less<int_> less;\r\n\r\n    const int_ size = 1024;\r\n    std::vector<int_> data(size);\r\n    for(int_ i = 0; i < size; i++){\r\n        data[i] = i%2 ? size - i : i - size;\r\n    }\r\n\r\n    BOOST_COMPUTE_FUNCTION(bool, abs_sort, (int_ a, int_ b),\r\n    {\r\n        return abs(a) < abs(b);\r\n    });\r\n\r\n    boost::compute::vector<int_> vector(data.begin(), data.end(), queue);\r\n    BOOST_CHECK_EQUAL(vector.size(), size);\r\n    BOOST_CHECK(\r\n        !boost::compute::is_sorted(vector.begin(), vector.end(), abs_sort, queue)\r\n    );\r\n\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), abs_sort, queue\r\n    );\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), abs_sort, queue)\r\n    );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(sort_mid_vector_int2)\r\n{\r\n    if(is_apple_cpu_device(device)) {\r\n        return;\r\n    }\r\n\r\n    using boost::compute::int2_;\r\n    using boost::compute::int_;\r\n    ::boost::compute::greater<int2_> greater;\r\n    ::boost::compute::less<int2_> less;\r\n\r\n    const int_ size = 1024;\r\n    std::vector<int2_> data(size);\r\n    for(int_ i = 0; i < size; i++){\r\n        data[i] = i%2 ? int2_(i, i) : int2_(i - size, i - size);\r\n    }\r\n\r\n    BOOST_COMPUTE_FUNCTION(bool, abs_sort, (int2_ a, int2_ b),\r\n    {\r\n        return abs(a.x + a.y) < abs(b.x + b.y);\r\n    });\r\n\r\n    boost::compute::vector<int2_> vector(data.begin(), data.end(), queue);\r\n    BOOST_CHECK_EQUAL(vector.size(), size);\r\n    BOOST_CHECK(\r\n        !boost::compute::is_sorted(vector.begin(), vector.end(), abs_sort, queue)\r\n    );\r\n\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), abs_sort, queue\r\n    );\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), abs_sort, queue)\r\n    );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(sort_mid_vector_long8)\r\n{\r\n    if(is_apple_cpu_device(device)) {\r\n        return;\r\n    }\r\n\r\n    using boost::compute::long8_;\r\n    using boost::compute::long_;\r\n    ::boost::compute::greater<long8_> greater;\r\n    ::boost::compute::less<long8_> less;\r\n\r\n    const long_ size = 256;\r\n    std::vector<long8_> data(size);\r\n    for(long_ i = 0; i < size; i++){\r\n        data[i] = i%2 ? long8_(i) : long8_(i * i);\r\n    }\r\n\r\n    BOOST_COMPUTE_FUNCTION(bool, comp, (long8_ a, long8_ b),\r\n    {\r\n        return a.s0 < b.s3;\r\n    });\r\n\r\n    boost::compute::vector<long8_> vector(data.begin(), data.end(), queue);\r\n    BOOST_CHECK_EQUAL(vector.size(), size);\r\n    BOOST_CHECK(\r\n        !boost::compute::is_sorted(vector.begin(), vector.end(), comp, queue)\r\n    );\r\n\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), comp, queue\r\n    );\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), comp, queue)\r\n    );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(stable_sort_vector_int2)\r\n{\r\n    if(is_apple_cpu_device(device)) {\r\n        return;\r\n    }\r\n\r\n    using boost::compute::int2_;\r\n\r\n    int2_ data[] = {\r\n        int2_(8, 3), int2_(5, 1),\r\n        int2_(2, 1), int2_(6, 1),\r\n        int2_(8, 1), int2_(7, 1),\r\n        int2_(4, 1), int2_(8, 2)\r\n    };\r\n\r\n    BOOST_COMPUTE_FUNCTION(bool, comp, (int2_ a, int2_ b),\r\n    {\r\n        return a.x < b.x;\r\n    });\r\n\r\n    boost::compute::vector<int2_> vector(data, data + 8, queue);\r\n    BOOST_CHECK_EQUAL(vector.size(), 8);\r\n    BOOST_CHECK(\r\n        !boost::compute::is_sorted(vector.begin(), vector.end(), comp, queue)\r\n    );\r\n\r\n    //\r\n    boost::compute::detail::merge_sort_on_gpu(\r\n        vector.begin(), vector.end(), comp, true /*stable*/, queue\r\n    );\r\n    BOOST_CHECK(\r\n        boost::compute::is_sorted(vector.begin(), vector.end(), comp, queue)\r\n    );\r\n    CHECK_RANGE_EQUAL(\r\n        int2_, 8, vector,\r\n        (\r\n            int2_(2, 1), int2_(4, 1),\r\n            int2_(5, 1), int2_(6, 1),\r\n            int2_(7, 1), int2_(8, 3),\r\n            int2_(8, 1), int2_(8, 2)\r\n        )\r\n    );\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "80baccb09c1f310743e2b3a239e48b1e07bdabf9", "size": 10769, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_merge_sort_gpu.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_merge_sort_gpu.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_merge_sort_gpu.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": 28.7173333333, "max_line_length": 90, "alphanum_fraction": 0.5758194818, "num_tokens": 2715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.532141415777712}}
{"text": "/**\n * @file transpsemilagr_main.cc\n * @brief NPDE homework TranspSemiLagr Main file\n * @author Philippe Peter\n * @date November 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/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <filesystem>\n#include <memory>\n\n#include \"transpsemilagr.h\"\n\nint main() {\n  // The equation is solved on the test mesh circle.msh\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/circle.msh\");\n  auto mesh_p = reader.mesh();\n\n  // construct linear finite element space\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  // initial conditions:\n  // const auto u0 = [](const Eigen::Vector2d& x){ return 1-(x(0)* x(0) +\n  // x(1)*x(1));};\n  const auto u0 = [](const Eigen::Vector2d& x) {\n    if (x(1) * x(1) + x(0) * x(0) > 0.99) {\n      return 0.0;\n    } else {\n      return -x(1) - x(0);\n    }\n  };\n\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u0));\n\n  // compute the solutions after 1st timestep\n  Eigen::VectorXd sol_rot_1 =\n      TranspSemiLagr::solverot(fe_space, u0_vector, 1, 0.1);\n  lf::fe::MeshFunctionFE mf_sol_rot_1(fe_space, sol_rot_1);\n  Eigen::VectorXd sol_trp_1 =\n      TranspSemiLagr::solvetrp(fe_space, u0_vector, 1, 0.1);\n  lf::fe::MeshFunctionFE mf_sol_trp_1(fe_space, sol_trp_1);\n\n  // compute solutions at final time\n  Eigen::VectorXd sol_rot_10 =\n      TranspSemiLagr::solverot(fe_space, u0_vector, 10, 1.0);\n  lf::fe::MeshFunctionFE mf_sol_rot_10(fe_space, sol_rot_10);\n  Eigen::VectorXd sol_trp_10 =\n      TranspSemiLagr::solvetrp(fe_space, u0_vector, 10, 1.0);\n  lf::fe::MeshFunctionFE mf_sol_trp_10(fe_space, sol_trp_10);\n\n  // OUTPUT RESULTS\n  // construct writers\n  lf::io::VtkWriter vtk_writer_rot_1(mesh_p, CURRENT_BINARY_DIR \"rot_1.vtk\");\n  lf::io::VtkWriter vtk_writer_rot_10(mesh_p, CURRENT_BINARY_DIR \"rot_10.vtk\");\n  lf::io::VtkWriter vtk_writer_trp_1(mesh_p, CURRENT_BINARY_DIR \"trp_1.vtk\");\n  lf::io::VtkWriter vtk_writer_trp_10(mesh_p, CURRENT_BINARY_DIR \"trp_10.vtk\");\n\n  // output data\n  vtk_writer_rot_1.WritePointData(\"rot_1\", mf_sol_rot_1);\n  vtk_writer_rot_10.WritePointData(\"rot_10\", mf_sol_rot_10);\n  vtk_writer_trp_1.WritePointData(\"trp_1\", mf_sol_trp_1);\n  vtk_writer_trp_10.WritePointData(\"trp_10\", mf_sol_trp_10);\n\n  return 0;\n}\n", "meta": {"hexsha": "26dcbe86090eecf9959f48ef3ae083969b4fb16b", "size": 2567, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/TranspSemiLagr/templates/transpsemilagr_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/TranspSemiLagr/templates/transpsemilagr_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/TranspSemiLagr/templates/transpsemilagr_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": 33.7763157895, "max_line_length": 79, "alphanum_fraction": 0.7004285158, "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5321414070511198}}
{"text": "// Copyright (c) Dietmar Wolz.\n//\n// This source code is licensed under the MIT license found in the\n// LICENSE file in the root directory.\n\n// Eigen based implementation of dual annealing \n// derived from https://github.com/scipy/scipy/blob/master/scipy/optimize/_dual_annealing.py\n// Implementation only differs regarding boundary handling - this implementattion \n// uses boundary-normalized X values. Local search is fixed to LBFGS-B, see\n// https://github.com/yixuan/LBFGSpp/tree/master/include \n// requires https://github.com/imneme/pcg-cpp\n\n#include <Eigen/Core>\n#include <iostream>\n#include <float.h>\n#include <math.h>\n#include <ctime>\n#include <random>\n#include \"pcg_random.hpp\"\n#include <LBFGSB.h>\n\nusing namespace LBFGSpp;\nusing namespace std;\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1> vec;\ntypedef Eigen::Matrix<int, Eigen::Dynamic, 1> ivec;\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat;\n\nnamespace dual_annealing {\n\ntypedef double (*callback_type)(int, const double*);\n\n// wrapper around the fitness function, scales according to boundaries\n\nclass Fitness;\n\nstatic uniform_real_distribution<> distr_01 = std::uniform_real_distribution<>(\n        0, 1);\nstatic normal_distribution<> gauss_01 = std::normal_distribution<>(0, 1);\n\nstatic vec zeros(int n) {\n    return Eigen::MatrixXd::Zero(n, 1);\n}\n\nstatic Eigen::MatrixXd normalVec(int dim, pcg64 &rs) {\n    return Eigen::MatrixXd::NullaryExpr(dim, 1, [&]() {\n        return gauss_01(rs);\n    });\n}\n\nstatic Eigen::MatrixXd uniformVec(int dim, pcg64 &rs) {\n    return Eigen::MatrixXd::NullaryExpr(dim, 1, [&]() {\n        return distr_01(rs);\n    });\n}\n\nstatic vec emptyVec = { };\n\nstatic vec logv(vec v) {\n    return v.unaryExpr([](double x) {\n        return log(x);\n    });\n}\n\nstatic vec expv(vec v) {\n    return v.unaryExpr([](double x) {\n        return exp(x);\n    });\n}\n\ndouble minLBFGS(Fitness *fitfun, vec &X0_, int maxIterations);\n\nclass Fitness {\n\npublic:\n\n    vec lower;\n    vec upper;\n\n    Fitness(callback_type pfunc, vec *lower_limit, vec *upper_limit,\n            long maxEvals_) {\n        func = pfunc;\n        lower = *lower_limit;\n        upper = *upper_limit;\n        if (lower.size() > 0) // bounds defined\n            scale = (upper - lower);\n        maxEvals = maxEvals_;\n    }\n\n    vec getClosestFeasible(const vec &X) const {\n        if (lower.size() > 0) {\n            return X.cwiseMin(1.0).cwiseMax(-1.0);\n        }\n        return X;\n    }\n\n    double eval(const vec &X) {\n        int n = X.size();\n        double res = func(n, X.data());\n        evaluationCounter++;\n        return res;\n    }\n\n    double value(const vec &X) {\n        double res = DBL_MAX;\n        if (lower.size() > 0)\n            res = eval(decode(getClosestFeasible(X)));\n        else\n            res = eval(X);\n        if (res < bestY) {\n            bestY = res;\n            bestX = vec(X);\n        }\n        return res;\n    }\n\n    const double LS_MAXITER_RATIO = 6;\n    const double LS_MAXITER_MIN = 100;\n    const double LS_MAXITER_MAX = 1000;\n\n    double local_search(const vec &x0, double currval, vec &res) {\n        vec init = getClosestFeasible(x0);\n        bestY = DBL_MAX;\n        int maxIter = LS_MAXITER_RATIO * x0.size();\n        if (maxIter > LS_MAXITER_MAX)\n            maxIter = LS_MAXITER_MAX;\n        if (maxIter < LS_MAXITER_MIN)\n            maxIter = LS_MAXITER_MIN;\n        minLBFGS(this, init, maxIter);\n        if (bestY < DBL_MAX) {\n            for (int i = 0; i < res.size(); i++)\n                res[i] = bestX(i);\n        }\n        return bestY;\n    }\n\n    vec encode(const vec &X) const {\n        if (lower.size() > 0)\n            return (X - lower).array() / scale.array();\n        else\n            return X;\n    }\n\n    vec decode(const vec &X) const {\n        if (lower.size() > 0)\n            return X.cwiseProduct(scale) + lower;\n        else\n            return X;\n    }\n\n    int getEvaluations() {\n        return evaluationCounter;\n    }\n\n    bool maxEvalReached() {\n        return evaluationCounter >= maxEvals;\n    }\n\nprivate:\n    callback_type func;\n    long evaluationCounter = 0;\n    long maxEvals;\n    vec scale;\n    double bestY = DBL_MAX;\n    vec bestX;\n};\n\nclass LBFGSFunc {\nprivate:\n    Fitness *func;\n    int dim;\n\npublic:\n\n    LBFGSFunc(Fitness *Fitness_, int dim_) {\n        func = Fitness_;\n        dim = dim_;\n    }\n\n    double operator()(const vec &x, vec &grad) {\n        if (!x.allFinite())\n            return DBL_MAX;\n        double eps = 1E-6;\n        vec arg = vec(dim);\n        for (int i = 0; i < dim; i++)\n            arg[i] = x(i);\n        for (int i = 0; i < dim; i++) {\n            vec x1 = vec(arg);\n            vec x2 = vec(arg);\n            double e1 = eps;\n            double e2 = eps;\n            x1[i] += eps;\n            if (x1[i] > 1) {\n                x1[i] = 1;\n                e1 = 1 - arg[i];\n            }\n            x2[i] -= eps;\n            if (x2[i] < 0) {\n                x2[i] = 0;\n                e2 = arg[i];\n            }\n            double f1 = func->value(x1);\n            double f2 = func->value(x2);\n            grad[i] = (f1 - f2) / (e1 + e2);\n        }\n        double f = func->value(arg);\n        return f;\n    }\n};\n\ndouble minLBFGS(Fitness *fitfun, vec &X0, int maxIterations) {\n    int dim = X0.size();\n    LBFGSFunc fun = LBFGSFunc(fitfun, dim);\n\n    LBFGSBParam<double> param;\n    param.max_iterations = maxIterations;\n    LBFGSBSolver<double> solver(param);\n    vec lb = vec::Constant(dim, 0.0);\n    vec ub = vec::Constant(dim, 1.0);\n    // Initial values\n    vec x = vec::Constant(dim, 0);\n    for (int i = 0; i < dim; i++)\n        x[i] = X0[i];\n    double fx;\n    int niter;\n    try {\n        niter = solver.minimize(fun, x, fx, lb, ub);\n    } catch (std::exception &e) {\n        //cout << e.what() << endl;\n        return DBL_MAX;\n    }\n    return fx;\n}\n\nclass VisitingDistribution {\n\n    //Class used to generate new coordinates based on the distorted\n    //Cauchy-Lorentz distribution. Depending on the steps within the Markov\n    //chain, the class implements the strategy for generating new location\n    //changes.\n\npublic:\n\n    VisitingDistribution(int dim, double visiting_param_, pcg64 *rs_) {\n        _visiting_param = visiting_param_;\n        rs = rs_;\n\n        // these are invariant numbers unless visiting_param changes\n        double factor2 = exp(\n                (4.0 - _visiting_param) * log(_visiting_param - 1.0));\n        double factor3 = exp(\n                (2.0 - _visiting_param) * log(2.0) / (_visiting_param - 1.0));\n        _factor4_p = sqrt(M_PI) * factor2 / (factor3 * (3.0 - _visiting_param));\n\n        double factor5 = 1.0 / (_visiting_param - 1.0) - 0.5;\n        double d1 = 2.0 - factor5;\n        _factor6 = M_PI * (1.0 - factor5) / sin(M_PI * (1.0 - factor5))\n                / exp(lgamma(d1));\n    }\n\n    vec visiting(const vec &x, int step, double temperature) {\n        //Based on the step in the strategy chain, new coordinated are\n        //generated by changing all components is the same time or only\n        //one of them, the new values are computed with visit_fn method\n\n        int dim = x.size();\n        if (step < dim) {\n            // Changing all coordinates with a new visiting value\n            double upper_sample = distr_01(*rs);\n            double lower_sample = distr_01(*rs);\n            vec visits = visit_fn(temperature, dim);\n            for (int i = 0; i < dim; i++) {\n                if (visits[i] > TAIL_LIMIT)\n                    visits[i] = TAIL_LIMIT * upper_sample;\n                else if (visits[i] < -TAIL_LIMIT)\n                    visits[i] = -TAIL_LIMIT * lower_sample;\n            }\n            vec x_visit = visits + x;\n            vec a = x_visit;\n            vec b = vec(dim);\n            for (int i = 0; i < dim; i++) {\n                b[i] = fmod(a[i], 1) + 1;\n                x_visit[i] = fmod(b[i], 1);\n                if (abs(x_visit[i]) < MIN_VISIT_BOUND)\n                    x_visit[i] += 1.e-10;\n            }\n            //cerr << step << \" \" << temperature <<  endl;// << x_visit << endl;\n            return x_visit;\n        } else {\n            // Changing only one coordinate at a time based on strategy\n            // chain step\n            vec x_visit = vec(x);\n            double visit = visit_fn(temperature, 1)[0];\n            if (visit > TAIL_LIMIT)\n                visit = TAIL_LIMIT * distr_01(*rs);\n            else if (visit < -TAIL_LIMIT)\n                visit = -TAIL_LIMIT * distr_01(*rs);\n            int index = step - dim;\n            x_visit[index] = visit + x[index];\n            double a = x_visit[index];\n            double b = fmod(a, 1) + 1;\n            x_visit[index] = fmod(b, 1);\n            if (abs(x_visit[index]) < MIN_VISIT_BOUND)\n                x_visit[index] += MIN_VISIT_BOUND;\n            //cerr << step << \" \" << temperature <<  endl;// << x_visit << endl;\n            return x_visit;\n        }\n    }\n\n    vec visit_fn(double temperature, int dim) {\n\n        //Formula Visita from p. 405 of reference [2]\n        vec x = normalVec(dim, *rs);\n        vec y = normalVec(dim, *rs);\n        ;\n\n        double factor1 = exp(log(temperature) / (_visiting_param - 1.0));\n        double factor4 = _factor4_p * factor1;\n\n        // sigmax\n        x = x\n                * exp(\n                        -(_visiting_param - 1.0) * log(_factor6 / factor4)\n                                / (3.0 - _visiting_param));\n\n        vec den = expv(\n                logv(y.cwiseAbs() * (_visiting_param - 1.0))\n                        / (3.0 - _visiting_param));\n        return x.cwiseQuotient(den);\n    }\n\nprivate:\n\n    pcg64 *rs;\n    double _visiting_param;\n    double _factor4_p;\n    double _factor6;\n\n    const double TAIL_LIMIT = 1.e8;\n    const double MIN_VISIT_BOUND = 1.e-10;\n};\n\nclass nanexception: public exception {\n    virtual const char* what() const throw () {\n        return \"Objective function is returning nan\";\n    }\n} naneexc;\n\nconst double BIG_VALUE = 1e16;\n\nclass EnergyState {\n\n    //Class used to record the energy state-> At any time, it knows what is the\n    //currently used coordinates and the most recent best location\npublic:\n\n    double ebest;\n    vec xbest;\n    double current_energy;\n    vec current_location;\n\n    EnergyState(int dim_) {\n        dim = dim_;\n        ebest = DBL_MAX;\n        xbest = { };\n        current_energy = DBL_MAX;\n        current_location = { };\n    }\n\n    void reset(Fitness *owf, pcg64 *rs, const vec &x0) {\n        if (x0.size() == 0)\n            current_location = normalVec(dim, *rs);\n        else\n            current_location = vec(x0);\n        bool init_error = true;\n        int reinit_counter = 0;\n        while (init_error) {\n            current_energy = owf->value(current_location);\n            if (current_energy >= BIG_VALUE || isnan(current_energy)) {\n                if (reinit_counter >= MAX_REINIT_COUNT) {\n                    init_error = false;\n                    throw naneexc;\n                }\n                current_location = uniformVec(dim, *rs);\n                reinit_counter++;\n            } else\n                init_error = false;\n            // If first time reset, initialize ebest and xbest\n            if (ebest == DBL_MAX && xbest.size() == 0) {\n                ebest = current_energy;\n                xbest = vec(current_location);\n            }\n            // Otherwise, keep them in case of reannealing reset\n        }\n    }\n\n    void update_best(double e, const vec &x) {\n        ebest = e;\n        xbest = vec(x);\n    }\n\n    void update_current(double e, const vec &x) {\n        current_energy = e;\n        current_location = vec(x);\n    }\n\nprivate:\n    // Maximimum number of trials for generating a valid starting point\n    int MAX_REINIT_COUNT = 1000;\n    int dim;\n};\n\nclass StrategyChain {\n    // Class used for the Markov chain and related strategy for local search\n    // decision\npublic:\n\n    StrategyChain(double acceptance_param_, VisitingDistribution *vd_,\n            Fitness *ofw_, pcg64 *rs_, EnergyState *state_) {\n        // Global optimizer state\n        state = state_;\n        // Local markov chain minimum energy and location\n        emin = state->current_energy;\n        xmin = vec(state->current_location);\n        // Acceptance parameter\n        acceptance_param = acceptance_param_;\n        // Visiting distribution instance\n        vd = vd_;\n        // Wrapper to objective function and related local minimizer\n        ofw = ofw_;\n        not_improved_idx = 0;\n        not_improved_max_idx = 1000;\n        rs = rs_;\n        temperature_step = 0;\n        K = 100 * (state->current_location).size();\n    }\n\n    void accept_reject(int j, double e, const vec &x_visit) {\n        double r = distr_01(*rs);\n        double pqv_temp = (acceptance_param - 1.0) * (e - state->current_energy)\n                / (temperature_step + 1.);\n        double pqv = 0;\n        if (pqv_temp < 0.)\n            pqv = 0.;\n        else\n            pqv = exp(log(pqv_temp) / (1. - acceptance_param));\n        if (r <= pqv) {\n            // We accept the new location and update state\n            state->update_current(e, x_visit);\n            xmin = vec(state->current_location);\n        }\n        // No improvement since long time\n        if (not_improved_idx >= not_improved_max_idx) {\n            if (j == 0 || state->current_energy < emin) {\n                emin = state->current_energy;\n                xmin = vec(state->current_location);\n            }\n        }\n    }\n\n    void run(int step, double temperature) {\n        temperature_step = temperature / (double) (step + 1);\n        not_improved_idx += 1;\n        for (unsigned int j = 0; j < (state->current_location).size() * 2;\n                j++) {\n            if (j == 0)\n                state_improved = false;\n            if (step == 0 && j == 0)\n                state_improved = true;\n            vec x_visit = vd->visiting(state->current_location, j, temperature);\n            // Calling the objective function\n            double e = ofw->value(x_visit);\n            if (e < state->current_energy) {\n                // We have got a better energy value\n                state->update_current(e, x_visit);\n                if (e < state->ebest) {\n                    state->update_best(e, x_visit);\n                    state_improved = true;\n                    not_improved_idx = 0;\n                }\n            } else {\n                // We have not improved but do we accept the new location?\n                accept_reject(j, e, x_visit);\n            }\n            if (ofw->maxEvalReached())\n                return;\n        }\t// End of StrategyChain loop\n    }\n\n    void local_search() {\n        // Decision making for performing a local search\n        // based on Markov chain results\n        // If energy has been improved or no improvement since too long,\n        // performing a local search with the best Markov chain location\n        int dim = state->xbest.size();\n        if (state_improved) {\n            // Global energy has improved, let's see if LS improved further\n            vec x = vec(dim);\n            double e = ofw->local_search(state->xbest, state->ebest, x);\n            if (e < state->ebest) {\n                not_improved_idx = 0;\n                state->update_best(e, x);\n                state->update_current(e, x);\n                if (ofw->maxEvalReached())\n                    return;\n            }\n        }\n        // Check probability of a need to perform a LS even if no improvment\n        bool do_ls = false;\n        if (K < 90 * state->current_location.size()) {\n            double pls = exp(\n                    K * (state->ebest - state->current_energy)\n                            / temperature_step);\n            if (pls >= distr_01(*rs))\n                do_ls = true;\n        }\n        // Global energy not improved, let's see what LS gives\n        // on the best strategy chain location\n        if (not_improved_idx >= not_improved_max_idx)\n            do_ls = true;\n        if (do_ls) {\n            vec x = vec(dim);\n            double e = ofw->local_search(xmin, state->ebest, x);\n            xmin = vec(x);\n            emin = e;\n            not_improved_idx = 0;\n            not_improved_max_idx = state->current_location.size();\n            if (e < state->ebest) {\n                state->update_best(emin, xmin);\n                state->update_current(e, x);\n            }\n        }\n    }\n\nprivate:\n\n    double emin;\n    vec xmin;\n    EnergyState *state;\n    double acceptance_param;\n    VisitingDistribution *vd;\n    int not_improved_idx;\n    int not_improved_max_idx;\n    pcg64 *rs;\n    Fitness *ofw;\n    double temperature_step;\n    double K;\n    bool state_improved = false;\n};\n\nclass sizeexception: public exception {\n    virtual const char* what() const throw () {\n        return \"Bounds size does not match x0\";\n    }\n} sizeeexc;\n\nclass DARunner {\n\npublic:\n\n    DARunner(Fitness *fun_, vec &x0_, long seed_, bool use_local_search_) {\n        owf = fun_;\n        if (x0_.size() > 0 && x0_.size() != owf->lower.size())\n            throw sizeeexc;\n        //Initialization of RandomState for reproducible runs if seed provided\n        rs = new pcg64(seed_);\n        use_local_search = use_local_search_;\n        // Initialization of the energy state\n        es = new EnergyState(owf->lower.size());\n        es->reset(owf, rs, x0_);\n        // VisitingDistribution instance\n        vd = new VisitingDistribution(owf->lower.size(), qv, rs);\n        // Markov chain instance\n        sc = new StrategyChain(qa, vd, owf, rs, es);\n    }\n\n    ~DARunner() {\n        delete rs;\n        delete vd;\n        delete sc;\n        delete es;\n    }\n\n    void search() {\n        iter = 0;\n        double t1 = exp((qv - 1) * log(2.0)) - 1.0;\n        for (;;) {\n            for (int i = 0; i < maxsteps; i++) {\n                // Compute temperature for this step\n                double s = i + 2.0;\n                double t2 = exp((qv - 1) * log(s)) - 1.0;\n                double temperature = temperature_start * t1 / t2;\n                if (iter++ >= maxsteps)\n                    return;\n                // Need a re-annealing process?\n                if (temperature < temperature_restart) {\n                    es->reset(owf, rs, emptyVec);\n                    break;\n                }\n                // starting strategy chain\n                sc->run(i, temperature);\n                if (owf->maxEvalReached())\n                    return;\n                if (use_local_search) {\n                    sc->local_search();\n                    if (owf->maxEvalReached())\n                        return;\n                }\n            }\n        }\n    }\n\n    vec bestX() {\n        return es->xbest;\n    }\n\n    double bestY() {\n        return es->ebest;\n    }\n\nprivate:\n\n    int MAX_REINIT_COUNT = 1000;\n    double temperature_start = 5230;\n    double qv = 2.62;\n    double qa = -5.0;\n    bool use_local_search;\n    // maximum number of step (main iteration)\n    double maxsteps = 1000;\n    // minimum value of annealing temperature reached to perform\n    // re-annealing temperature_start\n    double temperature_restart = 0.1;\n    Fitness *owf;\n    pcg64 *rs;\n    EnergyState *es;\n    StrategyChain *sc;\n    VisitingDistribution *vd;\n    int iter = 0;\n};\n\ndouble minimize(Fitness *fun, vec &x0, long seed, bool use_local_search,\n        vec &X) {\n    DARunner gr = DARunner(fun, x0, seed, use_local_search);\n    gr.search();\n    int dim = x0.size();\n    vec bx = gr.bestX();\n    for (int i = 0; i < dim; i++)\n        X[i] = bx[i];\n    return gr.bestY();\n}\n}\n\nusing namespace dual_annealing;\n\nextern \"C\" {\nvoid optimizeDA_C(long runid, callback_type func, int dim, int seed,\n        double *init, double *lower, double *upper, int maxEvals,\n        bool use_local_search, double* res) {\n    int n = dim;\n    vec guess(n), lower_limit(n), upper_limit(n);\n    bool useLimit = false;\n    for (int i = 0; i < n; i++) {\n        guess[i] = init[i];\n        lower_limit[i] = lower[i];\n        upper_limit[i] = upper[i];\n        useLimit |= (lower[i] != 0);\n        useLimit |= (upper[i] != 0);\n    }\n    if (useLimit == false) {\n        lower_limit.resize(0);\n        upper_limit.resize(0);\n    }\n    if (maxEvals <= 0)\n        maxEvals = 1E7;\n    Fitness fitfun(func, &lower_limit, &upper_limit, maxEvals);\n\n    try {\n        vec X = zeros(dim);\n        vec enc = fitfun.encode(guess);\n        double bestY = minimize(&fitfun, enc, seed, use_local_search, X);\n        vec bestX = fitfun.decode(X);\n        for (int i = 0; i < n; i++)\n            res[i] = bestX[i];\n        res[n] = bestY;\n        res[n + 1] = fitfun.getEvaluations();\n        res[n + 2] = 0;\n        res[n + 3] = 0;\n    } catch (std::exception &e) {\n        cerr << e.what() << endl;\n    }\n}\n}\n\n", "meta": {"hexsha": "057f815e7cbfdf2b3c6733bf555df43af64f63a8", "size": 20730, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_fcmaescpp/daoptimizer.cpp", "max_stars_repo_name": "vishalbelsare/fast-cma-es", "max_stars_repo_head_hexsha": "c6bed439bc4bf78dca7d9f2203b56d74ce272f01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-05-28T10:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T08:09:58.000Z", "max_issues_repo_path": "_fcmaescpp/daoptimizer.cpp", "max_issues_repo_name": "vishalbelsare/fast-cma-es", "max_issues_repo_head_hexsha": "c6bed439bc4bf78dca7d9f2203b56d74ce272f01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-03-04T15:16:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T07:14:19.000Z", "max_forks_repo_path": "_fcmaescpp/daoptimizer.cpp", "max_forks_repo_name": "vishalbelsare/fast-cma-es", "max_forks_repo_head_hexsha": "c6bed439bc4bf78dca7d9f2203b56d74ce272f01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2020-02-19T12:26:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:22:13.000Z", "avg_line_length": 29.8703170029, "max_line_length": 92, "alphanum_fraction": 0.5377231066, "num_tokens": 5289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.532045605865651}}
{"text": "/*\n * \n * Copyright (c) Toon Knapen & Kresimir Fresl 2003\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 * KF acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_HPSV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_HPSV_HPP\n\n#include <boost/numeric/bindings/traits/type_traits.hpp>\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/lapack/lapack.h>\n#include <boost/numeric/bindings/traits/detail/array.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits/is_same.hpp>\n#endif \n\n#include <cassert>\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace lapack {\n\n    /////////////////////////////////////////////////////////////////////\n    //\n    // system of linear equations A * X = B\n    // with A Hermitian indefinite matrix stored in packed format \n    //\n    /////////////////////////////////////////////////////////////////////\n\n    /*\n     * hpsv() computes the solution to a system of linear equations \n     * A * X = B, where A is an N-by-N Hermitian matrix in packed\n     * storage and X and B are N-by-NRHS matrices.\n     *\n     * The diagonal pivoting method is used to factor A as\n     *   A = U * D * U^H,  if UPLO = 'U', \n     *   A = L * D * L^H,  if UPLO = 'L',\n     * where  U (or L) is a product of permutation and unit upper \n     * (lower) triangular matrices, and D is Hermitian and block \n     * diagonal with 1-by-1 and 2-by-2 diagonal blocks. The factored \n     * form of A is then used to solve the system of equations A * X = B.\n     */\n\n    namespace detail {\n\n      inline \n      void hpsv (char const uplo, int const n, int const nrhs,\n                 traits::complex_f* ap, int* ipiv,  \n                 traits::complex_f* b, int const ldb, int* info) \n      {\n        LAPACK_CHPSV (&uplo, &n, &nrhs, \n                      traits::complex_ptr (ap), ipiv, \n                      traits::complex_ptr (b), &ldb, info);\n      }\n\n      inline \n      void hpsv (char const uplo, int const n, int const nrhs,\n                 traits::complex_d* ap, int* ipiv, \n                 traits::complex_d* b, int const ldb, int* info) \n      {\n        LAPACK_ZHPSV (&uplo, &n, &nrhs, \n                      traits::complex_ptr (ap), ipiv, \n                      traits::complex_ptr (b), &ldb, info);\n      }\n\n      template <typename HermA, typename MatrB, typename IVec>\n      inline\n      int hpsv (HermA& a, IVec& i, MatrB& b) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<HermA>::matrix_structure, \n          traits::hermitian_packed_t\n        >::value));\n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrB>::matrix_structure, \n          traits::general_t\n        >::value));\n#endif\n\n        int const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a)); \n        assert (n == traits::matrix_size1 (b)); \n\n        char uplo = traits::matrix_uplo_tag (a);\n        int info; \n        hpsv (uplo, n, traits::matrix_size2 (b), \n              traits::matrix_storage (a), \n              traits::vector_storage (i),  \n              traits::matrix_storage (b),\n              traits::leading_dimension (b),\n              &info);\n        return info; \n      }\n\n    }\n\n    template <typename HermA, typename MatrB, typename IVec> \n    inline\n    int hpsv (HermA& a, IVec& i, MatrB& b) {\n      assert (traits::matrix_size1 (a) == traits::vector_size (i)); \n      return detail::hpsv (a, i, b); \n    }\n\n    template <typename HermA, typename MatrB>\n    inline\n    int hpsv (HermA& a, MatrB& b) {\n      // with 'internal' pivot vector\n\n      int info = -101; \n      traits::detail::array<int> i (traits::matrix_size1 (a)); \n\n      if (i.valid()) \n        info = detail::hpsv (a, i, b); \n      return info; \n    }\n\n\n    /*\n     * hptrf() computes the factorization of a Hermitian matrix A \n     * in packed storage using the  Bunch-Kaufman diagonal pivoting \n     * method. The form of the factorization is\n     *    A = U * D * U^H  or  A = L * D * L^H\n     * where U (or L) is a product of permutation and unit upper (lower)  \n     * triangular matrices, and D is Hermitian and block diagonal with \n     * 1-by-1 and 2-by-2 diagonal blocks.\n     */\n\n    namespace detail {\n\n      inline \n      void hptrf (char const uplo, int const n, \n                  traits::complex_f* ap, int* ipiv, int* info) \n      {\n        LAPACK_CHPTRF (&uplo, &n, traits::complex_ptr (ap), ipiv, info);\n      }\n\n      inline \n      void hptrf (char const uplo, int const n, \n                  traits::complex_d* ap, int* ipiv, int* info) \n      {\n        LAPACK_ZHPTRF (&uplo, &n, traits::complex_ptr (ap), ipiv, info);\n      }\n\n      template <typename HermA, typename IVec, typename Work>\n      inline\n      int hptrf (char const ul, HermA& a, IVec& i, Work& w, int const lw) {\n\n      }\n\n    }\n\n    template <typename HermA, typename IVec> \n    inline\n    int hptrf (HermA& a, IVec& i) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure, \n        traits::hermitian_packed_t\n      >::value));\n#endif\n\n      int const n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a)); \n      assert (n == traits::vector_size (i)); \n\n      char uplo = traits::matrix_uplo_tag (a);\n      int info; \n      detail::hptrf (uplo, n, traits::matrix_storage (a), \n                     traits::vector_storage (i), &info);\n      return info; \n    }\n\n\n    /*\n     * hptrs() solves a system of linear equations A*X = B with \n     * a Hermitian matrix A in packed storage using the factorization \n     *    A = U * D * U^H   or  A = L * D * L^H\n     * computed by hptrf().\n     */\n\n    namespace detail {\n\n      inline \n      void hptrs (char const uplo, int const n, int const nrhs,\n                  traits::complex_f const* ap, int const* ipiv, \n                  traits::complex_f* b, int const ldb, int* info) \n      {\n        LAPACK_CHPTRS (&uplo, &n, &nrhs, \n                       traits::complex_ptr (ap), ipiv, \n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n      inline \n      void hptrs (char const uplo, int const n, int const nrhs,\n                  traits::complex_d const* ap, int const* ipiv, \n                  traits::complex_d* b, int const ldb, int* info) \n      {\n        LAPACK_ZHPTRS (&uplo, &n, &nrhs, \n                       traits::complex_ptr (ap), ipiv, \n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n    }\n\n    template <typename HermA, typename MatrB, typename IVec>\n    inline\n    int hptrs (HermA const& a, IVec const& i, MatrB& b) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure, \n        traits::hermitian_packed_t\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure, \n        traits::general_t\n      >::value));\n#endif\n\n      int const n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a)); \n      assert (n == traits::matrix_size1 (b)); \n      assert (n == traits::vector_size (i)); \n\n      char uplo = traits::matrix_uplo_tag (a);\n      int info; \n      detail::hptrs (uplo, n, traits::matrix_size2 (b), \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                     traits::matrix_storage (a), \n                     traits::vector_storage (i),  \n#else\n                     traits::matrix_storage_const (a), \n                     traits::vector_storage_const (i),  \n#endif \n                     traits::matrix_storage (b),\n                     traits::leading_dimension (b), \n                     &info);\n        return info; \n    }\n\n\n    // TO DO: hptri\n\n  }\n\n}}}\n\n#endif \n", "meta": {"hexsha": "0f723777c8f5e4bfb9026d32bd2771ca2bfd93b0", "size": 8146, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "openrave/plugins/include/boost/numeric/bindings/lapack/hpsv.hpp", "max_stars_repo_name": "jdsika/TUM_HOly", "max_stars_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-11-13T16:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T15:37:19.000Z", "max_issues_repo_path": "openrave/plugins/include/boost/numeric/bindings/lapack/hpsv.hpp", "max_issues_repo_name": "jdsika/holy", "max_issues_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-06-13T01:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-14T00:38:27.000Z", "max_forks_repo_path": "openrave/plugins/include/boost/numeric/bindings/lapack/hpsv.hpp", "max_forks_repo_name": "jdsika/holy", "max_forks_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "max_forks_repo_licenses": ["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.2107279693, "max_line_length": 75, "alphanum_fraction": 0.5713233489, "num_tokens": 2186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5320455950332541}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-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#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_HAVERSINE_HPP\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_HAVERSINE_HPP\n\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n\n\n\nnamespace boost { namespace geometry\n{\n\n\nnamespace strategy { namespace distance\n{\n\n\nnamespace comparable\n{\n\n// Comparable haversine.\n// To compare distances, we can avoid:\n// - multiplication with radius and 2.0\n// - applying sqrt\n// - applying asin (which is strictly (monotone) increasing)\ntemplate\n<\n    typename RadiusType,\n    typename CalculationType = void\n>\nclass haversine\n{\npublic :\n    template <typename Point1, typename Point2>\n    struct calculation_type\n        : promote_floating_point\n          <\n              typename select_calculation_type\n                  <\n                      Point1,\n                      Point2,\n                      CalculationType\n                  >::type\n          >\n    {};\n\n    typedef RadiusType radius_type;\n\n    explicit inline haversine(RadiusType const& r = 1.0)\n        : m_radius(r)\n    {}\n\n    template <typename Point1, typename Point2>\n    static inline typename calculation_type<Point1, Point2>::type\n    apply(Point1 const& p1, Point2 const& p2)\n    {\n        return calculate<typename calculation_type<Point1, Point2>::type>(\n                   get_as_radian<0>(p1), get_as_radian<1>(p1),\n                   get_as_radian<0>(p2), get_as_radian<1>(p2)\n               );\n    }\n\n    inline RadiusType radius() const\n    {\n        return m_radius;\n    }\n\n\nprivate :\n    template <typename R, typename T1, typename T2>\n    static inline R calculate(T1 const& lon1, T1 const& lat1,\n                              T2 const& lon2, T2 const& lat2)\n    {\n        return math::hav(lat2 - lat1)\n                + cos(lat1) * cos(lat2) * math::hav(lon2 - lon1);\n    }\n\n    RadiusType m_radius;\n};\n\n\n\n} // namespace comparable\n\n/*!\n\\brief Distance calculation for spherical coordinates\non a perfect sphere using haversine\n\\ingroup strategies\n\\tparam RadiusType \\tparam_radius\n\\tparam CalculationType \\tparam_calculation\n\\author Adapted from: http://williams.best.vwh.net/avform.htm\n\\see http://en.wikipedia.org/wiki/Great-circle_distance\n\\note (from Wiki:) The great circle distance d between two\npoints with coordinates {lat1,lon1} and {lat2,lon2} is given by:\n    d=acos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(lon1-lon2))\nA mathematically equivalent formula, which is less subject\n    to rounding error for short distances is:\n    d=2*asin(sqrt((sin((lat1-lat2) / 2))^2\n    + cos(lat1)*cos(lat2)*(sin((lon1-lon2) / 2))^2))\n\n\n\\qbk{\n[heading See also]\n[link geometry.reference.algorithms.distance.distance_3_with_strategy distance (with strategy)]\n}\n\n*/\ntemplate\n<\n    typename RadiusType,\n    typename CalculationType = void\n>\nclass haversine\n{\n    typedef comparable::haversine<RadiusType, CalculationType> comparable_type;\n\npublic :\n    template <typename Point1, typename Point2>\n    struct calculation_type\n        : services::return_type<comparable_type, Point1, Point2>\n    {};\n\n    typedef RadiusType radius_type;\n\n    /*!\n    \\brief Constructor\n    \\param radius radius of the sphere, defaults to 1.0 for the unit sphere\n    */\n    inline haversine(RadiusType const& radius = 1.0)\n        : m_radius(radius)\n    {}\n\n    /*!\n    \\brief applies the distance calculation\n    \\return the calculated distance (including multiplying with radius)\n    \\param p1 first point\n    \\param p2 second point\n    */\n    template <typename Point1, typename Point2>\n    inline typename calculation_type<Point1, Point2>::type\n    apply(Point1 const& p1, Point2 const& p2) const\n    {\n        typedef typename calculation_type<Point1, Point2>::type calculation_type;\n        calculation_type const a = comparable_type::apply(p1, p2);\n        calculation_type const c = calculation_type(2.0) * asin(math::sqrt(a));\n        return calculation_type(m_radius) * c;\n    }\n\n    /*!\n    \\brief access to radius value\n    \\return the radius\n    */\n    inline RadiusType radius() const\n    {\n        return m_radius;\n    }\n\nprivate :\n    RadiusType m_radius;\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename RadiusType, typename CalculationType>\nstruct tag<haversine<RadiusType, CalculationType> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename RadiusType, typename CalculationType, typename P1, typename P2>\nstruct return_type<haversine<RadiusType, CalculationType>, P1, P2>\n    : haversine<RadiusType, CalculationType>::template calculation_type<P1, P2>\n{};\n\n\ntemplate <typename RadiusType, typename CalculationType>\nstruct comparable_type<haversine<RadiusType, CalculationType> >\n{\n    typedef comparable::haversine<RadiusType, CalculationType> type;\n};\n\n\ntemplate <typename RadiusType, typename CalculationType>\nstruct get_comparable<haversine<RadiusType, CalculationType> >\n{\nprivate :\n    typedef haversine<RadiusType, CalculationType> this_type;\n    typedef comparable::haversine<RadiusType, CalculationType> comparable_type;\npublic :\n    static inline comparable_type apply(this_type const& input)\n    {\n        return comparable_type(input.radius());\n    }\n};\n\ntemplate <typename RadiusType, typename CalculationType, typename P1, typename P2>\nstruct result_from_distance<haversine<RadiusType, CalculationType>, P1, P2>\n{\nprivate :\n    typedef haversine<RadiusType, CalculationType> this_type;\n    typedef typename return_type<this_type, P1, P2>::type return_type;\npublic :\n    template <typename T>\n    static inline return_type apply(this_type const& , T const& value)\n    {\n        return return_type(value);\n    }\n};\n\n\n// Specializations for comparable::haversine\ntemplate <typename RadiusType, typename CalculationType>\nstruct tag<comparable::haversine<RadiusType, CalculationType> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename RadiusType, typename CalculationType, typename P1, typename P2>\nstruct return_type<comparable::haversine<RadiusType, CalculationType>, P1, P2>\n    : comparable::haversine<RadiusType, CalculationType>::template calculation_type<P1, P2>\n{};\n\n\ntemplate <typename RadiusType, typename CalculationType>\nstruct comparable_type<comparable::haversine<RadiusType, CalculationType> >\n{\n    typedef comparable::haversine<RadiusType, CalculationType> type;\n};\n\n\ntemplate <typename RadiusType, typename CalculationType>\nstruct get_comparable<comparable::haversine<RadiusType, CalculationType> >\n{\nprivate :\n    typedef comparable::haversine<RadiusType, CalculationType> this_type;\npublic :\n    static inline this_type apply(this_type const& input)\n    {\n        return input;\n    }\n};\n\n\ntemplate <typename RadiusType, typename CalculationType, typename P1, typename P2>\nstruct result_from_distance<comparable::haversine<RadiusType, CalculationType>, P1, P2>\n{\nprivate :\n    typedef comparable::haversine<RadiusType, CalculationType> strategy_type;\n    typedef typename return_type<strategy_type, P1, P2>::type return_type;\npublic :\n    template <typename T>\n    static inline return_type apply(strategy_type const& strategy, T const& distance)\n    {\n        return_type const s = sin((distance / strategy.radius()) / return_type(2));\n        return s * s;\n    }\n};\n\n\n// Register it as the default for point-types\n// in a spherical equatorial coordinate system\ntemplate <typename Point1, typename Point2>\nstruct default_strategy\n    <\n        point_tag, point_tag, Point1, Point2,\n        spherical_equatorial_tag, spherical_equatorial_tag\n    >\n{\n    typedef strategy::distance::haversine<typename select_coordinate_type<Point1, Point2>::type> type;\n};\n\n// Note: spherical polar coordinate system requires \"get_as_radian_equatorial\"\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::distance\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_HAVERSINE_HPP\n", "meta": {"hexsha": "8b32056f3e99198bc9d6d00f81ba320ddf853b2b", "size": 8510, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/geometry/strategies/spherical/distance_haversine.hpp", "max_stars_repo_name": "multi-os-engine/cinder-natj-binding", "max_stars_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/strategies/spherical/distance_haversine.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 369.0, "max_issues_repo_issues_event_min_datetime": "2016-10-21T07:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T10:49:29.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/strategies/spherical/distance_haversine.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 27.8104575163, "max_line_length": 102, "alphanum_fraction": 0.7207990599, "num_tokens": 2007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5320455943628052}}
{"text": "#ifndef __EIGENINTERFACE_HXX__\n#define __EIGENINTERFACE_HXX__\n\n#ifdef LEGOLAS_USE_EIGEN\n\n#include <Eigen/Core>\n\nnamespace Legolas{\n  \n  template <class REAL_TYPE>\n  class EigenInterface{\n  public:\n    typedef REAL_TYPE RealType;\n    //    typedef Eigen::Matrix<RealType,Eigen::Dynamic,1>     EigenVector;\n    typedef Eigen::Array<RealType,Eigen::Dynamic,1>     EigenVector;\n    typedef Eigen::Matrix<RealType,Eigen::Dynamic,1>    EigenMatrix;\n    //    typedef Eigen::Map<EigenVector>        EigenVectorView;\n    //    typedef Eigen::Map<EigenVector,Eigen::Aligned>        EigenVectorView;\n    //    typedef Eigen::Map<EigenVector>        EigenVectorView;\n    typedef Eigen::Map<EigenVector,Eigen::Aligned>        EigenVectorView;\n    typedef Eigen::Map<EigenMatrix,Eigen::Aligned>        EigenMatrixView;\n\n  };\n  \n}\n\n#endif\n\n\n#endif\n\n\n\n\n\n\n", "meta": {"hexsha": "867a5a86ff019dc53a388fcf84e746f94fe41770", "size": 840, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "Legolas/Vector/EigenInterface.hxx", "max_stars_repo_name": "LaurentPlagne/Legolas", "max_stars_repo_head_hexsha": "fdf533528baf7ab5fcb1db15d95d2387b3e3723c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Legolas/Vector/EigenInterface.hxx", "max_issues_repo_name": "LaurentPlagne/Legolas", "max_issues_repo_head_hexsha": "fdf533528baf7ab5fcb1db15d95d2387b3e3723c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Legolas/Vector/EigenInterface.hxx", "max_forks_repo_name": "LaurentPlagne/Legolas", "max_forks_repo_head_hexsha": "fdf533528baf7ab5fcb1db15d95d2387b3e3723c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-11T14:43:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-11T14:43:25.000Z", "avg_line_length": 22.7027027027, "max_line_length": 80, "alphanum_fraction": 0.6916666667, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5320455896170555}}
{"text": "#ifndef NBT_INTEGRATOR_HPP\r\n#define NBT_INTEGRATOR_HPP\r\n\r\n#include <Eigen>\r\n\r\n/**\r\n * Abstract function object for integrators. Integrators\r\n * are functional interfaces that update the position and\r\n * velocity matrices using an acceleration matrix.\r\n */\r\nclass Integrator {\r\n    public:\r\n        /**\r\n         * @brief Computes velocities and positions from accelerations and time step.\r\n         * \r\n         * @param dt Time step\r\n         * @param a Acceleration matrix\r\n         * @param v Velocity matrix\r\n         * @param x Position matrix\r\n         */\r\n        virtual void integrate(double dt,\r\n                               const Eigen::Ref<const Eigen::MatrixXd>& a,\r\n                               Eigen::Ref<Eigen::MatrixXd> v,\r\n                               Eigen::Ref<Eigen::MatrixXd> x) = 0;\r\n};\r\n\r\n\r\n/**\r\n * Performs Euler integration. Fast but inaccurate.\r\n */\r\nclass EulerIntegrator: public Integrator {\r\n    public:\r\n        /**\r\n         * @brief Computes velocities and positions from accelerations and time step.\r\n         * \r\n         * @param dt Time step\r\n         * @param a Acceleration matrix\r\n         * @param v Velocity matrix\r\n         * @param x Position matrix\r\n         */\r\n        void integrate(double dt,\r\n                       const Eigen::Ref<const Eigen::MatrixXd>& a,\r\n                       Eigen::Ref<Eigen::MatrixXd> v,\r\n                       Eigen::Ref<Eigen::MatrixXd> x);\r\n};\r\n\r\n\r\n/**\r\n * Performs Verlet integration. Is symplectic but not as accurate as RungeKuttaIntegrator.\r\n */\r\nclass VerletIntegrator: public Integrator {\r\n    public:\r\n        bool isFirstIteration = true;\r\n        Eigen::MatrixXd aPrev;\r\n\r\n        /**\r\n         * @brief Computes velocities and positions from accelerations and time step.\r\n         * \r\n         * @param dt Time step\r\n         * @param a Acceleration matrix\r\n         * @param v Velocity matrix\r\n         * @param x Position matrix\r\n         */\r\n        void integrate(double dt,\r\n                       const Eigen::Ref<const Eigen::MatrixXd>& a,\r\n                       Eigen::Ref<Eigen::MatrixXd> v,\r\n                       Eigen::Ref<Eigen::MatrixXd> x);\r\n};\r\n\r\n\r\n/**\r\n * Performs Runge-Kutta 4th order integration method. More accurate than EulerIntegrator but slower.\r\n */\r\nclass RungeKuttaIntegrator: public Integrator {\r\n    public:\r\n        /**\r\n         * @brief Computes velocities and positions from accelerations and time step.\r\n         * \r\n         * @param dt Time step\r\n         * @param a Acceleration matrix\r\n         * @param v Velocity matrix\r\n         * @param x Position matrix\r\n         */\r\n        void integrate(double dt,\r\n                       const Eigen::Ref<const Eigen::MatrixXd>& a,\r\n                       Eigen::Ref<Eigen::MatrixXd> v,\r\n                       Eigen::Ref<Eigen::MatrixXd> x); // TODO runge kutta\r\n};\r\n\r\n#endif", "meta": {"hexsha": "0ed0715722d4113aac2010ed6629ff40892f2e0e", "size": 2857, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/integrator.hpp", "max_stars_repo_name": "tdude92/nbody-tool", "max_stars_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-12T08:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:37:44.000Z", "max_issues_repo_path": "include/integrator.hpp", "max_issues_repo_name": "tdude92/nbody-tool", "max_issues_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_issues_repo_licenses": ["MIT"], "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/integrator.hpp", "max_forks_repo_name": "tdude92/nbody-tool", "max_forks_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_forks_repo_licenses": ["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.7444444444, "max_line_length": 101, "alphanum_fraction": 0.5502275114, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5320388958440719}}
{"text": "#define BOOST_TEST_DYN_LINK // optional\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE MyTest // specify the name of your test module\n#if defined (__GNUC__) && defined(__unix__)\n    #include <boost/test/included/unit_test.hpp> // include this to get main()\n#elif defined (WIN32)\n    #include <boost/test/unit_test.hpp> // include this to get main()\n#endif\n\n#include <iostream>\n#include <FixedPoints.h>\n#include <FixedPointsCommon.h>\n\nusing namespace boost::unit_test;\nusing namespace std;\n\ntemplate class UFixed<8, 8>;\ntemplate class SFixed<7, 8>;\n\nBOOST_AUTO_TEST_SUITE(testsuite)\n\nBOOST_AUTO_TEST_CASE(test_getters_ufixed) {\n  UQ8x8 a = 1.5;\n  BOOST_CHECK( sizeof(uint16_t) == sizeof(a.getInternal()));\n  BOOST_CHECK( 0x0180 == a.getInternal());\n\n  BOOST_CHECK( sizeof(uint8_t) == sizeof(a.getInteger()));\n  BOOST_CHECK( 0x01 == a.getInteger());\n\n  BOOST_CHECK( sizeof(uint8_t) == sizeof(a.getFraction()));\n  BOOST_CHECK( 0x80 == a.getFraction());\n}\n\nBOOST_AUTO_TEST_CASE(test_cast_operators_ufixed) {\n  UQ8x8 a = 1.5;\n  BOOST_CHECK( 1.5 == static_cast<float>(a) );\n  BOOST_CHECK( 1.5 == static_cast<double>(a) );\n  BOOST_CHECK( 1.5 == static_cast<long double>(a) );\n  BOOST_CHECK( 1 == static_cast<unsigned char>(a) );\n  BOOST_CHECK( 1.5 == static_cast<UQ16x16>(a) );\n  BOOST_CHECK(1.5 == (static_cast<UFixed<16, 8> >(a)));\n  BOOST_CHECK(1.5 == (static_cast<UFixed<20, 4> >(a)));\n\n  BOOST_CHECK(1.5 == static_cast<SQ7x8>(a));\n  BOOST_CHECK(1.5 == (static_cast<SFixed<7, 16> >(a)));\n  BOOST_CHECK(1.5 == (static_cast<SFixed<11, 4> >(a)));\n  a = 0;\n  BOOST_CHECK(0 == static_cast<SQ7x8>(a));\n}\n\nBOOST_AUTO_TEST_CASE(test_getters_sfixed) {\n  SQ7x8 a = 1.5;\n  BOOST_CHECK( sizeof(uint16_t) == sizeof(a.getInternal()));\n  BOOST_CHECK( 0x0180 == a.getInternal());\n\n  BOOST_CHECK( sizeof(uint8_t) == sizeof(a.getInteger()));\n  BOOST_CHECK( 0x01 == a.getInteger());\n\n  BOOST_CHECK( sizeof(uint8_t) == sizeof(a.getFraction()));\n  BOOST_CHECK( 0x80 == a.getFraction());\n}\n\nBOOST_AUTO_TEST_CASE(test_cast_operators_sfixed) {\n  SQ7x8 a = 1.5;\n  SQ15x16 b = 1.5;\n  BOOST_CHECK( 1.5 == static_cast<float>(a) );\n  BOOST_CHECK( 1.5 == static_cast<double>(a) );\n  BOOST_CHECK( 1.5 == static_cast<long double>(a) );\n  BOOST_CHECK( 1 == static_cast<signed char>(a) );\n  BOOST_CHECK( b == static_cast<SQ15x16>(a) );\n  BOOST_CHECK(1.5 == static_cast<UQ8x8>(a));\n  a = 0;\n  BOOST_CHECK(0 == static_cast<UQ8x8>(a));\n  a = -1;\n  BOOST_CHECK(255 == static_cast<UQ8x8>(a));\n  a = -12.5;\n  BOOST_CHECK(243.5 == static_cast<UQ8x8>(a));\n}\n\nBOOST_AUTO_TEST_CASE(test_utils) {\n  UQ8x8 a = 1.5;\n  UQ8x8 b = floorFixed(a);\n  BOOST_CHECK( 1.0 == static_cast<float>(b));\n}\n\nBOOST_AUTO_TEST_CASE(test_random_ufixed) {\n  auto a = randomUFixed<8, 8>();\n  BOOST_CHECK( sizeof(uint16_t) == sizeof(a.getInternal()));\n  BOOST_CHECK( sizeof(uint8_t) == sizeof(a.getInteger()));\n  BOOST_CHECK( sizeof(uint8_t) == sizeof(a.getFraction()));\n}\n\nBOOST_AUTO_TEST_CASE(test_random_sfixed) {\n  auto a = randomSFixed<7, 8>();\n  BOOST_CHECK( sizeof(uint16_t) == sizeof(a.getInternal()));\n  BOOST_CHECK( sizeof(uint8_t) == sizeof(a.getInteger()));\n  BOOST_CHECK( sizeof(uint8_t) == sizeof(a.getFraction()));\n}\n\nBOOST_AUTO_TEST_CASE(test_multiply_ufixed) {\n  UQ8x8 a = 200.0;\n  UQ8x8 b = 1.5;\n  BOOST_CHECK( 300.0 == static_cast<float>(multiply(a, b)));\n}\n\nBOOST_AUTO_TEST_CASE(test_multiply_sfixed) {\n  SQ7x8 a = 100.0;\n  SQ7x8 b = 1.5;\n  BOOST_CHECK( 150.0 == static_cast<float>(multiply(a, b)));\n}\n\nBOOST_AUTO_TEST_CASE(test_basic_arithmetic_operations_same_size_ufixed) {\n  UQ8x8 a = 100.0;\n  UQ8x8 b = 1.5;\n  BOOST_CHECK( 101.5 == a + b);\n  BOOST_CHECK( 98.5 == a - b);\n  BOOST_CHECK( 150 == a * b);\n  BOOST_CHECK( UQ8x8(66.66666666666667) == a / b);\n}\n\nBOOST_AUTO_TEST_CASE(test_basic_arithmetic_operations_same_size_sfixed) {\n  SQ7x8 a = 100.0;\n  SQ7x8 b = 1.5;\n  BOOST_CHECK( 101.5 == a + b);\n  BOOST_CHECK( 98.5 == a - b);\n  BOOST_CHECK( 150 == a * b);\n  BOOST_CHECK( SQ7x8(66.66666666666667) == a / b);\n}\n\nBOOST_AUTO_TEST_CASE(test_compound_assignemnt_operators_ufixed) {\n  UQ8x8 a = 100.0;\n  UQ8x8 b = 1.5;\n  a += b;\n  BOOST_CHECK( 101.5 == a);\n  a -= b;\n  BOOST_CHECK( 100.0 == a);\n  a *= b;\n  BOOST_CHECK( 150 == a);\n  a /= b;\n  BOOST_CHECK( 100.0 == a);\n}\n\nBOOST_AUTO_TEST_CASE(test_compound_assignemnt_operators_sfixed) {\n  SQ7x8 a = 100.0;\n  SQ7x8 b = 1.25;\n  a += b;\n  BOOST_CHECK( 101.25 == a);\n  a -= b;\n  BOOST_CHECK( 100.0 == a);\n  a *= b;\n  BOOST_CHECK( 125 == a);\n  a /= b;\n  BOOST_CHECK( 100.0 == a);\n\n  a = -100.0;\n  a += b;\n  BOOST_CHECK( -98.75 == a);\n  a -= b;\n  BOOST_CHECK( -100.0 == a);\n  a *= b;\n  BOOST_CHECK( -125 == a);\n  a /= b;\n  BOOST_CHECK( -100.0 == a);\n}\n\nBOOST_AUTO_TEST_CASE(test_increment_and_decrement_ufixed) {\n  UQ8x8 a = 100.0;\n  ++a;\n  BOOST_CHECK( 101.0 == a);\n  --a;\n  BOOST_CHECK( 100.0 == a);\n  UQ8x8 b = a++;\n  BOOST_CHECK( 100.0 == b);\n  BOOST_CHECK( 101.0 == a);\n  b = a--;\n  BOOST_CHECK( 100.0 == a);\n  BOOST_CHECK( 101.0 == b);\n}\n\nBOOST_AUTO_TEST_CASE(test_increment_and_decrement_sfixed) {\n  SQ7x8 a = 100.0;\n  ++a;\n  BOOST_CHECK( 101.0 == a);\n  --a;\n  BOOST_CHECK( 100.0 == a);\n  SQ7x8 b = a++;\n  BOOST_CHECK( 100.0 == b);\n  BOOST_CHECK( 101.0 == a);\n  b = a--;\n  BOOST_CHECK( 100.0 == a);\n  BOOST_CHECK( 101.0 == b);\n}\n\nBOOST_AUTO_TEST_CASE(test_statics_ufixed) {\n  UQ8x8 a = 100.0;\n  UQ8x8 b = UQ8x8::fromInternal(a.getInternal());\n  BOOST_CHECK( 100.0 == b);\n}\n\nBOOST_AUTO_TEST_CASE(test_statics_sfixed) {\n  SQ7x8 a = 100.0;\n  SQ7x8 b = SQ7x8::fromInternal(a.getInternal());\n  BOOST_CHECK( 100.0 == b);\n  BOOST_CHECK( -100.0 == -b);\n}\n\nBOOST_AUTO_TEST_CASE(test_constructors_ufixed) {\n  UQ8x8 a;\n  BOOST_CHECK(0.0 == a);\n  UQ8x8 b(static_cast<const char> (5));\n  BOOST_CHECK(5 == b);\n  UQ8x8 c(static_cast<const unsigned char> (5));\n  BOOST_CHECK(5 == c);\n  UQ8x8 d(static_cast<const signed char> (5));\n  BOOST_CHECK(5 == d);\n  UQ8x8 e(static_cast<const unsigned short> (5));\n  BOOST_CHECK(5 == e);\n  UQ8x8 f(static_cast<const signed short> (5));\n  BOOST_CHECK(5 == f);\n  UQ8x8 g(static_cast<const unsigned int> (5));\n  BOOST_CHECK(5 == g);\n  UQ8x8 h(static_cast<const signed int> (5));\n  BOOST_CHECK(5 == h);\n  UQ8x8 i(static_cast<const unsigned long> (5));\n  BOOST_CHECK(5 == i);\n  UQ8x8 j(static_cast<const signed long> (5));\n  BOOST_CHECK(5 == j);\n  UQ8x8 k(static_cast<const unsigned long long> (5));\n  BOOST_CHECK(5 == k);\n  UQ8x8 l(static_cast<const signed long long>(5));\n  BOOST_CHECK(5 == l);\n  UQ8x8 m(static_cast<float>(5));\n  BOOST_CHECK(5 == m);\n  UQ8x8 n(static_cast<long double>(5));\n  BOOST_CHECK(5 == n);\n  UQ8x8 o(static_cast<long double>(5));\n  BOOST_CHECK(5 == o);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3a11cdf5633f71ddf61ea4a875191e4770cb3dc4", "size": 6631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tst/FixedPointsTest.cpp", "max_stars_repo_name": "miracoli/FixedPointsArduino", "max_stars_repo_head_hexsha": "d593f5d16fd12dbc875b2ca539f5684bf69506cb", "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": "tst/FixedPointsTest.cpp", "max_issues_repo_name": "miracoli/FixedPointsArduino", "max_issues_repo_head_hexsha": "d593f5d16fd12dbc875b2ca539f5684bf69506cb", "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": "tst/FixedPointsTest.cpp", "max_forks_repo_name": "miracoli/FixedPointsArduino", "max_forks_repo_head_hexsha": "d593f5d16fd12dbc875b2ca539f5684bf69506cb", "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.5145228216, "max_line_length": 78, "alphanum_fraction": 0.6602322425, "num_tokens": 2295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5320388830967961}}
{"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_TRUNC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_TRUNC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-arithmetic\n    This function object computes the truncation toward @ref Zero\n    of its parameter.\n\n\n    @par Header <boost/simd/function/trunc.hpp>\n\n    @par Notes\n      - the call to `trunc(x)` is similar to `sign(x)*floor(abs(x))`\n\n      - For floating point number it is also one of the two ouputs of\n        the @ref modf function.\n        And we have:\n        @code\n          trunc(x) + frac(x) == x;\n        @endcode\n        except for nans\n\n    @par Decorators\n\n       - std_ for floating entries call std::trunc\n\n    @par Alias:\n\n       fix\n\n    @see abs, frac, floor, sign, modf, itrunc\n\n    @par Example:\n\n      @snippet trunc.cpp trunc\n\n    @par Possible output:\n\n      @snippet trunc.txt trunc\n\n  **/\n  Value trunc(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/trunc.hpp>\n#include <boost/simd/function/simd/trunc.hpp>\n\n#endif\n", "meta": {"hexsha": "f1e4f0f341c7bfc886c09ba8aa9c53ce3b70cc1c", "size": 1436, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/trunc.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/function/trunc.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/function/trunc.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": 22.0923076923, "max_line_length": 100, "alphanum_fraction": 0.5675487465, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5320360754277418}}
{"text": "/**\n * @author Tomas Polasek\n * @date 11.20.2019\n * @version 1.0\n * @brief Utilities and statistics for the treeio::Tree class.\n */\n\n#include \"TreeIOAccelerationUtils.h\"\n\n#include <Eigen/Eigen>\n\n#include <intersect/intersect.h>\n\nnamespace treeacc\n{\n\nLine Line::fromDirection(const Vector3D &origin, const Vector3D &direction)\n{ return Line{ origin, origin + direction }; }\n\nBoundingBox3D::BoundingBox3D() :\n    BoundingBox3D( Vector3D{ } )\n{ }\nBoundingBox3D::BoundingBox3D(const Vector3D &pos) :\n    BoundingBox3D(pos, pos)\n{ }\nBoundingBox3D::BoundingBox3D(const Vector3D &lv, const Vector3D &hv)\n{ min = lv; max = hv; }\n\nbool BoundingBox3D::intersects(const Ray &ray) const\n{ return intersection(ray) < std::numeric_limits<float>::max(); }\n\nfloat BoundingBox3D::intersection(const Ray &ray) const\n{\n    const auto tMinCorner{ (min - ray.origin) / ray.direction };\n    const auto tMaxCorner{ (max - ray.origin) / ray.direction };\n    const auto tMin{ Vector3D::elementMin(tMinCorner, tMaxCorner).max() };\n    const auto tMax{ Vector3D::elementMax(tMinCorner, tMaxCorner).min() };\n\n    return (tMax < 0.0f || tMin > tMax) ? std::numeric_limits<float>::max() : tMin;\n}\n\nfloat calculateTriangleArea(const Vector3D &p1, const Vector3D &p2, const Vector3D &p3)\n{\n    const auto a{ p2 - p1 };\n    const auto b{ p3 - p1 };\n\n    const auto prod{ Vector3D::crossProduct(a, b) };\n\n    return prod.length() / 2.0f;\n}\n\nfloat calculateTrianglePerimeter(const Vector3D &p1, const Vector3D &p2, const Vector3D &p3)\n{\n    const auto a{ p2 - p1 };\n    const auto b{ p3 - p1 };\n    const auto c{ p2 - p3 };\n\n    return a.length() + b.length() + c.length();\n}\n\nVector3D calculateTriangleMedianPoint(const Vector3D &p1, const Vector3D &p2, const Vector3D &p3)\n{ return (p1 + p2 + p3) / 3.0f; }\n\nfloat calculateTriangleMedian(const Vector3D &p1, const Vector3D &p2, const Vector3D &p3)\n{\n    const auto p1p2{ p1 + p2 / 2.0f };\n    return (p3 - p1p2).length();\n}\n\nfloat calculateTriangleLongestMedian(const Vector3D &p1, const Vector3D &p2, const Vector3D &p3)\n{\n    const auto m1{ calculateTriangleMedian(p1, p2, p3) };\n    const auto m2{ calculateTriangleMedian(p2, p3, p1) };\n    const auto m3{ calculateTriangleMedian(p1, p3, p2) };\n\n    return std::max<float>({ m1, m2, m3 });\n}\n\nVector3D sampleTriangle(const Vector3D &a1, const Vector3D &a2, const Vector3D &a3, const Vector3D &w)\n{\n    // TODO - Vector3D scalar multiplication + addition seems broken?\n    return {\n        w.x * a1.x + w.y * a2.x + w.z * a3.x,\n        w.x * a1.y + w.y * a2.y + w.z * a3.y,\n        w.x * a1.z + w.y * a2.z + w.z * a3.z\n    };\n}\n\n/**\n * Sample barycentric U coordinate using provided random value.\n * Source: Portsmouth, Jamie. \"Efficient barycentric point sampling on meshes.\"\n *\n * @param phiU Normalized relative weight for U-axis.\n * @param phiV Normalized relative weight for V-axis.\n * @param rand Random value used for sampling U coordinate.\n * @param limit Quality limit for inner loop.\n *\n * @return Returns sampled U coordinate.\n */\nfloat sampleBarycentricU(float phiU, float phiV, float rand, float limit = 5.0e-3)\n{\n    static constexpr auto MAX_ITERATIONS{ 20u };\n    static constexpr auto EPSILON{ std::numeric_limits<float>::epsilon() };\n    const auto l{ (2.0f * phiU - phiV) / 3.0f };\n    auto u{ 0.5f };\n    for (std::size_t iter = 0u; iter < MAX_ITERATIONS; ++iter)\n    {\n        const auto u1{ 1.0f - u };\n        const auto P{ u * (2.0f - u) - l * u * u1 * u1 - rand};\n        const auto Pd{ std::max<float>(u1 * (2.0f + l * (3.0f * u - 1.0f)), EPSILON)};\n        const auto du{ std::max<float>(std::min<float>(P / Pd, 0.25f), -0.25f) };\n\n        u -= du;\n        u = std::max<float>(std::min<float>(u, 1.0f - EPSILON), EPSILON);\n        if (std::fabs(du) < limit)\n        { break; }\n    }\n\n    return u;\n}\n\n/**\n * Sample barycentric V coordinate using provided random value.\n * Source: Portsmouth, Jamie. \"Efficient barycentric point sampling on meshes.\"\n *\n * @param u Previously sampled u coordinate.\n * @param phiU Normalized relative weight for U-axis.\n * @param phiV Normalized relative weight for V-axis.\n * @param rand Random value used for sampling V coordinate.\n *\n * @return Returns sampled V coordinate.\n */\nfloat sampleBarycentricV(float u, float phiU, float phiV, float rand)\n{\n    static constexpr auto EPSILON{ std::numeric_limits<float>::epsilon() };\n\n    if (std::fabs(phiV) < EPSILON)\n    { return (1.0f - u) * rand; }\n\n    const auto tau{ 1.0f / 3.0f - (1.0f + (u - 1.0f / 3.0f) * phiU) / phiV };\n    const auto tmp{ tau + u - 1.0f };\n    const auto q{ std::sqrt(tau * tau * (1.0f - rand) + tmp * tmp * rand) };\n\n    return tau <= 0.5f * (1.0f - u) ? tau + q : tau - q;\n}\n\nVector3D triangleWeights(const Vector3D &p1, const Vector3D &p2, const Vector3D &p3, const Vector3D &phi)\n{\n    /*\n     * Source: Portsmouth, Jamie. \"Efficient barycentric point sampling on meshes.\"\n     */\n\n    // Recover densities at each of the triangle vertices.\n    const auto phi1{ phi.x };\n    const auto phi2{ phi.y };\n    const auto phi3{ phi.z };\n    const auto averagePhi{ (phi1 + phi2 + phi3) / 3.0f};\n\n    // Transform absolute distances to normalized relative weights.\n    const auto relativePhi1{ (phi1 - phi3) / averagePhi };\n    const auto relativePhi2{ (phi2 - phi3) / averagePhi };\n\n    // Get independent random samples from uniform distribution.\n    const auto randU{ treeutil::uniformZeroToOne<float>() };\n    const auto randV{ treeutil::uniformZeroToOne<float>() };\n\n    // Sample barycentric coordinates.\n    const auto u{ sampleBarycentricU(relativePhi1, relativePhi2, randU) };\n    const auto v{ sampleBarycentricV(u, relativePhi1, relativePhi2, randV) };\n    const auto w{ 1.0f - u - v };\n\n    return { u, v, w };\n}\n\nVector3D uniformTriangleWeights(const Vector3D &p1, const Vector3D &p2, const Vector3D &p3)\n{ return triangleWeights(p1, p2, p3, { 1.0f, 1.0f, 1.0f }); }\n\nVector3D medianTriangleWeights(const Vector3D &p1, const Vector3D &p2, const Vector3D &p3)\n{\n    // Median - center of gravity of input triangle.\n    const auto median{ calculateTriangleMedianPoint(p1, p2, p3) };\n\n    // Calculate distances median <-> point.\n    const auto phi1{ (p1 - median).length() };\n    const auto phi2{ (p2 - median).length() };\n    const auto phi3{ (p3 - median).length() };\n\n    return triangleWeights(p1, p2, p3, { phi1, phi2, phi3 });\n}\n\nVertex3D uniformSampleTriangle(const Vertex3D &v1, const Vertex3D &v2, const Vertex3D &v3)\n{\n    const auto barycentricCoordinates{ uniformTriangleWeights(v1.p, v2.p, v3.p) };\n\n    const auto p{ sampleTriangle(v1.p, v2.p, v3.p, barycentricCoordinates) };\n    auto n{ sampleTriangle(v1.n, v2.n, v3.n, barycentricCoordinates) };\n    n.normalize();\n\n    return { p, n };\n}\n\nVertex3D uniformSampleTriangle(const Vertex3D &v1, const Vertex3D &v2, const Vertex3D &v3, const Vector3D &weights)\n{\n    const auto barycentricCoordinates{ triangleWeights(v1.p, v2.p, v3.p, weights) };\n\n    const auto p{ sampleTriangle(v1.p, v2.p, v3.p, barycentricCoordinates) };\n    auto n{ sampleTriangle(v1.n, v2.n, v3.n, barycentricCoordinates) };\n    n.normalize();\n\n    return { p, n };\n}\n\nVector3D middleSampleTriangle(const Vector3D &a1, const Vector3D &a2, const Vector3D &a3)\n{ return sampleTriangle(a1, a2, a3, Vector3D{ 1.0f / 3.0f, 1.0f / 3.0f, 1.0f / 3.0f }); }\n\nVector3D triangleNormal(const Vector3D &a1, const Vector3D &a2, const Vector3D &a3)\n{\n    const auto f{ a2 - a1 }; const auto s{ a3 - a1 };\n    return Vector3D{\n        f.y * s.z - f.z * s.y,\n        f.z * s.x - f.x * s.z,\n        f.x * s.y - f.y * s.x\n    };\n}\n\nTriangle::Triangle(std::size_t idx,\n    const treeio::ModelImporterBase::Vertex *vb,\n    const treeio::ModelImporterBase::IndexElementT *ib):\n    tIdx{ idx }\n{\n    const auto triangleBaseIndex{ idx * 3u };\n\n    i1 = ib[triangleBaseIndex + 0u];\n    i2 = ib[triangleBaseIndex + 1u];\n    i3 = ib[triangleBaseIndex + 2u];\n\n    v1 = modelVertexToCloudPoint(vb[i1]);\n    v2 = modelVertexToCloudPoint(vb[i2]);\n    v3 = modelVertexToCloudPoint(vb[i3]);\n    lv = Vector3D{\n        std::min<float>(std::min<float>(v1.x, v2.x), v3.x),\n        std::min<float>(std::min<float>(v1.y, v2.y), v3.y),\n        std::min<float>(std::min<float>(v1.z, v2.z), v3.z),\n    };\n    hv = Vector3D{\n        std::max<float>(std::max<float>(v1.x, v2.x), v3.x),\n        std::max<float>(std::max<float>(v1.y, v2.y), v3.y),\n        std::max<float>(std::max<float>(v1.z, v2.z), v3.z),\n    };\n    c = middleSampleTriangle(v1, v2, v3);\n\n    n1 = modelNormalToCloudNormal(vb[i1]);\n    n2 = modelNormalToCloudNormal(vb[i2]);\n    n3 = modelNormalToCloudNormal(vb[i3]);\n}\n\nfloat Triangle::centroidDistance(const Triangle &other) const\n{ return Vector3D::distance(c, other.c); }\n\nfloat Triangle::centroidSquaredDistance(const Triangle &other) const\n{ return Vector3D::squaredDistance(c, other.c); }\n\nfloat Triangle::centroidSquaredDistance(const Vector3D &point) const\n{ return Vector3D::squaredDistance(c, point); }\n\nbool Triangle::intersects(const Triangle &other) const\n{\n    // Vertices of this triangle:\n    double v11[3]{ v1.x, v1.y, v1.z };\n    double v12[3]{ v2.x, v2.y, v2.z };\n    double v13[3]{ v3.x, v3.y, v3.z };\n\n    // Vertices of the other triangle:\n    double v21[3]{ other.v1.x, other.v1.y, other.v1.z };\n    double v22[3]{ other.v2.x, other.v2.y, other.v2.z };\n    double v23[3]{ other.v3.x, other.v3.y, other.v3.z };\n\n    const auto result{ tri_tri_overlap_test_3d(\n        v11, v12, v13,\n        v21, v22, v23\n    ) };\n\n    return result != 0;\n}\n\nbool Triangle::intersects(const Ray &ray) const\n{ return intersection(ray) < std::numeric_limits<float>::max(); }\n\nfloat Triangle::intersection(const Ray &ray) const\n{\n    // Constants:\n    static constexpr auto EPSILON{ std::numeric_limits<float>::epsilon() };\n\n    // Moller Trumbore algorithm:\n    const auto edge1{ v2 - v1 };\n    const auto edge2{ v3 - v1 };\n    const auto cross{ Vector3D::crossProduct(ray.direction, edge2) };\n    const auto det{ Vector3D::dotProduct(edge1, cross) };\n\n    // Ray is parallel to the triangle.\n    /*\n    std::cout << \"v1: \" << v1 << \" v2: \" << v2 << \" v3: \" << v2 << std::endl;\n    std::cout << \"edg1: \" << edge1 << std::endl;\n    std::cout << \"edg2: \" << edge2 << std::endl;\n    std::cout << \"cross: \" << cross << std::endl;\n    std::cout << \"det: \" << det << std::endl;\n     */\n    if (std::abs<float>(det) < EPSILON)\n    { return std::numeric_limits<float>::max(); }\n\n    const auto invDet{ 1.0f / det };\n    const auto uVec{ ray.origin - v1 };\n    const auto vVec{ Vector3D::crossProduct(uVec, edge1) };\n\n    // Check intersection point is within triangle.\n    const auto u{ invDet * Vector3D::dotProduct(uVec, cross) };\n    //std::cout << \"u: \" << u << std::endl;\n    if (u < -EPSILON || u > 1.0f + EPSILON)\n    { return std::numeric_limits<float>::max(); }\n    const auto v{ invDet * Vector3D::dotProduct(ray.direction, vVec) };\n    //std::cout << \"v \" << v << std::endl;\n    if (v < -EPSILON || u + v > 1.0f + EPSILON)\n    { return std::numeric_limits<float>::max(); }\n\n    // Calculate intersection time.\n    const auto t{ invDet * Vector3D::dotProduct(edge2, vVec) };\n    return t;\n}\n\nbool Triangle::contains(const Vector3D &point, float epsilon) const\n{\n#if 0\n    /*\n     * Using volume of a tetrahedron v1, v2, v3, point:\n     *\n     * 1) Calculate volume.\n     * 2) Point is inside <-> volume < epsilon\n     */\n    return std::abs<float>(\n        Vector3D::dotProduct(\n            v1 - point,\n            Vector3D::crossProduct(v2 - point, v3 - point)\n        )\n    ) < epsilon;\n\n#else\n\n    /*\n     * Using barycentric coordinates:\n     *\n     * 1) Project point onto the triangle plane and get its distance -> distance.\n     * 2) Calculate barycentrics on the 2D plane -> alpha, beta.\n     * 3) Point is inside <-> distance < epsilon && alpha > -epsilon && beta > -epsilon && alpha + beta <= 1 + epsilon\n     */\n\n    const auto pn{ centralPlaneNormal() };\n    const auto distance{ Vector3D::dotProduct(pn, point) };\n    const auto projected{ pn * distance };\n\n    const auto s2{ v2 - v1 };\n    const auto s3{ v3 - v1 };\n    const auto sp{ point - v1 };\n\n    const auto d2p{ Vector3D::dotProduct(s2, sp) };\n    const auto d3p{ Vector3D::dotProduct(s2, sp) };\n    const auto dsh{ Vector3D::dotProduct(s2, s3) };\n    const auto s2l{ s2.length() };\n    const auto s3l{ s3.length() };\n    // Normalize for alpha and beta to be 1.0 when reaching v2 and v3 respectively.\n    const auto normalizer{ 1.0f / (d2p * d3p - dsh * dsh) };\n    // Alpha represents distance along s2.\n    const auto alpha{ (d2p * s3l - dsh * d3p) * normalizer };\n    const auto beta{ (d3p * s2l - dsh * d2p) * normalizer };\n\n    return alpha > -epsilon && beta > -epsilon && alpha + beta <= 1.0f + epsilon;\n#endif\n}\n\nVector3D Triangle::barycentrics(const Vector3D &point) const\n{\n    // Source: https://en.wikipedia.org/wiki/Barycentric_coordinate_system#Conversion_between_barycentric_and_Cartesian_coordinates\n    const auto &p{ point };\n    const auto b1{\n        ((v2.y - v3.y) * (p.x - v3.x) + (v3.x - v2.x) * (p.y - v3.y)) /\n        ((v2.y - v3.y) * (v1.x - v3.x) + (v3.x - v2.x) * (v1.y - v3.y))\n    };\n    const auto b2{\n        ((v3.y - v1.y) * (p.x - v3.x) + (v1.x - v3.x) * (p.y - v3.y)) /\n        ((v2.y - v3.y) * (v1.x - v3.x) + (v3.x - v2.x) * (v1.y - v3.y))\n    };\n    const auto b3{ 1.0f - b1 - b2 };\n\n    return { b1, b2, b3 };\n}\n\nBoundingBox3D Triangle::aabb() const\n{ return BoundingBox3D(lv, hv); }\n\nfloat Triangle::area() const\n{ return calculateTriangleArea(v1, v2, v3); }\n\nfloat Triangle::perimeter() const\n{ return calculateTrianglePerimeter(v1, v2, v3); }\n\nfloat Triangle::longestAltitude() const\n{ return calculateTriangleLongestMedian(v1, v2, v3); }\n\nVector3D Triangle::centralPlaneNormal() const\n{\n    /*\n     * Use cross product of two sides:\n     *    3\n     *  /   \\\n     * 1 --- 2\n     * Counter clock-wise -> front-face.\n     * normal = cross(1->2, 1->3)\n     */\n    const auto c1{ v2 - v1 };\n    const auto c2{ v3 - v1 };\n    auto planeNormal{ Vector3D::crossProduct(c1, c2) };\n    planeNormal.normalize();\n\n    return planeNormal;\n}\n\nvoid Triangle::providePlaneNormals(const Vector3D &pNormal1, const Vector3D &pNormal2, const Vector3D &pNormal3)\n{\n    providedPlaneNormals = true;\n\n    pn1 = pNormal1;\n    pn2 = pNormal2;\n    pn3 = pNormal3;\n\n    const auto l1{ Line::fromDirection(v1, pn1) };\n    const auto l2{ Line::fromDirection(v2, pn2) };\n    const auto l3{ Line::fromDirection(v3, pn3) };\n\n    const auto i12{ lsIntersect({ l1, l2 }) };\n    const auto i13{ lsIntersect({ l1, l3 }) };\n    const auto i23{ lsIntersect({ l2, l3 }) };\n\n    //d12 = Vector3D::distance(v1 + (v2 - v1) * Vector3D::dotProduct((v2 - v1), (i12 - v1)), i12);\n    //d13 = Vector3D::distance(v1 + (v3 - v1) * Vector3D::dotProduct((v3 - v1), (i13 - v1)), i13);\n    //d23 = Vector3D::distance(v2 + (v3 - v2) * Vector3D::dotProduct((v3 - v2), (i23 - v2)), i13);\n\n    pr12 = (Vector3D::distance(i12, v1) + Vector3D::distance(i12, v2)) / 2.0f;\n    pr13 = (Vector3D::distance(i13, v1) + Vector3D::distance(i13, v3)) / 2.0f;\n    pr23 = (Vector3D::distance(i23, v2) + Vector3D::distance(i23, v3)) / 2.0f;\n}\n\nVector3D Triangle::smoothPoint(const Vector3D &point) const\n{\n    if (!providedPlaneNormals)\n    { return point; }\n\n    const auto bary{ barycentrics(point) };\n    const auto shiftedBary{ bary - Vector3D{ 0.5f, 0.5f, 0.5f } };\n    const auto radiusWeights{ Vector3D{ 1.0f, 1.0f, 1.0f } - 4.0f * (shiftedBary * shiftedBary) };\n\n    return point + centralPlaneNormal() * radiusWeights * Vector3D{ pr12, pr13, pr23 };\n}\n\nfloat Triangle::curvature() const\n{\n    // TODO - Better curvature metric?\n    return (Vector3D::dotProduct(pn1, pn2) + Vector3D::dotProduct(pn2, pn3) + Vector3D::dotProduct(pn3, pn1)) / 3.0f;\n}\n\nVector3D Triangle::curvatureWeights() const\n{\n    const auto cpn{ centralPlaneNormal() };\n\n    // Calculate weights as offset from central plane normal.\n    const auto w1{ std::abs(Vector3D::dotProduct(cpn, pn1)) };\n    const auto w2{ std::abs(Vector3D::dotProduct(cpn, pn2)) };\n    const auto w3{ std::abs(Vector3D::dotProduct(cpn, pn3)) };\n\n    // Fallback to uniform if we don't have valid values.\n    const auto weightSum{ w1 + w2 + w3};\n    if (weightSum <= std::numeric_limits<float>::epsilon() || !std::isfinite(weightSum))\n    { return { 1.0f / 3.0f, 1.0f / 3.0f, 1.0f / 3.0f }; }\n\n    // Normalize weights to be in <0.0f, 1.0f> and sum to 1.0f .\n    const auto normalizer{ 1.0f / (w1 + w2 + w3) };\n    return { w1 * normalizer, w2 * normalizer, w3 * normalizer };\n}\n\nfloat Triangle::longestSide() const\n{\n    return std::max<float>(\n        std::max<float>(\n            v1.length(),\n            v2.length()),\n        v3.length()\n    );\n}\n\nVector3D lsIntersect(const std::vector<Line> &lines)\n{\n    // Initialize accumulation variables:\n\n    // Coefficients of the left sides.\n    Eigen::Matrix3f A{ Eigen::Matrix3f::Zero() };\n    // Coefficients of the right sides.\n    Eigen::Vector3f b{ Eigen::Vector3f::Zero() };\n    // Constants.\n    float c{ 0.0f };\n\n    //std::cout << \"Starting lsIntersect...\" << std::endl;\n\n    // Populate the coefficient matrices:\n    for (const auto &line : lines)\n    { // Process each line in turn.\n        // Recover points on the line.\n        const Eigen::Vector3f v{ line.v.x, line.v.y, line.v.z };\n        const Eigen::Vector3f w{ line.w.x, line.w.y, line.w.z };\n\n        //std::cout << \"Adding line: \" << v.transpose() << \" -> \" << w.transpose() << std::endl;\n\n        // Calculate line direction.\n        const Eigen::Vector3f u{ (v - w).normalized() };\n        const Eigen::Vector3f ut{ u.transpose() };\n\n        // Calculate projection to hyper-plane orthogonal to this line.\n        Eigen::Matrix3f kroneckerProduct{ };\n        kroneckerProduct <<\n                         u(0) * ut(0), u(0) * ut(1), u(0) * ut(2),\n            u(1) * ut(0), u(1) * ut(1), u(1) * ut(2),\n            u(2) * ut(0), u(2) * ut(1), u(2) * ut(2);\n        const Eigen::Matrix3f projection{ Eigen::Matrix3f::Identity() - kroneckerProduct };\n\n        // Calculate distance of our line to the projection plane.\n        const Eigen::Vector3f p{ projection * w };\n\n        // Populate coefficients of the least-squares system of equations.\n        A += projection;\n        b += p;\n        c += p(0) * p(0) + p(1) * p(1) + p(2) * p(2);\n    }\n\n    // Solve least-squares problem.\n    //const Eigen::Vector3f result{ A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b) };\n    const Eigen::Vector3f result{ A.bdcSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).solve(b) };\n\n    //std::cout << \"LS intersection result: \" << result.transpose() << std::endl;\n\n    return { result(0), result(1), result(2) };\n}\n\nVector3D lsIntersect(std::initializer_list<Line> lines)\n{ return lsIntersect({ lines.begin(), lines.end() }); }\n\n} // namespace treeacc\n", "meta": {"hexsha": "032d3e11d3611c654427208707d793fecbd04c8e", "size": 18798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TreeIOAcceleration/src/TreeIO/impl/TreeIOAccelerationUtils.cpp", "max_stars_repo_name": "PolasekT/ICTree", "max_stars_repo_head_hexsha": "d13ad603101805bcc288411504ecffd6f2e1f365", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-09T22:37:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T13:40:44.000Z", "max_issues_repo_path": "TreeIOAcceleration/src/TreeIO/impl/TreeIOAccelerationUtils.cpp", "max_issues_repo_name": "PolasekT/ICTree", "max_issues_repo_head_hexsha": "d13ad603101805bcc288411504ecffd6f2e1f365", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TreeIOAcceleration/src/TreeIO/impl/TreeIOAccelerationUtils.cpp", "max_forks_repo_name": "PolasekT/ICTree", "max_forks_repo_head_hexsha": "d13ad603101805bcc288411504ecffd6f2e1f365", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-09T22:37:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T14:38:39.000Z", "avg_line_length": 33.9314079422, "max_line_length": 131, "alphanum_fraction": 0.6250664964, "num_tokens": 6047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5320360705013996}}
{"text": "/***********************************************************************************************************************\n *  OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n *  following conditions are met:\n *\n *  (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n *  disclaimer.\n *\n *  (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n *  following disclaimer in the documentation and/or other materials provided with the distribution.\n *\n *  (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote\n *  products derived from this software without specific prior written permission from the respective party.\n *\n *  (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative\n *  works may not use the \"OpenStudio\" trademark, \"OS\", \"os\", or any other confusingly similar designation without\n *  specific prior written permission from Alliance for Sustainable Energy, LLC.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR\n *  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n *  PROCUREMENT OF SUBSTITUTE 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 NEGLIGENCE OR OTHERWISE)\n *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **********************************************************************************************************************/\n\n#ifndef UTILITIES_GEOMETRY_VECTOR3D_HPP\n#define UTILITIES_GEOMETRY_VECTOR3D_HPP\n\n#include \"../UtilitiesAPI.hpp\"\n#include \"../data/Vector.hpp\"\n#include \"../core/Logger.hpp\"\n\n#include <vector>\n#include <boost/optional.hpp>\n\nnamespace openstudio{\n\n  class UTILITIES_API Vector3d{\n  public:\n\n    /// default constructor creates vector with 0, 0, 0\n    Vector3d();\n\n    /// constructor with x, y, z\n    Vector3d(double x, double y, double z);\n\n    /// copy constructor\n    Vector3d(const Vector3d& other);\n\n    /// get x\n    double x() const;\n\n    /// get y\n    double y() const;\n\n    /// get z\n    double z() const;\n\n    /// addition\n    Vector3d operator+(const Vector3d& other) const;\n\n    /// addition\n    Vector3d& operator+=(const Vector3d& other);\n\n    /// subtraction\n    Vector3d operator-(const Vector3d& other) const;\n\n    /// subtraction\n    Vector3d& operator-=(const Vector3d& other);\n\n    /// check equality\n    bool operator==(const Vector3d& other) const;\n\n    /// normalize to one\n    bool normalize();\n\n    /// get a vector which is the reverse of this\n    Vector3d reverseVector() const;\n\n    /// get length\n    double length() const;\n\n    /// set length\n    bool setLength(double newLength);\n\n    /// dot product with another Vector3d\n    double dot(const Vector3d& other) const;\n\n    /// cross product with another Vector3d\n    Vector3d cross(const Vector3d& other) const;\n\n    /// get the Vector directly\n    Vector vector() const;\n\n  private:\n\n    REGISTER_LOGGER(\"utilities.Vector3d\");\n\n    Vector m_storage;\n\n  };\n\n  /// ostream operator\n  UTILITIES_API std::ostream& operator<<(std::ostream& os, const Vector3d& vec);\n\n  /// ostream operator\n  UTILITIES_API std::ostream& operator<<(std::ostream& os, const std::vector<Vector3d>& vecVector);\n\n  /// negation\n  UTILITIES_API Vector3d operator-(const Vector3d& vec);\n\n  /// multiplication by a scalar\n  UTILITIES_API Vector3d operator*(double mult, const Vector3d& vec);\n\n  // optional Vector3d\n  typedef boost::optional<Vector3d> OptionalVector3d;\n\n  // vector of Vector3d\n  typedef std::vector<Vector3d> Vector3dVector;\n\n} // openstudio\n\n#endif //UTILITIES_GEOMETRY_VECTOR3D_HPP\n", "meta": {"hexsha": "4fa63516a360b2e3e03d355aa3519f661a83c64d", "size": 4377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/geometry/Vector3d.hpp", "max_stars_repo_name": "OpenStudioThailand/OpenStudio", "max_stars_repo_head_hexsha": "4e2173955e687ef1b934904acc10939ac0bed52f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T09:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T09:23:04.000Z", "max_issues_repo_path": "openstudiocore/src/utilities/geometry/Vector3d.hpp", "max_issues_repo_name": "OpenStudioThailand/OpenStudio", "max_issues_repo_head_hexsha": "4e2173955e687ef1b934904acc10939ac0bed52f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openstudiocore/src/utilities/geometry/Vector3d.hpp", "max_forks_repo_name": "OpenStudioThailand/OpenStudio", "max_forks_repo_head_hexsha": "4e2173955e687ef1b934904acc10939ac0bed52f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-20T13:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T13:19:42.000Z", "avg_line_length": 34.4645669291, "max_line_length": 120, "alphanum_fraction": 0.6842586246, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5320360632661417}}
{"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 <utility>\n#include <cmath>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace std;  \n   \ntemplate <typename Matrix>\nvoid init(Matrix& A)\n{    \n    A= 0.0;\n    mtl::mat::inserter<Matrix>  ins(A);\n    \n    ins[0][1] << 3;  ins[1][4] << 7; ins[0][0] << 1; ins[4][4] << 17;\n    ins[2][3] << -2; ins[2][4] << 5; ins[4][0] << 2; ins[4][1] <<  3;\n    ins[3][2] << 4;\n}\n\n\ntemplate <typename Coll>\nvoid test(Coll& coll, const char* name)\n{\n    cout << \"\\n\" << name << \" =\\n\" << coll << \"\\n\";\n    \n    Coll E(coll), F(coll); F=0;\n    E= hessenberg(coll);\n    F=tril(E,-2);\n    std::cout<< \"Hessenberg=\\n\" << E << \"\\n\";\n    std::cout<< \"triu=\\n\" << F << \"\\n\";\n  \n    MTL_THROW_IF(one_norm(F)>0.000004, mtl::runtime_error(\"No Hessenberg-Form\"));\n    F=extract_householder_hessenberg(coll);\n    std::cout<< \"extract_householder_hessenberg=\\n\" << F << \"\\n\";\n    F=extract_hessenberg(coll);\n    std::cout<< \"extract_hessenberg=\\n\" << F << \"\\n\";\n    F=householder_hessenberg(coll);\n    std::cout<< \"householder_hessenberg=\\n\" << F << \"\\n\";\n    F=hessenberg_factors(coll);\n    std::cout<< \"hessenberg_factors=\\n\" << F << \"\\n\";\n    //      F=hessenberg_q(coll);\n    //      std::cout<< \"hessenberg_q=\\n\" << F << \"\\n\";\n}\n \n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    dense2D<double>       A(5, 5);\n    init(A);\n    compressed2D<double>  B(5, 5);\n    init(B);\n\n    test(A, \"dense matrix\");\n//      test(B, \"sparse matrix\");  // TODO sparse Form\n\n    return 0;\n}\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "d65e738fe9e1dadb739c24714cd7251632008e65", "size": 1945, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/hessenberg_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/hessenberg_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/hessenberg_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.6162790698, "max_line_length": 94, "alphanum_fraction": 0.5758354756, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5320360583397994}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\r\n/*\r\n    This example program shows you how to create your own custom binary classification\r\n    trainer object and use it with the multiclass classification tools in the dlib C++\r\n    library.  This example assumes you have already become familiar with the concepts\r\n    introduced in the multiclass_classification_ex.cpp example program.\r\n\r\n\r\n    In this example we will create a very simple trainer object that takes a binary\r\n    classification problem and produces a decision rule which says a test point has the\r\n    same class as whichever centroid it is closest to.  \r\n\r\n    The multiclass training dataset will consist of four classes.  Each class will be a blob \r\n    of points in one of the quadrants of the cartesian plane.   For fun, we will use \r\n    std::string labels and therefore the labels of these classes will be the following:\r\n        \"upper_left\",\r\n        \"upper_right\",\r\n        \"lower_left\",\r\n        \"lower_right\"\r\n*/\r\n\r\n#include <dlib/svm_threaded.h>\r\n\r\n#include <iostream>\r\n#include <vector>\r\n\r\n#include <dlib/rand.h>\r\n\r\nusing namespace std;\r\nusing namespace dlib;\r\n\r\n// Our data will be 2-dimensional data. So declare an appropriate type to contain these points.\r\ntypedef matrix<double,2,1> sample_type;\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nstruct custom_decision_function\r\n{\r\n    /*!\r\n        WHAT THIS OBJECT REPRESENTS\r\n            This object is the representation of our binary decision rule.  \r\n    !*/\r\n\r\n    // centers of the two classes\r\n    sample_type positive_center, negative_center;\r\n\r\n    double operator() (\r\n        const sample_type& x\r\n    ) const\r\n    {\r\n        // if x is closer to the positive class then return +1 \r\n        if (length(positive_center - x) < length(negative_center - x))\r\n            return +1;\r\n        else\r\n            return -1;\r\n    }\r\n};\r\n\r\n// Later on in this example we will save our decision functions to disk.  This\r\n// pair of routines is needed for this functionality.\r\nvoid serialize (const custom_decision_function& item, std::ostream& out)\r\n{\r\n    // write the state of item to the output stream\r\n    serialize(item.positive_center, out);\r\n    serialize(item.negative_center, out);\r\n}\r\n\r\nvoid deserialize (custom_decision_function& item, std::istream& in)\r\n{\r\n    // read the data from the input stream and store it in item\r\n    deserialize(item.positive_center, in);\r\n    deserialize(item.negative_center, in);\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nclass simple_custom_trainer\r\n{\r\n    /*!\r\n        WHAT THIS OBJECT REPRESENTS\r\n            This is our example custom binary classifier trainer object.  It simply \r\n            computes the means of the +1 and -1 classes, puts them into our \r\n            custom_decision_function, and returns the results.\r\n\r\n            Below we define the train() function.  I have also included the\r\n            requires/ensures definition for a generic binary classifier's train()\r\n    !*/\r\npublic:\r\n\r\n\r\n    custom_decision_function train (\r\n        const std::vector<sample_type>& samples,\r\n        const std::vector<double>& labels\r\n    ) const\r\n    /*!\r\n        requires\r\n            - is_binary_classification_problem(samples, labels) == true\r\n              (e.g. labels consists of only +1 and -1 values, samples.size() == labels.size())\r\n        ensures\r\n            - returns a decision function F with the following properties:\r\n                - if (new_x is a sample predicted have +1 label) then\r\n                    - F(new_x) >= 0\r\n                - else\r\n                    - F(new_x) < 0\r\n    !*/\r\n    {\r\n        sample_type positive_center, negative_center;\r\n\r\n        // compute sums of each class \r\n        positive_center = 0;\r\n        negative_center = 0;\r\n        for (unsigned long i = 0; i < samples.size(); ++i)\r\n        {\r\n            if (labels[i] == +1)\r\n                positive_center += samples[i];\r\n            else // this is a -1 sample\r\n                negative_center += samples[i];\r\n        }\r\n\r\n        // divide by number of +1 samples\r\n        positive_center /= sum(mat(labels) == +1);\r\n        // divide by number of -1 samples\r\n        negative_center /= sum(mat(labels) == -1);\r\n\r\n        custom_decision_function df;\r\n        df.positive_center = positive_center;\r\n        df.negative_center = negative_center;\r\n\r\n        return df;\r\n    }\r\n};\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nvoid generate_data (\r\n    std::vector<sample_type>& samples,\r\n    std::vector<string>& labels\r\n);\r\n/*!\r\n    ensures\r\n        - make some four class data as described above.  \r\n        - each class will have 50 samples in it\r\n!*/\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    std::vector<sample_type> samples;\r\n    std::vector<string> labels;\r\n\r\n    // First, get our labeled set of training data\r\n    generate_data(samples, labels);\r\n\r\n    cout << \"samples.size(): \"<< samples.size() << endl;\r\n\r\n    // Define the trainer we will use.  The second template argument specifies the type\r\n    // of label used, which is string in this case.\r\n    typedef one_vs_one_trainer<any_trainer<sample_type>, string> ovo_trainer;\r\n\r\n\r\n    ovo_trainer trainer;\r\n\r\n    // Now tell the one_vs_one_trainer that, by default, it should use the simple_custom_trainer\r\n    // to solve the individual binary classification subproblems.\r\n    trainer.set_trainer(simple_custom_trainer());\r\n\r\n    // Next, to make things a little more interesting, we will setup the one_vs_one_trainer\r\n    // to use kernel ridge regression to solve the upper_left vs lower_right binary classification\r\n    // subproblem.  \r\n    typedef radial_basis_kernel<sample_type> rbf_kernel;\r\n    krr_trainer<rbf_kernel> rbf_trainer;\r\n    rbf_trainer.set_kernel(rbf_kernel(0.1));\r\n    trainer.set_trainer(rbf_trainer, \"upper_left\", \"lower_right\");\r\n\r\n\r\n    // Now let's do 5-fold cross-validation using the one_vs_one_trainer we just setup.\r\n    // As an aside, always shuffle the order of the samples before doing cross validation.  \r\n    // For a discussion of why this is a good idea see the svm_ex.cpp example.\r\n    randomize_samples(samples, labels);\r\n    cout << \"cross validation: \\n\" << cross_validate_multiclass_trainer(trainer, samples, labels, 5) << endl;\r\n    // This dataset is very easy and everything is correctly classified.  Therefore, the output of \r\n    // cross validation is the following confusion matrix.\r\n    /*\r\n        50  0  0  0 \r\n         0 50  0  0 \r\n         0  0 50  0 \r\n         0  0  0 50 \r\n    */\r\n\r\n\r\n    // We can also obtain the decision rule as always.\r\n    one_vs_one_decision_function<ovo_trainer> df = trainer.train(samples, labels);\r\n\r\n    cout << \"predicted label: \"<< df(samples[0])  << \", true label: \"<< labels[0] << endl;\r\n    cout << \"predicted label: \"<< df(samples[90]) << \", true label: \"<< labels[90] << endl;\r\n    // The output is:\r\n    /*\r\n        predicted label: upper_right, true label: upper_right\r\n        predicted label: lower_left, true label: lower_left\r\n    */\r\n\r\n\r\n    // Finally, let's save our multiclass decision rule to disk.  Remember that we have\r\n    // to specify the types of binary decision function used inside the one_vs_one_decision_function.\r\n    one_vs_one_decision_function<ovo_trainer, \r\n            custom_decision_function,                             // This is the output of the simple_custom_trainer \r\n            decision_function<radial_basis_kernel<sample_type> >  // This is the output of the rbf_trainer\r\n        > df2, df3;\r\n\r\n    df2 = df;\r\n    // save to a file called df.dat\r\n    serialize(\"df.dat\") << df2;\r\n\r\n    // load the function back in from disk and store it in df3.  \r\n    deserialize(\"df.dat\") >> df3;\r\n\r\n\r\n    // Test df3 to see that this worked.\r\n    cout << endl;\r\n    cout << \"predicted label: \"<< df3(samples[0])  << \", true label: \"<< labels[0] << endl;\r\n    cout << \"predicted label: \"<< df3(samples[90]) << \", true label: \"<< labels[90] << endl;\r\n    // Test df3 on the samples and labels and print the confusion matrix.\r\n    cout << \"test deserialized function: \\n\" << test_multiclass_decision_function(df3, samples, labels) << endl;\r\n\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nvoid generate_data (\r\n    std::vector<sample_type>& samples,\r\n    std::vector<string>& labels\r\n)\r\n{\r\n    const long num = 50;\r\n\r\n    sample_type m;\r\n\r\n    dlib::rand rnd;\r\n\r\n\r\n    // add some points in the upper right quadrant\r\n    m = 10, 10;\r\n    for (long i = 0; i < num; ++i)\r\n    {\r\n        samples.push_back(m + randm(2,1,rnd));\r\n        labels.push_back(\"upper_right\");\r\n    }\r\n\r\n    // add some points in the upper left quadrant\r\n    m = -10, 10;\r\n    for (long i = 0; i < num; ++i)\r\n    {\r\n        samples.push_back(m + randm(2,1,rnd));\r\n        labels.push_back(\"upper_left\");\r\n    }\r\n\r\n    // add some points in the lower right quadrant\r\n    m = 10, -10;\r\n    for (long i = 0; i < num; ++i)\r\n    {\r\n        samples.push_back(m + randm(2,1,rnd));\r\n        labels.push_back(\"lower_right\");\r\n    }\r\n\r\n    // add some points in the lower left quadrant\r\n    m = -10, -10;\r\n    for (long i = 0; i < num; ++i)\r\n    {\r\n        samples.push_back(m + randm(2,1,rnd));\r\n        labels.push_back(\"lower_left\");\r\n    }\r\n\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n", "meta": {"hexsha": "4a515fcae25b98b735f6cf5caeb5a4fd6a2b83f5", "size": 9616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/custom_trainer_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/custom_trainer_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/custom_trainer_ex.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5899280576, "max_line_length": 118, "alphanum_fraction": 0.5893302829, "num_tokens": 2125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435030872968, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5320360570310861}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2018 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/distance_functions.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Clock.h>\n#include <gudhi/Points_off_io.h>\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <limits>  // for numeric limits\n#include <fstream>\n#include <cassert>\n\n\nstd::ofstream results_csv(\"results.csv\");\n\ntemplate< typename Adjacency_list, typename ForwardPointRange, typename Distance >\nAdjacency_list proximity_graph_computation(const ForwardPointRange& points, double threshold, Distance distance) {\n  std::vector<std::pair< int, int >> edges;\n  std::vector< double > edges_fil;\n  std::map< int, double > vertices;\n\n  int idx_u, idx_v;\n  double fil;\n  idx_u = 0;\n  for (auto it_u = points.begin(); it_u != points.end(); ++it_u) {\n    idx_v = idx_u + 1;\n    for (auto it_v = it_u + 1; it_v != points.end(); ++it_v, ++idx_v) {\n      fil = distance(*it_u, *it_v);\n      if (fil <= threshold) {\n        edges.emplace_back(idx_u, idx_v);\n        edges_fil.push_back(fil);\n      }\n    }\n    ++idx_u;\n  }\n\n  // Points are labeled from 0 to idx_u-1\n  Adjacency_list skel_graph(edges.begin(), edges.end(), edges_fil.begin(), idx_u);\n\n  auto vertex_prop = boost::get(Gudhi::vertex_filtration_t(), skel_graph);\n\n  typename boost::graph_traits<Adjacency_list>::vertex_iterator vi, vi_end;\n  for (std::tie(vi, vi_end) = boost::vertices(skel_graph);\n       vi != vi_end; ++vi) {\n    boost::put(vertex_prop, *vi, 0.);\n  }\n\n  return skel_graph;\n}\n\ntemplate <typename Adjacency_list>\nvoid benchmark_proximity_graph(const std::string& msg, const std::string& off_file_name) {\n  Gudhi::Points_off_reader<std::vector<double>> off_reader(off_file_name);\n  assert(off_reader.is_valid());\n\n  std::cout << \"+ \" << msg << std::endl;\n\n  results_csv << \"\\\"nb_points\\\";\"\n              << \"\\\"nb_simplices\\\";\"\n              << \"\\\"compute proximity graph(sec.)\\\";\"\n              << \"\\\"complex_creation_time(sec.)\\\";\"\n              << \"\\\"\" << msg << \"\\\";\" << std::endl;\n\n  Gudhi::Clock pg_compute_proximity_graph(\"    benchmark_proximity_graph - compute proximity graph\");\n  pg_compute_proximity_graph.begin();\n  // benchmark begin\n  Adjacency_list proximity_graph = proximity_graph_computation<Adjacency_list>(off_reader.get_point_cloud(),\n                                                                               std::numeric_limits<double>::infinity(),\n                                                                               Gudhi::Euclidean_distance());\n  // benchmark end\n  pg_compute_proximity_graph.end();\n  std::cout << pg_compute_proximity_graph;\n\n  Gudhi::Simplex_tree<> complex;\n  Gudhi::Clock st_create_clock(\"    benchmark_proximity_graph - complex creation\");\n  st_create_clock.begin();\n  // benchmark begin\n  complex.insert_graph(proximity_graph);\n  // benchmark end\n  st_create_clock.end();\n  std::cout << st_create_clock;\n\n  results_csv << off_reader.get_point_cloud().size() << \";\" << complex.num_simplices() << \";\"\n              << pg_compute_proximity_graph.num_seconds() << \";\"\n              << st_create_clock.num_seconds() << \";\" << std::endl;\n\n  std::cout << \"    benchmark_proximity_graph - nb simplices = \" << complex.num_simplices() << std::endl;\n}\n\nint main(int argc, char * const argv[]) {\n  std::string off_file_name(argv[1]);\n\n  // The fastest, the less memory used\n  using vecSdirectedS = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,\n                                              boost::property<Gudhi::vertex_filtration_t, double>,\n                                              boost::property<Gudhi::edge_filtration_t, double>>;\n  benchmark_proximity_graph<vecSdirectedS>(\"vecSdirectedS\", off_file_name);\n\n  using vecSundirectedS = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n                                                boost::property<Gudhi::vertex_filtration_t, double>,\n                                                boost::property<Gudhi::edge_filtration_t, double>>;\n  benchmark_proximity_graph<vecSundirectedS>(\"vecSundirectedS\", off_file_name);\n\n  using vecSbidirectionalS = boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS,\n                                                   boost::property<Gudhi::vertex_filtration_t, double>,\n                                                   boost::property<Gudhi::edge_filtration_t, double>>;\n  benchmark_proximity_graph<vecSbidirectionalS>(\"vecSbidirectionalS\", off_file_name);\n\n  using setSdirectedS = boost::adjacency_list<boost::setS, boost::vecS, boost::directedS,\n                                              boost::property<Gudhi::vertex_filtration_t, double>,\n                                              boost::property<Gudhi::edge_filtration_t, double>>;\n  benchmark_proximity_graph<setSdirectedS>(\"setSdirectedS\", off_file_name);\n\n  using setSundirectedS = boost::adjacency_list<boost::setS, boost::vecS, boost::undirectedS,\n                                                boost::property<Gudhi::vertex_filtration_t, double>,\n                                                boost::property<Gudhi::edge_filtration_t, double>>;\n  benchmark_proximity_graph<setSundirectedS>(\"setSundirectedS\", off_file_name);\n\n  using setSbidirectionalS = boost::adjacency_list<boost::setS, boost::vecS, boost::bidirectionalS,\n                                                   boost::property<Gudhi::vertex_filtration_t, double>,\n                                                   boost::property<Gudhi::edge_filtration_t, double>>;\n  benchmark_proximity_graph<setSbidirectionalS>(\"setSbidirectionalS\", off_file_name);\n\n  return 0;\n}\n", "meta": {"hexsha": "0fc145fd40299fd3d6621777a1f23ffa9606ca27", "size": 6010, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common/benchmark/Graph_simplicial_complex_benchmark.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/common/benchmark/Graph_simplicial_complex_benchmark.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/common/benchmark/Graph_simplicial_complex_benchmark.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": 43.2374100719, "max_line_length": 119, "alphanum_fraction": 0.6282861897, "num_tokens": 1428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5320360560308834}}
{"text": "#ifndef SHASTA_APPROXIMATE_COLORING_HPP\n#define SHASTA_APPROXIMATE_COLORING_HPP\n\n/*******************************************************************************\n\nApproximate coloring of a Boost undirected graph using the Dsatur algorithm.\n\nSee this Wikipedia article for greedy coloring in general:\nhttps://en.wikipedia.org/wiki/Greedy_coloring\n\nThis code uses the Brelaz (1979) Dsatur\nalgorithm described there in this section\nhttps://en.wikipedia.org/wiki/Greedy_coloring#Adaptive\n\nThe main Wikipedia article for this algorithm is here:\nhttps://en.wikipedia.org/wiki/DSatur\n\nThe Dsatur algorithm was ingtroduced in this paper:\nBrelaz, Daniel (April 1979),\n\"New methods to color the vertices of a graph\",\nCommunications of the ACM, 22 (4): 251\u2013256, doi:10.1145/359094.359101\n\nMany alternative approximate coloring methods are also available, for example\nhttps://www.gerad.ca/~alainh/RLFPaper.pdf\n\nFor a partial coloring of a graph, the Dsatur algorithm defines\nthe saturation degree of a vertex as the number of distinct colors\nto which the vertex is adjacent (only counting, of course,\nvertices that have already been colored).\nWith this definition, the Dsatur algorithm is simply described\nas follows:\n\n- Starting with the uncolored graph, iterate over vertices in the order\n  defined below.\n- At each iteration, assign to each vertex the lowest possible color.\n  This is the lowest color that the vertex is not adjacent to.\n- At each iteration choose the vertex with maximum saturation degree\n  (maximum number of adjacent colors). In case of ties, break\n  the ties by selecting the vertex with maximum degree in the uncolored\n  subgraph - that is, the vertex with the greatest number of uncolored\n  adjacent vertices.\n\nThe DSatur algorithm is an approximate coloring algorithm, but it\nis exact for 2-colorable graphs.\n\nThis function applies the above algorithm to a Boost undirected graph.\nIt assumes that the graph is defined as a\nboost::adjacency_list<\n    OutEdgeList,\n    VertexList,\n    Directed,\n    VertexProperties, EdgeProperties, GraphProperties,\n    EdgeList>\nwith:\n\n- VertexList = boost::vecS (so vertex descriptors are integers starting at zero).\n- Directed = boost::undirectedS.\n\nIt returns the computed coloring in its second argument, indexed\nby vertex_descriptor.\n\n*******************************************************************************/\n\n// Shasta.\n#include \"SHASTA_ASSERT.hpp\"\n\n// Boost libraries.\n#include <boost/container/flat_set.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/iteration_macros.hpp>\n\n// Standard library.\n#include \"algorithm.hpp\"\n#include \"cstdint.hpp\"\n#include <map>\n#include <numeric>\n#include \"vector.hpp\"\n\nnamespace shasta {\n    template<class Graph> void approximateColoring(\n        const Graph&,\n        vector<uint64_t>&\n    );\n}\n\n\n\ntemplate<class Graph> void shasta::approximateColoring(\n    const Graph& graph,\n    vector<uint64_t>& color\n)\n{\n    // Get the number of vertices and initialize the colors.\n    const uint64_t n = boost::num_vertices(graph);\n    color.resize(n);\n    const uint64_t noColor = std::numeric_limits<uint64_t>::max();\n    fill(color.begin(), color.end(), noColor);\n\n    // Vector to contain the number of colored vertices adjacent to\n    // each uncolored vertex. This is used to break ties in the Dsatur algorithm.\n    // We only maintain this for uncolored vertices.\n    // Once a vertex gets colored we stop updating this as it will never be needed.\n    vector<uint64_t> adjacentColoredCount(n, 0);\n\n    // The colors adjacent to each uncolored vertex. The number of colors adjacent\n    // to each vertex is small, so we use boost::container::flat_set\n    // instead of std::set.\n    // We only maintain this for uncolored vertices.\n    // Once a vertex gets colored we stop updating this as it will never be needed.\n    using boost::container::flat_set;\n    vector< flat_set<uint64_t> > adjacentColors(n);\n\n    // A multimap that stores uncolored vertices\n    // keyed by saturation degree (that is, the number of colors adjacent to\n    // each vertex), in decreasing order.\n    // This is used to select, at each iteration, the next vertex to be colored.\n    using MultiMap = std::multimap<uint64_t, uint64_t, std::greater<uint64_t> >;\n    MultiMap verticesBySaturationDegree;\n    for(uint64_t v=0; v<n; v++) {\n        verticesBySaturationDegree.insert(make_pair(0, v));\n    }\n\n\n\n    // Main iteration loop. At each iteration we color one vertex.\n    for(uint64_t iteration=0; iteration<n; iteration++) {\n\n        // To choose the vertex to color at this iteration, loop over\n        // all uncolored vertices with maximum saturation degree.\n        SHASTA_ASSERT(not verticesBySaturationDegree.empty());\n        const uint64_t highestSaturationDegree = verticesBySaturationDegree.begin()->first;\n        MultiMap::iterator begin, end;\n        tie(begin, end) = verticesBySaturationDegree.equal_range(highestSaturationDegree);\n        SHASTA_ASSERT(begin != end);\n        uint64_t v0 = begin->second;\n        uint64_t adjacentColoredCount0 = adjacentColoredCount[v0];\n        MultiMap::iterator it0 = begin;\n        for(MultiMap::iterator it=begin; it!=end; ++it) {\n            const uint64_t v1 = it->second;\n            if(adjacentColoredCount[v1] > adjacentColoredCount0) {\n                v0 = v1;\n                adjacentColoredCount0 = adjacentColoredCount[v1];\n                it0 = it;\n            }\n        }\n\n        // Remove v0 from verticesBySaturationDegree.\n        verticesBySaturationDegree.erase(it0);\n\n        // This iteration is coloring LocalVertexId v0.\n        // We choose the lowest color that is not present in adjacentColors[v0].\n        const auto& adjacentColors0 = adjacentColors[v0];\n        uint64_t color0;\n        for(uint64_t color=0; ; color++) {\n            if(adjacentColors0.find(color) == adjacentColors0.end()) {\n                color0 = color;\n                break;\n            }\n        }\n\n        // Color v0 with the color chosen in this way.\n        color[v0] = color0;\n\n        // Increment adjacentColoredCount for adjacent uncolored vertices.\n        BGL_FORALL_ADJ_T(v0, v1, graph, Graph) {\n            if(color[v1] == noColor) {\n                adjacentColoredCount[v1]++;\n            }\n        }\n\n\n        // Update adjacentColors for adjacent uncolored vertices, and\n        // update verticesBySaturationDegree accordingly.\n        BGL_FORALL_ADJ_T(v0, v1, graph, Graph) {\n            if(color[v1] == noColor) {\n                auto& adjacentColors1 = adjacentColors[v1];\n                if(adjacentColors1.find(color0) == adjacentColors1.end()) {\n                    adjacentColors1.insert(color0);\n\n                    // The saturation degree of this vertex has increased.\n                    MultiMap::iterator begin, end;\n                    tie(begin, end) = verticesBySaturationDegree.equal_range(adjacentColors1.size()-1);\n                    SHASTA_ASSERT(begin != end);\n                    bool done = false;\n                    for(MultiMap::iterator it=begin; it!=end; ++it) {\n                        if(it->second == v1) {\n                            verticesBySaturationDegree.erase(it);\n                            verticesBySaturationDegree.insert(make_pair(adjacentColors1.size(), v1));\n                            done = true;\n                            break;\n                        }\n                    }\n                    SHASTA_ASSERT(done);\n                }\n            }\n        }\n    }\n\n    // Verify that we colored all the vertices.\n    SHASTA_ASSERT(find(color.begin(), color.end(), noColor) == color.end());\n\n}\n\n#endif\n\n", "meta": {"hexsha": "c19b2646944d7ce5c814683f6512b22eadb231d3", "size": 7625, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/approximateColoring.hpp", "max_stars_repo_name": "AustinHartman/shasta", "max_stars_repo_head_hexsha": "105b8e85e272247f72ced59005c88879631931c0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 267.0, "max_stars_repo_stars_event_min_datetime": "2018-07-31T16:12:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:57:53.000Z", "max_issues_repo_path": "src/approximateColoring.hpp", "max_issues_repo_name": "AustinHartman/shasta", "max_issues_repo_head_hexsha": "105b8e85e272247f72ced59005c88879631931c0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 140.0, "max_issues_repo_issues_event_min_datetime": "2018-08-10T14:14:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T22:05:05.000Z", "max_forks_repo_path": "src/approximateColoring.hpp", "max_forks_repo_name": "AustinHartman/shasta", "max_forks_repo_head_hexsha": "105b8e85e272247f72ced59005c88879631931c0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 47.0, "max_forks_repo_forks_event_min_datetime": "2018-09-28T18:29:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T02:45:40.000Z", "avg_line_length": 37.0145631068, "max_line_length": 103, "alphanum_fraction": 0.6554754098, "num_tokens": 1699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.5320360557223726}}
{"text": "#include \"advent.hpp\"\n\n#include <iostream>\n#include <fstream>\n#include <robin_hood.h>\n#include <vector>\n#include <string>\n#include <fmt/ranges.h>\n\n#include <Eigen/Core>\n\nusing std::pair;\nusing std::ifstream;\nusing std::string;\nusing std::vector;\n\ntemplate<typename K, typename V>\nusing flat_map = robin_hood::unordered_flat_map<K, V>;\n\ntemplate<typename K>\nusing flat_set = robin_hood::unordered_flat_set<K>;\n\nauto day14(int argc, char** argv) -> int\n{\n    if (argc < 2) {\n        fmt::print(\"Error: no input.\");\n        return 1;\n    }\n\n    ifstream infile(argv[1]); // NOLINT\n    string line;\n\n    flat_map<std::string, char> rules;\n\n    std::getline(infile, line);\n    auto t = line; // the polymer template\n    \n    vector<string> tokens;\n    while (std::getline(infile, line)) {\n        if (line.empty()) { continue; }\n        tokens.clear();\n        util::tokenize(line, ' ', tokens);\n        ENSURE(!tokens[0].empty());\n        rules[tokens[0]] = tokens[2][0];\n    }\n\n    constexpr i64 alphabet_size = 26;\n    auto idx = [](char c) { return static_cast<i64>(std::tolower(c) - 'a'); };\n    constexpr i64 steps{40};\n\n    Eigen::Array<i64, alphabet_size, alphabet_size> cnt;\n    cnt.fill(0);\n    for (auto i = 0UL; i < std::ssize(t) - 1; ++i) {\n        auto a = idx(t[i]);\n        auto b = idx(t[i+1]);\n        ++cnt(a, b);\n    }\n\n    for (i64 step = 0; step < steps; ++step) {\n        auto tmp = cnt;\n        for (auto const& [k, v] : rules) {\n            auto a = idx(k[0]);\n            auto b = idx(k[1]);\n\n            if (cnt(a, b) > 0) {\n                auto c = idx(rules[k]);\n                tmp(a, c) += cnt(a, b);\n                tmp(c, b) += cnt(a, b);\n                tmp(a, b) -= cnt(a, b);\n            }\n        }\n        std::swap(cnt, tmp);\n    }\n    i64 min_count{std::numeric_limits<i64>::max()};\n    i64 max_count{0};\n    i64 most_common{0};\n    i64 least_common{0};\n    for (i64 i = 0; i != cnt.rows(); ++i) {\n        auto sum = cnt.col(i).sum();\n        if (sum > 0) {\n            if (sum == cnt(i, i)) {\n                sum += 1; // add 1 when the string is just one single repeated letter\n            }\n            if (min_count > sum) {\n                min_count = sum;\n                least_common = i;\n            }\n            if (max_count < sum) {\n                max_count = sum;\n                most_common = i;\n            }\n        }\n    }\n    fmt::print(\"least common: {:c}, most common: {:c}\\n\", static_cast<char>(least_common) + 'a', static_cast<char>(most_common) + 'a');\n    fmt::print(\"min: {} ({}), max: {} ({})\\n\", min_count, cnt(least_common, least_common), max_count, cnt(most_common, most_common));\n    fmt::print(\"string length: {}\\n\", cnt.sum() + 1);\n    fmt::print(\"part 2: {}\\n\", max_count - min_count);\n\n    return 0;\n}\n", "meta": {"hexsha": "dd02708f2029e1c15638bdcdfd7785057d7902d0", "size": 2772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/day14.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/day14.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/day14.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": 27.4455445545, "max_line_length": 135, "alphanum_fraction": 0.5158730159, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5320360511045413}}
{"text": "#include \"ExperimentDataUtils.hpp\"\n#include \"dakota_global_defs.hpp\"\n#include \"DataMethod.hpp\"\n#include \"DakotaResponse.hpp\"\n#include \"NonDBayesCalibration.hpp\"\n// Boost.Test\n#define BOOST_TEST_MODULE dakota_field_covariance_utils\n#include <boost/test/included/unit_test.hpp>\n\n//#include <boost/assign/std/vector.hpp>\n#include <boost/foreach.hpp>\n\n#include <cassert>\n#include <iostream>\n\n\nnamespace Dakota {\nnamespace TestFieldCovariance {\n  \nvoid test_multiple_scalar_covariance_matrix()\n{\n  std::vector<RealMatrix> matrices;\n  std::vector<RealVector> diagonals;\n  RealVector scalars;\n  IntVector matrix_map_indices, diagonal_map_indices, scalar_map_indices;\n\n  int num_scalars = 3;\n  Real scalar_array[] = {1.,2.,4.};\n  int scalar_map_index_array[] = {0, 1, 2};\n  scalars.sizeUninitialized( num_scalars );\n  scalar_map_indices.sizeUninitialized( num_scalars );\n  for ( int i=0; i<num_scalars; i++ ){\n    scalars[i] = scalar_array[i];\n    scalar_map_indices[i] = scalar_map_index_array[i];\n  }\n\n  ExperimentCovariance exper_cov; \n  exper_cov.set_covariance_matrices( matrices, diagonals, scalars,\n\t\t\t\t     matrix_map_indices,\n\t\t\t\t     diagonal_map_indices, \n\t\t\t\t     scalar_map_indices );\n\n  // Test determinant and log_determinant\n  BOOST_CHECK_CLOSE(exper_cov.determinant(), 8.0, 1.0e-12);\n  BOOST_CHECK_CLOSE(exper_cov.log_determinant(), std::log(8.0), 1.0e-12);\n\n  int num_residuals = 3;\n  Real residual_array[] = {1.,2.,4.};\n  RealVector residual( Teuchos::Copy, residual_array, num_residuals );\n\n  // Test application of the covariance inverse to residual vector\n  Real prod = exper_cov.apply_experiment_covariance( residual );\n  BOOST_CHECK(  std::abs( prod - 7. ) < \n\t\t10.*std::numeric_limits<double>::epsilon() );\n\n  // Test application of the sqrt of the covariance inverse to residual vector\n  RealVector result;\n  exper_cov.apply_experiment_covariance_inverse_sqrt( residual, result );\n  prod = result.dot( result );\n  BOOST_CHECK(  std::abs( prod - 7. ) < \n\t\t10.*std::numeric_limits<double>::epsilon() );\n\n  // Test application of the sqrt of the covariance inverse to matrix of \n  // gradient vectors\n  RealMatrix scaled_grads;\n  Real grads_array[] = {1.,2.,2.,4.,4.,8.};\n  RealMatrix grads( Teuchos::Copy, grads_array, 2, 2, 3 );\n  exper_cov.apply_experiment_covariance_inverse_sqrt_to_gradients( grads, \n\t\t\t\t\t\t\t\t   scaled_grads);\n\n  RealMatrix grammian( grads.numRows(), grads.numRows(), false );\n  grammian.multiply( Teuchos::NO_TRANS, Teuchos::TRANS, 1.0, scaled_grads, \n\t\t     scaled_grads, 0. );\n  BOOST_CHECK(  std::abs( grammian(0,0) - 7. ) < \n\t\t10.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK(  std::abs( grammian(1,1) - 28. ) < \n\t\t10.*std::numeric_limits<double>::epsilon() );\n\n  // Test application of the sqrt of the covariance inverse to matrix of \n  // Hessian matrices\n  Real hessian_0_array[] = {4., 2., 2., 2.};\n  RealSymMatrix hessian_0( Teuchos::Copy, false, hessian_0_array, 2, 2 );\n  RealSymMatrix hessian_1( hessian_0 );\n  RealSymMatrix hessian_2( hessian_0 );\n  hessian_1 *= 2.;\n  hessian_2 *= 4.;\n\n  RealSymMatrixArray hessians( 3 );\n  hessians[0] = hessian_0;\n  hessians[1] = hessian_1;\n  hessians[2] = hessian_2;\n  RealSymMatrixArray scaled_hessians;\n  exper_cov.apply_experiment_covariance_inverse_sqrt_to_hessians( hessians,\n\t\t\t\t\t\t\t       scaled_hessians );\n\n  Real exact_scaled_hessian_0_array[] = {4.,2.,2.,2.};\n  Real exact_scaled_hessian_1_array[] = {8./std::sqrt(2.),4./std::sqrt(2.),\n\t\t\t\t   4./std::sqrt(2.),4./std::sqrt(2.)};\n  Real exact_scaled_hessian_2_array[] = {8., 4., 4., 4.};\n  RealSymMatrix exact_scaled_hessian_0( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_0_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_1( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_1_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_2( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_2_array, 2, 2 );\n\n  scaled_hessians[0] -= exact_scaled_hessian_0;\n  scaled_hessians[1] -= exact_scaled_hessian_1;\n  scaled_hessians[2] -= exact_scaled_hessian_2;\n\n  BOOST_CHECK( scaled_hessians[0].normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[1].normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[2].normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n\n  // Test extraction of main diagonal\n  RealVector diagonal;\n  exper_cov.get_main_diagonal( diagonal );\n\n  Real exact_diagonal_array[] = {1.,2.,4.};\n  RealVector exact_diagonal(Teuchos::View, exact_diagonal_array, 3 );\n  \n  exact_diagonal -= diagonal;\n  BOOST_CHECK( exact_diagonal.normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n\n}\n\nvoid test_single_diagonal_block_covariance_matrix()\n{\n  std::vector<RealMatrix> matrices;\n  std::vector<RealVector> diagonals;\n  RealVector scalars;\n  IntVector matrix_map_indices, diagonal_map_indices, scalar_map_indices;\n\n  int num_diags = 1;\n  int num_diag_entries = 3;\n  Real diagonal_array[] = {1.,2.,4.};\n  diagonal_map_indices.sizeUninitialized( num_diags );\n  diagonal_map_indices[0] = 0;\n  diagonals.resize( num_diags );\n  diagonals[0].sizeUninitialized( num_diag_entries );\n  for ( int i=0; i<num_diag_entries; i++ ){\n    diagonals[0][i] = diagonal_array[i];\n  }\n\n  ExperimentCovariance exper_cov; \n  exper_cov.set_covariance_matrices( matrices, diagonals, scalars,\n\t\t\t\t     matrix_map_indices,\n\t\t\t\t     diagonal_map_indices, \n\t\t\t\t     scalar_map_indices );\n\n\n  // Test determinant and log_determinant\n  BOOST_CHECK_CLOSE(exper_cov.determinant(), 8.0, 1.0e-12);\n  BOOST_CHECK_CLOSE(exper_cov.log_determinant(), std::log(8.0), 1.0e-12);\n\n  int num_residuals = 3;\n  Real residual_array[] = {1.,2.,4.};\n  RealVector residual( Teuchos::Copy, residual_array, num_residuals );\n\n  // Test application of the covariance inverse to residual vector\n  Real prod = exper_cov.apply_experiment_covariance( residual );\n  BOOST_CHECK(  std::abs( prod - 7. ) < \n\t\t10.*std::numeric_limits<double>::epsilon() );\n  \n  // Test application of the sqrt of the covariance inverse to residual vector\n  RealVector result;\n  exper_cov.apply_experiment_covariance_inverse_sqrt( residual, result );\n  prod = result.dot( result );\n  BOOST_CHECK(  std::abs( prod - 7. ) < \n\t\t10.*std::numeric_limits<double>::epsilon() );\n\n  // Test application of the sqrt of the covariance inverse to matrix of \n  // gradient vectors\n  RealMatrix scaled_grads;\n  Real grads_array[] = {1.,2.,2.,4.,4.,8.};\n  RealMatrix grads( Teuchos::Copy, grads_array, 2, 2, 3 );\n  exper_cov.apply_experiment_covariance_inverse_sqrt_to_gradients( grads, \n\t\t\t\t\t\t\t\t   scaled_grads);\n\n  RealMatrix grammian( grads.numRows(), grads.numRows(), false );\n  grammian.multiply( Teuchos::NO_TRANS, Teuchos::TRANS, 1.0, scaled_grads, \n\t\t     scaled_grads, 0. );\n  BOOST_CHECK(  std::abs( grammian(0,0) - 7. ) < \n\t\t10.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK(  std::abs( grammian(1,1) - 28. ) < \n\t\t10.*std::numeric_limits<double>::epsilon() );\n\n  // Test application of the sqrt of the covariance inverse to matrix of \n  // Hessian matrices\n  Real hessian_0_array[] = {4., 2., 2., 2.};\n  RealSymMatrix hessian_0( Teuchos::Copy, false, hessian_0_array, 2, 2 );\n  RealSymMatrix hessian_1( hessian_0 );\n  RealSymMatrix hessian_2( hessian_0 );\n  hessian_1 *= 2.;\n  hessian_2 *= 4.;\n\n  RealSymMatrixArray hessians( 3 );\n  hessians[0] = hessian_0;\n  hessians[1] = hessian_1;\n  hessians[2] = hessian_2;\n  RealSymMatrixArray scaled_hessians;\n  exper_cov.apply_experiment_covariance_inverse_sqrt_to_hessians( hessians,\n\t\t\t\t\t\t\t       scaled_hessians );\n\n  Real exact_scaled_hessian_0_array[] = {4.,2.,2.,2.};\n  Real exact_scaled_hessian_1_array[] = {8./std::sqrt(2.),4./std::sqrt(2.),\n\t\t\t\t   4./std::sqrt(2.),4./std::sqrt(2.)};\n  Real exact_scaled_hessian_2_array[] = {8., 4., 4., 4.};\n  RealSymMatrix exact_scaled_hessian_0( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_0_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_1( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_1_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_2( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_2_array, 2, 2 );\n\n  scaled_hessians[0] -= exact_scaled_hessian_0;\n  scaled_hessians[1] -= exact_scaled_hessian_1;\n  scaled_hessians[2] -= exact_scaled_hessian_2;\n\n  BOOST_CHECK( scaled_hessians[0].normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[1].normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[2].normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n}\n\nvoid test_single_full_block_covariance_matrix()\n{\n  std::vector<RealMatrix> matrices;\n  std::vector<RealVector> diagonals;\n  RealVector scalars;\n  IntVector matrix_map_indices, diagonal_map_indices, scalar_map_indices;\n\n  int num_matrices = 1;\n  int num_matrix_rows = 3;\n  Real matrix_array[] = {1.,0.5,0.25,0.5,2.,0.5,0.25,0.5,4.};\n  matrix_map_indices.sizeUninitialized( num_matrices );\n  matrix_map_indices[0] = 0;\n  matrices.resize( num_matrices );\n  matrices[0].shapeUninitialized( num_matrix_rows, num_matrix_rows );\n  for ( int j=0; j<num_matrix_rows; j++ ){\n    for ( int i=0; i<num_matrix_rows; i++ )\n      matrices[0](i,j) = matrix_array[j*num_matrix_rows+i];\n  }\n\n  ExperimentCovariance exper_cov; \n  exper_cov.set_covariance_matrices( matrices, diagonals, scalars,\n\t\t\t\t     matrix_map_indices,\n\t\t\t\t     diagonal_map_indices, \n\t\t\t\t     scalar_map_indices );\n\n  // Test determinant and log_determinant\n  BOOST_CHECK_CLOSE(exper_cov.determinant(), 6.75, 1.0e-12);\n  BOOST_CHECK_CLOSE(exper_cov.log_determinant(), std::log(6.75), 1.0e-12);\n\n  int num_residuals = 3;\n  Real residual_array[] = {1.,2.,4.};\n  RealVector residual( Teuchos::Copy, residual_array, num_residuals );\n\n  // Test application of the covariance inverse to residual vector\n  Real prod = exper_cov.apply_experiment_covariance( residual );\n  BOOST_CHECK(  std::abs( prod - 16./3. ) < \n\t\t10.*std::numeric_limits<double>::epsilon() );\n\n  // Test application of the sqrt of the covariance inverse to residual vector\n  RealVector result;\n  exper_cov.apply_experiment_covariance_inverse_sqrt( residual, result );\n  prod = result.dot( result );\n  BOOST_CHECK( std::abs( prod - 16./3. ) < \n\t       10.*std::numeric_limits<double>::epsilon() ); \n  \n  // Test application of the sqrt of the covariance inverse to matrix of \n  // gradient vectors\n  RealMatrix scaled_grads;\n  Real grads_array[] = {1.,2.,2.,4.,4.,8.};\n  RealMatrix grads( Teuchos::Copy, grads_array, 2, 2, 3 );\n  exper_cov.apply_experiment_covariance_inverse_sqrt_to_gradients( grads, \n\t\t\t\t\t\t\t\t   scaled_grads);\n\n  RealMatrix grammian( grads.numRows(), grads.numRows(), false );\n  grammian.multiply( Teuchos::NO_TRANS, Teuchos::TRANS, 1.0, scaled_grads, \n\t\t     scaled_grads, 0. );\n  BOOST_CHECK(  std::abs( grammian(0,0) - 16./3. ) < \n\t\t10.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK(  std::abs( grammian(1,1) - 64./3. ) < \n\t\t20.*std::numeric_limits<double>::epsilon() );\n\n  // Test application of the sqrt of the covariance inverse to matrix of \n  // Hessian matrices\n  Real hessian_0_array[] = {4., 2., 2., 2.};\n  RealSymMatrix hessian_0( Teuchos::Copy, false, hessian_0_array, 2, 2 );\n  RealSymMatrix hessian_1( hessian_0 );\n  RealSymMatrix hessian_2( hessian_0 );\n  hessian_1 *= 2.;\n  hessian_2 *= 4.;\n\n  RealSymMatrixArray hessians( 3 );\n  hessians[0] = hessian_0;\n  hessians[1] = hessian_1;\n  hessians[2] = hessian_2;\n  RealSymMatrixArray scaled_hessians;\n  exper_cov.apply_experiment_covariance_inverse_sqrt_to_hessians( hessians,\n\t\t\t\t\t\t\t  scaled_hessians );\n\n  Real exact_scaled_hessian_0_array[] = {4.,2.,2.,2.};\n  Real exact_scaled_hessian_1_array[] = {4.53557367611073,2.26778683805536,\n\t\t\t\t   2.26778683805536,2.26778683805536};\n  Real exact_scaled_hessian_2_array[] = {6.98297248755176,3.49148624377588,\n\t\t\t\t   3.49148624377588,3.49148624377588};\n  RealSymMatrix exact_scaled_hessian_0( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_0_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_1( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_1_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_2( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_2_array, 2, 2 );\n\n  scaled_hessians[0] -= exact_scaled_hessian_0;\n  scaled_hessians[1] -= exact_scaled_hessian_1;\n  scaled_hessians[2] -= exact_scaled_hessian_2;\n  \n  BOOST_CHECK( scaled_hessians[0].normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[1].normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[2].normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n\n  // Test extraction of main diagonal\n  RealVector diagonal;\n  exper_cov.get_main_diagonal( diagonal );\n\n  Real exact_diagonal_array[] = {1.,2.,4.};\n  RealVector exact_diagonal(Teuchos::View, exact_diagonal_array, 3 );\n  \n  exact_diagonal -= diagonal;\n  BOOST_CHECK( exact_diagonal.normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n  \n}\n\nvoid test_mixed_scalar_diagonal_full_block_covariance_matrix()\n{\n  std::vector<RealMatrix> matrices;\n  std::vector<RealVector> diagonals;\n  RealVector scalars;\n  IntVector matrix_map_indices, diagonal_map_indices, scalar_map_indices;\n\n  // Experiment covariance matrix consists of the following blocks\n  // scalar_1, diagonal_1, matrix_1, scalar_2, scalar_3,\n\n  // MATLAB CODE: \n  // A = [1,0.5,0.25;0.5,2,0.5;0.25,0.5,4.]; B = eye(9); B(1,1)=1.; \n  // B(8,8) = 2.; B(9,9) = 4.; B(3,3) = 2.; B(4,4) = 4.; B(5:7,5:7)=A;\n  // d = [1., 1., 2., 4., 1., 2., 4., 2., 4.]';\n  // chol(inv(B))*d; r'*r\n\n  // Generate scalar matrix blocks\n  int num_scalars = 3;\n  Real scalar_array[] = {1.,2.,4.};\n  int scalar_map_index_array[] = {0, 3, 4};\n  scalars.sizeUninitialized( num_scalars );\n  scalar_map_indices.sizeUninitialized( num_scalars );\n  for ( int i=0; i<num_scalars; i++ ){\n    scalars[i] = scalar_array[i];\n    scalar_map_indices[i] = scalar_map_index_array[i];\n  }\n\n  // Generate diagonal covariance matrix blocks\n  int num_diags = 1;\n  int num_diag_entries = 3;\n  Real diagonal_array[] = {1.,2.,4.};\n  diagonal_map_indices.sizeUninitialized( num_diags );\n  diagonal_map_indices[0] = 1;\n  diagonals.resize( num_diags );\n  diagonals[0].sizeUninitialized( num_diag_entries );\n  for ( int i=0; i<num_diag_entries; i++ ){\n    diagonals[0][i] = diagonal_array[i];\n  }\n  \n  // Generate full covariance matrix blocks\n  int num_matrices=1;\n  int num_matrix_rows = 3;\n  Real matrix_array[] = {1.,0.5,0.25,0.5,2.,0.5,0.25,0.5,4.};\n  matrix_map_indices.sizeUninitialized( num_matrices );\n  matrix_map_indices[0] = 2;\n  matrices.resize( num_matrices );\n  matrices[0].shapeUninitialized( num_matrix_rows, num_matrix_rows );\n  for ( int j=0; j<num_matrix_rows; j++ ){\n    for ( int i=0; i<num_matrix_rows; i++ )\n      matrices[0](i,j) = matrix_array[j*num_matrix_rows+i];\n  }\n\n  ExperimentCovariance exper_cov; \n  exper_cov.set_covariance_matrices( matrices, diagonals, scalars,\n\t\t\t\t     matrix_map_indices,\n\t\t\t\t     diagonal_map_indices, \n\t\t\t\t     scalar_map_indices );\n\n  // Test determinant and log_determinant\n  BOOST_CHECK_CLOSE(exper_cov.determinant(), 432.0, 1.0e-12);\n  BOOST_CHECK_CLOSE(exper_cov.log_determinant(), std::log(432.0), 1.0e-12);\n\n  int num_residuals = 9;\n  Real residual_array[] = {1., 1., 2., 4., 1., 2., 4., 2., 4.};\n  RealVector residual( Teuchos::Copy, residual_array, num_residuals );\n\n  // Test application of the covariance inverse to residual vector\n  Real prod = exper_cov.apply_experiment_covariance( residual );\n  BOOST_CHECK( std::abs( prod - 58./3. ) < \n\t       20.*std::numeric_limits<double>::epsilon() );\n\n  // Test application of the sqrt of the covariance inverse to residual vector\n  RealVector result;\n  exper_cov.apply_experiment_covariance_inverse_sqrt( residual, result );\n  prod = result.dot( result );\n  BOOST_CHECK( std::abs( prod - 58./3. ) < \n\t       10.*std::numeric_limits<double>::epsilon() );\n\n  // Test application of the sqrt of the covariance inverse to matrix of \n  // gradient vectors\n  RealMatrix scaled_grads;\n  Real grads_array[] = { 1., 2., 1., 2., 2., 4., 4., 8., 1., 2., 2., 4., 4., 8.,\n\t\t\t 2., 4., 4., 8. };\n  RealMatrix grads( Teuchos::Copy, grads_array, 2, 2, 9 );\n  exper_cov.apply_experiment_covariance_inverse_sqrt_to_gradients( grads, \n\t\t\t\t\t\t\t\t   scaled_grads);\n\n  RealMatrix grammian( grads.numRows(), grads.numRows(), false );\n  grammian.multiply( Teuchos::NO_TRANS, Teuchos::TRANS, 1.0, scaled_grads, \n\t\t     scaled_grads, 0. );\n  BOOST_CHECK(  std::abs( grammian(0,0) - 58./3. ) < \n\t\t20.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK(  std::abs( grammian(1,1) - 232./3. ) < \n\t\t20.*std::numeric_limits<double>::epsilon() );\n\n  // Test application of the sqrt of the covariance inverse to matrix of \n  // Hessian matrices\n  Real hessian_0_array[] = {4., 2., 2., 2.};\n  RealSymMatrix hessian_0( Teuchos::Copy, false, hessian_0_array, 2, 2 );\n  RealSymMatrix hessian_1( hessian_0 ), hessian_2( hessian_0 ),\n    hessian_3( hessian_0 ),  hessian_4( hessian_0 ),\n    hessian_5( hessian_0 ),  hessian_6( hessian_0 ),\n    hessian_7( hessian_0 ), hessian_8( hessian_0 );\n  hessian_1 *= 1.;  hessian_2 *= 2.;  hessian_3 *= 4.;  hessian_4 *= 1.;\n  hessian_5 *= 2.;  hessian_6 *= 4.;  hessian_7 *= 2.;  hessian_8 *= 4.;\n\n  RealSymMatrixArray hessians( 9 );\n  hessians[0] = hessian_0;  hessians[1] = hessian_1;\n  hessians[2] = hessian_2;  hessians[3] = hessian_3;\n  hessians[4] = hessian_4;  hessians[5] = hessian_5;\n  hessians[6] = hessian_6;  hessians[7] = hessian_7;\n  hessians[8] = hessian_8;\n\n  RealSymMatrixArray scaled_hessians;\n  exper_cov.apply_experiment_covariance_inverse_sqrt_to_hessians( hessians, \n\t\t\t\t\t\t\t       scaled_hessians );\n\n  Real exact_scaled_hessian_0_array[] = {4.,2.,2.,2.};\n  Real exact_scaled_hessian_1_array[] = {4.,2.,2.,2.};\n  Real exact_scaled_hessian_2_array[] = {8./std::sqrt(2.),4./std::sqrt(2.),\n\t\t\t\t   4./std::sqrt(2.),4./std::sqrt(2.)};\n  Real exact_scaled_hessian_3_array[] = {8., 4., 4., 4.};\n  Real exact_scaled_hessian_4_array[] = {4.,2.,2.,2.};\n  Real exact_scaled_hessian_5_array[] = {4.53557367611073,2.26778683805536,\n\t\t\t\t   2.26778683805536,2.26778683805536};\n  Real exact_scaled_hessian_6_array[] = {6.98297248755176,3.49148624377588,\n\t\t\t\t   3.49148624377588,3.49148624377588};\n  Real exact_scaled_hessian_7_array[] = {8./std::sqrt(2.),4./std::sqrt(2.),\n\t\t\t\t   4./std::sqrt(2.),4./std::sqrt(2.)};\n  Real exact_scaled_hessian_8_array[] = {8., 4., 4., 4.};\n\n  RealSymMatrix exact_scaled_hessian_0( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_0_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_1( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_1_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_2( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_2_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_3( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_3_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_4( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_4_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_5( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_5_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_6( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_6_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_7( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_7_array, 2, 2 );\n  RealSymMatrix exact_scaled_hessian_8( Teuchos::View, false, \n\t\t\t\t  exact_scaled_hessian_8_array, 2, 2 );\n\n  scaled_hessians[0] -= exact_scaled_hessian_0;\n  scaled_hessians[1] -= exact_scaled_hessian_1;\n  scaled_hessians[2] -= exact_scaled_hessian_2;\n  scaled_hessians[3] -= exact_scaled_hessian_3;\n  scaled_hessians[4] -= exact_scaled_hessian_4;\n  scaled_hessians[5] -= exact_scaled_hessian_5;\n  scaled_hessians[6] -= exact_scaled_hessian_6;\n  scaled_hessians[7] -= exact_scaled_hessian_7;\n  scaled_hessians[8] -= exact_scaled_hessian_8;\n  \n  BOOST_CHECK( scaled_hessians[0].normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[1].normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[2].normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[3].normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[4].normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[5].normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[6].normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[7].normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n  BOOST_CHECK( scaled_hessians[8].normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n\n\n  // Test extraction of main diagonal\n  RealVector diagonal;\n  exper_cov.get_main_diagonal( diagonal );\n\n  Real exact_diagonal_array[] = {1.,1.,2.,4.,1.,2.,4.,2.,4.};\n  RealVector exact_diagonal(Teuchos::View, exact_diagonal_array, 9 );\n  \n  exact_diagonal -= diagonal;\n  BOOST_CHECK( exact_diagonal.normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n\n  // Test conversion to correlation matrix\n  // Matlab for correlation matrix\n  // std_dev = sqrt(diag(B)); correl_mat = diag(1./std_dev)*B*diag(1./std_dev);\n  RealSymMatrix exact_correl(9);\n  for (int i=0; i<9; ++i)\n    exact_correl(i,i) = 1.0;\n  // update off-diagonal entries for the full matrix block\n  for (int i=0; i<3; ++i)\n    for (int j=0; j<i; ++j)\n      exact_correl(4+i,4+j) = matrices[0](i,j) / \n        std::sqrt(matrices[0](i,i)) / std::sqrt(matrices[0](j,j));\n\n  RealSymMatrix calc_correl;\n  exper_cov.as_correlation(calc_correl);\n\n  calc_correl -= exact_correl;\n  BOOST_CHECK( calc_correl.normInf() < \n               10.*std::numeric_limits<double>::epsilon() );\n}\n\nvoid test_linear_interpolate_1d_no_extrapolation()\n{\n  // Generate field coordinates on [0,1]\n  int num_field_pts = 6;\n  Real field_pts_array[] = {1./6.,2./5.,7./12.,2./3.,6./7.,1.};\n  RealMatrix field_pts( Teuchos::View, field_pts_array, 1, num_field_pts, 1 );\n  // Generate field data which is the 3rd degree Legendre polynomial 1/2(5x^3-3x)\n  RealVector field_vals( num_field_pts, false );\n  for ( int i=0; i<num_field_pts; i++)\n    field_vals[i] = 0.5*(5.*std::pow(field_pts(i,0),3)-3.*field_pts(i,0));\n  \n  // Generate simulation coordinates on equally spaced on [0,1]\n  int num_sim_pts = 11;\n  RealMatrix sim_pts( num_sim_pts, 1, false );\n  Real dx = 1./(num_sim_pts-1); \n  for ( int i=0; i<num_sim_pts; i++)\n    sim_pts(i,0) = i*dx;\n  // Generate simulation data which is the 2nd degree Legendre polynomial\n  // 1/2(3x^2-1)\n  RealVector sim_vals( num_sim_pts, false );\n  for ( int i=0; i<num_sim_pts; i++)\n    sim_vals[i] = 0.5*(3.*std::pow(sim_pts(i,0),2)-1.);\n  // Generate gradients of simulation data which is [3x,4x]\n  int num_vars = 2;\n  RealMatrix sim_grads( num_vars, num_sim_pts, false );\n  for ( int i=0; i<num_sim_pts; i++){\n    sim_grads(0,i) = 3.*sim_pts(i,0);\n    sim_grads(1,i) = 4.*sim_pts(i,0);\n  }\n  // Generate gradients of simulation data which we assume is also \n  // [3x+0.2,3x+0.05;3x+0.05,3x+0.1]\n  // Note interp sets num_vars from gradients and so hessian must be\n  // consistent with grads\n  RealSymMatrixArray sim_hessians( num_sim_pts );\n  for ( int i=0; i<num_sim_pts; i++){\n    sim_hessians[i].shapeUninitialized(num_vars);\n    //symmetric so do not have to set all entries, just upper triangular ones\n    sim_hessians[i](0,0)=3.*sim_pts(i,0)+0.2;\n    sim_hessians[i](0,1)=3.*sim_pts(i,0)+0.05;\n    sim_hessians[i](1,1)=3.*sim_pts(i,0)+0.1;\n  }\n\n  // Interpolate the simulation data onto the coordinates of the field data\n  RealVector interp_vals;\n  RealMatrix interp_grads;\n  RealSymMatrixArray interp_hessians;\n  linear_interpolate_1d( sim_pts, sim_vals, sim_grads, sim_hessians, \n\t\t\t field_pts, interp_vals, interp_grads, interp_hessians );\n  interp_vals -= field_vals;\n\n  Real diff_array[] = {-2.16574074074074e-1,1.8e-1,3.91261574074074e-1,\n\t\t       4.29259259259259e-1,3.17084548104956e-1,0.0};\n  RealVector diff( Teuchos::View, diff_array, num_field_pts );\n  diff -= interp_vals;\n  BOOST_CHECK( diff.normInf() < 10.*std::numeric_limits<double>::epsilon() );\n\n  RealMatrix true_grads(num_vars,num_field_pts,false);\n  for ( int i=0; i<num_field_pts; i++){\n    true_grads(0,i) = 3.*field_pts(i,0);\n    true_grads(1,i) = 4.*field_pts(i,0);\n  }\n  true_grads -= interp_grads;\n  BOOST_CHECK( true_grads.normInf()<10.*std::numeric_limits<double>::epsilon() );\n\n  RealSymMatrixArray true_hessians( num_sim_pts );\n  for ( int i=0; i<num_field_pts; i++){\n    true_hessians[i].shapeUninitialized(num_vars);\n    //symmetric so do not have to set all entries, just upper triangular ones\n    true_hessians[i](0,0)=3.*field_pts(i,0)+0.2;\n    true_hessians[i](0,1)=3.*field_pts(i,0)+0.05;\n    true_hessians[i](1,1)=3.*field_pts(i,0)+0.1;\n    true_hessians[i] -= interp_hessians[i];\n    BOOST_CHECK( true_hessians[i].normInf()<\n\t\t 10.*std::numeric_limits<double>::epsilon() );\n  }\n}\n\nvoid test_linear_interpolate_1d_with_extrapolation()\n{\n  // Linear interpolate uses constant extrapolation\n\n  // Generate field coordinates on [-1/6,11/10]\n  int num_field_pts = 6;\n  Real field_pts_array[] = {-1./6.,2./5.,7./12.,2./3.,6./7.,11./10.};\n  RealMatrix field_pts( Teuchos::View, field_pts_array, 1, num_field_pts, 1 );\n  // Generate field data which is the 3rd degree Legendre polynomial 1/2(5x^3-3x)\n  RealVector field_vals( num_field_pts, false );\n  for ( int i=0; i<num_field_pts; i++)\n    field_vals[i] = 0.5*(5.*std::pow(field_pts(i,0),3)-3.*field_pts(i,0));\n  \n  // Generate simulation coordinates on equally spaced on [0,1]\n  int num_sim_pts = 11;\n  RealMatrix sim_pts( num_sim_pts, 1, false );\n  Real dx = 1./(num_sim_pts-1); \n  for ( int i=0; i<num_sim_pts; i++)\n    sim_pts(i,0) = i*dx;\n  // Generate simulation data which is the 2nd degree Legendre polynomial\n  // 1/2(3x^2-1)\n  RealVector sim_vals( num_sim_pts, false );\n  for ( int i=0; i<num_sim_pts; i++)\n    sim_vals[i] = 0.5*(3.*std::pow(sim_pts(i,0),2)-1.);\n\n  // Interpolate the simulation data onto the coordinates of the field data\n  RealVector interp_vals;\n  RealMatrix sim_grads, interp_grads;\n  RealSymMatrixArray sim_hessians, interp_hessians;\n  linear_interpolate_1d( sim_pts, sim_vals, sim_grads, sim_hessians, \n\t\t\t field_pts, interp_vals, interp_grads, interp_hessians );\n  interp_vals -= field_vals;\n\n  Real diff_array[] = {-7.38425925925926e-1,1.8e-1,3.91261574074074e-1,\n\t\t       4.29259259259259e-1,3.17084548104956e-1,-6.775e-1};\n  RealVector diff( Teuchos::View, diff_array, num_field_pts );\n  diff -= interp_vals;\n  BOOST_CHECK( diff.normInf() < 10.*std::numeric_limits<double>::epsilon() );\n}\n\n/*void test_build_hessian_of_sum_square_residuals_from_function_hessians()\n{\n  int num_residuals = 3;\n  RealSymMatrixArray func_hessians( num_residuals );\n  RealMatrix func_gradients( 2, num_residuals, false );\n  RealVector residuals( num_residuals );\n\n  Real pts_array[] = {-1,-1,-0.5,0.5,1./3.,2./3.};\n  RealMatrix pts( Teuchos::View, pts_array, 2, 2, 3 );\n\n  for ( int i=0; i<num_residuals; i++ ){\n    Real x = pts(0,i), y = pts(1,i);\n    Real x2 = x*x, y2 = y*y;\n    residuals[i] = (2.*x2-y2)*(2.*x2-y2)/10.-x2*y2; \n    // The following will not work. Build hessian assumes \n    // residual = (approx-data)\n    //residuals[i] = x2*y2-(2.*x2-y2)*(2.*x2-y2)/10.;\n    func_gradients(0,i) = 4./5.*x*(2.*x2-y2);\n    func_gradients(1,i) = 2./5.*y*(y2-2.*x2);\n    func_hessians[i].shape( 2 );\n    func_hessians[i](0,0) = -4./5.*(y2-6.*x2);\n    func_hessians[i](1,0) = -8.*x*y/5.;\n    func_hessians[i](1,1) = 2./5.*(3.*y2-2.*x2);\n  }\n\n  ActiveSet set(num_residuals, 2); set.request_values(7);\n  Response resp(SIMULATION_RESPONSE, set);\n  resp.function_values(residuals);\n  resp.function_gradients(func_gradients);\n  resp.function_hessians(func_hessians);\n\n  // -------------------------------------- //\n  // Build hessian without noise covariance\n  // -------------------------------------- //\n\n  // If no noise covariance specify exper_cov as empty\n  ExperimentCovariance exper_cov;\n\n  RealSymMatrix ssr_hessian;\n  build_hessian_of_sum_square_residuals_from_response(resp, exper_cov,\n\t\t\t\t\t\t      ssr_hessian);\n  // hessian computed for ssr= r'r/2\n  RealSymMatrix truth_ssr_hessian( 2 );\n  for ( int i=0; i<num_residuals; i++ ){\n    Real x = pts(0,i), y = pts(1,i);\n    Real x2 = x*x, x3 = x2*x, x4 = x2*x2, x5 = x3*x2, x6 = x4*x2,\n      y2 = y*y, y3 = y2*y, y4 = y2*y2, y5 = y3*y2, y6 = y4*y2;\n    truth_ssr_hessian(0,0) += 2./25.*( 10.*x2*y2*(y2-6.*x2)-\n\t\t\t\t\t(y2-14.*x2)*(2.*x2-y2)*(2.*x2-y2) );\n    truth_ssr_hessian(1,0) += 4./25.*y*x*( 10.*x2*y2-3.*(2.*x2-y2)*(2.*x2-y2) );\n    truth_ssr_hessian(1,1) += 1./25.*( 10.*x2*y2*(2.*x2-3.*y2) + \n\t\t\t\t       (7.*y2-2.*x2)*(2.*x2-y2)*(2.*x2-y2) );\n  }\n  // hack until build hessian can use covariance for multiple experiments\n  truth_ssr_hessian *=2;\n  \n  truth_ssr_hessian -= ssr_hessian;\n  BOOST_CHECK( truth_ssr_hessian.normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n\n  // -------------------------------------- //\n  // Build hessian with noise covariance\n  // -------------------------------------- //\n\n  // Fill exper_cov with noise covariance\n  std::vector<RealMatrix> matrices;\n  std::vector<RealVector> diagonals;\n  RealVector scalars;\n  IntVector matrix_map_indices, diagonal_map_indices, scalar_map_indices;\n\n  // Experiment covariance matrix consists of the following blocks\n  // scalar_1, matrix_1\n\n  // MATLAB CODE: \n  //\n  //  A = [1,0.5;0.5,2.]; S = eye(3); S(1,1)=1.; S(2:3,2:3)=A;\n  //  U = chol( inv(S) );\n\n  //  r = [-0.9 -0.05625 -0.04444444444444444]';\n  //  g = [-0.8, -0.1, -0.05925925925925925; 0.4, -0.05, 0.05925925925925925];\n  //  h1 = [4,-1.6;-1.6,0.4]; h2=[1 0.4;0.4,0.1]; \n  //  h3 =[0.1777777777777778,-0.3555555555555555;\n  //  -0.3555555555555555, 0.4444444444444445];\n\n  //  gnewton_hess = g*inv(S)*g';\n  //  rs = r'*inv(S);\n  //  hess = gnewton_hess + rs(1)*h1+rs(2)*h2+rs(3)*h3   \n\n  // Generate scalar matrix blocks\n  int num_scalars = 1;\n  Real scalar_array[] = {1.};\n  int scalar_map_index_array[] = {0};\n  scalars.sizeUninitialized( num_scalars );\n  scalar_map_indices.sizeUninitialized( num_scalars );\n  for ( int i=0; i<num_scalars; i++ ){\n    scalars[i] = scalar_array[i];\n    scalar_map_indices[i] = scalar_map_index_array[i];\n  }\n\n  // Generate full covariance matrix blocks\n  int num_matrices=1;\n  int num_matrix_rows = 2;\n  Real matrix_array[] = {1.,0.5,0.5,2.};\n  matrix_map_indices.sizeUninitialized( num_matrices );\n  matrix_map_indices[0] = 1;\n  matrices.resize( num_matrices );\n  matrices[0].shapeUninitialized( num_matrix_rows, num_matrix_rows );\n  for ( int j=0; j<num_matrix_rows; j++ ){\n    for ( int i=0; i<num_matrix_rows; i++ )\n      matrices[0](i,j) = matrix_array[j*num_matrix_rows+i];\n  }\n\n  exper_cov.set_covariance_matrices( matrices, diagonals, scalars,\n\t\t\t\t     matrix_map_indices,\n\t\t\t\t     diagonal_map_indices, \n\t\t\t\t     scalar_map_indices );\n  \n  // must reset ssr_hessian because if it is the right size\n  // the build_hessians... function will assume we want to add to it\n  ssr_hessian.shape(0);\n  build_hessian_of_sum_square_residuals_from_response(resp, exper_cov,\n\t\t\t\t\t\t      ssr_hessian);\n\n  Real truth_noise_scaled_ssr_hessian_array[] = {-3.00319615912208e+00,\n\t\t\t\t\t\t 1.10723495982755e+00,\n\t\t\t\t\t\t 1.10723495982755e+00,\n\t\t\t\t\t\t -2.02746423672350e-01};\n  RealSymMatrix truth_noise_scaled_ssr_hessian( Teuchos::View, true,\n\t\t\t\t\t  truth_noise_scaled_ssr_hessian_array,\n\t\t\t\t\t  2, 2 );\n\n  // hack until build hessian can use covariance for multiple experiments\n  truth_noise_scaled_ssr_hessian *=2;\n  \n  truth_noise_scaled_ssr_hessian -= ssr_hessian;\n  BOOST_CHECK( truth_noise_scaled_ssr_hessian.normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n\n  // -------------------------------------- //\n  // Build Gauss-Newton hessian with noise covariance\n  // -------------------------------------- //\n  ActiveSet set1(num_residuals, 2); set1.request_values(3);\n  Response resp1(SIMULATION_RESPONSE, set1);\n  resp1.function_values(residuals);\n  resp1.function_gradients(func_gradients);\n  resp1.function_hessians(func_hessians);\n  \n  // must reset ssr_hessian because if it is the right size\n  // the build_hessians... function will assume we want to add to it\n  ssr_hessian.shape(0);\n  build_hessian_of_sum_square_residuals_from_response(resp1, exper_cov,\n\t\t\t\t\t\t      ssr_hessian);\n\n  Real truth_noise_scaled_gn_ssr_hessian_array[] = {6.50048990789732e-01,\n\t\t\t\t\t\t    -3.15445816186557e-01,\n\t\t\t\t\t\t    -3.15445816186557e-01,\n\t\t\t\t\t\t    1.66556927297668e-01};\n  RealSymMatrix truth_noise_scaled_gn_ssr_hessian( Teuchos::View, true,\n\t\t\t\t\ttruth_noise_scaled_gn_ssr_hessian_array,\n\t\t\t\t\t2, 2 );\n\n  // hack until build hessian can use covariance for multiple experiments\n  truth_noise_scaled_gn_ssr_hessian *=2;\n  \n  truth_noise_scaled_gn_ssr_hessian -= ssr_hessian;\n  BOOST_CHECK( truth_noise_scaled_gn_ssr_hessian.normInf() < \n\t       100.*std::numeric_limits<double>::epsilon() );\n}*/\n\nvoid test_symmetric_eigenvalue_decomposition()\n{\n  Real matrix_array[] = { 1.64, 0.48, 0.48, 1.36 };\n  RealSymMatrix matrix( Teuchos::View, false, matrix_array, 2, 2 );\n\n  RealVector eigenvalues;\n  RealMatrix eigenvectors;\n  symmetric_eigenvalue_decomposition( matrix, eigenvalues, eigenvectors );\n\n  Real truth_eigenvalues_array[] = {1.,2.};\n  RealVector truth_eigenvalues( Teuchos::View, truth_eigenvalues_array, 2 );\n \n  truth_eigenvalues -=  eigenvalues;\n  BOOST_CHECK( truth_eigenvalues.normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n\n\n  Real truth_eigenvectors_array[] ={ 0.6, -0.8, -0.8, -0.6 };\n  RealMatrix truth_eigenvectors( Teuchos::View, truth_eigenvectors_array, 2,2,2);\n\n  truth_eigenvectors -= eigenvectors;\n  BOOST_CHECK( truth_eigenvectors.normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n}\n\nvoid test_get_positive_definite_covariance_from_hessian()\n{\n  // uncorrelated prior\n  Real prior_chol_fact1[] = { 0.2, 0., 0., 0.2 };\n  RealMatrix prior_L1(Teuchos::View, prior_chol_fact1, 2, 2, 2);\n\n  // non positive definite matrix\n  Real misfit_h_array1[] = { 0.92, 1.44, 1.44, 0.08 };\n  RealSymMatrix misfit_hessian1(Teuchos::View, false, misfit_h_array1, 2, 2 );\n\n  RealSymMatrix covariance1;\n  NonDBayesCalibration::\n    get_positive_definite_covariance_from_hessian(misfit_hessian1, prior_L1,\n\t\t\t\t\t\t  covariance1, NORMAL_OUTPUT);\n\n  // MATLAB result (no truncation of eigenvalues)\n  //Real truth_cov1_array[] ={  0.038703703703704, -0.002222222222222,\n  //\t\t\t       -0.002222222222222,  0.04 };\n  // Dakota result (truncation of 1 eigenvalue)\n  Real truth_cov1_array[] ={ 3.81037037037037e-02, -1.42222222222222e-03,\n\t\t\t    -1.42222222222222e-03,  3.89333333333333e-02 };\n  RealSymMatrix truth_covariance1(Teuchos::View, false, truth_cov1_array, 2, 2);\n\n  truth_covariance1 -= covariance1;\n  BOOST_CHECK( truth_covariance1.normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n\n  //////////////////////////////////////////////////////////////////////////////\n\n  // correlated prior\n  Real prior_chol_fact2[] = { 0.2, 0.05, 0., 0.2 };\n  RealMatrix prior_L2(Teuchos::View, prior_chol_fact2, 2, 2, 2);\n\n  // positive definite matrix\n  Real misfit_h_array2[] = { 1.64, 0.48, 0.48, 1.36 };\n  RealSymMatrix misfit_hessian2(Teuchos::View, false, misfit_h_array2, 2, 2);\n\n  RealSymMatrix covariance2;\n  NonDBayesCalibration::\n    get_positive_definite_covariance_from_hessian(misfit_hessian2, prior_L2,\n\t\t\t\t\t\t  covariance2, NORMAL_OUTPUT);\n\n  // MATLAB and Dakota result (no truncation of eigenvalues):\n  Real truth_cov2_array[] = { 0.037120225312445, 0.008125330047527,\n\t\t\t      0.008125330047527, 0.039714838936807 };\n  RealSymMatrix truth_covariance2(Teuchos::View, false, truth_cov2_array, 2, 2);\n\n  truth_covariance2 -= covariance2;\n  BOOST_CHECK( truth_covariance2.normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n\n  //////////////////////////////////////////////////////////////////////////////\n  /*\n  // zero misfit matrix: proposal covariance = prior covariance\n  // can't perform symmetric eigen-deomposition for L'HL = 0\n  Real misfit_h_array3[] = { 0., 0., 0., 0. };\n  RealSymMatrix misfit_hessian3(Teuchos::View, false, misfit_h_array3, 2, 2);\n\n  RealSymMatrix covariance3;\n  NonDBayesCalibration::\n    get_positive_definite_covariance_from_hessian(misfit_hessian3, prior_L2,\n\t\t\t\t\t\t  covariance3, NORMAL_OUTPUT);\n\n  Real truth_cov3_array[] = { 4., 0.1, 0.1, 4.0025 };\n  RealSymMatrix truth_covariance3(Teuchos::View, false, truth_cov3_array, 2, 2);\n\n  truth_covariance3 -= covariance3;\n  BOOST_CHECK( truth_covariance3.normInf() < \n\t       10.*std::numeric_limits<double>::epsilon() );\n  */\n}\n\nvoid test_matrix_symmetry()\n{\n  // Test non-square matrix\n  RealMatrix test_rect_matrix(4,3, true);\n  bool is_symm = is_matrix_symmetric(test_rect_matrix);\n  BOOST_CHECK( !is_symm );\n\n  Real matrix_array[] = { 1.0, 0.7, 0.7, 0.7, \n                          0.7, 1.0, 0.7, 0.7, \n                          0.7, 0.7, 1.0, 0.7, \n                          0.7, 0.7, 0.7, 1.0 };\n\n  // Test symmetric matrix\n  RealMatrix test_symm_mat(Teuchos::Copy, matrix_array, 4, 4, 4);\n  is_symm = is_matrix_symmetric(test_symm_mat);\n  BOOST_CHECK( is_symm );\n\n  // Test non-symmetric square matrix\n  RealMatrix test_nonsymm_mat(test_symm_mat);\n  test_nonsymm_mat(1,0) = 0.5;\n  is_symm = is_matrix_symmetric(test_nonsymm_mat);\n  BOOST_CHECK( !is_symm );\n}\n\n} // end namespace TestFieldCovariance\n} // end namespace Dakota\n\n// NOTE: Boost.Test framework provides the main progran driver\n\n//____________________________________________________________________________//\n\nBOOST_AUTO_TEST_CASE( test_main )\n//int test_main( int argc, char* argv[] )      // note the name!\n{\n  using namespace Dakota::TestFieldCovariance;\n\n  // Test ExperimentData covariance matrix\n  test_multiple_scalar_covariance_matrix();\n  test_single_diagonal_block_covariance_matrix();\n  test_single_full_block_covariance_matrix();\n  test_mixed_scalar_diagonal_full_block_covariance_matrix();\n\n  // Test field interpolation functions\n  test_linear_interpolate_1d_no_extrapolation();\n  test_linear_interpolate_1d_with_extrapolation();\n\n  // Test hessian functions\n  // Turn following test off until I can create an ExperimentData object\n  //test_build_hessian_of_sum_square_residuals_from_function_hessians();\n  test_get_positive_definite_covariance_from_hessian();\n\n  // Test linear algebra routines\n  test_symmetric_eigenvalue_decomposition();\n  test_matrix_symmetry();\n\n  int run_result = 0;\n  BOOST_CHECK( run_result == 0 || run_result == boost::exit_success );\n\n  //  return boost::exit_success;\n}\n", "meta": {"hexsha": "951775b6655cb183cd0cbd94a387ca6b42a4a7c1", "size": 38704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/unit_test/test_field_covariance_utils.cpp", "max_stars_repo_name": "jnnccc/Dakota-orb", "max_stars_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/unit_test/test_field_covariance_utils.cpp", "max_issues_repo_name": "jnnccc/Dakota-orb", "max_issues_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unit_test/test_field_covariance_utils.cpp", "max_forks_repo_name": "jnnccc/Dakota-orb", "max_forks_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_forks_repo_licenses": ["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.704, "max_line_length": 81, "alphanum_fraction": 0.6912722199, "num_tokens": 12153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5320360484871149}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n\n#include <Eigen/Core>\n\n#include \"igl/adjacency_list.h\"\n#include \"igl/adjacency_matrix.h\"\n#include \"igl/components.h\"\n#include \"igl/cotmatrix.h\"\n#include \"igl/dijkstra.h\"\n#include \"igl/embree/ambient_occlusion.h\"\n#include \"igl/embree/unproject_onto_mesh.h\"\n#include \"igl/gaussian_curvature.h\"\n#include \"igl/invert_diag.h\"\n#include \"igl/jet.h\"\n#include \"igl/massmatrix.h\"\n#include \"igl/per_vertex_attribute_smoothing.h\"\n#include \"igl/per_vertex_normals.h\"\n#include \"igl/polygon_mesh_to_triangle_mesh.h\"\n#include \"igl/principal_curvature.h\"\n#include \"igl/ray_mesh_intersect.h\"\n#include \"igl/readOFF.h\"\n#include \"igl/unproject_onto_mesh.h\"\n#include \"igl/viewer/Viewer.h\"\n#include \"igl/writeOFF.h\"\n\nvoid getMeanCurvature(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F,\n                      Eigen::VectorXd &VCs) {\n  // Get the laplacian\n  Eigen::SparseMatrix<double> L,M,Minv;\n  //   from the cotangent matrix\n  igl::cotmatrix(V,F, L);\n  //   and the mass matrix\n  igl::massmatrix(V,F, igl::MASSMATRIX_TYPE_VORONOI, M);\n  igl::invert_diag(M, Minv);\n\n  Eigen::MatrixXd HN = -Minv*(L * V);\n  // Mean curviture is this value, up to a sign.\n  Eigen::VectorXd VC = HN.rowwise().norm();\n\n  // Smooth this out a bit.\n  //igl::per_vertex_attribute_smoothing(VC,F, VCs);\n  VCs = VC;\n  Eigen::VectorXd VC_before = VCs;\n  VCs = VCs.cwiseMin(0.1);\n\n\n  // Normalize all the values.\n  VCs /= VCs.maxCoeff();\n  VCs = VCs.cwiseSqrt();\n  Eigen::VectorXd ones = Eigen::VectorXd::Constant(VCs.rows(), 1, 1);\n  VCs = ones - VCs;\n}\n\nint main(int argc, char* argv[]) {\n  if (argc < 2) {\n    fprintf(stderr, \"Used for selecting points on the surface of a mesh. Will write the\\n\"\n                    \"corresponding vertices to output.off\\n\");\n    fprintf(stderr, \"usage: %s <input.off>\\n\", argv[0]);\n    return -1;\n  }\n\n  Eigen::MatrixXd V;\n  Eigen::MatrixXi F;\n  \n  printf(\"Reading in mesh...\\n\");\n  // Read in the input file.\n  igl::readOFF(argv[1], V, F);\n  // Need the adjacency list\n  std::vector<std::vector<int> > VV;\n  igl::adjacency_list(F, VV);\n  // Also caluculate the curvature values.\n  printf(\"Calucalting curvature...\\n\");\n  std::vector<std::vector<double> > curveWeight;\n  Eigen::VectorXd mean_curve;\n  \n\n  Eigen::MatrixXd PD1,PD2;\n  Eigen::VectorXd PV1,PV2;\n  igl::principal_curvature(V,F,PD1,PD2,PV1,PV2, 5);\n  //mean_curve = 0.5 * (PV1 + PV2);\n  mean_curve = PV1.cwiseProduct(PV1) + PV2.cwiseProduct(PV2);\n  mean_curve = mean_curve.cwiseMin(0.1);\n  mean_curve.cwiseSqrt();\n  std::cout << mean_curve << std::endl;\n  //getMeanCurvature(V,F, mean_curve);\n\n\n  igl::viewer::Viewer viewer;\n  viewer.data.set_mesh(V, F);\n  Eigen::MatrixXd this_col;\n  igl::jet(mean_curve, true, this_col);\n  viewer.data.set_colors(this_col);\n  viewer.core.show_lines = false;\n  viewer.launch();\n}\n\n", "meta": {"hexsha": "e83863fbb05907799466282902bd0e12e24c71da", "size": 2826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cgal_mesh_generation/color_curvature.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/color_curvature.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/color_curvature.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": 28.5454545455, "max_line_length": 90, "alphanum_fraction": 0.6843595188, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5319431128639315}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed 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#include <boost/hana/ext/std/tuple.hpp>\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/integral.hpp>\n#include <boost/hana/monad/laws.hpp>\n\n#include <tuple>\nusing namespace boost::hana;\n\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto f = [](auto x) {\n    return std::make_tuple(x + int_<1>);\n};\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto g = [](auto x) {\n    return std::make_tuple(x * int_<3>);\n};\n\nint main() {\n    BOOST_HANA_CONSTANT_ASSERT(Monad::laws::check(std::make_tuple(), int_<1>, f, g));\n    BOOST_HANA_CONSTANT_ASSERT(Monad::laws::check(std::make_tuple(int_<1>), int_<1>, f, g));\n    BOOST_HANA_CONSTANT_ASSERT(Monad::laws::check(std::make_tuple(int_<1>, int_<2>), int_<1>, f, g));\n    BOOST_HANA_CONSTEXPR_ASSERT(Monad::laws::check(std::make_tuple(1, 2, 3, 4), int_<1>, f, g));\n}\n", "meta": {"hexsha": "6068149e975ce64644db530aeead7cc48ec119e4", "size": 1003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ext/std/tuple/monad/laws.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/ext/std/tuple/monad/laws.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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/ext/std/tuple/monad/laws.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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.34375, "max_line_length": 101, "alphanum_fraction": 0.7078763709, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5319430995153099}}
{"text": "#ifndef SMALL\n#define SMALL\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <iostream>\n\n#include \"MiniDnn/layer.h\"\n#include \"MiniDnn/layer/conv.h\"\n#include \"MiniDnn/layer/fully_connected.h\"\n#include \"MiniDnn/layer/ave_pooling.h\"\n#include \"MiniDnn/layer/max_pooling.h\"\n#include \"MiniDnn/layer/relu.h\"\n#include \"MiniDnn/layer/sigmoid.h\"\n#include \"MiniDnn/layer/softmax.h\"\n#include \"MiniDnn/loss.h\"\n#include \"MiniDnn/loss/mse_loss.h\"\n#include \"MiniDnn/loss/cross_entropy_loss.h\"\n#include \"MiniDnn/mnist.h\"\n#include \"MiniDnn/network.h\"\n#include \"MiniDnn/optimizer.h\"\n#include \"MiniDnn/optimizer/sgd.h\"\n#include \"Enclave.h\"\n#include \"Enclave_t.h\"  /* print_string */\n\n\nusing namespace std;\n\nclass RandData {\npublic:\n    Matrix train_data;\n    Matrix train_labels;\n    Matrix test_data;\n    Matrix test_labels;\n\n    RandData(int size) {\n        train_data = Matrix::Random(28 * 28, size);\n        train_labels = Matrix::Ones(1, size);\n        test_data = Matrix::Random(28 * 28, size);\n        test_labels = Matrix::Ones(1, size);\n    }\n};\n\nvoid ecall_ml_small() {\n    // data\n//    MNIST dataset(\"/Users/rc/Study/Projects/mini-dnn/data/mnist/\");\n//    dataset.read();\n//    int n_train = dataset.train_data.cols();\n//    int dim_in = dataset.train_data.rows();\n//    std::cout << \"mnist train number: \" << n_train << std::endl;\n//    std::cout << \"mnist test number: \" << dataset.test_labels.cols() << std::endl;\n    RandData dataset(1000);\n//    dataset.read();\n    int n_train = dataset.train_data.cols();\n    int dim_in = dataset.train_data.rows();\n    // dnn\n    Network dnn;\n\n\n    //------------------------------------------------------------\n    Layer *conv1 = new Conv(1, 28, 28, 128, 3, 3, 1, 1, 1);\n    Layer *relu1 = new ReLU;\n    Layer *conv2 = new Conv(128, 28, 28, 128, 3, 3, 1, 1, 1);\n    Layer *relu2 = new ReLU;\n    dnn.add_layer(conv1);\n    dnn.add_layer(relu1);\n    dnn.add_layer(conv2);\n    dnn.add_layer(relu2);\n\n    Layer *b1_pool = new MaxPooling(128, 28, 28, 2, 2, 2);\n    dnn.add_layer(b1_pool);\n\n\n    Layer *fc_fc1 = new FullyConnected(b1_pool->output_dim(), 10);\n    Layer *fc_relu1 = new Softmax;\n\n    dnn.add_layer(fc_fc1);\n    dnn.add_layer(fc_relu1);\n\n    // loss\n    Loss *loss = new CrossEntropy;\n    dnn.add_loss(loss);\n    // train & test\n    SGD opt(0.001, 5e-4, 0.9, true);\n    // SGD opt(0.001);\n    const int n_epoch = 5;\n    const int batch_size = 14;\n    for (int epoch = 0; epoch < n_epoch; epoch++) {\n        shuffle_data(dataset.train_data, dataset.train_labels);\n        for (int start_idx = 0; start_idx < n_train; start_idx += batch_size) {\n            int ith_batch = start_idx / batch_size;\n            Matrix x_batch = dataset.train_data.block(0, start_idx, dim_in,\n                                                      std::min(batch_size, n_train - start_idx));\n            Matrix label_batch = dataset.train_labels.block(0, start_idx, 1,\n                                                            std::min(batch_size, n_train - start_idx));\n            Matrix target_batch = one_hot_encode(label_batch, 10);\n            if (false && ith_batch % 10 == 1) {\n                // std::cout << ith_batch << \"-th grad: \" << std::endl;\n                printf(\"ith_batch: %d-th grad: \\n\");\n                dnn.check_gradient(x_batch, target_batch, 10);\n            }\n\n            ocall_start_clock();\n            dnn.forward(x_batch);\n            ocall_end_clock(\"Forward: %f\\n\");\n\n\n            dnn.backward(x_batch, target_batch);\n            ocall_end_clock(\"Backward: %f\\n\");\n\n\n            // display\n            if (ith_batch % 2 == 0) {\n                //std::cout << ith_batch << \"-th batch, loss: \" << dnn.get_loss() << std::endl;\n                printf(\"%d-th, loss: %f\\n\", ith_batch, dnn.get_loss());\n            }\n            // optimize\n            dnn.update(opt);\n        }\n\n\n//        // test\n        dnn.forward(dataset.test_data);\n        float acc = compute_accuracy(dnn.output(), dataset.test_labels);\n        // std::cout << std::endl;\n        // std::cout << epoch + 1 << \"-th epoch, test acc: \" << acc << std::endl;\n        // std::cout << std::endl;\n    }\n    return;\n}\n\n#endif\n", "meta": {"hexsha": "f036541fc1451cecc904abdaadb4fe6642e456a2", "size": 4146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Enclave/small.cpp", "max_stars_repo_name": "zeyu-zh/TrustFL", "max_stars_repo_head_hexsha": "9e05a7e160bbf4fa1e7a426767f69158ea89b22d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-09-11T18:06:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T11:16:59.000Z", "max_issues_repo_path": "Enclave/small.cpp", "max_issues_repo_name": "zeyu-zh/TrustFL", "max_issues_repo_head_hexsha": "9e05a7e160bbf4fa1e7a426767f69158ea89b22d", "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": "Enclave/small.cpp", "max_forks_repo_name": "zeyu-zh/TrustFL", "max_forks_repo_head_hexsha": "9e05a7e160bbf4fa1e7a426767f69158ea89b22d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-01-29T02:52:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T09:10:56.000Z", "avg_line_length": 31.1729323308, "max_line_length": 103, "alphanum_fraction": 0.5750120598, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5319056728491309}}
{"text": "//\n// Created by dchansen on 6/16/18.\n//\n#include <numeric>\n#include <boost/math/constants/constants.hpp>\n#include \"correct_frequency_shift.h\"\n#include \"hoNDFFT.h\"\n#include \"hoNDArray_elemwise.h\"\nnamespace Gadgetron{\n    namespace FatWater {\n\n        using namespace std::complex_literals;\n        static constexpr float PI = boost::math::constants::pi<float>();\n\n        void correct_frequency_shift(hoNDArray<std::complex<float>> &species_images, const Parameters &parameters){\n\n\n            uint16_t X = species_images.get_size(0);\n            uint16_t Y = species_images.get_size(1);\n            uint16_t Z = species_images.get_size(2);\n            uint16_t CHA = species_images.get_size(3);\n            uint16_t N = species_images.get_size(4);\n            uint16_t S = species_images.get_size(5);\n            uint16_t LOC = species_images.get_size(6);\n\n\n\n            std::vector<size_t> sub_dimension = {X,Y,Z,CHA,N,1,1};\n            auto data_ptr = species_images.get_data_ptr();\n\n\n            hoNDFFT<float>::instance()->fft(&species_images,0);\n\n            for (int kspecies = 0; kspecies < parameters.species.size(); kspecies++){\n\n                auto& species = parameters.species[kspecies];\n\n                auto mean_frequency_offset = std::accumulate(\n                        species.amplitude_frequency_pairs.begin(), species.amplitude_frequency_pairs.end(),0.0f,\n                                              [](auto v, auto pair){ return v+pair.first.real()*pair.second;}\n                                              ) /\n                              std::accumulate(\n                        species.amplitude_frequency_pairs.begin(),species.amplitude_frequency_pairs.end(), 0.0f,\n                                            [](auto v, auto pair) { return v + pair.first.real();});\n                mean_frequency_offset *= parameters.field_strength_T*parameters.gyromagnetic_ratio_Mhz;\n\n                if (std::abs(mean_frequency_offset) < 1.0 ) continue;\n\n\n\n                hoNDArray<std::complex<float>> phase_ramp(X);\n\n                for (int i = 0; i < phase_ramp.get_number_of_elements(); i++){\n                    phase_ramp[i] = std::exp(2if*PI*parameters.sample_time_us*1e-6f*float(i)*mean_frequency_offset);\n                }\n\n                //Kristoffer will have a field day with this.\n                for (int kL = 0; kL < LOC; kL++)\n                    for (int kN = 0; kN < N; kN++)\n                        for (int kCHA = 0; kCHA < CHA; kCHA++)\n                            for (int kZ = 0; kZ < Z; kZ++)\n                                for (int kY = 0; kY < Y; kY++)\n                                    for (int kX = 0; kX < Y; kX++)\n                                        species_images(kX,kY,kZ,kCHA,kN,kspecies,kL) *= phase_ramp[kX];\n\n\n\n\n            }\n//\n            hoNDFFT<float>::instance()->ifft(&species_images,0);\n\n\n\n\n\n\n\n\n\n        }\n    }\n}\n\n", "meta": {"hexsha": "ce184c946108c52df720217fe98532c1bac365f6", "size": 2887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolboxes/fatwater/correct_frequency_shift.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "toolboxes/fatwater/correct_frequency_shift.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolboxes/fatwater/correct_frequency_shift.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["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.9647058824, "max_line_length": 116, "alphanum_fraction": 0.5355039834, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642806, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5319056728491308}}
{"text": "//#include \"test_cases.h\"\n//#include <iostream>\n//#include \"Mesh.h\"\n//#include \"vector_var.h\"\n//#include <stdio.h>      /* printf */\n//#include <iostream>\n//#include <math.h>\n//#include \"Boundary_Conditions.h\"\n//#include \"Solution.h\"\n//#include \"Solver.h\"\n//#include \"quad_bcs.h\"\n//#include \"external_forces.h\"\n//#include \"global_variables.h\"\n//#include <algorithm>\n//#include <string>\n//#include <sstream>\n//#include <boost/algorithm/string/replace.hpp>\n//#include <boost/filesystem.hpp>\n//#include <cstdio>\n//#include <ctime>\n//\n//using namespace std;\n//using namespace boost::filesystem;\n//\n//test_cases::test_cases()\n//{\n//    //ctor\n//}\n//\n//test_cases::~test_cases()\n//{\n//    //dtor\n//}\n//\n//void test_cases::west_to_east_poiseuille_flow(){\n//\n//    double X,Y,dx,dy,dt; // dt is streaming time step\n//    double kine_viscosity,tau;\n//    double reynolds, umax;\n//    double simulation_length;\n//    double delta_t; // time stepping step\n//    quad_bcs_plus bcs;\n//    double cs;\n//    double pressure_grad;\n//    global_variables globals;\n//    std::string output_file;\n//    double average_pressure;\n//    double pre_condition_gamma;\n//    std::clock_t start;\n//    double duration;\n//\n//    pre_condition_gamma = 1;\n//    //average_pressure =1*3*pre_condition_gamma;\n//    average_pressure =1*3;\n//\n//    //vector_var pressure_gradient(-0.01,0,0), origin(1.1,0,0), origin_loc(0,0,0) ;\n//    vector_var pressure_gradient(0,0,0), origin(average_pressure,0,0), origin_loc(0,0,0) ;\n//\n//    /// Parameters unique to test case\n//\n//    X= 16;\n//    Y= 4.4;\n//    dx= 0.4; // grid spacing\n//    dy = 0.4;  // grid spacing\n//    dt = 0.2;  // streaming time step -> dictates mach number -> grid spacing /2\n//\n//\n//    /// Error :: let dt = l_dx = l_dy i.e. lattice spacing\n//\n//    simulation_length = 5000;\n//    //kine_viscosity = U * X/ reynolds;\n//    kine_viscosity = 0.0833333;\n//\n//    delta_t = 0.3;  // time marching step\n//    cs = 1/sqrt(3);\n//\n//    reynolds = 33.7094;\n//    umax = 0.17557;\n//    // tau = 0.5 + Umax* Length / reynolds/dt  --- assumes c = 1.\n//\n//    tau = 0.5 + umax*X /reynolds /dt;\n//    tau = 0.5 + umax*X /reynolds /dt *pre_condition_gamma;\n//    //tau = 1/pre_condition_gammma*(tau-0.5) + 0.5;\n//\n//\n//\n//    pressure_grad =0;\n//\n//    //tau =0.75\n//    output_file = create_output_directory(globals.tolerance,dx,delta_t);\n//\n//\n//    // set boundary conditions for this test case\n//    //bcs.w_rho = 1.1*3*pre_condition_gammma;\n//    bcs.w_rho = 1.1*3*pre_condition_gamma;\n//    bcs.w_u = 0;\n//    bcs.w_v = 0;\n//    bcs.w_w = 0;\n//    bcs.w_type_vel = globals.neumann;\n//    bcs.w_type_rho = globals.dirichlet;\n//\n//    bcs.s_rho = 0;\n//    bcs.s_u = 0;\n//    bcs.s_v = 0;\n//    bcs.s_w = 0;\n//    bcs.s_type_vel= globals.dirichlet;\n//    bcs.s_type_rho = globals.neumann;\n//\n//    //bcs.e_rho = 1*3*pre_condition_gammma;\n//    bcs.e_rho = 1*3*pre_condition_gamma;\n//    bcs.e_u = 0;\n//    bcs.e_v = 0;\n//    bcs.e_w = 0;\n//    bcs.e_type_vel= globals.neumann;\n//    bcs.e_type_rho = globals.dirichlet;\n//\n//    bcs.n_rho = 0;\n//    bcs.n_u = 0;\n//    bcs.n_v = 0;\n//    bcs.n_w = 0;\n//    bcs.n_type_vel= globals.dirichlet;\n//    bcs.n_type_rho = globals.neumann;\n//\n//\n//\n//\n//\n//    /// Methods to run the test case\n//    //vector_var_tests();\n//\n//    // create Mesh\n//    Mesh mesh(X,Y,dx,dy);\n//\n//    // create boundary conditions\n//    Boundary_Conditions bc(mesh.get_num_x(), mesh.get_num_y());\n//    bc.assign_boundary_conditions(mesh.get_num_x(), mesh.get_num_y(),bcs);\n//\n//    // assign external force terms\n//    external_forces source_term(mesh.get_total_nodes());\n//    source_term.set_uniform_force(pressure_grad);\n//\n//    //create solution\n//    Solution soln(mesh.get_total_nodes());\n//    soln.assign_pressure_gradient(pressure_gradient,origin_loc,origin,mesh);\n//    soln.set_average_rho(average_pressure);\n//    // Solvec\n//\n//    Solver solve;\n//\n//    solve.Mesh_Solver(dt,tau,mesh,soln,bc,simulation_length, delta_t,dx ,output_file,source_term,\n//                              pre_condition_gamma);\n//\n//    soln.post_process(pre_condition_gamma);\n//    soln.output(output_file);\n//    tau = 1;\n//\n//}\n//\n//\n//\n//void test_cases::lid_driven_cavity_N(){\n//\n//    double X,Y,dx,dy,dt; // dt is streaming time step\n//    double reynolds,kine_viscosity,tau;\n//    double U;\n//\n//\n//    quad_bcs bcs;\n//    double cs,delta_t;\n//\n//    /// Parameters unique to test case\n//    reynolds = 1000;\n//    X= 100;\n//    Y=100;\n//    dx=1; // grid spacing\n//    dy = 1;  // grid spacing\n//    dt = 0.05;  // streaming time step let dt =dx = dy i.e. lattice spacing\n//    U = 1;\n//    simulation_length = 200;\n//    kine_viscosity = U * X/ reynolds;\n//    //kine_viscosity = 20;\n//    delta_t = 0.1;\n//    cs = 1/sqrt(3);\n//    tau = kine_viscosity + 0.5* pow(cs,2) *dt;\n//    //tau =0.75;\n//\n//\n//    // set boundary conditions for this test case\n//    bcs.w_rho = 1;\n//    bcs.w_u = 0;\n//    bcs.w_v = 0;\n//    bcs.w_w = 0;\n//\n//    bcs.s_rho = 1;\n//    bcs.s_u = 0;\n//    bcs.s_v = 0;\n//    bcs.s_w = 0;\n//\n//    bcs.e_rho = 1;\n//    bcs.e_u = 0;\n//    bcs.e_v = 0;\n//    bcs.e_w = 0;\n//\n//    bcs.n_rho = 1;\n//    bcs.n_u = 1;\n//    bcs.n_v = 0;\n//    bcs.n_w = 0;\n//\n//    /// Methods to run the test case\n//    //vector_var_tests();\n//\n//    // create Mesh\n//    Mesh mesh(X,Y,dx,dy);\n//\n//    // create boundary conditions\n//    Boundary_Conditions bc(mesh.get_num_x(), mesh.get_num_y());\n//    bc.assign_boundary_conditions(mesh.get_num_x(), mesh.get_num_y(),bcs);\n//\n//\n//    //create solution\n//    Solution soln(mesh.get_total_nodes());\n//\n//    // Solve\n//\n//    Solver solve;\n//    //solve.Mesh_Solver(dt,tau,mesh,soln,bc,simulation_length, delta_t, dx,tolerance);\n//\n//    tau = 1;\n//\n//}\n//void test_cases::west_to_east_couette_flow(){\n//\n//    double X,Y,dx,dy,dt; // dt is streaming time step\n//    double kine_viscosity,tau;\n//    double U;\n//    double simulation_length;\n//    double delta_t; // time stepping step\n//    quad_bcs bcs;\n//    double cs;\n//    double pre_conditioned_gamma;\n//    pre_conditioned_gamma = 1.0;\n//    std::string output_file;\n//\n//    /// Parameters unique to test case\n//\n//    X= 0.3;\n//    Y=1;\n//    dx=0.1; // grid spacing\n//    dy = 0.1;  // grid spacing\n//    dt = 0.05;  // streaming time step -> dictates mach number -> grid spacing /2\n//    /// Error :: let dt =dx = dy i.e. lattice spacing\n//    U = 2;\n//    simulation_length = 2500;\n//    //kine_viscosity = U * X/ reynolds;\n//    kine_viscosity = 0.6;\n//\n//    delta_t = 0.1;  // time marching step\n//    cs = 1/sqrt(3);\n//    tau = kine_viscosity + 0.5* pow(cs,2) *dt;\n//\n//\n//    //output_file = \"/home/brendan/Dropbox/PhD/Test Cases/Couette Flow/\";\n//\n//    output_file = \"C:/Users/brendan/Dropbox/PhD/Test Cases/Couette Flow/\";\n//    //tau =0.75;\n//\n//    // set boundary conditions for this test case\n//    bcs.w_rho = 1;\n//    bcs.w_u = 1;\n//    bcs.w_v = 0;\n//    bcs.w_w = 0;\n//    bcs.w_type = 3;\n//\n//    bcs.s_rho = 1;\n//    bcs.s_u = 0;\n//    bcs.s_v = 0;\n//    bcs.s_w = 0;\n//    bcs.s_type = 1;\n//\n//    bcs.e_rho = 0;\n//    bcs.e_u = 0;\n//    bcs.e_v = 0;\n//    bcs.e_w = 0;\n//    bcs.e_type =2;\n//\n//    bcs.n_rho = 1;\n//    bcs.n_u = U;\n//    bcs.n_v = 0;\n//    bcs.n_w = 0;\n//    bcs.n_type = 1;\n//\n//\n//\n//    /// Methods to run the test case\n//    //vector_var_tests();\n//\n//    // create Mesh\n//    Mesh mesh(X,Y,dx,dy);\n//\n//    // create boundary conditions\n//    Boundary_Conditions bc(mesh.get_num_x(), mesh.get_num_y());\n//    bc.assign_boundary_conditions(mesh.get_num_x(), mesh.get_num_y(),bcs);\n//\n//    // assign external force terms\n//    external_forces source_term(mesh.get_total_nodes());\n//    source_term.set_uniform_force(0.0);\n//\n//\n//    //create solution\n//    Solution soln(mesh.get_total_nodes());\n//    soln.set_average_rho(1.0);\n//\n//    // Solve\n//\n//    Solver solve;\n//    solve.Mesh_Solver(dt,tau,mesh,soln,bc,simulation_length, delta_t,dx ,output_file, source_term,pre_conditioned_gamma);\n//    soln.output(output_file);\n//    tau = 1;\n//\n//}\n//\n//void test_cases::east_to_west_couette_flow(){\n//\n//    double X,Y,dx,dy,dt; // dt is streaming time step\n//    double kine_viscosity,tau;\n//    double U;\n//    double simulation_length;\n//    double delta_t; // time stepping step\n//    quad_bcs bcs;\n//    double cs;\n//\n//    double pre_conditioned_gamma;\n//    pre_conditioned_gamma = 1.0;\n//\n//    std::string output_file;\n//     output_file = \"/home/brendan/Dropbox/PhD/Test Cases/Couette Flow/\";\n//    /// Parameters unique to test case\n//\n//    X= 0.3;\n//    Y=1;\n//    dx=0.1; // grid spacing\n//    dy = 0.1;  // grid spacing\n//    dt = 0.05;  // streaming time step -> dictates mach number -> grid spacing /2\n//    /// Error :: let dt =dx = dy i.e. lattice spacing\n//    U = -2;\n//    simulation_length = 2500;\n//    //kine_viscosity = U * X/ reynolds;\n//    kine_viscosity = 0.6;\n//\n//    delta_t = 0.1;  // time marching step\n//    cs = 1/sqrt(3);\n//    tau = kine_viscosity + 0.5* pow(cs,2) *dt;\n//    //tau =0.75;\n//\n//\n//    output_file = \"/home/brendan/Dropbox/PhD/Test Cases/Couette Flow/\";\n//\n//    // set boundary conditions for this test case\n//    bcs.w_rho = 0;\n//    bcs.w_u = 0;\n//    bcs.w_v = 0;\n//    bcs.w_w = 0;\n//    bcs.w_type = 2;\n//\n//    bcs.s_rho = 1;\n//    bcs.s_u = 0;\n//    bcs.s_v = 0;\n//    bcs.s_w = 0;\n//    bcs.s_type = 1;\n//\n//    bcs.e_rho = 1;\n//    bcs.e_u = 0;\n//    bcs.e_v = 0;\n//    bcs.e_w = 0;\n//    bcs.e_type =3;\n//\n//    bcs.n_rho = 1;\n//    bcs.n_u = U;\n//    bcs.n_v = 0;\n//    bcs.n_w = 0;\n//    bcs.n_type = 1;\n//\n//\n//\n//    /// Methods to run the test case\n//    //vector_var_tests();\n//\n//    // create Mesh\n//    Mesh mesh(X,Y,dx,dy);\n//\n//    // create boundary conditions\n//    Boundary_Conditions bc(mesh.get_num_x(), mesh.get_num_y());\n//    bc.assign_boundary_conditions(mesh.get_num_x(), mesh.get_num_y(),bcs);\n//\n//    // assign external force terms\n//    external_forces source_term(mesh.get_total_nodes());\n//    source_term.set_uniform_force(0.0);\n//\n//    //create solution\n//    Solution soln(mesh.get_total_nodes());\n//\n//    // Solve\n//\n//\n//    Solver solve;\n//    solve.Mesh_Solver(dt,tau,mesh,soln,bc,simulation_length, delta_t,dx, output_file,source_term,pre_conditioned_gamma);\n//    soln.output(output_file);\n//\n//    tau = 1;\n//\n//}\n//void test_cases::north_to_south_couette_flow(){\n//\n//    double X,Y,dx,dy,dt; // dt is streaming time step\n//    double kine_viscosity,tau;\n//    double U;\n//    double simulation_length;\n//    double delta_t; // time stepping step\n//    quad_bcs bcs;\n//    double cs;\n//    std::string output_file;\n//\n//    double pre_conditioned_gamma;\n//    pre_conditioned_gamma = 1.0;\n//     output_file = \"/home/brendan/Dropbox/PhD/Test Cases/Couette Flow/\";\n//\n//    /// Parameters unique to test case\n//\n//    X= 1;\n//    Y=0.3;\n//    dx=0.1; // grid spacing\n//    dy = 0.1;  // grid spacing\n//    dt = 0.05;  // streaming time step -> dictates mach number -> grid spacing /2\n//    /// Error :: let dt =dx = dy i.e. lattice spacing\n//    U = -2;\n//    simulation_length = 2500;\n//    //kine_viscosity = U * X/ reynolds;\n//    kine_viscosity = 0.6;\n//\n//    delta_t = 0.1;  // time marching step\n//    cs = 1/sqrt(3);\n//    tau = kine_viscosity + 0.5* pow(cs,2) *dt;\n//    //tau =0.75;\n//\n//\n//\n//    // set boundary conditions for this test case\n//    bcs.w_rho = 1;\n//    bcs.w_u = 0;\n//    bcs.w_v = 0;\n//    bcs.w_w = 0;\n//    bcs.w_type = 1;\n//\n//    bcs.s_rho = 0;\n//    bcs.s_u = 0;\n//    bcs.s_v = 0;\n//    bcs.s_w = 0;\n//    bcs.s_type = 2;\n//\n//    bcs.e_rho = 1;\n//    bcs.e_u = 0;\n//    bcs.e_v = U;\n//    bcs.e_w = 0;\n//    bcs.e_type =1;\n//\n//    bcs.n_rho = 1;\n//    bcs.n_u = 0;\n//    bcs.n_v = 0;\n//    bcs.n_w = 0;\n//    bcs.n_type = 3;\n//\n//\n//\n//    /// Methods to run the test case\n//    //vector_var_tests();\n//\n//    // create Mesh\n//    Mesh mesh(X,Y,dx,dy);\n//\n//    // create boundary conditions\n//    Boundary_Conditions bc(mesh.get_num_x(), mesh.get_num_y());\n//    bc.assign_boundary_conditions(mesh.get_num_x(), mesh.get_num_y(),bcs);\n//\n//    // assign external force terms\n//    external_forces source_term(mesh.get_total_nodes());\n//    source_term.set_uniform_force(0.0);\n//\n//    //create solution\n//    Solution soln(mesh.get_total_nodes());\n//\n//    // Solve\n//\n//    Solver solve;\n//    solve.Mesh_Solver(dt,tau,mesh,soln,bc,simulation_length, delta_t,dx,output_file,source_term,pre_conditioned_gamma);\n//\n//    tau = 1;\n//\n//}\n//\n//void test_cases::south_to_north_couette_flow(){\n//\n//    double X,Y,dx,dy,dt; // dt is streaming time step\n//    double kine_viscosity,tau;\n//    double U;\n//    double simulation_length;\n//    double delta_t; // time stepping step\n//    quad_bcs bcs;\n//    double cs;\n//    std::string output_file;\n//\n//    double pre_conditioned_gamma;\n//    pre_conditioned_gamma = 1.0;\n//     output_file = \"/home/brendan/Dropbox/PhD/Test Cases/Couette Flow/\";\n//\n//    /// Parameters unique to test case\n//\n//    X= 1;\n//    Y=0.3;\n//    dx=0.1; // grid spacing\n//    dy = 0.1;  // grid spacing\n//    dt = 0.05;  // streaming time step -> dictates mach number -> grid spacing /2\n//    /// Error :: let dt =dx = dy i.e. lattice spacing\n//    U = 2;\n//    simulation_length = 2500;\n//    //kine_viscosity = U * X/ reynolds;\n//    kine_viscosity = 0.6;\n//\n//    delta_t = 0.1;  // time marching step\n//    cs = 1/sqrt(3);\n//    tau = kine_viscosity + 0.5* pow(cs,2) *dt;\n//    //tau =0.75;\n//\n//    // set boundary conditions for this test case\n//    bcs.w_rho = 1;\n//    bcs.w_u = 0;\n//    bcs.w_v = 0;\n//    bcs.w_w = 0;\n//    bcs.w_type = 1;\n//\n//    bcs.s_rho = 1;\n//    bcs.s_u = 0;\n//    bcs.s_v = 0;\n//    bcs.s_w = 0;\n//    bcs.s_type = 3;\n//\n//    bcs.e_rho = 1;\n//    bcs.e_u = 0;\n//    bcs.e_v = U;\n//    bcs.e_w = 0;\n//    bcs.e_type =1;\n//\n//    bcs.n_rho = 0;\n//    bcs.n_u = 0;\n//    bcs.n_v = 0;\n//    bcs.n_w = 0;\n//    bcs.n_type = 2;\n//\n//\n//\n//    /// Methods to run the test case\n//    //vector_var_tests();\n//\n//    // create Mesh\n//    Mesh mesh(X,Y,dx,dy);\n//\n//    // create boundary conditions\n//    Boundary_Conditions bc(mesh.get_num_x(), mesh.get_num_y());\n//    bc.assign_boundary_conditions(mesh.get_num_x(), mesh.get_num_y(),bcs);\n//\n//    // assign external force terms\n//    external_forces source_term(mesh.get_total_nodes());\n//    source_term.set_uniform_force(0.0);\n//\n//    //create solution\n//    Solution soln(mesh.get_total_nodes());\n//\n//    // Solve\n//\n//    Solver solve;\n//    solve.Mesh_Solver(dt,tau,mesh,soln,bc,simulation_length, delta_t,dx, output_file, source_term,pre_conditioned_gamma);\n//\n//    tau = 1;\n//\n//}\n//\n//std::string test_cases::create_output_directory(double tol, double dx, double dt){\n//\n//    std::string output_file;\n//    std::string folder;\n//    std::ostringstream s;\n//    //output_file = \"C:/Users/brendan/Dropbox/PhD/Test Cases/Poiseuille Flow/\";\n//\n//    output_file = \"/home/brendan/Dropbox/PhD/Test Cases/Poiseuille Flow/\";\n//    s << \"tol \" << tol << \" x \" << dx\n//     << \" t \" << dt;\n//     folder = s.str();\n//    //folder.replace(folder.begin(),folder.end(), \".\",  \"_\");\n//    boost::replace_all(folder, \".\" , \"_\");\n//    output_file = output_file + folder;\n//\n//    boost::filesystem::path dir(output_file);\n//    boost::filesystem::create_directories(dir);\n//\n//    return output_file;\n//\n//}\n//\n//void test_cases::vector_var_tests(){\n//     vector_var a,b,c,d,e,f;\n//\n//    a.x = 3;\n//    a.y = 4;\n//    a.z = 0;\n//\n//    b.x = 2;\n//    b.y = 2;\n//    b.z = 2;\n//\n//    c.x = 4;\n//    c.y = -3;\n//    c.z = 0;\n//\n//    d.x= 0;\n//    d.y = 0;\n//    d.z = 0;\n//\n//    f.x = 5;\n//    f.y = 5;\n//    f.z = 0;\n//\n//\n//\n//\n//    double mag , dp, ang;\n//    mag = a.Magnitude();\n//\n//    cout <<  \"Magnitude of a:\" << mag << endl ;\n//    dp = a.Dot_Product(b);\n//    cout << \"Dot product of a and b: \" << dp << endl ;\n//    ang = a.Angle_Between_Vectors(c);\n//    ang = ang *360/2/M_PI;\n//    cout << \"angle between a and c: \" << ang << endl ;\n//    e.Get_Gradient(10,20,d,b);\n//    cout << \"gradient vector between d and b =\" << e.x << \",\" << e.y << \",\" << e.z << endl ;\n//\n//\n//\n//}\n", "meta": {"hexsha": "03802650dd594be36ce1a5630dcb71d309bd5696", "size": 16143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_cases.cpp", "max_stars_repo_name": "CHRG-Developer/LBFS-IBM-ADE-SP", "max_stars_repo_head_hexsha": "6a214c48aef26f2c7c865183a3d612d1c8174257", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-27T13:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-27T13:14:12.000Z", "max_issues_repo_path": "test_cases.cpp", "max_issues_repo_name": "CHRG-Developer/LBFS-IBM-ADE-SP", "max_issues_repo_head_hexsha": "6a214c48aef26f2c7c865183a3d612d1c8174257", "max_issues_repo_licenses": ["MIT"], "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_cases.cpp", "max_forks_repo_name": "CHRG-Developer/LBFS-IBM-ADE-SP", "max_forks_repo_head_hexsha": "6a214c48aef26f2c7c865183a3d612d1c8174257", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-17T12:48:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T12:48:36.000Z", "avg_line_length": 24.873651772, "max_line_length": 123, "alphanum_fraction": 0.5692869975, "num_tokens": 5395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.6334102636778403, "lm_q1q2_score": 0.5318961113420166}}
{"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//// Body panels creation\n// Compute panel collocation point, surface, vertices, normal, longitudinal, transverse and perpendicular unit vectors\n// from data contained into sGrid\n//\n// I/O:\n// - sGrid: temporary dynamic array containing body panel vertices\n// - bPan: body panels (structure)\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"create_panel.h\"\n\n#define NDIM 3\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid create_panel(MatrixX3d &sGrid, Network &bPan) {\n\n    // Temporary variables\n    double norm = 0;\n    int panIdx;\n    int c1, c2, c3, c4;\n    Vector3d v1(NDIM), v2(NDIM);\n\n    //// Begin\n    cout << \"Creating panels... \" << flush;\n\n    // Resizing network matrices\n    bPan.CG.resize(bPan.nP, NDIM);\n    bPan.v0.resize(bPan.nP, NDIM);\n    bPan.v1.resize(bPan.nP, NDIM);\n    bPan.v2.resize(bPan.nP, NDIM);\n    bPan.v3.resize(bPan.nP, NDIM);\n    bPan.S.resize(bPan.nP, 1);\n    bPan.n.resize(bPan.nP, NDIM);\n    bPan.l.resize(bPan.nP, NDIM);\n    bPan.t.resize(bPan.nP, NDIM);\n    bPan.p.resize(bPan.nP, NDIM);\n\n    // Compute corner points, collocation points and vectors\n    for (int i = 0; i < bPan.nC_; ++i) {\n        for (int k = 0; k < bPan.nS_; ++k) {\n\n            panIdx = i + k * (bPan.nC_);\n            c1 = i + k * bPan.nC;\n            c2 = i + 1 + k * bPan.nC;\n            c3 = i + 1 + (k+1) *bPan.nC;\n            c4 = i + (k+1) * bPan.nC;\n\n            bPan.v0(panIdx,0) = sGrid(c1,0); // pts[i][k]\n            bPan.v1(panIdx,0) = sGrid(c2,0); // pts[i+1][k]\n            bPan.v2(panIdx,0) = sGrid(c3,0); // pts[i+1][k+1]\n            bPan.v3(panIdx,0) = sGrid(c4,0); // pts[i][k+1]\n            bPan.v0(panIdx,1) = sGrid(c1,1);\n            bPan.v1(panIdx,1) = sGrid(c2,1);\n            bPan.v2(panIdx,1) = sGrid(c3,1);\n            bPan.v3(panIdx,1) = sGrid(c4,1);\n            bPan.v0(panIdx,2) = sGrid(c1,2);\n            bPan.v1(panIdx,2) = sGrid(c2,2);\n            bPan.v2(panIdx,2) = sGrid(c3,2);\n            bPan.v3(panIdx,2) = sGrid(c4,2);\n\n            bPan.CG(panIdx,0) = (bPan.v0(panIdx,0) + bPan.v1(panIdx,0) + bPan.v2(panIdx,0) + bPan.v3(panIdx,0)) / 4;\n            bPan.CG(panIdx,1) = (bPan.v0(panIdx,1) + bPan.v1(panIdx,1) + bPan.v2(panIdx,1) + bPan.v3(panIdx,1)) / 4;\n            bPan.CG(panIdx,2) = (bPan.v0(panIdx,2) + bPan.v1(panIdx,2) + bPan.v2(panIdx,2) + bPan.v3(panIdx,2)) / 4;\n\n            bPan.l(panIdx,0) = (bPan.v0(panIdx,0) + bPan.v3(panIdx,0) - bPan.v1(panIdx,0) - bPan.v2(panIdx,0)) / 4;\n            bPan.l(panIdx,1) = (bPan.v0(panIdx,1) + bPan.v3(panIdx,1) - bPan.v1(panIdx,1) - bPan.v2(panIdx,1)) / 4;\n            bPan.l(panIdx,2) = (bPan.v0(panIdx,2) + bPan.v3(panIdx,2) - bPan.v1(panIdx,2) - bPan.v2(panIdx,2)) / 4;\n            bPan.l.row(panIdx) /= bPan.l.row(panIdx).norm();\n\n            bPan.t(panIdx,0) = (bPan.v2(panIdx,0) + bPan.v3(panIdx,0) - bPan.v0(panIdx,0) - bPan.v1(panIdx,0)) / 4;\n            bPan.t(panIdx,1) = (bPan.v2(panIdx,1) + bPan.v3(panIdx,1) - bPan.v0(panIdx,1) - bPan.v1(panIdx,1)) / 4;\n            bPan.t(panIdx,2) = (bPan.v2(panIdx,2) + bPan.v3(panIdx,2) - bPan.v0(panIdx,2) - bPan.v1(panIdx,2)) / 4;\n            bPan.t.row(panIdx) /= bPan.t.row(panIdx).norm();\n        }\n    }\n    // Compute panel normals and surfaces\n    for (int i = 0; i < bPan.nC_; ++i) {\n        for (int k = 0; k < bPan.nS_; ++k) {\n            panIdx = i + k * (bPan.nC_);\n\n            v1(0) = bPan.v2(panIdx,0) - bPan.v0(panIdx,0);\n            v2(0) = bPan.v1(panIdx,0) - bPan.v3(panIdx,0);\n            v1(1) = bPan.v2(panIdx,1) - bPan.v0(panIdx,1);\n            v2(1) = bPan.v1(panIdx,1) - bPan.v3(panIdx,1);\n            v1(2) = bPan.v2(panIdx,2) - bPan.v0(panIdx,2);\n            v2(2) = bPan.v1(panIdx,2) - bPan.v3(panIdx,2);\n\n            bPan.n.row(panIdx) = v1.cross(v2);\n            norm = bPan.n.row(panIdx).norm();\n\n            bPan.S(panIdx) = norm/2;\n            bPan.n.row(panIdx) /= norm;\n        }\n    }\n    // Compute panel perpendicular vector\n    for (int i = 0; i < bPan.nC_; ++i) {\n        for (int k = 0; k < bPan.nS_; ++k) {\n            panIdx = i + k * (bPan.nC_);\n            bPan.p.row(panIdx) = bPan.n.row(panIdx).cross(bPan.l.row(panIdx));\n        }\n    }\n\n    //// Control display\n    cout << \"Done!\" << endl;\n    #ifdef VERBOSE\n        cout << \"Collocation points: \" << bPan.CG.rows() << 'X' << bPan.CG.cols() << endl;\n        for (int i = 0; i < bPan.nP; ++i)\n            cout << i << ' ' << bPan.CG(i,0) << ' ' << bPan.CG(i,1) << ' ' << bPan.CG(i,2) << endl;\n        cout << \"Panel surfaces: \" << bPan.S.rows() << 'X' << bPan.S.cols() << endl;\n        for (int i = 0; i < bPan.nP; ++i)\n            cout << i << ' ' << bPan.S(i) << endl;\n        cout << \"Unit normals: \" << bPan.n.rows() << 'X' << bPan.n.cols() << endl;\n        for (int i = 0; i < bPan.nP; ++i)\n            cout << i << ' ' << bPan.n(i,0) << ' ' << bPan.n(i,1) << ' ' << bPan.n(i,2) << endl;\n        cout << \"Unit longitudinal vectors: \" << bPan.l.rows() << 'X' << bPan.l.cols() << endl;\n        for (int i = 0; i < bPan.nP; ++i)\n            cout << i << ' ' << bPan.l(i,0) << ' ' << bPan.l(i,1) << ' ' << bPan.l(i,2) << endl;\n        cout << \"Unit transverse vectors: \" << bPan.t.rows() << 'X' << bPan.t.cols() << endl;\n        for (int i = 0; i < bPan.nP; ++i)\n            cout << i << ' ' << bPan.t(i,0) << ' ' << bPan.t(i,1) << ' ' << bPan.t(i,2) << endl;\n        cout << \"Unit perpendicular vectors: \" << bPan.p.rows() << 'X' << bPan.p.cols() << endl;\n        for (int i = 0; i < bPan.nP; ++i)\n            cout << i << ' ' << bPan.p(i,0) << ' ' << bPan.p(i,1) << ' ' << bPan.p(i,2) << endl;\n    #endif\n    cout << endl;\n}", "meta": {"hexsha": "752bbcfa8406d831a11768477ef9d65edfebaf8b", "size": 6224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/create_panel.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/create_panel.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/create_panel.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": 42.0540540541, "max_line_length": 118, "alphanum_fraction": 0.5257069409, "num_tokens": 2334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.531896108801521}}
{"text": "#include \"func.hpp\"\n\n#include <core/func.hpp>\n\n#include <boost/python.hpp>\n\nnamespace python {\n\n\n  // TODO this should go somewhere else\n  template<class U>\n  struct norm2 : ::func< scalar<U> ( U ) > {\n\n\tusing To = scalar<U>;\n\tusing From = U;\n\n\tusing dTo = deriv<To>;\n\tusing dFrom = deriv<From>;\n  \n\tvirtual std::size_t size( slice<const From> ) const {\n\t  return 1;\n\t}\n  \n\tvirtual void apply( slice<To> to, slice<const From> from) const {\n\t  to[0] = 0;\n\n\t  for(const From& x : from) {\n\t\tto[0] += traits<From>::dot(x, x);\n\t  }\n\t  \n\t  to[0] /= 2.0;\n\t}\n  \n\n\tvirtual void jacobian(triplet_iterator block, slice<const From> from) const {\n\n\t  unsigned off = 0;\n\n\t  for(const From& x : from) {\n\t\tfor(unsigned j = 0, m = traits<From >::dim; j < m; ++j, ++off) {\n\t\t  *block++ = triplet(0, off, traits<From>::coord(j, x));\n\t\t}\n\t  }\n\t  \n\t}\n\n\n\tvirtual void hessian(triplet_iterator block, \n\t\t\t\t\t\t slice< const dTo > lambda, slice< const dFrom > from) const {\n\t  for(int i = 0, n = from.size() * traits< From >::dim; i < n; ++i) {\n\t\t*block++ = triplet(i, i, lambda[0]);\n\t  }\n\t}\n  \n  };\n  \n  \n  void func::module() {\n\tusing namespace boost::python;\n\tusing ::func;\n\n\tclass_<func_base, std::shared_ptr<func_base>, boost::noncopyable >(\"func_base\", no_init);\n\n\t// TODO moar\n\tclass_<norm2<vec3>, std::shared_ptr<norm2<vec3>>,\n\t\t   bases<func_base>, boost::noncopyable >(\"norm2_vec3\");\n  }\n\n}\n", "meta": {"hexsha": "d304ff211d1a907f8289b5696d3a1ca29078241c", "size": 1375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pouf/python/func.cpp", "max_stars_repo_name": "maxime-tournier/cpp", "max_stars_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pouf/python/func.cpp", "max_issues_repo_name": "maxime-tournier/cpp", "max_issues_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pouf/python/func.cpp", "max_forks_repo_name": "maxime-tournier/cpp", "max_forks_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_forks_repo_licenses": ["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.6428571429, "max_line_length": 90, "alphanum_fraction": 0.6007272727, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.531896108071427}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_CONSTANTS_INV2PI_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_INV2PI_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\n\nnamespace nt2\n{\n  namespace tag\n  {\n   /*!\n     @brief Inv2pi generic tag\n\n     Represents the Inv2pi constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    BOOST_SIMD_CONSTANT_REGISTER( Inv2pi, double\n                                  , 0, 0x3e22f983\n                                  , 0x3fc45f306dc9c883ll\n                                  )\n  }\n  namespace ext\n  {\n   template<class Site, class... Ts>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Inv2pi, Site> dispatching_Inv2pi(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n   {\n     return generic_dispatcher<tag::Inv2pi, Site>();\n   }\n   template<class... Args>\n   struct impl_Inv2pi;\n  }\n  /*!\n    Constant \\f$\\frac1\\pi\\f$.\n\n    @par Semantic:\n\n    For type T0:\n\n    @code\n    T0 r = Inv2pi<T0>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T0 r = rec(Two<T0>()*Pi<T0>());\n    @endcode\n\n    @return a value of type T0\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Inv2pi, Inv2pi);\n}\n\n#endif\n\n", "meta": {"hexsha": "209a04f77004ed61c68fac126c43fe6568c578fe", "size": 1772, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/inv2pi.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/trigonometric/include/nt2/trigonometric/constants/inv2pi.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/trigonometric/include/nt2/trigonometric/constants/inv2pi.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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.447761194, "max_line_length": 168, "alphanum_fraction": 0.5632054176, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5318883413003656}}
{"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 n_points>\nvoid generate_gauss_1d(\n    std::array< float, n_points >& values,\n    std::array< float, 4 > const & parameters )\n{\n    float const a = parameters[ 0 ];\n    float const x0 = parameters[ 1 ];\n    float const s = parameters[ 2 ];\n    float const b = parameters[ 3 ];\n\n    for ( int point_index = 0; point_index < n_points; point_index++ )\n    {\n        float const argx = ( ( point_index - x0 )*( point_index - x0 ) ) / ( 2.f * s * s );\n        float const ex = exp( -argx );\n        values[ point_index ] = a * ex + b;\n    }\n}\n\nBOOST_AUTO_TEST_CASE( Gauss_Fit_1D )\n{\n\t/*\n\t\tPerforms a single fit using the GAUSS_1D model.\n\t\t- Doesn't use user_info or weights.\n\t\t- No noise is added.\n\t\t- Checks fitted parameters equalling the true parameters.\n\t*/\n\n    std::size_t const n_fits{ 1 } ;\n    std::size_t const n_points{ 5 } ;\n\n    std::array< float, 4 > const true_parameters{ { 4.f, 2.f, 0.5f, 1.f } };\n\n    std::array< float, n_points > data{};\n    generate_gauss_1d( data, true_parameters );\n\n    std::array< float, 4 > initial_parameters{ { 2.f, 1.5f, 0.3f, 0.f } };\n\n    float tolerance{ 0.001f };\n\n    int max_n_iterations{ 10 };\n\n    std::array< int, 4 > parameters_to_fit{ { 1, 1, 1, 1 } };\n\n    std::array< float, 4 > 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                0,\n                GAUSS_1D,\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    BOOST_CHECK( output_states == 0 );\n    BOOST_CHECK( output_chi_square < 1e-6f );\n    BOOST_CHECK( output_n_iterations <= max_n_iterations );\n\n    BOOST_CHECK( std::fabsf(output_parameters[ 0 ] - true_parameters[ 0 ] ) < 1e-6f );\n    BOOST_CHECK( std::fabsf(output_parameters[ 1 ] - true_parameters[ 1 ] ) < 1e-6f );\n    BOOST_CHECK( std::fabsf(output_parameters[ 2 ] - true_parameters[ 2 ] ) < 1e-6f );\n    BOOST_CHECK( std::fabsf(output_parameters[ 3 ] - true_parameters[ 3 ] ) < 1e-6f );\n}\n", "meta": {"hexsha": "81a8c64afcf3a1467bb4bb87d4fc993b882349d5", "size": 2558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gpufit/tests/Gauss_Fit_1D.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_1D.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_1D.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": 29.0681818182, "max_line_length": 91, "alphanum_fraction": 0.577404222, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5318883365330949}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2004 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 exchangerate.cpp from test-suite\n\n#ifndef cl_adjoint_exchange_rate_impl_hpp\n#define cl_adjoint_exchange_rate_impl_hpp\n#pragma once\n\n#include \"adjointexchangeratetest.hpp\"\n#include \"adjointtestutilities.hpp\"\n#include \"adjointtestbase.hpp\"\n#include \"utilities.hpp\"\n#include <ql/exchangerate.hpp>\n#include <ql/currencies/europe.hpp>\n#include <ql/currencies/america.hpp>\n#include <ql/currencies/asia.hpp>\n#include <ql/currencies/exchangeratemanager.hpp>\n#include <boost/make_shared.hpp>\n#include <ql/quantlib.hpp>\n\nusing namespace QuantLib;\nusing namespace std;\nusing namespace boost::unit_test_framework;\n\nnamespace\n{\n   struct ExchangeTest\n        : cl::AdjointTest<ExchangeTest>\n    {\n        explicit ExchangeTest(Size size)\n            : AdjointTest()\n            , size_(size)\n            , rates_(size)\n            , derivedAmount_(1)\n            , EUR_(EURCurrency())\n            , USD_(USDCurrency())\n            , GBP_(GBPCurrency())\n            , m1_(50000.0 * GBP_)\n        {\n            Money::conversionType = Money::NoConversion;\n            rates_ = { 1.2042, 0.6612 };\n        }\n\n        Size indepVarNumber() { return size_; }\n\n        Size depVarNumber() { return 1; }\n\n        Size minPerfIteration() { return 0; }\n\n        void recordTape()\n        {\n            cl::Independent(rates_);\n            calculateAmount();\n            f_ = std::make_unique<cl::tape_function<double>>(rates_, derivedAmount_);\n        }\n\n        void calculateAmount()\n        {\n            ExchangeRate derived = ExchangeRate::chain(ExchangeRate(EUR_, USD_, rates_[0]), ExchangeRate(EUR_, GBP_, rates_[1]));\n            derivedAmount_[0] = derived.exchange(m1_).value();\n        }\n\n        // Calculates derivatives using analytical formula.\n        void calcAnalytical()\n        {\n            analyticalResults_.resize(size_, 0.0);\n            analyticalResults_[0] = m1_.value() / 0.6612;\n            analyticalResults_[1] = -m1_.value()*rates_[0] / std::pow(rates_[1], 2);\n        }\n\n        double relativeTol() const { return 1e-3; }\n\n        double absTol() const { return 1e-5; }\n\n        Size size_;\n        std::vector<cl::tape_double> rates_;\n        std::vector<cl::tape_double> derivedAmount_;\n        Currency EUR_, USD_, GBP_;\n        Money m1_;\n    };\n}\n\n#endif\n", "meta": {"hexsha": "a043a6b06012634ae93a5c46e894b7968047ba4f", "size": 3107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointexchangerateimpl.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/adjointexchangerateimpl.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/adjointexchangerateimpl.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": 30.4607843137, "max_line_length": 129, "alphanum_fraction": 0.6536852269, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.531888324177728}}
{"text": "/*\nCopyright 2008 Intel Corporation\n\nUse, modification and distribution are subject to the Boost Software License,\nVersion 1.0. (See accompanying file LICENSE_1_0.txt or copy at\nhttp://www.boost.org/LICENSE_1_0.txt).\n*/\n#include <boost/polygon/polygon.hpp>\n#include <cassert>\nnamespace gtl = boost::polygon;\nusing namespace boost::polygon::operators;\n\n//lets make the body of main from point_usage.cpp\n//a generic function parameterized by point type\ntemplate <typename Point>\nvoid test_point() {\n  //constructing a gtl point\n  int x = 10;\n  int y = 20;\n  //Point pt(x, y);\n  Point pt = gtl::construct<Point>(x, y);\n  assert(gtl::x(pt) == 10);\n  assert(gtl::y(pt) == 20);\n\n  //a quick primer in isotropic point access\n  typedef gtl::orientation_2d O;\n  using gtl::HORIZONTAL;\n  using gtl::VERTICAL;\n  O o = HORIZONTAL;\n  assert(gtl::x(pt) == gtl::get(pt, o));\n\n  o = o.get_perpendicular();\n  assert(o == VERTICAL);\n  assert(gtl::y(pt) == gtl::get(pt, o));\n\n  gtl::set(pt, o, 30);\n  assert(gtl::y(pt) == 30);\n\n  //using some of the library functions\n  //Point pt2(10, 30);\n  Point pt2 = gtl::construct<Point>(10, 30);\n  assert(gtl::equivalence(pt, pt2));\n\n  gtl::transformation<int> tr(gtl::axis_transformation::SWAP_XY);\n  gtl::transform(pt, tr);\n  assert(gtl::equivalence(pt, gtl::construct<Point>(30, 10)));\n\n  gtl::transformation<int> tr2 = tr.inverse();\n  assert(tr == tr2); //SWAP_XY is its own inverse transform\n\n  gtl::transform(pt, tr2);\n  assert(gtl::equivalence(pt, pt2)); //the two points are equal again\n\n  gtl::move(pt, o, 10); //move pt 10 units in y\n  assert(gtl::euclidean_distance(pt, pt2) == 10.0f);\n\n  gtl::move(pt, o.get_perpendicular(), 10); //move pt 10 units in x\n  assert(gtl::manhattan_distance(pt, pt2) == 20);\n}\n\n//Now lets declare our own point type\n//Bjarne says that if a class doesn't maintain an\n//invariant just use a struct.\nstruct CPoint {\n  int x;\n  int y;\n};\n\n//There, nice a simple...but wait, it doesn't do anything\n//how do we use it to do all the things a point needs to do?\n\n\n//First we register it as a point with boost polygon\nnamespace boost { namespace polygon {\n    template <>\n    struct geometry_concept<CPoint> { typedef point_concept type; };\n\n\n    //Then we specialize the gtl point traits for our point type\n    template <>\n    struct point_traits<CPoint> {\n      typedef int coordinate_type;\n\n      static inline coordinate_type get(const CPoint& point,\n\t\t\t\t\torientation_2d orient) {\n\tif(orient == HORIZONTAL)\n\t  return point.x;\n\treturn point.y;\n      }\n    };\n\n    template <>\n    struct point_mutable_traits<CPoint> {\n      typedef int coordinate_type;\n\n\n      static inline void set(CPoint& point, orientation_2d orient, int value) {\n\tif(orient == HORIZONTAL)\n\t  point.x = value;\n\telse\n\t  point.y = value;\n      }\n      static inline CPoint construct(int x_value, int y_value) {\n\tCPoint retval;\n\tretval.x = x_value;\n\tretval.y = y_value;\n\treturn retval;\n      }\n    };\n  } }\n\n//Now lets see if the CPoint works with the library functions\nint main() {\n  test_point<CPoint>(); //yay! All your testing is done for you.\n  return 0;\n}\n\n//Now you know how to map a user type to the library point concept\n//and how to write a generic function parameterized by point type\n//using the library interfaces to access it.\n", "meta": {"hexsha": "523234f7fca72ed216a06c04a2bd858c1093d650", "size": 3265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/polygon/example/gtl_custom_point.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/polygon/example/gtl_custom_point.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/polygon/example/gtl_custom_point.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": 26.9834710744, "max_line_length": 79, "alphanum_fraction": 0.6836140888, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.531888324177728}}
{"text": "#include <iostream>\n#include <Eigen/Core>\nusing namespace Eigen;\n\ntemplate<typename Derived>\nvoid print_size(const EigenBase<Derived> &b) {\n  std::cout << \"size (rows, cols): \" << b.size() << \" (\" << b.rows()\n            << \", \" << b.cols() << \")\" << std::endl;\n}\n\nint main() {\n  Vector3f v;\n  print_size(v);\n  // v.asDiagonal() returns a 3x3 diagonal matrix pseudo-expression\n  print_size(v.asDiagonal());\n}\n", "meta": {"hexsha": "e16339099a2298d5e573e6d210f882c67704ae9a", "size": 409, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen-3.3/doc/examples/function_taking_eigenbase.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/function_taking_eigenbase.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/function_taking_eigenbase.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": 24.0588235294, "max_line_length": 68, "alphanum_fraction": 0.6112469438, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5318851416252715}}
{"text": "#include \"algorithm/BruteForce.hpp\"\n#include \"generator/Generation.hpp\"\n#include \"sudoku/Grid.hpp\"\n#include <boost/program_options.hpp>\n#include <iostream>\n#include <random>\n#include <string>\n\nnamespace po = boost::program_options;\n\nauto getProgramOptions(int argc, char **argv, po::options_description desc) {\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);\n  return vm;\n}\n\nauto createOptionsDescription() {\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()(\"help,h\", \"Produce help message\")(\n      \"inline,i\", po::value<std::string>(),\n      \"Grid written line by line, e.g. 123000456789... with total of 81 \"\n      \"numbers from 0 to 9\")(\"generate,g\", po::value<unsigned>(),\n                             \"Return random board with given empty cells\")(\n      \"seed,s\", po::value<unsigned>(), \"Seed for random number generator\")(\n      \"with-solution,l\", \"Will print solution, when generating board\");\n  return desc;\n}\n\nauto toString(const Sudoku::Grid &grid) {\n  std::stringstream ss;\n  for (const auto &row : grid.getRows()) {\n    for (const auto &cell : row.getCells()) {\n      ss << std::to_string(cell.getValue());\n    }\n  }\n  return ss.str();\n}\n\nauto solveSudoku(const Sudoku::Grid &grid) {\n  std::unique_ptr<Sudoku::Algorithm> algorithm =\n      std::make_unique<Sudoku::BruteForce>();\n  const auto result = algorithm->solve(grid);\n  std::cout << toString(result.solution) << std::endl;\n  return result.success ? 0 : 1;\n}\n\nauto generateSudoku(const po::variables_map &vm) {\n  unsigned amountOfEmptyCells = vm[\"generate\"].as<unsigned>();\n  const auto seed = [&]() {\n    if (vm.count(\"seed\")) {\n      return vm[\"seed\"].as<unsigned>();\n    }\n    std::random_device os_seed;\n    return os_seed();\n  }();\n  const auto generated = Sudoku::generateRandomGrid(seed, amountOfEmptyCells);\n  std::cout << toString(generated.problem) << std::endl;\n  if (vm.count(\"with-solution\")) {\n    std::cout << toString(generated.solution) << std::endl;\n  }\n  return 0;\n}\n\nint main(int argc, char **argv) {\n  const auto desc = createOptionsDescription();\n  po::variables_map vm = getProgramOptions(argc, argv, desc);\n  if (vm.count(\"help\")) {\n    std::cout << desc << \"\\n\";\n    return 0;\n  }\n\n  if (vm.count(\"generate\")) {\n    return generateSudoku(vm);\n  }\n\n  if (vm.count(\"inline\")) {\n    return solveSudoku(Sudoku::Grid(vm[\"inline\"].as<std::string>()));\n  }\n\n  std::cout << desc << \"\\n\";\n  return 0;\n}", "meta": {"hexsha": "e2bd23a0319105867d363beaf5454c1b0c74693a", "size": 2462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "susolver/Main.cpp", "max_stars_repo_name": "wozniakpl/sudoku-solver", "max_stars_repo_head_hexsha": "ac25ed8e7793f1985bfe5aff4cb25be282425c52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "susolver/Main.cpp", "max_issues_repo_name": "wozniakpl/sudoku-solver", "max_issues_repo_head_hexsha": "ac25ed8e7793f1985bfe5aff4cb25be282425c52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "susolver/Main.cpp", "max_forks_repo_name": "wozniakpl/sudoku-solver", "max_forks_repo_head_hexsha": "ac25ed8e7793f1985bfe5aff4cb25be282425c52", "max_forks_repo_licenses": ["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.6626506024, "max_line_length": 78, "alphanum_fraction": 0.649471974, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5316802352783753}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n\nnamespace tools::linalg {\n\nstruct SolverData {\n  double relative_residual = 0;\n  double initial_algebraic_error = 0;\n  double algebraic_error = 0;\n  size_t iterations = 0;\n  bool converged = false;\n};\n\nenum StoppingCriterium { Relative, Algebraic };\n\n// Loosely based off Eigen/ConjugateGradient.h.\ntemplate <typename MatType, typename PrecondType>\nstd::pair<Eigen::VectorXd, SolverData> PCG(\n    const MatType &A, const Eigen::VectorXd &b, const PrecondType &M,\n    const Eigen::VectorXd &x0, int imax, double tol,\n    enum StoppingCriterium stopping = StoppingCriterium::Relative);\n\ntemplate <typename MatType, typename PrecondType>\nclass Lanczos {\n public:\n  Lanczos(const MatType &A, const PrecondType &P, size_t max_iterations = 200,\n          double tol = 0.0001, double tol_bisec = 0.000001)\n      : Lanczos(A, P, Eigen::VectorXd::Random(A.cols()), max_iterations, tol,\n                tol_bisec) {}\n  Lanczos(const MatType &A, const PrecondType &P,\n          const Eigen::VectorXd &initial_guess, size_t max_iterations = 200,\n          double tol = 0.0001, double tol_bisec = 0.000001);\n\n  double max() const { return lmax_; }\n  double min() const { return lmin_; }\n  double cond() const { return lmax_ / lmin_; }\n  float time() const { return time_; };\n\n  size_t iterations() const { return iterations_; }\n  bool converged() const { return converged_; }\n\n  // overload the << operator\n  friend std::ostream &operator<<(std::ostream &os, const Lanczos &lanczos) {\n    if (lanczos.converged())\n      os << \"converged\\t\";\n    else\n      os << \"NOT converged\\t\";\n\n    os << \"its=\" << lanczos.iterations() << \"\\tlmax=\" << lanczos.max()\n       << \"\\tlmin=\" << lanczos.min() << \"\\tkappa=\" << lanczos.cond()\n       << \"\\ttime=\" << lanczos.time() << \" s\";\n    return os;\n  }\n\n private:\n  Eigen::VectorXd alpha_, beta_;\n  double lmax_, lmin_;\n\n  size_t iterations_;\n  bool converged_;\n  float time_;\n\n  void bisec(size_t k, double &ymax, double &zmin, double tol_bisec);\n  double pol(int k, double x);\n};\n\n};  // namespace tools::linalg\n\n#include \"linalg.ipp\"\n", "meta": {"hexsha": "3d6b3338fdec887aed9cf55fb4fc3935b4a2a014", "size": 2135, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tools/linalg.hpp", "max_stars_repo_name": "rvanvenetie/spacetime", "max_stars_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_stars_repo_licenses": ["MIT"], "max_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/linalg.hpp", "max_issues_repo_name": "rvanvenetie/spacetime", "max_issues_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_issues_repo_licenses": ["MIT"], "max_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/linalg.hpp", "max_forks_repo_name": "rvanvenetie/spacetime", "max_forks_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_forks_repo_licenses": ["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.2465753425, "max_line_length": 78, "alphanum_fraction": 0.6669789227, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5316802262599879}}
{"text": "/*\nAuthor: Rohan Chetan Thanki\nDate created: 16-Oct-2021\n*/\n\n/*\nThis contains the implementation of the Hedging_Portfolio class\n*/\n\n#include \"Hedging_Portfolio.hpp\"\n#include <string>\n#include <boost/math/distributions.hpp>\n\nusing namespace std;\n\n/******************************* Constructors and Destructors ***************************************/\n\n// Default constructor\nHedging_Portfolio::Hedging_Portfolio() : Option() { }\n\n// Parametrised constructor\nHedging_Portfolio::Hedging_Portfolio(const double& K1, const double& S1, const double& r1, const double& T1, const double& vol1, const char& optionType) : Option(K1, S1, r1, T1, vol1, optionType)\n{\n\tif (!(optionType == 'c' || optionType == 'C' || optionType == 'p' || optionType == 'P'))\n\t\tthrow(20);\n}\n\n// Destructor\nHedging_Portfolio::~Hedging_Portfolio(void) { }\n\n/******************************* Getters ***************************************/\n\ndouble Hedging_Portfolio::getDelta(void) const { return delta; }\ndouble Hedging_Portfolio::getOptionPrice(void) const { return optionPrice; }\ndouble Hedging_Portfolio::getB(void) const { return B; }\ndouble Hedging_Portfolio::getHedgingError(void) const { return HE; }\n\nstring Hedging_Portfolio::getDate(void) const { return date; }\nstring Hedging_Portfolio::getExpDate(void) const { return expDate; }\ndouble Hedging_Portfolio::getpnlNaked(void) const { return pnlNaked; }\ndouble Hedging_Portfolio::getpnlHedged(void) const { return pnlHedged; }\n\n/******************************* Setters ***************************************/\n\nvoid Hedging_Portfolio::setDelta(const double& delta1) { delta = delta1; }\nvoid Hedging_Portfolio::setOptionPrice(const double& optionPrice1) { optionPrice = optionPrice1; }\nvoid Hedging_Portfolio::setB(const double& B1) { B = B1; }\nvoid Hedging_Portfolio::setHedgingError(const double& HE1) { HE = HE1; }\n\nvoid Hedging_Portfolio::setDate(const string& date1) { date = date1; }\nvoid Hedging_Portfolio::setExpDate(const string& expDate1) { expDate = expDate1; }\nvoid Hedging_Portfolio::setpnlNaked(const double& pnlNaked1) { pnlNaked = pnlNaked1; }\nvoid Hedging_Portfolio::setpnlHedged(const double& pnlHedged1) { pnlHedged = pnlHedged1; }\n\n/******************************* Other Functions ***************************************/\n\n// Get CDF of Standard Normal\ninline double N(const double& x)\n{\n\tboost::math::normal_distribution<> stdNormal(0.0, 1.0);\n\treturn(cdf(stdNormal, x));\n}\n\ndouble Hedging_Portfolio::computeDelta(void) const\n{\n\tchar flag = getFlag();\n\tdouble K = getStrikePrice();\n\tdouble S = getSpotPrice();\n\tdouble r = getRiskFreeRate();\n\tdouble T = getTimeToMaturity();\n\tdouble sigma = getVolatility();\n\tdouble d1 = (log(S / K) + ((r + (pow(sigma, 2) / 2)) * T)) / (sigma * sqrt(T));\n\tif (flag == 'c' || flag == 'C')\n\t\treturn (N(d1));\n\telse if (flag == 'p' || flag == 'P')\n\t\treturn (N(d1));\n\telse\n\t\tthrow(10);\n}\n\n// Compute option price using Black Scholes formula\ndouble Hedging_Portfolio::computeBlackScholesOptionPrice(const double& sigma) const\n{\n\tchar flag = getFlag();\n\tdouble K = getStrikePrice();\n\tdouble S = getSpotPrice();\n\tdouble r = getRiskFreeRate();\n\tdouble T = getTimeToMaturity();\n\n\tOption opt1(K, S, r, T, sigma, flag);\n\n\tdouble d1 = (log(S / K) + ((r + (pow(sigma, 2) / 2)) * T)) / (sigma * sqrt(T));\n\tdouble d2 = d1 - (sigma * sqrt(T));\n\n\tif (flag == 'c' || flag == 'C')\n\t\treturn (S * N(d1)) - (K * exp(-r * T) * N(d2));\n\telse if (flag == 'p' || flag == 'P')\n\t\treturn (K * exp(-r * T) * N(-d2)) - (S * N(-d1));\n\telse\n\t\tthrow(10);\n}\n\n//double getImpliedVol(const double&, const double&, const double&, \ndouble Hedging_Portfolio:: computeImpliedVol(double& volMax) const\n{\n\tdouble flag = getFlag();\n\tdouble volMin = 0;\n\tdouble impVol;\n\tdouble TMat = getTimeToMaturity();\n\tdouble epsilon = 0.001;\n\tdouble modelPrice;\n\tstring temp;\n\t\n\twhile (true)\n\t{\n\t\timpVol = 0.5 * (volMin + volMax);\n\t\tmodelPrice = computeBlackScholesOptionPrice(impVol);\n\n\t\tif (modelPrice > optionPrice + epsilon)\n\t\t\tvolMax = impVol;\n\t\telse if (modelPrice < optionPrice - epsilon)\n\t\t\tvolMin = impVol;\n\t\telse\n\t\t\treturn(impVol);\n\t}\n}", "meta": {"hexsha": "3305e818c23e5097c09b13caf111b04991f5aeeb", "size": 4065, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sys_Comp_Midterm_Project/Sys_Comp_Midterm_Project/Hedging_Portfolio.cpp", "max_stars_repo_name": "rohanthanki/delta_hedging", "max_stars_repo_head_hexsha": "f1c2b8e9965ccea594466e6a32e1c8f82036763e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sys_Comp_Midterm_Project/Sys_Comp_Midterm_Project/Hedging_Portfolio.cpp", "max_issues_repo_name": "rohanthanki/delta_hedging", "max_issues_repo_head_hexsha": "f1c2b8e9965ccea594466e6a32e1c8f82036763e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sys_Comp_Midterm_Project/Sys_Comp_Midterm_Project/Hedging_Portfolio.cpp", "max_forks_repo_name": "rohanthanki/delta_hedging", "max_forks_repo_head_hexsha": "f1c2b8e9965ccea594466e6a32e1c8f82036763e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2619047619, "max_line_length": 195, "alphanum_fraction": 0.6489544895, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5316802226300187}}
{"text": "#include \"ros_package_template/Algorithm.hpp\"\n\n#include <utility>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n\nnamespace ros_package_template {\n\nusing namespace boost::accumulators;\n\nstruct Algorithm::Data {\n  accumulator_set<double, features<tag::mean, tag::count>> acc;\n};\n\nAlgorithm::Algorithm() {\n  data_ = std::make_unique<Data>();\n}\n\nAlgorithm::~Algorithm() = default;\n\nvoid Algorithm::addData(const double data)\n{\n  data_->acc(data);\n}\n\nvoid Algorithm::addData(const Eigen::VectorXd& data)\n{\n  for(auto i = 0; i < data.size(); ++i)\n    addData(data[i]);\n}\n\ndouble Algorithm::getAverage() const\n{\n  return count(data_->acc) ? mean(data_->acc) : 0;\n}\n\n} /* namespace */\n", "meta": {"hexsha": "a66c49a07d55182775ecfdbcb0148bb434b7ec8c", "size": 780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros_package_template/src/Algorithm.cpp", "max_stars_repo_name": "muhammadasadurrehman/Asad", "max_stars_repo_head_hexsha": "0950b82b4bd018d8bd758568183ed7268224675c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 800.0, "max_stars_repo_stars_event_min_datetime": "2018-08-07T21:55:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:24:56.000Z", "max_issues_repo_path": "ros_package_template/src/Algorithm.cpp", "max_issues_repo_name": "muhammadasadurrehman/Asad", "max_issues_repo_head_hexsha": "0950b82b4bd018d8bd758568183ed7268224675c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-01-16T20:40:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T18:09:26.000Z", "max_forks_repo_path": "ros_package_template/src/Algorithm.cpp", "max_forks_repo_name": "muhammadasadurrehman/Asad", "max_forks_repo_head_hexsha": "0950b82b4bd018d8bd758568183ed7268224675c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 289.0, "max_forks_repo_forks_event_min_datetime": "2018-08-16T06:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T17:26:46.000Z", "avg_line_length": 19.5, "max_line_length": 63, "alphanum_fraction": 0.7153846154, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5316802226300187}}
{"text": "#ifndef NORMALIZED_NUMERICS_HH\n#define NORMALIZED_NUMERICS_HH\n\n#include <boost/static_assert.hpp>\n\nnamespace Typelib {\n    namespace details {\n        template<int Bits> struct sint_t;\n        template<> struct sint_t<7>  { typedef int8_t type; };\n        template<> struct sint_t<15> { typedef int16_t type; };\n        template<> struct sint_t<31> { typedef int32_t type; };\n        template<> struct sint_t<63> { typedef int64_t type; };\n\n        template<int Bits> struct uint_t;\n        template<> struct uint_t<8>  { typedef uint8_t type; };\n        template<> struct uint_t<16> { typedef uint16_t type; };\n        template<> struct uint_t<32> { typedef uint32_t type; };\n        template<> struct uint_t<64> { typedef uint64_t type; };\n    }\n\n    /** This template converts base C types (long, int, ...) in their normalized form (uin8_t, int16_t, ...) \n     * For consistency, it is also specialized for float and double */\n    template<typename T>\n    struct normalized_numeric_type \n    {\n        typedef std::numeric_limits<T>  limits;\n        BOOST_STATIC_ASSERT(( limits::is_integer )); // will specialize for float and double\n\n        typedef typename boost::mpl::if_\n            < boost::mpl::bool_<std::numeric_limits<T>::is_signed>\n            , details::sint_t< limits::digits >\n            , details::uint_t< limits::digits >\n            >::type                             getter;\n        typedef typename getter::type           type;\n    };\n\n    template<> struct normalized_numeric_type<float>  { typedef float\ttype; };\n    template<> struct normalized_numeric_type<double> { typedef double\ttype; };\n}\n\n#endif\n\n\n\n", "meta": {"hexsha": "ffd99b468bfbfdd55c4ec67c3c7c8592d2b85eb7", "size": 1633, "ext": "hh", "lang": "C++", "max_stars_repo_path": "typelib/normalized_numerics.hh", "max_stars_repo_name": "meyerj/typelib", "max_stars_repo_head_hexsha": "e2a8d67d35732ffdd1d586aa8370576033ecc5a6", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-07-06T06:30:14.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-06T06:30:14.000Z", "max_issues_repo_path": "typelib/normalized_numerics.hh", "max_issues_repo_name": "jmachowinski/typelib", "max_issues_repo_head_hexsha": "9f04e8d842dd489f95c35e63568ef30b29d5df5a", "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": "typelib/normalized_numerics.hh", "max_forks_repo_name": "jmachowinski/typelib", "max_forks_repo_head_hexsha": "9f04e8d842dd489f95c35e63568ef30b29d5df5a", "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": 36.2888888889, "max_line_length": 109, "alphanum_fraction": 0.6319657073, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5316802217507942}}
{"text": "#include <nori/integrator.h>\n#include <nori/scene.h>\n#include <nori/ray.h>\n#include <filesystem/resolver.h>\n#include <sh/spherical_harmonics.h>\n#include <sh/default_image.h>\n#include <Eigen/Core>\n#include <fstream>\n#include <random>\n#include <stb_image.h>\n\nNORI_NAMESPACE_BEGIN\n\nnamespace ProjEnv\n{\n    std::vector<std::unique_ptr<float[]>>\n    LoadCubemapImages(const std::string &cubemapDir, int &width, int &height,\n                      int &channel)\n    {\n        std::vector<std::string> cubemapNames{\"negx.jpg\", \"posx.jpg\", \"posy.jpg\",\n                                              \"negy.jpg\", \"posz.jpg\", \"negz.jpg\"};\n        std::vector<std::unique_ptr<float[]>> images(6);\n        for (int i = 0; i < 6; i++)\n        {\n            std::string filename = cubemapDir + \"/\" + cubemapNames[i];\n            int w, h, c;\n            float *image = stbi_loadf(filename.c_str(), &w, &h, &c, 3);\n            if (!image)\n            {\n                std::cout << \"Failed to load image: \" << filename << std::endl;\n                exit(-1);\n            }\n            if (i == 0)\n            {\n                width = w;\n                height = h;\n                channel = c;\n            }\n            else if (w != width || h != height || c != channel)\n            {\n                std::cout << \"Dismatch resolution for 6 images in cubemap\" << std::endl;\n                exit(-1);\n            }\n            images[i] = std::unique_ptr<float[]>(image);\n            int index = (0 * 128 + 0) * channel;\n            // std::cout << images[i][index + 0] << \"\\t\" << images[i][index + 1] << \"\\t\"\n            //           << images[i][index + 2] << std::endl;\n        }\n        return images;\n    }\n\n    const Eigen::Vector3f cubemapFaceDirections[6][3] = {\n        {{0, 0, 1}, {0, -1, 0}, {-1, 0, 0}},  // negx\n        {{0, 0, 1}, {0, -1, 0}, {1, 0, 0}},   // posx\n        {{1, 0, 0}, {0, 0, -1}, {0, -1, 0}},  // negy\n        {{1, 0, 0}, {0, 0, 1}, {0, 1, 0}},    // posy\n        {{-1, 0, 0}, {0, -1, 0}, {0, 0, -1}}, // negz\n        {{1, 0, 0}, {0, -1, 0}, {0, 0, 1}},   // posz\n    };\n\n    float CalcPreArea(const float &x, const float &y)\n    {\n        return std::atan2(x * y, std::sqrt(x * x + y * y + 1.0));\n    }\n\n    float CalcArea(const float &u_, const float &v_, const int &width,\n                   const int &height)\n    {\n        // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]\n        // ( 0.5 is for texel center addressing)\n        float u = (2.0 * (u_ + 0.5) / width) - 1.0;\n        float v = (2.0 * (v_ + 0.5) / height) - 1.0;\n\n        // shift from a demi texel, mean 1.0 / size  with u and v in [-1..1]\n        float invResolutionW = 1.0 / width;\n        float invResolutionH = 1.0 / height;\n\n        // u and v are the -1..1 texture coordinate on the current face.\n        // get projected area for this texel\n        float x0 = u - invResolutionW;\n        float y0 = v - invResolutionH;\n        float x1 = u + invResolutionW;\n        float y1 = v + invResolutionH;\n        float angle = CalcPreArea(x0, y0) - CalcPreArea(x0, y1) -\n                      CalcPreArea(x1, y0) + CalcPreArea(x1, y1);\n\n        return angle;\n    }\n\n    // template <typename T> T ProjectSH() {}\n\n    template <size_t SHOrder>\n    std::vector<Eigen::Array3f> PrecomputeCubemapSH(const std::vector<std::unique_ptr<float[]>> &images,\n                                                    const int &width, const int &height,\n                                                    const int &channel)\n    {\n        std::vector<Eigen::Vector3f> cubemapDirs;\n        cubemapDirs.reserve(6 * width * height);\n        for (int i = 0; i < 6; i++)\n        {\n            Eigen::Vector3f faceDirX = cubemapFaceDirections[i][0];\n            Eigen::Vector3f faceDirY = cubemapFaceDirections[i][1];\n            Eigen::Vector3f faceDirZ = cubemapFaceDirections[i][2];\n            for (int y = 0; y < height; y++)\n            {\n                for (int x = 0; x < width; x++)\n                {\n                    float u = 2 * ((x + 0.5) / width) - 1;\n                    float v = 2 * ((y + 0.5) / height) - 1;\n                    Eigen::Vector3f dir = (faceDirX * u + faceDirY * v + faceDirZ).normalized();\n                    cubemapDirs.push_back(dir);\n                }\n            }\n        }\n        constexpr int SHNum = (SHOrder + 1) * (SHOrder + 1);\n        std::vector<Eigen::Array3f> SHCoeffiecents(SHNum);\n        for (int i = 0; i < SHNum; i++)\n            SHCoeffiecents[i] = Eigen::Array3f(0);\n        float sumWeight = 0;\n        for (int i = 0; i < 6; i++)\n        {\n            for (int y = 0; y < height; y++)\n            {\n                for (int x = 0; x < width; x++)\n                {\n                    // TODO: here you need to compute light sh of each face of cubemap of each pixel\n                    // TODO: \u6b64\u5904\u4f60\u9700\u8981\u8ba1\u7b97\u6bcf\u4e2a\u50cf\u7d20\u4e0bcubemap\u67d0\u4e2a\u9762\u7684\u7403\u8c10\u7cfb\u6570\n                    Eigen::Vector3f dir = cubemapDirs[i * width * height + y * width + x];\n                    int index = (y * width + x) * channel;\n                    Eigen::Array3f Le(images[i][index + 0], images[i][index + 1],\n                                      images[i][index + 2]);\n                    auto wOmega = CalcArea(x, y, width, height);\n\n                    for (auto l = 0; l <= SHOrder; ++l)\n                    {\n                        for (auto m = -l; m <= l; ++m)\n                        {\n                            auto k = sh::GetIndex(l, m);\n                            auto basicFunc = sh::EvalSH(l, m, dir.cast<double>().normalized());\n\n                            SHCoeffiecents[k] += wOmega * Le * basicFunc;\n                        }\n                    }\n                }\n            }\n        }\n        return SHCoeffiecents;\n    }\n}\n\nclass PRTIntegrator : public Integrator\n{\npublic:\n    static constexpr int SHOrder = 2;\n    static constexpr int SHCoeffLength = (SHOrder + 1) * (SHOrder + 1);\n\n    enum class Type\n    {\n        Unshadowed = 0,\n        Shadowed = 1,\n        Interreflection = 2\n    };\n\n    PRTIntegrator(const PropertyList &props)\n    {\n        /* No parameters this time */\n        m_SampleCount = props.getInteger(\"PRTSampleCount\", 100);\n        m_CubemapPath = props.getString(\"cubemap\");\n        auto type = props.getString(\"type\", \"unshadowed\");\n        if (type == \"unshadowed\")\n        {\n            m_Type = Type::Unshadowed;\n        }\n        else if (type == \"shadowed\")\n        {\n            m_Type = Type::Shadowed;\n        }\n        else if (type == \"interreflection\")\n        {\n            m_Type = Type::Interreflection;\n            m_Bounce = props.getInteger(\"bounce\", 1);\n        }\n        else\n        {\n            throw NoriException(\"Unsupported type: %s.\", type);\n        }\n    }\n\n    virtual void preprocess(const Scene *scene) override\n    {\n\n        // Here only compute one mesh\n        const auto mesh = scene->getMeshes()[0];\n        // Projection environment\n        auto cubePath = getFileResolver()->resolve(m_CubemapPath);\n        auto lightPath = cubePath / \"light.txt\";\n        auto transPath = cubePath / \"transport.txt\";\n        std::ofstream lightFout(lightPath.str());\n        std::ofstream fout(transPath.str());\n        int width, height, channel;\n        std::vector<std::unique_ptr<float[]>> images =\n            ProjEnv::LoadCubemapImages(cubePath.str(), width, height, channel);\n        auto envCoeffs = ProjEnv::PrecomputeCubemapSH<SHOrder>(images, width, height, channel);\n        m_LightCoeffs.resize(3, SHCoeffLength);\n        for (int i = 0; i < envCoeffs.size(); i++)\n        {\n            lightFout << (envCoeffs)[i].x() << \" \" << (envCoeffs)[i].y() << \" \" << (envCoeffs)[i].z() << std::endl;\n            m_LightCoeffs.col(i) = (envCoeffs)[i];\n        }\n        std::cout << \"Computed light sh coeffs from: \" << cubePath.str() << \" to: \" << lightPath.str() << std::endl;\n        // Projection transport\n        m_TransportSHCoeffs.resize(SHCoeffLength, mesh->getVertexCount());\n        fout << mesh->getVertexCount() << std::endl;\n        for (int i = 0; i < mesh->getVertexCount(); i++)\n        {\n            const Point3f &v = mesh->getVertexPositions().col(i);\n            const Normal3f &n = mesh->getVertexNormals().col(i);\n            auto shFunc = [&](double phi, double theta) -> double\n            {\n                Eigen::Array3d d = sh::ToVector(phi, theta);\n                const auto wi = Vector3f(d.x(), d.y(), d.z());\n                const auto H = wi.dot(n);\n                if (m_Type == Type::Unshadowed)\n                {\n                    // TODO: here you need to calculate unshadowed transport term of a given direction\n                    // TODO: \u6b64\u5904\u4f60\u9700\u8981\u8ba1\u7b97\u7ed9\u5b9a\u65b9\u5411\u4e0b\u7684unshadowed\u4f20\u8f93\u9879\u7403\u8c10\u51fd\u6570\u503c\n                    return std::max(0.f, H);\n                }\n                else\n                {\n                    // TODO: here you need to calculate shadowed transport term of a given direction\n                    // TODO: \u6b64\u5904\u4f60\u9700\u8981\u8ba1\u7b97\u7ed9\u5b9a\u65b9\u5411\u4e0b\u7684shadowed\u4f20\u8f93\u9879\u7403\u8c10\u51fd\u6570\u503c\n                    Ray3f ray(v, wi.normalized());\n                    if (H > 0 && !scene->rayIntersect(ray))\n                        return H;\n                    return 0;\n                }\n            };\n            auto shCoeff = sh::ProjectFunction(SHOrder, shFunc, m_SampleCount);\n            for (int j = 0; j < shCoeff->size(); j++)\n            {\n                m_TransportSHCoeffs.col(i).coeffRef(j) = (*shCoeff)[j];\n            }\n        }\n        if (m_Type == Type::Interreflection)\n        {\n            // TODO: leave for bonus\n        }\n\n        // Save in face format\n        for (int f = 0; f < mesh->getTriangleCount(); f++)\n        {\n            const MatrixXu &F = mesh->getIndices();\n            uint32_t idx0 = F(0, f), idx1 = F(1, f), idx2 = F(2, f);\n            for (int j = 0; j < SHCoeffLength; j++)\n            {\n                fout << m_TransportSHCoeffs.col(idx0).coeff(j) << \" \";\n            }\n            fout << std::endl;\n            for (int j = 0; j < SHCoeffLength; j++)\n            {\n                fout << m_TransportSHCoeffs.col(idx1).coeff(j) << \" \";\n            }\n            fout << std::endl;\n            for (int j = 0; j < SHCoeffLength; j++)\n            {\n                fout << m_TransportSHCoeffs.col(idx2).coeff(j) << \" \";\n            }\n            fout << std::endl;\n        }\n        std::cout << \"Computed SH coeffs\"\n                  << \" to: \" << transPath.str() << std::endl;\n    }\n\n    Color3f Li(const Scene *scene, Sampler *sampler, const Ray3f &ray) const\n    {\n        Intersection its;\n        if (!scene->rayIntersect(ray, its))\n            return Color3f(0.0f);\n\n        const Eigen::Matrix<Vector3f::Scalar, SHCoeffLength, 1> sh0 = m_TransportSHCoeffs.col(its.tri_index.x()),\n                                                                sh1 = m_TransportSHCoeffs.col(its.tri_index.y()),\n                                                                sh2 = m_TransportSHCoeffs.col(its.tri_index.z());\n        const Eigen::Matrix<Vector3f::Scalar, SHCoeffLength, 1> rL = m_LightCoeffs.row(0), gL = m_LightCoeffs.row(1), bL = m_LightCoeffs.row(2);\n\n        Color3f c0 = Color3f(rL.dot(sh0), gL.dot(sh0), bL.dot(sh0)),\n                c1 = Color3f(rL.dot(sh1), gL.dot(sh1), bL.dot(sh1)),\n                c2 = Color3f(rL.dot(sh2), gL.dot(sh2), bL.dot(sh2));\n\n        const Vector3f &bary = its.bary;\n        Color3f c = bary.x() * c0 + bary.y() * c1 + bary.z() * c2;\n        // TODO: you need to delete the following four line codes after finishing your calculation to SH,\n        //       we use it to visualize the normals of model for debug.\n        // TODO: \u5728\u5b8c\u6210\u4e86\u7403\u8c10\u7cfb\u6570\u8ba1\u7b97\u540e\uff0c\u4f60\u9700\u8981\u5220\u9664\u4e0b\u5217\u56db\u884c\uff0c\u8fd9\u56db\u884c\u4ee3\u7801\u7684\u4f5c\u7528\u662f\u7528\u6765\u53ef\u89c6\u5316\u6a21\u578b\u6cd5\u7ebf\n        // if (c.isZero())\n        // {\n        //     auto n_ = its.shFrame.n.cwiseAbs();\n        //     return Color3f(n_.x(), n_.y(), n_.z());\n        // }\n        return c;\n    }\n\n    std::string toString() const\n    {\n        return \"PRTIntegrator[]\";\n    }\n\nprivate:\n    Type m_Type;\n    int m_Bounce = 1;\n    int m_SampleCount = 100;\n    std::string m_CubemapPath;\n    Eigen::MatrixXf m_TransportSHCoeffs;\n    Eigen::MatrixXf m_LightCoeffs;\n};\n\nNORI_REGISTER_CLASS(PRTIntegrator, \"prt\");\nNORI_NAMESPACE_END", "meta": {"hexsha": "7873853550459953376ee9130b1b66498f22a952", "size": 12128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homework2/prt/src/prt.cpp", "max_stars_repo_name": "QRWells/Games-202-Homework", "max_stars_repo_head_hexsha": "5308f57ffe4a1b2d011e43bd0e9890ad6501146d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework2/prt/src/prt.cpp", "max_issues_repo_name": "QRWells/Games-202-Homework", "max_issues_repo_head_hexsha": "5308f57ffe4a1b2d011e43bd0e9890ad6501146d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework2/prt/src/prt.cpp", "max_forks_repo_name": "QRWells/Games-202-Homework", "max_forks_repo_head_hexsha": "5308f57ffe4a1b2d011e43bd0e9890ad6501146d", "max_forks_repo_licenses": ["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.1383647799, "max_line_length": 144, "alphanum_fraction": 0.4822724274, "num_tokens": 3386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5316391260420201}}
{"text": "#pragma once\n#include <vector>\n\n#include <Eigen/Dense>\n\nnamespace Caesar {\n\nclass Pose3d {\npublic:\n  Pose3d() {\n    position_ << 0.0, 0.0, 0.0;\n    orientation_ = Eigen::Quaterniond(1.0, 0.0, 0.0, 0.0);\n  };\n\n  Pose3d(double x, double y, double z, double qw, double qx, double qy,\n         double qz) {\n    position_ << x, y, z;\n    orientation_ = Eigen::Quaterniond(qw, qx, qy, qz);\n  };\n\n  Pose3d(const Eigen::Vector3d &position,\n         const Eigen::Quaterniond &orientation) {\n    position_ = position;\n    orientation_ = orientation;\n  };\n\n  ~Pose3d(){};\n\n  std::vector<double> Vector(void) const {\n    std::vector<double> v = {\n        position_.x(),    position_.y(),    position_.z(),   orientation_.w(),\n        orientation_.x(), orientation_.y(), orientation_.z()};\n    return v;\n  }\n\n  Eigen::Vector3d position() { return position_; };\n  double x() const { return position_.x(); };\n  double y() const { return position_.y(); };\n  double z() const { return position_.z(); };\n  double qw() const { return orientation_.w(); };\n  double qx() const { return orientation_.x(); };\n  double qy() const { return orientation_.y(); };\n  double qz() const { return orientation_.z(); };\n\n  Eigen::Quaterniond q() const { return orientation_; };\n\nprivate:\n  Eigen::Vector3d position_;\n  Eigen::Quaterniond orientation_;\n};\n}\n", "meta": {"hexsha": "20469507ca3a893c5b0f64af447efc0e4a40d105", "size": 1323, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/caesar/Pose3d.hpp", "max_stars_repo_name": "pvazteixeira/rome-lcmtypes", "max_stars_repo_head_hexsha": "3e05d69e6ef6011835b9f2d427ee6f839268fb97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-04-29T01:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-02T19:03:35.000Z", "max_issues_repo_path": "src/caesar/Pose3d.hpp", "max_issues_repo_name": "pvazteixeira/rome-lcmtypes", "max_issues_repo_head_hexsha": "3e05d69e6ef6011835b9f2d427ee6f839268fb97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-04-03T18:11:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T17:16:04.000Z", "max_forks_repo_path": "src/caesar/Pose3d.hpp", "max_forks_repo_name": "pvazteixeira/caesar-lcm", "max_forks_repo_head_hexsha": "3e05d69e6ef6011835b9f2d427ee6f839268fb97", "max_forks_repo_licenses": ["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.4423076923, "max_line_length": 78, "alphanum_fraction": 0.6243386243, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021787, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5316391215660379}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\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#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SSF_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SSF_HPP\r\n\r\n#include <boost/mpl/if.hpp>\r\n#include <boost/type_traits.hpp>\r\n\r\n#include <boost/geometry/core/cs.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/util/select_coordinate_type.hpp>\r\n#include <boost/geometry/util/math.hpp>\r\n\r\n#include <boost/geometry/strategies/side.hpp>\r\n//#include <boost/geometry/strategies/concepts/side_concept.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n\r\nnamespace strategy { namespace side\r\n{\r\n\r\n\r\n/*!\r\n\\brief Check at which side of a Great Circle 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 spherical_side_formula\r\n{\r\n\r\npublic :\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\r\n                // Select at least a double...\r\n                typename select_most_precise\r\n                    <\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                        double\r\n                    >::type,\r\n                CalculationType\r\n            >::type coordinate_type;\r\n\r\n        // Convenient shortcuts\r\n        typedef coordinate_type ct;\r\n        ct const lambda1 = get_as_radian<0>(p1);\r\n        ct const delta1 = get_as_radian<1>(p1);\r\n        ct const lambda2 = get_as_radian<0>(p2);\r\n        ct const delta2 = get_as_radian<1>(p2);\r\n        ct const lambda = get_as_radian<0>(p);\r\n        ct const delta = get_as_radian<1>(p);\r\n\r\n        // Create temporary points (vectors) on unit a sphere\r\n        ct const cos_delta1 = cos(delta1);\r\n        ct const c1x = cos_delta1 * cos(lambda1);\r\n        ct const c1y = cos_delta1 * sin(lambda1);\r\n        ct const c1z = sin(delta1);\r\n\r\n        ct const cos_delta2 = cos(delta2);\r\n        ct const c2x = cos_delta2 * cos(lambda2);\r\n        ct const c2y = cos_delta2 * sin(lambda2);\r\n        ct const c2z = sin(delta2);\r\n\r\n        // (Third point is converted directly)\r\n        ct const cos_delta = cos(delta);\r\n        \r\n        // Apply the \"Spherical Side Formula\" as presented on my blog\r\n        ct const dist \r\n            = (c1y * c2z - c1z * c2y) * cos_delta * cos(lambda) \r\n            + (c1z * c2x - c1x * c2z) * cos_delta * sin(lambda)\r\n            + (c1x * c2y - c1y * c2x) * sin(delta);\r\n        \r\n        ct zero = ct();\r\n        return dist > zero ? 1\r\n            : dist < zero ? -1\r\n            : 0;\r\n    }\r\n};\r\n\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\nnamespace services\r\n{\r\n\r\n/*template <typename CalculationType>\r\nstruct default_strategy<spherical_polar_tag, CalculationType>\r\n{\r\n    typedef spherical_side_formula<CalculationType> type;\r\n};*/\r\n\r\ntemplate <typename CalculationType>\r\nstruct default_strategy<spherical_equatorial_tag, CalculationType>\r\n{\r\n    typedef spherical_side_formula<CalculationType> type;\r\n};\r\n\r\ntemplate <typename CalculationType>\r\nstruct default_strategy<geographic_tag, CalculationType>\r\n{\r\n    typedef spherical_side_formula<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_SPHERICAL_SSF_HPP\r\n", "meta": {"hexsha": "04ee35860e1b30246d19c26e7d2e86c0094c5e31", "size": 4262, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/geometry/strategies/spherical/ssf.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/spherical/ssf.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/spherical/ssf.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.1094890511, "max_line_length": 80, "alphanum_fraction": 0.6015954951, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5316391144484388}}
{"text": "// ----------------------------------------------------------------------------\n// -                        Open3D: www.open3d.org                            -\n// ----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2018 www.open3d.org\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\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n// ----------------------------------------------------------------------------\n\n#include \"PointCloud.h\"\n\n#include <Eigen/Eigenvalues>\n#include <Core/Utility/Console.h>\n#include <Core/Geometry/KDTreeFlann.h>\n\nnamespace three{\n\nnamespace {\n\ndouble sqr(double x) { return x * x; }\n\nEigen::Vector3d FastEigen3x3(const Eigen::Matrix3d &A)\n{\n\t// Based on:\n\t// https://en.wikipedia.org/wiki/Eigenvalue_algorithm#3.C3.973_matrices\n\tdouble p1 = sqr(A(0, 1)) + sqr(A(0, 2)) + sqr(A(1, 2));\n\tEigen::Vector3d eigenvalues;\n\tif (p1 == 0.0) {\n\t\teigenvalues(2) = std::min(A(0, 0), std::min(A(1, 1), A(2, 2)));\n\t\teigenvalues(0) = std::max(A(0, 0), std::max(A(1, 1), A(2, 2)));\n\t\teigenvalues(1) = A.trace() - eigenvalues(0) - eigenvalues(2);\n\t} else {\n\t\tdouble q = A.trace() / 3.0;\n\t\tdouble p2 = sqr((A(0, 0) - q)) + sqr(A(1, 1) - q) + sqr(A(2, 2) - q) +\n\t\t\t\t2 * p1;\n\t\tdouble p = sqrt(p2 / 6.0);\n\t\tEigen::Matrix3d B = (1.0 / p) * (A - q * Eigen::Matrix3d::Identity());\n\t\tdouble r = B.determinant() / 2.0;\n\t\tdouble phi;\n\t\tif (r <= -1) {\n\t\t\tphi = M_PI / 3.0;\n\t\t} else if (r >= 1) {\n\t\t\tphi = 0.0;\n\t\t} else {\n\t\t\tphi = std::acos(r) / 3.0;\n\t\t}\n\t\teigenvalues(0) = q + 2.0 * p * std::cos(phi);\n\t\teigenvalues(2) = q + 2.0 * p * std::cos(phi + 2.0 * M_PI / 3.0);\n\t\teigenvalues(1) = q * 3.0 - eigenvalues(0) - eigenvalues(2);\n\t}\n\n\tEigen::Vector3d eigenvector =\n\t\t\t(A - Eigen::Matrix3d::Identity() * eigenvalues(0)) *\n\t\t\t(A.col(0) - Eigen::Vector3d(eigenvalues(1), 0.0, 0.0));\n\tdouble len = eigenvector.norm();\n\tif (len == 0.0) {\n\t\treturn Eigen::Vector3d::Zero();\n\t} else {\n\t\treturn eigenvector.normalized();\n\t}\n}\n\nEigen::Vector3d ComputeNormal(const PointCloud &cloud,\n\t\tconst std::vector<int> &indices)\n{\n\tif (indices.size() == 0) {\n\t\treturn Eigen::Vector3d::Zero();\n\t}\n\tEigen::Matrix3d covariance;\n\tEigen::Matrix<double, 9, 1> cumulants;\n\tcumulants.setZero();\n\tfor (size_t i = 0; i < indices.size(); i++) {\n\t\tconst Eigen::Vector3d &point = cloud.points_[indices[i]];\n\t\tcumulants(0) += point(0);\n\t\tcumulants(1) += point(1);\n\t\tcumulants(2) += point(2);\n\t\tcumulants(3) += point(0) * point(0);\n\t\tcumulants(4) += point(0) * point(1);\n\t\tcumulants(5) += point(0) * point(2);\n\t\tcumulants(6) += point(1) * point(1);\n\t\tcumulants(7) += point(1) * point(2);\n\t\tcumulants(8) += point(2) * point(2);\n\t}\n\tcumulants /= (double)indices.size();\n\tcovariance(0, 0) = cumulants(3) - cumulants(0) * cumulants(0);\n\tcovariance(1, 1) = cumulants(6) - cumulants(1) * cumulants(1);\n\tcovariance(2, 2) = cumulants(8) - cumulants(2) * cumulants(2);\n\tcovariance(0, 1) = cumulants(4) - cumulants(0) * cumulants(1);\n\tcovariance(1, 0) = covariance(0, 1);\n\tcovariance(0, 2) = cumulants(5) - cumulants(0) * cumulants(2);\n\tcovariance(2, 0) = covariance(0, 2);\n\tcovariance(1, 2) = cumulants(7) - cumulants(1) * cumulants(2);\n\tcovariance(2, 1) = covariance(1, 2);\n\n\treturn FastEigen3x3(covariance);\n\t//Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> solver;\n\t//solver.compute(covariance, Eigen::ComputeEigenvectors);\n\t//return solver.eigenvectors().col(0);\n}\n\n}\t// unnamed namespace\n\nbool EstimateNormals(PointCloud &cloud,\n\t\tconst KDTreeSearchParam &search_param/* = KDTreeSearchParamKNN()*/)\n{\n\tbool has_normal = cloud.HasNormals();\n\tif (cloud.HasNormals() == false) {\n\t\tcloud.normals_.resize(cloud.points_.size());\n\t}\n\tKDTreeFlann kdtree;\n\tkdtree.SetGeometry(cloud);\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n\tfor (int i = 0; i < (int)cloud.points_.size(); i++) {\n\t\tstd::vector<int> indices;\n\t\tstd::vector<double> distance2;\n\t\tEigen::Vector3d normal;\n\t\tif (kdtree.Search(cloud.points_[i], search_param, indices,\n\t\t\t\tdistance2) >= 3) {\n\t\t\tnormal = ComputeNormal(cloud, indices);\n\t\t\tif (normal.norm() == 0.0) {\n\t\t\t\tif (has_normal) {\n\t\t\t\t\tnormal = cloud.normals_[i];\n\t\t\t\t} else {\n\t\t\t\t\tnormal = Eigen::Vector3d(0.0, 0.0, 1.0);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (has_normal && normal.dot(cloud.normals_[i]) < 0.0) {\n\t\t\t\tnormal *= -1.0;\n\t\t\t}\n\t\t\tcloud.normals_[i] = normal;\n\t\t} else {\n\t\t\tcloud.normals_[i] = Eigen::Vector3d(0.0, 0.0, 1.0);\n\t\t}\n\t}\n\n\treturn true;\n}\n\nbool OrientNormalsToAlignWithDirection(PointCloud &cloud,\n\t\tconst Eigen::Vector3d &orientation_reference\n\t\t/* = Eigen::Vector3d(0.0, 0.0, 1.0)*/)\n{\n\tif (cloud.HasNormals() == false) {\n\t\tPrintDebug(\"[OrientNormalsToAlignWithDirection] No normals in the PointCloud. Call EstimateNormals() first.\\n\");\n\t}\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n\tfor (int i = 0; i < (int)cloud.points_.size(); i++) {\n\t\tauto &normal = cloud.normals_[i];\n\t\tif (normal.norm() == 0.0) {\n\t\t\tnormal = orientation_reference;\n\t\t} else if (normal.dot(orientation_reference) < 0.0) {\n\t\t\tnormal *= -1.0;\n\t\t}\n\t}\n\treturn true;\n}\n\nbool OrientNormalsTowardsCameraLocation(PointCloud &cloud,\n\t\tconst Eigen::Vector3d &camera_location/* = Eigen::Vector3d::Zero()*/)\n{\n\tif (cloud.HasNormals() == false) {\n\t\tPrintDebug(\"[OrientNormalsTowardsCameraLocation] No normals in the PointCloud. Call EstimateNormals() first.\\n\");\n\t}\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n\tfor (int i = 0; i < (int)cloud.points_.size(); i++) {\n\t\tEigen::Vector3d orientation_reference = camera_location -\n\t\t\t\tcloud.points_[i];\n\t\tauto &normal = cloud.normals_[i];\n\t\tif (normal.norm() == 0.0) {\n\t\t\tnormal = orientation_reference;\n\t\t\tif (normal.norm() == 0.0) {\n\t\t\t\tnormal = Eigen::Vector3d(0.0, 0.0, 1.0);\n\t\t\t} else {\n\t\t\t\tnormal.normalize();\n\t\t\t}\n\t\t} else if (normal.dot(orientation_reference) < 0.0) {\n\t\t\tnormal *= -1.0;\n\t\t}\n\t}\n\treturn true;\n}\n\n}\t// namespace three\n", "meta": {"hexsha": "e14640e06f7c21a57afd5e472d0350c834c275fe", "size": 6827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Core/Geometry/EstimateNormals.cpp", "max_stars_repo_name": "zjudmd1015/Open3D", "max_stars_repo_head_hexsha": "245df0fd1d9174f061152fcca16ea4b9d88e6f68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-07T13:57:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-07T13:57:14.000Z", "max_issues_repo_path": "src/Core/Geometry/EstimateNormals.cpp", "max_issues_repo_name": "3DReconstruction/Open3D", "max_issues_repo_head_hexsha": "a3673d753091daf36fe0555a164b3967bf16546c", "max_issues_repo_licenses": ["MIT"], "max_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/Geometry/EstimateNormals.cpp", "max_forks_repo_name": "3DReconstruction/Open3D", "max_forks_repo_head_hexsha": "a3673d753091daf36fe0555a164b3967bf16546c", "max_forks_repo_licenses": ["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.9806763285, "max_line_length": 115, "alphanum_fraction": 0.629852058, "num_tokens": 2216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5316391037353968}}
{"text": "#include <iostream>\n#include <memory>\n#include <random>\n#include <string>\n\n#include <Eigen/Sparse>\n\n#include \"GeometricMultigridOperators.h\"\n#include \"GeometricMultigridPoissonSolver.h\"\n#include \"InitialMultigridTestDomains.h\"\n#include \"Renderer.h\"\n#include \"ScalarGrid.h\"\n#include \"Transform.h\"\n#include \"UniformGrid.h\"\n#include \"Utilities.h\"\n\nusing namespace FluidSim2D::RenderTools;\nusing namespace FluidSim2D::SimTools;\n\nstd::unique_ptr<Renderer> renderer;\n\nstatic constexpr int gridSize = 512;\nstatic constexpr bool useComplexDomain = true;\nstatic constexpr bool useSolidSphere = true;\n\nint main(int argc, char** argv)\n{\n\tusing namespace GeometricMultigridOperators;\n\n\tusing StoreReal = double;\n\tusing SolveReal = double;\n\n\tUniformGrid<CellLabels> domainCellLabels;\n\tVectorGrid<StoreReal> boundaryWeights;\n\n\tint mgLevels;\n\t{\n\t\tUniformGrid<CellLabels> baseDomainCellLabels;\n\t\tVectorGrid<StoreReal> baseBoundaryWeights;\n\n\t\t// Complex domain set up\n\t\tif (useComplexDomain)\n\t\t\tbuildComplexDomain(baseDomainCellLabels,\n\t\t\t\t\t\t\t\tbaseBoundaryWeights,\n\t\t\t\t\t\t\t\tgridSize,\n\t\t\t\t\t\t\t\tuseSolidSphere);\n\t\t// Simple domain set up\n\t\telse\n\t\t\tbuildSimpleDomain(baseDomainCellLabels,\n\t\t\t\t\t\t\t\tbaseBoundaryWeights,\n\t\t\t\t\t\t\t\tgridSize,\n\t\t\t\t\t\t\t\t1 /*dirichlet band*/);\n\n\t\t// Build expanded domain\n\t\tstd::pair<Vec2i, int> mgSettings = buildExpandedDomain(domainCellLabels, boundaryWeights, baseDomainCellLabels, baseBoundaryWeights);\n\n\t\tmgLevels = mgSettings.second;\n\t}\n\n\tSolveReal dx = boundaryWeights.dx();\n\n\tUniformGrid<StoreReal> rhsGrid(domainCellLabels.size(), 0);\n\n\tUniformGrid<StoreReal> solutionGrid(domainCellLabels.size(), 0);\n\n\ttbb::parallel_for(tbb::blocked_range<int>(0, domainCellLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t{\n\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t{\n\t\t\tVec2i cell = domainCellLabels.unflatten(cellIndex);\n\n\t\t\tif (domainCellLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\tdomainCellLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t{\n\t\t\t\tVec2f point(dx * Vec2f(cell));\n\t\t\t\tsolutionGrid(cell) = 4. * (std::sin(2 * PI * point[0]) * std::sin(2 * PI * point[1]) +\n\t\t\t\t\t\t\t\t\t\t\tstd::sin(4 * PI * point[0]) * std::sin(4 * PI * point[1]));\n\t\t\t}\n\t\t}\n\t});\n\n\tauto l1Norm = [&](const UniformGrid<StoreReal> &grid)\n\t{\n\t\tassert(grid.size() == domainCellLabels.size());\n\n\t\ttbb::enumerable_thread_specific<SolveReal> parallelAccumulatedValue(SolveReal(0));\n\t\ttbb::parallel_for(tbb::blocked_range<int>(0, domainCellLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t\t{\n\t\t\tauto& localAccumulatedValue = parallelAccumulatedValue.local();\n\n\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t{\n\t\t\t\tVec2i cell = domainCellLabels.unflatten(cellIndex);\n\n\t\t\t\tif (domainCellLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\tdomainCellLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t{\n\t\t\t\t\tlocalAccumulatedValue += fabs(grid(cell));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tSolveReal accumulatedValue = 0;\n\t\tparallelAccumulatedValue.combine_each([&](const SolveReal localAccumulatedValue)\n\t\t{\n\t\t\taccumulatedValue += localAccumulatedValue;\n\t\t});\n\n\t\treturn accumulatedValue;\n\t};\n\n\t// Print initial guess\n\tsolutionGrid.printAsOBJ(\"initialGuess\");\n\n\tstd::cout << \"L-1 initial: \" << l1Norm(solutionGrid) << std::endl;\n\n\t// Pre-build multigrid preconditioner\n\tGeometricMultigridPoissonSolver mgSolver(domainCellLabels, boundaryWeights, mgLevels, dx);\n\t\n\tfor (int iteration = 0; iteration < 50; ++iteration)\n\t{\n\t\tmgSolver.applyMGVCycle(solutionGrid, rhsGrid, true /* use initial guess */);\n\n\t\tstd::cout << \"L-1 v-cycle \" << iteration << \": \" << l1Norm(solutionGrid) << std::endl;\n\n\t\t// Print corrected solution after one v-cycle\n\t\t//solutionGrid.printAsOBJ(\"solutionGrid\" + std::to_string(iteration));\n\t}\n\n\t// Print domain labels to make sure they are set up correctly\n\tint pixelHeight = 1080;\n\tint pixelWidth = pixelHeight;\n\trenderer = std::make_unique<Renderer>(\"One level correction test\", Vec2i(pixelWidth, pixelHeight), Vec2f(0), 1, &argc, argv);\n\n\tScalarGrid<float> tempGrid(Transform(dx, Vec2f(0)), domainCellLabels.size());\n\n\ttbb::parallel_for(tbb::blocked_range<int>(0, tempGrid.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t{\n\t\tfor (int flatIndex = range.begin(); flatIndex != range.end(); ++flatIndex)\n\t\t{\n\t\t\tVec2i cell = tempGrid.unflatten(flatIndex);\n\n\t\t\ttempGrid(cell) = float(domainCellLabels(cell));\n\t\t}\n\t});\n\n\ttempGrid.drawVolumetric(*renderer, Vec3f(0), Vec3f(1), float(CellLabels::INTERIOR_CELL), float(CellLabels::BOUNDARY_CELL));\n\n\trenderer->run();\n}", "meta": {"hexsha": "6818eb3eb56f26efdcbd550b6e6857d943305aa8", "size": 4591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Projects/Tests/TestGeometricMGPoissonSolver/TestOneLevel/TestOneLevel.cpp", "max_stars_repo_name": "rgoldade/2DFluid", "max_stars_repo_head_hexsha": "8a30e17fc4bd97ca3c15e4b74f2aef896f39977c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-03-07T15:24:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-03T13:11:09.000Z", "max_issues_repo_path": "Projects/Tests/TestGeometricMGPoissonSolver/TestOneLevel/TestOneLevel.cpp", "max_issues_repo_name": "rgoldade/2DFluid", "max_issues_repo_head_hexsha": "8a30e17fc4bd97ca3c15e4b74f2aef896f39977c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-07T12:42:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-04T18:56:56.000Z", "max_forks_repo_path": "Projects/Tests/TestGeometricMGPoissonSolver/TestOneLevel/TestOneLevel.cpp", "max_forks_repo_name": "rgoldade/2DFluid", "max_forks_repo_head_hexsha": "8a30e17fc4bd97ca3c15e4b74f2aef896f39977c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-05-14T05:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-11T17:13:00.000Z", "avg_line_length": 30.6066666667, "max_line_length": 139, "alphanum_fraction": 0.7207580048, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5316391028548574}}
{"text": "#ifndef SCALARTYPE_HPP\n#define SCALARTYPE_HPP\n\n#include <boost/rational.hpp>\n#include <boost/operators.hpp>\n#include <sstream>\n#include <iomanip>\n#include <iostream>\n\nstruct scalarreal : boost::operators<scalarreal> {\n\ttemplate<typename... T>\n\tusing variant = boost::variant<T...>;\n\tusing rtype = boost::rational<int>;\n\n\tstruct eulerconst {};\n\tstruct piconst {};\n\n\tvariant<rtype,double,eulerconst,piconst> v;\n\n\tscalarreal(double val=0.0) : v(val) {}\n\texplicit scalarreal(eulerconst ec) : v(ec) {}\n\texplicit scalarreal(piconst pc) : v(pc) {}\n\texplicit scalarreal(rtype rt) : v(std::move(rt)) {}\n\n\tscalarreal(int i) : v(rtype(i)) {}\n\n\ttemplate<typename I1, typename I2>\n\texplicit scalarreal(I1 &&num, I2 &&den) : v(rtype(std::forward<I1>(num),std::forward<I2>(den))) {}\n\n\t/*\n\tscalarreal(scalarreal &r) : v(r.v) {}\n\tscalarreal(const scalarreal &r) : v(r.v) {}\n\tscalarreal(scalarreal &&r) : v(std::move(r.v)) {}\n\t*/\n\n\texplicit operator double() const {\n\t\tswitch(v.which()) {\n\t\t\tcase 0: return (double)(boost::get<rtype>(v).numerator())/(double)(boost::get<rtype>(v).denominator());\n\t\t\tcase 1: return boost::get<double>(v);\n\t\t\tcase 2: return std::exp(1.0);\n\t\t\tcase 3: return std::acos(-1.0);\n\t\t\tdefault: return 0.0;\n\t\t}\n\t}\n\n\texplicit operator int() const {\n\t\treturn asint();\n\t}\n\n\tscalarreal operator-() const {\n\t\tif (v.which()==0) return scalarreal{-boost::get<rtype>(v)};\n\t\telse return scalarreal{-(double)(*this)};\n\t\treturn *this;\n\t}\n\n\tscalarreal &operator+=(const scalarreal &s) {\n\t\tif (v.which()==0 && s.v.which()==0) boost::get<rtype>(v) += boost::get<rtype>(s.v);\n\t\telse v = (double)(*this) + (double)(s);\n\t\treturn *this;\n\t}\n\tscalarreal &operator-=(const scalarreal &s) {\n\t\tif (v.which()==0 && s.v.which()==0) boost::get<rtype>(v) -= boost::get<rtype>(s.v);\n\t\telse v = (double)(*this) - (double)(s);\n\t\treturn *this;\n\t}\n\tscalarreal &operator*=(const scalarreal &s) {\n\t\tif (v.which()==0 && s.v.which()==0) boost::get<rtype>(v) *= boost::get<rtype>(s.v);\n\t\telse v = (double)(*this) * (double)(s);\n\t\treturn *this;\n\t}\n\tscalarreal &operator/=(const scalarreal &s) {\n\t\tif (v.which()==0 && s.v.which()==0 && s) boost::get<rtype>(v) /= boost::get<rtype>(s.v);\n\t\telse v = (double)(*this) / (double)(s);\n\t\treturn *this;\n\t}\n\tbool operator<(const scalarreal &s) const {\n\t\tif (v.which()==0 && s.v.which()==0) return boost::get<rtype>(v) < boost::get<rtype>(s.v);\n\t\telse return (double)(*this) < (double)(s);\n\t}\n\tbool operator==(const scalarreal &s) const {\n\t\tif (v.which()==0 && s.v.which()==0) return boost::get<rtype>(v) == boost::get<rtype>(s.v);\n\t\telse return (double)(*this) == (double)(s);\n\t}\n\tbool operator==(const double &d) const {\n\t\treturn (double)(*this) == d;\n\t}\n\tbool operator<(const double &d) const {\n\t\treturn (double)(*this) < d;\n\t}\n\tbool operator==(const int &i) const {\n\t\tswitch (v.which()) {\n\t\t\tcase 0: return boost::get<rtype>(v)==i;\n\t\t\tcase 1: return (double)(*this) == i;\n\t\t\tdefault: return false;\n\t\t}\n\t}\n\tbool operator<(const int &i) const {\n\t\tif (v.which()==0) return boost::get<rtype>(v)<i;\n\t\telse return (double)(*this) < i;\n\t}\n\tconst scalarreal &operator++() {\n\t\tif (v.which()==0) boost::get<rtype>(v)++;\n\t\telse v = (double)(*this)+1.0;\n\t\treturn *this;\n\t}\n\tconst scalarreal &operator--() {\n\t\tif (v.which()==0) boost::get<rtype>(v)--;\n\t\telse v = (double)(*this)-1.0;\n\t\treturn *this;\n\t}\n\t\t\n\texplicit operator bool() const {\n\t\tswitch(v.which()) {\n\t\t\tcase 0: return (bool)(boost::get<rtype>(v));\n\t\t\tcase 1: return boost::get<double>(v)!=0.0;\n\t\t\tcase 2: return true;\n\t\t\tcase 3: return true;\n\t\t\tdefault: return true;\n\t\t}\n\t}\n\tbool operator!() const {\n\t\tswitch(v.which()) {\n\t\t\tcase 0: return !(boost::get<rtype>(v));\n\t\t\tcase 1: return boost::get<double>(v)==0.0;\n\t\t\tcase 2: return false;\n\t\t\tcase 3: return false;\n\t\t\tdefault: return false;\n\t\t}\n\t}\n\n\tbool isint() const {\n\t\tswitch(v.which()) {\n\t\t\tcase 0: return boost::get<rtype>(v).numerator() % boost::get<rtype>(v).denominator() == 0;\n\t\t\tcase 1: return std::fmod(boost::get<double>(v),1.0) == 0.0;\n\t\t\tdefault: return false;\n\t\t}\n\t}\n\n\tbool iseven() const {\n\t\treturn isint() && asint()%2==0;\n\t}\n\tbool isodd() const {\n\t\treturn isint() && asint()%2==1;\n\t}\n\n\tscalarreal round() const {\n\t\tswitch(v.which()) {\n\t\t\tcase 0: {\n\t\t\t\t   auto &r = boost::get<rtype>(v);\n\t\t\t\t   auto div = std::div(r.numerator(),r.denominator());\n\t\t\t\t   // away from zero... as in std::round\n\t\t\t\t   if (div.rem*2<=-abs(r.denominator()))\n\t\t\t\t\t   return div.quot - 1;\n\t\t\t\t   else if (div.rem*2>=abs(r.denominator()))\n\t\t\t\t\t   return div.quot + 1;\n\t\t\t\t   else return div.quot;\n\t\t\t   }\n\t\t\tdefault: return std::round((double)(*this));\n\t\t}\n\t}\n\n\tscalarreal floor() const {\n\t\tswitch(v.which()) {\n\t\t\tcase 0: {\n\t\t\t\t   auto &r = boost::get<rtype>(v);\n\t\t\t\t   auto div = std::div(r.numerator(),r.denominator());\n\t\t\t\t   if (div.rem<0)\n\t\t\t\t\t   return div.quot - 1;\n\t\t\t\t   else return div.quot;\n\t\t\t   }\n\t\t\tdefault: return std::floor((double)(*this));\n\t\t}\n\t}\n\n\tscalarreal ceil() const {\n\t\tswitch(v.which()) {\n\t\t\tcase 0: {\n\t\t\t\t   auto &r = boost::get<rtype>(v);\n\t\t\t\t   auto div = std::div(r.numerator(),r.denominator());\n\t\t\t\t   if (div.rem>0)\n\t\t\t\t\t   return div.quot + 1;\n\t\t\t\t   else return div.quot;\n\t\t\t   }\n\t\t\tdefault: return std::ceil((double)(*this));\n\t\t}\n\t}\n\n\tint asint() const {\n\t\tswitch(v.which()) {\n\t\t\tcase 0: return boost::get<rtype>(v).numerator() / boost::get<rtype>(v).denominator();\n\t\t\tdefault: return std::round((double)(*this));\n\t\t}\n\t}\n\n\tbool iszero() const {\n\t\tswitch(v.which()) {\n\t\t\tcase 0: return boost::get<rtype>(v).numerator() ==0;\n\t\t\tcase 1: return boost::get<double>(v) == 0.0;\n\t\t\tdefault: return false;\n\t\t}\n\t}\n};\n\nnamespace std {\n\ttemplate<> struct numeric_limits<scalarreal> {\n\t\tstatic scalarreal infinity() {\n\t\t\treturn scalarreal{std::numeric_limits<double>::infinity()};\n\t\t}\n\t\tstatic constexpr bool is_specialized = true;\n\t\tstatic constexpr bool is_signed = true;\n\t\tstatic constexpr bool is_integer = false;\n\t\tstatic constexpr bool is_exact = false;\n\t\tstatic constexpr int digits = numeric_limits<double>::digits;\n\t\tstatic constexpr int digits10 = numeric_limits<double>::digits10;\n\t\tstatic constexpr int radix = numeric_limits<double>::radix;\n\t};\n\n\tbool isfinite(const scalarreal &s) {\n\t\tswitch(s.v.which()) {\n\t\t\tcase 1: return std::isfinite(boost::get<double>(s.v));\n\t\t\tdefault: return true;\n\t\t}\n\t}\n}\n\nauto round(const scalarreal &s) {\n\treturn s.round();\n}\nauto ceil(const scalarreal &s) {\n\treturn s.ceil();\n}\nauto floor(const scalarreal &s) {\n\treturn s.floor();\n}\n\nstd::string tostring(const scalarreal &s) {\n\tif (s.isint()) return std::to_string(s.asint());\n\tswitch (s.v.which()) {\n\t\tcase 0: {\n\t\t\t\t   auto &r = boost::get<scalarreal::rtype>(s.v);\n\t\t\t\t   return std::string(\"(\")+std::to_string(r.numerator())+\"/\"+std::to_string(r.denominator())+\")\";\n\t\t\t   }\n\t\tcase 1: {\n\t\t\t\t   std::ostringstream ss;\n\t\t\t\t   ss << std::setprecision(17) << boost::get<double>(s.v);\n\t\t\t\t   return {ss.str()};\n\t\t\t   }\n\t\tcase 2: return {\"e\"};\n\t\tcase 3: return {\"pi\"};\n\t\tdefault: return {\"?\"};\n\t}\n}\n\n/*\nstd::ostream &operator<<(std::ostream &os, const scalarreal &s) {\n\treturn os << tostring(s);\n}\n\nstd::istream &operator>>(std::istream &is, scalarreal &s) {\n\t// not implemented\n\treturn is;\n}\n*/\n\nscalarreal abs(const scalarreal &s) {\n\tif (s.v.which()==0)\n\t\treturn scalarreal{abs(boost::get<scalarreal::rtype>(s.v))};\n\treturn scalarreal{(double)std::abs((double)(s))};\n}\n\nscalarreal log(const scalarreal &e) {\n\tif (e==1.0) return scalarreal{0};\n\tswitch(e.v.which()) {\n\t\tcase 2: return scalarreal{1};\n\t\tdefault: return log((double)e);\n\t}\n}\n\ntemplate<typename T>\nT intpow1(T b, int e) {\n\tif (e==1) return b;\n\tT ret = intpow1(b,e/2);\n\tret *= ret;\n\tif (e&1) ret *= b;\n\treturn ret;\n}\n\ntemplate<typename T>\nT intpow(T b, int e) {\n\tif (e==0) return T{1};\n\tif (e<0) return T{1}/intpow1(b,-e);\n\treturn intpow1(b,e);\n}\n\nscalarreal pow(const scalarreal &b, const int &e) {\n\tif (e==1) return b;\n\tif (e==0) return scalarreal{1};\n\tif (e==-1) return 1/b;\n\tif (b.v.which()==2)\n\t\treturn scalarreal{std::exp((double)e)};\n\tif (b.v.which()==1)\n\t\treturn scalarreal{ std::pow((double)b,(double)e) };\n\tif (b==1) return scalarreal{1};\n\tif (b.v.which()==0)\n\t\treturn intpow(b,e);\n\telse\n\t\treturn scalarreal{ std::pow((double)b,(double)e) };\n}\n\nscalarreal pow(const scalarreal &b, const scalarreal &e) {\n\tif (e==1) return b;\n\tif (e==0) return scalarreal{1};\n\tif (e==-1) return 1/b;\n\tif (b.v.which()==2)\n\t\treturn scalarreal{std::exp((double)e)};\n\tif (b.v.which()==1 || e.v.which()==1)\n\t\treturn scalarreal{ std::pow((double)b,(double)e) };\n\tif (b==1) return scalarreal{1};\n\tif (b.v.which()==0 && e.isint())\n\t\treturn intpow(b,e.asint());\n\telse\n\t\treturn scalarreal{ std::pow((double)b,(double)e) };\n}\n\n#endif\n", "meta": {"hexsha": "58bbcf6a2cae86d770a3692c4c93492674847eb4", "size": 8587, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "scalartype.hpp", "max_stars_repo_name": "cshelton/tqscas", "max_stars_repo_head_hexsha": "404fc79993571fe0c844bfca964eec5484e3b307", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scalartype.hpp", "max_issues_repo_name": "cshelton/tqscas", "max_issues_repo_head_hexsha": "404fc79993571fe0c844bfca964eec5484e3b307", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scalartype.hpp", "max_forks_repo_name": "cshelton/tqscas", "max_forks_repo_head_hexsha": "404fc79993571fe0c844bfca964eec5484e3b307", "max_forks_repo_licenses": ["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.3404907975, "max_line_length": 106, "alphanum_fraction": 0.6111563992, "num_tokens": 2658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5316390983788757}}
{"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <iterator>\n#include <Eigen/Dense>\n\nclass Point {\n  public:\n    Point();\n    Point(std::istream& in);\n    std::istream& read(std::istream&);\n    void print( std::ostream& );\n    double getX() const { return x; };\n    double getY() const { return y; };\n\n  private:\n    double x;\n    double y;\n    std::string name;\n};\n\nPoint::Point() : x(0), y(0) {}\n\nPoint::Point(std::istream& in){\n  read( in );\n}\n\nstd::istream& Point::read( std::istream& in){\n  in >> name >> x >> y;\n  return in;\n}\n\nvoid Point::print( std::ostream& out ) {\n  out << name << \" \" << x << \" \" << y << std::endl;\n}\n\nstd::istream& operator>>(std::istream& in, Point& p){\n  p.read(in);\n  return in;\n}\n\nvoid parse_args(int argc , char* argv[], std::string &fname)\n{\n  if ( 1 == argc ) {\n    fname = \"data.txt\";\n  } else {\n    fname = argv[1];\n  }\n}\n\nint main(int argc, char* argv[])\n{\n  std::string fname;\n\n  parse_args(argc, argv, fname);\n\n  std::ifstream in(fname);\n  if (!in) {\n    std::cout << \"File not found \" << fname << std::endl;\n    return 1;\n  }\n  \n  // Use STL to read numbers from file into a vector\n  std::vector<Point> data;\n  \n  std::copy( std::istream_iterator<Point>(in), \n    std::istream_iterator<Point>(), std::back_inserter(data));\n\n  // Transform data\n  std::vector<double> x;\n  std::transform( data.begin(), data.end(), std::back_inserter(x),\n    [](Point p){ return p.getX(); });\n  \n  std::vector<double> y;\n  std::transform( data.begin(), data.end(), std::back_inserter(y),\n    [](Point p){ return p.getY(); });\n\n  Eigen::Map<Eigen::VectorXd> X(x.data(),x.size());\n  Eigen::Map<Eigen::VectorXd> Y(y.data(),y.size());\n\n  // Store x and y coordinates as 2 x N matrix [x1, x2, ...; y1, y2, ...]\n  Eigen::MatrixXd m( 2, x.size());\n  m.row(0) = X;\n  m.row(1) = Y;\n  std::cout << m << std::endl;\n\n  // Shear transformation\n  Eigen::Matrix2d A;\n  A << 1, 2, 0, 1;\n  m = A*m;\n  std::cout << m << std::endl;\n  X = m.row(0);\n\n  for( auto d : data){\n    d.print( std::cout );\n  }\n  std::cout << std::endl;\n\n  for( auto xv : x){\n    std::cout << xv << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "dc1485b05fffe1a03819a9a7e51325149e026892", "size": 2162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ProcessData/process_data.cpp", "max_stars_repo_name": "mattmcd/CppSnippets", "max_stars_repo_head_hexsha": "b5f6a8bb8262d8362a7b7864a1babbe89ed32a9d", "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": "ProcessData/process_data.cpp", "max_issues_repo_name": "mattmcd/CppSnippets", "max_issues_repo_head_hexsha": "b5f6a8bb8262d8362a7b7864a1babbe89ed32a9d", "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": "ProcessData/process_data.cpp", "max_forks_repo_name": "mattmcd/CppSnippets", "max_forks_repo_head_hexsha": "b5f6a8bb8262d8362a7b7864a1babbe89ed32a9d", "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.2056074766, "max_line_length": 73, "alphanum_fraction": 0.5675300648, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5315676894310799}}
{"text": "// Author(s): Jan Friso Groote\n// Copyright: see the accompanying file COPYING or copy at\n// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n/// \\file find_test.cpp\n/// \\brief Test the linear_inequality functionality\n\n#include <boost/test/minimal.hpp>\n#include \"mcrl2/data/parse.h\"\n#include \"mcrl2/data/linear_inequalities.h\"\n\nusing namespace mcrl2;\nusing namespace mcrl2::core;\nusing namespace mcrl2::data;\n\nvoid split_conjunction_of_inequalities_set(const data_expression& e, std::vector < linear_inequality >& v, const rewriter& r)\n{\n  if (sort_bool::is_and_application(e))\n  {\n    split_conjunction_of_inequalities_set(application(e)[0],v,r);\n    split_conjunction_of_inequalities_set(application(e)[1],v,r);\n  }\n  else\n  {\n    v.push_back(linear_inequality(e,r));\n  }\n}\n\nbool test_consistency_of_inequalities(const std::string& vars,\n                                      const std::string& inequalities, \n                                      const bool expect_consistent)\n{\n  // Take care that reals are part of the data type.\n  data_specification data_spec;\n  variable_list variables=parse_variables(vars);\n  data_spec.add_context_sort(sort_real::real_());\n  const data_expression e=parse_data_expression(inequalities,variables,data_spec);\n\n  rewriter r(data_spec);\n  std::vector < linear_inequality > v_inequalities;\n  split_conjunction_of_inequalities_set(e,v_inequalities,r);\n\n  if (is_inconsistent(v_inequalities,r))\n  {\n    if (expect_consistent)\n    {\n      std::cout << \"Expected consistent, found inconsistent\\n\";\n      std::cout << variables << \": \" << inequalities << \"\\n\";\n      std::cout << \"Internal inequalities: \" << pp_vector(v_inequalities) << \"\\n\";\n      return false;\n    }\n  }\n  else\n  {\n    if (!expect_consistent)\n    {\n      std::cout << \"Expected inconsistent, found consistent\\n\";\n      std::cout << variables << \": \" << inequalities << \"\\n\";\n      std::cout << \"Internal inequalities: \" << pp_vector(v_inequalities) << \"\\n\";\n      return false;\n    }\n  }\n  return true;\n}\n\nbool test_application_of_Fourier_Motzkin(const std::string& vars,\n                                         const std::string& variables_to_be_eliminated,\n                                         const std::string& inequalities,\n                                         const std::string& inconsistent_with)\n{\n  // Take care that reals are part of the data type.\n  data_specification data_spec;\n  data_spec.add_context_sort(sort_real::real_());\n  const variable_list variables=parse_variables(vars);\n  const data_expression e_in=parse_data_expression(inequalities,variables,data_spec);\n  const variable_list v_elim=data::detail::parse_variables_new(variables_to_be_eliminated);\n\n  rewriter r(data_spec);\n  std::vector < linear_inequality > v_inequalities;\n  split_conjunction_of_inequalities_set(e_in,v_inequalities,r);\n\n  std::vector < linear_inequality> resulting_inequalities;\n  fourier_motzkin(v_inequalities, v_elim.begin(), v_elim.end(), resulting_inequalities, r);\n\n  std::vector < linear_inequality> inconsistent_inequalities=resulting_inequalities;\n  inconsistent_inequalities.push_back(linear_inequality(parse_data_expression(inconsistent_with,variables,data_spec),r));\n  if (!is_inconsistent(inconsistent_inequalities,r, false))\n  {\n    std::cout << \"Expected set of inequations to be inconsisten with given inequality after applying Fourier-Motzkin elimination\\n\";\n    std::cout << \"Input: \" << variables << \": \" << inequalities << \"\\n\";\n    std::cout << \"Parsed input : \" << pp_vector(v_inequalities) << \"\\n\";\n    std::cout << \"Variables to be eliminated: \" << v_elim << \"\\n\";\n    std::cout << \"Input after applying Fourier Motzkin: \" << pp_vector(resulting_inequalities) << \"\\n\";\n    std::cout << \"Should be inconsistent with \" << inconsistent_with << \"\\n\";\n    std::cout << \"Inconsistent inequality after parsing \" << pp(linear_inequality(parse_data_expression(inconsistent_with,variables,data_spec),r)) << \"\\n\";\n    return false;\n  }\n  return true;\n}\n\nint test_main(int /* argc */, char** /* argv[]*/)\n{\n  // BOOST_CHECK(test_consistency_of_inequalities(\"x:Real;\", \"x<3  && x>=4\", false));\n  // BOOST_CHECK(test_consistency_of_inequalities(\"x:Real;\", \"x<3  && x>=2\", true));\n  // BOOST_CHECK(test_consistency_of_inequalities(\"x:Real;\", \"x<3  && x>=3\", false));\n  // BOOST_CHECK(test_consistency_of_inequalities(\"x:Real;\", \"x<=3  && x>=3\", true));\n  // BOOST_CHECK(test_consistency_of_inequalities(\"u:Real;\",\"0 <= u && -u <= -4 && -u < 0\",true));\n  BOOST_CHECK(test_consistency_of_inequalities(\"u,t:Real;\",\"u + -t <= 1 && -u <= -4 && t < u && -u < 0 && -t <= 0 \",true));\n  // BOOST_CHECK(test_consistency_of_inequalities(\"u,t,l:Real;\",\"u + -t <= 1 && -u <= -4 && -u + l < 0 && -u < 0 && -t <= 0 && -l + t <= 0\",true));\n\n  // BOOST_CHECK(test_application_of_Fourier_Motzkin(\"x,y:Real;\", \"y:Real;\", \"-y + x < 0 &&  y < 2\", \"x>=2\"));\n  return 0;\n}\n\n", "meta": {"hexsha": "381fa1e7bcd86404bb85defd5943291c002d6bfe", "size": 5037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/data/test/linear_inequalities_test.cpp", "max_stars_repo_name": "gijskant/mcrl2-pmc", "max_stars_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/data/test/linear_inequalities_test.cpp", "max_issues_repo_name": "gijskant/mcrl2-pmc", "max_issues_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/data/test/linear_inequalities_test.cpp", "max_forks_repo_name": "gijskant/mcrl2-pmc", "max_forks_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "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.3277310924, "max_line_length": 155, "alphanum_fraction": 0.675402025, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.531567672380108}}
{"text": "#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <vector>\n\n#include \"../geometry/Polygon2.hh\"\n#include \"helpers.hh\"\n\nusing namespace std;\nusing namespace bold;\nusing namespace Eigen;\n\nTEST (Polygon2Tests, basics)\n{\n  Polygon2<int>::PointVector points;\n  points.emplace_back(0,0);\n  points.emplace_back(0,1);\n  points.emplace_back(1,0);\n\n  Polygon2<int> poly(points);\n\n  ASSERT_EQ ( 3, poly.vertexCount() );\n  EXPECT_TRUE ( VectorsEqual(Vector2i(0,0), poly[0] ));\n  EXPECT_TRUE ( VectorsEqual(Vector2i(0,1), poly[1] ));\n  EXPECT_TRUE ( VectorsEqual(Vector2i(1,0), poly[2] ));\n}\n\nTEST (Polygon2Tests, int_squareContains)\n{\n  Polygon2<int>::PointVector points;\n  points.emplace_back(0,0);\n  points.emplace_back(0,2);\n  points.emplace_back(2,2);\n  points.emplace_back(2,0);\n\n  Polygon2<int> poly(points);\n\n  EXPECT_TRUE( poly.contains(Vector2i(0,0)) );\n  EXPECT_TRUE( poly.contains(Vector2i(0,1)) );\n  EXPECT_TRUE( poly.contains(Vector2i(1,1)) );\n\n  EXPECT_FALSE( poly.contains(Vector2i(2,1)) );\n  EXPECT_FALSE( poly.contains(Vector2i(2,2)) );\n  EXPECT_FALSE( poly.contains(Vector2i(3,2)) );\n  EXPECT_FALSE( poly.contains(Vector2i(3,3)) );\n  EXPECT_FALSE( poly.contains(Vector2i(2,3)) );\n  EXPECT_FALSE( poly.contains(Vector2i(0,3)) );\n  EXPECT_FALSE( poly.contains(Vector2i(3,0)) );\n  EXPECT_FALSE( poly.contains(Vector2i(-1,-1)) );\n  EXPECT_FALSE( poly.contains(Vector2i(-1,1)) );\n  EXPECT_FALSE( poly.contains(Vector2i(1,-1)) );\n}\n\nTEST (Polygon2Tests, float_squareContains)\n{\n  Polygon2<float>::PointVector points;\n  points.emplace_back(0,0);\n  points.emplace_back(0,2);\n  points.emplace_back(2,2);\n  points.emplace_back(2,0);\n\n  Polygon2<float> poly(points);\n\n  EXPECT_TRUE( poly.contains(Vector2f(0,0)) );\n  EXPECT_TRUE( poly.contains(Vector2f(0,1)) );\n  EXPECT_TRUE( poly.contains(Vector2f(1,1)) );\n  EXPECT_TRUE( poly.contains(Vector2f(1.99999,1)) );\n  EXPECT_TRUE( poly.contains(Vector2f(1.99999,1.99999)) );\n\n  EXPECT_FALSE( poly.contains(Vector2f(2,1)) );\n  EXPECT_FALSE( poly.contains(Vector2f(2,2)) );\n  EXPECT_FALSE( poly.contains(Vector2f(3,2)) );\n  EXPECT_FALSE( poly.contains(Vector2f(3,3)) );\n  EXPECT_FALSE( poly.contains(Vector2f(2,3)) );\n  EXPECT_FALSE( poly.contains(Vector2f(0,3)) );\n  EXPECT_FALSE( poly.contains(Vector2f(3,0)) );\n  EXPECT_FALSE( poly.contains(Vector2f(-1,-1)) );\n  EXPECT_FALSE( poly.contains(Vector2f(-1,1)) );\n  EXPECT_FALSE( poly.contains(Vector2f(1,-1)) );\n}\n\nTEST (Polygon2Tests, double_diamondContains)\n{\n  Polygon2<double>::PointVector points;\n  points.emplace_back(0,0);\n  points.emplace_back(-1,1);\n  points.emplace_back(0,2);\n  points.emplace_back(1,1);\n\n  Polygon2<double> poly(points);\n\n  // vertices\n  EXPECT_TRUE( poly.contains(Vector2d(-1,1)) );\n  EXPECT_FALSE( poly.contains(Vector2d(0,0)) );\n  EXPECT_FALSE( poly.contains(Vector2d(1,1)) );\n  EXPECT_FALSE( poly.contains(Vector2d(0,2)) );\n\n  // clearly inside\n  EXPECT_TRUE( poly.contains(Vector2d(0,1)) );\n  EXPECT_TRUE( poly.contains(Vector2d(0,0.001)) );\n\n  // clearly outside\n  EXPECT_FALSE( poly.contains(Vector2d(1,0)) );\n  EXPECT_FALSE( poly.contains(Vector2d(1,1)) );\n}\n\nTEST (Polygon2Tests, double_triangleContains)\n{\n  Polygon2<double>::PointVector points;\n  points.emplace_back(0,0);\n  points.emplace_back(1,0);\n  points.emplace_back(0,1);\n\n  Polygon2<double> poly(points);\n\n  EXPECT_TRUE( poly.contains(Vector2d(0,0)) );\n  EXPECT_TRUE( poly.contains(Vector2d(0.0001,0.0001)) );\n  EXPECT_TRUE( poly.contains(Vector2d(0.0005,0.9990)) );\n  EXPECT_TRUE( poly.contains(Vector2d(0.9990,0.0005)) );\n  EXPECT_TRUE( poly.contains(Vector2d(0.4999,0.4999)) );\n\n  EXPECT_FALSE( poly.contains(Vector2d(0.0005,1)) );\n  EXPECT_FALSE( poly.contains(Vector2d(1,0.0005)) );\n  EXPECT_FALSE( poly.contains(Vector2d(0.5001,0.5001)) );\n  EXPECT_FALSE( poly.contains(Vector2d(1,1)) );\n  EXPECT_FALSE( poly.contains(Vector2d(-0.0001,-0.0001)) );\n  EXPECT_FALSE( poly.contains(Vector2d(-0.0001,0.0001)) );\n  EXPECT_FALSE( poly.contains(Vector2d(0.0001,-0.0001)) );\n}\n\nTEST (Polygon2Tests, clip)\n{\n  // unit square\n  Polygon2<double>::PointVector points;\n  points.emplace_back(0,0);\n  points.emplace_back(1,0);\n  points.emplace_back(1,1);\n  points.emplace_back(0,1);\n\n  Polygon2<double> poly(points);\n\n  // Exactly corner to corner, diagonally (touching all four line segments)\n  auto clipped = poly.clipLine(LineSegment2d(Vector2d(0,0),Vector2d(1,1)));\n  ASSERT_TRUE(clipped.hasValue());\n  ASSERT_TRUE(LinesEqual(\n    LineSegment2d(Vector2d(0,0),Vector2d(1,1)),\n    clipped.value()\n  ));\n\n  // Inside, completely contained\n  clipped = poly.clipLine(LineSegment2d(Vector2d(0.25,0.25),Vector2d(0.75,0.75)));\n  ASSERT_TRUE(clipped.hasValue());\n  ASSERT_TRUE(LinesEqual(\n    LineSegment2d(Vector2d(0.25,0.25),Vector2d(0.75,0.75)),\n    clipped.value()\n  ));\n\n  // From inside (corner) to outside, running through diagonally opposite corner (touching all four line segments)\n  clipped = poly.clipLine(LineSegment2d(Vector2d(0,0),Vector2d(5,5)));\n  ASSERT_TRUE(clipped.hasValue());\n  ASSERT_TRUE(LinesEqual(\n    LineSegment2d(Vector2d(0,0),Vector2d(1,1)),\n    clipped.value()\n  ));\n\n  // Completely inside to outside, touching one line segment\n  clipped = poly.clipLine(LineSegment2d(Vector2d(0.5,0.5),Vector2d(1.5,0.5)));\n  ASSERT_TRUE(clipped.hasValue());\n  ASSERT_TRUE(LinesEqual(\n    LineSegment2d(Vector2d(0.5,0.5),Vector2d(1,0.5)),\n    clipped.value()\n  ));\n\n  // Run horizontally through cube, intersecting both left and right edges\n  clipped = poly.clipLine(LineSegment2d(Vector2d(-1,0.5),Vector2d(2,0.5)));\n  ASSERT_TRUE(clipped.hasValue());\n  ASSERT_TRUE(LinesEqual(\n    LineSegment2d(Vector2d(0,0.5),Vector2d(1,0.5)),\n    clipped.value()\n  ));\n\n  // Run diagonally through cube, bisecting the top left quadrant\n  clipped = poly.clipLine(LineSegment2d(Vector2d(-0.5,0),Vector2d(1,1.5)));\n  ASSERT_TRUE(clipped.hasValue());\n  ASSERT_TRUE(LinesEqual(\n    LineSegment2d(Vector2d(0,0.5),Vector2d(0.5,1)),\n    clipped.value()\n  ));\n}\n", "meta": {"hexsha": "710d86615a3e15ac08143e16cf31ab656f68fc7f", "size": 5957, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/Polygon2Tests.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/Polygon2Tests.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/Polygon2Tests.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": 31.1884816754, "max_line_length": 114, "alphanum_fraction": 0.7104247104, "num_tokens": 1837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.531567672380108}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 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_ARCH_COMMON_FUNCTION_SCALAR_SQRT1PM1_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_SQRT1PM1_HPP_INCLUDED\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/minusone.hpp>\n#include <boost/simd/function/oneplus.hpp>\n#include <boost/simd/function/sqrt.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( sqrt1pm1_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      A0 tmp =  bs::sqrt(oneplus(a0));\n      return  bs::if_else((bs::abs(a0) < bs::Half<A0>()),\n                          a0/bs::oneplus(tmp),\n                          bs::minusone(tmp));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "c9cb8aeedfbf611c791925278557f371722ec8e2", "size": 1596, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/generic/function/sqrt1pm1.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/arch/common/generic/function/sqrt1pm1.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/arch/common/generic/function/sqrt1pm1.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": 33.25, "max_line_length": 100, "alphanum_fraction": 0.5682957393, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5315259703635536}}
{"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 GEOREFERENCING_HPP\n#define GEOREFERENCING_HPP\n\n#include <Eigen/Dense>\n#include \"../math/CoordinateTransform.hpp\"\n#include \"Raytracing.hpp\"\n#include \"../Ping.hpp\"\n\n/*!\n* \\brief Georeferencing class\n* \\author Guillaume Labbe-Morissette, Jordan McManus, Emile Gagne\n* \\date October 2, 2018, 9:39 AM\n*/\nclass Georeferencing{\npublic:\n  /**\n  * Georeferences a ping\n  *\n  * @param georeferencedPing georeferenced ping in vector form\n  * @param attitude the attitude of the ship in the IMU frame\n  * @param position the position of the ship in the TRF\n  * @param ping the ping of the georeference in the sonar frame\n  * @param svp the SoundVelocityProfile\n  * @param leverArm vector from the position reference point (PRP) to the acoustic center\n  *\n  */\n  virtual void georeference(Eigen::Vector3d & georeferencedPing,Attitude & attitude,Position & position,Ping & ping,SoundVelocityProfile & svp,Eigen::Vector3d & leverArm,Eigen::Matrix3d & boresight){};\n};\n\n/*!\n* \\brief TRF Georeferencing class\n*\n* Extends Georeferencing class\n*/\nclass GeoreferencingTRF : public Georeferencing{\npublic:\n\n  /**\n  * Georeferences a ping in the TRF\n  *\n  * @param georeferencedPing vector of a ping georeferenced\n  * @param attitude the attitude of the ship in the IM frame\n  * @param position the position of the ship in the TRF\n  * @param ping the ping of the georeference in the sonar frame\n  * @param svp the sound velocity profile\n  * @param leverArm vector from the position reference point (PRP) to the acoustic center\n  *\n  */\n  void georeference(Eigen::Vector3d & georeferencedPing,Attitude & attitude,Position & position,Ping & ping,SoundVelocityProfile & svp,Eigen::Vector3d & leverArm,Eigen::Matrix3d & boresight) {\n    //Compute transform matrixes\n    Eigen::Matrix3d ned2ecef;\n    CoordinateTransform::ned2ecef(ned2ecef,position);\n    \n#ifdef DEBUG\n        std::cerr << \"NED 2 ECEF: \" << std::endl << ned2ecef << std::endl << std::endl;\n#endif\n\n    Eigen::Matrix3d imu2ned;\n    CoordinateTransform::getDCM(imu2ned,attitude);\n\n#ifdef DEBUG\n        std::cerr << \"IMU 2 NED: \" << std::endl << imu2ned << std::endl << std::endl;\n#endif\n    \n    \n    //Convert position to ECEF\n    Eigen::Vector3d positionECEF;\n    CoordinateTransform::getPositionECEF(positionECEF,position);\n    \n#ifdef DEBUG\n        std::cerr << \"Position ECEF: \" << std::endl << positionECEF << std::endl << std::endl;\n#endif\n    \n\n    //Convert ping to ECEF\n    Eigen::Vector3d pingVectorNED;\n    Raytracing::rayTrace(pingVectorNED,ping,svp,boresight,imu2ned);\n    \n#ifdef DEBUG\n        std::cerr << \"Raytraced ping: \" << std::endl << pingVectorNED << std::endl << std::endl;\n#endif\n    \n\n    Eigen::Vector3d pingECEF = ned2ecef * pingVectorNED;\n\n#ifdef DEBUG\n        std::cerr << \"Ping ECEF: \" << std::endl << pingECEF << std::endl << std::endl;\n#endif\n    \n    \n    //Convert lever arm to ECEF\n    Eigen::Vector3d leverArmECEF =  ned2ecef * (imu2ned * leverArm);\n\n    //Compute total ECEF vector\n\n    georeferencedPing = positionECEF + pingECEF + leverArmECEF;\n  }\n};\n\n\n/*!\n* \\brief LGF Georeferencing class\n*/\nclass GeoreferencingLGF : public Georeferencing{\npublic:\n\n    /**\n     * Georeferences a ping in the LGF (NED)\n     *\n     * @param georeferencedPing vector of a ping georeferenced\n     * @param attitude the attitude of the ship in the IM frame\n     * @param position the position of the ship in the TRF\n     * @param ping the ping of the georeference in the sonar frame\n     * @param svp the sound velocity profile\n     * @param leverArm vector from the position reference point (PRP) to the acoustic center\n     *\n     */\n    \n    virtual void georeference(Eigen::Vector3d & georeferencedPing,Attitude & attitude,Position & position,Ping & ping,SoundVelocityProfile & svp,Eigen::Vector3d & leverArm,Eigen::Matrix3d & boresight) {\n        Eigen::Matrix3d imu2ned;\n        CoordinateTransform::getDCM(imu2ned,attitude);\n\n\t//Convert position's geographic coordinates to ECEF, and then from ECEF to NED\n        Eigen::Vector3d positionECEF;\n        CoordinateTransform::getPositionECEF(positionECEF,position);\n        \n#ifdef DEBUG\n        std::cerr << \"Position ECEF: \" << std::endl << positionECEF << std::endl << std::endl;\n#endif\n\n        Eigen::Vector3d centered = positionECEF-centroidECEF;    \n\n\tEigen::Vector3d positionNED = ecef2ned * centered;\n\n        //Convert ping to NED\n        Eigen::Vector3d pingNED;\n        Raytracing::rayTrace(pingNED,ping,svp,boresight,imu2ned);\n\n        //Convert lever arm to NED\n        Eigen::Vector3d leverArmNED =  imu2ned * leverArm;\n\n        //Compute total NED vector\n        georeferencedPing = positionNED + pingNED + leverArmNED;\n    }\n\n    /**\n     * Sets centroid and inits ECEF 2 NED matrix\n     */\n    void setCentroid(Position & c){\n\tif(this->centroid) delete centroid;\n\n\tthis->centroid=new Position(c.getTimestamp(), c.getLatitude(), c.getLongitude(), c.getEllipsoidalHeight());\n        CoordinateTransform::getPositionECEF(centroidECEF,*this->centroid);\n\tCoordinateTransform::ned2ecef(ecef2ned,*this->centroid);\n        ecef2ned.transposeInPlace();\n    }\n\n    /**\n    *  Get a pointer to the centroid\n    */\n\n    Position * getCentroid(){ return centroid;};\n\nprotected:\n\n        Eigen::Vector3d centroidECEF;\n\tEigen::Matrix3d ecef2ned;\n\n\nprivate:\n\tPosition * centroid = NULL; //in geographic coordinates\n};\n\n#endif\n", "meta": {"hexsha": "31ab9cb32a5b4d2c7bc17bfdc2f28dab60844835", "size": 5477, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/georeferencing/Georeferencing.hpp", "max_stars_repo_name": "CBcidco/MBES-lib", "max_stars_repo_head_hexsha": "6b7759554db48c62d6b350d315283eb3fe0fd009", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T14:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T06:44:37.000Z", "max_issues_repo_path": "src/georeferencing/Georeferencing.hpp", "max_issues_repo_name": "CBcidco/MBES-lib", "max_issues_repo_head_hexsha": "6b7759554db48c62d6b350d315283eb3fe0fd009", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2019-04-16T13:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T19:44:23.000Z", "max_forks_repo_path": "src/georeferencing/Georeferencing.hpp", "max_forks_repo_name": "CBcidco/MBES-lib", "max_forks_repo_head_hexsha": "6b7759554db48c62d6b350d315283eb3fe0fd009", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-04-10T19:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T21:42:22.000Z", "avg_line_length": 30.5977653631, "max_line_length": 202, "alphanum_fraction": 0.6921672448, "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5315259564788013}}
{"text": "// Copyright Louis Dionne 2013-2016\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/config.hpp>\r\n#include <boost/hana/div.hpp>\r\n#include <boost/hana/equal.hpp>\r\n#include <boost/hana/eval_if.hpp>\r\n#include <boost/hana/integral_constant.hpp>\r\n#include <boost/hana/lazy.hpp>\r\n#include <boost/hana/monadic_fold_right.hpp>\r\n#include <boost/hana/optional.hpp>\r\n#include <boost/hana/tuple.hpp>\r\nnamespace hana = boost::hana;\r\n\r\n\r\nint main() {\r\n    BOOST_HANA_CONSTEXPR_LAMBDA auto safe_div = [](auto x, auto y) {\r\n        return hana::eval_if(y == hana::int_c<0>,\r\n            hana::make_lazy(hana::nothing),\r\n            [=](auto _) {\r\n                return hana::just(_(x) / y);\r\n            }\r\n        );\r\n    };\r\n\r\n    // with an initial state\r\n    BOOST_HANA_CONSTANT_CHECK(\r\n        hana::monadic_fold_right<hana::optional_tag>(\r\n            hana::tuple_c<int, 1000, 8, 4>, hana::int_c<2>, safe_div\r\n        )\r\n            ==\r\n        hana::just(hana::int_c<1000> / (hana::int_c<8> / (hana::int_c<4> / hana::int_c<2>)))\r\n    );\r\n\r\n    BOOST_HANA_CONSTANT_CHECK(\r\n        hana::monadic_fold_right<hana::optional_tag>(\r\n            hana::tuple_c<int, 1000, 8, 4>, hana::int_c<0>, safe_div\r\n        )\r\n            ==\r\n        hana::nothing\r\n    );\r\n\r\n    // without an initial state\r\n    BOOST_HANA_CONSTANT_CHECK(\r\n        hana::monadic_fold_right<hana::optional_tag>(\r\n            hana::tuple_c<int, 1000, 8, 4, 2>, safe_div\r\n        )\r\n            ==\r\n        hana::just(hana::int_c<1000> / (hana::int_c<8> / (hana::int_c<4> / hana::int_c<2>)))\r\n    );\r\n\r\n    BOOST_HANA_CONSTANT_CHECK(\r\n        hana::monadic_fold_right<hana::optional_tag>(\r\n            hana::tuple_c<int, 1000, 8, 4, 0>, safe_div\r\n        )\r\n            ==\r\n        hana::nothing\r\n    );\r\n}\r\n", "meta": {"hexsha": "382eb9fe827f0ab28fde0be80e408dea65bdb891", "size": 1917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/monadic_fold_right.cpp", "max_stars_repo_name": "nxplatform/nx-mobile", "max_stars_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_stars_repo_licenses": ["Apache-2.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/hana/example/monadic_fold_right.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/hana/example/monadic_fold_right.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": 30.9193548387, "max_line_length": 93, "alphanum_fraction": 0.5779864371, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5314986027843861}}
{"text": "//=======================================================================\n// Copyright (c)\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 n_queens_test.cpp\n * @brief\n * @author Piotr Wygocki\n * @version 1.0\n * @date 2014-01-04\n */\n\n#include \"test_utils/logger.hpp\"\n\n#include \"paal/local_search/n_queens/n_queens_local_search.hpp\"\n#include \"paal/local_search/local_search.hpp\"\n#include \"paal/data_structures/components/components_replace.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/range/algorithm_ext/iota.hpp>\n#include <boost/range/algorithm/random_shuffle.hpp>\n\nBOOST_AUTO_TEST_CASE(n_queens_test) {\n    namespace ls = paal::local_search;\n    typedef ls::n_queens_solution_adapter<std::vector<int>> Adapter;\n    for (int i : { 4, 5, 6, 7, 8, 9, 10, 100, 500 }) {\n        std::vector<int> queens(i);\n        boost::iota(queens, 0);\n        boost::random_shuffle(queens);\n\n        LOGLN(\"n = \" << i\n                     << \" start obj fun val = \" << Adapter(queens).obj_fun());\n\n        ls::n_queens_local_search_components<> comps;\n        ls::n_queens_solution_first_improving(queens, comps);\n        LOGLN(\"end obj fun val = \" << Adapter(queens).obj_fun());\n    }\n}\n", "meta": {"hexsha": "26ba762634129d5dbb73822753f6c6c8554e57c8", "size": 1382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/local_search/n_queens/n_queens_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/local_search/n_queens/n_queens_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/local_search/n_queens/n_queens_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": 32.9047619048, "max_line_length": 78, "alphanum_fraction": 0.6027496382, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5314985975941556}}
{"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_REMROUND_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REMROUND_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n    @ingroup group-arithmetic\n    Function object implementing remround capabilities\n\n    Computes the remainder of division.\n    The return value is x-n*y, where n is the value x/y,\n    rounded toward infinity.\n\n    @par semantic:\n    For any given value @c x, @c y of type @c T:\n\n    @code\n    T r = remround(x, y);\n    @endcode\n\n    For floating point values the code is equivalent to:\n\n    @code\n    T r = x-divround(x, y)*y;\n    @endcode\n\n  **/\n  const boost::dispatch::functor<tag::remround_> remround = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/remround.hpp>\n#include <boost/simd/function/simd/remround.hpp>\n\n#endif\n", "meta": {"hexsha": "1497d285e08dc1207d9a29e310b5eae7cbf586f7", "size": 1226, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/remround.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/remround.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/remround.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.0204081633, "max_line_length": 100, "alphanum_fraction": 0.5905383361, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5314985961484313}}
{"text": "/**\n *\n */\n#include <stdio.h>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <Eigen/Dense>\n\nconst char* TRAIN_FILE_NAME = \"../DataSets/zip.data/zip.train\";\nconst char* TEST_FILE_NAME = \"../DataSets/zip.data/zip.test\";\n\ntypedef struct {\n  std::vector<int> labels;\n  Eigen::MatrixXd data;\n} LabeledData;\n\nEigen::MatrixXd StlVectorsToEigenMatrix(const std::vector<std::vector<double> >& data) {\n/**\n *\n */\n  Eigen::MatrixXd matrix(data.size(), data[0].size());\n\n  unsigned i;\n  unsigned j;\n  for (i = 0; i < data.size(); ++i) {\n    for (j = 0; j < data[0].size(); ++j) {\n      matrix(i, j) = data[i][j];\n    }\n  }\n\n  return matrix;\n}\n\nEigen::MatrixXd GetDataSubset(const LabeledData* labeledData, std::vector<int> labels) {\n/**\n *\n */\n\n\n\n\n\n}\n\nLabeledData ReadDataFromFile(const char* file_name, const int dimensionality) {\n/**\n *\n */\n  FILE* file = fopen(file_name, \"r\");\n  if (file == NULL) {\n    printf(\"Failed to read from file: %s\\n\", file_name);\n    exit(0);\n  }\n\n  std::vector<int> labels;\n  std::vector<std::vector<double> > data;\n\n  double dummy;\n  int read_result = fscanf(file, \"%lf\", &dummy);\n  while (read_result >= 1) {\n    labels.push_back((int) dummy);\n\n    std::vector<double> temp;\n    unsigned i;\n    for (i = 0; i < dimensionality; ++i) {\n      fscanf(file, \" %lf\", &dummy);\n      temp.push_back(dummy);\n    }\n    data.push_back(temp);\n\n    read_result = fscanf(file, \" %lf\", &dummy);\n  }\n\n  LabeledData labeledData = {labels, StlVectorsToEigenMatrix(data)};\n\n  return labeledData;\n}\n\nint main(int argc, char** argv) {\n  // printf(\"%s\\n%s\\n\", TRAIN_FILE_NAME, TEST_FILE_NAME);\n\n  LabeledData train = ReadDataFromFile(TRAIN_FILE_NAME, 256);\n  std::cout << train.data.row(0) << std::endl;\n\n  std::cout << train.labels[0] << ' ' << train.labels[1] << ' ' << train.labels[2];\n\n  return 0;\n}", "meta": {"hexsha": "84e27e21e4013d6d5ffce1c50bbbfa601c9e3312", "size": 1820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STAT775/HW07/main.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/HW07/main.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/HW07/main.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": 20.4494382022, "max_line_length": 88, "alphanum_fraction": 0.621978022, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.531498590958201}}
{"text": "#pragma once\n\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/storage.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"Solution.hpp\"\n\nusing namespace std;\nnamespace ublas = boost::numeric::ublas;\n\nbool checkSolution(\n\tconst vector<bool> &yi,\n\tconst vector<tuple<int, int, double>> &flow,\n\tconst unsigned int &flowNumber,\n\tconst ublas::matrix<double> &cij,\n\tconst vector<double> &bi,\n\tvector<double> dj,\n\tconst double &sum_dj);// Check if Solution is feasible\n\ndouble f(\n\tconst vector<bool> &yi,\n\tconst vector<double> &fi,\n\tconst double &transportation_cost); // Objective Function \n\nbool canUpdateXij(\n\tconst vector<double> &bi,\n\tconst vector<bool> &yi,\n\tconst double &sum_dj); // Checks if Capacity can fullfill the Demand", "meta": {"hexsha": "72e3e17d02d2aefcdbf3881e38f19750caf26118", "size": 800, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "VNS Implementierung/VNS Implementierung/Solution.hpp", "max_stars_repo_name": "franneck94/Variable-Neighborhood-Search-FLP", "max_stars_repo_head_hexsha": "891cea0be1c3250cd9990eb35ef5701cb20bf964", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-05T08:26:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-05T08:26:52.000Z", "max_issues_repo_path": "VNS Implementierung/VNS Implementierung/Solution.hpp", "max_issues_repo_name": "franneck94/Variable-Neighborhood-Search-FLP", "max_issues_repo_head_hexsha": "891cea0be1c3250cd9990eb35ef5701cb20bf964", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-28T09:54:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-28T09:54:53.000Z", "max_forks_repo_path": "VNS Implementierung/VNS Implementierung/Solution.hpp", "max_forks_repo_name": "franneck94/Variable-Neighborhood-Search-FLP", "max_forks_repo_head_hexsha": "891cea0be1c3250cd9990eb35ef5701cb20bf964", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-05T08:26:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-02T09:21:54.000Z", "avg_line_length": 26.6666666667, "max_line_length": 69, "alphanum_fraction": 0.7475, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5314985857679704}}
{"text": "/// \\file type.hpp\n\n#ifndef COLORUTIL_TYPE_HPP\n#define COLORUTIL_TYPE_HPP\n\n#include <Eigen/Core>\n\nnamespace colorutil\n{\n    /// \\brief RGB\n    ///\n    /// \\details Each value is defined in [0, 1].\n    using RGB = Eigen::Vector3d;\n\n    /// \\brief HSL\n    ///\n    /// \\details Each value is defined in [0, 1].\n    using HSL = Eigen::Vector3d;\n\n    /// \\brief CIEXYZ\n    using XYZ = Eigen::Vector3d;\n\n    /// \\brief CIELAB\n    using Lab = Eigen::Vector3d;\n} // namespace colorutil\n\n#endif // COLORUTIL_TYPE_HPP\n", "meta": {"hexsha": "14aa6f95db21e2b35666c62bb1bac342b145024a", "size": 508, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/color-util/type.hpp", "max_stars_repo_name": "Artoria2e5/color-util", "max_stars_repo_head_hexsha": "90ede061d8b64d0986dce949a9a23000a6682123", "max_stars_repo_licenses": ["MIT"], "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/color-util/type.hpp", "max_issues_repo_name": "Artoria2e5/color-util", "max_issues_repo_head_hexsha": "90ede061d8b64d0986dce949a9a23000a6682123", "max_issues_repo_licenses": ["MIT"], "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/color-util/type.hpp", "max_forks_repo_name": "Artoria2e5/color-util", "max_forks_repo_head_hexsha": "90ede061d8b64d0986dce949a9a23000a6682123", "max_forks_repo_licenses": ["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.1428571429, "max_line_length": 49, "alphanum_fraction": 0.6181102362, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5314985857679704}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2016 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 squarerootclvmodel.cpp\n    \\brief CLV model with a square root kernel process\n*/\n\n#include <ql/processes/blackscholesprocess.hpp>\n#include <ql/processes/squarerootprocess.hpp>\n#include <ql/math/integrals/gaussianquadratures.hpp>\n\n#include <ql/experimental/models/squarerootclvmodel.hpp>\n#include <ql/methods/finitedifferences/utilities/gbsmrndcalculator.hpp>\n\n#include <boost/math/distributions/non_central_chi_squared.hpp>\n\n#include <utility>\n\nnamespace QuantLib {\n    SquareRootCLVModel::SquareRootCLVModel(\n        const ext::shared_ptr<GeneralizedBlackScholesProcess>& bsProcess,\n        ext::shared_ptr<SquareRootProcess> sqrtProcess,\n        std::vector<Date> maturityDates,\n        Size lagrangeOrder,\n        Real pMax,\n        Real pMin)\n    : pMax_(pMax), pMin_(pMin), bsProcess_(bsProcess), sqrtProcess_(std::move(sqrtProcess)),\n      maturityDates_(std::move(maturityDates)), lagrangeOrder_(lagrangeOrder),\n      rndCalculator_(ext::make_shared<GBSMRNDCalculator>(bsProcess)) {}\n\n    Real SquareRootCLVModel::cdf(const Date& d, Real k) const {\n        return rndCalculator_->cdf(k, bsProcess_->time(d));\n    }\n\n\n    Real SquareRootCLVModel::invCDF(const Date& d, Real q) const {\n        return rndCalculator_->invcdf(q, bsProcess_->time(d));\n    }\n\n    std::pair<Real, Real> SquareRootCLVModel::nonCentralChiSquaredParams(\n        const Date& d) const {\n\n        const Time t = bsProcess_->time(d);\n\n        const Real kappa = sqrtProcess_->a();\n        const Real theta = sqrtProcess_->b();\n        const Real sigma = sqrtProcess_->sigma();\n\n        const Real df  = 4*theta*kappa/(sigma*sigma);\n        const Real ncp = 4*kappa*std::exp(-kappa*t)\n            / (sigma*sigma*(1-std::exp(-kappa*t)))*sqrtProcess_->x0();\n\n        return std::make_pair(df, ncp);\n    }\n\n\n    Array SquareRootCLVModel::collocationPointsX(const Date& d) const {\n\n        const std::pair<Real, Real> p = nonCentralChiSquaredParams(d);\n\n        Array x = GaussianQuadrature(lagrangeOrder_,\n            GaussNonCentralChiSquaredPolynomial(p.first, p.second))\n             .x();\n\n        std::sort(x.begin(), x.end());\n\n        const boost::math::non_central_chi_squared_distribution<Real>\n            dist(p.first, p.second);\n\n        const Real xMin = std::max(x.front(),\n            (pMin_ == Null<Real>())\n                ? 0.0 : boost::math::quantile(dist, pMin_));\n\n        const Real xMax = std::min(x.back(),\n            (pMax_ == Null<Real>())\n            ? QL_MAX_REAL : boost::math::quantile(dist, pMax_));\n\n        const Real b = xMin - x.front();\n        const Real a = (xMax - xMin)/(x.back() - x.front());\n\n        for (double& i : x) {\n            i = a * i + b;\n        }\n\n        return x;\n    }\n\n    Array SquareRootCLVModel::collocationPointsY(const Date& d) const {\n\n        const Array x = collocationPointsX(d);\n        const std::pair<Real, Real> params = nonCentralChiSquaredParams(d);\n        const boost::math::non_central_chi_squared_distribution<Real>\n            dist(params.first, params.second);\n\n        Array s(x.size());\n        for (Size i=0, n=s.size(); i < n; ++i) {\n            const Real q = boost::math::cdf(dist, x[i]);\n\n            s[i] = invCDF(d, q);\n        }\n\n        return s;\n    }\n\n    ext::function<Real(Time, Real)> SquareRootCLVModel::g() const {\n        calculate();\n        return g_;\n    }\n\n    void SquareRootCLVModel::performCalculations() const {\n        g_ = ext::function<Real(Time, Real)>(MappingFunction(*this));\n    }\n\n    SquareRootCLVModel::MappingFunction::MappingFunction(\n        const SquareRootCLVModel& model)\n    : s_(ext::make_shared<Matrix>(\n         model.maturityDates_.size(), model.lagrangeOrder_)),\n      x_(ext::make_shared<Matrix>(\n         model.maturityDates_.size(), model.lagrangeOrder_)) {\n\n        std::vector<Date> maturityDates = model.maturityDates_;\n        std::sort(maturityDates.begin(), maturityDates.end());\n\n        const ext::shared_ptr<GeneralizedBlackScholesProcess>&\n            bsProcess = model.bsProcess_;\n\n        for (Size i=0, n = maturityDates.size(); i < n; ++i) {\n            const Date maturityDate = maturityDates[i];\n\n            const Array x = model.collocationPointsX(maturityDate);\n            const Array y = model.collocationPointsY(maturityDate);\n\n            std::copy(x.begin(), x.end(), x_->row_begin(i));\n            std::copy(y.begin(), y.end(), s_->row_begin(i));\n\n            const Time maturity = bsProcess->time(maturityDate);\n\n            interpl.insert(\n                std::make_pair(maturity,\n                    ext::make_shared<LagrangeInterpolation>(\n                        x_->row_begin(i), x_->row_end(i),\n                        s_->row_begin(i))));\n        }\n    }\n\n    Real SquareRootCLVModel::MappingFunction::operator()(Time t,Real x) const {\n        const interpl_type::const_iterator ge = interpl.lower_bound(t);\n\n        if (close_enough(ge->first, t)) {\n            return (*ge->second)(x, true);\n        }\n\n        QL_REQUIRE(ge != interpl.end() && ge != interpl.begin(),\n             \"extrapolation to large or small t is not allowed\");\n\n        const Time t1 = ge->first;\n        const Real y1 = (*ge->second)(x, true);\n\n        interpl_type::const_iterator lt = ge;\n        std::advance(lt, -1);\n\n        const Time t0 = lt->first;\n        const Real y0 = (*lt->second)(x, true);\n\n        return y0 + (y1 - y0)/(t1 - t0)*(t - t0);\n    }\n}\n", "meta": {"hexsha": "cd139a6272c9a7599eb25eb9389c1dac83b4ff70", "size": 6191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/squarerootclvmodel.cpp", "max_stars_repo_name": "mshojatalab/QuantLib", "max_stars_repo_head_hexsha": "7801a0fb3226bc1b001e310bacdd35ddb2e51661", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T12:21:33.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-21T12:21:33.000Z", "max_issues_repo_path": "ql/experimental/models/squarerootclvmodel.cpp", "max_issues_repo_name": "mshojatalab/QuantLib", "max_issues_repo_head_hexsha": "7801a0fb3226bc1b001e310bacdd35ddb2e51661", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-03-09T16:19:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:33:42.000Z", "max_forks_repo_path": "ql/experimental/models/squarerootclvmodel.cpp", "max_forks_repo_name": "sweemer/QuantLib", "max_forks_repo_head_hexsha": "1341223e3d839dd77bb7231d0913809f01437740", "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.6467391304, "max_line_length": 92, "alphanum_fraction": 0.6262316266, "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.5314637235747302}}
{"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_ARCH_COMMON_GENERIC_FUNCTION_REM_PIO2_CEPHES_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_REM_PIO2_CEPHES_HPP_INCLUDED\n\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <boost/simd/function/fnms.hpp>\n#include <boost/simd/function/nearbyint.hpp>\n#include <boost/simd/function/quadrant.hpp>\n#include <boost/simd/function/bitwise_and.hpp>\n#include <boost/simd/constant/three.hpp>\n#include <boost/simd/constant/twoopi.hpp>\n#include <boost/simd/detail/constant/pio2_1.hpp>\n#include <boost/simd/detail/constant/pio2_2.hpp>\n#include <boost/simd/detail/constant/pio2_3.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <utility>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( rem_pio2_cephes_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_ < bd::floating_<A0> >\n                          )\n  {\n//    using i_t = bd::as_integer_t<A0>;\n    using result_t = std::pair<A0, A0>              ;\n\n    BOOST_FORCEINLINE result_t operator() ( A0 const& x) const\n    {\n      A0 xi =  bs::nearbyint(x*bs::Twoopi<A0>());\n      A0 xr  = fnms(xi, bs::Pio2_1<A0>(), x);\n      xr -= xi*bs::Pio2_2<A0>();\n      xr -= xi*bs::Pio2_3<A0>();\n      return {quadrant(xi), xr};\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "9259aa1fc1c6a1348fc1fa50ccc641340e8ec293", "size": 1840, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/generic/function/rem_pio2_cephes.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/arch/common/generic/function/rem_pio2_cephes.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/arch/common/generic/function/rem_pio2_cephes.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": 32.8571428571, "max_line_length": 100, "alphanum_fraction": 0.5934782609, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5314637167918838}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/include/functions/ceil.hpp>\n\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <complex>\n#include <nt2/sdk/complex/complex.hpp>\n#include <nt2/sdk/complex/dry.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n\nNT2_TEST_CASE_TPL ( ceil_real,  BOOST_SIMD_REAL_TYPES)\n{\n  using nt2::ceil;\n  using nt2::tag::ceil_;\n  typedef typename std::complex<T> cT;\n  typedef typename nt2::dry<T> dT;\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_EQUAL(ceil(nt2::Inf<cT>()), nt2::Inf<cT>());\n  NT2_TEST_EQUAL(ceil(nt2::Minf<cT>()), nt2::Minf<cT>());\n  NT2_TEST_EQUAL(ceil(nt2::Nan<cT>()), nt2::Nan<cT>());\n  NT2_TEST_EQUAL(ceil(dT(nt2::Inf<T>())), dT(nt2::Inf<T>()));\n  NT2_TEST_EQUAL(ceil(dT(nt2::Minf<T>())), dT(nt2::Minf<T>()));\n  NT2_TEST_EQUAL(ceil(dT(nt2::Nan<T>())), dT(nt2::Nan<T>()));\n#endif\n  NT2_TEST_EQUAL(ceil(cT(T(-1.1))), T(-1));\n  NT2_TEST_EQUAL(ceil(cT(T(1.1))), T(2));\n  NT2_TEST_EQUAL(ceil(nt2::Mone<cT>()), nt2::Mone<cT>());\n  NT2_TEST_EQUAL(ceil(nt2::One<cT>()), nt2::One<cT>());\n  NT2_TEST_EQUAL(ceil(nt2::Zero<cT>()), nt2::Zero<cT>());\n  NT2_TEST_EQUAL(ceil(dT(T(-1.1))), T(-1));\n  NT2_TEST_EQUAL(ceil(dT(T(1.1))), T(2));\n  NT2_TEST_EQUAL(ceil(dT(nt2::Mone<T>())), dT(nt2::Mone<T>()));\n  NT2_TEST_EQUAL(ceil(dT(nt2::One<T>())), dT(nt2::One<T>()));\n  NT2_TEST_EQUAL(ceil(dT(nt2::Zero<T>())), dT(nt2::Zero<T>()));\n}\n", "meta": {"hexsha": "37aaa7811c24113782bb6f30e9c69d6c747fc97c", "size": 2278, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/base/unit/arithmetic/scalar/ceil.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/type/complex/base/unit/arithmetic/scalar/ceil.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/type/complex/base/unit/arithmetic/scalar/ceil.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 41.4181818182, "max_line_length": 80, "alphanum_fraction": 0.6172080773, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5314242219084232}}
{"text": "\n// solving A * X = B\n// using driver function gesv()\n\n#include <cstddef>\n#include <iostream>\n#include <vector>\n#include <boost/numeric/bindings/lapack/driver/gesv.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\n\n#if !defined(TEST_MATLIB_UBLAS) && !defined(TEST_MATLIB_GLAS) && !defined(TEST_MATLIB_MTL) && !defined(TEST_MATLIB_EIGEN)\n#define TEST_MATLIB_UBLAS\n#endif\n\n#if defined(TEST_MATLIB_UBLAS)\n\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\nnamespace ublas = boost::numeric::ublas;\ntypedef ublas::matrix<double, ublas::column_major> m_t;\ntypedef std::size_t size_type;\n\n#elif defined(TEST_MATLIB_GLAS)\n\n#include <boost/numeric/bindings/glas/dense_matrix.hpp>\n#include <glas/toolbox/la/algorithm/operators.hpp>\nusing namespace glas::la;\ntypedef glas::dense_matrix<double, glas::column_orientation> m_t;\ntypedef std::ptrdiff_t size_type;\n\n#elif defined(TEST_MATLIB_MTL)\n\n#include <boost/numeric/bindings/mtl/dense2D.hpp>\n#include <boost/numeric/mtl/operation/operators.hpp>\ntypedef mtl::dense2D<double, mtl::matrix::parameters<mtl::tag::col_major> > m_t;\ntypedef std::ptrdiff_t size_type;\n\n#elif defined(TEST_MATLIB_EIGEN)\n\n#include <boost/numeric/bindings/eigen/matrix.hpp>\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> m_t;\ntypedef int size_type;\n\n#endif\n\n#include \"utils.h\"\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\nusing std::cout;\nusing std::endl;\n\nint main() {\n\n  cout << endl; \n\n  size_type n = 5;   \n  m_t a (n, n);   // system matrix \n\n  size_type nrhs = 2; \n  m_t x (n, nrhs), b (n, nrhs);  // b -- right-hand side matrix\n\n  init_symm (a); \n  //     [n   n-1 n-2  ... 1]\n  //     [n-1 n   n-1  ... 2]\n  // a = [n-2 n-1 n    ... 3]\n  //     [        ...       ]\n  //     [1   2   ...  n-1 n]\n\n  m_t aa (a); // copy of a, because a is `lost' after gesv()\n\n#if defined(TEST_MATLIB_UBLAS)\n  ublas::matrix_column<m_t> xc0 (x, 0), xc1 (x, 1); \n  for (int i = 0; i < xc0.size(); ++i) {\n    xc0 (i) = 1.;\n    xc1 (i) = 2.; \n  }\n  b = prod (a, x); \n#elif defined(TEST_MATLIB_GLAS) || defined(TEST_MATLIB_MTL) || defined(TEST_MATLIB_EIGEN)\n  for (int i = 0; i < bindings::size_row (x); ++i) {\n    x (i,0) = 1.;\n    x (i,1) = 2.; \n  }\n  b = a * x;\n#endif\n\n  print_m (a, \"A\"); \n  cout << endl; \n  print_m (b, \"B\"); \n  cout << endl; \n\n//  lapack::gesv (a, b);  // solving the system, b contains x \n//  no ipiv less version is currently provided, so fall back to using ipiv\n  std::vector<fortran_int_t> ipiv(n);\n  lapack::gesv (a, ipiv, b);  // solving the system, b contains x \n\n  print_m (b, \"X\");\n  cout << endl; \n\n#if defined(TEST_MATLIB_UBLAS)\n  x = prod (aa, b); \n#elif defined(TEST_MATLIB_GLAS) || defined(TEST_MATLIB_MTL) || defined(TEST_MATLIB_EIGEN)\n  x = aa * b;\n#endif\n  print_m (x, \"B = A X\"); \n\n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "95d234b5fe4d151042a32978158d337add0b607a", "size": 2863, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gesv2.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_gesv2.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_gesv2.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": 26.0272727273, "max_line_length": 121, "alphanum_fraction": 0.6570031436, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5314242047521404}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n\nusing namespace Eigen;\n\n// [functor]\ntemplate<class ArgType, class RowIndexType, class ColIndexType>\nclass indexing_functor {\n  const ArgType &m_arg;\n  const RowIndexType &m_rowIndices;\n  const ColIndexType &m_colIndices;\n public:\n  typedef Matrix<typename ArgType::Scalar,\n                 RowIndexType::SizeAtCompileTime,\n                 ColIndexType::SizeAtCompileTime,\n                 ArgType::Flags & RowMajorBit ? RowMajor : ColMajor,\n                 RowIndexType::MaxSizeAtCompileTime,\n                 ColIndexType::MaxSizeAtCompileTime> MatrixType;\n\n  indexing_functor(const ArgType &arg, const RowIndexType &row_indices, const ColIndexType &col_indices)\n      : m_arg(arg), m_rowIndices(row_indices), m_colIndices(col_indices) {}\n\n  const typename ArgType::Scalar &operator()(Index row, Index col) const {\n    return m_arg(m_rowIndices[row], m_colIndices[col]);\n  }\n};\n// [functor]\n\n// [function]\ntemplate<class ArgType, class RowIndexType, class ColIndexType>\nCwiseNullaryOp<indexing_functor<ArgType, RowIndexType, ColIndexType>, typename indexing_functor<ArgType,\n                                                                                                RowIndexType,\n                                                                                                ColIndexType>::MatrixType>\nindexing(const Eigen::MatrixBase<ArgType> &arg, const RowIndexType &row_indices, const ColIndexType &col_indices) {\n  typedef indexing_functor<ArgType, RowIndexType, ColIndexType> Func;\n  typedef typename Func::MatrixType MatrixType;\n  return MatrixType::NullaryExpr(row_indices.size(), col_indices.size(), Func(arg.derived(), row_indices, col_indices));\n}\n// [function]\n\n\nint main() {\n  std::cout << \"[main1]\\n\";\n  Eigen::MatrixXi A = Eigen::MatrixXi::Random(4, 4);\n  Array3i ri(1, 2, 1);\n  ArrayXi ci(6);\n  ci << 3, 2, 1, 0, 0, 2;\n  Eigen::MatrixXi B = indexing(A, ri, ci);\n  std::cout << \"A =\" << std::endl;\n  std::cout << A << std::endl << std::endl;\n  std::cout << \"A([\" << ri.transpose() << \"], [\" << ci.transpose() << \"]) =\" << std::endl;\n  std::cout << B << std::endl;\n  std::cout << \"[main1]\\n\";\n\n  std::cout << \"[main2]\\n\";\n  B = indexing(A, ri + 1, ci);\n  std::cout << \"A(ri+1,ci) =\" << std::endl;\n  std::cout << B << std::endl << std::endl;\n#if __cplusplus >= 201103L\n  B = indexing(A, ArrayXi::LinSpaced(13, 0, 12).unaryExpr([](int x) { return x % 4; }), ArrayXi::LinSpaced(4, 0, 3));\n  std::cout << \"A(ArrayXi::LinSpaced(13,0,12).unaryExpr([](int x){return x%4;}), ArrayXi::LinSpaced(4,0,3)) =\"\n            << std::endl;\n  std::cout << B << std::endl << std::endl;\n#endif\n  std::cout << \"[main2]\\n\";\n}\n\n", "meta": {"hexsha": "ef1fbb386328904a38d975d4a9920ea33b3ce28d", "size": 2672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen-3.3/doc/examples/nullary_indexing.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/nullary_indexing.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/nullary_indexing.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": 39.2941176471, "max_line_length": 122, "alphanum_fraction": 0.6111526946, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5314242047521403}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"CNNEdges\"\n#include <boost/test/unit_test.hpp>\n\n#include <vector>\n\n#include \"cnn/tests/test_utils.h\"\n#include \"cnn/tensor.h\"\n#include \"cnn/edges.h\"\n#include \"cnn/c2w.h\"\n\nusing namespace std;\nusing namespace cnn;\n\nBOOST_GLOBAL_FIXTURE(TestTensorSetup)\n\nDim size(const Tensor& t) {\n  if (t.cols() > 1)\n    return Dim(t.rows(), t.cols());\n  return Dim(t.rows());\n}\n\nBOOST_AUTO_TEST_CASE(ESqrL2)\n{\n  auto U = Ccm({2}, {4,5});\n  auto V = Ccm({2}, {1,1});\n  cerr << str(U) << endl;\n  SquaredEuclideanDistance e;\n  vector<const Tensor*> xs = {&U, &V};\n  Tensor W = e.forward(xs); \n  cerr << \"Norm^2:\" << str(W) << endl;\n  double eps = 1e-5;\n  BOOST_CHECK_CLOSE(t(W,0),25., eps);\n  Tensor dEdf = Ccm({1}, {1});\n  Tensor d1 = e.backward(xs, W, dEdf, 0);\n  Tensor d2 = e.backward(xs, W, dEdf, 1);\n  cerr << d1 << endl;\n  cerr << d2 << endl;\n  BOOST_CHECK_CLOSE(t(d1,0), 6., eps);\n  BOOST_CHECK_CLOSE(t(d1,1), 8., eps);\n  BOOST_CHECK_CLOSE(t(d2,0), -6., eps);\n  BOOST_CHECK_CLOSE(t(d2,1), -8., eps);\n}\n\nBOOST_AUTO_TEST_CASE(EMatrixMultiply) {\n  Tensor U = Ccm({2,3}, {1,2,3,4,5,6});\n  Tensor V = Ccm({3,2}, {7,8,9,10,11,12});\n  MatrixMultiply mm;\n  vector<const Tensor*> xs = {&U, &V};\n  Tensor W = mm.forward(xs);\n  BOOST_REQUIRE_EQUAL(Dim({2,2}),size(W));\n  double eps = 1e-5;\n  BOOST_CHECK_CLOSE(t(W,0,0), 76., eps);\n  BOOST_CHECK_CLOSE(t(W,1,0), 100., eps);\n  BOOST_CHECK_CLOSE(t(W,0,1), 103., eps);\n  BOOST_CHECK_CLOSE(t(W,1,1), 136., eps);\n  Tensor dEdf = Ccm({2,2}, {-1,0.5,1,2});\n  Tensor dEdx0 = mm.backward(xs, W, dEdf, 0);\n  cerr << str(dEdx0) << endl;\n  BOOST_CHECK_CLOSE(t(dEdx0,0,0),3.,eps);\n  BOOST_CHECK_CLOSE(t(dEdx0,0,1),3.,eps);\n  BOOST_CHECK_CLOSE(t(dEdx0,0,2),3.,eps);\n  BOOST_CHECK_CLOSE(t(dEdx0,1,0),23.5,eps);\n  BOOST_CHECK_CLOSE(t(dEdx0,1,1),26.,eps);\n  BOOST_CHECK_CLOSE(t(dEdx0,1,2),28.5,eps);\n  Tensor dEdx1 = mm.backward(xs, W, dEdf, 1);\n  cerr << str(dEdx1) << endl;\n  BOOST_CHECK_CLOSE(t(dEdx1,0,0),0.,eps);\n  BOOST_CHECK_CLOSE(t(dEdx1,1,0),-1.,eps);\n  BOOST_CHECK_CLOSE(t(dEdx1,2,0),-2.,eps);\n  BOOST_CHECK_CLOSE(t(dEdx1,0,1),5.,eps);\n  BOOST_CHECK_CLOSE(t(dEdx1,1,1),11.,eps);\n  BOOST_CHECK_CLOSE(t(dEdx1,2,1),17.,eps);\n}\n\nBOOST_AUTO_TEST_CASE(EColumnConcat)\n{\n  Tensor u1 = Ccm({2}, {1, 2});\n  Tensor u2 = Ccm({2}, {3, 4});\n  Tensor u3 = Ccm({2}, {5, 6});\n  cerr << u1 << endl;\n  cerr << u2 << endl;\n  cerr << u3 << endl;\n  vector<const Tensor*> xs = {&u1, &u2, &u3};\n  ConcatenateColumns cc;\n  Tensor U = cc.forward(xs);\n  cerr << U << endl;\n  Tensor V = Ccm({3,2}, {7,8,9,10,11,12});\n  MatrixMultiply mm;\n  vector<const Tensor*> xs2 = {&U, &V};\n  Tensor W = mm.forward(xs2);\n  cerr << W << endl;\n  cerr << str(W) << endl;\n  BOOST_REQUIRE_EQUAL(Dim({2,2}),size(W));\n  double eps = 1e-5;\n  BOOST_CHECK_CLOSE(t(W,0,0), 76., eps);\n  BOOST_CHECK_CLOSE(t(W,1,0), 100., eps);\n  BOOST_CHECK_CLOSE(t(W,0,1), 103., eps);\n  BOOST_CHECK_CLOSE(t(W,1,1), 136., eps);\n  Tensor b1 = cc.backward(xs, U, U, 0);\n  Tensor b2 = cc.backward(xs, U, U, 1);\n  Tensor b3 = cc.backward(xs, U, U, 2);\n  cerr << str(b1) << endl;\n  cerr << str(b2) << endl;\n  cerr << str(b3) << endl;\n  BOOST_CHECK_EQUAL(t(u1,0), t(b1,0));\n  BOOST_CHECK_EQUAL(t(u1,1), t(b1,1));\n  BOOST_CHECK_EQUAL(t(u2,0), t(b2,0));\n  BOOST_CHECK_EQUAL(t(u2,1), t(b2,1));\n  BOOST_CHECK_EQUAL(t(u3,0), t(b3,0));\n  BOOST_CHECK_EQUAL(t(u3,1), t(b3,1));\n}\n\nBOOST_AUTO_TEST_CASE(ERowConcat)\n{\n  Tensor u1 = Ccm({2}, {1, 4});\n  Tensor u2 = Ccm({2}, {2, 5});\n  Tensor u3 = Ccm({3}, {3, 6, 7});\n  cerr << str(u1) << endl;\n  cerr << str(u2) << endl;\n  cerr << str(u3) << endl;\n  vector<const Tensor*> xs = {&u1, &u2, &u3};\n  Concatenate cr;\n  Tensor U = cr.forward(xs);\n  cerr << str(U) << endl;\n  //BOOST_REQUIRE_EQUAL(Dim({7}),size(U));\n  double eps = 1e-5;\n  BOOST_CHECK_CLOSE(t(U,0), 1., eps);\n  BOOST_CHECK_CLOSE(t(U,1), 4., eps);\n  BOOST_CHECK_CLOSE(t(U,2), 2., eps);\n  BOOST_CHECK_CLOSE(t(U,3), 5., eps);\n  BOOST_CHECK_CLOSE(t(U,4), 3., eps);\n  BOOST_CHECK_CLOSE(t(U,5), 6., eps);\n\n  Tensor b1 = cr.backward(xs, U, U, 0);\n  Tensor b2 = cr.backward(xs, U, U, 1);\n  Tensor b3 = cr.backward(xs, U, U, 2);\n  cerr << str(b1) << endl;\n  cerr << str(b2) << endl;\n  cerr << str(b3) << endl;\n  BOOST_CHECK_EQUAL(t(u1,0), t(b1,0));\n  BOOST_CHECK_EQUAL(t(u1,1), t(b1,1));\n  BOOST_CHECK_EQUAL(t(u2,0), t(b2,0));\n  BOOST_CHECK_EQUAL(t(u2,1), t(b2,1));\n  BOOST_CHECK_EQUAL(t(u3,0), t(b3,0));\n  BOOST_CHECK_EQUAL(t(u3,1), t(b3,1));\n  BOOST_CHECK_EQUAL(t(u3,2), t(b3,2));\n}\n\nBOOST_AUTO_TEST_CASE(EMultilinear) {\n  Tensor b = Ccm({3},{1,2,3});\n  Tensor W = Ccm({3,2},{2,4,6,3,5,7});\n  Tensor x = Ccm({2},{-1,1});\n  Multilinear ml;\n  vector<const Tensor*> mlxs = {&b, &W, &x};\n  Tensor r1 = ml.forward(mlxs);\n  Sum se;\n  MatrixMultiply mm;\n  Tensor p = mm.forward(vector<const Tensor*>({&W, &x}));\n  Tensor r2 = se.forward(vector<const Tensor*>({&p, &b}));\n  BOOST_REQUIRE(size(r1) == size(r2));\n  double eps = 1e-5;\n  cerr << r1 << endl;\n  cerr << r2 << endl;\n  BOOST_CHECK_CLOSE(t(r1,0), 2., eps);\n  BOOST_CHECK_CLOSE(t(r1,1), 3., eps);\n  BOOST_CHECK_CLOSE(t(r1,2), 4., eps);\n  BOOST_CHECK_CLOSE(t(r2,0), 2., eps);\n  BOOST_CHECK_CLOSE(t(r2,1), 3., eps);\n  BOOST_CHECK_CLOSE(t(r2,2), 4., eps);\n  cerr << \"Multilinear forward complete\\n\";\n  Tensor dEdf = Ccm({3}, {1., 0.5, 0.25});\n  Tensor dEdx = ml.backward(mlxs, r1, dEdf, 0);\n  cerr << \"BACK 0:\\n\";\n  BOOST_CHECK(size(dEdx) == size(b));\n  cerr << str(dEdx) << endl;\n  BOOST_CHECK_CLOSE(t(dEdx,0), 1., eps);\n  BOOST_CHECK_CLOSE(t(dEdx,1), 0.5, eps);\n  BOOST_CHECK_CLOSE(t(dEdx,2), 0.25, eps);\n  dEdx = ml.backward(mlxs, r1, dEdf, 1);\n  cerr << \"BACK 1:\\n\";\n  BOOST_CHECK(size(dEdx) == size(W));\n  cerr << str(dEdx) << endl;\n  BOOST_CHECK_CLOSE(t(dEdx,0,0), -1., eps);\n  BOOST_CHECK_CLOSE(t(dEdx,1,0), -0.5, eps);\n  BOOST_CHECK_CLOSE(t(dEdx,2,0), -0.25, eps);\n  BOOST_CHECK_CLOSE(t(dEdx,0,1), 1., eps);\n  BOOST_CHECK_CLOSE(t(dEdx,1,1), 0.5, eps);\n  BOOST_CHECK_CLOSE(t(dEdx,2,1), 0.25, eps);\n  dEdx = ml.backward(mlxs, r1, dEdf, 2);\n  cerr << \"BACK 2:\\n\";\n  BOOST_CHECK(size(dEdx) == size(x));\n  cerr << str(dEdx) << endl;\n  BOOST_CHECK_CLOSE(t(dEdx,0), 5.5, eps);\n  BOOST_CHECK_CLOSE(t(dEdx,1), 7.25, eps);\n}\n\nBOOST_AUTO_TEST_CASE(ELogisticSigmoid) {\n  Tensor x = Ccm({5,1},{-6.f,-logf(3),0.f,logf(3),6.f});\n  LogisticSigmoid ls;\n  vector<const Tensor*> xs = {&x};\n  Tensor r = ls.forward(xs);\n  BOOST_REQUIRE_EQUAL(size(r), size(x));\n  double eps = 1e-2;\n  BOOST_CHECK_CLOSE(t(r,0,0), 1. /(1. + exp(6.)), eps);\n  BOOST_CHECK_CLOSE(t(r,1,0), 0.25, eps);\n  BOOST_CHECK_CLOSE(t(r,2,0), 0.5, eps);\n  BOOST_CHECK_CLOSE(t(r,3,0), 0.75, eps);\n  BOOST_CHECK_CLOSE(t(r,4,0), 1. - t(r,0,0), eps);\n  cerr << \"HERE\\n\";\n  cerr << str(r) << endl;\n  Tensor dEdf = Ccm({5,1},{1.,1.,1.,1.,1.});\n  Tensor dEdx = ls.backward(xs, r, dEdf, 0);\n  BOOST_CHECK_CLOSE(t(dEdx,1,0), 0.1875, eps);\n  BOOST_CHECK_CLOSE(t(dEdx,2,0), 0.25, eps);\n  BOOST_CHECK_CLOSE(t(dEdx,3,0), t(dEdx,1,0), eps);\n  BOOST_CHECK_CLOSE(t(dEdx,4,0), t(dEdx,0,0), eps);\n}\n\nBOOST_AUTO_TEST_CASE(ETanh) {\n  Tensor x = Ccm({5,1},{-6.f,-logf(3),0.f,logf(3),6.f});\n  Tanh th;\n  vector<const Tensor*> xs = {&x};\n  Tensor r = th.forward(xs);\n  BOOST_REQUIRE(size(r) == size(x));\n  double eps = 1e-2;\n  BOOST_CHECK_CLOSE(t(r,1,0), -0.8, eps);\n  BOOST_CHECK_CLOSE(t(r,2,0), 0, eps);\n  BOOST_CHECK_CLOSE(t(r,3,0), 0.8, eps);\n  BOOST_CHECK_CLOSE(t(r,4,0), -t(r,0,0), eps);\n  Tensor dEdf = Ccm({5,1},{1.,1.,1.,1.,1.});\n  cerr << \"Tanh complete forward\\n\";\n  Tensor dEdx = th.backward(xs, r, dEdf, 0);\n  BOOST_CHECK_CLOSE(t(dEdx,1,0), 0.36, eps);\n  BOOST_CHECK_CLOSE(t(dEdx,2,0), 1.0, eps);\n  BOOST_CHECK_CLOSE(t(dEdx,3,0), t(dEdx,1,0), eps);\n  BOOST_CHECK_CLOSE(t(dEdx,4,0), t(dEdx,0,0), eps);\n}\n\nBOOST_AUTO_TEST_CASE(MatrixVector) {\n  cerr << \"Matrix-Vector\\n\";\n  Tensor W = Ccm({3,2},{2,4,6,3,5,7});\n  Tensor x = Ccm({2},{-1,1});\n  MatrixMultiply mm;\n  vector<const Tensor*> xs = {&W, &x};\n  Tensor fx = mm.forward(xs);\n  cerr << str(fx) << endl;\n  Tensor dEdf = Ccm({3},{-.5,0.25,5});\n  Tensor M = mm.backward(xs, fx, dEdf, 0);\n  cerr << \"Diff with respect to W:\\n\";\n  cerr << str(M) << endl;\n  double eps = 1e-5;\n  BOOST_CHECK_CLOSE(t(M,0,0), 0.5, eps);\n  BOOST_CHECK_CLOSE(t(M,1,0), -0.25, eps);\n  BOOST_CHECK_CLOSE(t(M,2,0), -5, eps);\n  BOOST_CHECK_CLOSE(t(M,0,1), -0.5, eps);\n  BOOST_CHECK_CLOSE(t(M,1,1), 0.25, eps);\n  BOOST_CHECK_CLOSE(t(M,2,1), 5, eps);\n  Tensor vv = mm.backward(xs, fx, dEdf, 1);\n  cerr << \"Diff with respect to x:\\n\";\n  cerr << str(vv) << endl;\n  BOOST_CHECK_CLOSE(t(vv,0), 30., eps);\n  BOOST_CHECK_CLOSE(t(vv,1), 34.75, eps);\n}\n\nBOOST_AUTO_TEST_CASE(EConstantMinus) {\n  Tensor W = Ccm({2,2},{1,2,3,-4});\n  ConstantMinusX om(1);\n  vector<const Tensor*> xs(1, &W);\n  Tensor O = om.forward(xs);\n  cerr << str(W) << endl;\n  cerr << str(O) << endl;\n  double eps = 1e-6;\n  BOOST_CHECK_CLOSE(10 + 1 - t(W,0,0), 10 + t(O,0,0), eps);\n  BOOST_CHECK_CLOSE(10 + 1 - t(W,0,1), 10 + t(O,0,1), eps);\n  BOOST_CHECK_CLOSE(10 + 1 - t(W,1,0), 10 + t(O,1,0), eps);\n  BOOST_CHECK_CLOSE(10 + 1 - t(W,1,1), 10 + t(O,1,1), eps);\n  Tensor V = -W;\n  cerr << str(W) << endl;\n  cerr << str(V) << endl;\n}\n\nBOOST_AUTO_TEST_CASE(ESoftmaxUnif) {\n  for (float v = -12.; v < 12.; v += 1.) { \n    Tensor u = Ccm({4}, {v, v, v, v});\n    Softmax sm;\n    vector<const Tensor*> xs = {&u};\n    Tensor m = sm.forward(xs);\n    BOOST_REQUIRE_EQUAL(Dim({4}),size(m));\n    double eps = 1e-5;\n    for (unsigned i = 0; i < 4; ++i)\n      BOOST_CHECK_CLOSE(t(m, i), 0.25, eps);\n    Tensor dEdf = Ccm({4}, {1., 0., 0., 0.});\n    Tensor d = sm.backward(xs, m, dEdf, 0);\n    BOOST_CHECK_CLOSE(t(d,0), 0.1875, eps);\n    BOOST_CHECK_CLOSE(t(d,1), -0.0625, eps);\n    BOOST_CHECK_CLOSE(t(d,2), -0.0625, eps);\n    BOOST_CHECK_CLOSE(t(d,3), -0.0625, eps);\n//    cerr << d << endl;\n\n    LogSoftmax lsm;\n    Tensor lm = lsm.forward(xs);\n    BOOST_REQUIRE_EQUAL(Dim({4}),size(lm));\n    for (unsigned i = 0; i < 4; ++i)\n      BOOST_CHECK_CLOSE(log(t(m, i)), t(lm, i), eps);\n    Tensor b = lsm.backward(xs, lm, dEdf, 0);\n    BOOST_CHECK_CLOSE(t(b, 0), 0.75, eps);\n    BOOST_CHECK_CLOSE(t(b, 1), -0.25, eps);\n    BOOST_CHECK_CLOSE(t(b, 2), -0.25, eps);\n    BOOST_CHECK_CLOSE(t(b, 3), -0.25, eps);\n  }\n}\n\n#ifdef WITH_THPP_BACKEND\nBOOST_AUTO_TEST_CASE(TensorInner3D_1D) {\n  Tensor A = Ccm({24}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23});\n  A.reshape(A, {2,3,4});\n  Tensor v = Ccm({4}, {-0.5, 1, 1.5, 2});\n  Tensor B = Ccm({2,3}, {1, 2, 3, 4, 5, 6});\n  vector<const Tensor*> xs = {&A, &v, &B};\n  InnerProduct3D_1D e;\n  Tensor Y = e.forward(xs);\n  cerr << str(Y) << endl;\n  double eps = 1e-5;\n  BOOST_CHECK_CLOSE(t(Y, 0, 0), 11, eps);\n  BOOST_CHECK_CLOSE(t(Y, 1, 0), 60, eps);\n  BOOST_CHECK_CLOSE(t(Y, 0, 1), 29, eps);\n  BOOST_CHECK_CLOSE(t(Y, 1, 1), 78, eps);\n  BOOST_CHECK_CLOSE(t(Y, 0, 2), 47, eps);\n  BOOST_CHECK_CLOSE(t(Y, 1, 2), 96, eps);\n  Tensor dEdY = Ccm({2,3}, {1, 0.1, -1, 1.2, 2, -0.25});\n  Tensor dEdx3 = e.backward(xs, Y, dEdY, 2);\n  cerr << str(dEdY) << endl;\n  cerr << str(dEdx3) << endl;\n  Tensor dEdx1 = e.backward(xs, Y, dEdY, 0);\n  cerr << dEdx1 << endl;\n  //cerr << str(dEdx1) << endl;\n  Tensor dEdx2 = e.backward(xs, Y, dEdY, 1);\n  cerr << str(dEdx2) << endl;\n}\n#endif\n\n", "meta": {"hexsha": "e1b46cfa3752904f089ced47e7c2a7ed36f53443", "size": 11189, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cnn/cnn/tests/test_edges.cc", "max_stars_repo_name": "miguelballesteros/Spinal", "max_stars_repo_head_hexsha": "0f765e5baeb07a1d068c4eda06b9222e06df2cde", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 219.0, "max_stars_repo_stars_event_min_datetime": "2015-06-27T13:15:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T20:45:34.000Z", "max_issues_repo_path": "cnn/cnn/tests/test_edges.cc", "max_issues_repo_name": "miguelballesteros/Spinal", "max_issues_repo_head_hexsha": "0f765e5baeb07a1d068c4eda06b9222e06df2cde", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2015-07-08T05:12:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-23T13:38:10.000Z", "max_forks_repo_path": "cnn/cnn/tests/test_edges.cc", "max_forks_repo_name": "miguelballesteros/Spinal", "max_forks_repo_head_hexsha": "0f765e5baeb07a1d068c4eda06b9222e06df2cde", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-06-29T16:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T20:35:14.000Z", "avg_line_length": 32.6209912536, "max_line_length": 111, "alphanum_fraction": 0.5979980338, "num_tokens": 4476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577159, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5313250530333172}}
{"text": "//=======================================================================\r\n// Copyright 2013 University of Warsaw.\r\n// Authors: Piotr Wygocki \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#ifndef BOOST_GRAPH_FIND_FLOW_COST_HPP\r\n#define BOOST_GRAPH_FIND_FLOW_COST_HPP\r\n\r\n#include <boost/graph/iteration_macros.hpp>\r\n\r\nnamespace boost {\r\n\r\ntemplate<class Graph, class Capacity, class ResidualCapacity, class Weight>\r\ntypename property_traits<Weight>::value_type\r\nfind_flow_cost(const Graph & g, Capacity capacity, ResidualCapacity residual_capacity, Weight weight) {\r\n    typedef typename property_traits<Weight>::value_type Cost;\r\n\r\n    Cost cost = 0;\r\n    BGL_FORALL_EDGES_T(e, g, Graph) {\r\n        if(get(capacity, e) > Cost(0)) {\r\n            cost +=  (get(capacity, e) - get(residual_capacity, e)) * get(weight, e);\r\n        } \r\n    }\r\n    return cost;\r\n}\r\n\r\ntemplate <class Graph, class P, class T, class R> \r\ntypename detail::edge_weight_value<Graph, P, T, R>::type\r\nfind_flow_cost(const Graph & g,\r\n               const bgl_named_params<P, T, R>& params) {\r\n    return find_flow_cost(g,\r\n           choose_const_pmap(get_param(params, edge_capacity), g, edge_capacity),\r\n           choose_const_pmap(get_param(params, edge_residual_capacity), \r\n                       g, edge_residual_capacity),\r\n           choose_const_pmap(get_param(params, edge_weight), g, edge_weight));\r\n}\r\n\r\ntemplate <class Graph>\r\ntypename property_traits<typename property_map < Graph, edge_capacity_t >::type>::value_type\r\nfind_flow_cost(const Graph &g) {\r\n    bgl_named_params<int, buffer_param_t> params(0);\r\n    return find_flow_cost(g, params);\r\n}\r\n\r\n\r\n} //boost\r\n\r\n#endif /* BOOST_GRAPH_FIND_FLOW_COST_HPP */\r\n\r\n", "meta": {"hexsha": "b1d567319343df8d6b60deb336e67651e5ef32bb", "size": 1894, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/graph/find_flow_cost.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/graph/find_flow_cost.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/graph/find_flow_cost.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": 35.7358490566, "max_line_length": 104, "alphanum_fraction": 0.6393875396, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5313250502263305}}
{"text": "// $Id$\n//\n//  Copyright (C) 2003-2008 Greg Landrum and Rational Discovery LLC\n//\n//   @@ All Rights Reserved @@\n//  This file is part of the RDKit.\n//  The contents are covered by the terms of the BSD license\n//  which is included in the file license.txt, found at the root\n//  of the RDKit source tree.\n//\n#include <GraphMol/ROMol.h>\n#include <GraphMol/Atom.h>\n#include <GraphMol/Bond.h>\n#include <GraphMol/BondIterators.h>\n#include <GraphMol/MolOps.h>\n#include <memory>\n#include <boost/shared_array.hpp>\n#include <algorithm>\n#include <cstring>\n\nnamespace RDKit {\n\nconst int LOCAL_INF = (int)1e8;\n\n// local utility namespace\nnamespace {\n/* ----------------------------------------------\n\nThis implements the Floyd-Warshall all-pairs-shortest-paths\nalgorithm as described on pg 564 of the White Book (Cormen, Leiserson, Rivest)\n\nArguments:\nadjMat: the adjacency matrix.  This is overwritten with the shortest\npaths, should be dim x dim\ndim: the size of adjMat\npathMat: the path matrix, should be dim x dim\n\n-----------------------------------------------*/\ntemplate <class T>\nvoid FloydWarshall(int dim, T *adjMat, int *pathMat) {\n  int k, i, j;\n  T *currD, *lastD, *tTemp;\n  int *currP, *lastP, *iTemp;\n\n  currD = new T[dim * dim];\n  currP = new int[dim * dim];\n  lastD = new T[dim * dim];\n  lastP = new int[dim * dim];\n\n  memcpy(static_cast<void *>(lastD), static_cast<void *>(adjMat),\n         dim * dim * sizeof(T));\n\n  // initialize the paths\n  for (i = 0; i < dim; i++) {\n    int itab = i * dim;\n    for (j = 0; j < dim; j++) {\n      if (i == j || adjMat[itab + j] == LOCAL_INF) {\n        pathMat[itab + j] = -1;\n      } else {\n        pathMat[itab + j] = i;\n      }\n    }\n  }\n  memcpy(static_cast<void *>(lastP), static_cast<void *>(pathMat),\n         dim * dim * sizeof(int));\n\n  for (k = 0; k < dim; k++) {\n    int ktab = k * dim;\n    for (i = 0; i < dim; i++) {\n      int itab = i * dim;\n      for (j = 0; j < dim; j++) {\n        T v1 = lastD[itab + j];\n        T v2 = lastD[itab + k] + lastD[ktab + j];\n        if (v1 <= v2) {\n          currD[itab + j] = v1;\n          currP[itab + j] = lastP[itab + j];\n        } else {\n          currD[itab + j] = v2;\n          currP[itab + j] = lastP[ktab + j];\n        }\n      }\n    }\n    tTemp = currD;\n    currD = lastD;\n    lastD = tTemp;\n\n    iTemp = currP;\n    currP = lastP;\n    lastP = iTemp;\n  }\n  memcpy(static_cast<void *>(adjMat), static_cast<void *>(lastD),\n         dim * dim * sizeof(T));\n  memcpy(static_cast<void *>(pathMat), static_cast<void *>(lastP),\n         dim * dim * sizeof(int));\n\n  delete[] currD;\n  delete[] currP;\n  delete[] lastD;\n  delete[] lastP;\n}\n\ntemplate <class T>\nvoid FloydWarshall(int dim, T *adjMat, int *pathMat,\n                   const std::vector<int> &activeAtoms) {\n  T *currD, *lastD, *tTemp;\n  int *currP, *lastP, *iTemp;\n\n  currD = new T[dim * dim];\n  currP = new int[dim * dim];\n  lastD = new T[dim * dim];\n  lastP = new int[dim * dim];\n\n  memcpy(static_cast<void *>(lastD), static_cast<void *>(adjMat),\n         dim * dim * sizeof(T));\n\n  // initialize the paths\n  for (auto ai : activeAtoms) {\n    int itab = ai * dim;\n    for (int activeAtom : activeAtoms) {\n      if (ai == activeAtom || adjMat[itab + activeAtom] == LOCAL_INF) {\n        pathMat[itab + activeAtom] = -1;\n      } else {\n        pathMat[itab + activeAtom] = ai;\n      }\n    }\n  }\n  memcpy(static_cast<void *>(lastP), static_cast<void *>(pathMat),\n         dim * dim * sizeof(int));\n\n  for (auto ak : activeAtoms) {\n    int ktab = ak * dim;\n    for (auto ai : activeAtoms) {\n      int itab = ai * dim;\n      for (int activeAtom : activeAtoms) {\n        T v1 = lastD[itab + activeAtom];\n        T v2 = lastD[itab + ak] + lastD[ktab + activeAtom];\n        if (v1 <= v2) {\n          currD[itab + activeAtom] = v1;\n          currP[itab + activeAtom] = lastP[itab + activeAtom];\n        } else {\n          currD[itab + activeAtom] = v2;\n          currP[itab + activeAtom] = lastP[ktab + activeAtom];\n        }\n      }\n    }\n    tTemp = currD;\n    currD = lastD;\n    lastD = tTemp;\n\n    iTemp = currP;\n    currP = lastP;\n    lastP = iTemp;\n  }\n  memcpy(static_cast<void *>(adjMat), static_cast<void *>(lastD),\n         dim * dim * sizeof(T));\n  memcpy(static_cast<void *>(pathMat), static_cast<void *>(lastP),\n         dim * dim * sizeof(int));\n\n  delete[] currD;\n  delete[] currP;\n  delete[] lastD;\n  delete[] lastP;\n}\n}  // end of local utility namespace\n\nnamespace MolOps {\ndouble *getDistanceMat(const ROMol &mol, bool useBO, bool useAtomWts,\n                       bool force, const char *propNamePrefix) {\n  std::string propName;\n  boost::shared_array<double> sptr;\n  if (propNamePrefix) {\n    propName = propNamePrefix;\n  } else {\n    propName = \"\";\n  }\n  propName += \"DistanceMatrix\";\n  // make sure we don't use the nonBO cache for the BO matrix and vice versa:\n  if (useBO) {\n    propName += \"BO\";\n  }\n  if (!force && mol.hasProp(propName)) {\n    mol.getProp(propName, sptr);\n    return sptr.get();\n  }\n  int nAts = mol.getNumAtoms();\n  auto *dMat = new double[nAts * nAts];\n  int i, j;\n  // initialize off diagonals to LOCAL_INF and diagonals to 0\n  for (i = 0; i < nAts * nAts; i++) {\n    dMat[i] = LOCAL_INF;\n  }\n  for (i = 0; i < nAts; i++) {\n    dMat[i * nAts + i] = 0.0;\n  }\n\n  ROMol::EDGE_ITER firstB, lastB;\n  boost::tie(firstB, lastB) = mol.getEdges();\n  while (firstB != lastB) {\n    const Bond* bond = mol[*firstB];\n    i = bond->getBeginAtomIdx();\n    j = bond->getEndAtomIdx();\n    double contrib;\n    if (useBO) {\n      if (!bond->getIsAromatic()) {\n        contrib = 1. / bond->getBondTypeAsDouble();\n      } else {\n        contrib = 2. / 3.;\n      }\n    } else {\n      contrib = 1.0;\n    }\n    dMat[i * nAts + j] = contrib;\n    dMat[j * nAts + i] = contrib;\n    ++firstB;\n  }\n\n  auto *pathMat = new int[nAts * nAts];\n  memset(static_cast<void *>(pathMat), 0, nAts * nAts * sizeof(int));\n  FloydWarshall(nAts, dMat, pathMat);\n\n  if (useAtomWts) {\n    for (i = 0; i < nAts; i++) {\n      int anum = mol.getAtomWithIdx(i)->getAtomicNum();\n      dMat[i * nAts + i] = 6.0 / anum;\n    }\n  }\n  sptr.reset(dMat);\n  mol.setProp(propName, sptr, true);\n  boost::shared_array<int> iSptr(pathMat);\n  mol.setProp(propName + \"_Paths\", iSptr, true);\n\n  return dMat;\n};\n\ndouble *getDistanceMat(const ROMol &mol, const std::vector<int> &activeAtoms,\n                       const std::vector<const Bond *> &bonds, bool useBO,\n                       bool useAtomWts) {\n  const int nAts = rdcast<int>(activeAtoms.size());\n\n  auto *dMat = new double[nAts * nAts];\n  int i, j;\n  // initialize off diagonals to LOCAL_INF and diagonals to 0\n  for (i = 0; i < nAts * nAts; i++) {\n    dMat[i] = LOCAL_INF;\n  }\n  for (i = 0; i < nAts; i++) {\n    dMat[i * nAts + i] = 0.0;\n  }\n\n  for (auto bond : bonds) {\n    i = rdcast<int>(std::find(activeAtoms.begin(), activeAtoms.end(),\n                              static_cast<int>(bond->getBeginAtomIdx())) -\n                    activeAtoms.begin());\n    j = rdcast<int>(std::find(activeAtoms.begin(), activeAtoms.end(),\n                              static_cast<int>(bond->getEndAtomIdx())) -\n                    activeAtoms.begin());\n    double contrib;\n    if (useBO) {\n      if (!bond->getIsAromatic()) {\n        contrib = 1. / bond->getBondTypeAsDouble();\n      } else {\n        contrib = 2. / 3.;\n      }\n    } else {\n      contrib = 1.0;\n    }\n    dMat[i * nAts + j] = contrib;\n    dMat[j * nAts + i] = contrib;\n  }\n\n  auto *pathMat = new int[nAts * nAts];\n  memset(static_cast<void *>(pathMat), 0, nAts * nAts * sizeof(int));\n  FloydWarshall(nAts, dMat, pathMat);\n  delete[] pathMat;\n\n  if (useAtomWts) {\n    for (i = 0; i < nAts; i++) {\n      int anum = mol.getAtomWithIdx(activeAtoms[i])->getAtomicNum();\n      dMat[i * nAts + i] = 6.0 / anum;\n    }\n  }\n  return dMat;\n};\n\n// NOTE: do *not* delete results\ndouble *getAdjacencyMatrix(const ROMol &mol, bool useBO, int emptyVal,\n                           bool force, const char *propNamePrefix,\n                           const boost::dynamic_bitset<> *bondsToUse) {\n  std::string propName;\n  boost::shared_array<double> sptr;\n  if (propNamePrefix) {\n    propName = propNamePrefix;\n  } else {\n    propName = \"\";\n  }\n  propName += \"AdjacencyMatrix\";\n  if (!force && mol.hasProp(propName)) {\n    mol.getProp(propName, sptr);\n    return sptr.get();\n  }\n\n  int nAts = mol.getNumAtoms();\n  auto *res = new double[nAts * nAts];\n  memset(static_cast<void *>(res), emptyVal, nAts * nAts * sizeof(double));\n\n  for (ROMol::ConstBondIterator bondIt = mol.beginBonds();\n       bondIt != mol.endBonds(); bondIt++) {\n    if (bondsToUse && !(*bondsToUse)[(*bondIt)->getIdx()]) {\n      continue;\n    }\n    if (!useBO) {\n      int beg = (*bondIt)->getBeginAtomIdx();\n      int end = (*bondIt)->getEndAtomIdx();\n      res[beg * nAts + end] = 1;\n      res[end * nAts + beg] = 1;\n    } else {\n      int begIdx = (*bondIt)->getBeginAtomIdx();\n      int endIdx = (*bondIt)->getEndAtomIdx();\n      Atom const *beg = mol.getAtomWithIdx(begIdx);\n      Atom const *end = mol.getAtomWithIdx(endIdx);\n      res[begIdx * nAts + endIdx] = (*bondIt)->getValenceContrib(beg);\n      res[endIdx * nAts + begIdx] = (*bondIt)->getValenceContrib(end);\n    }\n  }\n  sptr.reset(res);\n  mol.setProp(propName, sptr, true);\n\n  return res;\n};\n\nINT_LIST getShortestPath(const ROMol &mol, int aid1, int aid2) {\n  int nats = mol.getNumAtoms();\n  RANGE_CHECK(0, aid1, nats - 1);\n  RANGE_CHECK(0, aid2, nats - 1);\n  CHECK_INVARIANT(aid1 != aid2, \"\");\n\n  INT_VECT pred(nats, -1);  // set all atoms to unprocessed state\n  pred[aid1] = -2;          // marks begin\n  pred[aid2] = -3;          // marks end\n\n  std::deque<int> bfsQ;\n\n  bfsQ.push_back(aid1);\n  bool done = false;\n  ROMol::ADJ_ITER nbrIdx, endNbrs;\n  while ((!done) && (bfsQ.size() > 0)) {\n    int curAid = bfsQ.front();\n    boost::tie(nbrIdx, endNbrs) =\n        mol.getAtomNeighbors(mol.getAtomWithIdx(curAid));\n    while (!done && nbrIdx != endNbrs) {\n      switch (pred[*nbrIdx]) {\n        case -1:\n          pred[*nbrIdx] = curAid;\n          bfsQ.push_back(rdcast<int>(*nbrIdx));\n          break;\n        case -3:  // end found\n          pred[*nbrIdx] = curAid;\n          done = true;\n          break;\n        default:  // already processed (or begin)\n          break;\n      }\n      ++nbrIdx;\n    }\n    bfsQ.pop_front();\n  }\n\n  INT_LIST res;\n  if (done) {\n    done = false;\n    int prev = aid2;\n    res.push_back(aid2);\n    while (!done) {\n      prev = pred[prev];\n      if (prev != aid1) {\n        res.push_front(prev);\n      } else {\n        done = true;\n      }\n    }\n    res.push_front(aid1);\n  }\n  return res;\n}\n\ndouble *get3DDistanceMat(const ROMol &mol, int confId, bool useAtomWts,\n                         bool force, const char *propNamePrefix) {\n  const Conformer &conf = mol.getConformer(confId);\n  std::string propName;\n  boost::shared_array<double> sptr;\n  if (propNamePrefix) {\n    propName = propNamePrefix;\n  } else {\n    propName = \"_\";\n  }\n  if (propName != \"\") {\n    propName += \"3DDistanceMatrix_Conf\" + std::to_string(conf.getId());\n    if (!force && mol.hasProp(propName)) {\n      mol.getProp(propName, sptr);\n      return sptr.get();\n    }\n  }\n\n  unsigned int nAts = mol.getNumAtoms();\n  auto *dMat = new double[nAts * nAts];\n\n  for (unsigned int i = 0; i < nAts; ++i) {\n    if (useAtomWts) {\n      dMat[i * nAts + i] = 6.0 / mol.getAtomWithIdx(i)->getAtomicNum();\n    } else {\n      dMat[i * nAts + i] = 0.0;\n    }\n    for (unsigned int j = i + 1; j < nAts; ++j) {\n      double dist = (conf.getAtomPos(i) - conf.getAtomPos(j)).length();\n      dMat[i * nAts + j] = dist;\n      dMat[j * nAts + i] = dist;\n    }\n  }\n\n  if (propName != \"\") {\n    sptr.reset(dMat);\n    mol.setProp(propName, sptr, true);\n  }\n  return dMat;\n}\n}  // end of namespace MolOps\n}  // end of namespace RDKit\n", "meta": {"hexsha": "6df5f661fb9554d9a55f32aad7e640e2a683c067", "size": 11775, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/Matrices.cpp", "max_stars_repo_name": "jungb-basf/rdkit", "max_stars_repo_head_hexsha": "5d0eb77c655b6ba91f0891e7dc51e658aced3d00", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T14:52:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T08:12:45.000Z", "max_issues_repo_path": "Code/GraphMol/Matrices.cpp", "max_issues_repo_name": "jungb-basf/rdkit", "max_issues_repo_head_hexsha": "5d0eb77c655b6ba91f0891e7dc51e658aced3d00", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-08-08T13:53:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-08T05:52:07.000Z", "max_forks_repo_path": "Code/GraphMol/Matrices.cpp", "max_forks_repo_name": "bp-kelley/rdkit", "max_forks_repo_head_hexsha": "e0de7c9622ce73894b1e7d9568532f6d5638058a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-15T15:48:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T15:48:44.000Z", "avg_line_length": 27.511682243, "max_line_length": 78, "alphanum_fraction": 0.5645010616, "num_tokens": 3660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5311390834283969}}
{"text": "#include <boost/compute/random/linear_congruential_engine.hpp>\n", "meta": {"hexsha": "77fc68a679b5de13fb1e8586b35e9689613ef6e6", "size": 63, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_compute_random_linear_congruential_engine.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_compute_random_linear_congruential_engine.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_compute_random_linear_congruential_engine.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 31.5, "max_line_length": 62, "alphanum_fraction": 0.8571428571, "num_tokens": 15, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5311390723139037}}
{"text": "#include <boost/python/def.hpp>\n#include <boost/python/args.hpp>\n\n#include <scitbx/math/interpolation.h>\n#include <scitbx/math/linear_interpolation.h>\n#include <scitbx/vec3.h>\n#include <scitbx/vec2.h>\n\nnamespace scitbx { namespace math {\n\nnamespace {\n\n  template <typename PointType>\n  void wrap_splines()\n  {\n    using namespace boost::python;\n    def(\"interpolate_catmull_rom_spline\",\n      (af::shared<PointType>(*)(\n        PointType const&,\n        PointType const&,\n        PointType const&,\n        PointType const&,\n        unsigned)) interpolate_catmull_rom_spline, (\n          arg(\"p0\"),\n          arg(\"p1\"),\n          arg(\"p2\"),\n          arg(\"p3\"),\n          arg(\"n_points\")));\n  }\n\n  template <typename FloatType>\n  void wrap_interp_2d()\n  {\n    using namespace boost::python;\n    def(\"linear_interpolation_2d\",\n      (FloatType (*)(\n          FloatType const&,\n          FloatType const&,\n          FloatType const&,\n          FloatType const&,\n          FloatType const&,\n          FloatType const&,\n          FloatType const&,\n          FloatType const&,\n          FloatType const&,\n          FloatType const&)) linear_interpolation_2d, (\n            arg(\"x1\"),\n            arg(\"y1\"),\n            arg(\"x2\"),\n            arg(\"y2\"),\n            arg(\"v1\"),\n            arg(\"v2\"),\n            arg(\"v3\"),\n            arg(\"v4\"),\n            arg(\"xx\"),\n            arg(\"yy\")));\n  }\n\n} // namespace <anonymous>\n\nnamespace boost_python {\n\n  void wrap_interpolation()\n  {\n    wrap_splines< scitbx::vec2<double> >();\n    wrap_splines< scitbx::vec3<double> >();\n    wrap_interp_2d <double> ();\n  }\n\n}}} // namespace scitbx::math::boost_python\n", "meta": {"hexsha": "1d73eb9eefbb4ce717115d6241d65b815abfdefa", "size": 1647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/math/boost_python/interpolation.cpp", "max_stars_repo_name": "dperl-sol/cctbx_project", "max_stars_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/math/boost_python/interpolation.cpp", "max_issues_repo_name": "dperl-sol/cctbx_project", "max_issues_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/math/boost_python/interpolation.cpp", "max_forks_repo_name": "dperl-sol/cctbx_project", "max_forks_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 23.1971830986, "max_line_length": 55, "alphanum_fraction": 0.5561627201, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5311390668310336}}
{"text": "#include <cmath>\n#include <vector>\n\n#include <Eigen/Dense>\n#include \"gtest/gtest.h\"\n\n#include \"BingoCpp/backend.h\"\n#include \"testing_utils.h\"\n#include \"test_fixtures.h\"\n\nusing namespace bingo;\nnamespace {\nconst int N_OPS = 13;\n\nclass AGraphBackend : public ::testing::TestWithParam<int> {\n public:\n  \n  const double AGRAPH_VAL_START =-1;\n  const double AGRAPH_VAL_END = 0;\n  const int N_AGRAPH_VAL = 11;\n\n  testutils::AGraphValues sample_agraph_1_values;\n  std::vector<Eigen::ArrayXXd> operator_evals_x0;\n  std::vector<Eigen::ArrayXXd> operator_x_derivs;\n  std::vector<Eigen::ArrayXXd> operator_c_derivs;\n\n  Eigen::ArrayX3i simple_stack;\n  Eigen::ArrayX3i simple_stack2;\n  Eigen::ArrayXXd x;\n  Eigen::ArrayXd constants;\n\n  virtual void SetUp() {\n    sample_agraph_1_values = testutils::init_agraph_vals(AGRAPH_VAL_START,\n                                                         AGRAPH_VAL_END,\n                                                         N_AGRAPH_VAL);\n    operator_evals_x0 = testutils::init_op_evals_x0(sample_agraph_1_values);\n    operator_x_derivs = testutils::init_op_x_derivs(sample_agraph_1_values);\n    operator_c_derivs = testutils::init_op_c_derivs(sample_agraph_1_values);\n\n    simple_stack = testutils::stack_operators_0_to_5(); \n    simple_stack2 = testutils::stack_unary_operator(4);\n    x = testutils::one_to_nine_3_by_3();\n    constants = testutils::pi_ten_constants();\n  }\n  virtual void TearDown() {}\n};\n\nTEST_P(AGraphBackend, simplify_and_evaluate) {\n  int operator_i = GetParam();\n  Eigen::ArrayXXd expected_outcome = operator_evals_x0[operator_i];\n\n  Eigen::ArrayX3i stack(3, 3);\n  stack << 0, 0, 0,\n           0, 1, 0,\n           operator_i, 0, 0;\n  Eigen::ArrayXXd f_of_x = simplify_and_evaluate(stack,\n                                                 sample_agraph_1_values.x_vals,\n                                                 sample_agraph_1_values.constants);\n  ASSERT_TRUE(testutils::almost_equal(expected_outcome, f_of_x));\n}\n\nTEST_P(AGraphBackend, simplify_and_evaluate_x_deriv) {\n  int operator_i = GetParam();\n  Eigen::ArrayXXd expected_derivative = \n    Eigen::ArrayXXd::Zero(sample_agraph_1_values.x_vals.rows(), 2);\n  expected_derivative.col(0) = operator_x_derivs[operator_i];\n\n  Eigen::ArrayX3i stack(4, 3);\n  stack << 0, 0, 0,\n           0, 0, 0,\n           0, 1, 1,\n           operator_i, 0, 1;\n\n  Eigen::ArrayXXd x_0 = sample_agraph_1_values.x_vals;\n  Eigen::ArrayXXd constants = sample_agraph_1_values.constants;\n  std::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> res_and_gradient = \n    simplify_and_evaluate_with_derivative(stack,\n                                          x_0,\n                                          constants,\n                                          true);\n  Eigen::ArrayXXd df_dx = res_and_gradient.second;\n  ASSERT_TRUE(testutils::almost_equal(expected_derivative, df_dx));\n}\n\nTEST_P(AGraphBackend, simplify_and_evaluate_c_deriv) {\n  int operator_i = GetParam();\n  int num_x_points = sample_agraph_1_values.x_vals.rows();\n  int num_consts = sample_agraph_1_values.constants.size();\n  int last_col = num_consts - 1;\n  Eigen::ArrayXXd expected_derivative = \n    Eigen::MatrixXd::Zero(num_x_points, num_consts).array();\n  expected_derivative.col(last_col) = operator_c_derivs[operator_i];\n  \n  Eigen::ArrayX3i stack(4, 3);\n  stack << 1, 1, 1,\n           1, 1, 1,\n           0, 1, 1,\n           operator_i, 1, 0;\n  \n  Eigen::ArrayXXd x_0 = sample_agraph_1_values.x_vals;\n  Eigen::ArrayXXd constants = sample_agraph_1_values.constants;\n  std::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> res_and_gradient = \n    simplify_and_evaluate_with_derivative(stack,\n                                          x_0,\n                                          constants,\n                                          false);\n  Eigen::ArrayXXd df_dc = res_and_gradient.second;\n  ASSERT_TRUE(testutils::almost_equal(expected_derivative, df_dc));\n}\nINSTANTIATE_TEST_CASE_P(,AGraphBackend, ::testing::Range(0, N_OPS, 1));\n\n\nTEST_F(AGraphBackend, evaluate) {\n  Eigen::ArrayXXd y = evaluate(simple_stack, x, constants);\n  Eigen::ArrayXXd y_true = x.col(0) * (constants[0] + constants[1] \n                          / x.col(1)) - x.col(0);\n  ASSERT_TRUE(testutils::almost_equal(y, y_true));\n}\n\nTEST_F(AGraphBackend, evaluate_and_derivative) {\n  std::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> y_and_dy =\n    evaluate_with_derivative(simple_stack, x, constants);\n  Eigen::ArrayXXd y_true = x.col(0) * (constants[0] + constants[1] \n                          / x.col(1)) - x.col(0);\n  Eigen::ArrayXXd dy_true = Eigen::ArrayXXd::Zero(3, 3);\n  dy_true.col(0) = constants[0] + constants[1] / x.col(1) - 1.;\n  dy_true.col(1) = - x.col(0) * constants[1] / x.col(1) / x.col(1);\n\n  ASSERT_TRUE(testutils::almost_equal(y_and_dy.first, y_true));\n  ASSERT_TRUE(testutils::almost_equal(y_and_dy.second, dy_true));\n}\n\nTEST_F(AGraphBackend, mask_evaluate) {\n  Eigen::ArrayXXd y = evaluate(simple_stack, x, constants);\n  Eigen::ArrayXXd y_simple = simplify_and_evaluate(simple_stack, x, constants);\n  ASSERT_TRUE(testutils::almost_equal(y, y_simple));\n}\n\nTEST_F(AGraphBackend, mask_evaluate_and_derivative) {\n  std::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> y_and_dy =\n    evaluate_with_derivative(simple_stack, x, constants);\n  std::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> y_and_dy_simple =\n    simplify_and_evaluate_with_derivative(simple_stack, x, constants);\n  ASSERT_TRUE(testutils::almost_equal(y_and_dy.first, y_and_dy_simple.first));\n  ASSERT_TRUE(testutils::almost_equal(y_and_dy.first, y_and_dy_simple.first));\n}\n\n// TEST_F(AcyclicGraphTest, simplify) {\n//   // shorter stack\n//   std::cout << \"stack\\n\" << stack << std::endl;\n//   Eigen::ArrayX3i short_stack = SimplifyStack(stack);\n//   std::cout << \"2\\n\";\n//   ASSERT_LE(short_stack.rows(), stack.rows());\n//   std::cout << \"3\\n\";\n\n//   // equivalent evatuation\n//   Eigen::ArrayXXd y = Evaluate(stack, x, constants);\n//   std::cout << \"4\\n\";\n//   Eigen::ArrayXXd simplified_y = Evaluate(short_stack, x, constants);\n//   std::cout << \"5\\n\";\n\n//   for (size_t i = 0; i < x.rows(); ++i) {\n//     ASSERT_EQ(y(i), simplified_y(i));\n//   }\n// }\n\nTEST_F(AGraphBackend, get_utilized_commands) {\n  std::vector<bool> used_commands = get_utilized_commands(simple_stack);\n  int num_used_commands = 0;\n  for (auto const& command_is_used : used_commands) {\n    if (command_is_used) {\n      ++num_used_commands;\n    }\n  }\n  ASSERT_EQ(num_used_commands, 8);\n}\n} // namespace\n", "meta": {"hexsha": "675101cc4787ba296bdcde5ae219acf00705fa68", "size": 6440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/agraph_backend_tests.cpp", "max_stars_repo_name": "tylertownsend/bingocpp", "max_stars_repo_head_hexsha": "c8133fca89edaea30205b70eb5d2a8c91271cb80", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/agraph_backend_tests.cpp", "max_issues_repo_name": "tylertownsend/bingocpp", "max_issues_repo_head_hexsha": "c8133fca89edaea30205b70eb5d2a8c91271cb80", "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/agraph_backend_tests.cpp", "max_forks_repo_name": "tylertownsend/bingocpp", "max_forks_repo_head_hexsha": "c8133fca89edaea30205b70eb5d2a8c91271cb80", "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.1797752809, "max_line_length": 83, "alphanum_fraction": 0.6628881988, "num_tokens": 1773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5311390667566568}}
{"text": "/**\n * GlobalNearestNeighborAssociation.hpp\n * @author koide\n * 15/05/29\n**/\n#ifndef KKL_GLOBAL_NEAREST_NEIGHBOR_ASSOCIATION_HPP\n#define KKL_GLOBAL_NEAREST_NEIGHBOR_ASSOCIATION_HPP\n\n#include <memory>\n#include <boost/range/algorithm.hpp>\n\n#include <kkl/alg/munkres.hpp>\n#include <kkl/alg/data_association.hpp>\n\nnamespace kkl {\n\tnamespace alg {\n\n/******************************************\n * GlobalNearestNeighborAssociation\n * \n******************************************/\ntemplate<typename Tracker, typename Observation>\nclass GlobalNearestNeighborAssociation : public DataAssociation<Tracker, Observation> {\n    typedef typename DataAssociation<Tracker, Observation>::Association Association;\npublic:\n\t// constructor, destructor\n\tGlobalNearestNeighborAssociation()\n\t\t: munkres( new Munkres<double>() ){}\n\tvirtual ~GlobalNearestNeighborAssociation() {}\n\n\t// associate\n    std::vector<Association> associate(const std::vector<Tracker>& trackers, const std::vector<Observation>& observations) override {\n\t\tconst double HUGE_VALUE = 1000000.0;\n\n\t\t// create cost matrix between tracker and observation\n\t\tEigen::MatrixXd cost_matrix;\n\t\tbool transposed = trackers.size() > observations.size();\n\t\t\n\t\tif (!transposed) {\n\t\t\tcost_matrix = Eigen::MatrixXd::Constant(trackers.size(), observations.size(), HUGE_VALUE + 1);\n\t\t\tfor (int i = 0; i < trackers.size(); i++) {\n\t\t\t\tfor (int j = 0; j < observations.size(); j++) {\n\t\t\t\t\tauto dist = distance<Tracker, Observation>(trackers[i], observations[j]);\n\t\t\t\t\tif (dist) {\n\t\t\t\t\t\tcost_matrix(i, j) = dist.get();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tcost_matrix = Eigen::MatrixXd::Constant(observations.size(), trackers.size(), HUGE_VALUE + 1);\n\t\t\tfor (int i = 0; i < observations.size(); i++) {\n\t\t\t\tfor (int j = 0; j < trackers.size(); j++) {\n\t\t\t\t\tauto dist = distance<Tracker, Observation>(trackers[j], observations[i]);\n\t\t\t\t\tif (dist) {\n\t\t\t\t\t\tcost_matrix(i, j) = dist.get();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// solve combinatorial optimization using Munkres algorithm\n\t\tauto solution = munkres->solve(cost_matrix);\n\n\t\tstd::vector<Association> associations;\n\t\tassociations.reserve(trackers.size());\n\n\t\tfor (int i = 0; i < solution.size(); i++) {\n\t\t\tint tracker;\n\t\t\tint observation;\n\n\t\t\tif (!transposed) {\n\t\t\t\ttracker = i;\n\t\t\t\tobservation = solution[i];\n\t\t\t} else {\n\t\t\t\ttracker = solution[i];\n\t\t\t\tobservation = i;\n\t\t\t}\n\n\t\t\tif (cost_matrix(i, solution[i]) < HUGE_VALUE) {\n\t\t\t\tassociations.push_back(Association(tracker, observation, cost_matrix(i, solution[i])));\n\t\t\t}\n\t\t}\n\n\t\treturn associations;\n\t}\n\nprivate:\n\tstd::unique_ptr<Munkres<double>> munkres;\n};\n\n\t}\n}\n\n#endif\n", "meta": {"hexsha": "3b6605ce9d98ace9fd603101314d406cedb819d6", "size": 2589, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kkl/alg/global_nearest_neighbor_association.hpp", "max_stars_repo_name": "y-lai/hdl_people_tracking", "max_stars_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 207.0, "max_stars_repo_stars_event_min_datetime": "2018-03-10T14:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T07:32:53.000Z", "max_issues_repo_path": "include/kkl/alg/global_nearest_neighbor_association.hpp", "max_issues_repo_name": "y-lai/hdl_people_tracking", "max_issues_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2018-02-19T10:50:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T19:44:55.000Z", "max_forks_repo_path": "include/kkl/alg/global_nearest_neighbor_association.hpp", "max_forks_repo_name": "y-lai/hdl_people_tracking", "max_forks_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 91.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T09:44:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T01:38:14.000Z", "avg_line_length": 26.96875, "max_line_length": 133, "alphanum_fraction": 0.662417922, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.5311390611250326}}
{"text": "#include <boost/cstdint.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/simd/sdk/memory/is_power_of_2.hpp>\n\nusing boost::simd::meta::is_power_of_2;\n\nint main()\n{\n  BOOST_MPL_ASSERT(( is_power_of_2< boost::mpl::int_<2> >::type ));\n  BOOST_MPL_ASSERT(( is_power_of_2< boost::mpl::int_<4> >::type ));\n  BOOST_MPL_ASSERT(( is_power_of_2< boost::mpl::int_<8> >::type ));\n  BOOST_MPL_ASSERT_NOT(( is_power_of_2< boost::mpl::int_<0> >::type ));\n  BOOST_MPL_ASSERT_NOT(( is_power_of_2< boost::mpl::int_<10> >::type ));\n}\n", "meta": {"hexsha": "c149c0843beb42e6fbadb5df4b4ea06eb1f26b36", "size": 589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/examples/memory/is_power_of_2.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/boost/simd/sdk/examples/memory/is_power_of_2.cpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/sdk/examples/memory/is_power_of_2.cpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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.6470588235, "max_line_length": 72, "alphanum_fraction": 0.7079796265, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5311254588939899}}
{"text": "#include \"drakeGeometryUtil.h\"\n#include <iostream>\n#include <cmath>\n#include <limits>\n#include <stdexcept>\n#include <Eigen/Sparse>\n\nusing namespace Eigen;\n\n\ndouble angleDiff(double phi1, double phi2)\n{\n  double d = phi2-phi1;\n  if(d>0.0)\n  {\n    d = fmod(d+M_PI,2*M_PI)-M_PI;\n  }\n  else\n  {\n    d = fmod(d-M_PI,2*M_PI)+M_PI;\n  }\n  return d;\n}\n\n\nVector4d quatConjugate(const Eigen::Vector4d& q)\n{\n  Vector4d q_conj;\n  q_conj << q(0), -q(1), -q(2), -q(3);\n  return q_conj;\n}\n\nEigen::Matrix4d dquatConjugate()\n{\n  Matrix4d dq_conj = Matrix4d::Identity();\n  dq_conj(1, 1) = -1.0;\n  dq_conj(2, 2) = -1.0;\n  dq_conj(3, 3) = -1.0;\n  return dq_conj;\n}\n\nEigen::Vector4d quatProduct(const Eigen::Vector4d& q1, const Eigen::Vector4d& q2)\n{\n  double w1 = q1(0);\n  double w2 = q2(0);\n  const auto& v1 = q1.tail<3>();\n  const auto& v2 = q2.tail<3>();\n  Vector4d r;\n  r << w1 * w2 - v1.dot(v2), v1.cross(v2) + w1 * v2 + w2 * v1;\n  return r;\n}\n\nEigen::Matrix<double, 4, 8> dquatProduct(const Eigen::Vector4d& q1, const Eigen::Vector4d& q2)\n{\n  double w1 = q1(0);\n  double w2 = q2(0);\n  const auto& v1 = q1.tail<3>();\n  const auto& v2 = q2.tail<3>();\n\n  Matrix<double, 4, 8> dr;\n  dr.row(0) << w2, -v2.transpose(), w1, -v1.transpose();\n  dr.row(1) << q2(1), q2(0), q2(3), -q2(2), q1(1), q1(0), -q1(3), q1(2);\n  dr.row(2) << q2(2), -q2(3), q2(0), q2(1), q1(2), q1(3), q1(0), -q1(1);\n  dr.row(3) << q2(3), q2(2), -q2(1), q2(0), q1(3), -q1(2), q1(1), q1(0);\n  return dr;\n}\n\nEigen::Vector3d quatRotateVec(const Eigen::Vector4d& q, const Eigen::Vector3d& v)\n{\n  Vector4d v_quat;\n  v_quat << 0, v;\n  Vector4d q_times_v = quatProduct(q, v_quat);\n  Vector4d q_conj = quatConjugate(q);\n  Vector4d v_rot = quatProduct(q_times_v, q_conj);\n  Vector3d r = v_rot.bottomRows<3>();\n  return r;\n}\n\nEigen::Matrix<double, 3, 7> dquatRotateVec(const Eigen::Vector4d& q, const Eigen::Vector3d& v)\n{\n  Matrix<double, 4, 7> dq;\n  dq << Matrix4d::Identity(), MatrixXd::Zero(4, 3);\n  Matrix<double, 4, 7> dv = Matrix<double, 4, 7>::Zero();\n  dv.bottomRightCorner<3, 3>() = Matrix3d::Identity();\n  Matrix<double, 8, 7> dqdv;\n  dqdv << dq, dv;\n\n  Vector4d v_quat;\n  v_quat << 0, v;\n  Vector4d q_times_v = quatProduct(q, v_quat);\n  Matrix<double, 4, 8> dq_times_v_tmp = dquatProduct(q, v_quat);\n  Matrix<double, 4, 7> dq_times_v = dq_times_v_tmp * dqdv;\n\n  Matrix<double, 4, 7> dq_conj = dquatConjugate() * dq;\n  Matrix<double, 8, 7> dq_times_v_dq_conj;\n  dq_times_v_dq_conj << dq_times_v, dq_conj;\n  Matrix<double, 4, 8> dv_rot_tmp = dquatProduct(q_times_v, quatConjugate(q));\n  Matrix<double, 4, 7> dv_rot = dv_rot_tmp * dq_times_v_dq_conj;\n  Eigen::Matrix<double, 3, 7> dr = dv_rot.bottomRows(3);\n  return dr;\n}\n\nEigen::Vector4d quatDiff(const Eigen::Vector4d& q1, const Eigen::Vector4d& q2)\n{\n  return quatProduct(quatConjugate(q1), q2);\n}\n\nEigen::Matrix<double, 4, 8> dquatDiff(const Eigen::Vector4d& q1, const Eigen::Vector4d& q2)\n{\n  auto dr = dquatProduct(quatConjugate(q1), q2);\n  dr.block<4, 3>(0, 1) = -dr.block<4, 3>(0, 1);\n  return dr;\n}\n\ndouble quatDiffAxisInvar(const Eigen::Vector4d& q1, const Eigen::Vector4d& q2, const Eigen::Vector3d& u)\n{\n  Vector4d r = quatDiff(q1, q2);\n  double e = -2.0 + 2 * r(0) * r(0) + 2 * pow(u(0) * r(1) + u(1) * r(2) + u(2) * r(3), 2);\n  return e;\n}\n\nEigen::Matrix<double, 1, 11> dquatDiffAxisInvar(const Eigen::Vector4d& q1, const Eigen::Vector4d& q2, const Eigen::Vector3d& u)\n{\n  Vector4d r = quatDiff(q1, q2);\n  Matrix<double, 4, 8> dr = dquatDiff(q1, q2);\n  Matrix<double, 1, 11> de;\n  const auto& rvec = r.tail<3>();\n  de << 4.0 * r(0) * dr.row(0) + 4.0 * u.transpose() * rvec *u.transpose() * dr.block<3, 8>(1, 0), 4.0 * u.transpose() * rvec * rvec.transpose();\n  return de;\n}\n\ndouble quatNorm(const Eigen::Vector4d& q)\n{\n  return std::acos(q(0));\n}\n\nEigen::Vector4d slerp(const Eigen::Vector4d& q1, const Eigen::Vector4d& q2, double interpolation_parameter)\n{\n  /*\n   * Q = slerp(q1, q2, f) Spherical linear interpolation between two quaternions\n   *   This function uses the implementation given in Algorithm 8 of [1].\n   *\n   * @param q1   Initial quaternion (w, x, y, z)\n   * @param q2   Final quaternion (w, x, y, z)\n   * @param f    Interpolation parameter between 0 and 1 (inclusive)\n   * @retval Q   Interpolated quaternion(s). 4-by-1 vector.\n   *\n   * [1] Kuffner, J.J., \"Effective sampling and distance metrics for 3D rigid\n   * body path planning,\" Robotics and Automation, 2004. Proceedings. ICRA '04.\n   * 2004 IEEE International Conference on , vol.4, no., pp.3993,3998 Vol.4,\n   * April 26-May 1, 2004\n   * doi: 10.1109/ROBOT.2004.1308895\n   */\n\n  // Compute the quaternion inner product\n  double lambda = (q1.transpose() * q2).value();\n  int q2_sign;\n  if (lambda < 0.0) {\n    // The quaternions are pointing in opposite directions, so use the equivalent alternative representation for q2\n    lambda = -lambda;\n    q2_sign = -1;\n  }\n  else {\n    q2_sign = 1;\n  }\n\n  // Calculate interpolation factors\n  // TODO: do we really want an epsilon so small?\n  double r, s;\n  if (std::abs(1.0 - lambda) < std::numeric_limits<double>::epsilon()) {\n    // The quaternions are nearly parallel, so use linear interpolation\n    r = 1.0 - interpolation_parameter;\n    s = interpolation_parameter;\n  }\n  else {\n    double alpha = std::acos(lambda);\n    double gamma = 1.0 / std::sin(alpha);\n    r = std::sin((1.0 - interpolation_parameter) * alpha) * gamma;\n    s = std::sin(interpolation_parameter * alpha) * gamma;\n  }\n\n  Vector4d ret = q1 * r;\n  ret += q2_sign * q2 * s;\n  return ret;\n}\n\nVector4d uniformlyRandomAxisAngle(std::default_random_engine& generator)\n{\n  std::normal_distribution<double> normal;\n  std::uniform_real_distribution<double> uniform(-M_PI, M_PI);\n  double angle = uniform(generator);\n  Vector3d axis = Vector3d(normal(generator), normal(generator), normal(generator));\n  axis.normalize();\n  Vector4d a;\n  a << axis, angle;\n  return a;\n}\n\nVector4d uniformlyRandomQuat(std::default_random_engine& generator)\n{\n  return axis2quat(uniformlyRandomAxisAngle(generator));\n}\n\nEigen::Matrix3d uniformlyRandomRotmat(std::default_random_engine& generator)\n{\n  return axis2rotmat(uniformlyRandomAxisAngle(generator));\n}\n\nEigen::Vector3d uniformlyRandomRPY(std::default_random_engine& generator)\n{\n  return axis2rpy(uniformlyRandomAxisAngle(generator));\n}\n\nDLLEXPORT int rotationRepresentationSize(int rotation_type)\n{\n  switch (rotation_type) {\n    case 0:\n      return 0;\n      break;\n    case 1:\n      return 3;\n      break;\n    case 2:\n      return 4;\n      break;\n    default:\n      throw std::runtime_error(\"rotation representation type not recognized\");\n  }\n}\n\nMatrix3d rotz(double theta) {\n  // returns 3D rotation matrix (about the z axis)\n  Matrix3d M;\n  double c=cos(theta);\n  double s=sin(theta);\n  M << c,-s, 0,\n      s, c, 0,\n      0, 0, 1;\n  return M;\n}\n\n\nvoid rotz(double theta, Matrix3d &M, Matrix3d &dM, Matrix3d &ddM)\n{\n  double c=cos(theta), s=sin(theta);\n  M << c,-s,0, s,c,0, 0,0,1;\n  dM << -s,-c,0, c,-s,0, 0,0,0;\n  ddM << -c,s,0, -s,-c,0, 0,0,0;\n}\n\nDLLEXPORT GradientVar<double,3,1> quat2expmap(const Ref<const Vector4d> &q, int gradient_order)\n{\n  double t = sqrt(1-q(0)*q(0));\n  bool is_degenerate=(t*t<std::numeric_limits<double>::epsilon());\n  double s = is_degenerate?2.0:2.0*acos(q(0))/t;\n  GradientVar<double,3,1> ret(3,1,4,gradient_order);\n  ret.value() = s*q.tail(3);\n  if(gradient_order>0)\n  {\n    ret.gradient().value() = Matrix<double,3,4>::Zero();\n    double dsdq1 = is_degenerate?0.0: (-2*t+2*acos(q(0))*q(0))/pow(t,3);\n    ret.gradient().value().col(0) = q.tail(3)*dsdq1;\n    ret.gradient().value().block(0,1,3,3) = Matrix3d::Identity()*s;\n  }\n  else if(gradient_order>1)\n  {\n    throw std::runtime_error(\"gradient_order>1 is not supported in quat2expmap\");\n  }\n  return ret;\n}\n\nDLLEXPORT GradientVar<double,3,1> flipExpmap(const Ref<const Vector3d> &expmap, int gradient_order)\n{\n  if(gradient_order>1)\n  {\n    throw std::runtime_error(\"gradient_order>1 is not supported in flipExpmap\");\n  }\n  double expmap_norm = expmap.norm();\n  bool is_degenerate=(expmap_norm<std::numeric_limits<double>::epsilon());\n  GradientVar<double,3,1> ret(3,1,3,gradient_order);\n  Matrix3d eye3 = Matrix3d::Identity();\n  if(is_degenerate)\n  {\n    ret.value() = expmap;\n    if(gradient_order>0)\n    {\n      ret.gradient().value() = eye3;\n    }\n  }\n  else\n  {\n    ret.value() = expmap-expmap/expmap_norm*2*M_PI;\n    if(gradient_order>0)\n    {\n      ret.gradient().value() = eye3-(expmap_norm*expmap_norm*eye3-expmap*expmap.transpose())/pow(expmap_norm,3)*2*M_PI;\n    }\n  }\n  return ret;\n}\n\nDLLEXPORT GradientVar<double, 3,1> unwrapExpmap(const Ref<const Vector3d> & expmap1, const Ref<const Vector3d> &expmap2, int gradient_order)\n{\n  auto expmap2_flip = flipExpmap(expmap2,gradient_order);\n  double distance1 = (expmap1-expmap2).squaredNorm();\n  double distance2 = (expmap1-expmap2_flip.value()).squaredNorm();\n  if(distance1>distance2)\n  {\n    return expmap2_flip;\n  }\n  else\n  {\n    GradientVar<double,3,1> ret(3,1,3,gradient_order);\n    ret.value() = expmap2;\n    if(gradient_order>0)\n    {\n      ret.gradient().value() = Matrix3d::Identity();\n    }\n    return ret;\n  }\n}\n\n\nvoid quat2expmapSequence(const Ref<const Matrix<double,4,Dynamic>> &quat, const Ref<const Matrix<double,4,Dynamic>> &quat_dot, Ref<Matrix<double,3,Dynamic>> expmap, Ref<Matrix<double,3,Dynamic>> expmap_dot)\n{\n  DenseIndex N = quat.cols();\n  if(quat_dot.cols() != N)\n  {\n    throw std::runtime_error(\"quat_dot must have the same number of columns as quat in quat2expmapSequence\");\n  }\n  expmap.resize(3,N);\n  expmap_dot.resize(3,N);\n  for(int i = 0;i<N;i++)\n  {\n    auto expmap_grad = quat2expmap(quat.col(i),1);\n    expmap.col(i) = expmap_grad.value();\n    expmap_dot.col(i) = expmap_grad.gradient().value()*quat_dot.col(i);\n    if(i>=1)\n    {\n      auto closest_grad = closestExpmap(expmap.col(i-1),expmap.col(i),1);\n      expmap.col(i) = closest_grad.value();\n      expmap_dot.col(i) = closest_grad.gradient().value()*expmap_dot.col(i);\n    }\n  }\n}\n\nDLLEXPORT GradientVar<double, 3,1> closestExpmap(const Ref<const Vector3d> & expmap1, const Ref<const Vector3d> &expmap2, int gradient_order)\n{\n  if (gradient_order>1) {\n    throw std::runtime_error(\"closestExpmap only supports first order gradient\");\n  }\n  double expmap1_norm = expmap1.norm();\n  double expmap2_norm = expmap2.norm();\n  GradientVar<double, 3, 1> ret(3,1,3,gradient_order);\n  if (expmap2_norm < std::numeric_limits<double>::epsilon()) {\n    if (expmap1_norm > std::numeric_limits<double>::epsilon()) {\n      Vector3d expmap1_axis = expmap1/expmap1_norm;\n      int expmap1_round = static_cast<int>(expmap1_norm/(2*M_PI) + 0.5);\n      ret.value() = expmap1_axis*expmap1_round*2*M_PI;\n      if(ret.hasGradient()) {\n        ret.gradient().value() = Matrix3d::Zero();\n      }\n      return ret;\n    }\n    else {\n      ret.value() = expmap2;\n      if (ret.hasGradient()) {\n        ret.gradient().value() = Matrix3d::Identity();\n      }\n    }\n  }\n  else {\n    Vector3d expmap2_axis = expmap2/expmap2_norm;\n    Matrix3d dexpmap2_axis_dexpmap2 = (expmap2_norm*Matrix3d::Identity() - expmap2*expmap2.transpose()/expmap2_norm)/pow(expmap2_norm,2);\n    double expmap2_closest_k = (expmap2_axis.transpose()*expmap1 - expmap2_norm)/(2*M_PI);\n    int expmap2_closest_k1;\n    int expmap2_closest_k2;\n    if (expmap2_closest_k>0) {\n      expmap2_closest_k1 = (int) expmap2_closest_k;\n    }\n    else {\n      expmap2_closest_k1 = (int) expmap2_closest_k - 1;\n    }\n    expmap2_closest_k2 = expmap2_closest_k1 + 1;\n    Vector3d expmap2_closest1 = expmap2 + 2*expmap2_closest_k1*M_PI*expmap2_axis;\n    Vector3d expmap2_closest2 = expmap2 + 2*expmap2_closest_k2*M_PI*expmap2_axis;\n    if ((expmap2_closest1 - expmap1).norm() < (expmap2_closest2 - expmap1).norm()) {\n      ret.value() = expmap2_closest1;\n      if (ret.hasGradient()) {\n        ret.gradient().value() = Matrix3d::Identity() + 2*dexpmap2_axis_dexpmap2*(double)expmap2_closest_k1*M_PI;\n      }\n      return ret;\n    }\n    else {\n      ret.value() = expmap2_closest2;\n      if (ret.hasGradient()) {\n        ret.gradient().value() = Matrix3d::Identity() + 2*dexpmap2_axis_dexpmap2*(double)expmap2_closest_k2*M_PI;\n      }\n      return ret;\n    }\n  }\n  return ret;\n}\n", "meta": {"hexsha": "3bb29a5151142df3fc6d76b904c6cf933d06cb7f", "size": 12190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "drake/util/drakeGeometryUtil.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/util/drakeGeometryUtil.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/util/drakeGeometryUtil.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": 30.2481389578, "max_line_length": 206, "alphanum_fraction": 0.6590648072, "num_tokens": 4155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5311254533190682}}
{"text": "/*!\n * @file\n * Forward declares the @ref Ring typeclass.\n *\n *\n * @copyright Louis Dionne 2014\n * Distributed under the Boost Software License, Version 1.0.\n *         (See accompanying file LICENSE.md or copy at\n *             http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_MPL11_FWD_RING_HPP\n#define BOOST_MPL11_FWD_RING_HPP\n\n#include <boost/mpl11/fwd/bool.hpp>\n\n\nnamespace boost { namespace mpl11 {\n    /*!\n     * @ingroup typeclasses\n     * @defgroup Ring Ring\n     *\n     * The `Ring` typeclass is used for `Group`s that also form a `Monoid`\n     * under a second binary operation that distributes over the first.\n     *\n     * Instances of `Ring` must satisfy the following laws:\n     *\n        @code\n            mult a (mult b c) == mult (mult a b) c\n\n            mult one a == a\n            mult a one == a\n\n            mult a (plus b c) == plus (mult a b) (mult a c)\n        @endcode\n     *\n     *\n     * ### Refines\n     * `Group`\n     *\n     * ### Methods\n     * `mult` and `one`\n     *\n     * ### Minimal complete definition\n     * All the methods.\n     *\n     * @{\n     */\n    template <typename Left, typename Right = Left, typename = true_>\n    struct Ring;\n\n    /*!\n     * `Ring` operation.\n     *\n     * `mult` can be invoked with more than two arguments. Specifically,\n     * `mult<x1, x2, xn...>` is equivalent to `mult<mult<x1, x2>, xn...>`.\n     */\n    template <typename x1, typename x2, typename ...xn>\n    struct mult;\n\n    //! Multiplicative identity for the given `Datatype`.\n    template <typename Datatype>\n    struct one;\n    //! @}\n}} // end namespace boost::mpl11\n\n#endif // !BOOST_MPL11_FWD_RING_HPP\n", "meta": {"hexsha": "f2fa140b6d2b1d87f3a3515b184b1fe8a6548312", "size": 1643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/mpl11/fwd/ring.hpp", "max_stars_repo_name": "ldionne/mpl11", "max_stars_repo_head_hexsha": "927d4339edc0c0cc41fb65ced2bf19d26bcd4a08", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T03:19:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T06:44:12.000Z", "max_issues_repo_path": "include/boost/mpl11/fwd/ring.hpp", "max_issues_repo_name": "rbock/mpl11", "max_issues_repo_head_hexsha": "7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-27T22:37:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-06T17:42:07.000Z", "max_forks_repo_path": "include/boost/mpl11/fwd/ring.hpp", "max_forks_repo_name": "rbock/mpl11", "max_forks_repo_head_hexsha": "7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T00:18:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T03:00:49.000Z", "avg_line_length": 24.1617647059, "max_line_length": 74, "alphanum_fraction": 0.5788192331, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135362, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5311254530654429}}
{"text": "#include <sstream>\n#include <boost/program_options.hpp>\n\n#include <frovedis/ml/fm/fm.hpp>\n#include <frovedis/matrix/crs_matrix.hpp>\n\nusing namespace boost;\nusing namespace frovedis;\nusing namespace std;\n\n\nint main(int argc, char* argv[]) {\n  use_frovedis use(argc, argv);\n\n  // debug option\n  set_loglevel(TRACE);\n\n  using namespace boost::program_options;\n    \n  vector<size_t> dims;\n  double init_stdev;\n  size_t iteration;\n  double init_learn_rate;\n  string optimizer_name;\n  string input_path, label_path, output_path;\n  vector<double> regulars;\n  string task;\n  size_t batch_size_pernode;\n  bool binary_input;\n\n  options_description opt(\"option\");\n  opt.add_options()\n    (\"dim\", value<vector<size_t>>(&dims)->multitoken()->zero_tokens()->default_value({1,1,8}, \"'1 1 8'\"), \n     \"k0 k1 k2: k0=use bias, k1=use 1-way interactions, k2=dim of 2-way interactions\")\n    (\"help,h\", \"print help\")\n    (\"init-stdev\", value<double>(&init_stdev)->default_value(0.1, \"0.1\"), \n     \"stdev of initialization of 2-way factors\")\n    (\"iter\", value<size_t>(&iteration)->default_value(100, \"100\"), \"number of iteration\")\n    (\"learn-rate\", value<double>(&init_learn_rate)->default_value(0.1, \"0.1\"), \n     \"learning rate for SGD; dafault=0.1\")\n    (\"method\", value<string>(&optimizer_name)->default_value(\"SGD\"),\n     \"learning method in SGD, SGDA, ALS, MCMC\")\n    (\"input,i\", value<string>(&input_path)->required(), \"filename for training data, crs matrix format\")\n    (\"label,l\", value<string>(&label_path)->required(), \"filename for training label, dvector format\")\n    (\"output,o\", value<string>(&output_path)->required(), \"filename for output model\")\n    (\"regular\", value<vector<double>>(&regulars)->multitoken()->default_value(vector<double>{0.,0.,0.}, \"'0 0 0'\"), \n     \"r0,r1,r2 for SGD or ALS: r0=bias reg., r1=1-way reg., r2=2-way reg.\")\n    (\"task,t\", value<string>(&task)->default_value(\"r\"), \"r=regression, c=classification\")\n    (\"batchsize,s\", value<size_t>(&batch_size_pernode)->default_value(5000, \"5000\"),\n     \"minibatch size per node\")\n    (\"binary\", bool_switch(&binary_input)->default_value(false, \"false\"),\n     \"use binary input file\")\n    ;\n\n  variables_map argmap;\n  store(command_line_parser(argc,argv).options(opt).allow_unregistered().run(), argmap);\n  if(argmap.count(\"help\")){\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  notify(argmap);\n\n  if (dims.size() != 3)  throw runtime_error(\"--dim is required to have 3 values.\");\n  bool dim_0 = dims[0];\n  bool dim_1 = dims[1];\n  size_t dim_2 = dims[2];\n  \n  fm::FmOptimizer optimizer;\n  if (optimizer_name == \"SGD\") {\n    optimizer = FmOptimizer::SGD;\n  } else if (optimizer_name == \"SGDA\") {\n    optimizer = FmOptimizer::SGDA;\n  } else if (optimizer_name == \"ALS\") {\n    optimizer = FmOptimizer::ALS;\n  } else if (optimizer_name == \"MCMC\") {\n    optimizer = FmOptimizer::MCMC;\n  } else {\n    throw runtime_error(\"optimizer specified by -method is not supported.\");\n  }\n  \n  if (regulars.size() != 3)  throw runtime_error(\"--regular is required to have 3 values.\");\n  double regular_0 = regulars[0];\n  double regular_1 = regulars[1];\n  double regular_2 = regulars[2];\n  \n  bool is_regression;\n  if (task == \"r\") {\n    is_regression = true;\n  } else if (task == \"c\") {\n    is_regression = false;\n  } else {\n    throw runtime_error(\"-task is required to be 'r' or 'c'.\");\n  }\n\n  crs_matrix<double> nl_data;\n  if (binary_input) {\n    nl_data = make_crs_matrix_loadbinary<double>(input_path);\n  } else {\n    nl_data = make_crs_matrix_load<double>(input_path);\n  }\n  \n  dvector<double> dv_label;\n  if (binary_input) {\n    dv_label = make_dvector_loadbinary<double>(label_path);\n  } else {\n    dv_label = make_dvector_loadline<double>(label_path);\n  }\n\n  auto model = fm_train(dim_0, dim_1, dim_2, \n        init_stdev, iteration, init_learn_rate, optimizer,\n        regular_0, regular_1, regular_2, is_regression,\n        nl_data, dv_label, batch_size_pernode); \n        \n  model.save(output_path);\n  return 0;\n}\n", "meta": {"hexsha": "72be517523b2e433f5606a182696666d9a22f4e4", "size": 3973, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/factorization_machine/train_fm.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": "samples/factorization_machine/train_fm.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": "samples/factorization_machine/train_fm.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": 33.6694915254, "max_line_length": 116, "alphanum_fraction": 0.6687641581, "num_tokens": 1130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.5311254250640219}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\n#include \"LSLOpt/BFGS.hpp\"\n#include \"ModelSystem.hpp\"\n\n\nint main(int argc, char* argv[])\n{\n  ModelSystem modelSystem;\n\n  // start with gamma = 67.5 deg\n  Eigen::VectorXd x0 = Eigen::VectorXd::Constant(1, 3*M_PI/8);\n\n  LSLOpt::OptimizationParameters<double> params\n      = LSLOpt::getOptimizationParameters<double>();\n  LSLOpt::OstreamOutput output{LSLOpt::OutputLevel::Status, std::cout};\n\n  auto result = LSLOpt::lsl_bfgs(modelSystem, x0, params, output);\n\n  // access the optimal parameters\n  std::cout << \"gamma: \" << result.x[0] << std::endl;\n  // access the final function value\n  std::cout << \"score: \" << result.function_value << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "d1258d49a37cf157c5573eda2da3e9fc0b638cd0", "size": 707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PaperExamples/PaperExample.cpp", "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/PaperExample.cpp", "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/PaperExample.cpp", "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": 25.25, "max_line_length": 71, "alphanum_fraction": 0.6888260255, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5311254193622872}}
{"text": "#include <bitset>\n#include <sstream>\n#include <string>\n#include <thread>\n#include <boost/beast/core.hpp>\n#include <boost/beast/websocket.hpp>\n#include <boost/asio/ip/tcp.hpp>\n#include <math_nerd/hill_cipher.h>\n\n#include \"file_handler.h\"\n\nnamespace beast = boost::beast;\nnamespace http = beast::http;\nnamespace websocket = beast::websocket;\nnamespace net = boost::asio;\nnamespace mod = math_nerd::int_mod;\nnamespace matrix = math_nerd::matrix_t;\nnamespace hc = math_nerd::hill_cipher;\n\nusing tcp = net::ip::tcp;\n\nauto operator<<(std::ostream &os, hc::hill_key key)->std::ostream &;\n\nauto do_session(tcp::socket socket) -> void\n{\n    websocket::stream<tcp::socket> ws{ std::move(socket) };\n\n    ws.set_option(websocket::stream_base::decorator(\n        [](websocket::response_type &res)\n        {\n            res.set(http::field::server,\n                \"Hill Cipher\");\n        }));\n\n    ws.accept();\n\n    auto key_size{ 5 };\n    std::unique_ptr<hc::hill_key> key{ new hc::hill_key{ key_size } };\n\n    while( true )\n    {\n        beast::flat_buffer input;\n\n        ws.read(input);\n\n        auto cmd{ beast::buffers_to_string(input.data()) };\n\n        std::bitset<3> cmd_type{ 0x0 };\n\n        enum command\n        {\n            generate_key,\n            encrypt,\n            decrypt\n        };\n\n        std::string output;\n        output.resize(100);\n        output = \"Error.\";\n\n        switch( cmd[0] )\n        {\n            case 'g':\n            {\n                if( cmd[1] >= '0' && cmd[1] <= '9' )\n                {\n                    key_size = std::max(cmd[1] - '0', 2);\n                    cmd_type[command::generate_key] = true;\n                }\n            }\n            break;\n\n            case 'e':\n            {\n                cmd_type[command::encrypt] = true;\n                cmd.erase(0, 1);\n            }\n            break;\n\n            case 'd':\n            {\n                cmd_type[command::decrypt] = true;\n                cmd.erase(0, 1);\n            }\n            break;\n\n            default:\n            {\n                // Empty.\n            }\n        }\n\n        if( cmd_type[command::generate_key] )\n        {\n            if( key_size != key->row_count() )\n            {\n                key.reset(new hc::hill_key{ key_size });\n            }\n\n            output = \"g\" + std::to_string(key_size);\n\n            // Create our (not cryptographically secure) PRNG.\n            std::random_device device;\n            std::mt19937 rng(device());\n\n            // Key distribution.\n            std::uniform_int_distribution<int> key_dist(0, 96);\n\n            // Index distribution for fixing invalid keys.\n            std::uniform_int_distribution<int> idx_dist(0, key_size);\n\n            for( auto i{ 0 }; i < key_size; ++i )\n            {\n                for( auto j{ 0 }; j < key_size; ++j )\n                {\n                    // Create (not cryptographically secure) random elements.\n                    (*key)[i][j] = key_dist(rng);\n                }\n            }\n\n            while( not hc::is_valid_key((*key)) )\n            {   // Randomly touch parts of the key to attempt to fix.\n                (*key)[idx_dist(rng)][idx_dist(rng)] += key_dist(rng);\n            }\n\n            std::stringstream os;\n\n            os << (*key);\n\n            output += os.str();\n        }\n        else if( cmd_type[command::encrypt] )\n        {\n            output = \"e\" + hc::encrypt((*key), cmd);\n        }\n        else if( cmd_type[command::decrypt] )\n        {\n            output = \"d\" + hc::decrypt((*key), cmd);\n        }\n\n        beast::multi_buffer buffer;\n        auto msg = net::buffer_copy(buffer.prepare(output.size()), net::buffer(output));\n        buffer.commit(msg);\n\n        ws.text(ws.got_text());\n        ws.write(buffer.data());\n    }\n}\n\nauto main() -> int\ntry\n{\n    auto const address{ net::ip::make_address(\"127.0.0.1\") };\n    auto const port{ static_cast<std::uint16_t>(31337) };\n\n    file_handler file;\n\n    net::io_context ioc{ 1 };\n\n    tcp::acceptor acceptor{ ioc, {address, port} };\n\n    tcp::socket socket{ ioc };\n\n    acceptor.accept(socket);\n\n    do_session(std::move(socket));\n\n    return EXIT_SUCCESS;\n}\ncatch( std::exception const &e )\n{\n    if( std::string(e.what()) == \"The WebSocket stream was gracefully closed at both endpoints\" )\n    {\n        return EXIT_SUCCESS;\n    }\n\n    std::cerr << e.what() << std::endl;\n    return EXIT_FAILURE;\n}\n\nauto operator<<(std::ostream &os, hc::hill_key key) -> std::ostream &\n{\n    // Starting bracket for key.\n    os << \"[\";\n\n    for( auto i{ 0 }; i < key.row_count(); ++i )\n    {\n        for( auto j{ 0 }; j < key.column_count(); ++j )\n        {\n            // Print element.\n            os << key[i][j];\n\n            if( j != key.column_count() - 1 )\n            {\n                // Delimit with comma.\n                os << \",\";\n            }\n        }\n\n        if( i != key.row_count() - 1 )\n        {   // Delimit row with semicolon.\n            os << \";\";\n        }\n    }\n\n    // Ending bracket for key.\n    os << \"]\";\n\n    return os;\n}\n", "meta": {"hexsha": "def46877309b8d2471fae2a6bf473936da9696c5", "size": 5030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hill.cpp", "max_stars_repo_name": "JacobSzepsy/Hill-Cipher-Webpage", "max_stars_repo_head_hexsha": "7fb9c7af9fd90af993de992fb0d5f556ecdc6b71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hill.cpp", "max_issues_repo_name": "JacobSzepsy/Hill-Cipher-Webpage", "max_issues_repo_head_hexsha": "7fb9c7af9fd90af993de992fb0d5f556ecdc6b71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hill.cpp", "max_forks_repo_name": "JacobSzepsy/Hill-Cipher-Webpage", "max_forks_repo_head_hexsha": "7fb9c7af9fd90af993de992fb0d5f556ecdc6b71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-18T21:27:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-18T21:27:10.000Z", "avg_line_length": 23.8388625592, "max_line_length": 97, "alphanum_fraction": 0.4876739563, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.5311229841767758}}
{"text": "//  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// Basic sanity check that header\n// #includes all the files that it needs to.\n//\n#include <boost/math/tools/engel_expansion.hpp>\n//\n// Note this header includes no other headers, this is\n// important if this test is to be meaningful:\n//\n#include \"test_compile_result.hpp\"\n\nvoid compile_and_link_test()\n{\n    boost::math::tools::engel_expansion<float> f_test(1.0f);\n    check_result<int64_t>(f_test.digits().front());\n\n    boost::math::tools::engel_expansion<double> d_test(1.0);\n    check_result<int64_t>(d_test.digits().front());\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    boost::math::tools::engel_expansion<long double> ld_test(1.0l);\n    check_result<int64_t>(ld_test.digits().front());\n#endif\n}\n", "meta": {"hexsha": "0a391eba03c9c33c320b807add8982fc45e28324", "size": 939, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/tools_engel_expansion_incl_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/compile_test/tools_engel_expansion_incl_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/compile_test/tools_engel_expansion_incl_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": 32.3793103448, "max_line_length": 68, "alphanum_fraction": 0.7358892439, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5311219267411178}}
{"text": "/* boost random/detail/const_mod.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$\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_CONST_MOD_HPP\n#define BOOST_RANDOM_CONST_MOD_HPP\n\n#include <boost/assert.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/integer_traits.hpp>\n#include <boost/type_traits/make_unsigned.hpp>\n#include <boost/random/detail/large_arithmetic.hpp>\n\n#include <boost/random/detail/disable_warnings.hpp>\n\nnamespace lslboost {\nnamespace random {\n\ntemplate<class IntType, IntType m>\nclass const_mod\n{\npublic:\n  static IntType apply(IntType x)\n  {\n    if(((unsigned_m() - 1) & unsigned_m()) == 0)\n      return (unsigned_type(x)) & (unsigned_m() - 1);\n    else {\n      IntType suppress_warnings = (m == 0);\n      BOOST_ASSERT(suppress_warnings == 0);\n      return x % (m + suppress_warnings);\n    }\n  }\n\n  static IntType add(IntType x, IntType c)\n  {\n    if(((unsigned_m() - 1) & unsigned_m()) == 0)\n      return (unsigned_type(x) + unsigned_type(c)) & (unsigned_m() - 1);\n    else if(c == 0)\n      return x;\n    else if(x < m - c)\n      return x + c;\n    else\n      return x - (m - c);\n  }\n\n  static IntType mult(IntType a, IntType x)\n  {\n    if(((unsigned_m() - 1) & unsigned_m()) == 0)\n      return unsigned_type(a) * unsigned_type(x) & (unsigned_m() - 1);\n    else if(a == 0)\n      return 0;\n    else if(a == 1)\n      return x;\n    else if(m <= traits::const_max/a)      // i.e. a*m <= max\n      return mult_small(a, x);\n    else if(traits::is_signed && (m%a < m/a))\n      return mult_schrage(a, x);\n    else\n      return mult_general(a, x);\n  }\n\n  static IntType mult_add(IntType a, IntType x, IntType c)\n  {\n    if(((unsigned_m() - 1) & unsigned_m()) == 0)\n      return (unsigned_type(a) * unsigned_type(x) + unsigned_type(c)) & (unsigned_m() - 1);\n    else if(a == 0)\n      return c;\n    else if(m <= (traits::const_max-c)/a) {  // i.e. a*m+c <= max\n      IntType suppress_warnings = (m == 0);\n      BOOST_ASSERT(suppress_warnings == 0);\n      return (a*x+c) % (m + suppress_warnings);\n    } else\n      return add(mult(a, x), c);\n  }\n\n  static IntType pow(IntType a, lslboost::uintmax_t exponent)\n  {\n      IntType result = 1;\n      while(exponent != 0) {\n          if(exponent % 2 == 1) {\n              result = mult(result, a);\n          }\n          a = mult(a, a);\n          exponent /= 2;\n      }\n      return result;\n  }\n\n  static IntType invert(IntType x)\n  { return x == 0 ? 0 : (m == 0? invert_euclidian0(x) : invert_euclidian(x)); }\n\nprivate:\n  typedef integer_traits<IntType> traits;\n  typedef typename make_unsigned<IntType>::type unsigned_type;\n\n  const_mod();      // don't instantiate\n\n  static IntType mult_small(IntType a, IntType x)\n  {\n    IntType suppress_warnings = (m == 0);\n    BOOST_ASSERT(suppress_warnings == 0);\n    return a*x % (m + suppress_warnings);\n  }\n\n  static IntType mult_schrage(IntType a, IntType value)\n  {\n    const IntType q = m / a;\n    const IntType r = m % a;\n\n    BOOST_ASSERT(r < q);        // check that overflow cannot happen\n\n    return sub(a*(value%q), r*(value/q));\n  }\n\n  static IntType mult_general(IntType a, IntType b)\n  {\n    IntType suppress_warnings = (m == 0);\n    BOOST_ASSERT(suppress_warnings == 0);\n    IntType modulus = m + suppress_warnings;\n    BOOST_ASSERT(modulus == m);\n    if(::lslboost::uintmax_t(modulus) <=\n        (::std::numeric_limits< ::lslboost::uintmax_t>::max)() / modulus)\n    {\n      return static_cast<IntType>(lslboost::uintmax_t(a) * b % modulus);\n    } else {\n      return static_cast<IntType>(detail::mulmod(a, b, modulus));\n    }\n  }\n\n  static IntType sub(IntType a, IntType b)\n  {\n    if(a < b)\n      return m - (b - a);\n    else\n      return a - b;\n  }\n\n  static unsigned_type unsigned_m()\n  {\n      if(m == 0) {\n          return unsigned_type((std::numeric_limits<IntType>::max)()) + 1;\n      } else {\n          return unsigned_type(m);\n      }\n  }\n\n  // invert c in the finite field (mod m) (m must be prime)\n  static IntType invert_euclidian(IntType c)\n  {\n    // we are interested in the gcd factor for c, because this is our inverse\n    BOOST_ASSERT(c > 0);\n    IntType l1 = 0;\n    IntType l2 = 1;\n    IntType n = c;\n    IntType p = m;\n    for(;;) {\n      IntType q = p / n;\n      l1 += q * l2;\n      p -= q * n;\n      if(p == 0)\n        return l2;\n      IntType q2 = n / p;\n      l2 += q2 * l1;\n      n -= q2 * p;\n      if(n == 0)\n        return m - l1;\n    }\n  }\n\n  // invert c in the finite field (mod m) (c must be relatively prime to m)\n  static IntType invert_euclidian0(IntType c)\n  {\n    // we are interested in the gcd factor for c, because this is our inverse\n    BOOST_ASSERT(c > 0);\n    if(c == 1) return 1;\n    IntType l1 = 0;\n    IntType l2 = 1;\n    IntType n = c;\n    IntType p = m;\n    IntType max = (std::numeric_limits<IntType>::max)();\n    IntType q = max / n;\n    BOOST_ASSERT(max % n != n - 1 && \"c must be relatively prime to m.\");\n    l1 += q * l2;\n    p = max - q * n + 1;\n    for(;;) {\n      if(p == 0)\n        return l2;\n      IntType q2 = n / p;\n      l2 += q2 * l1;\n      n -= q2 * p;\n      if(n == 0)\n        return m - l1;\n      q = p / n;\n      l1 += q * l2;\n      p -= q * n;\n    }\n  }\n};\n\n} // namespace random\n} // namespace lslboost\n\n#include <boost/random/detail/enable_warnings.hpp>\n\n#endif // BOOST_RANDOM_CONST_MOD_HPP\n", "meta": {"hexsha": "db24a90d7ac648c31ea0e79e8c45c00a47eada4f", "size": 5584, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lslboost/boost/random/detail/const_mod.hpp", "max_stars_repo_name": "samuelpowell/liblsl", "max_stars_repo_head_hexsha": "92f0e2f4870cd9b505cd35c89f70c7a9d3b191a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-19T00:57:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T23:24:51.000Z", "max_issues_repo_path": "lslboost/boost/random/detail/const_mod.hpp", "max_issues_repo_name": "samuelpowell/liblsl", "max_issues_repo_head_hexsha": "92f0e2f4870cd9b505cd35c89f70c7a9d3b191a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lslboost/boost/random/detail/const_mod.hpp", "max_forks_repo_name": "samuelpowell/liblsl", "max_forks_repo_head_hexsha": "92f0e2f4870cd9b505cd35c89f70c7a9d3b191a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-19T23:31:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T23:31:13.000Z", "avg_line_length": 25.732718894, "max_line_length": 91, "alphanum_fraction": 0.5868553009, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5311219150561449}}
{"text": "// Copyright (c) 2018 by University Paris-Est Marne-la-Vallee\n// InnerExplicit.hpp\n// This file is part of the Garamon for c3ga.\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 InnerExplicit.hpp\n/// \\author Stephane Breuils, Vincent Nozick\n/// \\brief Explicit precomputed per grades inner products of c3ga.\n\n#ifndef C3GA_INNER_PRODUCT_EXPLICIT_HPP__\n#define C3GA_INNER_PRODUCT_EXPLICIT_HPP__\n#pragma once\n\n#include <Eigen/Core>\n\n#include \"c3ga/Mvec.hpp\"\n#include \"c3ga/Inner.hpp\"\n#include \"c3ga/Constants.hpp\"\n\n\n/*!\n * @namespace c3ga\n */\nnamespace c3ga {\n    template<typename T> class Mvec;\n\n    /// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0\n\ttemplate<typename T>\n\tvoid inner_0_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 1). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_0_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1.coeff(0)*mv2;\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 2). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid inner_0_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1.coeff(0)*mv2;\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 3). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3\n\ttemplate<typename T>\n\tvoid inner_0_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1.coeff(0)*mv2;\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 4). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 4 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 4\n\ttemplate<typename T>\n\tvoid inner_0_4(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1.coeff(0)*mv2;\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 5). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 5 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 5\n\ttemplate<typename T>\n\tvoid inner_0_5(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1.coeff(0)*mv2;\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_1_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 1). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0\n\ttemplate<typename T>\n\tvoid inner_1_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(4) + mv1.coeff(1)*mv2.coeff(1) + mv1.coeff(2)*mv2.coeff(2) + mv1.coeff(3)*mv2.coeff(3) - mv1.coeff(4)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 2). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_1_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(3) - mv1.coeff(1)*mv2.coeff(0) - mv1.coeff(2)*mv2.coeff(1) - mv1.coeff(3)*mv2.coeff(2);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(0)*mv2.coeff(6) - mv1.coeff(2)*mv2.coeff(4) - mv1.coeff(3)*mv2.coeff(5) - mv1.coeff(4)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(0)*mv2.coeff(8) + mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(3)*mv2.coeff(7) - mv1.coeff(4)*mv2.coeff(1);\n\t\tmv3.coeffRef(3) +=  mv1.coeff(0)*mv2.coeff(9) + mv1.coeff(1)*mv2.coeff(5) + mv1.coeff(2)*mv2.coeff(7) - mv1.coeff(4)*mv2.coeff(2);\n\t\tmv3.coeffRef(4) +=  mv1.coeff(1)*mv2.coeff(6) + mv1.coeff(2)*mv2.coeff(8) + mv1.coeff(3)*mv2.coeff(9) - mv1.coeff(4)*mv2.coeff(3);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 3). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid inner_1_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(2) + mv1.coeff(2)*mv2.coeff(0) + mv1.coeff(3)*mv2.coeff(1);\n\t\tmv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(4) - mv1.coeff(1)*mv2.coeff(0) + mv1.coeff(3)*mv2.coeff(3);\n\t\tmv3.coeffRef(2) += -mv1.coeff(0)*mv2.coeff(5) - mv1.coeff(1)*mv2.coeff(1) - mv1.coeff(2)*mv2.coeff(3);\n\t\tmv3.coeffRef(3) += -mv1.coeff(1)*mv2.coeff(2) - mv1.coeff(2)*mv2.coeff(4) - mv1.coeff(3)*mv2.coeff(5);\n\t\tmv3.coeffRef(4) += -mv1.coeff(0)*mv2.coeff(7) + mv1.coeff(3)*mv2.coeff(6) - mv1.coeff(4)*mv2.coeff(0);\n\t\tmv3.coeffRef(5) += -mv1.coeff(0)*mv2.coeff(8) - mv1.coeff(2)*mv2.coeff(6) - mv1.coeff(4)*mv2.coeff(1);\n\t\tmv3.coeffRef(6) += -mv1.coeff(2)*mv2.coeff(7) - mv1.coeff(3)*mv2.coeff(8) - mv1.coeff(4)*mv2.coeff(2);\n\t\tmv3.coeffRef(7) += -mv1.coeff(0)*mv2.coeff(9) + mv1.coeff(1)*mv2.coeff(6) - mv1.coeff(4)*mv2.coeff(3);\n\t\tmv3.coeffRef(8) +=  mv1.coeff(1)*mv2.coeff(7) - mv1.coeff(3)*mv2.coeff(9) - mv1.coeff(4)*mv2.coeff(4);\n\t\tmv3.coeffRef(9) +=  mv1.coeff(1)*mv2.coeff(8) + mv1.coeff(2)*mv2.coeff(9) - mv1.coeff(4)*mv2.coeff(5);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 4). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 4 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3\n\ttemplate<typename T>\n\tvoid inner_1_4(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(1) - mv1.coeff(3)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(0)*mv2.coeff(2) + mv1.coeff(2)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(2)*mv2.coeff(1) + mv1.coeff(3)*mv2.coeff(2);\n\t\tmv3.coeffRef(3) +=  mv1.coeff(0)*mv2.coeff(3) - mv1.coeff(1)*mv2.coeff(0);\n\t\tmv3.coeffRef(4) += -mv1.coeff(1)*mv2.coeff(1) + mv1.coeff(3)*mv2.coeff(3);\n\t\tmv3.coeffRef(5) += -mv1.coeff(1)*mv2.coeff(2) - mv1.coeff(2)*mv2.coeff(3);\n\t\tmv3.coeffRef(6) +=  mv1.coeff(0)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(0);\n\t\tmv3.coeffRef(7) +=  mv1.coeff(3)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(1);\n\t\tmv3.coeffRef(8) += -mv1.coeff(2)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(2);\n\t\tmv3.coeffRef(9) +=  mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(3);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 5). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 5 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 4\n\ttemplate<typename T>\n\tvoid inner_1_5(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) += -mv1.coeff(3)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(2)*mv2.coeff(0);\n\t\tmv3.coeffRef(3) += -mv1.coeff(1)*mv2.coeff(0);\n\t\tmv3.coeffRef(4) += -mv1.coeff(4)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid inner_2_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 1). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_2_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(1) + mv1.coeff(1)*mv2.coeff(2) + mv1.coeff(2)*mv2.coeff(3) - mv1.coeff(3)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(0)*mv2.coeff(4) + mv1.coeff(4)*mv2.coeff(2) + mv1.coeff(5)*mv2.coeff(3) - mv1.coeff(6)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(1) + mv1.coeff(7)*mv2.coeff(3) - mv1.coeff(8)*mv2.coeff(0);\n\t\tmv3.coeffRef(3) +=  mv1.coeff(2)*mv2.coeff(4) - mv1.coeff(5)*mv2.coeff(1) - mv1.coeff(7)*mv2.coeff(2) - mv1.coeff(9)*mv2.coeff(0);\n\t\tmv3.coeffRef(4) +=  mv1.coeff(3)*mv2.coeff(4) - mv1.coeff(6)*mv2.coeff(1) - mv1.coeff(8)*mv2.coeff(2) - mv1.coeff(9)*mv2.coeff(3);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 2). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0\n\ttemplate<typename T>\n\tvoid inner_2_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(6) - mv1.coeff(1)*mv2.coeff(8) - mv1.coeff(2)*mv2.coeff(9) + mv1.coeff(3)*mv2.coeff(3) - mv1.coeff(4)*mv2.coeff(4) - mv1.coeff(5)*mv2.coeff(5) - mv1.coeff(6)*mv2.coeff(0) - mv1.coeff(7)*mv2.coeff(7) - mv1.coeff(8)*mv2.coeff(1) - mv1.coeff(9)*mv2.coeff(2);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 3). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_2_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(2) - mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(2)*mv2.coeff(5) - mv1.coeff(4)*mv2.coeff(0) - mv1.coeff(5)*mv2.coeff(1) - mv1.coeff(7)*mv2.coeff(3);\n\t\tmv3.coeffRef(1) += -mv1.coeff(1)*mv2.coeff(7) - mv1.coeff(2)*mv2.coeff(8) - mv1.coeff(3)*mv2.coeff(2) - mv1.coeff(7)*mv2.coeff(6) + mv1.coeff(8)*mv2.coeff(0) + mv1.coeff(9)*mv2.coeff(1);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(0)*mv2.coeff(7) - mv1.coeff(2)*mv2.coeff(9) - mv1.coeff(3)*mv2.coeff(4) + mv1.coeff(5)*mv2.coeff(6) - mv1.coeff(6)*mv2.coeff(0) + mv1.coeff(9)*mv2.coeff(3);\n\t\tmv3.coeffRef(3) +=  mv1.coeff(0)*mv2.coeff(8) + mv1.coeff(1)*mv2.coeff(9) - mv1.coeff(3)*mv2.coeff(5) - mv1.coeff(4)*mv2.coeff(6) - mv1.coeff(6)*mv2.coeff(1) - mv1.coeff(8)*mv2.coeff(3);\n\t\tmv3.coeffRef(4) += -mv1.coeff(4)*mv2.coeff(7) - mv1.coeff(5)*mv2.coeff(8) - mv1.coeff(6)*mv2.coeff(2) - mv1.coeff(7)*mv2.coeff(9) - mv1.coeff(8)*mv2.coeff(4) - mv1.coeff(9)*mv2.coeff(5);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 4). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 4 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid inner_2_4(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(1)*mv2.coeff(1) - mv1.coeff(2)*mv2.coeff(2) - mv1.coeff(7)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(0)*mv2.coeff(1) - mv1.coeff(2)*mv2.coeff(3) + mv1.coeff(5)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(0)*mv2.coeff(2) + mv1.coeff(1)*mv2.coeff(3) - mv1.coeff(4)*mv2.coeff(0);\n\t\tmv3.coeffRef(3) += -mv1.coeff(4)*mv2.coeff(1) - mv1.coeff(5)*mv2.coeff(2) - mv1.coeff(7)*mv2.coeff(3);\n\t\tmv3.coeffRef(4) += -mv1.coeff(2)*mv2.coeff(4) + mv1.coeff(3)*mv2.coeff(1) - mv1.coeff(9)*mv2.coeff(0);\n\t\tmv3.coeffRef(5) +=  mv1.coeff(1)*mv2.coeff(4) + mv1.coeff(3)*mv2.coeff(2) + mv1.coeff(8)*mv2.coeff(0);\n\t\tmv3.coeffRef(6) += -mv1.coeff(7)*mv2.coeff(4) + mv1.coeff(8)*mv2.coeff(1) + mv1.coeff(9)*mv2.coeff(2);\n\t\tmv3.coeffRef(7) += -mv1.coeff(0)*mv2.coeff(4) + mv1.coeff(3)*mv2.coeff(3) - mv1.coeff(6)*mv2.coeff(0);\n\t\tmv3.coeffRef(8) +=  mv1.coeff(5)*mv2.coeff(4) - mv1.coeff(6)*mv2.coeff(1) + mv1.coeff(9)*mv2.coeff(3);\n\t\tmv3.coeffRef(9) += -mv1.coeff(4)*mv2.coeff(4) - mv1.coeff(6)*mv2.coeff(2) - mv1.coeff(8)*mv2.coeff(3);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 5). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 5 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3\n\ttemplate<typename T>\n\tvoid inner_2_5(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(2)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(1)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) += -mv1.coeff(7)*mv2.coeff(0);\n\t\tmv3.coeffRef(3) += -mv1.coeff(0)*mv2.coeff(0);\n\t\tmv3.coeffRef(4) +=  mv1.coeff(5)*mv2.coeff(0);\n\t\tmv3.coeffRef(5) += -mv1.coeff(4)*mv2.coeff(0);\n\t\tmv3.coeffRef(6) += -mv1.coeff(3)*mv2.coeff(0);\n\t\tmv3.coeffRef(7) += -mv1.coeff(9)*mv2.coeff(0);\n\t\tmv3.coeffRef(8) +=  mv1.coeff(8)*mv2.coeff(0);\n\t\tmv3.coeffRef(9) += -mv1.coeff(6)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3\n\ttemplate<typename T>\n\tvoid inner_3_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 1). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid inner_3_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(2) + mv1.coeff(1)*mv2.coeff(3) - mv1.coeff(2)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(1) + mv1.coeff(3)*mv2.coeff(3) - mv1.coeff(4)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) += -mv1.coeff(1)*mv2.coeff(1) - mv1.coeff(3)*mv2.coeff(2) - mv1.coeff(5)*mv2.coeff(0);\n\t\tmv3.coeffRef(3) += -mv1.coeff(2)*mv2.coeff(1) - mv1.coeff(4)*mv2.coeff(2) - mv1.coeff(5)*mv2.coeff(3);\n\t\tmv3.coeffRef(4) += -mv1.coeff(0)*mv2.coeff(4) + mv1.coeff(6)*mv2.coeff(3) - mv1.coeff(7)*mv2.coeff(0);\n\t\tmv3.coeffRef(5) += -mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(6)*mv2.coeff(2) - mv1.coeff(8)*mv2.coeff(0);\n\t\tmv3.coeffRef(6) += -mv1.coeff(2)*mv2.coeff(4) - mv1.coeff(7)*mv2.coeff(2) - mv1.coeff(8)*mv2.coeff(3);\n\t\tmv3.coeffRef(7) += -mv1.coeff(3)*mv2.coeff(4) + mv1.coeff(6)*mv2.coeff(1) - mv1.coeff(9)*mv2.coeff(0);\n\t\tmv3.coeffRef(8) += -mv1.coeff(4)*mv2.coeff(4) + mv1.coeff(7)*mv2.coeff(1) - mv1.coeff(9)*mv2.coeff(3);\n\t\tmv3.coeffRef(9) += -mv1.coeff(5)*mv2.coeff(4) + mv1.coeff(8)*mv2.coeff(1) + mv1.coeff(9)*mv2.coeff(2);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 2). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_3_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(4) - mv1.coeff(1)*mv2.coeff(5) - mv1.coeff(2)*mv2.coeff(0) - mv1.coeff(3)*mv2.coeff(7) - mv1.coeff(4)*mv2.coeff(1) - mv1.coeff(5)*mv2.coeff(2);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(0)*mv2.coeff(8) + mv1.coeff(1)*mv2.coeff(9) - mv1.coeff(2)*mv2.coeff(3) - mv1.coeff(6)*mv2.coeff(7) - mv1.coeff(7)*mv2.coeff(1) - mv1.coeff(8)*mv2.coeff(2);\n\t\tmv3.coeffRef(2) += -mv1.coeff(0)*mv2.coeff(6) + mv1.coeff(3)*mv2.coeff(9) - mv1.coeff(4)*mv2.coeff(3) + mv1.coeff(6)*mv2.coeff(5) + mv1.coeff(7)*mv2.coeff(0) - mv1.coeff(9)*mv2.coeff(2);\n\t\tmv3.coeffRef(3) += -mv1.coeff(1)*mv2.coeff(6) - mv1.coeff(3)*mv2.coeff(8) - mv1.coeff(5)*mv2.coeff(3) - mv1.coeff(6)*mv2.coeff(4) + mv1.coeff(8)*mv2.coeff(0) + mv1.coeff(9)*mv2.coeff(1);\n\t\tmv3.coeffRef(4) += -mv1.coeff(2)*mv2.coeff(6) - mv1.coeff(4)*mv2.coeff(8) - mv1.coeff(5)*mv2.coeff(9) - mv1.coeff(7)*mv2.coeff(4) - mv1.coeff(8)*mv2.coeff(5) - mv1.coeff(9)*mv2.coeff(7);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 3). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0\n\ttemplate<typename T>\n\tvoid inner_3_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(7) + mv1.coeff(1)*mv2.coeff(8) + mv1.coeff(2)*mv2.coeff(2) + mv1.coeff(3)*mv2.coeff(9) + mv1.coeff(4)*mv2.coeff(4) + mv1.coeff(5)*mv2.coeff(5) - mv1.coeff(6)*mv2.coeff(6) + mv1.coeff(7)*mv2.coeff(0) + mv1.coeff(8)*mv2.coeff(1) + mv1.coeff(9)*mv2.coeff(3);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 4). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 4 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_3_4(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(1) - mv1.coeff(1)*mv2.coeff(2) - mv1.coeff(3)*mv2.coeff(3) + mv1.coeff(6)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) += -mv1.coeff(3)*mv2.coeff(4) + mv1.coeff(4)*mv2.coeff(1) + mv1.coeff(5)*mv2.coeff(2) + mv1.coeff(9)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(2)*mv2.coeff(1) + mv1.coeff(5)*mv2.coeff(3) - mv1.coeff(8)*mv2.coeff(0);\n\t\tmv3.coeffRef(3) += -mv1.coeff(0)*mv2.coeff(4) - mv1.coeff(2)*mv2.coeff(2) - mv1.coeff(4)*mv2.coeff(3) + mv1.coeff(7)*mv2.coeff(0);\n\t\tmv3.coeffRef(4) += -mv1.coeff(6)*mv2.coeff(4) + mv1.coeff(7)*mv2.coeff(1) + mv1.coeff(8)*mv2.coeff(2) + mv1.coeff(9)*mv2.coeff(3);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 5). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 5 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid inner_3_5(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(3)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) += -mv1.coeff(1)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(0)*mv2.coeff(0);\n\t\tmv3.coeffRef(3) +=  mv1.coeff(6)*mv2.coeff(0);\n\t\tmv3.coeffRef(4) +=  mv1.coeff(5)*mv2.coeff(0);\n\t\tmv3.coeffRef(5) += -mv1.coeff(4)*mv2.coeff(0);\n\t\tmv3.coeffRef(6) +=  mv1.coeff(9)*mv2.coeff(0);\n\t\tmv3.coeffRef(7) +=  mv1.coeff(2)*mv2.coeff(0);\n\t\tmv3.coeffRef(8) += -mv1.coeff(8)*mv2.coeff(0);\n\t\tmv3.coeffRef(9) +=  mv1.coeff(7)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 4) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 4 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 4\n\ttemplate<typename T>\n\tvoid inner_4_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 4) and mv2 (grade 1). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 4 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3\n\ttemplate<typename T>\n\tvoid inner_4_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(3) - mv1.coeff(1)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(2) - mv1.coeff(2)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) += -mv1.coeff(1)*mv2.coeff(2) - mv1.coeff(2)*mv2.coeff(3);\n\t\tmv3.coeffRef(3) +=  mv1.coeff(0)*mv2.coeff(1) - mv1.coeff(3)*mv2.coeff(0);\n\t\tmv3.coeffRef(4) +=  mv1.coeff(1)*mv2.coeff(1) - mv1.coeff(3)*mv2.coeff(3);\n\t\tmv3.coeffRef(5) +=  mv1.coeff(2)*mv2.coeff(1) + mv1.coeff(3)*mv2.coeff(2);\n\t\tmv3.coeffRef(6) +=  mv1.coeff(0)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(0);\n\t\tmv3.coeffRef(7) +=  mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(3);\n\t\tmv3.coeffRef(8) +=  mv1.coeff(2)*mv2.coeff(4) + mv1.coeff(4)*mv2.coeff(2);\n\t\tmv3.coeffRef(9) +=  mv1.coeff(3)*mv2.coeff(4) - mv1.coeff(4)*mv2.coeff(1);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 4) and mv2 (grade 2). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 4 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid inner_4_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(7) - mv1.coeff(1)*mv2.coeff(1) - mv1.coeff(2)*mv2.coeff(2);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(0)*mv2.coeff(5) + mv1.coeff(1)*mv2.coeff(0) - mv1.coeff(3)*mv2.coeff(2);\n\t\tmv3.coeffRef(2) += -mv1.coeff(0)*mv2.coeff(4) + mv1.coeff(2)*mv2.coeff(0) + mv1.coeff(3)*mv2.coeff(1);\n\t\tmv3.coeffRef(3) += -mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(2)*mv2.coeff(5) - mv1.coeff(3)*mv2.coeff(7);\n\t\tmv3.coeffRef(4) += -mv1.coeff(0)*mv2.coeff(9) + mv1.coeff(1)*mv2.coeff(3) - mv1.coeff(4)*mv2.coeff(2);\n\t\tmv3.coeffRef(5) +=  mv1.coeff(0)*mv2.coeff(8) + mv1.coeff(2)*mv2.coeff(3) + mv1.coeff(4)*mv2.coeff(1);\n\t\tmv3.coeffRef(6) +=  mv1.coeff(1)*mv2.coeff(8) + mv1.coeff(2)*mv2.coeff(9) - mv1.coeff(4)*mv2.coeff(7);\n\t\tmv3.coeffRef(7) += -mv1.coeff(0)*mv2.coeff(6) + mv1.coeff(3)*mv2.coeff(3) - mv1.coeff(4)*mv2.coeff(0);\n\t\tmv3.coeffRef(8) += -mv1.coeff(1)*mv2.coeff(6) + mv1.coeff(3)*mv2.coeff(9) + mv1.coeff(4)*mv2.coeff(5);\n\t\tmv3.coeffRef(9) += -mv1.coeff(2)*mv2.coeff(6) - mv1.coeff(3)*mv2.coeff(8) - mv1.coeff(4)*mv2.coeff(4);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 4) and mv2 (grade 3). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 4 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_4_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(6) + mv1.coeff(1)*mv2.coeff(0) + mv1.coeff(2)*mv2.coeff(1) + mv1.coeff(3)*mv2.coeff(3);\n\t\tmv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(9) - mv1.coeff(1)*mv2.coeff(4) - mv1.coeff(2)*mv2.coeff(5) + mv1.coeff(4)*mv2.coeff(3);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(0)*mv2.coeff(8) + mv1.coeff(1)*mv2.coeff(2) - mv1.coeff(3)*mv2.coeff(5) - mv1.coeff(4)*mv2.coeff(1);\n\t\tmv3.coeffRef(3) += -mv1.coeff(0)*mv2.coeff(7) + mv1.coeff(2)*mv2.coeff(2) + mv1.coeff(3)*mv2.coeff(4) + mv1.coeff(4)*mv2.coeff(0);\n\t\tmv3.coeffRef(4) += -mv1.coeff(1)*mv2.coeff(7) - mv1.coeff(2)*mv2.coeff(8) - mv1.coeff(3)*mv2.coeff(9) + mv1.coeff(4)*mv2.coeff(6);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 4) and mv2 (grade 4). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 4 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 4 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0\n\ttemplate<typename T>\n\tvoid inner_4_4(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(4) - mv1.coeff(1)*mv2.coeff(1) - mv1.coeff(2)*mv2.coeff(2) - mv1.coeff(3)*mv2.coeff(3) + mv1.coeff(4)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 4) and mv2 (grade 5). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 4 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 5 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_4_5(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(3)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) += -mv1.coeff(2)*mv2.coeff(0);\n\t\tmv3.coeffRef(3) +=  mv1.coeff(1)*mv2.coeff(0);\n\t\tmv3.coeffRef(4) +=  mv1.coeff(4)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 5) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 5 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 5\n\ttemplate<typename T>\n\tvoid inner_5_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 5) and mv2 (grade 1). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 5 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 4\n\ttemplate<typename T>\n\tvoid inner_5_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(3);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(0)*mv2.coeff(2);\n\t\tmv3.coeffRef(3) += -mv1.coeff(0)*mv2.coeff(1);\n\t\tmv3.coeffRef(4) += -mv1.coeff(0)*mv2.coeff(4);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 5) and mv2 (grade 2). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 5 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3\n\ttemplate<typename T>\n\tvoid inner_5_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(2);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(0)*mv2.coeff(1);\n\t\tmv3.coeffRef(2) += -mv1.coeff(0)*mv2.coeff(7);\n\t\tmv3.coeffRef(3) += -mv1.coeff(0)*mv2.coeff(0);\n\t\tmv3.coeffRef(4) +=  mv1.coeff(0)*mv2.coeff(5);\n\t\tmv3.coeffRef(5) += -mv1.coeff(0)*mv2.coeff(4);\n\t\tmv3.coeffRef(6) += -mv1.coeff(0)*mv2.coeff(3);\n\t\tmv3.coeffRef(7) += -mv1.coeff(0)*mv2.coeff(9);\n\t\tmv3.coeffRef(8) +=  mv1.coeff(0)*mv2.coeff(8);\n\t\tmv3.coeffRef(9) += -mv1.coeff(0)*mv2.coeff(6);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 5) and mv2 (grade 3). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 5 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid inner_5_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(3);\n\t\tmv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(1);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(0)*mv2.coeff(0);\n\t\tmv3.coeffRef(3) +=  mv1.coeff(0)*mv2.coeff(6);\n\t\tmv3.coeffRef(4) +=  mv1.coeff(0)*mv2.coeff(5);\n\t\tmv3.coeffRef(5) += -mv1.coeff(0)*mv2.coeff(4);\n\t\tmv3.coeffRef(6) +=  mv1.coeff(0)*mv2.coeff(9);\n\t\tmv3.coeffRef(7) +=  mv1.coeff(0)*mv2.coeff(2);\n\t\tmv3.coeffRef(8) += -mv1.coeff(0)*mv2.coeff(8);\n\t\tmv3.coeffRef(9) +=  mv1.coeff(0)*mv2.coeff(7);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 5) and mv2 (grade 4). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 5 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 4 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_5_4(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(0)*mv2.coeff(3);\n\t\tmv3.coeffRef(2) += -mv1.coeff(0)*mv2.coeff(2);\n\t\tmv3.coeffRef(3) +=  mv1.coeff(0)*mv2.coeff(1);\n\t\tmv3.coeffRef(4) +=  mv1.coeff(0)*mv2.coeff(4);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 5) and mv2 (grade 5). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 5 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 5 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0\n\ttemplate<typename T>\n\tvoid inner_5_5(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(0);\n\t}\n\n\n\t\n    template<typename T>\n\tstd::array<std::array<std::function<void(const Eigen::Matrix<T, Eigen::Dynamic, 1> & , const Eigen::Matrix<T, Eigen::Dynamic, 1> & , Eigen::Matrix<T, Eigen::Dynamic, 1>&)>, 6>, 6> innerFunctionsContainer = {{\n\t\t{{inner_0_0<T>,inner_0_1<T>,inner_0_2<T>,inner_0_3<T>,inner_0_4<T>,inner_0_5<T>}},\n\t\t{{inner_1_0<T>,inner_1_1<T>,inner_1_2<T>,inner_1_3<T>,inner_1_4<T>,inner_1_5<T>}},\n\t\t{{inner_2_0<T>,inner_2_1<T>,inner_2_2<T>,inner_2_3<T>,inner_2_4<T>,inner_2_5<T>}},\n\t\t{{inner_3_0<T>,inner_3_1<T>,inner_3_2<T>,inner_3_3<T>,inner_3_4<T>,inner_3_5<T>}},\n\t\t{{inner_4_0<T>,inner_4_1<T>,inner_4_2<T>,inner_4_3<T>,inner_4_4<T>,inner_4_5<T>}},\n\t\t{{inner_5_0<T>,inner_5_1<T>,inner_5_2<T>,inner_5_3<T>,inner_5_4<T>,inner_5_5<T>}}\n\t}};\n\n}/// End of Namespace\n\n#endif // C3GA_INNER_PRODUCT_EXPLICIT_HPP__", "meta": {"hexsha": "4363b83d413603e467f495715fca5c031c7a1b73", "size": 40006, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/c3ga/src/c3ga/InnerExplicit.hpp", "max_stars_repo_name": "qcoumes/GA-physics", "max_stars_repo_head_hexsha": "be72e0959620973ab29cd9e4705e97eda4356fe9", "max_stars_repo_licenses": ["MIT"], "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/c3ga/src/c3ga/InnerExplicit.hpp", "max_issues_repo_name": "qcoumes/GA-physics", "max_issues_repo_head_hexsha": "be72e0959620973ab29cd9e4705e97eda4356fe9", "max_issues_repo_licenses": ["MIT"], "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/c3ga/src/c3ga/InnerExplicit.hpp", "max_forks_repo_name": "qcoumes/GA-physics", "max_forks_repo_head_hexsha": "be72e0959620973ab29cd9e4705e97eda4356fe9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-23T19:17:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-23T19:17:06.000Z", "avg_line_length": 70.1859649123, "max_line_length": 300, "alphanum_fraction": 0.6919962006, "num_tokens": 13862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5311219139633809}}
{"text": "/// ---------------------------------------------------------------------------\n/// @section LICENSE\n///  \n/// Copyright (c) 2016 Georgia Tech Research Institute (GTRI) \n///               All Rights Reserved\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 \n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \n/// DEALINGS IN THE SOFTWARE.\n/// ---------------------------------------------------------------------------\n/// @file filename.ext\n/// @author Kevin DeMarco <kevin.demarco@gtri.gatech.edu> \n/// @author Eric Squires <eric.squires@gtri.gatech.edu>\n/// @version 1.0\n/// ---------------------------------------------------------------------------\n/// @brief A brief description.\n/// \n/// @section DESCRIPTION\n/// A long description.\n/// ---------------------------------------------------------------------------\n#include <scrimmage/common/Utilities.h>\n#include <scrimmage/parse/ParseUtils.h>\n#include <scrimmage/plugin_manager/RegisterPlugin.h>\n#include <scrimmage/entity/Entity.h>\n#include <scrimmage/math/State.h>\n#include <scrimmage/entity/Entity.h>\n#include <boost/algorithm/clamp.hpp>\n\n#include \"Unicycle.h\"\n\nREGISTER_PLUGIN(scrimmage::MotionModel, Unicycle, \n                Unicycle_plugin)\n\nnamespace sc = scrimmage;\n\nnamespace pl = std::placeholders;\n\nenum ModelParams\n{\n    X = 0,\n    Y,\n    THETA,\n    MODEL_NUM_ITEMS\n};\n\nUnicycle::Unicycle()\n{\n    x_.resize(MODEL_NUM_ITEMS);\n}\n\nbool Unicycle::init(std::map<std::string, std::string> &info,\n                            std::map<std::string, std::string> &params)\n{\n    x_[X] = state_->pos()(0);\n    x_[Y] = state_->pos()(1);\n    x_[THETA] = state_->quat().yaw();\n\n    turn_rate_max_ = std::stod(params.at(\"turn_rate_max\"));\n    vel_max_ = std::stod(params.at(\"vel_max\"));\n    return true;\n}\n\nbool Unicycle::step(double t, double dt)\n{   \n    u_ = std::static_pointer_cast<Controller>(parent_.lock()->controllers().back())->u();    \n    \n    double prev_x = x_[X];\n    double prev_y = x_[Y];\n    \n    ode_step(dt);\n    \n    double dx = (x_[X] - prev_x) / dt;\n    double dy = (x_[Y] - prev_y) / dt;\n\n    state_->vel()(0) = dx;\n    state_->vel()(1) = dy;\n\n    state_->pos()(0) = x_[X];\n    state_->pos()(1) = x_[Y];\n\n    state_->quat().set(0, 0, x_[THETA]);\n\n    return true;\n}\n\nvoid Unicycle::model(const vector_t &x , vector_t &dxdt , double t)\n{    \n    double vel = boost::algorithm::clamp(u_(0), -vel_max_, vel_max_);\n    double yaw_rate = boost::algorithm::clamp(u_(1), -turn_rate_max_, turn_rate_max_);\n    dxdt[X] = vel * cos(x[THETA]);\n    dxdt[Y] = vel * sin(x[THETA]);\n    dxdt[THETA] = yaw_rate;\n}\n", "meta": {"hexsha": "125e54710e6127cffae44af04c6daa2ceafc47d0", "size": 3088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scrimmage/plugins/motion/Unicycle/Unicycle.cpp", "max_stars_repo_name": "ddfan/swarm_evolve", "max_stars_repo_head_hexsha": "cd2d972c021e9af5946673363fbfd39cff18f13f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T03:01:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T03:11:30.000Z", "max_issues_repo_path": "scrimmage/plugins/motion/Unicycle/Unicycle.cpp", "max_issues_repo_name": "lyers179/swarm_evolve", "max_issues_repo_head_hexsha": "cd2d972c021e9af5946673363fbfd39cff18f13f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-29T02:14:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T02:36:14.000Z", "max_forks_repo_path": "scrimmage/plugins/motion/Unicycle/Unicycle.cpp", "max_forks_repo_name": "lyers179/swarm_evolve", "max_forks_repo_head_hexsha": "cd2d972c021e9af5946673363fbfd39cff18f13f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-10-29T02:07:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T06:37:53.000Z", "avg_line_length": 30.5742574257, "max_line_length": 93, "alphanum_fraction": 0.5841968912, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5311219139633809}}
{"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 <cmath>\n#include <cfloat>\n#include <cstdint>\n#include <limits>\n#include <utility>\n#include <type_traits>\n#include <boost/math/ccmath/modf.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\ntemplate <typename T>\ninline constexpr T floating_point_value(const T val)\n{\n    T i = 0;\n    const T ans = boost::math::ccmath::modf(val, &i);\n\n    return ans;\n}\n\ntemplate <typename T>\ninline constexpr T integral_value(const T val)\n{\n    T i = 0;\n    boost::math::ccmath::modf(val, &i);\n\n    return i;\n}\n\ntemplate <typename T>\ninline constexpr std::pair<T, T> pair_value(const T val)\n{\n    T i = 0;\n    T ans = boost::math::ccmath::modf(val, &i);\n\n    return std::make_pair(i, ans);\n}\n\ntemplate <typename T>\nconstexpr void test()\n{\n    if constexpr (std::numeric_limits<T>::has_quiet_NaN)\n    {\n        constexpr std::pair<T, T> NaN_val = pair_value(std::numeric_limits<T>::quiet_NaN());\n        static_assert(boost::math::ccmath::isnan(NaN_val.first));\n        static_assert(boost::math::ccmath::isnan(NaN_val.second));\n    }\n\n    // if x is +-0, +-0 is returned and +-0 is stored in *iptr\n    static_assert(floating_point_value(T(0)) == 0);\n    static_assert(floating_point_value(-T(0)) == -0);\n    static_assert(integral_value(T(0)) == 0);\n    static_assert(integral_value(-T(0)) == -0);\n\n    // if x is +- inf, +-0 is returned and +-inf is stored in *iptr\n    static_assert(floating_point_value(std::numeric_limits<T>::infinity()) == 0);\n    static_assert(floating_point_value(-std::numeric_limits<T>::infinity()) == -0);\n    static_assert(integral_value(std::numeric_limits<T>::infinity()) == std::numeric_limits<T>::infinity());\n    static_assert(integral_value(-std::numeric_limits<T>::infinity()) == -std::numeric_limits<T>::infinity());\n\n    // The returned value is exact, the current rounding mode is ignored\n    // The return value and *iptr each have the same type and sign as x\n    static_assert(integral_value(T(123.45)) == 123);\n    static_assert(integral_value(T(-234.56)) == -234);\n    static_assert(floating_point_value(T(1.0/2)) == T(1.0/2));\n    static_assert(floating_point_value(T(-1.0/3)) == T(-1.0/3));\n}\n\n#if !defined(BOOST_MATH_NO_CONSTEXPR_DETECTION) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\nint main()\n{\n    test<float>();\n    test<double>();\n\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test<long double>();\n    #endif\n    \n    #ifdef BOOST_HAS_FLOAT128\n    test<boost::multiprecision::float128>();\n    #endif\n\n    return 0;\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "eadd22b5c7726b799847bb8a05280147b610e857", "size": 2860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ccmath_modf_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/ccmath_modf_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/ccmath_modf_test.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 28.8888888889, "max_line_length": 110, "alphanum_fraction": 0.6814685315, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5311219108528039}}
{"text": "// std includes\n#include <iostream>\n#include <vector>\n#include <random>\n// thirdparties includes\n#include <Eigen/Dense>\n// lib includes\n#include \"m0sh/uniform.h\"\n\nusing TypeScalar = double;\n// Space\nconst unsigned int DIM = 3;\nusing TypeVector = Eigen::Matrix<TypeScalar, DIM, 1>;\ntemplate<typename ...Args>\nusing TypeRef = Eigen::Ref<Args...>;\n// Mesh\ntemplate<typename ...Args>\nusing TypeContainer = std::vector<Args...>;\nusing TypeMesh = m0sh::Uniform<TypeVector, TypeRef, TypeContainer>;\n// Data\nconst int nc = 100;\nconst double length = 1.0;\nconst double origin = 0.5;\n\nvoid print(const TypeMesh& mesh, std::uniform_int_distribution<int>& uniform, std::default_random_engine& e) {\n    TypeContainer<int> ijk;\n    TypeVector x;\n    std::size_t index;\n    // Print info\n    ijk = {uniform(e), uniform(e), uniform(e)};\n    x = mesh.positionPoint(ijk);\n    index = mesh.indexPoint(ijk);\n    std::cout << \"i: \" << ijk[0] << \" j: \" << ijk[1] << \" k: \" << ijk[2] << \"\\nindex: \" << index << \"\\nx: \" << x.transpose() << std::endl;\n    ijk = mesh.ijkPoint(x);\n    std::cout << \"xReverse: \" << \" i: \" << ijk[0] << \" j: \" << ijk[1] << \" k: \" << ijk[2] << std::endl;\n    ijk = mesh.ijkPoint(index);\n    std::cout << \"indexReverse: \" << \" i: \" << ijk[0] << \" j: \" << ijk[1] << \" k: \" << ijk[2] << std::endl;\n    std::cout << std::endl;\n}\n\nint main () { \n    TypeMesh mesh(TypeContainer<std::size_t>(DIM, nc), TypeContainer<double>(DIM, length), TypeVector::Constant(origin), TypeContainer<bool>(DIM, false));\n    // Random setup\n    std::random_device r;\n    std::default_random_engine e(r());\n    std::uniform_int_distribution<int> uniform(-nc, 2*nc);\n    // Print\n    print(mesh, uniform, e);\n    print(mesh, uniform, e);\n    print(mesh, uniform, e);\n}\n", "meta": {"hexsha": "b6249a91e382b2aa7c2566ad98979b8f7d6d7196", "size": 1746, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/uniform/main.cpp", "max_stars_repo_name": "C0PEP0D/m0sh", "max_stars_repo_head_hexsha": "2b7cb5a39efead42d6d823cb22d5423678e4934c", "max_stars_repo_licenses": ["MIT"], "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/uniform/main.cpp", "max_issues_repo_name": "C0PEP0D/m0sh", "max_issues_repo_head_hexsha": "2b7cb5a39efead42d6d823cb22d5423678e4934c", "max_issues_repo_licenses": ["MIT"], "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/uniform/main.cpp", "max_forks_repo_name": "C0PEP0D/m0sh", "max_forks_repo_head_hexsha": "2b7cb5a39efead42d6d823cb22d5423678e4934c", "max_forks_repo_licenses": ["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.5769230769, "max_line_length": 154, "alphanum_fraction": 0.6179839633, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.5311219097600404}}
{"text": "/*\n * 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#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <complex>\n#include <bitset>\n#include <boost/assert.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/polynomial.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/multiprecision/cpp_complex.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n\ntypedef boost::multiprecision::float128 float128_t;\n#else\ntypedef boost::multiprecision::cpp_bin_float_quad float128_t;\n#endif\n//#include <boost/multiprecision/complex128.hpp>\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n\nusing std::string;\nusing boost::math::tools::polynomial;\nusing boost::math::binomial_coefficient;\nusing boost::math::tools::schroder_iterate;\nusing boost::math::tools::halley_iterate;\nusing boost::math::tools::newton_raphson_iterate;\nusing boost::math::tools::complex_newton;\nusing boost::math::constants::half;\nusing boost::math::constants::root_two;\nusing boost::math::constants::pi;\nusing boost::math::quadrature::gauss_kronrod;\nusing boost::multiprecision::cpp_bin_float_100;\nusing boost::multiprecision::cpp_complex_100;\n\ntemplate<class Complex>\nstd::vector<std::pair<Complex, Complex>> find_roots(size_t p)\n{\n    // Initialize the polynomial; see Mallat, A Wavelet Tour of Signal Processing, equation 7.96\n    BOOST_ASSERT(p>0);\n    typedef typename Complex::value_type Real;\n    std::vector<Complex> coeffs(p);\n    for (size_t k = 0; k < coeffs.size(); ++k)\n    {\n        coeffs[k] = Complex(binomial_coefficient<Real>(p-1+k, k), 0);\n    }\n\n    polynomial<Complex> P(std::move(coeffs));\n    polynomial<Complex> Pcopy = P;\n    polynomial<Complex> Pcopy_prime = P.prime();\n    auto orig = [&](Complex z) { return std::make_pair<Complex, Complex>(Pcopy(z), Pcopy_prime(z)); };\n\n    polynomial<Complex> P_prime = P.prime();\n\n    // Polynomial is of degree p-1.\n\n    std::vector<Complex> roots(p-1, {std::numeric_limits<Real>::quiet_NaN(),std::numeric_limits<Real>::quiet_NaN()});\n    size_t i = 0;\n    while(P.size() > 1)\n    {\n        Complex guess = {0.0, 1.0};\n        std::cout << std::setprecision(std::numeric_limits<Real>::digits10+3);\n\n        auto f = [&](Complex x)->std::pair<Complex, Complex>\n        {\n            return std::make_pair<Complex, Complex>(P(x), P_prime(x));\n        };\n\n        Complex r = complex_newton(f, guess);\n        using std::isnan;\n        if(isnan(r.real()))\n        {\n            int i = 50;\n            do {\n                // Try a different guess\n                guess *= Complex(1.0,-1.0);\n                r = complex_newton(f, guess);\n                std::cout << \"New guess: \" << guess << \", result? \" << r << std::endl;\n\n            } while (isnan(r.real()) && i-- > 0);\n\n            if (isnan(r.real()))\n            {\n                std::cout << \"Polynomial that killed the process: \" << P << std::endl;\n                throw std::logic_error(\"Newton iteration did not converge\");\n            }\n        }\n        // Refine r with the original function.\n        // We only use the polynomial division to ensure we don't get the same root over and over.\n        // However, the division induces error which can grow quickly-or slowly! See Numerical Recipes, section 9.5.1.\n        r = complex_newton(orig, r);\n        if (isnan(r.real()))\n        {\n            throw std::logic_error(\"Found a root for the deflated polynomial which is not a root for the original. Indicative of catastrophic numerical error.\");\n        }\n        // Test the root:\n        using std::sqrt;\n        Real tol = sqrt(sqrt(std::numeric_limits<Real>::epsilon()));\n        if (norm(Pcopy(r)) > tol)\n        {\n            std::cout << \"This is a bad root: P\" <<  r << \" = \" << Pcopy(r) << std::endl;\n            std::cout << \"Reduced polynomial leading to bad root: \" << P << std::endl;\n            throw std::logic_error(\"Donezo.\");\n        }\n\n        BOOST_ASSERT(i < roots.size());\n        roots[i] = r;\n        ++i;\n        polynomial<Complex> q{-r, {1,0}};\n        // This optimization breaks at p = 11. I have no clue why.\n        // Unfortunate, because I expect it to be considerably more stable than\n        // repeatedly dividing by the complex root.\n        /*polynomial<Complex> q;\n        if (r.imag() > sqrt(std::numeric_limits<Real>::epsilon()))\n        {\n            // Then the complex conjugate is also a root:\n            using std::conj;\n            using std::norm;\n            BOOST_ASSERT(i < roots.size());\n            roots[i] = conj(r);\n            ++i;\n            q = polynomial<Complex>({{norm(r), 0}, {-2*r.real(),0}, {1,0}});\n        }\n        else\n        {\n            // The imaginary part is numerical noise:\n            r.imag() = 0;\n            q = polynomial<Complex>({-r, {1,0}});\n        }*/\n\n\n        auto PR = quotient_remainder(P, q);\n        // I should validate that the remainder is small, but . . .\n        //std::cout << \"Remainder = \" << PR.second<< std::endl;\n\n        P = PR.first;\n        P_prime = P.prime();\n    }\n\n    std::vector<std::pair<Complex, Complex>> Qroots(p-1);\n    for (size_t i = 0; i < Qroots.size(); ++i)\n    {\n        Complex y = roots[i];\n        Complex z1 = static_cast<Complex>(1) - static_cast<Complex>(2)*y + static_cast<Complex>(2)*sqrt(y*(y-static_cast<Complex>(1)));\n        Complex z2 = static_cast<Complex>(1) - static_cast<Complex>(2)*y - static_cast<Complex>(2)*sqrt(y*(y-static_cast<Complex>(1)));\n        Qroots[i] = {z1, z2};\n    }\n\n    return Qroots;\n}\n\ntemplate<class Complex>\nstd::vector<typename Complex::value_type> daubechies_coefficients(std::vector<std::pair<Complex, Complex>> const & Qroots)\n{\n    typedef typename Complex::value_type Real;\n    size_t p = Qroots.size() + 1;\n    // Choose the minimum abs root; see Mallat, discussion just after equation 7.98\n    std::vector<Complex> chosen_roots(p-1);\n    for (size_t i = 0; i < p - 1; ++i)\n    {\n        if(norm(Qroots[i].first) <= 1)\n        {\n            chosen_roots[i] = Qroots[i].first;\n        }\n        else\n        {\n            BOOST_ASSERT(norm(Qroots[i].second) <= 1);\n            chosen_roots[i] = Qroots[i].second;\n        }\n    }\n\n    polynomial<Complex> R{1};\n    for (size_t i = 0; i < p-1; ++i)\n    {\n        Complex ak = chosen_roots[i];\n        R *= polynomial<Complex>({-ak/(static_cast<Complex>(1)-ak), static_cast<Complex>(1)/(static_cast<Complex>(1)-ak)});\n    }\n    polynomial<Complex> a{{half<Real>(), 0}, {half<Real>(),0}};\n    polynomial<Complex> poly = root_two<Real>()*pow(a, p)*R;\n    std::vector<Complex> result = poly.data();\n    // If we reverse, we get the Numerical Recipes and Daubechies convention.\n    // If we don't reverse, we get the Pywavelets and Mallat convention.\n    // I believe this is because of the sign convention on the DFT, which differs between Daubechies and Mallat.\n    // You implement a dot product in Daubechies/NR convention, and a convolution in PyWavelets/Mallat convention.\n    std::reverse(result.begin(), result.end());\n    std::vector<Real> h(result.size());\n    for (size_t i = 0; i < result.size(); ++i)\n    {\n        Complex r = result[i];\n        BOOST_ASSERT(r.imag() < sqrt(std::numeric_limits<Real>::epsilon()));\n        h[i] = r.real();\n    }\n\n    // Quick sanity check: We could check all vanishing moments, but that sum is horribly ill-conditioned too!\n    Real sum = 0;\n    Real scale = 0;\n    for (size_t i = 0; i < h.size(); ++i)\n    {\n        sum += h[i];\n        scale += h[i]*h[i];\n    }\n    BOOST_ASSERT(abs(scale -1) < sqrt(std::numeric_limits<Real>::epsilon()));\n    BOOST_ASSERT(abs(sum - root_two<Real>()) < sqrt(std::numeric_limits<Real>::epsilon()));\n    return h;\n}\n\nint main()\n{\n    typedef boost::multiprecision::cpp_complex<500> Complex;\n    size_t p_max = 20;\n    std::ofstream fs{\"daubechies_filters.hpp\"};\n    fs << \"/*\\n\"\n       << \" * Copyright Nick Thompson, 2019\\n\"\n       << \" * Use, modification and distribution are subject to the\\n\"\n       << \" * Boost Software License, Version 1.0. (See accompanying file\\n\"\n       << \" * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\\n\"\n       << \" */\\n\"\n       << \"#ifndef BOOST_MATH_FILTERS_DAUBECHIES_HPP\\n\"\n       << \"#define BOOST_MATH_FILTERS_DAUBECHIES_HPP\\n\"\n       << \"#include <array>\\n\"\n       << \"#include <limits>\\n\"\n       << \"#include <boost/math/tools/big_constant.hpp>\\n\\n\"\n       << \"namespace boost::math::filters {\\n\\n\"\n       << \"template <typename Real, unsigned p>\\n\"\n       << \"constexpr std::array<Real, 2*p> daubechies_scaling_filter()\\n\"\n       << \"{\\n\"\n       << \"    static_assert(p < \" << p_max << \", \\\"Filter coefficients only implemented up to \" << p_max - 1 << \".\\\");\\n\";\n\n    for(size_t p = 1; p < p_max; ++p)\n    {\n        fs << std::setprecision(std::numeric_limits<boost::multiprecision::cpp_bin_float_oct>::max_digits10);\n        auto roots = find_roots<Complex>(p);\n        auto h = daubechies_coefficients(roots);\n        fs << \"    if constexpr (p == \" << p << \") {\\n\";\n        fs << \"       return {\";\n        for (size_t i = 0; i < h.size() - 1; ++i) {\n            fs << \"BOOST_MATH_BIG_CONSTANT(Real, std::numeric_limits<Real>::digits, \" << h[i] << \"), \";\n        }\n        fs << \"BOOST_MATH_BIG_CONSTANT(Real, std::numeric_limits<Real>::digits, \" << h[h.size()-1] << \") };\\n\";\n        fs << \"    }\\n\";\n    }\n\n    fs << \"}\\n\\n\";\n\n    fs << \"template<class Real, size_t p>\\n\";\n    fs << \"std::array<Real, 2*p> daubechies_wavelet_filter() {\\n\";\n    fs << \"    std::array<Real, 2*p> g;\\n\";\n    fs << \"    auto h = daubechies_scaling_filter<Real, p>();\\n\";\n    fs << \"    for (size_t i = 0; i < g.size(); i += 2)\\n\";\n    fs << \"    {\\n\";\n    fs << \"        g[i] = h[g.size() - i - 1];\\n\";\n    fs << \"        g[i+1] = -h[g.size() - i - 2];\\n\";\n    fs << \"    }\\n\";\n    fs << \"    return g;\\n\";\n    fs << \"}\\n\\n\";\n    fs << \"} // namespaces\\n\";\n    fs << \"#endif\\n\";\n    fs.close();\n}\n", "meta": {"hexsha": "1366e921cd953410e73247c065b6cb0ed6e67b3f", "size": 10201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/example/daubechies_wavelets/daubechies_coefficients.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T15:15:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T15:15:28.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/example/daubechies_wavelets/daubechies_coefficients.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/example/daubechies_wavelets/daubechies_coefficients.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 38.0634328358, "max_line_length": 161, "alphanum_fraction": 0.5868052152, "num_tokens": 2753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5311219097600403}}
{"text": "#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n#include <Eigen/Core>\n#include <unsupported/Eigen/FFT>\n#include \"VMD.h\"\n#include \"MMDFileIOUtil.h\"\n#include \"fpschanger.h\"\n#include \"smoothvmd.h\"\n#include \"reducevmd.h\"\n\nusing namespace Eigen;\nusing namespace MMDFileIOUtil;\nusing namespace std;\n\n// VMD\u30e2\u30fc\u30b7\u30e7\u30f3\u306e\u5e73\u6ed1\u5316\u304a\u3088\u3073\u9593\u5f15\u304d\u3092\u884c\u3046\nbool smooth_and_reduce(VMD& vmd, float cutoff_freq, float threshold_pos, float threshold_rot,\n                       float threshold_morph, float srcfps, float tgtfps, bool bezier)\n{\n  cout << \"vmd.frame.size(original): \" << vmd.frame.size() << endl;\n  // \u30ad\u30fc\u30d5\u30ec\u30fc\u30e0\u3092\u30dc\u30fc\u30f3\u3054\u3068\u306b\u5206\u3051\u308b\n  map<string, vector<VMD_Frame>> frame_map;\n  for (unsigned int i = 0; i < vmd.frame.size(); i++) {\n    VMD_Frame frame = vmd.frame[i];\n    string name;\n    sjis_to_utf8(frame.bonename, name, frame.bonename_len);\n    frame_map[name].push_back(frame);\n  }\n  // \u30dc\u30fc\u30f3\u3054\u3068\u306b\u5e73\u6ed1\u5316\u3068\u9593\u5f15\u304d\u3092\u884c\u3044\u3001vmd\u306e\u30dc\u30fc\u30f3\u30ad\u30fc\u30d5\u30ec\u30fc\u30e0\u3092\u5165\u308c\u66ff\u3048\u308b\n  vmd.frame.clear();\n  for (auto iter = frame_map.begin(); iter != frame_map.end(); iter++) {\n    vector<VMD_Frame>& fv = iter->second;\n    if (fv.size() > 2) {\n      smooth_bone_frame(fv, cutoff_freq, bezier);\n      if (srcfps != tgtfps) {\n        fv = change_fps_bone(fv, srcfps, tgtfps, bezier);\n      }\n      fv = reduce_bone_frame(fv, 0, fv.size() - 1, threshold_pos, threshold_rot, bezier);\n    }\n    for (unsigned int i = 0; i < fv.size(); i++) {\n      vmd.frame.push_back(fv[i]);\n    }\n  }\n  cout << \"vmd.frame.size(reduced): \" << vmd.frame.size() << endl;\n  \n  cout << \"vmd.morph.size(original): \" << vmd.morph.size() << endl;\n  // \u30ad\u30fc\u30d5\u30ec\u30fc\u30e0\u3092\u30e2\u30fc\u30d5\u3054\u3068\u306b\u5206\u3051\u308b\n  map<string, vector<VMD_Morph>> morph_map;\n  for (unsigned int i = 0; i < vmd.morph.size(); i++) {\n    VMD_Morph morph = vmd.morph[i];\n    string name;\n    sjis_to_utf8(morph.name, name, morph.name_len);\n    morph_map[name].push_back(morph);\n  }\n  // \u30e2\u30fc\u30d5\u3054\u3068\u306b\u5e73\u6ed1\u5316\u3068\u9593\u5f15\u304d\u3092\u884c\u3044\u3001vmd\u306e\u8868\u60c5\u30ad\u30fc\u30d5\u30ec\u30fc\u30e0\u3092\u5165\u308c\u66ff\u3048\u308b\n  vmd.morph.clear();\n  for (auto iter = morph_map.begin(); iter != morph_map.end(); iter++) {\n    vector<VMD_Morph>& mv = iter->second;\n    if (mv.size() > 2) {\n      smooth_morph_frame(mv, cutoff_freq);\n      if (srcfps != tgtfps) {\n        mv = change_fps_morph(mv, srcfps, tgtfps);\n      }\n      mv = reduce_morph_frame(mv, 0, mv.size() - 1, threshold_morph);\n    }\n    for (unsigned int i = 0; i < mv.size(); i++) {\n      vmd.morph.push_back(mv[i]);\n    }\n  }\n  cout << \"vmd.morph.size(reduced) : \" << vmd.morph.size() << endl;\n  \n  return true;\n}\n", "meta": {"hexsha": "751e1d8c680c7fdb0f4600c9ad86c42da1f7682e", "size": 2410, "ext": "cc", "lang": "C++", "max_stars_repo_path": "smooth_reduce.cc", "max_stars_repo_name": "ikeno-ikeo/readfacevmd", "max_stars_repo_head_hexsha": "854354812cbe27531afe8681c1b5b1df7207a42b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 49.0, "max_stars_repo_stars_event_min_datetime": "2018-05-19T07:28:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T07:16:06.000Z", "max_issues_repo_path": "smooth_reduce.cc", "max_issues_repo_name": "ikeno-ikeo/readfacevmd", "max_issues_repo_head_hexsha": "854354812cbe27531afe8681c1b5b1df7207a42b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-05-29T10:10:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T00:42:49.000Z", "max_forks_repo_path": "smooth_reduce.cc", "max_forks_repo_name": "ikeno-ikeo/readfacevmd", "max_forks_repo_head_hexsha": "854354812cbe27531afe8681c1b5b1df7207a42b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-03T20:58:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T09:06:47.000Z", "avg_line_length": 32.1333333333, "max_line_length": 93, "alphanum_fraction": 0.6377593361, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5311219097600403}}
{"text": "/*------------------------------------------------ Included libraries -----------------------------------------------*/\n#include <iostream>\n#include <cmath>\n#include <string>\n#include <Eigen/Core>\n#include \"random_forest.h\"\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing namespace derfcnd;\nusing namespace Eigen;\n/*-------------------------------------------------------------------------------------------------------------------*/\n\nchar generateRandomSet(unsigned int nrow, unsigned int ncol_c, unsigned int ncol_d, unsigned int nclass,\n\t\t\t\t\t\t\t\t\t\t\t string fpath, string fname);\n\n/*------------------------------------------------------- Main ------------------------------------------------------*/\nint main(int argc, char *argv[])\n{\n\tchar s;\n\tunsigned int nrow_train=1000, nrow_test=1000, ncol_c=20, ncol_d=2, nclass=5;\n\tstring fpath=\"\", ftrain=\"ftrain.txt\", ftest=\"ftest.txt\", fmodel=\"fmodel.txt\", fmodelbin=\"fmodel.bin\";\n\tSetData training_set, testing_set;\n\t/* default parameters; identical to: RandomForest derf; */\n\tRandomForest derf(N_POP, N_ITER, F, C, CONF_LVL);\n\tVectorXf prec, rec;\n\tMatrixXf certainty;\n\tMatrixXi confmat;\n\n\t/* generate random training set */\n\ts=generateRandomSet(nrow_train, ncol_c, ncol_d, nclass, fpath, ftrain);\n\tif(!s)\n\t{\n\t\tcout<<\"successful random set generation to file \"<<fpath<<ftrain<<endl;\n\t}\n\telse\n\t{\n\t\tcout<<\"ERROR \"<<(int) s<<\": random set generation to file \"<<fpath<<ftrain<<endl;\n\t\treturn 0;\n\t}\n\t/* generate random testing set */\n\ts=generateRandomSet(nrow_test, ncol_c, ncol_d, nclass, fpath, ftest);\n\tif(!s)\n\t{\n\t\tcout<<\"successful random set generation to file \"<<fpath<<ftest<<endl;\n\t}\n\telse\n\t{\n\t\tcout<<\"ERROR \"<<(int) s<<\": random set generation to file \"<<fpath<<ftest<<endl;\n\t\treturn 0;\n\t}\n\n\t/* reading training set */\n\ts=training_set.read(fpath, ftrain);\n\tif(!s)\n\t{\n\t\tcout<<\"successful training set reading from file \"<<fpath<<ftrain<<endl;\n\t}\n\telse\n\t{\n\t\tcout<<\"ERROR \"<<(int) s<<\": training set reading from file \"<<fpath<<ftrain<<endl;\n\t\treturn 0;\n\t}\n\t/* reading testing set */\n\tif(!testing_set.read(fpath, ftest))\n\t{\n\t\tcout<<\"successful testing set reading from file \"<<fpath<<ftest<<endl;\n\t}\n\telse\n\t{\n\t\tcout<<\"ERROR \"<<(int) s<<\": testing set reading from file \"<<fpath<<ftest<<endl;\n\t\treturn 0;\n\t}\n\n\t/* generating DERF model */\n\tcout<<\"generating DERF model...\"<<endl;\n\tderf.generate(training_set, N_TREES, log2(ncol_c)+1);\n\n\t/* testing DERF model */\n\tcout<<\"testing DERF model...\"<<endl;\n\tcertainty.resize(nrow_test, nclass);\n\tderf.test(testing_set, certainty);\n\n\t/* computing confusion matrix */\n\tconfmat.resize(nclass, nclass+1);\t\n\tconfusionMatrix(testing_set.x_class_, certainty, 0, confmat);\n\tcout<<\"confusion matrix:\"<<endl<<confmat<<endl;\n\t/* computing precision */\n\tprec.resize(nclass);\n\tprecision(confmat, prec);\n\tcout<<\"precision:\"<<endl<<prec.transpose()<<endl;\n\t/* computing recall */\n\trec.resize(nclass);\n\trecall(confmat, rec);\n\tcout<<\"recall:\"<<endl<<rec.transpose()<<endl;\n\n\t/* writing DERF model */\n\ts=derf.write(fpath, fmodel);\n\tif(!s)\n\t{\n\t\tcout<<\"successful model writing to file \"<<fpath<<fmodel<<endl;\n\t}\n\telse\n\t{\n\t\tcout<<\"ERROR \"<<(int) s<<\": model writing to file \"<<fpath<<fmodel<<endl;\n\t\treturn 0;\n\t}\n\ts=derf.writeBin(fpath, fmodelbin);\n\tif(!s)\n\t{\n\t\tcout<<\"successful model writing to file \"<<fpath<<fmodelbin<<endl;\n\t}\n\telse\n\t{\n\t\tcout<<\"ERROR \"<<(int) s<<\": model writing to file \"<<fpath<<fmodelbin<<endl;\n\t\treturn 0;\n\t}\n\n\t/* reading DERF model */\n\ts=derf.read(fpath, fmodel);\n\tif(!s)\n\t{\n\t\tcout<<\"successful model reading from file \"<<fpath<<fmodel<<endl;\n\t}\n\telse\n\t{\n\t\tcout<<\"ERROR \"<<(int) s<<\": model reading from file \"<<fpath<<fmodel<<endl;\n\t\treturn 0;\n\t}\n\n\t/* testing DERF model */\n\tcout<<\"testing DERF model...\"<<endl;\n\tcertainty.resize(nrow_test, nclass);\n\tderf.test(testing_set, certainty);\n\n\t/* computing confusion matrix */\n\tconfmat.resize(nclass, nclass+1);\t\n\tconfusionMatrix(testing_set.x_class_, certainty, 0, confmat);\n\tcout<<\"confusion matrix:\"<<endl<<confmat<<endl;\n\t/* computing precision */\n\tprec.resize(nclass);\n\tprecision(confmat, prec);\n\tcout<<\"precision:\"<<endl<<prec.transpose()<<endl;\n\t/* computing recall */\n\trec.resize(nclass);\n\trecall(confmat, rec);\n\tcout<<\"recall:\"<<endl<<rec.transpose()<<endl;\n\n\ts=derf.readBin(fpath, fmodelbin);\n\tif(!s)\n\t{\n\t\tcout<<\"successful model reading from file \"<<fpath<<fmodelbin<<endl;\n\t}\n\telse\n\t{\n\t\tcout<<\"ERROR \"<<(int) s<<\": model reading from file \"<<fpath<<fmodelbin<<endl;\n\t\treturn 0;\n\t}\n\n\t/* testing DERF model */\n\tcout<<\"testing DERF model...\"<<endl;\n\tcertainty.resize(nrow_test, nclass);\n\tderf.test(testing_set, certainty);\n\n\t/* computing confusion matrix */\n\tconfmat.resize(nclass, nclass+1);\t\n\tconfusionMatrix(testing_set.x_class_, certainty, 0, confmat);\n\tcout<<\"confusion matrix:\"<<endl<<confmat<<endl;\n\t/* computing precision */\n\tprec.resize(nclass);\n\tprecision(confmat, prec);\n\tcout<<\"precision:\"<<endl<<prec.transpose()<<endl;\n\t/* computing recall */\n\trec.resize(nclass);\n\trecall(confmat, rec);\n\tcout<<\"recall:\"<<endl<<rec.transpose()<<endl;\n\n\treturn 0;\n}\n/*-------------------------------------------------------------------------------------------------------------------*/\n\nchar generateRandomSet(unsigned int nrow, unsigned int ncol_c, unsigned int ncol_d, unsigned int nclass,\n\t\t\t\t\t\t\t\t\t\t\t string fpath, string fname)\n{\n\tunsigned int i, j;\n\tstring lbl;\n\tSetData set_data(nrow, ncol_c, ncol_d, nclass);\n\n\tfor(i=0; i<ncol_d; i++)\n\t{\n\t\tfor(j=0; j<nclass; j++)\n\t\t{\n\t\t\tlbl=\"lbl\";\n\t\t\tlbl+='1'+i;\n\t\t\tlbl+='1'+j;\n\t\t\tset_data.x_d_lbl_[i].push_back(lbl);\n\t\t}\n\t}\n\tfor(i=0; i<nclass; i++)\n\t{\n\t\tlbl=\"class\";\n\t\tlbl+='0'+i;\n\t\tset_data.class_lbl_[i]=lbl;\n\t}\n\tfor(i=0; i<nrow; i++)\n\t{\n\t\tfor(j=0; j<ncol_c; j++)\n\t\t{\n\t\t\tset_data.x_c_(i, j)=i*ncol_c+j;\n\t\t}\n\t\tfor(j=0; j<ncol_d; j++)\n\t\t{\n\t\t\tset_data.x_d_(i, j)=rand()%set_data.x_d_lbl_[j].size();\n\t\t}\n\t\tset_data.x_class_(i)=rand()%nclass;\n\t}\n\n\treturn set_data.write(fpath, fname);\n}", "meta": {"hexsha": "d08d47a21c5cba7cf00e2974d13f7508b236e2ab", "size": 5882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example.cpp", "max_stars_repo_name": "umgnunes/DERF", "max_stars_repo_head_hexsha": "5640586371a16cea7f1ba427949bba8c05ded82c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-10T05:02:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-10T05:02:40.000Z", "max_issues_repo_path": "example.cpp", "max_issues_repo_name": "umgnunes/DERF", "max_issues_repo_head_hexsha": "5640586371a16cea7f1ba427949bba8c05ded82c", "max_issues_repo_licenses": ["MIT"], "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": "umgnunes/DERF", "max_forks_repo_head_hexsha": "5640586371a16cea7f1ba427949bba8c05ded82c", "max_forks_repo_licenses": ["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.8584474886, "max_line_length": 119, "alphanum_fraction": 0.6176470588, "num_tokens": 1641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5311219086672766}}
{"text": "#include <iostream>\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/moment.hpp>\nusing namespace boost::accumulators;\n\nint main()\n{\n    // Define an accumulator set for calculating the mean and the\n    // 2nd moment ...\n    accumulator_set<double, stats<tag::mean, tag::moment<2> > > acc;\n\n    // push in some data ...\n    acc(1.2);\n    acc(2.3);\n    acc(3.4);\n    acc(4.5);\n\n    // Display the results ...\n    std::cout << \"Mean:   \" << mean(acc) << std::endl;\n    std::cout << \"Moment: \" << moment<2>(acc) << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "59650f8af7e6f1ee835bf2d1464c89397b5e27ac", "size": 678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "accumlator.cpp", "max_stars_repo_name": "sanikumar/ramdomaccess-machine", "max_stars_repo_head_hexsha": "e2f15020f0c47a3cf7e4e26010efdb5e4ecedfc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "accumlator.cpp", "max_issues_repo_name": "sanikumar/ramdomaccess-machine", "max_issues_repo_head_hexsha": "e2f15020f0c47a3cf7e4e26010efdb5e4ecedfc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "accumlator.cpp", "max_forks_repo_name": "sanikumar/ramdomaccess-machine", "max_forks_repo_head_hexsha": "e2f15020f0c47a3cf7e4e26010efdb5e4ecedfc0", "max_forks_repo_licenses": ["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": 68, "alphanum_fraction": 0.6415929204, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5311219086672765}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions,logical_eq) {\n  using stan::math::logical_eq;\n\n  EXPECT_TRUE(logical_eq(1,1));\n  EXPECT_TRUE(logical_eq(5.7,5.7));\n  EXPECT_TRUE(logical_eq(0,0.0));\n\n  EXPECT_FALSE(logical_eq(0,1));\n  EXPECT_FALSE(logical_eq(1.0,0));\n  EXPECT_FALSE(logical_eq(1, 2));\n  EXPECT_FALSE(logical_eq(2.0, -1.0));\n}\n\nTEST(MathFunctions, logical_eq_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_FALSE(stan::math::logical_eq(1.0, nan));\n  EXPECT_FALSE(stan::math::logical_eq(nan, 2.0));\n  EXPECT_FALSE(stan::math::logical_eq(nan, nan));\n}\n", "meta": {"hexsha": "e013438fadde9f1c8077e197fcdfde9595c69250", "size": 679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/logical_eq_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/logical_eq_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/logical_eq_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.16, "max_line_length": 56, "alphanum_fraction": 0.7201767305, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.5311171801552688}}
{"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 <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <vector>\n#include <dlib/rand.h>\n#include <dlib/string.h>\n#include <dlib/statistics.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.opt_qp_solver\");\n\n// ----------------------------------------------------------------------------------------\n\n    class test_smo\n    {\n    public:\n        double penalty;\n        double C;\n\n        double operator() (\n            const matrix<double,0,1>& alpha\n        ) const\n        {\n\n            double obj =  0.5* trans(alpha)*Q*alpha - trans(alpha)*b;\n            double c1 = pow(sum(alpha)-C,2);\n            double c2 = sum(pow(pointwise_multiply(alpha, alpha<0), 2));\n\n            obj += penalty*(c1 + c2);\n\n            return obj;\n        }\n\n        matrix<double> Q, b;\n    };\n\n// ----------------------------------------------------------------------------------------\n\n    class test_smo_derivative\n    {\n    public:\n        double penalty;\n        double C;\n\n        matrix<double,0,1> operator() (\n            const matrix<double,0,1>& alpha\n        ) const\n        {\n\n            matrix<double,0,1> obj =  Q*alpha - b;\n            matrix<double,0,1> c1 = uniform_matrix<double>(alpha.size(),1, 2*(sum(alpha)-C));\n            matrix<double,0,1> c2 = 2*pointwise_multiply(alpha, alpha<0);\n            \n            return obj + penalty*(c1 + c2);\n        }\n\n        matrix<double> Q, b;\n    };\n\n// ----------------------------------------------------------------------------------------\n\n    double compute_objective_value (\n        const matrix<double,0,1>& w,\n        const matrix<double>& A,\n        const matrix<double,0,1>& b,\n        const double C\n    )\n    {\n        return 0.5*dot(w,w) + C*max(trans(A)*w + b);\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_qp4_test1()\n    {\n        matrix<double> A(3,2);\n        A = 1,2,\n        -3,1,\n        6,7;\n\n        matrix<double,0,1> b(2);\n        b = 1,\n        2;\n\n        const double C = 2;\n\n        matrix<double,0,1> alpha(2), true_alpha(2);\n        alpha = C/2, C/2;\n\n        solve_qp4_using_smo(A, tmp(trans(A)*A), b, alpha, 1e-9, 800);\n        matrix<double,0,1> w = lowerbound(-A*alpha, 0);\n\n        dlog << LINFO << \"*******************************************************\";\n\n        dlog << LINFO << \"w:     \" << trans(w);\n\n        dlog << LINFO << \"computed obj:      \"<< compute_objective_value(w,A,b,C);\n        w = 0;\n        dlog << LINFO << \"with true w obj:   \"<< compute_objective_value(w,A,b,C);\n\n        dlog << LINFO << \"alpha:      \" << trans(alpha);\n        true_alpha = 0, 2;\n        dlog << LINFO << \"true alpha: \"<< trans(true_alpha);\n\n        dlog << LINFO << \"alpha error: \"<< max(abs(alpha-true_alpha));\n        DLIB_TEST(max(abs(alpha-true_alpha)) < 1e-9);\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_qp4_test2()\n    {\n        matrix<double> A(3,2);\n        A = 1,2,\n        3,-1,\n        6,7;\n\n        matrix<double,0,1> b(2);\n        b = 1,\n        2;\n\n        const double C = 2;\n\n        matrix<double,0,1> alpha(2), true_alpha(2);\n        alpha = C/2, C/2;\n\n        solve_qp4_using_smo(A, tmp(trans(A)*A), b, alpha, 1e-9, 800);\n        matrix<double,0,1> w = lowerbound(-A*alpha, 0);\n\n        dlog << LINFO << \"*******************************************************\";\n\n        dlog << LINFO << \"w:     \" << trans(w);\n\n        dlog << LINFO << \"computed obj:      \"<< compute_objective_value(w,A,b,C);\n        w = 0, 0.25, 0;\n        dlog << LINFO << \"with true w obj:   \"<< compute_objective_value(w,A,b,C);\n\n        dlog << LINFO << \"alpha:      \" << trans(alpha);\n        true_alpha = 0.43750, 1.56250;\n        dlog << LINFO << \"true alpha: \"<< trans(true_alpha);\n\n        dlog << LINFO << \"alpha error: \"<< max(abs(alpha-true_alpha));\n        DLIB_TEST(max(abs(alpha-true_alpha)) < 1e-9);\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_qp4_test3()\n    {\n        matrix<double> A(3,2);\n        A = 1,2,\n        -3,-1,\n        6,7;\n\n        matrix<double,0,1> b(2);\n        b = 1,\n        2;\n\n        const double C = 2;\n\n        matrix<double,0,1> alpha(2), true_alpha(2);\n        alpha = C/2, C/2;\n\n        solve_qp4_using_smo(A, tmp(trans(A)*A), b, alpha, 1e-9, 800);\n        matrix<double,0,1> w = lowerbound(-A*alpha, 0);\n\n        dlog << LINFO << \"*******************************************************\";\n\n        dlog << LINFO << \"w:     \" << trans(w);\n\n        dlog << LINFO << \"computed obj:      \"<< compute_objective_value(w,A,b,C);\n        w = 0, 2, 0;\n        dlog << LINFO << \"with true w obj:   \"<< compute_objective_value(w,A,b,C);\n\n        dlog << LINFO << \"alpha:      \" << trans(alpha);\n        true_alpha = 0, 2;\n        dlog << LINFO << \"true alpha: \"<< trans(true_alpha);\n\n        dlog << LINFO << \"alpha error: \"<< max(abs(alpha-true_alpha));\n        DLIB_TEST(max(abs(alpha-true_alpha)) < 1e-9);\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_qp4_test5()\n    {\n        matrix<double> A(3,3);\n        A = 1,2,4,\n        3,1,6,\n        6,7,-2;\n\n        matrix<double,0,1> b(3);\n        b = 1,\n        2,\n        3;\n\n        const double C = 2;\n\n        matrix<double,0,1> alpha(3), true_alpha(3);\n        alpha = C/2, C/2, 0;\n\n        solve_qp4_using_smo(A, tmp(trans(A)*A), b, alpha, 1e-9, 800);\n        matrix<double,0,1> w = lowerbound(-A*alpha, 0);\n\n\n        dlog << LINFO << \"*******************************************************\";\n\n        dlog << LINFO << \"w:     \" << trans(w);\n\n        dlog << LINFO << \"computed obj:      \"<< compute_objective_value(w,A,b,C);\n        w = 0, 0, 0.11111111111111111111;\n        dlog << LINFO << \"with true w obj:   \"<< compute_objective_value(w,A,b,C);\n\n        dlog << LINFO << \"alpha:      \" << trans(alpha);\n        true_alpha = 0, 0.432098765432099, 1.567901234567901;\n        dlog << LINFO << \"true alpha: \"<< trans(true_alpha);\n\n        dlog << LINFO << \"alpha error: \"<< max(abs(alpha-true_alpha));\n        DLIB_TEST(max(abs(alpha-true_alpha)) < 1e-9);\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_qp4_test4()\n    {\n        matrix<double> A(3,2);\n        A = 1,2,\n        3,1,\n        6,7;\n\n        matrix<double,0,1> b(2);\n        b = 1,\n        2;\n\n        const double C = 2;\n\n        matrix<double,0,1> alpha(2), true_alpha(2);\n        alpha = C/2, C/2;\n\n        solve_qp4_using_smo(A, tmp(trans(A)*A), b, alpha, 1e-9, 800);\n        matrix<double,0,1> w = lowerbound(-A*alpha, 0);\n\n        dlog << LINFO << \"*******************************************************\";\n\n        dlog << LINFO << \"w:     \" << trans(w);\n\n        dlog << LINFO << \"computed obj:      \"<< compute_objective_value(w,A,b,C);\n        w = 0, 0, 0;\n        dlog << LINFO << \"with true w obj:   \"<< compute_objective_value(w,A,b,C);\n\n        dlog << LINFO << \"alpha:      \" << trans(alpha);\n        true_alpha = 0, 2;\n        dlog << LINFO << \"true alpha: \"<< trans(true_alpha);\n\n        dlog << LINFO << \"alpha error: \"<< max(abs(alpha-true_alpha));\n        DLIB_TEST(max(abs(alpha-true_alpha)) < 1e-9);\n    }\n\n    void test_qp4_test6()\n    {\n        matrix<double> A(3,3);\n        A = 1,2,4,\n        3,1,6,\n        6,7,-2;\n\n        matrix<double,0,1> b(3);\n        b = -1,\n        -2,\n        -3;\n\n        const double C = 2;\n\n        matrix<double,0,1> alpha(3), true_alpha(3);\n        alpha = C/2, C/2, 0;\n\n        solve_qp4_using_smo(A, tmp(trans(A)*A), b, alpha, 1e-9, 800);\n        matrix<double,0,1> w = lowerbound(-A*alpha, 0);\n\n        dlog << LINFO << \"*******************************************************\";\n\n        dlog << LINFO << \"w:     \" << trans(w);\n\n        dlog << LINFO << \"computed obj:      \"<< compute_objective_value(w,A,b,C);\n        w = 0, 0, 0;\n        dlog << LINFO << \"with true w obj:   \"<< compute_objective_value(w,A,b,C);\n\n        dlog << LINFO << \"alpha:      \" << trans(alpha);\n        true_alpha = 2, 0, 0;\n        dlog << LINFO << \"true alpha: \"<< trans(true_alpha);\n\n        dlog << LINFO << \"alpha error: \"<< max(abs(alpha-true_alpha));\n        DLIB_TEST(max(abs(alpha-true_alpha)) < 1e-9);\n    }\n\n    void test_qp4_test7()\n    {\n        matrix<double> A(3,3);\n        A = -1,2,4,\n        -3,1,6,\n        -6,7,-2;\n\n        matrix<double,0,1> b(3);\n        b = -1,\n        -2,\n        3;\n\n        matrix<double> Q(3,3);\n        Q = 4,-5,6,\n        1,-4,2,\n        -9,-4,5;\n        Q = Q*trans(Q);\n\n        const double C = 2;\n\n        matrix<double,0,1> alpha(3), true_alpha(3);\n        alpha = C/2, C/2, 0;\n\n        solve_qp4_using_smo(A, Q, b, alpha, 1e-9, 800);\n\n        dlog << LINFO << \"*******************************************************\";\n\n        dlog << LINFO << \"alpha:      \" << trans(alpha);\n        true_alpha = 0, 2, 0;\n        dlog << LINFO << \"true alpha: \"<< trans(true_alpha);\n\n        dlog << LINFO << \"alpha error: \"<< max(abs(alpha-true_alpha));\n        DLIB_TEST(max(abs(alpha-true_alpha)) < 1e-9);\n\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_solve_qp4_using_smo()\n    {\n        test_qp4_test1();\n        test_qp4_test2();\n        test_qp4_test3();\n        test_qp4_test4();\n        test_qp4_test5();\n        test_qp4_test6();\n        test_qp4_test7();\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    class opt_qp_solver_tester : public tester\n    {\n        /*\n            The idea here is just to solve the same problem with two different\n            methods and check that they basically agree.  The SMO solver should be\n            very accurate but for this problem the BFGS solver is relatively\n            inaccurate.  So this test is really just a sanity check on the SMO\n            solver.\n        */\n    public:\n        opt_qp_solver_tester (\n        ) :\n            tester (\"test_opt_qp_solver\",\n                    \"Runs tests on the solve_qp_using_smo component.\")\n        {\n            thetime = time(0);\n        }\n\n        time_t thetime;\n        dlib::rand rnd;\n\n        void perform_test(\n        )\n        {\n            print_spinner();\n            test_solve_qp4_using_smo();\n            print_spinner();\n\n            ++thetime;\n            //dlog << LINFO << \"time seed: \" << thetime;\n            //rnd.set_seed(cast_to_string(thetime));\n\n            running_stats<double> rs;\n\n            for (int i = 0; i < 40; ++i)\n            {\n                for (long dims = 1; dims < 6; ++dims)\n                {\n                    rs.add(do_the_test(dims, 1.0));\n                }\n            }\n\n            for (int i = 0; i < 40; ++i)\n            {\n                for (long dims = 1; dims < 6; ++dims)\n                {\n                    rs.add(do_the_test(dims, 5.0));\n                }\n            }\n\n            dlog << LINFO << \"disagreement mean: \" << rs.mean();\n            dlog << LINFO << \"disagreement stddev: \" << rs.stddev();\n            DLIB_TEST_MSG(rs.mean() < 0.001, rs.mean());\n            DLIB_TEST_MSG(rs.stddev() < 0.001, rs.stddev());\n        }\n\n        double do_the_test (\n            const long dims,\n            double C\n        )\n        {\n            print_spinner();\n            dlog << LINFO << \"dims: \" << dims;\n            dlog << LINFO << \"testing with C == \" << C;\n            test_smo test;\n\n            test.Q = randm(dims, dims, rnd);\n            test.Q = trans(test.Q)*test.Q;\n            test.b = randm(dims,1, rnd);\n            test.C = C;\n\n            test_smo_derivative der;\n            der.Q = test.Q;\n            der.b = test.b;\n            der.C = test.C;\n\n\n            matrix<double,0,1> x(dims), alpha(dims);\n\n\n            test.penalty = 20000;\n            der.penalty = test.penalty;\n\n            alpha = C/alpha.size();\n            x = alpha;\n\n            const unsigned long max_iter = 400000;\n            solve_qp_using_smo(test.Q, test.b, alpha, 0.00000001, max_iter);\n            DLIB_TEST_MSG(abs(sum(alpha) - C) < 1e-13, abs(sum(alpha) - C) );\n            dlog << LTRACE << \"alpha: \" << alpha;\n            dlog << LINFO << \"SMO: true objective: \"<< 0.5*trans(alpha)*test.Q*alpha - trans(alpha)*test.b;\n\n\n            double obj = find_min(bfgs_search_strategy(),\n                                  objective_delta_stop_strategy(1e-13, 5000),\n                                  test,\n                                  der,\n                                  x,\n                                  -10);\n\n\n            dlog << LINFO << \"BFGS: objective: \" << obj;\n            dlog << LINFO << \"BFGS: true objective: \"<< 0.5*trans(x)*test.Q*x - trans(x)*test.b;\n            dlog << LINFO << \"sum(x): \" << sum(x);\n            dlog << LINFO << x;\n\n            double disagreement = max(abs(x-alpha));\n            dlog << LINFO << \"Disagreement: \" << disagreement;\n            return disagreement;\n        }\n    } a;\n\n}\n\n\n\n", "meta": {"hexsha": "104da5574f2da87b1c248a80c494316f87d361e9", "size": 13341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dlib/test/opt_qp_solver.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/opt_qp_solver.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/opt_qp_solver.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": 27.9685534591, "max_line_length": 107, "alphanum_fraction": 0.4304774755, "num_tokens": 3583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5311171761836894}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2005 - 2021 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\n\n// @sect3{Include files}  \n\n// \u7531\u4e8e\u8fd9\u4e2a\u7a0b\u5e8f\u53ea\u662f\u5bf9 step-4 \u7684\u6539\u7f16\uff0c\u6240\u4ee5\u5728\u5934\u6587\u4ef6\u65b9\u9762\u6ca1\u6709\u592a\u591a\u7684\u65b0\u4e1c\u897f\u3002\u5728deal.II\u4e2d\uff0c\u6211\u4eec\u901a\u5e38\u6309\u7167base-lac-grid-dofs-fe-numerics\u7684\u987a\u5e8f\u5217\u51fa\u5305\u542b\u6587\u4ef6\uff0c\u7136\u540e\u662fC++\u6807\u51c6\u5305\u542b\u6587\u4ef6\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/base/function.h> \n\n#include <deal.II/lac/block_vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/block_sparse_matrix.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/precondition.h> \n\n// \u552f\u4e00\u503c\u5f97\u5173\u6ce8\u7684\u4e24\u4e2a\u65b0\u5934\u6587\u4ef6\u662fLinearOperator\u548cPackagedOperation\u7c7b\u7684\u6587\u4ef6\u3002\n\n#include <deal.II/lac/linear_operator.h> \n#include <deal.II/lac/packaged_operation.h> \n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_renumbering.h> \n#include <deal.II/dofs/dof_tools.h> \n#include <deal.II/fe/fe_dgq.h> \n#include <deal.II/fe/fe_system.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\n#include <fstream> \n#include <iostream> \n\n// \u8fd9\u662f\u552f\u4e00\u91cd\u8981\u7684\u65b0\u6807\u9898\uff0c\u5373\u58f0\u660eRaviart-Thomas\u6709\u9650\u5143\u7684\u6807\u9898\u3002\n\n#include <deal.II/fe/fe_raviart_thomas.h> \n\n// \u6700\u540e\uff0c\u4f5c\u4e3a\u672c\u7a0b\u5e8f\u4e2d\u7684\u4e00\u9879\u5956\u52b1\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u4e00\u4e2a\u5f20\u91cf\u7cfb\u6570\u3002\u7531\u4e8e\u5b83\u53ef\u80fd\u5177\u6709\u7a7a\u95f4\u4f9d\u8d56\u6027\uff0c\u6211\u4eec\u8ba4\u4e3a\u5b83\u662f\u4e00\u4e2a\u5f20\u91cf\u503c\u7684\u51fd\u6570\u3002\u4e0b\u9762\u7684include\u6587\u4ef6\u63d0\u4f9b\u4e86 <code>TensorFunction</code> \u7c7b\uff0c\u63d0\u4f9b\u4e86\u8fd9\u6837\u7684\u529f\u80fd\u3002\n\n#include <deal.II/base/tensor_function.h> \n\n// \u6700\u540e\u4e00\u6b65\u548c\u4ee5\u524d\u6240\u6709\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\u6211\u4eec\u628a\u6240\u6709\u4e0e\u8fd9\u4e2a\u7a0b\u5e8f\u76f8\u5173\u7684\u4ee3\u7801\u653e\u5230\u4e00\u4e2a\u547d\u540d\u7a7a\u95f4\u4e2d\u3002(\u8fd9\u4e2a\u60f3\u6cd5\u5728  step-7  \u4e2d\u9996\u6b21\u63d0\u51fa) \u3002\n\nnamespace Step20 \n{ \n  using namespace dealii; \n// @sect3{The <code>MixedLaplaceProblem</code> class template}  \n\n// \u540c\u6837\uff0c\u7531\u4e8e\u8fd9\u662f\u5bf9 step-6 \u7684\u6539\u7f16\uff0c\u4e3b\u7c7b\u4e0e\u8be5\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u7684\u4e3b\u7c7b\u51e0\u4e4e\u76f8\u540c\u3002\u5c31\u6210\u5458\u51fd\u6570\u800c\u8a00\uff0c\u4e3b\u8981\u533a\u522b\u5728\u4e8e\u6784\u9020\u51fd\u6570\u5c06Raviart-Thomas\u5143\u7d20\u7684\u5ea6\u6570\u4f5c\u4e3a\u53c2\u6570\uff08\u5e76\u4e14\u6709\u4e00\u4e2a\u76f8\u5e94\u7684\u6210\u5458\u53d8\u91cf\u6765\u5b58\u50a8\u8fd9\u4e2a\u503c\uff09\uff0c\u5e76\u4e14\u589e\u52a0\u4e86 <code>compute_error</code> \u51fd\u6570\uff0c\u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\uff0c\u4e0d\u51fa\u610f\u5916\uff0c\u6211\u4eec\u5c06\u8ba1\u7b97\u7cbe\u786e\u89e3\u548c\u6570\u503c\u89e3\u4e4b\u95f4\u7684\u5dee\u5f02\uff0c\u4ee5\u786e\u5b9a\u6211\u4eec\u8ba1\u7b97\u7684\u6536\u655b\u6027\u3002\n\n  template <int dim> \n  class MixedLaplaceProblem \n  { \n  public: \n    MixedLaplaceProblem(const unsigned int degree); \n    void run(); \n\n  private: \n    void make_grid_and_dofs(); \n    void assemble_system(); \n    void solve(); \n    void compute_errors() const; \n    void output_results() const; \n\n    const unsigned int degree; \n\n    Triangulation<dim> triangulation; \n    FESystem<dim>      fe; \n    DoFHandler<dim>    dof_handler; \n\n// \u7b2c\u4e8c\u4e2a\u533a\u522b\u662f\u758f\u6563\u6a21\u5f0f\u3001\u7cfb\u7edf\u77e9\u9635\u3001\u89e3\u548c\u53f3\u624b\u5411\u91cf\u73b0\u5728\u88ab\u5c01\u9501\u4e86\u3002\u8fd9\u610f\u5473\u7740\u4ec0\u4e48\uff0c\u4eba\u4eec\u53ef\u4ee5\u7528\u8fd9\u4e9b\u5bf9\u8c61\u505a\u4ec0\u4e48\uff0c\u5728\u672c\u7a0b\u5e8f\u7684\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u89e3\u91ca\u8fc7\u4e86\uff0c\u4e0b\u9762\u6211\u4eec\u5728\u89e3\u91ca\u8fd9\u4e2a\u95ee\u9898\u7684\u7ebf\u6027\u6c42\u89e3\u5668\u548c\u9884\u5904\u7406\u5668\u65f6\u4e5f\u4f1a\u8fdb\u4e00\u6b65\u89e3\u91ca\u3002\n\n    BlockSparsityPattern      sparsity_pattern; \n    BlockSparseMatrix<double> system_matrix; \n\n    BlockVector<double> solution; \n    BlockVector<double> system_rhs; \n  }; \n// @sect3{Right hand side, boundary values, and exact solution}  \n\n// \u6211\u4eec\u7684\u4e0b\u4e00\u4e2a\u4efb\u52a1\u662f\u5b9a\u4e49\u6211\u4eec\u95ee\u9898\u7684\u53f3\u624b\u8fb9\uff08\u5373\u539f\u59cb\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\u4e2d\u538b\u529b\u7684\u6807\u91cf\u53f3\u624b\u8fb9\uff09\uff0c\u538b\u529b\u7684\u8fb9\u754c\u503c\uff0c\u4ee5\u53ca\u4e00\u4e2a\u63cf\u8ff0\u538b\u529b\u548c\u7cbe\u786e\u89e3\u7684\u901f\u5ea6\u7684\u51fd\u6570\uff0c\u4ee5\u4fbf\u4ee5\u540e\u8ba1\u7b97\u8bef\u5dee\u3002\u8bf7\u6ce8\u610f\uff0c\u8fd9\u4e9b\u51fd\u6570\u5206\u522b\u6709\u4e00\u4e2a\u3001\u4e00\u4e2a\u548c <code>dim+1</code> \u4e2a\u5206\u91cf\uff0c\u6211\u4eec\u5c06\u5206\u91cf\u7684\u6570\u91cf\u4f20\u9012\u7ed9 <code>Function@<dim@></code> \u57fa\u7c7b\u3002\u5bf9\u4e8e\u7cbe\u786e\u89e3\uff0c\u6211\u4eec\u53ea\u58f0\u660e\u5b9e\u9645\u4e00\u6b21\u6027\u8fd4\u56de\u6574\u4e2a\u89e3\u5411\u91cf\uff08\u5373\u5176\u4e2d\u7684\u6240\u6709\u6210\u5206\uff09\u7684\u51fd\u6570\u3002\u4e0b\u9762\u662f\u5404\u81ea\u7684\u58f0\u660e\u3002\n\n  namespace PrescribedSolution \n  { \n    constexpr double alpha = 0.3; \n    constexpr double beta  = 1; \n\n    template <int dim> \n    class RightHandSide : public Function<dim> \n    { \n    public: \n      RightHandSide() \n        : Function<dim>(1) \n      {} \n\n      virtual double value(const Point<dim> & p, \n                           const unsigned int component = 0) const override; \n    }; \n\n    template <int dim> \n    class PressureBoundaryValues : public Function<dim> \n    { \n    public: \n      PressureBoundaryValues() \n        : Function<dim>(1) \n      {} \n\n      virtual double value(const Point<dim> & p, \n                           const unsigned int component = 0) const override; \n    }; \n\n    template <int dim> \n    class ExactSolution : public Function<dim> \n    { \n    public: \n      ExactSolution() \n        : Function<dim>(dim + 1) \n      {} \n\n      virtual void vector_value(const Point<dim> &p, \n                                Vector<double> &  value) const override; \n    }; \n\n// \u7136\u540e\u6211\u4eec\u8fd8\u5fc5\u987b\u5b9a\u4e49\u8fd9\u4e9b\u5404\u81ea\u7684\u51fd\u6570\uff0c\u5f53\u7136\u4e86\u3002\u9274\u4e8e\u6211\u4eec\u5728\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u4e86\u89e3\u51b3\u65b9\u6848\u5e94\u8be5\u662f\u600e\u6837\u7684\uff0c\u4e0b\u9762\u7684\u8ba1\u7b97\u5e94\u8be5\u662f\u5f88\u7b80\u5355\u7684\u3002\n\n    template <int dim> \n    double RightHandSide<dim>::value(const Point<dim> & /*p*/, \n                                     const unsigned int /*component*/) const \n    { \n      return 0; \n    } \n\n    template <int dim> \n    double \n    PressureBoundaryValues<dim>::value(const Point<dim> &p, \n                                       const unsigned int /*component*/) const \n    { \n      return -(alpha * p[0] * p[1] * p[1] / 2 + beta * p[0] - \n               alpha * p[0] * p[0] * p[0] / 6); \n    } \n\n    template <int dim> \n    void ExactSolution<dim>::vector_value(const Point<dim> &p, \n                                          Vector<double> &  values) const \n    { \n      Assert(values.size() == dim + 1, \n             ExcDimensionMismatch(values.size(), dim + 1)); \n\n      values(0) = alpha * p[1] * p[1] / 2 + beta - alpha * p[0] * p[0] / 2; \n      values(1) = alpha * p[0] * p[1]; \n      values(2) = -(alpha * p[0] * p[1] * p[1] / 2 + beta * p[0] - \n                    alpha * p[0] * p[0] * p[0] / 6); \n    } \n\n//  @sect3{The inverse permeability tensor}  \n\n// \u9664\u4e86\u5176\u4ed6\u65b9\u7a0b\u6570\u636e\u5916\uff0c\u6211\u4eec\u8fd8\u60f3\u4f7f\u7528\u6e17\u900f\u6027\u5f20\u91cf\uff0c\u6216\u8005\u66f4\u597d\u7684\u662f--\u56e0\u4e3a\u8fd9\u662f\u5728\u5f31\u5f62\u5f0f\u4e2d\u51fa\u73b0\u7684\u5168\u90e8\u5185\u5bb9--\u6e17\u900f\u6027\u5f20\u91cf\u7684\u9006\uff0c  <code>KInverse</code>  \u3002\u5bf9\u4e8e\u9a8c\u8bc1\u89e3\u7684\u7cbe\u786e\u6027\u548c\u786e\u5b9a\u6536\u655b\u987a\u5e8f\u7684\u76ee\u7684\u6765\u8bf4\uff0c\u8fd9\u4e2a\u5f20\u91cf\u7684\u4f5c\u7528\u5927\u4e8e\u5e2e\u52a9\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5c06\u7b80\u5355\u5730\u628a\u5b83\u8bbe\u7f6e\u4e3a\u540c\u4e00\u77e9\u9635\u3002\n\n// \u7136\u800c\uff0c\u5728\u73b0\u5b9e\u751f\u6d3b\u4e2d\u7684\u591a\u5b54\u4ecb\u8d28\u6d41\u52a8\u6a21\u62df\u4e2d\uff0c\u7a7a\u95f4\u53d8\u5316\u7684\u6e17\u900f\u7387\u5f20\u91cf\u662f\u4e0d\u53ef\u7f3a\u5c11\u7684\uff0c\u6211\u4eec\u60f3\u5229\u7528\u8fd9\u4e2a\u673a\u4f1a\u6765\u5c55\u793a\u4f7f\u7528\u5f20\u91cf\u503c\u51fd\u6570\u7684\u6280\u672f\u3002\n\n// \u53ef\u80fd\u4e0d\u8db3\u4e3a\u5947\uff0cdeal.II\u4e5f\u6709\u4e00\u4e2a\u57fa\u7c7b\uff0c\u4e0d\u4ec5\u9002\u7528\u4e8e\u6807\u91cf\u548c\u4e00\u822c\u7684\u77e2\u91cf\u503c\u51fd\u6570\uff08 <code>Function</code> \u57fa\u7c7b\uff09\uff0c\u4e5f\u9002\u7528\u4e8e\u8fd4\u56de\u56fa\u5b9a\u7ef4\u5ea6\u548c\u7b49\u7ea7\u7684\u5f20\u91cf\u7684\u51fd\u6570\uff0c <code>TensorFunction</code> \u6a21\u677f\u3002\u5728\u8fd9\u91cc\uff0c\u6240\u8003\u8651\u7684\u51fd\u6570\u8fd4\u56de\u4e00\u4e2adim-by-dim\u77e9\u9635\uff0c\u5373\u4e00\u4e2a\u7b49\u7ea7\u4e3a2\u3001\u7ef4\u5ea6\u4e3a <code>dim</code> \u7684\u5f20\u91cf\u3002\u7136\u540e\u6211\u4eec\u9002\u5f53\u5730\u9009\u62e9\u57fa\u7c7b\u7684\u6a21\u677f\u53c2\u6570\u3002\n\n//  <code>TensorFunction</code> \u7c7b\u63d0\u4f9b\u7684\u63a5\u53e3\u672c\u8d28\u4e0a\u7b49\u540c\u4e8e <code>Function</code> \u7c7b\u3002\u7279\u522b\u662f\uff0c\u5b58\u5728\u4e00\u4e2a <code>value_list</code> \u51fd\u6570\uff0c\u5b83\u63a5\u6536\u4e00\u4e2a\u8bc4\u4f30\u51fd\u6570\u7684\u70b9\u7684\u5217\u8868\uff0c\u5e76\u5728\u7b2c\u4e8c\u4e2a\u53c2\u6570\u4e2d\u8fd4\u56de\u51fd\u6570\u7684\u503c\uff0c\u4e00\u4e2a\u5f20\u91cf\u7684\u5217\u8868\u3002\n\n    template <int dim> \n    class KInverse : public TensorFunction<2, dim> \n    { \n    public: \n      KInverse() \n        : TensorFunction<2, dim>() \n      {} \n\n      virtual void \n      value_list(const std::vector<Point<dim>> &points, \n                 std::vector<Tensor<2, dim>> &  values) const override; \n    }; \n\n// \u5b9e\u73b0\u8d77\u6765\u5c31\u4e0d\u90a3\u4e48\u6709\u8da3\u4e86\u3002\u548c\u4ee5\u524d\u7684\u4f8b\u5b50\u4e00\u6837\uff0c\u6211\u4eec\u5728\u7c7b\u7684\u5f00\u5934\u6dfb\u52a0\u4e00\u4e2a\u68c0\u67e5\uff0c\u4ee5\u786e\u4fdd\u8f93\u5165\u548c\u8f93\u51fa\u53c2\u6570\u7684\u5927\u5c0f\u662f\u76f8\u540c\u7684\uff08\u5173\u4e8e\u8fd9\u4e2a\u6280\u672f\u7684\u8ba8\u8bba\u89c1 step-5 \uff09\u3002\u7136\u540e\u6211\u4eec\u5728\u6240\u6709\u7684\u8bc4\u4f30\u70b9\u4e0a\u5faa\u73af\uff0c\u5bf9\u4e8e\u6bcf\u4e00\u4e2a\u8bc4\u4f30\u70b9\uff0c\u5c06\u8f93\u51fa\u5f20\u91cf\u8bbe\u7f6e\u4e3a\u8eab\u4efd\u77e9\u9635\u3002\n\n// \u5728\u51fd\u6570\u7684\u9876\u90e8\u6709\u4e00\u4e2a\u5947\u602a\u7684\u5730\u65b9\uff08`(void)point;`\u8bed\u53e5\uff09\uff0c\u503c\u5f97\u8ba8\u8bba\u3002\u6211\u4eec\u653e\u5230\u8f93\u51fa`values`\u6570\u7ec4\u4e2d\u7684\u503c\u5b9e\u9645\u4e0a\u5e76\u4e0d\u53d6\u51b3\u4e8e\u51fd\u6570\u88ab\u8bc4\u4f30\u7684\u5750\u6807`points`\u6570\u7ec4\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c`points'\u53c2\u6570\u5b9e\u9645\u4e0a\u662f\u4e0d\u7528\u7684\uff0c\u5982\u679c\u6211\u4eec\u60f3\u7684\u8bdd\uff0c\u53ef\u4ee5\u4e0d\u7ed9\u5b83\u8d77\u540d\u5b57\u3002\u4f46\u662f\u6211\u4eec\u60f3\u7528`points`\u5bf9\u8c61\u6765\u68c0\u67e5`values`\u5bf9\u8c61\u662f\u5426\u6709\u6b63\u786e\u7684\u5927\u5c0f\u3002\u95ee\u9898\u662f\uff0c\u5728\u53d1\u5e03\u6a21\u5f0f\u4e0b\uff0c`AssertDimension`\u88ab\u5b9a\u4e49\u4e3a\u4e00\u4e2a\u5b8f\uff0c\u6269\u5c55\u4e3a\u7a7a\uff1b\u7136\u540e\u7f16\u8bd1\u5668\u4f1a\u62b1\u6028`points`\u5bf9\u8c61\u6ca1\u6709\u4f7f\u7528\u3002\u6d88\u9664\u8fd9\u4e2a\u8b66\u544a\u7684\u4e60\u60ef\u65b9\u6cd5\u662f\u6709\u4e00\u4e2a\u8bc4\u4f30\uff08\u8bfb\u53d6\uff09\u53d8\u91cf\u7684\u8bed\u53e5\uff0c\u4f46\u5b9e\u9645\u4e0a\u4e0d\u505a\u4efb\u4f55\u4e8b\u60c5\uff1a\u8fd9\u5c31\u662f`(void)points;`\u6240\u505a\u7684\uff1a\u5b83\u4ece`points`\u4e2d\u8bfb\u53d6\uff0c\u7136\u540e\u5c06\u8bfb\u53d6\u7684\u7ed3\u679c\u8f6c\u6362\u4e3a`void`\uff0c\u4e5f\u5c31\u662f\u4ec0\u4e48\u90fd\u6ca1\u6709\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u8fd9\u53e5\u8bdd\u662f\u5b8c\u5168\u6ca1\u6709\u610f\u4e49\u7684\uff0c\u9664\u4e86\u5411\u7f16\u8bd1\u5668\u89e3\u91ca\u662f\u7684\uff0c\u8fd9\u4e2a\u53d8\u91cf\u4e8b\u5b9e\u4e0a\u662f\u88ab\u4f7f\u7528\u7684\uff0c\u5373\u4f7f\u662f\u5728\u53d1\u5e03\u6a21\u5f0f\u4e0b\u3002(\u5728\u8c03\u8bd5\u6a21\u5f0f\u4e0b\uff0c`AssertDimension`\u5b8f\u4f1a\u6269\u5c55\u4e3a\u4ece\u53d8\u91cf\u4e2d\u8bfb\u51fa\u7684\u4e1c\u897f\uff0c\u6240\u4ee5\u5728\u8c03\u8bd5\u6a21\u5f0f\u4e0b\uff0c\u8fd9\u4e2a\u6709\u8da3\u7684\u8bed\u53e5\u662f\u6ca1\u6709\u5fc5\u8981\u7684)\u3002\n\n    template <int dim> \n    void KInverse<dim>::value_list(const std::vector<Point<dim>> &points, \n                                   std::vector<Tensor<2, dim>> &  values) const \n    { \n      (void)points; \n      AssertDimension(points.size(), values.size()); \n\n      for (auto &value : values) \n        value = unit_symmetric_tensor<dim>(); \n    } \n  } // namespace PrescribedSolution \n\n//  @sect3{MixedLaplaceProblem class implementation}  \n// @sect4{MixedLaplaceProblem::MixedLaplaceProblem}  \n\n// \u5728\u8fd9\u4e2a\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u9996\u5148\u5b58\u50a8\u4f20\u5165\u7684\u5173\u4e8e\u6211\u4eec\u5c06\u4f7f\u7528\u7684\u6709\u9650\u5143\u7684\u5ea6\u6570\u7684\u503c\uff08\u4f8b\u5982\uff0c\u5ea6\u6570\u4e3a0\uff0c\u610f\u5473\u7740\u4f7f\u7528RT(0)\u548cDG(0)\uff09\uff0c\u7136\u540e\u6784\u9020\u5c5e\u4e8e\u4ecb\u7ecd\u4e2d\u63cf\u8ff0\u7684\u7a7a\u95f4 $X_h$ \u7684\u5411\u91cf\u503c\u7684\u5143\u7d20\u3002\u6784\u9020\u51fd\u6570\u7684\u5176\u4f59\u90e8\u5206\u4e0e\u65e9\u671f\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e00\u6837\u3002\n\n// \u8fd9\u91cc\u552f\u4e00\u503c\u5f97\u63cf\u8ff0\u7684\u662f\uff0c\u8fd9\u4e2a\u53d8\u91cf\u6240\u5c5e\u7684 <code>fe</code> variable. The <code>FESystem</code> \u7c7b\u7684\u6784\u9020\u51fd\u6570\u8c03\u7528\u6709\u5f88\u591a\u4e0d\u540c\u7684\u6784\u9020\u51fd\u6570\uff0c\u5b83\u4eec\u90fd\u662f\u6307\u5c06\u8f83\u7b80\u5355\u7684\u5143\u7d20\u7ed1\u5b9a\u5728\u4e00\u8d77\uff0c\u6210\u4e3a\u4e00\u4e2a\u8f83\u5927\u7684\u5143\u7d20\u3002\u5728\u76ee\u524d\u7684\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u60f3\u628a\u4e00\u4e2aRT(\u5ea6)\u5143\u7d20\u4e0e\u4e00\u4e2aDQ(\u5ea6)\u5143\u7d20\u7ed3\u5408\u8d77\u6765\u3002\u8fd9\u6837\u505a\u7684 <code>FESystem</code> \u6784\u9020\u51fd\u6570\u8981\u6c42\u6211\u4eec\u9996\u5148\u6307\u5b9a\u7b2c\u4e00\u4e2a\u57fa\u672c\u5143\u7d20\uff08\u7ed9\u5b9a\u7a0b\u5ea6\u7684 <code>FE_RaviartThomas</code> \u5bf9\u8c61\uff09\uff0c\u7136\u540e\u6307\u5b9a\u8fd9\u4e2a\u57fa\u672c\u5143\u7d20\u7684\u526f\u672c\u6570\u91cf\uff0c\u7136\u540e\u7c7b\u4f3c\u5730\u6307\u5b9a <code>FE_DGQ</code> \u5143\u7d20\u7684\u79cd\u7c7b\u548c\u6570\u91cf\u3002\u6ce8\u610fRaviart-Thomas\u5143\u7d20\u5df2\u7ecf\u6709 <code>dim</code> \u4e2a\u77e2\u91cf\u5206\u91cf\uff0c\u6240\u4ee5\u8026\u5408\u5143\u7d20\u5c06\u6709 <code>dim+1</code> \u4e2a\u77e2\u91cf\u5206\u91cf\uff0c\u5176\u4e2d\u7b2c\u4e00\u4e2a <code>dim</code> \u4e2a\u5bf9\u5e94\u4e8e\u901f\u5ea6\u53d8\u91cf\uff0c\u6700\u540e\u4e00\u4e2a\u5bf9\u5e94\u4e8e\u538b\u529b\u3002\n\n// \u6211\u4eec\u4ece\u57fa\u672c\u5143\u7d20\u4e2d\u6784\u5efa\u8fd9\u4e2a\u5143\u7d20\u7684\u65b9\u5f0f\u4e0e\u6211\u4eec\u5728 step-8 \u4e2d\u7684\u65b9\u5f0f\u4e5f\u503c\u5f97\u6bd4\u8f83\uff1a\u5728\u90a3\u91cc\uff0c\u6211\u4eec\u5c06\u5176\u6784\u5efa\u4e3a <code>fe (FE_Q@<dim@>(1), dim)</code> \uff0c\u5373\u6211\u4eec\u7b80\u5355\u5730\u4f7f\u7528 <code>dim</code> copies of the <code>FE_Q(1)</code> \u5143\u7d20\uff0c\u6bcf\u4e2a\u5750\u6807\u65b9\u5411\u4e0a\u7684\u4f4d\u79fb\u90fd\u6709\u4e00\u4efd\u3002\n\n  template <int dim> \n  MixedLaplaceProblem<dim>::MixedLaplaceProblem(const unsigned int degree) \n    : degree(degree) \n    , fe(FE_RaviartThomas<dim>(degree), 1, FE_DGQ<dim>(degree), 1) \n    , dof_handler(triangulation) \n  {} \n\n//  @sect4{MixedLaplaceProblem::make_grid_and_dofs}  \n\n// \u63a5\u4e0b\u6765\u7684\u51fd\u6570\u5f00\u59cb\u4e8e\u4f17\u6240\u5468\u77e5\u7684\u51fd\u6570\u8c03\u7528\uff0c\u521b\u5efa\u548c\u7ec6\u5316\u4e00\u4e2a\u7f51\u683c\uff0c\u7136\u540e\u5c06\u81ea\u7531\u5ea6\u4e0e\u4e4b\u5173\u8054\u3002\n\n  template <int dim> \n  void MixedLaplaceProblem<dim>::make_grid_and_dofs() \n  { \n    GridGenerator::hyper_cube(triangulation, -1, 1); \n    triangulation.refine_global(5); \n\n    dof_handler.distribute_dofs(fe); \n\n// \u7136\u800c\uff0c\u63a5\u4e0b\u6765\u4e8b\u60c5\u5c31\u53d8\u5f97\u4e0d\u540c\u4e86\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\uff0c\u6211\u4eec\u8981\u5c06\u77e9\u9635\u7ec6\u5206\u4e3a\u5bf9\u5e94\u4e8e\u901f\u5ea6\u548c\u538b\u529b\u8fd9\u4e24\u79cd\u4e0d\u540c\u7684\u53d8\u91cf\u7684\u5757\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u8981\u786e\u4fdd\u4e0e\u901f\u5ea6\u548c\u538b\u529b\u76f8\u5bf9\u5e94\u7684\u6307\u6570\u4e0d\u4f1a\u6df7\u5728\u4e00\u8d77\u3002\u9996\u5148\u662f\u6240\u6709\u901f\u5ea6\u81ea\u7531\u5ea6\uff0c\u7136\u540e\u662f\u6240\u6709\u538b\u529b\u81ea\u7531\u5ea6\u3002\u8fd9\u6837\u4e00\u6765\uff0c\u5168\u5c40\u77e9\u9635\u5c31\u5f88\u597d\u5730\u5206\u79bb\u6210\u4e00\u4e2a $2 \\times 2$ \u7cfb\u7edf\u3002\u4e3a\u4e86\u8fbe\u5230\u8fd9\u4e2a\u76ee\u7684\uff0c\u6211\u4eec\u5fc5\u987b\u6839\u636e\u81ea\u7531\u5ea6\u7684\u77e2\u91cf\u5206\u91cf\u5bf9\u5176\u91cd\u65b0\u7f16\u53f7\uff0c\u8fd9\u4e2a\u64cd\u4f5c\u5df2\u7ecf\u5f88\u65b9\u4fbf\u5730\u5b9e\u73b0\u4e86\u3002\n\n    DoFRenumbering::component_wise(dof_handler); \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u8981\u5f04\u6e05\u695a\u8fd9\u4e9b\u5757\u7684\u5927\u5c0f\uff0c\u4ee5\u4fbf\u6211\u4eec\u53ef\u4ee5\u5206\u914d\u9002\u5f53\u7684\u7a7a\u95f4\u91cf\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u8c03\u7528\u4e86 DoFTools::count_dofs_per_fe_component() \u51fd\u6570\uff0c\u8be5\u51fd\u6570\u8ba1\u7b97\u4e86\u67d0\u4e2a\u5411\u91cf\u5206\u91cf\u7684\u5f62\u72b6\u51fd\u6570\u975e\u96f6\u7684\u6570\u91cf\u3002\u6211\u4eec\u6709 <code>dim+1</code> \u4e2a\u5411\u91cf\u5206\u91cf\uff0c DoFTools::count_dofs_per_fe_component() \u5c06\u8ba1\u7b97\u6709\u591a\u5c11\u4e2a\u5f62\u72b6\u51fd\u6570\u5c5e\u4e8e\u8fd9\u4e9b\u5206\u91cf\u4e2d\u7684\u6bcf\u4e2a\u3002\n\n// \u8fd9\u91cc\u6709\u4e00\u4e2a\u95ee\u9898\u3002\u6b63\u5982\u8be5\u51fd\u6570\u7684\u6587\u6863\u6240\u63cf\u8ff0\u7684\uff0c\u5b83 <i>wants</i> \u5c06  $x$  -\u901f\u5ea6\u5f62\u72b6\u51fd\u6570\u7684\u6570\u91cf\u653e\u5165  <code>dofs_per_component[0]</code>  \u4e2d\uff0c\u5c06  $y$  -\u901f\u5ea6\u5f62\u72b6\u51fd\u6570\u7684\u6570\u91cf\u653e\u5165  <code>dofs_per_component[1]</code>  \u4e2d\uff08\u4ee5\u53ca\u7c7b\u4f3c\u76843d\uff09\uff0c\u5e76\u5c06\u538b\u529b\u5f62\u72b6\u51fd\u6570\u7684\u6570\u91cf\u653e\u5165  <code>dofs_per_component[dim]</code>  \u4e2d \u3002\u4f46\u662f\uff0cRaviart-Thomas\u5143\u7d20\u7684\u7279\u6b8a\u6027\u5728\u4e8e\u5b83\u662f\u975e @ref GlossPrimitive \"\u539f\u59cb \"\u7684\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5bf9\u4e8eRaviart-Thomas\u5143\u7d20\uff0c\u6240\u6709\u7684\u901f\u5ea6\u5f62\u72b6\u51fd\u6570\u5728\u6240\u6709\u5206\u91cf\u4e2d\u90fd\u662f\u975e\u96f6\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u8be5\u51fd\u6570\u4e0d\u80fd\u533a\u5206 $x$ \u548c $y$ \u901f\u5ea6\u51fd\u6570\uff0c\u56e0\u4e3a<i>is</i>\u6ca1\u6709\u8fd9\u79cd\u533a\u5206\u3002\u56e0\u6b64\uff0c\u5b83\u5c06\u901f\u5ea6\u7684\u603b\u4f53\u6570\u91cf\u653e\u5165 <code>dofs_per_component[c]</code>  ,  $0\\le c\\le \\text{dim}$ \u4e2d\u7684\u6bcf\u4e00\u4e2a\u3002\u53e6\u4e00\u65b9\u9762\uff0c\u538b\u529b\u53d8\u91cf\u7684\u6570\u91cf\u7b49\u4e8e\u5728dim-th\u5206\u91cf\u4e2d\u4e0d\u4e3a\u96f6\u7684\u5f62\u72b6\u51fd\u6570\u7684\u6570\u91cf\u3002\n\n// \u5229\u7528\u8fd9\u4e9b\u77e5\u8bc6\uff0c\u6211\u4eec\u53ef\u4ee5\u4ece <code>dofs_per_component</code> \u7684\u7b2c\u4e00\u4e2a <code>dim</code> \u5143\u7d20\u4e2d\u7684\u4efb\u4f55\u4e00\u4e2a\u5f97\u5230\u901f\u5ea6\u5f62\u72b6\u51fd\u6570\u7684\u6570\u91cf\uff0c\u7136\u540e\u7528\u4e0b\u9762\u8fd9\u4e2a\u6765\u521d\u59cb\u5316\u5411\u91cf\u548c\u77e9\u9635\u5757\u7684\u5927\u5c0f\uff0c\u4ee5\u53ca\u521b\u5efa\u8f93\u51fa\u3002\n\n//  @note  \u5982\u679c\u4f60\u89c9\u5f97\u8fd9\u4e2a\u6982\u5ff5\u96be\u4ee5\u7406\u89e3\uff0c\u4f60\u53ef\u4ee5\u8003\u8651\u7528\u51fd\u6570  DoFTools::count_dofs_per_fe_block()  \u6765\u4ee3\u66ff\uff0c\u5c31\u50cf\u6211\u4eec\u5728  step-22  \u7684\u76f8\u5e94\u4ee3\u7801\u4e2d\u505a\u7684\u90a3\u6837\u3002\u4f60\u53ef\u80fd\u8fd8\u60f3\u9605\u8bfb\u4e00\u4e0b\u672f\u8bed\u8868\u4e2d @ref GlossBlock \"\u5757 \"\u548c @ref GlossComponent \"\u7ec4\u4ef6 \"\u7684\u533a\u522b\u3002\n\n    const std::vector<types::global_dof_index> dofs_per_component = \n      DoFTools::count_dofs_per_fe_component(dof_handler); \n    const unsigned int n_u = dofs_per_component[0], \n                       n_p = dofs_per_component[dim]; \n\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              << \"Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << \" (\" << n_u << '+' << n_p << ')' << std::endl; \n\n// \u4e0b\u4e00\u4e2a\u4efb\u52a1\u662f\u4e3a\u6211\u4eec\u5c06\u8981\u521b\u5efa\u7684\u77e9\u9635\u5206\u914d\u4e00\u4e2a\u7a00\u758f\u6a21\u5f0f\u3002\u6211\u4eec\u4f7f\u7528\u4e0e\u524d\u9762\u6b65\u9aa4\u4e00\u6837\u7684\u538b\u7f29\u7a00\u758f\u6a21\u5f0f\uff0c\u4f46\u662f\u7531\u4e8e <code>system_matrix</code> \u662f\u4e00\u4e2a\u5757\u72b6\u77e9\u9635\uff0c\u6211\u4eec\u4f7f\u7528 <code>BlockDynamicSparsityPattern</code> \u7c7b\uff0c\u800c\u4e0d\u4ec5\u4ec5\u662f <code>DynamicSparsityPattern</code>  \u3002\u8fd9\u79cd\u5757\u72b6\u7a00\u758f\u6a21\u5f0f\u5728 $2 \\times 2$ \u6a21\u5f0f\u4e0b\u6709\u56db\u4e2a\u5757\u3002\u5757\u7684\u5927\u5c0f\u53d6\u51b3\u4e8e <code>n_u</code> and <code>n_p</code> \uff0c\u5b83\u6301\u6709\u901f\u5ea6\u548c\u538b\u529b\u53d8\u91cf\u7684\u6570\u91cf\u3002\u5728\u7b2c\u4e8c\u6b65\u4e2d\uff0c\u6211\u4eec\u5fc5\u987b\u6307\u793a\u5757\u7cfb\u7edf\u66f4\u65b0\u5b83\u6240\u7ba1\u7406\u7684\u5757\u7684\u5927\u5c0f\u7684\u77e5\u8bc6\uff1b\u8fd9\u53d1\u751f\u5728 <code>dsp.collect_sizes ()</code> \u7684\u8c03\u7528\u4e2d\u3002\n\n    BlockDynamicSparsityPattern dsp(2, 2); \n    dsp.block(0, 0).reinit(n_u, n_u); \n    dsp.block(1, 0).reinit(n_p, n_u); \n    dsp.block(0, 1).reinit(n_u, n_p); \n    dsp.block(1, 1).reinit(n_p, n_p); \n    dsp.collect_sizes(); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp); \n\n// \u6211\u4eec\u4ee5\u4e0e\u975e\u533a\u5757\u7248\u672c\u76f8\u540c\u7684\u65b9\u5f0f\u4f7f\u7528\u538b\u7f29\u7684\u533a\u5757\u7a00\u758f\u6a21\u5f0f\uff0c\u4ee5\u521b\u5efa\u7a00\u758f\u6a21\u5f0f\uff0c\u7136\u540e\u521b\u5efa\u7cfb\u7edf\u77e9\u9635\u3002\n\n    sparsity_pattern.copy_from(dsp); \n    system_matrix.reinit(sparsity_pattern); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u5fc5\u987b\u4ee5\u4e0e\u5757\u538b\u7f29\u7a00\u758f\u5ea6\u6a21\u5f0f\u5b8c\u5168\u76f8\u540c\u7684\u65b9\u5f0f\u8c03\u6574\u89e3\u51b3\u65b9\u6848\u548c\u53f3\u4fa7\u5411\u91cf\u7684\u5927\u5c0f\u3002\n\n    solution.reinit(2); \n    solution.block(0).reinit(n_u); \n    solution.block(1).reinit(n_p); \n    solution.collect_sizes(); \n\n    system_rhs.reinit(2); \n    system_rhs.block(0).reinit(n_u); \n    system_rhs.block(1).reinit(n_p); \n    system_rhs.collect_sizes(); \n  } \n// @sect4{MixedLaplaceProblem::assemble_system}  \n\n// \u540c\u6837\u5730\uff0c\u7ec4\u88c5\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\u5728\u8fd9\u4e2a\u4f8b\u5b50\u7684\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u5f88\u591a\u4e86\u3002\u5728\u5b83\u7684\u9876\u90e8\uff0c\u53d1\u751f\u7684\u662f\u6240\u6709\u5e38\u89c1\u7684\u6b65\u9aa4\uff0c\u6b64\u5916\uff0c\u6211\u4eec\u4e0d\u4ec5\u4e3a\u5355\u5143\u9879\u5206\u914d\u6b63\u4ea4\u548c <code>FEValues</code> \u5bf9\u8c61\uff0c\u800c\u4e14\u8fd8\u4e3a\u9762\u9879\u5206\u914d\u3002\u4e4b\u540e\uff0c\u6211\u4eec\u4e3a\u53d8\u91cf\u5b9a\u4e49\u901a\u5e38\u7684\u7f29\u5199\uff0c\u5e76\u4e3a\u672c\u5730\u77e9\u9635\u548c\u53f3\u624b\u8d21\u732e\u5206\u914d\u7a7a\u95f4\uff0c\u4ee5\u53ca\u4fdd\u5b58\u5f53\u524d\u5355\u5143\u7684\u5168\u5c40\u81ea\u7531\u5ea6\u6570\u7684\u6570\u7ec4\u3002\n\n  template <int dim> \n  void MixedLaplaceProblem<dim>::assemble_system() \n  { \n    QGauss<dim>     quadrature_formula(degree + 2); \n    QGauss<dim - 1> face_quadrature_formula(degree + 2); \n\n    FEValues<dim>     fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | update_JxW_values); \n    FEFaceValues<dim> fe_face_values(fe, \n                                     face_quadrature_formula, \n                                     update_values | update_normal_vectors | \n                                       update_quadrature_points | \n                                       update_JxW_values); \n\n    const unsigned int dofs_per_cell   = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points      = quadrature_formula.size(); \n    const unsigned int n_face_q_points = face_quadrature_formula.size(); \n\n    FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<double>     local_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n// \u4e0b\u4e00\u6b65\u662f\u58f0\u660e\u4ee3\u8868\u65b9\u7a0b\u4e2d\u6e90\u9879\u3001\u538b\u529b\u8fb9\u754c\u503c\u548c\u7cfb\u6570\u7684\u5bf9\u8c61\u3002\u9664\u4e86\u8fd9\u4e9b\u4ee3\u8868\u8fde\u7eed\u51fd\u6570\u7684\u5bf9\u8c61\u5916\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u6570\u7ec4\u6765\u4fdd\u5b58\u5b83\u4eec\u5728\u5404\u4e2a\u5355\u5143\u683c\uff08\u6216\u9762\uff0c\u5bf9\u4e8e\u8fb9\u754c\u503c\uff09\u7684\u6b63\u4ea4\u70b9\u7684\u503c\u3002\u8bf7\u6ce8\u610f\uff0c\u5728\u7cfb\u6570\u7684\u60c5\u51b5\u4e0b\uff0c\u6570\u7ec4\u5fc5\u987b\u662f\u77e9\u9635\u7684\u4e00\u79cd\u3002\n\n    const PrescribedSolution::RightHandSide<dim> right_hand_side; \n    const PrescribedSolution::PressureBoundaryValues<dim> \n                                            pressure_boundary_values; \n    const PrescribedSolution::KInverse<dim> k_inverse; \n\n    std::vector<double>         rhs_values(n_q_points); \n    std::vector<double>         boundary_values(n_face_q_points); \n    std::vector<Tensor<2, dim>> k_inverse_values(n_q_points); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u9700\u8981\u51e0\u4e2a\u63d0\u53d6\u5668\uff0c\u7528\u6765\u83b7\u53d6\u77e2\u91cf\u503c\u5f62\u72b6\u51fd\u6570\u7684\u901f\u5ea6\u548c\u538b\u529b\u6210\u5206\u3002\u5b83\u4eec\u7684\u529f\u80fd\u548c\u4f7f\u7528\u5728 @ref vector_valued\u62a5\u544a\u4e2d\u6709\u8be6\u7ec6\u63cf\u8ff0\u3002\u57fa\u672c\u4e0a\uff0c\u6211\u4eec\u5c06\u628a\u5b83\u4eec\u4f5c\u4e3a\u4e0b\u9762FEValues\u5bf9\u8c61\u7684\u4e0b\u6807\uff1aFEValues\u5bf9\u8c61\u63cf\u8ff0\u4e86\u5f62\u72b6\u51fd\u6570\u7684\u6240\u6709\u77e2\u91cf\u5206\u91cf\uff0c\u800c\u5728\u8ba2\u9605\u540e\uff0c\u5b83\u5c06\u53ea\u6307\u901f\u5ea6\uff08\u4e00\u7ec4\u4ece\u96f6\u5206\u91cf\u5f00\u59cb\u7684 <code>dim</code> \u5206\u91cf\uff09\u6216\u538b\u529b\uff08\u4f4d\u4e8e <code>dim</code> \u4f4d\u7f6e\u7684\u6807\u91cf\u5206\u91cf\uff09\u3002\n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure(dim); \n\n// \u6709\u4e86\u8fd9\u4e9b\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u7ee7\u7eed\u5bf9\u6240\u6709\u5355\u5143\u8fdb\u884c\u5faa\u73af\u3002\u8fd9\u4e2a\u5faa\u73af\u7684\u4e3b\u4f53\u5df2\u7ecf\u5728\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u8fc7\u4e86\uff0c\u8fd9\u91cc\u5c31\u4e0d\u518d\u505a\u4efb\u4f55\u8bc4\u8bba\u4e86\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        fe_values.reinit(cell); \n        local_matrix = 0; \n        local_rhs    = 0; \n\n        right_hand_side.value_list(fe_values.get_quadrature_points(), \n                                   rhs_values); \n        k_inverse.value_list(fe_values.get_quadrature_points(), \n                             k_inverse_values); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            { \n              const Tensor<1, dim> phi_i_u = fe_values[velocities].value(i, q); \n              const double div_phi_i_u = fe_values[velocities].divergence(i, q); \n              const double phi_i_p     = fe_values[pressure].value(i, q); \n\n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                { \n                  const Tensor<1, dim> phi_j_u = \n                    fe_values[velocities].value(j, q); \n                  const double div_phi_j_u = \n                    fe_values[velocities].divergence(j, q); \n                  const double phi_j_p = fe_values[pressure].value(j, q); \n\n                  local_matrix(i, j) += \n                    (phi_i_u * k_inverse_values[q] * phi_j_u // \n                     - phi_i_p * div_phi_j_u                 // \n                     - div_phi_i_u * phi_j_p)                // \n                    * fe_values.JxW(q); \n                } \n\n              local_rhs(i) += -phi_i_p * rhs_values[q] * fe_values.JxW(q); \n            } \n\n        for (const auto &face : cell->face_iterators()) \n          if (face->at_boundary()) \n            { \n              fe_face_values.reinit(cell, face); \n\n              pressure_boundary_values.value_list( \n                fe_face_values.get_quadrature_points(), boundary_values); \n\n              for (unsigned int q = 0; q < n_face_q_points; ++q) \n                for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                  local_rhs(i) += -(fe_face_values[velocities].value(i, q) * // \n                                    fe_face_values.normal_vector(q) *        // \n                                    boundary_values[q] *                     // \n                                    fe_face_values.JxW(q)); \n            } \n\n// \u5faa\u73af\u6240\u6709\u5355\u5143\u7684\u6700\u540e\u4e00\u6b65\u662f\u5c06\u5c40\u90e8\u8d21\u732e\u8f6c\u79fb\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u624b\u5411\u91cf\u4e2d\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u4f7f\u7528\u7684\u63a5\u53e3\u4e0e\u4e4b\u524d\u7684\u4f8b\u5b50\u5b8c\u5168\u76f8\u540c\uff0c\u5c3d\u7ba1\u6211\u4eec\u73b0\u5728\u4f7f\u7528\u7684\u662f\u5757\u72b6\u77e9\u9635\u548c\u5411\u91cf\uff0c\u800c\u4e0d\u662f\u5e38\u89c4\u7684\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u5bf9\u4e8e\u5916\u754c\u6765\u8bf4\uff0c\u5757\u5bf9\u8c61\u5177\u6709\u4e0e\u77e9\u9635\u548c\u5411\u91cf\u76f8\u540c\u7684\u63a5\u53e3\uff0c\u4f46\u5b83\u4eec\u8fd8\u5141\u8bb8\u8bbf\u95ee\u5355\u4e2a\u5757\u3002\n\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            system_matrix.add(local_dof_indices[i], \n                              local_dof_indices[j], \n                              local_matrix(i, j)); \n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          system_rhs(local_dof_indices[i]) += local_rhs(i); \n      } \n  } \n// @sect3{Implementation of linear solvers and preconditioners}  \n\n// \u6211\u4eec\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\u4f7f\u7528\u7684\u7ebf\u6027\u6c42\u89e3\u5668\u548c\u9884\u5904\u7406\u5668\u5df2\u7ecf\u5728\u4ecb\u7ecd\u4e2d\u8fdb\u884c\u4e86\u8be6\u7ec6\u7684\u8ba8\u8bba\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u4e0d\u518d\u8ba8\u8bba\u6211\u4eec\u7684\u65b9\u6cd5\u7684\u539f\u7406\uff0c\u800c\u53ea\u662f\u5bf9\u5269\u4e0b\u7684\u4e00\u4e9b\u5b9e\u73b0\u65b9\u9762\u8fdb\u884c\u8bc4\u8bba\u3002\n\n//  @sect4{MixedLaplace::solve}  \n\n// \u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u6982\u8ff0\u7684\u90a3\u6837\uff0c\u6c42\u89e3\u51fd\u6570\u57fa\u672c\u4e0a\u7531\u4e24\u4e2a\u6b65\u9aa4\u7ec4\u6210\u3002\u9996\u5148\uff0c\u6211\u4eec\u5fc5\u987b\u5f62\u6210\u6d89\u53ca\u8212\u5c14\u8865\u6570\u7684\u7b2c\u4e00\u4e2a\u65b9\u7a0b\uff0c\u5e76\u6c42\u89e3\u538b\u529b\uff08\u89e3\u51b3\u65b9\u6848\u7684\u7b2c\u4e00\u90e8\u5206\uff09\u3002\u7136\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u4ece\u7b2c\u4e8c\u4e2a\u65b9\u7a0b\uff08\u89e3\u7684\u7b2c0\u90e8\u5206\uff09\u4e2d\u91cd\u6784\u901f\u5ea6\u3002\n\n  template <int dim> \n  void MixedLaplaceProblem<dim>::solve() \n  { \n\n// \u4f5c\u4e3a\u7b2c\u4e00\u6b65\uff0c\u6211\u4eec\u58f0\u660e\u5bf9\u77e9\u9635\u7684\u6240\u6709\u5757\u72b6\u6210\u5206\u3001\u53f3\u624b\u8fb9\u548c\u6211\u4eec\u5c06\u9700\u8981\u7684\u89e3\u5411\u91cf\u7684\u5f15\u7528\u3002\n\n    const auto &M = system_matrix.block(0, 0); \n    const auto &B = system_matrix.block(0, 1); \n\n    const auto &F = system_rhs.block(0); \n    const auto &G = system_rhs.block(1); \n\n    auto &U = solution.block(0); \n    auto &P = solution.block(1); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u5c06\u521b\u5efa\u76f8\u5e94\u7684LinearOperator\u5bf9\u8c61\u5e76\u521b\u5efa <code>op_M_inv</code> \u8fd0\u7b97\u5668\u3002\n\n    const auto op_M = linear_operator(M); \n    const auto op_B = linear_operator(B); \n\n    ReductionControl         reduction_control_M(2000, 1.0e-18, 1.0e-10); \n    SolverCG<Vector<double>> solver_M(reduction_control_M); \n    PreconditionJacobi<SparseMatrix<double>> preconditioner_M; \n\n    preconditioner_M.initialize(M); \n\n    const auto op_M_inv = inverse_operator(op_M, solver_M, preconditioner_M); \n\n// \u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u58f0\u660e\u8212\u5c14\u8865\u6570  <code>op_S</code>  \u548c\u8fd1\u4f3c\u8212\u5c14\u8865\u6570  <code>op_aS</code>  \u3002\n\n    const auto op_S = transpose_operator(op_B) * op_M_inv * op_B; \n    const auto op_aS = \n      transpose_operator(op_B) * linear_operator(preconditioner_M) * op_B; \n\n// \u6211\u4eec\u73b0\u5728\u4ece <code>op_aS</code> \u4e2d\u521b\u5efa\u4e00\u4e2a\u9884\u5904\u7406\u7a0b\u5e8f\uff0c\u5e94\u7528\u56fa\u5b9a\u6570\u91cf\u768430\u6b21\uff08\u4fbf\u5b9c\u7684\uff09CG\u8fed\u4ee3\u3002\n\n    IterationNumberControl   iteration_number_control_aS(30, 1.e-18); \n    SolverCG<Vector<double>> solver_aS(iteration_number_control_aS); \n\n    const auto preconditioner_S = \n      inverse_operator(op_aS, solver_aS, PreconditionIdentity()); \n\n// \u73b0\u5728\u6765\u770b\u770b\u7b2c\u4e00\u4e2a\u65b9\u7a0b\u3002\u5b83\u7684\u53f3\u8fb9\u662f $B^TM^{-1}F-G$  \uff0c\u8fd9\u5c31\u662f\u6211\u4eec\u5728\u524d\u51e0\u884c\u8ba1\u7b97\u7684\u7ed3\u679c\u3002\u7136\u540e\u6211\u4eec\u7528CG\u6c42\u89e3\u5668\u548c\u6211\u4eec\u521a\u521a\u58f0\u660e\u7684\u9884\u5904\u7406\u7a0b\u5e8f\u6765\u89e3\u51b3\u7b2c\u4e00\u4e2a\u65b9\u7a0b\u3002\n\n    const auto schur_rhs = transpose_operator(op_B) * op_M_inv * F - G; \n\n    SolverControl            solver_control_S(2000, 1.e-12); \n    SolverCG<Vector<double>> solver_S(solver_control_S); \n\n    const auto op_S_inv = inverse_operator(op_S, solver_S, preconditioner_S); \n\n    P = op_S_inv * schur_rhs; \n\n    std::cout << solver_control_S.last_step() \n              << \" CG Schur complement iterations to obtain convergence.\" \n              << std::endl; \n\n// \u5f97\u5230\u538b\u529b\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u8ba1\u7b97\u901f\u5ea6\u3002\u65b9\u7a0b\u4e3a $MU=-BP+F$  \uff0c\u6211\u4eec\u901a\u8fc7\u9996\u5148\u8ba1\u7b97\u53f3\u624b\u8fb9\uff0c\u7136\u540e\u4e0e\u4ee3\u8868\u8d28\u91cf\u77e9\u9635\u9006\u7684\u5bf9\u8c61\u76f8\u4e58\u6765\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u3002\n\n    U = op_M_inv * (F - op_B * P); \n  } \n// @sect3{MixedLaplaceProblem class implementation (continued)}  \n// @sect4{MixedLaplace::compute_errors}  \n\n// \u5728\u6211\u4eec\u5904\u7406\u5b8c\u7ebf\u6027\u6c42\u89e3\u5668\u548c\u9884\u5904\u7406\u5668\u4e4b\u540e\uff0c\u6211\u4eec\u7ee7\u7eed\u5b9e\u73b0\u6211\u4eec\u7684\u4e3b\u7c7b\u3002\u7279\u522b\u662f\uff0c\u4e0b\u4e00\u4e2a\u4efb\u52a1\u662f\u8ba1\u7b97\u6211\u4eec\u6570\u503c\u89e3\u7684\u8bef\u5dee\uff0c\u5305\u62ec\u538b\u529b\u548c\u901f\u5ea6\u3002\n\n// \u4e3a\u4e86\u8ba1\u7b97\u89e3\u7684\u8bef\u5dee\uff0c\u6211\u4eec\u5df2\u7ecf\u5728  step-7  \u548c  step-11  \u4e2d\u4ecb\u7ecd\u4e86  <code>VectorTools::integrate_difference</code>  \u51fd\u6570\u3002\u7136\u800c\uff0c\u5728\u90a3\u91cc\u6211\u4eec\u53ea\u5904\u7406\u4e86\u6807\u91cf\u89e3\uff0c\u800c\u5728\u8fd9\u91cc\u6211\u4eec\u6709\u4e00\u4e2a\u77e2\u91cf\u503c\u7684\u89e3\uff0c\u5176\u7ec4\u6210\u90e8\u5206\u751a\u81f3\u8868\u793a\u4e0d\u540c\u7684\u91cf\uff0c\u5e76\u4e14\u53ef\u80fd\u6709\u4e0d\u540c\u7684\u6536\u655b\u9636\u6570\uff08\u7531\u4e8e\u6240\u4f7f\u7528\u7684\u6709\u9650\u5143\u7684\u9009\u62e9\uff0c\u8fd9\u91cc\u4e0d\u662f\u8fd9\u79cd\u60c5\u51b5\uff0c\u4f46\u5728\u6df7\u5408\u6709\u9650\u5143\u5e94\u7528\u4e2d\u7ecf\u5e38\u51fa\u73b0\u8fd9\u79cd\u60c5\u51b5\uff09\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u8981\u505a\u7684\u662f \"\u63a9\u76d6 \"\u6211\u4eec\u611f\u5174\u8da3\u7684\u6210\u5206\u3002\u8fd9\u5f88\u5bb9\u6613\u505a\u5230\uff1a <code>VectorTools::integrate_difference</code> \u51fd\u6570\u5c06\u4e00\u4e2a\u6307\u5411\u6743\u91cd\u51fd\u6570\u7684\u6307\u9488\u4f5c\u4e3a\u5176\u53c2\u6570\u4e4b\u4e00\uff08\u8be5\u53c2\u6570\u9ed8\u8ba4\u4e3a\u7a7a\u6307\u9488\uff0c\u610f\u5473\u7740\u5355\u4f4d\u6743\u91cd\uff09\u3002\u6211\u4eec\u8981\u505a\u7684\u662f\u4f20\u9012\u4e00\u4e2a\u51fd\u6570\u5bf9\u8c61\uff0c\u5728\u6211\u4eec\u611f\u5174\u8da3\u7684\u6210\u5206\u4e2d\u7b49\u4e8e1\uff0c\u800c\u5728\u5176\u4ed6\u6210\u5206\u4e2d\u7b49\u4e8e0\u3002\u4f8b\u5982\uff0c\u4e3a\u4e86\u8ba1\u7b97\u538b\u529b\u8bef\u5dee\uff0c\u6211\u4eec\u5e94\u8be5\u4f20\u5165\u4e00\u4e2a\u51fd\u6570\uff0c\u8be5\u51fd\u6570\u5728\u5206\u91cf <code>dim</code> \u4e2d\u4ee3\u8868\u5355\u4f4d\u503c\u7684\u5e38\u6570\u5411\u91cf\uff0c\u800c\u5bf9\u4e8e\u901f\u5ea6\uff0c\u5e38\u6570\u5411\u91cf\u5728\u7b2c\u4e00\u4e2a <code>dim</code> \u5206\u91cf\u4e2d\u5e94\u8be5\u662f1\uff0c\u800c\u5728\u538b\u529b\u7684\u4f4d\u7f6e\u662f0\u3002\n\n// \u5728deal.II\u4e2d\uff0c <code>ComponentSelectFunction</code> \u6b63\u662f\u8fd9\u6837\u505a\u7684\uff1a\u5b83\u60f3\u77e5\u9053\u5b83\u8981\u8868\u793a\u7684\u51fd\u6570\u5e94\u8be5\u6709\u591a\u5c11\u4e2a\u5411\u91cf\u5206\u91cf\uff08\u5728\u6211\u4eec\u7684\u4f8b\u5b50\u4e2d\uff0c\u8fd9\u5c06\u662f <code>dim+1</code> \uff0c\u7528\u4e8e\u8054\u5408\u901f\u5ea6-\u538b\u529b\u7a7a\u95f4\uff09\uff0c\u54ea\u4e2a\u4e2a\u4f53\u6216\u8303\u56f4\u7684\u5206\u91cf\u5e94\u8be5\u7b49\u4e8e1\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5728\u51fd\u6570\u7684\u5f00\u5934\u5b9a\u4e49\u4e86\u4e24\u4e2a\u8fd9\u6837\u7684\u63a9\u7801\uff0c\u63a5\u4e0b\u6765\u662f\u4e00\u4e2a\u4ee3\u8868\u7cbe\u786e\u89e3\u7684\u5bf9\u8c61\u548c\u4e00\u4e2a\u5411\u91cf\uff0c\u6211\u4eec\u5c06\u5728\u5176\u4e2d\u5b58\u50a8\u7531 <code>integrate_difference</code> \u8ba1\u7b97\u7684\u5355\u5143\u8bef\u5dee\u3002\n\n  template <int dim> \n  void MixedLaplaceProblem<dim>::compute_errors() const \n  { \n    const ComponentSelectFunction<dim> pressure_mask(dim, dim + 1); \n    const ComponentSelectFunction<dim> velocity_mask(std::make_pair(0, dim), \n                                                     dim + 1); \n\n    PrescribedSolution::ExactSolution<dim> exact_solution; \n    Vector<double> cellwise_errors(triangulation.n_active_cells()); \n\n// \u6b63\u5982\u5728 step-7 \u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u7684\u90a3\u6837\uff0c\u6211\u4eec\u5fc5\u987b\u8ba4\u8bc6\u5230\uff0c\u4e0d\u53ef\u80fd\u7cbe\u786e\u5730\u6574\u5408\u8bef\u5dee\u3002\u6211\u4eec\u6240\u80fd\u505a\u7684\u5c31\u662f\u7528\u6b63\u4ea4\u6cd5\u5bf9\u8fd9\u4e2a\u79ef\u5206\u8fdb\u884c\u8fd1\u4f3c\u3002\u8fd9\u5b9e\u9645\u4e0a\u5728\u8fd9\u91cc\u63d0\u51fa\u4e86\u4e00\u4e2a\u5c0f\u5c0f\u7684\u8f6c\u6298\uff1a\u5982\u679c\u6211\u4eec\u50cf\u4eba\u4eec\u53ef\u80fd\u503e\u5411\u4e8e\u505a\u7684\u90a3\u6837\u5929\u771f\u5730\u9009\u62e9\u4e00\u4e2a <code>QGauss@<dim@>(degree+1)</code> \u7c7b\u578b\u7684\u5bf9\u8c61\uff08\u8fd9\u5c31\u662f\u6211\u4eec\u7528\u4e8e\u79ef\u5206\u7ebf\u6027\u7cfb\u7edf\u7684\u5bf9\u8c61\uff09\uff0c\u5c31\u4f1a\u53d1\u73b0\u8bef\u5dee\u975e\u5e38\u5c0f\uff0c\u6839\u672c\u4e0d\u9075\u5faa\u9884\u671f\u7684\u6536\u655b\u66f2\u7ebf\u3002\u73b0\u5728\u7684\u60c5\u51b5\u662f\uff0c\u5bf9\u4e8e\u8fd9\u91cc\u4f7f\u7528\u7684\u6df7\u5408\u6709\u9650\u5143\uff0c\u9ad8\u65af\u70b9\u6070\u597d\u662f\u8d85\u6536\u655b\u70b9\uff0c\u5176\u4e2d\u7684\u70b9\u8bef\u5dee\u8981\u6bd4\u5176\u4ed6\u5730\u65b9\u5c0f\u5f97\u591a\uff08\u800c\u4e14\u6536\u655b\u7684\u9636\u6570\u66f4\u9ad8\uff09\u3002\u56e0\u6b64\uff0c\u8fd9\u4e9b\u70b9\u4e0d\u662f\u7279\u522b\u597d\u7684\u79ef\u5206\u70b9\u3002\u4e3a\u4e86\u907f\u514d\u8fd9\u4e2a\u95ee\u9898\uff0c\u6211\u4eec\u53ea\u9700\u4f7f\u7528\u68af\u5f62\u6cd5\u5219\uff0c\u5e76\u5728\u6bcf\u4e2a\u5750\u6807\u65b9\u5411\u4e0a\u8fed\u4ee3 <code>degree+2</code> \u6b21\uff08\u540c\u6837\u5982 step-7 \u4e2d\u7684\u89e3\u91ca\uff09\u3002\n\n    QTrapezoid<1>  q_trapez; \n    QIterated<dim> quadrature(q_trapez, degree + 2); \n\n// \u6709\u4e86\u8fd9\u4e2a\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u8ba9\u5e93\u8ba1\u7b97\u51fa\u8bef\u5dee\u5e76\u5c06\u5176\u8f93\u51fa\u5230\u5c4f\u5e55\u4e0a\u3002\n\n    VectorTools::integrate_difference(dof_handler, \n                                      solution, \n                                      exact_solution, \n                                      cellwise_errors, \n                                      quadrature, \n                                      VectorTools::L2_norm, \n                                      &pressure_mask); \n    const double p_l2_error = \n      VectorTools::compute_global_error(triangulation, \n                                        cellwise_errors, \n                                        VectorTools::L2_norm); \n\n    VectorTools::integrate_difference(dof_handler, \n                                      solution, \n                                      exact_solution, \n                                      cellwise_errors, \n                                      quadrature, \n                                      VectorTools::L2_norm, \n                                      &velocity_mask); \n    const double u_l2_error = \n      VectorTools::compute_global_error(triangulation, \n                                        cellwise_errors, \n                                        VectorTools::L2_norm); \n\n    std::cout << \"Errors: ||e_p||_L2 = \" << p_l2_error \n              << \",   ||e_u||_L2 = \" << u_l2_error << std::endl; \n  } \n// @sect4{MixedLaplace::output_results}  \n\n// \u6700\u540e\u4e00\u4e2a\u6709\u8da3\u7684\u51fd\u6570\u662f\u6211\u4eec\u751f\u6210\u56fe\u5f62\u8f93\u51fa\u7684\u51fd\u6570\u3002\u8bf7\u6ce8\u610f\uff0c\u6240\u6709\u7684\u901f\u5ea6\u5206\u91cf\u90fd\u5f97\u5230\u76f8\u540c\u7684\u89e3\u540d \"u\"\u3002\u518d\u52a0\u4e0a\u4f7f\u7528 DataComponentInterpretation::component_is_part_of_vector \uff0c\u8fd9\u5c06\u5bfc\u81f4 DataOut<dim>::write_vtu() \u751f\u6210\u5404\u4e2a\u901f\u5ea6\u5206\u91cf\u7684\u77e2\u91cf\u8868\u793a\uff0c\u66f4\u591a\u4fe1\u606f\u8bf7\u53c2\u89c1 step-22 \u6216 @ref VVOutput \u6a21\u5757\u4e2d\u7684 \"\u751f\u6210\u56fe\u5f62\u8f93\u51fa \"\u90e8\u5206\u3002\u6700\u540e\uff0c\u5bf9\u4e8e\u9ad8\u9636\u5143\u7d20\u6765\u8bf4\uff0c\u5728\u56fe\u5f62\u8f93\u51fa\u4e2d\u6bcf\u4e2a\u5355\u5143\u53ea\u663e\u793a\u4e00\u4e2a\u53cc\u7ebf\u6027\u56db\u8fb9\u5f62\u4f3c\u4e4e\u4e0d\u5408\u9002\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u751f\u6210\u5927\u5c0f\u4e3a(\u5ea6\u6570+1)x(\u5ea6\u6570+1)\u7684\u6591\u5757\u6765\u6355\u6349\u89e3\u51b3\u65b9\u6848\u7684\u5168\u90e8\u4fe1\u606f\u5185\u5bb9\u3002\u6709\u5173\u8fd9\u65b9\u9762\u7684\u66f4\u591a\u4fe1\u606f\uff0c\u8bf7\u53c2\u89c1 step-7 \u7684\u6559\u7a0b\u7a0b\u5e8f\u3002\n\n  template <int dim> \n  void MixedLaplaceProblem<dim>::output_results() const \n  { \n    std::vector<std::string> solution_names(dim, \"u\"); \n    solution_names.emplace_back(\"p\"); \n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      interpretation(dim, \n                     DataComponentInterpretation::component_is_part_of_vector); \n    interpretation.push_back(DataComponentInterpretation::component_is_scalar); \n\n    DataOut<dim> data_out; \n    data_out.add_data_vector(dof_handler, \n                             solution, \n                             solution_names, \n                             interpretation); \n\n    data_out.build_patches(degree + 1); \n\n    std::ofstream output(\"solution.vtu\"); \n    data_out.write_vtu(output); \n  } \n\n//  @sect4{MixedLaplace::run}  \n\n// \u8fd9\u662f\u6211\u4eec\u4e3b\u7c7b\u7684\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u3002\u5b83\u552f\u4e00\u7684\u5de5\u4f5c\u662f\u6309\u7167\u81ea\u7136\u987a\u5e8f\u8c03\u7528\u5176\u4ed6\u51fd\u6570\u3002\n\n  template <int dim> \n  void MixedLaplaceProblem<dim>::run() \n  { \n    make_grid_and_dofs(); \n    assemble_system(); \n    solve(); \n    compute_errors(); \n    output_results(); \n  } \n} // namespace Step20 \n// @sect3{The <code>main</code> function}  \n\n// \u6211\u4eec\u4ece  step-6  \u800c\u4e0d\u662f  step-4  \u90a3\u91cc\u5077\u6765\u7684\u4e3b\u51fd\u6570\u3002\u5b83\u51e0\u4e4e\u7b49\u540c\u4e8e step-6 \u4e2d\u7684\u51fd\u6570\uff08\u5f53\u7136\uff0c\u9664\u4e86\u6539\u53d8\u7684\u7c7b\u540d\uff09\uff0c\u552f\u4e00\u7684\u4f8b\u5916\u662f\u6211\u4eec\u5c06\u6709\u9650\u5143\u7a7a\u95f4\u7684\u5ea6\u6570\u4f20\u9012\u7ed9\u6df7\u5408\u62c9\u666e\u62c9\u65af\u95ee\u9898\u7684\u6784\u9020\u51fd\u6570\uff08\u8fd9\u91cc\uff0c\u6211\u4eec\u4f7f\u7528\u96f6\u9636\u5143\u7d20\uff09\u3002\n\nint main() \n{ \n  try \n    { \n      using namespace Step20; \n\n      const unsigned int     fe_degree = 0; \n      MixedLaplaceProblem<2> mixed_laplace_problem(fe_degree); \n      mixed_laplace_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\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\n\n\n", "meta": {"hexsha": "7a422c4526888af6aa87a15c134a478a9f56829f", "size": 24723, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-20/step-20.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-20/step-20.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-20/step-20.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.3970588235, "max_line_length": 489, "alphanum_fraction": 0.632811552, "num_tokens": 10076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5311171669720935}}
{"text": "/**\n This file is part of Poisson Image Editing.\n \n Copyright Christoph Heindl 2015\n \n Poisson Image Editing 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 Poisson Image Editing 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 Poisson Image Editing.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n\n#include <blend/poisson_solver.h>\n#include <opencv2/opencv.hpp>\n#pragma warning (push)\n#pragma warning (disable: 4244)\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#pragma warning (pop)\n#include <bitset>\n\nnamespace blend {       \n\n    bool isSameSize(cv::Size a, cv::Size b) {\n        return a.width == b.width && a.height == b.height;\n    }\n\n    /* Make matrix memory continuous. */\n    cv::Mat makeContinuous(cv::Mat m) {       \n        if (!m.isContinuous()) {\n            m = m.clone();\n        }        \n        return m;\n    }\n\n    /* Build a one dimensional index lookup for element in mask. */\n    cv::Mat buildPixelToIndexLookup(cv::InputArray mask, int &npixel)\n    {\n        cv::Mat_<uchar> m = makeContinuous(mask.getMat());\n\n        cv::Mat_<int> pixelToIndex(mask.size());\n        npixel = 0;\n        \n        int *pixelToIndexPtr = pixelToIndex.ptr<int>();\n        const uchar *maskPtr = m.ptr<uchar>();\n\n        for (int id = 0; id < (m.rows * m.cols); ++id) {\n            pixelToIndexPtr[id] = (maskPtr[id] == constants::DIRICHLET_BD) ? -1 : npixel++;\n        }\n\n        return pixelToIndex;\n    }\n    \n    void solvePoissonEquations(\n        cv::InputArray f_,\n        cv::InputArray bdMask_,\n        cv::InputArray bdValues_,\n        cv::OutputArray result_)\n    {\n        // Input validation\n\n        CV_Assert(\n            !f_.empty() &&\n            isSameSize(f_.size(), bdMask_.size()) &&\n            isSameSize(f_.size(), bdValues_.size())\n        );\n\n        CV_Assert(\n            f_.depth() == CV_32F &&\n            bdMask_.depth() == CV_8U &&\n            bdValues_.depth() == CV_32F &&\n            f_.channels() == bdValues_.channels() &&\n            bdMask_.channels() == 1);\n\n        // We assume continuous memory on input\n        cv::Mat f = makeContinuous(f_.getMat());\n        cv::Mat_<uchar> bm = makeContinuous(bdMask_.getMat());\n        cv::Mat bv = makeContinuous(bdValues_.getMat());\n\n        // Allocate output\n        result_.create(f.size(), f.type());\n        cv::Mat r = result_.getMat();\n        bv.copyTo(r, bm == constants::DIRICHLET_BD);\n\n        // The number of unknowns correspond to the number of pixels on the rectangular region \n        // that don't have a Dirichlet boundary condition.\n        int nUnknowns = 0;\n        cv::Mat_<int> unknownIdx = buildPixelToIndexLookup(bm, nUnknowns);\n\n        if (nUnknowns == 0) {\n            // No unknowns left, we're done\n            return;\n        } else if (nUnknowns == f.size().area()) {\n            // All unknowns, will not lead to a unique solution\n            // TODO emit warning\n        }\n\n        const cv::Rect bounds(0, 0, f.cols, f.rows);\n\n        // Directional indices\n        const int center = 0;\n        const int north = 1;\n        const int east = 2;\n        const int south = 3;\n        const int west = 4;\n\n        // Neighbor offsets in all directions\n        const int offsets[5][2] = { { 0, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };\n        \n        // Directional opposite\n        const int opposite[5] = { center, south, west, north, east };\n        const int channels = f.channels();\n        \n        std::vector< Eigen::Triplet<float> > lhsTriplets;\n        lhsTriplets.reserve(nUnknowns * 5);\n\n        Eigen::MatrixXf rhs(nUnknowns, channels);\n        rhs.setZero();\n        \n        // Loop over domain once. The coefficient matrix A is the same for all\n        // channels, the right hand side is channel dependent.\n\n        for (int y = 0; y < f.rows; ++y) {\n            for (int x = 0; x < r.cols; ++x) {\n\n                const cv::Point p(x, y);\n                const int pid = unknownIdx(p);\n\n                if (pid == -1) {\n                    // Current pixel is not an unknown, skip\n                    continue;\n                }\n\n                // Start coefficients of left hand side. Based on discrete Laplacian with central difference.\n                float lhs[] = { -4.f, 1.f, 1.f, 1.f, 1.f };\n                \n                const bool hasNeumann = (bm(p) == constants::NEUMANN_BD);\n                \n                if (hasNeumann) {\n                    \n                    // Implementation note:\n                    //\n                    // We first sweep over all neighbors and apply Neumann boundary (NB) conditions if necessary.\n                    // NBs are currently only applied if the neighbor is not in the domain or it has Dirichlet\n                    // boundary condition (DB).\n                    //\n                    // When the neighbor is not available we introduce ghost points which are immediately\n                    // removed by substitution. Assume that we are at a pixel C at the top border (not corner)\n                    // and that pixel is assigned a NB = 1. Denoting the pixels C, N, E, S, W we have for C\n                    // the Laplacian\n                    //      1: -4C + N + E + S + W = f(x)\n                    // From NB we have\n                    //      2: (N - S) * 0.5 = 1\n                    // As N is not in the domain we need to get rid of it through substitution. Rewriting 2:\n                    //      N = 2 + S\n                    // and substituting in 1:\n                    //      -4C + (2 + S) + E + S + W = f(x)\n                    //      -4C + E + 2S + W = f(x) - 2\n                    \n                    for (int n = 1; n < 5; ++n) {\n                        const cv::Point q(x + offsets[n][0], y + offsets[n][1]);\n                        \n                        if (!bounds.contains(q) || bm(q) == constants::DIRICHLET_BD) {\n                            lhs[opposite[n]] += 1.0f;\n                            lhs[n] = 0.f;\n                            rhs.row(pid) += 2.f * Eigen::Map<Eigen::VectorXf>(bv.ptr<float>(p.y, p.x), channels);\n                        }\n                    }\n                }\n                \n                for (int n = 1; n < 5; ++n) {\n                    const cv::Point q(x + offsets[n][0], y + offsets[n][1]);\n                    \n                    const bool hasNeighbor = bounds.contains(q);\n                    const bool isNeighborDirichlet = hasNeighbor && (bm(q) == constants::DIRICHLET_BD);\n                    \n                    if (!hasNeumann && !hasNeighbor) {\n                        lhs[center] += lhs[n];\n                        lhs[n] = 0.f;\n                    } else if (isNeighborDirichlet) {\n                        \n                        // Implementation note:\n                        //\n                        // Dirichlet boundary conditions (DB) turn neighbor unknowns into knowns (data) and\n                        // are therefore moved to the right hand side. Alternatively, we could add more\n                        // equations for these pixels setting the lhs 1 and rhs to the Dirichlet value, but\n                        // that would unnecessarily blow up the equation system.\n                        \n                        rhs.row(pid) -= lhs[n] * Eigen::Map<Eigen::VectorXf>(bv.ptr<float>(q.y, q.x), channels);\n                        lhs[n] = 0.f;\n                    }\n                }\n\n\n                // Add f to rhs.\n                rhs.row(pid) += Eigen::Map<Eigen::VectorXf>(f.ptr<float>(p.y, p.x), channels);\n\n                // Build triplets for row              \n                for (int n = 0; n < 5; ++n) {\n                    if (lhs[n] != 0.f) {\n                        const cv::Point q(x + offsets[n][0], y + offsets[n][1]);\n                        lhsTriplets.push_back(Eigen::Triplet<float>(pid, unknownIdx(q), lhs[n]));\n                    }\n                }\n                    \n            }\n        }\n\n        // Solve the sparse linear system of equations\n\n        Eigen::SparseMatrix<float> A(nUnknowns, nUnknowns);\n        A.setFromTriplets(lhsTriplets.begin(), lhsTriplets.end());\n\n        Eigen::SparseLU< Eigen::SparseMatrix<float> > solver;\n        solver.analyzePattern(A);\n        solver.factorize(A);\n\n        Eigen::MatrixXf result(nUnknowns, channels);\n        for (int c = 0; c < channels; ++c)\n            result.col(c) = solver.solve(rhs.col(c));\n        \n\n        // Copy results back\n\n        for (int y = 0; y < f.rows; ++y) {\n            for (int x = 0; x < f.cols; ++x) {\n                const cv::Point p(x, y);\n                const int pid = unknownIdx(p);\n\n                if (pid > -1) {\n                    Eigen::Map<Eigen::VectorXf>(r.ptr<float>(p.y, p.x), channels) = result.row(pid);\n                }\n\n            }\n        }\n\n    }\n\n}", "meta": {"hexsha": "7317a58e63c80e8c1797365ae325df2eb0deb228", "size": 9242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "poisson-image-editing/src/poisson_solver.cpp", "max_stars_repo_name": "eti-p-doray/inf8702", "max_stars_repo_head_hexsha": "1f420f6a6d8df5e9f5dce7c6192b622c761a909a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "poisson-image-editing/src/poisson_solver.cpp", "max_issues_repo_name": "eti-p-doray/inf8702", "max_issues_repo_head_hexsha": "1f420f6a6d8df5e9f5dce7c6192b622c761a909a", "max_issues_repo_licenses": ["MIT"], "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-image-editing/src/poisson_solver.cpp", "max_forks_repo_name": "eti-p-doray/inf8702", "max_forks_repo_head_hexsha": "1f420f6a6d8df5e9f5dce7c6192b622c761a909a", "max_forks_repo_licenses": ["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.4170040486, "max_line_length": 113, "alphanum_fraction": 0.4929668903, "num_tokens": 2184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.5311171577604977}}
{"text": "/*\n * Copyright (c) 2014-2017 The University of Utah\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\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/**\n * \\file AbsCoeffGas.cpp\n */\n\n#define PI 3.14159265\n\n#include <radprops/AbsCoeffGas.h>\n#include <radprops/RadiativeSpecies.h>\n#include <iostream>\n#include <fstream>\n#include <iomanip>   // format manipulation\n#include <vector>\n#include <stdexcept>\n#include <cmath>\n#include <cassert>\n#include <limits>\n#include <algorithm>\n\n#include <radprops/GPUHelper.h>\n\n#ifdef RadProps_ENABLE_PREPROCESSOR\n#include <boost/filesystem.hpp>\n#include <boost/regex.hpp>\n#include <boost/tokenizer.hpp>\n#include <boost/lexical_cast.hpp>\n#endif\n\nnamespace RadProps {\nusing namespace std;\n\n/**\n * @brief Implements the composite trapezoid rule for uniformly spaced data.\n * @fn double trapz( const double dx, const vector<double>& fx )\n * @param dx the spacing (assumed constant)\n * @param fx the function values\n * @return the integral\n */\ndouble trapz( const double dx, const vector<double>& fx )\n{\n  const size_t n = fx.size();  assert( n>2 );\n  // composite trapezoid rule\n  double integral = 0.5*(fx[0] + fx[n-1]);\n  for( size_t i=1; i<n-1; ++i ){\n    integral += fx[i];\n  }\n  integral *= dx;\n  return integral;\n}\n\n\n/**\n * @fn double planck_blackbody_intensity( const double eta, const double tref )\n * @param eta  wavenumber (1/cm)\n * @param tref temperature (K)\n * @return the Planck blackbody intensity (J/cm^2)\n *  calculates\n *  \\f[\n *  I(\\nu,T) = 2 h c^2 \\nu^3 \\frac{1}{\\exp(\\frac{h c \\nu}{k T})-1}\n *  \\f]\n *  where c is the speed of sound, k is the Boltzmann constant, h is the Planck constant.\n *  See <a href=\"http://en.wikipedia.org/wiki/Planck%27s_law#Different_forms\"> this link</a> for more information.\n */\ninline double planck_blackbody_intensity( const double eta, const double tref )\n{\n  const double h = 6.626070e-34;   // Planck constant (J s);\n  const double c = 2.997925e10;    // Speed of light in vacuum (cm/s);\n  const double k = 1.380658e-23;   // Boltzmann constant (J/K);\n  return 2*h*c*c*pow(eta,3.0) / ( (exp(h*c*eta/(k*tref)) - 1.0) );\n}\n\n\nnamespace detail{\n\ntemplate< typename IndexT, typename ValT >\nIndexT\nindex_finder( const ValT& x,\n              const std::vector<ValT>& xgrid,\n              const bool allowClipping=false )\n{\n  const size_t nx = xgrid.size();\n  IndexT ilo = 0;\n  IndexT ihi = nx-1;\n\n  if( allowClipping && x<xgrid.front() ) return ilo;\n  if( allowClipping && x>xgrid.back()  ) return ihi;\n\n  // sanity check\n  if( x<xgrid.front() || x>xgrid.back() ){\n    std::ostringstream msg;\n    msg << __FILE__ << \" : \" << __LINE__ << endl\n        << \"root is not bracketed!\" << endl;\n    throw std::runtime_error(msg.str());\n  }\n\n  // regula falsi method to find lower index\n\n  while( ihi-ilo > 1 ){\n    const ValT m = ( xgrid[ihi]-xgrid[ilo] ) / ValT( ihi-ilo );\n    const IndexT c = std::max( ilo+1, IndexT( ihi - (xgrid[ihi]-x)/m ) );\n    assert( c>0 && c<xgrid.size() );\n    if( x >= xgrid[c] )\n      ilo = std::min(ihi-1,c);\n    else\n      ihi = std::max(ilo+1,c);\n  }\n  // error checking:\n  if( !allowClipping && (x > xgrid[ihi] || x < xgrid[ilo]) ){\n    std::ostringstream msg;\n    msg << __FILE__ << \" : \" << __LINE__ << std::endl\n        << \" Regula falsi failed to converge properly!\" << std::endl\n        << \" Target x=\" << x << std::endl\n        << \" xlo=\" << xgrid[ilo] << \", xhi=\" << xgrid[ihi]\n        << std::endl << std::endl;\n    throw std::runtime_error( msg.str() );\n  }\n\n  return ilo;\n}\n\n}\n\nstruct RadiationData{\n  double waveNumber;    ///< wavenumber, cm\n  double absCoeff;      ///< absorption coefficient, 1/cm\n};\n\nstd::ostream& operator<<(std::ostream& out, const RadiationData& data ){\n  out << data.waveNumber << \",\" << data.absCoeff;\n  return out;\n}\n\nstd::ifstream& operator>>( std::ifstream& in, RadiationData& data ){\n  in >> data.waveNumber >> data.absCoeff;\n  return in;\n}\n\n\nSpeciesAbsCoeff::SpeciesAbsCoeff( const string& filename, const double temperature )\n : temperature_( temperature )\n{\n\n  std::ifstream file;\n  file.open(filename.c_str(),std::ios::in); // opens as ASCII!\n  if( file.bad() ){\n    std::ostringstream msg;\n    msg << \"ERROR! Could not open file '\" << filename << \"'\";\n    throw std::runtime_error( msg.str() );\n  }\n\n  RadiationData rdata;\n  file >> rdata;\n  npts_ = 1;\n  loWaveNum_ = rdata.waveNumber;        // the lowest wavenumber in the dataset\n  double wvn = rdata.waveNumber;        // the previous wave number we read\n  double wvnSpc = 0;                    // the wavenumber spacing between\n  while( !file.eof() ){\n    ++npts_;\n    file >> rdata;                      // read the next entry\n    absCoeff_.push_back( rdata.absCoeff );\n    wvnSpc = rdata.waveNumber - wvn;\n    if( std::abs((rdata.waveNumber-wvn)-wvnSpc) > 1e-10 ){\n      ostringstream msg;\n      msg << __FILE__ << \" : \" << __LINE__\n          << \"\\nInconsistency in wavenumber spacing! \" << wvnSpc << \"\\n\";\n      throw runtime_error( msg.str() );\n    }\n    wvn = rdata.waveNumber;             // update the previous wavenumber\n  }\n  hiWaveNum_  = rdata.waveNumber;       // the highest wavenumber in the dataset\n  waveNumInc_ = (hiWaveNum_-loWaveNum_)/double(npts_-1);\n  file.close();\n}\n\ndouble\nSpeciesAbsCoeff::planck_abs_coeff() const\n{\n  std::vector<double> plnckfunc1(npts_,0.0);\n//  std::vector<double> plnckfunc2(npts_,0.0);  // use this for consistency checking\n  const double sigma = 5.670373e-12;    // Stefan\ufffd Boltzmann constant (J/(cm^2 s K^4))\n\n  for( size_t i=0; i<npts_; ++i ){\n    // compute the integrand, which is I * kappa -- see equation 2.21 in Lyubima's thesis\n    plnckfunc1[i] = planck_blackbody_intensity( loWaveNum_ + i*waveNumInc_, temperature_ ) * absCoeff_[i];\n    //    plnckfunc2[i] = planck_blackbody_intensity(wvnmB_+i*wvnmst_,myTref);\n  }\n\n  const double integral = trapz( waveNumInc_, plnckfunc1 );\n  const double tt = integral*PI/( sigma * pow(temperature_,4.0) );\n//  const double tt2 = trapz(wvnmst_,plnckfunc1)/trapz(wvnmst_,plnckfunc2);\n////  std::cout << \" original: \"<<  tt\n////            << \" , ratio: \" << tt2 << std::endl;\n//  if( std::abs(tt-tt2)/tt2 > 0.1 )\n//    std::cout << \"\\tT=\" << myTref << \", \" << std::abs(tt-tt2)/tt2 << std::endl;\n\n  return tt;\n}\n\ndouble\nSpeciesAbsCoeff::rosseland_abs_coeff() const\n{\n  const double sigma = 5.67e-12;   // Stefan\ufffd Boltzmann constant (J/(cm^2 s K^4))\n  const double h = 6.626070e-34;   // Planck constant (J s);\n  const double c = 2.997925e10;    // Speed of light in vacuum (cm/s);\n  const double k = 1.380658e-23;   // Boltzmann constant (J/K);\n  const double tmp = 2.0*c*c*c*h*h/(k*temperature_*temperature_);\n\n  std::vector<double> rossfunc1(npts_,0.0);\n//  std::vector<double> rossfunc2(N_,0.0);  // use this for consistency checking\n  for( int i=0; i<npts_; ++i ){\n    if( absCoeff_[i] > 1e-16 ){\n      /* Matlab commands to get dI/dT:\n          syms h c k T v;\n          I = 2*h*c^2*v^3/(exp(h*c*v/k/T)-1);\n          pretty(I)\n          pretty(diff(I,T))\n       */\n      const double wvn = (loWaveNum_+i*waveNumInc_);\n      const double expTerm = exp(h*c*wvn/(k*temperature_));\n      rossfunc1[i] = tmp * pow(wvn,4.0) * expTerm/pow(expTerm-1.0,2.0) / absCoeff_[i];\n//      rossfunc2[i] = tmp * pow(wvn,4.0) * expTerm/pow(expTerm-1.0,2.0);\n    }\n  }\n\n  const double integral = trapz( waveNumInc_,rossfunc1 ) * PI / (4.0*sigma*pow(temperature_,3.0) );\n  return 1.0/integral;\n//  const double t1 = trapz(wvnmst_,rossfunc1);\n//  const double t2 = trapz(wvnmst_,rossfunc2);\n//  std::cout << t1 <<\" , \" << t2 << \" , \" << t2/t1 << \", \" << 4.0*sigma*pow(myTref,3.0)/(PI*t1) << \"\\n\";\n////  return trapz(wvnmst_,rossfunc2)/trapz(wvnmst_,rossfunc1);\n//  return 4.0*sigma*pow(myTref,3.0)/(PI*t1);\n}\n\ndouble\nSpeciesAbsCoeff::effective_abs_coeff( const double opl ) const\n{\n  std::vector<double> plnckfunc1(npts_,0.0);\n  std::vector<double> plnckfunc2(npts_,0.0);\n  for( int i=0; i<npts_; i++ ){\n    const double tmp = planck_blackbody_intensity(loWaveNum_+i*waveNumInc_,temperature_)*exp(-absCoeff_[i]*opl);\n    plnckfunc1[i] = tmp * absCoeff_[i];\n    plnckfunc2[i] = tmp;\n  }\n  return trapz(waveNumInc_,plnckfunc1) / trapz(waveNumInc_,plnckfunc2);\n}\n\n//==============================================================================\n\nvoid\nSpeciesGData::read( std::istream& file )\n{\n  data.clear();\n  size_t ntemp;\n  file >> speciesName >> ntemp;\n  for( size_t j=0; j<ntemp; ++j){\n    SpeciesGDataSingleTemperature d;\n    d.read(file);\n    data.push_back(d);\n  }\n}\n\nvoid\nSpeciesGData::write( std::ostream& file ) const\n{\n  file << speciesName << std::endl;\n  file << data.size() << std::endl;\n  for( size_t j=0; j<data.size(); ++j ){\n    data[j].write(file);\n  }\n}\n\nvoid\nSpeciesGDataSingleTemperature::read( std::istream& file )\n{\n  size_t ng;\n  file >> temperature >> ng;\n  gvalues.resize(ng,0.0);\n  kvalues.resize(ng,0.0);\n  for( size_t i=0; i<ng; ++i ){\n    file >> gvalues[i] >> kvalues[i];\n  }\n}\n\nvoid\nSpeciesGDataSingleTemperature::write( std::ostream& file ) const\n{\n  file << std::setprecision( std::numeric_limits<double>::digits10 );\n  file << temperature << std::endl\n       << gvalues.size() << std::endl;\n  for( int i=0; i<gvalues.size(); ++i ){\n    file << gvalues[i] << \" \" << kvalues[i]<<endl;\n  }\n}\n\nSpeciesGDataSingleTemperature\ncalculate_plank( const SpeciesAbsCoeff& absCoeffMix,\n                 const double myTref )\n{\n  SpeciesGDataSingleTemperature gandk;\n\n  const std::vector<double>& absCoef = absCoeffMix.get_coeffs();\n  const size_t nwvnm = absCoef.size();\n\n  const double kmin = *std::min_element( absCoef.begin(), absCoef.end() );\n  const double kmax = *std::max_element( absCoef.begin(), absCoef.end() );\n\n  const double pwr = 0.1;\n  const double pwrk_min = std::pow(kmin,pwr);\n  const double pwrk_max = std::pow(kmax,pwr);\n\n  const int n_pwrk=5;  //Number of g-values\n\n  std::vector<double> pwrk( n_pwrk,   0.0 );\n  std::vector<double> ff  ( n_pwrk+1, 0.0 );\n  std::vector<double> gg  ( n_pwrk+1, 0.0 );\n  std::vector<double>  k  ( n_pwrk+1, 0.0 );\n\n  double sum00 = 0;\n  for( size_t j=0; j<n_pwrk; ++j ){\n    const double pwrk_step = (pwrk_max - pwrk_min)*(log(j+2)-log(j+1)) / log(n_pwrk+2);\n    sum00 += pwrk_step;\n    pwrk[j] = sum00+kmin-pwrk_step/2;\n    k[j] = std::pow( pwrk[j], 1.0/pwr );\n  }\n\n  const double hhh = 6.626076e-34;  // Planck constant (Js);\n  const double ccc = 2.997925e10;   // Speed of light in vacuum (cm/s)\n  const double kkk = 1.380658e-23;  // Boltzmann constant (J/K);\n  const double hck = hhh*ccc/kkk;\n\n  const double c1      = 3.7419e-12; // First radiation constant (W cm^2)\n  const double sigma   = 5.67e-12;   // Stefan Boltzmann constant (J/(cm^2 s K^4))\n\n  for( size_t i=0; i<nwvnm; ++i ){\n    const double wvnm_b = absCoeffMix.min_wavenumber();    // Min wavenumber (1/cm)\n    const double wvnm_e = absCoeffMix.max_wavenumber();    // Max wavenumber (1/cm)\n    const double wvnmst = absCoeffMix.wavenumber_step();   // wavenumber step (1/cm)\n    const double c1sigt4 = c1/(sigma*std::pow(myTref,4))*wvnmst;\n    const double eb = c1sigt4 * std::pow((wvnm_b+wvnmst*i),3) / ( exp(hck/myTref*(wvnm_b+wvnmst*i)) - 1.0 );\n    const double kpwri = pow( absCoef[i], pwr );\n    vector<double>::const_iterator up = std::upper_bound( pwrk.begin(), pwrk.end(), kpwri );\n    const size_t iadd = up - pwrk.begin();\n    ff[iadd] += eb;\n  }\n  double fh=0;\n  for( size_t l=0; l<n_pwrk+1; ++l ){\n    fh += ff[l];\n    gg[l] = fh;\n  }\n\n  // jcs why are the temporary arrays of length n_pwrk+1 but the resultant array is length n_pwrk ???\n  gandk.temperature=myTref;\n  for( size_t i=0; i<n_pwrk-1; ++i ){\n    gandk.gvalues.push_back(gg[i]);\n    gandk.kvalues.push_back( k[i]);\n  }\n\n  gandk.gvalues.push_back(1);\n  gandk.kvalues.push_back(kmax);\n\n  return gandk;\n}\n\n#ifdef RadProps_ENABLE_PREPROCESSOR\n\n// sorts \"data\" and populates the vector of indices that indicate the sort pattern\ntemplate<typename T>\nvoid\npaired_sort( vector<size_t> & index,\n             vector<T> & data )\n{\n  // A vector of a pair which will contain the sorted value and its index in the original array\n  vector<pair<T,size_t> > indexedPair;\n  indexedPair.resize(data.size());\n  for( size_t i=0; i<indexedPair.size(); ++i ){\n    indexedPair[i].first = data[i];\n    indexedPair[i].second = i;\n  }\n  sort( indexedPair.begin(), indexedPair.end() );\n  index.resize( data.size() );\n  for( size_t i = 0; i < index.size(); ++i ){\n    index[i] = indexedPair[i].second;\n    data [i] = indexedPair[i].first;\n  }\n}\n\n/**\n *\n * @param specNam the name of the species to load files for\n * @param path the path to search\n * @param tempVec the sorted vector of temperatures (output)\n * @param sortFname the sorted vector of file names (output)\n */\nvoid\nget_files_sorted_by_temperature( const string specNam, const string path,\n                                 vector<double>& tempVec,\n                                 vector<string>& sortFname )\n{\n  const string firstPart( \"AbsCoeff\" + specNam + \"T\" );\n  const string  lastPart( \"txt\" );\n  const boost::regex filter( firstPart + \".*\" + lastPart );  // the \".*\" is a wildcard matching operation.\n\n  vector<string> fnames;\n  try{\n    boost::filesystem::directory_iterator end;\n    for( boost::filesystem::directory_iterator i(path); i!=end; ++i ){\n\n      if( !boost::filesystem::is_regular_file( i->status() ) ) continue; // only look at regular files (not dirs)\n\n      const std::string fname = i->path().filename().string();\n\n      // Skip if no match\n      boost::smatch what;\n      if( !boost::regex_match( fname, what, filter ) ) continue;\n      // grab off the temperature for this file\n      const string tmp = fname.substr( firstPart.size(), fname.size()-firstPart.size()-lastPart.size() );\n      const double temp = boost::lexical_cast<double>(tmp);\n\n      // File matches. parse it\n      tempVec.push_back(temp);\n      const string p( path+\"/\"+fname );\n      fnames.push_back( p );\n      assert( boost::filesystem::is_regular_file(p) );\n    }\n  }\n  catch( std::exception& err ){\n    std::ostringstream msg;\n    msg << \"ERROR loading files.  Details follow:\\n\" << err.what();\n    throw std::runtime_error( msg.str() );\n  }\n\n  // sort by temperature\n  vector<size_t> myIndex;\n  paired_sort( myIndex, tempVec );\n\n  sortFname.clear();\n  for( size_t i=0; i<myIndex.size(); ++i ){\n    sortFname.push_back( fnames[ myIndex[i] ] );\n  }\n}\n\n\nSpeciesAbsData\nload_species_abs_coefs( const string& mySp,\n                        const string path=\".\" )\n{\n  SpeciesAbsData specData;\n  specData.speciesName = mySp;\n  std::vector<SpeciesAbsCoeff> speciesAbsCoeffTempVector;\n  std::vector<double>& tempVec = specData.temperatures;\n  std::vector<SpeciesAbsCoeff>& specAbsCoefs = specData.absCoeff;\n\n  vector<string> fnames;\n  get_files_sorted_by_temperature( mySp, path, tempVec, fnames );\n\n  for( size_t i=0; i<fnames.size(); ++i ){\n    cout << \"\\t-> loading \" << fnames[i] << endl;\n    specAbsCoefs.push_back( SpeciesAbsCoeff(fnames[i],tempVec[i]) );\n  }\n  return specData;\n}\n\n\nFSK::FSK( const std::vector<RadiativeSpecies>& mySpecies,\n          const string outputFileName,\n          const string path )\n  : allowClipping_( true )\n{\n  speciesOrder_ = mySpecies;\n  std::vector<std::string> spnam;\n  for( size_t j=0; j<mySpecies.size(); ++j ){\n    spnam.push_back( species_name(mySpecies[j]) );\n    cout << \"Species = \" << spnam[j] << endl;\n  }\n\n  const size_t nspecies=spnam.size();\n  for( size_t isp=0; isp<nspecies; ++isp ){\n\n    cout << \"loading data for species \" << spnam[isp] << endl;\n    const SpeciesAbsData specAbsData = load_species_abs_coefs( spnam[isp], path );\n\n    SpeciesGData gSpIV;\n    gSpIV.speciesName = spnam[isp];\n    const size_t ntemp = specAbsData.temperatures.size();\n    std::vector<SpeciesGDataSingleTemperature>& calFSK = gSpIV.data;\n    for( size_t itemp=0; itemp<ntemp; ++itemp ){\n      const SpeciesAbsCoeff& sac = specAbsData.absCoeff[itemp];\n      calFSK.push_back( calculate_plank( specAbsData.absCoeff[itemp],\n                                         specAbsData.temperatures[itemp] ) );\n    }\n//    cout << endl << \"G data for \" << spnam[isp] << endl;\n//    gSpIV.write(cout);\n//    cout << endl << endl;\n    spCalFSK_.push_back(gSpIV);\n  }\n\n  ofstream gfile( outputFileName.c_str() );\n  gfile << nspecies << endl;\n  for( size_t ll=0; ll<nspecies; ++ll ){\n    spCalFSK_[ll].write(gfile);\n  }\n  gfile.close();\n  cout << endl << \"Processed FSK data has been written to \" << outputFileName << endl << endl;\n}\n#endif // RadProps_ENABLE_PREPROCESSOR\n\nFSK::FSK( const string fileN )\n  : allowClipping_( true )\n{\n  cout << \"Loading FSK Radiation data file: \" << fileN << endl;\n\n  std::ifstream fileM2( fileN.c_str(), std::ios::in ); // opens as ASCII!\n  if( !fileM2.good() ){\n    std::ostringstream msg;\n    msg << \"ERROR! Could not open file '\" << fileN << \"'\" << std::endl\n        << __FILE__ << \" : \" << __LINE__;\n    throw std::runtime_error( msg.str() );\n  }\n\n  int nspecies;\n  fileM2 >> nspecies;\n  for( size_t isp=0; isp<nspecies; ++isp ){\n    cout << \"loading \" << isp+1 << \" of \" << nspecies << endl;\n    SpeciesGData spGData;\n    spGData.read( fileM2 );\n    spCalFSK_.push_back( spGData );\n    speciesOrder_.push_back(species_enum( spCalFSK_[isp].speciesName ));\n  }\n  fileM2.close();\n\n  // echo file information back out to disk\n//  ofstream gfile(\"TestGs2.txt\");\n//  gfile << nspecies << endl;\n//  for (int ll=0; ll<nspecies; ll++) {\n//    spCalFSK_[ll].write(gfile);\n//  }\n//  gfile.close();\n\n}\n\ndouble\nFSK::mixture_abs_coeff( const std::vector<double>& mixMoleFrac,\n                        const double mixT,\n                        const double gp ) const\n{\n  std::vector<double> mixG;\n  std::vector<double> mixK;\n  mixG.clear();\n  mixK.clear();\n\n  mixture_coeffs( mixG, mixK, mixMoleFrac, mixT );\n\n  // clip if we exceed bounds.\n  if( gp <= mixG.front() ) return mixK.front();\n  if( gp >= mixG.back()  ) return mixK.back();\n\n  const size_t indexg = detail::index_finder<size_t,double>( gp, mixG, allowClipping_ );\n  return mixK[indexg]+(mixK[indexg+1]-mixK[indexg])*(gp-mixG[indexg])/(mixG[indexg+1]-mixG[indexg]);\n}\n\nvoid\nFSK::mixture_coeffs( std::vector<double>& gmix,\n                     std::vector<double>& kmix,\n                     const std::vector<double>& mixMoleFrac,\n                     const double mixT ) const\n{\n  const size_t nspecies = mixMoleFrac.size();\n  const size_t ng = spCalFSK_[0].data[0].gvalues.size();\n  gmix.resize(ng,1.0);\n  kmix.resize(ng,0.0);\n\n  for( size_t isp=0; isp<nspecies; ++isp ){\n\n    const SpeciesGData& spData = spCalFSK_[isp];\n\n    const size_t ntemp = spData.data.size();\n    std::vector<double> tvec(ntemp,0.0);  // jcs this is slow - need to fix it...\n    for( size_t j=0; j<ntemp; ++j ){\n      tvec[j] = spData.data[j].temperature;\n    }\n\n    const size_t tindex = detail::index_finder<size_t,double>( mixT, tvec, allowClipping_ );\n\n    const vector<double>& g     = spData.data[tindex  ].gvalues;\n    const vector<double>& gPlus = spData.data[tindex+1].gvalues;\n    const vector<double>& k     = spData.data[tindex  ].kvalues;\n    const vector<double>& kPlus = spData.data[tindex+1].kvalues;\n    const double T              = spData.data[tindex  ].temperature;\n    const double Tplus          = spData.data[tindex+1].temperature;\n\n    for( size_t ig=0; ig<ng; ++ig ){\n      gmix[ig] *= std::abs( g[ig] + ( gPlus[ig]-g[ig] )*( mixT-T )/( Tplus-T ) );\n      kmix[ig] += mixMoleFrac[isp]/nspecies*sqrt(k[ig]*kPlus[ig]);\n    }\n  }\n}\n\nvoid\nFSK::a_function( std::vector<double>& a,\n                 const std::vector<double>& mixMoleFrac,\n                 const double Tmed,\n                 const double Twall ) const\n{\n  std::vector<double> mediumG, mediumK, wallG, wallK;\n\n  mixture_coeffs(mediumG,mediumK,mixMoleFrac, Tmed);\n  mixture_coeffs(wallG,wallK,mixMoleFrac, Twall);\n  const size_t L = mediumG.size();\n\n  a.clear();\n  a.resize(L,0.0);\n\n  a[0]=((wallG[1]-wallG[0])/(mediumG[1]-mediumG[0]));\n  for( size_t l=1; l<mediumG.size()-1; l++ ){\n    a[l]=(wallG[l+1]-wallG[l-1])/(mediumG[l+1]-mediumG[l-1]);\n  }\n  a[L-1]=(wallG[L-1]-wallG[L-2])/(mediumG[L-1]-mediumG[L-2]);\n}\n\n\n//==============================================================================\n\n#ifdef RadProps_ENABLE_PREPROCESSOR\nGreyGas::GreyGas( const std::vector<RadiativeSpecies>& mySpecies,\n                  const double opl,\n                  const std::string outputFileName,\n                  const string path )\n : allowClipping_( true ),\n   opl_( opl ),\n   nspecies_( mySpecies.size() ),\n   order_(1)\n{\n  speciesOrder_=mySpecies;\n  std::vector<std::string> speciesNames;\n  for( int j=0; j<mySpecies.size(); j++ ){\n    speciesNames.push_back( species_name(mySpecies[j]) );\n  }\n\n  for( size_t isp=0; isp<nspecies_; ++isp ){\n    cout << \"Species = \" << speciesNames[isp] << endl;\n    const SpeciesAbsData specData = load_species_abs_coefs( speciesNames[isp], path );\n\n    // process this species information at each temperature to obtain\n    // the mean absorption coefficients\n    GreyGasData spData;\n    spData.speciesName = speciesNames[isp];\n    assert( speciesNames[isp] == specData.speciesName );\n    spData.ntemp = specData.temperatures.size();\n\n    for( size_t itemp=0; itemp<spData.ntemp; ++itemp ){\n      const SpeciesAbsCoeff& spAbsCoeff = specData.absCoeff[itemp];\n      spData.temperatures.push_back( specData.temperatures[itemp] );\n      spData.planckCoeff.push_back( spAbsCoeff.planck_abs_coeff()        );\n      spData.rossCoeff  .push_back( spAbsCoeff.rosseland_abs_coeff()     );\n      spData.effAbsCoeff.push_back( spAbsCoeff.effective_abs_coeff(opl_) );\n    }\n    data_.push_back(spData);\n    \n    LagrangeInterpolant1D interpplank( order_, spData.temperatures, spData.planckCoeff, allowClipping_);\n    planckCoeff_.push_back( interpplank );\n    \n    LagrangeInterpolant1D interpross( order_, spData.temperatures, spData.rossCoeff, allowClipping_);\n    rossCoeff_.push_back( interpross );\n    \n    LagrangeInterpolant1D interpeff( order_, spData.temperatures, spData.effAbsCoeff, allowClipping_);\n    effAbsCoeff_.push_back( interpeff );\n  }\n\n  std::cout << \"Writing preprocessed grey-gas properties to file: \" << outputFileName << std::endl;\n  ofstream out( outputFileName.c_str() );\n  out << nspecies_ << endl << opl_ << endl;\n  for( size_t isp=0; isp<nspecies_; ++isp ){\n    data_[isp].write(out);\n  }\n}\n#endif // RadProps_ENABLE_PREPROCESSOR\n\nGreyGas::GreyGas( const std::string fileName )\n: allowClipping_( true ), order_(1)\n{\n  std::ifstream fileMG( fileName.c_str(), std::ios::in ); // opens as ASCII!\n  if( !fileMG.good() ){\n    std::ostringstream msg;\n    msg << \"ERROR! Could not open file '\" << fileName << \"'\" << std::endl\n        << __FILE__ << \" : \" << __LINE__;\n    throw std::runtime_error( msg.str() );\n  }\n  fileMG >> nspecies_ >> opl_;\n  const std::vector<string> indepvarname(1, \"Temperature\");\n  for( size_t isp=0; isp<nspecies_; ++isp ){\n    GreyGasData data;\n    data.read( fileMG );\n    if (data.temperatures.size() < order_+1 ) {\n      std::ostringstream msg;\n      msg << \"ERROR! In order to make a table, size of independet variable (temperature) must be higher than  \" << order_  << std::endl\n      << __FILE__ << \" : \" << __LINE__;\n      throw std::runtime_error( msg.str() );\n    }\n    \n    LagrangeInterpolant1D interpplank( order_, data.temperatures, data.planckCoeff, allowClipping_);\n    planckCoeff_.push_back( interpplank );\n    \n    LagrangeInterpolant1D interpross( order_, data.temperatures, data.rossCoeff, allowClipping_);\n    rossCoeff_.push_back( interpross );\n    \n    LagrangeInterpolant1D interpeff( order_, data.temperatures, data.effAbsCoeff, allowClipping_);\n    effAbsCoeff_.push_back( interpeff );\n    speciesOrder_.push_back(species_enum( data.speciesName ));\n  }\n  fileMG.close();\n}\n\n#ifdef ENABLE_CUDA\nvoid\nGreyGas::gpu_mixture_coeffs(double* result,\n                            const std::vector<const double*>& mixMoleFrac,\n                            const double* mixT,\n                            const size_t indepsize,\n                            const MixtureProperties coeffname = EFF_ABS_COEFF)\n{\n\n  const size_t nspecies = mixMoleFrac.size();\n\n  const std::vector<const double*> tempvec(1, mixT);\n  \n  // initialize results with 0\n  cudaMemset( result, 0, sizeof(double) * indepsize);\n  GPU_ERROR_CHECK;\n  \n  double *coeffi;\n  cudaMalloc((void**) &coeffi,  sizeof(double) * indepsize);\n  GPU_ERROR_CHECK;\n\n  for (int i=0; i< mixMoleFrac.size(); i++) {\n    \n    switch (coeffname) {\n      case PLANK_COEFF:\n        planckCoeff_[i].gpu_value( tempvec, coeffi,  indepsize);\n        break;\n      case ROSS_COEFF:\n        rossCoeff_  [i].gpu_value( tempvec, coeffi,  indepsize);\n        break;\n      case EFF_ABS_COEFF:\n        effAbsCoeff_[i].gpu_value( tempvec, coeffi,  indepsize);\n        break;\n      case INVALID_RAD_COEFF:\n        ostringstream msg;\n        msg << __FILE__ << \" : \" << __LINE__ << endl << endl\n        << \"Invalid gray gas propety! \\n\";\n        throw invalid_argument( msg.str() );\n    }\n\n    gray_gas_gpu_mixture_coeffs<<<NBLOCK(indepsize), NTHREAD(indepsize)>>>(result, coeffi, mixMoleFrac[i], indepsize);\n    GPU_ERROR_CHECK;\n  }\n  cudaThreadSynchronize();\n  GPU_ERROR_CHECK;\n}\n\n#endif\n\nvoid\nGreyGas::mixture_coeffs( double& result,\n                         const std::vector<double>& mixMoleFrac,\n                         const double mixT,\n                         const MixtureProperties coeffname = EFF_ABS_COEFF) const\n{\n  if( nspecies_ != mixMoleFrac.size() ){\n    ostringstream msg;\n    msg << __FILE__ << \" : \" << __LINE__ << endl << endl\n        << \"The number of species supplied to 'GreyGas::mixture_coeffs()' is not consistent with the number in the table\\n\"\n        << \"  Number in table: \" << nspecies_ << endl\n        << \"  Number supplied: \" << mixMoleFrac.size() << endl << endl;\n    throw invalid_argument( msg.str() );\n  }\n  result = 0;\n  switch (coeffname) {\n    case PLANK_COEFF:\n      for( size_t i=0; i<nspecies_; i++ ) result += mixMoleFrac[i] * planckCoeff_[i].value(mixT);\n      break;\n    case ROSS_COEFF:\n      for( size_t i=0; i<nspecies_; i++ ) result += mixMoleFrac[i] * rossCoeff_[i].value(mixT);\n      break;\n    case EFF_ABS_COEFF:\n      for( size_t i=0; i<nspecies_; i++ ) result += mixMoleFrac[i] * effAbsCoeff_[i].value(mixT);\n      break;\n    case INVALID_RAD_COEFF:\n      ostringstream msg;\n      msg << __FILE__ << \" : \" << __LINE__ << endl << endl\n      << \"Invalid gray gas propety! \\n\";\n      throw invalid_argument( msg.str() );\n  }\n}\n\nvoid\nGreyGas::GreyGasData::read( std::ifstream& file )\n{\n  file >> speciesName;\n  file >> ntemp;\n  planckCoeff.resize(ntemp,0.0);\n  rossCoeff.resize(ntemp,0.0);\n  effAbsCoeff.resize(ntemp,0.0);\n  temperatures.resize(ntemp,0.0);\n  for( int i=0; i<ntemp; ++i ){\n    file >> temperatures[i] >> planckCoeff[i] >> rossCoeff[i] >> effAbsCoeff[i];\n  }\n}\n\nvoid\nGreyGas::GreyGasData::write( std::ofstream& file ) const\n{\n  file << speciesName << std::endl;\n  file << ntemp << std::endl;\n  for( int ll=0; ll<ntemp; ++ll ){\n    file << temperatures[ll] << \"  \"<< planckCoeff[ll] << \"  \" << rossCoeff[ll] << \"  \" << effAbsCoeff[ll] << endl;\n  }\n}\n} // namespace RadPorps\n", "meta": {"hexsha": "17465a8ad90a23af463a3da2579bcd54e22ece39", "size": 28035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "radprops/AbsCoeffGas.cpp", "max_stars_repo_name": "MaxZZG/RadProps", "max_stars_repo_head_hexsha": "bd95421430fc266ee88d0480069f7d20be1414f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "radprops/AbsCoeffGas.cpp", "max_issues_repo_name": "MaxZZG/RadProps", "max_issues_repo_head_hexsha": "bd95421430fc266ee88d0480069f7d20be1414f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "radprops/AbsCoeffGas.cpp", "max_forks_repo_name": "MaxZZG/RadProps", "max_forks_repo_head_hexsha": "bd95421430fc266ee88d0480069f7d20be1414f6", "max_forks_repo_licenses": ["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.375, "max_line_length": 135, "alphanum_fraction": 0.6347066167, "num_tokens": 8463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5311171577604977}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"puissance.h\"\n\nBOOST_AUTO_TEST_SUITE(test_puissance)\n\n    BOOST_AUTO_TEST_CASE(test_puissance_modulaire) {\n        BOOST_CHECK_EQUAL(puissance::puissance_modulaire(2u, 10u, 100u), 24u);\n        BOOST_CHECK_EQUAL(puissance::puissance_modulaire<unsigned long long>(97643u, 276799u, 456753u), 368123u);\n    }\n\n    BOOST_AUTO_TEST_CASE(test_puissance) {\n        BOOST_CHECK_EQUAL(puissance::puissance(2u, 10u), 1024u);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4755eb3289f2e92dcc3643117990ad4b77cdcbdd", "size": 495, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/puissance.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/puissance.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/puissance.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.9375, "max_line_length": 113, "alphanum_fraction": 0.7535353535, "num_tokens": 143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.531117154423137}}
{"text": "#include <cstddef>\n#include <sys/time.h>\n#include \"FHE.h\"\n#include \"EncryptedArray.h\"\n#include <NTL/ZZX.h>\n#include <NTL/ZZ.h>\n#include <gmp.h>\n#include <omp.h>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <iostream>\n#include \"Ctxt.h\"\n#include \"polyEval.h\"\n#include <algorithm>\n#include <math.h>\n\n\n\n//define how many numbers you want to compare at VECTOR_COUNT\n#define VECTOR_COUNT 2\n#define VECTOR_SIZE 1\n\n// Simple class to measure time for each method \nclass Timer\n{\npublic:\n    void start() { m_start = my_clock(); }\n    void stop() { m_stop = my_clock(); }\n    double elapsed_time() const {\n        return m_stop - m_start;\n    }\n\nprivate:\n    double m_start, m_stop;\n    double my_clock() const {\n        struct timeval tv;\n        gettimeofday(&tv, NULL);\n        return tv.tv_sec + tv.tv_usec * 1e-6;\n    }\n};\n\n//Equality recursive function at page 4 \nCtxt z(int i,int j, std::vector<Ctxt> x,std::vector<Ctxt> y, Ctxt enc1){\n    if (j==1){\n        Ctxt g=x[i];\n        g+=y[i];\n        g+=enc1;\n        return g;    \n    }\n    else {\n        int l=ceil(j/2);\n        Ctxt f= z(i+l,j-l,x,y, enc1);\n        f*=z(i,l,x,y,enc1);\n        return f;                     \n    }\n       \n}\n\n//Inequality recursive function at page 4 \nCtxt t(int i,int j, std::vector<Ctxt> x,std::vector<Ctxt> y,  Ctxt enc1){\n    if (j==1){\n    Ctxt  H=x[i];\n    H*=y[i];\n    H+=x[i];\n    return H;\n    }\n    else {\n        int l1=ceil(j/2);\n        Ctxt we=z(i+l1,j-l1,x,y,enc1); \n        we*=t(i,l1,x,y,enc1); \n        we+=t(i+l1,j-l1,x,y,enc1);\n        return we;                                    \n    }\n }\n\n//selection  function with input two numbers (extracted to bits) with output the minimum of two numbers\nstd::vector<Ctxt> sel(std::vector<Ctxt> digits, std::vector<Ctxt> digits1,std::vector<Ctxt> digitsenc1,std::vector<Ctxt> digitsqw){\n    for (int i=0;i<digits1.size();i++){\n        Ctxt reset=digitsenc1[0];\n        digits1[i]*=digitsqw[0];\n        digitsenc1[0]-=digitsqw[0];\n        digits[i]*=digitsenc1[0];\n        digits1[i]+=digits[i];\n        digitsenc1[0]=reset;\n    }\n    return digits1;\n\n}\n\n//function with input a list of encrypted numbers and output the minimum of them\nstd::vector<Ctxt> minimum(std::vector<Ctxt> list, Ctxt enc1){\n    Ctxt mini=list[0];\n\n    std::vector<Ctxt> digits1;\n    extractDigits(digits1, mini);\n\n   \n    \n    for (int i=1;i<list.size();i++){\n\n         std::vector<Ctxt> digitsenc1;\n        extractDigits(digitsenc1,enc1);\n        \n        std::vector<Ctxt> digitsi;\n        extractDigits(digitsi, list[i]); \n         \n        Ctxt compute_t=t(0,digits1.size(),digits1,digitsi, enc1);   \n\n        std::vector<Ctxt> digitsqw;\n        extractDigits(digitsqw, compute_t);\n        std::vector<Ctxt> mi=sel( digits1, digitsi, digitsenc1, digitsqw);\n        digits1=mi;\n    }\n    return digits1;\n\n}\n\n\n\n\n\nint main(int argc, char **argv)\n{\n    /*** BEGIN INITIALIZATION ***/\n    long m = 0;                   // Specific modulus\n    long p = 2;                 // Plaintext base [default=2], should be a prime number\n    long r = 8;                   // Lifting [default=1]\n    long L = 21;                  // Number of levels in the modulus chain [default=heuristic]\n    long c = 2;                   // Number of columns in key-switching matrix [default=2]\n    long w = 5;                  // Hamming weight of secret key\n    long d = 1;                   // Degree of the field extension [default=1]\n    long k = 80;                  // Security parameter [default=80] \n    long s = 0;                   // Minimum number of slots [default=0]\n    \n    Timer tInit;\n    tInit.start();\n\t\n    std::cout << \"Finding m... \" << std::flush;\n    m = FindM(k, L, c, p, d, s, 0);           // Find a value for m given the specified values\n    \n    std::cout << \"m = \" << m << std::endl;\n\t\n    std::cout << \"Initializing context... \" << std::flush;\n    FHEcontext context(m, p, r); \t          // Initialize context\n    buildModChain(context, L, c);             // Modify the context, adding primes to the modulus chain\n    std::cout << \"OK!\" << std::endl;\n\n    std::cout << \"Generating keys... \" << std::flush;\n    \n    fstream pubKeyFile(\"pk.txt\", fstream::out|fstream::trunc);  \n    assert(pubKeyFile.is_open());\n    writeContextBase(pubKeyFile,context);\n    pubKeyFile << context << std::endl;\n\n\n\n    FHESecKey sk(context);                    // Construct a secret key structure\n    const FHEPubKey& pk = sk;                 // An \"upcast\": FHESecKey is a subclass of FHEPubKey\n    sk.GenSecKey(w);                          // Actually generate a secret key with Hamming weight\n    //addSome1DMatrices(sk);                    // Extra information for relinearization\n    std::cout << \"OK!\" << std::endl;\n\n\n    pubKeyFile << pk << std::endl; \n    pubKeyFile.close();\n\n    /****INITIALIZATION END****/\n\n\n    std::ifstream infile(\"message1.txt\");\n   \n   //open the message.txt file each line of this txt is a vector\n\n\n    std::vector< std::vector<int> > e;\n    e.resize(VECTOR_COUNT);\n    for (int i=0; i<VECTOR_COUNT; i++){\n        e[i].resize(VECTOR_SIZE);\n    }\n    \n    for (int i=0; i<VECTOR_COUNT; i++){\n        for (int j=0; j<VECTOR_SIZE ;j++){\n            infile >> e[i][j]; \n        }\n    }\n    \n    std::cout << \"starting\"<< std::endl;\n\n   \n    //put the first line vector to u and the second line vector to v\n\n    /*******************************/\n    /************CLIENT*************/\n    /*******************************/\n    long int u,v,y,z; \n    u=e[0][0];\n    v=e[1][0];\n    //y=e[2][0];\n    //z=e[3][0];\n    std::cout << \"u:\" << u << std::endl; \n    std::cout << \"v:\" << v << std::endl;\n    //std::cout << \"y:\" << y << std::endl;\n    //std::cout << \"z:\" << z << std::endl;\n    std::cout << \"encryption of two number from the file message1.txt\" << std::endl;\n\n    Ctxt encU(pk),encV(pk),encG(pk),enc1(pk),enc11(pk),enc0(pk),encY(pk),encZ(pk);\n\n\n    \n    \n\n    pk.Encrypt(encU,to_ZZX(u));\n    pk.Encrypt(encV,to_ZZX(v));\n    pk.Encrypt(enc0,to_ZZX(0));\n     pk.Encrypt(enc1,to_ZZX(1));\n     //pk.Encrypt(encY,to_ZZX(y));\n     pk.Encrypt(enc11,to_ZZX(1));\n     //pk.Encrypt(encZ,to_ZZX(z));\n     std::vector<Ctxt> digits0;\n     extractDigits(digits0, enc0);\n\n    \n    //extractdigits of encU and store them at vector:digits\n    std::vector<Ctxt> digitsU;\n    extractDigits(digitsU, encU);\n    \n     \n\n  \t /*************************************************************/\n    /***decrypt each digit of encU to see if extractDigits work*****/\n    /***************************************************************/\n\n   \n\n    long res[digitsU.size()];\n    for (int i=0;i<digitsU.size();i++){\n    ZZX result;\n    sk.Decrypt(result,digitsU[i]);\n    if (result[0]>(pow(p,r))/2){ result[0]=result[0]-pow(p,r);}\n    res[i]=conv<long>(result[0]);\n    }\n\n    std::cout<< \"U:\";\n    size_t res_size = sizeof(res)/sizeof(res[0]);\n    std::reverse(res, res + res_size);\n    for (int i=0;i<digitsU.size();i++){\n        std::cout << res[i] << \",\" ;\n    }\n    std::cout << std::endl;\n\n    /****CORRECT******/\n\n\n    //extractdigits of encV and store them at vector:digitsV\n    std::vector<Ctxt> digitsV;\n    extractDigits(digitsV, encV);\n\n     \n    std::vector<Ctxt> digitsenc1;\n    extractDigits(digitsenc1, enc1);\n\n    /*************************************************************/\n    /***decrypt each digit of encV to see if extractDigits work*****/\n    /***************************************************************/\n\n\n    \n    long res1[digitsV.size()];\n    for (int i=0;i<digitsV.size();i++){\n    ZZX result;\n    sk.Decrypt(result,digitsV[i]);\n    if (result[0]>(pow(p,r))/2){ result[0]=result[0]-pow(p,r);}\n    res1[i]=conv<long>(result[0]);\n    }\n    size_t res1_size = sizeof(res1)/sizeof(res1[0]);\n    std::reverse(res1, res1 + res1_size);\n    std::cout<< \"V:\";\n    for (int i=0;i<digitsV.size();i++){\n        std::cout << res1[i] << \",\";\n    }\n    std::cout<< std::endl;\n    /*******CORRECT******/\n\n     //extractdigits of encV and store them at vector:digitsY\n    //td::vector<Ctxt> digitsY;\n    //extractDigits(digitsY, encY);\n\n\n    /*************************************************************/\n    /***decrypt each digit of encY to see if extractDigits work*****/\n    /***************************************************************/\n\n    /*long dig[digitsY.size()];\n    for (int i=0;i<digitsY.size();i++){\n     ZZX resultY;\n    sk.Decrypt(resultY,digitsY[i]);\n    if (resultY[0]>(pow(p,r))/2){ resultY[0]=resultY[0]-pow(p,r);}\n    dig[i]=conv<long>(resultY[0]);\n    }\n    size_t dig_size = sizeof(dig)/sizeof(dig[0]);\n    std::reverse(dig, dig + dig_size);\n    std::cout<< \"Y:\";\n    for (int i=0;i<digitsY.size();i++){\n        std::cout << dig[i] << \",\";\n    }\n    std::cout<< std::endl;\n    */\n\n    //input all encrypted numbers on list \n    std::vector<Ctxt> list;\n    \n        list.push_back(encU);\n        list.push_back(encV);\n        //list.push_back(encY);\n        //list.push_back(encZ);\n    \n\n    Timer timecompare;\n    timecompare.start();\n    \n   \t//calculate the encrypted minimum of the list\n    std::vector<Ctxt> kappa=minimum( list, enc1);\n     \n     timecompare.stop();\n    \n\n   \n\n\n     //decryption of the minimum \n    long res2[digitsV.size()];\n    for (int i=0;i<digitsV.size();i++){\n    \n        ZZX result2;\n        sk.Decrypt(result2,kappa[i]);\n        \n        res2[i]=conv<long>(result2[0]);\n    }\n    //the number\n    std::cout<< \"the minimum number is:\";\n    int min=0,flow;\n    for (int i=0;i<digitsV.size();i++){\n        flow=pow(2,i)*res2[i];\n        min+=flow;\n    }\n    std::cout << min << std::endl;\n    std::cout << \"and his binary form is:\" ;\n    //the binary form of the number\n    size_t res2_size = sizeof(res2)/sizeof(res2[0]);\n    std::reverse(res2, res2 + res2_size);\n    for (int i=0;i<digitsU.size();i++){\n        std::cout << res2[i] << \",\" ;\n    }\n    std::cout<< std::endl;\n    std::cout << \"the time to compute minimum is:\" << timecompare.elapsed_time() << std::endl;\n\n    \n\n    std::cout << std::endl;\n\n     return 0;\n\n\n\n\n}\n", "meta": {"hexsha": "a3bc8b9854a4646571608f8ff11db0a5bbff6bcc", "size": 10041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homcomparison.cpp", "max_stars_repo_name": "MikeAnast/Homomorphic-comparison-using-Helib", "max_stars_repo_head_hexsha": "cd10fe0360541acb4cfcd125dda6ca2e25d4b3c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T01:00:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:52:55.000Z", "max_issues_repo_path": "homcomparison.cpp", "max_issues_repo_name": "MikeAnast/Homomorphic-comparison-using-Helib", "max_issues_repo_head_hexsha": "cd10fe0360541acb4cfcd125dda6ca2e25d4b3c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homcomparison.cpp", "max_forks_repo_name": "MikeAnast/Homomorphic-comparison-using-Helib", "max_forks_repo_head_hexsha": "cd10fe0360541acb4cfcd125dda6ca2e25d4b3c7", "max_forks_repo_licenses": ["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.2113821138, "max_line_length": 131, "alphanum_fraction": 0.5263419978, "num_tokens": 2823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5310617024976704}}
{"text": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/time.h>\n#include <stdlib.h>\n#include <math.h>\n#include <inttypes.h>\n#include <string.h>\n#include <adept_source.h>\n#include <adept.h>\nusing adept::adouble;\n\ntemplate<typename Return, typename... T>\nReturn __enzyme_autodiff(T...);\n\nfloat tdiff(struct timeval *start, struct timeval *end) {\n  return (end->tv_sec-start->tv_sec) + 1e-6*(end->tv_usec-start->tv_usec);\n}\n\n#include \"fft.h\"\n\nvoid foobar(double* data, unsigned len) {\n  fft(data, len);\n  ifft(data, len);\n}\n\nvoid afoobar(aVector& data, unsigned len) {\n  fft(data, len);\n  ifft(data, len);\n}\n\nextern \"C\" {\n  int enzyme_dupnoneed;\n}\n\nstatic double foobar_and_gradient(unsigned len) {\n    double *inp = new double[2*len];\n    for(int i=0; i<2*len; i++) inp[i] = 2.0;\n    double *dinp = new double[2*len];\n    for(int i=0; i<2*len; i++) dinp[i] = 1.0;\n    __enzyme_autodiff<void>(foobar, enzyme_dupnoneed, inp, dinp, len);\n    double res = dinp[0];\n    delete[] dinp;\n    delete[] inp;\n    return res;\n}\n\nstatic double afoobar_and_gradient(unsigned len) {\n    adept::Stack stack;\n\n    aVector x(2*len);\n    for(int i=0; i<2*len; i++) x(i) = 2.0;\n    stack.new_recording();\n    afoobar(x, len);\n    for(int i=0; i<2*len; i++)\n      x(i).set_gradient(1.0);\n    stack.compute_adjoint();\n\n    double *dinp = new double[2*len];\n    for(int i=0; i<2*len; i++)\n      dinp[i] = x(i).get_gradient();\n    double res = dinp[0];\n    delete[] dinp;\n    return res;\n}\n\n\nstatic double tfoobar_and_gradient(unsigned len) {\n    double *inp = new double[2*len];\n    for(int i=0; i<2*len; i++) inp[i] = 2.0;\n    double *dinp = new double[2*len];\n    for(int i=0; i<2*len; i++) dinp[i] = 1.0;\n    foobar_b(inp, dinp, len);\n    double res = dinp[0];\n    delete[] dinp;\n    delete[] inp;\n    return res;\n}\n\nstatic void adept_sincos(double inp, unsigned len) {\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double *x = new double[2*len];\n  for(int i=0; i<2*len; i++) x[i] = 2.0;\n  foobar(x, len);\n  double res = x[0];\n\n  gettimeofday(&end, NULL);\n  printf(\"Adept real %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  delete[] x;\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  adept::Stack stack;\n\n  aVector x(2*len);\n  for(int i=0; i<2*len; i++) x[i] = 2.0;\n // stack.new_recording();\n  afoobar(x, len);\n  double res = x(0).value();\n\n  gettimeofday(&end, NULL);\n  printf(\"Adept forward %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res2 = afoobar_and_gradient(len);\n\n  gettimeofday(&end, NULL);\n  printf(\"Adept combined %0.6f res'=%f\\n\", tdiff(&start, &end), res2);\n  }\n}\n\n\nstatic void tapenade_sincos(double inp, unsigned len) {\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double *x = new double[2*len];\n  for(int i=0; i<2*len; i++) x[i] = 2.0;\n  foobar(x, len);\n  double res = x[0];\n\n  gettimeofday(&end, NULL);\n  printf(\"Tapenade real %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  delete[] x;\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double* x = new double[2*len];\n  for(int i=0; i<2*len; i++) x[i] = 2.0;\n  foobar(x, len);\n  double res = x[0];\n\n  gettimeofday(&end, NULL);\n  printf(\"Tapenade forward %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  delete[] x;\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res2 = tfoobar_and_gradient(len);\n\n  gettimeofday(&end, NULL);\n  printf(\"Tapenade combined %0.6f res'=%f\\n\", tdiff(&start, &end), res2);\n  }\n}\n\nstatic void enzyme_sincos(double inp, unsigned len) {\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double *x = new double[2*len];\n  for(int i=0; i<2*len; i++) x[i] = 2.0;\n  foobar(x, len);\n  double res = x[0];\n\n  gettimeofday(&end, NULL);\n  printf(\"Enzyme real %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  delete[] x;\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double *x = new double[2*len];\n  for(int i=0; i<2*len; i++) x[i] = 2.0;\n  foobar(x, len);\n  double res = x[0];\n\n  gettimeofday(&end, NULL);\n  printf(\"Enzyme forward %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  delete[] x;\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res2 = foobar_and_gradient(len);\n\n  gettimeofday(&end, NULL);\n  printf(\"Enzyme combined %0.6f res'=%f\\n\", tdiff(&start, &end), res2);\n  }\n}\n\n\n/* Function to check if x is power of 2*/\nbool isPowerOfTwo (int x)\n{\n    /* First x in the below expression is for the case when x is 0 */\n    return x && (!(x&(x-1)));\n}\n\nunsigned max(unsigned A, unsigned B){\n  if (A>B) return A;\n  return B;\n}\n\nint main(int argc, char** argv) {\n\n  if (argc < 2) {\n    printf(\"usage %s n [must be power of 2]\\n\", argv[0]);\n    return 1;\n  }\n  unsigned N = atoi(argv[1]);\n  if (!isPowerOfTwo(N)) {\n    printf(\"usage %s n [must be power of 2]\\n\", argv[0]);\n    return 1;\n  }\n  double inp = -2.1;\n\n  for(unsigned iters=max(1, N>>5); iters <= N; iters*=2) {\n    printf(\"iters=%d\\n\", iters);\n    adept_sincos(inp, iters);\n    tapenade_sincos(inp, iters);\n    enzyme_sincos(inp, iters);\n  }\n}\n", "meta": {"hexsha": "cf9459b9597a351812834aa13e3cec45526e840d", "size": 5133, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enzyme/benchmarks/fft/fft.cpp", "max_stars_repo_name": "anandijain/Enzyme", "max_stars_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 674.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T17:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T11:18:11.000Z", "max_issues_repo_path": "enzyme/benchmarks/fft/fft.cpp", "max_issues_repo_name": "anandijain/Enzyme", "max_issues_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2020-10-07T00:47:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T16:46:58.000Z", "max_forks_repo_path": "enzyme/benchmarks/fft/fft.cpp", "max_forks_repo_name": "anandijain/Enzyme", "max_forks_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T14:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:51:07.000Z", "avg_line_length": 21.5672268908, "max_line_length": 74, "alphanum_fraction": 0.6088057666, "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.5310616895251699}}
{"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#define BOOST_TEST_MAIN\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/Basics/timeType.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_time_type )\n\nusing namespace mathematical_constants;\n\n//! Test if Time objects cast to the expected precision\nBOOST_AUTO_TEST_CASE( testTimeBasicCasts )\n{\n    Time testTime( 2, LONG_PI );\n\n    //Test if Time casts to double/long double at the expected precision\n    {\n\n        BOOST_CHECK_CLOSE_FRACTION( testTime.getSeconds< long double >( ), 2.0L * TIME_NORMALIZATION_TERM + LONG_PI,\n                                    std::numeric_limits< long double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( testTime.getSeconds< double >( ), 2.0 * TIME_NORMALIZATION_TERM + PI,\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( static_cast< long double >( testTime ), 2.0L * TIME_NORMALIZATION_TERM + LONG_PI,\n                                    std::numeric_limits< long double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( static_cast< double >( testTime ),  2.0 * TIME_NORMALIZATION_TERM + PI,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test if Time pre-/post-multiplies Eigen vectors at expected level of precision\n    {\n        Eigen::Vector3d testVector = ( Eigen::Vector3d(  ) << 4.5, 4.5, 4.5 ).finished( );\n        Eigen::Matrix< long double, 3, 1 > testVectorLong = ( Eigen::Matrix< long double, 3, 1 >(  ) << 4.5L, 4.5L, 4.5L ).finished( );\n\n        Eigen::Vector3d multipliedTestVector = testTime * testVector;\n        Eigen::Matrix< long double, 3, 1 > multipliedTestVectorLong = testTime * testVectorLong;\n\n        for( unsigned int i = 0; i < 3; i++ )\n        {\n            BOOST_CHECK_CLOSE_FRACTION( multipliedTestVector( i ), multipliedTestVectorLong( i ),\n                                        std::numeric_limits< double >::epsilon( ) );\n            BOOST_CHECK_CLOSE_FRACTION( 4.5L * ( 2.0L * TIME_NORMALIZATION_TERM + LONG_PI ), multipliedTestVectorLong( i ),\n                                        std::numeric_limits< long double >::epsilon( ) );\n        }\n\n        multipliedTestVector = testVector * testTime;\n        multipliedTestVectorLong = testVectorLong * testTime;\n\n        for( unsigned int i = 0; i < 3; i++ )\n        {\n            BOOST_CHECK_CLOSE_FRACTION( multipliedTestVector( i ), multipliedTestVectorLong( i ),\n                                        std::numeric_limits< double >::epsilon( ) );\n            BOOST_CHECK_CLOSE_FRACTION( 4.5L * ( 2.0L * TIME_NORMALIZATION_TERM + LONG_PI ), multipliedTestVectorLong( i ),\n                                        std::numeric_limits< long double >::epsilon( ) );\n        }\n    }\n}\n\n//! Test if time saves/retrieves entries at the expected level of precision.\nBOOST_AUTO_TEST_CASE( testTimeContentsPrecision )\n{\n    int numberOfDays = 759;\n    long double numberOfSeconds = 2.0L * TIME_NORMALIZATION_TERM + LONG_PI;\n\n    Time testTime( numberOfDays, numberOfSeconds );\n    BOOST_CHECK_EQUAL( testTime.getFullPeriods( ), numberOfDays + 2 );\n    BOOST_CHECK_CLOSE_FRACTION( testTime.getSecondsIntoFullPeriod( ), LONG_PI,\n                                TIME_NORMALIZATION_TERM * std::numeric_limits< long double >::epsilon( ) );\n\n    numberOfSeconds = -2.0L * TIME_NORMALIZATION_TERM + LONG_PI;\n\n    Time testTime2 = Time( numberOfDays, numberOfSeconds );\n    BOOST_CHECK_EQUAL( testTime2.getFullPeriods( ), numberOfDays - 2 );\n    BOOST_CHECK_CLOSE_FRACTION( testTime2.getSecondsIntoFullPeriod( ), LONG_PI,\n                                TIME_NORMALIZATION_TERM * std::numeric_limits< long double >::epsilon( ) );\n\n    Time testTime3 = testTime2;\n    BOOST_CHECK_EQUAL( testTime2.getSecondsIntoFullPeriod( ), testTime3.getSecondsIntoFullPeriod( ) );\n    BOOST_CHECK_EQUAL( testTime2.getFullPeriods( ), testTime3.getFullPeriods( ) );\n\n    numberOfSeconds = -2.0L * TIME_NORMALIZATION_TERM - LONG_PI;\n\n    Time testTime4 = Time( numberOfDays, numberOfSeconds );\n    BOOST_CHECK_EQUAL( testTime4.getFullPeriods( ), numberOfDays - 3 );\n    BOOST_CHECK_CLOSE_FRACTION( testTime4.getSecondsIntoFullPeriod( ), TIME_NORMALIZATION_TERM - LONG_PI,\n                                TIME_NORMALIZATION_TERM * std::numeric_limits< long double >::epsilon( ) );\n\n}\n\n//! Test basic arithmetic operations of time object\nBOOST_AUTO_TEST_CASE( testArithmeticOperations )\n{\n    {\n        // Define Time test values\n        int numberOfDays1 = 759;\n        long double numberOfSeconds1 = 2566.8309405984728595902;\n        Time inputTime1( numberOfDays1, numberOfSeconds1 );\n\n        int numberOfDays2 = 2;\n        long double numberOfSeconds2 = 1432.48492385475949349;\n        Time inputTime2( numberOfDays2, numberOfSeconds2 );\n\n        Time outputTime;\n\n        // Test Time additions\n        {\n            outputTime = inputTime1 + inputTime2;\n            BOOST_CHECK_EQUAL( numberOfDays1 + numberOfDays2 + 1, outputTime.getFullPeriods( ) );\n            BOOST_CHECK_CLOSE_FRACTION( numberOfSeconds1 + numberOfSeconds2 - TIME_NORMALIZATION_TERM,\n                                        outputTime.getSecondsIntoFullPeriod( ),\n                                        std::numeric_limits< long double >::epsilon( ) );\n            outputTime = inputTime1;\n            outputTime += inputTime2;\n            BOOST_CHECK_EQUAL( numberOfDays1 + numberOfDays2 + 1, outputTime.getFullPeriods( ) );\n            BOOST_CHECK_CLOSE_FRACTION( numberOfSeconds1 + numberOfSeconds2 - TIME_NORMALIZATION_TERM,\n                                        outputTime.getSecondsIntoFullPeriod( ),\n                                        std::numeric_limits< long double >::epsilon( ) );\n        }\n\n        // Test addition between doubles and Time\n        {\n            outputTime = inputTime1 + numberOfSeconds2;\n            BOOST_CHECK_EQUAL( numberOfDays1 + 1, outputTime.getFullPeriods( ) );\n            BOOST_CHECK_CLOSE_FRACTION( numberOfSeconds1 + numberOfSeconds2 - TIME_NORMALIZATION_TERM,\n                                        outputTime.getSecondsIntoFullPeriod( ),\n                                        std::numeric_limits< long double >::epsilon( ) );\n\n            outputTime = inputTime1;\n            outputTime += numberOfSeconds2;\n            BOOST_CHECK_EQUAL( numberOfDays1 + 1, outputTime.getFullPeriods( ) );\n            BOOST_CHECK_CLOSE_FRACTION( numberOfSeconds1 + numberOfSeconds2 - TIME_NORMALIZATION_TERM,\n                                        outputTime.getSecondsIntoFullPeriod( ),\n                                        std::numeric_limits< long double >::epsilon( ) );\n\n            outputTime = numberOfSeconds2 + inputTime1;\n            BOOST_CHECK_EQUAL( numberOfDays1 + 1, outputTime.getFullPeriods( ) );\n            BOOST_CHECK_CLOSE_FRACTION( numberOfSeconds1 + numberOfSeconds2 - TIME_NORMALIZATION_TERM,\n                                        outputTime.getSecondsIntoFullPeriod( ),\n                                        std::numeric_limits< long double >::epsilon( ) );\n        }\n\n        // Test subtractions of Time objects\n        {\n            outputTime = inputTime2 - inputTime1;\n            BOOST_CHECK_EQUAL( numberOfDays2 - numberOfDays1 - 1, outputTime.getFullPeriods( ) );\n            BOOST_CHECK_CLOSE_FRACTION( numberOfSeconds2 - numberOfSeconds1 + TIME_NORMALIZATION_TERM,\n                                        outputTime.getSecondsIntoFullPeriod( ),\n                                        std::numeric_limits< long double >::epsilon( ) );\n            outputTime = inputTime2;\n            outputTime -= inputTime1;\n            BOOST_CHECK_EQUAL( numberOfDays2 - numberOfDays1 - 1, outputTime.getFullPeriods( ) );\n            BOOST_CHECK_CLOSE_FRACTION( numberOfSeconds2 - numberOfSeconds1 + TIME_NORMALIZATION_TERM,\n                                        outputTime.getSecondsIntoFullPeriod( ),\n                                        std::numeric_limits< long double >::epsilon( ) );\n\n            outputTime = inputTime2 - numberOfSeconds1;\n            BOOST_CHECK_EQUAL( numberOfDays2 - 1, outputTime.getFullPeriods( ) );\n            BOOST_CHECK_CLOSE_FRACTION( numberOfSeconds2 - numberOfSeconds1 + TIME_NORMALIZATION_TERM,\n                                        outputTime.getSecondsIntoFullPeriod( ),\n                                        std::numeric_limits< long double >::epsilon( ) );\n\n            outputTime = numberOfSeconds2 - inputTime1;\n            BOOST_CHECK_EQUAL( -numberOfDays1 - 1, outputTime.getFullPeriods( ) );\n            BOOST_CHECK_CLOSE_FRACTION( numberOfSeconds2 - numberOfSeconds1 + TIME_NORMALIZATION_TERM,\n                                        outputTime.getSecondsIntoFullPeriod( ),\n                                        std::numeric_limits< long double >::epsilon( ) );\n        }\n\n    }\n\n    // Test division of Time by double/long double values\n    {\n        // Define Time test values\n        Time testTime( 2, LONG_PI );\n\n        Time dividedTime = testTime / 2.0L;\n        BOOST_CHECK_EQUAL( dividedTime.getFullPeriods( ), 1 );\n        BOOST_CHECK_CLOSE_FRACTION( dividedTime.getSecondsIntoFullPeriod( ),\n                                    LONG_PI / 2.0L,\n                                    2.0 * std::numeric_limits< long double >::epsilon( ) );\n\n        dividedTime = testTime / 2.0;\n        BOOST_CHECK_EQUAL( dividedTime.getFullPeriods( ), 1 );\n        BOOST_CHECK_CLOSE_FRACTION( dividedTime.getSecondsIntoFullPeriod( ),\n                                    LONG_PI / 2.0L,\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n\n        dividedTime = testTime / 3.0L;\n        BOOST_CHECK_EQUAL( dividedTime.getFullPeriods( ), 0 );\n        BOOST_CHECK_CLOSE_FRACTION( dividedTime.getSecondsIntoFullPeriod( ),\n                                    LONG_PI / 3.0L + TIME_NORMALIZATION_TERM * 2.0L / 3.0L,\n                                    2.0 *std::numeric_limits< long double >::epsilon( ) );\n        dividedTime = testTime / 3.0;\n        BOOST_CHECK_EQUAL( dividedTime.getFullPeriods( ), 0 );\n        BOOST_CHECK_CLOSE_FRACTION( dividedTime.getSecondsIntoFullPeriod( ),\n                                    LONG_PI / 3.0L + TIME_NORMALIZATION_TERM * 2.0L / 3.0L,\n                                    2.0 *std::numeric_limits< double >::epsilon( ) );\n\n        testTime = Time( 9, 8.0 * LONG_PI );\n        dividedTime = testTime / 2.0L;\n        BOOST_CHECK_EQUAL( dividedTime.getFullPeriods( ), 4 );\n        BOOST_CHECK_CLOSE_FRACTION( dividedTime.getSecondsIntoFullPeriod( ),\n                                    LONG_PI * 4.0L + TIME_NORMALIZATION_TERM / 2.0L,\n                                    2.0 * std::numeric_limits< long double >::epsilon( ) );\n        dividedTime = testTime / 2.0;\n        BOOST_CHECK_EQUAL( dividedTime.getFullPeriods( ), 4 );\n        BOOST_CHECK_CLOSE_FRACTION( dividedTime.getSecondsIntoFullPeriod( ),\n                                    LONG_PI * 4.0L + TIME_NORMALIZATION_TERM / 2.0L,\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n\n        dividedTime = testTime / 3.0L;\n        BOOST_CHECK_EQUAL( dividedTime.getFullPeriods( ), 3 );\n        BOOST_CHECK_CLOSE_FRACTION( dividedTime.getSecondsIntoFullPeriod( ),\n                                    LONG_PI * 8.0L / 3.0L,\n                                    2.0 * std::numeric_limits< long double >::epsilon( ) );\n        dividedTime = testTime / 3.0;\n        BOOST_CHECK_EQUAL( dividedTime.getFullPeriods( ), 3 );\n        BOOST_CHECK_CLOSE_FRACTION( dividedTime.getSecondsIntoFullPeriod( ),\n                                    LONG_PI * 8.0L / 3.0L,\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test multiplication of Time by double/long double values\n    {\n        Time testTime( 5, 1200.0L + LONG_PI );\n        Time multipliedTime = testTime * 2.0L;\n        BOOST_CHECK_EQUAL( multipliedTime.getFullPeriods( ), 10 );\n        BOOST_CHECK_CLOSE_FRACTION( multipliedTime.getSecondsIntoFullPeriod( ),\n                                    2400.0L + LONG_PI * 2.0L,\n                                    2.0 * std::numeric_limits< long double >::epsilon( ) );\n\n        multipliedTime = testTime * 3.0L;\n        BOOST_CHECK_EQUAL( multipliedTime.getFullPeriods( ), 16 );\n        BOOST_CHECK_CLOSE_FRACTION( multipliedTime.getSecondsIntoFullPeriod( ),\n                                    LONG_PI * 3.0L,\n                                    200.0 * std::numeric_limits< long double >::epsilon( ) );\n\n        multipliedTime = 2.0L * testTime;\n        BOOST_CHECK_EQUAL( multipliedTime.getFullPeriods( ), 10 );\n        BOOST_CHECK_CLOSE_FRACTION( multipliedTime.getSecondsIntoFullPeriod( ),\n                                    2400.0L + LONG_PI * 2.0L,\n                                    2.0 * std::numeric_limits< long double >::epsilon( ) );\n\n        multipliedTime = 3.0L * testTime;\n        BOOST_CHECK_EQUAL( multipliedTime.getFullPeriods( ), 16 );\n        BOOST_CHECK_CLOSE_FRACTION( multipliedTime.getSecondsIntoFullPeriod( ),\n                                    LONG_PI * 3.0L,\n                                    200.0 * std::numeric_limits< long double >::epsilon( ) );\n\n        multipliedTime = testTime * 2.0;\n        BOOST_CHECK_EQUAL( multipliedTime.getFullPeriods( ), 10 );\n        BOOST_CHECK_CLOSE_FRACTION( multipliedTime.getSecondsIntoFullPeriod( ),\n                                    2400.0 + LONG_PI * 2.0,\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n\n        multipliedTime = testTime * 3.0;\n        BOOST_CHECK_EQUAL( multipliedTime.getFullPeriods( ), 16 );\n        BOOST_CHECK_CLOSE_FRACTION( multipliedTime.getSecondsIntoFullPeriod( ),\n                                    PI * 3.0,\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n\n        multipliedTime = 2.0 * testTime;\n        BOOST_CHECK_EQUAL( multipliedTime.getFullPeriods( ), 10 );\n        BOOST_CHECK_CLOSE_FRACTION( multipliedTime.getSecondsIntoFullPeriod( ),\n                                    2400.0 + LONG_PI * 2.0,\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n\n        multipliedTime = 3.0 * testTime;\n        BOOST_CHECK_EQUAL( multipliedTime.getFullPeriods( ), 16 );\n        BOOST_CHECK_CLOSE_FRACTION( multipliedTime.getSecondsIntoFullPeriod( ),\n                                    PI * 3.0,\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n\n\n    }\n}\n\n//! Test if the comparison operators defined for the Time object function correctly\nBOOST_AUTO_TEST_CASE( testComparisonOperators )\n{\n    for( unsigned int i = 0; i < 4; i++ )\n    {\n        // Define test time (same for each test)\n        int numberOfDays = 759;\n        long double numberOfSeconds = 2.0L * TIME_NORMALIZATION_TERM + LONG_PI;\n\n        Time testTime( numberOfDays, numberOfSeconds );\n        double testTimeDouble = testTime.getSeconds< double >( );\n        long double testTimeLongDouble = testTime.getSeconds< long double >( );\n\n        // Define test time (different values for each test)\n        Time testTime2 = TUDAT_NAN;\n        double testTimeDouble2 = TUDAT_NAN;\n        long double testTimeLongDouble2 = TUDAT_NAN;\n\n        // Check comparison if only seconds is larger\n        if( i == 0 )\n        {\n            testTime2 = Time( numberOfDays, numberOfSeconds + 1.0L );\n            testTimeDouble2 = testTime.getSeconds< double >( ) + 1.0;\n            testTimeLongDouble2 = testTime.getSeconds< long double >( ) + 1.0L;\n        }\n        // Check comparison if only hours is larger\n        else if( i == 1 )\n        {\n            testTime2 = Time( numberOfDays + 3, numberOfSeconds );\n            testTimeDouble2 = testTime.getSeconds< double >( ) + 3.0 * TIME_NORMALIZATION_TERM;\n            testTimeLongDouble2 = testTime.getSeconds< long double >( ) + 3.0L * TIME_NORMALIZATION_TERM;\n        }\n        // Check comparison if hours is larger and seconds is larger\n        else if( i == 2 )\n        {\n            testTime2 = Time( numberOfDays + 3, numberOfSeconds + 1.0L );\n            testTimeDouble2 = testTime.getSeconds< double >( ) + 3.0 * TIME_NORMALIZATION_TERM + 1.0;\n            testTimeLongDouble2 = testTime.getSeconds< long double >( ) + 3.0L * TIME_NORMALIZATION_TERM + 1.0L;\n        }\n        // Check comparison if hours is larger and seconds is smaller\n        else if( i == 3 )\n        {\n            testTime2 = Time( numberOfDays + 3, numberOfSeconds - 1.0L );\n            testTimeDouble2 = testTime.getSeconds< double >( ) + 3.0 * TIME_NORMALIZATION_TERM  - 1.0;\n            testTimeLongDouble2 = testTime.getSeconds< long double >( ) + 3.0L * TIME_NORMALIZATION_TERM - 1.0L;\n        }\n\n        // Check equals comparison\n        BOOST_CHECK( testTime == testTimeDouble );\n        BOOST_CHECK( testTime == testTimeLongDouble );\n        BOOST_CHECK( testTime == testTime );\n\n        BOOST_CHECK( testTimeDouble  == testTime );\n        BOOST_CHECK( testTimeLongDouble  == testTime );\n        BOOST_CHECK( testTimeLongDouble  == testTime );\n\n        // Check not-equals comparison\n        BOOST_CHECK( testTime2 != testTimeDouble );\n        BOOST_CHECK( testTime2 != testTimeLongDouble );\n        BOOST_CHECK( testTime2 != testTime );\n\n        BOOST_CHECK( testTimeDouble  != testTime2 );\n        BOOST_CHECK( testTimeLongDouble  != testTime2 );\n\n        // Check (strict) greater/less than\n        BOOST_CHECK( testTime2 > testTimeDouble );\n        BOOST_CHECK( testTime2 > testTimeLongDouble );\n        BOOST_CHECK( testTime2 > testTime );\n\n\n        BOOST_CHECK( testTimeDouble < testTime2 );\n        BOOST_CHECK( testTimeLongDouble  < testTime2 );\n\n        BOOST_CHECK( testTime2 >= testTimeDouble );\n        BOOST_CHECK( testTime2 >= testTimeLongDouble );\n        BOOST_CHECK( testTime2 >= testTime );\n\n        BOOST_CHECK( testTime >= testTime );\n\n        BOOST_CHECK( testTimeDouble <= testTime2 );\n        BOOST_CHECK( testTimeLongDouble  <= testTime2 );\n\n        // Check (strict) greater/less than (opposite direction)\n        BOOST_CHECK( testTime < testTimeDouble2 );\n        BOOST_CHECK( testTime < testTimeLongDouble2 );\n        BOOST_CHECK( testTime < testTime2 );\n\n        BOOST_CHECK( testTimeDouble2 > testTime );\n        BOOST_CHECK( testTimeLongDouble2  > testTime );\n\n        BOOST_CHECK( testTime <= testTimeDouble2 );\n        BOOST_CHECK( testTime <= testTimeLongDouble2 );\n        BOOST_CHECK( testTime <= testTime2 );\n\n        BOOST_CHECK( testTimeDouble2 >= testTime );\n        BOOST_CHECK( testTimeLongDouble2  >= testTime );\n\n        // Check if comparison picks up small differences\n        long double currentFullSeconds = testTime2.getSecondsIntoFullPeriod( );\n        BOOST_CHECK( testTime2 != testTime2 + currentFullSeconds * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK( testTime2 < testTime2 + currentFullSeconds * std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK( testTime2 != testTime2 - currentFullSeconds * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK( testTime2 > testTime2 - currentFullSeconds * std::numeric_limits< double >::epsilon( ) );\n\n        long double testTimeLongDouble2Rounded = testTimeLongDouble2 *\n                ( 1.0L + 2.0L * std::numeric_limits< long double >::epsilon( ) );\n        BOOST_CHECK( testTime2 != testTimeLongDouble2Rounded );\n        BOOST_CHECK( testTime2 < testTimeLongDouble2Rounded );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n}\n\n}\n\n", "meta": {"hexsha": "2aea32e7693afec2746d9cdd8fa6358a52c021b9", "size": 20106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Basics/UnitTests/unitTestTimeTypes.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/Basics/UnitTests/unitTestTimeTypes.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/Basics/UnitTests/unitTestTimeTypes.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": 48.6828087167, "max_line_length": 135, "alphanum_fraction": 0.6037501243, "num_tokens": 4583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.5310479169372454}}
{"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_STIRLING_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_STIRLING_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-euler\n    This function object computes an approwimation of the gamma function\n    using the Stirling formula:\n  \\f$\\sqrt{2 \\pi} x^{x-\\frac12} e^{-x} ( 1 + \\frac1{x} P(\\frac1{x}))\\f$,\n    where \\f$P\\f$ is a polynomial.\n\n    @see gamma, gammaln\n\n\n    @par Header <boost/simd/function/stirling.hpp>\n\n    @par Example:\n\n      @snippet stirling.cpp stirling\n\n    @par Possible output:\n\n      @snippet stirling.txt stirling\n\n  **/\n  Value stirling(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/stirling.hpp>\n#include <boost/simd/function/simd/stirling.hpp>\n\n#endif\n", "meta": {"hexsha": "2efad590d18a22c8dec03d50465874359338de66", "size": 1161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/stirling.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/function/stirling.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/function/stirling.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": 25.2391304348, "max_line_length": 100, "alphanum_fraction": 0.5839793282, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5310479107040308}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <robotics/common.hpp>\n\nnamespace Robotics::Model {\n\n    /**\n     * @brief A class for implemeting a generic dynamical system. Mostly serves to describe an\n     * interface.\n     */\n    template <int StateSize, int InputSize, int OutputSize>\n    class SystemBase {\n        static_assert(StateSize > 0);\n        static_assert(InputSize > 0);\n        static_assert(OutputSize > 0);\n\n      public:\n        using State = ColumnVector<StateSize>;\n        using Input = ColumnVector<InputSize>;\n        using Output = ColumnVector<OutputSize>;\n\n        using StateMatrix = SquareMatrix<StateSize>;\n        using InputMatrix = Matrix<StateSize, InputSize>;\n        using OutputMatrix = Matrix<OutputSize, StateSize>;\n        using FeedthroughMatrix = Matrix<OutputSize, StateSize>;\n\n        /**\n         * @brief Propagates the state for one time step\n         * @param u system input\n         */\n        virtual void PropagateDynamics(const Input& u, double dt) = 0;\n\n        /**\n         * @brief Updates the internal state of the system, which will become the new initial\n         * condition\n         * @param state new state\n         */\n        void SetInitialState(State state) { x = state; }\n\n        /**\n         * @brief Gets the latest state computed\n         * @return the latest state\n         */\n        State GetState() const { return x; }\n\n        /**\n         * @brief Gets the current output of the system\n         * @return the current output\n         */\n        Output GetOutput()\n        {\n            y = C * x;\n            return y;\n        }\n\n        /**\n         * @brief Gets the system's output matrix\n         * @return theoutput matrix\n         */\n        OutputMatrix GetOutputMatrix() const { return C; }\n\n        /**\n         * @brief Gets a noisy output reading\n         * @param noise noise statistic for the output reading\n         * @return the noisy output reading\n         */\n        Output GetNoisyMeasurement(const SquareMatrix<OutputSize>& noise)\n        {\n            return C * x + noise * random.GetColumnVector<OutputSize>();\n        }\n\n      protected:\n        State x{State::Zero()};\n        Output y{Output::Zero()};\n\n        StateMatrix A;\n        InputMatrix B;\n        OutputMatrix C;\n        FeedthroughMatrix D;\n\n        Robotics::NormalDistributionRandomGenerator random;\n    };\n\n}  // namespace Robotics::Model", "meta": {"hexsha": "d1e9af1733aacdf9da4f93bc7e6f2b43bbe509ed", "size": 2402, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/robotics/system/system_base.hpp", "max_stars_repo_name": "JKI757/CppRobotics", "max_stars_repo_head_hexsha": "469ce89f826b4cb981b017d9112ed311f39114b5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 286.0, "max_stars_repo_stars_event_min_datetime": "2021-09-27T20:58:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T19:12:10.000Z", "max_issues_repo_path": "include/robotics/system/system_base.hpp", "max_issues_repo_name": "imthemd/CppRobotics", "max_issues_repo_head_hexsha": "469ce89f826b4cb981b017d9112ed311f39114b5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T02:19:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-30T19:46:08.000Z", "max_forks_repo_path": "include/robotics/system/system_base.hpp", "max_forks_repo_name": "imthemd/CppRobotics", "max_forks_repo_head_hexsha": "469ce89f826b4cb981b017d9112ed311f39114b5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-28T01:26:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T11:01:01.000Z", "avg_line_length": 28.2588235294, "max_line_length": 94, "alphanum_fraction": 0.581182348, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5310479052894442}}
{"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#ifndef R10_HPP_\n#define R10_HPP_\n\n#include <boost/graph/isomorphism.hpp>\n\nnamespace unimod\n{\n\n  /**\n   * Singleton class to test a bipartite graph to be ismorphic to the graphs representing R10.\n   */\n\n  class bipartite_r10_graphs\n  {\n  public:\n    typedef boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS> graph_t;\n\n  private:\n\n    /**\n     * Constructs the R10 graph class.\n     */\n\n    bipartite_r10_graphs()\n    {\n      typedef std::pair <int, int> E;\n\n      E g1_edges[] =\n      { E(0, 5), E(0, 8), E(0, 9), E(1, 5), E(1, 6), E(1, 9), E(2, 6), E(2, 7), E(2, 9), E(3, 7), E(3, 8), E(3, 9), E(4, 5), E(4, 6), E(4, 7),\n          E(4, 8), E(4, 9) };\n      g1 = graph_t(&g1_edges[0], &g1_edges[0] + sizeof(g1_edges) / sizeof(E), 10);\n\n      E g2_edges[] =\n      { E(0, 5), E(0, 8), E(0, 9), E(1, 5), E(1, 6), E(1, 8), E(2, 6), E(2, 7), E(2, 9), E(3, 7), E(3, 8), E(3, 9), E(4, 5), E(4, 6), E(4, 7) };\n      g2 = graph_t(&g2_edges[0], &g2_edges[0] + sizeof(g2_edges) / sizeof(E), 10);\n    }\n\n    /**\n     * Singleton instance function.\n     *\n     * @return The unique instance\n     */\n\n    static bipartite_r10_graphs& instance()\n    {\n      static bipartite_r10_graphs* instance = NULL;\n      if (instance == NULL)\n        instance = new bipartite_r10_graphs();\n      return *instance;\n    }\n\n  public:\n\n    /**\n     * Checks a given graph to be isomorphic to the ones stored.\n     *\n     * @param graph Given graph\n     * @return true if and only if it is isomorphic to any of the two stored ones.\n     */\n\n    template <typename Graph>\n    static bool is_r10_graph(const Graph& graph)\n    {\n      return boost::isomorphism(graph, instance().g1) || boost::isomorphism(graph, instance().g2);\n    }\n\n  private:\n    graph_t g1, g2;\n  };\n\n  /**\n   * Tests a given matrix to be matrix-isomorphic to one of the R10-representing matrices\n   * by examining the corresponding bipartite graphs.\n   *\n   * @param matrix A given matrix\n   * @return true if and only if this matrix is a represenation matrix for R10\n   */\n\n  template <typename MatrixType>\n  inline bool is_r10(MatrixType matrix)\n  {\n    if (matrix.size1() != 5 || matrix.size2() != 5)\n      return false;\n\n    bipartite_r10_graphs::graph_t graph(10);\n\n    for (size_t row = 0; row < 5; ++row)\n    {\n      for (size_t column = 0; column < 5; ++column)\n      {\n        if (matrix(row, column))\n        {\n          boost::add_edge(boost::vertex(row, graph), boost::vertex(5 + column, graph), graph);\n        }\n      }\n    }\n\n    return bipartite_r10_graphs::is_r10_graph(graph);\n  }\n}\n\n#endif /* R10_HPP_ */\n", "meta": {"hexsha": "4ca4ba45608fa485fbc24f58e9f716325e97535f", "size": 2803, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "unimodularity-library-1.2c/src/r10.hpp", "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/r10.hpp", "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/r10.hpp", "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": 25.4818181818, "max_line_length": 144, "alphanum_fraction": 0.5840171245, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.6513548782017746, "lm_q1q2_score": 0.5310056705039337}}
{"text": "#include \"aslam/triangulation/triangulation.h\"\n\n#include <Eigen/QR>\n#include <glog/logging.h>\n\nnamespace aslam {\n\nTriangulationResult::Status TriangulationResult::SUCCESSFUL =\n    TriangulationResult::Status::kSuccessful;\nTriangulationResult::Status TriangulationResult::TOO_FEW_MEASUREMENTS =\n    TriangulationResult::Status::kTooFewMeasurments;\nTriangulationResult::Status TriangulationResult::UNOBSERVABLE =\n    TriangulationResult::Status::kUnobservable;\nTriangulationResult::Status TriangulationResult::UNINITIALIZED =\n    TriangulationResult::Status::kUninitialized;\n\nTriangulationResult linearTriangulateFromNViews(\n    const Aligned<std::vector, Eigen::Vector2d>& measurements_normalized,\n    const aslam::TransformationVector& T_G_B,\n    const aslam::Transformation& T_B_C, Eigen::Vector3d* G_point) {\n  CHECK_NOTNULL(G_point);\n  CHECK_EQ(measurements_normalized.size(), T_G_B.size());\n  if (measurements_normalized.size() < 2u) {\n    return TriangulationResult(TriangulationResult::TOO_FEW_MEASUREMENTS);\n  }\n\n  VLOG(200) << \"Triangulating from \" << T_G_B.size() << \" views.\";\n\n  const size_t rows = 3 * measurements_normalized.size();\n  const size_t cols = 3 + measurements_normalized.size();\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(rows, cols);\n  Eigen::VectorXd b = Eigen::VectorXd::Zero(rows);\n\n  const Eigen::Matrix3d R_B_C = T_B_C.getRotationMatrix();\n\n  // Fill in A and b.\n  for (size_t i = 0; i < measurements_normalized.size(); ++i) {\n    Eigen::Vector3d v(measurements_normalized[i](0),\n        measurements_normalized[i](1), 1.);\n    Eigen::Matrix3d R_G_B = T_G_B[i].getRotationMatrix();\n    const Eigen::Vector3d& p_G_B = T_G_B[i].getPosition();\n    A.block<3, 3>(3 * i, 0) = Eigen::Matrix3d::Identity();\n    A.block<3, 1>(3 * i, 3 + i) = -R_G_B * R_B_C * v;\n    b.segment<3>(3 * i) = p_G_B + R_G_B * T_B_C.getPosition();\n  }\n\n  Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr = A.colPivHouseholderQr();\n  static constexpr double kRankLossTolerance = 0.001;\n  qr.setThreshold(kRankLossTolerance);\n  const size_t rank = qr.rank();\n\n  if ((rank - measurements_normalized.size()) < 3) {\n    return TriangulationResult(TriangulationResult::UNOBSERVABLE);\n  }\n\n  *G_point = qr.solve(b).head<3>();\n\n  return TriangulationResult(TriangulationResult::SUCCESSFUL);\n}\n\nTriangulationResult linearTriangulateFromNViews(\n    const Eigen::Matrix3Xd& t_G_bv,\n    const Eigen::Matrix3Xd& p_G_C,\n    Eigen::Vector3d* p_G_P) {\n  CHECK_NOTNULL(p_G_P);\n\n  const int num_measurements = t_G_bv.cols();\n  if (num_measurements < 2) {\n    return TriangulationResult(TriangulationResult::TOO_FEW_MEASUREMENTS);\n  }\n\n  // 1.) Formulate the geometrical problem\n  // p_G_P + alpha[i] * t_G_bv[i] = p_G_C[i]      (+ alpha intended)\n  // as linear system Ax = b, where\n  // x = [p_G_P; alpha[0]; alpha[1]; ... ] and b = [p_G_C[0]; p_G_C[1]; ...]\n  //\n  // 2.) Apply the approximation AtAx = Atb\n  // AtA happens to be composed of mostly more convenient blocks than A:\n  // - Top left = N * Eigen::Matrix3d::Identity()\n  // - Top right and bottom left = t_G_bv\n  // - Bottom right = t_G_bv.colwise().squaredNorm().asDiagonal()\n\n  // - Atb.head(3) = p_G_C.rowwise().sum()\n  // - Atb.tail(N) = columnwise dot products between t_G_bv and p_G_C\n  //               = t_G_bv.cwiseProduct(p_G_C).colwise().sum().transpose()\n  //\n  // 3.) Apply the Schur complement to solve after p_G_P only\n  // AtA = [E B; C D] (same blocks as above) ->\n  // (E - B * D.inverse() * C) * p_G_P = Atb.head(3) - B * D.inverse() * Atb.tail(N)\n\n  const Eigen::MatrixXd BiD = t_G_bv *\n      t_G_bv.colwise().squaredNorm().asDiagonal().inverse();\n  const Eigen::Matrix3d AxtAx = num_measurements * Eigen::Matrix3d::Identity() -\n      BiD * t_G_bv.transpose();\n  const Eigen::Vector3d Axtbx = p_G_C.rowwise().sum() - BiD *\n      t_G_bv.cwiseProduct(p_G_C).colwise().sum().transpose();\n\n  Eigen::ColPivHouseholderQR<Eigen::Matrix3d> qr = AxtAx.colPivHouseholderQr();\n  static constexpr double kRankLossTolerance = 1e-5;\n  qr.setThreshold(kRankLossTolerance);\n  const size_t rank = qr.rank();\n  if (rank < 3) {\n    return TriangulationResult(TriangulationResult::UNOBSERVABLE);\n  }\n\n  *p_G_P = qr.solve(Axtbx);\n  return TriangulationResult(TriangulationResult::SUCCESSFUL);\n}\n\nTriangulationResult linearTriangulateFromNViewsMultiCam(\n    const Aligned<std::vector, Eigen::Vector2d>& measurements_normalized,\n    const std::vector<size_t>& measurement_camera_indices,\n    const Aligned<std::vector, aslam::Transformation>& T_G_B,\n    const Aligned<std::vector, aslam::Transformation>& T_B_C,\n    Eigen::Vector3d* G_point) {\n  CHECK_NOTNULL(G_point);\n  CHECK_EQ(measurements_normalized.size(), T_G_B.size());\n  CHECK_EQ(measurements_normalized.size(), measurement_camera_indices.size());\n  if (measurements_normalized.size() < 2u) {\n    return TriangulationResult(TriangulationResult::TOO_FEW_MEASUREMENTS);\n  }\n\n  const size_t rows = 3 * measurements_normalized.size();\n  const size_t cols = 3 + measurements_normalized.size();\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(rows, cols);\n  Eigen::VectorXd b = Eigen::VectorXd::Zero(rows);\n\n  // Fill in A and b.\n  for (size_t i = 0; i < measurements_normalized.size(); ++i) {\n    size_t cam_index = measurement_camera_indices[i];\n    CHECK_LT(cam_index, T_B_C.size());\n    Eigen::Vector3d v(measurements_normalized[i](0),\n        measurements_normalized[i](1), 1.);\n    const Eigen::Vector3d& t_B_C = T_B_C[cam_index].getPosition();\n\n    A.block<3, 3>(3 * i, 0) = Eigen::Matrix3d::Identity();\n    A.block<3, 1>(3 * i, 3 + i) = -1.0 * T_G_B[i].getRotation().rotate(\n        T_B_C[cam_index].getRotation().rotate(v));\n    b.segment<3>(3 * i) = T_G_B[i] * t_B_C;\n  }\n\n  Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr = A.colPivHouseholderQr();\n  static constexpr double kRankLossTolerance = 0.001;\n  qr.setThreshold(kRankLossTolerance);\n  const size_t rank = qr.rank();\n  if ((rank - measurements_normalized.size()) < 3) {\n    return TriangulationResult(TriangulationResult::UNOBSERVABLE);\n  }\n\n  *G_point = qr.solve(b).head<3>();\n  return TriangulationResult(TriangulationResult::SUCCESSFUL);\n}\n\n// [1]  A. I. Mourikis and S. I. Roumeliotis, \u201cA multi-state constraint kalman filter\n// \"for vision-aided inertial navigation,\u201d in Proc. IEEE Int. Conf. on Robotics\n// and Automation, pp. 10\u201314, 2007.\n// [2] T. Hinzmann, \"Robust Vision-Based Navigation for Micro Air Vehicles\", 2014.\nTriangulationResult iterativeGaussNewtonTriangulateFromNViews(\n    const Aligned<std::vector, Eigen::Vector2d>& measurements_normalized,\n    const Aligned<std::vector, aslam::Transformation>& T_G_B,\n    const aslam::Transformation& T_B_C, Eigen::Vector3d* G_point) {\n  CHECK_NOTNULL(G_point);\n  CHECK_EQ(measurements_normalized.size(), T_G_B.size());\n  if (measurements_normalized.size() < 2u) {\n    return TriangulationResult(TriangulationResult::TOO_FEW_MEASUREMENTS);\n  }\n\n  const double kPrecision = 1.0e-5;\n  const size_t kIterMax = 10;\n\n  // Initialize minimization variables.\n  double alpha = 0.0;\n  double beta = 0.0;\n  double rho = 0.0;\n\n  double residual_norm_last = 1000.0;\n  double residual_norm = 100.0;\n\n  // Camera frame n: camera frame in which feature was observed for the first time.\n  const size_t n = 0;\n\n  // Rotation and position of n-th camera in i-th camera frame.\n  const aslam::Transformation T_Cn_G = T_B_C.inverse() * T_G_B[n].inverse();\n  const Eigen::Matrix3d& R_Cn_G = T_Cn_G.getRotationMatrix();\n  const Eigen::Vector3d& p_G_Cn = T_Cn_G.getPosition();\n\n  // Cache matrices that are constant for every iteration.\n  Aligned<std::vector, Eigen::Matrix3d> R_Ci_Cn;\n  Aligned<std::vector, Eigen::Vector3d> p_Ci_Cn;\n  for (size_t i = 0; i < measurements_normalized.size(); ++i) {\n    const aslam::Transformation T_Ci_G = T_B_C.inverse() * T_G_B[i].inverse();\n    // Rotation from first camera to current camera.\n    const Eigen::Matrix3d R_Ci_G = T_Ci_G.getRotationMatrix();\n    R_Ci_Cn.emplace_back(R_Ci_G * R_Cn_G.transpose());\n    // Translation from first camera to current camera.\n    const Eigen::Vector3d p_G_Ci = T_Ci_G.inverse().getPosition();\n    p_Ci_Cn.emplace_back(R_Ci_G * p_G_Cn - R_Ci_G * p_G_Ci);\n  }\n\n  // [1.] Loop over iterations.\n  // Loop while delta residual too large or number of maximum iterations reached.\n  size_t iter = 0;\n  while (residual_norm_last - residual_norm > kPrecision && iter < kIterMax) {\n    const size_t num_measurements = 2 * measurements_normalized.size();\n    Eigen::VectorXd residuals(num_measurements);\n    Eigen::MatrixXd jacobian(num_measurements, 3);\n    residuals.setZero(num_measurements);\n    jacobian.setZero(num_measurements, 3);\n\n    // [2.] Loop over camera frames / measurements.\n    for (size_t i = 0; i < measurements_normalized.size(); ++i) {\n      // Current measurement.\n      const Eigen::Vector2d& h_meas = measurements_normalized[i];\n\n      // Predicted measurement.\n      const Eigen::Vector3d h_i = R_Ci_Cn[i] *\n\t  (Eigen::Matrix<double, 3, 1>() << alpha, beta, 1.0).finished() + rho * p_Ci_Cn[i];\n      // Normalized predicted measurement.\n      const Eigen::Vector2d h  = h_i.head<2>() / h_i(2);\n\n      // Calculate residuals.\n      residuals.segment<2>(i * 2) = h_meas - h;\n\n      // Calculate jacobians.\n      Eigen::Matrix<double, 2, 3> jacobian_perspective;\n      jacobian_perspective << -1.0 / h_i(2), 0.0, h_i(0) / (h_i(2) * h_i(2)),\n          0.0, -1.0 / h_i(2), h_i(1) / (h_i(2) * h_i(2));\n\n      const Eigen::Matrix<double, 3, 1> jacobian_alpha =\n          R_Ci_Cn[i] * (Eigen::Matrix<double, 3, 1>() << 1.0, 0.0, 0.0).finished();\n      const Eigen::Matrix<double, 3, 1> jacobian_beta =\n          R_Ci_Cn[i] * (Eigen::Matrix<double, 3, 1>() << 0.0, 1.0, 0.0).finished();\n      const Eigen::Matrix<double, 3, 1> jacobian_rho = p_Ci_Cn[i];\n\n      const Eigen::Matrix<double, 2, 1> jacobian_A = jacobian_perspective * jacobian_alpha;\n      const Eigen::Matrix<double, 2, 1> jacobian_B = jacobian_perspective * jacobian_beta;\n      const Eigen::Matrix<double, 2, 1> jacobian_C = jacobian_perspective * jacobian_rho;\n\n      jacobian.block<1, 3>(i * 2, 0) =\n          (Eigen::Matrix<double, 1, 3>() << jacobian_A(0), jacobian_B(0), jacobian_C(0)).finished();\n      jacobian.block<1, 3>(i * 2 + 1, 0) =\n          (Eigen::Matrix<double, 1, 3>() << jacobian_A(1), jacobian_B(1), jacobian_C(1)).finished();\n    }  // Measurement loop.\n\n    // Calculate update using LDLT decomposition.\n    Eigen::Vector3d delta = (jacobian.transpose() * jacobian)\n\t.ldlt().solve(jacobian.transpose() * residuals);\n\n    alpha = alpha - delta(0);\n    beta = beta - delta(1);\n    rho = rho - delta(2);\n\n    residual_norm_last = residual_norm;\n    residual_norm = residuals.squaredNorm();\n    ++iter;\n  } // Iteration loop.\n\n  // Coordinate of feature in global frame.\n  *G_point = 1.0 / rho * R_Cn_G.transpose() *\n      (Eigen::Matrix<double, 3, 1>() << alpha, beta, 1.0).finished() + p_G_Cn;\n  return TriangulationResult(TriangulationResult::SUCCESSFUL);\n}\n\nTriangulationResult triangulateFeatureTrack(\n    const aslam::FeatureTrack& track,\n    const aslam::TransformationVector& T_W_Bs,\n    Eigen::Vector3d* W_landmark) {\n  CHECK_NOTNULL(W_landmark);\n  size_t track_length = track.getTrackLength();\n  CHECK_GT(track_length, 1u);\n  CHECK_EQ(track_length, T_W_Bs.size());\n\n  VLOG(200) << \"Triangulating track of length \" << track_length;\n\n  const aslam::Camera::ConstPtr& camera = track.getFirstKeypointIdentifier().getCamera();\n  CHECK(camera);\n  const aslam::CameraId track_camera_id = camera->getId();\n  aslam::Transformation T_B_C = track.getFirstKeypointIdentifier().get_T_C_B().inverse();\n\n  // Get the normalized measurements for all observations on the track.\n  Aligned<std::vector, Eigen::Vector2d> normalized_measurements;\n  normalized_measurements.reserve(track_length);\n\n  size_t index = 0u;\n  for (const aslam::KeypointIdentifier& keypoint_on_track : track.getKeypointIdentifiers()) {\n    const aslam::Camera::ConstPtr& camera = keypoint_on_track.getCamera();\n    CHECK(camera) << \"Missing camera for keypoint on track with frame index: \"\n        << keypoint_on_track.getFrameIndex();\n\n    // Obtain the normalized keypoint measurements.\n    const Eigen::Vector2d& keypoint_measurement = keypoint_on_track.getKeypointMeasurement();\n    Eigen::Vector3d C_ray;\n    camera->backProject3(keypoint_measurement, &C_ray);\n    Eigen::Vector2d normalized_measurement = C_ray.head<2>() / C_ray[2];\n    normalized_measurements.push_back(normalized_measurement);\n  }\n\n  VLOG(200) << \"Assembled triangulation data.\";\n\n  // Triangulate the landmark.\n  CHECK_EQ(track_length, normalized_measurements.size());\n  CHECK_EQ(track_length, T_W_Bs.size());\n  aslam::TriangulationResult triangulation_result = linearTriangulateFromNViews(\n                                                        normalized_measurements,\n                                                        T_W_Bs,\n                                                        T_B_C,\n                                                        W_landmark);\n\n  VLOG(200) << \"Triangulation returned the following result:\" << std::endl\n          << triangulation_result;\n\n  return triangulation_result;\n}\n\nTriangulationResult fastTriangulateFeatureTrack(\n    const aslam::FeatureTrack& track,\n    const aslam::TransformationVector& T_W_Bs,\n    Eigen::Vector3d* W_landmark) {\n  CHECK_NOTNULL(W_landmark);\n  size_t track_length = track.getTrackLength();\n  CHECK_GT(track_length, 1u);\n  CHECK_EQ(track_length, T_W_Bs.size());\n\n  VLOG(200) << \"Triangulating track of length \" << track_length;\n\n  const aslam::Camera::ConstPtr& camera = track.getFirstKeypointIdentifier().getCamera();\n  CHECK(camera);\n  const aslam::CameraId track_camera_id = camera->getId();\n  aslam::Transformation T_B_C = track.getFirstKeypointIdentifier().get_T_C_B().inverse();\n\n  Eigen::Matrix3Xd G_bearing_vectors;\n  Eigen::Matrix3Xd p_G_C_vector;\n\n  G_bearing_vectors.resize(Eigen::NoChange, track_length);\n  p_G_C_vector.resize(Eigen::NoChange, track_length);\n\n  size_t index = 0u;\n  for (const aslam::KeypointIdentifier& keypoint_on_track : track.getKeypointIdentifiers()) {\n    const aslam::Camera::ConstPtr& camera = keypoint_on_track.getCamera();\n    CHECK(camera) << \"Missing camera for keypoint on track with frame index: \"\n        << keypoint_on_track.getFrameIndex();\n\n    // Obtain the normalized keypoint measurements.\n    const Eigen::Vector2d& keypoint_measurement = keypoint_on_track.getKeypointMeasurement();\n    Eigen::Vector3d C_ray;\n    camera->backProject3(keypoint_measurement, &C_ray);\n\n    aslam::Transformation T_W_C = T_W_Bs[index] * keypoint_on_track.get_T_C_B().inverse();\n\n    G_bearing_vectors.col(index) = T_W_C.getRotationMatrix() * C_ray;\n    p_G_C_vector.col(index) = T_W_C.getPosition();\n  }\n\n  VLOG(200) << \"Assembled triangulation data.\";\n\n  // Triangulate the landmark.\n  aslam::TriangulationResult triangulation_result = linearTriangulateFromNViews(\n      G_bearing_vectors, p_G_C_vector, W_landmark);\n\n  VLOG(200) << \"Triangulation returned the following result:\" << std::endl\n          << triangulation_result;\n\n  return triangulation_result;\n}\n\n}  // namespace aslam\n\n", "meta": {"hexsha": "d0b058fb61b7969b602b3ef172e5a2ea36850d52", "size": 15090, "ext": "cc", "lang": "C++", "max_stars_repo_path": "aslam_cv_triangulation/src/triangulation.cc", "max_stars_repo_name": "shuhannod/aslam_cv2", "max_stars_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-09-16T02:11:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-20T22:49:32.000Z", "max_issues_repo_path": "aslam_cv_triangulation/src/triangulation.cc", "max_issues_repo_name": "shuhannod/aslam_cv2", "max_issues_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "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": "aslam_cv_triangulation/src/triangulation.cc", "max_forks_repo_name": "shuhannod/aslam_cv2", "max_forks_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-28T14:11:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T08:30:50.000Z", "avg_line_length": 41.0054347826, "max_line_length": 100, "alphanum_fraction": 0.6962889331, "num_tokens": 4314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5310056532906219}}
{"text": "//============================================================================\n// Name         : dnatemplatematrixfuncs.hpp\n// Author       : Roger Fraser\n// Contributors :\n// Version      : 1.00\n// Copyright    : Copyright 2017 Geoscience Australia\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// Description  : Common functions involving matrix_2d operations\n//============================================================================\n\n#ifndef DNATEMPLATEMATRIXFUNCS_H_\n#define DNATEMPLATEMATRIXFUNCS_H_\n\n#if defined(_MSC_VER)\n\t#if defined(LIST_INCLUDES_ON_BUILD) \n\t\t#pragma message(\"  \" __FILE__) \n\t#endif\n#endif\n\n#include <algorithm>\n#include <functional>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <stdlib.h>\n#include <math.h>\n#include <iostream>\n\n#include <boost/shared_ptr.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include <include/parameters/dnaellipsoid.hpp>\n#include <include/config/dnatypes.hpp>\n#include <include/math/dnamatrix_contiguous.hpp>\n#include <include/measurement_types/dnameasurement.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nusing namespace dynadjust::datum_parameters;\nusing namespace dynadjust::math;\n\n// msr_t_Iterator = vector<measurement_t>::iterator\ntemplate<typename msr_t_Iterator>\n// Fills upper triangle\nvoid GetDirectionsVarianceMatrix(msr_t_Iterator begin, matrix_2d* vmat)\n{\n\tmsr_t_Iterator bmsRecord(begin);\n\tUINT32 a, angle_count(bmsRecord->vectorCount1 - 1);\t\t// number of directions excluding the RO\n\n\tvmat->zero();\n\tvmat->redim(angle_count, angle_count);\n\n\tbmsRecord++;\n\n\tfor (a=0; a<angle_count; ++a)\n\t{\n\t\tvmat->put(a, a, bmsRecord->scale2);\t\t\t\t// derived angle variance\n\t\tif (a+1 < angle_count)\n\t\t\tvmat->put(a, a+1, bmsRecord->scale3);\t\t// derived angle covariance\n\t\tbmsRecord++;\n\t}\n}\n\n\n// M = measurement_t, U = matrix_2d\n// Fills upper triangle\ntemplate<typename msr_t_Iterator>\nvoid GetGPSVarianceMatrix(const msr_t_Iterator begin, matrix_2d* vmat) \n{\n\tmsr_t_Iterator bmsRecord(begin);\n\tUINT32 variance_dim(bmsRecord->vectorCount1 * 3), covariance_dim, cov;\n\tvmat->zero();\n\tvmat->redim(variance_dim, variance_dim);\t\n\n\tfor (UINT32 var(0), cov_elem; var<variance_dim; var+=3)\n\t{\n\t\tcovariance_dim = bmsRecord->vectorCount2 * 3;\n\n\t\tvmat->put(var, var, (bmsRecord++)->term2);\t\t\t\t// XX\n\n\t\tvmat->put(var, var+1, bmsRecord->term2);\t\t\t\t// XY\n\t\tvmat->put(var+1, var+1, (bmsRecord++)->term3);\t\t\t// YY\n\t\t\n\t\tvmat->put(var, var+2, bmsRecord->term2);\t\t\t\t// XZ\n\t\tvmat->put(var+1, var+2, bmsRecord->term3);\t\t\t\t// YZ\n\t\tvmat->put(var+2, var+2, (bmsRecord++)->term4);\t\t\t// ZZ\n\t\t\n\t\tfor (cov_elem=0; cov_elem<covariance_dim; cov_elem+=3)\n\t\t{\n\t\t\tcov = var + 3 + cov_elem;\n\t\t\tvmat->put(var, cov, bmsRecord->term1);\t\t\t\t// m11\n\t\t\tvmat->put(var, cov+1, bmsRecord->term2);\t\t\t// m12\n\t\t\tvmat->put(var, cov+2, (bmsRecord++)->term3);\t\t// m13\n\t\t\t\n\t\t\tvmat->put(var+1, cov, bmsRecord->term1);\t\t\t// m21\n\t\t\tvmat->put(var+1, cov+1, bmsRecord->term2);\t\t\t// m22\n\t\t\tvmat->put(var+1, cov+2, (bmsRecord++)->term3);\t\t// m23\n\t\t\t\n\t\t\tvmat->put(var+2, cov, bmsRecord->term1);\t\t\t// m31\n\t\t\tvmat->put(var+2, cov+1, bmsRecord->term2);\t\t\t// m32\n\t\t\tvmat->put(var+2, cov+2, (bmsRecord++)->term3);\t\t// m33\n\t\t}\n\t}\n}\n\n\n// msr_t_Iterator = vector<measurement_t>::iterator\ntemplate<typename msr_t_Iterator>\n// Sets values based on upper triangle\nvoid SetDirectionsVarianceMatrix(msr_t_Iterator begin, const matrix_2d& vmat)\n{\n\tmsr_t_Iterator bmsRecord(begin);\n\tUINT32 a, angle_count(bmsRecord->vectorCount1 - 1);\t\t// number of directions excluding the RO\n\n\tbmsRecord->scale2 = 0.;\t// variance (angle)\n\tbmsRecord->scale3 = 0.;\t// covariance (angle)\n\n\tbmsRecord++;\n\n\tfor (a=0; a<angle_count; ++a)\n\t{\n\t\tbmsRecord->scale2 = vmat.get(a, a);\t\t\t\t// derived angle variance\n\t\tif (a+1 < angle_count)\n\t\t\tbmsRecord->scale3 = vmat.get(a, a+1);\t\t// derived angle covariance\n\t\telse\n\t\t\tbmsRecord->scale3 = 0.;\t\t\t\t\t\t// not necessary, but in the interest of \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// preventing confusion, set to zero\n\t\tbmsRecord++;\n\t}\n}\n\n// msr_t_Iterator = vector<measurement_t>::iterator\ntemplate<typename msr_t_Iterator>\n// Sets values based on upper triangle\nvoid SetGPSVarianceMatrix(msr_t_Iterator begin, const matrix_2d& vmat)\n{\n\tmsr_t_Iterator bmsRecord(begin);\n\tUINT32 variance_dim(bmsRecord->vectorCount1 * 3), covariance_dim, cov;\n\n\tfor (UINT32 var(0), cov_elem; var<variance_dim; var+=3)\n\t{\n\t\tcovariance_dim = bmsRecord->vectorCount2 * 3;\n\n\t\t(bmsRecord++)->term2 = vmat.get(var, var);\t\t\t\t// XX\n\n\t\tbmsRecord->term2 = vmat.get(var, var+1);\t\t\t\t// XY\n\t\t(bmsRecord++)->term3 = vmat.get(var+1, var+1);\t\t\t// YY\n\t\t\n\t\tbmsRecord->term2 = vmat.get(var, var+2);\t\t\t\t// XZ\n\t\tbmsRecord->term3 = vmat.get(var+1, var+2);\t\t\t\t// YZ\n\t\t(bmsRecord++)->term4 = vmat.get(var+2, var+2);\t\t\t// ZZ\n\t\t\n\t\tfor (cov_elem=0; cov_elem<covariance_dim; cov_elem+=3)\n\t\t{\n\t\t\tcov = var + 3 + cov_elem;\n\t\t\tbmsRecord->term1 = vmat.get(var, cov);\t\t\t\t// m11\n\t\t\tbmsRecord->term2 = vmat.get(var, cov+1);\t\t\t// m12\n\t\t\t(bmsRecord++)->term3 = vmat.get(var, cov+2);\t\t// m13\n\t\t\t\n\t\t\tbmsRecord->term1 = vmat.get(var+1, cov);\t\t\t// m21\n\t\t\tbmsRecord->term2 = vmat.get(var+1, cov+1);\t\t\t// m22\n\t\t\t(bmsRecord++)->term3 = vmat.get(var+1, cov+2);\t\t// m23\n\t\t\t\n\t\t\tbmsRecord->term1 = vmat.get(var+2, cov);\t\t\t// m31\n\t\t\tbmsRecord->term2 = vmat.get(var+2, cov+1);\t\t\t// m32\n\t\t\t(bmsRecord++)->term3 = vmat.get(var+2, cov+2);\t\t// m33\n\t\t}\n\t}\n}\n\ntemplate <class T>\nvoid FormCarttoGeoRotationMatrix(const T& latitude, const T& longitude, const T& height, \n\tmatrix_2d& mrotations, const CDnaEllipsoid* ellipsoid, bool CLUSTER=false, const UINT32& n=0)\n{\n\tif (!CLUSTER)\n\t\tmrotations.redim(3, 3);\n\n\tT coslat(cos(latitude));\n\tT sinlat(sin(latitude));\n\tT coslon(cos(longitude));\n\tT sinlon(sin(longitude));\n\n\tT term1_a(ellipsoid->GetSemiMajor() * ellipsoid->GetE1sqd());\n\tT one_minus_esq(1. - ellipsoid->GetE1sqd());\n\t\n\tT nu_plus_h(primeVertical(ellipsoid, latitude) + height);\n\tT nu_1minuse2_plus_h((primeVertical(ellipsoid, latitude) * (one_minus_esq) + height));\n\tT term1_b(term1_a * sinlat * coslat);\n\tT term1_c(pow((1. - ellipsoid->GetE1sqd() * sinlat * sinlat), 1.5));\n\t\n\t// set up Rotation matrix (geo to cart)\n\tmrotations.put(n,   n,   (term1_b * coslat * coslon / term1_c) - ((nu_plus_h) * sinlat * coslon));\n\tmrotations.put(n,   n+1, -(nu_plus_h) * coslat * sinlon);\n\tmrotations.put(n,   n+2, coslat * coslon);\n\tmrotations.put(n+1, n,   (term1_b * coslat * sinlon / term1_c) - ((nu_plus_h) * sinlat * sinlon));\n\tmrotations.put(n+1, n+1, (nu_plus_h) * coslat * coslon);\n\tmrotations.put(n+1, n+2, coslat * sinlon);\n\tmrotations.put(n+2, n,   (term1_b * one_minus_esq * sinlat / term1_c) + (nu_1minuse2_plus_h * coslat));\n\tmrotations.put(n+2, n+1, 0.);\n\tmrotations.put(n+2, n+2, sinlat);\n}\n\t\n\ntemplate <class T>\nvoid FormCarttoGeoRotationMatrix_Cluster(const matrix_2d& mpositions, matrix_2d& mrotations,\n\t\t\t\t\t\t\t\t\t  const CDnaEllipsoid* ellipsoid)\n{\n\tmrotations.redim(mpositions.rows(), mpositions.rows());\n\t\n\tfor (UINT32 i(0); i<mpositions.rows(); i+=3)\n\t{\n\t\tFormCarttoGeoRotationMatrix<T>(\n\t\t\tmpositions.get(i, 0),\n\t\t\tmpositions.get(i+1, 0),\n\t\t\tmpositions.get(i+2, 0),\n\t\t\tmrotations, ellipsoid, true, i);\n\t}\n}\n\t\n// Assumes design elements for station 1 and station 2 are always\n// -1 and 1 respectively.\ntemplate <class T>\nvoid Precision_Adjusted_GNSS_bsl(const matrix_2d& mvariances,\n\tconst UINT32& stn1, const UINT32& stn2,\n\tmatrix_2d* mvariances_mod, bool FILLLOWER=true)\n{\n\tmatrix_2d tmp(3, 6);\n\tmvariances_mod->zero();\n\tUINT32 i, j, k;\n\n\t// 1. Form A * V\n\tfor (i=0, j=0; i<3; ++i, ++j)\n\t{\n\t\t// variance-covariance\n\t\tfor (j=0; j<3; ++j)\n\t\t{\n\t\t\t// stn 11 variance\n\t\t\ttmp.elementadd(i, j, -mvariances.get(stn1+i, stn1+j));\n\t\t\t// stn 21 covariance\n\t\t\ttmp.elementadd(i, j, mvariances.get(stn2+i, stn1+j));\t\t\t\n\t\t}\n\t\tk=j;\n\t\t// variance-covariance\n\t\tfor (j=0; j<3; ++j, ++k)\n\t\t{\n\t\t\t// stn 12 covariance\n\t\t\ttmp.elementadd(i, k, -mvariances.get(stn1+i, stn2+j));\n\t\t\t// stn 22 variance\n\t\t\ttmp.elementadd(i, k, mvariances.get(stn2+i, stn2+j));\t\t\t\n\t\t}\n\t}\n\n\t//tmp.trace(\"A x V\", \"%.16G \");\n\n\t// 2. Form AV * AT (upper triangular variance-covariance)\n\tfor (i=0; i<3; ++i)\t\t\n\t\tfor (j=i; j<3; ++j)\n\t\t\t// Sum the variances & covariances\n\t\t\tmvariances_mod->put(i, j, tmp.get(i, j+3) - tmp.get(i, j));\n\t\t\n\tif (FILLLOWER)\n\t\tmvariances_mod->filllower();\n\n\t//mvariances_mod->trace(\"AV X At\", \"%.16G \");\n}\n\ntemplate <class T>\nvoid Prpagate_Variances_Geo_Cart(const matrix_2d& mvariances, matrix_2d mrotations, matrix_2d* mvariances_mod, bool FORWARD=true)\n{\n\t// the rotation matrix is in the direction geo to cart (forward)\n\t// so to go cart to geo, perform inverse\n\tif (!FORWARD)\n\t\tmrotations = mrotations.sweepinverse();\t\t// allows negative diagonal terms\n\t\n\tmatrix_2d mV(mrotations);\n\t//mV.multiply(mvariances);\t\t// original variance matrix\n\tmV.multiply_mkl(\"N\", mvariances, \"N\");\t\t// original variance matrix\n\t//mvariances_mod->multiply_square_t(mV, mrotations);\n\tmvariances_mod->multiply_mkl(mV, \"N\", mrotations, \"T\");\n}\n\n\ntemplate <class T>\nvoid PropagateVariances_GeoCart(const matrix_2d mvariances, matrix_2d* mvariances_mod, \n\t\t\t\t\t\t\t\tconst T& latitude, const T& longitude, const T& height, \n\t\t\t\t\t\t\t\tmatrix_2d& mrotations, \n\t\t\t\t\t\t\t\tconst CDnaEllipsoid* ellipsoid, bool GEO_TO_CART, bool CALCULATE_ROTATIONS)\n{\n\n\tif (CALCULATE_ROTATIONS)\n\t\tFormCarttoGeoRotationMatrix<T>(latitude, longitude, height, mrotations, ellipsoid);\n\n\tPrpagate_Variances_Geo_Cart<T>(mvariances, mrotations, mvariances_mod, GEO_TO_CART);\n}\n\t\n\ntemplate <class T>\nvoid PropagateVariances_GeoCart(const matrix_2d mvariances, matrix_2d* mvariances_mod, \n\t\t\t\t\t\t\t\tconst T& latitude, const T& longitude, const T& height, \n\t\t\t\t\t\t\t\tconst CDnaEllipsoid* ellipsoid, bool GEO_TO_CART)\n{\n\n\tmatrix_2d mrotations;\n\tPropagateVariances_GeoCart<T>(mvariances, mvariances_mod, \n\t\tlatitude, longitude, height, \n\t\tmrotations, \n\t\tellipsoid, GEO_TO_CART, \n\t\ttrue);\t\t// Calculate rotations\n}\n\t\n\ntemplate <class T>\nvoid PropagateVariances_GeoCart_Cluster(const matrix_2d& mvariances, matrix_2d* mvariances_mod, \n\t\t\t\t\t\t\t\tconst matrix_2d& mpositions, matrix_2d& mrotations, \n\t\t\t\t\t\t\t\tconst CDnaEllipsoid* ellipsoid, bool GEO_TO_CART, bool CALCULATE_ROTATIONS)\n{\n\tif (CALCULATE_ROTATIONS)\n\t\tFormCarttoGeoRotationMatrix_Cluster<T>(mpositions, mrotations, ellipsoid);\n\t\n\tPrpagate_Variances_Geo_Cart<T>(mvariances, mrotations, mvariances_mod, GEO_TO_CART);\n}\n\t\n\ntemplate <class T>\nvoid PropagateVariances_GeoCart_Cluster(const matrix_2d& mvariances, matrix_2d* mvariances_mod, \n\t\t\t\t\t\t\t\tconst matrix_2d& mpositions_rad, \n\t\t\t\t\t\t\t\tconst CDnaEllipsoid* ellipsoid, bool GEO_TO_CART)\n{\n\tmatrix_2d mrotations;\n\tFormCarttoGeoRotationMatrix_Cluster<T>(mpositions_rad, mrotations, ellipsoid);\n\t\n\tPrpagate_Variances_Geo_Cart<T>(mvariances, mrotations, mvariances_mod, GEO_TO_CART);\n}\n\t\ntemplate <class T>\nvoid ScaleMatrix(const matrix_2d mvariances, matrix_2d* mvariances_mod, const matrix_2d& scalars)\n{\n\t//matrix_2d mV(mvariances_mod->multiply(scalars, mvariances));\n\tmatrix_2d mV(mvariances_mod->multiply_mkl(scalars, \"N\", mvariances, \"N\"));\n\t//mvariances_mod->multiply_square_t(mV, scalars);\n\tmvariances_mod->multiply_mkl(mV, \"N\", scalars, \"T\");\n}\n\n\ntemplate <class T>\nvoid ScaleGPSVCV(const matrix_2d& mvariances, matrix_2d* mvariances_mod, \n\t\t\t\t\t\tconst T& latitude, const T& longitude, const T& height, \n\t\t\t\t\t\tconst CDnaEllipsoid* ellipsoid, \n\t\t\t\t\t\tconst T& pScale, const T& lScale, const T& hScale)\n{\n\tmatrix_2d mrotations(3, 3);\n\tPropagateVariances_GeoCart<T>(mvariances, mvariances_mod,\n\t\tlatitude, longitude, height, mrotations, ellipsoid,\n\t\tfalse, \t\t// Geographic -> Cartesian ?\n\t\ttrue);\t\t// create the rotation matrix\n\n\tmatrix_2d var_scalars(3, 3);\n\tvar_scalars.put(0, 0, sqrt(pScale));\n\tvar_scalars.put(1, 1, sqrt(lScale));\n\tvar_scalars.put(2, 2, sqrt(hScale));\n\tScaleMatrix<T>(*mvariances_mod, mvariances_mod, var_scalars);\n\n\tPropagateVariances_GeoCart<T>(*mvariances_mod, mvariances_mod,\n\t\tlatitude, longitude, height, mrotations, ellipsoid,\n\t\ttrue,\t\t// Geographic -> Cartesian ?\n\t\tfalse);\t\t// don't create a rotation matrix\n}\n\ntemplate <class T>\n// coordType is passed so that ScaleGPSVCV_Cluster knows whether\n// mvariances needs to be propagated to geographic first.  Hence,\n// if coordType == LLH_type_i, no propagation is undertaken\nvoid ScaleGPSVCV_Cluster(const matrix_2d& mvariances, matrix_2d* mvariances_mod, \n\t\t\t\t\t\tconst matrix_2d& mpositions, const CDnaEllipsoid* ellipsoid, \n\t\t\t\t\t\tconst T& pScale, const T& lScale, const T& hScale, _COORD_TYPE_ coordType=XYZ_type_i)\n{\n\tmatrix_2d mrotations;\n\t// form rotation matrix\n\tFormCarttoGeoRotationMatrix_Cluster<T>(mpositions, mrotations, ellipsoid);\n\n\t// Don't propagate if already in geographic\n\tif (coordType == XYZ_type_i)\n\t\t// propagate variances in cartesian system to geographic \n\t\tPropagateVariances_GeoCart_Cluster<T>(mvariances, mvariances_mod,\n\t\t\tmpositions, mrotations, ellipsoid,\n\t\t\tfalse, \t\t// Cartesian -> Geographic\n\t\t\tfalse);\t\t// don't create a rotation matrix\n\n\t// scale matrix\n\tmatrix_2d var_scalars(mvariances.rows(), mvariances.columns());\n\n\tfor (UINT32 r(0); r<var_scalars.rows(); r+=3)\n\t{\t\n\t\tvar_scalars.put(r, r, sqrt(pScale));\n\t\tvar_scalars.put(r+1, r+1, sqrt(lScale));\n\t\tvar_scalars.put(r+2, r+2, sqrt(hScale));\n\t}\n\n\t// perform the scaling\n\tScaleMatrix<T>(*mvariances_mod, mvariances_mod, var_scalars);\n\n\t// propagate variances in geographic system to cartesian\n\tPropagateVariances_GeoCart_Cluster<T>(*mvariances_mod, mvariances_mod,\n\t\tmpositions, mrotations, ellipsoid, \n\t\ttrue, \t\t// Geographic -> Cartesian\n\t\tfalse);\t\t// don't create a rotation matrix\n}\n\ntemplate <class T>\nvoid FormLocaltoCartRotationMatrix(const T& latitude, const T& longitude,\n\tmatrix_2d& mrotations, bool LOCAL_TO_CART=true)\n{\n\tmrotations.redim(3, 3);\n\n\tT coslat(cos(latitude));\n\tT sinlat(sin(latitude));\n\tT coslon(cos(longitude));\n\tT sinlon(sin(longitude));\n\n\tif (LOCAL_TO_CART)\n\t{\n\t\t// set up Rotation matrix for local to cart\n\t\tmrotations.put(0, 0, -sinlon);\n\t\tmrotations.put(0, 1, -sinlat*coslon);\n\t\tmrotations.put(0, 2, coslat*coslon);\n\t\tmrotations.put(1, 0, coslon);\n\t\tmrotations.put(1, 1, -sinlat*sinlon);\n\t\tmrotations.put(1, 2, coslat*sinlon);\n\t\tmrotations.put(2, 0, 0.);\n\t\tmrotations.put(2, 1, coslat);\n\t\tmrotations.put(2, 2, sinlat);\n\t}\n\telse\n\t{\n\t\t// set up Rotation matrix for cart to local, which is \n\t\t// transpose of local to cart!\n\t\tmrotations.put(0, 0, -sinlon); \n\t\tmrotations.put(0, 1, coslon); \n\t\tmrotations.put(0, 2, 0.); \n\t\tmrotations.put(1, 0, -sinlat*coslon); \n\t\tmrotations.put(1, 1, -sinlat*sinlon); \n\t\tmrotations.put(1, 2, coslat);\n\t\tmrotations.put(2, 0, coslat*coslon); \n\t\tmrotations.put(2, 1, coslat*sinlon); \n\t\tmrotations.put(2, 2, sinlat);\n\t}\n}\n\t\ntemplate <class T>\nvoid FormLocaltoPolarRotationMatrix(const T& azimuth, const T& elevation, const T& distance,\n\tmatrix_2d& mrotations, bool LOCAL_TO_POLAR=true)\n{\n\tmrotations.redim(3, 3);\n\n\tT cos_azimuth(cos(azimuth));\n\tT sin_azimuth(sin(azimuth));\n\tT cos_elevation(cos(elevation));\n\tT sin_elevation(sin(elevation));\n\t\n\tif (LOCAL_TO_POLAR)\n\t{\n\t\t// set up Jacobian matrix for local to polar\n\t\tmrotations.put(0, 0, cos_azimuth/distance); \n\t\tmrotations.put(0, 1, -sin_azimuth/distance); \n\t\tmrotations.put(0, 2, 0.); \n\t\tmrotations.put(1, 0, -sin_azimuth*sin_elevation/distance); \n\t\tmrotations.put(1, 1, -cos_azimuth*sin_elevation/distance); \n\t\tmrotations.put(1, 2, cos_elevation/distance);\n\t\tmrotations.put(2, 0, sin_azimuth*cos_elevation); \n\t\tmrotations.put(2, 1, cos_azimuth*cos_elevation); \n\t\tmrotations.put(2, 2, sin_elevation);\n\t}\n\telse\n\t{\n\t\t// Set up Jacobian matrix for polar to local, which is \n\t\t// transpose of local to polar!\n\t\tmrotations.put(0, 0, cos_azimuth/distance);\n\t\tmrotations.put(0, 1, -sin_azimuth*sin_elevation/distance);\n\t\tmrotations.put(0, 2, sin_azimuth*cos_elevation);\n\t\tmrotations.put(1, 0, -sin_azimuth/distance);\n\t\tmrotations.put(1, 1, -cos_azimuth*sin_elevation/distance);\n\t\tmrotations.put(1, 2, cos_azimuth*cos_elevation);\n\t\tmrotations.put(2, 0, 0.); \n\t\tmrotations.put(2, 1, cos_elevation/distance); \n\t\tmrotations.put(2, 2, sin_elevation);\n\t}\n}\n\ntemplate <class T>\nvoid PropagateVariances_CartLocal_Diagonal(const matrix_2d& mvariances, matrix_2d& mvariances_mod, \n\t\t\t\t\t\t\t\t  const T& latitude, const T& longitude,\n\t\t\t\t\t\t\t\t  matrix_2d& mrotations, bool CALCULATE_ROTATIONS=false)\n{\n\tif (CALCULATE_ROTATIONS)\n\t\tFormLocaltoCartRotationMatrix<T>(latitude, longitude, mrotations);\n\n\t//matrix_2d mrotations_T(mrotations.rows(), mrotations.columns());\n\tmatrix_2d rtv(mrotations.rows(), mrotations.columns());\n\n\t//mrotations_T.transpose(mrotations);\n\t\n\tmvariances_mod.redim(3, 3);\n\t\n\t// RtV\n\t//rtv.multiply(mrotations_T, mvariances);\n\trtv.multiply_mkl(mrotations, \"T\", mvariances, \"N\");\n\t\n\tUINT32 row, col, i;\n\t\n\t// RtVR\n\tfor (row=0; row<3; ++row) {\n\t\tfor (col=0; col<3; ++col) {\n\t\t\tmvariances_mod.put(row, col, 0.0);\n\t\t\t// diagonals only\n\t\t\tif (row != col)\n\t\t\t\tcontinue;\n\t\t\tfor (i=0; i<3; ++i)\n\t\t\t\tmvariances_mod.elementadd(row, col, rtv.get(row, i) * mrotations.get(i, col));\n\t\t}\n\t}\n}\n\n\ntemplate <class T>\nvoid PropagateVariances_LocalPolar_Diagonal(const matrix_2d& mvariances, matrix_2d& mvariances_mod, \n\t\t\t\t\t\t\t\t  const T& azimuth, const T& elevation, const T& distance,\n\t\t\t\t\t\t\t\t  matrix_2d& mrotations, bool CALCULATE_ROTATIONS=false)\n{\n\tif (CALCULATE_ROTATIONS)\n\t\tFormLocaltoPolarRotationMatrix<T>(azimuth, elevation, distance, mrotations);\n\n\tmatrix_2d mrotations_T(mrotations.rows(), mrotations.columns());\n\tmatrix_2d rtv(mrotations.rows(), mrotations.columns());\n\n\tmrotations_T.transpose(mrotations);\n\t\n\tmvariances_mod.redim(3, 3);\n\t\n\t// RtV\n\t//rtv.multiply(mrotations, mvariances);\n\trtv.multiply_mkl(mrotations, \"N\", mvariances, \"N\");\n\n\tUINT32 row, col, i;\n\t\n\t// RtVR\n\tfor (row=0; row<3; ++row) {\n\t\tfor (col=0; col<3; ++col) {\n\t\t\tmvariances_mod.put(row, col, 0.0);\n\t\t\t// diagonals only\n\t\t\tif (row != col)\n\t\t\t\tcontinue;\n\t\t\tfor (i=0; i<3; ++i)\n\t\t\t\tmvariances_mod.elementadd(row, col, rtv.get(row, i) * mrotations_T.get(i, col));\n\t\t}\n\t}\n}\n\n\ntemplate <class T>\nvoid PropagateVariances_LocalCart(const matrix_2d& mvariances, matrix_2d& mvariances_mod, \n\t\t\t\t\t\t\t\t  const T& latitude, const T& longitude, bool LOCAL_TO_CART,\n\t\t\t\t\t\t\t\t  matrix_2d& mrotations, bool CALCULATE_ROTATIONS=false)\n{\n\tif (CALCULATE_ROTATIONS)\n\t\tFormLocaltoCartRotationMatrix<T>(latitude, longitude, mrotations);\n\n\t// form transpose, from either passed in matrix or newly formed matrix\n\tmatrix_2d mrotations_T(mrotations.rows(), mrotations.columns());\n\tmrotations_T.transpose(mrotations);\n\n\t// the rotation matrix is in the direction local to cart (forward)\n\tif (LOCAL_TO_CART)\n\t{\n\t\t// Vc = R * Vl * RT\n\t\t//matrix_2d mV(mvariances_mod.multiply(mrotations, mvariances));\n\t\tmatrix_2d mV(mvariances_mod.multiply_mkl(mrotations, \"N\", mvariances, \"N\"));\n\t\t//mvariances_mod.multiply_square(mV, mrotations_T);\n\t\tmvariances_mod.multiply_mkl(mV, \"N\", mrotations, \"T\");\n\t}\n\telse\n\t{\n\t\t// Vc = R-1 * Vc * [R-1]T\n\t\t//    = RT * Vc * R (since R is orthogonal)\n\t\t//matrix_2d mV(mvariances_mod.multiply(mrotations_T, mvariances));\n\t\tmatrix_2d mV(mvariances_mod.multiply_mkl(mrotations, \"T\", mvariances, \"N\"));\n\t\t//mvariances_mod.multiply_square(mV, mrotations);\n\t\tmvariances_mod.multiply_mkl(mV, \"N\", mrotations, \"N\");\n\t}\n}\n\ntemplate <class T>\nvoid PropagateVariances_LocalCart(const matrix_2d& mvariances, matrix_2d& mvariances_mod, \n\t\t\t\t\t\t\t\t  const T& latitude, const T& longitude, bool LOCAL_TO_CART)\n{\n\tmatrix_2d mrotations;\n\n\tPropagateVariances_LocalCart<T>(mvariances, mvariances_mod, \n\t\tlatitude, longitude, LOCAL_TO_CART,\n\t\tmrotations, true);\t// calculate rotations\n}\n\ntemplate <class T>\nvoid Rotate_LocalCart(const matrix_2d mvector, matrix_2d* mvector_mod, \n\t\t\t\t\t\t\t\t  const T& latitude, const T& longitude)\n{\n\tmatrix_2d mrotations(3, 3);\n\tFormLocaltoCartRotationMatrix<T>(latitude, longitude, mrotations);\n\n\tmvector_mod->redim(3, 1);\n\t//mvector_mod->multiply(mrotations, mvector);\n\tmvector_mod->multiply_mkl(mrotations, \"N\", mvector, \"N\");\n}\n\ntemplate <class T>\nvoid Rotate_CartLocal(const matrix_2d mvector, matrix_2d* mvector_mod, \n\t\t\t\t\t\t\t\t  const T& latitude, const T& longitude)\n{\n\t// Helps\n\tT sin_lat(sin(latitude));\n\tT cos_lat(cos(latitude));\n\tT sin_long(sin(longitude));\n\tT cos_long(cos(longitude));\n\n\tmvector_mod->redim(3, 1);\n\t\n\tmvector_mod->put(0, 0, -sin_long * mvector.get(0,0) + cos_long * mvector.get(1,0));\n\tmvector_mod->put(1, 0, -sin_lat * cos_long * mvector.get(0,0) -\n\t\tsin_lat * sin_long * mvector.get(1,0) +\n\t\tcos_lat * mvector.get(2,0));\n\tmvector_mod->put(2, 0, cos_lat * cos_long * mvector.get(0,0) +\n\t\tcos_lat * sin_long * mvector.get(1,0) +\n\t\tsin_lat * mvector.get(2,0));\n}\n\n\ntemplate <class T>\nvoid Rotate_LocalPolar(const matrix_2d mvector, matrix_2d* mvector_mod, \n\t\t\t\t\t\t\t\t  const T& azimuth, const T& elevation, const T& distance)\n{\n\t// Helps\n\tT sin_azimuth(sin(azimuth));\n\tT cos_azimuth(cos(azimuth));\n\tT sin_elevation(sin(elevation));\n\tT cos_elevation(cos(elevation));\n\t\n\tmvector_mod->redim(3, 1);\n\t\n\tmvector_mod->put(0, 0, -cos_azimuth * mvector.get(0,0) - sin_azimuth * mvector.get(1,0));\n\tmvector_mod->put(1, 0, -sin_elevation * sin_azimuth * mvector.get(0,0) -\n\t\tsin_elevation * cos_azimuth * mvector.get(1,0) +\n\t\tcos_elevation * mvector.get(2,0));\n\tmvector_mod->put(2, 0, cos_elevation * sin_azimuth * mvector.get(0,0) +\n\t\tcos_elevation * cos_azimuth * mvector.get(1,0) +\n\t\tsin_elevation * mvector.get(2,0));\n}\n\n\ntemplate <class T>\n// rotx is x rotation in radians\n// roty is y rotation in radians\n// rotz is z rotation in radians\nvoid FormHelmertRotationMatrix(const T& rotx, const T& roty, const T& rotz, matrix_2d& mrotations, bool RIGOROUS=false)\n{\n\tmrotations.redim(3, 3);\n\n\t// Which rotation matrix is required?\n\t// Convert to seconds for the test\n\tif (RIGOROUS)\n\t{\n\t\t// rigorous formula for large (> 10 seconds) rotations\n\t\tmrotations.put(0, 0, cos(roty) * cos(rotz));\n\t\tmrotations.put(0, 1, cos(roty) * sin(rotz));\n\t\tmrotations.put(0, 2, -sin(roty));\n\t\tmrotations.put(1, 0, (sin(rotx) * sin(roty) * cos(rotz)) - (cos(rotx) * sin(rotz)));\n\t\tmrotations.put(1, 1, (sin(rotx) * sin(roty) * sin(rotz)) + (cos(rotx) * cos(rotz)));\n\t\tmrotations.put(1, 2, sin(rotx) * cos(roty));\n\t\tmrotations.put(2, 0, (cos(rotx) * sin(roty) * cos(rotz)) + (sin(rotx) * sin(rotz)));\n\t\tmrotations.put(2, 1, (cos(rotx) * sin(roty) * sin(rotz)) - (sin(rotx) * cos(rotz)));\n\t\tmrotations.put(2, 2, cos(rotx) * cos(roty));\n\t}\n\telse\n\t{\n\t\tmrotations.put(0, 0, 1.);\n\t\tmrotations.put(0, 1, rotz);\n\t\tmrotations.put(0, 2, -roty);\n\t\tmrotations.put(1, 0, -rotz);\n\t\tmrotations.put(1, 1, 1.);\n\t\tmrotations.put(1, 2, rotx);\n\t\tmrotations.put(2, 0, roty);\n\t\tmrotations.put(2, 1, -rotx);\n\t\tmrotations.put(2, 2, 1.);\n\t}\n}\n\t\n\ntemplate <class T>\nvoid ReduceParameters(const T* parameters, T* reduced_parameters, const T& elapsedTime, bool DYNAMIC=true)\n{\n\t// translations (reduce to metres)\n\treduced_parameters[0] = parameters[0] / 1000.;\n\treduced_parameters[1] = parameters[1] / 1000.;\n\treduced_parameters[2] = parameters[2] / 1000.;\n\t// scale\n\treduced_parameters[3] = parameters[3] / 1E9;\n\t// rotations\n\treduced_parameters[4] = parameters[4];\n\treduced_parameters[5] = parameters[5];\n\treduced_parameters[6] = parameters[6];\n\n\tif (DYNAMIC)\n\t{\n\t\t// apply rates to translations\n\t\treduced_parameters[0] += parameters[7] / 1000. * elapsedTime;\n\t\treduced_parameters[1] += parameters[8] / 1000. * elapsedTime;\n\t\treduced_parameters[2] += parameters[9] / 1000. * elapsedTime;\n\t\t// apply rate to scale\n\t\treduced_parameters[3] += parameters[10] / 1E9 * elapsedTime;\n\t\t// apply rates to rotations\n\t\treduced_parameters[4] += parameters[11] * elapsedTime;\n\t\treduced_parameters[5] += parameters[12] * elapsedTime;\n\t\treduced_parameters[6] += parameters[13] * elapsedTime;\n\t}\n\n\t// reduce rotations from milli-arc-seconds to radians\n\treduced_parameters[4] = SecondstoRadians(reduced_parameters[4]) / 1000.;\n\treduced_parameters[5] = SecondstoRadians(reduced_parameters[5]) / 1000.;\n\treduced_parameters[6] = SecondstoRadians(reduced_parameters[6]) / 1000.; \n}\n\ntemplate <class T>\n// No check or safe guard in place to test if mcoordinates_mod is a reference to mcoordinates\nvoid TransformCartesian(const matrix_2d& mcoordinates, matrix_2d& mcoordinates_mod, \n\tconst matrix_2d& parameters, const matrix_2d& mrotations)\n{\n\t// Add rotation and scale contributions\n\tfor (UINT16 i(0), j; i<3; ++i)\n\t{\n\t\t// Initialise 'to datum' matrix\n\t\tmcoordinates_mod.put(i, 0, 0.0);\n\n\t\tfor (j=0; j<3; ++j)\t\t// For each column in the row\n\t\t\tmcoordinates_mod.elementadd(i, 0, mrotations.get(i, j) * mcoordinates.get(j, 0));\t// Sum partial products\n\n\t\t// Apply scale\n\t\tmcoordinates_mod.elementmultiply(i, 0, 1.0 + parameters.get(3, 0));\n\n\t\t// Add translations\n\t\tmcoordinates_mod.elementadd(i, 0, parameters.get(i, 0));\n\t}\n}\n\ntemplate <class T>\nvoid Transform_7parameter(const matrix_2d& mcoordinates, matrix_2d& mcoordinates_mod, const T parameters[])\n{\n\tmcoordinates_mod.redim(3, 1);\n\n\tbool RIGOROUS(false);\n\tif (parameters[4] > 10. || parameters[5] > 10. || parameters[6] > 10.)\n\t\tRIGOROUS = true;\n\n\t// Form rotation matrix\n\tmatrix_2d mrotations(3, 3);\n\tFormHelmertRotationMatrix<T>(parameters[4], parameters[5], parameters[6], mrotations, RIGOROUS);\n\t\n\t// Put translations and scale into reducedParameters\n\tmatrix_2d mtrans_scale(4, 1, parameters, 4);\n\n\t// Transform\n\tTransformCartesian<T>(mcoordinates, mcoordinates_mod, \n\t\tmtrans_scale, mrotations);\n\n}\n\t\n\ntemplate <typename T>\nvoid PositionalUncertainty(const T& semimajor, const T& semiminor, const T& azimuth, const T& sdHt,\n\t\t\t\t\t\t   T& hzPosU_Radius, T& vtPosU_Radius)\n{\n\thzPosU_Radius = vtPosU_Radius = -1.;\n\tif (semimajor < 0.0)\n\t\treturn;\n\tif (semiminor < 0.0)\n\t\treturn;\n\n\t// Horizontal\n\tT c(semiminor / semimajor);\n\tT K(HPOS_UNCERT_Q0 + (HPOS_UNCERT_Q1 * c) + (HPOS_UNCERT_Q2 * (c * c)) + (HPOS_UNCERT_Q3 * (c * c * c)));\n\tT R(semimajor * K);\n\t\t\n\thzPosU_Radius = R;\n\t\t\n\t// Vertical\n\tvtPosU_Radius = sdHt * 1.96;\n}\n\ntemplate <typename T>\nT PedalVariance(const matrix_2d& mvariance, const T& direction)\n{\n\tT cos_theta(cos(direction));\n\tT sin_theta(sin(direction));\n\treturn mvariance.get(0, 0) * cos_theta * cos_theta +\n\t\tmvariance.get(1, 1) * sin_theta * sin_theta +\n\t\t2. * mvariance.get(0, 1) * cos_theta * sin_theta;\n}\n\t\n\ntemplate <typename T>\nvoid ErrorEllipseParameters(const matrix_2d& mvariance, T& semimajor, T& semiminor, T& azimuth)\n{\n\tsemimajor = semiminor = azimuth = -1.;\n\n\tif (mvariance.rows() < 2)\n\t\treturn;\n\tif (mvariance.columns() < 2)\n\t\treturn;\n\n\tT e2(mvariance.get(0, 0));\n\tT n2(mvariance.get(1, 1));\n\tT en(mvariance.get(0, 1));\n\tT e2_plus_n2(e2 + n2);\n\tT e2_minus_n2(e2 - n2);\n\tT n2_minus_e2(n2 - e2);\n\t\n\tT W((e2_minus_n2 * e2_minus_n2) + (4. * en * en));\n\t\n\tif (W < 0.0)\n\t{\n\t\tif (fabs(W) > PRECISION_1E15)\n\t\t\treturn;\t\t\t\t\t\t\t\t// temp term cannot be negative!!!\n\t\telse\n\t\t\tW = 0.0;\n\t}\n\n\tT a_sqd(0.5 * (e2_plus_n2 + sqrt(W)));\t\t// semi-major\n\tT b_sqd(0.5 * (e2_plus_n2 - sqrt(W)));\t\t// semi-minor\n\t\n\tif (a_sqd < 0.0)\n\t\treturn;\t\t\t\t\t\t\t\t\t// lamda2 term cannot be negative!!!\n\tif (b_sqd < 0.0)\n\t\treturn;\t\t\t\t\t\t\t\t\t// lamda2 term cannot be negative!!!\n\n\tsemimajor = sqrt(a_sqd);\n\tsemiminor = sqrt(b_sqd);\n\n\t// Compute the azimuth of the semi-major axis\n\tif (fabs(e2 - n2) < PRECISION_1E25)\n\t{\n\t\tif (en < PRECISION_1E25)\n\t\t\tazimuth = 0.;\t\t\t// ellipse is a circle\n\t\telse\n\t\t\tazimuth = PI / 4.;\t\t// azimuth = 45\n\t}\n\telse\n\t{\n\t\tT x(en + en);\n\t\tazimuth = 0.5 * atan_2(x, n2_minus_e2);\n\t}\n}\n\n#endif /* DNATEMPLATEMATRIXFUNCS_H_ */\n", "meta": {"hexsha": "230f940d7529e395c8e1c3828aa9ae24f63fa196", "size": 27818, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dynadjust/include/functions/dnatemplatematrixfuncs.hpp", "max_stars_repo_name": "nicgowans/DynAdjust", "max_stars_repo_head_hexsha": "7443f0a3a0487876dd2f568efaa6c7be0e3e75e3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T04:18:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T05:37:18.000Z", "max_issues_repo_path": "dynadjust/include/functions/dnatemplatematrixfuncs.hpp", "max_issues_repo_name": "nicgowans/DynAdjust", "max_issues_repo_head_hexsha": "7443f0a3a0487876dd2f568efaa6c7be0e3e75e3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 112.0, "max_issues_repo_issues_event_min_datetime": "2018-08-30T09:33:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T00:32:29.000Z", "max_forks_repo_path": "dynadjust/include/functions/dnatemplatematrixfuncs.hpp", "max_forks_repo_name": "nicgowans/DynAdjust", "max_forks_repo_head_hexsha": "7443f0a3a0487876dd2f568efaa6c7be0e3e75e3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2018-08-30T09:07:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T05:16:08.000Z", "avg_line_length": 31.828375286, "max_line_length": 129, "alphanum_fraction": 0.6902005895, "num_tokens": 9249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5310056484344149}}
{"text": "// Copyright (c) 2019 fortiss GmbH, Julian Bernhard, Klemens Esterle, Patrick Hart, 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\n#include <Eigen/Core>\n#include \"gtest/gtest.h\"\n\n#include \"modules/geometry/polygon.hpp\"\n#include \"modules/geometry/line.hpp\"\n#include \"modules/geometry/commons.hpp\"\n#include \"modules/models/dynamic/single_track.hpp\"\n#include \"modules/models/dynamic/integration.hpp\"\n\nTEST(single_track_model, dynamic_test) {\n  using namespace std;\n  using namespace modules::geometry;\n  using namespace modules::models::dynamic;\n\n  State x(static_cast<int>(StateDefinition::MIN_STATE_SIZE));\n  x << 0, 0, 0, 0, 5;\n\n  Input u(2);\n  u << 0, 0;\n\n  DynamicModel *m;\n  SingleTrackModel single_track_model;\n  m = &single_track_model;\n\n  float dt = 0.1;\n  for (int i = 0; i < 10; i++) {\n    x = euler_int(m, x, u, dt);\n    cout << x << endl;\n  }\n}\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "ad5616a69dcae29d5ca54e590a7086af84d2c5eb", "size": 1052, "ext": "cc", "lang": "C++", "max_stars_repo_path": "modules/models/tests/dynamic_test.cc", "max_stars_repo_name": "grzPat/bark", "max_stars_repo_head_hexsha": "807092815c81eeb23defff473449a535a9c42f8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/models/tests/dynamic_test.cc", "max_issues_repo_name": "grzPat/bark", "max_issues_repo_head_hexsha": "807092815c81eeb23defff473449a535a9c42f8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/models/tests/dynamic_test.cc", "max_forks_repo_name": "grzPat/bark", "max_forks_repo_head_hexsha": "807092815c81eeb23defff473449a535a9c42f8b", "max_forks_repo_licenses": ["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.0476190476, "max_line_length": 98, "alphanum_fraction": 0.6967680608, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893520001, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5310056477732426}}
{"text": "#include <iostream>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Dense>\n#include <vector>\n#include <math.h>\n#include <cmath>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <pcl/io/io.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/features/integral_image_normal.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/common/common_headers.h>\n#include <pcl/features/integral_image_normal.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/visualization/cloud_viewer.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/ModelCoefficients.h>\n#include <pcl/filters/project_inliers.h>\n#include <pcl/features/shot_omp.h>\n#include <pcl/features/fpfh.h>\n\n#include <Config.hpp>\n\n\nint main(int argc, char *argv[])\n{\n    // *Parse Config\n    Config config;\n    std::string input_pcd = config.input_pcd;\n    std::string output_pcd = config.output_pcd;\n\n    // *Read point cloud\n    pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGBA>);\n    pcl::io::loadPCDFile(input_pcd, *cloud);\n    std::cout << \"Number of points in the input cloud is:\" << cloud->points.size() << std::endl;\n\n    // *Create the filtering object\n    // pcl::VoxelGrid<pcl::PointXYZRGBA> sor;\n    // sor.setInputCloud(cloud);\n    // sor.setLeafSize(0.1f, 0.1f, 0.1f);\n    // sor.filter(*cloud);\n\n    pcl::PointCloud<pcl::PointXYZRGBA>::Ptr Normals(new pcl::PointCloud<pcl::PointXYZRGBA>);\n    Normals->resize(cloud->size());\n\n    // *K nearest neighbor search\n    int KNumbersNeighbor = 10; // numbers of neighbors 7 , 120\n    std::vector<int> NeighborsKNSearch(KNumbersNeighbor);\n    std::vector<float> NeighborsKNSquaredDistance(KNumbersNeighbor);\n\n    int *NumbersNeighbor = new int[cloud->points.size()];\n    pcl::KdTreeFLANN<pcl::PointXYZRGBA> kdtree;\n    kdtree.setInputCloud(cloud);\n    pcl::PointXYZRGBA searchPoint;\n\n    double *SmallestEigen = new double[cloud->points.size()];\n    double *MiddleEigen = new double[cloud->points.size()];\n    double *LargestEigen = new double[cloud->points.size()];\n\n    double *DLS = new double[cloud->points.size()];\n    double *DLM = new double[cloud->points.size()];\n    double *DMS = new double[cloud->points.size()];\n    double *Sigma = new double[cloud->points.size()];\n\n    //  ************ All the Points of the cloud *******************\n    for (size_t i = 0; i < cloud->points.size(); ++i)\n    {\n        searchPoint.x = cloud->points[i].x;\n        searchPoint.y = cloud->points[i].y;\n        searchPoint.z = cloud->points[i].z;\n\n        if (kdtree.nearestKSearch(searchPoint, KNumbersNeighbor, NeighborsKNSearch, NeighborsKNSquaredDistance) > 0)\n        {\n            NumbersNeighbor[i] = NeighborsKNSearch.size();\n        }\n        else\n        {\n            NumbersNeighbor[i] = 0;\n        }\n\n        float Xmean;\n        float Ymean;\n        float Zmean;\n        float sum = 0.00;\n        // *Computing Covariance Matrix\n        for (size_t ii = 0; ii < NeighborsKNSearch.size(); ++ii)\n        {\n            sum += cloud->points[NeighborsKNSearch[ii]].x;\n        }\n        Xmean = sum / NumbersNeighbor[i];\n        sum = 0.00;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size(); ++ii)\n        {\n            sum += cloud->points[NeighborsKNSearch[ii]].y;\n        }\n        Ymean = sum / NumbersNeighbor[i];\n        sum = 0.00;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size(); ++ii)\n        {\n            sum += cloud->points[NeighborsKNSearch[ii]].z;\n        }\n        Zmean = sum / NumbersNeighbor[i];\n\n        float CovXX;\n        float CovXY;\n        float CovXZ;\n        float CovYX;\n        float CovYY;\n        float CovYZ;\n        float CovZX;\n        float CovZY;\n        float CovZZ;\n\n        sum = 0.00;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size(); ++ii)\n        {\n            sum += ((cloud->points[NeighborsKNSearch[ii]].x - Xmean) * (cloud->points[NeighborsKNSearch[ii]].x - Xmean));\n        }\n        CovXX = sum / (NumbersNeighbor[i] - 1);\n\n        sum = 0.00;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size(); ++ii)\n        {\n            sum += ((cloud->points[NeighborsKNSearch[ii]].x - Xmean) * (cloud->points[NeighborsKNSearch[ii]].y - Ymean));\n        }\n        CovXY = sum / (NumbersNeighbor[i] - 1);\n\n        CovYX = CovXY;\n\n        sum = 0.00;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size(); ++ii)\n        {\n            sum += ((cloud->points[NeighborsKNSearch[ii]].x - Xmean) * (cloud->points[NeighborsKNSearch[ii]].z - Zmean));\n        }\n        CovXZ = sum / (NumbersNeighbor[i] - 1);\n\n        CovZX = CovXZ;\n\n        sum = 0.00;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size(); ++ii)\n        {\n            sum += ((cloud->points[NeighborsKNSearch[ii]].y - Ymean) * (cloud->points[NeighborsKNSearch[ii]].y - Ymean));\n        }\n        CovYY = sum / (NumbersNeighbor[i] - 1);\n\n        sum = 0.00;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size(); ++ii)\n        {\n            sum += ((cloud->points[NeighborsKNSearch[ii]].y - Ymean) * (cloud->points[NeighborsKNSearch[ii]].z - Zmean));\n        }\n        CovYZ = sum / (NumbersNeighbor[i] - 1);\n\n        CovZY = CovYZ;\n\n        sum = 0.00;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size(); ++ii)\n        {\n            sum += ((cloud->points[NeighborsKNSearch[ii]].z - Zmean) * (cloud->points[NeighborsKNSearch[ii]].z - Zmean));\n        }\n        CovZZ = sum / (NumbersNeighbor[i] - 1);\n\n        // *Computing Eigenvalue and EigenVector\n        Eigen::Matrix3f Cov;\n        Cov << CovXX, CovXY, CovXZ, CovYX, CovYY, CovYZ, CovZX, CovZY, CovZZ;\n\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigensolver(Cov);\n        if (eigensolver.info() != Eigen::Success)\n            abort();\n\n        double EigenValue1 = eigensolver.eigenvalues()[0];\n        double EigenValue2 = eigensolver.eigenvalues()[1];\n        double EigenValue3 = eigensolver.eigenvalues()[2];\n\n        double Smallest = 0.00;\n        double Middle = 0.00;\n        double Largest = 0.00;\n        if (EigenValue1 < EigenValue2)\n        {\n            Smallest = EigenValue1;\n        }\n        else\n        {\n            Smallest = EigenValue2;\n        }\n        if (EigenValue3 < Smallest)\n        {\n            Smallest = EigenValue3;\n        }\n\n        if (EigenValue1 <= EigenValue2 && EigenValue1 <= EigenValue3)\n        {\n            Smallest = EigenValue1;\n            if (EigenValue2 <= EigenValue3)\n            {\n                Middle = EigenValue2;\n                Largest = EigenValue3;\n            }\n            else\n            {\n                Middle = EigenValue3;\n                Largest = EigenValue2;\n            }\n        }\n\n        if (EigenValue1 >= EigenValue2 && EigenValue1 >= EigenValue3)\n        {\n            Largest = EigenValue1;\n            if (EigenValue2 <= EigenValue3)\n            {\n                Smallest = EigenValue2;\n                Middle = EigenValue3;\n            }\n            else\n            {\n                Smallest = EigenValue3;\n                Middle = EigenValue2;\n            }\n        }\n\n        if ((EigenValue1 >= EigenValue2 && EigenValue1 <= EigenValue3) || (EigenValue1 <= EigenValue2 && EigenValue1 >= EigenValue3))\n        {\n            Middle = EigenValue1;\n            if (EigenValue2 >= EigenValue3)\n            {\n                Largest = EigenValue2;\n                Smallest = EigenValue3;\n            }\n            else\n            {\n                Largest = EigenValue3;\n                Smallest = EigenValue2;\n            }\n        }\n\n        SmallestEigen[i] = Smallest;\n        MiddleEigen[i] = Middle;\n        LargestEigen[i] = Largest;\n\n        DLS[i] = std::abs(SmallestEigen[i] / LargestEigen[i]); // std::abs ( LargestEigen[i] -  SmallestEigen[i] ) ;\n        DLM[i] = std::abs(MiddleEigen[i] / LargestEigen[i]);   // std::abs (  LargestEigen[i] - MiddleEigen[i] ) ;\n        DMS[i] = std::abs(SmallestEigen[i] / MiddleEigen[i]);  // std::abs ( MiddleEigen[i] -  SmallestEigen[i] ) ;\n        Sigma[i] = (SmallestEigen[i]) / (SmallestEigen[i] + MiddleEigen[i] + LargestEigen[i]);\n    } // For each point of the cloud\n\n    std::cout << \"Computing Sigma is Done! \" << std::endl;\n    // *Color Map For the difference of the eigen values\n\n    double MaxD = 0.00;\n    double MinD = cloud->points.size();\n\n    for (size_t i = 0; i < cloud->points.size(); ++i)\n    {\n        if (Sigma[i] < MinD)\n            MinD = Sigma[i];\n        if (Sigma[i] > MaxD)\n            MaxD = Sigma[i];\n    }\n\n    std::cout << \"Minimum is :\" << MinD << std::endl;\n    std::cout << \"Maximum  is :\" << MaxD << std::endl;\n\n    //   *****************************************\n    // *Red and white (khaki)\n\n    for (size_t i = 0; i < cloud->points.size(); ++i)\n    {\n        cloud->points[i].r = 240;\n        cloud->points[i].g = 230;\n        cloud->points[i].b = 140;\n    }\n\n    float step = ((MaxD - MinD) / 100);\n    std::vector<Eigen::Vector3f> Edge;\n    int EdgeNum = 0;\n    for (size_t i = 0; i < cloud->points.size(); ++i)\n    {\n        if (Sigma[i] > (MinD + (10 * step)))\n        {\n            // *Original: 6 * step\n            cloud->points[i].r = 255;\n            cloud->points[i].g = 0;\n            cloud->points[i].b = 0;\n            Eigen::Vector3f temp(cloud->points[i].x, cloud->points[i].y, cloud->points[i].z);\n            Edge.push_back(temp);\n            EdgeNum++;\n        }\n    }\n\n    Eigen::Vector3f mu(0.0, 0.0, 0.0);\n    float mu_distance = 0.0;\n    float mean_distance = 0.0;\n    const int N = Edge.size();\n    for(size_t i = 0; i < N; i++) {\n        mu = mu + Edge[i];\n        mean_distance = mean_distance + sqrt(Edge[i].dot(Edge[i]));\n    }\n    mu = mu / N;\n    mu_distance = sqrt(mu.dot(mu));\n    mean_distance = mean_distance / N;\n    std::cout << \"Edge Points Center: \" << mu(0) << ' ' << mu(1) << ' ' << mu(2) << std::endl;\n    std::cout << \"Distance of Edge Points Center: \" << mu_distance << std::endl;\n    std::cout << \"Mean Distance of Edge Points: \" << mean_distance << std::endl;\n\n    //   *****************************************\n\n    std::cout << \"Number of Edge points  is :\" << EdgeNum << std::endl;\n\n    pcl::io::savePCDFileASCII(output_pcd, *cloud);\n    std::cerr << \"Saved \" << cloud->size() << \" data points to test_pcd.pcd.\" << std::endl;\n\n    pcl::visualization::CloudViewer viewer(\"Cloud Viewer\");\n    viewer.showCloud(cloud);\n    while (!viewer.wasStopped())\n    {\n    }\n\n    return 0;\n}", "meta": {"hexsha": "552a70f3b4104f5729d091c9f880cf29e0988c87", "size": 10431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main_visualization.cpp", "max_stars_repo_name": "zxl19/Edge_Extraction", "max_stars_repo_head_hexsha": "9f4c6ac878928a1390c5ce0f14b7fc899dbd1506", "max_stars_repo_licenses": ["MIT"], "max_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_visualization.cpp", "max_issues_repo_name": "zxl19/Edge_Extraction", "max_issues_repo_head_hexsha": "9f4c6ac878928a1390c5ce0f14b7fc899dbd1506", "max_issues_repo_licenses": ["MIT"], "max_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_visualization.cpp", "max_forks_repo_name": "zxl19/Edge_Extraction", "max_forks_repo_head_hexsha": "9f4c6ac878928a1390c5ce0f14b7fc899dbd1506", "max_forks_repo_licenses": ["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.3944099379, "max_line_length": 133, "alphanum_fraction": 0.5460646151, "num_tokens": 2872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5310009898593931}}
{"text": "//\n// Created by ziqwang on 04.04.20.\n//\n\n\n#include \"InterlockingSolver_Clp.h\"\n#include \"tbb/tbb.h\"\n#include <Eigen/SparseQR>\n\n#include \"ClpInterior.hpp\"\n#include \"ClpSimplex.hpp\"\n#include \"ClpCholeskyDense.hpp\"\n\n\ntemplate<typename Scalar>\nbool InterlockingSolver_Clp<Scalar>::isTranslationalInterlocking(InterlockingSolver_Clp::pInterlockingData &data) {\n    vector<EigenTriple> tris;\n    Eigen::Vector2i size;\n\n    InterlockingSolver<Scalar>::computeTranslationalInterlockingMatrix(tris, size);\n\n    if (!checkSpecialCase(data, tris, false, size)) {\n        return false;\n    }\n\n    int num_var = size[1];\n    InterlockingSolver<Scalar>::appendAuxiliaryVariables(tris, size);\n    InterlockingSolver<Scalar>::appendMergeConstraints(tris, size, false);\n\n    return solve(data, tris, false, size[0], size[1], num_var);\n}\n\ntemplate<typename Scalar>\nbool InterlockingSolver_Clp<Scalar>::isRotationalInterlocking(InterlockingSolver_Clp::pInterlockingData &data) {\n    vector<EigenTriple> tris;\n    Eigen::Vector2i size;\n\n    InterlockingSolver<Scalar>::computeRotationalInterlockingMatrix(tris, size);\n\n//    std::cout << \"special case\" << std::endl;\n    if (!checkSpecialCase(data, tris, true, size)) {\n        return false;\n    }\n\n    // Ignore this for lpopt - Enlarging the matrix\n    int num_var = size[1];\n    InterlockingSolver<Scalar>::appendAuxiliaryVariables(tris, size);\n    InterlockingSolver<Scalar>::appendMergeConstraints(tris, size, true);\n\n//    std::cout << \"solve\" << std::endl;\n    return solve(data, tris, true, size[0], size[1], num_var);\n}\n\ntemplate<typename Scalar>\nbool InterlockingSolver_Clp<Scalar>::checkSpecialCase(pInterlockingData &data,\n                                                      vector<EigenTriple> copy_tris,\n                                                      bool rotationalInterlockingCheck,\n                                                      Eigen::Vector2i copy_size) {\n\n    InterlockingSolver<Scalar>::appendMergeConstraints(copy_tris, copy_size, rotationalInterlockingCheck);\n\n    if (copy_size[0] < copy_size[1]) return true;\n\n    EigenSpMat A(copy_size[0], copy_size[1]);\n    A.setFromTriplets(copy_tris.begin(), copy_tris.end());\n\n    Eigen::SparseQR<Eigen::SparseMatrix<double>,\n            Eigen::COLAMDOrdering<int> > solver;\n    solver.compute(A.transpose());\n\n    if (A.cols() - solver.rank() == 0) {\n        return true;\n    } else {\n        Eigen::VectorXd solution = Eigen::MatrixXd(solver.matrixQ()).rightCols(A.cols() - solver.rank()).col(0);\n        std::cout << \"||A * x||: \" << (A * solution).norm() << \", ||x||: \" << solution.norm() << std::endl;\n        unpackSolution(data, rotationalInterlockingCheck, solution.data(), copy_size[1]);\n        return false;\n    }\n    return true;\n}\n\ntemplate<typename Scalar>\nbool InterlockingSolver_Clp<Scalar>::solve(InterlockingSolver_Clp::pInterlockingData &data, vector<EigenTriple> &tris,\n                                           bool rotationalInterlockingCheck,\n                                           int num_row,\n                                           int num_col,\n                                           int num_var) {\n\n    //Problem definition\n    //tris is equal to a sparse matrix A, which size is [num_row x num_col]\n    //our variables are [x, t], a row vector.\n    //x: (size: num_var) is the instant translational and rotational velocity.\n    //t: (size: num_col - num_var) is the auxiliary variable.\n    //the optimization is formulated as:\n    //              min \\sum_{i = 0}^{num_row} -t_i\n    //  s.t.            A[x, t] >= 0\n    //                  1 >= t >= 0\n    //                    x \\in R\n    // Ideally if the structure is interlocking, the objective value should be zero.\n    // In practice, due to numerical error, we have to allow a small tolerance for the objective value.\n\n\n    EigenSpMat spatMat(num_row, num_col);\n    spatMat.setFromTriplets(tris.begin(), tris.end());\n\n\n    CoinPackedMatrix matrix(true, num_row, num_col, spatMat.nonZeros(), spatMat.valuePtr(), spatMat.innerIndexPtr(),\n                            spatMat.outerIndexPtr(), spatMat.innerNonZeroPtr());\n\n    // boundaries for rows and colums values\n\n    double *objective = new double[num_col];\n    double *rowLower = new double[num_row];\n    double *rowUpper = new double[num_row];\n    double *colLower = new double[num_col];\n    double *colUpper = new double[num_col];\n\n    //objects\n    for (size_t id = 0; id < num_col; id++) {\n        if (id < num_var)\n            objective[id] = 0;\n        else\n            objective[id] = -1;\n    }\n\n    //bound\n    for (size_t id = 0; id < num_row; id++)\n        rowLower[id] = 0;\n\n    for (size_t id = 0; id < num_row; id++)\n        rowUpper[id] = 0;\n\n    for (size_t id = 0; id < num_col; id++) {\n        if (id < num_var)\n            colLower[id] = -COIN_DBL_MAX;\n        else\n            colLower[id] = 0;\n    }\n\n    for (size_t id = 0; id < num_col; id++) {\n        if (id < num_var)\n            colUpper[id] = COIN_DBL_MAX;\n        else\n            colUpper[id] = 1;\n    }\n\n    if (type == SIMPLEX) {\n        return solveSimplex(data, rotationalInterlockingCheck, num_row, num_col, num_var, matrix, colLower, colUpper, objective, rowLower,\n                            rowUpper);\n    } else {\n        return solveBarrier(data, rotationalInterlockingCheck, num_row, num_col, num_var, matrix, colLower, colUpper, objective, rowLower,\n                            rowUpper);\n    }\n}\n\ntemplate<typename Scalar>\nbool InterlockingSolver_Clp<Scalar>::solveSimplex(pInterlockingData &data,\n                                                  bool rotationalInterlockingCheck,\n                                                  int num_row,\n                                                  int num_col,\n                                                  int num_var,\n                                                  const CoinPackedMatrix &matrix,\n                                                  const double *colLower,\n                                                  const double *colUpper,\n                                                  const double *objective,\n                                                  const double *rowLower,\n                                                  const double *rowUpper) {\n\n    ClpSimplex model(true);\n    CoinMessageHandler handler;\n    handler.setLogLevel(0); //set loglevel to zero will silence the solver\n    model.passInMessageHandler(&handler);\n    model.newLanguage(CoinMessages::us_en);\n\n    // load problem\n    model.loadProblem(matrix, colLower, colUpper, objective, rowLower, rowUpper);\n\n    // set tolerance\n    // a experiment discovery: if the structure is interlocking,\n    // the maximum \"t\" (the auxiliary variables) is around tolerance * 10\n    // the average of the \"t\" is around tolerance * 5.\n    // it is very useful to use these number to check whether structure is interlocking or not.\n    model.setPrimalTolerance(1e-9);\n    // Solve\n    model.primal();\n\n    // Solution\n    const double target_obj_value = model.rawObjectiveValue();\n    double *solution = model.primalColumnSolution();\n    double *row_solution = model.primalRowSolution();\n\n    double max_sol = 0;\n    for (int id = num_var; id < num_col; id++) {\n        max_sol = std::max(solution[id], max_sol);\n    }\n\n    unpackSolution(data, rotationalInterlockingCheck, solution, num_var);\n\n    double min_row_sol = MAX_FLOAT;\n    for (int id = 0; id < num_row; id++) {\n        min_row_sol = std::min(row_solution[id], min_row_sol);\n    }\n\n    std::cout << \"min_row:\\t\" << min_row_sol; //should be around zero\n    std::cout << \",\\tmax_t:\\t\" << std::abs(max_sol); //interlocking if max_t is around zero\n    std::cout << \",\\taverage_t:\\t\" << std::abs(target_obj_value) / num_row << std::endl;//interlocking if average_t is around zero\n    if (max_sol < 5e-6) {\n        return true;\n    } else {\n        return false;\n    }\n}\n\ntemplate<typename Scalar>\nbool InterlockingSolver_Clp<Scalar>::solveBarrier(pInterlockingData &data,\n                                                  bool rotationalInterlockingCheck,\n                                                  int num_row,\n                                                  int num_col,\n                                                  int num_var,\n                                                  const CoinPackedMatrix &matrix,\n                                                  const double *colLower,\n                                                  const double *colUpper,\n                                                  const double *objective,\n                                                  const double *rowLower,\n                                                  const double *rowUpper) {\n\n    ClpInterior int_model;\n    ClpCholeskyDense *cholesky = new ClpCholeskyDense();\n\n    CoinMessageHandler handler;\n    handler.setLogLevel(0); //set loglevel to zero will silence the solver\n    int_model.passInMessageHandler(&handler);\n    int_model.newLanguage(CoinMessages::us_en);\n\n    int_model.loadProblem(matrix, colLower, colUpper, objective, rowLower, rowUpper);\n    int_model.setCholesky(cholesky);\n\n    int_model.setPrimalTolerance(1e-8);\n\n    int_model.primalDual();\n\n    // Solution\n    const double target_obj_value = int_model.rawObjectiveValue();\n    double *solution = int_model.primalColumnSolution();\n    double max_sol = 0;\n    for (int id = num_var; id < num_col; id++) {\n        max_sol = std::max(solution[id], max_sol);\n    }\n\n    unpackSolution(data, rotationalInterlockingCheck, solution, num_var);\n\n    //verify solution\n\n    double *row_solution = int_model.primalRowSolution();\n\n    double min_row_sol = MAX_FLOAT;\n    for (int id = 0; id < num_row; id++) {\n        min_row_sol = std::min(row_solution[id], min_row_sol);\n    }\n\n    std::cout << \"min_row:\\t\" << min_row_sol; //should be around zero\n    std::cout << \",\\tmax_t:\\t\" << std::abs(max_sol); //interlocking if max_t is around zero\n    std::cout << \",\\taverage_t:\\t\" << std::abs(target_obj_value) / num_row << std::endl;//interlocking if average_t is around zero\n    if (max_sol < 5e-6) {\n        return true;\n    } else {\n        return false;\n    }\n}\n\ntemplate<typename Scalar>\nvoid InterlockingSolver_Clp<Scalar>::unpackSolution(InterlockingSolver_Clp::pInterlockingData &data,\n                                                    bool rotationalInterlockingCheck,\n                                                    const double *solution,\n                                                    int num_var) {\n    data = make_shared<typename InterlockingSolver<Scalar>::InterlockingData>();\n    for (pContactGraphNode node: graph->nodes) {\n        Vector3 trans(0, 0, 0);\n        Vector3 rotate(0, 0, 0);\n        Vector3 center = node->centroid;\n        if (node->dynamicID != -1) {\n            if (rotationalInterlockingCheck) {\n                trans = Vector3(solution[node->dynamicID * 6],\n                                solution[node->dynamicID * 6 + 1],\n                                solution[node->dynamicID * 6 + 2]);\n                rotate = -Vector3(solution[node->dynamicID * 6 + 3],\n                                  solution[node->dynamicID * 6 + 4],\n                                  solution[node->dynamicID * 6 + 5]);\n            } else {\n                trans = Vector3(solution[node->dynamicID * 3],\n                                solution[node->dynamicID * 3 + 1],\n                                solution[node->dynamicID * 3 + 2]);\n            }\n        }\n\n        data->traslation.push_back(trans);\n        data->rotation.push_back(rotate);\n        data->center.push_back(center);\n\n//        std::cout << node->staticID << \":\" << trans.transpose() << \", \" << rotate.transpose() << std::endl;\n    }\n}\n\nvoid TemporaryFunction_InterlockingSolver_Clp ()\n{\n    InterlockingSolver_Clp<double> solver(nullptr, nullptr);\n}", "meta": {"hexsha": "36498edd363ae3d78e5858b776238fd6b370c6ac", "size": 11866, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TopoLite/Interlocking/InterlockingSolver_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": "src/TopoLite/Interlocking/InterlockingSolver_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": "src/TopoLite/Interlocking/InterlockingSolver_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": 38.651465798, "max_line_length": 138, "alphanum_fraction": 0.5686836339, "num_tokens": 2694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220294, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5310009863871918}}
{"text": "/* p_integrand.cpp */\n#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <boost/math/special_functions/gamma.hpp>\n#include <algorithm>\n\nextern \"C\"\n{\n/* Survival function for R^phi*W */\nint RW_marginal_C(double *xval, double phi, double gamma, int n_xval, double *result){\n    double tmp2 = pow(gamma/2, phi)/boost::math::tgamma(0.5);\n    double tmp1, tmp0, a;\n    a = 0.5-phi;\n    \n    for(int i=0; i<n_xval; i++){\n        tmp1 = gamma/(2*pow(xval[i],1/phi));\n        tmp0 = tmp2/(a*xval[i]);\n        result[i] = boost::math::gamma_p(0.5L,tmp1) + boost::math::tgamma((long double)(a+1),tmp1)*tmp0-pow(tmp1,a)*exp(-tmp1)*tmp0;\n    }\n    return 1;\n}\n\n/* Marginal distribution function for R^phi*W + epsilon */\nint pRW_me_interp_C(double *xval, double *xp, double *surv_p, double tau_sqd, double phi, double gamma, int n_xval, int n_grid, double *result){\n    bool tau_bool = (tau_sqd > 0.05);\n    double tp[n_grid];\n    double integrand_p[n_grid];\n    double tmp, tmp_res; /* temporary constant */\n    double tmp_sum = 0; /* temporary trapesoid sum */\n    double sd = sqrt(tau_sqd);\n    double sd_const = sqrt(2)*sd;\n    double sd_const_pi =sqrt(2*M_PI)*sd;\n    int i,j, tmp_int; /* iterative constants */\n\n    for (i = 0; i < n_xval; i++) {\n        if(tau_bool & (xval[i]<820)){\n            /* Calculate integrand on a grid */\n            for(j=0; j<n_grid;j++){\n                tmp = xval[i]-xp[j];\n                tp[j] = tmp;\n                integrand_p[j] = exp(-tmp*tmp/(2*tau_sqd)) * surv_p[j];\n            }\n            \n            /* Numerical integral using the trapesoid method */\n            for(j=0; j<(n_grid-1);j++){\n                tmp_sum+= (tp[j+1]-tp[j])*(integrand_p[j] + integrand_p[j+1])/2;\n            }\n            tmp_res = 0.5*erfc(-xval[i]/sd_const)-tmp_sum/sd_const_pi;\n            tmp_sum = 0;\n            \n            /* CDF value must be greater than 0 */\n            if(tmp_res < 0){\n                tmp_res = 0;\n            }\n            result[i] = tmp_res;\n        }\n        else{\n            tmp_int = RW_marginal_C(&xval[i], phi, gamma, 1, &tmp_res);\n            result[i] = 1-tmp_res;\n        }\n    }\n    \n    return 1;\n}\n\n\n/* Transform to uniform scales from RW mixtures */\nint RW_me_2_unifs(double *X, double *xp, double *Surv, double tau_sqd, double *phi, double gamma,\n                    int n_s, int n_grid, int n_t, double *unifs){\n    int tmp_int, X_lookup, Surv_lookup;\n    for (int i = 0; i<n_s;i++){\n        X_lookup = i*n_t;\n        Surv_lookup = i*n_grid;\n        tmp_int = pRW_me_interp_C(X+X_lookup, xp, Surv+Surv_lookup, tau_sqd, phi[i], gamma, n_t, n_grid, unifs+X_lookup);\n    }\n    \n    return 1;\n}\n\n\n\n/* Get the quantile range for certain probability levels */\nint find_xrange_pRW_C(double min_p, double max_p, double min_x, double max_x, double phi, double gamma, double *x_range){\n    if (min_x >= max_x){\n        printf(\"Initial value of mix_x must be smaller than max_x.\\n\");\n        exit(EXIT_FAILURE);\n    }\n    \n    /* First the min */\n    double p_min_x;\n    int tmp_int;\n    tmp_int = 1-RW_marginal_C(&min_x, phi, gamma, 1, &p_min_x);\n    while (1-p_min_x > min_p){\n        min_x = min_x/2; /* R^phi*W is always positive */\n        tmp_int = RW_marginal_C(&min_x, phi, gamma, 1, &p_min_x);\n    }\n        \n    x_range[0] = min_x;\n    \n    /* Now the max */\n    double p_max_x;\n    tmp_int = RW_marginal_C(&max_x,  phi, gamma, 1, &p_max_x); /* Survival value */\n    while (1 - p_max_x < max_p){\n        max_x = max_x*2; /* Upper will set to 20 initially */\n        tmp_int = RW_marginal_C(&max_x, phi, gamma, 1, &p_max_x);\n    }\n        \n    x_range[1] = max_x;\n    return 1;\n}\n\n/* Get the quantile using the bisection method */\ndouble qRW_bisection_C(double p, double phi, double gamma, int n_x){\n    double x_range[2];\n    int tmp_res = 0;\n    tmp_res = find_xrange_pRW_C(p, p, 1.0, 5.0, phi, gamma, x_range);\n    double m = (x_range[0]+x_range[1])/2;\n    int iter=0;\n    double new_F;\n    tmp_res = RW_marginal_C(&m, phi, gamma, 1, &new_F);\n    double diff = 1-new_F-p;\n    while (iter<100 & abs(diff)> 1e-04){\n        if (diff>0){\n            x_range[1] = m;}\n        else{\n            x_range[0]=m;}\n        m = (x_range[0]+x_range[1])/2;\n        tmp_res = RW_marginal_C(&m, phi, gamma, 1, &new_F);\n        diff = 1-new_F-p;\n        iter += 1;\n    }\n    return m;\n}\n\n/* Get the quantile range for certain probability levels */\nint find_xrange_pRW_me_C(double min_p, double max_p, double min_x, double max_x, double *xp, double *surv_p, double tau_sqd, double phi, double gamma, int n_grid, double *x_range){\n    if (min_x >= max_x){\n        printf(\"Initial value of mix_x must be smaller than max_x.\\n\");\n        exit(EXIT_FAILURE);\n    }\n    \n    /* First the min */\n    double p_min_x;\n    int tmp_int;\n    tmp_int = pRW_me_interp_C(&min_x, xp, surv_p, tau_sqd, phi, gamma, 1, n_grid, &p_min_x);\n    while (p_min_x > min_p){\n        min_x = min_x-40/phi;\n        tmp_int = pRW_me_interp_C(&min_x, xp, surv_p, tau_sqd, phi, gamma, 1, n_grid, &p_min_x);\n    }\n        \n    x_range[0] = min_x;\n    \n    /* Now the max */\n    double p_max_x;\n    tmp_int = pRW_me_interp_C(&max_x, xp, surv_p, tau_sqd, phi, gamma, 1, n_grid, &p_max_x);\n    while (p_max_x < max_p){\n        max_x = max_x*2; /* Upper will set to 20 initially */\n        tmp_int = pRW_me_interp_C(&max_x, xp, surv_p, tau_sqd, phi, gamma, 1, n_grid, &p_max_x);\n    }\n        \n    x_range[1] = max_x;\n    return 1;\n}\n\n\n\n/* Density function for R^phi*W */\nint RW_density_C(double *xval, double phi, double gamma, int n_xval, double *result){\n    double tmp2 = pow(gamma/2, phi)/boost::math::tgamma(0.5);\n    double tmp1, tmp0, a;\n    a = 0.5-phi;\n    \n    for(int i=0; i<n_xval; i++){\n        tmp1 = gamma/(2*pow(xval[i],1/phi));\n        tmp0 = tmp2/(a*pow(xval[i],2));\n        result[i] = (boost::math::tgamma((long double)(a+1),tmp1)-pow(tmp1,a)*exp(-tmp1))*tmp0;\n    }\n    return 1;\n}\n\n/* Get the quantile using Newton-Raphson method */\ndouble qRW_newton_C(double p, double phi, double gamma, int n_x){\n    double x_range[2];\n    int tmp_res = 0;\n    tmp_res = find_xrange_pRW_C(p, p, 1.0, 5.0, phi, gamma, x_range);\n    double new_x, current_x = x_range[0];\n    int iter=0;\n    double error=1;\n    double Surv_value, f_value;\n    \n    while (iter<400 & error> 1e-08){\n        tmp_res = RW_marginal_C(&current_x , phi, gamma, 1, &Surv_value);\n        tmp_res = RW_density_C(&current_x , phi, gamma, 1, &f_value);\n        new_x = current_x - (1-Surv_value-p)/f_value;\n        error = abs(new_x-current_x);\n        iter += 1;\n        current_x = fmax(x_range[0], new_x);\n        if(current_x == x_range[0]){current_x = qRW_bisection_C(p, phi, gamma, 100);}\n    }\n    \n    return current_x;\n}\n\n\n/* Marginal density function for R^phi*W + epsilon */\nint dRW_me_interp_C(double *xval, double *xp, double *den_p, double tau_sqd, double phi, double gamma, int n_xval, int n_grid, double *result){\n    double thresh_large = 820;\n    if(tau_sqd < 1) {\n        thresh_large = 50;\n    }\n    bool tau_bool = (tau_sqd > 0.05);\n    \n    double tp[n_grid];\n    double integrand_p[n_grid];\n    double tmp, tmp_res; /* temporary constant */\n    double tmp_sum = 0; /* temporary trapesoid sum */\n    double sd = sqrt(tau_sqd);\n    double sd_const_pi =sqrt(2*M_PI)*sd;\n    int i,j, tmp_int; /* iterative constants */\n\n    for (i = 0; i < n_xval; i++) {\n        if(tau_bool & (xval[i]<thresh_large)){\n            /* Calculate integrand on a grid */\n            for(j=0; j<n_grid;j++){\n                tmp = xval[i]-xp[j];\n                tp[j] = tmp;\n                integrand_p[j] = exp(-tmp*tmp/(2*tau_sqd)) * den_p[j];\n            }\n            \n            /* Numerical integral using the trapesoid method */\n            for(j=0; j<(n_grid-1);j++){\n                tmp_sum+= (tp[j+1]-tp[j])*(integrand_p[j] + integrand_p[j+1])/2;\n            }\n            tmp_res = tmp_sum/sd_const_pi;\n            tmp_sum = 0;\n            result[i] = tmp_res;\n        }else if((tau_bool & (xval[i]>=thresh_large))|(!tau_bool & (xval[i]>0))){\n            tmp_int = RW_density_C(&xval[i], phi, gamma, 1, &tmp_res);\n            result[i] = tmp_res;\n        }else{\n            result[i] = 0;\n        }\n    }\n    \n    return 1;\n}\n\nint density_interp_grid(double *xp, double *phi, double gamma, int n_phi, int n_grid, double *Den, double *Surv){\n    int counter = 0;\n    int i,j, tmp_int;\n    double tmp_surv, tmp_den;\n    double tmp2, tmp1, tmp0, a, tmp_incomp, tmp_phi, tmp_phi_inv, tmp_xp;\n    double gamma_half = gamma/2;\n    \n    for(i=0; i<n_phi; i++){\n        tmp_phi = phi[i];\n        a = 0.5-tmp_phi;\n        tmp2 = std::pow(gamma_half, tmp_phi)/(a*sqrt(M_PI));\n        tmp_phi_inv = 1/tmp_phi;\n        for(j=0; j<n_grid; j++){\n            tmp_xp = xp[j];\n            tmp1 = gamma_half/std::pow(tmp_xp,tmp_phi_inv);\n            tmp0 = tmp2/tmp_xp;\n            tmp_incomp = (boost::math::tgamma((long double)(a+1),tmp1)-std::pow(tmp1,a)*exp(-tmp1))*tmp0;\n            Surv[counter] = boost::math::gamma_p(0.5L,tmp1) + tmp_incomp;\n            Den[counter++] = tmp_incomp/tmp_xp;\n        }\n    }\n    return 1;\n}\n\ndouble dgev_C(double y, double loc, double scale, double shape, bool log_out){\n    double t = std::pow(1+shape*((y-loc)/scale), -1/shape);\n    double result;\n    if(log_out){\n        result = -log(scale)+(shape+1)*log(t)-t;\n    }else{\n        result = std::pow(t, shape+1)*exp(-t)/scale;\n    }\n    return result;\n}\n\ndouble dnorm_C(double y, double mean, double sd, bool log_out){\n    double t=(y-mean)/sd;\n    double result;\n    if(log_out){\n        result = -0.5*log(2*M_PI)-log(sd)-0.5*t*t;\n    }else{\n        result = exp(-0.5*t*t)/(sqrt(2*M_PI)*sd);\n    }\n    return result;\n}\n\n/* Thresh_X and Thresh_X_above are required */\n/* xp, den_p and surv_p are required */\n/* Calculate column_wise in C order OR one time  */\ndouble marg_transform_data_mixture_me_likelihood_C(double *Y, double *X, double *X_s, bool *cen, bool *cen_above,\n                                                double *Loc, double *Scale, double *Shape,\n                                                double tau_sqd, double *phi, double gamma,\n                                                double *xp, double *Den, int n_s, int n_grid){\n    double sd = sqrt(tau_sqd);\n    double sd_const = sqrt(2)*sd;\n    double ll=0;\n    double RW_den;\n    int i, tmp_int, Den_lookup;\n    \n    for (i=0; i<n_s; i++){\n        if(cen[i]){\n            ll += log(0.5*erfc(-(X[i]-X_s[i])/sd_const));\n        }else if(cen_above[i]){\n            ll += log(1-0.5*erfc(-(X[i]-X_s[i])/sd_const));\n        }else{\n            Den_lookup = i*n_grid;\n            tmp_int = dRW_me_interp_C(&X[i], xp, &Den[Den_lookup], tau_sqd, phi[i], gamma, 1, n_grid, &RW_den);\n            ll += dnorm_C(X[i], X_s[i], sd, true)+dgev_C(Y[i], Loc[i], Scale[i], Shape[i], true)-log(RW_den);\n        }\n    }\n    return ll;\n}\n\n/* Calculate row_wise in F order OR one location */\ndouble marg_transform_data_mixture_me_likelihood_F(double *Y, double *X, double *X_s, bool *cen, bool *cen_above,\n                                                double *Loc, double *Scale, double *Shape,\n                                                double tau_sqd, double phi, double gamma,\n                                                double *xp, double *den_p, int n_t, int n_grid){\n    double sd = sqrt(tau_sqd);\n    double sd_const = sqrt(2)*sd;\n    double ll=0;\n    double RW_den;\n    int i, tmp_int;\n    \n    for (i=0; i<n_t; i++){\n        if(cen[i]){\n            ll += log(0.5*erfc(-(X[i]-X_s[i])/sd_const));\n        }else if(cen_above[i]){\n            ll += log(1-0.5*erfc(-(X[i]-X_s[i])/sd_const));\n        }else{\n            tmp_int = dRW_me_interp_C(&X[i], xp, den_p, tau_sqd, phi, gamma, 1, n_grid, &RW_den);\n            ll += dnorm_C(X[i], X_s[i], sd, true)+dgev_C(Y[i], Loc[i], Scale[i], Shape[i], true)-log(RW_den);\n        }\n    }\n    return ll;\n}\n\n/* Calculate all locations and all times */\ndouble marg_transform_data_mixture_me_likelihood_global(double *Y, double *X, double *X_s, bool *cen, bool *cen_above,\n                                                double *Loc, double *Scale, double *Shape,\n                                                double tau_sqd, double *phi, double gamma,\n                                                double *xp, double *Den, int n_s, int n_t, int n_grid){\n    \n    double ll=0;\n    int site, tmp_int, Den_lookup, X_lookup;\n    \n    for (site=0; site<n_s; site++){\n        X_lookup = site*n_t;\n        Den_lookup = site*n_grid;\n        ll += marg_transform_data_mixture_me_likelihood_F(&Y[X_lookup], &X[X_lookup], &X_s[X_lookup], &cen[X_lookup], &cen_above[X_lookup], &Loc[X_lookup], &Scale[X_lookup], &Shape[X_lookup], tau_sqd, phi[site], gamma, xp, &Den[Den_lookup], n_t, n_grid);\n    }\n    return ll;\n}\n\n\nvoid print_c(double *Y, int n_grid){\n    printf(\"%4.2f %4.2f\\n\",*Y,*(Y+n_grid-1));\n}\n\ndouble print_Vec(double *Y, int n_grid, int n_s){\n    int Den_lookup;\n    for(int i=0; i<n_s; i++){\n        Den_lookup = i*n_grid;\n        print_c(&Y[Den_lookup], n_grid);\n    }\n    \n    return Y[0];\n}\n\n\n}\n", "meta": {"hexsha": "3e6d6427f660e12f37be3ca77e477c06ede8898b", "size": 13116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "p_integrand.cpp", "max_stars_repo_name": "likun-stat/nonstat_noNugget", "max_stars_repo_head_hexsha": "e013597809699ac683974238660e5759b7acf52b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "p_integrand.cpp", "max_issues_repo_name": "likun-stat/nonstat_noNugget", "max_issues_repo_head_hexsha": "e013597809699ac683974238660e5759b7acf52b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "p_integrand.cpp", "max_forks_repo_name": "likun-stat/nonstat_noNugget", "max_forks_repo_head_hexsha": "e013597809699ac683974238660e5759b7acf52b", "max_forks_repo_licenses": ["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.4251968504, "max_line_length": 254, "alphanum_fraction": 0.5616041476, "num_tokens": 3996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5309331220509242}}
{"text": "//\n// Created by lynn on 2020/7/19.\n//\n//#include <acado/acado_optimal_control.hpp>\n#include <acado/acado_toolkit.hpp>\n#include \"ros/ros.h\"\n#include <chrono>\n#include \"iomanip\"\n#include <acado/acado_gnuplot.hpp>\n#include <geometry_msgs/Point.h>\n#include <geometry_msgs/Vector3.h>\n#include <geometry_msgs/Quaternion.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/TwistStamped.h>\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\n#include <nav_msgs/Odometry.h>\n#include <mavros_msgs/State.h>\n#include <mavros_msgs/AttitudeTarget.h>\n#include <sensor_msgs/Imu.h>\n#include <std_msgs/Bool.h>\n#include <std_msgs/Float32.h>\n#include \"offb_posctl/controlstate.h\"\n//#include <Eigen/Eigen>// This step will generate error about eigen ,the reason is not clear by far\n#include <Eigen/Geometry>\n#include <Eigen/Core>\n#include <thread>\n#include <math.h>\n#include <stdlib.h>\n#include <FILTER.h>\n\nusing namespace Eigen;\nusing namespace std;\n\ngeometry_msgs::PoseStamped pos_ref;         //\u65e0\u4eba\u673a\u53c2\u8003\u4f4d\u7f6e\n\nmavros_msgs::State current_state;           //\u65e0\u4eba\u673a\u5f53\u524d\u72b6\u6001(mode arm)\nsensor_msgs::Imu   imu_drone;               //\u8bfb\u5165\u7684\u65e0\u4eba\u673a\u7684IMU\u4fe1\u606f \u5305\u62ec\u59ff\u6001\u89d2\u548c\u7ebf\u52a0\u901f\u5ea6\n\ngeometry_msgs::PoseStamped  pos_drone;      //\u8bfb\u5165\u7684\u65e0\u4eba\u673a\u5f53\u524d\u4f4d\u7f6e\ngeometry_msgs::PoseStamped  pos_drone_last; //\u8bfb\u5165\u7684\u65e0\u4eba\u673a\u4e0a\u4e00\u6b21\u4f4d\u7f6e\ngeometry_msgs::PoseStamped  fused_drone; //\u878d\u5408\u4e86vicon\u6570\u636e\u7684\u65e0\u4eba\u673a\u4f4d\u59ff\uff0c\u6ce8\u610f\u662fNED\u5750\u6807\u4e0b\u7684\uff0c\u9700\u8981\u7ffb\u8f6c\n\ngeometry_msgs::TwistStamped vel_drone;      //\u8bfb\u5165\u7684\u65e0\u4eba\u673a\u5f53\u524d\u901f\u5ea6\n\ngeometry_msgs::Vector3 acc_receive;         //\u8bfb\u5165\u7684\u65e0\u4eba\u673a\u7ebf\u52a0\u901f\u5ea6\ngeometry_msgs::Vector3 angle_receive;       //\u8bfb\u5165\u7684\u65e0\u4eba\u673a\u59ff\u6001\uff08\u6b27\u62c9\u89d2\uff09\ngeometry_msgs::Vector3 angle_fromvicon;       //\u8bfb\u5165\u7684vicon\u8ba1\u7b97\u7684sgement\u59ff\u6001\uff08\u6b27\u62c9\u89d2\uff09\ngeometry_msgs::Vector3 angle_fromvicon_qua;       //\u8bfb\u5165\u7684vicon\u8ba1\u7b97\u7684sgement\u59ff\u6001\uff08\u6b27\u62c9\u89d2\uff09\ngeometry_msgs::Vector3 angle_fromviconinit;  //\u8bfb\u5165\u7684vicon\u8ba1\u7b97\u7684sgement initial \u59ff\u6001\uff08\u6b27\u62c9\u89d2\uff09\ngeometry_msgs::Vector3 fusedangle_receive;\n\ngeometry_msgs::Quaternion orientation_target;   //\u53d1\u7ed9\u65e0\u4eba\u673a\u7684\u59ff\u6001\u6307\u4ee4\n\ngeometry_msgs::Vector3 angle_des;            //\u7ebf\u6027\u6a21\u578b\u8f93\u51fa\u7684\u7406\u60f3\u503c\n//geometry_msgs::Vector3 angle_dis;            //DOB\u63a7\u5236\u5668\u4f30\u8ba1\u7684\u6270\u52a8\u503c\ngeometry_msgs::Vector3 angle_target;            //\u7ecfDOB\u63a7\u5236\u5668\u4f5c\u7528\u540e\u7684\u5b9e\u9645\u7cfb\u7edf\u8f93\u5165\u503c\ngeometry_msgs::Vector3 vel_target, vel_read, vel_read2;\ngeometry_msgs::Vector3 currentRPYangle;   //\u6b27\u62c9\u89d2\ngeometry_msgs::Vector3 filteredPlaneVelmsg;   //\u6b27\u62c9\u89d2\n// debug data\ngeometry_msgs::Vector3 vel_vicon;\nconst float MAX_POSITION_MEASURE_ERROR = 1;\nEigen::Quaterniond current_quaternion(0,0,0,0);\n\nbool pose_initialized = false;\nbool vel_initialized = false;\nint posvel_updatesynflag= false;// the variable to make sure the pos and vel used in ocp is synchronized, In reality, we can put pos and vel in one topic to avoid this problem\nUSING_NAMESPACE_ACADO\nVariablesGrid state, parameter, control;// used for output result\nreturnValue resultofsolve;\nint timeconsumption=0;\nfloat t_end=2;\nint pointnumber=20;// the number is almost always 20. It less, the accuracy won't be enough, if more, the time consumpiton will be too large.\nint controlfreq=50;\nint discretizedpointpersecond=(int)pointnumber/t_end;\nfloat px_ini = -3.0;\nfloat pz_ini = 0.0;\nfloat vx_ini = -0.1;\nfloat vz_ini = 0.0;\nfloat theta_ini = 0.0;\nfloat rate_ini = 0.0;\nfloat vxPlane_ini=0.0,vyPlane_ini=0.0,vzPlane_ini=0.0;\nfloat aircoeffx=1.5,aircoeffz=0.35;\nfloat carPlaneDistance=3.0;\noffb_posctl::controlstate controlstate_msg;\nbool currentupdateflag= false;\nFILTER filterDroneVelx(150);\nsensor_msgs::Imu drone_imu;\nvoid do_process()\n{\n    chrono::time_point<chrono::steady_clock> begin_time = chrono::steady_clock::now();\n    DifferentialState        px,pz,vx,vz,vxPlane,theta,rate;     // px=xdrone-xcar, pz=zdrone-zcar vx=dot(px),vz=dot(pz)\n    Control                  u1,u2          ;     // u1 is thrust, u2 is theta\n    DifferentialEquation     f( 0.0, t_end );     // the differential equation\n    f << dot(px) == vx;                         // an implementation\n    f << dot(pz) == vz;             // of the model equations\n    f << dot(vx) == u1*sin(theta)-aircoeffx*vxPlane;                 // for the drone.\n    f << dot(vz) == u1*cos(theta)-9.8-aircoeffz*vxPlane;\n    f << dot(vxPlane) == u1*sin(theta)-aircoeffx*vxPlane;\n    f << dot(theta)==rate;\n    f << dot(rate)==u2;\n    OCP ocp_(0.0,t_end,pointnumber);\n    ocp_.minimizeLagrangeTerm(1*(pz+px*theta)*(pz+px*theta)+3*(px+carPlaneDistance)*(px+carPlaneDistance)+0.5*(u1-9.8)*(u1-9.8)+0.5*u2*u2); // the 1.5 is for the target high(in this gazebo the height of car is 0)\n//        ocp_.minimizeLagrangeTerm(1*(pz+px*u2)*(pz+px*u2)+3*(px+carPlaneDistance)*(px+carPlaneDistance)+0.5*(u1-9.8)*(u1-9.8)+0.5*u2*u2); // the 1.5 is for the target high(in this gazebo the height of car is 0)\n//    ocp_.minimizeLagrangeTerm((pz-0.61-(0.1*t-px)*u2)*(pz-0.61-(0.1*t-px)*u2)+(0.1*t-px-3)*(0.1*t-px-3)+0.5*u1*u1+0.5*u2*u2);\n\n    ocp_.subjectTo( f                   );     // minimize T s.t. the model,\n    ocp_.subjectTo( AT_START, px == px_ini );     // the initial values for s,\n    ocp_.subjectTo( AT_START, pz == pz_ini);     // v,\n    ocp_.subjectTo( AT_START, vx == vx_ini);     // and m,\n    ocp_.subjectTo( AT_START, vz == vz_ini);     // and m,\n    ocp_.subjectTo( AT_START, vxPlane == vxPlane_ini);     // and m,\n    ocp_.subjectTo( AT_START, theta == theta_ini);     // and m,\n    ocp_.subjectTo( AT_START, rate == rate_ini);     // and m,\n\n    ocp_.subjectTo( 0 <= u1 <=  9.8*2   );     // the crol input u,\n    ocp_.subjectTo(  -0.628<= theta <= 0.628  );     // and the time horizon T.\n    ocp_.subjectTo(  -1<= vxPlane <= 10  );     // and the time horizon T.\n    ocp_.subjectTo(  -3<= rate <= 3  );\n    ocp_.subjectTo(  -20<= u2 <= 20  );\n\n    OptimizationAlgorithm algorithm(ocp_);     // the optimization algorithm\n    algorithm.set(MAX_NUM_ITERATIONS,50);// default value is 1000\n    algorithm.set(MAX_NUM_QP_ITERATIONS,100);//default value is 10000\n    algorithm.set(KKT_TOLERANCE,1e-3);// default value is 1e-6\n    algorithm.set(PRINTLEVEL,NONE);// do not print solution process.\n    try {\n        resultofsolve=algorithm.solve();                        // solves the problem.\n        algorithm.getControls(control);\n        algorithm.getDifferentialStates(state);\n//        cout << \"controls:  time   |  controls\" <<endl;\n//        control.print();\n    }catch (exception e)\n    {\n        resultofsolve=-1;\n        std::cout<<\"ocp throw exception\"<<std::endl;\n    }\n    px.clearStaticCounters();\n    pz.clearStaticCounters();\n    vx.clearStaticCounters();\n    vz.clearStaticCounters();\n    vxPlane.clearStaticCounters();\n    theta.clearStaticCounters();\n    rate.clearStaticCounters();\n    u1.clearStaticCounters();\n    u2.clearStaticCounters();\n    chrono::time_point<chrono::steady_clock> end_time = chrono::steady_clock::now();\n    timeconsumption=chrono::duration_cast<chrono::milliseconds>(end_time - begin_time).count();\n    cout <<\"time acado consume~~...........~~~~~~~~mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm: \"<<timeconsumption<< endl;\n//    controlcounter=floor(timeconsumption/1000.0*controlfreq)\n}\n\n/**match the current state with the newest states solved by OCP, and the time of the nearest state will be the first used point\n// in the newest solved input. the return value is the matched index\n*/\ndouble tempStateX=0.0,tempStateZ=0.0,tempStateVX=0.0,tempStateVZ=0.0;\nint StateMatch()\n{\n    int k1=1,k2=1,k3=1,k4=1,lefnodeindex=0,rightnodeindex=0,controlcounter=0,mincounter=0;\n    float minStateDistance=0.0,currentStateDistance=0.0,stateX=0.0,stateZ=0.0,stateVX=0.0,stateVZ=0.0;\n    for(;rightnodeindex<controlstate_msg.stateXarray.size();)\n    {\n        lefnodeindex=floor(controlcounter*discretizedpointpersecond/controlfreq);\n        rightnodeindex=lefnodeindex+1;\n        if(rightnodeindex<controlstate_msg.stateXarray.size())\n        {\n            //interpolition\n            stateX= (rightnodeindex-(double)controlcounter*discretizedpointpersecond/controlfreq)*controlstate_msg.stateXarray[lefnodeindex]\n                                +((double)controlcounter*discretizedpointpersecond/controlfreq-lefnodeindex)*controlstate_msg.stateXarray[rightnodeindex];\n\n            stateZ =(rightnodeindex-(double)controlcounter*discretizedpointpersecond/controlfreq)*controlstate_msg.stateZarray[lefnodeindex]\n                               +((double)controlcounter*discretizedpointpersecond/controlfreq-lefnodeindex)*controlstate_msg.stateZarray[rightnodeindex];\n\n            stateVX= (rightnodeindex-(double)controlcounter*discretizedpointpersecond/controlfreq)*controlstate_msg.stateVXarray[lefnodeindex]\n                    +((double)controlcounter*discretizedpointpersecond/controlfreq-lefnodeindex)*controlstate_msg.stateVXarray[rightnodeindex];\n\n            stateVZ =(rightnodeindex-(double)controlcounter*discretizedpointpersecond/controlfreq)*controlstate_msg.stateVZarray[lefnodeindex]\n                    +((double)controlcounter*discretizedpointpersecond/controlfreq-lefnodeindex)*controlstate_msg.stateVZarray[rightnodeindex];\n            currentStateDistance=k1*pow(stateX-px_ini,2)+k2*pow(stateZ-pz_ini,2)+k3*pow(stateVX-vx_ini,2)+k4*pow(stateVZ-vx_ini,2);\n            if(minStateDistance==0)\n            {\n                minStateDistance=currentStateDistance;\n                controlcounter=0;\n            } else{\n                if(minStateDistance>currentStateDistance)\n                {\n                    minStateDistance=currentStateDistance;\n                    mincounter=controlcounter;\n                    tempStateX=stateX;\n                    tempStateZ=stateZ;\n                    tempStateVX=stateVX;\n                    tempStateVZ=stateVZ;\n                }\n            }\n        }\n        controlcounter++;\n    }\n//    std::cout<<\"matchedcoutner:---\"<<mincounter<<\" X:\"<<tempStateX<<\" Z:\"<<tempStateZ<<\" VX:\"<<tempStateVX<<\" VZ:\"<<tempStateVZ<<endl;\n    return mincounter;\n}\n\n\nvoid state_cb(const mavros_msgs::State::ConstPtr &msg){\n    current_state = *msg;\n}\n\nbool hasGotImu = false;\nvoid droneImu_cb(const sensor_msgs::Imu::ConstPtr &msg)\n{\n    drone_imu=*msg;\n    rate_ini=drone_imu.angular_velocity.y;\n}\n\nvoid dronerpy_cb(const geometry_msgs::Vector3::ConstPtr &msg)\n{\n    currentRPYangle =*msg;\n    theta_ini=currentRPYangle.y;\n//    std::cout <<\"currentRPYangle-----------theta_ini:\"<<theta_ini<<endl;\n}\n\nvoid pos_cb(const geometry_msgs::PoseStamped::ConstPtr &msg){ //\u7531ConstPtr\u53ef\u4ee5\u770b\u5230msg\u662f\u6307\u9488\u7684\u5f15\u7528\uff0c\u56e0\u6b64*msg\u76f8\u5f53\u4e8e\u5bf9\u88ab\u5f15\u7528\u7684\u6307\u9488\u5bf9\u8c61\u53d6\u503c\n    if (pose_initialized== false)\n    {\n        pos_drone_last=*msg;\n        pose_initialized=true;\n        return;\n    }\n    if(fabs((*msg).pose.position.x - pos_drone_last.pose.position.x) < MAX_POSITION_MEASURE_ERROR &&\n       fabs((*msg).pose.position.y - pos_drone_last.pose.position.y) < MAX_POSITION_MEASURE_ERROR &&\n       fabs((*msg).pose.position.z - pos_drone_last.pose.position.z) < MAX_POSITION_MEASURE_ERROR)\n    {\n        pos_drone_last = pos_drone;\n        pos_drone = *msg;\n        current_quaternion=Eigen::Quaterniond(pos_drone.pose.orientation.w,pos_drone.pose.orientation.x,pos_drone.pose.orientation.y,pos_drone.pose.orientation.z);\n       if(pose_initialized&&vel_initialized)\n       {\n           if (fabs(pos_drone.header.stamp.nsec-vel_drone.header.stamp.nsec)<30e6)\n           {\n               posvel_updatesynflag=true;\n           }\n       }\n    } else\n    {\n        pos_drone_last=*msg;\n    }\n}\n\nvoid plane_vel_cb(const geometry_msgs::TwistStamped::ConstPtr &msg){\n    vel_drone = *msg;\n//    vxPlane_ini=filterDroneVelx.filter(vel_drone.twist.linear.x);\n    vxPlane_ini=(vel_drone.twist.linear.x);\n    filteredPlaneVelmsg.x=vxPlane_ini;\n    vyPlane_ini=vel_drone.twist.linear.y;\n    vzPlane_ini=vel_drone.twist.linear.z;\n}\n\nvoid relative_postwist_cb(const nav_msgs::Odometry::ConstPtr &msg)\n{\n    px_ini=(*msg).pose.pose.position.x;\n    pz_ini=(*msg).pose.pose.position.z;\n    vx_ini=(*msg).twist.twist.linear.x;\n    vz_ini=(*msg).twist.twist.linear.z;\n    currentupdateflag=true;\n//    std::cout <<\"ocpsolveriniconditons-----------px_ini:  \" << px_ini <<\"   vx_ini:  \" << vx_ini<<\"  pz_ini:  \" << pz_ini <<\"   vz_ini:  \" << vz_ini<<\n//    \"   theta_ini:  \" << theta_ini<< \"   rate_ini:  \" << rate_ini<<std::endl;\n\n}\nint main( int argc, char ** argv)\n{\n    ros::init(argc, argv, \"acado_lag_control\");\n    ros::NodeHandle nh;\n    ros::Rate rate(100);// it is the rate to check and process callback functions. the high rate is to avoid the latency to accept the pos and vel\n//    //Gazebo \u4eff\u771f\u6570\u636e\n    ros::Subscriber drone_imu_sub=nh.subscribe<sensor_msgs::Imu>(\"/mavros/imu/data\",10,droneImu_cb);\n    ros::Subscriber plane_rpy_sub = nh.subscribe<geometry_msgs::Vector3>(\"drone/current_rpy\",10,dronerpy_cb);\n    ros::Subscriber car_position_sub = nh.subscribe<nav_msgs::Odometry>(\"current_relative_postwist\",10,relative_postwist_cb); //\u8f66\u7684pos+twist\n    ros::Subscriber plane_velocity_sub = nh.subscribe<geometry_msgs::TwistStamped>(\"mavros/local_position/velocity_local\", 10, plane_vel_cb); //twist\n\n    // \u3010\u53d1\u5e03\u3011\u98de\u673a\u59ff\u6001/\u62c9\u529b\u4fe1\u606f \u5750\u6807\u7cfb:NED\u7cfb\n    ros::Publisher controlstate_pub=nh.advertise<offb_posctl::controlstate>(\"ocp/control_state\",10);\n    ros::Publisher planeVel_pub=nh.advertise<geometry_msgs::Vector3>(\"filteredPlaneVel\",10);\n//  -------------------------------------\n    while (ros::ok())\n    {\n        ros::spinOnce();// to examine the queues of the callback functions once\n        if(currentupdateflag)\n        {\n            do_process();\n            if(resultofsolve==SUCCESSFUL_RETURN)\n            {\n                controlstate_msg.discrepointpersecond=discretizedpointpersecond;\n                controlstate_msg.inicounter=0;\n                controlstate_msg.arraylength=control.getNumPoints();\n                controlstate_msg.thrustarray.clear();\n                controlstate_msg.thetaarray.clear();\n                controlstate_msg.stateXarray.clear();\n                controlstate_msg.stateZarray.clear();\n                controlstate_msg.stateVXarray.clear();\n                controlstate_msg.stateVZarray.clear();\n                for(int i=0;i<control.getNumPoints();i++)\n                {\n//                    cout<<\"control.getNumPoints()-----!!!!:\"<<control.getNumPoints()<<\"  control.getMatrix(i)(0,0):\"<<control.getMatrix(i)(0,0)<<endl;\n                    controlstate_msg.thrustarray.push_back((float)control.getMatrix(i)(0,0));\n//                    controlstate_msg.thetaarray.push_back((float)control.getMatrix(i)(1,0));\n                    controlstate_msg.stateXarray.push_back((float)state.getMatrix(i)(0,0));\n                    controlstate_msg.stateZarray.push_back((float)state.getMatrix(i)(1,0));\n                    controlstate_msg.stateVXarray.push_back((float)state.getMatrix(i)(2,0));\n                    controlstate_msg.stateVZarray.push_back((float)state.getMatrix(i)(3,0));\n                    controlstate_msg.thetaarray.push_back((float)state.getMatrix(i)(5,0));\n\n                }\n//                ros::spinOnce();// update to newest state to match the state.\n//                controlstate_msg.inicounter=StateMatch();//match the state\n                controlstate_pub.publish(controlstate_msg);\n//                cout<<\"controlstate_msg.stateXarray[0]-----------fffffff:\"<<controlstate_msg.stateXarray[0]<<\"  state.getMatrix(i)(0,0):\"<<state.getMatrix(0)(0,0)<<endl;\n            }\n            currentupdateflag= false;\n            planeVel_pub.publish(filteredPlaneVelmsg);\n        }\n        rate.sleep();\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "c6d69844bce91d93f7ec7f30333349607bbca323", "size": 15263, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "offb_posctl/src/acado_lag_control.cpp", "max_stars_repo_name": "SensenLiu/aggrecup", "max_stars_repo_head_hexsha": "0c381ee259b388684205c1fa5fc41265a7e849b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "offb_posctl/src/acado_lag_control.cpp", "max_issues_repo_name": "SensenLiu/aggrecup", "max_issues_repo_head_hexsha": "0c381ee259b388684205c1fa5fc41265a7e849b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "offb_posctl/src/acado_lag_control.cpp", "max_forks_repo_name": "SensenLiu/aggrecup", "max_forks_repo_head_hexsha": "0c381ee259b388684205c1fa5fc41265a7e849b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.8190184049, "max_line_length": 212, "alphanum_fraction": 0.6738517985, "num_tokens": 4305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5309331150304449}}
{"text": "//////////////////////////////////////////////////////////////////////////////////\n// survival::models::exponential::scalar::function::log_unnormalized_pdf.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_DISTRIBUTION_SURVIVAL_MODELS_EXPONENTIAL_SCALAR_FUNCTION_INCLUDE_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_EXPONENTIAL_SCALAR_FUNCTION_INCLUDE_HPP_ER_2009\n\n#include <boost/statistics/detail/distribution/survival/models/exponential/scalar/function/log_unnormalized_pdf.hpp>\n\n#endif", "meta": {"hexsha": "f4decd699c68a7da6709bf49d4e7b1733dc2a7fa", "size": 924, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/function/include.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_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/function/include.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_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/function/include.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": 71.0769230769, "max_line_length": 116, "alphanum_fraction": 0.5670995671, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5308534510441532}}
{"text": "#ifndef ANGULAR_GAUSS_HPP\n#define ANGULAR_GAUSS_HPP\n\n#include <array>\n\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include \"types/types.hpp\"\n\nnamespace ublas = boost::numeric::ublas;\n\n// Angular Gaussian distribution\nclass AngularGauss {\n    Vector mean;\n    double mean_norm;\n\n    ublas::matrix<double> lambda;\n    double det_lambda;\n\n    // InvMatrix calculates inverse matrix for input_mat and stores it in\n    // inverse_mat\n    void InvMatrix(const ublas::matrix<double>& input_mat, ublas::matrix<double>& inverse_mat);\n    // Det calculates m's determinant\n    double Det(const ublas::matrix<double>& m) const;\n    // InnerProduct calculates inner product of x and y using lambda\n    double InnerProduct(const Vector& x, const Vector& y) const;\n\npublic:\n    // AngularGauss creates new Angular Gaussian distribution with mean using\n    // mean_vec and covariance using cov_mat\n    AngularGauss(const Vector& mean_vec, const ublas::matrix<double>& cov_mat);\n\n    // Mean returns mean vector for Angular Gaussian distribution\n    const Vector Mean(void) const;\n\n    // Calc calculates the Angular Gaussian PDF at u\n    double Calc(const CoordsOfPoint& u) const;\n};\n\n#endif // ANGULAR_GAUSS_HPP\n", "meta": {"hexsha": "3b55312b63bf65ebd974b6261dc85c55023a8c31", "size": 1198, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "server/distributions/angular_gauss.hpp", "max_stars_repo_name": "Bychin/uniformization-tool-on-sphere", "max_stars_repo_head_hexsha": "f5068d792aadb0dd8e694c348d068b6a8bcd8888", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-24T08:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T08:30:58.000Z", "max_issues_repo_path": "server/distributions/angular_gauss.hpp", "max_issues_repo_name": "Bychin/uniformization-tool-on-sphere", "max_issues_repo_head_hexsha": "f5068d792aadb0dd8e694c348d068b6a8bcd8888", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/distributions/angular_gauss.hpp", "max_forks_repo_name": "Bychin/uniformization-tool-on-sphere", "max_forks_repo_head_hexsha": "f5068d792aadb0dd8e694c348d068b6a8bcd8888", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2195121951, "max_line_length": 95, "alphanum_fraction": 0.7362270451, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5308534404964903}}
{"text": "//  ================================================================\n//  Created by Fei Shan on 03/05/19.\n//  ================================================================\n\n#pragma once\n\n//libraries\n#include <Eigen/Eigen>\n\nnamespace eig = Eigen;\n\nnamespace math{\n\n    eig::Matrix3f transformation_vector_to_matrix2d(const eig::Vector3f &twist);\n    eig::Matrix4f transformation_vector_to_matrix3d(const eig::Matrix<float, 6, 1>& twist);\n\n}\n", "meta": {"hexsha": "adbdc77739bf769c19bf5bbbb85282cb264a393a", "size": 443, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/transformation.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/transformation.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/transformation.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": 24.6111111111, "max_line_length": 91, "alphanum_fraction": 0.5079006772, "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5307783592921584}}
{"text": "#include \"pd/edge_length_constraint.h\"\n\n#include <Eigen/SparseCore>\n#include <array>\n\nnamespace pd {\n\nvoid edge_length_constraint_t::project_wi_SiT_AiT_Bi_pi(q_type const& q, Eigen::VectorXd& b) const\n{\n    using index_type         = decltype(indices().front());\n    index_type const vi      = indices().at(0);\n    index_type const vj      = indices().at(1);\n    Eigen::Vector3d const p1 = q.block(std::size_t{3u} * vi, 0, 3, 1);\n    Eigen::Vector3d const p2 = q.block(std::size_t{3u} * vj, 0, 3, 1);\n    auto const N             = q.rows() / 3;\n\n    Eigen::Vector3d const spring = p2 - p1;\n    auto const length            = spring.norm();\n    Eigen::Vector3d const n      = spring / length;\n    auto const delta             = scalar_type{0.5} * (length - d_);\n\n    // find the position p1 which results in ||p2 - p1|| = rest length\n    Eigen::Vector3d const pi1 = p1 + delta * n;\n    Eigen::Vector3d const pi2 = p2 - delta * n;\n\n    constexpr scalar_type half{0.5};\n    constexpr std::size_t three{3};\n    // the product wi * (Ai*Si)^T * (Ai*Si) only yields non-zero \n    // entries at coordinates [3vi, 3vi+3[ and [3vj, 3vj+3[.\n    // The matrices Ai,Bi are differential coordinate matrices \n    // which result in mean subtraction in every dimension.\n    // Thus, we subtract the mean in every dimension directly \n    // instead of performing the matrix multiplication.\n    b(three * vi + 0) += wi() * half * (pi1.x() - pi2.x());\n    b(three * vi + 1) += wi() * half * (pi1.y() - pi2.y());\n    b(three * vi + 2) += wi() * half * (pi1.z() - pi2.z());\n\n    b(three * vj + 0) += wi() * half * (pi2.x() - pi1.x());\n    b(three * vj + 1) += wi() * half * (pi2.y() - pi1.y());\n    b(three * vj + 2) += wi() * half * (pi2.z() - pi1.z());\n}\n\nstd::vector<Eigen::Triplet<edge_length_constraint_t::scalar_type>>\nedge_length_constraint_t::get_wi_SiT_AiT_Ai_Si(positions_type const& p, masses_type const& M) const\n{\n    int const vi = static_cast<int>(indices().at(0));\n    int const vj = static_cast<int>(indices().at(1));\n    auto const N = p.rows();\n\n    // We precompute the product (Ai*Si)^T * (Ai*Si) and find that \n    // there are only nonzero elements in the blocks \n    // [3vi:3vi+3, 3vi:3vi+3], [3vj:3vj+3, 3vi:3vi+3],\n    // [3vj:3vj+3, 3vi:3vi+3], [3vj:3vj+3, 3vj:3vj+3]\n    // Those blocks contain the differential coordinates of \n    // the mean subtraction differential coordinates Ai.\n    // We then multiply by wi as in wi * (Ai*Si)^T * (Ai*Si)\n    constexpr scalar_type half{0.5};\n    constexpr int three{3};\n    std::array<Eigen::Triplet<scalar_type>, 12u> triplets;\n    triplets[0] = {three * vi + 0, three * vi + 0, wi() * half};\n    triplets[2] = {three * vi + 1, three * vi + 1, wi() * half};\n    triplets[4] = {three * vi + 2, three * vi + 2, wi() * half};\n\n    triplets[1] = {three * vj + 0, three * vi + 0, -wi() * half};\n    triplets[3] = {three * vj + 1, three * vi + 1, -wi() * half};\n    triplets[5] = {three * vj + 2, three * vi + 2, -wi() * half};\n\n    triplets[6]  = {three * vi + 0, three * vj + 0, -wi() * half};\n    triplets[8]  = {three * vi + 1, three * vj + 1, -wi() * half};\n    triplets[10] = {three * vi + 2, three * vj + 2, -wi() * half};\n\n    triplets[7]  = {three * vj + 0, three * vj + 0, wi() * half};\n    triplets[9]  = {three * vj + 1, three * vj + 1, wi() * half};\n    triplets[11] = {three * vj + 2, three * vj + 2, wi() * half};\n\n    return std::vector<Eigen::Triplet<scalar_type>>{triplets.begin(), triplets.end()};\n}\n\n} // namespace pd\n", "meta": {"hexsha": "0b3767155c2c67956617630eb936cf2c1043864e", "size": 3483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pd/edge_length_constraint.cpp", "max_stars_repo_name": "Q-Minh/projective-dynamics", "max_stars_repo_head_hexsha": "02385b0255562cab476dbfaf5696d0b4eb2e833d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-20T03:24:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-30T07:16:49.000Z", "max_issues_repo_path": "src/pd/edge_length_constraint.cpp", "max_issues_repo_name": "Q-Minh/projective-dynamics", "max_issues_repo_head_hexsha": "02385b0255562cab476dbfaf5696d0b4eb2e833d", "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/pd/edge_length_constraint.cpp", "max_forks_repo_name": "Q-Minh/projective-dynamics", "max_forks_repo_head_hexsha": "02385b0255562cab476dbfaf5696d0b4eb2e833d", "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.5375, "max_line_length": 99, "alphanum_fraction": 0.5825437841, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.5307701245571167}}
{"text": "#include <iostream>\n#include <fstream>\n#include <Eigen/Eigen>\n//include the bie header files\n#include \"material.hh\"\n#include \"precomputed_kernel.hh\"\n#include \"bimat_interface.hh\"\n#include \"infinite_boundary.hh\"\n//include the fem header files\n#include \"mesh_Generated.hpp\"\n#include \"bcdof.hpp\"\n#include \"cal_ke.hpp\"\n#include \"cal_M.hpp\"\n#include \"cal_M_global_vec.hpp\"\n#include \"cal_fe_global_const_ke.hpp\"\n#include \"mapglobal.hpp\"\n#include \"Slip_Weakening.hpp\"\n#include \"cal_slip_sliprate.hpp\"\n#include \"time_advance.hpp\"\n#include \"BIE_correct.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\nint main() {\n    // Domain Size\n    double x_min = -5e3;\n    double x_max = 5e3;\n    double y_min = -1.0e3;\n    double y_max = 1.0e3;\n    int dim = 2.0;\n    double dx = 100;\n    double dy = 100;\n    int nx = (x_max-x_min)/dx;\n    int ny = (y_max-y_min)/dy;\n    MatrixXd Node = MatrixXd::Zero((nx+1)*(ny+1),2);\n    MatrixXd Element = MatrixXd::Zero(nx*ny,4);\n    VectorXd fault_surf_nodes = VectorXd::Zero((nx+1),1);\n    VectorXd fault_surf_nodes_new = VectorXd::Zero((nx+1),1);\n    VectorXd BIE_top_surf_nodes = VectorXd::Zero((nx+1),1);\n    VectorXd BIE_bot_surf_nodes = VectorXd::Zero((nx+1),1);\n    // Mesh\n    mesh_Generated(x_min,x_max,y_min,y_max,dx,dy,nx,ny,Node, Element, fault_surf_nodes, fault_surf_nodes_new, BIE_top_surf_nodes, BIE_bot_surf_nodes);\n    int n_nodes = Node.rows();\n    int n_el = Element.rows();\n    int Ndofn = 2;\n    int Nnel = Element.cols();\n    nx = fault_surf_nodes.size()-1;\n    // Material\n    double density = 2670.0;\n    double v_s =3.464e3;\n    double v_p = 6.0e3;\n    double G= pow(v_s,2)*density;\n    double Lambda = pow(v_p,2)*density-2.0*G;\n    double E  = G*(3.0*Lambda+2.0*G)/(Lambda+G);\n    double nu = Lambda/(2.0*(Lambda+G));\n    // Time\n    double alpha = 0.4;\n    double dt = alpha*dx/v_p;\n    // Reyleigh Damping\n    double beta =0.1;\n    double q = beta*dt;\n    double time_run = 6.0;\n    int numt = time_run/dt;\n    //numt = 3;\n    VectorXd time = dt*VectorXd::LinSpaced(numt,1,numt);\n    // Slip weakening friction parameters\n    double Dc = 0.2;\n    double mu_d= 0.5;\n    double mu_s = 0.6;\n    // Intialization\n    // disp velocity current and next time step (new)\n    VectorXd u_n = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd v_n = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd u_new = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd v_new = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd a_n = VectorXd::Zero(n_nodes*Ndofn,1);\n    // slip and slip-rate\n    VectorXd delt_u_n = VectorXd::Zero(Ndofn*(nx+1),1);\n    VectorXd delt_v_n = VectorXd::Zero(Ndofn*(nx+1),1);\n    // Stress on the fault T_0 = intial stress , T = sticking force, T_c= stress critical goes into F_global\n    VectorXd T_0 = VectorXd::Zero(Ndofn*(nx+1),1);\n    VectorXd T = VectorXd::Zero(Ndofn*(nx+1),1);\n    VectorXd T_c = VectorXd::Zero(Ndofn*(nx+1),1);\n    VectorXd tau_s = VectorXd::Zero(nx+1,1);\n    VectorXd F_ext_global = VectorXd::Zero(n_nodes*Ndofn,1);\n    // Setting intial stress on the fault\n    for (int i=0; i<T_0.size()/2; i++)\n    {\n        T_0(2*i+1) = -50.0e6;\n    }\n    VectorXd x = VectorXd::LinSpaced(nx+1,x_min,x_max);\n    for (int i=0 ; i<nx+1; i++)\n    {\n        if ((x(i)<=(x_max+x_min)/2+0.8e3)&&(x(i)>=(x_max+x_min)/2-0.8e3))\n        {\n            T_0(2*i) = 31.0e6;\n        }\n        else\n        {\n            T_0(2*i) = 27.5e6;\n            \n        }\n    }\n    // Get the index degree of freedome for each element\n    VectorXd index_el = VectorXd::Zero(Ndofn*Nnel,1);\n    MatrixXd index_store = MatrixXd::Zero(Nnel*Ndofn,n_el);\n    for (int i=0;i<n_el;i++)\n    {\n        bcdof(Element.row(i),dim,index_el);\n        index_store.col(i) = index_el;\n    }\n    VectorXd top_surf_index = VectorXd::Zero(Ndofn*(nx+1),1);\n    VectorXd bot_surf_index = VectorXd::Zero(Ndofn*(nx+1),1);\n    VectorXd BIE_top_surf_index = VectorXd::Zero(Ndofn*(nx+1),1);\n    VectorXd BIE_bot_surf_index = VectorXd::Zero(Ndofn*(nx+1),1);\n    bcdof(fault_surf_nodes,dim,top_surf_index);\n    bcdof(fault_surf_nodes_new,dim,bot_surf_index);\n    bcdof(BIE_top_surf_nodes,dim,BIE_top_surf_index);\n    bcdof(BIE_bot_surf_nodes,dim,BIE_bot_surf_index);\n    // Calculating the Global Mass Vector (lumped mass)\n    // Element mass\n    double M=density*dx*dy*1.0;\n    VectorXd M_el_vec = M/4*VectorXd::Ones(Nnel*Ndofn,1);\n    VectorXd M_global_vec=VectorXd::Zero(n_nodes*Ndofn,1);\n    cal_M_global_vec(Node, Element, density, index_store, Ndofn, M_global_vec);\n//    for (int i=0 ; i<n_el;i++)\n//    {\n//        index_el = index_store.col(i);\n//        mapglobal(index_el,M_global_vec,M_el_vec);\n//    }\n    // Element matrix\n    MatrixXd ke = MatrixXd::Zero(8,8);\n    MatrixXd coord = MatrixXd::Zero(4,2);\n    VectorXd Element_0= Element.row(0);\n    coord.row(0) = Node.row(Element_0(0));\n    coord.row(1) = Node.row(Element_0(1));\n    coord.row(2) = Node.row(Element_0(2));\n    coord.row(3) = Node.row(Element_0(3));\n    cal_ke (coord,E,nu,ke);\n    // BIE part initiation\n    // Setting up the material property for the BIE code\n    Material BIE_top_mat = Material(E,nu,density);\n    Material BIE_bot_mat = Material(E,nu,density);\n    double length = x_max-x_min;\n    // infinte bc BIE call infinite_boundary.cc\n    PrecomputedKernel h11(\"kernels/nu_.25_h11.dat\");\n    PrecomputedKernel h12(\"kernels/nu_.25_k12.dat\");\n    PrecomputedKernel h22(\"kernels/nu_.25_h22.dat\");\n    InfiniteBoundary BIE_inf_top(length,nx+1,1.0,&BIE_top_mat,&h11,&h12,&h22);\n    InfiniteBoundary BIE_inf_bot(length,nx+1,-1.0,&BIE_bot_mat,&h11,&h12,&h22);\n    // BIE setting time step\n    BIE_inf_top.setTimeStep(dt);\n    BIE_inf_bot.setTimeStep(dt);\n    // BIE initialization\n    BIE_inf_top.init();\n    BIE_inf_bot.init();\n\n    //BIE_initiation(E, nu, density, x_max, x_min, nx, dt);\n    printf(\"ready to start\\n\");\n    // Output\n    ofstream slip(\"slip.bin\",ios::binary);\n    slip.close();\n    ofstream slip_rate(\"slip_rate.bin\",ios::binary);\n    slip_rate.close();\n    ofstream shear(\"shear.bin\",ios::binary);\n    shear.close();\n    std::ofstream fe(\"results/fe.txt\");\n\n    \n    // Main time loop\n    for (int j=0;j<numt;j++)\n    {\n        // Compute the global internal force\n        VectorXd fe_global= VectorXd::Zero(n_nodes*Ndofn,1);\n        cal_fe_global_const_ke(n_nodes, n_el, index_store, q, u_n, v_n, Ndofn, ke, fe_global);\n        // Friction subroutine\n        VectorXd F_fault = VectorXd::Zero(Ndofn*(nx+1),1);\n        Slip_Weakening(M_global_vec, top_surf_index, bot_surf_index, fe_global, dt, dx, dy, nx, delt_v_n, delt_u_n, T_0, tau_s, mu_s, mu_d, Dc, Ndofn, M, F_fault, T_c);\n        // Calculate the global force vector\n        // Adding contribution of the fault force to the global force vector F_total\n        VectorXd F_total = F_ext_global-fe_global;\n        mapglobal(top_surf_index,F_total,-F_fault);\n        mapglobal(bot_surf_index,F_total,F_fault);\n        // Central Difference Time integration\n        time_advance(u_n, v_n, F_total, M_global_vec, dt);\n        // Get the slip and slip rate\n        cal_slip_slip_rate(u_n, v_n, top_surf_index, bot_surf_index, Ndofn, nx, delt_u_n, delt_v_n);\n        // Correct the BIE surf nodes solutions from FEM with the BIE solution\n        BIE_correct(BIE_top_surf_index, BIE_bot_surf_index, fe_global, Ndofn, nx, dx, BIE_inf_top, BIE_inf_bot, u_n, v_n);\n        //ofstream file;\n        slip.open(\"slip.bin\",ios::binary | ios::app);\n        slip.write((char*)(delt_u_n.data()),delt_u_n.size()*sizeof(double));\n        slip.close();\n        slip_rate.open(\"slip_rate.bin\",ios::binary | ios::app);\n        slip_rate.write((char*)(delt_v_n.data()),delt_v_n.size()*sizeof(double));\n        slip_rate.close();\n        shear.open(\"shear.bin\",ios::binary | ios::app);\n        shear.write((char*)(T_c.data()),T_c.size()*sizeof(double));\n        shear.close();\n        printf(\"Simulation time = %f\\n\",time(j));\n    }\n    return 0;\n}\n", "meta": {"hexsha": "f13d1c9c65e9b04bc8d3675e22b07a5d95f812a6", "size": 7884, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/test_simulation/main_v1.cc", "max_stars_repo_name": "XiaoMaResearch/hybrid_FEM_SBI", "max_stars_repo_head_hexsha": "32fcf1e21a7f78907e01585d892777c11ff1c21e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T19:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:12:57.000Z", "max_issues_repo_path": "tests/test_simulation/main_v1.cc", "max_issues_repo_name": "XiaoMaResearch/hybrid_FEM_SBI", "max_issues_repo_head_hexsha": "32fcf1e21a7f78907e01585d892777c11ff1c21e", "max_issues_repo_licenses": ["MIT"], "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_simulation/main_v1.cc", "max_forks_repo_name": "XiaoMaResearch/hybrid_FEM_SBI", "max_forks_repo_head_hexsha": "32fcf1e21a7f78907e01585d892777c11ff1c21e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-07T07:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T07:23:58.000Z", "avg_line_length": 38.4585365854, "max_line_length": 168, "alphanum_fraction": 0.6508117707, "num_tokens": 2472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.61878043374385, "lm_q1q2_score": 0.5307701200574166}}
{"text": "// Copyright (c) 2020 Chris Richardson\n// FEniCS Project\n// SPDX-License-Identifier:    MIT\n\n#include \"crouzeix-raviart.h\"\n#include \"core/element-families.h\"\n#include \"core/polyset.h\"\n#include \"core/quadrature.h\"\n#include <Eigen/Dense>\n#include <numeric>\n#include <vector>\n\nusing namespace basix;\n\n//-----------------------------------------------------------------------------\nFiniteElement basix::create_cr(cell::type celltype, int degree)\n{\n  if (degree != 1)\n    throw std::runtime_error(\"Degree must be 1 for Crouzeix-Raviart\");\n\n  const int tdim = cell::topological_dimension(celltype);\n  if (tdim < 2)\n    throw std::runtime_error(\"Tdim must be 2 or 3 for Crouzeix-Raviart\");\n\n  const std::vector<std::vector<std::vector<int>>> topology\n      = cell::topology(celltype);\n  const std::vector<std::vector<int>> facet_topology = topology[tdim - 1];\n  const Eigen::ArrayXXd geometry = cell::geometry(celltype);\n\n  const int ndofs = facet_topology.size();\n  Eigen::ArrayXXd pts = Eigen::ArrayXXd::Zero(ndofs, tdim);\n\n  // Compute facet midpoints\n  int c = 0;\n  for (const std::vector<int>& f : facet_topology)\n  {\n    for (int i : f)\n      pts.row(c) += geometry.row(i);\n    pts.row(c) /= static_cast<double>(f.size());\n    ++c;\n  }\n\n  Eigen::MatrixXd dual = polyset::tabulate(celltype, 1, 0, pts)[0];\n  int perm_count = tdim == 2 ? 3 : 14;\n  std::vector<Eigen::MatrixXd> base_permutations(\n      perm_count, Eigen::MatrixXd::Identity(ndofs, ndofs));\n\n  const Eigen::MatrixXd coeffs = compute_expansion_coefficients(\n      Eigen::MatrixXd::Identity(ndofs, ndofs), dual);\n\n  // Crouzeix-Raviart has one dof on each entity of tdim-1.\n  std::vector<std::vector<int>> entity_dofs(topology.size());\n  entity_dofs[0].resize(topology[0].size(), 0);\n  entity_dofs[1].resize(topology[1].size(), (tdim == 2) ? 1 : 0);\n  entity_dofs[2].resize(topology[2].size(), (tdim == 3) ? 1 : 0);\n  if (tdim == 3)\n    entity_dofs[3] = {0};\n\n  return FiniteElement(element::family::CR, celltype, 1, {1}, coeffs,\n                       entity_dofs, base_permutations, {});\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "517dfcc6e6555d220940464bc836b68afdf5ce80", "size": 2132, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/elements/crouzeix-raviart.cpp", "max_stars_repo_name": "draenog/basix", "max_stars_repo_head_hexsha": "172720a7ecf2caaf4619a4718fa3f3e1cbe0c1e4", "max_stars_repo_licenses": ["MIT"], "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/elements/crouzeix-raviart.cpp", "max_issues_repo_name": "draenog/basix", "max_issues_repo_head_hexsha": "172720a7ecf2caaf4619a4718fa3f3e1cbe0c1e4", "max_issues_repo_licenses": ["MIT"], "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/elements/crouzeix-raviart.cpp", "max_forks_repo_name": "draenog/basix", "max_forks_repo_head_hexsha": "172720a7ecf2caaf4619a4718fa3f3e1cbe0c1e4", "max_forks_repo_licenses": ["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.8412698413, "max_line_length": 79, "alphanum_fraction": 0.6191369606, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5307701155577165}}
{"text": "#pragma once\n#include <boost/numeric/ublas/matrix.hpp>\n#include <random>\n\n// fills matrix with pseudorandomly generated elements\ntemplate<class Matrix, class Generator>\nvoid randomize_matrix(Generator&& r, Matrix& m) {\n  std::uniform_int_distribution<typename Matrix::value_type> dist;\n  for(size_t i = 0; i < m.size1(); i++) {\n    for(size_t j = 0; j < m.size2(); j++) {\n      m(i, j) = dist(r);\n    }\n  }\n}\n", "meta": {"hexsha": "57318b517f712259cb2706aa02640687aea2a8c1", "size": 409, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/src/util/randomize_matrix.hpp", "max_stars_repo_name": "nikikilbertus/blind-justice", "max_stars_repo_head_hexsha": "2344609e55a2af20396ec042627ffed368e01e56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-06-11T21:12:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T18:49:16.000Z", "max_issues_repo_path": "c++/src/util/randomize_matrix.hpp", "max_issues_repo_name": "nikikilbertus/blind-justice", "max_issues_repo_head_hexsha": "2344609e55a2af20396ec042627ffed368e01e56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-17T14:28:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T14:28:11.000Z", "max_forks_repo_path": "c++/src/util/randomize_matrix.hpp", "max_forks_repo_name": "nikikilbertus/blind-justice", "max_forks_repo_head_hexsha": "2344609e55a2af20396ec042627ffed368e01e56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-06T08:46:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T15:39:26.000Z", "avg_line_length": 27.2666666667, "max_line_length": 66, "alphanum_fraction": 0.6674816626, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604181, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5307671657278147}}
{"text": "#include \"mtf/SSM/SL3.h\"\r\n#include \"mtf/SSM/HomographyEstimator.h\"\r\n#include \"mtf/Utilities/warpUtils.h\"\r\n#include \"mtf/Utilities/miscUtils.h\"\r\n#include \"mtf/Utilities/excpUtils.h\"\r\n\r\n#include <unsupported/Eigen/MatrixFunctions>\r\n#include \"opencv2/calib3d/calib3d.hpp\"\r\n#include <boost/random/random_device.hpp>\r\n#include <boost/random/seed_seq.hpp>\r\n\r\n#define VALIDATE_SL3_WARP(warp) \\\r\n\tassert(warp.determinant() == 1.0);\r\n\r\n#define SL3_NORMALIZED_BASIS 0\r\n#define SL3_ITERATIVE_SAMPLE_MEAN 1\r\n#define SL3_SAMPLE_MEAN_MAX_ITERS 10\r\n#define SL3_SAMPLE_MEAN_EPS 1e-4\r\n#define SL3_DEBUG_MODE 0\r\n\r\n#ifndef SL3_MAX_VALID_VAL\r\n#define SL3_MAX_VALID_VAL 1e10\r\n#endif\r\n#define is_unbounded(eig_mat) (eig_mat.array().cwiseAbs().eval() > SL3_MAX_VALID_VAL).any()\r\n\r\n_MTF_BEGIN_NAMESPACE\r\n\r\nSL3Params::SL3Params(const SSMParams *ssm_params,\r\nbool _normalized_init, bool _iterative_sample_mean,\r\nint _sample_mean_max_iters, double _sample_mean_eps,\r\nbool _debug_mode) :\r\nSSMParams(ssm_params),\r\nnormalized_init(_normalized_init),\r\niterative_sample_mean(_iterative_sample_mean),\r\nsample_mean_max_iters(_sample_mean_max_iters),\r\nsample_mean_eps(_sample_mean_eps),\r\ndebug_mode(_debug_mode){}\r\n\r\n//! copy/default constructor\r\nSL3Params::SL3Params(const SL3Params *params) :\r\nSSMParams(params),\r\nnormalized_init(SL3_NORMALIZED_BASIS),\r\niterative_sample_mean(SL3_ITERATIVE_SAMPLE_MEAN),\r\nsample_mean_max_iters(SL3_SAMPLE_MEAN_MAX_ITERS),\r\nsample_mean_eps(SL3_SAMPLE_MEAN_EPS),\r\ndebug_mode(SL3_DEBUG_MODE){\r\n\tif(params){\r\n\t\tnormalized_init = params->normalized_init;\r\n\t\titerative_sample_mean = params->iterative_sample_mean;\r\n\t\tsample_mean_max_iters = params->sample_mean_max_iters;\r\n\t\tsample_mean_eps = params->sample_mean_eps;\r\n\t\tdebug_mode = params->debug_mode;\r\n\t}\r\n}\r\n\r\nSL3::SL3(\r\n\tconst ParamType *_params) :\r\n\tProjectiveBase(_params), params(_params){\r\n\r\n\tprintf(\"\\n\");\r\n\tprintf(\"Using SL3 SSM with:\\n\");\r\n\tprintf(\"resx: %d\\n\", resx);\r\n\tprintf(\"resy: %d\\n\", resy);\r\n\tprintf(\"normalized_init: %d\\n\", params.normalized_init);\r\n\tprintf(\"iterative_sample_mean: %d\\n\", params.iterative_sample_mean);\r\n\tprintf(\"sample_mean_max_iters: %d\\n\", params.sample_mean_max_iters);\r\n\tprintf(\"sample_mean_eps: %f\\n\", params.sample_mean_eps);\r\n\tprintf(\"debug_mode: %d\\n\", params.debug_mode);\r\n\r\n\r\n\tname = \"sl3\";\r\n\tstate_size = 8;\r\n\tcurr_state.resize(state_size);\r\n\r\n\tlog_fname = log_fname;\r\n\r\n\tlie_alg_mat = Matrix3d::Zero();\r\n\twarp_mat = Matrix3d::Identity();\r\n\r\n\tlieAlgBasis[0] <<\r\n\t\t1, 0, 0,\r\n\t\t0, -1, 0,\r\n\t\t0, 0, 0;\r\n\tlieAlgBasis[1] <<\r\n\t\t0, 0, 0,\r\n\t\t0, -1, 0,\r\n\t\t0, 0, 1;\r\n\tlieAlgBasis[2] <<\r\n\t\t0, -1, 0,\r\n\t\t1, 0, 0,\r\n\t\t0, 0, 0;\r\n\tlieAlgBasis[3] <<\r\n\t\t0, 1, 0,\r\n\t\t1, 0, 0,\r\n\t\t0, 0, 0;\r\n\tlieAlgBasis[4] <<\r\n\t\t0, 0, 1,\r\n\t\t0, 0, 0,\r\n\t\t0, 0, 0;\r\n\tlieAlgBasis[5] <<\r\n\t\t0, 0, 0,\r\n\t\t0, 0, 1,\r\n\t\t0, 0, 0;\r\n\tlieAlgBasis[6] <<\r\n\t\t0, 0, 0,\r\n\t\t0, 0, 0,\r\n\t\t1, 0, 0;\r\n\tlieAlgBasis[7] <<\r\n\t\t0, 0, 0,\r\n\t\t0, 0, 0,\r\n\t\t0, 1, 0;\r\n\r\n\tutils::getNormUnitSquarePts(norm_pts, norm_corners, resx, resy,\r\n\t\t-static_cast<double>(resx) / 2.0, -static_cast<double>(resy) / 2.0,\r\n\t\tstatic_cast<double>(resx) / 2.0, static_cast<double>(resy) / 2.0);\r\n\tutils::homogenize(norm_corners, norm_corners_hm);\r\n\tutils::homogenize(norm_pts, norm_pts_hm);\r\n\r\n\tinit_corners = norm_corners;\r\n\tinit_corners_hm = norm_corners_hm;\r\n\tinit_pts = norm_pts;\r\n\tinit_pts_hm = norm_pts_hm;\r\n\r\n\tif(params.debug_mode){\r\n#ifdef _WIN32\r\n\t\tFILE *fid;\r\n\t\terrno_t err;\r\n\t\tif((err = fopen_s(&fid, log_fname, \"r\")) != 0) {\r\n\t\t\tthrow utils::InvalidArgument(cv_format(\"SL3 :: Log file %s could not be opened successfully : %s\\n\",\r\n\t\t\t\tlog_fname, strerror(err)));\r\n\t\t}\r\n#else\r\n\t\tFILE *fid = fopen(log_fname, \"w\");\r\n\t\tif(!fid){\r\n\t\t\tthrow utils::InvalidArgument(cv_format(\"SL3 :: Log file %s could not be opened successfully\\n\", log_fname));\r\n\t\t}\t\t\r\n#endif\t\r\n\t\tfclose(fid);\r\n\t}\r\n}\r\n\r\nvoid SL3::setState(const VectorXd &ssm_state){\r\n\tvalidate_ssm_state(ssm_state);\r\n\t//utils::printMatrix(ssm_state.transpose(), \" SL3::setState :: ssm_state\");\r\n\tif(!ssm_state.allFinite()){\r\n\t\tutils::printMatrix(ssm_state.transpose(), \"ssm_state\");\r\n\t\tthrow mtf::utils::InvalidTrackerState(\"SL3::setState::Invalid state provided\");\r\n\t}\r\n\tcurr_state = ssm_state;\r\n\tgetWarpFromState(curr_warp, curr_state);\r\n\tcurr_pts_hm.noalias() = curr_warp * init_pts_hm;\r\n\tcurr_corners_hm.noalias() = curr_warp * init_corners_hm;\r\n\tutils::dehomogenize(curr_pts_hm, curr_pts);\r\n\tutils::dehomogenize(curr_corners_hm, curr_corners);\r\n\tif(params.debug_mode){\r\n\t\tutils::printMatrixToFile(curr_warp, \"setState::curr_warp\", log_fname);\r\n\t\tutils::printMatrixToFile(curr_corners, \"setState::curr_corners\", log_fname);\r\n\t}\r\n}\r\n\r\nvoid SL3::setCorners(const CornersT& corners){\r\n\tif(!corners.allFinite() || is_unbounded(corners)){\r\n\t\tutils::printMatrix(corners, \"corners\");\r\n\t\tthrow mtf::utils::InvalidTrackerState(\"SL3::setCorners::Invalid corners provided\");\r\n\t}\r\n\tcurr_corners = corners;\r\n\tcurr_warp = utils::computeHomographyDLT(norm_corners, curr_corners);\r\n\tdouble warp_det = curr_warp.determinant();\r\n\tif(!warp_mat.allFinite() || is_unbounded(warp_mat) || warp_det == 0 || std::isnan(warp_det) || std::isinf(warp_det)){\r\n\t\tprintf(\"SL3::Cannot set SSM to the provided corners as the corresponding warp matrix is invalid: \\n\");\r\n\t\tutils::printMatrix(corners, \"corners\");\r\n\t\tutils::printMatrix(curr_warp, \"warp\");\r\n\t\tutils::printScalar(warp_det, \"warp_det\");\r\n\t\tthrow mtf::utils::InvalidTrackerState(\"SL3::setCorners :: Cannot set SSM to the provided points as the corresponding warp matrix is invalid\");\r\n\t}\r\n\tutils::homogenize(curr_corners, curr_corners_hm);\r\n\tcurr_pts_hm = curr_warp * norm_pts_hm;\r\n\tutils::dehomogenize(curr_pts_hm, curr_pts);\r\n\tcurr_warp = curr_warp / cbrt(warp_det);\r\n\tif(params.normalized_init){\r\n\t\tgetStateFromWarp(curr_state, curr_warp);\r\n\t} else{\r\n\t\tinit_corners = curr_corners;\r\n\t\tinit_corners_hm = curr_corners_hm;\r\n\t\tinit_pts = curr_pts;\r\n\t\tinit_pts_hm = curr_pts_hm;\r\n\t\tcurr_warp = Matrix3d::Identity();\r\n\t\tcurr_state.fill(0);\r\n\t}\r\n\tif(params.debug_mode){\r\n\t\tutils::printMatrixToFile(init_pts, \"setCorners::init_pts\", log_fname);\r\n\t\tutils::printMatrixToFile(init_corners, \"setCorners::init_corners\", log_fname);\r\n\t\tutils::printMatrixToFile(curr_warp, \"setCorners::curr_warp\", log_fname);\r\n\t}\r\n}\r\n\r\nvoid SL3::compositionalUpdate(const VectorXd& state_update){\r\n\tvalidate_ssm_state(state_update);\r\n\r\n\tgetWarpFromState(warp_update_mat, state_update);\r\n\tcurr_warp = curr_warp * warp_update_mat;\r\n\tif(!curr_warp.allFinite() || is_unbounded(curr_warp)){\r\n\t\tutils::printMatrix(state_update.transpose(), \"state_update\");\r\n\t\tutils::printMatrix(curr_warp, \"curr_warp\");\r\n\t\tutils::printMatrix(warp_update_mat, \"warp_update_mat\");\r\n\t\tthrow mtf::utils::InvalidTrackerState(\"SL3::compositionalUpdate::Invalid state update provided\");\r\n\t\t\r\n\t}\r\n\tcurr_pts_hm.noalias() = curr_warp * init_pts_hm;\r\n\tcurr_corners_hm.noalias() = curr_warp * init_corners_hm;\r\n\r\n\tutils::dehomogenize(curr_pts_hm, curr_pts);\r\n\tutils::dehomogenize(curr_corners_hm, curr_corners);\r\n\r\n\tgetStateFromWarp(curr_state, curr_warp);\r\n\r\n}\r\n\r\nvoid SL3::getWarpFromState(Matrix3d &warp_mat,\r\n\tconst VectorXd& ssm_state){\r\n\tvalidate_ssm_state(ssm_state);\r\n\tassert(ssm_state.size() == 8);\r\n\tif(!ssm_state.allFinite() || is_unbounded(ssm_state)){\r\n\t\tutils::printMatrix(ssm_state.transpose(), \"ssm_state\");\r\n\t\tthrow mtf::utils::InvalidTrackerState(\"SL3::getWarpFromState::Invalid state provided\");\r\n\t}\r\n\tgetLieAlgMatFromState(lie_alg_mat, ssm_state);\r\n\tif(!lie_alg_mat.allFinite() || is_unbounded(lie_alg_mat)){\r\n\t\tutils::printMatrix(ssm_state.transpose(), \"ssm_state\");\r\n\t\tutils::printMatrix(lie_alg_mat, \"lie_alg_mat\");\r\n\t\tthrow mtf::utils::InvalidTrackerState(\"SL3::getWarpFromState::Invalid sl3 matrix corresponds to the given state\");\r\n\t}\r\n\twarp_mat = lie_alg_mat.exp();\r\n}\r\n\r\nvoid SL3::getStateFromWarp(VectorXd &state_vec,\r\n\tconst Matrix3d& warp_mat){\r\n\tvalidate_ssm_state(state_vec);\r\n\tdouble warp_det = warp_mat.determinant();\r\n\tif(!warp_mat.allFinite() || is_unbounded(warp_mat) || warp_det == 0 || std::isnan(warp_det) || std::isinf(warp_det)){\r\n\t\tutils::printMatrix(warp_mat, \"warp_mat\");\r\n\t\tutils::printScalar(warp_det, \"warp_det\");\r\n\t\tthrow mtf::utils::InvalidTrackerState(\"SL3::getStateFromWarp :: Invalid warp matrix provided\");\r\n\t}\r\n\tMatrix3d norm_warp_mat = warp_mat / cbrt(warp_det);\r\n\tif(!norm_warp_mat.allFinite() || is_unbounded(norm_warp_mat)){\r\n\t\tutils::printMatrix(warp_mat, \"warp_mat\");\r\n\t\tutils::printScalar(warp_det, \"warp_det\");\r\n\t\tutils::printMatrix(norm_warp_mat, \"norm_warp_mat\");\r\n\t\tthrow mtf::utils::InvalidTrackerState(\"SL3::getStateFromWarp :: Invalid normalized warp matrix found\");\r\n\t}\r\n\tlie_alg_mat = norm_warp_mat.log();\r\n\tgetStateFromLieAlgMat(state_vec, lie_alg_mat);\r\n}\r\n\r\nvoid SL3::getLieAlgMatFromState(Matrix3d& lie_alg_mat,\r\n\tconst VectorXd& ssm_state){\r\n\tvalidate_ssm_state(ssm_state);\r\n\tassert(ssm_state.size() == state_size);\r\n\tlie_alg_mat(0, 0) = ssm_state(0);\r\n\tlie_alg_mat(0, 1) = ssm_state(3) - ssm_state(2);\r\n\tlie_alg_mat(0, 2) = ssm_state(4);\r\n\tlie_alg_mat(1, 0) = ssm_state(3) + ssm_state(2);\r\n\tlie_alg_mat(1, 1) = -ssm_state(1) - ssm_state(0);\r\n\tlie_alg_mat(1, 2) = ssm_state(5);\r\n\tlie_alg_mat(2, 0) = ssm_state(6);\r\n\tlie_alg_mat(2, 1) = ssm_state(7);\r\n\tlie_alg_mat(2, 2) = ssm_state(1);\r\n}\r\n\r\nvoid SL3::getStateFromLieAlgMat(VectorXd &ssm_state,\r\n\tconst Matrix3d& lie_alg_mat){\r\n\tvalidate_ssm_state(ssm_state);\r\n\tssm_state(0) = lie_alg_mat(0, 0);\r\n\tssm_state(1) = -lie_alg_mat(1, 1) - ssm_state(0);\r\n\tssm_state(2) = (lie_alg_mat(1, 0) - lie_alg_mat(0, 1)) / 2.0;\r\n\tssm_state(3) = (lie_alg_mat(1, 0) + lie_alg_mat(0, 1)) / 2.0;\r\n\tssm_state(4) = lie_alg_mat(0, 2);\r\n\tssm_state(5) = lie_alg_mat(1, 2);\r\n\tssm_state(6) = lie_alg_mat(2, 0);\r\n\tssm_state(7) = lie_alg_mat(2, 1);\r\n\tif(params.debug_mode){\r\n\t\tutils::printMatrixToFile(ssm_state.transpose(), \"getStateFromLieAlgMat :: ssm_state\", log_fname);\r\n\t\tutils::printMatrixToFile(lie_alg_mat, \"getStateFromLieAlgMat :: lie_alg_mat\", log_fname);\r\n\t}\r\n}\r\n\r\nvoid SL3::initializeSampler(const VectorXd &state_sigma, \r\n\tconst VectorXd &state_mean){\r\n\tif(state_sigma.size() != 8){\r\n\t\tthrow utils::InvalidArgument(\r\n\t\t\tcv::format(\"SL3::initializeSampler :: SSM sigma has invalid size: %d\\n\",\r\n\t\t\tstate_sigma.size()));\r\n\t}\r\n\tcovariance_mat = state_sigma.asDiagonal();\r\n\tprintf(\"Using SL3 sampler with sigma:\\n\");\r\n\tutils::printMatrix(state_sigma.transpose(), nullptr, \"%e\");\r\n\r\n\tstate_perturbation.resize(state_size);\r\n\trand_gen.resize(1);\r\n\trand_dist.resize(1);\r\n\r\n\tboost::random_device r;\r\n\tboost::random::seed_seq seed{ r(), r(), r(), r(), r(), r(), r(), r() };\r\n\trand_gen[0] = SampleGenT(seed);\r\n\trand_dist[0] = SampleDistT(0, 1);\r\n\r\n\tif(params.debug_mode){\r\n\t\tutils::printMatrixToFile(covariance_mat, \"covariance_mat\", log_fname);\r\n\t}\r\n\tis_initialized.sampler = true;\r\n}\r\n\r\nvoid SL3::setSampler(const VectorXd &state_sigma,\r\n\tconst VectorXd &state_mean){\r\n\tassert(state_sigma.size() == state_size);\r\n\tcovariance_mat = state_sigma.asDiagonal();\r\n}\r\n\r\nVectorXd SL3::getSamplerSigma(){\r\n\tVectorXd sampler_sigma = covariance_mat.diagonal();\r\n\treturn sampler_sigma;\r\n}\r\n\r\nvoid SL3::generatePerturbation(VectorXd &perturbation){\r\n\tassert(perturbation.size() == state_size);\r\n\tVector8d rand_vec;\r\n\tfor(unsigned int state_id = 0; state_id < 8; state_id++){\r\n\t\trand_vec(state_id) = rand_dist[0](rand_gen[0]);\r\n\t}\r\n\tperturbation = covariance_mat*rand_vec;\r\n}\r\n\r\n// use Random Walk model to generate perturbed sample\r\nvoid SL3::compositionalRandomWalk(VectorXd &perturbed_state,\r\n\tconst VectorXd &base_state){\r\n\tgeneratePerturbation(state_perturbation);\r\n\tperturbed_state = base_state + state_perturbation;\r\n}\r\n// use first order Auto Regressive model to generate perturbed sample\r\n//void SL3::compositionalAutoRegression1(VectorXd &perturbed_state, VectorXd &perturbed_ar,\r\n//\tconst VectorXd &base_state, const VectorXd &base_ar, double a){\r\n//\tProjWarpT warp_perturbation, sl3_perturbation, sl3_base_ar, base_warp;\r\n//\tgeneratePerturbation(state_perturbation);\r\n//\tgetLieAlgMatFromState(warp_perturbation, state_perturbation);\r\n//\tgetLieAlgMatFromState(sl3_base_ar, base_ar);\r\n//\tgetWarpFromState(base_warp, base_state);\r\n//\tsl3_perturbation = warp_perturbation + a*sl3_base_ar;\r\n//\tProjWarpT SL3_perturbation = sl3_perturbation.exp();\r\n//\tProjWarpT perturbed_warp = base_warp*SL3_perturbation;\r\n//\tProjWarpT base_warp_inv = base_warp.inverse();\r\n//\tif(params.debug_mode){\r\n//\t\tutils::printMatrixToFile(state_perturbation.transpose(), \"rand_perturbation\", log_fname);\r\n//\t\tutils::printMatrixToFile(warp_perturbation.transpose(), \"warp_perturbation\", log_fname);\r\n//\t\tutils::printMatrixToFile(sl3_perturbation, \"sl3_perturbation\", log_fname);\r\n//\t\tutils::printMatrixToFile(base_ar.transpose(), \"base_ar\", log_fname);\r\n//\t\tutils::printMatrixToFile(sl3_base_ar, \"sl3_base_ar\", log_fname);\r\n//\t\tutils::printMatrixToFile(SL3_perturbation, \"SL3_perturbation\", log_fname);\r\n//\t\tutils::printMatrixToFile(base_warp, \"base_warp\", log_fname);\r\n//\t\tutils::printMatrixToFile(base_warp_inv, \"base_warp_inv\", log_fname);\r\n//\t\tutils::printMatrixToFile(perturbed_warp, \"perturbed_warp\", log_fname);\r\n//\t\tutils::printMatrixToFile(perturbed_state.transpose(), \"perturbed_state\", log_fname);\r\n//\t\tutils::printMatrixToFile(perturbed_ar.transpose(), \"perturbed_ar\", log_fname);\r\n//\t}\r\n//\tProjWarpT SL3_perturbed_ar = a*(base_warp_inv*perturbed_warp);\r\n//\tProjWarpT sl3_perturbed_ar = SL3_perturbed_ar.log();\r\n//\tif(params.debug_mode){\r\n//\t\tutils::printMatrixToFile(sl3_perturbed_ar, \"sl3_perturbed_ar\", log_fname);\r\n//\t}\r\n//\tgetStateFromWarp(perturbed_state, perturbed_warp);\r\n//\tgetStateFromLieAlgMat(perturbed_ar, sl3_perturbed_ar);\r\n//\r\n//}\r\nvoid SL3::compositionalAutoRegression1(VectorXd &perturbed_state, VectorXd &perturbed_ar,\r\n\tconst VectorXd &base_state, const VectorXd &base_ar, double a){\r\n\tProjWarpT sl3_perturbation, lie_alg_base_ar, base_warp;\r\n\tgeneratePerturbation(state_perturbation);\r\n\tgetLieAlgMatFromState(sl3_perturbation, state_perturbation);\r\n\tgetLieAlgMatFromState(lie_alg_base_ar, base_ar);\r\n\tgetWarpFromState(base_warp, base_state);\r\n\tProjWarpT SL3_perturbation = (a*lie_alg_base_ar + sl3_perturbation).exp();\r\n\tProjWarpT perturbed_warp = base_warp*SL3_perturbation;\r\n\tProjWarpT base_warp_inv = base_warp.inverse();\r\n\tProjWarpT lie_alg_perturbed_ar = a*(base_warp_inv*perturbed_warp).log();\r\n\tgetStateFromWarp(perturbed_state, perturbed_warp);\r\n\tgetStateFromLieAlgMat(perturbed_ar, lie_alg_perturbed_ar);\r\n\tif(params.debug_mode){\r\n\t\tutils::printMatrixToFile(state_perturbation.transpose(), \"state_perturbation\", log_fname);\r\n\t\tutils::printMatrixToFile(sl3_perturbation, \"sl3_perturbation\", log_fname);\r\n\t\tutils::printMatrixToFile(base_ar.transpose(), \"base_ar\", log_fname);\r\n\t\tutils::printMatrixToFile(lie_alg_base_ar, \"lie_alg_base_ar\", log_fname);\r\n\t\tutils::printMatrixToFile(SL3_perturbation, \"SL3_perturbation\", log_fname);\r\n\t\tutils::printMatrixToFile(base_warp, \"base_warp\", log_fname);\r\n\t\tutils::printMatrixToFile(perturbed_warp, \"perturbed_warp\", log_fname);\r\n\t\tutils::printMatrixToFile(lie_alg_perturbed_ar, \"lie_alg_perturbed_ar\", log_fname);\r\n\t}\r\n}\r\n\r\nvoid SL3::getInitPixGrad(Matrix2Xd &ssm_grad, int pt_id) {\r\n\tdouble x = init_pts(0, pt_id);\r\n\tdouble y = init_pts(1, pt_id);\r\n\r\n\tssm_grad <<\r\n\t\tx, -x, -y, y, 1, 0, -x*x, -x*y,\r\n\t\t-x, -2*y, x, x, 0, 1, -y*x, -y*y;\r\n}\r\n\r\n\r\nvoid SL3::getCurrPixGrad(Matrix2Xd &ssm_grad, int pt_id) {\r\n\tdouble x = init_pts(0, pt_id);\r\n\tdouble y = init_pts(1, pt_id);\r\n\r\n\tdouble curr_x = curr_pts(0, pt_id);\r\n\tdouble curr_y = curr_pts(1, pt_id);\r\n\r\n\tdouble xx = x*curr_x, xy = x*curr_y, yy = y*curr_y, yx = y*curr_x;\r\n\r\n\tMatrix3d curr_warp;\r\n\tgetWarpFromState(curr_warp, curr_state);\r\n\tdouble a1 = curr_warp(0, 0), a2 = curr_warp(0, 1), a3 = curr_warp(0, 2);\r\n\tdouble a4 = curr_warp(1, 0), a5 = curr_warp(1, 1), a6 = curr_warp(1, 2);\r\n\tdouble a7 = curr_warp(2, 0), a8 = curr_warp(2, 1), a9 = curr_warp(2, 2);\r\n\r\n\tdouble p11 = a1*x - a2*y - a7*xx + a8*yx;\r\n\tdouble p12 = a1*y - a7*yx;\r\n\tdouble p13 = a1 - a7*curr_x;\r\n\tdouble p14 = a2*x - a8*xx;\r\n\tdouble p15 = a2*y - a3 - a8*yx + a9*curr_x;\r\n\tdouble p16 = a2 - a8*curr_x;\r\n\tdouble p17 = a3*x - a9*xx;\r\n\tdouble p18 = a3*y - a9*yx;\r\n\r\n\tdouble p21 = a4*x - a5*y - a7*xy + a8*yy;\r\n\tdouble p22 = a4*y - a7*yy;\r\n\tdouble p23 = a4 - a7*curr_y;\r\n\tdouble p24 = a5*x - a8*xy;\r\n\tdouble p25 = a5*y - a6 - a8*yy + a9*curr_y;\r\n\tdouble p26 = a5 - a8*curr_y;\r\n\tdouble p27 = a6*x - a9*xy;\r\n\tdouble p28 = a6*y - a9*yy;\r\n\r\n\tssm_grad <<\r\n\t\tp11, p12, p13, p14, p15, p16, p17, p18,\r\n\t\tp21, p22, p23, p24, p25, p26, p27, p28;\r\n\r\n\tdouble inv_d = 1.0 / curr_pts_hm(2, pt_id);\r\n\tssm_grad *= inv_d;\r\n}\r\n\r\nvoid SL3::cmptInitPixJacobian(MatrixXd &dI_dp,\r\n\tconst PixGradT &dI_dw){\r\n\tvalidate_ssm_jacobian(dI_dp, dI_dw);\r\n\r\n\tunsigned int ch_pt_id = 0;\r\n\tfor(unsigned int pt_id = 0; pt_id < n_pts; ++pt_id){\r\n\t\tdouble x = init_pts(0, pt_id);\r\n\t\tdouble y = init_pts(1, pt_id);\r\n\r\n\t\tfor(unsigned int ch_id = 0; ch_id < n_channels; ++ch_id){\r\n\t\t\tdouble Ix = dI_dw(ch_pt_id, 0);\r\n\t\t\tdouble Iy = dI_dw(ch_pt_id, 1);\r\n\r\n\t\t\tdouble Ixx = Ix * x;\r\n\t\t\tdouble Iyy = Iy * y;\r\n\t\t\tdouble Ixy = Ix * y;\r\n\t\t\tdouble Iyx = Iy * x;\r\n\r\n\t\t\tdI_dp(ch_pt_id, 0) = Ixx - Iyx;\r\n\t\t\tdI_dp(ch_pt_id, 1) = -(2 * Iyy + Ixx);\r\n\t\t\tdI_dp(ch_pt_id, 2) = Iyx - Ixy;\r\n\t\t\tdI_dp(ch_pt_id, 3) = Iyx + Ixy;\r\n\t\t\tdI_dp(ch_pt_id, 4) = Ix;\r\n\t\t\tdI_dp(ch_pt_id, 5) = Iy;\r\n\t\t\tdI_dp(ch_pt_id, 6) = -Ixx*x - Iyy*x;\r\n\t\t\tdI_dp(ch_pt_id, 7) = -Ixx*y - Iyy*y;\r\n\r\n\t\t\t++ch_pt_id;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid SL3::cmptWarpedPixJacobian(MatrixXd &dI_dp,\r\n\tconst PixGradT &dI_dw) {\r\n\tvalidate_ssm_jacobian(dI_dp, dI_dw);\r\n\r\n\tdouble a00 = curr_warp(0, 0);\r\n\tdouble a01 = curr_warp(0, 1);\r\n\tdouble a10 = curr_warp(1, 0);\r\n\tdouble a11 = curr_warp(1, 1);\r\n\tdouble a20 = curr_warp(2, 0);\r\n\tdouble a21 = curr_warp(2, 1);\r\n\r\n\tunsigned int ch_pt_id = 0;\r\n\tfor(unsigned int pt_id = 0; pt_id < n_pts; ++pt_id) {\r\n\t\tdouble w_x = curr_pts(0, pt_id);\r\n\t\tdouble w_y = curr_pts(1, pt_id);\r\n\r\n\t\tdouble D = curr_pts_hm(2, pt_id);\r\n\t\tdouble inv_det = 1.0 / D;\r\n\r\n\t\tdouble dwx_dx = (a00 - a20*w_x);\r\n\t\tdouble dwx_dy = (a01 - a21*w_x);\r\n\t\tdouble dwy_dx = (a10 - a20*w_y);\r\n\t\tdouble dwy_dy = (a11 - a21*w_y);\r\n\r\n\t\tdouble x = init_pts(0, pt_id);\r\n\t\tdouble y = init_pts(1, pt_id);\r\n\r\n\t\t//double Ix = pix_grad(pt_id, 0);\r\n\t\t//double Iy = pix_grad(pt_id, 1);\r\n\t\tfor(unsigned int ch_id = 0; ch_id < n_channels; ++ch_id){\r\n\t\t\tdouble Ix = (dwx_dx*dI_dw(ch_pt_id, 0) + dwy_dx*dI_dw(ch_pt_id, 1))*inv_det;\r\n\t\t\tdouble Iy = (dwx_dy*dI_dw(ch_pt_id, 0) + dwy_dy*dI_dw(ch_pt_id, 1))*inv_det;\r\n\r\n\t\t\tdouble Ixx = Ix * x;\r\n\t\t\tdouble Ixy = Ix * y;\r\n\t\t\tdouble Iyy = Iy * y;\r\n\t\t\tdouble Iyx = Iy * x;\r\n\r\n\t\t\tdI_dp(ch_pt_id, 0) = Ixx - Iyx;\r\n\t\t\tdI_dp(ch_pt_id, 1) = -(2 * Iyy + Ixx);\r\n\t\t\tdI_dp(ch_pt_id, 2) = Iyx - Ixy;\r\n\t\t\tdI_dp(ch_pt_id, 3) = Iyx + Ixy;\r\n\t\t\tdI_dp(ch_pt_id, 4) = Ix;\r\n\t\t\tdI_dp(ch_pt_id, 5) = Iy;\r\n\t\t\tdI_dp(ch_pt_id, 6) = -Ixx*x - Iyy*x;\r\n\t\t\tdI_dp(ch_pt_id, 7) = -Ixx*y - Iyy*y;\r\n\r\n\t\t\t++ch_pt_id;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid SL3::cmptPixJacobian(MatrixXd &dI_dp,\r\n\tconst PixGradT &pix_jacobian){\r\n\tvalidate_ssm_jacobian(dI_dp, pix_jacobian);\r\n\r\n\tfor(unsigned int pt_id = 0; pt_id < n_pts; ++pt_id){\r\n\t\tdouble x = init_pts(0, pt_id);\r\n\t\tdouble y = init_pts(1, pt_id);\r\n\t\tdouble Ix = pix_jacobian(pt_id, 0);\r\n\t\tdouble Iy = pix_jacobian(pt_id, 1);\r\n\r\n\t\tdouble curr_x = curr_pts(0, pt_id);\r\n\t\tdouble curr_y = curr_pts(1, pt_id);\r\n\t\tdouble inv_d = 1.0 / curr_pts_hm(2, pt_id);\r\n\r\n\t\tdouble Ixx = Ix * x;\r\n\t\tdouble Iyy = Iy * y;\r\n\t\tdouble Ixy = Ix * y;\r\n\t\tdouble Iyx = Iy * x;\r\n\r\n\t\tdI_dp(pt_id, 0) = (Ixx - Iyy) * inv_d;\r\n\t\tdI_dp(pt_id, 1) = Ixy * inv_d;\r\n\t\tdI_dp(pt_id, 2) = Ix * inv_d;\r\n\t\tdI_dp(pt_id, 3) = Iyx * inv_d;\r\n\t\tdI_dp(pt_id, 4) = (Ix*curr_x + Iy*(y + curr_y)) * inv_d;\r\n\t\tdI_dp(pt_id, 5) = Iy * inv_d;\r\n\t\tdI_dp(pt_id, 6) = (-Ixx*curr_x - Iyx*curr_y) * inv_d;\r\n\t\tdI_dp(pt_id, 7) = (-Ixy*curr_x - Iyy*curr_y) * inv_d;\r\n\t}\r\n\t//dI_dp.array().colwise() /= curr_pts_hm.array().row(2).transpose();\r\n}\r\n\r\n\r\nvoid SL3::cmptApproxPixJacobian(MatrixXd &dI_dp,\r\n\tconst PixGradT &pix_jacobian) {\r\n\tvalidate_ssm_jacobian(dI_dp, pix_jacobian);\r\n\r\n\tcurr_warp /= curr_warp(2, 2);\r\n\r\n\tdouble h00_plus_1 = curr_warp(0, 0);\r\n\tdouble h01 = curr_warp(0, 1);\r\n\tdouble h10 = curr_warp(1, 0);\r\n\tdouble h11_plus_1 = curr_warp(1, 1);\r\n\tdouble h20 = curr_warp(2, 0);\r\n\tdouble h21 = curr_warp(2, 1);\r\n\r\n\tfor(unsigned int pt_id = 0; pt_id < n_pts; ++pt_id){\r\n\r\n\t\tdouble Nx = curr_pts_hm(0, pt_id);\r\n\t\tdouble Ny = curr_pts_hm(1, pt_id);\r\n\t\tdouble D = curr_pts_hm(2, pt_id);\r\n\t\tdouble D_sqr_inv = 1.0 / (D*D);\r\n\r\n\t\tdouble a = (h00_plus_1*D - h21*Nx) * D_sqr_inv;\r\n\t\tdouble b = (h01*D - h21*Nx) * D_sqr_inv;\r\n\t\tdouble c = (h10*D - h20*Ny) * D_sqr_inv;\r\n\t\tdouble d = (h11_plus_1*D - h21*Ny) * D_sqr_inv;\r\n\t\tdouble inv_det = 1.0 / ((a*d - b*c)*D);\r\n\r\n\t\tdouble x = init_pts(0, pt_id);\r\n\t\tdouble y = init_pts(1, pt_id);\r\n\r\n\t\tdouble curr_x = curr_pts(0, pt_id);\r\n\t\tdouble curr_y = curr_pts(1, pt_id);\r\n\r\n\t\tdouble Ix = pix_jacobian(pt_id, 0);\r\n\t\tdouble Iy = pix_jacobian(pt_id, 1);\r\n\r\n\t\tdouble Ixx = Ix * x;\r\n\t\tdouble Ixy = Ix * y;\r\n\t\tdouble Iyy = Iy * y;\r\n\t\tdouble Iyx = Iy * x;\r\n\r\n\t\tdouble factor1 = b*curr_y - d*curr_x;\r\n\t\tdouble factor2 = c*curr_x - a*curr_y;\r\n\r\n\t\tdI_dp(pt_id, 0) = (Ixx*d + Ixy*b - Iyx*c - Iyy*a) * inv_det;\r\n\t\tdI_dp(pt_id, 1) = (Ixy*d - Iyy*c) * inv_det;\r\n\t\tdI_dp(pt_id, 2) = (Ix*d - Iy*c) * inv_det;\r\n\t\tdI_dp(pt_id, 3) = (Iyx*a - Ixx*b) * inv_det;\r\n\t\tdI_dp(pt_id, 4) = (Iyy*a - Ix*factor1 - Ixy*b - Iy*factor2) * inv_det;\r\n\t\tdI_dp(pt_id, 5) = (Iy*a - Ix*b) * inv_det;\r\n\t\tdI_dp(pt_id, 6) = (Ixx*factor1 + Iyx*factor2) * inv_det;\r\n\t\tdI_dp(pt_id, 7) = (Ixy*factor1 + Iyy*factor2) * inv_det;\r\n\r\n\t\t//dI_dp(i, 0) = (Ix*(d*x + b*y) - Iy*(c*x + a*y)) * inv_det;\r\n\t\t//dI_dp(i, 1) = (Ix*d*y - Iy*c*y) * inv_det;\r\n\t\t//dI_dp(i, 2) = (Ix*d - Iy*c) * inv_det;\r\n\t\t//dI_dp(i, 3) = (Iy*a*x - Ix*b*x) * inv_det;\r\n\t\t//dI_dp(i, 4) = (Ix*(d*curr_x - b*(y + curr_y)) + Iy*(-c*curr_x + a*(y + curr_y))) * inv_det;\r\n\t\t//dI_dp(i, 5) = (Iy*a - Ix*b) * inv_det;\r\n\t\t//dI_dp(i, 6) = (Ix*(-d*x*curr_x + b*x*curr_y) + Iy*(c*x*curr_x - a*x*curr_y)) * inv_det;\r\n\t\t//dI_dp(i, 7) = (Ix*(-d*y*curr_x + b*y*curr_y) + Iy*(c*y*curr_x - a*y*curr_y)) * inv_det;\r\n\t}\r\n}\r\n\r\nvoid SL3::estimateWarpFromCorners(VectorXd &state_update, const Matrix24d &in_corners,\r\n\tconst Matrix24d &out_corners){\r\n\tvalidate_ssm_state(state_update);\r\n\tMatrix3d warp_update_mat = utils::computeHomographyDLT(in_corners, out_corners);\r\n\tgetStateFromWarp(state_update, warp_update_mat);\r\n}\r\n\r\nvoid SL3::estimateWarpFromPts(VectorXd &state_update, vector<uchar> &mask,\r\n\tconst vector<cv::Point2f> &in_pts, const vector<cv::Point2f> &out_pts,\r\n\tconst EstimatorParams &est_params){\r\n\tcv::Mat warp_mat_cv = estimateHomography(in_pts, out_pts, mask, est_params);\r\n\tutils::copyCVToEigen<double, Matrix3d>(warp_mat, warp_mat_cv);\r\n\tgetStateFromWarp(state_update, warp_mat);\r\n}\r\n\r\nvoid SL3::estimateMeanOfSamples(VectorXd &sample_mean,\r\n\tconst std::vector<VectorXd> &samples, int n_samples){\r\n\tif(params.iterative_sample_mean){\r\n\t\tvector<ProjWarpT> lie_group_samples;\r\n\t\tlie_group_samples.resize(n_samples);\r\n\t\t// convert state vectors to SL3 matrices\r\n\t\tfor(int sample_id = 0; sample_id < n_samples; ++sample_id){\r\n\t\t\tgetWarpFromState(lie_group_samples[sample_id], samples[sample_id]);\r\n\t\t}\r\n\t\tProjWarpT lie_group_mean = lie_group_samples[0];\r\n\t\tProjWarpT lie_group_mean_inv = lie_group_mean.inverse();\r\n\t\tfor(int iter_id = 0; iter_id < params.sample_mean_max_iters; ++iter_id){\r\n\t\t\tProjWarpT lie_algebra_mean = ProjWarpT::Zero();\r\n\t\t\tfor(int sample_id = 0; sample_id < n_samples; ++sample_id){\r\n\t\t\t\tlie_algebra_mean += (lie_group_mean_inv*lie_group_samples[sample_id]).log();\r\n\t\t\t}\r\n\t\t\tlie_algebra_mean /= n_samples;\r\n\t\t\tProjWarpT lie_group_mean_upd = lie_algebra_mean.exp();\r\n\t\t\tlie_group_mean = lie_group_mean*lie_group_mean_upd;\r\n\t\t\tlie_group_mean_inv = lie_group_mean.inverse();\r\n\t\t\tdouble upd_norm = lie_group_mean_upd.squaredNorm();\r\n\t\t\tif(upd_norm < params.sample_mean_eps){\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tgetStateFromWarp(sample_mean, lie_group_mean);\r\n\t} else{\r\n\t\tProjectiveBase::estimateMeanOfSamples(sample_mean, samples, n_samples);\r\n\t}\r\n}\r\n\r\n\r\n_MTF_END_NAMESPACE\r\n\r\n", "meta": {"hexsha": "2dc63151ed3875dcb82e889efb93a25d45ee38a4", "size": 23987, "ext": "cc", "lang": "C++", "max_stars_repo_path": "SSM/src/SL3.cc", "max_stars_repo_name": "abhineet123/MTF", "max_stars_repo_head_hexsha": "6cb45c88d924fb2659696c3375bd25c683802621", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2016-12-11T00:34:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T23:03:40.000Z", "max_issues_repo_path": "SSM/src/SL3.cc", "max_issues_repo_name": "siqiyan/MTF", "max_issues_repo_head_hexsha": "9a76388c907755448bb7223420fe74349130f636", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2017-09-04T06:27:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T19:07:23.000Z", "max_forks_repo_path": "SSM/src/SL3.cc", "max_forks_repo_name": "siqiyan/MTF", "max_forks_repo_head_hexsha": "9a76388c907755448bb7223420fe74349130f636", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2017-02-19T02:12:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-23T03:47:55.000Z", "avg_line_length": 35.3790560472, "max_line_length": 145, "alphanum_fraction": 0.6939175387, "num_tokens": 7969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5307671412170226}}
{"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 <gsl/gsl_linalg.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_eigen.h>\n\nnamespace votca { namespace tools {\n\nusing namespace std;\n\nvoid linalg_cholesky_decompose( ub::matrix<double> &A){\n        // Cholesky decomposition using GSL\n        const size_t N = A.size1();\n        \n        gsl_matrix_view A_view = gsl_matrix_view_array(&A(0,0), N, N);\n        \n        // get the Cholesky matrices\n        int status = gsl_linalg_cholesky_decomp ( &A_view.matrix );\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 GSL_EDOM\n     * thrown by gsl_linalg_cholesky_decomp and take\n     * necessary steps\n     */\n    \n    gsl_matrix_view m\n        = gsl_matrix_view_array (&A(0,0), A.size1(), A.size2());\n\n    gsl_vector_view gb\n        = gsl_vector_view_array (&b(0), b.size());\n\n    gsl_vector *gsl_x = gsl_vector_alloc (x.size());\n\n    gsl_set_error_handler_off();\n    int status = gsl_linalg_cholesky_decomp(&m.matrix);\n\n    if( status == GSL_EDOM)\n        throw std::runtime_error(\"Matrix not symmetric positive definite\");\n\n    \n    gsl_linalg_cholesky_solve(&m.matrix, &gb.vector, gsl_x);\n\n    for (size_t i =0 ; i < x.size(); i++)\n        x(i) = gsl_vector_get(gsl_x, i);\n\n    gsl_vector_free (gsl_x);\n}\n\n\n}}\n", "meta": {"hexsha": "1e1da201fe6bc4c5bfb1bec460fa5202a36aef79", "size": 2050, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libtools/linalg/gsl/cholesky.cc", "max_stars_repo_name": "vaidyanathanms/votca.tools", "max_stars_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "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/gsl/cholesky.cc", "max_issues_repo_name": "vaidyanathanms/votca.tools", "max_issues_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "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/gsl/cholesky.cc", "max_forks_repo_name": "vaidyanathanms/votca.tools", "max_forks_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "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.2857142857, "max_line_length": 96, "alphanum_fraction": 0.6819512195, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5307592246125418}}
{"text": "//\n// Created by Bryn Elesedy on 12/11/2018.\n// Linear regression with a single output dimension\n\n#include <getopt.h>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nconst double DEFAULT_LAMBDA_VALUE = 0;\nconst std::streamsize DEFAULT_PREC = 2;\nconst char DELIM = ',';\nconst std::string INPUT_FILE_EXTENSION = \".csv\";\nconst std::string OUTPUT_PREDICTION_EXTENSION = \".fittedvalues\";\nconst std::string OUTPUT_WEIGHTS_EXTENSION = \".weights\";\n\n\n\n// ----------------\n// Parse command line arguments\n\nstruct command_line_args {\n    command_line_args() : lambda(DEFAULT_LAMBDA_VALUE), prec(DEFAULT_PREC) {}\n\n    double lambda;\n    std::streamsize prec;\n    std::string input_filename;\n\n};\n\nvoid print_help_message() {\n    std::cout << \"==========================================================\\n\";\n    std::cout << \">>>>>>>>>>>>>>>>>L2 Regularised Regression<<<<<<<<<<<<<<<<\\n\";\n    std::cout << \"==========================================================\\n\";\n    std::cout << \"Usage: linregress <path/to/input_file> [--lambda] [--prec]\\n\";\n    std::cout << \"----------------------------------------------------------\\n\";\n    std::cout << \"Parameters:\\n\";\n    std::cout << \"input_file: File containing training data, must be csv.\\n\"\n                 \"            Row stacked training examples.\\n\"\n                 \"            Final column the y values, others form X.\\n\";\n    std::cout << \"--lambda (numeric): Ridge regularisation parameter.\\n\"\n                 \"                    Must be >=0, 0 gives OLS regression.\\n\"\n                 \"                    Default is \" << DEFAULT_LAMBDA_VALUE << \"\\n\";\n    std::cout << \"--prec (int): Significant figures for console output.\\n\"\n                 \"              Default is \" << DEFAULT_PREC << \"\\n\";\n    std::cout << \"==========================================================\\n\";\n    return;\n}\n\n\n\ncommand_line_args parse_args(int argc, char *argv[]) {\n    const char *const short_opts = \"l:h\";\n    const option long_opts[] = {\n            {\"lambda\", required_argument, nullptr, 'l'},\n            {\"prec\",   required_argument,       nullptr, 'p'},\n            {\"help\",   no_argument,       nullptr, 'h'},\n    };\n\n    command_line_args output;\n    int opt;\n    int option_index = 0;\n    while ((opt = getopt_long(argc, argv, short_opts, long_opts, &option_index)) != -1) {\n        switch (opt) {\n            case 'l':\n                output.lambda = std::stod(optarg);\n                break;\n            case 'p':\n                output.prec = (std::streamsize) std::stoi(optarg);\n                break;\n            case 'h':\n            case '?':\n            default:\n                print_help_message();\n                exit(EXIT_SUCCESS);\n        }\n    }\n\n    if (optind < argc) {\n        output.input_filename = argv[optind++];\n    } else {\n        std::cerr << \"Failure: must give an input file.\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if (optind < argc) {\n        std::cerr << \"Warning: \" << argc - optind << \" additional arguments given, all ignored!\\n\" << std::endl;\n    }\n\n    return output;\n}\n\nvoid check_args(command_line_args &args) {\n\n    if (args.lambda < 0) {\n        std::cerr << \"Error: Ridge regularisation parameter lambda must be >= 0\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if (args.prec < 0) {\n        std::cerr << \"Warning: given output precision < 0.\" << std::endl;\n    }\n\n    return;\n}\n\n// ----------------\n\n\n\n// ----------------\n// Parse inputs into Eigen matrices\n\nstruct data_size {\n    std::size_t n_features;\n    std::size_t n_examples;\n};\n\nstruct input_data {\n    MatrixXd X;\n    VectorXd y;\n};\n\n\ndata_size get_data_size(std::string input_filename, char delim) {\n    std::ifstream infile(input_filename);\n\n    if (!infile.is_open()) {\n        std::cerr << \"Error: Failed to open \" << input_filename << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    data_size input_sizes;\n    std::string line;\n    std::size_t lc = 0;\n    while (std::getline(infile, line)) {\n        if (line.empty()) {\n            continue;\n\n        }\n\n        if (lc == 0) {\n            input_sizes.n_features = std::count(line.begin(), line.end(), delim);\n        }\n        lc++;\n    }\n    input_sizes.n_examples = lc;\n\n    infile.close();\n    return input_sizes;\n}\n\n\ninput_data read_input_file(std::string input_filename, data_size input_sizes, char delim) {\n\n    std::ifstream infile(input_filename);\n\n    if (!infile.is_open()) {\n        std::cerr << \"Error: Failed to open \" << input_filename << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    MatrixXd X(input_sizes.n_examples, input_sizes.n_features);\n    VectorXd y(input_sizes.n_examples);\n\n    std::size_t col = 0;\n    std::size_t row = 0;\n    std::string line;\n    while (std::getline(infile, line)) {\n        std::stringstream this_line(line);\n        std::string item;\n\n        while (std::getline(this_line, item, delim)) {\n            if (item.empty()) {\n                continue;\n            }\n\n            if (col == input_sizes.n_features) {\n                y(row) = std::stod(item);\n                col = 0;\n                row++;\n            } else {\n                X(row, col) = std::stod(item);\n                col++;\n            }\n        }\n\n    }\n    infile.close();\n\n    input_data output;\n    output.X = X;\n    output.y = y;\n    return output;\n}\n\n// ----------------\n\n\n\n// ----------------\n// Do the Regression\n\nMatrixXd append_ones_column(MatrixXd X) {\n    MatrixXd new_x(X.rows(), X.cols() + 1);\n    VectorXd c = VectorXd::Constant(X.rows(), 1.);\n    new_x << X, c;\n    return new_x;\n}\n\n\nclass RidgeRegression {\nprivate:\n    double lambda;\n    bool has_constant;\n    bool is_fitted;\n\n    Eigen::HouseholderQR <MatrixXd> qr_decomp;\n    VectorXd weights;\n\npublic:\n    RidgeRegression(double lambda) : lambda(lambda), is_fitted(false) {}\n\n    void fit(MatrixXd X, VectorXd y, bool add_constant);\n\n    VectorXd predict(MatrixXd x_vals);\n\n    inline VectorXd get_weights() { return this->weights; }\n\n    inline bool has_const() { return this->has_constant; }\n};\n\n\nvoid RidgeRegression::fit(MatrixXd X, VectorXd y, bool add_constant) {\n    if (X.rows() != y.rows()) {\n        throw std::invalid_argument(\"X and y must have same number of rows.\");\n    }\n\n    MatrixXd X_train = (add_constant) ? append_ones_column(X) : X;\n\n    Eigen::MatrixXd eye = Eigen::MatrixXd::Identity(X_train.cols(), X_train.cols());\n\n    this->qr_decomp = (this->lambda * eye + X_train.transpose() * X_train).householderQr();\n    this->weights = this->qr_decomp.solve(X_train.transpose() * y);\n    this->has_constant = add_constant;\n    this->is_fitted = true;\n    return;\n}\n\nVectorXd RidgeRegression::predict(MatrixXd xvals) {\n    if (!this->is_fitted) {\n        throw std::domain_error(\"Need to fit regression before prediction.\");\n    }\n\n    if (has_constant) {\n        double offset = this->weights(this->weights.rows() - 1);\n        VectorXd slope = this->weights.head(this->weights.rows() - 1);\n        return ((xvals * slope).array() + offset).matrix();\n    } else {\n        return xvals * this->weights;\n    }\n}\n// ----------------\n\n\n\n// ----------------\n// Output\n\ndouble rmse(VectorXd y1, VectorXd y2) {\n    return std::sqrt((y1 - y2).array().pow(2).mean());\n}\n\n\nvoid print_results(RidgeRegression regressor, double rmse_, std::streamsize prec) {\n\n    VectorXd weights = regressor.get_weights();\n\n    std::streamsize curr_prec = std::cout.precision();\n    std::cout << \"Fitted Model: y = \";\n    std::cout << std::setprecision(prec);\n    int i = 0;\n    while (i < weights.size() - 1) {\n        std::cout << weights(i) << \" x\" << i + 1 << \" + \";\n        i++;\n    }\n\n    std::cout << weights(i) << std::endl;\n    std::cout << \"RMSE: \" << rmse_ << std::endl;\n    std::cout << std::setprecision(curr_prec);\n    return;\n}\n\nstd::string get_output_filename(std::string input_filename, std::string old_ext, std::string new_ext) {\n    std::string prefix;\n    int d = input_filename.size() - old_ext.size();\n    if (d > 0 && input_filename.compare(d, old_ext.size(), old_ext) == 0) {\n        prefix = input_filename.substr(0, d);\n    } else {\n        prefix = input_filename;\n    }\n    return prefix + new_ext;\n}\n\nvoid save_vector(VectorXd fitted_values, std::string filename) {\n    std::ofstream outfile(filename);\n\n    if (!outfile.is_open()) {\n        std::cerr << \"Failed out open output file \" << filename << \" values not written.\" << std::endl;\n        return;\n    }\n\n    for (std::size_t i = 0; i < fitted_values.rows(); i++) {\n        outfile << fitted_values(i) << std::endl;\n    }\n\n    outfile.close();\n    return;\n}\n\n// ----------------\n\n\n\nint main(int argc, char *argv[]) {\n\n    command_line_args args = parse_args(argc, argv);\n\n    check_args(args);\n\n    data_size dims = get_data_size(args.input_filename, DELIM);\n    input_data data = read_input_file(args.input_filename, dims, DELIM);\n\n    std::cout << \"=================================================\" << std::endl;\n    std::cout << \"Least Squares Regression. L2 regularisation = \" << args.lambda << std::endl;\n    std::cout << \"-------------------------------------------------\" << std::endl;\n    std::cout << \"Read data from \" << args.input_filename << \", found \" << dims.n_features << \" features and \";\n    std::cout << dims.n_examples << \" examples\" << std::endl;\n    std::cout << \"-------------------------------------------------\" << std::endl;\n\n    RidgeRegression regressor(args.lambda);\n    // Previously considered giving user option to not include constant\n    // in regression but I changed my mind.\n    regressor.fit(data.X, data.y, true);\n\n    VectorXd fitted_values = regressor.predict(data.X);\n\n    print_results(regressor, rmse(data.y, fitted_values), args.prec);\n    save_vector(\n            fitted_values,\n            get_output_filename(args.input_filename, INPUT_FILE_EXTENSION, OUTPUT_PREDICTION_EXTENSION)\n            );\n\n    save_vector(\n            regressor.get_weights(),\n            get_output_filename(args.input_filename, INPUT_FILE_EXTENSION, OUTPUT_WEIGHTS_EXTENSION)\n    );\n    std::cout << \"=================================================\" << std::endl;\n\n    return 0;\n\n}\n", "meta": {"hexsha": "671b88831d6083f3f08d13f4ef2e486cf1dab9f9", "size": 10185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/linregress.cpp", "max_stars_repo_name": "brynhayder/cpp-ols", "max_stars_repo_head_hexsha": "d29d929d14a3b46072f7366edb484ff6deb37fe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-28T03:56:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T03:56:12.000Z", "max_issues_repo_path": "src/linregress.cpp", "max_issues_repo_name": "brynhayder/cpp-ols", "max_issues_repo_head_hexsha": "d29d929d14a3b46072f7366edb484ff6deb37fe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linregress.cpp", "max_forks_repo_name": "brynhayder/cpp-ols", "max_forks_repo_head_hexsha": "d29d929d14a3b46072f7366edb484ff6deb37fe6", "max_forks_repo_licenses": ["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.7520435967, "max_line_length": 112, "alphanum_fraction": 0.5551300933, "num_tokens": 2406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5307592153048409}}
{"text": "/*\n * Copyright 2015 David A. Boyuka II\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 * dilate-impl.hpp\n *\n * Bitwise integer dilation/undilation. Algorithms courtesy of\n * \"Converting to and from Dilated Integers\" by Raman and Wise\n * (http://www.cs.indiana.edu/~dswise/Arcee/castingDilated-comb.pdf).\n *\n *  Created on: Sep 16, 2015\n *      Author: David A. Boyuka II\n */\n#ifndef SRC_UTIL_IMPL_DILATE_IMPL_HPP_\n#define SRC_UTIL_IMPL_DILATE_IMPL_HPP_\n\n//#include <boost/math/special_functions/pow.hpp>\n#include <boost/integer/static_log2.hpp>\n\n/*\n\n// WIP - general multiplication-based implementation\ntemplate<typename word_t, int d>\nstruct DilaterHelper {\n\tstatic constexpr int w = std::numeric_limits<word_t>::digits;\n\tstatic constexpr int s = w / d;\n\n\ttemplate<int i>\n\tclass DilaterRound {\n\t\tstatic constexpr int di = std::pow(d, i);\n\t\tstatic constexpr int bitcount = (di < s ? di : s);\n\n\t\ttemplate<int j>\n\t\tstatic constexpr word_t z = z<j-1> | (z<0> >> (j * di * d));\n\n\t\ttemplate<>\n\t\tstatic constexpr word_t z<0> = ((1 << bitcount) - 1) << (d * (s - 1) + 1 - bitcount);\n\n\n\t};\n};\n*/\n\ntemplate<typename word_t, int d>\nword_t Dilater<word_t, d>::dilate(word_t word) { abort(); }\n\ntemplate<typename word_t, int d>\nword_t Dilater<word_t, d>::undilate(word_t word) { abort(); }\n\n// Partial specialization for d=2\ntemplate<typename word_t>\nclass Dilater<word_t, 2> {\npublic:\n\tstatic word_t dilate(word_t word);\n\tstatic word_t undilate(word_t word);\n};\n\nnamespace detail {\n\ttemplate<typename word_t> constexpr int S() { return std::numeric_limits<word_t>::digits/2; } // num dilateable bits\n\ttemplate<typename word_t> constexpr int ROUNDS() { return boost::static_log2< S<word_t>() >::value; }\n\n\ttemplate<typename word_t, int power> constexpr word_t EXP2P1() { return ((word_t)1<<((word_t)1<<power)) + (word_t)1; }\n\n\ttemplate<typename word_t, int round>\n\tstruct rounds {\n\t\t// DILATION\n\n\t\t// Useful <rounds> go from 1 to ROUNDS inclusive (0 is just a base case, though it is used by UNDILATE_MASK below)\n\t\t// MASK<0> is a set mask of the lower half bits of word_t\n\t\t// Each successive MASK chops all groups of set bits in half (keeping the lower halves), then\n\t\t// duplicates those groups up by twice the width of these now smaller groups\n\t\t// Examples: for 8-bit: MASK<0> = 00001111, MASK<1> = 00110011, MASK<2> = 01010101\n\t\tstatic constexpr word_t DILATE_MASK() { return rounds<word_t, round-1>::DILATE_MASK() / EXP2P1<word_t, ROUNDS<word_t>()-round>() * EXP2P1<word_t, ROUNDS<word_t>()-round+1>(); }\n\t\tstatic constexpr word_t dilate_round(word_t word) {\n\t\t\treturn\n\t\t\t\tword = rounds<word_t, round-1>::dilate_round(word),\n\t\t\t\t(word | (word << (S<word_t>() >> round))) & rounds<word_t, round>::DILATE_MASK();\n\t\t}\n\n\t\t// UNDILATION\n\n\t\t// Useful <rounds> go from 1 to ROUNDS inclusive (0 is just a base case)\n\t\t// UNDILATE_MASK is just DILATE_MASK in reverse order, shifted by one down\n\t\t// Examples: UNDILATE_MASK<1> is DILATE_MASK<ROUNDS-1>, UNDILATE_MASK<ROUNDS> is DILATE_MASK<0>\n\t\tstatic constexpr word_t UNDILATE_MASK() { return rounds<word_t, ROUNDS<word_t>()-round>::DILATE_MASK(); }\n\t\tstatic constexpr word_t undilate_round(word_t word) {\n\t\t\treturn\n\t\t\t\tword = rounds<word_t, round-1>::undilate_round(word),\n\t\t\t\t(word | (word >> ((word_t)1 << (round-1)))) & rounds<word_t, round>::UNDILATE_MASK();\n\t\t}\n\t};\n\n\ttemplate<typename word_t>\n\tstruct rounds<word_t, 0> {\n\t\tstatic constexpr word_t DILATE_MASK() { return ((word_t)1 << S<word_t>()) - 1; }\n\t\tstatic constexpr word_t dilate_round(word_t word) { return word; }\n\t\tstatic constexpr word_t undilate_round(word_t word) { return word; }\n\t};\n\n\ttemplate<typename word_t> constexpr word_t dilate(word_t word) { return rounds<word_t, ROUNDS<word_t>()>::dilate_round(word); }\n\ttemplate<typename word_t> constexpr word_t undilate(word_t word) { return rounds<word_t, ROUNDS<word_t>()>::undilate_round(word); }\n} // namespace detail\n\ntemplate<typename word_t>\nword_t Dilater<word_t, 2>::dilate(word_t word) {\n\treturn detail::dilate<word_t>(word);\n}\n\ntemplate<typename word_t>\nword_t Dilater<word_t, 2>::undilate(word_t word){\n\treturn detail::undilate<word_t>(word);\n}\n\n#endif /* SRC_UTIL_IMPL_DILATE_IMPL_HPP_ */\n", "meta": {"hexsha": "6ecd9f0a760508a58680b93390f1da123d25ed78", "size": 4679, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pique/util/impl/dilate-impl.hpp", "max_stars_repo_name": "daboyuka/PIQUE", "max_stars_repo_head_hexsha": "d0e2ba4cc47aaeaf364b3c76339306e1795adb5e", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/pique/util/impl/dilate-impl.hpp", "max_issues_repo_name": "daboyuka/PIQUE", "max_issues_repo_head_hexsha": "d0e2ba4cc47aaeaf364b3c76339306e1795adb5e", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/pique/util/impl/dilate-impl.hpp", "max_forks_repo_name": "daboyuka/PIQUE", "max_forks_repo_head_hexsha": "d0e2ba4cc47aaeaf364b3c76339306e1795adb5e", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5546875, "max_line_length": 178, "alphanum_fraction": 0.7121179739, "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5306837381774794}}
{"text": "/**\n *  testFrameConversion.cpp\n *\n *  Test the frame conversion between inertial and body frames.\n *\n *  Created by Yinan Li on Nov. 27, 2020.\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n\n#include <iostream>\n#include <cmath>\n#include <boost/numeric/odeint.hpp>\n#include <cstdlib>\n#include <ctime>\n\n\n#include \"src/definitions.h\"\n\n\n\n/* define dynamics */\nstruct car_dynamics {\n    rocs::Rn u;\n    car_dynamics (const rocs::Rn param): u (param) {}\n\n    void operator() (rocs::Rn &x, rocs::Rn &dxdt, double t) const\n    {\n\tdxdt[0] = u[0]*std::cos(x[2]);\n\tdxdt[1] = u[0]*std::sin(x[2]);\n\tdxdt[2] = u[1];\n    }\n};\n\nstruct twoagent_ode {\n    rocs::Rn u;\n    rocs::Rn d;\n    twoagent_ode (const rocs::Rn p1, const rocs::Rn p2): u(p1), d(p2){}\n    /**\n     * ODE model\n     * @param x system state: [x,y,theta], n=3\n     * @param dxdt vector field\n     * @param t time\n     */\n    void operator() (rocs::Rn &x, rocs::Rn &dxdt, double t) const\n    {\n\tdxdt[0] = -u[0] + d[0]*cos(x[2]) + u[1]*x[1];\n\tdxdt[1] = d[0]*sin(x[2]) - u[1]*x[0];\n\tdxdt[2] = d[1] - u[1];\n    }\n};\n\nvoid inertia_to_body(rocs::Rn &z, rocs::Rn z0) {\n    double x = std::cos(z0[2])*z[0] + std::sin(z0[2])*z[1];\n    double y = -std::sin(z0[2])*z[0] + std::cos(z0[2])*z[1];\n    z[0] = x;\n    z[1] = y;\n}\n\nvoid body_to_inertia(rocs::Rn &z, rocs::Rn z0) {\n    double x = std::cos(z0[2])*z[0] - std::sin(z0[2])*z[1];\n    double y = std::sin(z0[2])*z[0] + std::cos(z0[2])*z[1];\n    z[0] = x;\n    z[1] = y;\n}\n\n\nint main() {\n    boost::numeric::odeint::runge_kutta_cash_karp54<rocs::Rn> rk45;\n    rocs::Rn z0{5.08561,10.1089,1.8}, z1{3.7, 10.8, 0.0};\n    rocs::Rn u{0.9, -0.9}, d{0.6, 0.6/4.61};\n    rocs::Rn zr(3);\n    for(int i = 0; i < 3; ++i) {\n\tzr[i] = z1[i]-z0[i];\n    }\n    std::cout << \"z1 position to z0 in inertial frame initially: \";\n    for(int i = 0; i < 3; ++i) {\n\tstd::cout << zr[i] << ' ';\n    }\n    std::cout << '\\n';\n    \n    inertia_to_body(zr, z0);\n    std::cout << \"z1 position to z0 in z0 body frame initially: \";\n    for(int i = 0; i < 3; ++i) {\n\tstd::cout << zr[i] << ' ';\n    }\n    std::cout << '\\n';\n    \n    const double h = 0.3;  // sampling time\n    const double dt = 0.001; //integration step size for odeint\n    /* Integrate z0 and z1 separately */\n    boost::numeric::odeint::integrate_const(rk45, car_dynamics(u), z0, 0.0, h, dt);\n    boost::numeric::odeint::integrate_const(rk45, car_dynamics(d), z1, 0.0, h, dt);\n    std::cout << \"z1-z0 = \";\n    for(int i = 0; i < 3; ++i) {\n\tstd::cout << z1[i]-z0[i] << ' ';\n    }\n    std::cout << '\\n';\n    /* Integrate by the local model */\n    boost::numeric::odeint::integrate_const(rk45, twoagent_ode(u,d), zr, 0.0, h, dt);\n    std::cout << \"z1 position to z0 in z0 body frame after 0.3s: \";\n    for(int i = 0; i < 3; ++i) {\n\tstd::cout << zr[i] << ' ';\n    }\n    std::cout << '\\n';\n    \n    body_to_inertia(zr, z0);\n    std::cout << \"z1 position to z0 in inertial frame after 0.3s: \";\n    for(int i = 0; i < 3; ++i) {\n\tstd::cout << zr[i] << ' ';\n    }\n    std::cout << '\\n';\n}\n", "meta": {"hexsha": "ba093846102bec2ba5f43e32c4943fdff7af69b0", "size": 3013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/collision-avoid/testFrameConversion.cpp", "max_stars_repo_name": "yinanl/rocs", "max_stars_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "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/collision-avoid/testFrameConversion.cpp", "max_issues_repo_name": "yinanl/rocs", "max_issues_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/collision-avoid/testFrameConversion.cpp", "max_forks_repo_name": "yinanl/rocs", "max_forks_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "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.4298245614, "max_line_length": 85, "alphanum_fraction": 0.5350149353, "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5306837363754406}}
{"text": "#include <Eigen/Core>\n#include <fstream>\n#include <sstream>\n#include \"json/json.h\"\n#include <aruco/aruco.h>\n#include <aruco/cvdrawingutils.h>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv/cv.h>\n#include <opencv2/highgui/highgui_c.h>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/core/eigen.hpp>\n\nvoid rotateXAxis(cv::Mat &rotation) {\n    cv::Mat R(3, 3, CV_32F);\n    cv::Rodrigues(rotation, R);\n    // create a rotation matrix for x axis\n    cv::Mat RX = cv::Mat::eye(3, 3, CV_32F);\n    float angleRad = M_PI / 2;\n    RX.at< float >(1, 1) = cos(angleRad);\n    RX.at< float >(1, 2) = -sin(angleRad);\n    RX.at< float >(2, 1) = sin(angleRad);\n    RX.at< float >(2, 2) = cos(angleRad);\n    // now multiply\n    R = R * RX;\n    // finally, the the rodrigues back\n    cv::Rodrigues(R, rotation);\n}\n\n\ndouble calculateExtrinsics(aruco::Marker & m, float markerSizeMeters, cv::Mat camMatrix, cv::Mat distCoeff, bool setYPerpendicular,cv::Mat &Rvec,cv::Mat &Tvec)\n     {\n    if (!m.isValid())\n        return -1;\n    if (markerSizeMeters <= 0)\n        return -1; \n    if (camMatrix.rows == 0 || camMatrix.cols == 0)\n        return -1;\n\n    double halfSize = markerSizeMeters / 2.;\n    cv::Mat ObjPoints(4, 3, CV_32FC1);\n    ObjPoints.at< float >(1, 0) = -halfSize;\n    ObjPoints.at< float >(1, 1) = halfSize;\n    ObjPoints.at< float >(1, 2) = 0;\n    ObjPoints.at< float >(2, 0) = halfSize;\n    ObjPoints.at< float >(2, 1) = halfSize;\n    ObjPoints.at< float >(2, 2) = 0;\n    ObjPoints.at< float >(3, 0) = halfSize;\n    ObjPoints.at< float >(3, 1) = -halfSize;\n    ObjPoints.at< float >(3, 2) = 0;\n    ObjPoints.at< float >(0, 0) = -halfSize;\n    ObjPoints.at< float >(0, 1) = -halfSize;\n    ObjPoints.at< float >(0, 2) = 0;\n\n    cv::Mat ImagePoints(4, 1, CV_32FC2);\n    cv::Mat ximagePoints(4, 1, CV_32FC2);\n\n    // Set image points from the marker\n    for (int c = 0; c < 4; c++) {\n        ImagePoints.at< cv::Point2f >(c, 0) = m[c];\n    }\n\n    cv::Mat raux, taux;\n    bool x = cv::solvePnP(ObjPoints, ImagePoints, camMatrix, distCoeff, raux, taux);\n    if(!x)\n        return -2;\n    std::cout << \"solved\\n\";\n    raux.convertTo(Rvec, CV_32F);\n    taux.convertTo(Tvec, CV_32F);\n    // rotate the X axis so that Y is perpendicular to the marker plane\n    cv::projectPoints(ObjPoints,raux,taux,camMatrix,distCoeff,ximagePoints);\n    std::cout << \" op \" << ImagePoints.rows << \" \" << ImagePoints.cols << \" c \" << ImagePoints.channels() << \" t \" << ImagePoints.type() << std::endl;\n    std::cout << \" op \" << ximagePoints.rows << \" \" << ximagePoints.cols << \" c \" << ximagePoints.channels() << \" t\" << ximagePoints.type() << std::endl;\n    std::cout << \"reproject \" << ImagePoints-ximagePoints << std::endl;\n    //double r = 0;\n    //for(int i = 0; i < 4; i++)\n    //    r += cv::norm(ImagePoints.at<cv::Point2f>(i,0)-ximagePoints.at<cv::Point2f>(i,0));\n    double r = cv::norm(ImagePoints-ximagePoints);\n    if (setYPerpendicular)\n        rotateXAxis(Rvec);\n    // and now reprojection error\n    return r;\n}\n\n\nJson::Value mat2json(cv::Mat m)\n{\n    Json::Value r;\n    for(int i = 0; i < m.rows; i++)\n    {\n        Json::Value q;\n      for(int j = 0; j < m.cols; j++)\n            q[j] = m.at<double>(i,j);\n        r[i] = q;\n    }\n    return r;\n}\n\nJson::Value vec2json(double * p, int n)\n{\n    Json::Value r;\n    for(int i = 0; i < n; i++)\n        r[i] = p[i];\n    return r;\n}\n\nJson::Value mat2json1(Eigen::Matrix4d m)\n{\n    Json::Value r;\n    double *v_ptr = m.data();\n    for (int i = 0; i < 16; ++i)\n        r.append(Json::Value(v_ptr[i]));\n    return r;\n}\n\nJson::Value mat2json(const Eigen::Matrix4d & m)\n{\n    Json::Value r;\n    for(int i = 0; i < m.rows(); i++)\n    {\n        Json::Value q;\n      for(int j = 0; j < m.cols(); j++)\n            q[j] = m(i,j);\n        r[i] = q;\n    }    \n    return r;\n}\n\nvoid help(){\n        std::cerr << \"Arguments: [-xy] calibrationfile size imagefile alreadyundist [-|outfilename]\\n\\t-x mirror image along x\\n\\t-y mirror image along y\\n\\t-xy mirror image along xy\\n\"\";\n        exit(1);\n}\n\n\nint main(int argc, char const *argv[])\n{\n\t// first is camera as OpenCV\n\t// second is file\n\t// output is array of markers\t\n\tbool y_axis_perpendicular = false;\n    int mirror = 0;\n    bool show = false;\n\n    if(argc == 1)\n        help();\n\n    for(; argv[1][0] == '-'; argc--, argv++)\n    {\n        if(strcmp(argv[1],\"-xy\") == 0)\n            mirror = 3;\n        ele if(strcmp(argv[1],\"-x\") == 0)\n            mirror |= 1;\n        else if(strcmp(argv[1],\"-y\") == 0)\n            mirror |= 2;\n        else if(strcmp(argv[1],\"-s\") == 0)\n            show = true;\n    }\n\n\tif(argc < 5)\n\t{\n        help();\n\t\treturn -1;\n\t}\n\n    std::string saveframe;\n    if(argc > 5)\n    {\n        if(strcmp(argv[5],\"-\") == 0)\n            show = true;\n        else\n            saveframe = argv[5];\n    }\n\n\tcv::Mat camera_matrix,dist_coeffs;\n\tcv::FileStorage camera_calibration_file(argv[1], cv::FileStorage::READ);\n    if (!camera_calibration_file.isOpened())\n    {\n    \tstd::cerr << \"wrong calibration file\" << std::endl;\n    \treturn -2;\n    }\n\tcamera_calibration_file[\"rgb_intrinsics\"] >> camera_matrix;\n\tcamera_calibration_file[\"rgb_distortion\"] >> dist_coeffs;\n\tif(!camera_matrix.rows || !dist_coeffs.rows)\n\t{\n\t\tstd::cerr << \"expected rgb_intrinsics or rgb_distortion in file\" << std::endl;\n\t\treturn -1;\n\t}\n\n\tfloat marker_size = atof(argv[2]);\n\n    if(atoi(argv[4]) != 0)\n    {\n        // setZero\n        for(int i = 0; i < dist_coeffs.cols; i++)\n            dist_coeffs.at<float>(i) = 0;\n    }\n\n    std::cout << \"K:\"<<camera_matrix << std::endl;\n    std::cout << \"dist:\"<<dist_coeffs << std::endl;\n    std::cout << \"marker_size:\"<<marker_size << std::endl;\n\n    cv::VideoCapture cap(argv[3]);\n    if(!cap.isOpened()) \n    {\n        std::cerr << \"wrong image/video file \" << argv[3] << std::endl;\n        return -3;\n    }\n\n\n    std::vector<aruco::Marker> markers;\n    aruco::MarkerDetector marker_detector;\n    marker_detector.setMinMaxSize(0.01,0.1);\n\n    cv::Mat frame;\n    bool singleframe = cap.get(CV_CAP_PROP_FRAME_COUNT) == 1;\n\n    std::ofstream onf((std::string(argv[3]) +\".json\").c_str());\n\n    for(;;)\n    {\n        cap >> frame;\n        if(frame.rows == 0)\n        {\n            break;\n        }\n        if(mirror != 0)\n        {\n            cv::Mat dst;\n            cv::flip(frame,dst,mirror == 1 ? 0 : mirror == 2 ? 1 : -1);\n            frame = dst; // ref\n        }\n        aruco::CameraParameters cp(camera_matrix,dist_coeffs, cv::Size(frame.cols,frame.rows));\n\n        marker_detector.detect(\n        \tframe, \n        \tmarkers, \n        \tcp,\n            marker_size, \n            y_axis_perpendicular);\n        double pmat[16];\n        cp.glGetProjectionMatrix(cp.CamSize,cp.CamSize,pmat,0.1,100,false);\n\n        // TODO YML output for frames\n        std::string xin = argv[3];\n        std::unique_ptr<cv::FileStorage> recreate;\n        if(singleframe)\n            recreate = std::unique_ptr<cv::FileStorage>(new cv::FileStorage(xin+\".yml\", cv::FileStorage::WRITE));\n\n        Json::Value jmarkers(Json::arrayValue);\n        int found = 0;\n\n        std::cout << \"frame\\n\";\n\n    \tfor (auto marker : markers)\n        {\n            if (!marker.isValid())\n            {\n                continue;\n            }\n            found++;\n            cv::Mat Rvec,Tvec;\n            auto e = calculateExtrinsics(marker,marker_size,camera_matrix,dist_coeffs,y_axis_perpendicular,Rvec,Tvec);\n\n            marker.draw(frame, cv::Scalar(0,0,255), 2);\n            aruco::CvDrawingUtils::draw3dAxis(frame, marker, cp);\n\n\n\n            Eigen::Matrix4d marker_pose = Eigen::Matrix4d::Identity();\n            marker_pose.block<3, 1>(0, 3) = Eigen::Vector3d(Tvec.at<float>(0),\n                                                  Tvec.at<float>(1),\n                                                  Tvec.at<float>(2));\n            cv::Mat marker_rot;\n            cv::Rodrigues(Rvec, marker_rot);\n            marker_pose(0, 0) = marker_rot.at<float>(0, 0);\n            marker_pose(0, 1) = marker_rot.at<float>(0, 1);\n            marker_pose(0, 2) = marker_rot.at<float>(0, 2);\n            marker_pose(1, 0) = marker_rot.at<float>(1, 0);\n            marker_pose(1, 1) = marker_rot.at<float>(1, 1);\n            marker_pose(1, 2) = marker_rot.at<float>(1, 2);\n            marker_pose(2, 0) = marker_rot.at<float>(2, 0);\n            marker_pose(2, 1) = marker_rot.at<float>(2, 1);\n            marker_pose(2, 2) = marker_rot.at<float>(2, 2);\n\n            //void eigen2cv(const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, Mat& dst)\n            cv::Mat marker_posecv(4,4,CV_32F);\n            //marker_rot.copyTo(marker_posecv(cv::Rect(0,0,3,3)));\n            //Tvec.copyTo(marker_posecv(cv::Rect(0,3,3,1)));\n            cv::eigen2cv(marker_pose,marker_posecv);\n\n            //cv::Mat cvT(4,4,CV_32FC1); \n            //Eigen::Map<Matrix4f> eigenT( cvT.data() ); \n\n            //std::cout << \"marker mid:\" << marker.id << \" error:\" << e << \"\\n\\tTvec:\" << Tvec << \"\\n\\tRvec:\" << Rvec << std::endl;\n\n    \t    double mat[16];\n            marker.glGetModelViewMatrix(mat);\n            cv::Point2f center = marker.getCenter();\n\n            Json::Value jmarker;\n            jmarker[\"id\"] = marker.id;\n            jmarker[\"center\"][0] = center.x;\n            jmarker[\"center\"][1] = center.y;\n            jmarker[\"error\"] = e;\n            jmarker[\"areapx\"] = marker.getArea();\n            jmarker[\"areau\"] = marker.getArea()/(cp.CamSize.width*cp.CamSize.height);\n            jmarker[\"Tvec\"][0] = Tvec.at<float>(0,0);\n            jmarker[\"Tvec\"][1] = Tvec.at<float>(1,0);\n            jmarker[\"Tvec\"][2] = Tvec.at<float>(2,0);\n            jmarker[\"Rvec\"][0] = Rvec.at<float>(0,0);\n            jmarker[\"Rvec\"][1] = Rvec.at<float>(1,0);\n            jmarker[\"Rvec\"][2] = Rvec.at<float>(2,0);\n            jmarker[\"pose\"] = mat2json(marker_pose);\n            jmarker[\"glmodelview\"] = vec2json(mat,16);\n            for(int q = 0; q < marker.size(); q++)\n            {\n                jmarker[\"points\"][q][0] = marker[q].x;\n                jmarker[\"points\"][q][1] = marker[q].y;\n            }\n            jmarker[\"points\"][(int)marker.size()][0] = center.x;\n            jmarker[\"points\"][(int)marker.size()][1] = center.y;\n            // and then the center\n            jmarkers.append(jmarker);\n            std::cout <<\" mid:\" << marker.id << \" error:\" << e << \" area:\" << marker.getArea() << std::endl;\n\n\n            //markerpose\n            //markerid\n            //markersize\n            //mode\n            if(recreate)\n            {\n                *recreate << ((std::ostringstream() << \"markerid\" << found ).str().c_str()) << marker.id;\n                *recreate << ((std::ostringstream() << \"markersize\" << found  ).str().c_str()) << marker_size;\n                *recreate << ((std::ostringstream() << \"markerpose\" << found  ).str().c_str()) << marker_posecv;\n                *recreate << ((std::ostringstream() << \"mode\" << found ).str().c_str()) << 3;\n                *recreate << ((std::ostringstream() << \"corners\" << found ).str().c_str()) << marker;\n            }\n        }\n\n        Json::Value jroot;\n        jroot[\"markers\"] = jmarkers;\n        jroot[\"glprojection\"] = vec2json(pmat,16);\n        jroot[\"K\"] = mat2json(camera_matrix);\n        jroot[\"dist\"] = mat2json(dist_coeffs);\n        jroot[\"markersize\"] = marker_size;\n        jroot[\"yaxisup\"] = y_axis_perpendicular;\n        jroot[\"imagesize\"][0] = cp.CamSize.width;\n        jroot[\"imagesize\"][1] = cp.CamSize.height;\n\n        // multiple frames == multiple JSON messages, one per line\n        onf << Json::FastWriter().write(jroot);\n        \n        if(show && found)\n        {\n            cv::imshow(\"ciao\",frame);\n            cv::waitKey(1);\n        }\n        if(!saveframe.empty() && found)\n        {\n            // Multiframe => overwrite\n            if(!singleframe)\n                std::cout << \"Warning: overwriting output \" << saveframe << std::endl;\n            cv::imwrite(saveframe.c_str(),frame);            \n        }\n    }\n    return 0;\n}", "meta": {"hexsha": "edb5b472a22481a6816e5f12638bd1bb6b95eea6", "size": 12054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "eruffaldi/arucojson", "max_stars_repo_head_hexsha": "a54f156954c2374b429031e3abb565fb10018a6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-05T12:49:44.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-05T12:49:44.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "eruffaldi/arucojson", "max_issues_repo_head_hexsha": "a54f156954c2374b429031e3abb565fb10018a6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "eruffaldi/arucojson", "max_forks_repo_head_hexsha": "a54f156954c2374b429031e3abb565fb10018a6e", "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.7554347826, "max_line_length": 187, "alphanum_fraction": 0.5345113655, "num_tokens": 3542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5306837330494996}}
{"text": "#pragma once\n#include \"numeric/dense.hpp\"\n#include <Eigen/Jacobi>\n\nnamespace cpb { namespace compute {\n\nnamespace detail {\n    template<class real_t>\n    static void tridiagonal_qr_step(real_t* diag, real_t* subdiag, int start, int end) {\n        auto td = (diag[end-1] - diag[end]) * real_t(0.5);\n        auto e = subdiag[end-1];\n        auto mu = diag[end];\n        if (td == 0) {\n            mu -= std::abs(e);\n        }\n        else {\n            auto e2 = Eigen::numext::abs2(subdiag[end-1]);\n            auto h = Eigen::numext::hypot(td, e);\n            if (e2 == 0)\n                mu -= (e / (td + (td>0 ? 1 : -1))) * (e / h);\n            else\n                mu -= e2 / (td + (td>0 ? h : -h));\n        }\n\n        auto x = diag[start] - mu;\n        auto z = subdiag[start];\n        for (auto k = start; k < end; ++k) {\n            Eigen::JacobiRotation<real_t> rot;\n            rot.makeGivens(x, z);\n\n            // do T = G' T G\n            auto sdk = rot.s() * diag[k] + rot.c() * subdiag[k];\n            auto dkp1 = rot.s() * subdiag[k] + rot.c() * diag[k+1];\n\n            diag[k] = rot.c() * (rot.c() * diag[k] - rot.s() * subdiag[k])\n                - rot.s() * (rot.c() * subdiag[k] - rot.s() * diag[k+1]);\n            diag[k+1] = rot.s() * sdk + rot.c() * dkp1;\n            subdiag[k] = rot.c() * sdk - rot.s() * dkp1;\n\n            if (k > start)\n                subdiag[k - 1] = rot.c() * subdiag[k-1] - rot.s() * z;\n\n            x = subdiag[k];\n            if (k < end - 1) {\n                z = -rot.s() * subdiag[k+1];\n                subdiag[k + 1] = rot.c() * subdiag[k+1];\n            }\n        }\n    }\n}\n\ntemplate<class Derived, class scalar_t = typename Derived::Scalar>\ninline ArrayX<scalar_t> tridiagonal_eigenvalues(const DenseBase<Derived>& alpha,\n                                                const DenseBase<Derived>& beta)\n{\n    ArrayX<scalar_t> eigenvalues = alpha;\n    ArrayX<scalar_t> temp = beta;\n\n    auto start = 0;\n    auto end = static_cast<int>(eigenvalues.size()) - 1;\n    auto iter = 0;\n    constexpr auto max_iterations = 30;\n\n    while (end > 0) {\n        for (auto i = start; i < end; ++i) {\n            auto a = std::abs(temp[i]);\n            auto b = std::abs(eigenvalues[i]) + std::abs(eigenvalues[i + 1]);\n            // if a is much smaller than b\n            if (a < b * std::numeric_limits<scalar_t>::epsilon())\n                temp[i] = 0;\n        }\n\n        while (end > 0 && temp[end-1] == 0)\n            end--;\n\n        if (end <= 0)\n            break;\n\n        if (++iter > max_iterations * eigenvalues.size())\n            throw std::runtime_error{\"Tridiagonal QR error\"};\n\n        start = end - 1;\n        while (start > 0 && temp[start-1] != 0)\n            start--;\n\n        detail::tridiagonal_qr_step(eigenvalues.data(), temp.data(), start, end);\n    }\n\n    return eigenvalues;\n}\n\n}} // namespace cpb::compute\n", "meta": {"hexsha": "4ebed5318664fa0fb6450951efa1c485035c9ac0", "size": 2873, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cppcore/include/compute/eigen3/lanczos.hpp", "max_stars_repo_name": "lise1020/pybinding", "max_stars_repo_head_hexsha": "921d5c2ac0ecc0ef317ba28b0bf68899ea30709a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 159.0, "max_stars_repo_stars_event_min_datetime": "2016-01-20T17:40:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T06:08:55.000Z", "max_issues_repo_path": "cppcore/include/compute/eigen3/lanczos.hpp", "max_issues_repo_name": "deilynazar/pybinding", "max_issues_repo_head_hexsha": "ec1128aaa84a1b43a74fb970479ce4544bd63179", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 36.0, "max_issues_repo_issues_event_min_datetime": "2016-11-01T17:15:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T14:31:51.000Z", "max_forks_repo_path": "cppcore/include/compute/eigen3/lanczos.hpp", "max_forks_repo_name": "deilynazar/pybinding", "max_forks_repo_head_hexsha": "ec1128aaa84a1b43a74fb970479ce4544bd63179", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 57.0, "max_forks_repo_forks_event_min_datetime": "2016-04-23T22:12:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:33:04.000Z", "avg_line_length": 30.8924731183, "max_line_length": 88, "alphanum_fraction": 0.4712843717, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5305900933673838}}
{"text": "#include \"../include/simple_fft/fft_settings.h\"\n\n#ifdef __USE_SQUARE_BRACKETS_FOR_ELEMENT_ACCESS_OPERATOR\n#undef __USE_SQUARE_BRACKETS_FOR_ELEMENT_ACCESS_OPERATOR\n#endif\n\n#include \"../include/simple_fft/fft.h\"\n#include \"test_fft.h\"\n#include <iostream>\n#include <blitz/array.h>\n\nnamespace simple_fft {\nnamespace fft_test {\n\nint testBlitz()\n{\n    std::cout << \"Testing FFT algorithms with blitz\" << std::endl;\n\n    using namespace pulse_params;\n\n    std::vector<real_type> t, x, y;\n    makeGridsForPulse3D(t, x, y);\n\n    // typedefing arrays\n    typedef blitz::Array<real_type,int(1)> RealArray1D;\n    typedef blitz::Array<complex_type,int(1)> ComplexArray1D;\n    typedef blitz::Array<real_type,int(2)> RealArray2D;\n    typedef blitz::Array<complex_type,int(2)> ComplexArray2D;\n    typedef blitz::Array<real_type,int(3)> RealArray3D;\n    typedef blitz::Array<complex_type,int(3)> ComplexArray3D;\n\n    // 1D fields and spectrum\n    RealArray1D E1_real(nt);\n    ComplexArray1D E1_complex(nt), G1(nt), E1_restored(nt);\n\n    // 2D fields and spectrum,\n    RealArray2D E2_real(nt,nx);\n    ComplexArray2D E2_complex(nt,nx), G2(nt,nx), E2_restored(nt,nx);\n\n    // 3D fields and spectrum\n    RealArray3D E3_real(nt,nx,ny);\n    ComplexArray3D E3_complex(nt,nx,ny), G3(nt,nx,ny), E3_restored(nt,nx,ny);\n\n    if (!commonPartsForTests3D(E1_real, E2_real, E3_real, E1_complex, E2_complex,\n                               E3_complex, G1, G2, G3, E1_restored, E2_restored,\n                               E3_restored, t, x, y))\n    {\n        std::cout << \"Tests of FFT with blitz++ arrays returned with errors!\" << std::endl;\n        return FAILURE;\n    }\n\n    std::cout << \"Tests of FFT with blitz++ arrays completed successfully!\" << std::endl;\n    return SUCCESS;\n}\n\n} // namespace fft_test\n} // namespace simple_fft\n", "meta": {"hexsha": "dadbb1bf5042b1999538ccb34fa5c9afff364f62", "size": 1801, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit-tests/test_with_blitz.cpp", "max_stars_repo_name": "opalcompany/Simple-FFT", "max_stars_repo_head_hexsha": "5f397670ecac53c68ab1df90c36a319bd277b5d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T23:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T01:09:49.000Z", "max_issues_repo_path": "unit-tests/test_with_blitz.cpp", "max_issues_repo_name": "opalcompany/Simple-FFT", "max_issues_repo_head_hexsha": "5f397670ecac53c68ab1df90c36a319bd277b5d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-07-26T21:42:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T20:24:03.000Z", "max_forks_repo_path": "unit-tests/test_with_blitz.cpp", "max_forks_repo_name": "opalcompany/Simple-FFT", "max_forks_repo_head_hexsha": "5f397670ecac53c68ab1df90c36a319bd277b5d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-03-20T14:41:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T09:51:54.000Z", "avg_line_length": 31.0517241379, "max_line_length": 91, "alphanum_fraction": 0.6840644087, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.530564486081205}}
{"text": "#include <stan/math/mix/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <test/unit/math/rev/scal/fun/util.hpp>\n#include <test/unit/math/mix/scal/fun/nan_util.hpp>\n\n\nTEST(AgradFwdLmgamma,FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::lmgamma;\n\n  fvar<var> x(3.2,2.1);\n  fvar<var> a = lmgamma(3, x);\n\n  EXPECT_FLOAT_EQ(lmgamma(3,3.2), a.val_.val());\n  EXPECT_FLOAT_EQ(4.9138227, a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(4.9138227 / 2.1, g[0]);\n}\nTEST(AgradFwdLmgamma,FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::lmgamma;\n\n  fvar<var> x(3.2,2.1);\n  fvar<var> a = lmgamma(3, x);\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(2.9115787, g[0]);\n}\nTEST(AgradFwdLmgamma,FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::lmgamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.2;\n  x.val_.d_ = 2.1;\n\n  fvar<fvar<var> > a = lmgamma(3,x);\n\n  EXPECT_FLOAT_EQ(lmgamma(3,3.2), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(4.9138227, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(4.9138227 / 2.1, g[0]);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 3.2;\n  y.d_.val_ = 2.1;\n\n  fvar<fvar<var> > b = lmgamma(3,y);\n  EXPECT_FLOAT_EQ(lmgamma(3,3.2), b.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, b.val_.d_.val());\n  EXPECT_FLOAT_EQ(4.9138227, b.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, b.d_.d_.val());\n\n  AVEC q = createAVEC(y.val_.val_);\n  VEC r;\n  b.val_.val_.grad(q,r);\n  EXPECT_FLOAT_EQ(4.9138227 / 2.1, r[0]);\n}\nTEST(AgradFwdLmgamma,FvarFvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::lmgamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.2;\n  x.val_.d_ = 2.1;\n\n  fvar<fvar<var> > a = lmgamma(3,x);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(2.9115787, g[0]);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 3.2;\n  y.d_.val_ = 2.1;\n\n  fvar<fvar<var> > b = lmgamma(3,y);\n\n  AVEC q = createAVEC(y.val_.val_);\n  VEC r;\n  b.d_.val_.grad(q,r);\n  EXPECT_FLOAT_EQ(2.9115787, r[0]);\n}\nTEST(AgradFwdLmgamma,FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.2;\n  x.val_.d_ = 1.0;\n  x.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = stan::math::lmgamma(3,x);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.65043455, g[0]);\n}\n\nstruct lmgamma_fun {\n  template <typename T0>\n  inline T0\n  operator()(const T0& arg1) const {\n    return lmgamma(3,arg1);\n  }\n};\n\nTEST(AgradFwdLmgamma,lmgamma_NaN) {\n  lmgamma_fun lmgamma_;\n  test_nan_mix(lmgamma_,false);\n}\n", "meta": {"hexsha": "a67ecae6cc5f4cb9e21e022026b2309cd166da99", "size": 2874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/mix/scal/fun/lmgamma_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/mix/scal/fun/lmgamma_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/mix/scal/fun/lmgamma_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2790697674, "max_line_length": 54, "alphanum_fraction": 0.6454418928, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.530564481062044}}
{"text": "/*\r\nMIT License\r\n\r\nCopyright (c) 2019 Kalu U. Ogbureke\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n\r\nAuthors: Kalu U. Ogbureke\r\nChange Log: 01.04.2019 - Version 1.0.0\r\n*/\r\n#define BOOST_TEST_MODULE unitTest\r\n#include <boost/test/included/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <cmath>\r\n#include \"libutil.h\"\r\n#include \"network.h\"\r\n#include \"data_reader.h\"\r\n\r\nusing namespace mlearn;\r\ntemplate <class T>\r\n/**\r\n    A helper function used to validate/test if 2 vectors contain the same elements.\r\n\r\n    @param v1 First vector\r\n    @param v1 Second vector\r\n\r\n    @return A boolean value (true or false)\r\n*/\r\nboost::test_tools::predicate_result validateVector(const mublas::vector<T>& v1,  const mublas::vector<T>& v2)\r\n{\r\n    if (v1.size() != v2.size()) return false;\r\n    for (uint64_t i = 0; i < v1.size(); ++i)\r\n    {\r\n        if (fabs(v1[i] - v2[i]) > EPSILON)\r\n        {\r\n            return false;\r\n        }\r\n    }\r\n    return true;\r\n}\r\n/**\r\n    Unit test for the Node class. Tests constructors and operators.\r\n*/\r\nBOOST_AUTO_TEST_SUITE (NodeSuite)\r\nBOOST_AUTO_TEST_CASE(contructor_test)\r\n{\r\n    std::cout << \"Start Node class test\" << std::endl;\r\n    std::vector<int> sv1 {1, 2, 3, 4};\r\n    std::vector<double> sv2{2, 3, 4.0, 2};\r\n    std::vector<int> sv3{0, 0, 0, 0, 0};\r\n\r\n    mublas::vector<int> v1(sv1.size());\r\n    mublas::vector<double> v2(sv2.size());\r\n    mublas::vector<int> v3(sv3.size());\r\n\r\n    std::copy(sv1.begin(), sv1.end(), v1.begin());\r\n    std::copy(sv2.begin(), sv2.end(), v2.begin());\r\n    std::copy(sv3.begin(), sv3.end(), v3.begin());\r\n\r\n    Node<int> n1(v1);\r\n    Node<double> n2(v2);\r\n    Node<double> n3;\r\n    Node<int> n4{n1};\r\n    Node<int> n5(5);\r\n    BOOST_CHECK(validateVector(v1, n1.getData()));\r\n    BOOST_CHECK(validateVector(v1, n4.getData()));\r\n    BOOST_CHECK(validateVector(v2, n2.getData()));\r\n    BOOST_CHECK(n3.getDataSize() == 0);\r\n    BOOST_CHECK(n4.getDataSize() == n1.getDataSize());\r\n    BOOST_CHECK(validateVector(v3, n5.getData()));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(operator_test)\r\n{\r\n\r\n    std::vector<double> sv1 {1.2, 2.3, 3.0, 4.1};\r\n    std::vector<double> sv2{2, 3, 4.0, 2};\r\n    std::vector<double> sv3{3.2, 5.3, 7.0, 6.1};\r\n    std::vector<double> sv4 {1.2, 2.3, 3, 4.1};\r\n    std::vector<double> sv5 {2.4, 6.9, 12.0, 8.2};\r\n    std::vector<double> sv6 {4.8, 13.8, 24.0, 16.4};\r\n\r\n    mublas::vector<double> v1(sv1.size());\r\n    mublas::vector<double> v2(sv2.size());\r\n    mublas::vector<double> v3(sv3.size());\r\n    mublas::vector<double> v4(sv4.size());\r\n    mublas::vector<double> v5(sv5.size());\r\n    mublas::vector<double> v6(sv6.size());\r\n\r\n    std::copy(sv1.begin(), sv1.end(), v1.begin());\r\n    std::copy(sv2.begin(), sv2.end(), v2.begin());\r\n    std::copy(sv3.begin(), sv3.end(), v3.begin());\r\n    std::copy(sv4.begin(), sv4.end(), v4.begin());\r\n    std::copy(sv5.begin(), sv5.end(), v5.begin());\r\n    std::copy(sv6.begin(), sv6.end(), v6.begin());\r\n\r\n    Node<double> n1(v1);\r\n    Node<double> n2(v2);\r\n    //operator+\r\n    Node<double> n3 = n1 + n2;\r\n    BOOST_CHECK(validateVector(v3, n3.getData()));\r\n    //operator-\r\n    Node<double> n4 = n3 - n2;\r\n\r\n    BOOST_CHECK(validateVector(v1, n4.getData()));\r\n    //operator*\r\n    Node<double> n5 = n2 * n4;\r\n    BOOST_CHECK(validateVector(v5, n5.getData()));\r\n    //operator=\r\n    n4 = n5;\r\n    BOOST_CHECK(validateVector(n4.getData(), n5.getData()));\r\n    BOOST_CHECK(n4.getDataSize() == n5.getDataSize());\r\n    //scalarMultiply\r\n    Node<double> n6 = n5.scalarMultiply(2);\r\n    BOOST_CHECK(validateVector(v6, n6.getData()));\r\n    //sum\r\n    BOOST_CHECK(n6.sum() == 59);\r\n    std::cout << \"End Node class test\" << std::endl;\r\n\r\n}\r\nBOOST_AUTO_TEST_SUITE_END()\r\n\r\n/**\r\n    Unit test for the NetNode class. Tests constructors and operators.\r\n*/\r\nBOOST_AUTO_TEST_SUITE (NetNodeSuite)\r\nBOOST_AUTO_TEST_CASE(contructor_test)\r\n{\r\n    std::cout << \"Start NetNode class test\" << std::endl;\r\n    std::vector<int> sv1 {1, 2, 3, 4};\r\n    std::vector<double> sv2{2, 3, 4.0, 2};\r\n    std::vector<int> sv3{0, 0, 0, 0, 0};\r\n\r\n    mublas::vector<int> v1(sv1.size());\r\n    mublas::vector<double> v2(sv2.size());\r\n    mublas::vector<int> v3(sv3.size());\r\n\r\n    std::copy(sv1.begin(), sv1.end(), v1.begin());\r\n    std::copy(sv2.begin(), sv2.end(), v2.begin());\r\n    std::copy(sv3.begin(), sv3.end(), v3.begin());\r\n\r\n    NetNode<int> n1(v1);\r\n    NetNode<double> n2(v2);\r\n    NetNode<double> n3;\r\n    NetNode<int> n4{n1};\r\n    NetNode<int> n5(5);\r\n    BOOST_CHECK(validateVector(v1, n1.getData()));\r\n    BOOST_CHECK(validateVector(v1, n4.getData()));\r\n    BOOST_CHECK(validateVector(v2, n2.getData()));\r\n    BOOST_CHECK(n3.getDataSize() == 0);\r\n    BOOST_CHECK(n4.getDataSize() == n1.getDataSize());\r\n    BOOST_CHECK(validateVector(v3, n5.getData()));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(operator_test)\r\n{\r\n    std::vector<double> sv1 {1.2, 2.3, 3.0, 4.1};\r\n    std::vector<double> sv2{2, 3, 4.0, 2};\r\n    std::vector<double> sv3{3.2, 5.3, 7.0, 6.1};\r\n    std::vector<double> sv4 {1.2, 2.3, 3, 4.1};\r\n    std::vector<double> sv5 {2.4, 6.9, 12.0, 8.2};\r\n    std::vector<double> sv6 {4.8, 13.8, 24.0, 16.4};\r\n    std::vector<double> sv7 {0.76852478, 0.90887704, 0.95257413, 0.9836975};\r\n    std::vector<double> sv8 {0.17789444, 0.08281957, 0.04517666, 0.01603673};\r\n\r\n    mublas::vector<double> v1(sv1.size());\r\n    mublas::vector<double> v2(sv2.size());\r\n    mublas::vector<double> v3(sv3.size());\r\n    mublas::vector<double> v4(sv4.size());\r\n    mublas::vector<double> v5(sv5.size());\r\n    mublas::vector<double> v6(sv6.size());\r\n    mublas::vector<double> v7(sv7.size());\r\n    mublas::vector<double> v8(sv8.size());\r\n\r\n    std::copy(sv1.begin(), sv1.end(), v1.begin());\r\n    std::copy(sv2.begin(), sv2.end(), v2.begin());\r\n    std::copy(sv3.begin(), sv3.end(), v3.begin());\r\n    std::copy(sv4.begin(), sv4.end(), v4.begin());\r\n    std::copy(sv5.begin(), sv5.end(), v5.begin());\r\n    std::copy(sv6.begin(), sv6.end(), v6.begin());\r\n    std::copy(sv7.begin(), sv7.end(), v7.begin());\r\n    std::copy(sv8.begin(), sv8.end(), v8.begin());\r\n\r\n    NetNode<double> n1(v1);\r\n    NetNode<double> n2(v2);\r\n    //operator+\r\n    NetNode<double> n3 = n1 + n2;\r\n    BOOST_CHECK(validateVector(v3, n3.getData()));\r\n    //operator-\r\n    NetNode<double> n4 = n3 - n2;\r\n\r\n    BOOST_CHECK(validateVector(v4, n4.getData()));\r\n    BOOST_CHECK(validateVector(v4, n1.getData()));\r\n    //operator*\r\n    NetNode<double> n5 = n2 * n4;\r\n    BOOST_CHECK(validateVector(v5, n5.getData()));\r\n    //operator=   not working. Fix!\r\n    //n4 = n5;\r\n    //scalarMultiply\r\n    NetNode<double> n6 = n5.scalarMultiply(2);\r\n    BOOST_CHECK(validateVector(v6, n6.getData()));\r\n    // sum\r\n    BOOST_CHECK(n6.sum() == 59);\r\n    //sigmoid\r\n    NetNode<double> n7 = n1.sigmoid();\r\n    BOOST_CHECK(validateVector(v7, n7.getData()));\r\n    //sigmoidPrime\r\n    NetNode<double> n8 = n7.sigmoidPrime();\r\n    BOOST_CHECK(validateVector(v8, n8.getData()));\r\n    std::cout << \"End NetNode class test\" << std::endl;\r\n}\r\nBOOST_AUTO_TEST_SUITE_END()\r\n\r\n/**\r\n    Unit test for the Activation class. Performs general tests.\r\n*/\r\nBOOST_AUTO_TEST_SUITE (ActivationSuite)\r\nBOOST_AUTO_TEST_CASE(general_test)\r\n{\r\n    std::cout << \"Start Activation class test\" << std::endl;\r\n    std::vector<double> sv1 {1.2, 2.3, 3.0, 4.1};\r\n    std::vector<double> sv2{0.76852478, 0.90887704, 0.95257413, 0.9836975};\r\n    std::vector<double> sv3{1.2, 2.3, 3.0, 4.1};\r\n    std::vector<double> sv4{0.17789444, 0.08281957, 0.04517666, 0.01603673};\r\n\r\n    mublas::vector<double> v1(sv1.size());\r\n    mublas::vector<double> v2(sv2.size());\r\n    mublas::vector<double> v3(sv3.size());\r\n    mublas::vector<double> v4(sv4.size());\r\n\r\n    std::copy(sv1.begin(), sv1.end(), v1.begin());\r\n    std::copy(sv2.begin(), sv2.end(), v2.begin());\r\n    std::copy(sv3.begin(), sv3.end(), v3.begin());\r\n    std::copy(sv4.begin(), sv4.end(), v4.begin());\r\n\r\n    NetNode<double> n1(v1);\r\n    NetNode<double> n3(v3);\r\n    Activation<double> act(\"sigmoid\");\r\n    act.compute(n1);\r\n    BOOST_CHECK(validateVector(v2, n1.getData()));\r\n    //computeDerivative\r\n    act.computeDerivative(n1);\r\n    BOOST_CHECK(validateVector(v4, n1.getData()));\r\n    //softmax\r\n    mublas::vector<double> v5(2), v6(2);\r\n    v5[0] = 1.0, v5[1] = 2.0, v6[0] = 0.26894142, v6[1] = 0.73105858;\r\n    //compute\r\n    Activation<double> soft_act(\"softmax\");\r\n    NetNode<double> n5(v5);\r\n    soft_act.compute(n5);\r\n    BOOST_CHECK(validateVector(v6, n5.getData()));\r\n    //computeDerivative\r\n    mublas::matrix<double> m1(2, 2);\r\n    soft_act.computeDerivative(n5, m1);\r\n    //std::cout <<m1 <<std::endl; //[2,2]((0.196612,-0.196612),(-0.196612,0.196612))\r\n    std::cout << \"End Activation class test\" << std::endl;\r\n}\r\nBOOST_AUTO_TEST_SUITE_END()\r\n\r\n/**\r\n    Unit test for the Layer class. Performs general tests.\r\n*/\r\nBOOST_AUTO_TEST_SUITE (LayerSuite)\r\nBOOST_AUTO_TEST_CASE(general_test)\r\n{\r\n    std::cout << \"Start Layer class test\" << std::endl;\r\n    std::vector<double> ax{0, 0}, bx{0, 1}, cx{1, 0}, dx{1, 1};\r\n    std::vector<double> ay{0}, by{1}, cy{1}, dy{1};\r\n    std::vector<double> sv1{-0.7, 0.8}, sv2{0.66}, sv3{0, 0}, sv4{0.331812, 0.689974}, sv5{0.763192}, sv6{-0.76};\r\n    std::vector<double> sv7 {-0.14};\r\n    std::vector<double> sv8 {-0.03, -0.01};\r\n\r\n    mublas::vector<double> v1(sv1.size());\r\n    mublas::vector<double> v2(sv2.size());\r\n    mublas::vector<double> v3(sv3.size());\r\n    mublas::vector<double> v4(sv4.size());\r\n    mublas::vector<double> v5(sv5.size());\r\n    mublas::vector<double> v6(sv6.size());\r\n    mublas::vector<double> v7(sv7.size());\r\n    mublas::vector<double> v8(sv8.size());\r\n\r\n    std::copy(sv1.begin(), sv1.end(), v1.begin());\r\n    std::copy(sv2.begin(), sv2.end(), v2.begin());\r\n    std::copy(sv3.begin(), sv3.end(), v3.begin());\r\n    std::copy(sv4.begin(), sv4.end(), v4.begin());\r\n    std::copy(sv5.begin(), sv5.end(), v5.begin());\r\n    std::copy(sv6.begin(), sv6.end(), v6.begin());\r\n    std::copy(sv7.begin(), sv7.end(), v7.begin());\r\n    std::copy(sv8.begin(), sv8.end(), v8.begin());\r\n\r\n    Activation<double> hidden(\"sigmoid\"), output(\"sigmoid\");\r\n    Layer<double> hidden_layer(2, 2, \"hidden\", hidden);\r\n    Layer<double> output_layer(2, 1, \"output\", output);\r\n    std::unique_ptr<std::vector<double>> v_ptr1(new std::vector<double>{0.62, 0.55});\r\n    std::unique_ptr<std::vector<double>> v_ptr2(new std::vector<double>{0.42, -0.17});\r\n    std::unique_ptr<std::vector<double>> v_ptr3(new std::vector<double>{0.81, 0.35});\r\n    std::unique_ptr<NetNode<double>> v_ptr4(new NetNode<double>{v1});\r\n    std::unique_ptr<NetNode<double>> v_ptr5(new NetNode<double>{v2});\r\n    std::unique_ptr<NetNode<double>> v_ptr6(new NetNode<double>{v3});\r\n    std::unique_ptr<NetNode<double>> v_ptr7(new NetNode<double>{v6});\r\n    hidden_layer.push_row(0, *v_ptr1);\r\n    hidden_layer.push_row(1, *v_ptr2);\r\n    output_layer.push_row(0, *v_ptr3);\r\n    hidden_layer.setBias(*v_ptr4);\r\n    output_layer.setBias(*v_ptr5);\r\n\r\n    output_layer.connect(hidden_layer);\r\n    hidden_layer.setInputData(*v_ptr6);\r\n    NetNode<double> n1 = hidden_layer.forwardProp();\r\n    NetNode<double> n2 = output_layer.forwardProp();\r\n    BOOST_CHECK(validateVector(v4, n1.getData()));\r\n    BOOST_CHECK(validateVector(v5, n2.getData()));\r\n    //backwardProp()\r\n    output_layer.setInputDelta(*v_ptr7);\r\n    NetNode<double> n3 = output_layer.backwardProp();\r\n    NetNode<double> n4 = hidden_layer.backwardProp();\r\n\r\n    BOOST_CHECK(validateVector(v7, n3.getData()));\r\n    BOOST_CHECK(validateVector(v8, n4.getData()));\r\n    hidden_layer.clearDeltas();\r\n    mublas::matrix<double> m1 = hidden_layer.getDeltaWeight();\r\n    //std::cout<<m1<<std::endl; //should print zero matrix\r\n    NetNode<double> n5 = hidden_layer.getDeltaBias();\r\n    BOOST_CHECK(validateVector(v3, n5.getData()));\r\n    std::cout << \"End Activation class test\" << std::endl;\r\n}\r\nBOOST_AUTO_TEST_SUITE_END()\r\n/**\r\n    Unit test for the DataReader class. Performs general tests.\r\n*/\r\nBOOST_AUTO_TEST_SUITE (ReaderSuite)\r\nBOOST_AUTO_TEST_CASE(mnist_test)\r\n{\r\n\r\n    std::cout << \"Start Reader class test\" << std::endl;\r\n    MNIST_CIFARReader<double> mnist(\"data/mnist_sample.csv\", 784, 10, ',',  false), train(\"data/mnist_train.csv\", 784, 10, ',',  false), test, test2;\r\n    mnist.read();\r\n    BOOST_CHECK(mnist.getFeatureDim() == 784);\r\n    BOOST_CHECK(mnist.getLabelDim() == 10);\r\n    BOOST_CHECK(mnist.getRowDim() == 10);\r\n    //constructor\r\n    MNIST_CIFARReader<double> mnist2(mnist);\r\n    BOOST_CHECK(mnist.getFeatureDim() == mnist2.getFeatureDim());\r\n    BOOST_CHECK(mnist.getLabelDim() == mnist2.getLabelDim() );\r\n    BOOST_CHECK(mnist.getRowDim() == mnist2.getRowDim());\r\n    //shuffleIndex\r\n    std::vector<int> indices;\r\n    mnist.shuffleIndex(indices);\r\n    mnist.trainTestSplit(test, 0.2);\r\n    BOOST_CHECK(mnist.getFeatureDim() == 784);\r\n    BOOST_CHECK(mnist.getLabelDim() == 10);\r\n    BOOST_CHECK(mnist.getRowDim() == 8);\r\n    BOOST_CHECK(test.getFeatureDim() == 784);\r\n    BOOST_CHECK(test.getLabelDim() == 10);\r\n    BOOST_CHECK(test.getRowDim() == 2);\r\n    train.read();\r\n    train.trainTestSplit(test2, 0.1);\r\n    BOOST_CHECK(train.getFeatureDim() == 784);\r\n    BOOST_CHECK(train.getLabelDim() == 10);\r\n    BOOST_CHECK(train.getRowDim() == 54000);\r\n    BOOST_CHECK(test2.getFeatureDim() == 784);\r\n    BOOST_CHECK(test2.getLabelDim() == 10);\r\n    BOOST_CHECK(test2.getRowDim() == 6000);\r\n}\r\nBOOST_AUTO_TEST_CASE(general_test)\r\n{\r\n    GenericReader<double> data(\"data/xor.dat\", 2, 1, ' ', false);\r\n    data.read();\r\n    BOOST_CHECK(data.getFeatureDim() == 2);\r\n    BOOST_CHECK(data.getLabelDim() == 1);\r\n    BOOST_CHECK(data.getRowDim() == 12);\r\n    //shuffleIndex\r\n    std::vector<int> indices;\r\n    data.shuffleIndex(indices);\r\n    //////////////////////////////////////////////////////\r\n    GenericReader<double> test(\"data/xor_header.dat\", 2, 2, ' ', true);\r\n    test.read();\r\n    BOOST_CHECK(test.getFeatureDim() == 2);\r\n    BOOST_CHECK(test.getLabelDim() == 2);\r\n    BOOST_CHECK(test.getRowDim() == 12);\r\n    std::cout << \"End Reader class test\" << std::endl;\r\n}\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "e138111fa4fe7d40569d26bf6f85bf8bdeb72691", "size": 15081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit_test_suite.cpp", "max_stars_repo_name": "kalu-o/mLEARn", "max_stars_repo_head_hexsha": "43185edc48c2558fdd6a0ae8b97c3945672d1467", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-05-21T16:16:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T13:33:09.000Z", "max_issues_repo_path": "tests/unit_test_suite.cpp", "max_issues_repo_name": "labarba/mLEARn", "max_issues_repo_head_hexsha": "d731915c5b5143c71b8c60dc48772347a502d213", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-10-23T09:51:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-05T17:04:09.000Z", "max_forks_repo_path": "tests/unit_test_suite.cpp", "max_forks_repo_name": "labarba/mLEARn", "max_forks_repo_head_hexsha": "d731915c5b5143c71b8c60dc48772347a502d213", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-21T16:00:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T18:38:22.000Z", "avg_line_length": 37.7025, "max_line_length": 150, "alphanum_fraction": 0.6288044559, "num_tokens": 4508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.5305644760428829}}
{"text": "/*\n * Copyright (c) 2020, Eberty Alves\n */\n\n// C++ standard library\n#include <bits/stdc++.h>\n\n// Point cloud library\n#include <pcl/io/ply_io.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n\n#include <pcl/common/transforms.h>\n#include <pcl/common/centroid.h>\n\n// Boost library\n#include <boost/program_options.hpp>\n\n// Typedefs\ntypedef pcl::PointXYZRGBNormal PointT;\ntypedef pcl::PointCloud<PointT> PointC;\n\nint main(int argc, char* argv[]) {\n  try {\n    // Declaration of variables\n    std::string src_file_name;\n    std::string tgt_file_name;\n    std::string output_file_name;\n\n    std::string accumulated_file_name;\n    bool b_accumulated_file;\n\n    double roll;\n    double pitch;\n    double yaw;\n    double elevation;\n\n    // Parse command-line options\n    namespace po = boost::program_options;\n\n    // Define command-line options\n    po::options_description desc(\"Options\");\n    desc.add_options()\n    (\"help,h\", \"Print help message\")\n    (\"input,i\", po::value<std::string>(&src_file_name)->required(), \"Input cloud file (.ply)\")\n    (\"target,t\", po::value<std::string>(&tgt_file_name)->required(), \"Input target file (.ply)\")\n    (\"output,o\", po::value<std::string>(&output_file_name)->required(), \"Output file (.ply)\")\n    (\"accumulated,a\", po::value<std::string>(&accumulated_file_name), \"Saves the accumulated point cloud in a .ply file\")\n    (\"roll,r\", po::value<double>(&roll)->default_value(0.0), \"Rotation in X - degrees (Roll)\")\n    (\"pitch,p\", po::value<double>(&pitch)->default_value(0.0), \"Rotation in Y - degrees (Pitch)\")\n    (\"yaw,y\", po::value<double>(&yaw)->default_value(0.0), \"Rotation in Z - degrees (Yaw)\")\n    (\"elevation,e\", po::value<double>(&elevation)->default_value(0.0), \"Translation in Y\");\n\n    // Use a parser to evaluate the command line\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n\n    // Store the command-line options evaluated by the parser\n    if (vm.count(\"help\")) {\n      std::cout << \"Rotation tool to translate one point cloud with regard to one reference point cloud.\" << std::endl << std::endl;\n      std::cout << desc << std::endl;\n      return 0;\n    }\n\n    if (vm.count(\"input\") && vm.count(\"target\") && vm.count(\"output\")) {\n      src_file_name = vm[\"input\"].as<std::string>();\n      tgt_file_name = vm[\"target\"].as<std::string>();\n      output_file_name = vm[\"output\"].as<std::string>();\n    } else {\n      throw std::string(\"Correct mode of use: \" + std::string(argv[0]) + \" -i input.ply -t target.ply -o output.ply [opts]\");\n    }\n\n    b_accumulated_file = vm.count(\"accumulated\");\n    if (b_accumulated_file) {\n      accumulated_file_name = vm[\"accumulated\"].as<std::string>();\n    }\n\n    roll = vm[\"roll\"].as<double>();\n    pitch = vm[\"pitch\"].as<double>();\n    yaw = vm[\"yaw\"].as<double>();\n    elevation = vm[\"elevation\"].as<double>();\n\n    PointC::Ptr cloud_src(new PointC);\n    PointC::Ptr cloud_tgt(new PointC);\n\n    // Load point clouds data from disk\n    if (pcl::io::loadPLYFile<PointT>(src_file_name, *cloud_src) == -1) {\n      throw std::string(\"Couldn't load input cloud file\");\n    }\n    std::cout << \"Loaded \" << cloud_src->size() << \" data points from \" << src_file_name << std::endl;\n\n    if (pcl::io::loadPLYFile<PointT>(tgt_file_name, *cloud_tgt) == -1) {\n      throw std::string(\"Couldn't load input target file\");\n    }\n    std::cout << \"Loaded \" << cloud_tgt->size() << \" data points from \" << tgt_file_name << std::endl;\n\n    Eigen::Affine3f transform;\n\n    // Translate point cloud centroid to origin\n    Eigen::Vector4f src_centroid;\n    pcl::compute3DCentroid(*cloud_src, src_centroid);\n    transform = Eigen::Affine3f::Identity();\n    transform.translation() << -src_centroid[0], -src_centroid[1], -src_centroid[2];\n    pcl::transformPointCloudWithNormals(*cloud_src, *cloud_src, transform);\n\n    // Rotation\n    transform = Eigen::Affine3f::Identity();\n    Eigen::Matrix3f rotation;\n    rotation = Eigen::AngleAxisf(DEG2RAD(roll), Eigen::Vector3f::UnitX()) *\n               Eigen::AngleAxisf(DEG2RAD(pitch), Eigen::Vector3f::UnitY()) *\n               Eigen::AngleAxisf(DEG2RAD(yaw), Eigen::Vector3f::UnitZ());\n    transform.rotate(rotation);\n    pcl::transformPointCloudWithNormals(*cloud_src, *cloud_src, transform);\n\n    // Translate src point cloud centroid to tgt centroid\n    Eigen::Vector4f tgt_centroid;\n    pcl::compute3DCentroid(*cloud_tgt, tgt_centroid);\n    transform = Eigen::Affine3f::Identity();\n    transform.translation() << tgt_centroid[0], tgt_centroid[1], tgt_centroid[2];\n    pcl::transformPointCloudWithNormals(*cloud_src, *cloud_src, transform);\n\n    // Translate src point cloud in Y axis\n    transform = Eigen::Affine3f::Identity();\n    transform.translation() << 0, elevation, 0;\n    pcl::transformPointCloudWithNormals(*cloud_src, *cloud_src, transform);\n\n    pcl::io::savePLYFileBinary(output_file_name, *cloud_src);\n\n    if (b_accumulated_file) {\n      PointC::Ptr accumulated(new PointC);\n      pcl::copyPointCloud(*cloud_src, *accumulated);\n      *accumulated += *cloud_tgt;\n      pcl::io::savePLYFileBinary(accumulated_file_name, *accumulated);\n    }\n\n    return 0;\n  } catch (boost::program_options::error& msg) {\n    std::cerr << \"ERROR: \" << msg.what() << std::endl;\n  } catch (std::string msg) {\n    std::cerr << msg << std::endl;\n  }\n\n  return -1;\n}\n", "meta": {"hexsha": "1236819390b7b60354ab75f630ecded2018f9e1f", "size": 5324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pcl_tools/centroid_align.cpp", "max_stars_repo_name": "brschettini/msc-research", "max_stars_repo_head_hexsha": "e75562c12c441e2cb08deda905f41acf9a698e00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcl_tools/centroid_align.cpp", "max_issues_repo_name": "brschettini/msc-research", "max_issues_repo_head_hexsha": "e75562c12c441e2cb08deda905f41acf9a698e00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcl_tools/centroid_align.cpp", "max_forks_repo_name": "brschettini/msc-research", "max_forks_repo_head_hexsha": "e75562c12c441e2cb08deda905f41acf9a698e00", "max_forks_repo_licenses": ["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.7172413793, "max_line_length": 132, "alphanum_fraction": 0.6555221638, "num_tokens": 1411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.53056446900019}}
{"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 armadillo-with-viennacl.cpp\n*\n*   This tutorial shows how data can be directly transferred from the <a href=\"http://arma.sourceforge.net/\">Armadillo Library</a> to ViennaCL objects using the built-in convenience wrappers.\n*\n*   The first step is to include the necessary headers and activate the Armadillo convenience functions in ViennaCL:\n**/\n\n// System headers\n#include <iostream>\n\n// Armadillo headers (disable BLAS and LAPACK to avoid linking issues)\n#define ARMA_DONT_USE_BLAS\n#define ARMA_DONT_USE_LAPACK\n#include <armadillo>\n\n// IMPORTANT: Must be set prior to any ViennaCL includes if you want to use ViennaCL algorithms on Armadillo objects\n#define VIENNACL_WITH_ARMADILLO 1\n\n\n// ViennaCL includes\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n\n\n// Helper functions for this tutorial:\n#include \"vector-io.hpp\"\n\n\n/**\n*    The following function contains the main code for this tutorial.\n*    It consists of the following steps:\n*      - Creates Armadillo matrices and vectors\n*      - Initializes them with data\n*      - Create ViennaCL objects\n*      - Copy them over to the respective ViennaCL objects\n*      - Compute matrix-vector products in both Armadillo and ViennaCL and compare results.\n*\n**/\ntemplate<typename NumericT>\nvoid run_tutorial()\n{\n  typedef arma::SpMat<NumericT>  ArmaSparseMatrix;\n  typedef arma::Mat<NumericT>    ArmaMatrix;\n  typedef arma::Col<NumericT>    ArmaVector;\n\n  /**\n  * Create and fill dense matrices from the Armadillo library:\n  **/\n  ArmaMatrix arma_densemat(6, 5);\n  ArmaMatrix arma_densemat2(6, 5);\n  arma_densemat(0,0) = 2.0;   arma_densemat(0,1) = -1.0;\n  arma_densemat(1,0) = -1.0;  arma_densemat(1,1) =  2.0;  arma_densemat(1,2) = -1.0;\n  arma_densemat(2,1) = -1.0;  arma_densemat(2,2) = -1.0;  arma_densemat(2,3) = -1.0;\n  arma_densemat(3,2) = -1.0;  arma_densemat(3,3) =  2.0;  arma_densemat(3,4) = -1.0;\n                              arma_densemat(5,4) = -1.0;  arma_densemat(4,4) = -1.0;\n\n  /**\n  * Create and fill sparse matrices from the Armadillo library:\n  **/\n  ArmaSparseMatrix arma_sparsemat(6, 5);\n  ArmaSparseMatrix arma_sparsemat2(6, 5);\n  arma_sparsemat(0,0) = 2.0;   arma_sparsemat(0,1) = -1.0;\n  arma_sparsemat(1,1) = 2.0;   arma_sparsemat(1,2) = -1.0;\n  arma_sparsemat(2,2) = -1.0;  arma_sparsemat(2,3) = -1.0;\n  arma_sparsemat(3,3) = 2.0;   arma_sparsemat(3,4) = -1.0;\n  arma_sparsemat(5,4) = -1.0;\n\n  /**\n  * Create and fill a few vectors from the Armadillo library:\n  **/\n  ArmaVector arma_rhs(5);\n  ArmaVector arma_result(6);\n  ArmaVector arma_temp(6);\n\n  arma_rhs(0) = 10.0;\n  arma_rhs(1) = 11.0;\n  arma_rhs(2) = 12.0;\n  arma_rhs(3) = 13.0;\n  arma_rhs(4) = 14.0;\n\n\n  /**\n  * Create the corresponding ViennaCL objects:\n  **/\n  viennacl::vector<NumericT> vcl_rhs(5);\n  viennacl::vector<NumericT> vcl_result(6);\n  viennacl::matrix<NumericT> vcl_densemat(6, 5);\n  viennacl::compressed_matrix<NumericT> vcl_sparsemat(6, 5);\n\n\n  /**\n  * Directly copy the Armadillo objects to ViennaCL objects\n  **/\n  viennacl::copy(arma_rhs.memptr(), arma_rhs.memptr() + arma_rhs.n_elem, vcl_rhs.begin());  //method 1: via iterator interface (cf. std::copy())\n  viennacl::copy(arma_rhs, vcl_rhs);  //method 2: via built-in wrappers (convenience layer)\n\n  viennacl::copy(arma_densemat, vcl_densemat);\n  viennacl::copy(arma_sparsemat, vcl_sparsemat);\n  std::cout << \"VCL sparsematrix dimensions: \" << vcl_sparsemat.size1() << \", \" << vcl_sparsemat.size2() << std::endl;\n\n  // For completeness: Copy matrices from ViennaCL back to Eigen:\n  viennacl::copy(vcl_densemat, arma_densemat2);\n  viennacl::copy(vcl_sparsemat, arma_sparsemat2);\n\n\n  /**\n  * Run dense matrix-vector products and compare results:\n  **/\n  arma_result = arma_densemat * arma_rhs;\n  vcl_result = viennacl::linalg::prod(vcl_densemat, vcl_rhs);\n  viennacl::copy(vcl_result, arma_temp);\n  std::cout << \"Difference for dense matrix-vector product: \" << norm(arma_result - arma_temp) << std::endl;\n  std::cout << \"Difference for dense matrix-vector product (Armadillo -> ViennaCL -> Armadillo): \"\n            << norm(arma_densemat2 * arma_rhs - arma_temp) << std::endl;\n\n  /**\n  * Run sparse matrix-vector products and compare results:\n  **/\n  arma_result = arma_sparsemat * arma_rhs;\n  vcl_result = viennacl::linalg::prod(vcl_sparsemat, vcl_rhs);\n  viennacl::copy(vcl_result, arma_temp);\n  std::cout << \"Difference for sparse matrix-vector product: \" << norm(arma_result - arma_temp) << std::endl;\n  std::cout << \"Difference for sparse matrix-vector product (Armadillo -> ViennaCL -> Armadillo): \"\n            << norm(arma_sparsemat2 * arma_rhs - arma_temp) << std::endl;\n}\n\n\n/**\n*   In the main() routine we only call the worker function defined above with both single and double precision arithmetic.\n**/\nint main(int, char *[])\n{\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << \"## Single precision\" << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  run_tutorial<float>();\n\n#ifdef VIENNACL_HAVE_OPENCL\n  if ( viennacl::ocl::current_device().double_support() )\n#endif\n  {\n    std::cout << \"----------------------------------------------\" << std::endl;\n    std::cout << \"## Double precision\" << std::endl;\n    std::cout << \"----------------------------------------------\" << std::endl;\n    run_tutorial<double>();\n  }\n\n  /**\n  *   That's it. Print a success message and exit.\n  **/\n  std::cout << std::endl;\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n  std::cout << std::endl;\n\n}\n", "meta": {"hexsha": "b25e8f4de5f4f0afbbde056cbcb5417eb4b7ea6e", "size": 6389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/armadillo-with-viennacl.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/armadillo-with-viennacl.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/armadillo-with-viennacl.cpp", "max_forks_repo_name": "yuchengs/viennacl-dev", "max_forks_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 84.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T14:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T14:51:17.000Z", "avg_line_length": 36.5085714286, "max_line_length": 191, "alphanum_fraction": 0.6307716388, "num_tokens": 1795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.530564456938336}}
{"text": "#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <opencv2/core.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/core/eigen.hpp>\n\nint main(){\n  cv::Mat mat = cv::imread(\"sample.jpg\", cv::IMREAD_COLOR);\n  if(mat.empty()){\n    std::cout << \"There is no input file 'sample.jpg'\" << std::endl;\n    exit(EXIT_FAILURE);\n  }\n\n  const int mr = mat.rows;\n  const int mc = mat.cols;\n  const int nn = mr*mc;\n\n  if(RAND_MAX < mr){\n    std::cout << \"rand_max \" << RAND_MAX << std::endl;\n    std::cout << \"mat.rows \" << mr << std::endl;\n    std::cout << \"RAND_MAX < mr, error!\" << std::endl;\n  }\n\n// 1\u30c1\u30e3\u30f3\u30cd\u30eb\u306b\u5909\u63db\u3057\uff0cEigen\u306b\u5909\u63db\n  Eigen::MatrixXd em;\n  cv::cv2eigen(mat.reshape(1, mr*mc), em);\n\n// Eigen\u5074\u306e\u51e6\u7406\n  int kk;\n  std::ifstream fr;\n  fr.open(\"input_kk\", std::ios::in);\n  if(! fr.fail()){\n    fr >> kk;\n    std::cout << \"kk = \" << kk << std::endl;\n    fr.close();\n  }\n  else{\n    std::cout << \"There is no input file 'input_kk'\" << std::endl;\n    exit(EXIT_FAILURE);\n  }\n  Eigen::VectorXi gk(nn);\n  Eigen::VectorXi numk = Eigen::VectorXi::Zero(kk);\n  Eigen::MatrixXd::Index minIndex;\n  int i;\n  int j;\n  int l;\n  int sum_gk;\n  int bef_sum_gk;\n\n  std::cout << \"nn \" << nn << std::endl;\n  em.transposeInPlace();\n  Eigen::MatrixXd mu(3, kk);\n  for(i = 0; i < kk; i++){\n    mu.col(i) = em.col((rand() % mr));\n  }\n//  std::cout << \"mu = \" << mu << std::endl; //dbg\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      (mu.colwise() - em.col(j)).colwise().squaredNorm().minCoeff(&minIndex);\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) += em.col(j);\n\t}\n      }\n      if(numk(l) != 0){\n\tmu.col(l) /= static_cast<double> (numk(l));\n      }\n      else{\n\tmu.col(l) = em.col((rand() % mr));\n      }\n    }\n    sum_gk = gk.sum();\n    if(bef_sum_gk == sum_gk) break;\n    bef_sum_gk = sum_gk;\n//    std::cout << \"numk =\" << numk << std::endl; //dbg\n//    std::cout << \"mu =\" << mu << std::endl; //dbg\n  }\n\n  //\u8272\u3092\u6e1b\u3089\u3059\n  for(l = 0; l < kk; l++){\n    for(j = 0; j < nn; j++){\n      if(gk(j) == l){\n\tem.col(j) = mu.col(l);\n      }\n    }\n  }\n//  std::cout << \"mu =\" << mu << std::endl; //dbg\n  em.transposeInPlace();\n\n// cv\u306b\u623b\u3059\n  cv::Mat tmp;\n  cv::eigen2cv(em, tmp);\n\n// 3\u30c1\u30e3\u30f3\u30cd\u30eb\u306b\u5909\u63db\n  tmp = tmp.reshape(3, mr);\n\n  cv::namedWindow(\"sample\", cv::WINDOW_AUTOSIZE);\n  cv::imshow(\"sample\", mat);\n  cv::waitKey(0);\n  cv::destroyAllWindows();\n\n  cv::namedWindow(\"tmp\", cv::WINDOW_AUTOSIZE);\n  cv::imshow(\"tmp\", tmp/255);\n  cv::waitKey(0);\n  cv::destroyAllWindows();\n\n  return 0;\n}\n\n", "meta": {"hexsha": "ead70a30dd015f375c03c9ae3418bf7a9408c3bd", "size": 2679, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main.cc", "max_stars_repo_name": "ya-mat/k_means_cc_photo", "max_stars_repo_head_hexsha": "c9e3257c7064568e9e5e1bdedfd12570e61f62e9", "max_stars_repo_licenses": ["MIT"], "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_photo", "max_issues_repo_head_hexsha": "c9e3257c7064568e9e5e1bdedfd12570e61f62e9", "max_issues_repo_licenses": ["MIT"], "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_photo", "max_forks_repo_head_hexsha": "c9e3257c7064568e9e5e1bdedfd12570e61f62e9", "max_forks_repo_licenses": ["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.325, "max_line_length": 77, "alphanum_fraction": 0.5300485256, "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5305570921068653}}
{"text": "#include <cmath>\n#include <limits>\n#include <memory>\n\n#include <Eigen/Dense>\n#include <boost/filesystem.hpp>\n\n#include \"catch.hpp\"\n// MPI\n#ifdef USE_MPI\n#include \"mpi.h\"\n#endif\n\n#include \"constraints.h\"\n#include \"contact.h\"\n#include \"contact_friction.h\"\n#include \"element.h\"\n#include \"function_base.h\"\n#include \"hexahedron_element.h\"\n#include \"linear_function.h\"\n#include \"material.h\"\n#include \"mesh.h\"\n#include \"mpm_scheme_usf.h\"\n#include \"node.h\"\n#include \"partio_writer.h\"\n#include \"quadrilateral_element.h\"\n\n//! \\brief Check stress update 3D case\nTEST_CASE(\"Contact test case\", \"[contact][friction][3D]\") {\n  // Dimension\n  const unsigned Dim = 3;\n  // Degrees of freedom\n  const unsigned Dof = 6;\n  // Number of phases\n  const unsigned Nphases = 1;\n  // Number of nodes per cell\n  const unsigned Nnodes = 8;\n  // Tolerance\n  const double Tolerance = 1.E-9;\n\n  // Assign material\n  unsigned mid = 0;\n  std::vector<unsigned> mids(1, mid);\n  // Initialise material\n  Json jmaterial;\n  jmaterial[\"density\"] = 1000.;\n  jmaterial[\"youngs_modulus\"] = 1.0E+7;\n  jmaterial[\"poisson_ratio\"] = 0.3;\n\n  auto material =\n      Factory<mpm::Material<Dim>, unsigned, const Json&>::instance()->create(\n          \"LinearElastic3D\", std::move(0), jmaterial);\n\n  std::map<unsigned, std::shared_ptr<mpm::Material<Dim>>> materials;\n  materials[mid] = material;\n\n  // 8-noded hexahedron element\n  std::shared_ptr<mpm::Element<Dim>> element =\n      Factory<mpm::Element<Dim>>::instance()->create(\"ED3H8\");\n\n  // Particle 1\n  mpm::Index id1 = 0;\n  Eigen::Vector3d coords;\n  coords.setZero();\n  std::shared_ptr<mpm::ParticleBase<Dim>> particle1 =\n      std::make_shared<mpm::Particle<Dim>>(id1, coords);\n\n  // Particle 2\n  mpm::Index id2 = 1;\n  coords << 2., 2., 2.;\n  std::shared_ptr<mpm::ParticleBase<Dim>> particle2 =\n      std::make_shared<mpm::Particle<Dim>>(id2, coords);\n\n  auto mesh = std::make_shared<mpm::Mesh<Dim>>(0);\n  // Check mesh is active\n  REQUIRE(mesh->status() == false);\n\n  // Check nodal coordinates size\n  REQUIRE(mesh->nodal_coordinates().size() == 0);\n  // Check node pairs size\n  REQUIRE(mesh->node_pairs().size() == 0);\n\n  // Define nodes\n  coords << 0, 0, 0;\n  std::shared_ptr<mpm::NodeBase<Dim>> node0 =\n      std::make_shared<mpm::Node<Dim, Dof, Nphases>>(0, coords);\n  REQUIRE(mesh->add_node(node0) == true);\n\n  coords << 2, 0, 0;\n  std::shared_ptr<mpm::NodeBase<Dim>> node1 =\n      std::make_shared<mpm::Node<Dim, Dof, Nphases>>(1, coords);\n  REQUIRE(mesh->add_node(node1) == true);\n\n  coords << 2, 2, 0;\n  std::shared_ptr<mpm::NodeBase<Dim>> node2 =\n      std::make_shared<mpm::Node<Dim, Dof, Nphases>>(2, coords);\n  REQUIRE(mesh->add_node(node2) == true);\n\n  coords << 0, 2, 0;\n  std::shared_ptr<mpm::NodeBase<Dim>> node3 =\n      std::make_shared<mpm::Node<Dim, Dof, Nphases>>(3, coords);\n  REQUIRE(mesh->add_node(node3) == true);\n\n  coords << 0, 0, 2;\n  std::shared_ptr<mpm::NodeBase<Dim>> node4 =\n      std::make_shared<mpm::Node<Dim, Dof, Nphases>>(4, coords);\n  REQUIRE(mesh->add_node(node4) == true);\n\n  coords << 2, 0, 2;\n  std::shared_ptr<mpm::NodeBase<Dim>> node5 =\n      std::make_shared<mpm::Node<Dim, Dof, Nphases>>(5, coords);\n  REQUIRE(mesh->add_node(node5) == true);\n\n  coords << 2, 2, 2;\n  std::shared_ptr<mpm::NodeBase<Dim>> node6 =\n      std::make_shared<mpm::Node<Dim, Dof, Nphases>>(6, coords);\n  REQUIRE(mesh->add_node(node6) == true);\n\n  coords << 0, 2, 2;\n  std::shared_ptr<mpm::NodeBase<Dim>> node7 =\n      std::make_shared<mpm::Node<Dim, Dof, Nphases>>(7, coords);\n  REQUIRE(mesh->add_node(node7) == true);\n\n  // Create cell1\n  auto cell1 = std::make_shared<mpm::Cell<Dim>>(id1, Nnodes, element);\n\n  // Add nodes to cell\n  cell1->add_node(0, node0);\n  cell1->add_node(1, node1);\n  cell1->add_node(2, node2);\n  cell1->add_node(3, node3);\n  cell1->add_node(4, node4);\n  cell1->add_node(5, node5);\n  cell1->add_node(6, node6);\n  cell1->add_node(7, node7);\n\n  REQUIRE(cell1->nnodes() == 8);\n\n  REQUIRE(mesh->add_cell(cell1) == true);\n\n  REQUIRE(cell1->initialise() == true);\n\n  // Check nodal coordinates size\n  REQUIRE(mesh->nodal_coordinates().size() == 8);\n  // Check node pairs size\n  REQUIRE(mesh->node_pairs().size() == 12);\n\n  // Add particle 1 and check\n  REQUIRE(mesh->add_particle(particle1) == true);\n  // Add particle 2 and check\n  REQUIRE(mesh->add_particle(particle2) == true);\n  // Add particle 2 again and check\n  REQUIRE(mesh->add_particle(particle2) == false);\n\n  REQUIRE(particle1->assign_material(material) == true);\n  REQUIRE(particle2->assign_material(material) == true);\n\n  // Check mesh is active\n  REQUIRE(mesh->status() == true);\n  // Check number of particles in mesh\n  REQUIRE(mesh->nparticles() == 2);\n\n  REQUIRE_NOTHROW(mesh->locate_particles_mesh());\n\n  SECTION(\"Check ContactFriction\") {\n\n    unsigned phase = 0;\n\n    // Initialise material\n    Json jmaterial;\n    jmaterial[\"density\"] = 1000.;\n    jmaterial[\"youngs_modulus\"] = 1.0E+7;\n    jmaterial[\"poisson_ratio\"] = 0.3;\n\n    auto material1 =\n        Factory<mpm::Material<Dim>, unsigned, const Json&>::instance()->create(\n            \"LinearElastic3D\", std::move(0), jmaterial);\n    auto material2 =\n        Factory<mpm::Material<Dim>, unsigned, const Json&>::instance()->create(\n            \"LinearElastic3D\", std::move(1), jmaterial);\n    std::map<unsigned, std::shared_ptr<mpm::Material<Dim>>> materials;\n    materials[0] = material1;\n    materials[1] = material2;\n\n    // Assign materials to particles\n    REQUIRE_NOTHROW(particle1->assign_material(material1));\n    REQUIRE_NOTHROW(particle2->assign_material(material2));\n\n    // Assign mass\n    REQUIRE_NOTHROW(particle1->assign_mass(2.0));\n    REQUIRE_NOTHROW(particle2->assign_mass(3.0));\n\n    // Assign volume\n    REQUIRE_NOTHROW(particle1->assign_volume(4.0));\n    REQUIRE_NOTHROW(particle2->assign_volume(3.0));\n\n    auto mpm_scheme = std::make_shared<mpm::MPMSchemeUSF<Dim>>(mesh, 0.01);\n\n    auto contact = std::make_shared<mpm::ContactFriction<Dim>>(mesh);\n\n    // Initialise material models\n    REQUIRE_NOTHROW(mesh->initialise_material_models(materials));\n\n    // Create nodal properties\n    REQUIRE_NOTHROW(mesh->create_nodal_properties());\n    // Initialise\n    REQUIRE_NOTHROW(mpm_scheme->initialise());\n    // Contact initialize\n    REQUIRE_NOTHROW(contact->initialise());\n\n    // Mass momentum and compute velocity at nodes\n    REQUIRE_NOTHROW(mpm_scheme->compute_nodal_kinematics(phase));\n    // Contact compute forces\n    REQUIRE_NOTHROW(contact->compute_contact_forces());\n  }\n}\n", "meta": {"hexsha": "fe98064536ca170f60128e0b326662025b22f3b1", "size": 6472, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/contact_test.cc", "max_stars_repo_name": "andrewsolis/mpm", "max_stars_repo_head_hexsha": "c6ea73d3bac177a440f0aa0a5e66829c294a00e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 154.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T06:41:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T23:19:05.000Z", "max_issues_repo_path": "tests/contact_test.cc", "max_issues_repo_name": "andrewsolis/mpm", "max_issues_repo_head_hexsha": "c6ea73d3bac177a440f0aa0a5e66829c294a00e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 707.0, "max_issues_repo_issues_event_min_datetime": "2017-08-30T16:12:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T20:33:02.000Z", "max_forks_repo_path": "tests/contact_test.cc", "max_forks_repo_name": "andrewsolis/mpm", "max_forks_repo_head_hexsha": "c6ea73d3bac177a440f0aa0a5e66829c294a00e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2017-11-22T15:22:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T17:02:51.000Z", "avg_line_length": 29.8248847926, "max_line_length": 79, "alphanum_fraction": 0.6699629172, "num_tokens": 1971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5305570818367614}}
{"text": "#ifndef SRC_PHYSICS_FLUIDS_FLIPSOLVER2D_H_\n#define SRC_PHYSICS_FLUIDS_FLIPSOLVER2D_H_\n\n#include <vector>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <glm/glm.hpp>\n\nnamespace mk\n{\n  namespace physics\n  {\n    enum CellType\n    {\n      kCellTypeAir = 0,\n      kCellTypeFluid,\n      kCellTypeSolid\n    };\n\n    class FLIPSolver2D\n    {\n    public:\n      struct Particles\n      {\n      public:\n        Particles();\n\n        void addParticle(const glm::fvec2& pos, const glm::fvec2& vel);\n        void clearParticles();\n\n      public:\n        std::vector<glm::fvec2> positions;\n        std::vector<glm::fvec2> velocities;\n        int\tnumParticles;\n      };\n\n    public:\n      FLIPSolver2D(int grid_width, int grid_height, float dx);\n\n      float timeStep();\n      void simulate(float dt);\n      void setBoundaryVel(const glm::fvec2& vel);\n      float getPressure(int i, int j);\n      glm::fvec2 getVelocity(int i, int j);\n      glm::fvec2 getVelocity(float i, float j);\n      CellType getCellType(int i, int j) const;\n      void setCellType(int i, int j, CellType type);\n      void setPicFlipFactor(float factor);\n\n      float& u(int i, int j);\n      float& v(int i, int j);\n      int ix(int i, int j) const;\n      int ixBig(int i, int j);\n\n    public:\n      Particles mParticles;\n\n    private:\n      void applyForce(float dt, float ax, float ay);\n      void setBoundary();\n      void project(float dt);\n\n      void checkBoundary(float i_init_, float j_init_, float& i_end_, float& j_end_);\n      void advectParticles(float dt);\n      void particlesToGrid();\n      void storeVel();\n      float computePhi(float a, float b, float current);\n      void computeGridPhi();\n      void sweepU(int i0, int i1, int j0, int j1);\n      void sweepV(int i0, int i1, int j0, int j1);\n      void extrapolateVel();\n      void subtractVel();\n      void gridToParticles();\n      void fillHoles();\n\n      void solvePressure();\n      void calcPrecond();\n      void applyPrecond();\n      void applyA();\n\n      float uVel(float i, float j);\n      float vVel(float i, float j);\n      int uIndex_x(float x, float& wx);\n      int uIndex_y(float y, float& wy);\n      int vIndex_x(float x, float& wx);\n      int vIndex_y(float y, float& wy);\n      void swapVel();\n\n    private:\n      int mGridWidth;\n      int mGridHeight;\n      int mGridSize;\n      float mDx;\n      float mOverDx;\n      glm::fvec2 mBoundaryVelocity;\n      float mPicFlipFactor;\n      std::vector<float> mVelX;\n      std::vector<float> mVelY;\n      std::vector<float> mDeltaVelX;\n      std::vector<float> mDeltaVelY;\n      std::vector<float> mWeightSum;\n      std::vector<float> mPhi;\n      std::vector<CellType> mCellType;\n      std::vector<CellType> mCellTypeAux;\n\n      boost::numeric::ublas::vector<double> mP;\n      boost::numeric::ublas::vector<double> mR;\n      boost::numeric::ublas::vector<double> mS;\n      boost::numeric::ublas::vector<double> mZ;\n      boost::numeric::ublas::vector<double> mAux;\n      boost::numeric::ublas::vector<double> mRhs;\n      boost::numeric::ublas::vector<double> mPrecond;\n      boost::numeric::ublas::vector<double> mCoefDiag;\n      boost::numeric::ublas::vector<double> mCoefPlusI;\n      boost::numeric::ublas::vector<double> mCoefPlusJ;\n    };\n  }\n}\n\n#endif  // SRC_PHYSICS_FLUIDS_FLIPSOLVER2D_H_\n", "meta": {"hexsha": "29957dba1e9297a5fd81a357953e415ced735122", "size": 3281, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mk-physics/src/physics/fluids/FLIPSolver2D.hpp", "max_stars_repo_name": "mpazoscr/computer-graphics", "max_stars_repo_head_hexsha": "a6c9bf8700161a4243f753a965dfd5f56b195e36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-06-21T13:53:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T02:49:06.000Z", "max_issues_repo_path": "mk-physics/src/physics/fluids/FLIPSolver2D.hpp", "max_issues_repo_name": "mpazoscr/computer-graphics", "max_issues_repo_head_hexsha": "a6c9bf8700161a4243f753a965dfd5f56b195e36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mk-physics/src/physics/fluids/FLIPSolver2D.hpp", "max_forks_repo_name": "mpazoscr/computer-graphics", "max_forks_repo_head_hexsha": "a6c9bf8700161a4243f753a965dfd5f56b195e36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-15T16:14:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T02:49:07.000Z", "avg_line_length": 27.1157024793, "max_line_length": 85, "alphanum_fraction": 0.6272477903, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5305570811753576}}
{"text": "#include <iostream>     // std::cout\n#include <algorithm>    // std::count\n#include <unordered_map>//unordered_map\n#include <vector>       // std::vector\n#include <string>       // std::string, std::to_string\n#include <iostream>     // std::cout\n#include <random>       // std::random_device std::default_random_engine std::uniform_int_distribution std::normal_distribution\n#include <numeric>      // std::inner_product\n#include <chrono>       // std::chrono:\n#include <boost/math/distributions/normal.hpp> //boost::math::normal \n#include <math.h>  //std::sqrt\n\n\nconstexpr size_t n = 4;\nint p = 101;\nint s[n] = { 1, 2, 3, 4}; //{ 0, 0, 0 }; //{ 1, 2, 3 };\n\n// Declare EQUATION struct type\nstruct EQUATION {   \n    int a[n];\n    int b;\n    int e;\n\n};\n\n// mappings\nstd::unordered_map<std::string, std::vector<EQUATION>> equationMemo;\nstd::unordered_map<int, std::unordered_map<int, long>> guessCount;  // {position, {guess, count}\n\n// error distributions\n/// rounded gaussian\nfloat mu = 0;\nfloat sigma = 2;\n\nstd::random_device rd;\nstd::default_random_engine generator(rd());\nstd::uniform_int_distribution<int> uniform_int(0, p-1);  //min, max\nstd::normal_distribution<float> gaussian(mu, sigma);  // mean, std\n\n/// centered binomial\nconstexpr size_t upper = 2;  // has to be odd\nstd::binomial_distribution<int> binomial(upper, 0.5);  //upper bound, probability of success\n\n\n\n// oracle\nvoid oracleLWE(EQUATION& equation){\n\n    for (int i = 0; i < n; i++) {\n        equation.a[i] = uniform_int(generator);\n    }\n\n    // discrete gaussian\n    //equation.e = round(gaussian(generator));\n\n    // centered binomial (used in NewHope reference implementation)\n    equation.e = binomial(generator) - upper/2;\n\n    equation.b = std::inner_product(s, s+n, equation.a, 0.0) + equation.e;\n    equation.b %= p;\n}\n    \n\nvoid encodePosOfZeros(std::string& key, int(&coeffs)[n]) {\n    for (const auto& coeff : coeffs)\n        if (coeff == 0)\n            key.push_back('0');\n        else\n            key.push_back('1');\n}\nvoid initializeEquationMemo(int n, int arr[], int i) {\n    if (i == n) {\n        std::string key;\n        for (int j=0; j < n; j++) {\n            key += std::to_string(arr[j]);\n        }\n        std::vector<EQUATION> equations;\n        equationMemo.insert({ key, equations });\n        //std::cout << key << std::endl;\n        return;\n    }\n\n    // First assign \"0\" at ith position\n    // and try for all other permutations\n    // for remaining positions\n    arr[i] = 0;\n    initializeEquationMemo(n, arr, i + 1);\n\n    // And then assign \"1\" at ith position\n    // and try for all other permutations\n    // for remaining positions\n    arr[i] = 1;\n    initializeEquationMemo(n, arr, i + 1);\n}\n\n// fast pow for integer using square and multiply algo\nint integerPow(int a, int ex, int mod) {\n    if (a == 1) return 1;\n\n    long r = 1;\n    while (ex) {\n        if (ex & 1)r = (r * a) % mod;\n        ex = ex >> 1;\n        a = (a * a) % mod;\n    }\n    return r;\n}\n\nvoid compareEquationsSub(std::string& key, EQUATION& prevEquation, EQUATION& equation) {\n    for (int i = 0; i < n; ++i) {\n        if ((prevEquation.a[i] - equation.a[i]) % p == 0)\n            key.push_back('0');\n        else\n            key.push_back('1');\n    }\n}\n\nvoid compareEquationsAdd(std::string& key, EQUATION& prevEquation, EQUATION& equation) {\n    for (int i = 0; i < n; ++i) {\n        if ((prevEquation.a[i] + equation.a[i]) % p == 0)\n            key.push_back('0');\n        else\n            key.push_back('1');\n    }\n}\n\n\nvoid furtherElimination(std::string& prevKey, EQUATION& prevEquation) {\n    auto equations = equationMemo.at(prevKey);\n\n    std::string key;\n    for (auto& equation : equations) {\n        EQUATION newEquation;\n\n        // compare for subtraction\n        key.clear();\n        compareEquationsSub(key, prevEquation, equation);\n\n\n        if (std::count(key.begin(), key.end(), '1') == 1) {\n            for (int i = 0; i < n; ++i)\n                newEquation.a[i] = (prevEquation.a[i] - equation.a[i]) % p;\n            newEquation.b = (prevEquation.b - equation.b) % p;\n            int pos = key.find('1');\n            int coeff = newEquation.a[pos];\n            int s = newEquation.b*integerPow(coeff, p-2, p)%p;  // solving linear congruence fast by using little fermat\n            if (s < 0)\n                s += p;\n\n            guessCount.at(pos).at(s) += 1;\n        }\n        else {\n            if (std::count(key.begin(), key.end(), '1') < std::count(prevKey.begin(), prevKey.end(), '1')) {\n                for (int i = 0; i < n; ++i)\n                    newEquation.a[i] = (prevEquation.a[i] - equation.a[i]) % p;\n                newEquation.b = (prevEquation.b - equation.b) % p;\n                \n                furtherElimination(key, newEquation);\n\n                equationMemo.at(key).push_back(equation);\n            }\n        }\n\n        // compare for addition\n        key.clear();\n        compareEquationsAdd(key, prevEquation, equation);\n\n        if (std::count(key.begin(), key.end(), '1') == 1) {\n            for (int i = 0; i < n; ++i)\n                newEquation.a[i] = (prevEquation.a[i] + equation.a[i]) % p;\n            newEquation.b = (prevEquation.b + equation.b) % p;\n            int pos = key.find('1');\n            int coeff = newEquation.a[pos];\n            int s = newEquation.b * integerPow(coeff, p - 2, p) % p;  // solving linear congruence fast by using little fermat\n            if (s < 0)\n                s += p;\n\n            guessCount.at(pos).at(s) += 1;\n        }\n        else {\n            if (std::count(key.begin(), key.end(), '1') < std::count(prevKey.begin(), prevKey.end(), '1')) {\n                for (int i = 0; i < n; ++i)\n                    newEquation.a[i] = (prevEquation.a[i] + equation.a[i]) % p;\n                newEquation.b = (prevEquation.b + equation.b) % p;\n\n                furtherElimination(key, newEquation);\n\n                equationMemo.at(key).push_back(equation);\n            }\n        }\n    }  \n}\n\nint main(int argc, char** argv) {\n    // initialize equation memory\n    int arr[n];\n    initializeEquationMemo(n, arr, 0);\n\n    // initialize map to track the count of guesses for a possible solution\n    for (int pos = 0; pos < n; pos++) {\n        std::unordered_map<int, long> tmp;\n        for (int guess = 0; guess < p; guess++)\n            tmp.insert(std::make_pair(guess, 0));\n\n        guessCount.insert(std::make_pair(pos, tmp));\n    }\n\n    std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n    \n    long i = 1;\n    while (1) {\n        EQUATION equation;\n        oracleLWE(equation);\n\n        std::string key;\n        encodePosOfZeros(key, equation.a);\n\n        furtherElimination(key, equation);\n\n        equationMemo.at(key).push_back(equation);\n\n\n        // early stopping\n        if (i % 10 == 0) {\n            bool ready = true;\n            for (auto const& pos : guessCount) {\n                float mean = 0;\n                for (auto const& guess : pos.second)\n                    mean += guess.second;\n                if (mean < 20) {\n                    std::cout << \"mean: \" << mean << std::endl;\n                    goto endOfLoop;\n                }\n                mean /= p;\n\n                float var = 0;\n                for (auto const& guess : pos.second)\n                    var += (guess.second - mean) * (guess.second - mean); // fast pow\n                var /= p - 1;\n                float sigma = std::sqrt(var);\n\n                int guessCount = 0;\n                for (auto const& guess : pos.second) {\n                    if (mean + sigma < guess.second) {\n                        guessCount += 1;\n                        std::cout << \"Pos: \" << pos.first << \"\\t\\tGuess: \" << guess.first << \"\\t\\tCount: \" << \n                            guess.second << \"\\t\\tRight solution: \" << s[pos.first] << std::endl;\n                    }\n                }\n                std::cout << std::endl;\n                if (guessCount != 1) {\n                    ready = false;\n                }\n            }\n            if (ready) {\n                std::cout << \"Count of equations: \" << i << std::endl << std::endl;\n                break;\n            }\n        }\n    endOfLoop: {}\n        std::cout << \"Actual equations: \" << i << \"\\t\\tProcessing Time = \" << \n            std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - begin).count() / 1000 << \n            \"[s]\" << std::endl;\n        i += 1;\n    }\n\n    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n    \n\n    std::cout << \"Time difference = \" << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count()/1000 << \"[s]\" << std::endl;\n    //return 0;\n\n\n    // p-value empirical distribution\n    for (auto const& pos : guessCount) {\n        float mean = 0;\n        for (auto const& guess : pos.second)\n            mean += guess.second;\n        mean /= p;\n\n        float var = 0;\n        for (auto const& guess : pos.second)\n            var += (guess.second - mean)*(guess.second - mean); // fast pow\n        var /= p-1;  // empirical variance\n        float sigma = std::sqrt(var);\n        std::cout << \"mean + sigma \" << mean+sigma << std::endl;\n    }\n    std::cout << std::endl;\n\n    // p-value gaussian approximation of binomial\n    /*for (auto const& pos : guessCount) {\n        long sum = 0;\n        for (auto const& guess : pos.second)\n            sum += guess.second;\n        float mean = sum/p;\n        float sigma = std::sqrt(mean * (1 - 1 / p));\n        boost::math::normal dist(mean, sigma);\n        double q = quantile(dist, 0.99);\n        std::cout << \"quantile = \" << q << std::endl;\n    }*/\n\n    // determine guess\n\n    // debug\n    for (auto const& pos : guessCount) {\n        float mean = 0;\n        for (auto const& guess : pos.second)\n            mean += guess.second;\n        mean /= p;\n\n        float var = 0;\n        for (auto const& guess : pos.second)\n            var += (guess.second - mean) * (guess.second - mean); // fast pow\n        var /= p-1;\n        float sigma = std::sqrt(var);\n\n        for (auto const& guess : pos.second) {\n            if (mean + sigma < guess.second) {\n                std::cout << \"Pos: \" << pos.first << \"\\t\\tguess: \" << guess.first << \"\\t\\tcount: \" << guess.second << \"\\t\\tright: \" << s[pos.first] << '\\n';\n            }\n            //if (guess.second != 0)\n            //    std::cout << \"guess: \" << guess.first << \"    count: \" << guess.second <<'\\n';\n        }\n    }\n    return 0;\n\n    // debug\n    for (auto const& pos : guessCount) {\n        int trackGuess=0, trackMax=0;\n        for (auto const& guess : pos.second) {\n            if (trackMax < guess.second) {\n                trackGuess = guess.first;\n                trackMax = guess.second;\n            }\n            //if (guess.second != 0)\n            //    std::cout << \"guess: \" << guess.first << \"    count: \" << guess.second <<'\\n';\n        }\n        std::cout << \"Pos: \" << pos.first << \"\\t\\t\\tguess: \" << trackGuess << \"\\t\\t\\count: \" << trackMax << \"\\t\\t\\tright: \" << s[pos.first] << '\\n';\n    }\n    return 0;\n\n    for (auto const& tmp : equationMemo) {\n        std::cout << \"Key: \" << tmp.first << '\\n';\n        std::cout << \"tmp contains \" << tmp.second.size() << \" elements.\\n\";\n        continue;\n        for (auto const& equation : tmp.second) {\n            for (int i = 0; i < n; i++) \n                std::cout << \"a[\" << i << \"]: \" << equation.a[i] << '\\n';\n    \n            std::cout << \"b: \" << equation.b << '\\n';\n            std::cout << \"e: \" << equation.e << '\\n' << '\\n';\n        }\n\n    }\n\n    return 0;\n}", "meta": {"hexsha": "13b14271e9f48158413d13f67debaf30bf133c5c", "size": 11584, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_code/main.cpp", "max_stars_repo_name": "TomMasterThesis/sca_on_newhope", "max_stars_repo_head_hexsha": "3c72da72076119fb22a64e965c21d340f597cee1", "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_code/main.cpp", "max_issues_repo_name": "TomMasterThesis/sca_on_newhope", "max_issues_repo_head_hexsha": "3c72da72076119fb22a64e965c21d340f597cee1", "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_code/main.cpp", "max_forks_repo_name": "TomMasterThesis/sca_on_newhope", "max_forks_repo_head_hexsha": "3c72da72076119fb22a64e965c21d340f597cee1", "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.4481792717, "max_line_length": 156, "alphanum_fraction": 0.5089779006, "num_tokens": 3104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5305570805139534}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_BESSEL_FIRST_KIND_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_BESSEL_FIRST_KIND_HPP\n\n#include <boost/math/special_functions/bessel.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n *\n   \\f[\n   \\mbox{bessel\\_first\\_kind}(v, x) =\n   \\begin{cases}\n     J_v(x) & \\mbox{if } -\\infty\\leq x \\leq \\infty \\\\[6pt]\n     \\textrm{error} & \\mbox{if } x = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{bessel\\_first\\_kind}(v, x)}{\\partial x} =\n   \\begin{cases}\n     \\frac{\\partial\\, J_v(x)}{\\partial x} & \\mbox{if } -\\infty\\leq x\\leq \\infty\n \\\\[6pt] \\textrm{error} & \\mbox{if } x = \\textrm{NaN} \\end{cases} \\f]\n\n   \\f[\n   J_v(x)=\\left(\\frac{1}{2}x\\right)^v\n   \\sum_{k=0}^\\infty \\frac{\\left(-\\frac{1}{4}x^2\\right)^k}{k!\\, \\Gamma(v+k+1)}\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, J_v(x)}{\\partial x} = \\frac{v}{x}J_v(x)-J_{v+1}(x)\n   \\f]\n *\n */\ntemplate <typename T2>\ninline T2 bessel_first_kind(int v, const T2 z) {\n  check_not_nan(\"bessel_first_kind\", \"z\", z);\n  return boost::math::cyl_bessel_j(v, z);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "708d3ba3e0d56f32cfb317400d0fa7201be8bbc8", "size": 1130, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/bessel_first_kind.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": "stan/math/prim/scal/fun/bessel_first_kind.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": "stan/math/prim/scal/fun/bessel_first_kind.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": 25.1111111111, "max_line_length": 79, "alphanum_fraction": 0.6212389381, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5305570767017093}}
{"text": "#include \"core/Initializer.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nnamespace EllipsoidSLAM\n{\n    Initializer::Initializer(int rows, int cols) {\n        miImageRows = rows;\n        miImageCols = cols;\n    }\n\n    // ascending sort\n    bool cmp(pair<int, double>a, pair<int, double>b)\n    {\n        return a.second > b.second;\n    }\n\n    // Initialize an ellipsoid from several bounding boxes and camera poses.\n    g2o::ellipsoid Initializer::initializeQuadric(MatrixXd &pose_mat, MatrixXd &detection_mat, Matrix3d &calib) {\n        mbResult = false;\n\n        int input_size = pose_mat.rows();\n\n        // 1) Generate tangent planes from bounding boxes and camera cneter. \n        //    Those invalid observations are ignored.\n        MatrixXd planesHomo = getPlanesHomo(pose_mat, detection_mat, calib); \n\n        int plane_size = planesHomo.cols();\n        int invalid_plane = input_size*4 - plane_size;\n        if( invalid_plane > 0)\n            std::cout << \" * invalid_plane: \" << invalid_plane << std::endl;\n\n        if(plane_size < 9)  // at least 9 planes are needed\n        {\n            g2o::ellipsoid e_bad;\n            mbResult = false;\n            return e_bad;\n        }\n\n        // Using SVD to generate a quadric\n        MatrixXd planesVector = getVectorFromPlanesHomo(planesHomo);\n        Matrix4d QStar = getQStarFromVectors(planesVector);\n\n        // generate ellipsoid from the quadric\n        g2o::ellipsoid e = getEllipsoidFromQStar(QStar);\n\n        // Set color : blue.\n        Eigen::Vector3d blueScalar(0,0,255);\n        e.setColor(blueScalar);\n        return e;\n    }\n\n    MatrixXd Initializer::getPlanesHomo(MatrixXd &pose_mat, MatrixXd &detection_mat, Matrix3d &calib) {\n        assert( pose_mat.rows() == detection_mat.rows() && \" Two matrices should match. \" );\n        assert( pose_mat.rows() > 2 && \" At least 3 measurements are required. \" );\n\n        MatrixXd planes_all(4,0);\n\n        int rows = pose_mat.rows();\n        for(int i=0;i<rows;i++)\n        {\n            VectorXd pose = pose_mat.row(i);\n            VectorXd detection = detection_mat.row(i);\n\n            // filter invalid detections\n            if( detection(0) < 1 && detection(1) < 1 && detection(2) < 1 && detection(3) < 1  )\n                continue;\n\n            Vector7d pose_vec = pose.tail(7);\n            g2o::SE3Quat campose_wc(pose_vec);\n            // get projection matrix\n            MatrixXd P = generateProjectionMatrix(campose_wc.inverse(), calib);\n\n            MatrixXd lines = fromDetectionsToLines(detection);\n            MatrixXd planes = P.transpose() * lines;\n\n            // add to matrix\n            for( int m=0;m<planes.cols();m++)\n            {\n                planes_all.conservativeResize(planes_all.rows(), planes_all.cols()+1);\n                planes_all.col(planes_all.cols()-1) = planes.col(m);\n            }\n        }\n\n        return planes_all;\n    }\n\n    Matrix3Xd Initializer::generateProjectionMatrix(const SE3Quat& campose_cw, const Matrix3d& Kalib) const\n    {\n        Matrix3Xd identity_lefttop;\n        identity_lefttop.resize(3, 4);\n        identity_lefttop.col(3)=Vector3d(0,0,0);\n        identity_lefttop.topLeftCorner<3,3>() = Matrix3d::Identity(3,3);\n\n        Matrix3Xd proj_mat = Kalib * identity_lefttop;\n\n        proj_mat = proj_mat * campose_cw.to_homogeneous_matrix();\n\n        return proj_mat;\n    }\n\n    MatrixXd Initializer::fromDetectionsToLines(VectorXd &detections) {\n        bool flag_openFilter = true;        // filter those lines lying on the image boundary\n\n        double x1 = detections(0);\n        double y1 = detections(1);\n        double x2 = detections(2);\n        double y2 = detections(3);\n\n        Vector3d line1 (1, 0, -x1);\n        Vector3d line2 (0, 1, -y1);\n        Vector3d line3 (1, 0, -x2);\n        Vector3d line4 (0, 1, -y2);\n\n        // those lying on the image boundary have been marked -1 \n        MatrixXd line_selected(3, 0);\n        MatrixXd line_selected_none(3, 0);\n        if( !flag_openFilter || ( x1>0 && x1<miImageCols-1 ))\n        {\n            line_selected.conservativeResize(3, line_selected.cols()+1);\n            line_selected.col(line_selected.cols()-1) = line1;\n        }\n        if( !flag_openFilter || (y1>0 && y1<miImageRows-1 ))\n        {\n            line_selected.conservativeResize(3, line_selected.cols()+1);\n            line_selected.col(line_selected.cols()-1) = line2;\n        }\n        if( !flag_openFilter || (x2>0 && x2<miImageCols-1 ))\n        {\n            line_selected.conservativeResize(3, line_selected.cols()+1);\n            line_selected.col(line_selected.cols()-1) = line3;\n        }\n        if( !flag_openFilter || (y2>0 && y2<miImageRows-1 ))\n        {\n            line_selected.conservativeResize(3, line_selected.cols()+1);\n            line_selected.col(line_selected.cols()-1) = line4;\n        }\n\n        return line_selected;\n    }\n\n    MatrixXd Initializer::getVectorFromPlanesHomo(MatrixXd &planes) {\n        int cols = planes.cols();\n\n        MatrixXd planes_vector(10,0);\n\n        for(int i=0;i<cols;i++)\n        {\n            VectorXd p = planes.col(i);\n            Vector10d v;\n\n            v << p(0)*p(0),2*p(0)*p(1),2*p(0)*p(2),2*p(0)*p(3),p(1)*p(1),2*p(1)*p(2),2*p(1)*p(3),p(2)*p(2),2*p(2)*p(3),p(3)*p(3);\n\n            planes_vector.conservativeResize(planes_vector.rows(), planes_vector.cols()+1);\n            planes_vector.col(planes_vector.cols()-1) = v;\n        }\n\n        return planes_vector;\n    }\n\n    Matrix4d Initializer::getQStarFromVectors(MatrixXd &planeVecs) {\n        MatrixXd A = planeVecs.transpose();\n\n        // svd decompose\n        JacobiSVD<Eigen::MatrixXd> svd(A, ComputeThinU | ComputeThinV );\n        MatrixXd V = svd.matrixV();\n\n        VectorXd qj_hat = V.col(V.cols()-1);\n\n        // Get QStar\n        Matrix4d QStar;\n        QStar <<\n            qj_hat(0),qj_hat(1),qj_hat(2),qj_hat(3),\n            qj_hat(1),qj_hat(4),qj_hat(5),qj_hat(6),\n            qj_hat(2),qj_hat(5),qj_hat(7),qj_hat(8),\n            qj_hat(3),qj_hat(6),qj_hat(8),qj_hat(9);\n        \n        return QStar;\n    }\n\n    g2o::ellipsoid Initializer::getEllipsoidFromQStar(Matrix4d &QStar) {\n        g2o::ellipsoid e;\n\n        Matrix4d Q = QStar.inverse() * cbrt(QStar.determinant());\n\n        SelfAdjointEigenSolver<Matrix4d> es(Q);    // ascending order by default\n        MatrixXd D = es.eigenvalues().asDiagonal();\n        MatrixXd V = es.eigenvectors();\n\n        VectorXd eigens = es.eigenvalues();\n\n        // For an ellipsoid, the signs of the eigenvalues must be ---+ or +++-\n        int num_pos = int(eigens(0)>0) +int(eigens(1)>0) +int(eigens(2)>0) +int(eigens(3)>0);\n        int num_neg = int(eigens(0)<0) +int(eigens(1)<0) +int(eigens(2)<0) +int(eigens(3)<0);\n        if( !(num_pos ==3 && num_neg == 1) && !(num_pos ==1 && num_neg == 3) ){\n            cout << \" Not Ellipsoid : pos/neg  \" << num_pos << \" / \" << num_neg << endl;\n            cout << \"eigens :\" << eigens.transpose() << endl;\n            mbResult = false;\n            return e;\n        }\n        else\n            mbResult = true;\n\n        if( eigens(3) > 0  )  // normalize to - - - + \n        {\n            Q=-Q;\n            SelfAdjointEigenSolver<Matrix4d> es_2(Q);  \n            D = es_2.eigenvalues().asDiagonal();\n            V = es_2.eigenvectors();\n\n            eigens = es_2.eigenvalues();\n        }\n\n        // Solve ellipsoid parameters from matrix Q\n        Vector3d lambda_mat = eigens.head(3).array().inverse();\n\n        Matrix3d Q33 = Q.block(0,0,3,3);\n\n        double k = Q.determinant()/Q33.determinant();\n\n        Vector3d value = -k*(lambda_mat);\n        Vector3d s = value.array().abs().sqrt();\n\n        Vector4d t = QStar.col(3);\n        t = t/t(3);\n        Vector3d translation = t.head(3);\n\n        SelfAdjointEigenSolver<Matrix3d> es2(Q33);   \n        MatrixXd D_Q33 = es2.eigenvalues().asDiagonal();\n        MatrixXd rot = es2.eigenvectors();\n\n        double r,p,y;\n        rot_to_euler_zyx<double>(rot, r, p, y);\n        Vector3d rpy(r,p,y);\n\n        // generate ellipsoid\n        Vector9d objectVec;\n        objectVec << t(0),t(1),t(2),rpy(0),rpy(1),rpy(2),s(0),s(1),s(2);\n        e.fromMinimalVector(objectVec);\n\n        return e;\n\n    }\n\n    void Initializer::sortEigenValues(VectorXcd &eigens, MatrixXcd &V) {\n        vector<pair<int, double>> pairs;\n        for(int i=0;i<4;i++)\n            pairs.push_back( make_pair( i, eigens(i).real() ) );\n        sort(pairs.begin(), pairs.end(), cmp);\n\n        // Construct a new matrix in order\n        MatrixXcd V_new(4,4);\n        Vector4cd eigens_new;\n\n        for(int i=0;i<4;i++)\n        {\n            int oldID = pairs[i].first;\n            V_new.col(i) = V.col(oldID);\n            eigens_new(i) = complex<double>(pairs[i].second, 0);\n        }\n\n        eigens = eigens_new;\n        V = V_new;\n    }\n\n    double Initializer::quadricErrorWithPlanes(MatrixXd &pose_mat, MatrixXd &detection_mat, Matrix3d &calib,\n                                               g2o::ellipsoid &e) {\n        Matrix4d QStar = e.generateQuadric();           // get Q^*\n        Vector10d qj_hat;\n        qj_hat << QStar(0,0),QStar(0,1),QStar(0,2),QStar(0,3),QStar(1,1),QStar(1,2),QStar(1,3),QStar(2,2),QStar(2,3),QStar(3,3);\n\n        // Get planes vector\n        MatrixXd planesHomo = getPlanesHomo(pose_mat, detection_mat, calib);\n        MatrixXd planesVector = getVectorFromPlanesHomo(planesHomo);\n\n        // Get error\n        VectorXd result = planesVector.transpose() * qj_hat;\n        return result.transpose() * result;\n    }\n\n    bool Initializer::getInitializeResult() {\n        return mbResult;\n    }\n\n    g2o::ellipsoid Initializer::initializeQuadric(EllipsoidSLAM::Observations &obs, Matrix3d &calib) {\n        MatrixXd pose_mat;\n        MatrixXd detection_mat;\n\n        // get pose matrix and detection matrix from observations\n        getDetectionAndPoseMatFromObservations(obs, pose_mat, detection_mat);\n\n        g2o::ellipsoid e = initializeQuadric(pose_mat, detection_mat, calib);\n\n        if( getInitializeResult() )\n        {\n            e.miLabel = obs[0]->label;\n        }\n\n        return e;\n    }\n\n    void Initializer::getDetectionAndPoseMatFromObservations(EllipsoidSLAM::Observations &obs, MatrixXd &pose_mat,\n                                                             MatrixXd &detection_mat) {\n        int frameSize = obs.size();\n        pose_mat.resize(frameSize, 7);  // x y z qx qy qz qw\n        detection_mat.resize(frameSize, 5); // x1 y1 x2 y2 accuracy\n\n        int id = 0;\n        for (auto iter = obs.begin(); iter!=obs.end(); iter++)\n        {\n            Vector5d det_vec;\n            det_vec << (*iter)->bbox, (*iter)->rate;\n            Vector7d pos_vec = (*iter)->pFrame->cam_pose_Twc.toVector();\n\n            pose_mat.row(id) = pos_vec;\n            detection_mat.row(id) = det_vec;\n\n            id ++;\n        }\n    }\n}\n", "meta": {"hexsha": "4739e0426ebd39955975827352c492cf7f278ffc", "size": 10894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/Initializer.cpp", "max_stars_repo_name": "cuijiashuo111/Object-oriented-SLAM", "max_stars_repo_head_hexsha": "4b4ade4fff7290ee66b560fbe9755892d6a0388e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 91.0, "max_stars_repo_stars_event_min_datetime": "2020-04-02T06:47:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T02:52:39.000Z", "max_issues_repo_path": "src/core/Initializer.cpp", "max_issues_repo_name": "moshanATucsd/Object-oriented-SLAM", "max_issues_repo_head_hexsha": "40a32cc99843ef1ccfbabadb573137d9063ac53d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-12T08:53:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T06:55:43.000Z", "max_forks_repo_path": "src/core/Initializer.cpp", "max_forks_repo_name": "moshanATucsd/Object-oriented-SLAM", "max_forks_repo_head_hexsha": "40a32cc99843ef1ccfbabadb573137d9063ac53d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2020-04-02T06:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T17:33:55.000Z", "avg_line_length": 33.3149847095, "max_line_length": 129, "alphanum_fraction": 0.5734349183, "num_tokens": 3040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5305570760403057}}
{"text": "//\n// Created by jachu on 18.07.17.\n//\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include <vector>\n\n#include <Eigen/Eigen>\n\n#include \"Matching.hpp\"\n#include \"Misc.hpp\"\n\nusing namespace std;\n\nvoid transformObjs(const std::vector<Eigen::Vector3d> &points,\n                   const std::vector<Eigen::Vector4d> &planes,\n                   const std::vector<Vector6d> &lines,\n                   std::vector<Eigen::Vector3d> &retPoints,\n                   std::vector<Eigen::Vector4d> &retPlanes,\n                   std::vector<Vector6d> &retLines,\n                   Eigen::Matrix3d rotMat,\n                   Eigen::Vector3d trans,\n                   double rotNoise = 0.0,\n                   double transNoise = 0.0)\n{\n    for(int p = 0; p < points.size(); ++p){\n        retPoints.push_back(rotMat * points[p] + trans + transNoise * Eigen::Vector3d::Random());\n    }\n    Eigen::Matrix4d T = Eigen::Matrix4d::Identity();\n    T.block<3, 3>(0,0) = rotMat;\n    T.block<3, 1>(0, 3) = trans;\n    Eigen::Matrix4d Tinvt = T.inverse().transpose();\n    for(int pl = 0; pl < planes.size(); ++pl){\n        Eigen::Vector4d planeTrans = Tinvt * planes[pl];\n        planeTrans.head<3>() += rotNoise * Eigen::Vector3d::Random();\n        planeTrans.tail<1>() += transNoise * Eigen::MatrixXd::Random(1, 1);\n        double nNorm = planeTrans.head<3>().norm();\n        planeTrans /= nNorm;\n        retPlanes.push_back(planeTrans);\n    }\n    for(int l = 0; l < lines.size(); ++l){\n        Eigen::Vector3d p = lines[l].head<3>();\n        Eigen::Vector3d n = lines[l].tail<3>();\n        Eigen::Vector3d pTrans = rotMat * p + trans + transNoise * Eigen::Vector3d::Random();\n        Eigen::Vector3d nTrans = rotMat * n + rotNoise * Eigen::Vector3d::Random();\n        nTrans.normalize();\n        // move point to be closest to the origin\n        pTrans = Misc::closestPointOnLine(Eigen::Vector3d::Zero(), pTrans, nTrans);\n        Vector6d lTrans;\n        lTrans.head<3>() = pTrans;\n        lTrans.tail<3>() = nTrans;\n        retLines.push_back(lTrans);\n    }\n}\n\n\nvoid testFullConstr(const std::vector<Eigen::Vector3d> &points,\n                    const std::vector<Eigen::Vector3d> &virtPoints,\n                    const std::vector<Eigen::Vector3d> &dirs,\n                    const std::vector<double> &dists,\n                    const std::vector<Eigen::Vector3d> &distDirs,\n                    const std::vector<Eigen::Vector3d> &distPts,\n                    const std::vector<Eigen::Vector3d> &distPtsDirs,\n                    bool &fullConstrRot,\n                    bool &fullConstrTrans)\n{\n    {\n        int rotEqNum = dirs.size();\n        if (points.size() + virtPoints.size() > 0) {\n            rotEqNum += points.size() + virtPoints.size() - 1;\n        }\n        Eigen::MatrixXd rotMat(3, rotEqNum);\n        int rotEqCnt = 0;\n\n        // treating points as directions from the first point\n        Eigen::Vector3d origPoint;\n        if(points.size() > 0){\n            origPoint = points[0];\n        }\n        else if(virtPoints.size() > 0){\n            origPoint = virtPoints[0];\n        }\n        for (int p = 1; p < points.size(); ++p) {\n            rotMat.block<3, 1>(0, rotEqCnt++) = points[p] - origPoint;\n        }\n        // same for virtual points\n        int vpStart = 0;\n        if(points.size() == 0){\n            vpStart = 1;\n        }\n        for(int vp = vpStart; vp < virtPoints.size(); ++vp){\n            rotMat.block<3, 1>(0, rotEqCnt++) = virtPoints[vp] - origPoint;\n        }\n\n        for (int d = 0; d < dirs.size(); ++d) {\n            rotMat.block<3, 1>(0, rotEqCnt++) = dirs[d];\n        }\n//        if(rotEqCnt != rotEqNum){\n//            cout << \"rotEqCnt != rotEqNum\" << endl;\n//            throw std::exception();\n//        }\n        Eigen::FullPivLU<Eigen::MatrixXd> rotLu(rotMat);\n//            lu.setThreshold(sinValsThresh * distScale);\n        int rotRank = rotLu.rank();\n        cout << \"rotLu.rank() = \" << rotLu.rank() << endl;\n        if (rotRank < 2) {\n            fullConstrRot = false;\n        } else {\n            fullConstrRot = true;\n        }\n    }\n    {\n        int transEqNum = dists.size();\n        if (fullConstrRot) {\n            transEqNum += points.size() * 3 + distPts.size();\n        }\n        Eigen::MatrixXd transMat(3, transEqNum);\n        int transEqCnt = 0;\n        for(int d = 0; d < dists.size(); ++d){\n            transMat.block<3, 1>(0, transEqCnt++) = distDirs[d];\n        }\n        if(fullConstrRot) {\n            for (int p = 0; p < points.size(); ++p) {\n                transMat.block<3, 1>(0, transEqCnt++) = Eigen::Vector3d::UnitX();\n                transMat.block<3, 1>(0, transEqCnt++) = Eigen::Vector3d::UnitY();\n                transMat.block<3, 1>(0, transEqCnt++) = Eigen::Vector3d::UnitZ();\n            }\n            cout << \"distPts.size() = \" << distPts.size() << endl;\n            cout << \"distPtsDirs.size() = \" << distPtsDirs.size() << endl;\n            for(int dp = 0; dp < distPts.size(); ++dp){\n                transMat.block<3, 1>(0, transEqCnt++) = distPtsDirs[dp];\n            }\n        }\n//        if(transEqCnt != transEqNum){\n//            cout << \"transEqCnt != transEqNum\" << endl;\n//            throw std::exception();\n//        }\n        Eigen::FullPivLU<Eigen::MatrixXd> transLu(transMat);\n//            lu.setThreshold(sinValsThresh * distScale);\n        int transRank = transLu.rank();\n        cout << \"transLu.rank() = \" << transLu.rank() << endl;\n        if (transRank < 3) {\n            fullConstrTrans = false;\n        } else {\n            fullConstrTrans = true;\n        }\n    }\n\n}\n\nVector7d testTransform(const std::vector<Eigen::Vector3d> &points,\n                       const std::vector<Eigen::Vector4d> &planes,\n                       const std::vector<Vector6d> &lines,\n                       Vector7d transform,\n                       double sinValsThresh)\n{\n    cout << endl << \"testing transformation\" << endl;\n    cout << \"point.size() = \" << points.size() << endl;\n    cout << \"planes.size() = \" << planes.size() << endl;\n    cout << \"lines.size() = \" << lines.size() << endl;\n\n    for(int pt = 0; pt < points.size(); ++pt){\n        cout << \"points[\" << pt << \"] = \" << points[pt].transpose() << endl;\n    }\n    for(int pl = 0; pl < planes.size(); ++pl){\n        cout << \"planes[\" << pl << \"] = \" << planes[pl].transpose() << endl;\n    }\n    for(int l = 0; l < lines.size(); ++l){\n        cout << \"lines[\" << l << \"] = \" << lines[l].transpose() << endl;\n    }\n\n    Eigen::Vector3d trans = transform.head<3>();\n    Eigen::Vector4d rot = transform.tail<4>();\n    Eigen::Matrix3d rotMat = Eigen::Quaterniond(rot[3], rot[0], rot[1], rot[2]).toRotationMatrix();\n\n    std::vector<Eigen::Vector3d> retPoints;\n    std::vector<Eigen::Vector3d> retVirtPoints;\n    std::vector<Eigen::Vector3d> retDirs;\n    std::vector<double> retDists;\n    std::vector<Eigen::Vector3d> retDistDirs;\n    std::vector<Eigen::Vector3d> retDistPts;\n    std::vector<Eigen::Vector3d> retDistPtsDirs;\n    Matching::convertToPointsDirsDists(points,\n                                       planes,\n                                       lines,\n                                       retPoints,\n                                       retVirtPoints,\n                                       retDirs,\n                                       retDists,\n                                       retDistDirs,\n                                       retDistPts,\n                                       retDistPtsDirs);\n\n    bool fullConstrRot = true;\n    bool fullConstrTrans = true;\n    testFullConstr(retPoints,\n                   retVirtPoints,\n                   retDirs,\n                   retDists,\n                   retDistDirs,\n                   retDistPts,\n                   retDistPtsDirs,\n                   fullConstrRot,\n                   fullConstrTrans);\n\n\n    vector<Eigen::Vector3d> transPoints;\n    vector<Eigen::Vector4d> transPlanes;\n    vector<Vector6d> transLines;\n    transformObjs(points,\n                  planes,\n                  lines,\n                  transPoints,\n                  transPlanes,\n                  transLines,\n                  rotMat,\n                  trans,\n                  0.01,\n                  0.01);\n\n    std::vector<Eigen::Vector3d> retTransPoints;\n    std::vector<Eigen::Vector3d> retTransVirtPoints;\n    std::vector<Eigen::Vector3d> retTransDirs;\n    std::vector<double> retTransDists;\n    std::vector<Eigen::Vector3d> retTransDistDirs;\n    std::vector<Eigen::Vector3d> retTransDistPts;\n    std::vector<Eigen::Vector3d> retTransDistPtsDirs;\n    Matching::convertToPointsDirsDists(transPoints,\n                       transPlanes,\n                       transLines,\n                       retTransPoints,\n                       retTransVirtPoints,\n                       retTransDirs,\n                       retTransDists,\n                       retTransDistDirs,\n                       retTransDistPts,\n                       retTransDistPtsDirs);\n\n    bool fullConstrRotComp = true;\n    bool fullConstrTransComp = true;\n    cout << \"Running bestTransformPointsDirsDists\" << endl;\n    Vector7d transformComp = Matching::bestTransformPointsDirsDists(retTransPoints,\n                                                                    retPoints,\n                                                                    vector<double>(retPoints.size(), 1.0),\n                                                                    retTransVirtPoints,\n                                                                    retVirtPoints,\n                                                                    vector<double>(retVirtPoints.size(), 1.0),\n                                                                    retTransDirs,\n                                                                    retDirs,\n                                                                    vector<double>(retDirs.size(), 1.0),\n                                                                    retTransDists,\n                                                                    retDists,\n                                                                    retTransDistDirs,\n                                                                    vector<double>(retDists.size(), 1.0),\n                                                                    retTransDistPts,\n                                                                    retDistPts,\n                                                                    retTransDistPtsDirs,\n                                                                    vector<double>(retDistPts.size(), 1.0),\n                                                                    sinValsThresh,\n                                                                    fullConstrRotComp,\n                                                                    fullConstrTransComp);\n\n//    for(int dp = 0; dp < retDistPts.size(); ++dp){\n//        Eigen::Matrix4d Wrt = Misc::matrixW(Eigen::Quaterniond(transform[6],\n//                                               transform[3],\n//                                               transform[4],\n//                                               transform[5]).normalized()).transpose();\n//        Eigen::Matrix4d Qr = Misc::matrixQ(Eigen::Quaterniond(transform[6],\n//                                                              transform[3],\n//                                                              transform[4],\n//                                                              transform[5]).normalized());\n//\n//        cout << \"retDistPts = \" << retDistPts[dp].transpose() << endl;\n//        cout << \"retTransDistPts = \" << retTransDistPts[dp].transpose() << endl;\n//        cout << \"retTransDistPtsDir = \" << retTransDistPtsDirs[dp].transpose() << endl;\n//\n//        double d1 = retTransDistPtsDirs[dp].dot(retTransDistPts[dp]);\n//\n//        Eigen::Vector4d p2quat = Eigen::Vector4d::Zero();\n//        p2quat.head<3>() = retDistPts[dp];\n//        Eigen::Vector4d p2trans = Wrt * Qr * p2quat;\n//        double d2 = retTransDistPtsDirs[dp].dot(p2trans.head<3>());\n//\n//        cout << \"d1 = \" << d1 << endl;\n//        cout << \"d2 = \" << d2 << endl;\n//\n//        cout << \"t = \" << trans.transpose() << endl;\n//        cout << \"n * t = \" << retTransDistPtsDirs[dp].dot(trans) << endl;\n//        cout << \"d1 - d2 = \" << (d1 - d2) << endl;\n//        cout << \"n * t - (d1 - d2) = \" << retTransDistPtsDirs[dp].dot(trans) - (d1 - d2) << endl;\n//\n//\n//    }\n\n    double dist = Misc::transformLogDist(transform, transformComp);\n\n    cout << \"transform = \" << transform.transpose() << endl;\n    cout << \"transformComp = \" << transformComp.transpose() << endl;\n    REQUIRE(fullConstrRot == fullConstrRotComp);\n    REQUIRE(fullConstrTrans == fullConstrTransComp);\n    if(fullConstrRot == true &&\n       fullConstrTrans == true)\n    {\n        REQUIRE(dist < 0.4);\n    }\n    if(fullConstrRot == true){\n        double rotDist = Misc::rotLogDist(transform.tail<4>(), transformComp.tail<4>());\n        REQUIRE(rotDist < 0.2);\n    }\n    if(fullConstrTrans == true){\n        Eigen::Vector3d t = transform.head<3>();\n        Eigen::Vector3d tComp = transformComp.head<3>();\n        Eigen::Vector3d tDiff = t - tComp;\n        double tDist = tDiff.transpose() * tDiff;\n        REQUIRE(tDist < 0.2);\n    }\n}\n\nTEST_CASE(\"best transformations are correct\", \"[transformations]\"){\n    static constexpr int numPts = 10;\n    static constexpr int numPls = 10;\n    static constexpr int numLines = 10;\n    static constexpr int numTests = 10;\n    static constexpr double distScale = 10.0;\n    static constexpr double sinValsThresh = 0.001;\n\n    cout << \"Starting test\" << endl;\n    //[x, y, z]\n    vector<Eigen::Vector3d> points;\n    //[nx, ny, nz, -d]\n    vector<Eigen::Vector4d> planes;\n    //[px, py, pz, nx, ny, nz]\n    vector<Vector6d> lines;\n\n    for(int pt = 0; pt < numPts; ++pt){\n        points.push_back(Eigen::Vector3d::Random());\n        // from -10 do 10\n        points.back() *= distScale;\n    }\n    for(int pl = 0; pl < numPls; ++pl){\n        Eigen::Vector3d n = Eigen::Vector3d::Random();\n        // avoid numerical errors due to dividing by small numbers\n        while(n.norm() < 1e-6){\n            n = Eigen::Vector3d::Random();\n        }\n        n.normalize();\n\n        Eigen::Vector4d curPl = Eigen::Vector4d::Random();\n        curPl.head<3>() = n;\n        curPl[3] *= distScale;\n        planes.push_back(curPl);\n    }\n    for(int l = 0; l < numLines; ++l){\n        Eigen::Vector3d n = Eigen::Vector3d::Random();\n        // avoid numerical errors due to dividing by small numbers\n        while(n.norm() < 1e-6){\n            n = Eigen::Vector3d::Random();\n        }\n        n.normalize();\n        Eigen::Vector3d p = Eigen::Vector3d::Random();\n        p *= distScale;\n        // move point to be closest to the origin\n        p = Misc::closestPointOnLine(Eigen::Vector3d::Zero(),\n                                                    p,\n                                                    n);\n\n        Vector6d curLine;\n        curLine.head<3>() = p;\n        curLine.tail<3>() = n;\n        lines.push_back(curLine);\n    }\n\n\n    for(int t = 0; t < numTests; ++t){\n        Eigen::Vector3d trans = Eigen::Vector3d::Random();\n        Eigen::Vector4d rot = Eigen::Vector4d::Random();\n        rot.normalize();\n//        Eigen::Matrix3d rotMat = Eigen::Quaterniond(rot[3], rot[0], rot[1], rot[2]).toRotationMatrix();\n        Vector7d transform;\n        transform.head<3>() = trans;\n        transform.tail<4>() = rot;\n\n        //points only\n        for(int cpts = 0; cpts <= numPts; ++cpts){\n            std::default_random_engine gen;\n            std::uniform_int_distribution<int> distrPts(0, numPts - 1);\n\n            vector<Eigen::Vector3d> curPts;\n            for(int p = 0; p < cpts; ++p){\n                int idx = distrPts(gen);\n                curPts.push_back(points[idx]);\n            }\n\n            testTransform(curPts,\n                          vector<Eigen::Vector4d>(),\n                          vector<Vector6d>(),\n                          transform,\n                          sinValsThresh);\n        }\n\n        //planes only\n        for(int cpls = 0; cpls <= numPls; ++cpls){\n            std::default_random_engine gen;\n            std::uniform_int_distribution<int> distrPls(0, numPls - 1);\n\n            vector<Eigen::Vector4d> curPls;\n            for(int pl = 0; pl < cpls; ++pl){\n                int idx = distrPls(gen);\n                curPls.push_back(planes[idx]);\n            }\n\n            testTransform(vector<Eigen::Vector3d>(),\n                          curPls,\n                          vector<Vector6d>(),\n                          transform,\n                          sinValsThresh);\n        }\n\n\n        //lines only\n        for(int clines = 0; clines <= numLines; ++clines){\n            std::default_random_engine gen;\n            std::uniform_int_distribution<int> distrLines(0, numLines - 1);\n\n            vector<Vector6d> curLines;\n            for(int l = 0; l < clines; ++l){\n                int idx = distrLines(gen);\n                curLines.push_back(lines[idx]);\n            }\n\n            testTransform(vector<Eigen::Vector3d>(),\n                          vector<Eigen::Vector4d>(),\n                          curLines,\n                          transform,\n                          sinValsThresh);\n        }\n\n        //points + planes\n        for(int cpts = 0; cpts <= numPts; ++cpts){\n            for(int cpls = 0; cpls <= numPls; ++cpls) {\n                std::default_random_engine gen;\n\n                std::uniform_int_distribution<int> distrPts(0, numPts - 1);\n\n                vector<Eigen::Vector3d> curPts;\n                for (int p = 0; p < cpts; ++p) {\n                    int idx = distrPts(gen);\n                    curPts.push_back(points[idx]);\n                }\n\n\n                std::uniform_int_distribution<int> distrPls(0, numPls - 1);\n\n                vector<Eigen::Vector4d> curPls;\n                for (int pl = 0; pl < cpls; ++pl) {\n                    int idx = distrPls(gen);\n                    curPls.push_back(planes[idx]);\n                }\n\n                testTransform(curPts,\n                              curPls,\n                              vector<Vector6d>(),\n                              transform,\n                              sinValsThresh);\n            }\n        }\n\n        //points + lines\n        for(int cpts = 0; cpts <= numPts; ++cpts){\n            for(int clines = 0; clines <= numLines; ++clines) {\n                std::default_random_engine gen;\n                std::uniform_int_distribution<int> distrPts(0, numPts - 1);\n\n                vector<Eigen::Vector3d> curPts;\n                for (int p = 0; p < cpts; ++p) {\n                    int idx = distrPts(gen);\n                    curPts.push_back(points[idx]);\n                }\n\n                std::uniform_int_distribution<int> distrLines(0, numLines - 1);\n\n                vector<Vector6d> curLines;\n                for (int l = 0; l < clines; ++l) {\n                    int idx = distrLines(gen);\n                    curLines.push_back(lines[idx]);\n                }\n\n                testTransform(curPts,\n                              vector<Eigen::Vector4d>(),\n                              curLines,\n                              transform,\n                              sinValsThresh);\n            }\n        }\n\n        //planes + lines\n        for(int cpls = 0; cpls <= numPls; ++cpls){\n            for(int clines = 0; clines <= numLines; ++clines) {\n                std::default_random_engine gen;\n                std::uniform_int_distribution<int> distrPls(0, numPls - 1);\n\n                vector<Eigen::Vector4d> curPls;\n                for (int pl = 0; pl < cpls; ++pl) {\n                    int idx = distrPls(gen);\n                    curPls.push_back(planes[idx]);\n                }\n\n                std::uniform_int_distribution<int> distrLines(0, numLines - 1);\n\n                vector<Vector6d> curLines;\n                for (int l = 0; l < clines; ++l) {\n                    int idx = distrLines(gen);\n                    curLines.push_back(lines[idx]);\n                }\n\n                testTransform(vector<Eigen::Vector3d>(),\n                              curPls,\n                              curLines,\n                              transform,\n                              sinValsThresh);\n            }\n        }\n\n        //points + planes + lines\n        for(int cpts = 0; cpts <= numPts; ++cpts){\n            for(int cpls = 0; cpls <= numPls; ++cpls) {\n                for(int clines = 0; clines <= numLines; ++clines) {\n                    std::default_random_engine gen;\n\n                    std::uniform_int_distribution<int> distrPts(0, numPts - 1);\n\n                    vector<Eigen::Vector3d> curPts;\n                    for (int p = 0; p < cpts; ++p) {\n                        int idx = distrPts(gen);\n                        curPts.push_back(points[idx]);\n                    }\n\n\n                    std::uniform_int_distribution<int> distrPls(0, numPls - 1);\n\n                    vector<Eigen::Vector4d> curPls;\n                    for (int pl = 0; pl < cpls; ++pl) {\n                        int idx = distrPls(gen);\n                        curPls.push_back(planes[idx]);\n                    }\n\n                    std::uniform_int_distribution<int> distrLines(0, numLines - 1);\n\n                    vector<Vector6d> curLines;\n                    for (int l = 0; l < clines; ++l) {\n                        int idx = distrLines(gen);\n                        curLines.push_back(lines[idx]);\n                    }\n\n                    testTransform(curPts,\n                                  curPls,\n                                  curLines,\n                                  transform,\n                                  sinValsThresh);\n                }\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "e3362e41754a255ea8f9873256aa5ff6fb815986", "size": 21896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Tests.cpp", "max_stars_repo_name": "richard5635/PlaneLoc", "max_stars_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-08-29T06:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T07:42:31.000Z", "max_issues_repo_path": "tests/Tests.cpp", "max_issues_repo_name": "richard5635/PlaneLoc", "max_issues_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-03-26T06:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T01:59:41.000Z", "max_forks_repo_path": "tests/Tests.cpp", "max_forks_repo_name": "richard5635/PlaneLoc", "max_forks_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-04-24T08:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T07:56:58.000Z", "avg_line_length": 38.6172839506, "max_line_length": 110, "alphanum_fraction": 0.4586682499, "num_tokens": 5113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5305570715666569}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/LevenbergMarquardt>\n#include <unsupported/Eigen/MatrixFunctions>\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid flatten(Matrix<double, 4, 4> &g, Matrix<double,1,12> &y) {\n    y(0) = g(0,0);\n    y(1) = g(0,1);\n    y(2) = g(0,2);\n    y(3) = g(1,0);\n    y(4) = g(1,1);\n    y(5) = g(1,2);\n    y(6) = g(2,0);\n    y(7) = g(2,1);\n    y(8) = g(2,2);\n    y(9) = g(0,3);\n    y(10) = g(1,3);\n    y(11) = g(2,3);\n}\n\nvoid unflatten(Matrix<double, 1, 12> &y, Matrix<double, 4, 4> &g) {\n    g(0,0) = y(0);\n    g(0,1) = y(1);\n    g(0,2) = y(2);\n    g(1,0) = y(3);\n    g(1,1) = y(4);\n    g(1,2) = y(5);\n    g(2,0) = y(6);\n    g(2,1) = y(7);\n    g(2,2) = y(8);\n    g(0,3) = y(9);\n    g(1,3) = y(10);\n    g(2,3) = y(11);\n    g(3,0) = 0;\n    g(3,1) = 0;\n    g(3,2) = 0;\n    g(3,3) = 1;\n}\n\nvoid skew(Matrix<double, 3, 1> &x, Matrix<double, 3, 3> &y) {\n    y(0,1) = -x(2);\n    y(0,2) = x(1);\n    y(1,0) = x(2);\n    y(1,2) = -x(0);\n    y(2,0) = -x(1);\n    y(2,1) = x(0);\n    y(0,0) = 0;\n    y(1,1) = 0;\n    y(2,2) = 0;\n}\n\nvoid adjoint(Matrix<double, 6, 1> &x, Matrix<double, 6, 6> &y) {\n    Vector3d w = x.head<3>();\n    Vector3d v = x.tail<3>();\n    Matrix3d w_skew;\n    Matrix3d v_skew;\n\n    skew(w,w_skew);\n    skew(v,v_skew);\n\n    y.block<3,3>(0,0) = w_skew;\n    y.block<3,3>(3,0) = v_skew;\n    y.block<3,3>(0,3) = Matrix3d::Zero();\n    y.block<3,3>(3,3) = w_skew;\n}\n\nvoid se(Matrix<double, 6, 1> &x, Matrix<double, 4, 4> &y) {\n    Vector3d w = x.head<3>();\n    Vector3d v = x.tail<3>();\n    Matrix3d w_skew;\n    skew(w,w_skew);\n    y.block<3,3>(0,0) = w_skew;\n    y.block<3,1>(0,3) = v;\n    y(3,0) = 0;\n    y(3,1) = 0;\n    y(3,2) = 0;\n    y(3,3) = 0;\n\n}\n\n// initial implementation of rod\nclass Rod {\n    private:\n        double D;\n        double L;\n        double E;\n        double G;\n        double rho;\n        double mu;\n        double ds;\n        int N;\n        Matrix<double, 6, 6> K; //not necessarily diagonal, but for now its alright\n        DiagonalMatrix<double, 6> M; //always diagonal\n        DiagonalMatrix<double, 6> V; //I suppose not always diagonal\n        Matrix<double, 6, 1> xi_ref;\n    public:\n        Matrix<double, Dynamic, 6> xi;\n        Matrix<double, Dynamic, 6> eta;\n        Matrix<double, Dynamic, 12> g;\n        Rod(double D, double L, double E, double rho, double mu, int N);\n        double energy(void);\n        void step(double dt);\n        VectorXd condition(Rod *prev, double dt, VectorXd xi0);\n        void integrate(Rod *prev, double dt, VectorXd xi0);\n\n};\n\n// function object, for some reason called a functor in c++\nclass LM_Functor : public DenseFunctor<double> {\n    double dt;\n    Rod *prev;\n    Rod &next;\n    public:\n        LM_Functor(Rod *r, Rod &c, double t) : DenseFunctor<double>(6, 6), prev(r), next(c), dt(t) {};\n        int operator()(const VectorXd &x, VectorXd &fvec) const {\n            // x is the input for xi0\n            // fvec is the tip condition values\n            fvec = next.condition(prev, dt, x);\n            return 0;\n        }\n};\n\nRod::Rod(double d, double l, double e, double r, double m, int n) {\n    D = d;\n    L = l;\n    E = e;\n    G = E/3;\n    rho = r;\n    mu = m;\n    N = n;\n    ds = L/(N-1);\n\n    double A = M_PI/4*pow(D,2);\n    double I = M_PI/64*pow(D,4);\n    double J = 2*I;\n\n    //simplest initialization\n    // seems like there would be a better way to initialize these\n    int i;\n    MatrixXd xi_temp(N,6);\n    MatrixXd g_temp(N,12);\n    for (i=0; i<N; i++) {\n        xi_temp(i,0) = 0;\n        xi_temp(i,1) = M_PI/(4*10e-2);\n        xi_temp(i,2) = 0;\n        xi_temp(i,3) = 0;\n        xi_temp(i,4) = 0;\n        xi_temp(i,5) = 1;\n\n        g_temp(i,0) = 1;\n        g_temp(i,1) = 0;\n        g_temp(i,2) = 0;\n        g_temp(i,3) = 0;\n        g_temp(i,4) = 1;\n        g_temp(i,5) = 0;\n        g_temp(i,6) = 0;\n        g_temp(i,7) = 0;\n        g_temp(i,8) = 1;\n        g_temp(i,9) = 0;\n        g_temp(i,10) = 0;\n        g_temp(i,11) = ds*i;\n    }\n    xi = xi_temp;\n    g = g_temp;\n    eta = MatrixXd::Constant(N,6,0);\n\n    K = Matrix<double, 6, 6>::Zero();\n\n    K.diagonal() << E*I, E*I, G*J, G*A, G*A, E*A;\n    M.diagonal() << I, I, J, A, A, A;\n    M = rho*M;\n    V.diagonal() << 3*I, 3*I, J, A, A, 3*A;\n    V = mu*V;\n\n    xi_ref << 0, 0, 0, 0, 0, 1;\n\n}\n\ndouble Rod::energy(void) {\n    double H = 0;\n    int i;\n    for (i=0; i<N; i++) {\n        H += 0.5 * eta.row(i) * M * eta.row(i).transpose();\n        H += 0.5 * (xi.row(i).transpose() - xi_ref).transpose() * K * (xi.row(i).transpose() - xi_ref);\n    }\n    return ds*H;\n}\n\nvoid Rod::step(double dt) {\n    // solve the condition\n    Rod prev = *this;\n    VectorXd guess = xi.row(0);\n    LM_Functor functor(&prev, *this, dt);\n    DenseIndex nfev;\n    int info;\n    info = LevenbergMarquardt<LM_Functor>::lmdif1(functor, guess, &nfev);\n\n//    this->integrate(&prev, dt, guess);\n}\n\nVectorXd Rod::condition(Rod *prev, double dt, VectorXd xi0) {\n\n    this->integrate(prev, dt, xi0);\n    return xi.row(N-1).transpose() - xi_ref;\n\n}\n\nvoid Rod::integrate(Rod *prev, double dt, VectorXd xi0) {\n\n    Matrix<double, 6, 1> xi_half;\n    Matrix<double, 6, 1> eta_half;\n    Matrix<double, 6, 1> xi_half_next;\n    Matrix<double, 6, 1> eta_half_next;\n    Matrix<double, 6, 1> xi_dot;\n    Matrix<double, 6, 1> eta_dot;\n    Matrix<double, 6, 1> xi_der;\n    Matrix<double, 6, 1> eta_der;\n    Matrix<double, 6, 1> B_bar;\n\n    Matrix<double, 6, 6> A_bar;\n    Matrix<double, 6, 6> xi_ad;\n    Matrix<double, 6, 6> eta_ad;\n\n    Matrix4d eta_se;\n    Matrix<double, 1, 12> g_row;\n\n    xi.row(0) = xi0.transpose();\n\n    Matrix4d G = Matrix4d::Identity();\n    int i;\n    for (i=0; i<N-1; i++) {\n        xi_half = (xi.row(i) + prev->xi.row(i)).transpose()/2;\n        eta_half = (eta.row(i) + prev->eta.row(i)).transpose()/2;\n\n        xi_dot = (xi.row(i) - prev->xi.row(i)).transpose()/dt;\n        eta_dot = (eta.row(i) - prev->eta.row(i)).transpose()/dt;\n\n        A_bar = Matrix<double, 6, 6>::Zero();\n        B_bar = Matrix<double, 6, 1>::Zero();\n\n        B_bar = V * xi_dot;\n\n        adjoint(xi_half, xi_ad);\n        adjoint(eta_half, eta_ad);\n\n        xi_der = K.ldlt().solve(((M * eta_dot) - (eta_ad.transpose() * M * eta_half) + (xi_ad.transpose() * K * (xi_half - xi_ref)) + B_bar));\n        eta_der = xi_dot - xi_ad * eta_half;\n\n        xi_half_next = xi_half + ds * xi_der;\n        eta_half_next = eta_half + ds * eta_der;\n\n        xi.row(i+1) = (2 * xi_half_next.transpose() - prev->xi.row(i+1));\n        eta.row(i+1) = (2 * eta_half_next.transpose() - prev->eta.row(i+1));\n\n    }\n\n//    for (i=0; i<N; i++) {\n//        g_row = prev->g.row(i);\n//        unflatten(g_row, G);\n//        eta_half = (eta.row(i)+prev->eta.row(i)).transpose()/2*ds;\n//        se(eta_half, eta_se);\n//        G = G * eta_se.exp();\n//        flatten(G, g_row);\n//        g.row(i) = g_row;\n//    }\n\n}\n\n\n\n\n\nint main() {\n    double dt = 0.05;\n    Rod r1(1e-2,10e-2,1e6,1e3,0,40);\n    cout << r1.energy() << endl;\n    int i;\n    for (i=0; i<1000; i++) {\n        r1.step(dt);\n        cout << r1.energy() << endl;\n    }\n\n//    Matrix<double, 6,1> xi;\n//    xi << 1, 2, 3, 4, 5, 6;\n//    Matrix4d xi_se;\n//    Matrix<double, 6, 6> xi_ad;\n//\n//    cout << xi << endl;\n//    se(xi,xi_se);\n//    cout << xi_se << endl;\n//    adjoint(xi,xi_ad);\n//    cout << xi_ad << endl;\n\n\n    return 0;\n}", "meta": {"hexsha": "4718bf9366fac4f76dceeebf177660b9bdaacfc5", "size": 7321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/main.cpp", "max_stars_repo_name": "BenPski/RodDynamics", "max_stars_repo_head_hexsha": "a9d6521eb7253dba794c4e2b54ea631b74e11210", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-06T14:20:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T06:27:50.000Z", "max_issues_repo_path": "c++/main.cpp", "max_issues_repo_name": "BenPski/RodDynamics", "max_issues_repo_head_hexsha": "a9d6521eb7253dba794c4e2b54ea631b74e11210", "max_issues_repo_licenses": ["MIT"], "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": "BenPski/RodDynamics", "max_forks_repo_head_hexsha": "a9d6521eb7253dba794c4e2b54ea631b74e11210", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-22T21:51:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-28T20:18:29.000Z", "avg_line_length": 24.4849498328, "max_line_length": 142, "alphanum_fraction": 0.5084004917, "num_tokens": 2761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5305570599737455}}
{"text": "/* boost random/binomial_distribution.hpp header file\r\n *\r\n * Copyright Jens Maurer 2002\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: binomial_distribution.hpp,v 1.9 2004/07/27 03:43:32 dgregor Exp $\r\n *\r\n */\r\n\r\n#ifndef BOOST_RANDOM_BINOMIAL_DISTRIBUTION_HPP\r\n#define BOOST_RANDOM_BINOMIAL_DISTRIBUTION_HPP\r\n\r\n#include <cmath>\r\n#include <cassert>\r\n#include <boost/random/bernoulli_distribution.hpp>\r\n\r\nnamespace boost {\r\n\r\n// Knuth\r\ntemplate<class IntType = int, class RealType = double>\r\nclass binomial_distribution\r\n{\r\npublic:\r\n  typedef typename bernoulli_distribution<RealType>::input_type input_type;\r\n  typedef IntType result_type;\r\n\r\n  explicit binomial_distribution(IntType t = 1,\r\n                                 const RealType& p = RealType(0.5))\r\n    : _t(t)\r\n  {\r\n    assert(t >= 0);\r\n    assert(RealType(0) <= 0 && p <= RealType(1));\r\n  }\r\n\r\n  // compiler-generated copy ctor and assignment operator are fine\r\n\r\n  IntType t() const { return _t; }\r\n  RealType p() const { return _bernoulli.p(); }\r\n  void reset() { }\r\n\r\n  template<class Engine>\r\n  result_type operator()(Engine& eng)\r\n  {\r\n    // TODO: This is O(_t), but it should be O(log(_t)) for large _t\r\n    result_type n = 0;\r\n    for(IntType i = 0; i < _t; ++i)\r\n      if(_bernoulli(eng))\r\n        ++n;\r\n    return n;\r\n  }\r\n\r\n#if !defined(BOOST_NO_OPERATORS_IN_NAMESPACE) && !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)\r\n  template<class CharT, class Traits>\r\n  friend std::basic_ostream<CharT,Traits>&\r\n  operator<<(std::basic_ostream<CharT,Traits>& os, const binomial_distribution& bd)\r\n  {\r\n    os << bd._bernoulli << \" \" << bd._t;\r\n    return os;\r\n  }\r\n\r\n  template<class CharT, class Traits>\r\n  friend std::basic_istream<CharT,Traits>&\r\n  operator>>(std::basic_istream<CharT,Traits>& is, binomial_distribution& bd)\r\n  {\r\n    is >> std::ws >> bd._bernoulli >> std::ws >> bd._t;\r\n    return is;\r\n  }\r\n#endif\r\n\r\nprivate:\r\n  bernoulli_distribution<RealType> _bernoulli;\r\n  IntType _t;\r\n};\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_RANDOM_BINOMIAL_DISTRIBUTION_HPP\r\n", "meta": {"hexsha": "c899340be75a6e9f4b1f0902789432fb9ce2b439", "size": 2245, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/random/binomial_distribution.hpp", "max_stars_repo_name": "macaurther/DOCUSA", "max_stars_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2015-11-20T04:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:03:08.000Z", "max_issues_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/random/binomial_distribution.hpp", "max_issues_repo_name": "macaurther/DOCUSA", "max_issues_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 206.0, "max_issues_repo_issues_event_min_datetime": "2015-11-09T00:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-04T19:05:18.000Z", "max_forks_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/random/binomial_distribution.hpp", "max_forks_repo_name": "dguenms/Dawn-of-Civilization", "max_forks_repo_head_hexsha": "1c4f510af97a869637cddb4c0859759158cea5ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 117.0, "max_forks_repo_forks_event_min_datetime": "2015-11-08T02:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T06:29:00.000Z", "avg_line_length": 27.3780487805, "max_line_length": 92, "alphanum_fraction": 0.668596882, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.530492920364802}}
{"text": "/*\n * Copyright 2016 C. Brett Witherspoon\n */\n\n#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <iostream>\n#include <stdexcept>\n#include <random>\n\n#include <boost/preprocessor/stringize.hpp>\n#include <boost/program_options.hpp>\n#include <boost/compute/core.hpp>\n\n#include <signum/opencl/fft.hpp>\n\nnamespace compute = boost::compute;\nnamespace po = boost::program_options;\nnamespace opencl = signum::opencl;\n\nint main(int argc, char *argv[])\n{\n    size_t length;\n\n    po::options_description desc(\"Supported options\");\n    desc.add_options()\n        (\"help,h\", \"print help message\")\n        (\"length,l\", po::value<size_t>(&length)->default_value(8), \"set FFT length\")\n        (\"verbose,v\", \"print verbose messages\");\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\"))\n    {\n        std::cerr << desc << std::endl;\n        return 1;\n    }\n\n    compute::device device = compute::system::default_device();\n    compute::context context(device);\n    compute::command_queue queue(context, device, compute::command_queue::enable_profiling);\n\n    // Print some device information\n    std::cout << device.platform().name() << \": \" << device.name() << std::endl;\n    std::cout << \"Global memory size: \" << device.global_memory_size() << std::endl;\n    std::cout << \"Local memory size: \" << device.local_memory_size() << std::endl;\n    std::cout << \"Compute units: \" << device.compute_units() << std::endl;\n    std::cout << \"Preferred vector width: \" <<device.preferred_vector_width<float>() << std::endl;\n\n    // Create FFT object\n    opencl::fft fft(queue, length);\n\n    // Initialize input buffer\n    auto input = fft.map(compute::command_queue::map_write);\n    std::default_random_engine eng;\n    std::normal_distribution<> dist{0, 1};\n    auto rand = std::bind(dist, eng);\n    std::generate(input, input + length, rand);\n    if (vm.count(\"verbose\"))\n    {\n        std::cout << \"Input: \" << std::endl;\n        for (size_t i = 0; i < length; ++i) std::cout << input[i] << std::endl;\n    }\n    fft.unmap().wait();\n\n    // Enqueue kernels\n    auto events = fft();\n\n    events.wait();\n\n    // Print profiling information\n    std::chrono::nanoseconds time{0};\n    for (const auto &event : events)\n    {\n        time += event.duration<std::chrono::nanoseconds>();\n    }\n    std::cout << \"Execute time: \" << time.count() << \" ns\" << std::endl;\n\n    // Print output buffer\n    auto output = fft.map(compute::command_queue::map_read);\n    if (vm.count(\"verbose\"))\n    {\n        std::cout << \"Output: \" << std::endl;\n        for (size_t i = 0; i < length; ++i) std::cout << output[i] << std::endl;\n    }\n    fft.unmap().wait();\n\n    return 0;\n}\n", "meta": {"hexsha": "5d54952cebc9def9dd192153bba9fd9ceb15c9d2", "size": 2745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/fft_benchmark.cpp", "max_stars_repo_name": "spoonb/libcomm", "max_stars_repo_head_hexsha": "5638dac889bddb16420d8321067c783438a5deaf", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/fft_benchmark.cpp", "max_issues_repo_name": "spoonb/libcomm", "max_issues_repo_head_hexsha": "5638dac889bddb16420d8321067c783438a5deaf", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/fft_benchmark.cpp", "max_forks_repo_name": "spoonb/libcomm", "max_forks_repo_head_hexsha": "5638dac889bddb16420d8321067c783438a5deaf", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5161290323, "max_line_length": 98, "alphanum_fraction": 0.618579235, "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5304929203648019}}
{"text": "/*\n * Mesh.cpp\n *\n * This class contains the mesh and mesh properties to be used\n * in the nonlinear finite element method (FiniteElemNL.cpp).\n *\n * It constructs the mesh, then constructs the stiffness matrix and\n * calculates the boundary. It can be refined by calling\n * uniformrefine().\n *\n *  Created on: Aug 13, 2016\n *      Author: Ted Kwan\n */\n\n#include \"MeshMG.h\"\n#include \"ArmaFuns.h\"\n#include <cmath>\n#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nMeshMG::MeshMG() {\n\n}\n\n/**\n * Constructor for MeshMG. It takes one input, a vector containing the\n * properties of the mesh to be created.\n *\n * @param meshprops - double vector with all of the necessary properties.\n */\nMeshMG::MeshMG(vector<double> meshprops) {\n\t// Extract the mesh size value.\n\th = meshprops[4];\n\tn = round(1 / h);\n\t// Create vectors to be used for mesh creation.\n\tvec xr = linspace<vec>(meshprops[0], meshprops[1], n + 1);\n\tvec yr = linspace<vec>(meshprops[2], meshprops[3], n + 1);\n\t// Create the mesh.\n\tmakeMesh(xr, yr);\n\t// Assemble stiffness matrix\n\tvector<sp_mat> stiffmass = assembleMatrix();\n\tstiffness=stiffmass[0];\n\tmass=stiffmass[1];\n\t// Calculate boundary nodes.\n\tfindBoundary();\n}\n\n/**\n * makeMeshMG creates the mesh for the 2D Cartesian grid.\n *\n * @param xr - input vector containing the x values.\n * @param yr - input vector containing the y values.\n */\nvoid MeshMG::makeMesh(vec xr, vec yr) {\n\t// Findthe lengths to use.\n\tuword xrl = xr.n_rows;\n\tuword yrl = xr.n_rows;\n\tmat x = zeros<mat>(xrl, yrl);\n\tmat y = zeros<mat>(xrl, yrl);\n\t// Construct the meshes. This is just the same\n\t// as calling meshgrid() in MATLAB.\n\tfor (uword i = 0; i < yrl; i++) {\n\t\tx.row(i) = xr.t();\n\t}\n\tfor (uword i = 0; i < xrl; i++) {\n\t\ty.col(i) = yr;\n\t}\n\t// Vectorise the values to use for the nodes matrix.\n\tvec xv = vectorise(x);\n\tN = xv.n_rows;\n\tNs.push_back(N);\n\tuword ni = x.n_rows;\n\t// Initialize node matrix.\n\tnode = zeros<mat>(N, 2);\n\t// put all the values in the node matrix\n\tnode.col(0) = xv;\n\tnode.col(1) = vectorise(y);\n\t// Map the indices for the nodes to create elem matrix.\n\tuvec t2nidxMapnz = regspace<uvec>(0, N - ni - 1);\n\tuvec topNode = regspace<uvec>(ni - 1, ni, N - ni - 1);\n\t// Set all of the doubled nodes to not be included.\n\tt2nidxMapnz(topNode) = zeros<uvec>(topNode.n_rows);\n\t// Find nonzeros in the original indices map.\n\tuvec nnz = nonzeros(t2nidxMapnz);\n\tuvec k = zeros<uvec>(nnz.n_rows + 1);\n\t// Calculate the different values used to create nodes.\n\tk(span(1, nnz.n_rows)) = nnz;\n\tuword NE = k.n_rows;\n\tHBs.push_back(zeros<umat>(3,3));\n\tcoarse2Fine.push_back(zeros<uvec>(3));\n\tPro.push_back(zeros<sp_mat>(3,3));\n\t// Create the elements which will differ by odd and\n\t// even elements.\n\tumat elemup = zeros<umat>(NE, 3);\n\tumat elemdown = zeros<umat>(NE, 3);\n\tuvec niv = ones<uvec>(k.n_rows);\n\tniv = niv * ni;\n\tuvec onek = ones<uvec>(k.n_rows);\n\t// Map elements to nodes in order.\n\telemup.col(0) = k + niv;\n\telemup.col(1) = k + niv + onek;\n\telemup.col(2) = k;\n\telemdown.col(0) = k + onek;\n\telemdown.col(1) = k;\n\telemdown.col(2) = k + niv + onek;\n\t// join all columns together and stack them properly.\n\telem = join_cols(elemup, elemdown);\n\tNT = elem.n_rows;\n\trefines=0;\n}\n\n/**\n * assembleMatrix assembles the stiffness matrix using the quick\n * construction method from armadillo for sparse matrices.\n *\n * @return - Stiffness matrix as a sparse matrix.\n */\nvector<sp_mat> MeshMG::assembleMatrix() {\n\t// Initialize index maps and value vector.\n\tuvec ii = zeros<uvec>(9 * NT);\n\tuvec jj = zeros<uvec>(9 * NT);\n\tvec sA = zeros<vec>(9 * NT);\n\t// Calculate the area of each node.\n\tcube ve(NT, 2, 3);\n\tve.slice(0) = node.rows(elem.col(2)) - node.rows(elem.col(1));\n\tve.slice(1) = node.rows(elem.col(0)) - node.rows(elem.col(2));\n\tve.slice(2) = node.rows(elem.col(1)) - node.rows(elem.col(0));\n\t// Find the area using the dot product on the second dimension.\n\tarea = 0.5*abs((ve.slice(2).col(0) % ve.slice(1).col(1))\n\t\t\t\t\t-(ve.slice(2).col(1) % ve.slice(1).col(0)));\n\tuword index = 0;\n\t// Loop to map values and indices.\n\tfor (uword i = 0; i < 3; i++) {\n\t\tfor (uword j = 0; j < 3; j++) {\n\t\t\t// Setup indices to map in this iteration.\n\t\t\tuvec inds = regspace<uvec>(index, index + NT - 1);\n\t\t\t// Setup element maps for indices.\n\t\t\tii(inds) = elem.col(i);\n\t\t\tjj(inds) = elem.col(j);\n\t\t\t// Calculate values of stiffness matrix at\n\t\t\t// these points.\n\t\t\tmat prod = ve.slice(i) % ve.slice(j);\n\t\t\t// Store calculated value.\n\t\t\tsA(inds) = sum(prod, 1) / (4 * area);\n\t\t\tindex = index + NT;\n\t\t}\n\t}\n\t// Setup index map to be a 2x9NT matrix.\n\tumat inds = join_horiz(ii, jj);\n\t// Create the sparse matrix using the same\n\t// method as sparse(row indices, col indices, values, size)\n\tsp_mat A(true, inds.t(), sA, N, N, true, true);\n\tvector<sp_mat> matvec(2);\n\tmatvec[0]=A;\n\t// Create mass matrix.\n\tvec Mv=accumArrayM(join_vert(elem.col(0), join_vert(elem.col(1),elem.col(2)))\n\t\t\t,join_vert(area, join_vert(area,area))/(3.0), N);\n\tuvec inds2=regspace<uvec>(0,Mv.n_rows-1);\n\tumat subs2=join_horiz(inds2,inds2);\n\tsp_mat M(true,subs2.t(),Mv,N,N,true,true);\n\tmatvec[1]=M;\n\tmasses.push_back(Mv);\n\tstiffs.push_back(A);\n\treturn matvec;\n}\n\n/**\n * Find the boundary nodes and elements.\n *\n * This method calculates the boundary for the given mesh to be used\n * to set the boundary condition for the finite element method.\n *\n * Values are stored so that they can be accesssed later.\n *\n */\nvoid MeshMG::findBoundary() {\n\n\t// Setup as two column vectors to find the edges.\n\tumat e1 = join_vert(join_horiz(elem.col(2), elem.col(1)),\n\t\t\tjoin_horiz(elem.col(0), elem.col(2)));\n\t// Calculate all of the values of the edges.\n\tumat totalEdge = join_vert(e1, join_horiz(elem.col(1), elem.col(0)));\n\ttotalEdge = sort(totalEdge, \"ascend\", 1);\n\tvec onev = ones<vec>(totalEdge.n_rows);\n\t// Create sparse matrix containing the edges which are not being double counted\n\t// and are thus exterior edges.\n\tsp_mat fndmat(true, totalEdge.t(), onev, totalEdge.n_rows, totalEdge.n_rows,\n\t\t\ttrue, true);\n\t// Initialize edge matrix.\n\tumat bdEdge = zeros<umat>(totalEdge.n_rows, 2);\n\tvec s = nonzeros(fndmat);\n\tuvec ii = zeros<uvec>(s.n_elem);\n\tuvec jj = zeros<uvec>(s.n_elem);\n\tuword k = 0;\n\t// Get the indices for the edges which are exterior edges.\n\t// The indices map back to nodes.\n\tfor (uword i = 0; i < fndmat.n_rows; i++) {\n\t\tfor (uword j = 0; j < fndmat.n_cols; j++) {\n\t\t\tdouble spot = fndmat(i, j);\n\t\t\t// Only find edges where there are two boundary nodes.\n\t\t\tif (spot == 1.0 && k < s.n_elem) {\n\t\t\t\tii(k) = i;\n\t\t\t\tjj(k) = j;\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t}\n\tuvec i1 = nonzeros(ii);\n\tuvec j1 = nonzeros(jj);\n\t// Setup boolean vector which has whether or not a node is a boundary\n\t// node.\n\tisbdNode = zeros<uvec>(N);\n\tisbdNode.rows(i1) = ones<uvec>(i1.n_rows);\n\tisbdNode.rows(j1) = ones<uvec>(j1.n_rows);\n\tisbdNode(0) = 1.0;\n\t// Find indices of boundary nodes.\n\tbdNode = find(isbdNode);\n\tuvec onebd = ones<uvec>(isbdNode.n_rows);\n\t// Find indices of interior nodes.\n\tfreeNode = find(onebd - isbdNode);\n\tfreeNodes.push_back(freeNode);\n\n}\n\n/**\n * accumArrayM implements the accumarray method from MATLAB.\n *\n * This is a direct implementation and does the exact same thing\n * as the MATLAB function.\n *\n * @param subs - vector of indices.\n * @param ar - vector of values.\n * @param N - size of the array to be made.\n * @return accumulated array (same as MATLAB would).\n */\nvec MeshMG::accumArrayM(uvec subs,vec ar,uword N){\n\n\tvec S=zeros<vec>(N);\n\n\tfor(uword i=0;i<N;i++){\n\t\t// Get the subscripts.\n\t\tuvec q1=find(subs ==(i));\n\t\tvec spot;\n\t\tdouble thesum=0.0;\n\t\tif(!q1.is_empty()){\n\t\t\t// Find elements at indices q1\n\t\t\tspot=ar.elem(q1);\n\t\t\t// Sum elements.\n\t\t\tthesum=sum(spot);\n\t\t\t// Set at position i.\n\t\t\tS(i)=thesum;\n\t\t}\n\t\t// If it is empty, add 0.\n\t\telse{\n\t\t\tS(i)=0.0;\n\t\t}\n\t}\n\n\treturn S;\n}\n\n/**\n * uniformrefine refines the mesh and re-calculates the boundary\n * as well as all of the needed matrices and vectors.\n *\n * This function ensures that the mesh is refined by adding nodes at\n * the midpoints of all edges in each element.\n *\n */\nvoid MeshMG::uniformrefine(){\n\t// Find all of the edges.\n\tumat e23=join_horiz(elem.col(1),elem.col(2));\n\tumat e31=join_horiz(elem.col(2),elem.col(0));\n\tumat e12=join_horiz(elem.col(0),elem.col(1));\n\t// Matrix with all edge indices (n1 -> n2),\n\tumat totalEdge=sort(join_vert(e23,join_vert(e31,e12)),\"ascend\",1);\n\tArmaFuns funs;\n\t// Implementation of unique in MATLAB.\n\tumat edge=funs.uniqueu(totalEdge);\n\tuvec js=funs.uniqueidx;\n\tuword NE=edge.n_rows;\n\t// Map elems to edges.\n\tumat elem2edge=zeros<umat>(NT*3,1);\n\telem2edge.col(0)=js;\n\telem2edge.reshape(NT,3);\n\t// New nodes to create.\n\tmat nnode=(node.rows(edge.col(0))+node.rows(edge.col(1)))/(2.0);\n\t// Concatinate the new nodes with the old.\n\tnode=join_vert(node,nnode);\n\t// Re-map edges including new nodes.\n\tuvec edge2newNode=regspace<uvec>(N,N+NE-1);\n\t// Make hierarchical basis.\n\tHB=join_horiz(edge2newNode,edge);\n\tuvec t=regspace<uvec>(0,NT-1);\n\t// Indices for the new elements.\n\tumat p= join_horiz(elem,\n\t\t\tjoin_horiz(edge2newNode.rows(elem2edge.col(0)),\n\t\t\tjoin_horiz(edge2newNode.rows(elem2edge.col(1)),\n\t\t\t\t\tedge2newNode.rows(elem2edge.col(2)))));\n\t// Add elements to the elem matrix.\n\telem.rows(t)=join_horiz(p.col(0),join_horiz(p.col(4),p.col(5)));\n\t// Create new elements.\n\tumat nelem=zeros<umat>(4*NT,3);\n\tnelem.rows(span(NT,2*NT-1))=join_horiz(p.col(5),join_horiz(p.col(1),p.col(3)));\n\tnelem.rows(span(2*NT,3*NT-1))=join_horiz(p.col(4),join_horiz(p.col(3),p.col(2)));\n\tnelem.rows(span(3*NT,4*NT-1))=join_horiz(p.col(3),join_horiz(p.col(4),p.col(5)));\n\tnelem.rows(span(0,NT-1))=elem;\n\telem=nelem;\n\t// Save new information.\n\tNT=elem.n_rows;\n\tN=node.n_rows;\n\trefines=refines+1;\n\tNs.push_back(N);\n\tHBs.push_back(HB);\n\tProHB();\n\tvector<sp_mat> stiffmass = assembleMatrix();\n\tstiffness=stiffmass[0];\n\tmass=stiffmass[1];\n\tfindBoundary();\n}\n\n/**\n * ProHB creates the prolongation and restriction matrices,\n * as well as maps the fine nodes to the coarse nodes for the FAS.\n *\n * This function ensures that the multigrid method works properly and\n * interpolates the coarse grid to the fine grid, as well as restricts\n * the coarse grid and the fine grid.\n *\n */\nvoid MeshMG::ProHB(){\n\t// Get the number of coarse nodes.\n\tuword nCoarse = Ns[Ns.size()-2];\n\tuword nTotal=Ns[Ns.size()-1];\n\t// Get the number of fine grid only nodes.\n\tuword nFineNode=nTotal-nCoarse;\n\tuvec coarseNode=regspace<uvec>(0,nCoarse-1);\n\t// Save data for use by FEM.\n\tcoarse2Fine.push_back(coarseNode);\n\t// Setup indices for the prolongation matrix.\n\tuvec ii=join_vert(coarseNode,join_vert(HB.col(0),HB.col(0)));\n\tuvec jj=join_vert(coarseNode,join_vert(HB.col(1),HB.col(2)));\n\tvec ss=join_vert(ones<vec>(nCoarse),\n\t\t\tjoin_vert(0.5*ones<vec>(nFineNode),0.5*ones<vec>(nFineNode)));\n\t// Quick sparse construction of the prolongation matrix.\n\tsp_mat Procurr(true,join_horiz(ii,jj).t(),ss,nTotal,nCoarse);\n\tPro.push_back(Procurr);\n}\n\nMeshMG::~MeshMG() {\n\n}\n\n", "meta": {"hexsha": "c3d22bc9a876c5d6a74286d8da21c7fd1751c86a", "size": 10902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MeshMG.cpp", "max_stars_repo_name": "epsilonleqzero/Finite-Element-CPP-Nonlinear", "max_stars_repo_head_hexsha": "1b8c061523f18b74413cfaa3df4acb237f7a5860", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-20T19:04:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-20T19:04:17.000Z", "max_issues_repo_path": "src/MeshMG.cpp", "max_issues_repo_name": "tmkwan/Finite-Element-CPP-Nonlinear", "max_issues_repo_head_hexsha": "1b8c061523f18b74413cfaa3df4acb237f7a5860", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MeshMG.cpp", "max_forks_repo_name": "tmkwan/Finite-Element-CPP-Nonlinear", "max_forks_repo_head_hexsha": "1b8c061523f18b74413cfaa3df4acb237f7a5860", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-08-04T04:43:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-04T04:32:46.000Z", "avg_line_length": 30.5378151261, "max_line_length": 82, "alphanum_fraction": 0.6748303064, "num_tokens": 3450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5304929098948483}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n#include \"IO/readPLY.h\"\n#include \"IO/writePLY.h\"\n\n#include \"visualization/plotMesh.h\"\n#include \"visualization/plotTwoMeshes.h\"\n\n#include \"mesh/computeNormals.h\"\n#include \"mesh/computeFacesCentroids.h\"\n#include \"occupancyGrid.h\"\n\nint main() {\n    bool visualization = true;\n    int grid_resolution = 100;          // grid_resolution is used to define the grid resolution in the maximum direction\n    double bounding_box_scale = 1;\n\n    // IO: load files\n    std::cout << \"Progress: load data\\n\";\n    Eigen::MatrixXd V, cubes_V, faces_V;\n    Eigen::MatrixXi F, cubes_F;\n    Eigen::MatrixXd N, faces_N;\n    Eigen::MatrixXi RGB;\n\n    readPLY(\"../data/Lucy100k.ply\", V, F, N, RGB);\n\n    std::cout << \"size of V: \" << V.rows() << \", \" << V.cols() << \"\\n\";\n\n    faces_V = compute_faces_centroids(V,F);\n    faces_N = compute_faces_normals(V,F);\n\n    if (visualization)\n        plot_mesh(V,F);\n\n    OccupancyGrid occupancy_grid(faces_V, faces_N, grid_resolution, bounding_box_scale);\n    \n    Eigen::MatrixXd graph_V;\n    Eigen::MatrixXi graph_E;\n    occupancy_grid.generate_graph(graph_V, graph_E);\n    occupancy_grid.print_to_folder(\"../data/occupancy_grid/\");\n    occupancy_grid.print_to_yaml(\"../data/lucy\");\n\n    occupancy_grid.generate_mesh(cubes_V, cubes_F);\n\n    if (visualization)\n        plot_two_meshes(V,F,cubes_V,cubes_F);\n\n}\n", "meta": {"hexsha": "8b9002e26a5b8dc08c6a95eda46d69dad3d0ae44", "size": 1415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/test_occupancyGrid.cpp", "max_stars_repo_name": "rFalque/voxelization_and_sdf", "max_stars_repo_head_hexsha": "6ae111412f2383244b7caf04affd561f64ce9a4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2020-02-13T04:42:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T23:27:05.000Z", "max_issues_repo_path": "app/test_occupancyGrid.cpp", "max_issues_repo_name": "rFalque/voxelization_and_sdf", "max_issues_repo_head_hexsha": "6ae111412f2383244b7caf04affd561f64ce9a4f", "max_issues_repo_licenses": ["MIT"], "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/test_occupancyGrid.cpp", "max_forks_repo_name": "rFalque/voxelization_and_sdf", "max_forks_repo_head_hexsha": "6ae111412f2383244b7caf04affd561f64ce9a4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-01-15T10:32:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T01:44:27.000Z", "avg_line_length": 27.7450980392, "max_line_length": 121, "alphanum_fraction": 0.6862190813, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5304423491861237}}
{"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/triangulate_hole.h>\n\n#include <CGAL/boost/graph/helpers.h>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <boost/foreach.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\n\ntypedef OpenMesh::PolyMesh_ArrayKernelT< > Mesh;\n\ntypedef boost::graph_traits<Mesh>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<Mesh>::halfedge_descriptor halfedge_descriptor;\ntypedef boost::graph_traits<Mesh>::face_descriptor face_descriptor;\n\nint main(int argc, char* argv[])\n{\n  const char* filename = (argc > 1) ? argv[1] : \"data/mech-holes-shark.off\";\n\n\n  Mesh mesh;\n  OpenMesh::IO::read_mesh(mesh, filename);\n\n  // Incrementally fill the holes\n  unsigned int nb_holes = 0;\n  BOOST_FOREACH(halfedge_descriptor h, halfedges(mesh))\n  {\n    if(CGAL::is_border(h,mesh))\n    {\n      std::vector<face_descriptor>  patch_facets;\n      std::vector<vertex_descriptor> patch_vertices;\n      bool success = CGAL::cpp11::get<0>(\n        CGAL::Polygon_mesh_processing::triangulate_refine_and_fair_hole(\n                  mesh,\n                  h,\n                  std::back_inserter(patch_facets),\n                  std::back_inserter(patch_vertices),\n     CGAL::Polygon_mesh_processing::parameters::vertex_point_map(get(CGAL::vertex_point, mesh)).\n                  geom_traits(Kernel())) );\n\n      CGAL_assertion(CGAL::is_valid_polygon_mesh(mesh));\n\n      std::cout << \"* FILL HOLE NUMBER \" << ++nb_holes << std::endl;\n      std::cout << \"  Number of facets in constructed patch: \" << patch_facets.size() << std::endl;\n      std::cout << \"  Number of vertices in constructed patch: \" << patch_vertices.size() << std::endl;\n      std::cout << \"  Is fairing successful: \" << success << std::endl;\n    }\n  }\n\n  CGAL_assertion(CGAL::is_valid_polygon_mesh(mesh));\n  std::cout << std::endl;\n  std::cout << nb_holes << \" holes have been filled\" << std::endl;\n\n    OpenMesh::IO::write_mesh(mesh, \"filled_OM.off\");\n  return 0;\n}\n", "meta": {"hexsha": "44a7da31e6e6f85252a5f51ebc73dea82ccb8c3a", "size": 2216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Polygon_mesh_processing/hole_filling_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/hole_filling_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/hole_filling_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": 34.625, "max_line_length": 103, "alphanum_fraction": 0.696299639, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6584175139669998, "lm_q1q2_score": 0.5304423430408303}}
{"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_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_HYPOT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing hypot capabilities\n\n    Computes \\f$(x^2 + y^2)^{1/2}\\f$\n\n    @par semantic:\n    For any given value @c x,  @c y of floating type @c T:\n\n    @code\n    T r = hypot(x, y);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    T r = sqrt(sqr(x)+sqr(y));\n    @endcode\n\n    @par Note\n\n    - Provision are made to avoid overflow as possible and to compute\n    @c hypot accurately.\n\n    - If these considerations can be put aside, use the decorator fast_.\n\n    @par Decorators\n\n    std_,  fast_ for floating entries\n\n  **/\n  const boost::dispatch::functor<tag::hypot_> hypot = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/hypot.hpp>\n#include <boost/simd/function/scalar/hypot.hpp>\n#include <boost/simd/function/simd/hypot.hpp>\n\n#endif\n", "meta": {"hexsha": "eb770d87837a09ce93172f713a8bf2ba929e1df4", "size": 1389, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/hypot.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/hypot.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/hypot.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": 23.15, "max_line_length": 100, "alphanum_fraction": 0.5896328294, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5304423383863689}}
{"text": "#include <iostream>\n#include <fstream>\n\nusing namespace std;\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#include <octomap/octomap.h>    // for octomap \n\n#include <eigen3/Eigen/Geometry>\n#include <boost/format.hpp>  // for formating strings\n\nint main(int argc, char **argv) {\n    vector<cv::Mat> colorImgs, depthImgs;    // \uc0c9\uc0c1 \ub9f5 \ubc0f \uae4a\uc774 \ub9f5\n    vector<Eigen::Isometry3d> poses;         // \uce74\uba54\ub77c \ud3ec\uc988\n\n    ifstream fin(\"../dense_RGBD/data/pose.txt\");\n    if (!fin) {\n        cerr << \"cannot find pose file\" << endl;\n        return 1;\n    }\n\n    for (int i = 0; i < 5; i++) {\n        boost::format fmt(\"../dense_RGBD/data/%s/%d.%s\"); // \uc774\ubbf8\uc9c0 \ud30c\uc77c \ud615\uc2dd\n        colorImgs.push_back(cv::imread((fmt % \"color\" % (i + 1) % \"png\").str()));\n        depthImgs.push_back(cv::imread((fmt % \"depth\" % (i + 1) % \"png\").str(), -1)); // -1\uc744 \uc0ac\uc6a9\ud558\uc5ec \uc6d0\ubcf8 \uc774\ubbf8\uc9c0\ub97c \uc77d\uc2b5\ub2c8\ub2e4.\n\n        double data[7] = {0};\n        for (int i = 0; i < 7; i++) {\n            fin >> data[i];\n        }\n        Eigen::Quaterniond q(data[6], data[3], data[4], data[5]);\n        Eigen::Isometry3d T(q);\n        T.pretranslate(Eigen::Vector3d(data[0], data[1], data[2]));\n        poses.push_back(T);\n    }\n\n    // \ud3ec\uc778\ud2b8 \ud074\ub77c\uc6b0\ub4dc \ubc0f \uc2a4\ud2f0\uce58 \uacc4\uc0b0\n    // \uce74\uba54\ub77c \ub0b4\ubd80 \ub9e4\uac1c\ubcc0\uc218\n    double cx = 319.5;\n    double cy = 239.5;\n    double fx = 481.2;\n    double fy = -480.0;\n    double depthScale = 5000.0;\n\n    cout << \"\uc774\ubbf8\uc9c0 \ubcc0\ud658 Octomap ...\" << endl;\n\n    // octomap tree \n    octomap::OcTree tree(0.01); // \ub9e4\uac1c\ubcc0\uc218\ub294 \ud574\uc0c1\ub3c4\uc785\ub2c8\ub2e4.\n\n    for (int i = 0; i < 5; i++) {\n        cout << \"\uc774\ubbf8\uc9c0 \ubcc0\ud658: \" << i + 1 << endl;\n        cv::Mat color = colorImgs[i];\n        cv::Mat depth = depthImgs[i];\n        Eigen::Isometry3d T = poses[i];\n        octomap::Pointcloud cloud;  // the point cloud in octomap \n\n        for (int v = 0; v < color.rows; v++)\n            for (int u = 0; u < color.cols; u++) {\n                unsigned int d = depth.ptr<unsigned short>(v)[u]; // \uae4a\uc774 \uac12\n                if (d == 0) continue; // 0\uc740 \uce21\uc815 \uc5c6\uc74c\uc744 \uc758\ubbf8\ud569\ub2c8\ub2e4.\n                Eigen::Vector3d point;\n                point[2] = double(d) / depthScale;\n                point[0] = (u - cx) * point[2] / fx;\n                point[1] = (v - cy) * point[2] / fy;\n                Eigen::Vector3d pointWorld = T * point;\n                // \uc138\uacc4 \uc88c\ud45c\uacc4\uc758 \uc810\uc744 \uc810 \uad6c\ub984\uc5d0 \ub123\uc2b5\ub2c8\ub2e4.\n                cloud.push_back(pointWorld[0], pointWorld[1], pointWorld[2]);\n            }\n\n        // \ud22c\uc601\uc120\uc744 \uacc4\uc0b0\ud560 \uc218 \uc788\ub3c4\ub85d \uc6d0\uc810\uc774 \uc8fc\uc5b4\uc9c4 \uc625\ud2b8\ub9ac \ub9f5\uc5d0 \ud3ec\uc778\ud2b8 \ud074\ub77c\uc6b0\ub4dc\ub97c \uc800\uc7a5\ud569\ub2c8\ub2e4.\n        tree.insertPointCloud(cloud, octomap::point3d(T(0, 3), T(1, 3), T(2, 3)));\n    }\n\n    // \uc911\uac04 \ub178\ub4dc\uc758 \uc810\uc720 \uc815\ubcf4\ub97c \uc5c5\ub370\uc774\ud2b8\ud558\uace0 \ub514\uc2a4\ud06c\uc5d0 \uae30\ub85d\n    tree.updateInnerOccupancy();\n    cout << \"saving octomap ... \" << endl;\n    tree.writeBinary(\"octomap.bt\");\n    return 0;\n}\n", "meta": {"hexsha": "e761c044db5bedd5140501858b664bcd5fc2ad03", "size": 2642, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch12/dense_RGBD/octomap_mapping.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": "ch12/dense_RGBD/octomap_mapping.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": "ch12/dense_RGBD/octomap_mapping.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": 32.2195121951, "max_line_length": 111, "alphanum_fraction": 0.5234670704, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5304423368955365}}
{"text": "#include \"incidencematrices.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <array>\n#include <memory>\n\nnamespace IncidenceMatrices {\n\n/** @brief Create the mesh consisting of a triangle and quadrilateral\n *         from the exercise sheet.\n * @return Shared pointer to the hybrid2d mesh.\n */\nstd::shared_ptr<lf::mesh::Mesh> createDemoMesh() {\n  // builder for a hybrid mesh in a world of dimension 2\n  std::shared_ptr<lf::mesh::hybrid2d::MeshFactory> mesh_factory_ptr =\n      std::make_shared<lf::mesh::hybrid2d::MeshFactory>(2);\n\n  // Add points\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0, 0});    // (0)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{1, 0});    // (1)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{1, 1});    // (2)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0, 1});    // (3)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0.5, 1});  // (4)\n\n  // Add the triangle\n  // First set the coordinates of its nodes:\n  Eigen::MatrixXd nodesOfTria(2, 3);\n  nodesOfTria << 1, 1, 0.5, 0, 1, 1;\n  mesh_factory_ptr->AddEntity(\n      lf::base::RefEl::kTria(),  // we want a triangle\n      std::array<lf::mesh::Mesh::size_type, 3>{\n          {1, 2, 4}},  // indices of the nodes\n      std::make_unique<lf::geometry::TriaO1>(nodesOfTria));  // node coords\n\n  // Add the quadrilateral\n  Eigen::MatrixXd nodesOfQuad(2, 4);\n  nodesOfQuad << 0, 1, 0.5, 0, 0, 0, 1, 1;\n  mesh_factory_ptr->AddEntity(\n      lf::base::RefEl::kQuad(),\n      std::array<lf::mesh::Mesh::size_type, 4>{{0, 1, 4, 3}},\n      std::make_unique<lf::geometry::QuadO1>(nodesOfQuad));\n\n  std::shared_ptr<lf::mesh::Mesh> demoMesh_p = mesh_factory_ptr->Build();\n\n  return demoMesh_p;\n}\n\n/** @brief Compute the edge-vertex incidence matrix G for a given mesh\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *        such as lf::mesh::hybrid2d::Mesh)\n * @return The edge-vertex incidence matrix as Eigen::SparseMatrix<int>\n */\n/* SAM_LISTING_BEGIN_1 */\nEigen::SparseMatrix<int> computeEdgeVertexIncidenceMatrix(\n    const lf::mesh::Mesh &mesh) {\n  // Store edge-vertex incidence matrix here\n  Eigen::SparseMatrix<int, Eigen::RowMajor> G;\n\n  //====================\n  // Your code goes here\n  //====================\n\n  return G;\n}\n/* SAM_LISTING_END_1 */\n\n/** @brief Compute the cell-edge incidence matrix D for a given mesh\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *        such as lf::mesh::hybrid2d::Mesh)\n * @return The cell-edge incidence matrix as Eigen::SparseMatrix<int>\n */\n/* SAM_LISTING_BEGIN_2 */\nEigen::SparseMatrix<int> computeCellEdgeIncidenceMatrix(\n    const lf::mesh::Mesh &mesh) {\n  // Store cell-edge incidence matrix here\n  Eigen::SparseMatrix<int, Eigen::RowMajor> D;\n\n  //====================\n  // Your code goes here\n  //====================\n\n  return D;\n}\n/* SAM_LISTING_END_2 */\n\n/** @brief For a given mesh test if the product of cell-edge and edge-vertex\n *        incidence matrix is zero: D*G == 0?\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *             such as lf::mesh::hybrid2d::Mesh)\n * @return true, if the product is zero and false otherwise\n */\n/* SAM_LISTING_BEGIN_3 */\nbool testZeroIncidenceMatrixProduct(const lf::mesh::Mesh &mesh) {\n  bool isZero = false;\n\n  //====================\n  // Your code goes here\n  //====================\n  return isZero;\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace IncidenceMatrices\n", "meta": {"hexsha": "b1ce981372a009389f62873debef7ffc402157b6", "size": 3550, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/IncidenceMatrices/templates/incidencematrices.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/IncidenceMatrices/templates/incidencematrices.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/IncidenceMatrices/templates/incidencematrices.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 32.2727272727, "max_line_length": 76, "alphanum_fraction": 0.6515492958, "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.5304423322410756}}
{"text": "/**\n * Copyright (c) 2022 <Daumantas Kavolis>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#pragma once\n\n#include \"config.hpp\"\n\nMSVC_WARNING_DISABLE(4619)\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/chebyshev.hpp>\n#include <boost/math/special_functions/hermite.hpp>\n#include <boost/math/special_functions/laguerre.hpp>\n#include <boost/math/special_functions/legendre.hpp>\n#include <boost/math/special_functions/legendre_stieltjes.hpp>\nMSVC_WARNING_POP()\n\n#include \"quadrature.hpp\"\n\nnamespace poly {\nnamespace detail {\n\ntemplate <typename Integral>\nstruct BasicImpl {\n  using OrderType = Integral;\n  using Storage = Integral;\n\n  constexpr static inline bool is_trivial = true;\n\n  static auto make_storage(OrderType order = 0) noexcept -> Storage { return order; }\n  static auto get_order(Storage const& item) noexcept -> OrderType { return item; }\n  static void set_order(Storage& item, OrderType const& value) noexcept { item = value; }\n};\n\n}  // namespace detail\n\ntemplate <typename Real_, unsigned N = QuadraturePoints>\nstruct LegendreImpl : detail::BasicImpl<std::int16_t> {\n  using Real = Real_;\n  constexpr static inline bool is_orthonormal = true;\n\n  static auto eval(Storage const& item, Real x) -> Real { return boost::math::legendre_p(item, x); }\n  static auto prime(Storage const& item, Real x) -> Real {\n    return boost::math::legendre_p_prime(item, x);\n  }\n  static auto zeros(Storage const& item) -> std::vector<Real> {\n    using std::abs;\n    auto z = boost::math::legendre_p_zeros<Real>(item);\n    detail::reflect_in_place<detail::Reflection::Odd>(\n        z, abs(z[0]) < 2 * std::numeric_limits<Real>::epsilon());\n    return z;\n  }\n  static auto next(Storage const& item, Real x, Real Pl, Real Plm1) -> Real {\n    return boost::math::legendre_next(item, x, Pl, Plm1);\n  }\n\n  template <bool check = false>\n  static auto weights(Storage const& item, bounds_check<check> c = no_bounds_check)\n      -> view<Real const> {\n    return GaussQuadrature<Real, N>::weights(item + 1, c);\n  }\n  template <bool check = false>\n  static auto abscissa(Storage const& item, bounds_check<check> c = no_bounds_check)\n      -> view<Real const> {\n    return GaussQuadrature<Real, N>::abscissa(item + 1, c);\n  }\n  static auto domain() -> std::pair<Real, Real> { return {-1, 1}; }\n};\n\ntemplate <typename Real_>\nstruct LaguerreImpl : detail::BasicImpl<std::int16_t> {\n  using Real = Real_;\n  constexpr static inline bool is_orthonormal = true;\n\n  static auto eval(Storage const& item, Real x) -> Real { return boost::math::laguerre(item, x); }\n  static auto next(Storage const& item, Real x, Real Pl, Real Plm1) -> Real {\n    return boost::math::laguerre_next(item, x, Pl, Plm1);\n  }\n  static auto domain() -> std::pair<Real, Real> { return {0, 1}; }\n};\n\ntemplate <typename Real_>\nstruct HermiteImpl : detail::BasicImpl<std::uint16_t> {\n  using Real = Real_;\n  constexpr static inline bool is_orthonormal = true;\n\n  static auto eval(Storage const& item, Real x) -> Real { return boost::math::hermite(item, x); }\n  static auto next(Storage const& item, Real x, Real Pl, Real Plm1) -> Real {\n    return boost::math::hermite_next(item, x, Pl, Plm1);\n  }\n  static auto domain() -> std::pair<Real, Real> {\n    return {-std::numeric_limits<Real>::infinity(), std::numeric_limits<Real>::infinity()};\n  }\n};\n\ntemplate <typename, unsigned>\nstruct ChebyshevImpl;\nnamespace detail {\ntemplate <typename Real, unsigned N = QuadraturePoints>\nstruct ChebyshevQuadrature {\n  static auto abscissa() -> view<Real const> {\n    static std::vector<Real> v = ChebyshevImpl<Real, N>::zeros({N});\n    return {v.data(), v.size()};\n  }\n  static auto weights() -> view<Real const> {\n    static std::vector<Real> v(std::size_t(N), boost::math::constants::pi<Real>() / N);\n    return {v.data(), v.size()};\n  }\n};\n}  // namespace detail\n\ntemplate <typename Real, unsigned N = QuadraturePoints>\nusing ChebyshevQuadrature = detail::Quadrature<Real, detail::ChebyshevQuadrature, N, false>;\n\ntemplate <typename Real_, unsigned N = QuadraturePoints>\nstruct ChebyshevImpl : detail::BasicImpl<std::int16_t> {\n  using Real = Real_;\n  constexpr static inline bool is_orthonormal = true;\n\n  static auto eval(Storage const& item, Real x) -> Real {\n    return boost::math::chebyshev_t(item, x);\n  }\n  static auto prime(Storage const& item, Real x) -> Real {\n    return boost::math::chebyshev_t_prime(item, x);\n  }\n  static auto next(Storage const& /* unused */, Real x, Real Pl, Real Plm1) -> Real {\n    return boost::math::chebyshev_next(x, Pl, Plm1);\n  }\n  static auto zeros(Storage const& item) -> std::vector<Real> {\n    using std::cos;\n    std::vector<Real> values(item, 0);\n    Real factor{boost::math::constants::pi<Real>() / 2.0 / item};\n    auto half = item / 2;\n    auto start = (item + 1) / 2;\n    for (OrderType i = 0; i < half; ++i) {\n      Real x = cos((2 * (start + i) + 1) * factor);\n      values[start + i] = -x;\n      values[half - i - 1] = x;\n    }\n    return values;\n  }\n\n  template <bool check = false>\n  static auto weights(Storage const& item, bounds_check<check> c = no_bounds_check)\n      -> view<Real const> {\n    return ChebyshevQuadrature<Real, N>::weights(item + 1, c);\n  }\n  template <bool check = false>\n  static auto abscissa(Storage const& item, bounds_check<check> c = no_bounds_check)\n      -> view<Real const> {\n    return ChebyshevQuadrature<Real, N>::abscissa(item + 1, c);\n  }\n  static auto domain() -> std::pair<Real, Real> { return {-1, 1}; }\n};\n\ntemplate <typename Real_>\nstruct LegendreStieltjesImpl {\n  using Real = Real_;\n  using OrderType = std::int16_t;\n\n  constexpr static inline bool is_orthonormal = true;\n\n  class Storage {\n   public:\n    explicit Storage(OrderType m) : polynomial{m}, order{m} {};\n\n   private:\n    boost::math::legendre_stieltjes<Real> polynomial;\n    OrderType order;\n\n    template <class>\n    friend struct LegendreStieltjesImpl;\n  };\n\n  static auto make_storage(OrderType order = 0) noexcept -> Storage { return Storage{order}; }\n  static auto get_order(Storage const& item) noexcept -> OrderType { return item.order; }\n  static void set_order(Storage& item, OrderType const& value) noexcept { item = Storage{value}; }\n\n  static auto eval(Storage const& item, Real x) -> Real { return item.polynomial(x); }\n  static auto prime(Storage const& item, Real x) -> Real { return item.polynomial.prime(x); }\n  static auto zeros(Storage const& item) -> std::vector<Real> {\n    auto vector = item.polynomial.zeros();\n    detail::reflect_in_place<detail::Reflection::Odd>(vector, vector[0] == 0);\n    return vector;\n  }\n  static auto domain() -> std::pair<Real, Real> { return {-1, 1}; }\n};\n\ntemplate <typename Real_, unsigned N = QuadraturePoints>\nstruct GaussKronrodImpl : detail::BasicImpl<std::int16_t> {\n  using Real = Real_;\n\n  constexpr static inline bool is_orthonormal = true;\n\n  template <bool check = false>\n  static auto weights(Storage const& item, bounds_check<check> c = no_bounds_check)\n      -> view<Real const> {\n    return GaussKronrodQuadrature<Real, N>::weights(item, c);\n  }\n  template <bool check = false>\n  static auto abscissa(Storage const& item, bounds_check<check> c = no_bounds_check)\n      -> view<Real const> {\n    return GaussKronrodQuadrature<Real, N>::abscissa(item, c);\n  }\n  static auto domain() -> std::pair<Real, Real> { return {-1, 1}; }\n};\n\n}  // namespace poly\n", "meta": {"hexsha": "86c44bd72de8914c743ad3106ff5cc9d4a4d7a83", "size": 8390, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/polynomials/include/boost_polynomials.hpp", "max_stars_repo_name": "dkavolis/polynomials", "max_stars_repo_head_hexsha": "10abe0ca8bdd3ae7dafc1ecd04142b42e3213af0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomials/include/boost_polynomials.hpp", "max_issues_repo_name": "dkavolis/polynomials", "max_issues_repo_head_hexsha": "10abe0ca8bdd3ae7dafc1ecd04142b42e3213af0", "max_issues_repo_licenses": ["MIT"], "max_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/include/boost_polynomials.hpp", "max_forks_repo_name": "dkavolis/polynomials", "max_forks_repo_head_hexsha": "10abe0ca8bdd3ae7dafc1ecd04142b42e3213af0", "max_forks_repo_licenses": ["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.9603524229, "max_line_length": 100, "alphanum_fraction": 0.6959475566, "num_tokens": 2242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5304423322410756}}
{"text": "#include \"FiniteElement.h\"\n\n#include <Eigen/Core>\n#include <iostream>\n\nusing namespace Eigen;\n\nFiniteElement::FiniteElement(\n        FEMObject* femObj,\n        Cell cell,\n        ElasticMaterial material)\n    : mFemObj(femObj)\n    , mMaterial(material)\n{\n    mDensity = 100.0;\n    mCell = cell;\n    mStiffnessMatrixDirty = false;\n    mQ.setIdentity();\n}\n\nvoid FiniteElement::setMaterial(ElasticMaterial material)\n{\n    mMaterial = material;\n    mStiffnessMatrixDirty = true;\n}\n\nvoid FiniteElement::initialize()\n{\n    updateDnx();\n\n    // Initialize mQ with the correct rotation calculated with the slow singular\n    // value decomposition. Use that result with the iterative approach later.\n    updateRotation();\n    mQ = Eigen::Quaterniond(mR);\n\n    updateCauchyStressStrain();\n    updateLinearStiffnessMatrix();\n}\n\nvoid FiniteElement::updateRotation()\n{\n    updateF();\n    JacobiSVD<Matrix3d> svd(mF, ComputeFullU | ComputeFullV);\n    double det = (svd.matrixU() * svd.matrixV().transpose()).determinant();\n    Matrix3d C = Matrix3d::Identity();\n    C(2,2) = det;\n    mR = svd.matrixU() * C * svd.matrixV().transpose();\n//    if (det < 0)\n//        std::cout << \"inversion detected! det = \" << det << \"\\n\";\n\n}\n\nvoid FiniteElement::updateRotationFast(size_t maxIterations, double tolerance)\n{\n    updateF();\n\n    for (size_t i = 0; i < maxIterations; ++i)\n    {\n        Eigen::Matrix3d R = mQ.toRotationMatrix();\n        double s = std::abs(R.col(0).dot(mF.col(0)) +\n                            R.col(1).dot(mF.col(1)) +\n                            R.col(2).dot(mF.col(2)));\n\n        if (s < 1e-12)\n            break;\n\n        double sInv = 1.0 / s + tolerance;\n        Eigen::Vector3d v = R.col(0).cross(mF.col(0)) +\n                            R.col(1).cross(mF.col(1)) +\n                            R.col(2).cross(mF.col(2));\n\n        Eigen::Vector3d omega = sInv * v;\n        double w = omega.norm();\n\n        if (w < tolerance)\n            break;\n\n        Eigen::Quaterniond omegaQ =\n                Eigen::Quaterniond(Eigen::AngleAxisd(w, 1.0 / w * omega));\n\n        mQ = omegaQ * mQ;\n    }\n\n    mR = mQ.toRotationMatrix();\n}\n\nvoid FiniteElement::update(bool corotated)\n{\n    if (corotated)\n    {\n        updateCorotatedStiffnessMatrix();\n        updateCorotatedForces();\n    }\n    else\n    {\n        updateLinearForces();\n    }\n}\n\nvoid FiniteElement::updateStiffnessMatrix(bool corotated)\n{\n    if (corotated)\n        updateCorotatedStiffnessMatrix();\n    else if (mStiffnessMatrixDirty)\n        updateLinearStiffnessMatrix();\n}\n\nvoid FiniteElement::updateLinearStiffnessMatrix()\n{\n    for (size_t a = 0; a < 4; ++a)\n    {\n        for (size_t b = 0; b < 4; ++b)\n        {\n            double second_part = mMaterial.getLameMu() * mDnx[a].dot(mDnx[b]);\n            Matrix3d& K = mK[a][b];\n            for (Index i = 0; i < 3; ++i)\n            {\n                for (Index k = 0; k < 3; ++k)\n                {\n                    //K(i,k) = ...\n                    double value = 0.0;\n                    if (i == k)\n                        value = second_part;\n                    value += mMaterial.getLameLambda() * mDnx[a](i) * mDnx[b](k)\n                            + mMaterial.getLameMu() * mDnx[a](k) * mDnx[b](i);\n                    K(i,k) = value * mVolume;\n                }\n            }\n        }\n    }\n\n    updatePlasticityMatrix();\n}\n\nvoid FiniteElement::updateCorotatedStiffnessMatrix()\n{\n    for (size_t a = 0; a < 4; ++a)\n    {\n        for (size_t b = 0; b < 4; ++b)\n        {\n            Matrix3d& K = mK[a][b];\n            Matrix3d& K_corot = mKCorot[a][b];\n            K_corot = mR * K * mR.transpose();\n        }\n    }\n}\n\nvoid FiniteElement::updatePlasticityMatrix()\n{\n    Eigen::Matrix<double, 6, 6> D;\n    double mu = mMaterial.getLameMu();\n    double lambda = mMaterial.getLameLambda();\n\n    double temp = lambda + 2 * mu;\n\n    D << temp, lambda, lambda, 0, 0, 0,\n            lambda, temp, lambda, 0, 0, 0,\n            lambda, lambda, temp, 0, 0, 0,\n            0, 0, 0, mu, 0, 0,\n            0, 0, 0, 0, mu, 0,\n            0, 0, 0, 0, 0, mu;\n\n    mP = mVolume * mB.transpose() * D;\n}\n\nvoid FiniteElement::updateForces(bool corotated)\n{\n    if (corotated)\n        updateCorotatedForces();\n    else\n        updateLinearForces();\n}\n\nvoid FiniteElement::updateCorotatedForces()\n{\n    // TODO: Optimizations\n    // - Apply rotation only once\n    // - reformulate equation to precalculate parts of it\n    for (size_t a = 0; a < 4; ++a)\n    {\n        mForces[a].setZero();\n        for (size_t b = 0; b < 4; ++b)\n        {\n            mForces[a] += mR * mK[a][b] *\n                    (mR.transpose() * y(b) - x(b));\n        }\n    }\n\n    updatePlasticForces(0.01);\n}\n\nvoid FiniteElement::updateLinearForces()\n{\n    for (size_t a = 0; a < 4; ++a)\n    {\n        mForces[a] = Vector::Zero();\n        for (size_t b = 0; b < 4; ++b)\n        {\n            mForces[a] += mK[a][b] * u(b);\n\n            // directly globally updates them this way\n            // but this is not wanted here\n            //f(a) += mK[a][b] * u(b);\n        }\n    }\n}\n\nvoid FiniteElement::updatePlasticForces(double stepSize)\n{\n    if (mMaterial.getPlasticMaxStrain() > 1e-12)\n    {\n        // Calculate total strain.\n        Eigen::Matrix<double, 6, 1> strainTotal =\n                Eigen::Matrix<double, 6, 1>::Zero();\n        Eigen::Matrix3d RInv = mR.inverse();\n        for (Eigen::Index a = 0; a < 4; ++a)\n        {\n            strainTotal += mB.block(0, a * 3, 6, 3) * (RInv * y(a) - x(a));\n        }\n\n        // Update plastic strain.\n        Eigen::Matrix<double, 6, 1> strainElastic =\n                strainTotal - mStrainPlastic;\n        if (strainElastic.norm() > mMaterial.getPlasticYield())\n            mStrainPlastic += stepSize * mMaterial.getPlasticCreep() * strainElastic;\n        double strainPlasticNorm = mStrainPlastic.norm();\n        if (strainPlasticNorm > mMaterial.getPlasticMaxStrain())\n            mStrainPlastic *= mMaterial.getPlasticMaxStrain() / strainPlasticNorm;\n\n        // Calculate plastic forces.\n        for (Eigen::Index a = 0; a < 4; ++a)\n        {\n            mForces[a] -= mR * mP.block(a * 3, 0, 3, 6) * mStrainPlastic;\n        }\n    }\n}\n\nvoid FiniteElement::updateF()\n{\n//    mF = Matrix3d::Identity();\n//    for (size_t i = 0; i < 4; ++i) {\n//        mF += u(i) * mDnx[i].transpose();\n//    }\n    mF = Matrix3d::Zero();\n    for (size_t i = 0; i < 4; ++i) {\n        mF += y(i) * mDnx[i].transpose();\n    }\n\n    mB << mDnx[0](0), 0, 0, mDnx[1](0), 0, 0, mDnx[2](0), 0, 0, mDnx[3](0), 0, 0,\n            0, mDnx[0](1), 0, 0, mDnx[1](1), 0, 0, mDnx[2](1), 0, 0, mDnx[3](1), 0,\n            0, 0, mDnx[0](2), 0, 0, mDnx[1](2), 0, 0, mDnx[2](2), 0, 0, mDnx[3](2),\n            mDnx[0](1), mDnx[0](0), 0, mDnx[1](1), mDnx[1](0), 0, mDnx[2](1), mDnx[2](0), 0, mDnx[3](1), mDnx[3](0), 0,\n            mDnx[0](2), 0, mDnx[0](0), mDnx[1](2), 0, mDnx[1](0), mDnx[2](2), 0, mDnx[2](0), mDnx[3](2), 0, mDnx[3](0),\n            0, mDnx[0](2), mDnx[0](1), 0, mDnx[1](2), mDnx[1](1), 0, mDnx[2](2), mDnx[2](1), 0, mDnx[3](2), mDnx[3](1);\n}\n\nvoid FiniteElement::updateCauchyStressStrain()\n{\n    // Cauchy strain\n    mCauchyStrain = 0.5 * (mF + mF.transpose()) - Matrix3d::Identity();\n    double trace = mCauchyStrain.trace();\n    for (Index i = 0; i < 3; ++i)\n         for (Index j = 0; j < 3; ++j)\n            mCauchyStress(i, j) = (i == j) * mMaterial.getLameLambda() * trace\n                    + 2 * mMaterial.getLameMu() * mCauchyStrain(i, j);\n}\n\nvoid FiniteElement::updateDnx()\n{\n    // As described in\n    // http://www.iue.tuwien.ac.at/phd/nentchev/node30.html and\n    // http://www.iue.tuwien.ac.at/phd/nentchev/node31.html\n\n    Vector r1 = mFemObj->x(mCell[1]) - mFemObj->x(mCell[0]);\n    Vector r2 = mFemObj->x(mCell[2]) - mFemObj->x(mCell[0]);\n    Vector r3 = mFemObj->x(mCell[3]) - mFemObj->x(mCell[0]);\n\n    Vector r4 = mFemObj->x(mCell[2]) - mFemObj->x(mCell[1]);\n    Vector r5 = mFemObj->x(mCell[1]) - mFemObj->x(mCell[3]);\n\n    mVolume = r1.cross(r2).dot(r3);\n\n    // Sometimes tetrahedrons can be so degenerated that their volume is zero.\n    if (mVolume < 1e-10)\n        mVolume = 1e-5;\n\n    mDnx[0] = r4.cross(r5) / mVolume;\n    mDnx[1] = r2.cross(r3) / mVolume;\n    mDnx[2] = r3.cross(r1) / mVolume;\n    mDnx[3] = r1.cross(r2) / mVolume;\n\n    mVolume /= 6.0;\n}\n\nvoid FiniteElement::updateDny()\n{\n    updateF(); // TODO: look if necessary\n    Matrix3d F_inv = mF.inverse();\n    for (size_t i = 0; i < 4; ++i) {\n        mDny[i] = Vector(0,0,0);\n        for (int a = 0; a < 3; ++a) {\n            for (int k = 0; k < 3; ++k) {\n                mDny[i](a) += mDnx[i](k) * F_inv(k,a);\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "0bfc569b780ea4702f8f43050deabe8a3e0e241b", "size": 8645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulation/fem/FiniteElement.cpp", "max_stars_repo_name": "danielroth1/CAE", "max_stars_repo_head_hexsha": "7eaa096e45fd32f55bd6de94c30dcf706c6f2093", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-04-20T17:48:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T01:39:33.000Z", "max_issues_repo_path": "src/simulation/fem/FiniteElement.cpp", "max_issues_repo_name": "danielroth1/CAE", "max_issues_repo_head_hexsha": "7eaa096e45fd32f55bd6de94c30dcf706c6f2093", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulation/fem/FiniteElement.cpp", "max_forks_repo_name": "danielroth1/CAE", "max_forks_repo_head_hexsha": "7eaa096e45fd32f55bd6de94c30dcf706c6f2093", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-04T20:21:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T15:01:04.000Z", "avg_line_length": 28.0681818182, "max_line_length": 119, "alphanum_fraction": 0.5230769231, "num_tokens": 2948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5304019587167366}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"common/equality.hpp\"\n#include \"algorithms/data_structures/array/median_of_two_sorted_arrays.hpp\"\n\nBOOST_AUTO_TEST_SUITE(TestMedianOfTwoSortedArrays)\n\nBOOST_AUTO_TEST_CASE(empty_arrays)\n{\n    std::vector<int> first, second;\n    MedianOfTwoSortedArrays::Solution solution;\n    double result = solution.findMedianSortedArrays(first, second);\n\n    BOOST_CHECK(equal(result, 0.0));\n}\n\nBOOST_AUTO_TEST_CASE(empty_and_size_1_arrays)\n{\n    std::vector<int> first;\n    std::vector<int> second = {1};\n\n    MedianOfTwoSortedArrays::Solution solution;\n    double result = solution.findMedianSortedArrays(first, second);\n\n    BOOST_CHECK(equal(result, 1.0));\n}\n\nBOOST_AUTO_TEST_CASE(empty_and_small_arrays)\n{\n    std::vector<int> first;\n    std::vector<int> second = {2, 3};\n\n    MedianOfTwoSortedArrays::Solution solution;\n    double result = solution.findMedianSortedArrays(first, second);\n\n    BOOST_CHECK(equal(result, 2.5));\n}\n\nBOOST_AUTO_TEST_CASE(two_arrays)\n{\n    std::vector<int> first = {1, 2};\n    std::vector<int> second = {3, 4};\n\n    MedianOfTwoSortedArrays::Solution solution;\n    double result = solution.findMedianSortedArrays(first, second);\n\n    BOOST_CHECK(equal(result, 2.5));\n}\n\nBOOST_AUTO_TEST_CASE(two_small_arrays)\n{\n    std::vector<int> first = {1, 1};\n    std::vector<int> second = {1, 2};\n\n    MedianOfTwoSortedArrays::Solution solution;\n    double result = solution.findMedianSortedArrays(first, second);\n\n    BOOST_CHECK(equal(result, 1.0));\n}\n\nBOOST_AUTO_TEST_CASE(two_arrays_diff_size)\n{\n    std::vector<int> first = {1, 2, 3, 6};\n    std::vector<int> second = {9, 14, 17, 25, 26};\n\n    MedianOfTwoSortedArrays::Solution solution;\n    double result = solution.findMedianSortedArrays(first, second);\n\n    BOOST_CHECK(equal(result, 9.0));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "8560e92690b8b590034a36cf9750a24e10684dcb", "size": 1834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/data_structures/array/test_median_of_two_sorted_arrays.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/data_structures/array/test_median_of_two_sorted_arrays.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/data_structures/array/test_median_of_two_sorted_arrays.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": 25.1232876712, "max_line_length": 75, "alphanum_fraction": 0.7268266085, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.530350476800084}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/include/functions/sinpi.hpp>\n\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <complex>\n#include <nt2/sdk/complex/complex.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/basic.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/i.hpp>\n\nNT2_TEST_CASE_TPL ( sinpi,  NT2_REAL_TYPES)\n{\n\n  using nt2::sinpi;\n  using nt2::tag::sinpi_;\n  typedef std::complex<T> cT;\n  typedef typename nt2::meta::call<sinpi_(cT)>::type r_t;\n  typedef typename nt2:: meta::as_complex<T>::type wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(nt2::sinpi(cT(nt2::Inf<T>())), cT(nt2::Nan<T>()), 10);\n  NT2_TEST_ULP_EQUAL(nt2::sinpi(cT(nt2::Minf<T>())), cT(nt2::Nan<T>()), 10);\n  NT2_TEST_ULP_EQUAL(nt2::sinpi(cT(1, 1)),std::sin(nt2::Pi<T>()*cT(1.0, 1.0)), 10);\n  NT2_TEST_ULP_EQUAL(nt2::sinpi(cT(1, 0.5)),std::sin(nt2::Pi<T>()*cT(1.0, 0.5)), 10);\n  NT2_TEST_ULP_EQUAL(nt2::sinpi(cT(0.5, 1)),std::sin(nt2::Pi<T>()*cT(0.5, 1.0)), 10);\n  NT2_TEST_ULP_EQUAL(nt2::sinpi(cT(0.5, 0.5)),std::sin(nt2::Pi<T>()*cT(0.5, 0.5)), 10);\n  NT2_TEST_ULP_EQUAL(nt2::sinpi(cT(0, 1)),std::sin(nt2::Pi<T>()*cT(0.0, 1.0)), 10);\n  NT2_TEST_ULP_EQUAL(nt2::sinpi(cT(0, 0.5)),std::sin(nt2::Pi<T>()*cT(0.0, 0.5)), 10);\n  NT2_TEST_ULP_EQUAL(nt2::sinpi(cT(0.5, 0)),std::sin(nt2::Pi<T>()*cT(0.5, 0.0)), 10);\n\n  const int N = 20;\n  cT inputs[N] =\n    { cT(nt2::Zero<T>(),nt2::Zero<T>()),cT(nt2::Inf<T>(),nt2::Zero<T>()),cT(nt2::Minf<T>(),nt2::Zero<T>()),cT(nt2::Nan<T>(),nt2::Zero<T>()),\n      cT(nt2::Zero<T>(),nt2::Inf<T>()), cT(nt2::Inf<T>(),nt2::Inf<T>()), cT(nt2::Minf<T>(),nt2::Inf<T>()), cT(nt2::Nan<T>(),nt2::Inf<T>()),\n      cT(nt2::Zero<T>(),nt2::Minf<T>()),cT(nt2::Inf<T>(),nt2::Minf<T>()),cT(nt2::Minf<T>(),nt2::Minf<T>()),cT(nt2::Nan<T>(),nt2::Minf<T>()),\n      cT(nt2::Zero<T>(),nt2::Nan<T>()), cT(nt2::Inf<T>(),nt2::Nan<T>()), cT(nt2::Minf<T>(),nt2::Nan<T>()), cT(nt2::Nan<T>(),nt2::Nan<T>()),\n      cT(nt2::Zero<T>(),nt2::One<T>()), cT(nt2::Inf<T>(),nt2::One<T>()), cT(nt2::Minf<T>(),nt2::One<T>()), cT(nt2::Nan<T>(),nt2::One<T>()),\n    };\n\n  for(int i=0; i < N; i++)\n   {\n     NT2_TEST_ULP_EQUAL(nt2::sinpi(-inputs[i]), -nt2::sinpi(inputs[i]), 4);\n     NT2_TEST_ULP_EQUAL(nt2::sinpi(inputs[i]), nt2::sin(nt2::multiplies(nt2::Pi<T>(), inputs[i])), 4);\n   }\n} // end of test for floating_\n\n", "meta": {"hexsha": "98bdc0574b608d39a820a4d698fcbe6eadc6a946", "size": 3355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/trigonometric/unit/scalar/sinpi.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/type/complex/trigonometric/unit/scalar/sinpi.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/type/complex/trigonometric/unit/scalar/sinpi.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 47.9285714286, "max_line_length": 140, "alphanum_fraction": 0.59195231, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.5303504729263497}}
{"text": "// Boost.Geometry\n// Unit Test\n\n// Copyright (c) 2017 Adam Wulkiewicz, Lodz, Poland.\n\n// Copyright (c) 2016, 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#ifndef BOOST_GEOMETRY_TEST_STRATEGIES_SEGMENT_INTERSECTION_GEO_HPP\n#define BOOST_GEOMETRY_TEST_STRATEGIES_SEGMENT_INTERSECTION_GEO_HPP\n\n\n#include \"segment_intersection_sph.hpp\"\n\n#include <boost/geometry/strategies/geographic/intersection.hpp>\n#include <boost/geometry/strategies/geographic/intersection_elliptic.hpp>\n\n\ntemplate <typename S, typename P>\nvoid test_default_strategy(std::string const& s1_wkt, std::string const& s2_wkt,\n                           char m, std::size_t expected_count,\n                           std::string const& ip0_wkt = \"\", std::string const& ip1_wkt = \"\",\n                           int opposite_id = -1)\n{\n    typename bg::strategy::intersection::services::default_strategy\n        <\n            bg::geographic_tag\n        >::type strategy;\n\n    test_strategy<S, S, P>(s1_wkt, s2_wkt, strategy, m, expected_count, ip0_wkt, ip1_wkt, opposite_id);\n}\n\ntemplate <typename S, typename P>\nvoid test_great_elliptic(std::string const& s1_wkt, std::string const& s2_wkt,\n                         char m, std::size_t expected_count,\n                         std::string const& ip0_wkt = \"\", std::string const& ip1_wkt = \"\",\n                         int opposite_id = -1)\n{\n    bg::strategy::intersection::great_elliptic_segments<> strategy;\n\n    test_strategy<S, S, P>(s1_wkt, s2_wkt, strategy, m, expected_count, ip0_wkt, ip1_wkt, opposite_id);\n}\n/*\ntemplate <typename S, typename P>\nvoid test_experimental_elliptic(std::string const& s1_wkt, std::string const& s2_wkt,\n                                char m, std::size_t expected_count,\n                                std::string const& ip0_wkt = \"\", std::string const& ip1_wkt = \"\",\n                                int opposite_id = -1)\n{\n    bg::strategy::intersection::experimental_elliptic_segments<> strategy;\n\n    test_strategy<S, S, P>(s1_wkt, s2_wkt, strategy, m, expected_count, ip0_wkt, ip1_wkt, opposite_id);\n}\n*/\ntemplate <typename S, typename P>\nvoid test_geodesic_vincenty(std::string const& s1_wkt, std::string const& s2_wkt,\n                            char m, std::size_t expected_count,\n                            std::string const& ip0_wkt = \"\", std::string const& ip1_wkt = \"\",\n                            int opposite_id = -1)\n{\n    bg::strategy::intersection::geographic_segments<bg::strategy::vincenty, 4> strategy;\n\n    test_strategy<S, S, P>(s1_wkt, s2_wkt, strategy, m, expected_count, ip0_wkt, ip1_wkt, opposite_id);\n}\n\ntemplate <typename S, typename P>\nvoid test_geodesic_thomas(std::string const& s1_wkt, std::string const& s2_wkt,\n                          char m, std::size_t expected_count,\n                          std::string const& ip0_wkt = \"\", std::string const& ip1_wkt = \"\",\n                          int opposite_id = -1)\n{\n    bg::strategy::intersection::geographic_segments<bg::strategy::thomas, 2> strategy;\n\n    test_strategy<S, S, P>(s1_wkt, s2_wkt, strategy, m, expected_count, ip0_wkt, ip1_wkt, opposite_id);\n}\n\ntemplate <typename S, typename P>\nvoid test_geodesic_andoyer(std::string const& s1_wkt, std::string const& s2_wkt,\n                           char m, std::size_t expected_count,\n                           std::string const& ip0_wkt = \"\", std::string const& ip1_wkt = \"\",\n                           int opposite_id = -1)\n{\n    bg::strategy::intersection::geographic_segments<bg::strategy::andoyer, 1> strategy;\n\n    test_strategy<S, S, P>(s1_wkt, s2_wkt, strategy, m, expected_count, ip0_wkt, ip1_wkt, opposite_id);\n}\n\n\nstruct strategy_base\n{\n    strategy_base(char m_)\n        : m(m_), expected_count(0), opposite(-1)\n    {}\n    strategy_base(char m_, std::string const& wkt1_)\n        : m(m_), expected_count(1), wkt1(wkt1_), opposite(-1)\n    {}\n    strategy_base(char m_, std::string const& wkt1_, std::string const& wkt2_, bool opposite_)\n        : m(m_), expected_count(1), wkt1(wkt1_), wkt2(wkt2_), opposite(opposite_ ? 1 : 0)\n    {}\n\n    char m;\n    std::size_t expected_count;\n    std::string wkt1, wkt2;\n    int opposite;\n};\nstruct strategy_default : strategy_base\n{\n    strategy_default(char m)\n        : strategy_base(m)\n    {}\n    strategy_default(char m, std::string const& wkt1)\n        : strategy_base(m, wkt1)\n    {}\n    strategy_default(char m, std::string const& wkt1, std::string const& wkt2, bool opposite)\n        : strategy_base(m, wkt1, wkt2, opposite)\n    {}\n};\nstruct geodesic_vincenty : strategy_base\n{\n    geodesic_vincenty(char m)\n        : strategy_base(m)\n    {}\n    geodesic_vincenty(char m, std::string const& wkt1)\n        : strategy_base(m, wkt1)\n    {}\n    geodesic_vincenty(char m, std::string const& wkt1, std::string const& wkt2, bool opposite)\n        : strategy_base(m, wkt1, wkt2, opposite)\n    {}\n};\nstruct geodesic_thomas : strategy_base\n{\n    geodesic_thomas(char m)\n        : strategy_base(m)\n    {}\n    geodesic_thomas(char m, std::string const& wkt1)\n        : strategy_base(m, wkt1)\n    {}\n    geodesic_thomas(char m, std::string const& wkt1, std::string const& wkt2, bool opposite)\n        : strategy_base(m, wkt1, wkt2, opposite)\n    {}\n};\nstruct geodesic_andoyer : strategy_base\n{\n    geodesic_andoyer(char m)\n        : strategy_base(m)\n    {}\n    geodesic_andoyer(char m, std::string const& wkt1)\n        : strategy_base(m, wkt1)\n    {}\n    geodesic_andoyer(char m, std::string const& wkt1, std::string const& wkt2, bool opposite)\n        : strategy_base(m, wkt1, wkt2, opposite)\n    {}\n};\nstruct great_elliptic : strategy_base\n{\n    great_elliptic(char m)\n        : strategy_base(m)\n    {}\n    great_elliptic(char m, std::string const& wkt1)\n        : strategy_base(m, wkt1)\n    {}\n    great_elliptic(char m, std::string const& wkt1, std::string const& wkt2, bool opposite)\n        : strategy_base(m, wkt1, wkt2, opposite)\n    {}\n};\n\n\ntemplate <typename S, typename P>\nvoid test_strategy(std::string const& s1_wkt, std::string const& s2_wkt,\n                   strategy_default const& s)\n{\n    test_default_strategy<S, P>(s1_wkt, s2_wkt, s.m, s.expected_count, s.wkt1, s.wkt2);\n}\n\ntemplate <typename S, typename P>\nvoid test_strategy(std::string const& s1_wkt, std::string const& s2_wkt,\n                   great_elliptic const& s)\n{\n    test_great_elliptic<S, P>(s1_wkt, s2_wkt, s.m, s.expected_count, s.wkt1, s.wkt2);\n}\n\ntemplate <typename S, typename P>\nvoid test_strategy(std::string const& s1_wkt, std::string const& s2_wkt,\n                   geodesic_vincenty const& s)\n{\n    test_geodesic_vincenty<S, P>(s1_wkt, s2_wkt, s.m, s.expected_count, s.wkt1, s.wkt2);\n}\n\ntemplate <typename S, typename P>\nvoid test_strategy(std::string const& s1_wkt, std::string const& s2_wkt,\n                   geodesic_thomas const& s)\n{\n    test_geodesic_thomas<S, P>(s1_wkt, s2_wkt, s.m, s.expected_count, s.wkt1, s.wkt2);\n}\n\ntemplate <typename S, typename P>\nvoid test_strategy(std::string const& s1_wkt, std::string const& s2_wkt,\n                   geodesic_andoyer const& s)\n{\n    test_geodesic_andoyer<S, P>(s1_wkt, s2_wkt, s.m, s.expected_count, s.wkt1, s.wkt2);\n}\n\n\ntemplate <typename S, typename P, typename SR1>\nvoid test_strategies(std::string const& s1_wkt, std::string const& s2_wkt,\n                     SR1 const& sr1)\n{\n    test_strategy<S, P>(s1_wkt, s2_wkt, sr1);\n}\ntemplate <typename S, typename P, typename SR1, typename SR2>\nvoid test_strategies(std::string const& s1_wkt, std::string const& s2_wkt,\n                     SR1 const& sr1, SR2 const& sr2)\n{\n    test_strategy<S, P>(s1_wkt, s2_wkt, sr1);\n    test_strategy<S, P>(s1_wkt, s2_wkt, sr2);\n}\ntemplate <typename S, typename P, typename SR1, typename SR2, typename SR3>\nvoid test_strategies(std::string const& s1_wkt, std::string const& s2_wkt,\n                     SR1 const& sr1, SR2 const& sr2, SR3 const& sr3)\n{\n    test_strategy<S, P>(s1_wkt, s2_wkt, sr1);\n    test_strategy<S, P>(s1_wkt, s2_wkt, sr2);\n    test_strategy<S, P>(s1_wkt, s2_wkt, sr3);\n}\ntemplate <typename S, typename P, typename SR1, typename SR2, typename SR3, typename SR4>\nvoid test_strategies(std::string const& s1_wkt, std::string const& s2_wkt,\n                     SR1 const& sr1, SR2 const& sr2, SR3 const& sr3, SR4 const& sr4)\n{\n    test_strategy<S, P>(s1_wkt, s2_wkt, sr1);\n    test_strategy<S, P>(s1_wkt, s2_wkt, sr2);\n    test_strategy<S, P>(s1_wkt, s2_wkt, sr3);\n    test_strategy<S, P>(s1_wkt, s2_wkt, sr4);\n}\n\n\ntemplate <typename S, typename P>\nvoid test_all_strategies(std::string const& s1_wkt, std::string const& s2_wkt,\n                         char m, std::string const& ip0_wkt = \"\")\n{\n    std::size_t expected_count = ip0_wkt.empty() ? 0 : 1;\n\n    test_default_strategy<S, P>(s1_wkt, s2_wkt, m, expected_count, ip0_wkt);\n    test_great_elliptic<S, P>(s1_wkt, s2_wkt, m, expected_count, ip0_wkt);\n    //test_experimental_elliptic<S, P>(s1_wkt, s2_wkt, m, expected_count, ip0_wkt);\n    test_geodesic_vincenty<S, P>(s1_wkt, s2_wkt, m, expected_count, ip0_wkt);\n    test_geodesic_thomas<S, P>(s1_wkt, s2_wkt, m, expected_count, ip0_wkt);\n    test_geodesic_andoyer<S, P>(s1_wkt, s2_wkt, m, expected_count, ip0_wkt);\n}\n\ntemplate <typename S, typename P>\nvoid test_all_strategies(std::string const& s1_wkt, std::string const& s2_wkt,\n                         char m,\n                         std::string const& ip0_wkt, std::string const& ip1_wkt,\n                         bool opposite)\n{\n    int opposite_id = opposite ? 1 : 0;\n\n    test_default_strategy<S, P>(s1_wkt, s2_wkt, m, 2, ip0_wkt, ip1_wkt, opposite_id);\n    test_great_elliptic<S, P>(s1_wkt, s2_wkt, m, 2, ip0_wkt, ip1_wkt, opposite_id);\n    //test_experimental_elliptic<S, P>(s1_wkt, s2_wkt, m, 2, ip0_wkt, ip1_wkt, opposite_id);\n    test_geodesic_vincenty<S, P>(s1_wkt, s2_wkt, m, 2, ip0_wkt, ip1_wkt, opposite_id);\n    test_geodesic_thomas<S, P>(s1_wkt, s2_wkt, m, 2, ip0_wkt, ip1_wkt, opposite_id);\n    test_geodesic_andoyer<S, P>(s1_wkt, s2_wkt, m, 2, ip0_wkt, ip1_wkt, opposite_id);\n}\n\n#endif // BOOST_GEOMETRY_TEST_STRATEGIES_SEGMENT_INTERSECTION_GEO_HPP\n", "meta": {"hexsha": "86eb372fa47f673dd86537fb64d9ff8176da7cac", "size": 10265, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/geometry/test/strategies/segment_intersection_geo.hpp", "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/geometry/test/strategies/segment_intersection_geo.hpp", "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/geometry/test/strategies/segment_intersection_geo.hpp", "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": 37.8782287823, "max_line_length": 103, "alphanum_fraction": 0.6557233317, "num_tokens": 3149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.5303504720983704}}
{"text": "#include \"GlobalMap.h\"\n\n#include <Eigen/LU>\n\nGlobalMap::GlobalMap(double areaSize, int scanStride, int maxIter, double relErrChangeThresh)\n\t: tree(areaSize), icp(maxIter, relErrChangeThresh,\n\t\t\t\t\t\t  std::bind(&GlobalMap::getClosest, this, std::placeholders::_1)),\n\t  scanStride(scanStride) {\n}\n\npoints_t GlobalMap::getPoints() const {\n\treturn tree.getAllPoints();\n}\n\nsize_t GlobalMap::size() const {\n\treturn tree.getSize();\n}\n\nvoid GlobalMap::addPoints(const transform_t& robotTrf, const points_t& toAdd, double overlap) {\n\tif (toAdd.empty()) {\n\t\treturn;\n\t}\n\ttransform_t trfInv = robotTrf.inverse();\n\tpoints_t transformed;\n\tfor (size_t i = 0; i < toAdd.size(); i += scanStride) {\n\t\tconst point_t& point = toAdd[i];\n\t\tif (point(2) != 0) {\n\t\t\ttransformed.push_back(trfInv * point);\n\t\t}\n\t}\n\n\tif (!tree.empty()) {\n\t\tif (overlap > 0) {\n\t\t\t// find the transformation from the sample to the map\n\t\t\ttransform_t adj = icp.correct(transformed, overlap);\n\t\t\tfor (point_t& p : transformed) {\n\t\t\t\tp = adj * p;\n\t\t\t}\n\t\t}\n\t}\n\n\t// add to global map\n\tfor (const point_t& p : transformed) {\n\t\tassert(tree.add(p));\n\t}\n}\n\npoint_t GlobalMap::getClosest(const point_t& point) const {\n\tif (tree.empty()) {\n\t\treturn {0, 0, 0};\n\t}\n\tpoint_t closest = tree.getClosest(point);\n\treturn closest;\n}\n\npoints_t GlobalMap::getPointsWithin(const point_t& point, double dist) const {\n\tpoints_t points;\n\tif (!tree.empty()) {\n\t\tpoints_t within = tree.getPointsWithin(point, dist * 2);\n\t\tfor (const point_t& p1 : within) {\n\t\t\tif ((p1 - point).topRows<2>().norm() <= dist) {\n\t\t\t\tpoints.push_back(p1);\n\t\t\t}\n\t\t}\n\t}\n\treturn points;\n}\n\nbool GlobalMap::hasPointWithin(const point_t& point, double dist) const {\n\treturn tree.hasPointWithin(point, dist);\n}\n", "meta": {"hexsha": "1e3ac6cd121bc20e34b2ac4a53d2e1612503ad02", "size": 1709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/worldmap/GlobalMap.cpp", "max_stars_repo_name": "huskyroboticsteam/PY2020", "max_stars_repo_head_hexsha": "cd6368d85866204dbdca6aefacac69059e780aa2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-10-03T01:17:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-25T02:38:32.000Z", "max_issues_repo_path": "src/worldmap/GlobalMap.cpp", "max_issues_repo_name": "huskyroboticsteam/PY2020", "max_issues_repo_head_hexsha": "cd6368d85866204dbdca6aefacac69059e780aa2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2019-10-03T02:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-05T03:11:55.000Z", "max_forks_repo_path": "src/worldmap/GlobalMap.cpp", "max_forks_repo_name": "huskyroboticsteam/PY2020", "max_forks_repo_head_hexsha": "cd6368d85866204dbdca6aefacac69059e780aa2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-20T04:09:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-18T22:25:20.000Z", "avg_line_length": 23.7361111111, "max_line_length": 95, "alphanum_fraction": 0.6752486834, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5303504566034336}}
{"text": "#include <iostream>\n#include <math.h>\n#include <Eigen/Eigen>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\n#include \"../include/UKFilter.h\"\n#include \"../include/Robot.h\"\n#include \"../include/Odom.h\"\n#include \"../include/Imu.h\"\n#include \"../include/Gps.h\"\n\nUnscentedKalmanFilter unscentedKalmanFilter;\nUnscentedKalmanFilter *punscentedKalmanFilter;\n\n// Constructor\nUnscentedKalmanFilter::UnscentedKalmanFilter()\n{\n    is_initialized_ = false;\n    lastTimeStamp_ = 0;\n    nowTimeStamp_ = 0;\n    deltaTime_ = 0;\n}\n\n//Destructor\nUnscentedKalmanFilter::~UnscentedKalmanFilter()\n{\n    delete punscentedKalmanFilter;\n}\n\nvoid UnscentedKalmanFilter::Initialization()\n{\n    lastTimeStamp_ = nowTimeStamp_ = getSysTime();\n    \n    Eigen::VectorXf x_in = Eigen::VectorXf::Zero(5,1);\n    SetX(x_in);\n\n    // state covariance matrix the prediction error\n    Eigen::MatrixXf P_in(5,5);\n    P_in << 0.1, 0.0, 0.0, 0.0, 0.0,\n            0.0, 0.1, 0.0, 0.0, 0.0,\n            0.0, 0.0, 0.1, 0.0, 0.0,\n            0.0, 0.0, 0.0, 0.1, 0.0,\n            0.0, 0.0, 0.0, 0.0, 0.1;\n    SetP(P_in);\n    \n    //predicted sigma\n    Eigen::MatrixXf PreSigmaX_in = Eigen::MatrixXf::Zero(5, 15);\n    SetPreSigmaX(PreSigmaX_in);\n\n    //measurement covariance matrix\n    // R is provided by Sensor supplier\n    Eigen::MatrixXf R_in(3,3);\n    R_in << 0.1, 0.0, 0.0,\n            0.0, 0.1, 0.0,\n            0.0, 0.0, 0.1;\n    SetR(R_in);\n\n    //Observation\n    Eigen::VectorXf z_in(3,1);\n    z_in << 0.0,\n            0.0, \n            0.0;\n    SetZ(z_in);\n\n\n    is_initialized_ = true;\n\n}\n\n//state prediction\n//state defination: x, y, v, yaw, w\nvoid UnscentedKalmanFilter::StatePrediction(float d_t)\n{\n    Eigen::MatrixXf augmented_sigma = Eigen::MatrixXf::Zero(7, 15);\n    Eigen::VectorXf augmented_x = Eigen::VectorXf::Zero(7);\n    Eigen::MatrixXf augmented_P = Eigen::MatrixXf::Zero(7, 7);\n    augmented_x.head(5) = x_;\n    augmented_P.topLeftCorner(5, 5) = P_;\n    augmented_P(5, 5) = 0.1;\n    augmented_P(6, 6) = 0.1;\n    const Eigen::MatrixXf L = augmented_P.llt().matrixL();\n    augmented_sigma.col(0) = augmented_x;\n    for(int c = 0; c < 7; c++)\n    {\n        const int i = c + 1;\n        augmented_sigma.col(i)  = augmented_x + 1.732 * L.col(c);\n        augmented_sigma.col(i + 7)  = augmented_x - 1.732 * L.col(c);\n    }\n\n    Eigen::MatrixXf predicted_sigma = Eigen::MatrixXf(5, 15);\n    for(int c = 0; c < 15; ++c)\n    {\n        /*************************************\n        * Get the current state\n        *************************************/\n        const float px = augmented_sigma(0, c);\n        const float py = augmented_sigma(1, c);\n        const float speed = augmented_sigma(2, c);\n        const float yaw = augmented_sigma(3, c);\n        const float yawrate = augmented_sigma(4, c);\n        const float speed_noise = augmented_sigma(5, c);\n        const float yawrate_noise = augmented_sigma(6, c);\n \n        /*************************************\n        * predict the next state with noise\n        * USING THE CTRV MODEL\n        *************************************/\n        const float cos_yaw = cos(yaw);\n        const float sin_yaw = sin(yaw);\n        const float d_t2 = d_t * d_t;\n    \n        // predicted position noise\n        const float p_noise = 0.5 * speed_noise * d_t2;\n        // predicted yaw noise\n        const float y_noise = 0.5 * yawrate_noise * d_t2;\n        const float dyaw = yawrate * d_t; //change in yaw\n        const float dspeed = speed * d_t; //change in speed\n  \n        // predicted speed = assumed constant speed + noise\n        const float p_speed = speed + speed_noise * d_t;\n    \n        // predicted yaw\n        const float p_yaw = yaw + dyaw + y_noise;\n        // predicted yaw rate = assumed constant yawrate + noise\n        const float p_yawrate = yawrate + yawrate_noise * d_t;\n        // where predicted positions will be stored\n        float p_px, p_py;\n\n        if(fabs(yawrate) <= 0.001) \n        {\n            // moving straight\n            p_px = px + dspeed * cos_yaw + p_noise * cos_yaw;\n            p_py = py + dspeed * sin_yaw + p_noise * sin_yaw;\n\n        }\n        else\n        {\n            const float k = speed / yawrate;\n            const float theta = yaw + dyaw;\n            p_px = px + k * (sin(theta) - sin_yaw) + p_noise * cos_yaw;\n            p_py = py + k * (cos_yaw - cos(theta)) + p_noise * sin_yaw ;\n        }\n\n        /*************************************\n        * Write the prediction to the appropriate column\n        *************************************/\n        predicted_sigma(0, c) = p_px;\n        predicted_sigma(1, c) = p_py;\n        predicted_sigma(2, c) = p_speed;\n        predicted_sigma(3, c) = p_yaw;\n        predicted_sigma(4, c) = p_yawrate;\n    }\n\n    Eigen::VectorXf predicted_x = Eigen::VectorXf::Zero(5);\n    for(int c = 0; c < 15; c++)\n    {\n        predicted_x += WEIGHTS[c] * predicted_sigma.col(c);\n    }\n    Eigen::MatrixXf predicted_P = Eigen::MatrixXf::Zero(5, 5);\n    Eigen::VectorXf dx = Eigen::VectorXf(5);\n    for(int c = 0; c < 15; c++)\n    {\n        dx = predicted_sigma.col(c) - predicted_x;\n        dx(3) = (fabs(dx(3)) > M_PI) ? remainder(dx(3), 2. * M_PI) : dx(3);\n        predicted_P += WEIGHTS[c] * dx * dx.transpose();\n    }\n    SetPreSigmaX(predicted_sigma);\n    SetX(predicted_x);\n    SetP(predicted_P);\n}\n\nvoid UnscentedKalmanFilter::MeasurementPrediction()//measurement prediction\n{\n    Eigen::MatrixXf sigma = Eigen::MatrixXf::Zero(3, 15);\n    for(int c = 0; c < 15; c++)\n    {\n        const float px = PreSigmaX_(0, c);\n        const float py = PreSigmaX_(1, c);\n        const float v = PreSigmaX_(2, c);\n        const float yaw = PreSigmaX_(3, c);\n\n        const float vx = cos(yaw) * v;\n        const float vy = sin(yaw) * v;\n\n        const float rho = sqrt(px * px + py * py);\n        const float phi = atan2(py, px);\n        const float rhodot = (rho > 0.0001) ? ((px * vx + py * vy) / rho) : 0.0; \n\n        // avoid division by zero\n        sigma(0, c) = rho;\n        sigma(1, c) = phi;\n        sigma(2, c) = rhodot;\n    }\n\n    Eigen::VectorXf z = Eigen::VectorXf::Zero(3);\n    Eigen::VectorXf dz;\n    Eigen::MatrixXf S = Eigen::MatrixXf::Zero(3, 3);\n    for(int c = 0; c < 15; c++){\n        z += WEIGHTS[c] * sigma.col(c);\n    }\n    for(int c = 0; c < 15; c++)\n    {\n        dz = sigma.col(c) - z;\n        dz(1) =  (fabs(dz(1)) > M_PI) ? remainder(dz(1), 2. * M_PI) : dz(1);\n        S += WEIGHTS[c] * dz * dz.transpose();\n    }\n    S += R_;\n\n    SetPreSigmaZ(sigma);\n    SetZ(z);\n    SetS(S);\n}\n\n\nvoid UnscentedKalmanFilter::StateUpdate(Eigen::VectorXf z_new)\n{\n    Eigen::VectorXf dz;\n    Eigen::VectorXf dx;\n    Eigen::MatrixXf Tc = Eigen::MatrixXf::Zero(5, 3);\n\n    for(int c = 0; c < 15; c++)\n    {\n        dx = PreSigmaX_.col(c) - x_;\n        dx(3) = (fabs(dx(3)) > M_PI) ? remainder(dx(3), 2. * M_PI) : dx(3);\n        dz = PreSigmaZ_.col(c) - z_;\n        dz(1) = (fabs(dz(1)) > M_PI) ? remainder(dz(1), 2. * M_PI) : dz(1);\n        Tc += WEIGHTS[c] * dx * dz.transpose();\n    }\n    Eigen::MatrixXf Si = S_.inverse();\n    Eigen::MatrixXf K = Tc * Si;\n    Eigen::VectorXf dz = z_new - z_;\n    dz(1) = (fabs(dz(1)) > M_PI) ? remainder(dz(1), 2. * M_PI) : dz(1);\n\n    SetX(x_ + K * dz);\n    SetP(P_ - K * S_ * K.transpose());\n}\n\nbool UnscentedKalmanFilter::GetIsInitialized()\n{\n    return is_initialized_;\n}\n\nvoid UnscentedKalmanFilter::SetX(Eigen::VectorXf x_in)\n{\n    x_ = x_in;\n}\n\nvoid UnscentedKalmanFilter::SetP(Eigen::MatrixXf P_in)\n{\n    P_ = P_in;\n}\n\nvoid UnscentedKalmanFilter::SetPreSigmaX(Eigen::MatrixXf PreSigmaX_in)\n{\n    PreSigmaX_ = PreSigmaX_in;\n}\n\nvoid UnscentedKalmanFilter::SetPreSigmaZ(Eigen::MatrixXf PreSigmaZ_in)\n{\n    PreSigmaZ_ = PreSigmaZ_in;\n}\n\nvoid UnscentedKalmanFilter::SetZ(Eigen::VectorXf z_in)\n{\n    z_ = z_in;\n}\n\nvoid UnscentedKalmanFilter::SetR(Eigen::MatrixXf S_in)\n{\n    S_ = S_in;\n}\n\nvoid UnscentedKalmanFilter::SetR(Eigen::MatrixXf R_in)\n{\n    R_ = R_in;\n}\n\nvoid UnscentedKalmanFilter::setLastTimeStamp(const long int lastTimeStamp)\n{\n    this->lastTimeStamp_ = lastTimeStamp;\n}\n\nvoid UnscentedKalmanFilter::setNowTimeStamp(const long int nowTimeStamp )\n{\n    this->nowTimeStamp_ = nowTimeStamp;\n}\nvoid UnscentedKalmanFilter::setDeltaTime(const long int deltaTime)\n{\n    this->deltaTime_ = deltaTime;\n}\n\nvoid UnscentedKalmanFilter::getLastTimeStamp(long int& lastTimeStamp)\n{\n    lastTimeStamp = this->lastTimeStamp_;\n}\nvoid UnscentedKalmanFilter::getNowTimeStamp(long int& nowTimeStamp)\n{\n    nowTimeStamp = this->nowTimeStamp_;\n}\nvoid UnscentedKalmanFilter::getDeltaTime(long int& deltaTime)\n{\n    deltaTime = this->deltaTime_;\n}", "meta": {"hexsha": "588e1cf0fe68f55ab987e149c1b39bc3abd8fcdb", "size": 8583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RISS/src/UKFilter.cpp", "max_stars_repo_name": "wangarcher/examine", "max_stars_repo_head_hexsha": "e04c923f0db397558ea765d7fbf1050fe4aec3dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RISS/src/UKFilter.cpp", "max_issues_repo_name": "wangarcher/examine", "max_issues_repo_head_hexsha": "e04c923f0db397558ea765d7fbf1050fe4aec3dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RISS/src/UKFilter.cpp", "max_forks_repo_name": "wangarcher/examine", "max_forks_repo_head_hexsha": "e04c923f0db397558ea765d7fbf1050fe4aec3dd", "max_forks_repo_licenses": ["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.2335526316, "max_line_length": 81, "alphanum_fraction": 0.5788185949, "num_tokens": 2689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.5303118222356985}}
{"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 *    References\n *      Koon, W.S., et al. Dynamical Systems, the Three-Body Problem and Space Mission Design,\n *          2006.\n *      Jet Propulsion Laboratory, NASA. Planets and Pluto: Physical Characteristics.\n *          http://ssd.jpl.nasa.gov/?planet_phys_par, last updated: 5th November, 2008, last\n *          accessed: 22nd November, 2011.\n *      Jet Propulsion Laboratory, NASA. Astrodynamics Constants.\n *          http://ssd.jpl.nasa.gov/?constants, last updated: 6th September, 2011, last accessed:\n *          22nd November, 2011.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <cmath>\n#include <limits>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\n#include \"Tudat/Astrodynamics/Gravitation/unitConversionsCircularRestrictedThreeBodyProblem.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Test if Cartesian state conversion for CRTBP is computed correctly.\nBOOST_AUTO_TEST_CASE( testCartesianStateConversionCircularRestrictedThreeBodyProblem )\n{\n    // Test 1: conversion of dimensionless to dimensional Cartesian state vector for test particle\n    // in Sun-Jupiter system [m, m/s] (Koon, 2006).\n    {\n        // Set distance between Sun and Jupiter [m] [NASA, 2010].\n        double distanceSunJupiter = 7.784e11;\n\n        // Set magnitude of velocity of Sun-Jupiter system [m/s].\n        double velocitySunJupiter = 13.102e3;\n\n        // Set gravitational parameter of Jupiter [m^3 s^-2].\n        double gravitationalParameterJupiter = 6.67259e-11 * 1898.13e24;\n\n        // Set gravitational parameter of Sun [m^3 s^-2].\n        double gravitationalParameterSun = 1.32712440018e20;\n\n        // Set mass parameter of Sun-Jupiter system.\n        double massParameter = gravitationalParameterJupiter\n                / ( gravitationalParameterJupiter + gravitationalParameterSun );\n\n        // Set dimensionless state of the Sun.\n        using orbital_element_conversions::xCartesianPositionIndex;\n        Eigen::VectorXd dimensionlessStateOfSun = Eigen::VectorXd::Zero( 6 );\n        dimensionlessStateOfSun( xCartesianPositionIndex ) = -massParameter;\n\n        // Declare and set dimensionless state of Jupiter.\n        Eigen::VectorXd dimensionlessStateOfJupiter = Eigen::VectorXd::Zero( 6 );\n        dimensionlessStateOfJupiter( xCartesianPositionIndex ) = 1.0 - massParameter;\n\n        // Set dimensionless state of test particle in Sun-Jupiter system.\n        using orbital_element_conversions::yCartesianVelocityIndex;\n        Eigen::VectorXd dimensionlessStateOfTestParticle = Eigen::VectorXd::Zero( 6 );\n        dimensionlessStateOfTestParticle( xCartesianPositionIndex ) = 1.0;\n        dimensionlessStateOfTestParticle( yCartesianVelocityIndex ) = 1.0;\n\n        // Convert dimensionless to dimensional Cartesian state vector for test particle [m, m/s].\n        Eigen::VectorXd computedDimensionalStateOfTestParticle( 6 );\n        computedDimensionalStateOfTestParticle =\n                circular_restricted_three_body_problem::convertDimensionlessCartesianStateToDimensionalUnits(\n                    dimensionlessStateOfTestParticle, gravitationalParameterSun,\n                    gravitationalParameterJupiter, distanceSunJupiter );\n\n        // Check if computed position and velocity matches expected value.\n        BOOST_CHECK_CLOSE_FRACTION( distanceSunJupiter,\n                                    computedDimensionalStateOfTestParticle( xCartesianPositionIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( velocitySunJupiter,\n                                    computedDimensionalStateOfTestParticle( yCartesianVelocityIndex ),\n                                    1.0e-2 );\n    }\n}\n\n//! Test if time conversion for CRTBP is computed correctly.\nBOOST_AUTO_TEST_CASE( testTimeConversionCircularRestrictedThreeBodyProblem )\n{\n    using mathematical_constants::PI;\n\n    // Test 1: conversion of dimensionless to dimensional time for test particle in Sun-Jupiter\n    // system [s] (Koon, 2006).\n    {\n        // Set distance between Sun and Jupiter [m] (NASA, 2010).\n        double distanceSunJupiter = 7.784e11;\n\n        // Set gravitational parameter of Jupiter [m^3 s^-2].\n        double gravitationalParameterJupiter = 6.67259e-11 * 1898.13e24;\n\n        // Set gravitational parameter of Sun [m^3 s^-2].\n        double gravitationalParameterSun = 1.32712440018e20;\n\n        // Compute dimensional time for one complete orbit.\n        double computedDimensionalTime =\n                circular_restricted_three_body_problem::convertDimensionlessTimeToDimensionalTime(\n                    2.0 * PI, gravitationalParameterSun, gravitationalParameterJupiter,\n                    distanceSunJupiter );\n\n        // Set expected orbital period of system [s].\n        double expectedOrbitalPeriodOfSunJupiterSystem = 3.733e08;\n\n        // Check if computed orbital period matches expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedOrbitalPeriodOfSunJupiterSystem,\n                                    computedDimensionalTime, 1.0e-2 );\n    }\n}\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "baffd2a11016b96f59863543a2b43dbb85eb78e7", "size": 5740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Gravitation/UnitTests/unitTestUnitConversionsCircularRestrictedThreeBodyProblem.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/unitTestUnitConversionsCircularRestrictedThreeBodyProblem.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/unitTestUnitConversionsCircularRestrictedThreeBodyProblem.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": 44.1538461538, "max_line_length": 109, "alphanum_fraction": 0.6979094077, "num_tokens": 1301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5303059926214684}}
{"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/*! \\file qle/math/deltagammavar.hpp\n    \\brief functions to compute delta or delta-gamma VaR numbers\n    \\ingroup math\n*/\n\n#ifndef quantext_deltagammavar_hpp\n#define quantext_deltagammavar_hpp\n\n#include <qle/math/covariancesalvage.hpp>\n\n#include <ql/math/array.hpp>\n#include <ql/math/matrix.hpp>\n#include <ql/math/matrixutilities/choleskydecomposition.hpp>\n#include <ql/math/matrixutilities/pseudosqrt.hpp>\n#include <ql/math/randomnumbers/rngtraits.hpp>\n#include <ql/utilities/disposable.hpp>\n\n// fix for boost 1.64, see https://lists.boost.org/Archives/boost/2016/11/231756.php\n#if BOOST_VERSION >= 106400\n#include <boost/serialization/array_wrapper.hpp>\n#endif\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/tail_quantile.hpp>\n#include <boost/foreach.hpp>\n\nnamespace QuantExt {\nusing namespace QuantLib;\n\n//! function that computes a delta VaR\n/*! For a given covariance matrix and a delta vector this function computes a parametric var w.r.t. a given\n * confidence level for multivariate normal risk factors. */\nReal deltaVar(const Matrix& omega, const Array& delta, const Real p,\n              const CovarianceSalvage& sal = NoCovarianceSalvage());\n\n//! function that computes a delta-gamma normal VaR\n/*! For a given a covariance matrix, a delta vector and a gamma matrix this function computes a parametric var\n * w.r.t. a given confidence level. The gamma matrix is taken into account when computing the variance of the PL\n * distirbution, but the PL distribution is still assumed to be normal. */\nReal deltaGammaVarNormal(const Matrix& omega, const Array& delta, const Matrix& gamma, const Real p,\n                         const CovarianceSalvage& sal = NoCovarianceSalvage());\n\n//! function that computes a delta-gamma VaR using Monte Carlo (single quantile)\n/*! For a given a covariance matrix, a delta vector and a gamma matrix this function computes a parametric var\n * w.r.t. a given confidence level. The var quantile is estimated from Monte-Carlo realisations of a second order\n * sensitivity based PL. */\ntemplate <class RNG>\nReal deltaGammaVarMc(const Matrix& omega, const Array& delta, const Matrix& gamma, const Real p, const Size paths,\n                     const Size seed, const CovarianceSalvage& sal = NoCovarianceSalvage());\n\n//! function that computes a delta-gamma VaR using Monte Carlo (multiple quantiles)\n/*! For a given a covariance matrix, a delta vector and a gamma matrix this function computes a parametric var\n * w.r.t. a vector of given confidence levels. The var quantile is estimated from Monte-Carlo realisations of a second\n * order sensitivity based PL. */\ntemplate <class RNG>\nDisposable<std::vector<Real> > deltaGammaVarMc(const Matrix& omega, const Array& delta, const Matrix& gamma,\n                                               const std::vector<Real>& p, const Size paths, const Size seed,\n                                               const CovarianceSalvage& sal = NoCovarianceSalvage());\n\nnamespace detail {\nvoid check(const Real p);\nvoid check(const Matrix& omega, const Array& delta);\nvoid check(const Matrix& omega, const Array& delta, const Matrix& gamma);\ntemplate <typename A> Real absMax(const A& a) {\n    Real tmp = 0.0;\n    BOOST_FOREACH (Real x, a) {\n        if (std::abs(x) > tmp)\n            tmp = std::abs(x);\n    }\n    return tmp;\n}\n} // namespace detail\n\n// implementation\n\ntemplate <class RNG>\nDisposable<std::vector<Real> > deltaGammaVarMc(const Matrix& omega, const Array& delta, const Matrix& gamma,\n                                               const std::vector<Real>& p, const Size paths, const Size seed,\n                                               const CovarianceSalvage& sal) {\n    BOOST_FOREACH (Real q, p) { detail::check(q); }\n    detail::check(omega, delta, gamma);\n\n    Real num = std::max(detail::absMax(delta), detail::absMax(gamma));\n    if (close_enough(num, 0.0)) {\n        std::vector<Real> res(p.size(), 0.0);\n        return res;\n    }\n\n    Matrix L = sal.salvage(omega).second;\n    if (L.rows() == 0) {\n        L = CholeskyDecomposition(omega, true);\n    }\n\n    Real pmin = QL_MAX_REAL;\n    BOOST_FOREACH (Real q, p) { pmin = std::min(pmin, q); }\n\n    Size cache = Size(std::floor(static_cast<double>(paths) * (1.0 - pmin) + 0.5)) + 2;\n    boost::accumulators::accumulator_set<\n        double, boost::accumulators::stats<boost::accumulators::tag::tail_quantile<boost::accumulators::right> > >\n        acc(boost::accumulators::tag::tail<boost::accumulators::right>::cache_size = cache);\n\n    typename RNG::rsg_type rng = RNG::make_sequence_generator(delta.size(), seed);\n\n    for (Size i = 0; i < paths; ++i) {\n        std::vector<Real> seq = rng.nextSequence().value;\n        Array z(seq.begin(), seq.end());\n        Array u = L * z;\n        acc(DotProduct(u, delta) + 0.5 * DotProduct(u, gamma * u));\n    }\n\n    std::vector<Real> res;\n    BOOST_FOREACH (Real q, p) {\n        res.push_back(boost::accumulators::quantile(acc, boost::accumulators::quantile_probability = q));\n    }\n\n    return res;\n}\n\ntemplate <class RNG>\nReal deltaGammaVarMc(const Matrix& omega, const Array& delta, const Matrix& gamma, const Real p, const Size paths,\n                     const Size seed, const CovarianceSalvage& sal) {\n\n    std::vector<Real> pv(1, p);\n    return deltaGammaVarMc<RNG>(omega, delta, gamma, pv, paths, seed, sal).front();\n}\n\n} // namespace QuantExt\n\n#endif\n", "meta": {"hexsha": "44ca8571130d8ac764faeb3499a1600521b3aeaa", "size": 6196, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/math/deltagammavar.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/deltagammavar.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/deltagammavar.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": 41.8648648649, "max_line_length": 118, "alphanum_fraction": 0.6949644932, "num_tokens": 1503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451416, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.5303059664145396}}
{"text": "#include \"ezsolver.hpp\"\n\n#include <Eigen/Dense>\n#include <ezarpack/arpack_worker.hpp>\n#include <ezarpack/storages/eigen.hpp>\n\nusing namespace Eigen;\nusing namespace ezarpack;\n\nEzSolver::EzSolver(const Ref<const MatrixXd> &matA,\n                   const Ref<const MatrixXd> &matB)\n    : ndim_(matA.rows()), matA_(matA), matB_(matB) {}\n\nVectorXcd EzSolver::compute(double sigma, int nev) {\n  MatrixXd matL = matA_ - sigma * matB_;\n  // auto lu = matL.partialPivLu();\n  auto lhh = matL.householderQr();\n\n  using worker_t = arpack_worker<ezarpack::Asymmetric, eigen_storage>;\n  using params_t = worker_t::params_t;\n  using vector_view_t = worker_t::vector_view_t;\n  using vector_const_view_t = worker_t::vector_const_view_t;\n\n  auto o = [&](vector_const_view_t x, vector_view_t y) {\n    y = matB_ * x;\n    y = lhh.solve(y).eval();\n  };\n  worker_t worker(ndim_);\n  params_t params(nev, params_t::LargestMagnitude, params_t::Ritz);\n  worker(o, params);\n  auto const &mu = worker.eigenvalues();\n  VectorXcd lambda = mu.cwiseInverse().eval();\n  lambda.array() += sigma;\n  return lambda;\n}\n\nVectorXcd EzSolver::compute_sym(double sigma, int nev) {\n  MatrixXd matL = matA_ - sigma * matB_;\n  // auto lu = matL.partialPivLu();\n  auto lhh = matL.householderQr();\n\n  using worker_t = arpack_worker<ezarpack::Symmetric, eigen_storage>;\n  using params_t = worker_t::params_t;\n  using vector_view_t = worker_t::vector_view_t;\n  using vector_const_view_t = worker_t::vector_const_view_t;\n\n  auto o = [&](vector_const_view_t x, vector_view_t y) {\n    y = matB_ * x;\n    y = lhh.solve(y).eval();\n  };\n  worker_t worker(ndim_);\n  params_t params(nev, params_t::LargestMagnitude, false);\n  worker(o, params);\n  auto const &mu = worker.eigenvalues();\n  VectorXcd lambda = mu.cwiseInverse().eval();\n  lambda.array() += sigma;\n  return lambda;\n}", "meta": {"hexsha": "138414848250f2ac4ced0240a47f941ce1a3ce79", "size": 1821, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ezsolver.cc", "max_stars_repo_name": "pan3rock/shift-invert", "max_stars_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ezsolver.cc", "max_issues_repo_name": "pan3rock/shift-invert", "max_issues_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ezsolver.cc", "max_forks_repo_name": "pan3rock/shift-invert", "max_forks_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_forks_repo_licenses": ["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.3965517241, "max_line_length": 70, "alphanum_fraction": 0.7023613399, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5301604156495702}}
{"text": "#include <mtao/types.hpp>\n#include <iostream>\n#include<Eigen/IterativeLinearSolvers>\n#include <Eigen/Sparse>\n#include <mtao/logging/timer.hpp>\n#include <mtao/eigen/mic0_preconditioner.hpp>\nusing Mat = mtao::MatrixX<float>;\n\nfloat permeability = 100.0;\nfloat timestep = 1000.0;\n\nEigen::SparseMatrix<float> grid_boundary(int ni, int nj, bool dirichlet_boundary) {\n    int system_size = ni*nj;\n    int usize = (ni+1) * nj;\n    int vsize = (nj+1) * ni;\n    int offset = usize;\n\n    auto u_ind = [ni,nj](int i, int j) {\n        return i + j*(ni + 1);\n    };\n\n    auto v_ind = [ni,nj,offset](int i, int j) {\n        return i + j*ni + offset;\n    };\n\n    std::vector< Eigen::Triplet<float> > triplets;\n\n    Eigen::SparseMatrix<float> D(usize + vsize, system_size);\n    for (int j = 0; j < nj ; ++j) {\n        for (int i = 0; i < ni ; ++i) {\n            int index = i + ni*j;\n            if(!(dirichlet_boundary && i == 0)) {\n                triplets.push_back(Eigen::Triplet<float>( u_ind(i,j), index, 1.0/ni));\n            }\n            if(!(dirichlet_boundary && i == ni-1)) {\n            triplets.push_back(Eigen::Triplet<float>( u_ind(i+1,j), index, -1.0/ni));\n            }\n\n\n            if(!(dirichlet_boundary && j == 0)) {\n            triplets.push_back(Eigen::Triplet<float>(  v_ind(i,j), index, 1.0/nj));\n            }\n            if(!(dirichlet_boundary && j == ni-1)) {\n                triplets.push_back(Eigen::Triplet<float>(  v_ind(i,j+1), index, -1.0/nj));\n            }\n\n        }\n    }\n    D.setFromTriplets(triplets.begin(), triplets.end());\n    return D;\n}\n\n\n\n\ntemplate <typename SolverType>\nvoid run_test(int N, SolverType& solver, const std::string& name, bool print = false) {\n    Mat data = Mat::Random(N,N);\n    Eigen::Map<Eigen::VectorXf> theta(data.data(),data.size());\n    int size = N*N;\n    auto B = grid_boundary(N,N,true);\n    auto dirichlet_energy = [&]() -> double {\n        return (B * theta).squaredNorm();\n    };\n    //size ~ dx * dy ~ dx^2\n    Eigen::SparseMatrix<float> L = B.transpose() * B;\n    Eigen::SparseMatrix<float> A(size,size);\n\n    auto t = mtao::logging::timer(name + \"-total\");\n    for(int i = 0; i < 1; ++i) {\n        timestep = std::pow(10,i);\n        A.setIdentity();\n        A /= timestep;\n        A += L;\n        //auto t = mtao::logging::timer(name);\n        solver.compute(A);\n        for(int j = 0; j < 10; ++j) {\n            data = Mat::Random(N,N);\n            for(int i = 0; i < 10; ++i) {\n                theta = solver.solve(theta);\n                if(print) {\n                    std::cout << dirichlet_energy() << std::endl;\n                }\n            }\n        }\n    }\n\n        auto dms = std::chrono::duration_cast<std::chrono::milliseconds>(t.duration());\n        std::cout << dms.count() << \",\";\n}\n\nint main() {\n    mtao::logging::make_logger(\"default\",mtao::logging::Level::Info);\n    for(int i = 50; i < 1000; i+=10) {\n        Eigen::SimplicialLDLT<Eigen::SparseMatrix<float>> ldlt_solver;\n        Eigen::ConjugateGradient<Eigen::SparseMatrix<float>, Eigen::Lower|Eigen::Upper> cg_solver;\n        Eigen::ConjugateGradient<Eigen::SparseMatrix<float>, Eigen::Lower|Eigen::Upper, mtao::eigen::preconditioners::MIC0Preconditioner<float>> mic0pcg_solver;\n        //run_test(ldlt_solver, \"LDLT\");\n        std::cout << i << \",\";\n        run_test(i,cg_solver, \"CG\");\n        run_test(i,mic0pcg_solver, \"MIC0PCG\");\n        std::cout << std::endl;\n    }\n    return 0;\n\n    }\n", "meta": {"hexsha": "136e12f2c3a25faf35dd80e708bf1022f17f5782", "size": 3434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/laplacian_smoothing_test.cpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/laplacian_smoothing_test.cpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "tests/laplacian_smoothing_test.cpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0934579439, "max_line_length": 160, "alphanum_fraction": 0.5509609785, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.5301604147983174}}
{"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 \"FFT.hpp\"\n#include \"FluidEigenMappings.hpp\"\n#include \"../public/WindowFuncs.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nstruct SpectralMass\n{\n  index  startBin;\n  index  centerBin;\n  index  endBin;\n  double mass;\n};\n\nclass OptimalTransport\n{\n\n  using ArrayXd = Eigen::ArrayXd;\n  using VectorXd = Eigen::VectorXd;\n  using ArrayXXd = Eigen::ArrayXXd;\n  using ArrayXcd = Eigen::ArrayXcd;\n  template <typename T>\n  using Ref = Eigen::Ref<T>;\n  using TransportMatrix = std::vector<std::tuple<index, index, double>>;\n  template <typename T>\n  using vector = std::vector<T>;\n\npublic:\n  void init(ArrayXd A, ArrayXd B)\n  {\n    mA = A;\n    mB = B;\n    mS1 = segmentSpectrum(A);\n    mS2 = segmentSpectrum(B);\n    mTransportMatrix = computeTransportMatrix(mS1, mS2);\n    mInitialized = true;\n  }\n\n  bool initialized() const { return mInitialized; }\n\n  vector<SpectralMass> segmentSpectrum(const Ref<ArrayXd> magnitude)\n  {\n    const auto&          epsilon = std::numeric_limits<double>::epsilon();\n    vector<SpectralMass> masses;\n    ArrayXd              mag = magnitude;\n    double               totalMass = mag.sum() + epsilon;\n    ArrayXd              invMag = mag * (-1);\n    vector<index>        peaks = findPeaks(mag);\n    vector<index>        valleys = findPeaks(invMag);\n    if (peaks.size() == 0 || valleys.size() == 0) return masses;\n    index        nextValley = valleys[0] > peaks[0] ? 0 : 1;\n    SpectralMass firstMass{0, peaks[0], valleys[asUnsigned(nextValley)], 0};\n    firstMass.mass =\n        magnitude.segment(0, valleys[asUnsigned(nextValley)]).sum() / totalMass;\n    masses.emplace_back(firstMass);\n    for (index i = 1; asUnsigned(i) < (peaks.size() - 1); i++)\n    {\n      index start = valleys[asUnsigned(nextValley)];\n      if (start < 0) start = 0;\n      index center = peaks[asUnsigned(i)];\n      index end = valleys[asUnsigned(nextValley) + 1];\n      if (end > magnitude.size() - 1) end = magnitude.size() - 1;\n      if (end < 0 || start > end) continue;\n      double mass = magnitude.segment(start, end - start).sum() / totalMass;\n      masses.emplace_back(SpectralMass{start, center, end, mass});\n      nextValley++;\n    }\n    if (nextValley < valleys.size() - 1)\n    {\n      index lastStart = valleys[asUnsigned(nextValley)];\n      index lastSize = magnitude.size() - 1 - lastStart;\n      if (lastSize < 0) lastSize = 0;\n      if (lastSize > magnitude.size() - lastStart - 1)\n        lastSize = magnitude.size() - lastStart - 1;\n      double lastMass = magnitude.segment(lastStart, lastSize).sum();\n      lastMass /= totalMass;\n      masses.push_back(SpectralMass{valleys.at(asUnsigned(nextValley)),\n                                    peaks.at(peaks.size() - 1),\n                                    magnitude.size() - 1, lastMass});\n    }\n    return masses;\n  }\n\n  TransportMatrix computeTransportMatrix(std::vector<SpectralMass> m1,\n                                         std::vector<SpectralMass> m2)\n  {\n    TransportMatrix matrix;\n    index           index1 = 0, index2 = 0;\n    double          mass1 = m1[0].mass;\n    double          mass2 = m2[0].mass;\n    while (true)\n    {\n      if (mass1 < mass2)\n      {\n        matrix.emplace_back(index1, index2, mass1);\n        mDistance += mass1 * std::pow(index1 - index2, 2);\n        mass2 -= mass1;\n\n        index1++;\n        if (index1 >= asSigned(m1.size())) break;\n        mass1 = m1[asUnsigned(index1)].mass;\n      }\n      else\n      {\n        matrix.emplace_back(index1, index2, mass2);\n        mDistance += mass2 * std::pow(index1 - index2, 2);\n        mass1 -= mass2;\n        index2++;\n        if (index2 >= asSigned(m2.size())) break;\n        mass2 = m2[asUnsigned(index2)].mass;\n      }\n    }\n    return matrix;\n  }\n\n  void placeMass(const SpectralMass mass, index bin, double scale,\n                 Ref<ArrayXd> input, Ref<ArrayXd> output)\n  {\n    for (index i = mass.startBin; i < mass.endBin; i++)\n    {\n      index pos = i + bin - mass.centerBin;\n      if (pos < 0 || pos >= output.size()) continue;\n      double mag = scale * std::abs(input(i));\n      output(pos) += mag;\n    }\n  }\n\n  void interpolate(double interpolation, Eigen::Ref<ArrayXd> out)\n  {\n    for (auto t : mTransportMatrix)\n    {\n      SpectralMass m1 = mS1[asUnsigned(std::get<0>(t))];\n      SpectralMass m2 = mS2[asUnsigned(std::get<1>(t))];\n      index  interpolatedBin = std::lrint((1 - interpolation) * m1.centerBin +\n                                         interpolation * m2.centerBin);\n      double interpolationFactor = interpolation;\n      if (m1.centerBin != m2.centerBin)\n      {\n        interpolationFactor =\n            ((double) interpolatedBin - (double) m1.centerBin) /\n            ((double) m2.centerBin - (double) m1.centerBin);\n      }\n      placeMass(m1, interpolatedBin,\n                (1 - interpolation) * std::get<2>(t) / m1.mass, mA, out);\n      placeMass(m2, interpolatedBin, interpolation * std::get<2>(t) / m2.mass,\n                mB, out);\n    }\n  }\n\n  std::vector<index> findPeaks(const Ref<ArrayXd> correlation)\n  {\n    std::vector<index> peaks;\n    for (index i = 1; i < correlation.size() - 1; i++)\n    {\n      if (correlation(i) > correlation(i - 1) &&\n          correlation(i) > correlation(i + 1))\n      { peaks.push_back(i); }\n    }\n    return peaks;\n  }\n\n  bool                      mInitialized{false};\n  TransportMatrix           mTransportMatrix;\n  ArrayXd                   mA;\n  ArrayXd                   mB;\n  std::vector<SpectralMass> mS1;\n  std::vector<SpectralMass> mS2;\n  double                    mDistance{0};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "88035f2703af7c20ee7c580d602a921bf496fde9", "size": 6148, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/OptimalTransport.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/OptimalTransport.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/OptimalTransport.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": 32.3578947368, "max_line_length": 80, "alphanum_fraction": 0.5988939493, "num_tokens": 1616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5301604115025093}}
{"text": "#include <ompl/base/goals/GoalState.h>\n#include <ompl/base/spaces/SE2StateSpace.h>\n#include <ompl/base/spaces/DiscreteStateSpace.h>\n#include <ompl/control/spaces/RealVectorControlSpace.h>\n#include <ompl/control/SimpleSetup.h>\n#include <ompl/config.h>\n#include <iostream>\n#include <limits>\n#include <boost/math/constants/constants.hpp>\n\nnamespace ob = ompl::base;\nnamespace oc = ompl::control;\n\nvoid propagate(const oc::SpaceInformation *si, const ob::State *state, const oc::Control* control, const double duration, ob::State *result) {\n    static double timeStep = .01;\n    int nsteps = ceil(duration / timeStep);\n    double dt = duration / nsteps;\n    const double *u = control->as<oc::RealVectorControlSpace::ControlType>()->values;\n\n    ob::CompoundStateSpace::StateType& s = *result->as<ob::CompoundStateSpace::StateType>();\n    ob::SE2StateSpace::StateType& se2 = *s.as<ob::SE2StateSpace::StateType>(0);\n    ob::RealVectorStateSpace::StateType& velocity = *s.as<ob::RealVectorStateSpace::StateType>(1);\n    // ob::DiscreteStateSpace::StateType& gear = *s.as<ob::DiscreteStateSpace::StateType>(2);\n\n    si->getStateSpace()->copyState(result, state);\n    for (int i = 0; i < nsteps; i++) {\n        se2.setX(se2.getX() + dt * velocity.values[0] * cos(se2.getYaw()));\n        se2.setY(se2.getY() + dt * velocity.values[0] * sin(se2.getYaw()));\n        se2.setYaw(se2.getYaw() + dt * u[0]);\n        // velocity.values[0] = velocity.values[0] + dt * (u[1]*gear.value);\n        velocity.values[0] = velocity.values[0] + dt * u[1];\n\n        // 'guards' - conditions to change gears\n        // if (gear.value > 0)\n        // {\n        //     if (gear.value < 3 && velocity.values[0] > 10*(gear.value + 1))\n        //         gear.value++;\n        //     else if (gear.value > 1 && velocity.values[0] < 10*gear.value)\n        //         gear.value--;\n        // }\n\n        if (!si->satisfiesBounds(result))\n            return;\n    }\n}\n\n// The free space consists of two narrow corridors connected at right angle.\n// To make the turn, the car will have to downshift.\nbool isStateValid(const oc::SpaceInformation *si, const ob::State *state) {\n    const ob::SE2StateSpace::StateType *se2 = state->as<ob::CompoundState>()->as<ob::SE2StateSpace::StateType>(0);\n    // return si->satisfiesBounds(state) && (se2->getX() < -80. || se2->getY() > 80.);\n\n    // check if bounds are satisfied\n    // if (si->satisfiesBounds(state)) {        \n        if ((se2->getX() > -60. && se2->getX() < -30 && se2->getY() > -60. && se2->getY() < -30) ||\n            (se2->getX() > -60. && se2->getX() < -30 && se2->getY() > 30. && se2->getY() < 60) ||\n            (se2->getX() > 30. && se2->getX() < 60 && se2->getY() > 30. && se2->getY() < 60)) {\n            return false;\n        } else {\n            return true;\n        }\n    // } else {    \n    //     return false;\n    // }    \n}\n\nint main(int, char**) {\n    // plan for hybrid car in SE(2) with discrete gears\n    ob::StateSpacePtr SE2(new ob::SE2StateSpace());\n    ob::StateSpacePtr velocity(new ob::RealVectorStateSpace(1));\n    // set the range for gears: [-1,3] inclusive\n    // ob::StateSpacePtr gear(new ob::DiscreteStateSpace(-1,3));\n    ob::StateSpacePtr stateSpace = SE2 + velocity;\n\n    // set the bounds for the R^2 part of SE(2)\n    ob::RealVectorBounds bounds(2);\n    bounds.setLow(-100);\n    bounds.setHigh(100);\n    SE2->as<ob::SE2StateSpace>()->setBounds(bounds);\n\n    // set the bounds for the velocity\n    ob::RealVectorBounds velocityBound(1);\n    velocityBound.setLow(0);\n    velocityBound.setHigh(60);\n    velocity->as<ob::RealVectorStateSpace>()->setBounds(velocityBound);\n\n    // create start and goal states\n    ob::ScopedState<> start(stateSpace);\n    ob::ScopedState<> goal(stateSpace);\n\n    // Both start and goal are states with high velocity with the car in third gear.\n    // However, to make the turn, the car cannot stay in third gear and will have to\n    // shift to first gear.\n    start[0] = -79.6228; //position\n    start[1] = -81.93; //position\n    start[2] = -0.911333; // orientation\n    // start[3] = 40.; // velocity\n    // start->as<ob::CompoundState>()->as<ob::DiscreteStateSpace::StateType>(2)->value = 3; // gear\n\n    goal[0] = -50; // position\n    goal[1] = -50; //position\n    // goal[2] = 0; // orientation\n    // goal[3] = 40.; // velocity\n    // goal->as<ob::CompoundState>()->as<ob::DiscreteStateSpace::StateType>(2)->value = 3; // gear\n\n    oc::ControlSpacePtr cmanifold(new oc::RealVectorControlSpace(stateSpace, 2));\n\n    // set the bounds for the control manifold\n    ob::RealVectorBounds cbounds(2);\n    // bounds for steering input\n    cbounds.setLow(0, -3.);\n    cbounds.setHigh(0, 3.);\n    // bounds for brake/gas input\n    cbounds.setLow(1, -20.);\n    cbounds.setHigh(1, 20.);\n    cmanifold->as<oc::RealVectorControlSpace>()->setBounds(cbounds);\n\n    oc::SimpleSetup setup(cmanifold);\n    setup.setStartAndGoalStates(start, goal, 5.);\n    setup.setStateValidityChecker(boost::bind(&isStateValid, setup.getSpaceInformation().get(), _1));\n    setup.setStatePropagator(boost::bind(&propagate, setup.getSpaceInformation().get(), _1, _2, _3, _4));\n    setup.getSpaceInformation()->setPropagationStepSize(.1);\n    setup.getSpaceInformation()->setMinMaxControlDuration(2, 3);\n\n    // try to solve the problem\n    if (setup.solve(30)) {\n        // print the (approximate) solution path: print states along the path\n        // and controls required to get from one state to the next\n        oc::PathControl& path(setup.getSolutionPath());\n\n        // print out full state on solution path\n        // (format: x, y, theta, v, u0, u1, dt)\n        for (unsigned int i = 0; i < path.getStateCount(); ++i) {\n            const ob::State* state = path.getState(i);\n            const ob::SE2StateSpace::StateType *se2 = state->as<ob::CompoundState>()->as<ob::SE2StateSpace::StateType>(0);\n            const ob::RealVectorStateSpace::StateType *velocity = state->as<ob::CompoundState>()->as<ob::RealVectorStateSpace::StateType>(1);\n\n            std::cout << se2->getX() << ' ' << se2->getY() << ' ' << se2->getYaw() << ' ' << velocity->values[0] << ' ';\n            if (i == 0)\n                // null controls applied for zero seconds to get to start state\n                std::cout << \"0 0 0\";\n            else {\n                // print controls and control duration needed to get from state i-1 to state i\n                const double* u = path.getControl(i - 1)->as<oc::RealVectorControlSpace::ControlType>()->values;\n                std::cout << u[0] << ' ' << u[1] << ' ' << path.getControlDuration(i - 1);\n            }\n            std::cout << std::endl;\n        }\n        if (!setup.haveExactSolutionPath()) {\n            std::cout << \"Solution is approximate. Distance to actual goal is \" << setup.getProblemDefinition()->getSolutionDifference() << std::endl;\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "299e12ea66d8808927c5263d767524123de56225", "size": 6876, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ompl/demos/Patrol1.cpp", "max_stars_repo_name": "SZanlongo/omplapp", "max_stars_repo_head_hexsha": "c56679337e2a71d266359450afbe63d700c0a666", "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": "ompl/demos/Patrol1.cpp", "max_issues_repo_name": "SZanlongo/omplapp", "max_issues_repo_head_hexsha": "c56679337e2a71d266359450afbe63d700c0a666", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ompl/demos/Patrol1.cpp", "max_forks_repo_name": "SZanlongo/omplapp", "max_forks_repo_head_hexsha": "c56679337e2a71d266359450afbe63d700c0a666", "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": 44.0769230769, "max_line_length": 150, "alphanum_fraction": 0.6109656777, "num_tokens": 1952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5301604065041957}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// median.hpp\r\n//\r\n//  Copyright 2006 Eric Niebler, Olivier Gygi. Distributed under the Boost\r\n//  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#ifndef BOOST_ACCUMULATORS_STATISTICS_MEDIAN_HPP_EAN_28_10_2005\r\n#define BOOST_ACCUMULATORS_STATISTICS_MEDIAN_HPP_EAN_28_10_2005\r\n\r\n#include <boost/mpl/placeholders.hpp>\r\n#include <boost/range/iterator_range.hpp>\r\n#include <boost/accumulators/framework/accumulator_base.hpp>\r\n#include <boost/accumulators/framework/extractor.hpp>\r\n#include <boost/accumulators/numeric/functional.hpp>\r\n#include <boost/accumulators/framework/parameters/sample.hpp>\r\n#include <boost/accumulators/framework/depends_on.hpp>\r\n#include <boost/accumulators/statistics_fwd.hpp>\r\n#include <boost/accumulators/statistics/count.hpp>\r\n#include <boost/accumulators/statistics/p_square_quantile.hpp>\r\n#include <boost/accumulators/statistics/density.hpp>\r\n#include <boost/accumulators/statistics/p_square_cumul_dist.hpp>\r\n\r\nnamespace boost { namespace accumulators\r\n{\r\n\r\nnamespace impl\r\n{\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // median_impl\r\n    //\r\n    /**\r\n        @brief Median estimation based on the \\f$P^2\\f$ quantile estimator\r\n\r\n        The \\f$P^2\\f$ algorithm is invoked with a quantile probability of 0.5.\r\n    */\r\n    template<typename Sample>\r\n    struct median_impl\r\n      : accumulator_base\r\n    {\r\n        // for boost::result_of\r\n        typedef typename numeric::functional::average<Sample, std::size_t>::result_type result_type;\r\n\r\n        median_impl(dont_care) {}\r\n\r\n        template<typename Args>\r\n        result_type result(Args const &args) const\r\n        {\r\n            return p_square_quantile_for_median(args);\r\n        }\r\n    };\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // with_density_median_impl\r\n    //\r\n    /**\r\n        @brief Median estimation based on the density estimator\r\n\r\n        The algorithm determines the bin in which the \\f$0.5*cnt\\f$-th sample lies, \\f$cnt\\f$ being\r\n        the total number of samples. It returns the approximate horizontal position of this sample,\r\n        based on a linear interpolation inside the bin.\r\n    */\r\n    template<typename Sample>\r\n    struct with_density_median_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::average<Sample, std::size_t>::result_type float_type;\r\n        typedef std::vector<std::pair<float_type, float_type> > histogram_type;\r\n        typedef iterator_range<typename histogram_type::iterator> range_type;\r\n        // for boost::result_of\r\n        typedef float_type result_type;\r\n\r\n        template<typename Args>\r\n        with_density_median_impl(Args const &args)\r\n          : sum(numeric::average(args[sample | Sample()], (std::size_t)1))\r\n          , is_dirty(true)\r\n        {\r\n        }\r\n\r\n        void operator ()(dont_care)\r\n        {\r\n            this->is_dirty = true;\r\n        }\r\n\r\n\r\n        template<typename Args>\r\n        result_type result(Args const &args) const\r\n        {\r\n            if (this->is_dirty)\r\n            {\r\n                this->is_dirty = false;\r\n\r\n                std::size_t cnt = count(args);\r\n                range_type histogram = density(args);\r\n                typename range_type::iterator it = histogram.begin();\r\n                while (this->sum < 0.5 * cnt)\r\n                {\r\n                    this->sum += it->second * cnt;\r\n                    ++it;\r\n                }\r\n                --it;\r\n                float_type over = numeric::average(this->sum - 0.5 * cnt, it->second * cnt);\r\n                this->median = it->first * over + (it + 1)->first * (1. - over);\r\n            }\r\n\r\n            return this->median;\r\n        }\r\n\r\n    private:\r\n        mutable float_type sum;\r\n        mutable bool is_dirty;\r\n        mutable float_type median;\r\n    };\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // with_p_square_cumulative_distribution_median_impl\r\n    //\r\n    /**\r\n        @brief Median estimation based on the \\f$P^2\\f$ cumulative distribution estimator\r\n\r\n        The algorithm determines the first (leftmost) bin with a height exceeding 0.5. It\r\n        returns the approximate horizontal position of where the cumulative distribution\r\n        equals 0.5, based on a linear interpolation inside the bin.\r\n    */\r\n    template<typename Sample>\r\n    struct with_p_square_cumulative_distribution_median_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::average<Sample, std::size_t>::result_type float_type;\r\n        typedef std::vector<std::pair<float_type, float_type> > histogram_type;\r\n        typedef iterator_range<typename histogram_type::iterator> range_type;\r\n        // for boost::result_of\r\n        typedef float_type result_type;\r\n\r\n        with_p_square_cumulative_distribution_median_impl(dont_care)\r\n          : is_dirty(true)\r\n        {\r\n        }\r\n\r\n        void operator ()(dont_care)\r\n        {\r\n            this->is_dirty = true;\r\n        }\r\n\r\n        template<typename Args>\r\n        result_type result(Args const &args) const\r\n        {\r\n            if (this->is_dirty)\r\n            {\r\n                this->is_dirty = false;\r\n\r\n                range_type histogram = p_square_cumulative_distribution(args);\r\n                typename range_type::iterator it = histogram.begin();\r\n                while (it->second < 0.5)\r\n                {\r\n                    ++it;\r\n                }\r\n                float_type over = numeric::average(it->second - 0.5, it->second - (it - 1)->second);\r\n                this->median = it->first * over + (it + 1)->first * ( 1. - over );\r\n            }\r\n\r\n            return this->median;\r\n        }\r\n    private:\r\n\r\n        mutable bool is_dirty;\r\n        mutable float_type median;\r\n    };\r\n\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::median\r\n// tag::with_densisty_median\r\n// tag::with_p_square_cumulative_distribution_median\r\n//\r\nnamespace tag\r\n{\r\n    struct median\r\n      : depends_on<p_square_quantile_for_median>\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::median_impl<mpl::_1> impl;\r\n    };\r\n    struct with_density_median\r\n      : depends_on<count, density>\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::with_density_median_impl<mpl::_1> impl;\r\n    };\r\n    struct with_p_square_cumulative_distribution_median\r\n      : depends_on<p_square_cumulative_distribution>\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::with_p_square_cumulative_distribution_median_impl<mpl::_1> impl;\r\n    };\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::median\r\n// extract::with_density_median\r\n// extract::with_p_square_cumulative_distribution_median\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::median> const median = {};\r\n    extractor<tag::with_density_median> const with_density_median = {};\r\n    extractor<tag::with_p_square_cumulative_distribution_median> const with_p_square_cumulative_distribution_median = {};\r\n\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(median)\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(with_density_median)\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(with_p_square_cumulative_distribution_median)\r\n}\r\n\r\nusing extract::median;\r\nusing extract::with_density_median;\r\nusing extract::with_p_square_cumulative_distribution_median;\r\n\r\n// median(with_p_square_quantile) -> median\r\ntemplate<>\r\nstruct as_feature<tag::median(with_p_square_quantile)>\r\n{\r\n    typedef tag::median type;\r\n};\r\n\r\n// median(with_density) -> with_density_median\r\ntemplate<>\r\nstruct as_feature<tag::median(with_density)>\r\n{\r\n    typedef tag::with_density_median type;\r\n};\r\n\r\n// median(with_p_square_cumulative_distribution) -> with_p_square_cumulative_distribution_median\r\ntemplate<>\r\nstruct as_feature<tag::median(with_p_square_cumulative_distribution)>\r\n{\r\n    typedef tag::with_p_square_cumulative_distribution_median type;\r\n};\r\n\r\n// for the purposes of feature-based dependency resolution,\r\n// with_density_median and with_p_square_cumulative_distribution_median\r\n// provide the same feature as median\r\ntemplate<>\r\nstruct feature_of<tag::with_density_median>\r\n  : feature_of<tag::median>\r\n{\r\n};\r\n\r\ntemplate<>\r\nstruct feature_of<tag::with_p_square_cumulative_distribution_median>\r\n  : feature_of<tag::median>\r\n{\r\n};\r\n\r\n// So that median can be automatically substituted with\r\n// weighted_median when the weight parameter is non-void.\r\ntemplate<>\r\nstruct as_weighted_feature<tag::median>\r\n{\r\n    typedef tag::weighted_median type;\r\n};\r\n\r\ntemplate<>\r\nstruct feature_of<tag::weighted_median>\r\n  : feature_of<tag::median>\r\n{\r\n};\r\n\r\n// So that with_density_median can be automatically substituted with\r\n// with_density_weighted_median when the weight parameter is non-void.\r\ntemplate<>\r\nstruct as_weighted_feature<tag::with_density_median>\r\n{\r\n    typedef tag::with_density_weighted_median type;\r\n};\r\n\r\ntemplate<>\r\nstruct feature_of<tag::with_density_weighted_median>\r\n  : feature_of<tag::with_density_median>\r\n{\r\n};\r\n\r\n// So that with_p_square_cumulative_distribution_median can be automatically substituted with\r\n// with_p_square_cumulative_distribution_weighted_median when the weight parameter is non-void.\r\ntemplate<>\r\nstruct as_weighted_feature<tag::with_p_square_cumulative_distribution_median>\r\n{\r\n    typedef tag::with_p_square_cumulative_distribution_weighted_median type;\r\n};\r\n\r\ntemplate<>\r\nstruct feature_of<tag::with_p_square_cumulative_distribution_weighted_median>\r\n  : feature_of<tag::with_p_square_cumulative_distribution_median>\r\n{\r\n};\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#endif\r\n", "meta": {"hexsha": "a369983463b281d8b837e3176e9a45860a1d1d42", "size": 9906, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/accumulators/statistics/median.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/accumulators/statistics/median.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/accumulators/statistics/median.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": 32.8013245033, "max_line_length": 122, "alphanum_fraction": 0.6311326469, "num_tokens": 2000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5301603998033783}}
{"text": "////////////////////////////////////////////////////////////////////////////////////\n// The MIT License (MIT)                                                          //\n//                                                                                //\n// Copyright (c) 2015 Whit Armstrong                                              //\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#pragma once\n\n#include <stdexcept>\n#include <armadillo>\n#include <armalogp/arma.extensions.hpp>\n#include <armalogp/arma.math.hpp>\n\nnamespace armalogp {\n\n  template<double LOGF(double), typename T, typename U, typename V>\n  double normal_logp(const T& x, const U& mu, const V& tau) {\n    return arma::accu(0.5*LOGF(0.5*tau/arma::datum::pi) - 0.5 * arma::schur_prod(tau, square(x - mu)));\n  }\n\n  template<double LOGF(double), typename T, typename U, typename V>\n  double uniform_logp(const T& x, const U& lower, const V& upper) {\n    return (arma::any(arma::vectorise(x < lower)) || arma::any(arma::vectorise(x > upper))) ? -std::numeric_limits<double>::infinity() : -arma::accu(LOGF(upper - lower));\n  }\n\n  template<double LOGF(double), typename T, typename U, typename V>\n  double gamma_logp(const T& x, const U& alpha, const V& beta) {\n    return arma::any(arma::vectorise(x < 0)) ?\n      -std::numeric_limits<double>::infinity() :\n      arma::accu(arma::schur_prod((alpha - 1.0),LOGF(x)) - arma::schur_prod(beta,x) - lgamma(alpha) + arma::schur_prod(alpha,LOGF(beta)));\n  }\n\n  template<double LOGF(double), typename T, typename U, typename V>\n  double beta_logp(const T& x, const U& alpha, const V& beta) {\n    const double one = 1.0;\n    return arma::any(arma::vectorise(x <= 0)) || arma::any(arma::vectorise(x >= 1)) || arma::any(arma::vectorise(alpha <= 0)) || arma::any(arma::vectorise(beta <= 0)) ?\n      -std::numeric_limits<double>::infinity() :\n      arma::accu(lgamma(alpha+beta) - lgamma(alpha) - lgamma(beta) + arma::schur_prod((alpha-one),LOGF(x)) + arma::schur_prod((beta-one),LOGF(one-x)));\n  }\n\n  template<double LOGF(double)>\n  double categorical_logp(const arma::ivec& x, const arma::mat& p) {\n    if(arma::any(arma::vectorise(p <= 0)) || arma::any(arma::vectorise(p >= 1)) || arma::any(arma::vectorise(x < 0)) || arma::any(arma::vectorise(x >= p.n_cols))) {\n      return -std::numeric_limits<double>::infinity();\n    }\n    // replace w/ call to p.elems later\n    double ans(0);\n    for(unsigned int i = 0; i < x.n_rows; i++) {\n      ans += LOGF(p(i,x[i]));\n    }\n    return ans;\n  }\n\n  template<double LOGF(double)>\n  double categorical_logp(const arma::ivec& x, const arma::vec& p) {\n    if(arma::any(arma::vectorise(p <= 0)) || arma::any(arma::vectorise(p >= 1)) || arma::any(arma::vectorise(x < 0)) || arma::any(arma::vectorise(x >= p.n_elem))) {\n      return -std::numeric_limits<double>::infinity();\n    }\n    // replace w/ call to p.elems later\n    double ans(0);\n    for(unsigned int i = 0; i < x.n_rows; i++) {\n      ans += LOGF(p(x[i]));\n    }\n    return ans;\n  }\n\n  template<double LOGF(double)>\n  double categorical_logp(const int x, const arma::vec& p) {\n    return LOGF(p[x]);\n  }\n\n  template<double LOGF(double), typename T, typename U, typename V>\n  double binomial_logp(const T& x, const U& n, const V& p) {\n    if(arma::any(arma::vectorise(p <= 0)) || arma::any(arma::vectorise(p >= 1)) || arma::any(arma::vectorise(x < 0))  || arma::any(arma::vectorise(x > n))) {\n      return -std::numeric_limits<double>::infinity();\n    }\n    return arma::accu(arma::schur_prod(x,LOGF(p)) + arma::schur_prod((n-x),LOGF(1-p)) + arma::factln(n) - arma::factln(x) - arma::factln(n-x));\n  }\n\n  template<double LOGF(double), typename T, typename U>\n  double bernoulli_logp(const T& x, const U& p) {\n    if( arma::any(arma::vectorise(p <= 0)) || arma::any(arma::vectorise(p >= 1)) || arma::any(arma::vectorise(x < 0))  || arma::any(arma::vectorise(x > 1)) ) {\n      return -std::numeric_limits<double>::infinity();\n    } else {\n      return arma::accu(arma::schur_prod(x,LOGF(p)) + arma::schur_prod((1-x), LOGF(1-p)));\n    }\n  }\n\n  template<double LOGF(double), typename T, typename U>\n  double poisson_logp(const T& x, const U& mu) {\n    if( arma::any(arma::vectorise(mu < 0)) || arma::any(arma::vectorise(x < 0))) {\n      return -std::numeric_limits<double>::infinity();\n    } else {\n      return arma::accu(schur(x,LOGF(mu)) - mu - factln(x));\n    }\n  }\n\n  template<double LOGF(double), typename T, typename U>\n  double exponential_logp(const T& x, const U& lambda) {\n    if(!arma::all(arma::vectorise(x > 0)) || !arma::all(arma::vectorise(lambda > 0))) {\n        return -std::numeric_limits<double>::infinity();\n    }\n    return arma::accu(LOGF(lambda) - arma::schur_prod(lambda, x));\n  }\n\n  template<double LOGF(double), typename T, typename U>\n  double multivariate_normal_chol_logp(const T& x, const U& mu, const arma::mat& R) {\n    static double log_2pi = LOGF(2 * arma::datum::pi);\n    double ldet = LOGF(cholesky_determinant(R));\n    return -0.5 * (x.n_elem * log_2pi + ldet + mahalanobis_chol(x,mu,R));\n  }\n\n  // sigma denotes cov matrix rather than precision matrix\n  template<double LOGF(double), typename T, typename U>\n  double multivariate_normal_sigma_logp(const T& x, const U& mu, const arma::mat& sigma) {\n    arma::mat R;\n    bool chol_succeeded = chol(R,sigma);\n    if(!chol_succeeded) { return -std::numeric_limits<double>::infinity(); }\n\n    return multivariate_normal_chol_logp<LOGF>(x, mu, R);\n  }\n\n  // sigma denotes cov matrix rather than precision matrix\n  template<double LOGF(double)>\n  double multivariate_normal_sigma_logp(const arma::mat& x, const arma::vec& mu, const arma::mat& sigma) {\n    arma::mat R;\n    bool chol_succeeded = chol(R,sigma);\n    if(!chol_succeeded) { return -std::numeric_limits<double>::infinity(); }\n    const arma::rowvec mu_r = mu.t();\n    double ans(0);\n    for(size_t i = 0; i < x.n_rows; i++) {\n      ans += multivariate_normal_chol_logp<LOGF>(x.row(i), mu_r, R);\n    }\n    return ans;\n  }\n\n  template<double LOGF(double)>\n  double multivariate_normal_chol_logp(const arma::mat& x, const arma::vec& mu, const arma::mat& R) {\n    const arma::rowvec mu_r = mu.t();\n    double ans(0);\n    for(size_t i = 0; i < x.n_rows; i++) {\n      ans += multivariate_normal_chol_logp<LOGF>(x.row(i), mu_r, R);\n    }\n    return ans;\n  }\n\n  template<double LOGF(double)>\n  double wishart_logp(const arma::mat& X, const arma::mat& tau, const unsigned int n) {\n    if(X.n_cols != X.n_rows || tau.n_cols != tau.n_rows || X.n_cols != tau.n_rows || X.n_cols > n) { return -std::numeric_limits<double>::infinity(); }\n    const double lg2 = LOGF(2.0);\n    const int k = X.n_cols;\n    const double dx(arma::det(X));\n    const double db(arma::det(tau));\n    if(dx <= 0 || db <= 0) { return -std::numeric_limits<double>::infinity(); }\n\n    const double ldx(LOGF(dx));\n    const double ldb(LOGF(db));\n    const arma::mat bx(X * tau);\n    const double tbx = arma::trace(bx);\n\n    double cum_lgamma(0);\n    for(size_t i = 0; i < X.n_rows; ++i) {\n      cum_lgamma += lgamma((n + 1)/2.0);\n    }\n    return (n - k - 1)/2 * ldx + (n/2.0)*ldb - 0.5*tbx - (n*k/2.0)*lg2 - cum_lgamma;\n  }\n\n} // namespace armalogp\n\n", "meta": {"hexsha": "12059882887e8e9b807b4f803d4777f184e3bda8", "size": 8713, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "armalogp/arma.logp.hpp", "max_stars_repo_name": "armaMCMC/arma-log-likelihood", "max_stars_repo_head_hexsha": "c8323afb0a99fbb69cdf738b7fbbde98432a7c66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "armalogp/arma.logp.hpp", "max_issues_repo_name": "armaMCMC/arma-log-likelihood", "max_issues_repo_head_hexsha": "c8323afb0a99fbb69cdf738b7fbbde98432a7c66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "armalogp/arma.logp.hpp", "max_forks_repo_name": "armaMCMC/arma-log-likelihood", "max_forks_repo_head_hexsha": "c8323afb0a99fbb69cdf738b7fbbde98432a7c66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.3457446809, "max_line_length": 170, "alphanum_fraction": 0.5899231034, "num_tokens": 2377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5301313271715354}}
{"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_MANTISSA_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MANTISSA_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing mantissa capabilities\n\n    Returns the signed mantissa of the floating input.\n\n    @par Semantic:\n\n    @code\n    auto r = mantissa(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    auto r = x*pow(2, -exponent(x));\n    @endcode\n\n    @par Note\n    The @ref exponent e and signed @ref mantissa m of a floating point entry a are related by\n    \\f$a = m\\times 2^e\\f$, with |m| \\f$\\in[1, 2[\\f$.\n\n    @see frexp, pow, exponent\n\n  **/\n  Value mantissa(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/mantissa.hpp>\n#include <boost/simd/function/simd/mantissa.hpp>\n\n#endif\n", "meta": {"hexsha": "dd910bfc8a9d376679a4d39cf3322c5824acf2f9", "size": 1203, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/mantissa.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/mantissa.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/mantissa.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": 23.1346153846, "max_line_length": 100, "alphanum_fraction": 0.5768911056, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5301313247835712}}
{"text": "\n#include <boost/program_options.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <cassert>\n#include <list>\n#include <vector>\n\n\n// https://doc.cgal.org/latest/Triangulation_3/\n// https://doc.cgal.org/latest/Kernel_23/index.html#Chapter_2D_and_3D_Geometry_Kernel\n// http://doc.cgal.org/latest/Triangulation_3/classTriangulationTraits__3.html\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n// https://doc.cgal.org/latest/Triangulation_3/classCGAL_1_1Triangulation__3.html\n// https://doc.cgal.org/latest/Triangulation_3/classCGAL_1_1Delaunay__triangulation__3.html\n#include <CGAL/Delaunay_triangulation_3.h>\n#include <CGAL/Triangulation_data_structure_3.h>\n\n// The doc for Point is a little tricky to find. Delaunay and Triangulation pages\n// don't link here:\n// https://doc.cgal.org/latest/Kernel_23/classCGAL_1_1Point__3.html\n// http://doc.cgal.org/latest/Kernel_23/classCGAL_1_1Cartesian.html\n// http://www.cgal.org/FAQ.html\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Delaunay_triangulation_3<K>                   Triangulation;\ntypedef Triangulation::Point                                Point;\n\n\n// these two functions are for my readvtk function.\nTriangulation::Vertex_handle\nadd_vertex(Triangulation &T, std::string& vname, double x, double y, double z)\n{\n  // vertex name doesn't have any meaning in this context.\n  return T.insert(Point(x,y,z));\n}\n\nvoid add_edge(Triangulation &T,\n               Triangulation::Vertex_handle s,\n               Triangulation::Vertex_handle t)\n{\n  // no edges to add. CGAL does that.\n}\n\n#include <readvtk.hxx>\n\n\nint main(int argc,char* argv[])\n{\n\n    namespace po = boost::program_options;\n    po::options_description desc(\"Usage\");\n\n    std::string filename;\n    desc.add_options()\n        (\"help\", \"produce help message\")\n        (\"filename\", po::value<std::string>(&filename)->default_value(\"\"),\n         \"filename containing input points\");\n    \n    po::variables_map opts;\n    po::store(po::parse_command_line(argc, argv, desc), opts);\n\n    try {\n        po::notify(opts);\n    } catch (std::exception& e) {\n        std::cerr << \"Error: \" << e.what() << \"\\n\";\n        return 1;\n    }\n\n    if (filename == \"\") {\n      std::cerr << \"please provide a vtk file with the --filename <file> option\" << std::endl;\n      exit(-1);\n    }\n\n    std::ifstream input(filename.c_str());\n    Triangulation T;\n    \n    /* if you just have a file with a list of points, you can do this:\n       std::list<Point> L;\n       Point p ;\n       Triangulation T;\n       while (input >> p) {\n         T.insert(p);\n         L.push_front(p);\n       }\n       // if you already have a list of points:\n       // Triangulation T(L.begin(), L.end());\n       \n    */\n    \n    readvtk<Triangulation,Triangulation::Vertex_handle>(input, T);\n\n\n    // at this point, the trianulation is already done. Just have to extract\n    // the computed lines.\n    Triangulation::size_type n = T.number_of_vertices();\n\n    assert( T.is_valid() ); // checking validity of T\n\n\n\n    std::cout << \"# vtk DataFile Version 1.0\\n\";\n    std::cout << \"3D triangulation data\\n\";\n    std::cout << \"ASCII\\n\";\n    std::cout << std::endl;\n    std::cout << \"DATASET POLYDATA\\n\";\n\n    // according to http://doc.cgal.org/latest/TDS_3/classTriangulationDataStructure__3.html\n    // Note that the triangulation data structure has one more\n    // vertex than an associated geometric triangulation, if there\n    // is one, since the infinite vertex is a standard vertex and\n    // is thus also counted.\n    // I am omitting this one by using the finite_vertices/edges iterators below\n    int numvertices = T.number_of_vertices();\n    std::cout << \"POINTS \" << numvertices << \" float\\n\";\n\n    // the APIs I'm using below are documented here:\n    // http://doc.cgal.org/latest/Triangulation_3/classCGAL_1_1Triangulation__3.html\n\n    // as I iterate over the vertices, I assign ids to each vertex. Seems like there'd\n    // be an id method, but I haven't found it.\n    std::map<Point, int> vertex_ids;\n    Triangulation::Finite_vertices_iterator viter;\n    for (viter =  T.finite_vertices_begin();\n         viter != T.finite_vertices_end();\n         viter++) {\n      Triangulation::Triangulation_data_structure::Vertex v = *viter;\n      // in the line below, looking up the point (the [] part) will add a new\n      // element to the map. That's why I subtract 1.\n      vertex_ids[v.point()] = vertex_ids.size() - 1;\n      std::cout << v.point() << std::endl;\n    }\n\n    std::cout << \"LINES \" << T.number_of_finite_edges() << \" \"\n              << 3*T.number_of_finite_edges() << std::endl;\n\n    Triangulation::Finite_edges_iterator iter;\n    for(iter =  T.finite_edges_begin();\n        iter != T.finite_edges_end();\n        iter++) {\n      // edges are not represented as edges in CGAL triangulation graphs.\n      // Instead, they are stored in faces/cells.\n\n      Triangulation::Triangulation_data_structure::Edge e = *iter;\n      Triangulation::Triangulation_data_structure::Cell_handle c = e.first;\n      int i = e.second;\n      int j = e.third;\n            \n      Triangulation::Triangulation_data_structure::Vertex_handle a = c->vertex(i);\n      Point pa = a->point();\n      Point pb = c->vertex(j)->point();\n      int ida, idb;\n      if (vertex_ids.find(pa) == vertex_ids.end()) {\n        std::cout << \"didn't find \" << pa << std::endl;\n        ida = 0;\n      } else {\n        ida = vertex_ids[pa];\n      }\n      if (vertex_ids.find(pb) == vertex_ids.end()) {\n        std::cout << \"didn't find \" << pb << std::endl;\n        idb = 0;\n      } else {\n        idb = vertex_ids[pb];\n      }\n      std::cout << \"2 \" << ida << \" \" << idb << std::endl;\n    }\n    \n    return 0;\n}\n\n\n\n", "meta": {"hexsha": "eaf81fab62e3a204a49f26578f8028da4b5dd89a", "size": 5705, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "delaunay/delaunay3d.cxx", "max_stars_repo_name": "mmccoo/nerd_mmccoo", "max_stars_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2017-06-21T07:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T01:39:02.000Z", "max_issues_repo_path": "delaunay/delaunay3d.cxx", "max_issues_repo_name": "zxh1986123/nerd_mmccoo", "max_issues_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-02-08T19:29:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-14T09:27:18.000Z", "max_forks_repo_path": "delaunay/delaunay3d.cxx", "max_forks_repo_name": "zxh1986123/nerd_mmccoo", "max_forks_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-02-12T21:18:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T23:04:51.000Z", "avg_line_length": 32.6, "max_line_length": 94, "alphanum_fraction": 0.6406660824, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5301313222628298}}
{"text": "#include <cmath>\n#include <cstring>\n#include <Eigen/Eigenvalues>\n#include <Eigen/SVD>\n#include <esn/exceptions.hpp>\n#include <esn/network_nsli.h>\n#include <esn/network_nsli.hpp>\n#include <network_nsli.h>\n\nnamespace ESN {\n\n    std::unique_ptr< Network > CreateNetwork(\n        const NetworkParamsNSLI & params )\n    {\n        return std::unique_ptr< NetworkNSLI >( new NetworkNSLI( params ) );\n    }\n\n    NetworkNSLI::NetworkNSLI( const NetworkParamsNSLI & params )\n        : mParams( params )\n        , mIn( params.inputCount )\n        , mWIn( params.neuronCount, params.inputCount )\n        , mWInScaling( params.inputCount )\n        , mWInBias( params.inputCount )\n        , mX( params.neuronCount )\n        , mW( params.neuronCount, params.neuronCount )\n        , mOut( params.outputCount )\n        , mWOut( params.outputCount, params.neuronCount )\n        , mWFB()\n        , mWFBScaling()\n        , mAdaptiveFilter( params.neuronCount,\n            params.onlineTrainingForgettingFactor,\n            params.onlineTrainingInitialCovariance )\n    {\n        if ( params.inputCount <= 0 )\n            throw std::invalid_argument(\n                \"NetworkParamsNSLI::inputCount must be not null\" );\n        if ( params.neuronCount <= 0 )\n            throw std::invalid_argument(\n                \"NetworkParamsNSLI::neuronCount must be not null\" );\n        if ( params.outputCount <= 0 )\n            throw std::invalid_argument(\n                \"NetworkParamsNSLI::outputCount must be not null\" );\n        if ( !( params.leakingRateMin > 0.0 &&\n                params.leakingRateMin <= 1.0 ) )\n            throw std::invalid_argument(\n                \"NetworkParamsNSLI::leakingRateMin must be within \"\n                \"interval (0,1]\" );\n        if ( !( params.leakingRateMax > 0.0 &&\n                params.leakingRateMax <= 1.0 ) )\n            throw std::invalid_argument(\n                \"NetworkParamsNSLI::leakingRateMax must be within \"\n                \"interval (0,1]\" );\n        if ( params.leakingRateMin > params.leakingRateMax )\n            throw std::invalid_argument(\n                \"NetworkParamsNSLI::leakingRateMin must be less then or \"\n                \"equal to NetworkParamsNSLI::leakingRateMax\" );\n        if ( !( params.connectivity > 0.0f &&\n                params.connectivity <= 1.0f ) )\n            throw std::invalid_argument(\n                \"NetworkParamsNSLI::connectivity must be within \"\n                \"interval (0,1]\" );\n\n        mWIn = Eigen::MatrixXf::Random(\n            params.neuronCount, params.inputCount );\n\n        Eigen::MatrixXf randomWeights =\n            ( Eigen::MatrixXf::Random( params.neuronCount,\n                params.neuronCount ).array().abs()\n                    <= params.connectivity ).cast< float >() *\n            Eigen::MatrixXf::Random( params.neuronCount,\n                params.neuronCount ).array();\n        if ( params.useOrthonormalMatrix )\n        {\n            auto svd = randomWeights.jacobiSvd(\n                Eigen::ComputeFullU | Eigen::ComputeFullV );\n            mW = ( svd.matrixU() * svd.matrixV() ).sparseView();\n        }\n        else\n        {\n            float spectralRadius =\n                randomWeights.eigenvalues().cwiseAbs().maxCoeff();\n            mW = ( randomWeights / spectralRadius *\n                params.spectralRadius ).sparseView() ;\n        }\n\n        mWInScaling = Eigen::VectorXf::Constant( params.inputCount, 1.0f );\n        mWInBias = Eigen::VectorXf::Zero( params.inputCount );\n\n        mWOut = Eigen::MatrixXf::Zero(\n            params.outputCount, params.neuronCount );\n\n        if (params.hasOutputFeedback)\n        {\n            mWFB = Eigen::MatrixXf::Random(\n                params.neuronCount, params.outputCount);\n            mWFBScaling = Eigen::VectorXf::Constant(\n                params.outputCount, 1.0f);\n        }\n\n        mLeakingRate = ( Eigen::ArrayXf::Random( params.neuronCount ) *\n            ( mParams.leakingRateMax - mParams.leakingRateMin ) +\n            ( mParams.leakingRateMin + mParams.leakingRateMax ) ) / 2.0f;\n        mOneMinusLeakingRate = 1.0f - mLeakingRate.array();\n\n        mIn = Eigen::VectorXf::Zero( params.inputCount );\n        mX = Eigen::VectorXf::Random( params.neuronCount );\n        mOut = Eigen::VectorXf::Zero( params.outputCount );\n    }\n\n    NetworkNSLI::~NetworkNSLI()\n    {\n    }\n\n    void NetworkNSLI::SetInputs( const std::vector< float > & inputs )\n    {\n        if ( inputs.size() != mIn.rows() )\n            throw std::invalid_argument( \"Wrong size of the input vector\" );\n        mIn = (Eigen::Map<Eigen::VectorXf>(\n            const_cast<float*>(inputs.data()), inputs.size()) +\n            mWInBias).cwiseProduct(mWInScaling);\n    }\n\n    void NetworkNSLI::SetInputScalings(\n        const std::vector< float > & scalings )\n    {\n        if ( scalings.size() != mParams.inputCount )\n            throw std::invalid_argument(\n                \"Wrong size of the scalings vector\" );\n        mWInScaling = Eigen::Map< Eigen::VectorXf >(\n            const_cast< float * >( scalings.data() ), scalings.size() );\n    }\n\n    void NetworkNSLI::SetInputBias(\n        const std::vector< float > & bias )\n    {\n        if ( bias.size() != mParams.inputCount )\n            throw std::invalid_argument(\n                \"Wrong size of the scalings vector\" );\n        mWInBias = Eigen::Map< Eigen::VectorXf >(\n            const_cast< float * >( bias.data() ), bias.size() );\n    }\n\n    void NetworkNSLI::SetFeedbackScalings(\n        const std::vector< float > & scalings )\n    {\n        if (!mParams.hasOutputFeedback)\n            throw std::logic_error(\n                \"Trying to set up feedback scaling for a network \"\n                \"which doesn't have an output feedback\");\n        if ( scalings.size() != mParams.outputCount )\n            throw std::invalid_argument(\n                \"Wrong size of the scalings vector\" );\n        mWFBScaling = Eigen::Map< Eigen::VectorXf >(\n            const_cast< float * >( scalings.data() ), scalings.size() );\n    }\n\n    void NetworkNSLI::Step( float step )\n    {\n        if ( step <= 0.0f )\n            throw std::invalid_argument(\n                \"Step size must be positive value\" );\n\n        auto tanh = [] ( float x ) -> float { return std::tanh( x ); };\n\n        #define TEMP mWIn * mIn + mW * mX\n\n        #define CALC_X(val) \\\n            mX = mOneMinusLeakingRate.cwiseProduct(mX) + \\\n                mLeakingRate.cwiseProduct(val).unaryExpr(tanh)\n\n        #define CALC_X_WITH_FB(val) \\\n            if (mParams.hasOutputFeedback) \\\n                CALC_X(TEMP + val); \\\n            else \\\n                CALC_X(TEMP)\n\n        if ( mParams.linearOutput )\n        {\n            CALC_X_WITH_FB(\n                mWFB * mOut.unaryExpr(tanh).cwiseProduct(mWFBScaling));\n            mOut = mWOut * mX;\n        }\n        else\n        {\n            CALC_X_WITH_FB(\n                mWFB * mOut.cwiseProduct(mWFBScaling));\n            mOut = ( mWOut * mX ).unaryExpr( tanh );\n        }\n\n        #undef TEMP\n        #undef CALC_X\n        #undef CALC_X_WITH_FB\n\n        auto isnotfinite =\n            [] (float n) -> bool { return !std::isfinite(n); };\n        if (mOut.unaryExpr(isnotfinite).any())\n            throw OutputIsNotFinite();\n    }\n\n    void NetworkNSLI::CaptureTransformedInput(\n        std::vector< float > & input )\n    {\n        if ( input.size() != mParams.inputCount )\n            throw std::invalid_argument(\n                \"Size of the vector must be equal to \"\n                \"the number of inputs\" );\n        for ( int i = 0; i < mParams.inputCount; ++ i )\n            input[ i ] = mIn( i );\n    }\n\n    void NetworkNSLI::CaptureActivations(\n        std::vector< float > & activations )\n    {\n        if ( activations.size() != mParams.neuronCount )\n            throw std::invalid_argument(\n                \"Size of the vector must be equal \"\n                \"actual number of neurons\" );\n\n        for ( int i = 0; i < mParams.neuronCount; ++ i )\n            activations[ i ] = mX( i );\n    }\n\n    void NetworkNSLI::CaptureOutput( std::vector< float > & output )\n    {\n        if ( output.size() != mParams.outputCount )\n            throw std::invalid_argument(\n                \"Size of the vector must be equal \"\n                \"actual number of outputs\" );\n\n        for ( int i = 0; i < mParams.outputCount; ++ i )\n            output[ i ] = mOut( i );\n    }\n\n    void NetworkNSLI::Train(\n        const std::vector< std::vector< float > > & inputs,\n        const std::vector< std::vector< float > > & outputs )\n    {\n        if ( inputs.size() == 0 )\n            throw std::invalid_argument(\n                \"Number of samples must be not null\" );\n        if ( inputs.size() != outputs.size() )\n            throw std::invalid_argument(\n                \"Number of input and output samples must be equal\" );\n        const unsigned kSampleCount = inputs.size();\n\n        Eigen::MatrixXf matX( mParams.neuronCount, kSampleCount );\n        Eigen::MatrixXf matY( mParams.outputCount, kSampleCount );\n        for ( int i = 0; i < kSampleCount; ++ i )\n        {\n            SetInputs( inputs[i] );\n            Step( 0.1f );\n            matX.col( i ) = mX;\n            matY.col( i ) = Eigen::Map< Eigen::VectorXf >(\n                const_cast< float * >( outputs[i].data() ),\n                    mParams.outputCount );\n        }\n\n        Eigen::MatrixXf matXT = matX.transpose();\n\n        mWOut = ( matY * matXT * ( matX * matXT ).inverse() );\n    }\n\n    void NetworkNSLI::TrainOnline( const std::vector< float > & output,\n        bool forceOutput )\n    {\n        for ( unsigned i = 0; i < mParams.outputCount; ++ i )\n        {\n            Eigen::VectorXf w = mWOut.row( i ).transpose();\n            if ( mParams.linearOutput )\n                mAdaptiveFilter.Train( w, mOut( i ), output[i], mX );\n            else\n                mAdaptiveFilter.Train( w, std::atanh( mOut( i ) ),\n                    std::atanh( output[i] ), mX );\n            mWOut.row( i ) = w.transpose();\n        }\n\n        if ( forceOutput )\n            mOut = Eigen::Map< Eigen::VectorXf >(\n                const_cast< float * >( output.data() ),\n                mParams.outputCount );\n    }\n\n} // namespace ESN\n\n#define SIZEOF_MEMBER( structure, member ) \\\n    sizeof( ( ( structure * ) 0 )->member )\n\nvoid * esnCreateNetworkNSLI( esnNetworkParamsNSLI * params )\n{\n    static_assert( ( sizeof( esnNetworkParamsNSLI ) -\n        SIZEOF_MEMBER( esnNetworkParamsNSLI, structSize ) ) ==\n        sizeof( ESN::NetworkParamsNSLI ),\n        \"Wrong size of esnNetworkParamsNSLI\" );\n\n    if ( params->structSize != sizeof( esnNetworkParamsNSLI ) )\n        throw std::invalid_argument(\n            \"esnNetworkParamsNSLI::structSize must be equal the \"\n            \"sizeof( esnNetworkParamsNSLI )\" );\n\n    ESN::NetworkParamsNSLI p;\n    std::memcpy( &p, reinterpret_cast< char * >( params ) +\n        SIZEOF_MEMBER( esnNetworkParamsNSLI, structSize ),\n        sizeof( ESN::NetworkParamsNSLI ) );\n\n    return new ESN::NetworkNSLI( p );\n}\n\n#undef SIZEOF_MEMBER\n", "meta": {"hexsha": "9bf9f041334556fbe3e13f1b6be4ccb7faf302cc", "size": 11025, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/network_nsli.cpp", "max_stars_repo_name": "mode89/esn", "max_stars_repo_head_hexsha": "6de28a79ac264401c066f87922226dda70fadbdd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-02-17T23:10:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T00:09:33.000Z", "max_issues_repo_path": "source/network_nsli.cpp", "max_issues_repo_name": "mode89/esn", "max_issues_repo_head_hexsha": "6de28a79ac264401c066f87922226dda70fadbdd", "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/network_nsli.cpp", "max_forks_repo_name": "mode89/esn", "max_forks_repo_head_hexsha": "6de28a79ac264401c066f87922226dda70fadbdd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-28T12:20:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-28T12:20:03.000Z", "avg_line_length": 35.6796116505, "max_line_length": 76, "alphanum_fraction": 0.5542857143, "num_tokens": 2745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5300956896027217}}
{"text": "#ifndef STACK_HH\n#define STACK_HH\n\n// 2020: Changes by Benjamin Huth\n// - templated all classes\n\n\n// StackT classes\n//\n// These are the low-level classes that implement feed-forward and\n// recurrent neural networks. All the Eigen-dependant code in this\n// library should live in this file.\n//\n// To keep the Eigen code out of the high-level interface, the STL ->\n// Eigen ``preprocessor'' classes are also defined here.\n//\n// The ordering of classes is as follows:\n//  - Feed-forward Stack class\n//  - Feed-forward Layer classes\n//  - RecurrentStackT class\n//  - Recurrent layers\n//  - Activation functions\n//  - Various utility functions\n\n\n#include \"Exceptions.hh\"\n#include \"NNLayerConfig.hh\"\n\n#include <Eigen/Dense>\n\n#include <vector>\n#include <functional>\n\nnamespace lwt {\n\n  template<typename T>\n  using VectorX = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n  \n  template<typename T>\n  using MatrixX = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n  \n  template<typename T>\n  using ArrayX = Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic>;\n\n  template<typename T>\n  class ILayerT;\n  \n  template<typename T>\n  class IRecurrentLayerT;\n\n  class FittableLWTNN;\n  \n  // ______________________________________________________________________\n  // Feed forward Stack class\n\n  template<typename T>\n  class StackT\n  {\n    friend class FittableLWTNN;\n      \n  public:\n    // constructor for dummy net\n    StackT();\n    // constructor for real net\n    StackT(size_t n_inputs, const std::vector<LayerConfig>& layers,\n          size_t skip_layers = 0);\n    ~StackT();\n\n    // make non-copyable for now\n    StackT(StackT&) = delete;\n    StackT& operator=(StackT&) = delete;\n\n    VectorX<T> compute(VectorX<T>) const;\n    size_t n_outputs() const;\n\n  private:\n    // returns the size of the next layer\n    size_t add_layers(size_t n_inputs, const LayerConfig&);\n    size_t add_dense_layers(size_t n_inputs, const LayerConfig&);\n    size_t add_normalization_layers(size_t n_inputs, const LayerConfig&);\n    size_t add_highway_layers(size_t n_inputs, const LayerConfig&);\n    size_t add_maxout_layers(size_t n_inputs, const LayerConfig&);\n    std::vector<ILayerT<T>*> m_layers;\n    size_t m_n_outputs;\n  };\n  \n  using Stack = StackT<double>;\n\n  // _______________________________________________________________________\n  // Feed-forward layers\n\n  template<typename T>\n  class ILayerT\n  {\n  public:\n    virtual ~ILayerT() {}\n    virtual VectorX<T> compute(const VectorX<T>&) const = 0;\n  };\n  \n  using ILayer = ILayerT<double>;\n\n  template<typename T>\n  class DummyLayerT: public ILayerT<T>\n  {\n  public:\n    virtual VectorX<T> compute(const VectorX<T>&) const override;\n  };\n  \n  using DummyLayer = DummyLayerT<double>;\n\n  template<typename T>\n  class UnaryActivationLayerT: public ILayerT<T>\n  {\n  public:\n    UnaryActivationLayerT(ActivationConfig);\n    virtual VectorX<T> compute(const VectorX<T>&) const override;\n  private:\n    std::function<T(T)> m_func;\n  };\n  \n  using UnaryActivationLayer = UnaryActivationLayerT<double>;\n\n  template<typename T>\n  class SoftmaxLayerT: public ILayerT<T>\n  {\n  public:\n    virtual VectorX<T> compute(const VectorX<T>&) const override;\n  };\n  \n  using SoftmaxLayer = SoftmaxLayerT<double>;\n\n  template<typename T>\n  class BiasLayerT: public ILayerT<T>\n  {\n    friend class FittableLWTNN;\n    \n  public:\n    BiasLayerT(const VectorX<T>& bias);\n    template<typename U> BiasLayerT(const std::vector<U>& bias);\n    virtual VectorX<T> compute(const VectorX<T>&) const override;\n  private:\n    VectorX<T> m_bias;\n  };\n  \n  using BiasLayer = BiasLayerT<double>;\n\n  template<typename T>\n  class MatrixLayerT: public ILayerT<T>\n  {\n    friend class FittableLWTNN;\n    \n  public:\n    MatrixLayerT(const MatrixX<T>& matrix);\n    virtual VectorX<T> compute(const VectorX<T>&) const override;\n  private:\n    MatrixX<T> m_matrix;\n  };\n  \n  using MatrixLayer = MatrixLayerT<double>;\n\n  template<typename T>\n  class MaxoutLayerT: public ILayerT<T>\n  {\n    friend class FittableLWTNN;\n    \n  public:\n    typedef std::pair<MatrixX<T>, VectorX<T>> InitUnit;\n    MaxoutLayerT(const std::vector<InitUnit>& maxout_tensor);\n    virtual VectorX<T> compute(const VectorX<T>&) const override;\n  private:\n    std::vector<MatrixX<T>> m_matrices;\n    MatrixX<T> m_bias;\n  };\n  \n  using MaxoutLayer = MaxoutLayerT<double>;\n\n\n  /// Normalization layer ///\n  /// https://arxiv.org/abs/1502.03167 ///\n  template<typename T>\n  class NormalizationLayerT : public ILayerT<T>\n  {\n    friend class FittableLWTNN;\n    \n  public:\n    NormalizationLayerT(const VectorX<T>& W,const VectorX<T>& b);\n    virtual VectorX<T> compute(const VectorX<T>&) const override;\n\n  private:\n    VectorX<T> _W;\n    VectorX<T> _b;\n\n  };\n  \n  using NormalizationLayer = NormalizationLayerT<double>;\n\n  //http://arxiv.org/pdf/1505.00387v2.pdf\n  template<typename T>\n  class HighwayLayerT: public ILayerT<T>\n  {\n    friend class FittableLWTNN;\n    \n  public:\n    HighwayLayerT(const MatrixX<T>& W,\n                 const VectorX<T>& b,\n                 const MatrixX<T>& W_carry,\n                 const VectorX<T>& b_carry,\n                 ActivationConfig activation);\n    virtual VectorX<T> compute(const VectorX<T>&) const override;\n  private:\n    MatrixX<T> m_w_t;\n    VectorX<T> m_b_t;\n    MatrixX<T> m_w_c;\n    VectorX<T> m_b_c;\n    std::function<T(T)> m_act;\n  };\n  \n  using HighwayLayer = HighwayLayerT<double>;\n\n  // ______________________________________________________________________\n  // Recurrent StackT\n\n  template<typename T>\n  class RecurrentStackT\n  {\n  public:\n    RecurrentStackT(size_t n_inputs, const std::vector<LayerConfig>& layers);\n    ~RecurrentStackT();\n    RecurrentStackT(RecurrentStackT&) = delete;\n    RecurrentStackT& operator=(RecurrentStackT&) = delete;\n    MatrixX<T> scan(MatrixX<T> inputs) const;\n    size_t n_outputs() const;\n  private:\n    std::vector<IRecurrentLayerT<T>*> m_layers;\n    size_t add_lstm_layers(size_t n_inputs, const LayerConfig&);\n    size_t add_gru_layers(size_t n_inputs, const LayerConfig&);\n    size_t add_embedding_layers(size_t n_inputs, const LayerConfig&);\n    size_t m_n_outputs;\n  };\n  \n  using RecurrentStack = RecurrentStackT<double>;\n\n  // This is the old RecurrentStack. Should probably absorb this into\n  // the high-level interface in LightweightRNN, since all it does is\n  // provide a slightly higher-level interface to a network which\n  // combines recurrent + ff layers.\n  template<typename T>\n  class ReductionStackT\n  {\n  public:\n    ReductionStackT(size_t n_in, const std::vector<LayerConfig>& layers);\n    ~ReductionStackT();\n    ReductionStackT(ReductionStackT&) = delete;\n    ReductionStackT& operator=(ReductionStackT&) = delete;\n    VectorX<T> reduce(MatrixX<T> inputs) const;\n    size_t n_outputs() const;\n  private:\n    RecurrentStackT<T>* m_recurrent;\n    StackT<T>* m_stack;\n  };\n  \n  using ReductionStack = ReductionStackT<double>;\n\n  // __________________________________________________________________\n  // Recurrent layers\n\n  template<typename T>\n  class IRecurrentLayerT\n  {\n  public:\n    virtual ~IRecurrentLayerT() {}\n    virtual MatrixX<T> scan( const MatrixX<T>&) const = 0;\n  };\n  \n  using IRecurrentLayer = IRecurrentLayerT<double>;\n  \n  template<typename T>\n  class EmbeddingLayerT : public IRecurrentLayerT<T>\n  {\n  public:\n    EmbeddingLayerT(int var_row_index, MatrixX<T> W);\n    virtual ~EmbeddingLayerT() {};\n    virtual MatrixX<T> scan( const MatrixX<T>&) const override;\n\n  private:\n    int m_var_row_index;\n    MatrixX<T> m_W;\n  };\n  \n  using EmbeddingLayer = EmbeddingLayerT<double>;\n\n  /// long short term memory ///\n  template<typename T> struct LSTMStateT;\n  using LSTMState = LSTMStateT<double>;\n  \n  template<typename T>\n  class LSTMLayerT : public IRecurrentLayerT<T>\n  {\n  public:\n    LSTMLayerT(ActivationConfig activation,\n              ActivationConfig inner_activation,\n              MatrixX<T> W_i, MatrixX<T> U_i, VectorX<T> b_i,\n              MatrixX<T> W_f, MatrixX<T> U_f, VectorX<T> b_f,\n              MatrixX<T> W_o, MatrixX<T> U_o, VectorX<T> b_o,\n              MatrixX<T> W_c, MatrixX<T> U_c, VectorX<T> b_c);\n\n    virtual ~LSTMLayerT() {};\n    virtual MatrixX<T> scan( const MatrixX<T>&) const override;\n    void step( const VectorX<T>& input, LSTMState& ) const;\n\n  private:\n    std::function<T(T)> m_activation_fun;\n    std::function<T(T)> m_inner_activation_fun;\n\n    MatrixX<T> m_W_i;\n    MatrixX<T> m_U_i;\n    VectorX<T> m_b_i;\n\n    MatrixX<T> m_W_f;\n    MatrixX<T> m_U_f;\n    VectorX<T> m_b_f;\n\n    MatrixX<T> m_W_o;\n    MatrixX<T> m_U_o;\n    VectorX<T> m_b_o;\n\n    MatrixX<T> m_W_c;\n    MatrixX<T> m_U_c;\n    VectorX<T> m_b_c;\n\n    int m_n_outputs;\n  };\n  \n  using LSTMLayer = LSTMLayerT<double>;\n\n  /// gated recurrent unit ///\n  template<typename T> struct GRUStateT;\n  using GRUState = GRUStateT<double>;\n  \n  template<typename T>\n  class GRULayerT : public IRecurrentLayerT<T>\n  {\n  public:\n    GRULayerT(ActivationConfig activation,\n             ActivationConfig inner_activation,\n             MatrixX<T> W_z, MatrixX<T> U_z, VectorX<T> b_z,\n             MatrixX<T> W_r, MatrixX<T> U_r, VectorX<T> b_r,\n             MatrixX<T> W_h, MatrixX<T> U_h, VectorX<T> b_h);\n\n    virtual ~GRULayerT() {};\n    virtual MatrixX<T> scan( const MatrixX<T>&) const override;\n    void step( const VectorX<T>& input, GRUState& ) const;\n\n  private:\n    std::function<T(T)> m_activation_fun;\n    std::function<T(T)> m_inner_activation_fun;\n\n    MatrixX<T> m_W_z;\n    MatrixX<T> m_U_z;\n    VectorX<T> m_b_z;\n\n    MatrixX<T> m_W_r;\n    MatrixX<T> m_U_r;\n    VectorX<T> m_b_r;\n\n    MatrixX<T> m_W_h;\n    MatrixX<T> m_U_h;\n    VectorX<T> m_b_h;\n\n    int m_n_outputs;\n  };\n  \n  using GRULayer = GRULayerT<double>;\n\n  // ______________________________________________________________________\n  // Activation functions\n\n  // note that others are supported but are too simple to\n  // require a special function\n  template<typename T> T nn_sigmoidT( T x );\n  template<typename T> T nn_hard_sigmoidT( T x );\n  template<typename T> T nn_tanhT( T x );\n  template<typename T> T nn_reluT( T x );\n  \n  double nn_sigmoid( double x );\n  double nn_hard_sigmoid( double x );\n  double nn_tanh( double x );\n  double nn_relu( double x );\n  \n  template<typename T>\n  class ELUT\n  {\n  public:\n    ELUT(T alpha);\n    T operator()(T) const;\n  private:\n    T m_alpha;\n  };\n  \n  using ELU = ELUT<double>;\n  \n  template<typename T>\n  class LeakyReLUT\n  {\n  public:\n    LeakyReLUT(T alpha);\n    T operator()(T) const;\n  private:\n    T m_alpha;\n  };\n  \n  using LeakyReLU = LeakyReLUT<double>;\n  \n  template<typename T>\n  class SwishT\n  {\n  public:\n    SwishT(T alpha);\n    T operator()(T) const;\n  private:\n    T m_alpha;\n  };\n  \n  using Swish = SwishT<double>;\n  \n  template<typename T> std::function<T(T)> get_activationT(lwt::ActivationConfig);\n  std::function<double(double)> get_activation(lwt::ActivationConfig);\n\n  // WARNING: you own this pointer! Only call when assigning to member data!\n  template<typename T> ILayerT<T>* get_raw_activation_layerT(ActivationConfig);\n  ILayer* get_raw_activation_layer(ActivationConfig);\n  \n\n  // ______________________________________________________________________\n  // utility functions\n\n  // functions to build up basic units from vectors\n  template<typename T1, typename T2> MatrixX<T1> build_matrixT(const std::vector<T2>& weights, size_t n_inputs);\n  template<typename T1, typename T2> VectorX<T1> build_vectorT(const std::vector<T2>& bias);\n  \n  MatrixX<double> build_matrix(const std::vector<double>& weights, size_t n_inputs);\n  VectorX<double> build_vector(const std::vector<double>& bias);\n\n  // consistency checks\n  void throw_if_not_maxout(const LayerConfig& layer);\n  void throw_if_not_dense(const LayerConfig& layer);\n  void throw_if_not_normalization(const LayerConfig& layer);\n\n  // LSTM component for convenience in some layers\n  template<typename T>\n  struct DenseComponentsT\n  {\n    MatrixX<T> W;\n    MatrixX<T> U;\n    VectorX<T> b;\n  };\n  \n  using DenseComponents = DenseComponentsT<double>;\n  \n  template<typename T> DenseComponentsT<T> get_componentT(const lwt::LayerConfig& layer, size_t n_in);\n  DenseComponents get_component(const lwt::LayerConfig& layer, size_t n_in);\n}\n\n#include \"Stack.txx\"\n\n#endif // STACK_HH\n", "meta": {"hexsha": "f51a1a98166e541d3eef145d1a82026fb2d69b3b", "size": 12245, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/lwtnn/Stack.hh", "max_stars_repo_name": "benjaminhuth/lwtnn", "max_stars_repo_head_hexsha": "7bfa3f3895dd0f8ddee2ca83120a0549b3174bca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-25T22:16:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-25T22:16:47.000Z", "max_issues_repo_path": "include/lwtnn/Stack.hh", "max_issues_repo_name": "benjaminhuth/lwtnn", "max_issues_repo_head_hexsha": "7bfa3f3895dd0f8ddee2ca83120a0549b3174bca", "max_issues_repo_licenses": ["MIT"], "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/lwtnn/Stack.hh", "max_forks_repo_name": "benjaminhuth/lwtnn", "max_forks_repo_head_hexsha": "7bfa3f3895dd0f8ddee2ca83120a0549b3174bca", "max_forks_repo_licenses": ["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.2205567452, "max_line_length": 112, "alphanum_fraction": 0.6919559004, "num_tokens": 3271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5300900295433293}}
{"text": "#ifndef _HOMOMORPHINE_SEAL_BACKED_H_\n#define _HOMOMORPHINE_SEAL_BACKED_H_\n\n#include <iostream>\n#include <utility>\n#include <sstream>\n#include <string>\n#include <math.h>\n#include <seal/seal.h>\n#include <boost/log/trivial.hpp>\n#include <boost/log/utility/setup.hpp>\n\n#include \"util.hpp\"\n#include \"backend.hpp\"\n#include \"arithmetic_backend.hpp\"\n#include \"constants.hpp\"\n\nusing namespace seal;\nusing namespace std;\nusing namespace boost::archive::iterators;\n\nnamespace homomorphine \n{\n  \n  //! SEAL algorithms \n  enum class SealAlgorithm { \n    BFV,     /*!< SEAL BFV backend */\n    CKKS,    /*!< SEAL CKKS backend */\n    UNKNOWN  /*!< Unknown algorithm type - usually an error */\n  }; \n\n  /*! /brief SEAL backend\n   *\n   * This class is an implementation of the SEAL backend.\n   */\n  class SealBackend : public ArithmeticBackend\n  {\n    private:\n      std::shared_ptr<SEALContext> context;               /*!< SEAL context object */\n      KeyGenerator *keygen = nullptr;                     /*!< SEAL key generator */\n      SealAlgorithm algorithm;                            /*!< SEAL algorithm type (BFV, or CKKS) */\n      EncryptionParameters *encryption_params = nullptr;  /*!< SEAL specific encryption parameters */\n      PublicKey public_key;                               /*!< SEAL public key */\n      SecretKey secret_key;                               /*!< SEAL secret key */\n      RelinKeys relin_keys;                               /*!< SEAL relinearization keys */\n      Ciphertext cipher;                                  /*!< cipher */\n      double scale;                                       /*!< bit-precision of encoding, used by CKKS encryption implementation */\n\n      /*!\n       * Get SEAL algorithm type from algorithm name\n       * \n       * \\param name algorithm name\n       * \\return algorithm type\n       */\n      SealAlgorithm getAlgorithmType(string name);\n\n      /*!\n       * Initialize BFV specific stuff of SEAL backend\n       */\n      void initBFV();  \n\n      /*!\n       * Initialize CKKS specific stuff of SEAL backend\n       */\n      void initCKKS();  \n\n      /*!\n       * Encode vector of values using BFV algorithm\n       * \n       * \\param values vector of values\n       * \\return plaintext representation of values\n       */\n      Plaintext encodeWithBFV(vector<long> values);\n\n      /*!\n       * Encode single value using BFV algorithm\n       * \n       * \\param value value\n       * \\return plaintext representation of value\n       */\n      Plaintext encodeWithBFV(long value);\n\n      /*!\n       * Encode vector of values using CKKS algorithm\n       * \n       * \\param values vector of values\n       * \\return plaintext representation of values\n       */\n      Plaintext encodeWithCKKS(vector<long> values);\n\n      /*!\n       * Encode single value using CKKS algorithm\n       * \n       * \\param value value\n       * \\return plaintext representation of value\n       */\n      Plaintext encodeWithCKKS(long value);\n\n      /*!\n       * Decode value from plaintext using BFV algorithm\n       * \n       * \\param plain_result plaintext representation of value\n       * \\return value\n       */\n      long decodeWithBFV(Plaintext plain_result);\n\n      /*!\n       * Decode vector of values from plaintext using BFV algorithm\n       * \n       * \\param plain_result plaintext representation of value\n       * \\return value\n       */\n      vector<long> decodeValuesWithBFV(Plaintext plain_result);\n\n      /*!\n       * Decode value from plaintext using CKKS algorithm\n       * \n       * \\param plain_result plaintext representation of value\n       * \\return vector of values\n       */\n      long decodeWithCKKS(Plaintext plain_result);\n\n      /*!\n       * Decode vector of value from plaintext using CKKS algorithm\n       * \n       * \\param plain_result plaintext representation of value\n       * \\return vector of values\n       */\n      vector<long> decodeValuesWithCKKS(Plaintext plain_result);\n\n    public:\n\n      /*! \n       * SEAL backend cleanup\n       */\n      ~SealBackend();\n\n      /*!\n       * Initializes the SEAL backend\n       */\n      void init();\n\n      /*! \n       * Sets the specific SEAL algorithm implementation\n       * that backend provides (currently, BFV and CKKS)\n       * \n       * \\param algorithm homomorphic encryption algorithm\n       */\n      void setAlgorithm(string algorithm);\n\n      /*! \n       * Sets the specific SEAL algorithm implementation\n       * that backend provides using the name of algorithm\n       * \n       * \\param algorithm homomorphic encryption algorithm\n       */\n      void setAlgorithm(SealAlgorithm algorithm);\n\n      /*!\n       * Generates the public/secret key pair\n       */\n      void generateKeys();\n\n      /*!\n       * Returns the UUEncoded public key\n       * \n       * \\return public key\n       */\n      string getPublicKey();\n\n      /*!\n       * Writes the public key to a stream\n       * \n       * \\param stream public key stream\n       */\n      void writePublicKeyToStream(ostream& stream);\n\n      /*!\n       * Returns the UUEncoded secret key\n       * \n       * \\return secret key\n       */\n      string getSecretKey();\n\n      /*!\n       * Writes the secret key to a stream\n       * \n       * \\param stream secret key stream\n       */\n      void writeSecretKeyToStream(ostream& stream);\n\n      /*!\n       * Returns the pair of UUEncoded public and secret keys\n       * \n       * \\return pair of public and secret keys\n       */\n      pair<string, string> getKeys();\n\n      /*!\n       * Sets the public key \n       * \n       * \\param public_key UUEncoded public key\n       */\n      void setPublicKey(string public_key);\n\n      /*!\n       * Sets the public key from stream\n       * \n       * \\param stream public key binary stream\n       */\n      void readPublicKeyFromStream(istream &stream);\n\n      /*!\n       * Sets the secret key \n       * \n       * \\param secret_key UUEncoded secret key\n       */\n      void setSecretKey(string secret_key);\n\n      /*!\n       * Sets the secret key from stream\n       * \n       * \\param stream secret key binary stream\n       */\n      void readSecretKeyFromStream(istream &stream);\n\n      /*!\n       * Sets the both public and secret keys \n       * \n       * \\param public_key UUEncoded public key\n       * \\param secret_key UUEncoded secret key\n       */\n      void setKeys(string public_key, string secret_key);\n\n       /*!\n       * Returns the UUEncoded cipher containing ecrypted value, or vector of values\n       * \n       * \\return UUEncoded cipher\n       */\n      string getCipher();\n\n      /*!\n       * Writes the cipher to output stream\n       * \n       * \\param stream output stream\n       */\n      void writeCipherToStream(ostream& stream);\n\n      /*!\n       * Sets the UUEncoded cipher containing ecrypted value, or vector of values\n       * \n       * \\param cipher UUEncoded cipher\n       */\n      void setCipher(string cipher);\n\n      /*!\n       * Reads the cipher from input stream\n       * \n       * \\param stream cipher stream\n       */\n      void readCipherFromStream(istream &stream);\n\n      /*!\n       * Encrypts the vector of values using the public key\n       * \n       * \\param values vector of values\n       * \\return UUEncoded cipher\n       */\n      void encrypt(vector<long> values);\n\n      /*!\n       * Encrypts the single value using the public key\n       * \n       * \\param value value\n       * \\return UUEncoded cipher\n       */\n      void encrypt(long value);\n\n      /*!\n       * Decrypts the vector of values using the secret key\n       * \n       * \\return vector of decrypted values\n       */\n      vector<long> decryptValues();\n\n      /*!\n       * Decrypts the single value using the secret key\n       * \n       * \\return decrypted value\n       */\n      long decrypt();\n\n      /*!\n       * Adds the vector of values to encrypted vector of values\n       * \n       * \\param values vector of values\n       */\n      void add(vector<long> values);\n\n      /*!\n       * Adds the value to encrypted value\n       * \n       * \\param value value\n       */\n      void add(long value);\n\n      /*!\n       * Negates a single encrypted value, or a vector of encrypted values\n       */\n      void negate();\n\n      /*!\n       * Multiplies the vector of values with the encrypted vector of values\n       * \n       * \\param values vector of values\n       */\n      void multiply(vector<long> values);\n\n      /*!\n       * Multiplies the value with the encrypted value\n       * \n       * \\param value value\n       */\n      void multiply(long value);\n  };\n}\n\n#endif", "meta": {"hexsha": "6322939d2313673921f6ae4af5aa5e9c17466d2b", "size": 8500, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "native/src/seal_backend.hpp", "max_stars_repo_name": "caboom/homomorphine", "max_stars_repo_head_hexsha": "2284af18dc731acc4154747c5d441dadd85c224e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-23T10:02:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-03T09:22:31.000Z", "max_issues_repo_path": "native/src/seal_backend.hpp", "max_issues_repo_name": "caboom/homomorphine", "max_issues_repo_head_hexsha": "2284af18dc731acc4154747c5d441dadd85c224e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-07T16:26:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-07T16:26:07.000Z", "max_forks_repo_path": "native/src/seal_backend.hpp", "max_forks_repo_name": "caboom/homomorphine", "max_forks_repo_head_hexsha": "2284af18dc731acc4154747c5d441dadd85c224e", "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.9146341463, "max_line_length": 131, "alphanum_fraction": 0.5704705882, "num_tokens": 1817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5300852052304216}}
{"text": "#include \"quadrature/angular/level_symmetric_gaussian.h\"\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/quadrature_lib.h>\n\nnamespace bart {\n\nnamespace quadrature {\n\nnamespace angular {\n\nLevelSymmetricGaussian::LevelSymmetricGaussian(bart::quadrature::Order order)\n    : order_(order.get()) {\n  AssertThrow(order_ >= 2,\n              dealii::ExcMessage(\"Error in constructor of \"\n                                 \"LevelSymmetricGaussian order must be >= 2\"))\n  AssertThrow(order_ % 2 == 0,\n              dealii::ExcMessage(\"Error in constructor of \"\n                                 \"LevelSymmetricGaussian order must be even\"))\n  AssertThrow(order_ <= 16,\n              dealii::ExcMessage(\"Error in constructor of \"\n                                 \"LevelSymmetricGaussian order must be <= 16\"))\n}\n\nstd::vector<std::pair<CartesianPosition<3>, Weight>>\nLevelSymmetricGaussian::GenerateSet() const {\n  std::vector<std::pair<CartesianPosition<3>, Weight>> generated_set;\n  const int n_points = order_/2;\n\n  // Gaussian quadrature for theta, the lowest level has order_ points but we\n  // will only use half of the quadrature\n  dealii::QGauss<1> gaussian_quadrature(order_);\n\n  // For each quadrature point in the lowest level, we will create equally\n  // spaced points in phi\n  for (int level = 0; level < n_points; ++level) {\n    int n_points_this_level = level + 1;\n    // mu is just the gaussian quadrature point\n    double mu = 1 - gaussian_quadrature.point(level)[0] * 2;\n    // points in phi will be equally spaced from 0 to pi/2\n    double dphi = M_PI/(2*n_points_this_level);\n    // weights on this level are equal to the gaussian times 2PI/total points in\n    // 2PI. Here we have n_points_this_level*4 total points\n    double weight =\n        gaussian_quadrature.weight(level) * M_PI/(n_points_this_level);\n\n    for (int j = 0; j < n_points_this_level; ++j) {\n      double phi = (j + 0.5)*dphi;\n      double x = std::sqrt(1 - mu*mu) * std::cos(phi);\n      double y = std::sqrt(1 - mu*mu) * std::sin(phi);\n      double z = mu;\n      std::array<double, 3> position{x,y,z};\n      generated_set.emplace_back(std::make_pair(CartesianPosition<3>(position),\n                                                Weight(weight)));\n    }\n  }\n  return generated_set;\n}\n\n} // namespace angular\n\n} // namespace quadrature\n\n} //namespace bart", "meta": {"hexsha": "c778296ec1b2bac2a7b8b22a82ea8c375dd27e9e", "size": 2344, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/quadrature/angular/level_symmetric_gaussian.cc", "max_stars_repo_name": "narang-amit/BART", "max_stars_repo_head_hexsha": "22997c4ce6de3e97b39f4da4601edbd4cf73f9e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/quadrature/angular/level_symmetric_gaussian.cc", "max_issues_repo_name": "narang-amit/BART", "max_issues_repo_head_hexsha": "22997c4ce6de3e97b39f4da4601edbd4cf73f9e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quadrature/angular/level_symmetric_gaussian.cc", "max_forks_repo_name": "narang-amit/BART", "max_forks_repo_head_hexsha": "22997c4ce6de3e97b39f4da4601edbd4cf73f9e2", "max_forks_repo_licenses": ["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.625, "max_line_length": 80, "alphanum_fraction": 0.6476109215, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.529996369673571}}
{"text": "// All content Copyright (C) 2018 Genomics plc\n#define BOOST_TEST_DYN_LINK\n\n#include <boost/test/unit_test.hpp>\n\n#include \"utils/multinomialCoefficients.hpp\"\n\n// n=1; r=1\n\nBOOST_AUTO_TEST_CASE( multinomialCoefficient_1 )\n{\n    std::vector< unsigned int > input = {1};\n    BOOST_CHECK_EQUAL( 1, multinomial_coefficient( input ) );\n}\n\n// n=2; r=2\n\nBOOST_AUTO_TEST_CASE( multinomialCoefficient_0_2 )\n{\n    std::vector< unsigned int > input = {0, 2};\n    BOOST_CHECK_EQUAL( 1, multinomial_coefficient( input ) );\n}\n\nBOOST_AUTO_TEST_CASE( multinomialCoefficient_1_1 )\n{\n    std::vector< unsigned int > input = {1, 1};\n    BOOST_CHECK_EQUAL( 2, multinomial_coefficient( input ) );\n}\n\nBOOST_AUTO_TEST_CASE( multinomialCoefficient_2_0 )\n{\n    std::vector< unsigned int > input = {2, 0};\n    BOOST_CHECK_EQUAL( 1, multinomial_coefficient( input ) );\n}\n\n// n=3; r=3 (partial)\n\nBOOST_AUTO_TEST_CASE( multinomialCoefficient_3_0_0 )\n{\n    std::vector< unsigned int > input = {3, 0, 0};\n    BOOST_CHECK_EQUAL( 1, multinomial_coefficient( input ) );\n}\n\nBOOST_AUTO_TEST_CASE( multinomialCoefficient_2_1_0 )\n{\n    std::vector< unsigned int > input = {2, 1, 0};\n    BOOST_CHECK_EQUAL( 3, multinomial_coefficient( input ) );\n}\n\nBOOST_AUTO_TEST_CASE( multinomialCoefficient_2_0_1 )\n{\n    std::vector< unsigned int > input = {2, 0, 1};\n    BOOST_CHECK_EQUAL( 3, multinomial_coefficient( input ) );\n}\n\nBOOST_AUTO_TEST_CASE( multinomialCoefficient_1_1_1 )\n{\n    std::vector< unsigned int > input = {1, 1, 1};\n    BOOST_CHECK_EQUAL( 6, multinomial_coefficient( input ) );\n}\n\nBOOST_AUTO_TEST_CASE( multinomialCoefficient_0_2_1 )\n{\n    std::vector< unsigned int > input = {0, 2, 1};\n    BOOST_CHECK_EQUAL( 3, multinomial_coefficient( input ) );\n}\n\nBOOST_AUTO_TEST_CASE( multinomialCoefficient_0_1_2 )\n{\n    std::vector< unsigned int > input = {0, 1, 2};\n    BOOST_CHECK_EQUAL( 3, multinomial_coefficient( input ) );\n}\n\nBOOST_AUTO_TEST_CASE( multinomialCoefficient_0_0_3 )\n{\n    std::vector< unsigned int > input = {0, 0, 3};\n    BOOST_CHECK_EQUAL( 1, multinomial_coefficient( input ) );\n}\n", "meta": {"hexsha": "7f8afd928ae497d8b9b78e5e078b5862e97085df", "size": 2063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/test/unittest/utils/testMultinomialCoefficients.cpp", "max_stars_repo_name": "dylex/wecall", "max_stars_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-08T15:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T07:13:05.000Z", "max_issues_repo_path": "cpp/test/unittest/utils/testMultinomialCoefficients.cpp", "max_issues_repo_name": "dylex/wecall", "max_issues_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-05T09:16:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-09T12:32:56.000Z", "max_forks_repo_path": "cpp/test/unittest/utils/testMultinomialCoefficients.cpp", "max_forks_repo_name": "dylex/wecall", "max_forks_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T15:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T07:28:33.000Z", "avg_line_length": 26.1139240506, "max_line_length": 61, "alphanum_fraction": 0.7135239942, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5299963643336014}}
{"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 <boost/core/lightweight_test.hpp>\n\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/typedefs.hpp>\n\n#include <cstddef>\n#include <iostream>\n#include <limits>\n#include <vector>\n\nnamespace gil = boost::gil;\n\ntemplate <typename Rasterizer>\nvoid exact_fit_test(std::ptrdiff_t radius, gil::point_t offset, Rasterizer rasterizer)\n{\n    std::vector<gil::point_t> circle_points(rasterizer.point_count(radius));\n    rasterizer(radius, offset, circle_points.begin());\n    // const std::ptrdiff_t diameter = radius * 2 - 1;\n    const std::ptrdiff_t width = offset.x + radius + 1;\n    const std::ptrdiff_t height = offset.y + radius + 1;\n    gil::gray8_image_t image(width, height);\n    auto input = gil::view(image);\n\n    for (const auto& point : circle_points)\n    {\n        input(point) = std::numeric_limits<gil::uint8_t>::max();\n    }\n\n    using param_t = gil::hough_parameter<std::ptrdiff_t>;\n    const auto radius_parameter = param_t{radius, 0, 1};\n    // const auto x_parameter = param_t::from_step_count(offset.x, neighborhood, half_step_count);\n    // const auto y_parameter = param_t::from_step_count(offset.y, neighborhood, half_step_count);\n    const auto x_parameter = param_t{offset.x, 0, 1};\n    const auto y_parameter = param_t{offset.y, 0, 1};\n\n    std::vector<gil::gray16_image_t> output_images(\n        radius_parameter.step_count,\n        gil::gray16_image_t(x_parameter.step_count, y_parameter.step_count));\n    std::vector<gil::gray16_view_t> output_views(radius_parameter.step_count);\n    std::transform(output_images.begin(), output_images.end(), output_views.begin(),\n                   [](gil::gray16_image_t& img)\n                   {\n                       return gil::view(img);\n                   });\n    gil::hough_circle_transform_brute(input, radius_parameter, x_parameter, y_parameter,\n                                      output_views.begin(), rasterizer);\n    if (output_views[0](0, 0) != rasterizer.point_count(radius))\n    {\n        std::cout << \"accumulated value: \" << static_cast<int>(output_views[0](0, 0))\n                  << \" expected value: \" << rasterizer.point_count(radius) << \"\\n\\n\";\n    }\n    BOOST_TEST(output_views[0](0, 0) == rasterizer.point_count(radius));\n}\n\nint main()\n{\n    const int test_dim_length = 20;\n    for (std::ptrdiff_t radius = 5; radius < test_dim_length; ++radius)\n    {\n        for (std::ptrdiff_t x_offset = radius; x_offset < radius + test_dim_length; ++x_offset)\n        {\n            for (std::ptrdiff_t y_offset = radius; y_offset < radius + test_dim_length; ++y_offset)\n            {\n\n                exact_fit_test(radius, {x_offset, y_offset}, gil::midpoint_circle_rasterizer{});\n                exact_fit_test(radius, {x_offset, y_offset},\n                               gil::trigonometric_circle_rasterizer{});\n            }\n        }\n    }\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "9b0a3563dab2a04ccc0e60408e3dab89439e70d4", "size": 3269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/image_processing/hough_circle_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_circle_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_circle_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.9166666667, "max_line_length": 99, "alphanum_fraction": 0.6576934842, "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5299963633773825}}
{"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_CCMATH_FPCLASSIFY\n#define BOOST_MATH_CCMATH_FPCLASSIFY\n\n#include <cmath>\n#include <limits>\n#include <type_traits>\n#include <boost/math/tools/is_constant_evaluated.hpp>\n#include <boost/math/ccmath/abs.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/isfinite.hpp>\n\nnamespace boost::math::ccmath {\n\ntemplate <typename T, std::enable_if_t<!std::is_integral_v<T>, bool> = true>\ninline constexpr int fpclassify(T x)\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))\n    {\n        return boost::math::ccmath::isnan(x) ? FP_NAN :\n               boost::math::ccmath::isinf(x) ? FP_INFINITE :\n               boost::math::ccmath::abs(x) == T(0) ? FP_ZERO :\n               boost::math::ccmath::abs(x) > 0 && boost::math::ccmath::abs(x) < (std::numeric_limits<T>::min)() ? FP_SUBNORMAL : FP_NORMAL;\n    }\n    else\n    {\n        using std::fpclassify;\n        return fpclassify(x);\n    }\n}\n\ntemplate <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>\ninline constexpr int fpclassify(Z x)\n{\n    return boost::math::ccmath::fpclassify(static_cast<double>(x));\n}\n\n}\n\n#endif // BOOST_MATH_CCMATH_FPCLASSIFY\n", "meta": {"hexsha": "2750af6d3e26d5e63e22c6d98eaffa6010120928", "size": 1412, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/ccmath/fpclassify.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/ccmath/fpclassify.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/ccmath/fpclassify.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": 30.6956521739, "max_line_length": 139, "alphanum_fraction": 0.6883852691, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6619228758499941, "lm_q1q2_score": 0.5299963589936318}}
{"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\nmap<int, int> memorize;\nint f(int n) {\n    if (memorize.count(n)) {\n        return memorize[n];\n    }\n    int x = (n % 2 == 0) ? n / 2 : 3 * n + 1;\n    memorize[n] = x;\n    return x;\n}\n\nint main(void) {\n    int s;\n    cin >> s;\n\n    int i;\n    set<int> ans;\n    ans.insert(s);\n    for(i = 2; ; ++i) {\n        s = f(s);\n        if(ans.count(s)) break;\n        ans.insert(s);\n    }\n    cout << i << endl;\n    return 0;\n}", "meta": {"hexsha": "dc6525ca8efc4f5fe488d2cddefaa8bd7f2117c8", "size": 703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc116/b/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/b/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/b/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.575, "max_line_length": 45, "alphanum_fraction": 0.5547652916, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5299963580374132}}
{"text": "#include \"theia/sfm/estimators/estimate_absolute_pose_with_known_orientation.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <ceres/rotation.h>\n#include <vector>\n\n#include \"theia/matching/feature_correspondence.h\"\n#include \"theia/sfm/create_and_initialize_ransac_variant.h\"\n#include \"theia/sfm/estimators/feature_correspondence_2d_3d.h\"\n#include \"theia/sfm/pose/essential_matrix_utils.h\"\n#include \"theia/sfm/pose/relative_pose_from_two_points_with_known_rotation.h\"\n#include \"theia/sfm/pose/util.h\"\n#include \"theia/sfm/triangulation/triangulation.h\"\n#include \"theia/solvers/estimator.h\"\n#include \"theia/solvers/sample_consensus_estimator.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\nnamespace {\n\n// An estimator for computing the relative pose from 2 feature\n// correspondences. The feature correspondences should be normalized by the\n// focal length with the principal point at (0, 0).\nclass RelativePoseWithKnownOrientationEstimator\n    : public Estimator<FeatureCorrespondence, Eigen::Vector3d> {\n public:\n  RelativePoseWithKnownOrientationEstimator() {}\n\n  // 2 correspondences are needed to determine the relative position.\n  double SampleSize() const { return 2; }\n\n  // Estimates candidate relative poses from correspondences.\n  bool EstimateModel(const std::vector<FeatureCorrespondence>& correspondences,\n                     std::vector<Eigen::Vector3d>* relative_positions) const {\n    Eigen::Vector3d position;\n    const Eigen::Vector2d rotated_features1[2] = {\n        correspondences[0].feature1.point_, correspondences[1].feature1.point_};\n    const Eigen::Vector2d rotated_features2[2] = {\n        correspondences[0].feature2.point_, correspondences[1].feature2.point_};\n    if (!RelativePoseFromTwoPointsWithKnownRotation(\n            rotated_features1, rotated_features2, &position)) {\n      return false;\n    }\n\n    relative_positions->emplace_back(position);\n    return true;\n  }\n\n  // The error for a correspondences given an relative position. This is the\n  // squared reprojection error.\n  double Error(const FeatureCorrespondence& correspondence,\n               const Eigen::Vector3d& relative_position) const {\n    static const Eigen::Matrix3d rotation = Eigen::Matrix3d::Identity();\n    return SquaredSampsonDistance(CrossProductMatrix(-relative_position),\n                                  correspondence.feature1.point_,\n                                  correspondence.feature2.point_);\n  }\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(RelativePoseWithKnownOrientationEstimator);\n};\n\n}  // namespace\n\nbool EstimateRelativePoseWithKnownOrientation(\n    const RansacParameters& ransac_params,\n    const RansacType& ransac_type,\n    const std::vector<FeatureCorrespondence>& rotated_correspondences,\n    Eigen::Vector3d* relative_camera2_position,\n    RansacSummary* ransac_summary) {\n  RelativePoseWithKnownOrientationEstimator relative_pose_estimator;\n  std::unique_ptr<\n      SampleConsensusEstimator<RelativePoseWithKnownOrientationEstimator> >\n      ransac = CreateAndInitializeRansacVariant(\n          ransac_type, ransac_params, relative_pose_estimator);\n  // Estimate the relative pose.\n  return ransac->Estimate(\n      rotated_correspondences, relative_camera2_position, ransac_summary);\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "4794154d3fe89efcc69bea3e85b92beb4e03d228", "size": 3260, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/estimators/estimate_relative_pose_with_known_orientation.cc", "max_stars_repo_name": "urbste/pyTheiaSfM", "max_stars_repo_head_hexsha": "814034c96b602fef1dc76ae6692278d61179ebcc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-11-10T19:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T08:16:54.000Z", "max_issues_repo_path": "src/theia/sfm/estimators/estimate_relative_pose_with_known_orientation.cc", "max_issues_repo_name": "urbste/TheiaSfM", "max_issues_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/estimators/estimate_relative_pose_with_known_orientation.cc", "max_forks_repo_name": "urbste/TheiaSfM", "max_forks_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-20T03:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T08:08:52.000Z", "avg_line_length": 39.2771084337, "max_line_length": 80, "alphanum_fraction": 0.7607361963, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5299963580374132}}
{"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 <cmath>\n#include <cfloat>\n#include <cstdint>\n#include <limits>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/core/lightweight_test.hpp>\n#include <boost/math/tools/config.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\ntemplate <typename T>\nvoid test()\n{\n    constexpr bool test_val = boost::math::ccmath::isnan(T(0));\n    static_assert(!test_val, \"Not constexpr\");\n\n    if constexpr (std::numeric_limits<T>::has_quiet_NaN)\n    {\n        static_assert(boost::math::ccmath::isnan(std::numeric_limits<T>::quiet_NaN()), \"Quiet NAN failed\");\n    }\n    if constexpr (std::numeric_limits<T>::has_signaling_NaN)\n    {\n        static_assert(boost::math::ccmath::isnan(std::numeric_limits<T>::signaling_NaN()), \"Signaling NAN failed\");\n    }\n    static_assert(!boost::math::ccmath::isnan(std::numeric_limits<T>::infinity()), \"Infininty failed\");\n    static_assert(!boost::math::ccmath::isnan(T(0)), \"Real 0 failed\");\n}\n\n// Only test on platforms that provide BOOST_MATH_IS_CONSTANT_EVALUATED\n#ifndef BOOST_MATH_NO_CONSTEXPR_DETECTION\nint main()\n{\n    test<float>();\n    test<double>();\n\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test<long double>();\n    #endif\n\n    #if defined(BOOST_HAS_FLOAT128) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\n    test<boost::multiprecision::float128>();\n    #endif\n\n    test<int>();\n    test<unsigned>();\n    test<long>();\n    test<std::int32_t>();\n    test<std::int64_t>();\n    test<std::uint32_t>();\n    \n    return boost::report_errors();\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "75a0330c12ed0eb41cbbdde87392fcd2a6d3cd94", "size": 1813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ccmath_isnan_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/ccmath_isnan_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/ccmath_isnan_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": 27.4696969697, "max_line_length": 115, "alphanum_fraction": 0.694980695, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5299963580374131}}
{"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    testNonlinearOptimizer.cpp\n * @brief   Unit tests for NonlinearOptimizer class\n * @author  Frank Dellaert\n */\n\n#include <tests/smallExample.h>\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/Values.h>\n#include <gtsam/nonlinear/Symbol.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/GaussNewtonOptimizer.h>\n#include <gtsam/nonlinear/DoglegOptimizer.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/NoiseModel.h>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/base/Matrix.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/shared_ptr.hpp>\n#include <boost/assign/std/list.hpp> // for operator +=\nusing namespace boost::assign;\n\n#include <iostream>\n\nusing namespace std;\nusing namespace gtsam;\n\nconst double tol = 1e-5;\n\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\n/* ************************************************************************* */\nTEST( NonlinearOptimizer, iterateLM )\n{\n\t// really non-linear factor graph\n  example::Graph fg(example::createReallyNonlinearFactorGraph());\n\n\t// config far from minimum\n\tPoint2 x0(3,0);\n\tValues config;\n\tconfig.insert(X(1), x0);\n\n\t// normal iterate\n\tGaussNewtonParams gnParams;\n\tGaussNewtonOptimizer gnOptimizer(fg, config, gnParams);\n\tgnOptimizer.iterate();\n\n\t// LM iterate with lambda 0 should be the same\n\tLevenbergMarquardtParams lmParams;\n\tlmParams.lambdaInitial = 0.0;\n\tLevenbergMarquardtOptimizer lmOptimizer(fg, config, lmParams);\n\tlmOptimizer.iterate();\n\n\tCHECK(assert_equal(gnOptimizer.values(), lmOptimizer.values(), 1e-9));\n}\n\n/* ************************************************************************* */\nTEST( NonlinearOptimizer, optimize )\n{\n  example::Graph fg(example::createReallyNonlinearFactorGraph());\n\n\t// test error at minimum\n\tPoint2 xstar(0,0);\n\tValues cstar;\n\tcstar.insert(X(1), xstar);\n\tDOUBLES_EQUAL(0.0,fg.error(cstar),0.0);\n\n\t// test error at initial = [(1-cos(3))^2 + (sin(3))^2]*50 =\n\tPoint2 x0(3,3);\n\tValues c0;\n\tc0.insert(X(1), x0);\n\tDOUBLES_EQUAL(199.0,fg.error(c0),1e-3);\n\n\t// optimize parameters\n\tOrdering ord;\n\tord.push_back(X(1));\n\n\t// Gauss-Newton\n\tGaussNewtonParams gnParams;\n\tgnParams.ordering = ord;\n\tValues actual1 = GaussNewtonOptimizer(fg, c0, gnParams).optimize();\n\tDOUBLES_EQUAL(0,fg.error(actual1),tol);\n\n\t// Levenberg-Marquardt\n\tLevenbergMarquardtParams lmParams;\n\tlmParams.ordering = ord;\n  Values actual2 = LevenbergMarquardtOptimizer(fg, c0, lmParams).optimize();\n  DOUBLES_EQUAL(0,fg.error(actual2),tol);\n\n  // Dogleg\n  DoglegParams dlParams;\n  dlParams.ordering = ord;\n  Values actual3 = DoglegOptimizer(fg, c0, dlParams).optimize();\n  DOUBLES_EQUAL(0,fg.error(actual3),tol);\n}\n\n/* ************************************************************************* */\nTEST( NonlinearOptimizer, SimpleLMOptimizer )\n{\n\texample::Graph fg(example::createReallyNonlinearFactorGraph());\n\n\tPoint2 x0(3,3);\n\tValues c0;\n\tc0.insert(X(1), x0);\n\n\tValues actual = LevenbergMarquardtOptimizer(fg, c0).optimize();\n\tDOUBLES_EQUAL(0,fg.error(actual),tol);\n}\n\n/* ************************************************************************* */\nTEST( NonlinearOptimizer, SimpleGNOptimizer )\n{\n  example::Graph fg(example::createReallyNonlinearFactorGraph());\n\n  Point2 x0(3,3);\n  Values c0;\n  c0.insert(X(1), x0);\n\n  Values actual = GaussNewtonOptimizer(fg, c0).optimize();\n\tDOUBLES_EQUAL(0,fg.error(actual),tol);\n}\n\n/* ************************************************************************* */\nTEST( NonlinearOptimizer, SimpleDLOptimizer )\n{\n  example::Graph fg(example::createReallyNonlinearFactorGraph());\n\n  Point2 x0(3,3);\n  Values c0;\n  c0.insert(X(1), x0);\n\n  Values actual = DoglegOptimizer(fg, c0).optimize();\n  DOUBLES_EQUAL(0,fg.error(actual),tol);\n}\n\n/* ************************************************************************* */\nTEST( NonlinearOptimizer, optimization_method )\n{\n  LevenbergMarquardtParams paramsQR;\n  paramsQR.linearSolverType = LevenbergMarquardtParams::MULTIFRONTAL_QR;\n  LevenbergMarquardtParams paramsChol;\n  paramsChol.linearSolverType = LevenbergMarquardtParams::MULTIFRONTAL_CHOLESKY;\n\n\texample::Graph fg = example::createReallyNonlinearFactorGraph();\n\n\tPoint2 x0(3,3);\n\tValues c0;\n\tc0.insert(X(1), x0);\n\n\tValues actualMFQR = LevenbergMarquardtOptimizer(fg, c0, paramsQR).optimize();\n\tDOUBLES_EQUAL(0,fg.error(actualMFQR),tol);\n\n  Values actualMFChol = LevenbergMarquardtOptimizer(fg, c0, paramsChol).optimize();\n  DOUBLES_EQUAL(0,fg.error(actualMFChol),tol);\n}\n\n/* ************************************************************************* */\nTEST( NonlinearOptimizer, Factorization )\n{\n\tValues config;\n\tconfig.insert(X(1), Pose2(0.,0.,0.));\n\tconfig.insert(X(2), Pose2(1.5,0.,0.));\n\n\tNonlinearFactorGraph graph;\n\tgraph.add(PriorFactor<Pose2>(X(1), Pose2(0.,0.,0.), noiseModel::Isotropic::Sigma(3, 1e-10)));\n\tgraph.add(BetweenFactor<Pose2>(X(1),X(2), Pose2(1.,0.,0.), noiseModel::Isotropic::Sigma(3, 1)));\n\n\tOrdering ordering;\n\tordering.push_back(X(1));\n\tordering.push_back(X(2));\n\n\tLevenbergMarquardtOptimizer optimizer(graph, config, ordering);\n\toptimizer.iterate();\n\n\tValues expected;\n\texpected.insert(X(1), Pose2(0.,0.,0.));\n\texpected.insert(X(2), Pose2(1.,0.,0.));\n\tCHECK(assert_equal(expected, optimizer.values(), 1e-5));\n}\n\n/* ************************************************************************* */\nTEST(NonlinearOptimizer, NullFactor) {\n\n  example::Graph fg = example::createReallyNonlinearFactorGraph();\n\n  // Add null factor\n  fg.push_back(example::Graph::sharedFactor());\n\n  // test error at minimum\n  Point2 xstar(0,0);\n  Values cstar;\n  cstar.insert(X(1), xstar);\n  DOUBLES_EQUAL(0.0,fg.error(cstar),0.0);\n\n  // test error at initial = [(1-cos(3))^2 + (sin(3))^2]*50 =\n  Point2 x0(3,3);\n  Values c0;\n  c0.insert(X(1), x0);\n  DOUBLES_EQUAL(199.0,fg.error(c0),1e-3);\n\n  // optimize parameters\n  Ordering ord;\n  ord.push_back(X(1));\n\n  // Gauss-Newton\n  Values actual1 = GaussNewtonOptimizer(fg, c0, ord).optimize();\n  DOUBLES_EQUAL(0,fg.error(actual1),tol);\n\n  // Levenberg-Marquardt\n  Values actual2 = LevenbergMarquardtOptimizer(fg, c0, ord).optimize();\n  DOUBLES_EQUAL(0,fg.error(actual2),tol);\n\n  // Dogleg\n  Values actual3 = DoglegOptimizer(fg, c0, ord).optimize();\n  DOUBLES_EQUAL(0,fg.error(actual3),tol);\n}\n\n/* ************************************************************************* */\nTEST(NonlinearOptimizer, MoreOptimization) {\n\n  NonlinearFactorGraph fg;\n  fg.add(PriorFactor<Pose2>(0, Pose2(0,0,0), noiseModel::Isotropic::Sigma(3,1)));\n  fg.add(BetweenFactor<Pose2>(0, 1, Pose2(1,0,M_PI/2), noiseModel::Isotropic::Sigma(3,1)));\n  fg.add(BetweenFactor<Pose2>(1, 2, Pose2(1,0,M_PI/2), noiseModel::Isotropic::Sigma(3,1)));\n\n  Values init;\n  init.insert(0, Pose2(3,4,-M_PI));\n  init.insert(1, Pose2(10,2,-M_PI));\n  init.insert(2, Pose2(11,7,-M_PI));\n\n  Values expected;\n  expected.insert(0, Pose2(0,0,0));\n  expected.insert(1, Pose2(1,0,M_PI/2));\n  expected.insert(2, Pose2(1,1,M_PI));\n\n  // Try LM and Dogleg\n  EXPECT(assert_equal(expected, LevenbergMarquardtOptimizer(fg, init).optimize()));\n  EXPECT(assert_equal(expected, DoglegOptimizer(fg, init).optimize()));\n}\n\n/* ************************************************************************* */\nint main() {\n\tTestResult tr;\n\treturn TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "cb5e8f48216eca9408744f403015bc2486290518", "size": 7877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testNonlinearOptimizer.cpp", "max_stars_repo_name": "sdmiller/gtsam_pcl", "max_stars_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T16:41:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T07:02:44.000Z", "max_issues_repo_path": "tests/testNonlinearOptimizer.cpp", "max_issues_repo_name": "sdmiller/gtsam_pcl", "max_issues_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/testNonlinearOptimizer.cpp", "max_forks_repo_name": "sdmiller/gtsam_pcl", "max_forks_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T12:06:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T07:02:48.000Z", "avg_line_length": 29.8371212121, "max_line_length": 97, "alphanum_fraction": 0.6333629554, "num_tokens": 2189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5299963580374131}}
{"text": "// Copyright 2004 The Trustees of Indiana University.\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//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_CIRCLE_LAYOUT_HPP\n#define BOOST_GRAPH_CIRCLE_LAYOUT_HPP\n#include <boost/config/no_tr1/cmath.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <utility>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/topology.hpp>\n#include <boost/static_assert.hpp>\n\nnamespace boost {\n  /**\n   * \\brief Layout the graph with the vertices at the points of a regular\n   * n-polygon.\n   *\n   * The distance from the center of the polygon to each point is\n   * determined by the @p radius parameter. The @p position parameter\n   * must be an Lvalue Property Map whose value type is a class type\n   * containing @c x and @c y members that will be set to the @c x and\n   * @c y coordinates.\n   */\n  template<typename VertexListGraph, typename PositionMap, typename Radius>\n  void\n  circle_graph_layout(const VertexListGraph& g, PositionMap position,\n                      Radius radius)\n  {\n    BOOST_STATIC_ASSERT (property_traits<PositionMap>::value_type::dimensions >= 2);\n    const double pi = boost::math::constants::pi<double>();\n\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sin;\n    using std::cos;\n#endif // BOOST_NO_STDC_NAMESPACE\n\n    typedef typename graph_traits<VertexListGraph>::vertices_size_type\n      vertices_size_type;\n\n    vertices_size_type n = num_vertices(g);\n\n    vertices_size_type i = 0;\n    double two_pi_over_n = 2. * pi / n;\n    BGL_FORALL_VERTICES_T(v, g, VertexListGraph) {\n      position[v][0] = radius * cos(i * two_pi_over_n);\n      position[v][1] = radius * sin(i * two_pi_over_n);\n      ++i;\n    }\n  }\n} // end namespace boost\n\n#endif // BOOST_GRAPH_CIRCLE_LAYOUT_HPP\n", "meta": {"hexsha": "4fecefd63322fe6bd4ccfab34c4f5ae122de76a7", "size": 1942, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/graph/circle_layout.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/boost/graph/circle_layout.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/boost/graph/circle_layout.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": 32.9152542373, "max_line_length": 84, "alphanum_fraction": 0.7178166838, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5299963536536623}}
{"text": "/*\n  test_stoch_euler.cpp : Sample program to demonstrate the working of stochastic Euler\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#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <fstream>\n#include <string>\n\n#include \"det_model_hh_post.hpp\"\n#include \"physical_constants.hpp\"\n#include \"stl_vector_operation_functions.hpp\"\n#include \"stoch_odeint_explicit_euler.hpp\"\n\n#include <boost/numeric/odeint.hpp> /*  Specifying the file within < > lets c++ search for it at -I path  */\n#include <boost/range/iterator_range.hpp>\n#include <boost/range/iterator.hpp>\n\nnamespace bno=boost::numeric::odeint;\nnamespace myode=stoch_odeint_explicit_euler;\n\ntypedef std::vector< double > state_type;\ntypedef bno::runge_kutta4 < state_type > boost_rk4_stepper_type;\n\n//-----------------\n\nint main(int argc, char *argv[])\n{\n  // initializes the 'classical' odeint stepper from BOOST\n  boost_rk4_stepper_type boost_rk4;\n  state_type X_hh = {0,1,0,-80.0E-03}; // {m,h,n,V}\n  // initializes an HH object using the 'DET_MODEL_HH_POST' class\n  DET_MODEL_HH_POST det_hhp(X_hh); \n  //--------------------------------------\n\n  // initializes the stochastic explicit euler stepper\n  myode::STOCH_ODEINT_EXPLICIT_EULER< state_type > odeint_euler;\n  // the vector s can be used to add noise to each each element of the state vector\n  // '0' indictaes no noise added.\n  // setting all elements of the s vector reduces the stepper to simple explicit Euler!\n  std::vector<unsigned> s = {0,0,0,1}; // {m,h,n,V}\n  // initialization of observer object : outputs to stdout\n  null_observer my_observer;\n\n  //--------------------------------------\n  double t = 0.0;\n  const double dt = 15E-06;\n  const double tmax = 100E-03;\n  // integrate_const can be used to compute all the time steps at once. Use an oberver of your choise, defaults to the null_oberver which outputs to stdout\n  //integrate_const(odeint_euler,det_hhp, det_hhp.X,t,tmax,dt,s,my_observer);  \n  while (t <= tmax){\n    odeint_euler.do_step( det_hhp,det_hhp.X,t,dt,s);\n    //boost_rk4.do_step( det_hhp,det_hhp.X, t, dt);\n    //---------------------------\n    if( (t > 50E-03) && ( t < (54E-03 )) ){\n      det_hhp.IExt = 20E-02;\t// External current to trigger presynaptic spike \n    }\n    else{\n      det_hhp.IExt = 0.0;\n    }\n    std::cout << t << \" \" << det_hhp.X << std::endl;\n    t = t + dt;\n  };\n  return 0;\n}\n", "meta": {"hexsha": "d4bd70f386f10c1774a73ce99c4695d6b4ee7fb0", "size": 3059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/old/test_stoch_euler.cpp", "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/test_stoch_euler.cpp", "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/test_stoch_euler.cpp", "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": 37.3048780488, "max_line_length": 155, "alphanum_fraction": 0.6930369402, "num_tokens": 840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5299963526974437}}
{"text": "//\n// Created by Heuer on 10.03.18.\n//\n\n#include <gtest/gtest.h>\n#include <Eigen/Core>\n#include \"LebedevSphericalIntegration/GridCreator.h\"\n#include \"sphere_lebedev_rule.h\"\n\nclass AGridCreatorTest : public ::testing::Test {\npublic:\n    Lebedev::GridCreator gridCreator;\n    void SetUp() override {}\n};\n\nTEST_F(AGridCreatorTest, JBurkardtReferenceCheck) {\n\n    for (const auto & order : Lebedev::allOrders) {\n        \n        gridCreator.changeGrid(order);\n        auto nPts = gridCreator.totalNumberOfGridPoints();\n        auto calculated = gridCreator.grid();\n\n        double x[nPts], y[nPts], z[nPts], w[nPts];\n        ld_by_order(nPts, x, y, z, w);\n\n        Eigen::Matrix<double,Eigen::Dynamic,4> reference(nPts, 4);\n        reference.col(0) = Eigen::VectorXd::Map(x, nPts);\n        reference.col(1) = Eigen::VectorXd::Map(y, nPts);\n        reference.col(2) = Eigen::VectorXd::Map(z, nPts);\n        reference.col(3) = Eigen::VectorXd::Map(w, nPts);\n\n        ASSERT_EQ(calculated.rows(),reference.rows());\n        ASSERT_EQ(calculated.cols(),reference.cols());\n\n        ASSERT_TRUE(calculated.isApprox(reference,0.0));\n    }\n}\n\nTEST_F(AGridCreatorTest, JBurkardtReferenceCheckElementWise) {\n\n    for (const auto & order : Lebedev::allOrders) {\n\n        gridCreator.changeGrid(order);\n        auto nPts = gridCreator.totalNumberOfGridPoints();\n        auto calculated = gridCreator.grid();\n\n        double x[nPts], y[nPts], z[nPts], w[nPts];\n        ld_by_order(nPts, x, y, z, w);\n\n        Eigen::Matrix<double,Eigen::Dynamic,4> reference(nPts, 4);\n        reference.col(0) = Eigen::VectorXd::Map(x, nPts);\n        reference.col(1) = Eigen::VectorXd::Map(y, nPts);\n        reference.col(2) = Eigen::VectorXd::Map(z, nPts);\n        reference.col(3) = Eigen::VectorXd::Map(w, nPts);\n\n        ASSERT_EQ(calculated.rows(),reference.rows());\n        ASSERT_EQ(calculated.cols(),reference.cols());\n\n        for (int i = 0; i < nPts; ++i) {\n            for (int j = 0; j < 4; ++j) {\n                ASSERT_EQ(calculated.row(i)[j], reference.row(i)[j]);\n            }\n        }\n    }\n}\n\nTEST_F(AGridCreatorTest, CorrectTotalNumberOfPoints) {\n\n}\n", "meta": {"hexsha": "2cccaf524be417cf13089cf6c38e70dbd8e3c4c9", "size": 2138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/AGridCreatorTest.cpp", "max_stars_repo_name": "MonteCarloMichael/LebedevSphericalIntegration", "max_stars_repo_head_hexsha": "b75d589b0f29bcb66a7413b86c53e757a9172639", "max_stars_repo_licenses": ["MIT"], "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/AGridCreatorTest.cpp", "max_issues_repo_name": "MonteCarloMichael/LebedevSphericalIntegration", "max_issues_repo_head_hexsha": "b75d589b0f29bcb66a7413b86c53e757a9172639", "max_issues_repo_licenses": ["MIT"], "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/AGridCreatorTest.cpp", "max_forks_repo_name": "MonteCarloMichael/LebedevSphericalIntegration", "max_forks_repo_head_hexsha": "b75d589b0f29bcb66a7413b86c53e757a9172639", "max_forks_repo_licenses": ["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.1126760563, "max_line_length": 69, "alphanum_fraction": 0.619738073, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5299482542098594}}
{"text": "/**\n  * \\file test_solver_tools.cpp\n  *\n  * Tests for solver_tools\n  */\n\n#include<solver_tools.h>\n#include<sstream>\n#include<fstream>\n#include<iostream>\n\n#define BOOST_TEST_MODULE test_vector_tools\n#include <boost/test/included/unit_test.hpp>\n\ntypedef solverTools::errorOut errorOut;\ntypedef solverTools::errorNode errorNode;\ntypedef solverTools::floatType floatType;\ntypedef solverTools::floatVector floatVector;\ntypedef solverTools::floatMatrix floatMatrix;\ntypedef solverTools::intVector intVector;\ntypedef solverTools::intMatrix intMatrix;\n\nstruct cout_redirect{\n    cout_redirect( std::streambuf * new_buffer )\n        : old( std::cout.rdbuf( new_buffer ) )\n    { }\n\n    ~cout_redirect( ) {\n        std::cout.rdbuf( old );\n    }\n\n    private:\n        std::streambuf * old;\n};\n\nstruct cerr_redirect{\n    cerr_redirect( std::streambuf * new_buffer )\n        : old( std::cerr.rdbuf( new_buffer ) )\n    { }\n\n    ~cerr_redirect( ) {\n        std::cerr.rdbuf( old );\n    }\n\n    private:\n        std::streambuf * old;\n};\n\nerrorOut nlFxn1( const floatVector &x, const floatMatrix &floatArgs, const intMatrix &intArgs,\n                 floatVector &residual, floatMatrix &jacobian, floatMatrix &floatOuts,\n                 intMatrix &intOuts ){\n    /*!\n     * A non-linear function for use in testing the solver. This function is a linear\n     * function of the form\n     * \n     * \\f$ R = \\left [ x + 1, y - 5.6 \\right ]\\f$\n     * \n     * which has a solution at \\f$\\left ( -1, 5.6 \\right )\\f$\n     * \n     * The function also sets floatOuts to\n     * \n     * \\f$\\left [ \\left [ -1 \\right ], \\left [ -1, -2, -3 \\right ], \\left [ 4, 5, 6 \\right ] \\right ]\\f$\n     * \n     * And intOuts to\n     * \n     * \\f$\\left [ \\left [ 1, 2, 8 \\right ] \\right ]\\f$\n     * \n     * \\param &x: The variable vector. Of size 2.\n     * \\param &floatArgs: Floating point arguments to the function. None expected.\n     * \\param &intArgs: Integer arguments to the function. None expected.\n     * \\param &residual: The residual vector output.\n     * \\param &jacobian: The jacobian output.\n     * \\param &floatOuts: Additional floating point outputs.\n     * \\param &intOuts: Additional integer outputs.\n     */\n\n    if ( x.size( ) != 2 ){\n        return new errorNode( \"nlFnx1\", \"x must have a size of 2\" );\n    }\n\n    floatType x0 = -1;\n    floatType y0 = 5.6;\n\n    residual = { x[ 0 ] - x0, x[ 1 ] - y0 };\n    jacobian = { { 1, 0 }, { 0, 1 } };\n\n    floatOuts = { { -1 }, { -1, -2, -3 }, { 4, 5, 6 } };\n    intOuts = { { 1, 2, 8 } };\n\n    return NULL;\n}\n\nerrorOut nlFxn1( const floatVector &x, const floatMatrix &floatArgs, const intMatrix &intArgs,\n                 floatVector &residual ){\n    /*!\n     * A non-linear function for use in testing the solver. An overload that hides the jacobian,\n     * floatOut, and intOut arrays.\n     * \n     * \\param &x: The variable vector. Of size 2\n     * \\param &floatArgs: Floating point arguments to the function\n     * \\param &intArgs: Integer arguments to the function\n     * \\param &residual: The residual vector output.\n     */\n\n    floatMatrix Jtmp;\n    floatMatrix fO;\n    intMatrix iO;\n    return nlFxn1( x, floatArgs, intArgs, residual, Jtmp, fO, iO );\n}\n\nerrorOut nlFxn2( const floatVector &x, const floatMatrix &floatArgs, const intMatrix &intArgs,\n                 floatVector &residual, floatMatrix &jacobian, floatMatrix &floatOuts, \n                 intMatrix &intOuts ){\n    /*!\n     * A non-linear function for use in testing the solver. A polynomial function of the form\n     * \n     * \\f$ R = \\left [ ( x - 1 ) ( x - 7 ) y, ( y - 1 ) ( x - 3 ) z, x y z \\right ]\\f$\n     *\n     * The function also sets floatOuts to\n     * \n     * \\f$\\left [ \\left [ -1 \\right ], \\left [ -1, -2, -3 \\right ], \\left [ 4, 5, 6 \\right ] \\right ]\\f$\n     * \n     * And intOuts to\n     * \n     * \\f$\\left [ \\left [ 1, 2, 8 \\right ] \\right ]\\f$\n     * \n     * \\param &x: The variable vector. Of size 3.\n     * \\param &floatArgs: Floating point arguments to the function. Unused.\n     * \\param &intArgs: Integer arguments to the function. Unused.\n     * \\param &residual: The residual vector output.\n     * \\param &jacobian: The jacobian output.\n     * \\param &floatOuts: Additional floating point outputs.\n     * \\param &intOuts: Additional integer outputs.\n     */\n\n    if ( x.size( ) != 3 ){\n        return new errorNode( \"nlFxn2\", \"x must have a size of 3\" );\n    }\n\n    residual = { ( x[ 0 ] - 1 ) * ( x[ 0 ] - 7 ) * x[ 1 ], ( x[ 1 ] - 1 ) * ( x[ 0 ] - 3 ) * x[ 2 ], x[ 0 ] * x[ 1 ] * x[ 2 ] };\n    jacobian = { { ( x[ 0 ] - 7 ) * x[ 1 ] + ( x[ 0 ] - 1 ) * x[ 1 ], ( x[ 0 ] - 1 ) * ( x[ 0 ] - 7 ), 0 },\n                 {   ( x[ 1 ] - 1 ) * x[ 2 ],    ( x[ 0 ] - 3 ) * x[ 2 ], ( x[ 1 ] - 1 ) * ( x[ 0 ] - 3 ) },\n                 {   x[ 1 ] * x[ 2 ],    x[ 0 ] * x[ 2 ], x[ 0 ] * x[ 1 ] } };\n\n    floatOuts = { { -1 }, { -1, -2, -3 }, { 4, 5, 6 } };\n    intOuts = { { 1, 2, 8 } };\n\n    return NULL;\n}\n\nerrorOut nlFxn2( const floatVector &x, const floatMatrix &floatArgs, const intMatrix &intArgs,\n                 floatVector &residual ){\n    /*!\n     * A non-linear function for use in testing the solver. The same as the previously overloaded function\n     * except this function obfuscates the computation of the Jacobian, the floatOuts, and the intOuts.\n     * \n     * \\param &x: The variable vector\n     * \\param &floatArgs: Floating point arguments to the function\n     * \\param &intArgs: Integer arguments to the function\n     * \\param &residual: The residual vector output.\n     */\n\n    floatMatrix Jtmp;\n    floatMatrix fO;\n    intMatrix iO;\n    return nlFxn2( x, floatArgs, intArgs, residual, Jtmp, fO, iO );\n}\n\nerrorOut nlFxn3( const floatVector &x, const floatMatrix &floatArgs, const intMatrix &intArgs,\n                 floatVector &residual, floatMatrix &jacobian, floatMatrix &floatOuts, \n                 intMatrix &intOuts ){\n    /*!\n     * A non-linear function for use in testing the solver which will \n     * require the use of the line-search algorithm. The function is of the form\n     * \n     * \\f$R = exp( -x ) - 1\\f$\n     * \n     * The function also sets floatOuts to\n     * \n     * \\f$\\left [ \\left [ -1 \\right ], \\left [ -1, -2, -3 \\right ], \\left [ 4, 5, 6 \\right ] \\right ]\\f$\n     * \n     * And intOuts to\n     * \n     * \\f$\\left [ \\left [ 1, 2 8 \\right ] \\right ]\\f$\n     * \n     * \\param &x: The variable vector. Size 1.\n     * \\param &floatArgs: Floating point arguments to the function\n     * \\param &intArgs: Integer arguments to the function\n     * \\param &residual: The residual vector output.\n     * \\param &jacobian: The jacobian output.\n     * \\param &floatOuts: Additional floating point outputs.\n     * \\param &intOuts: Additional integer outputs.\n     */\n\n    residual = { std::exp( -x[ 0 ] ) - 1 };\n    jacobian = { { -std::exp( -x[ 0 ] ) } };\n    floatOuts = { { -1 }, { -1, -2, -3 }, { 4, 5, 6 } };\n    intOuts = { { 1, 2, 8 } };\n    return NULL;\n}\n\nerrorOut nlFxn3( const floatVector &x, const floatMatrix &floatArgs, const intMatrix &intArgs,\n                 floatVector &residual ){\n    /*!\n     * A non-linear function for use in testing the solver which will \n     * require the use of the line-search algorithm. The same as the overloaded nlFxn3 except\n     * this obfuscates the jacobian, the floatOuts, and the intOuts.\n     * \n     * \\param &x: The variable vector. Size 1.\n     * \\param &floatArgs: Floating point arguments to the function\n     * \\param &intArgs: Integer arguments to the function\n     * \\param &residual: The residual vector output.\n     */\n    floatMatrix Jtmp;\n    floatMatrix fO;\n    intMatrix iO;\n    return nlFxn3( x, floatArgs, intArgs, residual, Jtmp, fO, iO );\n}\n\nerrorOut nlFxn4( const floatVector &x, const floatMatrix &floatArgs, const intMatrix &intArgs,\n                 floatVector &residual, floatMatrix &jacobian, floatMatrix &floatOuts,\n                 intMatrix &intOuts ){\n    /*!\n     * A non-linear function for use in testing the solver which will\n     * require the use of the line-search algorithm. The function is of the form\n     * \n     * \\f$R = tanh( x )\\f$\n     *\n     * \\param &x: The variable vector. Of size 1.\n     * \\param &floatArgs: Floating point arguments to the function. Unused.\n     * \\param &intArgs: Integer arguments to the function. Unused.\n     * \\param &residual: The residual vector output.\n     * \\param &jacobian: The jacobian output.\n     * \\param &floatOuts: Additional floating point outputs. Unused.\n     * \\param &intOuts: Additional integer outputs. Unused.\n     */\n\n    residual = { std::tanh( x[ 0 ] ) };\n    jacobian = { { ( std::cosh( x[ 0 ] ) * std::cosh( x[ 0 ] ) - std::sinh( x[ 0 ] ) * std::sinh( x[ 0 ] ) ) / ( std::cosh( x[ 0 ] ) * std::cosh( x[ 0 ] ) ) } };\n    return NULL;\n}\n\nerrorOut nlFxn5( const floatVector &x, const floatMatrix &floatArgs, const intMatrix &intArgs,\n                 floatVector &residual, floatMatrix &jacobian, floatMatrix &floatOuts,\n                 intMatrix &intOuts ){\n    /*!\n     * A non-linear function for use in testing the solver which will require\n     * the use of the bounded homotopy solver. This function performs error checking on the\n     * floatArgs, intArgs, floatOuts, and intOuts arrays. The function is of the form.\n     * \n     *  \\f$ R = \\left [ ( x - 1 ) ( x + 1 ) ( x + 1 ) ( x - 0.25 ) ( x + 0.1 ) \\right ]\\f$\n     * \n     * The expected values for `floatArgs` are:\n     * \n     * \\f$ floatArgs = \\left [ \\left [ 0.1, 0.2, 0.3, 0.4 \\right ], \\left [ -0.01, -0.02 \\right ] \\right ] \\f$\n     * \n     * The expected values for `intArgs` are\n     * \n     * \\f$ intArgs = \\left [ \\left [ -1, -2, -3 \\right ], \\left [ 5, 4, 3, 2 \\right ], \\left [ 8, 9, 9 \\right ] \\right ]\\f$\n     * \n     * The expected incoming values for `floatOuts` are\n     * \n     * \\f$ floatOuts = \\left [ \\left [ 0, 1, 2 \\right ], \\left [ 7, -6 \\right ], \\left [ 0.24, 0.25 \\right ] \\right ]\\f$\n     *\n     * The expected incoming values for `intOuts` are\n     * \n     * \\f$ intOuts = \\left [ \\left [ 1, 2, 3 \\right ], \\left [ -5, 6, 7, 8 \\right ] \\right ] \\f$\n     * \n     * The function currently throws an error if the expected values are not provided. `floatOuts` is \n     * updated to\n     * \n     * \\f$ floatOuts = \\left [ \\left [ 0.1, 1.1, 2.1 \\right ], \\left [ 7, -6 \\right ], \\left [ 0, 1, 2 \\right ] \\right ]\\f$\n     * \n     * `intOuts` is updated to\n     * \n     * \\f$ intOuts = \\left [ \\left [ -1, 0, 1 \\right ], \\left [ 1, 2, 3 \\right ], \\left [ -5, 6, 7, 8 \\right ] \\right ] \\f$\n     * \n     * \\param &x: The variable vector. One value.\n     * \\param &floatArgs: Floating point arguments to the function\n     * \\param &intArgs: Integer arguments to the function\n     * \\param &residual: The residual vector output.\n     * \\param &jacobian: The jacobian output.\n     * \\param &floatOuts: Additional floating point outputs.\n     * \\param &intOuts: Additional integer outputs.\n     */\n\n    //floatArgs answers\n    floatVector answer1 = { .1, .2, .3, .4 };\n    floatVector answer2 = { -0.01, -0.02 };\n\n    //IntArgs answers\n    intVector answer3 = { -1, -2, -3 };\n    intVector answer4 = { 5, 4, 3, 2 };\n    intVector answer5 = { 8, 9, 9 };\n\n    //floatOuts answers\n    floatVector answer6 = { 0, 1, 2 };\n    floatVector answer7 = { 7, -6 };\n    floatVector answer8 = { .24, .25 };\n\n    //intOuts answers\n    intVector   answer9  = { 1, 2, 3 };\n    intVector   answer10 = { -5, 6, 7, 8 };\n\n    //x tests\n    if ( x.size( ) != 1 ){\n        return new errorNode( \"nlFxn5\", \"The x vector should have a size of 1\" );\n    }\n\n    //floatArgs tests\n    if ( floatArgs.size( ) != 2 ){\n        return new errorNode( \"nlFxn5\", \"The floatArgs matrix should have two values\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( floatArgs[ 0 ], answer1 ) ){\n        return new errorNode( \"nlFxn5\", \"The first value of floatArgs should be { 0.1, 0.2, 0.3, 0.4 }\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( floatArgs[ 1 ], answer2 ) ){\n        return new errorNode( \"nlFxn5\", \"The second value of floatArgs should be { -0.01, -0.02 }\" );\n    }\n\n    //intArgs tests\n    if ( intArgs.size( ) != 3 ){\n        return new errorNode( \"nlFxn5\", \"The intArgs matrix should have three values\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( intArgs[ 0 ], answer3 ) ){\n        return new errorNode( \"nlFxn5\", \"The first value of intargs should be { -1, -2, -3 }\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( intArgs[ 1 ], answer4 ) ){\n        return new errorNode( \"nlFxn5\", \"The second value of intargs should be { 5, 4, 3, 2 }\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( intArgs[ 2 ], answer5 ) ){\n        return new errorNode( \"nlFxn5\", \"The third value of intargs should be { 8, 9, 9 }\" );\n    }\n\n    //floatOuts tests\n    if ( floatOuts.size( ) != 3 ){\n        return new errorNode( \"nlFxn5\", \"The floatOuts matrix should have three values\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( floatOuts[ 0 ], answer6 ) ){\n        return new errorNode( \"nlFxn5\", \"The first values in the floatOuts should be { 0, 1, 2 }\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( floatOuts[ 1 ], answer7 ) ){\n        return new errorNode( \"nlFxn5\", \"The second values in the floatOuts should be { 7, -6 }\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( floatOuts[ 2 ], answer8 ) ){\n        return new errorNode( \"nlFxn5\", \"The third values in the floatOuts should be { 0.24, 0.25 }\" );\n    }\n\n    //intOuts tests\n    if ( intOuts.size( ) != 2 ){\n        return new errorNode( \"nlFxn5\", \"The intOuts matrix must have a size of 2\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( intOuts[ 0 ], answer9 ) ){\n        return new errorNode( \"nlFxn5\", \"The first values in the intOuts should be { 1, 2, 3 }\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( intOuts[ 1 ], answer10 ) ){\n        return new errorNode( \"nlFxn5\", \"The second values in the intOuts should be { -5, 6, 7, 8 }\" );\n    }\n\n    residual = { ( x[ 0 ] - 1. ) * ( x[ 0 ] + 1 ) * ( x[ 0 ] - 0.25 ) * ( x[ 0 ] + 0.1 ) };\n\n    jacobian = { {  ( x[ 0 ] + 1. ) * ( x[ 0 ] - 0.25 ) * ( x[ 0 ] + 0.1  )\n                  + ( x[ 0 ] - 1. ) * ( x[ 0 ] - 0.25 ) * ( x[ 0 ] + 0.1  )\n                  + ( x[ 0 ] - 1. ) * ( x[ 0 ] + 1.   ) * ( x[ 0 ] + 0.1  )\n                  + ( x[ 0 ] - 1. ) * ( x[ 0 ] + 1.   ) * ( x[ 0 ] - 0.25 ) } };\n\n    floatOuts = { floatOuts[ 0 ] + 0.1, floatOuts[ 1 ], floatOuts[ 0 ] };\n    intOuts = { intOuts[ 0 ] - 2, intOuts[ 0 ], intOuts[ 1 ] };\n\n    return NULL;\n}\n\nerrorOut nlFxn6( const floatVector &x, const floatMatrix &floatArgs, const intMatrix &intArgs,\n                 floatVector &residual, floatMatrix &jacobian, floatMatrix &floatOuts,\n                 intMatrix &intOuts ){\n    /*!\n     * A non-linear function for use in testing the solver which will require\n     * the use of the bounded homotopy solver. The function is of the form\n     * \n     * \\f$R = \\left [ \\left ( x - 1 \\right ) \\left ( x + 1 \\right ) \\left ( x - 0.25 \\right ) \\left ( x + 0.1 \\right ), \\left ( y - 1 \\right ) \\left ( y - 1 \\right ), \\left ( x + 5 \\right ) \\left ( z + 1 \\right ) \\right ]\\f$\n     *\n     * \\param &x: The variable vector. Three values required.\n     * \\param &floatArgs: Floating point arguments to the function. Unused.\n     * \\param &intArgs: Integer arguments to the function. Unused.\n     * \\param &residual: The residual vector output.\n     * \\param &jacobian: The jacobian output.\n     * \\param &floatOuts: Additional floating point outputs. Unused.\n     * \\param &intOuts: Additional integer outputs. Unused.\n     */\n\n    floatType x1 = x[ 0 ];\n    floatType x2 = x[ 1 ];\n    floatType x3 = x[ 2 ];\n\n    residual.resize( 3 );\n\n    residual[ 0 ] = ( x1 - 1 )*( x1 + 1 )*( x1 - 0.25 )*( x1 + 0.1 );\n    residual[ 1 ] = ( x2 - 1 ) * ( x2 - 1 );\n    residual[ 2 ] = ( x1 + 5 ) * ( x3 + 1 );\n\n    floatType dr1dx1 = ( x1 - 1 ) * ( x1 - 0.25 ) * ( x1 + 0.1 )\n                     + ( x1 - 1 ) * ( x1 - 0.25 ) * ( x1 + 1 )\n                     + ( x1 - 1 ) * ( x1 + 0.1 ) * ( x1 + 1 )\n                     + ( x1 - 0.25 ) * ( x1 + 0.1 ) * ( x1 + 1 );\n\n    floatType dr1dx2 = 0.;\n    floatType dr1dx3 = 0.;\n\n    floatType dr2dx1 = 0.;\n    floatType dr2dx2 = 2 * ( x2 - 1 );\n    floatType dr2dx3 = 0.;\n\n    floatType dr3dx1 = x3 + 1;\n    floatType dr3dx2 = 0.;\n    floatType dr3dx3 = x1 + 5;\n\n    jacobian = { { dr1dx1, dr1dx2, dr1dx3 },\n                 { dr2dx1, dr2dx2, dr2dx3 },\n                 { dr3dx1, dr3dx2, dr3dx3 } };\n\n    return NULL;\n}\n\nerrorOut nlFxn7( const floatVector &x, const floatMatrix &floatArgs, const intMatrix &intArgs,\n                 floatVector &residual, floatMatrix &jacobian, floatMatrix &floatOuts,\n                 intMatrix &intOuts ){\n    /*!\n     * A non-linear function for use in testing the solver which will require\n     * the use of the bounded homotopy solver. The function is of the form\n     *\n     * \\f$R = log( x )\\f$\n     * \n     * \\param &x: The variable vector. One value required.\n     * \\param &floatArgs: Floating point arguments to the function. Unused.\n     * \\param &intArgs: Integer arguments to the function. Unused.\n     * \\param &residual: The residual vector output.\n     * \\param &jacobian: The jacobian output.\n     * \\param &floatOuts: Additional floating point outputs. Unused.\n     * \\param &intOuts: Additional integer outputs. Unused.\n     */\n\n    if ( x.size( ) != 1 ){\n        return new errorNode( \"nlFxn7\", \"The x vector must have a size of 1\" );\n    }\n\n    residual = { std::log( x[ 0 ] ) };\n\n    jacobian = { { 1. / x[ 0 ] } };\n\n    return NULL;\n}\n\nerrorOut lagrangian1( const floatVector &x, const floatMatrix &floatArgs, const intMatrix &intArgs,\n                      floatType &value, floatVector &gradient, floatMatrix &floatOuts, intMatrix &intOuts ){\n    /*!\n     * A lagrangian used to test the optimization tools. The function is of the form.\n     * \n     * \\f$ L = ( x - 1 ) ( x + 3 )\\f$\n     * \n     * `floatOuts` is updated to\n     * \n     * \\f$floatOuts = \\left [ \\left [ 1, 2, 3 \\right ], \\left [ -0.4, -0.5, -0.6 \\right ] \\right ] \\f$\n     * \n     * `intOuts` is updated to\n     * \n     * \\f$intOuts = \\left [ \\left [ 5, 6, 7 \\right ], \\left [ 8 \\right ], \\left [ 9, 10 \\right ] \\right ]\\f$\n     *\n     * \\param &x: A vector of the variable to be solved. One value required.\n     * \\param &floatArgs: Additional floating point arguments to residual. Unused.\n     * \\param &intArgs: Additional integer arguments to the residual. Unused.\n     * \\param &value: The value of the Lagrangian\n     * \\param &gradient: The gradient of the Lagrangian\n     * \\param &floatOuts: Additional floating point values to return.\n     * \\param &intOuts: Additional integer values to return.\n     */\n\n    if ( x.size( ) != 1 ){\n        return new errorNode( \"lagrangian1\", \"The x vector must have a size of 1\" );\n    }\n\n    value = ( x[ 0 ] - 1 ) * ( x[ 0 ] + 3 );\n    gradient = { ( x[ 0 ] + 3 ) + ( x[ 0 ] - 1 ) };\n\n    floatOuts = { { 1, 2, 3 }, { -0.4, -0.5, -0.6 } };\n    intOuts = { { 5, 6, 7 }, { 8 }, { 9, 10 } };\n\n    return NULL;\n}\n\nerrorOut lagrangian2( const floatVector &x, const floatMatrix &floatArgs, const intMatrix &intArgs,\n                      floatType &value, floatVector &gradient, floatMatrix &floatOuts, intMatrix &intOuts ){\n    /*!\n     * A lagrangian used to test the optimization tools\n     *\n     * \\param &x: A vector of the variable to be solved.\n     * \\param &floatArgs: Additional floating point arguments to residual\n     * \\param &intArgs: Additional integer arguments to the residual\n     * \\param &value: The value of the Lagrangian\n     * \\param &gradient: The gradient of the Lagrangian\n     * \\param &floatOuts: Additional floating point values to return.\n     * \\param &intOuts: Additional integer values to return.\n     */\n\n    if ( x.size( ) != 3 ){\n        return new errorNode( \"lagrangian2\", \"The x vector must have a size of 3\" );\n    }\n\n    if ( floatOuts.size( ) != 1 ){\n        return new errorNode( \"lagrangian2\", \"The floatOuts must have a size of 1\" );\n    }\n\n    if ( intOuts.size( ) != 1 ){\n        return new errorNode( \"lagrangian2\", \"The intOuts must have a size of 1\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( floatOuts[ 0 ], { 0.1, 0.2, 0.3, 0.4 } ) ){\n        return new errorNode( \"lagrangian2\", \"The first value of the floatOuts is incorrect\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( intOuts[ 0 ], { -1, -2 } ) ){\n        return new errorNode( \"lagrangian2\", \"The first value of the intOuts is incorrect\" );\n    }\n\n    floatType _x = x[ 0 ];\n    floatType _y = x[ 1 ];\n    floatType _L = x[ 2 ];\n\n    value = _x + _y + _L * ( _x * _x + _y * _y - 1 );\n\n    gradient = { 1 + 2 * _L * _x,\n                 1 + 2 * _L * _y,\n                 _x * _x + _y * _y - 1 };\n\n    floatOuts = { { 1, 2, 3 }, { -0.4, -0.5, -0.6 }, { 7, 6, 5 } };\n    intOuts = { { -4 }, { 5, 6, 7 }, { 8 }, { 9, 10 } };\n\n    return NULL;\n}\n\nerrorOut lagrangian3( const floatVector &x, const floatMatrix &floatArgs, const intMatrix &intArgs,\n                      floatType &value, floatVector &gradient, floatMatrix &floatOuts, intMatrix &intOuts\n                    ){\n    /*!\n     * A lagrangian used to test the optimization tools. The function is of the form\n     * \n     * \\f$L = x^2 y + z * \\left ( x^2 y^2 - 3 \\right ) \\f$\n     * \n     * `floatOuts` is expected to have an incoming value of\n     * \n     * \\f$ floatOuts = \\left [ \\left [ 0.1, 0.2, 0.3, 0.4 \\right ] \\right ] \\f$\n     * \n     * `intOuts` is expected to have an incoming value of\n     * \n     * \\f$ intOuts = \\left [ \\left [ 0 \\right ], \\left [ -1, -2 \\right ] \\right ] \\f$\n     * \n     * `floatOuts is updated to\n     * \n     * \\f$ floatOuts = \\left [ \\left [ 1, 2, 3 \\right ], \\left [ -0.4, -0.5, -0.6 \\right ], \\left [ 7, 6, 5 \\right ] \\right ] \\f$\n     * \n     * `intOuts` is updated to\n     * \n     * \\f$ intOuts = \\left [ \\left [ -4 \\right ], \\left [ 5, 6, 7 \\right ], \\left [ 8 \\right ], \\left [ 9, 10 \\right ] \\right ] \\f$ \n     *\n     * \\param &x: A vector of the variable to be solved.\n     * \\param &floatArgs: Additional floating point arguments to residual\n     * \\param &intArgs: Additional integer arguments to the residual\n     * \\param &value: The value of the Lagrangian\n     * \\param &gradient: The gradient of the Lagrangian\n     * \\param &floatOuts: Additional floating point values to return.\n     * \\param &intOuts: Additional integer values to return.\n     */\n\n    if ( x.size( ) != 3 ){\n        return new errorNode( \"lagrangian3\", \"The x vector must have a size of 3\" );\n    }\n\n    if ( floatOuts.size( ) != 1 ){\n        return new errorNode( \"lagrangian3\", \"The floatOuts must have a size of 1\" );\n    }\n\n    if ( intOuts.size( ) != 1 ){\n        return new errorNode( \"lagrangian3\", \"The intOuts must have a size of 1\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( floatOuts[ 0 ], { 0.1, 0.2, 0.3, 0.4 } ) ){\n        return new errorNode( \"lagrangian3\", \"The first value of the floatOuts is incorrect\" );\n    }\n\n    if ( !vectorTools::fuzzyEquals( intOuts[ 0 ], { -1, -2 } ) ){\n        return new errorNode( \"lagrangian3\", \"The first value of the intOuts is incorrect\" );\n    }\n\n    floatType _x = x[ 0 ];\n    floatType _y = x[ 1 ];\n    floatType _L = x[ 2 ];\n\n    value = _x * _x * _y + _L * ( _x * _x + _y * _y - 3 );\n\n    gradient = { 2 * _x * _y + 2 * _L * _x,\n                 _x * _x + 2 * _L * _y,\n                 _x * _x + _y * _y - 3 };\n\n    floatOuts = { { 1, 2, 3 }, { -0.4, -0.5, -0.6 }, { 7, 6, 5 } };\n    intOuts = { { -4 }, { 5, 6, 7 }, { 8 }, { 9, 10 } };\n\n    return NULL;\n}\n\nBOOST_AUTO_TEST_CASE( testCheckTolerance ){\n    /*!\n     * Test the tolerance checking function.\n     */\n\n    floatVector R   = {  1,   2, 3.00000, -4.0 };\n    floatVector tol = { 1.5, 2.1, 3.00001,  4.1 };\n    bool result;\n\n    errorOut error = solverTools::checkTolerance( R, tol, result );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( result );\n\n    tol[ 0 ] = .98;\n\n    error = solverTools::checkTolerance( R, tol, result );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( ! result );\n\n    tol[ 0 ] = 1.5;\n    tol[ 3 ] = 3.8;\n    error = solverTools::checkTolerance( R, tol, result );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( ! result );\n\n    tol = { 1.6, 2.5 };\n\n    error = solverTools::checkTolerance( R, tol, result );\n\n    BOOST_CHECK( error );\n\n}\n\nBOOST_AUTO_TEST_CASE( testNewtonRaphson ){\n    /*!\n     * Tests of the Newton-Raphson solver\n     * \n     * \\param &results: The output file\n     */\n\n    //The first test\n    floatVector x0 = { 1.5, 6 };\n    floatVector x;\n    bool converged, fatalError;\n\n    solverTools::stdFncNLFJ func;\n    func = static_cast< solverTools::NonLinearFunctionWithJacobian >( nlFxn1 );\n\n    floatMatrix floatOut;\n    intMatrix intOut;    \n    errorOut error = solverTools::newtonRaphson( func, x0, x, converged, fatalError, floatOut, intOut, { }, { } );\n\n    BOOST_CHECK( ! error );\n\n    floatVector Rtmp;\n    floatMatrix Jtmp;\n    floatMatrix fO;\n    intMatrix iO;\n    error = nlFxn1( x, { }, { }, Rtmp, Jtmp, fO, iO );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( Rtmp, { 0, 0 } ) );\n\n    //The second test\n    x0 = { 1, 1, 1 };\n    floatOut.clear( );\n    intOut.clear( );\n    fO.clear( );\n    iO.clear( );\n\n    func = static_cast< solverTools::NonLinearFunctionWithJacobian >( nlFxn2 );\n    error = solverTools::newtonRaphson( func, x0, x, converged, fatalError, floatOut, intOut, { }, { } );\n\n    BOOST_CHECK( ! error );\n\n    error = nlFxn2( x, { }, { }, Rtmp, Jtmp, fO, iO );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( Rtmp, { 0, 0, 0 } ) );\n\n    //The third test\n    x0 = { 3 };\n    floatOut.clear( );\n    intOut.clear( );\n    fO.clear( );\n    iO.clear( );\n    \n    func = static_cast< solverTools::NonLinearFunctionWithJacobian >( nlFxn3 );\n    error = solverTools::newtonRaphson( func, x0, x, converged, fatalError, floatOut, intOut, { }, { } );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( x, { 0 } ) );\n\n    //The fourth test. Tests the bounded Newton method\n    x0 = { 10. };\n    floatOut.clear( );\n    intOut.clear( );\n    fO.clear( );\n    iO.clear( );\n\n    func = static_cast< solverTools::NonLinearFunctionWithJacobian >( nlFxn7 );\n\n    solverTools::solverType linearSolver;\n    floatMatrix J;\n\n    intVector boundVariableIndices = { 0 };\n    intVector boundSigns = { 0 };\n    floatVector boundValues = { 1e-9 };\n    floatMatrix Jexp = { { 1. } };\n\n    error = solverTools::newtonRaphson( func, x0, x, converged, fatalError, floatOut, intOut, { }, { }, linearSolver, J );\n\n    BOOST_CHECK( ! error );\n    BOOST_CHECK( vectorTools::fuzzyEquals( x, { 1. } ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( J, Jexp ) );\n\n    //The fifth test: This test makes sure that when a Newton-Raphson iteration fails it\n    //correctly returns a failure to converge.\n    x0 = { -5. };\n    floatOut.clear( );\n    intOut.clear( );\n\n    func = static_cast< solverTools::NonLinearFunctionWithJacobian >( nlFxn4 );\n\n    error = solverTools::newtonRaphson( func, x0, x, converged, fatalError, floatOut, intOut, { }, { }, 5 );\n\n    BOOST_CHECK( ! converged );\n\n}\n\nBOOST_AUTO_TEST_CASE( testFiniteDifference ){\n    /*!\n     * Test the finite difference jacobian calculator.\n     */\n\n    //The first test\n    floatVector x0 = { 1.5, 6 };\n    floatMatrix J;\n\n    solverTools::stdFncNLF func;\n    func = static_cast<solverTools::NonLinearFunction>( nlFxn1 );\n    solverTools::finiteDifference( func, x0, J, { }, { } );\n\n    floatVector Rtmp;\n    floatMatrix result;\n    floatMatrix floatOuts;\n    intMatrix intOuts;\n    nlFxn1( x0, { }, { }, Rtmp, result, floatOuts, intOuts );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( J, result ) );\n\n    //The second test\n    x0 = { 1, 1, 1 };\n    floatOuts.clear( );\n    intOuts.clear( );\n    func = static_cast<solverTools::NonLinearFunction>( nlFxn2 );\n    solverTools::finiteDifference( func, x0, J, { }, { } );\n    nlFxn2( x0, { }, { }, Rtmp, result, floatOuts, intOuts );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( J, result ) );\n\n}\n\nBOOST_AUTO_TEST_CASE( testCheckJacobian ){\n    /*!\n     * Test the jacobian checking utility.\n     */\n\n    //The first test\n\n    solverTools::stdFncNLFJ func;\n    func = static_cast<solverTools::NonLinearFunctionWithJacobian>( nlFxn1 );\n    bool isGood = false;\n    floatType eps = 1e-6;\n    floatType tolr = 1e-6;\n    floatType tola = 1e-6;\n    bool suppressOutput = true;\n\n    floatVector x0 = { 0, 0 };\n    errorOut error = solverTools::checkJacobian( func, x0, { }, { }, isGood, eps, tolr, tola, suppressOutput );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( isGood );\n\n    //The second test\n    solverTools::stdFncNLFJ badfunc;\n    badfunc = [ & ]( const floatVector &x_, const floatMatrix &floatArgs_, const intMatrix &intArgs_,\n                            floatVector &r, floatMatrix &j, floatMatrix &fO, intMatrix &iO ){\n        errorOut e = func( x_, floatArgs_, intArgs_, r, j, fO, iO );\n        j[ 0 ][ 1 ] = 0.1;\n        return e;\n    }; \n\n    error = solverTools::checkJacobian( badfunc, x0, { }, { }, isGood, eps, tolr, tola, suppressOutput );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( ! isGood );\n\n}\n\nBOOST_AUTO_TEST_CASE( testCheckLSCriteria ){\n    /*!\n     * Test the line search criteria\n     */\n\n    floatVector R  = { 1, 2, 3, 4, 5, 6 };\n    floatVector Rp = { 2, 3, 4, 5, 6, 7 };\n    bool result;\n\n    solverTools::checkLSCriteria( R, Rp, result );\n\n    BOOST_CHECK( result );\n\n    R[ 0 ] = 100;\n\n    solverTools::checkLSCriteria( R, Rp, result );\n\n    BOOST_CHECK( ! result );\n\n}\n\nBOOST_AUTO_TEST_CASE( testHomotopySolver ){\n    /*!\n     * Test the Homotopy solver.\n     */\n\n    //The first test\n    floatVector x0 = { 1.5, 6 };\n    floatVector x;\n    bool converged, fatalErrorFlag;\n    floatMatrix floatOuts;\n    intMatrix intOuts;\n\n    solverTools::stdFncNLFJ func;\n    func = static_cast< solverTools::NonLinearFunctionWithJacobian >( nlFxn1 );\n   \n    errorOut error = solverTools::homotopySolver( func, x0, x, converged, fatalErrorFlag, floatOuts, intOuts, { }, { } );\n\n    BOOST_CHECK( ! error );\n\n    floatVector Rtmp;\n    floatMatrix Jtmp;\n    floatMatrix fO;\n    intMatrix iO;\n    error = nlFxn1( x, { }, { }, Rtmp, Jtmp, fO, iO );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( Rtmp, { 0, 0 } ) );\n\n    //The second test\n    x0 = { 1, 1, 1 };\n    floatOuts.clear( );\n    intOuts.clear( );\n    fO.clear( );\n    iO.clear( );\n\n    func = static_cast< solverTools::NonLinearFunctionWithJacobian >( nlFxn2 );\n    error = solverTools::homotopySolver( func, x0, x, converged, fatalErrorFlag, floatOuts, intOuts, { }, { } );\n\n    BOOST_CHECK( ! error );\n\n    error = nlFxn2( x, { }, { }, Rtmp, Jtmp, fO, iO );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( Rtmp, { 0, 0, 0 } ) );\n\n    //The third test\n    x0 = { 3 };\n    floatOuts.clear( );\n    intOuts.clear( );\n    fO.clear( );\n    iO.clear( );\n    \n    func = static_cast< solverTools::NonLinearFunctionWithJacobian >( nlFxn3 );\n    error = solverTools::homotopySolver( func, x0, x, converged, fatalErrorFlag, floatOuts, intOuts, { }, { },\n                                         20, 1e-9, 1e-9, 1e-4, 5, 0.2, 0.01 );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( x, { 0 } ) );\n\n    //The fourth test\n    x0 = { 3 };\n    floatOuts.clear( );\n    intOuts.clear( );\n\n    func = static_cast< solverTools::NonLinearFunctionWithJacobian >( nlFxn4 );\n\n    error = solverTools::homotopySolver( func, x0, x, converged, fatalErrorFlag, floatOuts, intOuts, { }, { },\n                                         20, 1e-9, 1e-9, 1e-4, 4, 1.0, 0.1 );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( x, { 0 } ) );\n\n    //The fifth test ( hard bounds )\n    x0 = { 10 };\n    floatOuts.clear( );\n    intOuts.clear( );\n\n    solverTools::solverType linearSolver;\n    floatMatrix J, Jexp;\n\n    Jexp = { { 1 } };\n\n    intVector variableIndices = { 0 };\n    intVector barrierSigns = { 0 };\n    floatVector barrierValues = { 1e-9 };\n\n    func = static_cast< solverTools::NonLinearFunctionWithJacobian >( nlFxn7 );\n\n    error = solverTools::homotopySolver( func, x0, x, converged, fatalErrorFlag, floatOuts, intOuts, { }, { },\n                                         linearSolver, J, variableIndices, barrierSigns, barrierValues,\n                                         false, 20, 1e-9, 1e-9, 1e-4, 4, 1.0, 0.1 );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( x, { 1 } ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( J, Jexp ) );\n\n    \n}\n\nBOOST_AUTO_TEST_CASE( test_aFxn ){\n    /*!\n     * Test the computation of the \"\\f$a\\f$\" parameter in the Barrier function.\n     */\n\n    floatType pseudoT = .72;\n    floatType logAfxn = 5.2;\n\n    floatType answer  = 42.26671935907283;\n\n    floatType result;\n\n    errorOut error = solverTools::aFxn( pseudoT, logAfxn, result );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( result, answer ) );\n\n    floatType dadT;\n\n    error = solverTools::aFxn( pseudoT, logAfxn, result, dadT );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( result, answer ) );\n\n    floatType eps = 1e-6;\n    floatType delta = eps * pseudoT + eps;\n\n    floatType aP, aM;\n\n    error = solverTools::aFxn( pseudoT + delta, logAfxn, aP );\n\n    BOOST_CHECK( ! error );\n\n    error = solverTools::aFxn( pseudoT - delta, logAfxn, aM );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( ( aP - aM ) / ( 2 * delta ), dadT ) );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_computeBarrierFunction ){\n    /*!\n     * Test the computation of the boundary function\n     */\n\n    floatType x        = 0.4;\n    floatType pseudoT  = 0.25;\n    floatType logAmax  = 5;\n    floatType b        = 0.14;\n\n    floatType negativeSignAnswer = -0.5964638357684787;\n    floatType positiveSignAnswer = 1.4780926435784547;\n\n    floatType result;\n\n    errorOut error = solverTools::computeBarrierFunction( x, pseudoT, logAmax, b, false, result );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( result, negativeSignAnswer ) );\n\n    error = solverTools::computeBarrierFunction( x, pseudoT, logAmax, b, true, result );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( result, positiveSignAnswer ) );\n\n    //Test the Jacobians\n    floatType dbdx, dbdt;\n\n    //Test the Jacobians when the sign is negative\n    error = solverTools::computeBarrierFunction( x, pseudoT, logAmax, b, false, result, dbdx, dbdt );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( result, negativeSignAnswer ) );\n\n    floatType eps = 1e-6;\n\n    floatType dx = eps * fabs( x ) + eps;\n    floatType dt = eps * fabs( pseudoT ) + eps;\n\n    floatType bP, bM;\n\n    error = solverTools::computeBarrierFunction( x + dx, pseudoT, logAmax, b, false, bP );\n\n    BOOST_CHECK( ! error );\n\n    error = solverTools::computeBarrierFunction( x - dx, pseudoT, logAmax, b, false, bM );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( ( bP - bM ) / ( 2 * dx ), dbdx ) );\n\n    error = solverTools::computeBarrierFunction( x, pseudoT + dt, logAmax, b, false, bP );\n\n    BOOST_CHECK( ! error );\n\n    error = solverTools::computeBarrierFunction( x, pseudoT - dt, logAmax, b, false, bM );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( ( bP - bM ) / ( 2 * dt ), dbdt ) );\n\n    //Test the Jacobians when the sign is positive\n    error = solverTools::computeBarrierFunction( x, pseudoT, logAmax, b, true, result, dbdx, dbdt );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( result, positiveSignAnswer ) );\n\n    error = solverTools::computeBarrierFunction( x + dx, pseudoT, logAmax, b, true, bP );\n\n    BOOST_CHECK( ! error );\n\n    error = solverTools::computeBarrierFunction( x - dx, pseudoT, logAmax, b, true, bM );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( ( bP - bM ) / ( 2 * dx ), dbdx ) );\n\n    error = solverTools::computeBarrierFunction( x, pseudoT + dt, logAmax, b, true, bP );\n\n    BOOST_CHECK( ! error );\n\n    error = solverTools::computeBarrierFunction( x, pseudoT - dt, logAmax, b, true, bM );\n\n    BOOST_CHECK( ! error );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( ( bP - bM ) / ( 2 * dt ), dbdt ) );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_computeBarrierHomotopyResidual ){\n    /*!\n     * Test the computation of the barrier homotopy residual\n     */\n\n\n    solverTools::stdFncNLFJ func;\n    func = static_cast<solverTools::NonLinearFunctionWithJacobian>( nlFxn5 );\n\n    floatVector x0 = { 0. };\n    floatMatrix floatArgsDefault =\n        {\n            { 0.28 }, //The pseudo-time\n            { 0.1 },  //The barrier value\n            { 10. },  //The logAMax values\n            { .1, .2, .3, .4 }, //Function Parameters\n            { -0.01, -0.02 }\n        };\n\n    intMatrix intArgsDefault =\n        {\n            { 0 }, //Variable indices\n            { 0 }, //Residual indices\n            { 0 }, //Barrier signs\n            { -1, -2, -3 }, //Function parameters\n            { 5, 4, 3, 2 },\n            { 8, 9, 9 }\n        };\n\n    floatVector residualResult;\n    floatMatrix jacobian;\n\n    floatMatrix floatOutsDefault =\n        {\n            { 0, 1, 2 },\n            { 7, -6 },\n            { .24, .25 }\n        };\n\n    intMatrix intOutsDefault =\n        {\n            { 1, 2, 3 },\n            { -5, 6, 7, 8 },\n        };\n\n    floatMatrix floatArgs = floatArgsDefault;\n    intMatrix   intArgs   = intArgsDefault;\n    floatMatrix floatOuts = floatOutsDefault;\n    intMatrix   intOuts   = intOutsDefault;\n\n    floatVector residualAnswer = { 0.2775586103363596 };\n\n#ifdef DEBUG_MODE\n    debugMap DEBUG;\n#endif\n\n    errorOut error = solverTools::computeBarrierHomotopyResidual( func, x0, floatArgs, intArgs, residualResult, jacobian,\n                                                                  floatOuts, intOuts\n#ifdef DEBUG_MODE\n                                                                  , DEBUG\n#endif\n                                                                );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( residualAnswer, residualResult ) );\n\n    //Check that the non-homotopy outputs are as expected.\n    BOOST_CHECK( floatOuts.size( ) == 4 );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( floatOuts[ 1 ], floatOutsDefault[ 0 ] + 0.1 ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( floatOuts[ 2 ], floatOutsDefault[ 1 ] ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( floatOuts[ 3 ], floatOutsDefault[ 0 ] ) );\n\n    BOOST_CHECK( intOuts.size( ) == 3 );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( intOuts[ 0 ], intOutsDefault[ 0 ] - 2 ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( intOuts[ 1 ], intOutsDefault[ 0 ] ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( intOuts[ 2 ], intOutsDefault[ 1 ] ) );\n\n    //Test the Jacobians\n    floatType eps = 1e-6;\n\n    //Test drdx\n    floatVector dx = eps * x0 + eps;\n\n    floatVector rP, rM;\n    floatMatrix JP, JM;\n\n    floatOuts = floatOutsDefault;\n    intOuts   = intOutsDefault;\n\n    error = solverTools::computeBarrierHomotopyResidual( func, x0 + dx, floatArgs, intArgs, rP, JP,\n                                                         floatOuts, intOuts );\n\n    BOOST_CHECK( ! error  );\n\n    floatOuts = floatOutsDefault;\n    intOuts   = intOutsDefault;\n\n    error = solverTools::computeBarrierHomotopyResidual( func, x0 - dx, floatArgs, intArgs, rM, JM,\n                                                         floatOuts, intOuts );\n\n    BOOST_CHECK( ! error  );\n\n    floatVector gradCol = ( rP - rM ) / ( 2 * dx[ 0 ] );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( gradCol, jacobian[ 0 ] ) );\n\n    //test drdt\n    eps = 1e-7;\n    floatType dt = eps * floatArgsDefault[ 0 ][ 0 ] + eps;\n\n    floatArgs = floatArgsDefault;\n    floatArgs[ 0 ][ 0 ] += dt;\n\n    floatOuts = floatOutsDefault;\n    intOuts   = intOutsDefault;\n\n    error = solverTools::computeBarrierHomotopyResidual( func, x0, floatArgs, intArgs, rP, JP,\n                                                         floatOuts, intOuts );\n\n    BOOST_CHECK( ! error  );\n\n    floatArgs = floatArgsDefault;\n    floatArgs[ 0 ][ 0 ] -= dt;\n\n    floatOuts = floatOutsDefault;\n    intOuts   = intOutsDefault;\n\n    error = solverTools::computeBarrierHomotopyResidual( func, x0, floatArgs, intArgs, rM, JM,\n                                                         floatOuts, intOuts );\n\n    BOOST_CHECK( ! error  );\n\n    gradCol = ( rP - rM ) / ( 2 * dt );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( gradCol, floatOuts[ 0 ], 1e-5 ) );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_computeBarrierHomotopyResidual2 ){\n    /*!\n     * Test for the computation of the barrier homotopy residual.\n     */\n\n\n    solverTools::stdFncNLFJ func;\n    func = static_cast<solverTools::NonLinearFunctionWithJacobian>( nlFxn6 );\n\n    floatVector          x = { 0.15, 0.1, -1.2 };\n    floatType   pseudoTime = 0.24;\n\n    floatVector logAMaxVals = { 10, 6 };\n    floatVector bvals       = { 0.1, -1.1 };\n\n    intVector   variableIndices = { 0, 2 };\n    intVector   residualIndices = { 2, 1 };\n    intVector   signs           = { 0, 1 };\n\n    floatMatrix floatArgs = { { pseudoTime }, bvals, logAMaxVals };\n    intMatrix   intArgs   = { variableIndices, residualIndices, signs };\n\n    floatMatrix floatOuts = { { } };\n    intMatrix   intOuts   = { { } };\n\n    floatVector residualAnswer = { 0.0244375 ,  0.53651154, -0.97499937 };\n\n    floatVector residualResult;\n    floatMatrix jacobian;\n\n    errorOut error = solverTools::computeBarrierHomotopyResidual( func, x, floatArgs, intArgs, residualResult, jacobian,\n                                                                  floatOuts, intOuts );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( residualResult, residualAnswer ) );\n\n    //Tests of the Jacobians\n\n    //Test the Jacobian w.r.t. x\n    floatType eps = 1e-7;\n    for ( unsigned int i = 0; i < x.size( ); i++ ){\n        floatVector delta( x.size( ), 0 );\n        delta[ i ] = eps * fabs( x[ i ] ) + eps;\n\n        floatVector rP, rM;\n\n        error = solverTools::computeBarrierHomotopyResidual( func, x + delta, floatArgs, intArgs, rP, jacobian,\n                                                             floatOuts, intOuts );\n\n        BOOST_CHECK( ! error  );\n\n        error = solverTools::computeBarrierHomotopyResidual( func, x - delta, floatArgs, intArgs, rM, jacobian,\n                                                             floatOuts, intOuts );\n\n        BOOST_CHECK( ! error  );\n\n        floatVector gradCol = ( rP - rM ) / ( 2 * delta[ i ] );\n\n        for ( unsigned int j = 0; j < gradCol.size( ); j++ ){\n            BOOST_CHECK( vectorTools::fuzzyEquals( gradCol[ j ], jacobian[ j ][ i ] ) );\n        }\n    }\n\n    //Test the Jacobian w.r.t. t\n    floatType dt = eps * fabs( pseudoTime ) + eps;\n\n    floatVector rP, rM;\n\n    floatArgs[ 0 ][ 0 ] = pseudoTime + dt;\n\n    error = solverTools::computeBarrierHomotopyResidual( func, x, floatArgs, intArgs, rP, jacobian,\n                                                         floatOuts, intOuts );\n\n    BOOST_CHECK( ! error  );\n\n    floatArgs[ 0 ][ 0 ] = pseudoTime - dt;\n\n    error = solverTools::computeBarrierHomotopyResidual( func, x, floatArgs, intArgs, rM, jacobian,\n                                                         floatOuts, intOuts );\n\n    BOOST_CHECK( ! error  );\n\n    floatVector gradCol = ( rP - rM ) / ( 2 * dt );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( gradCol, floatOuts[ 0 ] ) );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_barrierHomotopySolver ){\n    /*!\n     * Test the barrier Homotopy solver. This solver enables the addition of\n     * bounds to a non-linear solve which can help prevent solutions from being\n     * pulled into undesirable domains without having to resort to computing the\n     * Hessian of the residual function as would be required for optimization\n     * based techniques.\n     */\n\n    solverTools::stdFncNLFJ func;\n    func = static_cast<solverTools::NonLinearFunctionWithJacobian>( nlFxn5 );\n\n    floatVector barrierValues = { 0.1 };\n    floatVector logAMaxValues = { 10. };\n    floatMatrix floatArgsDefault =\n        {\n            { .1, .2, .3, .4 },\n            { -0.01, -0.02 }\n        };\n\n    intVector variableIndices = { 0 };\n    intVector residualIndices = { 0 };\n    intVector barrierSigns    = { 0 };\n\n    intMatrix intArgsDefault =\n        {\n            { -1, -2, -3 },\n            { 5, 4, 3, 2 },\n            { 8, 9, 9 }\n        };\n\n    floatVector residualResult;\n    floatMatrix jacobian;\n\n    floatMatrix floatOutsDefault =\n        {\n            { 0, 1, 2 },\n            { 7, -6 },\n            { .24, .25 }\n        };\n\n    intMatrix intOutsDefault =\n        {\n            { 1, 2, 3 },\n            { -5, 6, 7, 8 },\n        };\n\n    floatMatrix floatArgs = floatArgsDefault;\n    intMatrix   intArgs   = intArgsDefault;\n    floatMatrix floatOuts = floatOutsDefault;\n    intMatrix   intOuts   = intOutsDefault;\n\n    floatType dt = 0.1;\n    floatVector x0 = { 0. };\n    bool implicitRefine = false;\n\n    bool convergeFlag, fatalErrorFlag;\n\n    floatVector result;\n    floatVector answer = { 0.25 };\n\n    errorOut error = solverTools::barrierHomotopySolver( func, dt, x0, variableIndices, residualIndices, barrierSigns,\n                                                         barrierValues, logAMaxValues, floatArgs, intArgs,\n                                                         implicitRefine, result, convergeFlag, fatalErrorFlag,\n                                                         floatOuts, intOuts,\n                                                         20, 1e-9, 1e-9, 1e-4, 5, true );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( answer, result ) );\n\n    floatOuts = floatOutsDefault;\n    intOuts = intOutsDefault;\n\n    solverTools::solverType linearSolver;\n\n    error = solverTools::barrierHomotopySolver( func, dt, x0, variableIndices, residualIndices, barrierSigns,\n                                                         barrierValues, logAMaxValues, floatArgs, intArgs,\n                                                         implicitRefine, result, convergeFlag, fatalErrorFlag,\n                                                         floatOuts, intOuts, linearSolver, jacobian,\n                                                         20, 1e-9, 1e-9, 1e-4, 5, true );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( answer, result ) );\n\n    floatMatrix jacobianResult;\n\n    floatOuts = floatOutsDefault;\n    intOuts = intOutsDefault;\n\n    error = func( result, floatArgs, intArgs, residualResult, jacobianResult, floatOuts, intOuts );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( jacobian, jacobianResult ) );\n\n    x0 = { 0. };\n    implicitRefine = true;\n\n    floatOuts = floatOutsDefault;\n    intOuts = intOutsDefault;\n\n    error = solverTools::barrierHomotopySolver( func, dt, x0, variableIndices, residualIndices, barrierSigns,\n                                                barrierValues, logAMaxValues, floatArgs, intArgs,\n                                                implicitRefine, result, convergeFlag, fatalErrorFlag,\n                                                floatOuts, intOuts,\n                                                20, 1e-9, 1e-9, 1e-4, 5, true );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( answer, result ) );\n\n    floatOuts = floatOutsDefault;\n    intOuts = intOutsDefault;\n\n    error = solverTools::barrierHomotopySolver( func, dt, x0, variableIndices, residualIndices, barrierSigns,\n                                                barrierValues, logAMaxValues, floatArgs, intArgs,\n                                                implicitRefine, result, convergeFlag, fatalErrorFlag,\n                                                floatOuts, intOuts, linearSolver, jacobian,\n                                                20, 1e-9, 1e-9, 1e-4, 5, true );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( answer, result ) );\n\n    floatOuts = floatOutsDefault;\n    intOuts = intOutsDefault;\n\n    error = func( result, floatArgs, intArgs, residualResult, jacobianResult, floatOuts, intOuts );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( jacobian, jacobianResult ) );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_applyBoundaryLimitation ){\n    /*!\n     * Test of the application of the boundary conditions.\n     *\n     * \\param &results: The output file\n     */\n\n    floatVector x0 = { 1.0,  2.0, 3.0, -1.0, -2.0, -3.0 };\n    floatVector dxDefault = { 0.1, -0.5, 1.0,  0.1,  2.1, -0.5 };\n\n    intVector variableIndices = {    0,    3, 4   };\n    intVector barrierSigns    = {    1,    0, 1   };\n    floatVector barrierValues = { 1.05, -1.0, 0.0 };\n\n    floatVector dx = dxDefault;\n\n    floatVector xAnswer1 = { 1.05, 1.75, 3.5, -0.95, -0.95, -3.25 };\n    floatVector xAnswer2 = { 1.033333, 1.833333, 3.333333, -1, -1.3, -3.1666667 };\n    floatVector xAnswer3 = { 1.05, 1.5, 4, -0.8, 0.0, -3.5 };\n\n    errorOut error = solverTools::applyBoundaryLimitation( x0, variableIndices, barrierSigns, barrierValues, dx );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( x0 + dx, xAnswer1 ) );\n\n    dx = dxDefault;\n    x0[ 3 ] = -0.9;\n    dx[ 3 ] = -0.3;\n\n    error = solverTools::applyBoundaryLimitation( x0, variableIndices, barrierSigns, barrierValues, dx );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( x0 + dx, xAnswer2 ) );\n\n    dx = dxDefault;\n    error = solverTools::applyBoundaryLimitation( x0, variableIndices, barrierSigns, barrierValues, dx, 1e-9, 1e-9, true );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( x0 + dx, xAnswer3 ) );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_BFGS ){\n    /*!\n     * Test of the BFGS optimization algorithm.\n     */\n\n    solverTools::stdFncLagrangianG func;\n    func = static_cast<solverTools::LagrangianFunctionWithGradient>( lagrangian1 );\n\n    solverTools::floatVector x0 = { 0. };\n    solverTools::floatVector x;\n\n    bool convergeFlag, fatalErrorFlag;\n    solverTools::floatMatrix floatArgs, floatOuts;\n    solverTools::intMatrix intArgs, intOuts;\n\n    floatVector xAnswer = { -1 };\n    floatMatrix floatOutsAnswer = { { 1, 2, 3 }, { -0.4, -0.5, -0.6 } };\n    intMatrix intOutsAnswer = { { 5, 6, 7 }, { 8 }, { 9, 10 } };\n\n    errorOut error = solverTools::BFGS( func, x0, x, convergeFlag, fatalErrorFlag,\n                                        floatOuts, intOuts, floatArgs, intArgs );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( x, xAnswer ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( floatOuts, floatOutsAnswer ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( intOuts, intOutsAnswer ) );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_BFGS2 ){\n    /*!\n     * Test of the BFGS optimization algorithm.\n     */\n\n    solverTools::stdFncLagrangianG func;\n    func = static_cast<solverTools::LagrangianFunctionWithGradient>( lagrangian2 );\n\n    solverTools::floatVector x0 = { 0., 0., 0. };\n    solverTools::floatVector x;\n\n    bool convergeFlag, fatalErrorFlag;\n    solverTools::floatMatrix floatArgs, floatOuts;\n    solverTools::intMatrix intArgs, intOuts;\n\n    floatOuts = { { .1, .2, .3, .4 } };\n    intOuts = { { -1, -2 } };\n\n    floatVector xAnswer = { -std::sqrt( 2. ) / 2, -std::sqrt( 2. ) / 2 };\n    floatMatrix floatOutsAnswer = { { 1, 2, 3 }, { -0.4, -0.5, -0.6 }, { 7, 6, 5 } };\n    intMatrix intOutsAnswer = { { -4 }, { 5, 6, 7 }, { 8 }, { 9, 10 } };\n\n    errorOut error = solverTools::BFGS( func, x0, x, convergeFlag, fatalErrorFlag,\n                                        floatOuts, intOuts, floatArgs, intArgs,\n                                        20, 1e-9, 1e-9, 1e-4, 5, true\n                                      );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( { x[ 0 ], x[ 1 ] }, xAnswer ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( floatOuts, floatOutsAnswer ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( intOuts, intOutsAnswer ) );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_homotopyBFGS ){\n    /*!\n     * Test of the homotopy BFGS optimization algorithm.\n     */\n\n    solverTools::stdFncLagrangianG func;\n    func = static_cast<solverTools::LagrangianFunctionWithGradient>( lagrangian1 );\n\n    solverTools::floatVector x0 = { 0. };\n    solverTools::floatVector x;\n\n    bool convergeFlag, fatalErrorFlag;\n    solverTools::floatMatrix floatArgs, floatOuts;\n    solverTools::intMatrix intArgs, intOuts;\n\n    floatVector xAnswer = { -1 };\n    floatMatrix floatOutsAnswer = { { 1, 2, 3 }, { -0.4, -0.5, -0.6 } };\n    intMatrix intOutsAnswer = { { 5, 6, 7 }, { 8 }, { 9, 10 } };\n\n    errorOut error = solverTools::homotopyBFGS( func, x0, x, convergeFlag, fatalErrorFlag,\n                                                floatOuts, intOuts, floatArgs, intArgs,\n                                                100, 1e-9, 1e-9, 1e-4, 10, 1.0, 0.1, true, 1.0\n                                              );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( x, xAnswer ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( floatOuts, floatOutsAnswer ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( intOuts, intOutsAnswer ) );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_homotopyBFGS2 ){\n    /*!\n     * Test of the BFGS optimization algorithm.\n     */\n\n    solverTools::stdFncLagrangianG func;\n    func = static_cast<solverTools::LagrangianFunctionWithGradient>( lagrangian2 );\n\n    solverTools::floatVector x0 = { 0., 0., 0. };\n    solverTools::floatVector x;\n\n    bool convergeFlag, fatalErrorFlag;\n    solverTools::floatMatrix floatArgs, floatOuts;\n    solverTools::intMatrix intArgs, intOuts;\n\n    floatOuts = { { .1, .2, .3, .4 } };\n    intOuts = { { -1, -2 } };\n\n    floatVector xAnswer = { -std::sqrt( 2. ) / 2, -std::sqrt( 2. ) / 2 };\n    floatMatrix floatOutsAnswer = { { 1, 2, 3 }, { -0.4, -0.5, -0.6 }, { 7, 6, 5 } };\n    intMatrix intOutsAnswer = { { -4 }, { 5, 6, 7 }, { 8 }, { 9, 10 } };\n\n    errorOut error = solverTools::homotopyBFGS( func, x0, x, convergeFlag, fatalErrorFlag,\n                                                floatOuts, intOuts, floatArgs, intArgs,\n                                                100, 1e-9, 1e-9, 1e-4, 10, 1.0, 0.1, true, 1.0\n                                              );\n\n    BOOST_CHECK( ! error  );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( { x[ 0 ], x[ 1 ] }, xAnswer ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( floatOuts, floatOutsAnswer ) );\n\n    BOOST_CHECK( vectorTools::fuzzyEquals( intOuts, intOutsAnswer ) );\n\n}\n", "meta": {"hexsha": "eabf75f8e887567154b6f2fecb5401b02d679d3b", "size": 54533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/tests/test_solver_tools.cpp", "max_stars_repo_name": "lanl/tardigrade-solver-tools", "max_stars_repo_head_hexsha": "757ecdbc48a509e6fd288bc62e1892a08afb2ccd", "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/tests/test_solver_tools.cpp", "max_issues_repo_name": "lanl/tardigrade-solver-tools", "max_issues_repo_head_hexsha": "757ecdbc48a509e6fd288bc62e1892a08afb2ccd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/tests/test_solver_tools.cpp", "max_forks_repo_name": "lanl/tardigrade-solver-tools", "max_forks_repo_head_hexsha": "757ecdbc48a509e6fd288bc62e1892a08afb2ccd", "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.0904126214, "max_line_length": 224, "alphanum_fraction": 0.574826252, "num_tokens": 16930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489892, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.5299226422877121}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.                \n */\n#pragma once\n\n#include <Eigen/Dense>\n#include <dpMM/basemeasure.hpp>\n#include <dpMM/sphere.hpp>\n\nusing namespace Eigen;\n\ntemplate<typename T>\nclass UnifSphere : public BaseMeasure<T>\n{\npublic:\n\n  uint32_t D_; // dimensionality of the space in which the sphere lies\n  Sphere<T> S_;\n\n  UnifSphere(uint32_t D);\n  ~UnifSphere();\n\n  virtual baseMeasureType getBaseMeasureType() const {return(UNIF_SPHERE); }\n\n  virtual BaseMeasure<T>* copy();\n\n  virtual T logLikelihood(const Matrix<T,Dynamic,1>& x) const;\n  virtual T logLikelihood(const Matrix<T,Dynamic,Dynamic>& x, uint32_t i) const \n    {return logLikelihood(x.col(i));};\n  virtual void posterior(const Matrix<T,Dynamic,Dynamic>& x, \n      const VectorXu& z, uint32_t k);\n  virtual T logPdfUnderPrior() const;\n  void print() const {cout<<\"Unif Sphere in D=\"<<D_<<endl;};\n  virtual uint32_t getDim() const {return(D_);};\nprivate:\n\n};\n\ntypedef UnifSphere<double> UnifSphered;\ntypedef UnifSphere<float> UnifSpheref;\n\n// ---------------------------------------------------------------------------\ntemplate<typename T>\nUnifSphere<T>::UnifSphere(uint32_t D)\n  : D_(D), S_(D)\n{};\ntemplate<typename T>\nUnifSphere<T>::~UnifSphere()\n{};\n\ntemplate<typename T>\nBaseMeasure<T>* UnifSphere<T>::copy()\n{\n  return new UnifSphere<T>(D_);\n};\n\ntemplate<typename T>\nT UnifSphere<T>::logLikelihood(const Matrix<T,Dynamic,1>& x) const\n{\n  return - S_.logSurfaceArea();\n};\n\ntemplate<typename T>\nvoid UnifSphere<T>::posterior(const Matrix<T,Dynamic,Dynamic>& x,\n    const VectorXu& z, uint32_t k)\n{\n  // nothing seince we have no priors\n};\n\ntemplate<typename T>\nT UnifSphere<T>::logPdfUnderPrior() const \n{\n  return 0.0;\n};\n\n", "meta": {"hexsha": "6b94450827084fa5d2c46175f20786f3e935f52d", "size": 1817, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/unifSphere.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/unifSphere.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/unifSphere.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": 23.9078947368, "max_line_length": 80, "alphanum_fraction": 0.6703357182, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639792, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5299226339884311}}
{"text": "#include <iostream>\n#include <list>\n#include <numeric>\n#include <unordered_map>\n\n#include <boost/optional.hpp>\n\n#include \"node.h\"\n#include \"graph.h\"\n\n// Route between two nodes\nnamespace rbn\n{\n    bool routeExists(g::IntGraph const& graph, g::IntVertex::Ptr const& start, g::IntVertex::Ptr const& end)\n    {\n        if (start == end)\n            return true;\n\n        // Just for sure mark all nodes as unvisited\n        for (auto && n : graph.verticies())\n            n.second->setState(g::IntVertex::Unvisited);\n\n        std::queue<g::IntVertex::Ptr> verteciesQueue;\n\n        start->setState(g::IntVertex::Visiting);\n        verteciesQueue.push(start);\n\n        g::IntVertex::Ptr visitingVertex;\n        while (!verteciesQueue.empty()) {\n            visitingVertex = verteciesQueue.front();\n            verteciesQueue.pop();\n\n            if (visitingVertex) {\n                for (auto && v : visitingVertex->linkedVertices()) {\n                    if (v->state() == g::IntVertex::Unvisited) {\n                        if (v == end)\n                            return true;\n                        else {\n                            v->setState(g::IntVertex::Visiting);\n                            verteciesQueue.push(v);\n                        }\n                    }\n                }\n\n                visitingVertex->setState(g::IntVertex::Visited);\n            }\n        }\n\n        return false;\n    }\n}\n\n// Minimal tree (create minimal tree from sorted array with unique elements)\nnamespace bst\n{\n    using namespace Tree;\n\n    namespace details\n    {\n        IntNodePtr createMinimalBSTImpl(std::vector<int> const& array, int from, int to)\n        {\n            if (to < from)\n                return nullptr;\n\n            int mid = (from + to) / 2;\n            auto node = std::make_shared<IntNode>(array.at(mid));\n            node->setLeftChild(createMinimalBSTImpl(array, from, mid - 1));\n            node->setRightChild(createMinimalBSTImpl(array, mid + 1, to));\n            return node;\n        }\n    }\n\n    IntNodePtr createMinimalBST(std::vector<int> const& array)\n    {\n        return details::createMinimalBSTImpl(array, 0, array.size() - 1);\n    }\n}\n\n// List of depth. For binary tree, algorithm to create a linked list of all nodes on each depth\n// using preorder traversal algorithm\nnamespace lod\n{\n    using namespace Tree;\n    using NodesList = std::list<IntNodePtr>;\n    using NodesListsArray = std::vector<NodesList>;\n\n    namespace details\n    {\n        void createLevelLinkedListImpl(IntNodePtr const& root, NodesListsArray & lists, std::size_t level)\n        {\n            if (!root)\n                return;\n\n            // Check if level not in the list\n            if (lists.size() == level) {\n                lists.push_back(NodesList());\n                lists.back().push_back(root);\n            } else\n                lists[level].push_back(root);\n\n            createLevelLinkedListImpl(root->mLeftChild, lists, level + 1);\n            createLevelLinkedListImpl(root->mRightChild, lists, level + 1);\n        }\n    }\n\n    NodesListsArray createLevelLinkedList(IntNodePtr const& root)\n    {\n        NodesListsArray lists;\n        details::createLevelLinkedListImpl(root, lists, 0);\n        return lists;\n    }\n}\n\n// Check if tree is balanced (difference between subtrees no more than one)\nnamespace bt\n{\n    using namespace Tree;\n\n    namespace details\n    {\n        static const int ERROR_TAG = std::numeric_limits<int>::min();\n\n        int checkHeight(IntNodePtr const& root)\n        {\n            if (!root)\n                return -1;\n\n            int leftHeight = checkHeight(root->mLeftChild);\n            if (leftHeight == ERROR_TAG)\n                return ERROR_TAG; // Propagate error to the top\n\n            int rightHeight = checkHeight(root->mRightChild);\n            if (rightHeight == ERROR_TAG)\n                return ERROR_TAG; // Propagate error to the top\n\n            if (std::abs(leftHeight - rightHeight) > 1)\n                return ERROR_TAG; // Pass error back\n            else\n                return std::max(leftHeight, rightHeight) + 1;\n        }\n    }\n\n    bool isBalanced(IntNodePtr const& root)\n    {\n        return details::checkHeight(root) != details::ERROR_TAG;\n    }\n}\n\n// Check if tree is a valid BST\nnamespace vbst\n{\n    using namespace Tree;\n\n    namespace details\n    {\n        using Int = boost::optional<int>;\n        bool checkBSTImpl(IntNodePtr const& n, Int min = Int(), Int max = Int())\n        {\n            if (!n)\n                return true;\n\n            if ((min && n->mKey <= min) || (max && n->mKey > max))\n                return false;\n\n            if (!checkBSTImpl(n->mLeftChild, min, n->mKey) ||\n                !checkBSTImpl(n->mRightChild, n->mKey, max))\n                return false;\n\n            return true;\n        }\n    }\n\n    bool checkBST(IntNodePtr const& root)\n    {\n        return details::checkBSTImpl(root);\n    }\n}\n\n// Successor (find \"next\" node)\nnamespace sr\n{\n    using namespace Tree;\n\n    namespace details\n    {\n        IntNodePtr leftMostChild(IntNodePtr node)\n        {\n            if (!node)\n                return nullptr;\n\n            while (node->mLeftChild)\n                node = node->mLeftChild;\n\n            return node;\n        }\n    }\n\n    IntNodePtr successor(IntNodePtr const& node)\n    {\n        if (!node)\n            return nullptr;\n\n        // If there are right child just return leftmost child shich will be the next node\n        if (node->mRightChild)\n            return details::leftMostChild(node->mRightChild);\n        else {\n            auto current = node;\n            auto parent  = node->parent();\n\n            // Go up until we're on left node instead of right\n            while (parent && parent->mLeftChild != current) {\n                current = parent;\n                parent  = parent->parent();\n            }\n\n            return parent;\n        }\n    }\n}\n\n// Topological sort.\n// Given list of projects and list of dependencies (pairs second depends on first). Find bild order\n// or error is there is no valid build order.\nnamespace ts\n{\n    using namespace g;\n    using ProjectsVector     = std::vector<std::string>;\n    using DependenciesVector = std::vector<std::pair<std::string, std::string>>;\n\n    namespace details\n    {\n        using Project = Vertex<std::string>;\n        using OrderedProjects = std::list<Project::Ptr>;\n\n        bool doDFS(Project::Ptr const& project, OrderedProjects & projects)\n        {\n            // Cycle detected\n            if (project->state() == Project::Visiting)\n                return false;\n\n            if (project->state() == Project::Unvisited) {\n                project->setState(Project::Visiting);\n\n                for (auto && child : project->linkedVertices())\n                    if (!doDFS(child, projects))\n                        return false; // Propagate cycle\n\n                project->setState(Project::Visited);\n                projects.push_front(project);\n            }\n\n            return true;\n        }\n\n        decltype(auto) fillGraph(ProjectsVector const& projects,\n                                 DependenciesVector const& dependencies)\n        {\n            auto graph = std::make_unique<StrGraph>();\n\n            for (auto && project : projects)\n                graph->addVertex(project);\n\n            // Second depends on first\n            for (auto && edge : dependencies)\n                graph->addEdge(edge.second, edge.first);\n\n            return graph;\n        }\n    }\n\n    ProjectsVector orderedProjects(ProjectsVector     const& projects,\n                                   DependenciesVector const& dependencies)\n    {\n        auto graph = details::fillGraph(projects, dependencies);\n\n        details::OrderedProjects op;\n        for (auto && project : graph->verticies())\n            if (project.second->state() == details::Project::Unvisited)\n                if (!details::doDFS(project.second, op))\n                    return ProjectsVector();\n\n        ProjectsVector result(op.size());\n        std::transform(op.begin(), op.end(), result.begin(), [](auto && p) { return p->data(); });\n        return result;\n    }\n}\n\n// Find first common ancestor for two nodes\nnamespace fca\n{\n    using namespace Tree;\n\n    namespace details\n    {\n        IntNodePtr doUpBy(IntNodePtr node, int depth)\n        {\n            while (depth > 0 && node) {\n                node = node->parent();\n                --depth;\n            }\n\n            return node;\n        }\n    }\n\n    IntNodePtr commonAncestor(IntNodePtr const& f, IntNodePtr const& s)\n    {\n        assert(f && s);\n        int delta = f->depth() - s->depth();\n        IntNodePtr shallower = delta > 0 ? s : f;\n        IntNodePtr deeper    = delta > 0 ? f : s;\n\n        // Up deeper node\n        deeper = details::doUpBy(deeper, std::abs(delta));\n\n        // Search for intersection\n        while (deeper != shallower && deeper && shallower) {\n            deeper = deeper->parent();\n            shallower = shallower->parent();\n        }\n\n        return !shallower || !deeper ? nullptr : shallower;\n    }\n}\n\n// Given a BST which created by traversing array left to right,\n// generate all arrays may lead to this tree\nnamespace bstsq\n{\n    using List = std::list<int>;\n    using VectorLists = std::vector<List>;\n\n    using namespace Tree;\n\n    namespace details\n    {\n        void mergeLists(List & first, List & second, VectorLists & results, List & prefix);\n\n        void addHeadToPrefixAndMerge(List & first, List & second, VectorLists & results,\n                                     List & prefix, List & listForTakingHead)\n        {\n            // Take head\n            int head = listForTakingHead.front();\n            listForTakingHead.pop_front();\n            prefix.push_back(head);\n\n            mergeLists(first, second, results, prefix);\n\n            // Restore head\n            prefix.pop_back();\n            listForTakingHead.push_front(head);\n        }\n\n        // Merge lists in all possible ways\n        void mergeLists(List & first, List & second, VectorLists & results, List & prefix)\n        {\n            // If one list is empty, add remainder to the prefix and store result\n            if (first.empty() || second.empty()) {\n                List result(prefix);\n                std::copy(first.begin(), first.end(), std::back_inserter(result));\n                std::copy(second.begin(), second.end(), std::back_inserter(result));\n                results.push_back(result);\n                return;\n            }\n\n            // Recurse go through first and second lists\n            addHeadToPrefixAndMerge(first, second, results, prefix, first /*listForTakingHead*/);\n            addHeadToPrefixAndMerge(first, second, results, prefix, second /*listForTakingHead*/);\n        }\n    }\n\n    VectorLists allSequences(IntNodePtr const& root)\n    {\n        VectorLists result;\n\n        if (!root) {\n            result.push_back(List());\n            return result;\n        }\n\n        List prefix;\n        prefix.push_back(root->mKey);\n\n        // Recurse on left and right subtrees\n        auto leftSeq  = allSequences(root->mLeftChild);\n        auto rightSeq = allSequences(root->mRightChild);\n\n        // Merge all list from the left and right sides\n        for (auto && left : leftSeq) {\n            for (auto && right : rightSeq) {\n                VectorLists merged;\n                details::mergeLists(left, right, merged, prefix);\n                std::copy(merged.begin(), merged.end(), std::back_inserter(result));\n            }\n        }\n\n        return result;\n    }\n}\n\n// There are two large binary trees (T1 and T2), check if T2 is sutree of T1. T1 is bigger.\nnamespace ct\n{\n    using namespace Tree;\n\n    namespace details\n    {\n        bool matchTree(IntNodePtr const& n1, IntNodePtr const& n2)\n        {\n            if (!n1 && !n2)\n                return true; // nothing left\n            else if (!n1 || !n2)\n                return false; // one of them is empty, don't match\n            else if (n1->mKey != n2->mKey)\n                return false; // different data\n            else // Recurse compare subtrees\n                return matchTree(n1->mLeftChild, n2->mLeftChild) &&\n                       matchTree(n1->mRightChild, n2->mRightChild);\n        }\n\n        bool subTree(IntNodePtr const& n1, IntNodePtr const& n2)\n        {\n            if (!n1)\n                return false; // big tree is empty\n            else if (n1->mKey == n2->mKey && matchTree(n1, n2))\n                return true;\n\n            return subTree(n1->mLeftChild, n2) || subTree(n1->mRightChild, n2);\n        }\n    }\n\n    bool containsTree(IntNodePtr const& t1, IntNodePtr const& t2)\n    {\n      // The empty tree is always a subtree :)\n      return !t2 || details::subTree(t1, t2);\n    }\n}\n\n// Given binary tree and sum. Count the number of pathes to get given sum. Paths should traveling\n// only from parent nodes to child.\nnamespace sp\n{\n    using namespace Tree;\n\n    namespace details\n    {\n        using PathCount = std::unordered_map<int, int>;\n\n        void incVal(PathCount & pathCount, int key, int delta)\n        {\n            int newCount = pathCount[key] + delta;\n            if (newCount == 0)\n                pathCount.erase(key); // Reduce space\n            else\n                pathCount[key] = delta;\n        }\n\n        int countPathsWithSumImpl(IntNodePtr const& node, int targetSum, int runnigSum,\n                                  PathCount & pathCount)\n        {\n            if (!node)\n                return 0; // Base case\n\n            // Count paths with with sum ending at the current node\n            runnigSum += node->mKey;\n            int sum = runnigSum - targetSum;\n            int totalPaths = pathCount[sum];\n\n            // One additional path starts at root\n            if (runnigSum == targetSum)\n                ++totalPaths;\n\n            // Increment pathCount, recurse, then decrement\n            incVal(pathCount, runnigSum, 1);\n            totalPaths += countPathsWithSumImpl(node->mLeftChild, targetSum, runnigSum, pathCount);\n            totalPaths += countPathsWithSumImpl(node->mRightChild, targetSum, runnigSum, pathCount);\n            incVal(pathCount, runnigSum, -1);\n\n            return totalPaths;\n        }\n    }\n\n    int countPathWithSum(IntNodePtr const& node, int sum)\n    {\n        details::PathCount pathCount;\n        return details::countPathsWithSumImpl(node, sum, 0, pathCount);\n    }\n}\n\nint main(int /*argc*/, char */*argv*/[])\n{\n    // 1\n//    g::IntGraph graph;\n//    auto first = graph.addVertex(1);\n//    auto second = graph.addVertex(2);\n//    auto third = graph.addVertex(3);\n//    auto fourth = graph.addVertex(4);\n\n//    graph.addEdge(1, 2);\n//    graph.addEdge(1, 3);\n//    graph.addEdge(2, 3);\n//    graph.addEdge(3, 4);\n\n//    std::cout << std::boolalpha << rbn::routeExists(graph, fourth, first) << std::endl;\n\n//    graph.dump(\"/home/vt4a2h/Projects/alg/graph.dot\");\n//    system(\"cd /home/vt4a2h/Projects/alg/ && dot graph.dot -Tsvg > graph.svg \");\n\n    // 2\n//    try {\n//        std::vector<int> v {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};\n//        auto tree = bst::createMinimalBST(v);\n//        tree->dump(\"/home/vt4a2h/Projects/alg/graph.dot\");\n//        system(\"cd /home/vt4a2h/Projects/alg/ && dot graph.dot -Tsvg > graph.svg \");\n//    } catch (std::exception const& e) {\n//        std::cout << e.what() << std::endl;\n//    }\n\n    // 3\n//    try {\n//        std::vector<int> v {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};\n//        auto tree = bst::createMinimalBST(v);\n\n//        auto lists = lod::createLevelLinkedList(tree);\n//        for (auto && list : lists) {\n//            for (auto && n : list) {\n//                std::cout << n->mKey << \"\\t\";\n//            }\n//            std::cout << std::endl;\n//        }\n//    } catch (std::exception const& e) {\n//        std::cout << e.what() << std::endl;\n//    }\n\n    // 4\n//    try {\n//        std::vector<int> v {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};\n//        auto tree = bst::createMinimalBST(v);\n\n//        // Must be balanced\n//        std::cout << \"Is balanced: \" << std::boolalpha << bt::isBalanced(tree) << std::endl;\n\n//        // Disbalance somehow\n//        Tree::IntNodePtr min = tree->mLeftChild;\n//        while (min->mLeftChild)\n//            min = min->mLeftChild;\n\n//        std::cout << \"Min element: \" << min->mKey << std::endl;\n\n//        min->makeLeftChild(-1)->makeLeftChild(-2);\n\n//        std::cout << \"Is balanced: \" << std::boolalpha << bt::isBalanced(tree) << std::endl;\n//    } catch (std::exception const& e) {\n//        std::cout << e.what() << std::endl;\n//    }\n\n    // 5\n//    try {\n//        std::vector<int> v {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};\n//        auto tree = bst::createMinimalBST(v);\n\n//        std::cout << \"Is BST: \" << std::boolalpha << vbst::checkBST(tree) << std::endl;\n\n//        Tree::IntNodePtr min = tree->mLeftChild;\n//        while (min->mLeftChild)\n//            min = min->mLeftChild;\n//        min->makeLeftChild(100)->makeLeftChild(200);\n\n//        std::cout << \"Is BST: \" << std::boolalpha << bt::isBalanced(tree) << std::endl;\n//    } catch (std::exception const& e) {\n//        std::cout << e.what() << std::endl;\n//    }\n\n    // 6\n//    try {\n//        std::vector<int> v {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};\n//        auto tree = bst::createMinimalBST(v);\n\n//        Tree::IntNodePtr min = tree->mLeftChild;\n//        while (min->mLeftChild)\n//            min = min->mLeftChild;\n\n//        // 1 -> 2\n//        std::cout << min->mKey << \" -> \" << sr::successor(min)->mKey << std::endl;\n\n//        // 2 -> 3\n//        auto two = min->parent();\n//        std::cout << two->mKey << \" -> \" << sr::successor(two)->mKey << std::endl;\n\n//        // 3 -> 4\n//        auto three = sr::successor(min)->mRightChild;\n//        std::cout << three->mKey << \" -> \" << sr::successor(three)->mKey << std::endl;\n\n//    } catch (std::exception const& e) {\n//        std::cout << e.what() << std::endl;\n//    }\n\n    // 7\n//    ts::ProjectsVector pv {\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"};\n//    ts::DependenciesVector dv {{\"a\", \"d\"}, {\"f\", \"b\"}, {\"b\", \"d\"}, {\"f\", \"a\"}, {\"d\", \"c\"}};\n//    try {\n//        auto orderedProjects = ts::orderedProjects(pv, dv);\n//        for (auto && p : orderedProjects)\n//            std::cout << p << \"\\t\";\n//        std::cout << std::endl;\n//    } catch (std::exception const& e) {\n//        std::cout << e.what() << std::endl;\n//    }\n\n    // 8\n//    try {\n//        std::vector<int> v {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};\n//        auto tree = bst::createMinimalBST(v);\n\n//        Tree::IntNodePtr min = tree->mLeftChild;\n//        while (min->mLeftChild)\n//            min = min->mLeftChild;\n\n//        Tree::IntNodePtr someNode = min->parent()->parent()->mRightChild->mRightChild;\n\n//        min = min->makeRightChild(200)->makeLeftChild(300);\n\n//        tree->dump(\"/home/vt4a2h/Projects/alg/fca_graph.dot\");\n//        system(\"cd /home/vt4a2h/Projects/alg/ && dot fca_graph.dot -Tsvg > fca_graph.svg \");\n\n//        if (auto ca = fca::commonAncestor(min, someNode))\n//            std::cout << \"First common ancestor: \" << ca->mKey << std::endl;\n//        else\n//            std::cout << \"No common ancestor here.\" << std::endl;\n//    } catch (std::exception const& e) {\n//        std::cout << e.what() << std::endl;\n//    }\n\n    // 9\n    // TODO: revise\n//    try {\n//        std::vector<int> v {1, 2, 3, 4, 5};\n//        auto tree = bst::createMinimalBST(v);\n\n//        auto allSequences = bstsq::allSequences(tree);\n//        for (auto && s : allSequences) {\n//            for (auto && e : s) {\n//                std::cout << e << \"\\t\";\n//            }\n//            std::cout << std::endl;\n//        }\n\n//        tree->dump(\"/home/vt4a2h/Projects/alg/bstsq_graph.dot\");\n//        system(\"cd /home/vt4a2h/Projects/alg/ && dot bstsq_graph.dot -Tsvg > bstsq_graph.svg \");\n//    } catch (std::exception const& e) {\n//        std::cout << e.what() << std::endl;\n//    }\n\n    // 10\n//    try {\n//        std::vector<int> v1 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n//        auto tree1 = bst::createMinimalBST(v1);\n\n//        auto tree2 = std::make_shared<Tree::IntNode>(2);\n//        tree2->makeLeftChild(1);\n//        tree2->makeRightChild(3)->makeRightChild(4);\n\n//        tree1->dump(\"/home/vt4a2h/Projects/alg/tree1.dot\");\n//        system(\"cd /home/vt4a2h/Projects/alg/ && dot tree1.dot -Tsvg > tree1.svg \");\n\n//        tree2->dump(\"/home/vt4a2h/Projects/alg/tree2.dot\");\n//        system(\"cd /home/vt4a2h/Projects/alg/ && dot tree2.dot -Tsvg > tree2.svg \");\n\n//        std::cout << std::boolalpha << ct::containsTree(tree1, tree2) << std::endl;\n//    } catch (std::exception const& e) {\n//        std::cout << e.what() << std::endl;\n//    }\n\n    // 11\n    // Implement method for getting random node from BST (nodes should be equally likelly to be chosen)\n//    try {\n//        srand(time(NULL));\n\n//        auto tree = std::make_shared<Tree::IntNode>(4);\n//        auto two = tree->insertInOrder(2);\n//        two->insertInOrder(1);\n//        two->insertInOrder(3);\n\n//        auto six = tree->insertInOrder(6);\n//        six->insertInOrder(5);\n//        six->insertInOrder(7);\n\n//        tree->dump(\"/home/vt4a2h/Projects/alg/ub.dot\");\n//        system(\"cd /home/vt4a2h/Projects/alg/ && dot ub.dot -Tsvg > ub.svg \");\n\n//        for (int i = 1; i <= 7; ++i)\n//            std::cout << tree->randomNode()->mKey << \"\\t\";\n//        std::cout << std::endl;\n//    } catch (std::exception const& e) {\n//        std::cout << e.what() << std::endl;\n//    }\n\n    // 12 // TODO: revise\n    try {\n        std::vector<int> v {1, 2, 3, 4, 5};\n        auto tree = bst::createMinimalBST(v);\n\n        std::cout << sp::countPathWithSum(tree, 3) << std::endl;\n    } catch (std::exception const& e) {\n        std::cout << e.what() << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "939f07697e980c4262707c49e15cdf9ff662d0e4", "size": 21912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphs/main.cpp", "max_stars_repo_name": "vt4a2h/alg-review", "max_stars_repo_head_hexsha": "73cd4d497163dcc42350f7f33eea78fb64768264", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "graphs/main.cpp", "max_issues_repo_name": "vt4a2h/alg-review", "max_issues_repo_head_hexsha": "73cd4d497163dcc42350f7f33eea78fb64768264", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphs/main.cpp", "max_forks_repo_name": "vt4a2h/alg-review", "max_forks_repo_head_hexsha": "73cd4d497163dcc42350f7f33eea78fb64768264", "max_forks_repo_licenses": ["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.861971831, "max_line_length": 108, "alphanum_fraction": 0.5324023366, "num_tokens": 5709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5299226166080186}}
{"text": "#include <vector>\n#include <string>\n#include <Eigen/Dense>\n#include <opencv2/opencv.hpp>\n#include <omp.h>\n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/eigen.h>\n\nnamespace py = pybind11;\n\nvoid calcIndexMap( const Eigen::Array2Xf &coords, const Eigen::Array3Xi &coordIdxs, const cv::Size &texSize,\n                   cv::Mat &indexMap )\n{\n    // IndexMap: 3 channels for each pixel, 1: triId, 2 and 3: baycentric coordinates\n    indexMap.create( texSize, CV_32FC3 );\n    indexMap.setTo( cv::Vec3f( -1.f, -1.f, -1.f ) );\n\n    // For each triangle, find the coverred pixels\n    int triNum = int( coordIdxs.cols() );\n    for( int triId=0; triId<triNum; triId++ ){\n        const Eigen::Vector3i& coordIdx = coordIdxs.col( triId );\n\n        Eigen::Vector2i bboxMin( texSize.width, texSize.height );\n        Eigen::Vector2i bboxMax( 0, 0 );\n\n        for( int i=0; i<3; i++ ){\n            const Eigen::Vector2f& coord = coords.col( coordIdx[ i ] );\n            int x = int( coord[ 0 ] * texSize.width );\n            int y = int( coord[ 1 ] * texSize.height );\n            bboxMin[ 0 ] = std::min( bboxMin[ 0 ], x );\n            bboxMin[ 1 ] = std::min( bboxMin[ 1 ], y );\n            bboxMax[ 0 ] = std::max( bboxMax[ 0 ], x );\n            bboxMax[ 1 ] = std::max( bboxMax[ 1 ], y );\n        }\n\n        bboxMin[ 0 ] = std::min( texSize.width - 1, std::max( 0, bboxMin[ 0 ] ) );\n        bboxMin[ 1 ] = std::min( texSize.height - 1, std::max( 0, bboxMin[ 1 ] ) );\n        bboxMax[ 0 ] = std::min( texSize.width - 1, std::max( 0, bboxMax[ 0 ] ) );\n        bboxMax[ 1 ] = std::min( texSize.height - 1, std::max( 0, bboxMax[ 1 ] ) );\n\n        Eigen::Vector2f vec01 = ( Eigen::Vector2f )coords.col( coordIdx[ 1 ] ) - ( Eigen::Vector2f )coords.col( coordIdx[ 0 ] );\n        Eigen::Vector2f vec02 = ( Eigen::Vector2f )coords.col( coordIdx[ 2 ] ) - ( Eigen::Vector2f )coords.col( coordIdx[ 0 ] );\n\n        for( int v = bboxMin[ 1 ]; v <= bboxMax[ 1 ]; v++ ){\n            for( int u = bboxMin[ 0 ]; u <= bboxMax[ 0 ]; u++ ){\n                Eigen::Vector2f uvCoord( ( u + 0.5f ) / float( texSize.width ), ( v + 0.5f ) / float( texSize.height ) );\n                Eigen::Vector2f pt = uvCoord - ( Eigen::Vector2f )coords.col( coordIdx[ 0 ] );\n\n                float denom = vec01[ 0 ] * vec02[ 1 ] - vec01[ 1 ] * vec02[ 0 ];\n                float lambda_2 = (pt[ 0 ] * vec02[ 1 ] - pt[ 1 ] * vec02[ 0 ]) / denom;\n                float lambda_3 = (vec01[ 0 ] * pt[ 1 ] - vec01[ 1 ] * pt[ 0 ]) / denom;\n                float lambda_1 = 1.f - lambda_2 - lambda_3;\n\n                if( lambda_1 > 0.f && lambda_1 < 1.f &&\n                    lambda_2 > 0.f && lambda_2 < 1.f &&\n                    lambda_3 > 0.f && lambda_3 < 1.f ){\n                    indexMap.at<cv::Vec3f>( v, u ) = cv::Vec3f( triId + 0.5f, lambda_1, lambda_2 );\n                }\n            }\n        }\n    }\n}\n\npy::array_t<float> calcIndexMap_py( const Eigen::Array2Xf& coords, const Eigen::Array3Xi& coordIdxs, int texWidth, int texHeight )\n{\n    cv::Mat idxMapMat;\n    calcIndexMap( coords, coordIdxs, cv::Size( texWidth, texHeight ), idxMapMat );\n\n    py::array_t<float> idxMap = py::array_t<float>( texHeight * texWidth * 3 );\n    auto idxMapBuf = idxMap.request();\n    memcpy( (float*)idxMapBuf.ptr, idxMapMat.ptr(), texHeight * texWidth * 3 * sizeof(float) );\n    idxMap.resize( { texHeight, texWidth, 3 } );\n\n    return idxMap;\n}\n\nvoid unwarpTex( const cv::Mat& img, const Eigen::Array3Xf& ptUVWs, const Eigen::Array3Xi& posIdxs, const cv::Mat& indexMap, cv::Mat& tex )\n{\n    cv::Size imgSize = img.size();\n    cv::Size texSize = indexMap.size();\n\n    tex.create( texSize, CV_8UC4 );\n    tex.setTo( cv::Vec4b( 0, 0, 0, 0 ) );\n\n    for( int v=0; v<texSize.height; v++ ){\n        for( int u=0; u<texSize.width; u++ ){\n            const cv::Vec3f& idx = indexMap.at<cv::Vec3f>( v, u );\n            float lambda_1 = idx[ 1 ], lambda_2 = idx[ 2 ];\n            float lambda_3 = 1.f - lambda_1 - lambda_2;\n\n            int triId = int( idx[ 0 ] );\n            const Eigen::Vector3i& posIdx = posIdxs.col( triId );\n\n            Eigen::Vector3f triUVWs[ 3 ];\n            for( int i=0; i<3; i++ ) triUVWs[ i ] = ptUVWs.col( posIdx[ i ] );\n\n            Eigen::Vector3f pixUVW = triUVWs[ 0 ] * lambda_1 + triUVWs[ 1 ] * lambda_2 + triUVWs[ 2 ] * lambda_3;\n\n            float x = pixUVW[ 0 ], y = pixUVW[ 1 ];\n            int x0 = int( x ), y0 = int( y );\n            int x1 = x0 + 1, y1 = y0 + 1;\n            float xWeight = x - float( x0 ), yWeight = y - float( y0 );\n\n            if( x0 < 0 || x1 >= imgSize.width || y0 < 0 || y1 >= imgSize.height ) continue;\n\n            cv::Vec3f pixes[ 4 ];\n            pixes[ 0 ] = (cv::Vec3f)img.at<cv::Vec3b>( y0, x0 );\n            pixes[ 1 ] = (cv::Vec3f)img.at<cv::Vec3b>( y0, x1 );\n            pixes[ 2 ] = (cv::Vec3f)img.at<cv::Vec3b>( y1, x0 );\n            pixes[ 3 ] = (cv::Vec3f)img.at<cv::Vec3b>( y1, x1 );\n\n            cv::Vec3f pixVal =\n                    ( pixes[ 0 ] * ( 1.f - xWeight ) + pixes[ 1 ] * xWeight ) * ( 1.f - yWeight )\n                    + ( pixes[ 2 ] * ( 1.f - xWeight ) + pixes[ 3 ] * xWeight ) * yWeight;\n\n            for( int i=0; i<3; i++ )\n                pixVal[ i ] = std::min( 255.f, std::max( 0.f, pixVal[ i ] ) );\n\n            tex.at<cv::Vec4b>( v, u ) = cv::Vec4b( (uchar)pixVal[0], (uchar)pixVal[1], (uchar)pixVal[2], 255 );\n        }\n    }\n}\n\nstd::vector<uchar> unwarpTex_py( const std::vector<uchar>& img_vec, int imgWidth, int imgHeight,\n    const Eigen::Array3Xf& ptUVWs, const Eigen::Array3Xi& posIdxs,\n    const std::vector<float>& idxMap_vec, int texWidth, int texHeight )\n{\n    cv::Mat img;\n    img.create( imgHeight, imgWidth, CV_8UC3 );\n    memcpy( img.ptr(), &img_vec[ 0 ], imgHeight * imgWidth * 3 );\n\n    cv::Mat idxMap;\n    idxMap.create( texHeight, texWidth, CV_32FC3 );\n    memcpy( idxMap.ptr(), &idxMap_vec[ 0 ], texWidth * texHeight * 3 * sizeof(float) );\n\n    cv::Mat tex;\n    unwarpTex( img, ptUVWs, posIdxs, idxMap, tex );\n\n    std::vector<uchar> tex_vec;\n    tex_vec.resize( texWidth * texHeight * 4 );\n    memcpy( &tex_vec[ 0 ], tex.ptr(), texWidth * texHeight * 4 );\n\n    return tex_vec;\n}\n\nvoid unwarpTexNor( const cv::Mat& img, const Eigen::Array3Xf& ptUVWs, const Eigen::Array3Xi& posIdxs,\n                   const cv::Mat& indexMap, const cv::Mat& texMask, cv::Mat& tex )\n{\n    // Calculate the ptUVWNors\n    int ptNum = int( ptUVWs.cols() ), triNum = int( posIdxs.cols() );\n    Eigen::Array3Xf ptUVWNors( 3, ptNum );\n    ptUVWNors.setZero();\n    for( int triId=0; triId<triNum; triId++ ){\n        const Eigen::Vector3i& posIdx = posIdxs.col( triId );\n        Eigen::Vector3f e0 = ptUVWs.col( posIdx[ 1 ] ) - ptUVWs.col( posIdx[ 0 ] );\n        Eigen::Vector3f e1 = ptUVWs.col( posIdx[ 2 ] ) - ptUVWs.col( posIdx[ 0 ] );\n        Eigen::Vector3f nor = e0.cross( e1 );\n\n        for( int i=0; i<3; i++ ){\n            Eigen::Vector3f ptNor = ptUVWNors.col( posIdx[ i ] );\n            ptUVWNors.col( posIdx[ i ] ) = ptNor + nor;\n        }\n    }\n    for( int ptId=0; ptId<ptNum; ptId++ ){\n        Eigen::Vector3f ptNor = ptUVWNors.col( ptId );\n        ptUVWNors.col( ptId ) = ptNor.normalized();\n    }\n\n    // Unwarp texture\n    cv::Size imgSize = img.size();\n    cv::Size texSize = indexMap.size();\n\n    tex.create( texSize, CV_8UC4 );\n    tex.setTo( cv::Vec4b( 0, 0, 0, 0 ) );\n\n    const float cPi = 3.1415926535897932384626433f;\n\n    #pragma omp parallel for\n    for( int v=0; v<texSize.height; v++ ){\n        for( int u=0; u<texSize.width; u++ ){\n            float pixWeight = texMask.at<float>( v, u );\n            if( pixWeight == 0.f ) continue;\n\n            const cv::Vec3f& idx = indexMap.at<cv::Vec3f>( v, u );\n            float lambda_1 = idx[ 1 ], lambda_2 = idx[ 2 ];\n            float lambda_3 = 1.f - lambda_1 - lambda_2;\n\n            int triId = int( idx[ 0 ] );\n            const Eigen::Vector3i& posIdx = posIdxs.col( triId );\n\n            Eigen::Vector3f triUVWs[ 3 ];\n            for( int i=0; i<3; i++ ) triUVWs[ i ] = ptUVWs.col( posIdx[ i ] );\n\n            Eigen::Vector3f pixUVW = triUVWs[ 0 ] * lambda_1 + triUVWs[ 1 ] * lambda_2 + triUVWs[ 2 ] * lambda_3;\n\n            float x = pixUVW[ 0 ], y = pixUVW[ 1 ];\n            int x0 = int( x ), y0 = int( y );\n            int x1 = x0 + 1, y1 = y0 + 1;\n            float xWeight = x - float( x0 ), yWeight = y - float( y0 );\n\n            if( x0 < 0 || x1 >= imgSize.width || y0 < 0 || y1 >= imgSize.height ) continue;\n\n            cv::Vec3f pixes[ 4 ];\n            pixes[ 0 ] = (cv::Vec3f)img.at<cv::Vec3b>( y0, x0 );\n            pixes[ 1 ] = (cv::Vec3f)img.at<cv::Vec3b>( y0, x1 );\n            pixes[ 2 ] = (cv::Vec3f)img.at<cv::Vec3b>( y1, x0 );\n            pixes[ 3 ] = (cv::Vec3f)img.at<cv::Vec3b>( y1, x1 );\n\n            cv::Vec3f pixVal =\n                    ( pixes[ 0 ] * ( 1.f - xWeight ) + pixes[ 1 ] * xWeight ) * ( 1.f - yWeight )\n                    + ( pixes[ 2 ] * ( 1.f - xWeight ) + pixes[ 3 ] * xWeight ) * yWeight;\n\n            // Get the pixel's normal\n            Eigen::Vector3f triNors[ 3 ];\n            for( int i=0; i<3; i++ ) triNors[ i ] = ptUVWNors.col( posIdx[ i ] );\n            Eigen::Vector3f pixNor = triNors[ 0 ] * lambda_1 + triNors[ 1 ] * lambda_2 + triNors[ 2 ] * lambda_3;\n\n            if( pixNor[ 2 ] < 0.f ) pixWeight *= tanh( pixNor[ 2 ] * 2.f * cPi + cPi );\n            pixVal *= pixWeight;\n\n            // Set pixel\n            for( int i=0; i<3; i++ )\n                pixVal[ i ] = std::min( 255.f, std::max( 0.f, pixVal[ i ] ) );\n            float alpha = ( pixNor[ 2 ] + 1.f ) * 0.5f;\n            alpha = std::min( 255.f, std::max( 0.f, alpha * 255.f ) );\n            tex.at<cv::Vec4b>( v, u ) = cv::Vec4b( (uchar)pixVal[0], (uchar)pixVal[1], (uchar)pixVal[2], (uchar)alpha );\n        }\n    }\n}\n\npy::array_t<uchar> unwarpTexNor_py( py::array_t<uchar>& py_imgs, py::array_t<float>& py_ptUVWs,\n                                    py::array_t<int>& py_posIdxs, py::array_t<float>& py_idxMap,\n                                    py::array_t<int>& py_viewIds, py::array_t<float>& py_texMasks,\n                                    py::array_t<int>& py_texRect, py::array_t<int>& py_texSize )\n{\n    // Get the buffer, and get the parameters\n    auto py_imgsBuf = py_imgs.request();\n    auto py_ptUVWsBuf = py_ptUVWs.request();\n    auto py_posIdxsBuf = py_posIdxs.request();\n    auto py_idxMapBuf = py_idxMap.request();\n    auto py_viewIdsBuf = py_viewIds.request();\n    auto py_texMasksBuf = py_texMasks.request();\n    auto py_texRectBuf = py_texRect.request();\n    auto py_texSizeBuf = py_texSize.request();\n\n    int imgNum = int( py_imgsBuf.shape[ 0 ] );\n    int imgHeight = int( py_imgsBuf.shape[ 1 ] ), imgWidth = int( py_imgsBuf.shape[ 2 ] );\n    int texHeight = int( py_idxMapBuf.shape[ 0 ] ), texWidth = int( py_idxMapBuf.shape[ 1 ] );\n    int ptNum = int( py_ptUVWsBuf.shape[ 1 ] );\n    int triNum = int( py_posIdxsBuf.shape[ 0 ] );\n    int viewNum = int( py_texMasksBuf.shape[ 0 ] );\n\n    // Build the data\n    cv::Mat idxMap;\n    idxMap.create( texHeight, texWidth, CV_32FC3 );\n    memcpy( idxMap.ptr(), (float*)py_idxMapBuf.ptr, texWidth * texHeight * 3 * sizeof(float) );\n\n    Eigen::Array3Xi posIdxs( 3, triNum );\n    memcpy( posIdxs.data(), (int*)py_posIdxsBuf.ptr, triNum * 3 * sizeof(int) );\n\n    float* py_texMaksPtr = (float*)py_texMasksBuf.ptr;\n    std::vector<cv::Mat> texMasks( viewNum );\n    for( int viewId=0; viewId<viewNum; viewId++ ){\n        cv::Mat& texMask = texMasks[ viewId ];\n        texMask.create( texHeight, texWidth, CV_32F );\n        memcpy( texMask.ptr(), &py_texMaksPtr[ texHeight * texWidth * viewId ],\n                texHeight * texWidth * sizeof( float ) );\n        cv::flip( texMask, texMask, 0 );\n    }\n\n    // Unwarp\n    cv::Rect cropRect( 0, 0, texHeight, texWidth );\n    if( py_texRectBuf.shape[ 0 ] == 4 ){\n        int* ptr = (int*)py_texRectBuf.ptr;\n        cropRect = cv::Rect( ptr[0], ptr[1], ptr[2], ptr[3] );\n    }\n\n    cv::Size cropSize( texHeight, texWidth );\n    if( py_texSizeBuf.shape[ 0 ] == 2 ){\n        int* ptr = (int*)py_texSizeBuf.ptr;\n        cropSize = cv::Size( ptr[ 0 ], ptr[ 1 ] );\n    }\n\n    py::array_t<uchar> py_texes = py::array_t<uchar>( imgNum * cropSize.width * cropSize.height * 4 );\n    auto py_texesBuf = py_texes.request();\n    uchar* py_texesPtr = (uchar*)py_texesBuf.ptr;\n\n    uchar* py_imgsPtr = (uchar*)py_imgsBuf.ptr;\n    float* py_ptUVWsPtr = (float*)py_ptUVWsBuf.ptr;\n    int* py_viewIdsPtr = (int*)py_viewIdsBuf.ptr;\n    for( int imgId=0; imgId<imgNum; imgId++ ){\n        cv::Mat img;\n        img.create( imgHeight, imgWidth, CV_8UC3 );\n        memcpy( img.ptr(), &py_imgsPtr[ imgHeight * imgWidth * 3 * imgId ], imgHeight * imgWidth * 3 );\n\n        Eigen::Array3Xf ptUVWs( 3, ptNum );\n        memcpy( ptUVWs.data(), &py_ptUVWsPtr[ ptNum * 3 * imgId ], ptNum * 3 * sizeof( float ) );\n\n        cv::Mat tex;\n        const cv::Mat& texMask = texMasks[ py_viewIdsPtr[ imgId ] ];\n        unwarpTexNor( img, ptUVWs, posIdxs, idxMap, texMask, tex );\n        cv::flip( tex, tex, 0 );\n        cv::resize( tex( cropRect ), tex, cropSize );\n\n        memcpy( &py_texesPtr[ cropSize.width * cropSize.height * 4 * imgId ], tex.ptr(),\n                cropSize.width * cropSize.height * 4 );\n\n        printf( \" Unwarp texture for image %d/%d\\r\", imgId + 1, imgNum );\n    }\n    printf( \"\\n\" );\n\n    py_texes.resize( { imgNum, cropSize.height, cropSize.width, 4 } );\n    return py_texes;\n}\n\nvoid unwarpPosMap( const Eigen::Array3Xf& ptXYZs, const Eigen::Array3Xi& posIdxs,\n                const cv::Mat& indexMap, cv::Mat& posMap  )\n{\n    cv::Size texSize = indexMap.size();\n    posMap.create( texSize, CV_32FC3 );\n    posMap.setTo( cv::Vec3f( 0.0, 0.0, 0.0 ) );\n\n    for( int v=0; v<texSize.height; v++ ){\n        for( int u=0; u<texSize.width; u++ ){\n            const cv::Vec3f& idx = indexMap.at<cv::Vec3f>( v, u );\n            int triId = int( idx[ 0 ] );\n            float lambda_1 = idx[ 1 ], lambda_2 = idx[ 2 ];\n            float lambda_3 = 1.f - lambda_1 - lambda_2;\n\n            const Eigen::Vector3i& posIdx = posIdxs.col( triId );\n            Eigen::Vector3f triXYZs[ 3 ];\n            for( int i=0; i<3; i++ ) triXYZs[ i ] = ptXYZs.col( posIdx[ i ] );\n\n            Eigen::Vector3f pixXYZ = triXYZs[ 0 ] * lambda_1\n                                    + triXYZs[ 1 ] * lambda_2\n                                    + triXYZs[ 2 ] * lambda_3;\n\n            posMap.at<cv::Vec3f>( v, u ) = cv::Vec3f( pixXYZ[ 0 ], pixXYZ[ 1 ], pixXYZ[ 2 ] );\n        }\n    }\n}\n\nstd::vector<float> unwarpPosMap_py( const Eigen::Array3Xf& ptXYZs, const Eigen::Array3Xi& posIdxs,\n                const std::vector<float>& idxMap_vec, int texWidth, int texHeight )\n{\n    cv::Mat idxMap;\n    idxMap.create( texHeight, texWidth, CV_32FC3 );\n    memcpy( idxMap.ptr(), &idxMap_vec[ 0 ], texWidth * texHeight * 3 * sizeof(float) );\n\n    cv::Mat posMap;\n    unwarpPosMap( ptXYZs, posIdxs, idxMap, posMap );\n\n    std::vector<float> posMap_vec;\n    posMap_vec.resize( texWidth * texHeight * 3 );\n    memcpy( &posMap_vec[ 0 ], posMap.ptr(), texWidth * texHeight * 3 * sizeof( float ) );\n\n    return posMap_vec;\n}\n\n\n// --------------------------------------------------\n// *Pybind\nPYBIND11_MODULE( texUnwarp, m ){\n    m.doc() = \"Unwarp texture from image\";\n\n    m.def( \"calcIndexMap\", &calcIndexMap_py, \"Calculate texture index map\" );\n    m.def( \"unwarpTex\", &unwarpTex_py, \"Unwarp the texture\" );\n    m.def( \"unwarpTexNor\", &unwarpTexNor_py, \"Unwarp the texture\" );\n    m.def( \"unwarpPos\", &unwarpPosMap_py, \"Unwarp the position map\" );\n}\n", "meta": {"hexsha": "bd7feb7d78e568345745722ef65fb04e08b46282", "size": 15576, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unwarp_texture/texUnwarp/texUnwarp.cpp", "max_stars_repo_name": "lelechen63/idinvert_pytorch", "max_stars_repo_head_hexsha": "0469e1e5460ee4dd626c05bd35a83d52f9dc2cac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unwarp_texture/texUnwarp/texUnwarp.cpp", "max_issues_repo_name": "lelechen63/idinvert_pytorch", "max_issues_repo_head_hexsha": "0469e1e5460ee4dd626c05bd35a83d52f9dc2cac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unwarp_texture/texUnwarp/texUnwarp.cpp", "max_forks_repo_name": "lelechen63/idinvert_pytorch", "max_forks_repo_head_hexsha": "0469e1e5460ee4dd626c05bd35a83d52f9dc2cac", "max_forks_repo_licenses": ["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.7587131367, "max_line_length": 138, "alphanum_fraction": 0.5486646122, "num_tokens": 5261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.529921694057513}}
{"text": "#include \"hard_nrosy.h\"\n#include <Eigen/Geometry>\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n#include <Eigen/Eigenvalues>\n#include <iostream>\n\nusing namespace Eigen;\n\nMatrixXd hard_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& hard_id,         // constraints face ids\n        const MatrixXd& hard_value,      // constraints 3d vectors\n        const int n                 // Degree of the n-rosy field\n        )\n{\n  // assert(hard_id.size() > 0); // One constraint is necessary to make the solution unique\n\n  // This code works only for n==1, see tutorial_nrosy_complete for a generic implementation that works for n >= 1\n  // assert(n==1);\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      // 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  for (unsigned r=0; r<hard_id.size(); ++r)\n  {\n    int f = hard_id(r);\n    Vector3d v = hard_value.row(r);\n    std::complex<double> c(v.dot(T1.row(f)),v.dot(T2.row(f)));\n    std::complex<double> o(1,0);\n    t.push_back(Triplet<std::complex<double> >(count,f, o));\n    tb.push_back(Triplet<std::complex<double> >(count,0, c));\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    R.row(f) = T1.row(f) * u(f).real() + T2.row(f) * u(f).imag();\n  \n  return R;\n}", "meta": {"hexsha": "db1b0c45d9df563c2b7ece817bcf95b783063b17", "size": 3310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hard_nrosy.cpp", "max_stars_repo_name": "josherich/libigl-web", "max_stars_repo_head_hexsha": "9b4b56fbd0847d0cb782e6bf159f47550c96903c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-16T01:56:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-09T05:02:32.000Z", "max_issues_repo_path": "hard_nrosy.cpp", "max_issues_repo_name": "josherich/libigl-web", "max_issues_repo_head_hexsha": "9b4b56fbd0847d0cb782e6bf159f47550c96903c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hard_nrosy.cpp", "max_forks_repo_name": "josherich/libigl-web", "max_forks_repo_head_hexsha": "9b4b56fbd0847d0cb782e6bf159f47550c96903c", "max_forks_repo_licenses": ["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.5913978495, "max_line_length": 114, "alphanum_fraction": 0.6117824773, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5299216853106617}}
{"text": "#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <mintrace.h>\n// Following header files are used in the step-3 in the examples of deal.II;\n// Here just using these to get a large scale matrix as the test data.\n#include <deal.II/grid/tria.h>\n#include <deal.II/dofs/dof_handler.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_accessor.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.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/compressed_sparsity_pattern.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n// Finally, this is for output to a file and to the console:\n#include <deal.II/numerics/data_out.h>\n#include <fstream>\n#include <iostream>\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// This function computes the inner-product corresponding with M of <u,v>\nvoid M_inner(SparseMatrix<double> M, std::vector<double>u, std::vector<double>v){}\n\n\nclass Step3\n{\npublic:\n  Step3 ();\n\n  void run ();\n  void make_grid ();\n  void setup_system ();\n  void assemble_system ();\n\n  //void multiply(std::vector<double>& x);\n  std::vector<double> multiply(std::vector<double> x0);\n\n  \n  //void solve ();\n  //\n  void output_results () const;\n\n  Triangulation<2>     triangulation;\n  FE_Q<2>              fe;\n  DoFHandler<2>        dof_handler;\n  SparsityPattern      sparsity_pattern;\n  SparseMatrix<double> system_matrix;\n\n  Vector<double>       solution;\n  Vector<double>       system_rhs;\n  \n  //std::vector<double> x;\n\n};\n\n\n\n//\n//\n//void Step3::multiply(std::vector<double>& x)\nstd::vector<double> multiply(SparseMatrix<double>A, std::vector<double> x0)\n{\n  std::vector<double> x(x0.size(),0);\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\nStep3::Step3 ()\n  :\n  fe (1),\n  dof_handler (triangulation)\n{}\n\nvoid Step3::make_grid ()\n{\n  // First create the grid and refine all cells five times. Since the initial\n  // grid (which is the square [-1,1]x[-1,1]) consists of only one cell, the\n  // final grid has 32 times 32 cells, for a total of 1024.\n  GridGenerator::hyper_cube (triangulation, -1, 1);\n  triangulation.refine_global (5);\n  // Unsure that 1024 is the correct number?  Let's see: n_active_cells\n  // returns the number of active cells:\n  std::cout << \"Number of active cells: \"\n            << triangulation.n_active_cells()\n            << std::endl;\n  \n  std::cout << \"Total number of cells: \"\n            << triangulation.n_cells()\n            << std::endl;\n  // Note the distinction between n_active_cells() and n_cells().\n}\n\nvoid Step3::setup_system ()\n{\n  dof_handler.distribute_dofs (fe);\n  std::cout << \"Number of degrees of freedom: \"\n            << dof_handler.n_dofs()\n            << std::endl;\n  \n  CompressedSparsityPattern c_sparsity(dof_handler.n_dofs());\n  DoFTools::make_sparsity_pattern (dof_handler, c_sparsity);\n  sparsity_pattern.copy_from(c_sparsity);\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\nvoid Step3::assemble_system ()\n{\n\n  QGauss<2>  quadrature_formula(2);\n\n  FEValues<2> fe_values (fe, quadrature_formula,\n                         update_values | update_gradients | update_JxW_values);\n\n  const unsigned int   dofs_per_cell = fe.dofs_per_cell;\n  const unsigned int   n_q_points    = quadrature_formula.size();\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  DoFHandler<2>::active_cell_iterator\n  cell = dof_handler.begin_active(),\n  endc = dof_handler.end();\n  for (; cell!=endc; ++cell)\n    {\n      fe_values.reinit (cell);\n\n      cell_matrix = 0;\n      cell_rhs = 0;\n\n      for (unsigned int i=0; i<dofs_per_cell; ++i)\n        for (unsigned int j=0; j<dofs_per_cell; ++j)\n          for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n            cell_matrix(i,j) += (fe_values.shape_grad (i, q_point) *\n                                 fe_values.shape_grad (j, q_point) *\n                                 fe_values.JxW (q_point));\n\n      for (unsigned int i=0; i<dofs_per_cell; ++i)\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          cell_rhs(i) += (fe_values.shape_value (i, q_point) *\n                          1 *\n                          fe_values.JxW (q_point));\n\n      cell->get_dof_indices (local_dof_indices);\n      ///////////////////////\n      // Following commands compute the interior of the matrix and store them into the matrix.\n      \n      for (unsigned int i=0; i<dofs_per_cell; ++i)\n        for (unsigned int j=0; j<dofs_per_cell; ++j)\n          system_matrix.add (local_dof_indices[i],\n                             local_dof_indices[j],\n                             cell_matrix(i,j));\n\n      // And again, we do the same thing for the right hand side vector.\n      for (unsigned int i=0; i<dofs_per_cell; ++i)\n        system_rhs(local_dof_indices[i]) += cell_rhs(i);\n    }\n\n  std::map<types::global_dof_index,double> boundary_values;\n  VectorTools::interpolate_boundary_values (dof_handler,\n                                            0,\n                                            ZeroFunction<2>(),\n                                            boundary_values);\n\n  MatrixTools::apply_boundary_values (boundary_values,\n                                      system_matrix,\n                                      solution,\n                                      system_rhs);\n}\n\n//void Step3::multiply(std::vector<double>& x)\nstd::vector<double> Step3::multiply(std::vector<double> x0)\n{\n  std::vector<double> x(x0.size(),0);\n  \n  if (system_matrix.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<system_matrix.m();k++)\n\t{\n\t  //std::cout<<\"this is the \"<<k<<\"th iterations \\n\";\n\t  SparseMatrix<double>::const_iterator i=system_matrix.begin(k);\n\t  \n\t  while(i!=system_matrix.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//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\nvoid Step3::run ()\n{\n  make_grid ();\n  setup_system();\n  assemble_system ();\n  std::cout<<system_matrix.m()<<\"\\n\";\n  std::cout<<system_matrix.n()<<\"\\n\";\n\n  //std::cout<<system_matrix.begin()->value()<<\"\\n\";\n  //std::cout<<system_matrix.begin()->column()<<\"\\n\";\n\n  std::vector<double> x(system_matrix.n(),1);\n  //\n  // Due to the system_matrix is a member of the class step3, but x is not a member of the class,\n  // So we can not directly define the multiply function out of the class and using the\n  // system_matrix directly.\n  // we need to get a variable A equals to the system_matrix but A is not a member of the class;\n  \n  std::cout << \"CheckPoint 1 \\n\";\n\n  // multiply(x);\n  x=multiply(x);\n  //std::cout<<\"This is the value of the vector x\"<<x[0]<<std::endl;\n  std::ofstream out (\"sparse_matrix\");\n  system_matrix.print(out);\n\n  std::ofstream output_file (\"solution\");\n  for (const auto &e : x) output_file << e << \"\\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// The function using Conjugate Gradient method to get the solution of the problem Ax=b;\n// It is modified CG function that is designed for solve PAP delta = PAX which needs A, M, X, b;\n// ATTENTION: It can be revised as a class for A and M, It will be more convenient.\nstd::vector<double> CG(SparseMatrix<double>A, SparseMatrix<double> M, std::vector<std::vector<double>> X, std::vector<double> b, std::vector<double> &x)\n{\n  return x;\n}\n\n// Computing the matrix P during the minimal trace process;\nstd::vector<std::vector<double>> matrixP(SparseMatrix<double> M, std::vector<std::vector<double>>X )\n{\n  std::vector<std::vector<double>> P;\n  return P;\n}\n\n//\n// This function computes the matrix M-orthogonal modified Gram-Schmidt procedure;\nstd::vector<double> M_orth(SparseMatrix<double> M, std::vector<double> x)\n{\n  return x;\n}\n\n// This function computes a random matrix V as the initial matrix of the iteration;\n// n implies the column number of V;\nvoid rand_V(SparseMatrix<double>M, std::vector<std::vector<double>> &V, int n)\n{\n  std::vector<std::vector<double>> A(V);\n  V=A;\n}\n\n// Compute matrix A - B;\nstd::vector<std::vector<double>> minus(std::vector<std::vector<double>> A, std::vector<std::vector<double>> B)\n{\n  return A;\n}\n\n// This function computes the smallest p eigenvalues of matrix A corresponding to matrix M; \n// Notice: The A and M are square matrices here.\nstd::vector<double> min_trace(SparseMatrix<double> A, SparseMatrix<double>M, int p, double tol=0.001, int max_iter=1)\n{\n  int n=A.m();\n  std::vector<std::vector<double>>V(p);\n  std::vector<std::vector<double>>W(n);\n  std::vector<std::vector<double>> MXTheta(p), U, X, Rk, delta;\n  //SparseMatrix<double> P;\n  \n  // Construct the initial matrix V1 which is a n x p matrix and it is orthogonal by M, i.e.\n  // V1'*M*V1=I_p;\n  // I store the V(i,j)=V[j][i];\n  rand_V(M,V,p);\n  for (int k=0;k<max_iter;k++)\n    {\n      // Computing the matrix W and H;\n      // Here I use the property of the symmetric A: H=V'*A*V=V'*W=W'*V=H'=V'*A'*V=H;\n\n      // store the A *V[i] into W[i];\n      for(int i=0;i<p;i++)\n\t{\n\t  std::vector<double> tempV=V[i];\n\t  // W[i]=multiply(A,V[i]);\n\t  W[i]=multiply(A,tempV);\n\t}\n\n      // copy the W into H;\n      std::vector<std::vector<double>> H(W);\n      // Computing H'*V; in fact H[i][j]=H(j,i); So above the H=H';\n      // Get the actual Hk;\n      multiply(H,transpose(V));\n\n      // Compute the spectral decomposition of Hk;\n      identitymatrix(U,p);\n      QRSolver(H,U); // H = theta_k, U=U_k;\n\n      // transpose V into V[i][j]=V(i,j);\n      X=transpose(V);\n      // Compute Ritz vectors X_k=V_k*U_k;\n      multiply(X,U);\n      \n      // Compute MXTheta = M * X_k * Theta_k\n      // using XTheta to represent the matrix otherwise X will be changed by multiply;\n      std::vector<std::vector<double>> XTheta(X);    \n      // Compute XTheta = X_k * Theta_k = XTheta*H;\n      multiply(XTheta,H);\n      for(int i=0;i<p;i++)\n\t{\n\t  MXTheta[i]=multiply(M, XTheta[i]);\n\t}\n      // Compute residual Rk in fact Rk[i][j] = Rk(j,i) ;\n      // This step might be wrong;\n      //Rk=minus(multiply(transpose(U),W), MXTheta);\n      /*\n      if(infi_Norm(Rk)<tol)\n\t{\n\t  break;\n\t}\n      */\n\n      // Compute matrix P;\n      //  P=matrixP(M, X);\n      \n      // Solve the SPD eigenvalue problem by modified PCG or CG;\n      // PAP delta_k = PA X_k;\n      // divide it into p eigenvalue problem:\n      // PAP d_i = PA x_i; d_i = delta_k*ei, x_i = X_k*e_i;\n      \n      for(int i=0;i<p;i++)\n\t{\n\t  std::vector<double> x(n,0);\n\t  SparseMatrix<double> PAP;\n\t  std::vector<double> PAXi;\n\t  delta[i]=CG(A, M, X, PAXi, x);\n\t}\n\n\n      // update the V = V_k+1;\n      std::vector<std::vector<double>> XT;\n      XT=transpose(X);\n      for(int i=0;i<p;i++)\n\t{\n\t  XT=minus(XT, delta);\n\t  V[i]=M_orth(M,XT[i]);\n\t}\n      //V=transpose(V);\n    }\n\n  // Compute the diagonal Matrix V'*A*V whose diagonal entries are eigenvalues of the matrix A\n  // corresponding to matrix M;\n\n  std::vector<double> eigenvalue(p);\n  for(int i=0;i<p;i++)\n    {\n      std::vector<double> tempV, tempV2;\n      tempV=multiply(A,V[i]);\n      tempV2=V[i];\n      eigenvalue[i]=multiply(tempV,tempV2);\n    }\n\n  return eigenvalue;\n\n}\n\n\n\nint main()\n{\n  Step3 laplace_problem;\n  /////laplace_problem.run ();\n\n  \n  //std::stringstream result;\n  std::vector<double> b(4,0);\n  std::vector<std::vector<double>> A(4, b), P(4,b);\n  P[0][0]=1;\n  P[1][1]=1;\n  P[2][2]=1;\n  P[3][3]=1;\n  std::vector<std::vector<double>> Q(P);\n\n  A[0][0]=4;\n  A[0][1]=1;\n  A[0][2]=-2;\n  A[0][3]=2;\n  A[1][0]=1;\n  A[1][1]=2;\n  A[1][2]=0;\n  A[1][3]=1;\n  A[2][0]=-2;\n  A[2][1]=0;\n  A[2][2]=3;\n  A[2][3]=-2;\n  A[3][0]=2;\n  A[3][1]=1;\n  A[3][2]=-2;\n  A[3][3]=-1;\n\n  \n  //std::vector<double> c={1,2,3,4};\n  //transpose(A);\n\n  std::cout<<\"The matrix A is :\\n\";\n  std::cout<<\"\\n\";\n \n      \n  for(int i=0;i<A.size();i++)\n    {\n      for(int j=0; j<A.size();j++)\n\t{\n\t  std::cout<<A[i][j]<<\" \";\n\t}\n      std::cout<<\"\\n\";\n    }\n  std::cout<<\"\\n\";\n  \n  // multiply(A,A);\n  \n  // c=multiply(A,c);\n\n  /*\n  Householder(A,P);\n\n  std::cout<<\"The matrix A is :\\n\";\n  std::cout<<\"\\n\";\n      \n  for(int i=0;i<A.size();i++)\n    {\n      for(int j=0; j<A.size();j++)\n\t{\n\t  std::cout<<A[i][j]<<\" \";\n\t}\n      std::cout<<\"\\n\";\n    }\n  std::cout<<\"\\n\";\n\n  QR(A,Q);\n\n  */\n\n  ////\n  //  ATTENTION:!!!!! the original matrix A is symmetric, but after A= QR to get A_=RQ, A_ might be  // nonsymmetric!!!!!! the function is useless!!!!!!! Please edit the function.\n  QRSolver(A,Q);\n\n  std::cout<<\"The matrix A is :\\n\";\n  std::cout<<\"\\n\";\n      \n  for(int i=0;i<A.size();i++)\n    {\n      for(int j=0; j<A.size();j++)\n\t{\n\t  std::cout<<A[i][j]<<\" \";\n\t}\n      std::cout<<\"\\n\";\n    }\n  std::cout<<\"\\n\";\n\n  std::cout<<\"The matrix Q is :::::::\\n\";\n  std::cout<<\"\\n\";\n      \n  for(int i=0;i<Q.size();i++)\n    {\n      for(int j=0; j<Q.size();j++)\n\t{\n\t  std::cout<<Q[i][j]<<\" \";\n\t}\n      std::cout<<\"\\n\";\n    }\n  std::cout<<\"\\n\";\n\n  std::cout<<\"check if the matrix Q is orthogonal\\n\";\n  multiply(Q,transpose(Q));\n\n  std::cout<<\"The matrix Q*Q' is :::::::\\n\";\n  std::cout<<\"\\n\";\n      \n  for(int i=0;i<Q.size();i++)\n    {\n      for(int j=0; j<Q.size();j++)\n\t{\n\t  std::cout<<Q[i][j]<<\" \";\n\t}\n      std::cout<<\"\\n\";\n    }\n  std::cout<<\"\\n\";\n  \n  std::cout<<\"hello world!\"<<std::endl;\n  //SparseMatrix<double> A;\n  return 0;\n}\n", "meta": {"hexsha": "bc1b35f674b659a405ced7ba50f316b785a3a5a8", "size": 23685, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Mintrace/c_min_trace/example/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/example/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/example/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": 24.646201873, "max_line_length": 179, "alphanum_fraction": 0.5492083597, "num_tokens": 7290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5298910738659736}}
{"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 <algorithm>\n#include <iostream>\n#include <vector>\n\n#include <boost/compute/lambda.hpp>\n#include <boost/compute/system.hpp>\n#include <boost/compute/algorithm/copy.hpp>\n#include <boost/compute/algorithm/transform.hpp>\n#include <boost/compute/container/vector.hpp>\n\n#include \"perf.hpp\"\n\nfloat rand_float()\n{\n    return (float(rand()) / float(RAND_MAX)) * 1000.f;\n}\n\n// y <- alpha * x + y\nvoid serial_saxpy(size_t n, float alpha, const float *x, float *y)\n{\n    for(size_t i = 0; i < n; i++){\n        y[i] = alpha * x[i] + y[i];\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    perf_parse_args(argc, argv);\n\n    using boost::compute::lambda::_1;\n    using boost::compute::lambda::_2;\n\n    std::cout << \"size: \" << PERF_N << std::endl;\n\n    float alpha = 2.5f;\n\n    // setup context and queue for the default device\n    boost::compute::device device = boost::compute::system::default_device();\n    boost::compute::context context(device);\n    boost::compute::command_queue queue(context, device);\n    std::cout << \"device: \" << device.name() << std::endl;\n\n    // create vector of random numbers on the host\n    std::vector<float> host_x(PERF_N);\n    std::vector<float> host_y(PERF_N);\n    std::generate(host_x.begin(), host_x.end(), rand_float);\n    std::generate(host_y.begin(), host_y.end(), rand_float);\n\n    // create vector on the device and copy the data\n    boost::compute::vector<float> device_x(host_x.begin(), host_x.end(), queue);\n    boost::compute::vector<float> device_y(host_y.begin(), host_y.end(), queue);\n\n    perf_timer t;\n    for(size_t trial = 0; trial < PERF_TRIALS; trial++){\n        boost::compute::copy(host_x.begin(), host_x.end(), device_x.begin(), queue);\n        boost::compute::copy(host_y.begin(), host_y.end(), device_y.begin(), queue);\n\n        t.start();\n        boost::compute::transform(\n            device_x.begin(),\n            device_x.end(),\n            device_y.begin(),\n            device_y.begin(),\n            alpha * _1 + _2,\n            queue\n        );\n        queue.finish();\n        t.stop();\n    }\n    std::cout << \"time: \" << t.min_time() / 1e6 << \" ms\" << std::endl;\n\n    // perform saxpy on host\n    serial_saxpy(PERF_N, alpha, &host_x[0], &host_y[0]);\n\n    // copy device_y to host_x\n    boost::compute::copy(device_y.begin(), device_y.end(), host_x.begin(), queue);\n\n    for(size_t i = 0; i < PERF_N; i++){\n        float host_value = host_y[i];\n        float device_value = host_x[i];\n\n        if(std::abs(device_value - host_value) > 1e-3){\n            std::cout << \"ERROR: \"\n                      << \"value at \" << i << \" \"\n                      << \"device_value (\" << device_value << \") \"\n                      << \"!= \"\n                      << \"host_value (\" << host_value << \")\"\n                      << std::endl;\n            return -1;\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "904834c1ef98aa6ecd08505df2732d443e3343a1", "size": 3280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perf/perf_saxpy.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": "2021-01-31T17:12:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T17:12:33.000Z", "max_issues_repo_path": "perf/perf_saxpy.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": "perf/perf_saxpy.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": 31.2380952381, "max_line_length": 84, "alphanum_fraction": 0.5567073171, "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5298910691166041}}
{"text": "/**\n * @file mapped_vector.hpp\n * @author David Albert (david.albert@insa-lyon.fr)\n * @brief \n * @version 0.1\n * @date 07/01/2021\n * \n * @copyright Copyright (c) 2021\n * \n */\n#pragma once\n\n#include <iostream>\n#include <unordered_map>\n#include <cmath>\n#include <string>\n#include <vector>\n#include <assert.h>\n\n#include <boost/serialization/base_object.hpp>\n\n#include <sdm/types.hpp>\n#include <sdm/utils/linear_algebra/vector_interface.hpp>\n#include <sdm/utils/struct/vector.hpp>\n#include <sdm/utils/struct/pair.hpp>\n#include <sdm/utils/struct/recursive_map.hpp>\n\nnamespace sdm\n{\n    /**\n     * @brief Mapped vectors are vectors with specific type of indexes. They are represented by a map. \n     * \n     * @tparam TIndex the type of index\n     * @tparam T the type of value (default : `double`)\n     * \n     * Using map structure allows to keep only necessary values. \n     * Moreover, it allows to see vectors not only as a mapping from integer to value but also as a mapping from any type of index to values.   \n     *\n     */\n    template <class TIndex, class T = double, class Hash = std::hash<TIndex>, class KeyEqual = std::equal_to<TIndex>>\n    class MappedVector : public std::unordered_map<TIndex, T, Hash, KeyEqual>, public VectorInterface<TIndex, T>\n    {\n    public:\n        using iterator = typename std::unordered_map<TIndex, T, Hash, KeyEqual>::iterator;\n        using const_iterator = typename std::unordered_map<TIndex, T, Hash, KeyEqual>::const_iterator;\n\n        using type = typename RecursiveMap<TIndex, T>::type;\n        using value_type = typename RecursiveMap<TIndex, T>::value_type;\n        using value_list_type = typename RecursiveMap<TIndex, T>::value_list_type;\n\n        static double PRECISION;\n\n        MappedVector();\n        MappedVector(T default_value);\n        MappedVector(long size, T default_value);\n        MappedVector(const MappedVector &);\n        MappedVector(std::initializer_list<value_list_type>);\n        virtual ~MappedVector();\n\n        T norm_1() const;\n        T norm_2() const;\n\n        T min();\n        TIndex argmin();\n\n        T max();\n        TIndex argmax();\n\n        T at(const TIndex &) const;\n        T getValueAt(const TIndex &) const;\n        void setValueAt(const TIndex &, const T &);\n        void addValueAt(const TIndex &, const T &);\n\n        bool isExist(const TIndex&) const;\n\n        /**\n         * @brief This method implements a non-commutative dot product\n         * @comment: It is worth noticing that sometimes arg1.dot(arg2) !=  arg2.dot(arg1)\n         * @return T \n         */\n        T operator^(const MappedVector &) const;\n        T operator*(const MappedVector &) const;\n\n        MappedVector add(const MappedVector &other, double coef_this = 1., double coef_other = 1.) const\n        {\n            MappedVector sum;\n            for (const auto &item : this->getIndexes())\n            {\n                sum.setValueAt(item, coef_this * this->getValueAt(item) + coef_other * other.getValueAt(item));\n            }\n            for (const auto &item : other.getIndexes())\n            {\n                sum.setValueAt(item, coef_this * this->getValueAt(item) + coef_other * other.getValueAt(item));\n            }\n            sum.finalize();\n            return sum;\n        }\n\n        bool operator!=(const MappedVector &) const;\n        bool operator<(const MappedVector &) const;\n        bool operator==(const MappedVector &other) const;\n        bool isEqual(const MappedVector &other, double precision) const;\n\n        /**\n         * @brief This method implements a non-commutative dot product\n         * @comment: It is worth noticing that sometimes arg1.dot(arg2) !=  arg2.dot(arg1)\n         * @return T \n         */\n        T dot(const MappedVector &) const;\n\n        T getDefault() const;\n        void setDefault(double default_value);\n\n        void setupIndexes();\n        void finalize();\n\n        std::vector<TIndex> getIndexes() const;\n\n        static void setPrecision(double);\n\n        std::string str() const;\n        size_t size() const;\n\n        friend std::ostream &operator<<(std::ostream &os, const MappedVector &vect)\n        {\n            os << vect.str();\n            return os;\n        }\n\n        friend class boost::serialization::access;\n\n        template <class Archive>\n        void serialize(Archive &archive, const unsigned int);\n\n    protected:\n        T default_value_ = 0.0;\n        long size_ = -1;\n\n        std::vector<TIndex> v_indexes = {};\n\n        bool bmin = false, bmax = false;\n        std::pair<TIndex, T> pmin, pmax;\n\n        const std::pair<TIndex, T> &getMin();\n        const std::pair<TIndex, T> &getMax();\n    };\n} // namespace sdm\n#include <sdm/utils/linear_algebra/mapped_vector.tpp>", "meta": {"hexsha": "e0884a31e4038a8bfac071d7362d8ec3b7bd31e8", "size": 4706, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/sdm/utils/linear_algebra/mapped_vector.hpp", "max_stars_repo_name": "SDMStudio/sdms", "max_stars_repo_head_hexsha": "43a86973081ffd86c091aed69b332f0087f59361", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sdm/utils/linear_algebra/mapped_vector.hpp", "max_issues_repo_name": "SDMStudio/sdms", "max_issues_repo_head_hexsha": "43a86973081ffd86c091aed69b332f0087f59361", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sdm/utils/linear_algebra/mapped_vector.hpp", "max_forks_repo_name": "SDMStudio/sdms", "max_forks_repo_head_hexsha": "43a86973081ffd86c091aed69b332f0087f59361", "max_forks_repo_licenses": ["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.7972972973, "max_line_length": 144, "alphanum_fraction": 0.6164470888, "num_tokens": 1110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5298457811506139}}
{"text": "/**\n * @file   CartanMatrixTest.cpp\n * @author ALIKAWA Hidehisa <alleyhide@gmail.com>\n * @date   2018/09/01\n \n * \n * @brief  for the tests of Cartan matrix\n * \n * Released under the MIT license\n */\n\n#include <iostream>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"gweyl.hpp\"\n\nint main(int argc, char** argv)\n{\n    //std::cout << argv[0] << \" and \" << argv[1] << \" and \" << argv[2] << std::endl;\n\n\n    char t = argv[1][0];\n\n    //std::cout << \"Type is \" << t << std::endl;\n\n    gweyl::Type X;\n    switch (t){\n    case 'A':\n        X=gweyl::Type::A;\n        break;\n    case 'B':\n        X=gweyl::Type::B;\n        break;\n    case 'C':\n        X=gweyl::Type::C;\n        break;\n    case 'D':\n        X=gweyl::Type::D;\n        break;\n    case 'E':\n        X=gweyl::Type::E;\n        break;                \n    case 'F':\n        X=gweyl::Type::F;\n        break;\n    case 'G':\n        X=gweyl::Type::G;\n        break;        \n    default:\n        std::cout << \"Error type \" << std::to_string(t);\n        return -1;\n    }\n\n    unsigned n = atoi(argv[2]);\n\n    try {\n        //gweyl::matrix CarMat = gweyl::CartanMatrix(X, n);\n        gweyl::Cartan T(X, n);\n        gweyl::matrix CarMat = T.CartanMatrix();\n        std::cout << CarMat << std::endl;\n    }catch (std::exception &e){\n        std::cout << \"Exeption is caught \\n what(): \";\n        std::cout << e.what();\n        std::cout << \"\\nError test CartanMatrix\" << std::endl;\n    }\n    \n    return 0;\n}\n", "meta": {"hexsha": "350425a99f73a7c520a3c05c87f6fcb5d346f401", "size": 1450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/CartanMatrixTest.cpp", "max_stars_repo_name": "alleyhide/gweyl", "max_stars_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/CartanMatrixTest.cpp", "max_issues_repo_name": "alleyhide/gweyl", "max_issues_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/CartanMatrixTest.cpp", "max_forks_repo_name": "alleyhide/gweyl", "max_forks_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0144927536, "max_line_length": 84, "alphanum_fraction": 0.4868965517, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5297545633606263}}
{"text": "#include <iostream>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\nint main()\n{\n    namespace ba = boost::accumulators;\n\n    ba::accumulator_set<double, ba::features<ba::tag::mean, ba::tag::variance>, int> acc;\n    acc(8, ba::weight=1);\n    acc(9, ba::weight=1);\n    acc(10, ba::weight=4);\n    acc(11, ba::weight=1);\n    acc(12, ba::weight=1);\n    std::cout << ba::mean(acc) << \":\" << ba::variance(acc) << std::endl;\n}\n", "meta": {"hexsha": "d4aff6da4e6e37e32e1da581eb90258180d6c327", "size": 466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lecture-9/example14-1.cpp", "max_stars_repo_name": "cvlabmiet/master-programming", "max_stars_repo_head_hexsha": "daec0d5a415011d44a124b8b7fe8ba2cd043bebd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-19T14:15:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T10:35:26.000Z", "max_issues_repo_path": "lecture-9/example14-1.cpp", "max_issues_repo_name": "cvlabmiet/master-programming", "max_issues_repo_head_hexsha": "daec0d5a415011d44a124b8b7fe8ba2cd043bebd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-09-06T17:31:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T17:10:11.000Z", "max_forks_repo_path": "lecture-9/example14-1.cpp", "max_forks_repo_name": "cvlabmiet/master-programming", "max_forks_repo_head_hexsha": "daec0d5a415011d44a124b8b7fe8ba2cd043bebd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-12-07T11:06:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T14:18:46.000Z", "avg_line_length": 25.8888888889, "max_line_length": 89, "alphanum_fraction": 0.6244635193, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5297545582955265}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2020, Jesus Tordesillas Torres, Aerospace Controls Laboratory\n * Massachusetts Institute of Technology\n * All Rights Reserved\n * Authors: Jesus Tordesillas, et al.\n * See LICENSE file for the license information\n * -------------------------------------------------------------------------- */\n\n#ifndef SOLVER_GUROBI_HPP\n#define SOLVER_GUROBI_HPP\n#include <Eigen/Dense>\n#include \"gurobi_c++.h\"\n#include <sstream>\n#include <Eigen/Dense>\n#include <type_traits>\n#include <fstream>\n#include \"termcolor.hpp\"\n\n#include <decomp_ros_utils/data_ros_utils.h>\n#include <unsupported/Eigen/Polynomials>\n#include \"faster_types.hpp\"\nusing namespace termcolor;\n\n// TODO: This function is the same as solvePolyOrder2 but with other name (weird conflicts...)\ninline double solvePolynomialOrder2(Eigen::Vector3f& coeff)\n{\n  // std::cout << \"solving\\n\" << coeff.transpose() << std::endl;\n  double a = coeff(0);\n  double b = coeff(1);\n  double c = coeff(2);\n  double dis = b * b - 4 * a * c;\n  if (dis >= 0)\n  {\n    double x1 = (-b - sqrt(dis)) / (2 * a);  // x1 will always be smaller than x2\n    double x2 = (-b + sqrt(dis)) / (2 * a);\n\n    if (x1 >= 0)\n    {\n      return x1;\n    }\n    if (x2 >= 0)\n    {\n      return x2;\n    }\n  }\n  printf(\"No solution found to the equation\\n\");\n  return std::numeric_limits<float>::max();\n}\n\nclass mycallback : public GRBCallback\n{\npublic:\n  bool should_terminate_;\n  mycallback();  // constructor\n  // void abortar();\n\nprotected:\n  void callback();\n};\n\nclass SolverGurobi\n{\npublic:\n  SolverGurobi();\n\n  // void setQ(double q);\n  void setN(int N);\n  void setX0(state& data);\n  // void set_u0(double u0[]);\n  void setXf(state& data);\n  void resetX();\n  void setBounds(double max_values[3]);\n  bool genNewTraj();\n  bool callOptimizer();\n  double getDTInitial();\n\n  void setDC(double dc);\n  void setPolytopes(std::vector<LinearConstraint3D> polytopes);\n  void setPolytopesConstraints();\n  void findDT(double factor);\n  void fillX();\n  void setObjective();\n  void setConstraintsXf();\n  void setConstraintsX0();\n  void setDynamicConstraints();\n  void setForceFinalConstraint(bool forceFinalConstraint);\n\n  // For the jackal\n  void setWMax(double w_max);\n  bool isWmaxSatisfied();\n\n  void setMaxConstraints();\n  void createVars();\n  void setThreads(int threads);\n  void setVerbose(int verbose);\n\n  void StopExecution();\n  void ResetToNormalState();\n\n  void setDistances(vec_Vecf<3>& samples, std::vector<double> dist_near_obs);\n\n  // void setSamplesPenalize(vec_Vecf<3>& samples_penalize);\n\n  void setDistanceConstraints();\n\n  void setMode(int mode);\n  void setFactorInitialAndFinalAndIncrement(double factor_initial, double factor_final, double factor_increment);\n\n  GRBLinExpr getPos(int t, double tau, int ii);\n  GRBLinExpr getVel(int t, double tau, int ii);\n  GRBLinExpr getAccel(int t, double tau, int ii);\n  GRBLinExpr getJerk(int t, double tau, int ii);\n\n  GRBLinExpr getA(int t, int ii);\n  GRBLinExpr getB(int t, int ii);\n  GRBLinExpr getC(int t, int ii);\n  GRBLinExpr getD(int t, int ii);\n\n  // Getters of the Normalized coefficients\n  GRBLinExpr getAn(int t, int ii);\n  GRBLinExpr getBn(int t, int ii);\n  GRBLinExpr getCn(int t, int ii);\n  GRBLinExpr getDn(int t, int ii);\n\n  std::vector<GRBLinExpr> getCP0(int t);\n  std::vector<GRBLinExpr> getCP1(int t);\n  std::vector<GRBLinExpr> getCP2(int t);\n  std::vector<GRBLinExpr> getCP3(int t);\n\n  std::vector<state> X_temp_;\n  double dt_;  // time step found by the solver\n  int trials_ = 0;\n  int temporal_ = 0;\n  double runtime_ms_ = 0;\n  double factor_that_worked_ = 0;\n  int N_ = 10;\n  mycallback cb_;\n\nprotected:\n  double cost_;\n\n  double xf_[3 * 3];\n  double x0_[3 * 3];\n  double v_max_;\n  double a_max_;\n  double j_max_;\n  double DC;\n  // double q_;  // weight to the 2nd term in the cost function\n  double** x_;\n  double** u_;\n\n  int N_of_polytopes_ = 3;\n\n  GRBEnv* env = new GRBEnv();\n  GRBModel m = GRBModel(*env);\n\n  std::vector<GRBConstr> at_least_1_pol_cons;  // Constraints at least in one polytope\n  std::vector<GRBGenConstr> polytopes_cons;    // Used for the whole trajectory\n  std::vector<GRBConstr> polytope_cons;        // Used for the rescue path\n  std::vector<GRBConstr> dyn_cons;\n  std::vector<GRBConstr> init_cons;\n  std::vector<GRBConstr> final_cons;\n\n  std::vector<GRBQConstr> distances_cons;\n\n  std::vector<std::vector<GRBVar>> b;  // binary variables\n  std::vector<std::vector<GRBVar>> x;\n  std::vector<std::vector<GRBVar>> u;\n\n  vec_Vecf<3> samples_;           // Samples along the rescue path\n  vec_Vecf<3> samples_penalize_;  // Samples along the rescue path\n\n  std::vector<double> dist_near_obs_;\n  std::vector<LinearConstraint3D> polytopes_;\n\n  std::ofstream times_log;\n\n  int mode_;\n  bool forceFinalConstraint_ = true;\n  double factor_initial_ = 2;\n  double factor_final_ = 2;\n  double factor_increment_ = 2;\n\n  int total_not_solved = 0;\n  double w_max_ = 1;\n};\n#endif", "meta": {"hexsha": "b3a347d8e61dff3bf912eac3b167c4c912e305da", "size": 4961, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "faster/include/solverGurobi.hpp", "max_stars_repo_name": "wyr501/faster", "max_stars_repo_head_hexsha": "df92802a72b1e5d2acf0682d0772d14a56bf56ab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 489.0, "max_stars_repo_stars_event_min_datetime": "2020-03-19T15:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:22:55.000Z", "max_issues_repo_path": "faster/include/solverGurobi.hpp", "max_issues_repo_name": "wyr501/faster", "max_issues_repo_head_hexsha": "df92802a72b1e5d2acf0682d0772d14a56bf56ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2020-05-08T13:51:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T07:43:21.000Z", "max_forks_repo_path": "faster/include/solverGurobi.hpp", "max_forks_repo_name": "wyr501/faster", "max_forks_repo_head_hexsha": "df92802a72b1e5d2acf0682d0772d14a56bf56ab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 116.0, "max_forks_repo_forks_event_min_datetime": "2020-03-19T20:37:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T03:51:21.000Z", "avg_line_length": 26.5294117647, "max_line_length": 113, "alphanum_fraction": 0.6762749446, "num_tokens": 1437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5297545564137189}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\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, EVecPRESS 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 <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <smooth/so3.hpp>\n\n#include \"smooth/feedback/ocp_to_nlp.hpp\"\n\ntemplate<typename T, std::size_t N>\nusing Vec = Eigen::Vector<T, N>;\n\nTEST(OcpToNlp, Derivatives2)\n{\n  // objective\n  auto theta = []<typename T>(T tf, Vec<T, 2> x0, Vec<T, 2> xf, Vec<T, 1> q) -> T {\n    return (tf - 2) * (tf - 2) + x0.cwiseProduct(xf).squaredNorm() + xf.squaredNorm() + q.sum();\n  };\n\n  // dynamics\n  auto f = []<typename T>(T t, Vec<T, 2> x, Vec<T, 1> u) -> Vec<T, 2> {\n    return Vec<T, 2>{{x.y() + t, x.x() * u.x() * u.x()}};\n  };\n\n  // integrals\n  auto g = []<typename T>(T t, Vec<T, 2> x, Vec<T, 1> u) -> Vec<T, 1> {\n    return Vec<T, 1>{{t + t * x.squaredNorm() + u.squaredNorm()}};\n  };\n\n  // running constraint\n  auto cr = []<typename T>(T t, Vec<T, 2> x, Vec<T, 1> u) -> Vec<T, 4> {\n    Vec<T, 4> ret(4);\n    ret << t, t * x * u.x(), u.cwiseAbs2();\n    return ret;\n  };\n\n  // end constraint\n  auto ce = []<typename T>(T tf, Vec<T, 2> x0, Vec<T, 2> xf, Vec<T, 1> q) -> Vec<T, 6> {\n    Vec<T, 6> ret(6);\n    ret << tf, x0.cwiseProduct(xf), xf, q.cwiseAbs2();\n    return ret;\n  };\n\n  const smooth::feedback::OCP<\n    Vec<double, 2>,\n    Vec<double, 1>,\n    decltype(theta),\n    decltype(f),\n    decltype(g),\n    decltype(cr),\n    decltype(ce)>\n    ocp{\n      .theta = theta,\n      .f     = f,\n      .g     = g,\n      .cr    = cr,\n      .crl   = Vec<double, 4>::Constant(4, -1),\n      .cru   = Vec<double, 4>::Constant(4, 1),\n      .ce    = ce,\n      .cel   = Vec<double, 6>::Constant(6, -1),\n      .ceu   = Vec<double, 6>::Constant(6, 1),\n    };\n\n  smooth::feedback::Mesh<3, 3> mesh;\n  mesh.refine_ph(0, 4);\n  mesh.refine_ph(0, 4);\n\n  auto nlp = ocp_to_nlp(ocp, mesh);\n\n  using nlp_t = std::decay_t<decltype(nlp)>;\n  static_assert(smooth::feedback::HessianNLP<nlp_t>);\n\n  srand(5);\n  const Eigen::VectorXd x      = Eigen::VectorXd::Random(nlp.n());\n  const Eigen::VectorXd lambda = Eigen::VectorXd::Random(nlp.m());\n\n  // Analytic derivatives\n  const auto & df_dx   = nlp.df_dx(x);\n  const auto & d2f_dx2 = nlp.d2f_dx2(x);\n  const auto & dg_dx   = nlp.dg_dx(x);\n  const auto & d2g_dx2 = nlp.d2g_dx2(x, lambda);\n\n  // Numerical derivatives (of base function)\n  const auto [fval, df_dx_num, d2f_dx2_num] =\n    smooth::diff::dr<2>([&](const auto & xvar) { return nlp.f(xvar); }, smooth::wrt(x));\n  const auto [gval, dg_dx_num] =\n    smooth::diff::dr<1>([&](const auto & xvar) { return nlp.g(xvar); }, smooth::wrt(x));\n  const auto g_l_fun = [&](Eigen::VectorXd xvar) -> double { return lambda.dot(nlp.g(xvar)); };\n  const auto [u1_, u2_, d2g_dx2_num] = smooth::diff::dr<2>(g_l_fun, smooth::wrt(x));\n\n  ASSERT_TRUE(Eigen::MatrixXd(df_dx).isApprox(df_dx_num, 1e-4));\n  ASSERT_TRUE(Eigen::MatrixXd(dg_dx).isApprox(dg_dx_num, 1e-4));\n  ASSERT_TRUE(Eigen::MatrixXd(Eigen::MatrixXd(d2f_dx2).selfadjointView<Eigen::Upper>())\n                .isApprox(d2f_dx2_num, 1e-3));\n  ASSERT_TRUE(Eigen::MatrixXd(Eigen::MatrixXd(d2g_dx2).selfadjointView<Eigen::Upper>())\n                .isApprox(d2g_dx2_num, 1e-3));\n}\n", "meta": {"hexsha": "c94fee71ae262ecc5cd5d2c79b3b955f2f5ed8b2", "size": 4328, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_ocp_to_nlp.cpp", "max_stars_repo_name": "tgurriet/smooth_feedback", "max_stars_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_stars_repo_licenses": ["MIT"], "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_ocp_to_nlp.cpp", "max_issues_repo_name": "tgurriet/smooth_feedback", "max_issues_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_issues_repo_licenses": ["MIT"], "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_ocp_to_nlp.cpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["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.7685950413, "max_line_length": 96, "alphanum_fraction": 0.6356284658, "num_tokens": 1380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5297545564137189}}
{"text": "//=======================================================================\n// Copyright (c)\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 knapsack_test.cpp\n * @brief\n * @author Piotr Wygocki\n * @version 1.0\n * @date 2013-09-20\n */\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/knapsack_tags_utils.hpp\"\n\n#include \"paal/dynamic/knapsack_unbounded.hpp\"\n#include \"paal/dynamic/knapsack_0_1.hpp\"\n#include \"paal/dynamic/knapsack_unbounded_fptas.hpp\"\n#include \"paal/dynamic/knapsack_0_1_fptas.hpp\"\n#include \"paal/utils/floating.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/fusion/include/for_each.hpp>\n\n#include <fstream>\n\nusing namespace paal;\n\nnamespace {\nconst int capacity = 6;\nusing Objects = std::vector<std::pair<int, int>>;\nObjects objects{ { 1, 3 }, { 2, 2 }, { 3, 65 }, { 1, 1 }, { 2, 2 }, { 4, 3 },\n                 { 1, 1 }, { 10, 23 } };\nauto size = [](std::pair<int, int> object) { return object.first; };\nauto value = [](std::pair<int, int> object) { return object.second; };\n}\n\nstatic const double OPT = 130;\nstatic const double OPT_0_1 = 70;\nstatic const double OPT_CAP = 6;\nstatic const double EPSILON = 1. / 4.;\nstatic const double VALUE_MULTIPLIER = 1. - EPSILON;\nstatic const double SIZE_MULTIPLIER = 1. + EPSILON;\nstatic const utils::compare<double> compare(0.001);\n\ntemplate <typename MaxValue>\nvoid check(MaxValue maxValue, pd::unbounded_tag, double valMultiplier = 1,\n           double capMultiplier = 1) {\n    BOOST_CHECK(compare.ge(maxValue.first, OPT * valMultiplier));\n    BOOST_CHECK(compare.ge(OPT_CAP * capMultiplier, maxValue.second));\n}\n\ntemplate <typename MaxValue>\nvoid check(MaxValue maxValue, pd::zero_one_tag, double valMultiplier = 1,\n           double capMultiplier = 1) {\n    BOOST_CHECK(compare.ge(maxValue.first, OPT_0_1 * valMultiplier));\n    BOOST_CHECK(compare.ge(OPT_CAP * capMultiplier, maxValue.second));\n}\n\ntemplate <typename IntegralTag, typename IsZeroOne,\n          typename RetrieveSolution = pd::retrieve_solution_tag>\nvoid detail_knapsack_and_check() {\n    auto maxValue = detail_knapsack<IntegralTag, IsZeroOne, RetrieveSolution>(\n        objects, capacity, size, value);\n    check(maxValue, IsZeroOne());\n}\n\nBOOST_AUTO_TEST_CASE(KnapsackOverloads) {\n    detail_knapsack_and_check<pd::integral_value_tag, pd::unbounded_tag>();\n    detail_knapsack_and_check<pd::integral_size_tag, pd::unbounded_tag>();\n    detail_knapsack_and_check<pd::integral_value_and_size_tag,\n                              pd::unbounded_tag>();\n    detail_knapsack_and_check<pd::integral_value_tag, pd::zero_one_tag,\n                              pd::retrieve_solution_tag>();\n    detail_knapsack_and_check<pd::integral_size_tag, pd::zero_one_tag,\n                              pd::retrieve_solution_tag>();\n    detail_knapsack_and_check<pd::integral_value_and_size_tag, pd::zero_one_tag,\n                              pd::retrieve_solution_tag>();\n    detail_knapsack_and_check<pd::integral_value_tag, pd::zero_one_tag,\n                              pd::no_retrieve_solution_tag>();\n    detail_knapsack_and_check<pd::integral_size_tag, pd::zero_one_tag,\n                              pd::no_retrieve_solution_tag>();\n    detail_knapsack_and_check<pd::integral_value_and_size_tag, pd::zero_one_tag,\n                              pd::no_retrieve_solution_tag>();\n}\n\n// Knapsack\nBOOST_AUTO_TEST_CASE(Knapsack) {\n    Objects result;\n    LOGLN(\"Knapsack\");\n    auto maxValue = paal::knapsack_unbounded(\n        objects, capacity, std::back_inserter(result), size, value);\n\n    check(maxValue, pd::unbounded_tag{});\n    print_result(maxValue, result, pd::retrieve_solution_tag());\n}\n\n// Knapsack 0/1\nBOOST_AUTO_TEST_CASE(Knapsack_0_1) {\n    Objects result;\n    LOGLN(\"Knapsack 0/1\");\n    auto maxValue = paal::knapsack_0_1(objects, capacity,\n                                       std::back_inserter(result), size, value);\n    check(maxValue, pd::zero_one_tag());\n    print_result(maxValue, result, pd::retrieve_solution_tag());\n}\n\nBOOST_AUTO_TEST_CASE(Knapsack_0_1_no_output) {\n    Objects result;\n    LOGLN(\"Knapsack 0/1 no output\");\n    auto maxValue =\n        paal::knapsack_0_1_no_output(objects, capacity, size, value);\n\n    check(maxValue, pd::zero_one_tag());\n    print_max_value(maxValue);\n}\n\n// Knapsack fptas value\nBOOST_AUTO_TEST_CASE(Knapsack_fptas_value) {\n    Objects result;\n    LOGLN(\"Knapsack fptas value\");\n    auto maxValue = paal::knapsack_unbounded_on_value_fptas(\n        EPSILON, objects, capacity, std::back_inserter(result), size, value);\n\n    check(maxValue, pd::unbounded_tag{}, VALUE_MULTIPLIER);\n    print_result(maxValue, result, pd::retrieve_solution_tag());\n}\n\n// TODO this tests is very weak because it runs standard algorithm no fptas\n// Knapsack fptas size\nBOOST_AUTO_TEST_CASE(Knapsack_fptas_size) {\n    Objects result;\n    LOGLN(\"Knapsack fptas size\");\n    auto maxValue = paal::knapsack_unbounded_on_size_fptas(\n        EPSILON, objects, capacity, std::back_inserter(result), size, value);\n\n    print_result(maxValue, result, pd::retrieve_solution_tag());\n    check(maxValue, pd::unbounded_tag{}, 1., SIZE_MULTIPLIER);\n}\n\n// Knapsack 0/1: no output iterator size fptas\nBOOST_AUTO_TEST_CASE(Knapsack_0_1_no_output_size_fptas) {\n    Objects result;\n    LOGLN(\"Knapsack 0/1 no output size fptas\");\n    auto maxValue = paal::knapsack_0_1_no_output_on_size_fptas(\n        EPSILON, objects, capacity, size, value);\n\n    check(maxValue, pd::zero_one_tag(), 1, SIZE_MULTIPLIER);\n    print_max_value(maxValue);\n}\n\n// Knapsack 0/1: no output iterator value fptas\nBOOST_AUTO_TEST_CASE(Knapsack_0_1_no_output_value_fptas) {\n    Objects result;\n    LOGLN(\"Knapsack 0/1 no output value fptas\");\n    auto maxValue = paal::knapsack_0_1_no_output_on_value_fptas(\n        EPSILON, objects, capacity, size, value);\n\n    check(maxValue, pd::zero_one_tag(), VALUE_MULTIPLIER);\n    print_max_value(maxValue);\n}\n\n// Knapsack 0/1 value fptas\nBOOST_AUTO_TEST_CASE(Knapsack_0_1_value_fptas) {\n    Objects result;\n    LOGLN(\"Knapsack 0/1 on value fptas\");\n    auto maxValue = paal::knapsack_0_1_on_value_fptas(\n        EPSILON, objects, capacity, std::back_inserter(result), size, value);\n\n    check(maxValue, pd::zero_one_tag(), VALUE_MULTIPLIER);\n    print_result(maxValue, result, pd::retrieve_solution_tag());\n}\n\n// Knapsack 0/1  size fptas\nBOOST_AUTO_TEST_CASE(Knapsack_0_1_size_fptas) {\n    Objects result;\n    LOGLN(\"Knapsack 0/1 on size fptas\");\n    auto maxValue = paal::knapsack_0_1_on_size_fptas(\n        EPSILON, objects, capacity, std::back_inserter(result), size, value);\n\n    check(maxValue, pd::zero_one_tag(), 1, SIZE_MULTIPLIER);\n    print_result(maxValue, result, pd::retrieve_solution_tag());\n}\n", "meta": {"hexsha": "58a8327acb742cd87e43583c3532bd2e2956898a", "size": 6866, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/dynamic/knapsack/knapsack_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/dynamic/knapsack/knapsack_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/dynamic/knapsack/knapsack_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": 36.7165775401, "max_line_length": 80, "alphanum_fraction": 0.690212642, "num_tokens": 1863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.529754551348619}}
{"text": "/* D.R. Reynolds\n   Math 6321 @ SMU\n   Fall 2020  */\n\n// Inclusions\n#include <stdlib.h>\n#include <iostream>\n#include <armadillo>\nusing namespace arma;\n\n// Example routine to show how to perform C++ output from Armadillo's\n// `mat' and 'vec' classes, followed by input/plotting in Matlab/Python\nint main(int argc, char **argv) {\n\n  // get problem size from command line, otherwise set to 201\n  int N = 201;\n  if (argc > 1)\n    N = atoi(argv[1]);\n  std::cout << \"\\nRunning I/O test using vectors of size N = \" << N << std::endl;\n  \n  // create x data\n  vec x = linspace(-1.0, 1.0, N);\n\n  // create function data (first 5 odd-degree Chebyshev polynomials)\n  mat T(N,5);\n  for (int j=0; j<5; j++)\n    for (int i=0; i<N; i++)\n      T(i,j) = cos((j*2+1.0) * acos(x(i)));\n\n  // save data to disk\n  x.save(\"x.txt\", arma::raw_ascii);\n  T.save(\"T.txt\", arma::raw_ascii);\n  \n  std::cout << \"Completed writing data to disk: x.txt and T.txt\\n\\n\";\n  return 0;\n} // end main\n", "meta": {"hexsha": "e7bac3fee7d77d6f1cc8e58ee0294242cf27a221", "size": 960, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "input_output/io_intro.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": "input_output/io_intro.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": "input_output/io_intro.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": 25.9459459459, "max_line_length": 81, "alphanum_fraction": 0.615625, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5297511366454913}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <crave/ConstrainedRandom.hpp>\n\n#include <boost/format.hpp>\n\n#include <set>\n#include <iostream>\n\n// using namespace std;\nusing namespace crave;\n\nusing boost::format;\n\nBOOST_FIXTURE_TEST_SUITE(Distribution_t, Context_Fixture)\n\nstruct s_crv_variable_dist_t1 : public crv_sequence_item {\n  s_crv_variable_dist_t1(crv_object_name) {}\n  crv_variable<int> v;\n  crv_constraint con = {\n      dist(v(), make_distribution(range<int>(0, 5), range<int>(50, 65), range<int>(100, 125)))};\n};\n\nBOOST_AUTO_TEST_CASE(crv_variable_dist_t1) {\n  s_crv_variable_dist_t1 item(\"item\");\n  std::map<int, int> s;\n  int total = 100000;\n  for (int i = 0; i < total; i++) {\n    BOOST_REQUIRE(item.randomize());\n    BOOST_REQUIRE((0 <= item.v && item.v <= 5) || (50 <= item.v && item.v <= 65) || (100 <= item.v && item.v <= 125));\n    ++s[item.v];\n  }\n  for (int i = 0; i <= 200; i++)\n    if ((0 <= i && i <= 5) || (50 <= i && i <= 65) || (100 <= i && i <= 125))\n      BOOST_REQUIRE(s.find(i) != s.end());\n}\n\nstruct s_crv_variable_dist_t2 : public crv_sequence_item {\n  s_crv_variable_dist_t2(crv_object_name) {}\n  crv_variable<int> v;\n  crv_constraint con;\n};\n\nBOOST_AUTO_TEST_CASE(crv_variable_dist_t2) {\n  s_crv_variable_dist_t2 item(\"item\");\n  BOOST_REQUIRE_THROW(\n      item.con = {dist(item.v(), make_distribution(range<int>(0, 10), range<int>(50, 75), range<int>(30, 51)))},\n      std::runtime_error);\n}\n\nstruct s_crv_variable_dist_t3 : public crv_sequence_item {\n  s_crv_variable_dist_t3(crv_object_name) {}\n  crv_variable<char> v;\n  crv_constraint con = {dist(v(), make_distribution(weighted_range<char>(1, 5, 50), weighted_range<char>(10, 20, 20),\n                        weighted_range<char>(-50, -50, 30)))};\n};\n\nBOOST_AUTO_TEST_CASE(crv_variable_dist_t3) {\n  s_crv_variable_dist_t3 item(\"item\");\n  int cnt1 = 0, cnt2 = 0, cnt3 = 0;\n  int total = 50000;\n  for (int i = 0; i < total; i++) {\n    BOOST_REQUIRE(item.randomize());\n    BOOST_REQUIRE((1 <= item.v && item.v <= 5) || (10 <= item.v && item.v <= 20) || (item.v == -50));\n    if (1 <= item.v && item.v <= 5) cnt1++;\n    if (10 <= item.v && item.v <= 20) cnt2++;\n    if (item.v == -50) cnt3++;\n  }\n  BOOST_REQUIRE_LT(cnt2, cnt3);\n  BOOST_REQUIRE_LT(cnt3, cnt1);\n}\n\nstruct s_crv_variable_dist_t4 : public crv_sequence_item {\n  s_crv_variable_dist_t4(crv_object_name) {}\n  crv_variable<int> v;\n  crv_constraint x = {dist(v(), make_distribution(range<int>(0, 10), range<int>(50, 75), range<int>(100, 200)))};\n  crv_constraint y = {dist(v(), make_distribution(range<int>(5000, 6000)))};\n};\n\nBOOST_AUTO_TEST_CASE(crv_variable_dist_t4) {\n  s_crv_variable_dist_t4 item(\"item\");\n  item.x.deactivate();\n  int total = 10000;\n  for (int i = 0; i < total; i++) {\n    BOOST_REQUIRE(item.randomize());\n    BOOST_REQUIRE(5000 <= item.v && item.v <= 6000);\n  }\n}\n\nstruct s_dist_of_boolean25 : crv_sequence_item {\n  s_dist_of_boolean25(crv_object_name) {}\n  crv_variable<bool> a;\n  crv_constraint con = {dist(a(), distribution<bool>::create(0.25))};\n};\n\nBOOST_AUTO_TEST_CASE(dist_of_boolean25) {\n  s_dist_of_boolean25 item(\"item\");\n  int counter = 0;\n  for (unsigned i = 0; i < 1000; i++) {\n    BOOST_REQUIRE(item.randomize());\n    if (item.a) {\n      ++counter;\n    } else {\n      --counter;\n    }\n  }\n\n  BOOST_REQUIRE_LT(counter, 0);\n}\n\nstruct s_dist_of_boolean50 : crv_sequence_item {\n  s_dist_of_boolean50(crv_object_name) {}\n  crv_variable<bool> a;\n  crv_constraint con = {dist(a(), distribution<bool>::create(0.5))};\n};\n\nBOOST_AUTO_TEST_CASE(dist_of_boolean50) {\n  s_dist_of_boolean50 item(\"item\");\n  int counter = 0;\n  for (unsigned i = 0; i < 1000; i++) {\n    BOOST_REQUIRE(item.randomize());\n    if (item.a) {\n      ++counter;\n    } else {\n      --counter;\n    }\n  }\n\n  BOOST_REQUIRE_LT(counter, 280);\n  BOOST_REQUIRE_GT(counter, -280);\n}\n\nstruct s_dist_of_boolean75 : public crv_sequence_item {\n  s_dist_of_boolean75(crv_object_name) {}\n  crv_variable<bool> a;\n  crv_constraint con = {dist(a(), distribution<bool>::create(0.75))};\n};\n\nBOOST_AUTO_TEST_CASE(dist_of_boolean75) {\n  s_dist_of_boolean75 item(\"item\");\n  int counter = 0;\n  for (unsigned i = 0; i < 1000; i++) {\n    BOOST_REQUIRE(item.randomize());\n    if (item.a) {\n      ++counter;\n    } else {\n      --counter;\n    }\n  }\n\n  BOOST_REQUIRE_GT(counter, 0);\n}\n\nBOOST_AUTO_TEST_SUITE_END()  // Context\n\n//  vim: ft=cpp:ts=2:sw=2:expandtab\n", "meta": {"hexsha": "df2b7acae2da2f8739216dfd0948a2bcfd827229", "size": 4373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/experimental/test_ExperimentalDistribution.cpp", "max_stars_repo_name": "quadric-io/crave", "max_stars_repo_head_hexsha": "8096d8b151cbe0d2ba437657f42d8bb0e05f5436", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2015-05-11T02:38:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T07:31:26.000Z", "max_issues_repo_path": "tests/experimental/test_ExperimentalDistribution.cpp", "max_issues_repo_name": "quadric-io/crave", "max_issues_repo_head_hexsha": "8096d8b151cbe0d2ba437657f42d8bb0e05f5436", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-06-08T14:44:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T16:07:21.000Z", "max_forks_repo_path": "tests/experimental/test_ExperimentalDistribution.cpp", "max_forks_repo_name": "quadric-io/crave", "max_forks_repo_head_hexsha": "8096d8b151cbe0d2ba437657f42d8bb0e05f5436", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-05-29T21:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T09:31:15.000Z", "avg_line_length": 27.8535031847, "max_line_length": 118, "alphanum_fraction": 0.6530985593, "num_tokens": 1329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.529751129949286}}
{"text": "#define BOOST_TEST_MODULE matrix\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/matrix/all.h++>\n\n\ntypedef boost::mpl::list<\n\tmla::matrix::DenseRowMajor<float>,\n\tmla::matrix::DenseRowMajor<double>,\n\tmla::matrix::Diagonal<float>,\n\tmla::matrix::Diagonal<double>,\n\tmla::matrix::SparseDOK<float>,\n\tmla::matrix::SparseDOK<double>,\n\tmla::matrix::SparseCRS<float>,\n\tmla::matrix::SparseCRS<double>\n> matrix_type_list;\n\n\nBOOST_AUTO_TEST_SUITE(test_matrix)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( Declaration, MatrixType, matrix_type_list )\n{\n\tsize_t row_size = 3;\n\tsize_t column_size = 3;\n\t\n\tMatrixType m(row_size,column_size);\n\n\tBOOST_CHECK_EQUAL(m.rows(), row_size);\n\tBOOST_CHECK_EQUAL(m.columns(), column_size);\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( Clearing, MatrixType, matrix_type_list )\n{\n\tsize_t row_size = 3;\n\tsize_t column_size = 3;\n\n\tMatrixType m(row_size,column_size);\n\n\tm.setZero();\n\n\tfor(unsigned int i = 0; i < row_size; i++)\n\t{\n\t\tfor(unsigned int j = 0; j < column_size; j++)\n\t\t{\n\t\t\tBOOST_CHECK_EQUAL(m.getValue(i, j), (typename MatrixType::scalar_type)0);\n\t\t}\n\t}\n\t\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( set_eye_square, MatrixType, matrix_type_list )\n{\n\tsize_t row_size = 3;\n\tsize_t column_size = 3;\n\n\tMatrixType m(row_size,column_size);\n\n\tm.setEye();\n\n\tfor(unsigned int i = 0; i < row_size; i++)\n\t{\n\t\tfor(unsigned int j = 0; j < column_size; j++)\n\t\t{\n\t\t\tBOOST_CHECK_EQUAL(m.getValue(i, j), (typename MatrixType::scalar_type)(i==j?1:0) );\n\t\t}\n\t}\n\t\n}\n\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( set_eye_rectangular_row, MatrixType, matrix_type_list )\n{\n\tsize_t row_size = 3;\n\tsize_t column_size = 5;\n\n\tMatrixType m(row_size,column_size);\n\n\tm.setEye();\n\n\tfor(unsigned int i = 0; i < row_size; i++)\n\t{\n\t\tfor(unsigned int j = 0; j < column_size; j++)\n\t\t{\n\t\t\tBOOST_CHECK_EQUAL(m.getValue(i, j), (typename MatrixType::scalar_type)(i==j?1:0) );\n\t\t}\n\t}\n\t\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( set_eye_rectangular_column, MatrixType, matrix_type_list )\n{\n\tsize_t row_size = 5;\n\tsize_t column_size = 3;\n\n\tMatrixType m(row_size, column_size);\n\n\tm.setEye();\n\n\tfor(unsigned int i = 0; i < row_size; i++)\n\t{\n\t\tfor(unsigned int j = 0; j < column_size; j++)\n\t\t{\n\t\t\tBOOST_CHECK_EQUAL(m.getValue(i, j), (typename MatrixType::scalar_type)(i==j?1:0) );\n\t\t}\n\t}\n\t\n}\n\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( reference_assigning_one, MatrixType, matrix_type_list )\n{\n\tif( mla::matrix::Traits<MatrixType>::is_writeable() )\n\t{\n\t\tMatrixType m(3,3);\n\t\tm.setZero();\n\n\t\tm(1,1) = 1.0;\t\n\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 0), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 1), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 2), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 0), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 1), 1.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 2), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 0), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 1), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 2), 0.0);\n\t}\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( reference_assigning_same_row_ordered, MatrixType, matrix_type_list )\n{\n\tif( mla::matrix::Traits<MatrixType>::is_writeable() )\n\t{\n\t\tMatrixType m(3,3);\n\t\tm.setZero();\n\n\t\tm(1,0) = 1.0;\n\t\tm(1,1) = 1.0;\n\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 0), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 1), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 2), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 0), 1.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 1), 1.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 2), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 0), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 1), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 2), 0.0);\n\t}\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( reference_assigning_same_row_unordered, MatrixType, matrix_type_list )\n{\n\tif( mla::matrix::Traits<MatrixType>::is_writeable() )\n\t{\n\t\tMatrixType m(3,3);\n\t\tm.setZero();\n\n\t\tm(1,1) = 1.0;\n\t\tm(1,0) = 1.0;\n\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 0), 0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 1), 0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 2), 0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 0), 1);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 1), 1);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 2), 0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 0), 0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 1), 0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 2), 0);\n\t}\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( reference_assigning_different_row_ordered, MatrixType, matrix_type_list )\n{\n\tif( mla::matrix::Traits<MatrixType>::is_writeable() )\n\t{\n\t\tMatrixType m(3,3);\n\t\tm.setZero();\n\n\t\tm(1,1) = 1.0;\n\t\tm(2,1) = 1.0;\n\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 0), 0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 1), 0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 2), 0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 0), 0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 1), 1);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 2), 0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 0), 0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 1), 1);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 2), 0);\n\t}\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( value_setting, MatrixType, matrix_type_list )\n{\n\tif( mla::matrix::Traits<MatrixType>::is_writeable() )\n\t{\n\t\tMatrixType m(3,3);\n\t\tm.setZero();\n\n\t\tm.setValue( 1, 1, (typename MatrixType::scalar_type)1);\t\n\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 1), 1.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 0), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 1), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(0, 2), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 0), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 1), 1.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(1, 2), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 0), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 1), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 2), 0.0);\n\t}\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( matrix_assigning, MatrixType, matrix_type_list )\n{\n\tif( mla::matrix::Traits<MatrixType>::is_writeable() )\n\t{\n\t\tMatrixType m(3,3), n;\n\t\tm.setZero();\n\n\t\tm.setValue( 1, 1, 1.0);\t\n\n\t\tn = m;\n\n\t\tBOOST_CHECK_EQUAL(n.getValue(1, 1), 1.0);\n\t\tBOOST_CHECK_EQUAL(n.getValue(0, 0), 0.0);\n\t\tBOOST_CHECK_EQUAL(n.getValue(0, 1), 0.0);\n\t\tBOOST_CHECK_EQUAL(n.getValue(0, 2), 0.0);\n\t\tBOOST_CHECK_EQUAL(n.getValue(1, 0), 0.0);\n\t\tBOOST_CHECK_EQUAL(n.getValue(1, 1), 1.0);\n\t\tBOOST_CHECK_EQUAL(n.getValue(1, 2), 0.0);\n\t\tBOOST_CHECK_EQUAL(n.getValue(2, 0), 0.0);\n\t\tBOOST_CHECK_EQUAL(n.getValue(2, 1), 0.0);\n\t\tBOOST_CHECK_EQUAL(m.getValue(2, 2), 0.0);\n\t}\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n", "meta": {"hexsha": "dafaf6defdbe9902e4ef5a05c8d0519409aa7879", "size": 6159, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_matrix.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "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": "unit_tests/test_matrix.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/test_matrix.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "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.5076335878, "max_line_length": 104, "alphanum_fraction": 0.6918330898, "num_tokens": 2061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5297511299492859}}
{"text": "/*! \\file\n  \\brief An example to demonstrate autoscaling with @b multiple STL containers.\n  \\details See also demo_2d_autoscaling.cpp, auto_1d_plot.cpp,\n  demo_1d_axis_scaling.cpp, demo_2d_autoscaling_vector.cpp and auto_1d_container.cpp.\n*/\n//  auto_2d_plot.cpp\n// Copyright Paul A Bristow 2008, 2021\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[auto_2d_plot_1\n\n/*`First we need a few includes to use Boost.Plot:\n*/\n\n#include <boost/svg_plot/svg_2d_plot.hpp>\n//  using namespace boost::svg;\n\n#include <utility>\n // using std::pair;\n#include <map>\n // using std::map;\n#include <set>\n//  using std::multiset;\n#include <iostream>\n//  using std::cout;\n//  using std::endl;\n\n#include <limits>\n//  using std::numeric_limits;\n//] [/auto_2d_plot_1]\n\n//! Getting the max and min of X and Y data-points.\ntemplate <typename T> // T an STL container: array, vector ...\nvoid s(T& container, // Container Data-series to plot - entire container.\n               // (not necessarily ordered, so will find min and max).\n               double* x_min,  double* x_max,\n               double* y_min,  double* y_max\n               )\n{\n  typedef typename T::const_iterator iter;\n  std::pair<iter, iter> result = boost::minmax_element(container.begin(), container.end());\n  // minmax_element is efficient for maps because can use knowledge of being sorted,\n  // BUT only if it can be assumed that no values are 'at limits',\n  // infinity, NaN, max_value, min_value, denorm_min.\n  // Otherwise it is necessary to inspect all values individually.\n  std::pair<const double, double> px = *result.first;\n  std::pair<const double, double> py = *result.second;\n  *x_min = px.first;\n  *x_max = py.first;\n  *y_min = px.second;\n  *y_max = py.second;\n\n  std::cout << \"s x_min \" << *x_min << \", x_max \" << *x_max << std::endl; // x_min 1, x_max 7.3\n  std::cout << \"s y_min \" << *y_min << \", y_max \" << *y_max << std::endl; // y_min 3.2, y_max 9.1\n} // template <class T> int scale_axis  T an STL container: array, vector ...\n\nint main()\n{\n//[auto_2d_plot_2\n  /*`This example uses a single @c std::map to demonstrate autoscaling.\n  We create a @c std::map to hold our data-series.\n  */\n  std::map<const double, double> my_map;\n  /*`\n  Inserting some fictional values also sorts the data.\n  The index value in [ ] is the X value.\n  */\n  my_map[1.1] = 3.2;\n  my_map[7.3] = 9.1;\n  my_map[2.1] = 5.4;\n\n/*`Also include some 'at limits' values that might confuse autoscaling.\n*/\n  my_map[99.99] = std::numeric_limits<double>::quiet_NaN();\n  my_map[999.9] = std::numeric_limits<double>::infinity();\n  my_map[999.] = +std::numeric_limits<double>::infinity();\n\n  /*`Next a 2D plot is created using defaults for the very many possible settings.\n  */\n  try\n  { // try'n'catch clocks are needed to ensure error messages from any exceptions are shown.\n   /*`Construct `myplot` and add at least a title,\n    specify the both X and Y axes are to use autoscaling,\n    and add the one data-series to be plotted.\n  */\n  using  namespace boost::svg;\n  svg_2d_plot my_plot;\n  my_plot.title(\"Autoscale example 1\"); // Add a title.\n  my_plot.xy_autoscale(my_map); // Specify that both X and Y-axes are to use autoscaling,\n  my_plot.plot(my_map); // Add the one data-series to be plotted.\n  my_plot.write(\"./auto_2d_plot_1.svg\"); // And write the SVG image to a file.\n\n  /*`We can show the ranges used by autoscaling; */\n  std::cout << \"X min \" << my_plot.x_range().first << \", X max \" << my_plot.x_range().second << std::endl;\n  std::cout << \"Y min \" << my_plot.y_range().first << \", Y max \"  << my_plot.y_range().second << std::endl;\n\n  /*`Had we know that there were no 'at limits' (NaN or infinite) values, we could have chosen to skip the checks.\n  This might be important for speed if there are thousands of data values.\n  */\n  my_plot.autoscale_check_limits(false);  // Skip checks for speed.\n/*`The possible cost is that it will fail at run-time if there are any infinite or NaNs.\n*/\n\n  svg_2d_plot my_plot_2;\n  my_plot_2.title(\"Autoscale example 2\"); // Add a title.\n  my_plot_2.plot(my_map); // Add the one data-series to be plotted.\n\n/*`and specify:*/\n\n  my_plot_2.y_autoscale(0.4, 9.3); // autoscale using two doubles.\n\n/*`which will chose a neater scale range from 0 to 10 for the Y axis. */\n\n/*`It is also possible to fully control the factors used by autoscaling with function `scale_axis`.\n For examples, see [../example/demo_1d_axis_scaling.cpp demo_1d_axis_scaling.cpp] */\n\n  my_plot_2.write(\"./auto_2d_plot_2.svg\"); // And write another SVG image to another file.\n\n//] [/auto_2d_plot_2]\n  }\n  catch(const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << std::endl;\n  }\n  return 0;\n}\n\n/*\n//[auto_2d_plot_output\nOutput:\n\nAutorun \"j:\\Cpp\\SVG\\Debug\\auto_2d_plot.exe\"\nChecked: x_min 1.1, x_max 7.3, y_min 3.2, y_max 9.1, 3 'good' values, 3 values at limits.\nX min 1, X max 8\nY min 3, Y max 10\nX min 1, X max 8\nY min 0, Y max 10\n//] [/auto_2d_plot_output]\n\n*/\n", "meta": {"hexsha": "dceabc57b374abc9ca1f624c83e026a210af0661", "size": 5253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/auto_2d_plot.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/auto_2d_plot.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/auto_2d_plot.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 35.255033557, "max_line_length": 114, "alphanum_fraction": 0.681705692, "num_tokens": 1542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.5297511229510565}}
{"text": "#include <mex.h>\n#include \"eigenlab.h\"\n#include <Eigen/Dense>\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n    plhs[0] = mxCreateDoubleMatrix(2, 2, mxREAL);\n\n    Eigen::MatrixXd mat(3, 2);\n    mat << 1, 4,\n           2, 5,\n           3, 6;\n\n    eigenToMxArray(mat, plhs[0], 3, 2);\n    return;\n}\n", "meta": {"hexsha": "34915e022f50fcf1c486e561af32e31632a5b6bd", "size": 330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test1.cpp", "max_stars_repo_name": "Epitrochoid/eigenlab", "max_stars_repo_head_hexsha": "bfa54b73ab3b7ad4bbabd7841d476f6c1aa7a7cf", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test1.cpp", "max_issues_repo_name": "Epitrochoid/eigenlab", "max_issues_repo_head_hexsha": "bfa54b73ab3b7ad4bbabd7841d476f6c1aa7a7cf", "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": "test1.cpp", "max_forks_repo_name": "Epitrochoid/eigenlab", "max_forks_repo_head_hexsha": "bfa54b73ab3b7ad4bbabd7841d476f6c1aa7a7cf", "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": 20.625, "max_line_length": 78, "alphanum_fraction": 0.5757575758, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5297511196029538}}
{"text": "//\n//  random.h\n//  yamcmc++\n//\n//  Created by Brandon Kelly on 3/2/13.\n//  Copyright (c) 2013 Brandon Kelly. All rights reserved.\n//\n\n#ifndef __yamcmc____random__\n#define __yamcmc____random__\n\n#include <iostream>\n//\n//  random.hpp\n//  yamcmc++\n//\n//  Created by Dr. Brandon C. Kelly on 11/21/12.\n//\n//  Header file for a class that generates pseudorandom numbers from common distributions.\n//  This is basically a wrapper for BOOST::RANDOM\n//\n\n// Standard includes\n#include <string>\n#include <vector>\n// Boost includes\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/exponential_distribution.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/lognormal_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/student_t_distribution.hpp>\n#include <boost/random/chi_squared_distribution.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n// Other includes\n#include <armadillo>\n\n// Class containing methods to generate random numbers from various\n// distributions. These should be self-explanatory, but see\n// random.cpp for more details.\nclass RandomGenerator {\npublic:\n    void SetSeed(unsigned long seed) const; // Set the random number generator seed. Be Careful with this!\n    void SaveSeed(std::string seed_filename = \"seed.txt\") const; // Save the random number generator seed to a file.\n    void RecoverSeed(std::string seed_filename = \"seed.txt\") const;\n    double exp(double lambda=1.0);\n    double normal(double mu=0.0, double sigma=1.0); // Univariate normal\n    arma::vec normal(arma::mat covar); // Multivariate normal\n    double lognormal(double logmean=0.0, double frac_sigma=1.0);\n    double uniform(double lowbound=0.0, double upbound=1.0);\n    int uniform(int lowbound, int upbound);\n    double powerlaw(double lower, double upper, double slope);\n    double tdist(double dof=1.0, double mean=0.0, double scale=1.0);\n    double chisqr(int dof=1);\n    double scaled_inverse_chisqr(int dof=1, double ssqr=1.0);\n    double gamma(double alpha=1.0, double beta=1.0);\n    double invgamma(double alpha=1.0, double beta=1.0);\n    int uniform_integer(int lowbound, int upbound);\n    // Additional methods to be added later\n    arma::vec mtdist(arma::mat covar, double dof=1.0);\n    double beta();\n    double weibull();\nprivate:\n    // Private functors for the various distributions.\n    boost::random::exponential_distribution<> exp_;\n    boost::random::normal_distribution<> normal_;\n    boost::random::lognormal_distribution<> lognormal_;\n    boost::random::uniform_real_distribution<> uniform_;\n    boost::random::uniform_int_distribution<> uniform_integer_;\n    boost::random::student_t_distribution<> tdist_;\n    boost::random::chi_squared_distribution<> chisqr_;\n    boost::random::gamma_distribution<> gamma_;\n};\n\n#endif /* defined(__yamcmc____random__) */\n", "meta": {"hexsha": "b8fcf15c927a9187f4a8c3b458abaf44e49a3f2a", "size": 2910, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/random.hpp", "max_stars_repo_name": "Jamieryan/carma_pack", "max_stars_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2015-01-25T19:24:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T11:55:28.000Z", "max_issues_repo_path": "src/include/random.hpp", "max_issues_repo_name": "Jamieryan/carma_pack", "max_issues_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-04-29T12:37:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T23:31:29.000Z", "max_forks_repo_path": "src/include/random.hpp", "max_forks_repo_name": "Jamieryan/carma_pack", "max_forks_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-09-15T00:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T07:28:47.000Z", "avg_line_length": 37.3076923077, "max_line_length": 116, "alphanum_fraction": 0.7402061856, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5297511129067483}}
{"text": "#include <doctest/doctest.h>  // for ResultBuilder, CHECK, TestCase\n// #include <__config>                // for std\n#include <boost/utility/string_view.hpp>  // for boost::string_view\n#include <ckpttn/HierNetlist.hpp>         // for HierNetlist, SimpleHierNetlist\n#include <ckpttn/netlist.hpp>             // for Netlist, SimpleNetlist\n#include <cstdint>                        // for uint8_t\n#include <memory>                         // for unique_ptr\n#include <py2cpp/set.hpp>                 // for set\n#include <vector>                         // for vector, operator==\n\nusing namespace std;\n\nextern auto create_test_netlist() -> SimpleNetlist;  // import create_test_netlist\nextern auto create_dwarf() -> SimpleNetlist;         // import create_dwarf\nextern auto readNetD(boost::string_view netDFileName) -> SimpleNetlist;\nextern void readAre(SimpleNetlist& H, boost::string_view areFileName);\n// extern tuple<py::set<node_t>, int>\n// min_net_cover_pd(SimpleNetlist &, const vector<int> &);\n\nusing node_t = SimpleNetlist::node_t;\nextern auto create_contraction_subgraph(const SimpleNetlist&, const py::set<node_t>&)\n    -> unique_ptr<SimpleHierNetlist>;\n\n//\n// Primal-dual algorithm for minimum vertex cover problem\n//\n\n// TEST_CASE(\"Test min_net_cover_pd dwarf\", \"[test_min_cover]\") {\n//     auto H = create_dwarf();\n//     auto [S, cost] = min_net_cover_pd(H, H.module_weight);\n//     CHECK(cost == 3);\n// }\n\n// TEST_CASE(\"Test min_net_cover_pd ibm01\", \"[test_min_cover]\") {\n//     auto H = readNetD(\"../../testcases/ibm01.net\");\n//     readAre(H, \"../../testcases/ibm01.are\");\n//     auto [S, cost] = min_net_cover_pd(H, H.net_weight);\n//     CHECK(cost == 4053);\n// }\n\nTEST_CASE(\"Test contraction subgraph dwarf\") {\n    const auto H = create_dwarf();\n    const auto H2 = create_contraction_subgraph(H, py::set<node_t>{});\n    // auto H3 = create_contraction_subgraph(*H2, py::set<node_t> {});\n    CHECK(H2->number_of_modules() < 7);\n    CHECK(H2->number_of_nets() == 3);\n    // CHECK(H2->number_of_pins() < 14);\n    CHECK(H2->get_max_net_degree() <= 3);\n\n    auto part = vector<uint8_t>(H.number_of_modules(), 0);\n    auto part2 = vector<uint8_t>(H2->number_of_modules(), 0);\n    auto part3 = vector<uint8_t>(H2->number_of_modules(), 0);\n    part2[0] = part2[2] = 1;\n    part2[1] = 2;\n    H2->projection_down(part2, part);\n    H2->projection_up(part, part3);\n    CHECK(part2 == part3);\n}\n\nTEST_CASE(\"Test contraction subgraph ibm01\") {\n    auto H = readNetD(\"../../testcases/ibm01.net\");\n    readAre(H, \"../../testcases/ibm01.are\");\n    auto H2 = create_contraction_subgraph(H, py::set<node_t>{});\n    auto H3 = create_contraction_subgraph(*H2, py::set<node_t>{});\n    CHECK(H2->number_of_modules() < H.number_of_modules());\n    CHECK(H2->number_of_nets() < H.number_of_nets());\n    // CHECK(H2->number_of_pins() < H.number_of_pins());\n    CHECK(H2->get_max_net_degree() <= H.get_max_net_degree());\n\n    auto part2 = vector<uint8_t>(H2->number_of_modules(), 0);\n    auto part3 = vector<uint8_t>(H3->number_of_modules(), 0);\n    auto part4 = vector<uint8_t>(H3->number_of_modules(), 0);\n    auto i = uint8_t(0);\n\n    for (auto& item : part3) {\n        item = ++i % 6;\n    }\n    H3->projection_down(part3, part2);\n    H3->projection_up(part2, part4);\n    CHECK(part3 == part4);\n}\n\nTEST_CASE(\"Test contraction subgraph ibm18\") {\n    auto H = readNetD(\"../../testcases/ibm18.net\");\n    readAre(H, \"../../testcases/ibm18.are\");\n    auto H2 = create_contraction_subgraph(H, py::set<node_t>{});\n    auto H3 = create_contraction_subgraph(*H2, py::set<node_t>{});\n    CHECK(H2->number_of_modules() < H.number_of_modules());\n    CHECK(H2->number_of_nets() < H.number_of_nets());\n    // CHECK(H2->number_of_pins() < H.number_of_pins());\n    CHECK(H2->get_max_net_degree() <= H.get_max_net_degree());\n\n    auto part2 = vector<uint8_t>(H2->number_of_modules(), 0);\n    auto part3 = vector<uint8_t>(H3->number_of_modules(), 0);\n    auto part4 = vector<uint8_t>(H3->number_of_modules(), 0);\n    for (auto i = 0u; i != H3->number_of_modules(); ++i) {\n        part3[i] = uint8_t(i);\n    }\n    H3->projection_down(part3, part2);\n    H3->projection_up(part2, part4);\n    CHECK(part3 == part4);\n}\n", "meta": {"hexsha": "0c6eb8f5f2946b10a3e77d1e4657abeecc8b39ba", "size": 4187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/source/test_min_cover.cpp", "max_stars_repo_name": "luk036/ckpttn-cpp", "max_stars_repo_head_hexsha": "9d15cdadf5e6b968e6e6a9d5e3db500256a11a6f", "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/source/test_min_cover.cpp", "max_issues_repo_name": "luk036/ckpttn-cpp", "max_issues_repo_head_hexsha": "9d15cdadf5e6b968e6e6a9d5e3db500256a11a6f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-24T12:00:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-11T04:35:10.000Z", "max_forks_repo_path": "test/source/test_min_cover.cpp", "max_forks_repo_name": "luk036/ckpttn-cpp", "max_forks_repo_head_hexsha": "9d15cdadf5e6b968e6e6a9d5e3db500256a11a6f", "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": 40.6504854369, "max_line_length": 85, "alphanum_fraction": 0.6462861237, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.529751102560416}}
{"text": "#ifndef GENETIC_CPP\n#define GENETIC_CPP\n\n#include \"Game/Render.hpp\"\n#include \"Genetic/Individual.hpp\"\n#include <Eigen/Dense>\n#include <algorithm>\n#include <random>\n#include <utility>\n#include <vector>\n\nnamespace GeneticUtils {\n    // RNGs\n    extern std::mt19937 gen;\n    extern std::normal_distribution<double> randn;\n    extern std::uniform_real_distribution<double> rand;\n}; // namespace GeneticUtils\n\nclass GeneticAlgo {\nprotected:\n    static int generations;\n    static int popSize;\n    static int offspringsSize;\n    static double etaX;\n    static double mutationProb;\n\n    // Genetic operators\n    // CROSSOVER\n    static std::pair<Eigen::MatrixXd, Eigen::MatrixXd> simulatedBinaryCrossover(const Eigen::MatrixXd &, const Eigen::MatrixXd &);\n    static std::pair<Eigen::VectorXd, Eigen::VectorXd> simulatedBinaryCrossover(const Eigen::VectorXd &, const Eigen::VectorXd &);\n    static std::pair<Eigen::MatrixXd, Eigen::MatrixXd> singlePointCrossover(const Eigen::MatrixXd &, const Eigen::MatrixXd &);\n    static std::pair<Eigen::VectorXd, Eigen::VectorXd> singlePointCrossover(const Eigen::VectorXd &, const Eigen::VectorXd &);\n\n    // MUTATION\n    static void gaussianMutation(Eigen::MatrixXd &);\n    static void gaussianMutation(Eigen::VectorXd &);\n\n    int currentGen;                     // current generation number\n    std::vector<Individual> population; // current population\n    std::vector<Individual> offsprings; // new offsprings\n    std::vector<Individual> globalBest; // best individuals\n\n    void updateAndLog(int &, bool, bool); // used for updating global best and logging\n\npublic:\n    GeneticAlgo();\n    void calculateFitness();                    // find fitness of offsprings by running the game\n    void elitismSelection();                    // Select the best individuals from offsprings to serve as new population\n    void crossoverAndMutation(double totalFit); // Perform roulette selection, crossover and mutation to generate 2 new offsprings\n    void nextGeneration();                      // Generate the offsprings for next generation\n    void start(bool = true, bool = false);      // start the GA\n};\n\n#endif", "meta": {"hexsha": "f5f668da155d064a67a02c12a0974397f8f42cd0", "size": 2143, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Genetic/Genetic.hpp", "max_stars_repo_name": "PragunSaini/snakes", "max_stars_repo_head_hexsha": "19b62fecca9c6854c712503e84bc854f8e2d1562", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T08:26:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T20:19:19.000Z", "max_issues_repo_path": "include/Genetic/Genetic.hpp", "max_issues_repo_name": "PragunSaini/snakes", "max_issues_repo_head_hexsha": "19b62fecca9c6854c712503e84bc854f8e2d1562", "max_issues_repo_licenses": ["MIT"], "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/Genetic/Genetic.hpp", "max_forks_repo_name": "PragunSaini/snakes", "max_forks_repo_head_hexsha": "19b62fecca9c6854c712503e84bc854f8e2d1562", "max_forks_repo_licenses": ["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.6851851852, "max_line_length": 130, "alphanum_fraction": 0.7064862343, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5296748913946379}}
{"text": "/**\n * MIT License\n\n * Copyright (c) 2018 Javonne Jason Martin\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 NEURALNETWORK_NEURALNETWORK_HPP\n#define NEURALNETWORK_NEURALNETWORK_HPP\n#include \"debug.hpp\"\n#include <Eigen/Dense>\n/**\n * Headers for the neural network class\n *\n *\n *\n *\n */\n/**\n * Explaination\n * The weight matrix _weights is an vector of matrices\n * Each element in a row is the incoming weight to a particular node ie\n * a row contains the weights incident on the next neuron\n *\n * This allows the propergation to be performed by computing _w * _a\n * Where _w is the weight matrix and _a is the input from the previous layer\n *\n * In this _a is the output from the current layer and the input to the next layer\n * _z is the input with out the activation function applied to it, for the backpropergation algorithm\n *\n */\nclass NeuralNetwork {\npublic:\n    enum ACTIVATION {SIGMOID, RELU, SOFTMAX};\n    /**\n     * Initialises the neural network with a vector of the size of each layer.\n     * @param layers, the size of each layer stored in a vector.\n     * @param dense\n     */\n    NeuralNetwork(std::vector<int> layers, float learningRate, bool dense=true);\n    /**\n     * Train the neural network using the input data and the expected output data.\n     * @param input, the input data <Input Layer> x <Datapoints>.\n     * @param output, the expected output data <Output layer> x <datapoints>.\n     * @param iterations, the number of iterations that the network should train for.\n     */\n    void train(Eigen::MatrixXf& input, Eigen::MatrixXf& expectedOutput, bool printIteration=false);\n    /**\n     * Use the network to predict the output using the input\n     * @param input, the input is a matrix of <datapoints> x <Input layer>.\n     * @param output, the output of the neural network <Output layer> x <datapoints>.\n     */\n    void predict(Eigen::MatrixXf& input, Eigen::MatrixXf& output);\n    void setActivationFunction(ACTIVATION);\n    ACTIVATION getActivationFunction();\n    /**\n     * Returns the number of neurons in the input layer.\n     * @return int.\n     */\n    int getInputSize();\n    /**\n     * Returns the number of neurons in the output layer.\n     * @return int.\n     */\n    int getOutputSize();\n    /**\n     * Get number of layers\n     * @return\n     */\n    unsigned long getLayerSize();\n\n\n\nprivate:\n    /**\n     * Apply the activation function to the input matrix\n     * @param input, the matrix that the activation function is applied to elementwise\n     */\n    void applyActivationFunction(Eigen::MatrixXf& input);\n    /**\n     * Computes the cost function\n     * @param x, the resulted output from the nerual network after the prediction\n     * @param y, the expected result\n     * @return the cost\n     */\n    float costFunction(float x, float y);\n    /**\n     * Applies the cost function to a series of inputs and ouputs\n     * @param expectedOuput, the resulted output from the nerual network after the prediction\n     * @param output, the expected result\n     * @return a Matrix with the costs\n     */\n    Eigen::MatrixXf costFunction(Eigen::MatrixXf& expectedOuput, Eigen::MatrixXf& output);\n    /**\n     * Computes the partial derivative of the cost function as a matrix\n     * @param expectedOuput, the resulted output from the nerual network after the prediction\n     * @param output, the expected result\n     * @return a Matrix containing the partial derivatives of the cost function\n     */\n    Eigen::MatrixXf costFunctionDerivative(Eigen::MatrixXf& expectedOuput, Eigen::MatrixXf& output);\n\n    /**\n     * Applies the derivative of the activation funciton\n     * @param matrix\n     * @return\n     */\n    Eigen::MatrixXf applyDerivativeActivationFunction(Eigen::MatrixXf& matrix);\n\n\n    float _learningRate = 1;\n    std::vector<Eigen::MatrixXf> _weights;\n    std::vector<Eigen::VectorXf> _bias;\n    std::vector<Eigen::MatrixXf> _delta;\n    std::vector<Eigen::MatrixXf> _deltaW;\n    std::vector<Eigen::VectorXf> _deltaB;\n    std::vector<Eigen::MatrixXf> _z; //This is the output after applying the weights and bias (the output of the layer without the actviation function)\n    std::vector<Eigen::MatrixXf> _a; //This is the output after applying the weights, bias and activation function, (the output of the layer)\n    std::vector<int> _layersSize;\n    ACTIVATION _activationFunction = SIGMOID;\n\n};\n\n/**\n * TODO Move these activation functions somewhere more logical\n *\n */\n//static Eigen::MatrixXf sigmoidDerivativeMatrix(Eigen::MatrixXf& z);\nstatic float sigmoid(float z);\nstatic float sigmoidDerivative(float z);\nstatic float relu(float z);\nstatic float reluDerivative(float z) ;\nstatic float softmax(float z);\nstatic float softmaxDerivative(float z);\n\n\n#endif //NEURALNETWORK_NEURALNETWORK_HPP\n", "meta": {"hexsha": "bae049beca476a022890eedcf1ad7a6f19d6f4bd", "size": 5779, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NeuralNetwork.hpp", "max_stars_repo_name": "JavonneM/NeuralNet", "max_stars_repo_head_hexsha": "d042814e96b0e0816acc18abe9530a47bf3e1ef2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T08:26:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T08:26:18.000Z", "max_issues_repo_path": "NeuralNetwork.hpp", "max_issues_repo_name": "JavonneM/NeuralNet", "max_issues_repo_head_hexsha": "d042814e96b0e0816acc18abe9530a47bf3e1ef2", "max_issues_repo_licenses": ["MIT"], "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.hpp", "max_forks_repo_name": "JavonneM/NeuralNet", "max_forks_repo_head_hexsha": "d042814e96b0e0816acc18abe9530a47bf3e1ef2", "max_forks_repo_licenses": ["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.525974026, "max_line_length": 151, "alphanum_fraction": 0.7129261118, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5296748801624392}}
{"text": "/*\n *\n * Copyright Toon Knapen, Karl Meerbergen & Kresimir Fresl 2003\n * Copyright Thomas Klimpel 2008\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 * KF acknowledges the support of the Faculty of Civil Engineering,\n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_HEEVX_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_HEEVX_HPP\n\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/traits/type.hpp>\n#include <boost/numeric/bindings/lapack/lapack.h>\n#include <boost/numeric/bindings/lapack/workspace.hpp>\n#include <boost/numeric/bindings/traits/detail/array.hpp>\n#include <boost/numeric/bindings/traits/detail/utils.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits.hpp>\n#endif\n\n\nnamespace boost { namespace numeric { namespace bindings {\n\n  namespace lapack {\n\n    ///////////////////////////////////////////////////////////////////\n    //\n    // Eigendecomposition of a complex Hermitian matrix A = Q * D * Q'\n    //\n    ///////////////////////////////////////////////////////////////////\n\n    /*\n     * heevx() computes selected eigenvalues and, optionally, eigenvectors\n     * of a complex Hermitian matrix A.  Eigenvalues and eigenvectors can\n     * be selected by specifying either a range of values or a range of\n     * indices for the desired eigenvalues.\n     *\n     * heevx() computes the eigendecomposition of a N x N matrix\n     * A = Q * D * Q',  where Q is a N x N unitary matrix and\n     * D is a diagonal matrix. The diagonal element D(i,i) is an\n     * eigenvalue of A and Q(:,i) is a corresponding eigenvector.\n     * The eigenvalues are stored in ascending order.\n     *\n     * On return of heevx, A is overwritten, z contains selected eigenvectors from Q\n     * and w contains selected eigenvalues from the main diagonal of D.\n     *\n     * int heevx (char jobz, char range, char uplo, A& a, T vl, T vu, integer_t il, integer_t iu, T abstol, integer_t& m,\n     *            W& w, Z& z, IFail& ifail, Work work) {\n     *    jobz :  'V' : compute eigenvectors\n     *            'N' : do not compute eigenvectors\n     *    range : 'A': all eigenvalues will be found.\n     *            'V': all eigenvalues in the half-open interval (vl,vu] will be found.\n     *            'I': the il-th through iu-th eigenvalues will be found.\n     *    uplo :  'U' : only the upper triangular part of A is used on input.\n     *            'L' : only the lower triangular part of A is used on input.\n     */\n\n    namespace detail {\n\n      inline void heevx (\n        char const jobz, char const range, char const uplo, integer_t const n,\n        float* a, integer_t const lda,\n        float const vl, float const vu, integer_t const il, integer_t const iu,\n        float const abstol, integer_t& m,\n        float* w, float* z, integer_t const ldz, float* work, integer_t const lwork,\n        integer_t* iwork, integer_t* ifail, integer_t& info)\n      {\n        LAPACK_SSYEVX (\n          &jobz, &range, &uplo, &n,\n          a, &lda,\n          &vl, &vu, &il, &iu,\n          &abstol, &m,\n          w, z, &ldz, work, &lwork,\n          iwork, ifail, &info);\n      }\n\n      inline void heevx (\n        char const jobz, char const range, char const uplo, integer_t const n,\n        double* a, integer_t const lda,\n        double const vl, double const vu, integer_t const il, integer_t const iu,\n        double const abstol, integer_t& m,\n        double* w, double* z, integer_t const ldz, double* work, integer_t const lwork,\n        integer_t* iwork, integer_t* ifail, integer_t& info)\n      {\n        LAPACK_DSYEVX (\n          &jobz, &range, &uplo, &n,\n          a, &lda,\n          &vl, &vu, &il, &iu,\n          &abstol, &m,\n          w, z, &ldz, work, &lwork,\n          iwork, ifail, &info);\n      }\n\n      inline void heevx (\n        char const jobz, char const range, char const uplo, integer_t const n,\n        traits::complex_f* a, integer_t const lda,\n        float const vl, float const vu, integer_t const il, integer_t const iu,\n        float const abstol, integer_t& m,\n        float* w, traits::complex_f* z, integer_t const ldz, traits::complex_f* work, integer_t const lwork,\n        float* rwork, integer_t* iwork, integer_t* ifail, integer_t& info)\n      {\n        LAPACK_CHEEVX (\n          &jobz, &range, &uplo, &n,\n          traits::complex_ptr(a), &lda,\n          &vl, &vu, &il, &iu, &abstol, &m, w,\n          traits::complex_ptr(z), &ldz,\n          traits::complex_ptr(work), &lwork,\n          rwork, iwork, ifail, &info);\n      }\n\n      inline void heevx (\n        char const jobz, char const range, char const uplo, integer_t const n,\n        traits::complex_d* a, integer_t const lda,\n        double const vl, double const vu, integer_t const il, integer_t const iu,\n        double const abstol, integer_t& m,\n        double* w, traits::complex_d* z, integer_t const ldz, traits::complex_d* work, integer_t const lwork,\n        double* rwork, integer_t* iwork, integer_t* ifail, integer_t& info)\n      {\n        LAPACK_ZHEEVX (\n          &jobz, &range, &uplo, &n,\n          traits::complex_ptr(a), &lda,\n          &vl, &vu, &il, &iu, &abstol, &m, w,\n          traits::complex_ptr(z), &ldz,\n          traits::complex_ptr(work), &lwork,\n          rwork, iwork, ifail, &info);\n      }\n    } // namespace detail\n\n    namespace detail {\n\n      template <int N>\n      struct Heevx{};\n\n      /// Handling of workspace in the case of one workarray.\n      template <>\n      struct Heevx< 1 > {\n        // Function that allocates temporary arrays\n        template <typename T, typename R>\n        void operator() (\n          char const jobz, char const range, char const uplo, integer_t const n,\n          T* a, integer_t const lda,\n          R vl, R vu, integer_t const il, integer_t const iu,\n          R abstol, integer_t& m,\n          R* w, T* z, integer_t const ldz, minimal_workspace, integer_t* ifail, integer_t& info) {\n\n          traits::detail::array<T> work( 8*n );\n          traits::detail::array<integer_t> iwork( 5*n );\n\n          heevx( jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz,\n            traits::vector_storage (work), traits::vector_size (work),\n            traits::vector_storage (iwork),\n            ifail, info);\n        }\n        // Function that allocates temporary arrays\n        template <typename T, typename R>\n        void operator() (\n          char const jobz, char const range, char const uplo, integer_t const n,\n          T* a, integer_t const lda,\n          R vl, R vu, integer_t const il, integer_t const iu,\n          R abstol, integer_t& m,\n          R* w, T* z, integer_t const ldz, optimal_workspace, integer_t* ifail, integer_t& info) {\n\n          traits::detail::array<integer_t> iwork( 5*n );\n\n          T workspace_query;\n          heevx( jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz,\n            &workspace_query, -1,\n            traits::vector_storage (iwork),\n            ifail, info);\n\n          traits::detail::array<T> work( traits::detail::to_int( workspace_query ) );\n\n          heevx( jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz,\n            traits::vector_storage (work), traits::vector_size (work),\n            traits::vector_storage (iwork),\n            ifail, info);\n        }\n        // Function that uses given workarrays\n        template <typename T, typename R, typename W, typename WI>\n        void operator() (\n          char const jobz, char const range, char const uplo, integer_t const n,\n          T* a, integer_t const lda,\n          R vl, R vu, integer_t const il, integer_t const iu,\n          R abstol, integer_t& m,\n          R* w, T* z, integer_t const ldz, detail::workspace2<W, WI> work, integer_t* ifail, integer_t& info) {\n\n          assert (traits::vector_size (work.select(T())) >= 8*n);\n          assert (traits::vector_size (work.select(integer_t())) >= 5*n);\n\n          heevx( jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz,\n            traits::vector_storage (work.select(T())), traits::vector_size (work.select(T())),\n            traits::vector_storage (work.select(integer_t())),\n            ifail, info);\n        }\n      };\n\n      /// Handling of workspace in the case of two workarrays.\n      template <>\n      struct Heevx< 2 > {\n        // Function that allocates temporary arrays\n        template <typename T, typename R>\n        void operator() (\n          char const jobz, char const range, char const uplo, integer_t const n,\n          T* a, integer_t const lda,\n          R vl, R vu, integer_t const il, integer_t const iu,\n          R abstol, integer_t& m,\n          R* w, T* z, integer_t const ldz, minimal_workspace, integer_t* ifail, integer_t& info) {\n\n          traits::detail::array<T> work( 2*n );\n          traits::detail::array<R> rwork( 7*n );\n          traits::detail::array<integer_t> iwork( 5*n );\n\n          heevx( jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz,\n            traits::vector_storage (work), traits::vector_size (work),\n            traits::vector_storage (rwork),\n            traits::vector_storage (iwork),\n            ifail, info);\n        }\n        // Function that allocates temporary arrays\n        template <typename T, typename R>\n        void operator() (\n          char const jobz, char const range, char const uplo, integer_t const n,\n          T* a, integer_t const lda,\n          R vl, R vu, integer_t const il, integer_t const iu,\n          R abstol, integer_t& m,\n          R* w, T* z, integer_t const ldz, optimal_workspace, integer_t* ifail, integer_t& info) {\n\n          traits::detail::array<R> rwork( 7*n );\n          traits::detail::array<integer_t> iwork( 5*n );\n\n          T workspace_query;\n          heevx( jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz,\n            &workspace_query, -1,\n            traits::vector_storage (rwork),\n            traits::vector_storage (iwork),\n            ifail, info);\n\n          traits::detail::array<T> work( traits::detail::to_int( workspace_query ) );\n\n          heevx( jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz,\n            traits::vector_storage (work), traits::vector_size (work),\n            traits::vector_storage (rwork),\n            traits::vector_storage (iwork),\n            ifail, info);\n        }\n        // Function that uses given workarrays\n        template <typename T, typename R, typename WC, typename WR, typename WI>\n        void operator() (\n          char const jobz, char const range, char const uplo, integer_t const n,\n          T* a, integer_t const lda,\n          R vl, R vu, integer_t const il, integer_t const iu,\n          R abstol, integer_t& m,\n          R* w, T* z, integer_t const ldz, detail::workspace3<WC, WR, WI> work, integer_t* ifail, integer_t& info) {\n\n          assert (traits::vector_size (work.select(T())) >= 2*n);\n          assert (traits::vector_size (work.select(R())) >= 7*n);\n          assert (traits::vector_size (work.select(integer_t())) >= 5*n);\n\n          heevx( jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz,\n            traits::vector_storage (work.select(T())), traits::vector_size (work.select(T())),\n            traits::vector_storage (work.select(R())),\n            traits::vector_storage (work.select(integer_t())),\n            ifail, info);\n        }\n      };\n    } // namespace detail\n\n    template <typename A, typename T, typename W, typename Z, typename IFail, typename Work>\n    int heevx (\n      char jobz, char range, A& a, T vl, T vu, integer_t il, integer_t iu, T abstol, integer_t& m,\n      W& w, Z& z, IFail& ifail, Work work = optimal_workspace() ) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      typedef typename A::value_type                               value_type ;\n      typedef typename traits::type_traits< value_type >::real_type real_type ;\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<A>::matrix_structure,\n        traits::hermitian_t\n      >::value || (boost::is_same<\n        typename traits::matrix_traits<A>::matrix_structure,\n        traits::symmetric_t\n      >::value && boost::is_same<value_type, real_type>::value)));\n#endif\n\n      integer_t const n = traits::matrix_size1 (a);\n      assert (traits::matrix_size2 (a) == n);\n      assert (traits::vector_size (w) == n);\n      assert (traits::vector_size (ifail) == n);\n      assert ( range=='A' || range=='V' || range=='I' );\n      char uplo = traits::matrix_uplo_tag (a);\n      assert ( uplo=='U' || uplo=='L' );\n      assert ( jobz=='N' || jobz=='V' );\n\n      integer_t info;\n      detail::Heevx< n_workspace_args<typename A::value_type>::value >() (\n        jobz, range, uplo, n,\n        traits::matrix_storage (a),\n        traits::leading_dimension (a),\n        vl, vu, il, iu, abstol, m,\n        traits::vector_storage (w),\n        traits::matrix_storage (z),\n        traits::leading_dimension (z),\n        work,\n        traits::vector_storage (ifail),\n        info);\n      return info;\n    }\n  }\n\n}}}\n\n#endif\n", "meta": {"hexsha": "a8cb18d05ad2e6473ad784cb3815b6078454dcb9", "size": 13225, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/heevx.hpp", "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/boost/numeric/bindings/lapack/heevx.hpp", "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/boost/numeric/bindings/lapack/heevx.hpp", "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": 41.0714285714, "max_line_length": 121, "alphanum_fraction": 0.5913043478, "num_tokens": 3592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.5296748801600213}}
{"text": "/**\n\n\\file\n\\author Datta Ramadasan\n//==============================================================================\n//         Copyright 2015 INSTITUT PASCAL UMR 6602 CNRS/Univ. Clermont II\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n\n*/\n\n#ifndef __NUMERIC_AD_RT_AD_HPP__\n#define __NUMERIC_AD_RT_AD_HPP__\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <TooN/TooN.h>\n#include <libv/lma/ttt/traits/naming.hpp>\n#include <cmath>\n\nnamespace AdRt\n{\n//   Eigen::Matrix<T,N,1>\n  template<class T, std::size_t N > struct Ad\n  {\n    typedef T type;\n    static const std::size_t dim = N;\n\n    typedef TooN::Vector<N,T> Array;\n    T value;\n    Array infinite;\n\n    Ad():value(0) {}\n\n    Ad(type value_) : value(value_)\n    {\n//       infinite.fill(0);\n      infinite = TooN::Zeros;\n    }\n\n    Ad(type value_, std::size_t k)\n    {\n      value = value_;\n//       infinite.fill(0);\n      infinite = TooN::Zeros;\n      infinite[k] = type(1);\n    }\n\n    Ad(type value_, const Array& infinite_): value(value_),infinite(infinite_) {}\n\n//     bool operator<(type value_) const\n//     {\n//       return value < value_;\n//     }\n//     \n//     bool operator>(type value_) const\n//     {\n//       return value > value_;\n//     }\n// \n//     bool operator<=(type value_) const\n//     {\n//       return value <= value_;\n//     }\n// \n//     bool operator<=(const Ad& ad) const\n//     {\n//       return value <= ad.value;\n//     }\n//     \n    bool operator>(const Ad& ad) const\n    {\n      return value > ad.value;\n    }\n    \n    Ad<T,N>& operator+=(const Ad<type, dim>& st) { *this = *this + st; return *this; }\n//     Ad<T,N>& operator-=(const Ad<type, dim>& st) { return *this -= st; }\n//     Ad<T,N>& operator*=(const Ad<type, dim>& st) { return *this *= st; }\n//     Ad<T,N>& operator/=(const Ad<type, dim>& st) { return *this /= st;}\n  };\n\n  template<class T, std::size_t N> bool operator==(const Ad<T,N>& st, const T& scalar)\n  {\n    return st.value == scalar;\n  }\n\n  template<class T, std::size_t N> bool operator!=(const Ad<T,N>& st, const T& scalar)\n  {\n    return st.value != scalar;\n  }\n\n  //! Arithmetic for Ad\n  template<class T, std::size_t N> const Ad<T,N>& operator+(const Ad<T,N>& st)\n  {\n    return st;\n  }\n\n  template<class T, std::size_t N> Ad<T,N> operator-(const Ad<T,N>& st)\n  {\n    return Ad<T,N>(-st.value,-st.infinite);\n  }\n\n  template<class T, std::size_t N> Ad<T,N> operator+(const Ad<T,N>& s, const Ad<T,N>& t)\n  {\n    return Ad<T,N>(s.value + t.value, s.infinite + t.infinite);\n  }\n\n  template<class T, std::size_t N> Ad<T,N> operator+(const Ad<T,N>& s, const T& value)\n  {\n    return Ad<T,N>(s.value + value, s.infinite);\n  }\n\n  template<class T, std::size_t N> Ad<T, N> operator+(const T& value, const Ad<T, N>& s)\n  {\n    return s + value;\n  }\n\n  template<class T, std::size_t N> Ad<T,N> operator-(const Ad<T,N>& s, const Ad<T,N>& t)\n  {\n    return Ad<T,N>(s.value - t.value, s.infinite - t.infinite);\n  }\n\n  template<class T, std::size_t N> Ad<T,N> operator-(const Ad<T,N>& s, const T& value)\n  {\n    return Ad<T,N>(s.value - value, s.infinite);\n  }\n\n  template<class T, std::size_t N> Ad<T,N> operator-(const T& value, const Ad<T,N>& s)\n  {\n    return -s + value;\n  }\n\n  template<class T, std::size_t N> Ad<T,N> operator*(const Ad<T,N>& s, const Ad<T,N>& t)\n  {\n    return Ad<T,N>(s.value * t.value , s.value * t.infinite + s.infinite * t.value );\n  }\n\n  template<class T, std::size_t N> Ad<T,N> operator*(const Ad<T,N>& s, const T& value)\n  {\n    return Ad<T,N>(s.value * value, s.infinite * value);\n  }\n\n  template<class T, std::size_t N> Ad<T,N> operator*(const T& value, const Ad<T,N>& s)\n  {\n    return s * value;\n  }\n\n  template<class T, std::size_t N> Ad<T,N> operator/(const Ad<T,N>& s, const Ad<T,N>& t)\n  {\n    return Ad<T,N>(s.value / t.value, (s.infinite - s.value / t.value * t.infinite ) / t.value);\n  }\n\n  template<class T, std::size_t N> Ad<T,N> operator/(const T& value, const Ad<T,N>& s)\n  {\n    return Ad<T,N>(value / s.value, - value * s.infinite / ( s.value * s.value ) );\n  }\n\n  template<class T, std::size_t N> Ad<T,N> operator/(const Ad<T,N>& s, const T& value)\n  {\n    return Ad<T,N>(s.value / value, s.infinite / value);\n  }\n\n//! trigonometric and others functions\n\n\n  template <class T, std::size_t N> Ad<T, N> abs(const Ad<T, N>& f)\n  {\n    return Ad<T,N>(f.value < T(0.0) ? -f : f);\n  }\n\n  template <class T, std::size_t N> Ad<T, N> log(const Ad<T, N>& f)\n  {\n    return Ad<T, N>(log(f.value),f.infinite / f.value);\n  }\n\n  template <class T, std::size_t N> Ad<T, N> exp(const Ad<T, N>& f)\n  {\n    Ad<T, N> g;\n    g.value = exp(f.value);\n    g.infinite = g.value * f.infinite;\n    return g;\n  }\n\n  template <class T, std::size_t N> Ad<T, N> sqrt(const Ad<T, N>& f)\n  {\n    Ad<T, N> g;\n    g.value = std::sqrt(f.value);\n    g.infinite = f.infinite / (T(2.0) * g.value);\n    return g;\n  }\n\n  template <class T, std::size_t N> Ad<T, N> cos(const Ad<T, N>& f)\n  {\n    using std::sin;using std::cos;\n    Ad<T, N> g;\n    g.value = cos(f.value);\n    T sin_a = sin(f.value);\n    g.infinite = - sin_a * f.infinite;\n    return g;\n  }\n\n  template <class T, std::size_t N> Ad<T, N> acos(const Ad<T, N>& f)\n  {\n    return Ad<T, N>(acos(f.value),- T(1.0) / sqrt(T(1.0) - f.value * f.value) * f.infinite);\n  }\n\n  template <class T, std::size_t N> Ad<T, N> sin(const Ad<T, N>& f)\n  {\n    using std::sin;using std::cos;\n    Ad<T, N> g;\n    g.value = sin(f.value);\n    T cos_a = cos(f.value);\n    g.infinite = cos_a * f.infinite;\n    return g;\n  }\n\n  template <class T, std::size_t N> Ad<T, N> asin(const Ad<T, N>& f)\n  {\n    return Ad<T, N>(asin(f.a),T(1.0) / sqrt(T(1.0) - f.a * f.a) * f.v);\n  }\n\n\n}//! eon AdRt\n\n  template<class T, std::size_t N> std::ostream& operator<<(std::ostream& o, const AdRt::Ad<T,N>& st)\n  {\n    return o << \" Ad<\" << ttt::name<T>() << \",\" << N << \":value = \" << st.value << \" ; [\" << st.infinite << \"]\";\n  }\n\n#endif\n", "meta": {"hexsha": "adda1707c7820bbe34b8e7a965b6b1c31e7db11f", "size": 6105, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libv/lma/numeric/ad/rt/ad.hpp", "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": "src/libv/lma/numeric/ad/rt/ad.hpp", "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": "src/libv/lma/numeric/ad/rt/ad.hpp", "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.0897435897, "max_line_length": 112, "alphanum_fraction": 0.5497133497, "num_tokens": 1937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5296748745463398}}
{"text": "#ifndef TRAJ_UTILS_HPP\n#define TRAJ_UTILS_HPP\n\n#include \"root_finder.hpp\"\n#include <vector>\n#include <list>\n#include <Eigen/Eigen>\n\n// Polynomial order and trajectory dimension are fixed here\nconstexpr int TrajOrder = 5;\nconstexpr int TrajDim = 3;\n\n// Type for piece boundary condition and coefficient matrix\ntypedef Eigen::Matrix<double, TrajDim, TrajOrder + 1> BoundaryCond;\ntypedef Eigen::Matrix<double, TrajDim, TrajOrder + 1> CoefficientMat;\ntypedef Eigen::Matrix<double, TrajDim, TrajOrder> VelCoefficientMat;\ntypedef Eigen::Matrix<double, TrajDim, TrajOrder - 1> AccCoefficientMat;\ntypedef Eigen::Matrix<double, TrajDim, TrajOrder - 2> JerkCoefficientMat;\n\ntypedef Eigen::Matrix<double, 6, 1> StatePV;\ntypedef Eigen::Matrix<double, 9, 1> StatePVA;\ntypedef Eigen::Matrix<double, 10, 1> StatePVAM;\ntypedef Eigen::Matrix<double, TrajDim, 1> ControlJrk;\ntypedef Eigen::Matrix<double, TrajDim, 1> ControlAcc;\n\n// A single piece of a trajectory, which is indeed a polynomial\nclass Piece\n{\nprivate:\n    // Piece(t) = c5*t^5 + c4*t^4 + ... + c1*t + c0\n    // The natural coefficient matrix = [c5,c4,c3,c2,c1,c0]\n    double duration;\n    // Any time in [0, T] is normalized into [0.0, 1.0]\n    // Therefore, nCoeffMat = [c5*T^5,c4*T^4,c3*T^3,c2*T^2,c1*T,c0*1]\n    // is used for better numerical stability\n    CoefficientMat nCoeffMat;\n\npublic:\n    Piece() = default;\n\n    // Constructor from duration and coefficient\n    Piece(double dur, const CoefficientMat &coeffs) : duration(dur)\n    {\n        double t = 1.0;\n        for (int i = TrajOrder; i >= 0; i--)\n        {\n            nCoeffMat.col(i) = coeffs.col(i) * t;\n            t *= dur;\n        }\n    }\n\n    // Constructor from boundary condition and duration\n    Piece(const BoundaryCond &boundCond, double dur) : duration(dur)\n    {\n        // The BoundaryCond matrix boundCond = [p(0),v(0),a(0),p(T),v(T),a(T)]\n        double t1 = dur;\n        double t2 = t1 * t1;\n\n        // Inverse mapping is computed without explicit matrix inverse\n        // It maps boundary condition to normalized coefficient matrix\n        nCoeffMat.col(0) = 0.5 * (boundCond.col(5) - boundCond.col(2)) * t2 -\n                           3.0 * (boundCond.col(1) + boundCond.col(4)) * t1 +\n                           6.0 * (boundCond.col(3) - boundCond.col(0));\n        nCoeffMat.col(1) = (-boundCond.col(5) + 1.5 * boundCond.col(2)) * t2 +\n                           (8.0 * boundCond.col(1) + 7.0 * boundCond.col(4)) * t1 +\n                           15.0 * (-boundCond.col(3) + boundCond.col(0));\n        nCoeffMat.col(2) = (0.5 * boundCond.col(5) - 1.5 * boundCond.col(2)) * t2 -\n                           (6.0 * boundCond.col(1) + 4.0 * boundCond.col(4)) * t1 +\n                           10.0 * (boundCond.col(3) - boundCond.col(0));\n        nCoeffMat.col(3) = 0.5 * boundCond.col(2) * t2;\n        nCoeffMat.col(4) = boundCond.col(1) * t1;\n        nCoeffMat.col(5) = boundCond.col(0);\n    }\n\n    inline int getDim() const\n    {\n        return TrajDim;\n    }\n\n    inline int getOrder() const\n    {\n        return TrajOrder;\n    }\n\n    inline double getDuration() const\n    {\n        return duration;\n    }\n\n    // Get the position at time t in this piece\n    inline Eigen::Vector3d getPos(double t) const\n    {\n        // Normalize the time\n        t /= duration;\n        Eigen::Vector3d pos(0.0, 0.0, 0.0);\n        double tn = 1.0;\n        for (int i = TrajOrder; i >= 0; i--)\n        {\n            pos += tn * nCoeffMat.col(i);\n            tn *= t;\n        }\n        // The pos is not affected by normalization\n        return pos;\n    }\n\n    // Get the velocity at time t in this piece\n    inline Eigen::Vector3d getVel(double t) const\n    {\n        // Normalize the time\n        t /= duration;\n        Eigen::Vector3d vel(0.0, 0.0, 0.0);\n        double tn = 1.0;\n        int n = 1;\n        for (int i = TrajOrder - 1; i >= 0; i--)\n        {\n            vel += n * tn * nCoeffMat.col(i);\n            tn *= t;\n            n++;\n        }\n        // Recover the actual vel\n        vel /= duration;\n        return vel;\n    }\n\n    // Get the acceleration at time t in this piece\n    inline Eigen::Vector3d getAcc(double t) const\n    {\n        // Normalize the time\n        t /= duration;\n        Eigen::Vector3d acc(0.0, 0.0, 0.0);\n        double tn = 1.0;\n        int m = 1;\n        int n = 2;\n        for (int i = TrajOrder - 2; i >= 0; i--)\n        {\n            acc += m * n * tn * nCoeffMat.col(i);\n            tn *= t;\n            m++;\n            n++;\n        }\n        // Recover the actual acc\n        acc /= duration * duration;\n        return acc;\n    }\n\n    // Get the jerk at time t in this piece\n    inline Eigen::Vector3d getJerk(double t) const\n    {\n        // Normalize the time\n        t /= duration;\n        Eigen::Vector3d jerk(0.0, 0.0, 0.0);\n        double tn = 1.0;\n        int m = 1;\n        int n = 2;\n        int k = 3;\n        for (int i = TrajOrder - 3; i >= 0; i--)\n        {\n            jerk += k * m * n * tn * nCoeffMat.col(i);\n            tn *= t;\n            k++;\n            m++;\n            n++;\n        }\n        // Recover the actual acc\n        jerk /= duration * duration * duration;\n        return jerk;\n    }\n\n    // Get the boundary condition of this piece\n    inline BoundaryCond getBoundCond() const\n    {\n        BoundaryCond boundCond;\n        boundCond << getPos(0.0), getVel(0.0), getAcc(0.0),\n            getPos(duration), getVel(duration), getAcc(duration);\n        return boundCond;\n    }\n\n    // Get the coefficient matrix of the piece\n    // Default arg chooses the natural coefficients\n    // If normalized version is needed, set the arg true\n    inline CoefficientMat getCoeffMat(bool normalized = false) const\n    {\n        CoefficientMat posCoeffsMat;\n        double t = 1;\n        for (int i = TrajOrder; i >= 0; i--)\n        {\n            posCoeffsMat.col(i) = nCoeffMat.col(i) / t;\n            t *= normalized ? 1.0 : duration;\n        }\n        return posCoeffsMat;\n    }\n\n    // Get the polynomial coefficients of velocity of this piece\n    // Default arg chooses the natural coefficients\n    // If normalized version is needed, set the arg true\n    inline VelCoefficientMat getVelCoeffMat(bool normalized = false) const\n    {\n        VelCoefficientMat velCoeffMat;\n        int n = 1;\n        double t = 1.0;\n        t *= normalized ? 1.0 : duration;\n        for (int i = TrajOrder - 1; i >= 0; i--)\n        {\n            velCoeffMat.col(i) = n * nCoeffMat.col(i) / t;\n            n++;\n            t *= normalized ? 1.0 : duration;\n        }\n        return velCoeffMat;\n    }\n\n    // Get the polynomial coefficients of acceleration of this piece\n    // Default arg chooses the natural coefficients\n    // If normalized version is needed, set the arg true\n    inline AccCoefficientMat getAccCoeffMat(bool normalized = false) const\n    {\n        AccCoefficientMat accCoeffMat;\n        int n = 2;\n        int m = 1;\n        double t = 1.0;\n        t *= normalized ? 1.0 : duration * duration;\n        for (int i = TrajOrder - 2; i >= 0; i--)\n        {\n            accCoeffMat.col(i) = n * m * nCoeffMat.col(i) / t;\n            n++;\n            m++;\n            t *= normalized ? 1.0 : duration;\n        }\n        return accCoeffMat;\n    }\n\n    // Get the polynomial coefficients of jerk of this piece\n    // Default arg chooses the natural coefficients\n    // If normalized version is needed, set the arg true\n    inline JerkCoefficientMat getJerkCoeffMat(bool normalized = false) const\n    {\n        JerkCoefficientMat jerkCoeffMat;\n        int n = 3;\n        int m = 2;\n        int l = 1;\n        double t = 1.0;\n        t *= normalized ? 1.0 : duration * duration * duration;\n        for (int i = TrajOrder - 3; i >= 0; i--)\n        {\n            jerkCoeffMat.col(i) = n * m * l * nCoeffMat.col(i) / t;\n            n++;\n            m++;\n            l++;\n            t *= normalized ? 1.0 : duration;\n        }\n        return jerkCoeffMat;\n    }\n\n    // Get the max velocity rate of the piece\n    inline double getMaxVelRate() const\n    {\n        // Compute normalized squared vel norm polynomial coefficient matrix\n        Eigen::MatrixXd nVelCoeffMat = getVelCoeffMat(true);\n        Eigen::VectorXd coeff = RootFinder::polySqr(nVelCoeffMat.row(0)) +\n                                RootFinder::polySqr(nVelCoeffMat.row(1)) +\n                                RootFinder::polySqr(nVelCoeffMat.row(2));\n        int N = coeff.size();\n        int n = N - 1;\n        for (int i = 0; i < N; i++)\n        {\n            coeff(i) *= n;\n            n--;\n        }\n        if (coeff.head(N - 1).squaredNorm() < DBL_EPSILON)\n        {\n            return 0.0;\n        }\n        else\n        {\n            // Search an open interval whose boundaries are not zeros\n            double l = -0.0625;\n            double r = 1.0625;\n            while (fabs(RootFinder::polyVal(coeff.head(N - 1), l)) < DBL_EPSILON)\n            {\n                l = 0.5 * l;\n            }\n            while (fabs(RootFinder::polyVal(coeff.head(N - 1), r)) < DBL_EPSILON)\n            {\n                r = 0.5 * (r + 1.0);\n            }\n            // Find all stationaries\n            std::set<double> candidates = RootFinder::solvePolynomial(coeff.head(N - 1), l, r,\n                                                                      FLT_EPSILON / duration);\n\n            // Check boundary points and stationaries within duration\n            candidates.insert(0.0);\n            candidates.insert(1.0);\n            double maxVelRateSqr = -INFINITY;\n            double tempNormSqr;\n            for (std::set<double>::const_iterator it = candidates.begin();\n                 it != candidates.end();\n                 it++)\n            {\n                if (0.0 <= *it && 1.0 >= *it)\n                {\n                    // Recover the actual time then get the vel squared norm\n                    tempNormSqr = getVel((*it) * duration).squaredNorm();\n                    maxVelRateSqr = maxVelRateSqr < tempNormSqr ? tempNormSqr : maxVelRateSqr;\n                }\n            }\n            return sqrt(maxVelRateSqr);\n        }\n    }\n\n    // Get the max acceleration rate of the piece\n    inline double getMaxAccRate() const\n    {\n        // Compute normalized squared acc norm polynomial coefficient matrix\n        Eigen::MatrixXd nAccCoeffMat = getAccCoeffMat(true);\n        Eigen::VectorXd coeff = RootFinder::polySqr(nAccCoeffMat.row(0)) +\n                                RootFinder::polySqr(nAccCoeffMat.row(1)) +\n                                RootFinder::polySqr(nAccCoeffMat.row(2));\n        int N = coeff.size();\n        int n = N - 1;\n        for (int i = 0; i < N; i++)\n        {\n            coeff(i) *= n;\n            n--;\n        }\n        if (coeff.head(N - 1).squaredNorm() < DBL_EPSILON)\n        {\n            return 0.0;\n        }\n        else\n        {\n            // Search an open interval whose boundaries are not zeros\n            double l = -0.0625;\n            double r = 1.0625;\n            while (fabs(RootFinder::polyVal(coeff.head(N - 1), l)) < DBL_EPSILON)\n            {\n                l = 0.5 * l;\n            }\n            while (fabs(RootFinder::polyVal(coeff.head(N - 1), r)) < DBL_EPSILON)\n            {\n                r = 0.5 * (r + 1.0);\n            }\n            // Find all stationaries\n            std::set<double> candidates = RootFinder::solvePolynomial(coeff.head(N - 1), l, r,\n                                                                      FLT_EPSILON / duration);\n            // Check boundary points and stationaries within duration\n            candidates.insert(0.0);\n            candidates.insert(1.0);\n            double maxAccRateSqr = -INFINITY;\n            double tempNormSqr;\n            for (std::set<double>::const_iterator it = candidates.begin();\n                 it != candidates.end();\n                 it++)\n            {\n                if (0.0 <= *it && 1.0 >= *it)\n                {\n                    // Recover the actual time then get the acc squared norm\n                    tempNormSqr = getAcc((*it) * duration).squaredNorm();\n                    maxAccRateSqr = maxAccRateSqr < tempNormSqr ? tempNormSqr : maxAccRateSqr;\n                }\n            }\n            return sqrt(maxAccRateSqr);\n        }\n    }\n\n    inline double getMaxJerkRate() const\n    {\n        // Compute normalized squared jerk norm polynomial coefficient matrix\n        Eigen::MatrixXd nJerkCoeffMat = getJerkCoeffMat(true);\n        Eigen::VectorXd coeff = RootFinder::polySqr(nJerkCoeffMat.row(0)) +\n                                RootFinder::polySqr(nJerkCoeffMat.row(1)) +\n                                RootFinder::polySqr(nJerkCoeffMat.row(2));\n        int N = coeff.size();\n        int n = N - 1;\n        for (int i = 0; i < N; i++)\n        {\n            coeff(i) *= n;\n            n--;\n        }\n        if (coeff.head(N - 1).squaredNorm() < DBL_EPSILON)\n        {\n            return 0.0;\n        }\n        else\n        {\n            // Search an open interval whose boundaries are not zeros\n            double l = -0.0625;\n            double r = 1.0625;\n            while (fabs(RootFinder::polyVal(coeff.head(N - 1), l)) < DBL_EPSILON)\n            {\n                l = 0.5 * l;\n            }\n            while (fabs(RootFinder::polyVal(coeff.head(N - 1), r)) < DBL_EPSILON)\n            {\n                r = 0.5 * (r + 1.0);\n            }\n            // Find all stationaries\n            std::set<double> candidates = RootFinder::solvePolynomial(coeff.head(N - 1), l, r,\n                                                                      FLT_EPSILON / duration);\n            // Check boundary points and stationaries within duration\n            candidates.insert(0.0);\n            candidates.insert(1.0);\n            double maxJerkRateSqr = -INFINITY;\n            double tempNormSqr;\n            for (std::set<double>::const_iterator it = candidates.begin();\n                 it != candidates.end();\n                 it++)\n            {\n                if (0.0 <= *it && 1.0 >= *it)\n                {\n                    // Recover the actual time then get the acc squared norm\n                    tempNormSqr = getJerk((*it) * duration).squaredNorm();\n                    maxJerkRateSqr = maxJerkRateSqr < tempNormSqr ? tempNormSqr : maxJerkRateSqr;\n                }\n            }\n            return sqrt(maxJerkRateSqr);\n        }\n    }\n\n    // Check whether velocity rate of the piece is always less than maxVelRate\n    inline bool checkMaxVelRate(double maxVelRate) const\n    {\n        double sqrMaxVelRate = maxVelRate * maxVelRate;\n        if (getVel(0.0).squaredNorm() >= sqrMaxVelRate ||\n            getVel(duration).squaredNorm() >= sqrMaxVelRate)\n        {\n            return false;\n        }\n        else\n        {\n            Eigen::MatrixXd nVelCoeffMat = getVelCoeffMat(true);\n            Eigen::VectorXd coeff = RootFinder::polySqr(nVelCoeffMat.row(0)) +\n                                    RootFinder::polySqr(nVelCoeffMat.row(1)) +\n                                    RootFinder::polySqr(nVelCoeffMat.row(2));\n            // Convert the actual squared maxVelRate to a normalized one\n            double t2 = duration * duration;\n            coeff.tail<1>()(0) -= sqrMaxVelRate * t2;\n            // Directly check the root existence in the normalized interval\n            return RootFinder::countRoots(coeff, 0.0, 1.0) == 0;\n        }\n    }\n\n    // Check whether accleration rate of the piece is always less than maxAccRate\n    inline bool checkMaxAccRate(double maxAccRate) const\n    {\n        double sqrMaxAccRate = maxAccRate * maxAccRate;\n        if (getAcc(0.0).squaredNorm() >= sqrMaxAccRate ||\n            getAcc(duration).squaredNorm() >= sqrMaxAccRate)\n        {\n            return false;\n        }\n        else\n        {\n            Eigen::MatrixXd nAccCoeffMat = getAccCoeffMat(true);\n            Eigen::VectorXd coeff = RootFinder::polySqr(nAccCoeffMat.row(0)) +\n                                    RootFinder::polySqr(nAccCoeffMat.row(1)) +\n                                    RootFinder::polySqr(nAccCoeffMat.row(2));\n            // Convert the actual squared maxAccRate to a normalized one\n            double t2 = duration * duration;\n            double t4 = t2 * t2;\n            coeff.tail<1>()(0) -= sqrMaxAccRate * t4;\n            // Directly check the root existence in the normalized interval\n            return RootFinder::countRoots(coeff, 0.0, 1.0) == 0;\n        }\n    }\n\n    // Check whether jerk rate of the piece is always less than maxJerkRate\n    inline bool checkMaxJerkRate(double maxJerkRate) const\n    {\n        double sqrMaxJerkRate = maxJerkRate * maxJerkRate;\n        if (getJerk(0.0).squaredNorm() >= sqrMaxJerkRate ||\n            getJerk(duration).squaredNorm() >= sqrMaxJerkRate)\n        {\n            return false;\n        }\n        else\n        {\n            Eigen::MatrixXd nJerkCoeffMat = getJerkCoeffMat(true);\n            Eigen::VectorXd coeff = RootFinder::polySqr(nJerkCoeffMat.row(0)) +\n                                    RootFinder::polySqr(nJerkCoeffMat.row(1)) +\n                                    RootFinder::polySqr(nJerkCoeffMat.row(2));\n            // Convert the actual squared maxJerkRate to a normalized one\n            double t2 = duration * duration;\n            double t4 = t2 * t2;\n            double t6 = t4 * t2;\n            coeff.tail<1>()(0) -= sqrMaxJerkRate * t6;\n            // Directly check the root existence in the normalized interval\n            return RootFinder::countRoots(coeff, 0.0, 1.0) == 0;\n        }\n    }\n\n    //Scale the Piece(t) to Piece(k*t)\n    inline void scaleTime(double k)\n    {\n        duration /= k;\n        return;\n    }\n\n    inline void sampleOneSeg(std::vector< StatePVA >* vis_x) const \n    {\n        double dt = 0.005;\n        for (double t = 0.0; t < duration; t += dt) \n        {\n            Eigen::Vector3d pos, vel, acc;\n            pos = getPos(t);\n            vel = getVel(t);\n            acc = getAcc(t);\n            StatePVA x;\n            x << pos(0), pos(1), pos(2), vel(0), vel(1), vel(2), acc(0), acc(1), acc(2);\n            vis_x->push_back(x);\n        }\n    }\n\n    inline void sampleOneSeg(std::vector< StatePVAM >* vis_x, double sample_t, double ground_judge) const \n    {\n        double dt = sample_t;\n        for (double t = 0.0; t < duration; t += dt) \n        {\n            Eigen::Vector3d pos, vel, acc;\n            pos = getPos(t);\n            vel = getVel(t);\n            acc = getAcc(t);\n            int motion_state = 0;\n            if(pos[2] >= ground_judge) motion_state = 1;\n            StatePVAM x;\n            x << pos(0), pos(1), pos(2), vel(0), vel(1), vel(2), acc(0), acc(1), acc(2), motion_state;\n            vis_x->push_back(x);\n        }\n    }\n\n    // for 5th degree polynomial\n    inline void cutPiece(const Piece &orig_piece, double ts, CoefficientMat &new_coeff) const\n    {\n        CoefficientMat ori_coeff = orig_piece.getCoeffMat();\n        double ts2 = ts * ts;\n        double ts3 = ts2 * ts;\n        double ts4 = ts3 * ts;\n        double ts5 = ts4 * ts;\n        for (int dim = 0; dim < 3; ++dim)\n        {\n            new_coeff(dim, 0) = ori_coeff(dim, 0);  //c5*t^5\n            new_coeff(dim, 1) = ori_coeff(dim, 1) + 5*ori_coeff(dim, 0)*ts;  //c4*4^4\n            new_coeff(dim, 2) = ori_coeff(dim, 2) + 4*ori_coeff(dim, 1)*ts + 10*ori_coeff(dim, 0)*ts2;\n            new_coeff(dim, 3) = ori_coeff(dim, 3) + 3*ori_coeff(dim, 2)*ts + 6*ori_coeff(dim, 1)*ts2 + 10*ori_coeff(dim, 0)*ts3;\n            new_coeff(dim, 4) = ori_coeff(dim, 4) + 2*ori_coeff(dim, 3)*ts + 3*ori_coeff(dim, 2)*ts2 + 4*ori_coeff(dim, 1)*ts3 + 5*ori_coeff(dim, 0)*ts4;\n            new_coeff(dim, 5) = ori_coeff(dim, 5) + ori_coeff(dim, 4)*ts + ori_coeff(dim, 3)*ts2 + ori_coeff(dim, 2)*ts3 + ori_coeff(dim, 1)*ts4 + ori_coeff(dim, 0)*ts5;\n        }\n    }\n\n    // for 5th degree polynomial\uff0c cost = integral(j^T rho j) + tau\n    inline double calCost(const double &rho) const\n    {\n        double tau2 = duration * duration;\n        double tau3 = tau2 * duration;\n        double tau4 = tau3 * duration;\n        double tau5 = tau4 * duration;\n\n        CoefficientMat coeff = getCoeffMat();\n        Eigen::Matrix<double, 6, 6> B = Eigen::Matrix<double, 6, 6>::Zero(6, 6);\n        B(0, 0) = 720 * tau5;\n        B(1, 1) = 192 * tau3;\n        B(2, 2) = 36 * duration;\n        B(0, 1) = B(1, 0) = 360 * tau4;\n        B(0, 2) = B(2, 0) = 120 * tau3;\n        B(1, 2) = B(2, 1) = 72 * tau2;\n        double cost(0.0);\n        for (int i=0; i<3; i++)\n        {\n            cost += coeff.row(i) * B * coeff.row(i).transpose();\n        }\n        cost *= rho;\n        cost += duration;\n\n        return cost;\n    }\n\n    inline double project_pt(const Eigen::Vector3d &pt,\n                           double &tt, Eigen::Vector3d &pro_pt) {\n        // 2*(p-p0)^T * \\dot{p} = 0\n        auto l_coeff = getCoeffMat();\n        l_coeff.col(5) = l_coeff.col(5) - pt;\n        auto r_coeff = getVelCoeffMat();\n        Eigen::VectorXd eq = Eigen::VectorXd::Zero(2 * 5);\n        for (int j = 0; j < l_coeff.rows(); ++j) {\n            eq = eq + RootFinder::polyConv(l_coeff.row(j), r_coeff.row(j));\n        }\n        double l = -0.0625;\n        double r = duration + 0.0625;\n        while (fabs(RootFinder::polyVal(eq, l)) < DBL_EPSILON) {\n            l = 0.5 * l;\n        }\n        while (fabs(RootFinder::polyVal(eq, r)) < DBL_EPSILON) {\n            r = 0.5 * (duration + r);\n        }\n        std::set<double> roots =\n            RootFinder::solvePolynomial(eq, l, r, 1e-6);\n        // std::cout << \"# roots: \" << roots.size() << std::endl;\n        double min_dist = -1;\n        for (const auto &root : roots) {\n            // std::cout << \"root: \" << root << std::endl;\n            if (root < 0 || root > duration) {\n                continue;\n            }\n            if (getVel(root).norm() < 1e-6) { // velocity == 0, ignore it\n                continue;\n            }\n            // std::cout << \"find min!\" << std::endl;\n            Eigen::Vector3d p = getPos(root);\n            // std::cout << \"p: \" << p.transpose() << std::endl;\n            double distance = (p - pt).norm();\n            if (distance < min_dist || min_dist < 0) {\n                min_dist = distance;\n                tt = root;\n                pro_pt = p;\n            }\n        }\n        return min_dist;\n    }\n    inline bool intersection_plane(const Eigen::Vector3d p, \n                                   const Eigen::Vector3d v,\n                                   double &tt, Eigen::Vector3d &pt) const {\n        // (pt - p)^T * v = 0\n        auto coeff = getCoeffMat();\n        coeff.col(5) = coeff.col(5) - p;\n        Eigen::VectorXd eq = coeff.transpose() * v;\n        double l = -0.0625;\n        double r = duration + 0.0625;\n        while (fabs(RootFinder::polyVal(eq, l)) < DBL_EPSILON) {\n            l = 0.5 * l;\n        }\n        while (fabs(RootFinder::polyVal(eq, r)) < DBL_EPSILON) {\n            r = 0.5 * (duration + r);\n        }\n        std::set<double> roots =\n            RootFinder::solvePolynomial(eq, l, r, 1e-6);\n        for (const auto &root : roots) {\n            tt = root;\n            pt = getPos(root);\n            return true;\n        }\n        return false;\n    }\n\n};\n\n// A whole trajectory which contains multiple pieces\nclass Trajectory\n{\nprivate:\n    typedef std::vector<Piece> Pieces;\n    Pieces pieces;\n\npublic:\n    Trajectory() = default;\n\n    // Constructor from durations and coefficient matrices\n    Trajectory(const std::vector<double> &durs,\n               const std::vector<CoefficientMat> &coeffMats)\n    {\n        int N = std::min(durs.size(), coeffMats.size());\n        pieces.reserve(N);\n        for (int i = 0; i < N; i++)\n        {\n            pieces.emplace_back(durs[i], coeffMats[i]);\n        }\n    }\n\n    inline int getPieceNum() const\n    {\n        return pieces.size();\n    }\n\n    // Get durations vector of all pieces\n    inline std::vector<double> getDurations() const\n    {\n        std::vector<double> durations;\n        durations.reserve(getPieceNum());\n        for (int i = 0; i < getPieceNum(); i++)\n        {\n            durations.push_back(pieces[i].getDuration());\n        }\n        return durations;\n    }\n\n    // Get total duration of the trajectory\n    inline double getTotalDuration() const\n    {\n        double totalDuration = 0.0;\n        for (int i = 0; i < getPieceNum(); i++)\n        {\n            totalDuration += pieces[i].getDuration();\n        }\n        return totalDuration;\n    }\n\n    // Reload the operator[] to reach the i-th piece\n    inline const Piece &operator[](int i) const\n    {\n        return pieces[i];\n    }\n\n    inline Piece &operator[](int i)\n    {\n        return pieces[i];\n    }\n\n    inline void clear(void)\n    {\n        pieces.clear();\n    }\n\n    inline Pieces::const_iterator begin() const\n    {\n        return pieces.begin();\n    }\n\n    inline Pieces::const_iterator end() const\n    {\n        return pieces.end();\n    }\n\n    inline void reserve(const int &n)\n    {\n        pieces.reserve(n);\n        return;\n    }\n\n    // Put another piece at the tail of this trajectory\n    inline void emplace_back(const Piece &piece)\n    {\n        pieces.emplace_back(piece);\n        return;\n    }\n\n    // Two corresponding constructors of Piece both are supported here\n    template <typename ArgTypeL, typename ArgTypeR>\n    inline void emplace_back(const ArgTypeL &argL, const ArgTypeR &argR)\n    {\n        pieces.emplace_back(argL, argR);\n        return;\n    }\n\n    // Append another Trajectory at the tail of this trajectory\n    inline void append(const Trajectory &traj)\n    {\n        pieces.insert(pieces.end(), traj.begin(), traj.end());\n        return;\n    }\n\n    // Find the piece at which the time t is located\n    // The index is returned and the offset in t is removed\n    inline int locatePieceIdx(double &t) const\n    {\n        int idx;\n        double dur;\n        for (idx = 0;\n             idx < getPieceNum() &&\n             t > (dur = pieces[idx].getDuration());\n             idx++)\n        {\n            t -= dur;\n        }\n        if (idx == getPieceNum())\n        {\n            idx--;\n            t += pieces[idx].getDuration();\n        }\n        return idx;\n    }\n\n    // Get the position at time t of the trajectory\n    inline Eigen::Vector3d getPos(double t) const\n    {\n        int pieceIdx = locatePieceIdx(t);\n        return pieces[pieceIdx].getPos(t);\n    }\n\n    // Get the velocity at time t of the trajectory\n    inline Eigen::Vector3d getVel(double t) const\n    {\n        int pieceIdx = locatePieceIdx(t);\n        return pieces[pieceIdx].getVel(t);\n    }\n\n    // Get the acceleration at time t of the trajectory\n    inline Eigen::Vector3d getAcc(double t) const\n    {\n        int pieceIdx = locatePieceIdx(t);\n        return pieces[pieceIdx].getAcc(t);\n    }\n\n    // Get the position at the juncIdx-th waypoint\n    inline Eigen::Vector3d getJuncPos(int juncIdx) const\n    {\n        if (juncIdx != getPieceNum())\n        {\n            return pieces[juncIdx].getPos(0.0);\n        }\n        else\n        {\n            return pieces[juncIdx - 1].getPos(pieces[juncIdx - 1].getDuration());\n        }\n    }\n\n    // Get the velocity at the juncIdx-th waypoint\n    inline Eigen::Vector3d getJuncVel(int juncIdx) const\n    {\n        if (juncIdx != getPieceNum())\n        {\n            return pieces[juncIdx].getVel(0.0);\n        }\n        else\n        {\n            return pieces[juncIdx - 1].getVel(pieces[juncIdx - 1].getDuration());\n        }\n    }\n\n    // Get the acceleration at the juncIdx-th waypoint\n    inline Eigen::Vector3d getJuncAcc(int juncIdx) const\n    {\n        if (juncIdx != getPieceNum())\n        {\n            return pieces[juncIdx].getAcc(0.0);\n        }\n        else\n        {\n            return pieces[juncIdx - 1].getAcc(pieces[juncIdx - 1].getDuration());\n        }\n    }\n\n    // Get the max velocity rate of the trajectory\n    inline double getMaxVelRate() const\n    {\n        double maxVelRate = -INFINITY;\n        double tempNorm;\n        for (int i = 0; i < getPieceNum(); i++)\n        {\n            tempNorm = pieces[i].getMaxVelRate();\n            maxVelRate = maxVelRate < tempNorm ? tempNorm : maxVelRate;\n        }\n        return maxVelRate;\n    }\n\n    // Get the max acceleration rate of the trajectory\n    inline double getMaxAccRate() const\n    {\n        double maxAccRate = -INFINITY;\n        double tempNorm;\n        for (int i = 0; i < getPieceNum(); i++)\n        {\n            tempNorm = pieces[i].getMaxAccRate();\n            maxAccRate = maxAccRate < tempNorm ? tempNorm : maxAccRate;\n        }\n        return maxAccRate;\n    }\n\n    // Get the max jerk rate of the trajectory\n    inline double getMaxJerkRate() const\n    {\n        double maxJerkRate = -INFINITY;\n        double tempNorm;\n        for (int i = 0; i < getPieceNum(); i++)\n        {\n            tempNorm = pieces[i].getMaxJerkRate();\n            maxJerkRate = maxJerkRate < tempNorm ? tempNorm : maxJerkRate;\n        }\n        return maxJerkRate;\n    }\n\n    // Check whether the velocity rate of this trajectory exceeds the threshold\n    inline bool checkMaxVelRate(double maxVelRate) const\n    {\n        bool feasible = true;\n        for (int i = 0; i < getPieceNum() && feasible; i++)\n        {\n            feasible = feasible && pieces[i].checkMaxVelRate(maxVelRate);\n        }\n        return feasible;\n    }\n\n    // Check whether the acceleration rate of this trajectory exceeds the threshold\n    inline bool checkMaxAccRate(double maxAccRate) const\n    {\n        bool feasible = true;\n        for (int i = 0; i < getPieceNum() && feasible; i++)\n        {\n            feasible = feasible && pieces[i].checkMaxAccRate(maxAccRate);\n        }\n        return feasible;\n    }\n\n    // Check whether the jerk rate of this trajectory exceeds the threshold\n    inline bool checkMaxJerkRate(double maxJerkRate) const\n    {\n        bool feasible = true;\n        for (int i = 0; i < getPieceNum() && feasible; i++)\n        {\n            feasible = feasible && pieces[i].checkMaxJerkRate(maxJerkRate);\n        }\n        return feasible;\n    }\n\n    // Scale the Trajectory(t) to Trajectory(k*t)\n    inline void scaleTime(double k)\n    {\n        for (int i = 0; i < getPieceNum(); i++)\n        {\n            pieces[i].scaleTime(k);\n        }\n    }\n\n    inline void sampleWholeTrajectory(std::vector< StatePVA >* vis_x) const \n    {\n        int n = getPieceNum();\n        for (int i = 0; i < n; ++i)\n        {\n            pieces[i].sampleOneSeg(vis_x);\n        }\n    }\n\n    inline double calCost(const double &rho, double* seg_cost) const\n    {\n        double cost(0.0);\n        for (int i = 0; i < getPieceNum(); i++)\n        {\n            seg_cost[i] = pieces[i].calCost(rho);\n            cost += seg_cost[i];\n        }\n        return cost;\n    }\n\n    inline void sampleWholeTrajectoryForOptimization(std::vector< StatePVAM >* vis_x, double sample_t, double ground_judge) const \n    {\n        int n = getPieceNum();\n        for (int i = 0; i < n; ++i)\n        {\n            pieces[i].sampleOneSeg(vis_x, sample_t, ground_judge);\n        }\n    }\n\n    inline void getWpts(std::vector< StatePVA >* wpts)\n    {\n        Eigen::Vector3d pos, vel, acc;\n        StatePVA x;\n        pos = pieces[0].getPos(0);\n        vel = pieces[0].getVel(0);\n        acc = pieces[0].getAcc(0);\n        x << pos(0), pos(1), pos(2), vel(0), vel(1), vel(2), acc(0), acc(1), acc(2);\n        wpts->push_back(x);\n        \n        int n = getPieceNum();\n        for (int i = 0; i < n; ++i)\n        {\n            double t = pieces[i].getDuration();\n            pos = pieces[i].getPos(t);\n            vel = pieces[i].getVel(t);\n            acc = pieces[i].getAcc(t);\n            x << pos(0), pos(1), pos(2), vel(0), vel(1), vel(2), acc(0), acc(1), acc(2);\n            wpts->push_back(x);\n        }\n    }\n\n    inline const Piece& getPiece(int i) const {\n        return pieces[i];\n    }\n    inline double project_pt(const Eigen::Vector3d &pt,\n                           int &ii, double &tt, Eigen::Vector3d &pro_pt) {\n        double dist = -1;\n        for (int i=0; i<getPieceNum(); ++i) {\n            auto piece = pieces[i];\n            dist = piece.project_pt(pt, tt, pro_pt);\n            if (dist > 0) {\n                ii = i;\n                break;\n            }\n        }\n        // if (dist < 0) {\n        //     std::cout << \"\\033[32m\" << \"cannot project pt to traj\" << \"\\033[0m\" << std::endl;\n        //     // std::cout << \"pt: \" << pt.transpose() << std::endl;\n        //     // assert(false);\n        // }\n        return dist;\n    }\n    inline bool intersection_plane(const Eigen::Vector3d p, \n                                   const Eigen::Vector3d v,\n                                   int &ii, double &tt, Eigen::Vector3d &pt) {\n        for (int i=0; i<getPieceNum(); ++i) {\n            const auto& piece = pieces[i];\n            if ( piece.intersection_plane(p,v,tt,pt) ) {\n                ii = i;\n                return true;\n            }\n        }\n        return false;\n    }\n\n    inline double evaluateTrajJerk() const\n    {\n        double objective = 0.0;\n        int M = getPieceNum();\n        CoefficientMat cMat;\n        double t1, t2, t3, t4, t5;\n        for (int i = 0; i < M; i++)\n        {\n            cMat = operator[](i).getCoeffMat();\n            t1 = operator[](i).getDuration();\n            t2 = t1 * t1;\n            t3 = t2 * t1;\n            t4 = t2 * t2;\n            t5 = t2 * t3;\n            objective += 36.0 * cMat.col(2).squaredNorm() * t1 +\n                        144.0 * cMat.col(1).dot(cMat.col(2)) * t2 +\n                        192.0 * cMat.col(1).squaredNorm() * t3 +\n                        240.0 * cMat.col(0).dot(cMat.col(2)) * t3 +\n                        720.0 * cMat.col(0).dot(cMat.col(1)) * t4 +\n                        720.0 * cMat.col(0).squaredNorm() * t5;\n        }\n        return objective;\n    }\n};\n\n// The banded system class is used for solving\n// banded linear system Ax=b efficiently.\n// A is an N*N band matrix with lower band width lowerBw\n// and upper band width upperBw.\n// Banded LU factorization has O(N) time complexity.\nclass BandedSystem\n{\npublic:\n    // The size of A, as well as the lower/upper\n    // banded width p/q are needed\n    inline void create(const int &n, const int &p, const int &q)\n    {\n        // In case of re-creating before destroying\n        destroy();\n        N = n;\n        lowerBw = p;\n        upperBw = q;\n        int actualSize = N * (lowerBw + upperBw + 1);\n        ptrData = new double[actualSize];\n        std::fill_n(ptrData, actualSize, 0.0);\n        return;\n    }\n\n    inline void destroy()\n    {\n        if (ptrData != nullptr)\n        {\n            delete[] ptrData;\n            ptrData = nullptr;\n        }\n        return;\n    }\n\nprivate:\n    int N;\n    int lowerBw;\n    int upperBw;\n    // Compulsory nullptr initialization here\n    double *ptrData = nullptr;\n\npublic:\n    // Reset the matrix to zero\n    inline void reset(void)\n    {\n        std::fill_n(ptrData, N * (lowerBw + upperBw + 1), 0.0);\n        return;\n    }\n\n    // The band matrix is stored as suggested in \"Matrix Computation\"\n    inline const double &operator()(const int &i, const int &j) const\n    {\n        return ptrData[(i - j + upperBw) * N + j];\n    }\n\n    inline double &operator()(const int &i, const int &j)\n    {\n        return ptrData[(i - j + upperBw) * N + j];\n    }\n\n    // This function conducts banded LU factorization in place\n    // Note that NO PIVOT is applied on the matrix \"A\" for efficiency!!!\n    inline void factorizeLU()\n    {\n        int iM, jM;\n        double cVl;\n        for (int k = 0; k <= N - 2; k++)\n        {\n            iM = std::min(k + lowerBw, N - 1);\n            cVl = operator()(k, k);\n            for (int i = k + 1; i <= iM; i++)\n            {\n                if (operator()(i, k) != 0.0)\n                {\n                    operator()(i, k) /= cVl;\n                }\n            }\n            jM = std::min(k + upperBw, N - 1);\n            for (int j = k + 1; j <= jM; j++)\n            {\n                cVl = operator()(k, j);\n                if (cVl != 0.0)\n                {\n                    for (int i = k + 1; i <= iM; i++)\n                    {\n                        if (operator()(i, k) != 0.0)\n                        {\n                            operator()(i, j) -= operator()(i, k) * cVl;\n                        }\n                    }\n                }\n            }\n        }\n        return;\n    }\n\n    // This function solves Ax=b, then stores x in b\n    // The input b is required to be N*m, i.e.,\n    // m vectors to be solved.\n    inline void solve(Eigen::MatrixXd &b) const\n    {\n        int iM;\n        for (int j = 0; j <= N - 1; j++)\n        {\n            iM = std::min(j + lowerBw, N - 1);\n            for (int i = j + 1; i <= iM; i++)\n            {\n                if (operator()(i, j) != 0.0)\n                {\n                    b.row(i) -= operator()(i, j) * b.row(j);\n                }\n            }\n        }\n        for (int j = N - 1; j >= 0; j--)\n        {\n            b.row(j) /= operator()(j, j);\n            iM = std::max(0, j - upperBw);\n            for (int i = iM; i <= j - 1; i++)\n            {\n                if (operator()(i, j) != 0.0)\n                {\n                    b.row(i) -= operator()(i, j) * b.row(j);\n                }\n            }\n        }\n        return;\n    }\n\n    // This function solves ATx=b, then stores x in b\n    // The input b is required to be N*m, i.e.,\n    // m vectors to be solved.\n    inline void solveAdj(Eigen::MatrixXd &b) const\n    {\n        int iM;\n        for (int j = 0; j <= N - 1; j++)\n        {\n            b.row(j) /= operator()(j, j);\n            iM = std::min(j + upperBw, N - 1);\n            for (int i = j + 1; i <= iM; i++)\n            {\n                if (operator()(j, i) != 0.0)\n                {\n                    b.row(i) -= operator()(j, i) * b.row(j);\n                }\n            }\n        }\n        for (int j = N - 1; j >= 0; j--)\n        {\n            iM = std::max(0, j - lowerBw);\n            for (int i = iM; i <= j - 1; i++)\n            {\n                if (operator()(j, i) != 0.0)\n                {\n                    b.row(i) -= operator()(j, i) * b.row(j);\n                }\n            }\n        }\n        return;\n    }\n};\n\nclass MinJerkOpt\n{\npublic:\n    MinJerkOpt() = default;\n    ~MinJerkOpt() { A.destroy(); }\n\nprivate:\n    int N;\n    Eigen::Matrix3d headPVA;\n    Eigen::Matrix3d tailPVA;\n    Eigen::VectorXd T1;\n    BandedSystem A;\n    Eigen::MatrixXd b;\n\n    // Temp variables\n    Eigen::VectorXd T2;\n    Eigen::VectorXd T3;\n    Eigen::VectorXd T4;\n    Eigen::VectorXd T5;\n    Eigen::MatrixXd gdC;\n\nprivate:\n    template <typename EIGENVEC>\n    inline void addGradJbyT(EIGENVEC &gdT) const\n    {\n        for (int i = 0; i < N; i++)\n        {\n            gdT(i) += 36.0 * b.row(6 * i + 3).squaredNorm() +\n                      288.0 * b.row(6 * i + 4).dot(b.row(6 * i + 3)) * T1(i) +\n                      576.0 * b.row(6 * i + 4).squaredNorm() * T2(i) +\n                      720.0 * b.row(6 * i + 5).dot(b.row(6 * i + 3)) * T2(i) +\n                      2880.0 * b.row(6 * i + 5).dot(b.row(6 * i + 4)) * T3(i) +\n                      3600.0 * b.row(6 * i + 5).squaredNorm() * T4(i);\n        }\n        return;\n    }\n\n    template <typename EIGENMAT>\n    inline void addGradJbyC(EIGENMAT &gdC) const\n    {\n        for (int i = 0; i < N; i++)\n        {\n            gdC.row(6 * i + 5) += 240.0 * b.row(6 * i + 3) * T3(i) +\n                                  720.0 * b.row(6 * i + 4) * T4(i) +\n                                  1440.0 * b.row(6 * i + 5) * T5(i);\n            gdC.row(6 * i + 4) += 144.0 * b.row(6 * i + 3) * T2(i) +\n                                  384.0 * b.row(6 * i + 4) * T3(i) +\n                                  720.0 * b.row(6 * i + 5) * T4(i);\n            gdC.row(6 * i + 3) += 72.0 * b.row(6 * i + 3) * T1(i) +\n                                  144.0 * b.row(6 * i + 4) * T2(i) +\n                                  240.0 * b.row(6 * i + 5) * T3(i);\n        }\n        return;\n    }\n\n    inline void solveAdjGradC(Eigen::MatrixXd &gdC) const\n    {\n        A.solveAdj(gdC);\n        return;\n    }\n\n    template <typename EIGENVEC>\n    inline void addPropCtoT(const Eigen::MatrixXd &adjGdC, EIGENVEC &gdT) const\n    {\n        Eigen::MatrixXd B1(6, 3), B2(3, 3);\n\n        Eigen::RowVector3d negVel, negAcc, negJer, negSnp, negCrk;\n\n        for (int i = 0; i < N - 1; i++)\n        {\n            negVel = -(b.row(i * 6 + 1) +\n                       2.0 * T1(i) * b.row(i * 6 + 2) +\n                       3.0 * T2(i) * b.row(i * 6 + 3) +\n                       4.0 * T3(i) * b.row(i * 6 + 4) +\n                       5.0 * T4(i) * b.row(i * 6 + 5));\n            negAcc = -(2.0 * b.row(i * 6 + 2) +\n                       6.0 * T1(i) * b.row(i * 6 + 3) +\n                       12.0 * T2(i) * b.row(i * 6 + 4) +\n                       20.0 * T3(i) * b.row(i * 6 + 5));\n            negJer = -(6.0 * b.row(i * 6 + 3) +\n                       24.0 * T1(i) * b.row(i * 6 + 4) +\n                       60.0 * T2(i) * b.row(i * 6 + 5));\n            negSnp = -(24.0 * b.row(i * 6 + 4) +\n                       120.0 * T1(i) * b.row(i * 6 + 5));\n            negCrk = -120.0 * b.row(i * 6 + 5);\n\n            B1 << negSnp, negCrk, negVel, negVel, negAcc, negJer;\n\n            gdT(i) += B1.cwiseProduct(adjGdC.block<6, 3>(6 * i + 3, 0)).sum();\n        }\n\n        negVel = -(b.row(6 * N - 5) +\n                   2.0 * T1(N - 1) * b.row(6 * N - 4) +\n                   3.0 * T2(N - 1) * b.row(6 * N - 3) +\n                   4.0 * T3(N - 1) * b.row(6 * N - 2) +\n                   5.0 * T4(N - 1) * b.row(6 * N - 1));\n        negAcc = -(2.0 * b.row(6 * N - 4) +\n                   6.0 * T1(N - 1) * b.row(6 * N - 3) +\n                   12.0 * T2(N - 1) * b.row(6 * N - 2) +\n                   20.0 * T3(N - 1) * b.row(6 * N - 1));\n        negJer = -(6.0 * b.row(6 * N - 3) +\n                   24.0 * T1(N - 1) * b.row(6 * N - 2) +\n                   60.0 * T2(N - 1) * b.row(6 * N - 1));\n\n        B2 << negVel, negAcc, negJer;\n\n        gdT(N - 1) += B2.cwiseProduct(adjGdC.block<3, 3>(6 * N - 3, 0)).sum();\n\n        return;\n    }\n\n    template <typename EIGENMAT>\n    inline void addPropCtoP(const Eigen::MatrixXd &adjGdC, EIGENMAT &gdInP) const\n    {\n        for (int i = 0; i < N - 1; i++)\n        {\n            gdInP.col(i) += adjGdC.row(6 * i + 5).transpose();\n        }\n        return;\n    }\n\n    template <typename EIGENVEC>\n    inline void addTimeIntPenalty(const Eigen::VectorXi cons,\n                                  const Eigen::VectorXi &idxHs,\n                                  const std::vector<Eigen::MatrixXd> &cfgHs,\n                                  const double vmax,\n                                  const double amax,\n                                  const Eigen::Vector3d ci,\n                                  double &cost,\n                                  EIGENVEC &gdT,\n                                  Eigen::MatrixXd &gdC) const\n    {\n        double pena = 0.0;\n        const double vmaxSqr = vmax * vmax;\n        const double amaxSqr = amax * amax;\n\n        Eigen::Vector3d pos, vel, acc, jer;\n        double step, alpha;\n        double s1, s2, s3, s4, s5;\n        Eigen::Matrix<double, 6, 1> beta0, beta1, beta2, beta3;\n        Eigen::Vector3d outerNormal;\n        int K;\n        double violaPos, violaVel, violaAcc;\n        double violaPosPenaD, violaVelPenaD, violaAccPenaD;\n        double violaPosPena, violaVelPena, violaAccPena;\n        Eigen::Matrix<double, 6, 3> gradViolaVc, gradViolaAc;\n        double gradViolaVt, gradViolaAt;\n        double omg;\n\n        int innerLoop, idx;\n        for (int i = 0; i < N; i++)\n        {\n            const auto &c = b.block<6, 3>(i * 6, 0);\n            step = T1(i) / cons(i);\n            s1 = 0.0;\n            innerLoop = cons(i) + 1;\n            for (int j = 0; j < innerLoop; j++)\n            {\n                s2 = s1 * s1;\n                s3 = s2 * s1;\n                s4 = s2 * s2;\n                s5 = s4 * s1;\n                beta0 << 1.0, s1, s2, s3, s4, s5;\n                beta1 << 0.0, 1.0, 2.0 * s1, 3.0 * s2, 4.0 * s3, 5.0 * s4;\n                beta2 << 0.0, 0.0, 2.0, 6.0 * s1, 12.0 * s2, 20.0 * s3;\n                beta3 << 0.0, 0.0, 0.0, 6.0, 24.0 * s1, 60.0 * s2;\n                alpha = 1.0 / cons(i) * j;\n                pos = c.transpose() * beta0;\n                vel = c.transpose() * beta1;\n                acc = c.transpose() * beta2;\n                jer = c.transpose() * beta3;\n                violaVel = vel.squaredNorm() - vmaxSqr;\n                violaAcc = acc.squaredNorm() - amaxSqr;\n\n                omg = (j == 0 || j == innerLoop - 1) ? 0.5 : 1.0;\n\n                idx = idxHs(i);\n                K = cfgHs[idx].cols();\n                for (int k = 0; k < K; k++)\n                {\n                    outerNormal = cfgHs[idx].col(k).head<3>();\n                    violaPos = outerNormal.dot(pos - cfgHs[idx].col(k).tail<3>());\n                    if (violaPos > 0.0)\n                    {\n                        violaPosPenaD = violaPos * violaPos;\n                        violaPosPena = violaPosPenaD * violaPos;\n                        violaPosPenaD *= 3.0;\n                        gdC.block<6, 3>(i * 6, 0) += omg * step * ci(0) * violaPosPenaD * beta0 * outerNormal.transpose();\n                        gdT(i) += omg * (ci(0) * violaPosPenaD * alpha * outerNormal.dot(vel) * step +\n                                         ci(0) * violaPosPena / cons(i));\n                        pena += omg * step * ci(0) * violaPosPena;\n                    }\n                }\n\n                if (violaVel > 0.0)\n                {\n                    violaVelPenaD = violaVel * violaVel;\n                    violaVelPena = violaVelPenaD * violaVel;\n                    violaVelPenaD *= 3.0;\n                    gradViolaVc = 2.0 * beta1 * vel.transpose();\n                    gradViolaVt = 2.0 * alpha * vel.transpose() * acc;\n                    gdC.block<6, 3>(i * 6, 0) += omg * step * ci(1) * violaVelPenaD * gradViolaVc;\n                    gdT(i) += omg * (ci(1) * violaVelPenaD * gradViolaVt * step +\n                                     ci(1) * violaVelPena / cons(i));\n                    pena += omg * step * ci(1) * violaVelPena;\n                }\n\n                if (violaAcc > 0.0)\n                {\n                    violaAccPenaD = violaAcc * violaAcc;\n                    violaAccPena = violaAccPenaD * violaAcc;\n                    violaAccPenaD *= 3.0;\n                    gradViolaAc = 2.0 * beta2 * acc.transpose();\n                    gradViolaAt = 2.0 * alpha * acc.transpose() * jer;\n                    gdC.block<6, 3>(i * 6, 0) += omg * step * ci(2) * violaAccPenaD * gradViolaAc;\n                    gdT(i) += omg * (ci(2) * violaAccPenaD * gradViolaAt * step +\n                                     ci(2) * violaAccPena / cons(i));\n                    pena += omg * step * ci(2) * violaAccPena;\n                }\n\n                s1 += step;\n            }\n        }\n\n        cost += pena;\n        return;\n    }\n\npublic:\n    inline void reset(const Eigen::Matrix3d &headState,\n                      const Eigen::Matrix3d &tailState,\n                      const int &pieceNum)\n    {\n        N = pieceNum;\n        headPVA = headState;\n        tailPVA = tailState;\n        T1.resize(N);\n        A.create(6 * N, 6, 6);\n        b.resize(6 * N, 3);\n        gdC.resize(6 * N, 3);\n        return;\n    }\n\n    inline void generate(const Eigen::MatrixXd &inPs,\n                         const Eigen::VectorXd &ts)\n    {\n        T1 = ts;\n        T2 = T1.cwiseProduct(T1);\n        T3 = T2.cwiseProduct(T1);\n        T4 = T2.cwiseProduct(T2);\n        T5 = T4.cwiseProduct(T1);\n\n        A.reset();\n        b.setZero();\n\n        A(0, 0) = 1.0;\n        A(1, 1) = 1.0;\n        A(2, 2) = 2.0;\n        b.row(0) = headPVA.col(0).transpose();\n        b.row(1) = headPVA.col(1).transpose();\n        b.row(2) = headPVA.col(2).transpose();\n\n        for (int i = 0; i < N - 1; i++)\n        {\n            A(6 * i + 3, 6 * i + 3) = 6.0;\n            A(6 * i + 3, 6 * i + 4) = 24.0 * T1(i);\n            A(6 * i + 3, 6 * i + 5) = 60.0 * T2(i);\n            A(6 * i + 3, 6 * i + 9) = -6.0;\n            A(6 * i + 4, 6 * i + 4) = 24.0;\n            A(6 * i + 4, 6 * i + 5) = 120.0 * T1(i);\n            A(6 * i + 4, 6 * i + 10) = -24.0;\n            A(6 * i + 5, 6 * i) = 1.0;\n            A(6 * i + 5, 6 * i + 1) = T1(i);\n            A(6 * i + 5, 6 * i + 2) = T2(i);\n            A(6 * i + 5, 6 * i + 3) = T3(i);\n            A(6 * i + 5, 6 * i + 4) = T4(i);\n            A(6 * i + 5, 6 * i + 5) = T5(i);\n            A(6 * i + 6, 6 * i) = 1.0;\n            A(6 * i + 6, 6 * i + 1) = T1(i);\n            A(6 * i + 6, 6 * i + 2) = T2(i);\n            A(6 * i + 6, 6 * i + 3) = T3(i);\n            A(6 * i + 6, 6 * i + 4) = T4(i);\n            A(6 * i + 6, 6 * i + 5) = T5(i);\n            A(6 * i + 6, 6 * i + 6) = -1.0;\n            A(6 * i + 7, 6 * i + 1) = 1.0;\n            A(6 * i + 7, 6 * i + 2) = 2 * T1(i);\n            A(6 * i + 7, 6 * i + 3) = 3 * T2(i);\n            A(6 * i + 7, 6 * i + 4) = 4 * T3(i);\n            A(6 * i + 7, 6 * i + 5) = 5 * T4(i);\n            A(6 * i + 7, 6 * i + 7) = -1.0;\n            A(6 * i + 8, 6 * i + 2) = 2.0;\n            A(6 * i + 8, 6 * i + 3) = 6 * T1(i);\n            A(6 * i + 8, 6 * i + 4) = 12 * T2(i);\n            A(6 * i + 8, 6 * i + 5) = 20 * T3(i);\n            A(6 * i + 8, 6 * i + 8) = -2.0;\n\n            b.row(6 * i + 5) = inPs.col(i).transpose();\n        }\n\n        A(6 * N - 3, 6 * N - 6) = 1.0;\n        A(6 * N - 3, 6 * N - 5) = T1(N - 1);\n        A(6 * N - 3, 6 * N - 4) = T2(N - 1);\n        A(6 * N - 3, 6 * N - 3) = T3(N - 1);\n        A(6 * N - 3, 6 * N - 2) = T4(N - 1);\n        A(6 * N - 3, 6 * N - 1) = T5(N - 1);\n        A(6 * N - 2, 6 * N - 5) = 1.0;\n        A(6 * N - 2, 6 * N - 4) = 2 * T1(N - 1);\n        A(6 * N - 2, 6 * N - 3) = 3 * T2(N - 1);\n        A(6 * N - 2, 6 * N - 2) = 4 * T3(N - 1);\n        A(6 * N - 2, 6 * N - 1) = 5 * T4(N - 1);\n        A(6 * N - 1, 6 * N - 4) = 2;\n        A(6 * N - 1, 6 * N - 3) = 6 * T1(N - 1);\n        A(6 * N - 1, 6 * N - 2) = 12 * T2(N - 1);\n        A(6 * N - 1, 6 * N - 1) = 20 * T3(N - 1);\n\n        b.row(6 * N - 3) = tailPVA.col(0).transpose();\n        b.row(6 * N - 2) = tailPVA.col(1).transpose();\n        b.row(6 * N - 1) = tailPVA.col(2).transpose();\n\n        A.factorizeLU();\n        A.solve(b);\n\n        return;\n    }\n\n    inline double getTrajJerkCost() const\n    {\n        double objective = 0.0;\n        for (int i = 0; i < N; i++)\n        {\n            objective += 36.0 * b.row(6 * i + 3).squaredNorm() * T1(i) +\n                         144.0 * b.row(6 * i + 4).dot(b.row(6 * i + 3)) * T2(i) +\n                         192.0 * b.row(6 * i + 4).squaredNorm() * T3(i) +\n                         240.0 * b.row(6 * i + 5).dot(b.row(6 * i + 3)) * T3(i) +\n                         720.0 * b.row(6 * i + 5).dot(b.row(6 * i + 4)) * T4(i) +\n                         720.0 * b.row(6 * i + 5).squaredNorm() * T5(i);\n        }\n        return objective;\n    }\n\n    template <typename EIGENVEC, typename EIGENMAT>\n    inline void evalTrajCostGrad(const Eigen::VectorXi &cons,\n                                 const Eigen::VectorXi &idxHs,\n                                 const std::vector<Eigen::MatrixXd> &cfgHs,\n                                 const double &vmax,\n                                 const double &amax,\n                                 const Eigen::Vector3d &ci,\n                                 double &cost,\n                                 EIGENVEC &gdT,\n                                 EIGENMAT &gdInPs)\n    {\n        gdT.setZero();\n        gdInPs.setZero();\n        gdC.setZero();\n\n        cost = getTrajJerkCost();\n        addGradJbyT(gdT);\n        addGradJbyC(gdC);\n\n        addTimeIntPenalty(cons, idxHs, cfgHs, vmax, amax, ci, cost, gdT, gdC);\n\n        solveAdjGradC(gdC);\n        addPropCtoT(gdC, gdT);\n        addPropCtoP(gdC, gdInPs);\n    }\n\n    inline Trajectory getTraj(void) const\n    {\n        Trajectory traj;\n        traj.reserve(N);\n        for (int i = 0; i < N; i++)\n        {\n            traj.emplace_back(T1(i), b.block<6, 3>(6 * i, 0).transpose().rowwise().reverse());\n        }\n        return traj;\n    }\n\n\n    // GaaiLam\n    template <typename EIGENVEC, typename EIGENMAT>\n    inline void initGradCost(EIGENVEC &gdT,\n                             EIGENMAT &gdInPs, \n                             double &cost) {\n        gdT.setZero();\n        gdInPs.setZero();\n        gdC.setZero();\n        cost = getTrajJerkCost();\n        addGradJbyT(gdT);\n        addGradJbyC(gdC);\n    }\n\n    template <class TRAJGEN, typename EIGENVEC>\n    // TRAJGEN::grad_cost_p(const Eigen::Vector3d &p, \n    //                      Eigen::Vector3d &gradp, \n    //                      double &cost) {}\n    inline void addGrad2PVA(TRAJGEN *ptrObj,  \n                            EIGENVEC &gdT, \n                            double &cost, \n                            const int &K=4) {\n        //\n        Eigen::Vector3d pos, vel, acc, jer;\n        Eigen::Vector3d gradp, gradv, grada;\n        double costp, costv, costa;\n        Eigen::Matrix<double, 6, 1> beta0, beta1, beta2, beta3;\n        double s1, s2, s3, s4, s5;\n        double step, alpha;\n        Eigen::Matrix<double, 6, 3> gradViolaPc, gradViolaVc, gradViolaAc;\n        double gradViolaPt, gradViolaVt, gradViolaAt;\n        double omg;\n\n        int innerLoop;\n        for (int i=0; i<N; ++i) {\n            const auto &c = b.block<6, 3>(i * 6, 0);\n            step = T1(i) / K;\n            s1 = 0.0;\n            innerLoop = K+1;\n\n            for (int j=0; j<innerLoop; ++j) {\n                s2 = s1 * s1;\n                s3 = s2 * s1;\n                s4 = s2 * s2;\n                s5 = s4 * s1;\n                beta0 << 1.0, s1, s2, s3, s4, s5;\n                beta1 << 0.0, 1.0, 2.0 * s1, 3.0 * s2, 4.0 * s3, 5.0 * s4;\n                beta2 << 0.0, 0.0, 2.0, 6.0 * s1, 12.0 * s2, 20.0 * s3;\n                beta3 << 0.0, 0.0, 0.0, 6.0, 24.0 * s1, 60.0 * s2;\n                alpha = 1.0 / K * j;\n                pos = c.transpose() * beta0;\n                vel = c.transpose() * beta1;\n                acc = c.transpose() * beta2;\n                jer = c.transpose() * beta3;\n\n                omg = (j == 0 || j == innerLoop - 1) ? 0.5 : 1.0;\n\n                if ( ptrObj->grad_cost_p(pos, gradp, costp) ) {\n                    gradViolaPc = beta0 * gradp.transpose();\n                    gradViolaPt = alpha * gradp.transpose() * vel;\n                    gdC.block<6, 3>(i * 6, 0) += omg * step * gradViolaPc;\n                    gdT(i) += omg * (costp/K + step * gradViolaPt);\n                    cost += omg * step * costp;\n                }\n                if ( ptrObj->grad_cost_v(vel, gradv, costv) ) {\n                    gradViolaVc = beta1 * gradv.transpose();\n                    gradViolaVt = alpha * gradv.transpose() * acc;\n                    gdC.block<6, 3>(i * 6, 0) += omg * step * gradViolaVc;\n                    gdT(i) += omg * (costv/K + step * gradViolaVt);\n                    cost += omg * step * costv;\n                }\n                if ( ptrObj->grad_cost_a(acc, grada, costa) ) {\n                    gradViolaAc = beta2 * grada.transpose();\n                    gradViolaAt = alpha * grada.transpose() * jer;\n                    gdC.block<6, 3>(i * 6, 0) += omg * step * gradViolaAc;\n                    gdT(i) += omg * (costa/K + step * gradViolaAt);\n                    cost += omg * step * costa;\n                }\n\n                s1 += step;\n            }\n        }\n    }\n\n    template <class TRAJGEN, typename EIGENVEC>\n    // i: the ith piece of traj\n    // w: percent of time of this piece\n    // TRAJGEN::grad_cost_p_at\n    inline void addGrad2P_at (TRAJGEN *ptrObj, \n                              const int &i, \n                              const double &w, \n                              EIGENVEC &gdT, \n                              double &cost) {\n        const auto &c = b.block<6, 3>(i * 6, 0);\n        Eigen::Vector3d pos, vel, gradp;\n        double costp = 0;\n        double s1 = w * T1(i);\n        double s2 = s1 * s1;\n        double s3 = s2 * s1;\n        double s4 = s3 * s1;\n        double s5 = s4 * s1;\n        Eigen::Matrix<double, 6, 1> beta0, beta1;\n        beta0 << 1.0, s1, s2, s3, s4, s5;\n        beta1 << 0.0, 1.0, 2.0 * s1, 3.0 * s2, 4.0 * s3, 5.0 * s4;\n        pos = c.transpose() * beta0;\n        vel = c.transpose() * beta1;\n        if ( ptrObj->grad_cost_p_at(pos, gradp, costp) ) {\n            gdC.block<6, 3>(i * 6, 0) += beta0 * gradp.transpose();\n            gdT(i) += w * gradp.transpose() * vel;\n            cost += costp;\n        }\n    }\n\n    template <typename EIGENVEC, typename EIGENMAT>\n    inline void getGrad2TP(EIGENVEC &gdT,\n                           EIGENMAT &gdInPs) {\n        solveAdjGradC(gdC);\n        addPropCtoT(gdC, gdT);\n        addPropCtoP(gdC, gdInPs);\n    }\n};\n\n#endif\n", "meta": {"hexsha": "cf6dbe561358e528176cb945a100ae83277d170c", "size": 56946, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/TIE_navigation/traj_utils/include/traj_utils/traj_utils.hpp", "max_stars_repo_name": "ZJU-FAST-Lab/Terrestrial-Aerial-Navigation", "max_stars_repo_head_hexsha": "3602623ff8cb9735c6ece8c25772a3809cb0362e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-09T06:35:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T02:34:39.000Z", "max_issues_repo_path": "src/TIE_navigation/traj_utils/include/traj_utils/traj_utils.hpp", "max_issues_repo_name": "RoboticsZhang/Terrestrial-Aerial-Navigation", "max_issues_repo_head_hexsha": "d73b6fa9d51985f442fda6d0e282226cb7a45186", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TIE_navigation/traj_utils/include/traj_utils/traj_utils.hpp", "max_forks_repo_name": "RoboticsZhang/Terrestrial-Aerial-Navigation", "max_forks_repo_head_hexsha": "d73b6fa9d51985f442fda6d0e282226cb7a45186", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-09T05:44:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T05:44:24.000Z", "avg_line_length": 33.8964285714, "max_line_length": 169, "alphanum_fraction": 0.4670740702, "num_tokens": 16810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.6442251064863695, "lm_q1q2_score": 0.5296748689350752}}
{"text": "#include <boost/mpi.hpp>\n\n#include \"mpi_impl/scatter_mesh.hpp\"\n#include \"mpi_impl/dot.hpp\"\n\nnamespace mpi = boost::mpi;\nusing namespace schro_mpi;\n\nbool test_dot(mpi::communicator& comm)\n{\n    int order = 6;\n    \n    Mesh<double> mesh = scatter_mesh<double>(order, \"../meshes/small_mesh\", comm, 0);\n    mesh.compute_metrics();\n\n    SparseData<matrix<double>> u;\n    for (auto it = mesh.elements.begin(); it != mesh.elements.end(); ++it)\n        u[it->first] = arma::ones(mesh.N, mesh.N);\n\n    double p = dot(mesh, u, u); // since u = 1, dot(u,u) = total degrees of freedom\n\n    int d = mesh.dof(); // processor-local degrees of freedom\n    d = mpi::all_reduce(comm, d, std::plus<int>{}); // all degrees of freedom\n\n    bool success = true;\n    if (p != d) {\n        if (comm.rank() == 0)\n            std::cout << \"dot() failed test: produced incorrect value\\n\";\n        success = false;\n    }\n\n    return success;\n}", "meta": {"hexsha": "867fc839072c5975e7c3c23ef56df7abd0c00a87", "size": 915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mpi_tests/dot.cpp", "max_stars_repo_name": "arotem3/SchrodingerSEM", "max_stars_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mpi_tests/dot.cpp", "max_issues_repo_name": "arotem3/SchrodingerSEM", "max_issues_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mpi_tests/dot.cpp", "max_forks_repo_name": "arotem3/SchrodingerSEM", "max_forks_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7272727273, "max_line_length": 85, "alphanum_fraction": 0.6109289617, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6442250928250376, "lm_q1q2_score": 0.5296748633165587}}
{"text": "/******************************************************************************\n * Copyright 2017 Baidu Robotic Vision Authors. 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 \"feature_utils.h\"\n#include <Eigen/Dense>\n\n#define SUBPIX_VERBOSE 0\n\nnamespace XP {\nnamespace align {\n\nusing Eigen::Vector2f;\nusing Eigen::Vector3f;\nusing Eigen::Matrix2f;\nusing Eigen::Matrix3f;\nusing Eigen::Matrix3i;\nconst int W_BITS = 14;\nconst int half_patch_size = 4;\nconst int patch_size = 8;\nconst int patch_area = 64;\nbool align1D(const cv::Mat& cur_img,\n             const Vector2f& dir,  // direction in which the patch is allowed to move\n             uint8_t* ref_patch_with_border,\n             uint8_t* ref_patch,\n             const int n_iter,\n             Vector2f* cur_px_estimate,\n             float* h_inv) {\n  bool converged = false;\n\n  // compute derivative of template and prepare inverse compositional\n  float __attribute__((__aligned__(16))) ref_patch_dv[patch_area];\n  Matrix2f H; H.setZero();\n\n  // compute gradient and hessian\n  const int ref_step = patch_size + 2;\n  float* it_dv = ref_patch_dv;\n  for (int y=0; y < patch_size; ++y) {\n    uint8_t* it = ref_patch_with_border + (y + 1) * ref_step + 1;\n    for (int x = 0; x < patch_size; ++x, ++it, ++it_dv) {\n      Vector2f J;\n      J[0] = 0.5*(dir[0] * (it[1] - it[-1]) + dir[1] * (it[ref_step] - it[-ref_step]));\n      J[1] = 1;\n      *it_dv = J[0];\n      H += J * J.transpose();\n    }\n  }\n  *h_inv = 1.0 / H(0, 0) * patch_size * patch_size;\n  Matrix2f Hinv = H.inverse();\n  float mean_diff = 0;\n\n  // Compute pixel location in new image:\n  float u = (*cur_px_estimate)(0);\n  float v = (*cur_px_estimate)(1);\n\n  // termination condition\n  const float min_update_squared = 0.03 * 0.03;\n  const int cur_step = cur_img.step.p[0];\n  float chi2 = 0;\n  Vector2f update; update.setZero();\n  for (int iter = 0; iter < n_iter; ++iter) {\n    int u_r = floor(u);\n    int v_r = floor(v);\n    if (u_r < half_patch_size || v_r < half_patch_size ||\n        u_r >= cur_img.cols-half_patch_size || v_r >= cur_img.rows - half_patch_size) {\n      break;\n    }\n    if (std::isnan(u) || std::isnan(v)) {\n      // TODO(SVO): very rarely this can happen, maybe H is singular? should not be at corner.\n      return false;\n    }\n\n    // compute interpolation weights\n    float subpix_x = u - u_r;\n    float subpix_y = v - v_r;\n    float wTL = (1.0 - subpix_x) * (1.0 - subpix_y);\n    float wTR = subpix_x * (1.0 - subpix_y);\n    float wBL = (1.0 - subpix_x) * subpix_y;\n    float wBR = subpix_x * subpix_y;\n\n    // loop through search_patch, interpolate\n    uint8_t* it_ref = ref_patch;\n    float* it_ref_dv = ref_patch_dv;\n    float new_chi2 = 0.0;\n    Vector2f Jres; Jres.setZero();\n    for (int y = 0; y < patch_size; ++y) {\n      uint8_t* it = static_cast<uint8_t*>(cur_img.data) +\n          (v_r + y - half_patch_size) * cur_step + u_r - half_patch_size;\n      for (int x = 0; x < patch_size; ++x, ++it, ++it_ref, ++it_ref_dv) {\n        float search_pixel = wTL * it[0] + wTR * it[1] + wBL * it[cur_step] + wBR * it[cur_step+1];\n        float res = search_pixel - *it_ref + mean_diff;\n        Jres[0] -= res * (*it_ref_dv);\n        Jres[1] -= res;\n        new_chi2 += res * res;\n      }\n    }\n\n    if (iter > 0 && new_chi2 > chi2) {\n#if SUBPIX_VERBOSE\n      cout << \"error increased.\" << endl;\n#endif\n      u -= update[0];\n      v -= update[1];\n      break;\n    }\n\n    chi2 = new_chi2;\n    update = Hinv * Jres;\n    u += update[0] * dir[0];\n    v += update[0] * dir[1];\n    mean_diff += update[1];\n\n#if SUBPIX_VERBOSE\n    VLOG(2) << \"Iter \" << iter << \":\"\n            << \"\\t u=\" << u << \", v=\" << v\n            << \"\\t update = \" << update[0] << \", \" << update[1]\n            << \"\\t new chi2 = \" << new_chi2;\n#endif\n\n    if (update[0] * update[0] + update[1] * update[1] < min_update_squared) {\n#if SUBPIX_VERBOSE\n      VLOG(2) << \"converged.\";\n#endif\n      converged = true;\n      break;\n    }\n  }\n\n  *cur_px_estimate << u, v;\n  return converged;\n}\n\n\n //\u9006\u5411\u7ec4\u5408\u6cd5\u8fdb\u884c2D\u56fe\u50cf\u5bf9\u9f50,\u8fd9\u4e2a\u597d\u50cf\u662f\u5728LK\u5341\u5e74\u90a3\u4e2a\u8bba\u6587\u91cc\u6709\u8bf4\u8fc7\n //\u8f93\u5165\u53f3\u76f8\u673a\u7684\u56fe\u50cf,\u4ece\u5de6\u76f8\u673a\u53d8\u6362\u5230\u53f3\u76f8\u673a\u4e0a\u7684patch_border,\u4ece\u5de6\u76f8\u673a\u53d8\u6362\u5230\u53f3\u76f8\u673a\u4e0a\u7684patch,\u6700\u5927\u8fed\u4ee3\u6b21\u6570\n //\u8f93\u51fa\u6700\u7ec8\u5757\u5339\u914d\u6b8b\u5dee\u6700\u5c0f\u7684\u53f3\u76ee\u4e2d\u7279\u5f81\u70b9\u7684\u50cf\u7d20\u5750\u6807\n //\u6b8b\u5dee: r = I(p_cur) - I(p_ref) + m ,\u5176\u4e2dI(*)\u8868\u793a\u5728\u67d0\u4e2a\u50cf\u7d20\u4f4d\u7f6e\u7684\u5149\u5ea6, m\u662f\u5747\u503c\u5dee.cur\u662f\u53f3\u76f8\u673a,ref\u662f\u5de6\u76f8\u673a\n //\u4f18\u5316\u53d8\u91cf\u662fp_ref,m\uff0c\u8fd9\u91cc\u4e3a\u4ec0\u4e48\u662fp_ref\u800c\u4e0d\u662fp_cur,\u662f\u56e0\u4e3a\u5982\u679c\u7528p_cur\uff0c\u6bcf\u6b21\u589e\u91cf\u4ee5\u540e\u8fd8\u9700\u8981\u518d\u8ba1\u7b97\u4e00\u6b21\u8fd9\u4e2a\u7684J,\u7528p_ref\u53ea\u7528\u7b97\u4e00\u6b21,\u5747\u503c\u5dee\u4e5f\u505a\u4e3a\u4f18\u5316\u53d8\u91cf\u662f\u9632\u6b62\u566a\u58f0\nbool align2D(const cv::Mat& cur_img,\n             uint8_t* ref_patch_with_border,\n             uint8_t* ref_patch,\n             const int n_iter,\n             Vector2f* cur_px_estimate,\n             bool no_simd)\n             {\n/*\n#ifdef __ARM_NEON__\n  Vector2f cur_px_estimate_neon = *cur_px_estimate;\n  if (!no_simd) {\n    align2D_NEON(cur_img, ref_patch_with_border, ref_patch, n_iter, &cur_px_estimate_neon);\n  }\n#endif\n*/\n  bool converged = false;\n// \u6a21\u677f\u56fe\u50cf\u5bf9\u50cf\u7d20 x,y \u5750\u6807\u8fdb\u884c\u6c42\u5bfc\n  // compute derivative of template and prepare inverse compositional\n  float __attribute__((__aligned__(16))) ref_patch_dx[patch_area];\n  float __attribute__((__aligned__(16))) ref_patch_dy[patch_area];\n  Matrix3f H; H.setZero();\n\n  // compute gradient and hessian\n  const int ref_step = patch_size+2;//patch\u6846\u8fb9\u957f\n     // \u56fe\u50cf\u5bfc\u6570\u7684\u6307\u9488\n  float* it_dx = ref_patch_dx;\n  float* it_dy = ref_patch_dy;\n  //\u6784\u9020H\u77e9\u9635\n  for (int y = 0; y < patch_size; ++y) {\n    uint8_t* it = ref_patch_with_border + (y + 1) * ref_step + 1;\n    for (int x = 0; x < patch_size; ++x, ++it, ++it_dx, ++it_dy) {\n      Vector3f J;\n      //p_ref\u50cf\u7d20\u503c\u5173\u4e8e\u4f4d\u7f6e\uff0c\u5176\u5b9e\u5c31\u662f\u68af\u5ea6\n      J[0] = 0.5 * (it[1] - it[-1]);\n      J[1] = 0.5 * (it[ref_step] - it[-ref_step]);\n      J[2] = 1;//\u5747\u503c\u5dee\u7684\u5bfc\u6570\n      *it_dx = J[0];\n      *it_dy = J[1];\n      H += J*J.transpose();\n    }\n  }\n  Matrix3f Hinv = H.inverse();\n  float mean_diff = 0;\n\n  // Compute pixel location in new image:\n     //\u521d\u503c\n  float u = (*cur_px_estimate)(0);\n  float v = (*cur_px_estimate)(1);\n\n  // termination condition\n  const float min_update_squared = 0.03 * 0.03;//\u6536\u655b\u6761\u4ef6\n  const int cur_step = cur_img.step.p[0];\n  float chi2 = std::numeric_limits<int>::max();\n  Vector3f update; update.setZero();//\u4f18\u5316\u53d8\u91cf\u7684\u589e\u91cf\n  for (int iter = 0; iter < n_iter; ++iter) //\u4f18\u5316\u5f00\u59cb\n  {\n    int u_r = floor(u);\n    int v_r = floor(v);\n    //\u8fb9\u7f18\u5904\u8df3\u8fc7\n    if (u_r < half_patch_size || v_r < half_patch_size ||\n        u_r >= cur_img.cols-half_patch_size || v_r >= cur_img.rows-half_patch_size) {\n      break;\n    }\n    if (std::isnan(u) || std::isnan(v)) {\n      // TODO(SVO): very rarely this can happen, maybe H is singular? should not be at corner\n      return false;\n    }\n\n    // compute interpolation weights\n    //\u53cc\u7ebf\u6027\u63d2\u503cI(i+u,j+v) = (1-u)(1-v)I(i,j) + (1-u)vI(i,j+1) + u(1-v)I(i+1,j) + uvI(i+1,j+1) \u4ee5\u7b97\u51fa\u8fd9\u4e2a\u7279\u5f81\u70b9\u5728\u53f3\u76ee\u56fe\u50cf\u4e2d\u7684\u50cf\u7d20\u503c\n    float subpix_x = u - u_r;\n    float subpix_y = v - v_r;\n    float wTL = (1.0 - subpix_x) * (1.0 - subpix_y);\n    float wTR = subpix_x * (1.0 - subpix_y);\n    float wBL = (1.0 - subpix_x) * subpix_y;\n    float wBR = subpix_x * subpix_y;\n\n    // loop through search_patch, interpolate\n    uint8_t* it_ref = ref_patch;// \u5de6\u56fe\u50cf patch\u6307\u9488\n    float* it_ref_dx = ref_patch_dx; // \u5de6\u56fe\u50cf patch x\u65b9\u5411\u5bfc\u6570\u6307\u9488\n    float* it_ref_dy = ref_patch_dy;// \u5de6\u56fe\u50cf patch y\u65b9\u5411\u5bfc\u6570\u6307\u9488\n    float new_chi2 = 0.0;\n    Vector3f Jres; Jres.setZero();\n    for (int y = 0; y < patch_size; ++y)\n    {\n      uint8_t* it = static_cast<uint8_t*>(cur_img.data) +\n          (v_r + y - half_patch_size) * cur_step + u_r - half_patch_size;\n      for (int x = 0; x < patch_size; ++x, ++it, ++it_ref, ++it_ref_dx, ++it_ref_dy)\n      {\n          //\u6b8b\u5deer = I(p_cur) - I(p_ref) + m\n        float search_pixel = wTL*it[0] + wTR*it[1] + wBL*it[cur_step] + wBR*it[cur_step+1];//\u53cc\u7ebf\u6027\u63d2\u503c\u5f97\u5230curimg\u4e2d\u7684\u50cf\u7d20\u503c\n        float res = search_pixel - *it_ref + mean_diff;\n        //\u8ba1\u7b97 H * deltax = -Jr\u4e2d\u7684Jres\n        Jres[0] -= res*(*it_ref_dx);\n        Jres[1] -= res*(*it_ref_dy);\n        Jres[2] -= res;\n        new_chi2 += res*res;// \u5361\u65b9\n      }\n    }\n\n    /*\n    if(iter > 0 && new_chi2 > chi2) {\n#if SUBPIX_VERBOSE\n      VLOG(2) << \"error increased.\";\n#endif\n      u -= update[0];\n      v -= update[1];\n      break;\n    }\n    */\n    chi2 = new_chi2;\n\n    //\u66f4\u65b0\u53d8\u91cf\n    //deltax = H.inv * -Jr\n    update = Hinv * Jres;\n    u += update[0];\n    v += update[1];\n    mean_diff += update[2];\n\n#if SUBPIX_VERBOSE\n    VLOG(2) << \"Iter \" << iter << \":\"\n            << \"\\t u=\" << u << \", v=\" << v\n            << \"\\t update = \" << update[0] << \", \" << update[1]\n            << \"\\t chi2 = \" << chi2;\n#endif\n\n    if (update[0] * update[0] + update[1] * update[1] < min_update_squared)\n    {\n        //\u6ee1\u8db3\u6536\u655b\u6761\u4ef6\n#if SUBPIX_VERBOSE\n      VLOG(2) << \"converged.\";\n#endif\n      converged = true;\n      break;\n    }\n  }\n  *cur_px_estimate << u, v;\n  return converged;\n}\n\n// TODO(mingyu): Add the SSE and NEON version\nbool align2D_SSE2(const cv::Mat& cur_img,\n                  uint8_t* ref_patch_with_border,\n                  uint8_t* ref_patch,\n                  const int n_iter,\n                  Vector2f* cur_px_estimate) {\n  LOG(FATAL) << \"align2D_SSE2 is not implemented\";\n  return false;\n}\n#ifdef __ARM_NEON__\nbool align2D_NEON(const cv::Mat& cur_img,\n                  const uint8_t* ref_patch_with_border,\n                  const uint8_t* ref_patch,\n                  const int n_iter,\n                  Vector2f* cur_px_estimate) {\n  bool converged = false;\n\n  // compute derivative of template and prepare inverse compositional\n  /*************************************\n   * memory layout\n   * dx dy 1 dx dy 1 dx dy 1 ...\n   */\n  float __attribute__((__aligned__(16))) ref_patch_dx_dy[patch_area * 3];\n  Matrix3f H = Matrix3f::Zero();\n\n  // compute gradient\n  const int ref_step = patch_size + 2;\n  for (int n = 0; n < patch_size; ++n) {\n    const uint8_t* it = ref_patch_with_border + (n + 1) * ref_step + 1;\n    int16x8_t horizontal_diff, vertical_diff;\n    {\n      int16x8_t raw_data_mid_left = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(it - 1)));\n      int16x8_t raw_data_mid_right = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(it + 1)));\n      int16x8_t raw_data_top = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(it - ref_step)));\n      int16x8_t raw_data_bot = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(it + ref_step)));\n      horizontal_diff = vsubq_s16(raw_data_mid_right, raw_data_mid_left);\n      vertical_diff = vsubq_s16(raw_data_bot, raw_data_top);\n    }\n    float32x4x3_t left4 = {\n      vmulq_n_f32(vcvtq_f32_s32(vmovl_s16(vget_low_s16(horizontal_diff))), 0.5),\n      vmulq_n_f32(vcvtq_f32_s32(vmovl_s16(vget_low_s16(vertical_diff))), 0.5),\n      vdupq_n_f32(1.f)\n    };\n    vst3q_f32(ref_patch_dx_dy + n * 24, left4);\n    float32x4x3_t right4 = {\n      vmulq_n_f32(vcvtq_f32_s32(vmovl_s16(vget_high_s16(horizontal_diff))), 0.5),\n      vmulq_n_f32(vcvtq_f32_s32(vmovl_s16(vget_high_s16(vertical_diff))), 0.5),\n      vdupq_n_f32(1.f)\n    };\n    vst3q_f32(ref_patch_dx_dy + n * 24 + 12, right4);\n  }\n  // compute hessian\n  float* ptr_dxy = ref_patch_dx_dy;\n  for (int cnt = patch_size * patch_size; cnt > 0; --cnt) {\n    Eigen::Map<Vector3f> J(ptr_dxy);\n    H += J * J.transpose();\n    ptr_dxy += 3;\n  }\n\n  Matrix3f Hinv = H.inverse();\n  float mean_diff = 0.f;\n\n  // Compute pixel location in new image:\n  float u = (*cur_px_estimate)(0);\n  float v = (*cur_px_estimate)(1);\n\n  // termination condition\n  const float min_update_squared = 0.03 * 0.03;\n  const int cur_step = cur_img.step.p[0];\n  float chi2 = std::numeric_limits<int>::max();\n  Vector3f update = Vector3f::Zero();\n  for (int iter = 0; iter < n_iter; ++iter) {\n    int u_r = floor(u);\n    int v_r = floor(v);\n    if (u_r < half_patch_size ||\n        v_r < half_patch_size ||\n        u_r >= cur_img.cols - half_patch_size ||\n        v_r >= cur_img.rows - half_patch_size) {\n      break;\n    }\n    if (std::isnan(u) || std::isnan(v)) {\n      // TODO(SVO): very rarely this can happen, maybe H is singular? should not be at corner\n      return false;\n    }\n\n    // compute interpolation weights\n    float subpix_x = u - u_r;\n    float subpix_y = v - v_r;\n\n    int iw00 = cvRound((1.f - subpix_x) * (1.f - subpix_y) * (1 << W_BITS));\n    int iw01 = cvRound(subpix_x * (1.f - subpix_y) * (1 << W_BITS));\n    int iw10 = cvRound((1.f - subpix_x) * subpix_y * (1 << W_BITS));\n    int iw11 = (1 << W_BITS) - iw00 - iw01 - iw10;\n    const int16x4_t viw00 = vdup_n_s16(static_cast<int16_t>(iw00));\n    const int16x4_t viw01 = vdup_n_s16(static_cast<int16_t>(iw01));\n    const int16x4_t viw10 = vdup_n_s16(static_cast<int16_t>(iw10));\n    const int16x4_t viw11 = vdup_n_s16(static_cast<int16_t>(iw11));\n    const int32x4_t shift = vdupq_n_s32(-W_BITS);\n    const float32x4_t vmean_diff = vdupq_n_f32(mean_diff);\n\n    // loop through search_patch, interpolate\n    const uint8_t* it_ref = ref_patch;\n    float new_chi2 = 0.f;\n    Vector3f Jres = Vector3f::Zero();\n    for (int n = 0; n < patch_size; ++n, it_ref += 8) {\n      uint8_t* it = static_cast<uint8_t*>(cur_img.data) +\n          (v_r + n - half_patch_size) * cur_step + u_r - half_patch_size;\n      int16x8_t topleft = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(it)));\n      int16x8_t topright = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(it + 1)));\n      int16x8_t botleft = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(it + cur_step)));\n      int16x8_t botright = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(it + cur_step + 1)));\n\n      int32x4_t left_half1 = vaddq_s32(\n                  vmull_s16(vget_low_s16(topleft), viw00),\n                  vmull_s16(vget_low_s16(topright), viw01));\n      int32x4_t left_half2 = vaddq_s32(\n                  vmull_s16(vget_low_s16(botleft), viw10),\n                  vmull_s16(vget_low_s16(botright), viw11));\n\n      int32x4_t right_half1 = vaddq_s32(\n                  vmull_s16(vget_high_s16(topleft), viw00),\n                  vmull_s16(vget_high_s16(topright), viw01));\n      int32x4_t right_half2 = vaddq_s32(\n                  vmull_s16(vget_high_s16(botleft), viw10),\n                  vmull_s16(vget_high_s16(botright), viw11));\n\n      int16x8_t v_it_ref8 = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(it_ref)));\n      float32x4x2_t search_pixel = {\n        vcvtq_f32_s32(vqrshlq_s32(vaddq_s32(left_half1, left_half2), shift)),\n        vcvtq_f32_s32(vqrshlq_s32(vaddq_s32(right_half1, right_half2), shift))\n      };\n\n      search_pixel.val[0] = vsubq_f32(search_pixel.val[0],\n                           vcvtq_f32_s32(vmovl_s16(vget_low_s16(v_it_ref8))));\n      search_pixel.val[1] = vsubq_f32(search_pixel.val[1],\n                           vcvtq_f32_s32(vmovl_s16(vget_high_s16(v_it_ref8))));\n      search_pixel.val[0] = vaddq_f32(search_pixel.val[0], vmean_diff);\n      search_pixel.val[1] = vaddq_f32(search_pixel.val[1], vmean_diff);\n\n      float32x4x3_t dxy_left = vld3q_f32(ref_patch_dx_dy + n * 24);\n      float32x4x3_t dxy_right = vld3q_f32(ref_patch_dx_dy + n * 24 + 12);\n\n      // dx\n      dxy_left.val[0]  = vmulq_f32(dxy_left.val[0], search_pixel.val[0]);\n      dxy_right.val[0] = vmulq_f32(dxy_right.val[0], search_pixel.val[1]);\n      // dy\n      dxy_left.val[1]  = vmulq_f32(dxy_left.val[1], search_pixel.val[0]);\n      dxy_right.val[1] = vmulq_f32(dxy_right.val[1], search_pixel.val[1]);\n\n      Jres[2] -= (vgetq_lane_f32(search_pixel.val[0], 0) + vgetq_lane_f32(search_pixel.val[0], 1) +\n                  vgetq_lane_f32(search_pixel.val[0], 2) + vgetq_lane_f32(search_pixel.val[0], 3) +\n                  vgetq_lane_f32(search_pixel.val[1], 0) + vgetq_lane_f32(search_pixel.val[1], 1) +\n                  vgetq_lane_f32(search_pixel.val[1], 2) + vgetq_lane_f32(search_pixel.val[1], 3));\n\n      search_pixel.val[0] = vmulq_f32(search_pixel.val[0], search_pixel.val[0]);\n      search_pixel.val[1] = vmulq_f32(search_pixel.val[1], search_pixel.val[1]);\n      dxy_left.val[0] = vaddq_f32(dxy_left.val[0], dxy_right.val[0]);\n      dxy_left.val[1] = vaddq_f32(dxy_left.val[1], dxy_right.val[1]);\n      Jres[0] -= (vgetq_lane_f32(dxy_left.val[0], 0)  + vgetq_lane_f32(dxy_left.val[0], 1) +\n                  vgetq_lane_f32(dxy_left.val[0], 2)  + vgetq_lane_f32(dxy_left.val[0], 3));\n      Jres[1] -= (vgetq_lane_f32(dxy_left.val[1], 0)  + vgetq_lane_f32(dxy_left.val[1], 1) +\n                  vgetq_lane_f32(dxy_left.val[1], 2)  + vgetq_lane_f32(dxy_left.val[1], 3));\n      search_pixel.val[0] = vaddq_f32(search_pixel.val[0], search_pixel.val[1]);\n      new_chi2 += vgetq_lane_f32(search_pixel.val[0], 0) + vgetq_lane_f32(search_pixel.val[0], 1) +\n                  vgetq_lane_f32(search_pixel.val[0], 2) + vgetq_lane_f32(search_pixel.val[0], 3);\n    }\n    /*\n    if(iter > 0 && new_chi2 > chi2) {\n#if SUBPIX_VERBOSE\n      VLOG(2) << \"error increased.\";\n#endif\n      u -= update[0];\n      v -= update[1];\n      break;\n    }\n    */\n    chi2 = new_chi2;\n\n    update = Hinv * Jres;\n    u += update[0];\n    v += update[1];\n    mean_diff += update[2];\n\n#if SUBPIX_VERBOSE\n    VLOG(2) << \"Iter \" << iter << \":\"\n            << \"\\t u=\" << u << \", v=\" << v\n            << \"\\t update = \" << update[0] << \", \" << update[1]\n            << \"\\t chi2 = \" << chi2;\n#endif\n\n    if (update[0] * update[0] + update[1] * update[1] < min_update_squared) {\n#if SUBPIX_VERBOSE\n      VLOG(2) << \"converged.\";\n#endif\n      converged = true;\n      break;\n    }\n  }\n\n  *cur_px_estimate << u, v;\n  return converged;\n}\n#endif\n}  // namespace align\n}  // namespace XP\n", "meta": {"hexsha": "dc2c46d811ffc48449a25e602308c664bf0936a9", "size": 17663, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Frontend/feature_utils_align.cc", "max_stars_repo_name": "wangyuanbiubiubiu/ICE-BA-ros", "max_stars_repo_head_hexsha": "9a3582a2dd1d5ae24115425bdf072864094cfb8e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2020-03-06T10:19:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:06:37.000Z", "max_issues_repo_path": "Frontend/feature_utils_align.cc", "max_issues_repo_name": "wangyuanbiubiubiu/ICE-BA-Annotation", "max_issues_repo_head_hexsha": "9a3582a2dd1d5ae24115425bdf072864094cfb8e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T11:57:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T01:47:22.000Z", "max_forks_repo_path": "Frontend/feature_utils_align.cc", "max_forks_repo_name": "wangyuanbiubiubiu/ICE-BA-Annotation", "max_forks_repo_head_hexsha": "9a3582a2dd1d5ae24115425bdf072864094cfb8e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-06T10:19:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T13:23:22.000Z", "avg_line_length": 35.6828282828, "max_line_length": 111, "alphanum_fraction": 0.6074279567, "num_tokens": 5995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.529665024345744}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::survival::data::algorithm::logit_log.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_LOGIT_LOG_HPP_ER_2009\n#define BOOST_STATISTICS_SURVIVAL_DATA_ALGORITHM_LOGIT_LOG_HPP_ER_2009\n#include <stdexcept>\n#include <iterator>\n#include <boost/format.hpp>\n#include <boost/statistics/survival/data/algorithm/detail/log_shift.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace survival{\nnamespace data{\n\n// Transforms an alternating sequence of (usually mean) failures \n// and event times to their logit and log, with an offset that prevents nan.\n//\n// The rationale for a logit is that 0<= mean failure <=1\ntemplate<typename It,typename ItO,typename T>\nItO logit_log(\n    It b,    // Alternating sequence, f[0],t[0],f[1],t[1],...\n    It e,\n    ItO o,   // Output iterator\n    T t0,\n    T t1\n){\n    static const char* str = \"logit_log : distance(b,e) = %1% mod 2 !=2\";\n\n   if( std::distance(b,e)%2 != 0 ){\n        format f(str); f%distance(b,e);\n        throw std::runtime_error(f.str());\n   }\n   while(b!=e){\n        (*o++) = detail::logit_shift((*b++),t0);\n        (*o++) = detail::log_shift((*b++),t1);\n    }\n    return o;\n}\n\n}// data\n}// survival\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "be4f94ba3df48abd6774ab9556f04ad99eaad93b", "size": 1700, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "survival_data copy/boost/statistics/survival/data/algorithm/logit_log.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/logit_log.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/logit_log.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.0, "max_line_length": 79, "alphanum_fraction": 0.5570588235, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5296650222696458}}
{"text": "/*\nCopyright 2014 Alberto Crivellaro, Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland.\nalberto.crivellaro@epfl.ch\n\nterms of the GNU General Public License as published by the Free Software\nFoundation; either version 2 of the License, or (at your option) any later\nversion.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with\nthis program; if not, write to the Free Software Foundation, Inc., 51 Franklin\nStreet, Fifth Floor, Boston, MA 02110-1301, USA\n */\n\n\n#ifndef ITERATIVEOPTIMIZATION_HPP_\n#define ITERATIVEOPTIMIZATION_HPP_\n\n#include \"Typedefs.hpp\"\n#include \"Utilities.hpp\"\n#include \"Homography.hpp\"\n\n#include <Eigen/LU>\n\n#include <math.h>\n#include <vector>\nusing namespace std;\n\nclass IterativeOptimization{\npublic:\n\tAlignmentResults SSDCalibration(const StructOfArray2di & pixelsOnTemplate, \n\t\tcv::Mat &grayscaleFloatTemplate, cv::Mat &grayscaleFloatImage, vector<float> &parameters, \n\t\tOptimizationParameters & optimizationParameters);\n\tAlignmentResults DescriptorFieldsCalibration(const StructOfArray2di & pixelsOnTemplate,\n\t\tcv::Mat &grayscaleFloatTemplate, cv::Mat &grayscaleFloatImage, vector<float> &paramters,\n\t\tOptimizationParameters & optimizationParameters);\n\tAlignmentResults GradientModuleCalibration(const StructOfArray2di & pixelsOnTemplate, \n\t\tcv::Mat &grayscaleFloatTemplate, cv::Mat &grayscaleFloatImage, vector<float> &paramters,\n\t\tOptimizationParameters & optimizationParameters);\n\n\t//these should be protected but there are tests on them.\n\tvoid ComputeWarpedPixels(const StructOfArray2di & pixelsOnTemplate, const vector<float>&  parameters, StructOfArray2di & warpedPixels);\n    void AssembleSDImages(const vector<float>&  parameters, const cv::Mat &imageDx, const cv::Mat &imageDy, \n\t\tconst StructOfArray2di & warpedPixels, const vector<Eigen::Matrix<float, 2, N_PARAM>, \n\t\tEigen::aligned_allocator<Eigen::Matrix<float, 2, N_PARAM> > > & warpJacobians,  \n\t\tEigen::MatrixXf & sdImages);\nprotected:\n\tvirtual AlignmentResults GaussNewtonMinimization(const StructOfArray2di & pixelsOnTemplate, const vector<cv::Mat> & images, const vector<cv::Mat> & templates, const OptimizationParameters optParam, vector<float> & parameters) = 0;\n\tAlignmentResults PyramidMultiLevelCalibration(const StructOfArray2di & pixelsOnTemplate, vector<cv::Mat> &templateDescriptorFields, vector<cv::Mat> &imageDescriptorFields, vector<float> & parameters, OptimizationParameters & optimizationParameters);\n\tvoid ComputeResiduals(const cv::Mat &image,  vector<float> & templatePixelIntensities, const StructOfArray2di & warpedPixels, vector<float> & errorImage);\n\tfloat ComputeResidualNorm(vector<float> &errorImage);\n\tint CheckConvergenceOptimization(float deltaPoseNorm, int nIter, float residualNormIncrement, OptimizationParameters optParam);\n};\n\n\nclass LucasKanade: public IterativeOptimization{\nprivate:\n\tAlignmentResults GaussNewtonMinimization(const StructOfArray2di & pixelsOnTemplate, const vector<cv::Mat> & images, const vector<cv::Mat> & templates, const OptimizationParameters optParam, vector<float> & parameters);\n};\n\n// TODO: implement this\n//class ICA: public IterativeOptimization{\n//private:\n//\tAlignmentResults GaussNewtonMinimization(const StructOfArray2di & pixelsOnTemplate, const vector<Mat> & images, const vector<Mat> & templates, const OptimizationParameters optParam, vector<float> & parameters);\n//};\n\n#endif /* ITERATIVEOPTIMIZATION_HPP_*/\n", "meta": {"hexsha": "490a5c7deeb632658bf7f3329f9ddbf6224e94dd", "size": 3645, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ThirdParty/DFT/include/mtf/ThirdParty/DFT/IterativeOptimization.hpp", "max_stars_repo_name": "abhineet123/MTF", "max_stars_repo_head_hexsha": "6cb45c88d924fb2659696c3375bd25c683802621", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2016-12-11T00:34:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T23:03:40.000Z", "max_issues_repo_path": "ThirdParty/DFT/include/mtf/ThirdParty/DFT/IterativeOptimization.hpp", "max_issues_repo_name": "siqiyan/MTF", "max_issues_repo_head_hexsha": "9a76388c907755448bb7223420fe74349130f636", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2017-09-04T06:27:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T19:07:23.000Z", "max_forks_repo_path": "ThirdParty/DFT/include/mtf/ThirdParty/DFT/IterativeOptimization.hpp", "max_forks_repo_name": "siqiyan/MTF", "max_forks_repo_head_hexsha": "9a76388c907755448bb7223420fe74349130f636", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2017-02-19T02:12:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-23T03:47:55.000Z", "avg_line_length": 51.338028169, "max_line_length": 250, "alphanum_fraction": 0.8043895748, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5296650080343643}}
{"text": "#include <cstdint>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <vector>\n\n#include <boost/program_options.hpp>\n\n#include \"hash.hpp\"\n#include \"sampler.hpp\"\n\nint main(int argc, char * argv[])\n{\n    boost::program_options::options_description cli(\"Options\");\n    cli.add_options()\n    (\"help,h\", \"help\")\n    (\"epsilon,e\", boost::program_options::value<double>(), \"epsilon value used in l0 sampling, must be in [0, 1], defaults to 1e-8\")\n    (\"probability,p\", boost::program_options::value<double>(), \"success probability for binomial distribution, must be in [0, 1], defaults to 0.5\")\n    (\"range,r\", boost::program_options::value<uint16_t>(), \"data range, must be positive, defaults to the stream size / 100\")\n    (\"size,s\", boost::program_options::value<uint16_t>(), \"stream size, must be positive, defaults to 10000\")\n    (\"trial,t\", boost::program_options::value<uint16_t>(), \"number of trials, must be positive, defaults to 10 * range\");\n\n    boost::program_options::variables_map options;\n    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, cli), options);\n    boost::program_options::notify(options);\n\n    if (options.count(\"help\"))\n    {\n        std::cout << cli << std::endl;\n        return 0;\n    }\n\n    double e = 1e-8;\n    if (options.count(\"epsilon\"))\n    {\n        e = options[\"epsilon\"].as<double>();\n        if (e <= 0 || e >= 1)\n        {\n            std::cerr << \"-e requires a value in range (0, 1)\" << std::endl;\n            return 1;\n        }\n    }\n\n    double p = 0.5;\n    if (options.count(\"probability\"))\n    {\n        p = options[\"probability\"].as<double>();\n        if (p <= 0 || p >= 1)\n        {\n            std::cerr << \"-p requires a value in range (0, 1)\" << std::endl;\n            return 1;\n        }\n    }\n\n    uint16_t s = 10000;\n    if (options.count(\"size\"))\n        s = options[\"size\"].as<uint16_t>();\n\n    uint16_t r = s / 100;\n    if (options.count(\"range\"))\n        r = options[\"range\"].as<uint16_t>();\n\n    uint16_t t = 10 * r;\n    if (options.count(\"trial\"))\n        t = options[\"trial\"].as<uint16_t>();\n\n    // used to record distribution\n    std::vector<uint16_t> vs(r), vlk(r);\n    std::mt19937_64 g { std::random_device()() };\n    uint8_t const k = log2(floor(1 / e));\n    hash::k_universal_family<uint16_t> kuf(k);\n\n    std::uniform_int_distribution<uint16_t> ud(0, r - 1);\n    std::vector<sampler::l0_insertion> l0ks;\n    l0ks.reserve(t);\n    for (uint64_t i = 0; i < t; ++i)\n        l0ks.emplace_back(r, kuf());\n    for (uint64_t i = 0; i < s; ++i)\n    {\n        uint64_t v = ud(g);\n        ++vs[v];\n        for (auto & l0k : l0ks)\n            l0k += v;\n    }\n    for (auto const & l0k : l0ks)\n        ++vlk[l0k];\n    for (uint64_t i = 0; i < r; ++i)\n        std::cout << i << \" \" << vs[i] << \" \" << vlk[i] << std::endl;\n\n    vs = std::vector<uint16_t>(r);\n    vlk = std::vector<uint16_t>(r);\n\n    std::binomial_distribution<uint16_t> ub(r - 1, p);\n    l0ks.clear();\n    for (uint64_t i = 0; i < t; ++i)\n        l0ks.emplace_back(r, kuf());\n    for (uint64_t i = 0; i < s; ++i)\n    {\n        uint64_t v = ub(g);\n        ++vs[v];\n        for (auto & l0k : l0ks)\n            l0k += v;\n    }\n    for (auto const & l0k : l0ks)\n        ++vlk[l0k];\n    for (uint64_t i = 0; i < r; ++i)\n        std::cout << i << \" \" << vs[i] << \" \" << vlk[i] << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "cd0c00025b39e23f071f7aa21d4cc025f9bbd457", "size": 3372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Assignment/B/a_main.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/a_main.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/a_main.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": 30.3783783784, "max_line_length": 147, "alphanum_fraction": 0.550118624, "num_tokens": 1025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5296233055984915}}
{"text": "/*\n * StrainInvariants.cpp\n *\n *  Created on: Dec 23, 2018\n *      Author: lorenzo\n */\n\n#include \"StrainInvariants.h\"\n\n#define QUICKHULL_IMPLEMENTATION\n#include <quickhull/quickhull.h>\n#include <Eigen/Eigenvalues>\n\n#include <iostream>\n#include <sstream>\n\nnamespace ashell {\n\nusing std::endl;\n\nStrainInvariants::StrainInvariants(std::string n_name) :\n\t\tObservable(n_name) {\n\n}\n\nStrainInvariants::~StrainInvariants() {\n\n}\n\nstd::string StrainInvariants::as_string() {\n\treturn _line;\n}\n\nvoid StrainInvariants::_observe(ullint step) {\n\tstd::stringstream ss;\n\n\tstd::vector<qh_vertex_t> vertices(_particles->N());\n\n\tauto poss = _particles->positions();\n\tvec3 com(0., 0., 0.);\n\tfor(uint i = 0; i < _particles->N(); i++) {\n\t\tcom += poss[i];\n\t}\n\tcom /= _particles->N();\n\n\tfor(uint i = 0; i < _particles->N(); i++) {\n\t\tvec3 v = poss[i] - com;\n\t\tvertices[i].x = v[0];\n\t\tvertices[i].y = v[1];\n\t\tvertices[i].z = v[2];\n\t}\n\n\tqh_mesh_t mesh = qh_quickhull3d(vertices.data(), _particles->N());\n\n\tvec3 ch_com(0., 0., 0.);\n\tdouble ch_volume = 0.;\n\tfor(uint i = 0; i < mesh.nindices; i += 3) {\n\t\tvec3 p1(mesh.vertices[mesh.indices[i + 0]].x, mesh.vertices[mesh.indices[i + 0]].y, mesh.vertices[mesh.indices[i + 0]].z);\n\t\tvec3 p2(mesh.vertices[mesh.indices[i + 1]].x, mesh.vertices[mesh.indices[i + 1]].y, mesh.vertices[mesh.indices[i + 1]].z);\n\t\tvec3 p3(mesh.vertices[mesh.indices[i + 2]].x, mesh.vertices[mesh.indices[i + 2]].y, mesh.vertices[mesh.indices[i + 2]].z);\n\n\t\tch_volume += (p1.dot(p2.cross(p3))) / 6.;\n\t\tch_com += (p1 + p2 + p3);\n\t}\n\n\tch_com /= mesh.nindices;\n\n\t// Gyration tensor\n\tmat3 gyration_tensor = mat3::Zero();\n\tfor(int i = 0, j = 0; i < (int)mesh.nindices; i += 3, j++) {\n\t\tvec3 p1(mesh.vertices[mesh.indices[i + 0]].x, mesh.vertices[mesh.indices[i + 0]].y, mesh.vertices[mesh.indices[i + 0]].z);\n\t\tvec3 p2(mesh.vertices[mesh.indices[i + 1]].x, mesh.vertices[mesh.indices[i + 1]].y, mesh.vertices[mesh.indices[i + 1]].z);\n\t\tvec3 p3(mesh.vertices[mesh.indices[i + 2]].x, mesh.vertices[mesh.indices[i + 2]].y, mesh.vertices[mesh.indices[i + 2]].z);\n\t\tvec3 triangle_com = (p1 + p2 + p3) / 3. - ch_com;\n\n\t\tgyration_tensor(0, 0) += SQR(triangle_com[0]);\n\t\tgyration_tensor(0, 1) += triangle_com[0] * triangle_com[1];\n\t\tgyration_tensor(0, 2) += triangle_com[0] * triangle_com[2];\n\n\t\tgyration_tensor(1, 1) += SQR(triangle_com[1]);\n\t\tgyration_tensor(1, 2) += triangle_com[1] * triangle_com[2];\n\n\t\tgyration_tensor(2, 2) += SQR(triangle_com[2]);\n\t}\n\tgyration_tensor(1, 0) = gyration_tensor(0, 1);\n\tgyration_tensor(2, 0) = gyration_tensor(0, 2);\n\tgyration_tensor(2, 1) = gyration_tensor(1, 2);\n\tgyration_tensor /= mesh.nindices / 3.;\n\n\tvec3 eigenvalues = gyration_tensor.eigenvalues().real();\n\n\tdouble eigen_volume = 4 * M_PI * sqrt(3) * sqrt(eigenvalues[0]) * sqrt(eigenvalues[1]) * sqrt(eigenvalues[2]);\n\n\tss << \" \" << ch_volume;\n\tss << \" \" << eigen_volume;\n\tss << \" \" << sqrt(eigenvalues[0]);\n\tss << \" \" << sqrt(eigenvalues[1]);\n\tss << \" \" << sqrt(eigenvalues[2]);\n\n\tqh_free_mesh(mesh);\n\n\t_line = ss.str();\n}\n\n} /* namespace ashell */\n", "meta": {"hexsha": "b46dd8d5769b0616446acb8e605de739724d443f", "size": 3026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/computers/observables/StrainInvariants.cpp", "max_stars_repo_name": "lorenzo-rovigatti/ashell", "max_stars_repo_head_hexsha": "f6c3d4b009ec9229d972a5cc851e90a772f3575b", "max_stars_repo_licenses": ["MIT"], "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/computers/observables/StrainInvariants.cpp", "max_issues_repo_name": "lorenzo-rovigatti/ashell", "max_issues_repo_head_hexsha": "f6c3d4b009ec9229d972a5cc851e90a772f3575b", "max_issues_repo_licenses": ["MIT"], "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/computers/observables/StrainInvariants.cpp", "max_forks_repo_name": "lorenzo-rovigatti/ashell", "max_forks_repo_head_hexsha": "f6c3d4b009ec9229d972a5cc851e90a772f3575b", "max_forks_repo_licenses": ["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.5471698113, "max_line_length": 124, "alphanum_fraction": 0.6457369465, "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5296233002389927}}
{"text": "// Local\n#include \"visualise/ar_example.h\"\n\n// Eigen\n#include <Eigen/Geometry>\n\n// OpenCV\n#include <opencv2/imgproc.hpp>\n#include <opencv2/highgui.hpp>\n\n// Standard Library\n#include <iomanip>\n\n// Define a few BGR-colors for convenience.\nnamespace color\n{\nconst cv::Scalar blue(255, 0, 0);\nconst cv::Scalar green(0, 255, 0);\nconst cv::Scalar red(0, 0, 255);\n}\n\n// Define font parameters.\nnamespace font\n{\nconstexpr auto face = cv::FONT_HERSHEY_PLAIN;\nconstexpr auto scale_small = 1.0;\nconstexpr auto scale_large = 2.0;\nconstexpr auto thickness_bold = 3;\n}\n\nnamespace visualise\n{\n\nARExample::ARExample(double axes_length)\n    : axes_length_{axes_length}\n    , origin_{0, 0, 0, 1}\n    , X_{axes_length_, 0, 0, 1}\n    , Y_{0, axes_length_, 0, 1}\n    , Z_{0, 0, axes_length_, 1}\n{}\n\nvoid ARExample::update(const cv::Mat& image,\n                       const estimators::PoseEstimate& estimate,\n                       const Eigen::Matrix3d& K,\n                       double matching_time_ms,\n                       double pose_est_time_ms) const\n{\n  // Clone image to draw in.\n  cv::Mat ar_img = image.clone();\n\n  // Extract reference to pose.\n  const auto& pose = estimate.pose_W_C;\n\n  if (estimate.isFound())\n  {\n    // Compute projection matrix P.\n    const Eigen::Matrix<double, 3, 4> P = K * pose.inverse().matrix3x4();\n\n    // Project 3D axis into image.\n    Eigen::Vector2d o = (P*origin_).hnormalized();\n    Eigen::Vector2d x = (P*X_).hnormalized();\n    Eigen::Vector2d y = (P*Y_).hnormalized();\n    Eigen::Vector2d z = (P*Z_).hnormalized();\n\n    // Draw axis.\n    cv::line(ar_img, cv::Point2d(o[0], o[1]), cv::Point2d(x[0], x[1]), color::red, 4);\n    cv::line(ar_img, cv::Point2d(o[0], o[1]), cv::Point2d(y[0], y[1]), color::green, 4);\n    cv::line(ar_img, cv::Point2d(o[0], o[1]), cv::Point2d(z[0], z[1]), color::blue, 4);\n\n    // Print processing durations.\n    std::stringstream corr_duration_txt;\n    corr_duration_txt << std::fixed << std::setprecision(0);\n    corr_duration_txt << \"Matching: \" << matching_time_ms << \"ms\";\n    cv::putText(ar_img, corr_duration_txt.str(), {10, 20}, font::face, font::scale_small, color::red);\n\n    std::stringstream pose_duration_txt;\n    pose_duration_txt << std::fixed << std::setprecision(0);\n    pose_duration_txt << \"Pose est.: \" << pose_est_time_ms << \"ms\";\n    cv::putText(ar_img, pose_duration_txt.str(), {10, 40}, font::face, font::scale_small, color::red);\n\n    // Print position.\n    const auto& pos = pose.translation() * 100.0; // In cm.\n    std::stringstream pos_txt;\n    pos_txt << std::fixed << std::setprecision(1);\n    pos_txt << \"Pos (cm): (\" << pos.x() << \", \" << pos.y() << \", \" << pos.z() << \")\";\n    cv::putText(ar_img, pos_txt.str(), {10, 60}, font::face, font::scale_small, color::green);\n\n    // Print attitude.\n    std::stringstream att_txt;\n    Eigen::Vector3d att = attitudeFromR(pose.rotationMatrix());\n    att_txt << std::fixed << std::setprecision(1);\n    att_txt << \"Att (deg): (\" << att.x() << \", \" << att.y() << \", \" << att.z() << \")\";\n    cv::putText(ar_img, att_txt.str(), {10, 80}, font::face, font::scale_small, color::green);\n\n    // Draw keypoints.\n    const auto& inliers = estimate.image_inlier_points;\n    for (const auto& inlier : inliers)\n    {\n      cv::drawMarker(ar_img, inlier, color::green, cv::MARKER_CROSS, 5);\n    }\n\n  }\n  else\n  {\n    cv::putText(ar_img, \"No tracking!\", {20, 80}, font::face, font::scale_large, color::red, font::thickness_bold);\n  }\n\n  cv::imshow(\"AR example\", ar_img);\n}\n\nEigen::Vector3d ARExample::attitudeFromR(const Eigen::Matrix3d& R) const\n{\n  Eigen::Vector3d att;\n\n  if (R(2, 0) < 1)\n  {\n    if (R(2, 0) > -1)\n    {\n      att.y() = std::asin(-R(2, 0));\n      att.x() = std::atan2(R(2, 1) / std::cos(att.y()), R(2, 2) / std::cos(att.y()));\n      att.z() = std::atan2(R(1, 0) / std::cos(att.y()), R(0, 0) / std::cos(att.y()));\n    }\n    else // R(2,0)==-1\n    {\n      att.x() = std::atan2(-R(1, 2), R(1, 1));\n      att.y() = 0.5 * CV_PI;\n      att.z() = 0;\n    }\n  }\n  else // R(2,0) == 1\n  {\n    att.x() = std::atan2(-R(1, 2), R(1, 1));\n    att.y() = -0.5 * CV_PI;\n    att.z() = 0;\n  }\n\n  att.x() *= (180. / CV_PI);\n  att.y() *= (180. / CV_PI);\n  att.z() *= (180. / CV_PI);\n\n  att.x() = std::fmod(360. + att.x(), 360.) - 180.;\n\n  return att;\n}\n\n} // namespace visualise\n", "meta": {"hexsha": "381edfcdc09d0cb25a1947ac221b8c6328956da6", "size": 4290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/visualise/ar_example.cpp", "max_stars_repo_name": "martiege/lab_06", "max_stars_repo_head_hexsha": "2c20adf354327c162a43473ee4c0653f698ac30f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/visualise/ar_example.cpp", "max_issues_repo_name": "martiege/lab_06", "max_issues_repo_head_hexsha": "2c20adf354327c162a43473ee4c0653f698ac30f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/visualise/ar_example.cpp", "max_forks_repo_name": "martiege/lab_06", "max_forks_repo_head_hexsha": "2c20adf354327c162a43473ee4c0653f698ac30f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1836734694, "max_line_length": 115, "alphanum_fraction": 0.5853146853, "num_tokens": 1404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.529623299839681}}
{"text": "#include <stan/math/fwd.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <vector>\n\nTEST(ProbDistributionsMultinomial, fvar_double) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using stan::math::fvar;\n  std::vector<int> ns;\n  ns.push_back(1);\n  ns.push_back(2);\n  ns.push_back(3);\n  Matrix<fvar<double>, Dynamic, 1> theta(3, 1);\n  theta << 0.2, 0.3, 0.5;\n  for (int i = 0; i < 3; i++)\n    theta(i).d_ = 1.0;\n\n  EXPECT_FLOAT_EQ(-2.002481, stan::math::multinomial_log(ns, theta).val_);\n  EXPECT_FLOAT_EQ(17.666666, stan::math::multinomial_log(ns, theta).d_);\n}\n\nTEST(ProbDistributionsMultinomial, fvar_fvar_double) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using stan::math::fvar;\n  std::vector<int> ns;\n  ns.push_back(1);\n  ns.push_back(2);\n  ns.push_back(3);\n  Matrix<fvar<fvar<double> >, Dynamic, 1> theta(3, 1);\n  theta << 0.2, 0.3, 0.5;\n  for (int i = 0; i < 3; i++)\n    theta(i).d_.val_ = 1.0;\n\n  EXPECT_FLOAT_EQ(-2.002481, stan::math::multinomial_log(ns, theta).val_.val_);\n  EXPECT_FLOAT_EQ(17.666666, stan::math::multinomial_log(ns, theta).d_.val_);\n}\n", "meta": {"hexsha": "bb5a975f5762a8b4566c071f0a0408af243d778f", "size": 1148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/fwd/prob/multinomial_test.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": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "test/unit/math/fwd/prob/multinomial_test.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": "test/unit/math/fwd/prob/multinomial_test.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": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 28.7, "max_line_length": 79, "alphanum_fraction": 0.6759581882, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6477982179521102, "lm_q1q2_score": 0.5296232944801826}}
{"text": "#ifndef BAOBZI_TEMPLATE_HPP\n#define BAOBZI_TEMPLATE_HPP\n#define _USE_MATH_DEFINES\n\n#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <mutex>\n#include <numeric>\n#include <queue>\n#include <vector>\n\n#include <msgpack.hpp>\n#define EIGEN_MATRIX_PLUGIN \"baobzi/eigen_matrix_plugin.h\"\n\n#define EIGEN_MAX_ALIGN_BYTES 64\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n#include <baobzi/header.h>\n\n/// Namespace for baobzi\nnamespace baobzi {\nusing index_t = uint32_t;    ///< Type specifying indexing into flattened tree\nusing coeff_data = double *; ///< Array to hold flattened coefficients\n\ntemplate <int DIM, int ORDER, int ISET>\nclass Function;\n\n/// @brief Structure to represent geometric portion of Baobzi nodes\n/// @tparam DIM number of dimensions of box\n/// @tparam ISET Instruction set index (dummy variable to force alignment for different instruction sets)\ntemplate <int DIM, int ISET>\nstruct Box {\n    using VecDimD = Eigen::Vector<double, DIM>; ///< DIM dimensional vector type\n\n    VecDimD center;          ///< Center of box\n    VecDimD inv_half_length; ///< 1.0 / half the dimension of the box\n\n    Box<DIM, ISET>() = default; ///< default constructor for msgpack happiness\n    /// @brief Constructor, just copies x, hl over\n    Box<DIM, ISET>(const VecDimD &x, const VecDimD &hl)\n        : center(x), inv_half_length(VecDimD::Ones().array() / hl.array()) {}\n\n    /// @brief return vector of box half lengths along each dimension\n    inline VecDimD half_length() const { return VecDimD::Ones().array() / inv_half_length.array(); }\n\n    /// @brief MSGPACK serialization magic\n    MSGPACK_DEFINE(center, inv_half_length);\n};\n\n/// @brief Return an estimate of the error for a given set of coefficients\n/// @param[in] coeffs one or two dimensional Vector/Matrix of coefficients\n/// @returns estimation of error given those coefficients\ninline double standard_error(const Eigen::Ref<Eigen::MatrixXd> &coeffs) {\n    double maxcoeff = 0.0;\n    double scaling_factor = 1.0;\n    if (coeffs.cols() == 1) {\n        int n = coeffs.size();\n        for (auto i = n - 2; i < n; ++i)\n            maxcoeff = std::max(std::abs(coeffs(i, 0)), maxcoeff);\n        scaling_factor = std::max(scaling_factor, std::abs(coeffs(0, 0)));\n    } else {\n        int n = coeffs.rows();\n        for (auto i = 0; i < n; ++i)\n            maxcoeff = std::max(std::abs(coeffs(i, n - i - 1)), maxcoeff);\n\n        scaling_factor = std::max(scaling_factor, std::abs(coeffs(n - 1, 0)));\n        scaling_factor = std::max(scaling_factor, std::abs(coeffs(0, n - 1)));\n    }\n\n    return maxcoeff / scaling_factor;\n}\n\n/// @brief Evaluate chebyshev polynomial given a box and a point inside that box\n/// @tparam DIM dim of chebyshev polynomial to evaluate\n/// @tparam ORDER order of chebyshev polynomial to evaluate\n/// @tparam ISET Instruction set index (dummy variable to force alignment for different instruction sets)\n/// @param[in] x position of point to evaluate (pre-normalized on interval from -1:1)\n/// @param[in] coeffs_raw flat vector of coefficients\n/// @returns value of interpolating function at x\ntemplate <int DIM, int ORDER, int ISET>\ninline double cheb_eval(const Eigen::Vector<double, DIM> &x, const double *coeffs_raw);\n\ntemplate <int ORDER, int ISET>\ninline double cheb_eval(const Eigen::Vector<double, 1> &x, const double *c) {\n    // note (RB): uses clenshaw's method to avoid direct calculation of recurrence relation of\n    // T_i, where res = \\Sum_i T_i c_i\n    const double x2 = 2 * x[0];\n\n    double c0 = c[0];\n    double c1 = c[1];\n    for (int i = 2; i < ORDER; ++i) {\n        double tmp = c1;\n        c1 = c[i] - c0;\n        c0 = tmp + c0 * x2;\n    }\n\n    return c1 + c0 * x[0];\n}\n\ntemplate <int ORDER, int ISET>\ninline double cheb_eval(const Eigen::Vector2d &x, const double *coeffs_raw) {\n    // note (RB): There is code to do this with clenshaw's method (twice), but it doesn't seem\n    // faster (isolated tests shows it's 3x faster, but that doesn't bear fruit in production\n    // and this is, imho, clearer)\n    Eigen::Matrix<double, 2, ORDER> Tns;\n    Tns.col(0).setOnes();\n    Tns.col(1) = x;\n    for (int i = 2; i < ORDER; ++i)\n        Tns.col(i) = 2 * x.array() * Tns.col(i - 1).array() - Tns.col(i - 2).array();\n\n    Eigen::Map<const Eigen::Matrix<double, ORDER, ORDER>> coeffs(coeffs_raw);\n\n    return Tns.row(0).transpose().dot(coeffs * Tns.row(1).transpose());\n}\n\ntemplate <int ORDER, int ISET>\ninline double cheb_eval(const Eigen::Vector3d &x, const double *coeffs_raw) {\n    Eigen::Vector<double, ORDER> Tn[3];\n    Tn[0][0] = Tn[1][0] = Tn[2][0] = 1.0;\n    for (int i = 0; i < 3; ++i) {\n        Tn[i][1] = x[i];\n        for (int j = 2; j < ORDER; ++j)\n            Tn[i][j] = 2 * x[i] * Tn[i][j - 1] - Tn[i][j - 2];\n    }\n\n    double res = 0.0;\n    using map_t = Eigen::Map<const Eigen::Matrix<double, ORDER, ORDER>>;\n    for (int i = 0; i < ORDER; ++i)\n        res += Tn[0][i] * Tn[1].dot(map_t(coeffs_raw + i * ORDER * ORDER) * Tn[2]);\n    return res;\n}\n\n/// @brief Node in baobzi::FunctionTree. If leaf, contains evaluation data, otherwise children\n/// @tparam DIM dimension of function\n/// @tparam ORDER order of evaluation polynomial\n/// @tparam ISET instruction set index (dummy variable to force alignment for different instruction sets)\ntemplate <int DIM, int ORDER, int ISET>\nclass Node {\n  public:\n    using VecDimD = Eigen::Vector<double, DIM>;     ///< D dimensional vector type\n    using VecOrderD = Eigen::Vector<double, ORDER>; ///< ORDER dimensional vector type\n    using Func = Function<DIM, ORDER, ISET>;        ///< Type of boabzi function this belongs to\n\n    Box<DIM, ISET> box_;                                          ///< Geometric position/size of this node\n    uint64_t coeff_offset = std::numeric_limits<uint64_t>::max(); ///< Flattened chebyshev coeffs\n    uint32_t first_child_idx = -1; ///< First child's index in a flattened list of all nodes\n\n    Node<DIM, ORDER, ISET>() = default; ///< Default constructor for msgpack happiness\n\n    /// @brief Construct node from box (without fitting)\n    /// @param [in] box box this node represents\n    Node<DIM, ORDER, ISET>(const Box<DIM, ISET> &box) : box_(box) {}\n\n    /// @brief check if node is leaf\n    /// @return true if leaf, false otherwise\n    inline bool is_leaf() const { return coeff_offset != std::numeric_limits<uint64_t>::max(); }\n\n    /// @brief Fit node to a given tolerance. If fit succeeds, set leaf and coeffs, otherwise ... don't\n    ///\n    /// Modifies: Node::leaf_, Node::coeffs_\n    /// @param[in] input parameters for fit (function, tol, etc)\n    /// @returns true if fit successful, false if not good enough\n    std::vector<double> fit(const baobzi_input_t *input) {\n        VecDimD half_length = box_.half_length();\n        if constexpr (DIM == 1) {\n            Eigen::Vector<double, ORDER> F;\n            VecOrderD xvec = Func::get_cheb_nodes(box_.center[0] - half_length[0], box_.center[0] + half_length[0]);\n\n            for (int i = 0; i < ORDER; ++i)\n                F(i) = input->func(&xvec[i], input->data);\n\n            Eigen::Vector<double, ORDER> coeffs = Func::VLU_.solve(F);\n\n            if (standard_error(coeffs) > input->tol)\n                return std::vector<double>();\n\n            std::vector<double> coeffs_stl(coeffs.size());\n            for (int i = 0; i < coeffs.size(); ++i)\n                coeffs_stl[i] = coeffs(ORDER - i - 1);\n\n            coeff_offset = 0;\n            return coeffs_stl;\n        }\n        if constexpr (DIM == 2) {\n            Eigen::Matrix<double, ORDER, ORDER> F;\n            VecOrderD xvec = Func::get_cheb_nodes(box_.center[0] - half_length[0], box_.center[0] + half_length[0]);\n            VecOrderD yvec = Func::get_cheb_nodes(box_.center[1] - half_length[1], box_.center[1] + half_length[1]);\n\n            for (int i = 0; i < ORDER; ++i) {\n                for (int j = 0; j < ORDER; ++j) {\n                    double x[2] = {xvec[i], yvec[j]};\n                    F(i, j) = input->func(x, input->data);\n                }\n            }\n\n            Eigen::Matrix<double, ORDER, ORDER> coeffs = Func::VLU_.solve(F);\n            coeffs = Func::VLU_.solve(coeffs.transpose()).transpose();\n\n            if (standard_error(coeffs) > input->tol)\n                return std::vector<double>();\n\n            std::vector<double> coeffs_stl(coeffs.size());\n            for (int i = 0; i < coeffs.size(); ++i)\n                coeffs_stl[i] = coeffs(i);\n\n            coeff_offset = 0;\n            return coeffs_stl;\n        }\n        if constexpr (DIM == 3) {\n            Eigen::Tensor<double, 3> F(ORDER, ORDER, ORDER);\n\n            VecOrderD xvec = Func::get_cheb_nodes(box_.center[0] - half_length[0], box_.center[0] + half_length[0]);\n            VecOrderD yvec = Func::get_cheb_nodes(box_.center[1] - half_length[1], box_.center[1] + half_length[1]);\n            VecOrderD zvec = Func::get_cheb_nodes(box_.center[2] - half_length[2], box_.center[2] + half_length[2]);\n\n            for (int i = 0; i < ORDER; ++i) {\n                for (int j = 0; j < ORDER; ++j) {\n                    for (int k = 0; k < ORDER; ++k) {\n                        double x[3] = {xvec[i], yvec[j], zvec[k]};\n                        F(i, j, k) = input->func(x, input->data);\n                    }\n                }\n            }\n\n            std::vector<double> coeffs(ORDER * ORDER * ORDER);\n            Eigen::Tensor<double, 3> coeffs_tensor(ORDER, ORDER, ORDER);\n            using matrix_t = Eigen::Matrix<double, ORDER, ORDER>;\n            using map_t = Eigen::Map<matrix_t>;\n            using tensor_t = Eigen::Tensor<double, 2>;\n            for (int block = 0; block < ORDER; ++block) {\n                tensor_t F_block_tensor = F.chip(block, 2);\n                map_t F_block(F_block_tensor.data());\n\n                matrix_t coeffs_tmp = Func::VLU_.solve(F_block);\n                coeffs_tmp = Func::VLU_.solve(coeffs_tmp.transpose()).transpose();\n                coeffs_tensor.chip(block, 2) = Eigen::TensorMap<tensor_t>(coeffs_tmp.data(), ORDER, ORDER);\n            }\n            for (int block = 0; block < ORDER; ++block) {\n                Eigen::Tensor<double, 2> coeffs_tmp = coeffs_tensor.chip(block, 0);\n                map_t coeffs_ysolve(coeffs_tmp.data());\n                map_t(coeffs.data() + block * ORDER * ORDER) = Func::VLU_.solve(coeffs_ysolve.transpose()).transpose();\n            }\n\n            // Hack to use local coefficient array rather than global one\n            coeff_offset = 0;\n            for (int i = 0; i < ORDER; ++i) {\n                for (int j = 0; j < ORDER; ++j) {\n                    for (int k = 0; k < ORDER; ++k) {\n                        VecDimD point =\n                            (box_.center - half_length).array() +\n                            2.0 * VecDimD{(double)i, (double)j, (double)k}.array() * half_length.array() / ORDER;\n\n                        const double test_val = eval(point, coeffs.data());\n                        const double actual_val = input->func(point.data(), input->data);\n                        const double rel_error = std::abs((actual_val - test_val) / actual_val);\n\n                        if (fabs(actual_val) > 1E-16 && rel_error > input->tol) {\n                            coeff_offset = std::numeric_limits<uint64_t>::max();\n                            return std::vector<double>();\n                        }\n                    }\n                }\n            }\n\n            return coeffs;\n        }\n    }\n\n    /// @brief eval node at point x\n    /// @param[in] x point to evaluate at\n    /// @param[in] coeffs flat/global coefficient array\n    /// @returns function approximation at x\n    inline double eval(const VecDimD &x, const double *coeffs) const {\n        const VecDimD xinterp = (x - box_.center).array() * box_.inv_half_length.array();\n        return cheb_eval<ORDER, ISET>(xinterp, coeffs + coeff_offset);\n    }\n\n    /// @brief Calculate memory usage of self (including unused space from vector allocation)\n    /// @returns size in bytes of object instance\n    inline std::size_t memory_usage() const { return sizeof(*this); }\n\n    /// @brief MSGPACK serialization magic\n    MSGPACK_DEFINE(box_, first_child_idx, coeff_offset);\n};\n\n/// @brief Represent a function in some domain as a tree of chebyshev nodes\n/// @tparam DIM dimension of function\n/// @tparam ORDER order of evaluation polynomial\n/// @tparam ISET instruction set index (dummy variable to force alignment for different instruction sets)\ntemplate <int DIM, int ORDER, int ISET>\nstruct FunctionTree {\n    static constexpr int NChild = 1 << DIM; ///< Number of children each node potentially has (2^D)\n    static constexpr int Dim = DIM;         ///< Dimension of tree\n    static constexpr int Order = ORDER;     ///< Order of tree\n\n    using node_t = Node<DIM, ORDER, ISET>;      ///< DIM,ORDER node type\n    using box_t = Box<DIM, ISET>;               ///< DIM box type\n    using VecDimD = Eigen::Vector<double, DIM>; ///< D dimensional vector type\n\n    std::vector<node_t> nodes_; ///< Flat list of all nodes in Tree (leaf or otherwise)\n    int max_depth_;             ///< Maximum depth of tree\n\n    /// @brief Construct tree\n    /// @param[in] input parameters for fit (function, tol, etc)\n    /// @param[in] coeffs flat/global coefficient vector\n    /// @param[in] box box that this tree lives in\n    FunctionTree<DIM, ORDER, ISET>(const baobzi_input_t *input, const Box<DIM, ISET> &box,\n                                   std::vector<double> &coeffs) {\n        std::queue<Box<DIM, ISET>> q;\n        VecDimD half_width = box.half_length() * 0.5;\n        q.push(box);\n\n        index_t curr_child_idx = 1;\n        max_depth_ = 0;\n        while (!q.empty()) {\n            int n_next = q.size();\n            int node_index = nodes_.size();\n            for (int i = 0; i < n_next; ++i) {\n                box_t box = q.front();\n                q.pop();\n\n                nodes_.push_back(node_t(box));\n\n                auto &node = nodes_[i + node_index];\n                std::vector new_coeffs = node.fit(input);\n\n                if (node.is_leaf()) {\n                    node.coeff_offset = coeffs.size();\n                    coeffs.insert(std::end(coeffs), std::begin(new_coeffs), std::end(new_coeffs));\n                } else if (!node.is_leaf()) {\n                    node.first_child_idx = curr_child_idx;\n                    curr_child_idx += NChild;\n\n                    VecDimD &center = node.box_.center;\n                    for (index_t child = 0; child < NChild; ++child) {\n                        VecDimD offset;\n\n                        // Extract sign of each offset component from the bits of child\n                        // Basically: permute all possible offsets\n                        for (int j = 0; j < DIM; ++j) {\n                            double signed_hw[2] = {-half_width[j], half_width[j]};\n                            offset[j] = signed_hw[(child >> j) & 1];\n                        }\n\n                        q.push(Box<DIM, ISET>(center + offset, half_width));\n                    }\n                }\n            }\n\n            if (!q.empty())\n                max_depth_++;\n\n            half_width *= 0.5;\n        }\n    }\n\n    FunctionTree<DIM, ORDER, ISET>() = default; ///< Default constructor for msgpack happiness\n\n    /// @brief Find leaf node containing a point via standard pointer traversal\n    /// @param[in] x point that the node will contain\n    /// @return leaf node containing point x\n    inline const node_t &find_node_traverse(const VecDimD &x) const {\n        auto *node = &nodes_[0];\n        auto *next_node = &nodes_[node->first_child_idx]; // attempt to force preload of potential next node\n        while (!node->is_leaf()) {\n            index_t child_idx = 0;\n            for (int i = 0; i < DIM; ++i)\n                child_idx = child_idx | ((x[i] > node->box_.center[i]) << i);\n\n            node = next_node + child_idx;\n            next_node = &nodes_[node->first_child_idx];\n        }\n\n        return *node;\n    }\n\n    /// @brief Get index of node at point x (relative to local nodes_ array)\n    /// @param[in] x [DIM] point to lookup\n    /// @returns index of node in nodes_ array containing x\n    inline std::size_t get_node_index(const VecDimD &x) const {\n        index_t curr_index = 0;\n        while (!nodes_[curr_index].is_leaf()) {\n            index_t child_idx = 0;\n            for (int i = 0; i < DIM; ++i)\n                child_idx = child_idx | ((x[i] > nodes_[curr_index].box_.center[i]) << i);\n\n            curr_index = nodes_[curr_index].first_child_idx + child_idx;\n        }\n\n        return curr_index;\n    }\n\n    /// @brief Calculate total number of nodes in instance\n    /// @return number of nodes in instance\n    inline std::size_t size() const { return nodes_.size(); }\n\n    /// @brief Calculate lowest depth of any node in instance (relative subtree node)\n    /// @return lowest depth of all contained nodes\n    inline int max_depth() const { return max_depth_; }\n\n    /// @brief Calculate memory usage of self (including all contained nodes)\n    /// @returns size in bytes of object instance\n    inline std::size_t memory_usage() const {\n        std::size_t memory_usage = sizeof(*this);\n        for (const auto &node : nodes_)\n            memory_usage += node.memory_usage();\n        return memory_usage;\n    }\n\n    /// @brief eval function approximation at point\n    /// @param[in] x point to evaluate function at\n    /// @param[in] coeffs flat/global coefficient array\n    /// @returns function approximation at point x\n    inline double eval(const VecDimD &x, const double *coeffs) const { return find_node_traverse(x).eval(x, coeffs); }\n\n    /// @brief msgpack serialization magic\n    MSGPACK_DEFINE(nodes_);\n};\n\n/// @brief Represents a function in some domain as a grid of baobzi::FunctionTree objects\n/// @tparam DIM dimension of function\n/// @tparam ORDER order of evaluation polynomial\n/// @tparam ISET instruction set index (dummy variable to force alignment for different instruction sets)\ntemplate <int DIM, int ORDER, int ISET = 0>\nclass Function {\n  public:\n    using VecDimD = Eigen::Vector<double, DIM>;            ///< DIM dimensional vector type\n    using VecOrderD = Eigen::Vector<double, ORDER>;        ///< Order dimensional vector type\n    using VanderMat = Eigen::Matrix<double, ORDER, ORDER>; ///< VanderMonde Matrix type\n    using node_t = Node<DIM, ORDER, ISET>;                 ///< DIM,ORDER Node type (duh)\n    using box_t = Box<DIM, ISET>;                          ///< DIM dimensional box type\n\n    static constexpr int NChild = 1 << DIM; ///< Number of children each node potentially has (2^D)\n    static constexpr int Dim = DIM;         ///< Input dimension of function\n    static constexpr int Order = ORDER;     ///< Order of polynomial representation\n    static constexpr int ISet = ISET;       ///< Instruction set (dummy param)\n\n    static std::mutex statics_mutex;            ///< mutex for locking vandermonde/chebyshev initialization\n    static VecOrderD cosarray_;                 ///< Cached array of cosine values at chebyshev nodes\n    static Eigen::PartialPivLU<VanderMat> VLU_; ///< Cached LU decomposition of Vandermonde matrix\n\n    box_t box_;          ///< box representing the domain of our function\n    double tol_;         ///< Desired relative tolerance of our approximation\n    VecDimD lower_left_; ///< Bottom 'corner' of our domain\n\n    std::vector<FunctionTree<DIM, ORDER, ISET>> subtrees_; ///< Grid of FunctionTree objects that do the work\n    Eigen::Vector<int, DIM> n_subtrees_;                   ///< Number of subtrees in each linear dimension of our space\n    std::vector<int> subtree_node_offsets_; ///< n_subtrees array of offsets for where in the global array of node\n                                            ///< pointers the global node pointer array starts\n    std::vector<node_t *> node_pointers_;   ///< Vector of pointers to every node from every subtree\n    VecDimD inv_bin_size_;                  ///< Inverse linear dimensions of the bins that our subtrees live\n\n    std::vector<double> coeffs_; ///< Flat vector of all chebyshev coefficients from all leaf nodes\n\n    bool split_multi_eval_ = true; ///< Split node-search and evaluation when evaluating multiple points\n\n    /// Structure containing info about self creation :D\n    struct {\n        uint16_t base_depth = 0;   ///< depth of subtrees\n        uint64_t n_evals_root = 0; ///< number of function evals before subtree calls\n        uint32_t t_elapsed = 0;    ///< time in milliseconds to create object\n    } stats_;\n\n    /// @brief Calculate memory_usage of this object in bytes\n    /// @returns Memory usage of baobzi object in bytes\n    std::size_t memory_usage() const {\n        std::size_t mem = sizeof(*this);\n        mem += subtree_node_offsets_.capacity() * sizeof(subtree_node_offsets_[0]);\n        mem += node_pointers_.capacity() * sizeof(node_pointers_[0]);\n        mem += coeffs_.capacity() * sizeof(double);\n        for (const auto &subtree : subtrees_)\n            mem += subtree.memory_usage();\n        return mem;\n    }\n\n    /// @brief Calculate and print various information about object instance to stdout\n    void print_stats() const {\n        std::size_t n_nodes = 0;\n        std::size_t n_leaves = 0;\n        std::size_t n_subtrees = subtrees_.size();\n        int max_depth = 0;\n        std::size_t mem = memory_usage();\n        for (const auto &subtree : subtrees_) {\n            n_nodes += subtree.size();\n            max_depth = std::max(max_depth, subtree.max_depth());\n            for (const auto &node : subtree.nodes_)\n                n_leaves += node.is_leaf();\n        }\n\n        std::cout << \"Baobzi tree represented by \" << n_nodes << \" nodes, of which \" << n_leaves << \" are leaves\\n\";\n        std::cout << \"Nodes are distributed across \" << n_subtrees << \" subtrees at an initial depth of \"\n                  << stats_.base_depth << \" with a maximum subtree depth of \" << max_depth << \"\\n\";\n        std::cout << \"Total function evaluations required for fit: \"\n                  << n_nodes * (int)std::pow(ORDER, DIM) + stats_.n_evals_root << std::endl;\n        std::cout << \"Total time to create tree: \" << stats_.t_elapsed << \" milliseconds\\n\";\n        std::cout << \"Approximate memory usage of tree: \" << (double)mem / (1024 * 1024) << \" MiB\" << std::endl;\n    }\n\n    /// @brief calculate vandermonde matrix\n    /// @return Vandermonde matrix for chebyshev polynomials with order=ORDER\n    static VanderMat calc_vandermonde() {\n        VanderMat V;\n\n        for (int j = 0; j < ORDER; ++j) {\n            V(0, j) = 1;\n            V(1, j) = cosarray_(j);\n        }\n\n        for (int i = 2; i < ORDER; ++i) {\n            for (int j = 0; j < ORDER; ++j) {\n                V(i, j) = double(2) * V(i - 1, j) * cosarray_(j) - V(i - 2, j);\n            }\n        }\n\n        return V.transpose();\n    }\n\n    /// @brief calculate chebyshev nodes on bounds [lb, ub]\n    /// @param[in] lb lower bound\n    /// @param[in] ub upper bound\n    /// @returns vector of chebyshev nodes scaled within [lb, ub]\n    static inline VecOrderD get_cheb_nodes(double lb, double ub) {\n        return 0.5 * ((lb + ub) + (ub - lb) * cosarray_.array());\n    }\n\n    /// @brief initialize static class variables\n    ///\n    /// Modifies baobzi::Function::cosarray_, baobzi::Function::VLU_\n    static void init_statics() {\n        static bool is_initialized = false;\n        std::lock_guard<std::mutex> lock(statics_mutex);\n        if (is_initialized)\n            return;\n\n        for (int i = 0; i < ORDER; ++i)\n            cosarray_[ORDER - i - 1] = cos(M_PI * (i + 0.5) / ORDER);\n        VLU_ = Eigen::PartialPivLU<VanderMat>(calc_vandermonde());\n        is_initialized = true;\n    }\n\n    /// @brief Construct our Function object (fits recursively, can be slow)\n    /// @param[in] input parameters for fit (function, tol, etc)\n    /// @param[in] xp [dim] center of function domain\n    /// @param[in] lp [dim] half length of function domain\n    Function<DIM, ORDER, ISET>(const baobzi_input_t *input, const double *xp, const double *lp)\n        : box_(VecDimD(xp), VecDimD(lp)), tol_(input->tol), split_multi_eval_(input->split_multi_eval) {\n        auto t_start = std::chrono::steady_clock::now();\n        init_statics();\n\n        VecDimD l(lp);\n        VecDimD x(xp);\n        std::queue<box_t> q;\n        std::queue<box_t> maybe_q;\n\n        for (int i = 0; i < DIM; ++i)\n            n_subtrees_[i] = l[i] / l.minCoeff();\n\n        q.push(box_t(x, l));\n\n        // Half-width of next children\n        VecDimD half_width = l * 0.5;\n\n        // Breadth first search. Step through each level of the tree and test fit all of the nodes\n        // We exit when a level isn't completely filled with parent nodes (rather than leaves)\n        // This way we can always avoid redundant traversals by jumping straight to a root node of a subtree\n        while (!q.empty()) {\n            int n_next = q.size();\n\n            auto add_node_children_to_queue = [](std::queue<box_t> &theq, const VecDimD &center,\n                                                 const VecDimD &half_width) {\n                for (unsigned child = 0; child < NChild; ++child) {\n                    VecDimD offset;\n\n                    // Extract sign of each offset component from the bits of child\n                    // Basically: permute all possible offsets\n                    for (int j = 0; j < DIM; ++j) {\n                        double signed_hw[2] = {-half_width[j], half_width[j]};\n                        offset[j] = signed_hw[(child >> j) & 1];\n                    }\n\n                    theq.push(box_t(center + offset, half_width));\n                }\n            };\n\n            std::vector<node_t> nodes;\n            double leaf_fraction = 0.0;\n            for (int i = 0; i < n_next; ++i) {\n                box_t box = q.front();\n                q.pop();\n\n                nodes.emplace_back(node_t(box));\n                auto &node = nodes.back();\n                node.fit(input);\n\n                if (!node.is_leaf()) {\n                    add_node_children_to_queue(q, node.box_.center, half_width);\n                } else {\n                    leaf_fraction += 1.0;\n                    add_node_children_to_queue(maybe_q, node.box_.center, half_width);\n                }\n            }\n            stats_.n_evals_root += nodes.size() * std::pow(ORDER, DIM);\n\n            leaf_fraction /= nodes.size();\n            if (leaf_fraction < input->minimum_leaf_fraction) {\n                while (!maybe_q.empty()) {\n                    box_t box = maybe_q.front();\n                    maybe_q.pop();\n                    q.push(box);\n                }\n            }\n\n            half_width *= 0.5;\n            if ((1 << (DIM * (stats_.base_depth + 1))) == q.size()) {\n                n_subtrees_ *= 2;\n                stats_.base_depth++;\n            } else\n                break;\n        }\n\n        VecDimD bin_size;\n        VecDimD half_length = box_.half_length();\n        for (int j = 0; j < DIM; ++j) {\n            bin_size[j] = 2.0 * half_length[j] / n_subtrees_[j];\n            inv_bin_size_[j] = 0.5 * n_subtrees_[j] / half_length[j];\n        }\n        lower_left_ = box_.center - half_length;\n\n        subtrees_.reserve(n_subtrees_.prod());\n        for (int i_bin = 0; i_bin < n_subtrees_.prod(); ++i_bin) {\n            Eigen::Vector<int, DIM> bins = get_bins(i_bin);\n\n            VecDimD parent_center =\n                (bins.template cast<double>().array() + 0.5) * bin_size.array() + lower_left_.array();\n\n            Box<DIM, ISET> root_box = {parent_center, 0.5 * bin_size};\n            subtrees_.push_back(FunctionTree<DIM, ORDER, ISET>(input, root_box, coeffs_));\n        }\n\n        auto t_end = std::chrono::steady_clock::now();\n        auto t_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start);\n        stats_.t_elapsed = t_elapsed.count();\n        build_cache();\n    }\n\n    /// @brief Build any intermediate state necessary for computation\n    void build_cache() {\n        subtree_node_offsets_.resize(n_subtrees_.prod());\n        subtree_node_offsets_[0] = 0;\n        for (int i = 1; i < subtree_node_offsets_.size(); ++i)\n            subtree_node_offsets_[i] = subtree_node_offsets_[i - 1] + subtrees_[i - 1].size();\n\n        auto n_nodes_tot = std::accumulate(subtrees_.begin(), subtrees_.end(), (std::size_t)0,\n                                           [](size_t prior, auto &subtree) { return prior + subtree.size(); });\n\n        node_pointers_.resize(n_nodes_tot);\n\n        int i = 0;\n        for (auto &subtree : subtrees_)\n            for (node_t &node : subtree.nodes_)\n                node_pointers_[i++] = &node;\n    }\n\n    /// @brief default constructor for msgpack magic\n    Function<DIM, ORDER, ISET>() { init_statics(); };\n\n    /// @brief convert linear bin index to [dim] bin vector\n    /// @param[in] i_bin linear index\n    /// @returns [dim] bin vector\n    inline Eigen::Vector<int, DIM> get_bins(const int i_bin) const {\n        if constexpr (DIM == 1)\n            return Eigen::Vector<int, DIM>{i_bin};\n        else if constexpr (DIM == 2)\n            return Eigen::Vector<int, DIM>{i_bin % n_subtrees_[0], i_bin / n_subtrees_[0]};\n        else if constexpr (DIM == 3)\n            return Eigen::Vector<int, DIM>{i_bin % n_subtrees_[0], (i_bin / n_subtrees_[0]) % n_subtrees_[1],\n                                           i_bin / (n_subtrees_[0] * n_subtrees_[1])};\n    }\n\n    /// @brief find linear index of bin at a point\n    /// @param[in] x [1] position to find bin\n    /// @returns linear index of bin that x lives in\n    inline int get_linear_bin(const Eigen::Vector<double, 1> &x) const {\n        const double x_bin = x[0] - lower_left_[0];\n        return x_bin * inv_bin_size_[0];\n    }\n\n    /// @brief find linear index of bin at a point\n    /// @param[in] x [2] position to find bin\n    /// @returns linear index of bin that x lives in\n    inline int get_linear_bin(const Eigen::Vector2d &x) const {\n        const VecDimD x_bin = x - lower_left_;\n        const Eigen::Vector<int, DIM> bin = (x_bin.array() * inv_bin_size_.array()).template cast<int>();\n        return bin[0] + n_subtrees_[0] * bin[1];\n    }\n\n    /// @brief find linear index of bin at a point\n    /// @param[in] x [3] position to find bin\n    /// @returns linear index of bin that x lives in\n    inline int get_linear_bin(const Eigen::Vector3d &x) const {\n        const VecDimD x_bin = x - lower_left_;\n        const Eigen::Vector<int, DIM> bin = (x_bin.array() * inv_bin_size_.array()).template cast<int>();\n        return bin[0] + n_subtrees_[0] * bin[1] + n_subtrees_[0] * n_subtrees_[1] * bin[2];\n    }\n\n    /// @brief get constant reference to leaf node that contains a point\n    /// @param[in] x point of interest\n    /// @returns constant reference to leaf node that contains x\n    inline const node_t &find_node(const VecDimD &x) const {\n        return subtrees_[get_linear_bin(x)].find_node_traverse(x);\n    }\n\n    /// @brief eval function approximation at point\n    /// @param[in] x point to evaluate function at\n    /// @returns function approximation at point x\n    inline double eval(const VecDimD &x) const { return find_node(x).eval(x, coeffs_.data()); }\n\n    /// @brief eval function approximation at point\n    /// @param[in] xp [DIM] point to evaluate function at\n    /// @returns function approximation at point xp\n    inline double eval(const double *xp) const { return eval(VecDimD(xp)); }\n\n    /// @brief get index of node (across all subnodes)\n    /// @param[in] x [DIM] point to find the node of\n    /// @returns index in global node array\n    inline std::size_t get_global_node_index(const VecDimD &x) const {\n        int i_sub = get_linear_bin(x);\n        return subtree_node_offsets_[i_sub] + subtrees_[i_sub].get_node_index(x);\n    }\n\n    /// @brief eval function approximation at n_trg points\n    /// @param[in] xp [DIM * n_trg] array of points to evaluate function at\n    /// @param[out] res [n_trg] array of results\n    /// @param[in] n_trg number of points to evaluate\n    inline void eval(const double *xp, double *res, int n_trg) const {\n        if (split_multi_eval_) {\n            std::vector<std::pair<node_t *, VecDimD>> node_map(n_trg);\n            for (int i = 0; i < n_trg; ++i) {\n                VecDimD xi = VecDimD(xp + DIM * i);\n                node_map[i] = std::make_pair(node_pointers_[get_global_node_index(xi)], xi);\n            }\n\n            for (int i_trg = 0; i_trg < n_trg; i_trg++)\n                res[i_trg] = node_map[i_trg].first->eval(node_map[i_trg].second, coeffs_.data());\n        } else\n            for (int i_trg = 0; i_trg < n_trg; i_trg++)\n                res[i_trg] = eval(VecDimD(xp + DIM * i_trg));\n    }\n\n    /// @brief eval function approximation at point\n    /// @param[in] x [DIM] point to evaluate function at\n    /// @returns function approximation at point x\n    inline double operator()(const VecDimD &x) const { return eval(x); }\n\n    /// @brief eval function approximation at point\n    /// @param[in] x point to evaluate function at\n    /// @returns function approximation at point x\n    inline double operator()(const double *x) const { return eval(x); }\n\n    /// @brief eval function approximation at n_trg points\n    /// @param[in] xp [DIM * n_trg] array of points to evaluate function at\n    /// @param[out] res [DIM * n_trg] array of results\n    /// @param[in] n_trg number of points to evaluate\n    inline void operator()(const double *xp, double *res, int n_trg) const { eval(xp, res, n_trg); }\n\n    /// @brief save function approximation to file\n    /// @param[in] filename path to save file at\n    void save(const char *filename) const {\n        std::ofstream ofs(filename, std::ofstream::binary | std::ofstream::out);\n        baobzi_header_t params{Dim, Order, BAOBZI_HEADER_VERSION};\n        msgpack::pack(ofs, params);\n        msgpack::pack(ofs, *this);\n    }\n\n    /// @brief msgpack serialization magic\n    MSGPACK_DEFINE_MAP(box_, subtrees_, n_subtrees_, tol_, lower_left_, inv_bin_size_, coeffs_, split_multi_eval_);\n};\n\ntemplate <int DIM, int ORDER, int ISET>\nstd::mutex Function<DIM, ORDER, ISET>::statics_mutex;\n\ntemplate <int DIM, int ORDER, int ISET>\ntypename Function<DIM, ORDER, ISET>::VecOrderD Function<DIM, ORDER, ISET>::cosarray_;\n\ntemplate <int DIM, int ORDER, int ISET>\nEigen::PartialPivLU<typename Function<DIM, ORDER, ISET>::VanderMat> Function<DIM, ORDER, ISET>::VLU_;\n} // namespace baobzi\n\n#endif\n", "meta": {"hexsha": "7567885a47ba5803c2a3d4723b5ab9de28c012c9", "size": 34595, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/baobzi_template.hpp", "max_stars_repo_name": "blackwer/baobzi", "max_stars_repo_head_hexsha": "a3cc7e0eee2bc93a30968c3339a0c92991528c36", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2022-01-05T14:21:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T16:57:19.000Z", "max_issues_repo_path": "include/baobzi_template.hpp", "max_issues_repo_name": "blackwer/baobzi", "max_issues_repo_head_hexsha": "a3cc7e0eee2bc93a30968c3339a0c92991528c36", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2022-01-06T15:36:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T19:20:02.000Z", "max_forks_repo_path": "include/baobzi_template.hpp", "max_forks_repo_name": "blackwer/baobzi", "max_forks_repo_head_hexsha": "a3cc7e0eee2bc93a30968c3339a0c92991528c36", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-09T04:25:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T04:25:58.000Z", "avg_line_length": 43.3521303258, "max_line_length": 120, "alphanum_fraction": 0.5918196271, "num_tokens": 8776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5296232883220596}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include \"sphere.hpp\"\n#include \"dpmeans.hpp\"\n#include \"dir.hpp\"\n#include \"cat.hpp\"\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl;\n\ntemplate<class T>\nclass DDPMeans : public DPMeans<T>\n{\npublic:\n  DDPMeans(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx,\n      T lambda, T Q, T tau, boost::mt19937* pRndGen);\n  virtual ~DDPMeans();\n\n//  void initialize(const Matrix<T,Dynamic,Dynamic>& x);\n  virtual void updateLabels();\n  virtual void updateCenters();\n  \n  virtual void nextTimeStep(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx);\n  virtual void updateState(); // after converging for a single time instant\n\n  virtual uint32_t indOfClosestCluster(int32_t i);\n\n  const static uint32_t UNASSIGNED = 4294967295;\nprotected:\n\n  std::vector<T> ts_; // age of clusters - incremented each iteration\n  std::vector<T> ws_; // weights of each cluster \n  T Q_; // Q parameter\n  T tau_; // tau parameter \n  T Kprev_; // K before updateLabels()\n  Matrix<T,Dynamic,Dynamic> psPrev_; // centroids from last set of datapoints\n \n};\n\n// -------------------------------- impl ----------------------------------\ntemplate<class T>\nDDPMeans<T>::DDPMeans(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx, \n    T lambda, T Q, T tau, boost::mt19937* pRndGen)\n  : DPMeans<T>(spx,0,lambda,pRndGen), Q_(Q), tau_(tau)\n{\n  // compute initial counts for weight initialization\n//#pragma omp parallel for\n//  for (uint32_t k=0; k<this->K_; ++k)\n//    for(uint32_t i=0; i<this->N_; ++i)\n//      if(this->z_(i) == k)\n//        this->Ns_(k) ++;\n//  for (uint32_t k=0; k<this->K_; ++k)\n//  {\n//    ws_.push_back(this->Ns_(k));\n//    ts_.push_back(1);\n//  }\n  this->Kprev_ = 0; // so that centers are initialized directly from sample mean\n  psPrev_ = this->ps_;\n}\n\ntemplate<class T>\nDDPMeans<T>::~DDPMeans()\n{}\n\ntemplate<class T>\nuint32_t DDPMeans<T>::indOfClosestCluster(int32_t i)\n{\n  int z_i = this->K_;\n  T sim_closest = this->lambda_;\n//  cout<<\"K=\"<<this->K_<<\" Ns:\"<<this->Ns_.transpose()<<endl;\n//  cout<<\"cluster dists \"<<i<<\": \"<<this->lambda_;\n  for (uint32_t k=0; k<this->K_; ++k)\n  {\n    T sim_k = this->dist(this->ps_.col(k), this->spx_->col(i));\n    if(this->Ns_(k) == 0) // cluster not instantiated yet in this timestep\n    {\n      //TODO use gamma\n//      T gamma = 1.0/(1.0/ws_[z_i] + ts_[z_i]*tau_);\n      sim_k = sim_k/(tau_*ts_[k]+1.) + Q_*ts_[k];\n//      sim_k = sim_k/(tau_*ts_[k]+1.) + Q_*ts_[k];\n    }\n//    cout<<\" \"<<sim_k;\n    if(this->closer(sim_k, sim_closest))\n    {\n      sim_closest = sim_k;\n      z_i = k;\n    }\n  }\n//  }cout<<endl;\n  return z_i;\n}\n\ntemplate<class T>\nvoid DDPMeans<T>::updateLabels()\n{\n  // reset cluster counts -> all uninstantiated\n//  for (uint32_t k=0; k<this->K_; ++k)\n//    this->Ns_(k) = 0; \n//#pragma omp parallel for \n// TODO not sure how to parallelize\n  for(uint32_t i=0; i<this->N_; ++i)\n  {\n    uint32_t z_i = indOfClosestCluster(i);\n    if(z_i == this->K_) \n    { // start a new cluster\n      Matrix<T,Dynamic,Dynamic> psNew(this->D_,this->K_+1);\n      psNew.leftCols(this->K_) = this->ps_;\n      psNew.col(this->K_) = this->spx_->col(i);\n      this->ps_ = psNew;\n      this->K_ ++;\n      this->Ns_.conservativeResize(this->K_); \n      this->Ns_(z_i) = 1.;\n    } else {\n      if(this->Ns_[z_i] == 0)\n      { // instantiated an old cluster\n        T gamma = 1.0/(1.0/ws_[z_i] + ts_[z_i]*tau_);\n        this->ps_.col(z_i)=(this->ps_.col(z_i)*gamma + this->spx_->col(i))/(gamma+1.);\n      }\n      this->Ns_(z_i) ++;\n    }\n    if(this->z_(i) != UNASSIGNED)\n    {\n      this->Ns_(this->z_(i)) --;\n    }\n    this->z_(i) = z_i;\n  }\n};\n\ntemplate<class T>\nvoid DDPMeans<T>::updateCenters()\n{\n#pragma omp parallel for \n  for(uint32_t k=0; k<this->K_; ++k)\n  {\n    Matrix<T,Dynamic,1> mean_k = this->computeCenter(k);\n    if (this->Ns_(k) > 0) \n    { // have data to update kth cluster\n      if(k < this->Kprev_){\n        T gamma = 1.0/(1.0/ws_[k] + ts_[k]*tau_);\n        this->ps_.col(k) = (this->ps_.col(k)*gamma+mean_k*this->Ns_(k))/\n          (gamma+this->Ns_(k));\n      }else{\n        this->ps_.col(k)=mean_k;\n      }\n    }\n  }\n};\n\ntemplate<class T>\nvoid DDPMeans<T>::nextTimeStep(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx)\n{\n  assert(this->D_ == spx->rows());\n  this->spx_ = spx; // update the data\n  this->N_ = spx->cols();\n  this->z_.resize(this->N_);\n  this->z_.fill(UNASSIGNED);\n};\n\ntemplate<class T>\nvoid DDPMeans<T>::updateState()\n{\n  for(uint32_t k=0; k<this->K_; ++k)\n  {\n    if (k<ws_.size() && this->Ns_(k) > 0)\n    { // instantiated cluster from previous time; \n      ws_[k] = 1./(1./ws_[k] + ts_[k]*tau_) + this->Ns_(k);\n      ts_[k] = 0; // re-instantiated -> age is 0\n    }else if(k >= ws_.size()){\n      // new cluster\n      ts_.push_back(0);\n      ws_.push_back(this->Ns_(k));\n    }\n    ts_[k] ++; // increment all ages\n    cout<<\"cluster \"<<k\n      <<\"\\tN=\"<<this->Ns_(k)\n      <<\"\\tage=\"<<ts_[k]\n      <<\"\\tweight=\"<<ws_[k]<<endl;\n    cout<<\"  center: \"<<this->ps_.col(k).transpose()<<endl;\n  }\n  psPrev_ = this->ps_;\n  this->Kprev_ = this->K_;\n};\n", "meta": {"hexsha": "9d20929b11deec014b9bbbc221f61ae3e458e23d", "size": 5195, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/deprecated/ddpmeans.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/deprecated/ddpmeans.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/deprecated/ddpmeans.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": 27.1989528796, "max_line_length": 88, "alphanum_fraction": 0.5896053898, "num_tokens": 1699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5296232718442533}}
{"text": "//\n//  main.cpp\n//  mph\n//\n//  Created by Oliver on 2020-04-09.\n//  Copyright \u00a9 2020 Oliver. All rights reserved.\n//\n\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <queue>\n#include <iostream>\n#include <sstream>\n#include <unordered_map>\n#include <set>\n#include <random>\n#include <time.h>\n#include <boost/progress.hpp>\n\n#include \"utils.h\"\n#include \"grade.h\"\n#include \"column.h\"\n#include \"signatureColumn.h\"\n#include \"matrix.h\"\n#include \"IO.h\"\n#include \"examples.h\"\n\n\ndouble res_memory=0;\ndouble virt_memory=0;\n\n/* Groebner bases */\n\nstd::pair<Matrix, Matrix> computeGroebnerBases(std::vector<SignatureColumn>& columns){\n    /*\n     The main function computing a Groebner basis for the image and kernel of the map described by the list of columns 'columns'.\n     \n     Arguments:\n     columns {std::vector<SignatureColumn>} -- columns describing the matrix of a map between two free multigraded momdules.\n     \n     Returns:\n     std::vector<SignatureColumn> -- a list of vectors decribing a minimal Groebner basis for the image of the map.\n     std::vector<SignatureColumn> -- a list of vectors describing a minimal Groebner basis for the kernel of the map.\n     */\n    \n    std::cout << \"Starting to compute Groebner bases...\" << std::endl;\n    \n    /* Sort columns colexicographically */\n    sort(columns.begin(), columns.end(), [ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade.lt_colex(rhs.grade);\n         });\n    // The sorted columns should agree with the columns sorted by index of signature\n    hash_map<size_t, size_t> index_map_high;\n    for(size_t i=0; i<columns.size(); i++){\n        columns[i].signature_index = i;\n        index_map_high[columns[i].grade[columns[i].grade.size()-1]] = i;\n    }\n    \n    /* Compute index set iterator */\n    std::vector<std::vector<index_t>> grade_base_set = get_grade_base_set<SignatureColumn>(columns);\n    int n_total_grades = 1;\n    for(auto& grade_list : grade_base_set){\n        n_total_grades *= grade_list.size();\n    }\n    Iterator_lex grade_iterator = Iterator_lex(grade_base_set);\n    \n    /* Vectors to store the columns of the GBs */\n    std::vector<SignatureColumn> gb_columns;\n    std::vector<SignatureColumn> syzygies;\n    \n    /* Index maps to keep track of signatures */\n    std::vector<std::vector<signature_t>> GB;\n    std::vector<std::vector<signature_t>> Syz;\n    \n    for(size_t i=0; i<columns.size(); i++){\n        GB.push_back(std::vector<signature_t>());\n        Syz.push_back(std::vector<signature_t>());\n    }\n    \n    /* Main algorithm that iterates through the index set */\n    int column_index;\n    index_t max_pivot=0;\n    for(auto& column : columns){\n        if(max_pivot < column.get_pivot().get_index()){\n            max_pivot = column.get_pivot().get_index();\n        }\n    }\n    index_t pivot;\n    \n    int iter_index = 0;\n    \n    while(grade_iterator.has_next()){\n        grade_t& v = grade_iterator.next();\n        iter_index++;\n        std::vector<index_t> pivot_map(max_pivot+1, -1);\n        /* Initialize Macaulay matrix */\n        size_t& index_bound = index_map_high[v[v.size()-1]];\n        for( size_t i=0; i<=index_bound; i++ ){\n            column_index = -1;\n            bool is_new=false;\n            if(GB[i].size() > 0){\n                bool in_syz = false;\n                if(Syz[i].size()>0){\n                    for(size_t j=Syz[i].size()-1; j < Syz[i].size(); j--){\n                        if((Syz[i][j].get_grade()).leq_poset(v)){\n                            in_syz = true;\n                            break;\n                        }\n                    }\n                }\n                if(!in_syz){\n                    for(size_t j=GB[i].size()-1; j < GB[i].size(); j--){\n                        if(GB[i][j].get_grade().leq_poset(v)){\n                            column_index = (int)GB[i][j].get_index();\n                            break;\n                        }\n                    }\n                }\n            } else{\n                if(columns[i].grade == v){\n                    gb_columns.push_back(columns[i]);\n                    column_index = (int)gb_columns.size()-1;\n                    is_new=true;\n                }\n            }\n            if(column_index > -1){\n                pivot = gb_columns[column_index].get_pivot().get_index();\n                if(pivot_map[pivot] > -1){// && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                    SignatureColumn working_column = gb_columns[column_index];\n                    while(pivot != -1 && pivot_map[pivot] > -1){// && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                        working_column.plus(gb_columns[pivot_map[pivot]]);\n                        pivot = working_column.get_pivot().get_index();\n                    }\n                    if(pivot != -1){\n                        working_column.refresh();\n                        working_column.syzygy.refresh();\n                        gb_columns.push_back(working_column);\n                        GB[i].push_back(signature_t(working_column.grade, gb_columns.size()-1));\n                        pivot_map[pivot] = gb_columns.size()-1;\n                        gb_columns[gb_columns.size()-1].last_updated = iter_index;\n                    }else{\n                        working_column.syzygy.refresh();\n                        syzygies.push_back(SignatureColumn(working_column.grade, working_column.signature_index, working_column.syzygy));\n                        Syz[i].push_back(signature_t(syzygies.back().grade, syzygies.size()-1));\n                    }\n                } else{\n                    if(pivot != -1){\n                        pivot_map[pivot] = column_index;\n                        gb_columns[column_index].last_updated = iter_index;\n                        if(is_new){\n                            GB[i].push_back(signature_t(gb_columns[column_index].grade, column_index));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    Matrix syzygies_output;\n    syzygies_output.reserve(syzygies.size());\n    for(size_t i=0; i<Syz.size(); i++){\n        for(size_t j=0; j<Syz[i].size(); j++){\n            syzygies_output.push_back(SignatureColumn(Syz[i][j].get_grade(), syzygies_output.size(), syzygies[Syz[i][j].get_index()]));\n        }\n    }\n    Matrix gb_columns_output;\n    gb_columns_output.reserve(gb_columns.size());\n    for(size_t i=0; i<GB.size(); i++){\n        for(size_t j=0; j<GB[i].size(); j++){\n            gb_columns_output.push_back(gb_columns[GB[i][j].get_index()]);\n        }\n    }\n    std::cout << \"Finished computing Groebner bases.\" << std::endl;\n    return std::pair<Matrix, Matrix>(gb_columns_output, syzygies_output);\n}\n\nstd::pair<Matrix, Matrix> computeGroebnerBases_gradeopt_min(std::vector<SignatureColumn>& columns){\n    /*\n     The main function computing a Groebner basis for the image and kernel of the map described by the list of columns 'columns'.\n     \n     Arguments:\n     columns {std::vector<SignatureColumn>} -- columns describing the matrix of a map between two free multigraded momdules.\n     \n     Returns:\n     std::vector<SignatureColumn> -- a list of vectors decribing a minimal Groebner basis for the image of the map.\n     std::vector<SignatureColumn> -- a list of vectors describing a minimal Groebner basis for the kernel of the map.\n     */\n    \n    std::cout << \"Starting to compute Groebner bases...\" << std::endl;\n    \n    /* Sort columns colexicographically */\n    sort(columns.begin(), columns.end(), [ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade.lt_colex(rhs.grade);\n         });\n    // The sorted columns should agree with the columns sorted by index of signature\n    hash_map<size_t, size_t> index_map_high;\n    for(size_t i=0; i<columns.size(); i++){\n        columns[i].signature_index = i;\n        index_map_high[columns[i].grade[columns[i].grade.size()-1]] = i;\n    }\n    \n    /* Compute index set iterator */\n    std::priority_queue<grade_t, std::vector<grade_t>, std::greater<grade_t>> grades;\n    std::vector<std::vector<grade_t>> grade_lists;\n    std::unordered_set<grade_t, GradeHasher> visited_grades;\n    \n    /* Vectors to store the columns of the GBs */\n    std::vector<SignatureColumn> gb_columns;\n    std::vector<VectorColumn> syzygies;\n    gb_columns.reserve(2*columns.size());\n    syzygies.reserve(columns.size());\n    \n    /* Index maps to keep track of signatures */\n    std::vector<std::vector<signature_t>> GB;\n    std::vector<std::vector<signature_t>> Syz;\n    GB.reserve(columns.size());\n    Syz.reserve(columns.size());\n    \n    for(size_t i=0; i<columns.size(); i++){\n        GB.push_back(std::vector<signature_t>());\n        Syz.push_back(std::vector<signature_t>());\n    }\n    \n    /* Main algorithm that iterates through the index set */\n    int column_index;\n    index_t max_pivot=0;\n    for(auto& column : columns){\n        if(max_pivot < column.get_pivot_index()){\n            max_pivot = column.get_pivot_index();\n        }\n    }\n    for(size_t i=0; i<=max_pivot; i++){\n        grade_lists.push_back(std::vector<grade_t>());\n    }\n    for(auto& column : columns){\n        if(visited_grades.find(column.grade) == visited_grades.end()){\n            grades.push(column.grade);\n            visited_grades.insert(column.grade);\n        }\n    }\n    \n    std::vector<size_t> grade_hashes;\n    grade_hashes.reserve(columns.size());\n    GradeHasher grade_hasher;\n    for(auto& c : columns){\n        grade_hashes.push_back(grade_hasher(c.grade));\n    }\n    std::vector<index_t> pivot_map(max_pivot+1, -1);\n    index_t pivot;\n    \n    int iter_index = 0;\n    \n    while(!grades.empty()){\n        grade_t v = grades.top();\n        grades.pop();\n        while(v == grades.top()){\n            grades.pop();\n        }\n        \n        size_t grade_hash = grade_hasher(v);\n        iter_index++;\n        \n        /* Initialize Macaulay matrix */\n        size_t& index_bound = index_map_high[v[v.size()-1]];\n        for( size_t i=0; i<=index_bound; i++ ){\n            column_index = -1;\n            bool is_new=false;\n            if(GB[i].size() > 0){\n                bool in_syz = false;\n                if(Syz[i].size()>0){\n                    for(size_t j=Syz[i].size()-1; j < Syz[i].size(); j--){\n                        if((Syz[i][j].get_grade()).leq_poset(v)){\n                            in_syz = true;\n                            break;\n                        }\n                    }\n                }\n                if(!in_syz){\n                    for(size_t j=GB[i].size()-1; j < GB[i].size(); j--){\n                        if(GB[i][j].get_grade().leq_poset(v)){\n                            column_index = (int)GB[i][j].get_index();\n                            break;\n                        }\n                    }\n                }\n            } else{\n                if(grade_hash == grade_hashes[i] && columns[i].grade == v){\n                    gb_columns.push_back(columns[i]);\n                    column_index = (int)gb_columns.size()-1;\n                    is_new=true;\n                }\n            }\n            if(column_index > -1){\n                pivot = gb_columns[column_index].get_pivot_index();\n                if(pivot_map[pivot] > -1 && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                    SignatureColumn working_column = gb_columns[column_index];\n                    while(pivot != -1 && pivot_map[pivot] > -1 && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                        working_column.plus(gb_columns[pivot_map[pivot]]);\n                        pivot = working_column.get_pivot_index();\n                    }\n                    if(pivot != -1){\n                        working_column.refresh();\n                        working_column.syzygy.refresh();\n                        gb_columns.push_back(working_column);\n                        GB[i].push_back(signature_t(working_column.grade, gb_columns.size()-1));\n                        pivot_map[pivot] = gb_columns.size()-1;\n                        gb_columns[gb_columns.size()-1].last_updated = iter_index;\n                        if(working_column.grade == v){\n                            if(grade_lists[pivot].size() == 0 || working_column.grade != grade_lists[pivot].back()){\n                                std::vector<grade_t> minimal_elements_tmp;\n                                for(size_t j=0; j<grade_lists[pivot].size(); j++){\n                                    grade_t m_ji = grade_lists[pivot][j].m_ji(working_column.grade);\n                                    bool is_minimal = true;\n                                    for(auto& el : minimal_elements_tmp){\n                                        if(el.leq_poset(m_ji)){\n                                            is_minimal = false;\n                                            break;\n                                        }\n                                    }\n                                    if(is_minimal){\n                                        minimal_elements_tmp.push_back(m_ji);\n                                        grade_t g = working_column.grade.join(grade_lists[pivot][j]);\n                                        if(visited_grades.find(g) == visited_grades.end()){\n                                            grades.push(g);\n                                            visited_grades.insert(g);\n                                        }\n                                    }\n                                }\n                                grade_lists[pivot].push_back(working_column.grade);\n                            }\n                        }\n                    }else{\n                        working_column.syzygy.refresh();\n                        syzygies.push_back(working_column.syzygy);\n                        Syz[i].push_back(signature_t(working_column.grade, syzygies.size()-1));\n                    }\n                } else{\n                    if(pivot != -1){\n                        pivot_map[pivot] = column_index;\n                        gb_columns[column_index].last_updated = iter_index;\n                        if(is_new){\n                            GB[i].push_back(signature_t(gb_columns[column_index].grade, column_index));\n                            if(grade_lists[pivot].size() == 0 || gb_columns[column_index].grade != grade_lists[pivot].back()){\n                                std::vector<grade_t> minimal_elements_tmp;\n                                for(size_t j=0; j<grade_lists[pivot].size(); j++){\n                                    grade_t m_ji = grade_lists[pivot][j].m_ji(gb_columns[column_index].grade);\n                                    bool is_minimal = true;\n                                    for(auto& el : minimal_elements_tmp){\n                                        if(el.leq_poset(m_ji)){\n                                            is_minimal = false;\n                                            break;\n                                        }\n                                    }\n                                    if(is_minimal){\n                                        minimal_elements_tmp.push_back(m_ji);\n                                        grade_t g = gb_columns[column_index].grade.join(grade_lists[pivot][j]);\n                                        if(visited_grades.find(g) == visited_grades.end()){\n                                            grades.push(g);\n                                            visited_grades.insert(g);\n                                        }\n                                    }\n                                }\n                                grade_lists[pivot].push_back(gb_columns[column_index].grade);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    Matrix syzygies_output;\n    syzygies_output.reserve(syzygies.size());\n    for(size_t i=0; i<Syz.size(); i++){\n        for(size_t j=0; j<Syz[i].size(); j++){\n            syzygies_output.push_back(SignatureColumn(Syz[i][j].get_grade(), syzygies_output.size(), syzygies[Syz[i][j].get_index()]));\n        }\n    }\n    Matrix gb_columns_output;\n    gb_columns_output.reserve(gb_columns.size());\n    for(size_t i=0; i<GB.size(); i++){\n        for(size_t j=0; j<GB[i].size(); j++){\n            gb_columns_output.push_back(gb_columns[GB[i][j].get_index()]);\n        }\n    }\n    std::cout << \"Finished computing Groebner bases.\" << std::endl;\n    return std::pair<Matrix, Matrix>(gb_columns_output, syzygies_output);\n}\n\nstd::pair<Matrix, Matrix> computeGroebnerBases_gradeopt(std::vector<SignatureColumn>& columns){\n    /*\n     The main function computing a Groebner basis for the image and kernel of the map described by the list of columns 'columns'.\n     \n     Arguments:\n     columns {std::vector<SignatureColumn>} -- columns describing the matrix of a map between two free multigraded momdules.\n     \n     Returns:\n     std::vector<SignatureColumn> -- a list of vectors decribing a minimal Groebner basis for the image of the map.\n     std::vector<SignatureColumn> -- a list of vectors describing a minimal Groebner basis for the kernel of the map.\n     */\n    \n    std::cout << \"Starting to compute Groebner bases...\" << std::endl;\n    \n    /* Sort columns colexicographically */\n    sort(columns.begin(), columns.end(), [ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade.lt_colex(rhs.grade);\n         });\n    // The sorted columns should agree with the columns sorted by index of signature\n    hash_map<size_t, size_t> index_map_high;\n    for(size_t i=0; i<columns.size(); i++){\n        columns[i].signature_index = i;\n        index_map_high[columns[i].grade[columns[i].grade.size()-1]] = i;\n    }\n    \n    /* Compute index set iterator */\n    std::priority_queue<grade_t, std::vector<grade_t>, std::greater<grade_t>> grades;\n    std::vector<std::vector<grade_t>> grade_lists;\n    std::unordered_set<grade_t, GradeHasher> visited_grades;\n    \n    /* Vectors to store the columns of the GBs */\n    Matrix gb_columns;\n    Matrix syzygies;\n    gb_columns.reserve(columns.size());\n    syzygies.reserve(columns.size());\n    \n    /* Index maps to keep track of signatures */\n    std::vector<std::vector<signature_t>> GB;\n    std::vector<std::vector<signature_t>> Syz;\n    GB.reserve(columns.size());\n    Syz.reserve(columns.size());\n    \n    for(size_t i=0; i<columns.size(); i++){\n        GB.push_back(std::vector<signature_t>());\n        Syz.push_back(std::vector<signature_t>());\n    }\n    \n    /* Main algorithm that iterates through the index set */\n    int column_index;\n    index_t max_pivot=0;\n    for(auto& column : columns){\n        if(max_pivot < column.get_pivot_index()){\n            max_pivot = column.get_pivot_index();\n        }\n    }\n    for(size_t i=0; i<=max_pivot; i++){\n        grade_lists.push_back(std::vector<grade_t>());\n    }\n    for(auto& column : columns){\n        grades.push(column.grade);\n    }\n    \n    std::vector<size_t> grade_hashes;\n    grade_hashes.reserve(columns.size());\n    GradeHasher grade_hasher;\n    for(auto& c : columns){\n        grade_hashes.push_back(grade_hasher(c.grade));\n    }\n    \n    index_t pivot;\n    std::vector<index_t> pivot_map(max_pivot+1, -1);\n    int iter_index = 0;\n    \n    while(!grades.empty()){\n        grade_t v = grades.top();\n        grades.pop();\n        while(v == grades.top()){\n            grades.pop();\n        }\n        size_t grade_hash = grade_hasher(v);\n        iter_index++;\n        \n        /* Initialize Macaulay matrix */\n        size_t& index_bound = index_map_high[v[v.size()-1]];\n        for( size_t i=0; i<=index_bound; i++ ){\n            column_index = -1;\n            bool is_new=false;\n            if(GB[i].size() > 0){\n                bool in_syz = false;\n                if(Syz[i].size()>0){\n                    for(size_t j=Syz[i].size()-1; j < Syz[i].size(); j--){\n                        if((Syz[i][j].get_grade()).leq_poset(v)){\n                            in_syz = true;\n                            break;\n                        }\n                    }\n                }\n                if(!in_syz){\n                    for(size_t j=GB[i].size()-1; j < GB[i].size(); j--){\n                        if(GB[i][j].get_grade().leq_poset(v)){\n                            column_index = (int)GB[i][j].get_index();\n                            break;\n                        }\n                    }\n                }\n            } else{\n                if(grade_hash == grade_hashes[i] && columns[i].grade == v){\n                    gb_columns.push_back(columns[i]);\n                    column_index = (int)gb_columns.size()-1;\n                    is_new=true;\n                }\n            }\n            if(column_index > -1){\n                pivot = gb_columns[column_index].get_pivot_index();\n                if(pivot_map[pivot] != -1 && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                    SignatureColumn working_column = gb_columns[column_index];\n                    while(pivot != -1 && pivot_map[pivot] > -1 && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                        working_column.plus(gb_columns[pivot_map[pivot]]);\n                        pivot = working_column.get_pivot_index();\n                    }\n                    if(pivot != -1){\n                        working_column.refresh();\n                        working_column.syzygy.refresh();\n                        grade_t grade = working_column.grade;\n                        if(is_new){\n                            gb_columns[column_index] = working_column;\n                            GB[i].push_back(signature_t(grade, column_index));\n                            pivot_map[pivot] = column_index;\n                            gb_columns[column_index].last_updated = iter_index;\n                        }else{\n                            /*if(GB[i].size()==1){\n                                gb_columns.push_back(working_column);\n                                GB[i].push_back(signature_t(grade, gb_columns.size()-1));\n                            }else{\n                                if(pivot_map[gb_columns[GB[i][1].get_index()].get_pivot_index()] == GB[i][1].get_index()){\n                                    pivot_map[gb_columns[GB[i][1].get_index()].get_pivot_index()] = -1;\n                                }\n                                gb_columns[GB[i][1].get_index()].swap(working_column);\n                                GB[i][1].first = grade;\n                            }*/\n                            gb_columns.push_back(working_column);\n                            GB[i].push_back(signature_t(grade, gb_columns.size()-1));\n                            pivot_map[pivot] = gb_columns.size()-1;\n                            gb_columns[gb_columns.size()-1].last_updated = iter_index;\n                        }\n                        if(grade == v){\n                            if(grade_lists[pivot].size() == 0 || grade != grade_lists[pivot].back()){\n                                for(size_t ig=0; ig<grade_lists[pivot].size(); ig++){\n                                    grade_t g = grade.join(grade_lists[pivot][ig]);\n                                    if(grade != g){\n                                        grades.push(g);\n                                    }\n                                }\n                                grade_lists[pivot].push_back(grade);\n                            }\n                        }\n                       \n                    }else{\n                        if(is_new){\n                            gb_columns.pop_back();\n                        }\n                        working_column.syzygy.refresh();\n                        syzygies.push_back(SignatureColumn(working_column.get_grade(), syzygies.size(), working_column.syzygy));\n                        Syz[i].push_back(signature_t(working_column.grade, syzygies.size()-1));\n                    }\n                } else{\n                    if(pivot != -1){\n                        pivot_map[pivot] = column_index;\n                        gb_columns[column_index].last_updated = iter_index;\n                        if(is_new){\n                            GB[i].push_back(signature_t(gb_columns[column_index].grade, column_index));\n                            if(grade_lists[pivot].size() == 0 || gb_columns[column_index].grade != grade_lists[pivot].back()){\n                                for(size_t ig=0; ig<grade_lists[pivot].size(); ig++){\n                                    grade_t g = gb_columns[column_index].grade.join(grade_lists[pivot][ig]);\n                                    if(gb_columns[column_index].grade != g){\n                                        grades.push(g);\n                                    }\n                                }\n                                grade_lists[pivot].push_back(gb_columns[column_index].grade);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    get_mem_usage(virt_memory, res_memory);\n    \n    std::cout << \"Finished computing Groebner bases.\" << std::endl;\n    return std::pair<Matrix, Matrix>(gb_columns, syzygies);\n}\n\nMatrix computekernel_gradeopt(std::vector<SignatureColumn>& columns){\n    /*\n     The main function computing a Groebner basis for the image and kernel of the map described by the list of columns 'columns'.\n     \n     Arguments:\n     columns {std::vector<SignatureColumn>} -- columns describing the matrix of a map between two free multigraded momdules.\n     \n     Returns:\n     std::vector<SignatureColumn> -- a list of vectors decribing a minimal Groebner basis for the image of the map.\n     std::vector<SignatureColumn> -- a list of vectors describing a minimal Groebner basis for the kernel of the map.\n     */\n    \n    std::cout << \"Starting to compute Groebner bases...\" << std::endl;\n    \n    /* Sort columns colexicographically */\n    sort(columns.begin(), columns.end(), [ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade.lt_colex(rhs.grade);\n         });\n    // The sorted columns should agree with the columns sorted by index of signature\n    hash_map<size_t, size_t> index_map_high;\n    for(size_t i=0; i<columns.size(); i++){\n        columns[i].signature_index = i;\n        index_map_high[columns[i].grade[columns[i].grade.size()-1]] = i;\n    }\n    \n    /* Compute index set iterator */\n    std::priority_queue<grade_t, std::vector<grade_t>, std::greater<grade_t>> grades;\n    std::vector<std::vector<grade_t>> grade_lists;\n    \n    /* Vectors to store the columns of the GBs */\n    std::vector<SignatureColumn> gb_columns;\n    std::vector<SyzColumn> syzygies;\n    gb_columns.reserve(2*columns.size());\n    syzygies.reserve(columns.size());\n    \n    /* Index maps to keep track of signatures */\n    std::vector<std::vector<signature_t>> GB;\n    std::vector<std::vector<signature_t>> Syz;\n    GB.reserve(columns.size());\n    Syz.reserve(columns.size());\n    \n    for(size_t i=0; i<columns.size(); i++){\n        GB.push_back(std::vector<signature_t>());\n        Syz.push_back(std::vector<signature_t>());\n    }\n    \n    /* Main algorithm that iterates through the index set */\n    int column_index;\n    index_t max_pivot=0;\n    for(auto& column : columns){\n        if(max_pivot < column.get_pivot_index()){\n            max_pivot = column.get_pivot_index();\n        }\n    }\n    for(size_t i=0; i<=max_pivot; i++){\n        grade_lists.push_back(std::vector<grade_t>());\n    }\n    for(auto& column : columns){\n        grades.push(column.grade);\n    }\n    \n    index_t pivot;\n    \n    int iter_index = 0;\n    \n    while(!grades.empty()){\n        grade_t v = grades.top();\n        grades.pop();\n        while(v == grades.top()){\n            grades.pop();\n        }\n        iter_index++;\n        std::vector<index_t> pivot_map(max_pivot+1, -1);\n        /* Initialize Macaulay matrix */\n        size_t& index_bound = index_map_high[v[v.size()-1]];\n        for( size_t i=0; i<=index_bound; i++ ){\n            column_index = -1;\n            bool is_new=false;\n            if(GB[i].size() > 0){\n                bool in_syz = false;\n                if(Syz[i].size()>0){\n                    for(size_t j=Syz[i].size()-1; j < Syz[i].size(); j--){\n                        if((Syz[i][j].get_grade()).leq_poset(v)){\n                            in_syz = true;\n                            break;\n                        }\n                    }\n                }\n                if(!in_syz){\n                    for(size_t j=GB[i].size()-1; j < GB[i].size(); j--){\n                        if(GB[i][j].get_grade().leq_poset(v)){\n                            column_index = (int)GB[i][j].get_index();\n                            break;\n                        }\n                    }\n                }\n            } else{\n                if(columns[i].grade == v){\n                    gb_columns.push_back(columns[i]);\n                    column_index = (int)gb_columns.size()-1;\n                    is_new=true;\n                }\n            }\n            if(column_index > -1){\n                pivot = gb_columns[column_index].get_pivot_index();\n                if(pivot_map[pivot] != -1){// && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                    SignatureColumn working_column = gb_columns[column_index];\n                    while(pivot != -1 && pivot_map[pivot] > -1){// && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                        working_column.plus(gb_columns[pivot_map[pivot]]);\n                        pivot = working_column.get_pivot_index();\n                    }\n                    if(pivot != -1){\n                        working_column.refresh();\n                        working_column.syzygy.refresh();\n                        if(is_new){\n                            GB[i].push_back(signature_t(gb_columns[column_index].grade, column_index));\n                            gb_columns.push_back(working_column);\n                            GB[i].push_back(signature_t(gb_columns[column_index].grade, gb_columns.size()-1));\n                            pivot_map[pivot] = gb_columns.size()-1;\n                            gb_columns[gb_columns.size()-1].last_updated = iter_index;\n                        }else{\n                            GB[i][1].first = working_column.grade;\n                            gb_columns[GB[i][1].get_index()].swap(working_column);\n                            pivot_map[pivot] = GB[i][1].get_index();\n                            gb_columns[GB[i][1].get_index()].last_updated = iter_index;\n                        }\n                        grade_t& grade = GB[i][1].get_grade();\n                        if(grade == v){\n                            if(grade_lists[pivot].size() == 0 || grade != grade_lists[pivot].back()){\n                                for(size_t ig=0; ig<grade_lists[pivot].size(); ig++){\n                                    if(grade.join(grade_lists[pivot][ig]) != grade){\n                                        grade_t g = grade_lists[pivot][ig];\n                                        grades.push(grade.join(grade_lists[pivot][ig]));\n                                    }\n                                }\n                                grade_lists[pivot].push_back(grade);\n                            }\n                        }\n                       \n                    }else{\n                        working_column.syzygy.refresh();\n                        syzygies.push_back(working_column.syzygy);\n                        Syz[i].push_back(signature_t(working_column.grade, syzygies.size()-1));\n                    }\n                } else{\n                    if(pivot != -1){\n                        pivot_map[pivot] = column_index;\n                        gb_columns[column_index].last_updated = iter_index;\n                        if(is_new){\n                            GB[i].push_back(signature_t(gb_columns[column_index].grade, column_index));\n                            gb_columns.push_back(gb_columns[column_index]);\n                            GB[i].push_back(signature_t(gb_columns[column_index].grade, gb_columns.size()-1));\n                            pivot_map[pivot] = gb_columns.size()-1;\n                            gb_columns[gb_columns.size()-1].last_updated = iter_index;\n                            if(grade_lists[pivot].size() == 0 || gb_columns[column_index].grade != grade_lists[pivot].back()){\n                                for(size_t ig=0; ig<grade_lists[pivot].size(); ig++){\n                                    if(gb_columns[column_index].grade.join(grade_lists[pivot][ig]) != gb_columns[column_index].grade){\n                                        grades.push(gb_columns[column_index].grade.join(grade_lists[pivot][ig]));\n                                    }\n                                }\n                                grade_lists[pivot].push_back(gb_columns[column_index].grade);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    Matrix syzygies_output;\n    syzygies_output.reserve(syzygies.size());\n    for(size_t i=0; i<Syz.size(); i++){\n        for(size_t j=0; j<Syz[i].size(); j++){\n            syzygies_output.push_back(SignatureColumn(Syz[i][j].get_grade(), syzygies_output.size(), syzygies[Syz[i][j].get_index()]));\n        }\n    }\n    std::cout << \"Finished computing Groebner bases.\" << std::endl;\n    return syzygies_output;\n}\n\nMatrix ImageGB(std::vector<SignatureColumn>& columns){\n    /*\n     The main function computing a Groebner basis for the image and kernel of the map described by the list of columns 'columns'.\n     \n     Arguments:\n     columns {std::vector<SignatureColumn>} -- columns describing the matrix of a map between two free multigraded momdules.\n     \n     Returns:\n     std::vector<SignatureColumn> -- a list of vectors decribing a minimal Groebner basis for the image of the map.\n     std::vector<SignatureColumn> -- a list of vectors describing a minimal Groebner basis for the kernel of the map.\n     */\n    \n    std::cout << \"Starting to compute Groebner bases...\" << std::endl;\n    \n    /* Sort columns colexicographically */\n    sort(columns.begin(), columns.end(), [ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade.lt_colex(rhs.grade);\n         });\n    // The sorted columns should agree with the columns sorted by index of signature\n    hash_map<size_t, size_t> index_map_high;\n    for(size_t i=0; i<columns.size(); i++){\n        columns[i].signature_index = i;\n        index_map_high[columns[i].grade[columns[i].grade.size()-1]] = i;\n    }\n    \n    /* Compute index set iterator */\n    std::priority_queue<grade_t, std::vector<grade_t>, std::greater<grade_t>> grades;\n    std::vector<std::vector<grade_t>> grade_lists;\n    std::unordered_set<grade_t, GradeHasher> visited_grades;\n    \n    /* Vectors to store the columns of the GBs */\n    Matrix gb_columns;\n    gb_columns.reserve(columns.size());\n    \n    /* Index maps to keep track of signatures */\n    std::vector<std::vector<signature_t>> GB;\n    std::vector<std::vector<signature_t>> Syz;\n    GB.reserve(columns.size());\n    Syz.reserve(columns.size());\n    \n    for(size_t i=0; i<columns.size(); i++){\n        GB.push_back(std::vector<signature_t>());\n        Syz.push_back(std::vector<signature_t>());\n    }\n    \n    /* Main algorithm that iterates through the index set */\n    int column_index;\n    index_t max_pivot=0;\n    for(auto& column : columns){\n        if(max_pivot < column.get_pivot_index()){\n            max_pivot = column.get_pivot_index();\n        }\n    }\n    for(size_t i=0; i<=max_pivot; i++){\n        grade_lists.push_back(std::vector<grade_t>());\n    }\n    for(auto& column : columns){\n        if(visited_grades.find(column.grade) == visited_grades.end()){\n            grades.push(column.grade);\n            visited_grades.insert(column.grade);\n        }\n    }\n    \n    std::vector<size_t> grade_hashes;\n    grade_hashes.reserve(columns.size());\n    GradeHasher grade_hasher;\n    for(auto& c : columns){\n        grade_hashes.push_back(grade_hasher(c.grade));\n    }\n    \n    index_t pivot;\n    std::vector<index_t> pivot_map(max_pivot+1, -1);\n    int iter_index = 0;\n    \n    while(!grades.empty()){\n        grade_t v = grades.top();\n        grades.pop();\n        /*while(v == grades.top()){\n            grades.pop();\n        }*/\n        size_t grade_hash = grade_hasher(v);\n        iter_index++;\n        \n        /* Initialize Macaulay matrix */\n        size_t& index_bound = index_map_high[v[v.size()-1]];\n        for( size_t i=0; i<=index_bound; i++ ){\n            column_index = -1;\n            bool is_new=false;\n            if(GB[i].size() > 0){\n                bool in_syz = false;\n                if(Syz[i].size()>0){\n                    for(size_t j=Syz[i].size()-1; j < Syz[i].size(); j--){\n                        if((Syz[i][j].get_grade()).leq_poset(v)){\n                            in_syz = true;\n                            break;\n                        }\n                    }\n                }\n                if(!in_syz){\n                    for(size_t j=GB[i].size()-1; j < GB[i].size(); j--){\n                        if(GB[i][j].get_grade().leq_poset(v)){\n                            column_index = (int)GB[i][j].get_index();\n                            break;\n                        }\n                    }\n                }\n            } else{\n                if(grade_hash == grade_hashes[i] && columns[i].grade == v){\n                    gb_columns.push_back(columns[i]);\n                    column_index = (int)gb_columns.size()-1;\n                    is_new=true;\n                }\n            }\n            if(column_index > -1){\n                pivot = gb_columns[column_index].get_pivot_index();\n                if(pivot_map[pivot] != -1 && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                    SignatureColumn working_column = gb_columns[column_index];\n                    while(pivot != -1 && pivot_map[pivot] > -1 && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                        working_column.plus(gb_columns[pivot_map[pivot]]);\n                        pivot = working_column.get_pivot_index();\n                    }\n                    if(pivot != -1){\n                        working_column.refresh();\n                        working_column.syzygy.refresh();\n                        if(is_new){\n                            gb_columns.pop_back();\n                        }\n                        gb_columns.push_back(working_column);\n                        GB[i].push_back(signature_t(working_column.grade, gb_columns.size()-1));\n                        pivot_map[pivot] = gb_columns.size()-1;\n                        gb_columns[gb_columns.size()-1].last_updated = iter_index;\n                        if(working_column.grade == v){\n                            if(grade_lists[pivot].size() == 0 || working_column.grade != grade_lists[pivot].back()){\n                                for(size_t ig=0; ig<grade_lists[pivot].size(); ig++){\n                                    grade_t g = working_column.grade.join(grade_lists[pivot][ig]);\n                                    if(visited_grades.find(g) == visited_grades.end()){\n                                        grades.push(g);\n                                        visited_grades.insert(g);\n                                    }\n                                }\n                                grade_lists[pivot].push_back(working_column.grade);\n                            }\n                        }\n                       \n                    }else{\n                        if(is_new){\n                            gb_columns.pop_back();\n                        }\n                        working_column.syzygy.refresh();\n                        Syz[i].push_back(signature_t(working_column.grade, -1));\n                    }\n                } else{\n                    if(pivot != -1){\n                        pivot_map[pivot] = column_index;\n                        gb_columns[column_index].last_updated = iter_index;\n                        if(is_new){\n                            GB[i].push_back(signature_t(gb_columns[column_index].grade, column_index));\n                            if(grade_lists[pivot].size() == 0 || gb_columns[column_index].grade != grade_lists[pivot].back()){\n                                for(size_t ig=0; ig<grade_lists[pivot].size(); ig++){\n                                    grade_t g = gb_columns[column_index].grade.join(grade_lists[pivot][ig]);\n                                    if(visited_grades.find(g) == visited_grades.end()){\n                                        grades.push(g);\n                                        visited_grades.insert(g);\n                                    }\n                                }\n                                grade_lists[pivot].push_back(gb_columns[column_index].grade);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    std::cout << \"Finished computing Groebner bases.\" << std::endl;\n    return gb_columns;\n}\n\nMatrix buchberger(Matrix& columns){\n    std::cout << \"Computing GB for the image using Buchbergers algorithm.\" << std::endl;\n    size_t max_pivot = 0;\n    for(size_t i=0; i<columns.size(); i++){\n        if(columns[i].get_pivot_index() > max_pivot){\n            max_pivot = columns[i].get_pivot_index();\n        }\n    }\n    std::vector<std::vector<size_t>> pivot_map(max_pivot+1, std::vector<size_t>());\n    Matrix G = columns;\n    std::queue<std::pair<size_t, size_t>> M;\n    for(size_t i=0; i<G.size(); i++){\n        for(size_t j=0; j<i; j++){\n            if(G[i].get_pivot_index() == G[j].get_pivot_index()){\n                M.push(std::pair<size_t, size_t>(i, j));\n            }\n        }\n    }\n    while(M.size()>0){\n        std::pair<size_t, size_t> p = M.front();\n        M.pop();\n        SignatureColumn c = G[p.first];\n        c.plus(G[p.second]);\n        index_t pivot = c.get_pivot_index();\n        while(pivot != -1){\n            bool has_reduced = false;\n            for(size_t i=0; i<pivot_map[pivot].size(); i++){\n                if(G[pivot_map[pivot][i]].grade.leq_poset(c.grade)){\n                    c.plus(G[pivot_map[pivot][i]]);\n                    c.refresh();\n                    c.syzygy.refresh();\n                    has_reduced = true;\n                    break;\n                }\n            }\n            if(has_reduced){\n                pivot = c.get_pivot_index();\n            }else{\n                \n                for(size_t i=0; i<G.size(); i++){\n                    if(G[i].get_pivot_index() == pivot){\n                        M.push(std::pair<size_t, size_t>(i, G.size()));\n                    }\n                }\n                G.push_back(c);\n                pivot_map[pivot].push_back(G.size()-1);\n                break;\n            }\n        }\n        \n    }\n    std::cout << \"Finished computing a GB of size: \" << G.size() << std::endl;\n    return G;\n}\n\nMatrix computeKernel_2p(std::vector<SignatureColumn>& columns){\n    /*\n     The main function computing a Groebner basis for the kernel of the bigraded map described by the list of columns 'columns'.\n     \n     Arguments:\n     columns {std::vector<SignatureColumn>} -- columns describing the matrix of a map between two free multigraded momdules.\n     \n     Returns:\n     std::vector<SignatureColumn> -- a list of vectors decribing a minimal Groebner basis for the image of the map.\n     std::vector<SignatureColumn> -- a list of vectors describing a minimal Groebner basis for the kernel of the map.\n     */\n    \n    std::cout << \"Starting to compute Groebner bases...\" << std::endl;\n    \n    /* Sort columns colexicographically */\n    sort(columns.begin(), columns.end(), [ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade.lt_colex(rhs.grade);\n         });\n    // The sorted columns should agree with the columns sorted by index of signature\n    hash_map<size_t, size_t> index_map_low, index_map_high;\n    for(size_t i=0; i<columns.size(); i++){\n        columns[i].signature_index = i;\n        index_map_high[columns[i].grade[columns[i].grade.size()-1]] = i;\n        if(index_map_low.find(columns[i].grade[columns[i].grade.size()-1]) == index_map_low.end()){\n            index_map_low[columns[i].grade[columns[i].grade.size()-1]] = i;\n        }\n    }\n    \n    /* Compute index set iterator */\n    std::vector<std::vector<index_t>> grade_base_set = get_grade_base_set<SignatureColumn>(columns);\n    int n_total_grades = 1;\n    for(auto& grade_list : grade_base_set){\n        n_total_grades *= grade_list.size();\n    }\n    Iterator_lex grade_iterator = Iterator_lex(grade_base_set);\n    \n    std::vector<SyzColumn> syzygies;\n    std::vector<std::vector<signature_t>> Syz;\n    \n    for(size_t i=0; i<columns.size(); i++){\n        Syz.push_back(std::vector<signature_t>());\n    }\n    \n    /* Main algorithm that iterates through the index set */\n    index_t pivot;\n    std::vector<index_t> pivot_map(columns.size(), -1);\n    \n    while(grade_iterator.has_next()){\n        grade_t& v = grade_iterator.next();\n        \n        /* Initialize Macaulay matrix */\n        for( size_t i=index_map_low[v[v.size()-1]]; i<=index_map_high[v[v.size()-1]] && columns[i].grade[0] <= v[0]; i++ ){\n            if(columns[i].size()>0){\n                pivot = columns[i].get_pivot_index();\n                if(pivot_map[pivot] > -1 && pivot_map[pivot] < i){\n                    SignatureColumn& working_column = columns[i];\n                    while(pivot != -1 && pivot_map[pivot] > -1 && pivot_map[pivot] < i){\n                        working_column.plus(columns[pivot_map[pivot]]);\n                        pivot = working_column.get_pivot().get_index();\n                    }\n                    if(pivot != -1){\n                        working_column.refresh();\n                        working_column.syzygy.refresh();\n                        pivot_map[pivot] = i;\n                    }else{\n                        working_column.syzygy.refresh();\n                        syzygies.push_back(working_column.syzygy);\n                        Syz[i].push_back(signature_t(working_column.grade, syzygies.size()-1));\n                    }\n                } else{\n                    if(pivot != -1){\n                        pivot_map[pivot] = i;\n                    }\n                }\n            }\n        }\n    }\n    \n    Matrix syzygies_output;\n    syzygies_output.reserve(syzygies.size());\n    for(size_t i=0; i<Syz.size(); i++){\n        for(size_t j=0; j<Syz[i].size(); j++){\n            syzygies_output.push_back(SignatureColumn(Syz[i][j].get_grade(), syzygies_output.size(), syzygies[Syz[i][j].get_index()]));\n        }\n    }\n    std::cout << \"Finished computing Groebner bases.\" << std::endl;\n    return syzygies_output;\n}\n\n/* Presentations */\n\nhash_map<size_t, size_t> compute_local_pairs(Matrix& columns, hash_map<size_t, grade_t>& row_grades){\n    /** Computes the local positive and negative pairs of columns and pivots.\n     \n     Arguments:\n     columns {Matrix} -- the matrix with columns to be labeled local positive, negative or global.\n     row_grades {std::vector<grade_t>} -- a list of the multigrade of each row.\n     \n     Returns:\n     hash_map<size_t, size_t> -- a map that sends a local positive row to a local negative column.\n     \n     */\n    std::cout << \"Starting to compute local pairs...\";\n    hash_map<size_t, size_t> pairs;\n    for(size_t column_index=0; column_index < columns.size(); column_index++){\n        if(columns[column_index].local != 1 && columns[column_index].get_pivot().get_index() != -1 && row_grades[columns[column_index].get_pivot().get_index()] == columns[column_index].grade){\n            \n            if(pairs.find(columns[column_index].get_pivot().get_index()) != pairs.end()){\n                SignatureColumn working_column(columns[column_index].grade, -1);\n                size_t column_to_add = column_index;\n                while(true){\n                    working_column.plus(columns[column_to_add]);\n                    index_t pivot = working_column.get_pivot().get_index();\n                    if(pivot != -1 && row_grades[pivot] == working_column.grade){\n                        if (pairs.find(pivot) != pairs.end()) {\n                            column_to_add = pairs[pivot];\n                        } else {\n                            pairs[pivot] = column_index;\n                            columns[column_index].local = -1;\n                            break;\n                        }\n                    } else{\n                        break;\n                    }\n                }\n            }else{\n                pairs[columns[column_index].get_pivot().get_index()] = column_index;\n                columns[column_index].local = -1;\n            }\n        }\n    }\n    std::cout << \"Finished computing local pairs.\";\n    return pairs;\n}\n\nMatrix compute_global_columns(Matrix& columns, hash_map<size_t, size_t>& positive_pairs, std::set<size_t>& negative_rows){\n    /** Performs the presentation minimization step by removing local positive and negative columns.\n     \n     Arguments:\n     columns {Matrix} -- a matrix with columns labeled local positive, negative or global.\n     positive_pairs {hash_map<size_t, size_t>} -- a map sending local positive rows to local negative columns.\n     negative_rows {std::set<size_t>} -- a set containing the indices of local negative rows.\n     \n     Returns:\n     Matrix -- a minimized presentation matrix.\n     \n     */\n    std::cout << \"Starting to compute global columns...\";\n    \n    Matrix global_columns;\n    for(size_t index_column_to_reduce = 0; index_column_to_reduce<columns.size();index_column_to_reduce++) {\n        if(columns[index_column_to_reduce].local != 0)\n            continue;\n        SignatureColumn working_boundary(columns[index_column_to_reduce].grade, index_column_to_reduce);\n        SignatureColumn global_column(columns[index_column_to_reduce].grade, index_column_to_reduce);\n        working_boundary.plus(columns[index_column_to_reduce]);\n        while(true) {\n            index_t pivot = working_boundary.get_pivot().get_index();\n            if (pivot != -1) {\n                if (negative_rows.find(pivot) != negative_rows.end()) {\n                    working_boundary.pop_pivot();\n                }else if(positive_pairs.find(pivot) != positive_pairs.end()) {\n                    working_boundary.plus(columns[positive_pairs[pivot]]);\n                }else{\n                    global_column.push(working_boundary.pop_pivot());\n                }\n            }else{\n                break;\n            }\n        }\n        if(global_column.get_pivot().get_index() != -1){\n            global_columns.push_back(global_column);\n        }\n    }\n    std::cout << \"Finished computing global columns of size: \" << global_columns.size();\n    return global_columns;\n}\n\n\nMatrix compute_syzygy_module(Matrix groebner_basis){\n    /** Computes the syzygy module of a Groebner basis using Schreyer's algorithm.\n     \n    */\n    \n    for(size_t i=0; i<groebner_basis.size(); i++){\n        groebner_basis[i].signature_index = i;\n    }\n    \n    hash_map<size_t, std::vector<SignatureColumn>> pivot_partition;\n    for(size_t i=0; i<groebner_basis.size(); i++){\n        if(pivot_partition.find(groebner_basis[i].get_pivot().get_index()) == pivot_partition.end()){\n            pivot_partition[groebner_basis[i].get_pivot().get_index()] = std::vector<SignatureColumn>();\n        }\n        pivot_partition[groebner_basis[i].get_pivot().get_index()].push_back(groebner_basis[i]);\n    }\n    Matrix syzygies;\n    for(auto& entry : pivot_partition){\n        std::vector<SignatureColumn>& columns = entry.second;\n        //Matrix M;\n        //for(auto& column : columns){\n        //    M.push_back(column);\n        //}\n        //std::cout << \"Partition for pivot \" << entry.first << \"\\n\";\n        //M.print();\n        for(size_t i=1; i<columns.size(); i++){\n            std::vector<grade_t> minimal_elements_tmp;\n            std::vector<size_t> minimal_indices_tmp;\n            for(size_t j=0; j<i; j++){\n                grade_t m_ji = columns[j].grade.m_ji(columns[i].grade);\n                //spdlog::info(\"m_ji...\");\n                //columns[j].grade.print();\n                //columns[i].grade.print();\n                //m_ji.print();\n                bool is_minimal = true;\n                for(auto& el : minimal_elements_tmp){\n                    if(el.leq_poset(m_ji)){\n                        is_minimal = false;\n                        break;\n                    }\n                }\n                //std::cout << \"Is minimal: \" << is_minimal << \"\\n\";\n                if(is_minimal){\n                    minimal_elements_tmp.push_back(m_ji);\n                    minimal_indices_tmp.push_back(j);\n                }\n            }\n            std::vector<grade_t> minimal_elements;\n            std::vector<size_t> minimal_indices;\n            for(size_t j=0; j<minimal_elements_tmp.size(); j++){\n                bool is_minimal = true;\n                for(size_t k=0; k<minimal_elements_tmp.size(); k++){\n                    if(k!=j && minimal_elements_tmp[k].leq_poset(minimal_elements_tmp[j])){\n                        is_minimal = false;\n                        break;\n                    }\n                }\n                if(is_minimal){\n                    minimal_elements.push_back(minimal_elements_tmp[j]);\n                    minimal_indices.push_back(minimal_indices_tmp[j]);\n                }\n            }\n            /*spdlog::info(\"Minimal elements...\");\n            for(auto& min_el : minimal_elements){\n                min_el.print();\n            }*/\n            for(size_t j=0; j<minimal_elements.size(); j++){\n                SignatureColumn column_to_reduce(columns[i]);\n                column_to_reduce.plus(columns[minimal_indices[j]]);\n                SignatureColumn syzygy(column_to_reduce.grade, -1);\n                index_t pivot = column_to_reduce.get_pivot().get_index();\n                while(pivot != -1){\n                    if(pivot_partition.find(pivot) == pivot_partition.end()){\n                        throw \"Unkown pivot.\";\n                    }\n                    bool has_reduced = false;\n                    for(auto& column : pivot_partition[pivot]){\n                        if(column.grade.leq_poset(column_to_reduce.grade)){\n                            column_to_reduce.plus(column);\n                            syzygy.push(column_entry_t(1, column.signature_index));\n                            has_reduced = true;\n                            break;\n                        }\n                    }\n                    if(!has_reduced){\n                        throw \"Could not reduce column.\";\n                    }\n                    pivot = column_to_reduce.get_pivot().get_index();\n                }\n                syzygy.push(column_entry_t(1, columns[i].signature_index));\n                syzygy.push(column_entry_t(1, columns[minimal_indices[j]].signature_index));\n                if(syzygy.get_pivot().get_index() != -1){\n                    syzygies.push_back(syzygy);\n                }\n                \n            }\n        }\n    }\n    return syzygies;\n}\n\nMatrix compute_minimal_generating_set(Matrix& generators){\n    /** Computes a minimal generating set for the module described by the columns in 'generators'.\n     \n     Arguments:\n     generators {Matrix} -- a matrix whose columns a generators of a module.\n     \n     Returns:\n     Matrix -- a subset of the columns of 'generators' that constitute a minimal set of generators for the module.\n     */\n    \n    /* Vectors to store the columns of the GBs */\n    std::cout << \"Starting to compute minimal generating set for columns of size: \" << generators.size() << std::endl;\n    \n    /* Sort columns colexicographically */\n    sort(generators.begin(), generators.end(), [ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade.lt_colex(rhs.grade);\n         });\n    \n    Matrix gb_columns;\n    \n    /* Index maps to keep track of signatures */\n    std::vector<std::vector<signature_t>> GB; //The columns of 'generators' with a non-empty signature list is a generator.\n    std::vector<std::vector<signature_t>> Syz;\n    \n    for(size_t i=0; i<generators.size(); i++){\n        GB.push_back(std::vector<signature_t>());\n        Syz.push_back(std::vector<signature_t>());\n        generators[i].signature_index = i;\n    }\n    \n    hash_map<size_t, size_t> index_map_high;\n    for(size_t i=0; i<generators.size(); i++){\n        generators[i].signature_index = i;\n        index_map_high[generators[i].grade[generators[i].grade.size()-1]] = i;\n    }\n    \n    std::vector<grade_t> index_list;\n    for(size_t column_index=0 ; column_index<generators.size(); column_index++){\n        index_list.push_back(generators[column_index].grade);\n    }\n    sort(index_list.begin(), index_list.end()); // Sort grades lexicographically\n    \n    \n    index_t max_pivot=0;\n    for(auto& generator : generators){\n        if(max_pivot < generator.get_pivot_index()){\n            max_pivot = generator.get_pivot_index();\n        }\n    }\n    \n    std::vector<size_t> grade_hashes;\n    grade_hashes.reserve(generators.size());\n    GradeHasher grade_hasher;\n    for(auto& c : generators){\n        grade_hashes.push_back(grade_hasher(c.grade));\n    }\n    \n    /* Main algorithm that iterates through the index set */\n    int column_index;\n    index_t pivot;\n    std::vector<index_t> pivot_map(max_pivot+1, -1);\n    int iter_index = 0;\n    \n    for(size_t index=0 ; index<index_list.size(); index++){\n        if(index > 0 && index_list[index]==index_list[index-1]){\n            continue;\n        }\n        grade_t v = index_list[index];\n        iter_index++;\n        size_t grade_hash = grade_hasher(v);\n        \n        \n        /* Initialize Macaulay matrix */\n        for( size_t i=0; i<=index_map_high[v[v.size()-1]]; i++ ){\n            column_index = -1;\n            bool is_new=false;\n            if(GB[i].size() > 0){\n                bool in_syz = false;\n                if(Syz[i].size()>0){\n                    for(size_t j=Syz[i].size()-1; j < Syz[i].size(); j--){\n                        if((Syz[i][j].get_grade()).leq_poset(v)){\n                            in_syz = true;\n                            break;\n                        }\n                    }\n                }\n                if(!in_syz){\n                    for(size_t j=GB[i].size()-1; j < GB[i].size(); j--){\n                        if(GB[i][j].get_grade().leq_poset(v)){\n                            column_index = (int)GB[i][j].get_index();\n                            break;\n                        }\n                    }\n                }\n            } else{\n                if(grade_hash == grade_hashes[i] && generators[i].grade == v){\n                    gb_columns.push_back(generators[i]);\n                    column_index = (int)gb_columns.size()-1;\n                    is_new=true;\n                }\n            }\n            if(column_index > -1){\n                pivot = gb_columns[column_index].get_pivot().get_index();\n                if(pivot > -1 && pivot_map[pivot] > -1 && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                    SignatureColumn working_column = gb_columns[column_index];\n                    while(pivot != -1 && pivot_map[pivot] > -1 && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                        working_column.plus(gb_columns[pivot_map[pivot]]);\n                        pivot = working_column.get_pivot().get_index();\n                    }\n                    if(is_new){\n                        gb_columns.pop_back();\n                    }\n                    if(pivot != -1){\n                        working_column.refresh();\n                        working_column.syzygy.refresh();\n                        gb_columns.push_back(working_column);\n                        GB[i].push_back(signature_t(working_column.grade, gb_columns.size()-1));\n                        pivot_map[pivot] = gb_columns.size()-1;\n                        gb_columns[gb_columns.size()-1].last_updated = iter_index;\n                    }else{\n                        working_column.syzygy.refresh();\n                        Syz[i].push_back(signature_t(working_column.grade, -1));\n                    }\n                } else{\n                    if(pivot != -1){\n                        pivot_map[pivot] = column_index;\n                        gb_columns[column_index].last_updated = iter_index;\n                        if(is_new){\n                            GB[i].push_back(signature_t(gb_columns[column_index].grade, column_index));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    Matrix minimal_generating_set;\n    for(size_t column_index=0 ; column_index<generators.size(); column_index++){\n        if(GB[column_index].size()>0){\n            minimal_generating_set.push_back(generators[column_index]);\n        }\n    }\n    //get_mem_usage(virt_memory, res_memory);\n    return minimal_generating_set;\n}\n\nstd::pair<Matrix, Matrix> compute_minimal_generating_set2(Matrix generators){\n    /** Computes a minimal generating set for the module described by the columns in 'generators'.\n     \n     Arguments:\n     generators {Matrix} -- a matrix whose columns a generators of a module.\n     \n     Returns:\n     Matrix -- a subset of the columns of 'generators' that constitute a minimal set of generators for the module.\n     */\n    \n    /* Vectors to store the columns of the GBs */\n    std::cout << \"Starting to compute minimal generating set for columns of size: \" << generators.size()  << std::endl;\n    \n    for(size_t i=0; i<generators.size(); i++){\n        generators[i].signature_index = i;\n    }\n    \n    /* Sort columns colexicographically */\n    sort(generators.begin(), generators.end(), [ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade.lt_colex(rhs.grade);\n         });\n    \n    hash_map<size_t, size_t> reorder_map;\n    for(size_t i=0; i<generators.size(); i++){\n        reorder_map[i] = generators[i].signature_index;\n    }\n    \n    Matrix gb_columns;\n    std::vector<SyzColumn> syzygies;\n    \n    /* Index maps to keep track of signatures */\n    std::vector<std::vector<signature_t>> GB; //The columns of 'generators' with a non-empty signature list is a generator.\n    std::vector<std::vector<signature_t>> Syz;\n    \n    for(size_t i=0; i<generators.size(); i++){\n        GB.push_back(std::vector<signature_t>());\n        Syz.push_back(std::vector<signature_t>());\n        generators[i].signature_index = i;\n        generators[i].syzygy = SyzColumn();\n        generators[i].syzygy.push(column_entry_t(1, i));\n    }\n    \n    hash_map<size_t, size_t> index_map_high;\n    for(size_t i=0; i<generators.size(); i++){\n        index_map_high[generators[i].grade[generators[i].grade.size()-1]] = i;\n    }\n    \n    std::vector<grade_t> index_list;\n    for(size_t column_index=0 ; column_index<generators.size(); column_index++){\n        index_list.push_back(generators[column_index].grade);\n    }\n    sort(index_list.begin(), index_list.end()); // Sort grades lexicographically\n    \n    index_t max_pivot=0;\n    for(auto& generator : generators){\n        if(max_pivot < generator.get_pivot().get_index()){\n            max_pivot = generator.get_pivot().get_index();\n        }\n    }\n    \n    std::vector<size_t> grade_hashes;\n    grade_hashes.reserve(generators.size());\n    GradeHasher grade_hasher;\n    for(auto& c : generators){\n        grade_hashes.push_back(grade_hasher(c.grade));\n    }\n    \n    /* Main algorithm that iterates through the index set */\n    int column_index;\n    index_t pivot;\n    \n    int iter_index = 0;\n    \n    for(size_t index=0 ; index<index_list.size(); index++){\n       // if(index > 0 && index_list[index]==index_list[index-1]){\n       //     continue;\n       // }\n        grade_t& v = index_list[index];\n        iter_index++;\n        std::vector<index_t> pivot_map(max_pivot+1, -1);\n        size_t grade_hash = grade_hasher(v);\n        /* Initialize Macaulay matrix */\n        for( size_t i=0; i<generators.size(); i++ ){\n            column_index = -1;\n            bool is_new=false;\n            if(GB[i].size() > 0){\n                bool in_syz = false;\n                if(Syz[i].size()>0){\n                    for(size_t j=Syz[i].size()-1; j < Syz[i].size(); j--){\n                        if((Syz[i][j].get_grade()).leq_poset(v)){\n                            in_syz = true;\n                            break;\n                        }\n                    }\n                }\n                if(!in_syz){\n                    for(size_t j=GB[i].size()-1; j < GB[i].size(); j--){\n                        if(GB[i][j].get_grade().leq_poset(v)){\n                            column_index = (int)GB[i][j].get_index();\n                            break;\n                        }\n                    }\n                }\n            } else{\n                if(grade_hash == grade_hashes[i] && generators[i].grade == v){\n                    gb_columns.push_back(generators[i]);\n                    column_index = (int)gb_columns.size()-1;\n                    is_new=true;\n                }\n            }\n            if(column_index > -1){\n                pivot = gb_columns[column_index].get_pivot().get_index();\n                if(pivot > -1 && pivot_map[pivot] > -1){\n                    SignatureColumn working_column(gb_columns[column_index]);\n                    SyzColumn syz;\n                    while(pivot != -1 && pivot_map[pivot] > -1){\n                        working_column.plus(gb_columns[pivot_map[pivot]]);\n                        syz.plus(gb_columns[pivot_map[pivot]].syzygy);\n                        pivot = working_column.get_pivot().get_index();\n                    }\n                    if(pivot != -1){\n                        working_column.refresh();\n                        working_column.syzygy.refresh();\n                        gb_columns.push_back(working_column);\n                        GB[i].push_back(signature_t(working_column.grade, gb_columns.size()-1));\n                        pivot_map[pivot] = gb_columns.size()-1;\n                        gb_columns[gb_columns.size()-1].last_updated = iter_index;\n                    }else{\n                        working_column.syzygy.refresh();\n                        syz.refresh();\n                        syzygies.push_back(syz);\n                        Syz[i].push_back(signature_t(working_column.grade, syzygies.size()-1));\n                    }\n                } else{\n                    if(pivot != -1){\n                        pivot_map[pivot] = column_index;\n                        gb_columns[column_index].last_updated = iter_index;\n                        if(is_new){\n                            GB[i].push_back(signature_t(gb_columns[column_index].grade, column_index));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    Matrix minimal_generating_set;\n    Matrix change_of_basis_map;\n    hash_map<size_t, size_t> reindex_map;\n    for(size_t column_index=0 ; column_index<generators.size(); column_index++){\n        if(GB[column_index].size()>0){\n            reindex_map[column_index] = minimal_generating_set.size();\n            minimal_generating_set.push_back(generators[column_index]);\n            SignatureColumn column(generators[column_index].grade, reorder_map[column_index]);\n            column.push(column_entry_t(1, reindex_map[column_index]));\n            change_of_basis_map.push_back(column);\n        }else{\n            SignatureColumn column(generators[column_index].grade, reorder_map[column_index]);\n            index_t pivot = syzygies[Syz[column_index][0].get_index()].get_pivot_index();\n            while(pivot != -1){\n                column.push(column_entry_t(1, reindex_map[pivot]));\n                syzygies[Syz[column_index][0].get_index()].pop_pivot();\n                pivot = syzygies[Syz[column_index][0].get_index()].get_pivot_index();\n            }\n            change_of_basis_map.push_back(column);\n        }\n    }\n    \n    sort(change_of_basis_map.begin(), change_of_basis_map.end(), [ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.signature_index < rhs.signature_index;\n         });\n    get_mem_usage(virt_memory, res_memory);\n    std::cout << \"Finished computing minimal generating set of size: \" << minimal_generating_set.size();\n    return std::pair<Matrix, Matrix>(minimal_generating_set, change_of_basis_map);\n}\n\n\nbool cmpID(const signature_t& lhs, const signature_t& rhs)\n{\n    return lhs.first.lt_colex(rhs.first);\n}\n\nvoid insert_sorted( std::vector<signature_t>& cont, signature_t value ) {\n    std::vector<signature_t>::iterator it = std::upper_bound( cont.begin(), cont.end(), value, cmpID); // find proper position in descending order\n    cont.insert( it, value ); // insert before iterator it\n}\n\nstd::pair<Matrix, hash_map<size_t, grade_t>> computePresentationDeg_imopt(Matrix& image_columns, Matrix& columns, bool debug=true){\n    /*\n     The main function computing a Groebner basis for the image and kernel of the map described by the list of columns 'columns'.\n     \n     Arguments:\n     image_columns {std::vector<SignatureColumn>} -- a minimal generating set of the image map.\n     columns {std::vector<SignatureColumn>} -- columns describing the matrix of a map between two free multigraded modules.\n     \n     Returns:\n     std::vector<SignatureColumn> -- a list of vectors decribing a minimal Groebner basis for the image of the map.\n     std::vector<SignatureColumn> -- a list of vectors describing a minimal Groebner basis for the kernel of the map.\n     */\n    \n    std::cout << \"Starting to presentation degree by degree...\"  << std::endl;\n    \n    /* Sort columns colexicographically */\n    sort(columns.begin(), columns.end(), [ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade.lt_colex(rhs.grade);\n         });\n    sort(image_columns.begin(), image_columns.end(), [ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade<rhs.grade;\n         });\n    // The sorted columns should agree with the columns sorted by index of signature\n    hash_map<size_t, size_t> index_map_high;\n    for(size_t i=0; i<columns.size(); i++){\n        columns[i].signature_index = i;\n        columns[i].syzygy = SyzColumn();\n        columns[i].syzygy.push(column_entry_t(1, i));\n        index_map_high[columns[i].grade[columns[i].grade.size()-1]] = i;\n    }\n    \n    /* Compute index set iterator */\n    std::priority_queue<grade_t, std::vector<grade_t>, std::greater<grade_t>> grades;\n    std::vector<std::vector<grade_t>> grade_lists;\n    std::vector<std::vector<grade_t>> grade_listsH;\n    \n    /* Vectors to store the columns of the GBs */\n    Matrix gb_columns, gb_columnsH, syzygiesH;\n    \n    \n    /* Index maps to keep track of signatures */\n    std::vector<std::vector<signature_t>> GB, GBH;\n    std::vector<std::vector<signature_t>> Syz, SyzH;\n    \n    for(size_t i=0; i<columns.size(); i++){\n        GB.push_back(std::vector<signature_t>());\n        Syz.push_back(std::vector<signature_t>());\n    }\n    \n    /* Main algorithm that iterates through the index set */\n    int column_index;\n    index_t max_pivot=0;\n    for(auto& column : columns){\n        if(max_pivot < column.get_pivot_index()){\n            max_pivot = column.get_pivot_index();\n        }\n    }\n    for(size_t i=0; i<=max_pivot; i++){\n        grade_lists.push_back(std::vector<grade_t>());\n    }\n    for(auto& column : columns){\n        grades.push(column.grade);\n        grade_listsH.push_back(std::vector<grade_t>());\n    }\n    for(auto& column : image_columns){\n        grades.push(column.grade);\n    }\n    index_t pivot;\n    \n    std::vector<index_t> pivot_map(max_pivot+1, -1);\n    std::vector<index_t> pivot_mapH(columns.size(), -1);\n    \n    std::vector<size_t> grade_hashes;\n    grade_hashes.reserve(columns.size());\n    GradeHasher grade_hasher;\n    for(auto& c : columns){\n        grade_hashes.push_back(grade_hasher(c.grade));\n    }\n    \n    std::vector<signature_t> reorder_Z_map;\n    \n    std::set<size_t> syz_pivots;\n    \n    size_t image_index=0;\n    \n    \n    int iter_index = 0;\n    while(!grades.empty()){\n        grade_t v = grades.top();\n        while(v == grades.top()){\n            grades.pop();\n        }\n    \n        iter_index++;\n        size_t grade_hash = grade_hasher(v);\n        \n        // B^h_z\n        for( auto& signature : reorder_Z_map ){\n            size_t i = signature.get_index();\n            column_index = -1;\n            //bool in_syz = false;\n            //size_t syz_size = SyzH[i].size();\n            if(SyzH[i].size()==0 && GBH[i][0].get_grade().leq_poset(v)){\n                size_t gb_size = GBH[i].size();\n                column_index = (int)GBH[i][0].get_index();\n                for(size_t j=gb_size-1; j >= 1; j--){\n                    if(GBH[i][j].get_grade().leq_poset(v)){\n                        column_index = (int)GBH[i][j].get_index();\n                        break;\n                    }\n                }\n                /*for(size_t j=syz_size-1; j < syz_size; j--){\n                    if((SyzH[i][j].get_grade()).leq_poset(v)){\n                        in_syz = true;\n                        break;\n                    }\n                }*/\n            }\n            \n            /*if(!in_syz){\n                size_t gb_size = GBH[i].size();\n                for(size_t j=gb_size-1; j < gb_size; j--){\n                    if(GBH[i][j].get_grade().leq_poset(v)){\n                        column_index = (int)GBH[i][j].get_index();\n                        break;\n                    }\n                }\n            }*/\n            \n            \n            if(column_index > -1){\n                pivot = gb_columnsH[column_index].get_pivot_index();\n                if(pivot > -1 && pivot_mapH[pivot] > -1 && gb_columnsH[pivot_mapH[pivot]].last_updated == iter_index){\n                    SignatureColumn working_column = gb_columnsH[column_index];\n                    while(pivot != -1 && pivot_mapH[pivot] > -1 && gb_columnsH[pivot_mapH[pivot]].last_updated == iter_index){\n                        working_column.plus(gb_columnsH[pivot_mapH[pivot]]);\n                        pivot = working_column.get_pivot_index();\n                    }\n                    if(pivot != -1){\n                        working_column.refresh();\n                        working_column.syzygy.refresh();\n                        grade_t grade = working_column.grade;\n                        /*if(GBH[i].size()==1){\n                            gb_columnsH.push_back(working_column);\n                            GBH[i].push_back(signature_t(grade, gb_columnsH.size()-1));\n                        }else{\n                            if(pivot_mapH[gb_columnsH[GBH[i][1].get_index()].get_pivot_index()] == GBH[i][1].get_index()){\n                                pivot_mapH[gb_columnsH[GBH[i][1].get_index()].get_pivot_index()] = -1;\n                            }\n                            gb_columnsH[GBH[i][1].get_index()] = working_column;\n                            GBH[i][1].first = grade;\n                        }*/\n                        gb_columnsH.push_back(working_column);\n                        GBH[i].push_back(signature_t(grade, gb_columnsH.size()-1));\n                        pivot_mapH[pivot] = gb_columnsH.size()-1;\n                        gb_columnsH[gb_columnsH.size()-1].last_updated = iter_index;\n                        if(grade == v){\n                            if(grade_listsH[pivot].size() == 0 || grade != grade_listsH[pivot].back()){\n                                std::vector<grade_t> minimal_elements_tmp;\n                                for(size_t j=0; j<grade_listsH[pivot].size(); j++){\n                                    grade_t m_ji = grade_listsH[pivot][j].m_ji(grade);\n                                    bool is_minimal = true;\n                                    for(auto& el : minimal_elements_tmp){\n                                        if(el.leq_poset_m(m_ji)){\n                                            is_minimal = false;\n                                            break;\n                                        }\n                                    }\n                                    if(is_minimal){\n                                        minimal_elements_tmp.push_back(m_ji);\n                                        grades.push(grade.join(grade_listsH[pivot][j]));\n                                    }\n                                }\n                                grade_listsH[pivot].push_back(grade);\n                            }\n                        }\n                    }else{\n                        working_column.syzygy.refresh();\n                       // if(syz_pivots.find(i) == syz_pivots.end()){\n                            syzygiesH.push_back(SignatureColumn(working_column.grade, syzygiesH.size(), working_column.syzygy));\n                            SyzH[i].push_back(signature_t(working_column.grade, syzygiesH.size()-1));\n                            syzygiesH[syzygiesH.size()-1].last_updated = iter_index;\n                      /*  }else{\n                            SyzH[i].push_back(signature_t(working_column.grade, syzygiesH.size()-1));\n                        }*/\n                    }\n                } else{\n                    if(pivot != -1){\n                        pivot_mapH[pivot] = column_index;\n                        gb_columnsH[column_index].last_updated = iter_index;\n                    }\n                }\n            }\n        }\n        \n        /* Reduce image columns */\n        while(image_index < image_columns.size() && image_columns[image_index].grade == v){\n            SignatureColumn working_column(image_columns[image_index]);\n            working_column.syzygy = SyzColumn();\n            pivot = working_column.get_pivot_index();\n            while(pivot != -1 && pivot_mapH[pivot] != -1 && gb_columnsH[pivot_mapH[pivot]].last_updated == iter_index){\n                working_column.plus(gb_columnsH[pivot_mapH[pivot]]);\n                pivot = working_column.get_pivot_index();\n            }\n            working_column.syzygy.refresh();\n            if(pivot != -1){\n                //throw \"Found non-reduced image column\";\n                working_column.refresh();\n                working_column.signature_index = GBH.size();\n                GBH.push_back(std::vector<signature_t>());\n                SyzH.push_back(std::vector<signature_t>());\n                gb_columnsH.push_back(working_column);\n                GBH[GBH.size()-1].push_back(signature_t(working_column.grade, gb_columnsH.size()-1));\n                insert_sorted(reorder_Z_map, signature_t(working_column.grade, GBH.size()-1));\n                pivot_mapH[pivot] = gb_columnsH.size()-1;\n                gb_columnsH[gb_columnsH.size()-1].last_updated = iter_index;\n                if(grade_listsH[pivot].size() == 0 || working_column.grade != grade_listsH[pivot].back()){\n                    std::vector<grade_t> minimal_elements_tmp;\n                    for(size_t j=0; j<grade_listsH[pivot].size(); j++){\n                        grade_t m_ji = grade_listsH[pivot][j].m_ji(working_column.grade);\n                        bool is_minimal = true;\n                        for(auto& el : minimal_elements_tmp){\n                            if(el.leq_poset_m(m_ji)){\n                                is_minimal = false;\n                                break;\n                            }\n                        }\n                        if(is_minimal){\n                            minimal_elements_tmp.push_back(m_ji);\n                            grades.push(working_column.grade.join(grade_listsH[pivot][j]));\n                        }\n                    }\n                    grade_listsH[pivot].push_back(working_column.grade);\n                }\n                //working_column.syzygy = SyzColumn();\n                //working_column.syzygy.push(column_entry_t(1, gb_columnsH.size()-1));\n                //syzygiesH.push_back(SignatureColumn(working_column.grade, syzygiesH.size(), working_column.syzygy));\n            }else{\n                syzygiesH.push_back(SignatureColumn(working_column.grade, syzygiesH.size(), working_column.syzygy));\n                //syz_pivots.insert(working_column.syzygy.get_pivot_index());\n            }\n            image_index++;\n        }\n        \n        /* Initialize Macaulay matrix */\n        size_t& index_bound = index_map_high[v[v.size()-1]];\n        for( size_t i=0; i<=index_bound; i++ ){\n            column_index = -1;\n            bool is_new=false;\n            if(GB[i].size() > 0){\n                if(pivot_mapH[i] == -1 || gb_columnsH[pivot_mapH[i]].last_updated != iter_index){\n                    for(size_t j=GB[i].size()-1; j < GB[i].size(); j--){\n                        if(GB[i][j].get_grade().leq_poset(v)){\n                            column_index = (int)GB[i][j].get_index();\n                            break;\n                        }\n                    }\n                }\n            } else{\n                if(pivot_mapH[i] == -1 && grade_hash == grade_hashes[i] && columns[i].grade == v){\n                    gb_columns.push_back(columns[i]);\n                    column_index = (int)gb_columns.size()-1;\n                    is_new=true;\n                }\n            }\n            if(column_index > -1){\n                pivot = gb_columns[column_index].get_pivot_index();\n                if(pivot != -1 && pivot_map[pivot] != -1 && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                    SignatureColumn working_column = gb_columns[column_index];\n                    while(pivot != -1 && pivot_map[pivot] != -1 && gb_columns[pivot_map[pivot]].last_updated == iter_index){\n                        working_column.plus(gb_columns[pivot_map[pivot]]);\n                        pivot = working_column.get_pivot_index();\n                    }\n                    if(pivot != -1){\n                        working_column.refresh();\n                        working_column.syzygy.refresh();\n                        grade_t grade = working_column.grade;\n                        if(is_new){\n                            gb_columns[column_index] = working_column;\n                            GB[i].push_back(signature_t(grade, column_index));\n                            pivot_map[pivot] = column_index;\n                            gb_columns[column_index].last_updated = iter_index;\n                        }else{\n                            /*if(GB[i].size()==1){\n                                gb_columns.push_back(working_column);\n                                GB[i].push_back(signature_t(grade, gb_columns.size()-1));\n                            }else{\n                                if(pivot_map[gb_columns[GB[i][1].get_index()].get_pivot_index()] == GB[i][1].get_index()){\n                                    pivot_map[gb_columns[GB[i][1].get_index()].get_pivot_index()] = -1;\n                                }\n                                gb_columns[GB[i][1].get_index()] = working_column;\n                                GB[i][1].first = grade;\n                            }*/\n                            gb_columns.push_back(working_column);\n                            GB[i].push_back(signature_t(grade, gb_columns.size()-1));\n                            pivot_map[pivot] = gb_columns.size()-1;\n                            gb_columns[gb_columns.size()-1].last_updated = iter_index;\n                        }\n                        if(grade == v){\n                            if(grade_lists[pivot].size() == 0 || grade != grade_lists[pivot].back()){\n                                std::vector<grade_t> minimal_elements_tmp;\n                                for(size_t j=0; j<grade_lists[pivot].size(); j++){\n                                    grade_t m_ji = grade_lists[pivot][j].m_ji(grade);\n                                    bool is_minimal = true;\n                                    for(auto& el : minimal_elements_tmp){\n                                        if(el.leq_poset_m(m_ji)){\n                                            is_minimal = false;\n                                            break;\n                                        }\n                                    }\n                                    if(is_minimal){\n                                        minimal_elements_tmp.push_back(m_ji);\n                                        grades.push(grade.join(grade_lists[pivot][j]));\n                                    }\n                                }\n                                grade_lists[pivot].push_back(grade);\n                            }\n                        }\n                    }else{\n                        if(is_new){\n                            gb_columns.pop_back();\n                        }\n                        working_column.syzygy.refresh();\n                        SignatureColumn syz(working_column.grade, GBH.size(), working_column.syzygy);\n                        syz.syzygy.push(column_entry_t(1, GBH.size()));\n                        GBH.push_back(std::vector<signature_t>());\n                        SyzH.push_back(std::vector<signature_t>());\n                        gb_columnsH.push_back(syz);\n                        GBH[GBH.size()-1].push_back(signature_t(syz.grade, gb_columnsH.size()-1));\n                        insert_sorted(reorder_Z_map, signature_t(working_column.grade, GBH.size()-1));\n                        pivot_mapH[i] = gb_columnsH.size()-1;\n                        gb_columnsH[gb_columnsH.size()-1].last_updated = iter_index;\n                        if(working_column.grade == v){\n                            if(grade_listsH[i].size() == 0 || working_column.grade != grade_listsH[i].back()){\n                                std::vector<grade_t> minimal_elements_tmp;\n                                for(size_t j=0; j<grade_listsH[i].size(); j++){\n                                    grade_t m_ji = grade_listsH[i][j].m_ji(working_column.grade);\n                                    bool is_minimal = true;\n                                    for(auto& el : minimal_elements_tmp){\n                                        if(el.leq_poset_m(m_ji)){\n                                            is_minimal = false;\n                                            break;\n                                        }\n                                    }\n                                    if(is_minimal){\n                                        minimal_elements_tmp.push_back(m_ji);\n                                        grades.push(working_column.grade.join(grade_listsH[i][j]));\n                                    }\n                                }\n                                grade_listsH[i].push_back(working_column.grade);\n                            }\n                        }\n                    }\n                } else{\n                    if(pivot != -1){\n                        if(is_new){\n                            GB[i].push_back(signature_t(gb_columns[column_index].grade, column_index));\n                            pivot_map[pivot] = column_index;\n                            gb_columns[column_index].last_updated = iter_index;\n                            if(grade_lists[pivot].size() == 0 || gb_columns[column_index].grade != grade_lists[pivot].back()){\n                                std::vector<grade_t> minimal_elements_tmp;\n                                for(size_t j=0; j<grade_lists[pivot].size(); j++){\n                                    grade_t m_ji = grade_lists[pivot][j].m_ji(gb_columns[column_index].grade);\n                                    bool is_minimal = true;\n                                    for(auto& el : minimal_elements_tmp){\n                                        if(el.leq_poset_m(m_ji)){\n                                            is_minimal = false;\n                                            break;\n                                        }\n                                    }\n                                    if(is_minimal){\n                                        minimal_elements_tmp.push_back(m_ji);\n                                        grades.push(gb_columns[column_index].grade.join(grade_lists[pivot][j]));\n                                    }\n                                }\n                                grade_lists[pivot].push_back(gb_columns[column_index].grade);\n                            }\n                        }else{\n                            pivot_map[pivot] = column_index;\n                            gb_columns[column_index].last_updated = iter_index;\n                        }\n                    } else {\n                        if(is_new){\n                            SignatureColumn working_column = gb_columns[column_index];\n                            SyzColumn syz_column = SyzColumn();\n                            syz_column.push(column_entry_t(1, column_index));\n                            SignatureColumn syz(working_column.grade, GBH.size(), syz_column);\n                            syz.syzygy.push(column_entry_t(1, GBH.size()));\n                            GBH.push_back(std::vector<signature_t>());\n                            SyzH.push_back(std::vector<signature_t>());\n                            gb_columnsH.push_back(syz);\n                            GBH[GBH.size()-1].push_back(signature_t(syz.grade, gb_columnsH.size()-1));\n                            insert_sorted(reorder_Z_map, signature_t(working_column.grade, GBH.size()-1));\n                            pivot_mapH[i] = gb_columnsH.size()-1;\n                            gb_columnsH[gb_columnsH.size()-1].last_updated = iter_index;\n                            if(working_column.grade == v){\n                                if(grade_listsH[i].size() == 0 || working_column.grade != grade_listsH[i].back()){\n                                    std::vector<grade_t> minimal_elements_tmp;\n                                    for(size_t j=0; j<grade_listsH[i].size(); j++){\n                                        grade_t m_ji = grade_listsH[i][j].m_ji(working_column.grade);\n                                        bool is_minimal = true;\n                                        for(auto& el : minimal_elements_tmp){\n                                            if(el.leq_poset_m(m_ji)){\n                                                is_minimal = false;\n                                                break;\n                                            }\n                                        }\n                                        if(is_minimal){\n                                            minimal_elements_tmp.push_back(m_ji);\n                                            grades.push(working_column.grade.join(grade_listsH[i][j]));\n                                        }\n                                    }\n                                    grade_listsH[i].push_back(working_column.grade);\n                                }\n                            }\n                        \n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    hash_map<size_t, grade_t> row_grade_map;\n    for(size_t j=0; j<gb_columnsH.size(); j++){\n        row_grade_map[j] = grade_t(gb_columnsH[j].grade);\n    }\n\n    std::cout << \"Nonminimal presentation of size \"<< syzygiesH.size() << std::endl;\n    \n    \n    std::vector<index_t> rows;\n    for(auto& entry : row_grade_map){\n        rows.push_back(entry.first);\n    }\n    sort(rows.begin(), rows.end());\n    hash_map<size_t, size_t> row_index_map;\n    for(size_t i=0; i<rows.size(); i++){\n        row_index_map[rows[i]] = i;\n    }\n\n    syzygiesH = compute_minimal_generating_set(syzygiesH);\n\n//get_mem_usage(virt_memory, res_memory);\n    return std::pair<Matrix, hash_map<size_t, grade_t>>(syzygiesH, row_grade_map);\n}\n\nstd::pair<Matrix, hash_map<size_t, grade_t>> compute_presentation_2p(Matrix& image_generators, Matrix& generating_set_kernel){\n    /** Computes a minimal presentation of the ith homology module using generators of the kernel and image of\n     the boundary matrices \\Delta_{i-1} and \\Delta_i respectively.\n     \n     Arguments:\n     image_generators {Matrix} -- a generating set of the image of the boundary map \\Delta_i.\n     kernel_generators {Matrix} -- a Groebner basis of the kernel of the boundary matrix \\Delta_{i-1}.\n     \n     Returns:\n     Matrix -- a matrix describing a minimal presentation of the ith homology module.\n     \n     */\n    \n    std::cout << \"Starting to compute presentation...\";\n    Matrix generating_set_image = compute_minimal_generating_set(image_generators);\n    \n    //Sort image and kernel gens in colex and lex respectively\n   sort(generating_set_kernel.begin(), generating_set_kernel.end(),[ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade.lt_colex(rhs.grade) ;\n         });\n     sort(generating_set_image.begin(), generating_set_image.end(),[ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade < rhs.grade ;\n         });\n    \n    generating_set_kernel.print();\n    hash_map<size_t, grade_t> row_grade_map;\n    for(size_t j=0; j<generating_set_kernel.size(); j++){\n        row_grade_map[j] = grade_t(generating_set_kernel[j].grade);\n        row_grade_map[j].print();\n    }\n    for(size_t i=0; i<generating_set_kernel.size(); i++){\n        generating_set_kernel[i].syzygy = SyzColumn();\n        generating_set_kernel[i].syzygy.push(column_entry_t(1, i));\n    }\n    \n    std::cout << \"Expressing the image columns in terms of the kernel...\";\n    \n    hash_map<size_t, size_t> index_map_low, index_map_high;\n    for(size_t i=0; i<generating_set_kernel.size(); i++){\n        generating_set_kernel[i].signature_index = i;\n        index_map_high[generating_set_kernel[i].grade.back()] = i;\n        if(index_map_low.find(generating_set_kernel[i].grade.back()) == index_map_low.end()){\n            index_map_low[generating_set_kernel[i].grade.back()] = i;\n        }\n    }\n    \n    \n    /* Main algorithm that iterates through the index set */\n    index_t max_pivot=0;\n    for(auto& generator : generating_set_kernel){\n        if(max_pivot < generator.get_pivot().get_index()){\n            max_pivot = generator.get_pivot().get_index();\n        }\n    }\n    index_t pivot;\n    std::vector<index_t> pivot_map(max_pivot+1, -1);\n    Matrix presentation_matrix;\n    presentation_matrix.reserve(generating_set_image.size());\n    for(auto& column : generating_set_image){\n        grade_t& v = column.grade;\n        \n        /* Initialize Macaulay matrix */\n        for( size_t i=0; i<=index_map_high[v.back()]; i++ ){\n            if(generating_set_kernel[i].size()>0 && generating_set_kernel[i].grade[0] <= v[0]){\n                pivot = generating_set_kernel[i].get_pivot().get_index();\n                if(pivot_map[pivot] > -1 && pivot_map[pivot] < i){\n                    SignatureColumn& working_column = generating_set_kernel[i];\n                    while(pivot != -1 && pivot_map[pivot] > -1 && pivot_map[pivot] < i){\n                        working_column.plus(generating_set_kernel[pivot_map[pivot]]);\n                        pivot = working_column.get_pivot().get_index();\n                    }\n                    if(pivot != -1){\n                        working_column.refresh();\n                        working_column.syzygy.refresh();\n                        pivot_map[pivot] = i;\n                    }\n                } else{\n                    if(pivot != -1){\n                        pivot_map[pivot] = i;\n                    }\n                }\n            }\n        }\n        \n        \n        // Reduce the image column with the pivot set.\n        column.syzygy = SyzColumn();\n        while(true){\n            pivot = column.get_pivot().get_index();\n            if(pivot != -1){\n                if(pivot_map[pivot] == -1){\n                    std::cerr << \"Cannot express image column in terms of kernel. Throwing exception...\";\n                    throw \"Failed to express image column in terms of kernel generating set.\";\n                }\n                column.plus(generating_set_kernel[pivot_map[pivot]]);\n            }else{\n                break;\n            }\n        }\n        presentation_matrix.push_back(SignatureColumn(column.grade, column.signature_index, column.syzygy));\n        presentation_matrix.back().refresh();\n    }\n    \n    \n    presentation_matrix.print();\n    for(auto& column : presentation_matrix){\n        column.grade.print();\n    }\n    \n    hash_map<size_t, size_t> pairs = compute_local_pairs(presentation_matrix, row_grade_map);\n    \n    std::set<size_t> negative_columns;\n    presentation_matrix = compute_global_columns(presentation_matrix, pairs, negative_columns);\n    \n    for(auto& entry : pairs){\n        if(row_grade_map.find(entry.first) != row_grade_map.end()){\n            row_grade_map.erase(entry.first);\n        }\n    }\n    \n    \n    \n    // Reindex the rows of the presentation matrix to account for deleted rows\n    \n    std::vector<index_t> rows;\n    for(auto& entry : row_grade_map){\n        rows.push_back(entry.first);\n    }\n    sort(rows.begin(), rows.end());\n    hash_map<size_t, size_t> row_index_map;\n    for(size_t i=0; i<rows.size(); i++){\n        row_index_map[rows[i]] = i;\n    }\n    \n    Matrix minimized_presentation;\n    for(size_t i=0;i<presentation_matrix.size(); i++){\n        SignatureColumn column(presentation_matrix[i].grade, presentation_matrix[i].signature_index);\n        for(auto& entry : presentation_matrix[i]){\n            if(row_grade_map.find(entry) != row_grade_map.end()){\n                column.push(column_entry_t(entry, row_index_map[entry]));\n            }\n        }\n        minimized_presentation.push_back(column);\n    }\n    \n    std::cout << \"Finished computing presentation of size \"<< minimized_presentation.size();\n    return std::pair<Matrix, hash_map<size_t, grade_t>>(minimized_presentation, row_grade_map);\n}\n\nstd::pair<Matrix, hash_map<size_t, grade_t>> compute_presentation_schreyer(Matrix& image_generators, Matrix& kernel_generators, bool debug=false){\n    /** Input a minimal set of generators for the image and a Groebner basis for the kernel.\n     \n     */\n    std::cout << \"Starting to compute presentation using Schreyer's algorithm\"<< std::endl;\n    \n    sort(kernel_generators.begin(), kernel_generators.end(),[ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade < rhs.grade ;\n         });\n    \n    for(size_t i=0; i<kernel_generators.size(); i++){\n        kernel_generators[i].signature_index = i;\n        kernel_generators[i].syzygy = SyzColumn();\n        kernel_generators[i].syzygy.push(column_entry_t(1, i));\n    }\n    \n    /* Translate image matrix */\n    hash_map<index_t, std::vector<size_t>> pivots_indices;\n    pivots_indices.reserve(kernel_generators.size());\n    for(auto& column : kernel_generators){\n        if(pivots_indices.find(column.get_pivot_index()) == pivots_indices.end()){\n            pivots_indices[column.get_pivot_index()] = std::vector<size_t>();\n        }\n        pivots_indices[column.get_pivot_index()].push_back(column.signature_index);\n    }\n    \n    Matrix translated_image_columns;\n    for(auto& column : image_generators){\n        SignatureColumn working_column(column);\n        working_column.syzygy = SyzColumn();\n        index_t pivot = working_column.get_pivot_index();\n        while(pivot != -1){\n            bool has_eliminated = false;\n            std::vector<SignatureColumn> pivot_columns;\n            for(auto& pivot_index : pivots_indices[pivot]){\n                pivot_columns.push_back(kernel_generators[pivot_index]);\n                if(kernel_generators[pivot_index].grade.leq_poset(working_column.grade)){\n                    working_column.plus(kernel_generators[pivot_index]);\n                    has_eliminated = true;\n                    break;\n                }\n            }\n            if(!has_eliminated){\n                throw \"Cannot express image column in terms of kernel.\";\n            }\n            pivot = working_column.get_pivot_index();\n        }\n        translated_image_columns.push_back(SignatureColumn(working_column.grade, working_column.signature_index, working_column.syzygy));\n    }\n    \n    Matrix syzygy_module = compute_syzygy_module(kernel_generators);\n    std::cout << \"Computed Syzygy module of size: \"<< syzygy_module.size()<< std::endl;\n    for(auto& column : translated_image_columns){\n        syzygy_module.push_back(column);\n    }\n    \n    std::pair<Matrix, Matrix> m_pair = compute_minimal_generating_set2(kernel_generators);\n    Matrix& generating_set_kernel = m_pair.first;\n    Matrix& change_of_basis_map = m_pair.second;\n    \n    std::cout << \"Minimal generating set for kernel of size: \"<< generating_set_kernel.size()<< std::endl;\n    \n    hash_map<size_t, grade_t> row_grade_map;\n    for(size_t j=0; j<generating_set_kernel.size(); j++){\n        row_grade_map[j] = generating_set_kernel[j].grade;\n    }\n\n    Matrix presentation;\n    for(auto& syz_column : syzygy_module){\n        SignatureColumn column(syz_column.grade, syz_column.signature_index);\n        index_t pivot = syz_column.get_pivot().get_index();\n        while(pivot != -1){\n            column.plus(change_of_basis_map[pivot]);\n            syz_column.pop_pivot();\n            pivot = syz_column.get_pivot().get_index();\n        }\n        if(debug){\n            if(syz_column.grade != column.grade){\n                throw \"Grade of columns has changed.\";\n            }\n            SignatureColumn ker_column(syz_column.grade, syz_column.signature_index);\n            SignatureColumn copy(column);\n            pivot = copy.get_pivot().get_index();\n            while(pivot != -1){\n                ker_column.plus(generating_set_kernel[pivot]);\n                copy.pop_pivot();\n                pivot = copy.get_pivot().get_index();\n            }\n            if(ker_column.get_pivot().get_index() != -1){\n                copy.print();\n                std::cout << \"\\n\";\n                column.print();\n                std::cout << \"\\n\";\n                ker_column.print();\n                throw \"Column non-zero\";\n            }\n        }\n        if(column.get_pivot().get_index() != -1){\n            presentation.push_back(column);\n        }\n    }\n\n    std::cout << \"Computed non-minimal presentation of size: \" << presentation.size()<< std::endl;\n    \n    // Compute minimal generating set from syz-module and image columns\n    sort(presentation.begin(), presentation.end(),[ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n         {\n             return lhs.grade < rhs.grade ;\n         });\n    \n    hash_map<size_t, size_t> pairs = compute_local_pairs(presentation, row_grade_map);\n    \n    std::set<size_t> negative_columns;\n    presentation = compute_global_columns(presentation, pairs, negative_columns);\n    \n    for(auto& entry : pairs){\n        if(row_grade_map.find(entry.first) != row_grade_map.end()){\n            row_grade_map.erase(entry.first);\n        }\n    }\n    \n    std::vector<index_t> rows;\n    for(auto& entry : row_grade_map){\n        rows.push_back(entry.first);\n    }\n    sort(rows.begin(), rows.end());\n    hash_map<size_t, size_t> row_index_map;\n    for(size_t i=0; i<rows.size(); i++){\n        row_index_map[rows[i]] = i;\n    }\n    \n    for(size_t i=0;i<presentation.size(); i++){\n        SignatureColumn column(presentation[i].grade, presentation[i].signature_index);\n        for(auto& entry : presentation[i]){\n            if(row_grade_map.find(entry) != row_grade_map.end()){\n                column.push(column_entry_t(entry, row_index_map[entry]));\n            }\n        }\n        presentation[i].swap(column);\n    }\n    presentation = compute_minimal_generating_set(presentation);\n    return std::pair<Matrix, hash_map<size_t, grade_t>>(presentation, row_grade_map);\n}\n\n\n/* Python interface */\n\nstruct GradedMatrix{\n    std::vector< std::vector<std::pair<int, int>> > matrix;\n    std::vector< std::vector<int> > column_grades;\n    std::vector< std::vector<int> > row_grades;\n};\n\nMetric* parse_metric(int metric_index){\n    switch(metric_index){\n        case 0:\n            return new SquaredEuclideanMetric();\n        default:\n            throw \"Failed to parse metric\";\n    }\n}\n\nFilter* parse_filter(int filter_index){\n    if(filter_index >= 0){\n        return new XFilter(filter_index);\n    }\n    switch(filter_index){\n        case -1:\n            return new XFilter(0); //TODO: implement more filters.\n        default:\n            throw \"Failed to parse metric\";\n    }\n}\n\nMatrix translateInputMatrix(std::vector<std::vector<int>>& matrix, std::vector<std::vector<int>>& column_grades){\n    Matrix M;\n    for(size_t i=0; i<matrix.size(); i++){\n        grade_t grade;\n        for(size_t j=0; j<column_grades[i].size(); j++){\n            grade.push_back(column_grades[i][j]);\n        }\n        SignatureColumn column(grade, i);\n        for(size_t j=0; j<matrix[i].size(); j++){\n            if(matrix[i][j] != 0){\n                column.push(column_entry_t(1, j)); // TODO: implement support for other modulus than Z/2Z.\n            }\n        }\n        column.syzygy.push(column_entry_t(1, i));\n        M.push_back(column);\n    }\n    return M;\n}\n\nGradedMatrix translateOutputMatrix(Matrix& matrix){\n    GradedMatrix graded_matrix;\n    for(SignatureColumn column : matrix){\n        std::vector<std::pair<int, int>> sparse_column;\n        while(!column.empty()){\n            column_entry_t entry = column.pop_pivot();\n            if(entry.get_index() != -1){\n                sparse_column.push_back(std::pair<int, int>(entry.get_value(), entry.get_index()));\n            }\n        }\n        graded_matrix.matrix.push_back(sparse_column);\n        std::vector<int> column_grade;\n        for(size_t grade_index=0; grade_index<column.grade.size(); grade_index++){\n            column_grade.push_back((int)column.grade[grade_index]);\n        }\n        graded_matrix.column_grades.push_back(column_grade);\n    }\n    return graded_matrix;\n}\n\nGradedMatrix compute_kernel(std::vector<std::vector<int>>& matrix, std::vector<std::vector<int>>& row_grades, std::vector<std::vector<int>>& column_grades){\n    Matrix M = translateInputMatrix(matrix, column_grades);\n    Matrix kernel;\n    if(column_grades.size()>0 && column_grades[0].size()==2){\n        kernel = computeKernel_2p(M);\n    }else{\n        std::pair<Matrix, Matrix> gbs = computeGroebnerBases_gradeopt_min(M);\n        kernel = gbs.first;\n    }\n    GradedMatrix Ker = translateOutputMatrix(kernel);\n    Ker.row_grades = column_grades;\n    return Ker;\n}\n\nstd::pair<GradedMatrix, GradedMatrix> groebner_bases(std::vector<std::vector<int>>& matrix, std::vector<std::vector<int>>& row_grades, std::vector<std::vector<int>>& column_grades){\n    Matrix M = translateInputMatrix(matrix, column_grades);\n    std::pair<Matrix, Matrix> gbs = computeGroebnerBases_gradeopt_min(M);\n    GradedMatrix Im = translateOutputMatrix(gbs.first);\n    GradedMatrix Ker = translateOutputMatrix(gbs.second);\n    Ker.row_grades = column_grades;\n    Im.row_grades = row_grades;\n    return std::pair<GradedMatrix, GradedMatrix>(Im, Ker);\n}\n\nGradedMatrix presentation_FIrep(std::vector<std::vector<int>>& high_matrix, std::vector<std::vector<int>>& column_grades_h, std::vector<std::vector<int>>& low_matrix, std::vector<std::vector<int>>& column_grades_l){\n    Matrix M_h = translateInputMatrix(high_matrix, column_grades_h);\n    Matrix M_l = translateInputMatrix(low_matrix, column_grades_l);\n    auto start = std::chrono::high_resolution_clock::now();\n    std::pair<Matrix, hash_map<size_t, grade_t>> presentation_output;\n    if(M_l.size()>0 && M_l[0].grade.size()==2){\n        Matrix kernel = computeKernel_2p(M_l);\n        presentation_output = compute_presentation_2p(M_h, kernel);\n    }else{\n        presentation_output = computePresentationDeg_imopt(M_h, M_l);\n    }\n    auto stop = std::chrono::high_resolution_clock::now();\n    auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start);\n    \n    std::cout << \"Time elapsed: \" << duration.count() << \" seconds\" << std::endl;\n    GradedMatrix graded_matrix = translateOutputMatrix(presentation_output.first);\n    for(std::pair<size_t, grade_t> entry : presentation_output.second){\n        std::vector<int> row_grade;\n        for(size_t grade_index=0; grade_index<entry.second.size(); grade_index++){\n            row_grade.push_back((int)entry.second[grade_index]);\n        }\n        graded_matrix.row_grades.push_back(row_grade);\n    }\n    return graded_matrix;\n}\n\nGradedMatrix presentation_dm(std::vector<std::vector<std::vector<input_t>>>& distance_matrices, std::vector<input_t>& max_metric_values, std::vector<std::vector<input_t>>& filters, int hom_dim){\n    std::pair<Matrix, Matrix> boundary_matrices = compute_boundary_matrices_dm(distance_matrices, max_metric_values, filters, hom_dim);\n    verify_kernel(boundary_matrices.first, boundary_matrices.second);\n    for(size_t i=0; i<boundary_matrices.second.size(); i++){\n        boundary_matrices.second[i].syzygy.push(column_entry_t(1, i));\n    }\n    Matrix input_copy;\n    for(auto& column : boundary_matrices.second){\n        input_copy.push_back(SignatureColumn(column.grade, 0, column));\n    }\n    std::pair<Matrix, hash_map<size_t, grade_t>> presentation;\n    if(boundary_matrices.second.size()>0 && boundary_matrices.second[0].grade.size()==2){\n        Matrix kernel = computeKernel_2p(boundary_matrices.second);\n        presentation = compute_presentation_2p(boundary_matrices.first, kernel);\n    }else{\n        std::pair<Matrix, Matrix> gbs = computeGroebnerBases(boundary_matrices.second);\n        presentation = computePresentationDeg_imopt(boundary_matrices.first, gbs.second);\n    }\n    GradedMatrix graded_matrix = translateOutputMatrix(presentation.first);\n    for(std::pair<size_t, grade_t> entry : presentation.second){\n        std::vector<int> row_grade;\n        for(size_t grade_index=0; grade_index<entry.second.size(); grade_index++){\n            row_grade.push_back((int)entry.second[grade_index]);\n        }\n        graded_matrix.row_grades.push_back(row_grade);\n    }\n    return graded_matrix;\n}\n\nGradedMatrix presentation(std::vector<std::vector<input_t>>& _points, std::vector<int>& _metrics, std::vector<input_t>& _max_metric_values, std::vector<int>& _filters, int hom_dim){\n    std::vector<Metric*> metrics;\n    for(size_t i=0; i<_metrics.size(); i++){\n        metrics.push_back(parse_metric(_metrics[i]));\n    }\n    std::vector<Filter*> filters;\n    for(size_t i=0; i<filters.size(); i++){\n        filters.push_back(parse_filter(_filters[i]));\n    }\n    std::vector<input_t> max_metric_values;\n    for(size_t i=0; i<_metrics.size(); i++){\n        max_metric_values.push_back(_max_metric_values[i]);\n    }\n    std::pair<Matrix, Matrix> boundary_matrices = compute_boundary_matrices(_points, metrics, filters, max_metric_values, hom_dim);\n    verify_kernel(boundary_matrices.first, boundary_matrices.second);\n    for(auto& metric : metrics){\n        delete metric;\n    }\n    for(auto& filter : filters){\n        delete filter;\n    }\n    for(size_t i=0; i<boundary_matrices.second.size(); i++){\n        boundary_matrices.second[i].syzygy.push(column_entry_t(1, i));\n    }\n    Matrix input_copy;\n    for(auto& column : boundary_matrices.second){\n        input_copy.push_back(SignatureColumn(column.grade, 0, column));\n    }\n    std::pair<Matrix, hash_map<size_t, grade_t>> presentation;\n    if(boundary_matrices.second.size()>0 && boundary_matrices.second[0].grade.size()==2){\n        Matrix kernel = computeKernel_2p(boundary_matrices.second);\n        presentation = compute_presentation_2p(boundary_matrices.first, kernel);\n    }else{\n        presentation = computePresentationDeg_imopt(boundary_matrices.first, boundary_matrices.second);\n    }\n    GradedMatrix graded_matrix = translateOutputMatrix(presentation.first);\n    for(std::pair<size_t, grade_t> entry : presentation.second){\n        std::vector<int> row_grade;\n        for(size_t grade_index=0; grade_index<entry.second.size(); grade_index++){\n            row_grade.push_back((int)entry.second[grade_index]);\n        }\n        graded_matrix.row_grades.push_back(row_grade);\n    }\n    return graded_matrix;\n}\n\n\n/*\n Testing\n */\n\nstd::vector<double> run_gb_singatures_pres(Matrix& input_matrix, Matrix& image, bool debug=false){\n    auto start = std::chrono::high_resolution_clock::now();\n    std::pair<Matrix, hash_map<size_t, grade_t>> presentation_sign = computePresentationDeg_imopt(image, input_matrix, debug);\n    auto stop = std::chrono::high_resolution_clock::now();\n    auto b_time = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);\n    std::cout << \" Presentation size: \" << presentation_sign.first.size() << std::endl;//gbs2.size() << std::endl;\n    double time = b_time.count();\n    double size = presentation_sign.first.size();\n    return std::vector<double>{time, res_memory, size};\n}\n\nstd::vector<double> run_gb_shreyer_pres(Matrix& input_matrix, Matrix& image, bool debug=false){\n    auto start = std::chrono::high_resolution_clock::now();\n    Matrix kernel = computeGroebnerBases_gradeopt(input_matrix).second;\n    std::pair<Matrix, hash_map<size_t, grade_t>> presentation = compute_presentation_schreyer(image, kernel);\n    auto stop = std::chrono::high_resolution_clock::now();\n    auto b_time = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);\n    std::cout << \" Presentation size: \" << presentation.first.size() << std::endl;//gbs2.size() << std::endl;\n    double time = b_time.count();\n    double size = presentation.first.size();\n    return std::vector<double>{time, res_memory, size};\n}\n\nvoid critical_points_geometric_pres(){\n    get_mem_usage(virt_memory, res_memory);\n    double start_mem = res_memory;\n    double metric_thresh = 3.5;\n    int n = 10;\n    std::vector<std::vector<double>> times;\n    std::vector<std::vector<double>> resident_memory;\n    std::vector<std::vector<double>> output_size;\n    std::vector<double> boundary_matrix_size;\n    while(n < 201){\n        std::cout << \"\\n Iteration: \" << n << std::endl;\n        uint32_t seed = 1;\n        std::vector<std::vector<input_t>> points = time_varying_point_cloud(10, 10*n, 3, seed);//time_varying_point_cloud(60, 100, 3, 1);\n        std::vector<std::vector<input_t>> xpoints = points;\n        for(auto& p:xpoints){\n            p.pop_back();\n        }\n        \n        std::vector<Metric*> metrics;\n        metrics.push_back(new SquaredEuclideanMetric());\n        std::vector<Filter*> filters;\n        filters.push_back(new XFilter(3, 1));\n        filters.push_back(new XFilter(3, -1));\n        //filters.push_back(new XFilter(0, 1));\n        //filters.push_back(new XFilter(0, -1));\n        //filters.push_back(new XFilter(1, 1));\n        //filters.push_back(new XFilter(1, -1));\n        //filters.push_back(new XFilter(2, 1));\n        //filters.push_back(new XFilter(2, -1));\n        //filters.push_back(new DensityFilter(xpoints));\n        \n        std::vector<input_t> max_metric_values;\n        max_metric_values.push_back(metric_thresh);\n        \n        std::pair<Matrix, Matrix> boundaries = compute_boundary_matrices(points, metrics, filters, max_metric_values, 1);\n        \n        for(size_t i=0; i<boundaries.second.size(); i++){\n            boundaries.second[i].signature_index = i;\n        }\n        \n        sort(boundaries.second.begin(), boundaries.second.end(), [ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n             {\n                 return lhs.grade.lt_colex(rhs.grade);\n             });\n        \n        //Reindex image columns\n        hash_map<size_t, size_t> map;\n        for(size_t i=0; i<boundaries.second.size();i++){\n            map[boundaries.second[i].signature_index] = i;\n        }\n        \n        for(size_t i=0; i<boundaries.first.size(); i++){\n            SyzColumn c;\n            while(boundaries.first[i].get_pivot().get_index() != -1){\n                c.push(column_entry_t(1, map[boundaries.first[i].get_pivot().get_index()]));\n                boundaries.first[i].pop_pivot();\n            }\n            while(c.get_pivot().get_index() != -1){\n                boundaries.first[i].push(c.get_pivot());\n                c.pop_pivot();\n            }\n        }\n        \n        sort(boundaries.first.begin(), boundaries.first.end(), [ ](  SignatureColumn& lhs,  SignatureColumn& rhs )\n             {\n                 return lhs.grade < rhs.grade;\n             });\n        \n        Matrix boundary = boundaries.second;\n        Matrix image = compute_minimal_generating_set(boundaries.first);\n        \n        std::cout << \"Size of boundary matrix: \" << boundary.size() << \" Size of image matrix: \" << image.size() << std::endl;\n        \n        for(size_t i=0; i<boundary.size(); i++){\n            boundary[i].signature_index = i;\n            boundary[i].syzygy = SyzColumn();\n            boundary[i].syzygy.push(column_entry_t(1, i));\n        }\n        \n        //Test is image maps into kernel\n        for(auto& column : image){\n            SignatureColumn c(column);\n            SignatureColumn z(column.grade, -1);\n            while(c.get_pivot_index() != -1){\n                z.plus(boundary[c.get_pivot_index()]);\n                c.pop_pivot();\n            }\n            if(z.get_pivot_index() != -1){\n                throw \"Image does not map to kernel\";\n            }\n        }\n        \n        Matrix input_copy;\n        for(auto& c : boundary){\n            input_copy.push_back(SignatureColumn(c));\n        }\n        Matrix image_copy;\n        for(auto& c : image){\n            image_copy.push_back(SignatureColumn(c));\n        }\n        std::vector<double> gb_res = run_gb_singatures_pres(input_copy, image_copy);\n        input_copy.clear();\n        for(auto& c : boundary){\n            input_copy.push_back(SignatureColumn(c));\n        }\n        image_copy.clear();\n        for(auto& c : image){\n            image_copy.push_back(SignatureColumn(c));\n        }\n        std::vector<double> gb_schreyer = run_gb_shreyer_pres(input_copy, image_copy);\n        \n        times.push_back(std::vector<double>{gb_schreyer[0], gb_res[0]});\n        resident_memory.push_back(std::vector<double>{gb_schreyer[1]-start_mem, gb_res[1]-start_mem});\n        output_size.push_back(std::vector<double>{gb_schreyer[2], gb_res[2]});\n        boundary_matrix_size.push_back(boundary.size());\n        \n        std::cout << \"$\"<< metric_thresh << \"$ & \" << times[times.size()-1][0]/1000 << \" & \" << resident_memory[times.size()-1][0] << \" & \" << times[times.size()-1][1]/1000 << \" & \" << resident_memory[times.size()-1][1]  << \"\\n\";\n        \n        n+= 10;\n    }\n    for(size_t i=0; i<times.size(); i++){\n        std::cout << \"$\"<< metric_thresh+i*0.05 << \"$ & \" << times[i][0]/1000 << \" & \" << resident_memory[i][0] << \" & \" << times[i][1]/1000 << \" & \" << resident_memory[i][1] << \"\\n\";\n    }\n    std::cout << \"\\n\";\n    std::cout << \"\\n Times GBS+Schreyer \\n\";\n    for(auto& v : times){\n        std::cout << v[0] << \", \";\n    }\n    std::cout << \"\\n Times PresentationPair \\n\";\n    for(auto& v : times){\n        std::cout << v[1] << \", \";\n    }\n    std::cout << \"\\n Resident memory GBS+Schreyer\\n\";\n    for(auto& v : resident_memory){\n        std::cout << v[0] << \", \";\n    }\n    std::cout << \"\\n Resident memory PresentationPair\\n\";\n    for(auto& v : resident_memory){\n        std::cout << v[1] << \", \";\n    }\n    \n    std::cout << \"\\n Input size \\n\";\n    for(auto& v : boundary_matrix_size){\n        std::cout << v << \", \";\n    }\n}\n\n\n/* Input */\n\nvoid print_usage_and_exit(int exit_code) {\n    std::cerr\n    << \"Usage: \"\n    << \"mph \"\n    << \"[options] [filename]\" << std::endl\n    << std::endl\n    << \"Options:\" << std::endl\n    << std::endl\n    << \"  --help           print this screen\" << std::endl\n    << \"  --dim <k>        compute presentation matrix of the k-th persistent homology module\" << std::endl\n    << \"  --firep <k>      input file with rivet <firep> file format\" << std::endl\n    << std::endl;\n    exit(exit_code);\n}\n\n\nint main(int argc, char** argv) {\n    const char* filename = nullptr;\n    \n    int dim_max = 1;\n    bool firep = false;\n    \n    if(argc==1){\n        print_usage_and_exit(0);\n    }\n    \n    for (index_t i = 1; i < argc; ++i) {\n        const std::string arg(argv[i]);\n        if (arg == \"--help\") {\n            print_usage_and_exit(0);\n        } else if (arg == \"--dim\") {\n            std::string parameter = std::string(argv[++i]);\n            size_t next_pos;\n            dim_max = (int)std::stol(parameter, &next_pos);\n            if (next_pos != parameter.size()) print_usage_and_exit(-1);\n        } else if (arg == \"--firep\"){\n            firep = true;\n        } else {\n            if (filename) { print_usage_and_exit(-1); }\n            filename = argv[i];\n        }\n    }\n    \n    std::pair<Matrix, hash_map<size_t, grade_t>> presentation;\n    if(firep){\n        Matrix high_matrix, low_matrix;\n        std::ifstream file_stream(filename);\n        if (file_stream.fail()) {\n            std::cerr << \"couldn't open file \" << filename << std::endl;\n            exit(-1);\n        }\n        read_input_file<SyzColumn, SyzColumn>(file_stream, high_matrix, low_matrix);\n        presentation = computePresentationDeg_imopt(high_matrix, low_matrix);\n    } else{\n        std::ifstream file_stream(filename);\n        if (filename && file_stream.fail()) {\n            std::cerr << \"couldn't open file \" << filename << std::endl;\n            exit(-1);\n        }\n        \n        // TODO: how should choice of metrics and filters be specified in input?\n        \n        std::vector<Metric*> metrics;\n        metrics.push_back(new SquaredEuclideanMetric());\n        std::vector<Filter*> filters;\n        filters.push_back(new Filter());\n        std::vector<input_t> max_metric_values;\n        max_metric_values.push_back(10);\n        std::vector<std::vector<input_t>> points = read_point_cloud(file_stream, 0);\n        std::pair<Matrix, Matrix> boundary_matrices = compute_boundary_matrices(points, metrics, filters, max_metric_values, dim_max);\n        verify_kernel(boundary_matrices.first, boundary_matrices.second);\n        for(auto& metric : metrics){\n            delete metric;\n        }\n        for(auto& filter : filters){\n            delete filter;\n        }\n        for(size_t i=0; i<boundary_matrices.second.size(); i++){\n            boundary_matrices.second[i].syzygy.push(column_entry_t(1, i));\n        }\n        presentation = computePresentationDeg_imopt(boundary_matrices.first, boundary_matrices.second);\n    }\n    \n    std::cout << \"Presentation matrix: \\n\";\n    presentation.first.print();\n    \n    std::cout << \"Column grades: \\n\";\n    for(auto& column: presentation.first){\n        column.grade.print();\n    }\n    std::cout << \"Row grades: \\n\";\n    for(auto& it: presentation.second){\n        it.second.print();\n    }\n    exit(0);\n}\n", "meta": {"hexsha": "f05486b4c05c6fd178d9f0a914063a9b201f740c", "size": 123431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mph/main.cpp", "max_stars_repo_name": "MBender/muphasa", "max_stars_repo_head_hexsha": "7d0887d7f6c6b0f673510a6a70fa9ae1f2473b89", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-08T13:45:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T12:11:34.000Z", "max_issues_repo_path": "mph/main.cpp", "max_issues_repo_name": "MBender/muphasa", "max_issues_repo_head_hexsha": "7d0887d7f6c6b0f673510a6a70fa9ae1f2473b89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mph/main.cpp", "max_forks_repo_name": "MBender/muphasa", "max_forks_repo_head_hexsha": "7d0887d7f6c6b0f673510a6a70fa9ae1f2473b89", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-11T16:57:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T16:57:36.000Z", "avg_line_length": 43.5690081186, "max_line_length": 229, "alphanum_fraction": 0.5286111269, "num_tokens": 26398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5296232660854426}}
{"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#include \"blake2.h\"\n#include \"blake2-kat.h\"\n\n#include \"Sampling.h\"\n#include \"params.h\"\n#include \"FFT.h\"\n#include \"Random.h\"\n#include \"Algebra.h\"\n#define bitRead(value, bit) (((value) >> (bit)) & 0x01)\nusing namespace std;\nusing namespace NTL;\n\nconst ZZX phi = Cyclo();\n\n\n//==============================================================================\n//Generates from parameters N and q :\n// - a public key : polynomial h\n// - a private key : polynomials f,g,F,G\n//==============================================================================\nvoid Keygen(ZZ_pX& PublicKey, ZZX* PrivateKey)\n{\n    ZZ SqNorm;\n    ZZX f,g,F,G;\n\n    SqNorm = conv<ZZ>(1.36*q0/2);\n\n    GenerateBasis(f, g, F, G, SqNorm);\n\t\n\t//added by me ============\n\t\n\t\n\t\n\t//added by me ==============\n\t\n    PrivateKey[0] = f;\n    PrivateKey[1] = g;\n    PrivateKey[2] = F;\n    PrivateKey[3] = G;\n\n    for(unsigned int i=0; i<4; i++)\n    {\n            PrivateKey[i].SetLength(N0);\n    }\n\n    PublicKey = Quotient(f, g);\n}\n\n\n\nvoid myKeygen(ZZ_pX& PublicKey, ZZX* PrivateKey)\n{\n    ZZ SqNorm;\n    ZZX f,g,F,G;\n\n    SqNorm = conv<ZZ>(1.36*q0/2);\n\n    GenerateBasis(f, g, F, G, SqNorm);\n\t\n\t//added by me ============\n\t\n\t\n\t\n\t//added by me ==============\n\t\n    PrivateKey[0] = f;\n    PrivateKey[1] = g;\n    PrivateKey[2] = F;\n    PrivateKey[3] = G;\n\n    for(unsigned int i=0; i<4; i++)\n    {\n            PrivateKey[i].SetLength(N0);\n    }\n\n    PublicKey = Quotient(f, g);\n}\n\n\n\n\n//==============================================================================\n//Computes the private basis B from private key PrivateKey and parameter N\n//==============================================================================\nvoid CompletePrivateKey(mat_ZZ& B, const ZZX * const PrivateKey)\n{\n    ZZX f,g,F,G;\n    f = PrivateKey[0];\n    g = PrivateKey[1];\n    F = PrivateKey[2];\n    G = PrivateKey[3];\n\n    f = -f;\n    F = -F;\n\n    B = BasisFromPolynomials(g, f, G, F);\n}\n\n\n\n\n\nvoid GPV(RR_t * v, const RR_t * const c, const RR_t s, const MSK_Data * const MSKD)\n{\n\n    int i;\n    unsigned j;\n    RR_t ci[2*N0], zi, cip, sip, aux;\n\n    for(j=0; j<2*N0;j++)\n    {\n        ci[j] = c[j];\n    }\n\n//    for(j=0; j<2*N0; j++)\n//    {\n//\n//    }    \n\n    for(i=2*N0-1; i>=0; i--)\n    {\n        aux = (MSKD->GS_Norms)[i];\n        cip = DotProduct(ci, MSKD->Bstar[i])/(aux*aux);\n        sip = s/aux;\n        zi = Sample4(cip, sip*PiPrime);\n\n        for(j=0; j<2*N0; j++)\n        {\n            ci[j] -= zi*(MSKD->B)[i][j];\n        }\n    }\n\n    for(j=0; j<2*N0; j++)\n    {\n        v[j] = c[j] - ci[j];\n    }\n\n}\n\n\n\n//==============================================================================\n//==============================================================================\n//                            KeyGen\n//==============================================================================\n//==============================================================================\n\n\nvoid CompleteMSK(MSK_Data * MSKD, ZZX * MSK)\n{\n    unsigned int i, j;\n    mat_ZZ B0;\n\n    for(i=0; i<4; i++)\n    {\n        MSKD->PrK[i] = MSK[i];\n        ZZXToFFT(MSKD->PrK_fft[i], MSK[i]);\n    }\n\n    CompletePrivateKey(B0, MSK);\n\n    for(i=0; i<2*N0; i++)\n    {\n        for(j=0; j<2*N0; j++)\n        {\n            MSKD->B[i][j] = ( (RR_t) conv<double>(B0[i][j]) );\n        }\n    }\n\n    for(i=0; i<1; i++)\n    {\n        FastMGS(MSKD->Bstar, MSKD->B);\n    }\n\n    for(i=0; i<2*N0; i++)\n    {\n        MSKD->GS_Norms[i] = sqrt( DotProduct(MSKD->Bstar[i], MSKD->Bstar[i]) );\n    }\n\n    MSKD->sigma = 2*MSKD->GS_Norms[0];\n\n}\n\n\n\nvoid CompleteMPK(MPK_Data * MPKD, ZZ_pX MPK)\n{\n    MPKD->h = MPK;\n    ZZXToFFT(MPKD->h_FFT, conv<ZZX>(MPK));\n}\n\n\n//==============================================================================\n//==============================================================================\n//                            Trapdoor\n//==============================================================================\n//==============================================================================\n\n\nvoid PEKS_Trapdoor(ZZX SK_id[2], vec_ZZ id, const MSK_Data * const MSKD)\n{\n    unsigned int i;\n    RR_t c[2*N0], sk[2*N0], sigma;\n    ZZX f,g,aux;\n\n/*\tid[0] = q0-1;\n\tid[1] = q0-3;\n\tid[2] = q0-5;\n\tid[3] = q0-5;\n\tid[4] = q0-8;\n\tid[5] = q0/2;\n\tid[6] = q0-10;\n\tid[7] = q0-11;*/\n//id = RandomVector();\n\n\n    f = MSKD -> PrK[0];\n    g = MSKD -> PrK[1];\n    sigma = MSKD->sigma;\n    SK_id[0].SetLength(N0);\n    SK_id[1].SetLength(N0);\n\n    for(i=0;i<N0;i++)\n    {\n        c[i] = ((RR_t) conv<double>(id[i])) ;\n        c[i+N0] = 0;\n    }\n/*\t\tcout<< \"ID in trapdoor: \";\n\tfor (int j = 0;j<N0;j++)\n\t\tcout << id[j]<< \"   \";*/\n\tcout << endl;\n\n    GPV(sk, c, sigma, MSKD);\n\n    for(i=0; i<N0; i++)\n    {\n        sk[i] = c[i] - sk[i];\n        sk[i+N0] = - sk[i+N0];\n    }\n\n    for(i=0; i<N0; i++)\n    {\n        SK_id[0][i] = sk[i];\n        SK_id[1][i] = sk[i+N0];\n    }\n\n\n}\n\n//==============================================================================\n//==============================================================================\n//                          Verify  Trapdoor\n//==============================================================================\n//==============================================================================\n\n\n\nunsigned long  PEKS_Verify_Trapdoor( const ZZX SK_td[2], const vec_ZZ kw, const MSK_Data * const MSKD)\n{\n    unsigned int i;\n    ZZX f,g,t,aux;\n\n    f = MSKD -> PrK[0];\n    g = MSKD -> PrK[1];\n    \n    t = conv<ZZX>(kw);\n    aux = ((SK_td[0] - t)*f + g*SK_td[1])%phi;\n\n    for(i=0; i<N0; i++)\n    {\n        aux[i] %= q1;\n    }\n\n    if( IsZero(aux) != 0)\n    {\n        cout << \"The signature (s1,s2) doesn't verify the required equality [ (s1 - t)*f + g*s2 = 0 ] !\\nActually, (s1 - t)*f + g*s2 = \" << aux << endl << endl;\n    }\n    return IsZero(aux);\n}\n\n//==============================================================================\n//==============================================================================\n//                          PEKS\n//==============================================================================\n//==============================================================================\n\n\n\n\nvoid PEKS_Enc(long C[2][N0],  long C2[N0],  long id0[N0], const MPK_Data * const MPKD)\n{\n\n    unsigned long i;\n//\tsrand(3);\n\n/*cout << \"The ID in PEKS_ENC  :   \";\n\t\tfor (int i = 0; i<N0 ; i++){\n\t\t\t\n\t\t\tcout << id0[i]<<\"  \";\n\t\t\t}*/\n\n/*\tunsigned char z[32] = {0x54, 0xa2, 0xf8, 0x03, 0x1d, 0x18, 0xac, 0x77, 0xd2, 0x53, 0x92, 0xf2, 0x80, 0xb4, 0xb1, 0x2f, 0xac, 0xf1, 0x29, 0x3f, 0x3a, 0xe6, 0x77, 0x7d, 0x74, 0x15, 0x67, 0x91, 0x99, 0x53, 0x69, 0xc5};\n\tuint8_t hashed[64];\n\tlong hashed2[64];\n\tuint8_t hash[2] = {0};\n\tblake2b(hashed, hash, z, 64, 2, 32);\n\tcout << \"the hashed values are as follows\";\n\tfor (int i = 0; i<64 ; i++){\n\t\thashed2[i]= hashed[i];\n\t hashed2[i] << 17;}\n\tfor (int i = 0; i<64 ; i++)\n\t\tcout << hashed2[i] << \"  \";\n\t\t*/\n/*\tid0[0] =  100;\n\tid0[1] = 234;\n\tid0[2] = 12;\n\tid0[3] = 546;\n\tid0[4] = 98;\n\tid0[5] = 0;\n\tid0[6] = 0;\n\tid0[7] = q0-0;\n\tid0[8] =  q0 + 100023 - 6619531;\n\tid0[9] = 0;\n\tid0[10] = 0;\n\tid0[11] = 0;\n\tid0[12] = 0;\n\tid0[13] = 0;\n\tid0[14] = 500;\n\tid0[15] = 0;*/\n\t\n\n    long r[N0], e1[N0], e2[N0];\n    CC_t r_FFT[N0], t_FFT[N0], aux1_FFT[N0], aux2_FFT[N0];\n\tfor(i=0; i<N0; i++)\n        {\n            C2[i] = (rand()%2);\n        }\n    for(i=0; i<N0; i++)\n    {\n        e1[i] = (rand()%3) - 1;\n        e2[i] = (rand()%3) - 1;\n        r[i] = (rand()%3) - 1;\n    }\n\t\n\t//============================\n\n\t\t//----------------\n    MyIntFFT(r_FFT, r);\n    MyIntFFT(t_FFT, id0);\n\n\n\n\n    for(i=0; i<N0; i++)\n    {\n        aux1_FFT[i] = r_FFT[i]*((MPKD->h_FFT)[i]);\n        aux2_FFT[i] = r_FFT[i]*t_FFT[i];\n    }\n\n    MyIntReverseFFT(C[0], aux1_FFT);\n    MyIntReverseFFT(C[1], aux2_FFT);\n\n    for(i=0; i<N0; i++)\n    {\n        C[0][i] = (C[0][i] + e1[i]               + q0/2)%q0 - (q0/2);\n        C[1][i] = (C[1][i] + e2[i] + (q0/2)*C2[i] + q0/2)%q0 - (q0/2);\n    } \n\n}\n\n//==============================================================================\n//==============================================================================\n//                          TEST\n//==============================================================================\n//==============================================================================\n\n\n\nvoid PEKS_Test(long message[N0],  long C[2][N0], const CC_t * const SKid_FFT)\n{\n    unsigned int i;\n    CC_t c0_FFT[N0], aux_FFT[N0];\n\t/*        for(int j=0; j<N0; j++)\n        {\n            C[1][j] = (rand()%q0);\n        }*/\n   \n\n    MyIntFFT(c0_FFT, C[0]);\n\n    for(i=0; i<N0; i++)\n    {\n        aux_FFT[i] = c0_FFT[i]*SKid_FFT[i];\n    }\n\n/*\t\tcout << \"MESSAGE b4 DECRYPT: \"<<endl;\n\t\tfor(int j=0; j<N0; j++)\n        {\n            cout << message[j] << \" \";  \n        }*/\n\n    MyIntReverseFFT(message, aux_FFT);\n\n\n    for(i=0; i<N0; i++)\n    {\n        message[i] = C[1][i] - message[i];\n        message[i] = ((unsigned long)(message[i] ))%q0;\n        message[i] = (message[i] + (q0>>2) )/(q0>>1);\n        message[i] %= 2;\n    }\n\n}\n\n\n//==============================================================================\n//==============================================================================\n//                             BENCHES AND TESTS\n//                   FOR EXTRACTION AND ENCRYPTION/DECRYPTION\n//==============================================================================\n//==============================================================================\n\n\nvoid Trapdoor_Bench(const unsigned int nb_extr, MSK_Data * MSKD)\n{\n    clock_t t1, t2;\n    float diff;\n    unsigned int i;\n    vec_ZZ kw;\n    ZZX SK_td[2];\n\n    t1 = clock();\n\n    cout << \"0%\" << flush;\n    for(i=0; i<nb_extr; i++)\n    {\n        kw = RandomVector();\n\n        PEKS_Trapdoor(SK_td, kw, MSKD);\n        if((i+1)%(nb_extr/10)==0)\n        {\n            cout << \"...\" << (i+1)/(nb_extr/10) << \"0%\" << flush;\n        }\n    }\n\n    t2 = clock();\n    diff = ((float)t2 - (float)t1)/1000000.0F;\n    cout << \"\\n\\nIt took \" << diff << \" seconds to create  \" << nb_extr << \" trapdoors.\" << endl;\n    cout << \"That's \" << (diff/nb_extr)*1000 << \" milliseconds per trapdoor.\" << endl << endl;\n}\n\n\nvoid Encrypt_Bench(const unsigned int nb_cryp, MPK_Data * MPKD, MSK_Data * MSKD)\n{\n    clock_t te1, te2, td1, td2;\n    float diffe, diffd;\n    unsigned int i,j;\n    vec_ZZ kw;\n    ZZX SK_td[2], w;\n    CC_t SKid_FFT[N0];\n    long int message[N0], decrypted[N0];\n    long int keyword[N0], Ciphertext[2][N0];\n\n\n    kw = RandomVector();\n    PEKS_Trapdoor(SK_td, kw, MSKD);\n    PEKS_Verify_Trapdoor(SK_td, kw, MSKD);\n    ZZXToFFT(SKid_FFT, SK_td[1]);\n\n    for(i=0; i<N0; i++)\n    {\n        keyword[i] = conv<long int>(kw[i]);\n    }\n\n    \n\n\n    cout << \"0%\" << flush ;\n    for(i=0; i<nb_cryp; i++)\n    {\n\n\n\tte1 = clock();\t\n\t\tPEKS_Enc(Ciphertext, message, keyword, MPKD);\n\tte2 = clock();\n\n\t\n\n\ttd1 = clock();\n\t/*\tif (!PEKS_Test(decrypted, Ciphertext, SKid_FFT)){\n\t\t\t cout << \"TEST FAILED --- Exiting...\"<<endl;\n\t\t\tbreak;\n\t\t\t}*/\n\t\t\t\n\ttd2 = clock();\n\t\n    //    if((i+1)%(nb_cryp/10)==0)\n        {\n            cout << \"...\" << (i+1)/(nb_cryp/10) << \"0%\" << flush;\n        }\n\n\tdiffe += ((float)te2 - (float)te1)/1000000.0l;\n\tdiffd += ((float)td2 - (float)td1)/1000000.0l;\n\n    }\n\n    cout << \"\\n\\nIt took \" << diffe << \" seconds to do \" << nb_cryp << \" encryptions.\" << endl;\n    cout << \"That's \" << (diffe/nb_cryp)*1000 << \" milliseconds per PEKS generation.\" << endl;\n    cout << \"That's \" << (diffe/nb_cryp)*1000*1024/N0 << \" milliseconds per PEKS per Kilobit.\" << endl << endl;\n\n    cout << \"\\n\\nIt took \" << diffd << \" seconds to do \" << nb_cryp << \" Tests.\" << endl;\n    cout << \"That's \" << (diffd/nb_cryp)*1000 << \" milliseconds per Tests.\" << endl;\n    cout << \"That's \" << (diffd/nb_cryp)*1000*1024/N0 << \" milliseconds per Tests per Kilobit.\" << endl << endl;\n\n}\n\n\nvoid Trapdoor_Test(const unsigned int nb_extr, MSK_Data * MSKD)\n{\n    unsigned int i, rep;\n    vec_ZZ kw;\n    ZZX SK_kw[2];\n\n    rep = 0;\n\n    cout << \"0%\" << flush;\n    for(i=0; i<nb_extr; i++)\n    {\n        kw = RandomVector();\n\n        PEKS_Trapdoor(SK_kw, kw, MSKD);\n        rep += PEKS_Verify_Trapdoor(SK_kw, kw, MSKD);\n      //  if((i+1)%(nb_extr/10)==0)\n        {\n            cout << \"...\" << (i+1)/(nb_extr/10) << \"0%\" << flush;\n        }\n    }\n\n    cout << endl;\n    if(rep == 0)\n    {    cout << endl << nb_extr << \" Trapdoor successfully performed!\" << endl << endl;    }\n    else\n    {    cout << endl << rep << \" out of \" << nb_extr << \" extractions failed miserabily!\" << endl << endl;    }\n}\n\n\nvoid Encrypt_Test(const unsigned int nb_cryp, MPK_Data * MPKD, MSK_Data * MSKD)\n{\n    unsigned int i, j, rep;\n    vec_ZZ kw;\n    ZZX SK_td[2], m;\n    CC_t SKtd_FFT[N0];\n    long int kw0[N0], Ciphertext[2][N0], Ciphertext2[N0];\n    long int message[N0], decrypted[N0];\n\tlong keywordConv [N0];\n\t\n\t\n\t\n/*\t\tkeywordConv[0] =  878974;\n\tkeywordConv[1] = 11134;\n\tkeywordConv[2] = 85012;\n\tkeywordConv[3] = 546;\n\tkeywordConv[4] = 1198876;\n\tkeywordConv[5] = 171110;\n\tkeywordConv[6] = 881000;\n\tkeywordConv[7] = 0;\n\tkeywordConv[8] =  100023 - 6619531;\n\tkeywordConv[9] = 1000;\n\tkeywordConv[10] = 0;\n\tkeywordConv[11] =0;\n\tkeywordConv[12] = 100257;\n\tkeywordConv[13] = 0;\n\tkeywordConv[14] = 0;\n\tkeywordConv[15] = q0-55555;*/\n\t\n\t/*long jim[N0];*/\n    //kw = RandomVector();\n\t\n\t//================\n\tint sum = 0;\n\tstring word1; char ch1;\n\tchar keywordAux1[N0];\n\tcout << \"Keyin a word\";\n\tcin >> word1;\n\tfor  (int i=0; i < word1.length();i++){\n\t\tkeywordAux1[i] = word1[i];\n\t\tch1  = keywordAux1[i];\n\t\tkeywordConv[i] = (ch1);\n\t}\n\tfor (int i =word1.length(); i<N0;i++){\n\t\tkeywordConv[i] = 0;\n\t}\n\t\tfor (int i =0; i<N0;i++){\n\t\tsum +=keywordConv[i];\n\t}\n\tsrand(sum);\n\t\t\tfor (int i = 0; i<N0 ; i++){\n\t\n\tkeywordConv[i] = (rand())%q0;\n\t\t}\n\t//==============\n\t\n\t\n\t\n\tkw = keywordVector(keywordConv);\n  //kw = RandomVector();\n\n    PEKS_Trapdoor(SK_td, kw, MSKD);\n    PEKS_Verify_Trapdoor(SK_td, kw, MSKD);\n    ZZXToFFT(SKtd_FFT, SK_td[1]);\n\n    rep = 0;\n\tsum = 0;\n\tlong keywordConverted[N0] ={0};\n\tstring word; char ch;\n\tchar keywordAux[N0];\n\tcout << \"Keyin a word\";\n\tcin >> word;\n\tfor  (int i=0; i < word.length();i++){\n\t\tkeywordAux[i] = word[i];\n\t\tch  = keywordAux[i];\n\t\tkeywordConverted[i] = (ch);\n\t}\n\tfor (int i =word.length(); i<N0;i++){\n\t\tkeywordConverted[i] = 0;\n\t}\n\tfor (int i =word1.length(); i<N0;i++){\n\t\tkeywordConverted[i] = 0;\n\t}\n\t\tfor (int i =0; i<N0;i++){\n\t\tsum +=keywordConverted[i];\n\t}\n\tsrand(sum);\n\t\t\tfor (int i = 0; i<N0; i++){\n\t\n\tkeywordConverted[i] = (rand())%q0;\n\t\t}\n\t\n\n  /*  for(i=0; i<N0; i++)\n    {\n        kw0[i] = conv<long int>(kw[i]);\n\t\n\n    }\n\n    cout << \"0%\" << flush;*/\n\t\n\n    for(i=0; i<nb_cryp; i++)\n    {\n\n\n\t\tPEKS_Enc(Ciphertext,Ciphertext2,keywordConverted, MPKD);\n\n\t\tPEKS_Test(decrypted,Ciphertext, SKtd_FFT);\n\n\t\tfor(j=0; j<N0; j++){\n\t\t\tif( Ciphertext2[j] != decrypted[j])\n\t\t\t{\n\t\t\t\tcout << \"ERROR : Dec(Enc(m)) != m \" << endl;\n\t\t\t\trep++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t  //  if((i+1)%(nb_cryp/10)==0)\n\t\t\t{\n\t\t   //     cout << \"...\" << (i+1)/(nb_cryp/10) << \"0%\" << flush;\n\t\t\t}\n    }\n\n    cout << endl;\n    if(rep == 0)\n    {    cout << endl << nb_cryp << \" PEKS+TEST successfully performed!\" << endl << endl;    }\n    else\n    {    cout << endl << rep << \" out of \" << nb_cryp << \" PEKS+TEST failed miserabily!\" << endl << endl;    }\n}\n", "meta": {"hexsha": "255e7b25233d2ec8ac72f6dbf1ff68f49c960a05", "size": 15451, "ext": "cc", "lang": "C++", "max_stars_repo_path": "NTRU-PEKS/Scheme.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/Scheme.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/Scheme.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": 22.4578488372, "max_line_length": 218, "alphanum_fraction": 0.4268332147, "num_tokens": 5025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5296229333328043}}
{"text": "//\n//  poly_grav.cpp\n//\n//\n//  Created by Protoss Probe on 2017/05/09.\n//  Copyright \u00a9 2016-2017\u5e74 probe. All rights reserved.\n//\n\n#include <boost/array.hpp>\n#include <cmath>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Eigenvalues>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n#include \"poly_grav.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nvec3 operator+(const vec3 &a1, const vec3 &a2) {\n    vec3 a;\n    for (size_t i = 0; i < 3; i++)\n        a[i] = a1[i] + a2[i];\n    return a;\n}\n\nvec3 operator-(const vec3 &a1, const vec3 &a2) {\n    vec3 a;\n    for (size_t i = 0; i < 3; i++)\n        a[i] = a1[i] - a2[i];\n    return a;\n}\n\nvec3 operator-(const vec3 &a1) {\n    vec3 a;\n    for (size_t i = 0; i < 3; i++)\n        a[i] = -a1[i];\n    return a;\n}\n\nvec3 operator*(const vec3 &a1, const double &a2) {\n    vec3 a;\n    for (size_t i = 0; i < 3; i++)\n        a[i] = a1[i] * a2;\n    return a;\n}\n\nvec3 operator/(const vec3 &a1, const double &a2) {\n    vec3 a;\n    for (size_t i = 0; i < 3; i++)\n        a[i] = a1[i] / a2;\n    return a;\n}\n\nmat3 operator+(const mat3 &a1, const mat3 &a2) {\n    mat3 a;\n    for (size_t i = 0; i < 3; i++) {\n        for (size_t j = 0; j < 3; j++) {\n            a[i][j] = a1[i][j] + a2[i][j];\n        }\n    }\n    return a;\n}\n\nmat3 operator-(const mat3 &a1, const mat3 &a2) {\n    mat3 a;\n    for (size_t i = 0; i < 3; i++) {\n        for (size_t j = 0; j < 3; j++) {\n            a[i][j] = a1[i][j] - a2[i][j];\n        }\n    }\n    return a;\n}\n\nPolyGrav::PolyGrav() = default;\nPolyGrav::~PolyGrav() = default;\nPolyGrav::PolyGrav(string dir) : dir(dir){};\n\nvoid PolyGrav::import_3d_obj(string dir) {\n    // parse .obj file to get vertexs and polygon data\n    string data;\n    double edge_len;\n    vec3 temp, normal, vector1, vector2;\n    mat3 F_f;\n    connect3 temp_c;\n    ifstream objfile(dir);\n    if (objfile.is_open()) {\n        while (!objfile.eof()) {\n            objfile >> data;\n            if (data == \"v\") {\n                for (size_t i = 0; i < 3; i++) {\n                    objfile >> data;\n                    temp[i] = stof(data);\n                }\n                points.push_back(temp);\n            } else if (data == \"f\") {\n                for (size_t i = 0; i < 3; i++) {\n                    objfile >> data;\n                    temp_c[i] = stoi(data) - 1;\n                }\n                vector1 = points[temp_c[1]] - points[temp_c[0]];\n                vector2 = points[temp_c[2]] - points[temp_c[1]];\n                edge_len = PolyGrav::norm(vector1);\n                vector1 = vector1 / edge_len;\n\n                normal = PolyGrav::cross(vector1, vector2);\n                normal = normal / PolyGrav::norm(normal);\n                F_f = PolyGrav::outer(normal, normal);\n\n                polygons.push_back(temp_c);\n                normals.push_back(normal);\n                F_fs.push_back(F_f);\n            }\n        }\n        objfile.close();\n        vert_n = points.size();\n        face_n = polygons.size();\n        edge_n = vert_n + face_n - 2;\n    };\n}\n\nvoid PolyGrav::get_edges_info() {\n    connect2 con;\n    double edge_len;\n    vec3 edge_vec, p0, p1;\n    mat3 E_e;\n    int common_edge;\n    size_t ii;\n\n    for (size_t i = 0; i < face_n; i++) {\n        for (size_t j = 0; j < 3; j++) {\n            con[0] = polygons[i][j];\n            con[1] = polygons[i][(j + 1) % 3];\n            common_edge = PolyGrav::find_common_edge(con, i);\n            if (common_edge != -1) {\n                ii = (size_t)common_edge;\n                p0 = points[con[0]];\n                p1 = points[con[1]];\n                edge_vec = p1 - p0;\n                edge_len = PolyGrav::norm(edge_vec);\n                edge_vec = edge_vec / edge_len;\n                E_e = PolyGrav::outer(normals[i],\n                                      PolyGrav::cross(edge_vec, normals[i])) +\n                      PolyGrav::outer(normals[ii],\n                                      PolyGrav::cross(-edge_vec, normals[ii]));\n\n                edges.push_back({{con[0], con[1], i, ii}});\n                edges_len.push_back(edge_len);\n                E_es.push_back(E_e);\n            }\n        }\n    }\n}\n\nint PolyGrav::find_common_edge(connect2 con, size_t i) {\n    size_t n = i + 1;\n    for (size_t i = n; i < face_n; i++) {\n        for (size_t j = 0; j < 3; j++) {\n            if (con[1] == polygons[i][j] and con[0] == polygons[i][(j + 1) % 3])\n                return i;\n        }\n    }\n    return -1;\n}\n\nvoid PolyGrav::export_3d_txt(string dir, char acc = 'f') {\n    ofstream txtfile;\n    txtfile.open(dir);\n    txtfile << vert_n << endl;\n    txtfile << endl;\n    for (size_t i = 0; i < vert_n; i++) {\n        for (size_t j = 0; j < 3; j++) {\n            if (acc == 'f') {\n                txtfile << float(points[i][j]) << ' ';\n            } else if (acc == 'd') {\n                txtfile << setprecision(8) << points[i][j] << ' ';\n            }\n        }\n        txtfile << endl;\n    }\n    txtfile << endl;\n    txtfile << face_n << endl;\n    txtfile << endl;\n    for (size_t i = 0; i < face_n; i++) {\n        txtfile << 3 << ' ';\n        for (size_t j = 0; j < 3; j++) {\n            txtfile << polygons[i][j] << ' ';\n        }\n        txtfile << endl;\n    }\n\n    txtfile << endl;\n    txtfile << edge_n << endl;\n    txtfile << endl;\n    for (size_t i = 0; i < edge_n; i++) {\n        for (size_t j = 0; j < 4; j++) {\n            txtfile << edges[i][j] << ' ';\n        }\n        txtfile << endl;\n    }\n}\n\nvoid PolyGrav::import_info(string dir) {\n    ifstream txtfile(dir);\n    if (txtfile.is_open()) {\n        while (!txtfile.eof()) {\n            for (size_t i = 0; i < 3; i++) {\n                txtfile >> mc[i];\n            }\n            for (size_t i = 0; i < 3; i++) {\n                for (size_t j = 0; j < 3; j++) {\n                    txtfile >> jj[i][j];\n                }\n            }\n        }\n    }\n    cout << \"Mass and inertia tensor are imported!!\" << endl;\n}\n\nvoid PolyGrav::calexec(string dir) {\n    string exe = \"./bin/volInt \";\n    exe += dir;\n    const char *input = exe.c_str();\n    cout << input << endl;\n    // execl(executable, executable, input, (char *)NULL);\n\n    system(input);\n}\n\nvoid PolyGrav::init() {\n    string filename = dir;\n    PolyGrav::import_3d_obj(\"assets/\" + filename + \".obj\");\n    PolyGrav::get_edges_info();\n    PolyGrav::export_3d_txt(\"assets/\" + filename + \".txt\");\n    PolyGrav::calexec(\"assets/\" + filename + \".txt\");\n    PolyGrav::import_info(\"assets/info.txt\");\n    // cout << \"Initialization Completed!\\n\\n\";\n    // cout << \"Vertex Number: \" << vert_n << \"\\n\\n\"\n    //      << \"Faces Number: \" << face_n << \"\\n\\n\";\n    // cout << \"Center of Mass: \\n\"\n    //      << mc << \"\\n\\n\"\n    //      << \"Inertia Tensor: \\n\"\n    //      << jj << \"\\n\\n\";\n}\n\nvoid PolyGrav::principle_axes() {\n    Matrix3d temp_mat;\n    temp_mat = boost2eigen_mat(jj);\n    EigenSolver<MatrixXd> es(temp_mat);\n    abc = eigen2boost_vec(es.eigenvalues().real());\n    mat3 rotmat = eigen2boost_mat(es.eigenvectors().real());\n    for (auto it = points.begin(); it != points.end(); ++it) {\n        *it = *it - mc;\n        *it = PolyGrav::mul(PolyGrav::transpose(rotmat), *it);\n    }\n}\n\ndouble PolyGrav::L_e(double a, double b, double e) {\n    return log((a + b + e) / (a + b - e));\n}\n\ndouble PolyGrav::omega_f(mat3 r, vec3 r_len) {\n    double y = PolyGrav::dot(r[0], PolyGrav::cross(r[1], r[2]));\n    double x = 0;\n    x += r_len[0] * r_len[1] * r_len[2];\n    for (size_t i = 0; i < 3; i++) {\n        x += r_len[i] * PolyGrav::dot(r[(i + 1) % 3], r[(i + 2) % 3]);\n    }\n\n    return 2 * atan2(y, x);\n}\n\ndouble PolyGrav::potential(vec3 field_p) {\n    double result = 0, E_term = 0, F_term = 0;\n    vec_data r_vec;\n    val_data r_len;\n    for (size_t i = 0; i < vert_n; i++) {\n        r_vec.push_back(points[i] - field_p);\n        r_len.push_back(PolyGrav::norm(r_vec[i]));\n    }\n    // faces loop\n    connect3 polygon;\n    size_t a, b, c;\n    mat3 F_f;\n    vec3 normal;\n    double omega_f;\n    for (size_t n = 0; n < face_n; n++) {\n        polygon = polygons[n];\n        a = polygon[0];\n        b = polygon[1];\n        c = polygon[2];\n        F_f = F_fs[n];\n        normal = normals[n];\n        omega_f = PolyGrav::omega_f({{r_vec[a], r_vec[b], r_vec[c]}},\n                                    {{r_len[a], r_len[b], r_len[c]}});\n        F_term +=\n            PolyGrav::dot(r_vec[a], PolyGrav::mul(F_f, r_vec[a])) * omega_f;\n    }\n    // edges loop\n    double edge_len;\n    mat3 E_e;\n    connect4 edge;\n    for (size_t n = 0; n < edge_n; n++) {\n        edge_len = edges_len[n];\n        E_e = E_es[n];\n        edge = edges[n];\n        a = edge[0], b = edge[1];\n        E_term += PolyGrav::dot(r_vec[a], PolyGrav::mul(E_e, r_vec[a])) *\n                  PolyGrav::L_e(r_len[a], r_len[b], edge_len);\n    }\n    result = co * (E_term - F_term);\n    return result;\n}\n\nVector3d PolyGrav::boost2eigen_vec(vec3 vec) {\n    Vector3d output;\n    for (size_t i = 0; i < 3; i++) {\n        output(i) = vec[i];\n    }\n    return output;\n}\n\nMatrix3d PolyGrav::boost2eigen_mat(mat3 mat) {\n    Matrix3d output;\n    for (size_t i = 0; i < 3; i++) {\n        for (size_t j = 0; j < 3; j++) {\n            output(i, j) = mat[i][j];\n        }\n    }\n    return output;\n}\n\nvec3 PolyGrav::eigen2boost_vec(Vector3d vec) {\n    vec3 output;\n    for (size_t i = 0; i < 3; i++) {\n        output[i] = vec(i);\n    }\n    return output;\n}\n\nmat3 PolyGrav::eigen2boost_mat(Matrix3d mat) {\n    mat3 output;\n    for (size_t i = 0; i < 3; i++) {\n        for (size_t j = 0; j < 3; j++) {\n            output[i][j] = mat(i, j);\n        }\n    }\n    return output;\n}\n\ndouble PolyGrav::norm(const vec3 &vec) {\n    return sqrt(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]);\n}\n\ndouble PolyGrav::dot(const vec3 &vec1, const vec3 &vec2) {\n    return vec1[0] * vec2[0] + vec1[1] * vec2[1] + vec1[2] * vec2[2];\n}\n\nvec3 PolyGrav::cross(const vec3 &vec1, const vec3 &vec2) {\n    vec3 output;\n    output[0] = -vec1[2] * vec2[1] + vec1[1] * vec2[2];\n    output[1] = vec1[2] * vec2[0] - vec1[0] * vec2[2];\n    output[2] = -vec1[1] * vec2[0] + vec1[0] * vec2[1];\n    return output;\n}\n\nvec3 PolyGrav::mul(const mat3 &mat, const vec3 &vec) {\n    vec3 output;\n    for (size_t i = 0; i < 3; i++) {\n        output[i] =\n            mat[i][0] * vec[0] + mat[i][1] * vec[1] + mat[i][2] * vec[2];\n    }\n    return output;\n}\n\nmat3 PolyGrav::outer(const vec3 &vec1, const vec3 &vec2) {\n    mat3 output;\n    for (size_t i = 0; i < 3; i++) {\n        for (size_t j = 0; j < 3; j++) {\n            output[i][j] = vec1[i] * vec2[j];\n        }\n    }\n    return output;\n}\n\nmat3 PolyGrav::transpose(const mat3 &mat) {\n    mat3 output;\n    for (size_t i = 0; i < 3; i++) {\n        for (size_t j = 0; j < 3; j++) {\n            output[i][j] = mat[j][i];\n        }\n    }\n    return output;\n}", "meta": {"hexsha": "03c59c87c31876698c2f55f77bf4ae1dd3718ce6", "size": 10777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/poly_grav.cpp", "max_stars_repo_name": "ProtossProbe/poly_grav", "max_stars_repo_head_hexsha": "7d48acbfe134fb969a1f480817b5de362c9e290c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/poly_grav.cpp", "max_issues_repo_name": "ProtossProbe/poly_grav", "max_issues_repo_head_hexsha": "7d48acbfe134fb969a1f480817b5de362c9e290c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-27T12:49:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-27T12:49:08.000Z", "max_forks_repo_path": "src/poly_grav.cpp", "max_forks_repo_name": "ProtossProbe/poly_grav", "max_forks_repo_head_hexsha": "7d48acbfe134fb969a1f480817b5de362c9e290c", "max_forks_repo_licenses": ["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.1460957179, "max_line_length": 80, "alphanum_fraction": 0.4869629767, "num_tokens": 3470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5296212337153995}}
{"text": "#include \"asymmetric_laplace.hpp\"\n#include \"asymmetric_normal.hpp\"\n#include \"mixture.hpp\"\n#include \"normal.hpp\"\n#include \"laplace.hpp\"\n\n#include <gtest/gtest.h>\n\n#include <boost/random/mersenne_twister.hpp>\n\nusing namespace MultidimensionalArray;\nusing namespace ProbabilityDistributions;\n\nTEST(MixtureTest, LikelihoodNormal) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  Normal<double> dist1(-10, 1);\n  Normal<double> dist2(10, 1);\n  AsymmetricNormal<double> dist3(0.5, -10, 1);\n  AsymmetricNormal<double> dist4(0.5, 10, 1);\n  dist3.fix_p(true);\n  dist4.fix_p(true);\n  auto dist = make_mixture(dist1, dist2);\n  auto dist_a = make_mixture(dist3, dist4);\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n\n  double likelihood1 = dist.log_likelihood(samples);\n  double likelihood1_a = dist_a.log_likelihood(samples);\n  EXPECT_DOUBLE_EQ(likelihood1, likelihood1_a);\n\n  dist.get_component<0>().set_mu(-0.1);\n  dist.get_component<1>().set_mu(0.1);\n  dist_a.get_component<0>().set_mu(-0.1);\n  dist_a.get_component<1>().set_mu(0.1);\n\n  auto new_dist = make_mixture(Laplace<double>(-0.1, 1),\n      Laplace<double>(0.1, 1));\n\n  dist.MLE(samples);\n  dist_a.MLE(samples);\n  new_dist.MLE(samples);\n\n  double likelihood2 = dist.log_likelihood(samples);\n  double likelihood2_a = dist_a.log_likelihood(samples);\n  double new_likelihood = new_dist.log_likelihood(samples);\n\n  EXPECT_NEAR(likelihood2, likelihood2_a, 1e-8);\n  EXPECT_GE(likelihood2, likelihood1);\n  EXPECT_GE(likelihood2, new_likelihood);\n}\n\nTEST(MixtureTest, LikelihoodLaplace) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  Laplace<double> dist1(-10, 1);\n  Laplace<double> dist2(10, 1);\n  AsymmetricLaplace<double> dist3(0.5, -10, 1);\n  AsymmetricLaplace<double> dist4(0.5, 10, 1);\n  dist3.fix_p(true);\n  dist4.fix_p(true);\n  auto dist = make_mixture(dist1, dist2);\n  auto dist_a = make_mixture(dist3, dist4);\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n\n  double likelihood1 = dist.log_likelihood(samples);\n  double likelihood1_a = dist_a.log_likelihood(samples);\n  EXPECT_DOUBLE_EQ(likelihood1, likelihood1_a);\n\n  dist.get_component<0>().set_mu(-0.1);\n  dist.get_component<1>().set_mu(0.1);\n  dist_a.get_component<0>().set_mu(-0.1);\n  dist_a.get_component<1>().set_mu(0.1);\n\n  auto new_dist = make_mixture(Normal<double>(-0.1, 1), Normal<double>(0.1, 1));\n\n  dist.MLE(samples);\n  dist_a.MLE(samples);\n  new_dist.MLE(samples);\n\n  double likelihood2 = dist.log_likelihood(samples);\n  double likelihood2_a = dist_a.log_likelihood(samples);\n  double new_likelihood = new_dist.log_likelihood(samples);\n\n  EXPECT_NEAR(likelihood2, likelihood2_a, 1e-8);\n  EXPECT_GE(likelihood2, likelihood1);\n  EXPECT_GE(likelihood2, new_likelihood);\n}\n\nTEST(MixtureTest, LikelihoodAsymmetricNormal) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  AsymmetricNormal<double> dist1(0.5, -10, 1);\n  AsymmetricNormal<double> dist2(0.5, 10, 1);\n  auto dist = make_mixture(dist1, dist2);\n  dist1.fix_p(true);\n  dist2.fix_p(true);\n  auto dist_a = make_mixture(dist1, dist2);\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n\n  double likelihood1 = dist.log_likelihood(samples);\n  double likelihood1_a = dist_a.log_likelihood(samples);\n  EXPECT_DOUBLE_EQ(likelihood1, likelihood1_a);\n\n  dist.get_component<0>().set_mu(-0.1);\n  dist.get_component<1>().set_mu(0.1);\n  dist_a.get_component<0>().set_mu(-0.1);\n  dist_a.get_component<1>().set_mu(0.1);\n\n  auto new_dist = make_mixture(Laplace<double>(-0.1, 1),\n      Laplace<double>(0.1, 1));\n\n  dist.MLE(samples);\n\n  dist_a.MLE(samples);\n  new_dist.MLE(samples);\n\n  double likelihood2 = dist.log_likelihood(samples);\n  double likelihood2_a = dist_a.log_likelihood(samples);\n  double new_likelihood = new_dist.log_likelihood(samples);\n\n  EXPECT_GE(likelihood2, likelihood2_a);\n  EXPECT_GE(likelihood2, likelihood1);\n  EXPECT_GE(likelihood2, new_likelihood);\n}\n\nTEST(MixtureTest, LikelihoodAsymmetricLaplace) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  AsymmetricLaplace<double> dist1(0.5, -10, 1);\n  AsymmetricLaplace<double> dist2(0.5, 10, 1);\n  auto dist = make_mixture(dist1, dist2);\n  dist1.fix_p(true);\n  dist2.fix_p(true);\n  auto dist_a = make_mixture(dist1, dist2);\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n\n  double likelihood1 = dist.log_likelihood(samples);\n  double likelihood1_a = dist_a.log_likelihood(samples);\n  EXPECT_DOUBLE_EQ(likelihood1, likelihood1_a);\n\n  dist.get_component<0>().set_mu(-0.1);\n  dist.get_component<1>().set_mu(0.1);\n  dist_a.get_component<0>().set_mu(-0.1);\n  dist_a.get_component<1>().set_mu(0.1);\n\n  auto new_dist = make_mixture(Normal<double>(-0.1, 1), Normal<double>(0.1, 1));\n\n  dist.MLE(samples);\n\n  dist_a.MLE(samples);\n  new_dist.MLE(samples);\n\n  double likelihood2 = dist.log_likelihood(samples);\n  double likelihood2_a = dist_a.log_likelihood(samples);\n  double new_likelihood = new_dist.log_likelihood(samples);\n\n  EXPECT_GE(likelihood2, likelihood2_a);\n  EXPECT_GE(likelihood2, likelihood1);\n  EXPECT_GE(likelihood2, new_likelihood);\n}\n\nTEST(MixtureTest, Samples) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  Normal<double> dist1(-10, 1);\n  Normal<double> dist2(10, 1);\n  auto dist = make_mixture(dist1, dist2);\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n  unsigned int count_0 = 0, count_1 = 0;\n\n  for (size_t i = 0; i < n_samples; i++) {\n    if (samples(i,0) < 0) {\n      EXPECT_LT(-15, samples(i,0));\n      EXPECT_GT(-5, samples(i,0));\n      count_0++;\n    }\n    else {\n      EXPECT_LT(5, samples(i,0));\n      EXPECT_GT(15, samples(i,0));\n      count_1++;\n    }\n  }\n\n  EXPECT_LT(0, count_0);\n  EXPECT_LT(0, count_1);\n}\n", "meta": {"hexsha": "d914014bc9bb50af72a21bb1adda4b469eab2e09", "size": 5764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/mixture.cpp", "max_stars_repo_name": "mirandaconrado/probability-distributions", "max_stars_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/mixture.cpp", "max_issues_repo_name": "mirandaconrado/probability-distributions", "max_issues_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/mixture.cpp", "max_forks_repo_name": "mirandaconrado/probability-distributions", "max_forks_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0208333333, "max_line_length": 80, "alphanum_fraction": 0.7199861207, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5296212280432165}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_TWO_PROD_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_TWO_PROD_HPP_INCLUDED\n#include <boost/simd/arithmetic/functions/two_prod.hpp>\n#include <boost/simd/include/functions/minus.hpp>\n#include <boost/simd/include/functions/two_split.hpp>\n#include <boost/simd/include/functions/multiplies.hpp>\n#include <boost/simd/include/functions/is_invalid.hpp>\n#include <boost/simd/include/functions/if_zero_else.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::two_prod_\n                                    , tag::cpu_\n                                    , (A0)\n                                    , (generic_< floating_<A0> >)\n                                      (generic_< floating_<A0> >)\n                                      (generic_< floating_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE\n    result_type operator()(A0 const& a0,A0 const& a1,A0& a3) const\n    {\n      result_type a2;\n      boost::simd::two_prod(a0, a1, a2, a3);\n      return a2;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::two_prod_, tag::cpu_\n                                    , (A0)\n                                    , (generic_< floating_<A0> >)\n                                      (generic_< floating_<A0> >)\n                                    )\n  {\n    typedef std::pair<A0,A0>                                   result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0,A0 const& a1) const\n    {\n      result_type res;\n      boost::simd::two_prod( a0, a1, res.first, res.second );\n      return res;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::two_prod_, tag::cpu_\n                                    , (A0)\n                                    , (generic_< floating_<A0> >)\n                                      (generic_< floating_<A0> >)\n                                      (generic_< floating_<A0> >)\n                                      (generic_< floating_<A0> >)\n                                    )\n  {\n    typedef void result_type;\n    BOOST_FORCEINLINE\n    result_type operator()(A0 const& a,A0 const& b, A0 & r0,A0 & r1) const\n    {\n      A0 a1, a2, b1, b2;\n      r0  = a*b;\n\n      two_split(a, a1, a2);\n      two_split(b, b1, b2);\n\n#if defined(BOOST_SIMD_NO_INVALIDS)\n      r1 = a2*b2 -(((r0-a1*b1)-a2*b1)-a1*b2);\n#else\n      r1 = if_zero_else(is_invalid(r0), a2*b2 -(((r0-a1*b1)-a2*b1)-a1*b2));\n#endif\n\n\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "75ead5971e25d3bf5ff650c88029a20877919dcf", "size": 3149, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/generic/two_prod.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/generic/two_prod.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/generic/two_prod.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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.1954022989, "max_line_length": 80, "alphanum_fraction": 0.5039695141, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5296212223710336}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n    dense2D<double>       A(5, 5), H(5, 5);  A= 0.0;  \n    \n    A[0][1] = 3;  A[1][4] = 7; A[0][0] = 1; A[4][4] = 17;\n    A[2][3] = -2; A[2][4] = 5; A[4][0] = 2; A[4][1] = 3;\n    A[3][2] = 4;\n    \n    H= hessenberg(A);\n    std::cout<< \"Hessenberg=\\n\" << H << \"\\n\";\n    H= extract_householder_hessenberg(A);\n    std::cout<< \"extract_householder_hessenberg=\\n\" << H << \"\\n\";\n    H= extract_hessenberg(A);\n    std::cout<< \"extract_hessenberg=\\n\" << H << \"\\n\";\n    H= householder_hessenberg(A);\n    std::cout<< \"householder_hessenberg=\\n\" << H << \"\\n\";\n    H= hessenberg_factors(A);\n    std::cout<< \"hessenberg_factors=\\n\" << H << \"\\n\";\n    // H= hessenberg_q(A);\n    // std::cout<< \"hessenberg_q=\\n\" << H << \"\\n\";\n\n   return 0;\n}\n", "meta": {"hexsha": "7e8d1bd24e2c6d1a752458b839054215f8ee748d", "size": 834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/hessenberg_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/hessenberg_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/hessenberg_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.7857142857, "max_line_length": 65, "alphanum_fraction": 0.5179856115, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6406358548398982, "lm_q1q2_score": 0.5296212169006917}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_AVERAGE_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_AVERAGE_HPP_INCLUDED\n#include <boost/simd/arithmetic/functions/average.hpp>\n#include <boost/simd/include/functions/simd/bitwise_and.hpp>\n#include <boost/simd/include/functions/simd/bitwise_xor.hpp>\n#include <boost/simd/include/functions/simd/plus.hpp>\n#include <boost/simd/include/functions/simd/multiplies.hpp>\n#include <boost/simd/include/functions/simd/shrai.hpp>\n#include <boost/simd/include/constants/half.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::average_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<arithmetic_<A0>,X>))((simd_<arithmetic_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return b_and(a0, a1)+shrai(b_xor(a0, a1),1);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::average_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<floating_<A0>,X>))((simd_<floating_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n       return (a0+a1)*Half<A0>();\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "1541a20a2ca3939c175a6038f6503989139e0e3f", "size": 1828, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/simd/common/average.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/simd/common/average.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/simd/common/average.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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.0833333333, "max_line_length": 86, "alphanum_fraction": 0.5782275711, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.5296212112285087}}
{"text": "\n// From:\n// http://stackoverflow.com/questions/6142576/sample-from-multivariate-normal-gaussian-distribution-in-c\n \n#include <iostream>\n#include <chrono>\n#include <functional>\n\n\n#include \"ThreadVector.hpp\"\n\n#include \"omp_util.h\"\n\n#ifdef USE_BOOST_RANDOM\n#include <boost/random.hpp>\n#define MERSENNE_TWISTER boost::random::mt19937\n#define UNIFORM_REAL_DISTRIBUTION boost::random::uniform_real_distribution<double>\n#define GAMMA_DISTRIBUTION boost::random::gamma_distribution<double>\n#else\n#include <random>\n#define MERSENNE_TWISTER std::mt19937\n#define UNIFORM_REAL_DISTRIBUTION std::uniform_real_distribution<double>\n#define GAMMA_DISTRIBUTION std::gamma_distribution<double>\n#endif\n\n#include <Eigen/Dense>\n\n#include \"Distribution.h\"\n\nusing namespace Eigen;\n\nstatic smurff::thread_vector<MERSENNE_TWISTER> bmrngs;\n\ndouble smurff::randn0()\n{\n   return smurff::bmrandn_single_thread();\n}\n\ndouble smurff::randn(double) \n{\n   return smurff::bmrandn_single_thread();\n}\n\nvoid smurff::bmrandn(double* x, long n) \n{\n   #pragma omp parallel \n   {\n      UNIFORM_REAL_DISTRIBUTION unif(-1.0, 1.0);\n      auto& bmrng = bmrngs.local();\n      \n      #pragma omp for schedule(static)\n      for (long i = 0; i < n; i += 2) \n      {\n         double x1, x2, w;\n         do \n         {\n           x1 = unif(bmrng);\n           x2 = unif(bmrng);\n           w = x1 * x1 + x2 * x2;\n         } while ( w >= 1.0 );\n   \n         w = std::sqrt( (-2.0 * std::log( w ) ) / w );\n         x[i] = x1 * w;\n\n         if (i + 1 < n) \n         {\n           x[i+1] = x2 * w;\n         }\n      }\n   }\n}\n   \nvoid smurff::bmrandn(Eigen::MatrixXd & X) \n{\n   long n = X.rows() * (long)X.cols();\n   smurff::bmrandn(X.data(), n);\n}\n\ndouble smurff::bmrandn_single_thread() \n{\n   //TODO: add bmrng as input\n   UNIFORM_REAL_DISTRIBUTION unif(-1.0, 1.0);\n   auto& bmrng = bmrngs.local();\n  \n   double x1, x2, w;\n   do \n   {\n      x1 = unif(bmrng);\n      x2 = unif(bmrng);\n      w = x1 * x1 + x2 * x2;\n   } while ( w >= 1.0 );\n\n   w = std::sqrt( (-2.0 * std::log( w ) ) / w );\n   return x1 * w;\n}\n\n// to be called within OpenMP parallel loop (also from serial code is fine)\nvoid smurff::bmrandn_single_thread(double* x, long n) \n{\n   UNIFORM_REAL_DISTRIBUTION unif(-1.0, 1.0);\n   auto& bmrng = bmrngs.local();\n\n   for (long i = 0; i < n; i += 2) \n   {\n      double x1, x2, w;\n\n      do \n      {\n         x1 = unif(bmrng);\n         x2 = unif(bmrng);\n         w = x1 * x1 + x2 * x2;\n      } while ( w >= 1.0 );\n \n      w = std::sqrt( (-2.0 * std::log( w ) ) / w );\n      x[i] = x1 * w;\n\n      if (i + 1 < n) \n      {\n         x[i+1] = x2 * w;\n      }\n   }\n}\n  \nvoid smurff::bmrandn_single_thread(Eigen::VectorXd & x) \n{\n   smurff::bmrandn_single_thread(x.data(), x.size());\n}\n \nvoid smurff::bmrandn_single_thread(Eigen::MatrixXd & X) \n{\n   long n = X.rows() * (long)X.cols();\n   smurff::bmrandn_single_thread(X.data(), n);\n}\n\n\nvoid smurff::init_bmrng() \n{\n   using namespace std::chrono;\n   auto ms = (duration_cast< milliseconds >(system_clock::now().time_since_epoch())).count();\n   smurff::init_bmrng(ms);\n}\n\nvoid smurff::init_bmrng(int seed) \n{\n    std::vector<MERSENNE_TWISTER> v;\n    for (int i = 0; i < threads::get_max_threads(); i++)\n    {\n        v.push_back(MERSENNE_TWISTER(seed + i * 1999));\n    }\n\n    bmrngs.init(v);\n}\n   \ndouble smurff::rand_unif() \n{\n   UNIFORM_REAL_DISTRIBUTION unif(0.0, 1.0);\n   auto& bmrng = bmrngs.local();\n   return unif(bmrng);\n}\n \ndouble smurff::rand_unif(double low, double high) \n{\n   UNIFORM_REAL_DISTRIBUTION unif(low, high);\n   auto& bmrng = bmrngs.local();\n   return unif(bmrng);\n}\n\n// returns random number according to Gamma distribution\n// with the given shape (k) and scale (theta). See wiki.\ndouble smurff::rgamma(double shape, double scale) \n{\n   GAMMA_DISTRIBUTION gamma(shape, scale);\n   return gamma(bmrngs.local());\n}\n\nauto smurff::nrandn(int n) -> decltype(Eigen::VectorXd::NullaryExpr(n, std::cref(randn))) \n{\n   return Eigen::VectorXd::NullaryExpr(n, std::cref(randn));\n}\n\nauto smurff::nrandn(int n, int m) -> decltype(Eigen::ArrayXXd::NullaryExpr(n, m, std::cref(randn)))\n{\n   return Eigen::ArrayXXd::NullaryExpr(n, m, std::cref(randn)); \n}\n\n\nEigen::MatrixXd WishartUnit(int m, int df)\n{\n   Eigen::MatrixXd c(m,m);\n   c.setZero();\n   auto& rng = bmrngs.local();\n\n   for ( int i = 0; i < m; i++ ) \n   {\n      GAMMA_DISTRIBUTION gam(0.5*(df - i));\n      c(i,i) = std::sqrt(2.0 * gam(rng));\n      Eigen::VectorXd r = smurff::nrandn(m-i-1);\n      c.block(i,i+1,1,m-i-1) = r.transpose();\n   }\n\n   Eigen::MatrixXd ret = c.transpose() * c;\n\n   #ifdef TEST_MVNORMAL\n   cout << \"WISHART UNIT {\\n\" << endl;\n   cout << \"  m:\\n\" << m << endl;\n   cout << \"  df:\\n\" << df << endl;\n   cout << \"  ret;\\n\" << ret << endl;\n   cout << \"  c:\\n\" << c << endl;\n   cout << \"}\\n\" << ret << endl;\n   #endif\n\n   return ret;\n}\n\nMatrixXd Wishart(const Eigen::MatrixXd &sigma, const int df)\n{\n   //  Get R, the upper triangular Cholesky factor of SIGMA.\n   auto chol = sigma.llt();\n   Eigen::MatrixXd r = chol.matrixL();\n\n   //  Get AU, a sample from the unit Wishart distribution.\n   Eigen::MatrixXd au = WishartUnit(sigma.cols(), df);\n\n   //  Construct the matrix A = R' * AU * R.\n   Eigen::MatrixXd a = r * au * chol.matrixU();\n\n   #ifdef TEST_MVNORMAL\n   cout << \"WISHART {\\n\" << endl;\n   cout << \"  sigma:\\n\" << sigma << endl;\n   cout << \"  r:\\n\" << r << endl;\n   cout << \"  au:\\n\" << au << endl;\n   cout << \"  df:\\n\" << df << endl;\n   cout << \"  a:\\n\" << a << endl;\n   cout << \"}\\n\" << endl;\n   #endif\n\n  return a;\n}\n\n// from julia package Distributions: conjugates/normalwishart.jl\nstd::pair<Eigen::VectorXd, Eigen::MatrixXd> smurff::NormalWishart(const Eigen::VectorXd & mu, double kappa, const Eigen::MatrixXd & T, double nu)\n{\n   Eigen::MatrixXd Lam = Wishart(T, nu);\n   Eigen::MatrixXd mu_o = smurff::MvNormal_prec(Lam * kappa, mu);\n\n   #ifdef TEST_MVNORMAL\n   cout << \"NORMAL WISHART {\\n\" << endl;\n   cout << \"  mu:\\n\" << mu << endl;\n   cout << \"  kappa:\\n\" << kappa << endl;\n   cout << \"  T:\\n\" << T << endl;\n   cout << \"  nu:\\n\" << nu << endl;\n   cout << \"  mu_o\\n\" << mu_o << endl;\n   cout << \"  Lam\\n\" << Lam << endl;\n   cout << \"}\\n\" << endl;\n   #endif\n\n   return std::make_pair(mu_o , Lam);\n}\n\nstd::pair<Eigen::VectorXd, Eigen::MatrixXd> smurff::CondNormalWishart(const int N, const Eigen::MatrixXd &NS, const Eigen::VectorXd &NU, const Eigen::VectorXd &mu, const double kappa, const Eigen::MatrixXd &T, const int nu)\n{\n   int nu_c = nu + N;\n\n   double kappa_c = kappa + N;\n   auto mu_c = (kappa * mu + NU) / (kappa + N);\n   auto X    = (T + NS + kappa * mu * mu.adjoint() - kappa_c * mu_c * mu_c.adjoint());\n   Eigen::MatrixXd T_c = X.inverse();\n    \n   return NormalWishart(mu_c, kappa_c, T_c, nu_c);\n}\n\nstd::pair<Eigen::VectorXd, Eigen::MatrixXd> smurff::CondNormalWishart(const Eigen::MatrixXd &U, const Eigen::VectorXd &mu, const double kappa, const Eigen::MatrixXd &T, const int nu)\n{\n   auto N = U.cols();\n   auto NS = U * U.adjoint();\n   auto NU = U.rowwise().sum();\n   return CondNormalWishart(N, NS, NU, mu, kappa, T, nu);\n}\n\n// Normal(0, Lambda^-1) for nn columns\nMatrixXd smurff::MvNormal_prec(const Eigen::MatrixXd & Lambda, int ncols)\n{\n   int nrows = Lambda.rows(); // Dimensionality (rows)\n   LLT<Eigen::MatrixXd> chol(Lambda);\n\n   Eigen::MatrixXd r(nrows, ncols);\n   smurff::bmrandn(r);\n\n   return chol.matrixU().solve(r);\n}\n\nEigen::MatrixXd smurff::MvNormal_prec(const Eigen::MatrixXd & Lambda, const Eigen::VectorXd & mean, int nn)\n{\n   Eigen::MatrixXd r = MvNormal_prec(Lambda, nn);\n   return r.colwise() + mean;\n}\n\n// Draw nn samples from a size-dimensional normal distribution\n// with a specified mean and covariance\nEigen::MatrixXd smurff::MvNormal(const Eigen::MatrixXd covar, const Eigen::VectorXd mean, int nn) \n{\n   int size = mean.rows(); // Dimensionality (rows)\n   Eigen::MatrixXd normTransform(size,size);\n\n   LLT<Eigen::MatrixXd> cholSolver(covar);\n   normTransform = cholSolver.matrixL();\n\n   auto normSamples = Eigen::MatrixXd::NullaryExpr(size, nn, std::cref(randn));\n   Eigen::MatrixXd samples = (normTransform * normSamples).colwise() + mean;\n\n   return samples;\n}\n", "meta": {"hexsha": "7b01a8492930a1f9b5758dcc7edc8ba20f4fc81c", "size": 8102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/smurff-cpp/SmurffCpp/Utils/Distribution.cpp", "max_stars_repo_name": "msteijaert/smurff", "max_stars_repo_head_hexsha": "e6066d51e1640e9aad0118628ba72c9d662919fb", "max_stars_repo_licenses": ["MIT"], "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/smurff-cpp/SmurffCpp/Utils/Distribution.cpp", "max_issues_repo_name": "msteijaert/smurff", "max_issues_repo_head_hexsha": "e6066d51e1640e9aad0118628ba72c9d662919fb", "max_issues_repo_licenses": ["MIT"], "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/smurff-cpp/SmurffCpp/Utils/Distribution.cpp", "max_forks_repo_name": "msteijaert/smurff", "max_forks_repo_head_hexsha": "e6066d51e1640e9aad0118628ba72c9d662919fb", "max_forks_repo_licenses": ["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.8849840256, "max_line_length": 223, "alphanum_fraction": 0.6113305357, "num_tokens": 2566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.5296212112285087}}
{"text": "#pragma once\n\n#include <complex>\n#include <memory>\n#include <utility>\n\n#include <Eigen/SVD>\n\n#include \"common.hpp\"\n#include \"piecewise_polynomial.hpp\"\n#include \"irlib/detail/basis_impl.ipp\"\n\nnamespace irlib {\n    /**\n     * Abstract class representing an analytical continuation kernel\n     */\n    template<typename T>\n    class kernel {\n    public:\n        typedef T mp_type;\n\n        virtual ~kernel() {};\n\n        /// return the value of the kernel for given x and y in the [-1,1] interval.\n        virtual T operator()(T x, T y) const = 0;\n\n        /// return statistics\n        virtual irlib::statistics::statistics_type get_statistics() const = 0;\n\n        /// return lambda\n        virtual double Lambda() const = 0;\n\n#ifndef SWIG\n\n        /// return a reference to a copy\n        virtual std::shared_ptr<kernel> clone() const = 0;\n\n#endif\n    };\n\n#ifdef SWIG\n    %template(real_kernel) kernel<mpreal>;\n#endif\n\n    /**\n     * Fermionic kernel\n     */\n    template<typename S>\n    class fermionic_kernel : public kernel<S> {\n    public:\n        fermionic_kernel(S Lambda) : Lambda_(Lambda) {}\n\n        virtual ~fermionic_kernel() {};\n\n        S operator()(S x, S y) const {\n            const S limit = 100.0;\n            if (Lambda_ * y > limit) {\n                return std::exp(-0.5 * Lambda_ * x * y - 0.5 * Lambda_ * y);\n            } else if (Lambda_ * y < -limit) {\n                return std::exp(-0.5 * Lambda_ * x * y + 0.5 * Lambda_ * y);\n            } else {\n                return std::exp(-0.5 * Lambda_ * x * y) / (2 * std::cosh(0.5 * Lambda_ * y));\n            }\n        }\n\n        irlib::statistics::statistics_type get_statistics() const {\n            return irlib::statistics::FERMIONIC;\n        }\n\n        double Lambda() const {\n            return Lambda_;\n        }\n\n#ifndef SWIG\n\n        std::shared_ptr <kernel<S> > clone() const {\n            return std::shared_ptr<kernel<S> >(new fermionic_kernel<S>(Lambda_));\n        }\n\n#endif\n\n    private:\n        double Lambda_;\n    };\n\n    template<>\n    class fermionic_kernel<mpreal> : public kernel<mpreal> {\n    public:\n        fermionic_kernel(double Lambda) : Lambda_(Lambda) {}\n\n        virtual ~fermionic_kernel() {};\n\n        mpreal operator()(mpreal x, mpreal y) const {\n            mpreal half_Lambda = mpreal(\"0.5\") * mpreal(Lambda_);\n\n            const double limit = 200.0;\n            if (Lambda_ * y > limit) {\n                return mpfr::exp(-half_Lambda * x * y - half_Lambda * y);\n            } else if (Lambda_ * y < -limit) {\n                return mpfr::exp(-half_Lambda * x * y + half_Lambda * y);\n            } else {\n                return mpfr::exp(-half_Lambda * x * y) / (2 * mpfr::cosh(half_Lambda * y));\n            }\n        }\n\n        irlib::statistics::statistics_type get_statistics() const {\n            return irlib::statistics::FERMIONIC;\n        }\n\n        double Lambda() const {\n            return Lambda_;\n        }\n\n#ifndef SWIG\n\n        std::shared_ptr<kernel<mpreal>> clone() const {\n            return std::shared_ptr<kernel<mpreal>>(new fermionic_kernel(Lambda_));\n        }\n\n#endif\n\n    private:\n        double Lambda_;\n    };\n\n\n    /**\n     * Bosonic kernel\n     */\n    template<typename S>\n    class bosonic_kernel : public kernel<S> {\n    public:\n        bosonic_kernel(double Lambda) : Lambda_(Lambda) {}\n\n        virtual ~bosonic_kernel() {};\n\n        S operator()(S x, S y) const {\n            const S limit = 100.0;\n            if (std::abs(Lambda_ * y) < 1e-10) {\n                return std::exp(-0.5 * Lambda_ * x * y) / Lambda_;\n            } else if (Lambda_ * y > limit) {\n                return y * std::exp(-0.5 * Lambda_ * x * y - 0.5 * Lambda_ * y);\n            } else if (Lambda_ * y < -limit) {\n                return -y * std::exp(-0.5 * Lambda_ * x * y + 0.5 * Lambda_ * y);\n            } else {\n                return y * std::exp(-0.5 * Lambda_ * x * y) / (2 * std::sinh(0.5 * Lambda_ * y));\n            }\n        }\n\n        irlib::statistics::statistics_type get_statistics() const {\n            return irlib::statistics::BOSONIC;\n        }\n\n        double Lambda() const {\n            return Lambda_;\n        }\n\n#ifndef SWIG\n\n        std::shared_ptr <kernel<S>> clone() const {\n            return std::shared_ptr<kernel<S>>(new bosonic_kernel<S>(Lambda_));\n        }\n\n#endif\n\n    private:\n        double Lambda_;\n    };\n\n    template<>\n    class bosonic_kernel<mpreal> : public kernel<mpreal> {\n    public:\n        bosonic_kernel(double Lambda) : Lambda_(Lambda) {}\n\n        virtual ~bosonic_kernel() {};\n\n        mpreal operator()(mpreal x, mpreal y) const {\n            const double limit = 200.0;\n            mpreal half_Lambda = mpreal(\"0.5\") * mpreal(Lambda_);\n\n            if (mpfr::abs(Lambda_ * y) < 1e-30) {\n                return mpfr::exp(-half_Lambda * x * y) / Lambda_;\n            } else if (Lambda_ * y > limit) {\n                return y * mpfr::exp(-half_Lambda * x * y - half_Lambda * y);\n            } else if (Lambda_ * y < -limit) {\n                return -y * mpfr::exp(-half_Lambda * x * y + half_Lambda * y);\n            } else {\n                return y * mpfr::exp(-half_Lambda * x * y) / (2 * mpfr::sinh(half_Lambda * y));\n            }\n        }\n\n        irlib::statistics::statistics_type get_statistics() const {\n            return irlib::statistics::BOSONIC;\n        }\n\n        double Lambda() const {\n            return Lambda_;\n        }\n\n#ifndef SWIG\n\n        std::shared_ptr<kernel<mpreal>> clone() const {\n            return std::shared_ptr<kernel<mpreal>>(new bosonic_kernel(Lambda_));\n        }\n\n#endif\n\n    private:\n        double Lambda_;\n    };\n\n\n}\n", "meta": {"hexsha": "2a5deba27aa1286988b703273428af74dc29fb82", "size": 5633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/include/irlib/kernel.hpp", "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++/include/irlib/kernel.hpp", "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++/include/irlib/kernel.hpp", "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": 26.3224299065, "max_line_length": 97, "alphanum_fraction": 0.5286703355, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5295839484907263}}
{"text": "#include <Eigen/Dense>\n#include <chrono>\n#include <iostream>\n#include <opencv2/core.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/highgui.hpp>\n#include <features.hpp>\n\nvoid cfar1d(cv::Mat fft_data, int window_size, float scale, int guard_cells, int min_range, Eigen::MatrixXd &targets) {\n    assert(fft_data.depth() == CV_32F);\n    assert(fft_data.channels() == 1);\n    auto t1 = std::chrono::high_resolution_clock::now();\n    int kernel_size = window_size + guard_cells * 2 + 1;\n    cv::Mat kernel = cv::Mat::ones(1, kernel_size, CV_32F) * -1 * scale / window_size;\n    kernel.at<float>(0, kernel_size / 2) = 1;\n    for (int i = 0; i < guard_cells; i++) {\n        kernel.at<float>(0, window_size / 2 + i) = 0;\n    }\n    for (int i = 0; i < guard_cells; i++) {\n        kernel.at<float>(0, kernel_size / 2 + 1 + i) = 0;\n    }\n    cv::Mat output;\n    cv::filter2D(fft_data, output, -1, kernel, cv::Point(-1, -1), 0, cv::BORDER_REFLECT101);\n    // Find filter responses > 0\n    std::vector<cv::Point2f> t;\n    for (int i = 0; i < output.rows; ++i) {\n        for (int j = min_range; j < output.cols; j++) {\n            if (output.at<float>(i, j) > 0) {\n                t.push_back(cv::Point(i, j));\n            }\n        }\n    }\n    targets = Eigen::MatrixXd::Ones(3, t.size());\n    for (uint i = 0; i < t.size(); ++i) {\n        targets(0, i) = t[i].x;\n        targets(1, i) = t[i].y;\n    }\n    auto t2 = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> e = t2 - t1;\n    std::cout << \"feature extraction: \" << e.count() << std::endl;\n}\n\n// Runtime: 0.035s\ndouble cen2018features(cv::Mat fft_data, float zq, int sigma_gauss, int min_range, Eigen::MatrixXd &targets) {\n    auto t1 = std::chrono::high_resolution_clock::now();\n\n    std::vector<float> sigma_q(fft_data.rows, 0);\n    // Estimate the bias and subtract it from the signal\n    cv::Mat q = fft_data.clone();\n    for (int i = 0; i < fft_data.rows; ++i) {\n        float mean = 0;\n        for (int j = 0; j < fft_data.cols; ++j) {\n            mean += fft_data.at<float>(i, j);\n        }\n        mean /= fft_data.cols;\n        for (int j = 0; j < fft_data.cols; ++j) {\n            q.at<float>(i, j) = fft_data.at<float>(i, j) - mean;\n        }\n    }\n\n    // Create 1D Gaussian Filter (0.09)\n    assert(sigma_gauss % 2 == 1);\n    int fsize = sigma_gauss * 3;\n    int mu = fsize / 2;\n    float sig_sqr = sigma_gauss * sigma_gauss;\n    cv::Mat filter = cv::Mat::zeros(1, fsize, CV_32F);\n    float s = 0;\n    for (int i = 0; i < fsize; ++i) {\n        filter.at<float>(0, i) = exp(-0.5 * (i - mu) * (i - mu) / sig_sqr);\n        s += filter.at<float>(0, i);\n    }\n    filter /= s;\n    cv::Mat p;\n    cv::filter2D(q, p, -1, filter, cv::Point(-1, -1), 0, cv::BORDER_REFLECT101);\n\n    // Estimate variance of noise at each azimuth (0.004)\n    for (int i = 0; i < fft_data.rows; ++i) {\n        int nonzero = 0;\n        for (int j = 0; j < fft_data.cols; ++j) {\n            float n = q.at<float>(i, j);\n            if (n < 0) {\n                sigma_q[i] += 2 * (n * n);\n                nonzero++;\n            }\n        }\n        if (nonzero)\n            sigma_q[i] = sqrt(sigma_q[i] / nonzero);\n        else\n            sigma_q[i] = 0.034;\n    }\n\n    // Extract peak centers from each azimuth\n    std::vector<std::vector<cv::Point2f>> t(fft_data.rows);\n#pragma omp parallel for\n    for (int i = 0; i < fft_data.rows; ++i) {\n        std::vector<int> peak_points;\n        float thres = zq * sigma_q[i];\n        for (int j = min_range; j < fft_data.cols; ++j) {\n            float nqp = exp(-0.5 * pow((q.at<float>(i, j) - p.at<float>(i, j)) / sigma_q[i], 2));\n            float npp = exp(-0.5 * pow(p.at<float>(i, j) / sigma_q[i], 2));\n            float b = nqp - npp;\n            float y = q.at<float>(i, j) * (1 - nqp) + p.at<float>(i, j) * b;\n            if (y > thres) {\n                peak_points.push_back(j);\n            } else if (peak_points.size() > 0) {\n                t[i].push_back(cv::Point(i, peak_points[peak_points.size() / 2]));\n                peak_points.clear();\n            }\n        }\n        if (peak_points.size() > 0)\n            t[i].push_back(cv::Point(i, peak_points[peak_points.size() / 2]));\n    }\n\n    int size = 0;\n    for (uint i = 0; i < t.size(); ++i) {\n        size += t[i].size();\n    }\n    targets = Eigen::MatrixXd::Ones(3, size);\n    int k = 0;\n    for (uint i = 0; i < t.size(); ++i) {\n        for (uint j = 0; j < t[i].size(); ++j) {\n            targets(0, k) = t[i][j].x;\n            targets(1, k) = t[i][j].y;\n            k++;\n        }\n    }\n\n    auto t2 = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> e = t2 - t1;\n    return e.count();\n}\n\nstruct Point {\n    float i;\n    int a;\n    int r;\n    Point(float i_, int a_, int r_) {i = i_; a = a_; r = r_;}\n};\n\nstruct greater_than_pt {\n    inline bool operator() (const Point& p1, const Point& p2) {\n        return p1.i > p2.i;\n    }\n};\n\nstatic void findRangeBoundaries(cv::Mat &s, int a, int r, int &rlow, int &rhigh) {\n    rlow = r;\n    rhigh = r;\n    if (r > 0) {\n        for (int i = r - 1; i >= 0; i--) {\n            if (s.at<float>(a, i) < 0)\n                rlow = i;\n            else\n                break;\n        }\n    }\n    if (r < s.rows - 1) {\n        for (int i = r + 1; i < s.cols; i++) {\n            if (s.at<float>(a, i) < 0)\n                rhigh = i;\n            else\n                break;\n        }\n    }\n}\n\nstatic bool checkAdjacentMarked(cv::Mat &R, int a, int start, int end) {\n    int below = a - 1;\n    int above = a + 1;\n    if (below < 0)\n        below = R.rows - 1;\n    if (above >= R.rows)\n        above = 0;\n    for (int r = start; r <= end; r++) {\n        if (R.at<float>(below, r) || R.at<float>(above, r))\n            return true;\n    }\n    return false;\n}\n\nstatic void getMaxInRegion(cv::Mat &h, int a, int start, int end, int &max_r) {\n    int max = -1000;\n    for (int r = start; r <= end; r++) {\n        if (h.at<float>(a, r) > max) {\n            max = h.at<float>(a, r);\n            max_r = r;\n        }\n    }\n}\n\n// Runtime: 0.050s\ndouble cen2019features(cv::Mat fft_data, int max_points, int min_range, Eigen::MatrixXd &targets) {\n    auto t1 = std::chrono::high_resolution_clock::now();\n    // Calculate gradient along each azimuth using the Prewitt operator\n    cv::Mat prewitt = cv::Mat::zeros(1, 3, CV_32F);\n    prewitt.at<float>(0, 0) = -1;\n    prewitt.at<float>(0, 2) = 1;\n    cv::Mat g;\n    cv::filter2D(fft_data, g, -1, prewitt, cv::Point(-1, -1), 0, cv::BORDER_REFLECT101);\n    g = cv::abs(g);\n    double maxg = 1, ming = 1;\n    cv::minMaxIdx(g, &ming, &maxg);\n    g /= maxg;\n\n    // Subtract the mean from the radar data and scale it by 1 - gradient magnitude\n    float mean = cv::mean(fft_data)[0];\n    cv::Mat s = fft_data - mean;\n    cv::Mat h = s.mul(1 - g);\n    float mean_h = cv::mean(h)[0];\n\n    // Get indices in descending order of intensity\n    std::vector<Point> vec;\n    for (int i = 0; i < fft_data.rows; ++i) {\n        for (int j = 0; j < fft_data.cols; ++j) {\n            if (h.at<float>(i, j) > mean_h)\n                vec.push_back(Point(h.at<float>(i, j), i, j));\n        }\n    }\n    std::sort(vec.begin(), vec.end(), greater_than_pt());\n\n    // Create a matrix, R, of \"marked\" regions consisting of continuous regions of an azimuth that may contain a target\n    int false_count = fft_data.rows * fft_data.cols;\n    uint j = 0;\n    int l = 0;\n    cv::Mat R = cv::Mat::zeros(fft_data.rows, fft_data.cols, CV_32F);\n    while (l < max_points && j < vec.size() && false_count > 0) {\n        if (!R.at<float>(vec[j].a, vec[j].r)) {\n            int rlow = vec[j].r;\n            int rhigh = vec[j].r;\n            findRangeBoundaries(s, vec[j].a, vec[j].r, rlow, rhigh);\n            bool already_marked = false;\n            for (int i = rlow; i <= rhigh; i++) {\n                if (R.at<float>(vec[j].a, i)) {\n                    already_marked = true;\n                    continue;\n                }\n                R.at<float>(vec[j].a, i) = 1;\n                false_count--;\n            }\n            if (!already_marked)\n                l++;\n        }\n        j++;\n    }\n\n    std::vector<std::vector<cv::Point2f>> t(fft_data.rows);\n\n#pragma omp parallel for\n    for (int i = 0; i < fft_data.rows; i++) {\n        // Find the continuous marked regions in each azimuth\n        int start = 0;\n        int end = 0;\n        bool counting = false;\n        for (int j = min_range; j < fft_data.cols; j++) {\n            if (R.at<float>(i, j)) {\n                if (!counting) {\n                    start = j;\n                    end = j;\n                    counting = true;\n                } else {\n                    end = j;\n                }\n            } else if (counting) {\n                // Check whether adjacent azimuths contain a marked pixel in this range region\n                if (checkAdjacentMarked(R, i, start, end)) {\n                    int max_r = start;\n                    getMaxInRegion(h, i, start, end, max_r);\n                    t[i].push_back(cv::Point(i, max_r));\n                }\n                counting = false;\n            }\n        }\n    }\n\n    int size = 0;\n    for (uint i = 0; i < t.size(); ++i) {\n        size += t[i].size();\n    }\n    targets = Eigen::MatrixXd::Ones(3, size);\n    int k = 0;\n    for (uint i = 0; i < t.size(); ++i) {\n        for (uint j = 0; j < t[i].size(); ++j) {\n            targets(0, k) = t[i][j].x;\n            targets(1, k) = t[i][j].y;\n            k++;\n        }\n    }\n\n    auto t2 = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> e = t2 - t1;\n    return e.count();\n}\n\n// Note: the dimensions of polar_points and cart_targets may not align\n// Runtime: 100 ms\ndouble cen2019descriptors(std::vector<double> azimuths, cv::Size polar_dims, Eigen::MatrixXd polar_points,\n    Eigen::MatrixXd cart_targets, float radar_resolution, float cart_resolution, int cart_pixel_width,\n    cv::Mat &descriptors, int navtech_version) {\n\n    auto t1 = std::chrono::high_resolution_clock::now();\n    // Create binary grid based on polar feature locations\n    cv::Mat polar_binary = cv::Mat::zeros(polar_dims.height, polar_dims.width, CV_32F);\n#pragma omp parallel for\n    for (uint i = 0; i < polar_points.cols(); ++i) {\n        polar_binary.at<float>(polar_points(0, i), polar_points(1, i)) = 1.0;\n    }\n    // Convert it to cartesian\n    cv::Mat cart_binary;\n    radar_polar_to_cartesian(azimuths, polar_binary, radar_resolution, cart_resolution, cart_pixel_width, true,\n        cart_binary, CV_32F, navtech_version);\n\n    // int M = polar_dims.height;\n    int M = 384;\n    float azimuth_step = (2 * M_PI) / float(M);\n    int N = 128;\n    float range_step = (cart_pixel_width / 2.0) / float(N);\n    float max_range_sq = pow(N * range_step, 2);\n\n    cv::Mat d1 = cv::Mat::zeros(cart_targets.cols(), M, CV_32F);\n    cv::Mat d2 = cv::Mat::zeros(cart_targets.cols(), N, CV_32F);\n\n    std::vector<cv::Point2f> bev_points;\n    convert_to_bev(cart_targets, cart_resolution, cart_pixel_width, bev_points);\n\n#pragma omp parallel for collapse(2)\n    for (int i = 0; i < cart_binary.rows; ++i) {\n        for (int j = 0; j < cart_binary.cols; ++j) {\n            if (cart_binary.at<float>(i, j) > 0) {\n                for (uint k = 0; k < bev_points.size(); ++k) {\n                    float range = pow(i - bev_points[k].y, 2) + pow(j - bev_points[k].x, 2);\n                    if (range > max_range_sq)\n                        continue;\n                    range = sqrt(range);\n                    float azimuth = atan2f(bev_points[k].y - i, j - bev_points[k].x);\n                    if (azimuth < 0)\n                        azimuth += 2 * M_PI;\n                    int azimuth_bin = azimuth / azimuth_step;\n                    int range_bin = range / range_step;\n#pragma omp atomic\n                    d1.at<float>(k, azimuth_bin)++;\n#pragma omp atomic\n                    d2.at<float>(k, range_bin)++;\n                }\n            }\n        }\n    }\n\n    // Calculate the FFT for each azimuth, normalize the magnitude\n#pragma omp parallel for\n    for (uint i = 0; i < cart_targets.cols(); ++i) {\n        cv::Mat row = cv::Mat::zeros(1, M, CV_32F);\n        for (int j = 0; j < M; ++j) {\n            row.at<float>(0, j) = d1.at<float>(i, j);\n        }\n        cv::Mat planes[] = {cv::Mat_<float>(row), cv::Mat::zeros(row.size(), CV_32F)};\n        cv::Mat complexI;\n        cv::merge(planes, 2, complexI);         // Add to the expanded another plane with zeros\n        cv::dft(complexI, complexI);            // this way the result may fit in the source matrix\n        cv::split(complexI, planes);\n        cv::magnitude(planes[0], planes[1], planes[0]);\n        cv::Mat magI = planes[0];\n        cv::normalize(magI, magI, 0, 1, cv::NORM_MINMAX);\n        for (int j = 0; j < M; ++j) {\n            d1.at<float>(i, j) = magI.at<float>(0, j);\n        }\n    }\n\n// #pragma omp parallel for\n//     // Reorder with the densest column first\n//     for (uint i = 0; i < cart_targets.cols(); ++i) {\n//         float max = 0;\n//         int max_col = 0;\n//         for (int j = 0; j < M; ++j) {\n//             if (d1.at<float>(i, j) > max) {\n//                 max = d1.at<float>(i, j);\n//                 max_col = j;\n//             }\n//         }\n//         cv::Mat row = cv::Mat::zeros(1, M, CV_32F);\n//         int k = 0;\n//         for (int j = max_col; j < M; ++j) {\n//             row.at<float>(0, k) = d1.at<float>(i, j);\n//             k++;\n//         }\n//         for (int j = 0; j < max_col; ++j) {\n//             row.at<float>(0, k) = d1.at<float>(i, j);\n//             k++;\n//         }\n//         cv::normalize(row, row, 0, 1, cv::NORM_MINMAX);\n//         for (int j = 0; j < M; ++j) {\n//             d1.at<float>(i, j) = row.at<float>(0, j);\n//         }\n//     }\n\n    // Normalize the counts for each range bin\n#pragma omp parallel for\n    for (uint i = 0; i < cart_targets.cols(); ++i) {\n        cv::normalize(d2.row(i), d2.row(i), 0, 1, cv::NORM_MINMAX);\n    }\n    // cv::hconcat(d1, d2, descriptors);\n    descriptors = d2;\n\n    auto t2 = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> e = t2 - t1;\n    return e.count();\n}\n", "meta": {"hexsha": "0026e391f4d82d42c8b8bf76743d57595b75250a", "size": 14179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/features.cpp", "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": "src/features.cpp", "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": "src/features.cpp", "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": 34.8378378378, "max_line_length": 119, "alphanum_fraction": 0.5076521616, "num_tokens": 4302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5295839439405724}}
{"text": "// Copyright 2014 Marco Guazzone (marco.guazzone@gmail.com).\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// Caution: this file contains Quickbook markup as well as code\n// and comments, don't change any of the special comment markups!\n\n\n//[hyperexponential_more_snip1\n#include <boost/math/distributions.hpp>\n#include <iostream>\n#include <string>\n\nstruct ds_info\n{\n   std::string name;\n   double iat_sample_mean;\n   double iat_sample_sd;\n   boost::math::hyperexponential iat_he;\n   double multi_lt_sample_mean;\n   double multi_lt_sample_sd;\n   boost::math::hyperexponential multi_lt_he;\n   double single_lt_sample_mean;\n   double single_lt_sample_sd;\n   boost::math::hyperexponential single_lt_he;\n};\n\n// DS1 dataset\nds_info make_ds1()\n{\n   ds_info ds;\n\n   ds.name = \"DS1\";\n\n   // VM interarrival time distribution\n   const double iat_fit_probs[] = { 0.34561,0.08648,0.56791 };\n   const double iat_fit_rates[] = { 0.0008,0.00005,0.02894 };\n   ds.iat_sample_mean = 2202.1;\n   ds.iat_sample_sd = 2.2e+4;\n   ds.iat_he = boost::math::hyperexponential(iat_fit_probs, iat_fit_rates);\n\n   // Multi-core VM lifetime distribution\n   const double multi_lt_fit_probs[] = { 0.24667,0.37948,0.37385 };\n   const double multi_lt_fit_rates[] = { 0.00004,0.000002,0.00059 };\n   ds.multi_lt_sample_mean = 257173;\n   ds.multi_lt_sample_sd = 4.6e+5;\n   ds.multi_lt_he = boost::math::hyperexponential(multi_lt_fit_probs, multi_lt_fit_rates);\n\n   // Single-core VM lifetime distribution\n   const double single_lt_fit_probs[] = { 0.09325,0.22251,0.68424 };\n   const double single_lt_fit_rates[] = { 0.000003,0.00109,0.00109 };\n   ds.single_lt_sample_mean = 28754.4;\n   ds.single_lt_sample_sd = 1.6e+5;\n   ds.single_lt_he = boost::math::hyperexponential(single_lt_fit_probs, single_lt_fit_rates);\n\n   return ds;\n}\n\n// DS2 dataset\nds_info make_ds2()\n{\n   ds_info ds;\n\n   ds.name = \"DS2\";\n\n   // VM interarrival time distribution\n   const double iat_fit_probs[] = { 0.38881,0.18227,0.42892 };\n   const double iat_fit_rates[] = { 0.000006,0.05228,0.00081 };\n   ds.iat_sample_mean = 41285.7;\n   ds.iat_sample_sd = 1.1e+05;\n   ds.iat_he = boost::math::hyperexponential(iat_fit_probs, iat_fit_rates);\n\n   // Multi-core VM lifetime distribution\n   const double multi_lt_fit_probs[] = { 0.42093,0.43960,0.13947 };\n   const double multi_lt_fit_rates[] = { 0.00186,0.00008,0.0000008 };\n   ds.multi_lt_sample_mean = 144669.0;\n   ds.multi_lt_sample_sd = 7.9e+05;\n   ds.multi_lt_he = boost::math::hyperexponential(multi_lt_fit_probs, multi_lt_fit_rates);\n\n   // Single-core VM lifetime distribution\n   const double single_lt_fit_probs[] = { 0.44885,0.30675,0.2444 };\n   const double single_lt_fit_rates[] = { 0.00143,0.00005,0.0000004 };\n   ds.single_lt_sample_mean = 599815.0;\n   ds.single_lt_sample_sd = 1.7e+06;\n   ds.single_lt_he = boost::math::hyperexponential(single_lt_fit_probs, single_lt_fit_rates);\n\n   return ds;\n}\n\n// DS3 dataset\nds_info make_ds3()\n{\n   ds_info ds;\n\n   ds.name = \"DS3\";\n\n   // VM interarrival time distribution\n   const double iat_fit_probs[] = { 0.39442,0.24644,0.35914 };\n   const double iat_fit_rates[] = { 0.00030,0.00003,0.00257 };\n   ds.iat_sample_mean = 11238.8;\n   ds.iat_sample_sd = 3.0e+04;\n   ds.iat_he = boost::math::hyperexponential(iat_fit_probs, iat_fit_rates);\n\n   // Multi-core VM lifetime distribution\n   const double multi_lt_fit_probs[] = { 0.37621,0.14838,0.47541 };\n   const double multi_lt_fit_rates[] = { 0.00498,0.000005,0.00022 };\n   ds.multi_lt_sample_mean = 30739.2;\n   ds.multi_lt_sample_sd = 1.6e+05;\n   ds.multi_lt_he = boost::math::hyperexponential(multi_lt_fit_probs, multi_lt_fit_rates);\n\n   // Single-core VM lifetime distribution\n   const double single_lt_fit_probs[] = { 0.34131,0.12544,0.53325 };\n   const double single_lt_fit_rates[] = { 0.000297,0.000003,0.00410 };\n   ds.single_lt_sample_mean = 44447.8;\n   ds.single_lt_sample_sd = 2.2e+05;\n   ds.single_lt_he = boost::math::hyperexponential(single_lt_fit_probs, single_lt_fit_rates);\n\n   return ds;\n}\n\nvoid print_fitted(ds_info const& ds)\n{\n   const double secs_in_a_hour = 3600;\n   const double secs_in_a_month = 30 * 24 * secs_in_a_hour;\n\n   std::cout << \"### \" << ds.name << std::endl;\n   std::cout << \"* Fitted Request Interarrival Time\" << std::endl;\n   std::cout << \" - Mean (SD): \" << boost::math::mean(ds.iat_he) << \" (\" << boost::math::standard_deviation(ds.iat_he) << \") seconds.\" << std::endl;\n   std::cout << \" - 99th Percentile: \" << boost::math::quantile(ds.iat_he, 0.99) << \" seconds.\" << std::endl;\n   std::cout << \" - Probability that a VM will arrive within 30 minutes: \" << boost::math::cdf(ds.iat_he, secs_in_a_hour / 2.0) << std::endl;\n   std::cout << \" - Probability that a VM will arrive after 1 hour: \" << boost::math::cdf(boost::math::complement(ds.iat_he, secs_in_a_hour)) << std::endl;\n   std::cout << \"* Fitted Multi-core VM Lifetime\" << std::endl;\n   std::cout << \" - Mean (SD): \" << boost::math::mean(ds.multi_lt_he) << \" (\" << boost::math::standard_deviation(ds.multi_lt_he) << \") seconds.\" << std::endl;\n   std::cout << \" - 99th Percentile: \" << boost::math::quantile(ds.multi_lt_he, 0.99) << \" seconds.\" << std::endl;\n   std::cout << \" - Probability that a VM will last for less than 1 month: \" << boost::math::cdf(ds.multi_lt_he, secs_in_a_month) << std::endl;\n   std::cout << \" - Probability that a VM will last for more than 3 months: \" << boost::math::cdf(boost::math::complement(ds.multi_lt_he, 3.0*secs_in_a_month)) << std::endl;\n   std::cout << \"* Fitted Single-core VM Lifetime\" << std::endl;\n   std::cout << \" - Mean (SD): \" << boost::math::mean(ds.single_lt_he) << \" (\" << boost::math::standard_deviation(ds.single_lt_he) << \") seconds.\" << std::endl;\n   std::cout << \" - 99th Percentile: \" << boost::math::quantile(ds.single_lt_he, 0.99) << \" seconds.\" << std::endl;\n   std::cout << \" - Probability that a VM will last for less than 1 month: \" << boost::math::cdf(ds.single_lt_he, secs_in_a_month) << std::endl;\n   std::cout << \" - Probability that a VM will last for more than 3 months: \" << boost::math::cdf(boost::math::complement(ds.single_lt_he, 3.0*secs_in_a_month)) << std::endl;\n}\n\nint main()\n{\n   print_fitted(make_ds1());\n\n   print_fitted(make_ds2());\n\n   print_fitted(make_ds3());\n}\n//]\n", "meta": {"hexsha": "ba9d5010e1ab1bf7dd31ddb391cdea4666434777", "size": 6374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/hyperexponential_more_snips.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/hyperexponential_more_snips.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/hyperexponential_more_snips.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": 40.858974359, "max_line_length": 174, "alphanum_fraction": 0.6915594603, "num_tokens": 1995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5295839439405723}}
{"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/text.hpp>\n#include <fcppt/cast/to_unsigned_fun.hpp>\n#include <fcppt/io/cout.hpp>\n#include <fcppt/mpl/append.hpp>\n#include <fcppt/mpl/ceil_div.hpp>\n#include <fcppt/mpl/contains_if.hpp>\n#include <fcppt/mpl/implication.hpp>\n#include <fcppt/mpl/index_of.hpp>\n#include <fcppt/mpl/inner.hpp>\n#include <fcppt/mpl/integral_cast.hpp>\n#include <fcppt/mpl/max_value.hpp>\n#include <fcppt/mpl/partial_sums.hpp>\n#include <fcppt/mpl/print.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/integral_c.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/sizeof.hpp>\n#include <boost/mpl/vector/vector10.hpp>\n#include <boost/mpl/vector/vector10_c.hpp>\n#include <ostream>\n#include <type_traits>\n#include <fcppt/config/external_end.hpp>\n\n\nnamespace\n{\nnamespace append\n{\n//! [mpl_append]\ntypedef\nboost::mpl::vector2<\n\tint,\n\tfloat\n>\nvec1;\n\ntypedef\nboost::mpl::vector2<\n\tchar,\n\tdouble\n>\nvec2;\n\ntypedef\nfcppt::mpl::append<\n\tvec1,\n\tvec2\n>::type\nvec3;\n\nstatic_assert(\n\tboost::mpl::equal<\n\t\tvec3,\n\t\tboost::mpl::vector4<\n\t\t\tint,\n\t\t\tfloat,\n\t\t\tchar,\n\t\t\tdouble\n\t\t>\n\t>::value,\n\t\"\"\n);\n//! [mpl_append]\n}\n\nnamespace ceil_div\n{\n//! [mpl_ceil_div]\ntypedef\nfcppt::mpl::ceil_div<\n\tunsigned,\n\t10u,\n\t3u\n>::type\nresult;\n\nstatic_assert(\n\tboost::mpl::equal_to<\n\t\tresult,\n\t\tboost::mpl::integral_c<\n\t\t\tunsigned,\n\t\t\t4u\n\t\t>\n\t>::value,\n\t\"\"\n);\n//! [mpl_ceil_div]\n}\n\nnamespace contains_if\n{\n//! [mpl_contains_if]\ntypedef\nboost::mpl::vector2<\n\tfloat,\n\tunsigned\n>\nvec;\n\ntypedef\nfcppt::mpl::contains_if<\n\tvec,\n\tstd::is_unsigned<\n\t\tboost::mpl::_1\n\t>\n>::type\nresult;\n\nstatic_assert(\n\tboost::mpl::equal_to<\n\t\tresult,\n\t\tboost::mpl::true_\n\t>::value,\n\t\"\"\n);\n//! [mpl_contains_if]\n}\n\nnamespace implication\n{\n//! [mpl_implication]\ntypedef\nfcppt::mpl::implication<\n\tboost::mpl::false_,\n\tboost::mpl::true_\n>::type\nresult;\n\nstatic_assert(\n\tboost::mpl::equal<\n\t\tresult,\n\t\tboost::mpl::true_\n\t>::value,\n\t\"\"\n);\n//! [mpl_implication]\n}\n\nnamespace index_if\n{\n//! [mpl_index_of]\ntypedef\nboost::mpl::vector3<\n\tfloat,\n\tint,\n\tdouble\n>\nvec;\n\ntypedef\nfcppt::mpl::index_of<\n\tvec,\n\tint\n>::type\nresult;\n\nstatic_assert(\n\tboost::mpl::equal_to<\n\t\tresult,\n\t\tboost::mpl::integral_c<\n\t\t\tunsigned,\n\t\t\t1\n\t\t>\n\t>::value,\n\t\"\"\n);\n//! [mpl_index_of]\n}\n\nnamespace inner\n{\n//! [mpl_inner]\nstruct func\n{\n\ttypedef int type;\n};\n\ntypedef\nfcppt::mpl::inner<\n\tfunc\n>::type\nresult;\n\nstatic_assert(\n\tstd::is_same<\n\t\tresult,\n\t\tint\n\t>::value,\n\t\"\"\n);\n//! [mpl_inner]\n}\n\nnamespace integral_cast\n{\n//! [mpl_integral_cast]\ntypedef\nstd::integral_constant<\n\tint,\n\t2\n> integral;\n\ntypedef\nfcppt::mpl::integral_cast<\n\tunsigned,\n\tfcppt::cast::to_unsigned_fun,\n\tintegral\n>::type\nresult;\n\nstatic_assert(\n\tstd::is_same<\n\t\tresult::value_type,\n\t\tunsigned\n\t>::value\n\t&&\n\tresult::value\n\t==\n\t2u,\n\t\"\"\n);\n//! [mpl_integral_cast]\n}\n\nnamespace max_value\n{\n//! [mpl_max_value]\n// Calculate the maximum size of all the types\ntypedef\nboost::mpl::vector3<\n\tshort,\n\tint,\n\tlong\n>\ntypes;\n\ntypedef\nfcppt::mpl::max_value<\n\ttypes,\n\tboost::mpl::sizeof_<\n\t\tboost::mpl::placeholders::_1\n\t>\n>::type\nresult;\n\nstatic_assert(\n\tboost::mpl::equal_to<\n\t\tresult,\n\t\tboost::mpl::sizeof_<\n\t\t\tlong\n\t\t>\n\t>::value,\n\t\"\"\n);\n//! [mpl_max_value]\n}\n\nnamespace partial_sums\n{\n//! [mpl_partial_sums]\ntypedef\nboost::mpl::vector3_c<\n\tint,\n\t3,\n\t4,\n\t5\n>\nvec;\n\ntypedef\nfcppt::mpl::partial_sums<\n\tvec\n>::type\nresult;\n\nstatic_assert(\n\tboost::mpl::equal<\n\t\tresult,\n\t\tboost::mpl::vector4_c<\n\t\t\tint,\n\t\t\t0,\n\t\t\t3,\n\t\t\t7,\n\t\t\t12\n\t\t>\n\t>::value,\n\t\"\"\n);\n//! [mpl_partial_sums]\n}\n\nnamespace print\n{\n//! [mpl_print}\nvoid\nprint_vec()\n{\n\ttypedef boost::mpl::vector3<\n\t\tint,\n\t\tfloat,\n\t\tdouble\n\t> vec;\n\n\t// prints (int, float, double) to cout\n\tfcppt::mpl::print<\n\t\tvec\n\t>(\n\t\tfcppt::io::cout()\n\t)\n\t<<\n\tFCPPT_TEXT('\\n');\n\n}\n//! [mpl_print}\n}\n\n}\n\nint\nmain()\n{\n\tprint::print_vec();\n}\n", "meta": {"hexsha": "a04e5529d16086bf6d858db53ee3e5a91efd0d31", "size": 4057, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpl/various.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": "examples/mpl/various.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": "examples/mpl/various.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": 12.1831831832, "max_line_length": 61, "alphanum_fraction": 0.6687207296, "num_tokens": 1268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.529538504157466}}
{"text": "\n#include <alglib/bimap/bimap.h>\n#include <string>\n#include <iostream>\n\nusing namespace std;\nusing namespace alglib::bimap;\n\nint main() {\n\n  bimap<string, int> bm;\n\n  bm.insert(\"div\", 1);\n  bm.insert(\"dip\", 2);\n\n  cout << bm.get_image(\"div\") << endl;\n  cout << bm.get_image(\"dip\") << endl;\n  cout << bm.get_preimage(1) << endl;\n  cout << bm.get_preimage(2) << endl;\n\n  // Iterator tests\n  cout << \"Domain:  \\t\";\n  for(auto it = bm.domain_begin(); it != bm.domain_end(); ++it)\n    cout << *it << \"\\t\";\n\n  cout << endl;\n\n  cout << \"Codomain:\\t\";\n  for(auto it = bm.codomain_begin(); it != bm.codomain_end(); ++it)\n    cout << *it << \"\\t\";\n\n  cout << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "8cf8fb6ee285b1020dfeef7464df814a9ec08b1d", "size": 669, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/bimap/bimap.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/bimap/bimap.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/bimap/bimap.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.5833333333, "max_line_length": 67, "alphanum_fraction": 0.5784753363, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.7154240079185318, "lm_q1q2_score": 0.5295385004476304}}
{"text": "//STD Libraries\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <cstdlib>\n#include <cstring>\n\n//BOOST\n//can replace boost with STD chrono, utility->function, and random\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/function.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/variate_generator.hpp>\n\n\nusing namespace std;\n\nbool DEBUG = 0;\n\nvoid TimeRoutine(string name,boost::function<int(int,int)>fun, \n            int arg1,int arg2, bool doTime);\nvoid SetAB(int, int & , int & );\nbool Test(int a, int b, int d);\n\nvoid args(string progname) {\n   cout << progname << \" [-l n -r -R n -t -d -a n -b n -h]\" << endl;\n   cout << endl;\n   cout << \"\\t\" << \" -l n \" << \"\\t\" << \" use a preset input\" << endl;\n   cout << \"\\t\\t\" << 0 << \"\\t  Book's Example \" << endl;\n   cout << \"\\t\\t\" << 1 << \"\\t  Two factorable numbers \" << endl;\n   cout << \"\\t\\t\" << 2 << \"\\t  Book's Problem \" << endl;\n   cout << \"\\t\\t\" << 3 << \"\\t  Medium Sized Numbers \" << endl;\n   cout << \"\\t\\t\" << 4 << \"\\t  Large Numbers \" << endl;\n   cout << \"\\t\\t\" << 5 << \"\\t  Very Large Numbers \" << endl;\n   cout << \"\\t\" << \" -r \" << \"\\t\" << \" Generate random numbers\" << endl;\n   cout << \"\\t\" << \" -R n \"<< \"\\t\" << \" Generate random numbers 2 to n\" << endl;\n   cout << \"\\t\" << \" -d \" << \"\\t\" << \" Debug output\" << endl;\n   cout << \"\\t\" << \" -h \" << \"\\t\" << \" This menu\" << endl;\n   cout << \"\\t\" << \" -t \" << \"\\t\" << \" Show Timing\" << endl;\n   cout << \"\\t\" << \" -a n \" << \"\\t\" << \" Set first number to be n\" << endl;\n   cout << \"\\t\" << \" -b n \" << \"\\t\" << \" Set second number to be n\" << endl;\n   return;\n}\n \nint main(int argc, char * argv[]) {\n    int a = 12;\n    int b = 15;\n    bool doTime = false;\n    int arg;\n\n    int i = 1; \n    while (i < argc) {\n        if (strcmp(argv[i],\"-l\")==0) {\n\t   i++;\n\t   if (i < argc) {\n\t       arg = -1;\n               arg = atoi(argv[i]); \n               SetAB(arg, a,b);\n\t       i++;\n\t   } else {\n\t       cout << \"-l requires an integer level, using default \" << endl;\n\t   }\n\t} else if (!strcmp(argv[i],\"-a\")) {\n\t   i++;\n\t   a = atoi(argv[i]);\n\t   if (a < 2) {\n\t      a = 12;\n\t   }\n\t   i++;\n\t} else if (!strcmp(argv[i],\"-b\")) {\n\t   i++;\n\t   b = atoi(argv[i]);\n\t   if (b < 2) {\n\t      b = 15;\n\t   }\n\t   i++;\n\t} else if (!strcmp(argv[i],\"-t\")) {\n\t   doTime = true;\n\t   i++;\n\t} else if (!strcmp(argv[i],\"-r\")) {\n\n\t   boost::mt19937 rng;\n\t   boost::uniform_int<> dist(2,1<<30);\n\t   boost::variate_generator<boost::mt19937&, boost::uniform_int<> >\n\t         bigDie(rng,dist);\n\n\t   rng.seed(static_cast<unsigned int>(std::time(0)));\n\n\t   a = bigDie(); \n\t   b = bigDie();\n\t   i++;\n\t} else if (!strcmp(argv[i],\"-R\")) {\n\t   int upperLimit;\n\n\t   i++;\n\t   upperLimit = atoi(argv[i]);\n\t   i++;\n\n\t   if (upperLimit < 2) {\n\t      upperLimit = 1 << 30;\n\t   }\n\n\t   boost::mt19937 rng;\n\t   boost::uniform_int<> dist(2,upperLimit);\n\t   boost::variate_generator<boost::mt19937&, boost::uniform_int<> >\n\t         bigDie(rng,dist);\n\n\t   rng.seed(static_cast<unsigned int>(std::time(0)));\n\n\t   a = bigDie(); \n\t   b = bigDie();\n\n\t} else if (!strcmp(argv[i],\"-h\")) {\n\t   args(argv[0]);\n\t   i++;\n\t} else if (!strcmp(argv[i],\"-d\")) {\n\t   DEBUG = true;\n\t   i++;\n\t} else {\n\t   cout << \"unknown argument \" << argv[i] << endl;\n\t   args(argv[0]);\n\t   i++;\n\t}\n    }\n\n    cout << endl;\n    cout << \"A = \" << a << \" and has \" << int(log(a)/log(2)) << \" bits\" << endl;\n    cout << \"B = \" << b << \" and has \" << int(log(b)/log(2)) << \" bits\" << endl;\n    cout << endl;\n\n    TimeRoutine(\"Euclid\", Euclid_Recursive, a,b,doTime);\n    TimeRoutine(\"Brute \", Brute, a,b,doTime);\n    TimeRoutine(\"School\", OldSchool, a,b,doTime);\n\n    return 0;\n}\n\n\n\nvoid SetAB(int arg, int & a, int & b) {\n       switch(arg) {\n          case 0:\n             // the book's example\n             a = 60;\n\t     b = 24;\n\t     break;\n\t  case 1:\n             // 2^2 x 3^3 x 5^5 x 7   and 2^2 x 3^2 x 5^4 (to test factoring)\n             a = 45000;\n\t     b = 787500;\n\t     break;\n\t  case 2:\n             // an exercise in the book\n             a=31415;\n\t     b= 14142;\n\t     break;\n\t  case 3:\n             // not to big prime number, look out old school!\n             a = 80147*2*3*3;\n             b = 21011*2*3*3;\n\t     break;\n\t  case 4:\n             // two bigger prime numbers\n             a=  4095036*2*3*5;\n             b = 4095043*2*3*5;\n\t     break;\n\t  default:\n\t     a = 40950391 * 2 * 3;\n\t     b = 40950401 * 2 * 3;\n       }\n       return;\n}\n\n\n\nvoid TimeRoutine(string name, boost::function < int (int, int)> fun, \n                   int arg1,int arg2, bool doTime){\n\n    int gcd;\n    boost::posix_time::ptime startTime, endTime;\n    boost::posix_time::time_duration totalTime;\n\n    startTime = boost::posix_time::microsec_clock::local_time();\n    gcd = fun(arg1, arg2);\n    endTime = boost::posix_time::microsec_clock::local_time();\n    cout <<\"\\t\" << name << \": \" << setw(15) << gcd;\n    if (doTime) {\n       totalTime = endTime-startTime;\n       cout << \"\\tTime: \" << totalTime;\n    }\n    cout << endl;\n    if (!Test(arg1, arg2, gcd)) {\n        cout << endl;\n        cout << \"ERROR ERROR ERROR ERROR ERROR ERROR \" << endl;\n        cout << endl << endl << endl;\n    }\n\n    return;\n}\n", "meta": {"hexsha": "31ab356affdc32de17409d8120ba139af3661fe0", "size": 5220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/code/scratch/old_repos/edinboro/CSCI-385/GCD-Test-Suite/src/code/bennett.cpp", "max_stars_repo_name": "luxe/CodeLang-compiler", "max_stars_repo_head_hexsha": "78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T07:43:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T13:12:32.000Z", "max_issues_repo_path": "source/code/scratch/old_repos/edinboro/CSCI-385/GCD-Test-Suite/src/code/bennett.cpp", "max_issues_repo_name": "luxe/CodeLang-compiler", "max_issues_repo_head_hexsha": "78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 371.0, "max_issues_repo_issues_event_min_datetime": "2019-05-16T15:23:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-04T15:45:27.000Z", "max_forks_repo_path": "source/code/scratch/old_repos/edinboro/CSCI-385/GCD-Test-Suite/src/code/bennett.cpp", "max_forks_repo_name": "UniLang/compiler", "max_forks_repo_head_hexsha": "c338ee92994600af801033a37dfb2f1a0c9ca897", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-08-22T17:37:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T07:15:32.000Z", "avg_line_length": 25.9701492537, "max_line_length": 80, "alphanum_fraction": 0.4982758621, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5295384955660039}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2012, 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//#define VIENNACL_DEBUG_ALL\n//#define VIENNACL_DEBUG_BUILD\n//#define VIENNACL_DEBUG_BUILD\n//\n// *** System\n//\n#include <iostream>\n\n//\n// *** Boost\n//\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/foreach.hpp>\n\n//\n// *** ViennaCL\n//\n//#define VIENNACL_DEBUG_BUILD\n#define VIENNACL_WITH_UBLAS\n//#define VIENNACL_DEBUG_ALL\n\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/linalg/inner_prod.hpp\"\n#include \"viennacl/linalg/reduce.hpp\"\n#include \"viennacl/linalg/vector_operations.hpp\"\n//#include \"viennacl/linalg/norm_1.hpp\"\n//#include \"viennacl/linalg/norm_2.hpp\"\n//#include \"viennacl/linalg/norm_inf.hpp\"\n#include \"viennacl/scheduler/io.hpp\"\n\n\n#define CHECK_RESULT(cpu,gpu, op) \\\n    if ( float delta = fabs ( diff ( cpu, gpu) ) > epsilon ) {\\\n        std::cout << \"# Error at operation: \" #op << std::endl;\\\n        std::cout << \"  diff: \" << delta << std::endl;\\\n        retval = EXIT_FAILURE;\\\n    }\\\n\n\nusing namespace boost::numeric;\nusing namespace viennacl;\n\ntemplate<typename ScalarType, typename VCLMatrixType>\nScalarType diff(ublas::matrix<ScalarType> & mat1, VCLMatrixType & mat2)\n{\n    ublas::matrix<ScalarType> mat2_cpu(mat2.size1(), mat2.size2());\n    viennacl::backend::finish();\n    viennacl::copy(mat2, mat2_cpu);\n    double ret = 0;\n    double act = 0;\n    for (unsigned int i = 0; i < mat2_cpu.size1(); ++i)\n    {\n      for (unsigned int j = 0; j < mat2_cpu.size2(); ++j)\n      {\n         act = fabs(mat2_cpu(i,j) - mat1(i,j)) / std::max( fabs(mat2_cpu(i, j)), fabs(mat1(i,j)) );\n         if (act > ret)\n           ret = act;\n      }\n    }\n    //std::cout << ret << std::endl;\n    return ret;\n}\n\ntemplate<typename ScalarType, unsigned int Alignment>\nScalarType diff ( ublas::vector<ScalarType> & v1, viennacl::vector<ScalarType,Alignment> & v2 ) {\n    ublas::vector<ScalarType> v2_cpu ( v2.size() );\n    viennacl::copy( v2.begin(), v2.end(), v2_cpu.begin() );\n    for ( unsigned int i=0; i<v1.size(); ++i ) {\n        if ( std::max ( fabs ( v2_cpu[i] ), fabs ( v1[i] ) ) > 0 )\n            v2_cpu[i] = fabs ( v2_cpu[i] - v1[i] ) / std::max ( fabs ( v2_cpu[i] ), fabs ( v1[i] ) );\n        else\n            v2_cpu[i] = 0.0;\n    }\n    return norm_inf ( v2_cpu );\n}\n\ntemplate<typename ScalarType>\nScalarType diff(ScalarType s, viennacl::scalar<ScalarType> & gs){\n  ScalarType other = gs;\n  return (s - other) / std::max(s, other);\n}\n\n\ntemplate< typename NumericT, typename Epsilon >\nint test_vector ( Epsilon const& epsilon) {\n    using namespace viennacl::device_specific;\n    int retval = EXIT_SUCCESS;\n\n    unsigned int size = 1024*32;\n    ublas::vector<NumericT> cw(size);\n    ublas::vector<NumericT> cx(size);\n    ublas::vector<NumericT> cy(size);\n    ublas::vector<NumericT> cz(size);\n\n//    NumericT s;\n\n\n\n    for (unsigned int i=0; i<cw.size(); ++i){\n      cw[i]=std::rand()/(NumericT)RAND_MAX;\n    }\n\n    std::cout << \"Running tests for vector of size \" << cw.size() << std::endl;\n    viennacl::vector<NumericT> w (size);\n    viennacl::vector<NumericT> x (size);\n    viennacl::vector<NumericT> y (size);\n    viennacl::vector<NumericT> z (size);\n    NumericT s = 0;\n    viennacl::scalar<NumericT> gs(0);\n\n    cx = 2.0f*cw;\n    cy = 3.0f*cw;\n    cz = 4.0f*cw;\n    viennacl::copy (cw, w);\n    viennacl::copy (cx, x);\n    viennacl::copy (cy, y);\n    viennacl::copy (cz, z);\n\n    NumericT alpha = 3.14;\n    NumericT beta = 1;\n\n    // --------------------------------------------------------------------------\n\n//    {\n//        std::cout << \"w = scalar_vector(alpha) ...\" << std::endl;\n//        for (unsigned int i = 0; i < size; ++i)\n//          cw[i] = alpha;\n//        viennacl::scheduler::statement statement(w, viennacl::op_assign(), viennacl::scalar_vector<NumericT>(size,alpha));\n//        device_specific::execute(database::get<NumericT>(database::axpy), statement);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = scalar_vector(alpha));\n//    }\n\n//    {\n//        std::cout << \"w = x ...\" << std::endl;\n//        cw = cx;\n//        viennacl::scheduler::statement statement(w, viennacl::op_assign(), x);\n//        device_specific::execute(database::get<NumericT>(database::axpy), statement);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = x);\n//    }\n\n\n//    {\n//        std::cout << \"w = -x ...\" << std::endl;\n//        viennacl::scalar<NumericT> s0(1);\n//        cw =  -cx;\n//        viennacl::scheduler::statement statement(w, viennacl::op_assign(), -s0*x);\n//        device_specific::execute(database::get<NumericT>(database::axpy), statement);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = -x);\n//    }\n\n//    {\n//        std::cout << \"w = alpha*x + beta*y ...\" << std::endl;\n//        cw = alpha*cx + beta*cy;\n//        viennacl::scheduler::statement statement(w, viennacl::op_assign(), alpha*x + beta*y);\n//        device_specific::execute(database::get<NumericT>(database::axpy), statement);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = alpha*x + beta*y);\n//    }\n\n//    {\n//        std::cout << \"x = alpha*w + beta*y ...\" << std::endl;\n//        cx = alpha*cw + beta*cy;\n//        viennacl::scheduler::statement statement(x, viennacl::op_assign(), alpha*w + beta*y);\n//        device_specific::execute(database::get<NumericT>(database::axpy), statement);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = alpha*x + beta*y);\n//    }\n\n//    {\n//        std::cout << \"[Independent] x = alpha*w + beta*y, y = alpha*x + beta*w ...\" << std::endl;\n//        for (std::size_t i = 0; i < size; ++i)\n//        {\n//          NumericT tmpcx = cx[i];\n//          NumericT tmpcy = cy[i];\n\n//          cx[i] = alpha*cw[i] + beta*tmpcy;\n//          cy[i] = alpha*tmpcx + beta*cw[i];\n//        }\n//        viennacl::scheduler::statement s1(x, viennacl::op_assign(), alpha*w + beta*y);\n//        viennacl::scheduler::statement s2(y, viennacl::op_assign(), alpha*x + beta*w);\n//        device_specific::execute(database::get<NumericT>(database::axpy), statements_container(s1, s2, statements_container::INDEPENDENT));\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cx, x, (x = alpha*w + beta*y, y = alpha*x + beta*w));\n//        CHECK_RESULT(cy, y, (x = alpha*w + beta*y, y = alpha*x + beta*w));\n//    }\n\n//    {\n//        std::cout << \"[Sequential] x = alpha*w + beta*y, y = alpha*x + beta*w ...\" << std::endl;\n//        cx = alpha*cw + beta*cy;\n//        cy = alpha*cx + beta*cw;\n//        viennacl::scheduler::statement s1(x, viennacl::op_assign(), alpha*w + beta*y);\n//        viennacl::scheduler::statement s2(y, viennacl::op_assign(), alpha*x + beta*w);\n//        device_specific::execute(database::get<NumericT>(database::axpy), statements_container(s1, s2, statements_container::SEQUENTIAL));\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cx, x, (x = alpha*w + beta*y, y = alpha*x + beta*w));\n//        CHECK_RESULT(cy, y, (x = alpha*w + beta*y, y = alpha*x + beta*w));\n//    }\n\n//    {\n//        std::cout << \"w = exp(y) ...\" << std::endl;\n//        for (std::size_t i = 0; i < size; ++i)\n//          cw[i] = std::exp(y[i]);\n//        viennacl::scheduler::statement statement(w, viennacl::op_assign(), viennacl::linalg::element_exp(y));\n//        device_specific::execute(database::get<NumericT>(database::axpy), statement);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = alpha*x + beta*y);\n//    }\n\n//    {\n//        std::cout << \"w = element_prod(x,y) ...\" << std::endl;\n//        for (std::size_t i = 0; i < size; ++i)\n//          cw[i] = x[i]*y[i];\n//        viennacl::scheduler::statement statement(w, viennacl::op_assign(), viennacl::linalg::element_prod(x,y));\n//        device_specific::execute(database::get<NumericT>(database::axpy), statement);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = element_prod(x,y));\n//    }\n\n//    {\n//        std::cout << \"w = x == x\" << std::endl;\n//        for (unsigned int i=0; i < size; ++i){\n//            cw(i) = (cx(i) == cx(i));\n//        }\n//        viennacl::scheduler::statement statement(w, viennacl::op_assign(), viennacl::linalg::element_eq(x,x));\n//        generator::execute(statement, statement.array()[0]);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = (x == x))\n//    }\n\n//    {\n//        std::cout << \"w = x != x\" << std::endl;\n//        for (unsigned int i=0; i < size; ++i){\n//            cw(i) = cx(i) != cx(i);\n//        }\n//        viennacl::scheduler::statement statement(w, viennacl::op_assign(), viennacl::linalg::element_neq(x,x));\n//        generator::execute(statement, statement.array()[0]);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = x != x)\n//    }\n\n//    {\n//        std::cout << \"w = x > y\" << std::endl;\n//        for (unsigned int i=0; i < size; ++i){\n//            cw(i) = cx(i) > cy(i);\n//        }\n//        viennacl::scheduler::statement statement(w, viennacl::op_assign(), viennacl::linalg::element_greater(x,y));\n//        generator::execute(statement, statement.array()[0]);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = x > y)\n//    }\n\n//    {\n//        std::cout << \"w = x >= y\" << std::endl;\n//        for (unsigned int i=0; i < size; ++i){\n//            cw(i) = cx(i) >= cy(i);\n//        }\n//        viennacl::scheduler::statement statement(w, viennacl::op_assign(), viennacl::linalg::element_geq(x,y));\n//        generator::execute(statement, statement.array()[0]);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = x > y)\n//    }\n\n//    {\n//        std::cout << \"w = x < y\" << std::endl;\n//        for (unsigned int i=0; i < size; ++i){\n//            cw(i) = cx(i) < cy(i);\n//        }\n//        viennacl::scheduler::statement statement(w, viennacl::op_assign(), viennacl::linalg::element_less(x,y));\n//        generator::execute(statement, statement.array()[0]);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = x > y)\n//    }\n\n//    {\n//        std::cout << \"w = x <= y\" << std::endl;\n//        for (unsigned int i=0; i < size; ++i){\n//            cw(i) = cx(i) <= cy(i);\n//        }\n//        viennacl::scheduler::statement statement(w, viennacl::op_assign(), viennacl::linalg::element_leq(x,y));\n//        generator::execute(statement, statement.array()[0]);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = x > y)\n//    }\n\n\n//    {\n//        std::cout << \"w = x.^y\" << std::endl;\n//        for (unsigned int i=0; i < size; ++i){\n//            cw(i) = std::pow(cx(i),cy(i));\n//        }\n//        viennacl::scheduler::statement statement(w, viennacl::op_assign(), viennacl::linalg::element_pow(x,y));\n//        generator::execute(statement, statement.array()[0]);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cw, w, w = x.^y)\n//    }\n\n//    {\n//        std::cout << \"s = inner_prod(x,y)...\" << std::endl;\n//        s = 0;\n//        for (unsigned int i=0; i<size; ++i)  s+=cx[i]*cy[i];\n//        viennacl::scheduler::statement statement(gs, viennacl::op_assign(), viennacl::linalg::inner_prod(x,y));\n//        device_specific::execute(database::get<NumericT>(database::reduction), statement);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(s, gs, s = inner_prod(x,y));\n//    }\n\n//    {\n//        std::cout << \"s = reduce<add>(x)...\" << std::endl;\n//        s = 0;\n//        for (unsigned int i=0; i<size; ++i)  s+=cx[i];\n//        viennacl::scheduler::statement statement(gs, viennacl::op_assign(), viennacl::linalg::reduce<viennacl::op_add>(x));\n//        device_specific::execute(profiles::get(REDUCTION_TYPE, NUMERIC_TYPE), statement);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(s, gs, s = reduce<add>(x));\n//    }\n\n//    {\n//        std::cout << \"s = reduce<fmax>(x)...\" << std::endl;\n//        s = cx[0];\n//        for (unsigned int i=1; i<size; ++i)  s=std::max(s,cx[i]);\n//        viennacl::scheduler::statement statement(gs, viennacl::op_assign(), viennacl::linalg::reduce<iennacl::op_fmax>(x));\n//        device_specific::execute(database::get<NumericT>(database::reduction), statement);\n//        viennacl::backend::finish();\n//        CHECK_RESULT(s, gs, s = reduce<mult>(x));\n//    }\n\n    {\n        std::cout << \"s = reduce<argmax>(x)...\" << std::endl;\n        NumericT s = 0;\n        NumericT val = cx[0];\n        for (unsigned int i=1; i<size; ++i)\n        {\n            if (cx[i] > val)\n            {\n                s = i;\n                val = cx[i];\n            }\n        }\n        viennacl::scheduler::statement statement(gs, viennacl::op_assign(), viennacl::linalg::reduce<viennacl::op_argmax>(x));\n        device_specific::execute(database::get<NumericT>(database::reduction), statement);\n        viennacl::backend::finish();\n        CHECK_RESULT(s, gs, s = reduce<argmax>(x));\n    }\n\n    return retval;\n}\n\n\n\ntemplate< typename NumericT, class Layout, typename Epsilon >\nint test_matrix ( Epsilon const& epsilon) {\n    int retval = EXIT_SUCCESS;\n\n    unsigned int size1 = 1024;\n    unsigned int size2 = 1024;\n\n    unsigned int pattern_size1 = 256;\n    unsigned int pattern_size2 = 128;\n\n//    unsigned int n_rep1 = size1/pattern_size1;\n//    unsigned int n_rep2 = size2/pattern_size2;\n\n    ublas::matrix<NumericT> cA(size1,size2);\n    ublas::matrix<NumericT> cB(size1,size2);\n    ublas::matrix<NumericT> cC(size1,size2);\n\n    ublas::matrix<NumericT> cPattern(pattern_size1,pattern_size2);\n\n    ublas::vector<NumericT> cx(size1);\n    ublas::vector<NumericT> cy(size2);\n\n\n    for (unsigned int i=0; i<size1; ++i)\n        for (unsigned int j=0; j<size2; ++j)\n            cA(i,j)=(NumericT)std::rand()/RAND_MAX;\n\n    for (unsigned int i = 0; i < pattern_size1; ++i)\n        for (unsigned int j = 0; j < pattern_size2; ++j)\n            cPattern(i,j) = (NumericT)std::rand()/RAND_MAX;\n\n\n    for (unsigned int i=0; i<size2; ++i){\n        cx(i) = (NumericT)std::rand()/RAND_MAX;\n        cy(i) = (NumericT)std::rand()/RAND_MAX;\n    }\n\n//    std::cout << \"Running tests for matrix of size \" << cA.size1() << \",\" << cA.size2() << std::endl;\n\n    viennacl::matrix<NumericT,Layout> A (size1, size2);\n    viennacl::matrix<NumericT,Layout> B (size1, size2);\n    viennacl::matrix<NumericT,Layout> C (size1, size2);\n\n    viennacl::matrix<NumericT, Layout> pattern(pattern_size1, pattern_size2);\n\n    viennacl::vector<NumericT> x(size1);\n    viennacl::vector<NumericT> y(size2);\n\n\n    cB = cA;\n    cC = cA;\n    viennacl::copy(cA,A);\n    viennacl::copy(cB,B);\n    viennacl::copy(cC,C);\n\n    viennacl::copy(cx,x);\n    viennacl::copy(cy,y);\n    viennacl::copy(cPattern,pattern);\n\n//    {\n//      std::cout << \"C = A + B ...\" << std::endl;\n//      cC     = ( cA + cB );\n//      viennacl::scheduler::statement statement(C, viennacl::op_assign(), A + B);\n//      device_specific::execute<device_specific::matrix_axpy_template>(device_specific::database::get<NumericT>(device_specific::database::matrix_axpy), statement);\n//      viennacl::backend::finish();\n//      CHECK_RESULT(cC, C, C=A+B)\n//    }\n\n    {\n      std::cout << \"C = diag(x) ...\" << std::endl;\n      for (unsigned int i = 0; i < size1; ++i)\n        for (unsigned int j = 0; j < size2; ++j)\n          cC(i,j) = (i==j)?cx[i]:0;\n      viennacl::scheduler::statement statement(C, viennacl::op_assign(), viennacl::diag(x));\n      device_specific::execute<device_specific::matrix_axpy_template>(device_specific::database::get<NumericT>(device_specific::database::matrix_axpy), statement);\n      viennacl::backend::finish();\n      CHECK_RESULT(cC, C, C=diag(x))\n    }\n\n    {\n      std::cout << \"x = diag(C) ...\" << std::endl;\n      for (unsigned int i = 0; i < std::min(size1, size2); ++i)\n        cx[i] = cC(i,i);\n      viennacl::scheduler::statement statement(x, viennacl::op_assign(), viennacl::diag(C));\n      device_specific::execute<device_specific::vector_axpy_template>(device_specific::database::get<NumericT>(device_specific::database::vector_axpy), statement);\n      viennacl::backend::finish();\n      CHECK_RESULT(cx, x, x=diag(C))\n    }\n\n    {\n      std::cout << \"y = row(C, 7) ...\" << std::endl;\n      for (unsigned int j = 0; j < size2; ++j)\n        cy[j] = cC(7,j);\n      viennacl::scheduler::statement statement(y, viennacl::op_assign(), viennacl::row(C, 7));\n      device_specific::execute<device_specific::vector_axpy_template>(device_specific::database::get<NumericT>(device_specific::database::vector_axpy), statement);\n      viennacl::backend::finish();\n      CHECK_RESULT(cy, y, y=row(C, 7))\n    }\n\n//    {\n//      std::cout << \"x = diag(C) ...\" << std::endl;\n//      for (unsigned int i = 0; i < std::min(size1, size2); ++i)\n//        cx[i] = cC(i,i);\n//      viennacl::scheduler::statement statement(x, viennacl::op_assign(), viennacl::diag(C));\n//      device_specific::execute<device_specific::vector_axpy_template>(device_specific::database::get<NumericT>(device_specific::database::vector_axpy), statement);\n//      viennacl::backend::finish();\n//      CHECK_RESULT(cx, x, x=diag(C))\n//    }\n\n\n//    {\n//        std::cout << \"C = diag(x) ...\" << std::endl;\n//        for (unsigned int i = 0; i < size1; ++i){\n//          for (unsigned int j = 0; j < size2; ++j){\n//            cC(i,j) = (i==j)?cx[i]:0;\n//          }\n//        }\n//        generator::custom_operation op;\n//        op.add(mat(C) = generator::diag(vec(x)));\n//        op.execute();\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cC, C, C = diag(x))\n//    }\n\n//    {\n//        std::cout << \"x = diag(C) ...\" << std::endl;\n//        for (unsigned int i = 0; i < size1; ++i){\n//            cx(i) = cA(i,i);\n//        }\n//        generator::custom_operation op;\n//        op.add(vec(x) = generator::diag(mat(A)));\n//        op.execute();\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cx,x, x = diag(A));\n//    }\n\n//    {\n//        std::cout << \"C = repmat(P, M, N) ...\" << std::endl;\n//        for (unsigned int i = 0; i < size1; ++i)\n//            for (unsigned int j = 0; j < size2; ++j)\n//                cC(i,j) = cPattern(i%pattern_size1, j%pattern_size2);\n//        generator::custom_operation op;\n//        op.add(mat(C) = generator::repmat(mat(pattern),n_rep1,n_rep2));\n//        op.execute();\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cC, C, C = repmat(P, M, N))\n//    }\n\n//    {\n//        std::cout << \"C = repmat(x, 1, N) ...\" << std::endl;\n//        for (unsigned int i = 0; i < size1; ++i)\n//            for (unsigned int j = 0; j < size2; ++j)\n//                cC(i,j) = cx(i);\n//        generator::custom_operation op;\n//        op.add(mat(C) = generator::repmat(vec(x),1, C.size2()));\n//        op.execute();\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cC, C, C = repmat(x, 1, N))\n//    }\n\n//    {\n//        std::cout << \"C = trans(repmat(x, 1, N)) ...\" << std::endl;\n//        for (unsigned int i = 0; i < size1; ++i)\n//            for (unsigned int j = 0; j < size2; ++j)\n//                cC(i,j) = cx(j);\n//        generator::custom_operation op;\n//        op.add(mat(C) = generator::trans(generator::repmat(vec(x),1,C.size2())));\n//        op.execute();\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cC, C, C = repmat(x, 1, N))\n//    }\n\n\n//    {\n//        std::cout << \"C = -A ...\" << std::endl;\n//        for (unsigned int i = 0; i < size1; ++i)\n//            for (unsigned int j = 0; j < size2; ++j)\n//                cC(i,j) = -cA(i,j);\n//        generator::custom_operation op;\n//        op.add(mat(C) = -mat(A));\n//        op.execute();\n//        viennacl::backend::finish();\n\n//        CHECK_RESULT(cC, C, C = -A)\n//    }\n\n//    {\n//        std::cout << \"C = 1/(1+EXP(-A)) ...\" << std::endl;\n//        for (unsigned int i = 0; i < size1; ++i)\n//            for (unsigned int j = 0; j < size2; ++j)\n//                cC(i,j) = 1.0f/(1.0f+std::exp(-cA(i,j)));\n//        generator::custom_operation op;\n//        op.add(mat(C) = 1.0f/(1.0f+generator::exp(-mat(A))));\n//        op.execute();\n//        viennacl::backend::finish();\n//        CHECK_RESULT(cC, C, C = 1/(1+EXP(-A)))\n//    }\n\n\n    return retval;\n}\n\n\nint main(int argc, char* argv[]){\n    std::vector<std::string> args(argv,argv+argc);\n    unsigned int requested_device;\n    if (argc!=2){\n        requested_device=0;\n    }\n    else{\n        requested_device = atoi(args[1].c_str());\n    }\n    int retval = EXIT_SUCCESS;\n\n    typedef std::vector< viennacl::ocl::platform > platforms_type;\n    typedef std::vector<viennacl::ocl::device> devices_type;\n\n    platforms_type platforms = viennacl::ocl::get_platforms();\n    size_t num_platforms = platforms.size();\n\n    unsigned int current_device = 0;\n\n    for (unsigned int k=0; k < num_platforms; ++k)\n    {\n        viennacl::ocl::platform pf(k);\n        viennacl::ocl::set_context_device_type(k,CL_DEVICE_TYPE_ALL);\n        viennacl::ocl::set_context_platform_index(k,k);\n        viennacl::ocl::switch_context(k);\n        devices_type dev = viennacl::ocl::current_context().devices();\n        for (devices_type::iterator it = dev.begin(); it != dev.end(); ++it){\n\n            if (current_device++ == requested_device ){\n                viennacl::ocl::switch_device(*it);\n                std::cout << std::endl;\n                std::cout << \"----------------------------------------------\" << std::endl;\n                std::cout << \"               Device Info\" << std::endl;\n                std::cout << \"----------------------------------------------\" << std::endl;\n                std::cout << viennacl::ocl::current_device().info() << std::endl;\n\n//                std::cout << std::endl;\n//                std::cout << \"----------------------------------------------\" << std::endl;\n//                std::cout << \"----------------------------------------------\" << std::endl;\n//                std::cout << \"## Test :: Vector\" << std::endl;\n//                std::cout << \"----------------------------------------------\" << std::endl;\n\n//                {\n//                    double epsilon = 1.0E-4;\n\n//                    std::cout << \"# Testing setup:\" << std::endl;\n//                    std::cout << \"  numeric: float\" << std::endl;\n//                    retval = test_vector<float> (epsilon);\n\n\n//                    std::cout << std::endl;\n\n//                    std::cout << \"# Testing setup:\" << std::endl;\n//                    std::cout << \"  numeric: double\" << std::endl;\n//                    retval = test_vector<double> (epsilon);\n\n//                    if ( retval == EXIT_SUCCESS )\n//                        std::cout << \"# Test passed\" << std::endl;\n//                    else\n//                        return retval;\n//              }\n\n\n              std::cout << std::endl;\n              std::cout << \"----------------------------------------------\" << std::endl;\n              std::cout << \"----------------------------------------------\" << std::endl;\n              std::cout << \"## Test :: Matrix\" << std::endl;\n              std::cout << \"----------------------------------------------\" << std::endl;\n\n              {\n                  double epsilon = 1.0E-4;\n                  std::cout << \"# Testing setup:\" << std::endl;\n\n                  std::cout << \"  numeric: float\" << std::endl;\n                  std::cout << \"  --------------\" << std::endl;\n                  std::cout << \"  Row-Major\"      << std::endl;\n                  std::cout << \"  --------------\" << std::endl;\n                  retval = test_matrix<float, viennacl::row_major> (epsilon);\n\n                  std::cout << \"  --------------\" << std::endl;\n                  std::cout << \"  Column-Major\"      << std::endl;\n                  std::cout << \"  --------------\" << std::endl;\n                  retval &= test_matrix<float, viennacl::column_major> (epsilon);\n\n                  std::cout << \"  numeric: double\" << std::endl;\n                  std::cout << \"  --------------\" << std::endl;\n                  std::cout << \"  Row-Major\"      << std::endl;\n                  std::cout << \"  --------------\" << std::endl;\n                  retval = test_matrix<double, viennacl::row_major> (epsilon);\n\n                  std::cout << \"  --------------\" << std::endl;\n                  std::cout << \"  Column-Major\"      << std::endl;\n                  std::cout << \"  --------------\" << std::endl;\n                  retval &= test_matrix<double, viennacl::column_major> (epsilon);\n\n                  if ( retval == EXIT_SUCCESS )\n                      std::cout << \"# Test passed\" << std::endl;\n                  else\n                      return retval;\n              }\n\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "58a682a7f23b09525b9391dab78e89901c2f7090", "size": 25456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/generator_blas1.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": "tests/src/generator_blas1.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": "tests/src/generator_blas1.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": 37.4352941176, "max_line_length": 165, "alphanum_fraction": 0.5147313011, "num_tokens": 7164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5295384914655714}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Header file for the SO3 Lie Group types.\n/// \\details These types provide a standardized definition for various SO3 quantities.\n///\n/// \\author Kirk MacTavish\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef LGM_SO3_TYPES_HPP\n#define LGM_SO3_TYPES_HPP\n\n#include <Eigen/Core>\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// Lie Group Math - Special Orthogonal Group\n/////////////////////////////////////////////////////////////////////////////////////////////\nnamespace lgmath {\nnamespace so3 {\n\n/// An axis angle rotation.\n/// AxisAngle is a 3x1 axis-angle vector, the magnitude of the angle of rotation\n/// can be recovered by finding the norm of the vector, and the axis of rotation is the unit-\n/// length vector that arises from normalization. Note that the angle around the axis,\n/// aaxis_ba, is a right-hand-rule (counter-clockwise positive) angle from 'a' to 'b'.\ntypedef Eigen::Vector3d AxisAngle;\n\n/// A rotation matrix.\n/// The convention is that C_ba rotates points from frame a to frame b.\ntypedef Eigen::Matrix3d RotationMatrix;\n\n} // so3\n} // lgmath\n\n#endif // LGM_SO3_TYPES_HPP\n", "meta": {"hexsha": "93cf6831612af5ec3c3bf9877ab9fbc9295ad21f", "size": 1306, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lgmath/so3/Types.hpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "include/lgmath/so3/Types.hpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "include/lgmath/so3/Types.hpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 38.4117647059, "max_line_length": 94, "alphanum_fraction": 0.5298621746, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5294650987099372}}
{"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_RATIO_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_RATIO_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Ratio Ratio (function template)\n\n  Generates a constant defined by compile-time rational number representation.\n\n  @headerref{<boost/simd/constant/ratio.hpp>}\n\n  @par Description\n\n  @code\n  template<typename T,std::uintmax_t Num, std::uintmax_t Denum> T Ratio();\n  @endcode\n\n  Generates a value of type @c T that evaluates to `Num/Denum`.\n\n  @par Template Parameters\n\n  | Name           | Description              |\n  |---------------:|:-------------------------|\n  | **T**          | the constant type        |\n  | **Num**        | the constant numerator   |\n  | **Denum**      | the constant denumerator |\n\n  @par Return Value\n  A value of type @c T that evaluates to `T(Num)/T(Denum)`.\n\n  @par Requirements\n  - **T** models Value\n**/\n\n#include <boost/simd/constant/scalar/ratio.hpp>\n#include <boost/simd/constant/simd/ratio.hpp>\n\n#endif\n", "meta": {"hexsha": "de39cd129cca0e5a48096d163ebcc66bbe5e2b13", "size": 1378, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/ratio.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/ratio.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/ratio.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": 28.1224489796, "max_line_length": 100, "alphanum_fraction": 0.5624092888, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5294650877071924}}
{"text": "#include \"fastmath.hpp\"\r\n\r\n#include <boost/math/special_functions/log1p.hpp>\r\n\r\n#include \"jacoblog.hpp\"\r\n#include \"icsilogw.hpp\"\r\n#include \"PowFast.hpp\"\r\n\r\n\r\n/** Switch to disable fast math routines for debugging. */\r\nstatic const bool DisableFastMath = true;\r\n\r\n\r\n/** Allocate precomputed tables. */\r\nstatic ICSILog flog(14);\r\nstatic PowFast fpow(14);\r\nstatic JacobianLogTable fjacoblog(1 << 11);\r\n\r\n\r\n/** Fast, approxiate jacobian logarithm: log(1+exp(x)) */\r\ndouble fast_jacoblog(double x) {\r\n\r\n    // Avoid numerical issues arising from extreme values \r\n    if (x >= 60.0) return x;\r\n    else if (x < -60.0) return 0.0;\r\n    else {\r\n        if (DisableFastMath) \r\n            return boost::math::log1p(std::exp(x));\r\n        else\r\n            return fjacoblog.jacobianLog(x);\r\n    }\r\n}\r\n\r\n\r\n/** Fast, approximate natural logarithm. */\r\ndouble fast_log(double x) {\r\n\r\n    if (DisableFastMath) return std::log(x);\r\n\r\n    return flog.log(static_cast<float>(x));\r\n}\r\n\r\n\r\n/** Fast, approximate exponentiation. */\r\ndouble fast_exp(double x) {\r\n\r\n    if (DisableFastMath) return std::exp(x);\r\n\r\n    return fpow.e(static_cast<float>(x));\r\n}\r\n", "meta": {"hexsha": "5f4bb4fb4816e75352ee84aed0c1e9399da59417", "size": 1138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fastmath.cpp", "max_stars_repo_name": "mgbellemare/SkipCTS", "max_stars_repo_head_hexsha": "ff142fa87bc16b1e2e381cf4f9e4959e754b9028", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2015-01-27T10:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T07:49:56.000Z", "max_issues_repo_path": "src/fastmath.cpp", "max_issues_repo_name": "GitHubBeinner/SkipCTS", "max_issues_repo_head_hexsha": "48af5c74ed43f724c61cdcf2e1a022f48c460ed7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-02-12T21:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-27T01:44:10.000Z", "max_forks_repo_path": "src/fastmath.cpp", "max_forks_repo_name": "GitHubBeinner/SkipCTS", "max_forks_repo_head_hexsha": "48af5c74ed43f724c61cdcf2e1a022f48c460ed7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-06-15T07:06:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-10T12:04:21.000Z", "avg_line_length": 22.3137254902, "max_line_length": 59, "alphanum_fraction": 0.6370826011, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5294637382165361}}
{"text": "#ifndef EKF_HPP\n#define EKF_HPP\n\n#include <Eigen/Dense>\n#include <utility>\n\nnamespace EKF {\n/** Class responsible for the prediction part of a kalman filter.\n *\n * Its two templates arguments are the dimension of the state and the\n * dimension of the control input.\n */\ntemplate <int N, int M>\nclass Predictor {\npublic:\n    typedef Eigen::Matrix<float, N, 1> State;\n    typedef Eigen::Matrix<float, N, N> Covariance;\n    typedef Eigen::Matrix<float, M, 1> Input;\n    typedef Eigen::Matrix<float, N, N> Jacobian;\n\n    Predictor(Covariance process_noise)\n        : R(process_noise)\n    {\n    }\n\n    Predictor()\n        : R(Covariance::Zero())\n    {\n    }\n\n    /** State update function. */\n    virtual State g(State state, Input input)\n    {\n        (void)input;\n        return state;\n    }\n\n    /** Returns the Jacobian of the state update function. */\n    virtual Jacobian G(State state, Input input)\n    {\n        (void)input;\n        (void)state;\n        return Jacobian::Identity();\n    }\n\n    std::pair<State, Covariance> predict(State mu, Covariance sigma, Input u)\n    {\n        mu = g(mu, u);\n        auto Gn = G(mu, u);\n        sigma = Gn * sigma * Gn.transpose() + R;\n\n        return std::pair<State, Covariance>(mu, sigma);\n    }\n\nprivate:\n    Covariance R; // < Process covariance\n};\n\n/** Class responsible for the correction class of a Kalman filter.\n *\n * The two template arguments are the dimension of the state and the dimension\n * of the measurement.\n */\ntemplate <int N, int M>\nclass Corrector {\npublic:\n    typedef Eigen::Matrix<float, M, 1> Measurement;\n    typedef Eigen::Matrix<float, N, 1> State;\n    typedef Eigen::Matrix<float, M, N> Jacobian;\n    typedef Eigen::Matrix<float, N, N> Covariance;\n\n    virtual Measurement h(State) = 0;\n    virtual Jacobian H(State) = 0;\n\n    Corrector(Measurement variance)\n        : Q(variance)\n    {\n    }\n\n    std::pair<State, Covariance> correct(State mu, Covariance sigma, Measurement z)\n    {\n        auto H = this->H(mu);\n        auto K = sigma * H.transpose() * (H * sigma * H.transpose() + Q).inverse();\n        mu = mu + K * (z - h(mu));\n        sigma = (Covariance::Identity() - K * H) * sigma;\n\n        return std::pair<State, Covariance>(mu, sigma);\n    }\n\nprivate:\n    Measurement Q;\n};\n\n}; // namespace EKF\n\n#endif\n", "meta": {"hexsha": "1ef02a2d306ead1eea6d37c5a0c50d87079253cf", "size": 2287, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "uwb-beacon-firmware/src/ekf.hpp", "max_stars_repo_name": "greck2908/robot-software", "max_stars_repo_head_hexsha": "2e1e8177148a089e8883967375dde7f8ed3d878b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2016-10-04T19:59:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-25T18:11:35.000Z", "max_issues_repo_path": "uwb-beacon-firmware/src/ekf.hpp", "max_issues_repo_name": "greck2908/robot-software", "max_issues_repo_head_hexsha": "2e1e8177148a089e8883967375dde7f8ed3d878b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 209.0, "max_issues_repo_issues_event_min_datetime": "2016-09-21T21:54:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T07:42:37.000Z", "max_forks_repo_path": "uwb-beacon-firmware/src/ekf.hpp", "max_forks_repo_name": "greck2908/robot-software", "max_forks_repo_head_hexsha": "2e1e8177148a089e8883967375dde7f8ed3d878b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2016-11-07T14:40:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T09:53:37.000Z", "avg_line_length": 23.5773195876, "max_line_length": 83, "alphanum_fraction": 0.6147791867, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5294637328876647}}
{"text": "// Boost.Geometry Index\n// Unit Test\n\n// Copyright (c) 2011-2013 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#include <geometry_index_test_common.hpp>\n\n#include <boost/geometry/index/detail/algorithms/segment_intersection.hpp>\n\n//#include <boost/geometry/io/wkt/read.hpp>\n\ntemplate <typename Box, typename Point, typename RelativeDistance>\nvoid test_segment_intersection(Box const& box, Point const& p0, Point const& p1,\n                               bool expected_result,\n                               RelativeDistance expected_rel_dist)\n{\n    RelativeDistance rel_dist;\n    bool value = bgi::detail::segment_intersection(box, p0, p1, rel_dist);\n    BOOST_CHECK(value == expected_result);\n    if ( value && expected_result )\n        BOOST_CHECK_CLOSE(rel_dist, expected_rel_dist, 0.0001);\n}\n\ntemplate <typename Box, typename Point, typename RelativeDistance>\nvoid test_geometry(std::string const& wkt_g, std::string const& wkt_p0, std::string const& wkt_p1,\n                   bool expected_result,\n                   RelativeDistance expected_rel_dist)\n{\n    Box box;\n    bg::read_wkt(wkt_g, box);\n    Point p0, p1;\n    bg::read_wkt(wkt_p0, p0);\n    bg::read_wkt(wkt_p1, p1);\n    test_segment_intersection(box, p0, p1, expected_result, expected_rel_dist);\n}\n\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n\nvoid test_large_integers()\n{\n    typedef bg::model::point<int, 2, bg::cs::cartesian> int_point_type;\n    typedef bg::model::point<double, 2, bg::cs::cartesian> double_point_type;\n\n    bg::model::box<int_point_type> int_box;\n    bg::model::box<double_point_type> double_box;\n    int_point_type int_p0, int_p1;\n    double_point_type double_p0, double_p1;\n\n    std::string const str_box = \"POLYGON((1536119 192000, 1872000 528000))\";\n    std::string const str_p0 = \"POINT(1535000 191000)\";\n    std::string const str_p1 = \"POINT(1873000 529000)\";\n    bg::read_wkt(str_box, int_box);\n    bg::read_wkt(str_box, double_box);\n    bg::read_wkt(str_p0, int_p0);\n    bg::read_wkt(str_p1, int_p1);\n    bg::read_wkt(str_p0, double_p0);\n    bg::read_wkt(str_p1, double_p1);\n\n    float int_value;\n    bool int_result = bgi::detail::segment_intersection(int_box, int_p0, int_p1, int_value);\n    double double_value;\n    bool double_result = bgi::detail::segment_intersection(double_box, double_p0, double_p1, double_value);\n    BOOST_CHECK(int_result == double_result);\n    if ( int_result && double_result )\n        BOOST_CHECK_CLOSE(int_value, double_value, 0.0001);\n}\n\nint test_main(int, char* [])\n{\n    typedef bg::model::point<int, 2, bg::cs::cartesian> P2ic;\n    typedef bg::model::point<float, 2, bg::cs::cartesian> P2fc;\n    typedef bg::model::point<double, 2, bg::cs::cartesian> P2dc;\n\n    typedef bg::model::point<int, 3, bg::cs::cartesian> P3ic;\n    typedef bg::model::point<float, 3, bg::cs::cartesian> P3fc;\n    typedef bg::model::point<double, 3, bg::cs::cartesian> P3dc;\n\n    test_geometry<bg::model::box<P2ic>, P2ic>(\"POLYGON((0 1,2 4))\", \"POINT(0 0)\", \"POINT(2 5)\", true, 1.0f/5);\n    test_geometry<bg::model::box<P2fc>, P2fc>(\"POLYGON((0 1,2 4))\", \"POINT(0 0)\", \"POINT(2 5)\", true, 1.0f/5);\n    test_geometry<bg::model::box<P2dc>, P2dc>(\"POLYGON((0 1,2 4))\", \"POINT(0 0)\", \"POINT(2 5)\", true, 1.0/5);\n    test_geometry<bg::model::box<P3ic>, P3ic>(\"POLYGON((0 1 2,2 4 6))\", \"POINT(0 0 0)\", \"POINT(2 5 7)\", true, 2.0f/7);\n    test_geometry<bg::model::box<P3fc>, P3fc>(\"POLYGON((0 1 2,2 4 6))\", \"POINT(0 0 0)\", \"POINT(2 5 7)\", true, 2.0f/7);\n    test_geometry<bg::model::box<P3dc>, P3dc>(\"POLYGON((0 1 2,2 4 6))\", \"POINT(0 0 0)\", \"POINT(2 5 7)\", true, 2.0/7);\n\n    test_geometry<bg::model::box<P2ic>, P2ic>(\"POLYGON((0 1,2 4))\", \"POINT(3 4)\", \"POINT(0 0)\", true, 1.0f/3);\n    test_geometry<bg::model::box<P2fc>, P2fc>(\"POLYGON((0 1,2 4))\", \"POINT(3 4)\", \"POINT(0 2)\", true, 1.0f/3);\n    test_geometry<bg::model::box<P2dc>, P2dc>(\"POLYGON((0 1,2 4))\", \"POINT(3 4)\", \"POINT(0 2)\", true, 1.0/3);\n    test_geometry<bg::model::box<P3ic>, P3ic>(\"POLYGON((0 1 2,2 4 6))\", \"POINT(3 5 6)\", \"POINT(0 3 3)\", true, 1.0f/2);\n    test_geometry<bg::model::box<P3fc>, P3fc>(\"POLYGON((0 1 2,2 4 6))\", \"POINT(3 5 6)\", \"POINT(0 3 3)\", true, 1.0f/2);\n    test_geometry<bg::model::box<P3dc>, P3dc>(\"POLYGON((0 1 2,2 4 6))\", \"POINT(3 5 6)\", \"POINT(0 3 3)\", true, 1.0/2);\n\n    test_geometry<bg::model::box<P2ic>, P2ic>(\"POLYGON((0 1,2 4))\", \"POINT(1 0)\", \"POINT(1 5)\", true, 1.0f/5);\n    test_geometry<bg::model::box<P2fc>, P2fc>(\"POLYGON((0 1,2 4))\", \"POINT(1 5)\", \"POINT(1 0)\", true, 1.0f/5);\n    test_geometry<bg::model::box<P2dc>, P2dc>(\"POLYGON((0 1,2 4))\", \"POINT(1 0)\", \"POINT(1 5)\", true, 1.0/5);\n    test_geometry<bg::model::box<P3ic>, P3ic>(\"POLYGON((0 1 2,2 4 6))\", \"POINT(1 3 0)\", \"POINT(1 3 7)\", true, 2.0f/7);\n    test_geometry<bg::model::box<P3fc>, P3fc>(\"POLYGON((0 1 2,2 4 6))\", \"POINT(1 3 7)\", \"POINT(1 3 0)\", true, 1.0f/7);\n    test_geometry<bg::model::box<P3dc>, P3dc>(\"POLYGON((0 1 2,2 4 6))\", \"POINT(1 3 0)\", \"POINT(1 3 7)\", true, 2.0/7);\n\n    test_geometry<bg::model::box<P2ic>, P2ic>(\"POLYGON((0 1,2 4))\", \"POINT(0 0)\", \"POINT(0 5)\", true, 0.2f);\n    test_geometry<bg::model::box<P2fc>, P2fc>(\"POLYGON((0 1,2 4))\", \"POINT(0 5)\", \"POINT(0 0)\", true, 0.2f);\n    test_geometry<bg::model::box<P2dc>, P2dc>(\"POLYGON((0 1,2 4))\", \"POINT(0 0)\", \"POINT(0 5)\", true, 0.2);\n\n    test_geometry<bg::model::box<P2ic>, P2ic>(\"POLYGON((0 1,2 4))\", \"POINT(3 0)\", \"POINT(3 5)\", false, 0.0f);\n    test_geometry<bg::model::box<P2fc>, P2fc>(\"POLYGON((0 1,2 4))\", \"POINT(3 5)\", \"POINT(3 0)\", false, 0.0f);\n    test_geometry<bg::model::box<P2dc>, P2dc>(\"POLYGON((0 1,2 4))\", \"POINT(3 0)\", \"POINT(3 5)\", false, 0.0);\n\n    test_geometry<bg::model::box<P2fc>, P2fc>(\"POLYGON((0 1,2 4))\", \"POINT(1 0)\", \"POINT(1 1)\", true, 1.0f);\n    test_geometry<bg::model::box<P2fc>, P2fc>(\"POLYGON((0 1,2 4))\", \"POINT(1 4)\", \"POINT(1 5)\", true, 0.0f);\n\n    test_geometry<bg::model::box<P2fc>, P2fc>(\"POLYGON((0 1,2 4))\", \"POINT(0.5 2)\", \"POINT(1.5 3)\", true, 0.0f);\n\n#ifdef HAVE_TTMATH\n    typedef bg::model::point<ttmath_big, 2, bg::cs::cartesian> P2ttmc;\n    typedef bg::model::point<ttmath_big, 3, bg::cs::cartesian> P3ttmc;\n\n    test_geometry<bg::model::box<P2ttmc>, P2ttmc>(\"POLYGON((0 1,2 4))\", \"POINT(0 0)\", \"POINT(2 5)\", true, 1.0f/5);\n    test_geometry<bg::model::box<P3ttmc>, P3ttmc>(\"POLYGON((0 1 2,2 4 6))\", \"POINT(0 0 0)\", \"POINT(2 5 7)\", true, 2.0f/7);\n#endif\n\n    test_large_integers();\n\n    return 0;\n}\n", "meta": {"hexsha": "f58ad5dd72fb2eb164ee825509f4f24f851a3166", "size": 6662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/geometry/index/test/algorithms/segment_intersection.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/geometry/index/test/algorithms/segment_intersection.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/geometry/index/test/algorithms/segment_intersection.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": 51.2461538462, "max_line_length": 122, "alphanum_fraction": 0.6385469829, "num_tokens": 2553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5294637107751591}}
{"text": "#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <iostream>\n\n#define VIENNACL_WITH_OPENCL 1\n#define VIENNACL_WITH_EIGEN 1\n\n#include \"viennacl/linalg/svd.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/vector.hpp\"\n\nusing namespace Eigen;\nusing std::cout;\n\nint main() {\n  // initializers\n  MatrixXf C;\n  viennacl::matrix<float> vcl_C = viennacl::zero_matrix<float>(1e3, 50);\n  viennacl::matrix<float> vcl_U = viennacl::zero_matrix<float>(1e3, 1e3);\n  viennacl::matrix<float> vcl_V = viennacl::zero_matrix<float>(50, 50);\n\n  // random data\n  C.setRandom(1e5, 50);\n\n  // copy eigen to viennacl\n  viennacl::copy(C, vcl_C);\n\n  // eigen SVD\n  // JacobiSVD<MatrixXf> svd(C, ComputeThinU | ComputeThinV);\n  //\n  // std::cout << \"diag\" << std::endl;\n  // std::cout << svd.singularValues() << std::endl;\n  //\n  // std::cout << \"U\" << std::endl;\n  // std::cout << svd.matrixU() << std::endl;\n  //\n  // std::cout << \"V\" << std::endl;\n  // std::cout << svd.matrixV() << std::endl;\n\n  // viennacl svd\n\n  viennacl::linalg::svd(vcl_C, vcl_U, vcl_V);\n\n  viennacl::vector_base<float> D(vcl_C.handle(),\n                                 std::min(vcl_C.size1(), vcl_C.size2()), 0,\n                                 vcl_C.internal_size2() + 1);\n\n  // std::cout << \"diag\" << std::endl;\n  // std::cout << D << std::endl;\n  //\n  // std::cout << \"U\" << std::endl;\n  // std::cout << vcl_U << std::endl;\n  //\n  // std::cout << \"V\" << std::endl;\n  // std::cout << vcl_V << std::endl;\n\n  std::cout << \"V\" << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "66aa54b60252f991fa3ccd5f45fd74a1c2bc4de5", "size": 1511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/gpu_cpp_darcy/opencl-master/viennacl/viennacl_svd.cpp", "max_stars_repo_name": "shadialameddin/numerical_tools_and_friends", "max_stars_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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/gpu_cpp_darcy/opencl-master/viennacl/viennacl_svd.cpp", "max_issues_repo_name": "shadialameddin/numerical_tools_and_friends", "max_issues_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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/gpu_cpp_darcy/opencl-master/viennacl/viennacl_svd.cpp", "max_forks_repo_name": "shadialameddin/numerical_tools_and_friends", "max_forks_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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.1833333333, "max_line_length": 75, "alphanum_fraction": 0.5843812045, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5294637050477778}}
{"text": "//\n// Created by foxfire on 1/20/18.\n//\n\n#ifndef GFX_OPENGL_HPP\n#define GFX_OPENGL_HPP\n\n#include \"gfx.hpp\"\n\n#include <vector>\n#include <cstdint>\n\n#define _USE_MATH_DEFINES\n#include <GL/glew.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace fox\n{\n\tclass counter;\n}\nstruct OBJ_MODEL;\n\nclass gfx_opengl : public gfx\n{\npublic:\n\tgfx_opengl();\n\t\n\t~gfx_opengl() override;\n\t\n\tvoid init(int w, int h) override;\n\t\n\tvoid render() override;\n\t\n\tvoid resize(int w, int h) override;\n\t\n\tvoid deinit() override;\n\nprivate:\n\tint win_w, win_h;\n\t// an empty vertex array object to bind to\n\tuint32_t default_vao;\n\t\n\tEigen::Vector3f eye, target, up;\n\tEigen::Affine3f V;\n\tEigen::Projective3f P;\n\t// model matrix (specific to the model instance)\n\tstd::vector<Eigen::Projective3f> MVP;\n\tstd::vector<Eigen::Affine3f> M, MV;\n\t// TODO: should this be Affine3f ?\n\tstd::vector<Eigen::Matrix3f> normal_matrix;\n\t// more shader uniforms\n\tEigen::Vector4f light_pos, color;\n\tEigen::Vector3f La, Ls, Ld;\n\tEigen::Vector3f Ka, Ks, Kd;\n\tfloat shininess;\n\t\n\tGLuint shader_id, shader_vert_id, shader_frag_id;\n\tGLuint vertex_vbo, normal_vbo;\n\t\n\tfox::counter *phy_counter;\n\tfox::counter *fps_counter;\n\tfox::counter *perf_counter;\n\n\tconst static uint8_t perf_array_size = 8;\n\tdouble phys_times[perf_array_size];\n\tdouble gfx_matrix_times[perf_array_size];\n\tdouble render_times[perf_array_size];\n\tdouble phys_time;\n\tdouble gfx_matrix_time;\n\tdouble render_time;\n\tuint8_t perf_index;\n\tdouble total_time;\n\t\n\tOBJ_MODEL *mesh;\n\t\n\tvoid print_info();\n\tvoid load_shaders();\n\n\tvoid update_matricies();\n};\n\n\n#endif //GFX_OPENGL_HPP\n", "meta": {"hexsha": "dd9d6539d207ac2ae75a8c2512fbf220c34151d0", "size": 1587, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gfx/gfx_opengl.hpp", "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": "gfx/gfx_opengl.hpp", "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": "gfx/gfx_opengl.hpp", "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": 18.6705882353, "max_line_length": 50, "alphanum_fraction": 0.7366099559, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5294456338943604}}
{"text": "/*\n * algebra.hpp\n *\n *  Created on: 30 Jul 2017\n *      Author: julianporter\n */\n\n#ifndef ALGEBRA_HPP_\n#define ALGEBRA_HPP_\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <cmath>\n\n#define PI 3.14159265359\n#define radians(x) (x*PI/180.0)\n#define degrees(x) (x*180.0/PI)\n\nnamespace mapping {\n\nusing Vector = boost::numeric::ublas::vector<double>;\nusing Zero   = boost::numeric::ublas::zero_vector<double>;\nusing Matrix = boost::numeric::ublas::matrix<double>;\nusing ID     = boost::numeric::ublas::identity_matrix<double>;\nusing ZMatrix= boost::numeric::ublas::zero_matrix<double>;\n\nbool operator==(const Vector &l,const Vector &r);\nbool operator!=(const Vector &l,const Vector &r);\n\nbool operator==(const Matrix &l,const Matrix &r);\nbool operator!=(const Matrix &l,const Matrix &r);\n\nMatrix transpose(const Matrix &m);\n\n}\n\n#endif /* ALGEBRA_HPP_ */\n", "meta": {"hexsha": "4042a91086517874c59b656953d9447ffc9ca236", "size": 934, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/include/mapping/algebra.hpp", "max_stars_repo_name": "EdwardBetts/OSGridConverter", "max_stars_repo_head_hexsha": "d28e04e3e86efb4b7e21141f9a9a2b26217dced3", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-06-20T16:07:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T11:14:04.000Z", "max_issues_repo_path": "cpp/include/mapping/algebra.hpp", "max_issues_repo_name": "EdwardBetts/OSGridConverter", "max_issues_repo_head_hexsha": "d28e04e3e86efb4b7e21141f9a9a2b26217dced3", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-02-16T19:10:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-07T07:38:29.000Z", "max_forks_repo_path": "cpp/include/mapping/algebra.hpp", "max_forks_repo_name": "EdwardBetts/OSGridConverter", "max_forks_repo_head_hexsha": "d28e04e3e86efb4b7e21141f9a9a2b26217dced3", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-02-27T06:15:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-20T18:34:44.000Z", "avg_line_length": 23.9487179487, "max_line_length": 62, "alphanum_fraction": 0.7162740899, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5294456338943604}}
{"text": "//==================================================================================================\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#include <boost/simd/pack.hpp>\n#include <boost/simd/function/gammaln.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/halfeps.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/five.hpp>\n#include <boost/simd/constant/mtwo.hpp>\n\nnamespace bs = boost::simd;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid limit_test(Env& runtime)\n{\n  using p_t = bs::pack<T, N>;\n  using bs::gammaln;\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(gammaln(bs::Inf<p_t>()), bs::Inf<p_t>(), 0);\n  STF_ULP_EQUAL(gammaln(bs::Minf<p_t>()), bs::Nan<p_t>(), 0);\n  STF_ULP_EQUAL(gammaln(bs::Nan<p_t>()), bs::Nan<p_t>(), 0);\n  STF_ULP_EQUAL(gammaln(bs::Zero<p_t>()), bs::Inf<p_t>(), 0);\n#endif\n  STF_ULP_EQUAL(gammaln(bs::Mone<p_t>()), bs::Inf<p_t>(), 0);\n  STF_ULP_EQUAL(gammaln(bs::Mtwo<p_t>()), bs::Inf<p_t>(), 0);\n  STF_ULP_EQUAL(gammaln(bs::One<p_t>()), bs::Zero<p_t>(), 0);\n  STF_ULP_EQUAL(gammaln(bs::Two<p_t>()), bs::Zero<p_t>(), 0);\n  STF_ULP_EQUAL(gammaln(bs::Mzero<p_t>()),         bs::Inf<p_t>(), 0);\n\n  STF_ULP_EQUAL(gammaln(bs::Halfeps<p_t>()),       p_t( bs::std_(gammaln)(bs::Halfeps<p_t>())), 1);\n  STF_ULP_EQUAL(gammaln(bs::Eps<p_t>()),           p_t(bs::std_(gammaln)(bs::Eps<p_t>())), 0.5);\n  STF_ULP_EQUAL(gammaln(bs::Half<p_t>()),          p_t(bs::std_(gammaln)(bs::Half<p_t>())), 0.5);\n  STF_ULP_EQUAL(gammaln(p_t(1.5)),                 p_t(bs::std_(gammaln)(T(1.5))), 1.5);\n  STF_ULP_EQUAL(gammaln(p_t(2.5)),                 p_t(bs::std_(gammaln)(T(2.5))), 0.5);\n  STF_ULP_EQUAL(gammaln(p_t(13)) ,                 p_t(bs::std_(gammaln)(T(13))), 0.5);\n  STF_ULP_EQUAL(gammaln(p_t(13.5)) ,               p_t(bs::std_(gammaln)(T(13.5))), 0.5);\n  STF_ULP_EQUAL(gammaln(p_t(-0.1)),                p_t(bs::std_(gammaln)(T(-0.1))),         1);\n  STF_ULP_EQUAL(gammaln(-bs::Half<p_t>()),         p_t(bs::std_(gammaln)(-bs::Half<T>())),  0.5);\n  STF_ULP_EQUAL(gammaln(-bs::Halfeps<p_t>()),      p_t(bs::std_(gammaln)(-bs::Halfeps<T>())), 0.5);\n  STF_ULP_EQUAL(gammaln(p_t(-27.5)),               p_t(bs::std_(gammaln)(T(-27.5))),            3);\n}\n\nSTF_CASE_TPL(\"Check gammaln limit cases\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n  limit_test<T, N>(runtime);\n  limit_test<T, N/2>(runtime);\n  limit_test<T, N*2>(runtime);\n}\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& runtime)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], b[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i) : T(-i);\n    b[i] = bs::gammaln(a1[i]) ;\n  }\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t bb (&b[0], &b[0]+N);\n\n  STF_ULP_EQUAL(bs::gammaln(aa1), bb, 0.5);\n}\n\nSTF_CASE_TPL(\"Check gammaln on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n   test<T, N>(runtime);\n   test<T, N/2>(runtime);\n   test<T, N*2>(runtime);\n}\n", "meta": {"hexsha": "81ba1becac1068a004e6a46c9ed00147e9008137", "size": 3640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/gammaln.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/simd/gammaln.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/simd/gammaln.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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": 39.1397849462, "max_line_length": 100, "alphanum_fraction": 0.5936813187, "num_tokens": 1294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5294456316496425}}
{"text": "#ifndef __HODLR_Tree__\n#define __HODLR_Tree__\n\n#include <Eigen/Dense>\n#include \"HODLR_Matrix.hpp\"\n#include \"HODLR_Node.hpp\"\n\nclass HODLR_Tree \n{\nprivate:\n    int N;\n    int n_levels;\n    double tolerance;\n    std::vector<int> nodes_in_level;\n    HODLR_Matrix* A;\n    bool is_sym, is_pd;\n    \n    // Vector of levels(which contain nodes) thereby giving the tree:\n    std::vector<std::vector<HODLR_Node*>> tree;\n    void createTree();\n    void createRoot();\n    void createChildren(int level_number, int node_number);\n\n    // Methods needed for the nonSPD HODLR solver:\n    void factorizeLeafNonSPD(int node_number);\n    void factorizeNonLeafNonSPD(int level_number, int node_number);\n    void factorizeNonSPD();\n    Mat solveLeafNonSPD(int node_number, Mat b);\n    Mat solveNonLeafNonSPD(int level_number, int node_number, Mat b);\n    Mat solveNonSPD(Mat b);\n    dtype logDeterminantNonSPD();\n\n    // Methods needed for the SPD HODLR solver:\n    void factorizeLeafSPD(int node_number);\n    void factorizeNonLeafSPD(int level_number, int node_number);\n    void factorizeSPD();\n    void qr(int level_number, int node_number);\n    void qrForLevel(int level_number);\n    Mat solveLeafSymmetricFactor(int node_number, Mat b);\n    Mat solveNonLeafSymmetricFactor(int level_number, int node_number, Mat b);\n    //Mat solveSymmetricFactor(Mat b);\n    Mat solveLeafSymmetricFactorTranspose(int node_number, Mat b);\n    Mat solveNonLeafSymmetricFactorTranspose(int level_number, int node_number, Mat b);\n    //Mat solveSymmetricFactorTranspose(Mat b);\n    Mat solveSPD(Mat b);\n    Mat SymmetricFactorNonLeafProduct(int level_number, int node_number, Mat b);\n    Mat SymmetricFactorTransposeNonLeafProduct(int level_number, int node_number, Mat b);\n    dtype logDeterminantSPD();\n\npublic:\n    HODLR_Tree(int n_levels, double tolerance, HODLR_Matrix* A);\n    ~HODLR_Tree();\n\n    //  Methods for HODLR solver\n    void assembleTree(bool is_sym = false, bool is_pd = false);\n    // Gives the box details of the prescribed box and level number:\n    void printNodeDetails(int level_number, int node_number);\n    // Lists details of all boxes in the tree\n    void printTreeDetails();\n    void plotTree(std::string image_name);\n    Mat matmatProduct(Mat x);\n    void factorize();\n    Mat solve(Mat b);\n    ////////////////////////////////////////////////\n    Mat solveSymmetricFactorTranspose(Mat b);\n    Mat solveSymmetricFactor(Mat b);\n    ////////////////////////////////////////////////\n    Mat symmetricFactorProduct(Mat x);\n    Mat symmetricFactorTransposeProduct(Mat x);\n    Mat getSymmetricFactor();\n    dtype logDeterminant();\n};\n\n#endif /*__HODLR_Tree__*/\n", "meta": {"hexsha": "d18f239d2be3c4ff46eaa5fe69c3afb5d397a1eb", "size": 2646, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fifa_gp/include/HODLR_Tree.hpp", "max_stars_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_stars_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fifa_gp/include/HODLR_Tree.hpp", "max_issues_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_issues_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fifa_gp/include/HODLR_Tree.hpp", "max_forks_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_forks_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_forks_repo_licenses": ["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.28, "max_line_length": 89, "alphanum_fraction": 0.7033257748, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.529445628939048}}
{"text": "#include <expression/dualtime/FixedPointBDFDualTimeIntegrator.h>\n#include <expression/dualtime/VariableImplicitBDFDualTimeIntegrator.h>\n#include <spatialops/structured/Grid.h>\n#include <spatialops/structured/FVStaggered.h>\n\n#include <test/TestHelper.h>\n#include \"ExpDecay.h\"\n#include <expression/Functions.h>\n#include <expression/ExpressionTree.h>\n#include <expression/ExprPatch.h>\n\n#include <boost/program_options.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <iostream>\n#include <fstream>\n\nusing std::cout;\nusing std::endl;\n\nnamespace po = boost::program_options;\nnamespace so = SpatialOps;\n\ntypedef so::SVolField FieldT;\n\ndouble bdf_error_from_dt( double dt, const unsigned designOrder )\n{\n  const double tend = 1.0;\n  const double k    = 1.0;\n  const double phi0 = 1.0;\n  const double ds   = 0.1*dt;\n\n  try{\n\n    Expr::ExprPatch patch(1);\n    SpatialOps::OperatorDatabase sodb;\n    Expr::FieldManagerList& fml = patch.field_manager_list();\n\n    const Expr::Tag dtTag    ( \"timestep\",      Expr::STATE_NONE );\n    const Expr::Tag dsTag    ( \"dual-timestep\", Expr::STATE_NONE );\n\n    Expr::DualTime::BDFDualTimeIntegrator* integrator = new Expr::DualTime::FixedPointBDFDualTimeIntegrator<FieldT>( 0, \"BasicDualTime\", dtTag, dsTag, designOrder );\n\n    typedef Expr::ConstantExpr<so::SingleValueField>::Builder ConstantSingleValueT;\n    integrator->set_physical_time_step_expression( new ConstantSingleValueT( dtTag, dt ) );\n    integrator->set_dual_time_step_expression    ( new ConstantSingleValueT( dsTag, ds ) );\n\n    Expr::ExpressionFactory& factory = integrator->factory();\n\n    std::string phiName = \"phi\";\n    const Expr::Tag phiTag   ( phiName,          Expr::STATE_NONE );\n    const Expr::Tag phiRHSTag( phiName + \"_rhs\", Expr::STATE_NONE );\n    factory.register_expression( new ExpDecayRHS<FieldT>::Builder( k, phiRHSTag, phiTag ) );\n\n    integrator->add_variable<FieldT>( phiTag.name(), phiRHSTag );\n\n    integrator->prepare_for_integration( fml, sodb, patch.field_info() );\n\n    Expr::ExpressionFactory icFactory;\n\n    const Expr::Tag phiNTag( phiName, Expr::STATE_N );\n    const Expr::ExpressionID id = icFactory.register_expression( new Expr::ConstantExpr<FieldT>::Builder( phiNTag, phi0 ) );\n    Expr::ExpressionTree icTree( id, icFactory, patch.id() );\n\n    icTree.register_fields( fml );\n    icTree.bind_fields( fml );\n    icTree.execute_tree();\n\n    double t = 0;\n\n    const unsigned maxIterPerStep = 100;\n\n    unsigned totalIter = 0;\n    unsigned stepCount = 0;\n    unsigned dualIter  = 0;\n    bool     converged = false;\n\n    while( t < ( tend-1e-12 ) ){\n      // this (tend - 1e-12) 'trick' is to prevent roundoff error from triggering an extra time step\n\n      dualIter = 0;\n      integrator->begin_time_step();\n\n      do{\n\n        integrator->advance_dualtime( converged );\n\n        dualIter++;\n        totalIter++;\n\n      } while( !converged && dualIter <= maxIterPerStep );\n\n      integrator->end_time_step();\n      stepCount++;\n      t += dt;\n    }\n\n    FieldT& prediction = fml.field_ref<FieldT>( Expr::Tag( phiName, Expr::STATE_N ) );\n    prediction.add_device(CPU_INDEX);\n    SpatialOps::SpatFldPtr<FieldT> exact = SpatialOps::SpatialFieldStore::get<FieldT>( prediction );\n    *exact <<= phi0*std::exp(-k*tend);\n    return SpatialOps::nebo_norm( *exact - prediction );\n  }\n  catch( std::exception& err ){\n    std::cout << err.what() << std::endl;\n    return -1;\n  }\n\n}\n\nbool bdf_run_test( const double designOrder,\n                   const bool check_vs_matlab = false,\n                   const double matlabObservedOrder = 0.0 )\n{\n  typedef std::vector<double> dvec;\n\n  const int ndt = 3;\n\n  dvec dt(ndt);\n  dvec e(ndt);\n\n  dt[0] = 0.1;\n  dt[1] = 0.05;\n  dt[2] = 0.01;\n\n  double meanlog10dt = 0.0;\n  double meanlog10error = 0.0;\n\n  for( int i=0; i<ndt; ++i ){\n    e[i] = bdf_error_from_dt( dt[i], (unsigned) designOrder );\n    meanlog10dt    += std::log10(dt[i])/((double) ndt);\n    meanlog10error += std::log10( e[i])/((double) ndt);\n  }\n\n  double numerator = 0.0;\n  double denominator = 0.0;\n\n  for( int i=0; i<ndt; ++i ){\n    const double dt_deviation = std::log10(dt[i]) - meanlog10dt;\n    numerator   += dt_deviation*(std::log10(e[i]) - meanlog10error);\n    denominator += dt_deviation*dt_deviation;\n  }\n\n  double observedOrder = numerator/denominator;\n\n  if( check_vs_matlab ){\n    return ( observedOrder > ( matlabObservedOrder - 0.05 ) ) && ( observedOrder < ( matlabObservedOrder + 0.1 ) );\n  }\n  else{\n    return ( observedOrder > ( designOrder - 0.05 ) ) && ( observedOrder < ( designOrder + 0.1 ) );\n  }\n}\n\n\n\nint main( int iarg, char* carg[] )\n{\n  TestHelper status;\n  status( bdf_run_test( 1 ), \"BDF-1 accuracy\" );\n  status( bdf_run_test( 2 ), \"BDF-2 accuracy\" );\n  status( bdf_run_test( 3, true, 1.965900224509586 ), \"BDF-3 vs Matlab code\" );\n  status( bdf_run_test( 4, true, 1.976953783712932 ), \"BDF-4 vs Matlab code\" );\n\n  if( status.ok() ){\n    std::cout << \"PASS\\n\";\n    return 0;\n  }\n\n  std::cout << \"FAIL\\n\";\n  return -1;\n}\n", "meta": {"hexsha": "3fe3b9d26e8991390b3c33e5d143812ca27e3b4e", "size": 4979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/dualtime/dualtimeExpDecayVerificationTest.cpp", "max_stars_repo_name": "MaxZZG/ExprLib", "max_stars_repo_head_hexsha": "c35e361ef6af365e7cd6afca6548595693bd149a", "max_stars_repo_licenses": ["MIT"], "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/dualtime/dualtimeExpDecayVerificationTest.cpp", "max_issues_repo_name": "MaxZZG/ExprLib", "max_issues_repo_head_hexsha": "c35e361ef6af365e7cd6afca6548595693bd149a", "max_issues_repo_licenses": ["MIT"], "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/dualtime/dualtimeExpDecayVerificationTest.cpp", "max_forks_repo_name": "MaxZZG/ExprLib", "max_forks_repo_head_hexsha": "c35e361ef6af365e7cd6afca6548595693bd149a", "max_forks_repo_licenses": ["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.9476744186, "max_line_length": 165, "alphanum_fraction": 0.6641895963, "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5294456266943304}}
{"text": "#ifndef WAVE_WEIGHTING_FUNCTIONS_HPP\n#define WAVE_WEIGHTING_FUNCTIONS_HPP\n\n#include <Eigen/Core>\n\nnamespace wave {\n\nEigen::Matrix3d calculatePointToLineWeight(const double *const pt,\n                                           const double *const ptA,\n                                           const double *const ptB,\n                                           const double &variance);\n\ndouble calculatePointToPlaneWeight(const double *const pt,\n                                   const double *const ptA,\n                                   const double *const ptB,\n                                   const double *const ptC,\n                                   const double &variance);\n\n}\n\n#endif //WAVE_WEIGHTING_FUNCTIONS_HPP\n", "meta": {"hexsha": "60b69a01ecab3db71a6a995d4440a176edf7e22d", "size": 729, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "wave_odometry/include/wave/odometry/weighting_functions.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_odometry/include/wave/odometry/weighting_functions.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_odometry/include/wave/odometry/weighting_functions.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": 33.1363636364, "max_line_length": 67, "alphanum_fraction": 0.5089163237, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.529445621739018}}
{"text": "//\n// Copyright 2019-2020 Mateusz Loskot <mateusz at loskot dot net>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#include <boost/gil.hpp>\n#include <boost/gil/extension/numeric/affine.hpp>\n#include <boost/gil/extension/numeric/resample.hpp>\n#include <boost/gil/extension/numeric/sampler.hpp>\n\n#include <boost/core/lightweight_test.hpp>\n\n#include <cmath>\n\nnamespace gil = boost::gil;\n\n// Tolerance predicate for floating point comparison to use with BOOST_TEST_WITH\ntemplate <typename T>\nstruct with_tolerance\n{\n    with_tolerance(T tolerance) : tolerance(tolerance) {}\n    bool operator()(T lhs, T rhs)\n    {\n        return (std::abs(lhs - rhs) <= tolerance);\n    }\n\nprivate:\n    T tolerance;\n};\n\nnamespace {\nconstexpr double HALF_PI = 1.57079632679489661923;\n}\n\nvoid test_matrix3x2_default_constructor()\n{\n    gil::matrix3x2<int> m1;\n    BOOST_TEST_EQ(m1.a, 1);\n    BOOST_TEST_EQ(m1.b, 0);\n    BOOST_TEST_EQ(m1.c, 0);\n    BOOST_TEST_EQ(m1.d, 1);\n    BOOST_TEST_EQ(m1.e, 0);\n    BOOST_TEST_EQ(m1.f, 0);\n}\n\nvoid test_matrix3x2_parameterized_constructor()\n{\n    gil::matrix3x2<int> m1(1, 2, 3, 4, 5, 6);\n    BOOST_TEST_EQ(m1.a, 1);\n    BOOST_TEST_EQ(m1.b, 2);\n    BOOST_TEST_EQ(m1.c, 3);\n    BOOST_TEST_EQ(m1.d, 4);\n    BOOST_TEST_EQ(m1.e, 5);\n    BOOST_TEST_EQ(m1.f, 6);\n}\n\nvoid test_matrix3x2_copy_constructor()\n{\n    gil::matrix3x2<int> m1(1, 2, 3, 4, 5, 6);\n    gil::matrix3x2<int> m2(m1);\n    BOOST_TEST_EQ(m2.a, 1);\n    BOOST_TEST_EQ(m2.b, 2);\n    BOOST_TEST_EQ(m2.c, 3);\n    BOOST_TEST_EQ(m2.d, 4);\n    BOOST_TEST_EQ(m2.e, 5);\n    BOOST_TEST_EQ(m2.f, 6);\n}\n\nvoid test_matrix3x2_assignment_operator()\n{\n    gil::matrix3x2<int> m1(1, 2, 3, 4, 5, 6);\n    gil::matrix3x2<int> m2;\n    m2 = m1;\n    BOOST_TEST_EQ(m2.a, 1);\n    BOOST_TEST_EQ(m2.b, 2);\n    BOOST_TEST_EQ(m2.c, 3);\n    BOOST_TEST_EQ(m2.d, 4);\n    BOOST_TEST_EQ(m2.e, 5);\n    BOOST_TEST_EQ(m2.f, 6);\n}\n\nvoid test_matrix3x2_multiplication_assignment()\n{\n    gil::matrix3x2<int> m1;\n    gil::matrix3x2<int> m2;\n    m2 *= m1;\n    BOOST_TEST_EQ(m2.a, 1);\n    BOOST_TEST_EQ(m2.b, 0);\n    BOOST_TEST_EQ(m2.c, 0);\n    BOOST_TEST_EQ(m2.d, 1);\n    BOOST_TEST_EQ(m2.e, 0);\n    BOOST_TEST_EQ(m2.f, 0);\n\n    gil::matrix3x2<int> m3(0, 0, 0, 0, 0, 0);\n    m2 *= m3;\n    BOOST_TEST_EQ(m2.a, 0);\n    BOOST_TEST_EQ(m2.b, 0);\n    BOOST_TEST_EQ(m2.c, 0);\n    BOOST_TEST_EQ(m2.d, 0);\n    BOOST_TEST_EQ(m2.e, 0);\n    BOOST_TEST_EQ(m2.f, 0);\n}\n\nvoid test_matrix3x2_matrix3x2_multiplication()\n{\n    gil::matrix3x2<int> m1;\n    gil::matrix3x2<int> m2(0, 0, 0, 0, 0, 0);\n    gil::matrix3x2<int> m3;\n    m3 = m1 * m2;\n    BOOST_TEST_EQ(m3.a, 0);\n    BOOST_TEST_EQ(m3.b, 0);\n    BOOST_TEST_EQ(m3.c, 0);\n    BOOST_TEST_EQ(m3.d, 0);\n    BOOST_TEST_EQ(m3.e, 0);\n    BOOST_TEST_EQ(m3.f, 0);\n}\n\nvoid test_matrix3x2_vector_multiplication()\n{\n    gil::matrix3x2<int> m1;\n    gil::point<int> v1{2, 4};\n\n    gil::point<int> v2 = v1 * m1;\n    BOOST_TEST_EQ(v2.x, 2);\n    BOOST_TEST_EQ(v2.y, 4);\n\n    gil::point<int> v3 = gil::transform(m1, v1);\n    BOOST_TEST_EQ(v3.x, 2);\n    BOOST_TEST_EQ(v3.y, 4);\n}\n\nvoid test_matrix3x2_get_rotate()\n{\n    auto m1 = gil::matrix3x2<double>::get_rotate(HALF_PI);\n    BOOST_TEST_WITH(m1.a, std::cos(HALF_PI), with_tolerance<double>(0.03));\n    BOOST_TEST_EQ(m1.b, 1);\n    BOOST_TEST_EQ(m1.c, -1);\n    BOOST_TEST_WITH(m1.d, std::cos(HALF_PI), with_tolerance<double>(0.03));\n    BOOST_TEST_EQ(m1.e, 0);\n    BOOST_TEST_EQ(m1.f, 0);\n}\n\nvoid test_matrix3x2_get_scale()\n{\n    gil::matrix3x2<int> m1;\n    m1 = gil::matrix3x2<int>::get_scale(2);\n    BOOST_TEST_EQ(m1.a, 2);\n    BOOST_TEST_EQ(m1.b, 0);\n    BOOST_TEST_EQ(m1.c, 0);\n    BOOST_TEST_EQ(m1.d, 2);\n    BOOST_TEST_EQ(m1.e, 0);\n    BOOST_TEST_EQ(m1.f, 0);\n    m1 = gil::matrix3x2<int>::get_scale(2, 4);\n    BOOST_TEST_EQ(m1.a, 2);\n    BOOST_TEST_EQ(m1.d, 4);\n    m1 = gil::matrix3x2<int>::get_scale(gil::point<int>{4, 8});\n    BOOST_TEST_EQ(m1.a, 4);\n    BOOST_TEST_EQ(m1.d, 8);\n}\n\nvoid test_matrix3x2_get_translate()\n{\n    gil::matrix3x2<int> m1;\n    m1 = gil::matrix3x2<int>::get_translate(2, 4);\n    BOOST_TEST_EQ(m1.a, 1);\n    BOOST_TEST_EQ(m1.b, 0);\n    BOOST_TEST_EQ(m1.c, 0);\n    BOOST_TEST_EQ(m1.d, 1);\n    BOOST_TEST_EQ(m1.e, 2);\n    BOOST_TEST_EQ(m1.f, 4);\n    m1 = gil::matrix3x2<int>::get_translate(gil::point<int>{4, 8});\n    BOOST_TEST_EQ(m1.e, 4);\n    BOOST_TEST_EQ(m1.f, 8);\n}\n\nvoid test_matrix3x2_transform()\n{\n    gil::matrix3x2<int> m1;\n    gil::point<int> v1{2, 4};\n    gil::point<int> v2 = gil::transform(m1, v1);\n    BOOST_TEST_EQ(v2.x, 2);\n    BOOST_TEST_EQ(v2.y, 4);\n}\n\nvoid test_matrix3x2_inverse()\n{\n    using matrix_t = gil::matrix3x2<double>;\n    using point_t = gil::point<double>;\n\n    matrix_t mo = matrix_t::get_translate(0, 16);\n    matrix_t mb = matrix_t::get_rotate(HALF_PI);\n    auto m = mo * mb;\n\n    point_t p(10, 10);\n    point_t q = gil::transform(inverse(m), p);\n    point_t p2 = gil::transform(m, q);\n\n    BOOST_TEST_WITH(p.x, p2.x, with_tolerance<double>(1e-9));\n    BOOST_TEST_WITH(p.y, p2.y, with_tolerance<double>(1e-9));\n}\n\nint main()\n{\n    test_matrix3x2_default_constructor();\n    test_matrix3x2_parameterized_constructor();\n    test_matrix3x2_copy_constructor();\n    test_matrix3x2_assignment_operator();\n    test_matrix3x2_multiplication_assignment();\n    test_matrix3x2_matrix3x2_multiplication();\n    test_matrix3x2_vector_multiplication();\n    test_matrix3x2_get_rotate();\n    test_matrix3x2_get_scale();\n    test_matrix3x2_get_translate();\n    test_matrix3x2_transform();\n    test_matrix3x2_inverse();\n\n    return ::boost::report_errors();\n}\n", "meta": {"hexsha": "d3c34f4e484c074b81ad94929748c29893935ecc", "size": 5620, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/extension/numeric/matrix3x2.cpp", "max_stars_repo_name": "Siddharth1010/gil", "max_stars_repo_head_hexsha": "c0023b9ba43555552bebcc05bc2fbf5b175db191", "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/extension/numeric/matrix3x2.cpp", "max_issues_repo_name": "Siddharth1010/gil", "max_issues_repo_head_hexsha": "c0023b9ba43555552bebcc05bc2fbf5b175db191", "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/extension/numeric/matrix3x2.cpp", "max_forks_repo_name": "Siddharth1010/gil", "max_forks_repo_head_hexsha": "c0023b9ba43555552bebcc05bc2fbf5b175db191", "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.4298642534, "max_line_length": 80, "alphanum_fraction": 0.6571174377, "num_tokens": 1994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5294456167837057}}
{"text": "#ifndef TEST_UTILS_HPP\n#define TEST_UTILS_HPP\n\n#if SKYLARK_HAVE_BOOST\n#include <boost/test/minimal.hpp>\n#endif\n\n#include \"../../skylark.hpp\"\n\n#include <El.hpp>\n\nnamespace test { namespace util {\n\ntemplate < typename InputMatrixType,\n           typename OutputMatrixType = InputMatrixType >\nstruct hash_transform_test_t : public skylark::sketch::hash_transform_t<\n    InputMatrixType, OutputMatrixType,\n    boost::random::uniform_int_distribution,\n    skylark::utility::rademacher_distribution_t > {\n\n    typedef skylark::sketch::hash_transform_t<\n        InputMatrixType, OutputMatrixType,\n        boost::random::uniform_int_distribution,\n        skylark::utility::rademacher_distribution_t >\n            hash_t;\n\n    hash_transform_test_t(int N, int S, skylark::base::context_t& context)\n        : skylark::sketch::hash_transform_t<InputMatrixType, OutputMatrixType,\n          boost::random::uniform_int_distribution,\n          skylark::utility::rademacher_distribution_t>(N, S, context)\n    {}\n\n    std::vector<size_t> getRowIdx() { return hash_t::row_idx; }\n    std::vector<double> getRowValues() { return hash_t::row_value; }\n};\n\ntemplate<typename MatrixType>\nMatrixType operator-(MatrixType& A, MatrixType& B) {\n    MatrixType C;\n    El::Copy(A, C);\n    El::Axpy(-1.0, B, C);\n    return C;\n}\n\ntemplate<typename MatrixType>\nbool equal(MatrixType& A, MatrixType& B,  double threshold=1.e-4) {\n    MatrixType C = A - B;\n    double diff_norm = El::Norm(C);\n    if (diff_norm < threshold) {\n        return true;\n    }\n    return false;\n}\n\ntemplate<typename InputMatrixType,\n         typename LeftSingularVectorsMatrixType,\n         typename SingularValuesMatrixType,\n         typename RightSingularVectorsMatrixType>\nbool equal_svd_product(InputMatrixType& A,\n    LeftSingularVectorsMatrixType& U,\n    SingularValuesMatrixType& S,\n    RightSingularVectorsMatrixType& V,\n    double threshold=1e-4) {\n\n    El::DistMatrix<double> S_CIRC_CIRC = S;\n    std::vector<double> values(S_CIRC_CIRC.Buffer(),\n        S_CIRC_CIRC.Buffer() + S_CIRC_CIRC.Height());\n    El::Diagonal(S_CIRC_CIRC, values);\n    El::DistMatrix<double> S_MC_MR = S_CIRC_CIRC;\n\n    El::DistMatrix<double> A_MC_MR = A;\n    El::DistMatrix<double> U_MC_MR = U;\n    El::DistMatrix<double> V_MC_MR = V;\n    El::DistMatrix<double> US_MC_MR;\n    El::DistMatrix<double> USVt_MC_MR;\n\n    US_MC_MR.Resize(U.Height(), S_CIRC_CIRC.Width());\n    El::Zero(US_MC_MR);\n    USVt_MC_MR.Resize(U.Height(), V.Height());\n\n    El::Zero(USVt_MC_MR);\n    El::Gemm(El::NORMAL, El::NORMAL,    1.0, U_MC_MR,\n        S_MC_MR, 0.0, US_MC_MR);\n    El::Gemm(El::NORMAL, El::TRANSPOSE, 1.0, US_MC_MR,\n        V_MC_MR, 0.0, USVt_MC_MR);\n\n    return equal(A_MC_MR, USVt_MC_MR, threshold);\n}\n\n\n#if SKYLARK_HAVE_BOOST\n\ntemplate <typename dense_matrix_t>\nvoid check_equal(const dense_matrix_t& A, const dense_matrix_t& B) {\n    double threshold = 1e-7;\n    for (int col = 0; col < A.LocalWidth(); col++) {\n        for (int row = 0; row < A.LocalHeight(); row++) {\n            double diff = fabs(A.GetLocal(row, col) - B.GetLocal(row, col));\n            if (diff > threshold) {\n                std::cerr << \"(\" << row << \", \" << col << \") diff = \"\n                          << A.GetLocal(row, col) << \" - \"\n                          << B.GetLocal(row, col) << \" = \" << diff\n                          << std::endl;\n                BOOST_FAIL(\"Matrices differ\");\n            }\n        }\n    }\n}\n\nvoid check(El::DistMatrix<double>& A,\n    double threshold=1e-4) {\n    El::DistMatrix<double> U, V;\n    El::DistMatrix<double, El::VR, El::STAR> S_VR_STAR;\n    U = A;\n    El::SVD(U, U, S_VR_STAR, V);\n    bool passed = equal_svd_product(A, U, S_VR_STAR, V, threshold);\n    if (!passed) {\n        BOOST_FAIL(\"Failure in [MC, MR] case\");\n    }\n\n}\n\n\ntemplate<El::Distribution ColDist>\nvoid check(El::DistMatrix<double, ColDist, El::STAR>& A,\n    double threshold=1e-4) {\n    El::DistMatrix<double, ColDist, El::STAR> A_CD_STAR, U_CD_STAR;\n    El::DistMatrix<double, El::STAR, El::STAR> S_STAR_STAR, V_STAR_STAR;\n    A_CD_STAR = A;\n    U_CD_STAR = A_CD_STAR;\n    El::SVD(U_CD_STAR, U_CD_STAR, S_STAR_STAR, V_STAR_STAR);\n    bool passed = equal_svd_product(A_CD_STAR,\n        U_CD_STAR, S_STAR_STAR, V_STAR_STAR, threshold);\n    if (!passed) {\n        BOOST_FAIL(\"Failure in [VC/VR, *] case\");\n    }\n}\n\ntemplate<El::Distribution RowDist>\nvoid check(El::DistMatrix<double, El::STAR, RowDist>& A,\n    double threshold=1e-4) {\n    El::DistMatrix<double, RowDist, El::STAR> V_RD_STAR;\n    El::DistMatrix<double, El::STAR, El::STAR> S_STAR_STAR, U_STAR_STAR;\n    U_STAR_STAR = A;\n    El::SVD(U_STAR_STAR, U_STAR_STAR, S_STAR_STAR, V_RD_STAR);\n    bool passed = equal_svd_product(A,\n        U_STAR_STAR, S_STAR_STAR, V_RD_STAR, threshold);\n    if (!passed) {\n        BOOST_FAIL(\"Failure in [*, VC/VR] case\");\n    }\n\n}\n\n#endif // SKYLARK_HAVE_BOOST\n\n} }\n\n#endif // TEST_UTILS_HPP\n", "meta": {"hexsha": "38976b9c502defee06336709f4b3b808b757823a", "size": 4886, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/unit/test_utils.hpp", "max_stars_repo_name": "xdata-skylark/libskylark", "max_stars_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "tests/unit/test_utils.hpp", "max_issues_repo_name": "xdata-skylark/libskylark", "max_issues_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "tests/unit/test_utils.hpp", "max_forks_repo_name": "xdata-skylark/libskylark", "max_forks_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T07:30:35.000Z", "avg_line_length": 30.7295597484, "max_line_length": 78, "alphanum_fraction": 0.6479738027, "num_tokens": 1381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5294456167837056}}
{"text": "// #include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n// #include <boost/multiprecision/float128.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/filesystem/fstream.hpp>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n\n\n\nint main()\n{\n  // typedef boost::multiprecision::cpp_dec_float_50;\n  using namespace boost::filesystem;\n  // using namespace boost::lambda;\n  using namespace boost::multiprecision;\n  using boost::multiprecision::cpp_dec_float_50;\n  unsigned int n_roots = 10000U;\n  std::vector<cpp_dec_float_50> roots;\n  boost::math::cyl_bessel_j_zero(-0.25, 1, n_roots, std::back_inserter(roots));\n  \n  path p{\"bessel_zeros_short.txt\"};\n  ofstream ofs{p};\n  ofs.precision(std::numeric_limits<cpp_dec_float_50>::digits10);\n  std::copy(roots.begin(),\n            roots.end(),\n            std::ostream_iterator<cpp_dec_float_50>(ofs, \"\\n\"));\n} \n", "meta": {"hexsha": "6338aa44e6802a734390dd380c4237722d13ac3b", "size": 963, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bessel_zeros/bessel_zeros.cpp", "max_stars_repo_name": "GrzegorzMika/Towards-adaptivity-via-a-new-discrepancy-principle-for-Poisson-inverse-problems", "max_stars_repo_head_hexsha": "13f62a5fa2a446c48796e12536e61125302d638d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bessel_zeros/bessel_zeros.cpp", "max_issues_repo_name": "GrzegorzMika/Towards-adaptivity-via-a-new-discrepancy-principle-for-Poisson-inverse-problems", "max_issues_repo_head_hexsha": "13f62a5fa2a446c48796e12536e61125302d638d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bessel_zeros/bessel_zeros.cpp", "max_forks_repo_name": "GrzegorzMika/Towards-adaptivity-via-a-new-discrepancy-principle-for-Poisson-inverse-problems", "max_forks_repo_head_hexsha": "13f62a5fa2a446c48796e12536e61125302d638d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-23T19:15:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T19:15:01.000Z", "avg_line_length": 31.064516129, "max_line_length": 79, "alphanum_fraction": 0.733125649, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5294393179415304}}
{"text": "#include \"catch.hpp\"\n\n#include <chrono>\n#include <fstream>\n\n#include <boost/filesystem.hpp>\n#include <boost/scope_exit.hpp>\n\n#include \"tntn/File.h\"\n\n#include \"tntn/geometrix.h\"\n#include \"tntn/Points2Mesh.h\"\n\n#include \"tntn/MeshIO.h\"\n\n#include \"delaunator_cpp/Delaunator.h\"\n\n// data\n#include \"vertex_points.h\"\n#include \"triangle_indices.h\"\n\nnamespace tntn {\nnamespace unittests {\n\nTEST_CASE(\"delaunator test\", \"[tntn]\")\n{\n\n    // super simple - one triangle\n    // points in anti-clockwise order\n\n    std::vector<double> ps_simple{0, 0, 1, 1, 1, 0};\n\n    delaunator_cpp::Delaunator dn;\n    if(!dn.triangulate(ps_simple))\n    {\n        CHECK(false);\n    }\n\n    CHECK(dn.triangles.size() == 3);\n\n    for(int i = 0; i < dn.triangles.size(); i += 3)\n    {\n        for(int j = 0; j < 3; j++)\n        {\n            int pi = dn.triangles[j];\n            CHECK(pi == j);\n        }\n    }\n\n    std::vector<double> vertex_list_big;\n    init_vertex_list(vertex_list_big);\n\n    //delaunator_cpp::Delaunator dn_big;\n    if(!dn.triangulate(vertex_list_big))\n    {\n        CHECK(false);\n    }\n\n    std::vector<int> tri_big;\n    init_triangle_list(tri_big);\n\n    CHECK(dn.triangles.size() == tri_big.size());\n    for(int i = 0; i < dn.triangles.size(); i++)\n    {\n        CHECK(dn.triangles[i] == tri_big[i]);\n    }\n}\n\nTEST_CASE(\"simple delaunay\", \"[tntn]\")\n{\n    std::vector<Vertex> vlist;\n\n    Vertex v;\n\n    // A (i = 0)\n    v.x = 0;\n    v.y = 0;\n    v.z = 0;\n\n    vlist.push_back(v);\n\n    // B  (i = 1)\n    v.x = 100;\n    v.y = 0;\n    v.z = 0;\n\n    vlist.push_back(v);\n\n    // C  (i = 2)\n    v.x = 100;\n    v.y = 100;\n    v.z = 0;\n\n    vlist.push_back(v);\n\n    // D  (i = 3)\n    v.x = 0;\n    v.y = 100;\n    v.z = 0;\n\n    vlist.push_back(v);\n\n    std::vector<Face> faces;\n    generate_delaunay_faces(vlist, faces);\n\n    CHECK(faces.size() == 2);\n\n    int h = 10;\n    int w = 20;\n\n    vlist.clear();\n    for(int r = 0; r < h; r++)\n    {\n        for(int c = 0; c < w; c++)\n        {\n            Vertex vvv;\n            vvv.x = c;\n            vvv.y = r;\n\n            float dx = c - w / 2;\n            float dy = r - h / 2;\n            if(dx * dx + dy * dy < 30 * 30)\n            {\n                vvv.z = 20;\n            }\n            else\n                vvv.z = 0;\n\n            vlist.push_back(vvv);\n        }\n    }\n\n    faces.clear();\n\n    std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n    generate_delaunay_faces(vlist, faces);\n    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n\n    CHECK(faces.size() == (w - 1) * (h - 1) * 2);\n\n    //std::cout <<\"delaunay on \" << vlist.size()/1000.0 << \"k vertices in \" << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() / 1000.0 << \"seconds\" << std::endl;\n}\n\n} //namespace unittests\n} //namespace tntn\n", "meta": {"hexsha": "b68a4459d1ff3a104d6b297d44ed0227def44246", "size": 2818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/Delaunay_tests.cpp", "max_stars_repo_name": "znly/tin-terrain", "max_stars_repo_head_hexsha": "59b7ac78cc95651e8d3b0555f153afe0bf86945c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-25T08:49:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T19:47:06.000Z", "max_issues_repo_path": "test/src/Delaunay_tests.cpp", "max_issues_repo_name": "sotex/tin-terrain", "max_issues_repo_head_hexsha": "dcf959e1dd71fbcb16dad58bfa6bb7db1999267f", "max_issues_repo_licenses": ["MIT"], "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/Delaunay_tests.cpp", "max_forks_repo_name": "sotex/tin-terrain", "max_forks_repo_head_hexsha": "dcf959e1dd71fbcb16dad58bfa6bb7db1999267f", "max_forks_repo_licenses": ["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.301369863, "max_line_length": 189, "alphanum_fraction": 0.5248403123, "num_tokens": 894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5294393062137783}}
{"text": "#include \"Camera.h\"\n\n#include <Eigen/Core>\n#include <iostream>\n\n  Camera::Camera(float width, float height, float fovY)\n:orientation( Eigen::Quaternionf::Identity()), \n  position(0,0,0),\n  projectionIsUpdate(false),\n  viewIsUpdate(false)\n{\n   this->fovY = fovY;\n   this->width = width;\n   this->height = height;\n   zFar = 50000.f;\n   zNear = 0.1f;\n}\n\nEigen::Vector3f Camera::getPosition()\n{\n  return position;\n}\n\nEigen::Affine3f Camera::getView()\n{\n  updateViewMatrix();\n  return view;\n}\n\nEigen::Matrix4f Camera::getProjection()\n{\n  updateProjectionMatrix();\n  return projection;\n}\n\nvoid Camera::setPosition(Eigen::Vector3f pos)\n{\n  viewIsUpdate = false;\n  position = pos;\n}\n\nvoid Camera::move(float distance, Eigen::Vector3f axis)\n{\n  viewIsUpdate = false;\n  axis.normalize();\n  position += orientation.toRotationMatrix() * axis * distance;\n}\n\nvoid Camera::moveFoward(float distance)\n{\n  move(distance,Eigen::Vector3f(0,0,1));\n}\n\nvoid Camera::moveVertical(float distance)\n{\n\n  move(distance,Eigen::Vector3f(0,1,0));\n}\n\nvoid Camera::moveHorizontal(float distance)\n{\n  move(distance,Eigen::Vector3f(1,0,0));\n}\n\nvoid Camera::rotate(float theta, Eigen::Vector3f axis)\n{\n  viewIsUpdate = false;\n  Eigen::AngleAxisf angleAxis(theta, axis);\n  Eigen::Quaternionf rot(angleAxis);\n  rot.normalize();\n  orientation = orientation * rot;\n  orientation.normalize();\n}\n\nvoid Camera::roll(float theta)\n{\n  rotate(theta,Eigen::Vector3f(0,0,1));\n}\n\nvoid Camera::pitch(float theta)\n{\n  rotate(theta,Eigen::Vector3f(1,0,0));\n}\n\nvoid Camera::yaw(float theta)\n{\n  rotate(theta,Eigen::Vector3f(0,1,0));\n}\n\nvoid Camera::updateViewMatrix()\n{\n  if(!viewIsUpdate)\n  {\n    view.linear() = orientation.conjugate().toRotationMatrix();\n    view.translation() = - (view.linear() * position);\n    viewIsUpdate = true;\n  }\n}\n\nvoid Camera::updateProjectionMatrix()\n{\n  if(!projectionIsUpdate)\n  {\n    projection.setIdentity();\n\n    float yScale = 1./tan(fovY*0.5);\n    float xScale = yScale * height / width;\n    projection(0,0) = xScale;\n    projection(1,1) = yScale;\n    projection(2,2) = -(zFar+zNear)/(zFar-zNear);\n    projection(3,2) = -1;\n    projection(2,3) = -2*zNear*zFar/(zFar-zNear);\n    projection(3,3) = 0;\n\n    projectionIsUpdate = true;\n  }\n}\n\n", "meta": {"hexsha": "43ad433ad008f4ba69788b9956cd2507e439280f", "size": 2225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/camera/Camera.cpp", "max_stars_repo_name": "Daepso/lambdaGalaxy", "max_stars_repo_head_hexsha": "ea693e52ea86808f53729783a4092f1f315c1d50", "max_stars_repo_licenses": ["Zlib"], "max_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/Camera.cpp", "max_issues_repo_name": "Daepso/lambdaGalaxy", "max_issues_repo_head_hexsha": "ea693e52ea86808f53729783a4092f1f315c1d50", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/camera/Camera.cpp", "max_forks_repo_name": "Daepso/lambdaGalaxy", "max_forks_repo_head_hexsha": "ea693e52ea86808f53729783a4092f1f315c1d50", "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": 18.6974789916, "max_line_length": 63, "alphanum_fraction": 0.6773033708, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5294393062137782}}
{"text": "#include <algorithm>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <iostream>\n#include <string>\n\nenum {\n    DIR_N = 1,\n    DIR_S,\n    DIR_NW,\n    DIR_NE,\n    DIR_SW,\n    DIR_SE\n};\n\nstatic int toDir(const std::string& dir) {\n    if (dir == \"n\") {\n        return DIR_N;\n    } else if (dir == \"s\") {\n        return DIR_S;\n    } else if (dir == \"nw\") {\n        return DIR_NW;\n    } else if (dir == \"ne\") {\n        return DIR_NE;\n    } else if (dir == \"sw\") {\n        return DIR_SW;\n    } else if (dir == \"se\") {\n        return DIR_SE;\n    } else {\n        std::cerr << \"WRONG MOVE!\\n\";\n        exit(1);\n    }\n};\n\nstruct Position\n{\n    int x = 0;\n    int y = 0;\n    int z = 0;\n    int dist = 0;\n\n    void move(const int dir)\n    {\n        if (dir == DIR_N) {\n            y += 1;\n            z -= 1;\n        } else if (dir == DIR_S) {\n            y -= 1;\n            z += 1;\n        } else if (dir == DIR_NW) {\n            x -= 1;\n            y += 1;\n        } else if (dir == DIR_NE) {\n            x += 1;\n            z -= 1;\n        } else if (dir == DIR_SW) {\n            x -= 1;\n            z += 1;\n        } else if (dir == DIR_SE) {\n            x += 1;\n            y -= 1;\n        }\n        dist = (std::abs(x)+std::abs(y)+std::abs(z)) / 2;\n    }\n};\n\n\nint main()\n{\n    std::string line;\n    std::getline(std::cin, line);\n\n    std::vector<float> path;\n    Position child;\n    {\n        std::vector<std::string> words;\n        boost::algorithm::split(\n            words, line, boost::is_any_of(\", \"), boost::algorithm::token_compress_on);\n        for (const auto& dir : words) {\n            child.move(toDir(dir));\n            path.push_back(child.dist);\n        }\n    }\n\n    std::cout << \"child dist: \" << *path.rbegin() << \"\\n\";\n    std::sort(path.begin(), path.end(), std::greater<int>());\n    std::cout << \"max dist: \" << path[0] << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "cb7492c02c55c653a6a2fd0714830e0be029a28e", "size": 1918, "ext": "cc", "lang": "C++", "max_stars_repo_path": "puzzle_11_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_11_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_11_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": 21.0769230769, "max_line_length": 86, "alphanum_fraction": 0.4457768509, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5294392956551255}}
{"text": "#include <boost/gil.hpp>\n#include <boost/gil/extension/io/png.hpp>\n#include <boost/gil/image_processing/histogram_equalization.hpp>\n\nusing namespace boost::gil;\n\nint main()\n{\n    gray8_image_t img;\n    \n    read_image(\"test_adaptive.png\", img, png_tag{});\n    gray8_image_t img_out(img.dimensions());\n\n    // Consider changing image to independent color space, e.g. cmyk\n    boost::gil::histogram_equalization(view(img),view(img_out));\n\n    write_view(\"histogram_gray_equalized.png\", view(img_out), png_tag{});\n\n    return 0;\n}\n", "meta": {"hexsha": "e076f9f74770a85a3af6adee317ce158944d148b", "size": 528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/histogram_equalization.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": "example/histogram_equalization.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": "example/histogram_equalization.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": 25.1428571429, "max_line_length": 73, "alphanum_fraction": 0.7196969697, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.5294392903757987}}
{"text": "#ifndef CPG_HPP\n#define CPG_HPP\n\n#include <set>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nnamespace raisim\n{\n\n    template<typename T>\n    class CPG\n    {\n    public:\n        CPG()\n        {\n            // 0: WALK; 1: TROT; 2: PACE; 3: GALLOP; -1: STAND\n            OFFSET[0] = {0.0, M_PI, M_PI * 0.5, M_PI * 1.5};\n            OFFSET[1] = {0.0, M_PI, M_PI, 0.0};\n            OFFSET[2] = {0.0, M_PI, 0.0, M_PI};\n            OFFSET[3] = {0.0, 0.0, M_PI, M_PI};\n\n            OFFSET_THREE = {0.0, 2.0 / 3.0 * M_PI, 4.0 / 3.0 * M_PI, 0.0};\n\n            q_ << 0.0, 1.0, 1.0, 0.0, 0.0, -1.0, -1.0, 0.0;\n\n            reset_gait_four_leg(gait_);\n        }\n\n        inline void update_r_mat_four_leg()\n        {\n            r_mat_.setZero();\n\n            for (int i = 0; i < 4; ++i)\n            {\n                for (int j = 0; j < 4; ++j)\n                {\n                    T theta = offset_[j] - offset_[i];\n                    r_mat_(2 * j, 2 * i) = std::cos(theta);\n                    r_mat_(2 * j + 1, 2 * i + 1) = std::cos(theta);\n                    r_mat_(2 * j, 2 * i + 1) = -std::sin(theta);\n                    r_mat_(2 * j + 1, 2 * i) = std::sin(theta);\n                }\n            }\n        }\n\n        inline void update_r_mat_four_leg_transition(int init_gait, int target_gait)\n        {\n            r_mat_.setZero();\n            update_phase();\n\n            for (int i = 0; i < 4; ++i)\n            {\n                for (int j = 0; j < 4; ++j)\n                {\n                    T target_theta = OFFSET[target_gait][j] - OFFSET[target_gait][i];\n                    T init_theta = OFFSET[init_gait][j] - OFFSET[init_gait][i];\n                    int control_variable = get_control_variable(init_gait, target_gait);\n                    \n                    // T theta = offset_[j] - offset_[i];\n                    T theta = target_theta + (target_theta - init_theta) / (OFFSET[target_gait][control_variable] - OFFSET[init_gait][control_variable]) * (phase_[control_variable] - OFFSET[target_gait][control_variable]) * 0.5;\n\n                    r_mat_(2 * j, 2 * i) = std::cos(theta);\n                    r_mat_(2 * j + 1, 2 * i + 1) = std::cos(theta);\n                    r_mat_(2 * j, 2 * i + 1) = -std::sin(theta);\n                    r_mat_(2 * j + 1, 2 * i) = std::sin(theta);\n\n                    // if (isnan(theta))\n                    // {\n                    //     std::cout << \"theta is nan!!!\" << std::endl\n                    //                 << \"i: \" << i << \" j: \" << j << std::endl\n                    //                 << \"target_theta: \" << target_theta << \" init_theta: \" << init_theta << std::endl\n                    //                 << \"control variable: \" << control_variable << std::endl\n                    //                 << \"delta control\" << OFFSET[target_gait][control_variable] - OFFSET[init_gait][control_variable] << std::endl\n                    //                 << \"target gait: \" << target_gait << \" init_gait: \" << init_gait << std::endl;\n                    // }\n                }\n            }\n        }\n\n        inline void update_r_mat_three_leg()\n        {\n            r_mat_.setZero();\n            int ii = 0;\n            int jj = 0;\n\n            for (int i = 0; i < 4; ++i)\n            {\n                if (i == hold_leg_)\n                {\n                    continue;\n                }\n                \n                ii = i > hold_leg_ ? i - 1 : i;\n\n                for (int j = 0; j < 4; ++j)\n                {\n                    if (j == hold_leg_)\n                    {\n                        continue;\n                    }\n    \n                    jj = j > hold_leg_ ? j - 1 : j;\n\n                    T theta = offset_[jj] - offset_[ii];\n                    r_mat_(2 * j, 2 * i) = std::cos(theta);\n                    r_mat_(2 * j + 1, 2 * i + 1) = std::cos(theta);\n                    r_mat_(2 * j, 2 * i + 1) = -std::sin(theta);\n                    r_mat_(2 * j + 1, 2 * i) = std::sin(theta);\n                }\n            }\n        }\n\n        inline int get_control_variable(int init_gait, int target_gait)\n        {\n            int p = 0;\n            for (int i = 0; i < 4; ++i)\n            {\n                if (fabs(OFFSET[target_gait][i] - OFFSET[init_gait][i]) > 0.1)\n                {\n                    p = i;\n                    break;\n                }\n            }\n            return p;\n        }\n\n        inline void update_phase()\n        {\n            for (int i = 0; i < 4; ++i)\n            {\n                phase_[i] = std::atan2(q_[2 * i + 1], q_[2 * i]);\n            }\n            for (int i = 1; i < 4; ++i)\n            {\n                phase_[i] -= phase_[0];\n                if (phase_[i] < 0)\n                {\n                    phase_[i] += M_PI * 2.0;\n                }\n            }\n            phase_[0] = 0.0;\n        }\n\n        Eigen::Matrix<T, Eigen::Dynamic, 1> get_raw_phase()\n        {\n            phase_raw_.setZero();\n            for (int i = 0; i < 4; ++i)\n            {\n                phase_raw_[i] = std::atan2(q_[2 * i + 1], q_[2 * i]);\n            }\n            return phase_raw_;\n        }\n\n        Eigen::Matrix<T, Eigen::Dynamic, 1> get_omega()\n        {\n            omega_.setZero();\n            for (int i = 0; i < 4; ++i)\n            {\n                omega_[i] = -M_PI / t_ * (1.0 / beta_ / (1.0 + std::exp(-b_ * q_(2 * i + 1))) + 1.0 / (1.0 - beta_) / (1.0 + std::exp(b_ * q_(2 * i + 1))));\n                // if (omega_[i] < -3.15*4)\n                // {\n                //     std::cout << \"omega: \" << omega_[i] << \"; i: \" << i << \"; t_: \" << t_ << \"; beta_: \" << beta_ << \"; q: \" << q_(2*i+1) << \"; b: \" << b_ << \"gait: \" << gait_ << std::endl;\n                // }\n\n                if (gait_ < 0)\n                {\n                    omega_[i] = 0.0;\n                }\n            }\n            return omega_;\n        }\n\n        inline void reset()\n        {\n            q_ << 0.0, 1.0, 1.0, 0.0, 0.0, -1.0, -1.0, 0.0;\n            hold_leg_ = -1;\n            reset_gait_four_leg(-1);\n        }\n\n        inline void reset_gait_four_leg(int gait)\n        {\n            // use this function only for reset\n            if (gait >= 0)\n            {\n                gait_ = gait;\n                previous_gait_ = gait;\n                target_gait_ = gait;\n\n                beta_ = BETA[gait_];\n                delta_ = DELTA[gait_];\n                t_ = TIME[gait_];\n                offset_ = OFFSET[gait_];\n                \n                phase_ = offset_;\n\n                for (int i = 0; i < 4; ++i)\n                {\n                    q_[2 * i] = std::cos(phase_[i]);\n                    q_[2 * i + 1] = std::sin(phase_[i]);\n                }\n\n                update_r_mat_four_leg();\n            }\n            else\n            {\n                gait_ = gait;\n                previous_gait_ = gait;\n                target_gait_ = gait;\n\n                beta_ = BETA[gait_];\n                delta_ = DELTA[gait_];\n                t_ = TIME[gait_];\n                offset_ = OFFSET[gait_];\n\n                // q_ << -1.0, 0.0, -0.5, 0.866, 0.5, 0.866, 1.0, 0.0;\n                // q_dot_.setZero();\n                // phase_raw_ << -M_PI, -M_PI / 3.0 * 2.0, M_PI / 3.0, 0.0;\n                // phase_ = {0.0, M_PI / 3.0, M_PI / 3.0 * 2.0, M_PI};\n                q_ << 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0;\n                q_dot_.setZero();\n                phase_raw_ << M_PI / 2.0, M_PI / 2.0, M_PI / 2.0, M_PI / 2.0;\n                phase_ = {0.0, 0.0, 0.0, 0.0};\n            }\n        }\n\n        inline void reset_gait_three_leg(int gait)\n        {\n            gait_ = gait;\n            previous_gait_ = gait;\n            target_gait_ = gait;\n\n            beta_ = BETA_THREE;\n            delta_ = DELTA_THREE;\n            t_ = TIME_THREE;\n            offset_ = OFFSET_THREE;\n\n            if (gait >= 0)\n            {   \n                phase_ = offset_;\n\n                int ii = 0;\n\n                for (int i = 0; i < 4; ++i)\n                {\n                    if (i == hold_leg_)\n                    {\n                        q_[2 * i] = 0.0;\n                        q_[2 * i + 1] = -1.0;\n                        continue;\n                    }\n                    ii = i > hold_leg_ ? i - 1 : i;\n                    q_[2 * i] = std::cos(phase_[ii]);\n                    q_[2 * i + 1] = std::sin(phase_[ii]);\n                }\n\n                update_r_mat_three_leg();\n            }\n            else\n            {\n                q_ << 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0;\n                q_[2 * hold_leg_ + 1] = -1.0;\n                q_dot_.setZero();\n                phase_raw_ << M_PI / 2.0, M_PI / 2.0, M_PI / 2.0, M_PI / 2.0;\n                phase_raw_[hold_leg_] = - M_PI / 2.0;\n                phase_ = {0.0, 0.0, 0.0, 0.0};\n                phase_[hold_leg_] = -0.5;\n            }\n        }\n\n        inline void change_gait(int gait)\n        {\n            if (hold_leg_ < 0)\n            {\n                if (previous_gait_ < 0 || gait_ < 0 || gait < 0)\n                {\n                    reset_gait_four_leg(gait);\n                }\n                else\n                {\n                    previous_gait_ = target_gait_;\n                    target_gait_ = gait;\n                    gait_ = target_gait_;\n\n                    beta_ = BETA[gait_];\n                    delta_ = DELTA[gait_];\n                    t_ = TIME[gait_];\n                    offset_ = OFFSET[gait_];\n\n                    update_r_mat_four_leg();\n                }\n            }\n            else\n            {\n                gait = gait > 0 ? 0 : gait;\n                if (previous_gait_ < 0 || gait_ < 0 || gait < 0)\n                {\n                    reset_gait_three_leg(gait);\n                }\n                else\n                {\n                    previous_gait_ = target_gait_;\n                    target_gait_ = gait;\n                    gait_ = target_gait_;\n\n                    beta_ = BETA_THREE;\n                    delta_ = DELTA_THREE;\n                    t_ = TIME_THREE;\n                    offset_ = OFFSET_THREE;\n\n                    update_r_mat_three_leg();\n                }\n            }\n        }\n\n        inline void three_leg_mode(int hold_leg)\n        {\n            hold_leg_ = hold_leg;\n\n            // if (hold_leg_ >= 0)\n            // {\n            //     update_r_mat_three_leg(hold_leg_);\n            // }\n            // else\n            // {\n            //     update_r_mat_four_leg();\n            // }\n        }\n\n        inline void step_()\n        {\n            for (int i = 0; i < 4; ++i)\n            {\n                r_square_[i] = q_[2 * i] * q_[2 * i] + q_[2 * i + 1] * q_[2 * i + 1];\n            }\n\n            f_mat_.setZero();\n            for (int i = 0; i < 4; ++i)\n            {\n                f_mat_(2 * i, 2 * i) = alpha_ * (mu_ - r_square_[i]);\n                f_mat_(2 * i + 1, 2 * i + 1) = gamma_ * (mu_ - r_square_[i]);\n                T omega = M_PI / t_ * (1.0 / beta_ / (1.0 + std::exp(-b_ * q_(2 * i + 1))) + 1.0 / (1.0 - beta_) / (1.0 + std::exp(b_ * q_(2 * i + 1))));\n                f_mat_(2 * i, 2 * i + 1) = omega;\n                f_mat_(2 * i + 1, 2 * i) = -omega;\n            }\n\n            q_dot_ = f_mat_ * q_ + r_mat_ * q_ * delta_;\n\n            if (hold_leg_ >= 0)\n            {\n                // for (int i = 0; i < 4; ++i)\n                // {\n                //     f_mat_(2 * i, 2 * i) = alpha_ * (mu_ - r_square_[i]);\n                //     f_mat_(2 * i + 1, 2 * i + 1) = gamma_ * (mu_ - r_square_[i]);\n                //     T omega = M_PI / TIME_THREE * (1.0 / BETA_THREE / (1.0 + std::exp(-b_ * q_(2 * i + 1))) + 1.0 / (1.0 - BETA_THREE) / (1.0 + std::exp(b_ * q_(2 * i + 1))));\n                //     f_mat_(2 * i, 2 * i + 1) = omega;\n                //     f_mat_(2 * i + 1, 2 * i) = -omega;\n                // }\n                // q_dot_ = f_mat_ * q_ + r_mat_ * q_ * delta_;\n\n                auto vec_dis = Eigen::Matrix<T, 2, 1>(0.0 - q_[2 * hold_leg_], -1.0 - q_[2 * hold_leg_ + 1]);\n                T dis = vec_dis.norm();\n                dis = dis > 0.4 ? 1.0 : dis * dis / 0.16;\n\n                q_dot_(2 * hold_leg_) *= dis;\n                q_dot_(2 * hold_leg_ + 1) *= dis;\n                q_dot_(2 * hold_leg_) += vec_dis(0);\n                q_dot_(2 * hold_leg_ + 1) += vec_dis(1);\n            }\n\n            q_ = q_ + q_dot_ * dt_;\n        }\n\n        inline void step()\n        {\n            if (hold_leg_ < 0)\n            {\n                if (gait_ != previous_gait_)\n                {\n                    update_r_mat_four_leg_transition(previous_gait_, target_gait_);\n\n                    int control_variable = get_control_variable(previous_gait_, target_gait_);\n                    // if (fabs(phase_[control_variable] - OFFSET[target_gait_][control_variable]) < 0.1 * phase_[control_variable])\n                    if (fabs(phase_[control_variable] - OFFSET[target_gait_][control_variable]) < 0.1 * M_PI)\n                    {\n                        previous_gait_ = gait_;\n                        update_r_mat_four_leg();\n                    }\n                }\n            }\n\n            if (gait_ < 0)\n            {\n                ;\n            }\n            else\n            {\n                step_();\n            }\n        }\n\n        bool get_transition_status()\n        {\n            if (gait_ != previous_gait_)\n            {\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        Eigen::Matrix<T, Eigen::Dynamic, 1> get_status()\n        {\n            return q_;\n        }\n\n        Eigen::Matrix<T, Eigen::Dynamic, 1> get_velocity()\n        {\n            return q_dot_;\n        }\n\n        T get_stance_time()\n        {\n            if (hold_leg_ < 0)\n            {\n                return t_ * beta_;\n            }\n            else\n            {\n                return TIME_THREE * BETA_THREE;\n            }\n        }\n\n        int get_gait_index()\n        {\n            return gait_;\n        }\n\n        int get_hold_leg()\n        {\n            return hold_leg_;\n        }\n\n    // private:\n        T mu_ = 1.0;\n        T alpha_ = 50.0;\n        T gamma_ = 50.0;\n        T b_ = 50.0;\n        T dt_ = 0.01;\n\n        std::array<T, 4> BETA = {0.75, 0.5, 0.5, 0.4};\n        std::array<T, 4> DELTA = {1.0, 1.0, 1.0, 1.0};\n        std::array<T, 4> TIME = {0.6, 0.5, 0.5, 0.3};\n        std::array<std::array<T, 4>, 4> OFFSET;\n\n        T BETA_THREE = 2.0 / 3.0;\n        T DELTA_THREE = 1.0;\n        T TIME_THREE = 0.45;\n        std::array<T, 4> OFFSET_THREE;\n\n        int gait_ = -1;\n        int previous_gait_ = -1;\n        int target_gait_ = -1;\n\n        T beta_, delta_, t_;\n        std::array<T, 4> offset_;\n        std::array<T, 4> r_square_;\n        std::array<T, 4> phase_; // 0 to 2 * pi\n\n        Eigen::Matrix<T, 8, 1> q_;\n        Eigen::Matrix<T, 8, 1> q_dot_;\n        Eigen::Matrix<T, 8, 8> r_mat_;\n        Eigen::Matrix<T, 8, 8> f_mat_;\n        Eigen::Matrix<T, 4, 1> phase_raw_; // -pi to +pi\n        Eigen::Matrix<T, 4, 1> omega_;\n        \n        int hold_leg_ = -1;\n    };\n\n} // namespace raisim\n\n#endif", "meta": {"hexsha": "22776fe0b0e2798a77975b19d3b7716f786b6e36", "size": 15162, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/CPG.hpp", "max_stars_repo_name": "ZJU-XMech/PhaseGuidedControl", "max_stars_repo_head_hexsha": "f8a35ae8e1f903e948710b50681d2aa59046150e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T07:37:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:45:42.000Z", "max_issues_repo_path": "src/CPG.hpp", "max_issues_repo_name": "ZJU-XMech/PhaseGuidedControl", "max_issues_repo_head_hexsha": "f8a35ae8e1f903e948710b50681d2aa59046150e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CPG.hpp", "max_forks_repo_name": "ZJU-XMech/PhaseGuidedControl", "max_forks_repo_head_hexsha": "f8a35ae8e1f903e948710b50681d2aa59046150e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-21T09:33:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T09:33:25.000Z", "avg_line_length": 31.2618556701, "max_line_length": 228, "alphanum_fraction": 0.3645956998, "num_tokens": 4418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5294346500766254}}
{"text": "#pragma once\n\n#include <Eigen/StdVector>\n#include <sophus/se2.hpp>\n#include <sophus/so2.hpp>\n\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::Vector2d)\n\nusing Scalar = double;\nusing so2    = Sophus::SO2<Scalar>;\nusing se2    = Sophus::SE2<Scalar>;\n\ntemplate <int rows, int cols>\nusing Mat = Eigen::Matrix<double, rows, cols>;\n\ntemplate <int cols>\nusing Vec = Eigen::Matrix<double, 1, cols>;", "meta": {"hexsha": "71a44aab6f7c2207225ff08b9a877e5f3edbda2e", "size": 388, "ext": "hh", "lang": "C++", "max_stars_repo_path": "raytracing/types.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/types.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/types.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": 22.8235294118, "max_line_length": 55, "alphanum_fraction": 0.7293814433, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5293811713188177}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Hidekazu Ikeno\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\n * THE SOFTWARE.\n */\n\n///\n/// \\file approx_power.hpp\n/// \\brief Find exponential sum approximations of power function\n///\n#ifndef MXPFIT_APPROX_POWER_HPP\n#define MXPFIT_APPROX_POWER_HPP\n\n#include <algorithm>\n#include <iosfwd>\n#include <iterator>\n#include <stdexcept>\n\n#include <boost/math/special_functions/gamma.hpp>\n\n#include <mxpfit/exponential_sum.hpp>\n#include <mxpfit/modified_prony_reduction.hpp>\n\nnamespace mxpfit\n{\n\nnamespace detail\n{\n\n/// \\internal\n///\n/// ### newton\n///\n/// Solve an equation \\f$f(x)=0\\f$ by Newton's method\n///\n/// \\tparam T value type for function argument \\f$x\\f$\n/// \\tparam NewtonFunctor a unwary function that takes \\f$x\\f$ as an argument\n/// and\n///         returns pair of function value \\f$f(x)\\f$ and its first derivative\n///         \\f$f^{\\prime}(x).\\f$\n///\n/// \\param[in] guess     initial guess of the solution\n/// \\param[in] tol       tolerance for convergence\n/// \\param[in] fn        an instance of `NewtonFunctor`\n/// \\param[in] max_iter  maximum number of iterations\n///\ntemplate <typename T, typename NewtonFunctor>\nT newton(T guess, T tol, NewtonFunctor fn, std::size_t max_iter = 1000)\n{\n    using std::abs;\n    auto counter = max_iter;\n    auto x       = guess;\n\n    while (counter--)\n    {\n        // We assume df(x) never to be too small.\n        const auto f_and_df = fn(x);\n        const auto delta    = std::get<0>(f_and_df) / std::get<1>(f_and_df);\n        // std::cout << \"(newton): \" << x << '\\t'     // t\n        //           << std::get<0>(f_and_df) << '\\t' // f(t)\n        //           << std::get<1>(f_and_df) << '\\t' // f'(t)\n        //           << delta << '\\n';\n        x -= delta;\n        if (abs(delta) < abs(x) * tol)\n        {\n            break;\n        }\n    }\n\n    return x;\n}\n\n} // namespace detail\n\n///\n/// ### ApproxPowerFunction\n///\n/// \\brief Compute parameters for the exponential sum approximation of power\n/// funciton, \\f$r^{-\\beta}\\,(\\beta>0).\\f$\n///\n/// \\tparam T Real scalar type for the parameters of the exponential sum\n///\n/// This funtion computes parameters to approximate the power functions\n/// \\f$r^{-\\beta}\\,(\\beta>0)\\f$ with a linear combination of exponential\n/// functions,\n///\n/// \\f[\n///   \\|r^{-\\beta}-sum_{m=1}^{M} w_{m} e^{-a_{m} x} \\| < r^{-\\beta}\\epsilon\n/// \\f]\n///\n/// for any given accuracy \\f$\\epsilon > 0\\f$ and distance to singularity\n/// \\f$\\delta>0\\f$ real axis `(x)`.\n///\n/// The multi-exponential function is obtained by discretize the integral\n/// representation of spherical Bessel function\n///\n/// #### References\n///\n/// 1. G. Beylkin and L. Monz\\'{o}n, \"Approximation by exponential sums\n///    revisited\", Appl. Comput. Harmon. Anal. 28 (2010) 131-149.\n///    [DOI: https://doi.org/10.1016/j.acha.2009.08.011]\n/// 2. W. McLean, \"Exponential sum approximations for \\f$t^{-\\beta}\\f$\",\n///    arXiv:1606.00123 [math]\n///\ntemplate <typename T>\nclass ApproxPowerFunction\n{\npublic:\n    using Index      = Eigen::Index;\n    using Real       = T;\n    using ResultType = ExponentialSum<T, T>;\n\n    ApproxPowerFunction()                           = default;\n    ApproxPowerFunction(const ApproxPowerFunction&) = default;\n    ApproxPowerFunction(ApproxPowerFunction&&)      = default;\n\n    ///\n    /// Create an instance with arguments.\n    ///\n    /// \\param[in] beta the power factor \\f$\\beta > 0\\f$\n    /// \\param[in] eps  the target accuracy of the exponential sum approximation\n    /// \\param[in] rmin the lower bound of the interval\n    /// \\param[in] rmax the upper bound of the interval\n    /// \\pre `beta > 0 && eps > 0 && rmin > 0 && rmax > rmin`\n    ///\n    ApproxPowerFunction(Real beta, Real eps, Real rmin, Real rmax)\n        : m_beta(beta), m_eps(eps), m_rmin(rmin), m_rmax(rmax)\n    {\n        check_args(beta, eps, rmin, rmax);\n        compute_extra_params();\n    }\n\n    ~ApproxPowerFunction() = default;\n\n    ApproxPowerFunction& operator=(const ApproxPowerFunction&) = default;\n    ApproxPowerFunction& operator=(ApproxPowerFunction&&) = default;\n\n    /// Get the value of power factor \\f$ \\beta \\f$\n    Real power_factor() const\n    {\n        return m_beta;\n    }\n\n    /// Get the target accuracy \\f$ \\epsilon \\f$\n    Real tolerance() const\n    {\n        return m_eps;\n    }\n\n    ///\n    /// Get the lower bound of the interval in which the exponential sum\n    /// approximation is constructed.\n    ///\n    Real rmin() const\n    {\n        return m_rmin;\n    }\n    ///\n    /// Get the upper bound of the interval in which the exponential sum\n    /// approximation is constructed.\n    ///\n    Real rmax() const\n    {\n        return m_rmax;\n    }\n    ///\n    /// Set parameters\n    ///\n    void set_params(Real beta, Real eps, Real rmin, Real rmax)\n    {\n        check_args(beta, eps, rmin, rmax);\n        m_beta = beta;\n        m_eps  = eps;\n        m_rmin = rmin;\n        m_rmax = rmax;\n        compute_extra_params();\n    }\n\n    ///\n    /// Compute the exponential sum approximation with the parameters set in\n    /// advance via constructor or `set_params` method.\n    ///\n    ResultType compute() const;\n\n    ///\n    /// Compute the exponential sum approximation with the given parameters.\n    ///\n    ResultType compute(Real beta, Real eps, Real rmin, Real rmax)\n    {\n        set_params(beta, eps, rmin, rmax);\n        return compute();\n    }\n    ///\n    /// Print parameters to the given ostream\n    ///\n    template <typename Ch, typename Tr>\n    void print(std::basic_ostream<Ch, Tr>& os) const;\n\nprivate:\n    constexpr static const Real safety = Real(10);\n\n    static void check_args(Real beta, Real eps, Real rmin, Real rmax);\n    void compute_extra_params();\n\n    Real m_beta;\n    Real m_eps;\n    Real m_rmin;\n    Real m_rmax;\n\n    Real m_h;        // step size for discretization\n    Index m_n_minus; // number of terms for trapezoidal rule\n    Index m_n_plus;  // number of terms for trapezoidal rule\n};\n\n// ostream operator\ntemplate <typename Ch, typename Tr, typename T>\nstd::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& os,\n                                       const ApproxPowerFunction<T>& es)\n{\n    es.print(os);\n    return os;\n}\n\n//\n// --- Implementations of member functions\n//\n\ntemplate <typename T>\ntypename ApproxPowerFunction<T>::ResultType\nApproxPowerFunction<T>::compute() const\n{\n    ResultType es(m_n_minus + m_n_plus + 1);\n\n    const Real scale = m_h / std::tgamma(m_beta);\n\n    for (Index n = -m_n_minus; n <= m_n_plus; ++n)\n    {\n        const Real tn              = Real(n) * m_h;\n        const Real en              = std::exp(-tn);\n        es.exponent(n + m_n_minus) = std::exp(tn - en);\n        es.weight(n + m_n_minus) =\n            scale * (Real(1) + en) * std::exp(m_beta * (tn - en));\n    }\n\n    //\n    // Reduce number of terms with small exponents (a[i] < 1) via the modified\n    // Prony method.\n    //\n    ModifiedPronyReduction<Real> reduction;\n    const Index n_target = static_cast<Index>(std::distance(\n        es.exponents().data(),\n        std::upper_bound(es.exponents().data(),\n                         es.exponents().data() + es.exponents().size(),\n                         Real(1))));\n\n    ResultType trunc = reduction.compute(es, n_target, m_eps);\n\n    const Real rmax_tmp = m_rmax * safety;\n    trunc.exponents() /= rmax_tmp;\n    trunc.weights() *= std::pow(rmax_tmp, -m_beta);\n\n    return trunc;\n}\n\ntemplate <typename T>\ntemplate <typename Ch, typename Tr>\nvoid ApproxPowerFunction<T>::print(std::basic_ostream<Ch, Tr>& os) const\n{\n    os << \"# Exponential sum approximation of power function, r^{-beta}\\n\"\n       << \"#   beta    : \" << m_beta << '\\n'                    //\n       << \"#   interval: [\" << m_rmin << ',' << m_rmax << \"]\\n\" //\n       << \"#   relative accuracy: \" << m_eps << '\\n'            //\n       << \"#   step size: \" << m_h << '\\n'                      //\n       << \"#   number of terms for discritization: [\" << -m_n_minus << \", \"\n       << m_n_plus << \"]\\n\";\n}\n\ntemplate <typename T>\nvoid ApproxPowerFunction<T>::check_args(Real beta, Real eps, Real rmin,\n                                        Real rmax)\n{\n    if (!(beta > Real()))\n    {\n        std::ostringstream msg;\n        msg << \"Invalid value for the argument `beta': \"\n               \"beta > 0 expected, but beta = \"\n            << beta << \" is given\";\n        throw std::invalid_argument(msg.str());\n    }\n\n    if (!(Real() < eps && eps < std::exp(Real(-1))))\n    {\n        std::ostringstream msg;\n        msg << \"Invalid value for the argument `eps': \"\n               \"0 < eps < 1/e expected, but \"\n            << eps << \" is given\";\n        throw std::invalid_argument(msg.str());\n    }\n\n    if (!(Real() < rmin && rmin < rmax))\n    {\n        std::ostringstream msg;\n        msg << \"Invalid value for the argument `rmin/rmax': \"\n               \"0 < rmin < rmax expected, but rmin = \"\n            << rmin << \" and rmax = \" << rmax << \" are given\";\n        throw std::invalid_argument(msg.str());\n    }\n}\n\ntemplate <typename T>\nvoid ApproxPowerFunction<T>::compute_extra_params()\n{\n    constexpr const T pi = boost::math::constants::pi<T>();\n    //\n    // Construct approximation for interval with extended rmax: otherwise, the\n    // relative error of Gaussian sum approximation for `r` close to `rmax`\n    // exceeds the prescribed accuracy.\n    //\n    const Real rmax = m_rmax * safety;\n\n    //\n    // Some constants related to given arguments\n    //\n    const T eps_d = m_eps / T(3); // upper bound of discretization error\n    const T eps_t = m_eps / T(3); // upper bound of truncation error\n    const T delta = m_rmin / rmax;\n\n    //\n    // ----- Spacing of discritization (See eq. (14) in [Beylkin2010])\n    //\n    // The step size h is determined to satisfy\n    //\n    //   \\sum_{n=1}^{\\infty}\n    //     \\frac{2|\\Gamma(\\beta + 2 \\pi i n / h)|}{\\Gamma(\\beta)} < \\epsilon_d.\n    //\n    // For \\beta = 1/2, the equation above can be written as,\n    //\n    //   \\sum_{n=1}^{\\infty} 2 / sqrt(cosh(2 \\pi^2 n / h)) < \\epsilon_d\n    //\n    // In practice, \\f$|\\Gamma(\\beta + 2 \\pi i n / h)|\\f$ decay so rapidly with\n    // \\f$n\\f$ that only the first term in the left-hand-side is significant.\n    //\n    if (m_beta == T(0.5))\n    {\n        // solve  2 / sqrt(cosh(2 * pi**2 / h)) == eps_d  with h\n        m_h = T(2) * pi * pi / std::acosh(T(4) / (eps_d * eps_d));\n    }\n    else\n    {\n        //\n        // |Gamma(beta + yi)| <= 1+(y/beta)**2 * exp(-y * atan(y/beta))\n        // so we solve (log(r.h.s) == log(eps_d)) with y = 2 * pi / h\n        //\n\n        //\n        // Initial guess of step size (See eq. (15) in [Beylkin2010])\n        //\n        // This yields a lower bound of step size h, which is not optimal.\n        //\n        m_h = T(2) * pi /\n              (std::log(T(3)) - m_beta * std::log(std::cos(T(1))) -\n               std::log(eps_d));\n\n        const T beta_half = m_beta / T(2);\n        const T log_eps_d = std::log(eps_d);\n        const T y         = detail::newton(\n            // Initial guess of y\n            T(2) * pi / m_h,\n            // relative accuracy\n            eps_d,\n            // function value and its derivative\n            [=](T t) {\n                const T x      = t / m_beta;\n                const T atan_x = std::atan2(t, m_beta);\n                const T f =\n                    beta_half * std::log1p(x * x) - t * atan_x - log_eps_d;\n                const T df = (beta_half - x) / (T(1) + x * x) - atan_x;\n                return std::make_pair(f, df);\n            });\n\n        m_h = T(2) * pi / y;\n    }\n\n    //\n    // Find lower bound `t_lower` such that the truncation error of integral is\n    // bounded up to `eps_t`\n    //\n    // `t_lower` satisfies\n    //\n    //   C_2 \\exp(-\\beta e^{t}) < \\epsilon_t\n    //\n    // with \\f$ C_2 = 2e/\\Gamma(\\beta)\\f$ (See eq. (25) in [McLean2017]).\n    //\n    const T c2 =\n        T(2) * boost::math::constants::e<T>() / std::tgamma(m_beta + 1);\n    const T t_lower = -std::log(-std::log(eps_t / c2) / m_beta);\n\n    //\n    // Find upper bound `t_upper` such that the truncation error of integral is\n    // bounded up to `eps_t`\n    //\n    // This is obtained by solving (see eq.(32) in [Beylkin2010])\n    //\n    //   \\Gamma(beta, \\delta \\exp(t)) = \\epsilon_t\n    //\n    // For beta = 1/2, the equation becomes\n    //\n    //   \\erfc(\\delta exp(t/2)) = \\epsilon_t\n    //\n    const T t_upper =\n        std::log(boost::math::gamma_q_inv(m_beta, eps_t)) - std::log(delta);\n\n    //\n    // Set the step size and number of terms for trapezoidal rule\n    //\n    m_n_minus = static_cast<Index>(std::floor((-t_lower) / m_h));\n    m_n_plus  = static_cast<Index>(std::ceil((t_upper) / m_h));\n}\n\n///\n/// ### approx_power\n///\ntemplate <typename T>\nExponentialSum<T, T> approx_power(T beta, T eps, T rmin, T rmax)\n{\n    ApproxPowerFunction<T> pow;\n    return pow.compute(beta, eps, rmin, rmax);\n}\n\n} // namespace mxpfit\n\n#endif /* MXPFIT_APPROX_POWER_HPP */\n", "meta": {"hexsha": "d47f864e2294c517b1058c2f9e544a2566013ae9", "size": 13937, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/approx_power.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/approx_power.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/approx_power.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": 30.9024390244, "max_line_length": 80, "alphanum_fraction": 0.5773121906, "num_tokens": 3788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.5293811665220167}}
{"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{\nArray4i v = Array4i::Random().abs();\ncout << \"Here is the initial vector v:\\n\" << v.transpose() << \"\\n\";\nstd::sort(v.begin(), v.end());\ncout << \"Here is the sorted vector v:\\n\" << v.transpose() << \"\\n\";\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "290ec4a212b7eb3cf55a18ad32841c1b51414ac0", "size": 736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_Tutorial_std_sort.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_Tutorial_std_sort.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_Tutorial_std_sort.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": 26.2857142857, "max_line_length": 224, "alphanum_fraction": 0.6657608696, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.5293811579490519}}
{"text": "/**\n * Authors:\n *      Joao Quintas (jquintas@gmail.com)\n *      Joao Cruz (joao.pedro.cruz@tecnico.ulisboa.pt)\n * \t\tMarcelo Jacinto (marcelo.jacinto@tecnico.ulisboa.pt)\n * Maintained by: Marcelo Fialho Jacinto (marcelo.jacinto@tecnico.ulisboa.pt)\n * Last Update: 14/12/2021\n * License: MIT\n * File: spherical_coordinates.hpp\n * Brief: Defines all functions related to spherical coordinates conversions\n */\n#pragma once\n#include <Eigen/Dense>\n\nnamespace DSOR {\n    \n    /**\n\t * @brief Convert from spherical to cartesian coordinates. Used mainly with usbl fixes\n\t * \n\t * @param bearing Horizontal angle between the direction of an object and another object or between it and the true north direction in degrees. \n\t * @param elevation Angle measured between the horizontal and the vehicle line of sight to the object\n\t * @param range Distance to the object\n\t * @return Eigen Vector with cartesian coordinates \n\t */\n    template <typename T>\n\tEigen::Matrix<T, 3, 1> spherical_to_cartesian(T bearing, T elevation, T range);\n}", "meta": {"hexsha": "a3d187431f5bad0bc18b483f8edded2102195136", "size": 1023, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dsor_utils/include/dsor_utils/spherical_coordinates.hpp", "max_stars_repo_name": "dsor-isr/dsor_utils", "max_stars_repo_head_hexsha": "9e0c47701340b18da423a6badfb698673179f6bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dsor_utils/include/dsor_utils/spherical_coordinates.hpp", "max_issues_repo_name": "dsor-isr/dsor_utils", "max_issues_repo_head_hexsha": "9e0c47701340b18da423a6badfb698673179f6bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dsor_utils/include/dsor_utils/spherical_coordinates.hpp", "max_forks_repo_name": "dsor-isr/dsor_utils", "max_forks_repo_head_hexsha": "9e0c47701340b18da423a6badfb698673179f6bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8888888889, "max_line_length": 145, "alphanum_fraction": 0.7350928641, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5293811466205601}}
{"text": "#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/quote.hpp>\n#include <boost/mpl/protect.hpp>\n#include <boost/mpl/bind.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <cmath>\n#include <boost/safe_float.hpp>\n#include <boost/safe_float/convenience.hpp>\n#include <boost/safe_float/policy/check_multiplication_overflow.hpp>\n#include <boost/safe_float/policy/check_multiplication_underflow.hpp>\n#include <boost/safe_float/policy/check_multiplication_inexact.hpp>\n#include <boost/safe_float/policy/check_multiplication_invalid_result.hpp>\n\n//types to be tested\nusing test_types=boost::mpl::list<\n    float, double, long double\n>;\n\nusing namespace boost::safe_float;\n\n/**\n  This test suite checks different policies on multiplication operations using default parameters for the other policies.\n  */\nBOOST_AUTO_TEST_SUITE( safe_float_multiplication_test_suite )\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_multiplication_throws_on_overflow, FPT, test_types){\n    // define two FPT numbers suppose to positive overflow\n    FPT a = std::numeric_limits<FPT>::max();\n    FPT b = 2;\n    // check FPT overflows to inf after add\n    BOOST_CHECK(std::isinf(a*b));\n\n    // construct safe_float version of the same two numbers\n    safe_float<FPT, policy::check_multiplication_overflow> c(std::numeric_limits<FPT>::max());\n    safe_float<FPT, policy::check_multiplication_overflow> d(FPT(2));\n\n    // check the multiplication throws\n    BOOST_CHECK_THROW(c*d, std::exception);\n\n    // define two FPT numbers suppose to negative overflow\n    FPT e = std::numeric_limits<FPT>::lowest();\n    FPT f = 2;\n    // check FPT overflows to inf after add\n    BOOST_CHECK(std::isinf(e*f));\n\n    // construct safe_float version of the same two numbers\n    safe_float<FPT, policy::check_multiplication_overflow> g(std::numeric_limits<FPT>::lowest());\n    safe_float<FPT, policy::check_multiplication_overflow> h(FPT(2));\n\n    // check the multiplication throws\n    BOOST_CHECK_THROW(g*h, std::exception);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_multiplication_inexact_rounding, FPT, test_types){\n    // define two FPT numbers suppose to produce inexact rounding\n    FPT a, b;\n    \n    if(std::is_same<FPT, float>()) {\n        a = 1.64005529880523681640625f;\n        b = 3.1559422016143798828125f;\n    } else if(std::is_same<FPT, double>()){\n        a = 1.200941392190915113502569511183537542819976806640625;\n        b = 1.7035518365272823704259508303948678076267242431640625;\n    } else if(std::is_same<FPT, long double>()) {\n        a = 1.48057361058650153290937312444697226965217851102352142333984375L;\n        b = 1.8352666822131742060432435525996197611675597727298736572265625L;\n    } else {\n        BOOST_ERROR(\"Test implemented only for float, double and long double\");\n    }\n\n    // check multiplying and dividing gives the same number back.\n    BOOST_CHECK((a*b)/b != a);\n\n    // construct safe_float version of the same two numbers\n    safe_float<FPT, policy::check_multiplication_inexact> c(a);\n    safe_float<FPT, policy::check_multiplication_inexact> d(b);\n\n    // check the multiplication throws\n    BOOST_CHECK_THROW(c*d, std::exception);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_multiplication_underflow, FPT, test_types){\n    // define two FPT numbers suppose to produce underflow\n    FPT a = std::numeric_limits<FPT>::min();\n    FPT b = 0.5;\n\n    // check FPT underflow to denormalized result after multiply\n    BOOST_CHECK(std::fpclassify(a*b) == FP_SUBNORMAL);\n\n    // construct safe_float version of the same two numbers\n    safe_float<FPT, policy::check_multiplication_underflow> c(a);\n    safe_float<FPT, policy::check_multiplication_underflow> d(b);\n\n    // check the multiplication throws\n    BOOST_CHECK_THROW(c*d, std::exception);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_multiplication_invalid_result, FPT, test_types){\n    // define two FPT numbers suppose to produce a NAN\n    FPT a = std::numeric_limits<FPT>::infinity();\n    FPT b = 0;\n\n    // check adding produced NaN\n    BOOST_CHECK(std::isnan(a*b));\n\n    // construct safe_float version of the same two numbers\n    safe_float<FPT, policy::check_multiplication_invalid_result> c(std::numeric_limits<FPT>::infinity());\n    safe_float<FPT, policy::check_multiplication_invalid_result> d(FPT(0));\n\n    // check the multiplication throws\n    BOOST_CHECK_THROW(c*d, std::exception);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n", "meta": {"hexsha": "7def3d3a1e12d3fc548aa00747099007a34fdbe0", "size": 4468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/safe_float_multiplication_test.cpp", "max_stars_repo_name": "aTom3333/safefloat", "max_stars_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-08T01:24:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-08T01:24:16.000Z", "max_issues_repo_path": "test/safe_float_multiplication_test.cpp", "max_issues_repo_name": "aTom3333/safefloat", "max_issues_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "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/safe_float_multiplication_test.cpp", "max_forks_repo_name": "aTom3333/safefloat", "max_forks_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T11:31:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-12T21:55:25.000Z", "avg_line_length": 36.0322580645, "max_line_length": 121, "alphanum_fraction": 0.7410474485, "num_tokens": 1123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5293811370269583}}
{"text": "/*\nCopyright 2012, 2013 Rogier van Dalen.\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/** \\file\nTest std::numeric_limits <log_float <...>>.\n*/\n\n#define BOOST_TEST_MODULE log_float_limits\n#include \"../boost_unit_test.hpp\"\n\n#include \"math/log-float.hpp\"\n\n#include <limits>\n\n#include <boost/math/special_functions/fpclassify.hpp>\n\nBOOST_AUTO_TEST_SUITE(test_suite_log_float_limits)\n\ntemplate <class LogFloat, class Underlying> void check_limits() {\n    typedef std::numeric_limits <LogFloat> limits;\n    typedef std::numeric_limits <Underlying> limits_underlying;\n\n    /* Static properties. */\n    static_assert (limits::is_specialized, \"\");\n    static_assert (!limits::is_integer, \"\");\n    static_assert (!limits::is_exact, \"\");\n    static_assert (limits::has_infinity, \"\");\n\n    static_assert (limits::has_quiet_NaN, \"\");\n    static_assert (limits::has_signaling_NaN, \"\");\n    static_assert (limits::has_denorm == std::denorm_absent, \"\");\n    static_assert (!limits::has_denorm_loss, \"\");\n    static_assert (limits::round_style == std::round_to_nearest, \"\");\n\n    static_assert (!limits::is_iec559, \"\");\n    static_assert (limits::is_bounded, \"\");\n    static_assert (!limits::is_modulo, \"\");\n\n    static_assert (!limits::traps, \"\");\n    static_assert (!limits::tinyness_before, \"\");\n\n    /* Functions. */\n    // min.\n    {\n        auto min = limits::min();\n        BOOST_CHECK (min > 0);\n        BOOST_CHECK_EQUAL (min.exponent(), limits_underlying::lowest());\n    }\n    {\n        auto max = limits::max();\n        BOOST_CHECK (max > 0);\n        BOOST_CHECK_EQUAL (max.exponent(), limits_underlying::max());\n    }\n    {\n        // 1+epsilon must have the smallest representable underlying float as\n        // its exponent.\n        auto epsilon = limits::epsilon();\n        decltype (epsilon) one = 1;\n        auto one_plus_epsilon = one + epsilon;\n        BOOST_CHECK_EQUAL (one_plus_epsilon.exponent(),\n            limits_underlying::denorm_min());\n    }\n    {\n        auto infinity = limits::infinity();\n        BOOST_CHECK (infinity > 0);\n        BOOST_CHECK_EQUAL (infinity.exponent(), limits_underlying::infinity());\n    }\n    {\n        auto quiet_NaN = limits::quiet_NaN();\n        BOOST_CHECK (!(quiet_NaN == quiet_NaN));\n        using namespace boost::math;\n        BOOST_CHECK (isnan (quiet_NaN.exponent()));\n    }\n    {\n        auto signaling_NaN = limits::signaling_NaN();\n        BOOST_CHECK (!(signaling_NaN == signaling_NaN));\n        using namespace boost::math;\n        BOOST_CHECK (isnan (signaling_NaN.exponent()));\n    }\n\n    /*\n    Not tested because they are not meaningfully implemented:\n    digits, digits10, max_digits10, radix\n    min_exponent, min_exponent10, max_exponent, max_exponent10\n    round_error(), denorm_min()\n    */\n}\n\ntemplate <class LogFloat, class Underlying> void check_limits_unsigned() {\n    check_limits <LogFloat, Underlying>();\n\n    typedef std::numeric_limits <LogFloat> limits;\n\n    static_assert (!limits::is_signed, \"\");\n\n    BOOST_CHECK_EQUAL (limits::lowest(), limits::min());\n}\n\ntemplate <class LogFloat, class Underlying> void check_limits_signed() {\n    check_limits <LogFloat, Underlying>();\n\n    typedef std::numeric_limits <LogFloat> limits;\n\n    static_assert (limits::is_signed, \"\");\n\n    BOOST_CHECK_EQUAL (limits::lowest(), -limits::max());\n}\n\nBOOST_AUTO_TEST_CASE (test_log_float_limits) {\n\n    check_limits_unsigned <math::log_float <float>, float>();\n    check_limits_unsigned <math::log_float <double> const, double>();\n    check_limits_unsigned <math::log_float <double> &, double>();\n    check_limits_unsigned <math::log_float <double> const &, double>();\n\n    check_limits_signed <math::signed_log_float <float>, float>();\n    check_limits_signed <math::signed_log_float <double> const &, double>();\n    check_limits_signed <math::signed_log_float <double> &&, double>();\n\n    // long double does not work under Valgrind.\n    // check_limits_signed <\n    //     math::signed_log_float <long double>, long double>();\n    // check_limits_signed <\n    //     math::signed_log_float <long double> const &, long double>();\n\n    using namespace boost::math::policies;\n    typedef policy <domain_error <errno_on_error>,\n        overflow_error <errno_on_error>> other_policy;\n\n    check_limits_unsigned <math::log_float <float, other_policy>, float>();\n    check_limits_unsigned <math::log_float <double, other_policy> &, double>();\n\n    check_limits_signed <math::signed_log_float <float, other_policy>, float>();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4eaef5623f05b5f2b8667382e24ed5fa0c832e53", "size": 4992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/test-log-float-limits.cpp", "max_stars_repo_name": "rogiervd/math", "max_stars_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "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/math/test-log-float-limits.cpp", "max_issues_repo_name": "rogiervd/math", "max_issues_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "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/math/test-log-float-limits.cpp", "max_forks_repo_name": "rogiervd/math", "max_forks_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "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.28, "max_line_length": 80, "alphanum_fraction": 0.6848958333, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5293081912122781}}
{"text": "#define BOOST_TEST_MODULE example\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <cmath>\n\n#include \"random_tree.h\"\n#include \"test_common.h\"\n\nusing namespace curfil;\nusing namespace cuv;\n\nBOOST_AUTO_TEST_SUITE(RandomTreeTest)\n\nBOOST_AUTO_TEST_CASE(testNormalizeHistogramEqualPriorDistribution) {\n\n    const LabelType NUM_LABELS = 3;\n\n    cuv::ndarray<WeightType, cuv::host_memory_space> histogram(NUM_LABELS);\n    histogram[0] = 850;\n    histogram[1] = 50;\n    histogram[2] = 100;\n\n    cuv::ndarray<WeightType, cuv::host_memory_space> priorDistribution(NUM_LABELS);\n    for (LabelType label = 0; label < NUM_LABELS; label++) {\n        priorDistribution[label] = 100;\n    }\n\n    ndarray<double, host_memory_space> normalizedHistogram = curfil::detail::normalizeHistogram(histogram,\n            priorDistribution, 0.0);\n\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[0]), 0.850 / 3.0, 1e-15);\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[1]), 0.050 / 3.0, 1e-15);\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[2]), 0.100 / 3.0, 1e-15);\n}\n\nBOOST_AUTO_TEST_CASE(testNormalizeHistogramEqualHistogramUnequalPriorDistribution) {\n\n    const LabelType NUM_LABELS = 3;\n\n    cuv::ndarray<WeightType, cuv::host_memory_space> histogram(NUM_LABELS);\n    histogram[0] = 50;\n    histogram[1] = 50;\n    histogram[2] = 50;\n\n    cuv::ndarray<WeightType, cuv::host_memory_space> priorDistribution(NUM_LABELS);\n    priorDistribution[0] = 80;\n    priorDistribution[1] = 10;\n    priorDistribution[2] = 10;\n\n    ndarray<double, host_memory_space> normalizedHistogram = curfil::detail::normalizeHistogram(histogram,\n            priorDistribution, 0.0);\n\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[0]), (1 / 3.0) * 0.8, 1e-15);\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[1]), (1 / 3.0) * 0.1, 1e-15);\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[2]), (1 / 3.0) * 0.1, 1e-15);\n}\n\nBOOST_AUTO_TEST_CASE(testNormalizeHistogramHighBias) {\n\n    const LabelType NUM_LABELS = 3;\n\n    cuv::ndarray<WeightType, cuv::host_memory_space> histogram(NUM_LABELS);\n    histogram[0] = 50;\n    histogram[1] = 50;\n    histogram[2] = 50;\n\n    cuv::ndarray<WeightType, cuv::host_memory_space> priorDistribution(NUM_LABELS);\n    priorDistribution[0] = 80;\n    priorDistribution[1] = 10;\n    priorDistribution[2] = 10;\n\n    ndarray<double, host_memory_space> normalizedHistogram = curfil::detail::normalizeHistogram(histogram,\n            priorDistribution, 0.5);\n\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[0]), 0.0, 1e-15);\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[1]), 0.0, 1e-15);\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[2]), 0.0, 1e-15);\n}\n\nBOOST_AUTO_TEST_CASE(testNormalizeHistogramMediumBias) {\n\n    const LabelType NUM_LABELS = 3;\n\n    cuv::ndarray<WeightType, cuv::host_memory_space> histogram(NUM_LABELS);\n    histogram[0] = 60;\n    histogram[1] = 20;\n    histogram[2] = 20;\n\n    cuv::ndarray<WeightType, cuv::host_memory_space> priorDistribution(NUM_LABELS);\n    priorDistribution[0] = 50;\n    priorDistribution[1] = 25;\n    priorDistribution[2] = 25;\n\n    ndarray<double, host_memory_space> normalizedHistogram = curfil::detail::normalizeHistogram(histogram,\n            priorDistribution, 0.5);\n\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[0]), 0.5, 1e-15);\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[1]), 0.0, 1e-15);\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[2]), 0.0, 1e-15);\n}\n\nBOOST_AUTO_TEST_CASE(testNormalizeHistogramLowBias) {\n\n    const LabelType NUM_LABELS = 3;\n\n    cuv::ndarray<WeightType, cuv::host_memory_space> histogram(NUM_LABELS);\n    histogram[0] = 20;\n    histogram[1] = 40;\n    histogram[2] = 40;\n\n    cuv::ndarray<WeightType, cuv::host_memory_space> priorDistribution(NUM_LABELS);\n    priorDistribution[0] = 20;\n    priorDistribution[1] = 10;\n    priorDistribution[2] = 10;\n\n    ndarray<double, host_memory_space> normalizedHistogram = curfil::detail::normalizeHistogram(histogram,\n            priorDistribution, 0.2);\n\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[0]), 0.0, 1e-15);\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[1]), 0.5 * 0.25, 1e-15);\n    BOOST_CHECK_CLOSE(static_cast<double>(normalizedHistogram[2]), 0.5 * 0.25, 1e-15);\n}\n\nBOOST_AUTO_TEST_CASE(testReservoirSampler) {\n\n    size_t sampleSize = 1000;\n    const int MAX = 100000;\n\n    RandomSource randomSource(4711);\n    Sampler sampler = randomSource.uniformSampler(0, 10 * MAX);\n\n    ReservoirSampler<int> reservoirSampler(sampleSize);\n    for (int i = 0; i < MAX; i++) {\n        reservoirSampler.sample(sampler, i);\n    }\n\n    const auto& reservoir = reservoirSampler.getReservoir();\n    BOOST_REQUIRE_EQUAL(reservoir.size(), sampleSize);\n\n    boost::accumulators::accumulator_set<int,\n            boost::accumulators::features<\n                    boost::accumulators::tag::min,\n                    boost::accumulators::tag::max,\n                    boost::accumulators::tag::mean,\n                    boost::accumulators::tag::variance> > acc;\n\n    acc = std::for_each(reservoir.begin(), reservoir.end(), acc);\n\n    double min = boost::accumulators::min(acc);\n    double max = boost::accumulators::max(acc);\n    double mean = boost::accumulators::mean(acc);\n    double stddev = std::sqrt(static_cast<double>(boost::accumulators::variance(acc)));\n\n    /*\n     * values are empirically determined with python and numpy\n     *\n     * >>> import random, numpy as np\n     * >>> a = np.arange(100000)\n     * >>> random.shuffle(a)\n     * >>> b = a[:10000]\n     * >>> b.mean()\n     * 50271.870999999999\n     *\n     * >>> np.sqrt(b.var())\n     * 28804.962206705768\n     *\n     * >>> b.min()\n     * 12.0\n     *\n     * >>> b.max()\n     * 99996.0\n     */\n    BOOST_REQUIRE_LT(min, 0.01 * MAX);\n    BOOST_REQUIRE_GT(max, 0.99 * MAX);\n    BOOST_REQUIRE_CLOSE(mean, 50000.0, 0.05);\n    BOOST_REQUIRE_CLOSE(stddev, 28000.0, 2.0);\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f4c8f1218dfff6165e7e876ea69a80d05b2c1026", "size": 6317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/random_tree_test.cpp", "max_stars_repo_name": "amueller/curfil", "max_stars_repo_head_hexsha": "47c97be43abe62035f4da290276176f0120c0be0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-14T13:43:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-13T20:56:42.000Z", "max_issues_repo_path": "src/tests/random_tree_test.cpp", "max_issues_repo_name": "ferasha/curfil", "max_issues_repo_head_hexsha": "f8c257dcb3a74aaa5c25eaa91c29a6dcbad04211", "max_issues_repo_licenses": ["MIT"], "max_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/random_tree_test.cpp", "max_forks_repo_name": "ferasha/curfil", "max_forks_repo_head_hexsha": "f8c257dcb3a74aaa5c25eaa91c29a6dcbad04211", "max_forks_repo_licenses": ["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.3315217391, "max_line_length": 106, "alphanum_fraction": 0.6955833465, "num_tokens": 1741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5293081704671512}}
{"text": "#include <util_tensors.h>\n#include <util_coo_matrix.h>\n#include <glue_triplet.h>\n#include <glue_matrix_assembly.h>\n\n#include <vector>\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\n/**\n * This assembles a test problem on a small example mesh. The mesh consist\n * of four vertices and three triangles. The element matrices is chosen such\n * that it is quite simple to verify if the assembled matrix is correct or not.\n */\ninline util::COOMatrix<double> do_assembly_of_tensor2_test_problem( bool const & interlaced )\n{\n  std::vector<glue::Triplet> triangles;\n\n  triangles.push_back( glue::make_triplet(0u, 1u, 2u) );\n  triangles.push_back( glue::make_triplet(0u, 2u, 3u) );\n  triangles.push_back( glue::make_triplet(0u, 3u, 1u) );\n\n  unsigned int const V = 4u;  // We got 4 vertices\n\n  std::vector<util::Block3x3Tensor2> Ae;\n\n  Ae.resize(3u); // We got 3 triangles\n\n  util::Block3x3Tensor2 E;\n\n  // Element matrix is the same for all elements\n  //\n  //         1 0 2 0 4 0\n  //         0 1 0 2 0 4\n  //         2 0 1 0 3 0\n  //   E =   0 2 0 1 0 3\n  //         4 0 3 0 1 0\n  //         0 4 0 3 0 1\n  //\n  E.m_block[0][0] = util::identity();\n  E.m_block[1][1] = util::identity();\n  E.m_block[2][2] = util::identity();\n  E.m_block[0][1] = util::mul( 2.0, util::identity() );\n  E.m_block[0][2] = util::mul( 4.0, util::identity() );\n  E.m_block[1][2] = util::mul( 3.0, util::identity() );\n  E.m_block[1][0] = E.m_block[0][1];\n  E.m_block[2][0] = E.m_block[0][2];\n  E.m_block[2][1] = E.m_block[1][2];\n\n  Ae[0] = E;\n  Ae[1] = E;\n  Ae[2] = E;\n\n  // Do the assembley, the \"interlaced\" results should be\n  //\n  //  3     0     6     0     6     0     6     0\n  //  0     3     0     6     0     6     0     6\n  //  6     0     2     0     3     0     3     0\n  //  0     6     0     2     0     3     0     3\n  //  6     0     3     0     2     0     3     0\n  //  0     6     0     3     0     2     0     3\n  //  6     0     3     0     3     0     2     0\n  //  0     6     0     3     0     3     0     2\n  //\n  // and non-interlaced should be\n  //\n  //  3     6     6     6     0     0     0     0\n  //  6     2     3     3     0     0     0     0\n  //  6     3     2     3     0     0     0     0\n  //  6     3     3     2     0     0     0     0\n  //  0     0     0     0     3     6     6     6\n  //  0     0     0     0     6     2     3     3\n  //  0     0     0     0     6     3     2     3\n  //  0     0     0     0     6     3     3     2\n\n  util::COOMatrix<double> A = glue::matrix_assembly<double>( triangles, V, Ae, interlaced );\n\n  std::cout << util::to_string(A) << std::endl;\n\n  return A;\n}\n\n/**\n * Specific for tensor1 data using cell-centered variables\n */\ninline util::COOMatrix<double> do_assembly_of_tensor1_test_problem( bool const & interlaced )\n{\n  std::vector<glue::Triplet> triangles;\n\n  triangles.push_back( glue::make_triplet(0u, 1u, 2u) );\n  triangles.push_back( glue::make_triplet(0u, 2u, 3u) );\n  triangles.push_back( glue::make_triplet(0u, 3u, 1u) );\n\n  unsigned int const V = 4u;  // We got 4 vertices\n\n  std::vector<util::Block3x1Tensor1> Ae;\n\n  Ae.resize(3u); // We got 3 triangles\n\n  util::Block3x1Tensor1 E;\n\n  E.m_block[0] = util::make(1.0, 1.0);\n  E.m_block[1] = util::make(1.0, 1.0);\n  E.m_block[2] = util::make(1.0, 1.0);\n\n  Ae[0] = E;\n  Ae[1] = E;\n  Ae[2] = E;\n\n  // Do the assembley, the \"interlaced\" results should be\n  //\n  //  1     1     1\n  //  1     1     1\n  //  1     0     1\n  //  1     0     1\n  //  1     1     0\n  //  1     1     0\n  //  0     1     1\n  //  0     1     1\n  //\n  // and non-interlaced should be\n  //\n  //  1     1     1\n  //  1     0     1\n  //  1     1     0\n  //  0     1     1\n  //  1     1     1\n  //  1     0     1\n  //  1     1     0\n  //  0     1     1\n\n  util::COOMatrix<double> A = glue::matrix_assembly<double>( triangles, V, Ae, interlaced );\n\n  std::cout << util::to_string(A) << std::endl;\n  \n  return A;\n}\n\n/**\n * Specific for tensor0 data using vertex variables\n */\ninline util::COOMatrix<double> do_assembly_of_tensor0_test_problem( )\n{\n  std::vector<glue::Triplet> triangles;\n\n  triangles.push_back( glue::make_triplet(0u, 1u, 2u) );\n  triangles.push_back( glue::make_triplet(0u, 2u, 3u) );\n  triangles.push_back( glue::make_triplet(0u, 3u, 1u) );\n\n  unsigned int const V = 4u;  // We got 4 vertices\n\n  std::vector<util::Block3x3Tensor0> Ae;\n\n  Ae.resize(3u); // We got 3 triangles\n\n  util::Block3x3Tensor0 E;\n\n  // Element matrix is the same for all elements\n  //\n  //         1 2 4\n  //         2 1 3\n  //   E =   4 3 1\n  //\n  E.m_block[0][0] = 1.0;\n  E.m_block[1][1] = 1.0;\n  E.m_block[2][2] = 1.0;\n  E.m_block[0][1] = 2.0;\n  E.m_block[0][2] = 4.0;\n  E.m_block[1][2] = 3.0;\n  E.m_block[1][0] = E.m_block[0][1];\n  E.m_block[2][0] = E.m_block[0][2];\n  E.m_block[2][1] = E.m_block[1][2];\n\n  Ae[0] = E;\n  Ae[1] = E;\n  Ae[2] = E;\n\n  // Do the assembley, the results should be\n  //\n  //\n  //  3     6     6     6\n  //  6     2     3     3\n  //  6     3     2     3\n  //  6     3     3     2\n\n  util::COOMatrix<double> A = glue::matrix_assembly<double>( triangles, V, Ae );\n\n  std::cout << util::to_string(A) << std::endl;\n  \n  return A;\n}\n\nBOOST_AUTO_TEST_SUITE(coo_matrix);\n\nBOOST_AUTO_TEST_CASE(assemble_tensor2_matrix_interlaced)\n{\n  util::COOMatrix<double> const A = do_assembly_of_tensor2_test_problem( true );\n\n  BOOST_CHECK_EQUAL(A.row_indices()[0], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[1], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[2], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[3], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[4], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[5], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[6], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[7], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[8], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[9], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[10], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[11], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[12], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[13], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[14], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[15], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[16], 4u);\n  BOOST_CHECK_EQUAL(A.row_indices()[17], 4u);\n  BOOST_CHECK_EQUAL(A.row_indices()[18], 4u);\n  BOOST_CHECK_EQUAL(A.row_indices()[19], 4u);\n  BOOST_CHECK_EQUAL(A.row_indices()[20], 5u);\n  BOOST_CHECK_EQUAL(A.row_indices()[21], 5u);\n  BOOST_CHECK_EQUAL(A.row_indices()[22], 5u);\n  BOOST_CHECK_EQUAL(A.row_indices()[23], 5u);\n  BOOST_CHECK_EQUAL(A.row_indices()[24], 6u);\n  BOOST_CHECK_EQUAL(A.row_indices()[25], 6u);\n  BOOST_CHECK_EQUAL(A.row_indices()[26], 6u);\n  BOOST_CHECK_EQUAL(A.row_indices()[27], 6u);\n  BOOST_CHECK_EQUAL(A.row_indices()[28], 7u);\n  BOOST_CHECK_EQUAL(A.row_indices()[29], 7u);\n  BOOST_CHECK_EQUAL(A.row_indices()[30], 7u);\n  BOOST_CHECK_EQUAL(A.row_indices()[31], 7u);\n\n  BOOST_CHECK_EQUAL(A.column_indices()[0], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[1], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[2], 4u);\n  BOOST_CHECK_EQUAL(A.column_indices()[3], 6u);\n  BOOST_CHECK_EQUAL(A.column_indices()[4], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[5], 3u);\n  BOOST_CHECK_EQUAL(A.column_indices()[6], 5u);\n  BOOST_CHECK_EQUAL(A.column_indices()[7], 7u);\n  BOOST_CHECK_EQUAL(A.column_indices()[8], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[9], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[10], 4u);\n  BOOST_CHECK_EQUAL(A.column_indices()[11], 6u);\n  BOOST_CHECK_EQUAL(A.column_indices()[12], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[13], 3u);\n  BOOST_CHECK_EQUAL(A.column_indices()[14], 5u);\n  BOOST_CHECK_EQUAL(A.column_indices()[15], 7u);\n  BOOST_CHECK_EQUAL(A.column_indices()[16], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[17], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[18], 4u);\n  BOOST_CHECK_EQUAL(A.column_indices()[19], 6u);\n  BOOST_CHECK_EQUAL(A.column_indices()[20], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[21], 3u);\n  BOOST_CHECK_EQUAL(A.column_indices()[22], 5u);\n  BOOST_CHECK_EQUAL(A.column_indices()[23], 7u);\n  BOOST_CHECK_EQUAL(A.column_indices()[24], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[25], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[26], 4u);\n  BOOST_CHECK_EQUAL(A.column_indices()[27], 6u);\n  BOOST_CHECK_EQUAL(A.column_indices()[28], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[29], 3u);\n  BOOST_CHECK_EQUAL(A.column_indices()[30], 5u);\n  BOOST_CHECK_EQUAL(A.column_indices()[31], 7u);\n\n  BOOST_CHECK_CLOSE(A.values()[0], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[1], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[2], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[3], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[4], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[5], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[6], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[7], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[8], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[9], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[10], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[11], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[12], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[13], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[14], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[15], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[16], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[17], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[18], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[19], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[20], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[21], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[22], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[23], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[24], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[25], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[26], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[27], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[28], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[29], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[30], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[31], 2.0, 0.01);\n\n}\n\nBOOST_AUTO_TEST_CASE(assemble_tensor2_matrix_non_interlaced)\n{\n  util::COOMatrix<double> const A = do_assembly_of_tensor2_test_problem( false );\n\n  BOOST_CHECK_EQUAL(A.row_indices()[0], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[1], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[2], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[3], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[4], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[5], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[6], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[7], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[8], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[9], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[10], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[11], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[12], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[13], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[14], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[15], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[16], 4u);\n  BOOST_CHECK_EQUAL(A.row_indices()[17], 4u);\n  BOOST_CHECK_EQUAL(A.row_indices()[18], 4u);\n  BOOST_CHECK_EQUAL(A.row_indices()[19], 4u);\n  BOOST_CHECK_EQUAL(A.row_indices()[20], 5u);\n  BOOST_CHECK_EQUAL(A.row_indices()[21], 5u);\n  BOOST_CHECK_EQUAL(A.row_indices()[22], 5u);\n  BOOST_CHECK_EQUAL(A.row_indices()[23], 5u);\n  BOOST_CHECK_EQUAL(A.row_indices()[24], 6u);\n  BOOST_CHECK_EQUAL(A.row_indices()[25], 6u);\n  BOOST_CHECK_EQUAL(A.row_indices()[26], 6u);\n  BOOST_CHECK_EQUAL(A.row_indices()[27], 6u);\n  BOOST_CHECK_EQUAL(A.row_indices()[28], 7u);\n  BOOST_CHECK_EQUAL(A.row_indices()[29], 7u);\n  BOOST_CHECK_EQUAL(A.row_indices()[30], 7u);\n  BOOST_CHECK_EQUAL(A.row_indices()[31], 7u);\n\n  BOOST_CHECK_EQUAL(A.column_indices()[0], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[1], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[2], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[3], 3u);\n  BOOST_CHECK_EQUAL(A.column_indices()[4], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[5], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[6], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[7], 3u);\n  BOOST_CHECK_EQUAL(A.column_indices()[8], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[9], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[10], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[11], 3u);\n  BOOST_CHECK_EQUAL(A.column_indices()[12], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[13], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[14], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[15], 3u);\n  BOOST_CHECK_EQUAL(A.column_indices()[16], 4u);\n  BOOST_CHECK_EQUAL(A.column_indices()[17], 5u);\n  BOOST_CHECK_EQUAL(A.column_indices()[18], 6u);\n  BOOST_CHECK_EQUAL(A.column_indices()[19], 7u);\n  BOOST_CHECK_EQUAL(A.column_indices()[20], 4u);\n  BOOST_CHECK_EQUAL(A.column_indices()[21], 5u);\n  BOOST_CHECK_EQUAL(A.column_indices()[22], 6u);\n  BOOST_CHECK_EQUAL(A.column_indices()[23], 7u);\n  BOOST_CHECK_EQUAL(A.column_indices()[24], 4u);\n  BOOST_CHECK_EQUAL(A.column_indices()[25], 5u);\n  BOOST_CHECK_EQUAL(A.column_indices()[26], 6u);\n  BOOST_CHECK_EQUAL(A.column_indices()[27], 7u);\n  BOOST_CHECK_EQUAL(A.column_indices()[28], 4u);\n  BOOST_CHECK_EQUAL(A.column_indices()[29], 5u);\n  BOOST_CHECK_EQUAL(A.column_indices()[30], 6u);\n  BOOST_CHECK_EQUAL(A.column_indices()[31], 7u);\n\n  BOOST_CHECK_CLOSE(A.values()[0], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[1], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[2], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[3], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[4], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[5], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[6], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[7], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[8], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[9], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[10], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[11], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[12], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[13], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[14], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[15], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[16], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[17], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[18], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[19], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[20], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[21], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[22], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[23], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[24], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[25], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[26], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[27], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[28], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[29], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[30], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[31], 2.0, 0.01);\n\n}\n\nBOOST_AUTO_TEST_CASE(assemble_tensor0_matrix)\n{\n  util::COOMatrix<double> const A = do_assembly_of_tensor0_test_problem();\n\n  BOOST_CHECK_EQUAL(A.row_indices()[0], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[1], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[2], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[3], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[4], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[5], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[6], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[7], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[8], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[9], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[10], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[11], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[12], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[13], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[14], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[15], 3u);\n\n  BOOST_CHECK_EQUAL(A.column_indices()[0], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[1], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[2], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[3], 3u);\n  BOOST_CHECK_EQUAL(A.column_indices()[4], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[5], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[6], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[7], 3u);\n  BOOST_CHECK_EQUAL(A.column_indices()[8], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[9], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[10], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[11], 3u);\n  BOOST_CHECK_EQUAL(A.column_indices()[12], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[13], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[14], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[15], 3u);\n\n  BOOST_CHECK_CLOSE(A.values()[0], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[1], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[2], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[3], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[4], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[5], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[6], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[7], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[8], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[9], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[10], 2.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[11], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[12], 6.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[13], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[14], 3.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[15], 2.0, 0.01);\n\n}\n\nBOOST_AUTO_TEST_CASE(assemble_tensor1_matrix_interlaced)\n{\n  util::COOMatrix<double> const A = do_assembly_of_tensor1_test_problem( true );\n\n  BOOST_CHECK_EQUAL(A.row_indices()[0], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[1], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[2], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[3], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[4], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[5], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[6], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[7], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[8], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[9], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[10], 4u);\n  BOOST_CHECK_EQUAL(A.row_indices()[11], 4u);\n  BOOST_CHECK_EQUAL(A.row_indices()[12], 5u);\n  BOOST_CHECK_EQUAL(A.row_indices()[13], 5u);\n  BOOST_CHECK_EQUAL(A.row_indices()[14], 6u);\n  BOOST_CHECK_EQUAL(A.row_indices()[15], 6u);\n  BOOST_CHECK_EQUAL(A.row_indices()[16], 7u);\n  BOOST_CHECK_EQUAL(A.row_indices()[17], 7u);\n\n\n  BOOST_CHECK_EQUAL(A.column_indices()[0], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[1], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[2], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[3], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[4], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[5], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[6], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[7], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[8], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[9], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[10], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[11], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[12], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[13], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[14], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[15], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[16], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[17], 2u);\n\n  BOOST_CHECK_CLOSE(A.values()[0], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[1], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[2], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[3], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[4], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[5], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[6], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[7], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[8], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[9], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[10], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[11], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[12], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[13], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[14], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[15], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[16], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[17], 1.0, 0.01);\n\n}\n\nBOOST_AUTO_TEST_CASE(assemble_tensor1_matrix_non_interlaced)\n{\n  util::COOMatrix<double> const A = do_assembly_of_tensor1_test_problem( false );\n\n  BOOST_CHECK_EQUAL(A.row_indices()[0], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[1], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[2], 0u);\n  BOOST_CHECK_EQUAL(A.row_indices()[3], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[4], 1u);\n  BOOST_CHECK_EQUAL(A.row_indices()[5], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[6], 2u);\n  BOOST_CHECK_EQUAL(A.row_indices()[7], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[8], 3u);\n  BOOST_CHECK_EQUAL(A.row_indices()[9], 4u);\n  BOOST_CHECK_EQUAL(A.row_indices()[10], 4u);\n  BOOST_CHECK_EQUAL(A.row_indices()[11], 4u);\n  BOOST_CHECK_EQUAL(A.row_indices()[12], 5u);\n  BOOST_CHECK_EQUAL(A.row_indices()[13], 5u);\n  BOOST_CHECK_EQUAL(A.row_indices()[14], 6u);\n  BOOST_CHECK_EQUAL(A.row_indices()[15], 6u);\n  BOOST_CHECK_EQUAL(A.row_indices()[16], 7u);\n  BOOST_CHECK_EQUAL(A.row_indices()[17], 7u);\n\n  BOOST_CHECK_EQUAL(A.column_indices()[0], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[1], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[2], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[3], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[4], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[5], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[6], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[7], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[8], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[9], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[10], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[11], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[12], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[13], 2u);\n  BOOST_CHECK_EQUAL(A.column_indices()[14], 0u);\n  BOOST_CHECK_EQUAL(A.column_indices()[15], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[16], 1u);\n  BOOST_CHECK_EQUAL(A.column_indices()[17], 2u);\n\n  BOOST_CHECK_CLOSE(A.values()[0], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[1], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[2], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[3], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[4], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[5], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[6], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[7], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[8], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[9], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[10], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[11], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[12], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[13], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[14], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[15], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[16], 1.0, 0.01);\n  BOOST_CHECK_CLOSE(A.values()[17], 1.0, 0.01);\n  \n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "919d6b59a510e1519a2dc8e79dffeb5fe3e08dbe", "size": 22510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GRIT/unit_tests/glue_matrix_assembly/glue_matrix_assembly.cpp", "max_stars_repo_name": "H2020-MSCA-ITN-rainbow/GRIT", "max_stars_repo_head_hexsha": "1bdfb0735515e9d462214f66b88a71aabf836d76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-28T19:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T19:57:26.000Z", "max_issues_repo_path": "GRIT/unit_tests/glue_matrix_assembly/glue_matrix_assembly.cpp", "max_issues_repo_name": "H2020-MSCA-ITN-rainbow/GRIT", "max_issues_repo_head_hexsha": "1bdfb0735515e9d462214f66b88a71aabf836d76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2018-05-06T21:08:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-11T17:59:00.000Z", "max_forks_repo_path": "GRIT/unit_tests/glue_matrix_assembly/glue_matrix_assembly.cpp", "max_forks_repo_name": "misztal/GRIT", "max_forks_repo_head_hexsha": "6850fec967c9de7c6c501f5067d021ef5288b88e", "max_forks_repo_licenses": ["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.7684563758, "max_line_length": 93, "alphanum_fraction": 0.6593069747, "num_tokens": 7811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225279, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.5293081649517242}}
{"text": "#include \"stdafx.h\"\n\n#include \"problem.hpp\"\n\n#include <fstream>\n\n#include <boost/algorithm/string.hpp>\n\nstruct advent_2017_2 : problem\n{\n\tadvent_2017_2() noexcept : problem(2017, 2) {\n\t}\n\n\tusing row         = std::vector<std::size_t>;\n\tusing spreadsheet = std::vector<row>;\n\nprotected:\n\tspreadsheet ss;\n\n\tvoid prepare_input(std::ifstream& fin) override {\n\t\t//auto const ss = spreadsheet(\n\t\t//        input | ranges::view::split(is_char('\\n'))\n\t\t//              | ranges::view::transform([](const std::string& line) -> row {\n\t\t//                return line | ranges::view::split(is_char('\\t'))\n\t\t//                            | ranges::view::transform(ranges::convert_to<std::size_t>{});\n\t\t//                })\n\t\t//);\n\n\t\tfor(std::string line; std::getline(fin, line);) {\n\t\t\tstd::vector<std::string> cells;\n\t\t\tboost::split(cells, line, [](char c) { return c == '\\t'; });\n\t\t\trow r;\n\t\t\tstd::transform(begin(cells), end(cells), std::back_inserter(r), [](const std::string& s) { return std::stoull(s); });\n\t\t\tss.push_back(r);\n\t\t}\n\t}\n\n\tstd::string part_1() override {\n\t\tstd::size_t running_checksum = 0;\n\t\tfor(const row& r : ss) {\n\t\t\tconst auto mm = std::minmax_element(begin(r), end(r));\n\t\t\trunning_checksum += *mm.second - *mm.first;\n\t\t}\n\t\treturn std::to_string(running_checksum);\n\t}\n\n\tstd::string part_2() override {\n\t\tstd::size_t running_sum = 0;\n\t\tfor(const row& r : ss) {\n\t\t\tconst std::size_t end = r.size();\n\t\t\tfor(size_t i = 0; i != end; ++i) {\n\t\t\t\tfor(size_t j = 0; j != end; ++j) {\n\t\t\t\t\tif(i == j) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif(r[i] % r[j] == 0) {\n\t\t\t\t\t\trunning_sum += r[i] / r[j];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn std::to_string(running_sum);\n\t}\n};\n\nREGISTER_SOLVER(2017, 2);\n", "meta": {"hexsha": "cfa6e00a744a1a82162b3bfd28a40d5ebd15f1ae", "size": 1681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc/src/2017/day-2.cpp", "max_stars_repo_name": "DrPizza/advent-of-code-2017", "max_stars_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-09T06:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-18T12:15:08.000Z", "max_issues_repo_path": "aoc/src/2017/day-2.cpp", "max_issues_repo_name": "DrPizza/advent-of-code-2017", "max_issues_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-03T17:46:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-03T17:46:56.000Z", "max_forks_repo_path": "aoc/src/2017/day-2.cpp", "max_forks_repo_name": "DrPizza/advent-of-code", "max_forks_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "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": 25.0895522388, "max_line_length": 120, "alphanum_fraction": 0.5704937537, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5293081649517242}}
{"text": "//\n//=======================================================================\n// Copyright 2002 Marc Wintermantel (wintermantel@imes.mavt.ethz.ch)\n// ETH Zurich, Center of Structure Technologies (www.imes.ethz.ch/st)\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\n\n#include <boost/config.hpp>\n#include <vector>\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/sloan_ordering.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/bandwidth.hpp>\n#include <boost/graph/profile.hpp>\n#include <boost/graph/wavefront.hpp>\n\n\nusing std::cout;\nusing std::endl;\n\n/*\n  Sample Output\n  #####################################\n  ### First light of sloan-ordering ###\n  #####################################\n\n  original bandwidth: 8\n  original profile: 42\n  original max_wavefront: 7\n  original aver_wavefront: 4.2\n  original rms_wavefront: 4.58258\n\n  Starting vertex: 0\n  Pseudoperipheral vertex: 9\n  Pseudoperipheral radius: 4\n\n  Sloan ordering starting at: 0\n    0 8 3 7 5 2 4 6 1 9\n    bandwidth: 4\n    profile: 28\n    max_wavefront: 4\n    aver_wavefront: 2.8\n    rms_wavefront: 2.93258\n\n  Sloan ordering without a start-vertex:\n    8 0 3 7 5 2 4 6 1 9\n    bandwidth: 4\n    profile: 27\n    max_wavefront: 4\n    aver_wavefront: 2.7\n    rms_wavefront: 2.84605\n\n  ###############################\n  ### sloan-ordering finished ###\n  ###############################\n*/\n\nint main(int , char* [])\n{\n  cout << endl;  \n  cout << \"#####################################\" << endl; \n  cout << \"### First light of sloan-ordering ###\" << endl;\n  cout << \"#####################################\" << endl << endl;\n\n  using namespace boost;\n  using namespace std;\n \n\n  //Defining the graph type \n  typedef adjacency_list<\n    setS, \n    vecS, \n    undirectedS, \n    property<\n    vertex_color_t, \n    default_color_type,\n    property<\n    vertex_degree_t,\n    int,\n    property<\n    vertex_priority_t,\n    double > > > > Graph;\n  \n  typedef graph_traits<Graph>::vertex_descriptor Vertex;\n  typedef graph_traits<Graph>::vertices_size_type size_type;\n\n  typedef std::pair<std::size_t, std::size_t> Pair;\n  \n  Pair edges[14] = { Pair(0,3), //a-d\n                     Pair(0,5),  //a-f\n                     Pair(1,2),  //b-c\n                     Pair(1,4),  //b-e\n                     Pair(1,6),  //b-g\n                     Pair(1,9),  //b-j\n                     Pair(2,3),  //c-d\n                     Pair(2,4),  //c-e\n                     Pair(3,5),  //d-f\n                     Pair(3,8),  //d-i\n                     Pair(4,6),  //e-g\n                     Pair(5,6),  //f-g\n                     Pair(5,7),  //f-h\n                     Pair(6,7) }; //g-h \n \n  \n  //Creating a graph and adding the edges from above into it\n  Graph G(10);\n  for (int i = 0; i < 14; ++i)\n    add_edge(edges[i].first, edges[i].second, G);\n\n  //Creating two iterators over the vertices\n  graph_traits<Graph>::vertex_iterator ui, ui_end;\n\n  //Creating a property_map with the degrees of the degrees of each vertex\n  property_map<Graph,vertex_degree_t>::type deg = get(vertex_degree, G);\n  for (boost::tie(ui, ui_end) = vertices(G); ui != ui_end; ++ui)\n    deg[*ui] = degree(*ui, G);\n\n  //Creating a property_map for the indices of a vertex\n  property_map<Graph, vertex_index_t>::type index_map = get(vertex_index, G);\n\n  std::cout << \"original bandwidth: \" << bandwidth(G) << std::endl;\n  std::cout << \"original profile: \" << profile(G) << std::endl;\n  std::cout << \"original max_wavefront: \" << max_wavefront(G) << std::endl;\n  std::cout << \"original aver_wavefront: \" << aver_wavefront(G) << std::endl;\n  std::cout << \"original rms_wavefront: \" << rms_wavefront(G) << std::endl;\n  \n\n  //Creating a vector of vertices  \n  std::vector<Vertex> sloan_order(num_vertices(G));\n  //Creating a vector of size_type  \n  std::vector<size_type> perm(num_vertices(G));\n\n  {\n    \n    //Setting the start node\n    Vertex s = vertex(0, G);\n    int ecc;   //defining a variable for the pseudoperipheral radius\n    \n    //Calculating the pseudoeperipheral node and radius\n    Vertex e = pseudo_peripheral_pair(G, s, ecc, get(vertex_color, G), get(vertex_degree, G) );\n\n    cout << endl;\n    cout << \"Starting vertex: \" << s << endl;\n    cout << \"Pseudoperipheral vertex: \" << e << endl;\n    cout << \"Pseudoperipheral radius: \" << ecc << endl << endl;\n\n\n\n    //Sloan ordering\n    sloan_ordering(G, s, e, sloan_order.begin(), get(vertex_color, G), \n                           get(vertex_degree, G), get(vertex_priority, G));\n    \n    cout << \"Sloan ordering starting at: \" << s << endl;\n    cout << \"  \";    \n    \n    for (std::vector<Vertex>::const_iterator i = sloan_order.begin();\n         i != sloan_order.end(); ++i)\n      cout << index_map[*i] << \" \";\n    cout << endl;\n\n    for (size_type c = 0; c != sloan_order.size(); ++c)\n      perm[index_map[sloan_order[c]]] = c;\n    std::cout << \"  bandwidth: \" \n              << bandwidth(G, make_iterator_property_map(&perm[0], index_map, perm[0]))\n              << std::endl;\n    std::cout << \"  profile: \" \n              << profile(G, make_iterator_property_map(&perm[0], index_map, perm[0]))\n              << std::endl;\n    std::cout << \"  max_wavefront: \" \n              << max_wavefront(G, make_iterator_property_map(&perm[0], index_map, perm[0]))\n              << std::endl;\n    std::cout << \"  aver_wavefront: \" \n              << aver_wavefront(G, make_iterator_property_map(&perm[0], index_map, perm[0]))\n              << std::endl;\n    std::cout << \"  rms_wavefront: \" \n              << rms_wavefront(G, make_iterator_property_map(&perm[0], index_map, perm[0]))\n              << std::endl;\n  }\n  \n\n\n\n    /////////////////////////////////////////////////\n    //Version including finding a good starting point\n    /////////////////////////////////////////////////\n   \n    {\n      //sloan_ordering\n      sloan_ordering(G, sloan_order.begin(), \n                        get(vertex_color, G),\n                        make_degree_map(G), \n                        get(vertex_priority, G) );\n      \n      cout << endl << \"Sloan ordering without a start-vertex:\" << endl;\n      cout << \"  \";\n      for (std::vector<Vertex>::const_iterator i=sloan_order.begin();\n           i != sloan_order.end(); ++i)\n        cout << index_map[*i] << \" \";\n      cout << endl;\n      \n      for (size_type c = 0; c != sloan_order.size(); ++c)\n        perm[index_map[sloan_order[c]]] = c;\n      std::cout << \"  bandwidth: \" \n                << bandwidth(G, make_iterator_property_map(&perm[0], index_map, perm[0]))\n                << std::endl;\n      std::cout << \"  profile: \" \n                << profile(G, make_iterator_property_map(&perm[0], index_map, perm[0]))\n                << std::endl;\n      std::cout << \"  max_wavefront: \" \n                << max_wavefront(G, make_iterator_property_map(&perm[0], index_map, perm[0]))\n                << std::endl;\n      std::cout << \"  aver_wavefront: \" \n                << aver_wavefront(G, make_iterator_property_map(&perm[0], index_map, perm[0]))\n                << std::endl;\n      std::cout << \"  rms_wavefront: \" \n                << rms_wavefront(G, make_iterator_property_map(&perm[0], index_map, perm[0]))\n                << std::endl;\n    }\n  \n\n  \n  cout << endl;\n  cout << \"###############################\" << endl;\n  cout << \"### sloan-ordering finished ###\" << endl;\n  cout << \"###############################\" << endl << endl;\n  return 0;\n\n}\n", "meta": {"hexsha": "e53e3552df8a86789565792b039c8a534ebab680", "size": 7590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/graph/example/sloan_ordering.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/graph/example/sloan_ordering.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/graph/example/sloan_ordering.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 32.2978723404, "max_line_length": 95, "alphanum_fraction": 0.5317523057, "num_tokens": 1998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5293081649517242}}
{"text": "/**\n * @file orientation.cc\n */\n#include <usml/sensors/orientation.h>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace usml::sensors ;\n\n/**\n * Default constructor\n */\norientation::orientation()\n    : _heading(0.0), _pitch(0.0), _roll(0.0),\n      _axis(3,0)\n{\n\n}\n\n/**\n * Pitch, heading, roll constructor\n */\norientation::orientation(\n    double heading, double pitch, double roll,\n    vector<double> ref_axis )\n    : _heading(-pitch*M_PI/180.0),\n      _pitch(-heading*M_PI/180.0),\n      _roll(roll*M_PI/180.0),\n      _axis(ref_axis)\n{\n    apply_rotation() ;\n}\n\n/**\n * Tilt angle/direction constructor\n */\norientation::orientation( double angle, double direction )\n    : _heading(0.0), _pitch(0.0), _roll(0.0),\n      _axis(3,0)\n{\n    compute_orientation(angle,direction) ;\n}\n\n/**\n * Destructor\n */\norientation::~orientation()\n{\n\n}\n\n/**\n * Computes pitch, heading, and roll as a function angle/direction from\n * the vertical reference axis\n */\nvoid orientation::compute_orientation(double angle, double direction)\n{\n    if( angle <= M_PI_2 ) {\n        double sin_theta2 = sin(angle)*sin(angle) ;\n        double sin_phi2 = sin(direction)*sin(direction) ;\n        double sqrt_theta_phi = std::sqrt(1 - sin_theta2*sin_phi2) ;\n        _roll = std::atan2( (cos(angle) / sqrt_theta_phi) , (cos(direction)*sin(angle) / sqrt_theta_phi) ) ;\n        _pitch = std::atan2( sqrt_theta_phi, (-sin(angle)*sin(direction)) ) ;\n        _heading = 0.0 ;\n    } else {\n        _pitch = angle ;\n        _heading = direction ;\n        _roll = 0.0 ;\n    }\n}\n\n/**\n * Applies a rotation from one coordinate system to the\n * current rotated coordinates for asymmetric systems.\n */\nvoid orientation::apply_rotation(\n    double& de, double& az,\n    double* de_prime, double* az_prime )\n{\n    _theta = M_PI_2 - de ;\n    _phi = az ;\n    _axis(0) = sin(_theta) * cos(_phi) ;\n    _axis(1) = sin(_theta) * sin(_phi) ;\n    _axis(2) = cos(_theta) ;\n    apply_rotation() ;\n    *de_prime = M_PI_2 - _theta ;\n    *az_prime = _phi ;\n}\n\n\n/**\n * Updates the heading, pitch, and roll\n */\nvoid orientation::update_orientation( double h, double p, double r )\n{\n   _heading = -h*M_PI/180.0 ;\n   _pitch = -p*M_PI/180.0 ;\n   _roll = r*M_PI/180.0 ;\n   apply_rotation() ;\n}\n\n/**\n* Updates the tilt angle and direction.\n*/\nvoid orientation::update_orientation(double angle, double direction)\n{\n    compute_orientation(angle,direction) ;\n}\n\n/**\n * Applies a rotation from one coordinate system to the\n * current rotated coordinates for symmetric systems.\n */\nvoid orientation::apply_rotation()\n{\n    _x = _axis(0)*cos(_heading)*cos(_roll) +\n         _axis(2)*( sin(_heading)*sin(_pitch) + cos(_heading)*cos(_pitch)*sin(_roll) ) +\n         _axis(1)*( -cos(_pitch)*sin(_heading) + cos(_heading)*sin(_pitch)*sin(_roll) ) ;\n    _y = _axis(0)*cos(_roll)*sin(_heading) +\n         _axis(2)*( -cos(_heading)*sin(_pitch) + cos(_pitch)*sin(_heading)*sin(_roll) ) +\n         _axis(1)*( cos(_heading)*cos(_pitch) + sin(_heading)*sin(_pitch)*sin(_roll) ) ;\n    _z = _axis(2)*cos(_pitch)*cos(_roll) +\n         _axis(1)*cos(_roll)*sin(_pitch) -\n         _axis(0)*sin(_roll) ;\n    convert_to_spherical() ;\n}\n\n/**\n * Converts the store vector in spherical coordinates to\n * cartesian coordinates.\n */\nvoid orientation::convert_to_cartesian()\n{\n    _x = sin(_theta) * cos(_phi) ;\n    _y = sin(_theta) * sin(_phi) ;\n    _z = cos(_theta) ;\n}\n\n/**\n * Converts the stored vector in cartesian coordinates to\n * spherical coordinates.\n */\nvoid orientation::convert_to_spherical()\n{\n//    double rho = std::sqrt( _x*_x + _y*_y + _z*_z ) ;\n    _theta = std::acos( _z - 1e-10 ) ;\n    _theta = std::fmod( _theta, M_PI ) ;\n    _phi = std::atan2( _y, _x ) ;\n    _phi = std::fmod( _phi, 2.0*M_PI ) ;\n}\n", "meta": {"hexsha": "07f7fbe774431c7f8c939ddca96578fcadac7402", "size": 3722, "ext": "cc", "lang": "C++", "max_stars_repo_path": "sensors/orientation.cc", "max_stars_repo_name": "fraclipe/UnderSeaModelingLibrary", "max_stars_repo_head_hexsha": "52ef9dd03c7cbe548749e4527190afe7668ff4e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-07T14:48:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T14:48:22.000Z", "max_issues_repo_path": "sensors/orientation.cc", "max_issues_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_issues_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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": "sensors/orientation.cc", "max_forks_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_forks_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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.8133333333, "max_line_length": 108, "alphanum_fraction": 0.631380978, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5292038636955415}}
{"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 <random>\n\n#include <Eigen/Eigenvalues>\n\n#include \"teaser/registration.h\"\n#include \"teaser/macros.h\"\n#include \"test_utils.h\"\n\nTEST(ScaleSolverTest, UnknownScale) {\n  double ACCEPTABLE_ERROR = 1e-5;\n\n  // Read in data\n  std::ifstream objectFile(\"./data/registration_test/objectIn.csv\");\n  auto object_points = teaser::test::readFileToEigenMatrix<double, 3, Eigen::Dynamic>(objectFile);\n\n  // Problem 1: No scaling\n  {\n    // Prepare parameters & solver\n    double noise_bound = 1; // arbitrary\n    int cbar2 = 1;          // arbitrary\n    teaser::TLSScaleSolver solver(noise_bound, cbar2);\n\n    // Solve for scale\n    double actual_scale = 0;\n    double expected_scale = 1;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> actual_inliers;\n    actual_inliers.resize(1, object_points.cols());\n    solver.solveForScale(object_points, object_points, &actual_scale, &actual_inliers);\n\n    // Compare with expected values\n    EXPECT_NEAR(expected_scale, actual_scale, ACCEPTABLE_ERROR);\n  }\n  // Problem 2: Random scaling\n  {\n    // Prepare parameters & solver\n    double noise_bound = 1; // arbitrary\n    int cbar2 = 1;          // arbitrary\n    teaser::TLSScaleSolver solver(noise_bound, cbar2);\n\n    // Scaling input points by a random value\n    std::uniform_real_distribution<double> unif(0, 5);\n    std::default_random_engine re;\n    double expected_scale = unif(re);\n    Eigen::Matrix<double, 3, Eigen::Dynamic> scaled_points = object_points.array() * expected_scale;\n\n    // Solve for scale\n    double actual_scale = 0;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> actual_inliers;\n    actual_inliers.resize(1, object_points.cols());\n    solver.solveForScale(object_points, scaled_points, &actual_scale, &actual_inliers);\n\n    // Compare with expected values\n    EXPECT_NEAR(expected_scale, actual_scale, ACCEPTABLE_ERROR);\n  }\n}\n\nTEST(ScaleSolverTest, FixedScale) {\n  // Read in data\n  std::ifstream objectFile(\"./data/registration_test/objectIn.csv\");\n  auto object_points = teaser::test::readFileToEigenMatrix<double, 3, Eigen::Dynamic>(objectFile);\n\n  // Problem 1: No outliers\n  {\n    double noise_bound = 1; // arbitrary\n    int cbar2 = 1;          // arbitrary\n    teaser::ScaleInliersSelector solver(noise_bound, cbar2);\n\n    double actual_scale = 0;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> actual_inliers;\n    actual_inliers.resize(1, object_points.cols());\n    solver.solveForScale(object_points, object_points, &actual_scale, &actual_inliers);\n\n    EXPECT_EQ(actual_scale, 1);\n    for (size_t i = 0; i < actual_inliers.cols(); ++i) {\n      EXPECT_TRUE(actual_inliers(0, i));\n    }\n  }\n  // Problem 2: All outliers\n  {\n    double noise_bound = 1; // arbitrary\n    int cbar2 = 1;          // arbitrary\n    // shift & scale the points so all points will be outliers\n    Eigen::Matrix<double, 3, Eigen::Dynamic> shifted_object = object_points.array() * 3 + 10;\n    teaser::ScaleInliersSelector solver(noise_bound, cbar2);\n\n    double actual_scale = 0;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> actual_inliers;\n    actual_inliers.resize(1, object_points.cols());\n    solver.solveForScale(object_points, shifted_object, &actual_scale, &actual_inliers);\n\n    EXPECT_EQ(actual_scale, 1);\n    for (size_t i = 0; i < actual_inliers.cols(); ++i) {\n      EXPECT_FALSE(actual_inliers(0, i));\n    }\n  }\n  // Problem 3: One outlier\n  {\n    double noise_bound = 1; // arbitrary\n    int cbar2 = 1;          // arbitrary\n    // shift & scale the points so all points will be outliers\n    Eigen::Matrix<double, 3, Eigen::Dynamic> shifted_object = object_points.array();\n    shifted_object.col(0).array() *= 10;\n    teaser::ScaleInliersSelector solver(noise_bound, cbar2);\n\n    double actual_scale = 0;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> actual_inliers;\n    actual_inliers.resize(1, object_points.cols());\n    solver.solveForScale(object_points, shifted_object, &actual_scale, &actual_inliers);\n\n    EXPECT_EQ(actual_scale, 1);\n    EXPECT_FALSE(actual_inliers(0, 0));\n    for (size_t i = 1; i < actual_inliers.cols(); ++i) {\n      EXPECT_TRUE(actual_inliers(0, i));\n    }\n  }\n}\n", "meta": {"hexsha": "ab9d6c9ae927dc6e873daff6a00e3a3394c94bed", "size": 4408, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/teaser/scale-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/scale-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/scale-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": 33.6488549618, "max_line_length": 100, "alphanum_fraction": 0.693738657, "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6334102636778403, "lm_q1q2_score": 0.5292038579138701}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"EntropyRegularizedBinaryPhrase\"\n\n#include <cmath>\n#include <algorithm>\n#include <boost/test/unit_test.hpp>\nnamespace utf = boost::unit_test;\n\n#include \"diffdp/algorithm/binary_phrase.h\"\n\n// using boost test with intolerance fails (too precise),\n// so let's just use the same test as in Dynet.\nbool check_grad(float g, float g_act)\n{\n    float f = std::fabs(g - g_act);\n    float m = std::max(std::fabs(g), std::fabs(g_act));\n    if (f > 0.01 && m > 0.f)\n        f /= m;\n\n    if (f > 0.01 || std::isnan(f))\n        return false;\n    else\n        return true;\n}\n\nBOOST_AUTO_TEST_CASE(first_order_gradient, * utf::tolerance(1e-2f))\n{\n    const unsigned size = 10;\n    const float sensitivity = 1e-2;\n\n    std::vector<float> weights(size * size);\n    for (unsigned i = 0 ; i < size ; ++i)\n        weights.at(i) = size;\n\n    diffdp::EntropyRegularizedBinaryPhraseStructure parser(size);\n        parser.forward(\n        [&] (unsigned left, unsigned right) -> float\n        {\n            return weights.at(left + right * size);\n        }\n    );\n\n    for (unsigned left = 0 ; left < size ; ++left)\n    {\n        for (unsigned right = left + 1; right < size ; ++right)\n        {\n            const float computed_arc = parser.output(left, right);\n\n            // estimate the gradient\n            const float original_weights = weights.at(left + right * size);\n\n            weights.at(left + right * size) = original_weights + sensitivity;\n            diffdp::EntropyRegularizedBinaryPhraseStructure parser2(size);\n                parser2.forward(\n                [&] (const unsigned left, const unsigned right) -> float\n                {\n                    return weights.at(left + right * size);\n                }\n            );\n            const float output_a = parser2.chart_forward->weight(0, size-1);\n\n            weights.at(left + right * size) = original_weights - sensitivity;\n            parser2.forward(\n            [&] (const unsigned left, const unsigned right) -> float\n                {\n                    return weights.at(left + right * size);\n                }\n            );\n            const float output_b = parser2.chart_forward->weight(0, size-1);\n\n            // restore\n            weights.at(left + right * size) = original_weights;\n\n            const float estimated_arc = (output_a - output_b) / (2.f * sensitivity);\n\n            BOOST_CHECK(check_grad(computed_arc, estimated_arc));\n        }\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(second_order_gradient, * utf::tolerance(1e-2f))\n{\n    const unsigned size = 10;\n    const float sensitivity = 1e-5;\n\n    std::vector<float> weights(size * size);\n    for (unsigned i = 0 ; i < size ; ++i)\n    weights.at(i) = size;\n\n    diffdp::EntropyRegularizedBinaryPhraseStructure parser(size);\n    parser.forward(\n        [&] (unsigned left, unsigned right) -> float\n        {\n            return weights.at(left + right * size);\n        }\n    );\n\n    for (unsigned input_left = 0 ; input_left < size ; ++input_left)\n    {\n        for (unsigned input_right = input_left + 1; input_right < size ; ++input_right)\n        {\n            for (unsigned output_left = 0 ; output_left < size ; ++output_left)\n            {\n                for (unsigned output_right = output_left + 1; output_right < size; ++output_right)\n                {\n                    parser.backward(\n                        [&](const unsigned left, const unsigned right)\n                        {\n                            if (left == output_left && right == output_right)\n                                return 1.f;\n                            else\n                                return 0.f;\n                        }\n                    );\n                    const float computed_gradient = parser.gradient(input_left, input_right);\n\n                    // estimate the gradient\n                    const float sensitivity = 1e-3;\n                    const float original_weights = weights.at(input_left + input_right * size);\n\n                    weights.at(input_left + input_right * size) = original_weights + sensitivity;\n                        diffdp::EntropyRegularizedBinaryPhraseStructure parser2(size);\n                        parser2.forward(\n                        [&](const unsigned left, const unsigned right) -> float\n                        {\n                            return weights.at(left + right * size);\n                        }\n                    );\n                    const float output_a = parser2.output(output_left, output_right);\n\n                    weights.at(input_left + input_right * size) = original_weights - sensitivity;\n                        parser2.forward(\n                        [&](const unsigned left, const unsigned right) -> float\n                        {\n                            return weights.at(left + right * size);\n                        }\n                    );\n                    const float output_b = parser2.output(output_left, output_right);\n\n                    // restore\n                    weights.at(input_left + input_right * size) = original_weights;\n\n                    const double estimated_gradient = (output_a - output_b) / (2.f * sensitivity);\n                    BOOST_CHECK(check_grad(computed_gradient, estimated_gradient));\n                }\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "41a751526e321dc79ca2101e7dd63103d89c086f", "size": 5340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test-binary-phrase-ereg.cpp", "max_stars_repo_name": "FilippoC/diffdp", "max_stars_repo_head_hexsha": "58ae35b171ddd54b778790bc64838890c0f8956f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2019-03-18T21:17:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:06:30.000Z", "max_issues_repo_path": "test/test-binary-phrase-ereg.cpp", "max_issues_repo_name": "FilippoC/diffdp", "max_issues_repo_head_hexsha": "58ae35b171ddd54b778790bc64838890c0f8956f", "max_issues_repo_licenses": ["MIT"], "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-binary-phrase-ereg.cpp", "max_forks_repo_name": "FilippoC/diffdp", "max_forks_repo_head_hexsha": "58ae35b171ddd54b778790bc64838890c0f8956f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-12-10T15:04:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T17:41:57.000Z", "avg_line_length": 35.3642384106, "max_line_length": 98, "alphanum_fraction": 0.5280898876, "num_tokens": 1080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414786, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5291989818611839}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2010 - 2020 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: Guido Kanschat, Texas A&M University, 2009 \n */ \n\n\n\n// \u7ebf\u6027\u4ee3\u6570\u7684\u5305\u542b\u6587\u4ef6\u3002\u4e00\u4e2a\u666e\u901a\u7684SparseMatrix\uff0c\u5b83\u53c8\u5c06\u5305\u62ecSparsityPattern\u548cVector\u7c7b\u7684\u5fc5\u8981\u6587\u4ef6\u3002\n\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/precondition_block.h> \n#include <deal.II/lac/block_vector.h> \n\n// \u5305\u62ec\u7528\u4e8e\u8bbe\u7f6e\u7f51\u683c\u7684\u6587\u4ef6\n\n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_refinement.h> \n\n// FiniteElement\u7c7b\u548cDoFHandler\u7684\u5305\u542b\u6587\u4ef6\u3002\n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_dgp.h> \n#include <deal.II/fe/fe_dgq.h> \n#include <deal.II/dofs/dof_tools.h> \n\n// \u4f7f\u7528MeshWorker\u6846\u67b6\u7684\u5305\u542b\u6587\u4ef6\n\n#include <deal.II/meshworker/dof_info.h> \n#include <deal.II/meshworker/integration_info.h> \n#include <deal.II/meshworker/assembler.h> \n#include <deal.II/meshworker/loop.h> \n\n// \u4e0e\u62c9\u666e\u62c9\u65af\u76f8\u5173\u7684\u5c40\u90e8\u79ef\u5206\u5668\u7684\u5305\u542b\u6587\u4ef6\n\n#include <deal.II/integrators/laplace.h> \n\n// \u652f\u6301\u591a\u7f51\u683c\u65b9\u6cd5\n\n#include <deal.II/multigrid/mg_tools.h> \n#include <deal.II/multigrid/multigrid.h> \n#include <deal.II/multigrid/mg_matrix.h> \n#include <deal.II/multigrid/mg_transfer.h> \n#include <deal.II/multigrid/mg_coarse.h> \n#include <deal.II/multigrid/mg_smoother.h> \n\n// \u6700\u540e\uff0c\u6211\u4eec\u4ece\u5e93\u4e2d\u53d6\u51fa\u6211\u4eec\u7684\u7cbe\u786e\u89e3\uff0c\u4ee5\u53ca\u6b63\u4ea4\u548c\u9644\u52a0\u5de5\u5177\u3002\n\n#include <deal.II/base/function_lib.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/data_out.h> \n\n#include <iostream> \n#include <fstream> \n\n// deal.II\u5e93\u7684\u6240\u6709\u7c7b\u90fd\u5728dealii\u547d\u540d\u7a7a\u95f4\u4e2d\u3002\u4e3a\u4e86\u8282\u7701\u6253\u5b57\uff0c\u6211\u4eec\u544a\u8bc9\u7f16\u8bd1\u5668\u4e5f\u8981\u5728\u5176\u4e2d\u641c\u7d22\u540d\u5b57\u3002\n\nnamespace Step39 \n{ \n  using namespace dealii; \n\n// \u8fd9\u662f\u6211\u4eec\u7528\u6765\u8bbe\u7f6e\u8fb9\u754c\u503c\u7684\u51fd\u6570\uff0c\u4e5f\u662f\u6211\u4eec\u6bd4\u8f83\u7684\u7cbe\u786e\u89e3\u3002\n\n  Functions::SlitSingularityFunction<2> exact_solution; \n// @sect3{The local integrators}  \n\n// MeshWorker\u5c06\u5c40\u90e8\u79ef\u5206\u4e0e\u5355\u5143\u683c\u548c\u9762\u7684\u5faa\u73af\u5206\u79bb\u5f00\u6765\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5fc5\u987b\u7f16\u5199\u5c40\u90e8\u79ef\u5206\u7c7b\u6765\u751f\u6210\u77e9\u9635\u3001\u53f3\u624b\u8fb9\u548c\u8bef\u5dee\u4f30\u8ba1\u5668\u3002\n\n// \u6240\u6709\u8fd9\u4e9b\u7c7b\u90fd\u6709\u76f8\u540c\u7684\u4e09\u4e2a\u51fd\u6570\uff0c\u5206\u522b\u7528\u4e8e\u5bf9\u5355\u5143\u3001\u8fb9\u754c\u9762\u548c\u5185\u90e8\u9762\u7684\u79ef\u5206\u3002\u5c40\u90e8\u79ef\u5206\u6240\u9700\u7684\u6240\u6709\u4fe1\u606f\u90fd\u7531 MeshWorker::IntegrationInfo<dim>. \u63d0\u4f9b\u3002\u8bf7\u6ce8\u610f\uff0c\u51fd\u6570\u7684\u7b7e\u540d\u4e0d\u80fd\u6539\u53d8\uff0c\u56e0\u4e3a\u5b83\u662f\u7531 MeshWorker::integration_loop(). \u6240\u671f\u671b\u7684\u3002\n\n// \u7b2c\u4e00\u4e2a\u5b9a\u4e49\u5c40\u90e8\u79ef\u5206\u5668\u7684\u7c7b\u8d1f\u8d23\u8ba1\u7b97\u5355\u5143\u548c\u9762\u77e9\u9635\u3002\u5b83\u88ab\u7528\u6765\u7ec4\u88c5\u5168\u5c40\u77e9\u9635\u4ee5\u53ca\u6c34\u5e73\u77e9\u9635\u3002\n\n  template <int dim> \n  class MatrixIntegrator : public MeshWorker::LocalIntegrator<dim> \n  { \n  public: \n    void cell(MeshWorker::DoFInfo<dim> &                 dinfo, \n              typename MeshWorker::IntegrationInfo<dim> &info) const override; \n    void \n         boundary(MeshWorker::DoFInfo<dim> &                 dinfo, \n                  typename MeshWorker::IntegrationInfo<dim> &info) const override; \n    void face(MeshWorker::DoFInfo<dim> &                 dinfo1, \n              MeshWorker::DoFInfo<dim> &                 dinfo2, \n              typename MeshWorker::IntegrationInfo<dim> &info1, \n              typename MeshWorker::IntegrationInfo<dim> &info2) const override; \n  }; \n\n// \u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\uff0c\u6211\u4eec\u5bf9Dirichlet\u5f62\u5f0f\u8fdb\u884c\u79ef\u5206\u3002\u6211\u4eec\u4f7f\u7528LocalIntegrators\u4e2d\u7684\u73b0\u6210\u79ef\u5206\u5e93\u6765\u907f\u514d\u81ea\u5df1\u7f16\u5199\u8fd9\u4e9b\u5faa\u73af\u3002\u540c\u6837\u5730\uff0c\u6211\u4eec\u5b9e\u73b0\u4e86Nitsche\u8fb9\u754c\u6761\u4ef6\u548c\u5355\u5143\u95f4\u7684\u5185\u90e8\u60e9\u7f5a\u901a\u91cf\u3002\n\n// \u8fb9\u754c\u548c\u901a\u91cf\u9879\u9700\u8981\u4e00\u4e2a\u60e9\u7f5a\u53c2\u6570\uff0c\u8fd9\u4e2a\u53c2\u6570\u5e94\u8be5\u6839\u636e\u5355\u5143\u7684\u5927\u5c0f\u548c\u591a\u9879\u5f0f\u7684\u5ea6\u6570\u6765\u8c03\u6574\u3002\u5728 LocalIntegrators::Laplace::compute_penalty() \u4e2d\u53ef\u4ee5\u627e\u5230\u5173\u4e8e\u8fd9\u4e2a\u53c2\u6570\u7684\u5b89\u5168\u9009\u62e9\uff0c\u6211\u4eec\u5728\u4e0b\u9762\u4f7f\u7528\u8fd9\u4e2a\u53c2\u6570\u3002\n\n  template <int dim> \n  void MatrixIntegrator<dim>::cell( \n    MeshWorker::DoFInfo<dim> &                 dinfo, \n    typename MeshWorker::IntegrationInfo<dim> &info) const \n  { \n    LocalIntegrators::Laplace::cell_matrix(dinfo.matrix(0, false).matrix, \n                                           info.fe_values()); \n  } \n\n  template <int dim> \n  void MatrixIntegrator<dim>::boundary( \n    MeshWorker::DoFInfo<dim> &                 dinfo, \n    typename MeshWorker::IntegrationInfo<dim> &info) const \n  { \n    const unsigned int degree = info.fe_values(0).get_fe().tensor_degree(); \n    LocalIntegrators::Laplace::nitsche_matrix( \n      dinfo.matrix(0, false).matrix, \n      info.fe_values(0), \n      LocalIntegrators::Laplace::compute_penalty(dinfo, dinfo, degree, degree)); \n  } \n\n// \u5185\u90e8\u9762\u4f7f\u7528\u5185\u90e8\u60e9\u7f5a\u65b9\u6cd5\n\n  template <int dim> \n  void MatrixIntegrator<dim>::face( \n    MeshWorker::DoFInfo<dim> &                 dinfo1, \n    MeshWorker::DoFInfo<dim> &                 dinfo2, \n    typename MeshWorker::IntegrationInfo<dim> &info1, \n    typename MeshWorker::IntegrationInfo<dim> &info2) const \n  { \n    const unsigned int degree = info1.fe_values(0).get_fe().tensor_degree(); \n    LocalIntegrators::Laplace::ip_matrix( \n      dinfo1.matrix(0, false).matrix, \n      dinfo1.matrix(0, true).matrix, \n      dinfo2.matrix(0, true).matrix, \n      dinfo2.matrix(0, false).matrix, \n      info1.fe_values(0), \n      info2.fe_values(0), \n      LocalIntegrators::Laplace::compute_penalty( \n        dinfo1, dinfo2, degree, degree)); \n  } \n\n// \u7b2c\u4e8c\u4e2a\u5c40\u90e8\u79ef\u5206\u5668\u5efa\u7acb\u4e86\u53f3\u624b\u8fb9\u3002\u5728\u6211\u4eec\u7684\u4f8b\u5b50\u4e2d\uff0c\u53f3\u624b\u8fb9\u7684\u51fd\u6570\u4e3a\u96f6\uff0c\u8fd9\u6837\uff0c\u8fd9\u91cc\u53ea\u8bbe\u7f6e\u4e86\u5f31\u5f62\u5f0f\u7684\u8fb9\u754c\u6761\u4ef6\u3002\n\n  template <int dim> \n  class RHSIntegrator : public MeshWorker::LocalIntegrator<dim> \n  { \n  public: \n    void cell(MeshWorker::DoFInfo<dim> &                 dinfo, \n              typename MeshWorker::IntegrationInfo<dim> &info) const override; \n    void \n         boundary(MeshWorker::DoFInfo<dim> &                 dinfo, \n                  typename MeshWorker::IntegrationInfo<dim> &info) const override; \n    void face(MeshWorker::DoFInfo<dim> &                 dinfo1, \n              MeshWorker::DoFInfo<dim> &                 dinfo2, \n              typename MeshWorker::IntegrationInfo<dim> &info1, \n              typename MeshWorker::IntegrationInfo<dim> &info2) const override; \n  }; \n\n  template <int dim> \n  void \n  RHSIntegrator<dim>::cell(MeshWorker::DoFInfo<dim> &, \n                           typename MeshWorker::IntegrationInfo<dim> &) const \n  {} \n\n  template <int dim> \n  void RHSIntegrator<dim>::boundary( \n    MeshWorker::DoFInfo<dim> &                 dinfo, \n    typename MeshWorker::IntegrationInfo<dim> &info) const \n  { \n    const FEValuesBase<dim> &fe           = info.fe_values(); \n    Vector<double> &         local_vector = dinfo.vector(0).block(0); \n\n    std::vector<double> boundary_values(fe.n_quadrature_points); \n    exact_solution.value_list(fe.get_quadrature_points(), boundary_values); \n\n    const unsigned int degree = fe.get_fe().tensor_degree(); \n    const double penalty = 2. * degree * (degree + 1) * dinfo.face->measure() / \n                           dinfo.cell->measure(); \n\n    for (unsigned k = 0; k < fe.n_quadrature_points; ++k) \n      for (unsigned int i = 0; i < fe.dofs_per_cell; ++i) \n        local_vector(i) += \n          (-penalty * fe.shape_value(i, k)              // (-sigma * v_i(x_k) \n           + fe.normal_vector(k) * fe.shape_grad(i, k)) // + n * grad v_i(x_k)) \n          * boundary_values[k] * fe.JxW(k);             // u^D(x_k) * dx \n  } \n\n  template <int dim> \n  void \n  RHSIntegrator<dim>::face(MeshWorker::DoFInfo<dim> &, \n                           MeshWorker::DoFInfo<dim> &, \n                           typename MeshWorker::IntegrationInfo<dim> &, \n                           typename MeshWorker::IntegrationInfo<dim> &) const \n  {} \n\n//\u7b2c\u4e09\u4e2a\u5c40\u90e8\u79ef\u5206\u5668\u8d1f\u8d23\u5bf9\u8bef\u5dee\u4f30\u8ba1\u7684\u8d21\u732e\u3002\u8fd9\u662f\u7531Karakashian\u548cPascal\uff082003\uff09\u63d0\u51fa\u7684\u6807\u51c6\u80fd\u91cf\u4f30\u8ba1\u5668\u3002\n\n  template <int dim> \n  class Estimator : public MeshWorker::LocalIntegrator<dim> \n  { \n  public: \n    void cell(MeshWorker::DoFInfo<dim> &                 dinfo, \n              typename MeshWorker::IntegrationInfo<dim> &info) const override; \n    void \n         boundary(MeshWorker::DoFInfo<dim> &                 dinfo, \n                  typename MeshWorker::IntegrationInfo<dim> &info) const override; \n    void face(MeshWorker::DoFInfo<dim> &                 dinfo1, \n              MeshWorker::DoFInfo<dim> &                 dinfo2, \n              typename MeshWorker::IntegrationInfo<dim> &info1, \n              typename MeshWorker::IntegrationInfo<dim> &info2) const override; \n  }; \n\n// \u5355\u5143\u7684\u8d21\u732e\u662f\u79bb\u6563\u89e3\u7684\u62c9\u666e\u62c9\u65af\uff0c\u56e0\u4e3a\u53f3\u624b\u8fb9\u662f\u96f6\u3002\n\n  template <int dim> \n  void \n  Estimator<dim>::cell(MeshWorker::DoFInfo<dim> &                 dinfo, \n                       typename MeshWorker::IntegrationInfo<dim> &info) const \n  { \n    const FEValuesBase<dim> &fe = info.fe_values(); \n\n    const std::vector<Tensor<2, dim>> &DDuh = info.hessians[0][0]; \n    for (unsigned k = 0; k < fe.n_quadrature_points; ++k) \n      { \n        const double t = dinfo.cell->diameter() * trace(DDuh[k]); \n        dinfo.value(0) += t * t * fe.JxW(k); \n      } \n    dinfo.value(0) = std::sqrt(dinfo.value(0)); \n  } \n\n// \u5728\u8fb9\u754c\uff0c\u6211\u4eec\u7b80\u5355\u5730\u4f7f\u7528\u8fb9\u754c\u6b8b\u5dee\u7684\u52a0\u6743\u5f62\u5f0f\uff0c\u5373\u6709\u9650\u5143\u89e3\u548c\u6b63\u786e\u8fb9\u754c\u6761\u4ef6\u4e4b\u95f4\u7684\u5dee\u503c\u7684\u89c4\u8303\u3002\n\n  template <int dim> \n  void Estimator<dim>::boundary( \n    MeshWorker::DoFInfo<dim> &                 dinfo, \n    typename MeshWorker::IntegrationInfo<dim> &info) const \n  { \n    const FEValuesBase<dim> &fe = info.fe_values(); \n\n    std::vector<double> boundary_values(fe.n_quadrature_points); \n    exact_solution.value_list(fe.get_quadrature_points(), boundary_values); \n\n    const std::vector<double> &uh = info.values[0][0]; \n\n    const unsigned int degree = fe.get_fe().tensor_degree(); \n    const double penalty = 2. * degree * (degree + 1) * dinfo.face->measure() / \n                           dinfo.cell->measure(); \n\n    for (unsigned k = 0; k < fe.n_quadrature_points; ++k) \n      { \n        const double diff = boundary_values[k] - uh[k]; \n        dinfo.value(0) += penalty * diff * diff * fe.JxW(k); \n      } \n    dinfo.value(0) = std::sqrt(dinfo.value(0)); \n  } \n\n// \u6700\u540e\uff0c\u5728\u5185\u90e8\u9762\uff0c\u4f30\u8ba1\u5668\u7531\u89e3\u7684\u8df3\u8dc3\u548c\u5b83\u7684\u6cd5\u5411\u5bfc\u6570\u7ec4\u6210\uff0c\u5e76\u8fdb\u884c\u9002\u5f53\u7684\u52a0\u6743\u3002\n\n  template <int dim> \n  void \n  Estimator<dim>::face(MeshWorker::DoFInfo<dim> &                 dinfo1, \n                       MeshWorker::DoFInfo<dim> &                 dinfo2, \n                       typename MeshWorker::IntegrationInfo<dim> &info1, \n                       typename MeshWorker::IntegrationInfo<dim> &info2) const \n  { \n    const FEValuesBase<dim> &          fe   = info1.fe_values(); \n    const std::vector<double> &        uh1  = info1.values[0][0]; \n    const std::vector<double> &        uh2  = info2.values[0][0]; \n    const std::vector<Tensor<1, dim>> &Duh1 = info1.gradients[0][0]; \n    const std::vector<Tensor<1, dim>> &Duh2 = info2.gradients[0][0]; \n\n    const unsigned int degree = fe.get_fe().tensor_degree(); \n    const double       penalty1 = \n      degree * (degree + 1) * dinfo1.face->measure() / dinfo1.cell->measure(); \n    const double penalty2 = \n      degree * (degree + 1) * dinfo2.face->measure() / dinfo2.cell->measure(); \n    const double penalty = penalty1 + penalty2; \n    const double h       = dinfo1.face->measure(); \n\n    for (unsigned k = 0; k < fe.n_quadrature_points; ++k) \n      { \n        const double diff1 = uh1[k] - uh2[k]; \n        const double diff2 = \n          fe.normal_vector(k) * Duh1[k] - fe.normal_vector(k) * Duh2[k]; \n        dinfo1.value(0) += \n          (penalty * diff1 * diff1 + h * diff2 * diff2) * fe.JxW(k); \n      } \n    dinfo1.value(0) = std::sqrt(dinfo1.value(0)); \n    dinfo2.value(0) = dinfo1.value(0); \n  } \n\n// \u6700\u540e\u6211\u4eec\u6709\u4e00\u4e2a\u8bef\u5dee\u7684\u79ef\u5206\u5668\u3002\u7531\u4e8e\u4e0d\u8fde\u7eedGalerkin\u95ee\u9898\u7684\u80fd\u91cf\u51c6\u5219\u4e0d\u4ec5\u6d89\u53ca\u5230\u5355\u5143\u5185\u90e8\u7684\u68af\u5ea6\u5dee\uff0c\u8fd8\u6d89\u53ca\u5230\u8de8\u9762\u548c\u8fb9\u754c\u7684\u8df3\u8dc3\u9879\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u80fd\u4ec5\u4ec5\u4f7f\u7528  VectorTools::integrate_difference().  \u800c\u662f\u4f7f\u7528MeshWorker\u63a5\u53e3\u6765\u81ea\u5df1\u8ba1\u7b97\u8bef\u5dee\u3002\n\n//\u6709\u51e0\u79cd\u4e0d\u540c\u7684\u65b9\u6cd5\u6765\u5b9a\u4e49\u8fd9\u4e2a\u80fd\u91cf\u51c6\u5219\uff0c\u4f46\u662f\u6240\u6709\u7684\u65b9\u6cd5\u90fd\u662f\u968f\u7740\u7f51\u683c\u5927\u5c0f\u7684\u53d8\u5316\u800c\u7b49\u4ef7\u7684\uff08\u6709\u4e9b\u4e0d\u662f\u968f\u7740\u591a\u9879\u5f0f\u7a0b\u5ea6\u7684\u53d8\u5316\u800c\u7b49\u4ef7\uff09\u3002\u8fd9\u91cc\uff0c\u6211\u4eec\u9009\u62e9\n// @f[ \\|u\\|_{1,h} =\n//  \\sum_{K\\in \\mathbb T_h} \\|\\nabla u\\|_K^2 + \\sum_{F \\in F_h^i}\n//  4\\sigma_F\\|\\average{ u \\mathbf n}\\|^2_F + \\sum_{F \\in F_h^b}\n//  2\\sigma_F\\|u\\|^2_F \n//  @f]\n\n  template <int dim> \n  class ErrorIntegrator : public MeshWorker::LocalIntegrator<dim> \n  { \n  public: \n    void cell(MeshWorker::DoFInfo<dim> &                 dinfo, \n              typename MeshWorker::IntegrationInfo<dim> &info) const override; \n    void \n         boundary(MeshWorker::DoFInfo<dim> &                 dinfo, \n                  typename MeshWorker::IntegrationInfo<dim> &info) const override; \n    void face(MeshWorker::DoFInfo<dim> &                 dinfo1, \n              MeshWorker::DoFInfo<dim> &                 dinfo2, \n              typename MeshWorker::IntegrationInfo<dim> &info1, \n              typename MeshWorker::IntegrationInfo<dim> &info2) const override; \n  }; \n\n// \u8fd9\u91cc\u6211\u4eec\u6709\u5173\u4e8e\u5355\u5143\u683c\u7684\u96c6\u6210\u3002\u76ee\u524dMeshWorker\u4e2d\u8fd8\u6ca1\u6709\u5f88\u597d\u7684\u63a5\u53e3\u53ef\u4ee5\u8ba9\u6211\u4eec\u8bbf\u95ee\u6b63\u4ea4\u70b9\u4e2d\u7684\u6b63\u5219\u51fd\u6570\u503c\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u5355\u5143\u683c\u79ef\u5206\u5668\u4e2d\u521b\u5efa\u7cbe\u786e\u51fd\u6570\u503c\u548c\u68af\u5ea6\u7684\u5411\u91cf\u3002\u4e4b\u540e\uff0c\u4e00\u5207\u7167\u65e7\uff0c\u6211\u4eec\u53ea\u9700\u5c06\u5dee\u503c\u7684\u5e73\u65b9\u52a0\u8d77\u6765\u3002\n\n// \u9664\u4e86\u8ba1\u7b97\u80fd\u91cf\u51c6\u5219\u7684\u8bef\u5dee\uff0c\u6211\u4eec\u8fd8\u5229\u7528\u7f51\u683c\u5de5\u4f5c\u8005\u7684\u80fd\u529b\u540c\u65f6\u8ba1\u7b97\u4e24\u4e2a\u51fd\u6570\u5e76\u5728\u540c\u4e00\u4e2a\u5faa\u73af\u4e2d\u8ba1\u7b97<i>L<sup>2</sup></i>\u7684\u8bef\u5dee\u3002\u5f88\u660e\u663e\uff0c\u8fd9\u4e2a\u51fd\u6570\u6ca1\u6709\u4efb\u4f55\u8df3\u8dc3\u9879\uff0c\u53ea\u51fa\u73b0\u5728\u5355\u5143\u683c\u7684\u79ef\u5206\u4e2d\u3002\n\n  template <int dim> \n  void ErrorIntegrator<dim>::cell( \n    MeshWorker::DoFInfo<dim> &                 dinfo, \n    typename MeshWorker::IntegrationInfo<dim> &info) const \n  { \n    const FEValuesBase<dim> &   fe = info.fe_values(); \n    std::vector<Tensor<1, dim>> exact_gradients(fe.n_quadrature_points); \n    std::vector<double>         exact_values(fe.n_quadrature_points); \n\n    exact_solution.gradient_list(fe.get_quadrature_points(), exact_gradients); \n    exact_solution.value_list(fe.get_quadrature_points(), exact_values); \n\n    const std::vector<Tensor<1, dim>> &Duh = info.gradients[0][0]; \n    const std::vector<double> &        uh  = info.values[0][0]; \n\n    for (unsigned k = 0; k < fe.n_quadrature_points; ++k) \n      { \n        double sum = 0; \n        for (unsigned int d = 0; d < dim; ++d) \n          { \n            const double diff = exact_gradients[k][d] - Duh[k][d]; \n            sum += diff * diff; \n          } \n        const double diff = exact_values[k] - uh[k]; \n        dinfo.value(0) += sum * fe.JxW(k); \n        dinfo.value(1) += diff * diff * fe.JxW(k); \n      } \n    dinfo.value(0) = std::sqrt(dinfo.value(0)); \n    dinfo.value(1) = std::sqrt(dinfo.value(1)); \n  } \n\n  template <int dim> \n  void ErrorIntegrator<dim>::boundary( \n    MeshWorker::DoFInfo<dim> &                 dinfo, \n    typename MeshWorker::IntegrationInfo<dim> &info) const \n  { \n    const FEValuesBase<dim> &fe = info.fe_values(); \n\n    std::vector<double> exact_values(fe.n_quadrature_points); \n    exact_solution.value_list(fe.get_quadrature_points(), exact_values); \n\n    const std::vector<double> &uh = info.values[0][0]; \n\n    const unsigned int degree = fe.get_fe().tensor_degree(); \n    const double penalty = 2. * degree * (degree + 1) * dinfo.face->measure() / \n                           dinfo.cell->measure(); \n\n    for (unsigned k = 0; k < fe.n_quadrature_points; ++k) \n      { \n        const double diff = exact_values[k] - uh[k]; \n        dinfo.value(0) += penalty * diff * diff * fe.JxW(k); \n      } \n    dinfo.value(0) = std::sqrt(dinfo.value(0)); \n  } \n\n  template <int dim> \n  void ErrorIntegrator<dim>::face( \n    MeshWorker::DoFInfo<dim> &                 dinfo1, \n    MeshWorker::DoFInfo<dim> &                 dinfo2, \n    typename MeshWorker::IntegrationInfo<dim> &info1, \n    typename MeshWorker::IntegrationInfo<dim> &info2) const \n  { \n    const FEValuesBase<dim> &  fe  = info1.fe_values(); \n    const std::vector<double> &uh1 = info1.values[0][0]; \n    const std::vector<double> &uh2 = info2.values[0][0]; \n\n    const unsigned int degree = fe.get_fe().tensor_degree(); \n    const double       penalty1 = \n      degree * (degree + 1) * dinfo1.face->measure() / dinfo1.cell->measure(); \n    const double penalty2 = \n      degree * (degree + 1) * dinfo2.face->measure() / dinfo2.cell->measure(); \n    const double penalty = penalty1 + penalty2; \n\n    for (unsigned k = 0; k < fe.n_quadrature_points; ++k) \n      { \n        const double diff = uh1[k] - uh2[k]; \n        dinfo1.value(0) += (penalty * diff * diff) * fe.JxW(k); \n      } \n    dinfo1.value(0) = std::sqrt(dinfo1.value(0)); \n    dinfo2.value(0) = dinfo1.value(0); \n  } \n\n//  @sect3{The main class}  \n\n// \u8fd9\u4e2a\u7c7b\u505a\u4e3b\u8981\u7684\u5de5\u4f5c\uff0c\u5c31\u50cf\u524d\u9762\u7684\u4f8b\u5b50\u4e00\u6837\u3002\u5173\u4e8e\u8fd9\u91cc\u58f0\u660e\u7684\u51fd\u6570\u7684\u63cf\u8ff0\uff0c\u8bf7\u53c2\u8003\u4e0b\u9762\u7684\u5b9e\u73b0\u3002\n\n  template <int dim> \n  class InteriorPenaltyProblem \n  { \n  public: \n    using CellInfo = MeshWorker::IntegrationInfo<dim>; \n\n    InteriorPenaltyProblem(const FiniteElement<dim> &fe); \n\n    void run(unsigned int n_steps); \n\n  private: \n    void   setup_system(); \n    void   assemble_matrix(); \n    void   assemble_mg_matrix(); \n    void   assemble_right_hand_side(); \n    void   error(); \n    double estimate(); \n    void   solve(); \n    void   output_results(const unsigned int cycle) const; \n\n// \u4e0e\u79bb\u6563\u5316\u6709\u5173\u7684\u6210\u5458\u5bf9\u8c61\u5728\u8fd9\u91cc\u3002\n\n    Triangulation<dim>        triangulation; \n    const MappingQ1<dim>      mapping; \n    const FiniteElement<dim> &fe; \n    DoFHandler<dim>           dof_handler; \n\n// \u7136\u540e\uff0c\u6211\u4eec\u6709\u4e0e\u5168\u5c40\u79bb\u6563\u7cfb\u7edf\u76f8\u5173\u7684\u77e9\u9635\u548c\u5411\u91cf\u3002\n\n    SparsityPattern      sparsity; \n    SparseMatrix<double> matrix; \n    Vector<double>       solution; \n    Vector<double>       right_hand_side; \n    BlockVector<double>  estimates; \n\n// \u6700\u540e\uff0c\u6211\u4eec\u6709\u4e00\u7ec4\u4e0e\u591a\u7ea7\u9884\u5904\u7406\u7a0b\u5e8f\u76f8\u5173\u7684\u7a00\u758f\u6a21\u5f0f\u548c\u7a00\u758f\u77e9\u9635\u3002 \u9996\u5148\uff0c\u6211\u4eec\u6709\u4e00\u4e2a\u6c34\u5e73\u77e9\u9635\u548c\u5b83\u7684\u7a00\u758f\u6027\u6a21\u5f0f\u3002\n\n    MGLevelObject<SparsityPattern>      mg_sparsity; \n    MGLevelObject<SparseMatrix<double>> mg_matrix; \n\n// \u5f53\u6211\u4eec\u5728\u5c40\u90e8\u7ec6\u5316\u7684\u7f51\u683c\u4e0a\u8fdb\u884c\u5c40\u90e8\u5e73\u6ed1\u7684\u591a\u91cd\u7f51\u683c\u65f6\uff0c\u9700\u8981\u989d\u5916\u7684\u77e9\u9635\uff1b\u89c1Kanschat\uff082004\uff09\u3002\u8fd9\u91cc\u662f\u8fd9\u4e9b\u8fb9\u7f18\u77e9\u9635\u7684\u7a00\u758f\u6027\u6a21\u5f0f\u3002\u6211\u4eec\u53ea\u9700\u8981\u4e00\u4e2a\uff0c\u56e0\u4e3a\u4e0a\u77e9\u9635\u7684\u6a21\u5f0f\u662f\u4e0b\u77e9\u9635\u7684\u8f6c\u7f6e\u3002\u5b9e\u9645\u4e0a\uff0c\u6211\u4eec\u5e76\u4e0d\u592a\u5173\u5fc3\u8fd9\u4e9b\u7ec6\u8282\uff0c\u56e0\u4e3aMeshWorker\u6b63\u5728\u586b\u5145\u8fd9\u4e9b\u77e9\u9635\u3002\n\n    MGLevelObject<SparsityPattern> mg_sparsity_dg_interface; \n\n// \u7cbe\u7ec6\u5316\u8fb9\u7f18\u7684\u901a\u91cf\u77e9\u9635\uff0c\u5c06\u7cbe\u7ec6\u7ea7\u81ea\u7531\u5ea6\u4e0e\u7c97\u7565\u7ea7\u81ea\u7531\u5ea6\u76f8\u8026\u5408\u3002\n\n    MGLevelObject<SparseMatrix<double>> mg_matrix_dg_down; \n\n// \u7cbe\u7ec6\u5316\u8fb9\u7f18\u7684\u901a\u91cf\u77e9\u9635\u7684\u8f6c\u7f6e\uff0c\u5c06\u7c97\u7ea7\u81ea\u7531\u5ea6\u8026\u5408\u5230\u7cbe\u7ec6\u7ea7\u3002\n\n    MGLevelObject<SparseMatrix<double>> mg_matrix_dg_up; \n  }; \n\n// \u6784\u9020\u51fd\u6570\u7b80\u5355\u5730\u8bbe\u7f6e\u4e86\u7c97\u7565\u7684\u7f51\u683c\u548cDoFHandler\u3002FiniteElement\u4f5c\u4e3a\u4e00\u4e2a\u53c2\u6570\u88ab\u63d0\u4f9b\uff0c\u4ee5\u5b9e\u73b0\u7075\u6d3b\u6027\u3002\n\n  template <int dim> \n  InteriorPenaltyProblem<dim>::InteriorPenaltyProblem( \n    const FiniteElement<dim> &fe) \n    : triangulation(Triangulation<dim>::limit_level_difference_at_vertices) \n    , mapping() \n    , fe(fe) \n    , dof_handler(triangulation) \n    , estimates(1) \n  { \n    GridGenerator::hyper_cube_slit(triangulation, -1, 1); \n  } \n\n// \u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u8bbe\u7f6e\u4e86\u7ebf\u6027\u7cfb\u7edf\u7684\u7ef4\u5ea6\u548c\u5168\u5c40\u77e9\u9635\u4ee5\u53ca\u6c34\u5e73\u77e9\u9635\u7684\u7a00\u758f\u6027\u6a21\u5f0f\u3002\n\n  template <int dim> \n  void InteriorPenaltyProblem<dim>::setup_system() \n  { \n\n// \u9996\u5148\uff0c\u6211\u4eec\u7528\u6709\u9650\u5143\u5c06\u81ea\u7531\u5ea6\u5206\u5e03\u5728\u7f51\u683c\u4e0a\u5e76\u5bf9\u5176\u8fdb\u884c\u7f16\u53f7\u3002\n\n    dof_handler.distribute_dofs(fe); \n    dof_handler.distribute_mg_dofs(); \n    unsigned int n_dofs = dof_handler.n_dofs(); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u5df2\u7ecf\u77e5\u9053\u4ee3\u8868\u6709\u9650\u5143\u51fd\u6570\u7684\u5411\u91cf\u7684\u5927\u5c0f\u3002\n\n    solution.reinit(n_dofs); \n    right_hand_side.reinit(n_dofs); \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u4e3a\u5168\u5c40\u77e9\u9635\u8bbe\u7f6e\u7a00\u758f\u6027\u6a21\u5f0f\u3002\u7531\u4e8e\u6211\u4eec\u4e8b\u5148\u4e0d\u77e5\u9053\u884c\u7684\u5927\u5c0f\uff0c\u6240\u4ee5\u6211\u4eec\u9996\u5148\u586b\u5145\u4e00\u4e2a\u4e34\u65f6\u7684DynamicSparsityPattern\u5bf9\u8c61\uff0c\u4e00\u65e6\u5b8c\u6210\uff0c\u5c31\u5c06\u5176\u590d\u5236\u5230\u5e38\u89c4\u7684SparsityPattern\u4e2d\u3002\n\n    DynamicSparsityPattern dsp(n_dofs); \n    DoFTools::make_flux_sparsity_pattern(dof_handler, dsp); \n    sparsity.copy_from(dsp); \n    matrix.reinit(sparsity); \n\n    const unsigned int n_levels = triangulation.n_levels(); \n\n// \u5168\u5c40\u7cfb\u7edf\u5df2\u7ecf\u8bbe\u7f6e\u597d\u4e86\uff0c\u73b0\u5728\u6211\u4eec\u6765\u5173\u6ce8\u4e00\u4e0b\u7ea7\u522b\u77e9\u9635\u3002\u6211\u4eec\u8c03\u6574\u6240\u6709\u77e9\u9635\u5bf9\u8c61\u7684\u5927\u5c0f\uff0c\u4ee5\u4fbf\u6bcf\u4e00\u7ea7\u90fd\u6709\u4e00\u4e2a\u77e9\u9635\u3002\n\n    mg_matrix.resize(0, n_levels - 1); \n    mg_matrix.clear_elements(); \n    mg_matrix_dg_up.resize(0, n_levels - 1); \n    mg_matrix_dg_up.clear_elements(); \n    mg_matrix_dg_down.resize(0, n_levels - 1); \n    mg_matrix_dg_down.clear_elements(); \n\n// \u5728\u4e3a\u6c34\u5e73\u77e9\u9635\u8c03\u7528<tt>clear()</tt>\u4e4b\u540e\u66f4\u65b0\u7a00\u758f\u6a21\u5f0f\u5f88\u91cd\u8981\uff0c\u56e0\u4e3a\u77e9\u9635\u901a\u8fc7SmartPointer\u548cSubscriptor\u673a\u5236\u9501\u5b9a\u4e86\u7a00\u758f\u6a21\u5f0f\u3002\n\n    mg_sparsity.resize(0, n_levels - 1); \n    mg_sparsity_dg_interface.resize(0, n_levels - 1); \n\n// \u73b0\u5728\uff0c\u6240\u6709\u7684\u5bf9\u8c61\u90fd\u51c6\u5907\u597d\u4e86\uff0c\u53ef\u4ee5\u5728\u6bcf\u4e00\u5c42\u5bb9\u7eb3\u4e00\u4e2a\u7a00\u758f\u6a21\u5f0f\u6216\u77e9\u9635\u3002\u5269\u4e0b\u7684\u5c31\u662f\u5728\u6bcf\u4e00\u5c42\u8bbe\u7f6e\u7a00\u758f\u6a21\u5f0f\u4e86\u3002\n\n    for (unsigned int level = mg_sparsity.min_level(); \n         level <= mg_sparsity.max_level(); \n         ++level) \n      { \n\n// \u8fd9\u4e9b\u4e0e\u4e0a\u9762\u7684\u5168\u5c40\u77e9\u9635\u7684\u884c\u6570\u5927\u81f4\u76f8\u540c\uff0c\u73b0\u5728\u662f\u6bcf\u4e2a\u7ea7\u522b\u7684\u3002\n\n        DynamicSparsityPattern dsp(dof_handler.n_dofs(level)); \n        MGTools::make_flux_sparsity_pattern(dof_handler, dsp, level); \n        mg_sparsity[level].copy_from(dsp); \n        mg_matrix[level].reinit(mg_sparsity[level]); \n\n// \u53e6\u5916\uff0c\u6211\u4eec\u9700\u8981\u521d\u59cb\u5316\u5404\u5c42\u4e4b\u95f4\u7ec6\u5316\u8fb9\u7f18\u7684\u8f6c\u79fb\u77e9\u9635\u3002\u5b83\u4eec\u88ab\u5b58\u50a8\u5728\u4e24\u4e2a\u7d22\u5f15\u4e2d\u8f83\u7ec6\u7684\u7d22\u5f15\u5904\uff0c\u56e0\u6b64\u57280\u5c42\u6ca1\u6709\u8fd9\u6837\u7684\u5bf9\u8c61\u3002\n\n        if (level > 0) \n          { \n            DynamicSparsityPattern dsp; \n            dsp.reinit(dof_handler.n_dofs(level - 1), \n                       dof_handler.n_dofs(level)); \n            MGTools::make_flux_sparsity_pattern_edge(dof_handler, dsp, level); \n            mg_sparsity_dg_interface[level].copy_from(dsp); \n            mg_matrix_dg_up[level].reinit(mg_sparsity_dg_interface[level]); \n            mg_matrix_dg_down[level].reinit(mg_sparsity_dg_interface[level]); \n          } \n      } \n  } \n\n// \u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u7ec4\u88c5\u5168\u5c40\u7cfb\u7edf\u77e9\u9635\uff0c\u8fd9\u91cc\u7684\u5168\u5c40\u662f\u6307\u6211\u4eec\u89e3\u51b3\u7684\u79bb\u6563\u7cfb\u7edf\u7684\u77e9\u9635\uff0c\u5b83\u8986\u76d6\u4e86\u6574\u4e2a\u7f51\u683c\u3002\n\n  template <int dim> \n  void InteriorPenaltyProblem<dim>::assemble_matrix() \n  { \n\n// \u9996\u5148\uff0c\u6211\u4eec\u9700\u8981\u8bbe\u7f6e\u63d0\u4f9b\u6211\u4eec\u96c6\u6210\u503c\u7684\u5bf9\u8c61\u3002\u8fd9\u4e2a\u5bf9\u8c61\u5305\u542b\u4e86\u6240\u6709\u9700\u8981\u7684FEValues\u548cFEFaceValues\u5bf9\u8c61\uff0c\u5e76\u4e14\u81ea\u52a8\u7ef4\u62a4\u5b83\u4eec\uff0c\u4f7f\u5b83\u4eec\u603b\u662f\u6307\u5411\u5f53\u524d\u5355\u5143\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u9700\u8981\u544a\u8bc9\u5b83\uff0c\u5728\u54ea\u91cc\u8ba1\u7b97\uff0c\u8ba1\u7b97\u4ec0\u4e48\u3002\u7531\u4e8e\u6211\u4eec\u6ca1\u6709\u505a\u4efb\u4f55\u82b1\u54e8\u7684\u4e8b\u60c5\uff0c\u6211\u4eec\u53ef\u4ee5\u4f9d\u9760\u4ed6\u4eec\u5bf9\u6b63\u4ea4\u89c4\u5219\u7684\u6807\u51c6\u9009\u62e9\u3002\n\n// \u7531\u4e8e\u4ed6\u4eec\u7684\u9ed8\u8ba4\u66f4\u65b0\u6807\u5fd7\u662f\u6700\u5c0f\u7684\uff0c\u6211\u4eec\u53e6\u5916\u6dfb\u52a0\u6211\u4eec\u9700\u8981\u7684\u4e1c\u897f\uff0c\u5373\u6240\u6709\u5bf9\u8c61\uff08\u5355\u5143\u683c\u3001\u8fb9\u754c\u548c\u5185\u90e8\u9762\uff09\u4e0a\u7684\u5f62\u72b6\u51fd\u6570\u7684\u503c\u548c\u68af\u5ea6\u3002\u4e4b\u540e\uff0c\u6211\u4eec\u51c6\u5907\u521d\u59cb\u5316\u5bb9\u5668\uff0c\u5b83\u5c06\u521b\u5efa\u6240\u6709\u5fc5\u8981\u7684FEValuesBase\u5bf9\u8c61\u8fdb\u884c\u6574\u5408\u3002\n\n    MeshWorker::IntegrationInfoBox<dim> info_box; \n    UpdateFlags update_flags = update_values | update_gradients; \n    info_box.add_update_flags_all(update_flags); \n    info_box.initialize(fe, mapping); \n\n// \u8fd9\u5c31\u662f\u6211\u4eec\u6574\u5408\u672c\u5730\u6570\u636e\u7684\u5bf9\u8c61\u3002\u5b83\u7531MatrixIntegrator\u4e2d\u7684\u5c40\u90e8\u6574\u5408\u4f8b\u7a0b\u586b\u5145\uff0c\u7136\u540e\u7531\u6c47\u7f16\u5668\u7528\u6765\u5c06\u4fe1\u606f\u5206\u914d\u5230\u5168\u5c40\u77e9\u9635\u4e2d\u3002\n\n    MeshWorker::DoFInfo<dim> dof_info(dof_handler); \n\n// \u6b64\u5916\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u4e00\u4e2a\u5c06\u5c40\u90e8\u77e9\u9635\u88c5\u914d\u5230\u5168\u5c40\u77e9\u9635\u7684\u5bf9\u8c61\u3002\u8fd9\u4e9b\u88c5\u914d\u5668\u5bf9\u8c61\u62e5\u6709\u76ee\u6807\u5bf9\u8c61\u7ed3\u6784\u7684\u6240\u6709\u77e5\u8bc6\uff0c\u5728\u8fd9\u91cc\u662f\u4e00\u4e2a\u7a00\u758f\u77e9\u9635\uff0c\u53ef\u80fd\u7684\u7ea6\u675f\u548c\u7f51\u683c\u7ed3\u6784\u3002\n\n    MeshWorker::Assembler::MatrixSimple<SparseMatrix<double>> assembler; \n    assembler.initialize(matrix); \n\n// \u73b0\u5728\u662f\u6211\u4eec\u81ea\u5df1\u7f16\u7801\u7684\u90e8\u5206\uff0c\u5c40\u90e8\u79ef\u5206\u5668\u3002\u8fd9\u662f\u552f\u4e00\u4e0e\u95ee\u9898\u6709\u5173\u7684\u90e8\u5206\u3002\n\n    MatrixIntegrator<dim> integrator; \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u628a\u6240\u6709\u7684\u4e1c\u897f\u90fd\u6254\u5230 MeshWorker::loop(), \u4e2d\uff0c\u5728\u8fd9\u91cc\u904d\u5386\u7f51\u683c\u7684\u6240\u6709\u6d3b\u52a8\u5355\u5143\uff0c\u8ba1\u7b97\u5355\u5143\u548c\u9762\u7684\u77e9\u9635\uff0c\u5e76\u628a\u5b83\u4eec\u96c6\u5408\u5230\u5168\u5c40\u77e9\u9635\u4e2d\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u53d8\u91cf<tt>dof_handler</tt>\uff0c\u4ee5\u4fbf\u4f7f\u7528\u5168\u5c40\u81ea\u7531\u5ea6\u7684\u7f16\u53f7\u3002\n\n    MeshWorker::integration_loop<dim, dim>(dof_handler.begin_active(), \n                                           dof_handler.end(), \n                                           dof_info, \n                                           info_box, \n                                           integrator, \n                                           assembler); \n  } \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u5bf9\u6c34\u5e73\u77e9\u9635\u505a\u540c\u6837\u7684\u5904\u7406\u3002\u4e0d\u592a\u4ee4\u4eba\u60ca\u8bb6\u7684\u662f\uff0c\u8fd9\u4e2a\u51fd\u6570\u770b\u8d77\u6765\u50cf\u524d\u4e00\u4e2a\u51fd\u6570\u7684\u5b6a\u751f\u5144\u5f1f\u3002\u4e8b\u5b9e\u4e0a\uff0c\u53ea\u6709\u4e24\u4e2a\u5c0f\u7684\u533a\u522b\u3002\n\n  template <int dim> \n  void InteriorPenaltyProblem<dim>::assemble_mg_matrix() \n  { \n    MeshWorker::IntegrationInfoBox<dim> info_box; \n    UpdateFlags update_flags = update_values | update_gradients; \n    info_box.add_update_flags_all(update_flags); \n    info_box.initialize(fe, mapping); \n\n    MeshWorker::DoFInfo<dim> dof_info(dof_handler); \n\n// \u5f88\u660e\u663e\uff0c\u9700\u8981\u7528\u4e00\u4e2a\u586b\u5145\u6c34\u5e73\u77e9\u9635\u7684\u6c47\u7f16\u5668\u6765\u4ee3\u66ff\u3002\u8bf7\u6ce8\u610f\uff0c\u5b83\u4e5f\u4f1a\u81ea\u52a8\u586b\u5145\u8fb9\u7f18\u77e9\u9635\u3002\n\n    MeshWorker::Assembler::MGMatrixSimple<SparseMatrix<double>> assembler; \n    assembler.initialize(mg_matrix); \n    assembler.initialize_fluxes(mg_matrix_dg_up, mg_matrix_dg_down); \n\n    MatrixIntegrator<dim> integrator; \n\n// \u8fd9\u91cc\u662f\u4e0e\u524d\u4e00\u4e2a\u51fd\u6570\u7684\u53e6\u4e00\u4e2a\u4e0d\u540c\u4e4b\u5904\uff1a\u6211\u4eec\u5728\u6240\u6709\u5355\u5143\u4e0a\u8fd0\u884c\uff0c\u800c\u4e0d\u4ec5\u4ec5\u662f\u6d3b\u52a8\u5355\u5143\u3002\u800c\u4e14\u6211\u4eec\u4f7f\u7528\u4ee5 <code>_mg</code> \u7ed3\u5c3e\u7684\u51fd\u6570\uff0c\u56e0\u4e3a\u6211\u4eec\u9700\u8981\u6bcf\u4e00\u5c42\u7684\u81ea\u7531\u5ea6\uff0c\u800c\u4e0d\u662f\u5168\u5c40\u7684\u7f16\u53f7\u3002\n\n    MeshWorker::integration_loop<dim, dim>(dof_handler.begin_mg(), \n                                           dof_handler.end_mg(), \n                                           dof_info, \n                                           info_box, \n                                           integrator, \n                                           assembler); \n  } \n\n// \u8fd9\u91cc\u6211\u4eec\u6709\u53e6\u4e00\u4e2aassemble\u51fd\u6570\u7684\u514b\u9686\u3002\u4e0e\u7ec4\u88c5\u7cfb\u7edf\u77e9\u9635\u7684\u533a\u522b\u5728\u4e8e\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u7ec4\u88c5\u4e86\u4e00\u4e2a\u5411\u91cf\u3002\n\n  template <int dim> \n  void InteriorPenaltyProblem<dim>::assemble_right_hand_side() \n  { \n    MeshWorker::IntegrationInfoBox<dim> info_box; \n    UpdateFlags                         update_flags = \n      update_quadrature_points | update_values | update_gradients; \n    info_box.add_update_flags_all(update_flags); \n    info_box.initialize(fe, mapping); \n\n    MeshWorker::DoFInfo<dim> dof_info(dof_handler); \n\n// \u56e0\u4e3a\u8fd9\u4e2a\u6c47\u7f16\u5668\u5141\u8bb8\u6211\u4eec\u586b\u5145\u591a\u4e2a\u5411\u91cf\uff0c\u6240\u4ee5\u63a5\u53e3\u8981\u6bd4\u4e0a\u9762\u590d\u6742\u4e00\u4e9b\u3002\u5411\u91cf\u7684\u6307\u9488\u5fc5\u987b\u5b58\u50a8\u5728\u4e00\u4e2aAnyData\u5bf9\u8c61\u4e2d\u3002\u867d\u7136\u8fd9\u5728\u8fd9\u91cc\u4f3c\u4e4e\u9020\u6210\u4e86\u4e24\u884c\u989d\u5916\u7684\u4ee3\u7801\uff0c\u4f46\u5b9e\u9645\u4e0a\u5728\u66f4\u590d\u6742\u7684\u5e94\u7528\u4e2d\u5b83\u662f\u5f88\u65b9\u4fbf\u7684\u3002\n\n    MeshWorker::Assembler::ResidualSimple<Vector<double>> assembler; \n    AnyData                                               data; \n    data.add<Vector<double> *>(&right_hand_side, \"RHS\"); \n    assembler.initialize(data); \n\n    RHSIntegrator<dim> integrator; \n    MeshWorker::integration_loop<dim, dim>(dof_handler.begin_active(), \n                                           dof_handler.end(), \n                                           dof_info, \n                                           info_box, \n                                           integrator, \n                                           assembler); \n\n    right_hand_side *= -1.; \n  } \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u5df2\u7ecf\u5bf9\u6784\u5efa\u79bb\u6563\u7ebf\u6027\u7cfb\u7edf\u7684\u6240\u6709\u51fd\u6570\u8fdb\u884c\u4e86\u7f16\u7801\uff0c\u73b0\u5728\u662f\u6211\u4eec\u5b9e\u9645\u89e3\u51b3\u5b83\u7684\u65f6\u5019\u4e86\u3002\n\n  template <int dim> \n  void InteriorPenaltyProblem<dim>::solve() \n  { \n\n// \u9009\u62e9\u7684\u6c42\u89e3\u5668\u662f\u5171\u8f6d\u68af\u5ea6\u3002\n\n    SolverControl            control(1000, 1.e-12); \n    SolverCG<Vector<double>> solver(control); \n\n// \u73b0\u5728\u6211\u4eec\u6b63\u5728\u8bbe\u7f6e\u591a\u7ea7\u9884\u5904\u7406\u7a0b\u5e8f\u7684\u7ec4\u4ef6\u3002\u9996\u5148\uff0c\u6211\u4eec\u9700\u8981\u5728\u7f51\u683c\u5c42\u4e4b\u95f4\u8fdb\u884c\u8f6c\u79fb\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u7684\u5bf9\u8c61\u4e3a\u8fd9\u4e9b\u8f6c\u79fb\u751f\u6210\u4e86\u7a00\u758f\u77e9\u9635\u3002\n\n    MGTransferPrebuilt<Vector<double>> mg_transfer; \n    mg_transfer.build(dof_handler); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u7cbe\u786e\u7684\u89e3\u7b97\u5668\u6765\u89e3\u7b97\u6700\u7c97\u5c42\u6b21\u4e0a\u7684\u77e9\u9635\u3002\n\n    FullMatrix<double> coarse_matrix; \n    coarse_matrix.copy_from(mg_matrix[0]); \n    MGCoarseGridHouseholder<double, Vector<double>> mg_coarse; \n    mg_coarse.initialize(coarse_matrix); \n\n// \u867d\u7136\u8f6c\u79fb\u548c\u7c97\u7565\u7f51\u683c\u6c42\u89e3\u5668\u51e0\u4e4e\u662f\u901a\u7528\u7684\uff0c\u4f46\u4e3a\u5e73\u6ed1\u5668\u63d0\u4f9b\u4e86\u66f4\u591a\u7684\u7075\u6d3b\u6027\u3002\u9996\u5148\uff0c\u6211\u4eec\u9009\u62e9Gauss-Seidel\u4f5c\u4e3a\u6211\u4eec\u7684\u5e73\u6ed1\u65b9\u6cd5\u3002\n\n    GrowingVectorMemory<Vector<double>> mem; \n    using RELAXATION = PreconditionSOR<SparseMatrix<double>>; \n    mg::SmootherRelaxation<RELAXATION, Vector<double>> mg_smoother; \n    RELAXATION::AdditionalData                         smoother_data(1.); \n    mg_smoother.initialize(mg_matrix, smoother_data); \n\n// \u5728\u6bcf\u4e2a\u7ea7\u522b\u4e0a\u505a\u4e24\u4e2a\u5e73\u6ed1\u6b65\u9aa4\u3002\n\n    mg_smoother.set_steps(2); \n\n// \u7531\u4e8eSOR\u65b9\u6cd5\u4e0d\u662f\u5bf9\u79f0\u7684\uff0c\u4f46\u6211\u4eec\u5728\u4e0b\u9762\u4f7f\u7528\u5171\u8f6d\u68af\u5ea6\u8fed\u4ee3\uff0c\u8fd9\u91cc\u6709\u4e00\u4e2a\u6280\u5de7\uff0c\u4f7f\u591a\u7ea7\u9884\u5904\u7406\u5668\u6210\u4e3a\u5bf9\u79f0\u7b97\u5b50\uff0c\u5373\u4f7f\u662f\u5bf9\u975e\u5bf9\u79f0\u5e73\u6ed1\u5668\u3002\n\n    mg_smoother.set_symmetric(true); \n\n// \u5e73\u6ed1\u5668\u7c7b\u53ef\u4ee5\u9009\u62e9\u5b9e\u73b0\u53d8\u91cfV\u578b\u5faa\u73af\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u4e0d\u9700\u8981\u3002\n\n    mg_smoother.set_variable(false); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u5fc5\u987b\u5c06\u6211\u4eec\u7684\u77e9\u9635\u5305\u88f9\u5728\u4e00\u4e2a\u5177\u6709\u6240\u9700\u4e58\u6cd5\u51fd\u6570\u7684\u5bf9\u8c61\u4e2d\u3002\n\n    mg::Matrix<Vector<double>> mgmatrix(mg_matrix); \n    mg::Matrix<Vector<double>> mgdown(mg_matrix_dg_down); \n    mg::Matrix<Vector<double>> mgup(mg_matrix_dg_up); \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u51c6\u5907\u8bbe\u7f6eV\u578b\u5faa\u73af\u7b97\u5b50\u548c\u591a\u7ea7\u9884\u5904\u7406\u7a0b\u5e8f\u3002\n\n    Multigrid<Vector<double>> mg( \n      mgmatrix, mg_coarse, mg_transfer, mg_smoother, mg_smoother); \n\n// \u8ba9\u6211\u4eec\u4e0d\u8981\u5fd8\u8bb0\u56e0\u4e3a\u81ea\u9002\u5e94\u7ec6\u5316\u800c\u9700\u8981\u7684\u8fb9\u7f18\u77e9\u9635\u3002\n\n    mg.set_edge_flux_matrices(mgdown, mgup); \n\n// \u5728\u6240\u6709\u7684\u51c6\u5907\u5de5\u4f5c\u5b8c\u6210\u540e\uff0c\u5c06Multigrid\u5bf9\u8c61\u5305\u88c5\u6210\u53e6\u4e00\u4e2a\u5bf9\u8c61\uff0c\u5b83\u53ef\u4ee5\u4f5c\u4e3a\u4e00\u4e2a\u666e\u901a\u7684\u9884\u5904\u7406\u7a0b\u5e8f\u4f7f\u7528\u3002\n\n    PreconditionMG<dim, Vector<double>, MGTransferPrebuilt<Vector<double>>> \n      preconditioner(dof_handler, mg, mg_transfer); \n\n// \u5e76\u7528\u5b83\u6765\u89e3\u51b3\u8fd9\u4e2a\u7cfb\u7edf\u3002\n\n    solver.solve(matrix, solution, right_hand_side, preconditioner); \n  } \n\n// \u53e6\u4e00\u4e2a\u514b\u9686\u7684\u96c6\u5408\u51fd\u6570\u3002\u4e0e\u4e4b\u524d\u7684\u6700\u5927\u533a\u522b\u662f\uff0c\u8fd9\u91cc\u6211\u4eec\u4e5f\u6709\u4e00\u4e2a\u8f93\u5165\u5411\u91cf\u3002\n\n  template <int dim> \n  double InteriorPenaltyProblem<dim>::estimate() \n  { \n\n// \u4f30\u7b97\u5668\u7684\u7ed3\u679c\u5b58\u50a8\u5728\u4e00\u4e2a\u6bcf\u4e2a\u5355\u5143\u683c\u6709\u4e00\u4e2a\u6761\u76ee\u7684\u5411\u91cf\u4e2d\u3002\u7531\u4e8edeal.II\u4e2d\u7684\u5355\u5143\u683c\u6ca1\u6709\u7f16\u53f7\uff0c\u6211\u4eec\u5fc5\u987b\u5efa\u7acb\u81ea\u5df1\u7684\u7f16\u53f7\uff0c\u4ee5\u4fbf\u4f7f\u7528\u8fd9\u4e2a\u5411\u91cf\u3002\u5bf9\u4e8e\u4e0b\u9762\u4f7f\u7528\u7684\u6c47\u7f16\u5668\u6765\u8bf4\uff0c\u7ed3\u679c\u5b58\u50a8\u5728\u5411\u91cf\u7684\u54ea\u4e2a\u5206\u91cf\u4e2d\u7684\u4fe1\u606f\u662f\u7531\u6bcf\u4e2a\u5355\u5143\u7684user_index\u53d8\u91cf\u4f20\u9001\u7684\u3002\u6211\u4eec\u9700\u8981\u5728\u8fd9\u91cc\u8bbe\u7f6e\u8fd9\u4e2a\u7f16\u53f7\u3002\n\n// \u53e6\u4e00\u65b9\u9762\uff0c\u6709\u4eba\u53ef\u80fd\u5df2\u7ecf\u4f7f\u7528\u4e86\u7528\u6237\u6307\u6570\u3002\u6240\u4ee5\uff0c\u8ba9\u6211\u4eec\u505a\u4e2a\u597d\u516c\u6c11\uff0c\u5728\u7be1\u6539\u5b83\u4eec\u4e4b\u524d\u4fdd\u5b58\u5b83\u4eec\u3002\n\n    std::vector<unsigned int> old_user_indices; \n    triangulation.save_user_indices(old_user_indices); \n\n    estimates.block(0).reinit(triangulation.n_active_cells()); \n    unsigned int i = 0; \n    for (const auto &cell : triangulation.active_cell_iterators()) \n      cell->set_user_index(i++); \n\n// \u8fd9\u5c31\u50cf\u4ee5\u524d\u4e00\u6837\u5f00\u59cb\u3002\n\n    MeshWorker::IntegrationInfoBox<dim> info_box; \n    const unsigned int                  n_gauss_points = \n      dof_handler.get_fe().tensor_degree() + 1; \n    info_box.initialize_gauss_quadrature(n_gauss_points, \n                                         n_gauss_points + 1, \n                                         n_gauss_points); \n\n// \u4f46\u73b0\u5728\u6211\u4eec\u9700\u8981\u901a\u77e5\u4fe1\u606f\u6846\u6211\u4eec\u8981\u5728\u6b63\u4ea4\u70b9\u4e0a\u8bc4\u4f30\u7684\u6709\u9650\u5143\u51fd\u6570\u3002\u9996\u5148\uff0c\u6211\u4eec\u7528\u8fd9\u4e2a\u5411\u91cf\u521b\u5efa\u4e00\u4e2aAnyData\u5bf9\u8c61\uff0c\u8fd9\u4e2a\u5411\u91cf\u5c31\u662f\u6211\u4eec\u521a\u521a\u8ba1\u7b97\u7684\u89e3\u3002\n\n    AnyData solution_data; \n    solution_data.add<const Vector<double> *>(&solution, \"solution\"); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u544a\u8bc9\u5355\u5143\u683c\u7684 Meshworker::VectorSelector \uff0c\u6211\u4eec\u9700\u8981\u8fd9\u4e2a\u89e3\u51b3\u65b9\u6848\u7684\u4e8c\u6b21\u5bfc\u6570\uff08\u7528\u6765\u8ba1\u7b97\u62c9\u666e\u62c9\u65af\uff09\u3002\u56e0\u6b64\uff0c\u9009\u62e9\u51fd\u6570\u503c\u548c\u7b2c\u4e00\u5bfc\u6570\u7684\u5e03\u5c14\u53c2\u6570\u662f\u5047\u7684\uff0c\u53ea\u6709\u9009\u62e9\u7b2c\u4e8c\u5bfc\u6570\u7684\u6700\u540e\u4e00\u4e2a\u53c2\u6570\u662f\u771f\u7684\u3002\n\n    info_box.cell_selector.add(\"solution\", false, false, true); \n\n// \u5728\u5185\u90e8\u548c\u8fb9\u754c\u9762\uff0c\u6211\u4eec\u9700\u8981\u51fd\u6570\u503c\u548c\u7b2c\u4e00\u5bfc\u6570\uff0c\u4f46\u4e0d\u9700\u8981\u7b2c\u4e8c\u5bfc\u6570\u3002\n\n    info_box.boundary_selector.add(\"solution\", true, true, false); \n    info_box.face_selector.add(\"solution\", true, true, false); \n\n// \u6211\u4eec\u7ee7\u7eed\u50cf\u4ee5\u524d\u4e00\u6837\uff0c\u9664\u4e86\u9ed8\u8ba4\u7684\u66f4\u65b0\u6807\u5fd7\u5df2\u7ecf\u88ab\u8c03\u6574\u4e3a\u6211\u4eec\u4e0a\u9762\u8981\u6c42\u7684\u503c\u548c\u5bfc\u6570\u4e4b\u5916\u3002\n\n    info_box.add_update_flags_boundary(update_quadrature_points); \n    info_box.initialize(fe, mapping, solution_data, solution); \n\n    MeshWorker::DoFInfo<dim> dof_info(dof_handler); \n\n// \u6c47\u7f16\u5668\u5728\u6bcf\u4e2a\u5355\u5143\u683c\u4e2d\u5b58\u50a8\u4e00\u4e2a\u6570\u5b57\uff0c\u5426\u5219\u8fd9\u4e0e\u53f3\u4fa7\u7684\u8ba1\u7b97\u662f\u4e00\u6837\u7684\u3002\n\n    MeshWorker::Assembler::CellsAndFaces<double> assembler; \n    AnyData                                      out_data; \n    out_data.add<BlockVector<double> *>(&estimates, \"cells\"); \n    assembler.initialize(out_data, false); \n\n    Estimator<dim> integrator; \n    MeshWorker::integration_loop<dim, dim>(dof_handler.begin_active(), \n                                           dof_handler.end(), \n                                           dof_info, \n                                           info_box, \n                                           integrator, \n                                           assembler); \n\n// \u5c31\u5728\u6211\u4eec\u8fd4\u56de\u9519\u8bef\u4f30\u8ba1\u7684\u7ed3\u679c\u4e4b\u524d\uff0c\u6211\u4eec\u6062\u590d\u65e7\u7684\u7528\u6237\u7d22\u5f15\u3002\n\n    triangulation.load_user_indices(old_user_indices); \n    return estimates.block(0).l2_norm(); \n  } \n\n// \u8fd9\u91cc\u6211\u4eec\u628a\u6211\u4eec\u7684\u6709\u9650\u5143\u89e3\u548c\uff08\u5df2\u77e5\u7684\uff09\u7cbe\u786e\u89e3\u8fdb\u884c\u6bd4\u8f83\uff0c\u8ba1\u7b97\u68af\u5ea6\u548c\u51fd\u6570\u672c\u8eab\u7684\u5e73\u5747\u4e8c\u6b21\u8bef\u5dee\u3002\u8fd9\u4e2a\u51fd\u6570\u662f\u4e0a\u9762\u90a3\u4e2a\u4f30\u8ba1\u51fd\u6570\u7684\u514b\u9686\u3002\n\n// \u7531\u4e8e\u6211\u4eec\u5206\u522b\u8ba1\u7b97\u80fd\u91cf\u548c<i>L<sup>2</sup></i>-norm\u7684\u8bef\u5dee\uff0c\u6211\u4eec\u7684\u5757\u5411\u91cf\u5728\u8fd9\u91cc\u9700\u8981\u4e24\u4e2a\u5757\u3002\n\n  template <int dim> \n  void InteriorPenaltyProblem<dim>::error() \n  { \n    BlockVector<double> errors(2); \n    errors.block(0).reinit(triangulation.n_active_cells()); \n    errors.block(1).reinit(triangulation.n_active_cells()); \n\n    std::vector<unsigned int> old_user_indices; \n    triangulation.save_user_indices(old_user_indices); \n    unsigned int i = 0; \n    for (const auto &cell : triangulation.active_cell_iterators()) \n      cell->set_user_index(i++); \n\n    MeshWorker::IntegrationInfoBox<dim> info_box; \n    const unsigned int                  n_gauss_points = \n      dof_handler.get_fe().tensor_degree() + 1; \n    info_box.initialize_gauss_quadrature(n_gauss_points, \n                                         n_gauss_points + 1, \n                                         n_gauss_points); \n\n    AnyData solution_data; \n    solution_data.add<Vector<double> *>(&solution, \"solution\"); \n\n    info_box.cell_selector.add(\"solution\", true, true, false); \n    info_box.boundary_selector.add(\"solution\", true, false, false); \n    info_box.face_selector.add(\"solution\", true, false, false); \n\n    info_box.add_update_flags_cell(update_quadrature_points); \n    info_box.add_update_flags_boundary(update_quadrature_points); \n    info_box.initialize(fe, mapping, solution_data, solution); \n\n    MeshWorker::DoFInfo<dim> dof_info(dof_handler); \n\n    MeshWorker::Assembler::CellsAndFaces<double> assembler; \n    AnyData                                      out_data; \n    out_data.add<BlockVector<double> *>(&errors, \"cells\"); \n    assembler.initialize(out_data, false); \n\n    ErrorIntegrator<dim> integrator; \n    MeshWorker::integration_loop<dim, dim>(dof_handler.begin_active(), \n                                           dof_handler.end(), \n                                           dof_info, \n                                           info_box, \n                                           integrator, \n                                           assembler); \n    triangulation.load_user_indices(old_user_indices); \n\n    deallog << \"energy-error: \" << errors.block(0).l2_norm() << std::endl; \n    deallog << \"L2-error:     \" << errors.block(1).l2_norm() << std::endl; \n  } \n\n// \u521b\u5efa\u56fe\u5f62\u8f93\u51fa\u3002\u6211\u4eec\u901a\u8fc7\u6574\u7406\u5176\u5404\u4e2a\u7ec4\u6210\u90e8\u5206\u7684\u540d\u79f0\u6765\u4ea7\u751f\u6587\u4ef6\u540d\uff0c\u5305\u62ec\u6211\u4eec\u7528\u4e24\u4e2a\u6570\u5b57\u8f93\u51fa\u7684\u7ec6\u5316\u5468\u671f\u3002\n\n  template <int dim> \n  void \n  InteriorPenaltyProblem<dim>::output_results(const unsigned int cycle) const \n  { \n    const std::string filename = \n      \"sol-\" + Utilities::int_to_string(cycle, 2) + \".gnuplot\"; \n\n    deallog << \"Writing solution to <\" << filename << \">...\" << std::endl \n            << std::endl; \n    std::ofstream gnuplot_output(filename); \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.add_data_vector(estimates.block(0), \"est\"); \n\n    data_out.build_patches(); \n\n    data_out.write_gnuplot(gnuplot_output); \n  } \n\n// \u6700\u540e\u662f\u81ea\u9002\u5e94\u5faa\u73af\uff0c\u6216\u591a\u6216\u5c11\u548c\u524d\u9762\u7684\u4f8b\u5b50\u4e00\u6837\u3002\n\n  template <int dim> \n  void InteriorPenaltyProblem<dim>::run(unsigned int n_steps) \n  { \n    deallog << \"Element: \" << fe.get_name() << std::endl; \n    for (unsigned int s = 0; s < n_steps; ++s) \n      { \n        deallog << \"Step \" << s << std::endl; \n        if (estimates.block(0).size() == 0) \n          triangulation.refine_global(1); \n        else \n          { \n            GridRefinement::refine_and_coarsen_fixed_fraction( \n              triangulation, estimates.block(0), 0.5, 0.0); \n            triangulation.execute_coarsening_and_refinement(); \n          } \n\n        deallog << \"Triangulation \" << triangulation.n_active_cells() \n                << \" cells, \" << triangulation.n_levels() << \" levels\" \n                << std::endl; \n\n        setup_system(); \n        deallog << \"DoFHandler \" << dof_handler.n_dofs() << \" dofs, level dofs\"; \n        for (unsigned int l = 0; l < triangulation.n_levels(); ++l) \n          deallog << ' ' << dof_handler.n_dofs(l); \n        deallog << std::endl; \n\n        deallog << \"Assemble matrix\" << std::endl; \n        assemble_matrix(); \n        deallog << \"Assemble multilevel matrix\" << std::endl; \n        assemble_mg_matrix(); \n        deallog << \"Assemble right hand side\" << std::endl; \n        assemble_right_hand_side(); \n        deallog << \"Solve\" << std::endl; \n        solve(); \n        error(); \n        deallog << \"Estimate \" << estimate() << std::endl; \n        output_results(s); \n      } \n  } \n} // namespace Step39 \n\nint main() \n{ \n  try \n    { \n      using namespace dealii; \n      using namespace Step39; \n\n      deallog.depth_console(2); \n      std::ofstream logfile(\"deallog\"); \n      deallog.attach(logfile); \n      FE_DGQ<2>                 fe1(3); \n      InteriorPenaltyProblem<2> test1(fe1); \n      test1.run(12); \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\n", "meta": {"hexsha": "39d8faed418461fb39a0b4eb308c9342744d9330", "size": 33597, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-39/step-39.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-39/step-39.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-39/step-39.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.2909663866, "max_line_length": 145, "alphanum_fraction": 0.6228234664, "num_tokens": 11530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5291989697530213}}
{"text": "#ifndef LINEARSOLVERS_H_\n#define LINEARSOLVERS_H_\n\n#include <Eigen/Sparse>\n//#include <SuiteSparse_config.h>\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/OrderingMethods>\n//#include <Eigen/SPQRSupport>\n#include <unsupported/Eigen/IterativeSolvers>\n//#include <Eigen/PaStiXSupport>\n\nusing namespace Eigen;\n\nnamespace echo\n{\n\nnamespace solvers\n{\n\n\nclass ConfigurationParameter{\n\npublic:\n    ConfigurationParameter(){\n        max_iterations=100;\n        tol=1E-06;\n        verbose=true;\n    }\n    ~ConfigurationParameter(){}\n    unsigned int max_iterations;\n    double tol;\n    bool verbose;\n};\n\n/**\n* Solve a linear system using conjugate gradient\n* The 'config' argument is an object of the class ConfigurationParameter\n* which has the following members:\n*   unsigned int max_iterations [100]\n*   double tol [1E-06]\n*   bool [true]\n*/\ntemplate <class SparseMatrixType, class DenseVectorType>\nvoid solveWithConjugateGradient(const SparseMatrixType &A, const DenseVectorType &b, DenseVectorType &x, ConfigurationParameter &config);\n\n/**\n* Solve a linear system using sparseQR\n* The 'config' argument is an object of the class ConfigurationParameter\n* which has the following members:\n*   unsigned int max_iterations [100]\n*   double tol [1E-06]\n*   bool [true]\n*/\n//template <class SparseMatrixType, class DenseVectorType>\n//void solveWithSparseQR(const SparseMatrixType &A, const DenseVectorType &b, DenseVectorType &x, ConfigurationParameter &config);\n\n/**\n* Solve a linear system using SPQR from SuiteSparse. Requires SuiteSparse to run\n* The 'config' argument is an object of the class ConfigurationParameter\n* which has the following members:\n*   unsigned int max_iterations [100]\n*   double tol [1E-06]\n*   bool [true]\n*/\n//template <class SparseMatrixType, class DenseVectorType>\n//void solveWithSPQR(const SparseMatrixType &A, const DenseVectorType &b, DenseVectorType &x, ConfigurationParameter &config);\n\n/**\n* Solve a linear system using biconjugate gradient stabilized\n* The 'config' argument is an object of the class ConfigurationParameter\n* which has the following members:\n*   unsigned int max_iterations [100]\n*   double tol [1E-06]\n*   bool [true]\n*/\ntemplate <class SparseMatrixType, class DenseVectorType>\nvoid solveWithBiCGSTAB(const SparseMatrixType &A, const DenseVectorType &b, DenseVectorType &x, ConfigurationParameter &config);\n\n/**\n * This implementation of GMRES is provided *as is* by Eigen, with no support planned.\n * Documentation here http://eigen.tuxfamily.org/dox/unsupported/classEigen_1_1GMRES.html\n */\ntemplate <class SparseMatrixType, class DenseVectorType>\nvoid solveWithGMRES(const SparseMatrixType &A, const DenseVectorType &b, DenseVectorType &x, ConfigurationParameter &config);\n\n}\n\n\n\n\n}\n\n/// --------------------------------------------------------------------///\n/// \t\t\t\t         IMPLEMENTATION          \t\t\t\t    ///\n/// --------------------------------------------------------------------///\n\ntemplate <class SparseMatrixType, class DenseVectorType>\nvoid echo::solvers::solveWithConjugateGradient(const SparseMatrixType &A, const DenseVectorType &b, DenseVectorType &x, ConfigurationParameter &config)\n{\n\n    ConjugateGradient<SparseMatrixType > solver;\n    solver.setMaxIterations(config.max_iterations);\n    solver.setTolerance(config.tol);\n    solver.compute(A);\n    if(solver.info()!=Success)\n    {\n        /// decomposition failed\n        if (config.verbose)          std::cerr << \"\\t\\tERROR: CG decomposition failed with a matrix of size \"<< A.rows() <<\"x\"<<A.cols()<<std::endl;\n    }\n    x = solver.solve(b);\n    if(solver.info()!=Success)\n    {\n        /// solving failed\n        if (config.verbose) std::cerr << \"\\t\\tERROR: CG solver failed with a matrix of size \"<< A.rows() <<\"x\"<<A.cols()<<std::endl;\n    }\n    if (config.verbose) std::cout << \"\\t\\t#iterations:     \" << solver.iterations() << std::endl;\n    if (config.verbose) std::cout << \"\\t\\testimated error: \" << solver.error()      << std::endl;\n\n    /// For using solve with guess refer to documentation here: http://eigen.tuxfamily.org/dox-devel/classEigen_1_1ConjugateGradient.html\n}\n\n/*template <class SparseMatrixType, class DenseVectorType>\nvoid echo::solvers::solveWithSparseQR(const SparseMatrixType &A, const DenseVectorType &b, DenseVectorType &x, ConfigurationParameter &config)\n{\n\n    SparseQR<SparseMatrixType, COLAMDOrdering<int> > solver;\n    //solver.setMaxIterations(config.max_iterations);\n    //solver.setTolerance(config.tol);\n    solver.compute(A);\n    if(solver.info()!=Success)\n    {\n        /// decomposition failed\n        if (config.verbose)          std::cerr << \"\\t\\tERROR: SparseQR decomposition failed with a matrix of size \"<< A.rows() <<\"x\"<<A.cols()<<std::endl;\n    }\n    x = solver.solve(b);\n    if(solver.info()!=Success)\n    {\n        /// solving failed\n        if (config.verbose) std::cerr << \"\\t\\tERROR: SparseQR solver failed with a matrix of size \"<< A.rows() <<\"x\"<<A.cols()<<std::endl;\n    }\n    //if (config.verbose) std::cout << \"\\t\\t#iterations:     \" << solver.iterations() << std::endl;\n    //if (config.verbose) std::cout << \"\\t\\testimated error: \" << solver.error()      << std::endl;\n\n    /// For using solve with guess refer to documentation here: http://eigen.tuxfamily.org/dox-devel/classEigen_1_1ConjugateGradient.html\n}\n*/\n/*template <class SparseMatrixType, class DenseVectorType>\nvoid echo::solvers::solveWithSPQR(const SparseMatrixType &A, const DenseVectorType &b, DenseVectorType &x, ConfigurationParameter &config)\n{\n\n    SPQR<SparseMatrixType > solver;\n    //solver.setMaxIterations(config.max_iterations);\n    //solver.setTolerance(config.tol);\n\n    solver.compute(A);\n\n    if(solver.info()!=Success)\n    {\n        /// decomposition failed\n        if (config.verbose)          std::cerr << \"\\t\\tERROR: SPQR decomposition failed with a matrix of size \"<< A.rows() <<\"x\"<<A.cols()<<std::endl;\n    }\n    x = solver.solve(b);\n    if(solver.info()!=Success)\n    {\n        /// solving failed\n        if (config.verbose) std::cerr << \"\\t\\tERROR: SPQR solver failed with a matrix of size \"<< A.rows() <<\"x\"<<A.cols()<<std::endl;\n    }\n    //if (config.verbose) std::cout << \"\\t\\t#iterations:     \" << solver.iterations() << std::endl;\n    //if (config.verbose) std::cout << \"\\t\\testimated error: \" << solver.error()      << std::endl;\n\n    /// For using solve with guess refer to documentation here: http://eigen.tuxfamily.org/dox-devel/classEigen_1_1ConjugateGradient.html\n}\n*/\ntemplate <class SparseMatrixType, class DenseVectorType>\nvoid echo::solvers::solveWithBiCGSTAB(const SparseMatrixType &A, const DenseVectorType &b, DenseVectorType &x, ConfigurationParameter &config){\n\n    BiCGSTAB<SparseMatrixType, IncompleteLUT<double> > solver;\n    solver.setMaxIterations(config.max_iterations);\n    solver.setTolerance(config.tol);\n    solver.compute(A);\n    if(solver.info()!=Success)\n    {\n        /// decomposition failed\n        if (config.verbose)          std::cerr << \"\\t\\tERROR: BiCGSTAB decomposition failed with a matrix of size \"<< A.rows() <<\"x\"<<A.cols()<<std::endl;\n    }\n    x = solver.solve(b);\n    if(solver.info()!=Success)\n    {\n        /// solving failed\n        if (config.verbose) std::cerr << \"\\t\\tERROR: BiCGSTAB solver failed with a matrix of size \"<< A.rows() <<\"x\"<<A.cols() <<std::endl;\n    }\n    if (config.verbose) std::cout << \"\\t\\t#iterations:     \" << solver.iterations() << std::endl;\n    if (config.verbose) std::cout << \"\\t\\testimated error: \" << solver.error()      << std::endl;\n\n}\n\ntemplate <class SparseMatrixType, class DenseVectorType>\nvoid echo::solvers::solveWithGMRES(const SparseMatrixType &A, const DenseVectorType &b, DenseVectorType &x, ConfigurationParameter &config){\n\n    GMRES<SparseMatrixType, IncompleteLUT<double> > solver;\n    solver.setMaxIterations(config.max_iterations);\n    solver.setTolerance(config.tol);\n    solver.compute(A);\n    if(solver.info()!=Success)\n    {\n        /// decomposition failed\n        if (config.verbose)          std::cerr << \"\\t\\tERROR: GMRES decomposition failed with a matrix of size \"<< A.rows() <<\"x\"<<A.cols()<<std::endl;\n    }\n    x = solver.solve(b);\n    if(solver.info()!=Success)\n    {\n        /// solving failed\n        if (config.verbose) std::cerr << \"\\t\\tERROR: GMRES solver failed with a matrix of size \"<< A.rows() <<\"x\"<<A.cols()<<std::endl;\n    }\n    if (config.verbose) std::cout << \"\\t\\t#iterations:     \" << solver.iterations() << std::endl;\n    if (config.verbose) std::cout << \"\\t\\testimated error: \" << solver.error()      << std::endl;\n\n}\n#endif /* LINEARSOLVERS_H_*/\n", "meta": {"hexsha": "2a8c95d65f048a0a13ed75ceb22caf2933dd4694", "size": 8560, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "Modules/PCMRIKernel/ExtensionPoint/internal/LinearSolvers.hxx", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Modules/PCMRIKernel/ExtensionPoint/internal/LinearSolvers.hxx", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/PCMRIKernel/ExtensionPoint/internal/LinearSolvers.hxx", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 38.9090909091, "max_line_length": 154, "alphanum_fraction": 0.6724299065, "num_tokens": 2100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5291989643102426}}
{"text": "/*\n *            Copyright 2009-2020 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\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// Third party includes\n#include <boost/format.hpp>\n\n// Local VOTCA includes\n#include \"votca/xtp/anderson_mixing.h\"\n\nnamespace votca {\nnamespace xtp {\n\nvoid Anderson::Configure(const Index order, const double alpha) {\n  order_ = order + 1;\n  alpha_ = alpha;\n}\n\nvoid Anderson::UpdateOutput(const Eigen::VectorXd &newOutput) {\n\n  // Check if max mixing history is reached and adding new step to history\n  Index size = output_.size();\n  if (size > order_ - 1) {\n    output_.erase(output_.begin());\n  }\n  output_.push_back(newOutput);\n}\n\nvoid Anderson::UpdateInput(const Eigen::VectorXd &newInput) {\n  Index size = output_.size();\n  if (size > order_ - 1) {\n    input_.erase(input_.begin());\n  }\n  input_.push_back(newInput);\n}\n\nconst Eigen::VectorXd Anderson::MixHistory() {\n\n  const Index iteration = output_.size();\n  const Index used_history = iteration - 1;\n  Eigen::VectorXd OutMixed = output_.back();\n  Eigen::VectorXd InMixed = input_.back();\n\n  if (iteration > 1 && order_ > 1) {\n\n    Eigen::VectorXd DeltaN = OutMixed - InMixed;\n\n    // Building Linear System for Coefficients\n    Eigen::MatrixXd A = Eigen::MatrixXd::Zero(used_history, used_history);\n    Eigen::VectorXd c = Eigen::VectorXd::Zero(used_history);\n\n    for (Index m = 1; m < iteration; m++) {\n\n      c(m - 1) = (DeltaN - output_[used_history - m] + input_[used_history - m])\n                     .dot(DeltaN);\n\n      for (Index j = 1; j < iteration; j++) {\n        A(m - 1, j - 1) =\n            (DeltaN - output_[used_history - m] + input_[used_history - m])\n                .dot((DeltaN - output_[used_history - j] +\n                      input_[used_history - j]));\n      }\n    }\n    // Solving the System to obtain coefficients\n    Eigen::VectorXd coefficients = A.fullPivHouseholderQr().solve(c);\n\n    // Mixing the Potentials\n    for (Index n = 1; n < iteration; n++) {\n\n      OutMixed += coefficients(n - 1) *\n                  (output_[used_history - n] - output_[used_history]);\n      InMixed += coefficients(n - 1) *\n                 (input_[used_history - n] - input_[used_history]);\n    }\n  }\n\n  // Returning the linear Mix of Input and Output\n  return alpha_ * OutMixed + (1 - alpha_) * InMixed;\n}\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "8ac2972bf7bdf110b6084a0b14de1be6cbae3a07", "size": 2917, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/anderson_mixing.cc", "max_stars_repo_name": "rubengerritsen/xtp", "max_stars_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "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/libxtp/anderson_mixing.cc", "max_issues_repo_name": "rubengerritsen/xtp", "max_issues_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "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/libxtp/anderson_mixing.cc", "max_forks_repo_name": "rubengerritsen/xtp", "max_forks_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "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.0721649485, "max_line_length": 80, "alphanum_fraction": 0.6390126843, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5291989588674639}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/ros2_pcl_utils/blob/master/LICENSE\n\n#ifndef PCL_UTILS__CAMERA_HPP_\n#define PCL_UTILS__CAMERA_HPP_\n\n#include <Eigen/Core>\n#include <sensor_msgs/msg/camera_info.hpp>\n\n/**\n * @brief Camera projection with OpenCV model\n *\n * https://docs.opencv.org/4.2.0/d9/d0c/group__calib3d.html\n *\n * @tparam T scalar data type\n * @param pt_CAM 3D point in camera frame\n * @param cam camera information\n * @return Eigen::Matrix<T, 2, 1> pixel coordinates\n */\ntemplate<typename T>\nEigen::Matrix<T, 2, 1> cameraProject(\n  const Eigen::Matrix<T, 3, 1> & pt_CAM,\n  const sensor_msgs::msg::CameraInfo & cam)\n{\n  const T xp = pt_CAM.x() / pt_CAM.z();\n  const T yp = pt_CAM.y() / pt_CAM.z();\n\n  const T r2 = xp * xp + yp * yp;\n  const T r4 = r2 * r2;\n  const T ratio = 1. + cam.d[0] * r2 + cam.d[1] * r4 + cam.d[4] * (r2 * r4);\n  const T xpp =\n    xp * ratio + 2 * cam.d[2] * xp * yp + cam.d[3] * (r2 + 2 * xp * xp);\n  const T ypp =\n    yp * ratio + cam.d[2] * (r2 + 2 * yp * yp) + 2 * cam.d[3] * xp * yp;\n\n  return Eigen::Matrix<T, 2, 1>(\n    cam.k[0] * xpp + cam.k[2],\n    cam.k[4] * ypp + cam.k[5]);\n}\n\n#endif  // PCL_UTILS__CAMERA_HPP_\n", "meta": {"hexsha": "f64b7678e64ca7589187016dbc4bfe350c8ee1ee", "size": 1189, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pcl_utils/camera.hpp", "max_stars_repo_name": "yamaha-bps/ros2_pcl_utils", "max_stars_repo_head_hexsha": "513615ac1b6b251a39f29eb7ff03f307747b8aa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-05T14:35:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-05T14:35:35.000Z", "max_issues_repo_path": "include/pcl_utils/camera.hpp", "max_issues_repo_name": "yamaha-bps/ros2_pcl_utils", "max_issues_repo_head_hexsha": "513615ac1b6b251a39f29eb7ff03f307747b8aa3", "max_issues_repo_licenses": ["MIT"], "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/pcl_utils/camera.hpp", "max_forks_repo_name": "yamaha-bps/ros2_pcl_utils", "max_forks_repo_head_hexsha": "513615ac1b6b251a39f29eb7ff03f307747b8aa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-31T01:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T01:35:07.000Z", "avg_line_length": 27.6511627907, "max_line_length": 76, "alphanum_fraction": 0.622371741, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5291989528133825}}
{"text": "// Copyright Louis Dionne 2013-2016\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#include <boost/hana/ext/std/integral_constant.hpp>\n\n#include <boost/hana/tuple.hpp>\n\n#include <laws/euclidean_ring.hpp>\n#include <laws/group.hpp>\n#include <laws/monoid.hpp>\n#include <laws/ring.hpp>\n\n#include <type_traits>\nnamespace hana = boost::hana;\n\n\nint main() {\n    auto ints = hana::make_tuple(\n        std::integral_constant<int, -10>{},\n        std::integral_constant<int, -2>{},\n        std::integral_constant<int, 0>{},\n        std::integral_constant<int, 1>{},\n        std::integral_constant<int, 3>{}\n    );\n\n    hana::test::TestMonoid<hana::ext::std::integral_constant_tag<int>>{ints};\n    hana::test::TestGroup<hana::ext::std::integral_constant_tag<int>>{ints};\n    hana::test::TestRing<hana::ext::std::integral_constant_tag<int>>{ints};\n    hana::test::TestEuclideanRing<hana::ext::std::integral_constant_tag<int>>{ints};\n}\n", "meta": {"hexsha": "44f0cdb4a15410fab7ad768e59f47aafece4dc4e", "size": 1021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/hana/test/ext/std/integral_constant/arithmetic.cpp", "max_stars_repo_name": "metux/boost", "max_stars_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-06-01T15:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-01T16:06:53.000Z", "max_issues_repo_path": "libs/hana/test/ext/std/integral_constant/arithmetic.cpp", "max_issues_repo_name": "metux/boost", "max_issues_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2016-10-16T19:42:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-14T21:29:48.000Z", "max_forks_repo_path": "libs/hana/test/ext/std/integral_constant/arithmetic.cpp", "max_forks_repo_name": "metux/boost", "max_forks_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T07:18:18.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-19T07:18:18.000Z", "avg_line_length": 31.90625, "max_line_length": 84, "alphanum_fraction": 0.6924583741, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5291989473706036}}
{"text": "/**\n * @author Alessandro Bianco\n */\n\n/**\n * @addtogroup DFNs\n * @{\n */\n\n#ifndef BUNDLEADJUSTMENT_CERESADJUSTMENT_HPP\n#define BUNDLEADJUSTMENT_CERESADJUSTMENT_HPP\n\n#include \"BundleAdjustmentInterface.hpp\"\n#include <Types/CPP/FramesSequence.hpp>\n#include <Types/CPP/PosesSequence.hpp>\n#include <Helpers/ParametersListHelper.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <yaml-cpp/yaml.h>\n#include <Eigen/Dense>\n#include <ceres/ceres.h>\n#include <Converters/CorrespondenceMaps2DSequenceToMatConverter.hpp>\n\nnamespace CDFF\n{\nnamespace DFN\n{\nnamespace BundleAdjustment\n{\n\t/**\n\t * Implementation of the factorization algorithm by Tomasi and Kanade\n\t *\n\t * @param leftCameraMatrix: the camera matrix of the left camera\n\t * @param rightCameraMatrix: the camera maxtrix of the right camera\n\t */\n\tclass CeresAdjustment : public BundleAdjustmentInterface\n\t{\n\t\tpublic:\n\n\t\t\tCeresAdjustment();\n\t\t\tvirtual ~CeresAdjustment();\n\n\t\t\tvirtual void configure() override;\n\t\t\tvirtual void process() override;\n\n\t\tprivate:\n\n\t\t\t//DFN Parameters\n\t\t\tstruct CameraMatrix\n\t\t\t{\n\t\t\t\tfloat focalLengthX;\n\t\t\t\tfloat focalLengthY;\n\t\t\t\tfloat principalPointX;\n\t\t\t\tfloat principalPointY;\n\t\t\t};\n\n\t\t\tstruct CeresAdjustmentOptionsSet\n\t\t\t{\n\t\t\t\tCameraMatrix leftCameraMatrix;\n\t\t\t\tCameraMatrix rightCameraMatrix;\n\t\t\t\tfloat baseline;\n\t\t\t\tdouble squaredPixelErrorTolerance;\n\t\t\t};\n\n\t\t\tHelpers::ParametersListHelper parametersHelper;\n\t\t\tCeresAdjustmentOptionsSet parameters;\n\t\t\tstatic const CeresAdjustmentOptionsSet DEFAULT_PARAMETERS;\n\n\t\t\t//Ceres Functor\n\t\t\tstruct StereoImagePointCostFunctor\n\t\t\t\t{\n\t\t\t\tStereoImagePointCostFunctor(cv::Mat leftCameraMatrix, cv::Mat rightCameraMatrix, cv::Mat pointMeasuresMatrix, float baseline);\n\t\t\t\ttemplate <typename T>\n\t\t\t\tbool operator()(const T* const leftCameraTransform, const T* const point3d, T* residual) const;\n\n\t\t\t\tstatic ceres::CostFunction* Create(cv::Mat leftCameraMatrix, cv::Mat rightCameraMatrix, cv::Mat pointMeasuresMatrix, float baseline);\n\n\t\t\t\tcv::Mat leftCameraMatrix, rightCameraMatrix;\n\t\t\t\tcv::Mat pointMeasuresMatrix;\n\t\t\t\tfloat baseline;\n\t\t\t\t};\n\t\t\ttypedef double Point3d[3];\n\t\t\ttypedef double Transform3d[6];\n\n\t\t\t//Internal State variables\n\t\t\tbool initialPoseEstimationIsAvailable;\n\t\t\tbool initialPointEstimationIsAvailable;\n\n\t\t\t//Configuration Parameters conversion\n\t\t\tcv::Mat leftCameraMatrix, rightCameraMatrix;\n\t\t\tcv::Mat CameraMatrixToCvMatrix(const CameraMatrix& cameraMatrix);\n\n\t\t\t//External conversion helpers\n\t\t\tConverters::CorrespondenceMaps2DSequenceToMatConverter correspondencesSequenceConverter;\n\n\t\t\t//Internal Type Conversion Methods\n\t\t\tvoid ConvertProjectionMatricesListToPosesSequence(std::vector<cv::Mat> projectionMatricesList, PoseWrapper::Poses3DSequence& posesSequence);\n\n\t\t\t//Core Computation Methods\n\t\t\tstd::vector<cv::Mat> SolveBundleAdjustment(cv::Mat measurementMatrix, bool& success);\n\t\t\tvoid InitializePoints(std::vector<Point3d>& pointCloud, cv::Mat measurementMatrix);\n\t\t\tvoid InitializePoses(std::vector<Transform3d>& posesSequence, int numberOfImages);\n\t\t\tbool PointIsNotInVector(BaseTypesWrapper::Point2D point, const std::vector<BaseTypesWrapper::Point2D>& vector);\n\n\t\t\t//Validation Methods\n\t\t\tvoid ValidateParameters();\n\t\t\tvoid ValidateInputs();\n\t\t\tvoid ValidateInitialEstimations(int numberOfCameras);\n\n\t};\n}\n}\n}\n\n#endif // BUNDLEADJUSTMENT_CERESADJUSTMENT_HPP\n\n/** @} */\n", "meta": {"hexsha": "7abf964ab8ef1d83bbbcbd776300f973fe162aab", "size": 3363, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "DFNs/BundleAdjustment/CeresAdjustment.hpp", "max_stars_repo_name": "H2020-InFuse/cdff", "max_stars_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-26T15:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T07:39:01.000Z", "max_issues_repo_path": "DFNs/BundleAdjustment/CeresAdjustment.hpp", "max_issues_repo_name": "H2020-InFuse/cdff", "max_issues_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "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": "DFNs/BundleAdjustment/CeresAdjustment.hpp", "max_forks_repo_name": "H2020-InFuse/cdff", "max_forks_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-06T12:09:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T12:09:05.000Z", "avg_line_length": 28.5, "max_line_length": 143, "alphanum_fraction": 0.7692536426, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571775, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5290724871750754}}
{"text": "#include \"Network.hpp\"\r\n#include <stdexcept>\r\n#include <math.h>\r\n#include <ctime>\r\n#include <cstdlib>\r\n#include <algorithm>\r\n#include <boost/numeric/ublas/matrix_proxy.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n\r\n\r\nNetwork::Network(const std::vector<int> &layers, double lR):\r\n\tlearningRate(lR),\r\n\tnbLayers(layers.size()),\r\n\terrors(),\r\n\tinputs(),\r\n\toutputs(),\r\n\tweights(),\r\n\tbiases(),\r\n\tfunctions(),\r\n\tderivates()\r\n{\r\n\tif (layers.size() < 3)\r\n\t\tthrow std::invalid_argument(\"Network must contain at least one hidden layer\");\r\n\r\n\tstd::srand(std::time(0));\r\n\tthis->initializeNetwork(layers);\r\n\r\n\t/* Setting activation functions & derivates */\r\n\tthis->functions.push_back(0);\r\n\tthis->derivates.push_back(0);\r\n\tfor (int i=0; i < this->nbLayers - 2; ++i)\r\n\t{\r\n\t\tthis->functions.push_back(new Function(&sigmoid));\r\n\t\tthis->derivates.push_back(new Function(&sigmoidPrime));\r\n\t}\r\n\tthis->functions.push_back(new Function(&identity));\r\n\tthis->derivates.push_back(new Function(&identityPrime));\r\n}\r\n\r\n\r\nNetwork::~Network()\r\n{\r\n\tfor (int i=0; i < this->nbLayers; ++i)\r\n\t{\r\n\t\tdelete this->errors[i];\r\n\t\tdelete this->outputs[i];\r\n\t\tdelete this->inputs[i];\r\n\r\n\t\tif (i != this->nbLayers - 1)\r\n\t\t{\r\n\t\t\tdelete this->biases[i];\r\n\t\t\tdelete this->weights[i];\r\n\t\t}\r\n\r\n\t\tif (this->functions[i])\r\n\t\t\tdelete this->functions[i];\r\n\t\tif (this->derivates[i])\r\n\t\t\tdelete this->derivates[i];\r\n\t}\r\n}\r\n\r\n\r\n/*\r\n\tInitializes all the components of the network\r\n \t(weights, biases, inputs, outputs, errors)\r\n*/\r\nvoid \t\t\t\t\t\tNetwork::initializeNetwork(const std::vector<int> &layers)\r\n{\r\n\t/* Initializing input & hidden layers */\r\n\tfor (unsigned int layer=0; layer < layers.size() - 1; ++layer)\r\n\t{\r\n\t\tint rows = layers[layer + 1];\r\n\t\tint columns = layers[layer];\r\n\r\n\t\tmatrix<double> \t*currentWeights = new matrix<double>(rows, columns);\r\n\t\tvector<double> \t*currentErrors = new vector<double>(columns);\r\n\t\tvector<double> \t*currentInputs = new vector<double>(columns);\r\n\t\tvector<double> \t*currentOutputs = new vector<double>(columns);\r\n\t\tvector<double>\t*currentBiases = new vector<double>(rows);\r\n\r\n\t\tfor (unsigned int i=0; i < currentWeights->size1(); ++i)\r\n\t\t{\r\n\t\t\tfor (unsigned j=0; j < currentWeights->size2(); ++j)\r\n\t\t\t{\r\n\t\t\t\t(*currentWeights)(i, j) = static_cast<double>(std::rand()) / RAND_MAX;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor (int i=0; i < rows; ++i)\r\n\t\t{\r\n\t\t\t(*currentBiases)[i] = static_cast<double>(std::rand()) / RAND_MAX;\r\n\t\t}\r\n\r\n\t\tstd::fill(currentErrors->begin(), currentErrors->end(), 0.0);\r\n\t\tstd::fill(currentInputs->begin(), currentInputs->end(), 0.0);\r\n\t\tstd::fill(currentOutputs->begin(), currentOutputs->end(), 0.0);\r\n\r\n\t\tthis->weights.push_back(currentWeights);\r\n\t\tthis->errors.push_back(currentErrors);\r\n\t\tthis->inputs.push_back(currentInputs);\r\n\t\tthis->outputs.push_back(currentOutputs);\r\n\t\tthis->biases.push_back(currentBiases);\r\n\t}\r\n\r\n\t/* Output layer */\r\n\tint outputSize = layers[layers.size() - 1];\r\n\r\n\tvector<double> *outputErrors = new vector<double>(outputSize);\r\n\tvector<double> *outputInputs = new vector<double>(outputSize);\r\n\tvector<double> *outputOutputs = new vector<double>(outputSize);\r\n\r\n\tstd::fill(outputErrors->begin(), outputErrors->end(), 0.0);\r\n\tstd::fill(outputInputs->begin(), outputInputs->end(), 0.0);\r\n\tstd::fill(outputOutputs->begin(), outputOutputs->end(), 0.0);\r\n\r\n\tthis->errors.push_back(outputErrors);\r\n\tthis->inputs.push_back(outputInputs);\r\n\tthis->outputs.push_back(outputOutputs);\r\n}\r\n\r\n\r\nvector<double> *Network::predict(const vector<double> &X)\r\n{\r\n\tif (X.size() != this->inputs[0]->size())\r\n\t\tthrow std::length_error(\"Invalid number of features\");\r\n\r\n\treturn this->feedForward(X);\r\n}\r\n\r\n\r\n/* Propagates the input through the network and returns the output */\r\nvector<double> \t*Network::feedForward(const vector<double> &X)\r\n{\r\n\tdelete this->inputs[0];\r\n\tdelete this->outputs[0];\r\n\r\n\tthis->inputs[0] = new vector<double>(X);\r\n\tthis->outputs[0] = new vector<double>(X);\r\n\r\n\tfor (int i=1; i < this->nbLayers; ++i)\r\n\t{\r\n\t\tdelete this->inputs[i];\r\n\t\tdelete this->outputs[i];\r\n\r\n\t\tthis->inputs[i] = new vector<double>(prod(*(this->weights[i - 1]), *(this->outputs[i - 1])) + *(this->biases[i - 1]));\r\n\t\tthis->outputs[i] = (*(this->functions[i]))(*(this->inputs[i]));\r\n\t}\r\n\r\n\treturn this->outputs[this->outputs.size() - 1];\r\n}\r\n\r\n\r\n/* Fits the network using the data given in parameter */\r\nvoid\t\t\tNetwork::fit(matrix<double> &X, matrix<double> &Y, const int iterations)\r\n{\r\n\tif (X.size1() != Y.size1())\r\n\t\tthrow std::length_error(\"Features and targets must have the same length\");\r\n\r\n\tfor (int iter=0; iter < iterations; ++iter)\r\n\t{\r\n\t\tfor (unsigned int idx=0; idx < X.size1(); ++idx)\r\n\t\t{\r\n\t\t\tmatrix_row<matrix<double> > rowX(X, idx);\r\n\t\t\tmatrix_row<matrix<double> > rowY(Y, idx);\r\n\r\n\t\t\tif (rowX.size() != this->inputs[0]->size())\r\n\t\t\t\tthrow std::length_error(\"Invalid number of features\");\r\n\r\n\t\t\tthis->updateWeights(this->row2vec(rowX), this->row2vec(rowY));\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n/* Updates the weights in the network by using the backpropagation algorithm */\r\nvoid\t\t\tNetwork::updateWeights(vector<double> *features, vector<double> *target)\r\n{\r\n\tFunction\t\t\t\tf(*(this->derivates[this->derivates.size() - 1]));\r\n\tvector<double> \t*output = this->feedForward(*features);\r\n\tvector<double> \tdiff = *output - *target;\r\n\tvector<double>\t*deriv = f(*(this->outputs[this->outputs.size() - 1]));\r\n\tvector<double>\t*err = new vector<double>(element_prod(*deriv, diff));\r\n\r\n\tdelete deriv;\r\n\tdelete this->errors[this->errors.size() - 1];\r\n\tthis->errors[this->errors.size() - 1] = err;\r\n\r\n\tfor (int i=this->nbLayers - 2; i > 0; --i)\r\n\t{\r\n\t\tvector<double>\t*deriv = (*(this->derivates[i]))(*(this->inputs[i]));\r\n\t\tvector<double>\tmul(prod(trans(*(this->weights[i])), *(this->errors[i + 1])));\r\n\t\tmatrix<double>\t*oldW = this->weights[i];\r\n\t\tvector<double>\t*oldB = this->biases[i];\r\n\r\n\t\tdelete this->errors[i];\r\n\t\tthis->errors[i] = new vector<double>(element_prod((*deriv), mul));\r\n\t\tthis->weights[i] = new matrix<double>(*(this->weights[i]) - (outer_prod(*(this->errors[i + 1]), *(this->outputs[i])) * this->learningRate));\r\n\t\tthis->biases[i] = new vector<double>(*(this->biases[i]) - (*(this->errors[i + 1]) * this->learningRate));\r\n\r\n\t\tdelete oldW;\r\n\t\tdelete oldB;\r\n\t\tdelete deriv;\r\n\t}\r\n\r\n\tmatrix<double>\t*oldW = this->weights[0];\r\n\tvector<double>\t*oldB = this->biases[0];\r\n\tthis->weights[0] = new matrix<double>(*(this->weights[0]) - (outer_prod(*(this->errors[1]), *(this->outputs[0])) * this->learningRate));\r\n\tthis->biases[0] = new vector<double>(*(this->biases[0]) - (*(this->errors[1])  * this->learningRate));\r\n\r\n\tdelete features;\r\n\tdelete target,\r\n\tdelete oldW;\r\n\tdelete oldB;\r\n}\r\n\r\n\r\nvector<double> \t*Network::sigmoid(const vector<double> &input)\r\n{\r\n\tvector<double> *result = new vector<double>(input.size());\r\n\r\n\tfor (unsigned int i=0; i < input.size(); ++i)\r\n\t{\r\n\t\t(*result)[i] = (1.0 / (1.0 + exp(-input[i])));\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\n\r\nvector<double> \t*Network::sigmoidPrime(const vector<double> &input)\r\n{\r\n\tvector<double>\t*result = new vector<double>(input.size());\r\n\r\n\tfor (unsigned int i=0; i < input.size(); ++i)\r\n\t{\r\n\t\tdouble sigmoid = (1.0 / (1.0 + exp(-input[i])));\r\n\t\t(*result)[i] = sigmoid * (1 - sigmoid);\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\n\r\nvector<double>\t*Network::identity(const vector<double> &input)\r\n{\r\n\treturn new vector<double>(input);\r\n}\r\n\r\n\r\nvector<double>\t*Network::identityPrime(const vector<double> &input)\r\n{\r\n\tvector<double>\t*result = new vector<double>(input.size());\r\n\r\n\tfor (unsigned int i=0; i < input.size(); ++i)\r\n\t{\r\n\t\t(*result)[i] = 1;\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\n\r\nvector<double>\t*Network::row2vec(const matrix_row<matrix<double> > &row) const\r\n{\r\n\tvector<double>\tvec(row.size());\r\n\r\n\tstd::copy(row.begin(), row.end(), vec.begin());\r\n\r\n\treturn new vector<double>(vec);\r\n}\r\n\r\n\r\nstd::ostream&\toperator<<(std::ostream& os, const Network& net)\r\n{\r\n\tfor (unsigned int layer=0; layer < net.outputs.size(); ++layer)\r\n\t{\r\n\t\tos << \"-> Layer \" << layer << \" : \" << net.outputs[layer]->size() << \" neuron(s)\" << std::endl;\r\n\t}\r\n\r\n    return os;\r\n}\r\n", "meta": {"hexsha": "d3bd67e960ebdfb3f2cd9cfb588c9682cd535fd2", "size": 7971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Network.cpp", "max_stars_repo_name": "amstuta/cpp_neural_network", "max_stars_repo_head_hexsha": "e664cd15a7119b418f4fb35775ab510d6b7655a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-19T22:46:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:48:43.000Z", "max_issues_repo_path": "Network.cpp", "max_issues_repo_name": "amstuta/cpp_neural_network", "max_issues_repo_head_hexsha": "e664cd15a7119b418f4fb35775ab510d6b7655a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Network.cpp", "max_forks_repo_name": "amstuta/cpp_neural_network", "max_forks_repo_head_hexsha": "e664cd15a7119b418f4fb35775ab510d6b7655a6", "max_forks_repo_licenses": ["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.2659574468, "max_line_length": 143, "alphanum_fraction": 0.6350520637, "num_tokens": 2165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5290724848094823}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <math.h>\n#include <complex>\n\nusing Eigen::MatrixXcd;\nusing Eigen::MatrixXd;\nusing Eigen::ComputeThinU;\nusing Eigen::ComputeThinV;\n\n// we firstly make a quite naive example, take n, s and return polynomial a\nEigen::MatrixXcd solve_poly_a(int n, int s, Eigen::MatrixXcd R)\n{\n\tint hat_s = 2 * s + 1;\n\tint p = 3;\n\n\tMatrixXcd C = MatrixXcd::Zero(n, n);\n\tMatrixXcd C1 = MatrixXcd::Zero(n, n-hat_s+1);\n\tMatrixXcd C2 = MatrixXcd::Zero(n, hat_s-1);\n\tMatrixXcd W_fake = MatrixXcd::Zero(n, p);\n\tMatrixXcd WPerp = MatrixXcd::Zero(hat_s-1, n);\n\n\tMatrixXcd A = MatrixXcd::Zero(s, s);\n\tMatrixXcd b = MatrixXcd::Zero(s, 1);\n\n\tMatrixXd G = MatrixXd::Random(p, 1);\n\tMatrixXd Q1 = MatrixXd::Random(n-2*s-1,p);\n\tMatrixXd Q = MatrixXd::Ones(n-2*s,p);\n\tMatrixXd eps = MatrixXd::Zero(n, 1);\n\n\tQ.topRows(n-2*s-1) = Q1;\n\teps.topRows(s) = -100.0*MatrixXd::Ones(s, 1);\n\n\tdouble factor1 = 1/std::sqrt(n);\n\t// generate C matrix:\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tfor (int j = 0; j < n; ++j)\n\t\t{\t\n\t\t\tif (j >= i)\n\t\t\t{\n\t\t\t\tif ((i == 0) || (j == 0))\n\t\t\t\t{\n\t\t\t\t\tC(i, j) = std::complex<double>(1, 0);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tstd::complex<double> temptElementValue = std::complex<double>(0, (-2*i*j*M_PI)/n);\n\t\t\t\t\tC(i, j) = std::exp(temptElementValue);\n\t\t\t\t} \n\t\t\t}\n\t\t\telse{\n\t\t\t\tC(i, j) = C(j, i);\n\t\t\t}\n\n\t\t}\n\t}\n\tC *= factor1;\n\t// fetch C1 and C2:\n\tC1 = C.leftCols(n-hat_s+1);\n\tC2 = C.rightCols(hat_s-1);\n\n\tWPerp = C2.adjoint();\n\tW_fake = C1 * Q;\n\n\t//MatrixXcd R = W_fake * G + eps;\n\t// we assume here R is passed by Python side\n\t// and it is a complex vector, shape of R should\n\t// be n * 1\n\tMatrixXcd E2 = WPerp * R;\n\n\t// form A * x = b:\n\tfor (int i = 0; i < s; ++i)\n\t{\n\t\tA.row(i) = E2.col(0).segment(2*s-i-s-1,s).transpose();\n\t\tb.row(i) = E2.row(2*s-i-1);\n\t}\n\t//MatrixXcd alpha = A.colPivHouseholderQr().solve(b);\n\tMatrixXcd alpha = A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b);\n\treturn alpha;\n}\n\nnamespace py = pybind11;\n\nPYBIND11_MODULE(coding, m)\n{\n  m.doc() = \"pybind11 coding plugin\";\n\n  m.def(\"solve_poly_a\", &solve_poly_a, py::arg(\"n\"), py::arg(\"s\"), py::arg(\"R\"));\n  //m.def(\"solve_poly_a\", &solve_poly_a, py::arg(\"n\"), py::arg(\"s\"));\n}\n", "meta": {"hexsha": "524212d73578c97f5847a7b6b39e693f479387aa", "size": 2224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/coding.cpp", "max_stars_repo_name": "hwang595/Draco", "max_stars_repo_head_hexsha": "8472912cce82e6d74087a402fd417e7a837517ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2018-09-19T06:30:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T22:44:39.000Z", "max_issues_repo_path": "src/coding.cpp", "max_issues_repo_name": "hwang595/Draco", "max_issues_repo_head_hexsha": "8472912cce82e6d74087a402fd417e7a837517ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-12-31T05:44:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T15:59:46.000Z", "max_forks_repo_path": "src/coding.cpp", "max_forks_repo_name": "hwang595/Draco", "max_forks_repo_head_hexsha": "8472912cce82e6d74087a402fd417e7a837517ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-09-19T06:30:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T09:53:54.000Z", "avg_line_length": 23.6595744681, "max_line_length": 87, "alphanum_fraction": 0.6079136691, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5290724800782964}}
{"text": "/**\n * \\file\n *\n * \\copyright\n * Copyright (c) 2012-2020, 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 <boost/math/special_functions/pow.hpp>\n#include <cmath>\n\n#include \"MaterialLib/MPL/Properties/ExponentialProperty.h\"\n\nnamespace MaterialPropertyLib\n{\nExponentialProperty::ExponentialProperty(\n    PropertyDataType const& property_reference_value, ExponentData const& v)\n    : _exponent_data(v)\n{\n    _value = property_reference_value;\n}\n\nPropertyDataType ExponentialProperty::value(\n    VariableArray const& variable_array,\n    ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/,\n    double const /*dt*/) const\n{\n    return std::get<double>(_value) *\n           std::exp(\n               -std::get<double>(_exponent_data.factor) *\n               (std::get<double>(\n                    variable_array[static_cast<int>(_exponent_data.type)]) -\n                std::get<double>(_exponent_data.reference_condition)));\n}\n\nPropertyDataType ExponentialProperty::dValue(\n    VariableArray const& variable_array, Variable const primary_variable,\n    ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/,\n    double const /*dt*/) const\n{\n    return _exponent_data.type == primary_variable\n               ? -std::get<double>(_value) *\n                     std::get<double>(_exponent_data.factor) *\n                     std::exp(\n                         -std::get<double>(_exponent_data.factor) *\n                         (std::get<double>(variable_array[static_cast<int>(\n                              _exponent_data.type)]) -\n                          std::get<double>(_exponent_data.reference_condition)))\n               : decltype(_value){};\n}\n\nPropertyDataType ExponentialProperty::d2Value(\n    VariableArray const& variable_array, Variable const pv1, Variable const pv2,\n    ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/,\n    double const /*dt*/) const\n{\n    return _exponent_data.type == pv1 && _exponent_data.type == pv2\n               ? std::get<double>(_value) *\n                     boost::math::pow<2>(\n                         std::get<double>(_exponent_data.factor)) *\n                     std::exp(\n                         -std::get<double>(_exponent_data.factor) *\n                         (std::get<double>(variable_array[static_cast<int>(\n                              _exponent_data.type)]) -\n                          std::get<double>(_exponent_data.reference_condition)))\n               : decltype(_value){};\n}\n\n}  // namespace MaterialPropertyLib\n", "meta": {"hexsha": "c1047231fa1033792ab58baa1cf9836e3ca4a05c", "size": 2690, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MaterialLib/MPL/Properties/ExponentialProperty.cpp", "max_stars_repo_name": "OlafKolditz/ogs", "max_stars_repo_head_hexsha": "e33400e1d9503d33ce80509a3441a873962ad675", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-24T13:33:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T13:33:52.000Z", "max_issues_repo_path": "MaterialLib/MPL/Properties/ExponentialProperty.cpp", "max_issues_repo_name": "OlafKolditz/ogs", "max_issues_repo_head_hexsha": "e33400e1d9503d33ce80509a3441a873962ad675", "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": "MaterialLib/MPL/Properties/ExponentialProperty.cpp", "max_forks_repo_name": "OlafKolditz/ogs", "max_forks_repo_head_hexsha": "e33400e1d9503d33ce80509a3441a873962ad675", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T05:55:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-15T05:55:55.000Z", "avg_line_length": 37.3611111111, "max_line_length": 80, "alphanum_fraction": 0.6040892193, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5290298998492908}}
{"text": "#include \"Harmonic.hh\"\n\n#include <LayoutEmbedding/Util/Assert.hh>\n#include <Eigen/SparseLU>\n\nnamespace LayoutEmbedding\n{\n\nnamespace\n{\n\n/// Angle at to-vertex between given and next halfedge\nauto calc_sector_angle(\n        const pm::vertex_attribute<tg::pos3>& _pos,\n        const pm::halfedge_handle& _h)\n{\n    const auto v1 = _pos[_h.next().vertex_to()] - _pos[_h.vertex_to()];\n    const auto v2 = _pos[_h.vertex_from()] - _pos[_h.vertex_to()];\n    return tg::angle_between(v1, v2);\n}\n\ndouble mean_value_weight(\n        const pm::vertex_attribute<tg::pos3>& _pos,\n        const pm::halfedge_handle& _h)\n{\n    if (_h.edge().is_boundary())\n        return 0.0;\n\n    const auto angle_l = calc_sector_angle(_pos, _h.prev());\n    const auto angle_r = calc_sector_angle(_pos, _h.opposite());\n    const auto edge_length = pm::edge_length(_h, _pos);\n    double w_ij = (tan(angle_l.radians() / 2.0) + tan(angle_r.radians() / 2.0)) / edge_length;\n\n    if (w_ij <= 0.0)\n        w_ij = 1e-5;\n\n    return w_ij;\n}\n\n}\n\nbool harmonic(\n        const pm::vertex_attribute<tg::pos3>& _pos,\n        const pm::vertex_attribute<bool>& _constrained,\n        const Eigen::MatrixXd& _constraint_values,\n        Eigen::MatrixXd& _res,\n        const LaplaceWeights _weights,\n        const bool _fallback_iterative)\n{\n    LE_ASSERT(_pos.mesh().is_compact());\n\n    const int n = _pos.mesh().vertices().size();\n    const int d = _constraint_values.cols();\n    LE_ASSERT_EQ(_constraint_values.rows(), n);\n\n    // Set up Laplace matrix and rhs\n    Eigen::MatrixXd rhs = Eigen::MatrixXd::Zero(n, d);\n    std::vector<Eigen::Triplet<double>> triplets;\n    for (auto v : _pos.mesh().vertices())\n    {\n        const int i = v.idx.value;\n\n        if (_constrained[v])\n        {\n            triplets.push_back(Eigen::Triplet<double>(i, i, 1.0));\n            rhs.row(i) = _constraint_values.row(i);\n        }\n        else\n        {\n            LE_ASSERT(!v.is_boundary());\n\n            for (auto h : v.outgoing_halfedges())\n            {\n                const int j = h.vertex_to().idx.value;\n                double w_ij;\n                if (_weights == LaplaceWeights::Uniform)\n                    w_ij = 1.0;\n                else if (_weights == LaplaceWeights::MeanValue)\n                    w_ij = mean_value_weight(_pos, h);\n                else\n                    LE_ERROR_THROW(\"\");\n\n                triplets.push_back(Eigen::Triplet<double>(i, j, w_ij));\n                triplets.push_back(Eigen::Triplet<double>(i, i, -w_ij));\n            }\n        }\n    }\n\n    Eigen::SparseMatrix<double> L(n, n);\n    L.setFromTriplets(triplets.begin(), triplets.end());\n\n    Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n    solver.compute(L);\n    if (solver.info() == Eigen::Success)\n    {\n        _res = solver.solve(rhs);\n        if (solver.info() == Eigen::Success)\n            return true;\n    }\n\n    std::cout << \"LU solve failed\" << std::endl;\n\n    if (_fallback_iterative)\n    {\n        std::cout << \"Falling back to iterative solver\" << std::endl;\n    }\n\n    return false;\n}\n\nbool harmonic_parametrization(\n        const pm::vertex_attribute<tg::pos3>& _pos,\n        const pm::vertex_attribute<bool>& _constrained,\n        const VertexParam& _constraint_values,\n        VertexParam& _res,\n        const LaplaceWeights _weights,\n        const bool _fallback_iterative)\n{\n    const int n = _pos.mesh().vertices().size();\n    const int d = 2;\n\n    // Convert constraints\n    Eigen::MatrixXd constraint_values = Eigen::MatrixXd::Zero(n, d);\n    for (auto v : _pos.mesh().vertices())\n        constraint_values.row(v.idx.value) = Eigen::Vector2d(_constraint_values[v].x, _constraint_values[v].y);\n\n    // Compute\n    Eigen::MatrixXd res_mat;\n    if (!harmonic(_pos, _constrained, constraint_values, res_mat, _weights, _fallback_iterative))\n        return false;\n\n    // Convert result\n    _res = _pos.mesh().vertices().make_attribute<tg::dpos2>();\n    for (auto v : _pos.mesh().vertices())\n        _res[v] = tg::dpos2(res_mat(v.idx.value, 0), res_mat(v.idx.value, 1));\n\n    return true;\n}\n\n}\n", "meta": {"hexsha": "6899ca02c00b11d98d27956986e48f9a3d47dbf9", "size": 4058, "ext": "cc", "lang": "C++", "max_stars_repo_path": "library/LayoutEmbedding/Harmonic.cc", "max_stars_repo_name": "jsb/LayoutEmbedding", "max_stars_repo_head_hexsha": "6ef02ed0043dfabce6d593486358d6ef15cbf3ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2021-02-18T15:35:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T07:20:37.000Z", "max_issues_repo_path": "library/LayoutEmbedding/Harmonic.cc", "max_issues_repo_name": "jsb/LayoutEmbedding", "max_issues_repo_head_hexsha": "6ef02ed0043dfabce6d593486358d6ef15cbf3ba", "max_issues_repo_licenses": ["MIT"], "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/LayoutEmbedding/Harmonic.cc", "max_forks_repo_name": "jsb/LayoutEmbedding", "max_forks_repo_head_hexsha": "6ef02ed0043dfabce6d593486358d6ef15cbf3ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-02-17T14:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T09:51:25.000Z", "avg_line_length": 28.780141844, "max_line_length": 111, "alphanum_fraction": 0.6020206999, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5289824069475743}}
{"text": "//==================================================================================================\n/*\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n*/\n//==================================================================================================\n#include <eve/module/core.hpp>\n#include <eve/module/bessel.hpp>\n#include <cmath>\n#include <boost/math/special_functions/bessel.hpp>\n\nint main()\n{\n  auto lmin = EVE_VALUE(0);\n  auto lmax = EVE_VALUE(11);\n  auto lmin1 = EVE_VALUE(0);\n  auto lmax1 = EVE_VALUE(100);\n\n  auto arg0 = eve::bench::random_<EVE_VALUE>(lmin,lmax);\n  auto arg1= eve::bench::random_<EVE_VALUE>(lmin1,lmax1);\n  auto stdjn   = [](auto n, auto x){return std::cyl_bessel_j(n, x);};\n  auto boostjn = [](auto n, auto x){return boost::math::cyl_bessel_j(n, x);};\n  eve::bench::experiment xp;\n  run<EVE_TYPE> (EVE_NAME(cyl_bessel_jn) , xp, eve::cyl_bessel_jn , arg0, arg1);\n  run<EVE_VALUE>(EVE_NAME(cyl_bessel_jn) , xp, eve::cyl_bessel_jn , arg0, arg1);\n  run<EVE_VALUE>(EVE_NAME(stdjn), xp, stdjn , arg0, arg1);\n  run<EVE_VALUE>(EVE_NAME(boostjn), xp, boostjn , arg0, arg1);\n}\n", "meta": {"hexsha": "2229316cac32cbd29b717e9802923a8ea9b0411c", "size": 1159, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmarks/module/bessel/cyl_bessel_jn/regular/cyl_bessel_jn.hpp", "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": "benchmarks/module/bessel/cyl_bessel_jn/regular/cyl_bessel_jn.hpp", "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": "benchmarks/module/bessel/cyl_bessel_jn/regular/cyl_bessel_jn.hpp", "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": 38.6333333333, "max_line_length": 100, "alphanum_fraction": 0.5737704918, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5289824069475743}}
{"text": "//  (C) Copyright John Maddock 2013.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/math/special_functions/bernoulli.hpp>\r\n#include <boost/chrono.hpp>\r\n#include <boost/multiprecision/cpp_dec_float.hpp>\r\n\r\ntemplate <class Clock>\r\nstruct stopwatch\r\n{\r\n   typedef typename Clock::duration duration;\r\n   stopwatch()\r\n   {\r\n      m_start = Clock::now();\r\n   }\r\n   duration elapsed()\r\n   {\r\n      return Clock::now() - m_start;\r\n   }\r\n   void reset()\r\n   {\r\n      m_start = Clock::now();\r\n   }\r\n\r\nprivate:\r\n   typename Clock::time_point m_start;\r\n};\r\n\r\nvoid time()\r\n{\r\n   stopwatch<boost::chrono::high_resolution_clock> w;\r\n   //\r\n   // Sum the first 1000 Bernoulli numbers:\r\n   //\r\n   boost::multiprecision::cpp_dec_float_50 sum = 0;\r\n   for(unsigned i = 0; i < 1000; ++i)\r\n   {\r\n      sum += boost::math::bernoulli_b2n<boost::multiprecision::cpp_dec_float_50>(i);\r\n   }\r\n   double t = boost::chrono::duration_cast<boost::chrono::duration<double> >(w.elapsed()).count();\r\n   std::cout << \"Total execution time = \" << std::setprecision(3) << t << \"s\" << std::endl;\r\n   std::cout << \"Sum was: \" << sum << std::endl;\r\n}\r\n\r\nint main()\r\n{\r\n   // Call time() twice: first call results in the cache being populated, second used already cached values:\r\n   time();\r\n   time();\r\n   return 0;\r\n}\r\n\r\n/*\r\n\r\nNo atomic int:\r\n\r\nTotal execution time = 0.646s\r\nSum was: 2.86e+4134\r\nTotal execution time = 0.000341s\r\nSum was: 2.86e+4134\r\n\r\nWith atomic int:\r\n\r\nTotal execution time = 0.643s\r\nSum was: 2.86e+4134\r\nTotal execution time = 0.000309s\r\nSum was: 2.86e+4134\r\n\r\nNo threads:\r\n\r\nTotal execution time = 0.652s\r\nSum was: 2.86e+4134\r\nTotal execution time = 0.000281s\r\nSum was: 2.86e+4134\r\n\r\n*/\r\n\r\n", "meta": {"hexsha": "cadcb694df49669d2e824ee258cd1e54fff0c0e7", "size": 1841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/performance/bernoulli_performance.cpp", "max_stars_repo_name": "Abce/boost", "max_stars_repo_head_hexsha": "2d7491a27211aa5defab113f8e2d657c3d85ca93", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/math/performance/bernoulli_performance.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/performance/bernoulli_performance.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": 23.0125, "max_line_length": 109, "alphanum_fraction": 0.639326453, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5288956029329117}}
{"text": "/*\n * Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// includes\n// std\n#include <iostream>\n\n// boost\n#define BOOST_TEST_MODULE Algo\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/unit_test.hpp>\n\n// SpaceVecAlg\n#include <SpaceVecAlg/SpaceVecAlg>\n\n// RBDyn\n#include \"RBDyn/Body.h\"\n#include \"RBDyn/EulerIntegration.h\"\n#include \"RBDyn/FA.h\"\n#include \"RBDyn/FK.h\"\n#include \"RBDyn/FV.h\"\n#include \"RBDyn/ID.h\"\n#include \"RBDyn/IK.h\"\n#include \"RBDyn/Jacobian.h\"\n#include \"RBDyn/Joint.h\"\n#include \"RBDyn/MultiBody.h\"\n#include \"RBDyn/MultiBodyConfig.h\"\n#include \"RBDyn/MultiBodyGraph.h\"\n\n// arm\n#include \"XYZSarm.h\"\n#include \"XYZarm.h\"\n\nnamespace rbd\n{\nstatic constexpr double PI = boost::math::constants::pi<double>();\n}\n\nconst double TOL = 0.0000001;\n\nBOOST_AUTO_TEST_CASE(FKTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  namespace cst = boost::math::constants;\n\n  rbd::MultiBody mb, mb2;\n  rbd::MultiBodyConfig mbc, mbc2;\n  rbd::MultiBodyGraph mbg, mbg2;\n  std::tie(mb, mbc, mbg) = makeXYZarm();\n  std::tie(mb2, mbc2, mbg2) = makeXYZSarm();\n\n  // check identity\n  mbc.q = {{}, {0.}, {0.}, {0.}};\n\n  forwardKinematics(mb, mbc);\n\n  std::vector<PTransformd> res = {PTransformd(Vector3d(0., 0., 0.)), PTransformd(Vector3d(0., 0.5, 0)),\n                                  PTransformd(Vector3d(0., 1.5, 0.)), PTransformd(Vector3d(0., 2.5, 0))};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc.bodyPosW.begin(), mbc.bodyPosW.end());\n\n  // check rotX\n  mbc.q = {{}, {cst::pi<double>() / 2.}, {0.}, {0.}};\n\n  forwardKinematics(mb, mbc);\n\n  res = {PTransformd(Vector3d(0., 0., 0.)), PTransformd(RotX(cst::pi<double>() / 2.), Vector3d(0., 0.5, 0.)),\n         PTransformd(RotX(cst::pi<double>() / 2.), Vector3d(0., 0.5, 1.)),\n         PTransformd(RotX(cst::pi<double>() / 2.), Vector3d(0., 0.5, 2.))};\n\n  for(size_t i = 0; i < res.size(); ++i)\n  {\n    BOOST_CHECK_SMALL((res[i].translation() - mbc.bodyPosW[i].translation()).norm(), TOL);\n    BOOST_CHECK_SMALL((res[i].rotation() - mbc.bodyPosW[i].rotation()).norm(), TOL);\n  }\n\n  // check rotY\n  mbc.q = {{}, {0.}, {cst::pi<double>() / 2.}, {0.}};\n\n  forwardKinematics(mb, mbc);\n\n  res = {PTransformd(Vector3d(0., 0., 0.)), PTransformd(Vector3d(0., .5, 0.)),\n         PTransformd(RotY(cst::pi<double>() / 2.), Vector3d(0., 1.5, 0.)),\n         PTransformd(RotY(cst::pi<double>() / 2.), Vector3d(0., 2.5, 0.))};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc.bodyPosW.begin(), mbc.bodyPosW.end());\n\n  // check rotZ\n  mbc.q = {{}, {0.}, {0.}, {cst::pi<double>() / 2.}};\n\n  forwardKinematics(mb, mbc);\n\n  res = {PTransformd(Vector3d(0., 0., 0.)), PTransformd(Vector3d(0., 0.5, 0.)), PTransformd(Vector3d(0., 1.5, 0.)),\n         PTransformd(RotZ(cst::pi<double>() / 2.), Vector3d(0., 2.5, 0.))};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc.bodyPosW.begin(), mbc.bodyPosW.end());\n\n  // check identity\n  mbc2.q = {{}, {0.}, {0.}, {0.}, {1., 0., 0., 0.}};\n\n  forwardKinematics(mb2, mbc2);\n\n  res = {PTransformd(Vector3d(0., 0., 0.)), PTransformd(Vector3d(0., 0.5, 0)), PTransformd(Vector3d(0., 1.5, 0.)),\n         PTransformd(Vector3d(0., 2.5, 0)), PTransformd(Vector3d(0.5, 1., 0.))};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc2.bodyPosW.begin(), mbc2.bodyPosW.end());\n  // check sphere rot Y\n  Quaterniond q(AngleAxisd(cst::pi<double>() / 2., Vector3d::UnitY()));\n  mbc2.q = {{}, {0.}, {0.}, {0.}, {q.w(), q.x(), q.y(), q.z()}};\n\n  forwardKinematics(mb2, mbc2);\n\n  res = {PTransformd(Vector3d(0., 0., 0.)), PTransformd(Vector3d(0., 0.5, 0)), PTransformd(Vector3d(0., 1.5, 0.)),\n         PTransformd(Vector3d(0., 2.5, 0)), PTransformd(RotY(cst::pi<double>() / 2.), Vector3d(0.5, 1., 0.))};\n\n  for(size_t i = 0; i < res.size(); ++i)\n  {\n    BOOST_CHECK_SMALL((res[i].translation() - mbc2.bodyPosW[i].translation()).norm(), TOL);\n    BOOST_CHECK_SMALL((res[i].rotation() - mbc2.bodyPosW[i].rotation()).norm(), TOL);\n  }\n\n  // check j1 rotX\n  mbc2.q = {{}, {cst::pi<double>() / 2.}, {0.}, {0.}, {1., 0., 0., 0.}};\n\n  forwardKinematics(mb2, mbc2);\n\n  res = {PTransformd(Vector3d(0., 0., 0.)), PTransformd(RotX(cst::pi<double>() / 2.), Vector3d(0., 0.5, 0.)),\n         PTransformd(RotX(cst::pi<double>() / 2.), Vector3d(0., 0.5, 1.)),\n         PTransformd(RotX(cst::pi<double>() / 2.), Vector3d(0., 0.5, 2.)),\n         PTransformd(RotX(cst::pi<double>() / 2.), Vector3d(0.5, 0.5, 0.5))};\n\n  for(size_t i = 0; i < res.size(); ++i)\n  {\n    BOOST_CHECK_SMALL((res[i].translation() - mbc2.bodyPosW[i].translation()).norm(), TOL);\n    BOOST_CHECK_SMALL((res[i].rotation() - mbc2.bodyPosW[i].rotation()).norm(), TOL);\n  }\n\n  // test safe version\n  BOOST_CHECK_NO_THROW(sForwardKinematics(mb2, mbc2));\n\n  // bad number of body\n  MultiBodyConfig mbcBadNrBody = mbc2;\n  mbcBadNrBody.bodyPosW.resize(4);\n\n  BOOST_CHECK_THROW(sForwardKinematics(mb2, mbcBadNrBody), std::domain_error);\n\n  // bad number of generalized position variable\n  MultiBodyConfig mbcBadNrQ = mbc2;\n  mbcBadNrQ.q = {{0.}, {0.}, {0.}, {1., 0., 0., 0.}};\n\n  BOOST_CHECK_THROW(sForwardKinematics(mb2, mbcBadNrQ), std::domain_error);\n\n  // bad generalized position variable size\n  MultiBodyConfig mbcBadQSize = mbc2;\n  mbcBadQSize.q = {{}, {0.}, {0.}, {0.}, {1., 0., 0.}};\n\n  BOOST_CHECK_THROW(sForwardKinematics(mb2, mbcBadQSize), std::domain_error);\n}\n\nBOOST_AUTO_TEST_CASE(FVTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  namespace cst = boost::math::constants;\n\n  rbd::MultiBody mb, mb2;\n  rbd::MultiBodyConfig mbc, mbc2;\n  rbd::MultiBodyGraph mbg, mbg2;\n  std::tie(mb, mbc, mbg) = makeXYZarm();\n  std::tie(mb2, mbc2, mbg2) = makeXYZSarm();\n\n  // check identity\n  mbc.q = {{}, {0.}, {0.}, {0.}};\n  mbc.alpha = {{}, {0.}, {0.}, {0.}};\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  std::vector<MotionVecd> res = {MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()),\n                                 MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero())};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc.bodyVelW.begin(), mbc.bodyVelW.end());\n\n  // check rot X\n  mbc.alpha = {{}, {1.}, {0.}, {0.}};\n  forwardVelocity(mb, mbc);\n\n  res = {MotionVecd(Vector6d::Zero()), MotionVecd(Vector3d(1., 0., 0.), Vector3d(0., 0., 0.)),\n         MotionVecd(Vector3d(1., 0., 0.), Vector3d(0., 0., 1.)),\n         MotionVecd(Vector3d(1., 0., 0.), Vector3d(0., 0., 2.))};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc.bodyVelW.begin(), mbc.bodyVelW.end());\n\n  // check rot Y\n  mbc.alpha = {{}, {0.}, {1.}, {0.}};\n  forwardVelocity(mb, mbc);\n\n  res = {MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()),\n         MotionVecd(Vector3d(0., 1., 0.), Vector3d(0., 0., 0.)),\n         MotionVecd(Vector3d(0., 1., 0.), Vector3d(0., 0., 0.))};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc.bodyVelW.begin(), mbc.bodyVelW.end());\n\n  // check rot Z\n  mbc.alpha = {{}, {0.}, {0.}, {1.}};\n  forwardVelocity(mb, mbc);\n\n  res = {MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()),\n         MotionVecd(Vector3d(0., 0., 1.), Vector3d(0., 0., 0.))};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc.bodyVelW.begin(), mbc.bodyVelW.end());\n\n  // check rot X with 90 X rotation\n  mbc.q = {{}, {cst::pi<double>() / 2.}, {0.}, {0.}};\n  mbc.alpha = {{}, {1.}, {0.}, {0.}};\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  res = {MotionVecd(Vector6d::Zero()), MotionVecd(Vector3d(1., 0., 0.), Vector3d(0., 0., 0.)),\n         MotionVecd(Vector3d(1., 0., 0.), Vector3d(0., -1., 0.)),\n         MotionVecd(Vector3d(1., 0., 0.), Vector3d(0., -2., 0.))};\n\n  for(size_t i = 0; i < res.size(); ++i)\n  {\n    BOOST_CHECK_SMALL((res[i].vector() - mbc.bodyVelW[i].vector()).norm(), TOL);\n  }\n\n  // check rot X with 90 Y rotation\n  mbc.alpha = {{}, {0.}, {1.}, {0.}};\n\n  forwardVelocity(mb, mbc);\n\n  res = {MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()),\n         MotionVecd(Vector3d(0., 0., 1.), Vector3d(0., 0., 0.)),\n         MotionVecd(Vector3d(0., 0., 1.), Vector3d(0., 0., 0.))};\n\n  for(size_t i = 0; i < res.size(); ++i)\n  {\n    BOOST_CHECK_SMALL((res[i].vector() - mbc.bodyVelW[i].vector()).norm(), TOL);\n  }\n\n  // check rot X with 90 Z rotation\n  mbc.alpha = {{}, {0.}, {0.}, {1.}};\n\n  forwardVelocity(mb, mbc);\n\n  res = {MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()),\n         MotionVecd(Vector3d(0., -1., 0.), Vector3d(0., 0., 0.))};\n\n  // check identity\n  mbc2.q = {{}, {0.}, {0.}, {0.}, {1., 0., 0., 0.}};\n  mbc2.alpha = {{}, {0.}, {0.}, {0.}, {0., 0., 0.}};\n\n  forwardKinematics(mb2, mbc2);\n  forwardVelocity(mb2, mbc2);\n\n  res = {MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()),\n         MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero())};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc2.bodyVelW.begin(), mbc2.bodyVelW.end());\n\n  // check spherical X\n  mbc2.alpha = {{}, {0.}, {0.}, {0.}, {1., 0., 0.}};\n\n  forwardVelocity(mb2, mbc2);\n\n  res = {MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()),\n         MotionVecd(Vector6d::Zero()), MotionVecd(Vector3d(1., 0., 0.), Vector3d(0., 0., 0.))};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc2.bodyVelW.begin(), mbc2.bodyVelW.end());\n\n  // check spherical Y\n  mbc2.alpha = {{}, {0.}, {0.}, {0.}, {0., 1., 0.}};\n\n  forwardVelocity(mb2, mbc2);\n\n  res = {MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()),\n         MotionVecd(Vector6d::Zero()), MotionVecd(Vector3d(0., 1., 0.), Vector3d(0., 0., 0.))};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc2.bodyVelW.begin(), mbc2.bodyVelW.end());\n\n  // check spherical Z\n  mbc2.alpha = {{}, {0.}, {0.}, {0.}, {0., 0., 1.}};\n\n  forwardVelocity(mb2, mbc2);\n\n  res = {MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()), MotionVecd(Vector6d::Zero()),\n         MotionVecd(Vector6d::Zero()), MotionVecd(Vector3d(0., 0., 1.), Vector3d(0., 0., 0.))};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc2.bodyVelW.begin(), mbc2.bodyVelW.end());\n}\n\nBOOST_AUTO_TEST_CASE(FreeFlyerTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  namespace cst = boost::math::constants;\n\n  MultiBodyGraph mbg;\n\n  double mass = 1.;\n  Matrix3d I = Matrix3d::Identity();\n  Vector3d h = Vector3d::Zero();\n\n  RBInertiad rbi(mass, h, I);\n\n  Body b0(rbi, \"b0\");\n\n  mbg.addBody(b0);\n\n  MultiBody mb = mbg.makeMultiBody(\"b0\", false);\n\n  MultiBodyConfig mbc(mb);\n\n  // check identity\n  mbc.q = {{1., 0., 0., 0., 0., 0., 0.}};\n  mbc.alpha = {{0., 0., 0., 0., 0., 0.}};\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  std::vector<MotionVecd> res = {MotionVecd(Vector6d::Zero())};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc.bodyVelW.begin(), mbc.bodyVelW.end());\n\n  // check Y Rot\n  Quaterniond q = Quaterniond::Identity();\n  mbc.q = {{q.w(), q.x(), q.y(), q.z(), 1., 0., 0.}};\n  mbc.alpha = {{0., 1., 0., 0., 0., 0.}};\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  res = {MotionVecd(Vector3d(0., 1., 0.), Vector3d(0., 0., 0.))};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), mbc.bodyVelW.begin(), mbc.bodyVelW.end());\n}\n\nBOOST_AUTO_TEST_CASE(EulerTest)\n{\n  using namespace std;\n  using namespace Eigen;\n  using namespace rbd;\n  namespace cst = boost::math::constants;\n\n  // 1 dof joint\n\n  // static\n  vector<double> q = {0.};\n\n  eulerJointIntegration(Joint::Rev, {0.}, {0.}, 1., q);\n\n  BOOST_CHECK_EQUAL(q[0], 0.);\n\n  // moving\n  eulerJointIntegration(Joint::Rev, {1.}, {0.}, 1., q);\n\n  BOOST_CHECK_EQUAL(q[0], 1.);\n\n  // free\n\n  // static\n  q = {1., 0., 0., 0., 0., 0., 0.};\n  vector<double> goalQ = q;\n  eulerJointIntegration(Joint::Spherical, {0., 0., 0., 0., 0., 0.}, {0., 0., 0., 0., 0., 0.}, 1., q);\n  BOOST_CHECK_EQUAL_COLLECTIONS(q.begin(), q.end(), goalQ.begin(), goalQ.end());\n\n  // X unit move\n  goalQ = {1., 0., 0., 0., 1., 0., 0.},\n  eulerJointIntegration(Joint::Free, {0., 0., 0., 1., 0., 0.}, {0., 0., 0., 0., 0., 0.}, 1., q);\n  BOOST_CHECK_EQUAL_COLLECTIONS(q.begin(), q.end(), goalQ.begin(), goalQ.end());\n\n  // X unit rot\n  const double pi = cst::pi<double>();\n  q = {1., 0., 0., 0., 0., 0., 0.};\n  goalQ = {std::cos(pi / 4), std::sin(pi / 4), 0., 0., 0., 0., 0.},\n  eulerJointIntegration(Joint::Free, {pi / 2., 0., 0., 0., 0., 0.}, {0., 0., 0., 0., 0., 0.}, 1., q);\n  BOOST_CHECK_EQUAL_COLLECTIONS(q.begin(), q.end(), goalQ.begin(), goalQ.end());\n\n  // planar\n  q = {0., 0., 0.};\n  goalQ = {1., 1., 1.};\n  eulerJointIntegration(Joint::Planar, {1., 1., 1.}, {0., 0., 0.}, 1., q);\n  BOOST_CHECK_EQUAL_COLLECTIONS(q.begin(), q.end(), goalQ.begin(), goalQ.end());\n}\n\n/// @return norm of the finite diff motion vector minus model motion vector\ndouble testEulerInteg(rbd::Joint::Type jType,\n                      const Eigen::Vector3d & axis,\n                      const Eigen::VectorXd & q,\n                      const Eigen::VectorXd & alpha,\n                      double timeStep = 0.001)\n{\n  using namespace std;\n  using namespace Eigen;\n  using namespace rbd;\n\n  Joint j(jType, axis, true, std::string(\"0\"));\n  std::vector<double> qVec(j.params()), alphaVec(j.dof()), alphaDVec(j.dof());\n  for(int i = 0; i < j.params(); ++i)\n  {\n    qVec[i] = q[i];\n  }\n  for(int i = 0; i < j.dof(); ++i)\n  {\n    alphaVec[i] = alpha[i];\n    alphaDVec[i] = 0.;\n  }\n\n  sva::PTransformd initPos(j.pose(qVec));\n  sva::MotionVecd motion(j.motion(alphaVec));\n\n  eulerJointIntegration(jType, alphaVec, alphaDVec, timeStep, qVec);\n  sva::PTransformd endPos(j.pose(qVec));\n\n  // linear velocity is set in initPos frame\n  Vector3d linVel((initPos.rotation() * (endPos.translation() - initPos.translation())) / timeStep);\n  // rotation velocity is also in initPos frame\n  Matrix3d rotErr(endPos.rotation() * initPos.rotation().transpose());\n  Vector3d angVel = sva::rotationVelocity(rotErr) / timeStep;\n  sva::MotionVecd motionDiff(angVel, linVel);\n\n  return (motionDiff - motion).vector().norm();\n}\n\nBOOST_AUTO_TEST_CASE(EulerTestV2)\n{\n  using namespace Eigen;\n  using namespace rbd;\n\n  for(int i = 0; i < 100; ++i)\n  {\n    BOOST_CHECK_SMALL(\n        testEulerInteg(Joint::Rev, Vector3d::Random().normalized(), VectorXd::Random(1), VectorXd::Random(1)), 1e-4);\n  }\n\n  for(int i = 0; i < 100; ++i)\n  {\n    BOOST_CHECK_SMALL(\n        testEulerInteg(Joint::Prism, Vector3d::Random().normalized(), VectorXd::Random(1), VectorXd::Random(1)), 1e-4);\n  }\n\n  for(int i = 0; i < 100; ++i)\n  {\n    BOOST_CHECK_SMALL(\n        testEulerInteg(Joint::Spherical, Vector3d::UnitZ(), VectorXd::Random(4).normalized(), VectorXd::Random(3)),\n        1e-4);\n  }\n\n  for(int i = 0; i < 100; ++i)\n  {\n    VectorXd q(VectorXd::Random(7));\n    q.head<4>() /= q.head<4>().norm();\n    BOOST_CHECK_SMALL(testEulerInteg(Joint::Free, Vector3d::UnitZ(), q, VectorXd::Random(6)), 1e-4);\n  }\n\n  for(int i = 0; i < 100; ++i)\n  {\n    BOOST_CHECK_SMALL(testEulerInteg(Joint::Planar, Vector3d::UnitZ(), VectorXd::Random(3), VectorXd::Random(3), 1e-4),\n                      1e-3);\n  }\n\n  for(int i = 0; i < 100; ++i)\n  {\n    BOOST_CHECK_SMALL(testEulerInteg(Joint::Cylindrical, Vector3d::UnitZ(), VectorXd::Random(2), VectorXd::Random(2)),\n                      1e-4);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(FATest)\n{\n  rbd::MultiBody mb;\n  rbd::MultiBodyConfig mbc;\n  rbd::MultiBodyGraph mbg;\n  std::tie(mb, mbc, mbg) = makeXYZSarm();\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n  forwardAcceleration(mb, mbc);\n\n  for(int i = 0; i < mb.nrBodies(); ++i)\n  {\n    BOOST_CHECK_SMALL(mbc.bodyAccB[i].vector().norm(), TOL);\n  }\n\n  std::vector<rbd::Jacobian> jacs(mb.nrBodies());\n  for(int i = 0; i < mb.nrBodies(); ++i)\n  {\n    jacs[i] = rbd::Jacobian(mb, mb.body(i).name());\n  }\n\n  Eigen::MatrixXd fullJac(6, mb.nrDof());\n  Eigen::MatrixXd fullJacDot(6, mb.nrDof());\n\n  for(int i = 0; i < 10; ++i)\n  {\n    Eigen::VectorXd q(mb.nrParams()), alpha(mb.nrDof()), alphaD(mb.nrDof());\n    q.setRandom();\n    q.tail<4>().normalize();\n    alpha.setRandom();\n    alphaD.setRandom();\n\n    rbd::vectorToParam(q, mbc.q);\n    rbd::vectorToParam(alpha, mbc.alpha);\n    rbd::vectorToParam(alphaD, mbc.alphaD);\n\n    forwardKinematics(mb, mbc);\n    forwardVelocity(mb, mbc);\n    forwardAcceleration(mb, mbc);\n\n    for(int j = 0; j < mb.nrBodies(); ++j)\n    {\n      const Eigen::MatrixXd & jac = jacs[j].bodyJacobian(mb, mbc);\n      const Eigen::MatrixXd & jacDot = jacs[j].bodyJacobianDot(mb, mbc);\n\n      jacs[j].fullJacobian(mb, jac, fullJac);\n      jacs[j].fullJacobian(mb, jacDot, fullJacDot);\n\n      Eigen::Vector6d acc = fullJac * alphaD + fullJacDot * alpha;\n      BOOST_CHECK_SMALL((mbc.bodyAccB[j].vector() - acc).norm(), TOL);\n    }\n  }\n}\n\n// test forward acceleration against inverse dynamics\nBOOST_AUTO_TEST_CASE(FAGravityTest)\n{\n  using namespace Eigen;\n\n  rbd::MultiBody mb;\n  rbd::MultiBodyConfig mbc, mbcId;\n  rbd::MultiBodyGraph mbg;\n\n  std::tie(mb, mbc, mbg) = makeXYZSarm();\n\n  rbd::InverseDynamics id(mb);\n  for(int i = 0; i < 10; ++i)\n  {\n    Eigen::VectorXd q(mb.nrParams()), alpha(mb.nrDof()), alphaD(mb.nrDof());\n    q.setRandom();\n    q.tail<4>().normalize();\n    alpha.setRandom();\n    alphaD.setRandom();\n\n    rbd::vectorToParam(q, mbc.q);\n    rbd::vectorToParam(alpha, mbc.alpha);\n    rbd::vectorToParam(alphaD, mbc.alphaD);\n\n    forwardKinematics(mb, mbc);\n    forwardVelocity(mb, mbc);\n    mbcId = mbc;\n\n    // compute acceleration through forwardAcceleration and\n    // inverseDynamics\n    forwardAcceleration(mb, mbc, sva::MotionVecd(Vector3d::Zero(), mbc.gravity));\n    id.inverseDynamics(mb, mbcId);\n\n#ifdef __i386__\n    for(size_t j = 0; j < mbc.bodyAccB.size(); ++j)\n    {\n      BOOST_CHECK_SMALL((mbc.bodyAccB[j] - mbcId.bodyAccB[j]).vector().array().abs().sum(), TOL);\n    }\n#else\n    BOOST_CHECK_EQUAL_COLLECTIONS(mbc.bodyAccB.begin(), mbc.bodyAccB.end(), mbcId.bodyAccB.begin(),\n                                  mbcId.bodyAccB.end());\n#endif\n  }\n}\n\nBOOST_AUTO_TEST_CASE(IKTest)\n{\n  using namespace Eigen;\n  rbd::MultiBody mb;\n  rbd::MultiBodyConfig mbc;\n  rbd::MultiBodyGraph mbg;\n\n  std::tie(mb, mbc, mbg) = makeXYZarm();\n\n  rbd::InverseKinematics ik(mb, 3);\n\n  rbd::forwardKinematics(mb, mbc);\n  rbd::forwardVelocity(mb, mbc);\n\n  sva::PTransformd target(mbc.bodyPosW[3]);\n  BOOST_CHECK(ik.inverseKinematics(mb, mbc, target));\n\n  Eigen::Vector3d pos_vec(mbc.q[1][0], mbc.q[2][0], mbc.q[3][0]);\n  Eigen::Vector3d solution(0, 0, 0);\n  BOOST_CHECK_SMALL((pos_vec - solution).norm(), TOL);\n\n  solution[0] = 1.;\n  mbc.q[1][0] = 1.;\n  rbd::forwardKinematics(mb, mbc);\n  target = sva::PTransformd(mbc.bodyPosW[3]);\n  mbc.q[1][0] = 0.;\n  rbd::forwardKinematics(mb, mbc);\n  BOOST_CHECK(ik.inverseKinematics(mb, mbc, target));\n  pos_vec = Eigen::Vector3d(mbc.q[1][0], mbc.q[2][0], mbc.q[3][0]);\n  BOOST_CHECK_SMALL((pos_vec - solution).norm(), TOL);\n\n  solution = Eigen::Vector3d(0., 1., 0.);\n  mbc.q[1][0] = 0.;\n  mbc.q[2][0] = 1.;\n  mbc.q[3][0] = 0.;\n  rbd::forwardKinematics(mb, mbc);\n  target = sva::PTransformd(mbc.bodyPosW[3]);\n  mbc.q[2][0] = 0.;\n  rbd::forwardKinematics(mb, mbc);\n  BOOST_CHECK(ik.inverseKinematics(mb, mbc, target));\n  pos_vec = Eigen::Vector3d(mbc.q[1][0], mbc.q[2][0], mbc.q[3][0]);\n  BOOST_CHECK_SMALL((pos_vec - solution).norm(), TOL);\n\n  solution = Eigen::Vector3d::Random();\n  mbc.q[1][0] = solution[0];\n  mbc.q[2][0] = solution[1];\n  mbc.q[3][0] = solution[2];\n  rbd::forwardKinematics(mb, mbc);\n  target = sva::PTransformd(mbc.bodyPosW[3]);\n  mbc.zero(mb);\n  rbd::forwardKinematics(mb, mbc);\n  BOOST_CHECK(ik.inverseKinematics(mb, mbc, target));\n  pos_vec = Eigen::Vector3d(mbc.q[1][0], mbc.q[2][0], mbc.q[3][0]);\n  BOOST_CHECK_SMALL((pos_vec - solution).norm(), TOL);\n}\n\nBOOST_AUTO_TEST_CASE(FailureIKTest)\n{\n  using namespace Eigen;\n  rbd::MultiBody mb;\n  rbd::MultiBodyConfig mbc;\n  rbd::MultiBodyGraph mbg;\n\n  std::tie(mb, mbc, mbg) = makeXYZarm();\n\n  rbd::InverseKinematics ik(mb, 3);\n\n  rbd::forwardKinematics(mb, mbc);\n  rbd::forwardVelocity(mb, mbc);\n\n  // This target is outside the reach of the arm\n  sva::PTransformd target(sva::RotX(rbd::PI / 2), Eigen::Vector3d(0., 0.5, 2.5));\n  BOOST_CHECK(!ik.inverseKinematics(mb, mbc, target));\n\n  Eigen::VectorXd q_target(mb.nrParams());\n  Eigen::VectorXd q(mb.nrParams());\n\n  q_target << rbd::PI / 2, 0, 0;\n  rbd::paramToVector(mbc.q, q);\n\n  BOOST_CHECK_SMALL((q_target - q).norm(), TOL);\n\n  /* This target is reachable, but IK will fail if given\n   * a too low maximum number of iterations */\n  ik.max_iterations_ = 10;\n  sva::PTransformd reachable_target(sva::RotX(-rbd::PI / 2), Eigen::Vector3d(0., 0.5, -2.));\n  BOOST_CHECK(!ik.inverseKinematics(mb, mbc, reachable_target));\n  ik.max_iterations_ = 40;\n  BOOST_CHECK(ik.inverseKinematics(mb, mbc, reachable_target));\n}\n", "meta": {"hexsha": "4f2aaf4c09c971acb0b8aa1187509b9a95a9b225", "size": 20842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/AlgoTest.cpp", "max_stars_repo_name": "dbdxnuliba/RBDyn-provides-a-set-of-classes-and-functions-to-model-the-dynamics-of-rigid-body-systems.", "max_stars_repo_head_hexsha": "c3f498f8330e06be7dae55570d00931702b920d6", "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": "tests/AlgoTest.cpp", "max_issues_repo_name": "dbdxnuliba/RBDyn-provides-a-set-of-classes-and-functions-to-model-the-dynamics-of-rigid-body-systems.", "max_issues_repo_head_hexsha": "c3f498f8330e06be7dae55570d00931702b920d6", "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/AlgoTest.cpp", "max_forks_repo_name": "dbdxnuliba/RBDyn-provides-a-set-of-classes-and-functions-to-model-the-dynamics-of-rigid-body-systems.", "max_forks_repo_head_hexsha": "c3f498f8330e06be7dae55570d00931702b920d6", "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.2942942943, "max_line_length": 119, "alphanum_fraction": 0.614288456, "num_tokens": 7403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.5288956029329117}}
{"text": "\ufeff// test_abc.cc\n#include \"menon/math.hh\"\n#include <boost/core/lightweight_test.hpp>\n\n// abs\u95a2\u6570\u306e\u30c6\u30b9\u30c8\u30b3\u30fc\u30c9\nvoid test_abs()\n{\n  // int\u578b\u306e\u30c6\u30b9\u30c8\n  constexpr auto x = menon::abs(-123);\n  BOOST_TEST_EQ(x, 123);\n  BOOST_TEST_EQ(menon::abs(std::numeric_limits<int>::max()), std::numeric_limits<int>::max());\n  BOOST_TEST_THROWS(menon::abs(std::numeric_limits<int>::min()), std::out_of_range);\n\n  // \u8fd4\u5374\u5024\u306e\u578b\u306e\u30c6\u30b9\u30c8\n  static_assert(std::is_same_v<decltype(menon::abs((unsigned char)123)), int>);\n  static_assert(std::is_same_v<decltype(menon::abs(123)), int>);\n  static_assert(std::is_same_v<decltype(menon::abs(123U)), unsigned int>);\n  static_assert(std::is_same_v<decltype(menon::abs(123L)), long>);\n  static_assert(std::is_same_v<decltype(menon::abs(123LL)), long long>);\n\n  // long\u578b\u306e\u30c6\u30b9\u30c8\n  BOOST_TEST_EQ(menon::abs(123L), 123L);\n  BOOST_TEST_EQ(menon::abs(-1L), 1L);\n  BOOST_TEST_EQ(menon::abs(std::numeric_limits<long>::max()), std::numeric_limits<long>::max());\n  BOOST_TEST_THROWS(menon::abs(std::numeric_limits<long>::min()), std::out_of_range);\n\n  // long long\u578b\u306e\u30c6\u30b9\u30c8\n  BOOST_TEST_EQ(menon::abs(123LL), 123LL);\n  BOOST_TEST_EQ(menon::abs(-1LL), 1LL);\n  BOOST_TEST_EQ(menon::abs(std::numeric_limits<long long>::max()), std::numeric_limits<long long>::max());\n  BOOST_TEST_THROWS(menon::abs(std::numeric_limits<long long>::min()), std::out_of_range);\n\n  // \u6d6e\u52d5\u5c0f\u6570\u70b9\u6570\u306e\u30c6\u30b9\u30c8\n  BOOST_TEST_EQ(menon::abs(1.23), 1.23);\n  BOOST_TEST_EQ(menon::abs(-1.0), 1.0);\n  BOOST_TEST_EQ(menon::abs(std::numeric_limits<long long>::max()), std::numeric_limits<long long>::max());\n  BOOST_TEST_THROWS(menon::abs(std::numeric_limits<long long>::min()), std::out_of_range);\n}\n\n// uabs\u95a2\u6570\u306e\u30c6\u30b9\u30c8\u30b3\u30fc\u30c9\nvoid test_uabs()\n{\n  // int\u578b\u304a\u3088\u3073unsigned int\u578b\u306e\u30c6\u30b9\u30c8\n  constexpr auto x1 = menon::uabs(-123);\n  BOOST_TEST_EQ(x1, 123u);\n  constexpr auto y1 = menon::uabs(123);\n  BOOST_TEST_EQ(y1, 123u);\n  static_assert(std::is_same_v<decltype(menon::uabs(-123)), unsigned int>);\n  BOOST_TEST_EQ(menon::uabs(std::numeric_limits<int>::min()), std::numeric_limits<int>::max() + 1u);\n\n  // long\u578b\u304a\u3088\u3073unsigned long\u578b\u306e\u30c6\u30b9\u30c8\n  constexpr auto x2 = menon::uabs(-123L);\n  BOOST_TEST_EQ(x2, 123UL);\n  constexpr auto y2 = menon::uabs(123L);\n  BOOST_TEST_EQ(y2, 123UL);\n  static_assert(std::is_same_v<decltype(menon::uabs(-123L)), unsigned long>);\n  BOOST_TEST_EQ(menon::uabs(std::numeric_limits<long>::min()), std::numeric_limits<long>::max() + 1UL);\n\n  // long long\u578b\u304a\u3088\u3073unsigned long long\u578b\u306e\u30c6\u30b9\u30c8\n  constexpr auto x3 = menon::uabs(-123LL);\n  BOOST_TEST_EQ(x3, 123ULL);\n  constexpr auto y3 = menon::uabs(123LL);\n  BOOST_TEST_EQ(y3, 123ULL);\n  static_assert(std::is_same_v<decltype(menon::uabs(-123LL)), unsigned long long>);\n  BOOST_TEST_EQ(menon::uabs(std::numeric_limits<long>::min()), std::numeric_limits<long>::max() + 1ULL);\n\n  // \u6d6e\u52d5\u5c0f\u6570\u70b9\u6570\u306e\u30c6\u30b9\u30c8\n  constexpr auto x = menon::uabs(-1.23);\n  BOOST_TEST_EQ(x, 1.23);\n  constexpr auto y = menon::uabs(1.23);\n  BOOST_TEST_EQ(y, 1.23);\n  static_assert(std::is_same_v<decltype(menon::uabs(-1.23)), double>);\n  BOOST_TEST_EQ(menon::uabs(-std::numeric_limits<double>::max()), std::numeric_limits<double>::max());\n}\n\nint main()\n{\n  test_abs();\n  test_uabs();\n  return boost::report_errors();\n}\n", "meta": {"hexsha": "00f4bc907f9feda790e49d0050ffb31f463edd9e", "size": 3143, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test_abs.cc", "max_stars_repo_name": "menonfled/menon_cpp_lib", "max_stars_repo_head_hexsha": "729bb581023e7558360fd17ac0866e20b2d7ec40", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T16:47:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-10T16:47:09.000Z", "max_issues_repo_path": "test/test_abs.cc", "max_issues_repo_name": "menonfled/menon_cpp_lib", "max_issues_repo_head_hexsha": "729bb581023e7558360fd17ac0866e20b2d7ec40", "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_abs.cc", "max_forks_repo_name": "menonfled/menon_cpp_lib", "max_forks_repo_head_hexsha": "729bb581023e7558360fd17ac0866e20b2d7ec40", "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.3292682927, "max_line_length": 106, "alphanum_fraction": 0.7056951957, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5288956029329117}}
{"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 gaussian_filter_kf_test.cpp\n * \\date Febuary 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#include <gtest/gtest.h>\n#include \"../typecast.hpp\"\n\n#include <Eigen/Dense>\n\n#include \"gaussian_filter_test_suite.hpp\"\n#include <fl/util/meta.hpp>\n#include <fl/filter/gaussian/gaussian_filter.hpp>\n\nusing namespace fl;\n\ntemplate <\n    int StateDimension,\n    int InputDimension,\n    int ObsrvDimension,\n    int FilterIterations = 100\n>\nstruct UnscentedKalmanFilterTestConfiguration\n{\n    enum : signed int\n    {\n        StateDim = StateDimension,\n        InputDim = InputDimension,\n        ObsrvDim = ObsrvDimension,\n        Iterations = FilterIterations\n    };\n\n    template <typename ModelFactory>\n    struct FilterDefinition\n    {\n        typedef UnscentedQuadrature Quadrature;\n\n        typedef GaussianFilter<\n                        typename ModelFactory::LinearTransition,\n                        typename ModelFactory::LinearObservation,\n                        Quadrature\n                > Type;\n    };\n\n    template <typename ModelFactory>\n    static typename FilterDefinition<ModelFactory>::Type\n    create_filter(ModelFactory&& factory)\n    {\n        return typename FilterDefinition<ModelFactory>::Type(\n            factory.create_linear_state_model(),\n            factory.create_sensor(),\n            UnscentedQuadrature());\n    }\n};\n\ntypedef ::testing::Types<\n            StaticTest<UnscentedKalmanFilterTestConfiguration<3, 1, 2>>,\n            StaticTest<UnscentedKalmanFilterTestConfiguration<3, 3, 10>>,\n            StaticTest<UnscentedKalmanFilterTestConfiguration<10, 10, 20>>,\n            DynamicTest<UnscentedKalmanFilterTestConfiguration<3, 1, 2>>,\n            DynamicTest<UnscentedKalmanFilterTestConfiguration<3, 3, 10>>,\n            DynamicTest<UnscentedKalmanFilterTestConfiguration<10, 10, 20>>\n        > TestTypes;\n\nINSTANTIATE_TYPED_TEST_CASE_P(UnscentedKalmanFilterTest,\n                              GaussianFilterTest,\n                              TestTypes);\n", "meta": {"hexsha": "1e22e701d9532cb72e0231d330ce85682acfb3da", "size": 2424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gaussian_filter/unscented_kalman_filter_test.cpp", "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": "test/gaussian_filter/unscented_kalman_filter_test.cpp", "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": "test/gaussian_filter/unscented_kalman_filter_test.cpp", "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": 29.5609756098, "max_line_length": 79, "alphanum_fraction": 0.6629537954, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.528895599562995}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"test_quadratic\"\n\n#include <boost/test/unit_test.hpp>\n#include \"nanocv/math/abs.hpp\"\n#include \"nanocv/math/random.hpp\"\n#include \"nanocv/math/epsilon.hpp\"\n#include \"nanocv/math/quadratic.hpp\"\n\nBOOST_AUTO_TEST_CASE(test_quadratic)\n{\n        using namespace ncv;\n\n        const size_t tests = 1327;\n\n        for (size_t t = 0; t < tests; t ++)\n        {\n                random_t<double> rnd(-1.0, +1.0);\n\n                // build random quadratic\n                const double a = rnd();\n                const double b = rnd();\n                const double c = rnd();\n                const quadratic_t<double> q(a, b, c);\n                BOOST_CHECK(q);\n\n                const double x0 = rnd();\n                const double f0 = q.value(x0);\n                const double g0 = q.gradient(x0);\n\n                const double x1 = x0 + rnd() + 1.0;\n                const double f1 = q.value(x1);\n\n                // check interpolation\n                const quadratic_t<double> iq(x0, f0, g0, x1, f1);\n                if (!iq)\n                {\n                        continue;\n                }\n\n                BOOST_CHECK_LE(math::abs(f0 - iq.value(x0)), math::epsilon0<double>());\n                BOOST_CHECK_LE(math::abs(g0 - iq.gradient(x0)), math::epsilon0<double>());\n\n                BOOST_CHECK_LE(math::abs(f1 - iq.value(x1)), math::epsilon0<double>());\n\n//                BOOST_CHECK_LE(math::abs(q.a() - iq.a()), math::epsilon1<double>());\n//                BOOST_CHECK_LE(math::abs(q.b() - iq.b()), math::epsilon1<double>());\n//                BOOST_CHECK_LE(math::abs(q.c() - iq.c()), math::epsilon1<double>());\n\n                // check extremum\n                double extremum;\n                iq.extremum(extremum);\n\n                if (!std::isfinite(extremum))\n                {\n                        continue;\n                }\n\n                BOOST_CHECK_LE(math::abs(iq.gradient(extremum)), math::epsilon0<double>());\n\n                const size_t etests = 1843;\n                for (size_t e = 0; e < etests; e ++)\n                {\n                        BOOST_CHECK_GE(math::abs(iq.gradient(rnd())),\n                                       math::abs(iq.gradient(extremum)));\n                }\n        }\n}\n", "meta": {"hexsha": "0245fd940de0eae8869395d83b2cbe1172418009", "size": 2282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_quadratic.cpp", "max_stars_repo_name": "0x0all/nanocv", "max_stars_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_stars_repo_licenses": ["MIT"], "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_quadratic.cpp", "max_issues_repo_name": "0x0all/nanocv", "max_issues_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_issues_repo_licenses": ["MIT"], "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_quadratic.cpp", "max_forks_repo_name": "0x0all/nanocv", "max_forks_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T02:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-02T02:41:37.000Z", "avg_line_length": 33.0724637681, "max_line_length": 91, "alphanum_fraction": 0.4772129711, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5288955927115093}}
{"text": "\n#include <vmmlib/vector.hpp>\n#include <vmmlib/math.hpp>\n\n#define BOOST_TEST_MODULE vector\n#include <boost/test/unit_test.hpp>\n\nusing namespace vmml;\n\nBOOST_AUTO_TEST_CASE(vector_base)\n{\n    vector< 4, double > v;\n    double data[] = { 1, 2, 3, 4 };\n\n    v.iter_set( data, data+4 );\n\n    // tests copyFrom1DimCArray function\n    size_t tmp = 1;\n    for( size_t index = 0; index < 4; ++index, ++tmp )\n    {\n        BOOST_CHECK(v.at( index ) == tmp);\n    }\n\n    tmp = 4;\n    float dataf[] = { 4, 3, 2, 1 };\n    v.iter_set( dataf, dataf + 4 );\n    for( size_t index = 0; index < 4; ++index, --tmp )\n    {\n        BOOST_CHECK(v.at( index ) == tmp);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(vector_plus)\n{\n    vector< 4, double > v;\n    double data[] = { 1, 2, 3, 4 };\n\n    // tests operator+ function\n    vector< 4, double > v_other;\n    vector< 4, double > v_result;\n\n    v = data;\n\n    double datad[] = { 4, 3, 2, 1 };\n    v_other = datad;\n\n    v_result = v + v_other;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(v_result.at( index ) == 5);\n    }\n\n    v_result = v;\n    v_result += v_other;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(v_result.at( index ) == 5);\n    }\n\n    v = data;\n    v_result = v + 2.;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(v_result.at( index ) == index + 3);\n    }\n\n    v_result = v;\n    v_result += 2;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(v_result.at( index ) == index + 3);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(vector_minus)\n{\n    vector< 4, double > v;\n    double data[] = { 1, 2, 3, 4 };\n\n    // tests operator- function\n    vector< 4, double > v_other;\n    vector< 4, double > v_result;\n    v = data;\n\n    double datad[] = { 1, 2, 3, 4 };\n    v_other = datad;\n\n    v_result = v - v_other;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(v_result.at( index ) == 0);\n    }\n\n    v_result = v;\n    v_result -= v_other;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(v_result.at( index ) == 0);\n    }\n\n\n    v_result = v - 1.0;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(v_result.at( index ) == index);\n    }\n\n    v_result = v;\n    v_result -= 1.0;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(v_result.at( index ) == index);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(vector_times)\n{\n    vector< 4, double > v;\n    double data[] = { 1, 2, 3, 4 };\n\n    // tests operator* function\n    vector< 4, double > v_other;\n    vector< 4, double > v_result;\n\n    v = data;\n\n    double datad[] = { 24, 12, 8, 6 };\n    v_other = datad;\n\n    v_result = v * v_other;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(v_result.at( index ) == 24);\n    }\n\n    v_result = v;\n    v_result *= v_other;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(v_result.at( index ) == 24);\n    }\n\n    v_result = v * 2.0;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(v_result.at( index ) == v.at( index ) * 2.0);\n    }\n\n    v_result = v;\n    v_result *= 2.0;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(v_result.at( index ) == v.at( index ) * 2.0);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(vector_div)\n{\n    vector< 4, double > v;\n    double data[] = { 1, 2, 3, 4 };\n\n    // tests operator/ function\n    vector< 4, double > v_other;\n    vector< 4, double > v_result;\n\n    v = data;\n\n    double datad[] = { 2, 4, 6, 8 };\n    v_other = datad;\n\n    v_result = v / v_other;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(( v_result.at( index ) - 0.5 ) < 1e-12);\n    }\n\n    v_result = v;\n    v_result /= v_other;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(( v_result.at( index ) - 0.5 ) < 1e-12);\n    }\n\n\n    v_result = v / 1.5;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(( v_result.at( index ) - ( v.at( index ) / 1.5 ) ) < 1e-12);\n    }\n\n    v_result = v;\n    v_result /= 1.5;\n    for( size_t index = 0; index < 4; ++index )\n    {\n        BOOST_CHECK(( v_result.at( index ) - ( v.at( index ) / 1.5 ) ) < 1e-12);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(vector_norm)\n{\n    vector< 4, double > v;\n    double data[] = { 1, 2, 3, 4 };\n\n    // tests norm / normSquared (length/lengthSquared) computation\n    vector< 4, double > vec;\n    vec = data;\n\n    double normSquared = vec.squared_length();\n    BOOST_CHECK(normSquared == 1 * 1 + 2 * 2 + 3 * 3 + 4 * 4);\n\n    double norm = vec.length();\n    BOOST_CHECK(sqrt( normSquared ) == norm);\n\n    // tests normalize\n    vec = data;\n    vec.normalize();\n    BOOST_CHECK_CLOSE( vec.length(), 1.0, 0.0000001 );\n\n\n    // constructor tests\n    double vData[] = { 1, 2, 3, 4 };\n    vector< 4, double > v4( 1, 2, 3, 4 );\n\n    vector< 2, double > v2C;\n    v2C = vData;\n    vector< 2, double > v2( 1, 2 );\n\n    BOOST_CHECK(v2 == v2C );\n\n    vector< 3, double > v3C;\n    v3C = vData;\n    vector< 3, double > v3( 1, 2, 3 );\n\n    BOOST_CHECK(v3 == v3C );\n\n    vector< 4, double > v4C;\n    v4C = vData;\n\n    BOOST_CHECK(v4 == v4C);\n\n    double vData2[] = { 23, 23, 23, 23 };\n    v4C = vData2;\n\n    vector< 4, double > v4_( 23 );\n    BOOST_CHECK(v4_ == v4C);\n\n    v3 = vData;\n    v4C = vData;\n    vector< 4, double > v4from3_1( v3, vData[ 3 ] );\n    BOOST_CHECK(v4from3_1 == v4C);\n\n    double hvData[] = { 1., 2., 3., 0.25 };\n    double xvData[] = { 4.0, 8.0, 12.0 };\n\n    vector< 4, double > homogenous;\n    homogenous.iter_set( hvData, hvData + 4 );\n    vector< 3, double > nonh;\n    nonh.iter_set( xvData, xvData + 3 );\n\n    vector< 4, double > htest( nonh );\n\n    // to-homogenous-coordinates ctor\n    BOOST_CHECK((htest == vector< 4, double >( 4, 8., 12., 1. ) ));\n\n    vector< 3, double > nhtest( homogenous );\n\n    // from homogenous-coordiates ctor\n    BOOST_CHECK(nhtest == nonh );\n\n    // set tests\n    vec.set( 2, 3, 4, 5 );\n    vector< 4, double > vecCorrect;\n    double vCData[] = { 2, 3, 4, 5 };\n    vecCorrect = vCData;\n    BOOST_CHECK(vec == vecCorrect);\n\n    vec.set( 2 );\n\n    double vCData2[] = { 2, 2, 2, 2 };\n    vecCorrect = vCData2;\n    BOOST_CHECK( vec == vecCorrect );\n\n    vector< 3, double > v1( 2, 3, 4 );\n\n    // component accessors\n    vector< 4, double > vd( 1, 2, 3, 4 );\n    BOOST_CHECK( vd.x() == 1 && vd.y() == 2 && vd.z() == 3 && vd.w() == 4 );\n}\n\nBOOST_AUTO_TEST_CASE(vector_dot)\n{\n    // dot product\n    vector< 3, float > v0( 1, 2, 3 );\n    vector< 3, float > v1( -6, 5, -4 );\n    BOOST_CHECK( v0.dot( v1 ) == -8 );\n}\n\nBOOST_AUTO_TEST_CASE(vector_cross)\n{\n    // cross product\n    vector< 3, float > v0( 1, 2, 3 );\n    vector< 3, float > v1( -6, 5, -4 );\n    vector< 3, float > vcorrect( -23, -14, 17 );\n    BOOST_CHECK(v0.cross( v1 ) == vcorrect);\n\n    // ???\n    vector< 4, float > vf( -1.0f, 3.0f, -99.0f, -0.9f );\n    vector< 4, size_t > vui( 0, 5, 2, 4 );\n\n    size_t index = vf.find_min_index();\n    float f = vf.find_min();\n\n    BOOST_CHECK( index == 2 && f == -99.0f );\n\n    index = vf.find_max_index();\n    f = vf.find_max();\n    BOOST_CHECK( index == 1 && f == 3.0f );\n\n    index = vui.find_min_index();\n    size_t ui = vui.find_min();\n    BOOST_CHECK( index == 0 && ui == 0 );\n\n    index = vui.find_max_index();\n    ui = vui.find_max();\n    BOOST_CHECK( index == 1 && ui == 5 );\n}\n\nBOOST_AUTO_TEST_CASE(vector_tbd1)\n{\n    vector< 4, float > v1( -1.0f, 3.0f, -99.0f, -0.9f );\n    float f = 4.0f;\n    vector< 4, float > v_scaled = f * v1;\n\n    BOOST_CHECK(v_scaled == (vector< 4, float >( -4.0f, 12.0f, -396.0f, -3.6f ) ));\n\n\n    // ???\n    vector< 3, float > vf( 3.0, 2.0, 1.0 );\n    vector< 3, double > vd( vf );\n    vector< 3, double >::const_iterator it = vd.begin(), it_end = vd.end();\n    vector< 3, float >::const_iterator fit = vf.begin();\n    for( ; it != it_end; ++it, ++fit )\n    {\n        BOOST_CHECK(*it == *fit);\n    }\n    vd = vf;\n    for( ; it != it_end; ++it, ++fit )\n    {\n        BOOST_CHECK(*it == *fit);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(vector_tbd2)\n{\n    // ???\n    vector< 4, float > vf( 3.0, 2.0, 1.0, 1.0 );\n    vector< 3, float >& v3 = vf.get_sub_vector< 3 >();\n    BOOST_CHECK(v3.x() == vf.x() && v3.y() == vf.y());\n    v3.normalize();\n\n    BOOST_CHECK(v3.x() == vf.x() && v3.y() == vf.y());\n\n    //elementwise sqrt\n    vector< 4, float > vsq( 9.0, 4.0, 1.0, 2.0 );\n    vector< 4, float > vsq_check( 3.0, 2.0, 1.0, 1.414213538169861 );\n    vsq.sqrt_elementwise();\n    BOOST_CHECK(vsq == vsq_check);\n\n    //elementwise sqrt\n    vector< 4, float > vr( 9.0, 4.0, 1.0, 2.0 );\n    vector< 4, float > vr_check( 0.1111111119389534, 0.25, 1, 0.5 );\n    vr.reciprocal();\n    BOOST_CHECK(vr == vr_check);\n}\n\nBOOST_AUTO_TEST_CASE(vector_l2norm)\n{\n    vector< 4, float > vr( 9.0, 4.0, 1.0, 2.0 );\n    double v_norm_check = 10.09950493836208;\n    double v_norm = vr.norm();\n\n    BOOST_CHECK((v_norm - v_norm_check) < 0.0001);\n}\n", "meta": {"hexsha": "4309ecd0fbae27dae3b8da09cf0f5026ff775035", "size": 8890, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/vector.cpp", "max_stars_repo_name": "biddisco/vmmlib", "max_stars_repo_head_hexsha": "afe9d7675953a74f17299fdd3f5508df44731505", "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/vector.cpp", "max_issues_repo_name": "biddisco/vmmlib", "max_issues_repo_head_hexsha": "afe9d7675953a74f17299fdd3f5508df44731505", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/vector.cpp", "max_forks_repo_name": "biddisco/vmmlib", "max_forks_repo_head_hexsha": "afe9d7675953a74f17299fdd3f5508df44731505", "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.1510416667, "max_line_length": 83, "alphanum_fraction": 0.5322834646, "num_tokens": 3213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5288955927115093}}
{"text": "//Author: Dr. Shantanu Shahane\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <float.h>\n#include <string.h>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include \"class.hpp\"\n#include <unistd.h>\n#include <limits.h>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/SparseExtra>\n#include <Eigen/SparseLU>\n#include <Eigen/OrderingMethods>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Spectra/GenEigsSolver.h>\n#include <Spectra/MatOp/SparseGenMatProd.h>\n#include <Spectra/GenEigsRealShiftSolver.h>\n#include <Spectra/MatOp/SparseGenRealShiftSolve.h>\nusing namespace std;\n\nPARAMETERS::PARAMETERS(string parameter_file, string gmsh_file)\n{\n    cout << \"\\n\";\n    check_mpi();\n    meshfile = gmsh_file;\n    cout << \"PARAMETERS::PARAMETERS gmsh_file: \" << meshfile << endl;\n    does_file_exist(meshfile.c_str(), \"Called from PARAMETERS::read_calc_parameters\");\n    read_calc_parameters(parameter_file);\n    verify_parameters();\n    get_problem_dimension_msh();\n    calc_cloud_num_points();\n    calc_polynomial_term_exponents();\n    cout << \"\\n\";\n}\n\nvoid PARAMETERS::read_calc_parameters(string parameter_file)\n{\n    does_file_exist(parameter_file.c_str(), \"Called from PARAMETERS::read_calc_parameters\");\n    char ctemp[5000], ctemp_2[100];\n    string stemp;\n    int itemp;\n    double dtemp;\n    FILE *file;\n    file = fopen(parameter_file.c_str(), \"r\");\n    cout << endl;\n    fscanf(file, \"%[^,],%i\\n\", ctemp, &poly_deg);\n    printf(\"PARAMETERS::read_calc_parameters Read %s = %i\\n\", ctemp, poly_deg);\n    fscanf(file, \"%[^,],%i\\n\", ctemp, &phs_deg);\n    printf(\"PARAMETERS::read_calc_parameters Read %s = %i\\n\", ctemp, phs_deg);\n    fscanf(file, \"%[^,],%lf\\n\", ctemp, &cloud_size_multiplier);\n    printf(\"PARAMETERS::read_calc_parameters Read %s = %g\\n\", ctemp, cloud_size_multiplier);\n\n    fscanf(file, \"%[^,],%i\\n\", ctemp, &nt);\n    printf(\"PARAMETERS::read_calc_parameters Read %s = %i\\n\", ctemp, nt);\n    fscanf(file, \"%[^,],%lf\\n\", ctemp, &Courant);\n    printf(\"PARAMETERS::read_calc_parameters Read %s = %g\\n\", ctemp, Courant);\n    fscanf(file, \"%[^,],%s\\n\", ctemp, ctemp_2);\n    solver_type = ctemp_2;\n    printf(\"PARAMETERS::read_calc_parameters Read %s = %s\\n\", ctemp, solver_type.c_str());\n    fscanf(file, \"%[^,],%lf\\n\", ctemp, &steady_tolerance);\n    printf(\"PARAMETERS::read_calc_parameters Read %s = %g\\n\", ctemp, steady_tolerance);\n    fscanf(file, \"%[^,],%lf\\n\", ctemp, &solver_tolerance);\n    printf(\"PARAMETERS::read_calc_parameters Read %s = %g\\n\", ctemp, solver_tolerance);\n    fscanf(file, \"%[^,],%i\\n\", ctemp, &euclid_precond_level_hypre);\n    printf(\"PARAMETERS::read_calc_parameters Read %s = %i\\n\", ctemp, euclid_precond_level_hypre);\n    fscanf(file, \"%[^,],%i\\n\", ctemp, &gmres_kdim);\n    printf(\"PARAMETERS::read_calc_parameters Read %s = %i\\n\", ctemp, gmres_kdim);\n    fscanf(file, \"%[^,],%lf\\n\", ctemp, &precond_droptol);\n    printf(\"PARAMETERS::read_calc_parameters Read %s = %g\\n\", ctemp, precond_droptol);\n    fscanf(file, \"%[^,],%i\\n\", ctemp, &n_iter);\n    printf(\"PARAMETERS::read_calc_parameters Read %s = %i\\n\", ctemp, n_iter);\n\n    cout << endl;\n}\n\nvoid PARAMETERS::verify_parameters()\n{\n    if (poly_deg < 2 || poly_deg > 15)\n    {\n        printf(\"\\n\\nERROR from PARAMETERS::verify_parameters poly_deg should be in range [2, 15]; current value: %i\\n\\n\", poly_deg);\n        throw bad_exception();\n    }\n    if (phs_deg != 3 && phs_deg != 5 && phs_deg != 7 && phs_deg != 9 && phs_deg != 11)\n    {\n        printf(\"\\n\\nERROR from PARAMETERS::verify_parameters phs_deg should be 3, 5, 7, 9, or 11; current value: %i\\n\\n\", phs_deg);\n        throw bad_exception();\n    }\n    if (strcmp(solver_type.c_str(), \"hypre_ilu_gmres\") != 0 && strcmp(solver_type.c_str(), \"eigen_direct\") != 0 && strcmp(solver_type.c_str(), \"eigen_ilu_bicgstab\") != 0)\n    {\n        cout << \"\\n\\nERROR from PARAMETERS::verify_parameters solver_type should be either hypre_ilu_gmres, eigen_ilu_bicgstab or eigen_direct; current value: \" << solver_type << \"\\n\\n\";\n        throw bad_exception();\n    }\n\n    if (meshfile.find_last_of(\".\") + 1 == meshfile.size())\n    {\n        cout << \"\\n\\nERROR from PARAMETERS::verify_parameters extension of meshfile should be msh; \\nUnable to find extension in the meshfile: \" << meshfile << \"\\n\\n\";\n        throw bad_exception();\n    }\n    string extension = meshfile.substr(meshfile.find_last_of(\".\") + 1, meshfile.size());\n    if (extension != \"msh\")\n    {\n        cout << \"\\n\\nERROR from PARAMETERS::verify_parameters extension of meshfile should be msh; \\nCurrent extension: \" << extension << \" of the meshfile: \" << meshfile << \"\\n\\n\";\n        throw bad_exception();\n    }\n\n    output_file_prefix = meshfile;\n    if (output_file_prefix.find_last_of(\"/\") < output_file_prefix.size()) //remove location details from mesh file name if required\n        output_file_prefix = output_file_prefix.substr(output_file_prefix.find_last_of(\"/\") + 1, output_file_prefix.size());\n    if (output_file_prefix.find_last_of(\".\") < output_file_prefix.size()) //remove extension from mesh file name if required\n        output_file_prefix.replace(output_file_prefix.begin() + output_file_prefix.find_last_of(\".\"), output_file_prefix.end(), \"\");\n    output_file_prefix += \"_polydeg_\" + to_string(poly_deg);\n    cout << \"PARAMETERS::verify_parameters output_file_prefix: \" << output_file_prefix << endl;\n}\n\nvoid PARAMETERS::calc_cloud_num_points()\n{\n    if (dimension == 2)\n        num_poly_terms = ((int)(0.5 * (poly_deg + 1) * (poly_deg + 2)));\n    else\n        num_poly_terms = ((int)((poly_deg + 1) * (poly_deg + 2) * (poly_deg + 3) / 6)); //sum(0.5*(1:poly_deg+1).*(2:poly_deg+2)) = (poly_deg + 1) * (poly_deg + 2) * (poly_deg + 3) / 6\n    cloud_size = (int)(ceil(cloud_size_multiplier * num_poly_terms));\n    cout << \"PARAMETERS::calc_cloud_num_points num_poly_terms: \" << num_poly_terms << \", cloud_size: \" << cloud_size << endl;\n}\n\nvoid PARAMETERS::get_problem_dimension_msh()\n{ //identify whether its a 2D or 3D gmsh grid\n\n    clock_t start = clock();\n    int dim = 2;\n    FILE *file;\n    int itemp, ncv, cv_type, eof_flag = 0;\n    double dtemp;\n    char temp[50];\n    file = fopen(meshfile.c_str(), \"r\");\n    while (true)\n    {\n        eof_flag = fscanf(file, \"%s \", temp);\n        if (strcmp(temp, \"$MeshFormat\") == 0)\n            break;\n        if (eof_flag < 0)\n        {\n            printf(\"\\n\\nERROR from PARAMETERS::get_problem_dimension_msh $MeshFormat not found in %s file\\n\\n\", meshfile.c_str());\n            throw bad_exception();\n        }\n    }\n    // fscanf(file, \"%s\", temp);\n    fgets(temp, 50, file);\n    if (strcmp(temp, \"2.2 0 8\\n\") != 0)\n    {\n        printf(\"\\n\\nERROR from PARAMETERS::get_problem_dimension_msh MeshFormat should be 2.2 0 8; but %s file has %s format instead\\n\\n\", meshfile.c_str(), temp);\n        throw bad_exception();\n    }\n    eof_flag = 0;\n    while (true)\n    {\n        eof_flag = fscanf(file, \"%s \", temp);\n        if (strcmp(temp, \"$Nodes\") == 0)\n            break;\n        if (eof_flag < 0)\n        {\n            printf(\"\\n\\nERROR from PARAMETERS::get_problem_dimension_msh $Nodes not found in %s file\\n\\n\", meshfile.c_str());\n            throw bad_exception();\n        }\n    }\n    eof_flag = 0;\n    while (true)\n    {\n        eof_flag = fscanf(file, \"%s \", temp);\n        if (strcmp(temp, \"$Elements\") == 0)\n            break;\n        if (eof_flag < 0)\n        {\n            printf(\"\\n\\nERROR from PARAMETERS::get_problem_dimension_msh $Elements not found in %s file\\n\\n\", meshfile.c_str());\n            throw bad_exception();\n        }\n    }\n    fscanf(file, \"%i \", &ncv);\n    // cout << \"get_problem_dimension_msh ncv = \" << ncv << endl;\n    //reference: http://www.manpagez.com/info/gmsh/gmsh-2.2.6/gmsh_63.php\n    for (int icv = 0; icv < ncv; icv++)\n    {\n        fscanf(file, \"%i \", &itemp);   //cv number\n        fscanf(file, \"%i \", &cv_type); //cv type\n        if (cv_type == 4 || cv_type == 5 || cv_type == 6 || cv_type == 7)\n        { //4-node tetrahedron || 8-node hexahedron || 6-node prism || 5-node pyramid\n            dim = 3;\n            break; //3D element found\n        }\n        else if (cv_type == 11 || cv_type == 12 || cv_type == 13 || cv_type == 14)\n        { //10-node tetrahedron || 27-node hexahedron || 18-node prism || 14-node pyramid\n            dim = 3;\n            break; //3D element found\n        }\n        else if (cv_type == 17 || cv_type == 18 || cv_type == 19)\n        { //20-node hexahedron || 15-node prism || 13-node pyramid\n            dim = 3;\n            break; //3D element found\n        }\n        else if (cv_type == 29 || cv_type == 30 || cv_type == 31)\n        { //20-node tetrahedron || 35-node tetrahedron || 56-node tetrahedron\n            dim = 3;\n            break; //3D element found\n        }\n        fscanf(file, \"%*[^\\n]\\n\"); //skip reading remaining row\n    }\n    dimension = dim;\n    cout << \"PARAMETERS::get_problem_dimension_msh problem dimension: \" << dimension << endl;\n}\n\nvoid PARAMETERS::calc_polynomial_term_exponents()\n{\n    polynomial_term_exponents.resize(num_poly_terms, dimension);\n    Eigen::MatrixXi deg_temp;\n    if (dimension == 2)\n    {\n        polynomial_term_exponents.row(0) = Eigen::MatrixXi::Zero(1, dimension);                                        //constant term\n        polynomial_term_exponents.block(1, 0, dimension, dimension) = Eigen::MatrixXi::Identity(dimension, dimension); //two linear terms\n        int previous_index = 1;\n        for (int deg = 2; deg <= poly_deg; deg++)\n        { //quadratic onwards terms\n            deg_temp.resize(deg + 1, dimension);\n            for (int i = previous_index; i < previous_index + deg; i++)\n            {\n                deg_temp(i - previous_index, 0) = 1 + polynomial_term_exponents(i, 0); //exponents of 'x'\n                deg_temp(i - previous_index, 1) = polynomial_term_exponents(i, 1);     //exponents of 'y'\n            }\n            deg_temp(deg, 0) = 0;\n            deg_temp(deg, 1) = deg;\n            previous_index = previous_index + deg;\n            polynomial_term_exponents.block(previous_index, 0, deg + 1, dimension) = deg_temp;\n        }\n    }\n    else\n    {\n        polynomial_term_exponents.row(0) = Eigen::MatrixXi::Zero(1, dimension);                                        //constant term\n        polynomial_term_exponents.block(1, 0, dimension, dimension) = Eigen::MatrixXi::Identity(dimension, dimension); //three linear terms\n        int previous_index = 1;\n        for (int deg = 2; deg <= poly_deg; deg++)\n        { //quadratic onwards terms\n            deg_temp.resize(0.5 * (deg + 1) * (deg + 2), dimension);\n            for (int i = previous_index; i < previous_index + (deg * (deg + 1) / 2); i++)\n            {\n                deg_temp(i - previous_index, 0) = 1 + polynomial_term_exponents(i, 0); //exponents of 'x'\n                deg_temp(i - previous_index, 1) = polynomial_term_exponents(i, 1);     //exponents of 'y'\n                deg_temp(i - previous_index, 2) = polynomial_term_exponents(i, 2);     //exponents of 'z'\n            }\n            for (int i = previous_index + (0.5 * deg * (deg - 1)); i < previous_index + (0.5 * deg * (deg + 1)); i++)\n            {\n                deg_temp(i - previous_index + deg, 0) = polynomial_term_exponents(i, 0);     //exponents of 'x'\n                deg_temp(i - previous_index + deg, 1) = 1 + polynomial_term_exponents(i, 1); //exponents of 'y'\n                deg_temp(i - previous_index + deg, 2) = polynomial_term_exponents(i, 2);     //exponents of 'z'\n            }\n            deg_temp((0.5 * (deg + 1) * (deg + 2)) - 1, 0) = 0;\n            deg_temp((0.5 * (deg + 1) * (deg + 2)) - 1, 1) = 0;\n            deg_temp((0.5 * (deg + 1) * (deg + 2)) - 1, 2) = deg;\n            previous_index = previous_index + (0.5 * deg * (deg + 1));\n            polynomial_term_exponents.block(previous_index, 0, 0.5 * (deg + 1) * (deg + 2), dimension) = deg_temp;\n        }\n    }\n}\n\nvoid PARAMETERS::calc_dt(Eigen::SparseMatrix<double, Eigen::RowMajor> &grad_x, Eigen::SparseMatrix<double, Eigen::RowMajor> &grad_y, Eigen::SparseMatrix<double, Eigen::RowMajor> &grad_z, Eigen::SparseMatrix<double, Eigen::RowMajor> &laplacian, double u0, double v0, double w0, double alpha)\n{\n    Eigen::VectorXcd eigval_grad_x, eigval_grad_y, eigval_grad_z, eigval_laplacian;\n    eigval_grad_x = calc_largest_magnitude_eigenvalue(grad_x);\n    eigval_grad_y = calc_largest_magnitude_eigenvalue(grad_y);\n    if (dimension == 3)\n        eigval_grad_z = calc_largest_magnitude_eigenvalue(grad_z);\n    eigval_laplacian = calc_largest_magnitude_eigenvalue(laplacian);\n    grad_x_eigval_real = eigval_grad_x[0].real(), grad_x_eigval_imag = eigval_grad_x[0].imag();\n    grad_y_eigval_real = eigval_grad_y[0].real(), grad_y_eigval_imag = eigval_grad_y[0].imag();\n    if (dimension == 3)\n        grad_z_eigval_real = eigval_grad_z[0].real(), grad_z_eigval_imag = eigval_grad_z[0].imag();\n    laplace_eigval_real = eigval_laplacian[0].real(), laplace_eigval_imag = eigval_laplacian[0].imag();\n    printf(\"\\nPARAMETERS::calc_dt Eigenvalue with largest magnitude: grad_x: (%g, %g)\\n\", eigval_grad_x[0].real(), eigval_grad_x[0].imag());\n    printf(\"PARAMETERS::calc_dt Eigenvalue with largest magnitude: grad_y: (%g, %g)\\n\", eigval_grad_y[0].real(), eigval_grad_y[0].imag());\n    if (dimension == 3)\n        printf(\"PARAMETERS::calc_dt Eigenvalue with largest magnitude: grad_z: (%g, %g)\\n\", eigval_grad_z[0].real(), eigval_grad_z[0].imag());\n    printf(\"PARAMETERS::calc_dt Eigenvalue with largest magnitude: laplacian: (%g, %g)\\n\", eigval_laplacian[0].real(), eigval_laplacian[0].imag());\n\n    double evalues = u0 * sqrt((eigval_grad_x[0].real() * eigval_grad_x[0].real()) + (eigval_grad_x[0].imag() * eigval_grad_x[0].imag()));\n    evalues += v0 * sqrt((eigval_grad_y[0].real() * eigval_grad_y[0].real()) + (eigval_grad_y[0].imag() * eigval_grad_y[0].imag()));\n    if (dimension == 3)\n        evalues += w0 * sqrt((eigval_grad_z[0].real() * eigval_grad_z[0].real()) + (eigval_grad_z[0].imag() * eigval_grad_z[0].imag()));\n    evalues += alpha * sqrt((eigval_laplacian[0].real() * eigval_laplacian[0].real()) + (eigval_laplacian[0].imag() * eigval_laplacian[0].imag()));\n    dt = 2.0 / evalues; //forward Euler\n    dt = dt * Courant;\n    printf(\"PARAMETERS::calc_dt Courant: %g, dt: %g seconds\\n\\n\", Courant, dt);\n}", "meta": {"hexsha": "0f2e7a17e83c1ea4333eb74dbf13ebec95ac4634", "size": 14359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "header_files/parameters.cpp", "max_stars_repo_name": "shahaneshantanu/memphys", "max_stars_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "header_files/parameters.cpp", "max_issues_repo_name": "shahaneshantanu/memphys", "max_issues_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "header_files/parameters.cpp", "max_forks_repo_name": "shahaneshantanu/memphys", "max_forks_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-07T00:32:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:32:37.000Z", "avg_line_length": 48.6745762712, "max_line_length": 290, "alphanum_fraction": 0.6229542447, "num_tokens": 4165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5288431298149349}}
{"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 \"fw/math.h\"\n\n#include <boost/test/auto_unit_test.hpp>\n\nusing namespace moteus;\n\nnamespace tt = boost::test_tools;\n\nBOOST_AUTO_TEST_CASE(log2f_approx_test, * boost::unit_test::tolerance(1e-3f)) {\n  const float test_values[] = {\n    1.0,\n    0.5,\n    0.25,\n    1.01,\n    1.02,\n    2.0,\n    1.5,\n    3.0,\n    4.0,\n    20.0,\n    31.0,\n    32.1,\n  };\n  for (const auto value : test_values) {\n    BOOST_TEST_CONTEXT(value) {\n      BOOST_TEST(std::abs(std::log2(value) - log2f_approx(value)) < 2e-3);\n      // This has a relative tolerance instead of an absolute one.\n      BOOST_TEST(pow2f_approx(log2f(value)) == value);\n    }\n  }\n\n  BOOST_TEST(pow2f_approx(0.0024f) == 1.00166f);\n  BOOST_TEST(pow2f_approx(log2f_approx(0.01)) == 0.01,\n             boost::test_tools::tolerance(3e-2));\n}\n\nBOOST_AUTO_TEST_CASE(WrapZeroToTwoPiTest) {\n  for (float v = -50.0f; v <= 50.0f; v += 0.001f) {\n    BOOST_TEST_CONTEXT(v) {\n      auto result = WrapZeroToTwoPi(v);\n      const auto oracle_neg_pos = std::atan2(std::sin(v), std::cos(v));\n      const auto corrected =\n          (oracle_neg_pos > 0.0f) ?\n          oracle_neg_pos :\n          (2.0f * M_PI + oracle_neg_pos);\n      BOOST_TEST(std::abs(corrected - result) < 0.001f);\n    }\n  }\n}\n", "meta": {"hexsha": "501335bd010b8555440290c913aabdfb3ab6cdc8", "size": 1837, "ext": "cc", "lang": "C++", "max_stars_repo_path": "fw/test/math_test.cc", "max_stars_repo_name": "fxd0h/moteus", "max_stars_repo_head_hexsha": "e66ba9fb54ad0482a0bdf9a32420f5bf18677216", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 347.0, "max_stars_repo_stars_event_min_datetime": "2019-03-16T12:00:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:19:42.000Z", "max_issues_repo_path": "fw/test/math_test.cc", "max_issues_repo_name": "fxd0h/moteus", "max_issues_repo_head_hexsha": "e66ba9fb54ad0482a0bdf9a32420f5bf18677216", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2020-04-20T20:37:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T18:13:59.000Z", "max_forks_repo_path": "fw/test/math_test.cc", "max_forks_repo_name": "fxd0h/moteus", "max_forks_repo_head_hexsha": "e66ba9fb54ad0482a0bdf9a32420f5bf18677216", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 127.0, "max_forks_repo_forks_event_min_datetime": "2019-03-23T16:06:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T21:33:27.000Z", "avg_line_length": 28.703125, "max_line_length": 79, "alphanum_fraction": 0.6543277082, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505964, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5288431247631078}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2018 Peter Caspers\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 \"cmsspread.hpp\"\n#include \"utilities.hpp\"\n\n#include <ql/cashflows/cmscoupon.hpp>\n#include <ql/cashflows/lineartsrpricer.hpp>\n#include <ql/experimental/coupons/cmsspreadcoupon.hpp>\n#include <ql/experimental/coupons/lognormalcmsspreadpricer.hpp>\n#include <ql/indexes/swap/euriborswap.hpp>\n#include <ql/math/array.hpp>\n#include <ql/math/comparison.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/matrixutilities/pseudosqrt.hpp>\n#include <ql/math/randomnumbers/sobolrsg.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/volatility/swaption/swaptionconstantvol.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\nusing namespace boost::accumulators;\n\nnamespace {\nstruct TestData {\n    TestData() {\n        refDate = Date(23, February, 2018);\n        Settings::instance().evaluationDate() = refDate;\n\n        yts2 = Handle<YieldTermStructure>(\n            ext::make_shared<FlatForward>(refDate, 0.02, Actual365Fixed()));\n\n        swLn = Handle<SwaptionVolatilityStructure>(\n            ext::make_shared<ConstantSwaptionVolatility>(\n                refDate, TARGET(), Following, 0.20, Actual365Fixed(),\n                ShiftedLognormal, 0.0));\n        swSln = Handle<SwaptionVolatilityStructure>(\n            ext::make_shared<ConstantSwaptionVolatility>(\n                refDate, TARGET(), Following, 0.10, Actual365Fixed(),\n                ShiftedLognormal, 0.01));\n        swN = Handle<SwaptionVolatilityStructure>(\n            ext::make_shared<ConstantSwaptionVolatility>(\n                refDate, TARGET(), Following, 0.0075, Actual365Fixed(), Normal,\n                0.01));\n\n        reversion = Handle<Quote>(ext::make_shared<SimpleQuote>(0.01));\n        cmsPricerLn =\n            ext::make_shared<LinearTsrPricer>(swLn, reversion, yts2);\n        cmsPricerSln =\n            ext::make_shared<LinearTsrPricer>(swSln, reversion, yts2);\n        cmsPricerN = ext::make_shared<LinearTsrPricer>(swN, reversion, yts2);\n\n        correlation = Handle<Quote>(ext::make_shared<SimpleQuote>(0.6));\n        cmsspPricerLn = ext::make_shared<LognormalCmsSpreadPricer>(\n            cmsPricerLn, correlation, yts2, 32);\n        cmsspPricerSln = ext::make_shared<LognormalCmsSpreadPricer>(\n            cmsPricerSln, correlation, yts2, 32);\n        cmsspPricerN = ext::make_shared<LognormalCmsSpreadPricer>(\n            cmsPricerN, correlation, yts2, 32);\n    }\n\n    SavedSettings backup;\n    Date refDate;\n    Handle<YieldTermStructure> yts2;\n    Handle<SwaptionVolatilityStructure> swLn, swSln, swN;\n    Handle<Quote> reversion, correlation;\n    ext::shared_ptr<CmsCouponPricer> cmsPricerLn, cmsPricerSln, cmsPricerN;\n    ext::shared_ptr<CmsSpreadCouponPricer> cmsspPricerLn, cmsspPricerSln,\n        cmsspPricerN;\n};\n} // namespace\n\nvoid CmsSpreadTest::testFixings() {\n    BOOST_TEST_MESSAGE(\"Testing fixings of cms spread indices...\");\n\n    TestData d;\n\n    ext::shared_ptr<SwapIndex> cms10y =\n        ext::make_shared<EuriborSwapIsdaFixA>(10 * Years, d.yts2, d.yts2);\n    ext::shared_ptr<SwapIndex> cms2y =\n        ext::make_shared<EuriborSwapIsdaFixA>(2 * Years, d.yts2, d.yts2);\n    ext::shared_ptr<SwapSpreadIndex> cms10y2y =\n        ext::make_shared<SwapSpreadIndex>(\"cms10y2y\", cms10y, cms2y);\n\n    Settings::instance().enforcesTodaysHistoricFixings() = false;\n\n    BOOST_CHECK_THROW(cms10y2y->fixing(d.refDate - 1), QuantLib::Error);\n    BOOST_REQUIRE_NO_THROW(cms10y2y->fixing(d.refDate));\n    BOOST_CHECK_EQUAL(cms10y2y->fixing(d.refDate),\n                      cms10y->fixing(d.refDate) - cms2y->fixing(d.refDate));\n    cms10y->addFixing(d.refDate, 0.05);\n    BOOST_CHECK_EQUAL(cms10y2y->fixing(d.refDate),\n                      cms10y->fixing(d.refDate) - cms2y->fixing(d.refDate));\n    cms2y->addFixing(d.refDate, 0.04);\n    BOOST_CHECK_EQUAL(cms10y2y->fixing(d.refDate),\n                      cms10y->fixing(d.refDate) - cms2y->fixing(d.refDate));\n    Date futureFixingDate = TARGET().adjust(d.refDate + 1 * Years);\n    BOOST_CHECK_EQUAL(cms10y2y->fixing(futureFixingDate),\n                      cms10y->fixing(futureFixingDate) -\n                          cms2y->fixing(futureFixingDate));\n    IndexManager::instance().clearHistories();\n\n    Settings::instance().enforcesTodaysHistoricFixings() = true;\n    BOOST_CHECK_THROW(cms10y2y->fixing(d.refDate), QuantLib::Error);\n    cms10y->addFixing(d.refDate, 0.05);\n    BOOST_CHECK_THROW(cms10y2y->fixing(d.refDate), QuantLib::Error);\n    cms2y->addFixing(d.refDate, 0.04);\n    BOOST_CHECK_EQUAL(cms10y2y->fixing(d.refDate),\n                      cms10y->fixing(d.refDate) - cms2y->fixing(d.refDate));\n    IndexManager::instance().clearHistories();\n}\n\nnamespace {\nReal mcReferenceValue(const ext::shared_ptr<CmsCoupon>& cpn1,\n                      const ext::shared_ptr<CmsCoupon>& cpn2, const Real cap,\n                      const Real floor,\n                      const Handle<SwaptionVolatilityStructure>& vol,\n                      const Real correlation) {\n    Size samples = 1000000;\n    accumulator_set<double, stats<tag::mean> > acc;\n    Matrix Cov(2, 2);\n    Cov(0, 0) = vol->blackVariance(cpn1->fixingDate(), cpn1->index()->tenor(),\n                                   cpn1->indexFixing());\n    Cov(1, 1) = vol->blackVariance(cpn2->fixingDate(), cpn2->index()->tenor(),\n                                   cpn2->indexFixing());\n    Cov(0, 1) = Cov(1, 0) = std::sqrt(Cov(0, 0) * Cov(1, 1)) * correlation;\n    Matrix C = pseudoSqrt(Cov);\n\n    Array atmRate(2), adjRate(2), avg(2), volShift(2);\n    atmRate[0] = cpn1->indexFixing();\n    atmRate[1] = cpn2->indexFixing();\n    adjRate[0] = cpn1->adjustedFixing();\n    adjRate[1] = cpn2->adjustedFixing();\n    if (vol->volatilityType() == ShiftedLognormal) {\n        volShift[0] = vol->shift(cpn1->fixingDate(), cpn1->index()->tenor());\n        volShift[1] = vol->shift(cpn2->fixingDate(), cpn2->index()->tenor());\n        avg[0] =\n            std::log((adjRate[0] + volShift[0]) / (atmRate[0] + volShift[0])) -\n            0.5 * Cov(0, 0);\n        avg[1] =\n            std::log((adjRate[1] + volShift[1]) / (atmRate[1] + volShift[1])) -\n            0.5 * Cov(1, 1);\n    } else {\n        avg[0] = adjRate[0];\n        avg[1] = adjRate[1];\n    }\n\n    InverseCumulativeNormal icn;\n    SobolRsg sb_(2, 42);\n    Array w(2), z(2);\n    for (Size i = 0; i < samples; ++i) {\n        std::vector<Real> seq = sb_.nextSequence().value;\n        std::transform(seq.begin(), seq.end(), w.begin(), icn);\n        z = C * w + avg;\n        for (Size i = 0; i < 2; ++i) {\n            if (vol->volatilityType() == ShiftedLognormal) {\n                z[i] =\n                    (atmRate[i] + volShift[i]) * std::exp(z[i]) - volShift[i];\n            }\n        }\n        acc(std::min(std::max(z[0] - z[1], floor), cap));\n    }\n    return mean(acc);\n} // mcReferenceValue\n} // namespace\n\nvoid CmsSpreadTest::testCouponPricing() {\n    BOOST_TEST_MESSAGE(\"Testing pricing of cms spread coupons...\");\n\n    TestData d;\n    Real tol = 1E-6; // abs tolerance coupon rate\n\n    ext::shared_ptr<SwapIndex> cms10y =\n        ext::make_shared<EuriborSwapIsdaFixA>(10 * Years, d.yts2, d.yts2);\n    ext::shared_ptr<SwapIndex> cms2y =\n        ext::make_shared<EuriborSwapIsdaFixA>(2 * Years, d.yts2, d.yts2);\n    ext::shared_ptr<SwapSpreadIndex> cms10y2y =\n        ext::make_shared<SwapSpreadIndex>(\"cms10y2y\", cms10y, cms2y);\n\n    Date valueDate = cms10y2y->valueDate(d.refDate);\n    Date payDate = valueDate + 1 * Years;\n    ext::shared_ptr<CmsCoupon> cpn1a =\n        ext::shared_ptr<CmsCoupon>(new CmsCoupon(\n            payDate, 10000.0, valueDate, payDate, cms10y->fixingDays(), cms10y,\n            1.0, 0.0, Date(), Date(), Actual360(), false));\n    ext::shared_ptr<CmsCoupon> cpn1b = ext::shared_ptr<CmsCoupon>(\n        new CmsCoupon(payDate, 10000.0, valueDate, payDate, cms2y->fixingDays(),\n                      cms2y, 1.0, 0.0, Date(), Date(), Actual360(), false));\n    ext::shared_ptr<CmsSpreadCoupon> cpn1 =\n        ext::shared_ptr<CmsSpreadCoupon>(new CmsSpreadCoupon(\n            payDate, 10000.0, valueDate, payDate, cms10y2y->fixingDays(),\n            cms10y2y, 1.0, 0.0, Date(), Date(), Actual360(), false));\n    BOOST_CHECK(cpn1->fixingDate() == d.refDate);\n    cpn1a->setPricer(d.cmsPricerLn);\n    cpn1b->setPricer(d.cmsPricerLn);\n    cpn1->setPricer(d.cmsspPricerLn);\n\n#ifndef __FAST_MATH__\n    constexpr Real eqTol = 100*QL_EPSILON;\n#else\n    constexpr Real eqTol = 1e-13;\n#endif\n    BOOST_CHECK_CLOSE(cpn1->rate(), cpn1a->rate() - cpn1b->rate(), eqTol);\n    cms10y->addFixing(d.refDate, 0.05);\n    BOOST_CHECK_CLOSE(cpn1->rate(), cpn1a->rate() - cpn1b->rate(), eqTol);\n    cms2y->addFixing(d.refDate, 0.03);\n    BOOST_CHECK_CLOSE(cpn1->rate(), cpn1a->rate() - cpn1b->rate(), eqTol);\n    IndexManager::instance().clearHistories();\n\n    ext::shared_ptr<CmsCoupon> cpn2a = ext::shared_ptr<CmsCoupon>(\n        new CmsCoupon(Date(23, February, 2029), 10000.0,\n                      Date(23, February, 2028), Date(23, February, 2029), 2,\n                      cms10y, 1.0, 0.0, Date(), Date(), Actual360(), false));\n    ext::shared_ptr<CmsCoupon> cpn2b = ext::shared_ptr<CmsCoupon>(\n        new CmsCoupon(Date(23, February, 2029), 10000.0,\n                      Date(23, February, 2028), Date(23, February, 2029), 2,\n                      cms2y, 1.0, 0.0, Date(), Date(), Actual360(), false));\n\n    ext::shared_ptr<CappedFlooredCmsSpreadCoupon> plainCpn =\n        ext::shared_ptr<CappedFlooredCmsSpreadCoupon>(\n            new CappedFlooredCmsSpreadCoupon(\n                Date(23, February, 2029), 10000.0, Date(23, February, 2028),\n                Date(23, February, 2029), 2, cms10y2y, 1.0, 0.0, Null<Rate>(),\n                Null<Rate>(), Date(), Date(), Actual360(), false));\n    ext::shared_ptr<CappedFlooredCmsSpreadCoupon> cappedCpn =\n        ext::shared_ptr<CappedFlooredCmsSpreadCoupon>(\n            new CappedFlooredCmsSpreadCoupon(\n                Date(23, February, 2029), 10000.0, Date(23, February, 2028),\n                Date(23, February, 2029), 2, cms10y2y, 1.0, 0.0, 0.03,\n                Null<Rate>(), Date(), Date(), Actual360(), false));\n    ext::shared_ptr<CappedFlooredCmsSpreadCoupon> flooredCpn =\n        ext::shared_ptr<CappedFlooredCmsSpreadCoupon>(\n            new CappedFlooredCmsSpreadCoupon(\n                Date(23, February, 2029), 10000.0, Date(23, February, 2028),\n                Date(23, February, 2029), 2, cms10y2y, 1.0, 0.0, Null<Rate>(),\n                0.01, Date(), Date(), Actual360(), false));\n    ext::shared_ptr<CappedFlooredCmsSpreadCoupon> collaredCpn =\n        ext::shared_ptr<CappedFlooredCmsSpreadCoupon>(\n            new CappedFlooredCmsSpreadCoupon(\n                Date(23, February, 2029), 10000.0, Date(23, February, 2028),\n                Date(23, February, 2029), 2, cms10y2y, 1.0, 0.0, 0.03, 0.01,\n                Date(), Date(), Actual360(), false));\n\n    cpn2a->setPricer(d.cmsPricerLn);\n    cpn2b->setPricer(d.cmsPricerLn);\n    plainCpn->setPricer(d.cmsspPricerLn);\n    cappedCpn->setPricer(d.cmsspPricerLn);\n    flooredCpn->setPricer(d.cmsspPricerLn);\n    collaredCpn->setPricer(d.cmsspPricerLn);\n\n    BOOST_CHECK_SMALL(\n        std::abs(plainCpn->rate() - mcReferenceValue(cpn2a, cpn2b, QL_MAX_REAL,\n                                                     -QL_MAX_REAL, d.swLn,\n                                                     d.correlation->value())),\n        tol);\n    BOOST_CHECK_SMALL(\n        std::abs(cappedCpn->rate() - mcReferenceValue(cpn2a, cpn2b, 0.03,\n                                                      -QL_MAX_REAL, d.swLn,\n                                                      d.correlation->value())),\n        tol);\n    BOOST_CHECK_SMALL(\n        std::abs(flooredCpn->rate() -\n                 mcReferenceValue(cpn2a, cpn2b, QL_MAX_REAL, 0.01, d.swLn,\n                                  d.correlation->value())),\n\n        tol);\n    BOOST_CHECK_SMALL(\n        std::abs(collaredCpn->rate() -\n                 mcReferenceValue(cpn2a, cpn2b, 0.03, 0.01, d.swLn,\n                                  d.correlation->value())),\n        tol);\n\n    cpn2a->setPricer(d.cmsPricerSln);\n    cpn2b->setPricer(d.cmsPricerSln);\n    plainCpn->setPricer(d.cmsspPricerSln);\n    cappedCpn->setPricer(d.cmsspPricerSln);\n    flooredCpn->setPricer(d.cmsspPricerSln);\n    collaredCpn->setPricer(d.cmsspPricerSln);\n\n    BOOST_CHECK_SMALL(\n        std::abs(plainCpn->rate() - mcReferenceValue(cpn2a, cpn2b, QL_MAX_REAL,\n                                                     -QL_MAX_REAL, d.swSln,\n                                                     d.correlation->value())),\n        tol);\n    BOOST_CHECK_SMALL(\n        std::abs(cappedCpn->rate() - mcReferenceValue(cpn2a, cpn2b, 0.03,\n                                                      -QL_MAX_REAL, d.swSln,\n                                                      d.correlation->value())),\n        tol);\n    BOOST_CHECK_SMALL(\n        std::abs(flooredCpn->rate() -\n                 mcReferenceValue(cpn2a, cpn2b, QL_MAX_REAL, 0.01, d.swSln,\n                                  d.correlation->value())),\n\n        tol);\n    BOOST_CHECK_SMALL(\n        std::abs(collaredCpn->rate() -\n                 mcReferenceValue(cpn2a, cpn2b, 0.03, 0.01, d.swSln,\n                                  d.correlation->value())),\n        tol);\n\n    cpn2a->setPricer(d.cmsPricerN);\n    cpn2b->setPricer(d.cmsPricerN);\n    plainCpn->setPricer(d.cmsspPricerN);\n    cappedCpn->setPricer(d.cmsspPricerN);\n    flooredCpn->setPricer(d.cmsspPricerN);\n    collaredCpn->setPricer(d.cmsspPricerN);\n\n    BOOST_CHECK_SMALL(\n        std::abs(plainCpn->rate() - mcReferenceValue(cpn2a, cpn2b, QL_MAX_REAL,\n                                                     -QL_MAX_REAL, d.swN,\n                                                     d.correlation->value())),\n        tol);\n    BOOST_CHECK_SMALL(\n        std::abs(cappedCpn->rate() - mcReferenceValue(cpn2a, cpn2b, 0.03,\n                                                      -QL_MAX_REAL, d.swN,\n                                                      d.correlation->value())),\n        tol);\n    BOOST_CHECK_SMALL(std::abs(flooredCpn->rate() -\n                               mcReferenceValue(cpn2a, cpn2b, QL_MAX_REAL, 0.01,\n                                                d.swN, d.correlation->value())),\n\n                      tol);\n    BOOST_CHECK_SMALL(std::abs(collaredCpn->rate() -\n                               mcReferenceValue(cpn2a, cpn2b, 0.03, 0.01, d.swN,\n                                                d.correlation->value())),\n                      tol);\n}\n\ntest_suite* CmsSpreadTest::suite() {\n    auto* suite = BOOST_TEST_SUITE(\"CmsSpreadTest\");\n    suite->add(QUANTLIB_TEST_CASE(&CmsSpreadTest::testFixings));\n    suite->add(QUANTLIB_TEST_CASE(&CmsSpreadTest::testCouponPricing));\n    return suite;\n}\n", "meta": {"hexsha": "8aa06bed0c81f27c49967f200dcdeba8780488e9", "size": 15876, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/cmsspread.cpp", "max_stars_repo_name": "mshojatalab/QuantLib", "max_stars_repo_head_hexsha": "7801a0fb3226bc1b001e310bacdd35ddb2e51661", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T12:21:33.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-21T12:21:33.000Z", "max_issues_repo_path": "test-suite/cmsspread.cpp", "max_issues_repo_name": "mshojatalab/QuantLib", "max_issues_repo_head_hexsha": "7801a0fb3226bc1b001e310bacdd35ddb2e51661", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-03-09T16:19:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:33:42.000Z", "max_forks_repo_path": "test-suite/cmsspread.cpp", "max_forks_repo_name": "sweemer/QuantLib", "max_forks_repo_head_hexsha": "1341223e3d839dd77bb7231d0913809f01437740", "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": 44.2228412256, "max_line_length": 80, "alphanum_fraction": 0.6039304611, "num_tokens": 4681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5288431080412186}}
{"text": "//\n// Created by lejonmcgowan on 4/16/16.\n//\n\n#include \"Transform.h\"\n#include <Eigen/Geometry>\n#include <util/MathUtils.h>\nTransform::Transform()\n{\n\n}\n\nvoid Transform::addTranslate(const Eigen::Vector3f& translate)\n{\n    Eigen::Affine3f affineTranslate(Eigen::Translation3f(translate[0], translate[1], translate[2]));\n    transformations.push_back(affineTranslate);\n    setDirty();\n}\n\nvoid Transform::addRotate(const Eigen::Vector3f& rotate)\n{\n    Eigen::Affine3f rotx(Eigen::AngleAxisf(MathHelper::toRadians(rotate[0]), Eigen::Vector3f(1, 0, 0)));\n    Eigen::Affine3f roty(Eigen::AngleAxisf(MathHelper::toRadians(rotate[1]), Eigen::Vector3f(0, 1, 0)));\n    Eigen::Affine3f rotz(Eigen::AngleAxisf(MathHelper::toRadians(rotate[2]), Eigen::Vector3f(0, 0, 1)));\n    transformations.push_back(rotz * roty * rotx);\n    setDirty();\n}\n\nvoid Transform::addScale(const Eigen::Vector3f& scale)\n{\n    Eigen::Affine3f affineScale(Eigen::Scaling(scale[0], scale[1], scale[2]));\n    transformations.push_back(affineScale);\n    setDirty();\n}\n\nEigen::Matrix4f Transform::getTransformMatrix()\n{\n    if (dirty)\n    {\n        Eigen::Matrix4f finalTransform;\n        finalTransform.setIdentity();\n        for (auto currentTransform: transformations)\n            finalTransform = currentTransform.matrix() * finalTransform;\n        transform = finalTransform;\n    }\n    dirty = false;\n    return transform;\n}\n\nvoid Transform::setDirty()\n{\n    dirty = true;\n    identity = false;\n}\n\nRay Transform::transformRay(const Ray& ray)\n{\n    Ray transformRay;\n    Eigen::Vector4f vectorO, vectorD;\n    vectorO << ray.origin[0], ray.origin[1], ray.origin[2], 1;\n    vectorD << ray.direction[0], ray.direction[1], ray.direction[2], 0;\n\n    vectorO = getTransformMatrix() * vectorO;\n    vectorD = getTransformMatrix() * vectorD;\n\n    transformRay.origin << vectorO[0], vectorO[1], vectorO[2];\n    transformRay.direction << vectorD[0], vectorD[1], vectorD[2];\n    transformRay.direction.normalize();\n\n    return transformRay;\n}\n\nEigen::Vector3f Transform::transformPoint(const Eigen::Vector3f& point)\n{\n    Eigen::Vector3f transformPoint;\n    Eigen::Vector4f vector;\n    vector << point[0], point[1], point[2], 1;\n\n\n    vector = getTransformMatrix() * vector;\n\n    transformPoint << vector[0], vector[1], vector[2];\n\n    return transformPoint;\n}\n", "meta": {"hexsha": "7936381d47b3c1962eac4ad454ce0152b45c2949", "size": 2311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/Transform.cpp", "max_stars_repo_name": "lejonmcgowan/JohnnyTracer1", "max_stars_repo_head_hexsha": "123876abdb184a684a60aed7d5676510c1a2ceb0", "max_stars_repo_licenses": ["MIT"], "max_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/Transform.cpp", "max_issues_repo_name": "lejonmcgowan/JohnnyTracer1", "max_issues_repo_head_hexsha": "123876abdb184a684a60aed7d5676510c1a2ceb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geometry/Transform.cpp", "max_forks_repo_name": "lejonmcgowan/JohnnyTracer1", "max_forks_repo_head_hexsha": "123876abdb184a684a60aed7d5676510c1a2ceb0", "max_forks_repo_licenses": ["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.8720930233, "max_line_length": 104, "alphanum_fraction": 0.6862829944, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5288431080412186}}
{"text": "//\n// Copyright 2021 Sayan Chaudhuri <sayanchaudhuri758@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#ifndef BOOST_GIL_IMAGE_PROCESSING_FAST_FEATURE_DETECTOR_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_FAST_FEATURE_DETECTOR_HPP\n\n#include <boost/gil/image.hpp>\n#include <boost/gil/image_view.hpp>\n#include <boost/gil/locator.hpp>\n#include <boost/gil/point.hpp>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n\nnamespace boost { namespace gil {\nnamespace detail {\n\n/// \\brief Implements the FAST corner detection algorithm by Edward Rosten.\n///       Algorithm :-\n///       1.Consider a circle of 16 pixels around a given pixel(Bresenham circle)\n///       2.Decide a threshold t\n///       3.Let I_p be the intensity of the central pixel.\n///       4.Find if there are n consecutive pixels in those 16 pixels where the intensities of all\n///         pixels are <I_p-t or >I_p+t.Here n is taken as 9.\n///       5.For step 4, to detect that a pixel is not a corner,check first whether the intensities\n///         at pixels from 0 to 6 (with a step of 2)or the 8th pixel from each of them satisfies\n///         condition of step 4. If not,check the same condition on odd numbered pixels or their\n///         corresponding 8th pixel.\n///       6.If the checks in step 5 is not affirmative, the given pixel cannot\n///         be a corner.\n///       7.Otherwise, proceed to find whether there are n consecutive pixels to satisfy the\n///         criterion. If yes, p is a corner,else no.\n\n///       @param buffer -type of source image.Must be grayscale\n///       @param r      -row index of the candidate pixel\n///       @param c      -column index of candidate pixel\n///       @param points -pixel locations for bresenham circle around the given\n///                       pixel\n///       @param t      -threshold\ntemplate <typename SrcView>\nbool fast_feature_detector(\n    SrcView const& buffer,\n    std::size_t r,\n    std::size_t c,\n    std::vector<point_t>& points,\n    int t)\n{\n    auto src_loc = buffer.xy_at(c, r);\n    std::vector<int> threshold_indicator;\n    std::vector<int> intensity_array(16);\n    std::vector<decltype(src_loc.cache_location(0, -1))> pointers(16);\n    // storing intensities of pixels on circumference beforehand to decrease runtime\n    for (std::ptrdiff_t i = 0; i < 16; i++)\n    {\n        pointers[i]        = src_loc.cache_location(points[i][0], points[i][1]);\n        intensity_array[i] = src_loc[pointers[i]];\n    }\n    // calculating the flags to be used during segment test\n    auto const I_p = buffer(point_t(c, r));\n\n    std::transform(\n        intensity_array.begin(),\n        intensity_array.end(),\n        back_inserter(threshold_indicator),\n        [low = I_p - t, hi = I_p + t](auto const& intensity) {\n            if (intensity < low)\n                return -1;\n            else if (intensity > hi)\n                return 1;\n            else\n                return 0;\n        });\n\n    std::transform(\n        intensity_array.begin(),\n        intensity_array.end(),\n        back_inserter(threshold_indicator),\n        [low = I_p - t, hi = I_p + t](auto const& intensity) {\n            if (intensity < low)\n                return -1;\n            else if (intensity > hi)\n                return 1;\n            else\n                return 0;\n        });\n\n    // high speed test for eliminating non-corners\n    for (std::ptrdiff_t i = 0; i <= 6; i += 2)\n    {\n        if (threshold_indicator[i] == 0 && threshold_indicator[i + 8] == 0)\n            return false;\n    }\n    for (std::ptrdiff_t i = 1; i <= 7; i += 2)\n    {\n        if (threshold_indicator[i] == 0 && threshold_indicator[i + 8] == 0)\n            return false;\n    }\n\n    // final segment test\n    bool is_feature_point =\n        threshold_indicator.end() !=\n            std::search_n(threshold_indicator.begin(), threshold_indicator.end(), 9, -1) ||\n        threshold_indicator.end() !=\n            std::search_n(threshold_indicator.begin(), threshold_indicator.end(), 9, 1);\n    return is_feature_point;\n}\n\n///\\brief assigns a score to each detected corner to measure their degree of\n/// cornerness.\n///           Algorithm\n///           Perform a binary search on threshold t to find out the maximum\n///           threshold for which a corner remains a corner\n///\n///           @param src         -type of input image\n///           @param i           -row index of the detected corner\n///           @param j           -column index of the detected corner\n///           @param points      -pixel locations for bresenham circle around\n///                               the given pixel\n///           @param threshold   -initial threshold given as input\ntemplate <typename SrcView>\nstd::size_t calculate_score(\n    SrcView const& src,\n    std::size_t i,\n    std::size_t j,\n    std::vector<point_t>& points,\n    std::size_t threshold)\n{\n    std::size_t low  = threshold;\n    std::size_t high = 255;\n    // score measure used= highest threshold for which a corner remains a corner.\n    // The cornerness of a corner decreases with increasing threshold\n    while (high - low > 1)\n    {\n        std::size_t mid = (low + high) / 2;\n        if (fast_feature_detector(src, i, j, points, mid))\n        {\n            low = mid;\n        }\n        else\n        {\n            high = mid - 1;\n        }\n    }\n    return low - 1;\n}\n}  // namespace detail\n\n/// \\brief public function for using fast feature detector\n///        @param src         -type of input image\n///        @param keypoints   -vector for storing the locations of\n///                            keypoints(corners)\n///        @param scores      -vector for scores of each detected keypoint\n///        @param nonmax      -indicates whether to perform nonmaximum\n///                            suppression or not\n///        @param threshold   -initial threshold given as input\ntemplate <typename SrcView>\nvoid fast(\n    SrcView const& src,\n    std::vector<point_t>& keypoints,\n    std::vector<std::size_t>& scores,\n    bool nonmax           = true,\n    std::size_t threshold = 10)\n{\n    // coordinates of a bresenham circle of radius 3\n    std::vector<point_t> final_points_clockwise{\n        point_t(3, 0),\n        point_t(3, 1),\n        point_t(2, 2),\n        point_t(1, 3),\n        point_t(0, 3),\n        point_t(-1, 3),\n        point_t(-2, 2),\n        point_t(-3, 1),\n        point_t(-3, 0),\n        point_t(-3, -1),\n        point_t(-2, -2),\n        point_t(-1, -3),\n        point_t(0, -3),\n        point_t(1, -3),\n        point_t(2, -2),\n        point_t(3, -1)};\n    // FAST features only calculated on grayscale images\n    auto input_image_view = color_converted_view<gray8_pixel_t>(src);\n    gray8_image_t fast_image(src.dimensions());\n    // scores to be used during nonmaximum suppression\n    gray8_view_t fast_score_matrix = view(fast_image);\n    fill_pixels(fast_score_matrix, gray8_pixel_t(0));\n    std::vector<point_t> kp;\n\n    for (std::size_t i = 3; i < src.height() - 3; i++)\n    {\n        for (std::size_t j = 3; j < src.width() - 3; j++)\n        {\n            if (detail::fast_feature_detector(\n                    input_image_view, i, j, final_points_clockwise, threshold))\n            {\n                kp.push_back(point_t(j, i));\n            }\n        }\n    }\n\n    for (auto u : kp)\n    {\n        int score = 0;\n        score     = detail::calculate_score(\n            input_image_view, u[1], u[0], final_points_clockwise, threshold);\n        fast_score_matrix(u[0], u[1])[0] = gray8_pixel_t(score);\n    }\n\n    for (auto u : kp)\n    {\n        std::size_t i     = u[1];\n        std::size_t j     = u[0];\n        std::size_t score = 0;\n        score             = int(fast_score_matrix(j, i)[0]);\n        // performing nonmaximum suppression\n        if (!nonmax || score > fast_score_matrix(j - 1, i)[0] &&\n                           score > fast_score_matrix(j + 1, i)[0] &&\n                           score > fast_score_matrix(j - 1, i - 1)[0] &&\n                           score > fast_score_matrix(j, i - 1)[0] &&\n                           score > fast_score_matrix(j + 1, i - 1)[0] &&\n                           score > fast_score_matrix(j - 1, i + 1)[0] &&\n                           score > fast_score_matrix(j, i + 1)[0] &&\n                           score > fast_score_matrix(j + 1, i + 1)[0])\n        {\n            keypoints.push_back(u);\n            scores.push_back(score);\n        }\n    }\n}\n\n}}  // namespace boost::gil\n#endif\n", "meta": {"hexsha": "3463cef454b9ef50f33d47c6252b7ecf7dcf562c", "size": 8566, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/fast_feature_detector.hpp", "max_stars_repo_name": "Sayan-Chaudhuri/gil", "max_stars_repo_head_hexsha": "6194f9a511a05051e171dd248394454575918500", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/gil/image_processing/fast_feature_detector.hpp", "max_issues_repo_name": "Sayan-Chaudhuri/gil", "max_issues_repo_head_hexsha": "6194f9a511a05051e171dd248394454575918500", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/gil/image_processing/fast_feature_detector.hpp", "max_forks_repo_name": "Sayan-Chaudhuri/gil", "max_forks_repo_head_hexsha": "6194f9a511a05051e171dd248394454575918500", "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.8410041841, "max_line_length": 98, "alphanum_fraction": 0.5744805043, "num_tokens": 2154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6584175139669998, "lm_q1q2_score": 0.5288237004847789}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed 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#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/integer_list.hpp>\n#include <boost/hana/integral.hpp>\n#include <boost/hana/maybe.hpp>\n#include <boost/hana/pair.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTEXPR_LAMBDA auto f = [](auto x) {\n        return if_(x == int_<0>, nothing, just(pair(x, x - int_<1>)));\n    };\n\n    BOOST_HANA_CONSTANT_ASSERT(\n        unfoldr<IntegerList>(f, int_<10>) == integer_list<int, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1>\n    );\n    //! [main]\n}\n", "meta": {"hexsha": "936d3ff5940843d90d823cc511b81958b06acb10", "size": 737, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/list/unfoldr.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/list/unfoldr.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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/list/unfoldr.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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.2962962963, "max_line_length": 93, "alphanum_fraction": 0.6689280868, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5288236888973489}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/sign.hpp\n *\n * \\brief Implement SIGN function through \\c std::signbit for a vector or matrix expression.\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 comcon1 based on code of Marco Guazzone\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_SIGN_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_SIGN_HPP\n\n\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/expression/matrix_unary_functor.hpp>\n#include <boost/numeric/ublasx/expression/vector_unary_functor.hpp>\n#include <cmath>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\nnamespace detail {\n\ntemplate <typename VectorExprT>\nstruct vector_sign_functor_traits\n{\n\ttypedef VectorExprT input_expression_type;\n\ttypedef typename vector_traits<input_expression_type>::value_type signature_argument_type;\n\ttypedef typename type_traits<signature_argument_type>::real_type signature_result_type;\n\ttypedef vector_unary_functor_traits<\n\t\t\t\tinput_expression_type,\n\t\t\t\tsignature_result_type (signature_argument_type)\n\t\t\t> unary_functor_expression_type;\n\ttypedef typename unary_functor_expression_type::result_type result_type;\n\ttypedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\ntemplate <typename MatrixExprT>\nstruct matrix_sign_functor_traits\n{\n\ttypedef MatrixExprT input_expression_type;\n\ttypedef typename matrix_traits<input_expression_type>::value_type signature_argument_type;\n\ttypedef typename type_traits<signature_argument_type>::real_type signature_result_type;\n\ttypedef matrix_unary_functor_traits<\n\t\t\t\tinput_expression_type,\n\t\t\t\tsignature_result_type (signature_argument_type)\n\t\t\t> unary_functor_expression_type;\n\ttypedef typename unary_functor_expression_type::result_type result_type;\n\ttypedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\ntemplate <typename RealType> \nBOOST_UBLAS_INLINE \nRealType sign(RealType v) {\n        return ( -(RealType)( ::std::signbit(v) ) + 0.5 ) * 2.0;\n}\n\n\n} // Namespace detail\n\n\n/**\n * \\brief Applies the \\c std::sign function to a given vector expression.\n *\n * \\tparam VectorExprT The type of the input vector expression.\n *\n * \\param ve The input vector expression.\n * \\return A vector expression representing the application of \\c std::sign to\n *  each element of \\a ve.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename detail::vector_sign_functor_traits<VectorExprT>::result_type sign(vector_expression<VectorExprT> const& ve)\n{\n\ttypedef typename detail::vector_sign_functor_traits<VectorExprT>::expression_type expression_type;\n\ttypedef typename detail::vector_sign_functor_traits<VectorExprT>::signature_result_type signature_result_type;\n\n\treturn expression_type(ve(), detail::sign<signature_result_type>);\n}\n\n\n/**\n * \\brief Applies the \\c std::sign function to a given matrix expression.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param me The input matrix expression.\n * \\return A matrix expression representing the application of \\c std::sign to\n *  each element of \\a me.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename detail::matrix_sign_functor_traits<MatrixExprT>::result_type sign(matrix_expression<MatrixExprT> const& me)\n{\n\ttypedef typename detail::matrix_sign_functor_traits<MatrixExprT>::expression_type expression_type;\n\ttypedef typename detail::matrix_sign_functor_traits<MatrixExprT>::signature_result_type signature_result_type;\n\n\treturn expression_type(me(), detail::sign<signature_result_type>);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_SIGN_HPP\n", "meta": {"hexsha": "5cf91d7c35afce5a55fef77d5f538f5db4910c15", "size": 3877, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/sign.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/sign.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/sign.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": 33.7130434783, "max_line_length": 116, "alphanum_fraction": 0.8055197318, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5288236888973488}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2012 John Maddock.\n//  Copyright 2012 Phil Endecott\n//  Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <nil/crypto3/multiprecision/cpp_int.hpp>\n#include \"arithmetic_backend.hpp\"\n#include <boost/chrono.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n#include <fstream>\n#include <iomanip>\n\ntemplate<class Clock>\nstruct stopwatch {\n    typedef typename Clock::duration duration;\n    stopwatch() {\n        m_start = Clock::now();\n    }\n    duration elapsed() {\n        return Clock::now() - m_start;\n    }\n    void reset() {\n        m_start = Clock::now();\n    }\n\nprivate:\n    typename Clock::time_point m_start;\n};\n\n// Custom 128-bit maths used for exact calculation of the Delaunay test.\n// Only the few operators actually needed here are implemented.\n\nstruct int128_t {\n    int64_t high;\n    uint64_t low;\n\n    int128_t() {\n    }\n    int128_t(int32_t i) : high(i >> 31), low(static_cast<int64_t>(i)) {\n    }\n    int128_t(uint32_t i) : high(0), low(i) {\n    }\n    int128_t(int64_t i) : high(i >> 63), low(i) {\n    }\n    int128_t(uint64_t i) : high(0), low(i) {\n    }\n};\n\ninline int128_t operator<<(int128_t val, int amt) {\n    int128_t r;\n    r.low = val.low << amt;\n    r.high = val.low >> (64 - amt);\n    r.high |= val.high << amt;\n    return r;\n}\n\ninline int128_t& operator+=(int128_t& l, int128_t r) {\n    l.low += r.low;\n    bool carry = l.low < r.low;\n    l.high += r.high;\n    if (carry)\n        ++l.high;\n    return l;\n}\n\ninline int128_t operator-(int128_t val) {\n    val.low = ~val.low;\n    val.high = ~val.high;\n    val.low += 1;\n    if (val.low == 0)\n        val.high += 1;\n    return val;\n}\n\ninline int128_t operator+(int128_t l, int128_t r) {\n    l += r;\n    return l;\n}\n\ninline bool operator<(int128_t l, int128_t r) {\n    if (l.high != r.high)\n        return l.high < r.high;\n    return l.low < r.low;\n}\n\ninline int128_t mult_64x64_to_128(int64_t a, int64_t b) {\n    // Make life simple by dealing only with positive numbers:\n    bool neg = false;\n    if (a < 0) {\n        neg = !neg;\n        a = -a;\n    }\n    if (b < 0) {\n        neg = !neg;\n        b = -b;\n    }\n\n    // Divide input into 32-bit halves:\n    uint32_t ah = a >> 32;\n    uint32_t al = a & 0xffffffff;\n    uint32_t bh = b >> 32;\n    uint32_t bl = b & 0xffffffff;\n\n    // Long multiplication, with 64-bit temporaries:\n\n    //            ah al\n    //          * bh bl\n    // ----------------\n    //            al*bl   (t1)\n    // +       ah*bl      (t2)\n    // +       al*bh      (t3)\n    // +    ah*bh         (t4)\n    // ----------------\n\n    uint64_t t1 = static_cast<uint64_t>(al) * bl;\n    uint64_t t2 = static_cast<uint64_t>(ah) * bl;\n    uint64_t t3 = static_cast<uint64_t>(al) * bh;\n    uint64_t t4 = static_cast<uint64_t>(ah) * bh;\n\n    int128_t r(t1);\n    r.high = t4;\n    r += int128_t(t2) << 32;\n    r += int128_t(t3) << 32;\n\n    if (neg)\n        r = -r;\n\n    return r;\n}\n\ntemplate<class R, class T>\nBOOST_FORCEINLINE void mul_2n(R& r, const T& a, const T& b) {\n    r = a;\n    r *= b;\n}\n\ntemplate<class B, nil::crypto3::multiprecision::expression_template_option ET, class T>\nBOOST_FORCEINLINE void mul_2n(nil::crypto3::multiprecision::number<B, ET>& r, const T& a, const T& b) {\n    multiply(r, a, b);\n}\n\nBOOST_FORCEINLINE void mul_2n(int128_t& r, const boost::int64_t& a, const boost::int64_t& b) {\n    r = mult_64x64_to_128(a, b);\n}\n\ntemplate<class Traits>\ninline bool delaunay_test(int32_t ax, int32_t ay, int32_t bx, int32_t by, int32_t cx, int32_t cy, int32_t dx,\n                          int32_t dy) {\n    // Test whether the quadrilateral ABCD's diagonal AC should be flipped to BD.\n    // This is the Cline & Renka method.\n    // Flip if the sum of the angles ABC and CDA is greater than 180 degrees.\n    // Equivalently, flip if sin(ABC + CDA) < 0.\n    // Trig identity: cos(ABC) * sin(CDA) + sin(ABC) * cos(CDA) < 0\n    // We can use scalar and vector products to find sin and cos, and simplify\n    // to the following code.\n    // Numerical robustness is important.  This code addresses it by performing\n    // exact calculations with large integer types.\n    //\n    // NOTE: This routine is limited to inputs with up to 30 BIT PRECISION, which\n    // is to say all inputs must be in the range [INT_MIN/2, INT_MAX/2].\n\n    typedef typename Traits::i64_t i64;\n    typedef typename Traits::i128_t i128;\n\n    i64 cos_abc, t;\n    mul_2n(cos_abc, (ax - bx), (cx - bx));    // subtraction yields 31-bit values, multiplied to give 62-bit values\n    mul_2n(t, (ay - by), (cy - by));\n    cos_abc += t;    // addition yields 63 bit value, leaving one left for the sign\n\n    i64 cos_cda;\n    mul_2n(cos_cda, (cx - dx), (ax - dx));\n    mul_2n(t, (cy - dy), (ay - dy));\n    cos_cda += t;\n\n    if (cos_abc >= 0 && cos_cda >= 0)\n        return false;\n    if (cos_abc < 0 && cos_cda < 0)\n        return true;\n\n    i64 sin_abc;\n    mul_2n(sin_abc, (ax - bx), (cy - by));\n    mul_2n(t, (cx - bx), (ay - by));\n    sin_abc -= t;\n\n    i64 sin_cda;\n    mul_2n(sin_cda, (cx - dx), (ay - dy));\n    mul_2n(t, (ax - dx), (cy - dy));\n    sin_cda -= t;\n\n    i128 sin_sum, t128;\n    mul_2n(sin_sum, sin_abc, cos_cda);    // 63-bit inputs multiplied to 126-bit output\n    mul_2n(t128, cos_abc, sin_cda);\n    sin_sum += t128;    // Addition yields 127 bit result, leaving one bit for the sign\n\n    return sin_sum < 0;\n}\n\nstruct dt_dat {\n    int32_t ax, ay, bx, by, cx, cy, dx, dy;\n};\n\ntypedef std::vector<dt_dat> data_t;\ndata_t data;\n\ntemplate<class Traits>\nvoid do_calc(const char* name) {\n    std::cout << \"Running calculations for: \" << name << std::endl;\n\n    stopwatch<boost::chrono::high_resolution_clock> w;\n\n    boost::uint64_t flips = 0;\n    boost::uint64_t calcs = 0;\n\n    for (int j = 0; j < 1000; ++j) {\n        for (data_t::const_iterator i = data.begin(); i != data.end(); ++i) {\n            const dt_dat& d = *i;\n            bool flip = delaunay_test<Traits>(d.ax, d.ay, d.bx, d.by, d.cx, d.cy, d.dx, d.dy);\n            if (flip)\n                ++flips;\n            ++calcs;\n        }\n    }\n    double t = boost::chrono::duration_cast<boost::chrono::duration<double>>(w.elapsed()).count();\n\n    std::cout << \"Number of calculations = \" << calcs << std::endl;\n    std::cout << \"Number of flips = \" << flips << std::endl;\n    std::cout << \"Total execution time = \" << t << std::endl;\n    std::cout << \"Time per calculation = \" << t / calcs << std::endl << std::endl;\n}\n\ntemplate<class I64, class I128>\nstruct test_traits {\n    typedef I64 i64_t;\n    typedef I128 i128_t;\n};\n\ndt_dat generate_quadrilateral() {\n    static boost::random::mt19937 gen;\n    static boost::random::uniform_int_distribution<> dist(INT_MIN / 2, INT_MAX / 2);\n\n    dt_dat result;\n\n    result.ax = dist(gen);\n    result.ay = dist(gen);\n    result.bx = boost::random::uniform_int_distribution<>(result.ax, INT_MAX / 2)(gen);    // bx is to the right of ax.\n    result.by = dist(gen);\n    result.cx = dist(gen);\n    result.cy = boost::random::uniform_int_distribution<>(result.cx > result.bx ? result.by : result.ay, INT_MAX / 2)(\n        gen);    // cy is below at least one of ay and by.\n    result.dx = boost::random::uniform_int_distribution<>(result.cx, INT_MAX / 2)(gen);    // dx is to the right of cx.\n    result.dy = boost::random::uniform_int_distribution<>(result.cx > result.bx ? result.by : result.ay, INT_MAX / 2)(\n        gen);    // cy is below at least one of ay and by.\n\n    return result;\n}\n\nstatic void load_data() {\n    for (unsigned i = 0; i < 100000; ++i)\n        data.push_back(generate_quadrilateral());\n}\n\nint main() {\n    using namespace nil::crypto3::multiprecision;\n    std::cout << \"loading data...\\n\";\n    load_data();\n\n    std::cout << \"calculating...\\n\";\n\n    do_calc<test_traits<boost::int64_t, boost::int64_t>>(\"int64_t, int64_t\");\n    do_calc<test_traits<number<arithmetic_backend<boost::int64_t>, et_off>,\n                        number<arithmetic_backend<boost::int64_t>, et_off>>>(\n        \"arithmetic_backend<int64_t>, arithmetic_backend<int64_t>\");\n    do_calc<test_traits<boost::int64_t, number<arithmetic_backend<boost::int64_t>, et_off>>>(\n        \"int64_t, arithmetic_backend<int64_t>\");\n    do_calc<test_traits<number<cpp_int_backend<64, 64, nil::crypto3::multiprecision::signed_magnitude,\n                                               nil::crypto3::multiprecision::unchecked, void>,\n                               et_off>,\n                        number<cpp_int_backend<64, 64, nil::crypto3::multiprecision::signed_magnitude,\n                                               nil::crypto3::multiprecision::unchecked, void>,\n                               et_off>>>(\"multiprecision::int64_t, nil::crypto3::multiprecision::int64_t\");\n\n    do_calc<test_traits<boost::int64_t, ::int128_t>>(\"int64_t, int128_t\");\n    do_calc<test_traits<boost::int64_t, nil::crypto3::multiprecision::int128_t>>(\n        \"int64_t, nil::crypto3::multiprecision::int128_t\");\n    do_calc<test_traits<boost::int64_t, number<cpp_int_backend<128, 128, nil::crypto3::multiprecision::signed_magnitude,\n                                                               nil::crypto3::multiprecision::unchecked, void>,\n                                               et_on>>>(\"int64_t, int128_t (ET)\");\n    do_calc<test_traits<number<cpp_int_backend<64, 64, nil::crypto3::multiprecision::signed_magnitude,\n                                               nil::crypto3::multiprecision::unchecked, void>,\n                               et_off>,\n                        nil::crypto3::multiprecision::int128_t>>(\"multiprecision::int64_t, nil::crypto3::multiprecision::int128_t\");\n\n    do_calc<test_traits<boost::int64_t, cpp_int>>(\"int64_t, cpp_int\");\n    do_calc<test_traits<boost::int64_t, number<cpp_int_backend<>, et_off>>>(\"int64_t, cpp_int (no ET's)\");\n    do_calc<test_traits<boost::int64_t, number<cpp_int_backend<128>>>>(\"int64_t, cpp_int(128-bit cache)\");\n    do_calc<test_traits<boost::int64_t, number<cpp_int_backend<128>, et_off>>>(\n        \"int64_t, cpp_int (128-bit Cache no ET's)\");\n\n    return 0;\n}\n", "meta": {"hexsha": "d76d48587dc952353f2276f39db09cbfc5475bde", "size": 10240, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/multiprecision/performance/delaunay_test.cpp", "max_stars_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "libs/multiprecision/performance/delaunay_test.cpp", "max_issues_repo_name": "Curryrasul/knapsack-snark", "max_issues_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_issues_repo_licenses": ["MIT"], "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/performance/delaunay_test.cpp", "max_forks_repo_name": "Curryrasul/knapsack-snark", "max_forks_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "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": 33.5737704918, "max_line_length": 132, "alphanum_fraction": 0.5956054688, "num_tokens": 2951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6584174871563662, "lm_q1q2_score": 0.5288236727471501}}
{"text": "#include <iostream>\n\n#define _mm256_set_m128d(vh, vl) \\\n\t_mm256_insertf128_pd(_mm256_castpd128_pd256(vl), (vh), 1)\n\n#include <Eigen/Dense>\n#include <chrono>\n#include <iomanip>\n#include <vector>\n\nusing namespace Eigen;\nusing namespace std;\n\ndouble timeProduct(int n) {\n\n\tMatrixXf a = MatrixXf::Random(n, n);\n\tMatrixXf b = MatrixXf::Random(n, n);\n\tb = a*b;\n\tauto t2 = chrono::high_resolution_clock::now();\n\tfor (int i = 0; i < 10; ++i) {\n\t\tb = a*b;\n\t}\n\tauto t3 = chrono::high_resolution_clock::now();\n\tdouble duration = chrono::duration_cast<chrono::microseconds>(t3-t2).count()/1000.0;\n\treturn duration;\n}\nint main() {\n\n\t// auto t1 = chrono::high_resolution_clock::now();\n\t// int n = 10000;\n\t// MatrixXf a = MatrixXf::Random(n, n);\n\t// MatrixXf b = MatrixXf::Random(n, n);\n\t// MatrixXf c = MatrixXf::Random(n, n);\n\t// a = a*1;\n\t// b = b*1;\n\t// c = c*1;\n\n\t// auto t2 = chrono::high_resolution_clock::now();\n\t// c = a*b;\n\t// auto t3 = chrono::high_resolution_clock::now();\n\t// auto durationAll = chrono::duration_cast<chrono::microseconds>(t2-t1).count()/1000.0;\n\t// auto duration = chrono::duration_cast<chrono::microseconds>(t3-t2).count()/1000.0;\n\t// cout << \"n = \" << n << \"\\n\";\n\t// cout << \"Allocation time:\\n\\t\";\n\t// cout << durationAll << \" ms\\n\";\n\t// cout << \"Product time:\\n\\t\";\n\t// cout << duration << \"ms\\n\";\n\n\tvector<int> sizes;\n\tvector<double> times;\n\tfor (int i = 0; i < 100; ++i) {\n\t\tsizes.push_back(100 + i*10);\n\t\ttimes.push_back(timeProduct(100+i*10));\n\t}\n\tfor (auto t : times)\n\t\tcout << t << \" \";\n\tcout << endl;\n}\n", "meta": {"hexsha": "decf0b67dc631af442af37be73cba868d08c89e0", "size": 1529, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mult.cpp", "max_stars_repo_name": "GaniAliguzhinov/tensorMultBenchmarks", "max_stars_repo_head_hexsha": "352e5d73e784ce346be0c48ca1174821164ac1b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mult.cpp", "max_issues_repo_name": "GaniAliguzhinov/tensorMultBenchmarks", "max_issues_repo_head_hexsha": "352e5d73e784ce346be0c48ca1174821164ac1b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mult.cpp", "max_forks_repo_name": "GaniAliguzhinov/tensorMultBenchmarks", "max_forks_repo_head_hexsha": "352e5d73e784ce346be0c48ca1174821164ac1b2", "max_forks_repo_licenses": ["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.9152542373, "max_line_length": 89, "alphanum_fraction": 0.627207325, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5288236719265192}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2013   MetaScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_MEMORY_IS_POWER_OF_2_HPP_INCLUDED\n#define BOOST_SIMD_MEMORY_IS_POWER_OF_2_HPP_INCLUDED\n\n/*!\n  @file\n  @brief Defines and implements is_power_of_2\n**/\n\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd\n{\n  /*!\n    @brief Power of two compliance predicate for integers\n\n    Checks if a value is a non-zero power of two.\n\n    @par Semantic:\n\n    For any integer @c v :\n\n    @code\n    bool r = is_power_of_2(v);\n    @endcode\n\n    is equivalent to\n\n    @code\n    bool r = (!(value & (value - 1)) && value);\n    @endcode\n\n    If @c a is not a power of two, an assertion is triggered.\n\n    @usage{memory/is_power_of_2.cpp}\n\n    @param value  Value to check\n\n    @return A boolean indicating if @c value is a non-zero power of two\n  **/\n  template<typename Integer> BOOST_FORCEINLINE\n  bool is_power_of_2(Integer value)\n  {\n    return (!(value & (value - 1)) && value);\n  }\n} }\n\n#endif\n", "meta": {"hexsha": "4e97b1df15229f333478f625acad26b460dcdd9b", "size": 1479, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/include/boost/simd/memory/is_power_of_2.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/sdk/include/boost/simd/memory/is_power_of_2.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/boost/simd/sdk/include/boost/simd/memory/is_power_of_2.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 25.9473684211, "max_line_length": 80, "alphanum_fraction": 0.5801217039, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5288209203784422}}
{"text": "//\n// Created by vogier on 21/04/2020.\n//\n\n#include \"Trajectory.h\"\n#include <Eigen/Geometry>\n\nusing namespace vcl;\n\n/** Function returning the index i such that t \\in [v[i].t,v[i+1].t] */\nsize_t index_at_value(float t, vcl::buffer<keyframe> const& v);\n\nvcl::vec3 linear_interpolation(float t, float t1, float t2, const vcl::vec3& p1, const vcl::vec3& p2);\n\n\nvoid Trajectory::init(vcl::buffer<keyframe> _keyframes)\n{\n    // Initial Keyframe data vector of (position, time)\n    keyframes = std::move(_keyframes);\n    \n    // Set timer bounds\n    // You should adapt these extremal values to the type of interpolation\n    timer.t_min = keyframes[1].t;                   // first time of the keyframe\n    timer.t_max = keyframes[keyframes.size()-2].t;  // last time of the keyframe\n    timer.t = timer.t_min;\n}\n\nvoid Trajectory::update() {\n  timer.update();\n  const float t = timer.t;\n\n  // ********************************************* //\n  // Compute interpolated position at time t\n  // ********************************************* //\n  const int idx = index_at_value(t, keyframes);\n\n  // Preparation of data for the linear interpolation\n  // Parameters used to compute the linear interpolation\n  keyframe const & k0 = keyframes[idx - 1]; // t_{i-1}\n  keyframe const & k1 = keyframes[idx]; // = t_i\n  keyframe const & k2 = keyframes[idx + 1]; // = t_{i+1}\n  keyframe const & k3 = keyframes[idx + 2]; // = t_{i+2}\n\n  // Update position and TNB\n  cardinal_spline_interpolation_update(t, k0, k1, k2, k3, trajectory_tension);\n\n}\n\n\nsize_t index_at_value(float t, vcl::buffer<keyframe> const& v)\n{\n    const size_t N = v.size();\n    assert(v.size()>=2);\n    assert(t>=v[0].t);\n    assert(t<v[N-1].t);\n\n    size_t k=0;\n    while( v[k+1].t<t )\n        ++k;\n    return k;\n}\n\n\nvec3 linear_interpolation(float t, float t1, float t2, const vec3& p1, const vec3& p2)\n{\n    const float alpha = (t-t1)/(t2-t1);\n    const vec3 p = (1-alpha)*p1 + alpha*p2;\n\n    return p;\n}\n\n\n/**\n *\n * Les positions sont donn\u00e9es par une interpolation par spline cardinale.\n *\n * Les rotations sont obtenus de la mani\u00e8re suivante :\n *\n * Chaque keyframe se voit associ\u00e9 une direction verticale (\"binormale\") par cross product\n * entre les vecteurs vers ses voisins. Exemple : si on a trois keyframes successifs\n *      A ---- B ---- C\n * alors la direction verticale en B est donn\u00e9e par cross(AB,BC).\n * Pour que cette direction verticale pointe \"vers le haut\" (z positif), on la retourne\n * si son produit scalaire avec le vecteur unitaire z est n\u00e9gatif.\n *\n * La tangente T en un keyframe est donn\u00e9e par le vecteur reliant ses voisins (AC pour le point B),\n * c'est le m\u00eame que pour l'interpolation par spline cardianale.\n *\n * Le dernier vecteur est obtenue par cross product : N = cross(B,T). Avec ces trois vecteurs, on\n * forme un quaternion repr\u00e9sentant la rotation \u00e0 ce keyframe.\n *\n * On obtient les rotations interm\u00e9diaires entre les keyframes par slerp dans le domaine\n * des quaternions unitaires.\n *\n */\n\nvoid Trajectory::cardinal_spline_interpolation_update(float t, keyframe const & k0, keyframe const & k1, keyframe const & k2, keyframe const & k3 , float K) {\n  auto t0 = k0.t, t1 = k1.t, t2 = k2.t, t3 = k3.t;\n  auto const & p0 = k0.p, p1 = k1.p, p2 = k2.p, p3 = k3.p;\n\n  float const s = (t - t1) / (t2 - t1);\n  float const s2 = s*s;\n  float const s3 = s*s*s;\n  vec3 d1 = 2 * K * (p2 - p0) / (t2 - t0);\n  vec3 d2 = 2 * K * (p3 - p1) / (t3 - t1);\n\n  // cardinal spline interpolation of position r\n  position =  (2 * s3 - 3 * s2 + 1) * p1 + (s3 - 2*s2 + s) * d1 + (-2*s3 + 3*s2) * p2 + (s3 - s2) * d2;\n\n  /*\n  tangent = normalize( (1-s) * d1 + s * d2);\n  vec3 T = normalize(tangent - tangent.z);\n  normal = {-T.y, T.x, 0};\n  binormal = cross(tangent,normal);\n  */\n\n\n  // compute quaternion rotation at 1 and 2 and use spherical interpolation.\n  Eigen::Quaternionf q1, q2;\n\n  // Ici on approxime T par interpolation lin\u00e9aire entre d1 et d2.\n  {\n    vec3 B = normalize(cross(p0 - p1, p2 - p1));\n    if (dot(B,{0,0,1}) < 0) {\n      B = -B;\n    }\n    vec3 const T = normalize(d1 - dot(B, d1) * B);\n    vec3 const N = cross(B,T);\n    Eigen::Matrix3f m;\n    m << T.x, N.x, B.x, T.y, N.y, B.y, T.z, N.z, B.z;\n    q1 = Eigen::Quaternionf{m};\n  }\n  {\n    //vec3 const B = normalize(vert2);\n    vec3 B = normalize(cross(p1 - p2, p3 - p2));\n    if (dot(B,{0,0,1}) < 0) {\n      B = -B;\n    }\n    vec3 const T = normalize(d2 - dot(B, d2) * B);\n    vec3 const N = cross(B,T);\n    Eigen::Matrix3f m;\n    m << T.x, N.x, B.x, T.y, N.y, B.y, T.z, N.z, B.z;\n    q2 = Eigen::Quaternionf{m};\n  }\n  Eigen::Quaternionf q {q1.slerp(s, q2)};\n\n  auto m {q.toRotationMatrix()};\n\n  tangent = {m(0,0), m(1,0), m(2,0)};\n  normal = {m(0,1), m(1,1), m(2,1)};\n  binormal = {m(0,2), m(1,2), m(2,2)};\n}", "meta": {"hexsha": "3fa20ed09f3b7ea792d66c980bb9650b83b1fdf9", "size": 4749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scenes/3D_graphics/01_modeling/trajectories/Trajectory.cpp", "max_stars_repo_name": "vogr/OceanGL", "max_stars_repo_head_hexsha": "e894df3319243b8ee2102856785ab3a9930e0029", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scenes/3D_graphics/01_modeling/trajectories/Trajectory.cpp", "max_issues_repo_name": "vogr/OceanGL", "max_issues_repo_head_hexsha": "e894df3319243b8ee2102856785ab3a9930e0029", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scenes/3D_graphics/01_modeling/trajectories/Trajectory.cpp", "max_forks_repo_name": "vogr/OceanGL", "max_forks_repo_head_hexsha": "e894df3319243b8ee2102856785ab3a9930e0029", "max_forks_repo_licenses": ["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.2434210526, "max_line_length": 158, "alphanum_fraction": 0.6098125921, "num_tokens": 1578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5288209129234075}}
{"text": "/*\n * Copyright 2020 INRIA\n */\n\n#ifndef __eigenpy_decomposition_llt_hpp__\n#define __eigenpy_decomposition_llt_hpp__\n\n#include \"eigenpy/eigenpy.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n\n#include \"eigenpy/utils/scalar-name.hpp\"\n\nnamespace eigenpy\n{\n  \n  template<typename _MatrixType>\n  struct LLTSolverVisitor\n  : public boost::python::def_visitor< LLTSolverVisitor<_MatrixType> >\n  {\n    \n    typedef _MatrixType MatrixType;\n    typedef typename MatrixType::Scalar Scalar;\n    typedef typename MatrixType::RealScalar RealScalar;\n    typedef Eigen::Matrix<Scalar,Eigen::Dynamic,1,MatrixType::Options> VectorType;\n    typedef Eigen::LLT<MatrixType> Solver;\n    \n    template<class PyClass>\n    void visit(PyClass& cl) const\n    {\n      namespace bp = boost::python;\n      cl\n      .def(bp::init<>(\"Default constructor\"))\n      .def(bp::init<Eigen::DenseIndex>(bp::arg(\"size\"),\n                                       \"Default constructor with memory preallocation\"))\n      .def(bp::init<MatrixType>(bp::arg(\"matrix\"),\n                                \"Constructs a LLT factorization from a given matrix.\"))\n       \n      .def(\"matrixL\",&matrixL,bp::arg(\"self\"),\n           \"Returns the lower triangular matrix L.\")\n      .def(\"matrixU\",&matrixU,bp::arg(\"self\"),\n           \"Returns the upper triangular matrix U.\")\n      .def(\"matrixLLT\",&Solver::matrixLLT,bp::arg(\"self\"),\n           \"Returns the LLT decomposition matrix.\",\n           bp::return_internal_reference<>())\n\n#if EIGEN_VERSION_AT_LEAST(3,3,90)\n      .def(\"rankUpdate\",(Solver& (Solver::*)(const VectorType &, const RealScalar &))&Solver::template rankUpdate<VectorType>,\n           bp::args(\"self\",\"vector\",\"sigma\"), bp::return_self<>())\n#else\n      .def(\"rankUpdate\",(Solver (Solver::*)(const VectorType &, const RealScalar &))&Solver::template rankUpdate<VectorType>,\n           bp::args(\"self\",\"vector\",\"sigma\"))\n#endif\n      \n#if EIGEN_VERSION_AT_LEAST(3,3,0)\n      .def(\"adjoint\",&Solver::adjoint,bp::arg(\"self\"),\n           \"Returns the adjoint, that is, a reference to the decomposition itself as if the underlying matrix is self-adjoint.\",\n           bp::return_self<>())\n#endif\n      \n      .def(\"compute\",(Solver & (Solver::*)(const Eigen::EigenBase<MatrixType> & matrix))&Solver::compute,\n           bp::args(\"self\",\"matrix\"),\n           \"Computes the LLT of given matrix.\",\n           bp::return_self<>())\n      \n      .def(\"info\",&Solver::info,bp::arg(\"self\"),\n           \"NumericalIssue if the input contains INF or NaN values or overflow occured. Returns Success otherwise.\")\n#if EIGEN_VERSION_AT_LEAST(3,3,0)\n      .def(\"rcond\",&Solver::rcond,bp::arg(\"self\"),\n           \"Returns an estimate of the reciprocal condition number of the matrix.\")\n#endif\n      .def(\"reconstructedMatrix\",&Solver::reconstructedMatrix,bp::arg(\"self\"),\n           \"Returns the matrix represented by the decomposition, i.e., it returns the product: L L^*. This function is provided for debug purpose.\")\n      .def(\"solve\",&solve<VectorType>,bp::args(\"self\",\"b\"),\n           \"Returns the solution x of A x = b using the current decomposition of A.\")\n      ;\n    }\n    \n    static void expose()\n    {\n      static const std::string classname = \"LLT\" + scalar_name<Scalar>::shortname();\n      expose(classname);\n    }\n    \n    static void expose(const std::string & name)\n    {\n      namespace bp = boost::python;\n      bp::class_<Solver>(name.c_str(),\n                         \"Standard Cholesky decomposition (LL^T) of a matrix and associated features.\\n\\n\"\n                         \"This class performs a LL^T Cholesky decomposition of a symmetric, positive definite matrix A such that A = LL^* = U^*U, where L is lower triangular.\\n\\n\"\n                         \"While the Cholesky decomposition is particularly useful to solve selfadjoint problems like D^*D x = b, for that purpose, we recommend the Cholesky decomposition without square root which is more stable and even faster. Nevertheless, this standard Cholesky decomposition remains useful in many other situations like generalised eigen problems with hermitian matrices.\",\n                         bp::no_init)\n      .def(LLTSolverVisitor());\n    }\n    \n  private:\n    \n    static MatrixType matrixL(const Solver & self) { return self.matrixL(); }\n    static MatrixType matrixU(const Solver & self) { return self.matrixU(); }\n    \n    template<typename VectorType>\n    static VectorType solve(const Solver & self, const VectorType & vec)\n    {\n      return self.solve(vec);\n    }\n  };\n  \n} // namespace eigenpy\n\n#endif // ifndef __eigenpy_decomposition_llt_hpp__\n", "meta": {"hexsha": "ba8c2f2b721a8febfce0820c68e3968e1eaa9e39", "size": 4587, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/eigenpy/decompositions/LLT.hpp", "max_stars_repo_name": "cmastalli/eigenpy", "max_stars_repo_head_hexsha": "aef2a9aa3be42d85275fbe654eb621e289b02017", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-31T01:30:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-24T12:06:39.000Z", "max_issues_repo_path": "include/eigenpy/decompositions/LLT.hpp", "max_issues_repo_name": "cmastalli/eigenpy", "max_issues_repo_head_hexsha": "aef2a9aa3be42d85275fbe654eb621e289b02017", "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/eigenpy/decompositions/LLT.hpp", "max_forks_repo_name": "cmastalli/eigenpy", "max_forks_repo_head_hexsha": "aef2a9aa3be42d85275fbe654eb621e289b02017", "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.9553571429, "max_line_length": 394, "alphanum_fraction": 0.6470459996, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5288209129234075}}
{"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 <cassert>\n#include <cstdlib>\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/timer.hpp>\n\n\nusing namespace std;\n\ntemplate <typename Matrix, typename Value, typename Vector>\nvoid test_vector(const Matrix& A, const Value& alpha, const Vector& v, double tol, int i)\n{\n    Vector diff(A*v-alpha*v), v1(A*v), v2(alpha*v); // , diff(v1-v2);\n    if (size(v1) < 17) \t\n\tcout << \"A*v is     \" << v1 << \"\\nalpha*v is \" << v2 << '\\n';\n    if (two_norm(diff) > tol) cout << \"two_norm(difference) of the \" << i << \"-th eigenvector is \" << two_norm(diff) << \", two_norm(A*v) is \" << two_norm(v1) << \", two_norm(alpha*v) is \" << two_norm(v2) << '\\n'; // throw \"wrong eigenvector\";\n}\n\n\nint main(int argc, char** argv) \n{\n    using namespace mtl;\n\n    int select= 1, sub= 600;\n    if (argc > 1)\n\tselect= atoi(argv[1]);\n    assert(select >= 1 && select <= 2);\n\n    if (argc > 2)\n\tsub= atoi(argv[2]);\n    \n    string fname= string(\"../../../../../branches/data/matrix_market/Partha\") + char('0' + select) + \".mtx\";\n    \n\n    dense2D<double>    A0(io::matrix_market(fname.c_str())), A(clone(A0[irange(sub)][irange(sub)]));\n    //    cout << \"Size of A is \" << num_rows(A) << \" x \" << num_cols(A) << '\\n';\n   \n    boost::timer tri_time;\n    dense2D<double>    C(hessenberg_factors(A)), D(clone(bands(C, -1, 2))), Q(num_rows(D), num_rows(D));\n    cout << \"The tridiagonal matrix is\\n\" << D[irange(10)][irange(10)] << \"This took \" << tri_time.elapsed() << \"s.\\n\";\n   \n    tri_time.restart();\n    dense_vector<double>       lambda(num_rows(D));\n\n    cuppen(D, Q, lambda);\n    cout << \"Q is\\n\" << Q[irange(10)][irange(10)] << \"This took \" << tri_time.elapsed() << \"s.\\n\";\n    // std::cout << \"The eigenvalues are \" << lambda << \"\\n\";\n#if 0  \n    for (unsigned i= 0; i < num_rows(D); i++)\n\ttest_vector(D, lambda[i], mtl::dense_vector<double>(Q[mtl::iall][i]), 1e-4, i);\n#endif\n    return 0;\n}\n", "meta": {"hexsha": "0516c5a7e65d3a2d52402ac992f83f2c3dce3e0b", "size": 2344, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/eigenvalues_givens_exp.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/eigenvalues_givens_exp.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/eigenvalues_givens_exp.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": 35.5151515152, "max_line_length": 241, "alphanum_fraction": 0.6028156997, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5288209080794171}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/rep.hpp\n *\n * \\brief Replicate and tile a matrix or a vector.\n *\n * This operation mimic the MATLAB \\c repmat function.\n *\n * Copyright (c) 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_REP_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_REP_HPP\n\n\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.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#include <boost/numeric/ublasx/operation/size.hpp>\n#include <cstddef>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\ntemplate <typename MatrixExprT>\nmatrix<typename matrix_traits<MatrixExprT>::value_type> rep(matrix_expression<MatrixExprT> const& me, ::std::size_t nr, ::std::size_t nc)\n{\n\ttypedef matrix<typename matrix_traits<MatrixExprT>::value_type> result_matrix_type;\n\ttypedef typename matrix_traits<MatrixExprT>::size_type size_type;\n\n\tsize_type nr_me(num_rows(me));\n\tsize_type nc_me(num_columns(me));\n\n\tresult_matrix_type res(nr_me*nr, nc_me*nc);\n\n\tfor (size_type r = 0; r < nr; ++r)\n\t{\n\t\tfor (size_type c = 0; c < nc; ++c)\n\t\t{\n\t\t\tsubrange(res, r*nr_me, (r+1)*nr_me, c*nc_me, (c+1)*nc_me) = me;\n\t\t}\n\t}\n\n\treturn res;\n}\n\n\ntemplate <typename VectorExprT>\nmatrix<typename vector_traits<VectorExprT>::value_type> rep(vector_expression<VectorExprT> const& ve, ::std::size_t nr, ::std::size_t nc)\n{\n\ttypedef matrix<typename vector_traits<VectorExprT>::value_type> result_matrix_type;\n\ttypedef typename vector_traits<VectorExprT>::size_type size_type;\n\n\tsize_type n_ve(size(ve));\n\n\tresult_matrix_type res(n_ve*nr, nc);\n\n\tfor (size_type r = 0; r < nr; ++r)\n\t{\n\t\tfor (size_type c = 0; c < nc; ++c)\n\t\t{\n\t\t\tfor (size_type i = 0; i < n_ve; ++i)\n\t\t\t{\n\t\t\t\tres(r*n_ve+i, c) = ve()(i);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res;\n}\n\n\ntemplate <typename MatrixExprT>\nmatrix<typename matrix_traits<MatrixExprT>::value_type> rep(matrix_expression<MatrixExprT> const& me, ::std::size_t n)\n{\n\treturn rep(me, n, n);\n}\n\n\ntemplate <typename MatrixExprT>\nmatrix<typename matrix_traits<MatrixExprT>::value_type> rep(vector_expression<MatrixExprT> const& ve, ::std::size_t n)\n{\n\treturn rep(ve, n, n);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_REP_HPP\n", "meta": {"hexsha": "3d89055c0577b3ea53a02901aac3d8ad3fe59bac", "size": 2631, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/rep.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/rep.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/rep.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": 26.0495049505, "max_line_length": 137, "alphanum_fraction": 0.7331812999, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.528820900624382}}
{"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_SQRTSMALLESTPOSVAL_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_SQRTSMALLESTPOSVAL_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate the square root of the least non zero positive non denormal\n    value of the chosen type.\n\n    @par Semantic:\n\n    @code\n    T r = Sqrtsmallestposval<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    if T is integral\n      r = 1\n    else if T is double\n      r =  1.491668146240041e-154;\n    else if T is float\n      r =   1.0842022e-19;\n    @endcode\n\n    @return The Sqrtsmallestposval constant for the proper type\n  **/\n  template<typename T> T Sqrtsmallestposval();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant sqrtsmallestposval.\n\n      @return The Sqrtsmallestposval constant for the proper type\n    **/\n    Value Sqrtsmallestposval();\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/sqrtsmallestposval.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": "ee6eaf3bc7baf65322e64b949421144fe562e355", "size": 1551, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/sqrtsmallestposval.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/sqrtsmallestposval.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/sqrtsmallestposval.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 25.0161290323, "max_line_length": 100, "alphanum_fraction": 0.6196002579, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.528820900624382}}
{"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    testPCGSolver.cpp\n * @brief   Unit tests for PCGSolver class\n * @author  Yong-Dian Jian\n */\n\n#include <tests/smallExample.h>\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/Values.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/GaussNewtonOptimizer.h>\n#include <gtsam/nonlinear/DoglegOptimizer.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/PCGSolver.h>\n#include <gtsam/linear/Preconditioner.h>\n#include <gtsam/linear/SubgraphPreconditioner.h>\n#include <gtsam/linear/NoiseModel.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/base/Matrix.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/shared_ptr.hpp>\n#include <boost/assign/std/list.hpp> // for operator +=\nusing namespace boost::assign;\n\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace gtsam;\n\nconst double tol = 1e-3;\n\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\n/* ************************************************************************* */\nTEST( PCGSolver, llt ) {\n  Matrix R = (Matrix(3,3) <<\n                1., -1., -1.,\n                0.,  2., -1.,\n                0.,  0.,  1.);\n  Matrix AtA = R.transpose() * R;\n\n  Vector Rvector = (Vector(9) << 1., -1., -1.,\n                                 0.,  2., -1.,\n                                 0.,  0.,  1.);\n//  Vector Rvector = (Vector(6) << 1., -1., -1.,\n//                                      2., -1.,\n//                                           1.);\n\n  Vector b = (Vector(3) << 1., 2., 3.);\n\n  Vector x = (Vector(3) << 6.5, 2.5, 3.) ;\n\n  /* test cholesky */\n  Matrix Rhat = AtA.llt().matrixL().transpose();\n  EXPECT(assert_equal(R, Rhat, 1e-5));\n\n  /* test backward substitution */\n  Vector xhat = Rhat.triangularView<Eigen::Upper>().solve(b);\n  EXPECT(assert_equal(x, xhat, 1e-5));\n\n  /* test in-place back substitution */\n  xhat = b;\n  Rhat.triangularView<Eigen::Upper>().solveInPlace(xhat);\n  EXPECT(assert_equal(x, xhat, 1e-5));\n\n  /* test triangular matrix map */\n  Eigen::Map<Eigen::MatrixXd> Radapter(Rvector.data(), 3, 3);\n  xhat = Radapter.transpose().triangularView<Eigen::Upper>().solve(b);\n  EXPECT(assert_equal(x, xhat, 1e-5));\n\n}\n\n/* ************************************************************************* */\nTEST( PCGSolver, dummy )\n{\n  LevenbergMarquardtParams paramsPCG;\n  paramsPCG.linearSolverType = LevenbergMarquardtParams::Iterative;\n  PCGSolverParameters::shared_ptr pcg = boost::make_shared<PCGSolverParameters>();\n  pcg->preconditioner_ = boost::make_shared<DummyPreconditionerParameters>();\n  paramsPCG.iterativeParams = pcg;\n\n  NonlinearFactorGraph fg = example::createReallyNonlinearFactorGraph();\n\n  Point2 x0(10,10);\n  Values c0;\n  c0.insert(X(1), x0);\n\n  Values actualPCG = LevenbergMarquardtOptimizer(fg, c0, paramsPCG).optimize();\n\n  DOUBLES_EQUAL(0,fg.error(actualPCG),tol);\n}\n\n/* ************************************************************************* */\nTEST( PCGSolver, blockjacobi )\n{\n  LevenbergMarquardtParams paramsPCG;\n  paramsPCG.linearSolverType = LevenbergMarquardtParams::Iterative;\n  PCGSolverParameters::shared_ptr pcg = boost::make_shared<PCGSolverParameters>();\n  pcg->preconditioner_ = boost::make_shared<BlockJacobiPreconditionerParameters>();\n  paramsPCG.iterativeParams = pcg;\n\n  NonlinearFactorGraph fg = example::createReallyNonlinearFactorGraph();\n\n  Point2 x0(10,10);\n  Values c0;\n  c0.insert(X(1), x0);\n\n  Values actualPCG = LevenbergMarquardtOptimizer(fg, c0, paramsPCG).optimize();\n\n  DOUBLES_EQUAL(0,fg.error(actualPCG),tol);\n}\n\n/* ************************************************************************* */\nTEST( PCGSolver, subgraph )\n{\n  LevenbergMarquardtParams paramsPCG;\n  paramsPCG.linearSolverType = LevenbergMarquardtParams::Iterative;\n  PCGSolverParameters::shared_ptr pcg = boost::make_shared<PCGSolverParameters>();\n  pcg->preconditioner_ = boost::make_shared<SubgraphPreconditionerParameters>();\n  paramsPCG.iterativeParams = pcg;\n\n  NonlinearFactorGraph fg = example::createReallyNonlinearFactorGraph();\n\n  Point2 x0(10,10);\n  Values c0;\n  c0.insert(X(1), x0);\n\n  Values actualPCG = LevenbergMarquardtOptimizer(fg, c0, paramsPCG).optimize();\n\n  DOUBLES_EQUAL(0,fg.error(actualPCG),tol);\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n\n", "meta": {"hexsha": "38a40521a97c30cd7cd3a085e4c6fc60b0bd9a94", "size": 4956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testPCGSolver.cpp", "max_stars_repo_name": "ashariati/gtsam-3.2.1", "max_stars_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T08:58:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T08:01:42.000Z", "max_issues_repo_path": "tests/testPCGSolver.cpp", "max_issues_repo_name": "ashariati/gtsam-3.2.1", "max_issues_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T16:21:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-13T16:50:42.000Z", "max_forks_repo_path": "tests/testPCGSolver.cpp", "max_forks_repo_name": "ashariati/gtsam-3.2.1", "max_forks_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2015-06-01T11:22:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T11:03:57.000Z", "avg_line_length": 31.3670886076, "max_line_length": 83, "alphanum_fraction": 0.6154156578, "num_tokens": 1345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5287701372028131}}
{"text": "// -------------------------------------------------------------------------------------------------\n//                              Copyright 2016 - NumScale SAS\n//\n//                   Distributed under the Boost Software License, Version 1.0.\n//                        See accompanying file LICENSE.txt or copy at\n//                            http://www.boost.org/LICENSE_1_0.txt\n// -------------------------------------------------------------------------------------------------\n\n#include <simd_bench.hpp>\n#include <boost/simd/function/simd/ldexp.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>\n\nnamespace nsb = ns::bench;\nnamespace bs =  boost::simd;\nnamespace bd =  boost::dispatch;\n\nDEFINE_SIMD_BENCH(simd_ldexp, bs::ldexp);\n\ntemplate < int N >\nstruct lde\n{\n  template<class T> T operator()(const T & a) const\n  {\n    return bs::ldexp(a, N);\n  }\n};\ntemplate < int N >\nstruct ldef\n{\n  template<class T> T operator()(const T & a) const\n  {\n    return bs::fast_(bs::ldexp)(a, N);\n  }\n};\n\n  DEFINE_SIMD_BENCH(simd_lde10, lde<10>());\n  DEFINE_SIMD_BENCH(fast_simd_lde10, ldef<10>());\n\nDEFINE_BENCH_MAIN() {\n  nsb::for_each<simd_lde10, NS_BENCH_IEEE_TYPES>(-10, 10);\n  nsb::for_each<fast_simd_lde10, NS_BENCH_IEEE_TYPES>(-10, 10);\n}\n\n\n", "meta": {"hexsha": "593b2f6426921e560788a04e21541b04a779ce2c", "size": 1341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/function/simd/ldexp.cpp", "max_stars_repo_name": "timblechmann/boost.simd", "max_stars_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_stars_repo_licenses": ["BSL-1.0"], "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": "bench/function/simd/ldexp.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "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": "bench/function/simd/ldexp.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "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": 28.5319148936, "max_line_length": 100, "alphanum_fraction": 0.5495898583, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5287701306009245}}
{"text": "/**\n * @file tests/binarize_test.cpp\n * @author Keon Kim\n *\n * Test the Binarize method.\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/data/binarize.hpp>\n#include <mlpack/core/math/random.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace arma;\nusing namespace mlpack::data;\n\nBOOST_AUTO_TEST_SUITE(BinarizeTest);\n\nBOOST_AUTO_TEST_CASE(BinerizeOneDimension)\n{\n  mat input;\n  input << 1 << 2 << 3 << endr\n        << 4 << 5 << 6 << endr // this row will be tested\n        << 7 << 8 << 9;\n\n  mat output;\n  const double threshold = 5.0;\n  const size_t dimension = 1;\n  Binarize<double>(input, output, threshold, dimension);\n\n  BOOST_REQUIRE_CLOSE(output(0, 0), 1, 1e-5); // 1\n  BOOST_REQUIRE_CLOSE(output(0, 1), 2, 1e-5); // 2\n  BOOST_REQUIRE_CLOSE(output(0, 2), 3, 1e-5); // 3\n  BOOST_REQUIRE_SMALL(output(1, 0), 1e-5); // 4 target\n  BOOST_REQUIRE_SMALL(output(1, 1), 1e-5); // 5 target\n  BOOST_REQUIRE_CLOSE(output(1, 2), 1, 1e-5); // 6 target\n  BOOST_REQUIRE_CLOSE(output(2, 0), 7, 1e-5); // 7\n  BOOST_REQUIRE_CLOSE(output(2, 1), 8, 1e-5); // 8\n  BOOST_REQUIRE_CLOSE(output(2, 2), 9, 1e-5); // 9\n}\n\nBOOST_AUTO_TEST_CASE(BinerizeAll)\n{\n  mat input;\n  input << 1 << 2 << 3 << endr\n        << 4 << 5 << 6 << endr // this row will be tested\n        << 7 << 8 << 9;\n\n  mat output;\n  const double threshold = 5.0;\n\n  Binarize<double>(input, output, threshold);\n\n  BOOST_REQUIRE_SMALL(output(0, 0), 1e-5); // 1\n  BOOST_REQUIRE_SMALL(output(0, 1), 1e-5); // 2\n  BOOST_REQUIRE_SMALL(output(0, 2), 1e-5); // 3\n  BOOST_REQUIRE_SMALL(output(1, 0), 1e-5); // 4\n  BOOST_REQUIRE_SMALL(output(1, 1), 1e-5); // 5\n  BOOST_REQUIRE_CLOSE(output(1, 2), 1.0, 1e-5); // 6\n  BOOST_REQUIRE_CLOSE(output(2, 0), 1.0, 1e-5); // 7\n  BOOST_REQUIRE_CLOSE(output(2, 1), 1.0, 1e-5); // 8\n  BOOST_REQUIRE_CLOSE(output(2, 2), 1.0, 1e-5); // 9\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "5d25028be0c818cf2a46c9bf508dd8759f8ef201", "size": 2192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/binarize_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/binarize_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/binarize_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": 30.4444444444, "max_line_length": 78, "alphanum_fraction": 0.6587591241, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5287701187810597}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_CONSTANT_CONSTANTS_PI_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_CONSTANTS_PI_HPP_INCLUDED\n\n#include <boost/simd/include/functor.hpp>\n#include <boost/simd/constant/register.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n   /*!\n     @brief Pi generic tag\n\n     Represents the Pi constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    BOOST_SIMD_CONSTANT_REGISTER( Pi, double, 3\n                                , 0x40490FDB, 0x400921FB54442D18ULL\n                                )\n  }\n  namespace ext\n  {\n   template<class Site>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Pi, Site> dispatching_Pi(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)\n   {\n     return generic_dispatcher<tag::Pi, Site>();\n   }\n   template<class... Args>\n   struct impl_Pi;\n  }\n  /*!\n    Generates value \\f$\\pi\\f$ that is the half length of a circle of radius one\n    ... in normal temperature and pressure conditions.\n\n    @par Semantic:\n\n    @code\n    T r = Pi<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = T(4*atan(1));\n    @endcode\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(boost::simd::tag::Pi, Pi)\n} }\n\n#include <boost/simd/constant/common.hpp>\n\n#endif\n", "meta": {"hexsha": "513ab2437fc921f67bb38b5dd048cbb15d9aefcb", "size": 1766, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/constant/constants/pi.hpp", "max_stars_repo_name": "feelpp/nt2", "max_stars_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/constant/constants/pi.hpp", "max_issues_repo_name": "feelpp/nt2", "max_issues_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "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": "modules/boost/simd/base/include/boost/simd/constant/constants/pi.hpp", "max_forks_repo_name": "feelpp/nt2", "max_forks_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 27.1692307692, "max_line_length": 125, "alphanum_fraction": 0.5815402039, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.528770114946996}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, 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#include <iostream>\n#include <sstream>\n\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/algorithms/make.hpp>\n#include <boost/geometry/algorithms/transform.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n#include <boost/geometry/util/write_dsv.hpp>\n#include <boost/geometry/domains/gis/io/wkt/wkt.hpp>\n\n#include <test_common/test_point.hpp>\n\ntemplate <typename P1, typename P2>\nvoid test_transform_point(\n        typename bg::select_most_precise\n            <\n                typename bg::coordinate_type<P1>::type,\n                double\n            >::type value)\n{\n    P1 p1;\n    bg::set<0>(p1, 1);\n    bg::set<1>(p1, 2);\n    P2 p2;\n    BOOST_CHECK(bg::transform(p1, p2));\n\n    BOOST_CHECK_CLOSE(value * bg::get<0>(p1), bg::get<0>(p2), 0.001);\n    BOOST_CHECK_CLOSE(value * bg::get<1>(p1), bg::get<1>(p2), 0.001);\n}\n\ntemplate <typename P1, typename P2>\nvoid test_transform_linestring()\n{\n    bg::model::linestring<P1> line1;\n    line1.push_back(bg::make<P1>(1, 1));\n    line1.push_back(bg::make<P1>(2, 2));\n    bg::model::linestring<P2> line2;\n    BOOST_CHECK(bg::transform(line1, line2));\n    BOOST_CHECK_EQUAL(line1.size(), line2.size());\n\n    std::ostringstream out1, out2;\n    out1 << bg::wkt(line1);\n    out2 << bg::wkt(line2);\n    BOOST_CHECK_EQUAL(out1.str(), out1.str());\n}\n\n\ntemplate <typename P1, typename P2>\nvoid test_all(double value = 1.0)\n{\n    test_transform_point<P1, P2>(value);\n    test_transform_linestring<P1, P2>();\n}\n\ntemplate <typename T, typename DegreeOrRadian>\nvoid test_transformations(double phi, double theta, double r)\n{\n    typedef bg::model::point<T, 3, bg::cs::cartesian> cartesian_type;\n    cartesian_type p;\n\n    // 1: using spherical coordinates\n    {\n        typedef bg::model::point<T, 3, bg::cs::spherical<DegreeOrRadian> >  spherical_type;\n        spherical_type sph1;\n        assign_values(sph1, phi, theta, r);\n        BOOST_CHECK(transform(sph1, p));\n\n        spherical_type sph2;\n        BOOST_CHECK(transform(p, sph2));\n\n        BOOST_CHECK_CLOSE(bg::get<0>(sph1), bg::get<0>(sph2), 0.001);\n        BOOST_CHECK_CLOSE(bg::get<1>(sph1), bg::get<1>(sph2), 0.001);\n\n        //std::cout << dsv(p) << std::endl;\n        //std::cout << dsv(sph2) << std::endl;\n    }\n\n    // 2: using spherical coordinates on unit sphere\n    {\n        typedef bg::model::point<T, 2, bg::cs::spherical<DegreeOrRadian> >  spherical_type;\n        spherical_type sph1, sph2;\n        assign_values(sph1, phi, theta);\n        BOOST_CHECK(transform(sph1, p));\n        BOOST_CHECK(transform(p, sph2));\n\n        BOOST_CHECK_CLOSE(bg::get<0>(sph1), bg::get<0>(sph2), 0.001);\n        BOOST_CHECK_CLOSE(bg::get<1>(sph1), bg::get<1>(sph2), 0.001);\n\n        //std::cout << dsv(sph1) << \" \" << dsv(p) << \" \" << dsv(sph2) << std::endl;\n    }\n}\n\nint test_main(int, char* [])\n{\n    typedef bg::model::d2::point_xy<double > P;\n    test_all<P, P>();\n    test_all<bg::model::d2::point_xy<int>, bg::model::d2::point_xy<float> >();\n\n    test_all<bg::model::point<double, 2, bg::cs::spherical<bg::degree> >,\n        bg::model::point<double, 2, bg::cs::spherical<bg::radian> > >(bg::math::d2r);\n    test_all<bg::model::point<double, 2, bg::cs::spherical<bg::radian> >,\n        bg::model::point<double, 2, bg::cs::spherical<bg::degree> > >(bg::math::r2d);\n\n    test_all<bg::model::point<int, 2, bg::cs::spherical<bg::degree> >,\n        bg::model::point<float, 2, bg::cs::spherical<bg::radian> > >(bg::math::d2r);\n\n    test_transformations<float, bg::degree>(4, 52, 1);\n    test_transformations<double, bg::degree>(4, 52, 1);\n\n    test_transformations<float, bg::radian>(3 * bg::math::d2r, 51 * bg::math::d2r, 1);\n    test_transformations<double, bg::radian>(3 * bg::math::d2r, 51 * bg::math::d2r, 1);\n\n#if defined(HAVE_TTMATH)\n    typedef bg::model::d2::point_xy<ttmath_big > PT;\n    test_all<PT, PT>();\n    test_transformations<ttmath_big, bg::degree>(4, 52, 1);\n    test_transformations<ttmath_big, bg::radian>(3 * bg::math::d2r, 51 * bg::math::d2r, 1);\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "c8b02e3944fdc3353149e8e1170899c7d33b27c8", "size": 4697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/algorithms/transform.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/test/algorithms/transform.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/test/algorithms/transform.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": 33.3120567376, "max_line_length": 91, "alphanum_fraction": 0.6478603364, "num_tokens": 1475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5287701149469959}}
{"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 <random>\n#include <string>\n\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\nint main(int argc, char** argv) \n{\n    default_random_engine re(random_device{}());\n    \n    \n    int n = 10;\n    if (argc > 1)\n        n = stoi(argv[1]);\n        \n    for (int s = 4; s < n; ++s) {\n        cout << \"s = \" << s << endl;\n        mtl::compressed2D<int> A(s, s), B(s, s);\n        {\n            mtl::mat::inserter<mtl::compressed2D<int>> ia(A, 5), ib(B, 0);\n            uniform_int_distribution<> u(0, s-1);\n            for (int i = 0; i < 4*s; ++i) {\n                int r = u(re), c = u(re), v = u(re) + 1;\n                ia[r][c] << v;\n                ib[r][c] << v;\n                // cout << \"A[\" << r << \"][\" << c << \"] = \" << v << endl;\n            }\n        }\n        if (s < 8)  \n            cout << \"A =\\n\" << A << \"B =\\n\" << B;\n        mtl::compressed2D<int> D(A - B);\n        if (one_norm(D) > 0) {\n            cout << \"Matrices are different!\\n\";\n            return 1;\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "ef6c65508af64df9a6eef40c85785c4dabc3a7b6", "size": 1490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/random_matrix_inserter_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/random_matrix_inserter_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/random_matrix_inserter_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": 27.0909090909, "max_line_length": 94, "alphanum_fraction": 0.488590604, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5287701135630837}}
{"text": "#include <iostream>\n#include \"CDTree.hpp\"\n#include \"RFCSV.hpp\"\n#include <Eigen/Dense>\nusing Eigen::MatrixXf; using Eigen::MatrixXi;\nint main()\n{\n\n\tstd::pair<MatrixXf, MatrixXi> trainData, testData;\n\tRFCSV<MatrixXf, MatrixXi> readcsv;\n\ttrainData = readcsv.getData(\"../data/ContinuousTrain.csv\");\n\ttestData = readcsv.getData(\"../data/ContinuousTest.csv\");\n\tCDTree myCDTree(4, 3, 0.0001);\n\tmyCDTree.buildTree(trainData.first, trainData.second, \"ID3\");\n\tMatrixXi predictresult = myCDTree.predict(testData.first);\n\tfloat accuracy = 0;\n\tfor (int i = 0; i < predictresult.size(); i++)\n\t{\n\t\tif (testData.second(i) == predictresult(i))\n\t\t{\n\t\t\taccuracy += 1.0 / predictresult.size();\n\t\t}\n\t}\n\tcout << \"\u51c6\u786e\u7387\u4e3a\uff1a\" << accuracy * 100 << \"\\% \u4f60\u5f88\u68d2\u68d2\u54e6\uff01\" << endl;\n}\n", "meta": {"hexsha": "b03b276e148a09515ecf407f37751b5a1152d65d", "size": 742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++ source Code/Continuous/main.cpp", "max_stars_repo_name": "PiggyGaGa/MachineLearning-DecisionTree", "max_stars_repo_head_hexsha": "3c063024405021739509e6cdb3655d5ebf417ebd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2018-07-21T15:18:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T10:09:52.000Z", "max_issues_repo_path": "C++ source Code/Continuous/main.cpp", "max_issues_repo_name": "PiggyGaGa/MachineLearning-DecisionTree", "max_issues_repo_head_hexsha": "3c063024405021739509e6cdb3655d5ebf417ebd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-18T07:38:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T02:51:01.000Z", "max_forks_repo_path": "C++ source Code/Continuous/main.cpp", "max_forks_repo_name": "PiggyGaGa/MachineLearning-DecisionTree", "max_forks_repo_head_hexsha": "3c063024405021739509e6cdb3655d5ebf417ebd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-04-01T05:18:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-20T13:11:47.000Z", "avg_line_length": 28.5384615385, "max_line_length": 62, "alphanum_fraction": 0.6846361186, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5287687416120187}}
{"text": "#include <boost/graph/clustering_coefficient.hpp>\n", "meta": {"hexsha": "77c51ff177c26b68cee4399535548551433969dd", "size": 50, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_graph_clustering_coefficient.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_graph_clustering_coefficient.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_graph_clustering_coefficient.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.0, "max_line_length": 49, "alphanum_fraction": 0.84, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5287687416120186}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2021 Nikita Kaskov <nbering@nil.foundation>\n// Copyright (c) 2022 Ilia Shirobokov <i.shirobokov@nil.foundation>\n// Copyright (c) 2022 Ekaterina Chukavina <kate@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 kzg_test\n\n#include <string>\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/curves/mnt4.hpp>\n#include <nil/crypto3/algebra/random_element.hpp>\n#include <nil/crypto3/algebra/pairing/mnt4.hpp>\n#include <nil/crypto3/math/polynomial/polynomial.hpp>\n#include <nil/crypto3/math/algorithms/unity_root.hpp>\n#include <nil/crypto3/math/domains/evaluation_domain.hpp>\n#include <nil/crypto3/math/algorithms/make_evaluation_domain.hpp>\n#include <nil/crypto3/zk/commitments/polynomial/kzg.hpp>\n\nusing namespace nil::crypto3;\nusing namespace nil::crypto3::zk::snark;\nusing namespace nil::crypto3::math;\n\nBOOST_AUTO_TEST_SUITE(kzg_test_suite)\n\nBOOST_AUTO_TEST_CASE(kzg_basic_test) {\n\n    typedef algebra::curves::mnt4<298> curve_type;\n    typedef typename curve_type::base_field_type::value_type base_field_value_type;\n    typedef zk::snark::kzg_commitment<curve_type> kzg_type;\n\n    typename kzg_type::params_type kzg_params;\n    kzg_params.a = 2;\n\n    const polynomial<base_field_value_type> f = {1, 1};\n\n    auto kzg_keys = kzg_type::setup(298, kzg_params);\n    auto commit = kzg_type::commit(std::get<0>(kzg_keys), f);\n    auto proof = kzg_type::proof_eval(std::get<0>(kzg_keys), 1, 2, f);\n\n    BOOST_CHECK(kzg_type::verify_eval(std::get<1>(kzg_keys), commit, 1, 2, proof));\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "7d519d02536a838a21980f33b0654b5e827ce2b6", "size": 2930, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/commitment/kzg.cpp", "max_stars_repo_name": "NilFoundation/zk", "max_stars_repo_head_hexsha": "60c63ba8e719620e9fe68d68621c84afded2a809", "max_stars_repo_licenses": ["MIT"], "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/commitment/kzg.cpp", "max_issues_repo_name": "NilFoundation/zk", "max_issues_repo_head_hexsha": "60c63ba8e719620e9fe68d68621c84afded2a809", "max_issues_repo_licenses": ["MIT"], "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/commitment/kzg.cpp", "max_forks_repo_name": "NilFoundation/zk", "max_forks_repo_head_hexsha": "60c63ba8e719620e9fe68d68621c84afded2a809", "max_forks_repo_licenses": ["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.4637681159, "max_line_length": 83, "alphanum_fraction": 0.7235494881, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5287687394005249}}
{"text": "#include <Eigen/Dense>\n\n#include <gpd/net/conv_layer.h>\n\nnamespace gpd {\nnamespace test {\nnamespace {\n\nint DoMain(int argc, char *argv[]) {\n  // Create example input, weights, bias.\n  Eigen::MatrixXf X(5, 5);\n  Eigen::MatrixXf W(3, 3);\n  Eigen::VectorXf b = Eigen::VectorXf::Zero(1);\n  X << 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0,\n      0;\n  W << 1, 0, 1, 0, 1, 0, 1, 0, 1;\n\n  std::vector<float> w_vec;\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n      W_rowmajor(W);\n  Eigen::Map<Eigen::VectorXf> w(W_rowmajor.data(), W_rowmajor.size());\n  w_vec.assign(w.data(), w.data() + w.size());\n\n  std::vector<float> b_vec;\n  b_vec.assign(b.data(), b.data() + b.size());\n\n  // Create a convolutional layer and execute a forward pass.\n  net::ConvLayer conv1(5, 5, 1, 1, 3, 1, 0);\n  conv1.setWeightsAndBiases(w_vec, b_vec);\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n      X_row_major(X);\n  Eigen::Map<Eigen::VectorXf> v1(X_row_major.data(), X_row_major.size());\n  std::vector<float> vec1;\n  vec1.assign(v1.data(), v1.data() + v1.size());\n  Eigen::MatrixXf Y = conv1.forward(vec1);\n\n  std::cout << \"Y: \" << Y.rows() << \" x \" << Y.cols() << std::endl;\n  std::cout << Y << std::endl;\n  std::cout << std::endl;\n}\n\n}  // namespace\n}  // namespace test\n}  // namespace gpd\n\nint main(int argc, char *argv[]) { return gpd::test::DoMain(argc, argv); }\n", "meta": {"hexsha": "a3a822a14afd29400d6cf671771d1c01cede0f7a", "size": 1422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/test_conv_layer.cpp", "max_stars_repo_name": "mjm522/gpd", "max_stars_repo_head_hexsha": "6327f20eabfcba41a05fdd2e2ba408153dc2e958", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 439.0, "max_stars_repo_stars_event_min_datetime": "2017-05-23T07:03:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:08:35.000Z", "max_issues_repo_path": "src/tests/test_conv_layer.cpp", "max_issues_repo_name": "mjm522/gpd", "max_issues_repo_head_hexsha": "6327f20eabfcba41a05fdd2e2ba408153dc2e958", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 113.0, "max_issues_repo_issues_event_min_datetime": "2017-05-23T16:52:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T02:06:19.000Z", "max_forks_repo_path": "src/tests/test_conv_layer.cpp", "max_forks_repo_name": "mjm522/gpd", "max_forks_repo_head_hexsha": "6327f20eabfcba41a05fdd2e2ba408153dc2e958", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 221.0, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:05:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T07:15:59.000Z", "avg_line_length": 30.2553191489, "max_line_length": 78, "alphanum_fraction": 0.6111111111, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5287687371890312}}
{"text": "#include <vector>\n#include <Rcpp.h>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/index/rtree.hpp>\nusing namespace Rcpp;\n#include \"landscape.h\"\n#include <vector>\n#include <algorithm>\n#include <functional>\n\nstd::mt19937 rng;\n\nvoid Resources::initResources() {\n    // generate n central items\n    std::vector<float> centreCoordX (nClusters);\n    std::vector<float> centreCoordY (nClusters);\n\n    std::uniform_real_distribution<float> item_ran_pos(0.0f, dSize);\n    std::normal_distribution<float> item_cluster_spread(0.0f, clusterSpread);\n\n    for(size_t i = 0; i < static_cast<size_t>(nClusters); i++) {\n\n        centreCoordX[i] = item_ran_pos(rng);\n        centreCoordY[i] = item_ran_pos(rng);\n\n        // also add to main set\n        coordX[i] = centreCoordX[i];\n        coordY[i] = centreCoordY[i];\n    }\n\n    // generate items around\n    for(int i = nClusters; i < nItems; i++) {\n\n        coordX[i] = (centreCoordX[(i % nClusters)] + item_cluster_spread(rng));\n        coordY[i] = (centreCoordY[(i % nClusters)] + item_cluster_spread(rng));\n\n        // wrap\n        coordX[i] = fmod(dSize + coordX[i], dSize);\n        coordY[i] = fmod(dSize + coordY[i], dSize);\n    }\n\n    // dist to set random counter value\n    std::poisson_distribution<int> distRegen(static_cast<int>(std::floor(static_cast<float>(regen_time) * 0.1)));\n    \n    // initialise rtree and set counter value\n    bgi::rtree< value, bgi::quadratic<16> > tmpRtree;\n    for (int i = 0; i < nItems; ++i)\n    {\n        point p = point(coordX[i], coordY[i]);\n        tmpRtree.insert(std::make_pair(p, i));\n\n        counter[i] = distRegen(rng);\n        // set all to available\n        available[i] = (counter[i] == 0);\n    }\n\n    std::swap(rtree, tmpRtree);\n    tmpRtree.clear();\n}\n\nvoid Resources::countAvailable() {\n    nAvailable = 0;\n    // counter set to max regeneration value on foraging\n    for (size_t i = 0; i < static_cast<size_t>(nItems); i++){\n        if(counter[i] == 0) {\n            nAvailable ++;\n        }\n    }\n}\n\nvoid Resources::regenerate() {\n    for (int i = 0; i < nItems; i++)\n    {\n        counter[i] -= (counter[i] > 0 ? 1 : 0);\n        available[i] = (counter[i] == 0);\n    }\n    // set availability\n    countAvailable();\n}\n\n/// function to export landscape as matrix\n//' Returns a test landscape.\n//'\n//' @param nItems How many items.\n//' @param landsize Size as a numeric (float).\n//' @param nClusters How many clusters, an integer value.\n//' @param clusterSpread Dispersal of items around cluster centres.\n//' @param regen_time Regeneration time, in timesteps.\n//' @return A data frame of the evolved population traits.\n// [[Rcpp::export]]\nRcpp::DataFrame get_test_landscape(\n        const int nItems, const float landsize,\n        const int nClusters, const float clusterSpread,\n        const int regen_time) {\n    \n    unsigned seed = static_cast<unsigned> (std::chrono::system_clock::now().time_since_epoch().count());\n    rng.seed(seed);\n\n    Resources food (nItems, landsize, nClusters, clusterSpread, regen_time);\n    food.initResources();\n\n    return Rcpp::DataFrame::create(\n                Rcpp::Named(\"x\") = food.coordX,\n                Rcpp::Named(\"y\") = food.coordY,\n                Rcpp::Named(\"tAvail\") = food.counter\n            );\n}\n", "meta": {"hexsha": "f7024154fab1be8a963f65a73d60a30b2d89222f", "size": 3296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/landscape.cpp", "max_stars_repo_name": "pratikunterwegs/pathomove", "max_stars_repo_head_hexsha": "be6b509442d975909bae2a46cc01d94e74e32a41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-16T11:20:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T11:20:02.000Z", "max_issues_repo_path": "src/landscape.cpp", "max_issues_repo_name": "pratikunterwegs/pathomove", "max_issues_repo_head_hexsha": "be6b509442d975909bae2a46cc01d94e74e32a41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-18T12:08:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T12:08:44.000Z", "max_forks_repo_path": "src/landscape.cpp", "max_forks_repo_name": "pratikunterwegs/pathomove", "max_forks_repo_head_hexsha": "be6b509442d975909bae2a46cc01d94e74e32a41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-18T20:29:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T20:29:28.000Z", "avg_line_length": 30.2385321101, "max_line_length": 113, "alphanum_fraction": 0.6246966019, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5287687371890312}}
{"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/cast/float_to_int_fun.hpp>\n#include <fcppt/math/box/comparison.hpp>\n#include <fcppt/math/box/object_impl.hpp>\n#include <fcppt/math/box/output.hpp>\n#include <fcppt/math/box/structure_cast.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_box_structure_cast\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef fcppt::math::box::object<\n\t\tfloat,\n\t\t2\n\t> box_f2;\n\n\ttypedef fcppt::math::box::object<\n\t\tint,\n\t\t2\n\t> box_i2;\n\n\tbox_f2 const box1(\n\t\tbox_f2::vector(\n\t\t\t1.5f,\n\t\t\t2.5f\n\t\t),\n\t\tbox_f2::dim(\n\t\t\t3.5f,\n\t\t\t4.5f\n\t\t)\n\t);\n\n\tbox_i2 const result(\n\t\tfcppt::math::box::structure_cast<\n\t\t\tbox_i2,\n\t\t\tfcppt::cast::float_to_int_fun\n\t\t>(\n\t\t\tbox1\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult,\n\t\tbox_i2(\n\t\t\tbox_i2::vector(\n\t\t\t\t1,\n\t\t\t\t2\n\t\t\t),\n\t\t\tbox_i2::dim(\n\t\t\t\t3,\n\t\t\t\t4\n\t\t\t)\n\t\t)\n\t);\n}\n", "meta": {"hexsha": "00771a0edf7f2b444cfecaf17d1fb5f72d3d02e4", "size": 1299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/box/structure_cast.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/box/structure_cast.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/box/structure_cast.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": 17.7945205479, "max_line_length": 61, "alphanum_fraction": 0.6936104696, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721305, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5287102802468739}}
{"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_SIGNUM_INCLUDE\n#define MTL_SIGNUM_INCLUDE\n\n#include <complex>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/operation/real.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl {\n\nnamespace sfunctor {\n\n    template <typename Value>\n    struct signum\n    {\n\ttypedef Value result_type;\n\n\tstatic inline Value apply(const Value& v)\n\t{\n\t    using math::zero; using math::one;\n\t    return v == zero(v) ? zero(v) : ( v < zero(v) ? -one(v) : one(v) );\n\t}\n    };\n\n    template <typename Value>\n    struct signum<std::complex<Value> >\n    {\n\ttypedef Value result_type;\n\n\tstatic inline Value apply(const std::complex<Value>& v)\n\t{\n\t    return signum<Value>::apply(mtl::real(v));\n\t}\n    };\n\n}\n\n/// Sign of scalars\n/** For complex numbers, the sign of real part is returned; subject to revision. **/\ntemplate <typename Value>\ninline typename sfunctor::signum<Value>::result_type signum(const Value& v)\n{\n\tvampir_trace<6> tracer;\n    return sfunctor::signum<Value>::apply(v);\n}\n\n\n} // namespace mtl\n\n#endif // MTL_SIGNUM_INCLUDE\n", "meta": {"hexsha": "337b6c95c37bbb4f9ccfc58f2201d245152a5bd7", "size": 1522, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/signum.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/signum.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/signum.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.78125, "max_line_length": 94, "alphanum_fraction": 0.691195795, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5287102681415673}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <k52/dsp/transform/circular_convolution.h>\n#include <k52/dsp/transform/fourier_transform.h>\n#include <k52/dsp/transform/fourier_based_circular_convolution.h>\n\n#include  <k52/common/constants.h>\n\n#include \"../boost_test_tools_extensions.h\"\n\nusing k52::common::Constants;\nusing k52::dsp::CircularConvolution;\nusing k52::dsp::ICircularConvolution;\nusing k52::dsp::IFourierTransform;\nusing k52::dsp::FourierTransform;\nusing k52::dsp::FourierBasedCircularConvolution;\n\n/**\n * Definition of test methods\n */\n\nvoid test_not_equal_size(const ICircularConvolution* convolution)\n{\n    //Prepare\n    std::vector< std::complex <double > > a(13);\n    std::vector< std::complex <double > > b(15);\n\n    //Test\n    //Check\n    BOOST_REQUIRE_THROW(convolution->EvaluateConvolution(a, b), std::runtime_error);\n}\n\nvoid test_zero(const ICircularConvolution* convolution)\n{\n    //Prepare\n    size_t N = 17;\n\n    std::vector< std::complex <double > > a(N);\n    std::vector< std::complex <double > > b(N);\n\n    //Test\n    std::vector< std::complex <double > > result = convolution->EvaluateConvolution(a, b);\n\n    //Check\n    BOOST_REQUIRE_EQUAL(result.size(), N);\n\n    for (size_t n = 0; n < N; ++n)\n    {\n        CheckComplexEqual(result[n], 0);\n    }\n}\n\nvoid test_simple_impulse(const ICircularConvolution* convolution)\n{\n    //Prepare\n    size_t N = 4;\n    std::vector< std::complex <double > > a(N);\n    a[0] = 1;\n    std::vector< std::complex <double > > b(N);\n    b[0] = 1;\n\n    //Test\n    std::vector< std::complex <double > > result = convolution->EvaluateConvolution(a, b);\n\n    //Check\n    BOOST_REQUIRE_EQUAL(result.size(), N);\n\n    for (size_t n = 0; n < N; ++n)\n    {\n        CheckComplexEqual(result[n], n == 0 ? 1 : 0);\n    }\n}\n\nvoid test_impulse(const ICircularConvolution* convolution)\n{\n    //Prepare\n    size_t N = 29;\n\n    size_t n_a = 2;\n    size_t n_b = 7;\n\n    std::vector< std::complex <double > > a(N);\n    a[n_a] = 1;\n\n    std::vector< std::complex <double > > b(N);\n    b[n_b] = 1;\n\n    //Test\n    std::vector< std::complex <double > > result = convolution->EvaluateConvolution(a, b);\n\n    //Check\n    BOOST_REQUIRE_EQUAL(result.size(), N);\n\n    for (size_t n = 0; n < N; ++n)\n    {\n        bool is_impulse_index = (n_b + n_a) == n;\n        CheckComplexEqual(result[n], is_impulse_index ? 1 : 0);\n    }\n}\n\nvoid test_constant(const ICircularConvolution* convolution)\n{\n    //Prepare\n    size_t N = 12;\n\n    std::vector< std::complex <double > > a(N, 1);\n    std::vector< std::complex <double > > b(N, 1);\n\n    //Test\n    std::vector< std::complex <double > > result = convolution->EvaluateConvolution(a, b);\n\n    //Check\n    BOOST_REQUIRE_EQUAL(result.size(), N);\n\n    for (size_t n = 0; n < N; ++n)\n    {\n        CheckComplexEqual(result[n], N);\n    }\n}\n\nvoid test_complex_harmonic(const ICircularConvolution* convolution)\n{\n    //Prepare\n    size_t N = 136;\n    size_t k0 = 17;\n\n    std::vector< std::complex <double > > complex_harmonic(N);\n    std::vector< std::complex <double > > b(N);\n\n    for (size_t n = 0; n < N; ++n)\n    {\n        complex_harmonic[n] = exp( 2 * Constants::Pi * Constants::ImaginaryUnit * (double)k0 * (double)n / (double)N);\n        b[n] = n;\n    }\n\n    std::complex <double> eigen_value = 0;\n    for (size_t n = 0; n < N; ++n)\n    {\n        //Fourier transform is eigenvalue for complex harmonic (eigenvector)\n        eigen_value += b[n] * exp(  -2 * Constants::Pi * Constants::ImaginaryUnit * (double)k0 * (double)n / (double)N);\n    }\n\n    //Test\n    std::vector< std::complex <double > > result = convolution->EvaluateConvolution(complex_harmonic, b);\n\n    //Check\n    BOOST_REQUIRE_EQUAL(result.size(), N);\n\n    for (size_t n = 0; n < N; ++n)\n    {\n        std::complex <double> out = eigen_value * complex_harmonic[n];\n        CheckComplexEqual(result[n], out);\n    }\n}\n\n/**\n * Actual tests are below\n */\n\n\nBOOST_AUTO_TEST_SUITE(circular_convolution_tests);\n\n\nstruct CircularConvolutionTestFixture\n{\n    CircularConvolution convolution;\n};\n\nBOOST_FIXTURE_TEST_SUITE(circular_convolution, CircularConvolutionTestFixture);\n\nBOOST_AUTO_TEST_CASE(not_equal_size)\n{\n    test_not_equal_size(&convolution);\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n    test_zero(&convolution);\n}\n\nBOOST_AUTO_TEST_CASE(simple_impulse)\n{\n    test_simple_impulse(&convolution);\n}\n\nBOOST_AUTO_TEST_CASE(impulse)\n{\n    test_impulse(&convolution);\n}\n\nBOOST_AUTO_TEST_CASE(constant)\n{\n    test_constant(&convolution);\n}\n\nBOOST_AUTO_TEST_CASE(complex_harmonic)\n{\n    test_complex_harmonic(&convolution);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n\n\n\nstruct FourierBasedCircularConvolutionTestFixture\n{\n    FourierBasedCircularConvolutionTestFixture() :\n            fourierBasedConvolution(IFourierTransform::shared_ptr(new FourierTransform()))\n    {\n    }\n    FourierBasedCircularConvolution fourierBasedConvolution;\n};\n\nBOOST_FIXTURE_TEST_SUITE(fourier_based_circular_convolution, FourierBasedCircularConvolutionTestFixture);\n\nBOOST_AUTO_TEST_CASE(not_equal_size)\n{\n    test_not_equal_size(&fourierBasedConvolution);\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n    test_zero(&fourierBasedConvolution);\n}\n\nBOOST_AUTO_TEST_CASE(simple_impulse_fourier)\n{\n    test_simple_impulse(&fourierBasedConvolution);\n}\n\nBOOST_AUTO_TEST_CASE(impulse)\n{\n    test_impulse(&fourierBasedConvolution);\n}\n\nBOOST_AUTO_TEST_CASE(constant)\n{\n    test_constant(&fourierBasedConvolution);\n}\n\nBOOST_AUTO_TEST_CASE(complex_harmonic)\n{\n    test_complex_harmonic(&fourierBasedConvolution);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "6837973ca2421b963868c4db37a926982007576e", "size": 5544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/unit_tests/dsp/circular_convolution.test.cpp", "max_stars_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_stars_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2016-04-14T07:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-22T22:03:20.000Z", "max_issues_repo_path": "src/unit_tests/dsp/circular_convolution.test.cpp", "max_issues_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_issues_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2016-04-05T08:49:05.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-29T07:09:00.000Z", "max_forks_repo_path": "src/unit_tests/dsp/circular_convolution.test.cpp", "max_forks_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_forks_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-16T07:53:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-12T21:31:51.000Z", "avg_line_length": 22.176, "max_line_length": 120, "alphanum_fraction": 0.6774891775, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5286945441962739}}
{"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_LAPLACIAN_SETUP_INCLUDE\n#define MTL_LAPLACIAN_SETUP_INCLUDE\n\n#include <boost/numeric/mtl/matrix/inserter.hpp>\n#include <boost/numeric/mtl/operation/set_to_zero.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace mtl { namespace matrix {\n\n/// Setup a matrix according to a Laplacian equation on a 2D-grid using a five-point-stencil\n/** Intended for sparse matrices but works also with dense matrices. Changes the size of\n    the matrix \\f$m\\cdot n\\times m\\cdot n\\f$. **/\ntemplate <typename Matrix>\ninline void laplacian_setup(Matrix& A, unsigned m, unsigned n)\n{\n    vampir_trace<3063> tracer;\n    A.change_dim(m*n, m*n);\n    set_to_zero(A);\n    inserter<Matrix>      ins(A, 5);\n\n    for (unsigned i= 0; i < m; i++)\n\tfor (unsigned j= 0; j < n; j++) {\n\t    typename Collection<Matrix>::value_type four(4.0), minus_one(-1.0);\n\t    unsigned row= i * n + j;\n\t    ins(row, row) << four;\n\t    if (j < n-1) ins(row, row+1) << minus_one;\n\t    if (i < m-1) ins(row, row+n) << minus_one;\n\t    if (j > 0) ins(row, row-1) << minus_one;\n\t    if (i > 0) ins(row, row-n) << minus_one;\n\t}\n}\n\n}} // namespace mtl::matrix\n\n#endif // MTL_LAPLACIAN_SETUP_INCLUDE\n", "meta": {"hexsha": "1bb7f145e54405e54d02a65ab08e06bb98c72df1", "size": 1609, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/matrix/laplacian_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/laplacian_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/laplacian_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.5208333333, "max_line_length": 94, "alphanum_fraction": 0.6774394034, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.528694542831707}}
{"text": "#include \"kernel.h\"\n#include \"angle.h\"\n#include \"geos/geom/Coordinate.h\"\n#include \"numericrange.h\"\n#include \"coordinate.h\"\n#include <Eigen/Dense>\n#include \"mathhelper.h\"\n\nusing namespace Ilwis;\n\n#define MAXTERMS 10\n\nMathHelper::MathHelper()\n{\n}\n\nbool MathHelper::findOblique(int iPoints,\n              const std::vector<Coordinate> &independent, const std::vector<Coordinate> &dependent, std::vector<Coefficient> &coef, bool useCols)\n\n{\n    if (iPoints < 4) return -2;\n    int N = 2 * iPoints;\n    int M = 8;\n\n    Eigen::Matrix2d A(N, M);\n    Eigen::VectorXd b(N);\n\n    for (int i = 0; i < iPoints; ++i) {\n        for (int j = 0; j < 8; ++j) {\n            A(2*i,j) = 0;\n            A(2*i+1,j) = 0;\n        }\n        A(2*i, 0) = independent[i].x;\n        A(2*i, 1) = independent[i].y;\n        A(2*i, 2) = 1;\n        A(2*i, 6) = - dependent[i].x * independent[i].x;\n        A(2*i, 7) = - dependent[i].x * independent[i].y;\n        A(2*i+1  , 3) = independent[i].x;\n        A(2*i+1  , 4) = independent[i].y;\n        A(2*i+1  , 5) = 1;\n        A(2*i+1  , 6) = - dependent[i].y * independent[i].x;\n        A(2*i+1  , 7) = - dependent[i].y * independent[i].y;\n        b(2*i) = dependent[i].x;\n        b(2*i+1  ) = dependent[i].y;\n    }\n    Eigen::VectorXd sol = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n    for (int i = 0; i < 8; ++i) {\n        double vb = sol(i);\n        if ( useCols)\n            coef[i]._x = vb;\n        else\n            coef[i]._y = vb;\n    }\n    return true;\n}\n\nbool MathHelper::findPolynom(int iTerms, int iPoints, const std::vector<Coordinate> &independent, const std::vector<Coordinate> &dependent, std::vector<Coefficient> &coef)\n{\n    double Matrix[MAXTERMS][MAXTERMS], InvMat[MAXTERMS][MAXTERMS];\n    double DU[MAXTERMS], DV[MAXTERMS], PolyProd[MAXTERMS];\n    double DX[4], DY[4];\n    double D0, D1;\n    int point, row, col, term, MaxPower, i;\n\n    const int PowerX[] = {0,1,0,1,2,0,3,2,1,0};\n    const int PowerY[] = {0,0,1,1,0,2,0,1,2,3};\n    const double MinVal = 1E-10; // was originally (in Fortran) 1e-10 and since ILWIS.1 (Pascal) it was 1e-3\n\n    //  Set no. of terms in Polynomial and Valid Order\n\n    if ( iPoints < iTerms ) return -2;\n\n    MaxPower = PowerY[iTerms-1];\n\n    //  Initialize Matrix and Dependent Vectors to Zero\n    //  and Create Identity Matrix for Inversion\n    for (term = 0; term < iTerms; ++term)\n    {\n        DU[term] = 0;\n        DV[term] = 0;\n        for (row = 0; row < iTerms; ++row)\n        {\n            Matrix[term][row] = 0;\n            InvMat[term][row] = 0;\n        }\n        InvMat[term][term] = 1;\n    }\n\n    //  Build Matrix and Dependent Vector\n    for ( point = 0; point < iPoints; ++point)\n    {\n\n        //\tSet up Products of X and Y\n        DX[0] = 1;\n        DY[0] = 1;\n        for (i = 0; i < MaxPower; ++i)\n        {\n            DX[i+1] = DX[i] * independent[point].x;\n            DY[i+1] = DY[i] * independent[point].y;\n        }\n        for (term = 0; term < iTerms; ++term)\n            PolyProd[term] = DX[PowerX[term]] * DY[PowerY[term]];\n\n        //\tIncrement First Diagonal term in Matrix\n        //\tand First Element in Both Dependent Vectors\n        Matrix[0][0] += 1;\n        DU[0] += dependent[point].x;\n        DV[0] += dependent[point].y;\n\n        //\tIncrement Next Diagonal term in Matrix\n        //\tand Next Elements in Dependent Vectors\n        for (row = 1; row < iTerms; ++row)\n        {\n            D0 = PolyProd[row];\n            Matrix[row][row] += D0 * D0;\n            DU[row] += dependent[point].x * D0;\n            DV[row] += dependent[point].y * D0;\n\n            //  Increment Remainder of row up to Diagonal term\n            //  and Copy to Corresponding column\n            for (col = 0; col < row; ++col)\n            {\n                Matrix[row][col] += D0 * PolyProd[col];\n                Matrix[col][row] = Matrix[row][col];\n            } // col\n        } // row\n    } // point\n\n    //  Start Matrix Inversion, points Next Diagonal Element Too Small ?\n    for (term = 0; term < iTerms; ++term)\n    {\n        D0 = Matrix[term][term];\n        if (abs(D0) <= MinVal) return -3;\n\n        //\tDivide This row by its Diagonal Element\n        for (row = 0; row < iTerms; ++row)\n        {\n            Matrix[term][row] /= D0;\n            InvMat[term][row] /= D0;\n        }\n\n        //\tSubtract Appropriate Multiple of This row from All Other rows\n        for (row = 0; row < iTerms; ++row)\n            if (row != term )\n            {\n                D1 = Matrix[row][term];\n                for ( col = 0; col < iTerms; ++col)\n                {\n                    Matrix[row][col] -= Matrix[term][col] * D1;\n                    InvMat[row][col] -= InvMat[term][col] * D1;\n                } // col\n            } // row\n    } // term\n\n    for (term = 0; term < MAXTERMS; ++term) {\n        coef[term]._x = 0;\n        coef[term]._y = 0;\n    }\n    //  Apply Inverse to Both Dependent Vectors and Give Coefficients\n    for (term = 0; term < iTerms; ++term)\n    {\n        D0 = 0;\n        D1 = 0;\n        for (row = 0; row < iTerms; ++row)\n        {\n            D0 += DU[row] * InvMat[term][row];\n            D1 += DV[row] * InvMat[term][row];\n        }\n        coef[term]._x = D0;\n        coef[term]._y = D1;\n    }\n    return 0;\n}\n\nNumericRange MathHelper::roundRange(double rmin, double rmax)\n{\n    double tickLimits []  = {0,0.1,0.2,0.25,0.5,1.0};\n    double range = rmax - rmin;\n    //long d =  abs(log10(range)) + 1;\n    long d =  log10(range) + 1;\n    double step = range / pow(10.0,abs(d));\n    int i = 0;\n    while(i < 6) {\n        if ( step < tickLimits[i]) {\n            step = tickLimits[i];\n            break;\n        }\n        ++i;\n    }\n    step = step * pow(10.0,d - 1);\n    double lower = step * round(rmin / step);\n    double intpart;\n    double r = modf (rmax / step , &intpart);\n    double upper = step * round(r ==0 ? intpart : 1 + intpart );\n    return NumericRange(lower, upper, step);\n}\n\ndouble MathHelper::round(double r)\n{\n    if (r < 7)\n      if (r < 1e-10)\n        return 1e-10;\n      else\n        return round(r*10)/10;\n    else if (r > 70)\n      if (r > 1e30)\n        return 1e30;\n      else\n        return round(r/10)*10;\n    else if (r < 17)\n      return 10;\n    else if (r <= 25)\n      return 20;\n    else\n      return 50;\n}\n", "meta": {"hexsha": "fc41e3c061d0108931c99f3b05520e648eb98629", "size": 6269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/util/mathhelper.cpp", "max_stars_repo_name": "ridoo/IlwisCore", "max_stars_repo_head_hexsha": "9d9837507d804a4643545a03fd40d9b4d0eaee45", "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": "core/util/mathhelper.cpp", "max_issues_repo_name": "ridoo/IlwisCore", "max_issues_repo_head_hexsha": "9d9837507d804a4643545a03fd40d9b4d0eaee45", "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": "core/util/mathhelper.cpp", "max_forks_repo_name": "ridoo/IlwisCore", "max_forks_repo_head_hexsha": "9d9837507d804a4643545a03fd40d9b4d0eaee45", "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.8894009217, "max_line_length": 171, "alphanum_fraction": 0.5043866645, "num_tokens": 2029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5286430018752597}}
{"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 \"WindowFuncs.hpp\"\n#include \"../util/FFT.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/MedianFilter.hpp\"\n#include \"../util/OnsetDetectionFuncs.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Eigen>\n#include <algorithm>\n#include <cassert>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass OnsetDetectionFunctions\n{\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXcd = Eigen::ArrayXcd;\n  using WindowTypes = WindowFuncs::WindowTypes;\n\npublic:\n  OnsetDetectionFunctions(index maxSize)\n      : mFFT(maxSize), mWindowStorage(maxSize)\n  {}\n\n  void init(index windowSize, index fftSize, index filterSize)\n  {\n    makeWindow(windowSize);\n    prevFrame = ArrayXcd::Zero(fftSize / 2 + 1);\n    prevPrevFrame = ArrayXcd::Zero(fftSize / 2 + 1);\n    mFilter.init(filterSize);\n    mFFT.resize(fftSize);\n    mDebounceCount = 1;\n    mPrevFuncVal = 0;\n    mInitialized = true;\n  }\n\n  void makeWindow(index windowSize)\n  {\n    mWindowStorage.setZero();\n    WindowFuncs::map()[mWindowType](windowSize, mWindowStorage);\n    mWindow = mWindowStorage.segment(0, windowSize);\n    mWindowSize = windowSize;\n  }\n\n  double processFrame(RealVectorView input, index function, index filterSize,\n                      index frameDelta = 0)\n  {\n    assert(mInitialized);\n    ArrayXd in = _impl::asEigen<Eigen::Array>(input);\n    double  funcVal = 0;\n    double  filteredFuncVal = 0;\n    \n    if (filterSize >= 3 &&\n        (!mFilter.initialized() || filterSize != mFilter.size()))\n      mFilter.init(filterSize);\n\n    ArrayXcd frame = mFFT.process(in.segment(0, mWindowSize) * mWindow);\n    auto     odf = static_cast<OnsetDetectionFuncs::ODF>(function);\n    if (function > 1 && function < 5 && frameDelta != 0)\n    {\n      ArrayXcd frame2 =\n          mFFT.process(in.segment(frameDelta, mWindowSize) * mWindow);\n      funcVal = OnsetDetectionFuncs::map()[odf](frame2, frame, frame);\n    }\n    else\n    {\n      funcVal =\n          OnsetDetectionFuncs::map()[odf](frame, prevFrame, prevPrevFrame);\n    }\n    if (filterSize >= 3)\n      filteredFuncVal = funcVal - mFilter.processSample(funcVal);\n    else\n      filteredFuncVal = funcVal - mPrevFuncVal;\n\n    prevPrevFrame = prevFrame;\n    prevFrame = frame;\n\n    return filteredFuncVal;\n  }\n\nprivate:\n  FFT          mFFT{1024};\n  ArrayXd      mWindowStorage;\n  ArrayXd      mWindow;\n  index        mWindowSize{1024};\n  index        mDebounceCount{1};\n  ArrayXcd     prevFrame;\n  ArrayXcd     prevPrevFrame;\n  double       mPrevFuncVal{0.0};\n  WindowTypes  mWindowType{WindowTypes::kHann};\n  MedianFilter mFilter;\n  bool         mInitialized{false};\n};\n\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "29359e2b893bc2aa29260c540f309375e775d96a", "size": 3111, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/OnsetDetectionFunctions.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/OnsetDetectionFunctions.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/OnsetDetectionFunctions.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.2818181818, "max_line_length": 77, "alphanum_fraction": 0.6830601093, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5286430002634707}}
{"text": "#include <cstdlib>\n#include <cstdio>\n#include <cmath>\n#include <fstream>\n#include <vector>\n#include <iostream>\n#include <cassert>\n#include <random>\n#include <algorithm>\n#include <Eigen>\n\nusing namespace Eigen;\nusing namespace std;\n\nconst float decay_rate = 0.12f;\nconst Vector3f amb_color = Vector3f(1.0f, 1.0f, 1.0f);\nconst float amb_coeff = 0.01f;\n\n//Vector3f bgcolor(1.0f, 1.0f, 1.0f);\nVector3f bgcolor(.0f, .0f, .0f);\n\nstd::vector<Vector3f> lightPositions = { Vector3f(0.0, 150, 20)\n\t\t\t\t\t\t\t\t\t   , Vector3f(-130.0, 60, 200)\n\t\t\t\t\t\t\t\t\t   , Vector3f(50.0, 60, 100) };\n\nfloat lcontrib = (float)((double)1.0 / (double)lightPositions.size());\n\nclass Sphere\n{\npublic:\n\tVector3f center;  // position of the sphere\n\tfloat radius;  // sphere radius\n\tVector3f surfaceColor; // surface color\n\tbool isSpecular;\n\tSphere(\n\t\tconst Vector3f &c,\n\t\tconst float &r,\n\t\tconst Vector3f &sc,\n\t\tbool sp) :\n\t\tcenter(c), radius(r), surfaceColor(sc), isSpecular(sp)\n\t{\n\t}\n\n\t// line vs. sphere intersection (note: this is slightly different from ray vs. sphere intersection!)\n\tbool intersect(const Vector3f &rayOrigin, const Vector3f &rayDirection, float &t0, float &t1) const\n\t{\n\t\tVector3f l = center - rayOrigin;\n\t\tfloat tca = l.dot(rayDirection);\n\t\tif (tca < 0) return false;\n\t\tfloat d2 = l.dot(l) - tca * tca;\n\t\tif (d2 > (radius * radius)) return false;\n\t\tfloat thc = sqrt(radius * radius - d2);\n\t\tt0 = tca - thc;\n\t\tt1 = tca + thc;\n\n\t\treturn true;\n\t}\n};\n\nVector3f diffuse(const Vector3f &L, const Vector3f &N, const Vector3f &diffuseColor, const float kd)\n{\n\treturn kd * max(L.dot(N), 0.0f)*diffuseColor * lcontrib;\n}\n\nVector3f phong(const Vector3f &L, const Vector3f &N, const Vector3f &V, const Vector3f &R, const Vector3f &diffuseColor, const Vector3f &specularColor, const float kd, const float ks, const float alpha)\n{\n\tVector3f resColor = Vector3f::Zero();\n\tresColor = diffuse(L, N, diffuseColor, .55f);\n\tresColor += specularColor * ks * pow(max(R.dot(V), 0.0f), alpha) * lcontrib;\n\treturn resColor;\n}\n\nSphere* getNearestSphere(const Vector3f &rayOrigin, const Vector3f &rayDirection, const std::vector<Sphere> &spheres, float&t0) {\n\tfloat t1 = 0, closest = 0;\n\tSphere* nearest = NULL;\n\tfor (auto sphere : spheres) {\n\t\tif (sphere.intersect(rayOrigin, rayDirection, t0, t1))\n\t\t{\n\t\t\tif (closest && closest <= t0) continue;\n\t\t\tclosest = t0;\n\t\t\tdelete nearest;\n\t\t\tnearest = new Sphere(sphere); // for some reason making a pointer directly to &sphere makes the color gray\n\t\t}\n\t}\n\tt0 = closest;\n\treturn nearest;\n}\nbool isObstructed(const Vector3f &rayOrigin, const Vector3f &rayDirection, const std::vector<Sphere> &spheres) {\n\tfloat t0 = 0, t1 = 0;\n\tfor (auto sphere : spheres) {\n\t\tif (sphere.intersect(rayOrigin, rayDirection, t0, t1))\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nVector3f trace_help(const Vector3f &rayOrigin, const Vector3f &rayDirection, const std::vector<Sphere> &spheres, int depth) {\n\tVector3f pixelColor = Vector3f::Zero();\n\tif (depth < 1) return pixelColor;\n\tdepth--;\n\tfloat t0 = 0, t1 = 0;\n\tSphere* nearest = getNearestSphere(rayOrigin, rayDirection, spheres, t0);\n\tif (!nearest) return bgcolor;\n\tVector3f bounce = (rayDirection * t0) + rayOrigin;\n\tVector3f normal = bounce - nearest->center;\n\tnormal.normalize();\n\tVector3f reflection = (2.0f * normal) * normal.dot(rayDirection) - rayDirection;\n\treflection.normalize();\n\n\tfor (auto light : lightPositions) {\n\t\tVector3f light_direction = light - bounce;\n\t\tlight_direction.normalize();\n\t\tVector3f reverse_ray_norm = -light_direction;\n\t\tif (!isObstructed(bounce, light_direction, spheres)) {\n\t\t\tpixelColor += phong(light_direction, normal, reverse_ray_norm, reflection, nearest->surfaceColor, Vector3f::Ones(), lcontrib, 5.40f, 70);\n\t\t\tpixelColor += amb_color * amb_coeff;\n\t\t}\n\t}\n\n\tif (!nearest->isSpecular) return pixelColor;\n\treturn pixelColor += (decay_rate * trace_help(bounce, -reflection, spheres, depth));\n}\n\nVector3f trace(const Vector3f &rayOrigin, const Vector3f &rayDirection, const std::vector<Sphere> &spheres)\n{\n\tint max_depth = 1;\n\treturn trace_help(rayOrigin, rayDirection, spheres, max_depth);\n}\n\n\n\nvoid render(const std::vector<Sphere> &spheres)\n{\n\tunsigned width = 640;\n\tunsigned height = 480;\n\tVector3f *image = new Vector3f[width * height];\n\tVector3f *pixel = image;\n\tfloat invWidth = 1 / float(width);\n\tfloat invHeight = 1 / float(height);\n\tfloat fov = 30;\n\tfloat aspectratio = width / float(height);\n\tfloat angle = tan(M_PI * 0.5f * fov / 180.f);\n\n\t// Trace rays\n\tfor (unsigned y = 0; y < height; ++y)\n\t{\n\t\tfor (unsigned x = 0; x < width; ++x)\n\t\t{\n\t\t\tfloat rayX = (2 * ((x + 0.5f) * invWidth) - 1) * angle * aspectratio;\n\t\t\tfloat rayY = (1 - 2 * ((y + 0.5f) * invHeight)) * angle;\n\t\t\tVector3f rayDirection(rayX, rayY, -1);\n\t\t\trayDirection.normalize();\n\t\t\t*(pixel++) = trace(Vector3f::Zero(), rayDirection, spheres);\n\t\t}\n\t}\n\n\t// Save result to a PPM image\n\tstd::ofstream ofs(\"./out007.ppm\", std::ios::out | std::ios::binary);\n\tofs << \"P6\\n\" << width << \" \" << height << \"\\n255\\n\";\n\tfor (unsigned i = 0; i < width * height; ++i)\n\t{\n\t\tconst float x = image[i](0);\n\t\tconst float y = image[i](1);\n\t\tconst float z = image[i](2);\n\n\t\tofs << (unsigned char)(std::min(float(1), x) * 255)\n\t\t\t<< (unsigned char)(std::min(float(1), y) * 255)\n\t\t\t<< (unsigned char)(std::min(float(1), z) * 255);\n\t}\n\n\tofs.close();\n\tdelete[] image;\n}\n\n\nint main(int argc, char **argv)\n{\n\tstd::vector<Sphere> spheres;\n\t// position, radius, surface color\n\tspheres.push_back(Sphere(Vector3f(0.0, -10004, -20), 10000, Vector3f(0.40, 0.40, 0.40), false));\n\tspheres.push_back(Sphere(Vector3f(0.0, 0, -20), 4, Vector3f(1.00, 0.32, 0.36), true));\n\tspheres.push_back(Sphere(Vector3f(-2.65, -2.5, -15), .5, Vector3f(0.00, 0.32, 0.9), true));\n\tspheres.push_back(Sphere(Vector3f(5.0, -1, -15), 2, Vector3f(0.90, 0.76, 0.46), true));\n\tspheres.push_back(Sphere(Vector3f(5.0, -1.7, -25), 3, Vector3f(0.65, 0.77, 0.97), true));\n\tspheres.push_back(Sphere(Vector3f(-5.5, 0.5, -13), 3, Vector3f(0.250, 0.250, 0.250), true));\n\n\trender(spheres);\n\tdouble b;\n\t//std::cin >> b;\n\treturn 0;\n}\n", "meta": {"hexsha": "a424c71392282467440017f9afa9a0b98241647f", "size": 6003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Ray Tracing/main-extra.cpp", "max_stars_repo_name": "ggstrader/Code-Samples", "max_stars_repo_head_hexsha": "fcad784673faa1dd0000b57e4527211c0b1a2c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ray Tracing/main-extra.cpp", "max_issues_repo_name": "ggstrader/Code-Samples", "max_issues_repo_head_hexsha": "fcad784673faa1dd0000b57e4527211c0b1a2c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ray Tracing/main-extra.cpp", "max_forks_repo_name": "ggstrader/Code-Samples", "max_forks_repo_head_hexsha": "fcad784673faa1dd0000b57e4527211c0b1a2c3d", "max_forks_repo_licenses": ["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.265625, "max_line_length": 202, "alphanum_fraction": 0.6746626687, "num_tokens": 1959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5286429938163139}}
{"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\n#include <Utils/Math/BSplines/BSpline.h>\n#include <Utils/Math/BSplines/ControlPolygonGenerator.h>\n#include <Utils/Math/BSplines/KnotInserter.h>\n#include <gmock/gmock.h>\n#include <Eigen/Core>\n\nusing namespace testing;\nnamespace Scine {\nnamespace Utils {\nusing namespace BSplines;\nnamespace Tests {\n\nclass ABSplineKnotInserterTest : public Test {\n public:\n  unsigned p;\n  BSpline bs;\n  KnotInserter bsKnotInserter;\n\n  void SetUp() override {\n  }\n};\n\nTEST_F(ABSplineKnotInserterTest, InsertNonExistingKnotDegree3) {\n  p = 3;\n\n  Eigen::MatrixXd data(5, 2);\n  data.row(0) = Eigen::Vector2d(1, 1);\n  data.row(1) = Eigen::Vector2d(2, 0);\n  data.row(2) = Eigen::Vector2d(3, 1);\n  data.row(3) = Eigen::Vector2d(4, 0);\n  data.row(4) = Eigen::Vector2d(5, 1);\n\n  ControlPolygonGenerator myBSplineGenerator_(data, p, true);\n  bs = myBSplineGenerator_.generateBSpline();\n  bsKnotInserter.insertKnotByReference(0.25, bs);\n\n  Eigen::VectorXd vecResult = bs.getKnotVector();\n  Eigen::MatrixXd matResult = bs.getControlPointMatrix();\n\n  // ContainerConverter::writeWithOuterBraces(vecResult);\n  // ContainerConverter::writeWithOuterBraces(matResult);\n\n  Eigen::VectorXd vecCheck(10);\n  vecCheck << 0, 0, 0, 0, 0.25, 0.5, 1, 1, 1, 1;\n  ASSERT_TRUE(vecResult.isApprox(vecCheck));\n\n  Eigen::MatrixXd matCheck(6, 2);\n  matCheck << 1, 1, 1.5, 0.5, 2.25, 0.25, 3.25, 0.75, 4, 0, 5, 1;\n  ASSERT_TRUE(matResult.isApprox(matCheck));\n}\n\n} // namespace Tests\n} // namespace Utils\n} // namespace Scine", "meta": {"hexsha": "a3eae6228be807ce8591c565192418cc69fed6fe", "size": 1688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Tests/Math/BSplines/BSplineKnotInserterTest.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/Tests/Math/BSplines/BSplineKnotInserterTest.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/Tests/Math/BSplines/BSplineKnotInserterTest.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": 27.6721311475, "max_line_length": 85, "alphanum_fraction": 0.7043838863, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.528383131670339}}
{"text": "//  Copyright (c) 2007 John Maddock\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//\r\n// This is a partial header, do not include on it's own!!!\r\n//\r\n// Contains asymptotic expansions for Bessel J(v,x) and Y(v,x)\r\n// functions, as x -> INF.\r\n//\r\n#ifndef BOOST_MATH_SF_DETAIL_BESSEL_JY_ASYM_HPP\r\n#define BOOST_MATH_SF_DETAIL_BESSEL_JY_ASYM_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/math/special_functions/factorials.hpp>\r\n\r\nnamespace boost{ namespace math{ namespace detail{\r\n\r\ntemplate <class T>\r\ninline T asymptotic_bessel_j_large_x_P(T v, T x)\r\n{\r\n   // A&S 9.2.9\r\n   T s = 1;\r\n   T mu = 4 * v * v;\r\n   T ez2 = 8 * x;\r\n   ez2 *= ez2;\r\n   s -= (mu-1) * (mu-9) / (2 * ez2);\r\n   s += (mu-1) * (mu-9) * (mu-25) * (mu - 49) / (24 * ez2 * ez2);\r\n   return s;\r\n}\r\n\r\ntemplate <class T>\r\ninline T asymptotic_bessel_j_large_x_Q(T v, T x)\r\n{\r\n   // A&S 9.2.10\r\n   T s = 0;\r\n   T mu = 4 * v * v;\r\n   T ez = 8*x;\r\n   s += (mu-1) / ez;\r\n   s -= (mu-1) * (mu-9) * (mu-25) / (6 * ez*ez*ez);\r\n   return s;\r\n}\r\n\r\ntemplate <class T>\r\ninline T asymptotic_bessel_j_large_x(T v, T x)\r\n{\r\n   // \r\n   // See http://functions.wolfram.com/BesselAiryStruveFunctions/BesselJ/06/02/02/0001/\r\n   //\r\n   // Also A&S 9.2.5\r\n   //\r\n   BOOST_MATH_STD_USING // ADL of std names\r\n   T chi = fabs(x) - constants::pi<T>() * (2 * v + 1) / 4;\r\n   return sqrt(2 / (constants::pi<T>() * x))\r\n      * (asymptotic_bessel_j_large_x_P(v, x) * cos(chi) \r\n         - asymptotic_bessel_j_large_x_Q(v, x) * sin(chi));\r\n}\r\n\r\ntemplate <class T>\r\ninline T asymptotic_bessel_y_large_x(T v, T x)\r\n{\r\n   // \r\n   // See http://functions.wolfram.com/BesselAiryStruveFunctions/BesselJ/06/02/02/0001/\r\n   //\r\n   // Also A&S 9.2.5\r\n   //\r\n   BOOST_MATH_STD_USING // ADL of std names\r\n   T chi = fabs(x) - constants::pi<T>() * (2 * v + 1) / 4;\r\n   return sqrt(2 / (constants::pi<T>() * x))\r\n      * (asymptotic_bessel_j_large_x_P(v, x) * sin(chi) \r\n         - asymptotic_bessel_j_large_x_Q(v, x) * cos(chi));\r\n}\r\n\r\ntemplate <class T>\r\ninline T asymptotic_bessel_amplitude(T v, T x)\r\n{\r\n   // Calculate the amplitude of J(v, x) and Y(v, x) for large\r\n   // x: see A&S 9.2.28.\r\n   BOOST_MATH_STD_USING\r\n   T s = 1;\r\n   T mu = 4 * v * v;\r\n   T txq = 2 * x;\r\n   txq *= txq;\r\n\r\n   s += (mu - 1) / (2 * txq);\r\n   s += 3 * (mu - 1) * (mu - 9) / (txq * txq * 8);\r\n   s += 15 * (mu - 1) * (mu - 9) * (mu - 25) / (txq * txq * txq * 8 * 6);\r\n\r\n   return sqrt(s * 2 / (constants::pi<T>() * x));\r\n}\r\n\r\ntemplate <class T>\r\nT asymptotic_bessel_phase_mx(T v, T x)\r\n{\r\n   //\r\n   // Calculate the phase of J(v, x) and Y(v, x) for large x.\r\n   // See A&S 9.2.29.\r\n   // Note that the result returned is the phase less x.\r\n   //\r\n   T mu = 4 * v * v;\r\n   T denom = 4 * x;\r\n   T denom_mult = denom * denom;\r\n\r\n   T s = -constants::pi<T>() * (v / 2 + 0.25f);\r\n   s += (mu - 1) / (2 * denom);\r\n   denom *= denom_mult;\r\n   s += (mu - 1) * (mu - 25) / (6 * denom);\r\n   denom *= denom_mult;\r\n   s += (mu - 1) * (mu * mu - 114 * mu + 1073) / (5 * denom);\r\n   denom *= denom_mult;\r\n   s += (mu - 1) * (5 * mu * mu * mu - 1535 * mu * mu + 54703 * mu - 375733) / (14 * denom);\r\n   return s;\r\n}\r\n\r\ntemplate <class T>\r\ninline T asymptotic_bessel_y_large_x_2(T v, T x)\r\n{\r\n   // See A&S 9.2.19.\r\n   BOOST_MATH_STD_USING\r\n   // Get the phase and amplitude:\r\n   T ampl = asymptotic_bessel_amplitude(v, x);\r\n   T phase = asymptotic_bessel_phase_mx(v, x);\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(ampl);\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(phase);\r\n   //\r\n   // Calculate the sine of the phase, using:\r\n   // sin(x+p) = sin(x)cos(p) + cos(x)sin(p)\r\n   //\r\n   T sin_phase = sin(phase) * cos(x) + cos(phase) * sin(x);\r\n   BOOST_MATH_INSTRUMENT_CODE(sin(phase));\r\n   BOOST_MATH_INSTRUMENT_CODE(cos(x));\r\n   BOOST_MATH_INSTRUMENT_CODE(cos(phase));\r\n   BOOST_MATH_INSTRUMENT_CODE(sin(x));\r\n   return sin_phase * ampl;\r\n}\r\n\r\ntemplate <class T>\r\ninline T asymptotic_bessel_j_large_x_2(T v, T x)\r\n{\r\n   // See A&S 9.2.19.\r\n   BOOST_MATH_STD_USING\r\n   // Get the phase and amplitude:\r\n   T ampl = asymptotic_bessel_amplitude(v, x);\r\n   T phase = asymptotic_bessel_phase_mx(v, x);\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(ampl);\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(phase);\r\n   //\r\n   // Calculate the sine of the phase, using:\r\n   // cos(x+p) = cos(x)cos(p) - sin(x)sin(p)\r\n   //\r\n   BOOST_MATH_INSTRUMENT_CODE(cos(phase));\r\n   BOOST_MATH_INSTRUMENT_CODE(cos(x));\r\n   BOOST_MATH_INSTRUMENT_CODE(sin(phase));\r\n   BOOST_MATH_INSTRUMENT_CODE(sin(x));\r\n   T sin_phase = cos(phase) * cos(x) - sin(phase) * sin(x);\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(sin_phase);\r\n   return sin_phase * ampl;\r\n}\r\n\r\n//\r\n// Various limits for the J and Y asymptotics\r\n// (the asympotic expansions are safe to use if\r\n// x is less than the limit given).\r\n// We assume that if we don't use these expansions then the\r\n// error will likely be >100eps, so the limits given are chosen\r\n// to lead to < 100eps truncation error.\r\n//\r\ntemplate <class T>\r\ninline T asymptotic_bessel_y_limit(const mpl::int_<0>&)\r\n{\r\n   // default case:\r\n   BOOST_MATH_STD_USING\r\n   return 2.25 / pow(100 * tools::epsilon<T>() / T(0.001f), T(0.2f));\r\n}\r\ntemplate <class T>\r\ninline T asymptotic_bessel_y_limit(const mpl::int_<53>&)\r\n{\r\n   // double case:\r\n   return 304 /*780*/;\r\n}\r\ntemplate <class T>\r\ninline T asymptotic_bessel_y_limit(const mpl::int_<64>&)\r\n{\r\n   // 80-bit extended-double case:\r\n   return 1552 /*3500*/;\r\n}\r\ntemplate <class T>\r\ninline T asymptotic_bessel_y_limit(const mpl::int_<113>&)\r\n{\r\n   // 128-bit long double case:\r\n   return 1245243 /*3128000*/;\r\n}\r\n\r\ntemplate <class T, class Policy>\r\nstruct bessel_asymptotic_tag\r\n{\r\n   typedef typename policies::precision<T, Policy>::type precision_type;\r\n   typedef typename mpl::if_<\r\n      mpl::or_<\r\n         mpl::equal_to<precision_type, mpl::int_<0> >,\r\n         mpl::greater<precision_type, mpl::int_<113> > >,\r\n      mpl::int_<0>,\r\n      typename mpl::if_<\r\n         mpl::greater<precision_type, mpl::int_<64> >,\r\n         mpl::int_<113>,\r\n         typename mpl::if_<\r\n            mpl::greater<precision_type, mpl::int_<53> >,\r\n            mpl::int_<64>,\r\n            mpl::int_<53>\r\n         >::type\r\n      >::type\r\n   >::type type;\r\n};\r\n\r\ntemplate <class T>\r\ninline T asymptotic_bessel_j_limit(const T& v, const mpl::int_<0>&)\r\n{\r\n   // default case:\r\n   BOOST_MATH_STD_USING\r\n   T v2 = (std::max)(T(3), T(v * v));\r\n   return v2 / pow(100 * tools::epsilon<T>() / T(2e-5f), T(0.17f));\r\n}\r\ntemplate <class T>\r\ninline T asymptotic_bessel_j_limit(const T& v, const mpl::int_<53>&)\r\n{\r\n   // double case:\r\n   T v2 = (std::max)(T(3), T(v * v));\r\n   return v2 * 33 /*73*/;\r\n}\r\ntemplate <class T>\r\ninline T asymptotic_bessel_j_limit(const T& v, const mpl::int_<64>&)\r\n{\r\n   // 80-bit extended-double case:\r\n   T v2 = (std::max)(T(3), T(v * v));\r\n   return v2 * 121 /*266*/;\r\n}\r\ntemplate <class T>\r\ninline T asymptotic_bessel_j_limit(const T& v, const mpl::int_<113>&)\r\n{\r\n   // 128-bit long double case:\r\n   T v2 = (std::max)(T(3), T(v * v));\r\n   return v2 * 39154 /*85700*/;\r\n}\r\n\r\ntemplate <class T, class Policy>\r\nvoid temme_asyptotic_y_small_x(T v, T x, T* Y, T* Y1, const Policy& pol)\r\n{\r\n   T c = 1;\r\n   T p = (v / boost::math::sin_pi(v, pol)) * pow(x / 2, -v) / boost::math::tgamma(1 - v, pol);\r\n   T q = (v / boost::math::sin_pi(v, pol)) * pow(x / 2, v) / boost::math::tgamma(1 + v, pol);\r\n   T f = (p - q) / v;\r\n   T g_prefix = boost::math::sin_pi(v / 2, pol);\r\n   g_prefix *= g_prefix * 2 / v;\r\n   T g = f + g_prefix * q;\r\n   T h = p;\r\n   T c_mult = -x * x / 4;\r\n\r\n   T y(c * g), y1(c * h);\r\n\r\n   for(int k = 1; k < policies::get_max_series_iterations<Policy>(); ++k)\r\n   {\r\n      f = (k * f + p + q) / (k*k - v*v);\r\n      p /= k - v;\r\n      q /= k + v;\r\n      c *= c_mult / k;\r\n      T c1 = pow(-x * x / 4, k) / factorial<T>(k, pol);\r\n      g = f + g_prefix * q;\r\n      h = -k * g + p;\r\n      y += c * g;\r\n      y1 += c * h;\r\n      if(c * g / tools::epsilon<T>() < y)\r\n         break;\r\n   }\r\n\r\n   *Y = -y;\r\n   *Y1 = (-2 / x) * y1;\r\n}\r\n\r\ntemplate <class T, class Policy>\r\nT asymptotic_bessel_i_large_x(T v, T x, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING  // ADL of std names\r\n   T s = 1;\r\n   T mu = 4 * v * v;\r\n   T ex = 8 * x;\r\n   T num = mu - 1;\r\n   T denom = ex;\r\n\r\n   s -= num / denom;\r\n\r\n   num *= mu - 9;\r\n   denom *= ex * 2;\r\n   s += num / denom;\r\n\r\n   num *= mu - 25;\r\n   denom *= ex * 3;\r\n   s -= num / denom;\r\n\r\n   // Try and avoid overflow to the last minute:\r\n   T e = exp(x/2);\r\n\r\n   s = e * (e * s / sqrt(2 * x * constants::pi<T>()));\r\n\r\n   return (boost::math::isfinite)(s) ? \r\n      s : policies::raise_overflow_error<T>(\"boost::math::asymptotic_bessel_i_large_x<%1%>(%1%,%1%)\", 0, pol);\r\n}\r\n\r\n}}} // namespaces\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "b4ba385f8328e9251022a6b3c3f7b194a62599a3", "size": 8819, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/math/special_functions/detail/bessel_jy_asym.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/math/special_functions/detail/bessel_jy_asym.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/math/special_functions/detail/bessel_jy_asym.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": 27.9082278481, "max_line_length": 111, "alphanum_fraction": 0.5713799751, "num_tokens": 2949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5283831223536511}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n\nusing namespace Eigen;\n\nint main(){\n    using std::cout;\n    using std::endl;\n    using std::vector;\n\n    MatrixXd X = MatrixXd::Zero(3,3);\n    MatrixXd Y = MatrixXd::Zero(3,1);\n\n    X << 1,2,3, 4,5,6, 7,8,9;\n    Y << 2, 0, 1;\n\n    vector<int> row_idx{0,1,2};\n    vector<int> col_idx{2,0,1};\n\n    for(int i=0; i<3; i++){\n        cout << X(i, (int)Y(i)) << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}", "meta": {"hexsha": "a9777eb2875400c17fdc6c3939bbfdc3d88013e6", "size": 463, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/check_eigen_index.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/check_eigen_index.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/check_eigen_index.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.1481481481, "max_line_length": 39, "alphanum_fraction": 0.5269978402, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5283380980333734}}
{"text": "#ifndef nomad__src__autodiff__third_order_hpp\n#define nomad__src__autodiff__third_order_hpp\n\n#include <iomanip>\n#include <string>\n#include <Eigen/Core>\n\n#include <src/var/var.hpp>\n#include <src/autodiff/first_order.hpp>\n#include <src/autodiff/second_order.hpp>\n\nnamespace nomad {\n\n  template<class T_var>\n  void third_order_forward_val(const T_var& v) {\n    for (nomad_idx_t i = 1; i <= v.node(); ++i)\n      var_nodes_[i].third_order_forward_val();\n  }\n  \n  template<class T_var>\n  void third_order_reverse_adj(const T_var& v) {\n    var_nodes_[v.node()].third_grad() = 0;\n    var_nodes_[v.node()].fourth_grad() = 0;\n    for (nomad_idx_t i = v.node(); i > 0; --i)\n      var_nodes_[i].third_order_reverse_adj();\n  }\n\n  template <typename F>\n  typename std::enable_if<is_var<typename F::var_type>::value && F::var_type::order() >= 3, void >::type\n  grad_hessian(const F& functional,\n               const Eigen::VectorXd& x,\n               double& f,\n               Eigen::VectorXd& g,\n               Eigen::MatrixXd& H,\n               Eigen::MatrixXd& grad_H) {\n    \n    reset();\n    \n    eigen_idx_t d = x.size();\n    \n    try {\n      \n      auto f_var = functional(x);\n      \n      f = f_var.first_val();\n      \n      // First-order\n      first_order_reverse_adj(f_var);\n      \n      for (eigen_idx_t i = 0; i < d; ++i)\n      g(i) = var_nodes_[i + 1].first_grad();\n      \n      Eigen::VectorXd v(d);\n      \n      for (eigen_idx_t i = 0; i < d; ++i) {\n        \n        // Second-order\n        for (eigen_idx_t j = 0; j < d; ++j)\n        var_nodes_[j + 1].second_val() = static_cast<double>(i == j);\n        \n        second_order_forward_val(f_var);\n        second_order_reverse_adj(f_var);\n        \n        for (Eigen::internal::traits<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> >::Index j = 0; j < d; ++j)\n        v(j) = var_nodes_[j + 1].second_grad();\n        \n        H.col(i) = v;\n        \n        // Third-order\n        for (eigen_idx_t j = 0; j < d; ++j)\n        var_nodes_[j + 1].fourth_val() = 0;\n        \n        for (eigen_idx_t k = 0; k <= i; ++k) {\n          \n          for (eigen_idx_t j = 0; j < d; ++j)\n          var_nodes_[j + 1].third_val() = static_cast<double>(k == j);\n          \n          third_order_forward_val(f_var);\n          \n          for (eigen_idx_t j = 0; j < d; ++j)\n          v(j) = var_nodes_[j + 1].fourth_grad();\n          \n          third_order_reverse_adj(f_var);\n          \n          for (eigen_idx_t j = 0; j < d; ++j)\n          v(j) = var_nodes_[j + 1].fourth_grad();\n          \n          grad_H.block(0, i * d, d, d).col(k) = v;\n          grad_H.block(0, k * d, d, d).col(i) = v;\n          \n        }\n        \n      }\n      \n      reset();\n      \n    } catch (nomad_error& e) {\n      reset();\n      throw e;\n    }\n    \n  }\n  \n  template <typename F>\n  void grad_hessian(const F& functional,\n                    const Eigen::VectorXd& x,\n                    Eigen::MatrixXd& grad_H) {\n    double f;\n    Eigen::VectorXd g(x.size());\n    Eigen::MatrixXd H(x.size(), x.size());\n    grad_hessian(functional, x, f, g, H, grad_H);\n  }\n  \n  template <typename F>\n  typename std::enable_if<is_var<typename F::var_type>::value && F::var_type::order() >= 2, void >::type\n  finite_diff_grad_hessian(const F& functional,\n                           const Eigen::VectorXd& x,\n                           Eigen::MatrixXd& grad_H,\n                           const double epsilon = 1e-6) {\n    eigen_idx_t d = x.size();\n    \n    Eigen::VectorXd x_dynam(x);\n    Eigen::MatrixXd H_diff(d, d);\n    Eigen::MatrixXd H_auto(d, d);\n    \n    for (eigen_idx_t k = 0; k < d; ++k) {\n      \n      H_diff.setZero();\n      \n      x_dynam(k) += epsilon;\n      hessian(functional, x_dynam, H_auto);\n      H_diff += H_auto;\n      \n      x_dynam(k) -= 2.0 * epsilon;\n      hessian(functional, x_dynam, H_auto);\n      H_diff -= H_auto;\n      \n      x_dynam(k) += epsilon;\n      H_diff /= 2.0 * epsilon;\n      \n      grad_H.block(0, k * d, d, d) = H_diff;\n      \n    }\n    \n  }\n  \n  template <typename F>\n  void test_grad_hessian(const F& functional,\n                         const Eigen::VectorXd& x,\n                         const double epsilon = 1e-6) {\n    \n    eigen_idx_t d = x.size();\n    \n    Eigen::MatrixXd auto_grad_H(d, d * d);\n    try {\n      grad_hessian(functional, x, auto_grad_H);\n    } catch (nomad_error& e) {\n      std::cout << \"Cannot compute Hessian Gradient Test\" << std::endl;\n      throw e;\n    }\n    \n    Eigen::MatrixXd diff_grad_H(d, d * d);\n    try {\n      finite_diff_grad_hessian(functional, x, diff_grad_H, epsilon);\n    } catch (nomad_error& e) {\n      std::cout << \"Cannot compute Hessian Gradient Test\" << std::endl;\n      throw e;\n    }\n    \n    std::cout.precision(6);\n    int width = 12;\n    int n_column = 6;\n    \n    std::cout << \"Hessian Gradient Test:\" << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"Component\"\n              << std::setw(width) << std::left << \"Row\"\n              << std::setw(width) << std::left << \"Column\"\n              << std::setw(width) << std::left << \"Automatic\"\n              << std::setw(width) << std::left << \"Finite\"\n              << std::setw(width) << std::left << \"Delta /\"\n              << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"(i)\"\n              << std::setw(width) << std::left << \"(j)\"\n              << std::setw(width) << std::left << \"(k)\"\n              << std::setw(width) << std::left << \"Derivative\"\n              << std::setw(width) << std::left << \"Difference\"\n              << std::setw(width) << std::left << \"Stepsize^{2}\"\n              << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    \n    for (eigen_idx_t k = 0; k < d; ++k) {\n      for (eigen_idx_t i = 0; i < d; ++i) {\n        for (eigen_idx_t j = 0; j < d; ++j) {\n          std::cout << \"    \"\n                    << std::setw(width) << std::left << k\n                    << std::setw(width) << std::left << i\n                    << std::setw(width) << std::left << j\n                    << std::setw(width) << std::left\n                    << auto_grad_H.block(0, k * d, d, d)(i, j)\n                    << std::setw(width) << std::left\n                    << diff_grad_H.block(0, k * d, d, d)(i, j)\n                    << std::setw(width) << std::left\n                    << (auto_grad_H.block(0, k * d, d, d)(i, j) - diff_grad_H.block(0, k * d, d, d)(i, j))\n                       / (epsilon * epsilon)\n                    << std::endl;\n        }\n      }\n    }\n    \n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << std::endl;\n    \n  }\n  \n  template <typename F>\n  typename std::enable_if<is_var<typename F::var_type>::value && F::var_type::order() >= 3, void >::type\n  grad_trace_matrix_times_hessian(const F& functional,\n                                  const Eigen::VectorXd& x,\n                                  const Eigen::MatrixXd& M,\n                                  double& f,\n                                  Eigen::VectorXd& g,\n                                  Eigen::MatrixXd& H,\n                                  Eigen::VectorXd& grad_trace_m_times_h) {\n    \n    reset();\n    \n    eigen_idx_t d = x.size();\n    \n    try {\n      \n      auto f_var = functional(x);\n      \n      f = f_var.first_val();\n      \n      // First-order\n      first_order_reverse_adj(f_var);\n      \n      for (eigen_idx_t i = 0; i < d; ++i)\n      g(i) = var_nodes_[i + 1].first_grad();\n      \n      Eigen::VectorXd v(d);\n      grad_trace_m_times_h.setZero();\n      \n      for (eigen_idx_t i = 0; i < d; ++i) {\n        \n        // Second-order\n        for (eigen_idx_t j = 0; j < d; ++j)\n        var_nodes_[j + 1].second_val() = static_cast<double>(i == j);\n        \n        second_order_forward_val(f_var);\n        second_order_reverse_adj(f_var);\n        \n        for (eigen_idx_t j = 0; j < d; ++j)\n        v(j) = var_nodes_[j + 1].second_grad();\n        \n        H.col(i) = v;\n        \n        // Third-order\n        for (eigen_idx_t j = 0; j < d; ++j)\n        var_nodes_[j + 1].fourth_val() = 0;\n        \n        for (eigen_idx_t j = 0; j < d; ++j)\n        var_nodes_[j + 1].third_val() = M(j, i);\n        \n        third_order_forward_val(f_var);\n        third_order_reverse_adj(f_var);\n        \n        for (eigen_idx_t j = 0; j < d; ++j)\n        v(j) = var_nodes_[j + 1].fourth_grad();\n        \n        grad_trace_m_times_h += v;\n        \n      }\n      \n      reset();\n      \n    } catch (nomad_error& e) {\n      reset();\n      throw e;\n    }\n    \n  }\n  \n  template <typename F>\n  void grad_trace_matrix_times_hessian(F& functional,\n                                       const Eigen::VectorXd& x,\n                                       const Eigen::MatrixXd& M,\n                                       Eigen::VectorXd& grad_trace_m_times_h) {\n    double f;\n    Eigen::VectorXd g(x.size());\n    Eigen::MatrixXd H(x.size(), x.size());\n    grad_trace_matrix_times_hessian(functional, x, M, f, g, H, grad_trace_m_times_h);\n  }\n  \n  template <typename F>\n  void test_grad_trace_matrix_times_hessian(const F& functional,\n                                            const Eigen::VectorXd& x,\n                                            const Eigen::MatrixXd& M) {\n    \n    eigen_idx_t d = x.size();\n    Eigen::MatrixXd grad_hessian_auto(d, d * d);\n    try {\n      grad_hessian(functional, x, grad_hessian_auto);\n    } catch (nomad_error& e) {\n      std::cout << \"Cannot compute Gradient of Trace Matrix Times Hessian Test\" << std::endl;\n      throw e;\n    }\n    \n    Eigen::VectorXd grad_trace_m_times_h = Eigen::VectorXd::Zero(d);\n    \n    for (eigen_idx_t i = 0; i < d; ++i) {\n      grad_trace_m_times_h(i) = 0;\n      for (eigen_idx_t j = 0; j < d; ++j)\n        grad_trace_m_times_h(i) += grad_hessian_auto.block(0, i * d, d, d).col(j).dot(M.row(j));\n    }\n    \n    Eigen::VectorXd grad_trace_m_times_h_auto(x.size());\n    try {\n      grad_trace_matrix_times_hessian(functional, x, M, grad_trace_m_times_h_auto);\n    } catch (nomad_error& e) {\n      std::cout << \"Cannot compute Gradient of Trace Matrix Times Hessian Test\" << std::endl;\n      throw e;\n    }\n    \n    std::cout.precision(6);\n    int width = 12;\n    int n_column = 3;\n    \n    std::cout << \"Gradient of Trace Matrix Times Hessian Test:\" << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"Component\"\n              << std::setw(width) << std::left << \"Automatic\"\n              << std::setw(width) << std::left << \"Exact\"\n              << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"(i)\"\n              << std::setw(width) << std::left << \"Derivative\"\n              << std::setw(width) << std::left << \"\"\n              << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    \n    for (eigen_idx_t i = 0; i < d; ++i) {\n      std::cout << \"    \"\n                << std::setw(width) << std::left << i\n                << std::setw(width) << std::left << grad_trace_m_times_h_auto(i)\n                << std::setw(width) << std::left << grad_trace_m_times_h(i)\n                << std::endl;\n    }\n    \n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << std::endl;\n    \n  }\n  \n}\n\n#endif\n", "meta": {"hexsha": "5d9ff4b204fe05b97ac05639ad06136283911fbb", "size": 11811, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/autodiff/third_order.hpp", "max_stars_repo_name": "stan-dev/nomad", "max_stars_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-12-11T20:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T18:59:58.000Z", "max_issues_repo_path": "src/autodiff/third_order.hpp", "max_issues_repo_name": "stan-dev/nomad", "max_issues_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-12-15T08:12:01.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-17T01:36:56.000Z", "max_forks_repo_path": "src/autodiff/third_order.hpp", "max_forks_repo_name": "stan-dev/nomad", "max_forks_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-10-13T17:40:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T19:17:51.000Z", "avg_line_length": 32.0951086957, "max_line_length": 116, "alphanum_fraction": 0.4843789688, "num_tokens": 3245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5283380916779915}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/common/transforms.h>\n\nusing namespace std;\nusing namespace pcl;\nusing namespace Eigen;\n\ntypedef pcl::PointXYZRGB PointType;\nconst static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, \", \", \"\\n\");\n\ntemplate<typename DataType>\nEigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic> load_csv(const std::string& path)\n{\n\tstd::ifstream indata;\n\tindata.open(path);\n\tstd::string line;\n\tstd::vector<DataType> values;\n\tunsigned int rows = 0;\n\twhile (std::getline(indata, line))\n\t{\n\t\tstd::stringstream lineStream(line);\n\t\tstd::string cell;\n\t\twhile (std::getline(lineStream, cell, ','))\n\t\t{\n\t\t\tvalues.push_back(std::stod(cell));\n\t\t}\n\t\t++rows;\n\t}\n\treturn Eigen::Map<const Eigen::Matrix<typename Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic>::Scalar, Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic>::RowsAtCompileTime, Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic>::ColsAtCompileTime, Eigen::RowMajor>>(values.data(), rows, values.size() / rows);\n}\n\nint main(int argc, char** argv)\n{\n\tstring master = \"master1_pre.pcd\";\n\tstring sub1 = \"sub1_pre.pcd\";\n\tstring sub2 = \"sub2_pre.pcd\";\n\n\t//point cloud\n\tpcl::PointCloud<PointType>::Ptr cloud(new PointCloud<PointType>);\n\tpcl::PointCloud<PointType>::Ptr cloud_master(new PointCloud<PointType>);\n\tpcl::PointCloud<PointType>::Ptr cloud_sub1(new PointCloud<PointType>);\n\tpcl::PointCloud<PointType>::Ptr cloud_sub2(new PointCloud<PointType>);\n\t\n\t//read point cloud\n\tpcl::PCDReader reader;\n\tcout << \"reading cloud master\" << endl;\n\treader.read<PointType>(master, *cloud_master);\n\tcout << \"reading cloud sub1\" << endl;\n\treader.read<PointType>(sub1, *cloud_sub1);\n\tcout << \"reading cloud sub2\" << endl;\n\treader.read<PointType>(sub2, *cloud_sub2);\n\n\t//read csv\n\tcout << \"loading csv\" << endl;\n\tEigen::Matrix4d init_transformation_sub1;\n\tEigen::Matrix4d init_transformation_sub2;\n\tinit_transformation_sub1 = load_csv<double>(\"matrix_optimal1.csv\");\n\tinit_transformation_sub2 = load_csv<double>(\"matrix_optimal2.csv\");\n\n\t//transform point cloud\n\ttransformPointCloud(*cloud_sub1, *cloud_sub1, init_transformation_sub1, true);\n\ttransformPointCloud(*cloud_sub2, *cloud_sub2, init_transformation_sub2, true);\n\n\t*cloud = *cloud_master + *cloud_sub1;\n\t*cloud += *cloud_sub2;\n\t//save merge cloud point;\n\tpcl::PCDWriter writer;\n\tcout << \"saving merge cloud...\" << endl;\n\twriter.write<PointType>(\"three_merge.pcd\", *cloud);\n\n\t// PCL Visualizer\n\tboost::shared_ptr<pcl::visualization::PCLVisualizer> viewer(new pcl::visualization::PCLVisualizer(\"Point Cloud Viewer\"));\n\tviewer->addPointCloud(cloud, \"cloud\");\n\tviewer->spinOnce(6000000);\n\n\treturn 0;\n\n}", "meta": {"hexsha": "ed9d83c278275662d1ac68be0ccdc56361e062e9", "size": 2888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Calibration/three_merge.cpp", "max_stars_repo_name": "libChan/K4aGrabber", "max_stars_repo_head_hexsha": "04693196eb8a80f3165ffdf7bc436a136982c3bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Calibration/three_merge.cpp", "max_issues_repo_name": "libChan/K4aGrabber", "max_issues_repo_head_hexsha": "04693196eb8a80f3165ffdf7bc436a136982c3bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Calibration/three_merge.cpp", "max_forks_repo_name": "libChan/K4aGrabber", "max_forks_repo_head_hexsha": "04693196eb8a80f3165ffdf7bc436a136982c3bd", "max_forks_repo_licenses": ["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.4494382022, "max_line_length": 326, "alphanum_fraction": 0.7382271468, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5283380884189699}}
{"text": "#include \"mapping/LocalBA.h\"\n#include <Eigen/SVD>\n#include \"types/Frame.h\"\n#include \"types/MapPoint.h\"\n#include \"camera/CameraModel.h\"\n#include \"matchers/matcher.h\"\n\n#include \"g2o/core/sparse_optimizer.h\"\n#include \"g2o/core/block_solver.h\"\n#include \"g2o/core/solver.h\"\n#include \"g2o/core/robust_kernel_impl.h\"\n#include \"g2o/core/optimization_algorithm_levenberg.h\"\n#include \"g2o/core/optimization_algorithm_gauss_newton.h\"\n#include \"g2o/solvers/cholmod/linear_solver_cholmod.h\"\n#include \"g2o/solvers/dense/linear_solver_dense.h\"\n#include \"g2o/types/sba/types_six_dof_expmap.h\"\n#include \"g2o/solvers/structure_only/structure_only_solver.h\"\n#include \"g2o/stuff/sampler.h\"\n#include<suitesparse/cholmod.h>\n#include <opencv2/opencv.hpp>\n\nnamespace TRACKING_BENCH\n{\n    Eigen::Vector3f LocalBA::LinearTriangle(\n            const Eigen::Vector2f& p0,\n            const Eigen::Vector2f& p1,\n            const Eigen::Matrix4f& Tcw0,\n            const Eigen::Matrix4f& Tcw1)\n    {\n        Eigen::Vector3f result;\n        Eigen::Matrix4f design_matrix = Eigen::Matrix4f::Zero();\n        design_matrix.row(0) = p0[0] * Tcw0.row(2) - Tcw0.row(0);\n        design_matrix.row(1) = p0[1] * Tcw0.row(2) - Tcw0.row(1);\n        design_matrix.row(2) = p1[0] * Tcw1.row(2) - Tcw1.row(0);\n        design_matrix.row(3) = p1[1] * Tcw1.row(2) - Tcw1.row(1);\n\n        Eigen::Vector4f point;\n        point = design_matrix.jacobiSvd(Eigen::ComputeFullV).matrixV().rightCols<1>();\n\n        result(0) = point(0) / point(3);\n        result(1) = point(1) / point(3);\n        result(2) = point(2) / point(3);\n    }\n\n\n    std::vector<float> LocalBA::AddMapPointsByStereo(const std::shared_ptr<Frame>& current_frame,\n                                                     const std::shared_ptr<Frame>& stereo_frame,\n                                                     const float bf, const float fx)\n    {\n        const size_t N = (int)current_frame->GetKeys().size();\n        std::vector<float> Depth(N, -1.0f);\n        std::shared_ptr<Matcher> matcher = std::make_shared<Matcher>();\n        std::vector<cv::Point2f> pts;\n        auto matches = matcher->searchByOPFlow(stereo_frame, current_frame, pts, true, true);\n\n        cv::Mat show = current_frame->GetImagePyramid()[0].clone();\n        cv::cvtColor(show, show, CV_GRAY2BGR);\n        for (auto& m:matches)\n        {\n            auto left_id = m.trainIdx;\n            auto right_id = m.queryIdx;\n            auto left_pt = current_frame->GetKey(left_id);\n            auto right_pt = pts.at(right_id);\n            cv::line(show, left_pt->kp.pt, right_pt, cv::Scalar(0,0,255),4);\n            Depth[left_id] = bf / fabsf(pts.at(right_id).x - current_frame->GetKey(left_id)->kp.pt.x);\n        }\n        cv::imshow(\"stereo\", show);\n        return Depth;\n/*\n        // old\n        std::vector<cv::DMatch> matches;\n\n        const size_t N = (int)current_frame->GetKeys().size();\n        std::vector<float> Depth(N, -1.0f);\n\n        const int thORBDist = 75;\n        const int nRows = current_frame->GetImagePyramid().at(0).rows;\n\n        std::vector<std::vector<std::size_t>> vRowIndices(nRows, std::vector<size_t>());\n        for (int i=0;i < nRows; i++)\n            vRowIndices.reserve(200);\n\n        // Assign keyPoints to row table\n        const size_t Nr = stereo_frame->GetKeys().size();\n        for (size_t iR = 0; iR < Nr; iR ++)\n        {\n            const float &kpY = stereo_frame->GetKey(iR)->px.y();\n            const float r = 2.f * current_frame->GetInverseScaleFactors().at(stereo_frame->GetKey(iR)->kp.octave);\n            const int max_r = ceil(kpY + r);\n            const int min_r = floor(kpY - r);\n\n            for(int yi = min_r; yi <= max_r; yi ++)\n                vRowIndices[yi].push_back(iR);\n        }\n\n        // set limits for search\n        const float minZ = bf / fx;\n        const float minD = 0;\n        const float maxD = bf/ minZ;\n\n        std::vector<std::pair<int, int>> vDistIdx;\n        vDistIdx.reserve(N);\n        cv::Mat show = current_frame->GetImagePyramid()[0].clone();\n        cv::cvtColor(show, show, CV_GRAY2BGR);\n\n        for ( size_t iL=0; iL<N; iL ++)\n        {\n            const int& levelL = current_frame->GetKey(iL)->kp.octave;\n            const float& vL = current_frame->GetKey(iL)->px.y();\n            const float& uL = current_frame->GetKey(iL)->px.x();\n\n\n            const std::vector<size_t>& vCandidates = vRowIndices[(size_t)vL];\n\n            if(vCandidates.empty())\n                continue;\n\n            const float minU = 0;//uL - maxD;\n            const float maxU = 100000;//uL - minD;\n\n            if (maxU < 0)\n                continue;\n\n            int bestDist0 = INT_MAX;\n            size_t bestIdxR0 = 0;\n\n            const cv::Mat& dL = current_frame->GetDescriptor((int)iL);\n\n            for (unsigned long iR : vCandidates)\n            {\n                const cv::KeyPoint& kpR = stereo_frame->GetKey(iR)->kp;\n                if(kpR.octave < levelL -1 || kpR.octave > levelL + 1)\n                    continue;\n\n                const float& uR = kpR.pt.x;\n\n                if (uR >= minU && uR <= maxU)\n                {\n                    const cv::Mat& dR = stereo_frame->GetDescriptor((int)iR);\n                    const int dist = Matcher::DescriptorDistance(dL, dR);\n                    if(dist < bestDist0 && dist > 0)\n                    {\n                        bestDist0 = dist;\n                        bestIdxR0 = iR;\n                    }\n                }\n            }\n            // subpixel match by correlation\n            if (bestDist0 < 30)//thORBDist)\n            {\n                static int cnt = 0;\n                if(cnt == 10)\n                {\n                    for(auto c:vCandidates)\n                    {\n                        cv::Point pt(stereo_frame->GetKey(c)->kp.pt);\n                        cv::circle(show, pt, 1, cv::Scalar(255, 0,0),4);\n                    }\n                }\n                cnt ++;\n                cv::DMatch m;\n                m.queryIdx = iL;\n                m.trainIdx = bestIdxR0;\n                m.distance = bestDist0;\n                matches.emplace_back(m);\n\n                auto left_pt = current_frame->GetKey(m.queryIdx);\n                auto right_pt = stereo_frame->GetKey(m.trainIdx);\n                if (abs(left_pt->kp.pt.x - right_pt->kp.pt.x) > 0)\n                    Depth[iL]= bf/abs(left_pt->kp.pt.x - right_pt->kp.pt.x);\n                else\n                    Depth[iL] = -1;\n//                const float uR0 = stereo_frame->GetKey(bestIdxR0)->px.x();\n//                const float scaleFactor = current_frame->GetScaleFactors().at(levelL);\n//\n//                const float scaled_uL = round(current_frame->GetKey(iL)->kp.pt.x * scaleFactor);\n//                const float scaled_vL = round(current_frame->GetKey(iL)->kp.pt.y * scaleFactor);\n//                const float scaled_uR0 = round(uR0 * scaleFactor);\n//\n//\n//                // sliding window search\n//                const int w = 5;\n//                if(scaled_vL - w < 0 || scaled_uL-w < 0)\n//                    continue;\n//                cv::Mat IL = current_frame->GetImagePyramid().at(levelL).rowRange(scaled_vL-w, scaled_vL+w+1).colRange(scaled_uL-w, scaled_uL+w+1);\n//                IL.convertTo(IL, CV_32F);\n//                IL = IL - IL.at<float>(w, w) * cv::Mat::ones(IL.rows, IL.cols, CV_32F);\n//\n//                int bestDist = INT_MAX;\n//                int bestincR = 0;\n//                const int L = 5;\n//                std::vector<float> vDists;\n//                vDists.resize(2*L + 1);\n//\n//                const float iniu = scaled_uR0 - L -w;\n//                const float endu = scaled_uR0 + L + w + 1;\n//                if(iniu < 0 || endu >= stereo_frame->GetImagePyramid().at(levelL).cols)\n//                    continue;\n//\n//                for(int incR=-L; incR<=+L; incR++)\n//                {\n//                    cv::Mat IR = stereo_frame->GetImagePyramid()[levelL].rowRange(scaled_vL-w,scaled_vL+w+1).colRange(scaled_uR0+incR-w,scaled_uR0+incR+w+1);\n//                    IR.convertTo(IR,CV_32F);\n//                    IR = IR - IR.at<float>(w,w) *cv::Mat::ones(IR.rows,IR.cols,CV_32F);\n//\n//                    float dist = cv::norm(IL,IR,cv::NORM_L1);\n//                    if(dist<bestDist)\n//                    {\n//                        bestDist =  dist;\n//                        bestincR = incR;\n//                    }\n//\n//                    vDists[L+incR] = dist;\n//                }\n//\n//                if(bestincR==-L || bestincR==L)\n//                    continue;\n//\n//                // Sub-pixel match (Parabola fitting)\n//                const float dist1 = vDists[L+bestincR-1];\n//                const float dist2 = vDists[L+bestincR];\n//                const float dist3 = vDists[L+bestincR+1];\n//\n//                const float deltaR = (dist1-dist3)/(2.0f*(dist1+dist3-2.0f*dist2));\n//\n//                if(deltaR<-1 || deltaR>1)\n//                    continue;\n//\n//                // Re-scaled coordinate\n//                float bestuR = current_frame->GetInverseScaleFactors().at(levelL)*((float)scaled_uR0+(float)bestincR+deltaR);\n//\n//                float disparity = (uL-bestuR);\n//\n//                if(disparity>=minD && disparity<maxD)\n//                {\n//                    if(disparity<=0)\n//                    {\n//                        disparity=0.01;\n//                        bestuR = uL-0.01;\n//                    }\n//\n//\n//                    Depth[iL]= bf/disparity;\n//                    vDistIdx.push_back(pair<int,int>(bestDist,iL));\n//                }\n            }\n        }\n//        sort(vDistIdx.begin(), vDistIdx.end());\n//        const auto median = (float)vDistIdx[(int)(vDistIdx.size()/2)].first;\n//        const float thDist = 1.5f*1.4f*median;\n//\n//        for (size_t i=vDistIdx.size()-1; i>=0;i --)\n//        {\n//            if ((float)vDistIdx[i].first < thDist)\n//                break;\n//            else\n//            {\n//                Depth[i] = -1;\n//            }\n//        }\n\n\n        std::vector<cv::KeyPoint> kps1, kps2;\n        for (auto& kp:current_frame->GetKeys())\n        {\n            kps1.emplace_back(kp->kp);\n        }\n        for (auto& kp:stereo_frame->GetKeys())\n        {\n            kps2.emplace_back(kp->kp);\n        }\n\n        for (int i = 10;i < matches.size(); i+= 10000)\n        {\n            auto match = matches.at(i);\n            auto left_pt = current_frame->GetKey(match.queryIdx);\n            auto right_pt = stereo_frame->GetKey(match.trainIdx);\n            cv::line(show, left_pt->kp.pt, right_pt->kp.pt, cv::Scalar(0,0,255),4);\n        }\n//        cv::drawMatches(\n//                current_frame->GetImagePyramid()[0],\n//                kps1,\n//                stereo_frame->GetImagePyramid()[0],\n//                kps2,\n//                matches, show);\n        cv::imshow(\"Stereo\", show);\n//        cv::waitKey(0);\n        return Depth; */\n    }\n\n    int LocalBA::PoseOptimization(std::shared_ptr<Frame>& F)\n    {\n        g2o::SparseOptimizer optimizer;\n        optimizer.setVerbose(false);\n\n        std::unique_ptr<g2o::BlockSolver_6_3::LinearSolverType> linearSolver;\n        linearSolver = g2o::make_unique<g2o::LinearSolverDense<g2o::BlockSolver_6_3::PoseMatrixType>>();\n\n        // \u9009\u62e9\u8fed\u4ee3\u7b56\u7565\uff0c\u901a\u5e38\u8fd8\u662fL-M\u7b97\u6cd5\u5c45\u591a\n        auto* solver = new g2o::OptimizationAlgorithmLevenberg(\n                g2o::make_unique<g2o::BlockSolver_6_3>(std::move(linearSolver))\n        );\n        solver->setUserLambdaInit(0.0001);\n        optimizer.setAlgorithm(solver);\n\n        int nInitialCorrespondences=0;\n\n        // Set Frame vertex\n        auto vSE3 = new g2o::VertexSE3Expmap();\n        Eigen::Matrix3d R = F->GetRotation().cast<double>().transpose();\n        Eigen::Vector3d t = - R * F->GetTranslation().cast<double>();\n        vSE3->setEstimate(g2o::SE3Quat(R, t));\n        vSE3->setId(0);\n        vSE3->setFixed(false);\n        optimizer.addVertex(vSE3);\n\n        // Set MapPoint vertices\n        const auto N = (int)F->GetKeys().size();\n\n        vector<g2o::EdgeSE3ProjectXYZOnlyPose*> vpEdgesMono;\n        vector<size_t> vnIndexEdgeMono;\n        vpEdgesMono.reserve(N);\n        vnIndexEdgeMono.reserve(N);\n\n        const float deltaMono = sqrtf(5.991f);\n\n        cv::Mat show = F->GetImagePyramid().at(0).clone();\n        cv::cvtColor(show, show, cv::COLOR_GRAY2BGR);\n\n        {\n            std::unique_lock<std::mutex> lock(MapPoint::mGlobalMutex);\n\n            for(int i=0; i<N; i++)\n            {\n                auto pMP = F->GetMapPoint(i);\n                if(pMP)\n                {\n                    // Monocular observation\n                    nInitialCorrespondences++;\n\n                    Eigen::Matrix<double,2,1> obs;\n                    obs << F->GetKey(i)->px.x(), F->GetKey(i)->px.y();\n\n                    auto e = new g2o::EdgeSE3ProjectXYZOnlyPose();\n\n                    e->setVertex(0, dynamic_cast<g2o::OptimizableGraph::Vertex*>(optimizer.vertex(0)));\n                    e->setMeasurement(obs);\n\n                    const float invSigma2 = F->GetInverseScaleSigmaSquares().at(F->GetKey(i)->kp.octave);\n                    e->setInformation(Eigen::Matrix2d::Identity()*invSigma2);\n\n                    auto rk = new g2o::RobustKernelHuber;\n                    e->setRobustKernel(rk);\n                    rk->setDelta(deltaMono);\n\n                    e->fx = 718.856;\n                    e->fy = 718.856;\n                    e->cx = 607.1928;\n                    e->cy = 185.2157;\n\n                    e->Xw[0] = F->GetMapPoint(i)->GetWorldPos().x();\n                    e->Xw[1] = F->GetMapPoint(i)->GetWorldPos().y();\n                    e->Xw[2] = F->GetMapPoint(i)->GetWorldPos().z();\n\n                    Eigen::Vector3d pw = e->Xw;\n                    Eigen::Vector3d pc = vSE3->estimate().map(pw);\n                    auto proj = e->cam_project(pc);\n                    double my_e2 = (proj - obs).dot(proj - obs);\n                    e->computeError();\n                    auto e2 = (float)e->chi2();\n                    if(e2 > 3)\n                    {\n//                        e->setLevel(1);\n//                        std::cout<<\"here!\";\n                    }\n\n                    auto T_cw = F->GetPose();\n                    const Eigen::Vector3f pw0 = F->GetMapPoint(i)->GetWorldPos();\n                    const Eigen::Vector3f pc0 = T_cw.block<3, 3>(0, 0) * pw0 + T_cw.block<3, 1>(0, 3);\n                    const Eigen::Vector2f uv0 = F->GetCameraModel()->World2Cam(pc0);\n\n                    cv::Point p0(obs.x(), obs.y());\n                    cv::Point p1(proj.x(), proj.y());\n                    cv::Point p2(uv0.x(), uv0.y());\n\n                    cv::circle(show, p0, 8,cv::Scalar(0, 0, 255), -1);\n                    cv::circle(show, p1, 2,cv::Scalar(0, 255, 0), -1);\n                    cv::circle(show, p2, 2,cv::Scalar(255, 0, 0), -1);\n\n\n                    optimizer.addEdge(e);\n                    vpEdgesMono.push_back(e);\n                    vnIndexEdgeMono.push_back(i);\n                }\n            }\n        }\n\n        cv::imshow(\"sba\", show);\n//        cv::waitKey(0);\n\n        if(nInitialCorrespondences<3)\n            return 0;\n\n        // test error\n        float sum_err = 0;\n        int cnt = 0;\n        for(auto& ee:vpEdgesMono)\n        {\n            if(ee->level() == 0)\n            {\n                ee->computeError();\n                auto e2 = (float)ee->chi2();\n                sum_err += e2;\n                cnt ++;\n            }\n        }\n        std::cout<<\"sum err \"<<sum_err<<\" mean err: \"<<sum_err / cnt<<std::endl;\n        // We perform 4 optimizations, after each optimization we classify observation as inlier/outlier\n        // At the next optimization, outliers are not included, but at the end they can be classified as inliers again.\n        const float chi2Mono[4]={5.991,5.991,5.991,5.991};\n        const int its[4]={10,10,10,10};\n\n        int nBad=0;\n        for(size_t it=0; it<4; it++)\n        {\n            Eigen::Matrix3f R0 = F->GetRotation().transpose();\n            Eigen::Vector3f t0 = - R0 * F->GetTranslation();\n            vSE3->setEstimate(g2o::SE3Quat(R0.cast<double>(), t0.cast<double>()));\n\n            optimizer.initializeOptimization(0);\n            optimizer.optimize(its[it]);\n\n            nBad=0;\n            for(size_t i=0, iend=vpEdgesMono.size(); i<iend; i++)\n            {\n                g2o::EdgeSE3ProjectXYZOnlyPose* e = vpEdgesMono[i];\n\n                const size_t idx = vnIndexEdgeMono[i];\n\n                if(F->GetOutlier(idx))\n                {\n                    e->computeError();\n                }\n\n                const auto chi2 = (float)e->chi2();\n\n                if(chi2>chi2Mono[it])\n                {\n                    F->SetOutlier(idx, true);\n                    e->setLevel(1);\n                    nBad++;\n                }\n                else\n                {\n                    F->SetOutlier(idx, false);\n                    e->setLevel(0);\n                }\n\n                if(it==2)\n                    e->setRobustKernel(nullptr);\n            }\n\n            float sum_err = 0;\n            int cnt = 0;\n            for(auto& ee:vpEdgesMono)\n            {\n                if(ee->level() == 0)\n                {\n                    ee->computeError();\n                    auto e2 = (float)ee->chi2();\n                    sum_err += e2;\n                    cnt ++;\n                }\n            }\n            std::cout<<\"sum err \"<<sum_err<<\" mean err: \"<<sum_err / cnt<<std::endl;\n\n            if(optimizer.edges().size()<10)\n                break;\n        }\n\n\n        // Recover optimized pose and return number of inliers\n        auto* vSE3_recov = dynamic_cast<g2o::VertexSE3Expmap*>(optimizer.vertex(0));\n        g2o::SE3Quat SE3quat_recov = vSE3_recov->estimate();\n        Eigen::Matrix4f pose = Eigen::Matrix4f::Identity();\n        pose.block<3, 3>(0, 0) = SE3quat_recov.rotation().toRotationMatrix().cast<float>();\n        pose.block<3, 1>(0, 3) = SE3quat_recov.translation().cast<float>();\n        F->SetPose(pose);\n        return nInitialCorrespondences-nBad;\n    }\n}\n\n", "meta": {"hexsha": "944c6f1675be84a1ebef5642b7837dd9a87f7303", "size": 18093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mapping/LocalBA.cpp", "max_stars_repo_name": "linyicheng1/trackingBench-SLAM", "max_stars_repo_head_hexsha": "2a110a43bb54867428faa218915cb03596f66e9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-11T08:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T08:32:16.000Z", "max_issues_repo_path": "src/mapping/LocalBA.cpp", "max_issues_repo_name": "linyicheng1/trackingBench-SLAM", "max_issues_repo_head_hexsha": "2a110a43bb54867428faa218915cb03596f66e9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mapping/LocalBA.cpp", "max_forks_repo_name": "linyicheng1/trackingBench-SLAM", "max_forks_repo_head_hexsha": "2a110a43bb54867428faa218915cb03596f66e9e", "max_forks_repo_licenses": ["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.6997971602, "max_line_length": 159, "alphanum_fraction": 0.4890289062, "num_tokens": 4759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5283380873868502}}
{"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_POW2_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_POW2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-exponential\n    Function object implementing pow2 capabilities\n\n    Returns \\f$ x 2^y\\f$.  (the result is undefined on overflow and\n    the function asserts for invalid second parameter )\n\n    @par Semantic:\n\n    For every parameters of floating type T\n\n    @code\n    T r = pow2(x, y);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = x*exp2(trunc(y));\n    @endcode\n\n    @see exp2, trunc, ldexp\n\n  **/\n  Value pow2(Value const & v0, Value const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/pow2.hpp>\n#include <boost/simd/function/simd/pow2.hpp>\n\n#endif\n", "meta": {"hexsha": "3e7910e8699c05bd293549a8bb5e40f0cbea9360", "size": 1139, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/pow2.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/pow2.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/pow2.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": 22.3333333333, "max_line_length": 100, "alphanum_fraction": 0.5741878841, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5283380873868502}}
{"text": "#ifndef AIKIDO_STATESPACE_SE3STATESPACE_HPP_\n#define AIKIDO_STATESPACE_SE3STATESPACE_HPP_\n#include <Eigen/Geometry>\n#include \"ScopedState.hpp\"\n#include \"StateSpace.hpp\"\n\nnamespace aikido {\nnamespace statespace {\n\n// Defined in detail/SE3-impl.hpp\ntemplate <class>\nclass SE3StateHandle;\n\n/// The three-dimensional special Euclidean group SE(3), i.e. the space of\n/// spatial rigid body transformations. Note that the group operation for SE(3)\n/// differs from the group operation of the Cartesian product space R^3 x SO(3)\n/// because it is constructed through the semi-direct product.\nclass SE3 : public virtual StateSpace\n{\npublic:\n  class State : public StateSpace::State\n  {\n  public:\n    using Isometry3d\n        = Eigen::Transform<double, 3, Eigen::Isometry, Eigen::DontAlign>;\n\n    /// Constructs the identity element.\n    State();\n\n    ~State() = default;\n\n    /// Constructs the state from an Eigen transformation object.\n    ///\n    /// \\param _transform Eigen transformation\n    explicit State(const Isometry3d& _transform);\n\n    /// Sets value to an Eigen transfomation object.\n    ///\n    /// \\param _transform Eigen transformation\n    void setIsometry(const Isometry3d& _transform);\n\n    /// Gets value as an Eigen transformation object.\n    ///\n    /// \\return Eigen trasnformation\n    const Isometry3d& getIsometry() const;\n\n  private:\n    Isometry3d mTransform;\n\n    friend class SE3;\n  };\n\n  using StateHandle = SE3StateHandle<State>;\n  using StateHandleConst = SE3StateHandle<const State>;\n\n  using ScopedState = statespace::ScopedState<StateHandle>;\n  using ScopedStateConst = statespace::ScopedState<StateHandleConst>;\n\n  using StateSpace::compose;\n\n  using Isometry3d = State::Isometry3d;\n\n  /// Constructs a state space representing SE(3).\n  SE3() = default;\n\n  /// Helper function to create a \\c ScopedState.\n  ///\n  /// \\return new \\c ScopedState\n  ScopedState createState() const;\n\n  /// Creates an identical clone of \\c stateIn.\n  ScopedState cloneState(const StateSpace::State* stateIn) const;\n\n  /// Gets value as an Eigen transformation object.\n  ///\n  /// \\param _state a \\c State in this state space\n  /// \\return Eigen transformation\n  const Isometry3d& getIsometry(const State* _state) const;\n\n  /// Sets value to an Eigen transfomation object.\n  ///\n  /// \\param _state a \\c State in this state space\n  /// \\param _transform Eigen transformation\n  void setIsometry(State* _state, const Isometry3d& _transform) const;\n\n  // Documentation inherited.\n  std::size_t getStateSizeInBytes() const override;\n\n  // Documentation inherited.\n  StateSpace::State* allocateStateInBuffer(void* _buffer) const override;\n\n  // Documentation inherited.\n  void freeStateInBuffer(StateSpace::State* _state) const override;\n\n  // Documentation inherited.\n  void compose(\n      const StateSpace::State* _state1,\n      const StateSpace::State* _state2,\n      StateSpace::State* _out) const override;\n\n  // Documentation inherited.\n  void getIdentity(StateSpace::State* _out) const override;\n\n  // Documentation inherited.\n  void getInverse(\n      const StateSpace::State* _in, StateSpace::State* _out) const override;\n\n  // Documentation inherited.\n  std::size_t getDimension() const override;\n\n  // Documentation inherited.\n  void copyState(\n      const StateSpace::State* _source,\n      StateSpace::State* _destination) const override;\n\n  /// Exponential mapping of Lie algebra element to a Lie group element. The\n  /// tangent space is parameterized a planar twist of the form (rotation,\n  /// translation).\n  ///\n  /// \\param _tangent element of the tangent space\n  /// \\param[out] _out corresponding element of the Lie group\n  void expMap(\n      const Eigen::VectorXd& _tangent, StateSpace::State* _out) const override;\n\n  /// Log mapping of Lie group element to a Lie algebra element. The tangent\n  /// space is parameterized as a planar twist of the form (rotation,\n  /// translation).\n  ///\n  /// \\param _in element of this Lie group\n  /// \\param[out] _tangent corresponding element of the tangent space\n  void logMap(\n      const StateSpace::State* _in, Eigen::VectorXd& _tangent) const override;\n\n  /// Print the quaternion followed by the translation\n  /// Format: [q.w, q.x, q.y, q.z, x, y, z] where is the quaternion\n  /// representation of the rotational component of the state\n  void print(const StateSpace::State* _state, std::ostream& _os) const override;\n};\n\n} // namespace statespace\n} // namespace aikido\n\n#include \"detail/SE3-impl.hpp\"\n\n#endif // ifndef AIKIDO_STATESPACE_SE3STATESPACE_HPP_\n", "meta": {"hexsha": "d4456018487c4d1bc3fd8282efe322eea0e5dc17", "size": 4524, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/aikido/statespace/SE3.hpp", "max_stars_repo_name": "usc-csci-545/aikido", "max_stars_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "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/aikido/statespace/SE3.hpp", "max_issues_repo_name": "usc-csci-545/aikido", "max_issues_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/aikido/statespace/SE3.hpp", "max_forks_repo_name": "usc-csci-545/aikido", "max_forks_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "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.9863013699, "max_line_length": 80, "alphanum_fraction": 0.7212643678, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5283380767403268}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra. Eigen itself is part of the KDE project.\n//\n// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>\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#define EIGEN_NO_ASSERTION_CHECKING\n#include \"main.h\"\n#include <Eigen/Cholesky>\n#include <Eigen/LU>\n\n#ifdef HAS_GSL\n#include \"gsl_helper.h\"\n#endif\n\ntemplate<typename MatrixType> void cholesky(const MatrixType& m)\n{\n  /* this test covers the following files:\n     LLT.h LDLT.h\n  */\n  int rows = m.rows();\n  int cols = m.cols();\n\n  typedef typename MatrixType::Scalar Scalar;\n  typedef typename NumTraits<Scalar>::Real RealScalar;\n  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;\n  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;\n\n  MatrixType a0 = MatrixType::Random(rows,cols);\n  VectorType vecB = VectorType::Random(rows), vecX(rows);\n  MatrixType matB = MatrixType::Random(rows,cols), matX(rows,cols);\n  SquareMatrixType symm =  a0 * a0.adjoint();\n  // let's make sure the matrix is not singular or near singular\n  MatrixType a1 = MatrixType::Random(rows,cols);\n  symm += a1 * a1.adjoint();\n\n  #ifdef HAS_GSL\n  if (ei_is_same_type<RealScalar,double>::ret)\n  {\n    typedef GslTraits<Scalar> Gsl;\n    typename Gsl::Matrix gMatA=0, gSymm=0;\n    typename Gsl::Vector gVecB=0, gVecX=0;\n    convert<MatrixType>(symm, gSymm);\n    convert<MatrixType>(symm, gMatA);\n    convert<VectorType>(vecB, gVecB);\n    convert<VectorType>(vecB, gVecX);\n    Gsl::cholesky(gMatA);\n    Gsl::cholesky_solve(gMatA, gVecB, gVecX);\n    VectorType vecX(rows), _vecX, _vecB;\n    convert(gVecX, _vecX);\n    symm.llt().solve(vecB, &vecX);\n    Gsl::prod(gSymm, gVecX, gVecB);\n    convert(gVecB, _vecB);\n    // test gsl itself !\n    VERIFY_IS_APPROX(vecB, _vecB);\n    VERIFY_IS_APPROX(vecX, _vecX);\n\n    Gsl::free(gMatA);\n    Gsl::free(gSymm);\n    Gsl::free(gVecB);\n    Gsl::free(gVecX);\n  }\n  #endif\n\n  {\n    LDLT<SquareMatrixType> ldlt(symm);\n    VERIFY(ldlt.isPositiveDefinite());\n    // in eigen3, LDLT is pivoting\n    //VERIFY_IS_APPROX(symm, ldlt.matrixL() * ldlt.vectorD().asDiagonal() * ldlt.matrixL().adjoint());\n    ldlt.solve(vecB, &vecX);\n    VERIFY_IS_APPROX(symm * vecX, vecB);\n    ldlt.solve(matB, &matX);\n    VERIFY_IS_APPROX(symm * matX, matB);\n  }\n\n  {\n    LLT<SquareMatrixType> chol(symm);\n    VERIFY(chol.isPositiveDefinite());\n    VERIFY_IS_APPROX(symm, chol.matrixL() * chol.matrixL().adjoint());\n    chol.solve(vecB, &vecX);\n    VERIFY_IS_APPROX(symm * vecX, vecB);\n    chol.solve(matB, &matX);\n    VERIFY_IS_APPROX(symm * matX, matB);\n  }\n\n#if 0 // cholesky is not rank-revealing anyway\n  // test isPositiveDefinite on non definite matrix\n  if (rows>4)\n  {\n    SquareMatrixType symm =  a0.block(0,0,rows,cols-4) * a0.block(0,0,rows,cols-4).adjoint();\n    LLT<SquareMatrixType> chol(symm);\n    VERIFY(!chol.isPositiveDefinite());\n    LDLT<SquareMatrixType> cholnosqrt(symm);\n    VERIFY(!cholnosqrt.isPositiveDefinite());\n  }\n#endif\n}\n\nvoid test_eigen2_cholesky()\n{\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( cholesky(Matrix<double,1,1>()) );\n    CALL_SUBTEST_2( cholesky(Matrix2d()) );\n    CALL_SUBTEST_3( cholesky(Matrix3f()) );\n    CALL_SUBTEST_4( cholesky(Matrix4d()) );\n    CALL_SUBTEST_5( cholesky(MatrixXcd(7,7)) );\n    CALL_SUBTEST_6( cholesky(MatrixXf(17,17)) );\n    CALL_SUBTEST_7( cholesky(MatrixXd(33,33)) );\n  }\n}\n", "meta": {"hexsha": "9c4b6f56197ff0686fdc741d7a7778aeb3b5aedf", "size": 3603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/PEST++/src/libs/Eigen/test/eigen2/eigen2_cholesky.cpp", "max_stars_repo_name": "usgs/neversink_workflow", "max_stars_repo_head_hexsha": "acd61435b8553e38d4a903c8cd7a3afc612446f9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "SCA/eigen_332/test/eigen2/eigen2_cholesky.cpp", "max_issues_repo_name": "JooseRajamaeki/TVCG18", "max_issues_repo_head_hexsha": "ddc73f422c267b1c38ede3ba20046efff46a6d74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T20:31:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T15:29:20.000Z", "max_forks_repo_path": "SCA/eigen_332/test/eigen2/eigen2_cholesky.cpp", "max_forks_repo_name": "JooseRajamaeki/TVCG18", "max_forks_repo_head_hexsha": "ddc73f422c267b1c38ede3ba20046efff46a6d74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 31.6052631579, "max_line_length": 104, "alphanum_fraction": 0.6872051069, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5283114334799447}}
{"text": "#include <CGAL/Cartesian.h>\n#include <CGAL/Exact_rational.h>\n#include <CGAL/Arr_segment_traits_2.h>\n#include <CGAL/Arrangement_2.h>\n#include <CGAL/Arr_extended_dcel.h>\n#include <CGAL/Arr_overlay_2.h>\n#include <CGAL/Arr_default_overlay_traits.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <strstream>\n#include <set>\n#include <unordered_set>\n#include <chrono>\n\n#include \"arrangement.h\"\n#include \"camera.h\"\n#include \"mesh.h\"\n#include \"divide_conquer_construct.h\"\n#include \"plane_param.h\"\n#include \"postprocess.h\"\n\nint main (int argc, char** argv)\n{\n\tMesh mesh;\n\tCamera camera;\n\tmesh.LoadFromFile(argv[1]);\n\tcamera.LoadFromFile(argv[2]);\n\tcamera.ApplyExtrinsic(mesh);\n\n\tmesh.BoundaryClip(2, 1e-2, 0, false);\n\tcamera.ApplyIntrinsic(mesh);\n\n\tmesh.BoundaryClip(0, -0.5, 0, true);\n\tmesh.BoundaryClip(1, -0.5, 0, true);\n\tmesh.BoundaryClip(0, 0.5, 1, true);\n\tmesh.BoundaryClip(1, 0.5, 1, true);\n\n\n\tmesh.ComputeNormals();\n\tmesh.ComputePlaneParameters();\n\n\tArrangement_2 overlay;\n\n\tConstructArrangement(mesh, 0, mesh.FaceNum() - 1, &overlay);\n\t//ConstructArrangement(mesh, 0, 1000, &overlay);\n\tprintf(\"\\n\");\n\n\t//exit(0);\n\tPostProcess process;\t\n\tprocess.CollectFaceAndVertices(mesh, overlay, camera.GetAngle());\n\n\t// remove 2-degree vertex on edge\n\tprocess.RemoveRedundantVertices();\n\n\t// merge close vertices\n\t//process.MergeDuplex(mesh);\n\n\t//process.CollectEdges(mesh);\n\n\t//recognize faces\n\tint l = strlen(argv[3]);\n\tif (l > 3 && argv[3][l - 1] == 'g' && argv[3][l - 2] == 'v' && argv[3][l - 3] == 's')\n\t\tprocess.SaveToSVG(mesh, argv[3]);\n\telse\n\t\tprocess.SaveToFile(mesh, argv[3]);\n}\n", "meta": {"hexsha": "697ff9e66952451141f6ff7cc98e770e5bae7234", "size": 1584, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/main.cc", "max_stars_repo_name": "hjwdzh/VectorGraphRenderer", "max_stars_repo_head_hexsha": "4af5a683fb1414f32101be22924a809db08d7cb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-02-15T23:00:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-25T05:01:17.000Z", "max_issues_repo_path": "src/main.cc", "max_issues_repo_name": "hjwdzh/VectorGraphRenderer", "max_issues_repo_head_hexsha": "4af5a683fb1414f32101be22924a809db08d7cb5", "max_issues_repo_licenses": ["MIT"], "max_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.cc", "max_forks_repo_name": "hjwdzh/VectorGraphRenderer", "max_forks_repo_head_hexsha": "4af5a683fb1414f32101be22924a809db08d7cb5", "max_forks_repo_licenses": ["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.6417910448, "max_line_length": 86, "alphanum_fraction": 0.7051767677, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5282199627595385}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\n#ifndef _UBLAS_\n#define _UBLAS_\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#endif\n\n#include \"time_bench.hpp\"\n#include \"Lloyd.hpp\"\n#include \"Hamerly.hpp\"\n#include \"Elkan.hpp\"\n\nusing namespace std;\nusing namespace boost::numeric::ublas;\nusing namespace boost::numeric;\n\nenum algorithm {Lloyd, Hamerly, Elkan}; /* \u5b9f\u884c\u3059\u308b\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0 */\nstatic const std::vector<string> algo_name{\"Lloyd\", \"Hamerly\", \"Elkan\"};\n\n#define BENCH 1\n/* k-means\u306e\u5404\u7a2e\u306e\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0\u306e\u30d9\u30f3\u30c1\u30de\u30fc\u30af\u3092\u53d6\u308b\u3068\u304d\u306b1*/\n\n#if BENCH\nint bench_show\n(ostream &stream,            /* \u51fa\u529b\u5148 */\n enum algorithm method,      /* \u4f7f\u7528\u3057\u305f\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0 */\n const unsigned int n,       /* \u30c7\u30fc\u30bf\u70b9\u6570 */\n const unsigned int d,       /* \u6b21\u5143\u6570 */\n const unsigned int k,       /* \u30af\u30e9\u30b9\u30bf\u6570 */\n const struct timeval start, /* \u958b\u59cb\u6642\u523b */\n const struct timeval end,   /* \u7d42\u4e86\u6642\u523b */\n const unsigned int rep,     /* \u7e70\u308a\u8fd4\u3057\u56de\u6570 */\n const ublas::matrix<double> x,       /* \u30c7\u30fc\u30bf\u70b9 */ \n const ublas::vector<unsigned int> a, /* \u5272\u308a\u5f53\u3066\u30af\u30e9\u30b9\u30bf */\n const ublas::matrix<double> c)       /* \u30af\u30e9\u30b9\u30bf\u4e2d\u5fc3 */\n{  \n  double err_sum = 0; /* \u4e8c\u4e57\u8aa4\u5dee\u548c\u3092\u8a08\u7b97\u3059\u308b */\n  for(unsigned int i = 0; i < n; ++i){\n    err_sum += dist_xc(row(x, i), c, a[i]) * dist_xc(row(x, i), c, a[i]);\n  }\n     \n  stream << algo_name[method] << \"\\t\" << n << \"\\t\" << d << \"\\t\" << k << \"\\t\" \t \n\t << diff_timeval(start, end)    << \"\\t\" /* \u5b9f\u884c\u6642\u9593(us) */\n\t << (err_sum / n)  << \"\\t\" << rep << endl;\n  return 0;\n}\n#endif\n\n\n/* \u5168\u3066\u306e\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0\u306b\u5171\u901a */\nint initialize_centers\n(const unsigned int k,\n const ublas::matrix<double> x,\n ublas ::matrix<double> &c)\n{\n  /* \u3068\u308a\u3042\u3048\u305a\u9069\u5f53\u306b\u6700\u521d\u306e\u30c7\u30fc\u30bf\u70b9\u3092\u5145\u3066\u308b */\n  for(unsigned int j = 0; j < k; ++j){\n    row(c, j) = row(x, j);\n  }\n  return 0;\n}\n\n\nint main(const int argc, char *argv[])\n{   if(argc < 6){ /* \u5b9f\u884c\u6642\u30aa\u30d7\u30b7\u30e7\u30f3\u304c\u5c11\u306a\u3044\u3068\u304d\u306e\u30a8\u30e9\u30fc\u51e6\u7406 */\n    /* \u4f7f\u3044\u65b9\u3092\u8868\u793a\u3057\u3066\u7570\u5e38\u7d42\u4e86 */\n    cerr << \"usage: \" << argv[0]\n\t << \" <method> <n> <d> <k> <data>\\n\"\n\t << \" <method> = Lloyd | Hamerly\\n\"\n\t << \" n : number of data points\\n\"\n      \t << \" d : dimension\\n\"\n\t << \" k : number of clusters\\n\"\n         << \" data    : file path of the data file\\n\"\n\t << endl;\n    exit(1);\n  }else{\n    \n    /* \u5b9f\u884c\u6642\u30aa\u30d7\u30b7\u30e7\u30f3\u306e\u51e6\u7406 */    \n    enum algorithm method; /* \u5b9f\u884c\u3059\u308b\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0 */\n    if     (strcmp(argv[1], \"Lloyd\")   == 0){ method = Lloyd; }\n    else if(strcmp(argv[1], \"Hamerly\") == 0){ method = Hamerly; }\n    else if(strcmp(argv[1], \"Elkan\")   == 0){ method = Elkan; }\n    else{ /* \u6307\u5b9a\u3055\u308c\u305f\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0\u304c\u4e0d\u660e */\n      cerr << \"unknown method : \" << argv[1] << endl;\n      exit(1);\n    }\n\n    unsigned int n = atoi(argv[2]), d = atoi(argv[3]), k = atoi(argv[4]);\n    char *input_file = argv[5];\n\n    if(n < k){ /* n < d \u306e\u3068\u304d\u306e\u30a8\u30e9\u30fc\u51e6\u7406 */\n      cerr << \"data size n is smaller than cluster size d\\n\"\n\t   << \"n = \" << n << \", d = \" << d\n\t   << endl;\n      exit(1);\n    }\n    \n    ublas::matrix<double> data(n, d); \n    { /* n\u500b\u306ed\u6b21\u5143\u30c7\u30fc\u30bf\u3092\u30d5\u30a1\u30a4\u30eb\u304b\u3089\u8aad\u307f\u8fbc\u3080 */\n      ifstream fs(input_file);\n      if(fs.fail()){ exit(1); }\n      for(unsigned int i = 0; i < n; ++i){\n\tfor(unsigned int j = 0; j < d; ++j){\n\t  fs >> data(i,j);\n\t}\n      }\n      fs.close();\n    }\n\n    /* \u30af\u30e9\u30b9\u30bf\u30ea\u30f3\u30b0\u306e\u7d50\u679c\u3092\u66f8\u304d\u8fbc\u3080\u30e1\u30e2\u30ea\u9818\u57df\u306e\u78ba\u4fdd */\n    ublas::vector<unsigned int> a(n, 0); /* \u5404\u70b9x_i\u304c\u5c5e\u3059\u308b\u30af\u30e9\u30b9\u30bf */\n    ublas::matrix<double> c(k,d,0);      /* \u30af\u30e9\u30b9\u30bf\u306e\u91cd\u5fc3 */\n    unsigned int rep = 0;                /* \u7e70\u308a\u8fd4\u3057\u56de\u6570 */ \n\n    /* \u521d\u671f\u30af\u30e9\u30b9\u30bf\u4e2d\u5fc3\u3092\u4f55\u3089\u304b\u306e\u65b9\u6cd5\u3067\u5f97\u308b */\n    initialize_centers(k, data, c);\n\n    \n#if BENCH /* \u30d7\u30ed\u30b0\u30e9\u30e0\u5b9f\u884c\u6642\u9593\u306e\u30d9\u30f3\u30c1\u30de\u30fc\u30af\u3092\u53d6\u308b */\n    struct timeval t_start, t_end;\n    gettimeofday(&t_start, NULL); /* \u6642\u9593\u8a08\u6e2c\u958b\u59cb */\n#endif\n    \n    if(method == Lloyd){\n      rep = Lloyd_main(n, d, k, data, a, c);\n    }else if(method == Hamerly){\n      rep = Hamerly_main(n, d, k, data, a, c);\n    }else if(method == Elkan){\n      rep = Elkan_main(n, d, k, data, a, c);\n    }\n\n#if BENCH\n    gettimeofday(&t_end, NULL); /* \u6642\u9593\u8a08\u6e2c\u7d42\u4e86 */\n#endif\n\n    { /* \u7d50\u679c\u3092\u51fa\u529b */\n      ofstream fs(algo_name[method] + \"_\"\n\t\t  + std::to_string(n) + \"_\"\n\t\t  + std::to_string(d) + \"_\"\n\t\t  + std::to_string(k) + \".txt\");\n      if(fs.fail()){ exit(1); }\n      fs << a << endl;\n      fs << c << endl;\n      fs.close();\n    }\n\n#if BENCH\n    bench_show(std::cerr, method, n, d, k, t_start, t_end, rep, data, a, c);\n#endif\n    \n    return 0;\n  }\n}\n", "meta": {"hexsha": "26b42915918f9e05905e6dd721c1945d6b6b1083", "size": 4184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "program/kmeans.cpp", "max_stars_repo_name": "yk-tanigawa/201503_clustering", "max_stars_repo_head_hexsha": "43a11e707c08f1576e5765824c74330b6730e7e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "program/kmeans.cpp", "max_issues_repo_name": "yk-tanigawa/201503_clustering", "max_issues_repo_head_hexsha": "43a11e707c08f1576e5765824c74330b6730e7e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-26T16:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-26T16:53:14.000Z", "max_forks_repo_path": "program/kmeans.cpp", "max_forks_repo_name": "yk-tanigawa/201503_clustering", "max_forks_repo_head_hexsha": "43a11e707c08f1576e5765824c74330b6730e7e9", "max_forks_repo_licenses": ["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.8271604938, "max_line_length": 79, "alphanum_fraction": 0.5540152964, "num_tokens": 1588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936484231889, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5282105257469557}}
{"text": "/**\n * @file    testImplicitSchurFactor.cpp\n * @brief   unit test implicit jacobian factors\n * @author  Frank Dellaert\n * @date    Oct 20, 2013\n */\n\n//#include <gtsam_unstable/slam/ImplicitSchurFactor.h>\n#include <gtsam/slam/ImplicitSchurFactor.h>\n//#include <gtsam_unstable/slam/JacobianFactorQ.h>\n#include <gtsam/slam/JacobianFactorQ.h>\n//#include \"gtsam_unstable/slam/JacobianFactorQR.h\"\n#include \"gtsam/slam/JacobianFactorQR.h\"\n\n#include <gtsam/base/timing.h>\n#include <gtsam/linear/VectorValues.h>\n#include <gtsam/linear/NoiseModel.h>\n#include <gtsam/linear/GaussianFactor.h>\n\n#include <boost/assign/list_of.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/range/adaptor/map.hpp>\n#include <CppUnitLite/TestHarness.h>\n\nusing namespace std;\nusing namespace boost::assign;\nusing namespace gtsam;\n\n// F\ntypedef Eigen::Matrix<double, 2, 6> Matrix26;\nconst Matrix26 F0 = Matrix26::Ones();\nconst Matrix26 F1 = 2 * Matrix26::Ones();\nconst Matrix26 F3 = 3 * Matrix26::Ones();\nconst vector<pair<Key, Matrix26> > Fblocks = list_of<pair<Key, Matrix> > //\n    (make_pair(0, F0))(make_pair(1, F1))(make_pair(3, F3));\n// RHS and sigmas\nconst Vector b = (Vector(6) << 1., 2., 3., 4., 5., 6.);\n\n//*************************************************************************************\nTEST( implicitSchurFactor, creation ) {\n  // Matrix E = Matrix::Ones(6,3);\n  Matrix E = zeros(6, 3);\n  E.block<2,2>(0, 0) = eye(2);\n  E.block<2,3>(2, 0) = 2 * ones(2, 3);\n  Matrix3 P = (E.transpose() * E).inverse();\n  ImplicitSchurFactor<6> expected(Fblocks, E, P, b);\n  Matrix expectedP = expected.getPointCovariance();\n  EXPECT(assert_equal(expectedP, P));\n}\n\n/* ************************************************************************* */\nTEST( implicitSchurFactor, addHessianMultiply ) {\n\n  Matrix E = zeros(6, 3);\n  E.block<2,2>(0, 0) = eye(2);\n  E.block<2,3>(2, 0) = 2 * ones(2, 3);\n  E.block<2,2>(4, 1) = eye(2);\n  Matrix3 P = (E.transpose() * E).inverse();\n\n  double alpha = 0.5;\n  VectorValues xvalues = map_list_of //\n  (0, gtsam::repeat(6, 2))//\n  (1, gtsam::repeat(6, 4))//\n  (2, gtsam::repeat(6, 0))// distractor\n  (3, gtsam::repeat(6, 8));\n\n  VectorValues yExpected = map_list_of//\n  (0, gtsam::repeat(6, 27))//\n  (1, gtsam::repeat(6, -40))//\n  (2, gtsam::repeat(6, 0))// distractor\n  (3, gtsam::repeat(6, 279));\n\n  // Create full F\n  size_t M=4, m = 3, d = 6;\n  Matrix F(2 * m, d * M);\n  F << F0, zeros(2, d * 3), zeros(2, d), F1, zeros(2, d*2), zeros(2, d * 3), F3;\n\n  // Calculate expected result F'*alpha*(I - E*P*E')*F*x\n  FastVector<Key> keys;\n  keys += 0,1,2,3;\n  Vector x = xvalues.vector(keys);\n  Vector expected = zero(24);\n  ImplicitSchurFactor<6>::multiplyHessianAdd(F, E, P, alpha, x, expected);\n  EXPECT(assert_equal(expected, yExpected.vector(keys), 1e-8));\n\n  // Create ImplicitSchurFactor\n  ImplicitSchurFactor<6> implicitFactor(Fblocks, E, P, b);\n\n  VectorValues zero = 0 * yExpected;// quick way to get zero w right structure\n  { // First Version\n    VectorValues yActual = zero;\n    implicitFactor.multiplyHessianAdd(alpha, xvalues, yActual);\n    EXPECT(assert_equal(yExpected, yActual, 1e-8));\n    implicitFactor.multiplyHessianAdd(alpha, xvalues, yActual);\n    EXPECT(assert_equal(2 * yExpected, yActual, 1e-8));\n    implicitFactor.multiplyHessianAdd(-1, xvalues, yActual);\n    EXPECT(assert_equal(zero, yActual, 1e-8));\n  }\n\n  typedef Eigen::Matrix<double, 24, 1> DeltaX;\n  typedef Eigen::Map<DeltaX> XMap;\n  double* y = new double[24];\n  double* xdata = x.data();\n\n  { // Raw memory Version\n    std::fill(y, y + 24, 0);// zero y !\n    implicitFactor.multiplyHessianAdd(alpha, xdata, y);\n    EXPECT(assert_equal(expected, XMap(y), 1e-8));\n    implicitFactor.multiplyHessianAdd(alpha, xdata, y);\n    EXPECT(assert_equal(Vector(2 * expected), XMap(y), 1e-8));\n    implicitFactor.multiplyHessianAdd(-1, xdata, y);\n    EXPECT(assert_equal(Vector(0 * expected), XMap(y), 1e-8));\n  }\n\n  // Create JacobianFactor with same error\n  const SharedDiagonal model;\n  JacobianFactorQ<6> jf(Fblocks, E, P, b, model);\n\n  { // error\n    double expectedError = jf.error(xvalues);\n    double actualError = implicitFactor.errorJF(xvalues);\n    DOUBLES_EQUAL(expectedError,actualError,1e-7)\n  }\n\n  { // JacobianFactor with same error\n    VectorValues yActual = zero;\n    jf.multiplyHessianAdd(alpha, xvalues, yActual);\n    EXPECT(assert_equal(yExpected, yActual, 1e-8));\n    jf.multiplyHessianAdd(alpha, xvalues, yActual);\n    EXPECT(assert_equal(2 * yExpected, yActual, 1e-8));\n    jf.multiplyHessianAdd(-1, xvalues, yActual);\n    EXPECT(assert_equal(zero, yActual, 1e-8));\n  }\n\n  { // check hessian Diagonal\n    VectorValues diagExpected = jf.hessianDiagonal();\n    VectorValues diagActual = implicitFactor.hessianDiagonal();\n    EXPECT(assert_equal(diagExpected, diagActual, 1e-8));\n  }\n\n  { // check hessian Block Diagonal\n    map<Key,Matrix> BD = jf.hessianBlockDiagonal();\n    map<Key,Matrix> actualBD = implicitFactor.hessianBlockDiagonal();\n    LONGS_EQUAL(3,actualBD.size());\n    EXPECT(assert_equal(BD[0],actualBD[0]));\n    EXPECT(assert_equal(BD[1],actualBD[1]));\n    EXPECT(assert_equal(BD[3],actualBD[3]));\n  }\n\n  { // Raw memory Version\n    std::fill(y, y + 24, 0);// zero y !\n    jf.multiplyHessianAdd(alpha, xdata, y);\n    EXPECT(assert_equal(expected, XMap(y), 1e-8));\n    jf.multiplyHessianAdd(alpha, xdata, y);\n    EXPECT(assert_equal(Vector(2 * expected), XMap(y), 1e-8));\n    jf.multiplyHessianAdd(-1, xdata, y);\n    EXPECT(assert_equal(Vector(0 * expected), XMap(y), 1e-8));\n  }\n\n  { // Check gradientAtZero\n    VectorValues expected = jf.gradientAtZero();\n    VectorValues actual = implicitFactor.gradientAtZero();\n    EXPECT(assert_equal(expected, actual, 1e-8));\n  }\n\n  // Create JacobianFactorQR\n  JacobianFactorQR<6> jfq(Fblocks, E, P, b, model);\n  {\n    const SharedDiagonal model;\n    VectorValues yActual = zero;\n    jfq.multiplyHessianAdd(alpha, xvalues, yActual);\n    EXPECT(assert_equal(yExpected, yActual, 1e-8));\n    jfq.multiplyHessianAdd(alpha, xvalues, yActual);\n    EXPECT(assert_equal(2 * yExpected, yActual, 1e-8));\n    jfq.multiplyHessianAdd(-1, xvalues, yActual);\n    EXPECT(assert_equal(zero, yActual, 1e-8));\n  }\n\n  { // Raw memory Version\n    std::fill(y, y + 24, 0);// zero y !\n    jfq.multiplyHessianAdd(alpha, xdata, y);\n    EXPECT(assert_equal(expected, XMap(y), 1e-8));\n    jfq.multiplyHessianAdd(alpha, xdata, y);\n    EXPECT(assert_equal(Vector(2 * expected), XMap(y), 1e-8));\n    jfq.multiplyHessianAdd(-1, xdata, y);\n    EXPECT(assert_equal(Vector(0 * expected), XMap(y), 1e-8));\n  }\n  delete [] y;\n}\n\n/* ************************************************************************* */\nTEST(implicitSchurFactor, hessianDiagonal)\n{\n  /* TESTED AGAINST MATLAB\n   *  F = [ones(2,6) zeros(2,6) zeros(2,6)\n        zeros(2,6) 2*ones(2,6) zeros(2,6)\n        zeros(2,6) zeros(2,6) 3*ones(2,6)]\n      E = [[1:6] [1:6] [0.5 1:5]];\n      E = reshape(E',3,6)'\n      P = inv(E' * E)\n      H = F' * (eye(6) - E * P * E') * F\n      diag(H)\n   */\n  Matrix E(6,3);\n  E.block<2,3>(0, 0) << 1,2,3,4,5,6;\n  E.block<2,3>(2, 0) << 1,2,3,4,5,6;\n  E.block<2,3>(4, 0) << 0.5,1,2,3,4,5;\n  Matrix3 P = (E.transpose() * E).inverse();\n  ImplicitSchurFactor<6> factor(Fblocks, E, P, b);\n\n  // hessianDiagonal\n  VectorValues expected;\n  expected.insert(0, 1.195652*ones(6));\n  expected.insert(1, 4.782608*ones(6));\n  expected.insert(3, 7.043478*ones(6));\n  EXPECT(assert_equal(expected, factor.hessianDiagonal(),1e-5));\n\n  // hessianBlockDiagonal\n  map<Key,Matrix> actualBD = factor.hessianBlockDiagonal();\n  LONGS_EQUAL(3,actualBD.size());\n  Matrix FtE0 = F0.transpose() * E.block<2,3>(0, 0);\n  Matrix FtE1 = F1.transpose() * E.block<2,3>(2, 0);\n  Matrix FtE3 = F3.transpose() * E.block<2,3>(4, 0);\n\n  // variant one\n  EXPECT(assert_equal(F0.transpose()*F0-FtE0*P*FtE0.transpose(),actualBD[0]));\n  EXPECT(assert_equal(F1.transpose()*F1-FtE1*P*FtE1.transpose(),actualBD[1]));\n  EXPECT(assert_equal(F3.transpose()*F3-FtE3*P*FtE3.transpose(),actualBD[3]));\n\n  // variant two\n  Matrix I2 = eye(2);\n  Matrix E0 = E.block<2,3>(0, 0);\n  Matrix F0t = F0.transpose();\n  EXPECT(assert_equal(F0t*F0-F0t*E0*P*E0.transpose()*F0,actualBD[0]));\n  EXPECT(assert_equal(F0t*(F0-E0*P*E0.transpose()*F0),actualBD[0]));\n\n  Matrix M1 = F0t*(F0-E0*P*E0.transpose()*F0);\n  Matrix M2 = F0t*F0-F0t*E0*P*E0.transpose()*F0;\n\n  EXPECT(assert_equal(  M1 , actualBD[0] ));\n  EXPECT(assert_equal(  M1 , M2 ));\n\n  Matrix M1b = F0t*(E0*P*E0.transpose()*F0);\n  Matrix M2b = F0t*E0*P*E0.transpose()*F0;\n  EXPECT(assert_equal(  M1b , M2b ));\n\n  EXPECT(assert_equal(F0t*(I2-E0*P*E0.transpose())*F0,actualBD[0]));\n  EXPECT(assert_equal(F1.transpose()*F1-FtE1*P*FtE1.transpose(),actualBD[1]));\n  EXPECT(assert_equal(F3.transpose()*F3-FtE3*P*FtE3.transpose(),actualBD[3]));\n}\n\n/* ************************************************************************* */\nint main(void) {\n  TestResult tr;\n  int result = TestRegistry::runAllTests(tr);\n  return result;\n}\n//*************************************************************************************\n", "meta": {"hexsha": "77faaacc1ac2ecbde29f8fb5d4b98ebdf3775a2a", "size": 9063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/slam/tests/testImplicitSchurFactor.cpp", "max_stars_repo_name": "ashariati/gtsam-3.2.1", "max_stars_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T08:58:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T08:01:42.000Z", "max_issues_repo_path": "gtsam/slam/tests/testImplicitSchurFactor.cpp", "max_issues_repo_name": "ashariati/gtsam-3.2.1", "max_issues_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T16:21:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-13T16:50:42.000Z", "max_forks_repo_path": "gtsam/slam/tests/testImplicitSchurFactor.cpp", "max_forks_repo_name": "ashariati/gtsam-3.2.1", "max_forks_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2015-06-01T11:22:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T11:03:57.000Z", "avg_line_length": 34.8576923077, "max_line_length": 87, "alphanum_fraction": 0.6335650447, "num_tokens": 2999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5282105171770538}}
{"text": "\n#include <gtest/gtest.h>\n#include \"../util/util.h\"\n#include <Eigen/Core>\n#include <string>\n#include <algorithm>\n\n#ifndef _MSC_VER\nextern \"C\" {\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n#include <csim/update_ops.h>\n#include <csim/init_ops.h>\n}\n#else\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n#include <csim/update_ops.h>\n#include <csim/init_ops.h>\n#endif\n#include <csim/update_ops_cpp.hpp>\n\nvoid test_single_diagonal_matrix_gate(std::function<void(UINT, const CTYPE*, CTYPE*, ITYPE)> func) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\n\tEigen::MatrixXcd Identity(2, 2), Z(2, 2);\n\tIdentity << 1, 0, 0, 1;\n\tZ << 1, 0, 0, -1;\n\n\tEigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U;\n\n\tUINT target;\n\tdouble icoef, zcoef, norm;\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state(state, dim);\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\tEigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\t// single qubit diagonal matrix gate\n\t\ttarget = rand_int(n);\n\t\ticoef = rand_real(); zcoef = rand_real();\n\t\tnorm = sqrt(icoef * icoef + zcoef * zcoef);\n\t\ticoef /= norm; zcoef /= norm;\n\t\tU = icoef * Identity + 1.i*zcoef * Z;\n\t\tEigen::VectorXcd diag = U.diagonal();\n\t\tfunc(target, (CTYPE*)diag.data(), state, dim);\n\t\ttest_state = get_expanded_eigen_matrix_with_identity(target, U, n) * test_state;\n\t\tstate_equal(state, test_state, dim, \"single diagonal gate\");\n\t}\n\trelease_quantum_state(state);\n}\n\nTEST(UpdateTest, SingleDiagonalMatrixTest) {\n\ttest_single_diagonal_matrix_gate(single_qubit_diagonal_matrix_gate);\n\ttest_single_diagonal_matrix_gate(single_qubit_diagonal_matrix_gate_single_unroll);\n#ifdef _OPENMP\n\ttest_single_diagonal_matrix_gate(single_qubit_diagonal_matrix_gate_parallel_unroll);\n#endif\n#ifdef _USE_SIMD\n\ttest_single_diagonal_matrix_gate(single_qubit_diagonal_matrix_gate_single_simd);\n#ifdef _OPENMP\n\ttest_single_diagonal_matrix_gate(single_qubit_diagonal_matrix_gate_parallel_simd);\n#endif\n#endif\n}\n\nvoid test_single_phase_gate(std::function<void(UINT, CTYPE, CTYPE*, ITYPE)> func) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\n\tEigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U;\n\n\tUINT target;\n\tdouble angle;\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state(state, dim);\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\tEigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\t// single qubit phase matrix gate\n\t\ttarget = rand_int(n);\n\t\tangle = rand_real();\n\t\tU << 1, 0, 0, cos(angle) + 1.i*sin(angle);\n#ifdef _MSC_VER\n\t\tCTYPE t = cos(angle) + 1.i*sin(angle);\n#else\n\t\tCTYPE t = cos(angle) + 1.j*sin(angle);\n#endif\n\t\tfunc(target, t, state, dim);\n\t\ttest_state = get_expanded_eigen_matrix_with_identity(target, U, n) * test_state;\n\t\tstate_equal(state, test_state, dim, \"single phase gate\");\n\t}\n\trelease_quantum_state(state);\n}\n\n\nTEST(UpdateTest, SinglePhaseGateTest) {\n\ttest_single_phase_gate(single_qubit_phase_gate);\n\ttest_single_phase_gate(single_qubit_phase_gate_single_unroll);\n#ifdef _OPENMP\n\ttest_single_phase_gate(single_qubit_phase_gate_parallel_unroll);\n#endif\n#ifdef _USE_SIMD\n\ttest_single_phase_gate(single_qubit_phase_gate_single_simd);\n#ifdef _OPENMP\n\ttest_single_phase_gate(single_qubit_phase_gate_parallel_simd);\n#endif\n#endif\n}\n", "meta": {"hexsha": "6b0c328e42b1ec196ca90fdb5a59cea6bfef0695", "size": 3577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/csim/test_update_diagonal.cpp", "max_stars_repo_name": "kamakiri01/qulacs", "max_stars_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 260.0, "max_stars_repo_stars_event_min_datetime": "2018-10-13T15:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T11:03:58.000Z", "max_issues_repo_path": "test/csim/test_update_diagonal.cpp", "max_issues_repo_name": "kamakiri01/qulacs", "max_issues_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 182.0, "max_issues_repo_issues_event_min_datetime": "2018-10-14T02:29:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:23:18.000Z", "max_forks_repo_path": "test/csim/test_update_diagonal.cpp", "max_forks_repo_name": "kamakiri01/qulacs", "max_forks_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 88.0, "max_forks_repo_forks_event_min_datetime": "2018-10-10T03:46:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T21:56:05.000Z", "avg_line_length": 29.5619834711, "max_line_length": 100, "alphanum_fraction": 0.7422421023, "num_tokens": 1028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.528210512286134}}
{"text": "// Copyright (c) 2017 Franka Emika GmbH\n// Use of this source code is governed by the Apache-2.0 license, see LICENSE\n#include <franka/duration.h>\n#include <franka/exception.h>\n#include <franka/model.h>\n#include <franka/robot.h>\n#include <Eigen/Dense>\n#include <array>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include \"examples_common.h\"\n\n/**\n * @example cartesian_impedance_control.cpp\n * An example showing a simple cartesian impedance controller without inertia shaping\n * that renders a spring damper system where the equilibrium is the initial configuration.\n * After starting the controller try to push the robot around and try different stiffness levels.\n *\n * @warning collision thresholds are set to high values. Make sure you have the user stop at hand!\n */\n\n\n\nvoid print_position(std::array<double, 42> initial_pose) {\n  std::cout << \"this is jacobian position\" << std::endl;\n  for (int i = 0; i < 42; i++) {\n    std::cout << initial_pose[i] << \"  \";\n    if ((i + 1) % 7 == 0)\n      std::cout << std::endl;\n  }\n}\n\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    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}\n\nint main(int argc, char** argv) {\n  // Check whether the required arguments were passed\n  if (argc != 2) {\n    std::cerr << \"Usage: \" << argv[0] << \" <robot-hostname>\" << std::endl;\n    return -1;\n  }\n\n  // Compliance parameters\n  const double translational_stiffness{150.0};\n  const double rotational_stiffness{10.0};\n  Eigen::MatrixXd stiffness(6, 6), damping(6, 6);\n  stiffness.setZero();\n  stiffness.topLeftCorner(3, 3) << translational_stiffness * Eigen::MatrixXd::Identity(3, 3);\n  stiffness.bottomRightCorner(3, 3) << rotational_stiffness * Eigen::MatrixXd::Identity(3, 3);\n  damping.setZero();\n  damping.topLeftCorner(3, 3) << 2.0 * sqrt(translational_stiffness) *\n                                     Eigen::MatrixXd::Identity(3, 3);\n  damping.bottomRightCorner(3, 3) << 2.0 * sqrt(rotational_stiffness) *\n                                         Eigen::MatrixXd::Identity(3, 3);\n\n  try {\n    // connect to robot\n    franka::Robot robot(argv[1]);\n    setDefaultBehavior(robot);\n    // load the kinematics and dynamics model\n    franka::Model model = robot.loadModel();\n    franka::RobotState initial_state = robot.readOnce();\n\n    // equilibrium point is the initial position\n    Eigen::Affine3d initial_transform(Eigen::Matrix4d::Map(initial_state.O_T_EE.data()));\n    Eigen::Vector3d position_d(initial_transform.translation());\n    Eigen::Quaterniond orientation_d(initial_transform.linear());\n    // set collision behavior\n    robot.setCollisionBehavior({{100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0}},\n                               {{100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0}},\n                               {{100.0, 100.0, 100.0, 100.0, 100.0, 100.0}},\n                               {{100.0, 100.0, 100.0, 100.0, 100.0, 100.0}});\n\n    // define callback for the torque control loop\n    std::function<franka::Torques(const franka::RobotState&, franka::Duration)>\n        impedance_control_callback = [&](const franka::RobotState& robot_state,\n                                         franka::Duration /*duration*/) -> franka::Torques {\n      // get state variables\n\n    \n      std::array<double, 7> coriolis_array = model.coriolis(robot_state);\n      std::array<double, 42> jacobian_array =\n          model.zeroJacobian(franka::Frame::kEndEffector, robot_state);\n      // print the jacobian array\n      // print_position(jacobian_array);\n\n      // convert to Eigen\n      Eigen::Map<const Eigen::Matrix<double, 7, 1>> coriolis(coriolis_array.data());\n      // jacobian matrix\n      Eigen::Map<const Eigen::Matrix<double, 6, 7>> jacobian(jacobian_array.data());\n\n      Eigen::Matrix<double, 3, 7> half_jacobian;\n      // only get three lines\n      for (int i = 0; i < half_jacobian.rows(); i++) {\n        for (int j = 0; j < half_jacobian.cols(); j++) {\n          half_jacobian(i, j) = jacobian(i, j);\n        }\n      }\n\n      Eigen::Map<const Eigen::Matrix<double, 7, 1>> q(robot_state.q.data());\n      Eigen::Map<const Eigen::Matrix<double, 7, 1>> dq(robot_state.dq.data());\n      Eigen::Affine3d transform(Eigen::Matrix4d::Map(robot_state.O_T_EE.data()));\n      Eigen::Vector3d position(transform.translation());\n      Eigen::Quaterniond orientation(transform.linear());\n\n      // compute error to desired equilibrium pose\n      Eigen::MatrixXf pse_inverse_jacobian=pseudoinverse(half_jacobian);\n      \n      double phi_sin = 2 * M_PI * std::sin(0.5 * M_PI * time / 10);\n      double phi_sinDot = M_PI * M_PI * std::cos(0.5 * M_PI * time / 10) / 10;\n      double phi = phi_sin * std::sin(0.5 * M_PI * time / 10);\n      double phiDot = phi_sin * M_PI * std::cos(0.5 * M_PI * time / 10) / 10;\n      double phiDotDot = M_PI * phi_sinDot * std::cos(0.5 * M_PI * time / 10) / 10 -\n                         M_PI * M_PI * phi_sin * std::sin(0.5 * M_PI * time / 10) / (2 * 10 * 10);\n      double rx = r * std::cos(2 * phi + alpha) + 0 - r * std::cos(alpha);\n      double ry = r * std::sin(phi + alpha) + 0 - r * std::sin(alpha);\n\n    double drx = r * std::cos(2 * phi + alpha) + 0 - r * std::cos(alpha);\n      double dry = r * std::sin(phi + alpha) + 0 - r * std::sin(alpha);\n\n\n  //     float  drx(jj,1)=-2*r*sin(2*phi+alpha)*phiDot;\n  //  dry(jj,1)=r*cos(phi+alpha)*phiDot;\n  //  drz(jj,1)=0;\n      pse_inverse_jacobian*(half_jacobian*dq-dq)\n\n      // position error\n\n      std::cout << \"position: \" << position << std::endl;\n      std::cout << \"positiond: \" << position_d << std::endl;\n      std::cout << \"positiond: \" << position_d << std::endl;\n\n      for (int i = 0; i < dq.size(); i++) {\n        std::cout << \"dq \" << dq[i] << \"  \" << std::endl;\n      }\n\n      Eigen::Matrix<double, 6, 1> error;\n      error.head(3) << position - position_d;\n\n      // orientation error\n      // \"difference\" quaternion\n      if (orientation_d.coeffs().dot(orientation.coeffs()) < 0.0) {\n        orientation.coeffs() << -orientation.coeffs();\n      }\n      // \"difference\" quaternion\n      Eigen::Quaterniond error_quaternion(orientation.inverse() * orientation_d);\n      error.tail(3) << error_quaternion.x(), error_quaternion.y(), error_quaternion.z();\n      // Transform to base frame\n      error.tail(3) << -transform.linear() * error.tail(3);\n\n      // compute control\n      Eigen::VectorXd tau_task(7), tau_d(7);\n\n      // Spring damper system with damping ratio=1\n      // matrix transpose multiple\n      tau_task << jacobian.transpose() * (-stiffness * error - damping * (jacobian * dq));\n      tau_d << tau_task + coriolis;\n\n      std::array<double, 7> tau_d_array{};\n      Eigen::VectorXd::Map(&tau_d_array[0], 7) = tau_d;\n      return tau_d_array;\n    };\n    // start real-time control loop\n    std::cout << \"WARNING: Collision thresholds are set to high values. \"\n              << \"Make sure you have the user stop at hand!\" << std::endl\n              << \"After starting try to push the robot and see how it reacts.\" << std::endl\n              << \"Press Enter to continue...\" << std::endl;\n    std::cin.ignore();\n    robot.control(impedance_control_callback);\n\n  } catch (const franka::Exception& ex) {\n    // print exception\n    std::cout << ex.what() << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "dd7061aec337e54d6f23114523d14c5aedbf32ab", "size": 8099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/generate_ik_motion.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/generate_ik_motion.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/generate_ik_motion.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": 40.904040404, "max_line_length": 98, "alphanum_fraction": 0.6200765527, "num_tokens": 2332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5281958828371976}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n\n#include <boost/python.hpp>\n\n#include <scitbx/sym_mat3.h>\n#include <scitbx/array_family/versa.h>\n#include <scitbx/array_family/shared.h>\n#include <scitbx/array_family/accessors/c_grid.h>\n#include <boost/scoped_array.hpp>\n\nnamespace boost_python_meta_ext { struct holder {}; }\n\nextern \"C\" {\n\n  void\n  dgesdd_(\n    char const* jobz,\n    int const* m,\n    int const* n,\n    double* a,\n    int const* lda,\n    double* s,\n    double* u,\n    int const* ldu,\n    double* vt,\n    int const* ldvt,\n    double* work,\n    int const* lwork,\n    int* iwork,\n    int* info,\n    int jobz_len);\n\n  void\n  dgesvd_(\n    char const* jobu,\n    char const* jobvt,\n    int const* m,\n    int const* n,\n    double* a,\n    int const* lda,\n    double* s,\n    double* u,\n    int const* ldu,\n    double* vt,\n    int const* ldvt,\n    double* work,\n    int const* lwork,\n    int* info,\n    int jobu_len,\n    int jobvt_len);\n\n  void\n  dsyev_(\n    char const* jobz,\n    char const* uplo,\n    int const* n,\n    double* a,\n    int const* lda,\n    double* w,\n    double* work,\n    int const* lwork,\n    int* info,\n    int jobz_len,\n    int uplo_len);\n\n} // extern \"C\"\n\n#if defined(SCITBX_LAPACK_FEM)\n#  include <lapack_fem/selected.hpp>\n#endif\n\nnamespace scitbx { namespace lapack { namespace boost_python {\n\n#if defined(SCITBX_LAPACK_FEM)\n  lapack_fem::common cmn(0, 0);\n#endif\n\n  boost::python::object\n  dgesdd_wrapper(\n    af::ref<double, af::c_grid<2> > const& a,\n    bool use_fortran=false)\n  {\n    int m = a.accessor()[1];\n    int n = a.accessor()[0];\n    SCITBX_ASSERT(m > 0);\n    SCITBX_ASSERT(n > 0);\n    boost::python::object result;\n#if defined(SCITBX_LAPACK_FEM) || defined(SCITBX_LAPACK_FOR)\n    int p = std::min(m,n);\n    af::shared<double> s(p, 0.);\n    af::versa<double, af::c_grid<2> > u(af::c_grid<2>(p, m), 0.);\n    af::versa<double, af::c_grid<2> > vt(af::c_grid<2>(n, p), 0.);\n    boost::scoped_array<int> iwork(new int[8*p]);\n    int lwork = -1;\n    int info;\n    for(unsigned i_pass=0;i_pass<2;i_pass++) {\n      boost::scoped_array<double> work(new double[std::max(1,lwork)]);\n#endif\n      if (!use_fortran) {\n#if defined(SCITBX_LAPACK_FEM)\n        lapack_fem::dgesdd(\n          cmn,\n          /*jobz*/ \"S\",\n          m,\n          n,\n          a[0],\n          /*lda*/ m,\n          s[0],\n          u[0],\n          /*ldu*/ m,\n          vt[0],\n          /*ldvt*/ p,\n          work[0],\n          lwork,\n          iwork[0],\n          info);\n#else\n        return result;\n#endif\n      }\n      else {\n#if defined(SCITBX_LAPACK_FOR)\n        dgesdd_(\n          /*jobz*/ \"S\",\n          &m,\n          &n,\n          &a[0],\n          /*lda*/ &m,\n          &s[0],\n          &u[0],\n          /*ldu*/ &m,\n          &vt[0],\n          /*ldvt*/ &p,\n          &work[0],\n          &lwork,\n          &iwork[0],\n          &info,\n          /*jobz_len*/ 1);\n#else\n        return result;\n#endif\n      }\n#if defined(SCITBX_LAPACK_FEM) || defined(SCITBX_LAPACK_FOR)\n      if (i_pass == 0) {\n        lwork = static_cast<int>(work[0]);\n      }\n    }\n    result = boost::python::object(boost_python_meta_ext::holder());\n    result.attr(\"s\") = s;\n    result.attr(\"u\") = u;\n    result.attr(\"vt\") = vt;\n    result.attr(\"info\") = info;\n#endif\n    return result;\n  }\n\n  boost::python::object\n  dgesvd_wrapper(\n    af::ref<double, af::c_grid<2> > const& a,\n    bool use_fortran=false)\n  {\n    int m = a.accessor()[1];\n    int n = a.accessor()[0];\n    SCITBX_ASSERT(m > 0);\n    SCITBX_ASSERT(n > 0);\n    boost::python::object result;\n#if defined(SCITBX_LAPACK_FEM) || defined(SCITBX_LAPACK_FOR)\n    int p = std::min(m,n);\n    af::shared<double> s(p, 0.);\n    af::versa<double, af::c_grid<2> > u(af::c_grid<2>(p, m), 0.);\n    af::versa<double, af::c_grid<2> > vt(af::c_grid<2>(n, p), 0.);\n    int lwork = -1;\n    int info;\n    for(unsigned i_pass=0;i_pass<2;i_pass++) {\n      boost::scoped_array<double> work(new double[std::max(1,lwork)]);\n#endif\n      if (!use_fortran) {\n#if defined(SCITBX_LAPACK_FEM)\n        lapack_fem::dgesvd(\n          cmn,\n          /*jobu*/ \"S\",\n          /*jobvt*/ \"S\",\n          m,\n          n,\n          a[0],\n          /*lda*/ m,\n          s[0],\n          u[0],\n          /*ldu*/ m,\n          vt[0],\n          /*ldvt*/ p,\n          work[0],\n          lwork,\n          info);\n#else\n        return result;\n#endif\n      }\n      else {\n#if defined(SCITBX_LAPACK_FOR)\n        dgesvd_(\n          /*jobu*/ \"S\",\n          /*jobvt*/ \"S\",\n          &m,\n          &n,\n          &a[0],\n          /*lda*/ &m,\n          &s[0],\n          &u[0],\n          /*ldu*/ &m,\n          &vt[0],\n          /*ldvt*/ &p,\n          &work[0],\n          &lwork,\n          &info,\n          /*jobu_len*/ 1,\n          /*jobvt_len*/ 1);\n#else\n        return result;\n#endif\n      }\n#if defined(SCITBX_LAPACK_FEM) || defined(SCITBX_LAPACK_FOR)\n      if (i_pass == 0) {\n        lwork = static_cast<int>(work[0]);\n      }\n    }\n    result = boost::python::object(boost_python_meta_ext::holder());\n    result.attr(\"s\") = s;\n    result.attr(\"u\") = u;\n    result.attr(\"vt\") = vt;\n    result.attr(\"info\") = info;\n#endif\n    return result;\n  }\n\n  int\n  dsyev_wrapper(\n    std::string const& jobz,\n    std::string const& uplo,\n    af::ref<double, af::c_grid<2> > const& a,\n    af::ref<double> const& w,\n    bool use_fortran=false)\n  {\n    SCITBX_ASSERT(a.accessor().is_square());\n    int n = a.accessor()[0];\n    SCITBX_ASSERT(w.size() == n);\n    int info = 99;\n#if defined(SCITBX_LAPACK_FEM) || defined(SCITBX_LAPACK_FOR)\n    int lwork = -1;\n    bool active = false;\n    for(unsigned i_pass=0;i_pass<2;i_pass++) {\n      boost::scoped_array<double> work(new double[std::max(1,lwork)]);\n#endif\n      if (!use_fortran) {\n#if defined(SCITBX_LAPACK_FEM)\n        lapack_fem::dsyev(\n          cmn,\n          fem::str_cref(jobz.data(), jobz.size()),\n          fem::str_cref(uplo.data(), uplo.size()),\n          n,\n          a[0],\n          /*lda*/ n,\n          w[0],\n          work[0],\n          lwork,\n          info);\n        active = true;\n#endif\n      }\n      else {\n#if defined(SCITBX_LAPACK_FOR)\n        dsyev_(\n          jobz.data(),\n          uplo.data(),\n          &n,\n          &a[0],\n          /*lda*/ &n,\n          &w[0],\n          &work[0],\n          &lwork,\n          &info,\n          jobz.size(),\n          uplo.size());\n        active = true;\n#endif\n      }\n#if defined(SCITBX_LAPACK_FEM) || defined(SCITBX_LAPACK_FOR)\n      if (!active) break;\n      if (i_pass == 0) {\n        TBXX_ASSERT(info == 0);\n        lwork = static_cast<int>(work[0]);\n      }\n    }\n#endif\n    return info;\n  }\n\n  // simlar to time_eigensystem_real_symmetric()\n  scitbx::vec3<double>\n  time_dsyev(\n    scitbx::sym_mat3<double> const& m,\n    std::size_t n_repetitions,\n    bool use_fortran=false)\n  {\n    SCITBX_ASSERT(n_repetitions % 2 == 0);\n    scitbx::vec3<double> result(0,0,0);\n    int info = 99;\n    for(std::size_t i=0;i<n_repetitions/2;i++) {\n      for(std::size_t j=0;j<2;j++) {\n        scitbx::vec3<double> w;\n        scitbx::mat3<double> a(m);\n        info = dsyev_wrapper(\"V\", \"U\",\n          af::ref<double, af::c_grid<2> >(a.begin(), af::c_grid<2>(3,3)),\n          w.ref(), use_fortran);\n        if (j == 0) result += w;\n        else        result -= w;\n      }\n    }\n    SCITBX_ASSERT(info == 0);\n    return result / static_cast<double>(n_repetitions);\n  }\n\n  bool\n  fem_is_available()\n  {\n#if defined(SCITBX_LAPACK_FEM)\n    return true;\n#else\n    return false;\n#endif\n  }\n\n  bool\n  for_is_available()\n  {\n#if defined(SCITBX_LAPACK_FOR)\n    return true;\n#else\n    return false;\n#endif\n  }\n\n  void\n  wrap()\n  {\n    using namespace boost::python;\n\n    def(\"fem_is_available\", fem_is_available);\n    def(\"for_is_available\", for_is_available);\n\n    def(\"lapack_dgesdd\", dgesdd_wrapper, (\n      arg(\"a\"), arg(\"use_fortran\")=false));\n    def(\"lapack_dgesvd\", dgesvd_wrapper, (\n      arg(\"a\"), arg(\"use_fortran\")=false));\n    def(\"lapack_dsyev\", dsyev_wrapper, (\n      arg(\"jobz\"), arg(\"uplo\"), arg(\"a\"), arg(\"w\"), arg(\"use_fortran\")=false));\n\n    def(\"time_lapack_dsyev\", time_dsyev, (\n      arg(\"m\"), arg(\"n_repetitions\"), arg(\"use_fortran\")=false));\n  }\n\n}}} // namespace scitbx::lapack::boost_python\n", "meta": {"hexsha": "25fc115b66094082acee205da1b23b24865be6df", "size": 8185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/linalg/boost_python/lapack_fem_bpl.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/linalg/boost_python/lapack_fem_bpl.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/linalg/boost_python/lapack_fem_bpl.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 22.5482093664, "max_line_length": 79, "alphanum_fraction": 0.5296273671, "num_tokens": 2596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.5281958828371975}}
{"text": "#include \"polyscope/polyscope.h\"\n\n#include <iostream>\n\n#include \"geometrycentral/geometry.h\"\n#include \"geometrycentral/halfedge_mesh.h\"\n#include \"geometrycentral/linear_solvers.h\"\n#include \"geometrycentral/polygon_soup_mesh.h\"\n\n#include <Eigen/SparseLU>\n\n#include \"args/args.hxx\"\n#include \"json/json.hpp\"\n\n#define GLM_ENABLE_EXPERIMENTAL\n#include \"glm/gtx/string_cast.hpp\"\n\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n\n\nusing namespace geometrycentral;\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::string;\n\nclass CatData {\n  // Initialized stuff\n  Geometry<Euclidean>* geom;\n  HalfedgeMesh* mesh;\n  std::string niceName;\n\n  // Original mesh information\n  VertexData<size_t> vInd;\n  size_t nVerts;\n  size_t nHalfedges;\n  size_t dim;\n  VertexData<double> angleDefects;\n  HalfedgeData<size_t> hInd;\n  CornerData<size_t> cInd;\n\npublic:\n  // Derived Information\n  HalfedgeData<double> finalCurvature;\n  VertexData<double> multiplier;\n\n  HalfedgeData<double> d;\n  HalfedgeData<double> alpha;\n\n  EdgeData<double> netEdgeCurvature;\n  CornerData<double> cornerAngle;\n  CornerData<char> badCorners;\n\n  // Solves the optimization problem\n  void solveOptMatrix() {\n    Eigen::SparseMatrix<double> d0 = Eigen::SparseMatrix<double>(dim, dim);\n    std::vector<Eigen::Triplet<double>> tripletList;\n    Vector<double> rhs = Vector<double>(dim);\n    // cout << dim << endl;\n    for (size_t i = 0; i < nHalfedges; i++) {\n      tripletList.emplace_back(i, i, 1.);\n      rhs[i] = 0.;\n    }\n\n    for (size_t i = nHalfedges; i < dim; i++) {\n      rhs[i] = angleDefects[mesh->vertex(i - nHalfedges)];\n    }\n    for (EdgePtr e : mesh->edges()) {\n      HalfedgePtr h1 = e.halfedge();\n      HalfedgePtr h2 = h1.twin();\n      size_t v1 = vInd[h1.vertex()];\n      size_t v2 = vInd[h2.vertex()];\n      tripletList.emplace_back(nHalfedges + v1, hInd[h1], 1);\n      tripletList.emplace_back(nHalfedges + v1, hInd[h2], 1);\n      tripletList.emplace_back(nHalfedges + v2, hInd[h1], 1);\n      tripletList.emplace_back(nHalfedges + v2, hInd[h2], 1);\n\n      tripletList.emplace_back(hInd[h1], nHalfedges + v1, 1);\n      tripletList.emplace_back(hInd[h2], nHalfedges + v1, 1);\n      tripletList.emplace_back(hInd[h1], nHalfedges + v2, 1);\n      tripletList.emplace_back(hInd[h2], nHalfedges + v2, 1);\n    }\n    d0.setFromTriplets(tripletList.begin(), tripletList.end());\n    cout << \"Matrix built\" << endl;\n\n    Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n    solver.compute(d0);\n    if (solver.info() != Eigen::Success) {\n      cout << \"solving failed\" << endl;\n    }\n    Vector<double> solution = solver.solve(rhs);\n    if (solver.info() != Eigen::Success) {\n      cout << \"solving failed\";\n    }\n    // cout << \"Matrix solved\";\n    for (size_t i = 0; i < nHalfedges; i++) {\n      finalCurvature[i] = solution[i];\n      //cout << solution[i] << endl;\n    }\n    for (size_t i = nHalfedges; i < dim; i++) {\n      multiplier[i - nHalfedges] = solution[i];\n    }\n    polyscope::getSurfaceMesh(niceName)->addQuantity(\"Original Curvature\", angleDefects);\n    polyscope::getSurfaceMesh(niceName)->addQuantity(\"Curvature change\", finalCurvature);\n    polyscope::getSurfaceMesh(niceName)->addQuantity(\"Lagrange Multiplier\", multiplier);\n    return;\n  }\n  void checkAngles()\n  {\n    size_t bad = 0;\n    for (CornerPtr c: mesh->corners())\n    {\n      cornerAngle[c] =  geom->angle(c);\n    }\n    for (CornerPtr c: mesh->corners())\n    {\n      HalfedgePtr h = c.halfedge();\n      cornerAngle[c] += finalCurvature[h];\n      cornerAngle[c.next()] += finalCurvature[h];\n    }\n    cout << bad << endl;\n    for (CornerPtr c: mesh->corners())\n    {\n      if (cornerAngle[c] < 0 || cornerAngle[c] > 2 * M_PI)\n      {\n        bad++;\n        badCorners[c] = true;\n      }\n    }\n    cout << bad << endl;\n  }\n  CatData(std::string filename) {\n    niceName = polyscope::utilities::guessNiceNameFromPath(filename);\n    mesh = new HalfedgeMesh(PolygonSoupMesh(filename), geom);\n    polyscope::registerSurfaceMesh(niceName, geom);\n\n    vInd = mesh->getVertexIndices();\n    nVerts = mesh->nVertices();\n    hInd = mesh->getHalfedgeIndices();\n    nHalfedges = mesh->nHalfedges();\n    cInd = mesh->getCornerIndices();\n    dim = nVerts + nHalfedges;\n\n    finalCurvature = HalfedgeData<double>(mesh);\n    multiplier = VertexData<double>(mesh);\n    d = HalfedgeData<double>(mesh);\n    alpha = HalfedgeData<double>(mesh);\n    netEdgeCurvature = EdgeData<double>(mesh);\n    cornerAngle = CornerData<double>(mesh);\n    badCorners = CornerData<char>(mesh, false);\n\n    geom->getVertexAngleDefects(angleDefects);\n    solveOptMatrix();\n    checkAngles();\n    polyscope::getSurfaceMesh(niceName)->addQuantity(\"Central angles\", alpha);\n    delete geom;\n    delete mesh;\n  }\n};\n\n\nint main(int argc, char** argv) {\n  // Configure the argument parser\n  /*args::ArgumentParser parser(\"A simple demo of Polyscope.\\nBy \"\n                              \"Nick Sharp (nsharp@cs.cmu.edu)\",\n                              \"\");\n  args::PositionalList<string> files(parser, \"files\", \"One or more files to visualize\");\n  */\n  // Options\n  polyscope::options::autocenterStructures = true;\n  // Initialize polyscope\n  polyscope::init();\n  CatData* c = new CatData(\"C:/spot1.obj\");\n  delete c;\n  // Show the gui\n  polyscope::show();\n\n  return 0;\n}\n", "meta": {"hexsha": "684089d8e4547557ae6c0edc73ed448da8353eef", "size": 5288, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "old/CAT-Flattening-v2.cpp", "max_stars_repo_name": "elu00/CATOpt", "max_stars_repo_head_hexsha": "5ea6e09b98488745d8f82a95bc34db14270ee5d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "old/CAT-Flattening-v2.cpp", "max_issues_repo_name": "elu00/CATOpt", "max_issues_repo_head_hexsha": "5ea6e09b98488745d8f82a95bc34db14270ee5d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old/CAT-Flattening-v2.cpp", "max_forks_repo_name": "elu00/CATOpt", "max_forks_repo_head_hexsha": "5ea6e09b98488745d8f82a95bc34db14270ee5d7", "max_forks_repo_licenses": ["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.2154696133, "max_line_length": 89, "alphanum_fraction": 0.651096823, "num_tokens": 1465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5281958773765145}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"functions/unary_minus.hh\"\n#include \"functions/addition.hh\"\n#include \"functions/std_functions.hh\"\n#include \"functions/zero.hh\"\n#include \"functions/polynomial.hh\"\n#include \"functions/function_matrix.hh\"\n#include \"functions/division.hh\"\n#include \"functions/all_simplifications.hh\"\n\nBOOST_AUTO_TEST_CASE(simplification_ambiguities_test) {\n  using namespace manifolds;\n\n// commas in template parameter packs in macros are hard...\n// hence this otherwise dumb-looking define\n#define C ,\n\n#define TESTCASE(code)                                                         \\\n  static_assert(Simplifies<code>::value, \"Simplification failed\")\n\n  // Tests ambiguity of add_nadd and nadd_add and var_add\n  TESTCASE(Addition<UnaryMinus<UnaryMinus<Sin> > C UnaryMinus<Sin> >);\n  // Tests ambiguity of add_f_z and add_z_f and add_f_f and var_add\n  TESTCASE(Addition<Zero C Zero>);\n  // Tests ambiguity of add_f_p_1 and var_add\n  TESTCASE(Addition<Sin C Polynomial<double C int_<1> > >);\n  // Tests ambiguity of com_add and var_com\n  TESTCASE(Composition<Addition<Sin C Cos> C Tan>);\n  // Tests com_fm_fm and var_com\n  TESTCASE(\n      Composition<FunctionMatrix<int_<1> C int_<2> C Variable<0> C Variable<1> >\n                      C FunctionMatrix<int_<1> C int_<2> C Sin C Cos> >);\n  // Tests com_v_0_f and com_v_fm and var_com\n  TESTCASE(Composition<\n      Variable<0> C FunctionMatrix<int_<2> C int_<1> C Tan C Cos> >);\n  // Tests com_mult_f and var_com\n  TESTCASE(Composition<Multiplication<Variable<1> C Variable<0> > C\n                           FunctionMatrix<int_<2> C int_<1> C Sin C Cos> >);\n  // Tests com_p_1_fs and com_p1_p2 and var_com\n  TESTCASE(\n      Composition<Polynomial<double C int_<1> > C Polynomial<int C int_<4> > >);\n  // Tests com_p_1_fs and and com_p_add_fs and var_com\n  TESTCASE(Composition<Polynomial<int C int_<1> > C Addition<Sin C Sin> >);\n  // Tests com_t_fm and var_com\n  TESTCASE(\n      Composition<Transpose C FunctionMatrix<int_<2> C int_<1> C Cos C Sin> >);\n  // Tests com_z_f and var_com\n  TESTCASE(Composition<Zero C Zero>);\n  // Tests mult_div_dif and mult_div_f\n  TESTCASE(Multiplication<Division<Sin C Cos> C Division<Cos C Sin> >);\n  // Tests mult_f1_com_pow_fm_f2_f1 and var_mult and mult_um_f1_f2\n  TESTCASE(Multiplication<UnaryMinus<Cos> C Composition<\n      Pow C FunctionMatrix<int_<1> C int_<2> C Cos C UnaryMinus<Cos> > > >);\n  // Tests add_p1_p2 and add_f_p_1\n  TESTCASE(Addition<Polynomial<int C int_<12> > C Polynomial<int C int_<1> > >);\n  // Tests um_um_f and um_f\n  TESTCASE(UnaryMinus<UnaryMinus<Sin> >);\n  // Tests mult_com_p1_fs_p2_1 and mult_com_p_f_f and\n  // var_com_f1_fs_com_f2_fs\n  TESTCASE(Multiplication<Composition<Polynomial<int C int_<2> > C Composition<\n      Polynomial<int C int_<2> > C Sin> > C\n                              Composition<Polynomial<int C int_<2> > C Sin> >);\n  // Tests mult_z_f and var_f_com_p_f\n  TESTCASE(\n      Multiplication<Zero C Composition<Polynomial<int C int_<2> > C Zero> >);\n  // Tests add_z_f and add_nadd\n  TESTCASE(Addition<Zero C UnaryMinus<Zero> >);\n  // Tests add_z_f and add_f_p_1\n  TESTCASE(Addition<Zero C Polynomial<int C int_<1> > >);\n  // Tests add_f_p_1 and add_f_f\n  TESTCASE(Addition<Polynomial<int C int_<1> > C Polynomial<int C int_<1> > >);\n  // Tests um_com_f_fs and um_f\n  TESTCASE(UnaryMinus<Composition<Polynomial<int C int_<2> > C Sin> >);\n  // Tests com_div_fs, var_com\n  TESTCASE(Composition<Division<Sin C Cos> C Polynomial<int C int_<12> > >);\n  // Tests mult_cos_cos and mult_f_f and var_mult\n  TESTCASE(Multiplication<Cos C Cos>);\n  // Tests var_com_f1_fs_com_f2_fs and var_add and add_f_f\n  TESTCASE(Addition<Composition<Polynomial<int C int_<3> > C Cos> C\n                        Composition<Polynomial<int C int_<3> > C Cos> >);\n  // Tests var_com_f1_fs_com_f2_fs and var_com\n  TESTCASE(Composition<Composition<Polynomial<int C int_<3> > C Cos> C\n                           Composition<Polynomial<int C int_<3> > C Cos> >);\n  // Tests var_grp and var_com_f1_fs_com_f2_fs\n  TESTCASE(Group<Composition<Polynomial<int C int_<4> > C Cos> C\n                     Composition<Polynomial<int C int_<4> > C Cos> >);\n  // Tests var_com_f1_fs_com_f2_fs and var_mult and mult_f_f\n  TESTCASE(Multiplication<Composition<Polynomial<int C int_<3> > C Cos> C\n                              Composition<Polynomial<int C int_<3> > C Cos> >);\n  // Tests var_com_f1_fs_com_f2_fs and add_com_p_f_f\n  TESTCASE(\n      Addition<Composition<Polynomial<int C int_<3> > C\n                               Composition<Polynomial<int C int_<2> > C Sin> > C\n                   Composition<Polynomial<int C int_<2> > C Sin> >);\n  // Tests var_com_f1_fs_com_f2_fs and mult_com_p_f_f\n  TESTCASE(Multiplication<Composition<Polynomial<int C int_<3> > C Composition<\n      Polynomial<int C int_<2> > C Sin> > C\n                              Composition<Polynomial<int C int_<2> > C Sin> >);\n  // Tests add_f_z and nadd_add\n  TESTCASE(Addition<UnaryMinus<Zero> C Zero>);\n  // Tests com_z_z\n  TESTCASE(Composition<Zero C Zero>);\n\n  TESTCASE(Multiplication<Zero C IntegralPolynomial<1> >);\n}\n", "meta": {"hexsha": "a8d7a0286472a51f6c7995d84ea44559b149be3b", "size": 5114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_simplification_ambiguities.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_simplification_ambiguities.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_simplification_ambiguities.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": 48.2452830189, "max_line_length": 80, "alphanum_fraction": 0.6906531091, "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5281958772367802}}
{"text": "/**\n    @file bayes_classifier.cpp\n\n    @author Terence Henriod\n\n    Project 1: Bayesian Minimum Error Classification\n\n    @brief Class implementations for the BayesClassifier defined in\n           bayes_classifier.h.\n\n    @version Original Code 1.00 (3/8/2014) - T. Henriod\n*/\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                   HEADER FILES / NAMESPACES\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n// Class Declaration\n#include \"bayes_classifier.h\"\n\n// Other Dependencies\n#include <cassert>\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>  // -I /home/thenriod/Desktop/cpp_libs/Eigen_lib\n\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n================================================================================\n                   CLASS FUNCTION IMPLEMENTATIONS\n================================================================================\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                   CONSTRUCTOR(S) / DESTRUCTOR\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n/**\nGameState\n\nThe default constructor for a game state. Constructs and initilizes an empty\nGameState.\n\n@pre\n-# The GameState object is given an appropriate identifier.\n\n@post\n-# A new, empty GameState will be initialized.\n\n@code\n@endcode\n*/\nBayesClassifier::BayesClassifier()\n{\n  // variables\n  int ndx = 0;\n  Eigen::Vector2d temp_mean;\n    temp_mean << 1, 1;\n  Eigen::Matrix2d temp_matrix;\n    temp_matrix << 1, 0,\n                   0, 1;\n\n  // initialize all members\n  for( ndx = 0; ndx < NUM_FEATURES; ndx++ )\n  {\n    prior_probabilities.push_back( double( 1.0 / NUM_FEATURES ) );\n  }\n  for( ndx = 0; ndx < NUM_FEATURES; ndx++ )\n  {\n    mean_vectors.push_back( temp_mean );\n  }\n  for( ndx = 0; ndx < NUM_FEATURES; ndx++ )\n  {\n    covariance_matrices.push_back( temp_matrix );\n  }\n  assumption_case_ = CASE_THREE;\n\n  // no return - constructor\n}\n\n\nBayesClassifier::BayesClassifier( const BayesClassifier& other )\n{\n  // no return - copy constructor\n}\n\n\nBayesClassifier& BayesClassifier::operator=( const BayesClassifier& other )\n{\n  // return *this\n  return *this;\n}\n\n\nBayesClassifier::~BayesClassifier()\n{\n  // no return - destructor\n}\n\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                   MUTATORS\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n\nvoid BayesClassifier::clear()\n{\n  // no return - void\n}\n\n\nvoid BayesClassifier::setMean( const Eigen::Vector2d& new_mean_vector,\n                               const int which_class )\n{\n  // variables\n    // none\n\n  // set the appropriate mean vector\n  mean_vectors[which_class] = new_mean_vector;\n\n  // no return - void\n}\n\n\nvoid BayesClassifier::setCovariance(\n    const Eigen::Matrix2d& new_covariance_matrix,\n    const int which_class )\n{\n  // variables\n    // none\n\n  // set the appropriate covariance matrix\n  covariance_matrices[which_class] = new_covariance_matrix;\n\n  // case: the new case was case 1\n  if( assumption_case_ == CASE_ONE )\n  {\n    // update the variance\n    variance = covariance_matrices[CLASS_ONE]( 0, 0 );\n  }\n\n  // no return - void\n}\n\n\nvoid BayesClassifier::setPriorProbabilities( const double class_one_prior )\n{\n  // assert pre-conditions\n  assert( ( class_one_prior >= 0.0 ) && ( class_one_prior <= 1.0 ) );\n  // assert( class_one_prior == ( 1 - class_one_prior ) );  // hopefully doubles don't screw this up\n    // they do\n\n  // variables\n    // none\n\n  // set the new prior probability\n  prior_probabilities[0] = class_one_prior;\n  prior_probabilities[1] = 1 - class_one_prior;\n\n  // no return - void\n}\n\n\nvoid BayesClassifier::setAssumptionCase( const int new_case )\n{\n  // set the new case   TODO: automate this\n  assumption_case_ = new_case;\n\n  // case: the new case was case 1\n  if( assumption_case_ == CASE_ONE )\n  {\n    // update the variance\n    variance = covariance_matrices[CLASS_ONE]( 0, 0 );\n  }\n}\n\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                   ACCESSORS\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\nvoid BayesClassifier::performAnalysis( const string input_file,\n                                       const string output_file )\n{\n  // variables\n  fstream file;\n  TestData temp;\n  char delimiter;\n  int num_data = 0;\n  int ndx = 0;\n  int num_misclassified = 0;\n  double test_error_rate = 0.5;\n  double beta_start = 0.5;\n  vector<TestData> data;\n  Chernoff chernoff_bound;\n\n  // read in all of the data\n  file.clear();\n  file.open( input_file.c_str(), fstream::in );\n  while( file.good() )\n  {\n    // read in a line of data\n    file >> temp.feature_vector(0) >> delimiter\n         >> temp.feature_vector(1) >> delimiter\n         >> temp.actual_class;\n\n    // store the data\n    data.push_back( temp );\n\n    // count the data\n    num_data++;\n  }\n  file.close();\n\n  // classify all of the data\n  for( ndx = 0; ndx < num_data; ndx++ )\n  {\n    // classify an object\n    data[ndx].classified_as = assignToClass( data[ndx].feature_vector );\n\n    // case: it was classified correctly\n    if( data[ndx].classified_as == data[ndx].actual_class )\n    {\n      // mark and count this as a correct classification\n      data[ndx].correctly_classified = CORRECT;\n    }\n    // case: it was not classified correctly\n    else\n    {\n      // mark this as an incorrect classification\n      data[ndx].correctly_classified = INCORRECT;\n      num_misclassified++;\n    }\n  }\n\n  // compute the error rate of the test\n  test_error_rate = double( num_misclassified ) / double( num_data );\n\n  // find chernoff bound\n  chernoff_bound = findChernoffBound( beta_start, 0 );\n\n  // output the results to file\n  file.clear();\n  file.open( output_file.c_str(), fstream::out );\n  file << \"Number of data: \" << ( num_data - 1 ) << endl\n       << \"Number of incorrect classifications: \"\n           << num_misclassified << endl\n       << \"Test Sample Error Rate: \" << test_error_rate << endl\n       << \"Battacharyya bound: \" << findBattacharyyaBound() << endl\n       << \"Chernoff bound: \" << chernoff_bound.bound << endl\n       << \"         beta*: \" << chernoff_bound.beta << endl;\n  for( ndx = 0; ndx < num_data; ndx++ )\n  {\n    // write the delimited data to the file\n    file << data[ndx].feature_vector(0) << \", \"\n         << data[ndx].feature_vector(1) << \", \"\n         << data[ndx].actual_class << \", \"\n         << data[ndx].classified_as << \", \"\n         << data[ndx].correctly_classified << endl;\n  }\n  file.close();\n\n  // no return - void\n}\n\n\nstring BayesClassifier::assignToClass( Eigen::Vector2d& input_vector )\n{\n  // variables\n  string classification_result;\n  double discriminant_difference = 0;\n\n  // calculate the difference of the discriminants\n  discriminant_difference = calculateDiscriminant( input_vector, CLASS_ONE ) -\n                            calculateDiscriminant( input_vector, CLASS_TWO );\n\n  // case: the difference has a positive result\n  if( discriminant_difference > 0 )\n  {\n    // the object is likely in class one\n    classification_result = \"ONE\";\n  }\n  // case: the difference has a negative result\n  else\n  {\n    // the object is likely in class two\n    classification_result = \"TWO\";\n  }\n\n  // return the resulting assignment\n  return classification_result;\n}\n\n\ndouble BayesClassifier::calculateDiscriminant(\n    const Eigen::Vector2d& input_vector,\n    const int which_class )\n{\n  // variables\n  double discriminant_result = 0;\n  double first_sum_term = 0;\n  double second_sum_term = 0;\n  double third_sum_term = 0;\n  double fourth_sum_term = 0;\n  double fifth_sum_term = 0;\n  Eigen::Vector2d mean;\n  Eigen::Matrix2d inverse_covariance_matrix;\n  Eigen::Vector2d intermediate_row;\n  Eigen::Vector2d intermediate_col;\n  Eigen::Matrix2d intermediate_mat;\n\n  // get the appropriate mean ready\n  mean = mean_vectors[which_class];\n\n  // prepare an inverse of the covariance matrix for the computations\n  inverse_covariance_matrix = covariance_matrices[which_class].inverse();\n\n\n  // case: the assumptions are not that of case 1\n  if( assumption_case_ != CASE_ONE )\n  {\n    // compute the first summative term of the discriminant function\n    intermediate_mat = -0.5 * inverse_covariance_matrix;\n    intermediate_row = ( input_vector.transpose() * intermediate_mat );\n    first_sum_term = intermediate_row.dot( input_vector );\n\n    // compute the second summative term of the discriminant function\n    second_sum_term = ( inverse_covariance_matrix * mean ).transpose().dot( input_vector );\n\n    // compute the third summative term of the discriminant function\n    intermediate_row = -0.5 * mean;\n    intermediate_row = intermediate_row.transpose() * inverse_covariance_matrix;\n    third_sum_term = intermediate_row.transpose().dot( mean );\n\n    // compute the fourth summative term of the discriminant function\n    fourth_sum_term = -0.5 *\n                      log( covariance_matrices[which_class].determinant() );\n  }\n  // case: we are assuming case 1 assumptions\n  else\n  {\n    // compute the first term ( 1/s^2 * mean * x )\n    intermediate_row = ( 1.0 / variance ) * mean;\n    first_sum_term = intermediate_row.transpose().dot( input_vector );\n\n    // compute the second term\n    intermediate_row = ( -1.0 / ( 2 * variance ) ) * mean;\n    second_sum_term = intermediate_row.transpose().dot( mean );\n  }\n\n  // compute the last summative term of the discriminant function\n  fifth_sum_term = log( prior_probabilities[which_class] );\n\n\n  // sum the terms to get the discriminant result\n  discriminant_result = first_sum_term + second_sum_term + third_sum_term +\n                        fourth_sum_term + fifth_sum_term;\n\n  // return the discriminant result\n  return discriminant_result;\n}\n\n\nChernoff BayesClassifier::findChernoffBound( double beta_star, int level )\n{\n  // variables\n  Chernoff chernoff_bound;\n    chernoff_bound.beta = beta_star;\n  Chernoff left_attempt;\n  Chernoff right_attempt;\n  double beta_increment = 0.0249999;\n  double prior_product = 0.0;\n  double kappa_of_beta = 0;\n\n  // compute the prior product\n  prior_product = pow( prior_probabilities[0], beta_star ) *\n                  pow( prior_probabilities[1], ( 1.0 - beta_star ) );\n\n  // kappa( beta* )\n  kappa_of_beta = kappaF( beta_star );\n\n  // compute the Chernoff bound\n  chernoff_bound.bound = prior_product * exp( -1.0 * kappa_of_beta );\n\n  // case: we aren't 1000 levels deep\n  if( level < 20 )\n  {\n    // find two different possible bounds\n    left_attempt = findChernoffBound( beta_star - beta_increment, level + 1 );\n    right_attempt = findChernoffBound( beta_star + beta_increment, level + 1 );\n\n    // test to find the lowest bound\n    if( left_attempt.bound < chernoff_bound.bound )\n    {\n      chernoff_bound = left_attempt;\n    }\n    if( right_attempt.bound < chernoff_bound.bound )\n    {\n      chernoff_bound = right_attempt;\n    }\n  }\n\n  // return the Chernoff bound\n  return chernoff_bound;\n}\n\n\ndouble BayesClassifier::findBattacharyyaBound()\n{\n  // variables\n  double battacharyya_bound = 1;\n  double kappa_of_beta = 0;\n  double root_prior_product = 0;\n  double root_covariance_det_product = 0;\n  Eigen::Vector2d mean_difference;\n  Eigen::Matrix2d covariance_sum;\n\n  // compute the square root term\n  root_prior_product = sqrt( prior_probabilities[0] * prior_probabilities[1] );\n\n  // compute kappa( 0.5 )\n  kappa_of_beta = kappaF( 0.5 );\n\n  // compute sqrt( P( w1 ) * P( w2 ) ) * e^( -kappa( 0.5 ) )\n  battacharyya_bound = root_prior_product * exp( -1.0 * kappa_of_beta );\n\n  // return the Battacharrya bound\n  return battacharyya_bound;\n}\n\n\ndouble BayesClassifier::kappaF( const double beta )\n{\n  // variables\n  double kappa_of_beta = 0;\n  double beta_complement = 1.0 - beta;\n  double beta_product_over_two = 0;\n  double root_prior_product = 0;\n  double root_covariance_det_product = 0;\n  double log_denominator = 0;\n  Eigen::Vector2d mean_difference;\n  Eigen::Vector2d intermediate_row;\n  Eigen::Matrix2d scaled_covariance_sum;\n\n  // compute (beta * beta^c) / 2\n  beta_product_over_two = ( beta * beta_complement ) / 2;\n\n  // compute the mean difference u2 - u1 (to be used later)\n  mean_difference = mean_vectors[0] - mean_vectors[1];\n\n  // compute the scaled covariance sum beta^c * E1 + beta * E2\n  // (to be used later)\n  scaled_covariance_sum = ( beta_complement * covariance_matrices[0] ) +\n                          ( beta * covariance_matrices[1] );\n\n  // compute the logarithm denominator (to be used later)\n  log_denominator = pow( covariance_matrices[0].determinant(),\n                         beta_complement );\n  log_denominator *= pow( covariance_matrices[1].determinant(),\n                          beta );\n\n  // compute the first term in the sum\n  intermediate_row = beta_product_over_two * mean_difference;\n  intermediate_row = intermediate_row.transpose() *\n                     scaled_covariance_sum.inverse();\n  kappa_of_beta = intermediate_row.transpose() * mean_difference;\n\n  // compute the second term in the sum\n  kappa_of_beta += 0.5 * log( scaled_covariance_sum.determinant() /\n                              log_denominator );  \n\n  // return the result\n  return kappa_of_beta;\n}\n\n\n", "meta": {"hexsha": "3275a2d120539b6a6adb1d4d3fa317fe44686e23", "size": 13350, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CS479/Project_1/code_files/bayes_classifier.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_1/code_files/bayes_classifier.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_1/code_files/bayes_classifier.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.0462184874, "max_line_length": 100, "alphanum_fraction": 0.6228464419, "num_tokens": 3257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5281958716363626}}
{"text": "// g++ -fopenmp -I .. -O3 -DNDEBUG -finline-limit=1000 benchmarkX.cpp -o b && time ./b\n#include <Eigen/Core>\n\nusing namespace std;\nUSING_PART_OF_NAMESPACE_EIGEN\n\n#ifndef MATTYPE\n#define MATTYPE MatrixXLd\n#endif\n\n#ifndef MATSIZE\n#define MATSIZE 400\n#endif\n\n#ifndef REPEAT\n#define REPEAT 100\n#endif\n\nint main(int argc, char *argv[])\n{\n\tMATTYPE I = MATTYPE::Ones(MATSIZE,MATSIZE);\n\tMATTYPE m(MATSIZE,MATSIZE);\n\tfor(int i = 0; i < MATSIZE; i++) for(int j = 0; j < MATSIZE; j++)\n\t{\n\t\tm(i,j) = (i+j+1)/(MATSIZE*MATSIZE);\n\t}\n\tfor(int a = 0; a < REPEAT; a++)\n\t{\n\t\tm = I + 0.0001 * (m + m*m);\n\t}\n\tcout << m(0,0) << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "18152e9e37a638eea0c63c3e94b490d19407b4bd", "size": 625, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "volna_init/external/eigen2/bench/benchmarkX.cpp", "max_stars_repo_name": "Devaraj-G/volna", "max_stars_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-07-08T23:53:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T11:55:28.000Z", "max_issues_repo_path": "volna_init/external/eigen2/bench/benchmarkX.cpp", "max_issues_repo_name": "Devaraj-G/volna", "max_issues_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-02T17:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-02T17:31:28.000Z", "max_forks_repo_path": "volna_init/external/eigen2/bench/benchmarkX.cpp", "max_forks_repo_name": "Devaraj-G/volna", "max_forks_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-02-05T19:34:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T08:46:34.000Z", "avg_line_length": 18.3823529412, "max_line_length": 86, "alphanum_fraction": 0.6352, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5281958659660775}}
{"text": "// Copyright (C) 2011  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n#include \"tester.h\"\n#include <dlib/svm_threaded.h>\n#include <dlib/data_io.h>\n#include \"create_iris_datafile.h\"\n#include <vector>\n#include <map>\n#include <sstream>\n\nnamespace  \n{\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n    dlib::logger dlog(\"test.svm_multiclass_trainer\");\n\n\n    class test_svm_multiclass_trainer : public tester\n    {\n        /*!\n            WHAT THIS OBJECT REPRESENTS\n                This object represents a unit test.  When it is constructed\n                it adds itself into the testing framework.\n        !*/\n    public:\n        test_svm_multiclass_trainer (\n        ) :\n            tester (\n                \"test_svm_multiclass_trainer\",       // the command line argument name for this test\n                \"Run tests on the svm_multiclass_linear_trainer stuff.\", // the command line argument description\n                0                     // the number of command line arguments for this test\n            )\n        {\n        }\n\n\n        void test_prior ()\n        {\n            print_spinner();\n            typedef matrix<double,4,1> sample_type;\n            typedef linear_kernel<sample_type> kernel_type;\n\n            std::vector<sample_type> samples;\n            std::vector<int> labels;\n\n            for (int i = 0; i < 4; ++i)\n            {\n                if (i==2)\n                    ++i;\n                for (int iter = 0; iter < 5; ++iter)\n                {\n                    sample_type samp;\n                    samp = 0;\n                    samp(i) = 1;\n                    samples.push_back(samp);\n                    labels.push_back(i);\n                }\n            }\n\n\n            svm_multiclass_linear_trainer<kernel_type,int> trainer;\n\n            multiclass_linear_decision_function<kernel_type,int> df = trainer.train(samples, labels);\n\n            //cout << \"test: \\n\" << test_multiclass_decision_function(df, samples, labels) << endl;\n            //cout << df.weights << endl;\n            //cout << df.b << endl;\n\n            std::vector<sample_type> samples2;\n            std::vector<int> labels2;\n            int i = 2;\n            for (int iter = 0; iter < 5; ++iter)\n            {\n                sample_type samp;\n                samp = 0;\n                samp(i) = 1;\n                samples2.push_back(samp);\n                labels2.push_back(i);\n                samples.push_back(samp);\n                labels.push_back(i);\n            }\n\n            trainer.set_prior(df);\n            trainer.set_c(0.1);\n            df = trainer.train(samples2, labels2);\n\n            matrix<double> res = test_multiclass_decision_function(df, samples, labels);\n            dlog << LINFO << \"test: \\n\" << res;\n            dlog << LINFO << df.weights;\n            dlog << LINFO << df.b;\n            DLIB_TEST((unsigned int)sum(diag(res))==samples.size());\n        }\n\n        void test_prior_sparse ()\n        {\n            print_spinner();\n            typedef std::map<unsigned long,double> sample_type;\n            typedef sparse_linear_kernel<sample_type> kernel_type;\n\n            std::vector<sample_type> samples;\n            std::vector<int> labels;\n\n            for (int i = 0; i < 4; ++i)\n            {\n                if (i==2)\n                    ++i;\n                for (int iter = 0; iter < 5; ++iter)\n                {\n                    sample_type samp;\n                    samp[i] = 1;\n                    samples.push_back(samp);\n                    labels.push_back(i);\n                }\n            }\n\n\n            svm_multiclass_linear_trainer<kernel_type,int> trainer;\n\n            multiclass_linear_decision_function<kernel_type,int> df = trainer.train(samples, labels);\n\n            //cout << \"test: \\n\" << test_multiclass_decision_function(df, samples, labels) << endl;\n            //cout << df.weights << endl;\n            //cout << df.b << endl;\n\n            std::vector<sample_type> samples2;\n            std::vector<int> labels2;\n            int i = 2;\n            for (int iter = 0; iter < 5; ++iter)\n            {\n                sample_type samp;\n                samp[i] = 1;\n                samp[i+10] = 1;\n                samples2.push_back(samp);\n                labels2.push_back(i);\n                samples.push_back(samp);\n                labels.push_back(i);\n            }\n\n            trainer.set_prior(df);\n            trainer.set_c(0.1);\n            df = trainer.train(samples2, labels2);\n\n            matrix<double> res = test_multiclass_decision_function(df, samples, labels);\n            dlog << LINFO << \"test: \\n\" << res;\n            dlog << LINFO << df.weights;\n            dlog << LINFO << df.b;\n            DLIB_TEST((unsigned int)sum(diag(res))==samples.size());\n        }\n\n        template <typename sample_type>\n        void run_test()\n        {\n            print_spinner();\n\n            typedef typename sample_type::value_type::second_type scalar_type;\n\n            std::vector<sample_type> samples;\n            std::vector<scalar_type> labels;\n\n            load_libsvm_formatted_data(\"iris.scale\",samples, labels);\n\n            DLIB_TEST(samples.size() == 150);\n            DLIB_TEST(labels.size() == 150);\n\n            typedef sparse_linear_kernel<sample_type> kernel_type;\n            svm_multiclass_linear_trainer<kernel_type> trainer;\n            trainer.set_c(100);\n            trainer.set_epsilon(0.000001);\n\n            randomize_samples(samples, labels);\n            matrix<double> cv = cross_validate_multiclass_trainer(trainer, samples, labels, 4);\n\n            dlog << LINFO << \"confusion matrix: \\n\" << cv;\n            const scalar_type cv_accuracy = sum(diag(cv))/sum(cv);\n            dlog << LINFO << \"cv accuracy: \" << cv_accuracy;\n            DLIB_TEST(cv_accuracy > 0.97);\n\n\n\n\n            {\n                print_spinner();\n                typedef matrix<scalar_type,0,1> dsample_type;\n                std::vector<dsample_type> dsamples = sparse_to_dense(samples);\n                DLIB_TEST(dsamples.size() == 150);\n\n                typedef linear_kernel<dsample_type> kernel_type;\n                svm_multiclass_linear_trainer<kernel_type> trainer;\n                trainer.set_c(100);\n\n                cv = cross_validate_multiclass_trainer(trainer, dsamples, labels, 4);\n\n                dlog << LINFO << \"dense confusion matrix: \\n\" << cv;\n                const scalar_type cv_accuracy = sum(diag(cv))/sum(cv);\n                dlog << LINFO << \"dense cv accuracy: \" << cv_accuracy;\n                DLIB_TEST(cv_accuracy > 0.97);\n            }\n\n        }\n\n\n\n\n        void perform_test (\n        )\n        {\n            print_spinner();\n            create_iris_datafile();\n\n            run_test<std::map<unsigned int, double> >();\n            run_test<std::map<unsigned int, float> >();\n            run_test<std::vector<std::pair<unsigned int, float> > >();\n            run_test<std::vector<std::pair<unsigned long, double> > >();\n\n            test_prior();\n            test_prior_sparse();\n        }\n    };\n\n    test_svm_multiclass_trainer a;\n\n}\n\n\n", "meta": {"hexsha": "e01d488927d1ad06760cb5a12daa33b781c00f48", "size": 7138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/dlib/test/svm_multiclass_linear.cpp", "max_stars_repo_name": "maxmert/nlp-mitie", "max_stars_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "dlib/test/svm_multiclass_linear.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "dlib/test/svm_multiclass_linear.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 31.4449339207, "max_line_length": 113, "alphanum_fraction": 0.5154104791, "num_tokens": 1548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5281958604355274}}
{"text": "#ifndef SFGE_MATH_INTERSECTIONS_HPP\r\n#define SFGE_MATH_INTERSECTIONS_HPP\r\n\r\n#include <boost/array.hpp>\r\n\r\n#include <SFML/System/Vector2.hpp>\r\n\r\n#include \"sfge/math/circle.hpp\"\r\n#include \"sfge/math/edge.hpp\"\r\n#include \"sfge/math/numerics.hpp\"\r\n\r\nnamespace sfge\r\n{\r\n\tenum IntersectionResult\r\n\t{\r\n\t\tIR_None,\r\n\t\tIR_Tangent,\r\n\t\tIR_TwoIntersections\r\n\t};\r\n\t\r\n\ttemplate <typename VectorStorageT>\r\n\tstruct EdgeCircleIntersectionCont\r\n\t{\r\n\t\tboost::array<VectorStorageT, 2> mTs;\r\n\t\tsf::Vector2f\t\t\t\t\tmStartPoint;\r\n\t\tsf::Vector2f\t\t\t\t\tmDir;\r\n\t};\r\n\t\r\n\ttemplate <typename VectorStorageT>\r\n\tIntersectionResult\tintersect(const Edge2<VectorStorageT> &e, const Circle<VectorStorageT> &c,\r\n\t\t\t\t\t\t\t\t  EdgeCircleIntersectionCont<VectorStorageT> &out);\r\n\r\n#include \"intersections.inl\"\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "cfb9abccd020291add642fadae30b203675b352b", "size": 775, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SFGE/include/sfge/math/intersections.hpp", "max_stars_repo_name": "sheldonrobinson/sfge", "max_stars_repo_head_hexsha": "af0adbc3ea1509a20d7255d41c34fb1f8db83728", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SFGE/include/sfge/math/intersections.hpp", "max_issues_repo_name": "sheldonrobinson/sfge", "max_issues_repo_head_hexsha": "af0adbc3ea1509a20d7255d41c34fb1f8db83728", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SFGE/include/sfge/math/intersections.hpp", "max_forks_repo_name": "sheldonrobinson/sfge", "max_forks_repo_head_hexsha": "af0adbc3ea1509a20d7255d41c34fb1f8db83728", "max_forks_repo_licenses": ["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.9459459459, "max_line_length": 95, "alphanum_fraction": 0.7225806452, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5281958490949572}}
{"text": "#ifndef HAZEN_CORE\n#define HAZEN_CORE\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <Eigen/QR>\n#include <cmath>\n#include <iostream>\n#include <type_traits>\n#include <utility>\n\nnamespace hazen {\n\n// Implementation --------------------------------------------------------------\nnamespace Unit_impl {\nusing fraction = std::pair<int, int>;\nconstexpr int gcd(int a, int b) {\n  if (a == 0)\n    return b;\n  return gcd(b % a, a);\n}\nconstexpr fraction simplify(fraction frac) {\n  int common_factor = gcd(frac.first, frac.second);\n  fraction result = {frac.first / common_factor, frac.second / common_factor};\n  if (result.second < 0) {\n    result.first *= -1;\n    result.second *= -1;\n  }\n  return result;\n}\nconstexpr fraction add_fraction(fraction frac1, fraction frac2) {\n  int den = gcd(frac1.second, frac2.second);\n  den = frac1.second * frac2.second / den;\n  int num =\n      frac1.first * (den / frac1.second) + frac2.first * (den / frac2.second);\n  return simplify({num, den});\n}\nconstexpr fraction subtract_fraction(fraction frac1, fraction frac2) {\n  frac2.first *= -1;\n  return add_fraction(frac1, frac2);\n}\n} // namespace Unit_impl\n\n// Unit Templates --------------------------------------------------------------\ntemplate <int L_num, int L_den, int T_num, int T_den, int M_num, int M_den,\n          int Theta_num, int Theta_den>\nstruct Unit {\n  static constexpr Unit_impl::fraction L = {L_num, L_den};\n  static constexpr Unit_impl::fraction T = {T_num, T_den};\n  static constexpr Unit_impl::fraction M = {M_num, M_den};\n  static constexpr Unit_impl::fraction Theta = {Theta_num, Theta_den};\n};\n\ntemplate <typename U1, typename U2> struct UPlus {\n  using type = Unit<Unit_impl::add_fraction(U1::L, U2::L).first,\n                    Unit_impl::add_fraction(U1::L, U2::L).second,\n                    Unit_impl::add_fraction(U1::T, U2::T).first,\n                    Unit_impl::add_fraction(U1::T, U2::T).second,\n                    Unit_impl::add_fraction(U1::M, U2::M).first,\n                    Unit_impl::add_fraction(U1::M, U2::M).second,\n                    Unit_impl::add_fraction(U1::Theta, U2::Theta).first,\n                    Unit_impl::add_fraction(U1::Theta, U2::Theta).second>;\n};\ntemplate <typename U1, typename U2> struct UMinus {\n  using type = Unit<Unit_impl::subtract_fraction(U1::L, U2::L).first,\n                    Unit_impl::subtract_fraction(U1::L, U2::L).second,\n                    Unit_impl::subtract_fraction(U1::T, U2::T).first,\n                    Unit_impl::subtract_fraction(U1::T, U2::T).second,\n                    Unit_impl::subtract_fraction(U1::M, U2::M).first,\n                    Unit_impl::subtract_fraction(U1::M, U2::M).second,\n                    Unit_impl::subtract_fraction(U1::Theta, U2::Theta).first,\n                    Unit_impl::subtract_fraction(U1::Theta, U2::Theta).second>;\n};\ntemplate <typename U, int divisor> struct UDivide {\n  static constexpr Unit_impl::fraction L =\n      Unit_impl::add_fraction({U::L.first, U::L.second *divisor}, {0, 1});\n  static constexpr Unit_impl::fraction T =\n      Unit_impl::add_fraction({U::T.first, U::T.second *divisor}, {0, 1});\n  static constexpr Unit_impl::fraction M =\n      Unit_impl::add_fraction({U::M.first, U::M.second *divisor}, {0, 1});\n  static constexpr Unit_impl::fraction Theta = Unit_impl::add_fraction(\n      {U::Theta.first, U::Theta.second *divisor}, {0, 1});\n  using type = Unit<L.first, L.second, T.first, T.second, M.first, M.second,\n                    Theta.first, Theta.second>;\n};\ntemplate <typename U, int multiplier> struct UMultiply {\n  static constexpr Unit_impl::fraction L =\n      Unit_impl::add_fraction({U::L.first * multiplier, U::L.second}, {0, 1});\n  static constexpr Unit_impl::fraction T =\n      Unit_impl::add_fraction({U::T.first * multiplier, U::T.second}, {0, 1});\n  static constexpr Unit_impl::fraction M =\n      Unit_impl::add_fraction({U::M.first * multiplier, U::M.second}, {0, 1});\n  static constexpr Unit_impl::fraction Theta = Unit_impl::add_fraction(\n      {U::Theta.first * multiplier, U::Theta.second}, {0, 1});\n  using type = Unit<L.first, L.second, T.first, T.second, M.first, M.second,\n                    Theta.first, Theta.second>;\n};\n\ntemplate <typename U1, typename U2>\nusing Unit_Plus = typename UPlus<U1, U2>::type;\ntemplate <typename U1, typename U2>\nusing Unit_Minus = typename UMinus<U1, U2>::type;\ntemplate <typename U, int divisor>\nusing Unit_Divide = typename UDivide<U, divisor>::type;\ntemplate <typename U, int multiplier>\nusing Unit_Multiply = typename UMultiply<U, multiplier>::type;\n\n// Unit Definitions ------------------------------------------------------------\nusing Dimensionless_Unit = Unit<0, 1, 0, 1, 0, 1, 0, 1>;\nusing Length_Unit = Unit<1, 1, 0, 1, 0, 1, 0, 1>;\nusing Time_Unit = Unit<0, 1, 1, 1, 0, 1, 0, 1>;\nusing Mass_Unit = Unit<0, 1, 0, 1, 1, 1, 0, 1>;\nusing Temperature_Unit = Unit<0, 1, 0, 1, 0, 1, 1, 1>;\nusing Velocity_Unit = Unit_Minus<Length_Unit, Time_Unit>;\nusing Acceleration_Unit = Unit_Minus<Velocity_Unit, Time_Unit>;\nusing Area_Unit = Unit_Plus<Length_Unit, Length_Unit>;\nusing Volume_Unit = Unit_Plus<Area_Unit, Length_Unit>;\nusing Density_Unit = Unit_Minus<Mass_Unit, Volume_Unit>;\nusing Force_Unit = Unit_Plus<Mass_Unit, Acceleration_Unit>;\nusing Pressure_Unit = Unit_Minus<Force_Unit, Area_Unit>;\nusing Dynamic_Viscosity_Unit = Unit_Plus<Pressure_Unit, Time_Unit>;\nusing Flow_Unit = Unit_Minus<Volume_Unit, Time_Unit>;\n\n// Scalar Templates ------------------------------------------------------------\ntemplate <typename U> class Scalar {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  Scalar<U> &operator+=(const Scalar<U> &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar<U> &operator-=(const Scalar<U> &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar<U> &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\n\n// Binary Arithmetic Operations\ntemplate <typename U> inline Scalar<U> operator+(Scalar<U> x, Scalar<U> y) {\n  return Scalar<U>{x.val + y.val};\n}\ntemplate <typename U> inline Scalar<U> operator-(Scalar<U> x, Scalar<U> y) {\n  return Scalar<U>{x.val - y.val};\n}\ntemplate <typename U1, typename U2>\ninline Scalar<Unit_Plus<U1, U2>> operator*(Scalar<U1> x, Scalar<U2> y) {\n  return Scalar<Unit_Plus<U1, U2>>{x.val * y.val};\n}\ntemplate <typename U1, typename U2>\ninline Scalar<Unit_Minus<U1, U2>> operator/(Scalar<U1> x, Scalar<U2> y) {\n  return Scalar<Unit_Minus<U1, U2>>{x.val / y.val};\n}\n\n// Use doubles as dimensionless scalars\ntemplate <typename U> inline Scalar<U> operator*(Scalar<U> x, double y) {\n  return Scalar<U>{x.val * y};\n}\ntemplate <typename U> inline Scalar<U> operator*(double x, Scalar<U> y) {\n  return Scalar<U>{x * y.val};\n}\ntemplate <typename U> inline Scalar<U> operator/(Scalar<U> x, double y) {\n  return Scalar<U>{x.val / y};\n}\ntemplate <typename U>\ninline Scalar<Unit_Minus<Unit<0, 1, 0, 1, 0, 1, 0, 1>, U>>\noperator/(double x, Scalar<U> y) {\n  return Scalar<Unit_Minus<Unit<0, 1, 0, 1, 0, 1, 0, 1>, U>>{x / y.val};\n}\n\n// Binary Comparison Operations\ntemplate <typename U> inline bool operator==(Scalar<U> x, Scalar<U> y) {\n  return x.val == y.val;\n}\ntemplate <typename U> inline bool operator!=(Scalar<U> x, Scalar<U> y) {\n  return x.val != y.val;\n}\ntemplate <typename U> inline bool operator>=(Scalar<U> x, Scalar<U> y) {\n  return x.val >= y.val;\n}\ntemplate <typename U> inline bool operator<=(Scalar<U> x, Scalar<U> y) {\n  return x.val <= y.val;\n}\ntemplate <typename U> inline bool operator>(Scalar<U> x, Scalar<U> y) {\n  return x.val > y.val;\n}\ntemplate <typename U> inline bool operator<(Scalar<U> x, Scalar<U> y) {\n  return x.val < y.val;\n}\n\n// Scalar Functions ------------------------------------------------------------\ntemplate <int pow_num, int pow_den, typename U>\nconstexpr inline Scalar<Unit_Divide<Unit_Multiply<U, pow_num>, pow_den>>\npower(Scalar<U> x) {\n  return Scalar<Unit_Divide<Unit_Multiply<U, pow_num>, pow_den>>(std::pow(\n      x.val, static_cast<double>(pow_num) / static_cast<double>(pow_den)));\n}\n\ntemplate <typename U>\nconstexpr inline Scalar<Unit_Divide<U, 2>> sqrt(Scalar<U> x) {\n  return Scalar<Unit_Divide<U, 2>>(std::sqrt(x.val));\n}\ntemplate <typename U> constexpr inline Scalar<U> abs(Scalar<U> x) {\n  return Scalar<U>(std::abs(x.val));\n}\ntemplate <typename U>\nconstexpr inline Scalar<Unit_Multiply<U, 2>> abs2(Scalar<U> x) {\n  return x * x;\n}\n\n// Scalar Result Types ---------------------------------------------------------\n// Product type of two scalars\ntemplate <typename T1, typename T2>\nusing product_type = decltype(std::declval<T1 &>() * std::declval<T2 &>());\n// Quotient type of two scalars\ntemplate <typename T1, typename T2>\nusing quotient_type = decltype(std::declval<T1 &>() / std::declval<T2 &>());\n// Root of a scalar\ntemplate <typename T> using root_type = decltype(sqrt(std::declval<T>()));\n\n// Scalar Definitions ----------------------------------------------------------\nusing Dimensionless = Scalar<Dimensionless_Unit>;\nusing Angle = Scalar<Dimensionless_Unit>;\nusing Length = Scalar<Length_Unit>;\nusing Time = Scalar<Time_Unit>;\nusing Mass = Scalar<Mass_Unit>;\nusing Temperature = Scalar<Temperature_Unit>;\nusing Velocity = Scalar<Velocity_Unit>;\nusing Acceleration = Scalar<Acceleration_Unit>;\nusing Area = Scalar<Area_Unit>;\nusing Volume = Scalar<Volume_Unit>;\nusing Density = Scalar<Density_Unit>;\nusing Force = Scalar<Force_Unit>;\nusing Pressure = Scalar<Pressure_Unit>;\nusing Dynamic_Viscosity = Scalar<Dynamic_Viscosity_Unit>;\nusing Flow = Scalar<Flow_Unit>;\n\ntemplate <> class Scalar<Dimensionless_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Angle Radians(double d) { return Angle(d); }\n  static constexpr Angle Degrees(double d) { return Angle(d * M_PI / 180.0); }\n  static Angle Slope(double rise, double run) {\n    return Angle(std::atan2(rise, run));\n  }\n  static Angle Slope(double slope) { return Angle(std::atan(slope)); }\n  static Angle Percent(double d) { return Angle(std::atan(d * 0.01)); }\n  constexpr double as_radians() const { return val; }\n  constexpr double as_degrees() const { return val * 180.0 / M_PI; }\n  double as_slope() const { return std::tan(val); }\n  double as_percent() const { return std::tan(val) * 100.0; }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\ntemplate <> class Scalar<Length_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Length Feet(double d) { return Length(d * 0.3048); }\n  static constexpr Length Yards(double d) { return Length(d * 0.3048 * 3); }\n  static constexpr Length Inches(double d) { return Length(d * 0.3048 / 12); }\n  static constexpr Length Meters(double d) { return Length(d); }\n  constexpr double as_feet() const { return val / 0.3048; }\n  constexpr double as_yards() const { return val / 0.3048 / 3; }\n  constexpr double as_inches() const { return val / 0.3048 * 12; }\n  constexpr double as_meters() const { return val; }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\ntemplate <> class Scalar<Time_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Time Seconds(double d) { return Time(d); }\n  constexpr double as_seconds() const { return val; }\n  constexpr double as_minutes() const { return val / 60.0; }\n  constexpr double as_hours() const { return val / 60.0 / 60.0; }\n  constexpr double as_days() const { return val / 60.0 / 60.0 / 24.0; }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\ntemplate <> class Scalar<Mass_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Mass Kilograms(double d) { return Mass(d); }\n  static constexpr Mass Slug(double d) { return Mass(d * 14.593903); }\n  constexpr double as_kilogram() const { return val; }\n  constexpr double as_slug() const { return val / 14.593903; }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\ntemplate <> class Scalar<Temperature_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Temperature Kelvin(double d) { return Temperature(d); }\n  static constexpr Temperature Celcius(double d) {\n    return Temperature(d + 273.15);\n  }\n  static constexpr Temperature Fahrenheit(double d) {\n    return Temperature((d - 32) * 5 / 9 + 237.15);\n  }\n  constexpr double as_kelvin(double d) const { return val; }\n  constexpr double as_celcius(double d) const { return val - 273.15; }\n  constexpr double as_fahrenheit(double d) const {\n    return (val - 273.15) * 9 / 5 + 32;\n  }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\ntemplate <> class Scalar<Velocity_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Velocity MPS(double d) { return Velocity(d); }\n  static constexpr Velocity FPS(double d) { return Velocity(d * 0.3048); }\n  constexpr double as_meters_per_second() const { return val; }\n  constexpr double as_feet_per_second() const { return val / 0.3048; }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\ntemplate <> class Scalar<Acceleration_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Acceleration MPS2(double d) { return Acceleration(d); }\n  static constexpr Acceleration FPS2(double d) {\n    return Acceleration(d * 0.3048);\n  }\n  constexpr double as_meters_per_second_squared() const { return val; }\n  constexpr double as_feet_per_second_squared() const { return val / 0.3048; }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\ntemplate <> class Scalar<Area_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Area Square_Meters(double d) { return Area(d); }\n  static constexpr Area Square_Feet(double d) {\n    return Area(d * 0.3048 * 0.3048);\n  }\n  static constexpr Area Square_Inches(double d) {\n    return Area(d * 0.3048 * 0.3048 / 12 / 12);\n  }\n  static constexpr Area Square_Yards(double d) {\n    return Area(d * 0.3048 * 0.3048 * 3 * 3);\n  }\n  static constexpr Area Acres(double d) { return Area(d * 4046.8564224); }\n  constexpr double as_square_meters() const { return val; }\n  constexpr double as_square_feet() const { return val / 0.3048 / 0.3048; }\n  constexpr double as_square_inches() const {\n    return 12 * 12 * val / 0.3048 / 0.3048;\n  }\n  constexpr double as_square_yards() const {\n    return val / 0.3048 / 0.3048 / 3 / 3;\n  }\n  constexpr double as_acres() const { return val / 4046.8564224; }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\ntemplate <> class Scalar<Volume_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Volume Cubic_Meters(double d) { return Volume(d); }\n  static constexpr Volume Cubic_Feet(double d) {\n    return Volume(d * 0.3048 * 0.3048 * 0.3048);\n  }\n  static constexpr Volume Gallons(double d) { return Volume(d * 0.0037854118); }\n  static constexpr Volume Liters(double d) { return Volume(d * 0.001); }\n  constexpr double as_cubic_meters() const { return val; }\n  constexpr double as_cubic_feet() const {\n    return val / 0.3048 / 0.3048 / 0.3048;\n  }\n  constexpr double as_gallons() const { return val / 0.0037854118; }\n  constexpr double as_liters() const { return val / 0.001; }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\ntemplate <> class Scalar<Density_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Density Kilograms_per_Cubic_Meter(double d) {\n    return Density(d);\n  }\n  static constexpr Density Slugs_per_Cubic_Foot(double d) {\n    return Density(d * 515.3788184);\n  }\n  constexpr double as_kilograms_per_cubic_meter() { return val; }\n  constexpr double as_slugs_per_cubic_foot() { return val / 515.3788184; }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\ntemplate <> class Scalar<Force_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Force Newtons(double d) { return Force(d); }\n  static constexpr Force Pounds(double d) { return Force(d * 4.4482216); }\n  constexpr double as_newtons(double d) const { return val; }\n  constexpr double as_pounds(double d) const { return val / 4.4482216; }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\ntemplate <> class Scalar<Pressure_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Pressure Pascals(double d) { return Pressure(d); }\n  static constexpr Pressure PSF(double d) {\n    return Pressure(d * 47.880258888889);\n  }\n  static constexpr Pressure PSI(double d) { return Pressure(d * 6894.7572932); }\n  constexpr double as_pascals() const { return val; }\n  constexpr double as_psf() const { return val / 47.880258888889; }\n  constexpr double as_psi() const { return val / 6894.7572932; }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\ntemplate <> class Scalar<Dynamic_Viscosity_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Dynamic_Viscosity Pascal_Seconds(double d) {\n    return Dynamic_Viscosity(d);\n  }\n  static constexpr Dynamic_Viscosity PSF_Seconds(double d) {\n    return Dynamic_Viscosity(d * 47.880258888889);\n  }\n  constexpr double as_pascal_seconds() const { return val; }\n  constexpr double as_psf_seconds() const { return val / 47.880258888889; }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\ntemplate <> class Scalar<Flow_Unit> {\npublic:\n  constexpr Scalar() : val{} {}\n  explicit constexpr Scalar(double d) : val{d} {}\n  static constexpr Flow CMS(double d) { return Flow(d); }\n  static constexpr Flow LPS(double d) { return Flow(d * 0.001); }\n  static constexpr Flow CFS(double d) {\n    return Flow(d * 0.3048 * 0.3048 * 0.3048);\n  }\n  static constexpr Flow GPM(double d) { return Flow(d * 0.0037854118 / 60); }\n  static constexpr Flow GPD(double d) {\n    return Flow(d * 0.0037854118 / 60 / 60 / 24);\n  }\n  static constexpr Flow MGD(double d) {\n    return Flow(d * 0.0037854118 / 60 / 60 / 24 * 1000000);\n  }\n  constexpr double as_cubic_meters_per_second() const { return val; }\n  constexpr double as_liters_per_second() const { return val / 0.001; }\n  constexpr double as_cubic_feet_per_second() const {\n    return val / 0.3048 / 0.3048 / 0.3048;\n  }\n  constexpr double as_gallons_per_minute() const {\n    return val * 60 / 0.0037854118;\n  }\n  constexpr double as_gallons_per_day() const {\n    return val * 60 * 60 * 24 / 0.0037854118;\n  }\n  constexpr double as_million_gallons_per_day() const {\n    return val * 60 * 60 * 24 / 0.0037854118 / 1000000;\n  }\n\n  Scalar &operator+=(const Scalar &x) {\n    val += x.val;\n    return *this;\n  }\n  Scalar &operator-=(const Scalar &x) {\n    val -= x.val;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Scalar &s) {\n    os << s.val;\n    return os;\n  }\n\n  double val;\n};\n\n// Unit Literals ---------------------------------------------------------------\n// Meters\nconstexpr Length operator\"\"_m(long double d) {\n  return Length::Meters(static_cast<double>(d));\n}\n// Yard\nconstexpr Length operator\"\"_yd(long double d) {\n  return Length::Yards(static_cast<double>(d));\n}\n// Feet\nconstexpr Length operator\"\"_ft(long double d) {\n  return Length::Feet(static_cast<double>(d));\n}\n// Inches\nconstexpr Length operator\"\"_in(long double d) {\n  return Length::Inches(static_cast<double>(d));\n}\n// Kilograms\nconstexpr Mass operator\"\"_kg(long double d) {\n  return Mass::Kilograms(static_cast<double>(d));\n}\n// Slug\nconstexpr Mass operator\"\"_slug(long double d) {\n  return Mass::Slug(static_cast<double>(d));\n}\n// Seconds\nconstexpr Time operator\"\"_s(long double d) {\n  return Time::Seconds(static_cast<double>(d));\n}\n// Kelvin\nconstexpr Temperature operator\"\"_K(long double d) {\n  return Temperature::Kelvin(static_cast<double>(d));\n}\n// Celcius\nconstexpr Temperature operator\"\"_C(long double d) {\n  return Temperature::Celcius(static_cast<double>(d));\n}\n// Fahrenheit\nconstexpr Temperature operator\"\"_F(long double d) {\n  return Temperature::Fahrenheit(static_cast<double>(d));\n}\n// Cubic Meters\nconstexpr Volume operator\"\"_m3(long double d) {\n  return Volume::Cubic_Meters(static_cast<double>(d));\n}\n// Cubic feet\nconstexpr Volume operator\"\"_ft3(long double d) {\n  return Volume::Cubic_Feet(static_cast<double>(d));\n}\n// Liters\nconstexpr Volume operator\"\"_l(long double d) {\n  return Volume::Liters(static_cast<double>(d));\n}\n// Gallons\nconstexpr Volume operator\"\"_gal(long double d) {\n  return Volume::Gallons(static_cast<double>(d));\n}\n// Cubic Meters per Second\nconstexpr Flow operator\"\"_cms(long double d) {\n  return Flow::CMS(static_cast<double>(d));\n}\n// Cubic Feet per Second\nconstexpr Flow operator\"\"_cfs(long double d) {\n  return Flow::CFS(static_cast<double>(d));\n}\n// Gallons per Minute\nconstexpr Flow operator\"\"_gpm(long double d) {\n  return Flow::GPM(static_cast<double>(d));\n}\n// Gallons per Day\nconstexpr Flow operator\"\"_gpd(long double d) {\n  return Flow::GPD(static_cast<double>(d));\n}\n// Million Gallons per Day\nconstexpr Flow operator\"\"_mgd(long double d) {\n  return Flow::MGD(static_cast<double>(d));\n}\n// Meters per Second\nconstexpr Velocity operator\"\"_mps(long double d) {\n  return Velocity::MPS(static_cast<double>(d));\n}\n// Feet per Second\nconstexpr Velocity operator\"\"_fps(long double d) {\n  return Velocity::FPS(static_cast<double>(d));\n}\n// Meters per Second Squared\nconstexpr Acceleration operator\"\"_mps2(long double d) {\n  return Acceleration::MPS2(static_cast<double>(d));\n}\n// Feet per Second Squared\nconstexpr Acceleration operator\"\"_fps2(long double d) {\n  return Acceleration::FPS2(static_cast<double>(d));\n}\n// Kilograms per Cubic Meter\nconstexpr Density operator\"\"_kgm3(long double d) {\n  return Density::Kilograms_per_Cubic_Meter(static_cast<double>(d));\n}\n// Slug per Cubic Feet\nconstexpr Density operator\"\"_slugcf(long double d) {\n  return Density::Slugs_per_Cubic_Foot(static_cast<double>(d));\n}\n// Pascal Seconds\nconstexpr Dynamic_Viscosity operator\"\"_pas(long double d) {\n  return Dynamic_Viscosity::Pascal_Seconds(static_cast<double>(d));\n}\n// Pounds per Square Foot Second\nconstexpr Dynamic_Viscosity operator\"\"_psfs(long double d) {\n  return Dynamic_Viscosity::PSF_Seconds(static_cast<double>(d));\n}\n// Newtons\nconstexpr Force operator\"\"_n(long double d) {\n  return Force::Newtons(static_cast<double>(d));\n}\n// Pounds (Force)\nconstexpr Force operator\"\"_lbf(long double d) {\n  return Force::Pounds(static_cast<double>(d));\n}\n// Pounds (Force) per Cubic Foot\nconstexpr Scalar<Unit_Minus<Force_Unit, Volume_Unit>>\noperator\"\"_pcf(long double d) {\n  return Scalar<Unit_Minus<Force_Unit, Volume_Unit>>{\n      static_cast<double>(d * 157.0874606377)};\n}\n// Radians\nconstexpr Angle operator\"\"_rads(long double d) {\n  return Angle::Radians(static_cast<double>(d));\n}\n// Degrees\nconstexpr Angle operator\"\"_degrees(long double d) {\n  return Angle::Degrees(static_cast<double>(d));\n}\n// Dimensionless\nconstexpr Dimensionless operator\"\"_pure(long double d) {\n  return Dimensionless(static_cast<double>(d));\n}\n\ntemplate <typename T, int rows, int cols> class Matrix {\npublic:\n  using value_type = T;\n\n  Matrix() = default;\n  Matrix(const Matrix &) = default;\n  Matrix(Matrix &&) = default;\n  Matrix &operator=(const Matrix &) = default;\n  Matrix &operator=(Matrix &&) = default;\n\n  Matrix(size_t m, size_t n)\n      : elems{Eigen::Matrix<double, rows, cols>::Zero(m, n)} {}\n  Matrix(size_t n) : elems{Eigen::Matrix<double, rows, cols>::Zero(n)} {}\n  Matrix(Eigen::Matrix<double, rows, cols> m) : elems{m} {}\n  Matrix &operator=(const T &s) {\n    elems.setConstant(s.val);\n    return *this;\n  }\n  Matrix &operator=(const Eigen::Matrix<double, rows, cols> &m) {\n    elems = m;\n    return *this;\n  }\n  Matrix &operator+=(const Matrix &m) {\n    elems += m.elems;\n    return *this;\n  }\n  Matrix &operator-=(const Matrix &m) {\n    elems -= m.elems;\n    return *this;\n  }\n  Matrix &operator-() {\n    elems = -elems;\n    return *this;\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Matrix &m) {\n    os << m.elems;\n    return os;\n  }\n\n  operator T &() { return elems(0, 0); }\n  operator T() const { return elems(0, 0); }\n  size_t size() const { return elems.size(); }\n  size_t n_rows() const { return elems.rows(); }\n  size_t n_cols() const { return elems.cols(); }\n\n  T operator()(size_t i, size_t j = 0) const { return T(elems(i, j)); }\n\n  static Matrix<T, Eigen::Dynamic, Eigen::Dynamic> Constant(int m, int n,\n                                                            const T &s) {\n    return Matrix<T, Eigen::Dynamic, Eigen::Dynamic>{\n        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Constant(m, n,\n                                                                        s.val)};\n  }\n  static Matrix<T, Eigen::Dynamic, Eigen::Dynamic> Random(int m, int n) {\n    return Matrix<T, Eigen::Dynamic, Eigen::Dynamic>{\n        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Random(m, n)};\n  }\n  static Matrix<T, Eigen::Dynamic, 1> Random(int n) {\n    return Matrix<T, Eigen::Dynamic, 1>{\n        Eigen::Matrix<double, Eigen::Dynamic, 1>::Random(n)};\n  }\n\n  Eigen::Matrix<double, rows, cols> elems;\n};\n\n// Binary Arithmetic Operations\ntemplate <typename T, int rows, int cols>\ninline Matrix<T, rows, cols> operator+(const Matrix<T, rows, cols> &x,\n                                       const Matrix<T, rows, cols> &y) {\n  return Matrix<T, rows, cols>{x.elems + y.elems};\n}\ntemplate <typename T, int rows, int cols>\ninline Matrix<T, rows, cols> operator-(const Matrix<T, rows, cols> &x,\n                                       const Matrix<T, rows, cols> &y) {\n  return Matrix<T, rows, cols>{x.elems - y.elems};\n}\ntemplate <typename T1, typename T2, int m, int n, int o>\ninline Matrix<product_type<T1, T2>, m, o> operator*(const Matrix<T1, m, n> &x,\n                                                    const Matrix<T2, n, o> &y) {\n  return Matrix<product_type<T1, T2>, m, o>{x.elems * y.elems};\n}\n\n// Use doubles as dimensionless scalars\ntemplate <typename T, int rows, int cols>\ninline Matrix<T, rows, cols> operator*(const Matrix<T, rows, cols> &x,\n                                       double y) {\n  return Matrix<T, rows, cols>{x.elems * y};\n}\ntemplate <typename T, int rows, int cols>\ninline Matrix<T, rows, cols> operator*(double x,\n                                       const Matrix<T, rows, cols> &y) {\n  return Matrix<T, rows, cols>{x * y.elems};\n}\ntemplate <typename T, int rows, int cols>\ninline Matrix<T, rows, cols> operator/(const Matrix<T, rows, cols> &x,\n                                       double y) {\n  return Matrix<T, rows, cols>{x.elems / y};\n}\ntemplate <typename T, int rows, int cols>\ninline Matrix<quotient_type<Dimensionless, T>, rows, cols>\noperator/(double x, const Matrix<T, rows, cols> &y) {\n  return Matrix<quotient_type<Dimensionless, T>, rows, cols>{x / y.elems};\n}\n\n// Scaling\ntemplate <typename T, typename U, int rows, int cols>\ninline Matrix<product_type<T, Scalar<U>>, rows, cols>\noperator*(const Matrix<T, rows, cols> &x, Scalar<U> y) {\n  return Matrix<product_type<T, Scalar<U>>, rows, cols>{x.elems * y.val};\n}\ntemplate <typename T, typename U, int rows, int cols>\ninline Matrix<product_type<T, Scalar<U>>, rows, cols>\noperator*(Scalar<U> x, const Matrix<T, rows, cols> &y) {\n  return Matrix<product_type<T, Scalar<U>>, rows, cols>{x.val * y.elems};\n}\ntemplate <typename T, typename U, int rows, int cols>\ninline Matrix<quotient_type<T, Scalar<U>>, rows, cols>\noperator/(const Matrix<T, rows, cols> &x, Scalar<U> y) {\n  return Matrix<quotient_type<T, Scalar<U>>, rows, cols>{x.elems / y.val};\n}\ntemplate <typename T, typename U, int rows, int cols>\ninline Matrix<quotient_type<Scalar<U>, T>, rows, cols>\noperator/(Scalar<U> x, const Matrix<T, rows, cols> &y) {\n  return Matrix<quotient_type<Scalar<U>, T>, rows, cols>{x.val / y.elems};\n}\n\n// Binary Comparison Operations\ntemplate <typename T, int rows, int cols>\ninline bool operator==(const Matrix<T, rows, cols> &x,\n                       const Matrix<T, rows, cols> &y) {\n  return x.elems == y.elems;\n}\ntemplate <typename T, int rows, int cols>\ninline bool operator!=(const Matrix<T, rows, cols> &x,\n                       const Matrix<T, rows, cols> &y) {\n  return x.elems != y.elems;\n}\ntemplate <typename T, int rows, int cols>\ninline bool operator>=(const Matrix<T, rows, cols> &x,\n                       const Matrix<T, rows, cols> &y) {\n  return x.elems >= y.elems;\n}\ntemplate <typename T, int rows, int cols>\ninline bool operator<=(const Matrix<T, rows, cols> &x,\n                       const Matrix<T, rows, cols> &y) {\n  return x.elems <= y.elems;\n}\ntemplate <typename T, int rows, int cols>\ninline bool operator>(const Matrix<T, rows, cols> &x,\n                      const Matrix<T, rows, cols> &y) {\n  return x.elems > y.elems;\n}\ntemplate <typename T, int rows, int cols>\ninline bool operator<(const Matrix<T, rows, cols> &x,\n                      const Matrix<T, rows, cols> &y) {\n  return x.elems < y.elems;\n}\n\n// Matrix Functions ------------------------------------------------------------\ntemplate <typename T, int rows, int cols>\nT norm(const Matrix<T, rows, cols> &m) {\n  return T{m.elems.norm()};\n}\ntemplate <typename T, int rows, int cols>\nMatrix<T, rows, cols> abs(const Matrix<T, rows, cols> &m) {\n  return Matrix<T, rows, cols>{m.elems.cwiseAbs()};\n}\n\ntemplate <typename T, int rows, int cols>\nproduct_type<T, T> squared_norm(const Matrix<T, rows, cols> &m) {\n  return product_type<T, T>{m.elems.squaredNorm()};\n}\ntemplate <typename T, int rows, int cols>\nMatrix<T, cols, rows> transpose(const Matrix<T, rows, cols> &m) {\n  return m.elems.transpose();\n}\ntemplate <typename T1, typename T2, int rows>\nproduct_type<T1, T2> dot_product(const Matrix<T1, rows, 1> &u,\n                                 const Matrix<T2, rows, 1> &v) {\n  return product_type<T1, T2>(u.elems.dot(v.elems));\n}\ntemplate <typename T1, typename T2, int n, int m>\nMatrix<quotient_type<T2, T1>, m, 1> solve(const Matrix<T1, n, m> &A,\n                                          const Matrix<T2, n, 1> &b) {\n  return Matrix<quotient_type<T2, T1>, m, 1>{A.elems.lu().solve(b.elems)};\n}\ntemplate <typename T1, typename T2, int n, int m>\nMatrix<quotient_type<T2, T1>, m, 1>\nsolve_least_squares(const Matrix<T1, n, m> &A, const Matrix<T2, n, 1> &b) {\n  // return Matrix<quotient_type<T2, T1>, m, 1>{\n  //     A.elems.householderQr().solve(b.elems)};\n  return Matrix<quotient_type<T2, T1>, m, 1>{\n      A.elems.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b.elems)};\n}\n\n// Matrix and Vector aliases\ntemplate <typename T> using Mat = Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\ntemplate <typename T> using Vec = Matrix<T, Eigen::Dynamic, 1>;\n\n} // namespace hazen\n\n#endif", "meta": {"hexsha": "4e9db4315edd090ab3bce511370ecf384529da5b", "size": 33943, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/Hazen/Core.hpp", "max_stars_repo_name": "barne856/Hazen", "max_stars_repo_head_hexsha": "afac525caa8d5229d6ce21248027d680cc5a620d", "max_stars_repo_licenses": ["MIT"], "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/Hazen/Core.hpp", "max_issues_repo_name": "barne856/Hazen", "max_issues_repo_head_hexsha": "afac525caa8d5229d6ce21248027d680cc5a620d", "max_issues_repo_licenses": ["MIT"], "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/Hazen/Core.hpp", "max_forks_repo_name": "barne856/Hazen", "max_forks_repo_head_hexsha": "afac525caa8d5229d6ce21248027d680cc5a620d", "max_forks_repo_licenses": ["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.0110220441, "max_line_length": 80, "alphanum_fraction": 0.6489703326, "num_tokens": 9399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.5281823888248868}}
{"text": "\n#pragma once\n\n#include <map>\n#include <stack>\n#include <boost/circular_buffer.hpp>\n#include <giecs/ll/arithmetic.hpp>\n#include <giecs/ll/io.hpp>\n\n#include <giecs/core.hpp>\n#include <giecs/eval.hpp>\n\nnamespace forth\n{\n\n/**\n * Implements the complete Virtual-Forth-Machine\n */\ntemplate <typename MemWord, typename MemContainer, typename DataStackContainer, typename ReturnStackContainer>\nclass VM : public std::stack<MemWord, DataStackContainer>\n{\n    public:\n        MemWord pc; /// Instruction pointer\n        MemContainer mem;\n        std::stack<MemWord, ReturnStackContainer> return_stack; /// return stack\n        std::map<MemWord, giecs::ProgramBase*> programs; /// external programs\n\n        struct Instruction\n        {\n            enum Opcode\n            {\n                compose, branch, exit, // flow\n                push, drop, dup, over, swap, pushr, popr, // stack\n                load, store, // memory\n                noti, andi, ori, xori, // bitwise logic\n                addi, subi, muli, divi, // integer arithmetic\n                gti, lti, eq, // integer relation\n                printi, emit, // out\n            };\n\n            using Data = VM<MemWord, MemContainer, DataStackContainer, ReturnStackContainer>;\n\n            Opcode op;\n            MemWord pc;\n\n            Opcode fetch(Data& data)\n            {\n                data.pc = this->pc;\n                return op;\n            }\n        }; // struct Instruction\n\n        giecs::ProgramBase* get_program(MemWord addr)\n        {\n            auto it = this->programs.find(addr);\n            if(it == this->programs.end())\n                return nullptr;\n            else\n                return it->second;\n        }\n\n        MemWord pop()\n        {\n            MemWord a = this->top();\n            this->std::stack<MemWord, DataStackContainer>::pop();\n            return a;\n        }\n\n        /**\n         * Executes Opcodes\n         */\n#define FN(def) ([](VM<MemWord, MemContainer, DataStackContainer, ReturnStackContainer>& state){ def ;})\n        GIECS_CORE_OPERATOR(Operator,\n                            ((Instruction::Opcode::compose, FN(state.return_stack.push(state.pc); state.pc = state.mem[state.pc];)))\n                            ((Instruction::Opcode::branch, FN(MemWord off = state.mem[++state.pc]-1; if(state.pop() == 0) state.pc += off;)))\n                            ((Instruction::Opcode::exit, FN(state.pc = state.return_stack.top(); state.return_stack.pop();)))\n\n                            ((Instruction::Opcode::load, FN(MemWord addr=state.pop(); state.push(state.mem[addr]);)))\n                            ((Instruction::Opcode::store, FN(MemWord addr=state.pop(); state.mem[addr] = state.pop();)))\n                            ((Instruction::Opcode::push, FN(state.push(state.mem[++state.pc]))))\n                            ((Instruction::Opcode::drop, FN(state.pop())))\n                            ((Instruction::Opcode::dup, FN(state.push(state.top()))))\n                            ((Instruction::Opcode::over, FN(MemWord a = state.pop(); MemWord b = state.top(); state.push(a); state.push(b);)))\n                            ((Instruction::Opcode::swap, FN(MemWord a = state.pop(); MemWord b = state.pop(); state.push(a); state.push(b);)))\n                            ((Instruction::Opcode::pushr, FN(state.return_stack.push(state.pop()))))\n                            ((Instruction::Opcode::popr, FN(state.push(state.return_stack.top()); state.return_stack.pop();)))\n\n                            ((Instruction::Opcode::noti, giecs::ll::Bitwise<int>::op_not))\n                            ((Instruction::Opcode::andi, giecs::ll::Bitwise<int>::op_and))\n                            ((Instruction::Opcode::ori, giecs::ll::Bitwise<int>::op_or))\n                            ((Instruction::Opcode::xori, giecs::ll::Bitwise<int>::op_xor))\n                            ((Instruction::Opcode::addi, giecs::ll::Arithmetic<int>::add))\n                            ((Instruction::Opcode::subi, giecs::ll::Arithmetic<int>::sub))\n                            ((Instruction::Opcode::muli, giecs::ll::Arithmetic<int>::mul))\n                            ((Instruction::Opcode::divi, giecs::ll::Arithmetic<int>::div))\n                            ((Instruction::Opcode::gti, giecs::ll::Relation<int>::gt))\n                            ((Instruction::Opcode::lti, giecs::ll::Relation<int>::lt))\n                            ((Instruction::Opcode::eq, giecs::ll::Relation<int>::eq))\n\n                            ((Instruction::Opcode::emit, giecs::ll::ConsoleIO<char>::print))\n                            ((Instruction::Opcode::printi, giecs::ll::ConsoleIO<int>::print))\n                           ); // Operator\n\n        /**\n         * Evaluated by giecs::eval\n         */\n        class Program : public giecs::Program<giecs::Core<Instruction, Operator>, Program>\n        {\n            private:\n                class InstructionDecoder : public boost::circular_buffer<Instruction>\n                {\n                    private:\n                        VM& state;\n\n                    public:\n                        InstructionDecoder(VM& s)\n                            : boost::circular_buffer<Instruction>(16), state(s)\n                        {\n                        }\n\n                        Instruction& front(void)\n                        {\n                            if(this->boost::circular_buffer<Instruction>::empty())\n                            {\n                                MemWord pc = state.pc;\n                                for(Instruction inst; inst.op != Instruction::Opcode::compose && inst.op != Instruction::Opcode::exit && inst.op != Instruction::Opcode::branch && !this->full();)\n                                {\n                                    ++pc;\n                                    inst.op = (typename Instruction::Opcode) this->state.mem[this->state.mem[pc]];\n                                    inst.pc = pc;\n                                    // We know which instructions take more\n                                    if(inst.op == Instruction::Opcode::push)\n                                        ++pc;\n                                    this->push_back(inst);\n                                }\n                            }\n                            return this->boost::circular_buffer<Instruction>::front();\n                        }\n\n                        bool empty(void) const\n                        {\n                            return (this->state.programs.count(this->state.pc) > 0) || this->state.return_stack.empty();\n                        }\n                }; // class InstructionDecoder\n\n                VM& state;\n                std::queue<Instruction, InstructionDecoder> queue; // could be multiple objects for multithreaded operation\n\n            public:\n                Program(VM& vm_, giecs::ProgramBase* ret=nullptr)\n                    : state(vm_), queue(InstructionDecoder(vm_))\n                {\n                }\n\n                std::queue<Instruction, InstructionDecoder>& program(void)\n                {\n                    return this->queue;\n                }\n\n                VM& data(void)\n                {\n                    return this->state;\n                }\n\n                giecs::ProgramBase* next(void)\n                {\n                    return this->state.get_program(this->state.pc);\n                }\n        }; // class Word\n}; // class VM\n\n} // namespace forth\n\n", "meta": {"hexsha": "5ce9809bbe25213570075571bab0765e2f98db6f", "size": 7448, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "languages/forth/vm.hpp", "max_stars_repo_name": "michaelsippel/cautious-potato", "max_stars_repo_head_hexsha": "3f683695cc4a071d0248bb5dc8f850a3a0a69650", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-01-31T12:53:37.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-26T20:48:04.000Z", "max_issues_repo_path": "languages/forth/vm.hpp", "max_issues_repo_name": "michaelsippel/cautious-potato", "max_issues_repo_head_hexsha": "3f683695cc4a071d0248bb5dc8f850a3a0a69650", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "languages/forth/vm.hpp", "max_forks_repo_name": "michaelsippel/cautious-potato", "max_forks_repo_head_hexsha": "3f683695cc4a071d0248bb5dc8f850a3a0a69650", "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.8045977011, "max_line_length": 194, "alphanum_fraction": 0.4727443609, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.528179865330457}}
{"text": "#include <float.h>\n#include <cmath>\n#include \"get_floor_Hf.h\"\n#include \"normalize2dpts.h\"\n#include <Eigen/Geometry>\n\nusing namespace Eigen;\n\nPoseData get_floor_Hf(MatrixXd &p1, MatrixXd &p2, Matrix3d &R1, Matrix3d &R2, double f1)\n{\n    int nbr_coeffs = 21;\n    int nbr_unknowns = 6;\n\n    // Save copies of the inverse rotation\n    Matrix3d R1T = R1.transpose();\n    Matrix3d R2T = R2.transpose();\n\n    // Compute normalization matrix\n    double scale = normalize2dpts(p2);\n    Vector3d s;\n    s << scale, scale, 1.0;\n    DiagonalMatrix<double, 3> S = s.asDiagonal();\n\n    // Initialize known calibration matrix\n    Vector3d k1inv;\n    k1inv << 1 / f1, 1 / f1, 1.0;\n    DiagonalMatrix<double, 3> K1inv = k1inv.asDiagonal();\n\n    // Normalize data\n    Matrix3d y1;\n    Matrix3d x2;\n    y1 = R1T * K1inv * p1.colwise().homogeneous();\n    x2 = p2.colwise().homogeneous();\n\n    x2 = S * x2;\n\n    MatrixXd y1t(2,3);\n    y1t << y1.colwise().hnormalized();\n    MatrixXd x2t(2,3);\n    x2t << x2.colwise().hnormalized();\n\n    // Wrap input data to expected format\n    VectorXd input(nbr_coeffs);\n    input << y1t.col(0),\n             x2t.col(0),\n             y1t.col(1),\n             x2t.col(1),\n             y1t.col(2),\n             x2t.col(2),\n             Map<VectorXd>(R2T.data(), 9);\n\n    // TODO: Not sure if this is necessary (assure const)\n    const Map<VectorXd> input_data(input.data(), nbr_coeffs);\n\n    // Extract solution\n    MatrixXcd sols = solver_floor_Hf(input_data);\n\n    // Pre-processing: Remove complex-valued solutions\n    double thresh = 1e-5;\n    ArrayXd real_sols(7);\n    real_sols = sols.imag().cwiseAbs().colwise().sum();\n    int nbr_real_sols = (real_sols <= thresh).count();\n\n    // Allocate space for putative (real) homographies\n    MatrixXd best_homography(3, 3);\n    double best_focal_length;\n    double best_algebraic_error = DBL_MAX;\n    double algebraic_error;\n\n    // Since this is a 2.5 pt solver, use the last\n    // (previously unused) constraint, to discard\n    // false solutions.\n    ArrayXd xx(nbr_unknowns);\n    VectorXd input_algebraic(nbr_coeffs + nbr_unknowns);\n\n    for (int i = 0; i < real_sols.size(); i++) {\n        if (real_sols(i) <= thresh) {\n            // Compute algebraic error, and compare to other solutions.\n            xx = sols.col(i).real();\n            input_algebraic << xx, input;\n            algebraic_error = get_algebraic_error_floor_Hf(input_algebraic);\n\n            if (algebraic_error < best_algebraic_error) {\n                best_algebraic_error = algebraic_error;\n                best_homography << xx[0], xx[2], xx[1],\n                                       0, xx[3],     0,\n                                  -xx[1], xx[4], xx[0];\n                best_focal_length = xx[5];\n            }\n        }\n    }\n\n    // Construct homography\n    Matrix3d K, H;\n    K = Vector3d(best_focal_length, best_focal_length, 1).asDiagonal();\n    // Ki = Vector3d(1, 1, best_focal_length).asDiagonal();\n    H = S.inverse() * K * R2 * best_homography * R1.transpose() * K1inv;\n\n    // Package output\n    PoseData posedata;\n    posedata.homography = H;\n    posedata.focal_length = best_focal_length / scale;\n\n    return posedata;\n}\n\n// ---------------- //\n// MATLAB interface //\n// ---------------- //\n#ifdef MATLAB_MEX_FILE\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n\tif (nrhs != 5) {\n\t\tmexErrMsgIdAndTxt(\"get_floor_Hf:nrhs\", \"Five input arguments are required.\");\n\t}\n\tif (nlhs != 2) {\n\t\tmexErrMsgIdAndTxt(\"get_floor_Hf:nlhs\", \"Two output arguments are required.\");\n\t}\n\tif (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) {\n\t\tmexErrMsgIdAndTxt(\"get_floor_Hf:notDouble\", \"Input data must be type double.\");\n\t}\n\tif(mxGetNumberOfElements(prhs[0]) != 6 && mxGetNumberOfElements(prhs[1]) != 6 && mxGetNumberOfElements(prhs[2]) != 9 && mxGetNumberOfElements(prhs[3]) != 9 && mxGetNumberOfElements(prhs[4]) != 1) {\n\t\tmexErrMsgIdAndTxt(\"get_floor_Hf:incorrectSize\", \"Input dimensions incorrect.\");\n\t}\n    // Convert to expected input\n    VectorXd x1_tmp = Map<VectorXd>(mxGetPr(prhs[0]), 6);\n    VectorXd x2_tmp = Map<VectorXd>(mxGetPr(prhs[1]), 6);\n    MatrixXd x1 = Map<MatrixXd>(x1_tmp.data(), 2, 3);\n    MatrixXd x2 = Map<MatrixXd>(x2_tmp.data(), 2, 3);\n\n    VectorXd R1_tmp = Map<VectorXd>(mxGetPr(prhs[2]), 9);\n    VectorXd R2_tmp = Map<VectorXd>(mxGetPr(prhs[3]), 9);\n    Matrix3d R1 = Map<Matrix3d>(R1_tmp.data(), 3, 3);\n    Matrix3d R2 = Map<Matrix3d>(R2_tmp.data(), 3, 3);\n\n    double *f1 = mxGetPr(prhs[4]);\n\n    // Compute output\n\tPoseData posedata = get_floor_Hf(x1, x2, R1, R2, f1[0]);\n\n    // Wrap it up to Matlab compatible output\n\tplhs[0] = mxCreateDoubleMatrix(3, 3, mxREAL);\n\tdouble* zr = mxGetPr(plhs[0]);\n    for (Index i = 0; i < posedata.homography.size(); i++) {\n        zr[i] = posedata.homography(i);\n    }\n\n    plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);\n    zr = mxGetPr(plhs[1]);\n    zr[0] = posedata.focal_length;\n}\n#endif\n\n// Function that utilizes the last equation of the DLT system to discard false solutions\ndouble get_algebraic_error_floor_Hf(VectorXd &data)\n{\n    const double* d = data.data();\n\n    // Compute algebraic error\n    double error;\n    error = -d[0]*d[5]*d[14]*d[25] - d[0]*d[14]*d[16]*d[19] - d[0]*d[14]*d[17]*d[22] - d[1]*d[5]*d[25] - d[1]*d[16]*d[19] - d[1]*d[17]*d[22] - d[2]*d[5]*d[15]*d[25] - d[2]*d[15]*d[16]*d[19] - d[2]*d[15]*d[17]*d[22] + d[3]*d[5]*d[15]*d[24] + d[3]*d[15]*d[16]*d[18] + d[3]*d[15]*d[17]*d[21];\n\n    return abs(error);\n}\n", "meta": {"hexsha": "d0e7dc25b7d77aab6cc90362e6416430c76fec91", "size": 5474, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/floor_Hf/get_floor_Hf.cpp", "max_stars_repo_name": "marcusvaltonen/minimal_indoor_uav", "max_stars_repo_head_hexsha": "79f3a26f2a6c10ee74a9fb70c5f3b42e4cf105ca", "max_stars_repo_licenses": ["MIT"], "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++/floor_Hf/get_floor_Hf.cpp", "max_issues_repo_name": "marcusvaltonen/minimal_indoor_uav", "max_issues_repo_head_hexsha": "79f3a26f2a6c10ee74a9fb70c5f3b42e4cf105ca", "max_issues_repo_licenses": ["MIT"], "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++/floor_Hf/get_floor_Hf.cpp", "max_forks_repo_name": "marcusvaltonen/minimal_indoor_uav", "max_forks_repo_head_hexsha": "79f3a26f2a6c10ee74a9fb70c5f3b42e4cf105ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-15T17:05:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T17:05:32.000Z", "avg_line_length": 33.1757575758, "max_line_length": 289, "alphanum_fraction": 0.6114358787, "num_tokens": 1777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.528179859934633}}
{"text": "#include <sequential-line-search/preferenceregressor.h>\n#include <sequential-line-search/utils.h>\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <Eigen/LU>\n#include <nlopt-util.hpp>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\n//#define VERBOSE\n//#define NOISELESS\n\n#ifdef VERBOSE\n#include <timer.hpp>\n#endif\n\nnamespace\n{\n    using namespace sequential_line_search;\n    \n#ifdef NOISELESS\n    const double b_fixed = 1e-06;\n#endif\n    \n    inline double calc_grad_a(const VectorXd& y, const MatrixXd& C_inv, const MatrixXd& X, double a, double b, const VectorXd& r)\n    {\n        const double   a_prior  = PreferenceRegressor::Params::getInstance().a;\n        const double   variance = PreferenceRegressor::Params::getInstance().variance;\n        \n        const MatrixXd C_grad_a             = Regressor::calc_C_grad_a(X, a, b, r);\n        const double   log_p_f_theta_grad_a = 0.5 * y.transpose() * C_inv * C_grad_a * C_inv * y - 0.5 * (C_inv * C_grad_a).trace();\n        const double   log_prior            = (std::log(a_prior) - variance - std::log(a)) / (variance * a);\n        return log_p_f_theta_grad_a + log_prior;\n    }\n    \n#ifndef NOISELESS\n    inline double calc_grad_b(const VectorXd& y, const MatrixXd& C_inv, const MatrixXd& X, double a, double b, const VectorXd& r)\n    {\n        const double   b_prior  = PreferenceRegressor::Params::getInstance().b;\n        const double   variance = PreferenceRegressor::Params::getInstance().variance;\n        \n        const MatrixXd C_grad_b             = Regressor::calc_C_grad_b(X, a, b, r);\n        const double   log_p_f_theta_grad_b = 0.5 * y.transpose() * C_inv * C_grad_b * C_inv * y - 0.5 * (C_inv * C_grad_b).trace();\n        const double   log_prior            = (std::log(b_prior) - variance - std::log(b)) / (variance * b);\n        return log_p_f_theta_grad_b + log_prior;\n    }\n#endif\n    \n    inline VectorXd calc_grad_r(const VectorXd& y, const MatrixXd& C_inv, const MatrixXd& X, double a, double b, const VectorXd& r)\n    {\n        const double   r_prior  = PreferenceRegressor::Params::getInstance().r;\n        const double   variance = PreferenceRegressor::Params::getInstance().variance;\n        \n        VectorXd grad = VectorXd::Zero(r.rows());\n        for (unsigned i = 0; i < r.rows(); ++ i)\n        {\n            const MatrixXd C_grad_r               = Regressor::calc_C_grad_r_i(X, a, b, r, i);\n            const double   log_p_f_theta_grad_r_i = 0.5 * y.transpose() * C_inv * C_grad_r * C_inv * y - 0.5 * (C_inv * C_grad_r).trace();\n            grad(i) += log_p_f_theta_grad_r_i;\n        }\n        for (unsigned i = 0; i < r.rows(); ++ i)\n        {\n            const double log_prior = (std::log(r_prior) - variance - std::log(r(i))) / (variance * r(i));\n            grad(i) += log_prior;\n        }\n        \n        return grad;\n    }\n    \n    // log p(d_k | f)\n    inline double calc_log_likelihood(const Preference& p, const double w, const VectorXd& y)\n    {\n        const double btl_scale = w * PreferenceRegressor::Params::getInstance().btl_scale;\n        \n        VectorXd tmp(p.size()); for (unsigned i = 0; i < p.size(); ++ i) tmp(i) = y(p[i]);\n        return std::log(utils::BTL(tmp, btl_scale));\n    }\n    \n    // Log likelihood that will be maximized\n    double objective(const std::vector<double> &x, std::vector<double>& grad, void* data)\n    {\n        const PreferenceRegressor* regressor = static_cast<PreferenceRegressor*>(data);\n        \n        const MatrixXd&                X = regressor->X;\n        const std::vector<Preference>& D = regressor->D;\n        const VectorXd&                w = regressor->w;\n        const unsigned                 M = X.cols();\n        const VectorXd                 y = Eigen::Map<const VectorXd>(&x[0], M);\n        \n        const double   a = (regressor->use_MAP_hyperparameters) ? x[M + 0] : PreferenceRegressor::Params::getInstance().a;\n#ifdef NOISELESS\n        const double   b = b_fixed;\n#else\n        const double   b = (regressor->use_MAP_hyperparameters) ? x[M + 1] : PreferenceRegressor::Params::getInstance().b;\n#endif\n        const VectorXd r = (regressor->use_MAP_hyperparameters) ? VectorXd(Eigen::Map<const VectorXd>(&x[M + 2], X.rows())) : VectorXd::Constant(X.rows(), PreferenceRegressor::Params::getInstance().r);\n        \n        double obj = 0.0;\n        \n        // Log likelihood of data\n        for (unsigned i = 0; i < D.size(); ++ i)\n        {\n            obj += calc_log_likelihood(D[i], w(i), y);\n        }\n        \n        // Log likelihood of y distribution\n        const MatrixXd C     = Regressor::calc_C(X, a, b, r);\n        const MatrixXd C_inv = C.inverse();\n        const double   C_det = C.determinant();\n        const double   term1 = - 0.5 * y.transpose() * C_inv * y;\n        const double   term2 = - 0.5 * std::log(C_det);\n        const double   term3 = - 0.5 * M * std::log(2.0 * M_PI);\n        obj += term1 + term2 + term3;\n        \n        if (regressor->use_MAP_hyperparameters)\n        {\n            // Priors for GP parameters\n            const double   a_prior  = PreferenceRegressor::Params::getInstance().a;\n#ifndef NOISELESS\n            const double   b_prior  = PreferenceRegressor::Params::getInstance().b;\n#endif\n            const double   r_prior  = PreferenceRegressor::Params::getInstance().r;\n            const double   variance = PreferenceRegressor::Params::getInstance().variance;\n            \n            obj += std::log(utils::log_normal(a, std::log(a_prior), variance));\n#ifndef NOISELESS\n            obj += std::log(utils::log_normal(b, std::log(b_prior), variance));\n#endif\n            for (unsigned i = 0; i < r.rows(); ++ i)\n            {\n                obj += std::log(utils::log_normal(r(i), std::log(r_prior), variance));\n            }\n        }\n        \n        // When the algorithm is gradient-based, compute the gradient vector\n        if (grad.size() == x.size())\n        {\n            VectorXd grad_y = VectorXd::Zero(y.rows());\n            \n            // Accumulate per-data derivatives\n            const double btl_scale = PreferenceRegressor::Params::getInstance().btl_scale;\n            for (unsigned i = 0; i < D.size(); ++ i)\n            {\n                const Preference& p = D[i];\n                const double      s = btl_scale * w(i);\n                VectorXd tmp1(p.size()); for (unsigned i = 0; i < p.size(); ++ i) tmp1(i) = y(p[i]);\n                const VectorXd tmp2 = utils::derivative_BTL(tmp1, s) / utils::BTL(tmp1, s);\n                for (unsigned i = 0; i < p.size(); ++ i) grad_y(p[i]) += tmp2(i);\n            }\n            \n            // Add GP term\n            grad_y += - C_inv * y;\n            \n            Eigen::Map<VectorXd>(&grad[0], grad_y.rows()) = grad_y;\n            \n            if (regressor->use_MAP_hyperparameters)\n            {\n                grad[M + 0] = calc_grad_a(y, C_inv, X, a, b, r);\n#ifdef NOISELESS\n                grad[M + 1] = 0.0;\n#else\n                grad[M + 1] = calc_grad_b(y, C_inv, X, a, b, r);\n#endif\n                VectorXd grad_r = calc_grad_r(y, C_inv, X, a, b, r);\n                for (unsigned i = 0; i < grad_r.rows(); ++ i)\n                {\n                    grad[M + 2 + i] = grad_r(i);\n                }\n            }\n            else\n            {\n                grad[M + 0] = 0.0;\n                grad[M + 1] = 0.0;\n                grad[M + 2] = 0.0;\n            }\n        }\n        \n        return obj;\n    }\n    \n}\n\nnamespace sequential_line_search\n{\n    PreferenceRegressor::PreferenceRegressor(const MatrixXd &X, const std::vector<Preference>& D, bool use_MAP_hyperparameters) :\n    use_MAP_hyperparameters(use_MAP_hyperparameters),\n    X(X),\n    D(D)\n    {\n        if (X.cols() == 0 || D.size() == 0) return;\n        \n        w = Eigen::VectorXd::Ones(D.size());\n        \n        compute_MAP();\n        \n        C     = calc_C(X, a, b, r);\n        C_inv = C.inverse();\n    }\n    \n    PreferenceRegressor::PreferenceRegressor(const MatrixXd &X, const std::vector<Preference>& D, const Eigen::VectorXd &w, bool use_MAP_hyperparameters) :\n    use_MAP_hyperparameters(use_MAP_hyperparameters),\n    X(X),\n    D(D),\n    w(w)\n    {\n        if (X.cols() == 0 || D.size() == 0) return;\n        \n        compute_MAP();\n        \n        C     = calc_C(X, a, b, r);\n        C_inv = C.inverse();\n    }\n    \n    PreferenceRegressor::PreferenceRegressor(const MatrixXd &X, const std::vector<Preference>& D, const Eigen::VectorXd &w, bool use_MAP_hyperparameters, const PreferenceRegressor* previous) :\n    use_MAP_hyperparameters(use_MAP_hyperparameters),\n    X(X),\n    D(D),\n    w(w)\n    {\n        if (X.cols() == 0 || D.size() == 0) return;\n        \n        compute_MAP(previous);\n        \n        C     = calc_C(X, a, b, r);\n        C_inv = C.inverse();\n    }\n    \n    double PreferenceRegressor::estimate_y(const VectorXd &x) const\n    {\n        const VectorXd k = Regressor::calc_k(x, X, a, b, r);\n        return k.transpose() * C_inv * y;\n    }\n    \n    double PreferenceRegressor::estimate_s(const VectorXd &x) const\n    {\n        const VectorXd k = Regressor::calc_k(x, X, a, b, r);\n        return std::sqrt(a + b - k.transpose() * C_inv * k);\n    }\n    \n    void PreferenceRegressor::compute_MAP(const PreferenceRegressor *previous)\n    {\n        const unsigned M = X.cols();\n        const unsigned d = X.rows();\n        \n        VectorXd upper = VectorXd::Constant(M + 2 + d, + 1e+01);\n        VectorXd lower = VectorXd::Constant(M + 2 + d, - 1e+01); lower.block(M, 0, 2 + d, 1) = VectorXd::Constant(2 + d, 1e-05);\n        VectorXd x_ini = VectorXd::Constant(M + 2 + d, 0.0);\n        x_ini(M + 0) = Params::getInstance().a;\n        x_ini(M + 1) = Params::getInstance().b;\n        x_ini.block(M + 2, 0, d, 1) = VectorXd::Constant(d, Params::getInstance().r);\n        \n        // Use the MAP estimated values in previous regression as initial values\n        if (previous != nullptr)\n        {\n            for (unsigned i = 0; i < M; ++ i)\n            {\n                x_ini(i) = previous->estimate_y(X.col(i));\n            }\n            x_ini(M + 0) = previous->a;\n            x_ini(M + 1) = previous->b;\n            x_ini.block(M + 2, 0, d, 1) = previous->r;\n        }\n        \n#ifdef VERBOSE\n        timer::Timer t(\"PreferenceRegressor::compute_MAP\");\n#endif\n        \n        const VectorXd x_opt = nloptutil::solve(x_ini, upper, lower, objective, nlopt::LD_TNEWTON, this, 500);\n        \n        y = x_opt.block(0, 0, M, 1);\n        \n        if (use_MAP_hyperparameters)\n        {\n            a = x_opt(M + 0);\n#ifdef NOISELESS\n            b = b_fixed;\n#else\n            b = x_opt(M + 1);\n#endif\n            r = x_opt.block(M + 2, 0, d, 1);\n            \n#ifdef VERBOSE\n            std::cout << \"Learned hyperparameters ... a: \" << a << \", \\tb: \" << b << \", \\tr: \" << r.transpose() << std::endl;\n#endif\n        }\n        else\n        {\n            a = PreferenceRegressor::Params::getInstance().a;\n            b = PreferenceRegressor::Params::getInstance().b;\n            r = VectorXd::Constant(d, PreferenceRegressor::Params::getInstance().r);\n        }\n    }\n    \n    ///////////////////////////////////////////////////////////////////\n    \n#if 0\n    namespace\n    {\n        \n        double objective_function(const std::vector<double> &x, std::vector<double>& grad, void* data)\n        {\n            const PreferenceRegressor* regressor = static_cast<PreferenceRegressor*>(data);\n            \n            const unsigned M = x.size();\n            \n            if (!grad.empty())\n            {\n                const VectorXd  x_vec = Eigen::Map<const VectorXd>(&x[0], M);\n                const MatrixXd& X     = regressor->X;\n                const MatrixXd& C_inv = regressor->C_inv;\n                const VectorXd& y     = regressor->y;\n                const unsigned  N     = y.rows();\n                const double    a     = regressor->a;\n                const double    l     = regressor->l;\n                \n                MatrixXd k_derivative(M, N);\n                \n                for (unsigned i = 0; i < N; ++ i)\n                {\n                    const double   tmp            = (- 0.5 / (l * l)) * (x_vec - X.col(i)).squaredNorm();\n                    const VectorXd k_i_derivative = a * std::exp(tmp) * (- 1.0 / (l * l) * (x_vec - X.col(i)));\n                    \n                    k_derivative.col(i) = k_i_derivative;\n                }\n                \n                const MatrixXd grad_vec = k_derivative * (C_inv * y);\n                Eigen::Map<VectorXd>(&grad[0], M) = grad_vec;\n            }\n            \n            return regressor->estimate_y(Eigen::Map<const VectorXd>(&x[0], M));\n        }\n        \n    }\n#endif\n    \n    VectorXd PreferenceRegressor::find_arg_max()\n    {\n        const unsigned M = X.rows();\n        \n        assert (M != 0);\n        \n        int i; y.maxCoeff(&i);\n#if 0\n        const VectorXd x_initial = X.col(i);\n        const VectorXd upper     = VectorXd::Constant(M, 1.0);\n        const VectorXd lower     = VectorXd::Constant(M, 0.0);\n        \n        return nloptutils::compute(x_initial, upper, lower, objective_function, static_cast<void*>(this), nlopt::LD_TNEWTON, 100);\n#else\n        return X.col(i);\n#endif\n    }\n    \n    void PreferenceRegressor::dampData(const std::string &dirPath) const\n    {\n        // Export X using CSV\n        utils::exportMatrixToCsv(dirPath + \"/X.csv\", X);\n        \n        // Export D using CSV\n        std::ofstream ofs_D(dirPath + \"/D.csv\");\n        for (unsigned i = 0 ; i < D.size(); ++ i)\n        {\n            for (unsigned j = 0; j < D[i].size(); ++ j)\n            {\n                ofs_D << D[i][j];\n                if (j + 1 != D[i].size()) ofs_D << \",\";\n            }\n            ofs_D << std::endl;\n        }\n    }\n}\n", "meta": {"hexsha": "daa1d6fee6ef70be554bb49258f0217f1468c636", "size": 13731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/preferenceregressor.cpp", "max_stars_repo_name": "stnoh/sequential-line-search", "max_stars_repo_head_hexsha": "3d40aa23facf6f23e6ed8835c928dd229b7a35ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/preferenceregressor.cpp", "max_issues_repo_name": "stnoh/sequential-line-search", "max_issues_repo_head_hexsha": "3d40aa23facf6f23e6ed8835c928dd229b7a35ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/preferenceregressor.cpp", "max_forks_repo_name": "stnoh/sequential-line-search", "max_forks_repo_head_hexsha": "3d40aa23facf6f23e6ed8835c928dd229b7a35ae", "max_forks_repo_licenses": ["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.7139037433, "max_line_length": 201, "alphanum_fraction": 0.5262544607, "num_tokens": 3545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5281061707213821}}
{"text": "/*\n   Copyright (C) 2016-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// Calculating free energy density of quantum antiferomagnetic Heisenberg chain\n\n#pragma once\n\n#include <Eigen/Dense>\n#include \"standards/exp_number.hpp\"\n#include \"chain.hpp\"\n\nnamespace afh { namespace free_energy { namespace chain {\n    \nclass finite {\n  typedef std::size_t uint_t;\n  typedef Eigen::VectorXd vector_t;\n  typedef Eigen::MatrixXd matrix_t;\npublic:\n  finite(uint_t L) : L_(L), eigenvalues_(1 << L_) {\n    // lattice\n    std::vector<std::pair<uint_t, uint_t> > lattice;\n    for (uint_t i = 0; i < L_; ++i) lattice.push_back(std::make_pair(i, (i+1) % L_));\n    \n    // generate Hamiltonian\n    uint_t dim = 1 << L_;\n    matrix_t hamiltonian(dim, dim);\n    afh::free_energy::chain::generate(L_, lattice, hamiltonian);\n  \n    /* perform eigenvalue decomposition */\n    Eigen::SelfAdjointEigenSolver<matrix_t> eigensolver(hamiltonian);\n    eigenvalues_ = eigensolver.eigenvalues();\n  }\n  double gs_energy() const { return eigenvalues_(0) / L_; }\n  double gap() const { return eigenvalues_(1) - eigenvalues_(0); }\n  std::tuple<double, double, double> free_energy(double t) const {\n    // calculate free energy and intternal energy\n    uint_t dim = 1 << L_;\n    double beta = 1 / t;\n    standards::exp_double z = 0;\n    standards::exp_double w = 0;\n    for (uint_t i = 0; i < dim; ++i) {\n      uint_t j = dim - i - 1;\n      z += standards::exp_double::exp(-beta * eigenvalues_(j));\n      w += eigenvalues_(j) * standards::exp_double::exp(-beta * eigenvalues_(j));\n    }\n    double f = - log(z) / (beta * L_);\n    double e = w / z / L_;\n    return std::make_tuple(f, e, beta * (e-f));\n  }\nprivate:\n  uint_t L_;\n  vector_t eigenvalues_;\n};\n\n} } }\n", "meta": {"hexsha": "6c70d42020a5d0c1a90204c2c7cbc1ab7640f6f3", "size": 2283, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "afh/free_energy/chain_finite.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": "afh/free_energy/chain_finite.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": "afh/free_energy/chain_finite.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": 33.0869565217, "max_line_length": 85, "alphanum_fraction": 0.6758650898, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.528106164905348}}
{"text": "/**\n * \\file dcs/math/random/mersenne_twister.hpp\n *\n * \\brief Mersenne Twister Random Number Engine.\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_RANDOM_MERSENNE_TWISTER_HPP\n#define DCS_MATH_RANDOM_MERSENNE_TWISTER_HPP\n\n\n#include <dcs/detail/config/boost.hpp>\n\n#if !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(101500) // 1.15\n#\terror \"Required Boost libraries version >= 1.15.\"\n#endif\n\n\n#include <boost/random/mersenne_twister.hpp>\n#include <dcs/math/random/base_generator.hpp>\n#include <cstddef>\n#include <stdint.h>\n\n\nnamespace dcs { namespace math { namespace random {\n\n/**\n * \\brief A mersenne_twister random number engine produces unsigned integer\n * random numbers in the closed interval \\f$[0, 2^w \u2212 1]\\f$.\n *\n * \\tparam UIntT The type of randomly generated numbers.\n * \\tparam w The word size.\n * \\tparam n The state size.\n * \\tparam m The shift size.\n * \\tparam r The mask bits.\n * \\tparam a The XOR mask.\n * \\tparam u The tempering.\n * \\tparam s The tempering.\n * \\tparam b The tempering.\n * \\tparam t The tempering.\n * \\tparam c The parameter.\n * \\tparam l The tempering.\n *\n * A mersenne_twister random number engine produces unsigned integer random\n * numbers in the closed interval \\f$[0, 2^{nw-r} \u2212 1]\\f$.\n * The state \\f$x_i\\f$ of a mersenne_twister object \\f$x\\f$ is of size \\f$n\\f$\n * and consists of a sequence \\f$X\\f$ of \\f$n\\f$ values of the type delivered by\n * \\f$x\\f$; all subscripts applied * to \\f$X\\f$ are to be taken modulo \\f$n\\f$.\n * The transition algorithm employs a twisted generalized feedback shift\n * register defined by shift values \\f$n\\f$ and \\f$m\\f$, a twist value \\f$r\\f$,\n * and a conditional xor-mask \\f$a\\f$.\n * To improve the uniformity of the result, the bits of the raw shift register\n * are additionally tempered (i.e., scrambled) according to a bit-scrambling\n * matrix defined by values \\f$u\\f$, \\f$s\\f$, \\f$b\\f$, \\f$t\\f$,\n * \\f$c\\f$, and \\f$l\\f$.\n * The state transition is performed as follows:\n * a) Concatenate the upper \\f$w-r\\f$ bits of \\f$X_{i-n}\\f$ with the lower\n *    \\f$r\\f$ bits of \\f$X_{i+1-n}\\f$ to obtain an unsigned integer value \\f$Y\\f$.\n * b) With \\f$\\alpha=a*(Y \\wedge 1)\\f$, set \\f$X_i\\f$ to\n *    \\f$X_{i+m-n} \\oplus (Y >> 1) xor \\alpha\\f$\n * The generation algorithm determines the unsigned integer values \\f$z_1\\f$,\n * \\f$z_2\\f$, \\f$z_3\\f$, \\f$z_4\\f$ as follows, then delivers \\f$z_4\\f$ as its\n * result:\n * a) Let \\f$z_1 = X_i \\oplus ((X_i >> u)\\f$.\n * b) Let \\f$z_2 = z_1 \\oplus ((z_1 << s) \\wedge b)\\f$.\n * c) Let \\f$z_3 = z_2 \\oplus ((z_2 << t) \\wedge c)\\f$. \n * d) Let \\f$z_4 = z_3 \\oplus (z_3 >> l).\n *\n * This class implements the \\c RandomNumberEngine concept.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate <\n\ttypename UIntT,\n\t::std::size_t w,\n\t::std::size_t n,\n\t::std::size_t m,\n\t::std::size_t r,\n\tUIntT a,\n\t::std::size_t u,\n\t::std::size_t s,\n\tUIntT b,\n\t::std::size_t t,\n\tUIntT c,\n\t::std::size_t l\n>\nclass mersenne_twister: public base_generator<UIntT>\n{\n\tprivate: typedef base_generator<UIntT> base_type;\n\tpublic: typedef UIntT result_type;\n\tpublic: typedef typename base_type::ulonglong_type ulonglong_type;\n\tprivate: typedef ::boost::random::mersenne_twister<UIntT,w,n,m,r,a,u,s,b,t,c,l,0> impl_type;\n\n\n\tpublic: static const ::std::size_t word_size = w;\n\tpublic: static const ::std::size_t state_size = n;\n\tpublic: static const ::std::size_t shift_size = m;\n\tpublic: static const ::std::size_t mask_bits = r;\n\tpublic: static const result_type xor_mask = a;\n\tpublic: static const ::std::size_t tempering_u = u;\n\tpublic: static const ::std::size_t tempering_s = s;\n\tpublic: static const result_type tempering_b = b;\n\tpublic: static const ::std::size_t tempering_t = t;\n\tpublic: static const result_type parameter_c = c;\n\tpublic: static const ::std::size_t tempering_l = l;\n\tpublic: static const result_type default_seed = impl_type::default_seed;\n\n\n\tpublic: mersenne_twister()\n\t\t: impl_()\n\t{\n\t\t// empty\n\t}\n\n\n\tpublic: explicit mersenne_twister(result_type z)\n\t\t: impl_(z)\n\t{\n\t\t// empty\n\t}\n\n\n//\tpublic: template <typename ItT>\n//\t\tmersenne_twister(ItT& first, ItT& last)\n//\t\t: impl_(first,last)\n//\t{\n//\t\t// empty\n//\t}\n\n\n//\tpublic: template <typename ItT>\n//\t\tvoid seed(ItT& first, ItT& last)\n//\t{\n//\t\timpl_.seed(first, last);\n//\t}\n\n\n\tpublic: static result_type min()\n\t{\n\t\t//return impl_type::min();//FIXME: has not been implemented yet\n\t\treturn 0;\n\t}\n\n\n\tpublic: static result_type max()\n\t{\n\t\t//return impl_type::max();//FIXME: has not been implemented yet\n\t\t// 2^w-1\n\t\tresult_type res = 0;\n\t\tfor(size_t i = 0; i < w; ++i)\n\t\t{\n\t\t\tres |= (1u << i);\n\t\t}\n\t\treturn res;\n\t}\n\n\n\tprivate: result_type do_min() const\n\t{\n\t\treturn impl_.min();\n\t}\n\n\n\tprivate: result_type do_max() const\n\t{\n\t\treturn impl_.max();\n\t}\n\n\n\tprivate: void do_seed()\n\t{\n\t\timpl_.seed();\n\t}\n\n\n\tprivate: void do_seed(result_type z)\n\t{\n\t\timpl_.seed(z);\n\t}\n\n\n\tprivate: result_type do_generate()\n\t{\n\t\treturn impl_();\n\t}\n\n\n\t//FIXME: actually cannot use impl_.discard since it is defined only when\n\t//       BOOST_NO_LONG_LONG is undefined.\n\tprivate: void do_discard(ulonglong_type z)\n\t{\n\t\tfor ( ; z != 0; --z)\n\t\t{\n\t\t\tthis->operator()();\n\t\t}\n\n//\t\timpl_.discard(z);\n\t}\n\n\n\tpublic: friend bool operator==(mersenne_twister const& x, mersenne_twister const& y)\n\t{\n\t\treturn x.impl_ == y.impl_;\n\t}\n\n\n\tpublic: friend bool operator!=(mersenne_twister const& x, mersenne_twister const& y)\n\t{\n\t\treturn !(x == y);\n\t}\n\n\n\tprivate: impl_type impl_;\n};\n\n\ntypedef mersenne_twister<uint32_t, 32, 351, 175, 19, 0xccab8ee7, 11, 7, 0x31b6ab00, 15, 0xffe50000, 17> mt11213b;\ntypedef mersenne_twister<uint32_t, 32, 624, 397, 31, 0x9908b0df, 11, 7, 0x9d2c5680, 15, 0xefc60000, 18> mt19937;\n\n\n}}} // Namespace dcs::math::random\n\n\n#endif // DCS_MATH_RANDOM_MERSENNE_TWISTER_HPP\n", "meta": {"hexsha": "35dc6bc73a4b6776aa40d0a8628049487bb0eea6", "size": 6370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/random/mersenne_twister.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/random/mersenne_twister.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/random/mersenne_twister.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.3223140496, "max_line_length": 113, "alphanum_fraction": 0.6811616954, "num_tokens": 2002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410783, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5281061622701351}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#pragma once\n#include <eve/detail/skeleton_calls.hpp>\n#include <eve/detail/hz_device.hpp>\n#include <eve/concept/value.hpp>\n#include <eve/function/if_else.hpp>\n#include <eve/function/oneminus.hpp>\n#include <eve/function/normal_distribution.hpp>\n#include <eve/function/lognormal_distribution.hpp>\n#include <eve/function/diff/gamma_p.hpp>\n#include <eve/function/abs.hpp>\n#include <eve/function/any.hpp>\n#include <eve/function/average.hpp>\n#include <eve/function/none.hpp>\n#include <eve/function/converter.hpp>\n#include <eve/function/dec.hpp>\n#include <eve/function/is_eqz.hpp>\n#include <eve/function/is_not_nan.hpp>\n#include <eve/function/is_lez.hpp>\n#include <eve/function/is_not_less.hpp>\n#include <eve/function/lgamma.hpp>\n#include <eve/function/log.hpp>\n#include <eve/function/log1p.hpp>\n#include <eve/function/max.hpp>\n#include <eve/function/min.hpp>\n#include <eve/function/rec.hpp>\n#include <eve/function/sqr.hpp>\n#include <eve/function/sqrt.hpp>\n#include <eve/constant/one.hpp>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/eps.hpp>\n#include <eve/function/ulpdist.hpp>\n#include <eve/function/next.hpp>\n#include <eve/function/nb_values.hpp>\n#include <eve/constant/valmax.hpp>\n#include <eve/constant/inf.hpp>\n#include <type_traits>\n#include <boost/math/special_functions/gamma.hpp>\n#include <tts/tts.hpp>\n#include <iomanip>\nnamespace eve::detail\n{\n\n  template<real_value T, real_value U>\n  EVE_FORCEINLINE  auto gamma_pinv_(EVE_SUPPORTS(cpu_)\n                              , T a\n                              , U b) noexcept\n  requires compatible_values<T, U>\n  {\n    return arithmetic_call(gamma_pinv, a, b);\n  }\n\n  template<floating_real_value T>\n  EVE_FORCEINLINE T gamma_pinv_(EVE_SUPPORTS(cpu_), T p, T k) noexcept\n  requires has_native_abi_v<T>\n  {\n    if constexpr(std::is_same_v<T, float>)\n    {\n      return float32(gamma_pinv(float64(p), float64(k)));\n    }\n    p = if_else(is_ltz(p) || p > one(as(p)), allbits, p);\n    auto iseqzp = is_eqz(p);\n    auto iseq1p = p == one(as(p));\n    auto x = if_else(iseq1p, inf(as(p)), if_else(iseqzp, zero(as(p)), allbits));\n    logical<T> notdone(is_not_nan(p) && !iseqzp && !iseq1p);\n    auto d = rec(9*k);\n    auto y = oneminus(d + invcdf(normal_distribution_01<T>, oneminus(p)) * eve::sqrt(d));\n\n    x = if_else(notdone, k*sqr(y)*y, x);\n    auto x0 = x;\n    int i = 10;\n    if (eve::none(notdone)) return x;\n    while(i)\n    {\n      auto dx = if_else(notdone, (gamma_p(x, k)-p)/diff(gamma_p)(x, k), zero);\n      x -= dx;\n      if (i < 7) notdone = notdone && is_not_less(abs(dx), 4*eps(as(x))*max(eve::abs(x), one(as(x))));\n      if (eve::none(notdone)) return x;\n      --i;\n    }\n    notdone =  notdone || is_ltz(y);\n    x = if_else(notdone, eve::abs(x0), x);\n    auto xlo = if_else(notdone, eve::min(x/2, zero(as(x))), x);\n    auto xhi = if_else(notdone, eve::min(x*2, eve::valmax(as(x))), x);\n    auto inl = ((gamma_p(xlo, k) > p)||(gamma_p(xhi, k) <  p)) && (xlo !=  xhi);\n    while (eve::any(inl))\n    {\n      xlo = if_else(inl, eve::max(xlo/2, zero(as(x))), xlo);\n      xhi  = if_else(inl, eve::min(xhi*2, eve::valmax(as(x))), xhi);\n      inl = ((gamma_p(xlo, k) > p)||(gamma_p(xhi, k) <  p)) && (xlo !=  xhi);\n    }\n    auto xmed = average(xlo, xhi);\n    while (eve::any(notdone))\n    {\n      auto test = (gamma_p(xmed, k) <  p);\n      xlo = if_else(test, xmed, xlo);\n      xhi = if_else(test, xhi, xmed);\n      notdone = ulpdist(xlo, xhi) > 1;\n      xmed = average(xlo, xhi);\n    }\n    xmed = if_else(iseq1p, inf(as(p)), if_else(iseqzp, zero(as(p)), xmed));\n    return if_else(k == one(as(k)),  -eve::log1p(-p), xmed);\n  }\n}\n", "meta": {"hexsha": "ca5273d8ef14230d9b2c37f4ca422d89151a7d0a", "size": 3913, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/eve/module/real/special/function/regular/generic/gamma_pinv.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "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/eve/module/real/special/function/regular/generic/gamma_pinv.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "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/eve/module/real/special/function/regular/generic/gamma_pinv.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["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.2522522523, "max_line_length": 102, "alphanum_fraction": 0.6072067467, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5280595644491143}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Surface_mesh.h>\n\n#if defined(CGAL_USE_OPENMESH)\n#include <OpenMesh/Core/IO/MeshIO.hh>\n#include <OpenMesh/Core/Mesh/PolyMesh_ArrayKernelT.hh>\n#include <CGAL/boost/graph/graph_traits_PolyMesh_ArrayKernelT.h>\n#endif\n\n#include <CGAL/boost/graph/copy_face_graph.h>\n\n#include <iostream>\n#include <fstream>\n#include <iterator>\n\n#include <boost/unordered_map.hpp>\n\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\n\ntypedef CGAL::Polyhedron_3<Kernel>                       Source;\ntypedef boost::graph_traits<Source>::vertex_descriptor   sm_vertex_descriptor;\ntypedef boost::graph_traits<Source>::halfedge_descriptor sm_halfedge_descriptor;\ntypedef boost::graph_traits<Source>::face_descriptor     sm_face_descriptor;\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel Other_kernel;\ntypedef Other_kernel::Point_3                             Point;\n\nint main(int argc, char* argv[])\n{\n  Source S;\n\n  std::ifstream in((argc>1)?argv[1]:CGAL::data_file_path(\"meshes/cube_poly.off\"));\n  in >> S;\n  assert( CGAL::is_valid_polygon_mesh(S) );\n\n  // Note that the vertex_point property of the Source and Target1\n  // come from different kernels.\n  typedef CGAL::Surface_mesh<Point> Target1;\n  Target1 T1;\n  CGAL::copy_face_graph(S, T1);\n  assert( CGAL::is_valid_polygon_mesh(T1) );\n  assert( vertices(S).size()==vertices(T1).size() );\n  assert( halfedges(S).size()==halfedges(T1).size() );\n  assert( faces(S).size()==faces(T1).size() );\n\n#if defined(CGAL_USE_OPENMESH)\n  typedef OpenMesh::PolyMesh_ArrayKernelT</* MyTraits*/> Target2;\n  Target2 T2;\n  {\n    typedef boost::graph_traits<Target2>::vertex_descriptor   tm_vertex_descriptor;\n    typedef boost::graph_traits<Target2>::halfedge_descriptor tm_halfedge_descriptor;\n    typedef boost::graph_traits<Target2>::face_descriptor     tm_face_descriptor;\n\n    // Use an unordered_map to keep track of elements.\n    boost::unordered_map<sm_vertex_descriptor, tm_vertex_descriptor>     v2v;\n    boost::unordered_map<sm_halfedge_descriptor, tm_halfedge_descriptor> h2h;\n    boost::unordered_map<sm_face_descriptor, tm_face_descriptor>         f2f;\n\n    CGAL::copy_face_graph(S, T2, CGAL::parameters::vertex_to_vertex_output_iterator(std::inserter(v2v, v2v.end()))\n                                 .halfedge_to_halfedge_output_iterator(std::inserter(h2h, h2h.end()))\n                                 .face_to_face_output_iterator(std::inserter(f2f, f2f.end())));\n    assert( CGAL::is_valid_polygon_mesh(T2) );\n    assert( v2v.size()==vertices(T2).size() );\n    assert( h2h.size()==halfedges(T2).size() );\n    assert( f2f.size()==faces(T2).size() );\n    assert( vertices(S).size()==vertices(T2).size() );\n    assert( halfedges(S).size()==halfedges(T2).size() );\n    assert( faces(S).size()==faces(T2).size() );\n  }\n#endif\n  S.clear();\n  {\n    typedef boost::graph_traits<Target1>::vertex_descriptor   source_vertex_descriptor;\n    typedef boost::graph_traits<Target1>::halfedge_descriptor source_halfedge_descriptor;\n    typedef boost::graph_traits<Target1>::face_descriptor source_face_descriptor;\n\n    typedef boost::graph_traits<Source>::vertex_descriptor   tm_vertex_descriptor;\n    typedef boost::graph_traits<Source>::halfedge_descriptor tm_halfedge_descriptor;\n    typedef boost::graph_traits<Source>::face_descriptor   tm_face_descriptor;\n\n\n    boost::unordered_map<source_vertex_descriptor, tm_vertex_descriptor> v2v;\n    boost::unordered_map<source_halfedge_descriptor, tm_halfedge_descriptor> h2h;\n    boost::unordered_map<source_face_descriptor, tm_face_descriptor> f2f;\n    CGAL::copy_face_graph(T1, S, CGAL::parameters::vertex_to_vertex_map(boost::make_assoc_property_map(v2v))\n                          .halfedge_to_halfedge_output_iterator(std::inserter(h2h, h2h.end()))\n                          .face_to_face_map(boost::make_assoc_property_map(f2f)));\n\n    assert( CGAL::is_valid_polygon_mesh(S) );\n    assert( vertices(S).size()==vertices(T1).size() );\n    assert( halfedges(S).size()==halfedges(T1).size() );\n    assert( faces(S).size()==faces(T1).size() );\n  }\n  return 0;\n}\n", "meta": {"hexsha": "7840c805a7ec8ded4db6c2db740a16593841db11", "size": 4224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGL/examples/BGL_polyhedron_3/copy_polyhedron.cpp", "max_stars_repo_name": "brucerennie/cgal", "max_stars_repo_head_hexsha": "314b94aafa9b08a1d086accd2cadff1aae1b57a9", "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_polyhedron_3/copy_polyhedron.cpp", "max_issues_repo_name": "brucerennie/cgal", "max_issues_repo_head_hexsha": "314b94aafa9b08a1d086accd2cadff1aae1b57a9", "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_polyhedron_3/copy_polyhedron.cpp", "max_forks_repo_name": "brucerennie/cgal", "max_forks_repo_head_hexsha": "314b94aafa9b08a1d086accd2cadff1aae1b57a9", "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": 42.24, "max_line_length": 114, "alphanum_fraction": 0.7284564394, "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5280595530247305}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 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 analytichestonadengine.hpp\n  \\brief analytic pricing engine for a heston option\n  based on fourier transformation\n*/\n\n#include <ql/math/functional.hpp>\n#include <ql/instruments/payoffs.hpp>\n#include <ql/math/integrals/gaussianadquadratures.hpp>\n#include <ql/pricingengines/vanilla/analytichestonadengine.hpp>\n\n#include <boost/assign/std/vector.hpp>\nusing namespace boost::assign;\n\nnamespace QuantLib {\n\n\tnamespace {\n\t\tstd::complex<CppAD::AD<Real> > operator*(\n\t\t\tReal a, const std::complex<CppAD::AD<Real> >& b ) {\n\t\t\treturn std::complex<CppAD::AD<Real> >(a*b.real(), a*b.imag());\n\t\t}\n\t\tstd::complex<CppAD::AD<Real> > operator*(\n\t\t\tconst std::complex<CppAD::AD<Real> >& b, Real a) {\n\t\t\treturn a*b;\n\t\t}\n\t\tstd::complex<CppAD::AD<Real> > operator-(\n\t\t\tReal a, const std::complex<CppAD::AD<Real> >& b) {\n\t\t\treturn std::complex<CppAD::AD<Real> >(a - b.real(), -b.imag());\n\t\t}\n\t}\n\n    // helper class for integration\n    class AnalyticHestonADEngine::Fj_Helper\n        : public std::unary_function<Real, Real>\n    {\n    public:\n        Fj_Helper(\n        \tCppAD::AD<Real>& kappa,\n        \tCppAD::AD<Real>& theta,\n        \tCppAD::AD<Real>& sigma,\n        \tCppAD::AD<Real>& v0,\n        \tCppAD::AD<Real>& s0,\n        \tCppAD::AD<Real>& rho,\n            const AnalyticHestonADEngine* const engine,\n            ComplexLogFormula cpxLog,\n            Time term,\n            Real strike,\n            Real ratio,\n            Size j);\n\n        CppAD::AD<Real> operator()(Real phi)      const;\n\n    private:\n        const Size j_;\n        const CppAD::AD<Real> &kappa_, &theta_, &sigma_, &v0_;\n        const ComplexLogFormula cpxLog_;\n\n        // helper variables\n        const Time term_;\n        CppAD::AD<Real> x_;\n        const Real sx_;\n        CppAD::AD<Real> dd_;\n        const CppAD::AD<Real> sigma2_, rsigma_;\n        const CppAD::AD<Real> t0_;\n\n        // log branch counter\n        mutable int  b_;     // log branch counter\n        mutable Real g_km1_; // imag part of last log value\n\n        const AnalyticHestonADEngine* const engine_;\n    };\n\n\n\n    AnalyticHestonADEngine::Fj_Helper::Fj_Helper(\n\t\tCppAD::AD<Real>& kappa,\n\t\tCppAD::AD<Real>& theta,\n\t\tCppAD::AD<Real>& sigma,\n\t\tCppAD::AD<Real>& v0,\n\t\tCppAD::AD<Real>& s0,\n\t\tCppAD::AD<Real>& rho,\n        const AnalyticHestonADEngine* const engine,\n        ComplexLogFormula cpxLog,\n        Time term,\n        Real strike,\n        Real ratio,\n        Size j)\n        :\n        j_(j),\n        kappa_(kappa),\n        theta_(theta),\n        sigma_(sigma),\n        v0_(v0),\n        cpxLog_(cpxLog),\n        term_(term),\n        x_(log(s0)),\n        sx_(std::log(strike)),\n        dd_(x_-std::log(ratio)),\n        sigma2_(sigma_*sigma_),\n        rsigma_(rho*sigma_),\n        t0_(kappa - ((j== 1)? rho*sigma : 0)),\n        b_(0),\n        g_km1_(0),\n        engine_(engine) {\n    }\n\n\n    CppAD::AD<Real> AnalyticHestonADEngine::Fj_Helper::operator()(\n    \tReal phi) const {\n\n        const CppAD::AD<Real> rpsig(rsigma_*phi);\n\n        const std::complex<CppAD::AD<Real> > t1 =\n        \tt0_+std::complex<CppAD::AD<Real> >(0, -rpsig);\n        const std::complex<CppAD::AD<Real> > d =\n            std::sqrt(t1*t1 - sigma2_*phi\n                      *std::complex<CppAD::AD<Real> >(-phi, (j_== 1)? 1 : -1));\n        const std::complex<CppAD::AD<Real> > ex = exp(-d*term_);\n\n        if (cpxLog_ == Gatheral) {\n            if (phi != 0.0) {\n                if (sigma_ > 1e-5) {\n                    const std::complex<CppAD::AD<Real> > p = (t1-d)/(t1+d);\n                    const std::complex<CppAD::AD<Real> > g\n                        = log((1.0 - p*ex)/(1.0 - p));\n\n                    const std::complex<CppAD::AD<Real> > c(\n                    \tv0_*(t1-d)*(1.0-ex)/(sigma2_*(1.0-ex*p))\n                    \t+ (kappa_*theta_)/sigma2_*((t1-d)*term_-2.0*g));\n\n                    CppAD::AD<Real> im(c.imag()), re(c.real());\n\n                    return\n                        exp(std::complex<CppAD::AD<Real> >(re, im)\n\t\t\t\t\t\t\t + std::complex<CppAD::AD<Real> >(0.0, phi*(dd_-sx_))\n\t\t\t\t\t\t\t ).imag()/phi;\n                }\n                else {\n                \tQL_FAIL(\"ouch, sigma < 1e-5\");\n                }\n            }\n            else {\n            \tQL_FAIL(\"ouch, phi = 0\");\n            }\n        }\n        else if (cpxLog_ == BranchCorrection) {\n        \tQL_FAIL(\"ouch, BranchCorrection\");\n        }\n        else {\n            QL_FAIL(\"unknown complex logarithm formula\");\n        }\n    }\n\n    AnalyticHestonADEngine::AnalyticHestonADEngine(\n                              const boost::shared_ptr<HestonModel>& model,\n                              Size integrationOrder)\n    : GenericModelEngine<HestonModel,\n                         VanillaOption::arguments,\n                         VanillaOption::results>(model),\n      evaluations_(0),\n      cpxLog_     (Gatheral),\n      integration_(new Integration(\n                          Integration::gaussLaguerre(integrationOrder))) {\n    }\n\n\n    Size AnalyticHestonADEngine::numberOfEvaluations() const {\n        return evaluations_;\n    }\n\n    void AnalyticHestonADEngine::doCalculation(Real riskFreeDiscount,\n                                             Real dividendDiscount,\n                                             Real spotPrice,\n                                             Real strikePrice,\n                                             Real term,\n                                             Real kappa, Real theta, Real sigma, Real v0, Real rho,\n                                             const TypePayoff& type,\n                                             const Integration& integration,\n                                             const ComplexLogFormula cpxLog,\n                                             const AnalyticHestonADEngine* const enginePtr,\n                                             VanillaOption::results& results,\n                                             Size& evaluations)\n    {\n        std::vector<CppAD::AD<Real> > params;\n        params += spotPrice, v0, kappa, theta, sigma, rho;\n        CppAD::Independent(params);\n\n        std::vector<Real> vp;\n        vp += spotPrice, v0, kappa, theta, sigma, rho;\n        const Real ratio = riskFreeDiscount/dividendDiscount;\n\n        evaluations = 0;\n\n        const CppAD::AD<Real> p1 = integration.calculate(\n            Fj_Helper(params[2], params[3], params[4],\n            \t\t  params[1], params[0], params[5], enginePtr,\n                      cpxLog, term, strikePrice, ratio, 1))/M_PI;\n        evaluations+= integration.numberOfEvaluations();\n\n        const CppAD::AD<Real> p2 = integration.calculate(\n            Fj_Helper(params[2], params[3], params[4],\n            \t\t  params[1], params[0], params[5], enginePtr,\n                      cpxLog, term, strikePrice, ratio, 2))/M_PI;\n        evaluations+= integration.numberOfEvaluations();\n\n        std::vector<CppAD::AD<Real> > y(1);\n\n        switch (type.optionType())\n        {\n          case Option::Call:\n            y[0] = params[0]*dividendDiscount*(p1+0.5)\n            \t- strikePrice*riskFreeDiscount*(p2+0.5);\n            break;\n          case Option::Put:\n        \t  y[0] = params[0]*dividendDiscount*(p1-0.5)\n                - strikePrice*riskFreeDiscount*(p2-0.5);\n            break;\n          default:\n            QL_FAIL(\"unknown option type\");\n        }\n\n        std::vector<Real> moreResults\n        \t= CppAD::ADFun<Real>(params, y).Reverse(1, std::vector<Real>(1, 1.0));\n\n        results.value = CppAD::Value(y[0]);\n\n        results.delta = moreResults[0];\n        results.additionalResults[\"delta\"] = moreResults[0];\n        results.additionalResults[\"v0\"]    = moreResults[1];\n        results.additionalResults[\"kappa\"] = moreResults[2];\n        results.additionalResults[\"theta\"] = moreResults[3];\n        results.additionalResults[\"sigma\"] = moreResults[4];\n        results.additionalResults[\"rho\"]   = moreResults[5];\n    }\n\n    void AnalyticHestonADEngine::calculate() const\n    {\n        // this is a european option pricer\n        QL_REQUIRE(arguments_.exercise->type() == Exercise::European,\n                   \"not an European option\");\n\n        // plain vanilla\n        boost::shared_ptr<PlainVanillaPayoff> payoff =\n            boost::dynamic_pointer_cast<PlainVanillaPayoff>(arguments_.payoff);\n        QL_REQUIRE(payoff, \"non plain vanilla payoff given\");\n\n        const boost::shared_ptr<HestonProcess>& process = model_->process();\n\n        const Real riskFreeDiscount = process->riskFreeRate()->discount(\n                                            arguments_.exercise->lastDate());\n        const Real dividendDiscount = process->dividendYield()->discount(\n                                            arguments_.exercise->lastDate());\n\n        const Real spotPrice = process->s0()->value();\n        QL_REQUIRE(spotPrice > 0.0, \"negative or null underlying given\");\n\n        const Real strikePrice = payoff->strike();\n        const Real term = process->time(arguments_.exercise->lastDate());\n\n        doCalculation(riskFreeDiscount,\n                      dividendDiscount,\n                      spotPrice,\n                      strikePrice,\n                      term,\n                      model_->kappa(),\n                      model_->theta(),\n                      model_->sigma(),\n                      model_->v0(),\n                      model_->rho(),\n                      *payoff,\n                      *integration_,\n                      cpxLog_,\n                      this,\n                      results_,\n                      evaluations_);\n    }\n\n\n\n    AnalyticHestonADEngine::Integration::Integration(\n            Algorithm intAlgo,\n            const boost::shared_ptr<GaussianADQuadrature>& gaussianQuadrature)\n    : intAlgo_(intAlgo),\n      gaussianQuadrature_(gaussianQuadrature) { }\n\n\n    AnalyticHestonADEngine::Integration\n    AnalyticHestonADEngine::Integration::gaussLaguerre(Size intOrder) {\n        QL_REQUIRE(intOrder <= 192, \"maximum integraton order (192) exceeded\");\n        return Integration(GaussLaguerre,\n                           boost::shared_ptr<GaussianADQuadrature>(\n                               new GaussLaguerreADIntegration(intOrder)));\n    }\n\n    AnalyticHestonADEngine::Integration\n    AnalyticHestonADEngine::Integration::gaussLegendre(Size intOrder) {\n        return Integration(GaussLegendre,\n                           boost::shared_ptr<GaussianADQuadrature>(\n                               new GaussLegendreADIntegration(intOrder)));\n    }\n\n    AnalyticHestonADEngine::Integration\n    AnalyticHestonADEngine::Integration::gaussChebyshev(Size intOrder) {\n        return Integration(GaussChebyshev,\n                           boost::shared_ptr<GaussianADQuadrature>(\n                               new GaussChebyshevADIntegration(intOrder)));\n    }\n\n    AnalyticHestonADEngine::Integration\n    AnalyticHestonADEngine::Integration::gaussChebyshev2nd(Size intOrder) {\n        return Integration(GaussChebyshev2nd,\n                           boost::shared_ptr<GaussianADQuadrature>(\n                               new GaussChebyshev2ndADIntegration(intOrder)));\n    }\n\n    Size AnalyticHestonADEngine::Integration::numberOfEvaluations() const {\n    \treturn gaussianQuadrature_->order();\n    }\n\n    CppAD::AD<Real> AnalyticHestonADEngine::Integration::calculate(\n\t    const boost::function<CppAD::AD<Real>(Real)>& f) const {\n\n    \tCppAD::AD<Real> retVal;\n\n        switch(intAlgo_) {\n          case GaussLaguerre:\n            retVal = gaussianQuadrature_->operator()(f);\n            break;\n          default:\n              QL_FAIL(\"unknwon integration algorithm\");\n        }\n\n        return retVal;\n     }\n}\n", "meta": {"hexsha": "d095e70b51431e6877b1e7d4be0dc1551e65ead8", "size": 12423, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ShineNgine/Volatility/analytichestonadengine.cpp", "max_stars_repo_name": "FinancialEngineerLab/fineQuantlib", "max_stars_repo_head_hexsha": "a07eb659a440964ded9e9f636de0fd379672f4c3", "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": "ShineNgine/Volatility/analytichestonadengine.cpp", "max_issues_repo_name": "FinancialEngineerLab/fineQuantlib", "max_issues_repo_head_hexsha": "a07eb659a440964ded9e9f636de0fd379672f4c3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShineNgine/Volatility/analytichestonadengine.cpp", "max_forks_repo_name": "FinancialEngineerLab/fineQuantlib", "max_forks_repo_head_hexsha": "a07eb659a440964ded9e9f636de0fd379672f4c3", "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.093220339, "max_line_length": 99, "alphanum_fraction": 0.552523545, "num_tokens": 3001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954684, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.528059544948555}}
{"text": "#include \"unscented.h\"\n\n#include <iostream>\n#include <cmath>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <unsupported/Eigen/MatrixFunctions>\n\nusing namespace uvdar;\n\ndouble angdiff(double x,double y){\n  double d = y-x;\n  if ((d>-M_PI)&&(d<M_PI)) return d;\n  return fmod(d+M_PI,2*M_PI)-M_PI;\n}\n\nunscented::measurement unscented::unscentedTransform(e::VectorXd x,e::MatrixXd Px, const boost::function<e::VectorXd(e::VectorXd,e::VectorXd,int)> &fcn,double fleft,double fright, double fcenter, int camera_index){\n  int L = x.rows();\n  double W0=1.0/3.0;\n  Eigen::MatrixXd X(L,2*L+1);\n  X.leftCols(1) = x;\n  X.rightCols(2*L).Ones(L,2*L);\n\n  Eigen::VectorXd W(2*L+1);\n  W =e::VectorXd::Ones(2*L+1)*((1-W0)/(2*L));\n  W(0)=W0;\n\n  e::MatrixXd sf = ((L/(1-W0))*Px).sqrt();\n\n  for (int i=0; i<L; i++){\n    X.col(i*2+1) = (x+(sf.row(i)).transpose());\n    X.col(i*2+2) = (x-(sf.row(i)).transpose());// check\n  }\n  e::MatrixXd Y(6,2*L+1);\n  \n  e::VectorXd expFrequencies;\n  if (fcenter>0){\n    expFrequencies = e::VectorXd(3);\n    expFrequencies << fleft,fright,fcenter;\n  }\n  else {\n    expFrequencies = e::VectorXd(2);\n    expFrequencies << fleft,fright;\n  }\n  \n  for (int i=0; i<(1+2*L); i++){\n    Y.col(i)=fcn(X.col(i),expFrequencies, camera_index); //this is weird, check please\n  }\n  int nan_index = -1;\n  int nan_count = 0;\n  for (int i=0; i<(1+2*L); i++){\n    if (Y.col(i).array().isNaN().any()){\n      nan_count++;\n      nan_index = i;\n    }\n  }\n\n  if (nan_count == 1){\n    Y.col(nan_index) = Y.col(0);\n  }\n  if (false){\n  /* if (true){ */\n    std::cout << \"unscented W: \"<< std::endl;\n    std::cout << W.transpose() << std::endl;\n    std::cout << \"unscented X: \"<< std::endl;\n    std::cout << X << std::endl;\n    std::cout << \"unscented Y: \"<< std::endl;\n    std::cout << Y << std::endl;\n  }\n  e::Vector3d mr;\n    mr << 0,0,0;\n  e::VectorXd y = Y*W;\n\n  e::MatrixXd Ye = (Y-y.replicate(1,2*L+1));\n  e::MatrixXd Py = ((Ye*W.asDiagonal())*Ye.transpose());\n\n  for (int i=0; i<3; i++){\n      if (y(3+i)>M_PI){\n        y(3+i)=-2*M_PI+y(3+i);\n    }\n  }\n  struct measurement output;\n  output.x = y;\n  output.C = Py;\n  return output;\n}\n\nstd::vector<Eigen::VectorXd> unscented::getSigmaPtsSource(e::VectorXd x,e::MatrixXd Px){\n  int L = x.rows();\n  double W0=1.0/3.0;\n  std::vector<e::VectorXd> output;\n  output.push_back(x);\n  Eigen::VectorXd W(2*L+1);\n  W =e::VectorXd::Ones(2*L+1)*((1-W0)/(2*L));\n  W(0)=W0;\n  e::MatrixXd sf = ((L/(1-W0))*Px).sqrt();\n  for (int i=0; i<L; i++){\n    output.push_back((x+(sf.row(i)).transpose()));\n    output.push_back((x-(sf.row(i)).transpose()));\n  }\n  return output;\n}\n\n/* } */\n", "meta": {"hexsha": "c5cf698e5298c7beab4ba359712dbab75059e24a", "size": 2615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/unscented/unscented.cpp", "max_stars_repo_name": "ctu-mrs/uvdar_core", "max_stars_repo_head_hexsha": "85f01498b433660fcff7410e40d35b79d3ca225a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-15T14:48:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T22:56:02.000Z", "max_issues_repo_path": "include/unscented/unscented.cpp", "max_issues_repo_name": "ctu-mrs/uvdar_core", "max_issues_repo_head_hexsha": "85f01498b433660fcff7410e40d35b79d3ca225a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-29T03:18:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T15:28:43.000Z", "max_forks_repo_path": "include/unscented/unscented.cpp", "max_forks_repo_name": "ctu-mrs/uvdar_core", "max_forks_repo_head_hexsha": "85f01498b433660fcff7410e40d35b79d3ca225a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-11-02T16:58:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T23:00:09.000Z", "avg_line_length": 24.9047619048, "max_line_length": 214, "alphanum_fraction": 0.5774378585, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5280595368723788}}
{"text": "#include \"utility.h\"\n#include <random>\n#include <ctime>\n#include <fstream>\n#include <iomanip>\n#include <Eigen/Core>\n#include \"slicesampler.h\"\n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\n\nnamespace\n{\nstd::random_device seed;\nstd::default_random_engine gen(seed());\nstd::uniform_real_distribution<double> uniform_dist(0.0, 1.0);\nstd::normal_distribution<> normal_dist(0.0, 1.0);\n}\n\nnamespace Utility\n{\n\nEigen::VectorXd generateRandomVector(unsigned n)\n{\n    Eigen::VectorXd x(n);\n    for (unsigned i = 0; i < n; ++ i)\n    {\n        x(i) = uniform_dist(gen);\n    }\n    return x;\n}\n\ndouble generateUniformReal()\n{\n    return uniform_dist(gen);\n}\n\ndouble generateStandardNormal()\n{\n    return normal_dist(gen);\n}\n\ndouble temp(const Eigen::VectorXd& x, const void* data)\n{\n    const MatrixXd& Sigma_inv = static_cast<const std::pair<MatrixXd, double>*>(data)->first;\n    const double    Sigma_det = static_cast<const std::pair<MatrixXd, double>*>(data)->second;\n    return Utility::gauss(x, VectorXd::Zero(x.rows()), Sigma_inv, Sigma_det);\n}\n\nVectorXd generateNormal(const Eigen::VectorXd &mu, const Eigen::MatrixXd &Sigma)\n{\n    VectorXd x = VectorXd::Zero(mu.rows());\n    std::pair<MatrixXd, double> data(Sigma.inverse(), Sigma.determinant());\n    x = SliceSampler::sampling(temp, &data, x, VectorXd::Constant(x.rows(), Sigma.maxCoeff() * 3.0));\n    x = SliceSampler::sampling(temp, &data, x, VectorXd::Constant(x.rows(), Sigma.maxCoeff() * 3.0));\n    x = SliceSampler::sampling(temp, &data, x, VectorXd::Constant(x.rows(), Sigma.maxCoeff() * 3.0));\n    x = SliceSampler::sampling(temp, &data, x, VectorXd::Constant(x.rows(), Sigma.maxCoeff() * 3.0));\n    x = SliceSampler::sampling(temp, &data, x, VectorXd::Constant(x.rows(), Sigma.maxCoeff() * 3.0));\n    return x + mu;\n}\n\nvoid exportMatrixToCsv(const std::string& filePath, const Eigen::MatrixXd& X)\n{\n    std::ofstream ofs(filePath);\n    for (unsigned i = 0; i < X.rows(); ++ i)\n    {\n        for (unsigned j = 0; j < X.cols(); ++ j)\n        {\n            ofs << X(i, j);\n            if (j + 1 != X.cols()) ofs << \",\";\n        }\n        ofs << std::endl;\n    }\n}\n\nstd::string getCurrentTimeInString()\n{\n    const std::time_t t = std::time(nullptr);\n    std::stringstream s; s << std::put_time(std::localtime(&t), \"%Y%m%d%H%M%S\");\n    return s.str();\n}\n\n}\n", "meta": {"hexsha": "0db430e9ad4cacc343bac36cddd5751f7b753d97", "size": 2309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main/utility.cpp", "max_stars_repo_name": "takuma-ya/sequential_bayesian_optimization", "max_stars_repo_head_hexsha": "cf0cc61adb4a66cbf3eb8e5f22e441d5af539f8f", "max_stars_repo_licenses": ["MIT"], "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/utility.cpp", "max_issues_repo_name": "takuma-ya/sequential_bayesian_optimization", "max_issues_repo_head_hexsha": "cf0cc61adb4a66cbf3eb8e5f22e441d5af539f8f", "max_issues_repo_licenses": ["MIT"], "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/utility.cpp", "max_forks_repo_name": "takuma-ya/sequential_bayesian_optimization", "max_forks_repo_head_hexsha": "cf0cc61adb4a66cbf3eb8e5f22e441d5af539f8f", "max_forks_repo_licenses": ["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.4880952381, "max_line_length": 101, "alphanum_fraction": 0.6401039411, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5279878474123929}}
{"text": "/*\r\nimgalt - Image Alignment Tool\r\nAuthor: GreatAttractor\r\n\r\nversion 0.5\r\n2014/05/22\r\n\r\nThis code can be freely distributed and used for any purpose.\r\n\r\nFile description:\r\n    Utility functions implementation.\r\n\r\n*/\r\n#include <string.h>\r\n#include <stdlib.h>\r\n#include <math.h>\r\n#include <stdexcept>\r\n#include <fstream>\r\n#include <cctype>\r\n#include <algorithm>\r\n#include <boost/format.hpp>\r\n#include \"comp.h\"\r\nusing namespace boost;\r\n\r\n\r\nint GetBytesPerPixel(PixelFormat_t pixFmt)\r\n{\r\n    switch (pixFmt)\r\n    {\r\n    case PIX_PAL8:\r\n    case PIX_MONO8:\r\n        return 1;\r\n    case PIX_MONO16: return 2;\r\n    case PIX_RGB24: return 3;\r\n    case PIX_RGB48: return 3*2;\r\n    case PIX_MONO32F: return sizeof(float);\r\n    default: return -1;\r\n    }\r\n}\r\n\r\n\r\n/// Returns the smallest power of 2 which is > n\r\nunsigned GetClosestGPowerOf2(unsigned n)\r\n{\r\n    int msb = 0;\r\n    while (n != 0)\r\n    {\r\n        n >>= 1;\r\n        msb++;\r\n    }\r\n\r\n    return ((unsigned)1 << msb);\r\n}\r\n\r\n/// Returns the greatest power of 2 which is <= n\r\nunsigned GetClosestLEPowerOf2(unsigned n)\r\n{\r\n    int msb = 0;\r\n    while (n != 0)\r\n    {\r\n        n >>= 1;\r\n        msb++;\r\n    }\r\n\r\n    return ((unsigned)1 << (msb-1));\r\n}\r\n\r\n\r\n\r\n\r\n/// Returns 0 for x=0, 1 for x=1\r\ninline float CosineWindow(float x)\r\n{\r\n    return 0.5f*(1.0f - cosf(3.1415926535f*x));\r\n}\r\n\r\n/// Returns 0 for x=0, 1 for x=1\r\ninline float BlackmanWindow(float x)\r\n{\r\n    const float A0 = 7938.0f/18608,\r\n                A1 = 9240.0f/18608,\r\n                A2 = 1430.0f/18608;\r\n\r\n    return A0 - A1*cosf(3.1415926535f*x) + A2*cosf(2*3.1415926535f*x);\r\n}\r\n\r\n#define SQR(x) ((x)*(x))\r\n\r\n/// Calculates window function and writes its values into 'buf' (a square array)\r\nvoid CalcWindowFunction(\r\n        int wndSize, ///< Window size\r\n        float buf[] ///< Destination buffer, wndSize*wndSize elements\r\n)\r\n{\r\n    // The window function is rotationally symmetrical, so calculate it only in a quarter of 'buf'\r\n    #pragma omp parallel for\r\n    for (int y = 0; y < wndSize/2; y++)\r\n        for (int x = 0; x < wndSize/2; x++)\r\n        {\r\n            float value = 0.0f;\r\n            float dist = sqrtf(SQR(wndSize/2 - x) + SQR(wndSize/2 - y));\r\n            if (dist < wndSize/2)\r\n                value = BlackmanWindow(1.0f-dist/(wndSize/2));\r\n\r\n            // upper left\r\n            buf[x + y*wndSize] = value;\r\n            // upper right\r\n            buf[wndSize-1-x + y*wndSize] = value;\r\n            // lower right\r\n            buf[wndSize-1-x + (wndSize-1-y)*wndSize] = value;\r\n            // lower left\r\n            buf[x + (wndSize-1-y)*wndSize] = value;\r\n        }\r\n}\r\n\r\n/// Multiplies input image by window function; input and output images may be the same\r\nvoid ApplyWindowFunction(float img[], ///< Input image, size*size elements; may be the same pointer as 'dest'\r\n        float windowFunc[], ///< Window function values, size*size elements\r\n        float dest[], ///< Output buffer, size*size elements; may be the same pointer as 'img'\r\n        int size ///< Number of rows and columns in each array\r\n)\r\n{\r\n    #pragma omp parallel for\r\n    for (int y = 0; y < size; y++)\r\n        for (int x = 0; x < size; x++)\r\n            dest[x + y*size] = img[x + y*size] * windowFunc[x + y*size];\r\n}\r\n\r\n/// Resizes and translates image (or its fragment) by cropping and/or padding (with zeros) to the destination size and offset (there is no scaling)\r\nvoid ResizeAndTranslate(\r\n        void *input,          ///< Input buffer\r\n        PixelFormat_t pixFmt, ///< Format of data in 'input' and 'output'\r\n        int srcWidth,         ///< Width of input image\r\n        int srcHeight,        ///< Height of input image\r\n        int srcXmin,          ///< X min of input data in input image\r\n        int srcYmin,          ///< Y min of input data in input image\r\n        int srcXmax,          ///< X max of input data in input image\r\n        int srcYmax,          ///< Y max of input data in input image\r\n        void *output,         ///< Output buffer\r\n        int destWidth,        ///< Width of output image\r\n        int destHeight,       ///< Height of output image\r\n        int xOfs,             ///< X offset of input data in output buffer\r\n        int yOfs              ///< Y offset of input data in output buffer\r\n)\r\n{\r\n    int bytesPP = GetBytesPerPixel(pixFmt);\r\n    memset(output, 0, destWidth*destHeight*bytesPP); // Works also if 'dest' points to an array of floats; 32 zero bits represent a floating-point 0.0f\r\n\r\n    // start and end (inclusive) coordinates to fill in the output buffer\r\n    unsigned Xstart = (xOfs < 0) ? 0 : xOfs;\r\n    unsigned Ystart = (yOfs < 0) ? 0 : yOfs;\r\n\r\n    unsigned Xend = std::max(0, std::min((int)xOfs + srcXmax, destWidth-1));\r\n    unsigned Yend = std::max(0, std::min((int)yOfs + srcYmax, destHeight-1));\r\n\r\n    for (int y = Ystart; y <= Yend; y++)\r\n    {\r\n        memcpy((uint8_t *)output + (Xstart + y*destWidth)*bytesPP,\r\n               (uint8_t *)input + (Xstart-xOfs+srcXmin + (y-yOfs + srcYmin)*srcWidth)*bytesPP,\r\n               (Xend - Xstart + 1)*bytesPP);\r\n    }\r\n}\r\n\r\n/// Blurs 'src' image using a 5x5 Gaussian kernel and writes the result to 'dest'; 2 pixel-wide borders are not blurred\r\nvoid BlurImage(\r\n    uint8_t *src, ///< Source image (8-bit luminance)\r\n    int width,    ///< Image width\r\n    int height,   ///< Image height\r\n    uint8_t *dest ///< Destination image (same dimensions as 'src')\r\n)\r\n{\r\n    const int KERNEL_SIZE = 5;\r\n    const int kernel[KERNEL_SIZE][KERNEL_SIZE] =\r\n    {\r\n        { 2, 4,  5,  4,  2 },\r\n        { 4, 9,  12, 9,  4 },\r\n        { 5, 12, 15, 12, 5 },\r\n        { 4, 9,  12, 9,  4 },\r\n        { 2, 4,  5,  4,  2 }\r\n    };\r\n\r\n    for (int y = KERNEL_SIZE/2; y <= height - KERNEL_SIZE/2 - 1; y++)\r\n        for (int x = KERNEL_SIZE/2; x <= width - KERNEL_SIZE/2 - 1; x++)\r\n        {\r\n            int sum = 0;\r\n            for (int yofs = -KERNEL_SIZE/2; yofs <= KERNEL_SIZE/2; yofs++)\r\n                for (int xofs = -KERNEL_SIZE/2; xofs <= KERNEL_SIZE/2; xofs++)\r\n                    sum += (int)src[(x + xofs) + (y + yofs) * width] * kernel[xofs + KERNEL_SIZE/2][yofs + KERNEL_SIZE/2];\r\n\r\n            dest[x + y*width] = sum/159;\r\n        }\r\n}\r\n\r\n/// Calculates squared gradient lengths in the source image; 3 pixel-wide borders are skipped\r\nvoid CalcGradients(\r\n    uint8_t *src,  ///< Source image\r\n    int width,     ///< Image width\r\n    int height,    ///< Image height\r\n    uint32_t *dest ///< Destination buffer (same dimensions as 'src')\r\n)\r\n{\r\n    const int KERNEL_SIZE = 3;\r\n    const int kernelX[KERNEL_SIZE][KERNEL_SIZE] =\r\n    {\r\n        { -1, 0, 1 },\r\n        { -2, 0, 2 },\r\n        { -1, 0, 1 }\r\n    };\r\n\r\n    const int kernelY[KERNEL_SIZE][KERNEL_SIZE] =\r\n    {\r\n        { 1,   2,  1 },\r\n        { 0,   0,  0 },\r\n        { -1, -2, -1 }\r\n    };\r\n\r\n    /// By skipping 3-pixel borders we skip the pixels that are also skipped by BlurImage()\r\n    for (int y = 3; y <= height - 4; y++)\r\n        for (int x = 3; x <= width - 4; x++)\r\n        {\r\n            int gradX = 0, gradY = 0;\r\n            for (int yofs = -KERNEL_SIZE/2; yofs <= KERNEL_SIZE/2; yofs++)\r\n                for (int xofs = -KERNEL_SIZE/2; xofs <= KERNEL_SIZE/2; xofs++)\r\n                {\r\n                    uint8_t srcVal = src[(x + xofs) + (y + yofs) * width];\r\n                    gradX += srcVal * kernelX[xofs + KERNEL_SIZE/2][yofs + KERNEL_SIZE/2];\r\n                    gradY += srcVal * kernelY[xofs + KERNEL_SIZE/2][yofs + KERNEL_SIZE/2];\r\n                }\r\n\r\n            dest[x + y*width] = gradX*gradX + gradY*gradY; // this is at most 2*(4*255)^2, so fits easily in uint32_t\r\n        }\r\n}\r\n\r\nnamespace BMP\r\n{\r\n\r\n#pragma pack(push)\r\n\r\n#pragma pack(1)\r\ntypedef struct\r\n{\r\n    uint16_t bfType;\r\n    uint32_t bfSize;\r\n    uint16_t bfReserved1;\r\n    uint16_t bfReserved2;\r\n    uint32_t bfOffBits;\r\n} BITMAPFILEHEADER_t; ///< BMP file header\r\n\r\n#pragma pack(1)\r\ntypedef struct\r\n{\r\n   uint32_t biSize;\r\n   int32_t biWidth;\r\n   int32_t biHeight;\r\n   uint16_t biPlanes;\r\n   uint16_t biBitCount;\r\n   uint32_t biCompression;\r\n   uint32_t biSizeImage;\r\n   int32_t biXPelsPerMeter;\r\n   int32_t biYPelsPerMeter;\r\n   uint32_t biClrUsed;\r\n   uint32_t biClrImportant;\r\n} BITMAPINFOHEADER_t; ///< BMP info header\r\n\r\n#pragma pack(pop)\r\n\r\nconst uint32_t BMP_NO_COMPRESSION = 0;\r\nconst int BMP_PALETTE_SIZE = 256*4;\r\n\r\n// returns the least multiple of 4 which is >= x\r\n#define UP4MULT(x) (((x)+3)/4*4)\r\n\r\n/// Reads a BMP image and returns pointer to the newly allocated buffer with pixel contents or 0 on error\r\nvoid *ReadBmp(const char *fileName,\r\n        int &imgWidth,  ///< Receives image width\r\n        int &imgHeight, ///< Receives image height\r\n        PixelFormat_t &pixFmt, ///< Receives the pixel format\r\n        uint8_t palette[]    ///< If not NULL and reading from an 8-bit file, receives the palette (1024 bytes)\r\n)\r\n{\r\n    std::ifstream file(fileName, std::ios_base::in | std::ios_base::binary);\r\n    if (file.fail())\r\n        return 0;\r\n\r\n    BITMAPFILEHEADER_t bmpFileHdr;\r\n    BITMAPINFOHEADER_t bmpInfoHdr;\r\n\r\n    file.read((char *)&bmpFileHdr, sizeof(bmpFileHdr));\r\n    file.read((char *)&bmpInfoHdr, sizeof(bmpInfoHdr));\r\n    if (file.eof())\r\n        return 0;\r\n\r\n    imgWidth = bmpInfoHdr.biWidth;\r\n    imgHeight = bmpInfoHdr.biHeight;\r\n    if (imgWidth == 0 || imgHeight == 0 ||\r\n        bmpFileHdr.bfType != 'B'+((int)'M'<<8) ||\r\n        bmpInfoHdr.biPlanes != 1 ||\r\n        bmpInfoHdr.biBitCount != 8 && bmpInfoHdr.biBitCount != 24 ||\r\n        bmpInfoHdr.biCompression != BMP_NO_COMPRESSION)\r\n    {\r\n        return 0;\r\n    }\r\n\r\n    if (bmpInfoHdr.biBitCount == 8)\r\n        pixFmt = PIX_PAL8;\r\n    else if (bmpInfoHdr.biBitCount == 24)\r\n        pixFmt = PIX_RGB24;\r\n\r\n    int bytesPP = GetBytesPerPixel(pixFmt);\r\n\r\n    void *pixels = malloc(imgWidth * imgHeight * bytesPP);\r\n\r\n    if (bmpInfoHdr.biBitCount == 8)\r\n    {\r\n        unsigned bmpStride = UP4MULT(imgWidth); // line length in bytes in the BMP file's pixel data\r\n        unsigned skip = bmpStride - imgWidth; // number of padding bytes at the end of a line\r\n\r\n        int actualPalSize = bmpInfoHdr.biClrUsed == 0 ? BMP_PALETTE_SIZE : bmpInfoHdr.biClrUsed*4;\r\n\r\n        // seek to the beginning of palette\r\n        file.seekg(sizeof(bmpFileHdr) + bmpInfoHdr.biSize, std::ios_base::beg);\r\n\r\n        if (palette != 0)\r\n            file.read((char *)palette, actualPalSize);\r\n\r\n        // Seek to the beginning of pixel values\r\n        file.seekg(bmpFileHdr.bfOffBits, std::ios_base::beg);\r\n\r\n        for (int y = imgHeight - 1; y >= 0; y--) // lines in BMP are stored bottom to top\r\n        {\r\n            file.read((char *)((uint8_t *)pixels + y*imgWidth), imgWidth);\r\n            if (skip > 0)\r\n                file.seekg(skip, std::ios_base::cur);\r\n        }\r\n    }\r\n    else if (bmpInfoHdr.biBitCount == 24)\r\n    {\r\n        unsigned bmpStride = UP4MULT(imgWidth*3); // line length in bytes in the BMP file's pixel data\r\n        unsigned skip = bmpStride - imgWidth*3; // number of padding bytes at the end of a row\r\n\r\n        // Seek to the beginning of pixel values\r\n        file.seekg(bmpFileHdr.bfOffBits, std::ios_base::beg);\r\n\r\n        // read the lines directly into the buffer\r\n        for (int y = imgHeight - 1; y >= 0; y--) // lines in BMP are stored bottom to top\r\n        {\r\n            file.read((char *)((uint8_t *)pixels + y*imgWidth*3), imgWidth*3);\r\n            if (skip > 0)\r\n                file.seekg(skip, std::ios_base::cur);\r\n        }\r\n    }\r\n\r\n    return pixels;\r\n}\r\n\r\n/// Saves image in BMP format; returns 'false' on error\r\nbool SaveBmp(const char *fileName, ///< Output file name\r\n        int imgWidth,              ///< Image width\r\n        int imgHeight,             ///< Image height\r\n        PixelFormat_t pixFmt,      ///< Pixel format; has to be PIX_PAL8 or PIX_RGB24\r\n        void *pixels,              ///< Pixel contents in 'pixFmt' format\r\n        uint8_t palette[]          ///< Points to the palette (1024 bytes) to be saved if pixFmt is PIX_PAL8\r\n)\r\n{\r\n    BITMAPFILEHEADER_t bmfh;\r\n    BITMAPINFOHEADER_t bmih;\r\n    int i;\r\n\r\n    int bytesPP = GetBytesPerPixel(pixFmt);\r\n    unsigned bmpLineWidth = UP4MULT(imgWidth * bytesPP);\r\n\r\n    bmfh.bfType = 'B'+((int)'M'<<8);\r\n    bmfh.bfSize = sizeof(bmfh) + sizeof(bmih) + imgHeight*bmpLineWidth;\r\n    if (pixFmt == PIX_PAL8)\r\n        bmfh.bfSize += BMP_PALETTE_SIZE;\r\n    bmfh.bfReserved1 = 0;\r\n    bmfh.bfReserved2 = 0;\r\n    bmfh.bfOffBits = sizeof(bmih) + sizeof(bmfh);\r\n    if (pixFmt == PIX_PAL8)\r\n        bmfh.bfOffBits += BMP_PALETTE_SIZE;\r\n\r\n    bmih.biSize = sizeof(bmih);\r\n    bmih.biWidth = imgWidth;\r\n    bmih.biHeight = imgHeight;\r\n    bmih.biPlanes = 1;\r\n    bmih.biBitCount = bytesPP * 8;\r\n    bmih.biCompression = BMP_NO_COMPRESSION;\r\n    bmih.biSizeImage = 0;\r\n    bmih.biXPelsPerMeter = 1000;\r\n    bmih.biYPelsPerMeter = 1000;\r\n    bmih.biClrUsed = 0;\r\n    bmih.biClrImportant = 0;\r\n\r\n    std::ofstream file(fileName, std::ios_base::out | std::ios_base::trunc | std::ios_base::binary);\r\n    if (file.fail())\r\n        return false;\r\n\r\n    file.write((const char *)&bmfh, sizeof(bmfh));\r\n    file.write((const char *)&bmih, sizeof(bmih));\r\n    if (pixFmt == PIX_PAL8)\r\n        file.write((const char *)palette, BMP_PALETTE_SIZE);\r\n\r\n    int skip = bmpLineWidth - imgWidth*bytesPP;\r\n\r\n    for (i = imgHeight - 1; i >= 0; i--) // lines in BMP are stored bottom to top\r\n    {\r\n        file.write((const char*)pixels + i * imgWidth * bytesPP, imgWidth*bytesPP);\r\n        if (skip > 0)\r\n            file.write((const char *)pixels, skip); //this is just padding, so write anything\r\n    }\r\n\r\n    file.close();\r\n\r\n    return true;\r\n}\r\n\r\nbool GetBmpDimensions(const char *fileName, unsigned &imgWidth, unsigned &imgHeight)\r\n{\r\n    std::ifstream file(fileName, std::ios_base::in | std::ios_base::binary);\r\n    if (file.fail())\r\n        return false;\r\n\r\n    BITMAPFILEHEADER_t bmpFileHdr;\r\n    BITMAPINFOHEADER_t bmpInfoHdr;\r\n\r\n    file.read((char *)&bmpFileHdr, sizeof(bmpFileHdr));\r\n    file.read((char *)&bmpInfoHdr, sizeof(bmpInfoHdr));\r\n    if (file.eof())\r\n        return false;\r\n\r\n    imgWidth = bmpInfoHdr.biWidth;\r\n    imgHeight = bmpInfoHdr.biHeight;\r\n\r\n    return true;\r\n}\r\n\r\n} // namespace BMP\r\n\r\nnamespace TIFF\r\n{\r\n\r\n#pragma pack(push, 1)\r\ntypedef struct\r\n{\r\n    uint16_t tag;\r\n    uint16_t type;\r\n    uint32_t count;\r\n    uint32_t value;\r\n} TiffField_t;\r\n\r\ntypedef struct\r\n{\r\n    uint16_t id;\r\n    uint16_t version;\r\n    uint32_t dirOffset; // = offset of 'numDirEntries'\r\n} TiffHeader_t;\r\n\r\n#pragma pack(pop)\r\n\r\ntypedef enum { ttByte = 1, ttAscii, ttWord, ttDWord, ttRational } TagType_t;\r\n\r\nconst int TIFF_VERSION = 42;\r\nconst int TAG_IMAGE_WIDTH =                0x100;\r\nconst int TAG_IMAGE_HEIGHT =               0x101;\r\nconst int TAG_BITS_PER_SAMPLE =            0x102;\r\nconst int TAG_COMPRESSION =                0x103;\r\nconst int TAG_PHOTOMETRIC_INTERPRETATION = 0x106;\r\nconst int TAG_STRIP_OFFSETS =              0x111;\r\nconst int TAG_SAMPLES_PER_PIXEL =          0x115;\r\nconst int TAG_ROWS_PER_STRIP =             0x116;\r\nconst int TAG_STRIP_BYTE_COUNTS =          0x117;\r\nconst int TAG_PLANAR_CONFIGURATION =       0x11C;\r\n\r\nconst uint16_t NO_COMPRESSION = 1;\r\nconst uint16_t PLANAR_CONFIGURATION_CHUNKY = 1;\r\nconst uint16_t INTEL_BYTE_ORDER = ((uint16_t)'I' << 8) + 'I'; // little-endian\r\nconst uint16_t MOTOROLA_BYTE_ORDER = ((uint16_t)'M' << 8) + 'M'; // big-endian\r\nconst int PHMET_WHITE_IS_ZERO = 0;\r\nconst int PHMET_BLACK_IS_ZERO = 1;\r\nconst int PHMET_RGB = 2;\r\n\r\ninline unsigned GetFieldTypeLength(TagType_t ttt)\r\n{\r\n    switch (ttt)\r\n    {\r\n    case ttByte: return 1; break;\r\n    case ttAscii: return 1; break;\r\n    case ttWord: return 2; break;\r\n    case ttDWord: return 4; break;\r\n    case ttRational: return 8; break;\r\n    }\r\n}\r\n\r\n/// Conditionally swaps a 32-bit value\r\nuint32_t inline SWAP32cnd(uint32_t x, bool swap)\r\n{\r\n    if (swap) return (x << 24) | ((x & 0x00FF0000) >> 8) | ((x & 0x0000FF00) << 8) | (x >> 24);\r\n    else return x;\r\n}\r\n\r\n/// Conditionally swaps two lower bytes of a 32-bit value\r\nuint32_t inline SWAP16in32cnd(uint32_t x, bool swap)\r\n{\r\n    if (swap) return ((x & 0xFF) << 8) | (x >> 8);\r\n    else return x;\r\n}\r\n\r\nuint16_t inline SWAP16cnd(uint16_t x, bool swap)\r\n{\r\n    if (swap) return (x << 8) | (x >> 8);\r\n    else return x;\r\n}\r\n\r\n/// Changes endianess of 16-bit words in the specified buffer\r\nvoid SwapBufferWords(uint16_t *buf, int numWords)\r\n{\r\n    for (unsigned i = 0; i < numWords; i++)\r\n        buf[i] = (buf[i] << 8) | (buf[i] >> 8);\r\n}\r\n\r\n/// Reverses values of an 8-bit grayscale buffer\r\nvoid NegateGrayscale8(uint8_t *buf, int length)\r\n{\r\n    for (int i = 0; i < length; i++)\r\n        buf[i] = 0xFF - buf[i];\r\n}\r\n\r\n/// Reverses values of a 16-bit grayscale buffer\r\nvoid NegateGrayscale16(uint16_t *buf, int length)\r\n{\r\n    for (int i = 0; i < length; i++)\r\n        buf[i] = 0xFFFF - buf[i];\r\n}\r\n\r\nbool SaveTiff(const char *fileName, ///< Output file name\r\n              void *pixels,   ///< Pointer to the buffer with pixel data (left to right, top to bottom, no padding)\r\n              PixelFormat_t pixFmt, ///< Pixel format of 'pixels'\r\n              int imgWidth,\r\n              int imgHeight\r\n)\r\n{\r\n    if (pixFmt != PIX_MONO8 && pixFmt != PIX_MONO16 && pixFmt != PIX_RGB24 && pixFmt != PIX_RGB48)\r\n        throw std::runtime_error(\"SaveTiff(): only grayscale and RGB, 8- and 16-bit formats are supported.\");\r\n\r\n    std::ofstream file(fileName, std::ios_base::trunc | std::ios_base::binary);\r\n\r\n    if (file.fail())\r\n        return false;\r\n\r\n    TiffHeader_t tiffHeader;\r\n    tiffHeader.id = INTEL_BYTE_ORDER;\r\n    tiffHeader.version = TIFF_VERSION;\r\n    tiffHeader.dirOffset = sizeof(tiffHeader);\r\n    file.write((const char *)&tiffHeader, sizeof(tiffHeader));\r\n\r\n    uint16_t numDirEntries = 10;\r\n    file.write((const char *)&numDirEntries, sizeof(numDirEntries));\r\n\r\n    uint32_t nextDirOffset = 0;\r\n\r\n    TiffField_t field;\r\n\r\n    field.tag = TAG_IMAGE_WIDTH;\r\n    field.type = ttWord;\r\n    field.count = 1;\r\n    field.value = imgWidth;\r\n    file.write((const char *)&field, sizeof(field));\r\n\r\n    field.tag = TAG_IMAGE_HEIGHT;\r\n    field.type = ttWord;\r\n    field.count = 1;\r\n    field.value = imgHeight;\r\n    file.write((const char *)&field, sizeof(field));\r\n\r\n    field.tag = TAG_BITS_PER_SAMPLE;\r\n    field.type = ttWord;\r\n    field.count = 1;\r\n    switch (pixFmt)\r\n    {\r\n    case PIX_MONO8:\r\n    case PIX_RGB24:\r\n        field.value = 8; break;\r\n    case PIX_MONO16:\r\n    case PIX_RGB48:\r\n        field.value = 16; break;\r\n    }\r\n    file.write((const char *)&field, sizeof(field));\r\n\r\n    field.tag = TAG_COMPRESSION;\r\n    field.type = ttWord;\r\n    field.count = 1;\r\n    field.value = NO_COMPRESSION;\r\n    file.write((const char *)&field, sizeof(field));\r\n\r\n    field.tag = TAG_PHOTOMETRIC_INTERPRETATION;\r\n    field.type = ttWord;\r\n    field.count = 1;\r\n    switch (pixFmt)\r\n    {\r\n    case PIX_MONO8:\r\n    case PIX_MONO16:\r\n        field.value = PHMET_BLACK_IS_ZERO; break;\r\n    case PIX_RGB24:\r\n    case PIX_RGB48:\r\n        field.value = PHMET_RGB; break;\r\n    }\r\n    file.write((const char *)&field, sizeof(field));\r\n\r\n    field.tag = TAG_STRIP_OFFSETS;\r\n    field.type = ttDWord;\r\n    field.count = 1;\r\n    // we write the header, num. of directory entries, 10 fields and a next directory offset (==0); pixel data starts next\r\n    field.value = sizeof(tiffHeader) + sizeof(numDirEntries) + 10*sizeof(field) + sizeof(nextDirOffset);\r\n    file.write((const char *)&field, sizeof(field));\r\n\r\n    field.tag = TAG_SAMPLES_PER_PIXEL;\r\n    field.type = ttWord;\r\n    field.count = 1;\r\n    switch (pixFmt)\r\n    {\r\n    case PIX_MONO8:\r\n    case PIX_MONO16:\r\n        field.value = 1; break;\r\n    case PIX_RGB24:\r\n    case PIX_RGB48:\r\n        field.value = 3; break;\r\n    }\r\n    file.write((const char *)&field, sizeof(field));\r\n\r\n    field.tag = TAG_ROWS_PER_STRIP;\r\n    field.type = ttWord;\r\n    field.count = 1;\r\n    field.value = imgHeight; // there is only one strip for the whole image\r\n    file.write((const char *)&field, sizeof(field));\r\n\r\n    field.tag = TAG_STRIP_BYTE_COUNTS;\r\n    field.type = ttDWord;\r\n    field.count = 1;\r\n    field.value = imgWidth * imgHeight * GetBytesPerPixel(pixFmt); // there is only one strip for the whole image\r\n    file.write((const char *)&field, sizeof(field));\r\n\r\n    field.tag = TAG_PLANAR_CONFIGURATION;\r\n    field.type = ttWord;\r\n    field.count = 1;\r\n    field.value = PLANAR_CONFIGURATION_CHUNKY; // there is only one strip for the whole image\r\n    file.write((const char *)&field, sizeof(field));\r\n\r\n    // write the next directory offset (0 = no other directories)\r\n    file.write((const char *)&nextDirOffset, sizeof(nextDirOffset));\r\n\r\n    file.write((const char *)pixels, imgWidth * imgHeight * GetBytesPerPixel(pixFmt));\r\n\r\n    file.close();\r\n    return true;\r\n}\r\n\r\n/// Returns newly allocated buffer with contents of the specified TIFF file (returns 0 on error)\r\nvoid *ReadTiff(const char *fileName, ///< Input file name\r\n              PixelFormat_t &pixFmt, ///< Receives the pixel format\r\n              int &imgWidth, ///< Receives image width\r\n              int &imgHeight, ///< Receives image height\r\n              std::string *errorMsg ///< If not null, receives error message (if any)\r\n)\r\n{\r\n    std::ifstream file(fileName, std::ios_base::binary);\r\n\r\n    if (file.fail())\r\n        return 0;\r\n\r\n    TiffHeader_t tiffHeader;\r\n    file.read((char *)&tiffHeader, sizeof(tiffHeader));\r\n    if (file.gcount() != sizeof(tiffHeader))\r\n    {\r\n        if (errorMsg) *errorMsg = \"File header is incomplete.\";\r\n        return 0;\r\n    }\r\n\r\n    bool isBE = tiffHeader.id == MOTOROLA_BYTE_ORDER; // true if the file has big endian data\r\n\r\n    if (SWAP16cnd(tiffHeader.version, isBE) != TIFF_VERSION)\r\n    {\r\n        if (errorMsg) *errorMsg = \"Unknown TIFF version.\";\r\n        return 0;\r\n    }\r\n\r\n    // Seek to the first TIFF directory\r\n    file.seekg(SWAP32cnd(tiffHeader.dirOffset, isBE), std::ios_base::beg);\r\n\r\n    uint16_t numDirEntries;\r\n    file.read((char *)&numDirEntries, sizeof(numDirEntries));\r\n    numDirEntries = SWAP16cnd(numDirEntries, isBE);\r\n    if (file.gcount() != sizeof(numDirEntries))\r\n    {\r\n        if (errorMsg) *errorMsg = \"The number of TIFF directory entries tag is incomplete.\";\r\n        return 0;\r\n    }\r\n\r\n    unsigned numStrips = 0;\r\n    unsigned bitsPerSample = 0;\r\n    unsigned *stripOffsets = 0;\r\n    unsigned *stripByteCounts = 0;\r\n    unsigned rowsPerStrip = 0;\r\n    int photometricInterpretation = -1;\r\n    int samplesPerPixel = 0;\r\n\r\n    std::fstream::pos_type nextFieldPos = file.tellg();\r\n    for (unsigned i = 0; i < numDirEntries; i++)\r\n    {\r\n        TiffField_t tiffField;\r\n\r\n        file.seekg(nextFieldPos, std::ios_base::beg);\r\n        file.read((char *)&tiffField, sizeof(tiffField));\r\n        if (file.gcount() != sizeof(tiffField))\r\n        {\r\n            if (errorMsg) *errorMsg = \"TIFF field is incomplete.\";\r\n            return 0;\r\n        }\r\n        nextFieldPos = file.tellg();\r\n\r\n        tiffField.tag = SWAP16cnd(tiffField.tag, isBE);\r\n        tiffField.type = SWAP16cnd(tiffField.type, isBE);\r\n        tiffField.count = SWAP32cnd(tiffField.count, isBE);\r\n        if (tiffField.count > 1 || tiffField.type == ttDWord)\r\n            tiffField.value = SWAP32cnd(tiffField.value, isBE);\r\n        else if (tiffField.count == 1 && tiffField.type == ttWord)\r\n            tiffField.value = SWAP16in32cnd(tiffField.value, isBE);\r\n\r\n        switch (tiffField.tag)\r\n        {\r\n        case TAG_IMAGE_WIDTH: imgWidth = tiffField.value; break;\r\n\r\n        case TAG_IMAGE_HEIGHT: imgHeight = tiffField.value; break;\r\n\r\n        case TAG_BITS_PER_SAMPLE:\r\n            if (tiffField.count == 1)\r\n                bitsPerSample = tiffField.value;\r\n            else\r\n            {\r\n                // Some files may have as many \"bits per sample\" values specified\r\n                // as there are channels. Make sure they are all the same.\r\n\r\n                file.seekg(tiffField.value, std::ios_base::beg);\r\n\r\n                uint16_t *fieldBuf = new uint16_t[tiffField.count];\r\n                file.read((char *)fieldBuf, tiffField.count * sizeof(uint16_t));\r\n\r\n                bool allEqual = true;\r\n                uint16_t first = fieldBuf[0];\r\n                for (unsigned j = 1; j < tiffField.count; j++)\r\n                    if (fieldBuf[j] != first)\r\n                    {\r\n                        allEqual = false;\r\n                        break;\r\n                    }\r\n\r\n                 if (!allEqual)\r\n                 {\r\n                    if (errorMsg) *errorMsg = \"Files with differing bit depts per channel are not supported.\";\r\n                    return 0;\r\n                 }\r\n\r\n                 bitsPerSample = SWAP16cnd(first, isBE);\r\n            }\r\n\r\n            if (bitsPerSample != 8 && bitsPerSample != 16)\r\n            {\r\n                if (errorMsg) *errorMsg = \"Only 8 and 16 bits per channel files are supported.\";\r\n                return 0;\r\n            }\r\n            break;\r\n\r\n        case TAG_COMPRESSION:\r\n            if (tiffField.value != NO_COMPRESSION)\r\n            {\r\n                if (errorMsg) *errorMsg = \"Compression is not supported.\";\r\n                return 0;\r\n            }\r\n            break;\r\n\r\n        case TAG_PHOTOMETRIC_INTERPRETATION: photometricInterpretation = tiffField.value; break;\r\n\r\n        case TAG_STRIP_OFFSETS:\r\n            numStrips = tiffField.count;\r\n            stripOffsets = new unsigned[numStrips];\r\n            if (numStrips == 1)\r\n                stripOffsets[0] = tiffField.value;\r\n            else\r\n            {\r\n                file.seekg(tiffField.value, std::ios_base::beg);\r\n                for (unsigned i = 0; i < numStrips; i++)\r\n                {\r\n                    file.read((char *)&stripOffsets[i], sizeof(stripOffsets[i]));\r\n                    stripOffsets[i] = SWAP32cnd(stripOffsets[i], isBE);\r\n                }\r\n            }\r\n            break;\r\n\r\n        case TAG_SAMPLES_PER_PIXEL: samplesPerPixel = tiffField.value; break;\r\n\r\n        case TAG_ROWS_PER_STRIP: rowsPerStrip = tiffField.value; break;\r\n\r\n        case TAG_STRIP_BYTE_COUNTS:\r\n            stripByteCounts = new unsigned[tiffField.count];\r\n            if (tiffField.count == 1)\r\n                stripByteCounts[0] = tiffField.value;\r\n            else\r\n            {\r\n                file.seekg(tiffField.value, std::ios_base::beg);\r\n                for (unsigned i = 0; i < tiffField.count; i++)\r\n                {\r\n                    file.read((char *)&stripByteCounts[i], sizeof(stripByteCounts[i]));\r\n                    stripByteCounts[i] = SWAP32cnd(stripByteCounts[i], isBE);\r\n                }\r\n            }\r\n            break;\r\n\r\n        case TAG_PLANAR_CONFIGURATION:\r\n            if (tiffField.value != PLANAR_CONFIGURATION_CHUNKY)\r\n            {\r\n                if (errorMsg) *errorMsg = \"Files with planar configuration other than packed (chunky) are not supported.\";\r\n                return 0;\r\n            }\r\n            break;\r\n        }\r\n    }\r\n\r\n    if (rowsPerStrip == 0 && numStrips == 1)\r\n        // If there is only 1 strip, it contains all the rows\r\n        rowsPerStrip = imgHeight;\r\n\r\n    // Validate the values\r\n\r\n    if (samplesPerPixel == 1 && photometricInterpretation != PHMET_BLACK_IS_ZERO && photometricInterpretation != PHMET_WHITE_IS_ZERO ||\r\n        samplesPerPixel == 3 && photometricInterpretation != PHMET_RGB ||\r\n        samplesPerPixel != 1 && samplesPerPixel != 3)\r\n    {\r\n        if (errorMsg) *errorMsg = \"Only RGB and grayscale images are supported.\";\r\n        return 0;\r\n    }\r\n\r\n    if (samplesPerPixel == 1)\r\n    {\r\n        if (bitsPerSample == 8)\r\n            pixFmt = PIX_MONO8;\r\n        else if (bitsPerSample == 16)\r\n            pixFmt = PIX_MONO16;\r\n    }\r\n    else if (samplesPerPixel == 3)\r\n    {\r\n        if (bitsPerSample == 8)\r\n            pixFmt = PIX_RGB24;\r\n        else if (bitsPerSample == 16)\r\n            pixFmt = PIX_RGB48;\r\n    }\r\n\r\n    // Buffer with all image pixel values, left to right, top to bottom, without any padding\r\n    void *pixels = malloc(imgWidth * imgHeight * GetBytesPerPixel(pixFmt));\r\n\r\n    int bufOfs = 0;\r\n    for (unsigned i = 0; i < numStrips; i++)\r\n    {\r\n        file.seekg(stripOffsets[i], std::ios_base::beg);\r\n        file.read((char *)pixels + bufOfs, stripByteCounts[i]);\r\n        bufOfs += stripByteCounts[i];\r\n        if (file.gcount() != stripByteCounts[i])\r\n        {\r\n            if (errorMsg) *errorMsg = boost::str(boost::format(\"The file is incomplete: pixel data in strip %d is too short. Expected %d bytes, but read only %d.\") % i % stripByteCounts[i] % file.gcount());\r\n            free(pixels);\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    if ((pixFmt == PIX_MONO16 || pixFmt == PIX_RGB48) && isBE)\r\n        SwapBufferWords((uint16_t *)pixels, imgWidth*imgHeight*GetBytesPerPixel(pixFmt)/2);\r\n\r\n    if (photometricInterpretation == PHMET_WHITE_IS_ZERO)\r\n    {\r\n        // Reverse the values so that \"black\" is zero, \"white\" is 255 or 65535.\r\n        if (pixFmt == PIX_MONO8)\r\n            NegateGrayscale8((uint8_t *)pixels, imgWidth*imgHeight);\r\n        else if (pixFmt == PIX_MONO16)\r\n            NegateGrayscale16((uint16_t *)pixels, imgWidth*imgHeight);\r\n    }\r\n\r\n    file.close();\r\n\r\n    return pixels;\r\n}\r\n\r\nbool GetTiffDimensions(const char *fileName, unsigned &imgWidth, unsigned &imgHeight)\r\n{\r\n    std::ifstream file(fileName, std::ios_base::binary);\r\n\r\n    if (file.fail())\r\n        return false;\r\n\r\n    TiffHeader_t tiffHeader;\r\n    file.read((char *)&tiffHeader, sizeof(tiffHeader));\r\n    if (file.gcount() != sizeof(tiffHeader))\r\n        return false;\r\n\r\n    bool isBE = tiffHeader.id == MOTOROLA_BYTE_ORDER; // true if the file has big endian data\r\n\r\n    if (SWAP16cnd(tiffHeader.version, isBE) != TIFF_VERSION)\r\n        return false;\r\n\r\n    // Seek to the first TIFF directory\r\n    file.seekg(SWAP32cnd(tiffHeader.dirOffset, isBE), std::ios_base::beg);\r\n\r\n    uint16_t numDirEntries;\r\n    file.read((char *)&numDirEntries, sizeof(numDirEntries));\r\n    numDirEntries = SWAP16cnd(numDirEntries, isBE);\r\n    if (file.gcount() != sizeof(numDirEntries))\r\n        return false;\r\n\r\n    imgWidth = imgHeight = -1;\r\n\r\n    std::fstream::pos_type nextFieldPos = file.tellg();\r\n    for (unsigned i = 0; i < numDirEntries; i++)\r\n    {\r\n        TiffField_t tiffField;\r\n\r\n        file.seekg(nextFieldPos, std::ios_base::beg);\r\n        file.read((char *)&tiffField, sizeof(tiffField));\r\n        if (file.gcount() != sizeof(tiffField))\r\n            return false;\r\n        nextFieldPos = file.tellg();\r\n\r\n        tiffField.tag = SWAP16cnd(tiffField.tag, isBE);\r\n        tiffField.type = SWAP16cnd(tiffField.type, isBE);\r\n        tiffField.count = SWAP32cnd(tiffField.count, isBE);\r\n        if (tiffField.count > 1 || tiffField.type == ttDWord)\r\n            tiffField.value = SWAP32cnd(tiffField.value, isBE);\r\n        else if (tiffField.count == 1 && tiffField.type == ttWord)\r\n            tiffField.value = SWAP16in32cnd(tiffField.value, isBE);\r\n\r\n        switch (tiffField.tag)\r\n        {\r\n        case TAG_IMAGE_WIDTH: imgWidth = tiffField.value; break;\r\n        case TAG_IMAGE_HEIGHT: imgHeight = tiffField.value; break;\r\n        }\r\n\r\n        if (imgWidth != -1 && imgHeight != -1)\r\n            break;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\n} // namespace TIFF\r\n\r\n/// Converts data in input buffer to the specified pixel format and writes it to the destination buffer; if formats are the same, does nothing\r\nvoid ConvertPixelFormat(\r\n    void *srcBuf,             ///< Source (input) buffer (pixels stored left to right, top to bottom, no padding)\r\n    void *destBuf,            ///< Destination (output) buffer\r\n    int width,                ///< Image width (number of columns in the buffers)\r\n    int height,               ///< Image height (number of rows in the buffers)\r\n    PixelFormat_t srcPixFmt,  ///< Pixel format in 'srcBuf'\r\n    PixelFormat_t destPixFmt, ///< Desired pixel format in 'destBuf'; PIX_PAL8 is not supported\r\n    uint8_t palette[]         ///< Pointer to 256-element RGB(+1) palette (256*4 bytes); required if 'srcPixFmt' or 'destPixFmt' is PIX_PAL8\r\n)\r\n{\r\n    if (srcPixFmt == PIX_UNCHANGED || destPixFmt == PIX_UNCHANGED)\r\n        throw std::runtime_error(\"ConvertPixelFormat(): specifying PIX_UNCHANGED is not allowed.\");\r\n    if (destPixFmt == PIX_PAL8 && srcPixFmt != PIX_PAL8)\r\n        throw std::runtime_error(\"ConvertPixelFormat(): cannot convert to PIX_PAL8\");\r\n    if (srcPixFmt == PIX_PAL8 && !palette)\r\n        throw std::runtime_error(\"ConvertPixelFormat(): palette required when converting from PIX_PAL8\");\r\n\r\n    if (srcPixFmt == destPixFmt)\r\n        return;\r\n\r\n    uint8_t *inpPtr = (uint8_t*)srcBuf,\r\n            *outPtr = (uint8_t*)destBuf;\r\n\r\n    int inpPtrStep = GetBytesPerPixel(srcPixFmt),\r\n        outPtrStep = GetBytesPerPixel(destPixFmt);\r\n\r\n    for (int i = 0; i < width*height; i++)\r\n    {\r\n        if (srcPixFmt == PIX_MONO8)\r\n        {\r\n            uint8_t src = *inpPtr;\r\n            switch (destPixFmt)\r\n            {\r\n            case PIX_MONO16: *(uint16_t *)outPtr = (uint16_t)src << 8; break;\r\n            case PIX_MONO32F: *(float *)outPtr = src * 1.0f/0xFF; break;\r\n            case PIX_RGB24: outPtr[0] = outPtr[1] = outPtr[2] = src; break;\r\n            case PIX_RGB48:\r\n                ((uint16_t *)outPtr)[0] =\r\n                    ((uint16_t *)outPtr)[1] =\r\n                    ((uint16_t *)outPtr)[2] =  (uint16_t)src << 8;\r\n                break;\r\n            }\r\n        }\r\n        else if (srcPixFmt == PIX_MONO16)\r\n        {\r\n            uint16_t src = *(uint16_t *)inpPtr;\r\n            switch (destPixFmt)\r\n            {\r\n            case PIX_MONO8: *outPtr = (uint8_t)(src >> 8); break;\r\n            case PIX_MONO32F: *(float *)outPtr = src * 1.0f/0xFFFF; break;\r\n            case PIX_RGB24: outPtr[0] = outPtr[1] = outPtr[2] = (uint8_t)(src >> 8); break;\r\n            case PIX_RGB48:\r\n                ((uint16_t *)outPtr)[0] =\r\n                    ((uint16_t *)outPtr)[1] =\r\n                    ((uint16_t *)outPtr)[2] = src;\r\n                break;\r\n            }\r\n        }\r\n        else if (srcPixFmt == PIX_MONO32F)\r\n        {\r\n            float src = *(float *)inpPtr;\r\n            switch (destPixFmt)\r\n            {\r\n            case PIX_MONO8: *outPtr = (uint8_t)(src * 0xFF); break;\r\n            case PIX_MONO16: *(uint16_t *)outPtr = (uint16_t)(src * 0xFFFF); break;\r\n            case PIX_RGB24: outPtr[0] = outPtr[1] = outPtr[2] = (uint8_t)(src * 0xFF); break;\r\n            case PIX_RGB48:\r\n                ((uint16_t *)outPtr)[0] =\r\n                    ((uint16_t *)outPtr)[1] =\r\n                    ((uint16_t *)outPtr)[2] = (uint16_t)(src * 0xFFFF); break;\r\n            }\r\n        }\r\n        // When converting from a color format to mono, use sum (scaled) of all channels as the pixel brightness.\r\n        else if (srcPixFmt == PIX_PAL8)\r\n        {\r\n            uint8_t src = *inpPtr;\r\n            switch (destPixFmt)\r\n            {\r\n            case PIX_MONO8: *outPtr = (uint8_t)(((int)palette[4*src] + palette[4*src+1] + palette[4*src+2])/3); break;\r\n            case PIX_MONO16: *(uint16_t *)outPtr = ((uint16_t)palette[4*src] + palette[4*src+1] + palette[4*src+2])/3; break;\r\n            case PIX_MONO32F: *(float *)outPtr = ((int)palette[4*src] + palette[4*src+1] + palette[4*src+2]) * 1.0f/(3*0xFF); break;\r\n            case PIX_RGB24:\r\n                outPtr[0] = palette[4*src];\r\n                outPtr[1] = palette[4*src+1];\r\n                outPtr[2] = palette[4*src+2];\r\n                break;\r\n            case PIX_RGB48:\r\n                ((uint16_t *)outPtr)[0] = (uint16_t)palette[4*src] << 8;\r\n                ((uint16_t *)outPtr)[1] = (uint16_t)palette[4*src+1] << 8;\r\n                ((uint16_t *)outPtr)[2] = (uint16_t)palette[4*src+2] << 8;\r\n                break;\r\n            }\r\n        }\r\n        else if (srcPixFmt == PIX_RGB24)\r\n        {\r\n            switch (destPixFmt)\r\n            {\r\n            case PIX_MONO8: *outPtr = (uint8_t)(((int)inpPtr[0] + inpPtr[1] + inpPtr[2])/3); break;\r\n            case PIX_MONO16: *(uint16_t *)outPtr = ((uint16_t)inpPtr[0] + inpPtr[1] + inpPtr[2])/3; break;\r\n            case PIX_MONO32F: *(float *)outPtr = ((int)inpPtr[0] + inpPtr[1] + inpPtr[2]) * 1.0f/(3*0xFF); break;\r\n            case PIX_RGB48:\r\n                ((uint16_t *)outPtr)[0] = (uint16_t)inpPtr[0] << 8;\r\n                ((uint16_t *)outPtr)[1] = (uint16_t)inpPtr[1] << 8;\r\n                ((uint16_t *)outPtr)[2] = (uint16_t)inpPtr[2] << 8;\r\n                break;\r\n            }\r\n        }\r\n        else if (srcPixFmt == PIX_RGB48)\r\n        {\r\n            uint16_t *inpPtr16 = (uint16_t *)inpPtr;\r\n            switch (destPixFmt)\r\n            {\r\n            case PIX_MONO8: *outPtr = (uint8_t)(((int)inpPtr16[0] + inpPtr16[1] + inpPtr16[2])/3); break;\r\n            case PIX_MONO16: *(uint16_t *)outPtr = (uint16_t)(((int)inpPtr16[0] + inpPtr16[1] + inpPtr16[2])/3); break;\r\n            case PIX_MONO32F: *(float *)outPtr = ((int)inpPtr16[0] + inpPtr16[1] + inpPtr16[2]) * 1.0f/(3*0xFFFF); break;\r\n            case PIX_RGB24:\r\n                outPtr[0] = (uint8_t)(inpPtr16[0] >> 8);\r\n                outPtr[1] = (uint8_t)(inpPtr16[1] >> 8);\r\n                outPtr[2] = (uint8_t)(inpPtr16[2] >> 8);\r\n                break;\r\n            }\r\n        }\r\n\r\n        inpPtr += inpPtrStep;\r\n        outPtr += outPtrStep;\r\n    }\r\n}\r\n\r\n/// Reads an image and returns pointer to the newly allocated buffer with pixel contents or 0 on error\r\nvoid *ReadImageFile(std::string fileName,\r\n        PixelFormat_t destPixFmt, ///< Desired pixel format of data in the returned buffer\r\n        int &imgWidth,  ///< Receives image width\r\n        int &imgHeight, ///< Receives image height\r\n        PixelFormat_t *receivedPixFmt, ///< If not null and destPixFmt==PIX_UNCHANGED, receives the pixel format of the source image\r\n        uint8_t palette[],     ///< If not null and reading from an 8-bit file with palette, receives the palette (1024 bytes)\r\n        std::string *errorMsg  ///< If not null, receives error message (if any)\r\n)\r\n{\r\n    std::string ext = fileName.substr(fileName.find_last_of('.'));\r\n    std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);\r\n\r\n    void *pixels = 0;\r\n\r\n    PixelFormat_t dummy; // Used when the caller passed null as 'receivedPixFmt'\r\n    if (receivedPixFmt == 0) receivedPixFmt = &dummy;\r\n\r\n    uint8_t localPalette[256*4];\r\n    uint8_t *palPtr = (palette != 0 ? palette : localPalette);\r\n\r\n    if (ext == \".bmp\")\r\n        pixels = BMP::ReadBmp(fileName.c_str(), imgWidth, imgHeight, *receivedPixFmt, palPtr);\r\n    else if (ext == \".tif\" || ext == \".tiff\")\r\n        pixels = TIFF::ReadTiff(fileName.c_str(), *receivedPixFmt, imgWidth, imgHeight, errorMsg);\r\n    else\r\n        return 0;\r\n\r\n    if (pixels && destPixFmt != PIX_UNCHANGED && destPixFmt != *receivedPixFmt)\r\n    {\r\n        void *convertedPixels = malloc(imgWidth * imgHeight * GetBytesPerPixel(destPixFmt));\r\n        ConvertPixelFormat(pixels, convertedPixels, imgWidth, imgHeight, *receivedPixFmt, destPixFmt, palPtr);\r\n        free(pixels);\r\n        return convertedPixels;\r\n    }\r\n    else\r\n        return pixels;\r\n}\r\n\r\nbool GetImageDimensions(std::string fileName, unsigned &imgWidth, unsigned &imgHeight)\r\n{\r\n    std::string ext = fileName.substr(fileName.find_last_of('.'));\r\n    std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);\r\n\r\n    if (ext == \".bmp\")\r\n        return BMP::GetBmpDimensions(fileName.c_str(), imgWidth, imgHeight);\r\n    else if (ext == \".tif\" || ext == \".tiff\")\r\n        return TIFF::GetTiffDimensions(fileName.c_str(), imgWidth, imgHeight);\r\n    else\r\n        return false;\r\n}\r\n\r\n/// Saves image; returns 'false' on error\r\nbool SaveImageFile(std::string fileName, ///< Output file name\r\n        int imgWidth,              ///< Image width\r\n        int imgHeight,             ///< Image height\r\n        PixelFormat_t pixFmt,      ///< Pixel format\r\n        void *pixels,              ///< Pixel contents in 'pixFmt' format\r\n        uint8_t palette[]          ///< Points to the palette (1024 bytes) to be saved if pixFmt is PIX_PAL8;\r\n)\r\n{\r\n    std::string ext = fileName.substr(fileName.find_last_of('.'));\r\n    std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);\r\n    if (ext == \".bmp\")\r\n        return BMP::SaveBmp(fileName.c_str(), imgWidth, imgHeight, pixFmt, pixels, palette);\r\n    else if (ext == \".tif\" || ext == \".tiff\")\r\n        return TIFF::SaveTiff(fileName.c_str(), pixels, pixFmt, imgWidth, imgHeight);\r\n    else\r\n        return false;\r\n}\r\n\r\n\r\ninline float ClampLuminance(float val, float maxVal)\r\n{\r\n    if (val < 0.0f)\r\n        return 0.0f;\r\n    else if (val > maxVal)\r\n        return maxVal;\r\n    else\r\n        return val;\r\n}\r\n\r\n/// Cubic (Hermite) interpolation of 4 subsequent values fm1, f0, f1, f2 at location 0<=t<=1 between the middle elements (f0 and f1)\r\ntemplate<typename T>\r\ninline float InterpolateCubic(float t, T fm1, T f0, T f1, T f2)\r\n{\r\n    float delta_k = (float)f1 - f0;\r\n    float dk = ((float)f1 - fm1)*0.5f, dk1 = ((float)f2 - f0)*0.5f;\r\n\r\n    float a0 = f0, a1 = dk, a2 = 3.0f*delta_k - 2.0f*dk - dk1,\r\n        a3 = (float)dk + dk1 - 2.0f*delta_k;\r\n\r\n    return t*(t*(a3*t + a2)+a1)+a0;\r\n}\r\n\r\n/// Performs sub-pixel image translation using cubic interpolation\r\ntemplate<typename Lum_t>\r\nvoid SubpixelTranslationImpl(\r\n        Lum_t *src,  ///< Source image\r\n        Lum_t *dest, ///< Destination image\r\n        int width,   ///< Image width\r\n        int height,  ///< Image height\r\n        int numChannels, ///< Number of channels (number of 'Lum_t' samples per pixel)\r\n        float maxLum, ///< Max value to clamp the output values to\r\n        float dx,   ///< Translation in X, |dx| < 1\r\n        float dy    ///< Translation in Y, |dy| < 1\r\n)\r\n{\r\n    if (fabs(dx) >= 1.0 || fabs(dy) >= 1.0)\r\n        throw std::runtime_error(\"SubpixelTranslation(): the translation must be by less than 1 pixel in each direction.\");\r\n\r\n    int idx = dx < 0.0f ? 1 : -1;\r\n    int idy = dy < 0.0f ? 1 : -1;\r\n\r\n    dx = fabs(dx);\r\n    dy = fabs(dy);\r\n\r\n    // Skip 2-pixels borders on each side of the image\r\n    #pragma omp parallel for\r\n    for (int row = 2; row < height-2; row++)\r\n    {\r\n        for (int col = 2; col < width-2; col++)\r\n        {\r\n            for (int ch = 0; ch < numChannels; ch++)\r\n            {\r\n                float yvals[4];\r\n\r\n                // Perform 4 interpolations at 4 adjacent rows, using X offsets -1, 0, 1, 2 (*idx)\r\n                int y = row - idy;\r\n                for (int relY = -1; relY <= 2; relY++)\r\n                {\r\n                    yvals[relY+1] = InterpolateCubic(dx,\r\n                                     src[(col-idx     + y*width)*numChannels + ch],\r\n                                     src[(col         + y*width)*numChannels + ch],\r\n                                     src[(col+idx     + y*width)*numChannels + ch],\r\n                                     src[(col+idx+idx + y*width)*numChannels + ch]);\r\n                    y += idy;\r\n                }\r\n\r\n                // Perform the final vertical (column) interpolation of the 4 horizontal (row) values interpolated previously\r\n                dest[(col + row*width)*numChannels + ch] = (Lum_t)ClampLuminance(InterpolateCubic(dy, yvals[0], yvals[1], yvals[2], yvals[3]), maxLum);\r\n            }\r\n        }\r\n    }\r\n\r\n    // Copy the 2-pixel borders without changes\r\n\r\n    // 2 top rows\r\n    memcpy(dest + (0 + 0*width) * numChannels, src + (0 + 0*width) * numChannels, width * numChannels * sizeof(Lum_t));\r\n    memcpy(dest + (0 + 1*width) * numChannels, src + (0 + 1*width) * numChannels, width * numChannels * sizeof(Lum_t));\r\n    // 2 bottom rows\r\n    memcpy(dest + (0 + (height-1)*width) * numChannels, src + (0 + (height-1)*width) * numChannels, width * numChannels * sizeof(Lum_t));\r\n    memcpy(dest + (0 + (height-2)*width) * numChannels, src + (0 + (height-2)*width) * numChannels, width * numChannels * sizeof(Lum_t));\r\n    // 2 leftmost and 2 rightmost columns\r\n    for (int row = 0; row < height; row++)\r\n    {\r\n        // 2 leftmost columns\r\n        memcpy(dest + (0 + row*width) * numChannels, src + (0 + row*width) * numChannels,\r\n                2  *numChannels * sizeof(Lum_t)); // copying 2 pixels, each is 'numChannels' elements\r\n        // 2 rightmost columns\r\n        memcpy(dest + (width-2 + row*width) * numChannels, src + (width-2 + row*width) * numChannels,\r\n                2 * numChannels * sizeof(Lum_t)); // copying 2 pixels, each is 'numChannels' elements\r\n    }\r\n}\r\n\r\n/// Performs a sub-pixel translation of an image using bicubic interpolation; PIX_PAL8 pixel format is not supported\r\nvoid SubpixelTranslation(\r\n    void *src,  ///< Source image\r\n    void *dest, ///< Destination image\r\n    int width,  ///< Image width\r\n    int height, ///< Image height\r\n    PixelFormat_t pixFmt, ///< Pixel format; PIX_PAL8 is not supported\r\n    float dx,   ///< Translation in X, |dx| < 1\r\n    float dy    ///< Translation in Y, |dy| < 1\r\n)\r\n{\r\n    if (pixFmt == PIX_PAL8)\r\n        throw std::runtime_error(\"SubpixelTranslation(): PIX_PAL8 is not supported.\");\r\n\r\n    switch (pixFmt)\r\n    {\r\n    case PIX_MONO8:   SubpixelTranslationImpl<uint8_t> ( (uint8_t *)src,  (uint8_t *)dest, width, height, 1,   (float)0xFF, dx, dy); break;\r\n    case PIX_MONO16:  SubpixelTranslationImpl<uint16_t>((uint16_t *)src, (uint16_t *)dest, width, height, 1, (float)0xFFFF, dx, dy); break;\r\n    case PIX_MONO32F: SubpixelTranslationImpl<float>   (   (float *)src,    (float *)dest, width, height, 1,          1.0f, dx, dy); break;\r\n    case PIX_RGB24:   SubpixelTranslationImpl<uint8_t> ( (uint8_t *)src,  (uint8_t *)dest, width, height, 3,   (float)0xFF, dx, dy); break;\r\n    case PIX_RGB48:   SubpixelTranslationImpl<uint16_t>((uint16_t *)src, (uint16_t *)dest, width, height, 3, (float)0xFFFF, dx, dy); break;\r\n    }\r\n}\r\n", "meta": {"hexsha": "e3e53e6bf9e6897e2f73d2143e0361a8a1233ab9", "size": 45863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "comp.cpp", "max_stars_repo_name": "johnnybeckett/imgalt", "max_stars_repo_head_hexsha": "8eac799d624013cdf9900f875ed690b3e27c352e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "comp.cpp", "max_issues_repo_name": "johnnybeckett/imgalt", "max_issues_repo_head_hexsha": "8eac799d624013cdf9900f875ed690b3e27c352e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "comp.cpp", "max_forks_repo_name": "johnnybeckett/imgalt", "max_forks_repo_head_hexsha": "8eac799d624013cdf9900f875ed690b3e27c352e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1410559496, "max_line_length": 207, "alphanum_fraction": 0.5740575191, "num_tokens": 12522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5279878474123929}}
{"text": "#define BOOST_TEST_MODULE \"test_3spn2_bond_potential\"\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 <test/util/check_potential.hpp>\n#include <mjolnir/forcefield/3SPN2/ThreeSPN2BondPotential.hpp>\n\nBOOST_AUTO_TEST_CASE(potential_3spn2_bond_double)\n{\n    using real_type = double;\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 1e-6;\n    constexpr real_type tol = 1e-6;\n\n    const real_type k  = 1.0;\n    const real_type r0 = 5.0;\n\n    mjolnir::ThreeSPN2BondPotential<real_type> potential(k, r0);\n\n    const real_type x_min = 0.5 * r0;\n    const real_type x_max = 1.5 * r0;\n\n    mjolnir::test::check_potential(potential, x_min, x_max, tol, h, N);\n}\n\nBOOST_AUTO_TEST_CASE(potential_3spn2_bond_float)\n{\n    using real_type = float;\n    constexpr std::size_t N = 100;\n    constexpr real_type   h = 1e-3f;\n    constexpr real_type tol = 1e-3f;\n\n    const real_type k  = 1.0f;\n    const real_type r0 = 5.0f;\n\n    mjolnir::ThreeSPN2BondPotential<real_type> potential(k, r0);\n\n    const real_type x_min = 0.5 * r0;\n    const real_type x_max = 1.5 * r0;\n\n    mjolnir::test::check_potential(potential, x_min, x_max, tol, h, N);\n}\n", "meta": {"hexsha": "3aeb56cfbd1b690cc444be4bb1f34f0e196c467b", "size": 1222, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_3spn2_bond_potential.cpp", "max_stars_repo_name": "ToruNiina/Mjolnir", "max_stars_repo_head_hexsha": "44435dd3afc12f5c8ea27a66d7ab282df3e588ff", "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_3spn2_bond_potential.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_3spn2_bond_potential.cpp", "max_forks_repo_name": "Mjolnir-MD/Mjolnir", "max_forks_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "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": 26.0, "max_line_length": 71, "alphanum_fraction": 0.709492635, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5279878354999932}}
{"text": "/*\n2014, the dachshund authors.\n*/\n\n#include <cmath>\n#include <cstdio>\n\n#include <iostream>\n#include <Eigen/Dense>\n\n#if defined(_OPENMP)\n#include <omp.h>\n#endif\n\n#include \"timer.h\"\n#include \"linalg.h\"\n\n#include \"map.h\"\n\nvoid smp_product(const int num_pixel_points, const Point* const pixel_coords,\n    const int num_map_points, const Point* const map_coords,\n    const SignalCovarParams* const s_params,\n    const double* const x, double* const m) {\n  int i, j;\n#if defined(_OPENMP)\n  #pragma omp parallel for private(i, j)\n#endif\n  for (i = 0; i < num_map_points; ++i) {\n    m[i] = 0.0;\n    const double x_i = map_coords[i].x;\n    const double y_i = map_coords[i].y;\n    const double z_i = map_coords[i].z;\n    for (j = 0; j < num_pixel_points; ++j) {\n      const double dx = x_i - pixel_coords[j].x;\n      const double dy = y_i - pixel_coords[j].y;\n      const double dz = z_i - pixel_coords[j].z;\n      const double x_perp_2 = (dx*dx + dy*dy);\n      const double x_para_2 = dz*dz;\n      const double S_ij = signal_covar(x_perp_2, x_para_2, s_params);\n      m[i] += S_ij * x[j];\n    }\n  }\n}\n", "meta": {"hexsha": "d37da475c578e578f334a06617c7333e0a73cb75", "size": 1093, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/map.cc", "max_stars_repo_name": "caseywstark/dachshund", "max_stars_repo_head_hexsha": "6a2aeed196fd08767791b1b3c5a6df8e546d261d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-04-10T18:38:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T11:40:53.000Z", "max_issues_repo_path": "lib/map.cc", "max_issues_repo_name": "caseywstark/dachshund", "max_issues_repo_head_hexsha": "6a2aeed196fd08767791b1b3c5a6df8e546d261d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T15:19:55.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-22T15:19:55.000Z", "max_forks_repo_path": "lib/map.cc", "max_forks_repo_name": "caseywstark/dachshund", "max_forks_repo_head_hexsha": "6a2aeed196fd08767791b1b3c5a6df8e546d261d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-06-21T20:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T04:31:17.000Z", "avg_line_length": 24.8409090909, "max_line_length": 77, "alphanum_fraction": 0.6468435499, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5279540370124136}}
{"text": "#pragma once\n\n#include <cmath>\n#include <iostream>\n#include <Eigen/Core>\n#include <string>\n\nclass GridFilter\n{\npublic:\n    GridFilter(const Eigen::MatrixXd & mat, double xStep, double yStep,\n               int initDeviation = 1, double gradInfl = 1.0, double allowErr = 0.0)\n        : m_ParaboloidMatrix(mat), m_InitialDeviation(initDeviation), m_GradientInfluence(gradInfl), m_AllowableError(allowErr) {\n            m_PMrows = mat.rows();\n            m_PMcols = mat.cols();\n            ComputeGradient(xStep, yStep);\n            m_CrossSectionModified = Eigen::MatrixXd::Zero(m_PMrows, m_PMcols);\n        }\n\n    GridFilter(int rows, int columns, double* mat, double xStep, double yStep,\n               int initDeviation = 1, double gradInfl = 1.0, double allowErr = 0.0)\n        : m_ParaboloidMatrix(Eigen::Map<Eigen::MatrixXd>(mat, rows, columns)),\n        m_InitialDeviation(initDeviation), m_GradientInfluence(gradInfl), m_AllowableError(allowErr) {\n            m_PMrows = rows;\n            m_PMcols = columns;\n            ComputeGradient(xStep, yStep);\n            m_CrossSectionModified = Eigen::MatrixXd::Zero(m_PMrows, m_PMcols);\n        }\n\n    void GetCrossSectionOriginal(Eigen::MatrixXd & CSOmatTarget, double value, bool isCScomputed = false);\n\n    void GetCrossSectionExtended(Eigen::MatrixXd & CSEmatTarget,\n                                 double value, int deviation, bool isCScomputed = false, bool isDevConst = true);\n\n    void GetCrossSectionExtendedAutoDev(Eigen::MatrixXd& CSEADmatTarget, double value);\n\n    void GetCrossSectionExtendedIrregular(Eigen::MatrixXd& CSEImatTarget, double value);\n\n    /**\n     * Getter for GridFilter#InterestingPoints matrix\n     * \\warning Should be computed at least once by addPoints() function before getting\n     * \\return SpectrumCrossSection#InterestingPoints matrix\n     */\n    inline void GetInterestingPoints(Eigen::MatrixXd & IPTarget)   {  IPTarget = m_InterestingPoints; }\n\n    /**\n     * Getter for GridFilter#CrossSectionModified matrix\n     * \\warning Should be computed at least once by addPoints() function before getting\n     * \\return GridFilter#CrossSectionModified matrix\n     */\n    inline void GetModifiedCrossSection(Eigen::MatrixXd & CSMTarget) { CSMTarget = m_CrossSectionModified; }\n\nprotected:\n\n    void ComputeGradient(double xStep, double yStep);\n    void addPoints(int deviation, bool isDevConst = true);\n    void ComputeCrossSectionOriginal(double value);\n    int ComputeCurrentDeviation();\n    void makeCorridor(int curr_x, int curr_y, int deviation);\n    void ComputeAbsGradMatrix();\n\n    Eigen::MatrixXd m_ParaboloidMatrix; //!< Full values matrix (2D and unknown size NxM)\n    Eigen::MatrixXd m_CrossSecOriginal; //!< Cross-section z=value, is not set at initial moment, can be recomputed\n    Eigen::MatrixXd m_CrossSectionModified;\n    Eigen::MatrixXd  m_AbsGrad;\n    Eigen::MatrixXd m_dxPM,         //!< x-component of gradient for ParaboloidMatrix size of [NxM-1]\n                    m_dyPM;         //!< y-omponents of gradient for ParaboloidMatrix size od [N-1xM]\n    Eigen::Matrix2Xd m_InterestingPoints;   //!< Found points\n    int m_InitialDeviation;         //!< Multiplier for deviation value, can be set at constructor, default is 1\n    double m_GradientInfluence;     //!< Multiplier for gradient component of deviation value, default is 1.0\n    double m_AllowableError;        //!< In cross-section z = value finding there is z = value+-AllowableError is found in fact\n    int m_PMcols,                   //!< The number of columns of ParaboloidMatrix, computed in constructor, can't be changed after\n        m_PMrows;                   //!< The number of rows of ParaboloidMatrix, computed in constructor, can't be changed after\n\n};\n", "meta": {"hexsha": "3001fe86ed0f01c08370ee47d57cbc9bc9420f72", "size": 3737, "ext": "hh", "lang": "C++", "max_stars_repo_path": "extra/GridFilter.hh", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "extra/GridFilter.hh", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extra/GridFilter.hh", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.1710526316, "max_line_length": 131, "alphanum_fraction": 0.6936044956, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5279540328845875}}
{"text": "#ifndef MATHTOOLBOX_MATRIX_INVERSION_HPP\n#define MATHTOOLBOX_MATRIX_INVERSION_HPP\n\n#include <Eigen/Core>\n\nnamespace mathtoolbox\n{\n    Eigen::MatrixXd GetInverseUsingUpperLeftBlockInverse(const Eigen::MatrixXd& matrix,\n                                                         const Eigen::MatrixXd& upper_left_block_inverse);\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_MATRIX_INVERSION_HPP\n", "meta": {"hexsha": "d8059f68952d3637d77e0cc45eff5a16fe225383", "size": 396, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/matrix-inversion.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/matrix-inversion.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/matrix-inversion.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": 30.4615384615, "max_line_length": 106, "alphanum_fraction": 0.7171717172, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5279255186770638}}
{"text": "#ifndef MJOLNIR_TEST_UTIL_CHECK_FORCE_HPP\n#define MJOLNIR_TEST_UTIL_CHECK_FORCE_HPP\n#include <mjolnir/math/Vector.hpp>\n#include <mjolnir/core/System.hpp>\n\n#include <mjolnir/core/LocalInteractionBase.hpp>\n#include <mjolnir/core/GlobalInteractionBase.hpp>\n#include <type_traits>\n#include <test/util/clear_system.hpp>\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\nnamespace mjolnir\n{\nnamespace test\n{\n\n// Check if the sum of the forces is zero, only if the interaction is internal.\n\ntemplate<typename traitsT, typename Interaction>\nvoid check_net_force(System<traitsT> sys,\n                     const Interaction& interaction,\n                     const typename traitsT::real_type tol)\n{\n    using real_type       = typename traitsT::real_type;\n    using coordinate_type = typename traitsT::coordinate_type;\n    clear_force(sys);\n\n    sys.preprocess_forces();\n    interaction.calc_force(sys);\n    sys.postprocess_forces();\n\n    coordinate_type f_tot = math::make_coordinate<coordinate_type>(0,0,0);\n    for(const auto& f : sys.forces())\n    {\n        f_tot += f;\n    }\n\n    BOOST_TEST(mjolnir::math::X(f_tot) == real_type(0), boost::test_tools::tolerance(tol));\n    BOOST_TEST(mjolnir::math::Y(f_tot) == real_type(0), boost::test_tools::tolerance(tol));\n    BOOST_TEST(mjolnir::math::Z(f_tot) == real_type(0), boost::test_tools::tolerance(tol));\n    return;\n}\n\n// This checks force applied to each particle and the numerical difference of\n// the corresponding energy\n\ntemplate<typename traitsT, typename Interaction>\nvoid check_force(const System<traitsT>& init,\n                 const Interaction& interaction,\n                 const typename traitsT::real_type tol,\n                 const typename traitsT::real_type dr,\n                 const bool zero_net_force = true) // sum of external force (e.g. wall potential) is non-zero\n{\n    using real_type = typename traitsT::real_type;\n\n    for(const auto& f : init.forces())\n    {\n        BOOST_TEST_REQUIRE(mjolnir::math::X(f) == real_type(0));\n        BOOST_TEST_REQUIRE(mjolnir::math::Y(f) == real_type(0));\n        BOOST_TEST_REQUIRE(mjolnir::math::Z(f) == real_type(0));\n    }\n    for(std::size_t i=0; i<9; ++i)\n    {\n        BOOST_TEST_REQUIRE(init.virial()[i] == real_type(0));\n    }\n\n    System<traitsT> sys(init);\n\n    for(std::size_t idx=0; idx<sys.size(); ++idx)\n    {\n        {\n            // ----------------------------------------------------------------\n            // reset positions\n            sys = init;\n\n            // calc U(x-dx)\n            const auto E0 = interaction.calc_energy(sys);\n\n            mjolnir::math::X(sys.position(idx)) += dr;\n\n            // calc F(x)\n            sys.preprocess_forces();\n            interaction.calc_force(sys);\n            sys.postprocess_forces();\n\n            mjolnir::math::X(sys.position(idx)) += dr;\n\n            // calc U(x+dx)\n            const auto E1 = interaction.calc_energy(sys);\n\n            // central difference\n            const auto dE = (E1 - E0) * 0.5;\n\n            BOOST_TEST(-dE == dr * mjolnir::math::X(sys.force(idx)),\n                       boost::test_tools::tolerance(tol));\n        }\n        {\n            // ----------------------------------------------------------------\n            // reset positions\n            sys = init;\n\n            // calc U(x-dx)\n            const auto E0 = interaction.calc_energy(sys);\n\n            mjolnir::math::Y(sys.position(idx)) += dr;\n\n            // calc F(x)\n            sys.preprocess_forces();\n            interaction.calc_force(sys);\n            sys.postprocess_forces();\n\n            mjolnir::math::Y(sys.position(idx)) += dr;\n\n            // calc U(x+dx)\n            const auto E1 = interaction.calc_energy(sys);\n\n            // central difference\n            const auto dE = (E1 - E0) * 0.5;\n\n            BOOST_TEST(-dE == dr * mjolnir::math::Y(sys.force(idx)),\n                       boost::test_tools::tolerance(tol));\n        }\n        {\n            // ----------------------------------------------------------------\n            // reset positions\n            sys = init;\n\n            // calc U(x-dx)\n            const auto E0 = interaction.calc_energy(sys);\n\n            mjolnir::math::Z(sys.position(idx)) += dr;\n\n            // calc F(x)\n            sys.preprocess_forces();\n            interaction.calc_force(sys);\n            sys.postprocess_forces();\n\n            mjolnir::math::Z(sys.position(idx)) += dr;\n\n            // calc U(x+dx)\n            const auto E1 = interaction.calc_energy(sys);\n\n            // central difference\n            const auto dE = (E1 - E0) * 0.5;\n\n            BOOST_TEST(-dE == dr * mjolnir::math::Z(sys.force(idx)),\n                       boost::test_tools::tolerance(tol));\n        }\n    }\n\n    // check if virial is not calculated in calc_force\n    for(std::size_t i=0; i<9; ++i)\n    {\n        BOOST_TEST_REQUIRE(init.virial()[i] == real_type(0));\n    }\n\n    if(zero_net_force)\n    {\n        check_net_force(sys, interaction, tol);\n    }\n}\n\n} // test\n} // mjolnir\n#endif// MJOLNIR_TEST_UTIL_CHECK_FORCE_HPP\n", "meta": {"hexsha": "fa33edcbfc8694f429dcb65240a97759e8c878c9", "size": 5106, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/util/check_force.hpp", "max_stars_repo_name": "ToruNiina/Mjolnir", "max_stars_repo_head_hexsha": "44435dd3afc12f5c8ea27a66d7ab282df3e588ff", "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/util/check_force.hpp", "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/util/check_force.hpp", "max_forks_repo_name": "Mjolnir-MD/Mjolnir", "max_forks_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "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": 29.8596491228, "max_line_length": 109, "alphanum_fraction": 0.5566000783, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5279255136294521}}
{"text": "/* compile_time_factorial.hpp\n *\n * Calculating factorial at compile time using recursive templates instantiation\n * Requires Boost.Multiprecision library\n*/\n\n\n\n#ifndef _COMPILE_TIME_FACTORIAL_HPP_\n#define _COMPILE_TIME_FACTORIAL_HPP_\n\n#include <type_traits>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n\n\n#ifdef __RECURSIVE_TEMPLATE_INSTANTIATION_FACTORIAL_COMPUTING\n#warning \"Be careful when using large numbers!\"\n#warning \"Add the -ftemplate-depth=N flag to increase the depth of template instantiation!\"\n#endif // __RECURSIVE_TEMPLATE_INSTANTIATION_FACTORIAL_COMPUTING\n\n\n\nnamespace alex::utils::math\n{\n    namespace concepts\n    {\n#if __cplusplus > 201703L && __cpp_concepts >= 201907L\n        template<typename T>\n        concept IntegerType =\n#if defined(__RECURSIVE_TEMPLATE_INSTANTIATION_FACTORIAL_COMPUTING) || defined(__RECURSIVE_CONSTEXPR_FUNCTION_FACTORIAL_COMPUTING) ||   \\\n    defined(__CONSTEXPR_FUNCTION_FOR_LOOP_FACTORIAL_COMPUTING)\n            std::is_integral_v<T> || boost::multiprecision::is_number<T>::value;\n#else\n            std::is_integral_v<T>;\n#endif\n#else\n    template<typename T>\n    struct IsIntegerType\n    {\n        static constexpr bool value {\n#if defined(__RECURSIVE_TEMPLATE_INSTANTIATION_FACTORIAL_COMPUTING) || defined(__RECURSIVE_CONSTEXPR_FUNCTION_FACTORIAL_COMPUTING) ||   \\\n    defined(__CONSTEXPR_FUNCTION_FOR_LOOP_FACTORIAL_COMPUTING)\n            std::is_integral_v<T> || boost::multiprecision::is_number<T>::value\n#else\n            std::is_integral_v<T>\n#endif\n        };\n    };\n#endif\n    }; // namespace alex::utils::math::concepts\n\n\n\n#if defined(__RECURSIVE_CONSTEXPR_FUNCTION_FACTORIAL_COMPUTING) || defined(__CONSTEXPR_FUNCTION_FOR_LOOP_FACTORIAL_COMPUTING)\n    namespace detail\n    {\n        template<size_t N>\n        constexpr size_t cached_factorial_value {\n            [] {\n                if constexpr (N <= 1)       return 1;\n                else if constexpr (N == 2)  return 2;\n                else if constexpr (N == 3)  return 6;\n                else if constexpr (N == 4)  return 24;\n                else if constexpr (N == 5)  return 120;\n            }()\n        };\n    } // namespace alex::utils::math::ct_factorial::detail\n#endif\n\n\n\n#ifdef __RECURSIVE_TEMPLATE_INSTANTIATION_FACTORIAL_COMPUTING\n\n    template<\n#if __cplusplus > 201703L && __cpp_concepts >= 201907L\n        concepts::IntegerType integer_type,\n        size_t N\n#else\n        typename integer_type,\n        size_t N,\n        typename = std::enable_if_t<concepts::IsIntegerType<integer_type>::value>\n#endif\n    >\n    struct ct_factorial { static constexpr integer_type value{N * ct_factorial<integer_type, N - 1>::value}; };\n\n    template<\n#if __cplusplus > 201703L && __cpp_concepts >= 201907L\n        concepts::IntegerType integer_type\n#else\n        typename integer_type\n#endif\n    >\n    struct ct_factorial<integer_type, 0> { static constexpr integer_type value{1}; };\n\n#elif defined(__RECURSIVE_CONSTEXPR_FUNCTION_FACTORIAL_COMPUTING)\n\n    template<\n#if __cplusplus > 201703L && __cpp_concepts >= 201907L\n        concepts::IntegerType integer_type,\n        size_t N\n#else\n        typename integer_type,\n        size_t N,\n        typename = std::enable_if_t<concepts::IsIntegerType<integer_type>::value>\n#endif\n    >\n    constexpr integer_type ct_factorial()\n    {\n        if constexpr (N <= 5) return detail::cached_factorial_value<N>;\n        else return N * ct_factorial<integer_type, N - 1>();\n    }\n\n#elif defined(__CONSTEXPR_FUNCTION_FOR_LOOP_FACTORIAL_COMPUTING)\n\n    template<\n#if __cplusplus > 201703L && __cpp_concepts >= 201907L\n        concepts::IntegerType integer_type,\n        size_t N\n#else\n        typename integer_type,\n        size_t N,\n        typename = std::enable_if_t<concepts::IsIntegerType<integer_type>::value>\n#endif\n    >\n    constexpr integer_type ct_factorial()\n    {\n        if constexpr (N <= 5) return detail::cached_factorial_value<N>;\n        else {\n            integer_type result{1};\n            for (size_t i{1}; i <= N; ++i) {\n                result *= i;\n            }\n            return result;\n        }\n    }\n\n#elif defined(__SFINAE_TEMLATE_INSTANTIATION_FACTORIAL_COMPUTING)\n\n    template<\n#if __cplusplus > 201703L && __cpp_concepts >= 201907L\n        concepts::IntegerType integer_type,\n        size_t N\n#else\n        typename integer_type,\n        size_t N,\n        typename = std::enable_if_t<concepts::IsIntegerType<integer_type>::value>\n#endif\n    >\n    struct ct_factorial : std::integral_constant<integer_type, N * ct_factorial<integer_type, N - 1>{}> {};\n\n    template<\n#if __cplusplus > 201703L && __cpp_concepts >= 201907L\n        concepts::IntegerType integer_type\n#else\n        typename integer_type\n#endif\n    >\n    struct ct_factorial<integer_type, 0> : std::integral_constant<integer_type, 1> {};\n\n#endif\n\n} // namespace alex::utils::math\n\n#endif // _COMPILE_TIME_FACTORIAL_HPP_", "meta": {"hexsha": "74794c3bf15fcc9b980b817eab863b7fc5ccd911", "size": 4873, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/utils/math/compile_time_factorial.hpp", "max_stars_repo_name": "AlexCr4ckPentest/CppHacks", "max_stars_repo_head_hexsha": "b622111955dd4f87d6a8fefb7cf3fd9febd1e106", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-03T19:04:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-19T09:02:55.000Z", "max_issues_repo_path": "include/utils/math/compile_time_factorial.hpp", "max_issues_repo_name": "AlexCr4ckPentest/CppHacks", "max_issues_repo_head_hexsha": "b622111955dd4f87d6a8fefb7cf3fd9febd1e106", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-10T19:36:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-11T21:33:14.000Z", "max_forks_repo_path": "include/utils/math/compile_time_factorial.hpp", "max_forks_repo_name": "AlexCr4ckPentest/CppHacks", "max_forks_repo_head_hexsha": "b622111955dd4f87d6a8fefb7cf3fd9febd1e106", "max_forks_repo_licenses": ["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.3554216867, "max_line_length": 137, "alphanum_fraction": 0.6847937615, "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.527925513629452}}
{"text": "#pragma once\n\n#include <LayoutEmbedding/Embedding.hh>\n\n#include <Eigen/Dense>\n\nnamespace LayoutEmbedding {\n\nEigen::MatrixXd compute_vertex_repulsive_energy(const Embedding& _em);\n\n}\n", "meta": {"hexsha": "3b2af72c38d9ef8ebd92355b52dbeae429870020", "size": 182, "ext": "hh", "lang": "C++", "max_stars_repo_path": "library/LayoutEmbedding/VertexRepulsiveEnergy.hh", "max_stars_repo_name": "jsb/LayoutEmbedding", "max_stars_repo_head_hexsha": "6ef02ed0043dfabce6d593486358d6ef15cbf3ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2021-02-18T15:35:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T07:20:37.000Z", "max_issues_repo_path": "library/LayoutEmbedding/VertexRepulsiveEnergy.hh", "max_issues_repo_name": "jsb/LayoutEmbedding", "max_issues_repo_head_hexsha": "6ef02ed0043dfabce6d593486358d6ef15cbf3ba", "max_issues_repo_licenses": ["MIT"], "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/LayoutEmbedding/VertexRepulsiveEnergy.hh", "max_forks_repo_name": "jsb/LayoutEmbedding", "max_forks_repo_head_hexsha": "6ef02ed0043dfabce6d593486358d6ef15cbf3ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-02-17T14:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T09:51:25.000Z", "avg_line_length": 15.1666666667, "max_line_length": 70, "alphanum_fraction": 0.7967032967, "num_tokens": 40, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5279255085818403}}
{"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 * @file    ShonanAveragingCLI.cpp\n * @brief   Run Shonan Rotation Averaging Algorithm on a file or example dataset\n * @author  Frank Dellaert\n * @date    August, 2020\n *\n * Example usage:\n *\n * Running without arguments will run on tiny 3D example pose3example-grid\n * ./ShonanAveragingCLI\n *\n * Read 2D dataset w10000 (in examples/data) and output to w10000-rotations.g2o\n * ./ShonanAveragingCLI -d 2 -n w10000 -o w10000-rotations.g2o\n *\n * Read 3D dataset sphere25000.txt and output to shonan.g2o (default)\n * ./ShonanAveragingCLI -i spere2500.txt\n *\n */\n\n#include <gtsam/base/timing.h>\n#include <gtsam/sfm/ShonanAveraging.h>\n#include <gtsam/slam/InitializePose.h>\n#include <gtsam/slam/dataset.h>\n\n#include <boost/program_options.hpp>\n\nusing namespace std;\nusing namespace gtsam;\nnamespace po = boost::program_options;\n\n/* ************************************************************************* */\nint main(int argc, char* argv[]) {\n  string datasetName;\n  string inputFile;\n  string outputFile;\n  int d, seed;\n  po::options_description desc(\n      \"Shonan Rotation Averaging CLI reads a *pose* graph, extracts the \"\n      \"rotation constraints, and runs the Shonan algorithm.\");\n  desc.add_options()(\"help\", \"Print help message\")(\n      \"named_dataset,n\",\n      po::value<string>(&datasetName)->default_value(\"pose3example-grid\"),\n      \"Find and read frome example dataset file\")(\n      \"input_file,i\", po::value<string>(&inputFile)->default_value(\"\"),\n      \"Read pose constraints graph from the specified file\")(\n      \"output_file,o\",\n      po::value<string>(&outputFile)->default_value(\"shonan.g2o\"),\n      \"Write solution to the specified file\")(\n      \"dimension,d\", po::value<int>(&d)->default_value(3),\n      \"Optimize over 2D or 3D rotations\")(\n      \"seed,s\", po::value<int>(&seed)->default_value(42),\n      \"Random seed for initial estimate\");\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    cout << desc << \"\\n\";\n    return 1;\n  }\n\n  // Get input file\n  if (inputFile.empty()) {\n    if (datasetName.empty()) {\n      cout << \"You must either specify a named dataset or an input file\\n\"\n           << desc << endl;\n      return 1;\n    }\n    inputFile = findExampleDataFile(datasetName);\n  }\n\n  // Seed random number generator\n  static std::mt19937 rng(seed);\n\n  NonlinearFactorGraph::shared_ptr inputGraph;\n  Values::shared_ptr posesInFile;\n  Values poses;\n  if (d == 2) {\n    cout << \"Running Shonan averaging for SO(2) on \" << inputFile << endl;\n    ShonanAveraging2 shonan(inputFile);\n    auto initial = shonan.initializeRandomly(rng);\n    auto result = shonan.run(initial);\n\n    // Parse file again to set up translation problem, adding a prior\n    boost::tie(inputGraph, posesInFile) = load2D(inputFile);\n    auto priorModel = noiseModel::Unit::Create(3);\n    inputGraph->addPrior(0, posesInFile->at<Pose2>(0), priorModel);\n\n    cout << \"recovering 2D translations\" << endl;\n    auto poseGraph = initialize::buildPoseGraph<Pose2>(*inputGraph);\n    poses = initialize::computePoses<Pose2>(result.first, &poseGraph);\n  } else if (d == 3) {\n    cout << \"Running Shonan averaging for SO(3) on \" << inputFile << endl;\n    ShonanAveraging3 shonan(inputFile);\n    auto initial = shonan.initializeRandomly(rng);\n    auto result = shonan.run(initial);\n\n    // Parse file again to set up translation problem, adding a prior\n    boost::tie(inputGraph, posesInFile) = load3D(inputFile);\n    auto priorModel = noiseModel::Unit::Create(6);\n    inputGraph->addPrior(0, posesInFile->at<Pose3>(0), priorModel);\n\n    cout << \"recovering 3D translations\" << endl;\n    auto poseGraph = initialize::buildPoseGraph<Pose3>(*inputGraph);\n    poses = initialize::computePoses<Pose3>(result.first, &poseGraph);\n  } else {\n    cout << \"Can only run SO(2) or SO(3) averaging\\n\" << desc << endl;\n    return 1;\n  }\n  cout << \"Writing result to \" << outputFile << endl;\n  writeG2o(NonlinearFactorGraph(), poses, outputFile);\n  return 0;\n}\n\n/* ************************************************************************* */\n", "meta": {"hexsha": "09221fda267b3aa367b44a1b57c11da624c6c296", "size": 4502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ShonanAveragingCLI.cpp", "max_stars_repo_name": "xxiao-1/gtsam", "max_stars_repo_head_hexsha": "8b1516f43ffdf6b5098fc282b566f2ee1edb50f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-09-24T02:19:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T16:49:46.000Z", "max_issues_repo_path": "examples/ShonanAveragingCLI.cpp", "max_issues_repo_name": "xxiao-1/gtsam", "max_issues_repo_head_hexsha": "8b1516f43ffdf6b5098fc282b566f2ee1edb50f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-18T17:43:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T20:21:19.000Z", "max_forks_repo_path": "examples/ShonanAveragingCLI.cpp", "max_forks_repo_name": "xxiao-1/gtsam", "max_forks_repo_head_hexsha": "8b1516f43ffdf6b5098fc282b566f2ee1edb50f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-16T05:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T05:36:30.000Z", "avg_line_length": 35.7301587302, "max_line_length": 80, "alphanum_fraction": 0.6366059529, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5279255085818403}}
{"text": "//  (C) Copyright John Maddock 2008.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <pch.hpp>\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/math/tools/test.hpp>\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include <boost/math/special_functions/ulp.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <iostream>\n#include <iomanip>\n\n#ifdef BOOST_MSVC\n#pragma warning(disable:4127)\n#endif\n\n#if !defined(_CRAYC) && !defined(__CUDACC__) && (!defined(__GNUC__) || (__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ > 3)))\n#if (defined(_M_IX86_FP) && (_M_IX86_FP >= 2)) || defined(__SSE2__) || defined(TEST_SSE2)\n#include <float.h>\n#include \"xmmintrin.h\"\n#define TEST_SSE2\n#endif\n#endif\n\n\ntemplate <class T>\nvoid test_value(const T& val, const char* name)\n{\n   using namespace boost::math;\n   T upper = tools::max_value<T>();\n   T lower = -upper;\n\n   std::cout << \"Testing type \" << name << \" with initial value \" << val << std::endl;\n\n   BOOST_CHECK_EQUAL(float_distance(float_next(val), val), -1);\n   BOOST_CHECK(float_next(val) > val);\n   BOOST_CHECK_EQUAL(float_distance(float_prior(val), val), 1);\n   BOOST_CHECK(float_prior(val) < val);\n   BOOST_CHECK_EQUAL(float_distance((boost::math::nextafter)(val, upper), val), -1);\n   BOOST_CHECK((boost::math::nextafter)(val, upper) > val);\n   BOOST_CHECK_EQUAL(float_distance((boost::math::nextafter)(val, lower), val), 1);\n   BOOST_CHECK((boost::math::nextafter)(val, lower) < val);\n   BOOST_CHECK_EQUAL(float_distance(float_next(float_next(val)), val), -2);\n   BOOST_CHECK_EQUAL(float_distance(float_prior(float_prior(val)), val), 2);\n   BOOST_CHECK_EQUAL(float_distance(float_prior(float_prior(val)), float_next(float_next(val))), 4);\n   BOOST_CHECK_EQUAL(float_distance(float_prior(float_next(val)), val), 0);\n   BOOST_CHECK_EQUAL(float_distance(float_next(float_prior(val)), val), 0);\n   BOOST_CHECK_EQUAL(float_prior(float_next(val)), val);\n   BOOST_CHECK_EQUAL(float_next(float_prior(val)), val);\n\n   BOOST_CHECK_EQUAL(float_distance(float_advance(val, 4), val), -4);\n   BOOST_CHECK_EQUAL(float_distance(float_advance(val, -4), val), 4);\n   if(std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::has_denorm == std::denorm_present))\n   {\n      BOOST_CHECK_EQUAL(float_distance(float_advance(float_next(float_next(val)), 4), float_next(float_next(val))), -4);\n      BOOST_CHECK_EQUAL(float_distance(float_advance(float_next(float_next(val)), -4), float_next(float_next(val))), 4);\n   }\n   if(val > 0)\n   {\n      T n = val + ulp(val);\n      T fn = float_next(val);\n      if(n > fn)\n      {\n         BOOST_CHECK_LE(ulp(val), boost::math::tools::min_value<T>());\n      }\n      else\n      {\n         BOOST_CHECK_EQUAL(fn, n);\n      }\n   }\n   else if(val == 0)\n   {\n      BOOST_CHECK_GE(boost::math::tools::min_value<T>(), ulp(val));\n   }\n   else\n   {\n      T n = val - ulp(val);\n      T fp = float_prior(val);\n      if(n < fp)\n      {\n         BOOST_CHECK_LE(ulp(val), boost::math::tools::min_value<T>());\n      }\n      else\n      {\n         BOOST_CHECK_EQUAL(fp, n);\n      }\n   }\n}\n\ntemplate <class T>\nvoid test_values(const T& val, const char* name)\n{\n   static const T a = static_cast<T>(1.3456724e22);\n   static const T b = static_cast<T>(1.3456724e-22);\n   static const T z = 0;\n   static const T one = 1;\n   static const T two = 2;\n\n   std::cout << \"Testing type \" << name << std::endl;\n\n   T den = (std::numeric_limits<T>::min)() / 4;\n   if(den != 0)\n   {\n      std::cout << \"Denormals are active\\n\";\n   }\n   else\n   {\n      std::cout << \"Denormals are flushed to zero.\\n\";\n   }\n\n   test_value(a, name);\n   test_value(-a, name);\n   test_value(b, name);\n   test_value(-b, name);\n   test_value(boost::math::tools::epsilon<T>(), name);\n   test_value(-boost::math::tools::epsilon<T>(), name);\n   test_value(boost::math::tools::min_value<T>(), name);\n   test_value(-boost::math::tools::min_value<T>(), name);\n   if (std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::has_denorm == std::denorm_present) && ((std::numeric_limits<T>::min)() / 2 != 0))\n   {\n      test_value(z, name);\n      test_value(-z, name);\n   }\n   test_value(one, name);\n   test_value(-one, name);\n   test_value(two, name);\n   test_value(-two, name);\n#if defined(TEST_SSE2)\n   if((_mm_getcsr() & (_MM_FLUSH_ZERO_ON | 0x40)) == 0)\n   {\n#endif\n      if(std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::has_denorm == std::denorm_present) && ((std::numeric_limits<T>::min)() / 2 != 0))\n      {\n         test_value(std::numeric_limits<T>::denorm_min(), name);\n         test_value(-std::numeric_limits<T>::denorm_min(), name);\n         test_value(2 * std::numeric_limits<T>::denorm_min(), name);\n         test_value(-2 * std::numeric_limits<T>::denorm_min(), name);\n      }\n#if defined(TEST_SSE2)\n   }\n#endif\n   static const int primes[] = {\n      11,     13,     17,     19,     23,     29, \n      31,     37,     41,     43,     47,     53,     59,     61,     67,     71, \n      73,     79,     83,     89,     97,    101,    103,    107,    109,    113, \n      127,    131,    137,    139,    149,    151,    157,    163,    167,    173, \n      179,    181,    191,    193,    197,    199,    211,    223,    227,    229, \n      233,    239,    241,    251,    257,    263,    269,    271,    277,    281, \n      283,    293,    307,    311,    313,    317,    331,    337,    347,    349, \n      353,    359,    367,    373,    379,    383,    389,    397,    401,    409, \n      419,    421,    431,    433,    439,    443,    449,    457,    461,    463, \n   };\n\n   for(unsigned i = 0; i < sizeof(primes)/sizeof(primes[0]); ++i)\n   {\n      T v1 = val;\n      T v2 = val;\n      for(int j = 0; j < primes[i]; ++j)\n      {\n         v1 = boost::math::float_next(v1);\n         v2 = boost::math::float_prior(v2);\n      }\n      BOOST_CHECK_EQUAL(boost::math::float_distance(v1, val), -primes[i]);\n      BOOST_CHECK_EQUAL(boost::math::float_distance(v2, val), primes[i]);\n      BOOST_CHECK_EQUAL(boost::math::float_advance(val, primes[i]), v1);\n      BOOST_CHECK_EQUAL(boost::math::float_advance(val, -primes[i]), v2);\n   }\n   if(std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::has_infinity))\n   {\n      BOOST_CHECK_EQUAL(boost::math::float_prior(std::numeric_limits<T>::infinity()), (std::numeric_limits<T>::max)());\n      BOOST_CHECK_EQUAL(boost::math::float_next(-std::numeric_limits<T>::infinity()), -(std::numeric_limits<T>::max)());\n      BOOST_MATH_CHECK_THROW(boost::math::float_prior(-std::numeric_limits<T>::infinity()), std::domain_error);\n      BOOST_MATH_CHECK_THROW(boost::math::float_next(std::numeric_limits<T>::infinity()), std::domain_error);\n      if(boost::math::policies:: BOOST_MATH_OVERFLOW_ERROR_POLICY == boost::math::policies::throw_on_error)\n      {\n         BOOST_MATH_CHECK_THROW(boost::math::float_prior(-(std::numeric_limits<T>::max)()), std::overflow_error);\n         BOOST_MATH_CHECK_THROW(boost::math::float_next((std::numeric_limits<T>::max)()), std::overflow_error);\n      }\n      else\n      {\n         BOOST_CHECK_EQUAL(boost::math::float_prior(-(std::numeric_limits<T>::max)()), -std::numeric_limits<T>::infinity());\n         BOOST_CHECK_EQUAL(boost::math::float_next((std::numeric_limits<T>::max)()), std::numeric_limits<T>::infinity());\n      }\n   }\n   //\n   // We need to test float_distance over mulyiple orders of magnitude,\n   // the only way to get an accurate true result is to count the representations\n   // between the two end points, but we can only really do this for type float:\n   //\n   if (std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::digits < 30) && (std::numeric_limits<T>::radix == 2))\n   {\n      T left, right, dist, fresult;\n      boost::uintmax_t result;\n\n      left = static_cast<T>(0.1);\n      right = left * static_cast<T>(4.2);\n      dist = boost::math::float_distance(left, right);\n      // We have to use a wider integer type for the accurate count, since there\n      // aren't enough bits in T to get a true result if the values differ\n      // by more than a factor of 2:\n      result = 0;\n      for (; left != right; ++result, left = boost::math::float_next(left));\n      fresult = static_cast<T>(result);\n      BOOST_CHECK_EQUAL(fresult, dist);\n\n      left = static_cast<T>(-0.1);\n      right = left * static_cast<T>(4.2);\n      dist = boost::math::float_distance(right, left);\n      result = 0;\n      for (; left != right; ++result, left = boost::math::float_prior(left));\n      fresult = static_cast<T>(result);\n      BOOST_CHECK_EQUAL(fresult, dist);\n\n      left = static_cast<T>(-1.1) * (std::numeric_limits<T>::min)();\n      right = static_cast<T>(-4.1) * left;\n      dist = boost::math::float_distance(left, right);\n      result = 0;\n      for (; left != right; ++result, left = boost::math::float_next(left));\n      fresult = static_cast<T>(result);\n      BOOST_CHECK_EQUAL(fresult, dist);\n   }\n}\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n   test_values(1.0f, \"float\");\n   test_values(1.0, \"double\");\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   test_values(1.0L, \"long double\");\n   test_values(boost::math::concepts::real_concept(0), \"real_concept\");\n#endif\n\n   //\n   // Test some multiprecision types:\n   //\n   test_values(boost::multiprecision::cpp_bin_float_quad(0), \"cpp_bin_float_quad\");\n   // This is way to slow to test routinely:\n   //test_values(boost::multiprecision::cpp_bin_float_single(0), \"cpp_bin_float_single\");\n   test_values(boost::multiprecision::cpp_bin_float_50(0), \"cpp_bin_float_50\");\n\n#if defined(TEST_SSE2)\n\n#ifdef _MSC_VER\n#  pragma message(\"Compiling SSE2 test code\")\n#endif\n#ifdef __GNUC__\n#  pragma message \"Compiling SSE2 test code\"\n#endif\n\n   int mmx_flags = _mm_getcsr(); // We'll restore these later.\n\n#ifdef _WIN32\n   // These tests fail pretty badly on Linux x64, especially with Intel-12.1\n   _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);\n   std::cout << \"Testing again with Flush-To-Zero set\" << std::endl;\n   std::cout << \"SSE2 control word is: \" << std::hex << _mm_getcsr() << std::endl;\n   test_values(1.0f, \"float\");\n   test_values(1.0, \"double\");\n   _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_OFF);\n#endif\n   BOOST_ASSERT((_mm_getcsr() & 0x40) == 0);\n   _mm_setcsr(_mm_getcsr() | 0x40);\n   std::cout << \"Testing again with Denormals-Are-Zero set\" << std::endl;\n   std::cout << \"SSE2 control word is: \" << std::hex << _mm_getcsr() << std::endl;\n   test_values(1.0f, \"float\");\n   test_values(1.0, \"double\");\n\n   // Restore the MMX flags:\n   _mm_setcsr(mmx_flags);\n#endif\n   \n}\n\n\n", "meta": {"hexsha": "b49e6ff90b4dadab76b7ec9af7d2492bddd92f70", "size": 10793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/test/test_next.cpp", "max_stars_repo_name": "pdu/boost", "max_stars_repo_head_hexsha": "d6da5587d43699be1a73f6f959f4b4fcaed021fc", "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": "math/test/test_next.cpp", "max_issues_repo_name": "pdu/boost", "max_issues_repo_head_hexsha": "d6da5587d43699be1a73f6f959f4b4fcaed021fc", "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": "math/test/test_next.cpp", "max_forks_repo_name": "pdu/boost", "max_forks_repo_head_hexsha": "d6da5587d43699be1a73f6f959f4b4fcaed021fc", "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.409252669, "max_line_length": 157, "alphanum_fraction": 0.6336514407, "num_tokens": 3107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5279255085818403}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/comparable.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/core/operators.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/logical.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <stdexcept>\n\n\nnamespace boost { namespace hana {\n    struct Function {\n        struct hana {\n            struct operators\n                : boost::hana::operators::of<Comparable>\n            { };\n        };\n    };\n\n    template <typename Domain, typename Codomain, typename F, typename = operators::adl>\n    struct function_type {\n        struct hana { using datatype = Function; };\n\n        Domain dom;\n        Codomain cod;\n        F def;\n\n        friend constexpr auto domain(function_type f)\n        { return f.dom; }\n\n        friend constexpr auto codomain(function_type f)\n        { return f.cod; }\n\n        template <typename X>\n        constexpr auto operator()(X x) const {\n            if (!elem(domain(*this), x))\n                throw std::domain_error{\"use of a hana::function with an argument out of the domain\"};\n            return def(x);\n        }\n    };\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto function = [](auto domain, auto codomain) {\n        return [=](auto definition) {\n            return function_type<decltype(domain), decltype(codomain), decltype(definition)>{\n                domain, codomain, definition\n            };\n        };\n    };\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto frange = [](auto f) {\n        // Note: that would be better handled by a set data structure, but\n        // whatever for now.\n        return foldl(transform(domain(f), f), make<Tuple>(), [](auto xs, auto x) {\n            return if_(elem(xs, x), xs, prepend(x, xs));\n        });\n    };\n\n\n    template <>\n    struct equal_impl<Function, Function> {\n        template <typename F, typename G>\n        static constexpr auto apply(F f, G g) {\n            return domain(f) == domain(g) && all_of(domain(f), demux(equal)(f, g));\n        }\n    };\n}} // end namespace boost::hana\n\n\n// BOOST_HANA_CONSTEXPR_LAMBDA auto is_injective = [](auto f) {\n//     auto check = [](auto x, auto y) {\n//         return (x != y)     ^implies^   (f(x) != f(y));\n//     };\n//     return all_of(product(domain(f), domain(f)), check);\n// };\n\n// BOOST_HANA_CONSTEXPR_LAMBDA auto is_onto = [](auto f) {\n//     return codomain(f) == range(g);\n// };\n\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/range.hpp>\n#include <boost/hana/tuple.hpp>\nusing namespace boost::hana;\nusing namespace literals;\n\n\nint main() {\n    auto f = function(make<Tuple>(1_c, 2_c, 3_c), make<Tuple>(1_c, 2_c, 3_c, 4_c, 5_c, 6_c))(\n        [](auto x) { return x + 1_c; }\n    );\n\n    auto g = function(make<Tuple>(1_c, 2_c, 3_c), make<Tuple>(2_c, 3_c, 4_c))(\n        [](auto x) { return x + 1_c; }\n    );\n\n    auto h = function(make<Tuple>(1_c, 2_c, 3_c), make<Tuple>(0_c, 1_c, 2_c))(\n        [](auto x) { return x - 1_c; }\n    );\n\n    BOOST_HANA_CONSTANT_CHECK(f == g);\n    BOOST_HANA_CONSTANT_CHECK(f != h);\n    BOOST_HANA_CONSTEXPR_CHECK(f(1) == 2);\n    try { f(6); throw; } catch (std::domain_error) { }\n\n\n    BOOST_HANA_CONSTANT_CHECK(frange(f) == make<Tuple>(4_c, 3_c, 2_c));\n    (void)frange;\n}\n", "meta": {"hexsha": "cc61c0917e3c3ad6830e6a687253a69014fee0e3", "size": 3393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/sandbox/function.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/sandbox/function.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/sandbox/function.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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.0, "max_line_length": 102, "alphanum_fraction": 0.597406425, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5279255085818403}}
{"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_COSPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_COSPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing cospi capabilities\n\n    cosine of angle in \\f$\\pi\\f$ multiples.\n\n    @par Semantic:\n\n    For every parameter of floating or integral type T\n\n    @code\n    T r = cospi(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = cos(Pi<T>()*x);\n    @endcode\n\n    @par Note\n\n    As other cosine functions cospi can be used with two parameters as\n    @code\n    T r = cos(x, range_);\n    @endcode\n\n    see @ref cos for further details\n\n    As it conveys a peculiar meaning,  unlike the orher cosine, cospi is defined\n    for integral types and the result of cospi(n) coincides with \\f$(-1)^n\\f$.\n\n    Take care that large floating entries are always integral and even !\n\n    @see sincospi, cos, cosd\n\n  **/\n  const boost::dispatch::functor<tag::cospi_> cospi = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/cospi.hpp>\n#include <boost/simd/function/simd/cospi.hpp>\n\n#endif\n", "meta": {"hexsha": "439f82b7f63565ed684a38c93dbf35e7d54e5652", "size": 1525, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/cospi.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/cospi.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/cospi.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": 23.4615384615, "max_line_length": 100, "alphanum_fraction": 0.6019672131, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5279255035342285}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/multiplies.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n\nSTF_CASE_TPL (\" bs::saturated_(bs::multiplies) signed_int\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n\n  using r_t = decltype(bs::saturated_(bs::multiplies)(T(), T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  STF_EQUAL(bs::saturated_(bs::multiplies)(bs::Mone<T>(), bs::Mone<T>()), bs::One<T>());\n  STF_EQUAL(bs::saturated_(bs::multiplies)(bs::One<T>(), bs::One<T>()), bs::One<T>());\n  STF_EQUAL(bs::saturated_(bs::multiplies)(bs::Valmax<T>(), bs::Valmax<T>()), bs::Valmax<T>());\n  STF_EQUAL(bs::saturated_(bs::multiplies)(bs::Valmax<T>(),T(2)), bs::Valmax<T>());\n  STF_EQUAL(bs::saturated_(bs::multiplies)(bs::Valmax<T>(),bs::Mone<T>()), bs::Valmin<T>()+bs::One<T>());\n  STF_EQUAL(bs::saturated_(bs::multiplies)(bs::Valmax<T>(),bs::One<T>()), bs::Valmax<T>());\n  STF_EQUAL(bs::saturated_(bs::multiplies)(bs::Valmin<T>(),bs::Mone<T>()), bs::Valmax<T>());\n  STF_EQUAL(bs::saturated_(bs::multiplies)(bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n} // end of test for signed_int_\n\nSTF_CASE_TPL (\" bs::saturated_(bs::multiplies)unsigned_int\",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using r_t = decltype(bs::saturated_(bs::multiplies)(T(), T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  STF_EQUAL(bs::saturated_(bs::multiplies)(bs::One<T>(), bs::One<T>()), bs::One<T>());\n  STF_EQUAL(bs::saturated_(bs::multiplies)(bs::Valmax<T>(),T(2)), bs::Valmax<T>());\n  STF_EQUAL(bs::saturated_(bs::multiplies)(bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n} // end of test for unsigned_int_\n\nSTF_CASE(\"mul sspecial\")\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::splat;\n  using bs::Valmin;\n\n  typedef short int T1;\n  STF_EQUAL(bs::saturated_(bs::multiplies)(splat<T1>(-5165), splat<T1>(23258)), Valmin<T1>());\n\n  typedef int T2;\n  STF_EQUAL(bs::saturated_(bs::multiplies)(splat<T2>(-1306766858), splat<T2>(1550772331)), Valmin<T2>());\n  STF_EQUAL(bs::saturated_(bs::multiplies)(splat<T2>(1467238299), splat<T2>(-900961598)), Valmin<T2>());\n}\n", "meta": {"hexsha": "298be96b8f15aa42ed375bd23b78832db96c0d6f", "size": 2923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/multiplies.saturated.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/scalar/multiplies.saturated.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/multiplies.saturated.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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": 41.7571428571, "max_line_length": 105, "alphanum_fraction": 0.6322271639, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5279255035342284}}
{"text": "#include <iostream>                          // std::cout/endl/dec/hex\n#include <boost/multiprecision/cpp_int.hpp>  // boost::multiprecision::cpp_int\n\nusing namespace std;\n\nint main()\n{\n    using namespace boost::multiprecision::literals;\n    using boost::multiprecision::cpp_int;\n\n    cpp_int a = 0x123456789abcdef0_cppi;\n    cpp_int b = 16;\n    cpp_int c{\"0400\"};\n    cpp_int result = a * b / c;\n    cout << hex << result << endl;\n    cout << dec << result << endl;\n}\n", "meta": {"hexsha": "3191f9897b1aff84f346aba416c15e1129ec519e", "size": 470, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "23/boost_multiprecision/test01_cpp_int.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/boost_multiprecision/test01_cpp_int.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/boost_multiprecision/test01_cpp_int.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": 26.1111111111, "max_line_length": 78, "alphanum_fraction": 0.6234042553, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5279254965265648}}
{"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  // Idea: iterate over entities in the mesh and get interior number of dofs for\n  // each\n  std::shared_ptr<const lf::mesh::Mesh> mesh = dofhandler.Mesh();\n  for (std::size_t codim = 0; codim <= 2; ++codim) {\n    entityDofs[codim] = 0;\n    for (const auto *el : mesh->Entities(codim)) {\n      if (el->RefEl() == lf::base::RefEl::kQuad()) {\n        throw \"Only triangular meshes are allowed!\";\n      }\n      entityDofs[codim] += dofhandler.NumInteriorDofs(*el);\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  // Edges and nodes can be on the boundary\n  for (const auto *edge : mesh->Entities(1)) {\n    if (bd_flags(*edge)) {\n      no_dofs_on_bd += dofhandler.NumInteriorDofs(*edge);\n    }\n  }\n  for (const auto *node : mesh->Entities(2)) {\n    if (bd_flags(*node)) {\n      no_dofs_on_bd += dofhandler.NumInteriorDofs(*node);\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  std::shared_ptr<const lf::mesh::Mesh> mesh = dofhandler.Mesh();\n  std::cout << \"indices\\n\";\n  for (const auto *cell : mesh->Entities(0)) {\n    // check if we the FE space is really $\\Cs_1^0$\n    if (dofhandler.NumLocalDofs(*cell) != 3) {\n      throw \"Not a S_1^0 FE space!\";\n    }\n    // iterate over dofs\n    auto int_dofs = dofhandler.GlobalDofIndices(*cell);\n\n    for (auto dof_idx_p = int_dofs.begin(); dof_idx_p < int_dofs.end();\n         ++dof_idx_p) {\n      // local integral of the basis function associated with this dof:\n      // in linear Lagrangian FE, the integral over the basis functions over\n      // a triangle K is: 1/3*vol(K)\n      const double I_bary = 1.0 / 3.0 * lf::geometry::Volume(*(cell->Geometry()));\n      // multiply by the value at the dof to get local contribution\n    std::cout << *dof_idx_p << \"\\n\";\n      I += I_bary * mu(*dof_idx_p);\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  std::shared_ptr<const lf::mesh::Mesh> mesh = dofhandler.Mesh();\n  for (const auto *cell : mesh->Entities(0)) {\n    // check if we the FE space is really $\\Cs_2^0$\n    if (dofhandler.NumLocalDofs(*cell) != 6) {\n      throw \"Not a S_2^0 FE space!\";\n    }\n    const double weight = 1.0 / 3.0 * lf::geometry::Volume(*(cell->Geometry()));\n    // iterate over dofs\n    auto int_dofs = dofhandler.GlobalDofIndices(*cell);\n    // The integrated basis functions associated with the nodes are 0:\n    //  $\\int_K b_K^j dx = 0$ for $j = 1,2,3$. Skip!\n    for (int l = 3; l < 6; ++l) {\n      // The integrated basis functions associated with the edges are:\n      // $\\int_K b_K^j dx = |K|/3$ for $j = 4,5,6$\n      // multiply by the value at the dof to get local contribution\n      I += (weight * mu(int_dofs[l]));\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    if (dofh_Linear_FE.NumLocalDofs(*cell) != 3 ||\n        dofh_Quadratic_FE.NumLocalDofs(*cell) != 6) {\n      throw \"dofh_Linear_FE must have 3 dofs per cell and dofh_Quadratic_FE 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    nonstd::span<const lf::assemble::gdof_idx_t> lin_dofs =\n        dofh_Linear_FE.GlobalDofIndices(*cell);\n    nonstd::span<const lf::assemble::gdof_idx_t> quad_dofs =\n        dofh_Quadratic_FE.GlobalDofIndices(*cell);\n    for (std::size_t l = 0; l <= 2; ++l) {\n      // Let $p_1,p_2,p_3$ be the nodes of the triangle and $p_4,p_5,p_6$ the\n      // edge midpoints. Let $\\lambda_1,\\lambda_2,\\lambda_3$ be the local basis\n      // functions of $\\Cs_1^0$ and $b_1,..,b_6$ for $\\Cs_2^0$. The values of\n      // $\\lambda_i$ in the interpolation nodes $p_1,..,p_6$ are the\n      // coefficients of writing $\\lambda_i$ as lin. comb of $b_1,..b_6$.\n      // From 2-9.a we know $\\lambda_l(p_l) = 1$; $l = 1,2,3$.\n      // Hence we simply \\textbf{copy} the coefficient of $\\lambda_l$ to $b_l$\n      // for $l=1,2,3$.\n      zeta(quad_dofs[l]) = mu(lin_dofs[l]);\n      // And $\\lambda_l(p_l+3) = 0.5$, $\\lambda_{(l+1) mod 3}(p_l+3) = 0.5$;\n      // $l =1,2,3$. Hence we copy 0.5 of the respective coefficients!\n      zeta(quad_dofs[l + 3]) =\n          0.5 * (mu(lin_dofs[l]) + mu(lin_dofs[(l + 1) % 3]));\n    }\n  }\n  return zeta;\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace LFPPDofHandling\n", "meta": {"hexsha": "f6cb391f1baa1fa58610780e62bf0d34a4165b01", "size": 6572, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/LFPPDofHandling/mastersolution/lfppdofhandling.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/LFPPDofHandling/mastersolution/lfppdofhandling.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/LFPPDofHandling/mastersolution/lfppdofhandling.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": 37.5542857143, "max_line_length": 82, "alphanum_fraction": 0.6433353621, "num_tokens": 2051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789269812082, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5279093917985337}}
{"text": "#include \"LatticeFitter.hpp\"\n#include <algorithm>\n#include <NTL/LLL.h>\n\nLatticeFitter::LatticeFitter(QObject* parent)\n  : QObject(parent) {}\n\nvoid LatticeFitter::findBestLattice(const std::vector<cv::Point2f>& points)\n{\n  emit latticeFittingStarted();\n  emit progressUpdated(0);\n\n  std::vector<Lattice> bestLattices;\n\n  double progress = 0.0;\n  double progress_delta = 100.0 / points.size();\n\n  for (const auto& p : points) {\n    bestLattices.emplace_back(bestLatticeForOrigin(p, points));\n    progress += progress_delta;\n    emit progressUpdated(static_cast<int>(std::round(progress)));\n  }\n\n  best_lattice = *std::min_element(bestLattices.cbegin(), bestLattices.cend(),\n  [](const Lattice& l1, const Lattice& l2) {\n    return l1.total_error < l2.total_error;\n  });\n\n  emit foundBestLattice(best_lattice);\n}\n\nLattice LatticeFitter::bestLatticeForOrigin(\n    const cv::Point2f& origin, const std::vector<cv::Point2f>& points) const\n{\n  std::vector<NTL::vec_ZZ> vecs;\n\n  for (const auto& point : points) {\n    if (point == origin) continue;\n\n    vecs.push_back(cvPoint2fToNTLVec(point - origin));\n  }\n\n  std::vector<Lattice> lattices;\n\n  for (size_t i = 0; i < vecs.size(); ++i) {\n    for (size_t j = i + 1; j < vecs.size(); ++j) {\n      lattices.emplace_back();\n      auto& current_lattice = lattices.back();\n\n      current_lattice.origin = cvPoint2fToNTLVec(origin);\n      current_lattice.bases.SetDims(2, 2);\n      current_lattice.bases[0] = vecs[i];\n      current_lattice.bases[1] = vecs[j];\n\n      NTL::LLL_FP(current_lattice.bases);\n      calculateErrorForLattice(current_lattice, vecs);\n    }\n  }\n\n  return *std::min_element(lattices.cbegin(), lattices.cend(),\n  [](const Lattice& l1, const Lattice& l2) {\n    return l1.total_error < l2.total_error;\n  });\n}\n\nvoid LatticeFitter::calculateErrorForLattice(Lattice& lattice,\n    const std::vector<NTL::vec_ZZ>& points) const\n{\n  lattice.total_error = 0;\n\n  for (const auto& vec : points) {\n    NTL::vec_ZZ v;\n    NTL::NearVector(v, lattice.bases, vec);\n    auto u = v - vec;\n\n    lattice.total_error += std::hypot(NTL::to_double(u[0]), NTL::to_double(u[1]));\n  }\n}\n", "meta": {"hexsha": "04480da4d7b485e573f298a032e819a70b9a82f9", "size": 2118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LatticeFitter.cpp", "max_stars_repo_name": "ZoltanDalmadi/lattice-fitting", "max_stars_repo_head_hexsha": "e72f2e7a702a2797ada9401e9d5c017e7fbb4659", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LatticeFitter.cpp", "max_issues_repo_name": "ZoltanDalmadi/lattice-fitting", "max_issues_repo_head_hexsha": "e72f2e7a702a2797ada9401e9d5c017e7fbb4659", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LatticeFitter.cpp", "max_forks_repo_name": "ZoltanDalmadi/lattice-fitting", "max_forks_repo_head_hexsha": "e72f2e7a702a2797ada9401e9d5c017e7fbb4659", "max_forks_repo_licenses": ["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.8101265823, "max_line_length": 82, "alphanum_fraction": 0.6775259679, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5279093858350915}}
{"text": "/* Copyright (c) 2017, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n#pragma once\n#include <random>\n#include <cmath>\n#include <iostream>\n#include <Eigen/Dense>\n\n#include \"vmf.hpp\"\n\ntemplate<typename T>\nclass vMFprior {\n public:\n  vMFprior(const Eigen::Matrix<T,3,1>& m0, T a, T b)\n    : m0_(m0), b_(b), a_(a), unif_(0.,1.)\n  {}\n\n  T logMarginal(const Eigen::Matrix<T,3,1>& x) const {\n    const T bTilde = (x + b_*m0_).norm();\n    const T bOverTan = b_ < 1e-9 ? 2./M_PI : b_/tan(M_PI*0.5*b_);  \n    const T sinc = bTilde < 1e-9 ? 1. : sin(bTilde*M_PI)/(bTilde*M_PI);\n    const T sinus = sin(bTilde*0.5*M_PI);\n    return log(bOverTan*0.125) + log(1.-sinc) - 2*log(sinus);\n  }\n\n  vMF<T,3> sample(std::mt19937& rnd) {\n//    std::cout << \"sample from vMF prior \" << a_ << \" \" << b_ \n//      << \" \" << m0_.transpose() << std::endl;\n    Eigen::Matrix<T,3,1> mu;\n    T tau = 1.;\n    vMF<T,3> vmf(m0_, tau*b_);\n//    std::cout << \"sampling from base\" << std::endl;\n    for (size_t it=0; it<10; ++it) {\n      vmf.tau_ = tau*b_;\n      mu = vmf.sample(rnd);\n//      std::cout << \"mu \" << mu.transpose() << std::endl;\n      const T dot = mu.dot(m0_); \n      tau = sampleConcentration(dot, rnd, 3, tau);\n//      std::cout <<\"@\" << it << \"tau \" << tau << \" mu \" << mu.transpose() << std::endl;\n    }\n    return vMF<T,3>(mu, tau);\n  }\n\n  vMF<T,3> MAP() {\n    Eigen::Matrix<T,3,1> xSum=b_*m0_;\n    float tau = MLEstimateTau<float,3>(xSum, m0_, a_);\n    return vMF<T,3>(m0_, tau);\n  }\n\n  vMFprior<T> posterior(const Eigen::Matrix<T,3,1>& xSum, const T count) const {\n    T aN = a_+count;\n    Eigen::Matrix<T,3,1> muN = xSum + b_*m0_;\n    T bN = muN.norm();\n    muN /= bN;\n    return vMFprior<T>(muN, aN, bN);\n  }\n\n  vMFprior<T> posterior(const Eigen::Matrix<T,4,1>& ss) const {\n    T aN = a_+ss(3);\n    Eigen::Matrix<T,3,1> muN = ss.topRows(3) + b_*m0_;\n    T bN = muN.norm();\n    muN /= bN;\n    return vMFprior<T>(muN, aN, bN);\n  }\n\n  Eigen::Matrix<T,3,1> m0_;\n  T b_;\n  T a_;\n private:\n\n  T propToConcentrationLogPdf(const T tau, const T dot) const\n  {\n    if (tau < 1e-16) {\n      return 0.; \n    } else {\n      return a_*(log(tau) + LOG_2 - log(1.-exp(-2.*tau))) + tau*(b_*dot-a_); \n    }\n  };\n\n  T propToConcentrationLogPdfDeriv(const T tau, const T dot) const\n  {\n    // this is only for 3D case\n    if (tau < 1e-16) {\n      return b_*dot; \n    } else {\n      return a_/tau - (2.*a_*exp(-2.*tau)/(1.-exp(-2.*tau))) + b_*dot -a_;\n    }\n  };\n  T propToConcentrationLogPdfDerivDeriv(const T tau, const T dot) const\n  {\n    // this is only for 3D case\n    if (tau < 1e-16) {\n      return -a_/3.; \n    } else {\n//      return -a_/(tau*tau) + (4.*a_*exp(2.*tau)/(1.-2.*exp(2.*tau)+exp(4.*tau)));\n      return -a_/(tau*tau) + (4.*a_*exp(-2.*tau)/(1.-2.*exp(-2.*tau)+exp(-4.*tau)));\n    }\n  };\n\n  T maximum(const T dot) {\n    if (dot*b_ <= 0)\n      return 0.;\n    T tau = 1.;\n    for (size_t it=0; it<100; ++it) {\n      T f = propToConcentrationLogPdfDeriv(tau, dot);\n      T df = propToConcentrationLogPdfDerivDeriv(tau, dot);\n      tau -= f/df;\n      if (fabs(f/df) < 1e-6)\n        break;\n    }\n    return tau;\n  };\n\n  T intersect(const T c, const T dot, const T tau0) {\n    T tau = tau0;\n    for (size_t it=0; it<100; ++it) {\n      T f = propToConcentrationLogPdf(tau, dot) - c;\n      T df = propToConcentrationLogPdfDeriv(tau, dot);\n      tau = std::max(0.f, tau-f/df);\n//      std::cout << \"   __ \" <<it << \": \" << f << \" \" << df \n//        << \"\\t f/df \" << fabs(f/df) \n//        << \"\\t step to \" << tau-f/df << \": \"<< tau << std::endl;\n      if (fabs(f/df) < 1e-6 || tau == 0.)\n        break;\n    }\n    return tau;\n  };\n\n  /// slice sampler for concentration paramter tau\n  T sampleConcentration(const T dot, std::mt19937& rnd, size_t maxIt, T tau0 = 0.3)\n  {\n    T tauMax = maximum(dot);\n    T tau = tau0;\n//    std::cout << \" ----- max \" << tauMax << \" \" << tau0 \n//      << \" dot \" << dot << std::endl;\n    T tauL = 0.;\n    T tauR = tauMax;\n    for(size_t t=0; t<maxIt; ++t)\n    {\n      const T f = propToConcentrationLogPdf(tau,dot);\n      const T u = log(unif_(rnd)) + f; \n      \n      if (tauMax > 0.) {\n        tauL = intersect(u, dot, tauMax*0.001);\n        tauR = intersect(u, dot, tauMax*1.5);\n      } else {\n        tauL = 0.;\n        tauR = intersect(u, dot, 0.5);\n      }\n      tau = unif_(rnd)*(tauR-tauL)+tauL;\n//      std::cout << tauL << \" - \" << tauMax << \" - \" << tauR \n//        << \" tau= \" << tau\n//        << \" : u \" << u << \" f(tau) \" << f \n//        << \" f(tau^star) \" << propToConcentrationLogPdf(tauMax,dot)\n//        << std::endl;\n    }\n    return tau;\n  };\n\n  /// Old backstepping slice sampler implementation\n  T sampleConcentrationStepping(const T dot, std::mt19937& rnd, size_t maxIt, T tau0 = 0.3)\n  {\n//    std::cout << \"start sampling concentration ---\" << std::endl;\n    // slice sampler for concentration paramter tau\n    const T w = 0.1;  // width for expansions of search region\n    T tau = tau0;      // arbitrary starting point\n    for(size_t t=0; t<maxIt; ++t)\n    {\n      const T yMax = propToConcentrationLogPdf(tau,dot);\n      const T y = log(unif_(rnd)) + yMax; \n      T tauMin = tau-w; \n      T tauMax = tau+w; \n//      std::cout << \"before \" << tauMin << \" \" << tauMax \n//        << \": \" << propToConcentrationLogPdf(tauMin,dot)\n//        << \" \" << propToConcentrationLogPdf(tauMax,dot) << std::endl;\n      while (tauMin >=0. && propToConcentrationLogPdf(tauMin,dot) >= y) tauMin -= w;\n      tauMin = std::max(static_cast<T>(0.),tauMin); \n      while (propToConcentrationLogPdf(tauMax,dot) >= y) tauMax += w;\n//      std::cout << \"after \"  << tauMin << \" \" << tauMax \n//        << \": \" << propToConcentrationLogPdf(tauMin,dot)\n//        << \" \" << propToConcentrationLogPdf(tauMax,dot) << std::endl;\n      while(42) {\n        T tauNew = unif_(rnd)*(tauMax-tauMin)+tauMin;\n\n//        std::cout << \"@\"<< t << \": \" << tauMin << \" \" << tauMax << \" \" << tauNew << \" \" << tau \n//          << \": \" << propToConcentrationLogPdf(tauNew,dot)\n//          << \" >=? \" << y\n//          << \",  \" << propToConcentrationLogPdf(tauMin,dot)\n//          << \" \"  << propToConcentrationLogPdf(tauMax,dot) << std::endl;\n\n        if(propToConcentrationLogPdf(tauNew,dot) >= y)\n        {\n          tau = tauNew; break;\n        }else{\n          if (tauNew < tau) tauMin = tauNew; else tauMax = tauNew;\n        }\n      };\n    }\n    return tau;\n  };\n  std::uniform_real_distribution<T> unif_;\n};\n", "meta": {"hexsha": "1d793b6d0e718d3b3db6ae35c7cf1128f76ef31f", "size": 6461, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/tdp/sampling/vmfPrior.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/vmfPrior.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/vmfPrior.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": 31.6715686275, "max_line_length": 97, "alphanum_fraction": 0.5299489243, "num_tokens": 2283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5279093853568572}}
{"text": "// Copyright (c) 2018 Steven Watanabe\n//\n// Distributed under the Boost Software License Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_UNITS2_DIMENSIONS_HPP_INCLUDED\n#define BOOST_UNITS2_DIMENSIONS_HPP_INCLUDED\n\n#include <boost/units2/def.hpp>\n#include <boost/units2/unit.hpp>\n\nnamespace boost {\nnamespace units2 {\n\nBOOST_UNITS2_DEF(length);\nBOOST_UNITS2_DEF(mass);\nBOOST_UNITS2_DEF(time);\nBOOST_UNITS2_DEF(temperature);\nBOOST_UNITS2_DEF(amount);\nBOOST_UNITS2_DEF(current);\nBOOST_UNITS2_DEF(luminous_intensity);\nBOOST_UNITS2_DEF(angle);\nBOOST_UNITS2_DEF(solid_angle);\n\ninline constexpr const auto velocity = length/time;\ninline constexpr const auto acceleration = velocity/time;\ninline constexpr const auto force = mass*acceleration;\ninline constexpr const auto energy = force*length;\n\n}\n}\n\n#endif\n", "meta": {"hexsha": "1d86d1ecceebd94662c4797d7f666d1357571e9f", "size": 874, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/units2/dimensions.hpp", "max_stars_repo_name": "swatanabe/cppnow17-units", "max_stars_repo_head_hexsha": "e317aff5255afd11e3ebcd759ae3c824f6c95260", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T20:46:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-21T21:21:46.000Z", "max_issues_repo_path": "include/boost/units2/dimensions.hpp", "max_issues_repo_name": "swatanabe/cppnow17-units", "max_issues_repo_head_hexsha": "e317aff5255afd11e3ebcd759ae3c824f6c95260", "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/units2/dimensions.hpp", "max_forks_repo_name": "swatanabe/cppnow17-units", "max_forks_repo_head_hexsha": "e317aff5255afd11e3ebcd759ae3c824f6c95260", "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.9714285714, "max_line_length": 65, "alphanum_fraction": 0.8066361556, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5279093739082067}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"../test_utils.hh\"\n#include \"../fixture.hh\"\n#include \"scylla_blas/queue/worker_proc.hh\"\n#include \"../vector_utils.hh\"\n\nBOOST_FIXTURE_TEST_CASE(float_vector_scale_IT, vector_fixture)\n{\n    // Given vector of 4 floats\n    std::vector<float> vals = {1.6f, 2.9999f, 3.0f, 0.0f};\n    auto vector = getScyllaVectorOf(test_const::float_vector_1_id, vals);\n\n    // When performing scaling by 2\n    scheduler->sscal(2, *vector);\n\n    // Then result vector is scaled by 2.\n    std::vector<float> vals2 = {1.6f * 2, 2.9999f * 2, 3.0f * 2, 0.0f * 2};\n    std::optional<scylla_blas::vector_value<float>> difference = cmp_vector(*vector, vals2);\n    BOOST_CHECK(!difference.has_value());\n    if (difference.has_value()) {\n        BOOST_ERROR(fmt::format(\"Difference at position {0}, {1} - {2}\",\n                                difference->index,\n                                difference->value,\n                                vals2[difference->index - 1]));\n    }\n}\n\nBOOST_FIXTURE_TEST_CASE(double_vector_scale_IT, vector_fixture)\n{\n    // Given vector of 4 doubles\n    std::vector<double> vals = {1.6, 2.999999, 3.0, 3.141592653589793238462643383};\n    auto vector = getScyllaVectorOf(test_const::double_vector_1_id, vals);\n\n    // When performing scaling by 59.49\n    const double alpha = 59.05;\n    scheduler->dscal(alpha, *vector);\n\n    // Then result vector is scaled by 59.49.\n    std::vector<double> vals2 = {\n            1.6 * alpha,\n            2.999999 * alpha,\n            3.0 * alpha,\n            3.141592653589793238462643383 * alpha};\n    std::optional<scylla_blas::vector_value<double>> difference = cmp_vector(*vector, vals2);\n    BOOST_CHECK(!difference.has_value());\n    if (difference.has_value()) {\n        BOOST_ERROR(fmt::format(\"Difference at position {0}, {1} - {2}\",\n                                difference->index,\n                                difference->value,\n                                vals2[difference->index - 1]));\n    }\n}\n", "meta": {"hexsha": "c4b0389f6c4dae05dada2c887d2c616524dfe58f", "size": 2001, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/blas_level_1/vector_scale.cc", "max_stars_repo_name": "scylla-zpp-blas/linear-algebra", "max_stars_repo_head_hexsha": "823fe4085fdac992ed9695416d9a38d2cf6908d8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T18:36:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T19:23:30.000Z", "max_issues_repo_path": "tests/blas_level_1/vector_scale.cc", "max_issues_repo_name": "scylla-zpp-blas/linear-algebra", "max_issues_repo_head_hexsha": "823fe4085fdac992ed9695416d9a38d2cf6908d8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-12-19T18:10:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-14T18:06:17.000Z", "max_forks_repo_path": "tests/blas_level_1/vector_scale.cc", "max_forks_repo_name": "scylla-zpp-blas/linear-algebra", "max_forks_repo_head_hexsha": "823fe4085fdac992ed9695416d9a38d2cf6908d8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0555555556, "max_line_length": 93, "alphanum_fraction": 0.6036981509, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594355, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.527909367944764}}
{"text": "/** \\file QuantumChannel.cc\n *  \\todo clean Clean code when it is simple.\n *  \\todo doc Write doxygen documentation.\n *  \\authors takaakimatsuo\n *\n *  \\brief QuantumChannel\n */\n#include <omnetpp.h>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <vector>\n//#include <Eigen/Dense>\n#include <PhotonicQubit_m.h>\n\nusing namespace Eigen;\nusing namespace omnetpp;\nusing namespace quisp::messages;\n\nnamespace quisp {\nnamespace channels {\n\n/*The sum of Z,X and Y error rate equates to pauli_error_rate. Value could potentially between 0 ~ 1. */\nstruct channel_error_model {\n  double pauli_error_rate;  // Overall error rate\n  double Z_error_rate;\n  double X_error_rate;\n  double Y_error_rate;\n};\n\n/** \\class QuantumChannel QuantumChannel.cc\n *  \\todo Documentation of the class header.\n *\n *  \\brief QuantumChannel\n */\nclass QuantumChannel : public cDatarateChannel {\n public:\n  channel_error_model err;\n  double photon_loss_rate;\n  double distance = 0;  // in km\n  // int less = 0, more = 0;\n private:\n  double No_error_ceil;\n  double X_error_ceil;\n  double Y_error_ceil;\n  double Z_error_ceil;\n  double Lost_ceil;\n  int DEBUG_darkcount_count = 0;\n  MatrixXd Q_to_the_distance;\n  virtual void initialize();\n  virtual void processMessage(cMessage *msg, simtime_t t, result_t &result);\n\n public:\n  QuantumChannel();\n};\n\nDefine_Channel(QuantumChannel)\n\n    QuantumChannel::QuantumChannel() {}\n\nvoid QuantumChannel::initialize() {\n  cDatarateChannel::initialize();\n  Q_to_the_distance(5, 5);\n  distance = par(\"distance\");  // in km\n\n  /*double Z_error_ratio = par(\"Z_error_ratio\");//par(\"name\") will be read from .ini or .ned file\n  double X_error_ratio = par(\"X_error_ratio\");\n  double Y_error_ratio = par(\"Y_error_ratio\");\n  double Loss_error_ratio = par(\"photon_loss_ratio\");\n  if(Z_error_ratio==0 && X_error_ratio==0 && Y_error_ratio==0 && Loss_error_ratio==0){\n      Z_error_ratio=1;//To avoid bug.\n      X_error_ratio=1;\n      Y_error_ratio=1;\n      Loss_error_ratio=1;\n  }\n\n\n\n  double ratio_sum = Z_error_ratio + X_error_ratio + Y_error_ratio + Loss_error_ratio;//Get the sum of x:y:z for normalization\n  err.pauli_error_rate = par(\"channel_error_rate\");//This is per km.\n  err.X_error_rate = err.pauli_error_rate * (X_error_ratio/ratio_sum);\n  err.Y_error_rate = err.pauli_error_rate * (Y_error_ratio/ratio_sum);\n  err.Z_error_rate = err.pauli_error_rate * (Z_error_ratio/ratio_sum);\n  photon_loss_rate = err.pauli_error_rate * (Loss_error_ratio/ratio_sum);//Photon Loss rate per km.\n  */\n\n  photon_loss_rate = par(\"channel_Loss_error_rate\");\n  err.X_error_rate = par(\"channel_X_error_rate\");\n  err.Y_error_rate = par(\"channel_Y_error_rate\");\n  err.Z_error_rate = par(\"channel_Z_error_rate\");\n  err.pauli_error_rate = err.X_error_rate + err.Y_error_rate + err.Z_error_rate + photon_loss_rate;\n\n  /*\n  int num_err_type = 0;\n  if(err.X_error_rate !=0){\n      num_err_type++;\n  }\n  if(err.Z_error_rate !=0){\n      num_err_type++;\n  }\n  if(err.Y_error_rate !=0){\n      num_err_type++;\n  }\n\n  if((1-err.pauli_error_rate) < double(1)/double(num_err_type)){\n      //error(\"Error rate inaccurate.\");\n      std::cout<<\"Inaccurate error rate \\n\";\n  }*/\n\n  // std::cout<<\"Sum of errors must be ... = \"<<err.X_error_rate+err.Y_error_rate+err.Z_error_rate+photon_loss_rate<<\"\\n\";\n  // std::cout<<\"Channel err:\"<<err.pauli_error_rate<<\" X = \" <<err.X_error_rate << \"Y = \"<< err.Y_error_rate << \", Z = \"<< err.Z_error_rate<<\",Loss\"<<photon_loss_rate<<\"\\n\";\n  MatrixXd Transition_matrix(5, 5);\n\n  Transition_matrix << 1 - err.pauli_error_rate, err.X_error_rate, err.Z_error_rate, err.Y_error_rate, photon_loss_rate, err.X_error_rate, 1 - err.pauli_error_rate,\n      err.Y_error_rate, err.Z_error_rate, photon_loss_rate, err.Z_error_rate, err.Y_error_rate, 1 - err.pauli_error_rate, err.X_error_rate, photon_loss_rate, err.Y_error_rate,\n      err.Z_error_rate, err.X_error_rate, 1 - err.pauli_error_rate, photon_loss_rate, 0, 0, 0, 0, 1;\n\n  std::cout << \"Transition mat per km = \\n\" << Transition_matrix << \"\\n\";\n  MatrixPower<MatrixXd> Apow(Transition_matrix);\n  Q_to_the_distance = Apow(distance);\n  std::cout << \"Transition mat = \" << Q_to_the_distance << \"\\n\";\n\n  // std::cout<<\"\\nNo_error_ceil = \"<<No_error_ceil<<\", X_error_ceil = \"<< X_error_ceil << \", Z_error_ceil\"<<Z_error_ceil<<\", Y_error_ceil\"<<Y_error_ceil<<\" pauli err rate is\n  // \"<<err.pauli_error_rate<<\"\\n\"; std::cout<<\" 1-err.pauli_error_rate\"\n  // <<1-err.pauli_error_rate<<\"err.X_error_rate\"<<err.X_error_rate<<\"err.Z_error_rate\"<<err.Z_error_rate<<\"err.Y_error_rate\"<<err.Y_error_rate<<\"photon_loss_rate\"<<photon_loss_rate<<\"\\n\";\n}\n\nvoid QuantumChannel::processMessage(cMessage *msg, simtime_t t, result_t &result) {\n  cDatarateChannel::processMessage(msg, t, result);  // Call the original processMessage\n\n  try {\n    PhotonicQubit *q = check_and_cast<PhotonicQubit *>(msg);\n\n    bool lost = q->getPhotonLost();\n    bool Zerr = q->getPauliZerr();\n    bool Xerr = q->getPauliXerr();\n\n    // The photon may have an error when emitted.\n    MatrixXd Initial_condition(1, 5);  // I, X, Z, Y, Photon Lost\n    if (lost) {\n      Initial_condition << 0, 0, 0, 0, 1;  // Photon already lost. Maybe by emission time. Not implemented though.\n    } else if (Zerr && Xerr) {\n      Initial_condition << 0, 0, 0, 1, 0;  // Has a Y error\n    } else if (Zerr && !Xerr) {\n      Initial_condition << 0, 0, 1, 0, 0;  // Has a Z error\n    } else if (!Zerr && Xerr) {\n      Initial_condition << 0, 1, 0, 0, 0;  // Has an X error\n    } else {\n      Initial_condition << 1, 0, 0, 0, 0;  // No error\n    }\n    MatrixXd Output_condition(1, 5);\n    Output_condition = Initial_condition * Q_to_the_distance;\n\n    // std::cout<<\"Q_to_the_distance\"<<Q_to_the_distance<<\"\\n\";\n    // std::cout<<\"Output_condition = \"<<Output_condition<<\"\\n\";\n    No_error_ceil = Output_condition(0, 0);\n    X_error_ceil = No_error_ceil + Output_condition(0, 1);\n    Z_error_ceil = X_error_ceil + Output_condition(0, 2);\n    Y_error_ceil = Z_error_ceil + Output_condition(0, 3);\n    Lost_ceil = Y_error_ceil + Output_condition(0, 4);\n\n    // std::cout<<\"NO error ceil = \"<<No_error_ceil<<\", X = \"<<X_error_ceil<<\"Z, \"<<Z_error_ceil<<\", Y = \"<<Y_error_ceil<<\", Lost = \"<<Lost_ceil<<\"\\n\";\n\n    double rand = dblrand();  // Gives a random double between 0.0 ~ 1.0\n    /* if(rand<0.5){\n         less++;\n     }else{\n         more++;\n     }*/\n    // double rand = std::rand()/(RAND_MAX + 1.);\n    if (rand < No_error_ceil) {\n      // Qubit will end up with no error\n    } else if (No_error_ceil <= rand && rand < X_error_ceil && (No_error_ceil != X_error_ceil)) {\n      // X error\n      bool xerr = q->getPauliXerr();\n      q->setPauliXerr(!xerr);  // if xerr already was true, then another x error will make it false\n    } else if (X_error_ceil <= rand && rand < Z_error_ceil && (X_error_ceil != Z_error_ceil)) {\n      // Z error\n      bool zerr = q->getPauliZerr();\n      q->setPauliZerr(!zerr);\n    } else if (Z_error_ceil <= rand && rand < Y_error_ceil && (Z_error_ceil != Y_error_ceil)) {\n      // Y error\n      bool xerr = q->getPauliXerr();\n      q->setPauliXerr(!xerr);\n      bool zerr = q->getPauliZerr();\n      q->setPauliZerr(!zerr);\n    } else {\n      // Photon was lost\n      DEBUG_darkcount_count++;\n      // std::cout<<\"less = \"<<less<<\", more = \"<<more<<\"\\n\";\n      // std::cout<<\"dbl=\"<<rand<<\" count = \"<<DEBUG_darkcount_count<<\"\\n\";\n      q->setPhotonLost(true);\n    }\n    q->setError_random_for_debug(rand);  // For debugging purpose\n  } catch (std::exception &e) {\n    // error(\"Only PhotonicQubit is allowed in quantum channel\");\n    EV << \"Only PhotonicQubit is allowed in quantum channel\";\n  }\n}\n\n}  // namespace channels\n}  // namespace quisp\n", "meta": {"hexsha": "a8738f6edbcc202d3daeab456230404a19051789", "size": 7671, "ext": "cc", "lang": "C++", "max_stars_repo_path": "quisp/channels/QuantumChannel.cc", "max_stars_repo_name": "TSarkar99/quisp", "max_stars_repo_head_hexsha": "1c954eb20f8bf098a68e0e93caf2f7bfd7fa28da", "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": "quisp/channels/QuantumChannel.cc", "max_issues_repo_name": "TSarkar99/quisp", "max_issues_repo_head_hexsha": "1c954eb20f8bf098a68e0e93caf2f7bfd7fa28da", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quisp/channels/QuantumChannel.cc", "max_forks_repo_name": "TSarkar99/quisp", "max_forks_repo_head_hexsha": "1c954eb20f8bf098a68e0e93caf2f7bfd7fa28da", "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.1641791045, "max_line_length": 188, "alphanum_fraction": 0.6747490549, "num_tokens": 2248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5278830674512341}}
{"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 <boost/program_options.hpp>\n#include \"lsqLeastSquare3D.h\"\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <iterator>\n\n// A helper function to simplify the help command.\ntemplate<class T>\nstd::ostream& operator<<(std::ostream& os, const std::vector<T>& v)\n{\n    std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, \" \"));\n    return os;\n}\n\n/**\n* \\file lsqComputeRotTrans.cpp\n* \\brief End-user application for computing the rotation and translation connecting two sets of 3D points.\n* \\ingroup applications\n*\n* This command line application can read from two separate files, each of them containing the coordinates of many 3D points,\n* and compute the rotation and translation connecting the two sets. The user can choose between two different methods to\n* compute the rotation, and the methods can be selected with a specific option (see help). The two methods are based, respectively,\n* on the singular value decomposition of a matrix obtained from the sets of points (K.S. Arun et al., IEEE PAMI-9, 698-700, 1987),\n* and on the quaternionic representation of matrices (B.K.P. Horn, J. Opt. Soc. Am. A 4, 629-642, 1987). Rotation and translation\n* are saved in file \"rotation.dat\" and \"translation.dat\" respectively.\n*/\nint main(int argc, char* argv[]) {\n\n  try {\n\n    std::string algorithm_strategy;\n    std::string output_filename;\n\n    // Allowed options, shown in the help.\n    boost::program_options::options_description desc(\"Options\");\n\n    desc.add_options()\n      (\"help,h\", \"produce help message\")\n      (\"version,v\", \"return the version of the application\")\n      (\"method,m\", boost::program_options::value< std::string >(&algorithm_strategy)->default_value(\"svd\"),\n        \"set the algorithm for computing the rotation, either svd or quat\")\n      (\"output,o\", boost::program_options::value< std::string >(&output_filename)->default_value(\"output.dat\"),\n        \"set the name of the output file where rotation and translation are saved\")\n    ;\n\n    // Hidden options, are allowed on command line, but are not shown to the user.\n    boost::program_options::options_description hidden(\"Hidden options\");\n\n    hidden.add_options()\n      (\"input-files\", boost::program_options::value< std::vector<std::string> >(),\n        \"input files with the coordinates of the two sets of 3D points\")\n    ;\n\n    boost::program_options::options_description cmdline_options;\n    cmdline_options.add(desc).add(hidden);\n\n    boost::program_options::positional_options_description p;\n    p.add(\"input-files\", -1);\n\n    boost::program_options::variables_map vm;\n    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);\n    boost::program_options::notify(vm);\n\n    if (vm.count(\"help\")) {\n      std::cout << \"Usage: options_description [options]\" << std::endl;\n      std::cout << desc;  // The helper function is used by the help to print the list of commands.\n      return 0;\n    }\n\n    if (vm.count(\"version\")) {\n      std::cout << \"lsqComputeRotTrans version 0.0.1\" << std::endl;\n      return 0;\n    }\n\n    lsq::LeastSquare3D reference_frames;\n\n    if (vm.count(\"input-files\")) {\n\n      auto input_filenames = vm[\"input-files\"].as<std::vector<std::string>>();\n\n      if (input_filenames.size() != 2) {\n        std::cerr << \"Provide two files with the sets of coordinates of the 3D points.\" << std::endl;\n        return 1;\n      }\n\n      // ---------------------------- Read the coordinates and fill the two sets of 3D points ---------------------------\n      std::ifstream filein;\n      double x_value, y_value, z_value;\n      Eigen::Vector3d point;\n\n      for( int i = 0 ; i < 2 ;  ++i ) {\n\n        filein.open( input_filenames[i] );\n\n        if (!filein.is_open()) {\n          std::cerr << \"Error opening the input file \" << input_filenames[i] << \".\" << std::endl;\n          return 1;\n        }\n\n        std::cout << \"Input file \" << input_filenames[i] << \" is read and points are saved...\" << std::endl;\n\n        while(!filein.eof()) {\n          filein >> x_value >> y_value >> z_value;\n          point = {x_value, y_value, z_value};\n          if ( i == 0 )\n            reference_frames.add_point_first_vector(point);\n          else\n            reference_frames.add_point_second_vector(point);\n        }\n\n        filein.close();\n      }\n\n      if ( !reference_frames.same_number_of_points() ) {\n        std::cout << \"warning: The two sets of points have different size. The additional points will be neglected.\" << std::endl;\n      }\n\n    }\n    else {\n      std::cerr << \"No input files are provided. Provide two files with the sets of coordinates of the 3D points.\" << std::endl;\n      return 1;\n    }\n\n    //  ----------------------------------- Set the algorithm to compute the rotation -----------------------------------\n    std::unique_ptr<lsq::ComputeRotation> algorithm;\n\n    if ( algorithm_strategy == std::string(\"svd\") ) {\n      std::cout << \"The chosen algorithm is svd.\" << std::endl;\n      algorithm = std::unique_ptr<lsq::ComputeRotation>( new lsq::SVDMethod() );\n    }\n    else if ( algorithm_strategy == std::string(\"quat\") ) {\n      std::cout << \"The chosen algorithm is quat.\" << std::endl;\n      algorithm = std::unique_ptr<lsq::ComputeRotation>( new lsq::QuaternionMethod() );\n    }\n    else {\n      std::cerr << \"The chosen method is not available. Refer to the --help for the available methods.\" << std::endl;\n      return 1;\n    }\n\n    reference_frames.set_rotation_strategy( std::move(algorithm) );\n\n    // ---------------------- Compute the centroids and the update the sets of points around them -----------------------\n    reference_frames.centroid_first_vector();\n    reference_frames.centroid_second_vector();\n    reference_frames.update_first_points_around_centroid();\n    reference_frames.update_second_points_around_centroid();\n\n    // ---------------------------------------------- Compute the H matrix ----------------------------------------------\n    reference_frames.compute_H_matrix();\n\n    // ---------------------------------------- Compute rotation and translation ----------------------------------------\n    reference_frames.compute_rotation_matrix();\n    reference_frames.compute_translation_vector();\n\n    // ----------------------------------------- Save rotation and translation -----------------------------------------\n    Eigen::Matrix3d rotation = reference_frames.get_rotation_matrix();\n    Eigen::Vector3d translation = reference_frames.get_translation_vector();\n\n    std::ofstream fileout;\n\n    fileout.open( output_filename );\n\n    if (!fileout.is_open()) {\n      std::cerr << \"Error opening the output file \" << output_filename << \".\" << std::endl;\n      return 1;\n    }\n\n    std::cout << \"Rotation and translation are saved in the output file \" << output_filename << \".\" << std::endl;\n\n    fileout << \"The rotation matrix is:\" << std::endl;\n    fileout << rotation << std::endl;\n    fileout << \"The translation vector is:\" << std::endl;\n    fileout << translation << std::endl;\n\n    fileout.close();\n\n    }\n    catch(std::exception& e)\n    {\n        std::cerr << e.what() << std::endl;\n        return 1;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "65221a227ff1f216c3e9fc90f4ed487de881255f", "size": 7741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/Apps/lsqComputeRotTrans.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": "Code/Apps/lsqComputeRotTrans.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": "Code/Apps/lsqComputeRotTrans.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": 38.705, "max_line_length": 140, "alphanum_fraction": 0.6159410929, "num_tokens": 1701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5278776545333718}}
{"text": "/*\nCopyright <2017> <Benjamin Santos>\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\nall copies 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 <fstream>\n#include <utility>\n#include <vector>\n\n#include <boost/numeric/odeint.hpp>\n\n#include <boost/phoenix/core.hpp>\n\n#include <boost/phoenix/core.hpp>\n#include <boost/phoenix/operator.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\nnamespace phoenix = boost::phoenix;\n\n// vector type\ntypedef double value_type;\ntypedef vector< value_type > state_type;\n\n\n// system definition\nstruct stiff_system{\n  \n  // constructor, sets a and b\n  stiff_system(double a_=-101.0, double b_=-100.0): a(a_), b(b_){  }\n  \n  // rhs of ode system\n  inline\n  void operator()( const state_type &x, state_type &dxdt, const value_type t) const {\n    dxdt[0] = a*x[0] + b*x[1];\n    dxdt[1] = x[0];\n  }\n  double a;\n  double b;\n};\n\n\nint main(int argc, char **argv) {\n\n  state_type xini( 2.0 , 1.0 );\n\n  // system\n  //   stiff_system ssys();\n  stiff_system* ssys = new stiff_system();\n\n  auto stepper = make_controlled(1.0e-6, 1.0e-6,\n                                runge_kutta_cash_karp54< state_type >());\n\n\n  size_t num_of_steps = integrate_adaptive(stepper, *ssys, xini,\n                                           0.01, 50.0, 0.01,\n                        cout << phoenix::arg_names::arg2 << '\\t'\n                             << phoenix::arg_names::arg1[0] << '\\t'\n                             << phoenix::arg_names::arg1[1] << '\\t'\n                             << phoenix::arg_names::arg1[1]\n                            *phoenix::arg_names::arg1[1] << \"\\n\" );\n\n  cerr << \"\\n[ii] Number of steps: \" <<  num_of_steps << endl;\n\n  // deallocate memory for ssys\n  delete(ssys);\n  \n  return 0;\n}\n", "meta": {"hexsha": "0f27aa90c3a7b1ed79b0bbc4d7c8e9fdec81fa2e", "size": 2683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "stiff_system_rk-ck54.cpp", "max_stars_repo_name": "caos21/test-ode", "max_stars_repo_head_hexsha": "5f3b066162061119de507384fa12b4b73643c88f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-19T16:26:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-19T16:26:08.000Z", "max_issues_repo_path": "stiff_system_rk-ck54.cpp", "max_issues_repo_name": "caos21/test-ode", "max_issues_repo_head_hexsha": "5f3b066162061119de507384fa12b4b73643c88f", "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": "stiff_system_rk-ck54.cpp", "max_forks_repo_name": "caos21/test-ode", "max_forks_repo_head_hexsha": "5f3b066162061119de507384fa12b4b73643c88f", "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.4886363636, "max_line_length": 85, "alphanum_fraction": 0.6638091688, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.527877646822027}}
{"text": "#ifndef FLEMU_UTILITY_HPP\n#define FLEMU_UTILITY_HPP\n#include <boost/ut.hpp>\n\n#include <cmath>\n#include <cstdint>\n#include <cstring>\n\n#include <concepts>\n\nnamespace flemu\n{\n\n// Both ends are included.\n//                 7654 3210\n// mask(1,3) == 0b'0000'1110;\n//\ntemplate<std::unsigned_integral UInt>\nconstexpr UInt mask(const std::size_t x, const std::size_t y) noexcept\n{\n    const auto start = std::min(x, y);\n    const auto stop  = std::max(x, y);\n\n    const std::size_t width = stop - start + 1;\n    if (width < 8 * sizeof(UInt))\n    {\n        const auto m = (UInt(1) << width) - 1;\n        return m << start;\n    }\n    else\n    {\n        return std::numeric_limits<UInt>::max();\n    }\n}\n\ntemplate<std::unsigned_integral UInt>\nconstexpr int bit_at(const UInt x, const std::size_t i) noexcept\n{\n    if (i < 8 * sizeof(UInt))\n    {\n        return (x & mask<UInt>(i, i)) == 0 ? 0 : 1;\n    }\n    else\n    {\n        return 0;\n    }\n}\n\ntemplate<std::unsigned_integral UInt>\nstd::string as_bit(const UInt x) noexcept\n{\n    std::string str;\n    const auto width = sizeof(UInt)*8;\n    for(std::size_t i=0; i<width; ++i)\n    {\n        if(i % 4 == 0 && i != 0)\n        {\n            str += '\\'';\n        }\n        str += bit_at(x, width-i-1) + '0';\n    }\n    return str;\n}\n\n// only g++11 supports std::bit_cast ...\ntemplate<typename T, typename U>\nT bit_cast(const U& u)\n{\n    static_assert(sizeof(T) == sizeof(U));\n    T t;\n    std::memcpy(reinterpret_cast<char*>(std::addressof(t)),\n                reinterpret_cast<const char*>(std::addressof(u)),\n                sizeof(T));\n    return t;\n}\n\n#ifdef FLEMU_ACTIVATE_UNIT_TESTS\ninline boost::ut::suite tests_utility = [] {\n    using namespace boost::ut::literals;\n\n    \"mask\"_test = [] {\n        boost::ut::expect(mask<std::uint32_t>( 1,  3) == 0b00001110);\n        boost::ut::expect(mask<std::uint32_t>( 3,  1) == 0b00001110);\n        boost::ut::expect(mask<std::uint32_t>( 3,  3) == 0b00001000);\n        boost::ut::expect(mask<std::uint32_t>(31,  0) == 0xFFFFFFFF);\n        boost::ut::expect(mask<std::uint32_t>( 0, 31) == 0xFFFFFFFF);\n        boost::ut::expect(mask<std::uint32_t>(31, 31) == 0x80000000);\n\n        boost::ut::expect(mask<std::uint64_t>(31,  0) == 0xFFFF'FFFF);\n        boost::ut::expect(mask<std::uint64_t>(47, 32) == 0x0000'FFFF'0000'0000);\n        boost::ut::expect(mask<std::uint64_t>(63,  0) == 0xFFFF'FFFF'FFFF'FFFFull);\n        boost::ut::expect(mask<std::uint64_t>(63, 63) == 0x8000'0000'0000'0000ull);\n    };\n};\n#endif\n\n} // flemu\n#endif// FLEMU_UTILITY_HPP\n", "meta": {"hexsha": "2b2a17a79dad4cadbba275474ec3a8f1563d996c", "size": 2529, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/flemu/utility.hpp", "max_stars_repo_name": "ToruNiina/flemu", "max_stars_repo_head_hexsha": "70d98c224b6746aaa75740b3065031009d155153", "max_stars_repo_licenses": ["MIT"], "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/flemu/utility.hpp", "max_issues_repo_name": "ToruNiina/flemu", "max_issues_repo_head_hexsha": "70d98c224b6746aaa75740b3065031009d155153", "max_issues_repo_licenses": ["MIT"], "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/flemu/utility.hpp", "max_forks_repo_name": "ToruNiina/flemu", "max_forks_repo_head_hexsha": "70d98c224b6746aaa75740b3065031009d155153", "max_forks_repo_licenses": ["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.5454545455, "max_line_length": 83, "alphanum_fraction": 0.5808620008, "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5278776391106819}}
{"text": "#ifndef MPP_HAMILTONIAN_KINETIC_ENERGY_MULTIVAR_NORMAL_HPP\n#define MPP_HAMILTONIAN_KINETIC_ENERGY_MULTIVAR_NORMAL_HPP\n\n#include <random>\n#include <exception>\n#include <sstream>\n#include <string>\n#include <cmath>\n#include <cstddef>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/assert.hpp>\n\nnamespace mpp { namespace hamiltonian {\n\ntemplate<class real_scalar_type>\nclass multivariate_normal {\npublic:\n    typedef boost::numeric::ublas::vector<real_scalar_type> real_vector_type;\n    typedef std::normal_distribution<real_scalar_type> normal_distribution_type;\n\n    explicit multivariate_normal(real_vector_type const & sigma_inv) throw()\n    :m_sigma_inv(sigma_inv) {\n        if( sigma_inv.size() == std::size_t(0)) {\n            std::stringstream msg;\n            msg << \"The number of dimensions = \"\n                << m_sigma_inv.size()\n                << \" of the multivariate normal kinetic energy should be\"\n                << \" greater than zero.\";\n            throw std::length_error(msg.str());\n        }\n\n        for(std::size_t i=0;i<sigma_inv.size();++i) {\n            if( not std::isfinite(sigma_inv (i)) ) {\n                std::stringstream msg;\n                msg << i << \"th value of sigma_inv is not finite\";\n                throw std::out_of_range(msg.str());\n            }\n        }\n    }\n\n    real_scalar_type log_posterior(real_vector_type const & p) const {\n        BOOST_ASSERT_MSG( p.size() == m_sigma_inv.size(),\n            \"p should have the same dimensionality of the log_posterior.\");\n        real_scalar_type val(0);\n        for(std::size_t i=0;i<p.size();++i) {\n            val -= p(i)*p(i)*m_sigma_inv(i);\n        }\n        return real_scalar_type(0.5)*val;\n    }\n\n    real_vector_type grad_log_posterior(real_vector_type const & p) const {\n        BOOST_ASSERT_MSG( p.size() == m_sigma_inv.size(),\n            \"p should have the same dimensionality of the log_posterior.\");\n        real_vector_type dp(p.size());\n        for(std::size_t i=0;i<p.size();++i) {\n            dp(i) = -m_sigma_inv(i)*p(i);\n        }\n        return dp;\n    }\n\n    template<class rng_type>\n    real_vector_type generate_sample(rng_type & rng) {\n        real_vector_type sample(m_sigma_inv.size());\n        for(std::size_t i=0;i<m_sigma_inv.size();++i) {\n            real_scalar_type scale\n                = m_sigma_inv(i) > real_scalar_type(0) ?\n                    std::sqrt( real_scalar_type(1)/m_sigma_inv(i) ) : 0 ;\n            sample(i) = scale*m_norm_dist(rng);\n        }\n        return sample;\n    }\nprivate:\n    real_vector_type m_sigma_inv;\n    normal_distribution_type m_norm_dist;\n};\n\n}}\n\n#endif //MPP_HAMILTONIAN_KINETIC_ENERGY_MULTIVAR_NORMAL_HPP\n", "meta": {"hexsha": "a46526cc9df13eb19e9bff2f4ef9811333b35f90", "size": 2682, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mpp/hamiltonian/kinetic_energy_multivar_normal.hpp", "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": "include/mpp/hamiltonian/kinetic_energy_multivar_normal.hpp", "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": "include/mpp/hamiltonian/kinetic_energy_multivar_normal.hpp", "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": 33.525, "max_line_length": 80, "alphanum_fraction": 0.624906786, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5278776373593803}}
{"text": "//  Copyright John Maddock 2007.\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 \"required_defines.hpp\"\n#include \"performance_measure.hpp\"\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/array.hpp>\n\n#define T double\n#include \"../test/erf_data.ipp\"\n#include \"../test/erf_large_data.ipp\"\n#include \"../test/erf_small_data.ipp\"\n\ntemplate <std::size_t N>\ndouble erf_evaluate2(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::erf(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(erf_test, \"erf\")\n{\n   double result = erf_evaluate2(erf_data);\n   result += erf_evaluate2(erf_large_data);\n   result += erf_evaluate2(erf_small_data);\n\n   consume_result(result);\n   set_call_count((sizeof(erf_data) + sizeof(erf_large_data) + sizeof(erf_small_data)) / sizeof(erf_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble erf_inv_evaluate2(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::erf_inv(data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(erf_inv_test, \"erf_inv\")\n{\n   double result = erf_inv_evaluate2(erf_data);\n   result += erf_inv_evaluate2(erf_large_data);\n   result += erf_inv_evaluate2(erf_small_data);\n\n   consume_result(result);\n   set_call_count((sizeof(erf_data) + sizeof(erf_large_data) + sizeof(erf_small_data)) / sizeof(erf_data[0]));\n}\n\n#ifdef TEST_CEPHES\n\nextern \"C\" {\n\ndouble erf(double);\n\n}\n\ntemplate <std::size_t N>\ndouble erf_evaluate_cephes(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += erf(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(erf_test, \"erf-cephes\")\n{\n   double result = erf_evaluate_cephes(erf_data);\n   result += erf_evaluate_cephes(erf_large_data);\n   result += erf_evaluate_cephes(erf_small_data);\n\n   consume_result(result);\n   set_call_count((sizeof(erf_data) + sizeof(erf_large_data) + sizeof(erf_small_data)) / sizeof(erf_data[0]));\n}\n\n#endif\n\n#ifdef TEST_GSL\n\n#include <gsl/gsl_sf.h>\n\ntemplate <std::size_t N>\ndouble erf_evaluate_gsl(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += gsl_sf_erf (data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(erf_test, \"erf-gsl\")\n{\n   double result = erf_evaluate_gsl(erf_data);\n   result += erf_evaluate_gsl(erf_large_data);\n   result += erf_evaluate_gsl(erf_small_data);\n\n   consume_result(result);\n   set_call_count((sizeof(erf_data) + sizeof(erf_large_data) + sizeof(erf_small_data)) / sizeof(erf_data[0]));\n}\n\n#endif\n\n\n", "meta": {"hexsha": "1052c1a05024c343125277cde3f815fa1bfc215a", "size": 2839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/performance/test_erf.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": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T17:17:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-22T17:17:41.000Z", "max_issues_repo_path": "libs/math/performance/test_erf.cpp", "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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/performance/test_erf.cpp", "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": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T05:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T05:20:43.000Z", "avg_line_length": 25.8090909091, "max_line_length": 110, "alphanum_fraction": 0.7083480099, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.52786206193327}}
{"text": "// Author: Dmitry Anisimov.\n// In this test we compute mean value coordinates at some particular points,\n// where the computation might break. The used polygon is a concave polygon with 7 vertices.\n// We also use inexact kernel and epsilon = 1.0e-15.\n\n// Works with an exact kernel, too.\n\n#include <cmath>\n#include <cassert>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Barycentric_coordinates_2/Mean_value_2.h>\n#include <CGAL/Barycentric_coordinates_2/Generalized_barycentric_coordinates_2.h>\n#include <boost/math/special_functions/fpclassify.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\n\ntypedef Kernel::FT      Scalar;\ntypedef Kernel::Point_2 Point;\n\ntypedef std::vector<Scalar> Coordinate_vector;\ntypedef std::vector<Point>  Point_vector;\n\ntypedef std::back_insert_iterator<Coordinate_vector> Vector_insert_iterator;\n\ntypedef CGAL::Barycentric_coordinates::Mean_value_2<Kernel> Mean_value;\ntypedef CGAL::Barycentric_coordinates::Generalized_barycentric_coordinates_2<Mean_value, Kernel> Mean_value_coordinates;\n\ntypedef boost::optional<Vector_insert_iterator> Output_type;\n\nusing std::cout; using std::endl; using std::string;\n\nint main()\n{\n    Point_vector vertices(7);\n\n    vertices[0] = Point(0, 0);                                     vertices[1] = Point(1, 1);\n    vertices[2] = Point(Scalar(7)/Scalar(4), Scalar(1)/Scalar(2)); vertices[3] = Point(Scalar(7)/Scalar(4), Scalar(5)/Scalar(2));\n    vertices[4] = Point(1, 2);                                     vertices[5] = Point(0, 3);\n    vertices[6] = Point(Scalar(1)/Scalar(2), Scalar(3)/Scalar(2));\n\n    Mean_value_coordinates mean_value_coordinates(vertices.begin(), vertices.end());\n\n    const Point query_points[11] = { Point(Scalar(1) + (Scalar(1) / Scalar(std::pow(10.0, 300.0)))            , Scalar(2) - (Scalar(1) / Scalar(std::pow(10.0, 300.0)))            ),\n                                     Point(Scalar(1) + (Scalar(1) / Scalar(std::pow(10.0, 300.0)))            , Scalar(1) + (Scalar(1) / Scalar(std::pow(10.0, 300.0)))            ),\n                                     Point(1                                                                  , Scalar(3) / Scalar(2)                                              ),\n                                     Point(Scalar(5) / Scalar(4)                                              , Scalar(5) / Scalar(4)                                              ),\n                                     Point(Scalar(5) / Scalar(4)                                              , Scalar(7) / Scalar(4)                                              ),\n                                     Point(Scalar(3) / Scalar(2)                                              , Scalar(3) / Scalar(2)                                              ),\n\n                                     Point(Scalar(7) / Scalar(4) - (Scalar(1) / Scalar(std::pow(10.0, 300.0))), Scalar(7) / Scalar(4) - (Scalar(1) / Scalar(std::pow(10.0, 300.0)))),\n                                     Point(Scalar(7) / Scalar(4) - (Scalar(1) / Scalar(std::pow(10.0, 300.0))), Scalar(5) / Scalar(4) + (Scalar(1) / Scalar(std::pow(10.0, 300.0)))),\n\n                                     Point(Scalar(3) / Scalar(4) - (Scalar(1) / Scalar(std::pow(10.0, 300.0))), Scalar(3) / Scalar(4) + (Scalar(1) / Scalar(std::pow(10.0, 300.0)))),\n                                     Point(Scalar(3) / Scalar(4) - (Scalar(1) / Scalar(std::pow(10.0, 300.0))), Scalar(9) / Scalar(4) - (Scalar(1) / Scalar(std::pow(10.0, 300.0)))),\n                                     Point(Scalar(1) / Scalar(2) + (Scalar(1) / Scalar(std::pow(10.0, 300.0))), Scalar(3) / Scalar(2)                                              )\n                                   };\n\n    Coordinate_vector coordinates;\n\n    int count = 0;\n    const Scalar epsilon = Scalar(1) / Scalar(std::pow(10.0, 15.0));\n\n    for(int i = 0; i < 11; ++i) {\n        const Output_type result = mean_value_coordinates(query_points[i], coordinates);\n\n        assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 0])));\n        assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 0])));\n\n        assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 1])));\n        assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 1])));\n\n        assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 2])));\n        assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 2])));\n\n        assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 3])));\n        assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 3])));\n\n        assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 4])));\n        assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 4])));\n\n        assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 5])));\n        assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 5])));\n\n        assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 6])));\n        assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 6])));\n\n        const Scalar coordinate_sum = coordinates[count + 0] +\n                                      coordinates[count + 1] +\n                                      coordinates[count + 2] +\n                                      coordinates[count + 3] +\n                                      coordinates[count + 4] +\n                                      coordinates[count + 5] +\n                                      coordinates[count + 6] ;\n\n        const Point linear_combination( vertices[0].x()*coordinates[count + 0] +\n                                        vertices[1].x()*coordinates[count + 1] +\n                                        vertices[2].x()*coordinates[count + 2] +\n                                        vertices[3].x()*coordinates[count + 3] +\n                                        vertices[4].x()*coordinates[count + 4] +\n                                        vertices[5].x()*coordinates[count + 5] +\n                                        vertices[6].x()*coordinates[count + 6] ,\n                                        vertices[0].y()*coordinates[count + 0] +\n                                        vertices[1].y()*coordinates[count + 1] +\n                                        vertices[2].y()*coordinates[count + 2] +\n                                        vertices[3].y()*coordinates[count + 3] +\n                                        vertices[4].y()*coordinates[count + 4] +\n                                        vertices[5].y()*coordinates[count + 5] +\n                                        vertices[6].y()*coordinates[count + 6] );\n\n        const Point difference(linear_combination.x() - query_points[i].x(), linear_combination.y() - query_points[i].y());\n\n        assert( ((coordinate_sum - Scalar(1)) < epsilon) && difference.x() < epsilon && difference.y() < epsilon );\n\n        if( ((coordinate_sum - Scalar(1)) > epsilon) || difference.x() > epsilon || difference.y() > epsilon )\n        {\n            cout << endl << \"MV_special_points_test: FAILED.\" << endl << endl;\n            exit(EXIT_FAILURE);\n        }\n        count += 7;\n    }\n\n    cout << endl << \"MV_special_points_test: PASSED.\" << endl << endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "4149372edac9ad73f93946bec13e2e75dc22a116", "size": 7289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Barycentric_coordinates_2/test/Barycentric_coordinates_2/MV_special_points_test.cpp", "max_stars_repo_name": "antoniospg/cgal", "max_stars_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T09:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T05:00:23.000Z", "max_issues_repo_path": "Barycentric_coordinates_2/test/Barycentric_coordinates_2/MV_special_points_test.cpp", "max_issues_repo_name": "antoniospg/cgal", "max_issues_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-10T13:32:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T12:23:20.000Z", "max_forks_repo_path": "Barycentric_coordinates_2/test/Barycentric_coordinates_2/MV_special_points_test.cpp", "max_forks_repo_name": "antoniospg/cgal", "max_forks_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T15:26:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-21T15:26:25.000Z", "avg_line_length": 57.8492063492, "max_line_length": 181, "alphanum_fraction": 0.5088489505, "num_tokens": 1701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5278620597842129}}
{"text": "#include <iostream>\n#include <vector>\n#include <stdlib.h>\n#include <sstream>\n#include <stdio.h>\n#include <boost/algorithm/string.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/thread.hpp>\n#include <fstream>\n#include <algorithm>\n#include <boost/filesystem.hpp>\n#include <GL/glut.h>\n#include <math.h>\n#include <map>\n#include <set>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\ndouble delta_D = 0.05;\n\nint sample_index = 0;\n\nint train_index = 0;\n\nfloat damp_weight = 0.1;\n\ntemplate < typename T >\nT sigmoid1(T x)\n{\n    return 1.0f / (1.0f + exp(-x));\n}\n\ntemplate < typename T >\nT dsigmoid1(T x)\n{\n    return (1.0f - x)*x;\n}\n\ntemplate < typename T >\nT sigmoid3(T x)\n{\n    return atan(x);\n}\n\ntemplate < typename T >\nT dsigmoid3(T x)\n{\n    return 1.00/(1+x*x);\n}\n\ntemplate < typename T >\nT sigmoid2(T x)\n{\n    return log(1+exp(1.00*x));\n}\n\ntemplate < typename T >\nT dsigmoid2(T x)\n{\n    return 1.00/(1+exp(-1.00*x));\n}\n\ntemplate < typename T >\nT sigmoid(T x,int type)\n{\n    switch(type)\n    {\n        case 0:\n            return sigmoid1(x);\n        case 1:\n            return sigmoid2(x);\n        case 2:\n            return sigmoid3(x);\n    }\n}\n\ntemplate < typename T >\nT dsigmoid(T x,int type)\n{\n    switch(type)\n    {\n        case 0:\n            return dsigmoid1(x);\n        case 1:\n            return dsigmoid2(x);\n        case 2:\n            return dsigmoid3(x);\n    }\n}\n\ntemplate < typename T >\nT max(T a,T b)\n{\n    return (a>b)?a:b;\n}\n\nint maxi(int a,int b)\n{\n    return (a>b)?a:b;\n}\n\ntemplate < typename T >\nvoid apply_worker(std::vector<long> const & indices,long size,T * y,T * W,T * x)\n{\n  for(long k=0;k<indices.size();k++)\n  {\n    long i = indices[k];\n    y[i] = 0;\n    for(long j=0;j<size;j++)\n    {\n      y[i] += W[i*size+j]*x[j];\n    }\n  }\n}\n\ntemplate < typename T >\nvoid outer_product_worker(std::vector<long> const & indices,long size,T * H,T * A,T * B,T fact)\n{\n  for(long k=0;k<indices.size();k++)\n  {\n    long i = indices[k];\n    for(long j=0;j<size;j++)\n    {\n      H[i*size+j] += A[i] * B[j] * fact;\n    }\n  }\n}\n\ntemplate<typename T>\nstruct quasi_newton_info\n{\n    quasi_newton_info()\n    {\n        quasi_newton_update = false;\n    }\n\n    long get_size()\n    {\n        long size = 0;\n        for(long layer = 0;layer < n_layers;layer++)\n        {\n            size += n_nodes[layer+1]*n_nodes[layer] + n_nodes[layer+1];\n        }\n        return size;\n    }\n\n    void init_gradient ()\n    {\n        long size = get_size();\n        for(long layer = 0,k = 0;layer < n_layers;layer++)\n        {\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n                for(long j=0;j<n_nodes[layer];j++,k++)\n                {\n                    grad_tmp[k] = 0;\n                }\n            }\n            for(long i=0;i<n_nodes[layer+1];i++,k++)\n            {\n                grad_tmp[k] = 0;\n            }\n        }\n    }\n\n    void copy (T * src,T * dst,long size)\n    {\n        for(long k=0;k<size;k++)\n        {\n            dst[k] = src[k];\n        }\n    }\n\n    void copy_avg (T * src,T * dst,T alph,long size)\n    {\n        for(long k=0;k<size;k++)\n        {\n            dst[k] += (src[k]-dst[k])*alph;\n        }\n    }\n\n    bool quasi_newton_update;\n    long n_layers;\n    T *** weights_neuron;\n    T **  weights_bias;\n    std::vector<long> n_nodes;\n    T * grad_tmp;\n    T * grad_1;\n    T * grad_2;\n    T * Y;\n    T * dX;\n    T * B;\n    T * H;\n    T alpha;\n\n    void init_QuasiNewton()\n    {\n        long size = get_size();\n        grad_tmp = new T[size];\n        init_gradient();\n        grad_1 = new T[size];\n        grad_2 = new T[size];\n        copy(grad_tmp,grad_1,size);\n        copy(grad_tmp,grad_2,size);\n        B = new T[size*size];\n        T * B_tmp = init_B();\n        copy(B_tmp,B,size*size);\n        delete [] B_tmp;\n        H = new T[size*size];\n        T * H_tmp = init_H();\n        copy(H_tmp,H,size*size);\n        delete [] H_tmp;\n        dX = new T[size*size];\n        T * dX_tmp = get_dx();\n        copy(dX_tmp,dX,size);\n        delete [] dX_tmp;\n        Y = new T[size*size];\n    }\n\n    T * init_B()\n    {\n        long size = get_size();\n        T * B = new T[size*size];\n        for(long t=0;t<size*size;t++)\n        {\n            B[t] = 0;\n        }\n        for(long layer = 0, k = 0;layer < n_layers;layer++)\n        {\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n                for(long j=0;j<n_nodes[layer];j++,k++)\n                {\n                    B[k*size+k] = weights_neuron[layer][i][j];\n                }\n            }\n            for(long i=0;i<n_nodes[layer+1];i++,k++)\n            {\n                B[k*size+k] = weights_bias[layer][i];\n            }\n        }\n        return B;\n    }\n\n    T * init_H()\n    {\n        long size = get_size();\n        T * H = new T[size*size];\n        for(long t=0;t<size*size;t++)\n        {\n            H[t] = 0;\n        }\n        for(long layer = 0, k = 0;layer < n_layers;layer++)\n        {\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n                for(long j=0;j<n_nodes[layer];j++,k++)\n                {\n                    H[k*size+k] = -1;\n                }\n            }\n            for(long i=0;i<n_nodes[layer+1];i++,k++)\n            {\n                H[k*size+k] = -1;\n            }\n        }\n        return H;\n    }\n\n    void update_QuasiNewton()\n    {\n        long size = get_size();\n        copy_avg(grad_2,grad_1,0.1,size);\n        copy(grad_tmp,grad_2,size);\n        T * Y_tmp = get_y();\n        copy(Y_tmp,Y,size);\n        delete [] Y_tmp;\n        T * dX_tmp = get_dx();\n        copy(dX_tmp,dX,size);\n        delete [] dX_tmp;\n    }\n\n    T * get_y ()\n    {\n        long size = get_size();\n        T * y = new T[size];\n        //T y_m = 0;\n        for(long k=0;k<size;k++)\n        {\n            y[k] = grad_2[k] - grad_1[k];\n            //y_m = max(y_m,fabs(y[k]));\n        }\n        return y;\n    }\n\n    T * get_dx ()\n    {\n        long size = get_size();\n        T * dx = apply(H,grad_1);\n        for(long k=0;k<size;k++)\n        {\n            dx[k] *= -alpha;\n        }\n        return dx;\n    }\n\n    T * get_outer_product(T * a,T * b)\n    {\n        long size = get_size();\n        long prod_size = size*size;\n        T * prod = new T[prod_size];\n        for(long i=0,k=0;i<size;i++)\n        {\n          for(long j=0;j<size;j++,k++)\n          {\n            prod[k] = a[i]*b[j];\n          }\n        }\n        return prod;\n    }\n\n    T get_inner_product(T * a,T * b)\n    {\n        T ret = 0;\n        long size = get_size();\n        for(long i=0;i<size;i++)\n        {\n            ret += a[i]*b[i];\n        }\n        T eps = 1e-2;\n        if(ret<0)\n        {\n            ret -= eps;\n        }\n        else\n        {\n            ret += eps;\n        }\n        return ret;\n    }\n\n    T * apply(T * W, T * x)\n    {\n        long size = get_size();\n        T * y = new T[size];\n        std::vector<boost::thread * > threads;\n        long num_cpu = boost::thread::hardware_concurrency();\n        std::vector<std::vector<long> > indices(num_cpu);\n        for(long i=0;i<size;i++)\n        {\n          indices[i%num_cpu].push_back(i);\n        }\n        for(long i=0;i<num_cpu;i++)\n        {\n          threads.push_back(new boost::thread(apply_worker<T>,indices[i],size,&y[0],&W[0],&x[0]));\n        }\n        for(long i=0;i<threads.size();i++)\n        {\n          threads[i]->join();\n          delete threads[i];\n        }\n        return y;\n    }\n\n    T * apply_t(T * x, T * W)\n    {\n        long size = get_size();\n        T * y = new T[size];\n        for(long i=0,k=0;i<size;i++)\n        {\n          y[i] = 0;\n          for(long j=0;j<size;j++,k++)\n          {\n            y[i] += W[size*j+i]*x[j];\n          }\n        }\n        return y;\n    }\n\n    T limit(T x,T eps)\n    {\n        if(x>0)\n        {\n            if(x>eps)return eps;\n        }\n        else\n        {\n            if(x<-eps)return -eps;\n        }\n        return x;\n    }\n\n    // SR1\n    void SR1_update()\n    {\n        long size = get_size();\n        T * dx_Hy = apply(H,Y);\n        for(long i=0;i<size;i++)\n        {\n          dx_Hy[i] = dX[i] - dx_Hy[i];\n        }\n        T inner = 1.0 / (get_inner_product(dx_Hy,Y));\n        std::vector<boost::thread * > threads;\n        long num_cpu = boost::thread::hardware_concurrency();\n        std::vector<std::vector<long> > indices(num_cpu);\n        for(long i=0;i<size;i++)\n        {\n          indices[i%num_cpu].push_back(i);\n        }\n        for(long i=0;i<num_cpu;i++)\n        {\n          threads.push_back(new boost::thread(outer_product_worker<T>,indices[i],size,&H[0],&dx_Hy[0],&dx_Hy[0],inner));\n        }\n        for(long i=0;i<threads.size();i++)\n        {\n          threads[i]->join();\n          delete threads[i];\n        }\n        delete [] dx_Hy;\n    }\n\n    // Broyden\n    void Broyden_update()\n    {\n        long size = get_size();\n        T * dx_Hy = apply(H,Y);\n        for(long i=0;i<size;i++)\n        {\n          dx_Hy[i] = dX[i] - dx_Hy[i];\n        }\n        T * xH = apply_t(dX,H);\n        T * outer = get_outer_product(dx_Hy,xH);\n        T inner = 1.0 / (get_inner_product(xH,Y));\n        for(long i=0;i<size*size;i++)\n        {\n          H[i] += outer[i] * inner;\n        }\n        delete [] dx_Hy;\n        delete [] xH;\n        delete [] outer;\n    }\n\n    // DFP\n    void DFP_update()\n    {\n        long size = get_size();\n        T * Hy = apply(H,Y);\n        T * outer_2 = get_outer_product(Hy,Hy);\n        T inner_2 = -1.0 / (get_inner_product(Hy,Y));\n        T * outer_1 = get_outer_product(dX,dX);\n        T inner_1 = 1.0 / (get_inner_product(dX,Y));\n        for(long i=0;i<size*size;i++)\n        {\n          H[i] += outer_1[i] * inner_1 + outer_2[i] * inner_2;\n        }\n        delete [] outer_2;\n        delete [] outer_1;\n        delete [] Hy;\n    }\n\n    T * apply_M(T * A, T * B)\n    {\n        long size = get_size();\n        T * C = new T[size*size];\n        for(long i=0,k=0;i<size;i++)\n        {\n          for(long j=0;j<size;j++,k++)\n          {\n            C[k] = 0;\n            for(long t=0;t<size;t++)\n            {\n              C[k] += A[i*size+t]*B[t*size+j];\n            }\n          }\n        }\n        return C;\n    }\n\n    // BFGS\n    void BFGS_update()\n    {\n        long size = get_size();\n        T inner = 1.0 / (get_inner_product(Y,dX));\n        T * outer_xx = get_outer_product(dX,dX);\n        T * outer_xy = get_outer_product(dX,Y);\n        T * outer_yx = get_outer_product(Y,dX);\n        for(long i=0,k=0;i<size;i++)\n        {\n          for(long j=0;j<size;j++,k++)\n          {\n            if(i==j)\n            {\n              outer_xy[k] = 1-outer_xy[k]*inner;\n              outer_yx[k] = 1-outer_yx[k]*inner;\n            }\n            else\n            {\n              outer_xy[k] = -outer_xy[k]*inner;\n              outer_yx[k] = -outer_yx[k]*inner;\n            }\n            outer_xx[k] = outer_xx[k]*inner;\n          }\n        }\n        T * F = apply_M(outer_xy,H);\n        T * G = apply_M(F,outer_yx);\n        for(long i=0;i<size*size;i++)\n        {\n          H[i] = G[i] + outer_xx[i];\n        }\n        delete [] F;\n        delete [] G;\n        delete [] outer_xx;\n        delete [] outer_xy;\n        delete [] outer_yx;\n    }\n\n};\n\ntemplate<typename T>\nstruct training_info\n{\n\n    quasi_newton_info<T> * quasi_newton;\n\n    std::vector<long> n_nodes;\n    T **  activation_values;\n    T **  deltas;\n    long n_variables;\n    long n_labels;\n    long n_layers;\n    long n_elements;\n\n    T *** weights_neuron;\n    T **  weights_bias;\n    T *** partial_weights_neuron;\n    T **  partial_weights_bias;\n\n    T partial_error;\n    T smallest_index;\n\n    T epsilon;\n\n    int type;\n\n    training_info()\n    {\n\n    }\n\n    void init(T _alpha)\n    {\n        type = 0;\n        smallest_index = 0;\n        partial_error = 0;\n        activation_values  = new T*[n_nodes.size()];\n        for(long layer = 0;layer < n_nodes.size();layer++)\n        {\n            activation_values [layer] = new T[n_nodes[layer]];\n        }\n        deltas = new T*[n_nodes.size()];\n        for(long layer = 0;layer < n_nodes.size();layer++)\n        {\n            deltas[layer] = new T[n_nodes[layer]];\n        }\n        partial_weights_neuron = new T**[n_layers];\n        partial_weights_bias = new T*[n_layers];\n        for(long layer = 0;layer < n_layers;layer++)\n        {\n            partial_weights_neuron[layer] = new T*[n_nodes[layer+1]];\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n                partial_weights_neuron[layer][i] = new T[n_nodes[layer]];\n                for(long j=0;j<n_nodes[layer];j++)\n                {\n                    partial_weights_neuron[layer][i][j] = 0;\n                }\n            }\n            partial_weights_bias[layer] = new T[n_nodes[layer+1]];\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n                partial_weights_bias[layer][i] = 0;\n            }\n        }\n    }\n\n    void destroy()\n    {\n        for(long layer = 0;layer < n_nodes.size();layer++)\n        {\n            delete [] activation_values [layer];\n        }\n        delete [] activation_values;\n        for(long layer = 0;layer < n_nodes.size();layer++)\n        {\n            delete [] deltas [layer];\n        }\n        delete [] deltas;\n        for(long layer = 0;layer < n_layers;layer++)\n        {\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n                delete [] partial_weights_neuron[layer][i];\n            }\n            delete [] partial_weights_neuron[layer];\n        }\n        delete [] partial_weights_neuron;\n        for(long layer = 0;layer < n_layers;layer++)\n        {\n            delete [] partial_weights_bias[layer];\n        }\n        delete [] partial_weights_bias;\n    }\n\n    void update_gradient ()\n    {\n        for(long layer = 0,k = 0;layer < n_layers;layer++)\n        {\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n                for(long j=0;j<n_nodes[layer];j++,k++)\n                {\n                    quasi_newton->grad_tmp[k] += partial_weights_neuron[layer][i][j] / n_elements;\n                }\n            }\n            for(long i=0;i<n_nodes[layer+1];i++,k++)\n            {\n                quasi_newton->grad_tmp[k] += partial_weights_bias[layer][i] / n_elements;\n            }\n        }\n    }\n\n    void globalUpdate()\n    {\n        if(quasi_newton->quasi_newton_update)\n        {\n            for(long layer = 0,k = 0;layer < n_layers;layer++)\n            {\n                for(long i=0;i<n_nodes[layer+1];i++)\n                {\n                    for(long j=0;j<n_nodes[layer];j++,k++)\n                    {\n                        weights_neuron[layer][i][j] += quasi_newton->dX[k];\n                    }\n                }\n                for(long i=0;i<n_nodes[layer+1];i++,k++)\n                {\n                    weights_bias[layer][i] += quasi_newton->dX[k];\n                }\n            }\n        }\n        else\n        {\n            for(long layer = 0,k = 0;layer < n_layers;layer++)\n            {\n                for(long i=0;i<n_nodes[layer+1];i++)\n                {\n                    for(long j=0;j<n_nodes[layer];j++,k++)\n                    {\n                        weights_neuron[layer][i][j] += epsilon * quasi_newton->grad_tmp[k];\n                    }\n                }\n                for(long i=0;i<n_nodes[layer+1];i++,k++)\n                {\n                    weights_bias[layer][i] += epsilon * quasi_newton->grad_tmp[k];\n                }\n            }\n        }\n    }\n\n};\n\ntemplate<typename T>\nT min(T a,T b)\n{\n    return (a<b)?a:b;\n}\n\ntemplate<typename T>\nvoid training_worker(training_info<T> * g,std::vector<long> const & vrtx,T * variables,T * labels)\n{\n    \n    for(long n=0;n<vrtx.size();n++)\n    {\n\n        // initialize input activations\n        for(long i=0;i<g->n_nodes[0];i++)\n        {\n            g->activation_values[0][i] = variables[vrtx[n]*g->n_variables+i];\n            // HUUUGGGGEEEE  MARK !!!!!!!!!!!!!!!!!!\n            if(i==0)g->activation_values[0][i] = 0.5;\n        }\n        // forward propagation\n        for(long layer = 0; layer < g->n_layers; layer++)\n        {\n            for(long i=0;i<g->n_nodes[layer+1];i++)\n            {\n                T sum = g->weights_bias[layer][i];\n                for(long j=0;j<g->n_nodes[layer];j++)\n                {\n                    sum += g->activation_values[layer][j] * g->weights_neuron[layer][i][j];\n                }\n                g->activation_values[layer+1][i] = sigmoid(sum,g->type);\n                //std::cout << g->activation_values[layer+1][i] << '\\t';\n            }\n            //std::cout << std::endl;\n        }\n        long last_layer = g->n_nodes.size()-2;\n        // initialize observed labels\n        T max_err = 0;\n        T min_err = 1e12;\n        T tmp_err;\n        T min_partial_error = 0;\n        T ind = 0;\n        for(long i=0;i<g->n_nodes[last_layer];i++)\n        {\n            tmp_err = fabs(g->deltas[last_layer+1][i] = labels[vrtx[n]*g->n_labels+i] - g->activation_values[last_layer][i]);\n            if(tmp_err>max_err)\n            {\n                max_err = tmp_err;\n            }\n            if(tmp_err<min_err)\n            {\n                min_err = tmp_err;\n                ind = i;\n            }\n        }\n        // MARK !!!!!!!!!!!!!!!!!!\n        train_index = 0;\n        for(long i=0;i<g->n_nodes[last_layer];i++)\n        {\n            //g->partial_error += fabs(g->deltas[last_layer+1][i]);\n            //if(i==sample_index)\n            //if(fabs(g->deltas[last_layer+1][i]<min_partial_error))\n            //{\n            //    min_partial_error = fabs(g->deltas[last_layer+1][i]);\n            //    ind = i;\n            //}\n            g->deltas[last_layer+1][i] = 0;\n            if(i==train_index)\n            {\n                g->deltas[last_layer+1][i] = labels[vrtx[n]*g->n_labels+i] - g->activation_values[last_layer][i];\n                min_partial_error += fabs(g->deltas[last_layer+1][i]);\n            }\n            else\n            {\n                g->deltas[last_layer+1][i] = 0;//damp_weight*(labels[vrtx[n]*g->n_labels+i] - g->activation_values[last_layer][i]);\n                //min_partial_error += fabs(g->deltas[last_layer+1][i]);\n            }\n            //std::cout << g->deltas[last_layer+1][i] << '\\t';\n        }\n        g->partial_error += min_partial_error;\n        g->smallest_index += ind;\n        //std::cout << std::endl;\n        // back propagation\n        for(long layer = g->n_layers-1; layer >= 0; layer--)\n        {\n            // back propagate deltas\n            for(long i=0;i<g->n_nodes[layer+1];i++)\n            {\n                g->deltas[layer+1][i] = 0;\n                for(long j=0;j<g->n_nodes[layer+2];j++)\n                {\n                    if(layer+1==last_layer)\n                    {\n                        g->deltas[layer+1][i] += dsigmoid(g->activation_values[layer+1][i],g->type)*g->deltas[layer+2][j];\n                    }\n                    else\n                    {\n                        g->deltas[layer+1][i] += dsigmoid(g->activation_values[layer+1][i],g->type)*g->deltas[layer+2][j]*g->weights_neuron[layer+1][j][i];\n                    }\n                }\n                //std::cout << g->deltas[layer+1][i] << '\\t';\n            }\n            //std::cout << std::endl;\n            //std::cout << \"biases\" << std::endl;\n            // biases\n            for(long i=0;i<g->n_nodes[layer+1];i++)\n            {\n                g->partial_weights_bias[layer][i] += g->deltas[layer+1][i];\n                //std::cout << g->partial_weights_bias[layer][i] << '\\t';\n            }\n            //std::cout << std::endl;\n            //std::cout << \"neuron weights\" << std::endl;\n            // neuron weights\n            for(long i=0;i<g->n_nodes[layer+1];i++)\n            {\n                for(long j=0;j<g->n_nodes[layer];j++)\n                {\n                    g->partial_weights_neuron[layer][i][j] += g->activation_values[layer][j] * g->deltas[layer+1][i];\n                    //std::cout << g->partial_weights_neuron[layer][i][j] << '\\t';\n                }\n                //std::cout << std::endl;\n            }\n            //std::cout << std::endl;\n        }\n        //char ch;\n        //std::cin >> ch;\n    }\n\n}\n\nbool stop_training = false;\nbool continue_training = true;\n\nstd::vector<double> errs;\nstd::vector<double> test_errs;\n\ntemplate<typename T>\nstruct Perceptron\n{\n    quasi_newton_info<T> * quasi_newton;\n\n    T ierror;\n    T perror;\n\n    T *** weights_neuron;\n    T **  weights_bias;\n    T **  activation_values;\n    T **  activation_values1;\n    T **  activation_values2;\n    T **  activation_values3;\n    T **  deltas;\n\n    long n_inputs;\n    long n_outputs;\n    long n_layers;\n    std::vector<long> n_nodes;\n\n    T get_variable(int ind)\n    {\n        int I = 0;\n          for(int layer = 0;layer < n_layers;layer++)\n          {\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n              if(I==ind)return weights_bias[layer][i];\n              I++;\n            }\n          }\n          for(int layer = 0;layer < n_layers;layer++)\n          {\n            for(int i=0;i<n_nodes[layer+1];i++)\n            {\n                for(int j=0;j<n_nodes[layer];j++)\n                {\n                    if(I==ind)return weights_neuron[layer][i][j];\n                    I++;\n                }\n            }\n          }\n        return 0;\n    }\n\n    int get_num_variables()\n    {\n        int I = 0;\n          for(int layer = 0;layer < n_layers;layer++)\n          {\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n              I++;\n            }\n          }\n          for(int layer = 0;layer < n_layers;layer++)\n          {\n            for(int i=0;i<n_nodes[layer+1];i++)\n            {\n                for(int j=0;j<n_nodes[layer];j++)\n                {\n                    I++;\n                }\n            }\n          }\n        return I;\n    }\n\n    void dump_to_file(std::string filename,bool quiet=false)\n    {\n        if(!quiet)\n          std::cout << \"dump to file:\" << filename << std::endl;\n        ofstream myfile (filename.c_str());\n        if (myfile.is_open())\n        {\n          myfile << \"#n_nodes\" << std::endl;\n          myfile << n_nodes.size() << \" \";\n          for(int i=0;i<n_nodes.size();i++)\n          {\n            myfile << n_nodes[i] << \" \";\n          }\n          myfile << std::endl;\n          myfile << \"#bias\" << std::endl;\n          for(int layer = 0;layer < n_layers;layer++)\n          {\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n              myfile << (float)weights_bias[layer][i] << \" \";\n            }\n            std::cout << \" \";\n          }\n          myfile << std::endl;\n          myfile << \"#weights\" << std::endl;\n          for(int layer = 0;layer < n_layers;layer++)\n          {\n            for(int i=0;i<n_nodes[layer+1];i++)\n            {\n                for(int j=0;j<n_nodes[layer];j++)\n                {\n                    myfile << (float)weights_neuron[layer][i][j] << \" \";\n                }\n            }\n          }\n          myfile << std::endl;\n          myfile << \"#error\" << std::endl;\n          myfile << final_error << std::endl;\n          myfile.close();\n        }\n        else\n        {\n          cout << \"Unable to open file: \" << filename << std::endl;\n          exit(1);\n        }\n\n    }\n\n    void load_from_file(std::string filename,bool quiet=false)\n    {\n        if(!quiet)\n          std::cout << \"loading from file:\" << filename << std::endl;\n        ifstream myfile (filename.c_str());\n        if (myfile.is_open())\n        {\n          std::string line;\n          std::string tmp;\n          int stage = 0;\n          bool done = false;\n          while(!done&&getline(myfile,line))\n          {\n            if(line[0] == '#')continue;\n            switch(stage)\n            {\n              case 0: // get n_nodes\n              {\n                std::stringstream ss;\n                ss << line;\n                int n_nodes_size;\n                ss >> tmp;\n                n_nodes_size = atoi(tmp.c_str());\n                if(n_nodes_size != n_nodes.size())\n                {\n                  std::cout << \"network structure is not consistent.\" << std::endl;\n                  exit(1);\n                }\n                for(int i=0;i<n_nodes_size;i++)\n                {\n                  int layer_size;\n                  ss >> tmp;\n                  layer_size = atoi(tmp.c_str());\n                  if(layer_size != n_nodes[i])\n                  {\n                    std::cout << \"network structure is not consistent.\" << std::endl;\n                    exit(1);\n                  }\n                }\n                stage = 1;\n                break;\n              }\n              case 1: // get bias\n              {\n                std::stringstream ss;\n                ss << line;\n                for(int layer = 0;layer < n_layers;layer++)\n                {\n                  for(long i=0;i<n_nodes[layer+1];i++)\n                  {\n                    ss >> tmp;\n                    weights_bias[layer][i] = atof(tmp.c_str());\n                  }\n                }\n                stage = 2;\n                break;\n              }\n              case 2: // get weights\n              {\n                std::stringstream ss;\n                ss << line;\n                for(int layer = 0;layer < n_layers;layer++)\n                {\n                  for(int i=0;i<n_nodes[layer+1];i++)\n                  {\n                      for(int j=0;j<n_nodes[layer];j++)\n                      {\n                          ss >> tmp;\n                          weights_neuron[layer][i][j] = atof(tmp.c_str());\n                      }\n                  }\n                }\n                stage = 3;\n                break;\n              }\n              case 3: // final error\n              {\n                std::stringstream ss;\n                ss << line;\n                ss >> tmp;\n                final_error = atof(tmp.c_str());\n                stage = 4;\n                break;\n              }\n              default:done = true;break;\n            }\n          }\n          myfile.close();\n        }\n        else cout << \"Unable to open file: \" << filename << std::endl;\n\n    }\n\n    T epsilon;\n    T alpha;\n    int sigmoid_type;\n\n    // std::vector<long> nodes;\n    // nodes.push_back(2); // inputs\n    // nodes.push_back(3); // hidden layer\n    // nodes.push_back(1); // output layer\n    // nodes.push_back(1); // outputs\n    Perceptron(std::vector<long> p_nodes)\n    {\n\n        quasi_newton = NULL;\n\n        sigmoid_type = 0;\n        alpha = 0.1;\n\n        ierror = 1e10;\n        perror = 1e10;\n\n        n_nodes = p_nodes;\n        n_inputs = n_nodes[0];\n        n_outputs = n_nodes[n_nodes.size()-1];\n        n_layers = n_nodes.size()-2; // first and last numbers and output and input dimensions, so we have n-2 layers\n\n        weights_neuron = new T**[n_layers];\n        weights_bias = new T*[n_layers];\n        activation_values  = new T*[n_nodes.size()];\n        activation_values1 = new T*[n_nodes.size()];\n        activation_values2 = new T*[n_nodes.size()];\n        activation_values3 = new T*[n_nodes.size()];\n        deltas = new T*[n_nodes.size()];\n        \n        for(long layer = 0;layer < n_nodes.size();layer++)\n        {\n            activation_values [layer] = new T[n_nodes[layer]];\n            activation_values1[layer] = new T[n_nodes[layer]];\n            activation_values2[layer] = new T[n_nodes[layer]];\n            activation_values3[layer] = new T[n_nodes[layer]];\n            deltas[layer] = new T[n_nodes[layer]];\n        }\n\n        for(long layer = 0;layer < n_layers;layer++)\n        {\n            weights_neuron[layer] = new T*[n_nodes[layer+1]];\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n                weights_neuron[layer][i] = new T[n_nodes[layer]];\n                for(long j=0;j<n_nodes[layer];j++)\n                {\n                    weights_neuron[layer][i][j] = 1.0 * (-1.0 + 2.0 * ((rand()%10000)/10000.0));\n                }\n            }\n            weights_bias[layer] = new T[n_nodes[layer+1]];\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n                weights_bias[layer][i] = 1.0 * (-1.0 + 2.0 * ((rand()%10000)/10000.0));\n            }\n        }\n\n        //weights_neuron[0][0][0] = .1;        weights_neuron[0][0][1] = .2;\n        //weights_neuron[0][1][0] = .3;        weights_neuron[0][1][1] = .4;\n        //weights_neuron[0][2][0] = .5;        weights_neuron[0][2][1] = .6;\n\n        //weights_bias[0][0] = .1;\n        //weights_bias[0][1] = .2;\n        //weights_bias[0][2] = .3;\n\n        //weights_neuron[1][0][0] = .6;        weights_neuron[1][0][1] = .7;      weights_neuron[1][0][2] = .8;\n\n        //weights_bias[1][0] = .5;\n\n    }\n\n    T * model(long n_elements,long n_labels,T * variables)\n    {\n        T * labels = new T[n_labels];\n        // initialize input activations\n        for(long i=0;i<n_nodes[0];i++)\n        {\n            activation_values1[0][i] = variables[i];\n        }\n        // forward propagation\n        for(long layer = 0; layer < n_layers; layer++)\n        {\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n                T sum = weights_bias[layer][i];\n                for(long j=0;j<n_nodes[layer];j++)\n                {\n                    sum += activation_values1[layer][j] * weights_neuron[layer][i][j];\n                }\n                activation_values1[layer+1][i] = sigmoid(sum,0);// <- zero is important here!!!!\n            }\n        }\n        long last_layer = n_nodes.size()-2;\n        for(long i=0;i<n_labels;i++)\n        {\n            labels[i] = activation_values1[last_layer][i];\n        }\n        return labels;\n    }\n\n    T * model2(long n_elements,long n_labels,T * variables)\n    {\n        T * labels = new T[n_labels];\n        // initialize input activations\n        for(long i=0;i<n_nodes[0];i++)\n        {\n            activation_values3[0][i] = variables[i];\n        }\n        // forward propagation\n        for(long layer = 0; layer < n_layers; layer++)\n        {\n            for(long i=0;i<n_nodes[layer+1];i++)\n            {\n                T sum = weights_bias[layer][i];\n                for(long j=0;j<n_nodes[layer];j++)\n                {\n                    sum += activation_values3[layer][j] * weights_neuron[layer][i][j];\n                }\n                activation_values3[layer+1][i] = sigmoid(sum,0);// <- zero is important here!!!!\n            }\n        }\n        long last_layer = n_nodes.size()-2;\n        for(long i=0;i<n_labels;i++)\n        {\n            labels[i] = activation_values3[last_layer][i];\n        }\n        return labels;\n    }\n\n    T verify( long n_test_elements\n            , long n_variables\n            , T * test_variables\n            , long n_labels\n            , T * test_labels\n            )\n    {\n        T err = 0;\n\n        T * labels = new T[n_labels];\n\n        for(int e=0;e<n_test_elements;e++)\n        {\n\n          // initialize input activations\n          for(long i=0;i<n_variables;i++)\n          {\n              activation_values2[0][i] = test_variables[e*n_variables+i];\n          }\n          // forward propagation\n          for(long layer = 0; layer < n_layers; layer++)\n          {\n              for(long i=0;i<n_nodes[layer+1];i++)\n              {\n                  T sum = weights_bias[layer][i];\n                  for(long j=0;j<n_nodes[layer];j++)\n                  {\n                      sum += activation_values2[layer][j] * weights_neuron[layer][i][j];\n                  }\n                  activation_values2[layer+1][i] = sigmoid(sum,0);// <- zero is important here!!!!\n              }\n          }\n          long last_layer = n_nodes.size()-2;\n          for(long i=0;i<n_labels;i++)\n          {\n            if(i==sample_index)\n            {\n              err += fabs(test_labels[e*n_labels+i] - activation_values2[last_layer][i]);\n            }\n          }\n\n        }\n\n        delete [] labels;\n\n        return err/n_test_elements;\n\n    }\n\n    int get_sigmoid()\n    {\n        return sigmoid_type;\n    }\n\n    void train ( int p_sigmoid_type\n               , T p_epsilon\n               , long n_iterations\n               , long n_elements\n               , long n_test_elements\n               , long n_variables\n               , T * variables\n               , T * test_variables\n               , long n_labels\n               , T * labels\n               , T * test_labels\n               , quasi_newton_info<T> * q_newton = NULL\n               )\n    {\n        sigmoid_type = p_sigmoid_type;\n        epsilon = p_epsilon;\n        if(n_variables != n_nodes[0]){std::cout << \"error 789437248932748293\" << std::endl;exit(0);}\n        if(q_newton == NULL)\n        {\n            quasi_newton = new quasi_newton_info<T>();\n            quasi_newton->alpha = alpha;\n            quasi_newton->n_nodes = n_nodes;\n            quasi_newton->n_layers = n_layers;\n            quasi_newton->weights_neuron = weights_neuron;\n            quasi_newton->weights_bias = weights_bias;\n            quasi_newton->init_QuasiNewton();\n            quasi_newton->quasi_newton_update = false;\n        }\n        else\n        {\n            quasi_newton = q_newton;\n        }\n        ierror = 1e10;\n        bool init = true;\n        perror = 1e10;\n        T min_final_error = 1e10;\n        for(long iter = 0; iter < n_iterations || continue_training; iter++)\n        {\n            T error = 0;\n            T index = 0;\n\n            //////////////////////////////////////////////////////////////////////////////////\n            //                                                                              //\n            //          Multi-threaded block                                                //\n            //                                                                              //\n            //////////////////////////////////////////////////////////////////////////////////\n            std::vector<boost::thread*> threads;\n            std::vector<std::vector<long> > vrtx(boost::thread::hardware_concurrency());\n            std::vector<training_info<T>*> g;\n            for(long i=0;i<n_elements;i++)\n            {\n              vrtx[i%vrtx.size()].push_back(i);\n            }\n            for(long i=0;i<vrtx.size();i++)\n            {\n              g.push_back(new training_info<T>());\n            }\n            quasi_newton->init_gradient();\n            for(long thread=0;thread<vrtx.size();thread++)\n            {\n              g[thread]->quasi_newton = quasi_newton;\n              g[thread]->n_nodes = n_nodes;\n              g[thread]->n_elements = n_elements;\n              g[thread]->n_variables = n_variables;\n              g[thread]->n_labels = n_labels;\n              g[thread]->n_layers = n_layers;\n              g[thread]->weights_neuron = weights_neuron;\n              g[thread]->weights_bias = weights_bias;\n              g[thread]->epsilon = epsilon;\n              g[thread]->type = get_sigmoid();\n\n              g[thread]->init(alpha);\n              threads.push_back(new boost::thread(training_worker<T>,g[thread],vrtx[thread],variables,labels));\n            }\n            for(long thread=0;thread<vrtx.size();thread++)\n            {\n              threads[thread]->join();\n              g[thread]->update_gradient();\n              delete threads[thread];\n            }\n            quasi_newton->update_QuasiNewton();\n            quasi_newton->SR1_update();\n            for(long thread=0;thread<vrtx.size();thread++)\n            {\n              g[thread]->globalUpdate();\n              error += g[thread]->partial_error;\n              index += g[thread]->smallest_index;\n              g[thread]->destroy();\n              delete g[thread];\n            }\n            threads.clear();\n            vrtx.clear();\n            g.clear();\n            final_error = verify(n_test_elements,n_variables,test_variables,n_labels,test_labels);\n            static int cnt1 = 0;\n            if(cnt1%100==0)\n            std::cout << iter << \"\\ttrain index=\" << train_index << \"\\tdamp weight=\" << damp_weight << \"\\tquasi_newton_update=\" << quasi_newton->quasi_newton_update << \"\\ttype=\" << sigmoid_type << \"\\tepsilon=\" << epsilon << \"\\talpha=\" << alpha << '\\t' << \"error=\" << error << \"\\tdiff=\" << (error-perror) << \"\\t\\%error=\" << 100*error/n_elements << \"\\ttest\\%error=\" << 100*final_error << \"\\tindex=\" << index/n_elements << std::endl;\n            cnt1++;\n            perror = error;\n            errs.push_back(error/n_elements);\n            test_errs.push_back(final_error);\n            if(error/n_elements < 0.1)\n            {\n                train_index = (train_index+1)%n_labels;//round(index/n_elements);\n            }\n            //if(train_index<0||train_index>=n_elements-1)\n            //{\n            //    train_index = 0;\n            //}\n            if(init)\n            {\n                ierror = error;\n                init = false;\n            }\n\n            if((iter+1)%100000==0||stop_training)\n            {\n                std::stringstream ss;\n                ss << \"snapshots/network.ann.\" << ((int)(100*10000*final_error)/10000.0f);\n                dump_to_file(ss.str());\n            }\n\n            if(stop_training){stop_training=false;break;}\n\n            // MARK!!!\n            //if(error/n_elements < 0.05 && iter > n_iterations)\n            //{\n            //  std::stringstream ss;\n            //  ss << \"snapshots/network.ann.\" << ((int)(100*10000*final_error)/10000.0f);\n            //  dump_to_file(ss.str());\n            //  dump_to_file(\"network.ann\");\n            //  exit(1);\n            //}\n\n            //char ch;\n            //std::cin >> ch;\n\n        }\n    }\n\n    T final_error;\n\n};\n\n\nvoid clear() {\n  // CSI[2J clears screen, CSI[H moves the cursor to top-left corner\n  std::cout << \"\\x1B[2J\\x1B[H\";\n}\n\ndouble norm(double * dat,long size)\n{\n  double ret = 0;\n  for(long i=0;i<size;i++)\n  {\n    ret += dat[i]*dat[i];\n  }\n  return sqrt(ret);\n}\n\nvoid zero(double * dat,long size)\n{\n  for(long i=0;i<size;i++)\n  {\n    dat[i] = 0;\n  }\n}\n\nvoid constant(double * dat,double val,long size)\n{\n  for(long i=0;i<size;i++)\n  {\n    dat[i] = (-1+2*((rand()%10000)/10000.0f))*val;\n  }\n}\n\nvoid add(double * A, double * dA, double epsilon, long size)\n{\n  for(long i=0;i<size;i++)\n  {\n    A[i] += epsilon * dA[i];\n  }\n}\n\nstruct gradient_info\n{\n  long n;\n  long v;\n  long h;\n  double * vis0;\n  double * hid0;\n  double * vis;\n  double * hid;\n  double * dW;\n  double * dc;\n  double * db;\n  double partial_err;\n  double * partial_dW;\n  double * partial_dc;\n  double * partial_db;\n  void init()\n  {\n    partial_err = 0;\n    partial_dW = new double[h*v];\n    for(int i=0;i<h*v;i++)partial_dW[i]=0;\n    partial_dc = new double[h];\n    for(int i=0;i<h;i++)partial_dc[i]=0;\n    partial_db = new double[v];\n    for(int i=0;i<v;i++)partial_db[i]=0;\n  }\n  void destroy()\n  {\n    delete [] partial_dW;\n    delete [] partial_dc;\n    delete [] partial_db;\n  }\n  void globalUpdate()\n  {\n    for(int i=0;i<h*v;i++)\n        dW[i] += partial_dW[i];\n    for(int i=0;i<h;i++)\n        dc[i] += partial_dc[i];\n    for(int i=0;i<v;i++)\n        db[i] += partial_db[i];\n  }\n};\n\nvoid gradient_worker(gradient_info * g,std::vector<long> const & vrtx)\n{\n  double factor = 1.0f / g->n;\n  double factorv= 1.0f / (g->v*g->v);\n  for(long t=0;t<vrtx.size();t++)\n  {\n    long k = vrtx[t];\n    for(long i=0;i<g->v;i++)\n    {\n      for(long j=0;j<g->h;j++)\n      {\n        g->partial_dW[i*g->h+j] -= factor * (g->vis0[k*g->v+i]*g->hid0[k*g->h+j] - g->vis[k*g->v+i]*g->hid[k*g->h+j]);\n      }\n    }\n\n    for(long j=0;j<g->h;j++)\n    {\n      g->partial_dc[j] -= factor * (g->hid0[k*g->h+j]*g->hid0[k*g->h+j] - g->hid[k*g->h+j]*g->hid[k*g->h+j]);\n    }\n\n    for(long i=0;i<g->v;i++)\n    {\n      g->partial_db[i] -= factor * (g->vis0[k*g->v+i]*g->vis0[k*g->v+i] - g->vis[k*g->v+i]*g->vis[k*g->v+i]);\n    }\n\n    for(long i=0;i<g->v;i++)\n    {\n      g->partial_err += factorv * (g->vis0[k*g->v+i]-g->vis[k*g->v+i])*(g->vis0[k*g->v+i]-g->vis[k*g->v+i]);\n    }\n  }\n}\n\nvoid vis2hid_worker(const double * X,double * H,long h,long v,double * c,double * W,std::vector<long> const & vrtx)\n{\n  for(long t=0;t<vrtx.size();t++)\n  {\n    long k = vrtx[t];\n    for(long j=0;j<h;j++)\n    {\n      H[k*h+j] = c[j]; \n      for(long i=0;i<v;i++)\n      {\n        H[k*h+j] += W[i*h+j] * X[k*v+i];\n      }\n      H[k*h+j] = 1.0f/(1.0f + exp(-H[k*h+j]));\n    }\n  }\n}\n\nvoid hid2vis_worker(const double * H,double * V,long h,long v,double * b,double * W,std::vector<long> const & vrtx)\n{\n  for(long t=0;t<vrtx.size();t++)\n  {\n    long k = vrtx[t];\n    for(long i=0;i<v;i++)\n    {\n      V[k*v+i] = b[i]; \n      for(long j=0;j<h;j++)\n      {\n        V[k*v+i] += W[i*h+j] * H[k*h+j];\n      }\n      V[k*v+i] = 1.0f/(1.0f + exp(-V[k*v+i]));\n    }\n  }\n}\n\nstruct RBM\n{\n  long h; // number hidden elements\n  long v; // number visible elements\n  long n; // number of samples\n  double * c; // bias term for hidden state, R^h\n  double * b; // bias term for visible state, R^v\n  double * W; // weight matrix R^h*v\n  double * X; // input data, binary [0,1], v*n\n\n  double * vis0;\n  double * hid0;\n  double * vis;\n  double * hid;\n  double * dW;\n  double * dc;\n  double * db;\n\n  RBM(long _v,long _h,double * _W,double * _b,double * _c,long _n,double * _X)\n  {\n    //for(long k=0;k<100;k++)\n    //  std::cout << _X[k] << \"\\t\";\n    //std::cout << \"\\n\";\n    X = _X;\n    h = _h;\n    v = _v;\n    n = _n;\n    c = _c;\n    b = _b;\n    W = _W;\n\n    vis0 = NULL;\n    hid0 = NULL;\n    vis = NULL;\n    hid = NULL;\n    dW = NULL;\n    dc = NULL;\n    db = NULL;\n  }\n  RBM(long _v,long _h,long _n,double* _X)\n  {\n    //for(long k=0;k<100;k++)\n    //  std::cout << _X[k] << \"\\t\";\n    //std::cout << \"\\n\";\n    X = _X;\n    h = _h;\n    v = _v;\n    n = _n;\n    c = new double[h];\n    b = new double[v];\n    W = new double[h*v];\n    constant(c,0.5f,h);\n    constant(b,0.5f,v);\n    constant(W,0.5f,v*h);\n\n    vis0 = NULL;\n    hid0 = NULL;\n    vis = NULL;\n    hid = NULL;\n    dW = NULL;\n    dc = NULL;\n    db = NULL;\n  }\n\n  void init(int offset)\n  {\n    boost::posix_time::ptime time_start(boost::posix_time::microsec_clock::local_time());\n    if(vis0==NULL)vis0 = new double[n*v];\n    if(hid0==NULL)hid0 = new double[n*h];\n    if(vis==NULL)vis = new double[n*v];\n    if(hid==NULL)hid = new double[n*h];\n    if(dW==NULL)dW = new double[h*v];\n    if(dc==NULL)dc = new double[h];\n    if(db==NULL)db = new double[v];\n\n    //std::cout << \"n*v=\" << n*v << std::endl;\n    //std::cout << \"offset=\" << offset << std::endl;\n    for(long i=0,size=n*v;i<size;i++)\n    {\n      vis0[i] = X[i+offset];\n    }\n\n    vis2hid(vis0,hid0);\n    boost::posix_time::ptime time_end(boost::posix_time::microsec_clock::local_time());\n    boost::posix_time::time_duration duration(time_end - time_start);\n    //std::cout << \"init timing:\" << duration << '\\n';\n  }\n\n  void cd(long nGS,double epsilon,int offset=0,bool bottleneck=false)\n  {\n    boost::posix_time::ptime time_0(boost::posix_time::microsec_clock::local_time());\n    //std::cout << \"cd\" << std::endl;\n\n    // CD Contrastive divergence (Hlongon's CD(k))\n    //   [dW, db, dc, act] = cd(self, X) returns the gradients of\n    //   the weihgts, visible and hidden biases using Hlongon's\n    //   approximated CD. The sum of the average hidden units\n    //   activity is returned in act as well.\n\n    for(long i=0;i<n*h;i++)\n    {\n      hid[i] = hid0[i];\n    }\n    boost::posix_time::ptime time_1(boost::posix_time::microsec_clock::local_time());\n    boost::posix_time::time_duration duration10(time_1 - time_0);\n    //std::cout << \"cd timing 1:\" << duration10 << '\\n';\n\n    for (long iter = 1;iter<=nGS;iter++)\n    {\n      //std::cout << \"iter=\" << iter << std::endl;\n      // sampling\n      hid2vis(hid,vis);\n      vis2hid(vis,hid);\n\n// Preview stuff\n#if 0\n      long off = dat_offset%(n);\n      long offv = off*v;\n      long offh = off*h;\n      long off_preview = off*(3*WIN*WIN+10);\n      for(long x=0,k=0;x<WIN;x++)\n      {\n        for(long y=0;y<WIN;y++,k++)\n        {\n          vis_preview[k] = vis[offv+k];\n          vis_previewG[k] = vis[offv+k+WIN*WIN];\n          vis_previewB[k] = vis[offv+k+2*WIN*WIN];\n        }\n      }\n      for(long x=0,k=0;x<WIN;x++)\n      {\n        for(long y=0;y<WIN;y++,k++)\n        {\n          vis1_preview[k] = orig_arr[offset+off_preview+k];\n          vis1_previewG[k] = orig_arr[offset+off_preview+k+WIN*WIN];\n          vis1_previewB[k] = orig_arr[offset+off_preview+k+2*WIN*WIN];\n        }\n      }\n      for(long x=0,k=0;x<WIN;x++)\n      {\n        for(long y=0;y<WIN;y++,k++)\n        {\n          vis0_preview[k] = vis0[offv+k];\n          vis0_previewG[k] = vis0[offv+k+WIN*WIN];\n          vis0_previewB[k] = vis0[offv+k+2*WIN*WIN];\n        }\n      }\n#endif\n\n    }\n    boost::posix_time::ptime time_2(boost::posix_time::microsec_clock::local_time());\n    boost::posix_time::time_duration duration21(time_2 - time_1);\n    //std::cout << \"cd timing 2:\" << duration21 << '\\n';\n  \n    zero(dW,v*h);\n    zero(dc,h);\n    zero(db,v);\n    boost::posix_time::ptime time_3(boost::posix_time::microsec_clock::local_time());\n    boost::posix_time::time_duration duration32(time_3 - time_2);\n    //std::cout << \"cd timing 3:\" << duration32 << '\\n';\n    double * err = new double(0);\n    gradient_update(n,vis0,hid0,vis,hid,dW,dc,db,err);\n    boost::posix_time::ptime time_4(boost::posix_time::microsec_clock::local_time());\n    boost::posix_time::time_duration duration43(time_4 - time_3);\n    //std::cout << \"cd timing 4:\" << duration43 << '\\n';\n    *err = sqrt(*err);\n    for(int t=2;t<3&&t<errs.size();t++)\n      *err += (errs[errs.size()+1-t]-*err)/t;\n    errs.push_back(*err);\n    test_errs.push_back(*err);\n    static int cnt2 = 0;\n    if(cnt2%100==0)\n    std::cout << \"rbm error=\" << *err << std::endl;\n    cnt2++;\n    boost::posix_time::ptime time_5(boost::posix_time::microsec_clock::local_time());\n    boost::posix_time::time_duration duration54(time_5 - time_4);\n    //std::cout << \"cd timing 5:\" << duration54 << '\\n';\n    //std::cout << \"epsilon = \" << epsilon << std::endl;\n    add(W,dW,-epsilon,v*h);\n    add(c,dc,-epsilon,h);\n    add(b,db,-epsilon,v);\n\n    //std::cout << \"dW norm = \" << norm(dW,v*h) << std::endl;\n    //std::cout << \"dc norm = \" << norm(dc,h) << std::endl;\n    //std::cout << \"db norm = \" << norm(db,v) << std::endl;\n    //std::cout << \"W norm = \" << norm(W,v*h) << std::endl;\n    //std::cout << \"c norm = \" << norm(c,h) << std::endl;\n    //std::cout << \"b norm = \" << norm(b,v) << std::endl;\n    //std::cout << \"err = \" << *err << std::endl;\n    delete err;\n\n    boost::posix_time::ptime time_6(boost::posix_time::microsec_clock::local_time());\n    boost::posix_time::time_duration duration65(time_6 - time_5);\n    //std::cout << \"cd timing 6:\" << duration65 << '\\n';\n    //char ch;\n    //std::cin >> ch;\n  }\n\n  void sigmoid(double * p,double * X,long n)\n  {\n    for(long i=0;i<n;i++)\n    {\n      p[i] = 1.0f/(1.0f + exp(-X[i]));\n    }\n  }\n\n  void vis2hid_simple(const double * X,double * H)\n  {\n    {\n      for(long j=0;j<h;j++)\n      {\n        H[j] = c[j]; \n        for(long i=0;i<v;i++)\n        {\n          H[j] += W[i*h+j] * X[i];\n        }\n        H[j] = 1.0f/(1.0f + exp(-H[j]));\n      }\n    }\n  }\n\n  void hid2vis_simple(const double * H,double * V)\n  {\n    {\n      for(long i=0;i<v;i++)\n      {\n        V[i] = b[i]; \n        for(long j=0;j<h;j++)\n        {\n          V[i] += W[i*h+j] * H[j];\n        }\n        V[i] = 1.0f/(1.0f + exp(-V[i]));\n      }\n    }\n  }\n\n  void vis2hid(const double * X,double * H)\n  {\n    std::vector<boost::thread*> threads;\n    std::vector<std::vector<long> > vrtx(boost::thread::hardware_concurrency());\n    for(long i=0;i<n;i++)\n    {\n      vrtx[i%vrtx.size()].push_back(i);\n    }\n    for(long thread=0;thread<vrtx.size();thread++)\n    {\n      threads.push_back(new boost::thread(vis2hid_worker,X,H,h,v,c,W,vrtx[thread]));\n    }\n    for(long thread=0;thread<vrtx.size();thread++)\n    {\n      threads[thread]->join();\n      delete threads[thread];\n    }\n    threads.clear();\n    vrtx.clear();\n  }\n\n  void gradient_update(long n,double * vis0,double * hid0,double * vis,double * hid,double * dW,double * dc,double * db,double * err)\n  {\n    boost::posix_time::ptime time_0(boost::posix_time::microsec_clock::local_time());\n\n    std::vector<boost::thread*> threads;\n    std::vector<std::vector<long> > vrtx(boost::thread::hardware_concurrency());\n    std::vector<gradient_info*> g;\n\n    boost::posix_time::ptime time_1(boost::posix_time::microsec_clock::local_time());\n    boost::posix_time::time_duration duration10(time_1 - time_0);\n    //std::cout << \"gradient update timing 1:\" << duration10 << '\\n';\n\n    for(long i=0;i<n;i++)\n    {\n      vrtx[i%vrtx.size()].push_back(i);\n    }\n    boost::posix_time::ptime time_2(boost::posix_time::microsec_clock::local_time());\n    boost::posix_time::time_duration duration21(time_2 - time_1);\n    //std::cout << \"gradient update timing 2:\" << duration21 << '\\n';\n    for(long i=0;i<vrtx.size();i++)\n    {\n      g.push_back(new gradient_info());\n    }\n    boost::posix_time::ptime time_3(boost::posix_time::microsec_clock::local_time());\n    boost::posix_time::time_duration duration32(time_3 - time_2);\n    //std::cout << \"gradient update timing 3:\" << duration32 << '\\n';\n    for(long thread=0;thread<vrtx.size();thread++)\n    {\n      g[thread]->n = n;\n      g[thread]->v = v;\n      g[thread]->h = h;\n      g[thread]->vis0 = vis0;\n      g[thread]->hid0 = hid0;\n      g[thread]->vis = vis;\n      g[thread]->hid = hid;\n      g[thread]->dW = dW;\n      g[thread]->dc = dc;\n      g[thread]->db = db;\n      g[thread]->init();\n      threads.push_back(new boost::thread(gradient_worker,g[thread],vrtx[thread]));\n    }\n    boost::posix_time::ptime time_4(boost::posix_time::microsec_clock::local_time());\n    boost::posix_time::time_duration duration43(time_4 - time_3);\n    //std::cout << \"gradient update timing 4:\" << duration43 << '\\n';\n    for(long thread=0;thread<vrtx.size();thread++)\n    {\n      threads[thread]->join();\n      delete threads[thread];\n      g[thread]->globalUpdate();\n      *err += g[thread]->partial_err;\n      g[thread]->destroy();\n      delete g[thread];\n    }\n    boost::posix_time::ptime time_5(boost::posix_time::microsec_clock::local_time());\n    boost::posix_time::time_duration duration54(time_5 - time_4);\n    //std::cout << \"gradient update timing 5:\" << duration54 << '\\n';\n    threads.clear();\n    vrtx.clear();\n    g.clear();\n  }\n  \n  void hid2vis(const double * H,double * V)\n  {\n    std::vector<boost::thread*> threads;\n    std::vector<std::vector<long> > vrtx(boost::thread::hardware_concurrency());\n    for(long i=0;i<n;i++)\n    {\n      vrtx[i%vrtx.size()].push_back(i);\n    }\n    for(long thread=0;thread<vrtx.size();thread++)\n    {\n      threads.push_back(new boost::thread(hid2vis_worker,H,V,h,v,b,W,vrtx[thread]));\n    }\n    for(long thread=0;thread<vrtx.size();thread++)\n    {\n      threads[thread]->join();\n      delete threads[thread];\n    }\n    threads.clear();\n    vrtx.clear();\n  }\n\n};\n\nstruct DataUnit\n{\n  DataUnit *   hidden;\n  DataUnit *  visible;\n  DataUnit * visible0;\n  long h,v;\n  double * W;\n  double * b;\n  double * c;\n  RBM * rbm;\n  long num_iters;\n  long batch_iter;\n  DataUnit(long _v,long _h,long _num_iters = 100,long _batch_iter = 1)\n  {\n    num_iters = _num_iters;\n    batch_iter = _batch_iter;\n    v = _v;\n    h = _h;\n    W = new double[v*h];\n    b = new double[v];\n    c = new double[h];\n    constant(c,0.5f,h);\n    constant(b,0.5f,v);\n    constant(W,0.5f,v*h);\n      hidden = NULL;\n     visible = NULL;\n    visible0 = NULL;\n  }\n\n  void train(double * dat, long n, long total_n,int n_cd,double epsilon,long n_var)\n  {\n    // RBM(long _v,long _h,double * _W,double * _b,double * _c,long _n,double * _X)\n    rbm = new RBM(v,h,W,b,c,n,dat);\n    for(long i=0;i<num_iters;i++)\n    {\n      //std::cout << \"DataUnit::train i=\" << i << std::endl;\n      long offset = (rand()%(total_n-n));\n      for(long k=0;k<batch_iter;k++)\n      {\n        rbm->init(offset);\n        //std::cout << \"prog:\" << 100*(double)k/batch_iter << \"%\" << std::endl;\n        rbm->cd(n_cd,epsilon,offset*n_var);\n      }\n    }\n    //char ch;\n    //std::cin >> ch;\n  }\n\n  void transform(double* X,double* Y)\n  {\n    rbm->vis2hid(X,Y);\n  }\n\n  void initialize_weights(DataUnit* d)\n  {\n    if(v==d->h&&h==d->v)\n    {\n      for(int i=0;i<v;i++)\n      {\n        for(int j=0;j<h;j++)\n        {\n          W[i*h+j] = d->W[j*d->h+i];\n        }\n      }\n    }\n  }\n\n  void initialize_weights(DataUnit* d1,DataUnit* d2)\n  {\n    if(v==d1->h+d2->h&&d1->v==h&&d2->v==h)\n    {\n      std::cout << \"initialize bottleneck\" << std::endl;\n      //char ch;\n      //std::cin >> ch;\n      int j=0;\n      for(int k=0;j<d1->h;j++,k++)\n      {\n        for(int i=0;i<d1->v;i++)\n        {\n          W[i*h+j] = d1->W[k*d1->h+i];\n        }\n      }\n      for(int k=0;j<d1->h+d2->h;j++,k++)\n      {\n        for(int i=0;i<d2->v;i++)\n        {\n          W[i*h+j] = d2->W[k*d2->h+i];\n        }\n      }\n    }\n  }\n\n};\n\n// Multi Layer RBM\n//\n//  Auto-encoder\n//\n//          [***]\n//         /     \\\n//     [*****] [*****]\n//       /         \\\n// [********]   [********]\n//   inputs      outputs\n//\nstruct mRBM\n{\n  long in_samp;\n  long out_samp;\n  bool model_ready;\n  std::vector<DataUnit*>  input_branch;\n  std::vector<DataUnit*> output_branch;\n  DataUnit* bottle_neck;\n  void addInputDatUnit(long v,long h)\n  {\n    DataUnit * unit = new DataUnit(v,h);\n    input_branch.push_back(unit);\n  }\n  void addOutputDatUnit(long v,long h)\n  {\n    output_branch.push_back(new DataUnit(v,h));\n  }\n  void addBottleNeckDatUnit(long v,long h)\n  {\n    bottle_neck = new DataUnit(v,h);\n  }\n  void construct(std::vector<long> input_num,std::vector<long> output_num,long bottle_neck_num)\n  {\n    for(long i=0;i+1<input_num.size();i++)\n    {\n      input_branch.push_back(new DataUnit(input_num[i],input_num[i+1]));\n    }\n    for(long i=0;i+1<output_num.size();i++)\n    {\n      output_branch.push_back(new DataUnit(output_num[i],output_num[i+1]));\n    }\n    bottle_neck = new DataUnit(input_num[input_num.size()-1]+output_num[output_num.size()-1],bottle_neck_num);\n  }\n  mRBM(long _in_samp,long _out_samp)\n  {\n    in_samp = _in_samp;\n    out_samp = _out_samp;\n    model_ready = false;\n    bottle_neck = NULL;\n  }\n  void copy(double * X,double * Y,long num)\n  {\n    for(long i=0;i<num;i++)\n    {\n      Y[i] = X[i];\n    }\n  }\n  void model_simple(long sample,double * in,double * out)\n  {\n    double * X = NULL;\n    double * Y = NULL;\n    X = new double[input_branch[0]->v];\n    for(long i=0;i<input_branch[0]->v;i++)\n    {\n      X[i] = in[sample*input_branch[0]->v+i];\n    }\n    for(long i=0;i<input_branch.size();i++)\n    {\n      Y = new double[input_branch[i]->h];\n      input_branch[i]->rbm->vis2hid_simple(X,Y);\n      delete [] X;\n      X = NULL;\n      X = new double[input_branch[i]->h];\n      copy(Y,X,input_branch[i]->h);\n      delete [] Y;\n      Y = NULL;\n    }\n    double * X_bottleneck = NULL;\n    X_bottleneck = new double[bottle_neck->h];\n    for(long i=0;i<input_branch[input_branch.size()-1]->h;i++)\n    {\n      X_bottleneck[i] = X[i];\n    }\n    for(long i=input_branch[input_branch.size()-1]->h;i<bottle_neck->h;i++)\n    {\n      X_bottleneck[i] = 0;\n    }\n    delete [] X;\n    X = NULL;\n    {\n      double * Y_bottleneck = NULL;\n      Y_bottleneck = new double[bottle_neck->h];\n      bottle_neck->rbm->vis2hid_simple(X_bottleneck,Y_bottleneck);\n      bottle_neck->rbm->hid2vis_simple(Y_bottleneck,X_bottleneck);\n      delete [] Y_bottleneck;\n      Y_bottleneck = NULL;\n      Y = new double[out_samp];\n      for(long i=input_branch[input_branch.size()-1]->h,k=0;i<bottle_neck->h;i++,k++)\n      {\n        Y[k] = X_bottleneck[i];\n      }\n      delete [] X_bottleneck;\n      X_bottleneck = NULL;\n    }\n    for(long j=0;j<out_samp;j++)\n    {\n      out[sample*out_samp+j] = Y[j];//(Y[j]+1e-5)/(Y_max+1e-5);\n    }\n    for(long i=output_branch.size()-1;i>=0;i--)\n    {\n      X = new double[output_branch[i]->v];\n      output_branch[i]->rbm->hid2vis_simple(Y,X);\n      delete [] Y;\n      Y = NULL;\n      Y = new double[output_branch[i]->v];\n      copy(X,Y,output_branch[i]->v);\n      delete [] X;\n      X = NULL;\n      for(long j=0;j<output_branch[i]->v;j++)\n      {\n        out[sample*output_branch[i]->v+j] = Y[j];\n      }\n    }\n    delete [] Y;\n    Y = NULL;\n  }\n  double ** model(long sample,double * in)\n  {\n    double ** out = new double*[20];\n    for(int i=0;i<20;i++)out[i]=new double[bottle_neck->v];\n    for(int l=0;l<20;l++)\n    for(int i=0;i<bottle_neck->v;i++)\n    out[l][i]=0;\n    //std::cout << \"model:\\t\\t\";\n    //for(int i=0;i<input_branch[0]->v;i++)\n    //std::cout << in[sample*input_branch[0]->v+i] << '\\t';\n    //std::cout << '\\n';\n    long layer = 0;\n    double * X = NULL;\n    double * Y = NULL;\n    X = new double[input_branch[0]->v];\n    for(long i=0;i<input_branch[0]->v;i++)\n    {\n      X[i] = in[sample*input_branch[0]->v+i];\n    }\n    for(long i=0;i<input_branch[0]->v;i++)\n    {\n      out[layer][i] = X[i];\n    }\n    //std::cout << \"out:\\t\\t\";\n    //for(int i=0;i<input_branch[0]->v;i++)\n    //std::cout << out[layer][i] << '\\t';\n    //std::cout << '\\n';\n    layer++;\n    //std::cout << \"input_branch size:\" << input_branch.size() << std::endl;\n    for(long i=0;i<input_branch.size();i++)\n    {\n      Y = new double[input_branch[i]->h];\n      input_branch[i]->rbm->vis2hid_simple(X,Y);\n      delete [] X;\n      X = NULL;\n      X = new double[input_branch[i]->h];\n      copy(Y,X,input_branch[i]->h);\n      delete [] Y;\n      Y = NULL;\n      for(long j=0;j<input_branch[i]->h;j++)\n      {\n        out[layer][j] = X[j];\n      }\n      layer++;\n    }\n    double * X_bottleneck = NULL;\n    X_bottleneck = new double[bottle_neck->h];\n    for(long i=0;i<input_branch[input_branch.size()-1]->h;i++)\n    {\n      X_bottleneck[i] = X[i];\n    }\n    for(long i=input_branch[input_branch.size()-1]->h;i<bottle_neck->h;i++)\n    {\n      X_bottleneck[i] = 0;\n    }\n    delete [] X;\n    X = NULL;\n    {\n      double * Y_bottleneck = NULL;\n      Y_bottleneck = new double[bottle_neck->h];\n      bottle_neck->rbm->vis2hid_simple(X_bottleneck,Y_bottleneck);\n      for(long j=0;j<bottle_neck->v;j++)\n      {\n        out[layer][j] = X_bottleneck[j];\n      }\n      layer++;\n      for(long j=0;j<bottle_neck->v;j++)\n      {\n        out[layer][j] = Y_bottleneck[j];\n      }\n      layer++;\n      bottle_neck->rbm->hid2vis_simple(Y_bottleneck,X_bottleneck);\n      for(long j=0;j<bottle_neck->v;j++)\n      {\n        out[layer][j] = X_bottleneck[j];\n      }\n      layer++;\n      delete [] Y_bottleneck;\n      Y_bottleneck = NULL;\n      Y = new double[out_samp];\n      for(long i=input_branch[input_branch.size()-1]->h,k=0;i<bottle_neck->h;i++,k++)\n      {\n        Y[k] = X_bottleneck[i];\n      }\n      delete [] X_bottleneck;\n      X_bottleneck = NULL;\n    }\n    //double Y_max = 0;\n    //for(long j=0;j<bottle_neck->v-input_branch[input_branch.size()-1]->v;j++)\n    //{\n    //  if(Y[j]>Y_max)Y_max = Y[j];\n    //}\n    for(long j=0;j<out_samp;j++)\n    {\n      out[layer][j] = Y[j];//(Y[j]+1e-5)/(Y_max+1e-5);\n    }\n    layer++;\n    for(long i=output_branch.size()-1;i>=0;i--)\n    {\n      X = new double[output_branch[i]->v];\n      output_branch[i]->rbm->hid2vis_simple(Y,X);\n      delete [] Y;\n      Y = NULL;\n      Y = new double[output_branch[i]->v];\n      copy(X,Y,output_branch[i]->v);\n      delete [] X;\n      X = NULL;\n      for(long j=0;j<output_branch[i]->v;j++)\n      {\n        out[layer][j] = Y[j];\n      }\n      layer++;\n    }\n    //for(long i=0;i<output_branch[0]->v;i++)\n    //{\n    //  out[layer][i] = Y[i];\n    //}\n    delete [] Y;\n    Y = NULL;\n    return out;\n  }\n  void train(long in_num,long out_num,long n_samp,long total_n,long n_cd,double epsilon,double * in,double * out)\n  {\n    double * X = NULL;\n    double * Y = NULL;\n    double * IN = NULL;\n    double * OUT = NULL;\n    X = new double[in_num*n_samp];\n    IN = new double[in_num*n_samp];\n    for(long i=0;i<in_num*n_samp;i++)\n    {\n      X[i] = in[i];\n    }\n    for(long i=0;i<input_branch.size();i++)\n    {\n      if(i>0)input_branch[i]->initialize_weights(input_branch[i-1]); // initialize weights to transpose of previous layer weights M_i -> W = M_{i-1} -> W ^ T\n      input_branch[i]->train(X,n_samp,total_n,n_cd,epsilon,input_branch[i]->h);\n      Y = new double[input_branch[i]->h*n_samp];\n      input_branch[i]->transform(X,Y);\n      delete [] X;\n      X = NULL;\n      //std::cout << \"X init:\" << in_num*n_samp << \"    \" << \"X fin:\" << input_branch[i]->h*n_samp << std::endl;\n      X = new double[input_branch[i]->h*n_samp];\n      copy(Y,X,input_branch[i]->h*n_samp);\n      copy(Y,IN,input_branch[i]->h*n_samp);\n      delete [] Y;\n      Y = NULL;\n    }\n    delete [] X;\n    X = NULL;\n    X = new double[out_num*n_samp];\n    OUT = new double[in_num*n_samp];\n    for(long i=0;i<out_num*n_samp;i++)\n    {\n      X[i] = out[i];\n      OUT[i] = out[i];\n    }\n    for(long i=0;i<output_branch.size();i++)\n    {\n      if(i>0)output_branch[i]->initialize_weights(output_branch[i-1]); // initialize weights to transpose of previous layer weights M_i -> W = M_{i-1} -> W ^ T\n      output_branch[i]->train(X,n_samp,total_n,n_cd,epsilon,input_branch[i]->h);\n      Y = new double[output_branch[i]->h*n_samp];\n      output_branch[i]->transform(X,Y);\n      delete [] X;\n      X = NULL;\n      X = new double[output_branch[i]->h*n_samp];\n      copy(Y,X,output_branch[i]->h*n_samp);\n      copy(Y,OUT,output_branch[i]->h*n_samp);\n      delete [] Y;\n      Y = NULL;\n    }\n    delete [] X;\n    X = NULL;\n    if(bottle_neck!=NULL)\n    {\n      X = new double[bottle_neck->h*n_samp];\n      for(long s=0;s<n_samp;s++)\n      {\n        long i=0;\n        for(long k=0;i<in_num&&k<in_num;i++,k++)\n        {\n          X[s*(in_num+out_num)+i] = IN[s*in_num+k];\n        }\n        for(long k=0;i<in_num+out_num&&k<out_num;i++,k++)\n        {\n          X[s*(in_num+out_num)+i] = OUT[s*out_num+k];\n        }\n      }\n      //bottle_neck->initialize_weights(input_branch[input_branch.size()-1],output_branch[output_branch.size()-1]); // initialize weights to transpose of previous layer weights M_i -> W = M_{i-1} -> W ^ T\n      bottle_neck->train(X,n_samp,total_n,n_cd,epsilon,in_num+out_num);\n      delete [] X;\n      X = NULL;\n    }\n    delete [] IN;\n    IN = NULL;\n    delete [] OUT;\n    OUT = NULL;\n    model_ready = true;\n  }\n  double compare(long sample,double * a,double * b)\n  {\n    double sum_a = 0;\n    double sum_b = 0;\n    for(int i=0;i<out_samp;i++)\n    {\n      sum_a += a[sample*out_samp+i];\n      sum_b += b[sample*out_samp+i];\n    }\n    for(int i=0;i<out_samp;i++)\n    {\n      a[sample*out_samp+i] = (a[sample*out_samp+i]+1e-5)/(sum_a+1e-5);\n      b[sample*out_samp+i] = (b[sample*out_samp+i]+1e-5)/(sum_b+1e-5);\n    }\n    double score = 0;\n    for(int i=0;i<out_samp;i++)\n    {\n      score += ((a[sample*out_samp+i]>0.5&&b[sample*out_samp+i]>0.5)||(a[sample*out_samp+i]<0.5&&b[sample*out_samp+i]<0.5))?1:0;\n    }\n    return score/out_samp;\n  }\n  void compare_all(long num,double * in,double * out)\n  {\n    double score = 0;\n    for(long i=0;i<num;i++)\n    {\n      score += (compare(i,in,out)-score)/(1+i);\n      for(int j=0;j<out_samp;j++)\n      {\n        std::cout << ((in[i*out_samp+j]>0.5)?\"1\":\"0\") << \":\" << ((out[i*out_samp+j]>0.5)?\"1\":\"0\") << \"\\t\";\n      }\n    }\n    std::cout << std::endl;\n    for(long i=0;i<num;i++)\n    {\n      for(int j=0;j<out_samp;j++)\n      {\n        std::cout << in[i*out_samp+j] << \":\" << out[i*out_samp+j] << \"\\t\";\n      }\n    }\n    std::cout << std::endl;\n    std::cout << \"score:\" << score << std::endl;\n    //char ch;\n    //std::cin >> ch;\n  }\n  void model_all(long num,double * in,double * out)\n  {\n    for(long i=0;i<num;i++)\n    {\n      model_simple(i,in,out);\n    }\n  }\n};\n\nmRBM * mrbm = NULL;\n\n/*\n \n RSI Oversold in Uptrend\n\n This scan reveals stocks that are in an uptrend with oversold RSI. First, stocks must be above their 200-day moving average to be in an overall uptrend. Second, RSI must cross below 30 to become oversold.\n\n [type = stock] AND [country = US] \n AND [Daily SMA(20,Daily Volume) > 40000] \n AND [Daily SMA(60,Daily Close) > 20] \n\n AND [Daily Close > Daily SMA(200,Daily Close)] \n AND [Daily RSI(5,Daily Close) <= 30]\n\n RSI Overbought in Downtrend\n\n This scan reveals stocks that are in a downtrend with overbought RSI turning down. First, stocks must be below their 200-day moving average to be in an overall downtrend. Second, RSI must cross above 70 to become overbought.\n\n [type = stock] AND [country = US] \n AND [Daily SMA(20,Daily Volume) > 40000] \n AND [Daily SMA(60,Daily Close) > 20] \n\n AND [Daily Close < Daily SMA(200,Daily Close)] \n AND [Daily RSI(5,Daily Close) >= 70]\n\n*/\n\ndouble max(double a,double b)\n{\n  return (a>b)?a:b;\n}\n\ndouble min(double a,double b)\n{\n  return (a>b)?b:a;\n}\n\ndouble fabs(double a)\n{\n  return (a>0)?a:-a;\n}\n\nstruct Point\n{\n  double t;\n  double x,y;\n  Point(double _x,double _y):x(_x),y(_y){}\n  double dist(Point const & a,double alpha)\n  {\n    return pow(sqrt((x-a.x)*(x-a.x) + (y-a.y)*(y-a.y)),alpha);\n  }\n};\n\ndouble total_dist(std::vector<Point> & pts,double alpha = 1)\n{\n  double temp_dist;\n  double total_dist = 0;\n  pts[0].t = total_dist;\n  for(int i=1;i<pts.size();i++)\n  {\n    temp_dist = pts[i].dist(pts[i-1],alpha);\n    total_dist += temp_dist;\n    pts[i].t = total_dist;\n  }\n}\n\nint find(std::vector<Point> & pts,double t)\n{\n  for(int i=1;i<pts.size();i++)\n  {\n    if(pts[i].t > t)return i-1;\n  }\n}\n\nPoint CatmulRom(std::vector<Point> & pts,double t)\n{\n  int ind0 = (int)find(pts,t)-1;\n  int ind1 = (int)find(pts,t);\n  int ind2 = (int)find(pts,t)+1;\n  int ind3 = (int)find(pts,t)+2;\n  //std::cout << pts[ind1].t << \"\\t\" << pts[ind1].x << \"\\t\" << pts[ind1].y << std::endl;\n  //std::cout << \"$$$$$\" << ind1 << std::endl;\n  if(ind0<0)ind0 = 0;\n  if(ind1<0)ind1 = 0;\n  if(ind2<0)ind2 = 0;\n  if(ind3<0)ind3 = 0;\n  if(ind0>=pts.size())ind0 = pts.size()-1;\n  if(ind1>=pts.size())ind1 = pts.size()-1;\n  if(ind2>=pts.size())ind2 = pts.size()-1;\n  if(ind3>=pts.size())ind3 = pts.size()-1;\n  //std::cout << t << \"~~~~\" << pts[ind0].t << '\\t' << pts[ind1].t << '\\t' << pts[ind2].t << '\\t' << pts[ind3].t << std::endl;\n  //std::cout << \"^^^^\" << pts[ind0].x << '\\t' << pts[ind1].x << '\\t' << pts[ind2].x << '\\t' << pts[ind3].x << std::endl;\n  double d10 = pts[ind1].t - pts[ind0].t;\n  double d21 = pts[ind2].t - pts[ind1].t;\n  double d32 = pts[ind3].t - pts[ind2].t;\n  double A1x = (d10>1e-5)?(pts[ind0].x*(pts[ind1].t-t) + pts[ind1].x*(t-pts[ind0].t))/d10:pts[ind0].x;\n  double A1y = (d10>1e-5)?(pts[ind0].y*(pts[ind1].t-t) + pts[ind1].y*(t-pts[ind0].t))/d10:pts[ind0].y;\n  double A2x = (d21>1e-5)?(pts[ind1].x*(pts[ind2].t-t) + pts[ind2].x*(t-pts[ind1].t))/d21:pts[ind1].x;\n  double A2y = (d21>1e-5)?(pts[ind1].y*(pts[ind2].t-t) + pts[ind2].y*(t-pts[ind1].t))/d21:pts[ind1].y;\n  double A3x = (d32>1e-5)?(pts[ind2].x*(pts[ind3].t-t) + pts[ind3].x*(t-pts[ind2].t))/d32:pts[ind2].x;\n  double A3y = (d32>1e-5)?(pts[ind2].y*(pts[ind3].t-t) + pts[ind3].y*(t-pts[ind2].t))/d32:pts[ind2].y;\n  //std::cout << \"^^^\" << A1x << '\\t' << A2x << '\\t' << A3x << std::endl;\n  double d20 = pts[ind2].t - pts[ind0].t;\n  double d31 = pts[ind3].t - pts[ind1].t;\n  double B1x = (d20>1e-5)?(A1x*(pts[ind2].t-t) + A2x*(t-pts[ind0].t))/d20:A1x;\n  double B1y = (d20>1e-5)?(A1y*(pts[ind2].t-t) + A2y*(t-pts[ind0].t))/d20:A1y;\n  double B2x = (d31>1e-5)?(A2x*(pts[ind3].t-t) + A3x*(t-pts[ind1].t))/d31:A2x;\n  double B2y = (d31>1e-5)?(A2y*(pts[ind3].t-t) + A3y*(t-pts[ind1].t))/d31:A2y;\n  //std::cout << \"^^\" << B1x << '\\t' << B2x << std::endl;\n  double Cx  = (d21>1e-5)?(B1x*(pts[ind2].t-t) + B2x*(t-pts[ind1].t))/d21:B1x;\n  double Cy  = (d21>1e-5)?(B1y*(pts[ind2].t-t) + B2y*(t-pts[ind1].t))/d21:B1y;\n  //std::cout << \"^\" << Cx << \"\\t\" << Cy << std::endl;\n  return Point(Cx,Cy);\n}\n\n\nPoint estimate_derivative(std::vector<Point> & pts,double a,double dx)\n{\n  Point p1 = CatmulRom(pts,a-dx);\n  Point p2 = CatmulRom(pts,a+dx);\n  return Point((p2.x-p1.x)/(2*dx),(p2.y-p1.y)/(2*dx));\n}\n\nstruct price\n{\n\n  price()\n  {\n    prediction_confidence = 0;\n    synthetic = false;\n    EMA = 0;\n    EMA1 = 0;\n    EMS = 0;\n    EMS1 = 0;\n  }\n\n  // these quantities are ground truth\n  bool synthetic;\n  int index;\n  std::string date;\n  double open;\n  double close;\n  double high;\n  double low;\n  int volume;\n  double prev_close;\n  double prct_change;\n  double prct_prediction;\n  double close_prediction;\n  double auto_encoding_x;\n  double auto_encoding_y;\n  double prediction_confidence;\n\n  // these quantities are derived from the values above\n  \n  double EMA_MACD; // temporary ema MACD\n  double calculate_ema_macd(std::vector<price> & prices,int N)\n  {\n    double a = 2.0f / ( 1.0f + N );\n    if(index>=N)\n    {\n      EMA_MACD = a * (MACD_line - prices[index-1].EMA_MACD) + prices[index-1].EMA_MACD;\n      return EMA_MACD;\n    }\n    else\n    {\n      EMA_MACD = MACD_line;\n      return EMA_MACD;\n    }\n  }\n  double EMA_MACD1; // temporary ema MACD\n  double calculate_ema_macd1(std::vector<price> & prices,int N)\n  {\n    double a = 2.0f / ( 1.0f + N );\n    if(index>=N)\n    {\n      EMA_MACD1 = a * (MACD_line - prices[index-1].EMA_MACD1) + prices[index-1].EMA_MACD1;\n      return EMA_MACD1;\n    }\n    else\n    {\n      EMA_MACD1 = MACD_line;\n      return EMA_MACD1;\n    }\n  }\n  double EMA; // temporary ema\n  double calculate_ema(std::vector<price> & prices,int N)\n  {\n    double a = 2.0f / ( 1.0f + N );\n    if(index>=N)\n    {\n      EMA = a * (close - prices[index-1].EMA) + prices[index-1].EMA;\n      return EMA;\n    }\n    else\n    {\n      EMA = close;\n      return EMA;\n    }\n  }\n  double EMA1; // temporary ema\n  double calculate_ema1(std::vector<price> & prices,int N)\n  {\n    double a = 2.0f / ( 1.0f + N );\n    if(index>=N)\n    {\n      EMA1 = a * (close - prices[index-1].EMA1) + prices[index-1].EMA1;\n      return EMA1;\n    }\n    else\n    {\n      EMA1 = close;\n      return EMA1;\n    }\n  }\n  double EMS; // temporary ems\n  double calculate_ems(std::vector<price> & prices,double mean,int N)\n  {\n    double a = 2.0f / ( 1.0f + N );\n    if(index>=N)\n    {\n      EMS = a * ((close - mean)*(close - mean) - prices[index-1].EMS) + prices[index-1].EMS;\n      return EMS;\n    }\n    else\n    {\n      EMS = 0;\n      return EMS;\n    }\n  }\n  double EMS1; // temporary ems\n  double calculate_ems1(std::vector<price> & prices,double mean,int N)\n  {\n    double a = 2.0f / ( 1.0f + N );\n    if(index>=N)\n    {\n      EMS1 = a * ((close - mean)*(close - mean) - prices[index-1].EMS1) + prices[index-1].EMS1;\n      return EMS1;\n    }\n    else\n    {\n      EMS1 = 0;\n      return EMS1;\n    }\n  }\n  double EMAV; // temporary ema\n  double calculate_ema_volume(std::vector<price> & prices,int N)\n  {\n    double a = 2.0f / ( 1.0f + N );\n    if(index>=N)\n    {\n      EMAV = a * (volume - prices[index-1].EMAV) + prices[index-1].EMAV;\n      return EMAV;\n    }\n    else\n    {\n      EMAV = volume;\n      return EMAV;\n    }\n  }\n  double SMAV; // temporary simple moving average\n  double calculate_sma_volume(std::vector<price> & prices,int N)\n  {\n    if(index>=N)\n    {\n      SMAV = 0;\n      for(int i=1;i<=N;i++)\n      {\n        SMAV += (prices[index+1-i].volume - SMAV)/i;\n      }\n      return SMAV;\n    }\n    else\n    {\n      SMAV = 0;\n      for(int i=1;i<=index+1;i++)\n      {\n        SMAV += (prices[index+1-i].volume - SMAV)/i;\n      }\n      return SMAV;\n    }\n  }\n\n  // Volume Spike - sizzle index\n  // Current Volume > tolerance x (5 d SMA Volume)\n  // close today > close yesterday => volume gain\n  // close today < close yesterday => volume loss\n  bool Volume_spike;\n  bool Volume_spike_gain;\n  bool Volume_spike_loss;\n  bool Volume_gain;\n  bool Volume_loss;\n  void calculate_Volume_spike(std::vector<price> & prices,int N=5,double tolerance=2.0f)\n  {\n    Volume_spike = volume > tolerance * SMAV;\n    Volume_spike_gain = false;\n    Volume_spike_loss = false;\n    Volume_gain = false;\n    Volume_loss = false;\n    if(index >= 1)\n    {\n      if(Volume_spike)\n      {\n        if(close > prices[index-1].close)\n        {\n          Volume_spike_gain = true;\n        }\n        else\n        {\n          Volume_spike_loss = true;\n        }\n      }\n      if(close > prices[index-1].close)\n      {\n        Volume_gain = true;\n      }\n      else\n      {\n        Volume_loss = true;\n      }\n    }\n  }\n  static void initialize_Volume_spike(std::vector<price> & prices, int N=5,double tolerance=2.0f)\n  {\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_sma_volume(prices,N);\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_Volume_spike(prices,N,tolerance);\n    }\n  }\n\n  // RSI \n  // 100 - 100/(1+RS)\n  // RS = Average Gain / Average Loss\n  double average_gain;\n  double average_loss;\n  double RS;\n  double RSI;\n  bool RSI_buy;\n  bool RSI_sell;\n  void calculate_RSI(std::vector<price> & prices,int N=14)\n  {\n    if(index==N)\n    {\n      average_gain = 0;\n      average_loss = 0;\n      for(int i=1;i<N+1;i++)\n      {\n        if(prices[index+1-i].close > prices[index-i].close)\n        {\n          average_gain += ((prices[index+1-i].close-prices[index-i].close) - average_gain)/i;\n          average_loss -= average_loss/i;\n        }\n        else\n        {\n          average_loss += ((prices[index-i].close-prices[index+1-i].close) - average_loss)/i;\n          average_gain -= average_gain/i;\n        }\n      }\n      if(average_loss>1e-10)\n      {\n        RS = average_gain / average_loss;\n      }\n      else\n      {\n        RS = 0;\n      }\n      RSI = 100 - 100/(1+RS);\n    }\n    else\n    if(index>=N+1)\n    {\n      if(prices[index].close > prices[index-1].close)\n      {\n        average_gain = ((prices[index].close-prices[index-1].close) + (N-1)*prices[index-1].average_gain)/N;\n        average_loss = ((N-1)*prices[index-1].average_loss)/N;\n      }\n      else\n      {\n        average_loss = ((prices[index-1].close-prices[index].close) + (N-1)*prices[index-1].average_loss)/N;\n        average_gain = ((N-1)*prices[index-1].average_gain)/N;\n      }\n      if(average_loss>1e-10)\n      {\n        RS = average_gain / average_loss;\n      }\n      else\n      {\n        RS = 0;\n      }\n      RSI = 100 - 100/(1+RS);\n    }\n    else\n    {\n      average_gain = 0;\n      average_loss = 0;\n      RS = 0;\n      RSI = 0;\n    }\n    //std::cout << index << \"\\t\" << date << \"\\t\" << average_gain << \"\\t\" << average_loss << \"\\t\" << RS << \"\\t\" << RSI << std::endl;\n    //char ch;\n    //std::cin >> ch;\n  }\n  void calculate_RSI_buy()\n  {\n    if(RSI>1e-10)\n    {\n      RSI_buy = RSI<30;\n    }\n    else\n    {\n      RSI_buy = false;\n    }\n  }\n  void calculate_RSI_sell()\n  {\n    if(RSI>1e-10)\n    {\n      RSI_sell = RSI>70;\n    }\n    else\n    {\n      RSI_sell = false;\n    }\n  }\n  static void initialize_RSI(std::vector<price> & prices,int N=14)\n  {\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_RSI(prices,N);\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_RSI_buy();\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_RSI_sell();\n    }\n  }\n\n  // MFI \n  // 100 - 100/(1+MF)\n  // MF = Average TP Gain * Gain Volume / Average TP Loss * Loss Volume\n  double raw_money_flow_gain;\n  double raw_money_flow_loss;\n  double MF;\n  double MFI;\n  bool MFI_buy;\n  bool MFI_sell;\n  void calculate_MFI(std::vector<price> & prices,int N=14)\n  {\n    if(index==N)\n    {\n      raw_money_flow_gain = 0;\n      raw_money_flow_loss = 0;\n      for(int i=1;i<N+1;i++)\n      {\n        if(prices[index+1-i].TP > prices[index-i].TP)\n        {\n          raw_money_flow_gain += (prices[index+1-i].TP*prices[index+1-i].volume - raw_money_flow_gain)/i;\n          raw_money_flow_loss -= raw_money_flow_loss/i;\n        }\n        else\n        {\n          raw_money_flow_loss += (prices[index+1-i].TP*prices[index+1-i].volume - raw_money_flow_loss)/i;\n          raw_money_flow_gain -= raw_money_flow_gain/i;\n        }\n      }\n      if(raw_money_flow_loss>1e-10)\n      {\n        MF = raw_money_flow_gain / raw_money_flow_loss;\n      }\n      else\n      {\n        MF = 0;\n      }\n      MFI = 100 - 100/(1+MF);\n    }\n    else\n    if(index>=N+1)\n    {\n      if(prices[index].TP > prices[index-1].TP)\n      {\n        raw_money_flow_gain = (prices[index].TP*prices[index-1].volume + (N-1)*prices[index-1].raw_money_flow_gain)/N;\n        raw_money_flow_loss = ((N-1)*prices[index-1].raw_money_flow_loss)/N;\n      }\n      else\n      {\n        raw_money_flow_loss = (prices[index-1].TP*prices[index].volume + (N-1)*prices[index-1].raw_money_flow_loss)/N;\n        raw_money_flow_gain = ((N-1)*prices[index-1].raw_money_flow_gain)/N;\n      }\n      if(raw_money_flow_loss>1e-10)\n      {\n        MF = raw_money_flow_gain / raw_money_flow_loss;\n      }\n      else\n      {\n        MF = 0;\n      }\n      MFI = 100 - 100/(1+MF);\n    }\n    else\n    {\n      raw_money_flow_gain = 0;\n      raw_money_flow_loss = 0;\n      MF = 0;\n      MFI = 0;\n    }\n  }\n  void calculate_MFI_buy()\n  {\n    if(MFI>1e-10)\n    {\n      MFI_buy = MFI<30;\n    }\n    else\n    {\n      MFI_buy = false;\n    }\n  }\n  void calculate_MFI_sell()\n  {\n    if(MFI>1e-10)\n    {\n      MFI_sell = MFI>70;\n    }\n    else\n    {\n      MFI_sell = false;\n    }\n  }\n  static void initialize_MFI(std::vector<price> & prices,int N=14)\n  {\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_TP();\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_MFI(prices,N);\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_MFI_buy();\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_MFI_sell();\n    }\n  }\n\n  // Golden cross\n  double ema_50;\n  double ema_200;\n  double ems_50;\n  double ems_200;\n  bool GoldenCross_uptrend;\n  bool GoldenCross_downtrend;\n  void calculate_GoldenCross_uptrend(std::vector<price> & prices,int N1=50,int N2=200)\n  {\n    if(index>=N2&&index>=N1)\n    {\n      ema_50 = calculate_ema(prices,N1);\n      ema_200= calculate_ema1(prices,N2);\n      ems_50 = sqrtf(calculate_ems(prices,ema_50,N1));\n      ems_200= sqrtf(calculate_ems1(prices,ema_200,N2));\n      GoldenCross_uptrend = ema_50>ema_200;\n    }\n    else\n    {\n      ema_50 = close;\n      ema_200 = close;\n      ems_50 = 0;\n      ems_200 = 0;\n      GoldenCross_uptrend = false;\n    }\n  }\n  void calculate_GoldenCross_downtrend(std::vector<price> & prices,int N1=50,int N2=200)\n  {\n    if(index>=N2&&index>=N1)\n    {\n      ema_50 = calculate_ema(prices,N1);\n      ema_200= calculate_ema1(prices,N2);\n      ems_50 = sqrtf(calculate_ems(prices,ema_50,N1));\n      ems_200= sqrtf(calculate_ems1(prices,ema_200,N2));\n      GoldenCross_downtrend = ema_50<ema_200;\n    }\n    else\n    {\n      ema_50 = close;\n      ema_200 = close;\n      ems_50 = 0;\n      ems_200 = 0;\n      GoldenCross_downtrend = false;\n    }\n  }\n  static void initialize_GoldenCross(std::vector<price> & prices,int N1=50,int N2=200)\n  {\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_GoldenCross_uptrend(prices,N1,N2);\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_GoldenCross_downtrend(prices,N1,N2);\n    }\n  }\n\n  // MACD\n  double ema_12;\n  double ema_26;\n  double ems_12;\n  double ems_26;\n  double MACD_line;\n  double MACD_signal;\n  double MACD_dline;\n  double MACD_dsignal;\n  bool MACD_uptrend;\n  bool MACD_downtrend;\n  void calculate_MACD_signal(std::vector<price> & prices,int N=9,int N1=12,int N2=26)\n  {\n    if(index>=N&&index>=N1&&index>=N2&&index>=100)\n    {\n      ema_12 = calculate_ema(prices,N1);\n      ema_26 = calculate_ema1(prices,N2);\n      if(index>=200)\n      {\n        MACD_line = (ema_12 - ema_26)/(ema_26+1);\n        MACD_signal = calculate_ema_macd(prices,N);\n      }\n      else\n      {\n        MACD_line = 0;\n        MACD_signal = 0;\n      }\n    }\n    else\n    {\n      ema_12 = close;\n      ema_26 = close;\n      MACD_line = 0;\n      MACD_signal = 0;\n    }\n  }\n  static void calculate_MACD_dsignal(std::vector<price> & prices)\n  {\n    //char ch;\n    //std::cout << \"pass 1\" << std::endl;\n    std::vector<Point> pts;\n    for(int i=0;i<prices.size();i++)\n    {\n      pts.push_back(Point(1000*prices[i].MACD_line,1000*prices[i].MACD_signal));\n      //std::cout << pts[i].x << \"\\t\" << pts[i].y << std::endl;\n    }\n    //std::cin >> ch;\n    //std::cout << \"pass 2\" << std::endl;\n    total_dist(pts,0.5);\n    //total_dist(pts,0.0);\n    //for(int i=0;i<prices.size();i++)\n    //{\n      //std::cout << pts[i].t << \"\\t\" << pts[i].x << \"\\t\" << pts[i].y << std::endl;\n    //}\n    //std::cout << \"pass 3\" << std::endl;\n    //std::cin >> ch;\n    prices[0].MACD_dline   = 0.0001;\n    prices[0].MACD_dsignal = 0.0001;\n    for(int i=0;i+1<pts.size();i++)\n    {\n      //std::cout << \"i=\" << i << \"\\t\" << pts[i].t << std::endl;\n      //Point pt = CatmulRom(pts,0.5f*(pts[i].t+pts[i+1].t));\n      //Point drv = estimate_derivative(pts,0.5f*(pts[i].t+pts[i+1].t),0.01);\n      Point drv = estimate_derivative(pts,pts[i].t,0.01);\n      prices[i+1].MACD_dline = drv.x;\n      prices[i+1].MACD_dsignal = drv.y;\n      //prices[i+1].MACD_dline = pt.x;\n      //prices[i+1].MACD_dsignal = pt.y;\n      //prices[i+1].MACD_dline = pts[i].x;\n      //prices[i+1].MACD_dsignal = pts[i].y;\n    }\n    //std::cin >> ch;\n    //std::cout << \"pass 4\" << std::endl;\n  }\n  void calculate_MACD_uptrend(std::vector<price> & prices,int N1=12,int N2=26)\n  {\n    if(index>=N2&&index>=N1&&index>=100)\n    {\n      ema_12 = calculate_ema(prices,N1);\n      ema_26 = calculate_ema1(prices,N2);\n      ems_12 = sqrtf(calculate_ems(prices,ema_12,N1));\n      ems_26 = sqrtf(calculate_ems1(prices,ema_26,N2));\n      MACD_uptrend = ema_12>ema_26;\n    }\n    else\n    {\n      ema_12 = close;\n      ema_26 = close;\n      ems_12 = 0;\n      ems_26 = 0;\n      MACD_uptrend = false;\n    }\n  }\n  void calculate_MACD_downtrend(std::vector<price> & prices,int N1=12,int N2=26)\n  {\n    if(index>=N2&&index>=N1&&index>=100)\n    {\n      ema_12 = calculate_ema(prices,N1);\n      ema_26 = calculate_ema1(prices,N2);\n      ems_12 = sqrtf(calculate_ems(prices,ema_12,N1));\n      ems_26 = sqrtf(calculate_ems1(prices,ema_26,N2));\n      MACD_downtrend = ema_12<ema_26;\n    }\n    else\n    {\n      ema_12 = close;\n      ema_26 = close;\n      ems_12 = 0;\n      ems_26 = 0;\n      MACD_downtrend = false;\n    }\n  }\n  static void initialize_MACD(std::vector<price> & prices,bool awesome_macd=false,int N=9,int N1=12,int N2=26)\n  {\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_MACD_uptrend(prices,N1,N2);\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_MACD_downtrend(prices,N1,N2);\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_MACD_signal(prices,N,N1,N2);\n    }\n    if(awesome_macd)\n    {\n      calculate_MACD_dsignal(prices);\n    }\n  }\n\n  // DOJI - open and close price are very similar\n  bool doji;\n  void calculate_doji()\n  {\n    doji = open + 0.003*open > close && open - 0.003*open < close;\n  }\n  static void initialize_doji(std::vector<price> & prices)\n  {\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_doji();\n    }\n  }\n\n  // CCI\n  double TP; // typical price = (high + low + close)/3\n  double smtp_cci; // 20 day simple moving average of Typical Price (TP)\n  double MD_cci; // 20 day mean deviation = sum_n |TP - smtp_n|/n\n  double CCI; // (TP - 20d SMTP) / (.015 MD)\n  bool CCI_buy, CCI_sell;\n  static void initialize_CCI(std::vector<price> & prices,int N = 20)\n  {\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_TP();\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_smtp(prices,N);\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_MD(prices,N);\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_CCI(prices,N);\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_CCI_buy();\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_CCI_sell();\n    }\n  }\n  void calculate_TP()\n  {\n    TP = (high + low + close)/3.0f;\n  }\n  void calculate_smtp(std::vector<price> & prices,int N = 20)\n  {\n    if(index>=N)\n    {\n      smtp_cci = 0;\n      for(int k=1;k<=N;k++)\n      {\n        smtp_cci += (prices[index+1-k].TP - smtp_cci)/k;\n      }\n    }\n    else\n    {\n      smtp_cci = 0;\n    }\n  }\n  void calculate_MD(std::vector<price> & prices,int N = 20)\n  {\n    if(index>=N)\n    {\n      MD_cci = 0;\n      for(int k=1;k<=N;k++)\n      {\n        MD_cci += (fabs(prices[index+1-k].TP - smtp_cci) - MD_cci)/k;\n      }\n    }\n    else\n    {\n      smtp_cci = 0;\n    }\n  }\n  void calculate_CCI(std::vector<price> & prices,int N=20)\n  {\n    if(index>=N)\n    {\n      CCI = (TP - smtp_cci) / (.015 * MD_cci);\n    }\n    else\n    {\n      CCI = 0;\n    }\n  }\n  void calculate_CCI_buy()\n  {\n    if(fabs(CCI-0)>1e-10)\n    {\n      CCI_buy = CCI < -100;\n    }\n    else\n    {\n      CCI_buy = false;\n    }\n  }\n  void calculate_CCI_sell()\n  {\n    if(fabs(CCI-0)>1e-10)\n    {\n      CCI_sell = CCI > 100;\n    }\n    else\n    {\n      CCI_sell = false;\n    }\n  }\n\n  // Bullish Engulfing Pattern\n  // Today close > Yesterday open\n  // Today open < Yesterday close\n  // Today close > Today open // today candlestick is green\n  // Yesterday close < Yesterday open // yesterday candlestick is red\n  bool bullish_engulfing_pattern;\n  void calculate_bullish_engulfing_pattern(std::vector<price> & prices)\n  {\n    if(index>=1)\n    {\n      bullish_engulfing_pattern = (close>prices[index-1].open)\n                                &&(open<prices[index-1].close)\n                                &&(close>open)\n                                &&(prices[index-1].close<prices[index-1].open)\n                                ;\n    }\n    else\n    {\n      bullish_engulfing_pattern = false;\n    }\n  }\n\n  // Bearish Engulfing Pattern\n  // Today open > Yesterday close\n  // Today close < Yesterday open\n  // Today close < Today open // today candlestick is red\n  // Yesterday close > Yesterday open // yesterday candlestick is green\n  bool bearish_engulfing_pattern;\n  void calculate_bearish_engulfing_pattern(std::vector<price> & prices)\n  {\n    if(index>=1)\n    {\n      bearish_engulfing_pattern = (open>prices[index-1].close)\n                                &&(close<prices[index-1].open)\n                                &&(close<open)\n                                &&(prices[index-1].close>prices[index-1].open)\n                                ;\n    }\n    else\n    {\n      bearish_engulfing_pattern = false;\n    }\n  }\n\n  static void initialize_engulfing_patterns(std::vector<price> & prices)\n  {\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_bullish_engulfing_pattern(prices);\n    }\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_bearish_engulfing_pattern(prices);\n    }\n  }\n\n  static void initialize_percent_change(std::vector<price> & prices)\n  {\n    prices[0].prev_close = prices[0].close;\n    prices[0].prct_change = 0;\n    prices[0].auto_encoding_x = 0;\n    prices[0].auto_encoding_y = 0;\n    prices[0].close_prediction = prices[0].close;\n    prices[0].prct_prediction = 0;\n    for(int i=1;i<prices.size();i++)\n    {\n      prices[i].prev_close = prices[i-1].close;\n      prices[i].prct_change = (prices[i].close - prices[i-1].close) / prices[i-1].close;\n      prices[i].auto_encoding_x = 0;\n      prices[i].auto_encoding_y = 0;\n      prices[i].close_prediction = prices[i-1].close;\n      prices[i].prct_prediction = 0;\n    }\n  }\n\n  // initialize all indicators \n  static void initialize_indicators(std::vector<price> & prices,bool awesome_macd)\n  {\n    for(int i=0;i<prices.size();i++)\n    {\n      prices[i].calculate_ema_volume(prices,500);\n    }\n    initialize_CCI(prices);\n    initialize_doji(prices);\n    initialize_MACD(prices,awesome_macd);\n    initialize_GoldenCross(prices);\n    initialize_engulfing_patterns(prices);\n    initialize_RSI(prices);\n    initialize_MFI(prices);\n    initialize_Volume_spike(prices);\n    initialize_percent_change(prices);\n  }\n\n};\n\nstruct Scanner\n{\n  std::set<std::string> buy;\n  void scan(std::vector<std::vector<price> > & prices, std::vector<std::string> & symbols)\n  {\n    buy . clear();\n    for(int i=0;i<prices.size();i++)\n    {\n      if(prices[i].size()>=3)\n      {\n        for(int d=0;d<3;d++)\n        {\n          if( prices[i][prices[i].size()-1-d].CCI_buy ||\n              prices[i][prices[i].size()-1-d].RSI_buy ||\n              prices[i][prices[i].size()-1-d].MFI_buy \n            )\n          {\n            buy.insert(symbols[i]);\n          }\n        }\n      }\n    }\n    std::cout << \"Buy candidates:\" << std::endl;\n    std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n    for(std::set<std::string>::iterator it = buy.begin();it != buy.end();it++)\n    {\n      std::cout << *it << std::endl;\n    }\n    std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n  }\n};\n\nbool comparator(price a,price b){return a.close < b.close;}\nbool comparator_MACD(price a,price b){return a.MACD_dline < b.MACD_dline;}\nbool comparator_auto(price a,price b){return a.auto_encoding_x < b.auto_encoding_x;}\nbool comparator_low(price a,price b){return a.low < b.low;}\nbool comparator_high(price a,price b){return a.high < b.high;}\n\nbool comparator_volume(price a,price b){return a.volume < b.volume;}\n\nstruct Bin\n{\n  double price_min;\n  double price_max;\n  double sum;\n  double sum_neg;\n  double sum_pos;\n  bool in(double price)\n  {\n    return price>=price_min&&price<price_max;\n  }\n  std::vector<price> collection;\n  Bin(double _price_min,double _price_max)\n  {\n    price_min = _price_min;\n    price_max = _price_max;\n  }\n  void push(price p)\n  {\n    if(in(p.close))\n    {\n      collection.push_back(p);\n    }\n  }\n  void calc()\n  {\n    sum = 0;\n    for(int i=0;i<collection.size();i++)\n    {\n      sum += collection[i].volume;\n      if(collection[i].Volume_gain) sum_pos += collection[i].volume;\n      if(collection[i].Volume_loss) sum_neg += collection[i].volume;\n    }\n  }\n};\n\nstruct VolumeByPrice\n{\n  double max_sum;\n  std::vector<Bin> bins;\n  void create_bins(std::vector<price> & prices,int nbins,int min_index,int max_index)\n  {\n    double max_price = double(std::max_element(prices.begin()+min_index,prices.begin()+max_index,comparator)->close);\n    double min_price = double(std::min_element(prices.begin()+min_index,prices.begin()+max_index,comparator)->close);\n    double bin_size = (max_price-min_price)/nbins;\n    for(int i=0;i<nbins;i++)\n    {\n      bins.push_back(Bin(min_price+bin_size*i,min_price+(i+1)*bin_size));\n    }\n    for(int i=min_index;i<=max_index;i++)\n    {\n      for(int k=0;k<nbins;k++)\n      {\n        bins[k].push(prices[i]);\n      }\n    }\n    for(int i=0;i<nbins;i++)\n    {\n      bins[i].calc();\n    }\n    max_sum = 0;\n    for(int i=0;i<nbins;i++)\n    {\n      if(bins[i].sum>max_sum)\n      {\n        max_sum = bins[i].sum;\n      }\n    }\n    for(int i=0;i<nbins;i++)\n    {\n      bins[i].sum     /= max_sum+1;\n      bins[i].sum_pos /= max_sum+1;\n      bins[i].sum_neg /= max_sum+1;\n    }\n  }\n};\n\nvoid generate_synthetic(std::vector<price> & prices,double multiplier,int nyears)\n{\n  double value = (rand()%10000000)/10000.0;\n  int date = 1;\n  int nweeks = (int)(nyears*52.1429);\n  for(int w=0;w<nweeks;w++)\n  {\n    for(int d=0;d<5;d++)\n    {\n      price p;\n      std::stringstream date_ss;\n      date_ss << date;\n      p.index = prices.size();\n      p.date = date_ss.str();\n      p.open = value;\n      p.close = value * ( 1.0 + multiplier*0.02 * (1-2*(rand()%10000)/10000.0) );\n      p.high = max(p.open,p.close) * ( 1 + multiplier*0.02 * ((rand()%10000)/10000.0) );\n      p.low = min(p.open,p.close) * ( 1 - multiplier*0.02 * ((rand()%10000)/10000.0) );\n      p.volume = (int)(100*fabs(p.close-p.open));\n      prices.push_back(p);\n      if((rand()%10000)/10000.0 > 1.0/4.0)\n      {\n        value *= 1.0 + multiplier*0.01 * ((rand()%10000)/10000.0);\n      }\n      else\n      {\n        value /= 1.0 + multiplier*0.03 * ((rand()%10000)/10000.0);\n      }\n      date++;\n    }\n    date+=2;\n  }\n}\n\nvoid read_data(std::string filename,std::vector<price> & prices)\n{\n  std::ifstream infile(filename.c_str());\n  std::string line;\n  int i=0;\n  int dat=0;\n  int day=0,month=0,year=0;\n  while (std::getline(infile, line))\n  {\n    price D;\n    std::stringstream iss(line);\n    std::string token;\n    // date\n    iss >> token;\n    boost::erase_all(token,\"/\");\n    boost::erase_all(token,\",\");\n    dat = atoi(token.c_str());\n    year = dat%100;\n    if(year > 50)year += 1900;else year += 2000;\n    day = (dat/100)%100;\n    month = (dat/10000)%100;\n    //fprintf(stderr,\"year:%d month:%d day:%d\\n\",year,month,day);\n    D.date = token.c_str();\n    // open\n    iss >> token;\n    boost::erase_all(token,\",\");\n    D.open = atof(token.c_str());\n    // high\n    iss >> token;\n    boost::erase_all(token,\",\");\n    D.high = atof(token.c_str());\n    // low\n    iss >> token;\n    boost::erase_all(token,\",\");\n    D.low = atof(token.c_str());\n    // close\n    iss >> token;\n    boost::erase_all(token,\",\");\n    D.close = atof(token.c_str());\n    D.volume = fabs(D.close - D.open)*100;\n    prices.push_back(D);\n  }\n  infile.close();\n  reverse(prices.begin(),prices.end());\n  for(int i=0;i<prices.size();i++)\n  {\n    prices[i].index = i;\n  }\n}\n\nvoid read_data_yahoo(std::string filename,std::vector<price> & prices,int synthetic_days=0)\n{\n  std::ifstream infile(filename.c_str());\n  std::string line;\n  int i=0;\n  int dat=0;\n  int day=0,month=0,year=0;\n  while (std::getline(infile, line))\n  {\n    price D;\n    boost::replace_all(line,\",\",\" \");\n    std::stringstream iss(line);\n    std::string token;\n    // date\n    iss >> token;\n    D.date = token.c_str();\n    // open\n    iss >> token;\n    boost::erase_all(token,\",\");\n    D.open = atof(token.c_str());\n    // high\n    iss >> token;\n    boost::erase_all(token,\",\");\n    D.high = atof(token.c_str());\n    // low\n    iss >> token;\n    boost::erase_all(token,\",\");\n    D.low = atof(token.c_str());\n    // close\n    iss >> token;\n    boost::erase_all(token,\",\");\n    D.close = atof(token.c_str());\n    // adj close\n    iss >> token;\n    boost::erase_all(token,\",\");\n    //D.close = atof(token.c_str());\n    // volume\n    iss >> token;\n    boost::erase_all(token,\",\");\n    D.volume = atoi(token.c_str());\n    if(D.close > 0 && D.low > 0 && D.high > 0 && D.open > 0)\n    {\n      prices.push_back(D);\n    }\n  }\n  infile.close();\n  for(int i=0;i<synthetic_days;i++)\n  {\n    price D;\n    D.synthetic=true;\n    D.open  =prices[prices.size()-1].open;\n    D.low   =prices[prices.size()-1].low;\n    D.high  =prices[prices.size()-1].high;\n    D.close =prices[prices.size()-1].close;\n    D.volume=prices[prices.size()-1].volume;\n    prices.push_back(D);\n  }\n  for(int i=0;i<prices.size();i++)\n  {\n    prices[i].index = i;\n  }\n}\n\nbool buy_only = false;\nbool game_mode = false;\nScanner scanner;\n\nstd::vector<std::vector<price> > prices;\nstd::vector<std::string> symbols;\nstd::vector<int> rsymbols;\nint start_date_index = 0;\nint   end_date_index = 0;\n\nstruct Symbol\n{\n  int index;\n  std::string name;\n  double units;\n  double buy_price;\n  Symbol(double _units,double _buy_price,std::string _name,int _index)\n    : units(_units)\n    , buy_price(_buy_price)\n    , name(_name)\n    , index(_index)\n  {\n\n  }\n  Symbol()\n    : units(0)\n    , buy_price(0)\n    , name(\"\")\n    , index(-1)\n  {\n\n  }\n};\n\nstruct User\n{\n  std::string name;\n  double prev_cash;\n  double cash;\n  std::map<int,Symbol> rstocks;\n  User(std::string _name,double _cash,std::vector<int> & _rsymbol)\n  {\n    name = _name;\n    cash = _cash;\n    for(int i=0;i<_rsymbol.size();i++)\n    {\n      initialize(_rsymbol[i]);\n    }\n  }\n  void initialize(int symbol)\n  {\n    //rstocks.insert(std::pair<int,Symbol>(symbol,Symbol(0,0,symbols[symbol],symbol)));\n    std::stringstream ss;\n    ss << \"Stock\" << (1+rstocks.size());\n    rstocks.insert(std::pair<int,Symbol>(symbol,Symbol(0,0,ss.str(),symbol)));\n  }\n  bool buyAll(int symbol,int date_index) // date_index counts backwards from last possible date\n  {\n    buy(symbol,cash/prices[symbol][prices[symbol].size()-1-date_index].high,date_index);\n  }\n  bool sellAll(int symbol,int date_index) // date_index counts backwards from last possible date\n  {\n    sell(symbol,rstocks[symbol].units,date_index);\n  }\n  bool buy(int symbol,double units,int date_index) // date_index counts backwards from last possible date\n  {\n    std::cout << prices[symbol][prices[symbol].size()-1-date_index].date << \": User <\" << name << \"> attempting to buy \" << units << \" of \" << symbols[symbol] << \".\" << std::endl;\n    std::cout << \"Available cash: $\" << cash << std::endl;\n    std::cout << symbols[symbol] << \" price: $\" << prices[symbol][prices[symbol].size()-1-date_index].high << std::endl;\n    std::cout << \"Units: \" << units << std::endl;\n    std::cout << \"Total price: $\" << (units * prices[symbol][prices[symbol].size()-1-date_index].high) << std::endl;\n    if(units * prices[symbol][prices[symbol].size()-1-date_index].high <= cash+1e5 && units > 1e-5 && cash > 1e-5)\n    {\n      std::cout << \"Buy successful\" << std::endl;\n      cash -= units * prices[symbol][prices[symbol].size()-1-date_index].high;\n      rstocks [symbol] . units += units;\n      rstocks [symbol] . buy_price = prices[symbol][prices[symbol].size()-1-date_index].high;\n      return true;\n    }\n    return false;\n  }\n  bool sell(int symbol,double units,int date_index) // date_index counts backwards from last possible date\n  {\n    std::cout << prices[symbol][prices[symbol].size()-1-date_index].date << \": User <\" << name << \"> attempting to sell \" << units << \" of \" << symbols[symbol] << \".\" << std::endl;\n    std::cout << symbols[symbol] << \" price: $\" << prices[symbol][prices[symbol].size()-1-date_index].low << std::endl;\n    std::cout << \"Units: \" << units << std::endl;\n    std::cout << \"Total price: $\" << (units * prices[symbol][prices[symbol].size()-1-date_index].low) << std::endl;\n    if(rstocks [symbol] . units >= units-1e-5 && units > 1e-5 && rstocks[symbol] . units > 1e-5)\n    {\n      std::cout << \"Sell successful\" << std::endl;\n      cash += units * prices[symbol][prices[symbol].size()-1-date_index].low;\n      rstocks [symbol] . units -= units;\n      rstocks [symbol] . buy_price = prices[symbol][prices[symbol].size()-1-date_index].low;\n      return true;\n    }\n    return false;\n  }\n  double expected_return(int date_index)\n  {\n    if(cash<1e-5){}\n    else{prev_cash=cash;}\n    double val = cash;\n    std::map<int,Symbol>::iterator it = rstocks.begin();\n    while(it!=rstocks.end())\n    {\n      val += it->second.units * prices[it->second.index][prices[it->second.index].size()-1-date_index].low;\n      ++it;\n    }\n    return val;\n  }\n};\n\nstruct Robot\n{\n  long num_elems;\n  long num_bits;\n  long num_out_bits;\n  Robot()\n  {\n    num_elems = 0;\n    num_bits = 1;\n    num_out_bits = 1;\n  }\n  User * user;\n  void predict(std::vector<double> const & input, std::vector<double> & output)\n  {\n\n  }\n  void train(std::vector<double> const & input, std::vector<double> const & output)\n  {\n\n  }\n  long get_input_size(long range)\n  {\n    std::vector<double> input;\n    //for(long i=0;i<num_bits;i++)\n    //    input.push_back(0/*p.CCI*/);\n    //for(long i=0;i<num_bits;i++)\n    //    input.push_back(0/*p.RSI*/);\n    //for(long i=0;i<num_bits;i++)\n    //    input.push_back(0/*p.MFI*/);\n    //for(long i=0;i<num_bits;i++)\n    //    input.push_back(0/*p.close > p.ema_12+1.5*p.ems_12*/);\n    //for(long i=0;i<num_bits;i++)\n    //    input.push_back(0/*p.MACD_dline>0&&p.MACD_dsignal>0*/);\n    //for(long i=0;i<num_bits;i++)\n    //    input.push_back(0/*p.MACD_dline<0&&p.MACD_dsignal<0*/);\n    return input.size()+num_bits*(range);\n  }\n  long get_output_size(long range)\n  {\n    std::vector<double> output;\n    return output.size()+num_bits*(range);\n    //return num_out_bits*(range-1);\n  }\n  void encode(std::vector<double> & vec,double dat,double min_dat,double max_dat,long num)\n  {\n    \n    if(dat<0.25*min_dat)dat=0.25*min_dat+1e-5;\n    if(dat>0.25*max_dat)dat=0.25*max_dat-1e-5;\n    if(dat<min_dat)dat=min_dat+1e-5;\n    if(dat>max_dat)dat=max_dat-1e-5;\n    double val = ((dat-min_dat)/(max_dat-min_dat));\n    vec.push_back(val);\n    \n  }\n  std::vector<double> construct_input_vector(price p,std::vector<price> const & prev)\n  {\n    std::vector<double> input;\n    //encode(input,p.CCI,-150,150,num_bits);\n    //encode(input,p.RSI,0,100,num_bits);\n    //encode(input,p.MFI,0,100,num_bits);\n    //encode(input,100*(p.close - p.ema_12)/p.ems_12,-150,150,num_bits);\n    //encode(input,p.MACD_dline,-2,2,num_bits);\n    //encode(input,p.MACD_dsignal,-2,2,num_bits);\n    for(int i=0;i<prev.size();i++)\n    {\n      encode(input,100*prev[i].prct_change,-2,2,num_bits);\n    }\n    return input;\n  }\n  std::vector<double> construct_output_vector(price p,std::vector<price> const & next)\n  {\n    std::vector<double> output;\n    for(int i=0;i<next.size();i++)\n    {\n      {\n        encode(output,100*next[i].prct_change,-2,2,num_out_bits);\n      }\n    }\n    return output;\n  }\n  void generate ( std::string symb\n                , price p\n                , std::vector<price> const & prev\n                , std::vector<price> const & next\n                , long & in_off\n                , long & out_off\n                , double * in_dump\n                , double * out_dump\n                , long & in_size\n                , long & out_size\n                , long & samples\n                )\n  {\n    std::vector<double> input = construct_input_vector(p,prev);\n    std::vector<double> output = construct_output_vector(p,next);\n    in_size = input.size();\n    out_size = output.size();\n    {\n      std::cout << symb << \":\";\n      std::cout << p.date << \":\";\n      for(int i=0;i<output.size();i++)\n      {\n        std::cout << ((output[i]>0.5)?\"1\":\"0\");\n        out_dump[out_off+i] = ((output[i]));\n      }\n      std::cout << \":\";\n      for(int i=0;i<input.size();i++)\n      {\n        if(i%num_bits==0&&i>0)std::cout << \"|\";\n        std::cout << ((input[i]>0.5)?\"1\":\"0\");\n        in_dump[in_off+i] = ((input[i]));\n      }\n      std::cout << std::endl;\n      in_off += in_size;\n      out_off += out_size;\n      samples ++;\n      num_elems = samples;\n    }\n  }\n};\n\nstruct mrbm_params\n{\n\n  long batch_iter;\n  long num_batch;\n  long total_n;\n  long n;\n  double epsilon;\n  long n_iter;\n  long n_cd;\n\n  long v;\n  long h;\n\n  std::vector<long> input_sizes;\n\n  std::vector<long> output_sizes;\n\n  std::vector<long> input_iters;\n\n  std::vector<long> output_iters;\n\n  long bottleneck_iters;\n\n  mrbm_params(Robot* robot,int range,long n_batch,long n_samples,double c_epsilon)\n  {\n\n    v  = robot->get_input_size(range);\n    h  = robot->get_output_size(range);\n\n    n_cd = 1;\n    num_batch = n_batch;\n    batch_iter = 1;\n    n = n_samples;\n    total_n = n_samples;\n    epsilon = c_epsilon;\n    n_iter = 1000;\n\n    input_sizes.push_back(v);\n    input_sizes.push_back(v);\n    input_sizes.push_back(v);\n    input_sizes.push_back(v);\n\n    output_sizes.push_back(h);\n\n    for(int i=0;i+1<input_sizes.size();i++)\n        input_iters.push_back(n_iter);\n\n    for(int i=0;i+1<output_sizes.size();i++)\n        output_iters.push_back(n_iter);\n\n    bottleneck_iters = n_iter;\n\n  }\n};\n\nvoid run_mrbm(mrbm_params p,double * dat_in,double * dat_out,double * prd_out)\n{\n  int cd = 0;\n  while(true)\n  {\n    if(mrbm == NULL)\n    {\n      mrbm = new mRBM(p.input_sizes[0],p.output_sizes[0]);\n      for(long i=0;i+1<p.input_sizes.size();i++)\n      {\n        mrbm->input_branch.push_back(new DataUnit(p.input_sizes[i],p.input_sizes[i+1],p.input_iters[i]));\n      }\n      for(long i=0;i+1<p.output_sizes.size();i++)\n      {\n        mrbm->output_branch.push_back(new DataUnit(p.output_sizes[i],p.output_sizes[i+1],p.output_iters[i]));\n      }\n      long bottle_neck_num = (p.input_sizes[p.input_sizes.size()-1]+p.output_sizes[p.output_sizes.size()-1]);\n      mrbm->bottle_neck = new DataUnit(p.input_sizes[p.input_sizes.size()-1]+p.output_sizes[p.output_sizes.size()-1],bottle_neck_num,p.bottleneck_iters);\n    }\n    mrbm->train(p.v,p.h,p.num_batch,p.total_n,(int)(p.n_cd+0.05*cd),p.epsilon/(1+0.05*cd),dat_in,dat_out);\n    mrbm->model_all(p.total_n,dat_in,prd_out);\n    mrbm->compare_all(p.total_n,dat_out,prd_out);\n    cd ++;\n  }\n}\n\nRobot * robot = new Robot();\n\nint width  = 1000;//1800;\nint height = 1000;\n\nint mouse_x = 0;\nint mouse_y = 0;\n\nint stock_index = 0;\n\nint start_index = -1;\nint   end_index = -1;\nbool pick_start_index = false;\nbool   pick_end_index = false;\n\nvoid drawString (void * font, char const *s, double x, double y, double z)\n{\n     unsigned int i;\n     glRasterPos3f(x, y, z);\n     for (i = 0; i < strlen (s); i++)\n     {\n         glutBitmapCharacter (font, s[i]);\n     }\n}\n\nUser * user = NULL;\n\nlong learning_samples = 0;\nlong test_learning_samples = 0;\nint  input_learning_range = 6;\nint output_learning_range = 6;\nint synthetic_range = 26;\nint learning_offset = 1;\nint learning_num = 600;\nint test_learning_num = 100;\ndouble *  in_dump = NULL;\ndouble * out_dump = NULL;\ndouble *  in_test = NULL;\ndouble * out_test = NULL;\n\nPerceptron<double> * perceptron = NULL;\nPerceptron<double> * perceptron_tmp = NULL;\n\nvoid reconstruct(std::vector<price> & prices,int index)\n{\n    if ( perceptron != NULL \n      && in_dump \n      && out_dump \n      && prices[index].synthetic == false \n      && index+     synthetic_range*learning_offset<prices.size()+1\n      && index-input_learning_range*learning_offset>=0\n       )\n    {\n      int  in_size = robot-> get_input_size( input_learning_range);\n      int out_size = robot->get_output_size(output_learning_range);\n      {\n        for(int j=0;j+1<synthetic_range;j++)\n        {\n            double * in = new double[in_size];\n            //std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n            for(int i=index+1+j,k=0;k<input_learning_range;i-=learning_offset,k++)\n            {\n                in[k] = 100*((prices[i].synthetic)?prices[i].prct_prediction:prices[i].prct_change);\n                if(in[k]<-2)in[k]=-2;\n                if(in[k]> 2)in[k]= 2;\n                in[k]+=2;\n                in[k]/=4;\n                //std::cout << \"k=\" << k << \"\\tin=\" << in[k] << std::endl;\n            }\n            double val = 0.5;\n            double tmp = 0;\n            double tru = in[0];\n            double min_D = tru-delta_D;\n            double max_D = tru+delta_D;\n            //if(prices[index+j*learning_offset].synthetic)\n            {\n              min_D = 0.3;\n              max_D = 0.7;\n            }\n            {\n                double err = 1e12;\n                for(double D=min_D;D<=max_D;D+=0.05)\n                {\n                  double * tmp_in = new double[in_size];\n                  for(int i=0;i<in_size;i++)\n                  {\n                    tmp_in[i] = in[i];\n                  }\n                  tmp_in[0] = D;\n                  for(int iter=0;iter<100;iter++)\n                  {\n                    double * dat = perceptron->model(in_size,out_size,&tmp_in[0]);\n                    for(int i=0;i<in_size;i++)\n                    {\n                      tmp_in[i] = dat[i];\n                    }\n                    delete [] dat;\n                    dat = NULL;\n                  }\n                  double dat_err = 0;\n                  for(int i=1;i<out_size;i++)\n                  {\n                    dat_err += fabs(in[i] - tmp_in[i]);\n                  }\n                  {\n                    dat_err += fabs(D - tmp_in[0]);\n                  }\n                  if(dat_err<err)\n                  {\n                    err=dat_err;\n                    val=(prices[index+1+j].synthetic)?tmp_in[0]:in[0];\n                  }\n                  delete [] tmp_in;\n                  tmp_in = NULL;\n                }\n            }\n            //val = in[0];\n            //std::cout << \"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\" << std::endl;\n            //std::cout << \"j=\" << j << \"\\tdat=\" << dat[0] << std::endl;\n            //std::cout << \"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\" << std::endl;\n            val -= 0.5;\n            val *= 4;\n            val *= 0.01;\n            prices[index+j*learning_offset+1]. prct_prediction = val;\n            prices[index+j*learning_offset+1].close_prediction = (j==0)\n                                                             ?  prices[index+j*learning_offset].close           *(1+val)\n                                                             :  prices[index+j*learning_offset].close_prediction*(1+val)\n                                                             ;\n            delete [] in;\n            in = NULL;\n        }\n      }\n    }\n}\n\nvoid reconstruct_rbm(std::vector<price> & prices,int index)\n{\n    if ( perceptron != NULL \n      && in_dump \n      && out_dump \n      && prices[index].synthetic == false \n      && index+     synthetic_range*learning_offset<prices.size() \n      && index-input_learning_range*learning_offset>=0\n       )\n    {\n      int  in_size = robot-> get_input_size( input_learning_range);\n      int out_size = robot->get_output_size(output_learning_range);\n      {\n        {\n            double * in = new double[in_size];\n            for(int i=index,k=0;k<input_learning_range;i-=learning_offset,k++)\n            {\n                in[k] = 100*((prices[i].synthetic)?prices[i].prct_prediction:prices[i].prct_change);\n                if(in[k]<-2)in[k]=-2;\n                if(in[k]> 2)in[k]= 2;\n                in[k]+=2;\n                in[k]/=4;\n            }\n            double * dat = perceptron->model(in_size,out_size,&in[0]);\n            //dat[0] -= 0.5;\n            //dat[0] *= 4;\n            //dat[0] *= 0.01;\n            //for(int k=0;k<perceptron->n_nodes.size();k++)\n            //{\n            //  std::cout << k << \"\\t\" << perceptron->n_nodes[k] << \"\\t\" << perceptron->n_layers/2 << std::endl;\n            //}\n            prices[index].auto_encoding_x = 2*perceptron->activation_values1[perceptron->n_layers/2][0] - 1;\n            prices[index].auto_encoding_y = 2*perceptron->activation_values1[perceptron->n_layers/2][1] - 1;\n            delete [] dat;\n            delete [] in;\n            dat = NULL;\n            in = NULL;\n        }\n      }\n    }\n}\n\nvoid dump_autoencoding_to_file(std::string filename,bool quiet=false)\n{\n    if(!quiet)\n      std::cout << \"dump autoencoding to file:\" << filename << std::endl;\n    ofstream myfile (filename.c_str());\n    if (myfile.is_open())\n    {\n      for(int stock=0;stock<prices.size();stock++)\n      {\n        for(int i=0;i<prices[stock].size();i++)\n        {\n          reconstruct_rbm(prices[stock],i);\n          myfile << prices[stock][i].auto_encoding_x << \" \" << prices[stock][i].auto_encoding_y << \" \" << stock << \" \" << i << std::endl;\n        }\n      }\n      myfile.close();\n    }\n    else\n    {\n      cout << \"Unable to open file: \" << filename << std::endl;\n      exit(1);\n    }\n\n}\n\nvoid draw_charts()\n{\n  glColor3f(1,1,1);\n  if(!game_mode)drawString(GLUT_BITMAP_HELVETICA_18,symbols[stock_index].c_str(),-0.6,0.9,0);\n  if(user&&game_mode)\n  {\n    {\n      glColor3f(1,1,1);\n      std::stringstream ss;\n      ss << \"Cash: $\" << user->cash;\n      drawString(GLUT_BITMAP_HELVETICA_18,ss.str().c_str(),-0.6,0.85,0);\n    }\n    std::map<int,Symbol>::iterator it = user->rstocks.begin();\n    int i = 0;\n    while(it != user->rstocks.end())\n    {\n      if(it->second.index == stock_index&&game_mode)glColor3f(0,1,0);else glColor3f(1,1,1);\n      std::stringstream ss;\n      ss << it->second.name << \"   \" << it->second.units;\n      drawString(GLUT_BITMAP_HELVETICA_18,ss.str().c_str(),-0.6,0.8-i*0.05,0);\n      ++it;\n      ++i;\n    }\n    {\n      glColor3f(1,1,1);\n      std::stringstream ss;\n      ss << \"expected return: $\" << user->expected_return(end_date_index);\n      drawString(GLUT_BITMAP_HELVETICA_18,ss.str().c_str(),-0.6,0.8-i*0.05,0);\n      ++i;\n    }\n    {\n      glColor3f(1,1,1);\n      std::stringstream ss;\n      ss << \"percent return: \" << (100*(user->expected_return(end_date_index)/user->prev_cash) - 100) << \"%\";\n      drawString(GLUT_BITMAP_HELVETICA_18,ss.str().c_str(),-0.6,0.8-i*0.05,0);\n    }\n  }\n  drawString(GLUT_BITMAP_HELVETICA_18,\"Volume\",-1,-0.10,0);\n  drawString(GLUT_BITMAP_HELVETICA_18,\"MACD\",-1,-0.30,0);\n  drawString(GLUT_BITMAP_HELVETICA_18,\"RSI\",-1,-0.50,0);\n  drawString(GLUT_BITMAP_HELVETICA_18,\"MFI\",-1,-0.70,0);\n  drawString(GLUT_BITMAP_HELVETICA_18,\"CCI\",-1,-0.90,0);\n  int n = start_date_index - end_date_index;\n  if(n>=prices[stock_index].size())\n  {\n    n = prices[stock_index].size()-1;\n  }\n  int size = prices[stock_index].size()-1-end_date_index;\n  double open_price = 0;\n  double close_price = 0;\n  double high_price = 0;\n  double low_price = 0;\n  int volume = 0;\n  std::string date = \"\";\n  int price_index = (int)((size-n)+(((double)mouse_x/width)*(n)));\n  reconstruct(prices[stock_index],price_index);\n  //reconstruct_rbm(prices[stock_index],price_index);\n  if(price_index>=0&&price_index<prices[stock_index].size())\n  {\n    open_price  = prices[stock_index][prices[stock_index].size()-1].open;\n    close_price = prices[stock_index][prices[stock_index].size()-1].close;\n    high_price  = prices[stock_index][prices[stock_index].size()-1].high;\n    low_price   = prices[stock_index][prices[stock_index].size()-1].low;\n    volume      = prices[stock_index][prices[stock_index].size()-1].volume;\n    date        = prices[stock_index][prices[stock_index].size()-1].date;\n    // Current\n    std::stringstream ss_date;\n    ss_date << date << std::endl;\n    std::stringstream ss_open_price;\n    ss_open_price << \"Open:\" << open_price << std::endl;\n    std::stringstream ss_close_price;\n    ss_close_price << \"Close:\" << close_price << std::endl;\n    std::stringstream ss_low_price;\n    ss_low_price << \"Low:\" << low_price << std::endl;\n    std::stringstream ss_high_price;\n    ss_high_price << \"High:\" << high_price << std::endl;\n    std::stringstream ss_volume;\n    ss_volume << \"Volume:\" << volume << std::endl;\n    drawString(GLUT_BITMAP_HELVETICA_18,ss_date.str().c_str()       ,-1.0f,-1.0f+0.25f,0);\n    drawString(GLUT_BITMAP_HELVETICA_18,ss_open_price.str().c_str() ,-1.0f,-1.0f+0.20f,0);\n    drawString(GLUT_BITMAP_HELVETICA_18,ss_close_price.str().c_str(),-1.0f,-1.0f+0.15f,0);\n    drawString(GLUT_BITMAP_HELVETICA_18,ss_high_price.str().c_str() ,-1.0f,-1.0f+0.10f,0);\n    drawString(GLUT_BITMAP_HELVETICA_18,ss_low_price.str().c_str()  ,-1.0f,-1.0f+0.05f,0);\n    drawString(GLUT_BITMAP_HELVETICA_18,ss_volume.str().c_str()     ,-1.0f,-1.0f+0.00f,0);\n  }\n  if(price_index>=0&&price_index<prices[stock_index].size()&&prices[stock_index][price_index].synthetic==false)\n  {\n    open_price  = prices[stock_index][price_index].open;\n    close_price = prices[stock_index][price_index].close;\n    high_price  = prices[stock_index][price_index].high;\n    low_price   = prices[stock_index][price_index].low;\n    volume      = prices[stock_index][price_index].volume;\n    date        = prices[stock_index][price_index].date;\n    // Historical\n    std::stringstream ss_date;\n    ss_date << date << std::endl;\n    std::stringstream ss_open_price;\n    ss_open_price << \"Open:\" << open_price << std::endl;\n    std::stringstream ss_close_price;\n    ss_close_price << \"Close:\" << close_price << std::endl;\n    std::stringstream ss_low_price;\n    ss_low_price << \"Low:\" << low_price << std::endl;\n    std::stringstream ss_high_price;\n    ss_high_price << \"High:\" << high_price << std::endl;\n    std::stringstream ss_volume;\n    ss_volume << \"Volume:\" << volume << std::endl;\n    drawString(GLUT_BITMAP_HELVETICA_18,ss_date.str().c_str()       ,-1.0f-0.15f+2.0f*mouse_x/width,1.0f-2.0f*mouse_y/height+0.25f,0);\n    drawString(GLUT_BITMAP_HELVETICA_18,ss_open_price.str().c_str() ,-1.0f-0.15f+2.0f*mouse_x/width,1.0f-2.0f*mouse_y/height+0.20f,0);\n    drawString(GLUT_BITMAP_HELVETICA_18,ss_close_price.str().c_str(),-1.0f-0.15f+2.0f*mouse_x/width,1.0f-2.0f*mouse_y/height+0.15f,0);\n    drawString(GLUT_BITMAP_HELVETICA_18,ss_high_price.str().c_str() ,-1.0f-0.15f+2.0f*mouse_x/width,1.0f-2.0f*mouse_y/height+0.10f,0);\n    drawString(GLUT_BITMAP_HELVETICA_18,ss_low_price.str().c_str()  ,-1.0f-0.15f+2.0f*mouse_x/width,1.0f-2.0f*mouse_y/height+0.05f,0);\n    drawString(GLUT_BITMAP_HELVETICA_18,ss_volume.str().c_str()     ,-1.0f-0.15f+2.0f*mouse_x/width,1.0f-2.0f*mouse_y/height+0.00f,0);\n  }\n  VolumeByPrice vol_by_price;\n  vol_by_price.create_bins(prices[stock_index],12,(int)(size-n),size);\n  //double factor = 2.0f/n;\n  double factor = 2.0f/(start_date_index - end_date_index + 1);\n  double vfactor100 = 2.0f/100.0f;\n  double vfactor400 = 2.0f/600.0f;\n  double Bollinger_sigma = 1.0f;\n  double vmin    = double(std::min_element(prices[stock_index].begin()+(int)(size-n),prices[stock_index].begin()+(int)(size),comparator_low )->low)/1.05f;\n  double vmax    = double(std::max_element(prices[stock_index].begin()+(int)(size-n),prices[stock_index].begin()+(int)(size),comparator_high)->high)*1.05f;\n  double MACD_min= double(std::min_element(prices[stock_index].begin()+(int)(size-n),prices[stock_index].begin()+(int)(size),comparator_MACD)->MACD_dline);\n  double MACD_max= double(std::max_element(prices[stock_index].begin()+(int)(size-n),prices[stock_index].begin()+(int)(size),comparator_MACD)->MACD_dline);\n  double MACD_cmp= max(fabs(MACD_min),fabs(MACD_max));\n  double auto_min= 0;\n  double auto_max= 1;\n  double auto_cmp= 1;\n  //std::cout << MACD_min << \"\\t\" << MACD_max << std::endl;\n  double vfactor = 2.0f/(vmax-vmin);\n  double vfactor_volume = 2.0f/double(std::max_element(prices[stock_index].begin()+(int)(size-n),prices[stock_index].begin()+(int)(size),comparator_volume)->volume);\n\n  glBegin(GL_LINES);\n  // mouse \n  glColor3f(1,1,1);\n  glVertex3f( 100.0f+-1.0f+2.0f*mouse_x/width,1.0f-2.0f*mouse_y/height,0);\n  glVertex3f(-100.0f+-1.0f+2.0f*mouse_x/width,1.0f-2.0f*mouse_y/height,0);\n  glVertex3f(-1.0f+2.0f*mouse_x/width, 100.0f+1.0f-2.0f*mouse_y/height,0);\n  glVertex3f(-1.0f+2.0f*mouse_x/width,-100.0f+1.0f-2.0f*mouse_y/height,0);\n  glEnd();\n\n  if(pick_start_index)\n  {\n    start_index = price_index;\n    pick_start_index = false;\n  }\n  if(pick_end_index)\n  {\n    end_index = price_index;\n    pick_end_index = false;\n  }\n  double chart_size = 0.05f;\n  glBegin(GL_LINES);\n  // MACD spiral axis \n  glColor3f(1.0,1.0,1.0);\n  glVertex3f(-chart_size+ chart_size+-1.0f+2.0f*mouse_x/width,-chart_size            +1.0f-2.0f*mouse_y/height,0);\n  glVertex3f(-chart_size+-chart_size+-1.0f+2.0f*mouse_x/width,-chart_size            +1.0f-2.0f*mouse_y/height,0);\n  glVertex3f(-chart_size            +-1.0f+2.0f*mouse_x/width,-chart_size+ chart_size+1.0f-2.0f*mouse_y/height,0);\n  glVertex3f(-chart_size            +-1.0f+2.0f*mouse_x/width,-chart_size+-chart_size+1.0f-2.0f*mouse_y/height,0);\n  glEnd();\n  glBegin(GL_LINES);\n  // MACD current state\n  glColor3f(1.0,1.0,1.0);\n  glVertex3f(-chart_size+chart_size*prices[stock_index][price_index].MACD_dline/MACD_cmp+ 0.01f+-1.0f+2.0f*mouse_x/width,-chart_size+chart_size*(prices[stock_index][price_index].MACD_dsignal)/MACD_cmp       +1.0f-2.0f*mouse_y/height,0);\n  glVertex3f(-chart_size+chart_size*prices[stock_index][price_index].MACD_dline/MACD_cmp+-0.01f+-1.0f+2.0f*mouse_x/width,-chart_size+chart_size*(prices[stock_index][price_index].MACD_dsignal)/MACD_cmp       +1.0f-2.0f*mouse_y/height,0);\n  glVertex3f(-chart_size+chart_size*prices[stock_index][price_index].MACD_dline/MACD_cmp       +-1.0f+2.0f*mouse_x/width,-chart_size+chart_size*(prices[stock_index][price_index].MACD_dsignal)/MACD_cmp+ 0.01f+1.0f-2.0f*mouse_y/height,0);\n  glVertex3f(-chart_size+chart_size*prices[stock_index][price_index].MACD_dline/MACD_cmp       +-1.0f+2.0f*mouse_x/width,-chart_size+chart_size*(prices[stock_index][price_index].MACD_dsignal)/MACD_cmp+-0.01f+1.0f-2.0f*mouse_y/height,0);\n  glEnd();\n  glBegin(GL_LINES);\n  glColor3f(1.0,1.0,0.0);\n  glVertex3f(-chart_size+chart_size*prices[stock_index][price_index].auto_encoding_x/auto_cmp+ 0.01f+-1.0f+2.0f*mouse_x/width,-chart_size+chart_size*prices[stock_index][price_index].auto_encoding_y/auto_cmp       +1.0f-2.0f*mouse_y/height,0);\n  glVertex3f(-chart_size+chart_size*prices[stock_index][price_index].auto_encoding_x/auto_cmp+-0.01f+-1.0f+2.0f*mouse_x/width,-chart_size+chart_size*prices[stock_index][price_index].auto_encoding_y/auto_cmp       +1.0f-2.0f*mouse_y/height,0);\n  glVertex3f(-chart_size+chart_size*prices[stock_index][price_index].auto_encoding_x/auto_cmp       +-1.0f+2.0f*mouse_x/width,-chart_size+chart_size*prices[stock_index][price_index].auto_encoding_y/auto_cmp+ 0.01f+1.0f-2.0f*mouse_y/height,0);\n  glVertex3f(-chart_size+chart_size*prices[stock_index][price_index].auto_encoding_x/auto_cmp       +-1.0f+2.0f*mouse_x/width,-chart_size+chart_size*prices[stock_index][price_index].auto_encoding_y/auto_cmp+-0.01f+1.0f-2.0f*mouse_y/height,0);\n  glEnd();\n  glBegin(GL_LINES);\n  // MACD spiral\n  for(int i=1;i<n;i++)\n  {\n    glColor4f(1,1,1,.2f);\n    if(size-i+1>start_index && size-i+1<end_index)\n    {\n      glColor4f(1,1,1,0.5f);\n    }\n    glVertex3f(-chart_size+chart_size*prices[stock_index][size-i+1].MACD_dline/MACD_cmp+-1.0f+2.0f*mouse_x/width,-chart_size+chart_size*(prices[stock_index][size-i+1].MACD_dsignal)/MACD_cmp+1.0f-2.0f*mouse_y/height,0);\n    glVertex3f(-chart_size+chart_size*prices[stock_index][size-i  ].MACD_dline/MACD_cmp+-1.0f+2.0f*mouse_x/width,-chart_size+chart_size*(prices[stock_index][size-i  ].MACD_dsignal)/MACD_cmp+1.0f-2.0f*mouse_y/height,0);\n  }\n  glEnd();\n\n  glBegin(GL_QUADS);\n  for(int i=0;i<vol_by_price.bins.size();i++)\n  {\n    glColor3f(1,0,0);\n    glVertex3f(-1.0f                                   , 0.0f+0.5f*vfactor*(vol_by_price.bins[i].price_min-vmin) ,0);\n    glVertex3f(-1.0f+0.25f*vol_by_price.bins[i].sum_neg, 0.0f+0.5f*vfactor*(vol_by_price.bins[i].price_min-vmin) ,0);\n    glVertex3f(-1.0f+0.25f*vol_by_price.bins[i].sum_neg, 0.0f+0.5f*vfactor*(vol_by_price.bins[i].price_max-vmin) ,0);\n    glVertex3f(-1.0f                                   , 0.0f+0.5f*vfactor*(vol_by_price.bins[i].price_max-vmin) ,0);\n    glColor3f(0,1,0);\n    glVertex3f(-1.0f+0.25f*vol_by_price.bins[i].sum_neg, 0.0f+0.5f*vfactor*(vol_by_price.bins[i].price_min-vmin) ,0);\n    glVertex3f(-1.0f+0.25f*vol_by_price.bins[i].sum    , 0.0f+0.5f*vfactor*(vol_by_price.bins[i].price_min-vmin) ,0);\n    glVertex3f(-1.0f+0.25f*vol_by_price.bins[i].sum    , 0.0f+0.5f*vfactor*(vol_by_price.bins[i].price_max-vmin) ,0);\n    glVertex3f(-1.0f+0.25f*vol_by_price.bins[i].sum_neg, 0.0f+0.5f*vfactor*(vol_by_price.bins[i].price_max-vmin) ,0);\n  }\n  glEnd();\n\n  glBegin(GL_LINES);\n  for(int i=1,j=0;i<n;i++,j++)\n  if(!prices[stock_index][size-i+1].synthetic)\n  {\n    glColor3f(1,1,1);\n\n    // volume\n    glVertex3f(1.0f- j   *factor,-0.2f+0.1f*vfactor_volume*prices[stock_index][size-i+1].volume,0);\n    glVertex3f(1.0f-(j+1)*factor,-0.2f+0.1f*vfactor_volume*prices[stock_index][size-i  ].volume,0);\n    glVertex3f(1.0f- j   *factor,-0.2f+0.1f*vfactor_volume*prices[stock_index][size-i+1].EMAV  ,0);\n    glVertex3f(1.0f-(j+1)*factor,-0.2f+0.1f*vfactor_volume*prices[stock_index][size-i  ].EMAV  ,0);\n\n    // MACD\n    glVertex3f(1.0f- j   *factor,-0.4f+0.1f*vfactor400*(300+100.0f*prices[stock_index][size-i+1].MACD_dline/MACD_cmp),0);\n    glVertex3f(1.0f-(j+1)*factor,-0.4f+0.1f*vfactor400*(300+100.0f*prices[stock_index][size-i  ].MACD_dline/MACD_cmp),0);\n    glColor3f(1,0,0);\n    glVertex3f(1.0f- j   *factor,-0.4f+0.1f*vfactor400*(300+100.0f*prices[stock_index][size-i+1].MACD_dsignal/MACD_cmp),0);\n    glVertex3f(1.0f-(j+1)*factor,-0.4f+0.1f*vfactor400*(300+100.0f*prices[stock_index][size-i  ].MACD_dsignal/MACD_cmp),0);\n    glColor3f(1,1,1);\n    glVertex3f(1.0f- j   *factor,-0.4f+0.1f*vfactor400*(300+0),0);\n    glVertex3f(1.0f-(j+1)*factor,-0.4f+0.1f*vfactor400*(300+0),0);\n\n    // RSI\n    glVertex3f(1.0f- j   *factor,-0.6f+0.1f*vfactor100*prices[stock_index][size-i+1].RSI,0);\n    glVertex3f(1.0f-(j+1)*factor,-0.6f+0.1f*vfactor100*prices[stock_index][size-i  ].RSI,0);\n    glVertex3f(1.0f- j   *factor,-0.6f+0.1f*vfactor100*30,0);\n    glVertex3f(1.0f-(j+1)*factor,-0.6f+0.1f*vfactor100*30,0);\n    glVertex3f(1.0f- j   *factor,-0.6f+0.1f*vfactor100*50,0);\n    glVertex3f(1.0f-(j+1)*factor,-0.6f+0.1f*vfactor100*50,0);\n    glVertex3f(1.0f- j   *factor,-0.6f+0.1f*vfactor100*70,0);\n    glVertex3f(1.0f-(j+1)*factor,-0.6f+0.1f*vfactor100*70,0);\n\n    // MFI\n    glVertex3f(1.0f- j   *factor,-0.8f+0.1f*vfactor100*prices[stock_index][size-i+1].MFI,0);\n    glVertex3f(1.0f-(j+1)*factor,-0.8f+0.1f*vfactor100*prices[stock_index][size-i  ].MFI,0);\n    glVertex3f(1.0f- j   *factor,-0.8f+0.1f*vfactor100*30,0);\n    glVertex3f(1.0f-(j+1)*factor,-0.8f+0.1f*vfactor100*30,0);\n    glVertex3f(1.0f- j   *factor,-0.8f+0.1f*vfactor100*50,0);\n    glVertex3f(1.0f-(j+1)*factor,-0.8f+0.1f*vfactor100*50,0);\n    glVertex3f(1.0f- j   *factor,-0.8f+0.1f*vfactor100*70,0);\n    glVertex3f(1.0f-(j+1)*factor,-0.8f+0.1f*vfactor100*70,0);\n\n    // CCI\n    glVertex3f(1.0f- j   *factor,-1.0f+0.1f*vfactor400*(300+prices[stock_index][size-i+1].CCI),0);\n    glVertex3f(1.0f-(j+1)*factor,-1.0f+0.1f*vfactor400*(300+prices[stock_index][size-i  ].CCI),0);\n    glVertex3f(1.0f- j   *factor,-1.0f+0.1f*vfactor400*(300+ 100),0);\n    glVertex3f(1.0f-(j+1)*factor,-1.0f+0.1f*vfactor400*(300+ 100),0);\n    glVertex3f(1.0f- j   *factor,-1.0f+0.1f*vfactor400*(300+   0),0);\n    glVertex3f(1.0f-(j+1)*factor,-1.0f+0.1f*vfactor400*(300+   0),0);\n    glVertex3f(1.0f- j   *factor,-1.0f+0.1f*vfactor400*(300+-100),0);\n    glVertex3f(1.0f-(j+1)*factor,-1.0f+0.1f*vfactor400*(300+-100),0);\n  }\n  glEnd();\n\n  glBegin(GL_QUADS);\n  for(int i=1,j=0;i<n;i++,j++)\n  if(!prices[stock_index][size-i+1].synthetic)\n  {\n    if(prices[stock_index][size-i+1].close>prices[stock_index][size-i].close)\n    {\n      glColor3f(0,1,0);\n    }\n    else\n    {\n      glColor3f(1,0,0);\n    }\n    // volume\n    glVertex3f(1.0f-(j-0.45f)*factor,-0.25f+0.125f*vfactor_volume*prices[stock_index][size-i+1].volume,0);\n    glVertex3f(1.0f-(j+0.45f)*factor,-0.25f+0.125f*vfactor_volume*prices[stock_index][size-i+1].volume,0);\n    glVertex3f(1.0f-(j+0.45f)*factor,-0.25f,0);\n    glVertex3f(1.0f-(j-0.45f)*factor,-0.25f,0);\n  }\n  glEnd();\n\n  glBegin(GL_QUADS);\n  {\n    glColor3f(0,0,0);\n    glVertex3f(-1,-1,0);\n    glVertex3f(1,-1,0);\n    glVertex3f(1,0,0);\n    glVertex3f(-1,0,0);\n  }\n  glEnd();\n    \n  glBegin(GL_LINES);\n  for(int i=1,j=0;i<n;i++,j++)\n  if(!prices[stock_index][size-i+1].synthetic)\n  {\n    if(prices[stock_index][size-i+1].prediction_confidence>0.5)\n    {\n        glColor3f(1,1,0);\n    }\n    else\n    {\n        glColor3f(.1,.1,0);\n    }\n    // price\n    glVertex3f(1.0f- j   *factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i+1].close_prediction-vmin) ,0);\n    glVertex3f(1.0f-(j+1)*factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i  ].close_prediction-vmin) ,0);\n    glColor3f(1,1,1);\n    // price\n    glVertex3f(1.0f- j   *factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i+1].close-vmin) ,0);\n    glVertex3f(1.0f-(j+1)*factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i  ].close-vmin) ,0);\n\n    glVertex3f(1.0f- j   *factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i+1].ema_12-vmin) ,0);\n    glVertex3f(1.0f-(j+1)*factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i  ].ema_12-vmin) ,0);\n    for(int b=1;b<=3;b++)\n    {\n      glColor3f(1.0f/(1+b),1.0f/(1+b),1.0f/(1+b));\n      glVertex3f(1.0f- j   *factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i+1].ema_12+b*Bollinger_sigma*prices[stock_index][size-i+1].ems_12-vmin) ,0);\n      glVertex3f(1.0f-(j+1)*factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i  ].ema_12+b*Bollinger_sigma*prices[stock_index][size-i  ].ems_12-vmin) ,0);\n      glVertex3f(1.0f- j   *factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i+1].ema_12-b*Bollinger_sigma*prices[stock_index][size-i+1].ems_12-vmin) ,0);\n      glVertex3f(1.0f-(j+1)*factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i  ].ema_12-b*Bollinger_sigma*prices[stock_index][size-i  ].ems_12-vmin) ,0);\n    }\n    \n    //glVertex3f(1.0f- j   *factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i+1].ema_26-vmin) ,0);\n    //glVertex3f(1.0f-(j+1)*factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i  ].ema_26-vmin) ,0);\n    //for(int b=1;b<=3;b++)\n    //{\n    //  glColor3f(1.0f/(1+b),1.0f/(1+b),1.0f/(1+b));\n    //  glVertex3f(1.0f- j   *factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i+1].ema_26+b*Bollinger_sigma*prices[stock_index][size-i+1].ems_26-vmin) ,0);\n    //  glVertex3f(1.0f-(j+1)*factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i  ].ema_26+b*Bollinger_sigma*prices[stock_index][size-i  ].ems_26-vmin) ,0);\n    //  glVertex3f(1.0f- j   *factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i+1].ema_26-b*Bollinger_sigma*prices[stock_index][size-i+1].ems_26-vmin) ,0);\n    //  glVertex3f(1.0f-(j+1)*factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i  ].ema_26-b*Bollinger_sigma*prices[stock_index][size-i  ].ems_26-vmin) ,0);\n    //}\n    \n    //glVertex3f(1.0f- j   *factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i+1].ema_50-vmin) ,0);\n    //glVertex3f(1.0f-(j+1)*factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i  ].ema_50-vmin) ,0);\n    //for(int b=1;b<=3;b++)\n    //{\n    //  glColor3f(1.0f/(1+b),1.0f/(1+b),1.0f/(1+b));\n    //  glVertex3f(1.0f- j   *factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i+1].ema_50+b*Bollinger_sigma*prices[stock_index][size-i+1].ems_50-vmin) ,0);\n    //  glVertex3f(1.0f-(j+1)*factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i  ].ema_50+b*Bollinger_sigma*prices[stock_index][size-i  ].ems_50-vmin) ,0);\n    //  glVertex3f(1.0f- j   *factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i+1].ema_50-b*Bollinger_sigma*prices[stock_index][size-i+1].ems_50-vmin) ,0);\n    //  glVertex3f(1.0f-(j+1)*factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i  ].ema_50-b*Bollinger_sigma*prices[stock_index][size-i  ].ems_50-vmin) ,0);\n    //}\n  }\n  else\n  {\n    if(prices[stock_index][size-i+1].prediction_confidence>0.5)\n    {\n        glColor3f(1,1,0);\n    }\n    else\n    {\n        glColor3f(.1,.1,0);\n    }\n    // price\n    glVertex3f(1.0f- j   *factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i+1].close_prediction-vmin) ,0);\n    glVertex3f(1.0f-(j+1)*factor, 0.0f+0.5f*vfactor       *(prices[stock_index][size-i  ].close_prediction-vmin) ,0);\n  } \n  glEnd();\n\n  glBegin(GL_QUADS);\n  for(int i=1,j=0;i<n;i++,j++)\n  if(!prices[stock_index][size-i+1].synthetic)\n  {\n    if(size-i+1 == price_index)\n    {\n      if(prices[stock_index][size-i+1].close>prices[stock_index][size-i+1].open)\n      {\n        glColor3f(0,1,0);\n      }\n      else\n      {\n        glColor3f(1,0,0);\n      }\n    }\n    else\n    {\n      if(prices[stock_index][size-i+1].close>prices[stock_index][size-i+1].open)\n      {\n        glColor3f(0,1,1);\n      }\n      else\n      {\n        glColor3f(1,0.5f,0);\n      }\n    }\n    // price\n    glVertex3f(1.0f-(j-0.45f)*factor, 0.0f+0.5f*vfactor*(prices[stock_index][size-i+1].open -vmin) ,0);\n    glVertex3f(1.0f-(j+0.45f)*factor, 0.0f+0.5f*vfactor*(prices[stock_index][size-i+1].open -vmin) ,0);\n    glVertex3f(1.0f-(j+0.45f)*factor, 0.0f+0.5f*vfactor*(prices[stock_index][size-i+1].close-vmin) ,0);\n    glVertex3f(1.0f-(j-0.45f)*factor, 0.0f+0.5f*vfactor*(prices[stock_index][size-i+1].close-vmin) ,0);\n\n    glVertex3f(1.0f-(j-0.05f)*factor, 0.0f+0.5f*vfactor*(prices[stock_index][size-i+1].low  -vmin) ,0);\n    glVertex3f(1.0f-(j+0.05f)*factor, 0.0f+0.5f*vfactor*(prices[stock_index][size-i+1].low  -vmin) ,0);\n    glVertex3f(1.0f-(j+0.05f)*factor, 0.0f+0.5f*vfactor*(prices[stock_index][size-i+1].high -vmin) ,0);\n    glVertex3f(1.0f-(j-0.05f)*factor, 0.0f+0.5f*vfactor*(prices[stock_index][size-i+1].high -vmin) ,0);\n  }\n  glEnd();\n\n}\n\nlong construct_learning_data(int start,int num,int offset,double * in_dump,double * out_dump)\n{\n  std::cout << \"construct learning data\" << std::endl;\n  long in_off = 0;\n  long out_off = 0;\n  long in_size = 0;\n  long out_size = 0;\n  long samples = 0;\n  for(int stock_index=0;stock_index<prices.size();stock_index++)\n  {\n    if(prices[stock_index].size()>num-offset*synthetic_range)\n    {\n      long size = prices[stock_index].size()-1;\n      for(long ind=(start+input_learning_range)*offset;ind<num;ind++)\n      {\n        bool go = true;\n        std::vector<price> prev_prcs;\n        for(long k=0;k<input_learning_range;k++)\n        {\n          if(prices[stock_index][size-offset*k-ind].synthetic){go=false;break;}\n          prev_prcs.push_back(prices[stock_index][size-offset*k-ind]);\n        }\n        if(go==false)continue;\n        std::vector<price> next_prcs;\n        for(long k=1;k<output_learning_range;k++)\n        {\n          if(prices[stock_index][size+offset*k-ind].synthetic){go=false;break;}\n          next_prcs.push_back(prices[stock_index][size+offset*k-ind]);\n        }\n        if(go==false)continue;\n        robot->generate ( symbols[stock_index]\n                        , prices[stock_index][size-ind]\n                        , prev_prcs\n                        , prev_prcs // next_prcs\n                        , in_off\n                        , out_off\n                        , in_dump\n                        , out_dump\n                        , in_size\n                        , out_size\n                        , samples\n                        );\n      }\n    }\n  }\n  std::cout << in_off << \"\\t\" << in_size << \"\\t\" << robot->get_input_size(input_learning_range) << std::endl;\n  std::cout << out_off << \"\\t\" << out_size << \"\\t\" << robot->get_output_size(output_learning_range) << std::endl;\n  std::cout << \"done constructing learning data\" << std::endl;\n  return samples;\n}\n\nlong learning_selection = 0;\n\ndouble * err_stats = NULL;\nbool err_stats_changed = false;\nlong err_stats_cnt = 1;\n\ndouble * min_variable = NULL;\ndouble * max_variable = NULL;\n\nint x_dim = 0;\nint y_dim = 1;\n\nvoid init_energy()\n{\n\n  if(perceptron != NULL)\n  {\n    min_variable = new double[perceptron->get_num_variables()];\n    max_variable = new double[perceptron->get_num_variables()];\n    for(int i=0;i<perceptron->get_num_variables();i++)\n    {\n        min_variable[i] = -20;\n        max_variable[i] =  20;\n    }\n  }\n\n}\n\nvoid draw_energy()\n{\n\n  if(  perceptron != NULL \n    && x_dim >= 0 \n    && x_dim < perceptron->get_num_variables() \n    && y_dim >= 0 \n    && y_dim < perceptron->get_num_variables() \n    )\n  {\n    static bool init_eng = true;\n    if(init_eng)\n    {\n        init_eng = false;\n        init_energy();\n    }\n    glColor3f(1,1,1);\n    std::stringstream ss0,ss1,ss2,ss3;\n    ss0 << ((int)(100*min_variable[x_dim])/100.0f);\n    if(!game_mode)drawString(GLUT_BITMAP_HELVETICA_18,ss0.str().c_str(),-0.9,-0.8,0);\n    ss1 << ((int)(100*max_variable[x_dim])/100.0f);\n    if(!game_mode)drawString(GLUT_BITMAP_HELVETICA_18,ss1.str().c_str(),-0.9, 0.8,0);\n    ss2 << ((int)(100*min_variable[y_dim])/100.0f);\n    if(!game_mode)drawString(GLUT_BITMAP_HELVETICA_18,ss2.str().c_str(),-0.8,-0.9,0);\n    ss3 << ((int)(100*max_variable[y_dim])/100.0f);\n    if(!game_mode)drawString(GLUT_BITMAP_HELVETICA_18,ss3.str().c_str(), 0.8,-0.9,0);\n    glColor3f(1-perceptron->final_error,1-perceptron->final_error,1-perceptron->final_error);\n    glBegin(GL_QUADS);\n    glVertex3f(\n        -1 + 2*(perceptron->get_variable(x_dim)-min_variable[x_dim])/(max_variable[x_dim]-min_variable[x_dim]) - 0.005 ,\n        -1 + 2*(perceptron->get_variable(y_dim)-min_variable[y_dim])/(max_variable[y_dim]-min_variable[y_dim]) - 0.005 ,\n        0\n    );\n    glVertex3f(\n        -1 + 2*(perceptron->get_variable(x_dim)-min_variable[x_dim])/(max_variable[x_dim]-min_variable[x_dim]) - 0.005 ,\n        -1 + 2*(perceptron->get_variable(y_dim)-min_variable[y_dim])/(max_variable[y_dim]-min_variable[y_dim]) + 0.005 ,\n        0\n    );\n    glVertex3f(\n        -1 + 2*(perceptron->get_variable(x_dim)-min_variable[x_dim])/(max_variable[x_dim]-min_variable[x_dim]) + 0.005 ,\n        -1 + 2*(perceptron->get_variable(y_dim)-min_variable[y_dim])/(max_variable[y_dim]-min_variable[y_dim]) + 0.005 ,\n        0\n    );\n    glVertex3f(\n        -1 + 2*(perceptron->get_variable(x_dim)-min_variable[x_dim])/(max_variable[x_dim]-min_variable[x_dim]) + 0.005 ,\n        -1 + 2*(perceptron->get_variable(y_dim)-min_variable[y_dim])/(max_variable[y_dim]-min_variable[y_dim]) - 0.005 ,\n        0\n    );\n    glEnd();\n    \n    // list all files in current directory.\n    boost::filesystem::path p (\"snapshots\");\n    boost::filesystem::directory_iterator end_itr;\n    // cycle through the directory\n    for (boost::filesystem::directory_iterator itr(p); itr != end_itr; ++itr)\n    {\n      // If it's not a directory, list it. If you want to list directories too, just remove this check.\n      if (boost::filesystem::is_regular_file(itr->path())) {\n        std::string current_file = itr->path().string();\n        perceptron_tmp -> load_from_file(current_file,true);\n        glColor3f(1-perceptron_tmp->final_error,1-perceptron_tmp->final_error,1-perceptron_tmp->final_error);\n        glBegin(GL_QUADS);\n        glVertex3f(\n            -1 + 2*(perceptron_tmp->get_variable(x_dim)-min_variable[x_dim])/(max_variable[x_dim]-min_variable[x_dim]) - 0.005 ,\n            -1 + 2*(perceptron_tmp->get_variable(y_dim)-min_variable[y_dim])/(max_variable[y_dim]-min_variable[y_dim]) - 0.005 ,\n            0\n        );\n        glVertex3f(\n            -1 + 2*(perceptron_tmp->get_variable(x_dim)-min_variable[x_dim])/(max_variable[x_dim]-min_variable[x_dim]) - 0.005 ,\n            -1 + 2*(perceptron_tmp->get_variable(y_dim)-min_variable[y_dim])/(max_variable[y_dim]-min_variable[y_dim]) + 0.005 ,\n            0\n        );\n        glVertex3f(\n            -1 + 2*(perceptron_tmp->get_variable(x_dim)-min_variable[x_dim])/(max_variable[x_dim]-min_variable[x_dim]) + 0.005 ,\n            -1 + 2*(perceptron_tmp->get_variable(y_dim)-min_variable[y_dim])/(max_variable[y_dim]-min_variable[y_dim]) + 0.005 ,\n            0\n        );\n        glVertex3f(\n            -1 + 2*(perceptron_tmp->get_variable(x_dim)-min_variable[x_dim])/(max_variable[x_dim]-min_variable[x_dim]) + 0.005 ,\n            -1 + 2*(perceptron_tmp->get_variable(y_dim)-min_variable[y_dim])/(max_variable[y_dim]-min_variable[y_dim]) - 0.005 ,\n            0\n        );\n        glEnd();\n      }\n    }\n\n    usleep(1000);\n\n  }\n\n}\n\ndouble min_D=0;\ndouble max_D=1;\nint selection_mode = 0;\n\nvoid evaluate_prediction()\n{\n    if(perceptron != NULL)\n    {\n        std::cout << \"Evaluating prediction confidence\" << std::endl;\n        int  in_size = robot-> get_input_size( input_learning_range);\n        int out_size = robot->get_output_size(output_learning_range);\n        for(int stock=0;stock<prices.size();stock++)\n        {\n            double err_prct = 0;\n            for(int index=0;index<prices[stock].size();index++)\n            {\n                //std::cout << symbols[stock] << '\\t' << index << std::endl;\n                double * in = new double[in_size];\n                bool go = true;\n                for(int i=index+1,k=0;k<input_learning_range;i-=learning_offset,k++)\n                {\n                    if(i<0||i>=prices[stock].size())\n                    {\n                        go = false;\n                        break;\n                    }\n                    in[k] = 100*((prices[stock][i].synthetic)?prices[stock][i].prct_prediction:prices[stock][i].prct_change);\n                    if(in[k]<-2)in[k]=-2;\n                    if(in[k]> 2)in[k]= 2;\n                    in[k]+=2;\n                    in[k]/=4;\n                }\n                if(!go)continue;\n                double dat_min_err = 1e10;\n                double del2 = 0.05;\n                for(double D=0.0;D<=1.0;D+=del2)\n                {\n                  double * tmp_in = new double[in_size];\n                  for(int i=0;i<in_size;i++)\n                  {\n                    tmp_in[i] = in[i];\n                  }\n                  tmp_in[0] = D;\n                  for(int iter=0;iter<100;iter++)\n                  {\n                    double * dat = perceptron->model2(in_size,out_size,&tmp_in[0]);\n                    for(int i=0;i<in_size;i++)\n                    {\n                      tmp_in[i] = dat[i];\n                    }\n                    delete [] dat;\n                    dat = NULL;\n                  }\n                  double dat_err = 0;\n                  for(int j=1;j<out_size;j++)\n                  {\n                    dat_err += fabs(in[j] - tmp_in[j]);\n                  }\n                  {\n                    dat_err += fabs(D - tmp_in[0]);\n                  }\n                  {\n                    if(dat_err < dat_min_err)\n                    {\n                      dat_min_err = dat_err;\n                      prices[stock][index+1].prediction_confidence = (fabs(D - in[0])<0.11)?1:0;\n                    }\n                  }\n                  delete [] tmp_in;\n                  tmp_in = NULL;\n                }\n                delete [] in;\n                in = NULL;\n                err_prct += prices[stock][index+1].prediction_confidence;\n            }\n            std::cout << \"Rate:\" << err_prct / prices[stock].size() << std::endl;\n        }\n        std::cout << \"Done\" << std::endl;\n    }\n}\n\nvoid draw_learning_progress()\n{\n  if(in_dump&&out_dump)\n  {\n    int  in_size = robot-> get_input_size( input_learning_range);\n    int out_size = robot->get_output_size(output_learning_range);\n    // draw input vector\n    {\n        double dx=0.5f/in_size;\n        double val;\n        glBegin(GL_QUADS);\n        for(int x=0;x<in_size;x++)\n        {\n            val = in_dump[learning_selection*in_size+x];\n            glColor3f(val,val,val);\n            glVertex3f(-1+0.2+ x   *dx,-1+.2     ,0);\n            glVertex3f(-1+0.2+(x+1)*dx,-1+.2     ,0);\n            glVertex3f(-1+0.2+(x+1)*dx,-1+.2+0.01,0);\n            glVertex3f(-1+0.2+ x   *dx,-1+.2+0.01,0);\n        }\n        glEnd();\n    }\n\n    // draw output vector\n    {\n        double dx=0.5f/out_size;\n        glBegin(GL_QUADS);\n        for(int x=0;x<out_size;x++)\n        {\n            double val = out_dump[learning_selection*out_size+x];\n            glColor3f(val,val,val);\n            glVertex3f(-1+1+0.2+ x   *dx,-1+.2     ,0);\n            glVertex3f(-1+1+0.2+(x+1)*dx,-1+.2     ,0);\n            glVertex3f(-1+1+0.2+(x+1)*dx,-1+.2+0.01,0);\n            glVertex3f(-1+1+0.2+ x   *dx,-1+.2+0.01,0);\n        }\n        glEnd();\n    }\n\n    // draw learning states\n    if(mrbm != NULL)\n    {\n      if(mrbm->model_ready == true)\n      {\n        double dx=0.5f/in_size;\n        //std::cout << \"in_dump:\\t\";\n        //for(int i=0;i<in_size;i++)\n        //std::cout << in_dump[learning_selection*in_size+i] << '\\t';\n        //std::cout << '\\n';\n        double ** dat = mrbm->model(learning_selection,in_dump);\n        //std::cout << \"dat:\\t\\t\";\n        //for(int i=0;i<in_size;i++)\n        //std::cout << dat[0][i] << '\\t';\n        //std::cout << '\\n';\n        for(int l=0;l<20;l++)\n        {\n          glBegin(GL_QUADS);\n          for(int x=0;x<in_size+out_size;x++)\n          {\n              double val = 0.2+0.8*dat[l][x];\n              if(val<0)val=0;\n              if(val>1)val=1;\n              {\n                  glColor3f(val,val,val);\n              }\n              glVertex3f(-1+0.2+ x   *dx,-1+.2+0.02*(l+1)     ,0);\n              glVertex3f(-1+0.2+(x+1)*dx,-1+.2+0.02*(l+1)     ,0);\n              glVertex3f(-1+0.2+(x+1)*dx,-1+.2+0.02*(l+1)+0.01,0);\n              glVertex3f(-1+0.2+ x   *dx,-1+.2+0.02*(l+1)+0.01,0);\n          }\n          glEnd();\n        }\n        for(int i=0;i<20;i++)delete [] dat[i];\n        delete [] dat;\n        dat = NULL;\n      }\n    }\n\n    if(perceptron != NULL)\n    {\n      {\n        //if(err_stats == NULL)\n        //{\n        //  err_stats = new double[out_size];\n        //  for(int x=0;x<out_size;x++)\n        //  {\n        //    err_stats[x] = 0.5; \n        //  }\n        //}\n        double dx=0.5f/out_size;\n        double * in = new double[in_size];\n        double * dat_fin = new double[in_size];\n        for(int i=0;i<in_size;i++)\n        {\n          in[i] = in_dump[in_size*learning_selection+i];\n        }\n        double tru_err=100;\n        double dat_err=0;\n        int it = 0;\n        glBegin(GL_LINES);\n        double tru = in[0];\n        double T = 0;\n        double R = 0;\n        {\n            //double del = 0.01;\n            //int n_distribution = (int)(1/del);\n            //double * distribution = new double[n_distribution];\n            //for(int i=0;i<n_distribution;i++)\n            //{\n            //    distribution[i] = 1;\n            //}\n            //double count = 0;\n            //for(int i=0;i<n_distribution;i++)\n            //{\n            //    count += distribution[i];\n            //}\n            //for(int iter=0;iter<10000;iter++)\n            //{\n            //    //std::cout << \"iter=\" << iter << std::endl;\n            //    double ret = 0;\n            //    int it = 0;\n            //    for(;it<n_distribution;it++)\n            //    {\n            //        double D = 0.3+0.4*((rand()%10000)/10000.0);\n            //        in[0] = D;\n            //        double * dat = perceptron->model(in_size,out_size,&in[0]);\n            //        ret += distribution[it] * dat[0] / count;\n            //        int I = dat[0]*n_distribution;\n            //        if(I>=0&&I<n_distribution)\n            //        distribution[I]++;\n            //        count++;\n            //        delete [] dat;\n            //        dat = NULL;\n            //    }\n            //    double max_distribution = 0;\n            //    for(int i=0;i<n_distribution;i++)\n            //    {\n            //        if(distribution[i]>max_distribution)\n            //        {\n            //            max_distribution = distribution[i];\n            //            R = i*del;\n            //        }\n            //    }\n            //}\n            //std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n            //for(int i=0;i<n_distribution;i++)\n            //{\n            //    std::cout << i << \"\\t\" << distribution[i] << std::endl;\n            //}\n            ////char ch;\n            ////std::cin >> ch;\n            //delete [] distribution;\n            double prev_dat_err=1;\n            double dat_min_err = 1e10;\n            double del2 = 0.01;\n            for(double D=0.0;D<=1.0;D+=del2)\n            {\n              double * tmp_in = new double[in_size];\n              for(int i=0;i<in_size;i++)\n              {\n                tmp_in[i] = in[i];\n              }\n              tmp_in[0] = D;\n              for(int iter=0;iter<1000;iter++)\n              {\n                double * dat = perceptron->model(in_size,out_size,&tmp_in[0]);\n                for(int i=0;i<in_size;i++)\n                {\n                  tmp_in[i] = dat[i];\n                }\n                delete [] dat;\n                dat = NULL;\n              }\n              dat_err = 0;\n              for(int j=1;j<out_size;j++)\n              {\n                dat_err += fabs(in[j] - tmp_in[j]);\n              }\n              {\n                dat_err += fabs(D - tmp_in[0]);\n              }\n              glColor3f(1,1,1);\n              glVertex3f(-1+2*(D-del2),-1+2*prev_dat_err,0);\n              glVertex3f(-1+2*(D),-1+2*dat_err,0);\n              prev_dat_err=dat_err;\n              {\n                if(dat_err < dat_min_err)\n                {\n                  T = D;\n                  dat_min_err = dat_err;\n                  for(int j=0;j<out_size;j++)\n                  {\n                    dat_fin[j] = tmp_in[j];\n                  }\n                }\n              }\n              delete [] tmp_in;\n              tmp_in = NULL;\n            }\n        }\n        {\n              double * tmp_in = new double[in_size];\n              for(int i=0;i<in_size;i++)\n              {\n                tmp_in[i] = in[i];\n              }\n              tmp_in[0] = 0.5;\n              for(int iter=0;iter<1000;iter++)\n              {\n                double * dat = perceptron->model(in_size,out_size,&tmp_in[0]);\n                for(int i=0;i<in_size;i++)\n                {\n                  tmp_in[i] = dat[i];\n                }\n                delete [] dat;\n                dat = NULL;\n              }\n              delete [] tmp_in;\n              tmp_in = NULL;\n        }\n        glColor3f(1,1,0);\n        glVertex3f(-1+2*tru,-1,0);\n        glVertex3f(-1+2*tru,1,0);\n        glColor3f(0,1,0);\n        glVertex3f(-1+2*T,-1,0);\n        glVertex3f(-1+2*T,1,0);\n        glColor3f(0,0,1);\n        glVertex3f(-1+2*R,-1,0);\n        glVertex3f(-1+2*R,1,0);\n        glEnd();\n        if(fabs(T-tru) > 0.05)\n        {\n            learning_selection++;if(learning_selection>=learning_samples)learning_selection=0;\n        }\n        {\n          glBegin(GL_QUADS);\n          for(int x=0;x<out_size;x++)\n          {\n              double val = dat_fin[x];\n              glColor3f(val,val,val);\n              glVertex3f(-1+1+0.2+ x   *dx,-1+.2+0.02     ,0);\n              glVertex3f(-1+1+0.2+(x+1)*dx,-1+.2+0.02     ,0);\n              glVertex3f(-1+1+0.2+(x+1)*dx,-1+.2+0.02+0.01,0);\n              glVertex3f(-1+1+0.2+ x   *dx,-1+.2+0.02+0.01,0);\n          }\n          glEnd();\n        }\n        delete [] dat_fin;\n        delete [] in;\n        dat_fin = NULL;\n        in = NULL;\n\n        for(int layer=0;layer<perceptron->n_nodes.size();layer++)\n        {\n            double dx=0.5f/perceptron->n_nodes[layer];\n            double val;\n            glBegin(GL_QUADS);\n            for(int x=0;x<perceptron->n_nodes[layer];x++)\n            {\n                val = perceptron->activation_values1[layer][x];\n                glColor3f(val,val,val);\n                glVertex3f(-1+0.2+ x   *dx,-1+.2+(layer+1)*0.02     ,0);\n                glVertex3f(-1+0.2+(x+1)*dx,-1+.2+(layer+1)*0.02     ,0);\n                glVertex3f(-1+0.2+(x+1)*dx,-1+.2+(layer+1)*0.02+0.01,0);\n                glVertex3f(-1+0.2+ x   *dx,-1+.2+(layer+1)*0.02+0.01,0);\n            }\n            glEnd();\n        }\n\n      }\n    }\n\n    // draw errors\n    {\n      double max_err = 0;\n      for(long k=0;k<errs.size();k++)\n      {\n        if(max_err<errs[k])max_err=errs[k];\n      }\n      glBegin(GL_LINES);\n      for(long k=0;k+1<errs.size();k++)\n      {\n        glColor3f(1,1,1);\n        glVertex3f( -1 + 2*k / ((double)errs.size()-1)\n                  , errs[k] / max_err\n                  , 0\n                  );\n        glVertex3f( -1 + 2*(k+1) / ((double)errs.size()-1)\n                  , errs[k+1] / max_err\n                  , 0\n                  );\n        glVertex3f( -1 + 2*k / ((double)errs.size()-1)\n                  , 0\n                  , 0\n                  );\n        glVertex3f( -1 + 2*(k+1) / ((double)errs.size()-1)\n                  , 0\n                  , 0\n                  );\n        glColor3f(1,1,0);\n        glVertex3f( -1 + 2*k / ((double)errs.size()-1)\n                  , test_errs[k] / max_err\n                  , 0\n                  );\n        glVertex3f( -1 + 2*(k+1) / ((double)errs.size()-1)\n                  , test_errs[k+1] / max_err\n                  , 0\n                  );\n        glVertex3f( -1 + 2*k / ((double)errs.size()-1)\n                  , 0\n                  , 0\n                  );\n        glVertex3f( -1 + 2*(k+1) / ((double)errs.size()-1)\n                  , 0\n                  , 0\n                  );\n      }\n      glEnd();\n    }\n\n  }\n}\n\nint draw_mode = 1;\n\nvoid display()\n{\n  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n  if(draw_mode == 0)\n  {\n    draw_charts();\n  }\n  else\n  if(draw_mode == 1)\n  {\n    draw_learning_progress();\n  }\n  else\n  if(draw_mode == 2)\n  {\n    draw_energy();\n  }\n  glutSwapBuffers();\n}\n\nvoid idle()\n{\n  usleep(10000);\n  glutPostRedisplay();\n}\n\nvoid init()\n{\n  /* Use depth buffering for hidden surface elimination. */\n  glEnable(GL_DEPTH_TEST);\n\n  /* Setup the view of the cube. */\n  glMatrixMode(GL_PROJECTION);\n  gluPerspective( /* field of view in degree */ 40.0,\n    /* aspect ratio */ 1.0,\n    /* Z near */ 1.0, /* Z far */ 10.0);\n  glMatrixMode(GL_MODELVIEW);\n  gluLookAt(0.0, 0.0, 1.8,  /* eye is at (0,0,5) */\n    0.0, 0.0, 0.0,      /* center is at (0,0,0) */\n    0.0, 1.0, 0.);      /* up is in positive Y direction */\n\n  /* Adjust cube position to be asthetic angle. */\n  glTranslatef(0.0, 0.0, -1.0);\n  glRotatef(0, 1.0, 0.0, 0.0);\n  glRotatef(0, 0.0, 0.0, 1.0);\n  glEnable (GL_BLEND); \n  //glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n  glBlendFunc (GL_SRC_ALPHA, GL_ONE);\n  glBlendEquation(GL_FUNC_ADD);\n}\n\nstd::string input_filename = \"\";\n\nvoid run_perceptron()\n{\n    std::cout << \"learning samples: \" << learning_samples << \"\\t\" << test_learning_samples << std::endl;\n    int  num_inputs = robot-> get_input_size(input_learning_range);\n    int num_outputs = robot->get_output_size(output_learning_range);\n    std::vector<int> layer;\n    int N = 21;\n    layer.push_back(N);\n    layer.push_back(N);\n    //layer.push_back(N);\n    //layer.push_back(N);\n    //while(N>2)\n    //{\n    //  N -= 2;\n    //  if(N>=2)\n    //  {\n    //    layer.push_back(N);\n    //  }\n    //}\n    std::vector<int> num_hidden;\n    for(int i=0;i<layer.size();i++)\n    {\n      num_hidden.push_back(layer[i]);\n    }\n    for(int i=0;i+1<layer.size();i++)\n    {\n      num_hidden.push_back(layer[(int)layer.size()-2-i]);\n    }\n    //for(int i=0;i<num_hidden.size();i++)\n    //{\n    //  std::cout << i << \"\\t\" << num_hidden[i] << std::endl;\n    //}\n    long num_ann_iters = 100000;\n    std::vector<long> nodes;\n    nodes.push_back(num_inputs); // inputs\n    for(int h=0;h<num_hidden.size();h++)\n      nodes.push_back(num_hidden[h]); // hidden layer\n    nodes.push_back(num_outputs); // output layer\n    nodes.push_back(num_outputs); // outputs\n\n    std::vector<RBM*> rbms;\n    double ** out = new double*[num_hidden.size()/2+1];\n    for(int r=0;r<num_hidden.size()/2+1;r++)\n    {\n        RBM * rbm = new RBM((r==0)?num_inputs:num_hidden[r-1],num_hidden[r],learning_samples,(r==0)?in_dump:out[r-1]);\n        int n_iters = 20000;\n        for(int i=0;i<n_iters;i++)\n        {\n          if(i%100==0)std::cout << i << \"\\t\" << n_iters << std::endl;\n          rbm->init(0);\n          rbm->cd(1+(int)(i/6000),0.1,0);\n        }\n        rbms.push_back(rbm);\n        out[r] = new double[num_hidden[r]*learning_samples];\n        rbm->vis2hid((r==0)?in_dump:out[r-1],out[r]);\n    }\n\n    int n_prptn = 1;//000;\n    perceptron_tmp = new Perceptron<double>(nodes);\n    Perceptron<double> ** p = new Perceptron<double>*[n_prptn];\n    double min_err = 1e10;\n    double tmp_err;\n    int min_ind = 0;\n    for(int i=0;i<n_prptn;i++)\n    {\n        p[i] = new Perceptron<double>(nodes);\n        p[i]->epsilon = 0.01;\n        p[i]->alpha = 0.01;\n        p[i]->sigmoid_type = 0;\n        if(input_filename.size()>0)\n        {\n          p[i]->load_from_file(input_filename);\n        }\n        perceptron = p[i];\n        {\n            int layer = 0;\n            for(int r=0;r<rbms.size();r++)\n            {\n              {\n                for(int i=0;i<nodes[layer+1];i++)\n                {\n                  for(int j=0;j<nodes[layer];j++)\n                  {\n                    perceptron->weights_neuron[layer][i][j] = rbms[r]->W[j*rbms[r]->h+i];\n                  }\n                  perceptron->weights_bias[layer][i] = rbms[r]->c[i];\n                }\n              }\n              layer++;\n            }\n            for(int r=rbms.size()-1;r>=0;r--)\n            {\n              {\n                for(int i=0;i<nodes[layer+1];i++)\n                {\n                  for(int j=0;j<nodes[layer];j++)\n                  {\n                    perceptron->weights_neuron[layer][i][j] = rbms[r]->W[i*rbms[r]->h+j];\n                  }\n                  perceptron->weights_bias[layer][i] = rbms[r]->b[i];\n                }\n              }\n              layer++;\n            }\n        }\n        //p[i]->train(p[i]->sigmoid_type,p[i]->epsilon,1000,learning_samples,test_learning_samples,num_inputs,in_dump,in_test,num_outputs,out_dump,out_test,(i==0)?NULL:p[0]->quasi_newton);\n        if(p[i]->final_error<min_err)\n        {\n            min_err = p[i]->final_error;\n            min_ind = i;\n        }\n    }\n    perceptron = p[min_ind];\n    //perceptron->train(perceptron->sigmoid_type,perceptron->epsilon,num_ann_iters,learning_samples,test_learning_samples,num_inputs,in_dump,in_test,num_outputs,out_dump,out_test,p[0]->quasi_newton);\n    evaluate_prediction();\n}\n\nbool training = false;\nvoid keyboard(unsigned char key,int x,int y)\n{\n  switch(key)\n  {\n    case 't':delta_D *= 1.1;break;\n    case 'h':delta_D /= 1.1;break;\n    case 'n':selection_mode=(selection_mode+1)%3;\n             switch(selection_mode)\n             {\n                case 0:min_D=0.3;max_D=0.43;break;\n                case 1:min_D=0.43;max_D=0.56;break;\n                case 2:min_D=0.56;max_D=0.7;break;\n             }\n             break;\n    case 'x':dump_autoencoding_to_file(\"autoencoding.csv\");break;\n    case '5':continue_training=!continue_training;std::cout << \"continue training:\" << continue_training << std::endl;break;\n    case '6':stop_training=!stop_training;std::cout << \"stop training:\" << stop_training << std::endl;break;\n    case '-':x_dim--;std::cout << x_dim << \"\\t\" << y_dim << '\\t' << perceptron->get_num_variables() << std::endl;break;\n    case '=':x_dim++;std::cout << x_dim << \"\\t\" << y_dim << '\\t' << perceptron->get_num_variables() << std::endl;break;\n    case '[':y_dim--;std::cout << x_dim << \"\\t\" << y_dim << '\\t' << perceptron->get_num_variables() << std::endl;break;\n    case ']':y_dim++;std::cout << x_dim << \"\\t\" << y_dim << '\\t' << perceptron->get_num_variables() << std::endl;break;\n    case '9':perceptron->dump_to_file(\"network.ann.new\");break;\n    case '0':perceptron->load_from_file(\"network.ann\");break;\n    case '\\'':if(perceptron->quasi_newton!=NULL){perceptron->quasi_newton->quasi_newton_update=!perceptron->quasi_newton->quasi_newton_update;}break;\n    case ';':perceptron->sigmoid_type = (perceptron->sigmoid_type+1)%3;break;\n    case '3':perceptron->epsilon /= 1.1;break;\n    case '4':perceptron->epsilon *= 1.1;break;\n    case '7':damp_weight /= 1.1;if(damp_weight>1)damp_weight=1;break;\n    case '8':damp_weight *= 1.1;if(damp_weight>1)damp_weight=1;break;\n    //case '1':sample_index--;if(sample_index<0)sample_index=0;break;\n    //case '2':sample_index++;if(sample_index>=robot->get_output_size(output_learning_range))sample_index=robot->get_output_size(output_learning_range)-1;break;\n    case '1':train_index--;if(train_index<0)train_index=0;break;\n    case '2':train_index++;if(train_index>=robot->get_output_size(output_learning_range))train_index=robot->get_output_size(output_learning_range)-1;break;\n    case 'r':perceptron->alpha *= 1.1;perceptron->quasi_newton->alpha = perceptron->alpha; break;\n    case 'f':perceptron->alpha /= 1.1;perceptron->quasi_newton->alpha = perceptron->alpha; break;\n    case 'p':\n      {\n        if(training==false)\n        {\n          training=true;\n          /*\n          mrbm_params params(robot,learning_range,learning_samples-1,learning_samples,.5);\n          boost::thread * thr ( new boost::thread ( run_mrbm\n                                                  , params\n                                                  , in_dump\n                                                  , out_dump\n                                                  , prd_dump\n                                                  ) \n                              );\n          */\n          boost::thread * thr ( new boost::thread ( run_perceptron ) );\n        }\n        break;\n      }\n      break;\n    case 'k':learning_selection++;if(learning_selection>=learning_samples)learning_selection=learning_samples-1;else err_stats_changed=true;break;\n    case 'j':learning_selection--;if(learning_selection<0)learning_selection=0;else err_stats_changed=true;break;\n    case 'm': // chage draw mode\n      draw_mode = (draw_mode+1)%3;\n      break;\n    case 'y': // buy\n      if(game_mode&&user){\n        user->buyAll(stock_index,end_date_index);\n      }\n      break;\n    case 'u': // sell\n      if(game_mode&&user){\n        user->sellAll(stock_index,end_date_index);\n      }\n      break;\n    case ' ':\n      if(start_date_index>0&&end_date_index>0)\n      {\n        start_date_index--;\n          end_date_index--;\n      }\n      break;\n    case 'a':\n      if(buy_only==false&&game_mode==false)\n      {\n        stock_index--;\n        if(stock_index<0)stock_index=prices.size()-1;\n      }\n      if(buy_only)\n      {\n        if(scanner.buy.size()==0)\n        {\n          buy_only=false;\n          stock_index--;\n          if(stock_index<0)stock_index=prices.size()-1;\n        }\n        else\n        {\n          while(true)\n          {\n            stock_index--;\n            if(stock_index<0)stock_index=prices.size()-1;\n            if(scanner.buy.find(symbols[stock_index]) != scanner.buy.end())break;\n          }\n        }\n      }\n      if(game_mode)\n      {\n        if(rsymbols.size()==0)\n        {\n          game_mode=false;\n          stock_index--;\n          if(stock_index<0)stock_index=prices.size()-1;\n        }\n        else\n        {\n          while(true)\n          {\n            stock_index--;\n            if(stock_index<0)stock_index=prices.size()-1;\n            if(std::find(rsymbols.begin(),rsymbols.end(),stock_index) != rsymbols.end())break;\n          }\n        }\n      }\n      std::cout << symbols[stock_index] << std::endl;\n      break;\n    case 'd':\n      if(buy_only==false&&game_mode==false)\n      {\n        stock_index++;\n        if(stock_index>=prices.size())stock_index=0;\n      }\n      if(buy_only)\n      {\n        if(scanner.buy.size()==0)\n        {\n          buy_only=false;\n          stock_index++;\n          if(stock_index>=prices.size())stock_index=0;\n        }\n        else\n        {\n          while(true)\n          {\n            stock_index++;\n            if(stock_index>=prices.size())stock_index=0;\n            if(scanner.buy.find(symbols[stock_index]) != scanner.buy.end())break;\n          }\n        }\n      }\n      if(game_mode)\n      {\n        if(rsymbols.size()==0)\n        {\n          game_mode=false;\n          stock_index++;\n          if(stock_index>=prices.size())stock_index=0;\n        }\n        else\n        {\n          while(true)\n          {\n            stock_index++;\n            if(stock_index>=prices.size())stock_index=0;\n            if(std::find(rsymbols.begin(),rsymbols.end(),stock_index) != rsymbols.end())break;\n          }\n        }\n      }\n      std::cout << symbols[stock_index] << std::endl;\n      break;\n    case 'g':\n      game_mode = !game_mode;\n      if(game_mode) \n      {\n        start_date_index = 3000 - (rand()%1000);\n        end_date_index = start_date_index - 100;\n        if(rsymbols.size()==0)\n        {\n          game_mode=false;\n          stock_index++;\n          if(stock_index>=prices.size())stock_index=0;\n        }\n        else\n        {\n          while(true)\n          {\n            stock_index++;\n            if(stock_index>=prices.size())stock_index=0;\n            if(std::find(rsymbols.begin(),rsymbols.end(),stock_index) != rsymbols.end())break;\n          }\n        }\n      }\n      else\n      {\n        start_date_index = 4000;\n        end_date_index = 0;\n      }\n      break;\n    case 'w':if(!game_mode){end_date_index=0;start_date_index*=1.1f;if(start_date_index>4000)start_date_index=4000;}break;\n    case 's':if(!game_mode){end_date_index=0;start_date_index/=1.1f;if(start_date_index<10)start_date_index=10;}break;\n    case 'c':pick_start_index = true;break;\n    case 'v':pick_end_index = true;break;\n    case 'b':start_index=-1;end_index=-1;break;\n    case 'z':\n      buy_only = !buy_only;\n      if(buy_only) \n      {\n        if(scanner.buy.size()==0)\n        {\n          buy_only=false;\n          stock_index++;\n          if(stock_index>=prices.size())stock_index=0;\n        }\n        else\n        {\n          while(true)\n          {\n            stock_index++;\n            if(stock_index>=prices.size())stock_index=0;\n            if(scanner.buy.find(symbols[stock_index]) != scanner.buy.end())break;\n          }\n        }\n      }\n      break;\n    case 27:exit(1);break;\n    default:break;\n  }\n}\n\nvoid passive_mouse(int x,int y)\n{\n  mouse_x = x;\n  mouse_y = y;\n}\n\nvoid active_mouse(int x,int y)\n{\n  mouse_x = x;\n  mouse_y = y;\n}\n\nint main(int argc,char ** argv)\n{\n\n  if(argc>=2)\n  {\n    learning_num = atoi(argv[1]);\n  }\n\n  if(argc>=3)\n  {\n    train_index = atoi(argv[2]);\n  }\n\n  if(argc>=4)\n  {\n    input_filename = std::string(argv[3]);\n  }\n\n  int seed;\n  seed = time(0);\n  srand(seed);\n\n  bool awesome_macd = true;\n\n  int synthetic_prices = (synthetic_range-1)*learning_offset;\n\n  start_date_index = 4000;\n  end_date_index = 0;\n  \n  // list all files in current directory.\n  boost::filesystem::path p (\"data\");\n  boost::filesystem::directory_iterator end_itr;\n  // cycle through the directory\n  int ind = 0;\n  for (boost::filesystem::directory_iterator itr(p); itr != end_itr; ++itr,ind++)\n  {\n    // If it's not a directory, list it. If you want to list directories too, just remove this check.\n    if (boost::filesystem::is_regular_file(itr->path())) {\n      prices.push_back(std::vector<price>());\n      // assign current file name to current_file and echo it out to the console.\n      std::string current_file = itr->path().string();\n      symbols.push_back(current_file);\n      fprintf(stderr,\"file:%s\\n\",current_file.c_str());\n      read_data_yahoo(current_file,prices[ind],synthetic_prices);\n    }\n  }\n\n  for(int i=0;i<prices.size();i++)\n  {\n    price::initialize_indicators(prices[i],awesome_macd);\n  }\n\n  scanner.scan(prices,symbols);\n\n  for(int i=0;i<4;i++)\n  {\n    int sym = rand()%symbols.size();\n    while(std::find(rsymbols.begin(),rsymbols.end(),sym)==rsymbols.end()){\n      if(std::find(rsymbols.begin(),rsymbols.end(),sym)==rsymbols.end()){\n        rsymbols.push_back(sym);\n        break;\n      }\n      sym = rand()%symbols.size();\n    }\n  }\n\n  std::cout << \"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\" << std::endl;\n  for(int i=0;i<rsymbols.size();i++)\n  {\n    std::cout << symbols[rsymbols[i]] << std::endl;\n  }\n  std::cout << \"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\" << std::endl;\n\n  user = new User(\"Anton Kodochygov\",10000,rsymbols);\n\n   in_dump = new double[learning_num*prices.size()*robot-> get_input_size( input_learning_range)];\n  out_dump = new double[learning_num*prices.size()*robot->get_output_size(output_learning_range)];\n   in_test = new double[test_learning_num*prices.size()*robot-> get_input_size( input_learning_range)];\n  out_test = new double[test_learning_num*prices.size()*robot->get_output_size(output_learning_range)];\n\n  learning_samples = construct_learning_data(40+test_learning_num,40+test_learning_num+learning_num,learning_offset,in_dump,out_dump);\n  test_learning_samples = construct_learning_data(0,test_learning_num,learning_offset,in_test,out_test);\n  std::cout << \"learning samples: \" << learning_samples << std::endl;\n\n  {\n    if(training==false)\n    {\n      training=true;\n      boost::thread * thr ( new boost::thread ( run_perceptron ) );\n    }\n  }\n\n  glutInit(&argc, argv);\n  glutInitWindowSize(width,height);\n  glutInitWindowPosition(0,0);\n  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);\n  glutCreateWindow(\"stock bot\");\n  glutDisplayFunc(display);\n  glutKeyboardFunc(keyboard);\n  glutPassiveMotionFunc(passive_mouse);\n  glutMotionFunc(active_mouse);\n  glutIdleFunc(idle);\n  init();\n  glutMainLoop();\n  return 0;\n}\n\n", "meta": {"hexsha": "754c1e332021f8e9254afed5b5e603d543e3e9b1", "size": 167064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "anton337/stock-bot", "max_stars_repo_head_hexsha": "5def8e9f46a2600a44eb899bfca04b08bca2dc86", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "anton337/stock-bot", "max_issues_repo_head_hexsha": "5def8e9f46a2600a44eb899bfca04b08bca2dc86", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "anton337/stock-bot", "max_forks_repo_head_hexsha": "5def8e9f46a2600a44eb899bfca04b08bca2dc86", "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.1559566787, "max_line_length": 430, "alphanum_fraction": 0.5305870804, "num_tokens": 50123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6113819591324416, "lm_q1q2_score": 0.527862054004283}}
{"text": "#include \"lin_reg_uni_hierarchy.h\"\n\n#include <Eigen/Dense>\n#include <stan/math/prim/err.hpp>\n#include <vector>\n\n#include \"src/utils/eigen_utils.h\"\n#include \"src/utils/proto_utils.h\"\n#include \"src/utils/rng.h\"\n\ndouble LinRegUniHierarchy::like_lpdf(\n    const Eigen::RowVectorXd &datum,\n    const Eigen::RowVectorXd &covariate /*= Eigen::RowVectorXd(0)*/) const {\n  return stan::math::normal_lpdf(\n      datum(0), state.regression_coeffs.dot(covariate), sqrt(state.var));\n}\n\ndouble LinRegUniHierarchy::marg_lpdf(\n    const LinRegUni::Hyperparams &params, const Eigen::RowVectorXd &datum,\n    const Eigen::RowVectorXd &covariate /*= Eigen::RowVectorXd(0)*/) const {\n  double sig_n = sqrt(\n      (1 + (covariate * params.var_scaling_inv * covariate.transpose())(0)) *\n      params.scale / params.shape);\n  return stan::math::student_t_lpdf(datum(0), 2 * params.shape,\n                                    covariate.dot(params.mean), sig_n);\n}\n\nvoid LinRegUniHierarchy::initialize_state() {\n  state.regression_coeffs = hypers->mean;\n  state.var = hypers->scale / (hypers->shape + 1);\n}\n\nvoid LinRegUniHierarchy::initialize_hypers() {\n  if (prior->has_fixed_values()) {\n    // Set values\n    hypers->mean = bayesmix::to_eigen(prior->fixed_values().mean());\n    dim = hypers->mean.size();\n    hypers->var_scaling =\n        bayesmix::to_eigen(prior->fixed_values().var_scaling());\n    hypers->var_scaling_inv = stan::math::inverse_spd(hypers->var_scaling);\n    hypers->shape = prior->fixed_values().shape();\n    hypers->scale = prior->fixed_values().scale();\n    // Check validity\n    if (dim != hypers->var_scaling.rows()) {\n      throw std::invalid_argument(\n          \"Hyperparameters dimensions are not consistent\");\n    }\n    bayesmix::check_spd(hypers->var_scaling);\n    if (hypers->shape <= 0) {\n      throw std::invalid_argument(\"Shape parameter must be > 0\");\n    }\n    if (hypers->scale <= 0) {\n      throw std::invalid_argument(\"Scale parameter must be > 0\");\n    }\n  }\n\n  else {\n    throw std::invalid_argument(\"Unrecognized hierarchy prior\");\n  }\n}\n\nvoid LinRegUniHierarchy::update_hypers(\n    const std::vector<bayesmix::AlgorithmState::ClusterState> &states) {\n  auto &rng = bayesmix::Rng::Instance().get();\n  if (prior->has_fixed_values()) {\n    return;\n  }\n\n  else {\n    throw std::invalid_argument(\"Unrecognized hierarchy prior\");\n  }\n}\n\nLinRegUni::State LinRegUniHierarchy::draw(\n    const LinRegUni::Hyperparams &params) {\n  auto &rng = bayesmix::Rng::Instance().get();\n  LinRegUni::State out;\n  out.var = stan::math::inv_gamma_rng(params.shape, params.scale, rng);\n  out.regression_coeffs = stan::math::multi_normal_prec_rng(\n      params.mean, params.var_scaling / out.var, rng);\n  return out;\n}\n\nvoid LinRegUniHierarchy::update_summary_statistics(\n    const Eigen::RowVectorXd &datum, const Eigen::RowVectorXd &covariate,\n    bool add) {\n  if (add) {\n    data_sum_squares += datum(0) * datum(0);\n    covar_sum_squares += covariate.transpose() * covariate;\n    mixed_prod += datum(0) * covariate.transpose();\n  } else {\n    data_sum_squares -= datum(0) * datum(0);\n    covar_sum_squares -= covariate.transpose() * covariate;\n    mixed_prod -= datum(0) * covariate.transpose();\n  }\n}\n\nvoid LinRegUniHierarchy::clear_data() {\n  mixed_prod = Eigen::VectorXd::Zero(dim);\n  data_sum_squares = 0.0;\n  covar_sum_squares = Eigen::MatrixXd::Zero(dim, dim);\n  card = 0;\n  cluster_data_idx = std::set<int>();\n}\n\nLinRegUni::Hyperparams LinRegUniHierarchy::get_posterior_parameters() {\n  if (card == 0) {  // no update possible\n    return *hypers;\n  }\n  // Compute posterior hyperparameters\n  LinRegUni::Hyperparams post_params;\n  post_params.var_scaling = covar_sum_squares + hypers->var_scaling;\n  auto llt = post_params.var_scaling.llt();\n  post_params.var_scaling_inv = llt.solve(Eigen::MatrixXd::Identity(dim, dim));\n  post_params.mean =\n      llt.solve(mixed_prod + hypers->var_scaling * hypers->mean);\n  post_params.shape = hypers->shape + 0.5 * card;\n  post_params.scale =\n      hypers->scale +\n      0.5 * (data_sum_squares +\n             hypers->mean.transpose() * hypers->var_scaling * hypers->mean -\n             post_params.mean.transpose() * post_params.var_scaling *\n                 post_params.mean);\n  return post_params;\n}\n\nvoid LinRegUniHierarchy::set_state_from_proto(\n    const google::protobuf::Message &state_) {\n  auto &statecast = google::protobuf::internal::down_cast<\n      const bayesmix::AlgorithmState::ClusterState &>(state_);\n  state.regression_coeffs =\n      bayesmix::to_eigen(statecast.lin_reg_uni_ls_state().regression_coeffs());\n  state.var = statecast.lin_reg_uni_ls_state().var();\n  set_card(statecast.cardinality());\n}\n\nvoid LinRegUniHierarchy::write_state_to_proto(\n    google::protobuf::Message *out) const {\n  bayesmix::LinRegUniLSState state_;\n  bayesmix::to_proto(state.regression_coeffs,\n                     state_.mutable_regression_coeffs());\n  state_.set_var(state.var);\n\n  auto *out_cast = google::protobuf::internal::down_cast<\n      bayesmix::AlgorithmState::ClusterState *>(out);\n  out_cast->mutable_lin_reg_uni_ls_state()->CopyFrom(state_);\n  out_cast->set_cardinality(card);\n}\n\nvoid LinRegUniHierarchy::write_hypers_to_proto(\n    google::protobuf::Message *out) const {\n  bayesmix::LinRegUniPrior hypers_;\n  bayesmix::to_proto(hypers->mean,\n                     hypers_.mutable_fixed_values()->mutable_mean());\n  bayesmix::to_proto(hypers->var_scaling,\n                     hypers_.mutable_fixed_values()->mutable_var_scaling());\n  hypers_.mutable_fixed_values()->set_shape(hypers->shape);\n  hypers_.mutable_fixed_values()->set_scale(hypers->scale);\n\n  google::protobuf::internal::down_cast<bayesmix::LinRegUniPrior *>(out)\n      ->mutable_fixed_values()\n      ->CopyFrom(hypers_.fixed_values());\n}\n", "meta": {"hexsha": "f35f13dd4be4f89d91bf2a6e72d3323eee724518", "size": 5756, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/hierarchies/lin_reg_uni_hierarchy.cc", "max_stars_repo_name": "mberaha/bayesmix", "max_stars_repo_head_hexsha": "4448f0e9f69ac71f3aacc11a239e3114790c1aaa", "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/hierarchies/lin_reg_uni_hierarchy.cc", "max_issues_repo_name": "mberaha/bayesmix", "max_issues_repo_head_hexsha": "4448f0e9f69ac71f3aacc11a239e3114790c1aaa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hierarchies/lin_reg_uni_hierarchy.cc", "max_forks_repo_name": "mberaha/bayesmix", "max_forks_repo_head_hexsha": "4448f0e9f69ac71f3aacc11a239e3114790c1aaa", "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.0975609756, "max_line_length": 79, "alphanum_fraction": 0.6937109104, "num_tokens": 1482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5278363736669961}}
{"text": "/*\n * odeint_rk4_lorenz_def_alg.cpp\n *\n * Copyright 2011 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 <boost/array.hpp>\n\n#include <boost/numeric/odeint/stepper/runge_kutta4_classic.hpp>\n#include <boost/numeric/odeint/algebra/array_algebra.hpp>\n\n#include \"rk_performance_test_case.hpp\"\n\n#include \"lorenz.hpp\"\n\ntypedef boost::array< double , 3 > state_type;\ntypedef boost::numeric::odeint::runge_kutta4_classic< state_type > rk4_odeint_type;\n\n\nclass odeint_wrapper\n{\npublic:\n    void reset_init_cond()\n    {\n        m_x[0] = 10.0 * rand() / RAND_MAX;\n        m_x[1] = 10.0 * rand() / RAND_MAX;\n        m_x[2] = 10.0 * rand() / RAND_MAX;\n        m_t = 0.0;\n    }\n\n    inline void do_step( const double dt )\n    {\n        m_stepper.do_step( lorenz() , m_x , m_t , dt );\n        //m_t += dt;\n    }\n\n    double state( const size_t i ) const\n    { return m_x[i]; }\n\nprivate:\n    state_type m_x;\n    double m_t;\n    rk4_odeint_type m_stepper;\n};\n\n\n\nint main()\n{\n    odeint_wrapper stepper;\n\n    run( stepper );\n}\n", "meta": {"hexsha": "0e71724164895dd056967eea8436495c077400cd", "size": 1182, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/performance/odeint_rk4_lorenz_range.cpp", "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/odeint_rk4_lorenz_range.cpp", "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/odeint_rk4_lorenz_range.cpp", "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": 19.7, "max_line_length": 83, "alphanum_fraction": 0.6556683587, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5278363679002649}}
{"text": "\n#ifndef M_PI\n#    define M_PI 3.14159265358979323846\n#endif\n\n#include <boost/shared_array.hpp>\n#include <boost/range.hpp>\n\n#include <smp/planner_utils/trajectory.hpp>\n#include <smp/planner_utils/vertex_edge.hpp>\n#include <smp/components/extenders/pos.h>\n\n#include <smp/components/extenders/state_array_double.hpp>\n#include <smp/components/extenders/input_array_double.hpp>\n#include <smp/components/extenders/base.hpp>\n#include <cmath>\n\n#include <cstdlib>\n/// Waypoint Position Controller WP=1\n#define WP 1\n\n\nusing namespace smp;\nusing namespace std;\n\n\ntemplate< class typeparams, int NUM_DIMENSIONS >\nint smp::extender_pos<typeparams,NUM_DIMENSIONS>\n::ex_update_insert_vertex (vertex_t *vertex_in) {\n\n    return 1;\n}\n\n\ntemplate< class typeparams, int NUM_DIMENSIONS >\nint smp::extender_pos<typeparams,NUM_DIMENSIONS>\n::ex_update_insert_edge (edge_t *edge_in) {\n\n    return 1;\n}\n\n\ntemplate< class typeparams , int NUM_DIMENSIONS>\nint smp::extender_pos<typeparams,NUM_DIMENSIONS>\n::ex_update_delete_vertex (vertex_t *vertex_in){\n\n    return 1;\n}\n\n\ntemplate< class typeparams, int NUM_DIMENSIONS >\nint smp::extender_pos<typeparams,NUM_DIMENSIONS>\n::ex_update_delete_edge (edge_t *edge_in) {\n\n    return 1;\n}\n\n\ntemplate< class typeparams, int NUM_DIMENSIONS >\ndouble smp::extender_pos<typeparams,NUM_DIMENSIONS>\n::set_angle_to_range(double alpha, double min)\n{\n\n    while (alpha >= min + 2.0 * M_PI) {\n        alpha -= 2.0 * M_PI;\n    }\n    while (alpha < min) {\n        alpha += 2.0 * M_PI;\n    }\n    return alpha;\n}\n\ntemplate< class typeparams, int NUM_DIMENSIONS >\ndouble smp::extender_pos<typeparams,NUM_DIMENSIONS>\n::diff_angle_unwrap(double alpha1, double alpha2)\n{\n    double delta;\n\n    // normalize angles alpha1 and alpha2\n    alpha1 = set_angle_to_range(alpha1, 0);\n    alpha2 = set_angle_to_range(alpha2, 0);\n\n    // take difference and unwrap\n    delta = alpha1 - alpha2;\n    if (alpha1 > alpha2) {\n        while (delta > M_PI) {\n            delta -= 2.0 * M_PI;\n        }\n    } else if (alpha2 > alpha1) {\n        while (delta < -M_PI) {\n            delta += 2.0 * M_PI;\n        }\n    }\n    return delta;\n}\n\n\ntemplate< class typeparams, int NUM_DIMENSIONS >\ndouble smp::extender_pos<typeparams,NUM_DIMENSIONS>\n::normangle(double a, double mina){\n\n    double ap,minap;\n    ap=a;\n    minap=mina;\n    while (ap>= (minap+M_PI*2)){\n        ap=ap-M_PI*2;\n    }\n    while(ap<minap){\n        ap=ap+M_PI*2;\n\n    }\n\n    return ap;\n\n}\n\n\n\ntemplate< class typeparams, int NUM_DIMENSIONS >\ndouble smp::extender_pos<typeparams,NUM_DIMENSIONS>\n::f(double rho){\n\n    double Kv;\n    /// New implementation  Kv= max atanh(rho)/rho\n    Kv=1;\n//    Kv=1;\n\n    return tanh(rho*Kv);\n    /// German Paper Version\n\n    //  return (2*v0/M_PI)*atan((M_PI/(2*v0))*rho);\n\n}\n\n\ntemplate< class typeparams, int NUM_DIMENSIONS >\ndouble smp::extender_pos<typeparams,NUM_DIMENSIONS>\n::g(double t){\n    /// German Paper Version\n//        double a;\n//        a=pow((t/T),4);\n//        return a/(a+1);\n\n    /// New implementation\n    return 1;\n\n}\n\n\n\n\n\ntemplate< class typeparams, int NUM_DIMENSIONS >\ndouble* smp::extender_pos<typeparams,NUM_DIMENSIONS>\n::posctrlstep (double x_c, double y_c, double t_c,\n               double x_end, double y_end, double t_end, double ct, double b, int dir) {\n\n\n    /** This function will generate a vector of double as output:\n\n     *  [0] Vl velocity of the left wheel;\n     *  [1] Vr velocity of the right wheel;\n     *  [2] V translational Velocity;\n     *  [3] W Angular Velocity.\n     *  [4] EOT End Of Trajectory\n\n    **/\n\n\n    static double oldBeta,controllerType;\n\n    double Krho,Kalpha,Kbeta,Kphi,Vmax,RhoThreshold1,RhoThreshold2,RhoEndCondition,PhiEndCondition;\n    // [1 3 -1 -1]\n    Krho    = 1.2;\n    Kalpha  = 3;\n    Kbeta   = -1;\n    Kphi    = -1;\n    Vmax    = Krho;\n    //  RhoThreshold1   = 0.04;\n    RhoThreshold1   = 0.005;\n\n    RhoThreshold2   = 0.02;\n    //  RhoThreshold2   = 0.2;\n/// The RRT* edges' lenght is related to the RhoEndCondition\n#if WP>0\n    RhoEndCondition = 0.35;\n#else\n    RhoEndCondition = 0.35;\n#endif\n\n/// the PhiEndCondition has to be setted properly,\n/// small Value, local minima can occur, tested --> greater than 35*M_PI/180\n\n    //  PhiEndCondition = 1*M_PI/180; [NOT IN THE ASTOLFI PAPER :)]\n    PhiEndCondition = 50*M_PI/180;\n\n\n\n    if(ct==0){\n        oldBeta=0;\n        controllerType=1;\n    }\n\n\n    double dx,dy,rho,fRho,alpha,phi,beta,v,w,vl,vr,eot,vi,di;\n    vi=0.1;\n    // rho\n    eot=1;\n    dx=x_end-x_c;\n    dy=y_end -y_c;\n    rho=sqrt(dx*dx+dy*dy);\n    fRho=rho;\n\n    if(fRho>(Vmax/Krho)){\n        fRho=Vmax/Krho;\n    }\n\n\n    //alpha\n\n    alpha=atan2(dy,dx)-t_c;\n    alpha=normangle(alpha,-M_PI);\n\n    //direction\n\n    if (dir==0){\n\n\n        if(alpha>(M_PI/2)) {\n            fRho=-fRho;\n            alpha=alpha-M_PI;\n        }else if(alpha<=-M_PI/2){\n            fRho=-fRho;\n            alpha=alpha+M_PI;\n        }\n    }\n    else if(dir==-1){\n        fRho=-fRho;\n        alpha=alpha+M_PI;\n        if(alpha>M_PI){\n            alpha=alpha-2*M_PI;\n        }\n    }\n\n\n    //phi\n\n    phi=t_end-t_c;\n    phi=normangle(phi, -M_PI);\n\n    beta=normangle(phi-alpha, -M_PI);\n\n    if ((abs(oldBeta-beta)>M_PI)){\n        beta=oldBeta;\n    }\n    oldBeta=beta;\n\n    //set speed\n\n\n#if WP>0\n    v=Krho*f(fRho)*g(ct+1);\n    w=(Kalpha*alpha+Kbeta*beta)*g(ct+1);\n#else\n    v=Krho*fRho;\n    w=Kalpha*alpha+Kbeta*beta;\n#endif\n\n\n\n\n\n#if WP>0\n    if (rho<this->rho_endcondition && abs(phi)<this->phi_endcondition ){\n#else\n    if (rho<RhoEndCondition && abs(phi)<PhiEndCondition){\n\n#endif\n\n\n        eot=1;\n        //    cout<<\"eot evaluated... \"<<eot<<endl;\n    }\n    else {\n        eot=0;\n        //   cout<<\"eot evaluated... \"<<eot<<endl;\n\n    }\n\n    if(eot){\n#if WP>0\n#else\n        v=0.0;\n#endif\n        w=0.;\n    }\n\n\n    //Convert speed to wheel speed\n\n    vl=v-w*b/2;\n\n    if(abs(vl)>Vmax){\n\n        if(vl<0){\n            vl=Vmax*-1;}\n        else{\n            vl=Vmax;}\n    }\n\n    vr=v+w*b/2;\n\n    if(abs(vr)>Vmax){\n        if(vr<0){\n            vr=Vmax*-1;}\n        else{\n            vr=Vmax;}\n    }\n\n\n\n\n\n    result[0]=vl;\n    result[1]=vr;\n    result[2]=v;\n    result[3]=w;\n    result[4]=eot;\n\n\n    return result;\n\n}\n\n\n\n\n\ntemplate< class typeparams, int NUM_DIMENSIONS >\ndouble smp::extender_pos<typeparams,NUM_DIMENSIONS>\n:: posctrl(state_t *state_ini, state_t *state_fin,int dir,double b, double dt ,\n           list<state_t *> *list_states_out, list<input_t *> *list_inputs_out) {\n\n\n    double sl,sr,oldSl,oldSr,t,eot,dSl,dSr,dSm,dSd,vl,vr,enc_l,enc_r;\n\n    enc_l=0;\n    enc_r=0;\n    sl=0;\n    sr=0;\n    oldSl=0;\n    oldSr=0;\n    eot=0;\n    t=0;\n    vl=0;\n    vr=0;\n\n    double x,y,th;\n    x=(*state_ini)[0];\n    y=(*state_ini)[1];\n    th=(*state_ini)[2];\n\n    this->xi=x;\n    this->yi=y;\n\n    double vv,ww,ths;\n    vv=0;\n    ww=0;\n    ths=0.1;\n\n    double dist;\n    dist=0;\n\n    if(list_states_out){\n\n\n        while(eot==0){\n            // calculate distance for both wheels\n            dSl=sl-oldSl;\n            dSr=sr-oldSr;\n            dSm=(dSl+dSr)/2;\n\n\n            dSd=(dSr-dSl)/b;\n            state_t *curr = new state_t;\n            input_t *ve = new input_t;\n\n\n\n            (*curr)[0]=x+dSm*cos(th+dSd/2);\n            (*curr)[1]=y+dSm*sin(th+dSd/2);\n            (*curr)[2]=normangle(th+dSd, -M_PI);\n\n\n            intRes= posctrlstep ((*curr)[0],(*curr)[1],(*curr)[2],(*state_fin)[0], (*state_fin)[1],(*state_fin)[2], t,b,dir);\n            //Save the velocity commands,eot\n            vv=intRes[2];\n            ww=intRes[3];\n            (*ve)[0]=intRes[2];\n            (*ve)[1]=intRes[3];\n            eot=intRes[4];\n            vl=intRes[0];\n            vr=intRes[1];\n\n\n\n            //Increase the timer\n            t=t+dt;\n\n            // keep track of previous wheel position\n            oldSl=sl;\n            oldSr=sr;\n\n\n            // increase encoder values\n            enc_l=enc_l+dt*vl;\n            enc_r=enc_r+dt*vr;\n\n            sl=enc_l;\n            sr=enc_r;\n\n            //\n            float dxl,dyl;\n            dxl=(*state_fin)[0]-(*curr)[0];\n            dyl=(*state_fin)[1]-(*curr)[1];\n            dist=sqrt(dxl*dxl+dyl*dyl);\n\n\n\n            //save the state for the next sample\n            x=(*curr)[0];\n            y=(*curr)[1];\n            th=(*curr)[2];\n\n\n            if(eot==1){\n\n            /// save the last state!!!\n            state_t *save = new state_t;\n            input_t *vesave = new input_t;\n            (*vesave)[0]=intRes[2];\n            (*vesave)[1]=intRes[3];\n            dSl=sl-oldSl;\n            dSr=sr-oldSr;\n            dSm=(dSl+dSr)/2;\n            dSd=(dSr-dSl)/b;\n            (*save)[0]=x+dSm*cos(th+dSd/2);\n            (*save)[1]=y+dSm*sin(th+dSd/2);\n            (*save)[2]=normangle(th+dSd, -M_PI);\n            // Add current values to the Trajectory\n            list_states_out->push_back ((curr));\n            list_inputs_out->push_back ((ve));\n\n            list_states_out->push_back ((save));\n            list_inputs_out->push_back ((vesave));\n\n            }\n            else\n\n            {\n            // Add current values to the Trajectory\n            list_states_out->push_back ((curr));\n            list_inputs_out->push_back ((ve));\n            }\n\n        }\n    }\n    return dist;\n\n\n\n}\n\n\ntemplate< class typeparams, int NUM_DIMENSIONS >\nsmp::extender_pos<typeparams,NUM_DIMENSIONS>\n::extender_pos () {\n     result= (double*)malloc(sizeof(double)*5);\n     intRes= (double*) malloc(sizeof(double)*5);\n     this->dt_=0.01;\n     this->rho_endcondition=0.15;\n     this->L_axis=0.5;\n     this->phi_endcondition = 20*M_PI/180;\n\n\n}\n\n\ntemplate< class typeparams, int NUM_DIMENSIONS >\nsmp::extender_pos<typeparams,NUM_DIMENSIONS>\n::~extender_pos () {\n\n\n}\n\n\ntemplate< class typeparams, int NUM_DIMENSIONS>\nint smp::extender_pos<typeparams, NUM_DIMENSIONS>\n::extend (state_t *state_from_in, state_t *state_towards_in,\n          int *exact_connection_out, trajectory_t *trajectory_out,\n          list<state_t*> *intermediate_vertices_out) {\n\n    int dir;\n    dir=1;\n\n    double b,dt,d,myEps;\n    dt=this->dt_;\n    T=0.31;\n    /// Base\n    // b=0.4;\n    b=this->L_axis;\n    /// myEps=0.1 for pursuit\n    /// myEps=0.25 no pursuit\n#if WP>0\n    myEps=0.50;\n#else\n    myEps=0.5;\n#endif\n    //   cout<<\"call posctrl /....\"<<endl<<endl;\n    intermediate_vertices_out->clear ();\n    trajectory_out->clear ();\n    d=posctrl(state_from_in, state_towards_in,dir, b, dt,&(trajectory_out->list_states),&(trajectory_out->list_inputs));\n\n\n    if(d<myEps)\n    {\n        (*exact_connection_out)=1;\n        return 1;\n\n    }   else\n\n    {\n\n        (*exact_connection_out)=0;\n        return 0;\n\n    }\n\n\n\n\n}\n", "meta": {"hexsha": "c2a030ec3154fd24cd83594e8811522261575bac", "size": 10586, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smp/components/extenders/pos.hpp", "max_stars_repo_name": "reobaird/srl_global_planner", "max_stars_repo_head_hexsha": "e2a4b3ea60a0b870aba0ca3e96ea07899c411bd2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 120.0, "max_stars_repo_stars_event_min_datetime": "2016-09-01T07:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T23:07:50.000Z", "max_issues_repo_path": "include/smp/components/extenders/pos.hpp", "max_issues_repo_name": "dz306271098/srl_global_planner", "max_issues_repo_head_hexsha": "e2a4b3ea60a0b870aba0ca3e96ea07899c411bd2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2015-08-26T05:24:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T06:57:28.000Z", "max_forks_repo_path": "include/smp/components/extenders/pos.hpp", "max_forks_repo_name": "dz306271098/srl_global_planner", "max_forks_repo_head_hexsha": "e2a4b3ea60a0b870aba0ca3e96ea07899c411bd2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2015-08-07T07:54:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T01:14:57.000Z", "avg_line_length": 19.4953959484, "max_line_length": 125, "alphanum_fraction": 0.56933686, "num_tokens": 3208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.5278363574125493}}
{"text": "#include <iostream>\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <sensor_msgs/Imu.h>\n#include <sensor_msgs/Range.h>\n#include <nav_msgs/Odometry.h>\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n#include <ros/time.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/transform_datatypes.h>\n#include <math.h>\n#include \"pose.h\"\n\n#define DEBUG_ODOM false\n#define DEBUG_IMU false\n#define DEBUG_TF false\n#define DEBUG_COV false\n\nusing namespace std;\nusing namespace Eigen;\nros::Publisher odom_pub;\nMatrixXd Q = MatrixXd::Identity(12, 12); // For propogate, IMU noise\nMatrixXd Rt = MatrixXd::Identity(6, 6);   // For update, Odometry noise\n\n\n// ros::Time current_time, last_time;\nros::Time current_time;\nros::Time last_time;\n\n/*  Mean and covariance matrixs\n    ps: present state\n    ba: state propogated\n    ns: next state\n\t[x1] x(0)  x(1)  x(2) = position, x y z\n\t[x2] x(3)  x(4)  x(5) = orientation, roll pitch yaw, ZXY Euler\n\t[x3] x(6)  x(7)  x(8) = linear velocity, x y z\n\t[x4] x(9)  x(10) x(11)= gyroscope bias\n\t[x5] x(12) x(13) x(14)= accelerator bias   \t\t\t\t\t\t\t*/\nVectorXd mean_ps= MatrixXd::Zero(15, 1 );\nVectorXd mean_ba= MatrixXd::Zero(15, 1 );\nVectorXd mean_ns= MatrixXd::Zero(15, 1 );\nMatrixXd cov_ps = MatrixXd::Identity(15, 15);\nMatrixXd cov_ba = MatrixXd::Identity(15, 15);\nMatrixXd cov_ns = MatrixXd::Identity(15, 15);\n/* Observation Model\t*/\nVectorXd g_ut(6);\n\n// Initially use a constant, later need to read from the environment\nfloat g = 9.82;\nbool IMU_UPDATED = false;\nbool CAMERA_UPDATED = false;\n\n/*  Process model, since IMU is an internal measurement\n    the gyro bias and accelerator bias is part to the state\n    From the process model, IMU measurement - bias = real state\n    Nov. 16th, 2016 note:\n    1. Everything IMU has an input, propogate once;\n    2. Getting g ~ 9.8 m.s^-2 is tricky\n    3. Use MATLAB to from the A, B, and U\n    Optimal:\n    4. The best way to handle timestamp difference is to store the propogated\n       and origin data, and trace back to the most recent propogated value\n       and repropogate after the odometry reading comes\n*/\nvoid imu_callback(const sensor_msgs::Imu::ConstPtr &msg)\n{\n\tIMU_UPDATED = true;\n\t#if DEBUG_IMU\n\t\t// cout << \"Before process, the mean_ps is: \" << endl << mean_ps << endl;\n\t\t// cout << \"The cov_ps is: \" << endl << cov_ps << endl;\n    \tROS_INFO(\"Imu Seq: [%d]\", msg->header.seq);\n    \tROS_INFO(\"Imu linear acceleration x: [%f], y: [%f], z: [%f]\", \\\n\t\tmsg->linear_acceleration.x,msg->linear_acceleration.y,msg->linear_acceleration.z);\n    \tROS_INFO(\"Imu angular velocity x: [%f], y: [%f], z: [%f]\", \\\n    \tmsg->angular_velocity.x,msg->angular_velocity.y,msg->angular_velocity.z);\n\t#endif\n    MatrixXd At = MatrixXd::Identity(15, 15);\n    MatrixXd Ut = MatrixXd::Identity(15, 12);\n    MatrixXd Ft = MatrixXd::Identity(15, 15);\n    MatrixXd Vt = MatrixXd::Identity(15, 12);\n    last_time = current_time;\n\tfloat dt = 0.0;\n\tif\t(current_time < msg->header.stamp) { // Check for its first time\n\t\tcurrent_time = msg->header.stamp;\n    \tdt = current_time.toSec() - last_time.toSec();\n\t}  else  {\n\t\tcurrent_time = msg->header.stamp;\n\t\tdt = 0.0;\n\t\treturn;\n\t}\n\n\t// double x11= mean_ps(0), x12= mean_ps(1), x13= mean_ps(2);\n\tdouble x21= mean_ps(3), x22= mean_ps(4), x23= mean_ps(5);\n\tdouble x31= mean_ps(6), x32= mean_ps(7), x33= mean_ps(8);\n\tdouble x41= mean_ps(9), x42= mean_ps(10),x43= mean_ps(11);\n\tdouble x51= mean_ps(12),x52= mean_ps(13),x53= mean_ps(14);\n\t// input u : acceleration, augular_velocity\n\tdouble am1= msg->linear_acceleration.x;\n\tdouble am2= msg->linear_acceleration.y;\n\tdouble am3= msg->linear_acceleration.z;\n\tdouble wm1= msg->angular_velocity.x;\n\tdouble wm2= msg->angular_velocity.y;\n\tdouble wm3= msg->angular_velocity.z;\n\n\t/**************************************************************************/\n\t/* updated to f(mu_t_1, u_t, 0), At(mu_t_1, u_t, 0), and Ut               */\n\t/* Generated by matlab ELEC6910P_Project2Phase2.m                         */\n\t/**************************************************************************/\n\n\tVectorXd f_t_1(15);\n\tf_t_1 <<\n\t\tx31,\n\t\tx32,\n\t\tx33,\n\t\twm1*cos(x22) - 0*cos(x22) - x41*cos(x22) - 0*sin(x22) + wm3*sin(x22) - x43*sin(x22),\n\t\t-(0*cos(x21) - wm2*cos(x21) + x42*cos(x21) - 0*cos(x22)*sin(x21) + wm3*cos(x22)*sin(x21) - x43*cos(x22)*sin(x21) + 0*sin(x21)*sin(x22) - wm1*sin(x21)*sin(x22) + x41*sin(x21)*sin(x22))/cos(x21),\n\t\t-(0*cos(x22) - wm3*cos(x22) + x43*cos(x22) - 0*sin(x22) + wm1*sin(x22) - x41*sin(x22))/cos(x21),\n\t\tcos(x21)*sin(x23)*(0 - am2 + x52) - (cos(x23)*sin(x22) + cos(x22)*sin(x21)*sin(x23))*(0 - am3 + x53) - (cos(x22)*cos(x23) - sin(x21)*sin(x22)*sin(x23))*(0 - am1 + x51),\n\t\t- (cos(x22)*sin(x23) + cos(x23)*sin(x21)*sin(x22))*(0 - am1 + x51) - (sin(x22)*sin(x23) - cos(x22)*cos(x23)*sin(x21))*(0 - am3 + x53) - cos(x21)*cos(x23)*(0 - am2 + x52),\n\t\tcos(x21)*sin(x22)*(0 - am1 + x51) - cos(x21)*cos(x22)*(0 - am3 + x53) - sin(x21)*(0 - am2 + x52) - g,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0;\n\n\tAt <<\n\t\t0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0,                                                                                                                                 0,                                                 wm3*cos(x22) - 0*cos(x22) - x43*cos(x22) + 0*sin(x22) - wm1*sin(x22) + x41*sin(x22),                                                                                                                                                                             0, 0, 0, 0,                     -cos(x22),  0,                    -sin(x22),                                                0,                  0,                                                0,\n\t\t0, 0, 0,                              (0*cos(x22) - wm3*cos(x22) + x43*cos(x22) - 0*sin(x22) + wm1*sin(x22) - x41*sin(x22))/cos(x21)^2,                          -(sin(x21)*(0*cos(x22) - wm1*cos(x22) + x41*cos(x22) + 0*sin(x22) - wm3*sin(x22) + x43*sin(x22)))/cos(x21),                                                                                                                                                                             0, 0, 0, 0, -(sin(x21)*sin(x22))/cos(x21), -1, (cos(x22)*sin(x21))/cos(x21),                                                0,                  0,                                                0,\n\t\t0, 0, 0,                  -(sin(x21)*(0*cos(x22) - wm3*cos(x22) + x43*cos(x22) - 0*sin(x22) + wm1*sin(x22) - x41*sin(x22)))/cos(x21)^2,                                      (0*cos(x22) - wm1*cos(x22) + x41*cos(x22) + 0*sin(x22) - wm3*sin(x22) + x43*sin(x22))/cos(x21),                                                                                                                                                                             0, 0, 0, 0,             sin(x22)/cos(x21),  0,           -cos(x22)/cos(x21),                                                0,                  0,                                                0,\n\t\t0, 0, 0, cos(x21)*sin(x22)*sin(x23)*(0 - am1 + x51) - cos(x21)*cos(x22)*sin(x23)*(0 - am3 + x53) - sin(x21)*sin(x23)*(0 - am2 + x52), (cos(x23)*sin(x22) + cos(x22)*sin(x21)*sin(x23))*(0 - am1 + x51) - (cos(x22)*cos(x23) - sin(x21)*sin(x22)*sin(x23))*(0 - am3 + x53), (cos(x22)*sin(x23) + cos(x23)*sin(x21)*sin(x22))*(0 - am1 + x51) + (sin(x22)*sin(x23) - cos(x22)*cos(x23)*sin(x21))*(0 - am3 + x53) + cos(x21)*cos(x23)*(0 - am2 + x52), 0, 0, 0,                             0,  0,                            0,   sin(x21)*sin(x22)*sin(x23) - cos(x22)*cos(x23),  cos(x21)*sin(x23), - cos(x23)*sin(x22) - cos(x22)*sin(x21)*sin(x23),\n\t\t0, 0, 0, cos(x23)*sin(x21)*(0 - am2 + x52) - cos(x21)*cos(x23)*sin(x22)*(0 - am1 + x51) + cos(x21)*cos(x22)*cos(x23)*(0 - am3 + x53), (sin(x22)*sin(x23) - cos(x22)*cos(x23)*sin(x21))*(0 - am1 + x51) - (cos(x22)*sin(x23) + cos(x23)*sin(x21)*sin(x22))*(0 - am3 + x53), cos(x21)*sin(x23)*(0 - am2 + x52) - (cos(x23)*sin(x22) + cos(x22)*sin(x21)*sin(x23))*(0 - am3 + x53) - (cos(x22)*cos(x23) - sin(x21)*sin(x22)*sin(x23))*(0 - am1 + x51), 0, 0, 0,                             0,  0,                            0, - cos(x22)*sin(x23) - cos(x23)*sin(x21)*sin(x22), -cos(x21)*cos(x23),   cos(x22)*cos(x23)*sin(x21) - sin(x22)*sin(x23),\n\t\t0, 0, 0,                            cos(x22)*sin(x21)*(0 - am3 + x53) - cos(x21)*(0 - am2 + x52) - sin(x21)*sin(x22)*(0 - am1 + x51),                                                               cos(x21)*cos(x22)*(na1 - am1 + x51) + cos(x21)*sin(x22)*(0 - am3 + x53),                                                                                                                                                                             0, 0, 0, 0,                             0,  0,                            0,                                cos(x21)*sin(x22),          -sin(x21),                               -cos(x21)*cos(x22),\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n\n\tUt <<\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0,                     -cos(x22),  0,                    -sin(x22), 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0, -(sin(x21)*sin(x22))/cos(x21), -1, (cos(x22)*sin(x21))/cos(x21), 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0,             sin(x22)/cos(x21),  0,           -cos(x22)/cos(x21), 0, 0, 0, 0, 0, 0,\n\t\t   sin(x21)*sin(x22)*sin(x23) - cos(x22)*cos(x23),  cos(x21)*sin(x23), - cos(x23)*sin(x22) - cos(x22)*sin(x21)*sin(x23), 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t - cos(x22)*sin(x23) - cos(x23)*sin(x21)*sin(x22), -cos(x21)*cos(x23),   cos(x22)*cos(x23)*sin(x21) - sin(x22)*sin(x23), 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t                                cos(x21)*sin(x22),          -sin(x21),                               -cos(x21)*cos(x22), 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n\t\t0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0;\n\n\tFt = MatrixXd::Identity(15, 15) + dt * At;\n    Vt = dt * Ut;\n\n    // Calculate the propogagted mean and covariance\n    mean_ba = mean_ps + dt * f_t_1;\n    cov_ba = Ft * cov_ps * Ft.transpose() + Vt * Q * Vt.transpose();\n\t#if DEBUG_IMU\n\t\t// cout<< \"After process, the mean_ba became\" << endl << mean_ba << endl;\n\t\t// cout<< \"The cov_ba became\" << endl << cov_ba << endl;\n\t#endif\n\t#if DEBUG_COV\n\t\tROS_INFO(\"Imu Seq: [%d]\", msg->header.seq);\n\t\tcout<< \"the mean_ba (0-5):\" << endl << mean_ba.head(6) << endl;\n\t\t// cout<< \"The cov_ba[6,6]  :\" << endl << cov_ba.topLeftCorner(6, 6) << endl;\n\t#endif\n}\n\n// store singularity info\ndouble phi_ppg;\ndouble the_ppg;\ndouble psi_ppg;\nvoid odom_callback(const nav_msgs::Odometry::ConstPtr &msg)\n{\n\tCAMERA_UPDATED = true;\n    //your code for update\n    //camera position in the IMU frame = (0, -0.04, -0.02)\n    //camera orientaion in the IMU frame = Quaternion(0, 0, 1, 0); w x y z, respectively\n    //\t\t\t   RotationMatrix << -1, 0, 0,\n    //\t\t\t\t\t\t\t      0, 1, 0,\n    //                                0, 0, -1;\n\n\tVectorXd zt(6); // Camera reading in x,y,z, ZXY Euler\n\n\t/*                     Transformation from TF                           */\n\t// Get the world frame in camera frame transformation from the msg\n\ttf::Transform camera_pose_cw;\n\ttf::poseMsgToTF(msg->pose.pose, camera_pose_cw);\n\n\t// Record the camera frame in the IMU frame from TA\n\ttf::Transform transform_ic;\n\ttransform_ic.setOrigin( tf::Vector3(0, -0.04, -0.02) );\n\ttransform_ic.setRotation( tf::Quaternion(0, 0, -1, 0) );\n\ttf::Transform camera_pose_iw = transform_ic * camera_pose_cw;\n\ttf::Transform camera_pose_wi = camera_pose_iw.inverse();\n\n\tgeometry_msgs::Transform camera_pose_wi_geo;\n\ttf::transformTFToMsg(camera_pose_wi, camera_pose_wi_geo);\n\n\t/*                     Transformation from Eigen                       */\n\tgeometry_msgs::Quaternion q_cw = msg->pose.pose.orientation;\n\t// camera to tag world\n\tMatrix3d R_cw = Quaterniond(q_cw.w, q_cw.x, q_cw.y, q_cw.z).toRotationMatrix();\n\tVector3d T_cw;\n\tT_cw << msg->pose.pose.position.x, msg->pose.pose.position.y, msg->pose.pose.position.z;\n//\tMatrixXd H_cw(4,4);\n//\tH_cw.col(0) << R_cw.col(0), 0;\n//\tH_cw.col(1) << R_cw.col(1), 0;\n//\tH_cw.col(2) << R_cw.col(2), 0;\n//\tH_cw.col(3) << T_cw   , 1;\n\n\t// IMU to camera frame\n\tMatrix3d R_ic = Quaterniond(0, 0, 1, 0).toRotationMatrix();\n    Vector3d T_ic = Vector3d(0, -0.04, -0.02);\n//\tMatrixXd H_ic(4,4);\n//\tH_ic << -1, 0,  0,  0,\n//\t\t\t 0, 1,  0, -0.04,\n//\t\t\t 0, 0, -1, -0.02,\n//\t\t\t 0, 0,  0,  1;\n\n\t// IMU to tag world\n\t// Matrix3d R_iw = R_ic * R_cw;\n\t// Vector3d T_iw = R_ic * T_cw + T_ic;\n\n\t// tag world to IMU\n//\tMatrixXd H_wi(4,4);\n//\tH_wi = H_ic.inverse() * H_cw.inverse();\n\t// Matrix3d R_wi = R_iw.inverse();\n\t// Vector3d T_wi = -R_wi*T_iw;\n\tMatrix3d R_wi;\n\tVector3d T_wi;\n\tR_wi =  R_cw.transpose() *  R_ic.transpose();\n\tT_wi = -R_cw.transpose() * (R_ic.transpose() * T_ic + T_cw);\n//\tR_wi = H_wi.topLeftCorner(3, 3);\n//\tT_wi = H_wi.topRightCorner(3, 1);\n\n\t#if DEBUG_TF\n\t\tQuaterniond R_wi_q(R_wi);\n\t\tcout << \"camera_pose_wi_geo transformation from TF is: \" << endl;\n\t\tcout << camera_pose_wi_geo.translation.x << endl;\n\t\tcout << camera_pose_wi_geo.translation.y << endl;\n\t\tcout << camera_pose_wi_geo.translation.z << endl;\n\t\tcout << \"quaternion from TF is: \" << endl;\n\t\tcout << camera_pose_wi_geo.rotation.w << endl;\n\t\tcout << camera_pose_wi_geo.rotation.x << endl;\n\t\tcout << camera_pose_wi_geo.rotation.y << endl;\n\t\tcout << camera_pose_wi_geo.rotation.z << endl;\n\t\tcout << \"camera_pose_wi_geo transformation from Eigen is: \" << endl;\n\t\tcout << T_wi(0) << endl;\n\t\tcout << T_wi(1) << endl;\n\t\tcout << T_wi(2) << endl;\n\t\tcout << \"quaternion from Eigen is: \" << endl;\n\t\tcout << R_wi_q.w() << endl;\n\t\tcout << R_wi_q.x() << endl;\n\t\tcout << R_wi_q.y() << endl;\n\t\tcout << R_wi_q.z() << endl;\n\t#endif\n\tif (DEBUG_TF) {\n\t\tzt(0) = camera_pose_wi_geo.translation.x;\n\t\tzt(1) = camera_pose_wi_geo.translation.y;\n\t\tzt(2) = camera_pose_wi_geo.translation.z;\n\t\t// From quaternion to rotation matrix and then ZXY Euler\n\t\tEigen::Quaterniond R_wi_quat;\n\t\tR_wi_quat.w() = camera_pose_wi_geo.rotation.w;\n\t\tR_wi_quat.x() = camera_pose_wi_geo.rotation.x;\n\t\tR_wi_quat.y() = camera_pose_wi_geo.rotation.y;\n\t\tR_wi_quat.z() = camera_pose_wi_geo.rotation.z;\n\t\tMatrix3d R_wi_tf = R_wi_quat.toRotationMatrix();\n\t\tzt(3) = asin(R_wi_tf(2, 1)); // roll\n\t\tzt(4) = atan2(-R_wi_tf(2, 0) / cos(zt(3)), R_wi_tf(2, 2) / cos(zt(3)) ); // pitch\n\t\tzt(5) = atan2(-R_wi_tf(0, 1) / cos(zt(3)), R_wi_tf(1, 1) / cos(zt(3)) ); // yaw\n\t}\n\telse {\n\t\t// Use the result from Eigen in rviz\n\t\tVector3d rpy_wi = R_to_rpy(R_wi);\n\t\tzt << T_wi, rpy_wi;\n//\t\tzt.head(3) = T_wi;\n//\t\tzt(3) = asin(R_wi(2, 1)); // roll\n//\t\tzt(4) = atan2(-R_wi(2, 0) / cos(zt(3)), R_wi(2, 2)) / cos(zt(3)) ; // pitch\n//\t\tzt(5) = atan2(-R_wi(0, 1) / cos(zt(3)), R_wi(1, 1)) / cos(zt(3)) ; // yaw\n\t}\n\n\tif (msg->header.seq == 0) { // first time callback, initialize all messages\n\t\tmean_ps << zt, MatrixXd::Zero(9, 1);\n\t\tmean_ba << zt, MatrixXd::Zero(9, 1);\n\t\tmean_ns << zt, MatrixXd::Zero(9, 1);\n\t\tphi_ppg = mean_ba(3);\n\t\tthe_ppg = mean_ba(4);\n\t\tpsi_ppg = mean_ba(5);\n\t}\n\n\t// Check if the angle passes the singularity point for ZXY Euler angle\n\n\tdouble phi = zt(3);\n\tdouble the = zt(4);\n\tdouble psi = zt(5);\n\tif (phi_ppg - phi >  2 * M_PI) { zt(3) += 2 * M_PI; cout<<\" phi changes up   2*pi: \" << phi << endl; }\n\tif (phi_ppg - phi < -2 * M_PI) { zt(3) -= 2 * M_PI; cout<<\" phi changes down 2*pi: \" << phi << endl; }\n\tif (the_ppg - the >  2 * M_PI) { zt(4) += 2 * M_PI; cout<<\" the changes up   2*pi: \" << the << endl; }\n\tif (the_ppg - the < -2 * M_PI) { zt(4) -= 2 * M_PI; cout<<\" the changes down 2*pi: \" << the << endl; }\n\tif (psi_ppg - psi >  2 * M_PI) { zt(5) += 2 * M_PI; cout<<\" psi changes up   2*pi: \" << psi << endl; }\n\tif (psi_ppg - psi < -2 * M_PI) { zt(5) -= 2 * M_PI; cout<<\" psi changes down 2*pi: \" << psi << endl; }\n\tphi_ppg = phi;\n\tthe_ppg = the;\n\tpsi_ppg = psi;\n\n    #if DEBUG_ODOM\n        // cout<<\" The x of camera: \" << zt(0) <<endl;\n        // cout<<\" The y of camera: \" << zt(1) <<endl;\n        // cout<<\" The z of camera: \" << zt(2) <<endl;\n        cout<<\" mean_ba(3) : \" << mean_ba(3) <<endl;\n        cout<<\" mean_ba(4) : \" << mean_ba(4) <<endl;\n        cout<<\" mean_ba(5) : \" << mean_ba(5) <<endl;\n\t\tcout<<\" zt(3) : \" << zt(3) <<endl;\n        cout<<\" zt(4) : \" << zt(4) <<endl;\n        cout<<\" zt(5) : \" << zt(5) <<endl;\n        // cout<<\" The pose of camera is in the coordinate frame: \" <<  msg->header.frame_id <<endl;\n        // cout<<\" The twist of camera is in the child frame: \" <<  msg->child_frame_id <<endl;\n    #endif\n\n    /*     Update, with C and W matrix\t\t\t\t\t\t\t\t\t\t  */\n    /*     Linear for this case, but still use  Extended Kalman Filter        */\n    MatrixXd Kt = MatrixXd::Identity(15, 6); // Kalman\n    MatrixXd Ct = MatrixXd::Identity(6, 15);\n    // MatrixXd Wt = MatrixXd::Identity(6, 6);\n\n    Kt = cov_ba * Ct.transpose() * ((Ct * cov_ba * Ct.transpose() + Rt).inverse());\n\tg_ut << mean_ba(0), mean_ba(1), mean_ba(2), mean_ba(3), mean_ba(4), mean_ba(5);\n    mean_ns = mean_ba + Kt * (zt - g_ut);\n    cov_ns  = cov_ba  - Kt * Ct * cov_ba;\n    mean_ps = mean_ns;\n    cov_ps  = cov_ns;\n\n\t// 2016.12.8 reconstruction\n\tVector3d X_rpy;\n\tX_rpy(0) = mean_ns(3);\n\tX_rpy(1) = mean_ns(4);\n\tX_rpy(2) = mean_ns(5);\n\tQuaterniond Q_output;\n\tQ_output = rpy_to_R(X_rpy);\n\n    nav_msgs::Odometry ekf_odom;\n\tif\t(IMU_UPDATED) {\n\t\tekf_odom.header.seq = msg->header.seq;\n\t\tekf_odom.header.stamp = msg->header.stamp;\n\t\tekf_odom.header.frame_id = \"world\";\n\t\tekf_odom.pose.pose.position.x = mean_ns(0);\n\t\tekf_odom.pose.pose.position.y = mean_ns(1);\n\t\tekf_odom.pose.pose.position.z = mean_ns(2);\n\t\tekf_odom.pose.pose.orientation.w = Q_output.w();\n\t\tekf_odom.pose.pose.orientation.x = Q_output.x();\n\t\tekf_odom.pose.pose.orientation.y = Q_output.y();\n\t\tekf_odom.pose.pose.orientation.z = Q_output.z();\n\t\tekf_odom.twist.twist.linear.x = mean_ns(6);\n\t\tekf_odom.twist.twist.linear.y = mean_ns(7);\n\t\tekf_odom.twist.twist.linear.z = mean_ns(8);\n\t}\n\telse {\n\t\tekf_odom = *msg;\n\t}\n\n    odom_pub.publish(ekf_odom);\n\n\t#if DEBUG_ODOM\n\t\t// cout<<\" The Kalman gain is:\" << endl << Kt << endl;\n\t\t// cout<<\" The mean_ns is:\" << endl << mean_ns << endl;\n\t\tcout<<\" The cov_ns is:\" << endl << cov_ns << endl;\n\t\t// cout<<\" The g_ut is:\" << endl << g_ut << endl;\n\t\tcout<<\" The odometry before EKF:\" << endl;\n        ROS_INFO(\"Seq: [%d]\", msg->header.seq);\n\t\tROS_INFO(\"Position-> x: [%f], y: [%f], z: [%f]\", camera_pose_wi_geo.translation.x,camera_pose_wi_geo.translation.y, camera_pose_wi_geo.translation.z);\n\t\tROS_INFO(\"Orientation-> x: [%f], y: [%f], z: [%f], w: [%f]\", camera_pose_wi_geo.rotation.x, camera_pose_wi_geo.rotation.y, camera_pose_wi_geo.rotation.z, camera_pose_wi_geo.rotation.w);\n\t\tcout<<\" The odometry after EKF:\" << endl;\n        ROS_INFO(\"Seq: [%d]\", ekf_odom.header.seq);\n\t\tROS_INFO(\"Position-> x: [%f], y: [%f], z: [%f]\", ekf_odom.pose.pose.position.x,ekf_odom.pose.pose.position.y, ekf_odom.pose.pose.position.z);\n\t\tROS_INFO(\"Orientation-> x: [%f], y: [%f], z: [%f], w: [%f]\", ekf_odom.pose.pose.orientation.x, ekf_odom.pose.pose.orientation.y, ekf_odom.pose.pose.orientation.z, ekf_odom.pose.pose.orientation.w);\n\t\tROS_INFO(\"Vel-> Linear: [%f], Angular: [%f]\", ekf_odom.twist.twist.linear.x,ekf_odom.twist.twist.angular.z);\n    #endif\n\t#if DEBUG_COV\n\t\tROS_INFO(\"Cam Seq: [%d]\", ekf_odom.header.seq);\n\t\tcout<< \"the mean_ns (0-5):\" << endl << mean_ns.head(6) << endl;\n\t\t// cout<< \"The cov_ns[6,6]  :\" << endl << cov_ns.topLeftCorner(6, 6) << endl;\n\t#endif\n\t// cout<<\" The end of Odometry callback\" << endl << endl;\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"ekf\");\n    ros::NodeHandle n(\"~\");\n\tros::Time::init();\n\tcurrent_time = ros::Time::now();\n    ros::Subscriber s1 = n.subscribe(\"imu\", 1000, imu_callback);\n    ros::Subscriber s2 = n.subscribe(\"tag_odom\", 1000, odom_callback);\n    odom_pub = n.advertise<nav_msgs::Odometry>(\"ekf_odom\", 100);\n    // Q imu covariance matrix; Rt visual odomtry covariance matrix\n    Q.topLeftCorner(6, 6) = 0.01 * Q.topLeftCorner(6, 6);\n    Q.bottomRightCorner(6, 6) = 0.01 * Q.bottomRightCorner(6, 6);\n    Rt.topLeftCorner(3, 3) = 0.5 * Rt.topLeftCorner(3, 3);\n    Rt.bottomRightCorner(3, 3) = 0.5 * Rt.bottomRightCorner(3, 3);\n    Rt.bottomRightCorner(1, 1) = 0.1 * Rt.bottomRightCorner(1, 1);\n\n    ros::spin();\n}\n", "meta": {"hexsha": "a8b22ceb5e34d44638a4324ac984f7f989f0d459", "size": 20613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ekf/src/ekf_node.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/src_old/ekf_node.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/src_old/ekf_node.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": 49.5504807692, "max_line_length": 643, "alphanum_fraction": 0.5422791442, "num_tokens": 7635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.5278363526915639}}
{"text": "#include \"joint_tracker/pdf/NonLinearRevoluteMeasurementPdf.h\"\n\n#include <Eigen/Geometry>\n#include <lgsm/Lgsm>\n#include <ros/ros.h>\n\n#include \"omip_common/OMIPUtils.h\"\n\n\nusing namespace BFL;\n\n#define REV_PDF_DIM 6\n#define REV_CONDITIONAL_VAR_DIM 7\n#define REV_NUM_CONDITIONAL_ARGS 2\n\nNonLinearRevoluteMeasurementPdf::NonLinearRevoluteMeasurementPdf(const Gaussian& additiveNoise) :\n    AnalyticConditionalGaussianAdditiveNoise(additiveNoise,REV_NUM_CONDITIONAL_ARGS),\n    dfx(REV_PDF_DIM, REV_CONDITIONAL_VAR_DIM)\n{\n\n}\n\nNonLinearRevoluteMeasurementPdf::~NonLinearRevoluteMeasurementPdf()\n{\n\n}\n\nMatrixWrapper::ColumnVector NonLinearRevoluteMeasurementPdf::ExpectedValueGet() const\n{\n    ColumnVector state = ConditionalArgumentGet(0);\n\n    double phi = state(1);\n    double theta = state(2);\n    double sp = sin(phi);\n    double cp = cos(phi);\n    double st = sin(theta);\n    double ct = cos(theta);\n\n    double px = state(3);\n    double py = state(4);\n    double pz = state(5);\n\n    Eigen::Vector3d rev_joint_orientation = Eigen::Vector3d(cp * st, sp * st, ct);\n    Eigen::Vector3d rev_joint_position = Eigen::Vector3d(px, py, pz);\n\n    double rv = state(6);\n\n    Eigen::Vector3d joint_translation = (-rv * rev_joint_orientation).cross(rev_joint_position);\n\n    Eigen::Twistd joint_pose = Eigen::Twistd(rv * rev_joint_orientation.x(),\n                                             rv * rev_joint_orientation.y(),\n                                             rv * rev_joint_orientation.z(),\n                                             joint_translation.x(),\n                                             joint_translation.y(),\n                                             joint_translation.z());\n\n    ColumnVector expected_pose(REV_PDF_DIM);\n    expected_pose(1) = joint_pose.vx();\n    expected_pose(2) = joint_pose.vy();\n    expected_pose(3) = joint_pose.vz();\n    expected_pose(4) = joint_pose.rx();\n    expected_pose(5) = joint_pose.ry();\n    expected_pose(6) = joint_pose.rz();\n\n    return expected_pose + this->AdditiveNoiseMuGet();\n}\n\nMatrixWrapper::Matrix NonLinearRevoluteMeasurementPdf::dfGet(unsigned int i) const\n{\n    if (i == 0) //derivative to the first conditional argument (x)\n    {\n        double phi = ConditionalArgumentGet(0)(1);\n        double theta = ConditionalArgumentGet(0)(2);\n        double sp = sin(phi);\n        double cp = cos(phi);\n        double st = sin(theta);\n        double ct = cos(theta);\n\n        double px = ConditionalArgumentGet(0)(3);\n        double py = ConditionalArgumentGet(0)(4);\n        double pz = ConditionalArgumentGet(0)(5);\n        double rv = ConditionalArgumentGet(0)(6);\n\n        dfx = 0;\n\n        dfx(1, 1) = -rv * cp * st * pz;\n        dfx(2, 1) = -rv * sp * st * pz;\n        dfx(3, 1) = rv * st * (cp * px + sp * py);\n        dfx(4, 1) = -rv * sp * st;\n        dfx(5, 1) = rv * cp * st;\n\n        dfx(1, 2) = -rv * (st * py + sp * ct * pz);\n        dfx(2, 2) = rv * (cp * ct * pz + st * px);\n        dfx(3, 2) = rv * ct * (sp * px - cp * py);\n        dfx(4, 2) = rv * cp * ct;\n        dfx(5, 2) = rv * sp * ct;\n        dfx(6, 2) = -rv * st;\n\n        dfx(2, 3) = -rv * ct;\n        dfx(3, 3) = rv * sp * st;\n\n        dfx(1, 4) = rv * ct;\n        dfx(3, 4) = -rv * cp * st;\n\n        dfx(1, 5) = -rv * sp * st;\n        dfx(2, 5) = rv * cp * st;\n\n        dfx(1, 6) = ct * py - sp * st * pz;\n        dfx(2, 6) = cp * st * pz - ct * px;\n        dfx(3, 6) = st * (sp * px - cp * py);\n        dfx(4, 6) = cp * st;\n        dfx(5, 6) = sp * st;\n        dfx(6, 6) = ct;\n\n        dfx(1, 7) = 0;\n        dfx(2, 7) = 0;\n        dfx(3, 7) = 0;\n        dfx(4, 7) = 0;\n        dfx(5, 7) = 0;\n        dfx(6, 7) = 0;\n        return dfx;\n    }\n    else\n    {\n        ROS_ERROR_STREAM_NAMED( \"NonLinearRevoluteMeasurementPdf::dfGet\",\n                    \"The derivative is not implemented for the \" << i << \"th conditional argument\");\n        exit(BFL_ERRMISUSE);\n    }\n}\n\n", "meta": {"hexsha": "31ddf797f3469b339f5261bad7bd2b7c762021a5", "size": 3908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "joint_tracker/src/pdf/NonLinearRevoluteMeasurementPdf.cpp", "max_stars_repo_name": "tu-rbo/omip", "max_stars_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2016-11-10T16:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T20:11:39.000Z", "max_issues_repo_path": "joint_tracker/src/pdf/NonLinearRevoluteMeasurementPdf.cpp", "max_issues_repo_name": "tu-rbo/omip", "max_issues_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-28T13:22:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-22T22:01:58.000Z", "max_forks_repo_path": "joint_tracker/src/pdf/NonLinearRevoluteMeasurementPdf.cpp", "max_forks_repo_name": "tu-rbo/omip", "max_forks_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-11-25T18:24:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T03:20:33.000Z", "avg_line_length": 29.8320610687, "max_line_length": 100, "alphanum_fraction": 0.5545035824, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.5278363521686912}}
{"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// Filename: matrix_free_2.cpp (part of MTL4)\n\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\tmtl::vampir_trace<9901> tracer;\n\tassert(int(size(v)) == m * n);\n\tVector w(m * n);\n\n\t// Inner domain\n\tfor (int i= 1; i < m-1; i++)\n\t    for (int j= 1, k= i * n + j; j < n-1; j++, k++) \n\t\tw[k]= 4 * v[k] - v[k-n] - v[k+n] - v[k-1] - v[k+1]; \n\t    \n\t// Upper border\n\tfor (int j= 1; j < n-1; j++) \n\t    w[j]= 4 * v[j] - v[j+n] - v[j-1] - v[j+1];\n\n\t// Lower border\n\tfor (int j= 1, k= (m-1) * n + j; j < n-1; j++, k++) \n\t    w[k]= 4 * v[k] - v[k-n] - v[k-1] - v[k+1]; \n\t\n\t// Left border\n\tfor (int i= 1, k= n; i < m-1; i++, k+= n)\n\t    w[k]= 4 * v[k] - v[k-n] - v[k+n] - v[k+1]; \n\n\t// Right border\n\tfor (int i= 1, k= n+n-1; i < m-1; i++, k+= n)\n\t    w[k]= 4 * v[k] - v[k-n] - v[k+n] - v[k-1]; \n\n\t// Corners\n\tw[0]= 4 * v[0] - v[1] - v[n];\n\tw[n-1]= 4 * v[n-1] - v[n-2] - v[2*n - 1];\n\tw[(m-1)*n]= 4 * v[(m-1)*n] - v[(m-2)*n] - v[(m-1)*n+1];\n\tw[m*n-1]= 4 * v[m*n-1] - v[m*n-2] - v[m*n-n-1];\n\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> B;\n    laplacian_setup(B, 1000, 1000);\n\n    mtl::dense_vector<double> v(1000000), w(1000000);\n    iota(v);\n\n    poisson2D_dirichlet A(1000, 1000);\n    // cout << \"A * v is \" << A * v << endl;\n    w= A * v;\n    \n    w= B * v;\n\n     return 0;\n}\n", "meta": {"hexsha": "b34765d2fc52772108da0a63041516fc40187dd0", "size": 1916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/timing/matrix_free_2_timing.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/timing/matrix_free_2_timing.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/timing/matrix_free_2_timing.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.5641025641, "max_line_length": 94, "alphanum_fraction": 0.5151356994, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5278363411581019}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2016, 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#ifndef BOOST_GEOMETRY_ARITHMETIC_NORMALIZE_HPP\n#define BOOST_GEOMETRY_ARITHMETIC_NORMALIZE_HPP\n\n\n#include <boost/geometry/core/coordinate_type.hpp>\n\n#include <boost/geometry/arithmetic/arithmetic.hpp>\n#include <boost/geometry/arithmetic/dot_product.hpp>\n#include <boost/geometry/util/math.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <typename Point>\ninline typename coordinate_type<Point>::type vec_length_sqr(Point const& pt)\n{\n    return dot_product(pt, pt);\n}\n\ntemplate <typename Point>\ninline typename coordinate_type<Point>::type vec_length(Point const& pt)\n{\n    // NOTE: hypot() could be used instead of sqrt()\n    return math::sqrt(dot_product(pt, pt));\n}\n\ntemplate <typename Point>\ninline bool vec_normalize(Point & pt, typename coordinate_type<Point>::type & len)\n{\n    typedef typename coordinate_type<Point>::type coord_t;\n\n    coord_t const c0 = 0;\n    len = vec_length(pt);\n    \n    if (math::equals(len, c0))\n    {\n        return false;\n    }\n\n    divide_value(pt, len);\n    return true;\n}\n\ntemplate <typename Point>\ninline bool vec_normalize(Point & pt)\n{\n    typedef typename coordinate_type<Point>::type coord_t;\n    coord_t len;\n    return vec_normalize(pt, len);\n}\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ARITHMETIC_NORMALIZE_HPP\n", "meta": {"hexsha": "7dfdbd2b039d8a3be886106466181c9631f6d917", "size": 1747, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/arithmetic/normalize.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/arithmetic/normalize.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/arithmetic/normalize.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": 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.2638888889, "max_line_length": 82, "alphanum_fraction": 0.7424155695, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5278363401123557}}
{"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_CUPPEN_INCLUDE\n#define MTL_MATRIX_CUPPEN_INCLUDE\n\n#include <cmath>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/utility/assert.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/operation/iota.hpp>\n#include <boost/numeric/mtl/operation/secular.hpp>\n#include <boost/numeric/mtl/operation/sort.hpp>\n#include <boost/numeric/mtl/operation/trans.hpp>\n#include <boost/numeric/mtl/utility/domain.hpp>\n#include <boost/numeric/mtl/matrix/permutation.hpp>\n\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/itl/iteration/basic_iteration.hpp>\n#include <boost/numeric/itl/krylov/fsm.hpp>\n\nnamespace mtl { namespace mat {\n\n/// Eigenvalues of triangle matrix A with Cuppen's divide and conquer algorithm\n/** Eigenvalues are returned in vector lambda. A is overwritten. **/\ntemplate <typename Matrix, typename Vector>\nvoid inline cuppen_inplace(Matrix& A, Matrix& Q, Vector& lambda)\n{\n    using std::abs; using mtl::irange; using mtl::imax; using mtl::iall; using vec::iota;\n\n    typedef typename Collection<Matrix>::value_type     value_type;\n    typedef typename Collection<Matrix>::size_type      size_type;\n    typedef vec::dense_vector<size_type, vec::parameters<> >   size_vector; // todo: with type trait\n\n    size_type        nrows= num_rows(A);\n    MTL_CRASH_IF(nrows != num_cols(A), \"Matrix not square\");\n    const value_type zero= 0, one= 1;   \n    \n    if (nrows == 1){\n\tlambda[0]= A[0][0];\n\tQ= one;\n    } else {\n\tsize_type     m= size_type(nrows/2);\n\tirange        till_m(m), from_m(m, imax);\n\n\tsize_vector   perm(nrows);\n\tMatrix        T1(A[till_m][till_m]), T2(A[from_m][from_m]),                               // sub-matrices of A\n\t              Q0(nrows, nrows), Q1(Q0[till_m][till_m]), Q2(Q0[from_m][from_m]);           // Q0 and sub-matrices\n\tVector        v(nrows, zero), diag(nrows), lambda1(diag[till_m]), lambda2(diag[from_m]);  // sub-vectors of diag\n\n\t//DIVIDE\n\tvalue_type    b= A[m-1][m];\n\tT1[m-1][m-1]-= abs(b);\n\tT2[0][0]-= abs(b);\n\n\tv[m-1]= b > zero ? one : -one;\n\tv[m]= one;\n\n\tcuppen_inplace(T1, Q1, lambda1);\n\tcuppen_inplace(T2, Q2, lambda2);\n\n\tQ0[till_m][from_m]= zero; Q0[from_m][till_m]= zero; // zero out non-diagonal blocks\n\n\tT1[m-1][m-1]+= abs(b);\n\tT2[0][0]+= abs(b);\n\n\tiota(perm);\n\tsort(diag, perm);\n\n\t// CONQUER, start with eq. (3.0.2) using rows (not columns)\n\tv[till_m]= b < zero ? Vector(-trans(Q1[m-1][iall])) : trans(Q1[m-1][iall]); \n\tv[from_m]= trans(Q2[0][iall]);\n\n\t// permutation on v\n\tmtl::mat::traits::permutation<>::type P= mtl::mat::permutation(perm); \n\tVector v1(P * v);\n\t\n\tlambda= secular(v1, diag, abs(b));   // solve secular equation \n\n\t// std::cout << \"lambda is \" << lambda << \"\\ndiag is \" << diag << '\\n';\n\t//Lemma 3.0.2  ... calculate eigenvectors\n\tMatrix Q_tilde(nrows, nrows);\n\tfor (size_type i = 0; i < nrows; i++) {\n\t    for (size_type j= 0; j < size(diag); ++j)\n\t\tMTL_THROW_IF (diag[j] == lambda[i], \n\t\t\t      logic_error(\"Can't compute eigenvector, probably due to double eigenvalue.\"));\n\t    Vector    li(nrows, lambda[i]), lambda_i(ele_quot(v1, diag - li));\n\t    Q_tilde[iall][i]= lambda_i / two_norm(lambda_i); // normalized eigenvector in Matrix Q \n\t}\n\n\tQ= Q0 * P * Q_tilde;\n\n#if 0\n\tfor (size_type i = 0; i < nrows; i++) {\n\t    // Vector    qi(Q[iall][i]); // Todo: find out valgrind complains about the memory of qi for reasons inexplicable\n\t    Vector qi(nrows);\n\t    for (size_type j= 0; j < nrows; j++) \n\t\tqi[j]= Q[j][i];\n\n\t    std::cout << \"q[\" << i << \"] = \" << qi << \", lambda[i] = \" << lambda[i] \n\t\t      << \", diff = \" << two_norm(Vector(A*qi - lambda[i]*qi)) << \", A*qi = \" << Vector(A*qi) << \", li*qi = \" << Vector(lambda[i]*qi) << '\\n';\n\t    itl::basic_iteration<double>   iter(1.0, 20, 1e-5, 1e-5);\n\t    fsm(A, qi, lambda[i], 0.1, iter);\n\t    std::cout << \"q[\" << i << \"] = \" << qi << \", diff = \" << two_norm(Vector(A*qi - lambda[i]*qi)) << '\\n';\n\t    Q[iall][i]= qi;\n\t}\n#endif\n    }     \n}\n\n/// Eigenvalues of triangle matrix A with Cuppen's divide and conquer algorithm\n/** Eigenvalues are returned in vector lambda. A is copied. **/\n// A not as reference to force copy\ntemplate <typename Matrix, typename Vector>\nvoid inline cuppen(Matrix A, Matrix& Q, Vector& lambda)\n{\n    Q= 0.0;\n    cuppen_inplace(A, Q, lambda);\n}\n\n}} // namespace mtl::matrix\n\n#endif // MTL_MATRIX_CUPPEN_INCLUDE\n", "meta": {"hexsha": "6b65b92d8cb6642ab5cd4622a0bce2fa623c4f11", "size": 4911, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/cuppen.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": "boost/numeric/mtl/operation/cuppen.hpp", "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": "boost/numeric/mtl/operation/cuppen.hpp", "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": 36.1102941176, "max_line_length": 143, "alphanum_fraction": 0.6456933415, "num_tokens": 1495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.5278363296246396}}
{"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/*! \\file spreadedoptionletvolatility2.hpp\n    \\brief Optionlet volaility with overlayed bilinearly interpolated spread surface\n    \\ingroup termstructures\n*/\n\n#pragma once\n\n#include <ql/math/interpolations/interpolation2d.hpp>\n#include <ql/quote.hpp>\n#include <ql/termstructures/volatility/optionlet/optionletvolatilitystructure.hpp>\n\n#include <boost/smart_ptr/shared_ptr.hpp>\n\nnamespace QuantExt {\nusing namespace QuantLib;\n\nclass SpreadedOptionletVolatility2 : public OptionletVolatilityStructure, public LazyObject {\npublic:\n    SpreadedOptionletVolatility2(const Handle<OptionletVolatilityStructure>& baseVol,\n                                 const std::vector<Date>& optionDates, const std::vector<Real>& strikes,\n                                 const std::vector<std::vector<Handle<Quote>>>& volSpreads);\n    BusinessDayConvention businessDayConvention() const override;\n    Rate minStrike() const override;\n    Rate maxStrike() const override;\n    DayCounter dayCounter() const override;\n    Date maxDate() const override;\n    Time maxTime() const override;\n    const Date& referenceDate() const override;\n    Calendar calendar() const override;\n    Natural settlementDays() const override;\n    VolatilityType volatilityType() const override;\n    Real displacement() const override;\n    void update() override;\n    void deepUpdate() override;\n\nprotected:\n    boost::shared_ptr<SmileSection> smileSectionImpl(Time optionTime) const override;\n    Volatility volatilityImpl(Time optionTime, Rate strike) const override;\n    void performCalculations() const override;\n\nprivate:\n    Handle<OptionletVolatilityStructure> baseVol_;\n    std::vector<Date> optionDates_;\n    std::vector<Real> strikes_;\n    std::vector<std::vector<Handle<Quote>>> volSpreads_;\n    //\n    mutable std::vector<Real> optionTimes_;\n    mutable Matrix volSpreadValues_;\n    mutable Interpolation2D volSpreadInterpolation_;\n};\n} // namespace QuantExt\n", "meta": {"hexsha": "b993b4eeb3feb462272531c3b7de3e96d7d97739", "size": 2677, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/spreadedoptionletvolatility2.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/termstructures/spreadedoptionletvolatility2.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/termstructures/spreadedoptionletvolatility2.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": 38.2428571429, "max_line_length": 104, "alphanum_fraction": 0.7571908853, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6224593452091673, "lm_q1q2_score": 0.5278254604214101}}
{"text": "#include <boost/math/constants/constants.hpp>\n#include <catch2/catch.hpp>\n#include <complex>\n#include \"ear/bs2051.hpp\"\n#include \"ear/decorrelate.hpp\"\n#include \"ear/layout.hpp\"\n#include \"helper/vector_approx.hpp\"\n#include \"kissfft/kissfft.hh\"\n\nconst double PI = boost::math::constants::pi<double>();\n\nusing namespace ear;\n\n// declare private decorrelate functions\nnamespace ear {\n  std::vector<double> designDecorrelatorBasic(int decorrelatorId, int size);\n  std::vector<long> genRandMt19937(int seed, int n);\n};  // namespace ear\n\nTEST_CASE(\"test_gen_rand_mt19937\") {\n  int seed = 5489;\n  int i = 10000;\n  long expected = 4123659995;\n  REQUIRE(genRandMt19937(seed, i)[i - 1] == expected);\n};\n\nTEST_CASE(\"test_design_decorrelator\") {\n  double rand = genRandMt19937(0, 1)[0] / static_cast<double>(UINT32_MAX - 1);\n  std::vector<std::complex<double>> expected = {\n      std::complex<double>(1.0, 1.0),\n      std::exp(std::complex<double>(0.0, 2.0 * rand * PI))};\n  std::vector<double> filt = designDecorrelatorBasic(0, 512);\n  REQUIRE(filt.size() == 512);\n  kissfft<double> fft(256, false);\n  std::vector<std::complex<double>> actual(512);\n  fft.transform_real(&filt[0], &actual[0]);\n  REQUIRE(actual[0].real() == Approx(expected[0].real()));\n  REQUIRE(actual[0].imag() == Approx(expected[0].imag()));\n  REQUIRE(actual[1].real() == Approx(expected[1].real()));\n  REQUIRE(actual[1].imag() == Approx(expected[1].imag()));\n};\n\nTEST_CASE(\"test_design_decorrelators\") {\n  Layout layout = getLayout(\"4+5+0\").withoutLfe();\n  std::vector<std::vector<double>> filters =\n      designDecorrelators<double>(layout);\n\n  // M+030 should get the second filter\n  boost::optional<int> index = layout.indexForName(\"M+030\");\n  auto rightFilter = filters[boost::get<int>(index)];\n  REQUIRE_VECTOR_APPROX(rightFilter, designDecorrelatorBasic(1, 512));\n}\n", "meta": {"hexsha": "9a968c310f5b9607b98b1f43c6baac49e96728d6", "size": 1830, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/decorrelate_tests.cpp", "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": "tests/decorrelate_tests.cpp", "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": "tests/decorrelate_tests.cpp", "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": 34.5283018868, "max_line_length": 78, "alphanum_fraction": 0.6983606557, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5278254580298783}}
{"text": "#include \"wave/optimization/ceres/odom_gp_reduced/point_to_line_gp.hpp\"\n#include <Eigen/QR>\n\nnamespace wave {\n\nSE3PointToLineGPRed::SE3PointToLineGPRed(const double *const p,\n                                         const double *const pA,\n                                         const double *const pB,\n                                         const Mat12 &hat,\n                                         const Mat12 &candle,\n                                         const Mat3 &CovZ,\n                                         bool calculate_weight)\n    : pt(p), ptA(pA), ptB(pB), hat(hat), candle(candle) {\n    this->JP_T.setZero();\n    this->JP_T.block<3, 3>(0, 3).setIdentity();\n\n    this->diff[0] = this->ptB[0] - this->ptA[0];\n    this->diff[1] = this->ptB[1] - this->ptA[1];\n    this->diff[2] = this->ptB[2] - this->ptA[2];\n    this->bottom = diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2];\n\n    if (this->bottom < 1e-10) {\n        // The points defining the line are too close to each other\n        throw std::out_of_range(\"Points defining line are too close!\");\n    }\n\n    this->Jres_P(0, 0) = 1 - (diff[0] * diff[0] / bottom);\n    this->Jres_P(0, 1) = -(diff[0] * diff[1] / bottom);\n    this->Jres_P(0, 2) = -(diff[0] * diff[2] / bottom);\n    this->Jres_P(1, 0) = -(diff[1] * diff[0] / bottom);\n    this->Jres_P(1, 1) = 1 - (diff[1] * diff[1] / bottom);\n    this->Jres_P(1, 2) = -(diff[1] * diff[2] / bottom);\n    this->Jres_P(2, 0) = -(diff[2] * diff[0] / bottom);\n    this->Jres_P(2, 1) = -(diff[2] * diff[1] / bottom);\n    this->Jres_P(2, 2) = 1 - (diff[2] * diff[2] / bottom);\n\n    Eigen::Vector3d unitdiff;\n    double invlength = 1.0 / sqrt(this->bottom);\n    if (this->diff[2] > 0) {\n        unitdiff[0] = this->diff[0] * invlength;\n        unitdiff[1] = this->diff[1] * invlength;\n        unitdiff[2] = this->diff[2] * invlength;\n    } else {\n        unitdiff[0] = -this->diff[0] * invlength;\n        unitdiff[1] = -this->diff[1] * invlength;\n        unitdiff[2] = -this->diff[2] * invlength;\n    }\n\n    Eigen::Vector3d unitz;\n    unitz << 0, 0, 1;\n\n    auto v = unitdiff.cross(unitz);\n    auto s = v.norm();\n    auto c = unitz.dot(unitdiff);\n    Mat3 skew;\n    Transformation<>::skewSymmetric3(v, skew);\n    this->rotation = Eigen::Matrix3d::Identity() + skew + skew * skew * ((1 - c) / (s * s));\n\n    this->Jres_P = this->rotation * this->Jres_P;\n\n    if (calculate_weight) {\n        auto rotated = this->Jres_P * CovZ * this->Jres_P.transpose();\n        this->weight_matrix = rotated.block<2, 2>(0, 0).inverse().sqrt();\n    } else {\n        this->weight_matrix.setIdentity();\n    }\n}\n\nbool SE3PointToLineGPRed::Evaluate(double const *const *parameters, double *residuals, double **jacobians) const {\n    Eigen::Map<const Mat34> tk_map(parameters[0], 3, 4);\n    Eigen::Map<const Mat34> tkp1_map(parameters[1], 3, 4);\n\n    Transformation<Eigen::Map<const Mat34>, true> Tk(tk_map);\n    Transformation<Eigen::Map<const Mat34>, true> Tkp1(tkp1_map);\n\n    Eigen::Map<const Vec6> vel_k(parameters[2], 6, 1);\n\n    if (jacobians) {\n        Transformation<Eigen::Map<const Eigen::Matrix<double, 3, 4>>, true>::interpolateAndJacobians(\n          Tk,\n          Tkp1,\n          vel_k,\n          vel_k,\n          this->hat,\n          this->candle,\n          this->T_current,\n          this->JT_Ti,\n          this->JT_Tip1,\n          this->JT_Wi,\n          this->JT_Wip1);\n    } else {\n        Transformation<Eigen::Map<const Eigen::Matrix<double, 3, 4>>, true>::interpolate(\n          Tk, Tkp1, vel_k, vel_k, this->hat, this->candle, this->T_current);\n    }\n\n    Eigen::Map<const Vec3> PT(this->pt, 3, 1);\n    Vec3 point = this->T_current.transform(PT);\n\n    double p_A[3] = {point(0) - this->ptA[0], point(1) - this->ptA[1], point(2) - this->ptA[2]};\n\n    double scaling = ceres::DotProduct(p_A, diff);\n    // point on line closest to point\n    double p_Tl[3] = {this->ptA[0] + (scaling / bottom) * diff[0],\n                      this->ptA[1] + (scaling / bottom) * diff[1],\n                      this->ptA[2] + (scaling / bottom) * diff[2]};\n\n    Eigen::Map<const Vec3> pt_Tl(p_Tl, 3, 1);\n    Eigen::Map<Eigen::Vector2d> reduced(residuals, 2, 1);\n\n    reduced = this->weight_matrix * (this->rotation * (point - pt_Tl)).block<2, 1>(0, 0);\n\n    if (jacobians != nullptr) {\n        this->JP_T(0, 1) = point(2);\n        this->JP_T(0, 2) = -point(1);\n        this->JP_T(1, 0) = -point(2);\n        this->JP_T(1, 2) = point(0);\n        this->JP_T(2, 0) = point(1);\n        this->JP_T(2, 1) = -point(0);\n\n        // Jres_P already has rotation incorporated during construction\n        this->Jr_T = this->Jres_P * this->JP_T;\n\n        if (jacobians[0]) {\n            Eigen::Map<Eigen::Matrix<double, 2, 12, Eigen::RowMajor>> Jr_Tk(jacobians[0], 2, 12);\n            Jr_Tk.block<2, 6>(0, 0) = this->weight_matrix * this->Jr_T.block<2, 6>(0, 0) * this->JT_Ti;\n            Jr_Tk.block<2, 6>(0, 6).setZero();\n        }\n        if (jacobians[1]) {\n            Eigen::Map<Eigen::Matrix<double, 2, 12, Eigen::RowMajor>> Jr_Tkp1(jacobians[1], 2, 12);\n            Jr_Tkp1.block<2, 6>(0, 0) = this->weight_matrix * this->Jr_T.block<2, 6>(0, 0) * this->JT_Tip1;\n            Jr_Tkp1.block<2, 6>(0, 6).setZero();\n        }\n        if (jacobians[2]) {\n            Eigen::Map<Eigen::Matrix<double, 2, 6, Eigen::RowMajor>> jac_map(jacobians[2], 2, 6);\n            jac_map = this->weight_matrix * this->Jr_T.block<2, 6>(0, 0) * (this->JT_Wi + this->JT_Wip1);\n        }\n    }\n\n    return true;\n}\n\n}  // namespace wave\n", "meta": {"hexsha": "486cb8ebb366f6398776b89aae646290b6d97848", "size": 5507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wave_optimization/src/ceres/odom_gp_reduced/point_to_line_gp.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/src/ceres/odom_gp_reduced/point_to_line_gp.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/src/ceres/odom_gp_reduced/point_to_line_gp.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": 38.5104895105, "max_line_length": 114, "alphanum_fraction": 0.5413110587, "num_tokens": 1862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5278254556383467}}
{"text": "#include \"segments.hpp\"\n\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Geometry>\n\n#include <boost/foreach.hpp>\n\n\nusing namespace std;\n\nint orientation(Point A, Point B, Point C)\n{\n    int val = (B[1] - A[1]) * (C[0] - B[0]) - (B[0] - A[0]) * (C[1] - B[1]);\n    return val == 0 ? 0 : (val > 0 ? 1 : 2);\n}\n\nbool onSegment(Point P, Segment S) //P collinear with S\n{\n    if (P[0] <= std::max(S.A[0], S.B[0]) &&\n        P[0] >= std::min(S.A[0], S.B[0]) &&\n        P[1] <= std::max(S.A[1], S.B[1]) &&\n        P[1] >= std::min(S.A[1], S.B[1]) )\n    {\n        return true;\n    }\n    return false;\n}\n\n\nint intersect(Segment sA, Segment sB)\n{\n    Point PA = sA.A, QA = sA.B, PB = sB.B, QB = sB.B;\n    int o1 = orientation(PA, QA, PB);\n    int o2 = orientation(PA, QA, QB);\n    int o3 = orientation(PB, QB, PA);\n    int o4 = orientation(PB, QB, QA);\n\n    if (o1 != o2 && o3 != o4) \n        return 1;\n\n    if (o1 == 0 && onSegment(PB, sA)) return 1;\n    if (o2 == 0 && onSegment(QB, sA)) return 1;\n    if (o3 == 0 && onSegment(PA, sB)) return 1;\n    if (o4 == 0 && onSegment(QA, sB)) return 1;\n\n    return 0;\n\n}\n\nbool isInPolygon(Polygon polygon, Point P)\n{\n    Point Q = P;\n    Q[0] = INF;\n    int nInter = 0;\n    Segment halfLine;\n    halfLine.A = P;\n    halfLine.B = Q;\n\n    BOOST_FOREACH(Segment seg, polygon.seg)\n    {\n        if (orientation(seg.A, P, seg.B) == 0)\n            return onSegment(P, seg);\n        nInter += intersect(seg, halfLine);\n    }\n\n    return nInter&1;\n}", "meta": {"hexsha": "46420bae429ab15f134cc467edeb14dd13c4149a", "size": 1477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "segments.cpp", "max_stars_repo_name": "caillotantoine/GOL-Rasterisation", "max_stars_repo_head_hexsha": "337f1e2d3e7ffe5815d17d87a578b3d9247727ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "segments.cpp", "max_issues_repo_name": "caillotantoine/GOL-Rasterisation", "max_issues_repo_head_hexsha": "337f1e2d3e7ffe5815d17d87a578b3d9247727ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "segments.cpp", "max_forks_repo_name": "caillotantoine/GOL-Rasterisation", "max_forks_repo_head_hexsha": "337f1e2d3e7ffe5815d17d87a578b3d9247727ee", "max_forks_repo_licenses": ["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.0447761194, "max_line_length": 76, "alphanum_fraction": 0.5220040623, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.5277410846476283}}
{"text": "#ifndef TRIUMF_BNMR_NUCLEI_HPP\n#define TRIUMF_BNMR_NUCLEI_HPP\n\n#include <boost/math/constants/constants.hpp>\n\n#include <triumf/nmr/utilities.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// \u03b2-detected nuclear magnetic resonance (\u03b2-NMR)\nnamespace bnmr {\n\n// \u03b2-NMR probe nuclei and their properties\nnamespace nuclei {\n\n// lithium-8\ntemplate <typename T = double> struct lithium_8 {\n  // radioactive half-life (s)\n  static inline constexpr T half_life() { return 1e-3 * 838.40; }\n  // radioactive lifetime (s)\n  static inline constexpr T lifetime() {\n    return half_life() / boost::math::constants::ln_two<T>();\n  }\n  // spin quantum number\n  static inline constexpr T spin() { return 2.0; }\n  // magnetic dipole moment (nm)\n  static inline constexpr T magnetic_dipole_moment() { return 1.65350; }\n  // electric dipole moment (b)\n  static inline constexpr T electric_quadrupole_moment() { return 0.0326; }\n  // gyromagnetic ratio (s^-1 T^-1)\n  static inline constexpr T gyromagnetic_ratio() {\n    return triumf::nmr::utilities::calculate_gamma<T>(magnetic_dipole_moment(),\n                                                      spin());\n  }\n  // gyromagnetic ratio (MHz / T)\n  static inline constexpr T gyromagnetic_ratio_in_MHz_T() {\n    return gyromagnetic_ratio() / 1e6 / boost::math::constants::two_pi<T>();\n  }\n};\n\n// beryllium-11\ntemplate <typename T = double> struct beryllium_11 {\n  // radioactive half-life (s)\n  static inline constexpr T half_life() { return 13.76; }\n  // radioactive lifetime (s)\n  static inline constexpr T lifetime() {\n    return half_life() / boost::math::constants::ln_two<T>();\n  }\n  // spin quantum number\n  static inline constexpr T spin() { return 1.0 / 2.0; }\n  // magnetic dipole moment (nm)\n  static inline constexpr T magnetic_dipole_moment() { return -1.6816; }\n  // electric dipole moment (b)\n  static inline constexpr T electric_quadrupole_moment() { return 0.0; }\n  // gyromagnetic ratio (s^-1 T^-1)\n  static inline constexpr T gyromagnetic_ratio() {\n    return triumf::nmr::utilities::calculate_gamma<T>(magnetic_dipole_moment(),\n                                                      spin());\n  }\n  // gyromagnetic ratio (MHz / T)\n  static inline constexpr T gyromagnetic_ratio_in_MHz_T() {\n    return gyromagnetic_ratio() / 1e6 / boost::math::constants::two_pi<T>();\n  }\n};\n\n// boron-12\ntemplate <typename T = double> struct boron_12 {\n  // radioactive half-life (s)\n  static inline constexpr T half_life() { return 1e-3 * 20.20; }\n  // radioactive lifetime (s)\n  static inline constexpr T lifetime() {\n    return half_life() / boost::math::constants::ln_two<T>();\n  }\n  // spin quantum number\n  static inline constexpr T spin() { return 1.0; }\n  // magnetic dipole moment (nm)\n  static inline constexpr T magnetic_dipole_moment() { return 1.003; }\n  // electric dipole moment (b)\n  static inline constexpr T electric_quadrupole_moment() { return 0.0132; }\n  // gyromagnetic ratio (s^-1 T^-1)\n  static inline constexpr T gyromagnetic_ratio() {\n    return triumf::nmr::utilities::calculate_gamma<T>(magnetic_dipole_moment(),\n                                                      spin());\n  }\n  // gyromagnetic ratio (MHz / T)\n  static inline constexpr T gyromagnetic_ratio_in_MHz_T() {\n    return gyromagnetic_ratio() / 1e6 / boost::math::constants::two_pi<T>();\n  }\n};\n\n// magnesium-31\ntemplate <typename T = double> struct magnesium_31 {\n  // radioactive half-life (s)\n  static inline constexpr T half_life() { return 1e-3 * 236.0; }\n  // radioactive lifetime (s)\n  static inline constexpr T lifetime() {\n    return half_life() / boost::math::constants::ln_two<T>();\n  }\n  // spin quantum number\n  static inline constexpr T spin() { return 1.0 / 2.0; }\n  // magnetic dipole moment (nm)\n  static inline constexpr T magnetic_dipole_moment() { return -0.88340; }\n  // electric dipole moment (b)\n  static inline constexpr T electric_quadrupole_moment() { return 0.0; }\n  // gyromagnetic ratio (s^-1 T^-1)\n  static inline constexpr T gyromagnetic_ratio() {\n    return triumf::nmr::utilities::calculate_gamma<T>(magnetic_dipole_moment(),\n                                                      spin());\n  }\n  // gyromagnetic ratio (MHz / T)\n  static inline constexpr T gyromagnetic_ratio_in_MHz_T() {\n    return gyromagnetic_ratio() / 1e6 / boost::math::constants::two_pi<T>();\n  }\n};\n\n} // namespace nuclei\n\n} // namespace bnmr\n\n} // namespace triumf\n\n#endif // TRIUMF_BNMR_NUCLEI_HPP\n", "meta": {"hexsha": "277f8c24949d8f481822c50bc497401d9c41e233", "size": 4450, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/bnmr/nuclei.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/bnmr/nuclei.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/bnmr/nuclei.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": 35.8870967742, "max_line_length": 79, "alphanum_fraction": 0.668988764, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059560743422, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5277410826392467}}
{"text": "#include <cstddef>\n#include <cassert>\n#include <immintrin.h> // AVX2\n\n#include <benchmark/benchmark.h>\n#include <boost/numeric/ublas/vector.hpp>\n\nnamespace\n{\n  const std::size_t kVectorSize = 100000000;\n\n  double doNaiveDotProduct(const std::vector<double>& v1, const std::vector<double>& v2)\n  {\n    assert((v1.size() == v2.size()) && \"Dot product can only be done on vectors with the same size\");\n\n    double dotProduct = 0.0;\n\n    for (std::size_t i = 0; i < v1.size(); ++i)\n    {\n      dotProduct += (v1[i] * v2[i]);\n    }\n\n    return dotProduct;\n  }\n\n  double doBoostDotProduct(const boost::numeric::ublas::vector<double>& v1, const boost::numeric::ublas::vector<double>& v2)\n  {\n    return inner_prod(v1, v2);\n  }\n\n  double doSimdDotProduct(const std::vector<double>& v1, const std::vector<double>& v2)\n  {\n    assert((v1.size() == v2.size()) && \"Dot product can only be done on vectors with the same size\");\n\n    const std::size_t numPacks = v1.size() / 4; // 4 doubles per 256-bit register\n    const std::size_t lastPackSize = v1.size() % 4;\n\n    __m256d accumulated = _mm256_setzero_pd();\n    __m256d a;\n    __m256d b;\n\n    for (std::size_t i = 0; i < numPacks; ++i)\n    {\n      a.m256d_f64[0] = v1[i * 4];\n      a.m256d_f64[1] = v1[i * 4 + 1];\n      a.m256d_f64[2] = v1[i * 4 + 2];\n      a.m256d_f64[3] = v1[i * 4 + 3];\n\n      b.m256d_f64[0] = v2[i * 4];\n      b.m256d_f64[1] = v2[i * 4 + 1];\n      b.m256d_f64[2] = v2[i * 4 + 2];\n      b.m256d_f64[3] = v2[i * 4 + 3];\n\n      accumulated = _mm256_fmaddsub_pd(a, b, accumulated);\n    }\n\n    const std::size_t lastPackOffset = numPacks * 4;\n\n    for (std::size_t i = 0; i < 4; ++i)\n    {\n      a.m256d_f64[i] = (i < lastPackSize) ? v1[lastPackOffset + i] : 0.0;\n      b.m256d_f64[i] = (i < lastPackSize) ? v2[lastPackOffset + i] : 0.0;\n    }\n\n    accumulated = _mm256_fmaddsub_pd(a, b, accumulated);\n\n    __m128d accumulatedHigh = _mm256_extractf128_pd(accumulated, 1);\n    __m128d sum = _mm_add_pd(accumulatedHigh, _mm256_castpd256_pd128(accumulated));\n\n    return sum.m128d_f64[0] + sum.m128d_f64[1];\n  }\n}\n\nstatic void naiveDotProduct(benchmark::State& state)\n{\n  std::vector<double> v1(kVectorSize);\n  std::vector<double> v2(kVectorSize);\n\n  while (state.KeepRunning())\n  {\n    doNaiveDotProduct(v1, v2);\n  }\n}\nBENCHMARK(naiveDotProduct);\n\nstatic void boostDotProduct(benchmark::State& state)\n{\n  boost::numeric::ublas::vector<double> v1(kVectorSize);\n  boost::numeric::ublas::vector<double> v2(kVectorSize);\n\n  while (state.KeepRunning())\n  {\n    doBoostDotProduct(v1, v2);\n  }\n}\nBENCHMARK(boostDotProduct);\n\nstatic void simdDotProduct(benchmark::State& state)\n{\n  std::vector<double> v1(kVectorSize);\n  std::vector<double> v2(kVectorSize);\n\n  while (state.KeepRunning())\n  {\n    doSimdDotProduct(v1, v2);\n  }\n}\nBENCHMARK(simdDotProduct);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "99166e723113bf4b67dfe8f1a034218c026c3d16", "size": 2821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fluid-benchmarks/src/main.cpp", "max_stars_repo_name": "mpazoscr/computer-graphics", "max_stars_repo_head_hexsha": "a6c9bf8700161a4243f753a965dfd5f56b195e36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-06-21T13:53:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T02:49:06.000Z", "max_issues_repo_path": "fluid-benchmarks/src/main.cpp", "max_issues_repo_name": "mpazoscr/computer-graphics", "max_issues_repo_head_hexsha": "a6c9bf8700161a4243f753a965dfd5f56b195e36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fluid-benchmarks/src/main.cpp", "max_forks_repo_name": "mpazoscr/computer-graphics", "max_forks_repo_head_hexsha": "a6c9bf8700161a4243f753a965dfd5f56b195e36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-15T16:14:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T02:49:07.000Z", "avg_line_length": 25.4144144144, "max_line_length": 124, "alphanum_fraction": 0.6398440269, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5277410793852357}}
{"text": "/**\n * @file tests/det_test.cpp\n * @author Parikshit Ram (pram@cc.gatech.edu)\n *\n * Unit tests for the functions of the class DTree and the utility functions\n * using this class.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\n// This trick does not work on Windows.  We will have to comment out the tests\n// that depend on it.\n#ifndef _WIN32\n  #define protected public\n  #define private public\n#endif\n\n#include <mlpack/methods/det/dtree.hpp>\n#include <mlpack/methods/det/dt_utils.hpp>\n\n#ifndef _WIN32\n  #undef protected\n  #undef private\n#endif\n\nusing namespace mlpack;\nusing namespace mlpack::det;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(DETTest);\n\n// Tests for the private functions.  We cannot perform these if we are on\n// Windows because we cannot make private functions accessible using the macro\n// trick above.\n#ifndef _WIN32\nBOOST_AUTO_TEST_CASE(TestGetMaxMinVals)\n{\n  arma::mat testData(3, 5);\n\n  testData << 4 << 5 << 7 << 3 << 5 << arma::endr\n           << 5 << 0 << 1 << 7 << 1 << arma::endr\n           << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  DTree<arma::mat> tree(testData);\n\n  BOOST_REQUIRE_EQUAL(tree.MaxVals()[0], 7);\n  BOOST_REQUIRE_EQUAL(tree.MinVals()[0], 3);\n  BOOST_REQUIRE_EQUAL(tree.MaxVals()[1], 7);\n  BOOST_REQUIRE_EQUAL(tree.MinVals()[1], 0);\n  BOOST_REQUIRE_EQUAL(tree.MaxVals()[2], 8);\n  BOOST_REQUIRE_EQUAL(tree.MinVals()[2], 1);\n}\n\nBOOST_AUTO_TEST_CASE(TestComputeNodeError)\n{\n  arma::vec maxVals(\"7 7 8\");\n  arma::vec minVals(\"3 0 1\");\n\n  DTree<arma::mat> testDTree(maxVals, minVals, 5);\n  double trueNodeError = -log(4.0) - log(7.0) - log(7.0);\n\n  BOOST_REQUIRE_CLOSE((double) testDTree.logNegError, trueNodeError, 1e-10);\n\n  testDTree.start = 3;\n  testDTree.end = 5;\n\n  double nodeError = testDTree.LogNegativeError(5);\n  trueNodeError = 2 * log(2.0 / 5.0) - log(4.0) - log(7.0) - log(7.0);\n  BOOST_REQUIRE_CLOSE(nodeError, trueNodeError, 1e-10);\n}\n\nBOOST_AUTO_TEST_CASE(TestWithinRange)\n{\n  arma::vec maxVals(\"7 7 8\");\n  arma::vec minVals(\"3 0 1\");\n\n  DTree<arma::mat> testDTree(maxVals, minVals, 5);\n\n  arma::vec testQuery(3);\n  testQuery << 4.5 << 2.5 << 2;\n\n  BOOST_REQUIRE_EQUAL(testDTree.WithinRange(testQuery), true);\n\n  testQuery << 8.5 << 2.5 << 2;\n\n  BOOST_REQUIRE_EQUAL(testDTree.WithinRange(testQuery), false);\n}\n\nBOOST_AUTO_TEST_CASE(TestFindSplit)\n{\n  arma::mat testData(3, 5);\n\n  testData << 4 << 5 << 7 << 3 << 5 << arma::endr\n           << 5 << 0 << 1 << 7 << 1 << arma::endr\n           << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  DTree<arma::mat> testDTree(testData);\n\n  size_t obDim;\n  double obLeftError, obRightError, obSplit;\n\n  size_t trueDim = 2;\n  double trueSplit = 5.5;\n  double trueLeftError = 2 * log(2.0 / 5.0) - (log(7.0) + log(4.0) + log(4.5));\n  double trueRightError = 2 * log(3.0 / 5.0) - (log(7.0) + log(4.0) + log(2.5));\n\n  testDTree.logVolume = log(7.0) + log(4.0) + log(7.0);\n  BOOST_REQUIRE(testDTree.FindSplit(\n      testData, obDim, obSplit, obLeftError, obRightError, 1));\n\n  BOOST_REQUIRE(trueDim == obDim);\n  BOOST_REQUIRE_CLOSE(trueSplit, obSplit, 1e-10);\n\n  BOOST_REQUIRE_CLOSE(trueLeftError, obLeftError, 1e-10);\n  BOOST_REQUIRE_CLOSE(trueRightError, obRightError, 1e-10);\n}\n\nBOOST_AUTO_TEST_CASE(TestSplitData)\n{\n  arma::mat testData(3, 5);\n\n  testData << 4 << 5 << 7 << 3 << 5 << arma::endr\n           << 5 << 0 << 1 << 7 << 1 << arma::endr\n           << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  DTree<arma::mat> testDTree(testData);\n\n  arma::Col<size_t> oTest(5);\n  oTest << 1 << 2 << 3 << 4 << 5;\n\n  size_t splitDim = 2;\n  double trueSplitVal = 5.5;\n\n  size_t splitInd = testDTree.SplitData(\n      testData, splitDim, trueSplitVal, oTest);\n\n  BOOST_REQUIRE_EQUAL(splitInd, 2); // 2 points on left side.\n\n  BOOST_REQUIRE_EQUAL(oTest[0], 1);\n  BOOST_REQUIRE_EQUAL(oTest[1], 4);\n  BOOST_REQUIRE_EQUAL(oTest[2], 3);\n  BOOST_REQUIRE_EQUAL(oTest[3], 2);\n  BOOST_REQUIRE_EQUAL(oTest[4], 5);\n}\n\nBOOST_AUTO_TEST_CASE(TestSparseFindSplit)\n{\n  arma::mat realData(4, 7);\n\n  realData << .0 << 4 << 5 << 7 << 0 << 5 << 0 << arma::endr\n           << .0 << 5 << 0 << 0 << 1 << 7 << 1 << arma::endr\n           << .0 << 5 << 6 << 7 << 1 << 0 << 8 << arma::endr\n           << -1 << 2 << 5 << 0 << 0 << 0 << 0 << arma::endr;\n\n  arma::sp_mat testData(realData);\n\n  DTree<arma::sp_mat> testDTree(testData);\n\n  size_t obDim;\n  double obLeftError, obRightError, obSplit;\n\n  size_t trueDim = 1;\n  double trueSplit = .5;\n  double trueLeftError = 2 * log(3.0 / 7.0) -\n      (log(7.0) + log(0.5) + log(8.0) + log(6.0));\n  double trueRightError = 2 * log(4.0 / 7.0) -\n      (log(7.0) + log(6.5) + log(8.0) + log(6.0));\n\n  testDTree.logVolume = log(7.0) + log(7.0) + log(8.0) + log(6.0);\n  BOOST_REQUIRE(testDTree.FindSplit(\n      testData, obDim, obSplit, obLeftError, obRightError, 1));\n\n  BOOST_REQUIRE(trueDim == obDim);\n  BOOST_REQUIRE_CLOSE(trueSplit, obSplit, 1e-10);\n\n  BOOST_REQUIRE_CLOSE(trueLeftError, obLeftError, 1e-10);\n  BOOST_REQUIRE_CLOSE(trueRightError, obRightError, 1e-10);\n}\n\nBOOST_AUTO_TEST_CASE(TestSparseSplitData)\n{\n  arma::mat realData(4, 7);\n\n  realData << .0 << 4 << 5 << 7 << 0 << 5 << 0 << arma::endr\n           << .0 << 5 << 0 << 0 << 1 << 7 << 1 << arma::endr\n           << .0 << 5 << 6 << 7 << 1 << 0 << 8 << arma::endr\n           << -1 << 2 << 5 << 0 << 0 << 0 << 0 << arma::endr;\n\n  arma::sp_mat testData(realData);\n\n  DTree<arma::sp_mat> testDTree(testData);\n\n  arma::Col<size_t> oTest(7);\n  oTest << 1 << 2 << 3 << 4 << 5 << 6 << 7;\n\n  size_t splitDim = 1;\n  double trueSplitVal = .5;\n\n  size_t splitInd = testDTree.SplitData(\n      testData, splitDim, trueSplitVal, oTest);\n\n  BOOST_REQUIRE_EQUAL(splitInd, 3); // 2 points on left side.\n\n  BOOST_REQUIRE_EQUAL(oTest[0], 1);\n  BOOST_REQUIRE_EQUAL(oTest[1], 4);\n  BOOST_REQUIRE_EQUAL(oTest[2], 3);\n  BOOST_REQUIRE_EQUAL(oTest[3], 2);\n  BOOST_REQUIRE_EQUAL(oTest[4], 5);\n  BOOST_REQUIRE_EQUAL(oTest[5], 6);\n  BOOST_REQUIRE_EQUAL(oTest[6], 7);\n}\n\n#endif\n\n// Tests for the public functions.\n\nBOOST_AUTO_TEST_CASE(TestGrow)\n{\n  arma::mat testData(3, 5);\n\n  testData << 4 << 5 << 7 << 3 << 5 << arma::endr\n           << 5 << 0 << 1 << 7 << 1 << arma::endr\n           << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  arma::Col<size_t> oTest(5);\n  oTest << 0 << 1 << 2 << 3 << 4;\n\n  double rootError, lError, rError, rlError, rrError;\n\n  rootError = -log(4.0) - log(7.0) - log(7.0);\n\n  lError = 2 * log(2.0 / 5.0) - (log(7.0) + log(4.0) + log(4.5));\n  rError =  2 * log(3.0 / 5.0) - (log(7.0) + log(4.0) + log(2.5));\n\n  rlError = 2 * log(1.0 / 5.0) - (log(0.5) + log(4.0) + log(2.5));\n  rrError = 2 * log(2.0 / 5.0) - (log(6.5) + log(4.0) + log(2.5));\n\n  DTree<arma::mat> testDTree(testData);\n  double alpha = testDTree.Grow(testData, oTest, false, 2, 1);\n\n  BOOST_REQUIRE_EQUAL(oTest[0], 0);\n  BOOST_REQUIRE_EQUAL(oTest[1], 3);\n  BOOST_REQUIRE_EQUAL(oTest[2], 1);\n  BOOST_REQUIRE_EQUAL(oTest[3], 2);\n  BOOST_REQUIRE_EQUAL(oTest[4], 4);\n\n  // Test the structure of the tree.\n  BOOST_REQUIRE(testDTree.Left()->Left() == NULL);\n  BOOST_REQUIRE(testDTree.Left()->Right() == NULL);\n  BOOST_REQUIRE(testDTree.Right()->Left()->Left() == NULL);\n  BOOST_REQUIRE(testDTree.Right()->Left()->Right() == NULL);\n  BOOST_REQUIRE(testDTree.Right()->Right()->Left() == NULL);\n  BOOST_REQUIRE(testDTree.Right()->Right()->Right() == NULL);\n\n  BOOST_REQUIRE(testDTree.SubtreeLeaves() == 3);\n\n  BOOST_REQUIRE(testDTree.SplitDim() == 2);\n  BOOST_REQUIRE_CLOSE(testDTree.SplitValue(), 5.5, 1e-5);\n  BOOST_REQUIRE(testDTree.Right()->SplitDim() == 1);\n  BOOST_REQUIRE_CLOSE(testDTree.Right()->SplitValue(), 0.5, 1e-5);\n\n  // Test node errors for every node (these are private functions).\n#ifndef _WIN32\n  BOOST_REQUIRE_CLOSE(testDTree.logNegError, rootError, 1e-10);\n  BOOST_REQUIRE_CLOSE(testDTree.Left()->logNegError, lError, 1e-10);\n  BOOST_REQUIRE_CLOSE(testDTree.Right()->logNegError, rError, 1e-10);\n  BOOST_REQUIRE_CLOSE(testDTree.Right()->Left()->logNegError, rlError, 1e-10);\n  BOOST_REQUIRE_CLOSE(testDTree.Right()->Right()->logNegError, rrError, 1e-10);\n#endif\n\n  // Test alpha.\n  double rootAlpha, rAlpha;\n  rootAlpha = std::log(-((std::exp(rootError) - (std::exp(lError) +\n      std::exp(rlError) + std::exp(rrError))) / 2));\n  rAlpha = std::log(-(std::exp(rError) - (std::exp(rlError) +\n      std::exp(rrError))));\n\n  BOOST_REQUIRE_CLOSE(alpha, min(rootAlpha, rAlpha), 1e-10);\n}\n\nBOOST_AUTO_TEST_CASE(TestPruneAndUpdate)\n{\n  arma::mat testData(3, 5);\n\n  testData << 4 << 5 << 7 << 3 << 5 << arma::endr\n           << 5 << 0 << 1 << 7 << 1 << arma::endr\n           << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  arma::Col<size_t> oTest(5);\n  oTest << 0 << 1 << 2 << 3 << 4;\n  DTree<arma::mat> testDTree(testData);\n  double alpha = testDTree.Grow(testData, oTest, false, 2, 1);\n  alpha = testDTree.PruneAndUpdate(alpha, testData.n_cols, false);\n\n  BOOST_REQUIRE_CLOSE(alpha, numeric_limits<double>::max(), 1e-10);\n  BOOST_REQUIRE(testDTree.SubtreeLeaves() == 1);\n\n  double rootError = -log(4.0) - log(7.0) - log(7.0);\n\n  BOOST_REQUIRE_CLOSE(testDTree.LogNegError(), rootError, 1e-10);\n  BOOST_REQUIRE_CLOSE(testDTree.SubtreeLeavesLogNegError(), rootError, 1e-10);\n  BOOST_REQUIRE(testDTree.Left() == NULL);\n  BOOST_REQUIRE(testDTree.Right() == NULL);\n}\n\nBOOST_AUTO_TEST_CASE(TestComputeValue)\n{\n  arma::mat testData(3, 5);\n\n  testData << 4 << 5 << 7 << 3 << 5 << arma::endr\n           << 5 << 0 << 1 << 7 << 1 << arma::endr\n           << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  arma::vec q1(3), q2(3), q3(3), q4(3);\n\n  q1 << 4 << 2 << 2;\n  q2 << 5 << 0.25 << 6;\n  q3 << 5 << 3 << 7;\n  q4 << 2 << 3 << 3;\n\n  arma::Col<size_t> oTest(5);\n  oTest << 0 << 1 << 2 << 3 << 4;\n\n  DTree<arma::mat> testDTree(testData);\n  double alpha = testDTree.Grow(testData, oTest, false, 2, 1);\n\n  double d1 = (2.0 / 5.0) / exp(log(4.0) + log(7.0) + log(4.5));\n  double d2 = (1.0 / 5.0) / exp(log(4.0) + log(0.5) + log(2.5));\n  double d3 = (2.0 / 5.0) / exp(log(4.0) + log(6.5) + log(2.5));\n\n  BOOST_REQUIRE_CLOSE(d1, testDTree.ComputeValue(q1), 1e-10);\n  BOOST_REQUIRE_CLOSE(d2, testDTree.ComputeValue(q2), 1e-10);\n  BOOST_REQUIRE_CLOSE(d3, testDTree.ComputeValue(q3), 1e-10);\n  BOOST_REQUIRE_CLOSE(0.0, testDTree.ComputeValue(q4), 1e-10);\n\n  alpha = testDTree.PruneAndUpdate(alpha, testData.n_cols, false);\n\n  double d = 1.0 / exp(log(4.0) + log(7.0) + log(7.0));\n\n  BOOST_REQUIRE_CLOSE(d, testDTree.ComputeValue(q1), 1e-10);\n  BOOST_REQUIRE_CLOSE(d, testDTree.ComputeValue(q2), 1e-10);\n  BOOST_REQUIRE_CLOSE(d, testDTree.ComputeValue(q3), 1e-10);\n  BOOST_REQUIRE_CLOSE(0.0, testDTree.ComputeValue(q4), 1e-10);\n}\n\nBOOST_AUTO_TEST_CASE(TestVariableImportance)\n{\n  arma::mat testData(3, 5);\n\n  testData << 4 << 5 << 7 << 3 << 5 << arma::endr\n           << 5 << 0 << 1 << 7 << 1 << arma::endr\n           << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  double rootError, lError, rError, rlError, rrError;\n\n  rootError = -1.0 * exp(-log(4.0) - log(7.0) - log(7.0));\n\n  lError = -1.0 * exp(2 * log(2.0 / 5.0) - (log(7.0) + log(4.0) + log(4.5)));\n  rError =  -1.0 * exp(2 * log(3.0 / 5.0) - (log(7.0) + log(4.0) + log(2.5)));\n\n  rlError = -1.0 * exp(2 * log(1.0 / 5.0) - (log(0.5) + log(4.0) + log(2.5)));\n  rrError = -1.0 * exp(2 * log(2.0 / 5.0) - (log(6.5) + log(4.0) + log(2.5)));\n\n  arma::Col<size_t> oTest(5);\n  oTest << 0 << 1 << 2 << 3 << 4;\n\n  DTree<arma::mat> testDTree(testData);\n  testDTree.Grow(testData, oTest, false, 2, 1);\n\n  arma::vec imps;\n\n  testDTree.ComputeVariableImportance(imps);\n\n  BOOST_REQUIRE_CLOSE((double) 0.0, imps[0], 1e-10);\n  BOOST_REQUIRE_CLOSE((double) (rError - (rlError + rrError)), imps[1], 1e-10);\n  BOOST_REQUIRE_CLOSE((double) (rootError - (lError + rError)), imps[2], 1e-10);\n}\n\nBOOST_AUTO_TEST_CASE(TestSparsePruneAndUpdate)\n{\n  arma::mat realData(3, 5);\n\n  realData << 4 << 5 << 7 << 3 << 5 << arma::endr\n           << 5 << 0 << 1 << 7 << 1 << arma::endr\n           << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  arma::sp_mat testData(realData);\n\n  arma::Col<size_t> oTest(5);\n  oTest << 0 << 1 << 2 << 3 << 4;\n\n  DTree<arma::sp_mat> testDTree(testData);\n  double alpha = testDTree.Grow(testData, oTest, false, 2, 1);\n  alpha = testDTree.PruneAndUpdate(alpha, testData.n_cols, false);\n\n  BOOST_REQUIRE_CLOSE(alpha, numeric_limits<double>::max(), 1e-10);\n  BOOST_REQUIRE(testDTree.SubtreeLeaves() == 1);\n\n  double rootError = -log(4.0) - log(7.0) - log(7.0);\n\n  BOOST_REQUIRE_CLOSE(testDTree.LogNegError(), rootError, 1e-10);\n  BOOST_REQUIRE_CLOSE(testDTree.SubtreeLeavesLogNegError(), rootError, 1e-10);\n  BOOST_REQUIRE(testDTree.Left() == NULL);\n  BOOST_REQUIRE(testDTree.Right() == NULL);\n}\n\nBOOST_AUTO_TEST_CASE(TestSparseComputeValue)\n{\n  arma::mat realData(3, 5);\n\n  realData << 4 << 5 << 7 << 3 << 5 << arma::endr\n           << 5 << 0 << 1 << 7 << 1 << arma::endr\n           << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  arma::vec q1d(3), q2d(3), q3d(3), q4d(3);\n\n  q1d << 4 << 2 << 2;\n  q2d << 5 << 0.25 << 6;\n  q3d << 5 << 3 << 7;\n  q4d << 2 << 3 << 3;\n\n  arma::sp_mat testData(realData);\n  arma::sp_vec q1(q1d), q2(q2d), q3(q3d), q4(q4d);\n\n  arma::Col<size_t> oTest(5);\n  oTest << 0 << 1 << 2 << 3 << 4;\n\n  DTree<arma::sp_mat> testDTree(testData);\n  double alpha = testDTree.Grow(testData, oTest, false, 2, 1);\n\n  double d1 = (2.0 / 5.0) / exp(log(4.0) + log(7.0) + log(4.5));\n  double d2 = (1.0 / 5.0) / exp(log(4.0) + log(0.5) + log(2.5));\n  double d3 = (2.0 / 5.0) / exp(log(4.0) + log(6.5) + log(2.5));\n\n  BOOST_REQUIRE_CLOSE(d1, testDTree.ComputeValue(q1), 1e-10);\n  BOOST_REQUIRE_CLOSE(d2, testDTree.ComputeValue(q2), 1e-10);\n  BOOST_REQUIRE_CLOSE(d3, testDTree.ComputeValue(q3), 1e-10);\n  BOOST_REQUIRE_CLOSE(0.0, testDTree.ComputeValue(q4), 1e-10);\n\n  alpha = testDTree.PruneAndUpdate(alpha, testData.n_cols, false);\n\n  double d = 1.0 / exp(log(4.0) + log(7.0) + log(7.0));\n\n  BOOST_REQUIRE_CLOSE(d, testDTree.ComputeValue(q1), 1e-10);\n  BOOST_REQUIRE_CLOSE(d, testDTree.ComputeValue(q2), 1e-10);\n  BOOST_REQUIRE_CLOSE(d, testDTree.ComputeValue(q3), 1e-10);\n  BOOST_REQUIRE_CLOSE(0.0, testDTree.ComputeValue(q4), 1e-10);\n}\n\n/**\n * These are not yet implemented.\n *\nBOOST_AUTO_TEST_CASE(TestTagTree)\n{\n  MatType testData(3, 5);\n\n  testData << 4 << 5 << 7 << 3 << 5 << arma::endr\n            << 5 << 0 << 1 << 7 << 1 << arma::endr\n            << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  DTree<>* testDTree = new DTree<>(&testData);\n\n  delete testDTree;\n}\n\nBOOST_AUTO_TEST_CASE(TestFindBucket)\n{\n  MatType testData(3, 5);\n\n  testData << 4 << 5 << 7 << 3 << 5 << arma::endr\n            << 5 << 0 << 1 << 7 << 1 << arma::endr\n            << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  DTree<>* testDTree = new DTree<>(&testData);\n\n  delete testDTree;\n}\n\n// Test functions in dt_utils.hpp\n\nBOOST_AUTO_TEST_CASE(TestTrainer)\n{\n\n}\n\nBOOST_AUTO_TEST_CASE(TestPrintVariableImportance)\n{\n\n}\n\nBOOST_AUTO_TEST_CASE(TestPrintLeafMembership)\n{\n\n}\n*/\n\n// Test the copy constructor and the copy operator.\nBOOST_AUTO_TEST_CASE(CopyConstructorAndOperatorTest)\n{\n  arma::mat testData(3, 5);\n\n  testData << 4 << 5 << 7 << 3 << 5 << arma::endr\n           << 5 << 0 << 1 << 7 << 1 << arma::endr\n           << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  // Construct another DTree for testing the children.\n  arma::Col<size_t> oTest(5);\n  oTest << 0 << 1 << 2 << 3 << 4;\n\n  DTree<arma::mat> *testDTree = new DTree<arma::mat>(testData);\n  testDTree->Grow(testData, oTest, false, 2, 1);\n\n  DTree<arma::mat> testDTree2(*testDTree);\n  DTree<arma::mat> testDTree3 = *testDTree;\n\n  double maxVals0 = testDTree->MaxVals()[0];\n  double maxVals1 = testDTree->MaxVals()[1];\n  double maxVals2 = testDTree->MaxVals()[2];\n  double minVals0 = testDTree->MinVals()[0];\n  double minVals1 = testDTree->MinVals()[1];\n  double minVals2 = testDTree->MinVals()[2];\n\n  double maxValsL0 = testDTree->Left()->MaxVals()[0];\n  double maxValsL1 = testDTree->Left()->MaxVals()[1];\n  double maxValsL2 = testDTree->Left()->MaxVals()[2];\n  double minValsL0 = testDTree->Left()->MinVals()[0];\n  double minValsL1 = testDTree->Left()->MinVals()[1];\n  double minValsL2 = testDTree->Left()->MinVals()[2];\n\n  double maxValsR0 = testDTree->Right()->MaxVals()[0];\n  double maxValsR1 = testDTree->Right()->MaxVals()[1];\n  double maxValsR2 = testDTree->Right()->MaxVals()[2];\n  double minValsR0 = testDTree->Right()->MinVals()[0];\n  double minValsR1 = testDTree->Right()->MinVals()[1];\n  double minValsR2 = testDTree->Right()->MinVals()[2];\n\n  // Delete the original tree.\n  delete testDTree;\n\n  // Test the data of copied tree (using copy constructor).\n  BOOST_REQUIRE_EQUAL(testDTree2.MaxVals()[0], maxVals0);\n  BOOST_REQUIRE_EQUAL(testDTree2.MinVals()[0], minVals0);\n  BOOST_REQUIRE_EQUAL(testDTree2.MaxVals()[1], maxVals1);\n  BOOST_REQUIRE_EQUAL(testDTree2.MinVals()[1], minVals1);\n  BOOST_REQUIRE_EQUAL(testDTree2.MaxVals()[2], maxVals2);\n  BOOST_REQUIRE_EQUAL(testDTree2.MinVals()[2], minVals2);\n\n  // Test the data of the copied tree (using the copy operator).\n  BOOST_REQUIRE_EQUAL(testDTree3.MaxVals()[0], maxVals0);\n  BOOST_REQUIRE_EQUAL(testDTree3.MinVals()[0], minVals0);\n  BOOST_REQUIRE_EQUAL(testDTree3.MaxVals()[1], maxVals1);\n  BOOST_REQUIRE_EQUAL(testDTree3.MinVals()[1], minVals1);\n  BOOST_REQUIRE_EQUAL(testDTree3.MaxVals()[2], maxVals2);\n  BOOST_REQUIRE_EQUAL(testDTree3.MinVals()[2], minVals2);\n\n  // Test the structure of the tree copied using the copy constructor.\n  BOOST_REQUIRE(testDTree2.Left()->Left() == NULL);\n  BOOST_REQUIRE(testDTree2.Left()->Right() == NULL);\n  BOOST_REQUIRE(testDTree2.Right()->Left()->Left() == NULL);\n  BOOST_REQUIRE(testDTree2.Right()->Left()->Right() == NULL);\n  BOOST_REQUIRE(testDTree2.Right()->Right()->Left() == NULL);\n  BOOST_REQUIRE(testDTree2.Right()->Right()->Right() == NULL);\n\n  // Test the structure of the tree copied using the copy operator.\n  BOOST_REQUIRE(testDTree3.Left()->Left() == NULL);\n  BOOST_REQUIRE(testDTree3.Left()->Right() == NULL);\n  BOOST_REQUIRE(testDTree3.Right()->Left()->Left() == NULL);\n  BOOST_REQUIRE(testDTree3.Right()->Left()->Right() == NULL);\n  BOOST_REQUIRE(testDTree3.Right()->Right()->Left() == NULL);\n  BOOST_REQUIRE(testDTree3.Right()->Right()->Right() == NULL);\n\n  // Test the data of the tree copied using the copy constructor.\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MaxVals()[0], maxValsL0);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MaxVals()[1], maxValsL1);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MaxVals()[2], maxValsL2);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MinVals()[0], minValsL0);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MinVals()[1], minValsL1);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MinVals()[2], minValsL2);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MaxVals()[0], maxValsR0);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MaxVals()[1], maxValsR1);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MaxVals()[2], maxValsR2);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MinVals()[0], minValsR0);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MinVals()[1], minValsR1);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MinVals()[2], minValsR2);\n  BOOST_REQUIRE(testDTree2.SplitDim() == 2);\n  BOOST_REQUIRE_CLOSE(testDTree2.SplitValue(), 5.5, 1e-5);\n  BOOST_REQUIRE(testDTree2.Right()->SplitDim() == 1);\n  BOOST_REQUIRE_CLOSE(testDTree2.Right()->SplitValue(), 0.5, 1e-5);\n\n  // Test the data of the tree copied using the copy operator.\n  BOOST_REQUIRE_EQUAL(testDTree3.Left()->MaxVals()[0], maxValsL0);\n  BOOST_REQUIRE_EQUAL(testDTree3.Left()->MaxVals()[1], maxValsL1);\n  BOOST_REQUIRE_EQUAL(testDTree3.Left()->MaxVals()[2], maxValsL2);\n  BOOST_REQUIRE_EQUAL(testDTree3.Left()->MinVals()[0], minValsL0);\n  BOOST_REQUIRE_EQUAL(testDTree3.Left()->MinVals()[1], minValsL1);\n  BOOST_REQUIRE_EQUAL(testDTree3.Left()->MinVals()[2], minValsL2);\n  BOOST_REQUIRE_EQUAL(testDTree3.Right()->MaxVals()[0], maxValsR0);\n  BOOST_REQUIRE_EQUAL(testDTree3.Right()->MaxVals()[1], maxValsR1);\n  BOOST_REQUIRE_EQUAL(testDTree3.Right()->MaxVals()[2], maxValsR2);\n  BOOST_REQUIRE_EQUAL(testDTree3.Right()->MinVals()[0], minValsR0);\n  BOOST_REQUIRE_EQUAL(testDTree3.Right()->MinVals()[1], minValsR1);\n  BOOST_REQUIRE_EQUAL(testDTree3.Right()->MinVals()[2], minValsR2);\n  BOOST_REQUIRE(testDTree3.SplitDim() == 2);\n  BOOST_REQUIRE_CLOSE(testDTree3.SplitValue(), 5.5, 1e-5);\n  BOOST_REQUIRE(testDTree3.Right()->SplitDim() == 1);\n  BOOST_REQUIRE_CLOSE(testDTree3.Right()->SplitValue(), 0.5, 1e-5);\n}\n\n// Test the move constructor.\nBOOST_AUTO_TEST_CASE(MoveConstructorTest)\n{\n  arma::mat testData(3, 5);\n\n  testData << 4 << 5 << 7 << 3 << 5 << arma::endr\n           << 5 << 0 << 1 << 7 << 1 << arma::endr\n           << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  // Construct another DTree for testing the children.\n  arma::Col<size_t> oTest(5);\n  oTest << 0 << 1 << 2 << 3 << 4;\n\n  DTree<arma::mat> *testDTree = new DTree<arma::mat>(testData);\n  testDTree->Grow(testData, oTest, false, 2, 1);\n\n  double maxVals0 = testDTree->MaxVals()[0];\n  double maxVals1 = testDTree->MaxVals()[1];\n  double maxVals2 = testDTree->MaxVals()[2];\n  double minVals0 = testDTree->MinVals()[0];\n  double minVals1 = testDTree->MinVals()[1];\n  double minVals2 = testDTree->MinVals()[2];\n\n  double maxValsL0 = testDTree->Left()->MaxVals()[0];\n  double maxValsL1 = testDTree->Left()->MaxVals()[1];\n  double maxValsL2 = testDTree->Left()->MaxVals()[2];\n  double minValsL0 = testDTree->Left()->MinVals()[0];\n  double minValsL1 = testDTree->Left()->MinVals()[1];\n  double minValsL2 = testDTree->Left()->MinVals()[2];\n\n  double maxValsR0 = testDTree->Right()->MaxVals()[0];\n  double maxValsR1 = testDTree->Right()->MaxVals()[1];\n  double maxValsR2 = testDTree->Right()->MaxVals()[2];\n  double minValsR0 = testDTree->Right()->MinVals()[0];\n  double minValsR1 = testDTree->Right()->MinVals()[1];\n  double minValsR2 = testDTree->Right()->MinVals()[2];\n\n  // Construct a new tree using the move constructor.\n  DTree<arma::mat> testDTree2(std::move(*testDTree));\n\n  // Check default values of the original tree.\n  BOOST_REQUIRE_EQUAL(testDTree->LogNegError(), -DBL_MAX);\n  BOOST_REQUIRE(testDTree->Left() == (DTree<arma::mat>*) NULL);\n  BOOST_REQUIRE(testDTree->Right() == (DTree<arma::mat>*) NULL);\n\n  // Delete the original tree.\n  delete testDTree;\n\n  // Test the data of the moved tree.\n  BOOST_REQUIRE_EQUAL(testDTree2.MaxVals()[0], maxVals0);\n  BOOST_REQUIRE_EQUAL(testDTree2.MinVals()[0], minVals0);\n  BOOST_REQUIRE_EQUAL(testDTree2.MaxVals()[1], maxVals1);\n  BOOST_REQUIRE_EQUAL(testDTree2.MinVals()[1], minVals1);\n  BOOST_REQUIRE_EQUAL(testDTree2.MaxVals()[2], maxVals2);\n  BOOST_REQUIRE_EQUAL(testDTree2.MinVals()[2], minVals2);\n\n  // Test the structure of the moved tree.\n  BOOST_REQUIRE(testDTree2.Left()->Left() == NULL);\n  BOOST_REQUIRE(testDTree2.Left()->Right() == NULL);\n  BOOST_REQUIRE(testDTree2.Right()->Left()->Left() == NULL);\n  BOOST_REQUIRE(testDTree2.Right()->Left()->Right() == NULL);\n  BOOST_REQUIRE(testDTree2.Right()->Right()->Left() == NULL);\n  BOOST_REQUIRE(testDTree2.Right()->Right()->Right() == NULL);\n\n  // Test the data of the moved tree.\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MaxVals()[0], maxValsL0);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MaxVals()[1], maxValsL1);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MaxVals()[2], maxValsL2);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MinVals()[0], minValsL0);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MinVals()[1], minValsL1);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MinVals()[2], minValsL2);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MaxVals()[0], maxValsR0);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MaxVals()[1], maxValsR1);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MaxVals()[2], maxValsR2);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MinVals()[0], minValsR0);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MinVals()[1], minValsR1);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MinVals()[2], minValsR2);\n  BOOST_REQUIRE(testDTree2.SplitDim() == 2);\n  BOOST_REQUIRE_CLOSE(testDTree2.SplitValue(), 5.5, 1e-5);\n  BOOST_REQUIRE(testDTree2.Right()->SplitDim() == 1);\n  BOOST_REQUIRE_CLOSE(testDTree2.Right()->SplitValue(), 0.5, 1e-5);\n}\n\n// Test the move operator.\nBOOST_AUTO_TEST_CASE(MoveOperatorTest)\n{\n  arma::mat testData(3, 5);\n\n  testData << 4 << 5 << 7 << 3 << 5 << arma::endr\n           << 5 << 0 << 1 << 7 << 1 << arma::endr\n           << 5 << 6 << 7 << 1 << 8 << arma::endr;\n\n  // Construct another DTree for testing the children.\n  arma::Col<size_t> oTest(5);\n  oTest << 0 << 1 << 2 << 3 << 4;\n\n  DTree<arma::mat> *testDTree = new DTree<arma::mat>(testData);\n  testDTree->Grow(testData, oTest, false, 2, 1);\n\n  double maxVals0 = testDTree->MaxVals()[0];\n  double maxVals1 = testDTree->MaxVals()[1];\n  double maxVals2 = testDTree->MaxVals()[2];\n  double minVals0 = testDTree->MinVals()[0];\n  double minVals1 = testDTree->MinVals()[1];\n  double minVals2 = testDTree->MinVals()[2];\n\n  double maxValsL0 = testDTree->Left()->MaxVals()[0];\n  double maxValsL1 = testDTree->Left()->MaxVals()[1];\n  double maxValsL2 = testDTree->Left()->MaxVals()[2];\n  double minValsL0 = testDTree->Left()->MinVals()[0];\n  double minValsL1 = testDTree->Left()->MinVals()[1];\n  double minValsL2 = testDTree->Left()->MinVals()[2];\n\n  double maxValsR0 = testDTree->Right()->MaxVals()[0];\n  double maxValsR1 = testDTree->Right()->MaxVals()[1];\n  double maxValsR2 = testDTree->Right()->MaxVals()[2];\n  double minValsR0 = testDTree->Right()->MinVals()[0];\n  double minValsR1 = testDTree->Right()->MinVals()[1];\n  double minValsR2 = testDTree->Right()->MinVals()[2];\n\n  // Construct a new tree using the move constructor.\n  DTree<arma::mat> testDTree2 = std::move(*testDTree);\n\n  // Check default values of the original tree.\n  BOOST_REQUIRE_EQUAL(testDTree->LogNegError(), -DBL_MAX);\n  BOOST_REQUIRE(testDTree->Left() == (DTree<arma::mat>*) NULL);\n  BOOST_REQUIRE(testDTree->Right() == (DTree<arma::mat>*) NULL);\n\n  // Delete the original tree.\n  delete testDTree;\n\n  // Test the data of the moved tree.\n  BOOST_REQUIRE_EQUAL(testDTree2.MaxVals()[0], maxVals0);\n  BOOST_REQUIRE_EQUAL(testDTree2.MinVals()[0], minVals0);\n  BOOST_REQUIRE_EQUAL(testDTree2.MaxVals()[1], maxVals1);\n  BOOST_REQUIRE_EQUAL(testDTree2.MinVals()[1], minVals1);\n  BOOST_REQUIRE_EQUAL(testDTree2.MaxVals()[2], maxVals2);\n  BOOST_REQUIRE_EQUAL(testDTree2.MinVals()[2], minVals2);\n\n  // Test the structure of the moved tree.\n  BOOST_REQUIRE(testDTree2.Left()->Left() == NULL);\n  BOOST_REQUIRE(testDTree2.Left()->Right() == NULL);\n  BOOST_REQUIRE(testDTree2.Right()->Left()->Left() == NULL);\n  BOOST_REQUIRE(testDTree2.Right()->Left()->Right() == NULL);\n  BOOST_REQUIRE(testDTree2.Right()->Right()->Left() == NULL);\n  BOOST_REQUIRE(testDTree2.Right()->Right()->Right() == NULL);\n\n  // Test the data of moved tree.\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MaxVals()[0], maxValsL0);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MaxVals()[1], maxValsL1);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MaxVals()[2], maxValsL2);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MinVals()[0], minValsL0);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MinVals()[1], minValsL1);\n  BOOST_REQUIRE_EQUAL(testDTree2.Left()->MinVals()[2], minValsL2);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MaxVals()[0], maxValsR0);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MaxVals()[1], maxValsR1);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MaxVals()[2], maxValsR2);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MinVals()[0], minValsR0);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MinVals()[1], minValsR1);\n  BOOST_REQUIRE_EQUAL(testDTree2.Right()->MinVals()[2], minValsR2);\n  BOOST_REQUIRE(testDTree2.SplitDim() == 2);\n  BOOST_REQUIRE_CLOSE(testDTree2.SplitValue(), 5.5, 1e-5);\n  BOOST_REQUIRE(testDTree2.Right()->SplitDim() == 1);\n  BOOST_REQUIRE_CLOSE(testDTree2.Right()->SplitValue(), 0.5, 1e-5);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "4a16bbd060b1e1c8434c3c3478fe53c357f74ebf", "size": 27939, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/det_test.cpp", "max_stars_repo_name": "gaurav-singh1998/mlpack", "max_stars_repo_head_hexsha": "c104a2dcf0b51a98d9d6fcfc01d4e7047cc83872", "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/det_test.cpp", "max_issues_repo_name": "R-Aravind/mlpack", "max_issues_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "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/det_test.cpp", "max_forks_repo_name": "R-Aravind/mlpack", "max_forks_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "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": 35.7276214834, "max_line_length": 80, "alphanum_fraction": 0.653996206, "num_tokens": 9481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5277410793852357}}
{"text": "#include <Eigen/Sparse>\n// system includes ------------------------------------------------------------\n#include <algorithm>\n#include <boost/program_options.hpp>\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n#include <cmath>\n#include <random>\n\n// own includes ---------------------------------------------------------------\n#include \"spectral/basis/spectral_basis_dimension_accessor.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"spectral/basis/spectral_elem_accessor.hpp\"\n\n#include \"spectral/rotate_basis.hpp\"\n\nusing namespace std;\nusing namespace boltzmann;\nnamespace po = boost::program_options;\n\nconst int dim = 2;\n\nint main(int argc, char *argv[])\n{\n  int K;\n  double beta;\n  bool sorted;\n  po::options_description options(\"options\");\n  options.add_options()\n      (\"help\", \"produce help message\")\n      (\"K\", po::value<int>(&K)->default_value(10))\n      (\"sorted\", po::value<bool>(&sorted)->default_value(true))\n      (\"beta\", po::value<double>(&beta)->default_value(2));\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    cout << options << \"\\n\";\n    return 1;\n  }\n\n  // ------------------------------------------------------------\n  typedef SpectralBasisFactoryKS::basis_type basis_type;\n  basis_type trial_basis;\n  SpectralBasisFactoryKS::create(trial_basis, K, K, beta, sorted);\n  // sort\n  typedef typename basis_type::elem_t elem_t;\n\n  // write to disk\n  SpectralBasisFactoryKS::write_basis_descriptor(trial_basis, \"spectral_basis.desc\");\n  basis_type test_basis;\n  SpectralBasisFactoryKS::create_test(test_basis, K, K, beta, sorted);\n  SpectralBasisFactoryKS::write_basis_descriptor(test_basis, \"spectral_basis_test.desc\");\n\n  // for (int i = 0; i < K; ++i) {\n  //   // loop over all elements in basis\n  //   for (auto  it = trial_basis.begin(); it < trial_basis.end(); ++it) {\n\n  //   }\n  // }\n\n  RotateBasis<basis_type> rotate_basis(trial_basis);\n\n  rotate_basis.init();\n\n  unsigned int L = 100;\n  unsigned int N = trial_basis.n_dofs();\n\n  Eigen::VectorXd x(L * N);\n  Eigen::VectorXd y(L * N);\n  Eigen::VectorXd y2(L * N);\n\n  std::random_device rd;\n\n  // Choose a random mean between 1 and 6\n  // std::default_random_engine e1(rd());\n  std::default_random_engine e1(1);\n  std::uniform_real_distribution<double> uniform_dist(-10, 10);\n\n  for (unsigned int i = 0; i < L * N; i++) {\n    x[i] = uniform_dist(e1);\n  }\n\n  double dphi = 2;\n\n  rotate_basis.apply(y.data(), x.data(), -dphi, L);\n  rotate_basis.apply(y2.data(), y.data(), dphi, L);\n\n  std::cout << \"error: \" << (y2 - x).norm() << std::endl;\n\n  //  Eigen::VectorXd diff = (y2-x);\n\n  // cout << diff\n  //      << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "722805666cc97c9280f06288bc6bab8084d0fb48", "size": 2759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/rotate_polar_basis/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/rotate_polar_basis/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/rotate_polar_basis/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": 26.786407767, "max_line_length": 89, "alphanum_fraction": 0.6270387822, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5277410728772138}}
{"text": "// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Copyright Paul A. Bristow 2015 - 2016.\n// Copyright Christopher Kormanyos 2015 - 2016.\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n// This file also includes Doxygen-style documentation about the function of the code.\n// See http://www.doxygen.org for details.\n\n//! \\file\n\n// Below are snippets of code that can be included into a Quickbook file.\n\n#include <iostream>\n#include <iomanip>\n#include <exception>\n#include <typeinfo>\n\n#include <boost/fixed_point/fixed_point.hpp>\n\n//[fixed_point_type_representation_example_3\n\ntemplate <typename T>\nvoid show_representation_types(std::ostream& os = std::cout)\n{\n  os << \"Fixed_point Type \"\n    << typeid(T).name() \n    // class boost::fixed_point::negatable<7,-1,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined>\n    << \" with range \" << T::range << \", resolution \" << T::resolution << std::endl;\n\n  os << \"value_type is \" << typeid(T::value_type).name() << std::endl; // signed char\n  os << \"float_type is \" << typeid(T::float_type).name() << std::endl; // float\n} // template <typename T>void show_representation_types()\n\n//] [/fixed_point_type_representation_example_3]\n\n\nint main()\n{\n  using boost::fixed_point::negatable;\n\n  typedef negatable<7, -1> fixed_point_type_7m1;\n  typedef negatable<15, -16> fixed_point_type_15m16;\n  typedef negatable<0, -15> fixed_point_type_0m15;\n  typedef negatable<0, -31> fixed_point_type_0m31;\n  typedef negatable<10, -21> fixed_point_type_10m21;\n  typedef negatable<0, -63> fixed_point_type_0m63;\n  typedef negatable<10, -53> fixed_point_type_10m53;\n  typedef negatable<2, -78> fixed_point_type_2m78; \n  typedef negatable<0, -126> fixed_point_type_0m126; // \n  typedef negatable<10, -116> fixed_point_type_10m116; // \n  typedef negatable<0, -254> fixed_point_type_0m254;\n\n  try\n  {\n    std::cout.setf(std::ios_base::boolalpha | std::ios_base::showpoint); // Show any trailing zeros.\n    std::cout << std::endl;\n\n//[fixed_point_type_representation_example_1\n     std::cout << typeid(negatable<0, -7>::value_type).name() << std::endl;\n//] [/fixed_point_type_representation_example_1]\n\n//[fixed_point_type_representation_example_2\n     std::cout << typeid(negatable<0, -7>::float_type).name() << std::endl;\n//] [/fixed_point_type_representation_example_2]\n\n   show_representation_types<fixed_point_type_7m1>();\n   show_representation_types<fixed_point_type_15m16>();\n   show_representation_types<fixed_point_type_0m15>();\n   show_representation_types<fixed_point_type_0m31>();\n   show_representation_types<fixed_point_type_10m21>();\n   show_representation_types<fixed_point_type_0m63>();\n   show_representation_types<fixed_point_type_10m53>();\n   show_representation_types<fixed_point_type_2m78>();\n   show_representation_types<fixed_point_type_0m126>();\n   show_representation_types<fixed_point_type_10m116>();\n   show_representation_types<fixed_point_type_0m254>();\n\n  }\n  catch (std::exception ex)\n  {\n    std::cout << ex.what() << std::endl;\n  }\n}\n\n/*\n//[fixed_point_representation_examples_output_1\n\nGCC5.1.0\n\nsigned char\nfloat\nFixed_point Type class boost::fixed_point::negatable<7,-1,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 7, resolution -1\nvalue_type is short\nfloat_type is float\nFixed_point Type class boost::fixed_point::negatable<15,-16,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 15, resolution -16\nvalue_type is int\nfloat_type is double\nFixed_point Type class boost::fixed_point::negatable<0,-15,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 0, resolution -15\nvalue_type is short\nfloat_type is float\nFixed_point Type class boost::fixed_point::negatable<0,-31,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 0, resolution -31\nvalue_type is int\nfloat_type is double\nFixed_point Type class boost::fixed_point::negatable<10,-21,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 10, resolution -21\nvalue_type is int\nfloat_type is double\nFixed_point Type class boost::fixed_point::negatable<0,-63,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 0, resolution -63\nvalue_type is __int64\nfloat_type is class boost::multiprecision::number<class boost::multiprecision::backends::cpp_bin_float<63,2,void,int,0,0>,0>\nFixed_point Type class boost::fixed_point::negatable<10,-53,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 10, resolution -53\nvalue_type is __int64\nfloat_type is class boost::multiprecision::number<class boost::multiprecision::backends::cpp_bin_float<63,2,void,int,0,0>,0>\nFixed_point Type class boost::fixed_point::negatable<2,-78,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 2, resolution -78\nvalue_type is class boost::multiprecision::number<struct boost::multiprecision::backends::cpp_int_backend<128,128,1,0,void>,0>\nfloat_type is class boost::multiprecision::number<class boost::multiprecision::backends::cpp_bin_float<80,2,void,int,0,0>,0>\nFixed_point Type class boost::fixed_point::negatable<0,-126,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 0, resolution -126\nvalue_type is class boost::multiprecision::number<struct boost::multiprecision::backends::cpp_int_backend<128,128,1,0,void>,0>\nfloat_type is class boost::multiprecision::number<class boost::multiprecision::backends::cpp_bin_float<126,2,void,int,0,0>,0>\nFixed_point Type class boost::fixed_point::negatable<10,-116,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 10, resolution -116\nvalue_type is class boost::multiprecision::number<struct boost::multiprecision::backends::cpp_int_backend<128,128,1,0,void>,0>\nfloat_type is class boost::multiprecision::number<class boost::multiprecision::backends::cpp_bin_float<126,2,void,int,0,0>,0>\nFixed_point Type class boost::fixed_point::negatable<0,-254,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 0, resolution -254\nvalue_type is class boost::multiprecision::number<struct boost::multiprecision::backends::cpp_int_backend<256,256,1,0,void>,0>\nfloat_type is class boost::multiprecision::number<class boost::multiprecision::backends::cpp_bin_float<254,2,void,int,0,0>,0>\n\n//] [/fixed_point_representation_examples_output_1]\n\n//[fixed_point_representation_examples_output_2\n\nVS 2013\n\nFixed_point Type class boost::fixed_point::negatable<7,-1,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 7, resolution -1\nvalue_type is short\nfloat_type is float\nFixed_point Type class boost::fixed_point::negatable<15,-16,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 15, resolution -16\nvalue_type is int\nfloat_type is double\nFixed_point Type class boost::fixed_point::negatable<0,-15,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 0, resolution -15\nvalue_type is short\nfloat_type is float\nFixed_point Type class boost::fixed_point::negatable<0,-31,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 0, resolution -31\nvalue_type is int\nfloat_type is double\nFixed_point Type class boost::fixed_point::negatable<10,-21,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 10, resolution -21\nvalue_type is int\nfloat_type is double\nFixed_point Type class boost::fixed_point::negatable<0,-63,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 0, resolution -63\nvalue_type is __int64\nfloat_type is class boost::multiprecision::number<class boost::multiprecision::backends::cpp_bin_float<63,2,void,int,0,0>,0>\nFixed_point Type class boost::fixed_point::negatable<10,-53,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 10, resolution -53\nvalue_type is __int64\nfloat_type is class boost::multiprecision::number<class boost::multiprecision::backends::cpp_bin_float<63,2,void,int,0,0>,0>\nFixed_point Type class boost::fixed_point::negatable<2,-78,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 2, resolution -78\nvalue_type is class boost::multiprecision::number<struct boost::multiprecision::backends::cpp_int_backend<128,128,1,0,void>,0>\nfloat_type is class boost::multiprecision::number<class boost::multiprecision::backends::cpp_bin_float<80,2,void,int,0,0>,0>\nFixed_point Type class boost::fixed_point::negatable<0,-126,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 0, resolution -126\nvalue_type is class boost::multiprecision::number<struct boost::multiprecision::backends::cpp_int_backend<128,128,1,0,void>,0>\nfloat_type is class boost::multiprecision::number<class boost::multiprecision::backends::cpp_bin_float<126,2,void,int,0,0>,0>\nFixed_point Type class boost::fixed_point::negatable<10,-116,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 10, resolution -116\nvalue_type is class boost::multiprecision::number<struct boost::multiprecision::backends::cpp_int_backend<128,128,1,0,void>,0>\nfloat_type is class boost::multiprecision::number<class boost::multiprecision::backends::cpp_bin_float<126,2,void,int,0,0>,0>\nFixed_point Type class boost::fixed_point::negatable<0,-254,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined> with range 0, resolution -254\nvalue_type is class boost::multiprecision::number<struct boost::multiprecision::backends::cpp_int_backend<256,256,1,0,void>,0>\nfloat_type is class boost::multiprecision::number<class boost::multiprecision::backends::cpp_bin_float<254,2,void,int,0,0>,0>\n\n\n//] [/fixed_point_representation_examples_output_2]\n\n\n*/\n", "meta": {"hexsha": "ef5a00ef5df60a7a19b862e14e027bf2874268f6", "size": 10658, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_representation_examples.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_representation_examples.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_representation_examples.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": 59.2111111111, "max_line_length": 181, "alphanum_fraction": 0.7867329705, "num_tokens": 2833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.5277410708688324}}
{"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    smallExample.cpp\n * @brief   Create small example with two poses and one landmark\n * @brief   smallExample\n * @author  Carlos Nieto\n * @author  Frank dellaert\n */\n\n#include <gtsam/nonlinear/Symbol.h>\n#include <gtsam/nonlinear/Ordering.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/NonlinearFactor.h>\n#include <gtsam/inference/FactorGraph.h>\n#include <gtsam/base/Matrix.h>\n\n#include <tests/smallExample.h>\n\n#include <boost/optional.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nnamespace gtsam {\nnamespace example {\n\n\tusing namespace gtsam::noiseModel;\n\n\ttypedef boost::shared_ptr<NonlinearFactor> shared;\n\n\tstatic SharedDiagonal sigma1_0 = noiseModel::Isotropic::Sigma(2,1.0);\n\tstatic SharedDiagonal sigma0_1 = noiseModel::Isotropic::Sigma(2,0.1);\n\tstatic SharedDiagonal sigma0_2 = noiseModel::Isotropic::Sigma(2,0.2);\n\tstatic SharedDiagonal constraintModel = noiseModel::Constrained::All(2);\n\n\tstatic const Index _l1_=0, _x1_=1, _x2_=2;\n\tstatic const Index _x_=0, _y_=1, _z_=2;\n\n\t// Convenience for named keys\n\tusing symbol_shorthand::X;\n\tusing symbol_shorthand::L;\n\n\t/* ************************************************************************* */\n\tboost::shared_ptr<const Graph> sharedNonlinearFactorGraph() {\n\t\t// Create\n\t\tboost::shared_ptr<Graph> nlfg(\n\t\t\t\tnew Graph);\n\n\t\t// prior on x1\n\t\tPoint2 mu;\n\t\tshared f1(new simulated2D::Prior(mu, sigma0_1, X(1)));\n\t\tnlfg->push_back(f1);\n\n\t\t// odometry between x1 and x2\n\t\tPoint2 z2(1.5, 0);\n\t\tshared f2(new simulated2D::Odometry(z2, sigma0_1, X(1), X(2)));\n\t\tnlfg->push_back(f2);\n\n\t\t// measurement between x1 and l1\n\t\tPoint2 z3(0, -1);\n\t\tshared f3(new simulated2D::Measurement(z3, sigma0_2, X(1), L(1)));\n\t\tnlfg->push_back(f3);\n\n\t\t// measurement between x2 and l1\n\t\tPoint2 z4(-1.5, -1.);\n\t\tshared f4(new simulated2D::Measurement(z4, sigma0_2, X(2), L(1)));\n\t\tnlfg->push_back(f4);\n\n\t\treturn nlfg;\n\t}\n\n\t/* ************************************************************************* */\n\tGraph createNonlinearFactorGraph() {\n\t\treturn *sharedNonlinearFactorGraph();\n\t}\n\n\t/* ************************************************************************* */\n\tValues createValues() {\n\t\tValues c;\n\t\tc.insert(X(1), Point2(0.0, 0.0));\n\t\tc.insert(X(2), Point2(1.5, 0.0));\n\t\tc.insert(L(1), Point2(0.0, -1.0));\n\t\treturn c;\n\t}\n\n\t/* ************************************************************************* */\n\tVectorValues createVectorValues() {\n\t\tVectorValues c(vector<size_t>(3, 2));\n\t\tc[_l1_] = Vector_(2, 0.0, -1.0);\n\t\tc[_x1_] = Vector_(2, 0.0, 0.0);\n\t\tc[_x2_] = Vector_(2, 1.5, 0.0);\n\t\treturn c;\n\t}\n\n\t/* ************************************************************************* */\n\tboost::shared_ptr<const Values> sharedNoisyValues() {\n\t\tboost::shared_ptr<Values> c(new Values);\n\t\tc->insert(X(1), Point2(0.1, 0.1));\n\t\tc->insert(X(2), Point2(1.4, 0.2));\n\t\tc->insert(L(1), Point2(0.1, -1.1));\n\t\treturn c;\n\t}\n\n\t/* ************************************************************************* */\n\tValues createNoisyValues() {\n\t\treturn *sharedNoisyValues();\n\t}\n\n\t/* ************************************************************************* */\n\tVectorValues createCorrectDelta(const Ordering& ordering) {\n\t\tVectorValues c(vector<size_t>(3,2));\n\t\tc[ordering[L(1)]] = Vector_(2, -0.1, 0.1);\n\t\tc[ordering[X(1)]] = Vector_(2, -0.1, -0.1);\n\t\tc[ordering[X(2)]] = Vector_(2, 0.1, -0.2);\n\t\treturn c;\n\t}\n\n\t/* ************************************************************************* */\n\tVectorValues createZeroDelta(const Ordering& ordering) {\n\t\tVectorValues c(vector<size_t>(3,2));\n\t\tc[ordering[L(1)]] = zero(2);\n\t\tc[ordering[X(1)]] = zero(2);\n\t\tc[ordering[X(2)]] = zero(2);\n\t\treturn c;\n\t}\n\n\t/* ************************************************************************* */\n\tGaussianFactorGraph createGaussianFactorGraph(const Ordering& ordering) {\n\t\t// Create empty graph\n\t  GaussianFactorGraph fg;\n\n\t\tSharedDiagonal unit2 = noiseModel::Unit::Create(2);\n\n\t\t// linearized prior on x1: c[_x1_]+x1=0 i.e. x1=-c[_x1_]\n\t\tfg.push_back(boost::make_shared<JacobianFactor>(ordering[X(1)], 10*eye(2), -1.0*ones(2), unit2));\n\n\t\t// odometry between x1 and x2: x2-x1=[0.2;-0.1]\n\t\tfg.push_back(boost::make_shared<JacobianFactor>(ordering[X(1)], -10*eye(2),ordering[X(2)], 10*eye(2), Vector_(2, 2.0, -1.0), unit2));\n\n    // measurement between x1 and l1: l1-x1=[0.0;0.2]\n\t\tfg.push_back(boost::make_shared<JacobianFactor>(ordering[X(1)], -5*eye(2), ordering[L(1)], 5*eye(2), Vector_(2, 0.0, 1.0), unit2));\n\n\t\t// measurement between x2 and l1: l1-x2=[-0.2;0.3]\n\t\tfg.push_back(boost::make_shared<JacobianFactor>(ordering[X(2)], -5*eye(2), ordering[L(1)], 5*eye(2), Vector_(2, -1.0, 1.5), unit2));\n\n\t\treturn fg;\n\t}\n\n\t/* ************************************************************************* */\n\t/** create small Chordal Bayes Net x <- y\n\t * x y d\n\t * 1 1 9\n\t *   1 5\n\t */\n\tGaussianBayesNet createSmallGaussianBayesNet() {\n\t\tMatrix R11 = Matrix_(1, 1, 1.0), S12 = Matrix_(1, 1, 1.0);\n\t\tMatrix R22 = Matrix_(1, 1, 1.0);\n\t\tVector d1(1), d2(1);\n\t\td1(0) = 9;\n\t\td2(0) = 5;\n\t\tVector tau(1);\n\t\ttau(0) = 1.0;\n\n\t\t// define nodes and specify in reverse topological sort (i.e. parents last)\n\t\tGaussianConditional::shared_ptr Px_y(new GaussianConditional(_x_, d1, R11, _y_, S12, tau));\n\t\tGaussianConditional::shared_ptr Py(new GaussianConditional(_y_, d2, R22, tau));\n\t\tGaussianBayesNet cbn;\n\t\tcbn.push_back(Px_y);\n\t\tcbn.push_back(Py);\n\n\t\treturn cbn;\n\t}\n\n\t/* ************************************************************************* */\n\t// Some nonlinear functions to optimize\n\t/* ************************************************************************* */\n\tnamespace smallOptimize {\n\n\t\tPoint2 h(const Point2& v) {\n\t\t\treturn Point2(cos(v.x()), sin(v.y()));\n\t\t}\n\n\t\tMatrix H(const Point2& v) {\n\t\t\treturn Matrix_(2, 2,\n\t\t\t\t\t-sin(v.x()), 0.0,\n\t\t\t\t\t 0.0, cos(v.y()));\n\t\t}\n\n\t\tstruct UnaryFactor: public gtsam::NoiseModelFactor1<Point2> {\n\n\t\t\tPoint2 z_;\n\n\t\t\tUnaryFactor(const Point2& z, const SharedNoiseModel& model, Key key) :\n\t\t\t\tgtsam::NoiseModelFactor1<Point2>(model, key), z_(z) {\n\t\t\t}\n\n\t\t\tVector evaluateError(const Point2& x, boost::optional<Matrix&> A = boost::none) const {\n\t\t\t\tif (A) *A = H(x);\n\t\t\t\treturn (h(x) - z_).vector();\n\t\t\t}\n\n\t\t};\n\n\t}\n\n\t/* ************************************************************************* */\n\tboost::shared_ptr<const Graph> sharedReallyNonlinearFactorGraph() {\n\t\tboost::shared_ptr<Graph> fg(new Graph);\n\t\tVector z = Vector_(2, 1.0, 0.0);\n\t\tdouble sigma = 0.1;\n\t\tboost::shared_ptr<smallOptimize::UnaryFactor> factor(\n\t\t\t\tnew smallOptimize::UnaryFactor(z, noiseModel::Isotropic::Sigma(2,sigma), X(1)));\n\t\tfg->push_back(factor);\n\t\treturn fg;\n\t}\n\n\tGraph createReallyNonlinearFactorGraph() {\n\t\treturn *sharedReallyNonlinearFactorGraph();\n\t}\n\n\t/* ************************************************************************* */\n\tpair<Graph, Values> createNonlinearSmoother(int T) {\n\n\t\t// Create\n\t\tGraph nlfg;\n\t\tValues poses;\n\n\t\t// prior on x1\n\t\tPoint2 x1(1.0, 0.0);\n\t\tshared prior(new simulated2D::Prior(x1, sigma1_0, X(1)));\n\t\tnlfg.push_back(prior);\n\t\tposes.insert(X(1), x1);\n\n\t\tfor (int t = 2; t <= T; t++) {\n\t\t\t// odometry between x_t and x_{t-1}\n\t\t\tPoint2 odo(1.0, 0.0);\n\t\t\tshared odometry(new simulated2D::Odometry(odo, sigma1_0, X(t - 1), X(t)));\n\t\t\tnlfg.push_back(odometry);\n\n\t\t\t// measurement on x_t is like perfect GPS\n\t\t\tPoint2 xt(t, 0);\n\t\t\tshared measurement(new simulated2D::Prior(xt, sigma1_0, X(t)));\n\t\t\tnlfg.push_back(measurement);\n\n\t\t\t// initial estimate\n\t\t\tposes.insert(X(t), xt);\n\t\t}\n\n\t\treturn make_pair(nlfg, poses);\n\t}\n\n\t/* ************************************************************************* */\n\tpair<FactorGraph<GaussianFactor>, Ordering> createSmoother(int T, boost::optional<Ordering> ordering) {\n\t\tGraph nlfg;\n\t\tValues poses;\n\t\tboost::tie(nlfg, poses) = createNonlinearSmoother(T);\n\n\t\tif(!ordering) ordering = *poses.orderingArbitrary();\n\t\treturn make_pair(*nlfg.linearize(poses, *ordering), *ordering);\n\t}\n\n\t/* ************************************************************************* */\n\tGaussianFactorGraph createSimpleConstraintGraph() {\n\t\t// create unary factor\n\t\t// prior on _x_, mean = [1,-1], sigma=0.1\n\t\tMatrix Ax = eye(2);\n\t\tVector b1(2);\n\t\tb1(0) = 1.0;\n\t\tb1(1) = -1.0;\n\t\tJacobianFactor::shared_ptr f1(new JacobianFactor(_x_, Ax, b1, sigma0_1));\n\n\t\t// create binary constraint factor\n\t\t// between _x_ and _y_, that is going to be the only factor on _y_\n\t\t// |1 0||x_1| + |-1  0||y_1| = |0|\n\t\t// |0 1||x_2|   | 0 -1||y_2|   |0|\n\t\tMatrix Ax1 = eye(2);\n\t\tMatrix Ay1 = eye(2) * -1;\n\t\tVector b2 = Vector_(2, 0.0, 0.0);\n\t\tJacobianFactor::shared_ptr f2(new JacobianFactor(_x_, Ax1, _y_, Ay1, b2,\n\t\t\t\tconstraintModel));\n\n\t\t// construct the graph\n\t\tGaussianFactorGraph fg;\n\t\tfg.push_back(f1);\n\t\tfg.push_back(f2);\n\n\t\treturn fg;\n\t}\n\n\t/* ************************************************************************* */\n\tVectorValues createSimpleConstraintValues() {\n\t\tVectorValues config(vector<size_t>(2,2));\n\t\tVector v = Vector_(2, 1.0, -1.0);\n\t\tconfig[_x_] = v;\n\t\tconfig[_y_] = v;\n\t\treturn config;\n\t}\n\n\t/* ************************************************************************* */\n\tGaussianFactorGraph createSingleConstraintGraph() {\n\t\t// create unary factor\n\t\t// prior on _x_, mean = [1,-1], sigma=0.1\n\t\tMatrix Ax = eye(2);\n\t\tVector b1(2);\n\t\tb1(0) = 1.0;\n\t\tb1(1) = -1.0;\n\t\t//GaussianFactor::shared_ptr f1(new JacobianFactor(_x_, sigma0_1->Whiten(Ax), sigma0_1->whiten(b1), sigma0_1));\n\t\tJacobianFactor::shared_ptr f1(new JacobianFactor(_x_, Ax, b1, sigma0_1));\n\n\t\t// create binary constraint factor\n\t\t// between _x_ and _y_, that is going to be the only factor on _y_\n\t\t// |1 2||x_1| + |10 0||y_1| = |1|\n\t\t// |2 1||x_2|   |0 10||y_2|   |2|\n\t\tMatrix Ax1(2, 2);\n\t\tAx1(0, 0) = 1.0;\n\t\tAx1(0, 1) = 2.0;\n\t\tAx1(1, 0) = 2.0;\n\t\tAx1(1, 1) = 1.0;\n\t\tMatrix Ay1 = eye(2) * 10;\n\t\tVector b2 = Vector_(2, 1.0, 2.0);\n\t\tJacobianFactor::shared_ptr f2(new JacobianFactor(_x_, Ax1, _y_, Ay1, b2,\n\t\t\t\tconstraintModel));\n\n\t\t// construct the graph\n\t\tGaussianFactorGraph fg;\n\t\tfg.push_back(f1);\n\t\tfg.push_back(f2);\n\n\t\treturn fg;\n\t}\n\n\t/* ************************************************************************* */\n\tVectorValues createSingleConstraintValues() {\n\t\tVectorValues config(vector<size_t>(2,2));\n\t\tconfig[_x_] = Vector_(2, 1.0, -1.0);\n\t\tconfig[_y_] = Vector_(2, 0.2, 0.1);\n\t\treturn config;\n\t}\n\n\t/* ************************************************************************* */\n\tGaussianFactorGraph createMultiConstraintGraph() {\n\t\t// unary factor 1\n\t\tMatrix A = eye(2);\n\t\tVector b = Vector_(2, -2.0, 2.0);\n\t\tJacobianFactor::shared_ptr lf1(new JacobianFactor(_x_, A, b, sigma0_1));\n\n\t\t// constraint 1\n\t\tMatrix A11(2, 2);\n\t\tA11(0, 0) = 1.0;\n\t\tA11(0, 1) = 2.0;\n\t\tA11(1, 0) = 2.0;\n\t\tA11(1, 1) = 1.0;\n\n\t\tMatrix A12(2, 2);\n\t\tA12(0, 0) = 10.0;\n\t\tA12(0, 1) = 0.0;\n\t\tA12(1, 0) = 0.0;\n\t\tA12(1, 1) = 10.0;\n\n\t\tVector b1(2);\n\t\tb1(0) = 1.0;\n\t\tb1(1) = 2.0;\n\t\tJacobianFactor::shared_ptr lc1(new JacobianFactor(_x_, A11, _y_, A12, b1,\n\t\t\t\tconstraintModel));\n\n\t\t// constraint 2\n\t\tMatrix A21(2, 2);\n\t\tA21(0, 0) = 3.0;\n\t\tA21(0, 1) = 4.0;\n\t\tA21(1, 0) = -1.0;\n\t\tA21(1, 1) = -2.0;\n\n\t\tMatrix A22(2, 2);\n\t\tA22(0, 0) = 1.0;\n\t\tA22(0, 1) = 1.0;\n\t\tA22(1, 0) = 1.0;\n\t\tA22(1, 1) = 2.0;\n\n\t\tVector b2(2);\n\t\tb2(0) = 3.0;\n\t\tb2(1) = 4.0;\n\t\tJacobianFactor::shared_ptr lc2(new JacobianFactor(_x_, A21, _z_, A22, b2,\n\t\t\t\tconstraintModel));\n\n\t\t// construct the graph\n\t\tGaussianFactorGraph fg;\n\t\tfg.push_back(lf1);\n\t\tfg.push_back(lc1);\n\t\tfg.push_back(lc2);\n\n\t\treturn fg;\n\t}\n\n\t/* ************************************************************************* */\n\tVectorValues createMultiConstraintValues() {\n\t\tVectorValues config(vector<size_t>(3,2));\n\t\tconfig[_x_] = Vector_(2, -2.0, 2.0);\n\t\tconfig[_y_] = Vector_(2, -0.1, 0.4);\n\t\tconfig[_z_] = Vector_(2, -4.0, 5.0);\n\t\treturn config;\n\t}\n\n\n\t/* ************************************************************************* */\n\t// Create key for simulated planar graph\n\tSymbol key(int x, int y) {\n\t\treturn X(1000*x+y);\n\t}\n\n\t/* ************************************************************************* */\n\tboost::tuple<GaussianFactorGraph, VectorValues> planarGraph(size_t N) {\n\n\t\t// create empty graph\n\t\tNonlinearFactorGraph nlfg;\n\n\t\t// Create almost hard constraint on x11, sigma=0 will work for PCG not for normal\n\t\tshared constraint(new simulated2D::Prior(Point2(1.0, 1.0), Isotropic::Sigma(2,1e-3), key(1,1)));\n\t\tnlfg.push_back(constraint);\n\n\t\t// Create horizontal constraints, 1...N*(N-1)\n\t\tPoint2 z1(1.0, 0.0); // move right\n\t\tfor (size_t x = 1; x < N; x++)\n\t\t\tfor (size_t y = 1; y <= N; y++) {\n\t\t\t\tshared f(new simulated2D::Odometry(z1, Isotropic::Sigma(2,0.01), key(x, y), key(x + 1, y)));\n\t\t\t\tnlfg.push_back(f);\n\t\t\t}\n\n\t\t// Create vertical constraints, N*(N-1)+1..2*N*(N-1)\n\t\tPoint2 z2(0.0, 1.0); // move up\n\t\tfor (size_t x = 1; x <= N; x++)\n\t\t\tfor (size_t y = 1; y < N; y++) {\n\t\t\t\tshared f(new simulated2D::Odometry(z2, Isotropic::Sigma(2,0.01), key(x, y), key(x, y + 1)));\n\t\t\t\tnlfg.push_back(f);\n\t\t\t}\n\n\t\t// Create linearization and ground xtrue config\n\t\tValues zeros;\n    for (size_t x = 1; x <= N; x++)\n      for (size_t y = 1; y <= N; y++)\n        zeros.insert(key(x, y), Point2());\n\t\tOrdering ordering(planarOrdering(N));\n\t\tVectorValues xtrue(zeros.dims(ordering));\n\t\tfor (size_t x = 1; x <= N; x++)\n\t\t\tfor (size_t y = 1; y <= N; y++)\n\t\t\t\txtrue[ordering[key(x, y)]] = Point2(x,y).vector();\n\n\t\t// linearize around zero\n\t\tboost::shared_ptr<GaussianFactorGraph> gfg = nlfg.linearize(zeros, ordering);\n\t\treturn boost::make_tuple(*gfg, xtrue);\n\t}\n\n\t/* ************************************************************************* */\n\tOrdering planarOrdering(size_t N) {\n\t\tOrdering ordering;\n\t\tfor (size_t y = N; y >= 1; y--)\n\t\t\tfor (size_t x = N; x >= 1; x--)\n\t\t\t\tordering.push_back(key(x, y));\n\t\treturn ordering;\n\t}\n\n\t/* ************************************************************************* */\n\tpair<GaussianFactorGraph, GaussianFactorGraph > splitOffPlanarTree(size_t N,\n\t\t\tconst GaussianFactorGraph& original) {\n\t\tGaussianFactorGraph T, C;\n\n\t\t// Add the x11 constraint to the tree\n\t\tT.push_back(original[0]);\n\n\t\t// Add all horizontal constraints to the tree\n\t\tsize_t i = 1;\n\t\tfor (size_t x = 1; x < N; x++)\n\t\t\tfor (size_t y = 1; y <= N; y++, i++)\n\t\t\t\tT.push_back(original[i]);\n\n\t\t// Add first vertical column of constraints to T, others to C\n\t\tfor (size_t x = 1; x <= N; x++)\n\t\t\tfor (size_t y = 1; y < N; y++, i++)\n\t\t\t\tif (x == 1)\n\t\t\t\t\tT.push_back(original[i]);\n\t\t\t\telse\n\t\t\t\t\tC.push_back(original[i]);\n\n\t\treturn make_pair(T, C);\n\t}\n\n/* ************************************************************************* */\n\n} // example\n} // namespace gtsam\n", "meta": {"hexsha": "71c8269e915c6ce7dc9df9bff143becffff47fe7", "size": 14977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/smallExample.cpp", "max_stars_repo_name": "sdmiller/gtsam_pcl", "max_stars_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T16:41:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T07:02:44.000Z", "max_issues_repo_path": "tests/smallExample.cpp", "max_issues_repo_name": "sdmiller/gtsam_pcl", "max_issues_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/smallExample.cpp", "max_forks_repo_name": "sdmiller/gtsam_pcl", "max_forks_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T12:06:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T07:02:48.000Z", "avg_line_length": 29.7753479125, "max_line_length": 135, "alphanum_fraction": 0.5479735595, "num_tokens": 4845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5276877474889764}}
{"text": "#pragma once\n\n#include <vector>\n\n#include <Eigen/Geometry>\n#include <iostream>\n#include <geometry_msgs/Vector3.h>\n#include <moveit/robot_state/robot_state.h>\n#include <moveit/robot_model/robot_model.h>\n\n#include \"../include/util/typedefs.hpp\"\n\nclass OmniMath {\n    private:\n\n    MovingAverage moving_average(5,6);\n\n    const bool enable_moving_average;\n\n    public:\n\n    template <typename Type>\n    Type saturate(Type value, Type min, Type max) {\n        if (value < min) {\n            return min;\n        }\n        if (value > max) {\n            return max;\n        }\n        return value;\n    }\n\n    template <typename Type>\n    std::vector<Type> saturate(std::vector<Type> values, Type min, Type max) {\n        std::vector<Type> s(values.size())\n        for (auto iter = values.begin(); iter < values.end(); ++iter) {\n            s[iter-values.begin()] = saturate(*iter, min, max);\n        }\n        return s;\n    }\n\n    Eigen::Affine3d fowardKinematics(\n        robot_state::RobotStatePtr kinematic_state,\n        std::string link_name) {\n            return kinematic_state->getGlobalLinkTransform(link_name);\n    }\n\n    Eigen::Vector3d OmniBase::calculateTorqueFeedback(\n        robot_state::RobotStatePtr kinematic_state,\n        robot_state::JointModelGroup* joint_model_group, \n        //const Eigen::Vector3d& force,\n        const Eigen::Vector3d force,\n        Eigen::Matrix3d rot_link_to_teleop,\n        double feedback_gain,\n        std::string end_effector_name,\n        const robot_state::LinkModel* end_effector_link_model) {\n            if (feedback_gain == 0)\n                return Eigen::Vector3d::Zero();\n\n            // Get the Jacobian matrix written on the base frame\n            Eigen::Vector3d origin(0,0.08,0);\n            Eigen::MatrixXd jacobian;\n            auto link_model = kinematic_state->getLinkModel(end_effector_name);\n            kinematic_state->getJacobian(joint_model_group, link_model, origin, jacobian, false);\n\n            // Rotate the force vector from the desired frame to the base frame\n            Eigen::Vector3d force_on_link_frame = rot_link_to_teleop * force;\n            //\n            auto quat_base_link = fowardKinematics(kinematic_state, end_effector_name)\n            force_on_link_frame = quat_base_link.conjugate() * force_on_link_frame;\n\n            auto ret = feedback_gain * jacobian.block<3,3>(0,0).transpose() * force_on_link_frame;\n            return ret.block<3,1>(0,0);\n        }\n\n    Eigen::VectorXd jerkSaturationFilter(\n        Eigen::VectorXd previous_calculated_velocities,\n        Eigen::VectorXd current_calculated_velocities,\n        double max_jerk) {\n            std:vector<double> saturated_velocities(6);\n            for (int i = 0; i < 6; ++i) {\n                if ( std::abs(current_calculated_velocities[i] - previous_calculated_velocites[i]) < max_jerk ) {\n                    saturated_velocities[i] = current_calculated_velocities[i];\n                }\n                else {\n                    saturated_velocities[i] = previous_calculated_velocities[i];\n                }\n            }\n            Eigen::VectorXd eigen_vector(saturated_velocities.data());\n            return eigen_vector;\n        }\n\n    Eigen::VectorXd calculateVelocities(\n        Time previous_measurement_time,\n        Time current_measurement_time,\n        Eigen::VectorXd previous_measurement,\n        Eigen::VecotrXd current_measurement,\n        bool enable_moving_average) {\n            double delta_angle;\n            double delta_t = (current_measurement_time - previous_measurement_time).total_microseconds();\n            std::vector<double> calculated_velocities(6);\n            for (int i = 0; i < 6; ++i) {\n                deltaAngle = current_measurement[i] - previous_measurement[i];\n                calculated_velocities[i] = deltaAngle * 1000000 / dt;\n            }\n            if (enable_moving_average) {\n                moving_average.input(calculated_velocities);\n                Eigen::VectorXd joint_velocities(moving_average.mean.data());\n            }\n            else Eigen::VectorXd joint_velocities(calculated_velocities.data());\n            return joint_velocities(6);\n        }\n\n    Eigen::VectorXd calculateTwist(\n        robot_state::RobotStatePtr kinematic_state,\n        robot_state::JointModelGroup* joint_model_group,\n        robot_state::LinkModel* end_effector_link_model,\n        Eigen::VectorXd current_joint_velocities) {\n        std::vector<double> twist;\n        Eigen::Vector3d origin(0,0,0);\n        Eigen::MatrixXd jacobian(6,6);\n        kinematic_state->getJacobian(joint_model_group, end_effector_link_model, origin, jacobian, false);\n        return jacobian * current_joint_velocities;\n    }\n\npublic:\n    /**\n     * @brief OmniBase constructor, sets some members and prepares ros topics and publishers.\n     * @param name Reference to string of omni name.\n     */\n    explicit OmniMath(const bool enable_moving_average);\n};", "meta": {"hexsha": "f059db72185281f4e71ce12e05abdb36adaef8bd", "size": 4930, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "omni_driver/include/math/omni_math.hpp", "max_stars_repo_name": "jdrew1303/ros_geomagic_touch_phantom_omni", "max_stars_repo_head_hexsha": "fada3eae2d6249112b9566ff43dfd6144ea0a959", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-11-13T06:49:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T22:35:04.000Z", "max_issues_repo_path": "omni_driver/include/math/omni_math.hpp", "max_issues_repo_name": "jdrew1303/ros_geomagic_touch_phantom_omni", "max_issues_repo_head_hexsha": "fada3eae2d6249112b9566ff43dfd6144ea0a959", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-05-22T19:32:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T03:59:05.000Z", "max_forks_repo_path": "omni_driver/include/math/omni_math.hpp", "max_forks_repo_name": "jdrew1303/ros_geomagic_touch_phantom_omni", "max_forks_repo_head_hexsha": "fada3eae2d6249112b9566ff43dfd6144ea0a959", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-19T02:30:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T22:35:12.000Z", "avg_line_length": 37.3484848485, "max_line_length": 113, "alphanum_fraction": 0.6365111562, "num_tokens": 1089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5276536635422724}}
{"text": "#include <math.h>\r\n#include <cmath>\r\n#include <RcppEigen.h>\r\n#include <Rcpp.h>\r\n#include <iostream>\r\n#include <vector>\r\n#include <Eigen/Core>\r\n#include <iostream>\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\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)floor(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}", "meta": {"hexsha": "4865467a9f19742d5db3ff15897b90f9a947e266", "size": 2085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Second/Numerico/Miniproyecto/W_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_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_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": 36.5789473684, "max_line_length": 117, "alphanum_fraction": 0.6177458034, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.5276536597413648}}
{"text": "// Std includes\n#include <cmath>\n#include <iostream>\n#include <memory>\n// Thirdparties includes\n#include <Eigen/Dense>\n// Lib includes\n#include \"s0s/runge_kutta_fehlberg.h\"\n#include \"sl0/point.h\"\n#include \"sl0/group/dynamic.h\"\n// Simple includes\n#include \"flow.h\"\n\nusing TypeScalar = double;\n// State\ntemplate<int Size>\nusing TypeVector = Eigen::Matrix<TypeScalar, Size, 1>;\n// Space\nconstexpr unsigned int DIM = 3;\nusing TypeSpaceVector = Eigen::Matrix<TypeScalar, DIM, 1>;\n// Ref and View\ntemplate<typename ...Args>\nusing TypeRef = Eigen::Ref<Args...>;\ntemplate<typename ...Args>\nusing TypeView = Eigen::Map<Args...>;\n// Group Parameters\nusing TypeStepPoint = sl0::StepPoint<TypeVector, DIM, TypeView, Flow>;\n// Solver\nusing TypeSolver = s0s::SolverRungeKuttaFehlberg<TypeVector<Eigen::Dynamic>, TypeView>;\n\nint main () { \n    // Parameters\n    TypeSpaceVector x0 = TypeSpaceVector::Constant(1.0);\n    TypeScalar t0 = 0.0;\n    TypeScalar dt = 1e-3;\n    unsigned int nt = std::round(1.0 / dt);\n    unsigned int np = 1000;\n    // Create group\n    sl0::GroupDynamic<TypeVector, DIM, TypeView, TypeSolver> group;\n    // Ceate points\n    std::cout << \"Point creation\" << \"\\n\";\n    std::shared_ptr<TypeStepPoint> sStepPoint = std::make_shared<TypeStepPoint>(std::make_shared<Flow>());\n    for(std::size_t i = 0; i < np; i++) {\n        group.sStep->addMember(group.state, std::make_shared<TypeStepPoint>(*sStepPoint), DIM);\n        sStepPoint->x(group.sStep->memberState(group.state.data(), i)) = x0;\n    }\n    // Set initial state\n    std::cout << \"Point init\" << \"\\n\";\n    for(std::size_t n = 0; n < group.sStep->size(); n++) {\n        sStepPoint->x(group.sStep->memberState(group.state.data(), n)) = x0;\n    }\n    group.t = t0;\n    // Computation\n    std::cout << \"Computing\" << \"\\n\";\n    for(std::size_t i = 0; i < nt; i++) {\n        group.update(dt);\n    }\n    // out\n    std::cout << \"\\n\";\n    std::cout << \"Group advected following a an exponential flow, exp(\" << group.t << \") = \" << \"\\n\";\n    std::cout << \"\\n\";\n    for(std::size_t n = 0; n < group.sStep->size(); n++) {\n        std::cout << \"Group Final Position : \" << \"\\n\" << sStepPoint->x(group.sStep->memberState(group.state.data(), n)) << \"\\n\";\n    }\n    std::cout << std::endl;\n}\n", "meta": {"hexsha": "8c7df716843dd32928ee61f9d7059e1a9b6931c2", "size": 2241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/group/dynamic/main.cpp", "max_stars_repo_name": "C0PEP0D/sl0", "max_stars_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_stars_repo_licenses": ["MIT"], "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/group/dynamic/main.cpp", "max_issues_repo_name": "C0PEP0D/sl0", "max_issues_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_issues_repo_licenses": ["MIT"], "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/group/dynamic/main.cpp", "max_forks_repo_name": "C0PEP0D/sl0", "max_forks_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_forks_repo_licenses": ["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.447761194, "max_line_length": 129, "alphanum_fraction": 0.6296296296, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5276536521395495}}
{"text": "#include \"LinearCodeGenerator.h\"\n#include \"Math.h\"\n\n#include <unordered_map>\n#include <gurobi_c++.h>\n#include <armadillo>\n#include <random>\n\n/* Configuration */\nconstexpr bool SHOW_GUROBI_OUTPUT = true;\nconstexpr bool SHOW_MATRIX_OUTPUT = false;\nconstexpr uint32_t TIMEOUT_MATRIX_REDUCE = 1;\n\nLinearCodeGenerator::LinearCodeGenerator(uint16_t q, uint16_t k, uint16_t b)\n\t: m_q(q)\n\t, m_k(k)\n\t, m_b(b)\n{\n\t\n}\n\nauto LinearCodeGenerator::generateCode() const -> LinearCode\n{\n\tstd::cout << \"Generating canonical represents\" << std::endl;\n\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\n\tauto canonialRepresents = Math::generateCanonialRepresents(m_q, m_k);\n\tif (SHOW_MATRIX_OUTPUT)\n\t{\n\t\tfor (arma::uword i = 0; i < canonialRepresents.size(); ++i)\n\t\t{\n\t\t\tstd::cout << \"r\" << i << \"\\t\";\n\t\t\tcanonialRepresents.at(i).t().raw_print();\n\t\t}\n\t}\n\tstd::cout << \"----------------------------------------------------\" << std::endl << std::endl;\n\n\n\n\tstd::cout << \"Generating matrix A\" << std::endl;\n\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\tconst auto matrixA = generateMatrixA(canonialRepresents);\n\tif (SHOW_MATRIX_OUTPUT)\n\t{\n\t\tmatrixA.raw_print();\n\t}\n\tstd::cout << \"----------------------------------------------------\" << std::endl << std::endl;\n\n\n\n\tstd::cout << \"Generating producer e0\" << std::endl;\n\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\tconst auto producerE0 = generateProducerE0(canonialRepresents, matrixA);\n\n\tconst auto colCycles = cycleCheck(canonialRepresents, producerE0, m_q);\n\tconst auto rowCycles = cycleCheck(canonialRepresents, producerE0.t(), m_q);\n\n\tauto colGroups = generateRepresentGroups(colCycles, canonialRepresents.size());\n\tauto rowGroups = generateRepresentGroups(rowCycles, canonialRepresents.size());\n\n\tstd::cout << \"Found Producer e0 - reducing to [\" << colGroups.size() << \"] groups\" << std::endl;\n\tif (SHOW_MATRIX_OUTPUT)\n\t{\n\t\tproducerE0.raw_print();\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl << std::endl;\n\t\tstd::cout << \"Found cycles for columns\" << std::endl;\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\t\tfor (auto& group : colGroups)\n\t\t{\n\t\t\tstd::cout << \"S([r\" << group.at(0) << \"]) = {\";\n\t\t\tfor (arma::uword i = 0; i < group.size(); i++)\n\t\t\t{\n\t\t\t\tstd::cout << \"[r\" << group.at(i) << \"]\";\n\t\t\t\tif (i != group.size() - 1) std::cout << \", \";\n\t\t\t}\n\t\t\tstd::cout << \"}\" << std::endl;\n\t\t}\n\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"Found cycles for rows\" << std::endl;\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\t\tfor (auto& group : rowGroups)\n\t\t{\n\t\t\tstd::cout << \"ST([r\" << group.at(0) << \"]) = {\";\n\t\t\tfor (arma::uword i = 0; i < group.size(); i++)\n\t\t\t{\n\t\t\t\tstd::cout << \"[r\" << group.at(i) << \"]\";\n\t\t\t\tif (i != group.size() - 1) std::cout << \", \";\n\t\t\t}\n\t\t\tstd::cout << \"}\" << std::endl;\n\t\t}\n\t}\n\tstd::cout << \"----------------------------------------------------\" << std::endl << std::endl;\n\n\n\n\tstd::cout << \"Re-calculate matrix A with cylces\" << std::endl;\n\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\tconst auto optMatrixA = generateOptimizedMatrixA(matrixA, colCycles, rowCycles);\n\tif (SHOW_MATRIX_OUTPUT)\n\t{\n\t\toptMatrixA.raw_print();\n\t}\n\tstd::cout << \"----------------------------------------------------\" << std::endl << std::endl;\n\n\n\n\tstd::cout << \"Calculate vector c\" << std::endl;\n\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\tconst auto vectorC = generateVectorC(colGroups);\n\tvectorC.t().raw_print();\n\tstd::cout << \"----------------------------------------------------\" << std::endl << std::endl;\n\n\n\n\tstd::cout << \"Calculating vector x\" << std::endl;\n\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\tauto vectorX = generateVectorX(optMatrixA, vectorC, m_b);\n\tvectorX.t().raw_print();\n\tstd::cout << \"----------------------------------------------------\" << std::endl << std::endl;\n\n\n\n\tconst uint16_t n = dot(vectorX, vectorC);\n\tconst uint16_t d = n - m_b;\n\tauto G = generateMatrixG(vectorX, colGroups, canonialRepresents);\n\n\treturn { n, m_q, m_k, d, G };\n}\n\n\nauto LinearCodeGenerator::generateProducerE0(const std::vector<arma::s32_vec>& canonialRepresents, const arma::s32_mat& matrixA) const -> arma::s32_mat\n{\n\tarma::s32_mat e0(m_k, m_k);\n\tarma::s32_mat test_e0(m_k, m_k);\n\ttest_e0.fill(0);\n\tauto colGroupCount = std::numeric_limits<uint32_t>::max();\n\tuint32_t timeout = 0;\n\n\tstd::chrono::high_resolution_clock::time_point start;\n\tdo\n\t{\n\t\tauto colCycles = cycleCheck(canonialRepresents, test_e0, m_q);\n\t\tauto colGroups = generateRepresentGroups(colCycles, canonialRepresents.size());\n\n\t\tuint32_t maxElements = 0;\n\t\tfor (auto& colGroup : colGroups)\n\t\t{\n\t\t\tif (colGroup.size() > maxElements)\n\t\t\t{\n\t\t\t\tmaxElements = colGroup.size();\n\t\t\t}\n\t\t}\n\t\tif (maxElements < m_q && colGroups.size() < colGroupCount)\n\t\t{\n\t\t\tcolGroupCount = colGroups.size();\n\t\t\te0 = test_e0;\n\t\t\ttimeout = 0;\n\t\t}\n\n\t\tconst auto end = std::chrono::high_resolution_clock::now();\n\t\tconst auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();\n\t\tif (duration > 1000)\n\t\t{\n\t\t\tstd::cout << \"Current producer e0 reduces A from [\" << matrixA.n_cols << \"] to [\" << colGroupCount << \"] columns.\" << std::endl;\n\t\t\tstart = end;\n\t\t\t++timeout;\n\t\t}\n\n\t\ttest_e0 = generateMatrixE0();\n\t} while (colGroupCount == matrixA.n_cols || timeout < TIMEOUT_MATRIX_REDUCE);\n\n\treturn e0;\n}\n\nauto LinearCodeGenerator::generateOptimizedMatrixA(const arma::s32_mat& matrixA,\n\tconst std::unordered_map<arma::uword, std::vector<arma::uword>>& colCycles,\n\tconst std::unordered_map<arma::uword, std::vector<arma::uword>>& rowCycles) const -> arma::s32_mat\n{\n\tauto optMatrixA = matrixA;\n\tstd::vector<arma::uword> colsDelete;\n\tstd::vector<arma::uword> rowsDelete;\n\n\tfor (auto& c : colCycles)\n\t{\n\t\tfor (arma::uword i = 1; i < c.second.size(); ++i)\n\t\t{\n\t\t\tfor (arma::uword j = 0; j < optMatrixA.n_rows; j++)\n\t\t\t{\n\t\t\t\toptMatrixA(j, c.second.at(0)) += optMatrixA(j, c.second.at(i));\n\t\t\t}\n\n\t\t\tcolsDelete.push_back(c.second.at(i));\n\t\t}\n\t}\n\n\tfor (auto& r : rowCycles)\n\t{\n\t\tfor (arma::uword i = 1; i < r.second.size(); ++i)\n\t\t{\n\t\t\trowsDelete.push_back(r.second.at(i));\n\t\t}\n\t}\n\n\tsort(colsDelete.begin(), colsDelete.end());\n\treverse(colsDelete.begin(), colsDelete.end());\n\tfor (auto& c : colsDelete)\n\t{\n\t\toptMatrixA.shed_col(c);\n\t}\n\n\tsort(rowsDelete.begin(), rowsDelete.end());\n\treverse(rowsDelete.begin(), rowsDelete.end());\n\tfor (auto& r : rowsDelete)\n\t{\n\t\toptMatrixA.shed_row(r);\n\t}\n\n\treturn optMatrixA;\n}\n\nauto LinearCodeGenerator::generateMatrixG(const arma::s32_vec& xVec, const std::vector<std::vector<arma::uword>>& colGroups,\n\tconst std::vector<arma::s32_vec>& rVector) -> arma::s32_mat\n{\n\tuint32_t colSize = 0;\n\tfor (uint32_t i = 0; i < xVec.size(); ++i)\n\t{\n\t\tcolSize += xVec.at(i) * colGroups.at(i).size();\n\t}\n\n\tconst auto rowSize = rVector.at(0).size();\n\tarma::s32_mat G(rowSize, colSize, arma::fill::zeros);\n\n\tint colIndex = 0;\n\tfor (uint32_t x = 0; x < xVec.size(); ++x)\n\t{\n\t\tfor (auto i = 0; i < xVec.at(x); ++i)\n\t\t{\n\t\t\tfor (unsigned int j : colGroups.at(x))\n\t\t\t{\n\t\t\t\tfor (uint32_t k = 0; k < rowSize; ++k)\n\t\t\t\t{\n\t\t\t\t\tG(k, colIndex) = rVector.at(j).at(k);\n\t\t\t\t}\n\t\t\t\tcolIndex++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn G;\n}\n\nauto LinearCodeGenerator::generateVectorC(const std::vector<std::vector<arma::uword>>& colGroups) -> arma::s32_vec\n{\n\tarma::s32_vec vectorC(colGroups.size());\n\n\tfor (arma::uword i = 0; i < colGroups.size(); ++i)\n\t{\n\t\tvectorC.at(i) = colGroups.at(i).size();\n\t}\n\n\treturn vectorC;\n}\n\nauto LinearCodeGenerator::generateVectorX(const arma::s32_mat& matrixA, const arma::s32_vec& vectorC, uint16_t b) -> arma::s32_vec\n{\n\tconst auto env = GRBEnv();\n\tauto model = GRBModel(env);\n\tmodel.getEnv().set(GRB_IntParam_OutputFlag, SHOW_GUROBI_OUTPUT);\n\n\tstd::vector<GRBVar> modelVars;\n\tmodelVars.reserve(vectorC.size());\n\tfor (uint32_t i = 0; i < vectorC.size(); i++)\n\t{\n\t\tmodelVars.push_back(model.addVar(0.0, GRB_INFINITY, 0.0, GRB_INTEGER));\n\t}\n\n\tGRBLinExpr expr = 0.0;\n\tfor (uint32_t i = 0; i < vectorC.size(); i++)\n\t{\n\t\texpr += modelVars.at(i) * vectorC.at(i);\n\t}\n\n\tmodel.setObjective(expr, GRB_MAXIMIZE);\n\n\tfor (arma::uword x = 0; x < matrixA.n_rows; x++)\n\t{\n\t\texpr = 0.0;\n\t\tfor (arma::uword y = 0; y < matrixA.n_cols; y++)\n\t\t{\n\t\t\texpr += modelVars.at(y) * matrixA(x, y);\n\t\t}\n\t\tmodel.addConstr(expr, GRB_LESS_EQUAL, b);\n\t}\n\n\t//model.update();\n\t//model.write(\"debug.lp\");\n\tmodel.optimize();\n\n\tarma::s32_vec vectorX(modelVars.size());\n\tfor (uint32_t i = 0; i < modelVars.size(); ++i)\n\t{\n\t\tvectorX.at(i) = static_cast<int>(modelVars.at(i).get(GRB_DoubleAttr_X));\n\t}\n\n\treturn vectorX;\n}\n\nauto LinearCodeGenerator::generateMatrixA(const std::vector<arma::s32_vec>& canonialRepresents) const -> arma::s32_mat\n{\n\tauto matrixA = arma::s32_mat(canonialRepresents.size(), canonialRepresents.size(), arma::fill::zeros);\n\n\tfor (arma::uword row = 0; row < canonialRepresents.size(); ++row)\n\t{\n\t\tfor (arma::uword col = 0; col < canonialRepresents.size(); ++col)\n\t\t{\n\t\t\tif (static_cast<int>(dot(canonialRepresents.at(row), canonialRepresents.at(col))) % m_q == 0)\n\t\t\t{\n\t\t\t\tmatrixA(row, col) = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn matrixA;\n}\n\nauto sortHelper(const std::vector<arma::uword>& i, const std::vector<arma::uword>& j) -> bool\n{\n\treturn i.at(0) < j.at(0);\n}\n\nauto LinearCodeGenerator::generateRepresentGroups(const std::unordered_map<arma::uword, std::vector<arma::uword>>& cycle,\n\tint vecCount) const -> std::vector<std::vector<arma::uword>>\n{\n\tstd::vector<std::vector<arma::uword>> repGroups;\n\trepGroups.reserve(cycle.size());\n\tfor (auto& c : cycle)\n\t{\n\t\trepGroups.push_back(c.second);\n\t}\n\n\tfor (auto i = 0; i < vecCount; ++i)\n\t{\n\t\tauto found = false;\n\t\tfor (auto& repGroup : repGroups)\n\t\t{\n\t\t\tfor (int k : repGroup)\n\t\t\t{\n\t\t\t\tif (k == i)\n\t\t\t\t{\n\t\t\t\t\tfound = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!found)\n\t\t{\n\t\t\trepGroups.push_back(std::vector<arma::uword>{static_cast<arma::uword>(i)});\n\t\t}\n\t}\n\n\tstd::sort(repGroups.begin(), repGroups.end(), sortHelper);\n\n\treturn repGroups;\n}\n\nauto LinearCodeGenerator::generateMatrixE0() const -> arma::s32_mat\n{\n\tstd::default_random_engine generator;\n\tconst std::uniform_int_distribution<int> distribution(0, m_q - 1);\n\n\tarma::mat e(m_k, m_k);\n\tdo\n\t{\n\t\tfor (auto i = 0; i < m_k; ++i)\n\t\t{\n\t\t\tfor (auto j = 0; j < m_k; ++j)\n\t\t\t{\n\t\t\t\tgenerator.seed(std::random_device()());\n\t\t\t\te(i, j) = distribution(generator);\n\t\t\t}\n\t\t}\n\t} while (0 == arma::det(e));\n\n\tarma::s32_mat e0(m_k, m_k);\n\tfor (auto i = 0; i < m_k; ++i)\n\t{\n\t\tfor (auto j = 0; j < m_k; ++j)\n\t\t{\n\t\t\te0(i, j) = e(i, j);\n\t\t}\n\t}\n\n\treturn e0;\n}\n\nauto LinearCodeGenerator::cycleCheck(const std::vector<arma::s32_vec>& rVector, const arma::s32_mat& E, uint16_t q) const\n-> std::unordered_map<arma::uword, std::vector<arma::uword>>\n{\n\tstd::unordered_map<arma::uword, arma::uword> convert;\n\tfor (arma::uword i = 0; i < rVector.size(); i++)\n\t{\n\t\tarma::s32_vec tmpVec = E * rVector.at(i);\n\t\tMath::normalizeVector(tmpVec, q);\n\t\tif (!Math::isLinDependent(rVector.at(i), tmpVec, q))\n\t\t{\n\t\t\tconst auto vectorIndex = Math::getVectorIndex(rVector, tmpVec, q);\n\t\t\tif (-1 != vectorIndex)\n\t\t\t{\n\t\t\t\t//cout << \"Found conversion: r\" << i << \" -> r\" << vectorIndex << endl;\n\t\t\t\tconvert.insert({ i, vectorIndex });\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::unordered_map<arma::uword, std::vector<arma::uword>> cycles;\n\tfor (arma::uword i = 0; i < rVector.size(); i++)\n\t{\n\t\tconst auto key = convert.find(i);\n\t\tif (key != convert.end())\n\t\t{\n\t\t\tstd::vector<arma::uword> tmp;\n\t\t\ttmp.push_back(key->first);\n\t\t\ttmp.push_back(key->second);\n\n\t\t\tbool search;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tsearch = false;\n\t\t\t\tconst auto next = convert.find(tmp.back());\n\t\t\t\tif (next != convert.end())\n\t\t\t\t{\n\t\t\t\t\tconst auto loop = find(tmp.begin() + 1, tmp.end(), next->second);\n\t\t\t\t\tif (loop != tmp.end())\n\t\t\t\t\t{\n\t\t\t\t\t\ttmp.erase(tmp.begin(), loop);\n\t\t\t\t\t}\n\n\t\t\t\t\ttmp.push_back(next->second);\n\t\t\t\t\tsearch = true;\n\t\t\t\t}\n\t\t\t} while (search && tmp.front() != tmp.back());\n\n\t\t\tif (tmp.front() == tmp.back())\n\t\t\t{\n\t\t\t\ttmp.pop_back();\n\t\t\t\tstd::sort(tmp.begin(), tmp.end());\n\t\t\t\tif (cycles.find(tmp.front()) == cycles.end())\n\t\t\t\t{\n\t\t\t\t\tcycles.insert({ tmp.front(), tmp });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn cycles;\n}\n", "meta": {"hexsha": "5be394d468869b7f1ebf3d058d7baef03b02fa32", "size": 12220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lin-code-gen/LinearCodeGenerator.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/LinearCodeGenerator.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/LinearCodeGenerator.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": 26.6812227074, "max_line_length": 151, "alphanum_fraction": 0.5890343699, "num_tokens": 3681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5276476554047569}}
{"text": "#ifndef BASETYPES\n#define BASETYPES\n\n/** \\file BaseTypes.hpp\n * \\brief Basic type definitions and global constants */\n\n#include <armadillo>\n\nusing Matrix = arma::mat;\nusing Vector = arma::vec;\nusing Vector_un = arma::Col<unsigned>;\n\nnamespace math\n{\nconst double pi = arma::datum::pi;\nconst double rpi2 = 1.0 / (2.0 * pi);\n};\n\n#endif\n", "meta": {"hexsha": "505cb097bc6cdcd48f74f6f6619efc5704515179", "size": 334, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/BaseTypes.hpp", "max_stars_repo_name": "gdeskos/DVMpp", "max_stars_repo_head_hexsha": "5d511ea55eec21e65e5d5104639f2c02d8df444d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-07-07T09:15:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T06:01:50.000Z", "max_issues_repo_path": "src/BaseTypes.hpp", "max_issues_repo_name": "gdeskos/DVMpp", "max_issues_repo_head_hexsha": "5d511ea55eec21e65e5d5104639f2c02d8df444d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-23T10:25:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-25T18:47:29.000Z", "max_forks_repo_path": "src/BaseTypes.hpp", "max_forks_repo_name": "gdeskos/DVMpp", "max_forks_repo_head_hexsha": "5d511ea55eec21e65e5d5104639f2c02d8df444d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T21:30:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-02T09:39:03.000Z", "avg_line_length": 16.7, "max_line_length": 56, "alphanum_fraction": 0.6976047904, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5276365628247486}}
{"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 TestPoint3D\n#include <boost/test/unit_test.hpp>\n#include \"minimath/point3d.hpp\"\n#include \"minimath/point3d_ops.hpp\"\n#include \"minimath/numeric_utils.hpp\" // for fp comparisons\n#include <iostream>\n#include <sstream>\n#include <limits>\n#include <cmath>\n\nnamespace\n{\ntypedef minimath::pointxyzd::value_type scalar_type;\nconst scalar_type EPS = std::numeric_limits<scalar_type>::epsilon();\n}\n\nBOOST_AUTO_TEST_SUITE(TestPoint3D)\n\nBOOST_AUTO_TEST_CASE(testInstantiation)\n{\n  minimath::pointxyzd pd1;\n  minimath::pointxyzd pd2(1,2,3);\n}\n\nBOOST_AUTO_TEST_CASE(testEquality)\n{\n  BOOST_CHECK(minimath::pointxyzd()==minimath::pointxyzd());\n  minimath::pointxyzd pd1(1, 2, 3);\n  minimath::pointxyzd pd2(1,2,3);\n  BOOST_CHECK( pd1 == pd2);\n}\n\nBOOST_AUTO_TEST_CASE(testInequality)\n{\n  minimath::pointxyzd pd1(10, 20, 30);\n  minimath::pointxyzd pd2(1,2,3);\n  BOOST_CHECK( pd1 != pd2);\n}\n\nBOOST_AUTO_TEST_CASE(testCloseInequality)\n{\n  minimath::pointxyzd pd1(10, 20, 30);\n  minimath::pointxyzd pd2(10.00001,20,30);\n  BOOST_CHECK( pd1 != pd2);\n}\n\nBOOST_AUTO_TEST_CASE(testAccessX)\n{\n  minimath::pointxyzd pd1(10, 20, 30);\n  BOOST_CHECK( minimath::compare_with_tolerance(pd1.x(), 10., EPS));\n}\n\nBOOST_AUTO_TEST_CASE(testAccessY)\n{\n  minimath::pointxyzd pd1(10, 20, 30);\n  BOOST_CHECK( minimath::compare_with_tolerance(pd1.y(), 20., EPS) );\n}\n\nBOOST_AUTO_TEST_CASE(testAccessZ)\n{\n  minimath::pointxyzd pd1(10, 20, 30);\n  BOOST_CHECK( minimath::compare_with_tolerance(pd1.z(), 30., EPS) );\n}\n\nBOOST_AUTO_TEST_CASE(testSetX)\n{\n  minimath::pointxyzd pd1;\n  pd1.x(3.14);\n  BOOST_CHECK( minimath::compare_with_tolerance(pd1.x(), 3.14, EPS) );\n}\n\nBOOST_AUTO_TEST_CASE(testSetY)\n{\n  minimath::pointxyzd pd1;\n  pd1.y(3.14);\n  BOOST_CHECK(  minimath::compare_with_tolerance(pd1.y(), 3.14, EPS) );\n}\n\nBOOST_AUTO_TEST_CASE(testSetZ)\n{\n  minimath::pointxyzd pd1;\n  pd1.z(3.14);\n  BOOST_CHECK(  minimath::compare_with_tolerance(pd1.z(), 3.14, EPS) );\n}\n\nBOOST_AUTO_TEST_CASE(testCopyConstruction)\n{\n  minimath::pointxyzd pd1(1,2,3);\n  minimath::pointxyzd pd2 = pd1;\n  BOOST_CHECK( pd1 == pd2);\n}\n\nBOOST_AUTO_TEST_CASE(testAssignment)\n{\n  minimath::pointxyzd pd1(1,2,3);\n  minimath::pointxyzd pd2;\n  pd2 = pd1;\n  BOOST_CHECK( pd1 == pd2);\n}\n\nBOOST_AUTO_TEST_CASE(testPlusEquals)\n{\n  minimath::pointxyzd pd(1, 2, 3);\n  pd += minimath::pointxyzd(10,20,30);\n  BOOST_CHECK( pd == minimath::pointxyzd(11,22,33));\n}\n\nBOOST_AUTO_TEST_CASE(testMinusEquals)\n{\n  minimath::pointxyzd pd(11, 22, 33);\n  pd -= minimath::pointxyzd(10,20,30);\n  BOOST_CHECK( pd == minimath::pointxyzd(1,2,3));\n}\n\nBOOST_AUTO_TEST_CASE(testTimesEqualsScalar)\n{\n  minimath::pointxyzd pd(1, 2, 3);\n  pd *= 11;\n  BOOST_CHECK( pd == minimath::pointxyzd(11,22,33));\n\n}\n\nBOOST_AUTO_TEST_CASE(testDivideEqualsScalar)\n{\n  minimath::pointxyzd pd(100, 200, 300);\n  pd /= 10;\n  BOOST_CHECK( pd == minimath::pointxyzd(10,20,30));\n}\n\nBOOST_AUTO_TEST_CASE(testTimesScalar)\n{\n  minimath::pointxyzd pd = minimath::pointxyzd(1, 2, 3) * 11;\n  BOOST_CHECK( pd == minimath::pointxyzd(11,22,33));\n\n}\n\nBOOST_AUTO_TEST_CASE(testDivideScalar)\n{\n  minimath::pointxyzd pd = minimath::pointxyzd(100, 200, 300)/10;\n  BOOST_CHECK( pd == minimath::pointxyzd(10,20,30));\n}\n\n\nBOOST_AUTO_TEST_CASE(testMagnitudeSquared)\n{\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::mag2(minimath::pointxyzd(1,1,1)), 3., EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::mag2(minimath::pointxyzd(5,5,5)), 75., EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::mag2(minimath::pointxyzd(5,0,0)), 25., EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::mag2(minimath::pointxyzd(0,5,0)), 25., EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::mag2(minimath::pointxyzd(0,0,5)), 25., EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::mag2(minimath::pointxyzd(-5,0,5)), 50., EPS));\n}\n\nBOOST_AUTO_TEST_CASE(testDistanceSquared)\n{\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::dist2(minimath::pointxyzd(1,1,1),\n                                                        minimath::pointxyzd(1,1,1)), 0., EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::dist2(minimath::pointxyzd(1,1,1),\n                                                        minimath::pointxyzd(0,0,0)), 3., EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::dist2(minimath::pointxyzd(1,1,0),\n                                                        minimath::pointxyzd(0,0,0)), 2., EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::dist2(minimath::pointxyzd(1,0,1),\n                                                        minimath::pointxyzd(0,0,0)), 2., EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::dist2(minimath::pointxyzd(1,0,0),\n                                                        minimath::pointxyzd(0,0,0)), 1., EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::dist2(minimath::pointxyzd(0,1,0),\n                                                        minimath::pointxyzd(0,0,0)), 1., EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::dist2(minimath::pointxyzd(0,0,1),\n                                                        minimath::pointxyzd(0,0,0)), 1., EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::dist2(minimath::pointxyzd(1,0,0),\n                                                        minimath::pointxyzd(-1,0,0)), 4., EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(minimath::dist2(minimath::pointxyzd(1,1,1),\n                                                        minimath::pointxyzd(-1,-1,-1)), 12., EPS));\n}\n\nBOOST_AUTO_TEST_CASE(testDotProduct)\n{\n  BOOST_CHECK(minimath::compare_with_tolerance(3., minimath::dot(minimath::pointxyzd(1,1,1),\n                                                          minimath::pointxyzd(1,1,1)), EPS));\n  // parallel opposite direction\n  BOOST_CHECK(minimath::compare_with_tolerance(-3., minimath::dot(minimath::pointxyzd(1,1,1),\n                                                           minimath::pointxyzd(-1,-1,-1)), EPS));\n  // orthoginal\n  BOOST_CHECK(minimath::compare_with_tolerance(0., minimath::dot(minimath::pointxyzd(1,0,0),\n                                                          minimath::pointxyzd(0,1,0)), EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(0., minimath::dot(minimath::pointxyzd(1,0,0),\n                                                          minimath::pointxyzd(0,0,1)), EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(0., minimath::dot(minimath::pointxyzd(0,1,0),\n                                                          minimath::pointxyzd(1,0,0)), EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(0., minimath::dot(minimath::pointxyzd(0,1,0),\n                                                          minimath::pointxyzd(0,0,1)), EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(0., minimath::dot(minimath::pointxyzd(0,0,1),\n                                                          minimath::pointxyzd(1,0,0)), EPS));\n  BOOST_CHECK(minimath::compare_with_tolerance(0., minimath::dot(minimath::pointxyzd(0,0,1),\n                                                          minimath::pointxyzd(0,1,0)), EPS));\n}\n\nnamespace\n{\nvoid test_normalize_non_member(int i, int j, int k)\n{\n  using namespace minimath;\n  for (int n = 0; n < 100; ++n)\n  {\n    pointxyzd p(i*std::rand(), j*std::rand(), k*std::rand());\n    pointxyzd::value_type d = std::sqrt(mag2(p));\n    pointxyzd::value_type EPS = std::numeric_limits<minimath::pointxyzd::value_type>::epsilon();\n    p = normalize(p);\n    d = mag2(p);\n    BOOST_CHECK(compare_with_tolerance(d, pointxyzd::value_type(1.), 5.0e-16));\n  }\n}\nvoid test_normalize(int i, int j, int k)\n{\n  using namespace minimath;\n  for (int n = 0; n < 100; ++n)\n  {\n    pointxyzd p(i*std::rand(), j*std::rand(), k*std::rand());\n    pointxyzd::value_type d = std::sqrt(mag2(p));\n    pointxyzd::value_type EPS = std::numeric_limits<minimath::pointxyzd::value_type>::epsilon();\n    BOOST_CHECK(compare_with_tolerance(p.normalize(), d, EPS));\n    std::stringstream ss;\n    ss << \"mag2(p) -1 = \" << mag2(p) - pointxyzd::value_type(1.);\n    ss << \" EPS \" << EPS;\n    d = mag2(p);\n    BOOST_CHECK_MESSAGE(ss.str().c_str(), compare_with_tolerance(d, pointxyzd::value_type(1.), 5.0e-16));\n  }\n}\n}\n\nBOOST_AUTO_TEST_CASE(testNormalize)\n{\n    test_normalize(1, 1, 1);\n    test_normalize(1, 1, -1);\n    test_normalize(1, -1, 1);\n    test_normalize(-1, 1, 1);\n    test_normalize(1, -1, -1);\n    test_normalize(-1, -1, 1);\n    test_normalize(-1, 1, -1);\n    test_normalize(-1, -1, -1);\n}\n\nBOOST_AUTO_TEST_CASE(testNormalizeNonMember)\n{\n    test_normalize_non_member(1, 1, 1);\n    test_normalize_non_member(1, 1, -1);\n    test_normalize_non_member(1, -1, 1);\n    test_normalize_non_member(-1, 1, 1);\n    test_normalize_non_member(1, -1, -1);\n    test_normalize_non_member(-1, -1, 1);\n    test_normalize_non_member(-1, 1, -1);\n    test_normalize_non_member(-1, -1, -1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7f06c0123c378980510aee94ac29a6b2bca1eeb1", "size": 9219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestPoint3D.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/TestPoint3D.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/TestPoint3D.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": 34.9204545455, "max_line_length": 105, "alphanum_fraction": 0.6400911162, "num_tokens": 2798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5276365625317844}}
{"text": "#include \"acrolib/sampling.h\"\n\n#include <Eigen/Core>\n\nnamespace acro\n{\ntemplate <typename SampleType>\nGridSamples<SampleType>::GridSamples(const std::vector<std::vector<double>>& sample_ranges)\n  : sample_ranges_(sample_ranges), n_(sample_ranges.size())\n{\n  for (auto& r : sample_ranges_)\n    sample_range_sizes_.push_back(r.size());\n\n  for (auto& s : sample_range_sizes_)\n    total_sample_count_ *= s;\n}\n\ntemplate <typename SampleType>\nSampleType GridSamples<SampleType>::operator[](std::size_t ind) const\n{\n  SampleType sample(n_);\n  auto s = convertBase(ind, sample_range_sizes_);\n  for (std::size_t dim{ 0 }; dim < n_; ++dim)\n  {\n    sample[dim] = sample_ranges_.at(dim).at(s[dim]);\n  }\n  return sample;\n}\n\ntemplate class GridSamples<Eigen::VectorXd>;\ntemplate class GridSamples<std::vector<double>>;\n\nstd::vector<std::vector<double>> calculateRangesFromLimits(const std::vector<Limits>& limits, double resolution)\n{\n  // calculate the specific sample levels for each dimension\n  std::vector<std::vector<double>> sample_ranges(limits.size());\n  for (size_t k{ 0 }; k < limits.size(); ++k)\n  {\n    double value = limits.at(k).lower;\n    while (value <= limits.at(k).upper)\n    {\n      sample_ranges.at(k).push_back(value);\n      value += resolution;\n    }\n  }\n\n  return sample_ranges;\n}\n\n}  // namespace acro\n", "meta": {"hexsha": "2b476b74105b1a5ce6d10852250c9e2024a6a2ff", "size": 1312, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sampling.cpp", "max_stars_repo_name": "JeroenDM/acrolib_cpp", "max_stars_repo_head_hexsha": "eb27de9df206f42dcd5a5dffecafce6dd4cab33e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sampling.cpp", "max_issues_repo_name": "JeroenDM/acrolib_cpp", "max_issues_repo_head_hexsha": "eb27de9df206f42dcd5a5dffecafce6dd4cab33e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sampling.cpp", "max_forks_repo_name": "JeroenDM/acrolib_cpp", "max_forks_repo_head_hexsha": "eb27de9df206f42dcd5a5dffecafce6dd4cab33e", "max_forks_repo_licenses": ["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.7254901961, "max_line_length": 112, "alphanum_fraction": 0.7004573171, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5276365540736868}}
{"text": "/***************************************************************************\n                          meshalgs.cc  -  description\n                             -------------------\n    begin                : Mon Mar 31 2008\n    copyright            : (C) 2005 by Knut-Helge Vik\n    email                : knuthelv@ifi.uio.no\n ***************************************************************************/\n#include \"meshalgs.h\"\n#include \"../treealgs/treestructure.h\"\n#include \"../simdefs.h\"\n#include \"../treealgs/fheap.h\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/reverse_graph.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <functional>\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\nusing namespace std;\nusing namespace boost;\nusing namespace TreeAlgorithms;\n\n//typedef TreeAlgorithms::COLOR COLOR;\n\nnamespace GraphAlgorithms\n{\n\n// dijkstra's shortest path tree\nvoid maxDistance(const GraphN &g, const VertexSet &V, int src, DistanceVector &zdistance, DistanceVector &hops, ParentVector &zparent, double &eccentricity, int &node_in_eccentricity_path)\n{\n    out_edge_iteratorN oit, oit_end;\n    //enum COLOR { WHITE = 0, GRAY, BLACK};\n    std::vector<TreeAlgorithms::COLOR> colorVector(num_vertices(g));\n\n    HeapD<FHeap> heapD;\n    Heap *heap = heapD.newInstance(num_vertices(g));\n\n    for(VertexSet::iterator vit = V.begin(), vit_end = V.end(); vit != vit_end; ++vit)\n    {\n        zdistance[*vit] = (std::numeric_limits<double>::max)();\n        zparent[*vit] = *vit;\n        hops[*vit] = 0;\n        colorVector[*vit] = WHITE;\n    }\n\n    colorVector[src] = GRAY;\n    zdistance[src] = 0;\n    heap->insert(src, 0.0);\n\n    while(heap->nItems() > 0)\n    {\n        int u = heap->deleteMin();\n        for(boost::tuples::tie(oit, oit_end) = out_edges(u, g); oit != oit_end; ++oit)\n        {\n            int v = target(*oit, g);\n            double path_weight = zdistance[u] + g[*oit].weight;\n\n            if((path_weight < zdistance[v]))\n            {\n                zdistance[v] = path_weight;\n                zparent[v] = u;\n                hops[v] = hops[u] + 1;\n\n                if(colorVector[v] == WHITE)\n                {\n                    colorVector[v] = GRAY;\n                    heap->insert(v, zdistance[v]);\n                }\n                else if(colorVector[v] == GRAY)\n                {\n                    heap->decreaseKey(v, zdistance[v]);\n                }\n\n                if(zdistance[v] >= eccentricity)\n                {\n                    eccentricity = zdistance[v];\n                    node_in_eccentricity_path = v;\n                }\n            }\n        }\n        colorVector[u] = BLACK;\n    }\n    delete heap;\n}\n\nvoid maxDistance(const TreeStructure &T, int src, DistanceVector &zdistance, DistanceVector &hops, ParentVector &zparent, double &eccentricity, int &node_in_eccentricity_path)\n{\n    maxDistance(T.g, T.V, src, zdistance, hops, zparent, eccentricity, node_in_eccentricity_path);\n}\n\n// dijkstra's shortest path tree\nvoid maxDistance(const TreeStructure &T, int src, DistanceVector &zdistance, DistanceVector &hops, ParentVector &zparent)\n{\n    double ecc = 0;\n    int node = -1;\n\n    maxDistance(T, src, zdistance, hops, zparent,ecc, node);\n}\n\ndouble eccentricity_distance(const TreeStructure &T, int src)\n{\n    return eccentricity_distance(T.g, T.V, src);\n}\n\ndouble eccentricity_distance(const GraphN &g, const VertexSet &V, int src)\n{\n    DistanceVector \tdistance(num_vertices(g));\n    DistanceVector \thops(num_vertices(g));\n    ParentVector\tparent(num_vertices(g));\n    double ecc = 0;\n    int node = -1;\n\n    maxDistance(g, V, src, distance, hops, parent, ecc, node);\n\n    return ecc;\n}\n\ndouble eccentricity_distance(const GraphN &g, const VertexSet &V, int src, DistanceVector &distance, DistanceVector &hops, ParentVector &parent)\n{\n    double ecc = 0;\n    int node = -1;\n\n    maxDistance(g, V, src, distance, hops, parent, ecc, node);\n    return ecc;\n}\n\n\n\n// breadth first search tree\nvoid maxDistanceHops(const TreeStructure &T, int src, DistanceVector &distance, DistanceVector &hops, ParentVector &parent)\n{\n    const GraphN &g = T.g;\n    ASSERTING(T.V.contains(src));\n\n    for(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n    {\n        distance[*vit] = (std::numeric_limits<double>::max)();   // set to maximum distance\n        hops[*vit] = (std::numeric_limits<double>::max)();   // set to maximum distance\n        parent[*vit] = *vit;\n    }\n\n    distance[src] = 0;\n    hops[src] = 0;\n    parent[src] = src;\n\n    typedef list<int> IntList;\n    IntList neighbors;\n    neighbors.push_back(src);\n\n    while(!neighbors.empty())\n    {\n        int v = neighbors.front();\n        neighbors.pop_front();\n\n        ASSERTING(T.V.contains(v));\n        out_edge_iteratorN oit, oit_end;\n        for(boost::tuples::tie(oit, oit_end) = out_edges(v, g); oit != oit_end; ++oit)\n        {\n            int u = target(*oit, g);\n            ASSERTING(T.V.contains(u));\n\n            if(hops[u] == (std::numeric_limits<double>::max()))\n            {\n                hops[u] = hops[v] + 1;\n                distance[u] = distance[v] + g[*oit].weight;\n                parent[u] = v;\n                neighbors.push_back(u);\n            }\n        }\n    }\n}\n\n\n// breadth first search tree\ndouble maxDistanceHops(const TreeStructure &T, int src, DistanceVector &distance)\n{\n    const GraphN &g = T.g;\n    ASSERTING(T.V.contains(src));\n\n    for(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n        distance[*vit] = (std::numeric_limits<double>::max)();\n\n    distance[src] = 0;\n    double diameter = 0;\n\n    typedef list<int> IntList;\n    IntList neighbors;\n    neighbors.push_back(src);\n\n    while(!neighbors.empty())\n    {\n        int v = neighbors.front();\n        neighbors.pop_front();\n\n        out_edge_iteratorN oit, oit_end;\n        for(boost::tuples::tie(oit, oit_end) = out_edges(v, g); oit != oit_end; ++oit)\n        {\n            int u = target(*oit, g);\n            ASSERTING(T.V.contains(u));\n\n            if(distance[u] == (std::numeric_limits<double>::max()))\n            {\n                distance[u] = distance[v] + 1;\n                if(distance[u] > diameter) diameter = distance[u];\n\n                neighbors.push_back(u);\n            }\n        }\n    }\n    return diameter;\n}\n\ndouble eccentricity_hops(const TreeStructure &T, int src)\n{\n    DistanceVector \tdistance(num_vertices(T.g));\n\n    return maxDistanceHops(T, src, distance);\n}\n\n\ndouble diameter_hops(const TreeStructure &T)\n{\n    double max = 0;\n    DistanceVector distance(num_vertices(T.g));\n\n    for(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n    {\n        int v = *vit;\n        double d = maxDistanceHops(T, v, distance);\n        max = d > max ? d : max;\n    }\n\n    return max;\n}\n\ndouble diameter_distance(const TreeStructure &T)\n{\n    double diameter = 0;\n    PathList diameterPath;\n    diameter_distance(T, diameterPath, diameter);\n\n    return diameter;\n}\n\n\nvoid diameter_distance(const TreeStructure &T, PathList &diameterPath, double &diameter)\n{\n    DistanceVector \tdistance(num_vertices(T.g));\n    DistanceVector \thops(num_vertices(T.g));\n    ParentVector\tparent(num_vertices(T.g));\n\n    for(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n    {\n        double eccentricity = 0;\n        int node_in_eccentricity_path = -1;\n        int v = *vit;\n        maxDistance(T, v, distance, hops, parent, eccentricity, node_in_eccentricity_path);\n\n        if(diameter < eccentricity)\n        {\n            diameter = eccentricity;\n            diameterPath.clear();\n\n            ASSERTING(node_in_eccentricity_path != v);\n            int path_node = node_in_eccentricity_path;\n            while(path_node != v)\n            {\n                diameterPath.push_back(path_node);\n                path_node = parent[path_node];\n            }\n\n            diameterPath.push_back(v);\n\n            //cerr << WRITE_FUNCTION << \" diameter : \" << diameter << endl;\n        }\n    }\n}\n\n// matrix of the shortest distances between any two vertices.\nvoid distanceMatrix(const TreeStructure &T, DistanceVectorMatrix &distance, DistanceVectorMatrix &hops, ParentVectorMatrix &parent)\n{\n    for(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n    {\n        int v = *vit;\n        maxDistance(T, v, distance[v], hops[v], parent[v]);\n    }\n}\n\nvoid distanceMatrixHops(const TreeStructure &T, DistanceVectorMatrix &distance)\n{\n    for(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n    {\n        int v = *vit;\n        maxDistanceHops(T, v, distance[v]);\n    }\n}\n\nvoid printAllPairsSP(ParentMatrix &parent, int src, int targ, PathList &path)\n{\n    if(src == targ)\n    {\n        cerr << src << \" \";\n        path.push_back(src);\n    }\n    else if(parent[src][targ] == src)\n    {\n        cerr << \" no path from \" << src << \" to \" << targ << \" exists \" << endl;\n    }\n    else\n    {\n        printAllPairsSP(parent, src, parent[src][targ], path);\n        cerr << targ << \" \";\n        path.push_back(targ);\n    }\n}\n\n};\n\n/*\ndouble maxDistanceHops(const TreeStructure &T, int src, DistanceVector &distance)\n{\n    const GraphN &g = T.g;\n    ASSERTING(T.V.contains(src));\n\n    for(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n        distance[*vit] = (std::numeric_limits<double>::max)();   // set to maximum distance\n\n    distance[src] = 0;\n    double depth = 1;                       // next distance in BFS\n    int cnt = 0;\n\n    VertexSet neighborSet;\n    neighborSet.insert(src);\n\n    while(!neighborSet.empty())\n    {\n        VertexSet nextNeighbors;\n        for(VertexSet::iterator vit = neighborSet.begin(), vit_end = neighborSet.end(); vit != vit_end; ++vit)\n        {\n            int v = *vit;\n            out_edge_iteratorN oit, oit_end;\n            ASSERTING(T.V.contains(v));\n\n            for(boost::tuples::tie(oit, oit_end) = out_edges(v, g); oit != oit_end; ++oit)\n            {\n                int u = target(*oit, g);\n                if(distance[u] == (std::numeric_limits<double>::max)()) // first time reachable?\n                {\n                    cnt++;\n                    distance[u] = depth;\n                    nextNeighbors.insert(u);\n                }\n            }\n        }\n        // next try set of vertices further away\n        neighborSet = nextNeighbors;\n        depth++;\n    }\n\n    return cnt == T.V.size() ? depth-1 : T.V.size();\n}\n*/\n\n/*void maxDistance(const TreeStructure &T, int src, DistanceVector &distance, DistanceVector &hops, ParentVector &parent, double &eccentricity, int &node_in_eccentricity_path)\n{\n    const GraphN &g = T.g;\n    ASSERTING(T.V.contains(src));\n\n    for(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n    {\n        distance[*vit] = (std::numeric_limits<double>::max)();   // set to maximum distance\n        hops[*vit] = (std::numeric_limits<double>::max)();   // set to maximum distance\n        parent[*vit] = *vit;\n    }\n\n    distance[src] = 0;\n    hops[src] = 0;\n    parent[src] = src;\n\n    typedef list<int> IntList;\n    IntList neighbors;\n    neighbors.push_back(src);\n\n    while(!neighbors.empty())\n    {\n        int v = neighbors.front();\n        neighbors.pop_front();\n\n        ASSERTING(T.V.contains(v));\n        out_edge_iteratorN oit, oit_end;\n        for(boost::tuples::tie(oit, oit_end) = out_edges(v, g); oit != oit_end; ++oit)\n        {\n            int u = target(*oit, g);\n            ASSERTING(T.V.contains(u));\n\n            if(distance[u] > distance[v] + g[*oit].weight)\n            {\n                hops[u] = hops[v] + 1;\n                distance[u] = distance[v] + g[*oit].weight;\n                parent[u] = v;\n                neighbors.push_back(u);\n\n                if(distance[u] >= eccentricity)\n                {\n                    eccentricity = distance[u];\n                    node_in_eccentricity_path = u;\n                }\n                //cerr << u << \" hops \" << hops[u] << \" distance \" << distance[u] << \" parent \" << parent[u] << endl;\n            }\n        }\n    }\n}*/\n\n", "meta": {"hexsha": "9da4f8bf246d031f8dc301ebc2a22262ca1e4c25", "size": 12178, "ext": "cc", "lang": "C++", "max_stars_repo_path": "GraphLib/graphalgs/meshalgs.cc", "max_stars_repo_name": "intact-software-systems/cpp-software-patterns", "max_stars_repo_head_hexsha": "e463fc7eeba4946b365b5f0b2eecf3da0f4c895b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-03T07:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-03T07:23:11.000Z", "max_issues_repo_path": "GraphLib/graphalgs/meshalgs.cc", "max_issues_repo_name": "intact-software-systems/cpp-software-patterns", "max_issues_repo_head_hexsha": "e463fc7eeba4946b365b5f0b2eecf3da0f4c895b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GraphLib/graphalgs/meshalgs.cc", "max_forks_repo_name": "intact-software-systems/cpp-software-patterns", "max_forks_repo_head_hexsha": "e463fc7eeba4946b365b5f0b2eecf3da0f4c895b", "max_forks_repo_licenses": ["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.2740384615, "max_line_length": 188, "alphanum_fraction": 0.5608474298, "num_tokens": 3010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5276042795368728}}
{"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_SQRT1PM1_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SQRT1PM1_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-arithmetic\n    This function object returns \\f$\\sqrt{1+x}-1\\f$ and the\n    result is accurate even for x  with small modulus\n\n    @see log1p, expm1.\n\n\n    @par Header <boost/simd/function/sqrt1pm1.hpp>\n\n    @par Example:\n\n      @snippet sqrt1pm1.cpp sqrt1pm1\n\n    @par Possible output:\n\n      @snippet sqrt1pm1.txt sqrt1pm1\n  **/\n  IEEEValue sqrt1pm1(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sqrt1pm1.hpp>\n#include <boost/simd/function/simd/sqrt1pm1.hpp>\n\n#endif\n", "meta": {"hexsha": "1a910ddbf1aa4fa46b23c1634fa1d2fdcf91b21f", "size": 1075, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sqrt1pm1.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/function/sqrt1pm1.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/function/sqrt1pm1.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": 23.8888888889, "max_line_length": 100, "alphanum_fraction": 0.5888372093, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5276042741104953}}
{"text": "/**\n * @file cmaes_test.cpp\n * @author Marcus Edel\n * @author Kartik Nighania\n *\n * Test file for CMA-ES.\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/optimizers/cmaes/cmaes.hpp>\n#include <mlpack/core/optimizers/problems/sgd_test_function.hpp>\n#include <mlpack/methods/logistic_regression/logistic_regression.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace arma;\nusing namespace mlpack::optimization;\nusing namespace mlpack::optimization::test;\n\nusing namespace mlpack::distribution;\nusing namespace mlpack::regression;\n\nusing namespace mlpack;\n\nBOOST_AUTO_TEST_SUITE(CMAESTest);\n\n/**\n * Tests the CMA-ES optimizer using a simple test function.\n */\nBOOST_AUTO_TEST_CASE(SimpleTestFunction)\n{\n  SGDTestFunction f;\n  CMAES<> optimizer(0, -1, 1, 32, 200, -1);\n\n  arma::mat coordinates = f.GetInitialPoint();\n  optimizer.Optimize(f, coordinates);\n\n  BOOST_REQUIRE_SMALL(coordinates[0], 0.003);\n  BOOST_REQUIRE_SMALL(coordinates[1], 0.003);\n  BOOST_REQUIRE_SMALL(coordinates[2], 0.003);\n}\n\n/**\n * Create the data for the logistic regression test case.\n */\nvoid CreateLogisticRegressionTestData(arma::mat& data,\n                                      arma::mat& testData,\n                                      arma::mat& shuffledData,\n                                      arma::Row<size_t>& responses,\n                                      arma::Row<size_t>& testResponses,\n                                      arma::Row<size_t>& shuffledResponses)\n{\n  // Generate a two-Gaussian dataset.\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  data = arma::mat(3, 1000);\n  responses = arma::Row<size_t>(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  // Shuffle the dataset.\n  arma::uvec indices = arma::shuffle(arma::linspace<arma::uvec>(0,\n      data.n_cols - 1, data.n_cols));\n  shuffledData = arma::mat(3, 1000);\n  shuffledResponses = arma::Row<size_t>(1000);\n  for (size_t i = 0; i < data.n_cols; ++i)\n  {\n    shuffledData.col(i) = data.col(indices[i]);\n    shuffledResponses[i] = responses[indices[i]];\n  }\n\n  // Create a test set.\n  testData = arma::mat(3, 1000);\n  testResponses = arma::Row<size_t>(1000);\n  for (size_t i = 0; i < 500; ++i)\n  {\n    testData.col(i) = g1.Random();\n    testResponses[i] = 0;\n  }\n  for (size_t i = 500; i < 1000; ++i)\n  {\n    testData.col(i) = g2.Random();\n    testResponses[i] = 1;\n  }\n}\n\n/**\n * Run CMA-ES with the full selection policy on logistic regression and\n * make sure the results are acceptable.\n */\nBOOST_AUTO_TEST_CASE(CMAESLogisticRegressionTest)\n{\n  const size_t trials = 3;\n  bool success = false;\n  for (size_t trial = 0; trial < trials; ++trial)\n  {\n    arma::mat data, testData, shuffledData;\n    arma::Row<size_t> responses, testResponses, shuffledResponses;\n\n    CreateLogisticRegressionTestData(data, testData, shuffledData,\n        responses, testResponses, shuffledResponses);\n\n    CMAES<> cmaes(0, -1, 1, 32, 200, 1e-3);\n    LogisticRegression<> lr(shuffledData, shuffledResponses, cmaes, 0.5);\n\n    // Ensure that the error is close to zero.\n    const double acc = lr.ComputeAccuracy(data, responses);\n    const double testAcc = lr.ComputeAccuracy(testData, testResponses);\n    if (acc >= 99.7 && testAcc >= 99.4)\n    {\n      success = true;\n      break;\n    }\n  }\n\n  BOOST_REQUIRE_EQUAL(success, true);\n}\n\n/**\n * Run CMA-ES with the random selection policy on logistic regression and\n * make sure the results are acceptable.\n */\nBOOST_AUTO_TEST_CASE(ApproxCMAESLogisticRegressionTest)\n{\n  const size_t trials = 3;\n  bool success = false;\n  for (size_t trial = 0; trial < trials; ++trial)\n  {\n    arma::mat data, testData, shuffledData;\n    arma::Row<size_t> responses, testResponses, shuffledResponses;\n\n    CreateLogisticRegressionTestData(data, testData, shuffledData,\n        responses, testResponses, shuffledResponses);\n\n    ApproxCMAES<> cmaes(0, -1, 1, 32, 200, 1e-3);\n    LogisticRegression<> lr(shuffledData, shuffledResponses, cmaes, 0.5);\n\n    // Ensure that the error is close to zero.\n    const double acc = lr.ComputeAccuracy(data, responses);\n    const double testAcc = lr.ComputeAccuracy(testData, testResponses);\n    if (acc >= 99.7 && testAcc >= 99.4)\n    {\n      success = true;\n      break;\n    }\n  }\n\n  BOOST_REQUIRE_EQUAL(success, true);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "ef6b9778e197f851c62fdde7931e4f85542cdf1c", "size": 4853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/cmaes_test.cpp", "max_stars_repo_name": "chigur/mlpack", "max_stars_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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/cmaes_test.cpp", "max_issues_repo_name": "chigur/mlpack", "max_issues_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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/cmaes_test.cpp", "max_forks_repo_name": "chigur/mlpack", "max_forks_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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.234939759, "max_line_length": 80, "alphanum_fraction": 0.6595920049, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5276042693701538}}
{"text": "/* Copyright (C) 2012-2019 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>\n#include <NTL/ZZ_p.h>\n#include <helib/EncryptedArray.h>\n#include <helib/polyEval.h>\n#include <helib/debugging.h>\n\nnamespace helib {\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(NTL::ZZX& result, long p, long e)\n{\n  if (p<2 || e<=1) return; // nothing to do\n  FHE_TIMER_START;\n  long p2e = NTL::power_long(p,e); // the integer p^e\n\n  // Compute x - x^p (mod p^e), for x=0,1,...,p-1\n  NTL::vec_long x(NTL::INIT_SIZE, p);\n  NTL::vec_long y(NTL::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-NTL::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  //OLD: assert(deg(result)<p); // interpolating p points, should get deg<=p-1\n  helib::assertTrue(deg(result)<p, \"Interpolation error - degree too high\");\n  SetCoeff(result, p);   // return result = x^p + poly'(x)\n  //  cerr << \"# digitExt mod \"<<p<<\"^\"<<e<<\"=\"<<result<<endl;\n  FHE_TIMER_STOP;\n}\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. The plaintext space of digits[j] is mod p^{r-j},\n// and all the digits are at the same level.\n\nint fhe_watcher = 0;\n\nvoid extractDigits(std::vector<Ctxt>& digits, const Ctxt& c, long r)\n{\n  const Context& context = 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\n  NTL::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\n#ifdef DEBUG_PRINTOUT\n  fprintf(stderr, \"***\\n\");\n#endif\n  for (long i=0; i<r; i++) {\n    tmp = c;\n    for (long j=0; j<i; j++) {\n\n      if (p==2) digits[j].square();\n      else if (p==3) digits[j].cube();\n      else polyEval(digits[j], x2p, digits[j]); \n      // \"in spirit\" digits[j] = digits[j]^p\n\n#ifdef DEBUG_PRINTOUT\n      fprintf(stderr, \"%5ld\", digits[j].bitCapacity());\n#endif\n\n      tmp -= digits[j];\n      tmp.divideByP();\n    }\n    digits[i] = tmp; // needed in the next round\n\n#ifdef DEBUG_PRINTOUT\n    if (dbgKey) {\n       double ratio = \n          log(embeddingLargestCoeff(digits[i], *dbgKey)/digits[i].getNoiseBound())/log(2.0);\n       fprintf(stderr, \"%5ld [%f]\", digits[i].bitCapacity(), ratio);\n       if (ratio > 0) fprintf(stderr, \" BAD-BOUND\");\n       fprintf(stderr, \"\\n\");\n    }\n    else {\n       fprintf(stderr, \"%5ld\\n\", digits[i].bitCapacity());\n    }\n#endif\n  }\n\n#ifdef DEBUG_PRINTOUT\n  fprintf(stderr, \"***\\n\");\n#endif\n}\n\n\n\nstatic\nvoid compute_a_vals(NTL::Vec<NTL::ZZ>& 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   NTL::ZZ p_to_e = NTL::power_ZZ(p, e);\n   NTL::ZZ p_to_2e = NTL::power_ZZ(p, 2*e);\n\n   long len = (e-1)*(p-1)+2;\n\n   NTL::ZZ_pPush push(p_to_2e);\n\n   NTL::ZZ_pX x_plus_1_to_p = power(NTL::ZZ_pX(NTL::INIT_MONO, 1) + 1, p);\n   NTL::ZZ_pX denom = InvTrunc(x_plus_1_to_p - NTL::ZZ_pX(NTL::INIT_MONO, p), len);\n   NTL::ZZ_pX poly = MulTrunc(x_plus_1_to_p, denom, len);\n   poly *= p;\n\n   a.SetLength(len);\n\n   NTL::ZZ 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      NTL::ZZ c = rep(coeff(poly, m));\n      NTL::ZZ d = GCD(m_fac, p_to_2e);\n      if (d == 0 || d > p_to_e || c % d != 0) throw helib::RuntimeError(\"cannot divide\");\n      NTL::ZZ m_fac_deflated = (m_fac / d) % p_to_e;\n      NTL::ZZ 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\n// This computes Chen and Han's magic polynomial G, which \n// has the property that G(x) = (x mod p) (mod p^e).\n// Here, (x mod p) is in the interval [0,1] if p == 2,\n// and otherwise, is in the interval (-p/2, p/2).\nstatic\nvoid compute_magic_poly(NTL::ZZX& poly1, long p, long e)\n{\n   FHE_TIMER_START;\n\n   NTL::Vec<NTL::ZZ> a;\n\n   compute_a_vals(a, p, e);\n\n   NTL::ZZ p_to_e = NTL::power_ZZ(p, e);\n   long len = (e-1)*(p-1)+2;\n\n   NTL::ZZ_pPush push(p_to_e);\n\n   NTL::ZZ_pX poly(0);\n   NTL::ZZ_pX term(1);\n   NTL::ZZ_pX X(NTL::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 * NTL::conv<NTL::ZZ_p>(a[m]);\n      term *= (X-m);\n   }\n\n   // replace poly by poly(X+(p-1)/2) for odd p\n   if (p % 2 == 1) {\n      NTL::ZZ_pX poly2(0);\n\n      for (long i = deg(poly); i >= 0; i--) \n         poly2 = poly2*(X+(p-1)/2) + poly[i];\n\n      poly = poly2;\n   }\n\n   poly = X - poly;\n   poly1 = NTL::conv<NTL::ZZX>(poly);\n}\n\n\n// extendExtractDigits assumes that the slots of *this contains integers mod\n// p^{r+e} i.e., that only the free terms are nonzero. (If that assumptions\n// does 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 digits 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 i'th\n// slot of the *this.  The plaintext space of digits[j] is mod p^{e+r-j}.\n\nvoid extendExtractDigits(std::vector<Ctxt>& digits, const Ctxt& c, long r, long e)\n{\n  const Context& context = c.getContext();\n\n  long p = context.zMStar.getP();\n  NTL::ZZX x2p;\n  if (p>3) { \n    buildDigitPolynomial(x2p, p, r);\n  }\n\n  // we should pre-compute this table\n  // for i = 0..r-1, entry i is G_{e+r-i} in Chen and Han\n  NTL::Vec<NTL::ZZX> G;\n  G.SetLength(r);\n  for (long i: range(r)) {\n    compute_magic_poly(G[i], p, e+r-i);\n  }\n\n  std::vector<Ctxt> digits0;\n\n  Ctxt tmp(c.getPubKey(), c.getPtxtSpace());\n\n  digits.resize(r, tmp);      // allocate space\n  digits0.resize(r, tmp);\n\n#ifdef DEBUG_PRINTOUT\n  fprintf(stderr, \"***\\n\");\n#endif\n  for (long i: range(r)) {\n    tmp = c;\n    for (long j: range(i)) {\n      if (digits[j].capacity() >= digits0[j].capacity()) {\n         // optimization: digits[j] is better than digits0[j],\n         // so just use it\n\n         tmp -= digits[j];\n#ifdef DEBUG_PRINTOUT\n      fprintf(stderr, \"%5ld*\", digits[j].bitCapacity());\n#endif\n      }\n      else {\n\tif (p==2) digits0[j].square();\n\telse if (p==3) digits0[j].cube();\n\telse polyEval(digits0[j], x2p, digits0[j]); // \"in spirit\" digits0[j] = digits0[j]^p\n\n\ttmp -= digits0[j];\n#ifdef DEBUG_PRINTOUT\n      fprintf(stderr, \"%5ld \", digits0[j].bitCapacity());\n#endif\n      }\n      tmp.divideByP();\n    }\n    digits0[i] = tmp; // needed in the next round\n    polyEval(digits[i], G[i], tmp);\n\n#ifdef DEBUG_PRINTOUT\n    if (dbgKey) {\n      double ratio = \n        log(embeddingLargestCoeff(digits[i], *dbgKey)/digits[i].getNoiseBound())/log(2.0);\n      fprintf(stderr, \"%5ld  --- %5ld\", digits0[i].bitCapacity(), digits[i].bitCapacity());\n      fprintf(stderr, \" [%f]\", ratio);\n      if (ratio > 0) fprintf(stderr, \" BAD-BOUND\");\n      fprintf(stderr, \"\\n\");\n    }\n    else {\n      fprintf(stderr, \"%5ld  --- %5ld\\n\", digits0[i].bitCapacity(), digits[i].bitCapacity());\n    }\n#endif\n  }\n}\n\n}\n", "meta": {"hexsha": "7974dea62be132fa19213cf558aee9c05bb7973d", "size": 8608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/extractDigits.cpp", "max_stars_repo_name": "lparth/homeenc-HElib", "max_stars_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-06T09:26:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T09:26:23.000Z", "max_issues_repo_path": "src/extractDigits.cpp", "max_issues_repo_name": "lparth/homeenc-HElib", "max_issues_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "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": "lparth/homeenc-HElib", "max_forks_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-18T14:03:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T14:03:29.000Z", "avg_line_length": 29.3788395904, "max_line_length": 93, "alphanum_fraction": 0.6045539033, "num_tokens": 2848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5276042625717039}}
{"text": "static char help[] = \"A character array that PETSc might be expecting\";\r\n#include <petscksp.h>\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <math.h>\r\n#include <string>\r\n\r\n#include \"Input_Reader.h\"\r\n#include \"Materials.h\"\r\n#include \"Fem_Quadrature.h\"\r\n#include \"Quadrule_New.h\"\r\n#include \"Cell_Data.h\"\r\n#include \"Angular_Quadrature.h\"\r\n#include \"Time_Data.h\"\r\n#include \"Temperature_Data.h\"\r\n\r\n#include <Eigen/Dense>\r\n#include \"Diffusion_Operator.h\"\r\n\r\n#include \"Dark_Arts_Exception.h\"\r\n\r\n/**\r\n  Goal of this unit test is to check source moment formation, and reaction matrix for SLXS Lobatto scheme\r\n  -This is a MMS problem with a spatially varying sigma_a, constant cv , zero sig_s\r\n*/ \r\n\r\nint main(int argc, char** argv)\r\n{  \r\n  /// change to -1 if you want ctest to dump this output.  Otherwise this test passes always\r\n  int val = 0;\r\n  PetscErrorCode ierr;  \r\n  PetscMPIInt size;\r\n  \r\n  PetscInitialize(&argc,&argv,(char*)0,help);\r\n  ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);\r\n  CHKERRQ(ierr);\r\n  if (size != 1) \r\n    SETERRQ(PETSC_COMM_WORLD,1,\"DARK_ARTS is written to be serial only!\");\r\n      \r\n  \r\n  Input_Reader input_reader;    \r\n  try\r\n  {\r\n    input_reader.read_xml(argv[1]);\r\n  }\r\n  catch(const Dark_Arts_Exception& da_exception )\r\n  {\r\n    da_exception.message() ;\r\n    val = -1;\r\n  }       \r\n  \r\n  /// Initialize a Quadrule object to be able to get all of the quadrature we need\r\n  Quadrule_New quad_fun;  \r\n  Fem_Quadrature fem_quadrature( input_reader , quad_fun);  \r\n  Cell_Data cell_data( input_reader );  \r\n  Angular_Quadrature angular_quadrature( input_reader , quad_fun );    \r\n    \r\n  /// Create a Materials object that contains all opacity, heat capacity, and source objects\r\n    Materials materials( input_reader, fem_quadrature , cell_data, angular_quadrature );  \r\n    Time_Data time_data(input_reader);\r\n    Temperature_Data t_old(fem_quadrature, input_reader, cell_data);      \r\n\r\n    const double dt = time_data.get_dt_max();\r\n    const double time_stage = dt + time_data.get_t_start();\r\n    double rk_a_ii = 1.;\r\n\r\n    const int n_p = fem_quadrature.get_number_of_interpolation_points() ;\r\n  try{\r\n    Diffusion_Operator diffusion_operator(input_reader, fem_quadrature, cell_data, \r\n      materials, angular_quadrature, 1,t_old, true,1.0E-20, 1.0E-10 , 2.);\r\n      \r\n    diffusion_operator.set_time_data(dt, time_stage, rk_a_ii);\r\n    \r\n    diffusion_operator.dump_matrix();\r\n        \r\n    std::vector<double> ref_norm(1,0.);\r\n    Intensity_Moment_Data phi_old(cell_data, angular_quadrature, fem_quadrature, ref_norm);  \r\n    Intensity_Moment_Data phi_new(phi_old);\r\n    \r\n    Eigen::VectorXd phi_old_vec = Eigen::VectorXd::Zero(n_p);\r\n    Eigen::VectorXd phi_new_vec = Eigen::VectorXd::Zero(n_p);\r\n    for(int el = 0; el < n_p ;el++)\r\n    {\r\n        phi_old_vec(el) = 0.1;\r\n        phi_new_vec(el) = 0.7;\r\n    }\r\n    \r\n    for(int i = 0 ; i < cell_data.get_total_number_of_cells() ; i++)\r\n    {\r\n      phi_old.set_cell_angle_integrated_intensity(i,0,0,phi_old_vec);\r\n      phi_new.set_cell_angle_integrated_intensity(i,0,0,phi_new_vec);\r\n    }\r\n    \r\n    // diffusion_operator.make_and_dump_rhs(phi_new , phi_old);\r\n    \r\n    std::cout << \"Update follows\\n\" << std::endl;\r\n    diffusion_operator.after_rhs_solve_system_and_dump_solution();\r\n    \r\n    double sig_a = 4.0;\r\n    double sig_s = 1.0;\r\n    double sum_sn_w = 2.;\r\n    double c_speed = 1.;\r\n    double cv = 0.5;\r\n    double temp = 0.1*(1.0);\r\n    double d_planck = 4.*pow(temp,3)/sum_sn_w;\r\n    double pseudo_sig_t = 1./(rk_a_ii*dt*c_speed) + sig_a + sig_s;\r\n    \r\n    double value = sum_sn_w*rk_a_ii*dt*sig_a*d_planck;\r\n    double nu = value/(cv + value);\r\n    double pseudo_sig_s = sig_s + nu*sig_a;\r\n    \r\n    std::cout << \"Pseudo sig_s: \" << pseudo_sig_s << std::endl;\r\n    std::cout << \"Pseudp sig_t: \" << pseudo_sig_t << std::endl;\r\n      \r\n      \r\n  }\r\n  catch(const Dark_Arts_Exception& da)\r\n  {\r\n    val = -1;\r\n    da.testing_message();\r\n  }\r\n  ierr = PetscFinalize();\r\n  return val;\r\n}\r\n", "meta": {"hexsha": "2ab70e27f522fe21b429f5364e9df102dd2c5284", "size": 4000, "ext": "cc", "lang": "C++", "max_stars_repo_path": "testing/mip/MIP_Matrix_Assembly.cc", "max_stars_repo_name": "pgmaginot/DARK_ARTS", "max_stars_repo_head_hexsha": "f04b0a30dcac911ef06fe0916921020826f5c42b", "max_stars_repo_licenses": ["MIT"], "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/mip/MIP_Matrix_Assembly.cc", "max_issues_repo_name": "pgmaginot/DARK_ARTS", "max_issues_repo_head_hexsha": "f04b0a30dcac911ef06fe0916921020826f5c42b", "max_issues_repo_licenses": ["MIT"], "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/mip/MIP_Matrix_Assembly.cc", "max_forks_repo_name": "pgmaginot/DARK_ARTS", "max_forks_repo_head_hexsha": "f04b0a30dcac911ef06fe0916921020826f5c42b", "max_forks_repo_licenses": ["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.746031746, "max_line_length": 106, "alphanum_fraction": 0.662, "num_tokens": 1081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5275501596010937}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/pow.hpp>\n#include <boost/simd/function/std.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/eight.hpp>\n#include <boost/simd/constant/third.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/function/is_negative.hpp>\n#include <boost/simd/function/is_positive.hpp>\n\nSTF_CASE_TPL(\"pow std\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::pow;\n  using r_t =  decltype(pow(T(), T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(bs::std_(pow)(bs::Inf<T>(), bs::Inf<T>()), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(pow)(bs::Nan<T>(), bs::Nan<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(pow)(bs::Minf<T>(), bs::Minf<T>()), bs::Zero<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(pow)(bs::Inf<T>(), bs::Minf<T>()), bs::Zero<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(bs::std_(pow)(T(-1),T(6)), T(1), 0);\n  STF_ULP_EQUAL(bs::std_(pow)(bs::Mone<T>(), bs::Mone<T>()), bs::Mone<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(pow)(bs::One<T>(), bs::One<T>()), bs::One<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(pow)(bs::Zero<T>(), bs::Zero<T>()), bs::One<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(pow)(T(-1),T(5)), T(-1), 0);\n  STF_ULP_EQUAL(bs::std_(pow)(bs::Zero<T>(), bs::One<T>()), bs::Zero<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(pow)(T(8),bs::Third<T>()), r_t(2), 0.5);\n}\n", "meta": {"hexsha": "5b452c75333ce8b4036788e24a08452c507f8e1d", "size": 2097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/pow.std.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/scalar/pow.std.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/pow.std.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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": 41.1176470588, "max_line_length": 100, "alphanum_fraction": 0.5999046257, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5275501596010937}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*!\n Copyright (C) 2016 Andres Hernandez\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 <ql/qldefines.hpp>\n#ifdef BOOST_MSVC\n#  include <ql/auto_link.hpp>\n#endif\n#include <ql/math/optimization/differentialevolution.hpp>\n#include <ql/math/optimization/simulatedannealing.hpp>\n#include <ql/experimental/math/fireflyalgorithm.hpp>\n#include <ql/experimental/math/hybridsimulatedannealing.hpp>\n#include <ql/experimental/math/particleswarmoptimization.hpp>\n#include <ql/functional.hpp>\n\n#include <boost/timer.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing namespace QuantLib;\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib {\n\n    Integer sessionId() { return 0; }\n\n}\n#endif\n\nunsigned long seed = 127;\n\n/*\n    Some benchmark functions taken from\n    https://en.wikipedia.org/wiki/Test_functions_for_optimization\n\n    Global optimizers have generally a lot of hyper-parameters, and one\n    * usually requires some hyper-parameter optimization to find appropriate values\n*/\n\nReal ackley(const Array& x) {\n    //Minimum is found at 0\n    Real p1 = 0.0, p2 = 0.0;\n\n    for (Size i = 0; i < x.size(); i++) {\n        p1 += x[i] * x[i];\n        p2 += std::cos(M_TWOPI*x[i]);\n    }\n    p1 = -0.2*std::sqrt(0.5*p1);\n    p2 *= 0.5;\n    return M_E + 20.0 - 20.0*std::exp(p1)-std::exp(p2);\n}\n\nDisposable<Array> ackleyValues(const Array& x) {\n    Array y(x.size());\n    for (Size i = 0; i < x.size(); i++) {\n        Real p1 = x[i] * x[i];\n        p1 = -0.2*std::sqrt(0.5*p1);\n        Real p2 = 0.5*std::cos(M_TWOPI*x[i]);\n        y[i] = M_E + 20.0 - 20.0*std::exp(p1)-std::exp(p2);\n    }\n    return y;\n}\n\nReal sphere(const Array& x) {\n    //Minimum is found at 0\n    return DotProduct(x, x);\n}\n\nDisposable<Array> sphereValues(const Array& x) {\n    Array y(x.size());\n    for (Size i = 0; i < x.size(); i++) {\n        y[i] = x[i]*x[i];\n    }\n    return y;\n}\n\nReal rosenbrock(const Array& x) {\n    //Minimum is found at f(1, 1, ...)\n    QL_REQUIRE(x.size() > 1, \"Input size needs to be higher than 1\");\n    Real result = 0.0;\n    for (Size i = 0; i < x.size() - 1; i++) {\n        Real temp = (x[i + 1] - x[i] * x[i]);\n        result += (x[i] - 1.0)*(x[i] - 1.0) + 100.0*temp*temp;\n    }\n    return result;\n}\n\nReal easom(const Array& x) {\n    //Minimum is found at f(\\pi, \\pi, ...)\n    Real p1 = 1.0, p2 = 0.0;\n    for (Size i = 0; i < x.size(); i++) {\n        p1 *= std::cos(x[i]);\n        p2 += (x[i] - M_PI)*(x[i] - M_PI);\n    }\n    return -p1*std::exp(-p2);\n}\n\nDisposable<Array> easomValues(const Array& x) {\n    Array y(x.size());\n    for (Size i = 0; i < x.size(); i++) {\n        Real p1 = std::cos(x[i]);\n        Real p2 = (x[i] - M_PI)*(x[i] - M_PI);\n        y[i] = -p1*std::exp(-p2);\n    }\n    return y;\n}\n\nReal eggholder(const Array& x) {\n    //Minimum is found at f(512, 404.2319)\n    QL_REQUIRE(x.size() == 2, \"Input size needs to be equal to 2\");\n    Real p = (x[1] + 47.0);\n    return -p*std::sin(std::sqrt(std::abs(0.5*x[0] + p))) -\n        x[0] * std::sin(std::sqrt(std::abs(x[0] - p)));\n}\n\nReal printFunction(Problem& p, const Array& x) {\n    std::cout << \" f(\" << x[0];\n    for (Size i = 1; i < x.size(); i++) {\n        std::cout << \", \" << x[i];\n    }\n    Real val = p.value(x);\n    std::cout << \") = \" << val << std::endl;\n    return val;\n}\n\nclass TestFunction : public CostFunction {\npublic:\n    typedef ext::function<Real(const Array&)> RealFunc;\n    typedef ext::function<Disposable<Array>(const Array&)> ArrayFunc;\n    TestFunction(const RealFunc & f, const ArrayFunc & fs = ArrayFunc()) : f_(f), fs_(fs) {}\n    TestFunction(Real(*f)(const Array&), Disposable<Array>(*fs)(const Array&) = NULL) : f_(f), fs_(fs) {}\n    virtual ~TestFunction(){}\n    virtual Real value(const Array& x) const {\n        return f_(x);\n    }\n    virtual Disposable<Array> values(const Array& x) const {\n        if(!fs_)\n            throw std::runtime_error(\"Invalid function\");\n        return fs_(x);\n    }\nprivate:\n    RealFunc f_;\n    ArrayFunc fs_;\n};\n\nint test(OptimizationMethod& method, CostFunction& f, const EndCriteria& endCriteria,\n          const Array& start, const Constraint& constraint = Constraint(),\n          const Array& optimum = Array()) {\n    QL_REQUIRE(start.size() > 0, \"Input size needs to be at least 1\");\n    std::cout << \"Starting point: \";\n    Constraint c;\n    if (!constraint.empty())\n        c = constraint;\n    Problem p(f, c, start);\n    printFunction(p, start);\n    method.minimize(p, endCriteria);\n    std::cout << \"End point: \";\n    Real val = printFunction(p, p.currentValue());\n    if(!optimum.empty())\n    {\n        std::cout << \"Global optimium: \";\n        Real optimVal = printFunction(p, optimum);\n        if(std::abs(optimVal) < 1e-13)\n            return std::abs(val-optimVal) < 1e-6;\n        else\n            return std::abs((val-optimVal)/optimVal) < 1e-6;\n    }\n    return 1;\n}\n\nvoid testFirefly() {\n    /*\n    The Eggholder function is only in 2 dimensions, it has a multitude\n    * of local minima, and they are not symmetric necessarily\n    */\n    Size n = 2;\n    NonhomogeneousBoundaryConstraint constraint(Array(n, -512.0), Array(n, 512.0));\n    Array x(n, 0.0);\n    Array optimum(n);\n    optimum[0] = 512.0;\n    optimum[1] = 404.2319;\n    Size agents = 150;\n    Real vola = 1.5;\n    Real intense = 1.0;\n    ext::shared_ptr<FireflyAlgorithm::Intensity> intensity =\n        ext::make_shared<ExponentialIntensity>(10.0, 1e-8, intense);\n    ext::shared_ptr<FireflyAlgorithm::RandomWalk> randomWalk =\n        ext::make_shared<LevyFlightWalk>(vola, 0.5, 1.0, seed);\n    std::cout << \"Function eggholder, Agents: \" << agents\n            << \", Vola: \" << vola << \", Intensity: \" << intense << std::endl;\n    TestFunction f(eggholder);\n    FireflyAlgorithm fa(agents, intensity, randomWalk, 40);\n    EndCriteria ec(5000, 1000, 1.0e-8, 1.0e-8, 1.0e-8);\n    test(fa, f, ec, x, constraint, optimum);\n    std::cout << \"================================================================\" << std::endl;\n}\n\nvoid testSimulatedAnnealing(Size dimension, Size maxSteps, Size staticSteps){\n\n    /*The ackley function has a large amount of local minima, but the\n      structure is symmetric, so if one could simply just ignore the\n      walls separating the local minima, it would look like almost\n      like a parabola\n\n      Andres Hernandez: I could not find a configuration that was able\n      to fix the problem\n    */\n\n    //global minimum is at 0.0\n    TestFunction f(ackley, ackleyValues);\n\n    //Starting point\n    Array x(dimension, 1.5);\n    Array optimum(dimension, 0.0);\n\n    //Constraint for local optimizer\n    Array lower(dimension, -5.0);\n    Array upper(dimension, 5.0);\n    NonhomogeneousBoundaryConstraint constraint(lower, upper);\n\n    Real lambda = 0.1;\n    Real temperature = 350;\n    Real epsilon = 0.99;\n    Size ms = 1000;\n    std::cout << \"Function ackley, Lambda: \" << lambda\n            << \", Temperature: \" << temperature\n            << \", Epsilon: \" << epsilon\n            << \", Iterations: \" << ms\n            << std::endl;\n\n    MersenneTwisterUniformRng rng(seed);\n    SimulatedAnnealing<MersenneTwisterUniformRng> sa(lambda, temperature, epsilon, ms, rng);\n    EndCriteria ec(maxSteps, staticSteps, 1.0e-8, 1.0e-8, 1.0e-8);\n    test(sa, f, ec, x, constraint, optimum);\n    std::cout << \"================================================================\" << std::endl;\n}\n\nvoid testGaussianSA(Size dimension, Size maxSteps, Size staticSteps, Real initialTemp,\n                    Real finalTemp,\n                    GaussianSimulatedAnnealing::ResetScheme resetScheme = GaussianSimulatedAnnealing::ResetToBestPoint,\n                    Size resetSteps = 150,\n                    GaussianSimulatedAnnealing::LocalOptimizeScheme optimizeScheme = GaussianSimulatedAnnealing::EveryBestPoint,\n                    ext::shared_ptr<OptimizationMethod> localOptimizer = ext::make_shared<LevenbergMarquardt>()){\n\n    /*The ackley function has a large amount of local minima, but the\n     * structure is symmetric, so if one could simply just ignore the\n     * walls separating the local minima, it would look like almost like\n     * a parabola*/\n\n    //global minimum is at 0.0\n    TestFunction f(ackley, ackleyValues);\n\n    std::cout << \"Function: ackley, Dimensions: \" << dimension\n              << \", Initial temp:\" << initialTemp\n              << \", Final temp:\" << finalTemp\n              << \", Reset scheme:\" << resetScheme\n              << \", Reset steps:\" << resetSteps\n              << std::endl;\n    //Starting point\n    Array x(dimension, 1.5);\n    Array optimum(dimension, 0.0);\n\n    //Constraint for local optimizer\n    Array lower(dimension, -5.0);\n    Array upper(dimension, 5.0);\n    NonhomogeneousBoundaryConstraint constraint(lower, upper);\n\n    //Simulated annealing setup\n    SamplerGaussian sampler(seed);\n    ProbabilityBoltzmannDownhill probability(seed);\n    TemperatureExponential temperature(initialTemp, dimension);\n    GaussianSimulatedAnnealing sa(sampler, probability, temperature, ReannealingTrivial(),\n                                  initialTemp, finalTemp, 50, resetScheme,\n                                  resetSteps, localOptimizer,\n                                  optimizeScheme);\n\n    EndCriteria ec(maxSteps, staticSteps, 1.0e-8, 1.0e-8, 1.0e-8);\n    test(sa, f, ec, x, constraint, optimum);\n    std::cout << \"================================================================\" << std::endl;\n}\n\nvoid testPSO(Size n){\n    /*The Rosenbrock function has a global minima at (1.0, ...) and a local minima at (-1.0, 1.0, ...)\n    The difficulty lies in the weird shape of the function*/\n    NonhomogeneousBoundaryConstraint constraint(Array(n, -1.0), Array(n, 4.0));\n    Array x(n, 0.0);\n    Array optimum(n, 1.0);\n    Size agents = 100;\n    Size kneighbor = 25;\n    Size threshold = 500;\n    std::cout << \"Function: rosenbrock, Dimensions: \" << n\n            << \", Agents: \" << agents << \", K-neighbors: \" << kneighbor\n            << \", Threshold: \" << threshold << std::endl;\n    ext::shared_ptr<ParticleSwarmOptimization::Topology> topology =\n        ext::make_shared<KNeighbors>(kneighbor);\n    ext::shared_ptr<ParticleSwarmOptimization::Inertia> inertia =\n        ext::make_shared<LevyFlightInertia>(1.5, threshold, seed);\n    TestFunction f(rosenbrock);\n    ParticleSwarmOptimization pso(agents, topology, inertia, 2.05, 2.05, seed);\n    EndCriteria ec(10000, 1000, 1.0e-8, 1.0e-8, 1.0e-8);\n    test(pso, f, ec, x, constraint, optimum);\n    std::cout << \"================================================================\" << std::endl;\n}\n\nvoid testDifferentialEvolution(Size n, Size agents){\n    /*The Rosenbrock function has a global minima at (1.0, ...) and a local minima at (-1.0, 1.0, ...)\n    The difficulty lies in the weird shape of the function*/\n    NonhomogeneousBoundaryConstraint constraint(Array(n, -4.0), Array(n, 4.0));\n    Array x(n, 0.0);\n    Array optimum(n, 1.0);\n\n    TestFunction f(rosenbrock);\n\n    Real probability = 0.3;\n    Real stepsizeWeight = 0.6;\n    DifferentialEvolution::Strategy strategy = DifferentialEvolution::BestMemberWithJitter;\n\n    std::cout << \"Function: rosenbrock, Dimensions: \" << n << \", Agents: \" << agents\n              << \", Probability: \" << probability\n              << \", StepsizeWeight: \" << stepsizeWeight\n              << \", Strategy: BestMemberWithJitter\" << std::endl;\n    DifferentialEvolution::Configuration config;\n    config.withBounds(true)\n          .withCrossoverProbability(probability)\n          .withPopulationMembers(agents)\n          .withStepsizeWeight(stepsizeWeight)\n          .withStrategy(strategy)\n          .withSeed(seed);\n\n    DifferentialEvolution de(config);\n    EndCriteria ec(5000, 1000, 1.0e-8, 1.0e-8, 1.0e-8);\n    test(de, f, ec, x, constraint, optimum);\n    std::cout << \"================================================================\" << std::endl;\n}\n\nvoid printTime(double seconds){\n    Integer hours = int(seconds/3600);\n    seconds -= hours * 3600;\n    Integer minutes = int(seconds/60);\n    seconds -= minutes * 60;\n    std::cout << \" \\nRun completed in \";\n    if (hours > 0)\n        std::cout << hours << \" h \";\n    if (hours > 0 || minutes > 0)\n        std::cout << minutes << \" m \";\n    std::cout << std::fixed << std::setprecision(0)\n              << seconds << \" s\\n\" << std::endl;\n}\n\nint main(int, char* []) {\n\n    try {\n        std::cout << std::endl;\n        boost::timer timer;\n\n        std::cout << \"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\" << std::endl;\n        std::cout << \"Firefly Algorithm Test\" << std::endl;\n        std::cout << \"----------------------------------------------------------------\" << std::endl;\n        testFirefly();\n\n        printTime(timer.elapsed());\n\n        std::cout << \"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\" << std::endl;\n        std::cout << \"Hybrid Simulated Annealing Test\" << std::endl;\n        std::cout << \"----------------------------------------------------------------\" << std::endl;\n        testGaussianSA(3, 500, 200, 100.0, 0.1, GaussianSimulatedAnnealing::ResetToBestPoint, 150, GaussianSimulatedAnnealing::EveryNewPoint);\n        testGaussianSA(10, 500, 200, 100.0, 0.1, GaussianSimulatedAnnealing::ResetToBestPoint, 150, GaussianSimulatedAnnealing::EveryNewPoint);\n        testGaussianSA(30, 500, 200, 100.0, 0.1, GaussianSimulatedAnnealing::ResetToBestPoint, 150, GaussianSimulatedAnnealing::EveryNewPoint);\n\n        printTime(timer.elapsed());\n\n        std::cout << \"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\" << std::endl;\n        std::cout << \"Particle Swarm Optimization Test\" << std::endl;\n        std::cout << \"----------------------------------------------------------------\" << std::endl;\n        testPSO(3);\n        testPSO(10);\n        testPSO(30);\n\n        printTime(timer.elapsed());\n\n        std::cout << \"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\" << std::endl;\n        std::cout << \"Simulated Annealing Test\" << std::endl;\n        std::cout << \"----------------------------------------------------------------\" << std::endl;\n        testSimulatedAnnealing(3, 10000, 4000);\n        testSimulatedAnnealing(10, 10000, 4000);\n        testSimulatedAnnealing(30, 10000, 4000);\n\n        printTime(timer.elapsed());\n\n        std::cout << \"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\" << std::endl;\n        std::cout << \"Differential Evolution Test\" << std::endl;\n        std::cout << \"----------------------------------------------------------------\" << std::endl;\n        testDifferentialEvolution(3, 50);\n        testDifferentialEvolution(10, 150);\n        testDifferentialEvolution(30, 450);\n\n        printTime(timer.elapsed());\n\n        return 0;\n    } catch (std::exception& e) {\n        std::cerr << e.what() << std::endl;\n        return 1;\n    } catch (...) {\n        std::cerr << \"unknown error\" << std::endl;\n        return 1;\n    }\n}\n", "meta": {"hexsha": "4fd2be81970a8311687ae317f92e79ede269b3f5", "size": 15657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/GlobalOptimizer/GlobalOptimizer.cpp", "max_stars_repo_name": "akshett/QuantLib", "max_stars_repo_head_hexsha": "eb02391a1c79009c0f1ba6ef235a424bed60c576", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-12T01:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T17:44:12.000Z", "max_issues_repo_path": "Examples/GlobalOptimizer/GlobalOptimizer.cpp", "max_issues_repo_name": "akshett/QuantLib", "max_issues_repo_head_hexsha": "eb02391a1c79009c0f1ba6ef235a424bed60c576", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-11T15:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-11T15:35:14.000Z", "max_forks_repo_path": "Examples/GlobalOptimizer/GlobalOptimizer.cpp", "max_forks_repo_name": "akshett/QuantLib", "max_forks_repo_head_hexsha": "eb02391a1c79009c0f1ba6ef235a424bed60c576", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-11T08:32:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T08:32:27.000Z", "avg_line_length": 36.9268867925, "max_line_length": 143, "alphanum_fraction": 0.5741202018, "num_tokens": 4217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5275341715712186}}
{"text": "/**\n * @file calc-characteristic.cpp\n *\n * @brief calculate characteristic polynomial.\n *\n * @author Mutsuo Saito (Hiroshima University)\n * @author Makoto Matsumoto (The University of Tokyo)\n *\n * Copyright (C) 2012 Mutsuo Saito, Makoto Matsumoto,\n * Hiroshima University and The University of Tokyo.\n * All rights reserved.\n *\n * The 3-clause BSD License is applied to this software, see\n * LICENSE.txt\n */\n#include <iostream>\n#include <inttypes.h>\n#include <stdint.h>\n#include \"dSFMText.hpp\"\n#include \"dSFMT-calc-jump.hpp\"\n#include <NTL/GF2X.h>\n#include <NTL/vec_GF2.h>\n#include <NTL/GF2XFactoring.h>\n\nusing namespace dsfmt;\nusing namespace NTL;\nusing namespace std;\n\nvoid calc_minimal(GF2X& minimal, dSFMText& dsfmt, int bitpos)\n{\n    uint64_t mask[2];\n    if (bitpos >= 52) {\n\tmask[0] = 0;\n\tmask[1] = UINT64_C(1) << (bitpos - 52);\n    } else {\n\tmask[0] = UINT64_C(1) << bitpos;\n\tmask[1] = 0;\n    }\n    int maxdegree = dsfmt.get_mamaxdegree();\n    vec_GF2 seq;\n    seq.SetLength(2 * maxdegree);\n    for (int i = 0; i < 2 * maxdegree; i++) {\n\tseq[i] = dsfmt.next(mask);\n    }\n    MinPolySeq(minimal, seq, maxdegree);\n#if defined(DEBUG)\n    cout << \"deg(minimal) = \" << dec << deg(minimal) << endl;\n#endif\n}\n\nvoid LCM(GF2X& lcm, const GF2X& x, const GF2X& y) {\n    GF2X gcd;\n    mul(lcm, x, y);\n    GCD(gcd, x, y);\n    lcm /= gcd;\n}\n\nvoid get_lcm(GF2X& lcmpoly, dSFMText& dsfmt) {\n    GF2X minimal;\n    GF2X tmp;\n    int maxdegree = dsfmt.get_mamaxdegree();\n    dsfmt.seeding(1234);\n//    dsfmt.set_high()\n//    dsfmt.seeding(1234, 1);\n    for (int bitpos = 0; bitpos < 52 * 2; bitpos++) {\n\tcalc_minimal(minimal, dsfmt, bitpos);\n\tLCM(tmp, lcmpoly, minimal);\n\tlcmpoly = tmp;\n#if defined(DEBUG)\n    cout << \"deg(lcm) = \" << dec << deg(lcmpoly) << endl;\n#endif\n#if 0\n\tif (deg(lcmpoly) == maxdegree) {\n\t    return;\n\t}\n\tif (deg(lcmpoly) > maxdegree) {\n\t    return;\n\t}\n#endif\n    }\n#if defined(DEBUG)\n    cout << \"deg(lcm) = \" << dec << deg(lcmpoly) << endl;\n#endif\n#if 1\n    for(int i = 0; i < maxdegree; i++) {\n\tdsfmt.init_basis();\n\tfor (int bitpos = 0; bitpos < 52 * 2; bitpos++) {\n\t    calc_minimal(minimal, dsfmt, bitpos);\n\t    LCM(tmp, lcmpoly, minimal);\n\t    lcmpoly = tmp;\n#if 0\n\t    if (deg(lcmpoly) == maxdegree) {\n\t\treturn;\n\t    }\n#endif\n\t}\n    }\n#endif\n#if 0\n    cerr << \"can't find lcm deg=\" << dec << deg(lcmpoly) << endl;\n    cerr << \"maxdegree = \" << dec << maxdegree << endl;\n    throw new logic_error(\"can't find lcm\");\n#endif\n}\n\nstatic int has_large_irreducible(GF2X& fpoly, int degree) {\n    static const GF2X t2(2, 1);\n    static const GF2X t1(1, 1);\n    GF2X t2m;\n    GF2X t;\n    GF2X alpha;\n    int m;\n\n    t2m = t2;\n    if (deg(fpoly) < degree) {\n\treturn 0;\n    }\n    t = t1;\n    t += t2m;\n\n    for (m = 1; deg(fpoly) > degree; m++) {\n\tfor(;;) {\n\t    GCD(alpha, fpoly, t);\n\t    if (IsOne(alpha)) {\n\t\tbreak;\n\t    }\n\t    fpoly /= alpha;\n\t    if (deg(fpoly) < degree) {\n\t\treturn 0;\n\t    }\n\t}\n\tt2m *= t2m;\n\tt2m %= fpoly;\n\tadd(t, t2m, t1);\n    }\n    if (deg(fpoly) != degree) {\n\treturn 0;\n    }\n    return IterIrredTest(fpoly);\n}\n\nvoid check_fix(dSFMText & fix)\n{\n    fix.setup_high();\n    cout << \"before:\";\n    fix.print(cout);\n    fix.next();\n    cout << \"after 1 step:\";\n    fix.print(cout);\n    fix.next();\n    cout << \"after 2 step:\";\n    fix.print(cout);\n    fix.next();\n    cout << \"after 3 step:\";\n    fix.print(cout);\n}\n\nvoid check_fix2(dSFMText & fix)\n{\n    cout << \"before:\";\n    fix.print(cout);\n    fix.next_add();\n    cout << \"after 1 step:\";\n    fix.print(cout);\n    fix.next_add();\n    cout << \"after 2 step:\";\n    fix.print(cout);\n    fix.next_add();\n    cout << \"after 3 step:\";\n    fix.print(cout);\n}\n\nvoid calc_fix(GF2X& lcm, int mexp, int pos1, int sl1,\n\t      uint64_t mask1, uint64_t mask2)\n{\n    dSFMText fix(mexp, pos1, sl1, mask1, mask2);\n    //fix.setup_high();\n    //fix.next();\n    //cout << \"setup0:\";\n    //fix.print(cout);\n    fix.setup_constants();\n    cout << \"setup:\";\n    fix.print(cout);\n    dSFMText work(mexp, pos1, sl1, mask1, mask2);\n    cout << \"zero:\";\n    work.print(cout);\n    for (int i = 0; i <= deg(lcm); i++) {\n\tif (IsOne(coeff(lcm, i))) {\n\t    work.add(fix);\n#if defined(DEBUG) && 0\n    cout << \"work:\";\n    work.print(cout);\n#endif\n\t}\n\tfix.next();\n    }\n    cout << \"fix:\";\n    work.print(cout);\n    check_fix2(work);\n#if 0\n    cout << \"* (t+1)\" << endl;\n    GF2X t1(1,1);\n    dSFMText work2(mexp, pos1, sl1, mask1, mask2);\n    cout << \"work2:\";\n    work2.print(cout);\n    for (int i = 0; i <= deg(t1); i++) {\n\tif (IsOne(coeff(t1, i))) {\n\t    work2.add(work);\n#if defined(DEBUG)\n    cout << \"work2:\";\n    work2.print(cout);\n#endif\n\t}\n\twork.next();\n    }\n    cout << \"work2:\";\n    work2.print(cout);\n#endif\n}\n\nvoid check_const(GF2X& lcm, int mexp, int pos1, int sl1,\n\t      uint64_t mask1, uint64_t mask2)\n{\n    dSFMText normal(mexp, pos1, sl1, mask1, mask2);\n    dSFMText add(mexp, pos1, sl1, mask1, mask2);\n    normal.seeding(123);\n    add.seeding(123);\n\n    normal.setup_high();\n    normal.next();\n    add.next_add();\n    cout << \"normal:\";\n    normal.print(cout);\n    cout << \"add:\";\n    add.print(cout);\n    for (int i = 0; i < 5; i++) {\n\tnormal.next();\n\tadd.next_add();\n    }\n    cout << \"normal:\";\n    normal.print(cout);\n    cout << \"add:\";\n    add.print(cout);\n}\n\nint main(int argc, char *argv[]) {\n    if (argc < 6) {\n\tcout << argv[0] << \" mexp pos1 sl1 mask1 mask2\" << endl;\n\treturn -1;\n    }\n    int mexp = strtol(argv[1], NULL, 10);\n    int pos1 = strtol(argv[2], NULL, 10);\n    int sl1 = strtol(argv[3], NULL, 10);\n    uint64_t mask[2];\n    mask[0] = strtoull(argv[4], NULL, 16);\n    mask[1] = strtoull(argv[5], NULL, 16);\n#if defined(DEBUG)\n    cout << \"mexp:\" << dec << mexp << endl;\n    cout << \"pos1:\" << dec << pos1 << endl;\n    cout << \"sl1:\" << dec << sl1 << endl;\n    cout << \"mask1:\" << hex<< mask[0] << endl;\n    cout << \"mask2:\" << hex << mask[1] << endl;\n#endif\n    dSFMText dsfmt(mexp, pos1, sl1, mask[0], mask[1]);\n    GF2X characteristic(0,1);\n    get_lcm(characteristic, dsfmt);\n#if defined(DEBUG)\n    cout << \"degree:\" << dec << deg(characteristic) << endl;\n    cerr << \"maxdegree = \" << dec << dsfmt.get_mamaxdegree() << endl;\n    cout << characteristic << endl;\n#endif\n    GF2X work;\n    work = characteristic;\n#if defined(DEBUG)\n    cout << \"degree:\" << deg(characteristic) << endl;\n    cout << characteristic << endl;\n#endif\n    if (!has_large_irreducible(characteristic, mexp)) {\n        cout << \"error?\" << endl;\n        return -1;\n    }\n#if 0\n    GF2X remain = work / characteristic;\n    vec_pair_GF2X_long factors;\n    CanZass(factors, remain);\n    cout << \"=== factor of remain ===\" << endl;\n    for (int i = 0; i < factors.length(); i++) {\n\tcout << factors[i].a;\n\tcout << \":\";\n\tcout << factors[i].b << endl;\n    }\n    cout << \"=== factor of remain ===\" << endl;\n#endif\n    GF2X d, s, inv;\n    GF2X t1(1,1);\n    XGCD(d, s, inv, work, t1);\n// d = gcd(a,b), a s + b t = d\n    MulMod(s, inv, t1, work);\n    if (deg(s) != 0) {\n\tcout << \"inv is not inv.\" << endl;\n    }\n\n    string x;\n//    cout << \"# deg = \" << dec << deg(work) << endl;\n    polytostring(x, work);\n    cout << \"#\" << dec << mexp;\n    cout << \",\" << dec << pos1;\n    cout << \",\" << dec << sl1;\n    cout << \",\" << hex << mask[0];\n    cout << \",\" << hex << mask[1];\n    cout << dec << endl;\n    cout << x << endl;\n    cout << dec << flush;\n#if 0\n    string y;\n    polytostring(y, inv);\n    if (deg(d) == 0) {\n\tcout << y << endl;\n    } else {\n\tcout << \"can't finf inv d=\" << d << endl;\n    }\n    calc_fix(inv, mexp, pos1, sl1, mask[0], mask[1]);\n    //check_const(inv, mexp, pos1, sl1, mask[0], mask[1]);\n#endif\n}\n", "meta": {"hexsha": "55031087b8b15f818588e99a7bd537f7db2d3c0d", "size": 7578, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jump/calc-characteristic-old.cpp", "max_stars_repo_name": "mkt-matsumoto-lab/dSFMT", "max_stars_repo_head_hexsha": "6929b76f2ab07e6302f8daece28045d5bec6ff5c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T06:39:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T14:18:47.000Z", "max_issues_repo_path": "jump/calc-characteristic-old.cpp", "max_issues_repo_name": "mkt-matsumoto-lab/dSFMT", "max_issues_repo_head_hexsha": "6929b76f2ab07e6302f8daece28045d5bec6ff5c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-09-02T02:08:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T06:15:28.000Z", "max_forks_repo_path": "jump/calc-characteristic-old.cpp", "max_forks_repo_name": "MersenneTwister-Lab/dSFMT", "max_forks_repo_head_hexsha": "6929b76f2ab07e6302f8daece28045d5bec6ff5c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-03-09T10:59:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T20:36:09.000Z", "avg_line_length": 23.245398773, "max_line_length": 69, "alphanum_fraction": 0.5554235946, "num_tokens": 2545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199673867852, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5275117977557934}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <vector>\n#include <strstream>\n#include <fstream>\n#include <set>\n#include <map>\nusing namespace Eigen;\n\nMatrixXd V;\nMatrixXi F;\nstd::vector<std::vector<int> > IrregularF;\n\nvoid Upsampling()\n{\n\tstd::map<std::pair<int, int>, int> edgeid;\n\tfor (int i = 0; i < F.cols(); ++i) {\n\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\tint v1 = F(j, i);\n\t\t\tint v2 = F((j + 1) % 4, i);\n\t\t\tif (v1 > v2)\n\t\t\t\tstd::swap(v1, v2);\n\t\t\tauto key = std::make_pair(v1, v2);\n\t\t\tint s = edgeid.size();\n\t\t\tif (edgeid.count(key) == 0)\n\t\t\t\tedgeid[key] = s;\n\t\t}\n\t}\n\tstd::vector<Vector4i> faces(F.cols() * 4);\n\tstd::vector<Vector3d> vertices(V.cols() + edgeid.size() + F.cols());\n\tfor (int i = 0; i < V.cols(); ++i) {\n\t\tvertices[i] = V.col(i);\n\t}\n\tfor (auto info : edgeid)\n\t\tvertices[V.cols() + info.second] = 0.5 * (V.col(info.first.first) + V.col(info.first.second));\n\tfor (int i = 0; i < F.cols(); ++i) {\n\t\tVector3d p(0, 0, 0);\n\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\tp += V.col(F(j, i));\n\t\t}\n\t\tp *= 0.25;\n\t\tvertices[V.cols() + edgeid.size() + i] = p;\n\t}\n\tfor (int i = 0; i < F.cols(); ++i) {\n\t\tint eid[4];\n\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\tint v1 = F(j, i);\n\t\t\tint v2 = F((j + 1) % 4, i);\n\t\t\tif (v1 > v2)\n\t\t\t\tstd::swap(v1, v2);\n\t\t\tauto key = std::make_pair(v1, v2);\n\t\t\tif (edgeid.count(key) == 0) {\n\t\t\t\tprintf(\"OMG!\\n\");\n\t\t\t}\n\t\t\teid[j] = edgeid[key];\n\t\t}\n\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\tfaces[i * 4 + j] =\n\t\t\t\tVector4i(F(j, i), eid[j] + V.cols(), V.cols() + edgeid.size() + i, eid[(j + 3) % 4] + V.cols());\n\t\t}\n\t}\n\tV.resize(3, vertices.size());\n\tmemcpy(V.data(), vertices.data(), sizeof(double) * 3 * vertices.size());\n\tF.resize(4, faces.size());\n\tmemcpy(F.data(), faces.data(), sizeof(int) * 4 * faces.size());\n}\nvoid Load(const char* filename) {\n\tstd::vector<Vector3d> positions;\n\tstd::vector<Vector4i> faces;\n\tstd::ifstream is(filename);\n\tchar buffer[2048];\n\twhile (is.getline(buffer, 2048)) {\n\t\tstd::strstream str;\n\t\tstr << buffer;\n\t\tstr >> buffer;\n\t\tif (strcmp(buffer, \"v\") == 0) {\n\t\t\tdouble x, y, z;\n\t\t\tstr >> x >> y >> z;\n\t\t\tpositions.push_back(Vector3d(x, y, z));\n\t\t}\n\t\telse if (strcmp(buffer, \"f\") == 0) {\n\t\t\tstd::vector<int> face;\n\t\t\twhile (str >> buffer) {\n\t\t\t\tstd::strstream fstr;\n\t\t\t\tfstr << buffer;\n\t\t\t\tint f;\n\t\t\t\tfstr >> f;\n\t\t\t\tface.push_back(f-1);\n\t\t\t}\n\t\t\tif (face.size() == 4) {\n\t\t\t\tVector4i f(face[0], face[1], face[2], face[3]);\n\t\t\t\tfaces.push_back(f);\n\t\t\t} else {\n\t\t\t\tIrregularF.push_back(face);\n\t\t\t}\n\t\t}\n\t}\n\tV.resize(3, positions.size());\n\tF.resize(4, faces.size());\n\tmemcpy(F.data(), faces.data(), sizeof(int) * 4 * faces.size());\n\t\n\tstd::vector<std::set<int> > VF(positions.size());\n\tfor (int i = 0; i < F.cols(); ++i) {\n\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\tint x = F(j, i);\n\t\t\tint y = F((j + 1) % 4, i);\n\t\t\tVF[x].insert(y);\n\t\t\tVF[y].insert(x);\n\t\t}\n\t}\n\tstd::vector<Vector3d> new_positions(positions.size());\n\tfor (int i = 0; i < positions.size(); ++i) {\n\t\tnew_positions[i] = Eigen::Vector3d(0, 0, 0);\n\t}\n\tfor (int i = 0; i < VF.size(); ++i) {\n\t\tfor (auto& ind : VF[i]) {\n\t\t\tnew_positions[i] += positions[ind];\n\t\t}\n\t\tnew_positions[i] /= VF[i].size();\n\t}\n\t\n\tmemcpy(V.data(), new_positions.data(), sizeof(double) * 3 * positions.size());\n}\n\nvoid ReportFaceInfo()\n{\n\tprintf(\"Vertex: %d      Regular Faes: %d       Irregular faces %d\\n\", V.cols(), F.cols(), IrregularF.size());\n}\n\nvoid ReportManifold()\n{\n\tstd::set<std::pair<int, int> > dedges;\n\tbool isManifold = true;\n\tfor (int i = 0; i < F.cols(); ++i) {\n\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\tint v1 = F(j, i);\n\t\t\tint v2 = F((j + 1) % 4, i);\n\t\t\tauto key = std::make_pair(v1, v2);\n\t\t\tif (dedges.count(key)) {\n\t\t\t\tisManifold = false;\n\t\t\t} else {\n\t\t\t\tdedges.insert(key);\n\t\t\t}\n\t\t}\n\t}\n\tfor (int i = 0; i < IrregularF.size(); ++i) {\n\t\tfor (int j = 0; j < IrregularF[i].size(); ++j) {\n\t\t\tint v1 = IrregularF[i][j];\n\t\t\tint v2 = IrregularF[i][(j + 1) % IrregularF[i].size()];\n\t\t\tauto key = std::make_pair(v1, v2);\n\t\t\tif (dedges.count(key)) {\n\t\t\t\tisManifold = false;\n\t\t\t} else {\n\t\t\t\tdedges.insert(key);\n\t\t\t}\t\t\t\n\t\t}\n\t}\n\tif (isManifold) {\n\t\tprintf(\"Is Manifold: True.\\n\");\n\t} else {\n\t\tprintf(\"Is Manifold: False.\\n\");\n\t}\n}\n\nvoid ReportSingularity()\n{\n\tstd::vector<std::set<int> > links(V.cols());\n\tfor (int i = 0; i < F.cols(); ++i) {\n\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\tint v1 = F(j, i);\n\t\t\tint v2 = F((j + 1) % 4, i);\n\t\t\tlinks[v1].insert(v2);\n\t\t\tlinks[v2].insert(v1);\n\t\t}\n\t}\n\tfor (int i = 0; i < IrregularF.size(); ++i) {\n\t\tfor (int j = 0; j < IrregularF[i].size(); ++j) {\n\t\t\tint v1 = IrregularF[i][j];\n\t\t\tint v2 = IrregularF[i][(j + 1) % IrregularF[i].size()];\n\t\t\tlinks[v1].insert(v2);\n\t\t\tlinks[v2].insert(v1);\n\t\t}\n\t}\n\tstd::map<int, int> valences;\n\tfor (int i = 0; i < links.size(); ++i) {\n\t\tint v = links[i].size();\n\t\tif (v != 0) {\n\t\t\tif (v > 5) {\n\t\t\t\t//printf(\"Weird %d\\n\", i);\n\t\t\t}\n\t\t\tif (valences.count(v)) {\n\t\t\t\tvalences[v] += 1;\n\t\t\t} else {\n\t\t\t\tvalences[v] = 1;\n\t\t\t}\n\t\t}\n\t}\n\tfor (auto& p : valences) {\n\t\tprintf(\"Valence %d: %d\\n\", p.first, p.second);\n\t}\n}\n\nvoid ReportAngleDifference()\n{\n\tdouble e = 0, max_angle = 0, min_angle = 360;\n\tfor (int i = 0; i < F.cols(); ++i) {\n\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\tint v0 = F(j, i);\n\t\t\tint v1 = F((j+1)%4,i);\n\t\t\tint v2 = F((j+3)%4,i);\n\t\t\tVector3d d1 = V.col(v1) - V.col(v0);\n\t\t\tVector3d d2 = V.col(v2) - V.col(v0);\n\t\t\td1.normalize();\n\t\t\td2.normalize();\n\t\t\tdouble angle = 180.0/3.141592654*atan2(d1.cross(d2).norm(), d1.dot(d2));\n\t\t\te += (angle-90)*(angle-90);\n\t\t\tmax_angle = std::max(angle, max_angle);\n\t\t\tmin_angle = std::min(angle, min_angle);\n\t\t}\n\t}\n\tprintf(\"min max angle: %lf %lf\\n\", min_angle, max_angle);\n\tprintf(\"angle average error: %lf\\n\", sqrt(e / 4 / F.cols()));\n\tstd::vector<double> len;\n\tdouble sum_area = 0;\n\tfor (int i = 0; i < F.cols(); ++i) {\n\t\tEigen::Vector3d a1 = V.col(F(1, i)) - V.col(F(0, i));\n\t\tEigen::Vector3d a2 = V.col(F(3, i)) - V.col(F(0, i));\n\t\tEigen::Vector3d a3 = V.col(F(1, i)) - V.col(F(2, i));\n\t\tEigen::Vector3d a4 = V.col(F(3, i)) - V.col(F(2, i));\n\t\tdouble t1 = a1.cross(a2).norm();\n\t\tdouble t2 = a3.cross(a4).norm();\n\t\tlen.push_back(t1 + t2);\n\t\tsum_area += t1 + t2;\n\t}\n\tdouble med_area = sum_area / F.cols();\n\tfor (int i = 0; i < len.size(); ++i) {\n\t\tlen[i] = (len[i] - med_area) / med_area;\n\t}\n\tdouble t = 0;\n\tfor (int i = 0; i < len.size(); ++i) {\n\t\tt += len[i] * len[i];\n\t}\n\tprintf(\"area %lf\\n\", sqrt(t / len.size()));\n}\n\nvoid Analyze()\n{\n\tReportFaceInfo();\n\tReportManifold();\n\tReportSingularity();\n\tReportAngleDifference();\n}\n\nint main(int argc, char** argv) {\n\tif (argc < 2) {\n\t\tprintf(\"./analyzer input.obj [scale] [output.txt]\\n\");\n\t\treturn 0;\n\t}\n\n\tLoad(argv[1]);\n\n\tint scale = 1;\n\tif (argc >= 3) {\n\t\tsscanf(argv[2], \"%d\", &scale);\n\t}\n\tfor (int i = 1; i < scale; ++i) {\n\t\tUpsampling();\n\t}\n\tif (argc >= 4) {\n\t\tfreopen(argv[3],\"w\",stdout);\n\t}\n\n\tAnalyze();\n\n\tfclose(stdout);\n}\n", "meta": {"hexsha": "25c5f519ea55f7270299a695bf99c926352fc486", "size": 6734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/QuadriFlow/tools/analyzer.cpp", "max_stars_repo_name": "hjwdzh/TextureNet", "max_stars_repo_head_hexsha": "f3515537909ffb4ab04694b91109b535bb5c85d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 89.0, "max_stars_repo_stars_event_min_datetime": "2019-03-30T03:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T05:16:51.000Z", "max_issues_repo_path": "data/QuadriFlow/tools/analyzer.cpp", "max_issues_repo_name": "jtpils/TextureNet", "max_issues_repo_head_hexsha": "f3515537909ffb4ab04694b91109b535bb5c85d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-29T11:21:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T04:09:41.000Z", "max_forks_repo_path": "data/QuadriFlow/tools/analyzer.cpp", "max_forks_repo_name": "jtpils/TextureNet", "max_forks_repo_head_hexsha": "f3515537909ffb4ab04694b91109b535bb5c85d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2019-04-12T01:20:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-12T16:10:33.000Z", "avg_line_length": 24.3104693141, "max_line_length": 110, "alphanum_fraction": 0.5368280368, "num_tokens": 2534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5275117944882407}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n#include <float.h>\n#include <iostream>\n\n#include <armadillo>\n#include <tuple>\n\n#include \"sys.h\"\n#include \"grid.h\"\n#include \"vtk_functions.h\"\n\nusing namespace std;\n\ntypedef struct {\n    double minMag;\n    double maxMag;\n    double range;\n\n} SYS_Image;\n\n// void draw_image(System *sys, Grid *grid) {\n//     std::cout << \"Started drawing image\" << endl;\n\n//     int w = sys->NGrid;\n//     int h = sys->NGrid;\n\n//     FILE *f;\n//     unsigned char *img = NULL;\n//     int filesize = 54 + 3 * w * h;  \n//     //w is your image width, h is image height, both int\n\n//     img = (unsigned char *) malloc(3 * w * h);\n//     memset(img, 0, sizeof(&img));\n\n//     for (int i = 0; i < sys->NGrid; i++) {\n//         for (int j = 0; j < sys->NGrid; j++) {\n//             int x = i;\n//             int y = j;\n\n//             double r = sys->theImage[i][j].x;\n//             double g = sys->theImage[i][j].y;\n//             double b = sys->theImage[i][j].z;\n\n//             if (r > 255) r = 255;\n//             if (g > 255) g = 255;\n//             if (b > 255) b = 255;\n\n//             img[(x + y * w) * 3 + 2] = (unsigned char) (r);\n//             img[(x + y * w) * 3 + 1] = (unsigned char) (g);\n//             img[(x + y * w) * 3 + 0] = (unsigned char) (b);\n//         }\n//     }\n\n//     unsigned char bmpfileheader[14] = {'B', 'M', 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0};\n//     unsigned char bmpinfoheader[40] = {40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 24, 0};\n//     unsigned char bmppad[3] = {0, 0, 0};\n\n//     bmpfileheader[2] = (unsigned char) (filesize);\n//     bmpfileheader[3] = (unsigned char) (filesize >> 8);\n//     bmpfileheader[4] = (unsigned char) (filesize >> 16);\n//     bmpfileheader[5] = (unsigned char) (filesize >> 24);\n\n//     bmpinfoheader[4] = (unsigned char) (w);\n//     bmpinfoheader[5] = (unsigned char) (w >> 8);\n//     bmpinfoheader[6] = (unsigned char) (w >> 16);\n//     bmpinfoheader[7] = (unsigned char) (w >> 24);\n//     bmpinfoheader[8] = (unsigned char) (h);\n//     bmpinfoheader[9] = (unsigned char) (h >> 8);\n//     bmpinfoheader[10] = (unsigned char) (h >> 16);\n//     bmpinfoheader[11] = (unsigned char) (h >> 24);\n\n//     f = fopen(\"magix.bmp\", \"wb\");\n\n//     fwrite(bmpfileheader, 1, 14, f);\n//     fwrite(bmpinfoheader, 1, 40, f);\n\n//     for (int i = 0; i < h; i++) {\n//         fwrite(img + (w * (h - i - 1) * 3), 3, w, f);\n//         fwrite(bmppad, 1, (4 - (w * 3) % 4) % 4, f);\n//     }\n\n//     fclose(f);\n\n//     std::cout << \"Image drawn\" << endl;\n// }\n\n// void set_min_max(System *sys, Grid *grid) {\n//     int i, j;\n\n//     // sys->theImage = (Node **) calloc(sys->NGrid, sizeof(Node *));\n\n//     // for (i = 0; i < sys->NGrid; i++)\n//     //     sys->theImage[i] = (Node *) calloc(sys->NGrid, sizeof(Node));\n\n//     double *magSorted = (double *) malloc(sizeof(double) * sys->NGrid * sys->NGrid);\n\n//     for (j = 0; j < sys->NGrid; j++) {\n//         for (i = 0; i < sys->NGrid; i++) {\n//             double mag = sqrtf(sys->BField[j][i].x * sys->BField[j][i].x + sys->BField[j][i].y * sys->BField[j][i].y + sys->BField[j][i].z * sys->BField[j][i].z);\n\n//             if (mag > 0)\n//                 magSorted[j * sys->NGrid + i] = log(mag);\n//         }\n//     }\n\n//     mergesort(magSorted, sys->NGrid * sys->NGrid);\n\n//     sys_image->minMag = DBL_MAX;\n//     sys_image->maxMag = -DBL_MAX;\n\n//     for (j = 0; j < sys->NGrid; j++) {\n//         for (i = 0; i < sys->NGrid; i++) {\n//             if (magSorted[j * sys->NGrid + i] != DBL_MAX) {\n//                 if (sys_image->minMag > magSorted[j * sys->NGrid + i])\n//                     sys_image->minMag = magSorted[j * sys->NGrid + i];\n//                 if (sys_image->maxMag < magSorted[j * sys->NGrid + i])\n//                     sys_image->maxMag = magSorted[j * sys->NGrid + i];\n//             }\n//         }\n//     }\n\n//     sys_image->range = sys_image->maxMag - sys_image->minMag;\n\n//     if (sys->debug == 1) {\n//       printf(\"\\nminMag: %E\\n\", sys_image->minMag);\n//       printf(\"maxMag: %E\\n\", sys_image->maxMag);\n//       printf(\"minMag non log: %E\\n\", exp(sys_image->minMag));\n//       printf(\"maxMag non log: %E\\n\", exp(sys_image->maxMag));\n//     }\n// }\n\nvoid write_bmp(System *sys, Grid *grid) {\n    double red = 0;\n    double green = 0;\n    double blue = 0;\n\n    Node *x_box = (Node *) calloc(1, sizeof(Node));\n    Node *y_box = (Node *) calloc(1, sizeof(Node));\n    Node *point = (Node *) calloc(1, sizeof(Node));\n\n    arma::field<arma::rowvec> image(sys->NGrid, sys->NGrid);\n    arma::rowvec pixel(3);\n\n    tuple <double, double, double> geek;\n\n    for (int i = 0; i < sys->NGrid; i++) {\n        for (int j = 0; j < sys->NGrid; j++) {\n            double lic_val = grid->Hx(j,i) / 255;\n            double val = 0;\n\n            // if (sys->pImage[j][i].y > 0)\n            //     val = ((get_dec_place(sys->pImage[j][i].y, 20)) - sys_image->minMag) / sys_image->range;\n\n            if (val < 0.25) {\n                red = 0;\n                green = 255 * (val / 0.25);\n                blue = 255;\n            } else if ((val >= 0.25) && (val < 0.5)) {\n                red = 0;\n                green = 255;\n                blue = 255 - 255 * (val - 0.25) / 0.25;\n            } else if ((val >= 0.5) && (val < 0.75)) {\n                red = 255 * (val - 0.5) / 0.25;\n                green = 255;\n                blue = 0;\n            } else if ((val >= 0.75) && (val < 1.00)) {\n                red = 255;\n                green = 255 - 255 * (val - 0.75) / 0.25;\n                blue = 0;\n            } else {\n                red = 255;\n                green = 255 - 255 * (val - 0.75) / 0.25;\n                blue = 0;\n            }\n\n            pixel(0) = red * grid->Hy(j,i) * lic_val;\n            pixel(1) = green * grid->Hy(j,i) * lic_val;\n            pixel(2) = blue * grid->Hy(j,i) * lic_val;\n\n            image(i, j) = pixel;\n\n            // if (sys->set_vtk == 1) {\n            //     pixel(0) = red * grid->Hy(j,i) * lic_val;\n            //     pixel(1) = green * grid->Hy(j,i) * lic_val;\n            //     pixel(2) = blue * grid->Hy(j,i) * lic_val;\n\n            //     image(i, j) = pixel;\n            // } else {\n            //     pixel(0) = red * lic_val;\n            //     pixel(1) = green * lic_val;\n            //     pixel(2) = blue * lic_val;\n\n            //     image(i, j) = pixel;\n            // }\n\n            // if (sys->set_vtk == 1) {\n            //     // sys->theImage[i][sys->NGrid - j].x = red * sys->pImage[j][i].y * lic_val;\n            //     // sys->theImage[i][sys->NGrid - j].y = green * sys->pImage[j][i].y * lic_val;\n            //     // sys->theImage[i][sys->NGrid - j].z = blue * sys->pImage[j][i].y * lic_val;\n            // } else {\n            //     // sys->theImages[i][sys->NGrid - j].x = red * lic_val;\n            //     // sys->theImage[i][sys->NGrid - j].y = green * lic_val;\n            //     // sys->theImage[i][sys->NGrid - j].z = blue * lic_val;\n            // }\n\n            // for (k = 0; k < (int) p.size(); k++) {\n            //     sort(p, x_box, 0, k, (int) p[k].size());\n            //     sort(p, y_box, 1, k, (int) p[k].size());\n\n            //     point->x = obs_grid(i)(1); // y-coord\n            //     point->y = obs_grid(j)(2); // z-coord\n\n            //     if (point_in_box(point, x_box, y_box)) {\n            //         sys->theImage[i][sys->NGrid - j].x = 0;\n            //         sys->theImage[i][sys->NGrid - j].y = 0;\n            //         sys->theImage[i][sys->NGrid - j].z = 0;\n            //     }\n            // }\n        }\n    }\n    \n    // image.save(\"image.field\");    \n\n    // if (sys->set_vtk == 1)\n    //     vtk_mag_field(sys, image, obs_grid);\n    // else\n    //     draw_image(sys);\n}\n", "meta": {"hexsha": "d285ff201f89b63b073fab901ed6d87fcc6d4e92", "size": 7765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/images.cpp", "max_stars_repo_name": "rubenvanstaden/Magix", "max_stars_repo_head_hexsha": "0b45955d98a57b15b021e3d2e99698972f874a2d", "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": "src/images.cpp", "max_issues_repo_name": "rubenvanstaden/Magix", "max_issues_repo_head_hexsha": "0b45955d98a57b15b021e3d2e99698972f874a2d", "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": "src/images.cpp", "max_forks_repo_name": "rubenvanstaden/Magix", "max_forks_repo_head_hexsha": "0b45955d98a57b15b021e3d2e99698972f874a2d", "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": 33.4698275862, "max_line_length": 165, "alphanum_fraction": 0.4405666452, "num_tokens": 2588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.527511789382663}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <queue>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/tuple/tuple.hpp>\n\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;\ntypedef  boost::graph_traits<graph>::edge_descriptor      edge_desc;\ntypedef  boost::graph_traits<graph>::out_edge_iterator      out_edge_it;\n\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 edge_desc e = boost::add_edge(from, to, G).first;\n    const edge_desc 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// Modeling it as a flow problem. \n// The source connects to all vertices with a positive balance, all other vertices connect to the sink.\n// Since an unions total value needs to be strictly greater than zero, we know there needs to be at \n// least one province that does not need its full balance to support it. I no such province exists, \n// there can not be an union. If there is a province that does not need its full balance, the flow is \n// less than the sum of positive balances\nvoid solve() {\n  int n, m;\n  cin >> n >> m;\n  \n  // Set up the graph\n  graph G(n);\n  edge_adder adder(G);\n  auto rc_map = boost::get(boost::edge_residual_capacity, G);\n  \n  auto source = boost::add_vertex(G);\n  auto target = boost::add_vertex(G);\n  \n  // Connect all provinces to source/target depending on balance\n  int sumPositive = 0;\n  int b;\n  for (int i = 0; i < n; ++i) {\n    cin >> b;\n    if (b > 0) {\n      sumPositive += b;\n      adder.add_edge(source, i, b);\n    }\n    else {\n      adder.add_edge(i, target, -b);\n    }\n  }\n  \n  // Connect provinces\n  int u, v, d;\n  for (int i = 0; i < m; ++i) {\n    cin >> u >> v >> d;\n    adder.add_edge(u, v, d);\n  }\n  \n\n  // Compute flow & output\n  int flow = boost::push_relabel_max_flow(G, source, target);\n  cout << (flow < sumPositive ? \"yes\" : \"no\") << endl;\n}\n\nint main() {\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": "da24b7442408e625f67dd84fb3c5cd49d3585a1c", "size": 2670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/switzerland.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/switzerland.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/switzerland.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": 29.6666666667, "max_line_length": 103, "alphanum_fraction": 0.6606741573, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.5275117719216381}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include <mrpt/core/exceptions.h>\n#include <mrpt/core/lock_helper.h>\n#include <mrpt/gui/CDisplayWindowGUI.h>\n#include <mrpt/opengl/CAxis.h>\n#include <mrpt/opengl/CGridPlaneXY.h>\n#include <mrpt/opengl/stock_objects.h>\n#include <mrpt/poses/Lie/SO.h>\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <iostream>\n\nstatic void AppRotationConverter()\n{\n\tnanogui::init();\n\n\t// Create main window:\n\tmrpt::gui::CDisplayWindowGUI_Params cp;\n\t// cp.fullscreen = true;\n\n\t// Input variables (they are bound to the GUI controls):\n\tmrpt::math::CQuaternionDouble in_quat;\n\tmrpt::math::CMatrixFixed<double, 3, 3> in_rot;\n\tin_rot.setIdentity();\n\tstd::array<double, 3> in_ypr = {0, 0, 0};\n\tmrpt::math::TVector3D in_axisangle_ax(0, 0, 0);\n\tdouble in_axisangle_ang = 0;\n\tauto in_lie_log = mrpt::math::CVectorFixed<double, 3>::Zero();\n\tbool units_radians = true;\n\n\tmrpt::opengl::CSetOfObjects::Ptr gl_corner_user =\n\t\tmrpt::opengl::stock_objects::CornerXYZ(1.0f);\n\tmrpt::opengl::CAxis::Ptr gl_corner_reference = mrpt::opengl::CAxis::Create(\n\t\t-1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.2f, 1.0f, true);\n\tgl_corner_reference->setTextScale(0.04);\n\n\t// In/out UI control declarations (declared here so we can use them in the\n\t// lambda below):\n\tnanogui::TabWidget* tabWidget = nullptr;\n\tnanogui::TextBox* ed_in_rot[3][3];\n\tnanogui::TextBox *edOutMatrix = nullptr, *edOutQuat = nullptr,\n\t\t\t\t\t *edOutAxisAngle_Ax = nullptr, *edOutAxisAngle_An = nullptr,\n\t\t\t\t\t *edOutLogSO3 = nullptr;\n\tnanogui::TextBox* ed_out_rot[3][3];\n\tnanogui::Slider* sl_in_ypr[3] = {nullptr, nullptr, nullptr};\n\n\t// The main function: update all calculations:\n\tauto lambdaRecalcAll = [&]() {\n\t\tmrpt::poses::CPose3D userPose;\n\t\tswitch (tabWidget->activeTab())\n\t\t{\n\t\t\t// YPR\n\t\t\tcase 0:\n\t\t\t{\n\t\t\t\tconst double K = units_radians ? 1.0 : (M_PI / 180.0);\n\t\t\t\tuserPose.setFromValues(\n\t\t\t\t\t0, 0, 0, in_ypr[0] * K, in_ypr[1] * K, in_ypr[2] * K);\n\t\t\t}\n\t\t\tbreak;\n\t\t\t// Rot matrix:\n\t\t\tcase 1:\n\t\t\t{\n\t\t\t\t// Run a SVD to ensure we take the closest SO(3) matrix to the\n\t\t\t\t// user input:\n\t\t\t\tEigen::Matrix3d M = in_rot.asEigen();\n\t\t\t\tEigen::JacobiSVD<Eigen::Matrix3d> svd(\n\t\t\t\t\tM, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n\t\t\t\tauto R = mrpt::math::CMatrixDouble33(\n\t\t\t\t\t(svd.matrixU() * svd.matrixV().transpose()).eval());\n\t\t\t\tuserPose.setRotationMatrix(R);\n\t\t\t\tfor (int r = 0; r < 3; r++)\n\t\t\t\t\tfor (int c = 0; c < 3; c++)\n\t\t\t\t\t\ted_in_rot[r][c]->setValue(\n\t\t\t\t\t\t\tmrpt::format(\"%.05f\", R(r, c)));\n\t\t\t}\n\t\t\tbreak;\n\t\t\t// Quaternion\n\t\t\tcase 2:\n\t\t\t{\n\t\t\t\tuserPose = mrpt::poses::CPose3D(in_quat, 0, 0, 0);\n\t\t\t}\n\t\t\tbreak;\n\t\t\t// axis+angle\n\t\t\tcase 3:\n\t\t\t{\n\t\t\t\tconst double K = units_radians ? 1.0 : (M_PI / 180.0);\n\t\t\t\tmrpt::math::TVector3D v =\n\t\t\t\t\tin_axisangle_ax * (in_axisangle_ang * K);\n\t\t\t\tmrpt::math::CVectorFixed<double, 3> vn;\n\t\t\t\tfor (int i = 0; i < 3; i++)\n\t\t\t\t\tvn[i] = v[i];\n\n\t\t\t\tuserPose.setRotationMatrix(mrpt::poses::Lie::SO<3>::exp(vn));\n\t\t\t}\n\t\t\tbreak;\n\t\t\t// log(SO(3))\n\t\t\tcase 4:\n\t\t\t{\n\t\t\t\tuserPose.setRotationMatrix(\n\t\t\t\t\tmrpt::poses::Lie::SO<3>::exp(in_lie_log));\n\t\t\t}\n\t\t\tbreak;\n\t\t};\n\n\t\t// Set 3D view corner:\n\t\tgl_corner_user->setPose(userPose);\n\n\t\t// Update text output:\n\t\tconst mrpt::math::CMatrixDouble33 Rout = userPose.getRotationMatrix();\n\n\t\t// matrix:\n\t\tedOutMatrix->setValue(Rout.inMatlabFormat());\n\t\tfor (int r = 0; r < 3; r++)\n\t\t\tfor (int c = 0; c < 3; c++)\n\t\t\t\ted_out_rot[r][c]->setValue(mrpt::format(\"%.05f\", Rout(r, c)));\n\n\t\t// quat:\n\t\tmrpt::math::CQuaternionDouble q;\n\t\tuserPose.getAsQuaternion(q);\n\t\tedOutQuat->setValue(q.asString());\n\n\t\t// SO(3) log:\n\t\tconst auto log_R = mrpt::poses::Lie::SO<3>::log(Rout);\n\t\tedOutLogSO3->setValue(\n\t\t\tmrpt::format(\"[%.05f %.05f %.05f]\", log_R[0], log_R[1], log_R[2]));\n\n\t\t// axis-angle:\n\t\tmrpt::math::TVector3D axis(log_R[0], log_R[1], log_R[2]);\n\t\tif (axis.norm() > 1e-20) axis = axis.unitarize();\n\n\t\tedOutAxisAngle_Ax->setValue(\n\t\t\tmrpt::format(\"[%.05f %.05f %.05f]\", axis[0], axis[1], axis[2]));\n\t\tedOutAxisAngle_An->setValue(mrpt::format(\n\t\t\t\"%.05f %s\", log_R.norm() * (units_radians ? 1.0 : 180.0 / M_PI),\n\t\t\t(units_radians ? \"rad\" : \"deg\")));\n\t};\n\n\t// Create GUI:\n\tmrpt::gui::CDisplayWindowGUI win(\"3D rotation converter\", 900, 700, cp);\n\n\t// Add INPUT window:\n\t// -----------------------------\n\tnanogui::Window* winInput = new nanogui::Window(&win, \"Rotation input\");\n\twinInput->setPosition(nanogui::Vector2i(10, 50));\n\twinInput->setLayout(new nanogui::GroupLayout());\n\twinInput->setFixedWidth(350);\n\n\ttabWidget = winInput->add<nanogui::TabWidget>();\n\n\t{  // Yaw/pitch/roll  tab:\n\t\tnanogui::Widget* layer = tabWidget->createTab(\"Yaw-pitch-roll\");\n\t\tauto layout = new nanogui::GridLayout(\n\t\t\tnanogui::Orientation::Horizontal, 3, nanogui::Alignment::Fill, 5,\n\t\t\t0);\n\t\tlayer->setLayout(layout);\n\n\t\tconst char* lb[3] = {\"yaw (Z)=\", \"pitch (Y)=\", \"roll (x)=\"};\n\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tlayer->add<nanogui::Label>(lb[i]);\n\t\t\tnanogui::TextBox* ed =\n\t\t\t\tlayer->add<nanogui::TextBox>(mrpt::format(\"%.2f\", in_quat[i]));\n\t\t\ted->setEditable(true);\n\t\t\ted->setFormat(\"[-+]?[0-9.e+-]*\");\n\t\t\ted->setCallback([&in_ypr, i, lambdaRecalcAll, &sl_in_ypr,\n\t\t\t\t\t\t\t &units_radians](const std::string& s) {\n\t\t\t\tin_ypr[i] = std::stod(s);\n\t\t\t\tsl_in_ypr[i]->setValue(\n\t\t\t\t\tin_ypr[i] / (units_radians ? M_PIf : 180.0f));\n\t\t\t\tlambdaRecalcAll();\n\t\t\t\treturn true;\n\t\t\t});\n\t\t\tnanogui::Slider* sl = layer->add<nanogui::Slider>();\n\t\t\tsl_in_ypr[i] = sl;\n\t\t\tsl->setRange({-1.0f, 1.0f});\n\t\t\tsl->setCallback([&, i, ed](float val) {\n\t\t\t\tval *= units_radians ? M_PIf : 180.0f;\n\t\t\t\tif (i == 1) val *= 0.5f;  // Pitch\n\t\t\t\ted->setValue(mrpt::format(\"%.03f\", val));\n\t\t\t\ted->callback()(ed->value());\n\t\t\t});\n\t\t}\n\t}\n\n\t{  // rotation matrix tab:\n\t\tnanogui::Widget* layer = tabWidget->createTab(\"SO(3) matrix\");\n\n\t\tauto layout = new nanogui::GridLayout(\n\t\t\tnanogui::Orientation::Horizontal, 3, nanogui::Alignment::Fill, 5,\n\t\t\t0);\n\t\tlayer->setLayout(layout);\n\n\t\tfor (int r = 0; r < 3; r++)\n\t\t{\n\t\t\tfor (int c = 0; c < 3; c++)\n\t\t\t{\n\t\t\t\tnanogui::TextBox* ed = layer->add<nanogui::TextBox>(\n\t\t\t\t\tmrpt::format(\"%.04f\", in_rot(r, c)));\n\t\t\t\ted->setEditable(true);\n\t\t\t\ted->setFormat(\"[-+]?[0-9.e+-]*\");\n\t\t\t\ted->setCallback([&in_rot, r, c](const std::string& s) {\n\t\t\t\t\tin_rot(r, c) = std::stod(s);\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t\ted_in_rot[r][c] = ed;\n\t\t\t}\n\t\t}\n\t}\n\n\t{  // Quaternion tab:\n\t\tnanogui::Widget* layer = tabWidget->createTab(\"Quaternion\");\n\t\tauto layout = new nanogui::GridLayout(\n\t\t\tnanogui::Orientation::Horizontal, 2, nanogui::Alignment::Fill, 5,\n\t\t\t0);\n\t\tlayer->setLayout(layout);\n\n\t\tconst char* lb[4] = {\"w (real)=\", \"x=\", \"y=\", \"z=\"};\n\n\t\tfor (int i = 0; i < 4; i++)\n\t\t{\n\t\t\tlayer->add<nanogui::Label>(lb[i]);\n\n\t\t\tnanogui::TextBox* ed =\n\t\t\t\tlayer->add<nanogui::TextBox>(mrpt::format(\"%.2f\", in_quat[i]));\n\t\t\ted->setEditable(true);\n\t\t\ted->setFormat(\"[-+]?[0-9.e+-]*\");\n\t\t\ted->setCallback([&in_quat, i](const std::string& s) {\n\t\t\t\tin_quat[i] = std::stod(s);\n\t\t\t\treturn true;\n\t\t\t});\n\t\t}\n\t}\n\n\t{  // Axis-angle tab:\n\t\tnanogui::Widget* layer = tabWidget->createTab(\"Axis-angle\");\n\t\tlayer->setLayout(new nanogui::GridLayout(\n\t\t\tnanogui::Orientation::Horizontal, 2, nanogui::Alignment::Fill, 5,\n\t\t\t0));\n\t\tlayer->add<nanogui::Label>(\"Axis:\");\n\n\t\t{\n\t\t\tnanogui::Widget* panel = layer->add<nanogui::Widget>();\n\t\t\tpanel->setLayout(new nanogui::GridLayout(\n\t\t\t\tnanogui::Orientation::Horizontal, 3, nanogui::Alignment::Fill,\n\t\t\t\t5, 0));\n\n\t\t\tfor (int r = 0; r < 3; r++)\n\t\t\t{\n\t\t\t\tnanogui::TextBox* ed = panel->add<nanogui::TextBox>(\n\t\t\t\t\tmrpt::format(\"%.04f\", in_axisangle_ax[r]));\n\t\t\t\ted->setEditable(true);\n\t\t\t\ted->setFormat(\"[-+]?[0-9.e+-]*\");\n\t\t\t\ted->setCallback([&in_axisangle_ax, r](const std::string& s) {\n\t\t\t\t\tin_axisangle_ax[r] = std::stod(s);\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\t{\n\t\t\tlayer->add<nanogui::Label>(\"Angle:\");\n\t\t\tnanogui::TextBox* ed = layer->add<nanogui::TextBox>(\n\t\t\t\tmrpt::format(\"%.04f\", in_axisangle_ang));\n\t\t\ted->setEditable(true);\n\t\t\ted->setFormat(\"[-+]?[0-9.e+-]*\");\n\t\t\ted->setCallback([&in_axisangle_ang](const std::string& s) {\n\t\t\t\tin_axisangle_ang = std::stod(s);\n\t\t\t\treturn true;\n\t\t\t});\n\t\t}\n\t}\n\n\t{  // axis with magnitude = log(R) in Lie group\n\t\tnanogui::Widget* layer = tabWidget->createTab(\"log(SO(3))\");\n\n\t\tauto layout = new nanogui::GridLayout(\n\t\t\tnanogui::Orientation::Horizontal, 1, nanogui::Alignment::Fill, 5,\n\t\t\t0);\n\t\tlayer->setLayout(layout);\n\n\t\tlayer->add<nanogui::Label>(\"Axis with magnitude\", \"sans-bold\");\n\t\tlayer->add<nanogui::Label>(\"(i.e. vee(log(R)) in SO(3))\");\n\t\t{\n\t\t\tnanogui::Widget* panel = layer->add<nanogui::Widget>();\n\t\t\tpanel->setLayout(new nanogui::GridLayout(\n\t\t\t\tnanogui::Orientation::Horizontal, 3, nanogui::Alignment::Fill,\n\t\t\t\t5, 0));\n\n\t\t\tfor (int r = 0; r < 3; r++)\n\t\t\t{\n\t\t\t\tnanogui::TextBox* ed = layer->add<nanogui::TextBox>(\n\t\t\t\t\tmrpt::format(\"%.04f\", in_lie_log[r]));\n\t\t\t\ted->setEditable(true);\n\t\t\t\ted->setFormat(\"[-+]?[0-9.e+-]*\");\n\t\t\t\ted->setCallback([&in_lie_log, r](const std::string& s) {\n\t\t\t\t\tin_lie_log[r] = std::stod(s);\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\ttabWidget->setActiveTab(0);\n\n\t// Apply button:\n\twinInput->add<nanogui::Button>(\"Apply\", ENTYPO_ICON_CALCULATOR)\n\t\t->setCallback(lambdaRecalcAll);\n\n\t// Add top menu subwindow:\n\t// -----------------------------\n\t{\n\t\tnanogui::ref<nanogui::Window> winMenu = new nanogui::Window(&win, \"\");\n\t\twinMenu->setPosition(nanogui::Vector2i(0, 0));\n\t\twinMenu->setLayout(new nanogui::BoxLayout(\n\t\t\tnanogui::Orientation::Horizontal, nanogui::Alignment::Middle, 5));\n\t\tnanogui::Theme* modTheme =\n\t\t\tnew nanogui::Theme(win.screen()->nvgContext());\n\t\tmodTheme->mWindowHeaderHeight = 1;\n\t\twinMenu->setTheme(modTheme);\n\n\t\twinMenu->add<nanogui::Button>(\"Quit\", ENTYPO_ICON_ARROW_BOLD_LEFT)\n\t\t\t->setCallback([&win]() { win.setVisible(false); });\n\n\t\twinMenu->add<nanogui::Label>(\"      \");\t // separator\n\n\t\twinMenu\n\t\t\t->add<nanogui::CheckBox>(\n\t\t\t\t\"Show reference frame\",\n\t\t\t\t[&](bool b) { gl_corner_reference->setVisibility(b); })\n\t\t\t->setChecked(true);\n\n\t\twinMenu\n\t\t\t->add<nanogui::CheckBox>(\n\t\t\t\t\"Show rotated frame\",\n\t\t\t\t[&](bool b) { gl_corner_user->setVisibility(b); })\n\t\t\t->setChecked(true);\n\t\twinMenu\n\t\t\t->add<nanogui::CheckBox>(\n\t\t\t\t\"Ortho. view\",\n\t\t\t\t[&](bool b) { win.camera().setCameraProjective(!b); })\n\t\t\t->setChecked(false);\n\n\t\twinMenu->add<nanogui::Label>(\"Units:\");\n\t\twinMenu\n\t\t\t->add<nanogui::ComboBox>(\n\t\t\t\tstd::vector<std::string>({\"radians\", \"degrees\"}))\n\t\t\t->setCallback([&](int index) {\n\t\t\t\t// On units update:\n\t\t\t\tunits_radians = (index == 0);\n\t\t\t\tlambdaRecalcAll();\n\t\t\t});\n\t}\n\n\t// Add OUTPUT window:\n\t// -----------------------------\n\t{\n\t\tnanogui::Window* winOutput =\n\t\t\tnew nanogui::Window(&win, \"Rotation output\");\n\t\twinOutput->setPosition(nanogui::Vector2i(10, 320));\n\t\tauto layout = new nanogui::GridLayout(\n\t\t\tnanogui::Orientation::Horizontal, 1, nanogui::Alignment::Fill, 5,\n\t\t\t0);\n\t\twinOutput->setLayout(layout);\n\t\twinOutput->setFixedWidth(350);\n\n\t\twinOutput->add<nanogui::Label>(\"SO(3) rotation matrix\", \"sans-bold\");\n\t\t{\n\t\t\tnanogui::Widget* panel = winOutput->add<nanogui::Widget>();\n\t\t\tpanel->setLayout(new nanogui::GridLayout(\n\t\t\t\tnanogui::Orientation::Horizontal, 3, nanogui::Alignment::Fill,\n\t\t\t\t5, 0));\n\t\t\tfor (int r = 0; r < 3; r++)\n\t\t\t\tfor (int c = 0; c < 3; c++)\n\t\t\t\t\ted_out_rot[r][c] = panel->add<nanogui::TextBox>(\"\");\n\t\t}\n\n\t\twinOutput->add<nanogui::Label>(\"In MATLAB-like notation:\");\n\t\tedOutMatrix = winOutput->add<nanogui::TextBox>(\"\");\n\t\tedOutMatrix->setEditable(true);\n\n\t\twinOutput->add<nanogui::Label>(\"Quaternion (r,x,y,z)\", \"sans-bold\");\n\t\tedOutQuat = winOutput->add<nanogui::TextBox>(\"\");\n\t\tedOutQuat->setEditable(true);\n\n\t\twinOutput->add<nanogui::Label>(\"Axis-angle (r,x,y,z)\", \"sans-bold\");\n\t\tedOutAxisAngle_Ax = winOutput->add<nanogui::TextBox>(\"\");\n\t\tedOutAxisAngle_Ax->setEditable(true);\n\t\tedOutAxisAngle_An = winOutput->add<nanogui::TextBox>(\"\");\n\t\tedOutAxisAngle_An->setEditable(true);\n\n\t\twinOutput->add<nanogui::Label>(\"Axis with angle (log(R))\", \"sans-bold\");\n\t\tedOutLogSO3 = winOutput->add<nanogui::TextBox>(\"\");\n\t\tedOutLogSO3->setEditable(true);\n\t}\n\n\t// Add a background scene:\n\t// -----------------------------\n\t{\n\t\tauto scene = mrpt::opengl::COpenGLScene::Create();\n\t\tscene->insert(mrpt::opengl::CGridPlaneXY::Create());\n\n\t\tscene->insert(gl_corner_user);\n\t\tscene->insert(gl_corner_reference);\n\n\t\tauto lck = mrpt::lockHelper(win.background_scene_mtx);\n\t\twin.background_scene = std::move(scene);\n\t}\n\n\twin.performLayout();\n\n\twin.camera().setZoomDistance(5.0f);\n\n\t// Update view and process events:\n\twin.drawAll();\n\twin.setVisible(true);\n\tnanogui::mainloop();\n\n\tnanogui::shutdown();\n}\n\nint main()\n{\n\ttry\n\t{\n\t\tAppRotationConverter();\n\t\treturn 0;\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\tstd::cerr << mrpt::exception_to_str(e) << std::endl;\n\t\treturn -1;\n\t}\n}\n", "meta": {"hexsha": "33492ecbff7e297714b681e1b18e8d0cf4961500", "size": 13212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/3d-rotation-converter/3d-rotation-converter_main.cpp", "max_stars_repo_name": "wstnturner/mrpt", "max_stars_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "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": "apps/3d-rotation-converter/3d-rotation-converter_main.cpp", "max_issues_repo_name": "wstnturner/mrpt", "max_issues_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "apps/3d-rotation-converter/3d-rotation-converter_main.cpp", "max_forks_repo_name": "wstnturner/mrpt", "max_forks_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "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.7567567568, "max_line_length": 80, "alphanum_fraction": 0.6055858311, "num_tokens": 4355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5273933061308659}}
{"text": "/* boost random/cauchy_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$\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_CAUCHY_DISTRIBUTION_HPP\n#define BOOST_RANDOM_CAUCHY_DISTRIBUTION_HPP\n\n#include <boost/config/no_tr1/cmath.hpp>\n#include <iosfwd>\n#include <istream>\n#include <boost/limits.hpp>\n#include <boost/random/detail/config.hpp>\n#include <boost/random/detail/operators.hpp>\n#include <boost/random/uniform_01.hpp>\n\nnamespace boost {\nnamespace random {\n\n// Cauchy distribution: \n\n/**\n * The cauchy distribution is a continuous distribution with two\n * parameters, median and sigma.\n *\n * It has \\f$\\displaystyle p(x) = \\frac{\\sigma}{\\pi(\\sigma^2 + (x-m)^2)}\\f$\n */\ntemplate<class RealType = double>\nclass cauchy_distribution\n{\npublic:\n    typedef RealType input_type;\n    typedef RealType result_type;\n\n    class param_type\n    {\n    public:\n\n        typedef cauchy_distribution distribution_type;\n\n        /** Constructs the parameters of the cauchy distribution. */\n        explicit param_type(RealType median_arg = RealType(0.0),\n                            RealType sigma_arg = RealType(1.0))\n          : _median(median_arg), _sigma(sigma_arg) {}\n\n        // backwards compatibility for Boost.Random\n\n        /** Returns the median of the distribution. */\n        RealType median() const { return _median; }\n        /** Returns the sigma parameter of the distribution. */\n        RealType sigma() const { return _sigma; }\n\n        // The new names in C++0x.\n\n        /** Returns the median of the distribution. */\n        RealType a() const { return _median; }\n        /** Returns the sigma parameter of the distribution. */\n        RealType b() const { return _sigma; }\n\n        /** Writes the parameters to a std::ostream. */\n        BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, param_type, parm)\n        {\n            os << parm._median << \" \" << parm._sigma;\n            return os;\n        }\n\n        /** Reads the parameters from a std::istream. */\n        BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, param_type, parm)\n        {\n            is >> parm._median >> std::ws >> parm._sigma;\n            return is;\n        }\n\n        /** Returns true if the two sets of parameters are equal. */\n        BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(param_type, lhs, rhs)\n        { return lhs._median == rhs._median && lhs._sigma == rhs._sigma; }\n\n        /** Returns true if the two sets of parameters are different. */\n        BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(param_type)\n\n    private:\n        RealType _median;\n        RealType _sigma;\n    };\n\n    /**\n     * Constructs a \\cauchy_distribution with the paramters @c median\n     * and @c sigma.\n     */\n    explicit cauchy_distribution(RealType median_arg = RealType(0.0), \n                                 RealType sigma_arg = RealType(1.0))\n      : _median(median_arg), _sigma(sigma_arg) { }\n    \n    /**\n     * Constructs a \\cauchy_distribution from it's parameters.\n     */\n    explicit cauchy_distribution(const param_type& parm)\n      : _median(parm.median()), _sigma(parm.sigma()) { }\n\n    // compiler-generated copy ctor and assignment operator are fine\n\n    // backwards compatibility for Boost.Random\n\n    /** Returns: the \"median\" parameter of the distribution */\n    RealType median() const { return _median; }\n    /** Returns: the \"sigma\" parameter of the distribution */\n    RealType sigma() const { return _sigma; }\n    \n    // The new names in C++0x\n\n    /** Returns: the \"median\" parameter of the distribution */\n    RealType a() const { return _median; }\n    /** Returns: the \"sigma\" parameter of the distribution */\n    RealType b() const { return _sigma; }\n\n    /** Returns the smallest value that the distribution can produce. */\n    RealType min BOOST_PREVENT_MACRO_SUBSTITUTION () const\n    { return -(std::numeric_limits<RealType>::infinity)(); }\n\n    /** Returns the largest value that the distribution can produce. */\n    RealType max BOOST_PREVENT_MACRO_SUBSTITUTION () const\n    { return (std::numeric_limits<RealType>::infinity)(); }\n\n    param_type param() const { return param_type(_median, _sigma); }\n\n    void param(const param_type& parm)\n    {\n        _median = parm.median();\n        _sigma = parm.sigma();\n    }\n\n    /**\n     * Effects: Subsequent uses of the distribution do not depend\n     * on values produced by any engine prior to invoking reset.\n     */\n    void reset() { }\n\n    /**\n     * Returns: A random variate distributed according to the\n     * cauchy distribution.\n     */\n    template<class Engine>\n    result_type operator()(Engine& eng)\n    {\n        // Can we have a boost::mathconst please?\n        const result_type pi = result_type(3.14159265358979323846);\n        using std::tan;\n        RealType val = uniform_01<RealType>()(eng)-result_type(0.5);\n        return _median + _sigma * tan(pi*val);\n    }\n\n    /**\n     * Returns: A random variate distributed according to the\n     * cauchy distribution with parameters specified by param.\n     */\n    template<class Engine>\n    result_type operator()(Engine& eng, const param_type& parm)\n    {\n        return cauchy_distribution(parm)(eng);\n    }\n\n    /**\n     * Writes the distribution to a @c std::ostream.\n     */\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, cauchy_distribution, cd)\n    {\n        os << cd._median << \" \" << cd._sigma;\n        return os;\n    }\n\n    /**\n     * Reads the distribution from a @c std::istream.\n     */\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, cauchy_distribution, cd)\n    {\n        is >> cd._median >> std::ws >> cd._sigma;\n        return is;\n    }\n\n    /**\n     * Returns true if the two distributions will produce\n     * identical sequences of values, given equal generators.\n     */\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(cauchy_distribution, lhs, rhs)\n    { return lhs._median == rhs._median && lhs._sigma == rhs._sigma; }\n\n    /**\n     * Returns true if the two distributions may produce\n     * different sequences of values, given equal generators.\n     */\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(cauchy_distribution)\n\nprivate:\n    RealType _median;\n    RealType _sigma;\n};\n\n} // namespace random\n\nusing random::cauchy_distribution;\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_CAUCHY_DISTRIBUTION_HPP\n", "meta": {"hexsha": "998e523447bcb4f07438b67c21a43bfa8b707a93", "size": 6528, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/random/cauchy_distribution.hpp", "max_stars_repo_name": "189569400/ClickHouse", "max_stars_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/random/cauchy_distribution.hpp", "max_issues_repo_name": "189569400/ClickHouse", "max_issues_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/random/cauchy_distribution.hpp", "max_forks_repo_name": "189569400/ClickHouse", "max_forks_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": 30.3627906977, "max_line_length": 76, "alphanum_fraction": 0.6502757353, "num_tokens": 1512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5273932965732884}}
{"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 \"../src/core/config.hpp\"\n#include \"../src/mymfem/utilities.hpp\"\n\nusing namespace mymfem;\n\n\n/** @brief Unit test for point locator algorithm\n * Test the point location algorithm implemented in class PointLocator\n * for meshes with local refinement, generated by _serial_ code\n */\nTEST(MfemUtil, pointLocator1)\n{\n    std::string input_dir\n            = \"../tests/input/gammaShapedBr/\";\n\n    int lx1 = 1;\n    const std::string mesh_file1\n            = input_dir+\"mesh_lx\"+std::to_string(lx1);\n\n    int lx2 = 6;\n    const std::string mesh_file2\n            = input_dir+\"mesh_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    const IntegrationRule *ir = nullptr;\n    ir = &IntRules.Get(2, 3);\n\n    std::random_device rd;     // initialise (seed) engine\n    std::mt19937 rng(rd());    // random-number engine used\n    std::uniform_int_distribution<int> uni(0,mesh1.GetNE()-1);\n\n    auto elId1 = uni(rng);\n    //std::cout << \"Generate in element:\" << elId1 << std::endl;\n    //elId1 = 3;\n    ElementTransformation *trans1 = mesh1.GetElementTransformation(elId1);\n    DenseMatrix true_x(mesh1.Dimension(), ir->GetNPoints());\n    Vector xk;\n    for (int k=0; k < true_x.NumCols(); k++) {\n        true_x.GetColumnReference(k,xk);\n        trans1->Transform(ir->IntPoint(k), xk);\n    }\n\n    Array <int> elIds1(true_x.NumCols());\n    Array <IntegrationPoint> ips1(true_x.NumCols());\n\n    Array <int> elIds2(true_x.NumCols());\n    Array <IntegrationPoint> ips2(true_x.NumCols());\n\n    auto start1 = std::chrono::high_resolution_clock::now();\n    mesh2.FindPoints(true_x, elIds1, ips1);\n    auto end1 = std::chrono::high_resolution_clock::now();\n\n    auto start2 = std::chrono::high_resolution_clock::now();\n    PointLocator point_locator(&mesh2);\n    int init_elId = 0;\n    for (int k=0; k < true_x.NumCols(); k++) {\n        Vector xk;\n        true_x.GetColumn(k, xk);\n        std::tie (elIds2[k],ips2[k]) = point_locator(xk, init_elId);\n        init_elId = elIds2[k];\n    }\n    auto end2 = std::chrono::high_resolution_clock::now();\n\n    ElementTransformation *trans2 = nullptr;\n    Vector x1, x2, x;\n    double TOL = 1E-8;\n    for (int k=0; k < true_x.NumCols(); k++)\n    {\n        trans2 = mesh2.GetElementTransformation(elIds1[k]);\n        trans2->Transform(ips1[k], x1);\n\n        trans2 = mesh2.GetElementTransformation(elIds2[k]);\n        trans2->Transform(ips2[k], x2);\n\n        true_x.GetColumn(k,x);\n\n        Vector xmx1(x.Size()), xmx2(x.Size());\n        subtract(x, x1, xmx1);\n        subtract(x, x2, xmx2);\n\n        ASSERT_LE(xmx1.Norml1(), TOL);\n        ASSERT_LE(xmx2.Norml1(), TOL);\n    }\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 << \"Run times: \"\n              << \"\\t slow  \" << duration1.count()\n              << \"\\t fast  \" << duration2.count() << std::endl;\n}\n\n/** @brief Unit test for point locator algorithm\n * Test the point location algorithm implemented in class PointLocator\n * for quasi-uniform meshes, generated by _serial_ code.\n * The shared vertices table is generated, but expected to be empty.\n */\nTEST(MfemUtil, pointLocator2)\n{\n    std::string input_dir\n            = \"../tests/input/unitSquareQu/\";\n\n    int lx1 = 1;\n    const std::string mesh_file1 = input_dir+\"mesh_lx\"+std::to_string(lx1);\n\n    int lx2 = 6;\n    const std::string mesh_file2 = input_dir+\"mesh_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    const IntegrationRule *ir = nullptr;\n    ir = &IntRules.Get(2, 3);\n\n    std::random_device rd;     // initialise (seed) engine\n    std::mt19937 rng(rd());    // random-number engine used\n    std::uniform_int_distribution<int> uni(0,mesh1.GetNE()-1);\n\n    auto elId1 = uni(rng);\n    ElementTransformation *trans1 = mesh1.GetElementTransformation(elId1);\n    DenseMatrix true_x(mesh1.Dimension(), ir->GetNPoints());\n    Vector xk;\n    for (int k=0; k < true_x.NumCols(); k++) {\n        true_x.GetColumnReference(k,xk);\n        trans1->Transform(ir->IntPoint(k), xk);\n    }\n\n    Array <int> elIds1(true_x.NumCols());\n    Array <IntegrationPoint> ips1(true_x.NumCols());\n\n    Array <int> elIds2(true_x.NumCols());\n    Array <IntegrationPoint> ips2(true_x.NumCols());\n\n    auto start1 = std::chrono::high_resolution_clock::now();\n    mesh2.FindPoints(true_x, elIds1, ips1);\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    PointLocator point_locator(&mesh2, has_shared_vertices);\n    int init_elId = 0;\n    std::tie (elIds2, ips2) = point_locator(true_x,\n                                            init_elId);\n    auto end2 = std::chrono::high_resolution_clock::now();\n\n    ElementTransformation *trans2 = nullptr;\n    Vector x1, x2, x;\n    double TOL = 1E-8;\n    for (int k=0; k < true_x.NumCols(); k++)\n    {\n        trans2 = mesh2.GetElementTransformation(elIds1[k]);\n        trans2->Transform(ips1[k], x1);\n\n        trans2 = mesh2.GetElementTransformation(elIds2[k]);\n        trans2->Transform(ips2[k], x2);\n\n        true_x.GetColumn(k,x);\n\n        Vector xmx1(x.Size()), xmx2(x.Size());\n        subtract(x, x1, xmx1);\n        subtract(x, x2, xmx2);\n\n        ASSERT_LE(xmx1.Norml1(), TOL);\n        ASSERT_LE(xmx2.Norml1(), TOL);\n    }\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 << \"Run times: \"\n              << \"\\t slow  \" << duration1.count()\n              << \"\\t fast  \" << duration2.count() << std::endl;\n}\n", "meta": {"hexsha": "ad3c2358104a18ed5c2131197acc449df1cb9afc", "size": 6204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_mesh_point_locator.cpp", "max_stars_repo_name": "pratyuksh/lsqXtFemParabolic", "max_stars_repo_head_hexsha": "48057f237956acb531f503e8d4af8048a8a1446f", "max_stars_repo_licenses": ["MIT"], "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_mesh_point_locator.cpp", "max_issues_repo_name": "pratyuksh/lsqXtFemParabolic", "max_issues_repo_head_hexsha": "48057f237956acb531f503e8d4af8048a8a1446f", "max_issues_repo_licenses": ["MIT"], "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_mesh_point_locator.cpp", "max_forks_repo_name": "pratyuksh/lsqXtFemParabolic", "max_forks_repo_head_hexsha": "48057f237956acb531f503e8d4af8048a8a1446f", "max_forks_repo_licenses": ["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.175879397, "max_line_length": 75, "alphanum_fraction": 0.6239522888, "num_tokens": 1727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5273806427049449}}
{"text": "#pragma once\n\n// -*- coding: utf-8 -*-\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <py2cpp/nx2bgl.hpp>\n#include <utility>  // for std::pair\n\nusing graph_t = boost::adjacency_list<\n    boost::listS, boost::vecS, boost::directedS, boost::no_property,\n    boost::property<boost::edge_weight_t, int, boost::property<boost::edge_index_t, int>>>;\nusing Vertex = boost::graph_traits<graph_t>::vertex_descriptor;\nusing Edge_it = boost::graph_traits<graph_t>::edge_iterator;\n\ntemplate <typename Container> inline auto create_test_case1(const Container& weights)\n    -> py::grAdaptor<graph_t> {\n    using Edge = std::pair<int, int>;\n    const auto num_nodes = 5;\n    enum nodes { A, B, C, D, E };\n    static Edge edge_array[] = {Edge{A, B}, Edge{B, C}, Edge{C, D}, Edge{D, E}, Edge{E, A}};\n    // int weights[] = {-5, 1, 1, 1, 1};\n    int num_arcs = sizeof(edge_array) / sizeof(Edge);\n    auto g = graph_t(edge_array, edge_array + num_arcs, weights, num_nodes);\n    return py::grAdaptor<graph_t>{std::move(g)};\n}\n\ntemplate <typename Container> inline auto create_test_case_timing(const Container& weights)\n    -> py::grAdaptor<graph_t> {\n    using Edge = std::pair<int, int>;\n    constexpr auto num_nodes = 3;\n    enum nodes { A, B, C };\n    static Edge edge_array[] = {Edge{A, B}, Edge{B, A}, Edge{B, C}, Edge{C, B},\n                                Edge{B, C}, Edge{C, B}, Edge{C, A}, Edge{A, C}};\n    // int weights[] = {7, 0, 3, 1, 6, 4, 2, 5};\n    constexpr int num_arcs = sizeof(edge_array) / sizeof(Edge);\n    auto g = graph_t(edge_array, edge_array + num_arcs, weights, num_nodes);\n    return py::grAdaptor<graph_t>{std::move(g)};\n}\n", "meta": {"hexsha": "5924151e96a224ce122a84fa41cfc70e288ecde4", "size": 1677, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/netoptim/test_cases_boost.hpp", "max_stars_repo_name": "luk036/netoptim-cpp", "max_stars_repo_head_hexsha": "fcfa332cc78a7c5013f915ce0ec731cbc5ea9118", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/netoptim/test_cases_boost.hpp", "max_issues_repo_name": "luk036/netoptim-cpp", "max_issues_repo_head_hexsha": "fcfa332cc78a7c5013f915ce0ec731cbc5ea9118", "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/netoptim/test_cases_boost.hpp", "max_forks_repo_name": "luk036/netoptim-cpp", "max_forks_repo_head_hexsha": "fcfa332cc78a7c5013f915ce0ec731cbc5ea9118", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-13T02:58:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T02:58:11.000Z", "avg_line_length": 43.0, "max_line_length": 92, "alphanum_fraction": 0.6499701849, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.527380638232216}}
{"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//[degree_centrality_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/degree_centrality.hpp>\n\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 container type for degree centralities and its\n// corresponding property map.\ntypedef exterior_vertex_property< Graph, unsigned > CentralityProperty;\ntypedef CentralityProperty::container_type CentralityContainer;\ntypedef CentralityProperty::map_type CentralityMap;\n\nint main(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 standard input.\n    read_graph(g, nm, cin);\n\n    // Compute the degree centrality for graph.\n    CentralityContainer cents(num_vertices(g));\n    CentralityMap cm(cents, g);\n    all_degree_centralities(g, cm);\n\n    // Print the degree centrality of each vertex.\n    graph_traits< Graph >::vertex_iterator i, end;\n    for (boost::tie(i, end) = vertices(g); i != end; ++i)\n    {\n        cout << setiosflags(ios::left) << setw(12) << g[*i].name << cm[*i]\n             << endl;\n    }\n\n    return 0;\n}\n//]\n", "meta": {"hexsha": "1dbee79b4d977d79ab6581f362d462ffaf1ed0c0", "size": 1962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/degree_centrality.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.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": "3rdparty/boost_1_73_0/libs/graph/example/degree_centrality.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": "3rdparty/boost_1_73_0/libs/graph/example/degree_centrality.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": 29.2835820896, "max_line_length": 74, "alphanum_fraction": 0.7186544343, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.5273806292867583}}
{"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/bessel.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n\n//==================================================================================================\n//== Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of cyl_bessel_yn\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  using i_t = eve::as_integer_t<v_t>;\n  using I_t = eve::wide<i_t, eve::cardinal_t<T>>;\n  TTS_EXPR_IS( eve::cyl_bessel_yn(T(), T())  ,  T);\n  TTS_EXPR_IS( eve::cyl_bessel_yn(v_t(),v_t()), v_t);\n  TTS_EXPR_IS( eve::cyl_bessel_yn(i_t(),T()),   T);\n  TTS_EXPR_IS( eve::cyl_bessel_yn(I_t(),T()),   T);\n  TTS_EXPR_IS( eve::cyl_bessel_yn(i_t(),v_t()), v_t);\n  TTS_EXPR_IS( eve::cyl_bessel_yn(I_t(),v_t()), T);\n};\n\n//==================================================================================================\n//== integral orders\n//==================================================================================================\nEVE_TEST( \"Check behavior of cyl_bessel_yn on wide with integral order\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::ramp(0), eve::test::randoms(0.0, 2000.0))\n        )\n  <typename T>(T n, T a0)\n{\n  using v_t = eve::element_type_t<T>;\n\n  auto eve__cyl_bessel_yn =  [](auto n, auto x) { return eve::cyl_bessel_yn(n, x); };\n  auto std__cyl_bessel_yn =  [](auto n, auto x)->v_t { return boost::math::cyl_neumann(n, x); };\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(0, eve::minf(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(2, eve::inf(eve::as<v_t>())), v_t(0), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(3, eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n  }\n  //scalar large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(3, v_t(1500)), std__cyl_bessel_yn(3, v_t(1500)), 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(2, v_t(500)), std__cyl_bessel_yn(2, v_t(500)), 3.0);\n  //scalar forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(0, v_t(10)), std__cyl_bessel_yn(0, v_t(10))  , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(1, v_t(5)),  std__cyl_bessel_yn(1, v_t(5))   , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(2, v_t(10)), std__cyl_bessel_yn(2, v_t(10))  , 35.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(3, v_t(5)),  std__cyl_bessel_yn(3, v_t(5))   , 35.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(-1, v_t(5)),  std__cyl_bessel_yn(-1, v_t(5))   , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(-2, v_t(10)), std__cyl_bessel_yn(-2, v_t(10))  , 35.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(-3, v_t(5)),  std__cyl_bessel_yn(-3, v_t(5))   , 35.0);\n  //scalar small\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(0, v_t(0.1)), std__cyl_bessel_yn(0, v_t(0.1))  , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(1, v_t(0.2)),  std__cyl_bessel_yn(1, v_t(0.2))   , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(2, v_t(0.1)), std__cyl_bessel_yn(2, v_t(0.1))  , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(3, v_t(0.2)),  std__cyl_bessel_yn(3, v_t(0.2))   , 3.0);\n  //scalar besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(10, v_t(8)), std__cyl_bessel_yn(10, v_t(8))  , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(10, v_t(8)),  std__cyl_bessel_yn(10, v_t(8))   , 3.0);\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(0, eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(2, eve::inf(eve::as<T>())), T(0), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(3, eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n  //simd large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(3, T(1500)),  T(std__cyl_bessel_yn(3, v_t(1500))),  3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(2, T(500)),   T(std__cyl_bessel_yn(2, v_t(500))),   3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(-3, T(1500)), T(std__cyl_bessel_yn(-3, v_t(1500))), 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(-2, T(500)),  T(std__cyl_bessel_yn(-2, v_t(500))),  3.0);\n  //simd forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(2, T(10)),    T(std__cyl_bessel_yn(2, v_t(10)))   , 35.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(3, T(5)),     T(std__cyl_bessel_yn(3, v_t(5)))    , 35.0);\n  //simd small\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(0, T(0.1)),   T(std__cyl_bessel_yn(0, v_t(0.1)))  , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(1, T(0.2)),   T(std__cyl_bessel_yn(1, v_t(0.2)))  , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(2, T(0.1)),   T(std__cyl_bessel_yn(2, v_t(0.1)))  , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(3, T(0.2)),   T(std__cyl_bessel_yn(3, v_t(0.2)))  , 3.0);\n  //simd besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(10, T(8)),   T(std__cyl_bessel_yn(10, v_t(8)))   , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(10, T(8)),   T(std__cyl_bessel_yn(10, v_t(8)))   , 3.0);\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(0), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(2), eve::inf(eve::as<T>())), T(0), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n  // large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(3), T(1500)),  T(std__cyl_bessel_yn(3, v_t(1500))),  3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(2), T(500)),   T(std__cyl_bessel_yn(2, v_t(500))),   3.0);\n  // forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(2), T(10)),    T(std__cyl_bessel_yn(2, v_t(10)))   , 35.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(3), T(5)),     T(std__cyl_bessel_yn(3, v_t(5)))    , 35.0);\n  // serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(2), T(0.1)),   T(std__cyl_bessel_yn(2, v_t(0.1)))  , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(3), T(0.2)),   T(std__cyl_bessel_yn(3, v_t(0.2)))  , 3.0);\n  // besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(10), T(8)),   T(std__cyl_bessel_yn(10, v_t(8)))   , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(10), T(8)),   T(std__cyl_bessel_yn(10, v_t(8)))   , 3.0);\n\n  using i_t = eve::as_integer_t<v_t>;\n  using I_t = eve::wide<i_t, eve::cardinal_t<T>>;\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(I_t(0), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(I_t(2), eve::inf(eve::as<T>())), T(0), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(I_t(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n  // large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(I_t(3), T(1500)),  T(std__cyl_bessel_yn(3, v_t(1500))),  3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(I_t(2), T(500)),   T(std__cyl_bessel_yn(2, v_t(500))),   3.0);\n  // forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(I_t(2), T(10)),    T(std__cyl_bessel_yn(2, v_t(10)))   , 35.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(I_t(3), T(5)),     T(std__cyl_bessel_yn(3, v_t(5)))    , 35.0);\n  // serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(I_t(2), T(0.1)),   T(std__cyl_bessel_yn(2, v_t(0.1)))  , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(I_t(3), T(0.2)),   T(std__cyl_bessel_yn(3, v_t(0.2)))  , 3.0);\n  // besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(I_t(10), T(8)),   T(std__cyl_bessel_yn(10, v_t(8)))   , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(I_t(10), T(8)),   T(std__cyl_bessel_yn(10, v_t(8)))   , 3.0);\n\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(n, a0),   map(std__cyl_bessel_yn, n, a0)   , 20.0);\n  TTS_ULP_EQUAL(map(eve__cyl_bessel_yn, n, a0),   map(std__cyl_bessel_yn, n, a0)   , 20.0);\n\n};\n\n//==================================================================================================\n//== non integral orders\n//==================================================================================================\nEVE_TEST( \"Check behavior of cyl_bessel_yn on wide with non integral order\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(0.0, 10.0)\n        , eve::test::randoms(0.0, 2000.0))\n        )\n  <typename T>(T n, T a0 )\n{\n  using v_t = eve::element_type_t<T>;\n\n  auto eve__cyl_bessel_yn =  [](auto n, auto x) { return eve::cyl_bessel_yn(n, x); };\n  auto std__cyl_bessel_yn =  [](auto n, auto x)->v_t { return boost::math::cyl_neumann(n, x); };\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(2.5), eve::inf(eve::as<T>())), T(0), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n  // large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(3.5), T(1500)),  T(std__cyl_bessel_yn(v_t(3.5), v_t(1500))),  3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(2.5), T(500)),   T(std__cyl_bessel_yn(v_t(2.5), v_t(500))),   3.0);\n  // forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(2.5), T(10)),    T(std__cyl_bessel_yn(v_t(2.5), v_t(10)))   , 35.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(3.5), T(5)),     T(std__cyl_bessel_yn(v_t(3.5), v_t(5)))    , 35.0);\n  // serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(2.5), T(0.1)),   T(std__cyl_bessel_yn(v_t(2.5), v_t(0.1)))  , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(3.5), T(0.2)),   T(std__cyl_bessel_yn(v_t(3.5), v_t(0.2)))  , 2.5);\n  // besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(10.5), T(8)),   T(std__cyl_bessel_yn(v_t(10.5), v_t(8)))   , 3.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_yn(T(10.5), T(8)),   T(std__cyl_bessel_yn(v_t(10.5), v_t(8)))   , 3.0);\n\n  TTS_RELATIVE_EQUAL(eve__cyl_bessel_yn(n, a0),   map(std__cyl_bessel_yn, n, a0)   , 0.001);\n};\n\nEVE_TEST( \"Check behavior of cyl_bessel_yn on wide with negative non integral order\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(0.0, 10.0)\n                             , eve::test::randoms(0.0, 60.0))\n        )\n  <typename T>(T n, T a0 )\n{\n  using v_t = eve::element_type_t<T>;\n  auto eve__diff_bessel_yn =  [](auto n, auto x) { return eve::diff(eve::cyl_bessel_yn)(n, x); };\n  auto std__diff_bessel_yn =  [](auto n, auto x)->v_t { return boost::math::cyl_neumann_prime(n, x); };\n  TTS_RELATIVE_EQUAL(eve__diff_bessel_yn(n, a0),   map(std__diff_bessel_yn, n, a0)   , 1.0e-2);\n};\n", "meta": {"hexsha": "fe8b762d7f20751e49fbf90832f5bff9d8488663", "size": 10468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/bessel/cyl_bessel_yn.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/bessel/cyl_bessel_yn.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/bessel/cyl_bessel_yn.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": 55.3862433862, "max_line_length": 105, "alphanum_fraction": 0.6050821551, "num_tokens": 4363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5271896330025934}}
{"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    @ingroup group-trigonometric\n    This function object returns the atan2pi function : atan2 in pi multiples.\n\n\n    @par Header <boost/simd/function/atan2pi.hpp>\n\n    @par Note\n\n      For every parameters of same floating type `atan2pi(y, x)`\n      is similar  to: `atan2(y, x)/Pi`\n\n\n    @see atan2,  atan2pi\n\n    @par Example:\n\n      @snippet atan2pi.cpp atan2pi\n\n    @par Possible output:\n\n      @snippet atan2pi.txt atan2pi\n\n  **/\n  IEEEValue atan2pi(IEEEValue const& y, const IEEEValue& x);\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": "37376785cc40c776be3b89c6fee02a9710440eae", "size": 1176, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/atan2pi.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/function/atan2pi.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/function/atan2pi.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": 23.52, "max_line_length": 100, "alphanum_fraction": 0.5918367347, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.527189632106513}}
{"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/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\nint main(int argc, char** argv) \n{\n    using namespace mtl;\n\n    using cblock= mtl::vector<double, dim<2> >;\n    using rblock= mtl::vector<double, dim<2>, row_major >; \n\n    using mtype= matrix<rblock, sparse>;\n    using vtype= mtl::vector<cblock>;\n\n    mtype A(2, 3);\n    {\n\tmat::inserter<mtype> ins(A);\n\t\n\tins[0][0] << rblock{1, 3};\n\tins[1][1] << rblock{4, 9};\n    }\n    cout << \"A = \\n\" << A;\n\n    vtype x{cblock{1, 3}, cblock{1, 2}, cblock{9, 3}};\n    cout << \"x = \" << x << endl;\n\n    mtl::vector<double> y( A * x );\n    cout << \"y= \" << y << endl;\n\n    return 0;\n}\n \n", "meta": {"hexsha": "75d91844730ff94d09850a5dc2bc82efaf64a946", "size": 1099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/block_matrix_2x1.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/block_matrix_2x1.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/block_matrix_2x1.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.3829787234, "max_line_length": 94, "alphanum_fraction": 0.6087352138, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5271896267397481}}
{"text": "// permutation_iterator.hpp\n//\n// Generates all permutations of the {0,...n-1} element universe.\n// The generation algorithm used is from the standard library.\n\n#ifndef PERMUTATION_ITERATOR_HPP\n#define PERMUTATION_ITERATOR_HPP\n\n#include <cstdint>\n#include <numeric>\n#include <algorithm>\n#include <type_traits>\n#include <vector>\n#include <cassert>\n\n#include <boost/iterator/iterator_facade.hpp>\n\ntemplate <typename T>\nclass permutation_iterator\n\t: public boost::iterator_facade <\n\tpermutation_iterator<T>,\n\tconst std::vector<T>&,\n\tboost::forward_traversal_tag\n\t>\n{\nprivate:\n\tstatic_assert(std::is_integral<T>::value, \"T must be integral\");\n\npublic:\n\tpermutation_iterator() : end_(true), perm_() { }\n\n\texplicit permutation_iterator(int n) : end_(false), perm_(n)\n\t{\n\t\tstd::iota(perm_.begin(), perm_.end(), 0);\n\t}\n\nprivate:\n\tfriend class boost::iterator_core_access;\n\n\tvoid increment()\n\t{\n\t\tend_ = !std::next_permutation(perm_.begin(), perm_.end());\n\t}\n\n\tbool equal(const permutation_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 perm_;\n\t}\n\n\tbool end_;\n\tstd::vector<T> perm_;\n};\n\n#endif\n", "meta": {"hexsha": "3de8e324cd6e34f2ee2904fcf4463acd2bae1f03", "size": 1152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "permutation_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": "permutation_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": "permutation_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.2, "max_line_length": 65, "alphanum_fraction": 0.7239583333, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.5271896128747954}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2020, Jesus Tordesillas Torres, Aerospace Controls Laboratory\n * Massachusetts Institute of Technology\n * All Rights Reserved\n * Authors: Jesus Tordesillas, et al.\n * See LICENSE file for the license information\n * -------------------------------------------------------------------------- */\n\n// Class JPS Manager\n#include \"ros/ros.h\"\n// Convex Decomposition includes\n#include <decomp_ros_utils/data_ros_utils.h>\n#include <decomp_util/ellipsoid_decomp.h>\n#include <decomp_util/seed_decomp.h>\n\n#include \"read_map.hpp\"\n#include <jps_basis/data_utils.h>\n#include <jps_planner/jps_planner/jps_planner.h>\n\n#include <Eigen/Dense>\n\n#include \"utils.hpp\"\n\n#include <mutex>\n\nclass JPS_Manager\n{\npublic:\n  JPS_Manager();\n\n  std::mutex mtx_jps_map_util;  // mutex for map_util_ and planner_ptr_\n\n  std::shared_ptr<JPS::VoxelMapUtil> map_util_;\n  std::unique_ptr<JPSPlanner3D> planner_ptr_;\n\n  vec_Vec3f vec_o_;   // Vector that contains the occupied points\n  vec_Vec3f vec_uo_;  // Vector that contains the unkown and occupied points\n\n  // JPS\n  void updateJPSMap(pcl::PointCloud<pcl::PointXYZ>::Ptr pclptr, Eigen::Vector3d& center);\n  vec_Vecf<3> solveJPS3D(Vec3f& start, Vec3f& goal, bool* solved, int i);\n  void setNumCells(int cells_x, int cells_y, int cells_z);\n\n  // Convex Decomposition\n  void cvxEllipsoidDecomp(vec_Vecf<3>& path, int type_space, std::vector<LinearConstraint3D>& l_constraints,\n                          vec_E<Polyhedron<3>>& poly_out);\n\n  void setResolution(double res);\n  void setFactorJPS(double factor_jps);\n  void setInflationJPS(double inflation_jps);\n\n  void setZGroundAndZMax(double z_ground, double z_max);\n  void setVisual(bool visual);\n  void setDroneRadius(double inflation_jps);\n\nprivate:\n  double factor_jps_, res_, inflation_jps_, z_ground_, z_max_, drone_radius_;\n  int cells_x_, cells_y_, cells_z_;\n  bool visual_;\n  EllipsoidDecomp3D ellip_decomp_util_;\n};", "meta": {"hexsha": "a746e03630d26f64eb713d6a5aeb043d0e418964", "size": 1981, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "faster/include/jps_manager.hpp", "max_stars_repo_name": "wyr501/faster", "max_stars_repo_head_hexsha": "df92802a72b1e5d2acf0682d0772d14a56bf56ab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 489.0, "max_stars_repo_stars_event_min_datetime": "2020-03-19T15:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:22:55.000Z", "max_issues_repo_path": "faster/include/jps_manager.hpp", "max_issues_repo_name": "wyr501/faster", "max_issues_repo_head_hexsha": "df92802a72b1e5d2acf0682d0772d14a56bf56ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2020-05-08T13:51:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T07:43:21.000Z", "max_forks_repo_path": "faster/include/jps_manager.hpp", "max_forks_repo_name": "wyr501/faster", "max_forks_repo_head_hexsha": "df92802a72b1e5d2acf0682d0772d14a56bf56ab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 116.0, "max_forks_repo_forks_event_min_datetime": "2020-03-19T20:37:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T03:51:21.000Z", "avg_line_length": 32.4754098361, "max_line_length": 108, "alphanum_fraction": 0.698637052, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919830720203, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5271896034805271}}
{"text": "#include \"hello.h\"\n\n#include <Eigen/Dense>\n\nnamespace voltlbx\n{\n    \n    int add(int i, int j)\n    {        \n        return i + j;\n    }\n\n    using Matrix = Eigen::MatrixXd;\n    using Vector = Eigen::VectorXd;\n    void test_eigen()\n    {\n        Matrix m1 = Matrix::Zero(2, 2);\n        m1(0, 0) = 3.0;\n        m1(1, 1) = 50.0;\n\n        Vector v(2);\n        v(0) = 1.0;\n        v(1) = 1.0;\n\n        auto r = m1 * v;       \n    }\n\n}\n", "meta": {"hexsha": "a1a18ac555d16297a0cec2f6e685b0d856a934be", "size": 431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/voltlbx/hello.cpp", "max_stars_repo_name": "quintron/vol-toolbox", "max_stars_repo_head_hexsha": "0bddb66c0160da1fb9393c60f6a99600311bbcf9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/voltlbx/hello.cpp", "max_issues_repo_name": "quintron/vol-toolbox", "max_issues_repo_head_hexsha": "0bddb66c0160da1fb9393c60f6a99600311bbcf9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/voltlbx/hello.cpp", "max_forks_repo_name": "quintron/vol-toolbox", "max_forks_repo_head_hexsha": "0bddb66c0160da1fb9393c60f6a99600311bbcf9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-18T17:56:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-18T17:56:09.000Z", "avg_line_length": 14.8620689655, "max_line_length": 39, "alphanum_fraction": 0.43387471, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.5271760062358546}}
{"text": "#include <gtest/gtest.h> \n#include \"../include/model.h\"\n#include <math.h>\n#include \"../include/Eigen.h\" \n#include <vector>\n#include <stdexcept>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/operators.hpp>\n\n\n#include <iostream>\n\n//Testing continuousSolverRK4<double> and continuousModel<double>\n//---tests to make sure continuousSolverRK4<T>.solve(double t) does not\n//accept values with t < 0 (can't solve back in time)\n//---tests to make sure that RK4 method can solve basic heat equation PDE\n//correctly according to exact solution while testing that the solved\n//state and updated current time are properly stored  \nTEST(continuousSolverRK4, RK4Test){\n\n\tdouble exponent = -0.1;\n\tclass testModel: public continuousModel<double>{\n\t\tpublic:\n\t\t\tdouble function(const double & val, const double time) const override{\n\t\t\t\tdouble rhs = -0.1*val;\n\t\t\t\treturn rhs;\n\t\t\t}\n\t};\n\ttestModel instance;\n\n\tdouble initialCondition = 100;\n\tdouble initialTime = 0;\n\tcontinuousSolverRK4<double> testModelSolver(&instance,initialTime,initialCondition,0.001);\n\n\tdouble times[9] = {0,1,1,1,1,1,1,1,1};\n\tint length = 9;\n\t//assert time can't be negative\n\tdouble rollingSum = 0;\n\tfor(int i=0; i<length; i++){\n\t\trollingSum+=times[i];\n\t\ttestModelSolver.solve(times[i]);\n\t\tASSERT_NEAR(rollingSum,testModelSolver.getCurrentTime(),1e-6);\n\t\tASSERT_NEAR(exp(exponent*rollingSum)*initialCondition,testModelSolver.getCurrentState(),1e-6);\n\t\tif(i!=length-1){continue;}\n\t}\n\tASSERT_THROW(testModelSolver.solve(-1),std::out_of_range);\n}\n\n//CUSTOM VECTOR CLASS\t\nclass customVector{\n\tprivate:\n\t\tstd::vector<double> entries;\n\tpublic:\n\t\tint getSize() const{\n\t\t\treturn entries.size();\n\t\t}\n\t\t\n\t\tdouble getValueAtIndex(int i) const{\n\t\t\tif(i < 0 || i >= getSize()){\n\t\t\t\tthrow std::out_of_range(\"\");\n\t\t\t}\n\t\t\treturn entries[i];\n\t\t}\n\t\tvoid setValueAtIndex(int i, double value){\n\t\t\tif(i < 0 || i >= getSize()){\n\t\t\t\tthrow std::out_of_range(\"\");\n\t\t\t}\n\t\t\tentries[i] = value;\n\t\t}\n\n\t\tcustomVector(const std::vector<double> & vec){\n\t\t\tif(vec.size() == 0){\n\t\t\t\tthrow std::out_of_range(\"\");\n\t\t\t}\n\t\t\tentries = vec;\n\t\t}\n\n\t\tcustomVector(int size){\n\t\t\tif(size <= 0){\n\t\t\t\tthrow std::out_of_range(\"\");\n\t\t\t}\n\t\t\tentries = std::vector<double>(size);\n\t\t}\n};\n\n\ncustomVector operator+(const customVector &lhs,const customVector &rhs){\n\tif(lhs.getSize() != rhs.getSize()){\n\t\tthrow std::range_error(\"\");\t\n\t}\n\tcustomVector res(rhs.getSize());\n\tfor(int i = 0; i < lhs.getSize(); i++){\n\t\tres.setValueAtIndex(i,lhs.getValueAtIndex(i)+rhs.getValueAtIndex(i));\n\t}\n\treturn res;\n};\n\ncustomVector operator*(const double &lhs, const customVector &rhs){\n\tcustomVector res(rhs.getSize());\n\tfor(int i = 0; i < rhs.getSize(); i++){\n\t\tres.setValueAtIndex(i,rhs.getValueAtIndex(i)*lhs);\n\t}\n\treturn res;\n}\n\n\nTEST(continuousSolverRK4,differentLibraryTest){\n\tclass testModel: public continuousModel<customVector>{\n\t\tpublic:\n\t\tcustomVector function(const customVector & val, const double time) const{\n\t\t\tcustomVector result(2);\n\t\t\tresult.setValueAtIndex(0,-0.1*val.getValueAtIndex(0));\n\t\t\tresult.setValueAtIndex(1,-0.2*val.getValueAtIndex(1));\n\t\t\treturn result;\n\t\t}\n\t};\n\ttestModel instance;\n\tstd::vector<double> t;\n\tt.push_back(100);t.push_back(100);\n\tcustomVector initialCondition(t);\n\tdouble initialTime = 0;\n\tcontinuousSolverRK4<customVector> testModelSolver(&instance,initialTime,initialCondition,1);\n\n\tclass testModel2: public continuousModel<Eigen::VectorXd>{\n\t\tprivate:\n\t\t\tEigen::MatrixXd modelMatrix;\n\t\tpublic:\n\t\t\ttestModel2(){\n\t\t\t\tEigen::MatrixXd tmp(2,2);\n\t\t\t\ttmp<<-0.1,0,0,-0.2;\n\t\t\t\tmodelMatrix = tmp;\n\t\t\t}\n\t\t\tEigen::VectorXd function(const Eigen::VectorXd & val, const double time) const{\n\t\t\t\tEigen::VectorXd gg = modelMatrix*val;\n\t\t\t\treturn modelMatrix*val;\n\t\t\t}\n\t};\n\n\ttestModel2 instance2;;\n\tEigen::VectorXd initialCondition2(2); initialCondition2<<100,100;\n\tinstance2.function(initialCondition2,0.0);\n\tcontinuousSolverRK4<Eigen::VectorXd> testModelSolver2(&instance2,initialTime,initialCondition2,1);\n\n\n/*\n\tclass testModel3: public continuousModel<boost::numeric::ublas::vector<double>>{\n\t\tprivate:\n\t\t\tboost::numeric::ublas::matrix<double> modelMatrix;\n\t\tpublic:\n\t\t\ttestModel3(){\n\t\t\t\tboost::numeric::ublas::matrix<double> tmp(2,2);\n\t\t\t\ttmp(0,0) = -0.1;\n\t\t\t\ttmp(0,1) = 0;\n\t\t\t\ttmp(1,0) = 0;\n\t\t\t\ttmp(1,1) = -0.2;\n\t\t\t\tmodelMatrix = tmp;\n\t\t\t}\n\t\t\tboost::numeric::ublas::vector<double>function(boost::numeric::ublas::vector<double> & val,const double time)const{\n\t\t\t\t//modelMatrix*val;\n\t\t\t\treturn prod(modelMatrix,val);\n\t\t\t}\n\t};\n\n\ttestModel3 instance3 = testModel3();\n\tboost::numeric::ublas::vector<double> initialCondition3(2); initialCondition3(0) = 100; initialCondition3(1) = 100;\n\tcontinuousSolverRK4<boost::numeric::ublas::vector<double>> testModelSolver3(&instance3,initialTime,initialCondition3,0.001);\n*/\t\n\n\tdouble times[9] = {0,1,1,1,1,1,1,1,1};\n\tint length = 9;\n\tdouble rollingSum = 0;\n\tfor(int i=0; i<length; i++){\n\t\trollingSum+=times[i];\n\t\ttestModelSolver.solve(times[i]);\n\t\ttestModelSolver2.solve(times[i]);\n\t\tEigen::VectorXd tmp2 = testModelSolver2.getCurrentState();\n\t\tdouble tmp3 = tmp2[0]; \n\t\tdouble tmp4 = tmp2[1];\n\t\tASSERT_NEAR(testModelSolver.getCurrentState().getValueAtIndex(0),tmp3,1e-9);\n\t\tASSERT_NEAR(testModelSolver.getCurrentState().getValueAtIndex(1),tmp4,1e-9);\n\t}\n\tASSERT_THROW(testModelSolver.solve(-1),std::out_of_range);\n}\n\nint main(int argc, char **argv){\n\ttesting::InitGoogleTest(&argc, argv);\n\treturn RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "5ebfbd3849dcfbfb7d4678bc1610b26db557c180", "size": 5426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++_implementation/tests/tests.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/tests.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/tests.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": 28.5578947368, "max_line_length": 125, "alphanum_fraction": 0.7051234795, "num_tokens": 1512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5271759853861603}}
{"text": "#include <armadillo>\n#include \"electronic.hpp\"\n\n\n/*\n  From NR 17.1.3 and A&S 25.5.10. For systems of the form $i \\hbar\n  \\dot{c} = H c$, advances c using a 4th order Runge-Kutta integrator\n*/\n// FIXME: Returns different results than exact propagation\nvoid Electronic::advance_rk4(const arma::cx_mat &H, double dt){\n  const std::complex<double> midt(0,-dt);\n\n  k1 = midt * H * amplitudes;\n  k2 = midt * H * (amplitudes + (k1 / 2));\n  k3 = midt * H * (amplitudes - (k1 / 3) + k2);\n  k4 = midt * H * (amplitudes + (k1    ) - k2 + k3);\n\n  amplitudes = amplitudes + (k1 / 6) + (k2 / 3) + (k3 / 3) + (k4 / 6);\n}\n\n\nvoid Electronic::advance_exact(const arma::cx_mat &H, double dt){\n  const std::complex<double> midt(0,-dt);\n  amplitudes = arma::expmat(midt * H) * amplitudes;\n}\n\n\nvoid Electronic::reserve(void){\n  auto s = arma::size(amplitudes);\n  k1.set_size(s);\n  k2.set_size(s);\n  k3.set_size(s);\n  k4.set_size(s);\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*/\nvoid Electronic::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;\n}\n\n/*\n  Implements Zeyu Zhou et al. JCTC 2020, 16, 835--846\n\n  Approximately minimizes Tr[log(U)^2] via jacobi sweeps while\n  enforcing det(U) == 1\n\n  Results agree with the matricies in the paper's Appendix D\n*/\nvoid Electronic::phase_match(arma::mat &U, bool do_unitarize){\n  // Step 1: det(U) == 1\n  if (do_unitarize){\n    unitarize(U);\n  }\n  if (arma::det(U) < 0){\n    U.col(0) *= -1.0;\n  }\n\n  // Step 2: Jacobi sweeps\n  double deljk, Ujj, Ukk;\n\n  const arma::uword N = U.n_rows;\n  bool change;\n  do{\n    change = false;\n    for (arma::uword j = 0; j < N; j++){\n      for (arma::uword k = j + 1; k < N; k++){\n\tUjj = U(j,j);\n\tUkk = U(k,k);\n\t// Eq. 34 with the sum implemented as a dot product\n\tdeljk =\n            3*(Ujj*Ujj + Ukk*Ukk)\n\t  + 6*(U(j,k)*U(k,j))\n\t  + 8*(Ujj + Ukk)\n\t  - 3*(arma::as_scalar(U.row(j)*U.col(j) + U.row(k)*U.col(k)));\n\tif (deljk < 0){\n\t  U.col(j) *= -1.0;\n\t  U.col(k) *= -1.0;\n          change = true;\n\t}\n      }\n    }\n  }while(change);\n}\n\nvoid Electronic::phase_match(arma::cx_mat &U, bool do_unitarize){\n  (void) U;\n  (void) do_unitarize;\n  throw std::runtime_error(\"complex phase matching not implemented\");\n}\n", "meta": {"hexsha": "f34f11d0b76d017c272f83214dad5ffb965c4336", "size": 2725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gifs_src/electronic.cpp", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-11T19:48:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T19:48:20.000Z", "max_issues_repo_path": "gifs_src/electronic.cpp", "max_issues_repo_name": "farajilab/gifs_release", "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gifs_src/electronic.cpp", "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "avg_line_length": 24.7727272727, "max_line_length": 70, "alphanum_fraction": 0.6099082569, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5271717289831612}}
{"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, gamma_p) {\n  using stan::math::gamma_p;\n\n  EXPECT_FLOAT_EQ(0.63212055, gamma_p(1.0, 1.0));\n  EXPECT_FLOAT_EQ(0.82755178, gamma_p(0.1, 0.1));\n  EXPECT_FLOAT_EQ(0.76189667, gamma_p(3.0, 4.0));\n  EXPECT_FLOAT_EQ(0.35276812, gamma_p(4.0, 3.0));\n  EXPECT_THROW(gamma_p(-4.0, 3.0), std::domain_error);\n  EXPECT_THROW(gamma_p(4.0, -3.0), std::domain_error);\n}\n\nTEST(MathFunctions, gamma_p_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::gamma_p(1.0, nan));\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::gamma_p(nan, 1.0));\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::gamma_p(nan, nan));\n}\n", "meta": {"hexsha": "2a4a22bdedc01ca3534936713381c737b309ac86", "size": 830, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/gamma_p_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/gamma_p_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/gamma_p_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9230769231, "max_line_length": 74, "alphanum_fraction": 0.7096385542, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5270915979498927}}
{"text": "//==================================================================================================\n/*!\n  @file\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_ERFCX_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ERFCX_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n  @ingroup group-euler\n    Function object implementing erfcx capabilities\n\n   Computes the  underflow-compensating (scaled) error function:\n   \\f$\\displaystyle e^{x^2}\\frac{2}{\\sqrt\\pi}\\int_0^{x} e^{-t^2}\\mbox{d}t\\f$\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = erfcx(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = exp(sqr(x))*erfc(x);\n    @endcode\n\n    But avoid underflow as much as possible.\n\n    @see erfc, erf\n\n  **/\n  const boost::dispatch::functor<tag::erfcx_> erfcx = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/erfcx.hpp>\n#include <boost/simd/function/simd/erfcx.hpp>\n\n#endif\n", "meta": {"hexsha": "dbcc4743990c141e27ba2278994861aff57e77a9", "size": 1231, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/erfcx.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/erfcx.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/erfcx.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": 23.6730769231, "max_line_length": 100, "alphanum_fraction": 0.5808285946, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.527087395724413}}
{"text": "#include <gtest/gtest.h>\n#include <boost/lexical_cast.hpp>\n\n#include \"base/eigen2hdf.hpp\"\n#include \"fft/fft2.hpp\"\n#include \"fft/fft2_r2c.hpp\"\n#include \"ridgelet/construction/translation_grid.hpp\"\n#include \"ridgelet/ridgelet_cell_array.hpp\"\n#include \"ridgelet/ridgelet_frame.hpp\"\n#include \"ridgelet/rt.hpp\"\n\nusing namespace std;\n\n/**\n *  @brief test rt -> irt\n *\n *  performs tests for PlannerR2COD\n *\n *  @param param\n *  @return return type\n */\nTEST(base, rt)\n{\n  typedef RT<double, RidgeletFrame, FFTr2c<PlannerR2COD> > rt_t;\n  typedef typename rt_t::numeric_t numeric_t;\n  typedef typename rt_t::complex_array_t complex_array_t;\n  typedef typename rt_t::fft_t fft_t;\n  typedef typename rt_t::rt_coeff_t rt_coeff_t;\n  fft_t fft;\n  double tol = 1e-15;\n\n  int J = 7;\n\n  unsigned int rho_x = 1;\n  unsigned int rho_y = 1;\n\n  for (int j = 0; j < J; ++j) {\n    RidgeletFrame rf(J, J, rho_x, rho_y);\n    unsigned int Nx = rf.Nx();\n    unsigned int Ny = rf.Ny();\n    rt_t rt(rf);\n\n    typedef Eigen::Array<numeric_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> array_t;\n    array_t R(Nx, Ny);\n    R.setRandom();\n\n    std::vector<rt_coeff_t> rt_coeffs(rf.size());\n\n    complex_array_t Fh(Nx, Ny);\n    fft.ft(Fh, R);\n    rt.rt(rt_coeffs, Fh);\n\n    // check that tgrid_dim is correct\n    auto& lambdas = rf.lambdas();\n    for (unsigned int i = 0; i < lambdas.size(); ++i) {\n      auto tt = tgrid_dim(lambdas[i], rf);\n      int rows = rt_coeffs[i].rows();\n      int cols = rt_coeffs[i].cols();\n\n      EXPECT_EQ(rows * cols, std::get<0>(tt) * std::get<1>(tt)) << lambdas[i];\n      // EXPECT_EQ(rows, std::get<0>(tt)) << lambdas[i];\n      // EXPECT_EQ(cols, std::get<1>(tt)) << lambdas[i];\n    }\n\n    complex_array_t Fh2(Nx, Ny);\n    rt.irt(Fh2, rt_coeffs);\n\n    // check that is invertible\n    array_t DIFF = (ftcut(Fh2, Nx / 2, Ny / 2) - ftcut(Fh, Nx / 2, Ny / 2)).abs();\n    double dmax = DIFF.maxCoeff();\n    EXPECT_TRUE(dmax < tol) << dmax;\n  }\n}\n\n/**\n *  @brief test rt -> irt\n *\n *  performs tests for PlannerR2COD\n *\n *  @param param\n *  @return return type\n */\nTEST(base, rt_planned)\n{\n  typedef RT<double, RidgeletFrame, FFTr2c<PlannerR2C> > rt_t;\n  typedef typename rt_t::numeric_t numeric_t;\n  typedef typename rt_t::complex_array_t complex_array_t;\n  typedef typename rt_t::fft_t fft_t;\n  typedef typename rt_t::rt_coeff_t rt_coeff_t;\n  fft_t fft;\n  double tol = 1e-15;\n\n  int J = 7;\n\n  unsigned int rho_x = 1;\n  unsigned int rho_y = 1;\n\n  for (int j = 0; j < J; ++j) {\n    RidgeletFrame rf(J, J, rho_x, rho_y);\n    unsigned int Nx = rf.Nx();\n    unsigned int Ny = rf.Ny();\n    rt_t rt(rf);\n    init_fftw(fft, FFTW_MEASURE, rf);\n\n    typedef Eigen::Array<numeric_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> array_t;\n    array_t R(Nx, Ny);\n    R.setRandom();\n\n    std::vector<rt_coeff_t> rt_coeffs(rf.size());\n\n    complex_array_t Fh(Nx, Ny);\n    fft.ft(Fh, R);\n    rt.rt(rt_coeffs, Fh);\n\n    // check that tgrid_dim is correct\n    auto& lambdas = rf.lambdas();\n    for (unsigned int i = 0; i < lambdas.size(); ++i) {\n      auto tt = tgrid_dim(lambdas[i], rf);\n      int rows = rt_coeffs[i].rows();\n      int cols = rt_coeffs[i].cols();\n\n      EXPECT_EQ(rows * cols, std::get<0>(tt) * std::get<1>(tt)) << lambdas[i];\n      // EXPECT_EQ(rows, std::get<0>(tt)) << lambdas[i];\n      // EXPECT_EQ(cols, std::get<1>(tt)) << lambdas[i];\n    }\n\n    complex_array_t Fh2(Nx, Ny);\n    rt.irt(Fh2, rt_coeffs);\n\n    // check that is invertible\n    array_t DIFF = (ftcut(Fh2, Nx / 2, Ny / 2) - ftcut(Fh, Nx / 2, Ny / 2)).abs();\n    double dmax = DIFF.maxCoeff();\n    EXPECT_TRUE(dmax < tol) << dmax;\n  }\n}\n\n\n\n\n/**\n *  @brief check that rt transform is invertible if the Fourier coefficients are padded by zeros.\n *  (the zero-padding is done to have invertibility on the entire grid)\n *  Detailed description\n *\n *  @param param\n *  @return return type\n */\nTEST(base, rt_padded)\n{\n  typedef RT<double, RidgeletFrame, FFTr2c<PlannerR2COD> > rt_t;\n  typedef typename rt_t::numeric_t numeric_t;\n  typedef typename rt_t::complex_array_t complex_array_t;\n  typedef typename rt_t::fft_t fft_t;\n  typedef typename rt_t::rt_coeff_t rt_coeff_t;\n  fft_t fft;\n  double tol = 1e-15;\n\n  int J = 6;\n\n  unsigned int rho_x = 1;\n  unsigned int rho_y = 1;\n\n  for (int j = 0; j < J; ++j) {\n    RidgeletFrame rf(J, J, rho_x, rho_y);\n    unsigned int Nx = rf.Nx();\n    unsigned int Ny = rf.Ny();\n    unsigned int nx = Nx / 2;\n    unsigned int ny = Ny / 2;\n    rt_t rt(rf);\n\n    typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> array_t;\n    array_t R(nx, ny);\n    R.setRandom();\n\n    std::vector<rt_coeff_t> rt_coeffs(rf.size());\n\n    complex_array_t Fh0(nx, ny);\n    fft.ft(Fh0, R);\n    // set lowest frequency to zero (e.g. make sure that the Fourier series is\n    // real-valued also on the fine grid)\n    hf_zero(Fh0);\n\n    complex_array_t Fh(Nx, Ny);\n    Fh.setZero();\n    ftcut(Fh, nx, ny) = Fh0;\n\n    rt.rt(rt_coeffs, Fh);\n\n    // check that tgrid_dim is correct\n    auto& lambdas = rf.lambdas();\n    for (unsigned int i = 0; i < lambdas.size(); ++i) {\n      auto tt = tgrid_dim(lambdas[i], rf);\n      int rows = rt_coeffs[i].rows();\n      int cols = rt_coeffs[i].cols();\n\n      EXPECT_EQ(rows * cols, std::get<0>(tt) * std::get<1>(tt)) << lambdas[i];\n\n      // EXPECT_EQ(rows, std::get<0>(tt)) << lambdas[i];\n      // EXPECT_EQ(cols, std::get<1>(tt)) << lambdas[i];\n    }\n\n    complex_array_t Fhp(Nx, Ny);\n    rt.irt(Fhp, rt_coeffs);\n\n    complex_array_t Fhp0(nx, ny);\n    Fhp0 = ftcut(Fhp, nx, ny);\n\n    std::string fname = \"base_rt_padded\" + boost::lexical_cast<std::string>(j) + \".h5\";\n    hid_t h5f = H5Fcreate(fname.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n    eigen2hdf::save(h5f, \"Fh0\", Fh0);\n    eigen2hdf::save(h5f, \"Fh\", Fh);\n    eigen2hdf::save(h5f, \"Fhp\", Fhp);\n    H5Fclose(h5f);\n\n    // check that is invertible\n    array_t DIFF = (Fhp0 - Fh0).abs();\n    double dmax = DIFF.maxCoeff();\n    EXPECT_TRUE(dmax < tol) << dmax;\n  }\n}\n\n// todo check irt, when ft coeffs are padded\n", "meta": {"hexsha": "0b054bac202b37b68ed757c580dc371723be3531", "size": 6014, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gtest/gtest_rt.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/gtest/gtest_rt.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/gtest/gtest_rt.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.9686098655, "max_line_length": 97, "alphanum_fraction": 0.6265380778, "num_tokens": 1947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5270873857857311}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TOOLBOX_HYPERBOLIC_FUNCTIONS_SCALAR_SINHCOSH_HPP_INCLUDED\n#define NT2_TOOLBOX_HYPERBOLIC_FUNCTIONS_SCALAR_SINHCOSH_HPP_INCLUDED\n\n#include <nt2/toolbox/hyperbolic/functions/sinhcosh.hpp>\n#include <nt2/include/functions/scalar/tofloat.hpp>\n#include <nt2/include/functions/scalar/expm1.hpp>\n#include <nt2/include/functions/scalar/negif.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/oneplus.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/is_negative.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/sdk/meta/as_logical.hpp>\n#include <nt2/sdk/meta/as_floating.hpp>\n#include <boost/fusion/tuple.hpp>\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION(  nt2::tag::sinhcosh_, tag::cpu_,(A0)(A1)\n                               , ((scalar_<arithmetic_<A0> >))\n                                 ((scalar_<floating_<A1> >))\n                                 ((scalar_<floating_<A1> >))\n                             )\n  {\n    typedef int result_type;\n    inline result_type operator()(A0 const& a0,A1 & a1,A1 & a2) const\n    {\n      a2 =  nt2::abs(a0);\n      a1 = a0;\n      if (a2 == Inf<A1>()) return 0;\n      const A1 u = expm1(a2);\n      const A1 up1 = oneplus(u);\n      const A1 tmp =u/up1;\n      a1 = negif(is_negative(a0), Half<A1>()*tmp*(oneplus(up1)));\n      a2 = oneplus(Half<A1>()*tmp*u);\n      return 0;\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::sinhcosh_, tag::cpu_,(A0)(A1),\n                             ((scalar_ < arithmetic_<A0> > ))\n                             ((scalar_ < floating_<A1> > ))\n                             )\n    {\n    typedef A1 result_type;\n    inline result_type operator()(A0 const& a0,A1 & a2) const\n    {\n      A1 a1;\n      sinhcosh(tofloat(a0),a1, a2);\n      return a1;\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::sinhcosh_, tag::cpu_,\n                         (A0),\n                         ((scalar_<arithmetic_<A0> >))\n                        )\n  {\n      typedef typename meta::as_floating<A0>::type  rtype;\n      typedef boost::fusion::tuple<rtype, rtype> result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      result_type res;\n      sinhcosh(tofloat(a0), boost::fusion::at_c<0>(res),\n                 boost::fusion::at_c<1>(res));\n      return res;\n    }\n  };\n} }\n#endif\n", "meta": {"hexsha": "dd183f601b8a143f0f66ab4e9dfb4351c1330442", "size": 2882, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/hyperbolic/include/nt2/toolbox/hyperbolic/functions/scalar/sinhcosh.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/hyperbolic/include/nt2/toolbox/hyperbolic/functions/scalar/sinhcosh.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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": "modules/core/hyperbolic/include/nt2/toolbox/hyperbolic/functions/scalar/sinhcosh.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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.5802469136, "max_line_length": 80, "alphanum_fraction": 0.5582928522, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.5270873799127296}}
{"text": "//\n// Created by Hamza El-Kebir on 5/9/21.\n//\n\n#ifndef LODESTAR_DISCRETELQE_HPP\n#define LODESTAR_DISCRETELQE_HPP\n\n#include \"Lodestar/synthesis/AlgebraicRiccatiEquation.hpp\"\n#include <Eigen/QR>\n#include <vector>\n\nnamespace ls {\n    namespace filter {\n        class DiscreteLQE {\n            static Eigen::MatrixXd\n            infiniteHorizon(const Eigen::MatrixXd &A,\n                            const Eigen::MatrixXd &B,\n                            const Eigen::MatrixXd &Q,\n                            const Eigen::MatrixXd &C,\n                            const Eigen::MatrixXd &R);\n\n            static Eigen::MatrixXd\n            infiniteHorizon(const systems::StateSpace<> &sys,\n                            const Eigen::MatrixXd &Q,\n                            const Eigen::MatrixXd &R);\n\n            static Eigen::MatrixXd\n            finiteHorizon(const Eigen::MatrixXd &A,\n                          const Eigen::MatrixXd &B,\n                          const Eigen::MatrixXd &C,\n                          const Eigen::MatrixXd &Q,\n                          const Eigen::MatrixXd &R,\n                          unsigned int N = 5);\n\n            static Eigen::MatrixXd\n            finiteHorizon(const systems::StateSpace<> &sys,\n                          const Eigen::MatrixXd &Q,\n                          const Eigen::MatrixXd &R,\n                          unsigned int N = 5);\n        };\n    }\n}\n\n#endif //LODESTAR_DISCRETELQE_HPP\n", "meta": {"hexsha": "ec0806de484a8d5e2fd14a1102c1c2974d32c2e3", "size": 1435, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lodestar/filter/DiscreteLQE.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/filter/DiscreteLQE.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/filter/DiscreteLQE.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.8888888889, "max_line_length": 61, "alphanum_fraction": 0.4947735192, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5270316336977001}}
{"text": "#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <Eigen/Geometry>\n#include <Inventor/SoDB.h>\n#include <Inventor/SoOutput.h>\n#include <Inventor/actions/SoWriteAction.h>\n#include <Inventor/VRMLnodes/SoVRMLInline.h>\n#include <Inventor/VRMLnodes/SoVRMLTransform.h>\n\nint\nmain(int argc, char** argv)\n{\n\tif (argc != 3)\n\t{\n\t\tstd::cerr << \"Usage: csv2wrl [input.csv] [output.wrl]\" << std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\t\n\tSoDB::init();\n\t\n\tSoVRMLTransform* root = new SoVRMLTransform();\n\troot->ref();\n\t\n\tstd::fstream input;\n\tinput.open(argv[1]);\n\t\n\tfor (std::string line; std::getline(input, line);)\n\t{\n\t\tstd::istringstream stream(line);\n\t\t\n\t\tstd::string name;\n\t\tstd::getline(stream, name, ',');\n\t\t\n\t\tstd::string number;\n\t\tstd::getline(stream, number, ',');\n\t\tdouble x = std::atof(number.c_str());\n\t\tstd::getline(stream, number, ',');\n\t\tdouble y = std::atof(number.c_str());\n\t\tstd::getline(stream, number, ',');\n\t\tdouble z = std::atof(number.c_str());\n\t\tstd::getline(stream, number, ',');\n\t\tdouble a = std::atof(number.c_str());\n\t\tstd::getline(stream, number, ',');\n\t\tdouble b = std::atof(number.c_str());\n\t\tstd::getline(stream, number, ',');\n\t\tdouble c = std::atof(number.c_str());\n\t\t\n\t\tEigen::AngleAxis<double> rotation(\n\t\t\tEigen::AngleAxis<double>(c * static_cast<double>(M_PI) / 180, Eigen::Vector3d::UnitZ()) *\n\t\t\tEigen::AngleAxis<double>(b * static_cast<double>(M_PI) / 180, Eigen::Vector3d::UnitY()) *\n\t\t\tEigen::AngleAxis<double>(a * static_cast<double>(M_PI) / 180, Eigen::Vector3d::UnitX())\n\t\t);\n\t\t\n\t\tSoVRMLTransform* vrmlTransform = new SoVRMLTransform();\n\t\tvrmlTransform->setName(name.c_str());\n\t\tvrmlTransform->rotation.setValue(SbVec3f(rotation.axis().x(), rotation.axis().y(), rotation.axis().z()), rotation.angle());\n\t\tvrmlTransform->translation.setValue(x / 1000, y / 1000, z / 1000);\n\t\tSoVRMLInline* vrmlInline = new SoVRMLInline();\n\t\tvrmlInline->url.setValue(std::string(name + \".wrl\").c_str());\n\t\tvrmlTransform->addChild(vrmlInline);\n\t\troot->addChild(vrmlTransform);\n\t}\n\t\n\tinput.close();\n\t\n\tSoOutput output;\n\toutput.openFile(argv[2]);\n\toutput.setHeaderString(\"#VRML V2.0 utf8\");\n\tSoWriteAction writeAction(&output);\n\twriteAction.apply(root);\n\toutput.closeFile();\n\t\n\troot->unref();\n\t\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "3280cf94c9ea0905d10fd92e21bf9328d0452138", "size": 2291, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extras/csv2wrl/csv2wrl.cpp", "max_stars_repo_name": "Roboy/rl", "max_stars_repo_head_hexsha": "7686cbd5f9c3630daa6d972f2244ed31f4dc5142", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 568.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T03:38:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:12:56.000Z", "max_issues_repo_path": "extras/csv2wrl/csv2wrl.cpp", "max_issues_repo_name": "jencureboy/rl", "max_issues_repo_head_hexsha": "658cdd8387397261ebf0f52d3bde74aae0379e24", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-03-23T13:16:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T05:58:06.000Z", "max_forks_repo_path": "extras/csv2wrl/csv2wrl.cpp", "max_forks_repo_name": "jencureboy/rl", "max_forks_repo_head_hexsha": "658cdd8387397261ebf0f52d3bde74aae0379e24", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 169.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T12:59:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T13:44:54.000Z", "avg_line_length": 28.2839506173, "max_line_length": 125, "alphanum_fraction": 0.6769969446, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5270316299578897}}
{"text": "\n\n\n#ifndef HELPERSDNA \n#define HELPERSDNA\n\n#include <boost/operators.hpp>\n#include <iostream>\n#include <ostream>\n#include <boost/bimap.hpp>\n#include <string>\n#include <map>\n#include<vector>\n\nusing namespace std;\n\n\ntemplate<class uint>\nunsigned degree(uint v){ \n\tuint r = 0;\n\twhile (v >>= 1) {\n\t\tr++;\n\t}\n\treturn r;\n}\n\n\ntemplate<class cf_t> \nostream &operator<<(ostream &stream, const vector<cf_t>& x) \n{ \n\tfor(unsigned i = 0; i<x.size(); ++i) stream << x[i] << \"  \";\n\treturn stream; // must return stream \n}; \n\n\n\ntemplate<class vectt>\nunsigned hamming_distance(vectt& v1,vectt& v2){\n\tassert(v1.size()=v2.size());\n\tunsigned hd = 0;\n\tfor(unsigned i=0;i<v1.size();++i)\n\t\tif(v1[i] != v2[i]) hd++;\n\treturn hd;\n}\n\ntemplate<class vectt>\nvoid flipvecdir(vectt& v){\n\tvectt tmp = v;\n\tfor(unsigned i=0;i<v.size();++i){\n\t\tv[i] = tmp[v.size()-1-i];\n\t}\n}\n\n\n// convert decimal number to a number with another base\n// nu: \t\tan unsigned integer\n// base: \tbase of the new representation\n// size: \tsize of the vector required for the new representation\ntemplate<class base_t>\nvector<base_t> tobase(uint64_t nu, uint64_t base, unsigned size){\n\t\n\tvector<base_t> nn(size,(base_t) 0 ); \n\tif(nu == 0) return nn;\n\t\n\tuint64_t div = nu;\n\tunsigned i = 0;\n\twhile(div != 0){\n\t\t//nn[i] = base_t(div % base); // rest\n\t\tassert( i < nn.size() );\n\t\tnn[i] = base_t(div % base);\n\t\tdiv = div/base;\t\n\t\ti++;\n\t}\n\t\n\treturn nn;\n};\n\n\n// convert vector of numbers in some basis to decimal number\ntemplate<class base_t>\nuint64_t frombase(const vector<base_t>& nn,uint64_t base){\n\tunsigned deg = degree(base);\n\t\n\tassert(deg*nn.size() < 64); // otherwise we have an overflow below\n\t\n\tuint64_t nu = 0;\n\tuint64_t basepow = 1;\n\tfor(unsigned i=0;i<nn.size();++i){\n\t\tuint64_t adf = nn[i];\n\t\tnu += ((uint64_t)adf) * basepow;//((unsigned) (adf)) * ((int) pow((double) base,(int) i));\n\t\tbasepow *= base;\n\t}\n\treturn nu;\n};\n\n\ntemplate<class GFM,class GFN>\nvoid GFM2GFN(vector<GFM>& from, vector<GFN>& to){\n\t// choose a and b as smallest numbers such that a*m == b*n\n\tunsigned a = 1;\n\tunsigned b = 1;\n\twhile (a*GFM::m != b*GFN::m){\n\t\tif(a*GFM::m < b*GFN::m)\n\t\t\ta += 1;\n\t\telse\n\t\t\tb += 1;\t\n\t}\n\twhile( (from.size() % a) != 0 ) from.push_back(GFM(0));\n    to.resize(0);\n    // every a entries of `from' are mapped to b entries of `to'\n\tfor(unsigned i=0;i<from.size()/a; ++i){\n\t\t// the unsigned char type below is important, otherwise errors occur when converting..\n\t\tvector<uint> ind;\n\t\tfor(typename vector<GFM>::iterator it = from.begin()+i*a; it != from.begin()+i*a+a; ++it){\n\t\t\tind.push_back(it->el);\n\t\t}\t\t\n\t\tunsigned mm = GFM::m;\n\t\tassert(mm < 64);\n\t\tuint64_t powmm = 1;\n\t\tpowmm = powmm << mm;\n\t\tuint64_t pownm = 1;\n\t\tunsigned nm = GFN::m;\n\t\tassert(nm < 64);\n\t\tpownm = pownm << nm;\n\t\tint64_t\tindec = frombase( ind , powmm );     \n        vector<uint> tmpvec = tobase<uint>(indec, pownm ,b);\n\t\tfor(uint j : tmpvec)\n\t\t\tto.push_back(GFN(j,0));\n\t\t//to.insert(to.begin()+i*b,tmpvec.begin(),tmpvec.end());\n\t}\n};\n\n\ntemplate<class uint,unsigned m, unsigned n>\nvoid gfm2gfn(vector<uint>& from, vector<uint>& to){\n\t// choose a and b as smallest numbers such that a*m == b*n\n\tunsigned a = 1;\n\tunsigned b = 1;\n\twhile (a*m != b*n){\n\t\tif(a*m < b*n)\n\t\t\ta += 1;\n\t\telse\n\t\t\tb += 1;\t\n\t}\n\twhile((from.size() % a) != 0 ) from.push_back(0);\n   \n    to.resize(0);\n    // every a entries of `from' are maped to three entries of `to'\n\tfor(unsigned i=0;i<from.size()/a; ++i){\n        // the unsigned char type below is important, otherwise errors occur when converting..\n\t\tunsigned indec = frombase(vector<unsigned char>(from.begin()+i*a, from.begin()+i*a+a), 1<<m );       \n        vector<uint> tmpvec = tobase<uint>(indec,1<<n,b);\n        to.insert(to.begin()+i*b,tmpvec.begin(),tmpvec.end());\n\t}\n};\n\n\n\n\n// converts each 2 characters in data_char to 3 elements of GF(47), which are appended at \ntemplate<class pfe>\nvoid char2pfe(string& data_char, vector<pfe>& data_b47){\n    if((data_char.size() % 2) != 0 ) data_char.push_back('\\n');\n   \n    data_b47.resize(0);\n\t// convert vector of char to vector with base 47;\n    // every 2 char's are coded to three pfe's \n    for(unsigned i=0;i<data_char.size()/2; ++i){\n        // the unsigned char type below is important, otherwise errors occur when converting..\n\t\tunsigned indec = frombase(vector<unsigned char>(data_char.begin()+i*2, data_char.begin()+i*2+2),256);\n        \n        vector<pfe> tmpvec = tobase<pfe>(indec,47,3);\n        data_b47.insert(data_b47.begin()+i*3,tmpvec.begin(),tmpvec.end());\n\t}\n};\n\n\ntemplate<class pfe>\nvoid pfe2char(string& data_char, vector<pfe>& data_b47){\n    \n    assert(data_b47.size() % 3  == 0);\n\n    data_char.resize(2*(data_char.size()/3) );\n    // convert vector of char to vector with base 47;\n    // every 2 char's are coded to three pfe's \n    for(unsigned i=0;i<data_b47.size()/3; ++i){\n        unsigned indec = frombase(vector<pfe>(data_b47.begin()+i*3, data_b47.begin()+i*3+3),47);\n        \n        vector<char> tmpvec = tobase<char>(indec,256,2);\n        data_char.insert(data_char.begin()+i*2,tmpvec.begin(),tmpvec.end());\n    }\n\n};\n\n\n\n\n/*\nmaps each element of GF2M to a string with letters {A,C,G,T}\n*/\n\ntemplate<class GF>\nclass DNAmapGF{\npublic: \n\tDNAmapGF(){assert(GF::m % 2 == 0);};\t\n\t// codeword to DNA fragment\n\tvoid cw2frag(const vector<GF>& cw, string& frag ){\n\t\tfrag.resize(0);\n\t\tfor(GF gf: cw){\n\t\t\tfor(unsigned i=0; i<GF::m; i+=2){\n\t\t\t\tswitch( (gf.el >> i) & 3 ) { // shift by two, and then check the bits..\n    \t\t\t\tcase 0 : frag.append(\"A\");\n\t\t\t\t\t\t\t break;\n\t\t\t\t\tcase 1 : frag.append(\"C\"); \n\t\t\t\t\t\t\t break;\n\t\t\t\t\tcase 2 : frag.append(\"G\");\n\t\t\t\t\t\t\t break;\n\t\t\t\t\tcase 3 : frag.append(\"T\");\n\t\t\t\t\t\t\t break;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// DNA fragment to codeword\n\tvoid frag2cw(vector<GF>& cw, const string& frag ){\n\t\tassert( (frag.size() % (GF::m/2)) == 0 );\n\t\tcw.resize( frag.size() / (GF::m/2) );\n\t\tfor(unsigned i=0;i<cw.size();++i){ \n\t\t\ttypename GF::uint el = 0;\n\t\t\tfor(unsigned j=0; j<GF::m/2; j++){\n\t\t\t\tswitch(frag[i*GF::m/2 + j]){\t\n    \t\t\t\tcase 'A' :  // add zero..  \n\t\t\t\t\t\t\t break;\n\t\t\t\t\tcase 'C' : el += ((typename GF::uint) 1) << 2*j ;\n\t\t\t\t\t\t\t break;\n\t\t\t\t\tcase 'G' : el += ((typename GF::uint) 2) << 2*j ;\n\t\t\t\t\t\t\t break;\n\t\t\t\t\tcase 'T' : el += ((typename GF::uint) 3) << 2*j ;\n\t\t\t\t\t\t\t break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcw[i] = GF(el,0);\n\t\t}\n\t}\n};\n\n\n\n\n\n\n/*\nmaps each element of GF(47) to a string with letters {A,C,G,T}\n*/\n\ntemplate<class PFE>\nclass DNAmap{\nprivate: \n\t//typedef boost::bimap< PFE , std::string > mapdna_type;\n\t//mapdna_type mapdna;\n\t\n\tmap<PFE,string> pfetostr;\n\tmap<string,PFE> strtopfe;\n\npublic: \n\tDNAmap(){\n\t\t//initialize map\n\t\tunsigned prime = 47;\n\t\t\n\t\tchar nucl[] = \"ACGT\"; // nucleotides\t\n\n\t\tvector<string> allpos(4*4*4);\n\t\tfor(unsigned i=0;i<allpos.size();++i){\n\t\t\tchar cur[] = \"AAA\";\n\t\t\tcur[0] = nucl[i % 4];\n\t\t\tcur[1] = nucl[(i/4) % 4];\n\t\t\tcur[2] = nucl[(i/16) % 4];\n\t\t\tallpos[i] = string(cur);\n\t\t}\n\t\t\n\t\tunsigned j = 0;\n\t\tfor(unsigned i=0;i<prime;++i){\n\t\t\twhile( allpos[j][1] == allpos[j][2]) j++;\n\t\t\t//mapdna.insert( typename mapdna_type::value_type(PFE(i), allpos[j] ));\n\t\t\tpfetostr[PFE(i)] = allpos[j];\n\t\t\tstrtopfe[allpos[j]] = PFE(i);\n\t\t\t\n\t\t\tj++;\n\t\t}\n\t\t//print_map(mapdna.right, \" \", cout);\n\t}\n\t\n\t// codeword to DNA fragment\n\tvoid cw2frag(const vector<PFE>& cw, string& frag ){\n\t\tfrag.resize(0);\n\t\tfor(unsigned i=0;i<cw.size();++i){\n\t\t\tfrag.append(pfetostr[cw[i]]); //mapdna.left.at(cw[i]); \n\t\t}\n\t}\n\t\n\t// DNA fragment to codeword\n\tvoid frag2cw(vector<PFE>& cw, const string& frag ){\n\t\tassert( (frag.size() % 3) == 0   );\n\t\tcw.resize(frag.size()/3);\n\t\tfor(unsigned i=0;i<cw.size();++i){ \n\t\t\n\t\t\t//char charartmp[] = \"AAA\"; // nucleotides\t\n\t\t\t//charartmp[0] = frag[i*3];\n\t\t\t//charartmp[1] = frag[i*3+1];\n\t\t\t//charartmp[2] = frag[i*3+2];\n\t\t\t//string tmp(charartmp);\n\t\t\tstring tmp = string(frag.begin()+i*3, frag.begin()+i*3+3  );\n\t\t\t\t\n\t\t\t//print_map(mapdna.right, \" \", cout);\n\t\t\t\n\t\t\t//cout <<  mapdna.right.at(tmp )  << endl; \n\t\t\t//cw[i] = PFE( mapdna.right.at(tmp ) ); \n\t\t\tcw[i] = strtopfe[tmp];\n\t\t\t//cout << cw[i] << endl;\n\t\t}\n\t}\n};\n\nvoid fliplett(string& frag){\n    for(unsigned i=0;i<frag.size();++i){\n        switch(frag[i]){\n            case 'T': frag[i] = 'A';\n                break;\n            case 'A': frag[i] = 'T';\n                break;\n            case 'G': frag[i] = 'C';\n                break;\n            case 'C': frag[i] = 'G';\n                break;\n        }\n    }\n}\n\n\n#endif\n", "meta": {"hexsha": "cc6533ffbccae3dbac0fa5ab61a78a393f2d4be8", "size": 8321, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/helpers.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/helpers.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/helpers.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": 24.3304093567, "max_line_length": 103, "alphanum_fraction": 0.5855065497, "num_tokens": 2719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5270316284968799}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2013   MetaScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_META_PREV_POWER_OF_2_HPP_INCLUDED\n#define BOOST_SIMD_META_PREV_POWER_OF_2_HPP_INCLUDED\n\n/*!\n  @file\n  @brief Defines and implements prev_power_of_2 and prev_power_of_2_c\n**/\n\n#include <boost/mpl/integral_c.hpp>\n#include <boost/mpl/size_t.hpp>\n#include <cstddef>\n\nnamespace boost { namespace simd {  namespace details\n{\n  // Adaptation of :\n  // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2\n  template<std::size_t N> struct prev_power_of_2_impl\n  {\n    BOOST_STATIC_CONSTANT(std::size_t, x0    = N               );\n    BOOST_STATIC_CONSTANT(std::size_t, x1    = x0 | (x0 >>  1) );\n    BOOST_STATIC_CONSTANT(std::size_t, x2    = x1 | (x1 >>  2) );\n    BOOST_STATIC_CONSTANT(std::size_t, x3    = x2 | (x2 >>  4) );\n    BOOST_STATIC_CONSTANT(std::size_t, x4    = x3 | (x3 >>  8) );\n    BOOST_STATIC_CONSTANT(std::size_t, x5    = x4 | (x4 >> 16) );\n    BOOST_STATIC_CONSTANT(std::size_t, value = (x5 >> 1) + 1   );\n  };\n\n  // Requried for MSVC\n  template<> struct prev_power_of_2_impl<0>\n  {\n    BOOST_STATIC_CONSTANT(std::size_t, value = 0 );\n  };\n} } }\n\nnamespace boost { namespace simd {  namespace meta\n{\n  /*!\n    @brief Evaluates previous power of two\n\n    Computes the power of two lesser or equal to any given integral value @c N.\n\n    @par Semantic:\n    For any given integral value @c N:\n\n    @code\n    typedef prev_power_of_2_c<N>::type r;\n    @endcode\n\n    is equivalent to:\n\n    @code\n    typedef mpl::size_t<M> r;\n    @endcode\n\n    Where @c M is lesser or equal to N and so that it exists a given @c P so\n    that @c M is equal to two at the power of @c P.\n\n    @usage{meta/prev_power_of_2_c.cpp}\n\n    @tparam N Integral constant to downgrade\n  **/\n  template<std::size_t N> struct  prev_power_of_2_c\n#if !defined(DOXYGEN_ONLY)\n        : boost::mpl::size_t<details::prev_power_of_2_impl<N>::value>\n#endif\n  {};\n\n  /*!\n    @brief Evaluates previous power of two\n\n    Computes the power of two lesser or equal to any given @mplint @c N.\n\n    @par Semantic:\n    For any given @mplint @c N:\n\n    @code\n    typedef prev_power_of_2<N>::type r;\n    @endcode\n\n    is equivalent to:\n\n    @code\n    typedef prev_power_of_2<N::value>::type r;\n    @endcode\n\n    @par Models:\n\n    @metafunction\n\n    @usage{meta/prev_power_of_2.cpp}\n\n    @tparam N @mplint to downgrade\n  **/\n  template<typename N> struct  prev_power_of_2\n#if !defined(DOXYGEN_ONLY)\n        : boost::mpl::integral_c< typename N::value_type\n                                , details::prev_power_of_2_impl<N::value>::value\n                                >\n#endif\n  {};\n} } }\n\n#endif\n", "meta": {"hexsha": "ef275a1aeffa77096516517d8b9ea3648a061f3e", "size": 3143, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/include/boost/simd/meta/prev_power_of_2.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/sdk/include/boost/simd/meta/prev_power_of_2.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/boost/simd/sdk/include/boost/simd/meta/prev_power_of_2.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 27.814159292, "max_line_length": 80, "alphanum_fraction": 0.6064269806, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5270316284968798}}
{"text": "#include \"main.h\"\n\n#include <Eigen/CXX11/Tensor>\n\nusing Eigen::Tensor;\n\nstatic void test_single_voxel_patch()\n{\n  Tensor<float, 5> tensor(4,2,3,5,7);\n  tensor.setRandom();\n  Tensor<float, 5, RowMajor> tensor_row_major = tensor.swap_layout();\n\n  Tensor<float, 6> single_voxel_patch;\n  single_voxel_patch = tensor.extract_volume_patches(1, 1, 1);\n  VERIFY_IS_EQUAL(single_voxel_patch.dimension(0), 4);\n  VERIFY_IS_EQUAL(single_voxel_patch.dimension(1), 1);\n  VERIFY_IS_EQUAL(single_voxel_patch.dimension(2), 1);\n  VERIFY_IS_EQUAL(single_voxel_patch.dimension(3), 1);\n  VERIFY_IS_EQUAL(single_voxel_patch.dimension(4), 2 * 3 * 5);\n  VERIFY_IS_EQUAL(single_voxel_patch.dimension(5), 7);\n\n  Tensor<float, 6, RowMajor> single_voxel_patch_row_major;\n  single_voxel_patch_row_major = tensor_row_major.extract_volume_patches(1, 1, 1);\n  VERIFY_IS_EQUAL(single_voxel_patch_row_major.dimension(0), 7);\n  VERIFY_IS_EQUAL(single_voxel_patch_row_major.dimension(1), 2 * 3 * 5);\n  VERIFY_IS_EQUAL(single_voxel_patch_row_major.dimension(2), 1);\n  VERIFY_IS_EQUAL(single_voxel_patch_row_major.dimension(3), 1);\n  VERIFY_IS_EQUAL(single_voxel_patch_row_major.dimension(4), 1);\n  VERIFY_IS_EQUAL(single_voxel_patch_row_major.dimension(5), 4);\n\n  for (int i = 0; i < tensor.size(); ++i) {\n    VERIFY_IS_EQUAL(tensor.data()[i], single_voxel_patch.data()[i]);\n    VERIFY_IS_EQUAL(tensor_row_major.data()[i], single_voxel_patch_row_major.data()[i]);\n    VERIFY_IS_EQUAL(tensor.data()[i], tensor_row_major.data()[i]);\n  }\n}\n\n\nstatic void test_entire_volume_patch()\n{\n  const int depth = 4;\n  const int patch_z = 2;\n  const int patch_y = 3;\n  const int patch_x = 5;\n  const int batch = 7;\n\n  Tensor<float, 5> tensor(depth, patch_z, patch_y, patch_x, batch);\n  tensor.setRandom();\n  Tensor<float, 5, RowMajor> tensor_row_major = tensor.swap_layout();\n\n  Tensor<float, 6> entire_volume_patch;\n  entire_volume_patch = tensor.extract_volume_patches(patch_z, patch_y, patch_x);\n  VERIFY_IS_EQUAL(entire_volume_patch.dimension(0), depth);\n  VERIFY_IS_EQUAL(entire_volume_patch.dimension(1), patch_z);\n  VERIFY_IS_EQUAL(entire_volume_patch.dimension(2), patch_y);\n  VERIFY_IS_EQUAL(entire_volume_patch.dimension(3), patch_x);\n  VERIFY_IS_EQUAL(entire_volume_patch.dimension(4), patch_z * patch_y * patch_x);\n  VERIFY_IS_EQUAL(entire_volume_patch.dimension(5), batch);\n\n  Tensor<float, 6, RowMajor> entire_volume_patch_row_major;\n  entire_volume_patch_row_major = tensor_row_major.extract_volume_patches(patch_z, patch_y, patch_x);\n  VERIFY_IS_EQUAL(entire_volume_patch_row_major.dimension(0), batch);\n  VERIFY_IS_EQUAL(entire_volume_patch_row_major.dimension(1), patch_z * patch_y * patch_x);\n  VERIFY_IS_EQUAL(entire_volume_patch_row_major.dimension(2), patch_x);\n  VERIFY_IS_EQUAL(entire_volume_patch_row_major.dimension(3), patch_y);\n  VERIFY_IS_EQUAL(entire_volume_patch_row_major.dimension(4), patch_z);\n  VERIFY_IS_EQUAL(entire_volume_patch_row_major.dimension(5), depth);\n\n  const int dz = patch_z - 1;\n  const int dy = patch_y - 1;\n  const int dx = patch_x - 1;\n\n  const int forward_pad_z = dz - dz / 2;\n  const int forward_pad_y = dy - dy / 2;\n  const int forward_pad_x = dx - dx / 2;\n\n  for (int pz = 0; pz < patch_z; pz++) {\n    for (int py = 0; py < patch_y; py++) {\n      for (int px = 0; px < patch_x; px++) {\n        const int patchId = pz + patch_z * (py + px * patch_y);\n        for (int z = 0; z < patch_z; z++) {\n          for (int y = 0; y < patch_y; y++) {\n            for (int x = 0; x < patch_x; x++) {\n              for (int b = 0; b < batch; b++) {\n                for (int d = 0; d < depth; d++) {\n                  float expected = 0.0f;\n                  float expected_row_major = 0.0f;\n                  const int eff_z = z - forward_pad_z + pz;\n                  const int eff_y = y - forward_pad_y + py;\n                  const int eff_x = x - forward_pad_x + px;\n                  if (eff_z >= 0 && eff_y >= 0 && eff_x >= 0 &&\n                      eff_z < patch_z && eff_y < patch_y && eff_x < patch_x) {\n                    expected = tensor(d, eff_z, eff_y, eff_x, b);\n                    expected_row_major = tensor_row_major(b, eff_x, eff_y, eff_z, d);\n                  }\n                  VERIFY_IS_EQUAL(entire_volume_patch(d, z, y, x, patchId, b), expected);\n                  VERIFY_IS_EQUAL(entire_volume_patch_row_major(b, patchId, x, y, z, d), expected_row_major);\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid test_cxx11_tensor_volume_patch()\n{\n  CALL_SUBTEST(test_single_voxel_patch());\n  CALL_SUBTEST(test_entire_volume_patch());\n}\n", "meta": {"hexsha": "ca6840f3bfe127d7d52a92e48e146582ae9b9bf1", "size": 4599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/unsupported/test/cxx11_tensor_volume_patch.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/unsupported/test/cxx11_tensor_volume_patch.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1057.0, "max_issues_repo_issues_event_min_datetime": "2015-04-27T04:27:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:14:59.000Z", "max_forks_repo_path": "src/Eigen-3.3/unsupported/test/cxx11_tensor_volume_patch.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 40.6991150442, "max_line_length": 109, "alphanum_fraction": 0.6764514025, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5270316232960595}}
{"text": "#ifndef MPP_HAMILTONIAN_CLASSIC_HAMILTONIAN_HPP\n#define MPP_HAMILTONIAN_CLASSIC_HAMILTONIAN_HPP\n\n#include <exception>\n#include <sstream>\n#include <string>\n#include <random>\n#include <type_traits>\n#include <cmath>\n#include <functional>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/assert.hpp>\n#include <mpp/config.hpp>\n#include <mpp/chains/mcmc_chain.hpp>\n#include <mpp/hamiltonian/kinetic_energy_multivar_normal.hpp>\n\nnamespace mpp { namespace hamiltonian {\n\ntemplate<class real_scalar_type>\nclass hmc_sampler\n{\npublic:\n    typedef boost::numeric::ublas::vector<real_scalar_type> real_vector_type;\n    typedef mpp::chains::mcmc_chain<real_scalar_type> chain_type;\n    typedef std::mt19937 rng_type;\n    typedef std::uniform_real_distribution<real_scalar_type> uni_real_dist_type;\n    typedef std::uniform_int_distribution<size_t> uni_int_dist_type;\n    typedef mpp::hamiltonian::multivariate_normal<\n        real_scalar_type> kinetic_energy_type;\n\n    typedef typename std::function<\n        real_scalar_type (real_vector_type const &) > log_post_func_type;\n\n    typedef typename std::function<\n        real_vector_type (real_vector_type const &)> grad_log_post_func_type;\n\n    static_assert(\n        std::is_floating_point<real_scalar_type>::value,\n        \"The real scalar is expected to be a floating point type.\"\n    );\n\n    hmc_sampler (\n        log_post_func_type & log_posterior,\n        grad_log_post_func_type & grad_log_posterior,\n        size_t const num_dims,\n        size_t const max_num_steps,\n        real_scalar_type const max_eps,\n        real_vector_type const & inv_mass_mat\n    ) throw()\n    : m_log_posterior(log_posterior)\n    , m_grad_log_posterior(grad_log_posterior)\n    , m_num_dims(num_dims)\n    , m_max_num_steps(max_num_steps)\n    , m_max_eps(max_eps)\n    , m_inv_mass_mat(inv_mass_mat)\n    , m_beta(1)\n    ,m_acc_rate(0) {\n\n        if( m_num_dims == size_t(0) ) {\n            std::stringstream msg;\n            msg << \"The number of dimensions = \"\n                << m_num_dims\n                << \" should be greater than zero.\";\n            throw std::length_error(msg.str());\n        }\n\n        BOOST_ASSERT_MSG(\n            m_num_dims <= size_t(MPP_MAXIMUM_NUMBER_OF_DIMENSIONS),\n            \"num_dims too big. Please modify the config.hpp and recompile.\"\n        );\n\n        if( m_max_num_steps == size_t(0) ) {\n            std::stringstream msg;\n            msg << \"Maximum number of steps = \"\n                << m_max_num_steps\n                << \" in the discretisation of Hamiltonian should be\"\n                << \" greater than zero.\";\n            throw std::length_error(msg.str());\n        }\n\n        BOOST_ASSERT_MSG(\n            m_max_num_steps <= size_t(MPP_CLASSIC_HAMILTONIAN_MAX_NUM_STEPS),\n            \"max_num_steps too big. Please modify the config.hpp and recompile.\"\n        );\n\n        if( m_max_eps <= real_scalar_type(0)\n            or m_max_eps > real_scalar_type(1)) {\n            std::stringstream msg;\n            msg << \"Maximum value of epsilon = \"\n                << m_max_eps\n                << \" in the discretisation of Hamiltonian should be\"\n                << \" in the intervale (0,1].\";\n            throw std::domain_error(msg.str());\n        }\n\n    }\n\n    chain_type run_sampler(size_t const num_samples,\n        real_vector_type const & start_point) throw() {\n        BOOST_ASSERT_MSG(\n            num_samples <=\n                size_t(MPP_MAXIMUM_NUMBER_OF_SAMPLES_PER_RUN_SAMPLER_CALL),\n            \"num_samples too big. Please modify the config and recompile.\"\n        );\n\n        chain_type hmc_chain(num_samples,m_num_dims);\n        uni_real_dist_type uni_real_dist;\n        uni_int_dist_type uni_int_dist( size_t(1),m_max_num_steps+size_t(1) );\n        kinetic_energy_type kin_eng(m_inv_mass_mat);\n        real_vector_type q_1(start_point);\n        size_t num_accepted(0);\n        size_t num_rejected(0);\n        while( num_accepted < num_samples ) {\n            real_vector_type q_0(q_1);\n            real_scalar_type const eps = m_max_eps*uni_real_dist(m_rng);\n            size_t const num_steps = uni_int_dist(m_rng);\n            real_vector_type p_0 = kin_eng.generate_sample(m_rng);\n\n            real_scalar_type const h_0 = -m_log_posterior(q_0)\n                -kin_eng.log_posterior(p_0);\n            leap_frog(m_grad_log_posterior,kin_eng,q_0,p_0,eps,num_steps);\n            real_scalar_type const log_post_val = m_log_posterior(q_0);\n            real_scalar_type const h_1 = -log_post_val\n                -kin_eng.log_posterior(p_0);\n            real_scalar_type const delta_h = h_1 - h_0;\n\n            if( not std::isfinite(delta_h) ) {\n                std::stringstream msg;\n                msg << \"delta(H) value is not finite\";\n                throw std::out_of_range(msg.str());\n            }\n            real_scalar_type const uni_rand = uni_real_dist(m_rng);\n            if(std::log(uni_rand) < -delta_h*m_beta) {\n                q_1 = q_0;\n                hmc_chain.set_sample(num_accepted,q_1,log_post_val);\n                ++num_accepted;\n            }\n            else {\n                ++num_rejected;\n            }\n        }\n\n        m_acc_rate = real_scalar_type(num_accepted)\n            / real_scalar_type(num_accepted + num_rejected);\n\n        return hmc_chain;\n    }\n\n    inline real_scalar_type acc_rate() const {\n        return m_acc_rate;\n    }\n\nprivate:\n\n    static void leap_frog(\n        grad_log_post_func_type & grad_log_posterior,\n        kinetic_energy_type & kin_eng,\n        real_vector_type & q,\n        real_vector_type & p,\n        real_scalar_type const eps,\n        size_t const num_steps\n    ) {\n        BOOST_ASSERT_MSG(\n            num_steps <= size_t(MPP_CLASSIC_HAMILTONIAN_MAX_NUM_STEPS),\n            \"m_max_num_steps too big. Please modify the config and recompile.\"\n        );\n\n        BOOST_ASSERT_MSG(\n            eps > real_scalar_type(0) and eps <= real_scalar_type(1),\n            \"epsilon value should be a real number in [0,1]\"\n        );\n\n        BOOST_ASSERT_MSG(\n            p.size() == q.size(),\n            \"p and q should have identical dimensions\"\n        );\n\n        real_vector_type dq = grad_log_posterior(q);\n        real_vector_type dp = kin_eng.grad_log_posterior(p);\n\n        p += 0.5*eps*dq;\n        for(size_t j=0;j<num_steps;++j) {\n            dp = kin_eng.grad_log_posterior(p);\n            q -= eps*dp;\n            dq = grad_log_posterior(q);\n            p += eps*dq;\n        }\n        p -= 0.5*eps*dq;\n    }\n\n    log_post_func_type m_log_posterior;\n    grad_log_post_func_type m_grad_log_posterior;\n    size_t m_num_dims;\n    size_t m_max_num_steps;\n    real_scalar_type m_max_eps;\n    real_vector_type m_inv_mass_mat;\n    rng_type m_rng;\n    real_scalar_type m_beta;\n    real_scalar_type m_acc_rate;\n};\n\n}}\n\n#endif // MPP_HAMILTONIAN_CLASSIC_HAMILTONIAN_HPP\n", "meta": {"hexsha": "8da3e171cb258855751dc1038cada2d0389126c4", "size": 6828, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mpp/hamiltonian/classic_hamiltonian.hpp", "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": "include/mpp/hamiltonian/classic_hamiltonian.hpp", "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": "include/mpp/hamiltonian/classic_hamiltonian.hpp", "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": 33.3073170732, "max_line_length": 80, "alphanum_fraction": 0.6303456356, "num_tokens": 1602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5270316232960595}}
{"text": "#ifndef _INCLUDED_GEOMETRY_HPP_\n#define _INCLUDED_GEOMETRY_HPP_\n/**\n * @file   geometry.hpp\n * @author Aron Ahmadia <aron@casiphia.local>\n * @date   Tue Feb 26 14:43:29 2008\n * \n * @brief  Geometry - A set of static methods to assist in hypersphere decomposition\n * \n * \n */\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n//#include \"boost_ext/ublas_vector.hpp\"\n//#include \"boost_ext/ublas_matrix.hpp\"\n#include <boost/version.hpp>\n\nnamespace smo {\n\n  const double pi = M_PI;\n\n  typedef double PolarAngle;\n  typedef double Area;\n  typedef int DimCount;\n  typedef int PointCount;\n  typedef int RegionCount;\n\n  typedef boost::numeric::ublas::matrix<PolarAngle> Region;\n  typedef boost::numeric::ublas::matrix<PolarAngle> SpherePoints;\n  typedef boost::numeric::ublas::vector<RegionCount> RegionCounts;\n  typedef boost::numeric::ublas::vector<double> CartPoint;\n  typedef boost::numeric::ublas::matrix<double> CartPoints;\n\n  typedef struct {\n    DimCount d;\n    Area capAreaZero;\n  } AreaOfCapP;\n\n  class Geometry\n  {\n  public:\n    /** \n     * Find the angle that encloses the area of a d-dimensional spherical cap embedded in R^{d+1}\n     * \n     * @param d dimension of the sphere\n     * @param capArea area enclosed by the angle\n     * \n     * @return angle that ecloses capArea\n     */\n    static PolarAngle angleOfCap(DimCount d, Area capArea);\n    static PolarAngle polarCap(DimCount d, PointCount n);\n    static Area regionArea(DimCount d, PointCount n);\n    static Area regionArea(DimCount d, Area polarCapArea, PolarAngle phi1, PolarAngle phi2, PointCount n);\n    static Area areaOfCap(DimCount d, PolarAngle capPhi);\n    static Area areaOfCap(PolarAngle capPhi,AreaOfCapP &p);\n    static Area areaOfSphere(DimCount d); \n    static Area areaOfCollar(DimCount d, PolarAngle phi1, PolarAngle phi2); \n    static void bottomCapRegion(DimCount d, PolarAngle capPhi, Region &r);  \n    static void topCapRegion(DimCount d, PolarAngle capPhi, Region &r);\n    static void sphereRegion(DimCount d, Region &r);\n    static PolarAngle circleOffset(PointCount p1, PointCount p2);\n    static void toPolar(CartPoints p, SpherePoints &s);\n    static void toCart(SpherePoints s, CartPoints &p);\n  };\n}\n\n\n\n\n#endif\n", "meta": {"hexsha": "ee3981b857464b399f0b2c58695bb2686bded4f4", "size": 2238, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hyper_sample/utility/geometry.hpp", "max_stars_repo_name": "ahmadia/hypermesh", "max_stars_repo_head_hexsha": "c694d634a8493c94be39488b85aacc2d1b8884e7", "max_stars_repo_licenses": ["MIT"], "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/hyper_sample/utility/geometry.hpp", "max_issues_repo_name": "ahmadia/hypermesh", "max_issues_repo_head_hexsha": "c694d634a8493c94be39488b85aacc2d1b8884e7", "max_issues_repo_licenses": ["MIT"], "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/hyper_sample/utility/geometry.hpp", "max_forks_repo_name": "ahmadia/hypermesh", "max_forks_repo_head_hexsha": "c694d634a8493c94be39488b85aacc2d1b8884e7", "max_forks_repo_licenses": ["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.0833333333, "max_line_length": 106, "alphanum_fraction": 0.7247542449, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5270316195562487}}
{"text": "#include \"gradient.hpp\"\n#include \"gradient_psv.hpp\"\n#include \"gradient_sh.hpp\"\n\n#include <Eigen/Dense>\n#include <exception>\n#include <fmt/format.h>\n#include <memory>\n\nusing namespace Eigen;\nusing grad_psv::GradientPSV;\nusing grad_sh::GradientSH;\n\nGradient::Gradient(const Ref<const ArrayXXd> &model)\n    : model_(model), nl_(model.rows()) {}\n\nGradient::~Gradient() = default;\n\nGradientEval::GradientEval(const Ref<const ArrayXXd> &model,\n                           const std::string &type) {\n  if (type == \"rayleigh\") {\n    grad_ = std::make_unique<GradientPSV>(model);\n  } else if (type == \"love\") {\n    grad_ = std::make_unique<GradientSH>(model);\n  } else {\n    std::string msg = fmt::format(\"type {:s} is invalid.\", type);\n    throw std::runtime_error(msg);\n  }\n}\n\nArrayXd GradientEval::compute(const double freq, const double c) {\n  ArrayXd kvs = grad_->compute(freq, c);\n  return kvs;\n}\n", "meta": {"hexsha": "70ad42f66d4cccce75cd03da5ba63dad1a74fbe6", "size": 893, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/gradient.cc", "max_stars_repo_name": "pan3rock/DisbaTomo", "max_stars_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2021-07-30T03:27:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T14:05:47.000Z", "max_issues_repo_path": "src/gradient.cc", "max_issues_repo_name": "pan3rock/DisbaTomo", "max_issues_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gradient.cc", "max_forks_repo_name": "pan3rock/DisbaTomo", "max_forks_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2021-07-31T12:38:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T15:07:53.000Z", "avg_line_length": 25.5142857143, "max_line_length": 66, "alphanum_fraction": 0.6696528555, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5269317958699512}}
{"text": "#include \"NFmiLambertConformalConicArea.h\"\n#include \"NFmiStringTools.h\"\n#include <boost/functional/hash.hpp>\n#include <fmt/format.h>\n#include <macgyver/Exception.h>\n#include <cmath>\n\nusing namespace std;\n\n// For some reason Boost.Constants does not define quart_pi so we'll just use our own definitions\nnamespace\n{\nconst double pi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286;\nconst double half_pi = pi / 2;\nconst double quart_pi = pi / 4;\n}  // namespace\n\n// ----------------------------------------------------------------------\n/*!\n * Constructor\n */\n// ----------------------------------------------------------------------\n\nNFmiLambertConformalConicArea::NFmiLambertConformalConicArea(const NFmiPoint &theBottomLeftLatLon,\n                                                             const NFmiPoint &theTopRightLatLon,\n                                                             double theCentralLongitude,\n                                                             double theCentralLatitude,\n                                                             double theTrueLatitude1,\n                                                             double theTrueLatitude2,\n                                                             double theRadius,\n                                                             bool usePacificView,\n                                                             const NFmiPoint &theTopLeftXY,\n                                                             const NFmiPoint &theBottomRightXY)\n    : NFmiArea(theTopLeftXY, theBottomRightXY, usePacificView),\n      itsBottomLeftLatLon(theBottomLeftLatLon),\n      itsTopRightLatLon(theTopRightLatLon),\n      itsCentralLongitude(theCentralLongitude),\n      itsCentralLatitude(theCentralLatitude),\n      itsTrueLatitude1(theTrueLatitude1),\n      itsTrueLatitude2(theTrueLatitude2),\n      itsRadius(theRadius)\n{\n  try\n  {\n    Init();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param fKeepWorldRect Undocumented\n */\n// ----------------------------------------------------------------------\n\nvoid NFmiLambertConformalConicArea::Init(bool fKeepWorldRect)\n{\n  try\n  {\n    const double lat1 = FmiRad(itsTrueLatitude1);\n    const double lat2 = FmiRad(itsTrueLatitude2);\n    const double lat0 = FmiRad(itsCentralLatitude);\n\n    if (itsTrueLatitude1 != itsTrueLatitude2)\n      itsN = log(cos(lat1) / cos(lat2)) / log(tan(quart_pi + lat2 / 2) / tan(quart_pi + lat1 / 2));\n    else\n      itsN = sin(lat1);\n\n    itsF = cos(lat1) * pow(tan(quart_pi + lat1 / 2), itsN) / itsN;\n    itsRho0 = itsRadius * itsF / pow(tan(quart_pi + lat0 / 2), itsN);\n\n    if (!fKeepWorldRect)\n      itsWorldRect =\n          NFmiRect(LatLonToWorldXY(itsBottomLeftLatLon), LatLonToWorldXY(itsTopRightLatLon));\n\n    itsXScaleFactor = Width() / itsWorldRect.Width();\n    itsYScaleFactor = Height() / itsWorldRect.Height();\n\n    const char *fmt =\n        \"+proj=lcc +lat_1={} +lat_2={} +lat_0={} +lon_0={} +x_0=0 +y_0=0 +R={} +units=m +wktext \"\n        \"+no_defs +type=crs\";\n    itsProjStr = fmt::format(fmt,\n                             itsTrueLatitude1,\n                             itsTrueLatitude2,\n                             itsCentralLatitude,\n                             itsCentralLongitude,\n                             itsRadius);\n    itsSpatialReference = std::make_shared<Fmi::SpatialReference>(itsProjStr);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theBottomLeftLatLon Undocumented\n * \\param theTopRightLatLon Undocumented\n * \\return Undocumented\n * \\todo Should return an boost::shared_ptr instead\n */\n// ----------------------------------------------------------------------\n\nNFmiArea *NFmiLambertConformalConicArea::NewArea(const NFmiPoint &theBottomLeftLatLon,\n                                                 const NFmiPoint &theTopRightLatLon,\n                                                 bool allowPacificFix) const\n{\n  try\n  {\n    if (allowPacificFix)\n    {\n      PacificPointFixerData fixedPointData =\n          NFmiArea::PacificPointFixer(theBottomLeftLatLon, theTopRightLatLon);\n      return new NFmiLambertConformalConicArea(fixedPointData.itsBottomLeftLatlon,\n                                               fixedPointData.itsTopRightLatlon,\n                                               itsCentralLongitude,\n                                               itsCentralLatitude,\n                                               itsTrueLatitude1,\n                                               itsTrueLatitude2,\n                                               itsRadius,\n                                               fixedPointData.fIsPacific,\n                                               TopLeft(),\n                                               BottomRight());\n    }\n\n    return new NFmiLambertConformalConicArea(theBottomLeftLatLon,\n                                             theTopRightLatLon,\n                                             itsCentralLongitude,\n                                             itsCentralLatitude,\n                                             itsTrueLatitude1,\n                                             itsTrueLatitude2,\n                                             itsRadius,\n                                             PacificView(),\n                                             TopLeft(),\n                                             BottomRight());\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\return Undocumented\n * \\todo Should return an boost::shared_ptr instead\n */\n// ----------------------------------------------------------------------\n\nNFmiArea *NFmiLambertConformalConicArea::Clone() const\n{\n  try\n  {\n    return new NFmiLambertConformalConicArea(*this);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Equality comparison\n *\n * \\param theArea The other object being compared to\n * \\return True, if the objects are equal\n */\n// ----------------------------------------------------------------------\n\nbool NFmiLambertConformalConicArea::operator==(const NFmiLambertConformalConicArea &theArea) const\n{\n  try\n  {\n    if ((itsBottomLeftLatLon == theArea.itsBottomLeftLatLon) &&\n        (itsTopRightLatLon == theArea.itsTopRightLatLon) &&\n        (itsCentralLongitude == theArea.itsCentralLongitude) &&\n        (itsCentralLatitude == theArea.itsCentralLatitude) &&\n        (itsTrueLatitude1 == theArea.itsTrueLatitude1) &&\n        (itsTrueLatitude2 == theArea.itsTrueLatitude2) && (itsRadius == theArea.itsRadius) &&\n        (itsWorldRect == theArea.itsWorldRect))\n      return true;\n\n    return false;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Inequality comparison\n *\n * \\param theArea The other object being compared to\n * \\return True, if the objects are not equal\n */\n// ----------------------------------------------------------------------\n\nbool NFmiLambertConformalConicArea::operator!=(const NFmiLambertConformalConicArea &theArea) const\n{\n  try\n  {\n    return !(*this == theArea);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Equality comparison\n *\n * \\param theArea The other object being compared to\n * \\return True, if the objects are equal\n */\n// ----------------------------------------------------------------------\n\nbool NFmiLambertConformalConicArea::operator==(const NFmiArea &theArea) const\n{\n  try\n  {\n    return *this == static_cast<const NFmiLambertConformalConicArea &>(theArea);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Inequality comparison\n *\n * \\param theArea The other object being compared to\n * \\return True, if the objects are not equal\n */\n// ----------------------------------------------------------------------\n\nbool NFmiLambertConformalConicArea::operator!=(const NFmiArea &theArea) const\n{\n  try\n  {\n    return !(*this == theArea);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n// ----------------------------------------------------------------------\n/*!\n * Write the object to the given output stream\n *\n * \\param file The output stream to write to\n * \\return The output stream written to\n */\n// ----------------------------------------------------------------------\n\nstd::ostream &NFmiLambertConformalConicArea::Write(std::ostream &file) const\n{\n  try\n  {\n    NFmiArea::Write(file);\n\n    file << itsBottomLeftLatLon << itsTopRightLatLon << endl\n         << itsCentralLongitude << ' ' << itsCentralLatitude << endl\n         << itsTrueLatitude1 << ' ' << itsTrueLatitude2 << endl\n         << itsRadius << endl;\n\n    int oldPrec = file.precision();\n    file.precision(15);\n    file << itsWorldRect << endl;\n\n    file.precision(oldPrec);\n\n    return file;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Read new object contents from the given input stream\n *\n * \\param file The input stream to read from\n * \\return The input stream read from\n */\n// ----------------------------------------------------------------------\n\nstd::istream &NFmiLambertConformalConicArea::Read(std::istream &file)\n{\n  try\n  {\n    NFmiArea::Read(file);\n\n    file >> itsBottomLeftLatLon >> itsTopRightLatLon;\n    PacificView(NFmiArea::IsPacificView(itsBottomLeftLatLon, itsTopRightLatLon));\n    file >> itsCentralLongitude >> itsCentralLatitude >> itsTrueLatitude1 >> itsTrueLatitude2 >>\n        itsRadius >> itsWorldRect;\n    Init();\n\n    return file;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nNFmiArea *NFmiLambertConformalConicArea::CreateNewArea(const NFmiRect &theRect) const\n{\n  try\n  {\n    NFmiPoint bottomLeft(ToLatLon(theRect.BottomLeft()));\n    NFmiPoint topRight(ToLatLon(theRect.TopRight()));\n    NFmiArea *area = new NFmiLambertConformalConicArea(bottomLeft,\n                                                       topRight,\n                                                       itsCentralLongitude,\n                                                       itsCentralLatitude,\n                                                       itsTrueLatitude1,\n                                                       itsTrueLatitude2,\n                                                       itsRadius,\n                                                       false,\n                                                       TopLeft(),\n                                                       BottomRight());\n    return area;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nconst std::string NFmiLambertConformalConicArea::AreaStr() const\n{\n  try\n  {\n    std::ostringstream out;\n    out << \"lcc,\" << itsCentralLongitude << ',' << itsCentralLatitude << ',' << itsTrueLatitude1;\n    if (itsTrueLatitude2 != itsTrueLatitude2 || itsRadius != kRearth)\n      out << ',' << itsTrueLatitude2 << ',' << itsRadius;\n    out << ':' << BottomLeftLatLon().X() << ',' << BottomLeftLatLon().Y() << ','\n        << TopRightLatLon().X() << ',' << TopRightLatLon().Y();\n    return out.str();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n\nconst std::string NFmiLambertConformalConicArea::WKT() const\n{\n  try\n  {\n    const char *fmt = R\"(PROJCS[\"FMI_LambertConic\",)\"\n                      R\"(GEOGCS[\"Unknown\",)\"\n                      R\"(DATUM[\"Unknown\",SPHEROID[\"Sphere\",{:.0f},0]],)\"\n                      R\"(PRIMEM[\"Greenwich\",0],)\"\n                      R\"(UNIT[\"Degree\",0.0174532925199433]],)\"\n                      R\"(PROJECTION[\"Lambert_Conformal_Conic_2SP\"],)\"\n                      R\"(PARAMETER[\"latitude_of_origin\",{}],)\"\n                      R\"(PARAMETER[\"central_meridian\",{}],)\"\n                      R\"(PARAMETER[\"standard_parallel_1\",{}],)\"\n                      R\"(PARAMETER[\"standard_parallel_2\",{}],)\"\n                      R\"(UNIT[\"Metre\",1.0]])\";\n    return fmt::format(fmt,\n                       itsRadius,\n                       itsCentralLatitude,\n                       itsCentralLongitude,\n                       itsTrueLatitude1,\n                       itsTrueLatitude2);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nconst NFmiPoint NFmiLambertConformalConicArea::LatLonToWorldXY(\n    const NFmiPoint &theLatLonPoint) const\n{\n  try\n  {\n    const double lat = FmiRad(theLatLonPoint.Y());\n\n    const double theta = itsN * FmiRad(theLatLonPoint.X() - itsCentralLongitude);\n    const double rho = itsRadius * itsF * pow(tan(quart_pi + lat / 2), -itsN);\n\n    const double x = rho * sin(theta);\n    const double y = itsRho0 - rho * cos(theta);\n\n    return NFmiPoint(x, y);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nconst NFmiPoint NFmiLambertConformalConicArea::WorldXYToLatLon(const NFmiPoint &theXYPoint) const\n{\n  try\n  {\n    double lambda = 0;\n    double phi = 0;\n\n    double x = theXYPoint.X();\n    double y = itsRho0 - theXYPoint.Y();\n\n    double rho = std::hypot(x, y);\n\n    if (rho == 0)\n    {\n      // Either pole\n      phi = (itsN > 0 ? half_pi : -half_pi);\n    }\n    else\n    {\n      if (itsN < 0)\n      {\n        rho = -rho;\n        x = -x;\n        y = -y;\n      }\n      phi = 2 * atan(pow(itsRadius * itsF / rho, 1 / itsN)) - half_pi;\n      lambda = atan2(x, y) / itsN + FmiRad(itsCentralLongitude);\n    }\n\n    return NFmiPoint(FmiDeg(lambda), FmiDeg(phi));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nconst NFmiPoint NFmiLambertConformalConicArea::XYToWorldXY(const NFmiPoint &theXYPoint) const\n{\n  try\n  {\n    double xWorld = itsWorldRect.Left() + (theXYPoint.X() - Left()) / itsXScaleFactor;\n    double yWorld = itsWorldRect.Bottom() - (theXYPoint.Y() - Top()) / itsYScaleFactor;\n\n    return NFmiPoint(xWorld, yWorld);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nconst NFmiPoint NFmiLambertConformalConicArea::WorldXYToXY(const NFmiPoint &theWorldXYPoint) const\n{\n  try\n  {\n    double x = itsXScaleFactor * (theWorldXYPoint.X() - itsWorldRect.Left()) + Left();\n    double y = Top() - itsYScaleFactor * (theWorldXYPoint.Y() - itsWorldRect.Bottom());\n    return NFmiPoint(x, y);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nconst NFmiPoint NFmiLambertConformalConicArea::ToLatLon(const NFmiPoint &theXYPoint) const\n{\n  try\n  {\n    // Transform local xy-coordinates into world xy-coordinates (meters).\n\n    double xWorld = itsWorldRect.Left() + (theXYPoint.X() - Left()) / itsXScaleFactor;\n    double yWorld = itsWorldRect.Bottom() - (theXYPoint.Y() - Top()) / itsYScaleFactor;\n\n    // Transform world xy-coordinates into geodetic coordinates.\n\n    return WorldXYToLatLon(NFmiPoint(xWorld, yWorld));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nconst NFmiPoint NFmiLambertConformalConicArea::ToXY(const NFmiPoint &theLatLonPoint) const\n{\n  try\n  {\n    double xLocal, yLocal;\n\n    // Transform input geodetic coordinates into world coordinates (meters) on xy-plane.\n    NFmiPoint latlon(FixLongitude(theLatLonPoint.X()), theLatLonPoint.Y());\n    NFmiPoint xyWorld(LatLonToWorldXY(latlon));\n\n    if (xyWorld == NFmiPoint::gMissingLatlon)\n    {\n      return xyWorld;\n    }\n\n    // Finally, transform world xy-coordinates into local xy-coordinates\n    xLocal = Left() + itsXScaleFactor * (xyWorld.X() - itsWorldRect.Left());\n    yLocal = Top() + itsYScaleFactor * (itsWorldRect.Bottom() - xyWorld.Y());\n\n    return NFmiPoint(xLocal, yLocal);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Hash value\n */\n// ----------------------------------------------------------------------\n\nstd::size_t NFmiLambertConformalConicArea::HashValue() const\n{\n  try\n  {\n    std::size_t hash = NFmiArea::HashValue();\n    boost::hash_combine(hash, itsBottomLeftLatLon.HashValue());\n    boost::hash_combine(hash, itsTopRightLatLon.HashValue());\n    boost::hash_combine(hash, boost::hash_value(itsCentralLongitude));\n    boost::hash_combine(hash, boost::hash_value(itsCentralLatitude));\n    boost::hash_combine(hash, boost::hash_value(itsTrueLatitude1));\n    boost::hash_combine(hash, boost::hash_value(itsTrueLatitude2));\n    boost::hash_combine(hash, boost::hash_value(itsRadius));\n    return hash;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n// ======================================================================\n", "meta": {"hexsha": "12eaab6ad73809bd87580c184c622e5df998ddda", "size": 17440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "newbase/NFmiLambertConformalConicArea.cpp", "max_stars_repo_name": "fmidev/smartmet-library-newbase", "max_stars_repo_head_hexsha": "12d93660c06e3c66a039ea75530bd9ca5daf7ab8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "newbase/NFmiLambertConformalConicArea.cpp", "max_issues_repo_name": "fmidev/smartmet-library-newbase", "max_issues_repo_head_hexsha": "12d93660c06e3c66a039ea75530bd9ca5daf7ab8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-01-17T10:46:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-21T07:50:17.000Z", "max_forks_repo_path": "newbase/NFmiLambertConformalConicArea.cpp", "max_forks_repo_name": "fmidev/smartmet-library-newbase", "max_forks_repo_head_hexsha": "12d93660c06e3c66a039ea75530bd9ca5daf7ab8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-01-17T07:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-26T07:10:23.000Z", "avg_line_length": 31.5942028986, "max_line_length": 99, "alphanum_fraction": 0.5165711009, "num_tokens": 3968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5269317859567257}}
{"text": "/// \\ref https://www.hackerrank.com/challenges/quicksort1/problem?h_r=next-challenge&h_v=zen\n\n#include \"Algorithms/HackerRank/QuickSort.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <vector>\n\nusing Algorithms::HackerRank::Sorting::QuickSort::quick_sort_partition;\nusing std::vector;\n\nBOOST_AUTO_TEST_SUITE(Algorithms)\nBOOST_AUTO_TEST_SUITE(HackerRank)\nBOOST_AUTO_TEST_SUITE(Sorting)\nBOOST_AUTO_TEST_SUITE(QuickSort_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(QuickSortPartitionPartitions)\n{\n\tvector<int> arr {4, 5, 3, 7, 2};\n\n\tconst vector<int> partition_result {quick_sort_partition(arr)};\n\n\tBOOST_TEST(partition_result[2] == 4);\n\tBOOST_TEST((partition_result[0] == 2 && partition_result[1] == 3 ||\n\t\tpartition_result[0] == 3 && partition_result[1] == 2));\n\tBOOST_TEST((partition_result[3] == 5 && partition_result[4] == 7 ||\n\t\tpartition_result[3] == 7 && partition_result[4] == 5));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // QuickSort_tests\nBOOST_AUTO_TEST_SUITE_END() // Sorting\nBOOST_AUTO_TEST_SUITE_END() // HackerRank\nBOOST_AUTO_TEST_SUITE_END() // Algorithms", "meta": {"hexsha": "744603ccda76e084e363837da3dfe83b6a702096", "size": 1207, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Algorithms/HackerRank/QuickSort_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/HackerRank/QuickSort_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/HackerRank/QuickSort_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": 35.5, "max_line_length": 92, "alphanum_fraction": 0.6661143331, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5269203508951691}}
{"text": "/*\n * Copyright 2020-2021 INRIA\n */\n\n#ifndef __eigenpy_decomposition_ldlt_hpp__\n#define __eigenpy_decomposition_ldlt_hpp__\n\n#include \"eigenpy/eigenpy.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n\n#include \"eigenpy/utils/scalar-name.hpp\"\n\nnamespace eigenpy\n{\n  \n  template<typename _MatrixType>\n  struct LDLTSolverVisitor\n  : public boost::python::def_visitor< LDLTSolverVisitor<_MatrixType> >\n  {\n    \n    typedef _MatrixType MatrixType;\n    typedef typename MatrixType::Scalar Scalar;\n    typedef typename MatrixType::RealScalar RealScalar;\n    typedef Eigen::Matrix<Scalar,Eigen::Dynamic,1,MatrixType::Options> VectorXs;\n    typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic,MatrixType::Options> MatrixXs;\n    typedef Eigen::LDLT<MatrixType> Solver;\n    \n    template<class PyClass>\n    void visit(PyClass& cl) const\n    {\n      namespace bp = boost::python;\n      cl\n      .def(bp::init<>(\"Default constructor\"))\n      .def(bp::init<Eigen::DenseIndex>(bp::arg(\"size\"),\n                                       \"Default constructor with memory preallocation\"))\n      .def(bp::init<MatrixType>(bp::arg(\"matrix\"),\n                                \"Constructs a LDLT factorization from a given matrix.\"))\n      \n      .def(\"isNegative\",&Solver::isNegative,bp::arg(\"self\"),\n           \"Returns true if the matrix is negative (semidefinite).\")\n      .def(\"isPositive\",&Solver::isPositive,bp::arg(\"self\"),\n           \"Returns true if the matrix is positive (semidefinite).\")\n       \n      .def(\"matrixL\",&matrixL,bp::arg(\"self\"),\n           \"Returns the lower triangular matrix L.\")\n      .def(\"matrixU\",&matrixU,bp::arg(\"self\"),\n           \"Returns the upper triangular matrix U.\")\n      .def(\"vectorD\",&vectorD,bp::arg(\"self\"),\n           \"Returns the coefficients of the diagonal matrix D.\")\n      .def(\"transpositionsP\",&transpositionsP,bp::arg(\"self\"),\n           \"Returns the permutation matrix P.\")\n      \n      .def(\"matrixLDLT\",&Solver::matrixLDLT,bp::arg(\"self\"),\n           \"Returns the LDLT decomposition matrix.\",\n           bp::return_internal_reference<>())\n      \n      .def(\"rankUpdate\",(Solver & (Solver::*)(const Eigen::MatrixBase<VectorXs> &, const RealScalar &))&Solver::template rankUpdate<VectorXs>,\n           bp::args(\"self\",\"vector\",\"sigma\"),\n           bp::return_self<>())\n    \n#if EIGEN_VERSION_AT_LEAST(3,3,0)\n      .def(\"adjoint\",&Solver::adjoint,bp::arg(\"self\"),\n           \"Returns the adjoint, that is, a reference to the decomposition itself as if the underlying matrix is self-adjoint.\",\n           bp::return_self<>())\n#endif\n      \n      .def(\"compute\",(Solver & (Solver::*)(const Eigen::EigenBase<MatrixType> & matrix))&Solver::compute,\n           bp::args(\"self\",\"matrix\"),\n           \"Computes the LDLT of given matrix.\",\n           bp::return_self<>())\n      \n      .def(\"info\",&Solver::info,bp::arg(\"self\"),\n           \"NumericalIssue if the input contains INF or NaN values or overflow occured. Returns Success otherwise.\")\n#if EIGEN_VERSION_AT_LEAST(3,3,0)\n      .def(\"rcond\",&Solver::rcond,bp::arg(\"self\"),\n           \"Returns an estimate of the reciprocal condition number of the matrix.\")\n#endif\n      .def(\"reconstructedMatrix\",&Solver::reconstructedMatrix,bp::arg(\"self\"),\n           \"Returns the matrix represented by the decomposition, i.e., it returns the product: L L^*. This function is provided for debug purpose.\")\n      .def(\"solve\",&solve<VectorXs>,bp::args(\"self\",\"b\"),\n           \"Returns the solution x of A x = b using the current decomposition of A.\")\n      .def(\"solve\",&solve<MatrixXs>,bp::args(\"self\",\"B\"),\n           \"Returns the solution X of A X = B using the current decomposition of A where B is a right hand side matrix.\")\n      \n      .def(\"setZero\",&Solver::setZero,bp::arg(\"self\"),\n           \"Clear any existing decomposition.\")\n      ;\n    }\n    \n    static void expose()\n    {\n      static const std::string classname = \"LDLT\" + scalar_name<Scalar>::shortname();\n      expose(classname);\n    }\n    \n    static void expose(const std::string & name)\n    {\n      namespace bp = boost::python;\n      bp::class_<Solver>(name.c_str(),\n                         \"Robust Cholesky decomposition of a matrix with pivoting.\\n\\n\"\n                         \"Perform a robust Cholesky decomposition of a positive semidefinite or negative semidefinite matrix $ A $ such that $ A = P^TLDL^*P $, where P is a permutation matrix, L is lower triangular with a unit diagonal and D is a diagonal matrix.\\n\\n\"\n                         \"The decomposition uses pivoting to ensure stability, so that L will have zeros in the bottom right rank(A) - n submatrix. Avoiding the square root on D also stabilizes the computation.\",\n                         bp::no_init)\n      .def(LDLTSolverVisitor());\n    }\n    \n  private:\n    \n    static MatrixType matrixL(const Solver & self) { return self.matrixL(); }\n    static MatrixType matrixU(const Solver & self) { return self.matrixU(); }\n    static VectorXs vectorD(const Solver & self) { return self.vectorD(); }\n    \n    static MatrixType transpositionsP(const Solver & self)\n    {\n      return self.transpositionsP() * MatrixType::Identity(self.matrixL().rows(),\n                                                           self.matrixL().rows());\n    }\n    \n    template<typename MatrixOrVector>\n    static MatrixOrVector solve(const Solver & self, const MatrixOrVector & vec)\n    {\n      return self.solve(vec);\n    }\n  };\n  \n} // namespace eigenpy\n\n#endif // ifndef __eigenpy_decomposition_ldlt_hpp__\n", "meta": {"hexsha": "1e4dbab8bb7095d61588aff2c2780ad3299bd978", "size": 5510, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/eigenpy/decompositions/LDLT.hpp", "max_stars_repo_name": "seanyen/eigenpy", "max_stars_repo_head_hexsha": "e164f03eb13b5fc531dd6b5e7e0f28560f405464", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-12-25T10:05:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:14:25.000Z", "max_issues_repo_path": "include/eigenpy/decompositions/LDLT.hpp", "max_issues_repo_name": "seanyen/eigenpy", "max_issues_repo_head_hexsha": "e164f03eb13b5fc531dd6b5e7e0f28560f405464", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 123.0, "max_issues_repo_issues_event_min_datetime": "2015-04-29T09:48:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T02:26:33.000Z", "max_forks_repo_path": "include/eigenpy/decompositions/LDLT.hpp", "max_forks_repo_name": "seanyen/eigenpy", "max_forks_repo_head_hexsha": "e164f03eb13b5fc531dd6b5e7e0f28560f405464", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T00:45:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T11:25:43.000Z", "avg_line_length": 42.0610687023, "max_line_length": 268, "alphanum_fraction": 0.631215971, "num_tokens": 1307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5269203503589139}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <string>\n#include <vector>\n#include <boost/lexical_cast.hpp>\n#include <CGAL/Exact_predicates_exact_constructions_kernel_with_root_of.h>\n#include <CGAL/Construct_theta_graph_2.h>\n#include <CGAL/gnuplot_output_2.h>\n\n// select the kernel type\ntypedef CGAL::Exact_predicates_exact_constructions_kernel_with_root_of   Kernel;\ntypedef Kernel::Point_2                   Point_2;\ntypedef Kernel::Direction_2               Direction_2;\n/* Note: due to a bug in the boost library, using a directed graph\n * will cause a compilation error with g++ and clang++ when using c++11 standard.\n * See https://lists.boost.org/Archives/boost/2016/05/229458.php.\n */\n// define the graph type\ntypedef boost::adjacency_list<boost::listS,\n                              boost::vecS,\n                              boost::undirectedS,\n                              Point_2\n                             > Graph;\n\nint main(int argc, char ** argv)\n{\n  unsigned int k=4; // By default, no. of cones==4\n  std::string filename=\"data/n9.cin\"; // file used by default\n\n  if (argc > 1 &&\n      (!strcmp(argv[1],\"-h\") || !strcmp(argv[1],\"--help\") || !strcmp(argv[1],\"-?\")))\n  {\n    std::cout << \"Usage: \" << argv[0] << \" <no. of cones> <input filename> [<direction-x> <direction-y>]\" << std::endl;\n    return 1;\n  }\n\n  if (argc > 1)\n  {\n    k = atoi(argv[1]);\n    if (k<2) {\n      std::cout << \"The number of cones should be larger than 1!\" << std::endl;\n      return 1;\n    }\n  }\n\n  if (argc > 2)\n  { filename=std::string(argv[2]); }\n\n  // open the file containing the vertex list\n  std::ifstream inf(filename);\n  if (!inf) {\n    std::cout << \"Cannot open file \" << filename << \"!\" << std::endl;\n    return 1;\n  }\n\n  Direction_2 initial_direction;\n  if (argc == 1 || argc == 3)\n    initial_direction = Direction_2(1, 0);  // default initial_direction\n  else if (argc == 5)\n    initial_direction = Direction_2(atof(argv[3]), atof(argv[4]));\n  else {\n    std::cout << \"Usage: \" << argv[0] << \" <no. of cones> <input filename> [<direction-x> <direction-y>]\" << 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  CGAL::Construct_theta_graph_2<Kernel, Graph> theta(k, initial_direction);\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  // obtain the number of vertices in the constructed graph\n  boost::graph_traits<Graph>::vertices_size_type n = boost::num_vertices(g);\n  // generate gnuplot files for plotting this graph\n  std::string file_prefix = \"t\" + boost::lexical_cast<std::string>(k) + \"n\" + boost::lexical_cast<std::string>(n);\n  CGAL::gnuplot_output_2(g, file_prefix);\n\n  return 0;\n}\n", "meta": {"hexsha": "4096cf1c71f87298d99a97c7a0d4591f47f08e99", "size": 2885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Cone_spanners_2/examples/Cone_spanners_2/theta_io.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/theta_io.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/theta_io.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": 33.1609195402, "max_line_length": 119, "alphanum_fraction": 0.6398613518, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.526920337723214}}
{"text": "#include \"voronoi.h\"\n\n#include <boost/foreach.hpp>\n\nusing namespace std;\n\nnamespace voronoi\n{\n\ntemplate<class Tp_>\nvoid\nVoronoiDiagram<Tp_>::clip_infinite_edge(const edge_type& edge,\n    point_type& p0, point_type& p1)\n  const\n{\n  const cell_type& cell1 = *edge.cell();\n  const cell_type& cell2 = *edge.twin()->cell();\n  point_type origin, direction;\n\n  point_type s1 = sites[cell1.source_index()];\n  point_type s2 = sites[cell2.source_index()];\n  bg::assign_point(origin, s1);\n  bg::add_point(origin, s2);\n  bg::divide_value(origin, 2);\n  bg::set<0>(direction, bg::get<1>(s1) - bg::get<1>(s2));\n  bg::set<1>(direction, bg::get<0>(s2) - bg::get<0>(s1));\n\n  coordinate_type koef = boundsx\n    / (std::max)(fabs(bg::get<0>(direction)), fabs(bg::get<1>(direction)));\n  if (edge.vertex0() == NULL) {\n    p0 = point_type(\n        bg::get<0>(origin) - bg::get<0>(direction) * koef,\n        bg::get<1>(origin) - bg::get<1>(direction) * koef);\n  } else {\n    p0 = point_type(edge.vertex0()->x(), edge.vertex0()->y());\n  }\n  if (edge.vertex1() == NULL) {\n    p1 = point_type(\n        bg::get<0>(origin) + bg::get<0>(direction) * koef,\n        bg::get<1>(origin) + bg::get<1>(direction) * koef);\n  } else {\n    p1 = point_type(edge.vertex1()->x(), edge.vertex1()->y());\n  }\n}\n\n// Function object to filter-out users whose sites are already known.\ntemplate <class Value>\nstruct is_unknown {\n  const vector<int> &index_set;\n  is_unknown(const vector<int> &s) : index_set(s) {}\n  inline bool operator()(Value const& p) const {\n    return index_set[p.second] == -1;\n  }\n};\n\ntemplate <class Value, class Tp_>\nstruct inside_cell {\n  typedef typename VoronoiDiagram<Tp_>::cell_type cell_type;\n  const VoronoiDiagram<Tp_> &vd;\n  const cell_type &cell;\n  inside_cell(const VoronoiDiagram<Tp_> &v, const cell_type& c)\n    : vd(v), cell(c) {}\n  inline bool operator()(Value const& p) const {\n    return vd.is_inside(cell, p.first); // point inside cell\n  }\n};\n\ntemplate<class Tp_>\nvoid\nVoronoiDiagram<Tp_>::map_knn(void)\n{\n  // Construct an R-tree for NN(1) queries on the sites.\n  // We use this to efficiently find the site that is nearest to each user.\n  typedef pair<point_type, int> rvalue_t;\n  vector<rvalue_t> svals;\n  int site_idx = 0;\n  for (auto site = sites.begin(); site != sites.end(); ++site, ++site_idx)\n    svals.push_back(make_pair(\n          point_type(bg::get<0>(*site), bg::get<1>(*site)),\n          site_idx));\n  typedef typename bgi::rtree<rvalue_t, bgi::quadratic<16> > voronoi_tree;\n  voronoi_tree vtree(svals.begin(), svals.end());\n\n  // The nearest-neighbor is of course the voronoi cell.\n  for (size_t user_idx = 0u; user_idx < users.size(); user_idx++)\n  {\n    const point_type &user = users[user_idx];\n    u2s[user_idx] = vtree.qbegin(bgi::nearest(user, 1))->second;\n  }\n}\n\n// This is an efficient method for mapping user points to their nearest site,\n// using a voronoi diagram and range-tree.\n// This runs in O(m log m + (m + n) log n) on average for m sites and n users:\n//   O(m log m) worst-case to build the voronoi diagram;\n//   O(n log n) worst-case to build the user range tree;\n//   O(m log n) average-case to find user points in each cell (see below).\n// Since Voronoi cells are convex and the Voronoi edge set is O(m), we can\n// use the winding check for containment of a query point in amortized O(1)\n// time per cell.\n// Each containment check in the worst case must consider O(n) users.\n// We improve this to O(log n) on average by using a range tree to filter each\n// user query down to points which lie in the cell's bounding box. Of course\n// this only works when the cells and users are distributed randomly.\n// In the worst case, all Voronoi cells may share the same bounding box, and\n// all O(n) user points will be checked for all O(m) cells anyway. However, the\n// containment check is short-circuited for those users who have already been\n// assigned a cell yet, so the overhead is small for the extra comparisons.\ntemplate<class Tp_>\nvoid\nVoronoiDiagram<Tp_>::map_quick(void)\n{\n  // Construct an R-tree for range queries on the user points.\n  // We use this to efficiently find the user points that lie within each\n  // voronoi cell using its bounding box.\n  typedef pair<point_type, int> rvalue_t;\n  vector<rvalue_t> uvals;\n  int user_idx = 0;\n  for (auto user = users.begin(); user != users.end(); ++user, ++user_idx)\n    uvals.push_back(make_pair(\n          point_type(bg::get<0>(*user), bg::get<1>(*user)),\n          user_idx));\n  bgi::rtree<rvalue_t, bgi::quadratic<16> > utree(uvals.begin(), uvals.end());\n\n  for (auto it = vd.cells().begin(); it != vd.cells().end(); ++it)\n  {\n    const cell_type &cell = *it;\n    // Map the users that lie inside our cell to this site.\n    rect_type bbox = boundingRect(cell);\n    vector<rvalue_t> query_users;\n    utree.query(\n           bgi::satisfies(is_unknown<rvalue_t>(u2s))\n        && bgi::within(bbox)\n        && bgi::satisfies(inside_cell<rvalue_t, Tp_>(*this, cell)),\n        back_inserter(query_users));\n    BOOST_FOREACH(rvalue_t const& v, query_users)\n    {\n      int user_idx = v.second;\n      u2s[user_idx] = cell.source_index();\n    }\n  }\n}\n\n/*\n// This is a brute-force (slow) method for mapping user points to their cells\n// simply by associating each user to the site to which it is nearest.\n// This runs in O(m*n) for m sites and n users.\ntemplate<class Tp_>\nvoid\nVoronoiDiagram<Tp_>::map_slow(void)\n{\n  u2s = vector<int>(users.size(), -1);\n  for (size_t user_idx = 0u; user_idx < users.size(); ++user_idx)\n  {\n    const Point &user = users[user_idx];\n    double mindist = std::numeric_limits<double>::infinity();\n    int closest_site_idx = -1;\n    for (size_t site_idx = 0u; site_idx < sites.size(); ++site_idx)\n    {\n      const Point &site = sites[site_idx];\n      double distance = normalize(site - user);\n      if (distance < mindist) {\n        mindist = distance;\n        closest_site_idx = static_cast<int>(site_idx);\n      }\n    }\n    u2s[user_idx] = closest_site_idx;\n  }\n}\n*/\n\ntemplate<class Tp_>\nvoid\nVoronoiDiagram<Tp_>::build(SearchMethod sm)\n{\n  vd.clear();\n\n  // Always construct the voronoi diagram from the sites so we have edges.\n  boost::polygon::construct_voronoi(sites.begin(), sites.end(), &vd);\n\n  // u2s maps user index to nearest facility index\n  u2s = vector<int>(users.size(), -1);\n\n  // Now map users to their cells through whichever method we want.\n  switch (sm) {\n    /*\n    case SearchMethod::Slow:\n      this->map_slow(); break;\n      */\n    case SearchMethod::Quick:\n      this->map_quick(); break;\n    case SearchMethod::KNN:\n    case SearchMethod::Default:\n      this->map_knn(); break;\n    default:\n      throw runtime_error(\"VoronoiDiagram::build(): bad SearchMethod!\");\n  };\n}\n\n// Common instantiations.\ntemplate class VoronoiDiagram<double>;\n\n}\n", "meta": {"hexsha": "ce58d854e6350fe250b2d0e1c8ee36f3f15d7500", "size": 6777, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/voronoi.cc", "max_stars_repo_name": "fritzr/voronoi-game", "max_stars_repo_head_hexsha": "77fcc6a40076ab092795445f4e2a73f475338090", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/voronoi.cc", "max_issues_repo_name": "fritzr/voronoi-game", "max_issues_repo_head_hexsha": "77fcc6a40076ab092795445f4e2a73f475338090", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/voronoi.cc", "max_forks_repo_name": "fritzr/voronoi-game", "max_forks_repo_head_hexsha": "77fcc6a40076ab092795445f4e2a73f475338090", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-12T03:44:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-12T03:44:53.000Z", "avg_line_length": 33.2205882353, "max_line_length": 79, "alphanum_fraction": 0.6657813192, "num_tokens": 1916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5269203285844071}}
{"text": "#include \"stdafx.h\"\n#include \"Triangle.h\"\n#include <stdexcept>\n#include <string>\n#include <sstream>\n#include <boost/format.hpp>\n#include <math.h>\n\nusing namespace std;\n\nnamespace\n{\nconst double & AssureNotNegative(const double & value, const string & argName = string())\n{\n\tif (value >= 0)\n\t{\n\t\treturn value;\n\t}\n\tthrow invalid_argument(argName.empty() ? \"Argument\" : argName + \" can not be negative.\");\n}\n}\n\n#define ASSURE_NOT_NEGATIVE(value) AssureNotNegative((value), #value)\n\nCTriangle::CTriangle(double side1, double side2, double side3)\n\t: m_side1(ASSURE_NOT_NEGATIVE(side1))\n\t, m_side2(AssureNotNegative(side2, \"Side 2\"))\n\t, m_side3(AssureNotNegative(side3, \"Side 3\"))\n{\n\tValidateSideLength(side1, side2, side3, 1, 2, 3);\n\tValidateSideLength(side2, side1, side3, 2, 1, 3);\n\tValidateSideLength(side3, side1, side2, 3, 1, 2);\n\t//if (side1 > side2 + side3)\n\t//{\n\t//\tthrow domain_error(\"Side 1 can not be greater than sum of side 2 and side 3\");\n\t//}\n\n\t//if (side2 > side1 + side3)\n\t//{\n\t//\tthrow domain_error(\"Side 2 can not be greater than sum of side 1 and side 3\");\n\t//}\n\n\t//if (side3 > side1 + side2)\n\t//{\n\t//\tthrow domain_error(\"Side 3 can not be greater than sum of side 1 and side 2\");\n\t//}\n}\n\ndouble CTriangle::GetSide1()const\n{\n\treturn m_side1;\n}\n\ndouble CTriangle::GetSide2()const\n{\n\treturn m_side2;\n}\n\ndouble CTriangle::GetSide3()const\n{\n\treturn m_side3;\n}\n\ndouble CTriangle::GetPerimeter()const\n{\n\treturn m_side1 + m_side2 + m_side3;\n}\n\ndouble CTriangle::GetArea()const\n{\n\tdouble p = GetPerimeter() / 2;\n\treturn sqrt(p * (p - m_side1) * (p - m_side2) * (p - m_side3));\n}\n\nvoid CTriangle::ValidateSideLength(\n\tdouble sideToCheck, double side1, double side2,\n\tint checkedSideIndex, int side1Index, int side2Index)\n{\n\tif (sideToCheck > side1 + side2)\n\t{\n\t\tthrow domain_error((boost::format(\"Side %1% can not be greater than sum of side %2% and side %3%\") \n\t\t\t\t% checkedSideIndex % side1Index % side2Index).str());\n\n\t\t//ostringstream msg;\n\t\t//msg << \"Side \" << checkedSideIndex << \" can not be greater than sum of side \" \n\t\t//\t<< side1Index << \" and side \" << side2Index;\n\t\t//throw domain_error(msg.str());\n\n\t\t//throw domain_error(\n\t\t//\t\"Side \" + to_string(checkedSideIndex) + \n\t\t//\t\" can not be greater than sum of side \" + to_string(side1Index) + \n\t\t//\t\" and side \" + to_string(side2Index));\n\t}\n}\n", "meta": {"hexsha": "1f4eae7fc6f8e68fd6e5dcbd3b91d6a7215d22b2", "size": 2310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lab6/task01/Triangle.cpp", "max_stars_repo_name": "alexey-malov/ips-oop2015", "max_stars_repo_head_hexsha": "fd47a03213b9387eef5f1664725557b41a2ffd1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab6/task01/Triangle.cpp", "max_issues_repo_name": "alexey-malov/ips-oop2015", "max_issues_repo_head_hexsha": "fd47a03213b9387eef5f1664725557b41a2ffd1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab6/task01/Triangle.cpp", "max_forks_repo_name": "alexey-malov/ips-oop2015", "max_forks_repo_head_hexsha": "fd47a03213b9387eef5f1664725557b41a2ffd1b", "max_forks_repo_licenses": ["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.3157894737, "max_line_length": 101, "alphanum_fraction": 0.680952381, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.5268585824369891}}
{"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 *\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#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE newton_rapson\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// Local VOTCA includes\n#include \"votca/xtp/newton_rapson.h\"\n\nusing namespace votca::xtp;\nusing namespace votca;\n\nBOOST_AUTO_TEST_SUITE(newton_rapson)\nclass Func {\n public:\n  std::pair<double, double> operator()(double x) const {\n    std::pair<double, double> value;\n    value.first = x * x - 612;\n    value.second = 2 * x;\n    return value;\n  }\n};\n\nBOOST_AUTO_TEST_CASE(newton_rapson) {\n\n  Func f;\n  Index iterations = 50;\n  double tolerance = 1e-9;\n  NewtonRapson<Func> n(iterations, tolerance);\n  double root = n.FindRoot(f, 10.0);\n  BOOST_CHECK_EQUAL(n.getInfo(), NewtonRapson<Func>::Errors::success);\n  // see https://en.wikipedia.org/wiki/Newton%27s_method\n  BOOST_CHECK_CLOSE(root, 24.738633753, 1e-7);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "354d397985644574962e3dc988b29527dc8ebea4", "size": 1466, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_newton_rapson.cc", "max_stars_repo_name": "fossabot/xtp", "max_stars_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "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_newton_rapson.cc", "max_issues_repo_name": "fossabot/xtp", "max_issues_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "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_newton_rapson.cc", "max_forks_repo_name": "fossabot/xtp", "max_forks_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "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.6603773585, "max_line_length": 75, "alphanum_fraction": 0.7298772169, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5268585765431283}}
{"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_INVEXP_1_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_INVEXP_1_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    Generates constant 1/e.\n\n    @par Semantic:\n    The e constant is the real number such that \\f$\\log(e) = 1\\f$.\n\n    @code\n    T r = Invexp_1<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    r =  T(0.3678794411714423215955237701614608674458111310317678);\n    @endcode\n\n\n**/\n  template<typename T> T Invexp_1();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Generates constant 1/e.\n\n      Generate the  constant invexp_1.\n\n      @return The Invexp_1 constant for the proper type\n    **/\n    Value Invexp_1<Value>();\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/invexp_1.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": "d78944a0c1eb53da048931d7602f7f6f082041e2", "size": 1365, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/invexp_1.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/invexp_1.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/invexp_1.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": 22.0161290323, "max_line_length": 100, "alphanum_fraction": 0.5978021978, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.5268585717171129}}
{"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#include <boost/python.hpp>\n\n#include <ndhist/stats/excess.hpp>\n\nnamespace bp = boost::python;\n\nnamespace ndhist {\nnamespace stats {\n\nvoid register_excess()\n{\n    bp::def(\"excess\"\n      , &py::excess\n      , ( bp::arg(\"hist\")\n        , bp::arg(\"axis\")=bp::object()\n        )\n      , \"Calculates the excess kurtosis along the given axis of the given    \\n\"\n        \"ndhist object. As in statistics, the excess kurtosis is defined as  \\n\"\n        \":math:`Excess[x] = Kurtosis[x] - 3`.                                \\n\"\n        \"It is a measure how normaly distributed the distribution is.        \\n\"\n        \"This function generates a projection along the given axis and then  \\n\"\n        \"calculates the excess kurtosis.                                     \\n\"\n        \"If ``None`` is given as axis argument (the default), the excess     \\n\"\n        \"kurtosis for all individual axes of the ndhist object is calculated \\n\"\n        \"and returned as a tuple. But if the dimensionality of the histogram \\n\"\n        \"is 1, a scalar value is returned.                                   \\n\"\n        \"                                                                    \\n\"\n        \".. note:: This function is only defined for ndhist objects with POD \\n\"\n        \"          type axis values AND POD type weight values.              \\n\"\n    );\n}\n\n}// namespace stats\n}// namespace ndhist\n", "meta": {"hexsha": "83d81a95a10e153e49f594fab0ddfe8ed671fbe8", "size": 1576, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pybindings/stats/excess.cpp", "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": "src/pybindings/stats/excess.cpp", "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": "src/pybindings/stats/excess.cpp", "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": 34.2608695652, "max_line_length": 80, "alphanum_fraction": 0.5437817259, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5268585717171129}}
{"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_MATRIX_MAX_ABS_POS_INCLUDE\n#define MTL_MATRIX_MAX_ABS_POS_INCLUDE\n\n#include <utility>\n#include <cmath>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/concept/magnitude.hpp>\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace mtl { \n\nnamespace mat {\n///Returns pair (row, col) from absolut maximal entry of %matrix A\n    template <typename Matrix>\n    typename mtl::traits::enable_if_matrix<Matrix, std::pair<typename Collection<Matrix>::size_type, typename Collection<Matrix>::size_type> >::type\n    inline max_abs_pos(const Matrix& A)\n    {\n\tvampir_trace<3024> tracer;\n\tnamespace traits = mtl::traits;\n\tusing std::abs;\n\ttypedef typename Collection<Matrix>::value_type   value_type;\n\ttypedef typename Collection<Matrix>::size_type    size_type;\n\n\ttypename RealMagnitude<value_type>::type max(abs(A[0][0]));\n\tsize_type r= 0, c= 0;\n\n\ttypename traits::row<Matrix>::type             row(A); \n\ttypename traits::col<Matrix>::type             col(A); \n\ttypename traits::const_value<Matrix>::type     value(A); \n\ttypedef typename traits::range_generator<tag::major, Matrix>::type  cursor_type;\n\t\n\tfor (cursor_type cursor = begin<tag::major>(A), cend = end<tag::major>(A); cursor != cend; ++cursor) {\n\t    typedef typename traits::range_generator<tag::nz, cursor_type>::type icursor_type;\n\t    for (icursor_type icursor = begin<tag::nz>(cursor), icend = end<tag::nz>(cursor); icursor != icend; ++icursor) \n\t\tif (abs(value(*icursor)) > max) {\n\t\t    max= abs(value(*icursor));\n\t\t    r= row(*icursor);\n\t\t    c= col(*icursor);\n\t\t}\n\t}\n\t\n\treturn std::make_pair(r, c);\n    }\n\n} // namespace matrix\n\nnamespace vec {\n///Returns position from absolut maximal entry of %vector v\n    template <typename Vector>\n    typename mtl::traits::enable_if_vector<Vector, typename Collection<Vector>::size_type>::type\n    inline max_abs_pos(const Vector& v)\n    {\n\tvampir_trace<2011> tracer;\n\tusing std::abs;\n\ttypedef typename Collection<Vector>::size_type    size_type;\n\ttypedef typename Collection<Vector>::value_type   value_type;\n\n\tsize_type i= 0;\n\tsize_type max_col= size(v);\n\tvalue_type max(abs(v[0]));\n\t\n\tfor(size_type j= 1; j < max_col; j++)\n\t    if(abs(v[j]) > max) {\n\t\tmax = abs(v[j]);\n\t\ti= j;\n\t    }\n\treturn i;\n    }\n\n} // namespace vector\n\n} // namespace mtl\n\n#endif // MTL_MATRIX_MAX_ABS_POS_INCLUDE\n\n", "meta": {"hexsha": "58828abb045076a9d189e6c228604b0d1319e76c", "size": 2930, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/max_abs_pos.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": "boost/numeric/mtl/operation/max_abs_pos.hpp", "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": "boost/numeric/mtl/operation/max_abs_pos.hpp", "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": 32.1978021978, "max_line_length": 148, "alphanum_fraction": 0.7044368601, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5268585690267885}}
{"text": "#ifndef SETTINGS_HPP\n#define SETTINGS_HPP\n\n#include <boost/lexical_cast.hpp>\n#include <clstatphys/physics/todalattice.hpp>\n#include <clstatphys/ensemble/hybrid_monte_carlo.hpp>\n#include <clstatphys/ensemble/modeoccupancy_ensemble_periodic_boundary_fftw.hpp>\n#include <common/settings_common.hpp>\n\nusing Ensembler = ensemble::ModeOccupancyEnsemblePeriodicBoundaryFFTW; \nusing Hamiltonian = hamiltonian::TodaLattice;\nusing MonteCarloSamplerOrigin = ensemble::HybridMonteCarlo; \n\nclass MonteCarloSampler: public MonteCarloSamplerOrigin{\npublic:\n  template<class Hamiltonian>\n  MonteCarloSampler(\n            int num_particles, double temperture, double dt_relax, \n            double relax_time, int total_accept, Hamiltonian hamiltonian)\n    : MonteCarloSamplerOrigin(num_particles, temperture, dt_relax, relax_time, total_accept)\n  {hamiltonian_ = hamiltonian;}\n  \n  template<class Rand>\n  void montecarlo(std::vector<double> & z, Rand & mt){\n    int counter = 0;\n    MonteCarloSamplerOrigin::montecarlo(z, counter, hamiltonian_, mt);\n  }\n\nprivate:\n  Hamiltonian hamiltonian_;\n}; //end MonteCarloSampler definition\n\nstruct Settings : public SettingsCommon{\n  int N_normalmode = 5; //numer of time step\n  int k_initial = 0; //start wave vector filled by initialization \n  double E_initial = 1.0; // initial energy\n\n  int total_accept = 10;\n  double relax_time = 10;\n  double dt_relax = 0.1;\n  double temperture = 1.0;\n\n  double J = 1.0; //interaction constant;\n  double alpha = 1.0; //interaction constant;\n\n  Settings(int argc, char **argv, int & input_counter) \n    : SettingsCommon(argc, argv, input_counter) \n  { \n    set(argc, argv, input_counter);\n  }\n  Settings() = default;\n\n  inline void set(int argc, char **argv, int & input_counter){\n    if (argc > input_counter) E_initial =        boost::lexical_cast<double>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) k_initial =        boost::lexical_cast<int>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) N_normalmode =     boost::lexical_cast<int>(argv[input_counter]);++input_counter;\n    if (Ns < N_normalmode + k_initial){\n      std::cerr << \"k_initial + N_noramalmode should be lower than Ns\" << std::endl;\n      std::exit(1);\n    } \n\n    if (argc > input_counter) total_accept       = boost::lexical_cast<int>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) relax_time         = boost::lexical_cast<double>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) dt_relax           = boost::lexical_cast<double>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) temperture         = boost::lexical_cast<double>(argv[input_counter]);++input_counter;\n\n    if (argc > input_counter) J =     boost::lexical_cast<double>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) alpha = boost::lexical_cast<double>(argv[input_counter]);++input_counter;\n  }\n\n  template <class Dataput>\n  inline void declare(Dataput & dataput){\n    SettingsCommon::declare(dataput);\n\n    dataput <<  \"<<System Depend Settings>> \" << std::endl\n            <<  \"  \" << Hamiltonian::name() << std::endl\n            <<  \"  \" << Ensembler::name() << std::endl\n            <<  \"  \" << MonteCarloSampler::name() << std::endl\n\n            // declare normalmode ensemble \n            << \"  Energy initial : E_initial =\" << E_initial << std::endl\n            << \"  Number of non-zero energy normal modes : N_normalmode =\" << N_normalmode << std::endl\n            << \"  Start wave vector filled by initialization : k_initial =\" << k_initial << std::endl\n\n            // declare hybrid monte carlo\n            << \"  Number of step for fianally accept : total_accept = \" << total_accept << std::endl\n            << \"  Relaxtion time for update : relax_time = \" << relax_time << std::endl\n            << \"  Interbal of time development : dt_relax  = \" << dt_relax << std::endl\n            << \"  Temperture : temperture = \" << temperture << std::endl\n\n            // declare hamiltonian \n            << \"  Coupling constant : J = \" << J << std::endl\n            << \"  Coupling constant : alpha = \" << alpha << std::endl;\n  }\n\n  Hamiltonian hamiltonian(){\n    Lattice lattice_t(Ns);\n\n    std::vector<std::vector<int> > pair_table(\n                                              num_particles,\n                                              std::vector<int>(N_adj)\n                                              ); \n    lattice_t.create_table(pair_table);\n\n    Hamiltonian hamiltonian_t(\n                              num_particles,\n                              J,\n                              alpha,\n                              pair_table,\n                              N_adj\n                              );\n    return hamiltonian_t;\n  }\n\n  MonteCarloSampler monte_carlo_sampler(){\n    MonteCarloSampler monte_carlo_sampler_t(\n                                            num_particles,\n                                            temperture,\n                                            dt_relax,\n                                            relax_time,\n                                            total_accept,\n                                            hamiltonian()\n                                            );\n    return monte_carlo_sampler_t;\n  }\n\n  Ensembler ensembler(){\n    Ensembler ensembler_t(\n                          num_particles,\n                          k_initial,\n                          N_normalmode,\n                          E_initial\n                          );\n    return ensembler_t;\n  }\n\n};\n\n#endif\n", "meta": {"hexsha": "9c1947db25478b4df829c4d8ffa285359c4c2061", "size": 5553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "toda-lattice-action-angle-sampling/include/specific/toda_lattice_periodic_boundary_hybrid_monte_carlo.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": "toda-lattice-action-angle-sampling/include/specific/toda_lattice_periodic_boundary_hybrid_monte_carlo.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": "toda-lattice-action-angle-sampling/include/specific/toda_lattice_periodic_boundary_hybrid_monte_carlo.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": 39.6642857143, "max_line_length": 116, "alphanum_fraction": 0.5859895552, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5268401108504133}}
{"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#include <boost/python.hpp>\n\n#include <ndhist/stats/kurtosis.hpp>\n\nnamespace bp = boost::python;\n\nnamespace ndhist {\nnamespace stats {\n\nvoid register_kurtosis()\n{\n    bp::def(\"kurtosis\"\n      , &py::kurtosis\n      , ( bp::arg(\"hist\")\n        , bp::arg(\"axis\")=bp::object()\n        )\n      , \"Calculates the kurtosis along the given axis of the given           \\n\"\n        \"ndhist object. As in statistics, the kurtosis is defined as         \\n\"\n        \":math:`Kurtosis[x] = (E[x^4] - 4 E[x] E[x^3] + 6 E[x]^2 E[x^2] - 3 E[x]^4) / V[x]^2`.\\n\"\n        \"This function generates a projection along the given axis and then  \\n\"\n        \"calculates the kurtosis.                                            \\n\"\n        \"If ``None`` is given as axis argument (the default), the kurtosis   \\n\"\n        \"for all individual axes of the ndhist object is calculated and      \\n\"\n        \"returned as a tuple. But if the dimensionality of the histogram is  \\n\"\n        \"1, a scalar value is returned.                                      \\n\"\n        \"                                                                    \\n\"\n        \".. note:: This function is only defined for ndhist objects with POD \\n\"\n        \"          type axis values AND POD type weight values.              \\n\"\n    );\n}\n\n}// namespace stats\n}// namespace ndhist\n", "meta": {"hexsha": "fb9eafce3c1c014185cf28eb873f3b98bc213bdd", "size": 1520, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pybindings/stats/kurtosis.cpp", "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": "src/pybindings/stats/kurtosis.cpp", "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": "src/pybindings/stats/kurtosis.cpp", "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": 33.7777777778, "max_line_length": 97, "alphanum_fraction": 0.5296052632, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5268401036858161}}
{"text": "/*!\n  @file glm.hpp\n  @author Klaus K. Holst\n  @copyright 2018-2020, Klaus K\u00e4hler Holst\n\n  @brief Utility functions for Generalized Linear Models\n\n*/\n\n#pragma once\n\n#ifndef ARMA_R\n#define MATHLIB_STANDALONE\n#include <armadillo>\n#endif\n#if defined(ARMA_R)\n#include <RcppArmadillo.h>\n#endif\n#include <cmath>\n#include <complex>\n#include <cfloat>     // precision of double (DBL_MIN)\n#include <functional>  // std::bind for using non-static member function as argument to free function\n#include <vector>\n\nusing cx_dbl  = std::complex<double>;\nusing cx_func = std::function<arma::cx_mat(arma::cx_vec theta)>;\nusing matlist = std::vector<arma::mat>;\n\nnamespace target {\n\n  arma::mat expit(arma::mat x);\n  arma::cx_mat expit(arma::cx_mat x);\n  arma::vec softmax(arma::vec u);\n  arma::mat softmax(arma::mat lp, bool ref, bool log);\n\n  // template<typename T>\n  // arma::Mat<T> expit(const arma::Mat<T> &x) {\n  //   return 1.0/(1+exp(-x));\n  // }\n  arma::mat expit(arma::mat x);\n  arma::cx_mat expit(arma::cx_mat x);\n\n  class IID {\n  public:\n    arma::mat iid;\n    arma::mat vcov;\n    IID(): iid(arma::zeros(1, 1)), vcov(arma::zeros(1, 1)) {}\n    IID(arma::mat score, arma::mat v): iid(score*v), vcov(v) {}\n  };\n\n  IID logistic_iid(const arma::vec &y,\n\t\t   const arma::vec &p,\n\t\t   const arma::mat &x,\n\t\t   const arma::vec &w);\n\n  IID linear_iid(const arma::vec &y,\n\t\t const arma::vec &p,\n\t\t const arma::mat &x,\n\t\t const arma::vec &w);\n\n}  // namespace target\n", "meta": {"hexsha": "f676cbd1b0f656d8c04b9743e692f71674a372f7", "size": 1451, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inst/include/target/glm.hpp", "max_stars_repo_name": "kkholst/gof", "max_stars_repo_head_hexsha": "806286ccec6509155e44fb221eb34aaf0b3bfb20", "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": "inst/include/target/glm.hpp", "max_issues_repo_name": "kkholst/gof", "max_issues_repo_head_hexsha": "806286ccec6509155e44fb221eb34aaf0b3bfb20", "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": "inst/include/target/glm.hpp", "max_forks_repo_name": "kkholst/gof", "max_forks_repo_head_hexsha": "806286ccec6509155e44fb221eb34aaf0b3bfb20", "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.4032258065, "max_line_length": 101, "alphanum_fraction": 0.6526533425, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5268400987018879}}
{"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 robust_sensor_function.hpp\n * \\date 2014\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n\n#include <fl/filter/gaussian/transform/point_set.hpp>\n#include <fl/filter/gaussian/transform/unscented_transform.hpp>\n\nTEST(UnscentedTransformTest, weights)\n{\n    typedef Eigen::Matrix<double, 10, 1> Point;\n    typedef fl::PointSet<Point> Distribution;\n    fl::UnscentedTransform ut;\n    const double dim = 10;\n\n    EXPECT_DOUBLE_EQ(1., ut.weight_mean_0(dim) + 2*dim * ut.weight_mean_i(dim));\n}\n\ntemplate<\n    template<typename, int> class PointSet,\n    typename Point,\n    int Dim\n>\nvoid test_mean_transform(PointSet<Point, Dim>& point_set, int dim)\n{\n    fl::UnscentedTransform ut;\n\n    Point a = Point::Ones(dim) * 9;\n    fl::Gaussian<Point> gaussian;\n\n    gaussian.dimension(dim);\n    gaussian.mean(a);\n\n    //EXPECT_FALSE(a.isApprox(point_set.mean()));\n    ut.forward(gaussian, point_set);\n    EXPECT_TRUE(fl::are_similar(a, point_set.mean()));\n}\n\n// fixed dimension, fixed number of points\nTEST(UnscentedTransformTest, mean_recovery_fixed_fixed)\n{\n    constexpr size_t dim = 10;\n    typedef Eigen::Matrix<double, dim, 1> Point;\n\n    fl::PointSet<\n        Point,\n        fl::UnscentedTransform::number_of_points(dim)\n    > point_set;\n    test_mean_transform(point_set, dim);\n}\n\n// fixed dimension, dynamic number of points\nTEST(UnscentedTransformTest, mean_recovery_fixed_dynamic)\n{\n    constexpr size_t dim = 10;\n    typedef Eigen::Matrix<double, dim, 1> Point;\n\n    fl::PointSet<Point> point_set;\n    test_mean_transform(point_set, dim);\n}\n\n// dynamic dimension, dynamic number of points\nTEST(UnscentedTransformTest, mean_recovery_dynamic_dynamic)\n{\n    constexpr size_t dim = 10;\n    typedef Eigen::Matrix<double, Eigen::Dynamic, 1> Point;\n    typedef fl::PointSet<Point> PointSet;\n\n    PointSet point_set(dim);\n    test_mean_transform(point_set, dim);\n\n    EXPECT_EQ(point_set.count_points(),\n              fl::UnscentedTransform::number_of_points(dim));\n}\n\n// dynamic dimension, fixed number of points\nTEST(UnscentedTransformTest, mean_recovery_dynamic_fixed_throw)\n{\n    constexpr size_t dim = 10;\n    typedef Eigen::Matrix<double, Eigen::Dynamic, 1> Point;\n\n    fl::UnscentedTransform ut;\n    Point a = Point::Ones(dim) * 9;\n\n    fl::Gaussian<Point> gaussian;\n    gaussian.dimension(dim);\n    gaussian.mean(a);\n\n    fl::PointSet<Point, 3> point_set;\n\n    EXPECT_THROW(ut.forward(gaussian, point_set),\n                 fl::WrongSizeException);\n}\n\n// dynamic dimension, fixed number of points\nTEST(UnscentedTransformTest, mean_recovery_dynamic_fixed)\n{\n    constexpr size_t dim = 10;\n    typedef Eigen::Matrix<double, Eigen::Dynamic, 1> Point;\n    typedef fl::PointSet<Point, 21> PointSet;\n\n    PointSet point_set(dim);\n    test_mean_transform(point_set, dim);\n\n    EXPECT_EQ(point_set.count_points(),\n              fl::UnscentedTransform::number_of_points(dim));\n}\n\n\ntemplate<\n    template<typename, int> class PointSet,\n    typename Point,\n    int Dim\n>\nvoid test_covariance_transform(PointSet<Point, Dim>& point_set, int dim)\n{\n    fl::UnscentedTransform ut;\n\n    typename fl::Gaussian<Point>::SecondMoment cov;\n    cov.setRandom(dim, dim);\n    cov *= cov.transpose();\n\n    Point a = Point::Random(dim);\n\n    fl::Gaussian<Point> gaussian;\n    gaussian.dimension(dim);\n    gaussian.mean(a);\n    gaussian.covariance(cov);\n\n    EXPECT_NO_THROW(ut.forward(gaussian, point_set));\n\n    EXPECT_TRUE(\n        fl::are_similar(\n            ( point_set.centered_points() *\n              point_set.covariance_weights_vector().asDiagonal() *\n              point_set.centered_points().transpose() ),\n            cov));\n}\n\nTEST(UnscentedTransformTest, covariance_recovery_fixed_fixed)\n{\n    constexpr size_t dim = 10;\n    typedef Eigen::Matrix<double, dim, 1> Point;\n\n    fl::PointSet<\n        Point,\n        fl::UnscentedTransform::number_of_points(dim)\n    > point_set;\n\n    test_covariance_transform(point_set, dim);\n}\n\nTEST(UnscentedTransformTest, covariance_recovery_fixed_dynamic)\n{\n    constexpr size_t dim = 10;\n    typedef Eigen::Matrix<double, dim, 1> Point;\n\n    fl::PointSet<Point> point_set;\n    test_covariance_transform(point_set, dim);\n}\n\nTEST(UnscentedTransformTest, covariance_recovery_dynamic_dynamic)\n{\n    constexpr size_t dim = 10;\n    typedef Eigen::Matrix<double, Eigen::Dynamic, 1> Point;\n\n    fl::PointSet<Point> point_set(dim);\n    test_covariance_transform(point_set, dim);\n}\n\nTEST(UnscentedTransformTest, covariance_recovery_dynamic_fixed_throw)\n{\n    constexpr size_t dim = 10;\n    typedef Eigen::Matrix<double, Eigen::Dynamic, 1> Point;\n\n    fl::UnscentedTransform ut;\n\n    typename fl::Gaussian<Point>::SecondMoment cov;\n    cov.setRandom(dim, dim);\n    cov *= cov.transpose();\n\n    Point a = Point::Random(dim);\n\n    fl::Gaussian<Point> gaussian;\n    gaussian.dimension(dim);\n    gaussian.mean(a);\n    gaussian.covariance(cov);\n\n    fl::PointSet<Point, 20> point_set;\n\n    EXPECT_THROW(ut.forward(gaussian, point_set),\n                 fl::WrongSizeException);\n}\n\nTEST(UnscentedTransformTest, covariance_recovery_dynamic_fixed)\n{\n    constexpr size_t dim = 10;\n    typedef Eigen::Matrix<double, Eigen::Dynamic, 1> Point;\n\n    fl::PointSet<Point, 21> point_set;\n    point_set.dimension(dim);\n    test_covariance_transform(point_set, dim);\n}\n\n", "meta": {"hexsha": "463e4299dd911c1db0b9e6e9ef7b5a3d3b6d07fd", "size": 5744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gaussian_filter/unscented_transform_test.cpp", "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": "test/gaussian_filter/unscented_transform_test.cpp", "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": "test/gaussian_filter/unscented_transform_test.cpp", "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": 25.7578475336, "max_line_length": 80, "alphanum_fraction": 0.6995125348, "num_tokens": 1418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5268400965212189}}
{"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 <gmock/gmock.h>\n#include <mars/core_state.h>\n#include <mars/general_functions/utils.h>\n#include <mars/sensors/pose/pose_sensor_class.h>\n#include <mars/type_definitions/core_state_type.h>\n#include <Eigen/Dense>\n\nclass mars_bind_sensor_data : public testing::Test\n{\npublic:\n};\n\nTEST_F(mars_bind_sensor_data, CTOR)\n{\n  mars::PoseSensorData sensor_data;\n\n  constexpr int core_state_size = mars::CoreStateType::size_error_;\n  int sensor_state_size = sensor_data.state_.cov_size_;\n  int full_state_size = core_state_size + sensor_state_size;\n\n  // Check for correct dimensions\n  EXPECT_EQ(sensor_data.get_full_cov().size(), full_state_size * full_state_size);\n\n  // Check that all entrys are zero when no data was written\n  EXPECT_EQ(sensor_data.get_full_cov(), Eigen::MatrixXd::Zero(full_state_size, full_state_size));\n\n  // Check that the cov is returned correctly, and that the core cov is set to zero\n  Eigen::MatrixXd full_cov(full_state_size, full_state_size);\n  full_cov.setRandom();\n  full_cov = mars::Utils::EnforceMatrixSymmetry(full_cov);\n\n  Eigen::MatrixXd expected_result = full_cov;\n  expected_result.block(0, 0, core_state_size, core_state_size) =\n      Eigen::Matrix<double, core_state_size, core_state_size>::Zero();\n\n  sensor_data.set_cov(full_cov);\n  Eigen::MatrixXd full_cov_return = sensor_data.get_full_cov();\n\n  Eigen::IOFormat OctaveFmt(Eigen::StreamPrecision, 0, \", \", \";\\n\", \"\", \"\", \"[\", \"]\");\n  std::cout << (full_cov_return - expected_result).format(OctaveFmt) << std::endl;\n\n  EXPECT_EQ(expected_result, full_cov_return);\n}\n", "meta": {"hexsha": "2e13df414e511184d952abc97ac9398f35bcab22", "size": 1967, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/tests/mars-test/mars_bind_sensor_data.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/tests/mars-test/mars_bind_sensor_data.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/tests/mars-test/mars_bind_sensor_data.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": 36.4259259259, "max_line_length": 105, "alphanum_fraction": 0.7585155058, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5268400965212189}}
{"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     isovist.cpp\n* \\author   Collin Johnson\n*\n* Implementation of classes:\n*\n*   - Isovist\n*   - IsovistField\n*/\n\n#include <utils/isovist.h>\n#include <math/covariance.h>\n#include <math/geometry/convex_hull.h>\n#include <math/moments_features.h>\n#include <math/trigonometry.h>\n#include <math/zernike_moments.h>\n#include <math/geometry/shape_fitting.h>\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 <boost/accumulators/statistics/skewness.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <cmath>\n\nnamespace vulcan\n{\nnamespace utils\n{\n\nstatic math::ZernikeMoments<5> zernike;\n\n\ndouble area     (Isovist::Iter begin, Isovist::Iter end);\ndouble perimeter(Isovist::Iter begin, Isovist::Iter end);\ndouble circularity(double area, double perimeter);\n\ntemplate <class BinaryOp> // BinaryOp = double func(Point<double>, Point<double>)\ndouble accumulate_pair(Isovist::Iter begin, Isovist::Iter end, BinaryOp op);\n\n\nstd::string Isovist::scalarName(Scalar scalar)\n{\n    switch(scalar)\n    {\n        case kArea:\n            return \"area\";\n        case kPerimeter:\n            return \"perimeter\";\n        case kCircularity:\n            return \"circularity\";\n        case kOrientation:\n            return \"orientation\";\n        case kWeightedOrientation:\n            return \"weighted_orientation\";\n        case kShapeEccentricity:\n            return \"eccentricity\";\n        case kShapeCompactness:\n            return \"shape compactness\";\n        case kShapeWaviness:\n            return \"waviness\";\n        case kMinDistOrientation:\n            return \"min_dist_orientation\";\n        case kMaxThroughDist:\n            return \"max_through_dist\";\n        case kMaxThroughDistOrientation:\n            return \"max_through_dist_orientation\";\n        case kMinLineDist:\n            return \"min_line_dist\";\n        case kMinLineNormal:\n            return \"min_line_normal\";\n        case kMinNormalDiff:\n            return \"min_normal_diff\";\n        case kDmax:\n            return \"dist_max\";\n        case kDmin:\n            return \"dist_min\";\n        case kDavg:\n            return \"dist_avg\";\n        case kDstd:\n            return \"dist_std\";\n        case kDVariation:\n            return \"dist_variation\";\n        case kDskewness:\n            return \"dist_skewness\";\n        case kShapeDistAvg:\n            return \"shape_dist_avg\";\n        case kShapeDistStd:\n            return \"shape_dist_std\";\n        case kShapeDistVariation:\n            return \"shape_dist_variation\";\n        case kShapeDistCompactness:\n            return \"shape_dist_compactness\";\n        case kDeltaAvg:\n            return \"delta_avg\";\n        case kDeltaStd:\n            return \"delta_std\";\n        case kDeltaVariation:\n            return \"delta_variation\";\n        case kDistRelationAvg:\n            return \"dist_relation_avg\";\n        case kDistRelationStd:\n            return \"dist_relation_std\";\n        case kRayCompactness:\n            return \"ray compactness\";\n        case kAngleBetweenMinDists:\n            return \"angle between min dists\";\n        case kMinHalfArea:\n            return \"min half area\";\n        case kAreaBalance:\n            return \"area balance\";\n        default:\n            return \"unknown\";\n    }\n\n    return \"Unknown\";\n}\n\n\nvoid Isovist::calculateScalars(PointIter begin, PointIter end, std::vector<double>& scalars)\n{\n    scalars_.resize(kNumScalars + zernike.numMoments());\n\n    calculateDistanceScalars(begin, end, scalars);\n    calculateDeltaScalars(begin, end, scalars);\n    calculatePolygonScalars(begin, end, scalars);\n    calculateMomentsScalars(begin, end, scalars);\n}\n\n\nvoid Isovist::calculateDistanceScalars(PointIter begin, PointIter end, std::vector<double>& scalars)\n{\n    using namespace boost::accumulators;\n\n    accumulator_set<double, stats<tag::mean, tag::lazy_variance, tag::skewness, tag::max, tag::min>> distanceAcc;\n    accumulator_set<double, stats<tag::mean, tag::max, tag::lazy_variance>> distFromCenterAcc;\n    accumulator_set<double, stats<tag::mean, tag::lazy_variance, tag::count>> relationAcc;\n\n    auto shapeCenter = std::accumulate(begin, end, Point<float>(0.0f, 0.0f));\n    shapeCenter.x /= std::distance(begin, end);\n    shapeCenter.y /= std::distance(begin, end);\n\n    double lastDist = distance_between_points(position_, *(end - 1));\n    double minDist = std::numeric_limits<double>::max();\n    double minDistOrientation = 0.0;\n\n    for(auto p : boost::make_iterator_range(begin, end))\n    {\n        double dist = distance_between_points(position_, p);\n        distanceAcc(dist);\n        distFromCenterAcc(distance_between_points(shapeCenter, p));\n        relationAcc(std::abs(dist - lastDist));\n\n        // Keeping track of min dist here for the min dist orientation calculation\n        if(dist < minDist)\n        {\n            minDist = dist;\n            minDistOrientation = angle_to_point(position_, p);\n        }\n        lastDist = dist;\n    }\n\n    double secondShortestDist = std::numeric_limits<double>::max();\n    double secondShortestOrientation = 0.0;\n\n    // Find the other local minimum. Need to see that it's actually a minimum when doing the computation\n    // Only relative distances matter here, so we can use the squared_point_distance for efficiency\n    double prevDist = squared_point_distance(position_, *(end-2)); // *begin == *end-1 b/c poly wraps around\n    double curDist = squared_point_distance(position_, *begin);\n\n    // Want the min diff to be far enough for the discretization error to not be the source of\n    // the next min dist\n    const double kMinAngleDiff = std::acos(minDist / (minDist + 0.1));\n\n    for(auto pIt = begin, endIt = end - 1; pIt != endIt; ++pIt)\n    {\n        double nextDist = (pIt + 1 != endIt) ? squared_point_distance(position_, *(pIt + 1)) :\n            squared_point_distance(position_, *begin);\n\n        // If this is a local minima cell, check that it is a little far from the min dist\n        // then see if its angle diff is greater than the existing, but it is still within 0.1m\n        // of the min dist. If so, it's a discretization error that is causing the miss.\n        if((curDist < secondShortestDist)\n            && (curDist < nextDist) && (curDist < prevDist))\n        {\n            // Avoid the angle_to_point except when it matters -- atan2 is expensive!\n            double orientation = angle_to_point(position_, *pIt);\n\n            if(angle_diff_abs(orientation, minDistOrientation) > kMinAngleDiff)\n            {\n                secondShortestDist = curDist;\n                secondShortestOrientation = orientation;\n            }\n        }\n\n        prevDist = curDist;\n        curDist = nextDist;\n    }\n\n    scalars[kMinDistOrientation] = minDistOrientation;\n    scalars[kAngleBetweenMinDists] = angle_diff_abs(minDistOrientation, secondShortestOrientation);\n\n    scalars[kDavg] = mean(distanceAcc);\n    scalars[kDstd] = std::sqrt(variance(distanceAcc));\n    scalars[kDVariation] = (scalars[kDavg] > 0.0) ? scalars[kDstd] / scalars[kDavg] : 0.0;\n    scalars[kDskewness] = skewness(distanceAcc);\n    scalars[kDmin] = min(distanceAcc);\n    scalars[kDmax] = max(distanceAcc);\n    scalars[kShapeDistAvg] = mean(distFromCenterAcc);\n    scalars[kShapeDistStd] = std::sqrt(variance(distFromCenterAcc));\n    scalars[kShapeDistVariation] = (scalars[kShapeDistAvg] > 0.0) ? scalars[kShapeDistStd] / scalars[kShapeDistAvg] : 0.0;\n    scalars[kShapeDistCompactness] = (max(distFromCenterAcc) > 0.0) ? scalars[kShapeDistAvg] / max(distFromCenterAcc) : 1e5;\n\n    scalars[kRayCompactness] = (max(distFromCenterAcc) > 0.0) ? (mean(distFromCenterAcc) / max(distFromCenterAcc)) : 1.0;\n\n    if(count(relationAcc) > 1)\n    {\n        assert(!std::isnan(mean(relationAcc)));\n        scalars[kDistRelationAvg] = mean(relationAcc);\n        scalars[kDistRelationStd] = std::sqrt(variance(relationAcc));\n    }\n\n    double maxDist = 0.0;\n    int maxIdx = 0;\n\n    int otherSide = std::distance(begin, end) / 2;\n    for(std::size_t n = 0, end = otherSide; n < end; ++n)\n    {\n        double dist = squared_point_distance(*(begin + n), *(begin + n + otherSide));\n        if(dist > maxDist)\n        {\n            maxDist = dist;\n            maxIdx = n;\n        }\n    }\n\n    scalars[kMaxThroughDist] = std::sqrt(maxDist);\n    scalars[kMaxThroughDistOrientation] = angle_to_point(position_, *(begin + maxIdx));\n}\n\n\nvoid Isovist::calculateDeltaScalars(PointIter begin, PointIter end, std::vector<double>& scalars)\n{\n    using namespace boost::accumulators;\n\n    accumulator_set<double, stats<tag::mean, tag::lazy_variance>> deltaAcc;\n\n    auto rayDeltaFunc = [begin, &deltaAcc](int n) {\n        deltaAcc(distance_between_points(*(begin + n - 1), *(begin + n)));\n    };\n    auto rayBegin     = boost::make_counting_iterator<std::size_t>(1);\n    auto rayEnd       = boost::make_counting_iterator<std::size_t>(std::distance(begin, end));\n\n    std::for_each(rayBegin, rayEnd, rayDeltaFunc);\n\n    scalars[kDeltaAvg]       = mean(deltaAcc);\n    scalars[kDeltaStd]       = std::sqrt(variance(deltaAcc));\n    scalars[kDeltaVariation] = (scalars[kDeltaAvg] > 0.0) ? scalars[kDeltaStd] / scalars[kDeltaAvg] : 0.0;\n}\n\n\nvoid Isovist::calculatePolygonScalars(PointIter begin, PointIter end, std::vector<double>& scalars)\n{\n    scalars[kArea]        = area(begin, end);\n    scalars[kPerimeter]   = perimeter(begin, end);\n    scalars[kCircularity] = circularity(scalars[kArea], scalars[kPerimeter]);\n\n    if((scalars[kArea] > 0.0) && (scalars[kPerimeter] > 0.0))\n    {\n        auto shapeFeatures = math::shape_features(begin, end, scalars[kArea], position_);\n        scalars[kWeightedOrientation] = shapeFeatures[math::kShapeWeightedOrientation];\n        scalars[kShapeEccentricity] = shapeFeatures[math::kShapeEccentricity];\n        scalars[kOrientation] = shapeFeatures[math::kShapeOrientation];\n        scalars[kShapeCompactness] = shapeFeatures[math::kShapeCompactness];\n\n        auto hull = math::convex_hull<float>(begin, end);\n        scalars[kShapeWaviness] = hull.perimeter() / scalars[kPerimeter];\n    }\n    else\n    {\n        scalars[kWeightedOrientation] = 0.0;\n        scalars[kShapeEccentricity] = 0.0;\n        scalars[kOrientation] = 0.0;\n        scalars[kShapeCompactness] = 0.0;\n        scalars[kShapeWaviness] = 0.0;\n    }\n}\n\n\nvoid Isovist::calculateMomentsScalars(PointIter begin, PointIter end, std::vector<double>& scalars)\n{\n    if(scalars[kArea] > 0.0)\n    {\n        auto zernikeFeatures = zernike.moments<float>(begin,\n                                                      end,\n                                                      position_,\n                                                      scalars[kDmax] * 3);\n        std::copy(zernikeFeatures.begin(), zernikeFeatures.end(), scalars.begin() + kNumScalars);\n    }\n    else\n    {\n        std::fill(scalars.begin() + kNumScalars, scalars.end(), 0.0);\n    }\n}\n\n\nvoid Isovist::calculateDerivs(std::vector<Point<float>>& endpoints)\n{\n    // Find the two halves separated by the min dist line. Store those at the end of endpoints. Compute the\n    // scalars for each side -- except Zernike. The derivative of each can be easily found with abs of difference.\n\n    std::size_t numPoints = endpoints.size();\n    double minDist = HUGE_VAL;\n    int minIdx = 0;\n\n    int otherSide = numPoints / 2;\n    for(int n = 0, end = otherSide; n < end; ++n)\n    {\n        double dist = squared_point_distance(endpoints[n], endpoints[n + otherSide]);\n        if(dist < minDist)\n        {\n            minDist = dist;\n            minIdx = n;\n        }\n    }\n\n    scalars_[kMinLineDist] = std::sqrt(minDist);\n    scalars_[kMinLineNormal] = angle_sum(angle_to_point(endpoints[minIdx],\n                                                                    endpoints[minIdx + otherSide]), M_PI_2);\n\n    // Copy the derivative points on to the end of endpoints. Want to continuous regions, so do the [n,n+otherSide)\n    // then [n+otherSide,end) [0,n)\n    // add one to num points because the ranges need to wrap around\n    endpoints.resize((numPoints + 1) * 2);    // resize to ensure the iterators don't change\n    auto halfIt = std::copy(endpoints.begin() + minIdx, endpoints.begin() + minIdx + otherSide, endpoints.begin() + numPoints);\n    *halfIt++ = *(endpoints.begin() + numPoints);\n    auto endIt = std::copy(endpoints.begin() + minIdx + otherSide, endpoints.begin() + numPoints, halfIt);\n    std::copy(endpoints.begin(), endpoints.begin() + minIdx, endIt);\n    endpoints.back() = *halfIt;\n\n    std::vector<double> halfScalars(kNumScalars);\n    std::vector<double> otherHalfScalars(kNumScalars);\n    scalarDerivs_.resize(kNumScalars);\n\n    calculateDistanceScalars(endpoints.begin() + numPoints, halfIt, halfScalars);\n    calculateDeltaScalars(endpoints.begin() + numPoints, halfIt, halfScalars);\n    calculatePolygonScalars(endpoints.begin() + numPoints, halfIt, halfScalars);\n    calculateDistanceScalars(halfIt, endpoints.end(), otherHalfScalars);\n    calculateDeltaScalars(halfIt, endpoints.end(), otherHalfScalars);\n    calculatePolygonScalars(halfIt, endpoints.end(), otherHalfScalars);\n\n    for(int n = 0; n < kNumScalars; ++n)\n    {\n        scalarDerivs_[n] = std::abs(halfScalars[n] - otherHalfScalars[n]);\n    }\n\n    // Handle wraparound for the angles\n    scalarDerivs_[kOrientation] = angle_diff_abs_pi_2(halfScalars[kOrientation], otherHalfScalars[kOrientation]);\n    scalarDerivs_[kWeightedOrientation] = angle_diff_abs_pi_2(halfScalars[kWeightedOrientation],\n                                                                    otherHalfScalars[kWeightedOrientation]);\n    scalarDerivs_[kMinDistOrientation] = angle_diff_abs(halfScalars[kMinDistOrientation],\n                                                              otherHalfScalars[kMinDistOrientation]);\n    scalarDerivs_[kMaxThroughDistOrientation] = angle_diff_abs(halfScalars[kMaxThroughDistOrientation],\n                                                                     otherHalfScalars[kMaxThroughDistOrientation]);\n\n    // Assign features based on the half-isovists\n    scalars_[kMinHalfArea] = std::min(halfScalars[kArea], otherHalfScalars[kArea]);\n    if(scalars_[kMinHalfArea] > 0.0)\n    {\n        scalars_[kAreaBalance] = scalars_[kMinHalfArea] / std::max(halfScalars[kArea], otherHalfScalars[kArea]);\n    }\n    else\n    {\n        scalars_[kAreaBalance] = 1.0;\n    }\n}\n\n\ndouble area(Isovist::Iter begin, Isovist::Iter end)\n{\n    double sum = accumulate_pair(begin, end, [](const Point<double>& lhs, const Point<double>& rhs) {\n        return lhs.x*rhs.y - lhs.y*rhs.x;\n    });\n    return std::abs(sum / 2.0);\n}\n\n\ndouble perimeter(Isovist::Iter begin, Isovist::Iter end)\n{\n    return accumulate_pair(begin, end, [](const Point<double>& lhs, const Point<double>& rhs) {\n        return distance_between_points(lhs, rhs);\n    });\n}\n\n\ndouble circularity(double area, double perimeter)\n{\n    return (perimeter > 0.0) ? (4.0*M_PI*area) / (perimeter*perimeter) : 1.0;\n}\n\n\ntemplate <class BinaryOp>\ndouble accumulate_pair(Isovist::Iter begin, Isovist::Iter end, BinaryOp op)\n{\n    if(begin == end)\n    {\n        return 0.0;\n    }\n\n    double sum = 0.0;\n\n    for(auto first = begin, second = begin+1; second < end; ++first, ++second)\n    {\n        sum += op(*first, *second);\n    }\n\n    return sum;\n}\n\n} // namespace utils\n} // namespace vulcan\n", "meta": {"hexsha": "4802cf911c49a9d0d5e818a62eb0663d78072b1e", "size": 15972, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/isovist.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/utils/isovist.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/utils/isovist.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": 36.7172413793, "max_line_length": 127, "alphanum_fraction": 0.6507638367, "num_tokens": 4006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5267289392444076}}
{"text": "// Copyright (c) 2020\n// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n// ABN 41 687 119 230\n//\n// Author: Kazys Stepanas\n#include \"OhmConfig.h\"\n\n// #define GLM_ENABLE_EXPERIMENTAL\n#include <glm/gtx/norm.hpp>\n#include <glm/mat3x3.hpp>\n#include <glm/vec3.hpp>\n\n// Must come after glm includes due to usage on GPU.\n#include \"CovarianceVoxel.h\"\n\n#include \"NdtMap.h\"\n#include \"OccupancyMap.h\"\n#include \"Voxel.h\"\n#include \"VoxelMean.h\"\n#include \"VoxelOccupancy.h\"\n\n#include <glm/gtc/type_ptr.hpp>\n#include <glm/gtx/matrix_factorisation.hpp>\n\n#ifdef OHM_WITH_EIGEN\n#include <Eigen/Dense>\n#endif  // OHM_WITH_EIGEN\n\n#include <3esservermacros.h>\n#ifdef TES_ENABLE\n#include <3esserver.h>\n#include <shapes/3esshapes.h>\n#endif  // TES_ENABLE\n\n#include <array>\n\nnamespace ohm\n{\n#if OHM_COV_DEBUG\nnamespace\n{\nunsigned max_iterations = 0;\ndouble max_error = 0;\n}  // namespace\n#endif  // OHM_COV_DEBUG\n\nnamespace\n{\n#ifdef OHM_WITH_EIGEN\nvoid covarianceEigenDecompositionEigen(const CovarianceVoxel *cov, glm::dmat3 *eigenvectors, glm::dvec3 *eigenvalues)\n{\n  // This has been noted to be ~3x faster than the GLM iterative version.\n  const glm::dmat3 cov_mat = covarianceMatrix(cov);\n  // Both GLM and Eigen are column major. Direct mapping is fine.\n  const auto cov_eigen = Eigen::Matrix3d::ConstMapType(glm::value_ptr(cov_mat), 3, 3);\n\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver(cov_eigen);\n  Eigen::Vector3d evals = Eigen::Vector3d::Ones();\n  Eigen::Matrix3d evecs = Eigen::Matrix3d::Identity();\n\n  if (eigensolver.info() == Eigen::Success)\n  {\n    evals = eigensolver.eigenvalues();\n    evecs = eigensolver.eigenvectors();\n  }\n  const double det = evecs.determinant();\n  if (det < 0.0)\n  {\n    evecs.col(0) = -evecs.col(0);  // must be valid rotation matrix (determinant=+1)\n  }\n  else if (det == 0.0)\n  {\n    evecs = Eigen::Matrix3d::Identity();\n  }\n\n  *eigenvalues = glm::dvec3(evals[0], evals[1], evals[2]);\n\n  for (int r = 0; r < 3; ++r)\n  {\n    for (int c = 0; c < 3; ++c)\n    {\n      (*eigenvectors)[c][r] = evecs(r, c);\n    }\n  }\n}\n#else  // OHM_WITH_EIGEN\nvoid covarianceEigenDecompositionGlm(const CovarianceVoxel *cov, glm::dmat3 *eigenvectors, glm::dvec3 *eigenvalues)\n{\n  // This has been noted to be ~3x slower than the Eigen solver.\n  glm::dmat3 mat = covarianceMatrix(cov);\n\n  *eigenvectors = glm::dmat3(1.0);  // Identity initialisation\n\n  // Use QR decomposition to implement the QR algorithm.\n  // For this algorithm, we iterate as follows:\n  //\n  // P = cov * cov^T  // cov by cov transpose\n  // for i = 1 to N\n  //   Q, R = qr_decomposition(P)\n  //   P = R * Q\n  // end\n  //\n  // The eigenvalues converge in the diagonal of R.\n  // Meanwhile the eigenvectors are found by the product all the Q matrices\n  //\n  // We set a hard iteration limit, but we also check for convergence with last iteration and may early out.\n  const unsigned iteration_limit = 20;\n  glm::dmat3 q, r;\n  glm::dvec3 eigenvalues_last, eigenvalues_current(0);\n  const glm::dvec3 delta_threshold(1e-9);\n  for (unsigned i = 0; i < iteration_limit; ++i)\n  {\n    eigenvalues_last = eigenvalues_current;\n#if OHM_COV_DEBUG\n    max_iterations = std::max(max_iterations, i + 1);\n#endif  // OHM_COV_DEBUG\n\n    glm::qr_decompose(mat, q, r);\n    // Progressively refine the eigenvectors.\n    *eigenvectors = *eigenvectors * q;\n    // Update eigenvalues and check for convergence\n    eigenvalues_current[0] = r[0][0];\n    eigenvalues_current[1] = r[1][1];\n    eigenvalues_current[2] = r[2][2];\n\n    mat = r * q;\n\n    const glm::dvec3 eval_delta = glm::abs(eigenvalues_current - eigenvalues_last);\n    if (glm::all(glm::lessThanEqual(eval_delta, delta_threshold)))\n    {\n      break;\n    }\n  }\n\n#if OHM_COV_DEBUG\n  const glm::dvec3 eval_delta = glm::abs(eigenvalues_current - eigenvalues_last);\n  max_error = std::max(eval_delta.x, max_error);\n  max_error = std::max(eval_delta.y, max_error);\n  max_error = std::max(eval_delta.z, max_error);\n#endif  // OHM_COV_DEBUG\n\n  *eigenvalues = eigenvalues_current;\n}\n#endif  // OHM_WITH_EIGEN\n}  // namespace\n\nvoid covarianceEigenDecomposition(const CovarianceVoxel *cov, glm::dmat3 *eigenvectors, glm::dvec3 *eigenvalues)\n{\n#ifdef OHM_WITH_EIGEN\n  covarianceEigenDecompositionEigen(cov, eigenvectors, eigenvalues);\n#else   // OHM_WITH_EIGEN\n  covarianceEigenDecompositionGlm(cov, eigenvectors, eigenvalues);\n#endif  // OHM_WITH_EIGEN\n}\n\n\nvoid covarianceEstimatePrimaryNormal(const CovarianceVoxel *cov, glm::dvec3 *normal, int preferred_axis)\n{\n  glm::dmat3 eigenvectors;\n  glm::dvec3 eigenvalues;\n\n  covarianceEigenDecomposition(cov, &eigenvectors, &eigenvalues);\n\n  int smallest_eval_index = preferred_axis;\n  for (int i = 0; i < 3; ++i)\n  {\n    if (eigenvalues[i] < eigenvalues[smallest_eval_index])\n    {\n      smallest_eval_index = i;\n    }\n  }\n\n  const double length2 = glm::length2(eigenvectors[smallest_eval_index]);\n  // const double confidence = 1.0 - length2;\n  *normal = (length2 > 0) ? eigenvectors[smallest_eval_index] / glm::sqrt(length2) : eigenvectors[smallest_eval_index];\n  // return confidence;\n}\n\n\nbool covarianceUnitSphereTransformation(const CovarianceVoxel *cov, glm::dquat *rotation, glm::dvec3 *scale)\n{\n  glm::dmat3 eigenvectors;\n  glm::dvec3 eigenvalues;\n\n  covarianceEigenDecomposition(cov, &eigenvectors, &eigenvalues);\n\n  const double det = glm::determinant(eigenvectors);\n  if (det < 0.0)\n  {\n    eigenvectors[0] = -eigenvectors[0];  // must be valid rotation matrix (determinant=+1)\n  }\n  else if (det == 0.0)\n  {\n    eigenvectors = glm::dmat3(1.0);\n  }\n\n  *rotation = glm::dquat(eigenvectors);\n  for (int i = 0; i < 3; ++i)\n  {\n    const double eval = std::abs(eigenvalues[i]);  // abs just in case.\n    const double epsilon = 1e-9;\n    (*scale)[i] = (eval > epsilon) ? std::sqrt(eval) : eval;\n  }\n\n  return true;\n}\n\n\n#if OHM_COV_DEBUG\n#include <iostream>\nvoid covDebugStats()\n{\n  std::cout << \"QR algorithm max iterations: \" << max_iterations << std::endl;\n  std::cout << \"QR algorithm max error: \" << max_error << std::endl;\n}\n#endif  // OHM_COV_DEBUG\n\nvoid integrateNdtHit(NdtMap &map, const Key &key, const glm::dvec3 &sensor, const glm::dvec3 &sample, bool ndt_tm,\n                     const float sample_intensity)\n{\n  OccupancyMap &occupancy_map = map.map();\n  Voxel<float> occupancy_voxel(&occupancy_map, occupancy_map.layout().occupancyLayer(), key);\n  Voxel<VoxelMean> mean_voxel(occupancy_voxel, occupancy_map.layout().meanLayer());\n  Voxel<CovarianceVoxel> cov_voxel(occupancy_voxel, occupancy_map.layout().covarianceLayer());\n  const glm::dvec3 voxel_centre = occupancy_map.voxelCentreGlobal(key);\n\n  assert(occupancy_voxel.isValid());\n  assert(mean_voxel.isValid());\n  assert(cov_voxel.isValid());\n\n  // Keep clang analysis happy\n#ifdef __clang_analyzer__\n  if (!occupancy_voxel.voxelMemory() || !mean_voxel.voxelMemory() || !cov_voxel.voxelMemory())\n  {\n    return;\n  }\n#endif  // __clang_analyzer__\n\n  // NDT-OM\n  CovarianceVoxel cov;\n  VoxelMean mean;\n  float occupancy;\n  occupancy_voxel.read(&occupancy);\n  mean_voxel.read(&mean);\n  cov_voxel.read(&cov);\n\n  float updated_value = occupancy;\n  const glm::dvec3 voxel_pos = position(mean, voxel_centre, occupancy_map.resolution());\n\n  // NDT-TM\n  if (ndt_tm)\n  {\n    Voxel<IntensityMeanCov> intensity_voxel(&occupancy_map, occupancy_map.layout().intensityLayer(), key);\n    Voxel<HitMissCount> hit_miss_count_voxel(&occupancy_map, occupancy_map.layout().hitMissCountLayer(), key);\n\n    if (intensity_voxel.isLayerValid() && hit_miss_count_voxel.isLayerValid())\n    {\n      IntensityMeanCov intensity;\n      HitMissCount hit_miss_count;\n      intensity_voxel.read(&intensity);\n      hit_miss_count_voxel.read(&hit_miss_count);\n\n      const bool reinitialise_permeability_with_covariance = true;  // TODO: make a parameter of map\n      calculateHitMissUpdateOnHit(&cov, updated_value, &hit_miss_count, sensor, sample, voxel_pos, mean.count,\n                                  unobservedOccupancyValue(), reinitialise_permeability_with_covariance,\n                                  map.adaptationRate(), map.sensorNoise(), map.reinitialiseCovarianceThreshold(),\n                                  map.reinitialiseCovariancePointCount(), map.ndtSampleThreshold());\n\n      hit_miss_count_voxel.write(hit_miss_count);\n\n      calculateIntensityUpdateOnHit(&intensity, updated_value, sample_intensity, map.initialIntensityCovariance(),\n                                    mean.count, map.reinitialiseCovarianceThreshold(),\n                                    map.reinitialiseCovariancePointCount());\n\n      intensity_voxel.write(intensity);\n    }\n  }\n\n  if (calculateHitWithCovariance(&cov, &updated_value, sample, voxel_pos, mean.count, occupancy_map.hitValue(),\n                                 unobservedOccupancyValue(), float(occupancy_map.resolution()),\n                                 map.reinitialiseCovarianceThreshold(), map.reinitialiseCovariancePointCount()))\n  {\n    // Covariance matrix has reset. Reset the point count to clear the mean value.\n    mean.count = 0;\n  }\n\n  // Ensure we update the occupancy within the configured map limits.\n  occupancyAdjustUp(\n    &occupancy, occupancy, updated_value, unobservedOccupancyValue(), occupancy_map.maxVoxelValue(),\n    occupancy_map.saturateAtMinValue() ? occupancy_map.minVoxelValue() : std::numeric_limits<float>::lowest(),\n    occupancy_map.saturateAtMaxValue() ? occupancy_map.maxVoxelValue() : std::numeric_limits<float>::max(), false);\n  occupancy_voxel.write(occupancy);\n\n  // Update the voxel mean.\n  updatePosition(&mean, sample, voxel_centre, occupancy_map.resolution());\n  mean_voxel.write(mean);\n  cov_voxel.write(cov);\n}\n\n\nvoid integrateNdtMiss(NdtMap &map, const Key &key, const glm::dvec3 &sensor, const glm::dvec3 &sample, bool ndt_tm)\n{\n  OccupancyMap &occupancy_map = map.map();\n  Voxel<float> occupancy_voxel(&occupancy_map, occupancy_map.layout().occupancyLayer(), key);\n  Voxel<const VoxelMean> mean_voxel(occupancy_voxel, occupancy_map.layout().meanLayer());\n  Voxel<const CovarianceVoxel> cov_voxel(occupancy_voxel, occupancy_map.layout().covarianceLayer());\n  const glm::dvec3 voxel_centre = occupancy_map.voxelCentreGlobal(key);\n\n  assert(occupancy_voxel.isValid());\n  assert(mean_voxel.isValid());\n  assert(cov_voxel.isValid());\n\n  // Keep clang analysis happy\n#ifdef __clang_analyzer__\n  if (!occupancy_voxel.voxelMemory() || !mean_voxel.voxelMemory() || !cov_voxel.voxelMemory())\n  {\n    return;\n  }\n#endif  // __clang_analyzer__\n\n  // NDT-OM\n  CovarianceVoxel cov;\n  VoxelMean mean;\n  float occupancy;\n  occupancy_voxel.read(&occupancy);\n  mean_voxel.read(&mean);\n  cov_voxel.read(&cov);\n\n  float updated_value = occupancy;\n#ifdef TES_ENABLE\n  const float initial_value = occupancy;\n  glm::dvec3 voxel_maximum_likelihood;\n#endif  // TES_ENABLE\n  const glm::dvec3 voxel_mean = position(mean, voxel_centre, occupancy_map.resolution());\n  bool confirm_miss = false;\n  calculateMissNdt(&cov, &updated_value, &confirm_miss, sensor, sample, voxel_mean, mean.count,\n                   unobservedOccupancyValue(), occupancy_map.missValue(), map.adaptationRate(), map.sensorNoise(),\n                   map.ndtSampleThreshold());\n\n  if (ndt_tm && confirm_miss)\n  {\n    Voxel<HitMissCount> hit_miss_count_voxel(&occupancy_map, occupancy_map.layout().hitMissCountLayer(), key);\n    if (hit_miss_count_voxel.isLayerValid())\n    {\n      HitMissCount hit_miss_count;\n      hit_miss_count_voxel.read(&hit_miss_count);\n      ++hit_miss_count.miss_count;\n      hit_miss_count_voxel.write(hit_miss_count);\n    }\n  }\n\n  occupancyAdjustDown(\n    &occupancy, occupancy, updated_value, unobservedOccupancyValue(), occupancy_map.minVoxelValue(),\n    occupancy_map.saturateAtMinValue() ? occupancy_map.minVoxelValue() : std::numeric_limits<float>::lowest(),\n    occupancy_map.saturateAtMaxValue() ? occupancy_map.maxVoxelValue() : std::numeric_limits<float>::max(), false);\n  occupancy_voxel.write(occupancy);\n\n#ifdef TES_ENABLE\n  if (map.trace())\n  {\n    const glm::dvec3 voxel_centre = occupancy_map.voxelCentreGlobal(key);\n    TES_BOX_W(g_tes, TES_COLOUR(OrangeRed), tes::Id(cov_voxel.voxelMemory()),\n              tes::Transform(glm::value_ptr(voxel_centre), glm::value_ptr(glm::dvec3(occupancy_map.resolution()))));\n    TES_SERVER_UPDATE(g_tes, 0.0f);\n\n    bool drew_surfel = false;\n    glm::dquat rot;\n    glm::dvec3 scale;\n    if (covarianceUnitSphereTransformation(&cov, &rot, &scale))\n    {\n      TES_SPHERE(g_tes, TES_COLOUR(SeaGreen), tes::Id(cov_voxel.voxelMemory()),\n                 tes::Transform(tes::Vector3d(glm::value_ptr(voxel_mean)), tes::Quaterniond(rot.x, rot.y, rot.z, rot.w),\n                                tes::Vector3d(glm::value_ptr(scale))));\n      drew_surfel = true;\n    }\n\n    // Trace the voxel mean, maximum likelihood point and the ellipsoid.\n    // Mean\n    const float mean_pos_radius = 0.05f;\n    const float likely_pos_radius = 0.1f;\n    TES_SPHERE(g_tes, TES_COLOUR(OrangeRed), tes::Id(&voxel_mean),\n               tes::Spherical(glm::value_ptr(voxel_mean), mean_pos_radius));\n    // Maximum likelihood\n    TES_SPHERE_W(g_tes, TES_COLOUR(PowderBlue), tes::Id(&voxel_maximum_likelihood),\n                 tes::Spherical(glm::value_ptr(voxel_maximum_likelihood), likely_pos_radius));\n\n    std::array<char, 64> text;  // NOLINT(readability-magic-numbers)\n    text[0] = '\\0';\n    sprintf(text.data(), \"P %.3f\", valueToProbability(occupancy - initial_value));\n    TES_TEXT2D_WORLD(g_tes, TES_COLOUR(White), text.data(), tes::Id(),\n                     tes::Spherical(tes::Vector3d(glm::value_ptr(voxel_centre))));\n\n    TES_SERVER_UPDATE(g_tes, 0.0f);\n    TES_BOX_END(g_tes, tes::Id(cov_voxel.voxelMemory()));\n    TES_SPHERE_END(g_tes, tes::Id(&voxel_mean));\n    TES_SPHERE_END(g_tes, tes::Id(&voxel_maximum_likelihood));\n    if (drew_surfel)\n    {\n      TES_SPHERE_END(g_tes, tes::Id(cov_voxel.voxelMemory()));\n    }\n  }\n#endif  // TES_ENABLE\n}\n}  // namespace ohm\n", "meta": {"hexsha": "8004ca386a6c856f0ec7b1738fe18e795dbc549c", "size": 13907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ohm/CovarianceVoxel.cpp", "max_stars_repo_name": "jmackay2/ohm", "max_stars_repo_head_hexsha": "15f7b9f221419d2faf3802404a2f378ef570a990", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2020-06-09T23:26:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T12:16:33.000Z", "max_issues_repo_path": "ohm/CovarianceVoxel.cpp", "max_issues_repo_name": "jmackay2/ohm", "max_issues_repo_head_hexsha": "15f7b9f221419d2faf3802404a2f378ef570a990", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-10T05:50:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T02:50:01.000Z", "max_forks_repo_path": "ohm/CovarianceVoxel.cpp", "max_forks_repo_name": "jmackay2/ohm", "max_forks_repo_head_hexsha": "15f7b9f221419d2faf3802404a2f378ef570a990", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-02-25T15:08:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T13:08:03.000Z", "avg_line_length": 34.3382716049, "max_line_length": 120, "alphanum_fraction": 0.7008700654, "num_tokens": 3913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6113819874558603, "lm_q1q2_score": 0.5267289384040337}}
{"text": "#include \"cnn/saxe-init.h\"\n#include \"cnn/tensor.h\"\n\n#include <random>\n#include <cstring>\n\n#include <Eigen/SVD>\n\nusing namespace std;\n\nnamespace cnn {\n\ninline Eigen::MatrixXf EigenRandomNormal(int dim, real mean, real stddev) {\n  normal_distribution<real> distribution(mean, stddev);\n  auto b = [&] (real) {return distribution(*rndeng);};\n  Eigen::MatrixXf r = Eigen::MatrixXf::NullaryExpr(dim, dim, b);\n  return r;\n}\n\nvoid OrthonormalRandom(int dim, real g, Tensor& x) {\n  Eigen::MatrixXf m = EigenRandomNormal(dim, 0.0, 0.01);\n  Eigen::JacobiSVD<Eigen::MatrixXf> svd(m, Eigen::ComputeFullU);\n  *x = svd.matrixU();\n}\n\n}\n\n", "meta": {"hexsha": "737ddba8dca7b697d4dc3830c49330ff2ff5dae7", "size": 621, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cnn/cnn/saxe-init.cc", "max_stars_repo_name": "lstmparser/orig_list_lstm", "max_stars_repo_head_hexsha": "335edbb9680f1dd0bcbf9e4adbbc0eef4763ebd3", "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": "cnn/cnn/saxe-init.cc", "max_issues_repo_name": "lstmparser/orig_list_lstm", "max_issues_repo_head_hexsha": "335edbb9680f1dd0bcbf9e4adbbc0eef4763ebd3", "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": "cnn/cnn/saxe-init.cc", "max_forks_repo_name": "lstmparser/orig_list_lstm", "max_forks_repo_head_hexsha": "335edbb9680f1dd0bcbf9e4adbbc0eef4763ebd3", "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.1785714286, "max_line_length": 75, "alphanum_fraction": 0.6988727858, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5267238589191177}}
{"text": "/**\n * @file GINS.hpp\n * @author LauZanMo (LauZanMo@whu.edu.cn)\n * @brief GINS class\n * @version 1.0\n * @date 2021-07-14\n *\n * @copyright Copyright (c) 2021 WHU-Drones\n *\n */\n#pragma once\n\n#include <Eigen/Geometry>\n#include <iostream>\n\n#include \"DataStorage.hpp\"\n#include \"INSMechanization.hpp\"\n#include \"Utils.hpp\"\n\nnamespace iNav {\n\nusing ErrorType = Eigen::Matrix<double, 21, 1>;\nusing qType = Eigen::Matrix<double, 18, 18>;\nusing GType = Eigen::Matrix<double, 21, 18>;\nusing HType = Eigen::Matrix<double, 3, 21>;\nusing KType = Eigen::Matrix<double, 21, 3>;\nusing Matrix21d = Eigen::Matrix<double, 21, 21>;\n\nclass GINS : INS::INSMechanization {\npublic:\n  GINS(const iNav::NavData& init_nav_data, const IMUParam& init_imu_param,\n       const Eigen::Vector3d& l_b, const iNav::IMUData& init_imu_data);\n  ~GINS();\n\n  NavData Mechanization(IMUData data, bool record_data = true);\n  void Prediction(bool record_data = true);\n  NavData GNSSUpdate(GnssData gnss_data, IMUData imu_data);\n\nprivate:\n  Eigen::Vector3d gyro_bias_, acc_bias_, gyro_scalar_, acc_scalar_;\n  Eigen::Vector3d l_b_;\n  ErrorType delta_x_;\n  qType q_;\n  GType G_, last_G_;\n  Matrix21d P_, Phi_, Q_;\n  IMUParam IMU_param_;\n\n  inline Eigen::Vector3d CorrectGyroError(const Eigen::Vector3d& gyro_raw) {\n    return Eigen::Vector3d((gyro_raw - gyro_bias_ * delta_time_).array() /\n                           (1 + gyro_scalar_.array()));\n  }\n  inline Eigen::Vector3d CorrectAccError(const Eigen::Vector3d& acc_raw) {\n    return Eigen::Vector3d((acc_raw - acc_bias_ * delta_time_).array() /\n                           (1 + acc_scalar_.array()));\n  }\n\n  Matrix21d SetP(const Eigen::Vector3d& position_std,\n                 const Eigen::Vector3d& velocity_std,\n                 const Eigen::Vector3d& theta_std, const IMUParam& param);\n  qType Setq(const IMUParam& param);\n  Matrix21d ComputeF();\n  GType ComputeG(const Eigen::Quaterniond& q_b_to_n);\n  HType ComputeHr();\n  NavData NavDataInterpolation(const NavData& last_nav_data,\n                               const NavData& nav_data, const double& ratio,\n                               const double& timestamp);\n  NavData CorrectNavDataAndIMUError(const NavData& data, ErrorType& error);\n  Eigen::Vector3d ComputeZr(const GnssData& gnss_data, const NavData& nav_data);\n};\n\n}  // namespace iNav\n", "meta": {"hexsha": "dc69f7e17ff5d5f2145d24e8058466f60b02df52", "size": 2306, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/GINS.hpp", "max_stars_repo_name": "LauZanMo/INS", "max_stars_repo_head_hexsha": "13bd9427c98ba551318f76c94dc793273d2dd070", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-13T02:29:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T02:29:54.000Z", "max_issues_repo_path": "include/GINS.hpp", "max_issues_repo_name": "LauZanMo/INS", "max_issues_repo_head_hexsha": "13bd9427c98ba551318f76c94dc793273d2dd070", "max_issues_repo_licenses": ["MIT"], "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/GINS.hpp", "max_forks_repo_name": "LauZanMo/INS", "max_forks_repo_head_hexsha": "13bd9427c98ba551318f76c94dc793273d2dd070", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-28T01:05:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T01:05:16.000Z", "avg_line_length": 32.0277777778, "max_line_length": 80, "alphanum_fraction": 0.6830008673, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5267238533367122}}
{"text": "/*\n * MA.cpp\n *\n *  Created on: 2015\u5e742\u670816\u65e5\n *      Author: fasiondog\n */\n\n#include <boost/algorithm/string.hpp>\n#include \"MA.h\"\n#include \"SMA.h\"\n#include \"EMA.h\"\n#include \"AMA.h\"\n\nnamespace hku {\n\nIndicator HKU_API MA(const Indicator& data, int n, const string& type) {\n    string str_type(type);\n    boost::to_upper(str_type);\n    if (str_type == \"SMA\") {\n        return SMA(data, n);\n    } else if (str_type == \"EMA\") {\n        return EMA(data, n);\n    } else if (str_type == \"AMA\") {\n        return AMA(data, n);\n    } else {\n        return SMA(data, n);\n    }\n}\n\nIndicator HKU_API MA(int n, const string& type) {\n    string str_type(type);\n    boost::to_upper(str_type);\n    if (str_type == \"SMA\") {\n        return SMA(n);\n    } else if (str_type == \"EMA\") {\n        return EMA(n);\n    } else if (str_type == \"AMA\") {\n        return AMA(n);\n    } else {\n        return SMA(n);\n    }\n}\n\n} /* namespae hku */\n\n\n", "meta": {"hexsha": "b5d4d654e02fe820e15a507ec13c284004c6588f", "size": 913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/hikyuu/indicator/crt/MA.cpp", "max_stars_repo_name": "CodingNowNow/jiaoyi", "max_stars_repo_head_hexsha": "57513f8cf0d282fa70ac9e8e76ff785d7a2a019c", "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/hikyuu/indicator/crt/MA.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/hikyuu/indicator/crt/MA.cpp", "max_forks_repo_name": "archya/hikyuu", "max_forks_repo_head_hexsha": "2305a977a78bab832bf8fcb4d66482dfef442c9d", "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": 19.4255319149, "max_line_length": 72, "alphanum_fraction": 0.5509309967, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.5267238532779653}}
{"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\n/*\n*   Benchmark:  Sparse matrix operations, i.e. matrix-vector products (sparse.cpp and sparse.cu are identical, the latter being required for compilation using CUDA nvcc)\n*\n*/\n\n//#define VIENNACL_BUILD_INFO\n#ifndef NDEBUG\n #define NDEBUG\n#endif\n\n#define VIENNACL_WITH_UBLAS 1\n\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/coordinate_matrix.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/ell_matrix.hpp\"\n#include \"viennacl/hyb_matrix.hpp\"\n#include \"viennacl/sliced_ell_matrix.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n#include \"viennacl/linalg/ilu.hpp\"\n#include \"viennacl/tools/timer.hpp\"\n\n\n#include <iostream>\n#include <vector>\n\n\n#define BENCHMARK_RUNS          10\n\n\ninline void printOps(double num_ops, double exec_time)\n{\n  std::cout << \"GFLOPs: \" << num_ops / (1000000 * exec_time * 1000) << std::endl;\n}\n\n\ntemplate<typename ScalarType>\nint run_benchmark()\n{\n  viennacl::tools::timer timer;\n  double exec_time;\n\n  ScalarType std_factor1 = ScalarType(3.1415);\n  ScalarType std_factor2 = ScalarType(42.0);\n  viennacl::scalar<ScalarType> vcl_factor1(std_factor1);\n  viennacl::scalar<ScalarType> vcl_factor2(std_factor2);\n\n  boost::numeric::ublas::vector<ScalarType> ublas_vec1;\n  boost::numeric::ublas::vector<ScalarType> ublas_vec2;\n\n  boost::numeric::ublas::compressed_matrix<ScalarType> ublas_matrix;\n  if (!viennacl::io::read_matrix_market_file(ublas_matrix, \"../examples/testdata/mat65k.mtx\"))\n  {\n    std::cout << \"Error reading Matrix file\" << std::endl;\n    return 0;\n  }\n  //unsigned int cg_mat_size = cg_mat.size();\n  std::cout << \"done reading matrix\" << std::endl;\n\n  ublas_vec1 = boost::numeric::ublas::scalar_vector<ScalarType>(ublas_matrix.size1(), ScalarType(1.0));\n  ublas_vec2 = ublas_vec1;\n\n  viennacl::compressed_matrix<ScalarType, 1> vcl_compressed_matrix_1;\n  viennacl::compressed_matrix<ScalarType, 4> vcl_compressed_matrix_4;\n  viennacl::compressed_matrix<ScalarType, 8> vcl_compressed_matrix_8;\n\n  viennacl::coordinate_matrix<ScalarType> vcl_coordinate_matrix_128;\n\n  viennacl::ell_matrix<ScalarType, 1> vcl_ell_matrix_1;\n  viennacl::hyb_matrix<ScalarType, 1> vcl_hyb_matrix_1;\n  viennacl::sliced_ell_matrix<ScalarType> vcl_sliced_ell_matrix_1;\n\n  viennacl::vector<ScalarType> vcl_vec1(ublas_vec1.size());\n  viennacl::vector<ScalarType> vcl_vec2(ublas_vec1.size());\n\n  //cpu to gpu:\n  viennacl::copy(ublas_matrix, vcl_compressed_matrix_1);\n  #ifndef VIENNACL_EXPERIMENTAL_DOUBLE_PRECISION_WITH_STREAM_SDK_ON_GPU\n  viennacl::copy(ublas_matrix, vcl_compressed_matrix_4);\n  viennacl::copy(ublas_matrix, vcl_compressed_matrix_8);\n  #endif\n  viennacl::copy(ublas_matrix, vcl_coordinate_matrix_128);\n  viennacl::copy(ublas_matrix, vcl_ell_matrix_1);\n  viennacl::copy(ublas_matrix, vcl_hyb_matrix_1);\n  viennacl::copy(ublas_matrix, vcl_sliced_ell_matrix_1);\n  viennacl::copy(ublas_vec1, vcl_vec1);\n  viennacl::copy(ublas_vec2, vcl_vec2);\n\n\n  ///////////// Matrix operations /////////////////\n\n  std::cout << \"------- Matrix-Vector product on CPU ----------\" << std::endl;\n  timer.start();\n  for (int runs=0; runs<BENCHMARK_RUNS; ++runs)\n  {\n    //ublas_vec1 = boost::numeric::ublas::prod(ublas_matrix, ublas_vec2);\n    boost::numeric::ublas::axpy_prod(ublas_matrix, ublas_vec2, ublas_vec1, true);\n  }\n  exec_time = timer.get();\n  std::cout << \"CPU time: \" << exec_time << std::endl;\n  std::cout << \"CPU \"; printOps(2.0 * static_cast<double>(ublas_matrix.nnz()), static_cast<double>(exec_time) / static_cast<double>(BENCHMARK_RUNS));\n  std::cout << ublas_vec1[0] << std::endl;\n\n\n  std::cout << \"------- Matrix-Vector product with compressed_matrix ----------\" << std::endl;\n\n\n  vcl_vec1 = viennacl::linalg::prod(vcl_compressed_matrix_1, vcl_vec2); //startup calculation\n  vcl_vec1 = viennacl::linalg::prod(vcl_compressed_matrix_4, vcl_vec2); //startup calculation\n  vcl_vec1 = viennacl::linalg::prod(vcl_compressed_matrix_8, vcl_vec2); //startup calculation\n  //std_result = 0.0;\n\n  viennacl::backend::finish();\n  timer.start();\n  for (int runs=0; runs<BENCHMARK_RUNS; ++runs)\n  {\n    vcl_vec1 = viennacl::linalg::prod(vcl_compressed_matrix_1, vcl_vec2);\n  }\n  viennacl::backend::finish();\n  exec_time = timer.get();\n  std::cout << \"GPU time align1: \" << exec_time << std::endl;\n  std::cout << \"GPU align1 \"; printOps(2.0 * static_cast<double>(ublas_matrix.nnz()), static_cast<double>(exec_time) / static_cast<double>(BENCHMARK_RUNS));\n  std::cout << vcl_vec1[0] << std::endl;\n\n  std::cout << \"Testing triangular solves: compressed_matrix\" << std::endl;\n\n  viennacl::copy(ublas_vec1, vcl_vec1);\n  viennacl::linalg::inplace_solve(trans(vcl_compressed_matrix_1), vcl_vec1, viennacl::linalg::unit_lower_tag());\n  viennacl::copy(ublas_vec1, vcl_vec1);\n  std::cout << \"ublas...\" << std::endl;\n  timer.start();\n  boost::numeric::ublas::inplace_solve(trans(ublas_matrix), ublas_vec1, boost::numeric::ublas::unit_lower_tag());\n  std::cout << \"Time elapsed: \" << timer.get() << std::endl;\n  std::cout << \"ViennaCL...\" << std::endl;\n  viennacl::backend::finish();\n  timer.start();\n  viennacl::linalg::inplace_solve(trans(vcl_compressed_matrix_1), vcl_vec1, viennacl::linalg::unit_lower_tag());\n  viennacl::backend::finish();\n  std::cout << \"Time elapsed: \" << timer.get() << std::endl;\n\n  ublas_vec1 = boost::numeric::ublas::prod(ublas_matrix, ublas_vec2);\n\n  viennacl::backend::finish();\n  timer.start();\n  for (int runs=0; runs<BENCHMARK_RUNS; ++runs)\n  {\n    vcl_vec1 = viennacl::linalg::prod(vcl_compressed_matrix_4, vcl_vec2);\n  }\n  viennacl::backend::finish();\n  exec_time = timer.get();\n  std::cout << \"GPU time align4: \" << exec_time << std::endl;\n  std::cout << \"GPU align4 \"; printOps(2.0 * static_cast<double>(ublas_matrix.nnz()), static_cast<double>(exec_time) / static_cast<double>(BENCHMARK_RUNS));\n  std::cout << vcl_vec1[0] << std::endl;\n\n  viennacl::backend::finish();\n  timer.start();\n  for (int runs=0; runs<BENCHMARK_RUNS; ++runs)\n  {\n    vcl_vec1 = viennacl::linalg::prod(vcl_compressed_matrix_8, vcl_vec2);\n  }\n  viennacl::backend::finish();\n  exec_time = timer.get();\n  std::cout << \"GPU time align8: \" << exec_time << std::endl;\n  std::cout << \"GPU align8 \"; printOps(2.0 * static_cast<double>(ublas_matrix.nnz()), static_cast<double>(exec_time) / static_cast<double>(BENCHMARK_RUNS));\n  std::cout << vcl_vec1[0] << std::endl;\n\n\n  std::cout << \"------- Matrix-Vector product with coordinate_matrix ----------\" << std::endl;\n  vcl_vec1 = viennacl::linalg::prod(vcl_coordinate_matrix_128, vcl_vec2); //startup calculation\n  viennacl::backend::finish();\n\n  viennacl::copy(vcl_vec1, ublas_vec2);\n  long err_cnt = 0;\n  for (std::size_t i=0; i<ublas_vec1.size(); ++i)\n  {\n    if ( fabs(ublas_vec1[i] - ublas_vec2[i]) / std::max(fabs(ublas_vec1[i]), fabs(ublas_vec2[i])) > 1e-2)\n    {\n      std::cout << \"Error at index \" << i << \": Should: \" << ublas_vec1[i] << \", Is: \" << ublas_vec2[i] << std::endl;\n      ++err_cnt;\n      if (err_cnt > 5)\n        break;\n    }\n  }\n\n  viennacl::backend::finish();\n  timer.start();\n  for (int runs=0; runs<BENCHMARK_RUNS; ++runs)\n  {\n    vcl_vec1 = viennacl::linalg::prod(vcl_coordinate_matrix_128, vcl_vec2);\n  }\n  viennacl::backend::finish();\n  exec_time = timer.get();\n  std::cout << \"GPU time: \" << exec_time << std::endl;\n  std::cout << \"GPU \"; printOps(2.0 * static_cast<double>(ublas_matrix.nnz()), static_cast<double>(exec_time) / static_cast<double>(BENCHMARK_RUNS));\n  std::cout << vcl_vec1[0] << std::endl;\n\n\n  std::cout << \"------- Matrix-Vector product with ell_matrix ----------\" << std::endl;\n  vcl_vec1 = viennacl::linalg::prod(vcl_ell_matrix_1, vcl_vec2); //startup calculation\n  viennacl::backend::finish();\n\n  viennacl::copy(vcl_vec1, ublas_vec2);\n  err_cnt = 0;\n  for (std::size_t i=0; i<ublas_vec1.size(); ++i)\n  {\n    if ( fabs(ublas_vec1[i] - ublas_vec2[i]) / std::max(fabs(ublas_vec1[i]), fabs(ublas_vec2[i])) > 1e-2)\n    {\n      std::cout << \"Error at index \" << i << \": Should: \" << ublas_vec1[i] << \", Is: \" << ublas_vec2[i] << std::endl;\n      ++err_cnt;\n      if (err_cnt > 5)\n        break;\n    }\n  }\n\n  viennacl::backend::finish();\n  timer.start();\n  for (int runs=0; runs<BENCHMARK_RUNS; ++runs)\n  {\n    vcl_vec1 = viennacl::linalg::prod(vcl_ell_matrix_1, vcl_vec2);\n  }\n  viennacl::backend::finish();\n  exec_time = timer.get();\n  std::cout << \"GPU time: \" << exec_time << std::endl;\n  std::cout << \"GPU \"; printOps(2.0 * static_cast<double>(ublas_matrix.nnz()), static_cast<double>(exec_time) / static_cast<double>(BENCHMARK_RUNS));\n  std::cout << vcl_vec1[0] << std::endl;\n\n\n  std::cout << \"------- Matrix-Vector product with hyb_matrix ----------\" << std::endl;\n  vcl_vec1 = viennacl::linalg::prod(vcl_hyb_matrix_1, vcl_vec2); //startup calculation\n  viennacl::backend::finish();\n\n  viennacl::copy(vcl_vec1, ublas_vec2);\n  err_cnt = 0;\n  for (std::size_t i=0; i<ublas_vec1.size(); ++i)\n  {\n    if ( fabs(ublas_vec1[i] - ublas_vec2[i]) / std::max(fabs(ublas_vec1[i]), fabs(ublas_vec2[i])) > 1e-2)\n    {\n      std::cout << \"Error at index \" << i << \": Should: \" << ublas_vec1[i] << \", Is: \" << ublas_vec2[i] << std::endl;\n      ++err_cnt;\n      if (err_cnt > 5)\n        break;\n    }\n  }\n\n  viennacl::backend::finish();\n  timer.start();\n  for (int runs=0; runs<BENCHMARK_RUNS; ++runs)\n  {\n    vcl_vec1 = viennacl::linalg::prod(vcl_hyb_matrix_1, vcl_vec2);\n  }\n  viennacl::backend::finish();\n  exec_time = timer.get();\n  std::cout << \"GPU time: \" << exec_time << std::endl;\n  std::cout << \"GPU \"; printOps(2.0 * static_cast<double>(ublas_matrix.nnz()), static_cast<double>(exec_time) / static_cast<double>(BENCHMARK_RUNS));\n  std::cout << vcl_vec1[0] << std::endl;\n\n\n  std::cout << \"------- Matrix-Vector product with sliced_ell_matrix ----------\" << std::endl;\n  vcl_vec1 = viennacl::linalg::prod(vcl_sliced_ell_matrix_1, vcl_vec2); //startup calculation\n  viennacl::backend::finish();\n\n  viennacl::copy(vcl_vec1, ublas_vec2);\n  err_cnt = 0;\n  for (std::size_t i=0; i<ublas_vec1.size(); ++i)\n  {\n    if ( fabs(ublas_vec1[i] - ublas_vec2[i]) / std::max(fabs(ublas_vec1[i]), fabs(ublas_vec2[i])) > 1e-2)\n    {\n      std::cout << \"Error at index \" << i << \": Should: \" << ublas_vec1[i] << \", Is: \" << ublas_vec2[i] << std::endl;\n      ++err_cnt;\n      if (err_cnt > 5)\n        break;\n    }\n  }\n\n  viennacl::backend::finish();\n  timer.start();\n  for (int runs=0; runs<BENCHMARK_RUNS; ++runs)\n  {\n    vcl_vec1 = viennacl::linalg::prod(vcl_sliced_ell_matrix_1, vcl_vec2);\n  }\n  viennacl::backend::finish();\n  exec_time = timer.get();\n  std::cout << \"GPU time: \" << exec_time << std::endl;\n  std::cout << \"GPU \"; printOps(2.0 * static_cast<double>(ublas_matrix.nnz()), static_cast<double>(exec_time) / static_cast<double>(BENCHMARK_RUNS));\n  std::cout << vcl_vec1[0] << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n\nint main()\n{\n  std::cout << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << \"               Device Info\" << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n\n#ifdef VIENNACL_WITH_OPENCL\n  std::cout << viennacl::ocl::current_device().info() << std::endl;\n#endif\n  std::cout << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << \"## Benchmark :: Sparse\" << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << std::endl;\n  std::cout << \"   -------------------------------\" << std::endl;\n  std::cout << \"   # benchmarking single-precision\" << std::endl;\n  std::cout << \"   -------------------------------\" << std::endl;\n  run_benchmark<float>();\n#ifdef VIENNACL_WITH_OPENCL\n  if ( viennacl::ocl::current_device().double_support() )\n#endif\n  {\n    std::cout << std::endl;\n    std::cout << \"   -------------------------------\" << std::endl;\n    std::cout << \"   # benchmarking double-precision\" << std::endl;\n    std::cout << \"   -------------------------------\" << std::endl;\n    run_benchmark<double>();\n  }\n  return 0;\n}\n\n", "meta": {"hexsha": "1b9379fb7aa5e0a600e6d2337c13fe7c4652c779", "size": 13171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/benchmarks/sparse.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/benchmarks/sparse.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/benchmarks/sparse.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": 37.3116147309, "max_line_length": 169, "alphanum_fraction": 0.6353352061, "num_tokens": 3968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891348788759, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5267238505455095}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <mimkl/kernels.hpp>\n#include <mimkl/linear_algebra.hpp>\n#include <stdexcept>\n\nint main(int argc, char **argv)\n{\n    try\n    {\n        Eigen::Matrix<double, 2, 3> X;\n        Eigen::SparseMatrix<double> L(3, 3);\n        double p;\n        double c;\n        Eigen::Matrix<double, 2, 2> K_reference;\n\n        X << 1., 2., 3., 4., 5., 6.;\n        mimkl::linear_algebra::fill_sparse_diagonal(L, 1.0);\n        p = 1;\n        c = 0;\n        K_reference << 14., 32., 32., 77.;\n\n        Eigen::Matrix<double, 2, 2> K =\n        mimkl::induction::induce_polynomial_kernel<MATRIX(double)>(X, X, L, p, c);\n        assert((K - K_reference).norm() == 0.0);\n\n        return EXIT_SUCCESS;\n    }\n    catch (const std::exception &e)\n    {\n        std::cerr << e.what();\n        return EXIT_FAILURE;\n    }\n}\n", "meta": {"hexsha": "08472175026c66eb6b7b1b6595beb2218978fdb0", "size": 862, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/polynomial_induction/main.cpp", "max_stars_repo_name": "vishalbelsare/mimkl", "max_stars_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T23:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:00:03.000Z", "max_issues_repo_path": "test/polynomial_induction/main.cpp", "max_issues_repo_name": "vishalbelsare/mimkl", "max_issues_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T13:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:20:55.000Z", "max_forks_repo_path": "test/polynomial_induction/main.cpp", "max_forks_repo_name": "vishalbelsare/mimkl", "max_forks_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T09:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:40:27.000Z", "avg_line_length": 23.9444444444, "max_line_length": 82, "alphanum_fraction": 0.5498839907, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.5267238419956605}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <fc/crypto/rand.hpp>\n\n#include <cmath>\n\nstatic void check_randomness( const char* buffer, size_t len ) {\n    if (len == 0) { return; }\n    // count bit runs and 0's / 1's\n    unsigned int zc = 0, oc = 0, rc = 0, last = 2;\n    for (size_t k = len; k; k--) {\n        char c = *buffer++;\n        for (int i = 0; i < 8; i++) {\n            unsigned int bit = c & 1;\n            c >>= 1;\n            if (bit) { oc++; } else { zc++; }\n            if (bit != last) { rc++; last = bit; }\n        }\n    }\n    BOOST_CHECK_EQUAL( 8*len, zc + oc );\n    double E = 1 + (zc + oc) / 2.0;\n    double variance = (E - 1) * (E - 2) / (oc + zc - 1);\n    double sigma = sqrt(variance);\n    std::cout << \"rc :\"<< rc <<\"; E: \"<< E <<\"; sigma: \" <<sigma <<\"\\n\";\n    BOOST_CHECK( rc > E - 2* sigma && rc < E + 2* sigma);\n}\n\nBOOST_AUTO_TEST_SUITE(fc_crypto)\n\nBOOST_AUTO_TEST_CASE(rand_test)\n{\n    char buffer[81920];\n    fc::rand_bytes( buffer, sizeof(buffer) );\n    std::cout <<\"\\n\";\n    check_randomness( buffer, sizeof(buffer) );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "dc7302b9f605f8bebaf32b136c9e52560cad8cc2", "size": 1102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/fc/tests/crypto/rand_test.cpp", "max_stars_repo_name": "SophiaTX/SophiaTx-Blockchain", "max_stars_repo_head_hexsha": "c964691c020962ad1aba8263c0d8a78a9fa27e45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-07-25T20:42:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T03:14:09.000Z", "max_issues_repo_path": "libraries/fc/tests/crypto/rand_test.cpp", "max_issues_repo_name": "SophiaTX/SophiaTx-Blockchain", "max_issues_repo_head_hexsha": "c964691c020962ad1aba8263c0d8a78a9fa27e45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T17:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-25T13:38:11.000Z", "max_forks_repo_path": "libraries/fc/tests/crypto/rand_test.cpp", "max_forks_repo_name": "SophiaTX/SophiaTx-Blockchain", "max_forks_repo_head_hexsha": "c964691c020962ad1aba8263c0d8a78a9fa27e45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-07-25T14:34:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-03T13:29:37.000Z", "avg_line_length": 28.2564102564, "max_line_length": 72, "alphanum_fraction": 0.5245009074, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.526723836530749}}
{"text": "#include \"uniform_bspline_ceres.hpp\"\n\n#include <random>\n\n#include <Eigen/Dense>\n#include <ceres/ceres.h>\n#include <gtest/gtest.h>\n\n#include \"test_helper.hpp\"\n#include \"uniform_bspline_ceres.hpp\"\n\nnamespace {\ntemplate <typename Spline_>\nclass FitCostFunctor {\npublic:\n    static_assert(Spline_::OutputDims == 1, \"Invalid number of output dims specified.\");\n\n    explicit FitCostFunctor(const ubs::UniformBSplineCeresEvaluator<Spline_>& splineEvaluator, double val)\n            : splineEvaluator_(splineEvaluator), val_(val) {\n    }\n\n    template <typename T>\n    bool operator()(T const* const* paramPointers, T* residual) const {\n        splineEvaluator_.evaluate(paramPointers, residual);\n        *residual -= T(val_);\n        return true;\n    }\n\nprivate:\n    ubs::UniformBSplineCeresEvaluator<Spline_> splineEvaluator_;\n    double val_;\n};\n\n} // namespace\n\nTEST(UniformBSplineCeres, PlaneFitPrior) { // NOLINT(readability-function-size)\n    using Spline = ubs::UniformBSpline<double, 3, Eigen::Vector2d, double, Eigen::MatrixXd>;\n\n    Eigen::MatrixXd controlPoints = Eigen::MatrixXd::Random(20, 20);\n    Spline spline(controlPoints);\n\n    // Generate measurements.\n    ubs::UniformBSplineCeres<Spline> splineCeres(spline);\n\n    std::vector<double*> parameterPointers(splineCeres.ControlPointsSupport);\n    ceres::Problem problem;\n    const int numMeasurements = 10;\n\n    const Eigen::Vector3d supportPoint(1.0, 2.0, 3.0);\n    const Eigen::Vector3d dir1 = Eigen::Vector3d(2.0, 0.12, 0.32).normalized();\n    const Eigen::Vector3d dir2 = Eigen::Vector3d(0.1, 1.5, 1.74).normalized();\n\n    Eigen::Matrix2d a = Eigen::Matrix2d::Zero();\n    a << dir1.head<2>(), dir2.head<2>();\n\n    const Eigen::Matrix2d aInv = a.inverse();\n\n    // Create ceres problem.\n    for (int i = 0; i < numMeasurements; ++i) {\n        for (int j = 0; j < numMeasurements; ++j) {\n            Eigen::Vector2d planePos{};\n            planePos << i, j;\n            planePos = planePos / (numMeasurements - 1) * 0.2 - supportPoint.head<2>();\n\n            const Eigen::Vector2d rs = aInv * planePos;\n            const Eigen::Vector3d pos = supportPoint + dir1 * rs[0] + dir2 * rs[1];\n\n            const auto data = splineCeres.getPointData(pos.head<2>());\n            splineCeres.fillParameterPointers(data, parameterPointers.begin(), parameterPointers.end());\n            ubs::UniformBSplineCeresEvaluator<Spline> evaluator = splineCeres.getEvaluator(data);\n\n            auto* costFunctor = new ceres::DynamicAutoDiffCostFunction<FitCostFunctor<Spline>>(\n                new FitCostFunctor<Spline>(evaluator, pos[2]));\n            for (int k = 0; k < splineCeres.ControlPointsSupport; ++k) {\n                costFunctor->AddParameterBlock(1);\n            }\n            costFunctor->SetNumResiduals(1);\n\n            problem.AddResidualBlock(costFunctor, nullptr, parameterPointers);\n        }\n    }\n\n    splineCeres.addSmoothnessResiduals<2>(problem);\n\n    // Solve problem.\n    ceres::Solver::Options options;\n    options.minimizer_progress_to_stdout = false;\n    options.initial_trust_region_radius = 1e16;\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n\n    // Check result.\n    test_util::linspace(std::array<int, 2>{200, 200}, [&](const Eigen::Vector2d& pos) {\n        const Eigen::Vector3d splinePos(pos[0], pos[1], spline.evaluate(pos));\n\n        Eigen::Vector2d planePos = pos - supportPoint.head<2>();\n        Eigen::Vector2d rs = aInv * planePos;\n        const Eigen::Vector3d gtPos = supportPoint + dir1 * rs[0] + dir2 * rs[1];\n\n        for (int i = 0; i < 3; ++i) {\n            EXPECT_NEAR(gtPos[i], splinePos[i], 1e-8) << pos;\n        }\n    });\n}\n", "meta": {"hexsha": "5c4798c0eb7ae786fee8752fa6cd0cff4cd1febb", "size": 3662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/smoothness_prior.cpp", "max_stars_repo_name": "KIT-MRT/uniform_bspline_ceres", "max_stars_repo_head_hexsha": "2953bf549c15d49b8a82c5331be3231852ff69b3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T00:12:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T09:22:43.000Z", "max_issues_repo_path": "test/smoothness_prior.cpp", "max_issues_repo_name": "KIT-MRT/uniform_bspline_ceres", "max_issues_repo_head_hexsha": "2953bf549c15d49b8a82c5331be3231852ff69b3", "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/smoothness_prior.cpp", "max_forks_repo_name": "KIT-MRT/uniform_bspline_ceres", "max_forks_repo_head_hexsha": "2953bf549c15d49b8a82c5331be3231852ff69b3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-01-16T15:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T09:22:44.000Z", "avg_line_length": 34.8761904762, "max_line_length": 106, "alphanum_fraction": 0.652375751, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5267238196072921}}
{"text": "#pragma once\n#include <range/v3/algorithm/for_each.hpp>\n#include <range/v3/view/cycle.hpp>\n#include <range/v3/view/take_while.hpp>\n#include <boost/container/flat_set.hpp>\n#include <vector>\n#include \"day1part1.hpp\"\n\nconstexpr auto day1part2 = [](auto&& input) {\n  auto current_frequency = initial_frequency;\n  boost::container::flat_set<decltype(current_frequency)> previous_frequencies{};\n\n  std::vector<int> frequency_changes{};\n  std::string line;\n  while (not input.eof()) {\n    std::getline(input, line);\n    frequency_changes.push_back(std::stoi(line));\n  }\n\n  ranges::v3::for_each(\n    ranges::view::cycle(frequency_changes)\n      | ranges::view::take_while([&]([[maybe_unused]] const auto frequency_change) {\n        auto [iter,inserted] = previous_frequencies.insert(current_frequency);\n        return inserted;\n      }),\n    [&](const auto frequency_change) {\n      current_frequency = resulting_frequency(current_frequency, frequency_change);\n    }\n  );\n\n  return current_frequency;;\n};\n", "meta": {"hexsha": "29af4ad96d495cde5aaa12c6f02e515688c256e0", "size": 997, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/day1part2.hpp", "max_stars_repo_name": "bengoodwyn/aoc-2018", "max_stars_repo_head_hexsha": "6eb7a6f77574331e41fabc9f58c78f1a6348784c", "max_stars_repo_licenses": ["MIT"], "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/day1part2.hpp", "max_issues_repo_name": "bengoodwyn/aoc-2018", "max_issues_repo_head_hexsha": "6eb7a6f77574331e41fabc9f58c78f1a6348784c", "max_issues_repo_licenses": ["MIT"], "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/day1part2.hpp", "max_forks_repo_name": "bengoodwyn/aoc-2018", "max_forks_repo_head_hexsha": "6eb7a6f77574331e41fabc9f58c78f1a6348784c", "max_forks_repo_licenses": ["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.2121212121, "max_line_length": 84, "alphanum_fraction": 0.7121364092, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.526702003986388}}
{"text": "//  Copyright (c) 2001-2011 Hartmut Kaiser\n//  Copyright (c) 2011 Jan Frederick Eick\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#include <boost/config/warning_disable.hpp>\n#include <boost/detail/lightweight_test.hpp>\n#include <boost/spirit/include/karma_numeric.hpp>\n\n#include <boost/cstdint.hpp>\n\n#include \"test.hpp\"\n\n///////////////////////////////////////////////////////////////////////////////\n//\n//  *** BEWARE PLATFORM DEPENDENT!!! ***\n//  *** The following assumes 32 bit boost::uint32_tegers.\n//  *** Modify these constants when appropriate.\n//\n///////////////////////////////////////////////////////////////////////////////\n\nchar const* max_unsigned_base2 =  \"11111111111111111111111111111111\";\nchar const* max_unsigned_base3 =  \"102002022201221111210\";\nchar const* max_unsigned_base4 =  \"3333333333333333\";\nchar const* max_unsigned_base5 =  \"32244002423140\";\nchar const* max_unsigned_base6 =  \"1550104015503\";\nchar const* max_unsigned_base7 =  \"211301422353\";\nchar const* max_unsigned_base8 =  \"37777777777\";\nchar const* max_unsigned_base9 =  \"12068657453\";\nchar const* max_unsigned_base11 = \"1904440553\";\nchar const* max_unsigned_base12 = \"9ba461593\";\nchar const* max_unsigned_base13 = \"535a79888\";\nchar const* max_unsigned_base14 = \"2ca5b7463\";\nchar const* max_unsigned_base15 = \"1a20dcd80\";\nchar const* max_unsigned_base16 = \"ffffffff\";\nchar const* max_unsigned_base17 = \"a7ffda90\";\nchar const* max_unsigned_base18 = \"704he7g3\";\nchar const* max_unsigned_base19 = \"4f5aff65\";\nchar const* max_unsigned_base20 = \"3723ai4f\";\nchar const* max_unsigned_base21 = \"281d55i3\";\nchar const* max_unsigned_base22 = \"1fj8b183\";\nchar const* max_unsigned_base23 = \"1606k7ib\";\nchar const* max_unsigned_base24 = \"mb994af\";\nchar const* max_unsigned_base25 = \"hek2mgk\";\nchar const* max_unsigned_base26 = \"dnchbnl\";\nchar const* max_unsigned_base27 = \"b28jpdl\";\nchar const* max_unsigned_base28 = \"8pfgih3\";\nchar const* max_unsigned_base29 = \"76beigf\";\nchar const* max_unsigned_base30 = \"5qmcpqf\";\nchar const* max_unsigned_base31 = \"4q0jto3\";\nchar const* max_unsigned_base32 = \"3vvvvvv\";\nchar const* max_unsigned_base33 = \"3aokq93\";\nchar const* max_unsigned_base34 = \"2qhxjlh\";\nchar const* max_unsigned_base35 = \"2br45qa\";\nchar const* max_unsigned_base36 = \"1z141z3\";\n\nint \nmain()\n{\n    using spirit_test::test;\n    using boost::spirit::karma::uint_generator;\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 2)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 2> base2_generator;\n\n        BOOST_TEST(test(\"1100111100100110010\", base2_generator(424242)));\n        BOOST_TEST(test(\"1100111100100110010\", base2_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base2, base2_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base2, base2_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 3)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 3> base3_generator;\n\n        BOOST_TEST(test(\"210112221200\", base3_generator(424242)));\n        BOOST_TEST(test(\"210112221200\", base3_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base3, base3_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base3, base3_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 4)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 4> base4_generator;\n\n        BOOST_TEST(test(\"1213210302\", base4_generator(424242)));\n        BOOST_TEST(test(\"1213210302\", base4_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base4, base4_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base4, base4_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 5)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 5> base5_generator;\n\n        BOOST_TEST(test(\"102033432\", base5_generator(424242)));\n        BOOST_TEST(test(\"102033432\", base5_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base5, base5_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base5, base5_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 6)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 6> base6_generator;\n\n        BOOST_TEST(test(\"13032030\", base6_generator(424242)));\n        BOOST_TEST(test(\"13032030\", base6_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base6, base6_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base6, base6_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 7)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 7> base7_generator;\n\n        BOOST_TEST(test(\"3414600\", base7_generator(424242)));\n        BOOST_TEST(test(\"3414600\", base7_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base7, base7_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base7, base7_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 8)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 8> base8_generator;\n\n        BOOST_TEST(test(\"1474462\", base8_generator(424242)));\n        BOOST_TEST(test(\"1474462\", base8_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base8, base8_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base8, base8_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 9)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 9> base9_generator;\n\n        BOOST_TEST(test(\"715850\", base9_generator(424242)));\n        BOOST_TEST(test(\"715850\", base9_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base9, base9_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base9, base9_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 11)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 11> base11_generator;\n\n        BOOST_TEST(test(\"26a815\", base11_generator(424242)));\n        BOOST_TEST(test(\"26a815\", base11_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base11, base11_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base11, base11_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 12)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 12> base12_generator;\n\n        BOOST_TEST(test(\"185616\", base12_generator(424242)));\n        BOOST_TEST(test(\"185616\", base12_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base12, base12_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base12, base12_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 13)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 13> base13_generator;\n\n        BOOST_TEST(test(\"11b140\", base13_generator(424242)));\n        BOOST_TEST(test(\"11b140\", base13_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base13, base13_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base13, base13_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 14)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 14> base14_generator;\n\n        BOOST_TEST(test(\"b0870\", base14_generator(424242)));\n        BOOST_TEST(test(\"b0870\", base14_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base14, base14_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base14, base14_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 15)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 15> base15_generator;\n\n        BOOST_TEST(test(\"85a7c\", base15_generator(424242)));\n        BOOST_TEST(test(\"85a7c\", base15_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base15, base15_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base15, base15_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 16)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 16> base16_generator;\n\n        BOOST_TEST(test(\"67932\", base16_generator(424242)));\n        BOOST_TEST(test(\"67932\", base16_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base16, base16_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base16, base16_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 17)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 17> base17_generator;\n\n        BOOST_TEST(test(\"515g7\", base17_generator(424242)));\n        BOOST_TEST(test(\"515g7\", base17_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base17, base17_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base17, base17_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 18)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 18> base18_generator;\n\n        BOOST_TEST(test(\"40d70\", base18_generator(424242)));\n        BOOST_TEST(test(\"40d70\", base18_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base18, base18_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base18, base18_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 19)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 19> base19_generator;\n\n        BOOST_TEST(test(\"34g3a\", base19_generator(424242)));\n        BOOST_TEST(test(\"34g3a\", base19_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base19, base19_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base19, base19_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 20)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 20> base20_generator;\n\n        BOOST_TEST(test(\"2d0c2\", base20_generator(424242)));\n        BOOST_TEST(test(\"2d0c2\", base20_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base20, base20_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base20, base20_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 21)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 21> base21_generator;\n\n        BOOST_TEST(test(\"23h00\", base21_generator(424242)));\n        BOOST_TEST(test(\"23h00\", base21_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base21, base21_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base21, base21_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 22)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 22> base22_generator;\n\n        BOOST_TEST(test(\"1hibg\", base22_generator(424242)));\n        BOOST_TEST(test(\"1hibg\", base22_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base22, base22_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base22, base22_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 23)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 23> base23_generator;\n\n        BOOST_TEST(test(\"1bjm7\", base23_generator(424242)));\n        BOOST_TEST(test(\"1bjm7\", base23_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base23, base23_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base23, base23_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 24)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 24> base24_generator;\n\n        BOOST_TEST(test(\"16gci\", base24_generator(424242)));\n        BOOST_TEST(test(\"16gci\", base24_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base24, base24_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base24, base24_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 25)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 25> base25_generator;\n\n        BOOST_TEST(test(\"123jh\", base25_generator(424242)));\n        BOOST_TEST(test(\"123jh\", base25_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base25, base25_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base25, base25_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 26)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 26> base26_generator;\n\n        BOOST_TEST(test(\"o3f0\", base26_generator(424242)));\n        BOOST_TEST(test(\"o3f0\", base26_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base26, base26_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base26, base26_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 27)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 27> base27_generator;\n\n        BOOST_TEST(test(\"lepi\", base27_generator(424242)));\n        BOOST_TEST(test(\"lepi\", base27_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base27, base27_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base27, base27_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 28)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 28> base28_generator;\n\n        BOOST_TEST(test(\"j93e\", base28_generator(424242)));\n        BOOST_TEST(test(\"j93e\", base28_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base28, base28_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base28, base28_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 29)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 29> base29_generator;\n\n        BOOST_TEST(test(\"hbd1\", base29_generator(424242)));\n        BOOST_TEST(test(\"hbd1\", base29_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base29, base29_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base29, base29_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 30)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 30> base30_generator;\n\n        BOOST_TEST(test(\"flbc\", base30_generator(424242)));\n        BOOST_TEST(test(\"flbc\", base30_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base30, base30_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base30, base30_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 31)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 31> base31_generator;\n\n        BOOST_TEST(test(\"e7e7\", base31_generator(424242)));\n        BOOST_TEST(test(\"e7e7\", base31_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base31, base31_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base31, base31_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 32)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 32> base32_generator;\n\n        BOOST_TEST(test(\"cu9i\", base32_generator(424242)));\n        BOOST_TEST(test(\"cu9i\", base32_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base32, base32_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base32, base32_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 33)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 33> base33_generator;\n\n        BOOST_TEST(test(\"bqir\", base33_generator(424242)));\n        BOOST_TEST(test(\"bqir\", base33_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base33, base33_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base33, base33_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 34)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 34> base34_generator;\n\n        BOOST_TEST(test(\"aqxo\", base34_generator(424242)));\n        BOOST_TEST(test(\"aqxo\", base34_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base34, base34_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base34, base34_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 35)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 35> base35_generator;\n\n        BOOST_TEST(test(\"9vb7\", base35_generator(424242)));\n        BOOST_TEST(test(\"9vb7\", base35_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base35, base35_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base35, base35_generator, 0xffffffffu));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  arbitrary radix test (base 36)\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        uint_generator<boost::uint32_t, 36> base36_generator;\n\n        BOOST_TEST(test(\"93ci\", base36_generator(424242)));\n        BOOST_TEST(test(\"93ci\", base36_generator, 424242));\n\n        BOOST_TEST(test(max_unsigned_base36, base36_generator(0xffffffffu)));\n        BOOST_TEST(test(max_unsigned_base36, base36_generator, 0xffffffffu));\n    }\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "a39838fb9ff49bc5f72b2c20e5778e6190ee61f9", "size": 21330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/spirit/test/karma/uint_radix.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/spirit/test/karma/uint_radix.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/spirit/test/karma/uint_radix.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": 41.9881889764, "max_line_length": 81, "alphanum_fraction": 0.5153305204, "num_tokens": 4282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5267019982593418}}
{"text": "#pragma once\n/**\n    Anderson Acceleration for linear iterative problems.\n    @author @copyright sentinel (Github: Enigmatisms)\n    @ref (paper) Convergence Analysis for Anderson Acceleration\n*/\n#include <Eigen/Dense>\n#include <iostream>\n#include <deque>\n\ntemplate <typename T, int Dim>\nclass AA {\nusing MatrixDxt = Eigen::Matrix<T, Dim, -1>;\nusing MatrixDt = Eigen::Matrix<T, Dim, Dim>;\nusing MatrixXt = Eigen::Matrix<T, -1, -1>;\nusing VectorDt = Eigen::Matrix<T, Dim, 1>;\nusing VectorXt = Eigen::Matrix<T, -1, 1>;\npublic:\n    AA(T restart_thresh, T alpha_lim = 10., int dim = 2): \n            restart_thresh(restart_thresh), alpha_lim(alpha_lim), dim(dim) {}\n    ~AA() {}\n\n    bool andersonAccelerate(const VectorDt& pose, const VectorDt& prev_pose, VectorDt& out_pose, T avg_err, int iter_num);\nprivate:\n    const T restart_thresh;\n    const T alpha_lim;\n    const int dim;\n    std::deque<VectorDt> Gs;\n    std::deque<VectorDt> Fs;\n};\n", "meta": {"hexsha": "a088e182046e74621d35be855460d93b9d2382a8", "size": 938, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "anderson_acc/aa.hpp", "max_stars_repo_name": "Enigmatisms/cppUtils", "max_stars_repo_head_hexsha": "8ea584aa0457478a0d382c957d69ef5dc122ff55", "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": "anderson_acc/aa.hpp", "max_issues_repo_name": "Enigmatisms/cppUtils", "max_issues_repo_head_hexsha": "8ea584aa0457478a0d382c957d69ef5dc122ff55", "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": "anderson_acc/aa.hpp", "max_forks_repo_name": "Enigmatisms/cppUtils", "max_forks_repo_head_hexsha": "8ea584aa0457478a0d382c957d69ef5dc122ff55", "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.2580645161, "max_line_length": 122, "alphanum_fraction": 0.6876332623, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5267019926747636}}
{"text": "/*\n * SensorValues.cpp\n *\n *  Created on: 30.08.2017\n *      Author: thies\n */\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/mpi.h>\n\n#include <measurements/SensorValues.h>\n\n#include <stddef.h>\n#include <tgmath.h>\n#include <algorithm>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <random>\n#include <string>\n#include <vector>\n\nnamespace wavepi {\nnamespace measurements {\n\ntemplate<int dim>\nSensorValues<dim> SensorValues<dim>::noise(std::shared_ptr<SensorDistribution<dim>> grid) {\n   SensorValues<dim> res(grid);\n\n   // auto time = std::chrono::high_resolution_clock::now();\n   // std::default_random_engine generator(time.time_since_epoch().count() % 1000000);\n   std::default_random_engine generator(2307);\n   std::uniform_real_distribution<double> distribution(-1, 1);\n\n   for (size_t i = 0; i < grid->size(); i++)\n      res[i] = distribution(generator);\n\n   return res;\n}\n\ntemplate<int dim>\nSensorValues<dim> SensorValues<dim>::noise(const SensorValues<dim>& like) {\n   return noise(like.grid);\n}\n\ntemplate<int dim>\nSensorValues<dim> SensorValues<dim>::noise(const SensorValues<dim>& like, double norm) {\n   auto res = noise(like.grid);\n   res *= norm / res.norm();\n\n   return res;\n}\n\ntemplate<int dim>\ndouble SensorValues<dim>::relative_error(const SensorValues<dim>& other) const {\n   SensorValues<dim> tmp(*this);\n   tmp -= other;\n\n   double denom = this->norm();\n   return tmp.norm() / (denom == 0.0 ? 1.0 : denom);\n}\n\ntemplate<int dim>\nvoid SensorValues<dim>::write_pvd(std::string path, std::string filename, std::string name) const {\n   AssertThrow(grid, ExcNotInitialized());\n\n   grid->write_pvd(elements, path, filename, name);\n}\n\n#ifdef WAVEPI_MPI\ntemplate<int dim>\nvoid SensorValues<dim>::mpi_irecv(size_t source, std::vector<MPI_Request>& reqs) {\n   AssertThrow(reqs.size() == 0, ExcInternalError());\n\n   reqs.emplace_back();\n   MPI_Irecv(&elements[0], elements.size(), MPI_DOUBLE, source, 1, MPI_COMM_WORLD, &reqs[0]);\n}\n\ntemplate<int dim>\nvoid SensorValues<dim>::mpi_send(size_t destination) {\n   MPI_Send(&elements[0], elements.size(), MPI_DOUBLE, destination, 1, MPI_COMM_WORLD);\n}\n\ntemplate<int dim>\nvoid SensorValues<dim>::mpi_isend(size_t destination, std::vector<MPI_Request>& reqs) {\n   AssertThrow(reqs.size() == 0, ExcInternalError());\n\n   reqs.emplace_back();\n   MPI_Isend(&elements[0], elements.size(), MPI_DOUBLE, destination, 1, MPI_COMM_WORLD, &reqs[0]);\n}\n\ntemplate<int dim>\nvoid SensorValues<dim>::mpi_all_reduce(SensorValues<dim> source, MPI_Op op) {\n   MPI_Allreduce(&source.elements[0], &elements[0], elements.size(), MPI_DOUBLE, op, MPI_COMM_WORLD);\n}\n\ntemplate<int dim>\nvoid SensorValues<dim>::mpi_bcast(size_t root) {\n   MPI_Bcast(&elements[0], elements.size(), MPI_DOUBLE, root, MPI_COMM_WORLD);\n}\n\n#endif\n\ntemplate class SensorValues<1> ;\ntemplate class SensorValues<2> ;\ntemplate class SensorValues<3> ;\n\n} /* namespace measurements */\n} /* namespace wavepi */\n", "meta": {"hexsha": "1b187b593e595e26cf6f4b0ae3509736622c5474", "size": 2956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/measurements/SensorValues.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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": "lib/measurements/SensorValues.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/measurements/SensorValues.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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.6306306306, "max_line_length": 101, "alphanum_fraction": 0.7117726658, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5266643148145672}}
{"text": "//######################################################################\n//#   Refiner Module \n//#   \n//#   Copyright (C) 2020 Siemens AG\n//#   SPDX-License-Identifier: MIT\n//#   Author 2020: This module has been developed by \n//#                Roman Kaskman under supervision of Slobodan Ilic\n//#######################################################################\n\n#include \"refiner.h\"\n#include <util.h>\n#include \"rendering_helper.h\"\n#include \"frame_payload.h\"\n#include \"optimizer.h\"\n#include \"correspondence_finder.h\"\n#include <string>\n#include <Eigen/Geometry>\n#include \"occlusion_handler.hpp\"\n#include <filesystem>\n#include <vis_utils.h>\n\nusing namespace Eigen;\nusing namespace std;\n\n#define CAST_ROUND_INT(x) static_cast<int>(lround(x))\n\nstd::vector<Vector4f> extract_edges(const cv::Rect& roi, const cv::Mat& image)\n{\n\t// Create and LSD detector with standard or no refinement.\n\tcv::Ptr<cv::LineSegmentDetector> ls = cv::createLineSegmentDetector(cv::LSD_REFINE_ADV, 0.9, 0.7);\n\tvector<cv::Vec4f> lines_std;\n\n\t// Detect the lines\n\tls->detect(image(roi), lines_std);\n\n\tvector<Vector4f> edges(lines_std.size());\n\n\ttransform(lines_std.begin(), lines_std.end(), edges.begin(), [&roi](const auto& line)\n\t{\n\t\tcv::Vec4f crop_line = line + cv::Vec4f(roi.x, roi.y, roi.x, roi.y);\n\t\treturn Vector4f(crop_line[0], crop_line[1], crop_line[2], crop_line[3]);\n\t});\n\n\treturn edges;\n}\n\ncv::Vec4i find_bounding_box_coordinates(const cv::Mat& img)\n{\n\tint min_y = img.rows - 1;\n\tint min_x = img.cols - 1;\n\tint max_y = 0;\n\tint max_x = 0;\n\n\tfor (int i = 0; i < img.rows; ++i)\n\t{\n\t\tfor (int j = 0; j < img.cols; ++j)\n\t\t{\n\t\t\tfloat val = img.at<float>(i, j);\n\n\t\t\tif (val > 0.0)\n\t\t\t{\n\t\t\t\tif (i < min_y)\n\t\t\t\t{\n\t\t\t\t\tmin_y = i;\n\t\t\t\t}\n\t\t\t\telse if (i > max_y)\n\t\t\t\t{\n\t\t\t\t\tmax_y = i;\n\t\t\t\t}\n\n\t\t\t\tif (j < min_x)\n\t\t\t\t{\n\t\t\t\t\tmin_x = j;\n\t\t\t\t}\n\t\t\t\telse if (j > max_x)\n\t\t\t\t{\n\t\t\t\t\tmax_x = j;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn cv::Vec4i(min_y, max_y, min_x, max_x);\n}\n\nvoid add_padding(cv::Vec4i& vec, int padding_pixels) {\n\tvec[0] = vec[0] - padding_pixels;\n\tvec[1] = vec[1] + padding_pixels;\n\tvec[2] = vec[2] - padding_pixels;\n\tvec[3] = vec[3] + padding_pixels;\n}\n\n\ntemplate <typename T>\nT get_median_absolute_deviation(const Matrix<T, Dynamic, 1>& v) {\n\tT median = get_median(v);\n\tMatrix<T, Dynamic, 1> res = (v - median).cwiseAbs();\n\treturn get_median(res);\n}\n\nvoid compute_residual_std_dev(const vector<FramePayload>& frame_payloads, const Matrix4d& model_pose_m,\n                              const Matrix3d& intrinsics, double& std_dev, bool& has_converged)\n{\n\tvector<double> residuals;\n\n\tint converged_num = 0;\n\tconst Isometry3d model_pose = to_isometry(model_pose_m);\n\tfor (const auto& payload : frame_payloads)\n\t{\n\t\tconst Correspondence& correspondence = payload.correspondence;\n\t\tMatrix4d scene_pose_inv = payload.scene_pose.inverse();\n\n\t\tIsometry3d world_to_cam_transform = to_isometry(scene_pose_inv) * model_pose;\n\n\t\tfor (size_t i = 0; i < correspondence.get_number_of_correspondences(); i++)\n\t\t{\n\t\t\tconst Vector3d world_point = correspondence.world_points[i].cast<double>();\n\t\t\tconst Vector2d pixel_point = correspondence.corresponding_points[i].cast<double>();\n\n\t\t\tVector3d point_in_cam_coords = world_to_cam_transform * world_point;\n\t\t\tpoint_in_cam_coords /= point_in_cam_coords[2];\n\t\t\tVector2d pixel_coords = (intrinsics * point_in_cam_coords).block<2, 1>(0, 0);\n\n\t\t\tVector2d rgb_edge_normal = correspondence.get_rgb_normal(i).cast<double>();\n\t\t\tdouble residual = (pixel_point - pixel_coords).dot(rgb_edge_normal);\n\n\t\t\tif (std::abs(residual) < 1.5)\n\t\t\t{\n\t\t\t\tconverged_num++;\n\t\t\t}\n\n\t\t\tresiduals.push_back(residual);\n\t\t}\n\t}\n\n\tVectorXd eigen_residuals = Eigen::Map<VectorXd, Unaligned>(residuals.data(), residuals.size());\n\tdouble mad = get_median_absolute_deviation(eigen_residuals);\n\tstd_dev = 1.482579 * mad;\n\n\tauto res_num = static_cast<double>(residuals.size());\n\thas_converged = (converged_num / res_num) >= 0.9;\n}\n\ncv::Rect get_roi_box(const cv::Mat& depth_img, int model_padding_pixels)\n{\n\tcv::Vec4i bbox = find_bounding_box_coordinates(depth_img);\n\tadd_padding(bbox, model_padding_pixels);\n\n\tbbox[0] = max(0, bbox[0]);\n\tbbox[1] = min(depth_img.rows - 1, bbox[1]);\n\n\tbbox[2] = max(0, bbox[2]);\n\tbbox[3] = min(depth_img.cols - 1, bbox[3]);\n\n\tint crop_width = bbox[3] - bbox[2];\n\tint crop_height = bbox[1] - bbox[0];\n\n\treturn cv::Rect(bbox[2], bbox[0], crop_width, crop_height);\n}\n\n\nRefiner::Refiner(const Configuration& p_configuration)\n{\n\tconfiguration = p_configuration;\n}\n\nvector<Vector4f> get_depth_edges(const cv::Mat &depth_img, const cv::Rect &cropping_box)\n{\n\tcv::Mat norm_depth_img;\n\tcv::normalize(depth_img, norm_depth_img, 255, 0, cv::NORM_MINMAX);\n\tnorm_depth_img.convertTo(norm_depth_img, CV_8UC1);\n\treturn extract_edges(cropping_box, norm_depth_img);\n}\n\ninline void draw_line_ids(cv::Mat &img, const vector<Vector4f> &edges) {\n\tfor (int i = 0; i < edges.size(); i++) {\n\t\tconst auto &edge = edges[i];\n\t\tcv::line(img, cv::Point(CAST_ROUND_INT(edge[0]), CAST_ROUND_INT(edge[1])),\n\t\t\tcv::Point(CAST_ROUND_INT(edge[2]), CAST_ROUND_INT(edge[3])), cv::Scalar(i), 1, 8);\n\t}\n}\n\nMatrix4d Refiner::refine_model_pose(const vector<Matrix4d>& camera_poses,\n                                           const vector<cv::Mat>& grayscale_images,\n                                           const Matrix4d& model_pose, int model_id)\n{\n\tconst auto& first_image = grayscale_images[0];\n\n\tint height = first_image.rows;\n\tint width = first_image.cols;\n\n\tCorrespondenceFinder correspondence_finder(configuration);\n\tRenderingHelper rendering_helper(configuration, model_id, width, height);\n\n\tconst size_t number_of_frames = grayscale_images.size();\n\tMatrix4d current_model_pose = model_pose;\n\n\tint number_of_iterations = configuration.get_max_iterations();\n\tconst Matrix3d intrinsics = configuration.get_intrinsics().cast<double>();\n\n\tfor (int iteration = 0; iteration < number_of_iterations; iteration++)\n\t{\n\t\tvector<FramePayload> frame_payloads(number_of_frames);\n\t\tfor (size_t frame_idx = 0; frame_idx < number_of_frames; ++frame_idx)\n\t\t{\n\t\t\tFramePayload payload;\n\n\t\t\tconst Matrix4d& camera_pose = camera_poses[frame_idx];\n\t\t\tpayload.scene_pose = camera_pose;\n\n\t\t\tMatrix4d world_to_camera = camera_pose.inverse() * current_model_pose;\n\n\t\t\tcv::Mat depth_img;\n\t\t\tcv::Mat rendered_color_img; // not used here\n\t\t\trendering_helper.render(world_to_camera, depth_img, rendered_color_img);\n\t\t\tcv::Rect cropping_box = get_roi_box(depth_img, configuration.get_model_padding_pixels());\n\t\t\t\n\t\t\tvector<Vector4f> depth_edges = get_depth_edges(depth_img, cropping_box);\n\t\t\n\t\t\tconst cv::Mat& grayscale_img = grayscale_images[frame_idx];\n\t\t\tcv::Mat edge_id_img = cv::Mat(height, width, CV_32SC1, cv::Scalar::all(-1));\n\t\t\tvector<Vector4f> rgb_edges = extract_edges(cropping_box, grayscale_img);\n\n\t\t\tdraw_line_ids(edge_id_img, rgb_edges);\n\t\t\ttransform(rgb_edges.begin(), rgb_edges.end(), back_inserter(payload.correspondence.rgb_edge_normals),\n\t\t\t          [](const Vector4f& edge) { return get_edge_normal(edge); });\n\t\t\t\n\t\t\tMatrix4d to_world_transformation = world_to_camera.inverse();\n\t\t\tcorrespondence_finder.find_correspondences(depth_img, edge_id_img, to_world_transformation,\n\t\t\t                                           depth_edges, payload.correspondence);\n\t\t\t\n\n#ifdef _DEBUG\n\t\t\t\tif (frame_idx % 20 == 0)\n\t\t\t\t{\n\t\t\t\t\tcv::Mat edge_viz = get_edge_visualization(height, width, payload, depth_edges, rgb_edges);\n\t\t\t\t\tcv::imshow(\"Edge matches\", edge_viz);\n\t\t\t\t\tcv::waitKey(0);\n\t\t\t\t}\n\t\t\t\n#endif\n\t\t\tframe_payloads[frame_idx] = payload;\n\t\t}\n\n\t\tdouble res_std_dev;\n\t\tbool has_converged;\n\t\tcompute_residual_std_dev(frame_payloads, current_model_pose, intrinsics, res_std_dev, has_converged);\n\n\t\tif (has_converged) break;\n\n\t\tcurrent_model_pose = optimize_model_pose(frame_payloads, current_model_pose, intrinsics, res_std_dev);\n\t}\n\n\treturn current_model_pose;\n}\n\n\nmap<int, Matrix4d> Refiner::refine_model_poses(const RefinementInput& input)\n{\n\tOcclusionHandler occlusion_handler(configuration, input.rgbd_image_files, input.camera_poses);\n\n\tmap<int, Matrix4d> refined_model_poses;\n\n\tfor (const auto& [model_id, model_pose] : input.model_poses)\n\t{\n\t\tvector<size_t> valid_frame_ids = occlusion_handler.get_frame_ids_with_visible_model(model_id, model_pose);\n\t\tif (!valid_frame_ids.empty())\n\t\t{\n\t\t\tcout << \"Running optimization for model #\" << model_id << \" on \" << valid_frame_ids.size() << \" frames\" << endl;\n\n\t\t\tvector<Matrix4d> camera_poses(valid_frame_ids.size());\n\t\t\tvector<cv::Mat> grayscale_images(valid_frame_ids.size());\n\n\t\t\ttransform(valid_frame_ids.begin(), valid_frame_ids.end(), camera_poses.begin(),\n\t\t\t          [&input](const auto& frame_id) { return input.camera_poses[frame_id]; });\n\t\t\ttransform(valid_frame_ids.begin(), valid_frame_ids.end(), grayscale_images.begin(),\n\t\t\t          [&input](const auto& frame_id)\n\t\t\t          {\n\t\t\t\t          const string& rgb_file = input.rgbd_image_files[frame_id].first;\n\t\t\t\t          cv::Mat rgb = read_image(rgb_file);\n\t\t\t\t\t\t  cv::Mat grayscale;\n\t\t\t\t\t\t  cv::cvtColor(rgb, grayscale, CV_RGB2GRAY);\n\t\t\t\t\t\t  return grayscale;\n\t\t\t          });\n\n\n\t\t\trefined_model_poses[model_id] = refine_model_pose(camera_poses, grayscale_images, model_pose, model_id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\trefined_model_poses[model_id] = model_pose;\n\t\t\tcerr << \"No valid frames for model #\" << model_id << \", skipping refinement\" << endl;\n\t\t}\n\t}\n\n\treturn refined_model_poses;\n}\n", "meta": {"hexsha": "7cc84ddab81c193a392b7b113010fcae17b819cd", "size": 9346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "refiner/src/refiner.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": "refiner/src/refiner.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": "refiner/src/refiner.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": 31.3624161074, "max_line_length": 115, "alphanum_fraction": 0.6899208217, "num_tokens": 2465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5266643083999402}}
{"text": "/*\n * Copyright 2013-2015 Raphael Bost\n *\n * This file is part of ciphermed.\n\n *  ciphermed 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 *  ciphermed 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 ciphermed.  If not, see <http://www.gnu.org/licenses/>. 2\n *\n */\n\n#include <assert.h>\n#include <vector>\n#include <crypto/paillier.hh>\n#include <crypto/gm.hh>\n#include <NTL/ZZ.h>\n#include <gmpxx.h>\n#include <math/util_gmp_rand.h>\n\n#include <ctime>\n\n#include<iostream>\n\nusing namespace std;\nusing namespace NTL;\n\nstatic void test_paillier()\n{\n    cout << \"Test Paillier ...\\n\" << flush;\n\n    gmp_randstate_t randstate;\n    gmp_randinit_default(randstate);\n    gmp_randseed_ui(randstate,time(NULL));\n\n    auto sk = Paillier_priv::keygen(randstate,16,2); //600 ,256\n    Paillier_priv pp(sk,randstate);\n\n    auto pk = pp.pubkey();\n    mpz_class n = pk[0];\n    Paillier p(pk,randstate);\n\n    //mpz_class pt0, pt1,m;\n    //mpz_urandomm(pt0.get_mpz_t(),randstate,n.get_mpz_t());\n    //mpz_urandomm(pt1.get_mpz_t(),randstate,n.get_mpz_t());\n    //mpz_urandomm(m.get_mpz_t(),randstate,n.get_mpz_t());\n    mpz_class pt0 = 2, pt1 = 3, m = 5; //instead of the random values\n    cout << \"pt0: \"<< pt0 << endl;\n    cout << \"pt1: \"<< pt1 << endl;\n    cout << \"m: \"<< m << endl;\n\n    mpz_class ct0 = p.encrypt(pt0);         cout << \"ct0: \"<< ct0 << endl;\n    mpz_class ct1 = p.encrypt(pt1);         cout << \"ct1: \"<< ct1 << endl;\n    mpz_class sum = p.add(ct0, ct1);        cout << \"sum_enc: \"<< sum << endl;\n    mpz_class prod = p.constMult(m,ct0);    cout << \"prod_enc: \"<< prod << endl;\n    //    mpz_class diff = p.constMult(-1, ct0);\n    mpz_class diff = p.sub(ct0, ct1);       cout << \"diff_enc: \"<< diff << endl;\n\n    assert(pp.decrypt(ct0) == pt0);\n    assert(pp.decrypt(ct1) == pt1);\n    assert(pp.decrypt(sum) == (pt0+pt1)%n);\n    mpz_class d = pt0 - pt1;\n    if (d < 0) {\n        d += n;\n    }\n    assert( pp.decrypt(diff) == d);\n    assert(pp.decrypt(prod) == (m*pt0)%n);\n\n    cout << \"Test Paillier passed\" << endl;\n\n    mpz_class A[3][3] = {{1,2,3},{1,1,1},{4,5,6}};\n    //int rows = sizeof A / sizeof A[0];\n    //int cols = sizeof A[0] / sizeof(mpz_class);\n    //cout << rows << \" \" << cols <<endl;\n    mpz_class A_enc[3][3];\n    p.encryptMatrix(A, A_enc);\n    mpz_class A_dec[3][3];\n    pp.decryptMatrix(A_enc, A_dec);\n    cout << \"Test Matrix Paillier passed\" << endl;\n}\n\nstatic void test_paillier_fast()\n{\n    cout << \"Test Paillier Fast...\" << flush;\n\n    gmp_randstate_t randstate;\n    gmp_randinit_default(randstate);\n    gmp_randseed_ui(randstate,time(NULL));\n\n    auto sk = Paillier_priv_fast::keygen(randstate,600);\n    Paillier_priv_fast pp(sk,randstate);\n\n    auto pk = pp.pubkey();\n    mpz_class n = pk[0];\n    Paillier p(pk,randstate);\n\n    mpz_class pt0, pt1,m;\n    mpz_urandomm(pt0.get_mpz_t(),randstate,n.get_mpz_t());\n    mpz_urandomm(pt1.get_mpz_t(),randstate,n.get_mpz_t());\n    mpz_urandomm(m.get_mpz_t(),randstate,n.get_mpz_t());\n\n    mpz_class ct0 = pp.encrypt(pt0);\n    mpz_class ct1 = pp.encrypt(pt1);\n    mpz_class sum = p.add(ct0, ct1);\n    mpz_class prod = p.constMult(m,ct0);\n    //    mpz_class diff = p.constMult(-1, ct0);\n    mpz_class diff = p.sub(ct0, ct1);\n\n    assert(pp.decrypt(ct0) == pt0);\n    assert(pp.decrypt(ct1) == pt1);\n    assert(pp.decrypt(sum) == (pt0+pt1)%n);\n    mpz_class d = pt0 - pt1;\n    if (d < 0) {\n        d += n;\n    }\n    assert( pp.decrypt(diff) == d);\n    assert(pp.decrypt(prod) == (m*pt0)%n);\n\n    cout << \" passed\" << endl;\n}\n\nstatic void paillier_perf(unsigned int k, unsigned int a_bits, size_t n_iteration)\n{\n    cout << \"Test Paillier performances ...\" << endl;\n\n    cout << \"k = \" << k << \"\\na_bits = \" << a_bits << \"\\n\" << n_iteration << \" iterations\" << endl;\n\n    gmp_randstate_t randstate;\n    gmp_randinit_default(randstate);\n    gmp_randseed_ui(randstate,time(NULL));\n\n    auto sk = Paillier_priv::keygen(randstate,k,a_bits);\n    Paillier_priv pp(sk,randstate);\n\n    auto pk = pp.pubkey();\n    mpz_class n = pk[0];\n    Paillier p(pk,randstate);\n\n    mpz_class pt0, pt1,m;\n    mpz_urandomm(pt0.get_mpz_t(),randstate,n.get_mpz_t());\n    mpz_urandomm(pt1.get_mpz_t(),randstate,n.get_mpz_t());\n    mpz_urandomm(m.get_mpz_t(),randstate,n.get_mpz_t());\n\n    mpz_class ct0 = p.encrypt(pt0);\n    mpz_class ct1 = p.encrypt(pt1);\n    mpz_class sum = p.add(ct0, ct1);\n    mpz_class prod = p.constMult(m,ct0);\n    //    mpz_class diff = p.constMult(-1, ct0);\n    mpz_class diff = p.sub(ct0, ct1);\n\n    assert(pp.decrypt(ct0) == pt0);\n    assert(pp.decrypt(ct1) == pt1);\n    assert(pp.decrypt(sum) == (pt0+pt1)%n);\n    mpz_class d = pt0 - pt1;\n    if (d < 0) {\n        d += n;\n    }\n    assert( pp.decrypt(diff) == d);\n    assert(pp.decrypt(prod) == (m*pt0)%n);\n\n    struct timespec t0,t1;\n\n    vector<mpz_class> ct(n_iteration);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        mpz_class pt;\n        mpz_urandomm(pt.get_mpz_t(),randstate,n.get_mpz_t());\n        ct[i] = p.encrypt(pt);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    uint64_t t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"public encryption: \"<<  ((double)t/1000000)/n_iteration <<\"ms per plaintext\" << endl;\n\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        mpz_class pt;\n        mpz_urandomm(pt.get_mpz_t(),randstate,n.get_mpz_t());\n        pp.encrypt(pt);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"private encryption: \"<<  ((double)t/1000000)/n_iteration <<\"ms per plaintext\" << endl;\n\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        mpz_class pt;\n        mpz_urandomm(pt.get_mpz_t(),randstate,n.get_mpz_t());\n        pp.fast_encrypt_precompute(pt);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"private encryption with precomputation: \"<<  ((double)t/1000000)/n_iteration <<\"ms per plaintext\" << endl;\n\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        pp.decrypt(ct[i]);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"decryption: \"<<  ((double)t/1000000)/n_iteration <<\"ms per cyphertext\" << endl;\n\n}\n\nstatic void paillier_fast_perf(unsigned int k, size_t n_iteration)\n{\n    cout << \"Test Paillier Fast performances ...\" << endl;\n\n    cout << \"k = \" << k << \"\\n\" << n_iteration << \" iterations\" << endl;\n\n    gmp_randstate_t randstate;\n    gmp_randinit_default(randstate);\n    gmp_randseed_ui(randstate,time(NULL));\n\n    auto sk = Paillier_priv_fast::keygen(randstate,k);\n    Paillier_priv_fast pp(sk,randstate);\n\n    auto pk = pp.pubkey();\n    mpz_class n = pk[0];\n//    Paillier p(pk,randstate);\n\n    mpz_class pt0, pt1,m;\n    mpz_urandomm(pt0.get_mpz_t(),randstate,n.get_mpz_t());\n    mpz_urandomm(pt1.get_mpz_t(),randstate,n.get_mpz_t());\n    mpz_urandomm(m.get_mpz_t(),randstate,n.get_mpz_t());\n\n    struct timespec t0,t1;\n    uint64_t t;\n\n    vector<mpz_class> ct(n_iteration);\n\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        mpz_class pt;\n        mpz_urandomm(pt.get_mpz_t(),randstate,n.get_mpz_t());\n        ct[i] = pp.encrypt(pt);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"private encryption with generator precomputations: \"<<  ((double)t/1000000)/n_iteration <<\"ms per plaintext\" << endl;\n\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        pp.decrypt(ct[i]);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"decryption: \"<<  ((double)t/1000000)/n_iteration <<\"ms per cyphertext\" << endl;\n\n}\n\nstatic void test_gm()\n{\n    cout << \"Test GM ...\" << flush;\n\n    gmp_randstate_t randstate;\n    gmp_randinit_default(randstate);\n    gmp_randseed_ui(randstate,time(NULL));\n\n    auto sk = GM_priv::keygen(randstate);\n    GM_priv pp(sk,randstate);\n\n    auto pk = pp.pubkey();\n    GM p(pk,randstate);\n\n    bool b0 = true; //(bool)RandomBits_long(1);\n    bool b1 = false; //(bool)RandomBits_long(1);\n\n    mpz_class ct0 = p.encrypt(b0);\n    mpz_class ct1 = p.encrypt(b1);\n    mpz_class XOR = p.XOR(ct0, ct1);\n    mpz_class rerand = p.reRand(ct0);\n\n    assert(pp.decrypt(pk[1]) == true);\n    assert(pp.decrypt(ct0) == b0);\n    assert(pp.decrypt(ct1) == b1);\n    assert(pp.decrypt(XOR) == (b0 xor b1));\n    assert(pp.decrypt(rerand) == b0);\n\n    cout << \" passed\" << endl;\n}\n\nint main(int ac, char **av)\n{\n    SetSeed(to_ZZ(time(NULL)));\n    //test_elgamal();\n    test_paillier();\n    //test_paillier_fast();\n    //test_gm();\n\n    return 0;\n}\n", "meta": {"hexsha": "90ba7c2df096c092b6cd04ab4ecbe536fefa8fa1", "size": 9632, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Source/crypto/test_crypto.cc", "max_stars_repo_name": "TarekIbnZiad/CryptoImg", "max_stars_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-05T18:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T07:33:10.000Z", "max_issues_repo_path": "Source/crypto/test_crypto.cc", "max_issues_repo_name": "TarekIbnZiad/CryptoImg", "max_issues_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_issues_repo_licenses": ["MIT"], "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/crypto/test_crypto.cc", "max_forks_repo_name": "TarekIbnZiad/CryptoImg", "max_forks_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-11T00:32:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T23:35:20.000Z", "avg_line_length": 32.1066666667, "max_line_length": 130, "alphanum_fraction": 0.6291528239, "num_tokens": 2980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580806813577, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.526664284957891}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// error_of.hpp\r\n//\r\n//  Copyright 2005 Eric Niebler. Distributed under the Boost\r\n//  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#ifndef BOOST_ACCUMULATORS_STATISTICS_ERROR_OF_MEAN_HPP_EAN_27_03_2006\r\n#define BOOST_ACCUMULATORS_STATISTICS_ERROR_OF_MEAN_HPP_EAN_27_03_2006\r\n\r\n#include <boost/mpl/placeholders.hpp>\r\n#include <boost/accumulators/framework/accumulator_base.hpp>\r\n#include <boost/accumulators/framework/extractor.hpp>\r\n#include <boost/accumulators/framework/depends_on.hpp>\r\n#include <boost/accumulators/statistics_fwd.hpp>\r\n#include <boost/accumulators/statistics/error_of.hpp>\r\n#include <boost/accumulators/statistics/variance.hpp>\r\n#include <boost/accumulators/statistics/count.hpp>\r\n\r\nnamespace boost { namespace accumulators\r\n{\r\n\r\nnamespace impl\r\n{\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // error_of_mean_impl\r\n    template<typename Sample, typename Variance>\r\n    struct error_of_mean_impl\r\n      : accumulator_base\r\n    {\r\n        // for boost::result_of\r\n        typedef typename numeric::functional::average<Sample, std::size_t>::result_type result_type;\r\n\r\n        error_of_mean_impl(dont_care) {}\r\n\r\n        template<typename Args>\r\n        result_type result(Args const &args) const\r\n        {\r\n            using namespace std;\r\n            extractor<Variance> const variance = {};\r\n            return sqrt(numeric::average(variance(args), count(args) - 1));\r\n        }\r\n    };\r\n\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::error_of\r\n//\r\nnamespace tag\r\n{\r\n    template<>\r\n    struct error_of<mean>\r\n      : depends_on<lazy_variance, count>\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::error_of_mean_impl<mpl::_1, lazy_variance> impl;\r\n    };\r\n\r\n    template<>\r\n    struct error_of<immediate_mean>\r\n      : depends_on<variance, count>\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::error_of_mean_impl<mpl::_1, variance> impl;\r\n    };\r\n}\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#endif\r\n", "meta": {"hexsha": "23298d336767596e27b0597ec7bad8cc590e432e", "size": 2272, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/accumulators/statistics/error_of_mean.hpp", "max_stars_repo_name": "importlib/klib", "max_stars_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "master/core/third/boost/accumulators/statistics/error_of_mean.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/accumulators/statistics/error_of_mean.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 30.7027027027, "max_line_length": 101, "alphanum_fraction": 0.6038732394, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706733, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.526640882376835}}
{"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/*! \\file spreadeddiscountcurve.hpp\n    \\brief spreaded discount term structure\n    \\ingroup termstructures\n*/\n\n#pragma once\n\n#include <ql/math/interpolation.hpp>\n#include <ql/patterns/lazyobject.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantExt {\nusing namespace QuantLib;\n\n/*! Curve taking a reference curve and discount factor quotes, that are used to overlay the reference\n  curve with a spread. The quotes are interpolated loglinearly. The spread curve is given in terms of\n  times relative to the reference date, which means that the spread will float with a changing reference\n  date in the reference curve. */\nclass SpreadedDiscountCurve : public YieldTermStructure, public LazyObject {\npublic:\n    enum class Interpolation { logLinear, linearZero };\n    enum class Extrapolation { flatFwd, flatZero };\n    //! times should be consistent with reference ts day counter\n    SpreadedDiscountCurve(const Handle<YieldTermStructure>& referenceCurve, const std::vector<Time>& times,\n                          const std::vector<Handle<Quote>>& quotes,\n                          const Interpolation interpolation = Interpolation::logLinear,\n                          const Extrapolation extrapolation = Extrapolation::flatFwd);\n\n    Date maxDate() const override;\n    void update() override;\n    const Date& referenceDate() const override;\n\n    Calendar calendar() const override;\n    Natural settlementDays() const override;\n\nprotected:\n    void performCalculations() const override;\n    DiscountFactor discountImpl(Time t) const override;\n\nprivate:\n    Handle<YieldTermStructure> referenceCurve_;\n    std::vector<Time> times_;\n    std::vector<Handle<Quote>> quotes_;\n    Interpolation interpolation_;\n    Extrapolation extrapolation_;\n    mutable std::vector<Real> data_;\n    boost::shared_ptr<QuantLib::Interpolation> dataInterpolation_;\n};\n\n} // namespace QuantExt\n", "meta": {"hexsha": "b996a55b76d5334c0c8db930f5f23915b8c71d63", "size": 2679, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/spreadeddiscountcurve.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/termstructures/spreadeddiscountcurve.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/termstructures/spreadeddiscountcurve.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": 37.7323943662, "max_line_length": 107, "alphanum_fraction": 0.751399776, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5266408764227026}}
{"text": "/*\n * manouver.cc\n * Copyright (C) 2017 romancpodolski <mailto:roman.podolski@tum.de>\n *\n * Distributed under terms of the MIT license.\n */\n\n#include \"planner/maneuver.h\"\n#include <gflags/gflags.h>\n#include <boost/format.hpp>\n#include <boost/numeric/odeint.hpp>\n#include <cmath>\n#include <eigen3/Eigen/Dense>\n#include \"planner/baseframe.h\"\n#include \"planner/car.h\"\n\nDEFINE_double(min_manouver_length, 20.0, \"Minimal length of manouver in [m]\");\nDEFINE_double(manouver_speed_gain, 1.0,\n              \"Gain of manouver length from vehicle speed\");\nDEFINE_double(weight_safety, 1.0, \"weigthing factor for the safety cost\");\nDEFINE_double(weight_smoothness, 1.0,\n              \"weigthing factor for the smoothness cost\");\nDEFINE_double(weight_consistency, 1.0,\n              \"weigthing factor for the consistency cost\");\nDEFINE_double(granularity, 1.0, \"Stepsize of the path generation\");\nDEFINE_double(collision_standart_deviation, 1.0,\n              \"standart deviation of risk of collision\");\nDEFINE_double(max_curvature, 0.5, \"standart deviation of risk of collision\");\n\nnamespace planner {\n\nManeuver::Maneuver(const point position, const double heading,\n                   const double velocity, const double q_i, const double q_f,\n                   const double s_i,\n                   const std::shared_ptr<Baseframe> &baseframe,\n                   const std::shared_ptr<Rtree> &rtree)\n    : _q_f{q_f},\n      _s_i{s_i},\n      _baseframe{baseframe},\n      _rtree{rtree},\n      _theta{heading - baseframe->theta(s_i)},\n      _v{velocity},\n      _position{position},\n      _heading{heading},\n      _collision_checked{false},\n      _drivable{true},\n      _collision_length{0.0} {\n  const double delta_s_f =\n      FLAGS_manouver_speed_gain * velocity + FLAGS_min_manouver_length;\n  s_f(_s_i + delta_s_f);\n\n  Eigen::Matrix4d A;\n  Eigen::Vector4d b, c;\n  A << 0, 0, 0, 1,                                         // end first row\n      pow(delta_s_f, 3), pow(delta_s_f, 2), delta_s_f, 1,  // second row\n      0, 0, 1, 0,                                          // third\n      3 * pow(delta_s_f, 2), 2 * delta_s_f, 1, 0;          // fourth\n  c << q_i, q_f, tan(_theta), 0.0;\n  b = A.inverse() * c;\n  _a = b(0), _b = b(1), _c = b(2), _d = b(3);\n}\n\ndouble Maneuver::q(double s) const {\n  double result = 0.0;\n  double delta_s = s - _s_i;\n  if (_s_i <= s && s < _s_f) {\n    result = _a * pow(delta_s, 3) + _b * pow(delta_s, 2) + _c * delta_s + _d;\n  } else if (_s_f <= s) {\n    result = _q_f;\n  } else {\n    // result = _d;\n    throw std::domain_error(\"q is not defined for s < \" + std::to_string(_s_i));\n  }\n  return result;\n}\n\ndouble Maneuver::dq(double s) const {\n  double result = 0.0;\n  double delta_s = s - _s_i;\n\n  if (_s_i <= s && s < _s_f) {\n    result = 3 * _a * pow(delta_s, 2) + 2 * _b * delta_s + _c;\n  } else if (_s_f <= s) {\n    result = 0.0;  // this is redundant - but makes the code more readable\n  } else {\n    // result = 0.0;  // this is redundant - but makes the code more readable\n    throw std::domain_error(\"dq/ds is not defined for s < \" +\n                            std::to_string(_s_i));\n  }\n  return result;\n}\n\ndouble Maneuver::ddq(double s) const {\n  double result = 0.0;\n  double delta_s = s - _s_i;\n\n  if (_s_i <= s && s < _s_f) {\n    result = 6 * _a * delta_s + 2 * _b;\n  } else if (_s_f <= s) {\n    result = 0.0;  // this is redundant - but makes the code more readable\n  } else {\n    // result = 0.0;  // this is redundant - but makes the code more readable\n    throw std::domain_error(\"d^2q/ds^2 is not defined for s < \" +\n                            std::to_string(_s_i));\n  }\n  return result;\n}\n\ndouble Maneuver::Q(const double s) const {\n  return sqrt(pow(dq(s), 2) + pow((1 - q(s) * _baseframe->curvature(s)), 2));\n}\n\ndouble Maneuver::S(const double s) const {\n  return sign(1 - q(s) * _baseframe->curvature(s));\n}\n\ndouble Maneuver::curvature(const double s) const {\n  double K_b = _baseframe->curvature(s);\n\n  double k =\n      (S(s) / Q(s)) *\n      (K_b + ((1 - q(s) * K_b) * ddq(s) + K_b * pow(dq(s), 2)) / pow(Q(s), 2));\n\n  return k;\n}\n\n/*! \\struct push_back_state_and_arc_length\n *  \\brief Brief struct description\n *\n *  Detailed description\n */\nstruct push_back_state_and_arc_length {\n  std::vector<pose> &_path; /*!< Description */\n\n  push_back_state_and_arc_length(std::vector<pose> &path) : _path(path) {}\n\n  void operator()(const state_type &x, double s) {\n    _path.push_back(pose{point(x[0], x[1]), x[2], s});\n  }\n};\n\nstd::vector<pose> Maneuver::path() {\n  // TODO(roman): make sure that the path does not extend L without setting s_f\n  // to L\n  if (_path.empty()) {\n    double ds = FLAGS_granularity;\n\n    state_type x_0 = {_position.x(), _position.y(), _heading};\n\n    auto system = [this](const state_type &x, state_type &dxds,\n                         const double s) {\n      double K_b{_baseframe->curvature(s)};\n      double K{curvature(s)};\n\n      if (fabs(q(s)) >= fabs(1 / K_b) || fabs(K) > FLAGS_max_curvature) {\n        _drivable = false;\n      }\n\n      double Q_s{Q(s)};\n      double theta{x[2]};\n\n      dxds[0] = Q_s * cos(theta);\n      dxds[1] = Q_s * sin(theta);\n      dxds[2] = Q_s * K;\n    };\n\n    boost::numeric::odeint::euler<state_type> stepper;\n\n    boost::numeric::odeint::integrate_const(\n        stepper, system, x_0, s_i(), s_f(), ds,\n        push_back_state_and_arc_length(_path));\n  }\n  return _path;\n}\n\ndouble Maneuver::J(const Maneuver &previous,\n                   const std::shared_ptr<std::vector<Maneuver>> maneuvers,\n                   double w_s, double w_k, double w_c) const {\n  return w_s * C_s(maneuvers) + w_k * C_k() + w_c * C_c(previous);\n}\n\ndouble Maneuver::C_s(const std::shared_ptr<std::vector<Maneuver>> maneuvers,\n                     const double sigma) const {\n  double result = 0.0;\n  normal g(q_f(), sigma);\n\n  for (auto &m : *maneuvers) {\n    result += static_cast<bool>(m.collision()) * pdf(g, m.q_f());\n  }\n\n  return result;\n}\n\ndouble Maneuver::C_k() const {\n  auto l = [this](const double s) { return pow(curvature(s), 2) * Q(s); };\n  return trapezoidal(l, s_i(), s_f());\n}\n\ndouble Maneuver::C_c(const Maneuver &previous) const {\n  const double s_1 = s_i();\n  const double s_2 = s_f();\n  // TODO(roman): handle this better!\n  if (s_1 > previous.s_f()) {\n    throw std::domain_error(\"Maneuvers do not overlap!\");\n  }\n  auto l = [this, &previous](double s) {\n    point a(s, q(s));\n    point b(s, previous.q(s));\n    return bg::distance(a, b);\n  };\n  double result = 1 / (s_2 - s_1) * trapezoidal(l, s_1, s_2);\n  return result;\n}\n\ndouble Maneuver::collision() {\n  // if a collision check was already performed, return the result\n  if (_collision_checked) return _collision_length;\n  _collision_length = 0.0;\n  _collision_checked = true;\n\n  Car car;\n\n  for (const auto &p : path()) {\n    // search spatial index for possible collisions\n    std::vector<value> collision_risk;\n    _rtree->query(bgi::intersects(car.aabb(p)),\n                  std::back_inserter(collision_risk));\n    // perfom the actual collision check.\n    for (const auto &risk : collision_risk) {\n      polygon obstacle{*risk.second};\n      if (bg::intersects(car.obb(p), obstacle)) {  // collision detected\n        _collision_length = p.s;  // return length at collison and stop loop.\n        return _collision_length;\n      }\n    }\n  }\n  return _collision_length;  // return 0.0 - no collision detected\n}\n\nstd::ostream &operator<<(std::ostream &os, const Maneuver &m) {\n  os << \"\\\\addplot coordinates {\\n\";\n  for (auto point : m.path()) {\n    os << boost::format(\"(%d,%d)\\n\") % point.x() % point.y();\n  }\n  os << \"};\\n\";\n  return os;\n}\n\n}  // namespace planner\n", "meta": {"hexsha": "4e455ff7538ea87b937327c3916e0791d877acaf", "size": 7630, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/planner/maneuver.cc", "max_stars_repo_name": "RomanCPodolski/samling_based_planning", "max_stars_repo_head_hexsha": "30a064d60e1f278459dfeacbc764022346f6ec84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-05-15T17:15:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-27T20:06:00.000Z", "max_issues_repo_path": "src/planner/maneuver.cc", "max_issues_repo_name": "RomanCPodolski/samling_based_planning", "max_issues_repo_head_hexsha": "30a064d60e1f278459dfeacbc764022346f6ec84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/planner/maneuver.cc", "max_forks_repo_name": "RomanCPodolski/samling_based_planning", "max_forks_repo_head_hexsha": "30a064d60e1f278459dfeacbc764022346f6ec84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-05T04:45:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-05T04:45:14.000Z", "avg_line_length": 30.52, "max_line_length": 80, "alphanum_fraction": 0.6090432503, "num_tokens": 2297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5266408652862984}}
{"text": "#include <boost/random/chi_squared_distribution.hpp>\n", "meta": {"hexsha": "3926cf6e3ba1c8e60a55c8bf16e093482acd5546", "size": 53, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_chi_squared_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_chi_squared_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_chi_squared_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.5, "max_line_length": 52, "alphanum_fraction": 0.8490566038, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5266408595894527}}
{"text": "\n///////////////////////////////////////////////////////////////////////////////\n// random::example::poisson_convergence.cpp     \t\t\t\t\t\t     //\n//                                                                           //\n//  Copyright 2010 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 LIBS_RANDOM_EXAMPLE_POISSON_CONVERGENCE_CPP_ER_2010\n#define LIBS_RANDOM_EXAMPLE_POISSON_CONVERGENCE_CPP_ER_2010\n#include <vector>\n#include <algorithm>\n#include <iterator>\n\n#include <boost/mpl/int.hpp>\n\n#include <boost/typeof/typeof.hpp>\n#include <boost/ref.hpp>\n#include <boost/range.hpp>\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/format.hpp>\n#include <boost/foreach.hpp>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n\n#include <boost/math/distributions/poisson.hpp>\n#include <boost/random/poisson_distribution.hpp>\n\n#include <boost/random/poisson_ext/devroye/detail/step4/standard.hpp>\n#include <boost/random/poisson_ext/devroye/detail/step4/squeeze.hpp>\n#include <boost/random/poisson_ext/devroye/sampler/meta_int_mean.hpp>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <boost/statistics/detail/non_parametric/kolmogorov_smirnov/check_convergence.hpp>\n\ntemplate<typename Int>\nvoid example_poisson_convergence(\n\tstd::ostream& os,\n    double mean,\n    std::size_t n_loops,\n    std::size_t n_init,\n    std::size_t n_factor\n)\n{\n\n\tnamespace ks = boost::statistics::detail::kolmogorov_smirnov;\n\tnamespace devroye = boost::random::poisson::devroye;\n\n    typedef Int int_;\n    typedef double \tval_;\n    typedef boost::math::poisson_distribution<val_> dist_;\n    typedef boost::poisson_distribution<int_> random1_;\n    typedef devroye::tag::standard tag3_;\n    typedef devroye::tag::squeeze tag4_;\n    typedef typename devroye::sampler::template \n    \tmeta_int_mean<tag3_,int_>::type random3_;\n    typedef typename devroye::sampler::template \n    \tmeta_int_mean<tag4_,int_>::type random4_;\n    \n\ttypedef boost::mt19937 urng_;\n\ttypedef std::vector<val_> vals_;\n\ttypedef ks::check_convergence<val_> check_;\n\n    urng_ urng;\n\turng_ urng1 = urng;\n    urng_ urng2 = urng;\n    urng_ urng3 = urng;\n    urng_ urng4 = urng;\n\tcheck_ check;\n\n\tos  << \"mean = \" << mean << std::endl;\n\t{\n    \ttypedef boost::variate_generator<urng_&,random1_> vg1_;\n    \ttypedef boost::variate_generator<urng_&,random3_> vg3_;\n    \ttypedef boost::variate_generator<urng_&,random4_> vg4_;\n    \t\n        dist_ dist(mean);\n        os << \"default : \" << std::endl;\n        {\n\t\t\tvg1_ vg1(urng,random1_(mean));\n    \t\tcheck(n_loops,n_init,n_factor,dist,vg1,os);\n        }\n        os << \"devroye - standard\" << std::endl;\n        {\n        \trandom3_ r(mean);\n\t\t\tvg3_ vg(urng,r);\n            vg();\n    \t\tcheck(n_loops,n_init,n_factor,dist,vg,os);\n            //os << vg.distribution() << std::endl;\n        }\n        os << \"devroye - squeeze\" << std::endl;\n        {\n        \trandom4_ r(mean);\n\t\t\tvg4_ vg(urng,r);\n    \t\tcheck(n_loops,n_init,n_factor,dist,vg,os);\n            //os << vg.distribution() << std::endl;\n        }\n    }\n\tos << \"<-\" << std::endl;\n\n}\n\n#endif\n", "meta": {"hexsha": "d46980484e85219002f3491eba94c3acd44302e5", "size": 3395, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/libs/random/example/poisson_convergence.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": "random/libs/random/example/poisson_convergence.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": "random/libs/random/example/poisson_convergence.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": 31.4351851852, "max_line_length": 90, "alphanum_fraction": 0.6318114875, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5266408595894527}}
{"text": "/**\r\n *  @file    FDProblem.hpp\r\n *  @brief   The finite difference problem.\r\n *  @author  Francois Roy\r\n *  @date    12/01/2019\r\n */\r\n#ifndef FDPROBLEM_H\r\n#define FDPROBLEM_H\r\n\r\n// #include <iostream>\r\n#include <stdexcept>\r\n#include <string>\r\n#include <vector>\r\n#include <Eigen/SparseCore>\r\n#include \"spdlog/spdlog.h\"\r\n#include \"Parameters.hpp\"\r\n#include \"FDMesh.hpp\"\r\n\r\nnamespace numerical {\r\n\r\nnamespace fdm {\r\n\r\n/**\r\n * Defines the finite difference problem over the hypercube.\r\n * This class only define the 1D diffusion problem with Dirichlet/Neumann \r\n * boundary conditions and heterogenous diffusion coefficient (for now).\r\n */\r\ntemplate <typename T>\r\nclass FDProblem {\r\ntypedef Eigen::Matrix<T, Eigen::Dynamic, 1> Vec;\r\ntypedef std::vector<Eigen::Matrix<T, 3, 1>> Coord;\r\n// function pointer to member functions\r\ntypedef  T (FDProblem<T>::*fctptr)(T x1, T x2, T time);\r\nprivate:\r\n    int m_dim; // space dimensions of the problem \r\n    Vec m_t;\r\n    std::vector<T> m_dx;\r\n    T m_dt;\r\nprotected:\r\n    Parameters<T>* m_params;  // default parameters\r\n    FDMesh<T>* m_mesh;  // mesh\r\n    int m_bc_types[6];  // boundary types (default = Dirichlet)\r\n    Coord m_coordinates;\r\n    // array of function pointers to member functions\r\n    fctptr m_functions[6] = {&FDProblem<T>::left, &FDProblem<T>::right,\r\n                             &FDProblem<T>::bottom, &FDProblem<T>::top,\r\n                             &FDProblem<T>::back, &FDProblem<T>::front};\r\npublic:\r\n    FDProblem(Parameters<T>* params): \r\n      m_params(params),\r\n      m_bc_types{0, 0, 0, 0, 0, 0} {\r\n        // define other variables variables\r\n        m_dim = m_params->lengths.size();\r\n        if(m_dim>1){\r\n            // TODO implement higher dimensions\r\n            spdlog::error(\"Only one-dimensional problems supported.\");\r\n        }\r\n  \t    // define mesh\r\n  \t    m_mesh = new FDMesh<T>(m_params->lengths, m_params->t0, m_params->tend, \r\n          m_params->n, m_params->nt);\r\n        m_coordinates = m_mesh->coordinates();  // constant\r\n        m_t = m_mesh->t();\r\n        m_dx = m_mesh->dx();\r\n        m_dt = m_mesh->dt();\r\n    }\r\n    virtual ~FDProblem(){\r\n        delete m_mesh;\r\n    }\r\n\r\n    /**\r\n    * Diffusion coefficient value. The default is a constant obtained from \r\n    * m_params.\r\n    *\r\n    * @param x The \\f$x\\f$-, \\f$y\\f$-, and \\f$z\\f$-coordinates of the mesh \r\n    *    node.\r\n    * @param t The discrete time.\r\n    * @param u The state variable for nonlinear problems.\r\n    * @return The diffusion coefficient value at a specified mesh location.\r\n    */\r\n    virtual T alpha(const Eigen::Matrix<T, 3, 1>& x, T t, T u=0){\r\n  \t    return m_params->alpha;\r\n    }\r\n    /**\r\n    *  @return The mesh coordinates.\r\n    */\r\n    std::vector<Eigen::Matrix<T, 3, 1>> coordinates(){\r\n        return m_coordinates;\r\n    }\r\n    /**\r\n    * Set the boundary types, with the following code:\r\n    *\r\n    *  0 = Dirichlet\r\n    *  1 = Neumann\r\n    *\r\n    * For the six boundaries in the following order:\r\n    *\r\n    * 0- letf\r\n    * 1- right\r\n    * 2- bottom\r\n    * 3- top\r\n    * 4- back\r\n    * 5- front\r\n    *\r\n    *  @param types The type of boundary conditions for all boundaries.\r\n    */\r\n    void bc_types(const int (&types)[6]){\r\n        for (int i=0; i<6; i++){\r\n            m_bc_types[i] = types[i];\r\n            // spdlog::info(\"{}\", m_bc_types[i]);\r\n        }\r\n    }\r\n    /**\r\n    *\r\n    * @param boundary The boundary selection.\r\n    * @return The boundary type of the selected boundary,\r\n    */\r\n    int bc_type(int boundary){\r\n        return m_bc_types[boundary];\r\n    }\r\n    /**\r\n    * User defined function: back boundary.\r\n    * \r\n    * Back boundary value, i.e. at z = length[2][0]. Only for 3D models.\r\n    *\r\n    * @param x The \\f$x\\f$-coordinate.\r\n    * @param y The \\f$y\\f$-coordinate.\r\n    * @param t The discrete time.\r\n    * @return The boundary value at a specified mesh location.\r\n    */\r\n    virtual T back(T x, T y, T t){\r\n        return 0.0;\r\n    }\r\n    /**\r\n    * User defined function: bottom boundary.\r\n    *\r\n    * Bottom boundary value, i.e. at y = lengths[1][0]. Only for 2D and \r\n    * 3D models.\r\n    *\r\n    * @param x The \\f$x\\f$-coordinate.\r\n    * @param z The \\f$z\\f$-coordinate.\r\n    * @param t The discrete time.\r\n    * @return The boundary value at a specified mesh location.\r\n    */\r\n    virtual T bottom(T x, T z, T t){\r\n        return 0.0;\r\n    }\r\n    /**\r\n    * Set the value of the diagonals of the coefficient matrix at the indices \r\n    * of the boundary nodes.\r\n    *\r\n    *  @param dia The main diagonal.\r\n    *  @param lower The lower diagonal.\r\n    *  @param upper The upper diagonal.\r\n    *  @param lower_a The second lower diagonal.\r\n    *  @param upper_a The second upper diagonal.\r\n    *  @param lower_b The third lower diagonal.\r\n    *  @param upper_b The third upper diagonal.\r\n    *  @param t The discrete time.\r\n    */\r\n    void coeffs_bc(Vec& dia, Vec& lower, Vec& upper, Vec& lower_a, \r\n        Vec& upper_a, Vec& lower_b, Vec& upper_b, T t=0.0){\r\n    }\r\n    /**\r\n    * @return The spatial dimension of the problem.\r\n    */\r\n    int dim(){\r\n        return m_dim;\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 spatial increment.\r\n    */\r\n    std::vector<T> dx() {\r\n        return m_dx;\r\n    }\r\n    /**\r\n    * User defined function: front boundary.\r\n    *\r\n    * Front boundary value, i.e. at z = length[2][0]. Only for 3D models.\r\n    *\r\n    * @param x The \\f$x\\f$-coordinate.\r\n    * @param y The \\f$y\\f$-coordinate.\r\n    * @param t The discrete time.\r\n    * @return The boundary value at a specified mesh location.\r\n    */\r\n    virtual T front(T x, T y, T t){\r\n        return 0.0;\r\n    }\r\n    /**\r\n    * User defined function: initial  value.\r\n    *\r\n    * @param x The \\f$x\\f$-, \\f$y\\f$-, and \\f$z\\f$-coordinates of the mesh \r\n    *    node.\r\n    * @return The initial value at a specified mesh location.\r\n    */\r\n    virtual T initial_value(const Eigen::Matrix<T, 3, 1>& x){\r\n        return 0.0;\r\n    }\r\n    /**\r\n    * User defined function: left boundary.\r\n    *\r\n    * Left boundary value, i.e. for x = lengths[0][0].\r\n    *\r\n    * @param y The \\f$y\\f$-coordinate.\r\n    * @param z The \\f$z\\f$-coordinate.\r\n    * @param t The discrete time.\r\n    * @return The boundary value at a specified mesh location.\r\n    */\r\n    virtual T left(T y, T z, T t){\r\n        return 0.0;\r\n    }\r\n    /**\r\n    * @return The total number of spatial mesh nodes.\r\n    */\r\n    int n() {\r\n        int out = m_params->n[0] + 1;\r\n        if (m_dim == 2){\r\n            out = (m_params->n[0] + 1)*(m_params->n[1] + 1);\r\n        }\r\n        if (m_dim == 3){\r\n            out = (m_params->n[0] + 1)*(m_params->n[1] + 1)*\r\n                (m_params->n[2] + 1);\r\n        }\r\n        return out;\r\n    }\r\n    /**\r\n    *  @return The number of division along the \\f$x\\f$-axis.\r\n    */\r\n    int n_x(){\r\n        return m_params->n[0]; \r\n    }\r\n    /**\r\n    * @return The number of division along the \\f$y\\f$-axis.\r\n    */\r\n    int n_y(){\r\n        int n = 1;\r\n        if (m_dim != 1){\r\n            n = m_params->n[1];\r\n        }\r\n        return n; \r\n    }\r\n    /**\r\n    * @return The number of division along the \\f$z\\f$-axis.\r\n    */\r\n    int n_z(){\r\n        int n = 1;\r\n        if (m_dim == 3){\r\n            n = m_params->n[2];\r\n        }\r\n        return n; \r\n    }\r\n    /**\r\n    * @return The total number of discrete time steps.\r\n    */\r\n    int n_t(){\r\n        return m_params->nt;\r\n    }\r\n    /**\r\n    *  Get the reference solution at a specified mesh location.\r\n    *\r\n    * @param x The \\f$x\\f$-, \\f$y\\f$-, and \\f$z\\f$-coordinates of the mesh \r\n    *    node.\r\n    * @param t The discrete time.\r\n    * @return The reference solution at a specified mesh location.\r\n    */\r\n    virtual T reference(const Eigen::Matrix<T, 3, 1>& x, T t){\r\n        return 0.0;\r\n    }\r\n    /**\r\n    *  Set the value of the RHS vector at the indices of the boundary\r\n    *  nodes for Dirichlet and Neumann boundary conditions.\r\n    *\r\n    *  The user defined functions at the boundaries are time-dependent and\r\n    *  depend on the location of the boundary nodes on the plane defining \r\n    *  the boundaries. We use function pointers to member functions,\r\n    *  numerical::fdm::Problem::left(), numerical::fdm::Problem::right(),\r\n    *  numerical::fdm::Problem::bottom(), numerical::fdm::Problem::top(),\r\n    *  numerical::fdm::Problem::back(), and numerical::fdm::Problem::front()\r\n    *  to define the value of the Dirichlet or Neumann boundary condition at\r\n    *  each boundary nodes. The boundary nodes are passed by address from the\r\n    *  Mesh instance, and stored in an array of addresses of l;ength 6, where \r\n    *  the indices respectively represent the left (0), right (1), bottom (2),\r\n    *  top (3), back (4) and front (5) boundaries. In order to pass the right\r\n    *  coordinates to the user defined functions, we use a two-dimensional \r\n    *  array of size (6, 2), where the first indice correspond to the boundary \r\n    *  and the second to the indice of the spatial coordinates, i.e. 0 for \r\n    *  \\f$x\\f$, 1 for \\f$y\\f$ and 2 for \\f$z\\f$.\r\n    *\r\n    *  For Dirichlet boundary conditions, we only have to set the value of the\r\n    *  RHS vector at the boundary nodes equal to the specified value obtained \r\n    *  from the user defined function.\r\n    *\r\n    *  For Neumann boundary conditions, it is a little bit more complicated\r\n    *  since we have to approximate the normal derivative at the boundary \r\n    *  nodes. In order to define the right normal unit vector (pointing \r\n    *  outward of the domain) and \"interior node\", we define \r\n    *  the left and right side of each boundaries, such that \\f$\\mathbf{n}=1\\f$\r\n    *  , and side = -1 for the boundaries that have the right side outside of \r\n    *  the domain, i.e. right, top, and front. The opposite happens for the\r\n    *  boundaries that have the left side outside the domain, i.e., left,\r\n    *  bottom, and back have \\f$\\mathbf{n}=-1\\f$, and side = 1. We also use \r\n    *  the same indices to define the space increment in the direction normal \r\n    *  to the boundary. \r\n    *\r\n    *  For a boundary node that is not an edge nor a corner, the RHS vector\r\n    *  at the position of the node is expressed as:\r\n    *\r\n    *  **Left-side boundaries:**\r\n    *\r\n    *  Using \\f$\\textrm{bnd}\\f$ as the index of the boundary for the normal\r\n    *  direction, for example \\f$dx[\\textrm{bnd}=0]=\\Delta x\\f$ for the left\r\n    *  boundary, i.e. \\f$\\textrm{bnd}=0\\f$, we have:  \r\n    *\r\n    *  \\f[\r\n    *    \\textrm{RHS}[i] = u_n[i] + \\theta\\left(2d\\alpha_m[i]g[i]\r\n    *        dx[\\textrm{bnd}]+\r\n    *        \\Delta tf[i]\\right) + \\left(1-\\theta\\right)\\left(\r\n    *    d\\left(\\alpha_p[i]\\left(u_n[i+1]-u_n[i]\\right)-\r\n    *           \\alpha_m[i]\\left(u_n[i]-u_n[i+1]\\right)\\right)+\r\n    *    2d\\alpha_m[i]g_n[i]dx[\\textrm{bnd}]+\\Delta tf_n[i]\\right) \r\n    *  \\f]\r\n    *\r\n    *  where\r\n    *\r\n    *  \\f[\r\n    *    \\begin{align}\r\n    *    \\alpha_m[i] &= \\frac{1}{2}\\left(\\alpha_\\textrm{out} + \r\n    *        \\alpha[i]\\right)\\\\\r\n    *    \\alpha_p[i] &= \\frac{1}{2}\\left(\\alpha[i] + \\alpha[i+1]\\right)\r\n    *    \\end{align}\r\n    *  \\f]\r\n    *\r\n    *  and where \\f$\\alpha_\\textrm{out}\\f$ is the value of the diffusion \r\n    *  coefficient outside of the left side of the boundary (outside of the \r\n    *  domain). By default we set \\f$\\alpha_\\textrm{out}=\\alpha[i]\\f$\r\n    *\r\n    *  **Right-side boundaries:** \r\n    *\r\n    *  Similarly for the right-side boundaries we have:\r\n    *\r\n    *  \\f[\r\n    *    \\textrm{RHS}[i] = u_n[i] + \\theta\\left(-2d\\alpha_p[i]g[i]\r\n    *        dx[\\textrm{bnd}]+\r\n    *        \\Delta tf[i]\\right) + \\left(1-\\theta\\right)\\left(\r\n    *    d\\left(\\alpha_p[i]\\left(u_n[i-1]-u_n[i]\\right)-\r\n    *           \\alpha_m[i]\\left(u_n[i]-u_n[i-1]\\right)\\right)-\r\n    *    2d\\alpha_p[i]g_n[i]dx[\\textrm{bnd}]+\\Delta tf_n[i]\\right) \r\n    *  \\f]\r\n    *\r\n    *  where\r\n    *\r\n    *  \\f[\r\n    *    \\begin{align}\r\n    *    \\alpha_m[i] &= \\frac{1}{2}\\left(\\alpha[i-1] + \\alpha[i]\\right)\\\\\r\n    *    \\alpha_p[i] &= \\frac{1}{2}\\left(\\alpha[i] + \\alpha_\\textrm{out}\\right)\r\n    *    \\end{align}\r\n    *  \\f]\r\n    *\r\n    *  and where \\f$\\alpha_\\textrm{out}\\f$ is the value of the diffusion \r\n    *  coefficient outside of the right side of the boundary (outside of the \r\n    *  domain). By default we set \\f$\\alpha_\\textrm{out}=\\alpha[i]\\f$\r\n    *\r\n    *  With the sign and side variables we can simply write:\r\n    *\r\n    *  \\f[\r\n    *    \\textrm{RHS}[i] = u_n[i] + \\theta\\left(\\textrm{sign}2d\\alpha[i]g[i]\r\n    *        dx[\\textrm{bnd}]+\r\n    *        \\Delta tf[i]\\right) + \\left(1-\\theta\\right)\\left(\r\n    *    d\\left(\\alpha_p[i]\\left(u_n[i+\\textrm{side}]-u_n[i]\\right)-\r\n    *           \\alpha_m[i]\\left(u_n[i]-u_n[i+\\textrm{side}]\\right)\\right)+\r\n    *    \\textrm{sign}2d\\alpha[i]g_n[i]dx[\\textrm{bnd}]+\\Delta tf_n[i]\\right) \r\n    *  \\f]\r\n    *\r\n    *  where we used the default value for the outside diffusion coefficient.\r\n    *\r\n    *  For 2D and 3D models we have to define the boundary corners. Boundary\r\n    *  edges have to be defined for 3D models. \r\n    *\r\n    *  @param rhs The rhs vector.\r\n    *  @param u_n The solution vector at previous time step.\r\n    *  @param alpha The rhs vector.\r\n    *  @param f_n The source vector at privious time step.\r\n    *  @param f The source vector.\r\n    *  @param dx The space increment in the \\f$x\\f$-direction.\r\n    *  @param dy The space increment in the \\f$y\\f$-direction.\r\n    *  @param dz The space increment in the \\f$z\\f$-direction.\r\n    *  @param dt The time increment.\r\n    *  @param theta The scheme coefficient.\r\n    *  @param t The discrete time.\r\n    */\r\n    void rhs_bc(Vec& rhs, Vec& u_n, const Vec& alpha, const Vec& f_n, \r\n                const Vec& f, const T dx, const T dy, const T dz,\r\n                const T dt, const T theta, const T t){\r\n        // boundary node addresses\r\n        const std::vector<int>& left_nodes = m_mesh->left();\r\n        const std::vector<int>& right_nodes = m_mesh->right();\r\n        const std::vector<int>& bottom_nodes = m_mesh->bottom();\r\n        const std::vector<int>& top_nodes = m_mesh->top();\r\n        const std::vector<int>& back_nodes = m_mesh->back();\r\n        const std::vector<int>& front_nodes = m_mesh->front();\r\n        // array of addresses to specific boundry nodes \r\n        std::vector<int> nodes[6] = {\r\n            left_nodes, right_nodes,\r\n            bottom_nodes, top_nodes,\r\n            back_nodes, front_nodes\r\n            };\r\n        // indices of the in-plane coordinates for each boundaries\r\n        // 0 for x, 1 for y, 2 for z\r\n        int ind[6][2] = {{1,2},{1,2},{0,2},{0,2},{0,1},{0,1}};\r\n        T d;\r\n        // space increment normal to the boundaries\r\n        T d_i[6] = {dx, dx, dy, dy, dz, dz};\r\n        // the number of boundary to set up depend on the dimension\r\n        int n_bnd = 2 * m_dim;\r\n        const Coord& c = coordinates();\r\n        for(int bnd=0; bnd<n_bnd; bnd++){\r\n            if (m_bc_types[bnd] == 0){  // Dirichlet\r\n                for(int i=0; i<nodes[bnd].size(); i++){\r\n                    // the rhs value is equal to the value returned by the\r\n                    // boundary function\r\n                    rhs[nodes[bnd][i]] = (this->*m_functions[bnd]) (\r\n                        c[nodes[bnd][i]][ind[bnd][0]], \r\n                        c[nodes[bnd][i]][ind[bnd][1]], \r\n                        t + dt);\r\n                }\r\n            } else if(m_bc_types[bnd] == 1){  // Neumann\r\n                T sign = 1.0, g, g_n, alpha_m, alpha_p;\r\n                int k, side = 1;\r\n                for(int i=0; i<nodes[bnd].size(); i++){  // scaled by 1/2\r\n                    k = nodes[bnd][i];\r\n                    g = (this->*m_functions[bnd]) (\r\n                            c[k][ind[bnd][0]], \r\n                            c[k][ind[bnd][1]],\r\n                            t + dt);\r\n                    g_n = (this->*m_functions[bnd]) (\r\n                            c[k][ind[bnd][0]], \r\n                            c[k][ind[bnd][1]], \r\n                            t);\r\n                    if (bnd % 2){  // right, top, front (right side outside)\r\n                        sign = 1.0;  // outward --> normal unit vector\r\n                        side = -1;\r\n                        alpha_m = 0.5 * (alpha[k] + alpha[k-1]);\r\n                        // TODO get alpha on the right of the boundary\r\n                        alpha_p = 0.5 * (alpha[k] + alpha[k]);\r\n                    } else{  // left, bottom, back (left side outside)\r\n                        sign = -1.0;  // outward --> normal unit vector\r\n                        side = 1;\r\n                        // TODO get alpha on the left of the boundary\r\n                        alpha_m = 0.5 * (alpha[k] + alpha[k]);\r\n                        alpha_p = 0.5 * (alpha[k] + alpha[k+1]);\r\n                    }\r\n                    d = dt/d_i[bnd]/d_i[bnd];\r\n                    rhs[k] = 0.5 * (\r\n                        u_n[k] + \r\n                        theta*(sign*2.0*d*alpha[k]*g*d_i[bnd] + dt*f[k]) +\r\n                        (1.0-theta)*(\r\n                            d*alpha_p*(u_n[k+side]-u_n[k])-\r\n                            d*alpha_m*(u_n[k]-u_n[k+side])+\r\n                            sign*2.0*d*alpha[k]*g_n*d_i[bnd] + dt*f_n[k])\r\n                        );\r\n                }\r\n                // TODO: fix corners for 2D and 3D and fix edges for 3D\r\n                // if corner: we use two dirivatives in 2D and 3 derivatives \r\n                // in 3D. If edges, use two derivatives.\r\n            } else{\r\n                throw std::invalid_argument(\r\n                \"Not a valid boundary condition type.\");\r\n            }\r\n        }\r\n    }\r\n    /**\r\n    * User defined function: right boundary.\r\n    *\r\n    * Right boundary value, i.e. for x = lengths[0][1].\r\n    *\r\n    * @param y The \\f$y\\f$-coordinate.\r\n    * @param z The \\f$z\\f$-coordinate.\r\n    * @param t The discrete time.\r\n    * @return The boundary value at a specified mesh location.\r\n    */\r\n    virtual T right(T y, T z, T t){\r\n        return 0.0;\r\n    }\r\n    \r\n    /**\r\n    *  Get the computed solution at a specified mesh location.\r\n    *\r\n    * @param x The \\f$x\\f$-, \\f$y\\f$-, and \\f$z\\f$-coordinates of the mesh \r\n    *    node.\r\n    * @param t The discrete time.\r\n    * @return The computed solution at a specified mesh location.\r\n    */\r\n    virtual T solution(const Eigen::Matrix<T, 3, 1>& x, T t){\r\n        return 0.0;\r\n    }\r\n    /**\r\n    * User defined function: source term.\r\n    *\r\n    * @param x The \\f$x\\f$-, \\f$y\\f$-, and \\f$z\\f$-coordinates of the mesh \r\n    *    node.\r\n    * @param t The discrete time.\r\n    * @param u The state variable for nonlinear problems.\r\n    * @return The source term at a specified mesh location.\r\n    */\r\n    virtual T source(const Eigen::Matrix<T, 3, 1>& x, T t, T u=0){\r\n        return 0.0;\r\n    }\r\n    /**\r\n    * @return The theta parameter for the finite difference scheme. \r\n    */\r\n    T theta(){\r\n        return m_params->theta;\r\n    }\r\n    /**\r\n    *\r\n    */\r\n    Vec t(){\r\n        return m_t;\r\n    }\r\n    /**\r\n    * User defined function: top boundary.\r\n    *\r\n    * Top boundary value, i.e. at y = lengths[1][1]. Only for 2D and 3D models.\r\n    *\r\n    * @param x The \\f$x\\f$-coordinate.\r\n    * @param z The \\f$z\\f$-coordinate.\r\n    * @param t The discrete time.\r\n    * @return The boundary value at a specified mesh location.\r\n    */\r\n    virtual T top(T x, T z, T t){\r\n        return 0.0;\r\n    }\r\n    /**\r\n    *\r\n    *  @return The initial value vector.\r\n    */\r\n    Vec u_0(){\r\n        int num = n();\r\n        Vec u_0(num), x(num), y(num), z(num);\r\n        Coord coords = coordinates();\r\n        for(int i=0; i<num; i++) {\r\n            x[i] = coords[i][0];\r\n            y[i] = coords[i][1];\r\n            z[i] = coords[i][2];\r\n            u_0[i] = initial_value(coords[i]);\r\n        } \r\n        return u_0;\r\n    }\r\n};\r\n\r\n}  // namespace fdm\r\n\r\n}  // namespace numerical\r\n\r\n#endif  // PROBLEM_H\r\n", "meta": {"hexsha": "589b4ed8a0f09393c08266f1709950e39beb9e9e", "size": 20010, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "numerical/fdm/FDProblem.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/fdm/FDProblem.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/fdm/FDProblem.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": 35.6684491979, "max_line_length": 80, "alphanum_fraction": 0.5247376312, "num_tokens": 5669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5266137425523375}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Header file for Euclidean space R3 types.\n/// \\details Mostly typedefs to standardize interfacing points with transformations.\n///\n/// \\author Kirk MacTavish\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n///\n/// A note on EIGEN_MAKE_ALIGNED_OPERATOR_NEW (Sean Anderson, as of May 23, 2013)\n/// (also see http://eigen.tuxfamily.org/dox-devel/group__TopicStructHavingEigenMembers.html)\n///\n/// Fortunately, Eigen::Matrix3d and Eigen::Vector3d are NOT 16-byte vectorizable,\n/// therefore this class should not require alignment, and can be used normally in STL.\n///\n/// To inform others of the issue, classes that include *fixed-size vectorizable Eigen types*,\n/// see http://eigen.tuxfamily.org/dox-devel/group__TopicFixedSizeVectorizable.html,\n/// must include the above macro! Furthermore, special considerations must be taken if\n/// you want to use them in STL containers, such as std::vector or std::map.\n/// The macro overloads the dynamic \"new\" operator so that it generates\n/// 16-byte-aligned pointers, this MUST be in the public section of the header!\n///\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef LGM_R3_TYPES_HPP\n#define LGM_R3_TYPES_HPP\n\n#include <Eigen/Dense>\n\nnamespace lgmath {\nnamespace r3 {\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// A 3D point\n//////////////////////////////////////////////////////////////////////////////////////////////\ntypedef Eigen::Vector3d Point;\ntypedef Eigen::Ref<Point> PointRef;\ntypedef Eigen::Ref<const Point> PointConstRef;\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// A 3D homogeneous point\n//////////////////////////////////////////////////////////////////////////////////////////////\ntypedef Eigen::Vector4d HPoint;\ntypedef Eigen::Ref<HPoint> HPointRef;\ntypedef Eigen::Ref<const HPoint> HPointConstRef;\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// A 3x3 covariance for a 3D point\n//////////////////////////////////////////////////////////////////////////////////////////////\ntypedef Eigen::Matrix3d CovarianceMatrix;\ntypedef Eigen::Ref<CovarianceMatrix> CovarianceMatrixRef;\ntypedef Eigen::Ref<const CovarianceMatrix> CovarianceMatrixConstRef;\n\n} // r3\n} // lgmath\n\n#endif // LGM_R3_TYPES_HPP\n", "meta": {"hexsha": "717d63dee933f3e5dd24e736374f94f4c9b5b33d", "size": 2621, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lgmath/r3/Types.hpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "include/lgmath/r3/Types.hpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "include/lgmath/r3/Types.hpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 45.1896551724, "max_line_length": 94, "alphanum_fraction": 0.4883632201, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5266137333173342}}
{"text": "/*!=======================================================\n  |                                                     |\n  |            test_finite_difference.cpp               |\n  |                                                     |\n  -------------------------------------------------------\n  | The unit test file for finite_difference.h          |\n  =======================================================*/\n  \n#include <functional>\n#include <iostream>\n#include <fstream>\n#include <numeric>\n#include <vector>\n#include <Eigen/Dense>\n#include <finite_difference.h>\n#include <ctime>\n#include <stdlib.h>\n\nvoid print_matrix(std::vector< std::vector< double > > M){\n    /*!======================\n    |    print_matrix    |\n    ======================\n    \n    Print a matrix out\n    \n    */\n    for(int i=0; i<M.size(); i++){\n        for(int j=0; j<M[i].size(); j++){\n            std::cout << M[i][j] << \" \";\n        }\n        std::cout << \"\\n\";\n    }\n    return;\n}\n\nbool compare_vectors(const std::vector<double> &V1, const std::vector<double> &V2){\n    /*!=========================\n    |    compare_vectors    |\n    =========================\n    \n    Compare two vectors and determine if they are \n    equal.\n    \n    */\n    \n    //!Check vector's size\n    if(V1.size()!=V2.size()){return false;}\n    \n    //!Compare the values\n    else{\n        for(int i=0; i<V1.size(); i++){\n            if(!(1e-9>fabs(V1[i]-V2[i]))){return false;}\n        }\n        return true;\n    }\n}\n\nbool compare_vectors_of_vectors(const std::vector< std::vector< double > > &V1, const std::vector< std::vector< double > > &V2){\n    /*!====================================\n    |    compare_vectors_of_vectors    |\n    ====================================\n    \n    Compare two vectors of vectors and determine if they are equal.\n    \n    */\n    \n    bool result = true;     //!The overall result\n    \n    //!Check vector's size\n    if(V1.size()!=V2.size()){std::cout << \"\\nHI!\\n\"; return false;}\n    \n    //Compare each column against the value in the other column\n    for(int i=0; i<V1.size(); i++){result *= compare_vectors(V1[i],V2[i]); if(result==false){return false;}}\n    \n    return result;\n}\n\nstd::vector<double> test_fxn_1(std::vector<double> x){\n    /*! test_fxn_1\n    \n    A test function used in test_finite_difference\n    \n    */\n    \n    return {x[0]*x[0]};\n}\n\nstd::vector<double> answer_fxn_1(std::vector<double> x){\n    /*! answer_fxn_1\n    \n    A solution function used in test_finite_difference \n        \n    */\n    \n    return {2.*x[0]};\n}\n\nstd::vector<double> test_fxn_2(std::vector<double> x){\n    /*! test_fxn_2\n    \n    A test function used in test_finite_difference \n    and test_numeric_gradient\n    \n    */\n    \n    return {x[0]*x[0],x[1]-1};\n}\n\nstd::vector< std::vector< double > > answer_fxn_2(std::vector<double> x){\n    /*! answer_fxn_2\n    \n    A solution function used in test_finite_difference\n    and test_numeric_gradient\n    \n    */\n    \n    return {{2.*x[0], 0},{0., 1.}};\n}\n\nstd::vector< double > test_fxn_3(std::vector< double > x){\n    /*! test_fxn_3\n    \n    A test function used in test_numeric_gradient\n    \n    */\n    \n    return {x[1]*x[0]*x[0],x[1]+x[2]*x[0], x[0]};\n}\n\nstd::vector< std::vector< double > > answer_fxn_3(std::vector< double > x){\n    /*! answer_fxn_3\n    \n    A solution function used in test_numeric_gradient\n    \n    */\n    \n    return {{2*x[0]*x[1], x[2], 1.},\n            {  x[0]*x[0],   1., 0.},\n            {         0., x[0], 0.}};\n}\n\nstd::vector< double > test_fxn_4(std::vector< double > x){\n    /*! test_fxn_4\n    \n    A test function used in test_numeric_gradient\n    \n    */\n    \n    return {x[1]*x[0]*x[0],x[1]+x[2]*x[0]};\n}\n\nstd::vector< std::vector< double > > answer_fxn_4(std::vector< double > x){\n    /*! answer_fxn_4\n    \n    A solution function used in test_numeric_gradient\n    \n    */\n    \n    return {{2*x[0]*x[1], x[2]},\n            {  x[0]*x[0],   1.},\n            {         0., x[0]}};\n}\n\nint test_finite_difference(std::ofstream &results){\n    /*!================================\n    |    test_finite_difference    |\n    ================================\n    \n    Test the finite difference method in the\n    class FiniteDifference\n    \n    */\n    \n    //!Initialize test results\n    int  test_num        = 3;\n    std::vector<bool> test_results(test_num,false);\n    \n    //!Initialize the points about which to compute the finite differences\n    std::vector< double > x01(1,2.6);\n    std::vector< double > x02 = {2.3,-5.7};\n    \n    //!Initialize the finite difference\n    finite_difference::FiniteDifference FD1 = finite_difference::FiniteDifference(test_fxn_1, 2, x01, 1e-6);\n    finite_difference::FiniteDifference FD2 = finite_difference::FiniteDifference(test_fxn_2, 2, x02, 1e-6);\n    \n    //!Initialize the perturbation vectors\n    std::vector< double > hvec1   = {1e-6};\n    std::vector< double > hvec2a  = {1e-6,  0.};\n    std::vector< double > hvec2b  = {  0.,1e-6};\n    \n    //!Compute the results of the finite difference\n    std::vector< double > result1  = FD1.finite_difference(hvec1);\n    std::vector< double > result2a = FD2.finite_difference(hvec2a);\n    std::vector< double > result2b = FD2.finite_difference(hvec2b);\n    \n    //!Compute the answers\n    std::vector< double > answer1 = answer_fxn_1(x01);\n    std::vector< std::vector< double > > answer2 = answer_fxn_2(x02);\n    \n    test_results[0] = 1e-9>fabs(answer1[0]-result1[0]);\n    test_results[1] = 1e-9>fabs(answer2[0][0]-result2a[0]);\n    test_results[2] = 1e-9>fabs(answer2[1][1]-result2b[1]);\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_finite_difference & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_finite_difference & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return 1;\n}\n\nint test_numeric_gradient(std::ofstream &results){\n    /*!===============================\n    |    test_numeric_gradient    |\n    ===============================\n    \n    Test the numeric gradient method in the\n    class FiniteDifference\n    \n    */\n    \n    //!Initialize test results\n    int  test_num        = 3;\n    std::vector<bool> test_results(test_num,false);\n    \n    //!Initialize the points about which to compute the finite differences\n    std::vector< double > x01 = {2.3,-5.7};\n    std::vector< double > x02 = {1.4,-2.0,3.4};\n    std::vector< double > x03 = {1.4,-2.0,3.4};\n    \n    //!Initialize the finite difference\n    finite_difference::FiniteDifference FD1 = finite_difference::FiniteDifference(test_fxn_2, 2, x01, 1e-6);\n    finite_difference::FiniteDifference FD2 = finite_difference::FiniteDifference(test_fxn_3, 2, x02, 1e-6);\n    finite_difference::FiniteDifference FD3 = finite_difference::FiniteDifference(test_fxn_4, 2, x03, 1e-6);\n    \n    //!Compute the results of the finite difference\n    std::vector< std::vector< double > > result1  = FD1.numeric_gradient();\n    std::vector< std::vector< double > > result2  = FD2.numeric_gradient();\n    std::vector< std::vector< double > > result3  = FD3.numeric_gradient();\n    \n    //!Compute the answers\n    std::vector< std::vector< double > > answer1 = answer_fxn_2(x01);\n    std::vector< std::vector< double > > answer2 = answer_fxn_3(x02);\n    std::vector< std::vector< double > > answer3 = answer_fxn_4(x03);\n    \n    //!Compare the resulting gradients\n    test_results[0] = compare_vectors_of_vectors(answer1,result1);\n    test_results[1] = compare_vectors_of_vectors(answer2,result2);\n    test_results[2] = compare_vectors_of_vectors(answer3,result3);\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_numeric_gradient & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_numeric_gradient & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return 1;\n}\n\nint main(){\n    /*!==========================\n    |         main            |\n    ===========================\n    \n    The main loop which runs the tests defined in the \n    accompanying functions. Each function should output\n    the function name followed by & followed by True or \n    False if the test passes or fails respectively.*/\n    \n    std::ofstream results;\n    //Open the results file\n    results.open (\"results.tex\");\n    \n    //!Run the test functions\n    test_finite_difference(results);\n    test_numeric_gradient(results);\n    \n    //Close the results file\n    results.close();\n}\n", "meta": {"hexsha": "f728766703897b32f0e142bf9d2ee65e26184c3e", "size": 8799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/tests/finite_difference/test_finite_difference.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/tests/finite_difference/test_finite_difference.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/tests/finite_difference/test_finite_difference.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": 29.1357615894, "max_line_length": 128, "alphanum_fraction": 0.5482441186, "num_tokens": 2346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5266137299664883}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <fstream>\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 <vector>\n#include <cmath>\n#include <cstring>\n\n#include <unistd.h>\n\n#include \"NRGclasses.hpp\"\n#include \"NRGfunctions.hpp\"\n#include \"OneChQS.hpp\"\n\n#ifndef pi\n#define pi 3.141592653589793238462643383279502884197169\n#endif\n\n#ifndef _CHIN_\n#define _CHIN_\n\n\ndouble chiN(int Nsites, double Lambda)\n{\n\n  double daux[3];\n  daux[0]=1.0-pow( Lambda,-((double)(Nsites)+1.0) );\n  daux[1]=sqrt( 1.0-pow(Lambda,-(2.0*(double)(Nsites)+1.0)) );\n  daux[2]=sqrt( 1.0-pow(Lambda,-(2.0*(double)(Nsites)+3.0)) );  \n\n  return(daux[0]/(daux[1]*daux[2]));\n\n}\n\n#endif\n\n\nint main (int argc, char* argv[]){\n\n\n  // Parameters for command-line passing (GetOpt)\n\n  //char ModelOption[]=\"Anderson\";\n  //int ModelNo=0;\n\n#include\"ModelOpt.cpp\"\n\n\n  // NRG objects\n\n  CNRGarray Aeig(2);\n\n  CNRGbasisarray AeigCut(2);\n\n  CNRGbasisarray Abasis(2);\n\n  CNRGbasisarray SingleSite(3);\n\n  // STL vector\n\n  CNRGmatrix HN;\n  CNRGmatrix Qm1fNQ;\n\n  //CNRGmatrix MQQp1;\n\n  CNRGmatrix* MatArray;\n  int NumNRGarrays=3;\n  // MatArray 0 is nd\n  // MatArray 1 is cd\n  // MatArray 2 is a test\n\n  int KeepSz=0;\n\n  double U,ed,Gamma;\n  double Lambda;\n  double HalfLambdaFactor;\n  double Dband;\n  int auxIn;\n  int calcdens=0;\n  vector <double> Params;\n  vector <int> Indexes;\n\n  double chi_m1,chi_N,daux[4];\n  int Nsites;\n  int Nsitesmax=5;\n  int Nsites0=0;\n  double DN=0.0;\n\n\n  // Thermodynamics\n\n  CNRGthermo Suscep;\n  CNRGthermo Entropy;\n\n\n  double TM=0.0;\n  double betabar=0.727;\n  double Temp=0.0;\n  double Sus=0.0;\n  double SusDot=1.0/8.0;\n  vector<double> SuscepChain;\n\n  double ndot=0.0;\n  double Sz2=0.0;\n\n  int Ncutoff=700;\n  int UpdateBefCut=1;\n\n  char arqSus[32],arqname[32];\n\n  int ii,jj,i1,i2;\n\n  // STL iterator:\n\n  vector<double>::iterator diter;\n\n  // outstream\n  ofstream OutFile;\n  // instream\n  ifstream InFile;\n\n\n  /////////////////////////////////////////////////////////////////\n  /////////////////////////////////////////////////////////////////\n  ////                    READ PARAMETERS                      ////\n  /////////////////////////////////////////////////////////////////\n  /////////////////////////////////////////////////////////////////\n\n\n  U=0.5;\n  ed=-0.5*U;\n  Gamma=0.0282691;\n  Lambda=2.5;\n\n\n  InFile.open(\"nrg_input_OneChQS.dat\");\n  if (InFile.is_open())\n    {\n      InFile >> Nsitesmax;\n      InFile >> Ncutoff;\n      InFile >> U;\n      InFile >> Gamma;\n      InFile >> ed;\n      InFile >> Lambda;\n      InFile >> Dband;\n      InFile >> auxIn;\n      InFile >> UpdateBefCut;\n      InFile >> calcdens;\n    }\n  else\n    {\n      cout << \"can't open nrg_input_OneChQS.dat\" << endl;\n      exit(0);\n   }\n\n  InFile.close();\n\n  // NRG chain\n  CNRGchain chain1(Lambda,Nsitesmax);\n\n\n  // New stuff\n  strcpy(Suscep.ArqName,\"SuscepImp1Ch_25_726.dat\");\n  strcpy(Suscep.ChainArqName,\"SuscepChain1Ch.dat\");\n  Suscep.Calc=CalcSuscep;\n  \n  strcpy(Entropy.ArqName,\"EntropyImp1Ch_25_726.dat\");\n  strcpy(Entropy.ChainArqName,\"EntropyChain1Ch.dat\");\n  Entropy.Calc=CalcEntropy;\n\n  // Check for SuscepChain.dat file. If it is there, read Temp, Sus\n  // If not, change to calcdens=3, U=0, ed=0 Gamma=1\n  if ( (calcdens==1)&&(ModelNo==1) )\n    {\n      cout << \"Kondo model: Can't calculate spectral function\" << endl;\n      exit(0);\n    }\n  if (ModelNo==3) calcdens=3; // Chain calculation\n  if (calcdens==2)\n    {\n      Suscep.CalcChain=false;\n      Entropy.CalcChain=false;\n      Suscep.Nsite0Chain=0; // Anderson chains\n      Entropy.Nsite0Chain=0; // Anderson chains\n\n      if ( (!FileExists(Suscep.ChainArqName))||\n\t   (!FileExists(Entropy.ChainArqName)) )\n\t{\n\t  cout << \" Can't find chain files: \" << endl \n\t  << \"   \" << Suscep.ChainArqName << endl\n\t  << \"   \" << Entropy.ChainArqName << endl;\n\t  cout << \" Exiting... \" << endl;\n\t  exit(0);\n\t}\n      else\n\t  cout << \" Found files \" \n\t       << Suscep.ChainArqName << \", \" \n\t       << Entropy.ChainArqName \n\t       << endl;\n\n\n\n      //int ReadChainStatus=Suscep.ReadChain();\n      //int ReadChainStatus2=Entropy.ReadChain();\n      //if (ReadChainStatus==-1)calcdens=3;\n\n    }\n  if (calcdens==3)\n    {\n      Suscep.CalcChain=true;\n      Entropy.CalcChain=true;\n      U=0.0;ed=0.0;Gamma=0.0;\n    }\n\n\n  HalfLambdaFactor=0.5*(1.0+(1.0/Lambda));\n  chi_m1=sqrt(2.0*Gamma/pi)/(sqrt(Lambda)*HalfLambdaFactor);\n\n  double U_tilde=ed/(Lambda*HalfLambdaFactor);\n  cout << \"e1 = \" << 0.5*U/(Lambda*HalfLambdaFactor) << endl;\n  cout << \"e2 = \" << (ed+0.5*U)/(Lambda*HalfLambdaFactor) << endl;\n  cout << \"e3 = \" << (2.0*ed+1.5*U)/(Lambda*HalfLambdaFactor) << endl;\n  cout << \"chi_m1  = \" << chi_m1 << endl;\n\n\n  cout << \" Nsitesmax    = \" << Nsitesmax-1 << endl;\n  cout << \" Ncutoff      = \" << Ncutoff << endl;\n  if (strcmp(ModelOption,\"Anderson\")==0){\n    cout << \" U            = \" << U << endl;\n    cout << \" Gamma        = \" << Gamma << endl;\n    cout << \" ed           = \" << ed << endl;\n  }\n  if (strcmp(ModelOption,\"Kondo\")==0){\n    cout << \" JK            = \" << Gamma << endl;\n  }\n  cout << \" Lambda       = \" << Lambda << endl;\n  cout << \" Dband        = \" << Dband << endl;\n  cout << \" UpdateBefCut = \" << UpdateBefCut << endl;\n  cout << \" calcdens     = \" << calcdens << endl;\n\n  /////////////////////////////////////////////////\n  OutFile.open(\"NRG_in.txt\");\n  OutFile << \"Begin NRG calculation. Model :\" << ModelOption << endl;\n  OutFile << \" Nsitesmax    = \" << Nsitesmax-1 << endl;\n  OutFile << \" Ncutoff      = \" << Ncutoff << endl;\n  if (strcmp(ModelOption,\"Anderson\")==0){\n    OutFile << \" U            = \" << U << endl;\n    OutFile << \" Gamma        = \" << Gamma << endl;\n    OutFile << \" ed           = \" << ed << endl;\n  }\n  if (strcmp(ModelOption,\"Kondo\")==0){\n    OutFile << \" JK            = \" << Gamma << endl;\n  }\n  OutFile << \" Lambda       = \" << Lambda << endl;\n  OutFile << \" Dband        = \" << Dband << endl;\n  OutFile << \" UpdateBefCut = \" << UpdateBefCut << endl;\n  OutFile << \" calcdens     = \" << calcdens << endl;\n  OutFile.close();\n  \n  /////////////////////////////////////////////////////////////////\n  /////////////////////////////////////////////////////////////////\n  ////                   END READ PARAMETERS                   ////\n  /////////////////////////////////////////////////////////////////\n  /////////////////////////////////////////////////////////////////\n\n  // Set SingleSite\n\n  OneChQS_SetSingleSite(SingleSite);\n\n\n  // Allocate MatArray (hope this works!)\n  MatArray = new CNRGmatrix [NumNRGarrays];\n\n\n  // Test Kondo model\n  \n  Params.clear();\n\n\n  switch (ModelNo)\n    {\n    case 0 :\n      // Set initial CNRG array (N=-1)\n      Params.push_back(U);\n      Params.push_back(ed);\n      Params.push_back(Lambda);\n      Params.push_back(HalfLambdaFactor);\n      //OneChQS_SetAndersonHm1(Params,&Aeig, &Qm1fNQ, &MQQp1);\n      OneChQS_SetAndersonHm1(Params,&Aeig, &Qm1fNQ, MatArray);\n\n      Nsites0=0; // Adding N=0 site\n      chi_N=chi_m1; // tunneling to site N=0 (hi_N connects sites N and N+1)\n      SusDot=1.0/8.0;\n      // Local Susceptibility,Entropy\n      Suscep.dImpValue=SusDot;\n      Entropy.dImpValue=2.0*log(2.0);\n      break;\n    case 1 :\n      Params.push_back(Gamma); // JK\n      OneChQS_SetKondoH0(Params,&Aeig,&Qm1fNQ,&SingleSite );\n      Nsites0=1; // Adding N=1 site\n      chi_N=chiN(0,Lambda);\n      SusDot=1.0/4.0; // check this difference\n      // Local Susceptibility,Entropy\n      Suscep.dImpValue=SusDot;\n      Entropy.dImpValue=log(2.0);\n      break;\n    case 2 :\n      cout << \" Not implemented yet...\" << endl;\n      exit(0);\n      break;\n    case 3 :\n      OneChQS_SetH0Chain(&Aeig, &Qm1fNQ);\n      Nsites0=1; // Adding N=1 site\n      chi_N=chiN(0,Lambda); // tunneling to site N=1 \n                            //(chi_N connects sites N and N+1)\n      // Local Susceptibility,Entropy\n      Suscep.CalcChain=true;\n      Entropy.CalcChain=true;\n      Suscep.dImpValue=0.0;\n      Entropy.dImpValue=0.0;\n      break;\n    case 5 :\n      OneChQS_SetSMM_Hm1(Params,&Aeig, &Qm1fNQ,MatArray);\n      Nsites0=0; // N=0 site only\n      chi_N=chiN(0,Lambda); // tunneling to site N=1 \n                            //(chi_N connects sites N and N+1)\n      KeepSz=1;\n      calcdens=0;\n      break;\n    default :\n      cout << \" Model not implemented. Exiting... \" << endl;\n      exit(0);\n      break;\n    }\n  //end switch models\n\n\n  // Set AeigCut\n  AeigCut.ClearAll();\n  AeigCut=CutStates(&Aeig, Ncutoff);\n  \n // Set operators to update\n\n\n  // Will this work??? Yes!!\n\n//   MatArray[0].NeedOld=false;\n//   MatArray[0].CheckForMatEl=OneChQS_cd_check;\n//   MatArray[0].CalcMatEl=OneChQS_fN_MatEl;\n\n\n\n  ////////////// \n  Nsites=Nsites0-1; //Nsites=-1 or 0\n  DN=HalfLambdaFactor*pow(Lambda,(-(Nsites-1)/2.0) );\n  TM=DN/betabar;\n  cout << \"DN = \" << DN << \"TM = \" << TM << endl;\n\n  if (calcdens==1)\n    {\n      MatArray[0].NeedOld=true;\n      MatArray[0].CheckForMatEl=OneChQS_nd_check;\n      MatArray[0].CalcMatEl=OneChQS_nd_MatEl;\n\n      MatArray[1].NeedOld=true;\n      MatArray[1].CheckForMatEl=OneChQS_cd_check;\n      MatArray[1].CalcMatEl=OneChQS_cd_MatEl;\n\n      // Sep 08: calculating <Sz2>\n      MatArray[2].NeedOld=true;\n      MatArray[2].CheckForMatEl=OneChQS_nd_check;\n      MatArray[2].CalcMatEl=OneChQS_nd_MatEl;\n\n\n\n      Params.clear();\n      Params.push_back(betabar);  \n      ndot=CalcOpAvg(Params,&AeigCut,&MatArray[0],true,1);\n      cout << \" ed = \" << ed << \" Initial ndot = \" << ndot << endl;\n      Sz2=CalcOpAvg(Params,&AeigCut,&MatArray[2],true,1);\n      cout << \" Sz2 = \" << Sz2 << \" Initial Sz2 = \" << Sz2 << endl;\n\n\n      for (int ibl=0;ibl<MatArray[1].NumMatBlocks();ibl++)\n\tMatArray[1].PrintMatBlock(ibl);\n\n      // Interface with old functions.\n//       AeigCut.SaveQSParameters();\n//       MatArray[1].SaveInOldFormat();\n\n    }\n  if ( (ModelNo==3)&&(calcdens==3) ){\n    TM=DN/betabar;\n    Params.clear();\n    Params.push_back(betabar);\n    // New Stuff\n    //Suscep.ReadNChainValue(Nsites,Nsites0); // Chain starts at N=0\n    // Wrong: Nsites=Nsites0-1 AND it's a chain calculation!\n    Suscep.AddValue(Params,&Aeig,1,true,TM);\n    Suscep.SaveNValue(Nsites,Nsites0);\n    //Entropy.ReadNChainValue(Nsites,Nsites0);\n    // Wrong: Nsites=Nsites0-1 AND it's a chain calculation!\n    Entropy.AddValue(Params,&Aeig,1,true,TM);\n    Entropy.SaveNValue(Nsites,Nsites0);\n  }\n\n  // Jul 09: testing CNRGchain\n\n  //chain1.SetChainWilson(Nsitesmax);\n\n  // Loop on Nsites\n\n  // Entering calculation of H_Nsites0\n  Nsites=Nsites0;\n  while (Nsites<Nsitesmax)\n    {\n      cout << \"Nsites = \" << Nsites << endl;\n      cout << \"Old Nshell = \" << Aeig.Nshell << endl;\n      cout << \"BEG Nshell = \" << Aeig.Nshell+1 << endl;\n      cout << \"chi_(N-1) = \" << chi_N << endl;\n      DN=HalfLambdaFactor*pow(Lambda,(-(Nsites-1)/2.0) );\n      TM=DN/betabar;\n      cout << \"DN = \" << DN << \"TM = \" << TM << endl;\n\n      // Build Abasis\n\n      /////QS_BuildBasis(&AeigCut,&Abasis,&SingleSite,UpdateBefCut);\n      QS_BuildBasis(&AeigCut,&Abasis,&SingleSite,UpdateBefCut,KeepSz);\n\n      //Abasis.PrintAll();\n      \n      cout << \"Basis Nstates = \" << Abasis.Nstates() << endl;\n      \n      // Build and diagonalize H_N+1 (general): Build Aeigv\n      // 1 - Get old matrix elements\n      // 2 - Build and diagonalize H_N+1\n\n      cout << \"Diagonalizing HN... \" << endl;\n\n      OneChQS_DiagHN(Qm1fNQ,Abasis,SingleSite,Aeig,0.0,chi_N,Lambda);\n\n      cout << \"... done diagonalizing HN. \" << endl;\n\n      Aeig.PrintEn();\n//       for (int ibl=0;ibl<Aeig.NumBlocks();ibl++)\n// \tAeig.PrintBlock(ibl);\n\n      if (UpdateBefCut==1)\n\t{\n\t  cout << \"Updating matrices before cutting... \" << endl;\n\t  OneChQS_UpdateQm1fQ(&Qm1fNQ,&Aeig,&Abasis,&SingleSite);\n\t  cout << \"... done updating matrices. \" << endl;\n\t}\n\n\n      // Calculate Susceptibility\n\n      if ( (calcdens==2)||(calcdens==3) ){\n\tTM=DN/betabar;\n\tParams.clear();\n\tParams.push_back(betabar);\n\t// New Stuff\n\t//Suscep.ReadNChainValue(Nsites,Nsites0); // Chain starts at N=0 WRONG\n\tSuscep.ReadNChainValue(Nsites-Nsites0,0);// Chain starts at N=1!\n\tSuscep.AddValue(Params,&Aeig,1,true,TM);\n\tSuscep.SaveNValue(Nsites,Nsites0);\n\t//Entropy.ReadNChainValue(Nsites,Nsites0); // WRONG\n\tEntropy.ReadNChainValue(Nsites-Nsites0,0);\n\tEntropy.AddValue(Params,&Aeig,1,true,TM);\n\tEntropy.SaveNValue(Nsites,Nsites0);\n      }\n\n      // Eliminate states, update matrices, calculate stuff \n\n      // Try this here!\n      cout << \"Cutting states...\" << endl;\n      \n      AeigCut.ClearAll();\n      AeigCut=CutStates(&Aeig, Ncutoff);\n\n      cout << \"... done cutting states.\" << endl;\n\n      // Calculate new matrix elements using the CUT basis:\n      // update Qm1fNQ, Qm1cdQ, etc.\n\n      if (UpdateBefCut==0)\n\t{\n\t  cout << \"Updating matrices after cutting... \" << endl;\n\t  //OneChQS_UpdateMatrixAfterCutting(&Qm1fNQ,&MQQp1,\n\t  //          &AeigCut,&Abasis,&SingleSite);\n\t  OneChQS_UpdateMatrixAfterCutting(&Qm1fNQ,&MatArray[1],\n\t\t\t\t\t   &AeigCut,&Abasis,&SingleSite);\n\t  cout << \"... done updating matrices. \" << endl;\n\n\t  // New Update\n\n\t  // Calculate Spectral density, <ndot>\n\t  if (calcdens==1)\n\t    {\t      \n// \t      UpdateMatrices(&SingleSite,&AeigCut, \n// \t\t\t     &Abasis,MatArray, 2);\n// Calc Sz2 too now: update 3 mats\n\t      UpdateMatrices(&SingleSite,&AeigCut, \n\t\t\t     &Abasis,MatArray, 3);\n\n// \t      for (int ibl=0;ibl<MatArray[1].NumMatBlocks();ibl++)\n// \t\tMatArray[1].PrintMatBlock(ibl);\n\n\t      if (Nsites==0)\n\t\tfor (int ist=0;ist<MatArray[1].Nstates();ist++)\n\t\t  {\n\t\t    for (int jst=0;jst<MatArray[1].Nstates();jst++) \n\t\t      cout << MatArray[1].GetMatEl(ist,jst) << \"  \";\n\t\t    cout << endl;\n\t\t  }\n\n\t      // Changed to NumMats to 2\n\t      TM=DN/betabar;\n\t      Params.clear();\n\t      Params.push_back(betabar);\n\t      ndot=CalcOpAvg(Params,&AeigCut,&MatArray[0],true,1);\n\t      \t      \n\t      \n\t      cout << \" ed = \" << ed; \n\t      cout.precision(10);\n\t      cout << scientific << \" Temp = \" << TM;\n\t      cout << resetiosflags (ios_base::floatfield);\n\t      cout << \" ndot = \" << ndot << endl;\n\n\t      Sz2=CalcOpAvg(Params,&AeigCut,&MatArray[2],true,1);\n\t      cout << \" ed = \" << ed; \n\t      cout.precision(10);\n\t      cout << scientific << \" Temp = \" << TM;\n\t      cout << resetiosflags (ios_base::floatfield);\n\t      cout << \" Sz2 = \" << Sz2 << endl;\n\n\n\t      // Interface with old functions.\n\t      AeigCut.SaveQSParameters();\n\t      MatArray[1].SaveInOldFormat();\n\t    }\n\t  // end if calcdens==1\n\t  \t  \n\t}\n      // end if UpdateCefCut==0\n\n      cout << \"END Nshell = \" << Aeig.Nshell << endl;\n\n     // Update chi_N\n\n//       daux[0]=(double)( 1.0-pow(Lambda,(-(Nsites+1))) );\n//       daux[1]=(double)sqrt( 1.0-pow(Lambda,-(2*(Nsites+1)-1)) );\n//       daux[2]=(double)sqrt( 1.0-pow(Lambda,-(2*(Nsites+1)+1)) );  \n//       daux[3]=0.5*(1.0+(1.0/Lambda))*(double)sqrt(Lambda);\n\n//       chi_N=daux[0]/(daux[1]*daux[2]);\n// new (Jul 09)\n      chi_N=chain1.GetChin(Nsites);\n\n      cout << \"chi_N = \" << chi_N << endl;\n//       cout << \"Chi(N=\"<< Nsites <<\") = \" << chiN(Nsites,Lambda) << endl; \n\n      // Update sites\n      Nsites++;\n    }\n  // end NRG loop\n\n  // De-allocate MatArray \n  delete[] MatArray;\n\n\n  cout << \"=== Calculation Finished! ==== \"<< endl;\n  OutFile.open(\"NRG_end.txt\");\n  OutFile << \"END NRG calculation\" << endl;\n  OutFile.close();\n\n\n\n}\n// END code\n\n\n\n////////////////////////////////\n///                          ///\n///       Trash can          ///\n///                          ///\n////////////////////////////////\n\n\n", "meta": {"hexsha": "732949ec996a4104aa26a5faaa2a79a215422d91", "size": 15449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/OneChQS/OneChQS.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/OneChQS/OneChQS.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OneChQS/OneChQS.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["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.9211409396, "max_line_length": 76, "alphanum_fraction": 0.5584180206, "num_tokens": 4885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042216, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5265740080442897}}
{"text": "#ifndef _glia_util_random_hxx_\n#define _glia_util_random_hxx_\n\n#include \"glia_base.hxx\"\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/discrete_distribution.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace glia {\nnamespace random {\n\ntemplate <typename T, typename TInputIterator> void\nsampleWithoutReplacement (\n    std::vector<T>& output, TInputIterator inputBegin,\n    TInputIterator inputEnd, int n)\n{\n  std::random_shuffle(inputBegin, inputEnd);\n  output.reserve(output.size() + n);\n  for (int i = 0; i < n; ++i) { output.push_back(*(inputBegin + i)); }\n}\n\n\ntemplate <typename T> void\nsampleWithReplacement (\n    std::vector<T>& output, std::vector<T> const& input, int n,\n    const long seed)\n{\n  boost::mt19937 rng(seed);\n  boost::random::uniform_int_distribution<> dice(0, input.size() - 1);\n  output.reserve(n);\n  for (int i = 0; i < n; ++i) { output.push_back(input[dice(rng)]); }\n}\n\n\ninline int sample (std::vector<double> const& weights, const long seed)\n{\n  boost::mt19937 rng(seed);\n  boost::random::discrete_distribution<>\n      dist(weights.begin(), weights.end());\n  return dist(rng);\n}\n\n\ninline boost::variate_generator\n<boost::mt19937, boost::normal_distribution<>>\n    gaussian (double mean, double stddev, const long seed)\n{\n  boost::mt19937 rng(seed);\n  boost::normal_distribution<> dist(mean, stddev);\n  return\n      boost::variate_generator\n      <boost::mt19937, boost::normal_distribution<>>(rng, dist);\n}\n\n};\n};\n\n#endif\n", "meta": {"hexsha": "a062de659647f5fb6bcd2935eb32b8375db2cb6b", "size": 1528, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/util/random.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/util/random.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/util/random.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": 25.4666666667, "max_line_length": 71, "alphanum_fraction": 0.7133507853, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5265739947457904}}
{"text": "#include <omp.h>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <iostream>\n#include <limits>\n#include <vector>\n#include \"Python.h\"\n#include \"arrayobject.h\"\n#include \"kdtree.h\"\n#include \"progress_bar.h\"\n#include \"python_util.h\"\n#include \"timer.h\"\n\nusing namespace Eigen;\nusing namespace std;\n\ntemplate <typename T>\nvoid estimate_normals(vector<T>* eigenvectors, vector<T>* eigenvalues,\n                      vector<int>* neighborhood_sizes, const vector<T>& points,\n                      const std::size_t k, const T d_max,\n                      const std::vector<int>* subsample_indices,\n                      int num_eigen = 1, bool verbose = true,\n                      int num_procs = -1) {\n  size_t num_points = points.size() / 3;\n  Map<const Matrix<T, Dynamic, 3, RowMajor> > P(&points[0], num_points, 3);\n\n  if (num_procs < 0) num_procs = omp_get_num_procs();\n  if (verbose)\n    cout << \"(estimate_normals) using \" << num_procs << \" threads\" << endl;\n\n  // organize points into k-d tree\n  pointkd::BuildParams build_params;\n  build_params.num_proc = num_procs;\n  double build_time = getTime();\n  pointkd::KdTree<T, 3> tree(points, build_params);\n  build_time = getTime() - build_time;\n  if (verbose) {\n    cout << \"(estimate_normals) \";\n    cout << \"k-d tree build time (s): \" << build_time << endl;\n  }\n\n  int num_normals = num_points;\n  if (subsample_indices != NULL)\n    num_normals = subsample_indices->size();\n\n  // pre-allocate space for results (assume num_eigen either 1 or 3)\n  if (eigenvectors) eigenvectors->resize(num_normals * num_eigen * 3);\n  if (eigenvalues) eigenvalues->resize(num_normals * num_eigen);\n  if (neighborhood_sizes) neighborhood_sizes->resize(num_normals);\n\n  tbb::task_scheduler_init(1);  // use just 1 thread for k-d tree queries\n  omp_set_num_threads(num_procs);\n\n  if (verbose) {\n    cout << \"(estimate_normals) neighborhood parameters: \" << endl;\n    cout << \"  k = \" << k << endl;\n    cout << \"  r = \" << d_max << endl;\n  }\n\n  ProgressBar<int> bar((int)num_normals);\n\n  double pca_time = getTime();\n\n#pragma omp parallel for schedule(static, 1000)\n  for (int i = 0; i < (int)num_normals; i++) {\n    if (verbose && omp_get_thread_num() == 0 && i % 1000 == 0) {\n      bar.update(i);\n      cout << \"\\r\" << bar.get_string();\n    }\n\n    int i_ = i;\n    if (subsample_indices != NULL)\n      i_ = (*subsample_indices)[i];\n\n    // not using KNearestNeighborsSelf, because we want to include the\n    // current point in the normal estimation calculation\n    pointkd::Indices indices;\n    vector<T> q(P.data() + i_ * 3, P.data() + (i_ + 1) * 3);\n    if (k == -1)\n      tree.RNearNeighbors(indices, &q[0], d_max);\n    else\n      tree.KNearestNeighbors(indices, &q[0], k, d_max);\n\n    Matrix<T, Dynamic, 3, RowMajor> X(indices.size(), 3);\n    for (size_t j = 0; j < indices.size(); j++) X.row(j) = P.row(indices[j]);\n    X.rowwise() -= X.colwise().mean();\n    Matrix<T, 3, 3> C = X.transpose() * X;\n    C /= (T)indices.size();\n    SelfAdjointEigenSolver<Matrix<T, 3, 3> > es(C);\n\n    // record results of PCA\n    if (eigenvectors) {\n      if (num_eigen == 1) {\n        Map<Matrix<T, 3, 1> > temp(&(*eigenvectors)[i * 3]);\n        temp = es.eigenvectors().col(0);\n      } else {  // num_eigen == 3\n        Map<Matrix<T, 3, 3> > temp(&(*eigenvectors)[i * 9]);\n        temp = es.eigenvectors();\n      }\n    }\n    if (eigenvalues) {\n      if (num_eigen == 1) {\n        (*eigenvalues)[i] = es.eigenvalues()(0);\n      } else {  // num_eigen == 1\n        Map<Matrix<T, 3, 1> > temp(&(*eigenvalues)[i * 3]);\n        temp = es.eigenvalues();\n      }\n    }\n    if (neighborhood_sizes)\n      (*neighborhood_sizes)[i] = indices.size();\n  }\n\n  pca_time = getTime() - pca_time;\n\n  if (verbose) {\n    bar.update((int)num_normals);\n    cout << \"\\r\" << bar.get_string() << endl;\n    cout << \"(estimate_normals) PCA time (s): \" << pca_time << std::endl;\n  }\n}\n\ntemplate <typename T>\nstruct NumpyTypeNumber {};\n\ntemplate <>\nstruct NumpyTypeNumber<float> {\n  static const int value = NPY_FLOAT32;\n};\n\ntemplate <>\nstruct NumpyTypeNumber<double> {\n  static const int value = NPY_FLOAT64;\n};\n\ntemplate <typename T>\nvoid estimate_normals(PyObject*& out1, PyObject*& out2, PyObject*& out3,\n                      const Array2D& arr, int k, float r,\n                      std::vector<int>* ptr_subsample_indices,\n                      bool output_eigenvalues, bool output_all_eigenvectors,\n                      bool output_neighborhood_sizes, bool verbose,\n                      int num_procs) {\n  vector<T> points;\n  VectorFromArray2D(points, arr);\n\n  int num_normals = arr.m;\n  if (ptr_subsample_indices != NULL)\n    num_normals = ptr_subsample_indices->size();\n\n  int num_eigen = 1;\n  int out1_ndim = 2;\n  int out2_ndim = 1;\n  npy_intp out1_dims[3] = {num_normals, 3, -1};\n  npy_intp out2_dims[2] = {num_normals, -1};\n  if (output_all_eigenvectors) {\n    num_eigen = 3;\n    out1_ndim = 3;\n    out2_ndim = 2;\n    out1_dims[2] = 3;\n    out2_dims[1] = 3;\n  }\n\n  int out3_ndim = 1;\n  int out3_typenum = NPY_INT;\n  npy_intp out3_dims[2] = {num_normals, -1};\n\n  int typenum = NumpyTypeNumber<T>::value;\n\n  out1 = NULL;\n  out2 = NULL;\n  out3 = NULL;\n  vector<T> evecs;\n  vector<T> evals;\n  vector<int> nbhd_sizes;\n  estimate_normals<T>(&evecs, output_eigenvalues == 1 ? &evals : NULL,\n                      output_neighborhood_sizes == 1 ? &nbhd_sizes : NULL,\n                      points, k, r, ptr_subsample_indices, num_eigen, verbose,\n                      num_procs);\n  out1 = PyArray_EMPTY(out1_ndim, out1_dims, typenum, false);\n  copy(evecs.begin(), evecs.end(), (T*)PyArray_DATA((PyArrayObject*)out1));\n  if (output_eigenvalues) {\n    out2 = PyArray_EMPTY(out2_ndim, out2_dims, typenum, false);\n    copy(evals.begin(), evals.end(), (T*)PyArray_DATA((PyArrayObject*)out2));\n  }\n  if (output_neighborhood_sizes) {\n    out3 = PyArray_EMPTY(out3_ndim, out3_dims, out3_typenum, false);\n    copy(nbhd_sizes.begin(), nbhd_sizes.end(),\n         (int*)PyArray_DATA((PyArrayObject*)out3));\n  }\n}\n\nstatic char estimate_normals_usage[] =\n    \"Estimates normals at all points using principal component analysis\\n\"\n    \"(PCA). Specifically, computes eigenvectors of the covariance matrix C\\n\"\n    \"based on the local neighborhoods of each point.\\n\"\n    \"\\n\"\n    \".. math::\\n\"\n    \"   C = \\\\frac{1}{N}\\\\sum_{i=1}^{N}{(p_i-\\\\mu)(p_i-\\\\mu)^T}\\n\"\n    \"\\n\"\n    \"where :math:`p_1 ... p_N` are the points in a given neighborhood and\\n\"\n    \":math:`\\\\mu` is the centroid of the points.\\n\"\n    \"\\n\"\n    \"\\n\"\n    \"Parameters\\n\"\n    \"----------\\n\"\n    \"points : 3-column numpy array of type float32 or float64\\n\"\n    \"    Input point cloud.\\n\"\n    \"k : int\\n\"\n    \"    Number of neighbors to use.\\n\"\n    \"    For pure r-near neighborhoods, set this to -1.\\n\"\n    \"r : float\\n\"\n    \"    Use neighbors within r of query point.\\n\"\n    \"    For pure k-nearest neighborhoods, set this to np.inf.\\n\"\n    \"subsample : 1-d array of bool or int, optional\\n\"\n    \"    Optionally estimate normals at subset of points specified by a\\n\"\n    \"    boolean mask having length equal to the number of points, or by\\n\"\n    \"    integer indices into the array of points. Default: None.\\n\"\n    \"output_eigenvalues : bool, optional\\n\"\n    \"    Default: False.\\n\"\n    \"output_all_eigenvectors : bool, optional\\n\"\n    \"    Default: False.\\n\"\n    \"output_neighborhood_sizes : bool, optional\\n\"\n    \"    Default: False.\\n\"\n    \"verbose : bool, optional\\n\"\n    \"    Default: True.\\n\"\n    \"num_procs : int, optional\\n\"\n    \"    Default: use all processors.\\n\"\n    \"\\n\"\n    \"Returns\\n\"\n    \"-------\\n\"\n    \"results : ndarray or tuple of ndarray's\\n\"\n    \"    PCA results. The tuple return type is triggered if any of\\n\"\n    \"    output_eigenvalues or output_neighborhood_sizes is True.\\n\"\n    \"\\n\"\n    \"\\n\"\n    \"The following table summarizes all potential return types. Here m is the\\n\"\n    \"number of PCAs performed. If subsample is not None, then m is the size\\n\"\n    \"of subsample. Otherwise, m is just the number of input points.\\n\"\n    \"\\n\"\n    \"+---------------------------+------------------------------------------+\\n\"\n    \"|                           |output_all_eigenvectors                   |\\n\"\n    \"|                           +----------------+-------------------------+\\n\"\n    \"|                           |F               |T                        |\\n\"\n    \"+======================+====+================+=========================+\\n\"\n    \"|**output_eigenvalues**|F, F|m x 3           |m x 3 x 3                |\\n\"\n    \"|                      +----+----------------+-------------------------+\\n\"\n    \"|**output_nbhd_sizes** |F, T|(m x 3, None, m)|(m x 3 x 3, None, m)     |\\n\"\n    \"|                      +----+----------------+-------------------------+\\n\"\n    \"|                      |T, F|(m x 3, m, None)|(m x 3 x 3, m x 3, None) |\\n\"\n    \"|                      +----+----------------+-------------------------+\\n\"\n    \"|                      |T, T|(m x 3, m, m)   |(m x 3 x 3, m x 3, m)    |\\n\"\n    \"+----------------------+----+----------------+-------------------------+\\n\"\n    \"\\n\"\n    \"Note:\\n\"\n    \"    * The j-th eigenvector of the i-th PCA result is given by\\n\"\n    \"      indices [i, j, :].\\n\"\n    \"    * eigenvectors are sorted in order of increasing eigenvalue\\n\"\n    \"\\n\";\n\nstatic PyObject* estimate_normals_wrapper(PyObject* self, PyObject* args,\n                                          PyObject* kwargs) {\n  PyObject* p = NULL;\n  PyObject* subsample = Py_None;\n  int k;\n  float r;\n  int output_eigenvalues = 0;\n  int output_all_eigenvectors = 0;\n  int output_neighborhood_sizes = 0;\n  int verbose = 1;\n  int num_procs = -1;\n  static char* keywords[] = {\n      \"points\", \"k\", \"r\", \"subsample\", \"output_eigenvalues\",\n      \"output_all_eigenvectors\", \"output_neighborhood_sizes\", \"verbose\",\n      \"num_procs\", NULL};\n  if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"Oif|Oiiiii\", keywords, &p, &k,\n                                   &r, &subsample, &output_eigenvalues,\n                                   &output_all_eigenvectors,\n                                   &output_neighborhood_sizes, &verbose,\n                                   &num_procs)) {\n    PyErr_SetString(PyExc_RuntimeError, \"Failed to parse inputs\");\n    return NULL;\n  }\n\n  // check k and r\n  if (r <= 0.0f) {\n    PyErr_SetString(PyExc_ValueError, \"r must be positive\");\n    return NULL;\n  } else if (k == 0) {\n    PyErr_SetString(PyExc_ValueError, \"k cannot be zero\");\n    return NULL;\n  } else if (k < 0 && r == std::numeric_limits<float>::infinity()) {\n    PyErr_SetString(PyExc_ValueError, \"invalid combo: r == inf and k < 0\");\n    return NULL;\n  }\n\n  Array2D arr;\n  if (!CheckAndExtractArray2D(arr, p)) {\n    if (!PyErr_Occurred())\n      PyErr_SetString(PyExc_TypeError,\n                      \"points must be interpretable as 0, 1 or 2-d array\");\n    return NULL;\n  }\n\n  std::vector<int> subsample_indices;\n  std::vector<int>* ptr_subsample_indices = NULL;\n  if (subsample != Py_None) {\n    if (!CheckAndExtractIndices(subsample_indices, subsample, arr.m)) {\n      if (!PyErr_Occurred())\n        PyErr_SetString(PyExc_TypeError,\n                        \"subsample must be interpretable as specifying a \"\n                        \"subset of points\");\n      return NULL;\n    }\n    ptr_subsample_indices = &subsample_indices;\n  }\n\n  PyObject* out1 = NULL;\n  PyObject* out2 = NULL;\n  PyObject* out3 = NULL;\n  if (arr.type_num == NPY_FLOAT32) {\n    estimate_normals<float>(out1, out2, out3, arr, k, r, ptr_subsample_indices,\n                            (bool)output_eigenvalues,\n                            (bool)output_all_eigenvectors,\n                            (bool)output_neighborhood_sizes, (bool)verbose,\n                            num_procs);\n  } else if (arr.type_num == NPY_FLOAT64) {\n    estimate_normals<double>(out1, out2, out3, arr, k, r, ptr_subsample_indices,\n                             (bool)output_eigenvalues,\n                             (bool)output_all_eigenvectors,\n                             (bool)output_neighborhood_sizes, (bool)verbose,\n                             num_procs);\n  } else {\n    PyErr_SetString(PyExc_TypeError, \"points must be float32 or float64\");\n    return NULL;\n  }\n\n  if (out2 == NULL && out3 == NULL) {\n    return out1;\n  } else {\n    PyObject* out = PyTuple_New(3);\n    PyTuple_SetItem(out, 0, out1);\n    PyTuple_SetItem(out, 1, out2 != NULL ? out2 : Py_None);\n    PyTuple_SetItem(out, 2, out3 != NULL ? out3 : Py_None);\n    return out;\n  }\n}\n\nstatic PyMethodDef methods[] = {\n    {\"estimate_normals\", (PyCFunction)estimate_normals_wrapper,\n     METH_VARARGS | METH_KEYWORDS, estimate_normals_usage},\n    {NULL, NULL, 0, NULL}};\n\n#if PY_MAJOR_VERSION >= 3\nstatic struct PyModuleDef module_def = {PyModuleDef_HEAD_INIT,\n                                        \"estimate_normals\",\n                                        NULL,\n                                        -1,\n                                        methods,\n                                        NULL,\n                                        NULL,\n                                        NULL,\n                                        NULL};\n\nPyMODINIT_FUNC PyInit_estimate_normals(void) {\n  PyObject* module = PyModule_Create(&module_def);\n#else\nPyMODINIT_FUNC initestimate_normals(void) {\n  (void)Py_InitModule(\"estimate_normals\", methods);\n#endif\n\n  import_array();\n\n#if PY_MAJOR_VERSION >= 3\n  return module;\n#endif\n}\n", "meta": {"hexsha": "a17239918163081adf28d66c24c05882f48e8357", "size": 13414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pptk/processing/estimate_normals/estimate_normals.cpp", "max_stars_repo_name": "elementreeinc/pptk", "max_stars_repo_head_hexsha": "1e82c008172367a117473d3869ea57b75cd74ed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-17T08:08:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-17T08:08:15.000Z", "max_issues_repo_path": "pptk/processing/estimate_normals/estimate_normals.cpp", "max_issues_repo_name": "Yuanqiujie/pptk", "max_issues_repo_head_hexsha": "697c09ac1a5a652d43aa8c4deb98c27c3a0b77e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pptk/processing/estimate_normals/estimate_normals.cpp", "max_forks_repo_name": "Yuanqiujie/pptk", "max_forks_repo_head_hexsha": "697c09ac1a5a652d43aa8c4deb98c27c3a0b77e3", "max_forks_repo_licenses": ["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.6755319149, "max_line_length": 80, "alphanum_fraction": 0.5619502013, "num_tokens": 3626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5265739881799026}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// random::poisson_ext::devroye::detail::step4::basic.hpp         \t\t    //\n//                                                                          //\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#ifndef BOOST_RANDOM_POISSON_EXT_DEVROYE_DETAIL_STEP4_BASIC_HPP_ER_2010\n#define BOOST_RANDOM_POISSON_EXT_DEVROYE_DETAIL_STEP4_BASIC_HPP_ER_2010\n\n#include <boost/random/poisson_ext/devroye/detail/q.hpp>\n#include <boost/random/poisson_ext/devroye/detail/int_mean.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace poisson{\nnamespace devroye{  \nnamespace step4{\n\n\t// Poisson sampler by the method of Devroye with a basic step4\n\t//\n\t// Complexity O(1+sqrt(mean)) as mean -> infinity, p.203\n\ttemplate<typename Int,typename T,typename P,\n        typename IntT,typename TInt,typename Q>\n    class basic \n        public devroye::crtp<\n            step4::basic<Int,T,P,IntT,TInt,Q>,\n            Int,T,P,IntT,TInt\n        >\n    {\n\t\ttypedef crtp<step4::basic<Int,T,P,IntT,Q>,Int,T,P,IntT,TInt> crtp_;\n\n\t\tpublic:\n\n\t\tbasic(){}\n\t\texplicit basic(const result_type& mean)\n            :crtp_(mean)\n            {}\n\n\t\tbool accept()const{    \n            T q = q::fun(this->i_mean(),this->i_y(),P(),IntT(),Q());\n\t\t\tif(this->v()<q)\n            {\n            \tthis->i_y_ += this->i_mean();\n                return true;\n            }else{\n\t\t\t\treturn false;            \n            }\n\t\t}\n\n\t};\n\n}// step4\n}// devroye\n}// poisson\n}// random\n}// boost\n\n#endif\n\n\n\n\n", "meta": {"hexsha": "c6647512f37ef75b958c7de914001bbdce868821", "size": 1944, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/poisson_ext/devroye/step4/basic.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": "random/boost/random/poisson_ext/devroye/step4/basic.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": "random/boost/random/poisson_ext/devroye/step4/basic.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": 29.4545454545, "max_line_length": 78, "alphanum_fraction": 0.5030864198, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5265647804469102}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2014.\n// Modifications copyright (c) 2014, Oracle and/or its affiliates.\n\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#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_AZIMUTH_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_AZIMUTH_HPP\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/algorithms/not_implemented.hpp>\n#include <boost/geometry/algorithms/detail/vincenty_inverse.hpp>\n\nnamespace boost { namespace geometry\n{\n\n// An azimuth is an angle between a vector/segment from origin to a point of\n// interest and a reference vector. Typically north-based azimuth is used.\n// North direction is used as a reference, angle is measured clockwise\n// (North - 0deg, East - 90deg). For consistency in 2d cartesian CS\n// the reference vector is Y axis, angle is measured clockwise.\n// http://en.wikipedia.org/wiki/Azimuth\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace detail_dispatch\n{\n\ntemplate <typename ReturnType, typename Tag>\nstruct azimuth\n    : not_implemented<Tag>\n{};\n\ntemplate <typename ReturnType>\nstruct azimuth<ReturnType, geographic_tag>\n{\n    template <typename P1, typename P2, typename Spheroid>\n    static inline ReturnType apply(P1 const& p1, P2 const& p2, Spheroid const& spheroid)\n    {\n        return geometry::detail::vincenty_inverse<ReturnType>\n                    ( get_as_radian<0>(p1), get_as_radian<1>(p1),\n                      get_as_radian<0>(p2), get_as_radian<1>(p2),\n                      spheroid ).azimuth();\n    }\n\n    template <typename P1, typename P2>\n    static inline ReturnType apply(P1 const& p1, P2 const& p2)\n    {\n        return apply(p1, p2, srs::spheroid<ReturnType>());\n    }\n};\n\ntemplate <typename ReturnType>\nstruct azimuth<ReturnType, spherical_equatorial_tag>\n{\n    template <typename P1, typename P2, typename Sphere>\n    static inline ReturnType apply(P1 const& p1, P2 const& p2, Sphere const& /*unused*/)\n    {\n        // http://williams.best.vwh.net/avform.htm#Crs\n        ReturnType dlon = get_as_radian<0>(p2) - get_as_radian<0>(p1);\n        ReturnType cos_p2lat = cos(get_as_radian<1>(p2));\n\n        // An optimization which should kick in often for Boxes\n        //if ( math::equals(dlon, ReturnType(0)) )\n        //if ( get<0>(p1) == get<0>(p2) )\n        //{\n        //    return - sin(get_as_radian<1>(p1)) * cos_p2lat);\n        //}\n\n        // \"An alternative formula, not requiring the pre-computation of d\"\n        // In the formula below dlon is used as \"d\"\n        return atan2(sin(dlon) * cos_p2lat,\n            cos(get_as_radian<1>(p1)) * sin(get_as_radian<1>(p2))\n            - sin(get_as_radian<1>(p1)) * cos_p2lat * cos(dlon));\n    }\n\n    template <typename P1, typename P2>\n    static inline ReturnType apply(P1 const& p1, P2 const& p2)\n    {\n        return apply(p1, p2, 0); // dummy model\n    }\n};\n\ntemplate <typename ReturnType>\nstruct azimuth<ReturnType, spherical_polar_tag>\n    : azimuth<ReturnType, spherical_equatorial_tag>\n{};\n\ntemplate <typename ReturnType>\nstruct azimuth<ReturnType, cartesian_tag>\n{\n    template <typename P1, typename P2, typename Plane>\n    static inline ReturnType apply(P1 const& p1, P2 const& p2, Plane const& /*unused*/)\n    {\n        ReturnType x = get<0>(p2) - get<0>(p1);\n        ReturnType y = get<1>(p2) - get<1>(p1);\n\n        // NOTE: azimuth 0 is at Y axis, increasing right\n        // as in spherical/geographic where 0 is at North axis\n        return atan2(x, y);\n    }\n\n    template <typename P1, typename P2>\n    static inline ReturnType apply(P1 const& p1, P2 const& p2)\n    {\n        return apply(p1, p2, 0); // dummy model\n    }\n};\n\n} // detail_dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\n/// Calculate azimuth between two points.\n/// The result is in radians.\ntemplate <typename ReturnType, typename Point1, typename Point2>\ninline ReturnType azimuth(Point1 const& p1, Point2 const& p2)\n{\n    return detail_dispatch::azimuth\n            <\n                ReturnType,\n                typename geometry::cs_tag<Point1>::type\n            >::apply(p1, p2);\n}\n\n/// Calculate azimuth between two points.\n/// The result is in radians.\ntemplate <typename ReturnType, typename Point1, typename Point2, typename Model>\ninline ReturnType azimuth(Point1 const& p1, Point2 const& p2, Model const& model)\n{\n    return detail_dispatch::azimuth\n            <\n                ReturnType,\n                typename geometry::cs_tag<Point1>::type\n            >::apply(p1, p2, model);\n}\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_AZIMUTH_HPP\n", "meta": {"hexsha": "3e9c398f7d644b8adc54de53343053cc5dba6912", "size": 5122, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/algorithms/detail/azimuth.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T05:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T05:02:05.000Z", "max_issues_repo_path": "3party/boost/boost/geometry/algorithms/detail/azimuth.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "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": "3party/boost/boost/geometry/algorithms/detail/azimuth.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-09T21:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-09T21:21:09.000Z", "avg_line_length": 32.213836478, "max_line_length": 88, "alphanum_fraction": 0.6811792269, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5265647637623248}}
{"text": "/// General Matrix Multiplication\n#include <HElib/FHE.h>\n#include <HElib/FHEContext.h>\n#include <HElib/EncryptedArray.h>\n#include <HElib/NumbTh.h>\n\n#include \"SMP/Matrix.hpp\"\n#include \"SMP/Timer.hpp\"\n#include \"SMP/HElib.hpp\"\n#include \"SMP/literal.hpp\"\n#include \"SMP/network/net_io.hpp\"\n#include \"SMP/SMPServer.hpp\"\n\n#include <boost/asio.hpp>\n#include <boost/asio/ip/tcp.hpp>\n#include <iostream>\n#include <numeric>\n#include <list>\nusing boost::asio::ip::tcp;\nconstexpr int REPEAT = 1;\nstd::atomic<int> global_counter(0);\n\ninline long round_div(long a, long b) {\n    return (a + b - 1) / b;\n}\n\nvoid zero(Matrix &mat) {\n    for (long i = 0; i < mat.NumRows(); i++)\n        for (long j = 0; j < mat.NumCols(); j++)\n            mat[i][j] = 0;\n}\n\nvoid randomize(Matrix &mat, long p = 3) {\n    for (long i = 0; i < mat.NumRows(); i++)\n        for (long j = 0; j < mat.NumCols(); j++)\n            mat[i][j] = NTL::RandomBnd(p);\n}\n\n\nvoid fill_compute(Matrix& mat,\n\t\t\t\t  long row_blk,\n\t\t\t\t  long col,\n                  const std::vector<long> &inner_prod,\n                  const EncryptedArray *ea)\n{\n    const long l = ea->size();\n    assert(inner_prod.size() == l);\n\tconst bool is_vec = mat.NumRows() == 1;\n\tconst long row_start = is_vec ? 0 : row_blk * l;\n\tconst long col_start = is_vec ? row_blk * l : col;\n\n    for (long ll = 0; ll < l; ll++) {\n        long computed = inner_prod[ll];\n\t\tif (!is_vec) {\n\t\t\tlong row = row_start + ll;\n\t\t\tif (row < mat.NumRows())\n\t\t\t\tmat.put(row, col, computed);\n\t\t\telse\n\t\t\t\tbreak;\n\t\t} else {\n\t\t\tlong col = col_start + ll;\n\t\t\tif (col < mat.NumCols())\n\t\t\t\tmat.put(0, col, computed);\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n    }\n}\n\nstruct ClientBenchmark {\n    std::vector<double> pack_times;\n    std::vector<double> enc_times;\n    std::vector<double> dec_times;\n    std::vector<double> unpack_times;\n    std::vector<double> total_times;\n    int ctx_sent, ctx_recv;\n};\nClientBenchmark clt_ben;\n\nstruct ServerBenchmark {\n    std::vector<double> eval_times;\n};\nServerBenchmark srv_ben;\n\nvoid play_client(tcp::iostream &conn,\n                 FHESecKey &sk,\n                 FHEcontext &context,\n                 const long n1,\n                 const long n2,\n                 const long n3) {\n\t//* Convert to evalution key.\n\t//* This function is not provided by the origin HElib. Checkout our fork.\n    sk.convertToSymmetric();\n    FHEPubKey ek(sk);\n    conn << ek;\n    const EncryptedArray *ea = context.ea;\n    const long l = ea->size();\n    const long d = ea->getDegree();\n\n    Matrix A, B, ground_truth;\n    A.SetDims(n1, n2);\n    B.SetDims(n2, n3);\n    NTL::SetSeed(NTL::to_ZZ(123));\n    randomize(A, ek.getPtxtSpace());\n    randomize(B, ek.getPtxtSpace());\n    ground_truth = mul(A, B);\n    /// print grouth truth for debugging\n    const long MAX_X1 = round_div(A.NumRows(), l);\n    const long MAX_Y1 = round_div(A.NumCols(), d);\n    const long MAX_X2 = round_div(B.NumCols(), l);\n\n    std::vector<std::vector<Ctxt>> uploading;\n    uploading.resize(MAX_X1, std::vector<Ctxt>(MAX_Y1, Ctxt(sk)));\n\tdouble enc_time = 0.;\n    double pack_time = 0.;\n\t/// encrypt matrix\n\tNTL::ZZX packed_poly;\n\tfor (int x = 0; x < MAX_X1; x++) {\n\t\tfor (int k = 0; k < MAX_Y1; k++) {\n\t\t\tinternal::BlockId blk = {x, k};\n\t\t\tdouble one_pack_time = 0.;\n\t\t\tdouble one_enc_time = 0.;\n\t\t\tauto block = internal::partition(A, blk, ea, false);\n\t\t\t{/// packing\n\t\t\t\tAutoTimer timer(&one_pack_time);\n\t\t\t\trawEncode(packed_poly, block.polys, context);\n\t\t\t}\n\t\t\t{/// encryption\n\t\t\t\tAutoTimer timer(&one_enc_time);\n\t\t\t\tsk.Encrypt(uploading[x][k], packed_poly);\n\t\t\t}\n\t\t\tpack_time += one_pack_time;\n\t\t\tenc_time += one_enc_time;\n\t\t}\n\t}\n    clt_ben.pack_times.push_back(pack_time);\n    clt_ben.enc_times.push_back(enc_time);\n\n    /// send ciphertexts of matrix\n    for (auto const& row : uploading) {\n        for (auto const& ctx : row) {\n            conn << ctx;\n            //_ctx_sent++;\n        }\n    }\n\tconn.flush();\n    clt_ben.ctx_sent = MAX_X1 * MAX_Y1;\n\t/// we convert DoubleCRT to poly form when send ciphertexts through, and thus, we\n\t/// count this cost as a part of encryption.\n\tclt_ben.enc_times.back() += getTimerByName(\"TO_POLY_OUTPUT\")->getTime() * 1000.;\n\n    std::vector<GMMPrecompTable> tbls = precompute_gmm_tables(context);\n    /// waiting results\n    long rows_of_A = A.NumRows();\n    long rows_of_Bt = B.NumCols(); // Bt::Rows = B::Cols\n\tint64_t ctx_cnt = 0;\n\tconn >> ctx_cnt;\n    clt_ben.ctx_recv = ctx_cnt;\n    std::vector<Ctxt> ret_ctxs(ctx_cnt, Ctxt(ek));\n\tfor (size_t k = 0; k < ctx_cnt; k++) {\n\t\tconn >> ret_ctxs.at(k);\n        //_ctx_received++;\n    }\n    double eval_time = 0.;\n    conn >> eval_time;\n    srv_ben.eval_times.push_back(eval_time);\n    /// decrypt\n    Matrix computed;\n    computed.SetDims(A.NumRows(), B.NumCols());\n    zero(computed);\n    int x = 0;\n    int y = 0;\n    std::vector<long> slots;\n    std::vector<NTL::zz_pX> _slots;\n    //NTL::Vec<long> decrypted;\n\tNTL::ZZX decrypted;\n\tdouble decrypt_time = 0.;\n    double unpack_time = 0.;\n\tlong ctx_idx = 0;\n\tbool dec_pass = true;\n\tfor (const auto &ctx : ret_ctxs) {\n\t\tdouble one_dec_time = 0.;\n\t\tdouble one_unpack_time = 0.;\n\t\tdo {\n\t\t\tAutoTimer timer(&one_dec_time);\n\t\t\tdec_pass &= ctx.isCorrect();\n\t\t\t//faster_decrypt(decrypted, sk, ctx);\n\t\t\tsk.Decrypt(decrypted, ctx);\n\t\t} while(0);\n\t\tdo {\n\t\t\tAutoTimer timer(&one_unpack_time);\n            extract_inner_products(slots, decrypted, tbls, context);\n\t\t} while(0);\n        decrypt_time += one_dec_time;\n        unpack_time += one_unpack_time;\n\n\t\tlong row_blk = ctx_idx / B.NumCols();\n\t\tlong column = ctx_idx % B.NumCols();\n\t\tctx_idx += 1;\n        fill_compute(computed, row_blk, column, slots, ea);\n    }\n\t/// we convert poly to DoubleCRT when receiving ciphertexts.\n\tdecrypt_time += getTimerByName(\"FROM_POLY_OUTPUT\")->getTime() * 1000.;\n    clt_ben.dec_times.push_back(decrypt_time);\n    clt_ben.unpack_times.push_back(unpack_time);\n\tif (!::is_same(ground_truth, computed, NTL::zz_p::modulus()))\n\t\tstd::cerr << \"The computation seems wrong \" << std::endl;\n\tif (!dec_pass)\n\t\tstd::cerr << \"Decryption might fail\" << std::endl;\n    global_counter++;\n}\n\nint run_client(std::string const& addr, long port,\n               long n1, long n2, long n3) {\n    const long m = 8192;\n    const long p = 70913;\n    const long r = 1;\n    const long L = 2;\n    NTL::zz_p::init(p);\n    FHEcontext context(m, p, r);\n    context.bitsPerLevel = 60;\n    buildModChain(context, L);\n    FHESecKey sk(context);\n    sk.GenSecKey(64);\n    auto start_time_stamp = std::clock();\n    auto last_time_stamp = std::clock();\n    int done = 0;\n    while (true) {\n        tcp::iostream conn(addr, std::to_string(port));\n        if (!conn) {\n            std::cerr << \"Can not connect to server!\" << std::endl;\n            return -1;\n        }\n\n        /// send FHEcontext obj\n        double all_time = 0.;\n        do {\n            send_context(conn, context);\n            AutoTimer time(&all_time);\n            // send the evaluation key\n            play_client(conn, sk, context, n1, n2, n3);\n        } while(0);\n        clt_ben.total_times.push_back(all_time);\n        conn.close();\n\t\tresetAllTimers(); // reset timers in HElib\n\n        ++done;\n        auto now_time = std::clock();\n        if (now_time - last_time_stamp >= 60 * CLOCKS_PER_SEC) {\n            std::cout << done << \"\\n\";\n            last_time_stamp = now_time;\n        }\n\n        if (now_time - start_time_stamp >= 3600 * CLOCKS_PER_SEC) {\n            /// one hour\n            break;\n        }\n    }\n    std::cout << \"one hour finished: \" << done << \"\\n\";\n    return 0;\n}\n\nint run_server(long port, long n1, long n2, long n3) {\n    boost::asio::io_service ios;\n    tcp::endpoint endpoint(tcp::v4(), port);\n    tcp::acceptor acceptor(ios, endpoint);\n    for (long run = 0; run < REPEAT; run++) {\n        tcp::iostream conn;\n        boost::system::error_code err;\n        acceptor.accept(*conn.rdbuf(), err);\n\n        if (!err) {\n\t\t\tSMPServer server;\n\t\t\tserver.run(conn, n1, n2, n3);\n\t\t\tresetAllTimers(); // reset timers in HElib\n        }\n    }\n\tSMPServer::print_statistics();\n    return 0;\n}\n\nint main(int argc, char *argv[]) {\n    ArgMapping argmap;\n    long role = -1;\n    long n1 = 8;\n    long n2 = 8;\n    long n3 = 8;\n    std::string addr = \"127.0.0.1\";\n\tlong port = 12345;\n    argmap.arg(\"N\", n1, \"n1\");\n    argmap.arg(\"M\", n2, \"n2\");\n    argmap.arg(\"D\", n3, \"n3\");\n    argmap.arg(\"R\", role, \"role. 0 for server and 1 for client\");\n\targmap.arg(\"a\", addr, \"server address\");\n\targmap.arg(\"p\", port, \"port\");\n    argmap.parse(argc, argv);\n    if (role == 0) {\n        run_server(port, n1, n2, n3);\n    } else if (role == 1) {\n        run_client(addr, port, n1, n2, n3);\n    } else {\n\t\targmap.usage(\"General Matrix Multiplication for |N*M| * |M*D|\");\n\t\treturn -1;\n\t}\n}\n", "meta": {"hexsha": "57664fb6c5a395d125915dad6e6a8689febfeef1", "size": 8716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SMP.cpp", "max_stars_repo_name": "Vampsj/SMP", "max_stars_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SMP.cpp", "max_issues_repo_name": "Vampsj/SMP", "max_issues_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SMP.cpp", "max_forks_repo_name": "Vampsj/SMP", "max_forks_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4836601307, "max_line_length": 82, "alphanum_fraction": 0.6003900872, "num_tokens": 2560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931457, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5264545433026238}}
{"text": "#include <NTL/ZZX.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\n\nvoid CharPolyMod(ZZX& gg, const ZZX& a, const ZZX& f, long deterministic)\n{\n   if (!IsOne(LeadCoeff(f)) || deg(f) < 1 || deg(a) >= deg(f))\n      Error(\"CharPolyMod: bad args\");\n\n\n   if (IsZero(a)) {\n      clear(gg);\n      SetCoeff(gg, deg(f));\n      return;\n   }\n\n   long bound = 2 + CharPolyBound(a, f);\n\n   long gp_cnt = 0;\n\n   zz_pBak bak;\n   bak.save();\n\n   ZZ_pBak bak1;\n   bak1.save();\n\n   ZZX g;\n   ZZ prod;\n\n   clear(g);\n   set(prod);\n\n   long i;\n\n   long instable = 1;\n\n   for (i = 0; ; i++) {\n      if (NumBits(prod) > bound)\n         break;\n\n      if (!deterministic &&\n          !instable && bound > 1000 && NumBits(prod) < 0.25*bound) {\n         long plen = 90 + NumBits(max(bound, MaxBits(g)));\n\n         ZZ P;\n\n         GenPrime(P, plen, 90 + 2*NumBits(gp_cnt++));\n\n         ZZ_p::init(P);\n         ZZ_pX G, A, F;\n         conv(A, a);\n         conv(F, f);\n         CharPolyMod(G, A, F);\n\n         if (CRT(g, prod, G))\n            instable = 1;\n         else\n            break;\n      }\n\n      zz_p::FFTInit(i);\n\n      zz_pX G, A, F;\n      conv(A, a);\n      conv(F, f);\n      CharPolyMod(G, A, F);\n      instable = CRT(g, prod, G);\n   }\n\n   gg = g;\n\n   bak.restore();\n   bak1.restore();\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "99c1bcdaac6e2f2746d50b6f34c9d1a81c150464", "size": 1277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/src/ZZXCharPoly.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-17T20:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T19:52:14.000Z", "max_issues_repo_path": "RUNETag/WinNTL/src/ZZXCharPoly.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/src/ZZXCharPoly.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 15.9625, "max_line_length": 73, "alphanum_fraction": 0.4815974941, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5264545433026238}}
{"text": "#pragma once\n\n#include <boost/numeric/odeint.hpp>\n\n#include \"eigenIntegration.hpp\"\n\n#include \"activeModel.hpp\"\n\nnamespace scpp::discretization\n{\n\ntemplate <bool INTERPOLATE_INPUT, bool VARIABLE_TIME>\nclass ODE\n{\nprivate:\n    Model::input_vector_t u_t0, u_t1;\n    double time;\n    double dt;\n    Model::ptr_t model;\n\npublic:\n    using ode_matrix_t = typename Eigen::Matrix<double, Model::state_dim,\n                                                1 + Model::state_dim + Model::input_dim +\n                                                    INTERPOLATE_INPUT * Model::input_dim +\n                                                    VARIABLE_TIME + 1>;\n\n    ODE(const Model::input_vector_t &u_t0,\n        const Model::input_vector_t &u_t1,\n        const double &time,\n        double dt,\n        Model::ptr_t model)\n        : u_t0(u_t0), u_t1(u_t1), time(time), dt(dt), model(model) {}\n\n    void operator()(const ode_matrix_t &V, ode_matrix_t &dVdt, const double t);\n};\n\ntemplate <bool INTERPOLATE_INPUT, bool VARIABLE_TIME>\nvoid ODE<INTERPOLATE_INPUT, VARIABLE_TIME>::operator()(const ode_matrix_t &V, ode_matrix_t &dVdt, const double t)\n{\n    const Model::state_vector_t x = V.col(0);\n\n    Model::input_vector_t u;\n    if constexpr (INTERPOLATE_INPUT)\n    {\n        u = u_t0 + t / dt * (u_t1 - u_t0);\n    }\n    else\n    {\n        u = u_t0;\n    }\n\n    Model::state_vector_t f;\n    Model::state_matrix_t A;\n    Model::control_matrix_t B;\n    model->computef(x, u, f);\n    model->computeJacobians(x, u, A, B);\n\n    if constexpr (VARIABLE_TIME)\n    {\n        A *= time;\n        B *= time;\n    }\n\n    const Model::state_matrix_t Phi_A_xi = V.template block<Model::state_dim, Model::state_dim>(0, 1);\n    const Model::state_matrix_t Phi_A_xi_inverse = Phi_A_xi.inverse();\n\n    size_t cols = 0;\n\n    // state\n    if constexpr (VARIABLE_TIME)\n    {\n        dVdt.template block<Model::state_dim, 1>(0, cols) = time * f;\n    }\n    else\n    {\n        dVdt.template block<Model::state_dim, 1>(0, cols) = f;\n    }\n    cols += 1;\n\n    // A\n    dVdt.template block<Model::state_dim, Model::state_dim>(0, cols).noalias() = A * Phi_A_xi;\n    cols += Model::state_dim;\n\n    if constexpr (INTERPOLATE_INPUT)\n    {\n        // B\n        const double alpha = (dt - t) / dt;\n        dVdt.template block<Model::state_dim, Model::input_dim>(0, cols).noalias() = Phi_A_xi_inverse * B * alpha;\n        cols += Model::input_dim;\n\n        // C\n        const double beta = t / dt;\n        dVdt.template block<Model::state_dim, Model::input_dim>(0, cols).noalias() = Phi_A_xi_inverse * B * beta;\n        cols += Model::input_dim;\n    }\n    else\n    {\n        // B\n        dVdt.template block<Model::state_dim, Model::input_dim>(0, cols).noalias() = Phi_A_xi_inverse * B;\n        cols += Model::input_dim;\n    }\n\n    if constexpr (VARIABLE_TIME)\n    {\n        // s\n        dVdt.template block<Model::state_dim, 1>(0, cols).noalias() = Phi_A_xi_inverse * f;\n        cols += 1;\n        // z\n        dVdt.template block<Model::state_dim, 1>(0, cols).noalias() = Phi_A_xi_inverse * (-A * x - B * u);\n        cols += 1;\n    }\n    else\n    {\n        // z\n        dVdt.template block<Model::state_dim, 1>(0, cols).noalias() = Phi_A_xi_inverse * (f - A * x - B * u);\n        cols += 1;\n    }\n\n    assert(cols == ode_matrix_t::ColsAtCompileTime);\n}\n\ntemplate <bool INTERPOLATE_INPUT, bool VARIABLE_TIME>\nvoid multipleShootingImplementation(\n    Model::ptr_t model,\n    trajectory_data_t &td,\n    discretization_data_t &dd)\n{\n    const size_t K = td.n_X();\n\n    using ODEFun = ODE<INTERPOLATE_INPUT, VARIABLE_TIME>;\n    using ode_matrix_t = typename ODEFun::ode_matrix_t;\n\n    double dt = 1. / double(K - 1);\n\n    if constexpr (not VARIABLE_TIME)\n    {\n        dt *= td.t;\n    }\n\n    using namespace boost::numeric::odeint;\n    runge_kutta_fehlberg78<ode_matrix_t, double, ode_matrix_t, double, vector_space_algebra> stepper;\n\n    for (size_t k = 0; k < K - 1; k++)\n    {\n        ode_matrix_t V;\n        V.col(0) = td.X.at(k);\n        V.template block<Model::state_dim, Model::state_dim>(0, 1).setIdentity();\n        V.template rightCols<ode_matrix_t::ColsAtCompileTime - 1 - Model::state_dim>().setZero();\n\n        const Model::input_vector_t u0 = td.U[k];\n        const Model::input_vector_t u1 = INTERPOLATE_INPUT ? td.U[k + 1] : u0;\n        ODEFun odeMultipleShooting(u0, u1, td.t, dt, model);\n\n        integrate_adaptive(stepper, odeMultipleShooting, V, 0., dt, dt / 5.);\n\n        size_t cols = 1;\n\n        dd.A[k] = V.template block<Model::state_dim, Model::state_dim>(0, cols);\n        cols += Model::state_dim;\n\n        dd.B[k].noalias() = dd.A[k] * V.template block<Model::state_dim, Model::input_dim>(0, cols);\n        cols += Model::input_dim;\n\n        if constexpr (INTERPOLATE_INPUT)\n        {\n            dd.C[k].noalias() = dd.A[k] * V.template block<Model::state_dim, Model::input_dim>(0, cols);\n            cols += Model::input_dim;\n        }\n\n        if constexpr (VARIABLE_TIME)\n        {\n            dd.s[k].noalias() = dd.A[k] * V.template block<Model::state_dim, 1>(0, cols);\n            cols += 1;\n        }\n\n        dd.z[k].noalias() = dd.A[k] * V.template block<Model::state_dim, 1>(0, cols);\n        cols += 1;\n\n        assert(cols == ode_matrix_t::ColsAtCompileTime);\n    }\n}\n\n} // namespace scpp::discretization", "meta": {"hexsha": "a1191c8e6d9db037e1326f474222ac3bdca229a8", "size": 5296, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "scpp_core/include/discretizationImplementation.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_core/include/discretizationImplementation.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_core/include/discretizationImplementation.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": 28.9398907104, "max_line_length": 114, "alphanum_fraction": 0.5898791541, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931457, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5264545375509894}}
{"text": "#ifndef CORE_OBJECT_HPP\n#define CORE_OBJECT_HPP\n\n#include \"material.hpp\"\n\n#include <math/ray3d.hpp>\n#include <shapes/intersection_info.hpp>\n#include <shapes/sphere.hpp>\n\n#include <boost/optional.hpp>\n\n#include <tuple>\n\nnamespace core\n{\n\nstruct object\n{\n  core::material material;\n  shapes::sphere shape;\n};\n\ninline bool operator==(object lhs, object rhs)\n{\n  return std::tie(lhs.material, lhs.shape)\n    == std::tie(rhs.material, rhs.shape);\n}\n\ninline bool operator!=(object lhs, object rhs)\n{\n  return !(lhs == rhs);\n}\n\ninline bool intersects(const object& obj, math::ray3d ray)\n{\n  return shapes::intersects(obj.shape, ray);\n}\n\ninline boost::optional<shapes::intersection_info> closest_intersection(const object& obj, math::ray3d ray)\n{\n  return shapes::closest_intersection(obj.shape, ray);\n}\n\n}\n\n#endif\n", "meta": {"hexsha": "cd941e0ec0645588aee75509990be9252e24d2fb", "size": 807, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/object.hpp", "max_stars_repo_name": "TiagoRabello/Path-Tracer", "max_stars_repo_head_hexsha": "1ad32741fdff0b8f48ef675e9071c1495cbcdde3", "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/core/object.hpp", "max_issues_repo_name": "TiagoRabello/Path-Tracer", "max_issues_repo_head_hexsha": "1ad32741fdff0b8f48ef675e9071c1495cbcdde3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-02-01T09:14:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-01T09:14:44.000Z", "max_forks_repo_path": "src/core/object.hpp", "max_forks_repo_name": "TiagoRabello/Path-Tracer", "max_forks_repo_head_hexsha": "1ad32741fdff0b8f48ef675e9071c1495cbcdde3", "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": 17.170212766, "max_line_length": 106, "alphanum_fraction": 0.7261462206, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5264545317993549}}
{"text": "#include <boost/random/extreme_value_distribution.hpp>\n", "meta": {"hexsha": "bcd320ced42417bd4e5273c850c0d6b049376148", "size": 55, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_extreme_value_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_extreme_value_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_extreme_value_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.5, "max_line_length": 54, "alphanum_fraction": 0.8545454545, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.526454530893256}}
{"text": "// TRENTO: Reduced Thickness Event-by-event Nuclear Topology\n// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland\n// TRENTO3D: Three-dimensional extension of TRENTO by Weiyao Ke\n// MIT License\n\n#include \"nucleon.h\"\n\n#include <cmath>\n#include <limits>\n#include <random>\n#include <stdexcept>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/expint.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include \"fwd_decl.h\"\n\nnamespace trento {\n\nnamespace {\n\n// Create ctor parameters for unit mean std::gamma_distribution.\n//   mean = alpha*beta == 1  ->  beta = 1/alpha\n// Used below in NucleonProfile ctor initializer list.\n\ntemplate <typename RealType> using param_type =\n  typename std::gamma_distribution<RealType>::param_type;\n\ntemplate <typename RealType>\nparam_type<RealType> gamma_param_unit_mean(RealType alpha = 1.) {\n  return param_type<RealType>{alpha, 1./alpha};\n}\n\n// These constants define distances in terms of the width of the nucleon profile\n// Gaussian thickness function.\n\n// Truncation radius of the thickness function.\nconstexpr double trunc_radius_widths = 5.;\n\n// Maximum impact parameter for participation.\nconstexpr double max_impact_widths = 6.;\n\n// Trivial helper function.\ntemplate <typename T>\nconstexpr T sqr(T value) {\n  return value * value;\n}\n\n// Inelastic nucleon-nucleon cross section as function of beam energy sqrt(s)\n// Fit coefficients explained in the docs.\ndouble cross_sec_from_energy(double sqrts) {\n  auto a = 3.1253;\n  auto b = 0.1280;\n  auto c = 2.0412;\n  auto d = 1.8231;\n  return a + b * pow(std::log(sqrts) - c, d);\n}\n\n// Determine the cross section parameter for sampling participants.\n// See section \"Fitting the cross section\" in the online docs.\ndouble compute_cross_sec_param(const VarMap& var_map) {\n  // Read parameters from the configuration.\n\n  // Use manual inelastic nucleon-nucleon cross section if specified.\n  // Otherwise default to extrapolated cross section.\n  auto sigma_nn = var_map[\"cross-section\"].as<double>();\n  if (sigma_nn < 0) {\n    sigma_nn = cross_sec_from_energy(var_map[\"beam-energy\"].as<double>());\n  }\n  auto width = var_map[\"nucleon-width\"].as<double>();\n\n  // Initialize arguments for boost root finding function.\n\n  // Bracket min and max.\n  auto a = -10.;\n  auto b = 20.;\n\n  // Tolerance function.\n  // Require 3/4 of double precision.\n  math::tools::eps_tolerance<double> tol{\n    (std::numeric_limits<double>::digits * 3) / 4};\n\n  // Maximum iterations.\n  // This is overkill -- in testing only 10-20 iterations were required\n  // (but no harm in overestimating).\n  boost::uintmax_t max_iter = 1000;\n\n  // The right-hand side of the equation.\n  auto rhs = sigma_nn / (4 * math::double_constants::pi * sqr(width));\n\n  // This quantity appears a couple times in the equation.\n  auto c = sqr(max_impact_widths) / 4;\n\n  try {\n    auto result = math::tools::toms748_solve(\n      [&rhs, &c](double x) {\n        using std::exp;\n        using math::expint;\n        return c - expint(-exp(x)) + expint(-exp(x-c)) - rhs;\n      },\n      a, b, tol, max_iter);\n\n    return .5*(result.first + result.second);\n  }\n  catch (const std::domain_error&) {\n    // Root finding fails for very small nucleon widths, w^2/sigma_nn < ~0.01.\n    throw std::domain_error{\n      \"unable to fit cross section -- nucleon width too small?\"};\n  }\n}\n\n}  // unnamed namespace\n\nNucleonProfile::NucleonProfile(const VarMap& var_map)\n    : width_sqr_(sqr(var_map[\"nucleon-width\"].as<double>())),\n      trunc_radius_sqr_(sqr(trunc_radius_widths)*width_sqr_),\n      max_impact_sqr_(sqr(max_impact_widths)*width_sqr_),\n      neg_one_div_two_width_sqr_(-.5/width_sqr_),\n\t  neg_one_div_four_width_sqr_(-.25/width_sqr_),\n\t  one_div_four_pi_(0.5*math::double_constants::one_div_two_pi),\n      cross_sec_param_(compute_cross_sec_param(var_map)),\n      fast_exp_(-.5*sqr(trunc_radius_widths), 0., 1000),\n      fluct_dist_(gamma_param_unit_mean(var_map[\"fluctuation\"].as<double>())),\n      prefactor_(math::double_constants::one_div_two_pi/width_sqr_),\n      with_ncoll_(var_map[\"ncoll\"].as<bool>())\n{}\n\n}  // namespace trento\n", "meta": {"hexsha": "b8b5ff9a00c0271d0823e604278cff3d81b1c3e6", "size": 4146, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/nucleon.cxx", "max_stars_repo_name": "keweiyao/trento", "max_stars_repo_head_hexsha": "996124a1b00031ee2a46bed22cb9ee3f7043a3aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-02T08:46:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-02T08:46:01.000Z", "max_issues_repo_path": "src/nucleon.cxx", "max_issues_repo_name": "K-JW/trento", "max_issues_repo_head_hexsha": "9f8f74add763ef95757f4d448d6e3f2e77ab54de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nucleon.cxx", "max_forks_repo_name": "K-JW/trento", "max_forks_repo_head_hexsha": "9f8f74add763ef95757f4d448d6e3f2e77ab54de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-10T16:32:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-10T16:32:08.000Z", "avg_line_length": 31.6488549618, "max_line_length": 80, "alphanum_fraction": 0.7120115774, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.526423644367557}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\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, EVecPRESS 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 <gtest/gtest.h>\n\n#include <Eigen/Core>\n\n#include \"smooth/feedback/ocp.hpp\"\n#include \"smooth/feedback/ocp_to_qp.hpp\"\n\ntemplate<typename T>\nusing X = Eigen::Vector<T, 2>;\n\ntemplate<typename T>\nusing U = Eigen::Vector<T, 1>;\n\ntemplate<typename T, std::size_t N>\nusing Vec = Eigen::Vector<T, N>;\n\nTEST(OcpToQp, Basic)\n{\n  const auto theta = []<typename T>(T, X<T>, X<T> xf, Vec<T, 1> q) -> T {\n    return xf.squaredNorm() + 2 * q.sum();\n  };\n\n  const auto f = []<typename T>(T, X<T> x, U<T> u) -> smooth::Tangent<X<T>> {\n    return {x.y(), u.x()};\n  };\n\n  const auto g = []<typename T>(T, X<T>, U<T> u) -> Vec<T, 1> {\n    return Vec<T, 1>{{u.x() * u.x()}};\n  };\n\n  const auto cr = []<typename T>(T, X<T>, U<T> u) -> Vec<T, 1> { return Vec<T, 1>{{u.x()}}; };\n\n  const auto ce = []<typename T>(T, X<T>, X<T> xf, Vec<T, 1>) -> Vec<T, 2> { return xf; };\n\n  smooth::feedback::\n    OCP<X<double>, U<double>, decltype(theta), decltype(f), decltype(g), decltype(cr), decltype(ce)>\n      ocp{\n        .theta = theta,\n        .f     = f,\n        .g     = g,\n        .cr    = cr,\n        .crl   = Eigen::VectorXd{{-1}},\n        .cru   = Eigen::VectorXd{{1}},\n        .ce    = ce,\n        .cel   = Eigen::Vector2d{-5, -5},\n        .ceu   = Eigen::Vector2d{5, 5},\n      };\n\n  smooth::feedback::Mesh<5, 5> mesh;\n  mesh.refine_ph(0, 10);\n\n  constexpr auto tf = 2.;\n\n  const auto xl_fun = []<typename T>(T t) -> X<T> { return X<T>{{0.05 * t * t, 0.1 * t}}; };\n\n  const auto ul_fun = []<typename T>(T) -> U<T> { return U<T>{{0.1}}; };\n\n  const auto qp = smooth::feedback::ocp_to_qp(ocp, mesh, tf, xl_fun, ul_fun);\n\n  ASSERT_EQ(qp.P.cols(), qp.q.size());\n  ASSERT_EQ(qp.P.rows(), qp.q.size());\n  ASSERT_EQ(qp.P.cols(), qp.A.cols());\n\n  ASSERT_EQ(qp.A.rows(), qp.l.size());\n  ASSERT_EQ(qp.A.rows(), qp.u.size());\n\n  // check that simple trajectory satisfies constraints\n\n  static constexpr double x0 = 3;\n  static constexpr double v0 = -0.3;\n  static constexpr double u0 = 0.1;\n\n  const auto xtraj = [](double t) {\n    return X<double>{{x0 + v0 * t + u0 * t * t / 2, v0 + u0 * t}};\n  };\n\n  Eigen::Matrix<double, 2, -1> Xvar(ocp.Nx, mesh.N_colloc() + 1);\n  Eigen::Matrix<double, 1, -1> Uvar(ocp.Nu, mesh.N_colloc());\n\n  for (const auto [i, t] : smooth::utils::zip(std::views::iota(0u), mesh.all_nodes())) {\n    Xvar.col(i) = xtraj(tf * t);\n    if (i < mesh.N_colloc()) { Uvar.col(i).setConstant(u0); }\n  }\n\n  Eigen::VectorXd var(Xvar.size() + Uvar.size());\n  var.head(Xvar.size()) = Xvar.reshaped();\n  var.tail(Uvar.size()) = Uvar.reshaped();\n\n  // check constraint satisfaction\n  ASSERT_GE((qp.A * var - qp.l).minCoeff(), -1e-8);\n  ASSERT_GE((qp.u - qp.A * var).minCoeff(), -1e-8);\n}\n", "meta": {"hexsha": "bd4734d367a092587219c9254c35b5b7772d0f8d", "size": 3957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_ocp_to_qp.cpp", "max_stars_repo_name": "tgurriet/smooth_feedback", "max_stars_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_stars_repo_licenses": ["MIT"], "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_ocp_to_qp.cpp", "max_issues_repo_name": "tgurriet/smooth_feedback", "max_issues_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_issues_repo_licenses": ["MIT"], "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_ocp_to_qp.cpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["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.5338983051, "max_line_length": 100, "alphanum_fraction": 0.6242102603, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5263385335052224}}
{"text": "#include <boost/math/common_factor_rt.hpp>\n", "meta": {"hexsha": "e48d890ff244e077902cc71743e4b0ee62631807", "size": 43, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_common_factor_rt.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_common_factor_rt.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_common_factor_rt.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 21.5, "max_line_length": 42, "alphanum_fraction": 0.8139534884, "num_tokens": 9, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.526338527483865}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nnamespace icarus {\n    template <typename T>\n    struct EllipsoidalCalibration\n    {\n        explicit EllipsoidalCalibration() :\n            mTransformation(Eigen::Matrix<float, 3, 4>::Identity())\n        {}\n\n        explicit EllipsoidalCalibration(Eigen::Matrix<T, 3, 4> const & transformation) :\n            mTransformation(transformation)\n        {}\n\n        void transformAxes(Eigen::Matrix<T, 3, 3> const & transform)\n        {\n            mTransformation.template block<3, 3>(0, 0) = transform * mTransformation.template block<3, 3>(0, 0);\n        }\n\n        void addOffset(Eigen::Matrix<T, 3, 1> const & offset)\n        {\n            mTransformation.col(3) += offset;\n        }\n\n        Eigen::Matrix<T, 3, 1> adjust(Eigen::Matrix<T, 3, 1> const & measurement) const\n        {\n            return mTransformation.template block<3, 3>(0, 0)\n                * (measurement + mTransformation.col(3));\n        }\n\n        Eigen::Matrix<T, 3, 4> const & transformation() const\n        {\n            return mTransformation;\n        }\n    private:\n        Eigen::Matrix<T, 3, 4> mTransformation;\n    };\n}\n", "meta": {"hexsha": "cad230887085ba5d26b5d85a3e51a753b98abf94", "size": 1141, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "icarus/include/icarus/sensor/EllipsoidalCalibration.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/EllipsoidalCalibration.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/EllipsoidalCalibration.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": 27.8292682927, "max_line_length": 112, "alphanum_fraction": 0.5687992989, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067222797121, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.526338522014979}}
{"text": "/** \\file ITL_Solver.h */\n\n#pragma once\n\n// MTL4 includes\n#include <boost/numeric/itl/krylov/bicg.hpp>\n#include <boost/numeric/itl/krylov/bicgstab_2.hpp>\n#include <boost/numeric/itl/krylov/bicgstab_ell.hpp>\n#include <boost/numeric/itl/krylov/bicgstab.hpp>\n#include <boost/numeric/itl/krylov/cg.hpp>\n#include <boost/numeric/itl/krylov/cgs.hpp>\n#include <boost/numeric/itl/krylov/gmres.hpp>\n#include <boost/numeric/itl/krylov/idr_s.hpp>\n#include <boost/numeric/itl/krylov/qmr.hpp>\n#include <boost/numeric/itl/krylov/tfqmr.hpp>\n\n// AMDiS includes\n#include \"MTL4Types.hpp\"\n#include \"solver/LinearSolver.hpp\"\n#include \"solver/ITL_Runner.hpp\"\n\n// more solvers defined in AMDiS\n#include \"solver/itl/minres.hpp\"\n#include \"solver/itl/gcr.hpp\"\n#include \"solver/itl/fgmres.hpp\"\n#include \"solver/itl/fgmres_householder.hpp\"\n#include \"solver/itl/gmres2.hpp\"\n#include \"solver/itl/gmres_householder.hpp\"\n#include \"solver/itl/preonly.hpp\"\n\n\nnamespace AMDiS\n{\n  /**\n   * \\ingroup Solver\n   *\n   * \\brief\n   * Wrapper for MTL4 itl-solvers.\n   *\n   * One of the following solvers can be chosen:\n   * - @ref CGSolver \"cg\" (conjugate gradient method)\n   * - @ref CGSSolver \"cgs\" (squared conjugate gradient method)\n   * - @ref BiCGSolver \"bicg\" (biconjugate gradient method)\n   * - @ref BiCGStabSolver \"bicgstab\" (stabilized BiCG method)\n   * - @ref BiCGStab2Solver \"bicgstab2\" (stabilized BiCG(l) method with l=2)\n   * - @ref QMRSolver \"qmr\" (Quasi-Minimal Residual method)\n   * - @ref TFQMRSolver \"tfqmr\" (Transposed-Free Quasi-Minimal Residual method)\n   * - @ref BiCGStabEllSolver \"bicgstab_ell\" (stabilized BiCG(l) method)\n   * - @ref GMResSolver \"gmres\" (generalized minimal residual method)\n   * - @ref IDRsSolver \"idr_s\" (Induced Dimension Reduction method)\n   * - @ref MinResSolver \"minres\" (minimal residual method)\n   * - @ref GcrSolver \"gcr\" (generalized conjugate residual method)\n   * - @ref FGMResSolver \"fgmres\" (flexible GMRes method)\n   * - @ref PreOnly \"preonly\" (solver that implements pure preconditioning applied to the rhs)\n   */\n  template <class SolverType>\n  using ITL_Solver = LinearSolver<\n    MTLTypes::MTLMatrix,\n    MTLTypes::MTLVector,\n    ITL_Runner<SolverType, MTLTypes::MTLMatrix, MTLTypes::MTLVector>>;\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::CGSolver\n   * \\brief ITL_Solver <\\ref cg_solver_type> implementation of conjugate gradient\n   * method \\implements ITL_Solver\n   *\n   * Solves a linear system \\f$ Ax=b \\f$ by the conjugate gradient method (CG)\n   * and can be used for symmetric positive definite system matrices.\n   * Right preconditioner is ignored.\n   */\n\n  class cg_solver_type\n  {\n  public:\n    cg_solver_type(std::string /*name*/) {}\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const& r, I& iter)\n    {\n      return itl::cg(A, x, b, l, r, iter);\n    }\n  };\n  using CGSolver = ITL_Solver<cg_solver_type>;\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::CGSSolver\n   * \\brief ITL_Solver <\\ref cgs_solver_type> implementation of squared conjugate\n   * gradient method \\implements ITL_Solver\n   *\n   * Solves a linear system \\f$ Ax=b \\f$ by the squared conjugate gradient method\n   * (CGS). Right preconditioner is ignored.\n   */\n\n  class cgs_solver_type\n  {\n  public:\n    cgs_solver_type(std::string /*name*/) {}\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const&, I& iter)\n    {\n      return itl::cgs(A, x, b, l, iter);\n    }\n  };\n  using CGSSolver = ITL_Solver<cgs_solver_type>;\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::BiCGSolver\n   * \\brief ITL_Solver <\\ref bicg_solver_type> implementation of bi-conjugate\n   * gradient method \\implements ITL_Solver\n   *\n   * Solves a linear system \\f$ Ax=b \\f$ by a BiCG method and can be used for\n   * system matrices.\n   */\n\n  class bicg_solver_type\n  {\n  public:\n    bicg_solver_type(std::string /*name*/) {}\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const&, I& iter)\n    {\n      return itl::bicg(A, x, b, l, iter);\n    }\n  };\n  using BiCGSolver = ITL_Solver<bicg_solver_type>;\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::BiCGStabSolver\n   * \\brief ITL_Solver <\\ref bicgstab_type> implementation of stabilized\n   * bi-conjugate gradient method \\implements ITL_Solver\n   *\n   * Solves a linear system \\f$ Ax=b \\f$ by a stabilized BiCG method and can be\n   * used for system matrices.\n   */\n\n  class bicgstab_type\n  {\n  public:\n    bicgstab_type(std::string /*name*/) {}\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const&, I& iter)\n    {\n      return itl::bicgstab(A, x, b, l, iter);\n    }\n  };\n  using BiCGStabSolver = ITL_Solver<bicgstab_type>;\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::BiCGStab2Solver\n   * \\brief ITL_Solver <\\ref bicgstab2_type> implementation of BiCGStab(l) method\n   * with l=2 \\implements ITL_Solver\n   *\n   * Solves a linear system \\f$ Ax=b \\f$ by a stabilized BiCG(2) method and can\n   * be used for system matrices.\n   */\n\n  class bicgstab2_type\n  {\n  public:\n    bicgstab2_type(std::string /*name*/) {}\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const&, I& iter)\n    {\n      return itl::bicgstab_2(A, x, b, l, iter);\n    }\n  };\n  using BiCGStab2Solver = ITL_Solver<bicgstab2_type>;\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::QMRSolver\n   * \\brief ITL_Solver <\\ref qmr_solver_type> implementation of Quasi-Minimal\n   * Residual method \\implements ITL_Solver\n   *\n   * Solves a linear system \\f$ Ax=b \\f$ by the Quasi-Minimal Residual method (QMR).\n   */\n\n  class qmr_solver_type\n  {\n  public:\n    qmr_solver_type(std::string /*name*/) {}\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const& r, I& iter)\n    {\n      return itl::qmr(A, x, b, l, r, iter);\n    }\n  };\n  using QMRSolver = ITL_Solver<qmr_solver_type>;\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::TFQMRSolver\n   * \\brief ITL_Solver <\\ref tfqmr_solver_type> implementation of Transposed-Free\n   * Quasi-Minimal Residual method \\implements ITL_Solver\n   *\n   * Solves a linear system by the Transposed-Free Quasi-Minimal Residual method\n   * (TFQMR). Does not use preconditioning currently.\n   */\n\n  class tfqmr_solver_type\n  {\n  public:\n    tfqmr_solver_type(std::string /*name*/) {}\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const& r, I& iter)\n    {\n      return itl::tfqmr(A, x, b, l, r, iter);\n    }\n  };\n  using TFQMRSolver = ITL_Solver<tfqmr_solver_type>;\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::BiCGStabEllSolver\n   * \\brief ITL_Solver <\\ref bicgstab_ell_type> implementation of stabilized\n   * BiCG(ell) method \\implements ITL_Solver\n   *\n   * Solves a linear system by a stabilized BiCG(ell) method and can be used for\n   * system matrices. The parameter ell [3] can be specified.\n   */\n\n  class bicgstab_ell_type\n  {\n    int ell;\n  public:\n    bicgstab_ell_type(std::string name) : ell(3)\n    {\n      Parameters::get(name + \"->ell\", ell);\n    }\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const& r, I& iter)\n    {\n      return itl::bicgstab_ell(A, x, b, l, r, iter, ell);\n    }\n  };\n  using BiCGStabEllSolver = ITL_Solver<bicgstab_ell_type>;\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::GMResSolver\n   * \\brief ITL_Solver <\\ref gmres_type> implementation of generalized minimal\n   * residual method \\implements ITL_Solver\n   *\n   * Solves a linear system by the GMRES method.\n   * The parameter restart [30] is the maximal number of orthogonalized vectors.\n   * The method is not preconditioned\n   */\n\n  enum ORTHOGONALIZATION\n  {\n    GRAM_SCHMIDT = 1,\n    HOUSEHOLDER = 2\n  };\n\n  class gmres_type\n  {\n    int restart;\n    int ortho;\n\n  public:\n    gmres_type(std::string name) : restart(30), ortho(GRAM_SCHMIDT)\n    {\n      Parameters::get(name + \"->restart\", restart);\n      Parameters::get(name + \"->orthogonalization\", ortho);\n    }\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const& r, I& iter)\n    {\n      switch ((ORTHOGONALIZATION)ortho)\n      {\n      default:\n      case GRAM_SCHMIDT:\n        return itl::gmres2(A, x, b, l, r, iter, restart);\n        break;\n#ifndef HAVE_PARALLEL_MTL4\n      case HOUSEHOLDER:\n        return itl::gmres_householder(A, x, b, l, iter, restart);\n        break;\n#endif\n      }\n    }\n  };\n  using GMResSolver = ITL_Solver<gmres_type>;\n\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::IDRsSolver\n   * \\brief ITL_Solver <\\ref idr_s_type> implementation of Induced Dimension\n   * Reduction method \\implements ITL_Solver\n   *\n   * Solves a linear system by an Induced Dimension Reduction method and can be\n   * used for system matrices.  The parameter s [30] can be specified.\n   *\n   * Peter Sonneveld and Martin B. van Gijzen, IDR(s): a family of simple and fast\n   * algorithms for solving large nonsymmetric linear systems.\n   * SIAM J. Sci. Comput. Vol. 31, No. 2, pp. 1035-1062 (2008). (copyright SIAM)\n   */\n\n  class idr_s_type\n  {\n    int s;\n  public:\n    idr_s_type(std::string name) : s(30)\n    {\n      Parameters::get(name + \"->s\", s);\n    }\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const& r, I& iter)\n    {\n      return itl::idr_s(A, x, b, l, r, iter, s);\n    }\n  };\n  using IDRsSolver = ITL_Solver<idr_s_type>;\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::MinResSolver\n   * \\brief ITL_Solver <\\ref minres_solver_type> implementation of minimal\n   * residual method \\implements ITL_Solver\n   *\n   * Solves a linear system by the Minres method. Can be used for symmetric\n   * indefinite systems.\n   */\n\n  class minres_solver_type\n  {\n  public:\n    minres_solver_type(std::string /*name*/) {}\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const& r, I& iter)\n    {\n      return itl::minres(A, x, b, l, r, iter);\n    }\n  };\n  using MinResSolver = ITL_Solver<minres_solver_type>;\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::GcrSolver\n   * \\brief ITL_Solver <\\ref gcr_type> implementation of generalized conjugate\n   * residual method \\implements ITL_Solver\n   *\n   * Solves a linear system by the GCR method - generalized conjugate residual\n   * method. The parameter restart [30] is the maximal number of orthogonalized\n   * vectors.\n   */\n\n  class gcr_type\n  {\n    int restart;\n\n  public:\n    gcr_type(std::string name) : restart(30)\n    {\n      Parameters::get(name + \"->restart\", restart);\n    }\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const& r, I& iter)\n    {\n      return itl::gcr(A, x, b, l, r, iter, restart);\n    }\n  };\n  using GcrSolver = ITL_Solver<gcr_type>;\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::FGMResSolver\n   * \\brief ITL_Solver <\\ref fgmres_type> implementation of flexible GMRes method\n   * \\implements ITL_Solver\n   *\n   * Solves a linear system by the FGMRES method.\n   * The parameter restart [30] is the maximal number of orthogonalized vectors.\n   * See reference \"A Flexible Inner-Outer Preconditiones GMRES Algorithm\",\n   * Youcef Saad, (1993)\n   */\n\n  class fgmres_type\n  {\n    int restart;\n    int orthogonalization;\n\n  public:\n    fgmres_type(std::string name) : restart(30), orthogonalization(GRAM_SCHMIDT)\n    {\n      Parameters::get(name + \"->restart\", restart);\n      Parameters::get(name + \"->orthogonalization\", orthogonalization);\n    }\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const& r, I& iter)\n    {\n      switch ((ORTHOGONALIZATION)orthogonalization)\n      {\n      default:\n      case GRAM_SCHMIDT:\n        return itl::fgmres(A, x, b, l, r, iter, restart);\n        break;\n#ifndef HAVE_PARALLEL_MTL4\n      case HOUSEHOLDER:\n        return itl::fgmres_householder(A, x, b, r, iter, restart);\n        break;\n#endif\n      }\n    }\n  };\n  using FGMResSolver = ITL_Solver<fgmres_type>;\n\n  // ===========================================================================\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::PreOnly\n   * \\brief ITL_Solver <\\ref preonly_type> implementation of preconditioner as\n   * \\implements ITL_Solver\n   *\n   * Solves a linear system by applying a preconditioner only.\n   */\n  class preonly_type\n  {\n  public:\n    preonly_type(std::string /*name*/) {}\n    template <class LinOp, class X, class B, class L, class R, class I>\n    int operator()(LinOp const& A, X& x, B const& b, L const& l, R const& /*r*/, I& iter)\n    {\n      return itl::preonly(A, x, b, l, iter);\n    }\n  };\n  using PreOnly = ITL_Solver<preonly_type>;\n\n  // ===========================================================================\n\n} // end namespace AMDiS\n", "meta": {"hexsha": "18c5a089df468787e5eee8422cd37e4da02f9b36", "size": 14452, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/ITL_Solver.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": "src/solver/ITL_Solver.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": "src/solver/ITL_Solver.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": 31.2138228942, "max_line_length": 94, "alphanum_fraction": 0.6001245502, "num_tokens": 4225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5263385105247356}}
{"text": "#include <lost.hpp>\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"LOST tests\"\n#include <boost/test/unit_test.hpp>\n\nboost::adjacency_list<boost::hash_setS, boost::vecS, boost::undirectedS> typedef graph;\n\nBOOST_AUTO_TEST_CASE( info_branch_test )\n{\n  // 0-1-2-3-4-5-6\n  //     |   |\n  //     7   9\n  //     |   |\n  //     8   10\n  graph T;\n  add_edge(0, 1, T);\n  add_edge(1, 2, T);\n  add_edge(2, 3, T);\n  add_edge(3, 4, T);\n  add_edge(4, 5, T);\n  add_edge(5, 6, T);\n  add_edge(2, 7, T);\n  add_edge(7, 8, T);\n  add_edge(4, 9, T);\n  add_edge(9, 10, T);\n  leaf_info<graph> info(T);\n  BOOST_CHECK( !info.is_path() );\n  for(int i = 0; i < 3; ++i)\n    BOOST_CHECK( info.on_branch(0, i) );\n  for(int i = 3; i < 11; ++i)\n    BOOST_CHECK( !info.on_branch(0, i) );\n}\n", "meta": {"hexsha": "621de980b06de851d3f5cb4bf0b1f8feb4c7f9fe", "size": 764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/lost_test.cpp", "max_stars_repo_name": "arekolek/MaxIST", "max_stars_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_stars_repo_licenses": ["MIT"], "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/lost_test.cpp", "max_issues_repo_name": "arekolek/MaxIST", "max_issues_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_issues_repo_licenses": ["MIT"], "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/lost_test.cpp", "max_forks_repo_name": "arekolek/MaxIST", "max_forks_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_forks_repo_licenses": ["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.1515151515, "max_line_length": 87, "alphanum_fraction": 0.5890052356, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5263385099722638}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@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_DETAIL_PRIMES_HPP\n#define CRYPTO3_DETAIL_PRIMES_HPP\n\n#include <boost/integer.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace detail {\n\n            template<int Bits>\n            struct all_ones {\n                typedef typename boost::uint_t<Bits>::least type;\n                static type const value = (all_ones<Bits - 1>::value << 1) | 1;\n            };\n            template<>\n            struct all_ones<0> {\n                typedef boost::uint_t<0>::least type;\n                static type const value = 0;\n            };\n\n            template<int Bits>\n            struct largest_prime;\n\n#define CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(B, D)                              \\\n    template<>                                                                         \\\n    struct largest_prime<B> {                                                          \\\n        constexpr static boost::uint_t<B>::least const value = all_ones<B>::value - D; \\\n    };                                                                                 \\\n    constexpr boost::uint_t<B>::least const largest_prime<B>::value;\n\n            // http://primes.utm.edu/lists/2small/0bit.html or\n            // http://www.research.att.com/~njas/sequences/A013603\n            // Though those offets are from 2**b; This code is offsets from 2**b-1\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(2, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(3, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(4, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(5, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(6, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(7, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(8, 4);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(9, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(10, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(11, 8);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(12, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(13, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(14, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(15, 18);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(16, 14);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(17, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(18, 4);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(19, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(20, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(21, 8);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(22, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(23, 14);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(24, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(25, 38);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(26, 4);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(27, 38);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(28, 56);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(29, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(30, 34);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(31, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(32, 4);\n\n        }    // namespace detail\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_HASH_DETAIL_PRIMES_HPP\n", "meta": {"hexsha": "1080b481ac96756da66f5fced2c7aa10d32aac67", "size": 4791, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/detail/primes.hpp", "max_stars_repo_name": "NilFoundation/crypto3-block", "max_stars_repo_head_hexsha": "94f9cc42ac0fa62c5ee54e7d678abf48ffa9eec5", "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": "include/nil/crypto3/detail/primes.hpp", "max_issues_repo_name": "tonlabs/crypto3-block", "max_issues_repo_head_hexsha": "d7eede022f6130797d28bc39eb312bff9afebf07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T23:11:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-16T18:04:20.000Z", "max_forks_repo_path": "include/nil/crypto3/detail/primes.hpp", "max_forks_repo_name": "tonlabs/crypto3-block", "max_forks_repo_head_hexsha": "d7eede022f6130797d28bc39eb312bff9afebf07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-11T15:37:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T21:47:05.000Z", "avg_line_length": 50.4315789474, "max_line_length": 88, "alphanum_fraction": 0.6351492382, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5263385045033779}}
{"text": "#include <gtest/gtest.h>\n#include \"pitts_multivector_tsqr.hpp\"\n#include \"pitts_multivector_random.hpp\"\n#include \"pitts_multivector.hpp\"\n#include \"pitts_multivector_eigen_adaptor.hpp\"\n#include \"pitts_tensor2.hpp\"\n#include \"pitts_tensor2_eigen_adaptor.hpp\"\n#include <Eigen/Dense>\n#include \"eigen_test_helper.hpp\"\n\n\nTEST(PITTS_MultiVector_tsqr, internal_HouseholderQR_applyReflection_inplace)\n{\n  constexpr auto eps = 1.e-8;\n  using Chunk = PITTS::Chunk<double>;\n  using MultiVector = PITTS::MultiVector<double>;\n\n  constexpr int n = 100;\n  constexpr int m = 5;\n\n  MultiVector X(n,m), X_ref(n,m);\n  randomize(X);\n  // copy X to X_ref\n  for(int i = 0; i < n; i++)\n    for(int j = 0; j < m; j++)\n      X_ref(i,j) = X(i,j);\n\n  MultiVector v(n,1);\n  randomize(v);\n  int col = 3;\n  int firstRow = 1;\n  constexpr int nChunks = 2;\n\n  // mak upper part of v zero\n  for(int i = (nChunks+firstRow+1)*Chunk::size; i < n; i++)\n    v(i,0) = 0;\n\n  PITTS::internal::HouseholderQR::applyReflection(nChunks, firstRow, col, &v.chunk(0,0), &X.chunk(0,0), X.colStrideChunks(), &X.chunk(0,0), X.colStrideChunks()); // memory layout ok because X is small enough\n\n  // calculate reference result with Eigen\n  auto mapX_ref = EigenMap(X_ref);\n  auto mapV = ConstEigenMap(v);\n\n  int offset = firstRow*Chunk::size;\n  int n_ = n - offset;\n  mapX_ref.block(offset, col, n_, 1) = (Eigen::MatrixXd::Identity(n_,n_) - mapV.bottomRows(n_) * mapV.bottomRows(n_).transpose()) * mapX_ref.block(offset, col, n_, 1);\n\n  ASSERT_NEAR(ConstEigenMap(X_ref), ConstEigenMap(X), eps);\n}\n\n\nTEST(PITTS_MultiVector_tsqr, internal_HouseholderQR_applyReflection_inplace_firstRow_bigger_nChunks)\n{\n  constexpr auto eps = 1.e-8;\n  using Chunk = PITTS::Chunk<double>;\n  using MultiVector = PITTS::MultiVector<double>;\n\n  constexpr int n = 100;\n  constexpr int m = 5;\n\n  MultiVector X(n,m), X_ref(n,m);\n  randomize(X);\n  // copy X to X_ref\n  for(int i = 0; i < n; i++)\n    for(int j = 0; j < m; j++)\n      X_ref(i,j) = X(i,j);\n\n  MultiVector v(n,1);\n  randomize(v);\n  int col = 3;\n  int firstRow = 2;\n  constexpr int nChunks = 1;\n\n  // mak upper part of v zero\n  for(int i = (nChunks+firstRow+1)*Chunk::size; i < n; i++)\n    v(i,0) = 0;\n\n  PITTS::internal::HouseholderQR::applyReflection(nChunks, firstRow, col, &v.chunk(0,0), &X.chunk(0,0), X.colStrideChunks(), &X.chunk(0,0), X.colStrideChunks()); // memory layout ok because X is small enough\n\n  // calculate reference result with Eigen\n  auto mapX_ref = EigenMap(X_ref);\n  auto mapV = ConstEigenMap(v);\n\n  int offset = firstRow*Chunk::size;\n  int n_ = n - offset;\n  mapX_ref.block(offset, col, n_, 1) = (Eigen::MatrixXd::Identity(n_,n_) - mapV.bottomRows(n_) * mapV.bottomRows(n_).transpose()) * mapX_ref.block(offset, col, n_, 1);\n\n  ASSERT_NEAR(ConstEigenMap(X_ref), ConstEigenMap(X), eps);\n}\n\n\nTEST(PITTS_MultiVector_tsqr, internal_HouseholderQR_applyReflection_out_of_place)\n{\n  constexpr auto eps = 1.e-8;\n  using Chunk = PITTS::Chunk<double>;\n  using MultiVector = PITTS::MultiVector<double>;\n\n  constexpr int n = 100;\n  constexpr int m = 5;\n\n  MultiVector X(n,m), X_ref(n,m), X_in(2*n,m);\n  randomize(X);\n  // copy X to X_ref\n  for(int i = 0; i < n; i++)\n    for(int j = 0; j < m; j++)\n      X_ref(i,j) = X(i,j);\n\n  MultiVector v(n,1);\n  randomize(v);\n  int col = 3;\n  int firstRow = 1;\n  constexpr int nChunks = 2;\n\n  // mak upper part of v zero\n  for(int i = (nChunks+firstRow+1)*Chunk::size; i < n; i++)\n    v(i,0) = 0;\n\n  // set parts of X that will be overwritten to just some number\n  for(int i = firstRow; i < nChunks; i++)\n    for(int j = 0; j < Chunk::size; j++)\n    {\n      X_in.chunk(i,col)[j] = X.chunk(i,col)[j];\n      X.chunk(i,col)[j] = 77.;\n    }\n\n\n  PITTS::internal::HouseholderQR::applyReflection(nChunks, firstRow, col, &v.chunk(0,0), &X_in.chunk(0,0), X_in.colStrideChunks(), &X.chunk(0,0), X.colStrideChunks()); // memory layout ok because X is small enough\n\n  // calculate reference result with Eigen\n  auto mapX_ref = EigenMap(X_ref);\n  auto mapV = ConstEigenMap(v);\n\n  int offset = firstRow*Chunk::size;\n  int n_ = n - offset;\n  mapX_ref.block(offset, col, n_, 1) = (Eigen::MatrixXd::Identity(n_,n_) - mapV.bottomRows(n_) * mapV.bottomRows(n_).transpose()) * mapX_ref.block(offset, col, n_, 1);\n\n  ASSERT_NEAR(ConstEigenMap(X_ref), ConstEigenMap(X), eps);\n}\n\n\nTEST(PITTS_MultiVector_tsqr, internal_HouseholderQR_applyReflection_out_of_place_firstRow_bigger_nChunks)\n{\n  constexpr auto eps = 1.e-8;\n  using Chunk = PITTS::Chunk<double>;\n  using MultiVector = PITTS::MultiVector<double>;\n\n  constexpr int n = 100;\n  constexpr int m = 5;\n\n  MultiVector X(n,m), X_ref(n,m), X_in(2*n,m);\n  randomize(X);\n  // copy X to X_ref\n  for(int i = 0; i < n; i++)\n    for(int j = 0; j < m; j++)\n      X_ref(i,j) = X(i,j);\n\n  MultiVector v(n,1);\n  randomize(v);\n  int col = 3;\n  int firstRow = 2;\n  constexpr int nChunks = 1;\n\n  // mak upper part of v zero\n  for(int i = (nChunks+firstRow+1)*Chunk::size; i < n; i++)\n    v(i,0) = 0;\n\n  // X_in is completely ignored as firstRow >= nChunks\n\n  PITTS::internal::HouseholderQR::applyReflection(nChunks, firstRow, col, &v.chunk(0,0), &X_in.chunk(0,0), X_in.colStrideChunks(), &X.chunk(0,0), X.colStrideChunks()); // memory layout ok because X is small enough\n\n  // calculate reference result with Eigen\n  auto mapX_ref = EigenMap(X_ref);\n  auto mapV = ConstEigenMap(v);\n\n  int offset = firstRow*Chunk::size;\n  int n_ = n - offset;\n  mapX_ref.block(offset, col, n_, 1) = (Eigen::MatrixXd::Identity(n_,n_) - mapV.bottomRows(n_) * mapV.bottomRows(n_).transpose()) * mapX_ref.block(offset, col, n_, 1);\n\n  ASSERT_NEAR(ConstEigenMap(X_ref), ConstEigenMap(X), eps);\n}\n\n\nTEST(PITTS_MultiVector_tsqr, internal_HouseholderQR_applyReflection2_inplace)\n{\n  constexpr auto eps = 1.e-8;\n  using Chunk = PITTS::Chunk<double>;\n  using MultiVector = PITTS::MultiVector<double>;\n\n  constexpr int n = 100;\n  constexpr int m = 5;\n\n  MultiVector X(n,m), X_ref(n,m);\n  randomize(X);\n  // copy X to X_ref\n  for(int i = 0; i < n; i++)\n    for(int j = 0; j < m; j++)\n      X_ref(i,j) = X(i,j);\n\n  MultiVector v(n,1);\n  randomize(v);\n  MultiVector w(n,1);\n  randomize(w);\n\n  int col = 3;\n  int firstRow = 1;\n  int nChunks = 2;\n\n  // calculate vTw\n  double vTw = 0;\n  for(int i = firstRow; i <= nChunks+firstRow; i++)\n    for(int j = 0; j < Chunk::size; j++)\n      vTw += v.chunk(i,0)[j] * w.chunk(i,0)[j];\n  Chunk vTw_chunk;\n  for(int i = 0; i < Chunk::size; i++)\n    vTw_chunk[i] = vTw;\n\n  PITTS::internal::HouseholderQR::applyReflection2(nChunks, firstRow, col, &w.chunk(0,0), &v.chunk(0,0), vTw_chunk, &X.chunk(0,0), X.colStrideChunks(), &X.chunk(0,0), X.colStrideChunks()); // memory layout ok because X is small enough\n\n  PITTS::internal::HouseholderQR::applyReflection(nChunks, firstRow, col, &w.chunk(0,0), &X_ref.chunk(0,0), X_ref.colStrideChunks(), &X_ref.chunk(0,0), X_ref.colStrideChunks());\n  PITTS::internal::HouseholderQR::applyReflection(nChunks, firstRow, col, &v.chunk(0,0), &X_ref.chunk(0,0), X_ref.colStrideChunks(), &X_ref.chunk(0,0), X_ref.colStrideChunks());\n\n  ASSERT_NEAR(ConstEigenMap(X_ref), ConstEigenMap(X), eps);\n}\n\n\nTEST(PITTS_MultiVector_tsqr, internal_HouseholderQR_applyReflection2_out_of_place)\n{\n  constexpr auto eps = 1.e-8;\n  using Chunk = PITTS::Chunk<double>;\n  using MultiVector = PITTS::MultiVector<double>;\n\n  constexpr int n = 100;\n  constexpr int m = 5;\n\n  MultiVector X(n,m), X_ref(n,m), X_in(2*n,m);\n  randomize(X);\n  // copy X to X_ref\n  for(int i = 0; i < n; i++)\n    for(int j = 0; j < m; j++)\n      X_ref(i,j) = X(i,j);\n\n  MultiVector v(n,1);\n  randomize(v);\n  MultiVector w(n,1);\n  randomize(w);\n\n  int col = 3;\n  int firstRow = 1;\n  int nChunks = 2;\n\n  // calculate vTw\n  double vTw = 0;\n  for(int i = firstRow; i <= nChunks+firstRow; i++)\n    for(int j = 0; j < Chunk::size; j++)\n      vTw += v.chunk(i,0)[j] * w.chunk(i,0)[j];\n  Chunk vTw_chunk;\n  for(int i = 0; i < Chunk::size; i++)\n    vTw_chunk[i] = vTw;\n\n\n  // set parts of X that will be overwritten to just some number\n  for(int i = firstRow; i < nChunks; i++)\n    for(int j = 0; j < Chunk::size; j++)\n    {\n      X_in.chunk(i,col)[j] = X.chunk(i,col)[j];\n      X.chunk(i,col)[j] = 77.;\n    }\n\n  PITTS::internal::HouseholderQR::applyReflection2(nChunks, firstRow, col, &w.chunk(0,0), &v.chunk(0,0), vTw_chunk, &X_in.chunk(0,0), X_in.colStrideChunks(), &X.chunk(0,0), X.colStrideChunks()); // memory layout ok because X is small enough\n\n  PITTS::internal::HouseholderQR::applyReflection(nChunks, firstRow, col, &w.chunk(0,0), &X_ref.chunk(0,0), X_ref.colStrideChunks(), &X_ref.chunk(0,0), X_ref.colStrideChunks());\n  PITTS::internal::HouseholderQR::applyReflection(nChunks, firstRow, col, &v.chunk(0,0), &X_ref.chunk(0,0), X_ref.colStrideChunks(), &X_ref.chunk(0,0), X_ref.colStrideChunks());\n\n  ASSERT_NEAR(ConstEigenMap(X_ref), ConstEigenMap(X), eps);\n}\n\n\nTEST(PITTS_MultiVector_tsqr, internal_HouseholderQR_transformBlock_inplace)\n{\n  constexpr auto eps = 1.e-8;\n  using Chunk = PITTS::Chunk<double>;\n  using MultiVector = PITTS::MultiVector<double>;\n\n  constexpr int n = 16*Chunk::size - 7;   // force padding, we need some extra space in transformBlock\n  constexpr int m = 19;\n  constexpr int mChunks = (m-1) / Chunk::size + 1;\n  constexpr int nTotalChunks = (n-1) / Chunk::size + 1;\n  constexpr int nChunks = nTotalChunks - mChunks;\n\n  MultiVector X(n,m), X_ref(n,m);\n  randomize(X);\n  // make lower triangular part zero...\n  for(int j = 0; j < m; j++)\n    for(int i = nChunks+j/Chunk::size+1; i < nTotalChunks; i++)\n      X.chunk(i,j) = Chunk{};\n  // copy X to X_ref\n  for(int i = 0; i < n; i++)\n    for(int j = 0; j < m; j++)\n      X_ref(i,j) = X(i,j);\n\n  PITTS::internal::HouseholderQR::transformBlock(nChunks, m, &X.chunk(0,0), X.colStrideChunks(), &X.chunk(0,0), X.colStrideChunks(), nChunks);\n\n  // check that the result is upper triangular\n  for(int i = 0; i < mChunks*Chunk::size; i++)\n  {\n    for(int j = 0; j < m; j++)\n    {\n      if( i > j )\n      {\n        ASSERT_NEAR(0., X(i,j), eps);\n      }\n    }\n  }\n\n  // use Eigen to check that the singular values and the right singular vectors are identical\n  auto mapX = ConstEigenMap(X);\n  auto mapX_ref = ConstEigenMap(X_ref);\n  //std::cout << \"X:\\n\" << mapX << std::endl;\n  Eigen::BDCSVD<Eigen::MatrixXd> svd(mapX.topRows(m), Eigen::ComputeThinV);\n  Eigen::BDCSVD<Eigen::MatrixXd> svd_ref(mapX_ref, Eigen::ComputeThinV);\n\n  ASSERT_NEAR(svd_ref.singularValues(), svd.singularValues(), eps);\n  // V can differ by sign, only consider absolute part\n  ASSERT_NEAR(svd_ref.matrixV().array().abs(), svd.matrixV().array().abs(), eps);\n}\n\n\nTEST(PITTS_MultiVector_tsqr, internal_HouseholderQR_transformBlock_out_of_place)\n{\n  constexpr auto eps = 1.e-8;\n  using Chunk = PITTS::Chunk<double>;\n  using MultiVector = PITTS::MultiVector<double>;\n\n  constexpr int n = 16*Chunk::size - 7;   // force padding, we need some extra space in transformBlock\n  constexpr int m = 19;\n  constexpr int mChunks = (m-1) / Chunk::size + 1;\n  constexpr int nTotalChunks = (n-1) / Chunk::size + 1;\n  constexpr int nChunks = nTotalChunks - mChunks;\n\n  MultiVector X(n,m), X_ref(n,m), Xresult(n+2*Chunk::size,m);\n  randomize(X);\n  randomize(Xresult);\n  // make lower triangular part zero...\n  for(int j = 0; j < m; j++)\n    for(int i = nChunks+j/Chunk::size+1; i < nTotalChunks; i++)\n      X.chunk(i,j) = Chunk{};\n  // copy X to X_ref\n  for(int i = 0; i < n; i++)\n    for(int j = 0; j < m; j++)\n      X_ref(i,j) = X(i,j);\n  // prepare lower part of result\n  for(int col = 0; col < m; col++)\n    for(int i = nChunks; i < nTotalChunks; i++)\n      for(int j = 0; j < Chunk::size; j++)\n      {\n        Xresult.chunk(2+i,col)[j] = X.chunk(i,col)[j];\n        X.chunk(i,col)[j] = 77;\n      }\n\n  PITTS::internal::HouseholderQR::transformBlock(nChunks, m, &X.chunk(0,0), X.colStrideChunks(), &Xresult.chunk(0,0), Xresult.colStrideChunks(), 2+nChunks);\n\n  // check that the result is upper triangular, copied to the bottom\n  for(int i = 0; i < n; i++)\n  {\n    for(int j = 0; j < m; j++)\n    {\n      if( i > nChunks*Chunk::size + j )\n      {\n        EXPECT_NEAR(0., Xresult(2*Chunk::size+i,j), eps);\n      }\n      // X shouldn't change\n      if( i < nChunks*Chunk::size )\n      {\n        ASSERT_EQ(X_ref(i,j), X(i,j));\n      }\n      else\n      {\n        ASSERT_EQ(77., X(i,j));\n      }\n    }\n  }\n\n  // use Eigen to check that the singular values and the right singular vectors are identical\n  auto mapXresult = ConstEigenMap(Xresult);\n  //std::cout << \"X:\\n\" << mapXresult << std::endl;\n  auto mapX_ref = ConstEigenMap(X_ref);\n  Eigen::BDCSVD<Eigen::MatrixXd> svd(mapXresult.bottomRows(n-nChunks*Chunk::size), Eigen::ComputeThinV);\n  Eigen::BDCSVD<Eigen::MatrixXd> svd_ref(mapX_ref, Eigen::ComputeThinV);\n\n  ASSERT_NEAR(svd_ref.singularValues(), svd.singularValues(), eps);\n  // V can differ by sign, only consider absolute part\n  ASSERT_NEAR(svd_ref.matrixV().array().abs(), svd.matrixV().array().abs(), eps);\n}\n\n\nTEST(PITTS_MultiVector_tsqr, internal_combineTwoBlocks)\n{\n  constexpr auto eps = 1.e-8;\n  using Chunk = PITTS::Chunk<double>;\n  using MultiVector = PITTS::MultiVector<double>;\n\n  MultiVector R1;\n  MultiVector R2;\n  for(int m = 1; m < 77; m+=7)\n  {\n    // implementation also works with non-triangular factors, so for simplicity just use random square blocks\n    R1.resize(m,m);\n    R2.resize(m,m);\n    randomize(R1);\n    randomize(R2);\n    // should both be upper triangular\n    for(int i = 0; i < m; i++)\n      for(int j = i+1; j < m; j++)\n        R1(j,i) = R2(j,i) = 0;\n\n    // we need buffers of correctly padded size...\n    const auto mChunks = (m-1) / Chunk::size + 1;\n    const int totalSize = int(mChunks*m*Chunk::size);\n    std::vector<Chunk> buff1(mChunks*m);\n    std::vector<Chunk> buff2(mChunks*m);\n\n    for(int j = 0; j < m; j++)\n    {\n      for(int i = 0; i < mChunks; i++)\n      {\n        buff1[i+j*mChunks] = R1.chunk(i,j);\n        buff2[i+j*mChunks] = R2.chunk(i,j);\n      }\n    }\n\n    MPI_Datatype mpi_double = MPI_DOUBLE;\n    PITTS::internal::HouseholderQR::combineTwoBlocks((const double*)(&(buff1[0][0])), &(buff2[0][0]), &totalSize, &mpi_double);\n\n    // compara singular values with Eigen\n    Eigen::MatrixXd R12(2*m,m);\n    R12.block(0,0,m,m) = ConstEigenMap(R1);\n    R12.block(m,0,m,m) = ConstEigenMap(R2);\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd_ref(R12);\n\n    Eigen::Map<Eigen::MatrixXd> result(&(buff2[0][0]), mChunks*Chunk::size, m);\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(result);\n\n    EXPECT_NEAR(svd_ref.singularValues(), svd.singularValues(), eps);\n  }\n}\n\n\nnamespace\n{\n  // helper function for testing block_TSQR with different data dimensions, etc\n  void test_block_TSQR(int n, int m)\n  {\n    constexpr auto eps = 1.e-8;\n    using Chunk = PITTS::Chunk<double>;\n    using MultiVector = PITTS::MultiVector<double>;\n    using Tensor2 = PITTS::Tensor2<double>;\n\n    MultiVector M(n,m);\n    randomize(M);\n\n    // store the original matrix for later\n    Eigen::MatrixXd M_ref = ConstEigenMap(M);\n\n    Tensor2 R;\n    block_TSQR(M, R, 4, false);\n    ASSERT_EQ(m, R.r1());\n    ASSERT_EQ(m, R.r2());\n    for(int j = 0; j < m; j++)\n    {\n      for(int i = j+1; i < m; i++)\n      {\n        ASSERT_NEAR(0., R(i,j), eps);\n      }\n    }\n\n    // check that the singular values and right singular vectors match...\n    Eigen::BDCSVD<Eigen::MatrixXd> svd(PITTS::ConstEigenMap(R), Eigen::ComputeThinV);\n    Eigen::BDCSVD<Eigen::MatrixXd> svd_ref(M_ref, Eigen::ComputeThinV);\n\n    ASSERT_NEAR(svd_ref.singularValues(), svd.singularValues(), eps);\n    // V can differ by sign, only consider absolute part\n    ASSERT_NEAR(svd_ref.matrixV().array().abs(), svd.matrixV().array().abs(), eps);\n  }\n\n  // helper function to determine the currently default number of threads in a parallel region\n  int get_default_num_threads()\n  {\n    int numThreads = 1;\n#pragma omp parallel\n    {\n#pragma omp critical (PITTS_TEST_MULTIVECTOR_TSQR)\n      numThreads = omp_get_num_threads();\n    }\n    return numThreads;\n  }\n}\n\nTEST(PITTS_MultiVector_tsqr, block_TSQR_small_serial)\n{\n  int nThreads = get_default_num_threads();\n\n  omp_set_num_threads(1);\n  test_block_TSQR(50, 10);\n  omp_set_num_threads(nThreads);\n}\n\n\nTEST(PITTS_MultiVector_tsqr, block_TSQR_small_4threads)\n{\n  int nThreads = get_default_num_threads();\n\n  ASSERT_LE(4, omp_get_max_threads());\n  omp_set_num_threads(4);\n\n  test_block_TSQR(50, 10);\n\n  omp_set_num_threads(nThreads);\n}\n\n\nTEST(PITTS_MultiVector_tsqr, block_TSQR_large_serial)\n{\n  int nThreads = get_default_num_threads();\n\n  omp_set_num_threads(1);\n  test_block_TSQR(200, 30);\n  omp_set_num_threads(nThreads);\n}\n\n\nTEST(PITTS_MultiVector_tsqr, block_TSQR_large_varying_sizes_serial)\n{\n  int nThreads = get_default_num_threads();\n\n  omp_set_num_threads(1);\n  for(int m = 1; m < 30; m++)\n  {\n    std::cout << \"Testing #cols = \" << m << \"\\n\";\n    test_block_TSQR(250, m);\n  }\n  omp_set_num_threads(nThreads);\n}\n\n\n\nTEST(PITTS_MultiVector_tsqr, block_TSQR_large_parallel)\n{\n  test_block_TSQR(200, 30);\n}\n\n\nTEST(PITTS_MultiVector_tsqr, block_TSQR_manyRows_differentNumbersOfThreads)\n{\n  int nThreads = get_default_num_threads();\n\n  ASSERT_LE(4, omp_get_max_threads());\n  for(int iThreads = 1; iThreads < 5; iThreads++)\n  {\n    omp_set_num_threads(iThreads);\n    test_block_TSQR(1000, 1);\n  }\n  omp_set_num_threads(nThreads);\n}\n\n\nTEST(PITTS_MultiVector_tsqr, block_TSQR_mpiGlobal)\n{\n  constexpr auto eps = 1.e-8;\n  using Chunk = PITTS::Chunk<double>;\n  using MultiVector = PITTS::MultiVector<double>;\n  using Tensor2 = PITTS::Tensor2<double>;\n\n  const long long nTotal = 500;\n  const long long m = 4;\n\n  const auto& [iProc,nProcs] = PITTS::internal::parallel::mpiProcInfo();\n  const auto& [nFirst,nLast] = PITTS::internal::parallel::distribute(nTotal, {iProc,nProcs});\n  const long long n = nLast - nFirst + 1;\n\n  Eigen::MatrixXd Mglobal = Eigen::MatrixXd::Random(nTotal, 4);\n  MPI_Bcast(Mglobal.data(), nTotal*m, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\n  MultiVector M(n,m);\n  {\n    auto mapM = EigenMap(M);\n    mapM = Mglobal.block(nFirst,0,n,m);\n  }\n\n  Tensor2 R;\n  block_TSQR(M, R);\n  ASSERT_EQ(m, R.r1());\n  ASSERT_EQ(m, R.r2());\n  for(int j = 0; j < m; j++)\n  {\n    for(int i = j+1; i < m; i++)\n    {\n      ASSERT_NEAR(0., R(i,j), eps);\n    }\n  }\n\n  // check that the singular values and right singular vectors match...\n  Eigen::BDCSVD<Eigen::MatrixXd> svd(ConstEigenMap(R), Eigen::ComputeThinV);\n  Eigen::BDCSVD<Eigen::MatrixXd> svd_ref(Mglobal, Eigen::ComputeThinV);\n\n  ASSERT_NEAR(svd_ref.singularValues(), svd.singularValues(), eps);\n  // V can differ by sign, only consider absolute part\n  ASSERT_NEAR(svd_ref.matrixV().array().abs(), svd.matrixV().array().abs(), eps);\n}\n", "meta": {"hexsha": "b653e6f6f00b2f1bd0e9f65c624f86944b21fc8b", "size": 18570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_multivector_tsqr.cpp", "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": "test/test_multivector_tsqr.cpp", "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": "test/test_multivector_tsqr.cpp", "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": 30.4926108374, "max_line_length": 240, "alphanum_fraction": 0.6549811524, "num_tokens": 5886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5263385045033778}}
{"text": "/*\n * Copyright (c) 2013-2015 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef LP_HPP\n#define LP_HPP\n\n#include <stdexcept>\n#include <list>\n#include <limits>\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\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\ntemplate <class T> inline T lp_minimize(ub::vector<T>& objfunc, std::list< ub::vector<T> >& constraints)\n{\n\tint i, j;\n\tint m = constraints.size();\n\tint lp_n = objfunc.size() - 1;\n\tint n = lp_n + m;\n\tint pivot_i, pivot_j;\n\tT tmp, minmax;\n\ttypename std::list< ub::vector<T> >::iterator p;\n\n\tub::matrix<T> a(m+1, n+1);\n\n\ta(0, 0) = objfunc(0);\n\n\tfor (i=1; i<n+1; i++) {\n\t\tif (i <= lp_n) a(0, i) = -objfunc(i);\n\t\telse a(0, i) = 0.;\n\t}\n\n\tp = constraints.begin();\n\tfor (i=0; i<m; i++) {\n\t\tif ((*p)[0] > 0) {\n\t\t\tthrow std::domain_error(\"lp_minimize: constraints sign error\");\n\t\t}\n\t\ta(i+1, 0) = -(*p)[0];\n\t\tfor (j=1; j<=lp_n; j++) {\n\t\t\tif (j < (*p).size()) a(i+1, j) = (*p)[j];\n\t\t\telse a(i+1, j) = 0.;\n\t\t}\n\t\tfor (j=0; j<m; j++) {\n\t\t\ta(i+1, lp_n+j+1) = (i == j) ? 1 : 0;\n\t\t}\n\t\tp++;\n\t}\n\n\tub::vector<bool> isbasic(n+1);\n\tfor (i=0; i<lp_n+1; i++) isbasic(i) = false;\n\tfor (i=0; i<m; i++) isbasic(lp_n+i+1) = true;\n\n\tub::vector<int> basic(m+1);\n\tfor (i=0; i<m; i++) basic(i+1) = lp_n+i+1;\n\t\n\twhile (true) {\n\t\tpivot_j = -1;\n\t\tminmax = 0.;\n\t\tfor (i=1; i<n+1; i++) {\n\t\t\tif (isbasic(i)) continue;\n\t\t\tif (a(0, i) > minmax) {\n\t\t\t\tpivot_j = i;\n\t\t\t\tminmax = a(0, i);\n\t\t\t}\n\t\t}\n\t\tif (pivot_j == -1) break;\n\n\t\tpivot_i = -1;\n\t\tminmax = std::numeric_limits<T>::max();\n\t\tfor (i=1; i<m+1; i++) {\n\t\t\tif (a(i, pivot_j) <= 0.) continue;\n\t\t\ttmp = a(i, 0) / a(i, pivot_j);\n\t\t\tif (tmp < minmax) {\n\t\t\t\tminmax = tmp;\n\t\t\t\tpivot_i = i;\n\t\t\t}\n\t\t}\n\t\tif (pivot_i == -1) {\n\t\t\tthrow std::domain_error(\"lp_minimize: no optimal solution\");\n\t\t}\n\n\t\tisbasic(basic(pivot_i)) = false;\n\t\tisbasic(pivot_j) = true;\n\t\tbasic(pivot_i) = pivot_j;\n\n\t\ttmp = a(pivot_i, pivot_j);\n\t\tfor (i=0; i<n+1; i++) {\n\t\t\tif (isbasic(i)) {\n\t\t\t\tif (i == pivot_j) a(pivot_i, i) = 1.;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ta(pivot_i, i) /= tmp;\n\t\t}\n\n\t\tfor (i=0; i<m+1; i++) {\n\t\t\tif (i == pivot_i) continue;\n\t\t\ttmp = a(i, pivot_j);\n\t\t\tfor (j=0; j<n+1; j++) {\n\t\t\t\tif (isbasic(j)) {\n\t\t\t\t\tif (j == pivot_j) a(i, j) = 0.;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ta(i, j) -= a(pivot_i, j) * tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn a(0, 0);\n}\n\ntemplate <class T> inline T lp_minimize_verified(ub::vector<T>& objfunc, std::list< ub::vector<T> >& constraints, int round)\n{\n\tint i, j;\n\tint m = constraints.size();\n\tint lp_n = objfunc.size() - 1;\n\tint n = lp_n + m;\n\tint pivot_i, pivot_j;\n\tT tmp, minmax;\n\ttypename std::list< ub::vector<T> >::iterator p;\n\tinterval<T> Itmp, Imin;\n\n\tub::matrix<T> a(m+1, n+1);\n\tub::matrix< interval<T> > Ia(m+1, n+1);\n\n\ta(0, 0) = objfunc(0);\n\n\tfor (i=1; i<n+1; i++) {\n\t\tif (i <= lp_n) a(0, i) = -objfunc(i);\n\t\telse a(0, i) = 0.;\n\t}\n\n\tp = constraints.begin();\n\tfor (i=0; i<m; i++) {\n\t\tif ((*p)[0] > 0) {\n\t\t\tthrow std::domain_error(\"lp_minimize: constraints sign error\");\n\t\t}\n\t\ta(i+1, 0) = -(*p)[0];\n\t\tfor (j=1; j<=lp_n; j++) {\n\t\t\tif (j < (*p).size()) a(i+1, j) = (*p)[j];\n\t\t\telse a(i+1, j) = 0.;\n\t\t}\n\t\tfor (j=0; j<m; j++) {\n\t\t\ta(i+1, lp_n+j+1) = (i == j) ? 1 : 0;\n\t\t}\n\t\tp++;\n\t}\n\n\tub::vector<bool> isbasic(n+1);\n\tfor (i=0; i<lp_n+1; i++) isbasic(i) = false;\n\tfor (i=0; i<m; i++) isbasic(lp_n+i+1) = true;\n\n\tub::vector<int> basic(m+1);\n\tfor (i=0; i<m; i++) basic(i+1) = lp_n+i+1;\n\t\n\twhile (true) {\n\t\tpivot_j = -1;\n\t\tminmax = 0.;\n\t\tfor (i=1; i<n+1; i++) {\n\t\t\tif (isbasic(i)) continue;\n\t\t\tif (a(0, i) > minmax) {\n\t\t\t\tpivot_j = i;\n\t\t\t\tminmax = a(0, i);\n\t\t\t}\n\t\t}\n\t\tif (pivot_j == -1) break;\n\n\t\tpivot_i = -1;\n\t\tminmax = std::numeric_limits<T>::max();\n\t\tfor (i=1; i<m+1; i++) {\n\t\t\tif (a(i, pivot_j) <= 0.) continue;\n\t\t\ttmp = a(i, 0) / a(i, pivot_j);\n\t\t\tif (tmp < minmax) {\n\t\t\t\tminmax = tmp;\n\t\t\t\tpivot_i = i;\n\t\t\t}\n\t\t}\n\t\tif (pivot_i == -1) {\n\t\t\tthrow std::domain_error(\"lp_minimize: no optimal solution\");\n\t\t}\n\n\t\tImin = (interval<T>)a(pivot_i, 0) / a(pivot_i, pivot_j);\n\n\t\tfor (i=1; i<m+1; i++) {\n\t\t\tif (a(i, pivot_j) <= 0.) continue;\n\t\t\tif (i == pivot_i) {continue;}\n\t\t\tif (round == -1) {\n\t\t\t\twhile (true) {\n\t\t\t\t\tItmp = (interval<T>)a(i, 0) / a(i, pivot_j);\n\t\t\t\t\tif (Imin.upper() < Itmp.lower()) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// succ\n\t\t\t\t\ta(i, 0) = ((interval<T>)a(i, 0) + std::numeric_limits<T>::denorm_min()).upper();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tItmp = (interval<T>)a(i, 0) / a(i, pivot_j);\n\t\t\t\twhile (true) {\n\t\t\t\t\tif (Imin.upper() < Itmp.lower()) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// pred\n\t\t\t\t\ta(pivot_i, 0) = ((interval<T>)a(pivot_i, 0) - std::numeric_limits<T>::denorm_min()).lower();\n\n\t\t\t\t\tImin = (interval<T>)a(pivot_i, 0) / a(pivot_i, pivot_j);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tisbasic(basic(pivot_i)) = false;\n\t\tisbasic(pivot_j) = true;\n\t\tbasic(pivot_i) = pivot_j;\n\n\t\tItmp = a(pivot_i, pivot_j);\n\t\tfor (i=0; i<n+1; i++) {\n\t\t\tif (isbasic(i)) {\n\t\t\t\tif (i == pivot_j) a(pivot_i, i) = 1.;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tIa(pivot_i, i) = a(pivot_i, i) / Itmp;\n\t\t}\n\n\t\tfor (i=0; i<m+1; i++) {\n\t\t\tif (i == pivot_i) continue;\n\t\t\tItmp = a(i, pivot_j);\n\t\t\tfor (j=0; j<n+1; j++) {\n\t\t\t\tif (isbasic(j)) {\n\t\t\t\t\tif (j == pivot_j) a(i, j) = 0.;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tIa(i, j) = a(i, j) - Ia(pivot_i, j) * Itmp;\n\t\t\t}\n\t\t}\n\n\t\tfor (i=0; i<n+1; i++) {\n\t\t\tif (isbasic(i)) continue;\n\t\t\tif ((i == 0) ^ (round == 1))  {\n\t\t\t\ta(pivot_i, i) = Ia(pivot_i, i).upper();\n\t\t\t} else {\n\t\t\t\ta(pivot_i, i) = Ia(pivot_i, i).lower();\n\t\t\t}\n\t\t}\n\t\tfor (i=0; i<m+1; i++) {\n\t\t\tif (i == pivot_i) continue;\n\t\t\tfor (j=0; j<n+1; j++) {\n\t\t\t\tif (isbasic(j)) continue;\n\t\t\t\tif ((j == 0) ^ (round == 1) ^ (i == 0))  {\n\t\t\t\t\ta(i, j) = Ia(i, j).upper();\n\t\t\t\t} else {\n\t\t\t\t\ta(i, j) = Ia(i, j).lower();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn a(0, 0);\n}\n\n} // namespace kv\n\n#endif // LP_HPP\n", "meta": {"hexsha": "4c56e82b38ff75d29d9231b24261044268d09319", "size": 5729, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/lp.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/lp.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/lp.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": 21.3768656716, "max_line_length": 124, "alphanum_fraction": 0.5072438471, "num_tokens": 2365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5263384995869635}}
{"text": "/*\n * This file belongs to the Galois project, a C++ library for exploiting\n * parallelism. The code is being released under the terms of the 3-Clause BSD\n * License (a copy is located in LICENSE.txt at the top-level directory).\n *\n * Copyright (C) 2018, The University of Texas at Austin. All rights reserved.\n * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS\n * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF\n * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF\n * DEALING OR USAGE OF TRADE.  NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH\n * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances\n * shall University be liable for incidental, special, indirect, direct or\n * consequential damages or loss of profits, interruption of business, or\n * related expenses which may arise from use of Software or Documentation,\n * including but not limited to those resulting from defects in Software and/or\n * Documentation, or loss or inaccuracy of data of any kind.\n */\n\n#include <boost/rational.hpp>\n\n#include <random>\n#include <iostream>\n\n#include <cstdio>\n\nusing Rational = boost::rational<size_t>;\n\nvoid multiplyTest(const double mpcand, const double mplier, const double ans) {\n\n  double lim = mplier / 100.0;\n  assert(lim >= 1.0);\n\n  std::mt19937 eng;\n  eng.seed(0);\n\n  std::uniform_real_distribution<double> dist(0.0, lim);\n\n  double remainMplier = mplier;\n\n  double computed = 0.0;\n\n  while (remainMplier > 0.0) {\n\n    double partial = dist(eng);\n\n    if (partial > remainMplier) {\n      partial = remainMplier;\n    }\n\n    remainMplier -= partial;\n\n    computed += mpcand * partial;\n  }\n\n  std::printf(\"Error in multiplication with doubles = %g\\n\", (ans - computed));\n}\n\nvoid multiplyTestRational(const Rational& mpcand, const Rational& mplier,\n                          const Rational& ans) {\n\n  size_t lim = boost::rational_cast<size_t>(mplier / Rational(100));\n\n  std::mt19937 eng;\n  eng.seed(0);\n\n  std::uniform_int_distribution<size_t> dist(1, lim);\n\n  Rational remainMplier = mplier;\n\n  Rational computed(0);\n\n  while (remainMplier > Rational(0)) {\n\n    Rational partial(dist(eng), lim);\n\n    if (partial > remainMplier) {\n      partial = remainMplier;\n    }\n\n    // std::cout << \"Rational partial mpcand: \" << partial << std::endl;\n\n    remainMplier -= partial;\n\n    computed += mpcand * partial;\n  }\n\n  std::cout << \"Error in multiplication with Rational: \" << (ans - computed)\n            << std::endl;\n}\n\nvoid rationalConversionError(double fpVal) {\n\n  static const unsigned SIGNIFICANT_BITS = 40;\n\n  size_t q = (size_t(1) << SIGNIFICANT_BITS);\n  size_t p = size_t(fpVal * q);\n\n  Rational r(p, q);\n\n  std::printf(\"Conversion error = %g\\n\",\n              (fpVal - boost::rational_cast<double>(r)));\n}\n\nint main() {\n  multiplyTest(0.125, 1000.0, 125.0);\n\n  multiplyTestRational(Rational(125, 1000), Rational(1000), Rational(125));\n\n  rationalConversionError(boost::rational_cast<double>(Rational(1, 3)));\n\n  rationalConversionError(sqrt(2.0));\n  rationalConversionError(sqrt(3.0));\n  rationalConversionError(sqrt(1000.0));\n  rationalConversionError(sqrt(100000.0));\n  rationalConversionError(sqrt(15485867)); // prime number\n\n  return 0;\n}\n", "meta": {"hexsha": "f6ead19272cda08f4bc6653721bb2e561ad9f1ba", "size": 3320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libgalois/test/floatingPointErrors.cpp", "max_stars_repo_name": "lineagech/Galois", "max_stars_repo_head_hexsha": "5c7c0abaf7253cb354e35a3836147a960a37ad5b", "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": "libgalois/test/floatingPointErrors.cpp", "max_issues_repo_name": "lineagech/Galois", "max_issues_repo_head_hexsha": "5c7c0abaf7253cb354e35a3836147a960a37ad5b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libgalois/test/floatingPointErrors.cpp", "max_forks_repo_name": "lineagech/Galois", "max_forks_repo_head_hexsha": "5c7c0abaf7253cb354e35a3836147a960a37ad5b", "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.6666666667, "max_line_length": 79, "alphanum_fraction": 0.7018072289, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.526338499034492}}
{"text": "/*! \\file MeshPointsMPI.hpp\n  \\brief Generates grids for parallel simulations\n  \\author Elad Steinberg\n */\n\n#ifndef MESHPOINTSMPI_HPP\n#define MESHPOINTSMPI_HPP 1\n#ifdef RICH_MPI\n#define _USE_MATH_DEFINES\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include \"../tessellation/ConvexHull.hpp\"\n#include \"../tessellation/VoronoiMesh.hpp\"\n#include \"../misc/utils.hpp\"\n\n/*!\n\\brief Creates a cartesian mesh for MPI\n\\param nx The total number of point in the x direction\n\\param ny The total number of point in the y direction\n\\param tess The tessellation of the processors\n\\param lower_left Lower left point\n\\param upper_right Upper right point\n\\return The set of points corresponding to the local process\n*/\nvector<Vector2D> SquareMeshM(int nx,int ny,Tessellation const& tess,\n\t\t\t     Vector2D const& lower_left,\n\t\t\t     Vector2D const& upper_right);\n\n/*!\n  \\brief Generates a round grid with constant point density\n  \\param PointNum The number of points.\n  \\param Rmin The min radius\n  \\param Rmax The max radius\n  \\param bottomleft The lower left corner of a boundaing box to cut off the circle\n  \\param topright The top right corner of a boundaing box to cut off the circle\n  \\param tess The tessellation of the processors\n  \\param xc X of circle center\n  \\param yc Y of circle center\n  \\return List of two dimensional points\n*/\nvector<Vector2D> CirclePointsRmaxM(int PointNum,double Rmin,double Rmax,\n\tVector2D const& bottomleft,Vector2D const& topright,\n\tTessellation const& tess,double xc=0,double yc=0);\n/*!\n  \\brief Generates a round grid with r^alpha point density\n  \\param PointNum The number of points.\n  \\param Rmin The min radius\n  \\param Rmax The max radius\n  \\param xc X of circle center\n  \\param yc Y of circle center\n  \\param alpha The point density, should not be -1 or -2\n  \\param tess The tessellation of the processors\n  \\return List of two dimensional points\n*/\nvector<Vector2D> CirclePointsRmax_aM(int PointNum,double Rmin,double Rmax,\n\tdouble xc,double yc,double alpha,Tessellation const& tess);\n\n/*!\n  \\brief Creates a circle of evenly spaced points\n  \\param point_number Number of points along the circumference\n  \\param radius Radius of the circle\n  \\param center Position of the center of the circle\n  \\param tproc The tessellation of the processors\n  \\return List of two dimensional points\n*/\nvector<Vector2D> circle_circumferenceM(int point_number,double radius,\n\tVector2D const& center,Tessellation const& tproc);\n\n/*!\n\\brief Creates a uniform random mesh for MPI\n\\param npoints The total number of point\n\\param tess The tessellation of the processors\n\\param lowerleft The lower left point of the domain\n\\param upperright The upper right point of the domain\n\\return The set of points corresponding to the local process\n*/\nvector<Vector2D> RandSquare(int npoints,Tessellation const& tess,\n\tVector2D const& lowerleft,Vector2D const& upperright);\n\n#endif\n#endif //MESHPOINTSMPI_HPP\n", "meta": {"hexsha": "06666826c9031a32b7a35f2a425957097d821b8c", "size": 2957, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/mpi/MeshPointsMPI.hpp", "max_stars_repo_name": "GalaxyHunters/Vivid", "max_stars_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "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": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/mpi/MeshPointsMPI.hpp", "max_issues_repo_name": "GalaxyHunters/Vivid", "max_issues_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T18:13:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T14:54:04.000Z", "max_forks_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/mpi/MeshPointsMPI.hpp", "max_forks_repo_name": "GalaxyHunters/Vivid", "max_forks_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-29T09:39:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-25T19:17:49.000Z", "avg_line_length": 36.0609756098, "max_line_length": 82, "alphanum_fraction": 0.7771389922, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5263384875442483}}
{"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 <boost/math/special_functions/gamma.hpp>\n#include \"metro/rBF.hpp\"\n\nnamespace metro {\n\tnamespace {\n\t\t// compute the log of the density of the Dirichlet-multinomial distribution.\n\t\t// See http://en.wikipedia.org/wiki/Dirichlet-multinomial_distribution\n\t\ttemplate< typename Row1, typename Row2 >\n\t\tdouble log_dirichlet_multinomial( Row1 const& counts, Row2 const& lambdas ) {\n\t\t\tusing boost::math::lgamma ;\n\t\t\tdouble result = 0.0 ;\n\t\t\tif( lambdas.maxCoeff() > 0 ) {\n\t\t\t\tresult\n\t\t\t\t\t+= lgamma( lambdas.sum() )\n\t\t\t\t\t- lgamma( ( lambdas + counts ).sum() )\n\t\t\t\t;\n\t\t\t}\n\n\t\t\tfor( int i = 0; i < counts.size(); ++i ) {\n\t\t\t\tif( lambdas(i) > 0 ) {\n\t\t\t\t\tresult += lgamma( lambdas(i) + counts(i) ) - lgamma( lambdas(i) ) ;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result ;\n\t\t}\n\t}\n\n\tdouble compute_rBF( Eigen::MatrixXd const& counts, double const lambda ) {\n\t\tdouble const n = counts.sum() ;\n\t\tEigen::RowVectorXd const colSums = counts.colwise().sum() ;\n\t\tEigen::RowVectorXd const lambdas = lambda * colSums / n ;\n\t\treturn std::exp(\n\t\t\tlog_dirichlet_multinomial( counts.row(0), lambdas )\n\t\t\t+ log_dirichlet_multinomial( counts.row(1), lambdas )\n\t\t\t- log_dirichlet_multinomial( colSums, lambdas )\n\t\t) ;\n\t}\n}\n\n", "meta": {"hexsha": "281992f22e103532097f59ba69eb4616380bbc79", "size": 1397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metro/src/rBF.cpp", "max_stars_repo_name": "gavinband/bingwa", "max_stars_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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/src/rBF.cpp", "max_issues_repo_name": "gavinband/bingwa", "max_issues_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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/src/rBF.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": 30.3695652174, "max_line_length": 79, "alphanum_fraction": 0.6585540444, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5263092213644454}}
{"text": "//Code for project 5 in FYS4150\n//Made by Ingvild, Hanne and Ola\n//No copyrights or copywrongs, but still inspired by the work of Morten H. Jensen from project 4.\n//Thanks to the one and only Jostein for discussions, help and inspiration.\n//Also thanks to H\u00e5kon for late night studies.\n//Most importantly the and the introuduction of [stepnum-2] and [1] for boundary calculations.\n//No elegant coding implemented here, a lot of brute force. Sorry for that, but it still gives us OK results in reasonable time\n//IMPORTANT: For reasonable results in 1D periodic, you need to have armadillo version later than 4.600!! \n\n\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <time.h>\n//#include <armadillo> //Comment out when working from forskningsparken where no armadillo is to be found\n#include <cmath>\n#include \"project5header.h\"\n\nusing namespace std;\n//using namespace arma; //Comment out when working from forskningsparken where no armadillo is to be found\n\n//Initializing file objects for 1D and 2D;\nofstream ofile;\n\nint main(int argc, char *argv[])\n{\n\n    //------------------------------------ Start up stuff -----------------------------------------------//\n\n    //Declearing some global variables\n    double dx, delta_time, initialtime, finaltime;\n    int dimension, option;\n    char* outfilename;\n\n    // Read in output file, abort if there are too few command-line arguments\n    if ( argc <= 1 ){cout << \"Bad Usage: \" << argv[0] << \" read also output file on same line \" << endl;}\n    else {outfilename=argv[1];}\n\n    //Opening file\n    ofile.open(outfilename);\n\n    //Read inputs, at set up inital psi and vorticity\n    read_input(dx, delta_time, finaltime, initialtime, dimension, option, argv);\n\n    //Set time equal to initialtime\n    double time = initialtime;\n\n    //calculating number of stepshttps://www.tvedestrandsposten.no/\n    int stepnum = (int) ((1/dx) + 1);\n\n    //allocates memory for psi and vorticity and some vectors needed in tridiagonal function.\n    double *psi = new double[stepnum]; //Stream function array\n    double *vorticity = new double[stepnum]; //Vorticity array\n    double *e1 = new double[stepnum]; //upper diagonal\n    double *d = new double[stepnum]; //mid diagonal\n    double *e2 = new double[stepnum]; //lower diagonal\n    double *force = new double[stepnum]; //forcing term in tridiagonal algo\n    double *first_vorticity = new double [stepnum]; //vorticity vector for centered difference 1D\n    double **temp_vorticity2D = new double* [stepnum]; //vorticity vector for 2D forward difference.\n    double **psi2D = new double* [stepnum]; //2D psi\n    double **vorticity2D = new double* [stepnum]; //2D vorticity\n    double **first_vorticity2D = new double* [stepnum]; //2D temporarly vorticity used in centered diff\n    double **psi2D_temp = new double* [stepnum]; //2D temporarly psi used in iterative solver\n\n\n    //initializes the psi and vorticity arrays.\n    if(dimension == 1){initialize(psi, vorticity, stepnum, option, dx);}\n    if(dimension == 2){initialize2D(psi2D,vorticity2D,stepnum,dx, option);}\n\n    //Initialize the temporary arrays\n    first_vorticity = vorticity;\n    psi2D_temp = psi2D;\n\n    //initializing the force 1D array\n    for(int i = 0; i < (stepnum); i++){force[i] = vorticity[i]*dx*dx;}\n\n    //precalculating constants needed in the different schemes.\n    //Named in honour of ourselves, and jostein.\n    //Sorry about this, but alpha, beta etc. doesn't make it any better, just less fun.\n    double ola = delta_time/(2*dx);\n    double ingvild = delta_time/(dx);\n    double hanne = 4*(dx*dx); //since dx = dy\n    double jostein = dx*dx;\n    double jostein2 = jostein*jostein;\n\n\n    //-------------------------------------- Calculations and write to file  ---------------------------//\n\n    while(time < finaltime){\n\n        //One dimension\n        if(dimension == 1){\n\n        //write to file\n        output(psi,vorticity,stepnum);\n\n        //Calculate next step with forward or centered method. Comment in/out the one you want\n        //forward_diff_solidb(psi, vorticity, stepnum, ola);\n        center_diff_solidb(psi,vorticity, first_vorticity, stepnum, ingvild, ola, time);\n        //forward_diff_periodicb(psi,vorticity,stepnum,ola);\n        //center_diff_periodicb(psi,vorticity, first_vorticity, stepnum, ingvild, ola, time);\n\n        //update the force 1D array\n        for(int i = 0; i < (stepnum); i++){force[i] = vorticity[i]*dx*dx;}\n\n        //Reuse project 1 code or armadillo (periodic case) to calculate psi, comment in/out the one you want.\n        tridiagonal_solidb(psi, force, e1, e2, d, dx, stepnum);\n        //tridiagonal_periodicb(psi, force, e1, e2, d, dx, stepnum);\n\t//Armadillo_1D_periodic_solver(psi,force,stepnum);\n\n        }//end 1D\n\n\n        //Two dimensions\n        if(dimension == 2){\n\n        //Write to file\n        output2d(psi2D, vorticity2D, stepnum);\n\n        //Calculate next time step vorticity\n        centered_diff_solidb_2D(psi2D,vorticity2D,first_vorticity2D,stepnum,ingvild,ola,time);\n\n        //Iterative Jacobi solver to find psi next time step\n        Jacobi_Iterative_solidb_2D(psi2D,psi2D_temp,vorticity2D,stepnum,jostein,hanne,jostein2);\n\n        }\n\n        //adds a time step\n        time += delta_time;\n\n    }\n\n    cout << \"great success\"<< endl;\n\n  return 0;\n\n}//end main\n\n\n//----------------------------------- 1D Functions -----------------------------------------------------//\n\nvoid read_input(double& dx, double& delta_time, double& finaltime, double& initialtime,int& dimension, int& option, char* argv[]){\n\n        //reading in variables\n        dx = atof(argv[2]);\n        delta_time = atof(argv[3]);\n        initialtime = atof(argv[4]);\n        finaltime = atof(argv[5]);\n        dimension = atof(argv[6]);\n        option = atoi(argv[7]);\n\n}\n\nvoid initialize(double*& psi, double*& vorticity, int stepnum, int option, double dx){\n\n    //Setting up initial values for psi and vorticity (option = 1 ---> sine)\n    if(option == 1){\n        for(int i = 0; i < stepnum; i++ ){\n\n            psi[i] = sin(4*M_PI*i*dx);\n            vorticity[i] = -16*M_PI*M_PI*cos(4*M_PI*i*dx);\n\n        }//end for\n    }//end if\n\n    //Setting up initial values for psi and vorticity (option = 2 --> exp)\n    if(option == 2){\n        for(int i = 0; i < stepnum; i++){\n\n            psi[i] = exp(-(pow(((dx*i - 0.5)/0.1),2)));\n            vorticity[i] = exp(-100*(-0.5 + dx*i)*(-0.5 + dx*i))*(9800. - 40000*dx*i + 40000.*(dx*i*dx*i)); //wolframalpha\n\n        }\n    }\n}\n\nvoid output(double*& psi, double*& vorticity, int stepnum){\n\n    ofile << setiosflags(ios::showpoint | ios::uppercase);\n\n    for(int i = 0; i < stepnum; i++){\n\n        ofile << setw(15) << setprecision(8) << psi[i];\n        ofile << setw(15) << setprecision(8) << vorticity[i] << endl;\n    }\n\n\n}\n\nvoid tridiagonal_solidb(double*& psi, double*& force, double*& e1, double*& e2, double*& d, double dx, int stepnum){\n\n\n    //Initializing our matrix and the forcing term.\n    for(int i = 0 ; i < stepnum; i++){\n\n        e1[i] = 1.0;\n        e2[i] = 1.0;\n        d[i] = -2.0;\n\n\n    }//end for\n\n    //Declare x_n and the endpoints\n    psi[stepnum-1] = 0.0;\n    psi[0] = 0.0;\n\n    //Forward substitution algorithm\n    for(int i = 2; i < stepnum ; i++){\n\n         //initializing dtilde\n         d[i] -= (e1[i]*e2[i-1])/d[i-1];\n\n         //initializing ytilde\n         force[i] -= ((e1[i])*(force[i-1]))/d[i-1];\n\n\n    }//end for\n\n\n    //Backward substitution with ytilde and dtilde\n    for(int i = (stepnum-2); i >= 1; i--){\n\n        psi[i] = (force[i] - (e2[i]*(psi[i+1])))/d[i];\n\n    }//end for\n\n\n}\n\nvoid forward_diff_solidb(double*& psi, double*& vorticity, int stepnum, double ola){\n\n\n    //Set the boundary conditions for solid walls (just to be sure!)\n    psi[0] = 0;\n    psi[stepnum-1] = 0;\n\n    //loop over all interior points\n    for(int i = 1; i < (stepnum-1); i++){\n\n    double temp_vorticity = vorticity[i];\n    double temp_psi1    = psi[i+1];\n    double temp_psi2    = psi[i-1];\n\n    vorticity[i] = temp_vorticity + (temp_psi2 - temp_psi1)*ola;\n\n    }//end for\n\n\n\n}\n\nvoid center_diff_solidb(double*& psi, double*& vorticity, double*& first_vorticity, int stepnum, double ingvild, double ola, double time){\n\n    //Calculate forward on first step\n    if(time == 0){\n\n    //Update first_vorticity\n    first_vorticity = vorticity;\n\n    //Calculate first time step with loop over all points except boundary points\n    for(int i = 1; i < (stepnum-1); i++){\n\n    double temp_vorticity = vorticity[i];\n    double temp_psi1    = psi[i+1];\n    double temp_psi2    = psi[i-1];\n\n    vorticity[i] = temp_vorticity + (temp_psi2 - temp_psi1)*ola;\n\n    }\n    }\n\n    //Centered on next steps\n    if(time != 0){\n\n    //Calculate first time step with loop over all points except boundary points\n    for(int i = 1; i < (stepnum-1); i++){\n\n    //Decleare and initialize some temporare variables\n    double temp_first_vorticity = first_vorticity[i];\n    double temp_psi1    = psi[i+1];\n    double temp_psi2    = psi[i-1];\n\n    //Update first_vorticity\n    first_vorticity = vorticity;\n\n    //Calculate new vorticity\n    vorticity[i] = temp_first_vorticity + (temp_psi2 - temp_psi1)*ingvild;\n\n    }\n\n    }//end for\n\n}\n\nvoid forward_diff_periodicb(double* psi, double* vorticity, int stepnum, double ola){\n\t\n    //Saving some temporary values\n    double temp_vorticity0 = vorticity[0];\n    double temp_vorticity_end = vorticity[stepnum - 1];\n\n    //loop over all interior points\n    for(int i = 1; i < (stepnum-1); i++){\n\n        //Save some temporary variables\n        double temp_vorticity = vorticity[i];\n        double temp_psi1    = psi[i+1];\n        double temp_psi2    = psi[i-1];\n\n        //Calculate vorticity at next timestep\n        vorticity[i] = temp_vorticity + (temp_psi2 - temp_psi1)*ola;\n\n\n    }//end for\n\n    //Calculating boundary values\n    vorticity[0] = temp_vorticity0 + (psi[stepnum - 2] - psi[1])*ola;\n    vorticity[stepnum - 1] = vorticity[0];\n\n}\n\nvoid center_diff_periodicb(double*& psi, double*& vorticity, double*& first_vorticity, int stepnum, double ingvild, double ola, double time){\n\n    //Calculate forward on first step\n    if(time == 0){\n\n    //Save some temporary variables\n    double temp_vorticity0 = vorticity[0];\n    double temp_vorticity_end = vorticity[stepnum - 1];\n\n\n    //Calculate first time step with loop over all points except boundary points\n    for(int i = 1; i < (stepnum-1); i++){\n\n    double temp_vorticity = vorticity[i];\n    double temp_psi1    = psi[i+1];\n    double temp_psi2    = psi[i-1];\n\n    vorticity[i] = temp_vorticity + (temp_psi2 - temp_psi1)*ola;\n\n    }\n\n    //Calculating boundary values\n    vorticity[0] = temp_vorticity0 + (psi[stepnum-2] - psi[1])*ola;\n    vorticity[stepnum - 1] = vorticity[0];\n\n    }\n\n    //Centered on next steps\n    if(time != 0){\n\n    //Calculate next time step with loop over all points except boundary points\n    for(int i = 1; i < (stepnum-1); i++){\n\n    //Decleare and initialize some temporare variables\n    double temp_first_vorticity = first_vorticity[i];\n    double temp_psi1    = psi[i+1];\n    double temp_psi2    = psi[i-1];\n\n    //Savce current vorticity\n    first_vorticity = vorticity;\n\n    //Calculate new vorticity\n    vorticity[i] = temp_first_vorticity + (temp_psi2 - temp_psi1)*ingvild;\n\n    }\n\n    //Calculating boundary values\n    vorticity[0] = first_vorticity[0] + (psi[stepnum-2] - psi[1])*ingvild;\n    vorticity[stepnum - 1] = first_vorticity[stepnum-1] + (psi[stepnum - 2] - psi[1])*ingvild;\n\n    }//end else\n\n\n\n\n}\n\nvoid tridiagonal_periodicb(double*& psi, double*& force, double*& e1, double*& e2, double*& d, double dx, int stepnum){\n\n\n    //Initializing our matrix and the forcing term.\n    for(int i = 0 ; i < stepnum; i++){\n\n        e1[i] = 1.0;\n        e2[i] = 1.0;\n        d[i] = -2.0;\n\n\n    }//end for\n\n    //Calculating lower endpoint dtile and ytilde explicit with periodic boundary conditions (The Jostein condition: stepnum - 2 = much better )\n    d[0] -= (e1[0]*e2[stepnum-2])/d[stepnum-2];\n    force[0] -= ((e1[stepnum-2])*(force[stepnum-2]))/d[stepnum-2];\n\n    //Forward substitution algorithm\n    for(int i = 1; i < stepnum ; i++){\n\n         //initializing dtilde\n         d[i] -= (e1[i]*e2[i-1])/d[i-1];\n\n         //initializing ytilde\n         force[i] -= ((e1[i])*(force[i-1]))/d[i-1];\n\n\n    }//end for\n\n    //Calculating upper endpoint explicit with periodic jostein boundary conditions\n    //error arises from psi[1] which is taken from timestep n and not n+1.\n    psi[stepnum-1] = (force[stepnum-1] - (e2[stepnum-2]*(psi[1])))/d[stepnum-2];\n\n\n    //Backward substitution with ytilde and dtilde\n    for(int i = (stepnum-2); i >= 0; i--){\n\n        psi[i] = (force[i] - (e2[i]*(psi[i+1])))/d[i];\n\n    }//end for\n\n    //prints the error using the modified jostein method\n    cout << \"error\" << fabs(psi[0] - psi[stepnum-1]) << endl;\n}\n\n//Comment out due to no armadillo in forskningsparken\n/*void Armadillo_1D_periodic_solver(double*& psi, double*& force, int stepnum){\n    \n    //initializing vectors and matrix\n    vec psivec(stepnum);\n    vec forcevec(stepnum-1);\n    vec dvec(stepnum-1, fill::ones);\n    vec evec(stepnum-2, fill::ones);\n    mat A(stepnum-1, stepnum-1, fill::zeros);\n    \n    //for loop to convert force from array to armadillo vectors\n    for(int i = 0; i < (stepnum-1); i++){\n        \n        forcevec(i) = -force[i];\n        \n    }//end for\n    \n    //Initializing our matrix and the forcing term.  \n    A.diag() = 2*dvec;\n    A.diag(1)= -evec;\n    A.diag(-1)= -evec;\n    A(0,stepnum-2) = -1;\n    A(stepnum-2,0) = -1;\n\n    //Solve system with armadillo-function\n    vec solution = solve(A, forcevec);\n\t\n\tfor(int i=0; i<stepnum-1;i++) {\n\t\tpsi[i] = solution(i);\n    }\n\n\tpsi[stepnum-1] = solution(0);\n\n}//end function\n\n*/\n//----------------------------------- 2D functions -----------------------------------------------------//\n\nvoid initialize2D(double **&psi2D, double **&vorticity2D, int stepnum, double dx, int option){\n\n    psi2D = new double*[stepnum];\n    vorticity2D = new double*[stepnum];\n\n    if(option == 1){\t\n    for(int j = 0; j < stepnum; j++){\n\n        psi2D[j] = new double[stepnum];\n        vorticity2D[j] = new double[stepnum];\n\t\n        for(int i = 0; i < stepnum; i++){\n\n\n                psi2D[j][i] = sin(M_PI*j*dx)*sin(4*M_PI*i*dx);  //Assumed a periodicity in y direction as well\n                vorticity2D[j][i] = -(17)*M_PI*M_PI*sin(M_PI*j*dx)*sin(4*M_PI*i*dx); //Vorticity = second derivative of psi.\n\t\t\n                if((i==0)|| (j==0)){\n\n                    psi2D[j][i] = 0.0;\n                    vorticity2D[j][i] = 0.0;\n                }\n        }//end i\n    }//end j\n    }//end option 1\n\n\n    if(option == 2){\n    for(int j = 0; j < stepnum; j++){\n\n        psi2D[j] = new double[stepnum];\n        vorticity2D[j] = new double[stepnum];\n\t\n        for(int i = 0; i < stepnum; i++){\n\n\n                psi2D[j][i] = exp(-(pow(((dx*i - 0.5)/0.1),2)))*(exp(-(pow(((dx*j - 0.5)/0.1),2)))); //Assume exp in y dir as well\n                vorticity2D[j][i] = exp(-100*(-0.5 + i*dx)*(-0.5 + i*dx) - 100*(-0.5 + j*dx)*(-0.5 + j*dx))*(19600. - 40000.*i*dx + 40000.*(i*dx)*(i*dx) - 40000.*(j*dx) + 40000.*(j*dx)*(j*dx)); //Vorticity = second derivative of psi.\n\t\t\n                if((i==0)||(j==0)){\n\n                    psi2D[j][i] = 0.0;\n                    vorticity2D[j][i] = 0.0;\n\n                }\n\n\n\n        }//end i\n    }//end j\n    }//end option 2\n\n\n}\n\nvoid output2d(double**& psi2D, double**& vorticity2D, int stepnum){\n\n    for(int j = 0; j < stepnum; j++){\n\n        //Writes the psi and vorticity to each file\n        for(int i = 0; i < stepnum; i++){\n        ofile << ' ' << psi2D[j][i];\n        }\n        ofile << endl;\n    }\n\n\n}\n\nvoid forward_diff_solidb_2D(double** psi2D, double** vorticity2D, int stepnum, double ola){\n\n    for(int j = 0; j<stepnum; j++){\n\n        //Set the boundary conditions for solid walls (just to be sure!)\n        psi2D[j][0] = 0;\n        psi2D[j][stepnum-1] = 0;\n\n        //loop over all interior points\n        for(int i = 1; i < (stepnum-1); i++){\n\n        double temp_vorticity = vorticity2D[j][i];\n        double temp_psi1    = psi2D[j][i+1];\n        double temp_psi2    = psi2D[j][i-1];\n\n        vorticity2D[j][i] = temp_vorticity + (temp_psi2 - temp_psi1)*ola;\n\n        }//end for col\n\n    }//end for rows\n\n}\n\nvoid centered_diff_solidb_2D(double**& psi2D, double**& vorticity2D, double**& first_vorticity2D, int stepnum, double ingvild, double ola, double time){\n\n//forward solution in the first step\nif (time == 0){\n\t\n    first_vorticity2D = vorticity2D;\n\n    for(int j = 0; j<stepnum; j++){\n\n    //Set the boundary conditions for solid walls (just to be sure!)\n    psi2D[j][0] = 0;\n    psi2D[j][stepnum-1] = 0;\n\n    //loop over all interior points\n    for(int i = 1; i < (stepnum-1); i++){\n\n    double temp_vorticity = vorticity2D[j][i];\n    double temp_psi1    = psi2D[j][i+1];\n    double temp_psi2    = psi2D[j][i-1];\n\n    vorticity2D[j][i] = temp_vorticity + (temp_psi2 - temp_psi1)*ola;\n    }//end for i\n    }//end for j\n}//end if time == 0\n\nelse{\n\n    for(int j = 0; j<stepnum; j++){\n\n    //Calculate first time step with loop over all points except boundary points\n    for(int i = 1; i < (stepnum-1); i++){\n\n    //Decleare and initialize some temporare variables\n    double temp_first_vorticity = first_vorticity2D[j][i];\n    double temp_psi1    = psi2D[j][i+1];\n    double temp_psi2    = psi2D[j][i-1];\n\n    //Update first_vorticity\n    first_vorticity2D = vorticity2D;\n\n    //Calculate new vorticity\n    vorticity2D[j][i] = temp_first_vorticity + (temp_psi2 - temp_psi1)*ingvild;\n\n    }//end for i\n    }//end for j\n}//end else\n\n}\n\nvoid forward_diff_periodicb_2D(double**& psi2D, double**& vorticity2D, double**& temp_vorticity2D, int stepnum, double ola){\n\t\n    //Update first_vorticity temporarly array\n    temp_vorticity2D = vorticity2D;\n\n    for(int j = 0; j<stepnum; j++){\n\n\t//Set the periodic boundaries at right and left endpoints for all rows\t\n\tvorticity2D[j][0] = temp_vorticity2D[j][0] + (psi2D[j][stepnum - 2] - psi2D[j][1])*ola;\n    \tvorticity2D[j][stepnum-1] = temp_vorticity2D[j][stepnum-1] + (psi2D[j][stepnum - 2] - psi2D[j][1])*ola;\t\n\n        //loop over all interior points\n        for(int i = 1; i < (stepnum-1); i++){\n\n        vorticity2D[j][i] = temp_vorticity2D[j][i] + (psi2D[j][i-1]- psi2D[j][i+1])*ola;\n\t\n\t}//end for col\n\n    }//end for rows\n\n}\n\nvoid Jacobi_Iterative_solidb_2D(double**& psi2D, double**& psi2D_temp, double**& vorticity2D, int stepnum, double jostein, double hanne, double jostein2){\n\n//Declearing the iteration limit and counter\nint maxiter = 100;\nint iter = 0;\n\n\n//Calculate next step by iterative method which uses the four neighbours\nwhile(iter < maxiter){\n\n    //Declaring temporary psi\n    psi2D_temp = psi2D;\n\t\n    //Calculate the interior psi's. Endpoint just stays zero.\n    for(int j = 1; j < (stepnum -1); j++){\n        for(int i = 1; i < (stepnum - 1); i++){\n\n        psi2D[j][i] = (jostein*((psi2D_temp[j][i+1] + psi2D_temp[j][i-1]) + (psi2D_temp[j+1][i] + psi2D_temp[j-1][i])) - jostein2*vorticity2D[j][i])/hanne;\n\n        }//end i\n    }//end j\n\n //Update iteration counter\n iter += 1;\n\n}//end iteration while\n\n}\n\nvoid Jacobi_Iterative_periodicb_2D(double**& psi2D, double**& psi2D_temp, double**& vorticity2D, int stepnum, double jostein, double hanne, double jostein2){\n\n//Declearing the iteration limit and counter\nint maxiter = 100;\nint iter = 0;\n\n\n//Calculate next step by iterative method which uses the four neighbours. Brute force and ugly code. sorry sorry sorry.\nwhile(iter < maxiter){\n\n    //Declaring temporary psi\n    psi2D_temp = psi2D;\n\n    for(int j = 0; j < (stepnum); j++){\n        for(int i = 0; i < (stepnum); i++){\n\t\n\t//The points and corners on left border ----------------------------------------------------------------------//\n        if((i == 0)){\n\t\n\t\t//upper left corner. OK\n\t\tif(j==(stepnum-1)){\t\n\t        \t\tpsi2D[j][i] = (jostein*((psi2D_temp[j][1] + psi2D_temp[j][stepnum-2]) + (psi2D_temp[1][i] + \t\t\tpsi2D_temp[j-1][i])) - jostein2*vorticity2D[j][i])/hanne;\n\t\t}\n\n\t\t//lower left corner OK\n\t\telse if(j==0){\n        \tpsi2D[j][i] = (jostein*((psi2D_temp[j][i+1] + psi2D_temp[j][stepnum-2]) + (psi2D_temp[j+1][i] + psi2D_temp[stepnum-2][i])) - \t\t\tjostein2*vorticity2D[j][i])/hanne;\n\t\t}\n\t\n\t\t//Internal points on left border OK\n\t\telse if(j != 0 && j!= (stepnum-1)){\n\t\tpsi2D[j][i] = (jostein*((psi2D_temp[j][i+1] + psi2D_temp[j][stepnum - 2]) + (psi2D_temp[j+1][i] + psi2D_temp[j-1][i])) - \t\t\tjostein2*vorticity2D[j][i])/hanne;\n\n        \t}\n\t}//end left endpoints\n\n\n\n\t//Points and corners on right border----------------------------------------------------------------------//\n        if(i == (stepnum-1)){\n\n\t\t//upper right corner OK\n\t\tif(j == (stepnum-1)){\n\t\tpsi2D[j][i] = (jostein*((psi2D_temp[j][1] + psi2D_temp[j][i-1]) + (psi2D_temp[1][i] + psi2D_temp[j-1][i])) - \t\t\tjostein2*vorticity2D[j][i])/hanne;\n\t\t}\n\t\n\t\t//lower right corner OK\n\t\telse if(j == 0){\n        \tpsi2D[j][i] = (jostein*((psi2D_temp[j][1] + psi2D_temp[j][i-1]) + (psi2D_temp[j+1][i] + psi2D_temp[stepnum-2][i])) -    \t  \tjostein2*vorticity2D[j][i])/hanne;\n\t\t}\n\t\t\n\t\t//Internal points on right border OK\n\t\telse if(j != 0 && j!= (stepnum-1)){\n\t\tpsi2D[j][i] = (jostein*((psi2D_temp[j][1] + psi2D_temp[j][i-1]) + (psi2D_temp[j+1][i] + psi2D_temp[j-1][i])) - \t\t\tjostein2*vorticity2D[j][i])/hanne;\n\t\t}\n        }//end right endpoints\n\n\t//Points on upper border------------------------------------------------------------------------//\n        if(j == (stepnum-1)){\n\t\n\t\t//interior points on upper border (corners already been taken)\tOK\n\t\tif(i != 0 && i != (stepnum-1)){\n\t\tpsi2D[j][i] = (jostein*((psi2D_temp[j][i+1] + psi2D_temp[j][i-1]) + (psi2D_temp[1][i] + psi2D_temp[j-1][i])) - \t  \t\t\tjostein2*vorticity2D[j][i])/hanne;}\n\n        \t}//end upper endpoints\n\n\t//Points on lower border ------------------------------------------------------------------------//\n        if(j == 0){\n\t\n\t\t//interior points on lower border (corners already been taken) OK\n\t\tif(i != 0 && i != (stepnum-1)){\t\n\t\tpsi2D[j][i] = (jostein*((psi2D_temp[j][i+1] + psi2D_temp[j][i-1]) + (psi2D_temp[j+1][i] + psi2D_temp[stepnum-2][i])) - \t\t\tjostein2*vorticity2D[j][i])/hanne;\n\t\t}\n        \t}//end lower endpoints\n\t\t\n\t//Interior interior points. hehe.---------------------------------------------------------------// \n\tif(i != 0 && j!= 0 && j != (stepnum-1) && i != (stepnum-1))  {\n        psi2D[j][i] = (jostein*((psi2D_temp[j][i+1] + psi2D_temp[j][i-1]) + (psi2D_temp[j+1][i] + psi2D_temp[j-1][i])) - \t  \t  \n        jostein2*vorticity2D[j][i])/hanne;\n\t}\n\n        \n      }//end i\n    }//end j\n\n\n //Update iteration counter\n iter += 1;\n\n}//end iteration while\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "793d009657d7f876cfc86a17c523f034bb36e7e7", "size": 22699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project5/main.cpp", "max_stars_repo_name": "olaba/FYS4150", "max_stars_repo_head_hexsha": "68309cf124d220d0bb1c9c6b7e0a65aa7fb9aba5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-06T08:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-06T08:35:06.000Z", "max_issues_repo_path": "Project5/main.cpp", "max_issues_repo_name": "olaba/FYS4150", "max_issues_repo_head_hexsha": "68309cf124d220d0bb1c9c6b7e0a65aa7fb9aba5", "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": "Project5/main.cpp", "max_forks_repo_name": "olaba/FYS4150", "max_forks_repo_head_hexsha": "68309cf124d220d0bb1c9c6b7e0a65aa7fb9aba5", "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.7107329843, "max_line_length": 233, "alphanum_fraction": 0.5939468699, "num_tokens": 7227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5262736562884364}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm accumulator variance\n#include <boost/test/unit_test.hpp>\n#include \"fern/algorithm/accumulator/variance.h\"\n\n\nnamespace faa = fern::algorithm::accumulator;\n\n\n// TODO Once we have a full blown square algorithm we must use that\n//      instead of this one.\ntemplate<\n    typename T>\ninline constexpr T square(\n    T const& value)\n{\n    return value * value;\n}\n\n\nBOOST_AUTO_TEST_CASE(default_construct)\n{\n    faa::Variance<int> variance;\n}\n\n\nBOOST_AUTO_TEST_CASE(accumulate)\n{\n    {\n        faa::Variance<int> variance(5);\n        // 5\n        BOOST_CHECK_EQUAL(variance(), (\n            square(5 - 5)) / 1);\n\n        variance(2);\n        // 5 2\n        BOOST_CHECK_EQUAL(variance(), (\n            square(3 - 5) +\n            square(3 - 2)) / 2);\n\n        variance(3);\n        // 5 2 3\n        BOOST_CHECK_EQUAL(variance(), (\n            square(3 - 5) +\n            square(3 - 2) +\n            square(3 - 3)) / 3);\n\n        variance = 8;\n        // 8\n        BOOST_CHECK_EQUAL(variance(), (\n            square(8 - 8)) / 1);\n    }\n\n    {\n        faa::Variance<int, double> variance(5);\n        // 5\n        BOOST_CHECK_EQUAL(variance(), (\n            square(5.0 - 5.0)) / 1.0);\n\n        variance(2);\n        // 5 2\n        BOOST_CHECK_EQUAL(variance(), (\n            square(3.5 - 5.0) +\n            square(3.5 - 2.0)) / 2.0);\n\n        variance = 3;\n        // 3\n        BOOST_CHECK_EQUAL(variance(), (\n            square(3.0 - 3.0)) / 1.0);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(merge)\n{\n    {\n        auto variance(faa::Variance<int>(15) | faa::Variance<int>(5));\n        // 15 5\n        BOOST_CHECK_EQUAL(variance(), (\n            square(10 - 15) +\n            square(10 - 5)) / 2);\n    }\n\n    {\n        auto variance(faa::Variance<int, double>(5) |\n            faa::Variance<int, double>(20));\n        // 5 20\n        BOOST_CHECK_EQUAL(variance(), (\n            square(12.5 - 5.0) +\n            square(12.5 - 20.0)) / 2.0);\n    }\n}\n", "meta": {"hexsha": "477ae9922158ca2fe8c6aa25d1e952b334b24b35", "size": 2424, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/accumulator/test/variance_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/accumulator/test/variance_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/accumulator/test/variance_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["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.24, "max_line_length": 80, "alphanum_fraction": 0.5004125413, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5262736514154509}}
{"text": "#include <possumwood_sdk/node_implementation.h>\n#include <tbb/blocked_range.h>\n#include <tbb/parallel_reduce.h>\n\n#include <boost/noncopyable.hpp>\n\n#include \"sequence.h\"\n\nnamespace {\n\ndependency_graph::InAttr<possumwood::opencv::Sequence> a_in;\ndependency_graph::OutAttr<possumwood::opencv::Frame> a_out;\n\nstruct Reduce : public boost::noncopyable {\n\texplicit Reduce(const possumwood::opencv::Sequence& seq) {\n\t\tfor(auto& f : seq)\n\t\t\tmats.push_back(*f);  // \"shallow\" copy\n\t}\n\n\t// splitting constructor - copies the input matrices but there is no need to initialise the accumulator\n\t// as it will get overwritten anyway\n\tReduce(const Reduce& r, tbb::split) : mats(r.mats) {\n\t}\n\n\tReduce(const Reduce&) = delete;\n\tReduce& operator=(const Reduce&) = delete;\n\n\t/// converts a range of input images int double format, and sums them together\n\tvoid operator()(const tbb::blocked_range<std::size_t>& range) {\n\t\tassert(!range.empty());\n\n\t\tauto it = range.begin();\n\n\t\tif(accum.empty()) {\n\t\t\tmats[it].convertTo(accum, CV_MAKETYPE(CV_64F, mats[it].channels()));\n\t\t\t++it;\n\t\t}\n\n\t\tcv::Mat tmp;\n\t\tfor(; it != range.end(); ++it) {\n\t\t\tmats[it].convertTo(tmp, CV_MAKETYPE(CV_64F, mats[it].channels()));\n\t\t\taccum += tmp;\n\t\t}\n\t}\n\n\t// combine two results together\n\tvoid join(const Reduce& r) {\n\t\tassert(accum.rows == r.accum.rows && accum.cols == r.accum.cols);\n\t\taccum += r.accum;\n\t}\n\n\tstd::vector<cv::Mat> mats;  // input matrices (shallow copy)\n\tcv::Mat accum;              // resulting accumulator\n};\n\ndependency_graph::State compute(dependency_graph::Values& data) {\n\tconst possumwood::opencv::Sequence& in = data.get(a_in);\n\n\tif(!in.isValid())\n\t\tthrow std::runtime_error(\"Input sequence does not have consistent size or type.\");\n\n\tcv::Mat out;\n\n\tif(in.size() > 1) {\n\t\t// parallelized reduction implementing the accumulation and data conversion on multiple threads\n\t\tReduce r(in);\n\t\ttbb::parallel_reduce(tbb::blocked_range<std::size_t>(0, in.size()), r);\n\n\t\t// normalize the result of the accumulation, and convert back to the original type\n\t\tr.accum /= (double)in.size();\n\t\tr.accum.convertTo(out, in[0]->type());\n\t}\n\n\telse\n\t\tthrow std::runtime_error(\"At least two frames in the input sequence required!\");\n\n\tdata.set(a_out, possumwood::opencv::Frame(out));\n\n\treturn dependency_graph::State();\n}\n\nvoid init(possumwood::Metadata& meta) {\n\tmeta.addAttribute(a_in, \"in\");\n\tmeta.addAttribute(a_out, \"out\", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);\n\n\tmeta.addInfluence(a_in, a_out);\n\n\tmeta.setCompute(compute);\n}\n\npossumwood::NodeImplementation s_impl(\"opencv/sequence/mean\", init);\n\n}  // namespace\n", "meta": {"hexsha": "a7665d7b05e87a290ad3e0950ccd7606b393390e", "size": 2599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plugins/opencv/nodes/sequence/mean.cpp", "max_stars_repo_name": "LIUJUN-liujun/possumwood", "max_stars_repo_head_hexsha": "745e48eb44450b0b7f078ece81548812ab1ccc63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-06T08:40:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-06T08:40:10.000Z", "max_issues_repo_path": "src/plugins/opencv/nodes/sequence/mean.cpp", "max_issues_repo_name": "LIUJUN-liujun/possumwood", "max_issues_repo_head_hexsha": "745e48eb44450b0b7f078ece81548812ab1ccc63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plugins/opencv/nodes/sequence/mean.cpp", "max_forks_repo_name": "LIUJUN-liujun/possumwood", "max_forks_repo_head_hexsha": "745e48eb44450b0b7f078ece81548812ab1ccc63", "max_forks_repo_licenses": ["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.6489361702, "max_line_length": 104, "alphanum_fraction": 0.7006540977, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5262736490886043}}
{"text": "/**\n *      @file slowMetropolis.cpp\n *      @date May 23, 2012\n *      @author Brian Peasley\n *      @author Frank Dellaert\n */\n\n#include \"OccupancyGrid/OccupancyGrid.h\"\n#include \"OccupancyGrid/visualiser.h\"\n#include \"OccupancyGrid/TwoAssumptionAlgorithm.h\"\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n\nusing namespace std;\nusing namespace gtsam;\n\n/**\n * @brief Run a metropolis sampler.\n * @param iterations defines the number of iterations to run.\n * @return  vector of marginal probabilities.\n */\nOccupancyGrid::Marginals runSlowMetropolis(const OccupancyGrid &occupancyGrid,\n    size_t iterations, double max_clock) {\n\n  // Create a data structure to hold the estimated marginal occupancy probabilities\n  // and initialize to zero.\n  size_t size = occupancyGrid.cellCount();\n  OccupancyGrid::Marginals marginals(size);\n  for (size_t it = 0; it < marginals.size(); it++)\n    marginals[it] = 0;\n\n  // Initialize randum number generator\n  size_t nrows = occupancyGrid.height();\n  //size_t ncols = occupancyGrid.width();\n  boost::mt19937 rng;\n  boost::uniform_int < Index > random_cell(0, size - 1);\n  double sigma = 0.05 * nrows ; // next sample point will be within 2*5 cells (95% of the times)\n\n  boost::normal_distribution< double > normal_dist(0, sigma);\n  boost::variate_generator<boost::mt19937&,\n    boost::normal_distribution< double > > var_nor(rng, normal_dist);\n\n  // double dsize   = static_cast<double>(size);\n  // double dheight = floor(sqrt(dsize));\n  // size_t height  = static_cast<size_t>(dheight);\n  // size_t width   = static_cast<size_t>(floor(dsize/dheight));\n  clock_t st = clock();\n\n  // Create empty occupancy as initial state and\n  // compute initial neg log-probability of occupancy grid, - log P(x_t)\n  LaserFactor::Occupancy occupancy = occupancyGrid.emptyOccupancy();\n  std::vector<double> two_energy(occupancyGrid.cellCount());\n  two_assumption_algorithm(occupancyGrid, occupancy, two_energy); \n\n  double Ex = occupancyGrid(occupancy);\n  global_vis_.init(occupancyGrid.height(), occupancyGrid.width());\n\n  // for logging\n  vector<double> energy;\n\n  // Choose a random cell\n  //Index x_;// = random_cell(rng);\n\n  // run Metropolis for the requested number of operations\n  for (size_t it = 0; it < iterations && clock() < (max_clock - st); it++) {\n\n    // Log and print\n    energy.push_back(Ex);\n    if (it % 100 == 0) {\n      clock_t et = clock();\n      std::cout << \"<Energy>\\t\" << ((float)(et - st)) / CLOCKS_PER_SEC << \"\\t\" << Ex << std::endl;\n      printf(\"%lf\\n\", (double) it / (double) iterations);\n\n      if (it % 10000) {\n        global_vis_.enable_show();\n        global_vis_.reset();\n        global_vis_.setMarginals(marginals);\n        global_vis_.show();\n      }\n    }\n\n    // Sample a point close to the previous point with gaussian probability\n    // This is a heuristic strategy that high occupancy regions (high\n    // probability) are going to be few but close together in space. This is\n    // not same as the choosing the proposal distribution for metropolis\n    // algorithm as the space we are working is a 100x100 dimensional space\n    // rather than a 2D space. But some of the properties of this 2D space can\n    // be made use of. This idea is similar to that of a heat map.\n    // double col = x % ncols;\n    // double row = x / ncols;\n    // row += var_nor();\n    // col += var_nor();\n    // Index row_lu = (row < 0) ? 0\n    //   : (row >= nrows) ? nrows - 1\n    //   : static_cast<Index>(row);\n    // Index col_lu = (col < 0) ? 0\n    //   : (col >= ncols) ? ncols - 1\n    //   : static_cast<Index>(col);\n    // Index x_prime = row_lu * occupancyGrid.width() + col_lu;\n    Index x_prime = random_cell(rng);\n\n\n    // Compute neg log-probability of new occupancy grid, -log P(x')\n    // by summing over all LaserFactor::operator()\n    double oldValue = occupancy[x_prime];\n    double deltaEx = \n      occupancyGrid.computeDelta(occupancy, x_prime, 1 - occupancy[x_prime]);\n    assert(occupancy[x_prime] == oldValue);\n\n    // Calculate acceptance ratio, a\n    // See e.g. MacKay 96 \"Intro to Monte Carlo Methods\"\n    // a = P(x')/P(x) = exp {-E(x')} / exp {-E(x)} = exp {E(x)-E(x')}\n    double a = exp(- deltaEx);\n\n    // If a <= 1 otherwise accept with probability a\n    double rn = static_cast<double>(std::rand()) / (RAND_MAX);\n    bool accept = (a>=1) ? true // definitely accept\n      : (a >= rn) ?  true       // accept with probability a\n      : false;\n\n    //printf(\"%lu : %lu; accepted: %d\\n\", x_prime, occupancy.at(x_prime), accept);\n    if (accept) {\n      Ex += deltaEx;\n      //x_ = x_prime;\n      // we accept: flip it !\n      occupancy[x_prime] = 1 - occupancy[x_prime];\n    } else {\n      //x_ = random_cell(rng);\n    }\n\n    //increment the number of iterations each cell has been on\n    for (size_t i = 0; i < size; i++) {\n      if (occupancy[i] == 1)\n        marginals[i]++;\n    }\n  }\n\n  FILE *fptr = fopen(\"Data/Metropolis_Energy.txt\", \"w\");\n  for (size_t i = 0; i < iterations; i++)\n    fprintf(fptr, \"%lf \", energy[i]);\n\n  //compute the marginals\n  for (size_t it = 0; it < size; it++)\n    marginals[it] /= iterations;\n\n  return marginals;\n}\n", "meta": {"hexsha": "cf8386f2bfcee70031c3f25f8f3c884f5b9f75c1", "size": 5151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MCMC/Metropolis.cpp", "max_stars_repo_name": "wecacuee/modern-occupancy-grid", "max_stars_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-03-14T16:24:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T05:39:06.000Z", "max_issues_repo_path": "src/MCMC/Metropolis.cpp", "max_issues_repo_name": "wecacuee/modern-occupancy-grid", "max_issues_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MCMC/Metropolis.cpp", "max_forks_repo_name": "wecacuee/modern-occupancy-grid", "max_forks_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-08-10T02:02:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-20T12:20:29.000Z", "avg_line_length": 34.8040540541, "max_line_length": 98, "alphanum_fraction": 0.6445350417, "num_tokens": 1400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5262736439963257}}
{"text": "#include <algorithm>\n#include <fstream>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <map>\n#include <numeric>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <deque>\n\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/iterator/function_input_iterator.hpp>\n#include <boost/iterator/filter_iterator.hpp>\n//#include <boost/bind.hpp>\n//\nnamespace ph=std::placeholders;\n\nusing namespace std;\n\nvoid init_flags(deque<bool>& flags) {\n  if (flags.size() > 0) flags[0] = false;\n  if (flags.size() > 1) flags[1] = false;\n}\n\nvoid cross_off(deque<bool>& flags, int prime) {\n  for (int i = prime * prime; i < flags.size(); i += prime) {\n    flags[i] = false;\n  }\n}\n\nint get_next_prime(deque<bool>& flags, int prime) {\n  int next = prime + 1;\n  while (next < flags.size() && !flags[next]) {\n    next++;\n  }\n  return next;\n}\n\nvoid sieve_of_eratos_thenes(int max, std::deque<bool>& flags) {\n  flags.assign(max, true);\n  init_flags(flags);\n\n  int prime = 2;\n  int count = 0;\n\n  while (prime <= max) {\n    cross_off(flags, prime);\n    prime = get_next_prime(flags, prime);\n    if (prime >= flags.size()) {\n      break;\n    }\n  }\n}\n\ntypedef std::pair<int, bool> PrimePair;\n\nint my_f(int a, int b, int c) { return a * b * c; }\n\nPrimePair my_make_pair(int a, bool b) {\n  return std::make_pair(a, b);\n}\n\nvoid write_primes(int max) {\n  std::deque<bool> flags;\n  sieve_of_eratos_thenes(max, flags);\n\n  std::vector<PrimePair> pairs;\n  std::transform(boost::counting_iterator<int>(0),\n            boost::counting_iterator<int>(max),\n            flags.begin(),\n            back_inserter(pairs),\n            make_pair<const int&, const bool&>);\n\n  std::transform(\n      boost::make_filter_iterator(std::bind(&PrimePair::second, ph::_1), pairs.begin(), pairs.end()),\n      boost::make_filter_iterator(std::bind(&PrimePair::second, ph::_1), pairs.end(), pairs.end()),\n      ostream_iterator<int>(cout, \" \"),\n      std::bind(&PrimePair::first, ph::_1));\n}\n\nint main(int argc, char **argv) {\n  write_primes(1000);\n  cout << endl;\n  \n  return 0;\n}\n", "meta": {"hexsha": "ac87ad8d7118278bbcbf65eb071c80cd5b662d6e", "size": 2088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "langs/c++/primes/primes.cpp", "max_stars_repo_name": "danielgrigg/sandbox", "max_stars_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-23T03:57:39.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-23T03:57:39.000Z", "max_issues_repo_path": "langs/c++/primes/primes.cpp", "max_issues_repo_name": "danielgrigg/sandbox", "max_issues_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "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": "langs/c++/primes/primes.cpp", "max_forks_repo_name": "danielgrigg/sandbox", "max_forks_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "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": 23.2, "max_line_length": 101, "alphanum_fraction": 0.6465517241, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5262736391233401}}
{"text": "#pragma once\n\n#include <cmath>\n#include <vector>\n#include <stdexcept>\n#include <string.h>\n#include <Eigen/Core>\n\n#include \"traits.hh\"\n#include \"../util/assert.hh\"\n\nnamespace bold\n{\n  template<typename T>\n  class MovingAverage\n  {\n  public:\n    MovingAverage(unsigned short windowSize)\n    : d_items(new T[windowSize]),\n      d_length(0),\n      d_nextPointer(0),\n      d_sum(),\n      d_windowSize(windowSize)\n    {\n      if (windowSize == 0)\n        throw new std::runtime_error(\"Cannot have zero window size.\");\n      AveragingTraits::zero(d_sum);\n    }\n\n    MovingAverage(MovingAverage const& other)\n    {\n      copy(other);\n    }\n\n    ~MovingAverage()\n    {\n      destroy();\n    }\n\n    MovingAverage& operator=(MovingAverage const& other)\n    {\n      destroy();\n      copy(other);\n      return *this;\n    }\n\n    int count() const { return d_length; }\n    int getWindowSize() const { return d_windowSize; }\n    bool isMature() const { return d_length == d_windowSize; }\n\n    T next(T value)\n    {\n      if (d_length == d_windowSize)\n      {\n        d_sum -= d_items[d_nextPointer];\n      }\n      else\n      {\n        d_length++;\n      }\n\n      d_items[d_nextPointer] = value;\n      d_sum += value;\n      d_nextPointer = (d_nextPointer + 1) % d_windowSize;\n\n      d_avg = d_sum / int{d_length};\n\n      return d_avg;\n    }\n\n    void reset()\n    {\n      d_length = 0;\n      d_nextPointer = 0;\n      AveragingTraits::zero(d_sum);\n    }\n\n    T getAverage() const { return d_avg; }\n\n    T calculateStdDev()\n    {\n      // TODO unit test this\n      T sum;\n      AveragingTraits::zero(sum);\n      for (int i = 0; i < d_length; i++)\n      {\n        int index = (d_nextPointer - i - 1) % d_windowSize;\n        if (index < 0)\n          index += d_windowSize;\n        ASSERT(index >= 0 && index < d_length);\n        T diff = d_items[index] - d_avg;\n        sum += diff * diff;\n      }\n      return sqrt(sum / d_length);\n    }\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  private:\n    T* d_items;\n    unsigned short d_length;\n    int d_nextPointer;\n    T d_sum;\n    T d_avg;\n    unsigned short d_windowSize;\n\n    void destroy()\n    {\n      delete[] d_items;\n    }\n\n    void copy(MovingAverage const& other)\n    {\n      d_windowSize = other.d_windowSize;\n      d_items = new T[other.d_windowSize];\n      for (unsigned i = 0; i < d_windowSize; ++i)\n        d_items[i] = other.d_items[i];\n\n      d_length = other.d_length;\n      d_nextPointer = other.d_nextPointer;\n      d_sum = other.d_sum;\n      d_avg = other.d_avg;\n    }\n  };\n\n  template <>\n  inline Eigen::Vector3d MovingAverage<Eigen::Vector3d>::calculateStdDev()\n  {\n    Eigen::Matrix3d sum = Eigen::Matrix3d::Zero();\n    for (int i = 0; i < d_length; i++)\n    {\n      int index = (d_nextPointer - i - 1) % d_windowSize;\n      if (index < 0)\n        index += d_windowSize;\n      ASSERT(index >= 0 && index < d_length);\n      Eigen::Vector3d diff = d_items[index] - d_avg;\n      sum += diff * diff.transpose();\n    }\n    Eigen::Vector3d r = sum.diagonal();\n    for (int i = 0; i < r.size(); i++)\n      r[i] = sqrt(r[i]);\n    return r / d_length;\n  }\n\n  template <>\n  inline Eigen::Vector2d MovingAverage<Eigen::Vector2d>::calculateStdDev()\n  {\n//     std::cout << \"------------------------\" << std::endl;\n//     std::cout << \"d_avg = \" << d_avg.transpose() << std::endl;\n    Eigen::Matrix2d sum = Eigen::Matrix2d::Zero();\n    for (int i = 0; i < d_length; i++)\n    {\n      int index = (d_nextPointer - i - 1) % d_windowSize;\n      if (index < 0)\n        index += d_windowSize;\n      ASSERT(index >= 0 && index < d_length);\n      Eigen::Vector2d diff = d_items[index] - d_avg;\n      sum += diff * diff.transpose();\n//       std::cout << \"---- index \" << index << std::endl\n//           << \"diff \" << diff.transpose() << std::endl\n//           << \"sum\" << std::endl << sum << std::endl;\n    }\n    Eigen::Vector2d r = sum.diagonal();\n//     std::cout << \"r = \" << r.transpose() << std::endl;\n    for (int i = 0; i < r.size(); i++)\n      r[i] = sqrt(r[i]);\n//     std::cout << \"r_squared = \" << r.transpose() << std::endl;\n//     std::cout << \"stddev = \" << (r/d_length).transpose() << std::endl;\n    return r / d_length;\n  }\n}\n", "meta": {"hexsha": "f4883d37ae5189f2b5cb9a4456cedf2803ea9ee6", "size": 4160, "ext": "hh", "lang": "C++", "max_stars_repo_path": "stats/movingaverage.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": "stats/movingaverage.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": "stats/movingaverage.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": 24.3274853801, "max_line_length": 74, "alphanum_fraction": 0.5514423077, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177519, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5262562953593826}}
{"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#include <boost/simd/pack.hpp>\n#include <boost/simd/function/nearbyint.hpp>\n#include <boost/simd/function/bits.hpp>\n#include <boost/simd/meta/cardinal_of.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/function/is_negative.hpp>\n#include <boost/simd/function/is_positive.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/mhalf.hpp>\n#include <boost/simd/constant/true.hpp>\n#include <boost/simd/function/is_negative.hpp>\n#include <boost/simd/function/is_positive.hpp>\n\ntemplate <typename T, int N, typename Env>\nvoid test(Env& $)\n{\n  namespace bs = boost::simd;\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], b[N], a2[N], c[N];\n  for(int i = 0; i < N; ++i)\n  {\n    a1[i] = ((i%2) ? T(2*i) : T(-2*i))/T(3);\n    a2[i] = T(2*i+1)/T(2);\n    b[i] = bs::nearbyint(a1[i]) ;\n    c[i] = bs::nearbyint(a2[i]) ;\n  }\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t aa2(&a2[0], &a2[0]+N);\n  p_t bb (&b[0], &b[0]+N);\n  p_t cc (&c[0], &c[0]+N);\n  STF_IEEE_EQUAL(bs::nearbyint(aa1), bb);\n  STF_IEEE_EQUAL(bs::nearbyint(aa2), cc);\n}\n\nSTF_CASE_TPL(\"Check nearbyint on pack\" , STF_NUMERIC_TYPES)\n{\n  namespace bs = boost::simd;\n  using p_t = bs::pack<T>;\n  static const std::size_t N = bs::cardinal_of<p_t>::value;\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n\n\nSTF_CASE_TPL(\"Check nearbyint on halfs\" , STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  using p_t = bs::pack<T>;\n  p_t a(1.5);\n  p_t b(2.5);\n  for(int i = 1; i <= 9; i+= 1)\n  {\n    STF_IEEE_EQUAL(bs::nearbyint(p_t(i+T(0.5))), p_t(i%2 ? i+1 : i ));\n    STF_IEEE_EQUAL(bs::nearbyint(p_t(-i+T(0.5))), p_t(i%2 ? -i+1 : -i ));\n  }\n  STF_EXPECT(bs::is_negative(nearbyint(bs::Mzero<T>())));\n  STF_EXPECT(bs::is_positive(nearbyint(bs::Zero<T>())));\n}\n\n\nSTF_CASE_TPL ( \"nearbyint real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::nearbyint;\n  using p_t = bs::pack<T>;\n  using r_t = decltype(nearbyint(p_t()));\n\n  // return type conformity test\n  STF_TYPE_IS( r_t, p_t );\n\n  // specific values tests\n  STF_IEEE_EQUAL(nearbyint(p_t(1.4)), p_t(1));\n  STF_IEEE_EQUAL(nearbyint(p_t(1.5)), p_t(2));\n  STF_IEEE_EQUAL(nearbyint(p_t(1.6)), p_t(2));\n  STF_IEEE_EQUAL(nearbyint(p_t(2.5)), p_t(2));\n  STF_IEEE_EQUAL(nearbyint(bs::Half<p_t>()), bs::Zero<r_t>());\n  STF_IEEE_EQUAL(nearbyint(bs::Inf<p_t>()), bs::Inf<r_t>());\n  STF_IEEE_EQUAL(nearbyint(bs::Mhalf<p_t>()), bs::Zero<r_t>());\n  STF_IEEE_EQUAL(nearbyint(bs::Minf<p_t>()), bs::Minf<r_t>());\n  STF_IEEE_EQUAL(nearbyint(bs::Mone<p_t>()), bs::Mone<r_t>());\n  STF_IEEE_EQUAL(nearbyint(bs::Nan<p_t>()), bs::Nan<r_t>());\n  STF_IEEE_EQUAL(nearbyint(bs::One<p_t>()), bs::One<r_t>());\n  STF_IEEE_EQUAL(nearbyint(bs::Zero<p_t>()), bs::Zero<r_t>());\n  STF_IEEE_EQUAL(nearbyint(bs::Nan<p_t>()), bs::Nan<r_t>());\n  STF_EQUAL(bs::is_negative(nearbyint(bs::Mzero<p_t>())), bs::True<r_t>());\n  STF_EQUAL(bs::is_positive(nearbyint(bs::Zero<p_t>())), bs::True<r_t>());\n} // end of test for floating_\n", "meta": {"hexsha": "6a8eca26c08c8e5e25aa2161472b7220cc85059e", "size": 3688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/nearbyint.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": "test/function/simd/nearbyint.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": "test/function/simd/nearbyint.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": 33.5272727273, "max_line_length": 100, "alphanum_fraction": 0.6206616052, "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5262562921543382}}
{"text": "// Copyright 2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_custom_2d_axis\n\n#include <boost/histogram.hpp>\n#include <cassert>\n\nint main() {\n  using namespace boost::histogram;\n\n  // axis which returns 1 if the input falls inside the unit circle and zero otherwise\n  struct circle_axis {\n    // accepts a 2D point in form of a std::tuple\n    axis::index_type index(const std::tuple<double, double>& point) const {\n      const auto x = std::get<0>(point);\n      const auto y = std::get<1>(point);\n      return x * x + y * y <= 1.0;\n    }\n\n    axis::index_type size() const { return 2; }\n  };\n\n  auto h1 = make_histogram(circle_axis());\n\n  // fill looks normal for a histogram which has only one Nd-axis\n  h1(0, 0);   // in\n  h1(0, -1);  // in\n  h1(0, 1);   // in\n  h1(-1, 0);  // in\n  h1(1, 0);   // in\n  h1(1, 1);   // out\n  h1(-1, -1); // out\n\n  // 2D histogram, but only 1D index\n  assert(h1.at(0) == 2); // out\n  assert(h1.at(1) == 5); // in\n\n  // other axes can be combined with a Nd-axis\n  auto h2 = make_histogram(circle_axis(), axis::category<std::string>({\"red\", \"blue\"}));\n\n  // now we need to pass arguments for Nd-axis explicitly as std::tuple\n  h2(std::make_tuple(0, 0), \"red\");\n  h2(std::make_tuple(1, 1), \"blue\");\n\n  // 3D histogram, but only 2D index\n  assert(h2.at(0, 0) == 0); // out, red\n  assert(h2.at(0, 1) == 1); // out, blue\n  assert(h2.at(1, 0) == 1); // in, red\n  assert(h2.at(1, 1) == 0); // in, blue\n}\n\n//]\n", "meta": {"hexsha": "6a952a659a1a5a0a4a0b054f17b42346605b9777", "size": 1575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/histogram/examples/guide_custom_2d_axis.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/histogram/examples/guide_custom_2d_axis.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/histogram/examples/guide_custom_2d_axis.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": 27.6315789474, "max_line_length": 88, "alphanum_fraction": 0.6082539683, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5262562906939652}}
{"text": "/**\n * \\file boost/numeric/ublasx/test/relational_opts.cpp\n *\n * \\brief Test suite for matrix/vector relational operators.\n *\n * Copyright (c) 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#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublasx/detail/debug.hpp>\n#include <boost/numeric/ublasx/operation/relational_ops.hpp>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\n\nnamespace ublas = ::boost::numeric::ublas;\nnamespace ublasx = ::boost::numeric::ublasx;\n\n\nBOOST_UBLASX_TEST_DEF( equal_real_vector )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: Real Vector - Equality\");\n\n\ttypedef double value_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\n\tconst ::std::size_t n(4);\n\n\tvector_type u;\n\tvector_type v;\n\n\tbool res;\n\tbool expect;\n\n\tu = ublas::scalar_vector<value_type>(n, 1);\n\tv = ublas::scalar_vector<value_type>(n, 1);\n\tres = u == v;\n\texpect = true;\n\tBOOST_UBLASX_DEBUG_TRACE(\"u=\" << u);\n\tBOOST_UBLASX_DEBUG_TRACE(\"v=\" << v);\n\tBOOST_UBLASX_DEBUG_TRACE(\"u==v? \" << std::boolalpha << res);\n\tBOOST_UBLASX_TEST_CHECK( res == expect );\n\n\tu = ublas::scalar_vector<value_type>(n, 1);\n\tv = 2*ublas::scalar_vector<value_type>(n, 1);\n\tres = u == v;\n\texpect = false;\n\tBOOST_UBLASX_DEBUG_TRACE(\"u=\" << u);\n\tBOOST_UBLASX_DEBUG_TRACE(\"v=\" << v);\n\tBOOST_UBLASX_DEBUG_TRACE(\"u==v? \" << std::boolalpha << res);\n\tBOOST_UBLASX_TEST_CHECK( res == expect );\n}\n\n\nBOOST_UBLASX_TEST_DEF( not_equal_real_vector )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: Real Vector - Inequality\");\n\n\ttypedef double value_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\n\tconst ::std::size_t n(4);\n\n\tvector_type u;\n\tvector_type v;\n\n\tbool res;\n\tbool expect;\n\n\tu = ublas::scalar_vector<value_type>(n, 1);\n\tv = 2*ublas::scalar_vector<value_type>(n, 1);\n\tres = u != v;\n\texpect = true;\n\tBOOST_UBLASX_DEBUG_TRACE(\"u=\" << u);\n\tBOOST_UBLASX_DEBUG_TRACE(\"v=\" << v);\n\tBOOST_UBLASX_DEBUG_TRACE(\"u!=v? \" << std::boolalpha << res);\n\tBOOST_UBLASX_TEST_CHECK( res == expect );\n\n\tu = ublas::scalar_vector<value_type>(n, 1);\n\tv = ublas::scalar_vector<value_type>(n, 1);\n\tres = u != v;\n\texpect = false;\n\tBOOST_UBLASX_DEBUG_TRACE(\"u=\" << u);\n\tBOOST_UBLASX_DEBUG_TRACE(\"v=\" << v);\n\tBOOST_UBLASX_DEBUG_TRACE(\"u!=v? \" << std::boolalpha << res);\n\tBOOST_UBLASX_TEST_CHECK( res == expect );\n}\n\n\nBOOST_UBLASX_TEST_DEF( equal_real_matrix )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: Real Matrix - Equality\");\n\n\ttypedef double value_type;\n\ttypedef ublas::matrix<value_type> matrix_type;\n\n\tconst ::std::size_t nr(4);\n\tconst ::std::size_t nc(4);\n\n\tmatrix_type A;\n\tmatrix_type B;\n\n\tbool res;\n\tbool expect;\n\n\tA = ublas::identity_matrix<value_type>(nr,nc);\n\tB = ublas::identity_matrix<value_type>(nr,nc);\n\tres = A == B;\n\texpect = true;\n\tBOOST_UBLASX_DEBUG_TRACE(\"A=\" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"B=\" << B);\n\tBOOST_UBLASX_DEBUG_TRACE(\"A==B? \" << std::boolalpha << res);\n\tBOOST_UBLASX_TEST_CHECK( res == expect );\n\n\tA = ublas::identity_matrix<value_type>(nr,nc);\n\tB = 2*ublas::identity_matrix<value_type>(nr,nc);\n\tres = A == B;\n\texpect = false;\n\tBOOST_UBLASX_DEBUG_TRACE(\"A=\" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"B=\" << B);\n\tBOOST_UBLASX_DEBUG_TRACE(\"A==B? \" << std::boolalpha << res);\n\tBOOST_UBLASX_TEST_CHECK( res == expect );\n}\n\n\nBOOST_UBLASX_TEST_DEF( not_equal_real_matrix )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: Real Matrix - Inequality\");\n\n\ttypedef double value_type;\n\ttypedef ublas::matrix<value_type> matrix_type;\n\n\tconst ::std::size_t nr(4);\n\tconst ::std::size_t nc(4);\n\n\tmatrix_type A;\n\tmatrix_type B;\n\n\tbool res;\n\tbool expect;\n\n\tA = ublas::identity_matrix<value_type>(nr,nc);\n\tB = 2*ublas::identity_matrix<value_type>(nr,nc);\n\tres = A != B;\n\texpect = true;\n\tBOOST_UBLASX_DEBUG_TRACE(\"A=\" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"B=\" << B);\n\tBOOST_UBLASX_DEBUG_TRACE(\"A!=B? \" << std::boolalpha << res);\n\tBOOST_UBLASX_TEST_CHECK( res == expect );\n\n\tA = ublas::identity_matrix<value_type>(nr,nc);\n\tB = ublas::identity_matrix<value_type>(nr,nc);\n\tres = A != B;\n\texpect = false;\n\tBOOST_UBLASX_DEBUG_TRACE(\"A=\" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"B=\" << B);\n\tBOOST_UBLASX_DEBUG_TRACE(\"A!=B? \" << std::boolalpha << res);\n\tBOOST_UBLASX_TEST_CHECK( res == expect );\n}\n\n\nint main()\n{\n\tBOOST_UBLASX_TEST_BEGIN();\n\n\tBOOST_UBLASX_TEST_DO( equal_real_vector );\n\tBOOST_UBLASX_TEST_DO( not_equal_real_vector );\n\tBOOST_UBLASX_TEST_DO( equal_real_matrix );\n\tBOOST_UBLASX_TEST_DO( not_equal_real_matrix );\n\n\tBOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "3b4ab6621cb706e7fb57ff2989a3a4e42cda011e", "size": 4605, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/relational_ops.cpp", "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": "libs/numeric/ublasx/test/relational_ops.cpp", "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": "libs/numeric/ublasx/test/relational_ops.cpp", "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": 25.7262569832, "max_line_length": 66, "alphanum_fraction": 0.7096634093, "num_tokens": 1392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.5262562906939652}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 1999 - 2015 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 at\n * the top level of the deal.II distribution.\n *\n * ---------------------------------------------------------------------\n *\n * based on deal.II step-2\n */\n\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_renumbering.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_q.h>\n\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/manifold_lib.h>\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#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/sparse_matrix.h>\n\n#include <fstream>\n\nusing namespace dealii;\n\n\nvoid\nshow_statistics(const SparsityPattern &sparsity_pattern)\n{\n  Vector<int> v;\n  double      sum = 0.0;\n  for (unsigned int i = 0; i < sparsity_pattern.n_cols(); ++i)\n    {\n      sum += sparsity_pattern.row_length(i);\n    }\n\n  std::cout << \"Statistics for the current sparsity pattern:\"\n            << \"\\n\"\n            << \"bandwidth: \" << sparsity_pattern.bandwidth() << \"\\t\"\n            << \" number of unknowns : \" << sparsity_pattern.n_cols() << \"\\t\"\n            << \"average number of of entries per row\"\n            << sum / sparsity_pattern.n_cols() << \"\\n\";\n}\n\nvoid\nmake_grid(Triangulation<2> &triangulation)\n{\n  const Point<2> center(1, 0);\n  const double   inner_radius = 0.5, outer_radius = 1.0;\n  GridGenerator::hyper_shell(\n    triangulation, center, inner_radius, outer_radius, 5);\n\n  static const SphericalManifold<2> manifold_description(center);\n  triangulation.set_all_manifold_ids(0);\n  triangulation.set_manifold(0, manifold_description);\n\n  for (unsigned int step = 0; step < 3; ++step)\n    {\n      Triangulation<2>::active_cell_iterator cell =\n                                               triangulation.begin_active(),\n                                             endc = triangulation.end();\n\n      for (; cell != endc; ++cell)\n        for (unsigned int v = 0; v < GeometryInfo<2>::vertices_per_cell; ++v)\n          {\n            const double distance_from_center =\n              center.distance(cell->vertex(v));\n\n            if (std::fabs(distance_from_center - inner_radius) < 1e-10)\n              {\n                cell->set_refine_flag();\n                break;\n              }\n          }\n\n      triangulation.execute_coarsening_and_refinement();\n    }\n}\n\n\nvoid\ndistribute_dofs(DoFHandler<2> &dof_handler)\n{\n  static const FE_Q<2> finite_element(\n    1); // degree of poly 1: bilinear element, 2:bi-quadratic element, ...\n  // std::cout << \"Value at (1,1) \"\n  //           << finite_element.shape_value(2, Point<2>(1, 1)) << \"\\n\";\n\n\n  dof_handler.distribute_dofs(\n    finite_element); // we have associated a degree of freedom with a global\n                     // number to each vertex\n\n  DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs(),\n                                                  dof_handler.n_dofs());\n\n\n\n  DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern);\n\n  SparsityPattern sparsity_pattern;\n  sparsity_pattern.copy_from(dynamic_sparsity_pattern);\n  std::cout << \"Number of entries per row in the sparsity pattern\"\n            << \"\\n\";\n  // SparseMatrix<double> system_matrix;\n  // system_matrix.reinit(sparsity_pattern);\n\n  for (unsigned int i = 0; i < dof_handler.n_dofs(); ++i)\n    {\n      std::cout << \"Length of \" << i << \"-th row\"\n                << \"\\t\" << sparsity_pattern.row_length(i) << \"\\n\";\n    }\n\n\n  show_statistics(sparsity_pattern);\n  std::ofstream out(\"sparsity_pattern1.svg\");\n  sparsity_pattern.print_svg(out);\n\n\n  std::cout\n    << \"Printing all the non-zero entries for row 42 before renumbering: \"\n    << \"\\n\";\n\n  auto start_row_42 = sparsity_pattern.begin(42);\n  auto end_row_42   = sparsity_pattern.end(42);\n  for (auto it = start_row_42; it != end_row_42; ++it)\n    {\n      std::cout << (*it).column() << \"\\n\";\n    }\n}\n\n\n\nvoid\nrenumber_dofs(DoFHandler<2> &dof_handler)\n{\n  DoFRenumbering::Cuthill_McKee(dof_handler);\n\n  DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs(),\n                                                  dof_handler.n_dofs());\n  DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern);\n\n  SparsityPattern sparsity_pattern;\n  sparsity_pattern.copy_from(dynamic_sparsity_pattern);\n\n\n  std::cout << \"Row length for Line 42: \" << sparsity_pattern.row_length(42)\n            << \"\\n\";\n\n  show_statistics(sparsity_pattern); // Bonus\n  std::ofstream out(\"sparsity_pattern2.svg\");\n  sparsity_pattern.print_svg(out);\n\n  std::cout\n    << \"Printing all the non-zero entries for row 42 after renumbering: \"\n    << \"\\n\";\n  for (auto it = sparsity_pattern.begin(42); it != sparsity_pattern.end(42);\n       ++it)\n    {\n      std::cout << (*it).column() << \"\\n\";\n    }\n}\n\n\nvoid\nmake_grid_square(Triangulation<2> &square)\n{\n  GridGenerator::hyper_cube(square, -1, 1);\n  square.refine_global(3);\n}\n\n\n\nint\nmain()\n{\n  Triangulation<2> triangulation;\n  make_grid(triangulation);\n\n  DoFHandler<2> dof_handler(triangulation);\n\n  distribute_dofs(dof_handler);\n  renumber_dofs(dof_handler);\n\n\n  // //Test with a square\n  // Triangulation<2> square;\n  // make_grid_square(square);\n\n  // DoFHandler<2> dof_handler_square(square);\n\n  // distribute_dofs(dof_handler_square);\n  // renumber_dofs(dof_handler_square);\n}\n", "meta": {"hexsha": "b9cb4fb5e434beb3402e33fee22cdc3692d7a4c6", "size": 5803, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/step-2.cc", "max_stars_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-fdrmrc", "max_stars_repo_head_hexsha": "62ce89931f91be19b4824b9c7064029cd9729311", "max_stars_repo_licenses": ["MIT"], "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/step-2.cc", "max_issues_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-fdrmrc", "max_issues_repo_head_hexsha": "62ce89931f91be19b4824b9c7064029cd9729311", "max_issues_repo_licenses": ["MIT"], "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/step-2.cc", "max_forks_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-fdrmrc", "max_forks_repo_head_hexsha": "62ce89931f91be19b4824b9c7064029cd9729311", "max_forks_repo_licenses": ["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.8990384615, "max_line_length": 77, "alphanum_fraction": 0.6300189557, "num_tokens": 1479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5262562702876252}}
{"text": "#include <tuple>\n#include <vector>\n#include <string>\n#include <cmath>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <boost/optional/optional_io.hpp>\n\n#include \"CommonSetting.h\"\n#include \"SamplingGrid.h\"\n\nusing cgal = CGAL::Exact_predicates_inexact_constructions_kernel;\n\npl::SamplingGrid::SamplingGrid() : width(0), height(0) {}\n\npl::SamplingGrid::SamplingGrid(int w, int h) : width(w), height(h) {}\n\npl::SamplingGrid::SamplingGrid(CommonSetting common_setting) : SamplingGrid() {\n  std::string sampling_grid = common_setting.val;\n\n  auto t = pl::split(sampling_grid, 'x');\n  width = std::stoi(t[0]);\n  height = std::stoi(t[1]);\n}\n\npl::SamplingGrid &pl::SamplingGrid::operator=(const SamplingGrid &cs) {\n  width = cs.width;\n  height = cs.height;\n  return *this;\n}\n\nbool pl::SamplingGrid::isOutOfArea(const cgal::Point_2 p) const {\n  return p.x() < 0 || width < p.x() || p.y() < 0 || height < p.y();\n}\n\nbool pl::SamplingGrid::isInsideOfArea(const cgal::Point_2 p) const {\n  return (0 - 1.0e-10) <= p.x() && p.x() <= (width + 1.0e-10) && (0 - 1.0e-10) <= p.y() && p.y() <= (height + 1.0e-10);\n}\n\nstd::tuple<cgal::Point_2, cgal::Point_2> pl::SamplingGrid::intersection(const cgal::Line_2 &line) const {\n  std::vector<cgal::Segment_2> border = {\n    {{width, height}, {0, height}},\n    {{width, 0}, {width, height}},\n    {{0, 0}, {width, 0}},\n    {{0, height}, {0, 0}}\n  };\n\n  std::vector<cgal::Point_2> intersections;\n\n  for (auto segment : border)\n    if (const auto point = CGAL::intersection(cgal::Line_2{segment}, line); point && isInsideOfArea(boost::get<cgal::Point_2>(*point)))\n      intersections.push_back(boost::get<cgal::Point_2>(*point));\n\n  if (intersections.size() < 2 || 2 < intersections.size()) {\n    std::cout << \"intersection with border does have more then 2 or less then 2 intersections\" << \"\\n\";\n    std::exit(-1);\n  }\n\n  return {intersections[0], intersections[1]};\n}\n\ncgal::Point_2 pl::SamplingGrid::center() const {\n  cgal::Point_2 p(0, 0), q(width, 0), r(0, height);\n  const auto circle = cgal::Circle_2(p, q, r);\n  return circle.center();\n}\n\nstd::vector<cgal::Point_2> pl::SamplingGrid::points() const {\n  return {{0,0},{0,height},{width,height},{width,0}};\n}\n", "meta": {"hexsha": "56e59f6ce5ed1701f7b229904bb65b615db19410", "size": 2212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "server/src/SamplingGrid.cpp", "max_stars_repo_name": "utnapischtim/polygon", "max_stars_repo_head_hexsha": "4c926553f436199d643f43a0129610d8d67d72da", "max_stars_repo_licenses": ["MIT"], "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/SamplingGrid.cpp", "max_issues_repo_name": "utnapischtim/polygon", "max_issues_repo_head_hexsha": "4c926553f436199d643f43a0129610d8d67d72da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/src/SamplingGrid.cpp", "max_forks_repo_name": "utnapischtim/polygon", "max_forks_repo_head_hexsha": "4c926553f436199d643f43a0129610d8d67d72da", "max_forks_repo_licenses": ["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.1549295775, "max_line_length": 135, "alphanum_fraction": 0.6559674503, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5262088011749807}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2012 Desire Nuentsa Wakam <desire.nuentsa_wakam@inria.fr>\n// Copyright (C) 2014 Gael Guennebaud <gael.guennebaud@inria.fr>\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#include \"sparse.h\"\n#include <Eigen/SparseQR>\n\ntemplate<typename MatrixType,typename DenseMat>\nint generate_sparse_rectangular_problem(MatrixType& A, DenseMat& dA, int maxRows = 300, int maxCols = 150)\n{\n  eigen_assert(maxRows >= maxCols);\n  typedef typename MatrixType::Scalar Scalar;\n  int rows = internal::random<int>(1,maxRows);\n  int cols = internal::random<int>(1,maxCols);\n  double density = (std::max)(8./(rows*cols), 0.01);\n  \n  A.resize(rows,cols);\n  dA.resize(rows,cols);\n  initSparse<Scalar>(density, dA, A,ForceNonZeroDiag);\n  A.makeCompressed();\n  int nop = internal::random<int>(0, internal::random<double>(0,1) > 0.5 ? cols/2 : 0);\n  for(int k=0; k<nop; ++k)\n  {\n    int j0 = internal::random<int>(0,cols-1);\n    int j1 = internal::random<int>(0,cols-1);\n    Scalar s = internal::random<Scalar>();\n    A.col(j0)  = s * A.col(j1);\n    dA.col(j0) = s * dA.col(j1);\n  }\n  \n//   if(rows<cols) {\n//     A.conservativeResize(cols,cols);\n//     dA.conservativeResize(cols,cols);\n//     dA.bottomRows(cols-rows).setZero();\n//   }\n  \n  return rows;\n}\n\ntemplate<typename Scalar> void test_sparseqr_scalar()\n{\n  typedef SparseMatrix<Scalar,ColMajor> MatrixType; \n  typedef Matrix<Scalar,Dynamic,Dynamic> DenseMat;\n  typedef Matrix<Scalar,Dynamic,1> DenseVector;\n  MatrixType A;\n  DenseMat dA;\n  DenseVector refX,x,b; \n  SparseQR<MatrixType, COLAMDOrdering<int> > solver; \n  generate_sparse_rectangular_problem(A,dA);\n  \n  b = dA * DenseVector::Random(A.cols());\n  solver.compute(A);\n  if(internal::random<float>(0,1)>0.5f)\n    solver.factorize(A);  // this checks that calling analyzePattern is not needed if the pattern do not change.\n  if (solver.info() != MySuccess)\n  {\n    std::cerr << \"sparse QR factorization failed\\n\";\n    exit(0);\n    return;\n  }\n  x = solver.solve(b);\n  if (solver.info() != MySuccess)\n  {\n    std::cerr << \"sparse QR factorization failed\\n\";\n    exit(0);\n    return;\n  }\n  \n  VERIFY_IS_APPROX(A * x, b);\n  \n  //Compare with a dense QR solver\n  ColPivHouseholderQR<DenseMat> dqr(dA);\n  refX = dqr.solve(b);\n  \n  VERIFY_IS_EQUAL(dqr.rank(), solver.rank());\n  if(solver.rank()==A.cols()) // full rank\n    VERIFY_IS_APPROX(x, refX);\n//   else\n//     VERIFY((dA * refX - b).norm() * 2 > (A * x - b).norm() );\n\n  // Compute explicitly the matrix Q\n  MatrixType Q, QtQ, idM;\n  Q = solver.matrixQ();\n  //Check  ||Q' * Q - I ||\n  QtQ = Q * Q.adjoint();\n  idM.resize(Q.rows(), Q.rows()); idM.setIdentity();\n  VERIFY(idM.isApprox(QtQ));\n  \n  // Q to dense\n  DenseMat dQ;\n  dQ = solver.matrixQ();\n  VERIFY_IS_APPROX(Q, dQ);\n}\nvoid test_sparseqr()\n{\n  for(int i=0; i<g_repeat; ++i)\n  {\n    CALL_SUBTEST_1(test_sparseqr_scalar<double>());\n    CALL_SUBTEST_2(test_sparseqr_scalar<std::complex<double> >());\n  }\n}\n\n", "meta": {"hexsha": "e1d01c4474bb161ad9e2b3e93b14a4a898e2aa5f", "size": 3098, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "A4-paper-sheet-detection-and-cropping/Header_files/eigen/test/sparseqr.cpp", "max_stars_repo_name": "satvik007/Scanner_OP", "max_stars_repo_head_hexsha": "c146f67e3851cd537d62989842abfee7d34de2c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A4-paper-sheet-detection-and-cropping/Header_files/eigen/test/sparseqr.cpp", "max_issues_repo_name": "satvik007/Scanner_OP", "max_issues_repo_head_hexsha": "c146f67e3851cd537d62989842abfee7d34de2c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A4-paper-sheet-detection-and-cropping/Header_files/eigen/test/sparseqr.cpp", "max_forks_repo_name": "satvik007/Scanner_OP", "max_forks_repo_head_hexsha": "c146f67e3851cd537d62989842abfee7d34de2c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-10T10:14:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T10:14:27.000Z", "avg_line_length": 28.953271028, "max_line_length": 112, "alphanum_fraction": 0.6591349258, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5262087994968749}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Framework/TestingFramework.hpp\"\n\n#include <boost/math/quaternion.hpp>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"Domain/FunctionsOfTime/QuaternionHelpers.hpp\"\n#include \"Utilities/Gsl.hpp\"\n\nSPECTRE_TEST_CASE(\"Unit.Domain.FunctionsOfTime.QuaternionHelpers\",\n                  \"[Unit][Domain]\") {\n  using quaternion = boost::math::quaternion<double>;\n\n  quaternion quat1(1.0, 2.0, 3.0, -4.0);\n  DataVector dv{1.0, 2.0, 3.0, -4.0};\n  DataVector dv_short{9.9, 9.8, 9.7};\n\n  DataVector dv2 = quaternion_to_datavector(quat1);\n  CHECK(dv2 == dv);\n\n  quaternion quat2 = datavector_to_quaternion(dv2);\n  CHECK(quat2 == quat1);\n\n  quaternion quat3 = datavector_to_quaternion(dv_short);\n  CHECK(quat3 == quaternion{0.0, 9.9, 9.8, 9.7});\n\n  normalize_quaternion(make_not_null(&quat2));\n  CHECK(norm(quat2) == approx(1.0));\n  CHECK(abs(quat2) == approx(1.0));\n}\n", "meta": {"hexsha": "90132c5ec05af7859ab6eed166365c46583415dd", "size": 938, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/Domain/FunctionsOfTime/Test_QuaternionHelpers.cpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 117.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T22:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:23:36.000Z", "max_issues_repo_path": "tests/Unit/Domain/FunctionsOfTime/Test_QuaternionHelpers.cpp", "max_issues_repo_name": "GitHimanshuc/spectre", "max_issues_repo_head_hexsha": "4de4033ba36547113293fe4dbdd77591485a4aee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3177.0, "max_issues_repo_issues_event_min_datetime": "2017-04-07T21:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:59.000Z", "max_forks_repo_path": "tests/Unit/Domain/FunctionsOfTime/Test_QuaternionHelpers.cpp", "max_forks_repo_name": "geoffrey4444/spectre", "max_forks_repo_head_hexsha": "9350d61830b360e2d5b273fdd176dcc841dbefb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2017-04-07T19:36:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T10:21:00.000Z", "avg_line_length": 28.4242424242, "max_line_length": 66, "alphanum_fraction": 0.7046908316, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5262087943583007}}
{"text": "/**\n * @file momentum_sgd_test.cpp\n * @author Ryan Curtin\n *\n * Test file for MomentumSGD (stochastic gradient descent with momentum updates).\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/optimizers/sgd/sgd.hpp>\n#include <mlpack/core/optimizers/sgd/update_policies/gradient_clipping.hpp>\n#include <mlpack/core/optimizers/sgd/update_policies/momentum_update.hpp>\n#include <mlpack/core/optimizers/problems/generalized_rosenbrock_function.hpp>\n#include <mlpack/core/optimizers/problems/sgd_test_function.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace std;\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::optimization;\nusing namespace mlpack::optimization::test;\n\nBOOST_AUTO_TEST_SUITE(MomentumSGDTest);\n\nBOOST_AUTO_TEST_CASE(MomentumSGDSpeedUpTestFunction)\n{\n  SGDTestFunction f;\n  MomentumUpdate momentumUpdate(0.7);\n  MomentumSGD s(0.0003, 1, 2500000, 1e-9, true, momentumUpdate);\n\n  arma::mat coordinates = f.GetInitialPoint();\n  double result = s.Optimize(f, coordinates);\n\n  BOOST_REQUIRE_CLOSE(result, -1.0, 0.15);\n  BOOST_REQUIRE_SMALL(coordinates[0], 1e-3);\n  BOOST_REQUIRE_SMALL(coordinates[1], 1e-7);\n  BOOST_REQUIRE_SMALL(coordinates[2], 1e-7);\n\n  // Compare with SGD with vanilla update.\n  SGDTestFunction f1;\n  StandardSGD s1(0.0003, 1, 2500000, 1e-9, true);\n\n  arma::mat coordinates1 = f.GetInitialPoint();\n  double result1 = s1.Optimize(f1, coordinates1);\n\n  // Result doesn't converge in 2500000 iterations.\n  BOOST_REQUIRE_GT(result1 + 1.0, 0.05);\n  BOOST_REQUIRE_GE(coordinates1[0], 1e-3);\n  BOOST_REQUIRE_SMALL(coordinates1[1], 1e-7);\n  BOOST_REQUIRE_SMALL(coordinates1[2], 1e-7);\n\n  BOOST_REQUIRE_LE(result, result1);\n}\n\nBOOST_AUTO_TEST_CASE(GeneralizedRosenbrockTest)\n{\n  // Loop over several variants.\n  for (size_t i = 10; i < 50; i += 5)\n  {\n    // Create the generalized Rosenbrock function.\n    GeneralizedRosenbrockFunction f(i);\n    MomentumUpdate momentumUpdate(0.4);\n    MomentumSGD s(0.0008, 1, 0, 1e-15, true, momentumUpdate);\n\n    arma::mat coordinates = f.GetInitialPoint();\n    double result = s.Optimize(f, coordinates);\n\n    BOOST_REQUIRE_SMALL(result, 1e-4);\n    for (size_t j = 0; j < i; ++j)\n      BOOST_REQUIRE_CLOSE(coordinates[j], (double) 1.0, 1e-3);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "ba1932c3bb580bd23ecd73a8699dcfb62b0e5769", "size": 2585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/momentum_sgd_test.cpp", "max_stars_repo_name": "MJ10/mlpack", "max_stars_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "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-05-02T21:10:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T21:10:55.000Z", "max_issues_repo_path": "src/mlpack/tests/momentum_sgd_test.cpp", "max_issues_repo_name": "MJ10/mlpack", "max_issues_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "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/momentum_sgd_test.cpp", "max_forks_repo_name": "MJ10/mlpack", "max_forks_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "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.3125, "max_line_length": 81, "alphanum_fraction": 0.7462282398, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5262087840811521}}
{"text": "#ifndef SEQUENTIAL_LINE_SEARCH_ACQUISITION_FUNCTION_HPP\n#define SEQUENTIAL_LINE_SEARCH_ACQUISITION_FUNCTION_HPP\n\n#include <Eigen/Core>\n#include <memory>\n#include <sequential-line-search/regressor.hpp>\n#include <vector>\n\nnamespace sequential_line_search\n{\n    enum class AcquisitionFuncType\n    {\n        ExpectedImprovement,\n        GaussianProcessUpperConfidenceBound,\n    };\n\n    namespace acquisition_func\n    {\n        /// \\brief Calculate the value of the acquisition function value.\n        ///\n        /// \\param function_type Type of the acquisition function.\n        ///\n        /// \\param gaussian_process_upper_confidence_bound_hyperparam The hyperparameter in the GP-UCB algorithm, which\n        /// controls the trade-off of exploration and exploitation. If the acquisition function is not GP-UCB, this\n        /// value will not be used.\n        double CalcAcquisitionValue(const Regressor&          regressor,\n                                    const Eigen::VectorXd&    x,\n                                    const AcquisitionFuncType func_type,\n                                    const double              gaussian_process_upper_confidence_bound_hyperparam = 1.0);\n\n        /// \\param gaussian_process_upper_confidence_bound_hyperparam The hyperparameter in the GP-UCB algorithm, which\n        /// controls the trade-off of exploration and exploitation. If the acquisition function is not GP-UCB, this\n        /// value will not be used.\n        Eigen::VectorXd\n        CalcAcquisitionValueDerivative(const Regressor&          regressor,\n                                       const Eigen::VectorXd&    x,\n                                       const AcquisitionFuncType func_type,\n                                       const double gaussian_process_upper_confidence_bound_hyperparam = 1.0);\n\n        /// \\param num_global_search_iters The number of trials of acquisition value maximization. Specifying a large\n        /// number is helpful for finding the global maximizer while it increases the computational cost proportional to\n        /// it.\n        ///\n        /// \\param gaussian_process_upper_confidence_bound_hyperparam The hyperparameter in the GP-UCB algorithm, which\n        /// controls the trade-off of exploration and exploitation. If the acquisition function is not GP-UCB, this\n        /// value will not be used.\n        Eigen::VectorXd FindNextPoint(const Regressor&          regressor,\n                                      const unsigned            num_global_search_iters = 100,\n                                      const unsigned            num_local_search_iters  = 50,\n                                      const AcquisitionFuncType func_type = AcquisitionFuncType::ExpectedImprovement,\n                                      const double gaussian_process_upper_confidence_bound_hyperparam = 1.0);\n\n        /// \\brief Find the next n sampled points that should be observed.\n        ///\n        /// \\details The points will be determined by Schonlau et al.'s method [1998]. This method determines the points\n        /// one by one sequentially by maximizing the acquisition function. In each maximization, the variance of the\n        /// surrogate function (or the covariance matrix of the underlying GP model) is updated using the newly sampled\n        /// point, by which it avoids sampling similar points.\n        ///\n        /// Matthias Schonlau, William J. Welch, and Donald R. Jones. 1998. Global versus local search in constrained\n        /// optimization of computer models. Institute of Mathematical Statistics Lecture Notes - Monograph Series,\n        /// 1998: 11-25 (1998). DOI: https://doi.org/10.1214/lnms/1215456182\n        ///\n        /// \\param num_points The number of the sampled points.\n        ///\n        /// \\param num_global_search_iters The number of trials of acquisition value maximization. Specifying a large\n        /// number is helpful for finding the global maximizer while it increases the computational cost proportional to\n        /// it.\n        ///\n        /// \\param gaussian_process_upper_confidence_bound_hyperparam The hyperparameter in the GP-UCB algorithm, which\n        /// controls the trade-off of exploration and exploitation. If the acquisition function is not GP-UCB, this\n        /// value will not be used.\n        std::vector<Eigen::VectorXd>\n        FindNextPoints(const Regressor&          regressor,\n                       const unsigned            num_points,\n                       const unsigned            num_global_search_iters = 100,\n                       const unsigned            num_local_search_iters  = 50,\n                       const AcquisitionFuncType func_type               = AcquisitionFuncType::ExpectedImprovement,\n                       const double              gaussian_process_upper_confidence_bound_hyperparam = 1.0);\n    } // namespace acquisition_func\n} // namespace sequential_line_search\n\n#endif // SEQUENTIAL_LINE_SEARCH_ACQUISITION_FUNCTION_HPP\n", "meta": {"hexsha": "b9452920cbe0e1c4ae1d20a3b9896046f5212f76", "size": 4979, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sequential-line-search/acquisition-function.hpp", "max_stars_repo_name": "yuki-koyama/sequential-line-search", "max_stars_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2018-03-12T13:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T20:28:04.000Z", "max_issues_repo_path": "include/sequential-line-search/acquisition-function.hpp", "max_issues_repo_name": "yuki-koyama/sequential-line-search", "max_issues_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T23:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T03:52:42.000Z", "max_forks_repo_path": "include/sequential-line-search/acquisition-function.hpp", "max_forks_repo_name": "yuki-koyama/sequential-line-search", "max_forks_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-06-12T17:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T11:13:03.000Z", "avg_line_length": 59.2738095238, "max_line_length": 120, "alphanum_fraction": 0.6443060856, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.526208784081152}}
{"text": "/*\n * NativeFilterMatrixOps.cpp\n *\n *  Created on: Sep 5, 2018\n *      Author: Georg Wiedebach\n */\n\n#include <jni.h>\n#include <Eigen/Dense>\n#include \"us_ihmc_ekf_filter_NativeFilterMatrixOpsWrapper.h\"\n\nusing Eigen::MatrixXd;\n\ntypedef Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> JMatrixMap;\n\nJNIEXPORT void JNICALL Java_us_ihmc_ekf_filter_NativeFilterMatrixOpsWrapper_computeABAt(JNIEnv *env, jobject thisObj, jdoubleArray result,\n      jdoubleArray aData, jdoubleArray bData, jint n, jint m)\n{\n   jdouble *aDataArray = (jdouble*) env->GetPrimitiveArrayCritical(aData, NULL);\n   jdouble *bDataArray = (jdouble*) env->GetPrimitiveArrayCritical(bData, NULL);\n   jdouble *resultDataArray = (jdouble*) env->GetPrimitiveArrayCritical(result, NULL);\n\n   JMatrixMap A(aDataArray, n, m);\n   JMatrixMap B(bDataArray, m, m);\n   JMatrixMap ABAt(resultDataArray, n, n);\n\n   ABAt.noalias() = A * B * A.transpose();\n\n   env->ReleasePrimitiveArrayCritical(aData, aDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(bData, bDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(result, resultDataArray, 0);\n}\n\nJNIEXPORT void JNICALL Java_us_ihmc_ekf_filter_NativeFilterMatrixOpsWrapper_predictErrorCovariance\n  (JNIEnv *env, jobject thisObj, jdoubleArray result, jdoubleArray fData, jdoubleArray pData, jdoubleArray qData, jint n)\n{\n   jdouble *fDataArray = (jdouble*) env->GetPrimitiveArrayCritical(fData, NULL);\n   jdouble *pDataArray = (jdouble*) env->GetPrimitiveArrayCritical(pData, NULL);\n   jdouble *qDataArray = (jdouble*) env->GetPrimitiveArrayCritical(qData, NULL);\n   jdouble *resultDataArray = (jdouble*) env->GetPrimitiveArrayCritical(result, NULL);\n\n   JMatrixMap F(fDataArray, n, n);\n   JMatrixMap P(pDataArray, n, n);\n   JMatrixMap Q(qDataArray, n, n);\n   JMatrixMap errorCovariance(resultDataArray, n, n);\n\n   MatrixXd Qdiag = Q.diagonal().asDiagonal();\n   errorCovariance.noalias() = F * P.selfadjointView<Eigen::Upper>() * F.transpose() + Qdiag;\n\n   env->ReleasePrimitiveArrayCritical(fData, fDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(pData, pDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(qData, qDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(result, resultDataArray, 0);\n}\n\nJNIEXPORT void JNICALL Java_us_ihmc_ekf_filter_NativeFilterMatrixOpsWrapper_updateErrorCovariance\n  (JNIEnv *env, jobject thisObj, jdoubleArray result, jdoubleArray kData, jdoubleArray hData, jdoubleArray pData, jint n, jint m)\n{\n   jdouble *kDataArray = (jdouble*) env->GetPrimitiveArrayCritical(kData, NULL);\n   jdouble *hDataArray = (jdouble*) env->GetPrimitiveArrayCritical(hData, NULL);\n   jdouble *pDataArray = (jdouble*) env->GetPrimitiveArrayCritical(pData, NULL);\n   jdouble *resultDataArray = (jdouble*) env->GetPrimitiveArrayCritical(result, NULL);\n\n   JMatrixMap K(kDataArray, m, n);\n   JMatrixMap H(hDataArray, n, m);\n   JMatrixMap P(pDataArray, m, m);\n   JMatrixMap errorCovariance(resultDataArray, m, m);\n\n   errorCovariance.noalias() = (MatrixXd::Identity(m, m) - K * H) * P.selfadjointView<Eigen::Upper>();\n\n   env->ReleasePrimitiveArrayCritical(kData, kDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(hData, hDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(pData, pDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(result, resultDataArray, 0);\n}\n\nJNIEXPORT void JNICALL Java_us_ihmc_ekf_filter_NativeFilterMatrixOpsWrapper_computeKalmanGain\n  (JNIEnv *env, jobject thisObj, jdoubleArray result, jdoubleArray pData, jdoubleArray hData, jdoubleArray rData, jint n, jint m)\n{\n   jdouble *pDataArray = (jdouble*) env->GetPrimitiveArrayCritical(pData, NULL);\n   jdouble *hDataArray = (jdouble*) env->GetPrimitiveArrayCritical(hData, NULL);\n   jdouble *rDataArray = (jdouble*) env->GetPrimitiveArrayCritical(rData, NULL);\n   jdouble *resultDataArray = (jdouble*) env->GetPrimitiveArrayCritical(result, NULL);\n\n   JMatrixMap P(pDataArray, m, m);\n   JMatrixMap H(hDataArray, n, m);\n   JMatrixMap R(rDataArray, n, n);\n   JMatrixMap gain(resultDataArray, m, n);\n\n   MatrixXd PHt = P.selfadjointView<Eigen::Upper>() * H.transpose();\n   MatrixXd Rdiag = R.diagonal().asDiagonal();\n   MatrixXd toInvert = H * PHt + Rdiag;\n   gain.noalias() = PHt * toInvert.inverse();\n\n   env->ReleasePrimitiveArrayCritical(pData, pDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(hData, hDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(rData, rDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(result, resultDataArray, 0);\n}\n\nJNIEXPORT void JNICALL Java_us_ihmc_ekf_filter_NativeFilterMatrixOpsWrapper_updateState\n  (JNIEnv *env, jobject thisObj, jdoubleArray result, jdoubleArray xData, jdoubleArray kData, jdoubleArray rData, jint n, jint m)\n{\n   jdouble *xDataArray = (jdouble*) env->GetPrimitiveArrayCritical(xData, NULL);\n   jdouble *kDataArray = (jdouble*) env->GetPrimitiveArrayCritical(kData, NULL);\n   jdouble *rDataArray = (jdouble*) env->GetPrimitiveArrayCritical(rData, NULL);\n   jdouble *resultDataArray = (jdouble*) env->GetPrimitiveArrayCritical(result, NULL);\n\n   JMatrixMap x(xDataArray, n, 1);\n   JMatrixMap K(kDataArray, n, m);\n   JMatrixMap r(rDataArray, m, 1);\n   JMatrixMap state(resultDataArray, n, 1);\n\n   state.noalias() = x + K * r;\n\n   env->ReleasePrimitiveArrayCritical(xData, xDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(kData, kDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(rData, rDataArray, 0);\n   env->ReleasePrimitiveArrayCritical(result, resultDataArray, 0);\n}\n", "meta": {"hexsha": "26577944b3fd263c4d42a4ae1bcfce01e15a2aa4", "size": 5468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nativeEKF/NativeFilterMatrixOps.cpp", "max_stars_repo_name": "ihmcrobotics/ekf", "max_stars_repo_head_hexsha": "afcc24544109057d862023fdab6178dac1c2a6c2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-08T17:55:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T17:55:53.000Z", "max_issues_repo_path": "nativeEKF/NativeFilterMatrixOps.cpp", "max_issues_repo_name": "ihmcrobotics/ekf", "max_issues_repo_head_hexsha": "afcc24544109057d862023fdab6178dac1c2a6c2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-20T11:19:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-20T17:47:58.000Z", "max_forks_repo_path": "nativeEKF/NativeFilterMatrixOps.cpp", "max_forks_repo_name": "ihmcrobotics/ekf", "max_forks_repo_head_hexsha": "afcc24544109057d862023fdab6178dac1c2a6c2", "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": 45.1900826446, "max_line_length": 138, "alphanum_fraction": 0.7574981712, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5261663326967798}}
{"text": "//  (C) Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <pch.hpp>\r\n\r\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\r\n\r\n#include <boost/math/concepts/real_concept.hpp>\r\n#include <boost/math/special_functions/gamma.hpp>\r\n#include <boost/test/test_exec_monitor.hpp>\r\n#include <boost/test/results_collector.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/math/tools/stats.hpp>\r\n#include <boost/math/tools/test.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/type_traits/is_floating_point.hpp>\r\n#include <boost/array.hpp>\r\n#include \"functor.hpp\"\r\n\r\n#include \"handle_test_result.hpp\"\r\n\r\n#if !defined(TEST_FLOAT) && !defined(TEST_DOUBLE) && !defined(TEST_LDOUBLE) && !defined(TEST_REAL_CONCEPT)\r\n#  define TEST_FLOAT\r\n#  define TEST_DOUBLE\r\n#  define TEST_LDOUBLE\r\n#  define TEST_REAL_CONCEPT\r\n#endif\r\n\r\n//\r\n// DESCRIPTION:\r\n// ~~~~~~~~~~~~\r\n//\r\n// This file tests the incomplete gamma function inverses \r\n// gamma_p_inva and gamma_q_inva. There are two sets of tests:\r\n// 2) TODO: Accuracy tests use values generated with NTL::RR at \r\n// 1000-bit precision and our generic versions of these functions.\r\n// 3) Round trip sanity checks, use the test data for the forward\r\n// functions, and verify that we can get (approximately) back\r\n// where we started.\r\n//\r\n// Note that when this file is first run on a new platform many of\r\n// these tests will fail: the default accuracy is 1 epsilon which\r\n// is too tight for most platforms.  In this situation you will \r\n// need to cast a human eye over the error rates reported and make\r\n// a judgement as to whether they are acceptable.  Either way please\r\n// report the results to the Boost mailing list.  Acceptable rates of\r\n// error are marked up below as a series of regular expressions that\r\n// identify the compiler/stdlib/platform/data-type/test-data/test-function\r\n// along with the maximum expected peek and RMS mean errors for that\r\n// test.\r\n//\r\n\r\nvoid expected_results()\r\n{\r\n   //\r\n   // Define the max and mean errors expected for\r\n   // various compilers and platforms.\r\n   //\r\n   const char* largest_type;\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())\r\n   {\r\n      largest_type = \"(long\\\\s+)?double\";\r\n   }\r\n   else\r\n   {\r\n      largest_type = \"long double\";\r\n   }\r\n#else\r\n   largest_type = \"(long\\\\s+)?double\";\r\n#endif\r\n   //\r\n   // Linux:\r\n   //\r\n   add_expected_result(\r\n      \"[^|]*\",                          // compiler\r\n      \"[^|]*\",                          // stdlib\r\n      \"linux\",                          // platform\r\n      largest_type,                     // test type(s)\r\n      \"[^|]*\",                          // test data group\r\n      \"[^|]*\", 800, 200);               // test function\r\n\r\n   //\r\n   // Catch all cases come last:\r\n   //\r\n   add_expected_result(\r\n      \"[^|]*\",                          // compiler\r\n      \"[^|]*\",                          // stdlib\r\n      \"[^|]*\",                          // platform\r\n      \"real_concept\",                   // test type(s)\r\n      \"[^|]*\",                          // test data group\r\n      \"[^|]*\", 3000, 1000);             // test function\r\n   add_expected_result(\r\n      \"[^|]*\",                          // compiler\r\n      \"[^|]*\",                          // stdlib\r\n      \"[^|]*\",                          // platform\r\n      largest_type,                     // test type(s)\r\n      \"[^|]*\",                          // test data group\r\n      \"[^|]*\", 300, 100);               // test function\r\n   // this one has to come last in case double *is* the widest\r\n   // float type:\r\n   add_expected_result(\r\n      \"[^|]*\",                          // compiler\r\n      \"[^|]*\",                          // stdlib\r\n      \"[^|]*\",                          // platform\r\n      \"float|double\",                   // test type(s)\r\n      \"[^|]*\",                          // test data group\r\n      \"[^|]*\", 10, 5);                 // test function\r\n   //\r\n   // Finish off by printing out the compiler/stdlib/platform names,\r\n   // we do this to make it easier to mark up expected error rates.\r\n   //\r\n   std::cout << \"Tests run with \" << BOOST_COMPILER << \", \" \r\n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << std::endl;\r\n}\r\n\r\n#define BOOST_CHECK_CLOSE_EX(a, b, prec, i) \\\r\n   {\\\r\n      unsigned int failures = boost::unit_test::results_collector.results( boost::unit_test::framework::current_test_case().p_id ).p_assertions_failed;\\\r\n      BOOST_CHECK_CLOSE(a, b, prec); \\\r\n      if(failures != boost::unit_test::results_collector.results( boost::unit_test::framework::current_test_case().p_id ).p_assertions_failed)\\\r\n      {\\\r\n         std::cerr << \"Failure was at row \" << i << std::endl;\\\r\n         std::cerr << std::setprecision(35); \\\r\n         std::cerr << \"{ \" << data[i][0] << \" , \" << data[i][1] << \" , \" << data[i][2];\\\r\n         std::cerr << \" , \" << data[i][3] << \" , \" << data[i][4] << \" , \" << data[i][5] << \" } \" << std::endl;\\\r\n      }\\\r\n   }\r\n\r\ntemplate <class T>\r\nvoid do_test_gamma_2(const T& data, const char* type_name, const char* test_name)\r\n{\r\n   //\r\n   // test gamma_p_inva(T, T) against data:\r\n   //\r\n   using namespace std;\r\n   typedef typename T::value_type row_type;\r\n   typedef typename row_type::value_type value_type;\r\n\r\n   std::cout << test_name << \" with type \" << type_name << std::endl;\r\n\r\n   //\r\n   // These sanity checks test for a round trip accuracy of one half\r\n   // of the bits in T, unless T is type float, in which case we check\r\n   // for just one decimal digit.  The problem here is the sensitivity\r\n   // of the functions, not their accuracy.  This test data was generated\r\n   // for the forward functions, which means that when it is used as\r\n   // the input to the inverses then it is necessarily inexact.  This rounding\r\n   // of the input is what makes the data unsuitable for use as an accuracy check,\r\n   // and also demonstrates that you can't in general round-trip these functions.\r\n   // It is however a useful sanity check.\r\n   //\r\n   value_type precision = static_cast<value_type>(ldexp(1.0, 1-boost::math::policies::digits<value_type, boost::math::policies::policy<> >()/2)) * 100;\r\n   if(boost::math::policies::digits<value_type, boost::math::policies::policy<> >() < 50)\r\n      precision = 1;   // 1% or two decimal digits, all we can hope for when the input is truncated to float\r\n\r\n   for(unsigned i = 0; i < data.size(); ++i)\r\n   {\r\n      //\r\n      // These inverse tests are thrown off if the output of the\r\n      // incomplete gamma is too close to 1: basically there is insuffient\r\n      // information left in the value we're using as input to the inverse\r\n      // to be able to get back to the original value.\r\n      //\r\n      if(data[i][5] == 0)\r\n         BOOST_CHECK_EQUAL(boost::math::gamma_p_inva(data[i][1], data[i][5]), boost::math::tools::max_value<value_type>());\r\n      else if((1 - data[i][5] > 0.001) && (fabs(data[i][5]) > 2 * boost::math::tools::min_value<value_type>()))\r\n      {\r\n         value_type inv = boost::math::gamma_p_inva(data[i][1], data[i][5]);\r\n         BOOST_CHECK_CLOSE_EX(data[i][0], inv, precision, i);\r\n      }\r\n      else if(1 == data[i][5])\r\n         BOOST_CHECK_EQUAL(boost::math::gamma_p_inva(data[i][1], data[i][5]), boost::math::tools::min_value<value_type>());\r\n      else if(data[i][5] > 2 * boost::math::tools::min_value<value_type>())\r\n      {\r\n         // not enough bits in our input to get back to x, but we should be in\r\n         // the same ball park:\r\n         value_type inv = boost::math::gamma_p_inva(data[i][1], data[i][5]);\r\n         BOOST_CHECK_CLOSE_EX(data[i][0], inv, 100, i);\r\n      }\r\n\r\n      if(data[i][3] == 0)\r\n         BOOST_CHECK_EQUAL(boost::math::gamma_q_inva(data[i][1], data[i][3]), boost::math::tools::min_value<value_type>());\r\n      else if((1 - data[i][3] > 0.001) \r\n         && (fabs(data[i][3]) > 2 * boost::math::tools::min_value<value_type>()) \r\n         && (fabs(data[i][3]) > 2 * boost::math::tools::min_value<double>()))\r\n      {\r\n         value_type inv = boost::math::gamma_q_inva(data[i][1], data[i][3]);\r\n         BOOST_CHECK_CLOSE_EX(data[i][0], inv, precision, i);\r\n      }\r\n      else if(1 == data[i][3])\r\n         BOOST_CHECK_EQUAL(boost::math::gamma_q_inva(data[i][1], data[i][3]), boost::math::tools::max_value<value_type>());\r\n      else if(data[i][3] > 2 * boost::math::tools::min_value<value_type>()) \r\n      {\r\n         // not enough bits in our input to get back to x, but we should be in\r\n         // the same ball park:\r\n         value_type inv = boost::math::gamma_q_inva(data[i][1], data[i][3]);\r\n         BOOST_CHECK_CLOSE_EX(data[i][0], inv, 100, i);\r\n      }\r\n   }\r\n   std::cout << std::endl;\r\n}\r\n\r\ntemplate <class T>\r\nvoid do_test_gamma_inva(const T& data, const char* type_name, const char* test_name)\r\n{\r\n   typedef typename T::value_type row_type;\r\n   typedef typename row_type::value_type value_type;\r\n\r\n   typedef value_type (*pg)(value_type, value_type);\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n   pg funcp = boost::math::gamma_p_inva<value_type, value_type>;\r\n#else\r\n   pg funcp = boost::math::gamma_p_inva;\r\n#endif\r\n\r\n   boost::math::tools::test_result<value_type> result;\r\n\r\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\r\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\r\n\r\n   //\r\n   // test gamma_p_inva(T, T) against data:\r\n   //\r\n   result = boost::math::tools::test(\r\n      data,\r\n      bind_func(funcp, 0, 1),\r\n      extract_result(2));\r\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::gamma_p_inva\", test_name);\r\n   //\r\n   // test gamma_q_inva(T, T) against data:\r\n   //\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n   funcp = boost::math::gamma_q_inva<value_type, value_type>;\r\n#else\r\n   funcp = boost::math::gamma_q_inva;\r\n#endif\r\n   result = boost::math::tools::test(\r\n      data,\r\n      bind_func(funcp, 0, 1),\r\n      extract_result(3));\r\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::gamma_q_inva\", test_name);\r\n}\r\n\r\ntemplate <class T>\r\nvoid test_gamma(T, const char* name)\r\n{\r\n   //\r\n   // The actual test data is rather verbose, so it's in a separate file\r\n   //\r\n   // First the data for the incomplete gamma function, each\r\n   // row has the following 6 entries:\r\n   // Parameter a, parameter z,\r\n   // Expected tgamma(a, z), Expected gamma_q(a, z)\r\n   // Expected tgamma_lower(a, z), Expected gamma_p(a, z)\r\n   //\r\n#  include \"igamma_med_data.ipp\"\r\n\r\n   do_test_gamma_2(igamma_med_data, name, \"Running round trip sanity checks on incomplete gamma medium sized values\");\r\n\r\n#  include \"igamma_small_data.ipp\"\r\n\r\n   do_test_gamma_2(igamma_small_data, name, \"Running round trip sanity checks on incomplete gamma small values\");\r\n\r\n#  include \"igamma_big_data.ipp\"\r\n\r\n   do_test_gamma_2(igamma_big_data, name, \"Running round trip sanity checks on incomplete gamma large values\");\r\n\r\n#  include \"igamma_inva_data.ipp\"\r\n\r\n   do_test_gamma_inva(igamma_inva_data, name, \"Incomplete gamma inverses.\");\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n   expected_results();\r\n   BOOST_MATH_CONTROL_FP;\r\n\r\n#ifndef BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS\r\n#ifdef TEST_FLOAT\r\n   test_gamma(0.1F, \"float\");\r\n#endif\r\n#endif\r\n#ifdef TEST_DOUBLE\r\n   test_gamma(0.1, \"double\");\r\n#endif\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n#ifdef TEST_LDOUBLE\r\n   test_gamma(0.1L, \"long double\");\r\n#endif\r\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\r\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\r\n#ifdef TEST_REAL_CONCEPT\r\n   test_gamma(boost::math::concepts::real_concept(0.1), \"real_concept\");\r\n#endif\r\n#endif\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   return 0;\r\n}\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "5b7099fec91032a84c31bbf1e7b7ece9b4b4d7e6", "size": 12369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_igamma_inva.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_igamma_inva.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_igamma_inva.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": 39.517571885, "max_line_length": 163, "alphanum_fraction": 0.6058695125, "num_tokens": 3142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.629774621301746, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.5261663294730498}}
{"text": "#include <benchmark/benchmark.h>\n\n#include <Eigen/Dense>\n#include <iostream>\n\n#include \"src/utils/distributions.h\"\n#include \"utils.h\"\n\nEigen::VectorXd lpdf_cov(const Eigen::MatrixXd &x, const Eigen::VectorXd &mean,\n                         const Eigen::MatrixXd &cov) {\n  Eigen::VectorXd out(x.rows());\n  for (int i = 0; i < x.rows(); i++) {\n    out(i) = stan::math::multi_normal_lpdf(x.row(i), mean, cov);\n  }\n  return out;\n}\n\nEigen::VectorXd lpdf_prec(const Eigen::MatrixXd &x,\n                          const Eigen::VectorXd &mean,\n                          const Eigen::MatrixXd &prec) {\n  Eigen::VectorXd out(x.rows());\n  for (int i = 0; i < x.rows(); i++) {\n    out(i) = stan::math::multi_normal_prec_lpdf(x.row(i), mean, prec);\n  }\n  return out;\n}\n\nEigen::VectorXd lpdf_naive(const Eigen::MatrixXd &x,\n                           const Eigen::VectorXd &mean,\n                           const Eigen::MatrixXd &prec_chol,\n                           double prec_logdet) {\n  Eigen::VectorXd out(x.rows());\n  for (int i = 0; i < x.rows(); i++) {\n    out(i) = bayesmix::multi_normal_prec_lpdf(x.row(i), mean, prec_chol,\n                                              prec_logdet);\n  }\n  return out;\n}\n\n\nEigen::VectorXd lpdf_fully_optimized(const Eigen::MatrixXd &x,\n                                     const Eigen::VectorXd &mean,\n                                     const Eigen::MatrixXd &prec_chol,\n                                     double prec_logdet) {\n  using stan::math::NEG_LOG_SQRT_TWO_PI;\n  Eigen::VectorXd exp =\n      ((x.rowwise() - mean.transpose()) * prec_chol).rowwise().squaredNorm();\n  Eigen::VectorXd base = Eigen::ArrayXd::Ones(x.rows()) * prec_logdet +\n                         NEG_LOG_SQRT_TWO_PI * x.cols();\n  return (base - exp) * 0.5;\n}\n\nstatic void BM_gauss_lpdf_cov(benchmark::State &state) {\n  int dim = state.range(0);\n  Eigen::VectorXd mean = Eigen::VectorXd::Zero(dim);\n  Eigen::MatrixXd cov = get_spd_matrix(dim);\n  Eigen::MatrixXd x = Eigen::MatrixXd::Ones(200, dim);\n  for (auto _ : state) {\n    lpdf_cov(x, mean, cov);\n  }\n}\n\nstatic void BM_gauss_lpdf_prec(benchmark::State &state) {\n  int dim = state.range(0);\n  Eigen::VectorXd mean = Eigen::VectorXd::Zero(dim);\n  Eigen::MatrixXd prec = get_spd_matrix(dim);\n  Eigen::MatrixXd x = Eigen::MatrixXd::Ones(200, dim);\n  for (auto _ : state) {\n    lpdf_prec(x, mean, prec);\n  }\n}\n\nstatic void BM_gauss_lpdf_naive(benchmark::State &state) {\n  int dim = state.range(0);\n  Eigen::VectorXd mean = Eigen::VectorXd::Zero(dim);\n  Eigen::MatrixXd prec = get_spd_matrix(dim);\n  Eigen::MatrixXd prec_chol = Eigen::LLT<Eigen::MatrixXd>(prec).matrixU();\n  Eigen::VectorXd diag = prec_chol.diagonal();\n  double prec_logdet = 2 * log(diag.array()).sum();\n  Eigen::MatrixXd x = Eigen::MatrixXd::Ones(200, dim);\n\n  for (auto _ : state) {\n    lpdf_naive(x, mean, prec_chol, prec_logdet);\n  }\n}\n\n\nstatic void BM_gauss_lpdf_fully_optimized(benchmark::State &state) {\n  int dim = state.range(0);\n  Eigen::VectorXd mean = Eigen::VectorXd::Zero(dim);\n  Eigen::MatrixXd prec = get_spd_matrix(dim);\n  Eigen::MatrixXd prec_chol = Eigen::LLT<Eigen::MatrixXd>(prec).matrixU();\n  Eigen::VectorXd diag = prec_chol.diagonal();\n  double prec_logdet = 2 * log(diag.array()).sum();\n  Eigen::MatrixXd x = Eigen::MatrixXd::Ones(200, dim);\n\n  for (auto _ : state) {\n    lpdf_fully_optimized(x, mean, prec_chol, prec_logdet);\n  }\n}\n\n\nBENCHMARK(BM_gauss_lpdf_cov)->RangeMultiplier(2)->Range(2, 2 << 4);\nBENCHMARK(BM_gauss_lpdf_cov)->RangeMultiplier(2)->Range(2, 2 << 4);\nBENCHMARK(BM_gauss_lpdf_naive)->RangeMultiplier(2)->Range(2, 2 << 4);\nBENCHMARK(BM_gauss_lpdf_fully_optimized)->RangeMultiplier(2)->Range(2, 2 << 4);\n", "meta": {"hexsha": "d297f59437332c946b871653b3012bcbe2fcd65f", "size": 3667, "ext": "cc", "lang": "C++", "max_stars_repo_path": "benchmarks/lpd_grid.cc", "max_stars_repo_name": "mberaha/bayesmix", "max_stars_repo_head_hexsha": "4448f0e9f69ac71f3aacc11a239e3114790c1aaa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-10-13T16:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T13:50:42.000Z", "max_issues_repo_path": "benchmarks/lpd_grid.cc", "max_issues_repo_name": "mberaha/bayesmix", "max_issues_repo_head_hexsha": "4448f0e9f69ac71f3aacc11a239e3114790c1aaa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-10-26T09:49:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:23:38.000Z", "max_forks_repo_path": "benchmarks/lpd_grid.cc", "max_forks_repo_name": "mberaha/bayesmix", "max_forks_repo_head_hexsha": "4448f0e9f69ac71f3aacc11a239e3114790c1aaa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2020-11-17T06:52:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T12:08:47.000Z", "avg_line_length": 34.2710280374, "max_line_length": 79, "alphanum_fraction": 0.622852468, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5261663165721675}}
{"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#ifndef BOOST_MATH_DIFFERENTIATION_FINITE_DIFFERENCE_HPP\n#define BOOST_MATH_DIFFERENTIATION_FINITE_DIFFERENCE_HPP\n\n/*\n * Performs numerical differentiation by finite-differences.\n *\n * All numerical differentiation using finite-differences are ill-conditioned, and these routines are no exception.\n * A simple argument demonstrates that the error is unbounded as h->0.\n * Take the one sides finite difference formula f'(x) = (f(x+h)-f(x))/h.\n * The evaluation of f induces an error as well as the error from the finite-difference approximation, giving\n * |f'(x) - (f(x+h) -f(x))/h| < h|f''(x)|/2 + (|f(x)|+|f(x+h)|)eps/h =: g(h), where eps is the unit roundoff for the type.\n * It is reasonable to choose h in a way that minimizes the maximum error bound g(h).\n * The value of h that minimizes g is h = sqrt(2eps(|f(x)| + |f(x+h)|)/|f''(x)|), and for this value of h the error bound is\n * sqrt(2eps(|f(x+h) +f(x)||f''(x)|)).\n * In fact it is not necessary to compute the ratio (|f(x+h)| + |f(x)|)/|f''(x)|; the error bound of ~\\sqrt{\\epsilon} still holds if we set it to one.\n *\n *\n * For more details on this method of analysis, see\n *\n * http://www.uio.no/studier/emner/matnat/math/MAT-INF1100/h08/kompendiet/diffint.pdf\n * http://web.archive.org/web/20150420195907/http://www.uio.no/studier/emner/matnat/math/MAT-INF1100/h08/kompendiet/diffint.pdf\n *\n *\n * It can be shown on general grounds that when choosing the optimal h, the maximum error in f'(x) is ~(|f(x)|eps)^k/k+1|f^(k-1)(x)|^1/k+1.\n * From this we can see that full precision can be recovered in the limit k->infinity.\n *\n * References:\n *\n * 1) Fornberg, Bengt. \"Generation of finite difference formulas on arbitrarily spaced grids.\" Mathematics of computation 51.184 (1988): 699-706.\n *\n *\n * The second algorithm, the complex step derivative, is not ill-conditioned.\n * However, it requires that your function can be evaluated at complex arguments.\n * The idea is that f(x+ih) = f(x) +ihf'(x) - h^2f''(x) + ... so f'(x) \\approx Im[f(x+ih)]/h.\n * No subtractive cancellation occurs. The error is ~ eps|f'(x)| + eps^2|f'''(x)|/6; hard to beat that.\n *\n * References:\n *\n * 1) Squire, William, and George Trapp. \"Using complex variables to estimate derivatives of real functions.\" Siam Review 40.1 (1998): 110-112.\n */\n\n#include <complex>\n#include <boost/math/special_functions/next.hpp>\n\nnamespace boost{ namespace math{ namespace differentiation {\n\nnamespace detail {\n    template<class Real>\n    Real make_xph_representable(Real x, Real h)\n    {\n        using std::numeric_limits;\n        // Redefine h so that x + h is representable. Not using this trick leads to large error.\n        // The compiler flag -ffast-math evaporates these operations . . .\n        Real temp = x + h;\n        h = temp - x;\n        // Handle the case x + h == x:\n        if (h == 0)\n        {\n            h = boost::math::nextafter(x, (numeric_limits<Real>::max)()) - x;\n        }\n        return h;\n    }\n}\n\ntemplate<class F, class Real>\nReal complex_step_derivative(const F f, Real x)\n{\n    // Is it really this easy? Yes.\n    // Note that some authors recommend taking the stepsize h to be smaller than epsilon(), some recommending use of the min().\n    // This idea was tested over a few billion test cases and found the make the error *much* worse.\n    // Even 2eps and eps/2 made the error worse, which was surprising.\n    using std::complex;\n    using std::numeric_limits;\n    constexpr const Real step = (numeric_limits<Real>::epsilon)();\n    constexpr const Real inv_step = 1/(numeric_limits<Real>::epsilon)();\n    return f(complex<Real>(x, step)).imag()*inv_step;\n}\n\nnamespace detail {\n\n   template <unsigned>\n   struct fd_tag {};\n\n   template<class F, class Real>\n   Real finite_difference_derivative(const F f, Real x, Real* error, const fd_tag<1>&)\n   {\n      using std::sqrt;\n      using std::pow;\n      using std::abs;\n      using std::numeric_limits;\n\n      const Real eps = (numeric_limits<Real>::epsilon)();\n      // Error bound ~eps^1/2\n      // Note that this estimate of h differs from the best estimate by a factor of sqrt((|f(x)| + |f(x+h)|)/|f''(x)|).\n      // Since this factor is invariant under the scaling f -> kf, then we are somewhat justified in approximating it by 1.\n      // This approximation will get better as we move to higher orders of accuracy.\n      Real h = 2 * sqrt(eps);\n      h = detail::make_xph_representable(x, h);\n\n      Real yh = f(x + h);\n      Real y0 = f(x);\n      Real diff = yh - y0;\n      if (error)\n      {\n         Real ym = f(x - h);\n         Real ypph = abs(yh - 2 * y0 + ym) / h;\n         // h*|f''(x)|*0.5 + (|f(x+h)+|f(x)|)*eps/h\n         *error = ypph / 2 + (abs(yh) + abs(y0))*eps / h;\n      }\n      return diff / h;\n   }\n\n   template<class F, class Real>\n   Real finite_difference_derivative(const F f, Real x, Real* error, const fd_tag<2>&)\n   {\n      using std::sqrt;\n      using std::pow;\n      using std::abs;\n      using std::numeric_limits;\n\n      const Real eps = (numeric_limits<Real>::epsilon)();\n      // Error bound ~eps^2/3\n      // See the previous discussion to understand determination of h and the error bound.\n      // Series[(f[x+h] - f[x-h])/(2*h), {h, 0, 4}]\n      Real h = pow(3 * eps, static_cast<Real>(1) / static_cast<Real>(3));\n      h = detail::make_xph_representable(x, h);\n\n      Real yh = f(x + h);\n      Real ymh = f(x - h);\n      Real diff = yh - ymh;\n      if (error)\n      {\n         Real yth = f(x + 2 * h);\n         Real ymth = f(x - 2 * h);\n         *error = eps * (abs(yh) + abs(ymh)) / (2 * h) + abs((yth - ymth) / 2 - diff) / (6 * h);\n      }\n\n      return diff / (2 * h);\n   }\n\n   template<class F, class Real>\n   Real finite_difference_derivative(const F f, Real x, Real* error, const fd_tag<4>&)\n   {\n      using std::sqrt;\n      using std::pow;\n      using std::abs;\n      using std::numeric_limits;\n\n      const Real eps = (numeric_limits<Real>::epsilon)();\n      // Error bound ~eps^4/5\n      Real h = pow(11.25*eps, (Real)1 / (Real)5);\n      h = detail::make_xph_representable(x, h);\n      Real ymth = f(x - 2 * h);\n      Real yth = f(x + 2 * h);\n      Real yh = f(x + h);\n      Real ymh = f(x - h);\n      Real y2 = ymth - yth;\n      Real y1 = yh - ymh;\n      if (error)\n      {\n         // Mathematica code to extract the remainder:\n         // Series[(f[x-2*h]+ 8*f[x+h] - 8*f[x-h] - f[x+2*h])/(12*h), {h, 0, 7}]\n         Real y_three_h = f(x + 3 * h);\n         Real y_m_three_h = f(x - 3 * h);\n         // Error from fifth derivative:\n         *error = abs((y_three_h - y_m_three_h) / 2 + 2 * (ymth - yth) + 5 * (yh - ymh) / 2) / (30 * h);\n         // Error from function evaluation:\n         *error += eps * (abs(yth) + abs(ymth) + 8 * (abs(ymh) + abs(yh))) / (12 * h);\n      }\n      return (y2 + 8 * y1) / (12 * h);\n   }\n\n   template<class F, class Real>\n   Real finite_difference_derivative(const F f, Real x, Real* error, const fd_tag<6>&)\n   {\n      using std::sqrt;\n      using std::pow;\n      using std::abs;\n      using std::numeric_limits;\n\n      const Real eps = (numeric_limits<Real>::epsilon)();\n      // Error bound ~eps^6/7\n      // Error: h^6f^(7)(x)/140 + 5|f(x)|eps/h\n      Real h = pow(eps / 168, (Real)1 / (Real)7);\n      h = detail::make_xph_representable(x, h);\n\n      Real yh = f(x + h);\n      Real ymh = f(x - h);\n      Real y1 = yh - ymh;\n      Real y2 = f(x - 2 * h) - f(x + 2 * h);\n      Real y3 = f(x + 3 * h) - f(x - 3 * h);\n\n      if (error)\n      {\n         // Mathematica code to generate fd scheme for 7th derivative:\n         // Sum[(-1)^i*Binomial[7, i]*(f[x+(3-i)*h] + f[x+(4-i)*h])/2, {i, 0, 7}]\n         // Mathematica to demonstrate that this is a finite difference formula for 7th derivative:\n         // Series[(f[x+4*h]-f[x-4*h] + 6*(f[x-3*h] - f[x+3*h]) + 14*(f[x-h] - f[x+h] + f[x+2*h] - f[x-2*h]))/2, {h, 0, 15}]\n         Real y7 = (f(x + 4 * h) - f(x - 4 * h) - 6 * y3 - 14 * y1 - 14 * y2) / 2;\n         *error = abs(y7) / (140 * h) + 5 * (abs(yh) + abs(ymh))*eps / h;\n      }\n      return (y3 + 9 * y2 + 45 * y1) / (60 * h);\n   }\n\n   template<class F, class Real>\n   Real finite_difference_derivative(const F f, Real x, Real* error, const fd_tag<8>&)\n   {\n      using std::sqrt;\n      using std::pow;\n      using std::abs;\n      using std::numeric_limits;\n\n      const Real eps = (numeric_limits<Real>::epsilon)();\n      // Error bound ~eps^8/9.\n      // In double precision, we only expect to lose two digits of precision while using this formula, at the cost of 8 function evaluations.\n      // Error: h^8|f^(9)(x)|/630 + 7|f(x)|eps/h assuming 7 unstabilized additions.\n      // Mathematica code to get the error:\n      // Series[(f[x+h]-f[x-h])*(4/5) + (1/5)*(f[x-2*h] - f[x+2*h]) + (4/105)*(f[x+3*h] - f[x-3*h]) + (1/280)*(f[x-4*h] - f[x+4*h]), {h, 0, 9}]\n      // If we used Kahan summation, we could get the max error down to h^8|f^(9)(x)|/630 + |f(x)|eps/h.\n      Real h = pow(551.25*eps, (Real)1 / (Real)9);\n      h = detail::make_xph_representable(x, h);\n\n      Real yh = f(x + h);\n      Real ymh = f(x - h);\n      Real y1 = yh - ymh;\n      Real y2 = f(x - 2 * h) - f(x + 2 * h);\n      Real y3 = f(x + 3 * h) - f(x - 3 * h);\n      Real y4 = f(x - 4 * h) - f(x + 4 * h);\n\n      Real tmp1 = 3 * y4 / 8 + 4 * y3;\n      Real tmp2 = 21 * y2 + 84 * y1;\n\n      if (error)\n      {\n         // Mathematica code to generate fd scheme for 7th derivative:\n         // Sum[(-1)^i*Binomial[9, i]*(f[x+(4-i)*h] + f[x+(5-i)*h])/2, {i, 0, 9}]\n         // Mathematica to demonstrate that this is a finite difference formula for 7th derivative:\n         // Series[(f[x+5*h]-f[x- 5*h])/2 + 4*(f[x-4*h] - f[x+4*h]) + 27*(f[x+3*h] - f[x-3*h])/2 + 24*(f[x-2*h]  - f[x+2*h]) + 21*(f[x+h] - f[x-h]), {h, 0, 15}]\n         Real f9 = (f(x + 5 * h) - f(x - 5 * h)) / 2 + 4 * y4 + 27 * y3 / 2 + 24 * y2 + 21 * y1;\n         *error = abs(f9) / (630 * h) + 7 * (abs(yh) + abs(ymh))*eps / h;\n      }\n      return (tmp1 + tmp2) / (105 * h);\n   }\n\n   template<class F, class Real, class tag>\n   Real finite_difference_derivative(const F, Real, Real*, const tag&)\n   {\n      // Always fails, but condition is template-arg-dependent so only evaluated if we get instantiated.\n      static_assert(sizeof(Real) == 0, \"Finite difference not implemented for this order: try 1, 2, 4, 6 or 8\");\n   }\n\n}\n\ntemplate<class F, class Real, size_t order=6>\ninline Real finite_difference_derivative(const F f, Real x, Real* error = nullptr)\n{\n   return detail::finite_difference_derivative(f, x, error, detail::fd_tag<order>());\n}\n\n}}}  // namespaces\n#endif\n", "meta": {"hexsha": "3376c70734acbb9422dac286563956598891dde3", "size": 10750, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/differentiation/finite_difference.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/differentiation/finite_difference.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/differentiation/finite_difference.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": 40.2621722846, "max_line_length": 160, "alphanum_fraction": 0.5829767442, "num_tokens": 3430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5260805523883031}}
{"text": "/* test_poisson.cpp\n *\n * Copyright Steven Watanabe 2010\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$\n *\n */\n\n#include <boost/random/discrete_distribution.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/exception/diagnostic_information.hpp>\n#include <vector>\n#include <iostream>\n#include <numeric>\n\n#include \"chi_squared_test.hpp\"\n\nbool do_test(int n, long long max) {\n    std::cout << \"running discrete(p0, p1, ..., p\" << n-1 << \")\" << \" \" << max << \" times: \" << std::flush;\n\n    std::vector<double> expected;\n    {\n        boost::mt19937 egen;\n        for(int i = 0; i < n; ++i) {\n            expected.push_back(egen());\n        }\n        double sum = std::accumulate(expected.begin(), expected.end(), 0.0);\n        for(std::vector<double>::iterator iter = expected.begin(), end = expected.end(); iter != end; ++iter) {\n            *iter /= sum;\n        }\n    }\n    \n    boost::random::discrete_distribution<> dist(expected);\n    boost::mt19937 gen;\n    std::vector<long long> results(expected.size());\n    for(long long i = 0; i < max; ++i) {\n        ++results[dist(gen)];\n    }\n\n    long long sum = std::accumulate(results.begin(), results.end(), 0ll);\n    if(sum != max) {\n        std::cout << \"*** Failed: incorrect total: \" << sum << \" ***\" << std::endl;\n        return false;\n    }\n    double chsqr = chi_squared_test(results, expected, max);\n\n    bool result = chsqr < 0.99;\n    const char* err = result? \"\" : \"*\";\n    std::cout << std::setprecision(17) << chsqr << err << std::endl;\n\n    std::cout << std::setprecision(6);\n\n    return result;\n}\n\nbool do_tests(int repeat, int max_n, long long trials) {\n    boost::mt19937 gen;\n    boost::uniform_int<> idist(1, max_n);\n    int errors = 0;\n    for(int i = 0; i < repeat; ++i) {\n        if(!do_test(idist(gen), trials)) {\n            ++errors;\n        }\n    }\n    if(errors != 0) {\n        std::cout << \"*** \" << errors << \" errors detected ***\" << std::endl;\n    }\n    return errors == 0;\n}\n\nint usage() {\n    std::cerr << \"Usage: test_discrete -r <repeat> -n <max n> -t <trials>\" << std::endl;\n    return 2;\n}\n\ntemplate<class T>\nbool handle_option(int& argc, char**& argv, char opt, T& value) {\n    if(argv[0][1] == opt && argc > 1) {\n        --argc;\n        ++argv;\n        value = boost::lexical_cast<T>(argv[0]);\n        return true;\n    } else {\n        return false;\n    }\n}\n\nint main(int argc, char** argv) {\n    int repeat = 10;\n    int max_n = 100000;\n    long long trials = 1000000ll;\n\n    if(argc > 0) {\n        --argc;\n        ++argv;\n    }\n    while(argc > 0) {\n        if(argv[0][0] != '-') return usage();\n        else if(!handle_option(argc, argv, 'r', repeat)\n             && !handle_option(argc, argv, 'n', max_n)\n             && !handle_option(argc, argv, 't', trials)) {\n            return usage();\n        }\n        --argc;\n        ++argv;\n    }\n\n    try {\n        if(do_tests(repeat, max_n, trials)) {\n            return 0;\n        } else {\n            return EXIT_FAILURE;\n        }\n    } catch(...) {\n        std::cerr << boost::current_exception_diagnostic_information() << std::endl;\n        return EXIT_FAILURE;\n    }\n}\n", "meta": {"hexsha": "6a6d378653387ca1f4ae5f4a4d3c4a62fc5c26ac", "size": 3321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_discrete.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-07T16:21:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:58:37.000Z", "max_issues_repo_path": "boost/libs/random/test/test_discrete.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/random/test/test_discrete.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 26.7822580645, "max_line_length": 111, "alphanum_fraction": 0.5501355014, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5260805453199494}}
{"text": "#include \"drake/math/saturate.h\"\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"drake/common/autodiff.h\"\n#include \"drake/common/symbolic.h\"\n\nnamespace drake {\n\nusing symbolic::Environment;\nusing symbolic::Expression;\n\nnamespace math {\nnamespace {\n\n// Tests that saturate works with double types.\nGTEST_TEST(SaturateTest, DoubleTest) {\n  const double kLow{5};\n  const double kHigh{10};\n\n  const double kTooLow{kLow - 1e-10};\n  const double kMiddle{kLow + kHigh / 2.0};\n  const double kTooHigh{kHigh + 1e-10};\n  EXPECT_EQ(saturate(kTooLow, kLow, kHigh), kLow);\n  EXPECT_EQ(saturate(kMiddle, kLow, kHigh), kMiddle);\n  EXPECT_EQ(saturate(kTooHigh, kLow, kHigh), kHigh);\n}\n\n// Tests that saturate works with AutoDiff types.\nGTEST_TEST(SaturateTest, AutoDiffXdTest) {\n  const AutoDiffXd lowerbound{5.0, Vector1d(1.5)};\n  const AutoDiffXd upperbound{10.0, Vector1d(-1.5)};\n  const AutoDiffXd withinBoundsValue{7.5, Vector1d(6.38)};\n\n  EXPECT_EQ(\n      saturate(AutoDiffXd{1.0, Vector1d(10.2)}, lowerbound, upperbound),\n      lowerbound);\n  EXPECT_EQ(\n      saturate(withinBoundsValue, lowerbound, upperbound),\n      withinBoundsValue);\n  EXPECT_EQ(\n      saturate(AutoDiffXd{100.3, Vector1d(-9)}, lowerbound, upperbound),\n      upperbound);\n\n  // Tests a mixed-type scenario. Adding or subtracting 1 from an AutoDiffXd\n  // does not result in an AutoDiffXd, but rather some intermediate type that\n  // implicitly converts to AutoDiffXd.\n  EXPECT_EQ(\n      saturate(AutoDiffXd{1.0, Vector1d(10.2)}, lowerbound - 1, upperbound + 1),\n      lowerbound - 1);\n}\n\n// Tests that saturate() works with symbolic::Expression types.\nGTEST_TEST(SaturateTest, SymbolicExpressionTest) {\n  Expression result;\n  result = saturate(Expression{1.5}, Expression::One(), Expression::Pi());\n  EXPECT_EQ(result.to_string(), \"1.5\");\n  result = saturate(Expression::Zero(), Expression::One(), Expression::Pi());\n  EXPECT_EQ(result.to_string(), \"1\");\n  result = saturate(Expression{5.6}, Expression::One(), Expression::Pi());\n  const std::string kPi{\"3.14\"};\n  EXPECT_EQ(result.to_string().compare(0, kPi.length(), kPi), 0);\n\n  symbolic::Variable x{\"x\"};\n  symbolic::Variable lo{\"lo\"};\n  symbolic::Variable hi{\"hi\"};\n  auto saturate_expression = saturate(\n      Expression{x}, Expression{lo}, Expression{hi});\n  EXPECT_EQ(saturate_expression.Evaluate(\n      Environment{{x, 0}, {lo, 3}, {hi, 10}}), 3);\n  EXPECT_EQ(saturate_expression.Evaluate(\n      Environment{{x, 5}, {lo, 3}, {hi, 10}}), 5);\n  EXPECT_EQ(saturate_expression.Evaluate(\n      Environment{{x, 12.334}, {lo, 3}, {hi, 10}}), 10);\n}\n\n}  // namespace\n}  // namespace math\n}  // namespace drake\n", "meta": {"hexsha": "daa2115244279eaee439f0cc654129e5d7bac56a", "size": 2636, "ext": "cc", "lang": "C++", "max_stars_repo_path": "math/test/saturate_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/saturate_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/saturate_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": 32.5432098765, "max_line_length": 80, "alphanum_fraction": 0.6991654021, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.526080538794183}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed 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#include <boost/hana/integral.hpp>\n\n#include <boost/hana/detail/assert.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n    // Integral < Integral\n    BOOST_HANA_CONSTANT_ASSERT(less(int_<0>, int_<1>));\n    BOOST_HANA_CONSTANT_ASSERT(not_(less(int_<0>, int_<0>)));\n    BOOST_HANA_CONSTANT_ASSERT(not_(less(int_<1>, int_<0>)));\n\n    BOOST_HANA_CONSTANT_ASSERT(less(int_<0>, long_<1>));\n    BOOST_HANA_CONSTANT_ASSERT(not_(less(int_<0>, long_<0>)));\n    BOOST_HANA_CONSTANT_ASSERT(not_(less(int_<1>, long_<0>)));\n\n\n    // Integral < other\n    BOOST_HANA_CONSTEXPR_ASSERT(less(int_<0>, int{1}));\n    BOOST_HANA_CONSTEXPR_ASSERT(not_(less(int_<0>, int{0})));\n    BOOST_HANA_CONSTEXPR_ASSERT(not_(less(int_<1>, int{0})));\n\n    BOOST_HANA_CONSTEXPR_ASSERT(less(int_<0>, long{1}));\n    BOOST_HANA_CONSTEXPR_ASSERT(not_(less(int_<0>, long{0})));\n    BOOST_HANA_CONSTEXPR_ASSERT(not_(less(int_<1>, long{0})));\n\n    BOOST_HANA_CONSTEXPR_ASSERT(less(int_<0>, float{1}));\n    BOOST_HANA_CONSTEXPR_ASSERT(not_(less(int_<0>, float{0})));\n    BOOST_HANA_CONSTEXPR_ASSERT(not_(less(int_<1>, float{0})));\n\n\n    // other < Integral\n    BOOST_HANA_CONSTEXPR_ASSERT(less(int{0}, int_<1>));\n    BOOST_HANA_CONSTEXPR_ASSERT(not_(less(int{0}, int_<0>)));\n    BOOST_HANA_CONSTEXPR_ASSERT(not_(less(int{1}, int_<0>)));\n\n    BOOST_HANA_CONSTEXPR_ASSERT(less(int{0}, long_<1>));\n    BOOST_HANA_CONSTEXPR_ASSERT(not_(less(int{0}, long_<0>)));\n    BOOST_HANA_CONSTEXPR_ASSERT(not_(less(int{1}, long_<0>)));\n\n    BOOST_HANA_CONSTEXPR_ASSERT(less(float{0}, long_<1>));\n    BOOST_HANA_CONSTEXPR_ASSERT(not_(less(float{0}, long_<0>)));\n    BOOST_HANA_CONSTEXPR_ASSERT(not_(less(float{1}, long_<0>)));\n}\n", "meta": {"hexsha": "f72efce395644f0fd97a9a31e1b0797995c3e5eb", "size": 1845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/integral/orderable/less.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/integral/orderable/less.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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/integral/orderable/less.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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.1764705882, "max_line_length": 78, "alphanum_fraction": 0.7111111111, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5260805352600062}}
{"text": "//  Copyright (c) 2015 John Maddock\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#ifndef BOOST_MATH_ELLINT_JZ_HPP\n#define BOOST_MATH_ELLINT_JZ_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/special_functions/ellint_1.hpp>\n#include <boost/math/special_functions/ellint_rj.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/tools/workaround.hpp>\n\n// Elliptic integral the Jacobi Zeta function.\n\nnamespace boost { namespace math { \n   \nnamespace detail{\n\n// Elliptic integral - Jacobi Zeta\ntemplate <typename T, typename Policy>\nT jacobi_zeta_imp(T phi, T k, const Policy& pol)\n{\n    BOOST_MATH_STD_USING\n    using namespace boost::math::tools;\n    using namespace boost::math::constants;\n\n    bool invert = false;\n    if(phi < 0)\n    {\n       phi = fabs(phi);\n       invert = true;\n    }\n\n    T result;\n    T sinp = sin(phi);\n    T cosp = cos(phi);\n    T s2 = sinp * sinp;\n    T k2 = k * k;\n    T kp = 1 - k2;\n    if(k == 1)\n       result = sinp * (boost::math::sign)(cosp);  // We get here by simplifying JacobiZeta[w, 1] in Mathematica, and the fact that 0 <= phi.\n    else\n       result = k2 * sinp * cosp * sqrt(1 - k2 * s2) * ellint_rj_imp(T(0), kp, T(1), T(1 - k2 * s2), pol) / (3 * ellint_k_imp(k, pol));\n    return invert ? T(-result) : result;\n}\n\n} // detail\n\ntemplate <class T1, class T2, class Policy>\ninline typename tools::promote_args<T1, T2>::type jacobi_zeta(T1 k, T2 phi, const Policy& pol)\n{\n   typedef typename tools::promote_args<T1, T2>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::jacobi_zeta_imp(static_cast<value_type>(phi), static_cast<value_type>(k), pol), \"boost::math::jacobi_zeta<%1%>(%1%,%1%)\");\n}\n\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type jacobi_zeta(T1 k, T2 phi)\n{\n   return boost::math::jacobi_zeta(k, phi, policies::policy<>());\n}\n\n}} // namespaces\n\n#endif // BOOST_MATH_ELLINT_D_HPP\n\n", "meta": {"hexsha": "a3fa54746e42a13aa0b0146159583993de37f97b", "size": 2273, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/math/special_functions/jacobi_zeta.hpp", "max_stars_repo_name": "189569400/ClickHouse", "max_stars_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/math/special_functions/jacobi_zeta.hpp", "max_issues_repo_name": "189569400/ClickHouse", "max_issues_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/math/special_functions/jacobi_zeta.hpp", "max_forks_repo_name": "189569400/ClickHouse", "max_forks_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": 30.3066666667, "max_line_length": 194, "alphanum_fraction": 0.69291685, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5260805252000629}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/trunc.hpp>\n#include <boost/simd/function/fast.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/three.hpp>\n\nSTF_CASE_TPL (\" trunc real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::trunc;\n  using r_t = decltype(trunc(T()));\n\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_EQUAL(trunc(bs::Inf<T>()), bs::Inf<T>());\n  STF_EQUAL(trunc(bs::Minf<T>()), bs::Minf<T>());\n  STF_IEEE_EQUAL(trunc(bs::Nan<T>()), bs::Nan<T>());\n#endif\n  STF_EQUAL(trunc(bs::One<T>()), bs::One<T>());\n  STF_EQUAL(trunc(bs::Mone<T>()), bs::Mone<T>());\n  STF_EQUAL(trunc(bs::Zero<T>()), bs::Zero<T>());\n  STF_EQUAL(trunc(bs::Pi<T>()), bs::Three<T>());\n  STF_EQUAL(trunc(T(1.4)), T(1));\n  STF_EQUAL(trunc(T(1.5)), T(1));\n  STF_EQUAL(trunc(T(1.6)), T(1));\n  STF_EQUAL(trunc(T(2.5)), T(2));\n  STF_EQUAL(trunc(T(-1.4)), T(-1));\n  STF_EQUAL(trunc(T(-1.5)), T(-1));\n  STF_EQUAL(trunc(T(-1.6)), T(-1));\n  STF_EQUAL(trunc(T(-2.5)), T(-2));\n} // end of test for floating_\n\nSTF_CASE_TPL (\" trunc unsigned_int\",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::trunc;\n  using r_t = decltype(trunc(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  STF_EQUAL(trunc(bs::One<T>()), bs::One<T>());\n  STF_EQUAL(trunc(bs::Zero<T>()), bs::Zero<T>());\n} // end of test for unsigned_int_\n\nSTF_CASE_TPL (\" trunc signed_int\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::trunc;\n  using r_t = decltype(trunc(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  STF_EQUAL(trunc(bs::Mone<T>()), bs::Mone<T>());\n  STF_EQUAL(trunc(bs::One<T>()), bs::One<T>());\n  STF_EQUAL(trunc(bs::Zero<T>()), bs::Zero<T>());\n} // end of test for signed_int_\n\nSTF_CASE_TPL ( \"fast trunc real\",  STF_IEEE_TYPES)\n{\n\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::trunc;\n  using r_t = decltype(trunc(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  STF_EQUAL(bs::fast_(trunc)(bs::One<T>()), bs::One<T>());\n  STF_EQUAL(bs::fast_(trunc)(bs::Mone<T>()), bs::Mone<T>());\n  STF_EQUAL(bs::fast_(trunc)(bs::Zero<T>()), bs::Zero<T>());\n  STF_EQUAL(bs::fast_(trunc)(bs::Pi<T>()), bs::Three<T>());\n  STF_EQUAL(bs::fast_(trunc)(T(1.4)), T(1));\n  STF_EQUAL(bs::fast_(trunc)(T(1.5)), T(1));\n  STF_EQUAL(bs::fast_(trunc)(T(1.6)), T(1));\n  STF_EQUAL(bs::fast_(trunc)(T(2.5)), T(2));\n  STF_EQUAL(bs::fast_(trunc)(T(-1.4)), T(-1));\n  STF_EQUAL(bs::fast_(trunc)(T(-1.5)), T(-1));\n  STF_EQUAL(bs::fast_(trunc)(T(-1.6)), T(-1));\n  STF_EQUAL(bs::fast_(trunc)(T(-2.5)), T(-2));\n} // end of test for floating_\n\n", "meta": {"hexsha": "1d151928fb7d78eda5e0563e7ec6eb37d1cf92b3", "size": 3547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/trunc.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": "test/function/scalar/trunc.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": "test/function/scalar/trunc.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": 32.5412844037, "max_line_length": 100, "alphanum_fraction": 0.6109388215, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5260805231616811}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"../include/layer.h\"\n\nint main()\n{\n    using std::cout;\n    using std::endl;\n    using namespace MyDL;\n    using namespace Eigen;\n\n    int row = 4;\n    int col = 5;\n    double dropout_ratio = 0.5;\n    Dropout dropout(row, col, dropout_ratio);\n\n    MatrixXd X = MatrixXd::Random(row, col);\n    MatrixXd dout = MatrixXd::Ones(row, col);\n    vector<MatrixXd> inputs, outputs, douts, grads;\n    inputs.push_back(X);\n    douts.push_back(dout);\n\n    cout << \"input: \" << endl;\n    cout << X << endl;\n\n    cout << \"Dropout forward -train mode- :\" << endl;\n    outputs = dropout.forward(inputs);\n\n    cout << outputs[0] << endl;\n\n    Config::getInstance().set_flag(false);\n\n    cout << \"Dropout forward -inference mode- : \" << endl;\n    outputs = dropout.forward(inputs);\n\n    cout << outputs[0] << endl;\n\n    cout << \"Dropout backward: \" << endl;\n    grads = dropout.backward(douts);\n\n    cout << grads[0] << endl;\n\n    return 0;\n}", "meta": {"hexsha": "d211cd210db93f9ca88934227773bcffc221ebbc", "size": 976, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/test_dropout.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_dropout.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_dropout.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.1818181818, "max_line_length": 58, "alphanum_fraction": 0.6055327869, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5260272328652301}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// Example illustrating the use of GCoptimization.cpp\n//\n/////////////////////////////////////////////////////////////////////////////\n//\n//  Optimization problem:\n//  is a set of sites (pixels) of width 10 and hight 5. Thus number of pixels is 50\n//  grid neighborhood: each pixel has its left, right, up, and bottom pixels as neighbors\n//  7 labels\n//  Data costs: D(pixel,label) = 0 if pixel < 25 and label = 0\n//            : D(pixel,label) = 10 if pixel < 25 and label is not  0\n//            : D(pixel,label) = 0 if pixel >= 25 and label = 5\n//            : D(pixel,label) = 10 if pixel >= 25 and label is not  5\n// Smoothness costs: V(p1,p2,l1,l2) = min( (l1-l2)*(l1-l2) , 4 )\n// Below in the main program, we illustrate different ways of setting data and smoothness costs\n// that our interface allow and solve this optimizaiton problem\n\n// For most of the examples, we use no spatially varying pixel dependent terms. \n// For some examples, to demonstrate spatially varying terms we use\n// V(p1,p2,l1,l2) = w_{p1,p2}*[min((l1-l2)*(l1-l2),4)], with \n// w_{p1,p2} = p1+p2 if |p1-p2| == 1 and w_{p1,p2} = p1*p2 if |p1-p2| is not 1\n\n#include <ctype.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n#include <string>\n#include <time.h>\n#include <opencv2/core.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/ximgproc.hpp>\n#include <boost/log/core.hpp>\n#include <boost/log/trivial.hpp>\n#include <boost/log/expressions.hpp>\n#include <boost/filesystem.hpp>\n#include <limits>\n\n//#include <opencv/contrib/contrib.hpp>\n#include <iostream>\n#include <fstream>\n\nusing namespace cv;\nusing namespace std;\nusing namespace ximgproc;\n//using namespace GCoptimization;\n\n#include \"GCoptimization.h\"\n#include \"IcgBench.h\"\n#include \"CImg.h\"\n\nusing namespace cimg_library;\n\nstruct ForDataFn {\n\tint numLab;\n\tint *data;\n};\n\nstruct Result {\n\tint *labels;\n\tlong long e;\n};\n\nint delta = 5;\nint desvio = 1.2;\n\nint smoothFn(int p1, int p2, int l1, int l2) {\n\n\t//return exp( pow(p1 - p2, 2)/(2*d*d) );\n\n\tif (l1 == l2) {\n\t\treturn 0;\n\t} else {\n\t\t//return delta * abs(p1 - p2);//pow(p1 - p2, 2);\n\t\treturn delta * exp(-pow(p1 - p2, 2) / (2 * desvio * desvio));\n\t}\n\n\t//return a * abs(p1 - p2);\n\t//if ((l1 - l2) * (l1 - l2) <= 4)\n\t// return ((l1 - l2) * (l1 - l2));\n\t// else\n\t// return (4);\n}\n\nint dataFn(int p, int l, void *data) {\n\tForDataFn *myData = (ForDataFn *) data;\n\tint numLab = myData->numLab;\n\n\treturn (myData->data[p * numLab + l]);\n}\n\nint loadImage(std::string path, Mat& mask, Mat &labelSuperpixels) {\n\n\t//Load Image with opencv\n\tMat image;\n\n\timage = imread(path, CV_LOAD_IMAGE_COLOR);   // Read the file\n\n\tif (!image.data)                              // Check for invalid input\n\t{\n\t\tprintf(\"Could not open or find the image\\n\");\n\t\treturn 0;\n\t}\n\n\t//cvtColor(image, gray, CV_RGB2GRAY);\n\n\tint num_iterations = 4;\n\tint prior = 2;\n\tbool double_step = false;\n\tint num_superpixels = 100;\n\tint num_levels = 4;\n\tint num_histogram_bins = 5;\n\n\tMat result;\n\tPtr<SuperpixelSEEDS> seeds;\n\tint width, height;\n\n\twidth = image.size().width;\n\theight = image.size().height;\n\n\tseeds = createSuperpixelSEEDS(width, height, image.channels(),\n\t\t\tnum_superpixels, num_levels, prior, num_histogram_bins,\n\t\t\tdouble_step);\n\n\tMat converted;\n\tcvtColor(image, converted, COLOR_BGR2HSV);\n\n\tdouble t = (double) getTickCount();\n\n\n\tPtr<SuperpixelSLIC> slic = createSuperpixelSLIC(converted,SLIC,50,float(100));\n\n\n\t//seeds->iterate(converted, num_iterations);\n\tslic->iterate(num_iterations);\n\tresult = image;\n\n\tt = ((double) getTickCount() - t) / getTickFrequency();\n\t//printf(\"SEEDS segmentation took %i ms with %3i superpixels\\n\",\n\t//\t\t(int) (t * 1000), seeds->getNumberOfSuperpixels());\n\n\t/* retrieve the segmentation result */\n\t//Mat labels;\n\t//seeds->getLabels(labels);\n\t//slic->getLabels(labels);\n\t/* get the contours for displaying */\n\tslic->getLabelContourMask(mask, false);\n\tresult.setTo(Scalar(50, 50, 255), mask);\n\n\n\t//seeds->getLabels()\n\n\n\tslic->getLabels(labelSuperpixels);\n\n\n\n\t//cout << labelSuperpixels.size() << endl;\n\n\t//abort();\n\t//imshow(\"Superpixel\", result);\n\n\t//namedWindow(\"Display window\", WINDOW_AUTOSIZE); // Create a window for display.\n\t//imshow(\"Display window\", superPixel);           // Show our image inside it.\n\t//imshow(\"Gray image\", gray);\n\n\t//waitKey(0);\n\n\t// Wait for a keystroke in the window\n\n\treturn slic->getNumberOfSuperpixels();\n\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// in this version, set data and smoothness terms using arrays\n// grid neighborhood structure is assumed\n//\nResult * GridGraph_DMAT(const Mat& I, int num_labels, int f_labels[],\n\t\tstd::vector<IcgBench::Seed> seeds, int countSeed[], CImg<float> *dataTermCuda,\n\t\tvector<vector<IcgBench::Seed>> &super) {\n\n\tint width = I.cols;\n\tint height = I.rows;\n\tint num_pixels = width * height;\n\tlong long e = 0;\n\n\tint *result = new int[num_pixels];   // stores result of optimization\n\n\tvector<Mat> labelsSeed(num_labels);\n\tint countInstSeed[num_labels];\n\n\tfor (int i = 0; i < num_labels; ++i) {\n\t\tMat l(3, countSeed[i], CV_8SC1);\n\t\tlabelsSeed[i] = l;\n\t\tcountInstSeed[i] = 0;\n\t}\n\n\tfor (unsigned int i = 0; i < seeds.size(); ++i) {\n\t\tIcgBench::Seed seed = seeds[i];\n\t\tunsigned int p = I.at<unsigned char>(seed.y, seed.x);\n\t\t//printf(\"%u\", p);\n\t\t(labelsSeed[seed.label]).at<unsigned char>(0, countInstSeed[seed.label]) =\n\t\t\t\tp;\n\t\t(labelsSeed[seed.label]).at<unsigned char>(1, countInstSeed[seed.label]) =\n\t\t\t\tseed.y;\n\t\t(labelsSeed[seed.label]).at<unsigned char>(2, countInstSeed[seed.label]) =\n\t\t\t\tseed.x;\n\n\t\tcountInstSeed[seed.label]++;\n\t}\n\n\tMat r = I.reshape(1, num_pixels);\n\t//cout << r.depth() << \", \" << r.channels() << endl;\n\t//printf(\"%d\", r.);\n\t// first set up the array for data costs\n\tint sizeData = num_pixels * num_labels;\n\tdouble *data = new double[sizeData];\n\tint *dataInt = new int[sizeData];\n\tdouble min = std::numeric_limits<double>::max();\n\tdouble max = std::numeric_limits<double>::min();\n\tfor (int i = 0; i < num_pixels; i++) {\n\t\tfor (int l = 0; l < num_labels; l++) {\n\t\t\t//printf(\"Teste %d\\n\", r.at<unsigned char>(i));\n\t\t\t//data[i * num_labels + l] = pow(\n\t\t\t//\t\tf_labels[l] - r.at<unsigned char>(0, i), 2);\n\t\t\tdataInt[i * num_labels + l] = abs(\n\t\t\t\t\tf_labels[l] - r.at<unsigned char>(0, i));\n\n\t\t\t/*int x = i/I.size().width;\n\t\t\t int y = i%I.size().width;\n\t\t\t Mat t1(1,countSeed[l],CV_32F);\n\t\t\t Mat t2(1,countSeed[l],CV_32F);\n\t\t\t Mat rootSquare;\n\t\t\t pow(x - labelsSeed[l].col(2), 2, t1);\n\t\t\t pow(y - labelsSeed[l].col(1), 2, t2);\n\t\t\t sqrt(t1 + t2, rootSquare);*/\n\n\t\t\t//cout << labelsSeed[l].col(0) << endl;\n\t\t\t//abort();\n\t\t\tMat c = labelsSeed[l].col(0);\n\t\t\tint diff = 0;\n\t\t\tfor (int j = 0; j < c.size().height; j++) {\n\t\t\t\tdiff += abs(r.at<unsigned char>(0, i) - c.at<unsigned char>(j, 0));\n\t\t\t\t//printf(\"%d\", diff);\n\t\t\t}\n\t\t\tdouble p = diff / (1.0 * countSeed[l]);\n\n\t\t\tdata[i * num_labels + l] = p;\n\n\t\t\tif (p < min) {\n\t\t\t\tmin = p;\n\t\t\t\t//printf(\"%lf\\n\", min);\n\t\t\t}\n\t\t\tif (p > max) {\n\t\t\t\tmax = p;\n\t\t\t\t//printf(\"%lf\\n\", min);\n\t\t\t}\n\n\t\t\t/*\tdouble p = sum((r.at<unsigned char>(0, i) - labelsSeed[l].col(0)))[0]/countSeed[l];\n\t\t\t //printf(\"%lf\\n\", -log());\n\t\t\t data[i * num_labels + l] = p;\n\t\t\t if ( p < min){\n\t\t\t min = p;\n\t\t\t //printf(\"%lf\\n\", min);\n\t\t\t }\n\t\t\t if ( p > max){\n\t\t\t max = p;\n\t\t\t //printf(\"%lf\\n\", min);\n\t\t\t }*/\n\n\t\t}\n\t}\n\n\t//min = abs(min);\n\tdouble sumData = 0;\n\tfor (int i = 0; i < sizeData; ++i) {\n\t\tdata[i] = (data[i] - min)/(max - min);\n\t\t//printf(\"%lf\\n\", data[i]);\n\t\t//sumData += data[i];\n\t}\n\n\t//int *dataInt = new int[sizeData];\n\n\tfor (int i = 0; i < sizeData; ++i) {\n\t\t//printf(\"%lf\\n\", -log(data[i]));\n\t\tdata[i] = abs(-1* -log(data[i]));\n\t\t//dataInt[i] = data[i];\n\t\t//printf(\"%d\\n\", dataInt[i]);\n\t}\n\n\tfor (int i = 0; i < I.size().height; i++) {\n\t\t\tfor (int j = 0; j < I.size().width; j++) {\n\t\t\t\tfor (int l = 0; l < num_labels; l++) {\n\n\t\t\t\t\tdataInt[(i * I.size().width + j) * num_labels + l] = (*dataTermCuda)(j,i, 0, l);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t/*for (int i = 0; i < num_pixels; i++) {\n\t\tfor (int l = 0; l < num_labels; l++) {\n\n\t\t\tdataInt[i * num_labels + l] = (*dataTermCuda)(i/num_pixels, i%num_pixels, 0, l);//(*dataTermCuda)();\n\t\t}\n\t}*/\n\n\ttry {\n\t\tGCoptimizationGridGraph *gc = new GCoptimizationGridGraph(width, height,\n\t\t\t\tnum_labels);\n\n// set up the needed data to pass to function for the data costs\n\t\tForDataFn toFn;\n\t\ttoFn.data = dataInt;\n\t\ttoFn.numLab = num_labels;\n\n\t\tgc->setDataCost(&dataFn, &toFn);\n\n// smoothness comes from function pointer\n\t\tgc->setSmoothCost(&smoothFn);\n\n//gc->setLabelCost()\n\t\t//gc->setLabelOrder(true);\n\n\t\t//gc->setLabelOrder(true);\n\t\t//gc->dynamic_programming();\n\n\t\tint *ordem = new int(num_labels);\n\t\tfor (int i = 0; i < num_labels; ++i) {\n\t\t\tordem[i] = num_labels - i - 1;\n\t\t}\n\t\tgc->setLabelOrder(ordem, num_labels);\n\n//printf(\"\\nBefore optimization energy is %lld\", gc->compute_energy());\n//for(int i =0; i < 100; i+=10){\n\t\t//gc->expansion(1); // run expansion for 2 iterations. For swap use gc->swap(num_iterations);\n\t\tsrand(time(NULL));\n//gc->swap(10);\n\n\t\tgc->dynamic_programming(super, super.size(), dataTermCuda);\n\t\t//gc->expansion(1);\n\n\t\t//printf(\"\\n%lld\", gc->compute_energy());\n\n\t\tfor (int i = 0; i < num_labels; ++i) {\n\t\t\tordem[i] = i;\n\t\t}\n\t\tgc->setLabelOrder(ordem, num_labels);\n\n\n\t\t//gc->expansion(1);\n\n\t\t//gc->setLabel(0,0);\n\n\t\t//printf(\"\\n%lld\", gc->compute_energy());\n\n//printf(\" Dynamic Programming \");\n//gc->dynamic_programming();\n//printf(\"\\n%lld\", gc->compute_energy());\n//}\n//gc->expansion(100); // run expansion for 2 iterations. For swap use gc->swap(num_iterations);\n//printf(\"\\nAfter optimization energy is %lld\", gc->compute_energy());\n\t\te = gc->compute_energy();\n//printf(\"\\n%lld\", e);\n\n\t\tfor (int i = 0; i < num_pixels; i++)\n\t\t\tresult[i] = gc->whatLabel(i);\n\n\t\tdelete gc;\n\n\t} catch (GCException e) {\n\t\te.Report();\n\t}\n\n\t//delete[] result;\n\t//delete[] smooth;\n\tdelete[] data;\n\n\tResult *rEnd = new Result;\n\n\trEnd->labels = result;\n\trEnd->e = e;\n\n\treturn rEnd;\n\n}\n\nvoid createImageLabelsShow(int *labels, int k, Mat &img) {\n\n\tunsigned char pv[k];\n\n\tfor (int i = 0, j = 0; i < 256; i += (256 / k)) {\n\t\tpv[j] = i;\n\t\tj++;\n\t}\n\n\tfor (int i = 0; i < img.rows; i++) {\n\t\tfor (int j = 0; j < img.cols; j++) {\n\t\t\timg.at<unsigned char>(i, j) = pv[labels[i * img.cols + j]];\n\t\t}\n\t}\n\n}\n\nvoid createImageLabels(int *labels, int k, Mat &img) {\n\n\tunsigned char pv[k];\n\n\tfor (int i = 0, j = 0; i < 256; i += (256 / k)) {\n\t\tpv[j] = i;\n\t\tj++;\n\t}\n\n\tfor (int i = 0; i < img.rows; i++) {\n\t\tfor (int j = 0; j < img.cols; j++) {\n\t\t\timg.at<unsigned char>(i, j) = labels[i * img.cols + j];\n\t\t}\n\t}\n\n}\n\nvoid writeCSV(string filename, cv::Mat m) {\n//cv::Formatter const * c_formatter(cv::Formatter::get(cv::Formatter::FMT_CSV));\n\tofstream myfile;\n\tmyfile.open(filename.c_str(), ios::out);\n\tmyfile << cv::format(m, cv::Formatter::FMT_CSV);//c_formatter->format(m);\n\tmyfile.close();\n}\n\n\nint main(int argc, char **argv) {\n\n\tboost::log::core::get()->set_logging_enabled(false);\n\n\tint iflag = 0, oflag = 0, gflag = 0, dataflag = 0;\n\tchar *cvalue = NULL;\n\tchar *gvalue = NULL;\n\tchar *outValue = NULL;\n\tchar *dataValue = NULL;\n\n\n\tint index;\n\tint c;\n\n\topterr = 0;\n\n\twhile ((c = getopt(argc, argv, \"o:g:i:d:\")) != -1) {\n\t\tswitch (c) {\n\t\tcase 'i':\n\t\t\tcvalue = optarg;\n\t\t\tiflag = 1;\n\t\t\tbreak;\n\t\tcase 'g':\n\t\t\tgvalue = optarg;\n\t\t\tgflag = 1;\n\t\t\tbreak;\n\t\tcase 'o':\n\t\t\toutValue = optarg;\n\t\t\toflag = 1;\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\tdataValue = optarg;\n\t\t\tdataflag = 1;\n\t\t\tbreak;\n\t\tcase '?':\n\t\t\tif (optopt == 'i')\n\t\t\t\tfprintf(stderr, \"Option -i requires an argument.\\n\");\n\t\t\telse if (optopt == 'o')\n\t\t\t\tfprintf(stderr, \"Option -o requires an argument.\\n\");\n\t\t\telse if (optopt == 'g')\n\t\t\t\tfprintf(stderr, \"Option -g requires an argument.\\n\");\n\t\t\telse if (isprint(optopt))\n\t\t\t\tfprintf(stderr, \"Unknown option `-%c'.\\n\", optopt);\n\t\t\telse\n\t\t\t\tfprintf(stderr, \"Unknown option character `\\\\x%x'.\\n\", optopt);\n\t\t\treturn 1;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\t}\n\n\t//printf(\"aflag = %d, bflag = %d, cvalue = %s\\n\", aflag, bflag, cvalue);\n\n\tfor (index = optind; index < argc; index++) {\n\t\tprintf(\"Non-option argument %s\\n\", argv[index]);\n\t}\n\n\tif (!iflag) {\n\t\tprintf(\"-i require\");\n\t\tabort();\n\t} else if (!oflag) {\n\t\tprintf(\"-o require\");\n\t\tabort();\n\t}\n\tif (!gflag) {\n\t\tprintf(\"-g require\");\n\t\tabort();\n\t}\n\tif (!dataflag) {\n\t\t\tprintf(\"-d require\");\n\t\t\tabort();\n\t\t}\n\n\t//BOOST_LOG_TRIVIAL(trace)<< \"A trace severity message\";\n\t//BOOST_LOG_TRIVIAL(debug)<< \"A debug severity message\";\n\t//BOOST_LOG_TRIVIAL(info)<< \"An informational severity message\";\n\t//BOOST_LOG_TRIVIAL(warning)<< \"A warning severity message\";\n\t//BOOST_LOG_TRIVIAL(error)<< \"An error severity message\";\n\t//BOOST_LOG_TRIVIAL(fatal)<< \"A fatal severity message\";\n\n\t//Load Data Term\n\tboost::filesystem::path dataTermPath(dataValue);\n\tboost::filesystem::path dataTermName(\"dataEnergy.cimg\");\n\tboost::filesystem::path fullDataTermPath = dataTermPath / dataTermName;\n\n\tCImg<float> dataTerm(fullDataTermPath.string().c_str());\n\n\t//printf(\"\\nData Term %f\\n\", dataTerm(0,0,0,0));\n\n\n\tstring fileNameGroundTruth(gvalue);\n\tBOOST_LOG_TRIVIAL(info)<< \"Load groundtruth \" << fileNameGroundTruth;\n\tIcgBench::IcgBenchFileIO groudTruth(fileNameGroundTruth);\n\n\tboost::filesystem::path fileImagePath(cvalue);\n\tboost::filesystem::path fileImage(groudTruth.getFileName());\n\tboost::filesystem::path fullImagePath = fileImagePath / fileImage;\n\tBOOST_LOG_TRIVIAL(info)<< \"Load Image \" << fullImagePath;\n\tMat grayImage, labelSuperPixels;\n\tint numSuperPixels = loadImage(fullImagePath.string(), grayImage, labelSuperPixels);\n\tif (numSuperPixels) {\n\n\t\tint k = groudTruth.getNumLabels();\n\t\tResult *r = NULL;\n\t\tint s_labels[k];\n\t\tint c_labels[k];\n\t\tfor (int i = 0; i < k; ++i) {\n\t\t\tc_labels[i] = 0;\n\t\t\ts_labels[i] = 0;\n\t\t}\n\n\t\tvector<vector<IcgBench::Seed>> super(numSuperPixels);\n\t\tfor (int i = 0; i < super.size(); ++i) {\n\t\t\tvector<IcgBench::Seed> s;\n\t\t\tsuper[i] = s;\n\t\t}\n\n\t\tfor(int i = 0; i < labelSuperPixels.size().height; i++){\n\t\t\tfor(int j = 0; j < labelSuperPixels.size().width; j++){\n\t\t\t\tIcgBench::Seed s;\n\t\t\t\ts.x = i;\n\t\t\t\ts.y = j;\n\t\t\t\ts.label = i * grayImage.cols + j;//labelSuperPixels.at<unsigned int>(i,j);\n\t\t\t\tsuper[labelSuperPixels.at<unsigned int>(i,j)].push_back(s);\n\t\t\t}\n\t\t}\n\n\t\tBOOST_LOG_TRIVIAL(info)<< \"Define seeds using ground truth \";\n\t\tstd::vector<IcgBench::Seed> seeds = groudTruth.getSeeds();\n\t\tfor (unsigned int i = 0; i < seeds.size(); ++i) {\n\t\t\tIcgBench::Seed seed = seeds[i];\n\t\t\t//if ( seed.x <= grayImage.cols &&  seed.y <= grayImage.rows)\n\t\t\tunsigned int p = grayImage.at<unsigned char>(seed.y, seed.x);\n\t\t\ts_labels[seed.label] += p;\n\t\t\tc_labels[seed.label]++;\n\t\t}\n\n\t\tfor (int i = 0; i < k; ++i) {\n\t\t\ts_labels[i] /= c_labels[i];\n\t\t}\n\n\t\tBOOST_LOG_TRIVIAL(info)<< \"Execute segmentation\";\n\t\tdouble t = (double) getTickCount();\n\n\t\tr = GridGraph_DMAT(grayImage, k, s_labels, seeds, c_labels, &dataTerm, super);\n\n\t\tt = ((double) getTickCount() - t) / getTickFrequency();\n\n\t\tBOOST_LOG_TRIVIAL(info)<< \"Show result\";\n\n\t\tMat seg(grayImage.rows, grayImage.cols, CV_8SC1);\n\t\tcreateImageLabelsShow(r->labels, k - 1, seg);\n\n\t\t//imshow(\"Seg\", seg);\n\t\t//waitKey(0);\n\n\t\tBOOST_LOG_TRIVIAL(info)<< \"Save Label and Seed path\";\n\n\t\tMat labelsMat(grayImage.rows, grayImage.cols, CV_8SC1);\n\t\tMat seedsMat = Mat::ones(grayImage.rows, grayImage.cols, CV_8SC1) * -1;\n\n\t\tboost::filesystem::path fileNameGroundTruthPath(fileNameGroundTruth);\n\t\tboost::filesystem::path fileOutPath(outValue);\n\t\tboost::filesystem::path fullOutPath = fileOutPath\n\t\t\t\t/ fileNameGroundTruthPath.stem();\n\t\tboost::filesystem::create_directory(fullOutPath);\n\t\tboost::filesystem::path extensionLabel(\".label\");\n\t\tboost::filesystem::path extensionSeed(\".seed\");\n\n\t\tboost::filesystem::path fullOutLabelPath(\"gd.label\");\n\t\t//fullOutLabelPath.replace_extension(extensionLabel);\n\t\tfullOutLabelPath = fullOutPath / fullOutLabelPath;\n\t\tboost::filesystem::path fullOutSeedPath(\"gd.seed\");// = fullOutPath;\n\t\tfullOutSeedPath = fullOutPath / fullOutSeedPath;\n\t\t//fullOutSeedPath.replace_extension(extensionSeed);\n\n\t\tcreateImageLabels(r->labels, k - 1, labelsMat);\n\n//Label unsigned\n\t\tint sizeLabels = grayImage.rows * grayImage.cols;\n\t\tunsigned int labels[grayImage.rows * grayImage.cols];\n\t\tfor (int i = 0; i < sizeLabels; ++i) {\n\t\t\tlabels[i] = r->labels[i];\n\t\t}\n\n\t\tIcgBench::LabelImage labelImageIcg(labels, grayImage.cols,\n\t\t\t\tgrayImage.rows);\n\n\t\tIcgBench::LabelImage* a = groudTruth.getLabels();\n\t\tIcgBench::LabelImage* b = &labelImageIcg;\n\n//printf(\"%d\\t%d\\t%d\\t%d\\n\", a->height(), b->height(), a->width(), b->width());\n\n\t\tdouble score = IcgBench::computeDiceScore(*a, *b);\n\n\t\tprintf(\"%lld\\t%.6lf\\t%d\\t%d\\t%3i\\n\", r->e, score, numSuperPixels, k, (int) (t * 1000));\n\n\t\twriteCSV(fullOutLabelPath.string(), labelsMat);\n\t\twriteCSV(fullOutSeedPath.string(), seedsMat);\n\n\t\tBOOST_LOG_TRIVIAL(info)<< \"End\";\n\n\t\treturn 0;\n\n\t} else {\n\t\tfprintf(stderr, \"Not load image\\n\");\n\t\tabort();\n\t}\n\n\n\n\t//Load Image\n\t/*Mat gray;\n\t int *labels = NULL;\n\t Result *r;\n\t int k  = 3;\n\t if (loadImage(cvalue, gray)) {\n\t //imshow(\"Gray image\", gray);\n\n\n\n\t long long eBefore = 0;\n\t int l = 20;\n\n\t for (k = 4; k < 5; k++) {\n\n\t l = k;\n\t int f_labels[l];\n\n\t for (int i = 0, j = 0; i < 256; i += (256 / l)) {\n\t f_labels[j] = i;\n\t j++;\n\t }\n\n\t r = GridGraph_DMAT(gray, l, f_labels);\n\n\t if ( k == 2 ){\n\t eBefore = r->e;\n\t labels = r->labels;\n\n\t }\n\n\t if (r->e >= eBefore ){\n\t labels = r->labels;\n\t break;\n\t }\n\n\t cout <<\"E=\" << r->e << \" k = \" << k << endl;\n\n\t eBefore = r->e;\n\n\n\t delete[] r->labels;\n\t delete r;\n\n\t }\n\n\n\t //\n\t waitKey(0);\n\n\t }\n\n\t Mat seg(gray.rows, gray.cols, CV_8SC1);\n\n\t createImageLabelsShow(labels, k-1, seg);\n\n\t Mat labelsMat(gray.rows, gray.cols, CV_8SC1);\n\t Mat seedsMat = Mat::ones(gray.rows, gray.cols, CV_8SC1)*-1;\n\n\t createImageLabels(labels, k-1, labelsMat);\n\n\t cout << labelsMat << endl;\n\n\n\t writeCSV(\"teste.label\", labelsMat);\n\t writeCSV(\"teste.seed\", seedsMat);\n\n\n\t /*for (int i = 0; i < gray.rows; i++) {\n\t for (int j = 0; j < gray.cols; j++) {\n\t printf(\"%d \", labels[i * gray.cols + j]);\n\n\t }\n\t printf(\"\\n\");\n\t }*/\n\n\t//Mat seg(gray.rows, gray.cols, CV_32SC1, labels);\n\t//Mat cm_img0;\n\t// Apply the colormap:\n\t//applyColorMap(seg, cm_img0, COLORMAP_HOT);\n\t// Show the result:\n\t//imshow(\"Seg\", seg);\n\t//waitKey(0);\n\t//return 0;\n\t/*int width = 10;\n\t int height = 5;\n\t int num_pixels = width*height;\n\t int num_labels = 7;\n\n\n\t // smoothness and data costs are set up one by one, individually\n\t GridGraph_Individually(width,height,num_pixels,num_labels);\n\n\t // smoothness and data costs are set up using arrays\n\t GridGraph_DArraySArray(width,height,num_pixels,num_labels);\n\n\t // smoothness and data costs are set up using functions\n\t GridGraph_DfnSfn(width,height,num_pixels,num_labels);\n\n\t // smoothness and data costs are set up using arrays.\n\t // spatially varying terms are present\n\t GridGraph_DArraySArraySpatVarying(width,height,num_pixels,num_labels);\n\n\t //Will pretend our graph is\n\t //general, and set up a neighborhood system\n\t // which actually is a grid\n\t GeneralGraph_DArraySArray(width,height,num_pixels,num_labels);\n\n\t //Will pretend our graph is general, and set up a neighborhood system\n\t // which actually is a grid. Also uses spatially varying terms\n\t GeneralGraph_DArraySArraySpatVarying(width,height,num_pixels,num_labels);\n\n\t printf(\"\\n  Finished %d (%d) clock per sec %d\",clock()/CLOCKS_PER_SEC,clock(),CLOCKS_PER_SEC);\n\t */\n\n\n\n\n}\n", "meta": {"hexsha": "b4a5e88e8ac126de405a5a18743fcd9a861e61ba", "size": 19321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/img/src/main.cpp", "max_stars_repo_name": "jeffersonfs/dp-superpixel", "max_stars_repo_head_hexsha": "f36994668332d8f8e605419f4b7078c8e22f3be3", "max_stars_repo_licenses": ["MIT"], "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/img/src/main.cpp", "max_issues_repo_name": "jeffersonfs/dp-superpixel", "max_issues_repo_head_hexsha": "f36994668332d8f8e605419f4b7078c8e22f3be3", "max_issues_repo_licenses": ["MIT"], "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/img/src/main.cpp", "max_forks_repo_name": "jeffersonfs/dp-superpixel", "max_forks_repo_head_hexsha": "f36994668332d8f8e605419f4b7078c8e22f3be3", "max_forks_repo_licenses": ["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.3224115334, "max_line_length": 103, "alphanum_fraction": 0.6262615807, "num_tokens": 5980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5260272315428905}}
{"text": "#ifndef _pyp_hh\n#define _pyp_hh\n\n#include \"slice-sampler.h\"\n#include <math.h>\n#include <map>\n#include <tr1/unordered_map>\n//#include <google/sparse_hash_map>\n\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\n#include \"log_add.h\"\n#include \"mt19937ar.h\"\n\n//\n// Pitman-Yor process with customer and table tracking\n//\n\ntemplate <typename Dish, typename Hash=std::tr1::hash<Dish> >\nclass PYP : protected std::tr1::unordered_map<Dish, int, Hash>\n//class PYP : protected google::sparse_hash_map<Dish, int, Hash>\n{\npublic:\n  using std::tr1::unordered_map<Dish,int>::const_iterator;\n  using std::tr1::unordered_map<Dish,int>::iterator;\n  using std::tr1::unordered_map<Dish,int>::begin;\n  using std::tr1::unordered_map<Dish,int>::end;\n//  using google::sparse_hash_map<Dish,int>::const_iterator;\n//  using google::sparse_hash_map<Dish,int>::iterator;\n//  using google::sparse_hash_map<Dish,int>::begin;\n//  using google::sparse_hash_map<Dish,int>::end;\n\n  PYP(double a, double b, unsigned long seed = 0, Hash hash=Hash());\n\n  virtual int increment(Dish d, double p0);\n  virtual int decrement(Dish d);\n\n  // lookup functions\n  int count(Dish d) const;\n  double prob(Dish dish, double p0) const;\n  double prob(Dish dish, double dcd, double dca, \n              double dtd, double dta, double p0) const;\n  double unnormalised_prob(Dish dish, double p0) const;\n\n  int num_customers() const { return _total_customers; }\n  int num_types() const { return std::tr1::unordered_map<Dish,int>::size(); }\n  //int num_types() const { return google::sparse_hash_map<Dish,int>::size(); }\n  bool empty() const { return _total_customers == 0; }\n\n  double log_prob(Dish dish, double log_p0) const;\n  // nb. d* are NOT logs\n  double log_prob(Dish dish, double dcd, double dca, \n                       double dtd, double dta, double log_p0) const;\n\n  int num_tables(Dish dish) const;\n  int num_tables() const;\n\n  double a() const { return _a; }\n  void set_a(double a) { _a = a; }\n\n  double b() const { return _b; }\n  void set_b(double b) { _b = b; }\n\n  virtual void clear();\n  std::ostream& debug_info(std::ostream& os) const;\n\n  double log_restaurant_prob() const;\n  double log_prior() const;\n  static double log_prior_a(double a, double beta_a, double beta_b);\n  static double log_prior_b(double b, double gamma_c, double gamma_s);\n\n  template <typename Uniform01>\n    void resample_prior(Uniform01& rnd);\n  template <typename Uniform01>\n    void resample_prior_a(Uniform01& rnd);\n  template <typename Uniform01>\n    void resample_prior_b(Uniform01& rnd);\n\nprotected:\n  double _a, _b; // parameters of the Pitman-Yor distribution\n  double _a_beta_a, _a_beta_b; // parameters of Beta prior on a\n  double _b_gamma_s, _b_gamma_c; // parameters of Gamma prior on b\n\n  struct TableCounter {\n    TableCounter() : tables(0) {};\n    int tables;\n    std::map<int, int> table_histogram; // num customers at table -> number tables\n  };\n  typedef std::tr1::unordered_map<Dish, TableCounter, Hash> DishTableType;\n  //typedef google::sparse_hash_map<Dish, TableCounter, Hash> DishTableType;\n  DishTableType _dish_tables;\n  int _total_customers, _total_tables;\n\n  typedef boost::mt19937 base_generator_type;\n  typedef boost::uniform_real<> uni_dist_type;\n  typedef boost::variate_generator<base_generator_type&, uni_dist_type> gen_type;\n\n//  uni_dist_type uni_dist;\n//  base_generator_type rng; //this gets the seed\n//  gen_type rnd; //instantiate: rnd(rng, uni_dist)\n                //call: rnd() generates uniform on [0,1)\n\n  // Function objects for calculating the parts of the log_prob for \n  // the parameters a and b\n  struct resample_a_type {\n    int n, m; double b, a_beta_a, a_beta_b;\n    const DishTableType& dish_tables;\n    resample_a_type(int n, int m, double b, double a_beta_a, \n                    double a_beta_b, const DishTableType& dish_tables)\n      : n(n), m(m), b(b), a_beta_a(a_beta_a), a_beta_b(a_beta_b), dish_tables(dish_tables) {}\n\n    double operator() (double proposed_a) const {\n      double log_prior = log_prior_a(proposed_a, a_beta_a, a_beta_b);\n      double log_prob = 0.0;\n      double lgamma1a = lgamma(1.0 - proposed_a);\n      for (typename DishTableType::const_iterator dish_it=dish_tables.begin(); dish_it != dish_tables.end(); ++dish_it) \n        for (std::map<int, int>::const_iterator table_it=dish_it->second.table_histogram.begin(); \n             table_it !=dish_it->second.table_histogram.end(); ++table_it) \n          log_prob += (table_it->second * (lgamma(table_it->first - proposed_a) - lgamma1a));\n\n      log_prob += (proposed_a == 0.0 ? (m-1.0)*log(b) \n                   : ((m-1.0)*log(proposed_a) + lgamma((m-1.0) + b/proposed_a) - lgamma(b/proposed_a)));\n      assert(std::isfinite(log_prob));\n      return log_prob + log_prior;\n    }\n  };\n\n  struct resample_b_type {\n    int n, m; double a, b_gamma_c, b_gamma_s;\n    resample_b_type(int n, int m, double a, double b_gamma_c, double b_gamma_s)\n      : n(n), m(m), a(a), b_gamma_c(b_gamma_c), b_gamma_s(b_gamma_s) {}\n\n    double operator() (double proposed_b) const {\n      double log_prior = log_prior_b(proposed_b, b_gamma_c, b_gamma_s);\n      double log_prob = 0.0;\n      log_prob += (a == 0.0  ? (m-1.0)*log(proposed_b) \n                  : ((m-1.0)*log(a) + lgamma((m-1.0) + proposed_b/a) - lgamma(proposed_b/a)));\n      log_prob += (lgamma(1.0+proposed_b) - lgamma(n+proposed_b));\n      return log_prob + log_prior;\n    }\n  };\n   \n  /* lbetadist() returns the log probability density of x under a Beta(alpha,beta)\n   * distribution. - copied from Mark Johnson's gammadist.c\n   */\n  static long double lbetadist(long double x, long double alpha, long double beta);\n\n  /* lgammadist() returns the log probability density of x under a Gamma(alpha,beta)\n   * distribution - copied from Mark Johnson's gammadist.c\n   */\n  static long double lgammadist(long double x, long double alpha, long double beta);\n\n};\n\ntemplate <typename Dish, typename Hash>\nPYP<Dish,Hash>::PYP(double a, double b, unsigned long seed, Hash)\n: std::tr1::unordered_map<Dish, int, Hash>(10), _a(a), _b(b), \n//: google::sparse_hash_map<Dish, int, Hash>(10), _a(a), _b(b), \n  _a_beta_a(1), _a_beta_b(1), _b_gamma_s(1), _b_gamma_c(1),\n  //_a_beta_a(1), _a_beta_b(1), _b_gamma_s(10), _b_gamma_c(0.1),\n  _total_customers(0), _total_tables(0)//,\n  //uni_dist(0,1), rng(seed == 0 ? (unsigned long)this : seed), rnd(rng, uni_dist)\n{\n//  std::cerr << \"\\t##PYP<Dish,Hash>::PYP(a=\" << _a << \",b=\" << _b << \")\" << std::endl;\n  //set_deleted_key(-std::numeric_limits<Dish>::max());\n}\n\ntemplate <typename Dish, typename Hash>\ndouble \nPYP<Dish,Hash>::prob(Dish dish, double p0) const\n{\n  int c = count(dish), t = num_tables(dish);\n  double r = num_tables() * _a + _b;\n  //std::cerr << \"\\t\\t\\t\\tPYP<Dish,Hash>::prob(\" << dish << \",\" << p0 << \") c=\" << c << \" r=\" << r << std::endl;\n  if (c > 0)\n    return (c - _a * t + r * p0) / (num_customers() + _b);\n  else\n    return r * p0 / (num_customers() + _b);\n}\n\ntemplate <typename Dish, typename Hash>\ndouble \nPYP<Dish,Hash>::unnormalised_prob(Dish dish, double p0) const\n{\n  int c = count(dish), t = num_tables(dish);\n  double r = num_tables() * _a + _b;\n  if (c > 0) return (c - _a * t + r * p0);\n  else       return r * p0;\n}\n\ntemplate <typename Dish, typename Hash>\ndouble \nPYP<Dish,Hash>::prob(Dish dish, double dcd, double dca, \n                     double dtd, double dta, double p0)\nconst\n{\n  int c = count(dish) + dcd, t = num_tables(dish) + dtd;\n  double r = (num_tables() + dta) * _a + _b;\n  if (c > 0)\n    return (c - _a * t + r * p0) / (num_customers() + dca + _b);\n  else\n    return r * p0 / (num_customers() + dca + _b);\n}\n\ntemplate <typename Dish, typename Hash>\ndouble \nPYP<Dish,Hash>::log_prob(Dish dish, double log_p0) const\n{\n  using std::log;\n  int c = count(dish), t = num_tables(dish);\n  double r = log(num_tables() * _a + b);\n  if (c > 0)\n    return Log<double>::add(log(c - _a * t), r + log_p0)\n      - log(num_customers() + _b);\n  else\n    return r + log_p0 - log(num_customers() + b);\n}\n\ntemplate <typename Dish, typename Hash>\ndouble \nPYP<Dish,Hash>::log_prob(Dish dish, double dcd, double dca, \n                         double dtd, double dta, double log_p0)\nconst\n{\n  using std::log;\n  int c = count(dish) + dcd, t = num_tables(dish) + dtd;\n  double r = log((num_tables() + dta) * _a + b);\n  if (c > 0)\n    return Log<double>::add(log(c - _a * t), r + log_p0)\n      - log(num_customers() + dca + _b);\n  else\n    return r + log_p0 - log(num_customers() + dca + b);\n}\n\ntemplate <typename Dish, typename Hash>\nint \nPYP<Dish,Hash>::increment(Dish dish, double p0) {\n  int delta = 0;\n  TableCounter &tc = _dish_tables[dish];\n\n  // seated on a new or existing table?\n  int c = count(dish), t = num_tables(dish), T = num_tables();\n  double pshare = (c > 0) ? (c - _a*t) : 0.0;\n  double pnew = (_b + _a*T) * p0;\n  assert (pshare >= 0.0);\n  //assert (pnew > 0.0);\n\n  //if (rnd() < pnew / (pshare + pnew)) {\n  if (mt_genrand_res53() < pnew / (pshare + pnew)) {\n    // assign to a new table\n    tc.tables += 1;\n    tc.table_histogram[1] += 1;\n    _total_tables += 1;\n    delta = 1;\n  }\n  else {\n    // randomly assign to an existing table\n    // remove constant denominator from inner loop\n    //double r = rnd() * (c - _a*t);\n    double r = mt_genrand_res53() * (c - _a*t);\n    for (std::map<int,int>::iterator\n         hit = tc.table_histogram.begin();\n         hit != tc.table_histogram.end(); ++hit) {\n      r -= ((hit->first - _a) * hit->second);\n      if (r <= 0) {\n        tc.table_histogram[hit->first+1] += 1;\n        hit->second -= 1;\n        if (hit->second == 0)\n          tc.table_histogram.erase(hit);\n        break;\n      }\n    }\n    if (r > 0) {\n      std::cerr << r << \" \" << c << \" \" << _a << \" \" << t << std::endl;\n      assert(false);\n    }\n    delta = 0;\n  }\n\n  std::tr1::unordered_map<Dish,int,Hash>::operator[](dish) += 1;\n  //google::sparse_hash_map<Dish,int,Hash>::operator[](dish) += 1;\n  _total_customers += 1;\n\n  return delta;\n}\n\ntemplate <typename Dish, typename Hash>\nint \nPYP<Dish,Hash>::count(Dish dish) const\n{\n  typename std::tr1::unordered_map<Dish, int>::const_iterator \n  //typename google::sparse_hash_map<Dish, int>::const_iterator \n    dcit = find(dish);\n  if (dcit != end())\n    return dcit->second;\n  else\n    return 0;\n}\n\ntemplate <typename Dish, typename Hash>\nint \nPYP<Dish,Hash>::decrement(Dish dish)\n{\n  typename std::tr1::unordered_map<Dish, int>::iterator dcit = find(dish);\n  //typename google::sparse_hash_map<Dish, int>::iterator dcit = find(dish);\n  if (dcit == end()) {\n    std::cerr << dish << std::endl;\n    assert(false);\n  } \n\n  int delta = 0;\n\n  typename std::tr1::unordered_map<Dish, TableCounter>::iterator dtit = _dish_tables.find(dish);\n  //typename google::sparse_hash_map<Dish, TableCounter>::iterator dtit = _dish_tables.find(dish);\n  if (dtit == _dish_tables.end()) {\n    std::cerr << dish << std::endl;\n    assert(false);\n  } \n  TableCounter &tc = dtit->second;\n\n  //std::cerr << \"\\tdecrement for \" << dish << \"\\n\";\n  //std::cerr << \"\\tBEFORE histogram: \" << tc.table_histogram << \" \";\n  //std::cerr << \"count: \" << count(dish) << \" \";\n  //std::cerr << \"tables: \" << tc.tables << \"\\n\";\n\n  //double r = rnd() * count(dish);\n  double r = mt_genrand_res53() * count(dish);\n  for (std::map<int,int>::iterator hit = tc.table_histogram.begin();\n       hit != tc.table_histogram.end(); ++hit)\n  {\n    //r -= (hit->first - _a) * hit->second;\n    r -= (hit->first) * hit->second;\n    if (r <= 0)\n    {\n      if (hit->first > 1)\n        tc.table_histogram[hit->first-1] += 1;\n      else\n      {\n        delta = -1;\n        tc.tables -= 1;\n        _total_tables -= 1;\n      }\n\n      hit->second -= 1;\n      if (hit->second == 0) tc.table_histogram.erase(hit);\n      break;\n    }\n  }\n  if (r > 0) {\n    std::cerr << r << \" \" << count(dish) << \" \" << _a << \" \" << num_tables(dish) << std::endl;\n    assert(false);\n  }\n\n  // remove the customer\n  dcit->second -= 1;\n  _total_customers -= 1;\n  assert(dcit->second >= 0);\n  if (dcit->second == 0) {\n    erase(dcit);\n    _dish_tables.erase(dtit);\n    //std::cerr << \"\\tAFTER histogram: Empty\\n\";\n  }\n  else {\n    //std::cerr << \"\\tAFTER histogram: \" << _dish_tables[dish].table_histogram << \" \";\n    //std::cerr << \"count: \" << count(dish) << \" \";\n    //std::cerr << \"tables: \" << _dish_tables[dish].tables << \"\\n\";\n  }\n\n  return delta;\n}\n\ntemplate <typename Dish, typename Hash>\nint \nPYP<Dish,Hash>::num_tables(Dish dish) const\n{\n  typename std::tr1::unordered_map<Dish, TableCounter, Hash>::const_iterator \n  //typename google::sparse_hash_map<Dish, TableCounter, Hash>::const_iterator \n    dtit = _dish_tables.find(dish);\n\n  //assert(dtit != _dish_tables.end());\n  if (dtit == _dish_tables.end())\n    return 0;\n\n  return dtit->second.tables;\n}\n\ntemplate <typename Dish, typename Hash>\nint \nPYP<Dish,Hash>::num_tables() const\n{\n  return _total_tables;\n}\n\ntemplate <typename Dish, typename Hash>\nstd::ostream&\nPYP<Dish,Hash>::debug_info(std::ostream& os) const\n{\n  int hists = 0, tables = 0;\n  for (typename std::tr1::unordered_map<Dish, TableCounter, Hash>::const_iterator \n  //for (typename google::sparse_hash_map<Dish, TableCounter, Hash>::const_iterator \n       dtit = _dish_tables.begin(); dtit != _dish_tables.end(); ++dtit)\n  {\n    hists += dtit->second.table_histogram.size();\n    tables += dtit->second.tables;\n\n//    if (dtit->second.tables <= 0)\n//      std::cerr << dtit->first << \" \" << count(dtit->first) << std::endl;\n    assert(dtit->second.tables > 0);\n    assert(!dtit->second.table_histogram.empty());\n\n//    os << \"Dish \" << dtit->first << \" has \" << count(dtit->first) << \" customers, and is sitting at \" << dtit->second.tables << \" tables.\\n\"; \n    for (std::map<int,int>::const_iterator \n         hit = dtit->second.table_histogram.begin();\n         hit != dtit->second.table_histogram.end(); ++hit) {\n//      os << \"    \" << hit->second << \" tables with \" << hit->first << \" customers.\" << std::endl; \n      assert(hit->second > 0);\n    }\n  }\n\n  os << \"restaurant has \" \n    << _total_customers << \" customers; \"\n    << _total_tables << \" tables; \" \n    << tables << \" tables'; \" \n    << num_types() << \" dishes; \"\n    << _dish_tables.size() << \" dishes'; and \"\n    << hists << \" histogram entries\\n\";\n\n  return os;\n}\n\ntemplate <typename Dish, typename Hash>\nvoid \nPYP<Dish,Hash>::clear()\n{\n  this->std::tr1::unordered_map<Dish,int,Hash>::clear();\n  //this->google::sparse_hash_map<Dish,int,Hash>::clear();\n  _dish_tables.clear();\n  _total_tables = _total_customers = 0;\n}\n\n// log_restaurant_prob returns the log probability of the PYP table configuration.\n// Excludes Hierarchical P0 term which must be calculated separately.\ntemplate <typename Dish, typename Hash>\ndouble \nPYP<Dish,Hash>::log_restaurant_prob() const {\n  if (_total_customers < 1)\n    return (double)0.0;\n\n  double log_prob = 0.0;\n  double lgamma1a = lgamma(1.0-_a);\n\n  //std::cerr << \"-------------------\\n\" << std::endl;\n  for (typename DishTableType::const_iterator dish_it=_dish_tables.begin(); \n       dish_it != _dish_tables.end(); ++dish_it) {\n    for (std::map<int, int>::const_iterator table_it=dish_it->second.table_histogram.begin(); \n         table_it !=dish_it->second.table_histogram.end(); ++table_it) {\n      log_prob += (table_it->second * (lgamma(table_it->first - _a) - lgamma1a));\n      //std::cerr << \"|\" << dish_it->first->parent << \" --> \" << dish_it->first->rhs << \" \" << table_it->first << \" \" << table_it->second << \" \" << log_prob;\n    }\n  }\n  //std::cerr << std::endl;\n\n  log_prob += (_a == (double)0.0 ? (_total_tables-1.0)*log(_b) : (_total_tables-1.0)*log(_a) + lgamma((_total_tables-1.0) + _b/_a) - lgamma(_b/_a));\n  //std::cerr << \"\\t\\t\" << log_prob << std::endl;\n  log_prob += (lgamma(1.0 + _b) - lgamma(_total_customers + _b));\n\n  //std::cerr << _total_customers << \" \" << _total_tables << \" \" << log_prob << \" \" << log_prior() << std::endl;\n  //std::cerr << _a << \" \" << _b << std::endl;\n  if (!std::isfinite(log_prob)) {\n    assert(false);\n  }\n  //return log_prob;\n  if (log_prob > 0.0)\n    std::cerr << log_prob << std::endl;\n  return log_prob;// + log_prior();\n}\n\ntemplate <typename Dish, typename Hash>\ndouble \nPYP<Dish,Hash>::log_prior() const {\n  double prior = 0.0;\n  if (_a_beta_a > 0.0 && _a_beta_b > 0.0 && _a > 0.0)\n    prior += log_prior_a(_a, _a_beta_a, _a_beta_b);\n  if (_b_gamma_s > 0.0 && _b_gamma_c > 0.0)\n    prior += log_prior_b(_b, _b_gamma_c, _b_gamma_s);\n\n  return prior;\n}\n\ntemplate <typename Dish, typename Hash>\ndouble \nPYP<Dish,Hash>::log_prior_a(double a, double beta_a, double beta_b) {\n  return lbetadist(a, beta_a, beta_b); \n}\n\ntemplate <typename Dish, typename Hash>\ndouble \nPYP<Dish,Hash>::log_prior_b(double b, double gamma_c, double gamma_s) {\n  return lgammadist(b, gamma_c, gamma_s); \n}\n\ntemplate <typename Dish, typename Hash>\nlong double PYP<Dish,Hash>::lbetadist(long double x, long double alpha, long double beta) {\n  assert(x > 0);\n  assert(x < 1);\n  assert(alpha > 0);\n  assert(beta > 0);\n  return (alpha-1)*log(x)+(beta-1)*log(1-x)+lgamma(alpha+beta)-lgamma(alpha)-lgamma(beta);\n//boost::math::lgamma\n}\n\ntemplate <typename Dish, typename Hash>\nlong double PYP<Dish,Hash>::lgammadist(long double x, long double alpha, long double beta) {\n  assert(alpha > 0);\n  assert(beta > 0);\n  return (alpha-1)*log(x) - alpha*log(beta) - x/beta - lgamma(alpha);\n}\n\n\ntemplate <typename Dish, typename Hash>\n  template <typename Uniform01>\nvoid \nPYP<Dish,Hash>::resample_prior(Uniform01& rnd) {\n  for (int num_its=5; num_its >= 0; --num_its) {\n    resample_prior_b(rnd);\n    resample_prior_a(rnd);\n  }\n  resample_prior_b(rnd);\n}\n\ntemplate <typename Dish, typename Hash>\n  template <typename Uniform01>\nvoid \nPYP<Dish,Hash>::resample_prior_b(Uniform01& rnd) {\n  if (_total_tables == 0) \n    return;\n\n  //int niterations = 10;   // number of resampling iterations\n  int niterations = 5;   // number of resampling iterations\n  //std::cerr << \"\\n## resample_prior_b(), initial a = \" << _a << \", b = \" << _b << std::endl;\n  resample_b_type b_log_prob(_total_customers, _total_tables, _a, _b_gamma_c, _b_gamma_s);\n  _b = slice_sampler1d(b_log_prob, _b, rnd, (double) 0.0, std::numeric_limits<double>::infinity(), \n  //_b = slice_sampler1d(b_log_prob, _b, mt_genrand_res53, (double) 0.0, std::numeric_limits<double>::infinity(), \n                       (double) 0.0, niterations, 100*niterations);\n  //std::cerr << \"\\n## resample_prior_b(), final a = \" << _a << \", b = \" << _b << std::endl;\n}\n\ntemplate <typename Dish, typename Hash>\n  template <typename Uniform01>\nvoid \nPYP<Dish,Hash>::resample_prior_a(Uniform01& rnd) {\n  if (_total_tables == 0) \n    return;\n\n  //int niterations = 10;\n  int niterations = 5;\n  //std::cerr << \"\\n## Initial a = \" << _a << \", b = \" << _b << std::endl;\n  resample_a_type a_log_prob(_total_customers, _total_tables, _b, _a_beta_a, _a_beta_b, _dish_tables);\n  _a = slice_sampler1d(a_log_prob, _a, rnd, std::numeric_limits<double>::min(), \n  //_a = slice_sampler1d(a_log_prob, _a, mt_genrand_res53, std::numeric_limits<double>::min(), \n                       (double) 1.0, (double) 0.0, niterations, 100*niterations);\n}\n\n#endif\n", "meta": {"hexsha": "b1cb62bef4426e4097f8e9272c0fa9c39b3aeb29", "size": 19176, "ext": "hh", "lang": "C++", "max_stars_repo_path": "gi/pyp-topics/src/pyp.hh", "max_stars_repo_name": "agesmundo/FasterCubePruning", "max_stars_repo_head_hexsha": "f80150140b5273fd1eb0dfb34bdd789c4cbd35e6", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-03T00:44:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-03T00:44:01.000Z", "max_issues_repo_path": "gi/pyp-topics/src/pyp.hh", "max_issues_repo_name": "jhclark/cdec", "max_issues_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "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": "gi/pyp-topics/src/pyp.hh", "max_forks_repo_name": "jhclark/cdec", "max_forks_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-19T12:44:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T12:44:54.000Z", "avg_line_length": 33.8201058201, "max_line_length": 157, "alphanum_fraction": 0.6368377138, "num_tokens": 5871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5260272276199274}}
{"text": "#include <Engine/MeshEdit/MinSurf.h>\n\n#include <Engine/Primitive/TriMesh.h>\n\n#include <Eigen/Sparse>\n\nusing namespace Ubpa;\n\nusing namespace std;\nusing namespace Eigen;\n\nMinSurf::MinSurf(Ptr<TriMesh> triMesh)\n\t: heMesh(make_shared<HEMesh<V>>())\n{\n\tInit(triMesh);\n}\n\nvoid MinSurf::Clear() {\n\theMesh->Clear();\n\ttriMesh = nullptr;\n}\n\nbool MinSurf::Init(Ptr<TriMesh> triMesh) {\n\tClear();\n\n\tif (triMesh == nullptr)\n\t\treturn true;\n\n\tif (triMesh->GetType() == TriMesh::INVALID) {\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is invalid\\n\");\n\t\treturn false;\n\t}\n\n\t// init half-edge structure\n\tsize_t nV = triMesh->GetPositions().size();\n\tvector<vector<size_t>> triangles;\n\ttriangles.reserve(triMesh->GetTriangles().size());\n\tfor (auto triangle : triMesh->GetTriangles())\n\t\ttriangles.push_back({ triangle->idx[0], triangle->idx[1], triangle->idx[2] });\n\theMesh->Reserve(nV);\n\theMesh->Init(triangles);\n\n\tif (!heMesh->IsTriMesh() || !heMesh->HaveBoundary()) {\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is not a triangle mesh or hasn't a boundaries\\n\");\n\t\theMesh->Clear();\n\t\treturn false;\n\t}\n\n\t// triangle mesh's positions ->  half-edge structure's positions\n\tfor (int i = 0; i < nV; i++) {\n\t\tauto v = heMesh->Vertices().at(i);\n\t\tv->pos = triMesh->GetPositions()[i].cast_to<vecf3>();\n\t}\n\n\tthis->triMesh = triMesh;\n\treturn true;\n}\n\nbool MinSurf::Run() {\n\tif (heMesh->IsEmpty() || !triMesh) {\n\t\tprintf(\"ERROR::MinSurf::Run\\n\"\n\t\t\t\"\\t\"\"heMesh->IsEmpty() || !triMesh\\n\");\n\t\treturn false;\n\t}\n\n\tMinimize();\n\n\t// half-edge structure -> triangle mesh\n\tsize_t nV = heMesh->NumVertices();\n\tsize_t nF = heMesh->NumPolygons();\n\tvector<pointf3> positions;\n\tvector<unsigned> indice;\n\tpositions.reserve(nV);\n\tindice.reserve(3 * nF);\n\tfor (auto v : heMesh->Vertices())\n\t\tpositions.push_back(v->pos.cast_to<pointf3>());\n\tfor (auto f : heMesh->Polygons()) { // f is triangle\n\t\tfor (auto v : f->BoundaryVertice()) // vertices of the triangle\n\t\t\tindice.push_back(static_cast<unsigned>(heMesh->Index(v)));\n\t}\n\n\ttriMesh->Init(indice, positions);\n\n\treturn true;\n}\n\nvoid MinSurf::Minimize() {\n\t\n\tLaplace_init();\n\n\tPredecomposition();\n\n\tSolve();\n\n\n\tcout << \"INFO::MinSurf::Minimize:\" << endl\n\t\t<< \"\\t\" << \"Success\" << endl;\n}\n\nvoid MinSurf::Laplace_init()\n{\n\tsize_t nV = heMesh->NumVertices();\n\n\t//\tgenerate Laplace Matrix\n\tvector<Eigen::Triplet<double>> Lij;\n\n\tfor (size_t i = 0; i < nV; i++)\n\t{\n\t\tV* v1 = heMesh->Vertices()[i];\n\t\tLij.push_back(Eigen::Triplet<double>(i, i, 1));\n\t\tif(!v1->IsBoundary())\n\t\t{\n\t\t\tdouble connect_num = v1->AdjVertices().size();\n\t\t\tfor (size_t j = 0; j < connect_num; j++)\n\t\t\t{\n\t\t\t\tLij.push_back(Eigen::Triplet<double>(i, heMesh->Index(v1->AdjVertices()[j]), -1 / connect_num));\n\t\t\t}\n\t\t}\n\t}\n\n\tLaplace_matrix.resize(nV, nV);\n\tLaplace_matrix.setZero();\n\n\tLaplace_matrix.setFromTriplets(Lij.begin(), Lij.end());\n\t//Laplace_matrix.makeCompressed();\n}\n\nvoid MinSurf::Predecomposition()\n{\n\tsolver.compute(Laplace_matrix);\n\tif (solver.info() != Eigen::Success)\n\t{\n\t\tthrow std::exception(\"Compute Matrix Is Error!\");\n\t\treturn;\n\t}\n}\n\nvoid MinSurf::Solve()\n{\n\tsize_t nV = heMesh->NumVertices();\n\tEigen::VectorXd x(nV), y(nV), z(nV);\n\tEigen::VectorXd bx(nV), by(nV), bz(nV);\n\tbx.setZero(); by.setZero(); bz.setZero();\n\n\tfor (size_t i = 0; i < nV; i++)\n\t{\n\t\tV* v = heMesh->Vertices()[i];\n\t\tif (v->IsBoundary())\n\t\t{\n\t\t\tbx(i) = v->pos.at(0);\n\t\t\tby(i) = v->pos.at(1);\n\t\t\tbz(i) = v->pos.at(2);\n\t\t}\n\t}\n\n\tx = solver.solve(bx);\n\ty = solver.solve(by);\n\tz = solver.solve(bz);\n\n\tfor (size_t i = 0; i < nV; i++)\n\t{\n\t\theMesh->Vertices()[i]->pos.at(0) = x(i);\n\t\theMesh->Vertices()[i]->pos.at(1) = y(i);\n\t\theMesh->Vertices()[i]->pos.at(2) = z(i);\n\t}\n}", "meta": {"hexsha": "52aeda2ac31144463aff67854d2e395df26864aa", "size": 3630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/MinSurf.cpp", "max_stars_repo_name": "Chaphlagical/USTC_CG", "max_stars_repo_head_hexsha": "9f8b0321e09e5a05afb1c93303e3c736f78503fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T03:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T01:25:02.000Z", "max_issues_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/MinSurf.cpp", "max_issues_repo_name": "lyf7115/USTC_CG", "max_issues_repo_head_hexsha": "9f8b0321e09e5a05afb1c93303e3c736f78503fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/MinSurf.cpp", "max_forks_repo_name": "lyf7115/USTC_CG", "max_forks_repo_head_hexsha": "9f8b0321e09e5a05afb1c93303e3c736f78503fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-06-13T13:14:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T07:36:05.000Z", "avg_line_length": 21.6071428571, "max_line_length": 100, "alphanum_fraction": 0.6371900826, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5260272262975878}}
{"text": "#include <unistd.h> // getopt\n#include <cstring> // memcpy\n#include <iostream> // cout\n#include <sys/stat.h> // stat\n#include <chrono> // high_resolution_clock\n#include <cstdio> // printf\n#include <fstream> // ifstream, ofstream\n#include <sstream> // stringstream\n#include <ratio>  // milli\n\n#ifdef _OPENMP\n#include \"omp.h\" // omp_set_num_threads\n#endif\n\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n\n#include \"inf.hpp\"\n//#include \"getInf.hpp\"\n#include \"util.hpp\"\n#include \"floyd_warshall.hpp\"\n#include \"johnson.hpp\"\n\nstruct bench_result{\n  bool correct;\n  double seq_total_time;\n  double total_time;\n};\n\ntemplate<typename Number>\nvoid print_matrix(int n, int n_blocked, Number *adjacencyMatrix, Number *distanceMatrix, Number *solution, int *successorMatrix){\n  if(adjacencyMatrix != nullptr){\n    std::cout << \"[adjacencyMatrix]\\n\";\n    print_matrix<Number>(adjacencyMatrix, n, n_blocked);\n  }\n  if(distanceMatrix != nullptr){\n    std::cout << \"[distanceMatrix]\\n\";\n    print_matrix<Number>(distanceMatrix, n, n_blocked);\n  }\n  if (solution != nullptr) {\n    std::cout << \"[solution]\\n\";\n    print_matrix<Number>(solution, n, n);\n  }\n  if (successorMatrix != nullptr) {\n    std::cout << \"[successorMatrix]\\n\";\n    print_matrix<int>(successorMatrix, n, n_blocked);\n  }\n}\n\ntemplate<typename Number> inline char getTypeChar();\ntemplate<> inline char getTypeChar<double>(){\n  return 'd';\n}\ntemplate<> inline char getTypeChar<float>(){\n  return 'f';\n}\ntemplate<> inline char getTypeChar<int>(){\n  return 'i';\n}\n\ntemplate<typename Number>\nNumber* get_solution(\n  const int n,\n  double p,\n  unsigned long seed){\n  size_t size = n * n * sizeof(Number);\n  Number *solution = (Number *) malloc(size);\n  bool write_solution_to_file = true;\n  char chr = getTypeChar<Number>();\n\n  // have we cached the solution before?\n  std::string solution_filename = get_solution_filename(\"apsp\", n, p, seed, chr);\n  struct stat file_stat;\n  bool solution_available = stat(solution_filename.c_str(), &file_stat) != -1 || errno != ENOENT;\n\n  if (solution_available) {\n    // std::cout << \"Reading reference solution from file: \" << solution_filename << \"\\n\";\n    std::ifstream in(solution_filename, std::ios::in | std::ios::binary);\n    in.read(reinterpret_cast<char *>(solution), size);\n    in.close();\n    // std::cout << \"filename: \" << solution_filename << \" size: \" << size << \" bytes read.\\n\";\n  } else {\n    const Number *adjacencyMatrix = create_random_adjacencyMatrix<Number>(n, p, seed);\n    auto start = std::chrono::high_resolution_clock::now();\n    if(p > 0.1){\n      floyd_warshall_blocked<Number>(adjacencyMatrix, &solution, n, 32);\n    }else{\n     johnson_parallel_matrix<Number>(adjacencyMatrix, &solution, n);\n    }\n\n    //floyd_warshall<Number>(adjacencyMatrix, &solution, n);\n    auto end = std::chrono::high_resolution_clock::now();\n\n    std::chrono::duration<double, std::milli> start_to_end = end - start;\n    std::cout << \"Algorithm runtime: \" << start_to_end.count() << \"ms\\n\";\n\n    delete[] adjacencyMatrix;\n\n    if (write_solution_to_file) {\n      std::cout << \"Writing solution to file: \" << solution_filename << \"\\n\";\n\n      if (system(\"mkdir -p solution_cache\") == -1) {\n        std::cerr << \"mkdir failed!\";\n        return nullptr;\n      }\n\n      std::ofstream out(solution_filename, std::ios::out | std::ios::binary);\n      out.write(reinterpret_cast<const char *>(solution), size);\n      out.close();\n    }\n  }\n  return solution;\n}\n\ntemplate<typename Number>\ndouble do_floyd_warshall(int n, int block_size, double p, unsigned long seed, bool with_successor, bool check_correctness){\n\n  Number *solution = check_correctness ? get_solution<Number>(n, p, seed) : nullptr;\n\n  Number *adjacencyMatrix = create_random_adjacencyMatrix<Number>(n, p, seed);\n  Number *distanceMatrix = nullptr;\n  int *successorMatrix = nullptr;\n\n  auto start = std::chrono::high_resolution_clock::now();\n  if (with_successor) {\n    floyd_warshall_blocked<Number>(adjacencyMatrix, &distanceMatrix, &successorMatrix, n, block_size);\n  } else {\n    floyd_warshall_blocked<Number>(adjacencyMatrix, &distanceMatrix, n, block_size);floyd_warshall_blocked<Number>(adjacencyMatrix, &distanceMatrix, n, block_size);\n  }\n  auto end = std::chrono::high_resolution_clock::now();\n  std::chrono::duration<double, std::milli> start_to_end = end - start;\n\n  if (check_correctness) {\n    if(n <= 256) print_matrix(n, n, adjacencyMatrix, distanceMatrix, solution, successorMatrix);\n    correctness_check<Number>(distanceMatrix, n, solution, n);\n  }\n  if (check_correctness) {\n    delete[] solution;\n  }\n  if (with_successor) {\n    delete[] successorMatrix;\n  }\n  delete[] distanceMatrix;\n  delete[] adjacencyMatrix;\n\n  return start_to_end.count();\n}\n\n\ntemplate<typename Number>\nbench_result * bench_floyd_warshall(int iterations, int v, int block_size, double p, unsigned long seed, bool with_successor, bool check_correctness) {\n\n  Number *solution = check_correctness ? get_solution<Number>(v, p, seed) : nullptr;\n  const Number *adjacencyMatrix = create_random_adjacencyMatrix<Number>(v, p, seed);\n  static const Number inf = getInf<Number>();\n\n  bench_result *result = new bench_result;\n  result->correct = true;\n  result->seq_total_time = 0.0;\n  result->total_time = 0.0;\n\n  for (int b = 0; b < iterations; b++) {\n\n    Number *distanceMatrix = nullptr;\n    int *successorMatrix = nullptr;\n\n    auto seq_start = std::chrono::high_resolution_clock::now();\n    if (with_successor) {\n      floyd_warshall<Number>(adjacencyMatrix, &distanceMatrix, &successorMatrix, v);\n    } else {\n      floyd_warshall<Number>(adjacencyMatrix, &distanceMatrix, v);\n    }\n    auto seq_end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double, std::milli> seq_start_to_end = seq_end - seq_start;\n    result->seq_total_time += seq_start_to_end.count() / iterations;;\n\n    delete[] distanceMatrix;\n    if(with_successor){\n      delete[] successorMatrix;\n    }\n\n    distanceMatrix = nullptr;\n    successorMatrix = nullptr;\n\n    auto start = std::chrono::high_resolution_clock::now();\n    if (with_successor) {\n      floyd_warshall_blocked<Number>(adjacencyMatrix, &distanceMatrix, &successorMatrix, v, block_size);\n    } else {\n      floyd_warshall_blocked<Number>(adjacencyMatrix, &distanceMatrix, v, block_size);\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double, std::milli> start_to_end = end - start;\n    result->total_time += start_to_end.count() / iterations;;\n\n    if (check_correctness) {\n      result->correct = result->correct && correctness_check<Number>(distanceMatrix, v, solution, v);\n    }\n\n    delete[] distanceMatrix;\n    if(with_successor){\n      delete[] successorMatrix;\n    }\n  }\n\n  if (check_correctness) {\n    delete[] solution;\n  }\n  delete[] adjacencyMatrix;\n\n  return result;\n}\n\ntemplate<typename Number>\ndouble do_johnson(const int n, const double p, const unsigned long seed, const bool with_successor, const bool check_correctness){\n\n  Number *solution = check_correctness ? get_solution<Number>(n, p, seed) : nullptr;\n  Number *adjacencyMatrix = create_random_adjacencyMatrix<Number>(n, p, seed);\n  Number *distanceMatrix = nullptr;\n  int *successorMatrix = nullptr;\n\n  auto start = std::chrono::high_resolution_clock::now();\n  if (with_successor) {\n    johnson_parallel_matrix<Number>(adjacencyMatrix, &distanceMatrix, &successorMatrix, n);\n  } else {\n    johnson_parallel_matrix<Number>(adjacencyMatrix, &distanceMatrix, n);\n  }\n  auto end = std::chrono::high_resolution_clock::now();\n\n  if (check_correctness) {\n    if(n <= 256) print_matrix(n, n, adjacencyMatrix, distanceMatrix, solution, successorMatrix);\n    correctness_check<Number>(distanceMatrix, n, solution, n);\n  }\n\n  delete[] distanceMatrix;\n  if (with_successor) {\n    delete[] successorMatrix;\n  }\n  delete[] adjacencyMatrix;\n  if (check_correctness){\n    delete[] solution;\n  }\n\n  std::chrono::duration<double, std::milli> start_to_end = end - start;\n  return start_to_end.count();\n}\n\ntemplate<typename Number>\nbench_result * bench_johnson(int iterations, int n, double p, unsigned long seed, bool with_successor, bool check_correctness) {\n\n  Number *solution = check_correctness ? get_solution<Number>(n, p, seed) : nullptr;\n  Number *adjacencyMatrix = create_random_adjacencyMatrix<Number>(n, p, seed);\n\n  Number inf = getInf<Number>();\n\n  bench_result *result = new bench_result;\n  result->correct = true;\n  result->seq_total_time = 0.0;\n  result->total_time = 0.0;\n\n  for (int b = 0; b < iterations; b++) {\n\n    Number *distanceMatrix = nullptr;\n    int *successorMatrix = nullptr;\n\n    auto start = std::chrono::high_resolution_clock::now();\n    graph_t<Number> *gr = init_graph<Number>(adjacencyMatrix, n);\n    if (with_successor) {\n      johnson_parallel_matrix<Number>(adjacencyMatrix, &distanceMatrix, &successorMatrix, (const int)n);\n    } else {\n      johnson_parallel_matrix<Number>(adjacencyMatrix, &distanceMatrix, (const int)n);\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double, std::milli> start_to_end = end - start;\n    result->total_time += start_to_end.count() / iterations;\n\n    delete[] distanceMatrix;\n    if(with_successor){\n      delete[] successorMatrix;\n    }\n\n    auto seq_start = std::chrono::high_resolution_clock::now();\n    Graph<Number> G(gr->edge_array, gr->edge_array + gr->E, gr->weights, gr->V);\n    std::vector<Number> d(num_vertices(G));\n    std::vector<int> predecessor(num_vertices(G));\n    Number **distanceArray = new Number *[n];\n    for (int i = 0; i < n; i++) distanceArray[i] = &adjacencyMatrix[i * n];\n    if (with_successor) {\n      johnson_all_pairs_shortest_paths(G, distanceArray, distance_map(&d[0]).predecessor_map(&predecessor[0]).distance_inf(inf));\n    }else{\n      johnson_all_pairs_shortest_paths(G, distanceArray, distance_map(&d[0]).distance_inf(inf));\n    }\n    auto seq_end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double, std::milli> seq_start_to_end = seq_end - seq_start;\n    result->seq_total_time += seq_start_to_end.count() / iterations;\n\n    free_graph<Number>(gr);\n    delete[] distanceArray;\n\n    if (solution != nullptr) {\n      result->correct = result->correct && correctness_check<Number>(distanceMatrix, n, solution, n);\n    }\n  }\n\n  if (check_correctness) {\n    delete[] solution;\n  }\n  delete[] adjacencyMatrix;\n\n  return result;\n}\n\ntemplate<typename Number>\nint do_benchmark(\n  int iterations,\n  unsigned long seed,\n  bool use_floyd_warshall,\n  int block_size,\n  bool with_successor,\n  bool check_correctness\n) {\n\n  if (use_floyd_warshall) {\n      std::cout << \"\\n\\nFloyd-Warshall's Algorithm benchmarking results for seed=\" << seed << \" and block size=\"\n                << block_size << \"\\n\";\n      print_table_header(check_correctness);\n\n      for (double p = 0.25; p < 1.0; p += 0.25) {\n        for (int v = 64; v <= 4096; v *= 2) {\n          bench_result *result = bench_floyd_warshall<Number>(iterations, v, block_size, p, seed, with_successor, check_correctness);\n          print_table_row(p, v, result->seq_total_time, result->total_time, result->correct, check_correctness);\n          delete result;\n        }\n        print_table_break(check_correctness);\n      }\n      std::cout << \"\\n\\n\";\n  } else {  // Using Johnson's Algorithm\n      std::cout << \"\\n\\nJohnson's Algorithm benchmarking results for seed=\" << seed << \"\\n\";\n      print_table_header(check_correctness);\n      for (double p = 0.025; p < 0.1; p += 0.025) {\n        for (int v = 64; v <= 4096; v *= 2) {\n          bench_result *result = bench_johnson<Number>(iterations, v, p, seed, with_successor, check_correctness);\n          print_table_row(p, v, result->seq_total_time, result->total_time, result->correct, check_correctness);\n          delete result;\n        }\n        print_table_break(check_correctness);\n      }\n      std::cout << \"\\n\\n\";\n  }\n\n  return 0;\n}\n\ntemplate<typename Number>\nint do_main(\n  int n,\n  double p,\n  unsigned long seed,\n  bool with_successor,\n  bool use_floyd_warshall,\n  int block_size,\n  bool check_correctness\n) {\n\n  if (use_floyd_warshall) {\n      std::cout << \"Using Floyd-Warshall's on \" << n << \"x\" << n\n                << \" with p=\" << p << \" and seed=\" << seed << \"\\n\";\n      double start_to_end_count = do_floyd_warshall<Number>(n, block_size, p, seed, with_successor, check_correctness);\n      std::cout << \"Algorithm runtime: \" << start_to_end_count << \"ms\\n\\n\";\n  } else {  // Using Johnson's Algorithm\n      std::cout << \"Using Johnson's on \" << n << \"x\" << n\n                << \" with p=\" << p << \" and seed=\" << seed << \"\\n\";\n      double start_to_end_count = do_johnson<Number>(n, p, seed, with_successor, check_correctness);\n      std::cout << \"Algorithm runtime: \" << start_to_end_count << \"ms\\n\\n\";\n  }\n\n  return 0;\n}\n\n\nint main(int argc, char *argv[]) {\n  // parameter defaults\n  unsigned long seed = 0;\n  int n = 1024;\n  double p = 0.01;\n  bool use_floyd_warshall = true;\n  bool benchmark = false;\n  bool check_correctness = false;\n  bool with_successor = false;\n  int block_size = 16;\n  int thread_count = 1;\n  char type = 'i';\n  int iterations = 5;\n\n  extern char *optarg;\n  int opt;\n  while ((opt = getopt(argc, argv, \"ha:n:p:s:bd:ct:T:Si:\")) != -1) {\n    switch (opt) {\n      case 'h':\n      case '?': // illegal command\n      case ':': // forgot command's argument\n        print_usage();\n        return 0;\n\n      case 'a':\n        if (optarg[0] == 'j') {\n          use_floyd_warshall = false;\n        } else if (optarg[0] != 'f') {\n          std::cerr << \"Illegal algorithm argument, must be f or j\\n\";\n          return -1;\n        }\n        break;\n\n      case 'p':\n        p = std::stod(optarg);\n        break;\n\n      case 's':\n        seed = std::stoul(optarg);\n        break;\n\n      case 'b':\n        benchmark = true;\n        break;\n\n      case 'n':\n        n = std::stoi(optarg);\n        break;\n\n      case 'i':\n        iterations = std::stoi(optarg);\n        break;\n\n      case 'd':\n        block_size = std::stoi(optarg);\n        break;\n\n      case 'c':\n        check_correctness = true;\n        break;\n\n      case 't':\n        thread_count = std::stoi(optarg);\n        break;\n\n      case 'S':\n        with_successor = true;\n        break;\n\n      case 'T':\n        if (optarg[0] == 'i') {\n          type = 'i'; // int\n        } else if (optarg[0] == 'f') {\n          type = 'f'; // float\n        } else if (optarg[0] == 'd') {\n          type = 'd'; // double\n        } else {\n          std::cerr << \"Illegal type argument (neigher i, f nor d)\\n\";\n          return -1;\n        }\n        break;\n    }\n  }\n\n#ifdef _OPENMP\n  if(thread_count > 1){\n    omp_set_num_threads(thread_count);\n  }\n#else\n  (void) thread_count; // suppress unused warning\n#endif\n\n  if(benchmark){\n    switch(type){\n      case 'i':\n        return do_benchmark<int>(iterations, seed, use_floyd_warshall, block_size, with_successor, check_correctness);\n      case 'f':\n        return do_benchmark<float>(iterations, seed, use_floyd_warshall, block_size, with_successor, check_correctness);\n      case 'd':\n        return do_benchmark<double>(iterations, seed, use_floyd_warshall, block_size, with_successor, check_correctness);\n    }\n  }else{\n    switch(type){\n      case 'i':\n        return do_main<int>(n, p, seed, with_successor, use_floyd_warshall, block_size, check_correctness);\n      case 'f':\n        return do_main<float>(n, p, seed, with_successor, use_floyd_warshall, block_size, check_correctness);\n      case 'd':\n        return do_main<double>(n, p, seed, with_successor, use_floyd_warshall, block_size, check_correctness);\n    }\n  }\n  return -1;\n}\n", "meta": {"hexsha": "bc30c9df61aa83bb28893f2f76a3d066c7378c05", "size": 15648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "kubohiroya/APSP-in-parallel", "max_stars_repo_head_hexsha": "c1f94d29f85129b6eaf3cbdf0c376939b7af3282", "max_stars_repo_licenses": ["MIT"], "max_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": "kubohiroya/APSP-in-parallel", "max_issues_repo_head_hexsha": "c1f94d29f85129b6eaf3cbdf0c376939b7af3282", "max_issues_repo_licenses": ["MIT"], "max_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": "kubohiroya/APSP-in-parallel", "max_forks_repo_head_hexsha": "c1f94d29f85129b6eaf3cbdf0c376939b7af3282", "max_forks_repo_licenses": ["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.8048780488, "max_line_length": 164, "alphanum_fraction": 0.6579754601, "num_tokens": 4117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5260272262975878}}
{"text": "/*\r\n [auto_generated]\r\n boost/numeric/odeint/stepper/runge_kutta_fehlberg87.hpp\r\n\r\n [begin_description]\r\n Implementation of the Runge-Kutta-Fehlberg stepper with the generic stepper.\r\n [end_description]\r\n\r\n Copyright 2011-2013 Mario Mulansky\r\n Copyright 2012-2013 Karsten Ahnert\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\r\n#ifndef BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA_FEHLBERG87_HPP_INCLUDED\r\n#define BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA_FEHLBERG87_HPP_INCLUDED\r\n\r\n\r\n#include <boost/fusion/container/vector.hpp>\r\n#include <boost/fusion/container/generation/make_vector.hpp>\r\n\r\n#include <boost/numeric/odeint/stepper/explicit_error_generic_rk.hpp>\r\n#include <boost/numeric/odeint/algebra/range_algebra.hpp>\r\n#include <boost/numeric/odeint/algebra/default_operations.hpp>\r\n#include <boost/numeric/odeint/algebra/algebra_dispatcher.hpp>\r\n#include <boost/numeric/odeint/algebra/operations_dispatcher.hpp>\r\n\r\n#include <boost/array.hpp>\r\n\r\n#include <boost/numeric/odeint/util/state_wrapper.hpp>\r\n#include <boost/numeric/odeint/util/is_resizeable.hpp>\r\n#include <boost/numeric/odeint/util/resizer.hpp>\r\n\r\n\r\n\r\n\r\nnamespace boost {\r\nnamespace numeric {\r\nnamespace odeint {\r\n\r\n\r\n#ifndef DOXYGEN_SKIP\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_a1 : boost::array< Value , 1 >\r\n{\r\n    rk78_coefficients_a1( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( 2 )/static_cast< Value >( 27 );\r\n            }\r\n};\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_a2 : boost::array< Value , 2 >\r\n{\r\n    rk78_coefficients_a2( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( 1 )/static_cast< Value >( 36 );\r\n        (*this)[1] = static_cast< Value >( 1 )/static_cast< Value >( 12 );\r\n            }\r\n};\r\n\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_a3 : boost::array< Value , 3 >\r\n{\r\n    rk78_coefficients_a3( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( 1 )/static_cast< Value >( 24 );\r\n        (*this)[1] = static_cast< Value >( 0 );\r\n        (*this)[2] = static_cast< Value >( 1 )/static_cast< Value >( 8 );\r\n            }\r\n};\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_a4 : boost::array< Value , 4 >\r\n{\r\n    rk78_coefficients_a4( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( 5 )/static_cast< Value >( 12 );\r\n        (*this)[1] = static_cast< Value >( 0 );\r\n        (*this)[2] = static_cast< Value >( -25 )/static_cast< Value >( 16 );\r\n        (*this)[3] = static_cast< Value >( 25 )/static_cast< Value >( 16 );\r\n            }\r\n};\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_a5 : boost::array< Value , 5 >\r\n{\r\n    rk78_coefficients_a5( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( 1 )/static_cast< Value >( 20 );\r\n        (*this)[1] = static_cast< Value >( 0 );\r\n        (*this)[2] = static_cast< Value >( 0 );\r\n        (*this)[3] = static_cast< Value >( 1 )/static_cast< Value >( 4 );\r\n        (*this)[4] = static_cast< Value >( 1 )/static_cast< Value >( 5 );\r\n            }\r\n};\r\n\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_a6 : boost::array< Value , 6 >\r\n{\r\n    rk78_coefficients_a6( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( -25 )/static_cast< Value >( 108 );\r\n        (*this)[1] = static_cast< Value >( 0 );\r\n        (*this)[2] = static_cast< Value >( 0 );\r\n        (*this)[3] = static_cast< Value >( 125 )/static_cast< Value >( 108 );\r\n        (*this)[4] = static_cast< Value >( -65 )/static_cast< Value >( 27 );\r\n        (*this)[5] = static_cast< Value >( 125 )/static_cast< Value >( 54 );\r\n            }\r\n};\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_a7 : boost::array< Value , 7 >\r\n{\r\n    rk78_coefficients_a7( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( 31 )/static_cast< Value >( 300 );\r\n        (*this)[1] = static_cast< Value >( 0 );\r\n        (*this)[2] = static_cast< Value >( 0 );\r\n        (*this)[3] = static_cast< Value >( 0 );\r\n        (*this)[4] = static_cast< Value >( 61 )/static_cast< Value >( 225 );\r\n        (*this)[5] = static_cast< Value >( -2 )/static_cast< Value >( 9 );\r\n        (*this)[6] = static_cast< Value >( 13 )/static_cast< Value >( 900 );\r\n            }\r\n};\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_a8 : boost::array< Value , 8 >\r\n{\r\n    rk78_coefficients_a8( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( 2 );\r\n        (*this)[1] = static_cast< Value >( 0 );\r\n        (*this)[2] = static_cast< Value >( 0 );\r\n        (*this)[3] = static_cast< Value >( -53 )/static_cast< Value >( 6 );\r\n        (*this)[4] = static_cast< Value >( 704 )/static_cast< Value >( 45 );\r\n        (*this)[5] = static_cast< Value >( -107 )/static_cast< Value >( 9 );\r\n        (*this)[6] = static_cast< Value >( 67 )/static_cast< Value >( 90 );\r\n        (*this)[7] = static_cast< Value >( 3 );\r\n            }\r\n};\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_a9 : boost::array< Value , 9 >\r\n{\r\n    rk78_coefficients_a9( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( -91 )/static_cast< Value >( 108 );\r\n        (*this)[1] = static_cast< Value >( 0 );\r\n        (*this)[2] = static_cast< Value >( 0 );\r\n        (*this)[3] = static_cast< Value >( 23 )/static_cast< Value >( 108 );\r\n        (*this)[4] = static_cast< Value >( -976 )/static_cast< Value >( 135 );\r\n        (*this)[5] = static_cast< Value >( 311 )/static_cast< Value >( 54 );\r\n        (*this)[6] = static_cast< Value >( -19 )/static_cast< Value >( 60 );\r\n        (*this)[7] = static_cast< Value >( 17 )/static_cast< Value >( 6 );\r\n        (*this)[8] = static_cast< Value >( -1 )/static_cast< Value >( 12 );\r\n            }\r\n};\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_a10 : boost::array< Value , 10 >\r\n{\r\n    rk78_coefficients_a10( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( 2383 )/static_cast< Value >( 4100 );\r\n        (*this)[1] = static_cast< Value >( 0 );\r\n        (*this)[2] = static_cast< Value >( 0 );\r\n        (*this)[3] = static_cast< Value >( -341 )/static_cast< Value >( 164 );\r\n        (*this)[4] = static_cast< Value >( 4496 )/static_cast< Value >( 1025 );\r\n        (*this)[5] = static_cast< Value >( -301 )/static_cast< Value >( 82 );\r\n        (*this)[6] = static_cast< Value >( 2133 )/static_cast< Value >( 4100 );\r\n        (*this)[7] = static_cast< Value >( 45 )/static_cast< Value >( 82 );\r\n        (*this)[8] = static_cast< Value >( 45 )/static_cast< Value >( 164 );\r\n        (*this)[9] = static_cast< Value >( 18 )/static_cast< Value >( 41 );\r\n            }\r\n};\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_a11 : boost::array< Value , 11 >\r\n{\r\n    rk78_coefficients_a11( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( 3 )/static_cast< Value >( 205 );\r\n        (*this)[1] = static_cast< Value >( 0 );\r\n        (*this)[2] = static_cast< Value >( 0 );\r\n        (*this)[3] = static_cast< Value >( 0 );\r\n        (*this)[4] = static_cast< Value >( 0 );\r\n        (*this)[5] = static_cast< Value >( -6 )/static_cast< Value >( 41 );\r\n        (*this)[6] = static_cast< Value >( -3 )/static_cast< Value >( 205 );\r\n        (*this)[7] = static_cast< Value >( -3 )/static_cast< Value >( 41 );\r\n        (*this)[8] = static_cast< Value >( 3 )/static_cast< Value >( 41 );\r\n        (*this)[9] = static_cast< Value >( 6 )/static_cast< Value >( 41 );\r\n        (*this)[10] = static_cast< Value >( 0 );\r\n            }\r\n};\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_a12 : boost::array< Value , 12 >\r\n{\r\n    rk78_coefficients_a12( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( -1777 )/static_cast< Value >( 4100 );\r\n        (*this)[1] = static_cast< Value >( 0 );\r\n        (*this)[2] = static_cast< Value >( 0 );\r\n        (*this)[3] = static_cast< Value >( -341 )/static_cast< Value >( 164 );\r\n        (*this)[4] = static_cast< Value >( 4496 )/static_cast< Value >( 1025 );\r\n        (*this)[5] = static_cast< Value >( -289 )/static_cast< Value >( 82 );\r\n        (*this)[6] = static_cast< Value >( 2193 )/static_cast< Value >( 4100 );\r\n        (*this)[7] = static_cast< Value >( 51 )/static_cast< Value >( 82 );\r\n        (*this)[8] = static_cast< Value >( 33 )/static_cast< Value >( 164 );\r\n        (*this)[9] = static_cast< Value >( 12 )/static_cast< Value >( 41 );\r\n        (*this)[10] = static_cast< Value >( 0 );\r\n        (*this)[11] = static_cast< Value >( 1 );\r\n            }\r\n};\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_b : boost::array< Value , 13 >\r\n{\r\n    rk78_coefficients_b( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( 0 );\r\n        (*this)[1] = static_cast< Value >( 0 );\r\n        (*this)[2] = static_cast< Value >( 0 );\r\n        (*this)[3] = static_cast< Value >( 0 );\r\n        (*this)[4] = static_cast< Value >( 0 );\r\n        (*this)[5] = static_cast< Value >( 34 )/static_cast<Value>( 105 );\r\n        (*this)[6] = static_cast< Value >( 9 )/static_cast<Value>( 35 );\r\n        (*this)[7] = static_cast< Value >( 9 )/static_cast<Value>( 35 );\r\n        (*this)[8] = static_cast< Value >( 9 )/static_cast<Value>( 280 );\r\n        (*this)[9] = static_cast< Value >( 9 )/static_cast<Value>( 280 );\r\n        (*this)[10] = static_cast< Value >( 0 );\r\n        (*this)[11] = static_cast< Value >( 41 )/static_cast<Value>( 840 );\r\n        (*this)[12] = static_cast< Value >( 41 )/static_cast<Value>( 840 );\r\n            }\r\n};\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_db : boost::array< Value , 13 >\r\n{\r\n    rk78_coefficients_db( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( 0 ) - static_cast< Value >( 41 )/static_cast<Value>( 840 );\r\n        (*this)[1] = static_cast< Value >( 0 );\r\n        (*this)[2] = static_cast< Value >( 0 );\r\n        (*this)[3] = static_cast< Value >( 0 );\r\n        (*this)[4] = static_cast< Value >( 0 );\r\n        (*this)[5] = static_cast< Value >( 0 );\r\n        (*this)[6] = static_cast< Value >( 0 );\r\n        (*this)[7] = static_cast< Value >( 0 );\r\n        (*this)[8] = static_cast< Value >( 0 );\r\n        (*this)[9] = static_cast< Value >( 0 );\r\n        (*this)[10] = static_cast< Value >( 0 ) - static_cast< Value >( 41 )/static_cast<Value>( 840 );\r\n        (*this)[11] = static_cast< Value >( 41 )/static_cast<Value>( 840 );\r\n        (*this)[12] = static_cast< Value >( 41 )/static_cast<Value>( 840 );\r\n            }\r\n};\r\n\r\n\r\ntemplate< class Value = double >\r\nstruct rk78_coefficients_c : boost::array< Value , 13 >\r\n{\r\n    rk78_coefficients_c( void )\r\n            {\r\n        (*this)[0] = static_cast< Value >( 0 );\r\n        (*this)[1] = static_cast< Value >( 2 )/static_cast< Value >( 27 );\r\n        (*this)[2] = static_cast< Value >( 1 )/static_cast< Value >( 9 );\r\n        (*this)[3] = static_cast< Value >( 1 )/static_cast<Value>( 6 );\r\n        (*this)[4] = static_cast< Value >( 5 )/static_cast<Value>( 12 );\r\n        (*this)[5] = static_cast< Value >( 1 )/static_cast<Value>( 2 );\r\n        (*this)[6] = static_cast< Value >( 5 )/static_cast<Value>( 6 );\r\n        (*this)[7] = static_cast< Value >( 1 )/static_cast<Value>( 6 );\r\n        (*this)[8] = static_cast< Value >( 2 )/static_cast<Value>( 3 );\r\n        (*this)[9] = static_cast< Value >( 1 )/static_cast<Value>( 3 );\r\n        (*this)[10] = static_cast< Value >( 1 );\r\n        (*this)[11] = static_cast< Value >( 0 );\r\n        (*this)[12] = static_cast< Value >( 1 );\r\n            }\r\n};\r\n#endif // DOXYGEN_SKIP\r\n\r\n\r\n\r\n\r\n\r\ntemplate<\r\nclass State ,\r\nclass Value = double ,\r\nclass Deriv = State ,\r\nclass Time = Value ,\r\nclass Algebra = typename algebra_dispatcher< State >::algebra_type ,\r\nclass Operations = typename operations_dispatcher< State >::operations_type ,\r\nclass Resizer = initially_resizer\r\n>\r\n#ifndef DOXYGEN_SKIP\r\nclass runge_kutta_fehlberg78 : public explicit_error_generic_rk< 13 , 8 , 8 , 7 , State , Value , Deriv , Time ,\r\nAlgebra , Operations , Resizer >\r\n#else\r\nclass runge_kutta_fehlberg78 : public explicit_error_generic_rk\r\n#endif\r\n{\r\n\r\npublic:\r\n#ifndef DOXYGEN_SKIP\r\n    typedef explicit_error_generic_rk< 13 , 8 , 8 , 7 , State , Value , Deriv , Time ,\r\n            Algebra , Operations , Resizer > stepper_base_type;\r\n#endif\r\n    typedef typename stepper_base_type::state_type state_type;\r\n    typedef typename stepper_base_type::value_type value_type;\r\n    typedef typename stepper_base_type::deriv_type deriv_type;\r\n    typedef typename stepper_base_type::time_type time_type;\r\n    typedef typename stepper_base_type::algebra_type algebra_type;\r\n    typedef typename stepper_base_type::operations_type operations_type;\r\n    typedef typename stepper_base_type::resizer_type resizer_type;\r\n\r\n    #ifndef DOXYGEN_SKIP\r\n    typedef typename stepper_base_type::stepper_type stepper_type;\r\n    typedef typename stepper_base_type::wrapped_state_type wrapped_state_type;\r\n    typedef typename stepper_base_type::wrapped_deriv_type wrapped_deriv_type;\r\n    #endif // DOXYGEN_SKIP\r\n\r\n\r\n    runge_kutta_fehlberg78( const algebra_type &algebra = algebra_type() ) : stepper_base_type(\r\n            boost::fusion::make_vector( rk78_coefficients_a1<Value>() , rk78_coefficients_a2<Value>() , rk78_coefficients_a3<Value>() ,\r\n                    rk78_coefficients_a4<Value>() , rk78_coefficients_a5<Value>() , rk78_coefficients_a6<Value>() ,\r\n                    rk78_coefficients_a7<Value>() , rk78_coefficients_a8<Value>() , rk78_coefficients_a9<Value>() ,\r\n                    rk78_coefficients_a10<Value>() , rk78_coefficients_a11<Value>() , rk78_coefficients_a12<Value>() ) ,\r\n            rk78_coefficients_b<Value>() , rk78_coefficients_db<Value>() , rk78_coefficients_c<Value>() , algebra )\r\n    { }\r\n};\r\n\r\n\r\n\r\n/************* DOXYGEN *************/\r\n\r\n/**\r\n * \\class runge_kutta_fehlberg78\r\n * \\brief The Runge-Kutta Fehlberg 78 method.\r\n *\r\n * The Runge-Kutta Fehlberg 78 method is a standard method for high-precision applications.\r\n * The method is explicit and fulfills the Error Stepper concept. Step size control\r\n * is provided but continuous output is not available for this method.\r\n * \r\n * This class derives from explicit_error_stepper_base and inherits its interface via CRTP (current recurring template pattern).\r\n * Furthermore, it derivs from explicit_error_generic_rk which is a generic Runge-Kutta algorithm with error estimation.\r\n * For more details see explicit_error_stepper_base and explicit_error_generic_rk.\r\n *\r\n * \\tparam State The state type.\r\n * \\tparam Value The value type.\r\n * \\tparam Deriv The type representing the time derivative of the state.\r\n * \\tparam Time The time representing the independent variable - the time.\r\n * \\tparam Algebra The algebra type.\r\n * \\tparam Operations The operations type.\r\n * \\tparam Resizer The resizer policy type.\r\n */\r\n\r\n\r\n    /**\r\n     * \\fn runge_kutta_fehlberg78::runge_kutta_fehlberg78( const algebra_type &algebra )\r\n     * \\brief Constructs the runge_kutta_cash_fehlberg78 class. This constructor can be used as a default\r\n     * constructor if the algebra has a default constructor.\r\n     * \\param algebra A copy of algebra is made and stored inside explicit_stepper_base.\r\n     */\r\n\r\n}\r\n}\r\n}\r\n\r\n#endif //BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA_FEHLBERG87_HPP_INCLUDED\r\n", "meta": {"hexsha": "c8869b0a39f2d6af2e6d2d0b317da879aede7874", "size": 15379, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/odeint/stepper/runge_kutta_fehlberg78.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/numeric/odeint/stepper/runge_kutta_fehlberg78.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/numeric/odeint/stepper/runge_kutta_fehlberg78.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": 41.0106666667, "max_line_length": 136, "alphanum_fraction": 0.5965927564, "num_tokens": 4199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303236047049, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5260272243361064}}
{"text": "/*\n  @file:    control_base.cpp\n  @author:  pdsherman\n  @date:    April. 2021\n\n  @brief: control base object\n*/\n\n#include <pendulum/LoggingData.h>\n#include <pendulum/State.h>\n#include <pendulum/Control.h>\n\n#include <hardware/pendulum_hardware/PendulumHardware.hpp>\n#include <libs/control/Pid.hpp>\n#include <libs/control/DigitalPid.hpp>\n#include <libs/control/LeadLag.hpp>\n#include <libs/util/ros_util.hpp>\n\n#include <boost/program_options.hpp>\n#include <ros/ros.h>\n#include <iostream>\n#include <thread>   // For this_thread::sleep_until\n#include <chrono>\n\nstatic constexpr double kRunTime_s  = 15.0;\nstatic constexpr int kUpdateCycleTime_us  = 5000;\nstatic constexpr double kMaxForce_N = 80.0;\n// Time in seconds between cycles\nstatic constexpr double step_s = static_cast<double>(kUpdateCycleTime_us) / (1e6);\n\nstatic double Kp = 195.0;\nstatic double Ki = 95.0;\nstatic double Kd = 1.5;\n\nstatic double Zero = 50.0;\nstatic double Pole = 5.0;\nstatic double Gain = 40.5;\n\n/// Publish data from cycle\nvoid publish(ros::Publisher &log_pub, ros::Publisher &state_pub,\n  pendulum::LoggingData &data, pendulum::State &state,\n  const double target, const double x, const double u, const double t);\n\n/// Initialize logging to table for test\nros::Publisher initialize_logging(ros::NodeHandle &nh, const std::string &log_table_name);\n\n/// Get current target position for system\ndouble get_target(const double test_time);\n\nbool parse_args(int argc, char *argv[]);\n\n/// ---------------------------------------- ///\n/// ----        MAIN FUNCTION           ---- ///\n/// ---------------------------------------- ///\nint main(int argc, char *argv[])\n{\n  ros::init(argc, argv, \"base_control\");\n  ros::NodeHandle nh;\n\n  if(!parse_args(argc, argv)) {\n    ROS_WARN(\"Error parsing arguments\");\n  }\n  // ---   Start Logging   --- //\n  std::string log_table = \"BaseControl\";\n  ros::Publisher log_pub = initialize_logging(nh, log_table);\n\n  // ---  Display on GUI    --- //\n  std::string state_topic = \"base_control\";\n  ros::Publisher state_pub = nh.advertise<pendulum::State>(state_topic, 50);\n  util::draw_image(nh, state_topic, 0.0, 0.0, pendulum::DrawSystemRequest::MASS_ONLY, \"blue\");\n\n  // --- Initialize Variables --- //\n  std::shared_ptr<Controller<double, double>> cntrl;\n  std::string test_name;\n  // if(argc > 1) {\n  //   if(std::string(argv[1]) == \"pid\"){\n  cntrl = std::dynamic_pointer_cast<Controller<double, double>>(\n    std::make_shared<PID>(step_s, Kp, Ki, Kd, 0.0));\n  test_name = \"PID\";\n  ROS_INFO(\"Using PID control\");\n  ROS_INFO(\"Kp: %.2f\", Kp);\n  ROS_INFO(\"Kd: %.2f\", Kd);\n  ROS_INFO(\"Ki: %.2f\", Ki);\n\n  //   } else if(std::string(argv[1]) == \"dpid\"){\n  //     cntrl = std::dynamic_pointer_cast<Controller<double, double>>(\n  //       std::make_shared<DigitalPID>(step_s, Kp, Ki, Kd, 0.0));\n  //     test_name = \"digital-PID\";\n  //   } else if(std::string(argv[1]) == \"lag\") {\n  //     cntrl = std::dynamic_pointer_cast<Controller<double, double>>(\n  //       std::make_shared<LeadLag>(step_s, Zero, Pole, Gain, LeadLag::DigitialTransform::kTustins));\n  //     test_name = \"lag\";\n  //   } else {\n  //     ROS_WARN(\"Invalid controller type\");\n  //     return 0;\n  //   }\n  // } else {\n  //   ROS_WARN(\"Need to pick a controller type (pid|dpid|lag)\");\n  //   return 0;\n  // }\n\n  PendulumHardware::Positions pos;\n  PendulumHardware hw;\n\n  pendulum::State state;\n  state.x     = 0.0;\n  state.theta = 0.0;\n\n  pendulum::LoggingData data;\n  data.test_name = test_name;\n  data.data      = std::vector<double>(4);\n\n  double x = 0.0; // Initialize Position\n  double u = 0.0; // Input command\n  double t = 0.0; // Time since start of test\n\n  // ---   Run Test   --- //\n  ros::Duration(1.0).sleep();\n\n  if(!hw.initialize() || !hw.motor_enable()) {\n    ROS_ERROR(\"Failed to initialize hardware.\");\n    return 0;\n  }\n  ROS_INFO(\"Hardware Initialized.\");\n  ROS_INFO(\"--- Beginning Test ---\");\n\n  std::chrono::steady_clock::time_point time_start = std::chrono::steady_clock::now();\n  std::chrono::steady_clock::time_point time_now   = time_start;\n  std::chrono::steady_clock::time_point time_loop  = time_start;\n\n  // ***************************************** //\n  // ****        MAIN TEST LOOP           **** //\n  // ***************************************** //\n  while(ros::ok() && t < kRunTime_s) {\n    /// Calculate end-time of cycle\n    using namespace std::chrono;\n    time_loop += microseconds(kUpdateCycleTime_us);\n\n    // Feedback Loop\n    double target = get_target(t);\n    cntrl->set_target(target);\n    u   = cntrl->update(x);\n\n    if(u > kMaxForce_N) {\n      ROS_WARN(\"Command Input MAX Saturation\");\n      u = kMaxForce_N;\n    } else if(u < -kMaxForce_N) {\n      ROS_WARN(\"Command Input MIN Saturation\");\n      u = -kMaxForce_N;\n    }\n\n    pos = hw.update(u);\n    x   = pos.position_x;\n\n    // Publish\n    int dt   = duration_cast<microseconds>(time_now - time_start).count();\n    t = static_cast<double>(dt)/1000000.0;\n    publish(log_pub, state_pub, data, state, target, x, u, t);\n\n    //   Wait until end of cycle time\n    std::this_thread::sleep_until(time_loop);\n    time_now  = steady_clock::now();\n  }\n\n  ROS_INFO(\"--- End of Test Loop ---\");\n  util::stop_logging(nh, log_table);\n  util::remove_image(nh, state_topic);\n\n  return 0;\n}\n\nros::Publisher initialize_logging(ros::NodeHandle &nh, const std::string &log_table_name)\n{\n  std::string logging_topic = \"base_model\";\n  ros::Publisher log_pub = nh.advertise<pendulum::LoggingData>(\"/\" + logging_topic, 50);\n\n  std::vector<std::string> header({\n    \"test\", \"test_time\", \"target\", \"input\", \"x\"\n  });\n\n  if(!util::drop_logging_table(nh, log_table_name) ||\n     !util::start_logging(nh, log_table_name, logging_topic, header)) {\n    ROS_WARN(\"Failed to start logging.\");\n  }\n\n  return log_pub;\n}\n\nvoid publish(ros::Publisher &log_pub, ros::Publisher &state_pub,\n  pendulum::LoggingData &data, pendulum::State &state,\n  const double target, const double x, const double u, const double t)\n{\n  auto timestamp = ros::Time::now();\n\n  state.header.seq += 1;\n  state.header.stamp = timestamp;\n  state.x = x;\n  state_pub.publish(state);\n\n  data.header.seq += 1;\n  data.header.stamp = timestamp;\n  data.data[0] = t;\n  data.data[1] = target;\n  data.data[2] = u;\n  data.data[3] = x;\n  log_pub.publish(data);\n\n  ros::spinOnce();\n}\n\ndouble get_target(const double test_time)\n{\n  double target = 0.0;\n  if(test_time < 0.5)\n    target = 0.0;\n  else if (test_time < 5.5)\n    target = 0.3;\n  else\n    target = 0.0;\n\n  return target;\n}\n\nbool parse_args(int argc, char *argv[])\n{\n  boost::program_options::options_description desc(\"Options\");\n  try {\n    desc.add_options()\n      (\"help\", \"produce help message\")\n      (\"Kp\", boost::program_options::value<double>(), \"Proportional Gain\")\n      (\"Kd\", boost::program_options::value<double>(), \"Derivative Gain\")\n      (\"Ki\", boost::program_options::value<double>(), \"Integral Gain\");\n\n      boost::program_options::variables_map var_map;\n      boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).run(), var_map);\n\n      if (var_map.count(\"help\")) {\n        std::cout << desc << std::endl;\n        return false;\n      }\n\n      if (var_map.count(\"Kp\"))\n        Kp = var_map[\"Kp\"].as<double>();\n      if (var_map.count(\"Kd\"))\n        Kd = var_map[\"Kd\"].as<double>();\n      if (var_map.count(\"Ki\"))\n        Ki = var_map[\"Ki\"].as<double>();\n\n    } catch(const std::invalid_argument& ia) {\n      ROS_WARN(\"Invalid String as Integer. Program will exit\");\n      return false;\n    } catch(...) {\n      ROS_WARN(\"Invalid Option. Program will exit\");\n      return false;\n    }\n\n    return true;\n}\n", "meta": {"hexsha": "fb6633b234de10027b05ce9fe169d4eaa7cf0eef", "size": 7616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/hardware/control_base.cpp", "max_stars_repo_name": "pdsherman/pendulum", "max_stars_repo_head_hexsha": "ed3e708e8cd66c1a7d5282110b4ceb94492c460f", "max_stars_repo_licenses": ["MIT"], "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/hardware/control_base.cpp", "max_issues_repo_name": "pdsherman/pendulum", "max_issues_repo_head_hexsha": "ed3e708e8cd66c1a7d5282110b4ceb94492c460f", "max_issues_repo_licenses": ["MIT"], "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/hardware/control_base.cpp", "max_forks_repo_name": "pdsherman/pendulum", "max_forks_repo_head_hexsha": "ed3e708e8cd66c1a7d5282110b4ceb94492c460f", "max_forks_repo_licenses": ["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.4054054054, "max_line_length": 122, "alphanum_fraction": 0.6292016807, "num_tokens": 2099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5260272223746246}}
{"text": "//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include <boost/test/unit_test.hpp>\n#include \"ParserFlatbuffersSerializeFixture.hpp\"\n#include \"../Deserializer.hpp\"\n\n#include <string>\n#include <iostream>\n\nBOOST_AUTO_TEST_SUITE(DeserializeParser)\n\nstruct FullyConnectedFixture : public ParserFlatbuffersSerializeFixture\n{\n    explicit FullyConnectedFixture(const std::string & inputShape1,\n                                   const std::string & outputShape,\n                                   const std::string & weightsShape,\n                                   const std::string & dataType)\n    {\n        m_JsonString = R\"(\n        {\n            inputIds: [0],\n            outputIds: [2],\n            layers: [{\n                layer_type: \"InputLayer\",\n                layer: {\n                    base: {\n                        layerBindingId: 0,\n                        base: {\n                            index: 0,\n                            layerName: \"InputLayer\",\n                            layerType: \"Input\",\n                            inputSlots: [{\n                                index: 0,\n                                connection: {sourceLayerIndex:0, outputSlotIndex:0 },\n                                }],\n                            outputSlots: [{\n                                index: 0,\n                                tensorInfo: {\n                                    dimensions: )\" + inputShape1 + R\"(,\n                                    dataType: )\" + dataType + R\"(,\n                                    quantizationScale: 1.0,\n                                    quantizationOffset: 0\n                                    },\n                                }]\n                            },\n                        }\n                    },\n                },\n            {\n            layer_type: \"FullyConnectedLayer\",\n            layer : {\n                base: {\n                    index:1,\n                    layerName: \"FullyConnectedLayer\",\n                    layerType: \"FullyConnected\",\n                    inputSlots: [{\n                            index: 0,\n                            connection: {sourceLayerIndex:0, outputSlotIndex:0 },\n                        }],\n                    outputSlots: [{\n                        index: 0,\n                        tensorInfo: {\n                            dimensions: )\" + outputShape + R\"(,\n                            dataType: )\" + dataType + R\"(,\n                            quantizationScale: 2.0,\n                            quantizationOffset: 0\n                        },\n                        }],\n                    },\n                descriptor: {\n                    biasEnabled: false,\n                    transposeWeightsMatrix: true\n                    },\n                weights: {\n                    info: {\n                             dimensions: )\" + weightsShape + R\"(,\n                             dataType: )\" + dataType + R\"(,\n                             quantizationScale: 1.0,\n                             quantizationOffset: 0\n                         },\n                    data_type: ByteData,\n                    data: {\n                        data: [\n                            2, 3, 4, 5\n                            ],\n                        }\n                    }\n                },\n            },\n            {\n            layer_type: \"OutputLayer\",\n            layer: {\n                base:{\n                    layerBindingId: 0,\n                    base: {\n                        index: 2,\n                        layerName: \"OutputLayer\",\n                        layerType: \"Output\",\n                        inputSlots: [{\n                            index: 0,\n                            connection: {sourceLayerIndex:1, outputSlotIndex:0 },\n                        }],\n                        outputSlots: [ {\n                            index: 0,\n                            tensorInfo: {\n                                dimensions: )\" + outputShape + R\"(,\n                                dataType: )\" + dataType + R\"(\n                            },\n                        }],\n                    }\n                }},\n            }]\n        }\n        )\";\n        Setup();\n    }\n};\n\nstruct FullyConnectedWithNoBiasFixture : FullyConnectedFixture\n{\n    FullyConnectedWithNoBiasFixture()\n        : FullyConnectedFixture(\"[ 1, 4, 1, 1 ]\",     // inputShape\n                                \"[ 1, 1 ]\",           // outputShape\n                                \"[ 1, 4 ]\",           // filterShape\n                                \"QuantisedAsymm8\")     // filterData\n    {}\n};\n\nBOOST_FIXTURE_TEST_CASE(FullyConnectedWithNoBias, FullyConnectedWithNoBiasFixture)\n{\n    RunTest<2, armnn::DataType::QAsymmU8>(\n         0,\n         {{\"InputLayer\",  { 10, 20, 30, 40 }}},\n         {{\"OutputLayer\", { 400/2 }}});\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "90698cb993f1dba8123dda5610765236b363454c", "size": 4915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/armnnDeserializer/test/DeserializeFullyConnected.cpp", "max_stars_repo_name": "Project-Xtended/external_armnn", "max_stars_repo_head_hexsha": "c5e1bbf9fc8ecbb8c9eb073a1550d4c8c15fce94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-09T15:14:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T01:37:53.000Z", "max_issues_repo_path": "src/armnnDeserializer/test/DeserializeFullyConnected.cpp", "max_issues_repo_name": "Project-Xtended/external_armnn", "max_issues_repo_head_hexsha": "c5e1bbf9fc8ecbb8c9eb073a1550d4c8c15fce94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/armnnDeserializer/test/DeserializeFullyConnected.cpp", "max_forks_repo_name": "Project-Xtended/external_armnn", "max_forks_repo_head_hexsha": "c5e1bbf9fc8ecbb8c9eb073a1550d4c8c15fce94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-23T11:34:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T15:51:37.000Z", "avg_line_length": 34.8581560284, "max_line_length": 85, "alphanum_fraction": 0.3436419125, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5260272223746246}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n\n#include <boost/numeric/mtl/mtl.hpp>\n\n\n\nusing std::cout; \n\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC>\nvoid test(MatrixA&, MatrixB&, MatrixC&, const char* name)\n{\n    double aa[][3]= {{0., 2., 0.}, {0., 0., 1.}, {1., 0., 0.}},\n\t   ba[][3]= {{0., 3., 0.}, {4., 0., 0.}, {1., 0., 0.}};\n\n    MatrixA A(aa); \n    MatrixB B(ba); \n    MatrixC C;\n\n    cout << \"\\n\\n\" << name << \"\\n\";\n    cout << \"Original matrices:\\nA=\\n\" << A << \"B=\\n\" << B << \"\\n\";\n\n    C= ele_prod(A, B);\n    cout << \"C= ele_prod(A, B)\\n\" << C << \"\\n\";\n    MTL_THROW_IF(C[0][1] != 6.0, mtl::runtime_error(\"C[0][1] should be 6.0\"));\n    MTL_THROW_IF(C[1][0] != 0.0, mtl::runtime_error(\"C[1][0] should be 0.0\"));\n\n\n    C= A + ele_prod(A, B);\n    cout << \"C= A + ele_prod(A, B)\\n\" << C << \"\\n\";\n    MTL_THROW_IF(C[0][1] != 8.0, mtl::runtime_error(\"C[0][1] should be 6.0\"));\n    MTL_THROW_IF(C[1][2] != 1.0, mtl::runtime_error(\"C[1][2] should be 1.0\"));\n\n\n    C= ele_prod(ele_prod(A, B), A);\n    cout << \"C= ele_prod(ele_prod(A, B), A)\\n\" << C << \"\\n\";\n    MTL_THROW_IF(C[0][1] != 12.0, mtl::runtime_error(\"C[0][1] should be 12.0\"));\n    MTL_THROW_IF(C[1][0] != 0.0, mtl::runtime_error(\"C[1][0] should be 0.0\"));\n\n\n    C= ele_prod(A, ele_prod(A, B));    \n    cout << \"C= ele_prod(ele_prod(A, B), A)\\n\" << C << \"\\n\";\n    MTL_THROW_IF(C[0][1] != 12.0, mtl::runtime_error(\"C[0][1] should be 12.0\"));\n    MTL_THROW_IF(C[1][0] != 0.0, mtl::runtime_error(\"C[1][0] should be 0.0\"));\n\n\n    C-= ele_prod(A, B);\n    cout << \"C-= ele_prod(A, B)\\n\" << C << \"\\n\";\n    MTL_THROW_IF(C[0][1] != 6.0, mtl::runtime_error(\"C[0][1] should be 6.0\"));\n    MTL_THROW_IF(C[1][0] != 0.0, mtl::runtime_error(\"C[1][0] should be 0.0\"));\n\n    C+= ele_prod(A, B);\n    cout << \"C+= ele_prod(A, B)\\n\" << C << \"\\n\";\n    MTL_THROW_IF(C[0][1] != 12.0, mtl::runtime_error(\"C[0][1] should be 12.0\"));\n    MTL_THROW_IF(C[1][0] != 0.0, mtl::runtime_error(\"C[1][0] should be 0.0\"));\n\n}\n\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    dense2D<double>                                      dr(3, 3);\n    dense2D<double, mat::parameters<col_major> >      dc(3, 3);\n    morton_dense<double, recursion::morton_z_mask>       mzd(3, 3);\n    morton_dense<double, recursion::doppled_2_row_mask>  d2r(3, 3);\n    compressed2D<double>                                 cr(3, 3);\n    compressed2D<double, mat::parameters<col_major> > cc(3, 3);\n\n\n    test(dr, dr, dr, \"Dense row major\");\n    test(dc, dr, dr, \"Dense column major as sum of dense rows\");\n    test(dc, dr, dc, \"Dense column major as sum of dense rows and column\");\n\n    test(mzd, mzd, mzd, \"Morton Z-order\");\n    test(d2r, mzd, d2r, \"Hybrid 2 row-major + Morton Z-order\");\n\n    test(cr, cr, cr, \"Compressed row major\");\n    test(cc, cr, cc, \"Compressed column major + row\");\n\n    return 0;\n}\n", "meta": {"hexsha": "14ec1c5cdc5e534c3fe6b8962c7d83e1293ffd29", "size": 3254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/matrix_ele_prod_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_ele_prod_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_ele_prod_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.5463917526, "max_line_length": 94, "alphanum_fraction": 0.561462815, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5260272210522853}}
{"text": "#pragma once\n\n#ifndef _MATRIX_H_\n#define _MATRIX_H_\n\n// Includes\n#include <Eigen/Dense>\n#include <viennacl/matrix.hpp>\n#include \"AbstractLinearAlgebraObject.hpp\"\n\nnamespace LightBulb\n{\n\t/**\n\t * \\brief Describes a two dimensional linear algebra data structure, also called matrix.\n\t * \\note Red or blue?\n\t * \\tparam DataType The data type which should be stored in the data structure.\n\t */\n\ttemplate<typename DataType = float>\n\tclass Matrix : public AbstractLinearAlgebraObject<Eigen::Matrix<DataType, -1, -1>, viennacl::matrix<DataType>>\n\t{\n\tprotected:\n\t\t// Inherited:\n\t\tvoid copyToEigen() const override\n\t\t{\n\t\t\tif (this->eigenValue.rows() != this->viennaclValue.size1() || this->eigenValue.cols() != this->viennaclValue.size2())\n\t\t\t\tthis->eigenValue.resize(this->viennaclValue.size1(), this->viennaclValue.size2());\n\n\t\t\tviennacl::copy(this->viennaclValue, this->eigenValue);\n\t\t}\n\t\tvoid copyToViennaCl() const override\n\t\t{\n\t\t\tif (this->eigenValue.rows() != this->viennaclValue.size1() || this->eigenValue.cols() != this->viennaclValue.size2())\n\t\t\t\tthis->viennaclValue.resize(this->eigenValue.rows(), this->eigenValue.cols());\n\n\t\t\tif (this->eigenValue.size() != 0)\n\t\t\t\tviennacl::copy(this->eigenValue, this->viennaclValue);\n\t\t}\n\tpublic:\n\t\t/**\n\t\t * \\brief Creates a new matrix with a specific size.\n\t\t * \\param rows The amount of rows.\n\t\t * \\param cols The amount of cols.\n\t\t */\n\t\tMatrix(int rows = 0, int cols = 0)\n\t\t{\n\t\t\tif (rows > 0 && cols > 0) {\n\t\t\t\tthis->eigenValue = Eigen::Matrix<DataType, -1, -1>(rows, cols);\n\t\t\t\tthis->eigenValueIsDirty = true;\n\t\t\t}\n\t\t}\n\t\tMatrix(const Eigen::Matrix<DataType, -1, -1>& eigenMatrix)\n\t\t{\n\t\t\tthis->eigenValue = eigenMatrix;\n\t\t\tthis->eigenValueIsDirty = true;\n\t\t}\n\t\tMatrix(const Matrix& other)\n\t\t\t: AbstractLinearAlgebraObject<Eigen::Matrix<DataType, -1, -1>, viennacl::matrix<DataType>>()\n\t\t{\n\t\t\tif (!((other.eigenValueIsDirty && other.eigenValue.size() == 0) || (other.viennaclValueIsDirty && other.viennaclValue.size1() == 0 && other.viennaclValue.size2() == 0) || (other.eigenValue.size() == 0 && other.viennaclValue.size1() == 0 && other.viennaclValue.size2() == 0)))\n\t\t\t\tthis->copyAllFrom(other);\n\t\t}\n\t};\n\n}\n\n\n#include \"LightBulb/IO/MatrixIO.hpp\"\n\n#endif", "meta": {"hexsha": "39f5d5fc9acb412f80e3216ec9fd18f76e589adf", "size": 2197, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/LightBulb/LinearAlgebra/Matrix.hpp", "max_stars_repo_name": "domin1101/ANNHelper", "max_stars_repo_head_hexsha": "50acb5746d6dad6777532e4c7da4983a7683efe0", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-02-04T06:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-06T02:21:43.000Z", "max_issues_repo_path": "include/LightBulb/LinearAlgebra/Matrix.hpp", "max_issues_repo_name": "domin1101/ANNHelper", "max_issues_repo_head_hexsha": "50acb5746d6dad6777532e4c7da4983a7683efe0", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-04-15T21:05:45.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-09T12:59:02.000Z", "max_forks_repo_path": "include/LightBulb/LinearAlgebra/Matrix.hpp", "max_forks_repo_name": "domin1101/LightBulb", "max_forks_repo_head_hexsha": "50acb5746d6dad6777532e4c7da4983a7683efe0", "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": 31.8405797101, "max_line_length": 278, "alphanum_fraction": 0.6818388712, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5260272210522852}}
{"text": "// Copyright (C) 2016 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 \"gtest/gtest.h\"\n#include <Eigen/Core>\n#include <Eigen/LU>\n\n#include \"theia/math/qp_solver.h\"\n#include \"theia/util/random.h\"\n\nnamespace theia {\n\n// A rigged QP minimization problem with a known output.\n//\n// 1/2 * x' * P * x + q' * x + r\n//     [  5  -2  -1 ]\n// P = [ -2   4   3 ]\n//     [ -1   3   5 ]\n//\n// q = [ 2  -35  -47 ]^t\n// r = 5\n//\n// Minimizing this unbounded problem should result in:\n//   x = [ 3  5  7 ]^t\nTEST(QPSolver, Unbounded) {\n  static const double kTolerance = 1e-4;\n\n  Eigen::MatrixXd P(3, 3);\n  P << 5, -2, -1, -2, 4, 3, -1, 3, 5;\n  Eigen::VectorXd q(3);\n  q << 2, -35, -47;\n  const double r = 5;\n\n  QPSolver::Options options;\n  options.max_num_iterations = 100;\n  Eigen::SparseMatrix<double> P_sparse(P.sparseView());\n  QPSolver qp_solver(options, P_sparse, q, r);\n  Eigen::VectorXd solution;\n  ASSERT_TRUE(qp_solver.Solve(&solution));\n\n  // Verify the solution is near (3, 5, 7).\n  const Eigen::Vector3d gt_solution(3, 5, 7);\n  for (int i = 0; i < 3; i++) {\n    EXPECT_NEAR(solution(i), gt_solution(i), kTolerance);\n  }\n\n  // Check that the residual is near optimal.\n  const double residual =\n      0.5 * solution.dot(P * solution) + solution.dot(q) + r;\n  const double gt_residual =\n      0.5 * gt_solution.dot(P * gt_solution) + gt_solution.dot(q) + r;\n  EXPECT_NEAR(residual, gt_residual, kTolerance);\n}\n\nTEST(QPSolver, LooseBounds) {\n  static const double kTolerance = 1e-4;\n\n  Eigen::MatrixXd P(3, 3);\n  P << 5, -2, -1, -2, 4, 3, -1, 3, 5;\n  Eigen::VectorXd q(3);\n  q << 2, -35, -47;\n  const double r = 5;\n\n  QPSolver::Options options;\n  options.max_num_iterations = 100;\n  Eigen::SparseMatrix<double> P_sparse(P.sparseView());\n  QPSolver qp_solver(options, P_sparse, q, r);\n\n  // Set a lower bound that should not affect the output.\n  Eigen::VectorXd lower_bound(3);\n  lower_bound << 0, 0, 0;\n  qp_solver.SetLowerBound(lower_bound);\n\n  // Set an upper bound that should not affect the output.\n  Eigen::VectorXd upper_bound(3);\n  upper_bound << 10, 10, 10;\n  qp_solver.SetUpperBound(upper_bound);\n  Eigen::VectorXd solution;\n\n  ASSERT_TRUE(qp_solver.Solve(&solution));\n\n  // Verify the solution is near (3, 5, 7).\n  const Eigen::Vector3d gt_solution(3, 5, 7);\n  for (int i = 0; i < 3; i++) {\n    EXPECT_NEAR(solution(i), gt_solution(i), kTolerance);\n  }\n\n  // Check that the residual is near optimal.\n  const double residual =\n      0.5 * solution.dot(P * solution) + solution.dot(q) + r;\n  const double gt_residual =\n      0.5 * gt_solution.dot(P * gt_solution) + gt_solution.dot(q) + r;\n  EXPECT_NEAR(residual, gt_residual, kTolerance);\n}\n\nTEST(QPSolver, TightBounds) {\n  static const double kTolerance = 1e-4;\n\n  Eigen::MatrixXd P(3, 3);\n  P << 5, -2, -1, -2, 4, 3, -1, 3, 5;\n  Eigen::VectorXd q(3);\n  q << 2, -35, -47;\n  const double r = 5;\n\n  QPSolver::Options options;\n  options.absolute_tolerance = 1e-8;\n  options.relative_tolerance = 1e-8;\n  Eigen::SparseMatrix<double> P_sparse(P.sparseView());\n  QPSolver qp_solver(options, P_sparse, q, r);\n\n  // Set a lower bound that constrains the output.\n  Eigen::VectorXd lower_bound(3);\n  lower_bound << 5, 7, 9;\n  qp_solver.SetLowerBound(lower_bound);\n\n  // Set an upper bound that constrains the output.\n  Eigen::VectorXd upper_bound(3);\n  upper_bound << 10, 12, 14;\n  qp_solver.SetUpperBound(upper_bound);\n\n  Eigen::VectorXd solution;\n  ASSERT_TRUE(qp_solver.Solve(&solution));\n\n  // Verify the solution is near (5, 7, 9).\n  const Eigen::Vector3d gt_solution(5, 7, 9);\n  for (int i = 0; i < 3; i++) {\n    EXPECT_NEAR(solution(i), gt_solution(i), kTolerance);\n  }\n\n  // Check that the residual is near optimal.\n  const double residual =\n      0.5 * solution.dot(P * solution) + solution.dot(q) + r;\n  const double gt_residual =\n      0.5 * gt_solution.dot(P * gt_solution) + gt_solution.dot(q) + r;\n  EXPECT_NEAR(residual, gt_residual, kTolerance);\n}\n\nTEST(QPSolver, InvalidBounds) {\n  Eigen::MatrixXd P(3, 3);\n  P << 5, -2, -1, -2, 4, 3, -1, 3, 5;\n  Eigen::VectorXd q(3);\n  q << 2, -35, -47;\n  const double r = 5;\n\n  QPSolver::Options options;\n  Eigen::SparseMatrix<double> P_sparse(P.sparseView());\n  QPSolver qp_solver(options, P_sparse, q, r);\n\n  // Set the upper bound as the lower bound.\n  Eigen::VectorXd lower_bound(3);\n  lower_bound << 5, 7, 9;\n  qp_solver.SetUpperBound(lower_bound);\n\n  // Set the lower bound as the upper bound, making the valid solution space\n  // non-existant.\n  Eigen::VectorXd upper_bound(3);\n  upper_bound << 10, 12, 14;\n  qp_solver.SetLowerBound(upper_bound);\n\n  Eigen::VectorXd solution;\n  EXPECT_FALSE(qp_solver.Solve(&solution));\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "5feb1016f9fb6afb8400b7a50b5e1f70d9c8bd55", "size": 6385, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/math/qp_solver_test.cc", "max_stars_repo_name": "urbste/TheiaSfM", "max_stars_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T03:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T08:08:45.000Z", "max_issues_repo_path": "src/theia/math/qp_solver_test.cc", "max_issues_repo_name": "urbste/TheiaSfM", "max_issues_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/math/qp_solver_test.cc", "max_forks_repo_name": "urbste/TheiaSfM", "max_forks_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-20T03:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T08:08:52.000Z", "avg_line_length": 32.5765306122, "max_line_length": 78, "alphanum_fraction": 0.6815974941, "num_tokens": 1847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5260272144846427}}
{"text": "#include <iostream>\n\n\n#include <numbers>\n#include <Eigen/Geometry>\n\n#include \"functional_mesh.h\"\n\n\n///////////////////////////////////////////////////////////////\n//                    CFunctionalMesh\n///////////////////////////////////////////////////////////////\n\nCFunctionalMesh::CFunctionalMesh()\n{\n    SetColorFunctor(nullptr);\n}\n\nvoid CFunctionalMesh::m_InvalidateAll()const\n{\n    m_valid_points=m_valid_normals=m_valid_colors=false;\n    m_levels_valid[0]=m_levels_valid[1]=m_levels_valid[2]=false;\n}\n\nvoid CFunctionalMesh::m_SetBoundedBox()const\n{\n    using eig_size_t=decltype(m_points.rows());\n    m_bounded_box.first=m_bounded_box.second=m_points(0,0);\n    for(eig_size_t i_s=0;i_s<m_points.rows();++i_s)\n    {\n        for(eig_size_t i_t=0;i_t<m_points.cols();++i_t)\n        {\n            for(size_t dim=0;dim<3;dim++)\n            {\n                const point_t& current=m_points(i_s,i_t);\n                m_bounded_box.first[dim]=std::min(current[dim],m_bounded_box.first[dim]);\n                m_bounded_box.second[dim]=std::max(current[dim],m_bounded_box.second[dim]);\n            }\n        }\n    }\n}\n\n// normal to parametrically defined surface\n// defined as || (dr / ds) x (dr / dt) ||\n// derivatives are approximated by finite differences\n\nvoid CFunctionalMesh::m_FillNormals()const\n{\n    using eig_size_t=decltype(m_points.rows());\n    float s_delta=m_grid.s_delta();\n    auto get_s_tangent=[this,&s_delta](size_t i,size_t j)->point_t\n    {\n        return (m_points(i+1,j)-m_points(i-1,j))/(2*s_delta);\n    };\n    auto get_s_top_bound=[&](size_t j)->point_t\n    {\n        return (m_points(1,j)-m_points(0,j))/(s_delta);\n    };\n    auto get_s_down_bound=[&](size_t j)->point_t\n    {\n        return (m_points(m_points.rows()-1,j)-m_points(m_points.rows()-2,j))/(s_delta);\n    };\n\n    float t_delta=m_grid.t_delta();\n    auto get_t_tangent=[this,&t_delta](size_t i,size_t j)->point_t\n    {\n        return (m_points(i,j+1)-m_points(i,j-1) )/(2*t_delta);\n    };\n    auto get_t_left_bound=[&](size_t i)->point_t\n    {\n        return (m_points(i,1)-m_points(i,0))/(t_delta);\n    };\n    auto get_t_right_bound=[&](size_t i)->point_t\n    {\n        return (m_points(i,m_points.cols()-1)-m_points(i,m_points.cols()-2))/(t_delta);\n    };\n\n    m_normals.resize(m_points.rows(),m_points.cols());\n\n    // internal domain\n    for(eig_size_t i=1;i<m_normals.rows()-1;++i)\n      for(eig_size_t j=1;j<m_normals.cols()-1;++j)\n      {\n          m_normals(i,j)=get_s_tangent(i,j).cross(get_t_tangent(i,j));\n          m_normals(i,j).normalize();\n      }\n    // left bound\n    for(eig_size_t i=1;i<m_normals.rows()-1;++i)\n    {\n        m_normals(i,0)=get_s_tangent(i,0).cross(get_t_left_bound(i));\n        m_normals(i,0).normalize();\n    }\n    // right bound\n    for(eig_size_t i=1;i<m_normals.rows()-1;++i)\n    {\n        m_normals(i,m_normals.cols()-1)=get_s_tangent(i,0).cross(get_t_right_bound(i));\n        m_normals(i,m_normals.cols()-1).normalize();\n    }\n\n    // top bound\n    for(eig_size_t i=1;i<m_normals.cols()-1;++i)\n    {\n        m_normals(0,i)=get_s_top_bound(i).cross(get_t_tangent(0,i));\n        m_normals(0,i).normalize();\n    }\n    // down bound\n    for(eig_size_t i=1;i<m_normals.cols()-1;++i)\n    {\n        m_normals(m_normals.rows()-1,i)=get_s_down_bound(i).cross(get_t_tangent(m_normals.rows()-1,i));\n        m_normals(m_normals.rows()-1,i).normalize();\n    }\n    // corners\n    m_normals(0,0)=get_s_top_bound(0).cross(get_t_left_bound(0));\n    m_normals(0,0).normalize();\n\n    m_normals(0,m_normals.cols()-1)=get_s_top_bound(m_normals.cols()-1).cross(get_t_right_bound(0));\n    m_normals(0,m_normals.cols()-1).normalize();\n\n    m_normals(m_normals.rows()-1,m_normals.cols()-1)=get_s_down_bound(m_normals.cols()-1).\n                                                     cross(get_t_right_bound(m_normals.rows()-1));\n    m_normals(m_normals.rows()-1,m_normals.cols()-1).normalize();\n\n    m_normals(m_normals.rows()-1,0)=get_s_down_bound(0).cross(get_t_left_bound(m_normals.rows()-1));\n    m_normals(m_normals.rows()-1,0).normalize();\n}\n\nvoid CFunctionalMesh::m_SetLevelLines(int index,float time)const\n{\n    assert(index==0||index==1||index==2);\n    assert(m_valid_points);\n    m_levels[index].clear();\n    auto cell_pocess=[index,time,this](float level,int i,int j,int& lines)\n    ->std::array<point_t,4>\n    {\n        auto is_same_sign=[](float _1,float _2){ return (_1>=0) == (_2>=0);};\n        std::array<float,4> diffs;\n        std::array<point_t,4> cell={m_points(i+1,j),m_points(i+1,j+1),m_points(i,j+1),m_points(i,j)};\n        std::array<int,4>   intersections;\n        int num_intersetions=0;\n        auto intersection_point=[&](int side)\n        {\n            int next=(1+side)%4;\n            return (cell[side]*diffs[next]-cell[next]*diffs[side])/(diffs[next]-diffs[side]);\n        };\n        diffs[0]=cell[0][index]-level;\n        for(int i=0;i<4;++i)\n        {\n            int next_index=(i+1)%4;\n            diffs[next_index]=cell[next_index][index]-level;\n            if(!is_same_sign(diffs[i],diffs[next_index])) intersections[num_intersetions++]=i;\n        }\n        lines=num_intersetions/2;\n        if(lines==0) return std::array<point_t,4>{};\n        else if(num_intersetions==2)\n        {\n            return std::array<point_t,4>{intersection_point(intersections[0]),\n                                         intersection_point(intersections[1]),\n                                         point_t{},point_t{}};\n        }\n        else if(num_intersetions==4)\n        {\n            float center_diff=m_points_functor(m_grid.s(i)+m_grid.s_delta()/2,\n                                               m_grid.t(j)+m_grid.t_delta()/2,\n                                               time)[index]-level;\n            if(is_same_sign(diffs[0],center_diff))\n            {\n                    return {\n                                intersection_point(intersections[0]),\n                                intersection_point(intersections[1]),\n                                intersection_point(intersections[2]),\n                                intersection_point(intersections[3])\n                            };\n            }\n            else\n            {\n                    return {\n                                intersection_point(intersections[1]),\n                                intersection_point(intersections[2]),\n                                intersection_point(intersections[3]),\n                                intersection_point(intersections[0])\n                            };\n            }\n        }\n        else assert(false);\n    };\n\n    float delta=(m_bounded_box.second[index]-m_bounded_box.first[index])/(1+m_num_levels[index]);\n\n    for(size_t k=0;k<m_num_levels[index];++k)\n    {\n        float level=delta*(k+1);\n        m_levels[index].push_back(level_line_t(level));\n        auto&current=m_levels[index].back();\n\n        for(size_t i=0;i<m_grid.s_resolution;++i)\n            for(size_t j=0;j<m_grid.t_resolution;++j)\n            {\n                int num_lines;\n                auto lines=cell_pocess(level+m_bounded_box.first[index],i,j,num_lines);\n                if(num_lines==0) continue;\n\n                if(num_lines==1) current.push_back(lines[0],lines[1]);\n                if(num_lines==2) current.push_back(lines[2],lines[3]);\n            }\n    }\n}\n\nCFunctionalMesh& CFunctionalMesh::SetUniformColor(const point_t&p)\n{\n    SetColorFunctor([p](float,float,float){return p;});\n    m_traits.SetColored(true);\n    m_valid_colors=false;\n    assert(m_traits.IsColored());\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetTraits(const CRenderingTraits&traits)\n{\n    m_traits=traits;\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetAmbientReflection(float val)\n{\n    m_material.ambient=val;\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetDiffuseReflection(float val)\n{\n    m_material.diffuse=val;\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetSpecularReflection(float val)\n{\n    m_material.specular=val;\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetShininess(float val)\n{\n    m_material.shininess=val;\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetGrid(grid_t grid)\n{\n    assert(!grid.empty());\n    if(m_grid!=grid) m_InvalidateAll();\n    m_grid=grid;\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetResolution(size_t s_resol,size_t t_resol)\n{\n    if(s_resol==m_grid.s_resolution&&t_resol==m_grid.t_resolution) return*this;\n    m_grid.s_resolution=s_resol;\n    m_grid.t_resolution=t_resol;\n    assert(!m_grid.empty());\n    m_InvalidateAll();\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetRange(std::pair<float,float> s_range,std::pair<float,float> t_range)\n{\n    if(s_range==m_grid.s_range&&t_range==m_grid.t_range) return *this;\n    m_grid.s_range=s_range;\n    m_grid.t_range=t_range;\n    m_InvalidateAll();\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetNumberOfLevelsX(uint32_t x)\n{\n    m_levels_valid[0]= x==m_num_levels[0];\n    m_num_levels[0]=x;\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetNumberOfLevelsY(uint32_t y)\n{\n    m_levels_valid[1]= y==m_num_levels[1];\n    m_num_levels[1]=y;\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetNumberOfLevelsZ(uint32_t z)\n{\n    m_levels_valid[2]= z==m_num_levels[2];\n    m_num_levels[2]=z;\n    return *this;\n}\n\n\nvoid CFunctionalMesh::Clear()\n{\n    m_points_functor=nullptr;\n    m_InvalidateAll();\n}\n\n\nCFunctionalMesh::CUpdateResult CFunctionalMesh::UpdateData(float time)\n{\n    int update=0;\n    if(Empty()) return CUpdateResult(0);\n    if(IsDynamic())\n    {\n       if(time!=m_last_update_time) m_InvalidateAll();\n    }\n    else\n    {\n        time=0.0f;\n    }\n\n    if(!m_valid_points)\n    {\n        //std::cout<<\"UPDATE POINTS\\n\";\n        if(m_grid.s_resolution+1!=m_points.rows()||m_grid.t_resolution+1!=m_points.cols())\n        {\n            m_points.resize(m_grid.s_resolution+1,m_grid.t_resolution+1);\n            update|=CUpdateResult::update_grid;\n        }\n        m_fill_functor(m_points,m_grid,time);\n        m_SetBoundedBox();\n        m_valid_points=true;\n        update|=CUpdateResult::update_points;\n    }\n    if(!m_valid_normals&&m_traits.IsSpecularSurface())\n    {\n        //std::cout<<\"UPDATE NORMALS\\n\";\n        m_normals.resize(m_grid.s_resolution+1,m_grid.t_resolution+1);\n        m_FillNormals();\n        m_valid_normals=true;\n        update|=CUpdateResult::update_normals;\n    }\n    if(!m_valid_colors&&m_traits.IsColored())\n    {\n        //std::cout<<\"UPDATE COLORS\\n\";\n        m_colors.resize(m_grid.s_resolution+1,m_grid.t_resolution+1);\n        m_colors_functor(m_points,m_colors);\n        m_valid_colors=true;\n        update|=CUpdateResult::update_colors;\n    }\n    for(int i=0;i<3;++i)\n    {\n        if(!m_levels_valid[i]&&m_traits.IsLevelLines(i))\n        {\n            //std::cout<<\"UPDATE LEVELS\\n\";\n            m_SetLevelLines(i,time);\n            m_levels_valid[i]=true;\n            update|=CUpdateResult::update_levels(i);\n        }\n    }\n    m_last_update_time=time;\n    if(m_update_callback)\n    {\n        m_update_callback(*this,CUpdateResult(update));\n    }\n    return CUpdateResult(update);\n}\n\n\nCFunctionalMesh::CUpdateResult CFunctionalMesh::UpdateData()\n{\n    return UpdateData(m_last_update_time);\n}\n\n// Get functions\n\nCFunctionalMesh::grid_t CFunctionalMesh::GetGrid()const\n{\n    return m_grid;\n}\n\nconst material_t&CFunctionalMesh::GetMaterial()const\n{\n    return m_material;\n}\n\nuint32_t CFunctionalMesh::GetNumberOfLevel(int i)const\n{\n    return m_num_levels[i];\n}\n\nconst CFunctionalMesh::matrix_t*CFunctionalMesh::Points()const\n{\n    return m_valid_points? &m_points:nullptr;\n}\n\nconst CFunctionalMesh::matrix_t*CFunctionalMesh::Colors()const\n{\n    return m_valid_colors? &m_colors:nullptr;\n}\n\nconst CFunctionalMesh::matrix_t*CFunctionalMesh::Normals()const\n{\n    return m_valid_normals? &m_normals:nullptr;\n}\n\nconst std::pair<CFunctionalMesh::point_t,CFunctionalMesh::point_t>* CFunctionalMesh::BoundedBox()const\n{\n    return m_valid_points? &m_bounded_box:nullptr;\n}\n\nconst std::vector<CFunctionalMesh::level_line_t>*  CFunctionalMesh::Levels(int i)const\n{\n    return m_levels_valid[i]? &m_levels[i]:nullptr;\n}\n\nbool CFunctionalMesh::Empty()const\n{\n    return m_points_functor==nullptr;\n}\n\nfloat CFunctionalMesh::LastUpdateTime()const\n{\n    return m_last_update_time;\n}\n\nCRenderingTraits&CFunctionalMesh::RenderingTraits()\n{\n    return m_traits;\n}\n\nconst CRenderingTraits&CFunctionalMesh::RenderingTraits()const\n{\n    return m_traits;\n}\n\n// Set specific surface\n\nCFunctionalMesh& CFunctionalMesh::SetSphere(float r,size_t teta_resol,size_t phi_resol)\n{\n    using namespace std::numbers;\n    SetMeshFunctor(plot::spherical([r](float,float){return r;}));\n    SetRange({0.00001,pi_v<float>-0.00001},{0.0f,2*pi_v<float>});\n    SetResolution(teta_resol,phi_resol);\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetTorus(float rad,float tubular,size_t rad_resol,size_t tubular_resol)\n{\n    using namespace std::numbers;\n    auto mesh_f=[rad,tubular](float teta,float phi)\n    {\n        float r=rad+tubular*std::cos(phi);\n        return point_t(r*std::cos(teta),r*std::sin(teta),tubular*std::sin(phi));\n    };\n    SetMeshFunctor(mesh_f);\n    SetRange({0.0f,2*pi_v<float>},{0.0f,2*pi_v<float>});\n    SetResolution(rad_resol,tubular_resol);\n    return *this;\n}\n\n\nCFunctionalMesh& CFunctionalMesh::SetCylinder(float rad,float h,size_t phi_resol)\n{\n    using namespace std::numbers;\n    auto mesh_f=[rad](float phi,float z)\n    {\n        return point_t(rad*std::cos(phi),rad*std::sin(phi),z);\n    };\n    SetMeshFunctor(mesh_f);\n    SetRange({0.0f,2*pi_v<float>},{0.0f,h});\n    SetResolution(phi_resol,1);\n    return *this;\n}\n\n\nCFunctionalMesh& CFunctionalMesh::SetCone(float bottom_rad,float h,size_t phi_resol)\n{\n    using namespace std::numbers;\n    auto mesh_f=[bottom_rad,h](float phi,float z)\n    {\n        float rad=bottom_rad*(1.0f-z/h);\n        return point_t(rad*std::cos(phi),rad*std::sin(phi),z);\n    };\n    SetMeshFunctor(mesh_f);\n    SetRange({0.0f,2*pi_v<float>},{0.0f,h});\n    SetResolution(phi_resol,1);\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetPlane(float dx,float dy,size_t x_resol,size_t y_resol)\n{\n    SetMeshFunctor([](float x,float y){return point_t(x,y,0);});\n    SetRange({-dx/2,dx/2},{-dy/2,dy/2});\n    SetResolution(x_resol,y_resol);\n    return *this;\n}\n\n\n// Transformations\n\nCFunctionalMesh& CFunctionalMesh::SetAnchor(const point_t&p)\n{\n    m_anchor=p;\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::DeltaOrg(float x,float y,float z)\n{\n    m_rigid.DeltaOrg(x,y,z);\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::DeltaOrg(const point_t&p)\n{\n    m_rigid.DeltaOrg(p);\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetOrg(float x,float y,float z)\n{\n    m_rigid.SetOrg(x,y,z);\n    return *this;\n}\n\nCFunctionalMesh& CFunctionalMesh::SetOrg(const point_t&p)\n{\n    m_rigid.SetOrg(p);\n    return *this;\n}\n\nCRigidTransform::point_t CFunctionalMesh::GetOrg()const\n{\n    return m_rigid.GetOrg();\n}\n\nconst CRigidTransform::matrix_t& CFunctionalMesh::GetTransform()const\n{\n    return m_rigid.GetTransform();\n}\n", "meta": {"hexsha": "d4acfc251a828fc716fce5bfe3f4b8b5254c66ff", "size": 15126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functional_mesh.cpp", "max_stars_repo_name": "RomanFesenko/SurfaceViewer", "max_stars_repo_head_hexsha": "e8f27946ae3bce125b4c6639d9315e4652f401e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functional_mesh.cpp", "max_issues_repo_name": "RomanFesenko/SurfaceViewer", "max_issues_repo_head_hexsha": "e8f27946ae3bce125b4c6639d9315e4652f401e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functional_mesh.cpp", "max_forks_repo_name": "RomanFesenko/SurfaceViewer", "max_forks_repo_head_hexsha": "e8f27946ae3bce125b4c6639d9315e4652f401e5", "max_forks_repo_licenses": ["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.2728971963, "max_line_length": 105, "alphanum_fraction": 0.631230993, "num_tokens": 3956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5260272144846427}}
{"text": "/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*/\n\n#include <mitkTestingMacros.h>\n#include <mitkTestFixture.h>\n#include \"mitkIOUtil.h\"\n#include \"itkArray2D.h\"\n\n#include <mitkLibSVMClassifier.h>\n#include <itkLabelSampler.h>\n#include <mitkImageCast.h>\n#include <mitkStandaloneDataStorage.h>\n#include <itkCSVArray2DFileReader.h>\n#include <itkCSVArray2DDataObject.h>\n#include <itkCSVNumericObjectFileWriter.h>\n\n//#include <boost/algorithm/string.hpp>\n\nclass mitkLibSVMClassifierTestSuite : public mitk::TestFixture\n{\n  CPPUNIT_TEST_SUITE(mitkLibSVMClassifierTestSuite);\n  MITK_TEST(TrainSVMClassifier_MatlabDataSet_shouldReturnTrue);\n  MITK_TEST(TrainSVMClassifier_BreastCancerDataSet_shouldReturnTrue);\n  CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\n  typedef Eigen::Matrix<double ,Eigen::Dynamic,Eigen::Dynamic> MatrixDoubleType;\n  typedef Eigen::Matrix<int, Eigen::Dynamic,Eigen::Dynamic> MatrixIntType;\n\n  Eigen::MatrixXd m_TrainingMatrixX;\n  Eigen::MatrixXi m_TrainingLabelMatrixY;\n  Eigen::MatrixXd m_TestXPredict;\n  Eigen::MatrixXi m_TestYPredict;\n\n  mitk::LibSVMClassifier::Pointer classifier;\n\npublic:\n\n  /*Reading an file, which includes the trainingdataset and the testdataset, and convert the\n  content of the file into an 2dim matrixpair.\n  There are an delimiter, which separates the matrix into an trainingmatrix and testmatrix */\n  template<typename T>\n  std::pair<Eigen::Matrix<T ,Eigen::Dynamic,Eigen::Dynamic>,Eigen::Matrix<T ,Eigen::Dynamic,Eigen::Dynamic> >convertCSVToMatrix(const std::string &path, char delimiter,double range, bool isXMatrix)\n  {\n    typename itk::CSVArray2DFileReader<T>::Pointer fr = itk::CSVArray2DFileReader<T>::New();\n    fr->SetFileName(path);\n    fr->SetFieldDelimiterCharacter(delimiter);\n    fr->HasColumnHeadersOff();\n    fr->HasRowHeadersOff();\n    fr->Parse();\n    try{\n      fr->Update();\n    }catch(itk::ExceptionObject& ex){\n      cout << \"Exception caught!\" << std::endl;\n      cout << ex << std::endl;\n    }\n\n    typename itk::CSVArray2DDataObject<T>::Pointer p = fr->GetOutput();\n    unsigned int maxrowrange = p->GetMatrix().rows();\n    unsigned int c = p->GetMatrix().cols();\n    auto percentRange = (unsigned int)(maxrowrange*range);\n\n    if(isXMatrix == true)\n    {\n      Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> trainMatrixX(percentRange,c);\n      Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> testMatrixXPredict(maxrowrange-percentRange,c);\n\n      for(unsigned int row = 0; row < percentRange; row++){\n        for(unsigned int col = 0; col < c; col++){\n          trainMatrixX(row,col) =  p->GetData(row,col);\n        }\n      }\n\n      for(unsigned int row = percentRange; row < maxrowrange; row++){\n        for(unsigned int col = 0; col < c; col++){\n          testMatrixXPredict(row-percentRange,col) =  p->GetData(row,col);\n        }\n      }\n\n      return std::make_pair(trainMatrixX,testMatrixXPredict);\n    }\n    else\n    {\n      Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> trainLabelMatrixY(percentRange,c);\n      Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> testMatrixYPredict(maxrowrange-percentRange,c);\n\n      for(unsigned int row = 0; row < percentRange; row++){\n        for(unsigned int col = 0; col < c; col++){\n          trainLabelMatrixY(row,col) =  p->GetData(row,col);\n        }\n      }\n\n      for(unsigned int row = percentRange; row < maxrowrange; row++){\n        for(unsigned int col = 0; col < c; col++){\n          testMatrixYPredict(row-percentRange,col) =  p->GetData(row,col);\n        }\n      }\n\n      return std::make_pair(trainLabelMatrixY,testMatrixYPredict);\n    }\n  }\n\n  /*\n  Reading an csv-data and transfer the included datas into an matrix.\n  */\n  template<typename T>\n  Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> readCsvData(const std::string &path, char delimiter)\n  {\n    typename itk::CSVArray2DFileReader<T>::Pointer fr = itk::CSVArray2DFileReader<T>::New();\n    fr->SetFileName(path);\n    fr->SetFieldDelimiterCharacter(delimiter);\n    fr->HasColumnHeadersOff();\n    fr->HasRowHeadersOff();\n    fr->Parse();\n    try{\n      fr->Update();\n    }catch(itk::ExceptionObject& ex){\n      cout << \"Exception caught!\" << std::endl;\n      cout << ex << std::endl;\n    }\n\n    typename itk::CSVArray2DDataObject<T>::Pointer p = fr->GetOutput();\n    unsigned int maxrowrange = p->GetMatrix().rows();\n    unsigned int maxcols = p->GetMatrix().cols();\n    Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> matrix(maxrowrange,maxcols);\n\n    for(unsigned int rows = 0; rows < maxrowrange; rows++){\n      for(unsigned int cols = 0; cols < maxcols; cols++ ){\n        matrix(rows,cols) = p->GetData(rows,cols);\n      }\n    }\n\n    return matrix;\n  }\n\n  /*\n  Write the content of the array into an own csv-data in the following sequence:\n  root.csv:   1    2    3    0   0    4\n  writen.csv:     1  1:2  2:3  3:0 4:0  5:4\n  */\n  template<typename T>\n  void writeMatrixToCsv(Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> paramMatrix,const std::string &path)\n  {\n    std::ofstream outputstream (path,std::ofstream::out);   // 682\n\n    if(outputstream.is_open()){\n      for(int i = 0; i < paramMatrix.rows(); i++){\n        outputstream << paramMatrix(i,0);\n        for(int j = 1; j < 11; j++){\n          outputstream  << \" \" << j << \":\" << paramMatrix(i,j);\n        }\n        outputstream << endl;\n      }\n      outputstream.close();\n    }\n    else{\n      cout << \"Unable to write into CSV\" << endl;\n    }\n  }\n\n  /*\n  Train the classifier with an exampledataset of mattlab.\n  Note: The included data are gau\u00dfan normaldistributed.\n  */\n  void TrainSVMClassifier_MatlabDataSet_shouldReturnTrue()\n  {\n    /* Declarating an featurematrixdataset, the first matrix\n    of the matrixpair is the trainingmatrix and the second one is the testmatrix.*/\n    std::pair<MatrixDoubleType,MatrixDoubleType> matrixDouble;\n    matrixDouble = convertCSVToMatrix<double>(GetTestDataFilePath(\"Classification/FeaturematrixMatlab.csv\"),';',0.5,true);\n    m_TrainingMatrixX = matrixDouble.first;\n    m_TestXPredict = matrixDouble.second;\n\n    /* The declaration of the labelmatrixdataset is equivalent to the declaration\n    of the featurematrixdataset.*/\n    std::pair<MatrixIntType,MatrixIntType> matrixInt;\n    matrixInt = convertCSVToMatrix<int>(GetTestDataFilePath(\"Classification/LabelmatrixMatlab.csv\"),';',0.5,false);\n    m_TrainingLabelMatrixY = matrixInt.first;\n    m_TestYPredict = matrixInt.second;\n    classifier = mitk::LibSVMClassifier::New();\n\n    /* Setting of the SVM-Parameters*/\n    classifier->SetGamma(1/(double)(m_TrainingMatrixX.cols()));\n    classifier->SetSvmType(0);\n    classifier->SetKernelType(0);\n\n    /* Train the classifier, by giving trainingdataset for the labels and features.\n    The result in an colunmvector of the labels.*/\n    classifier->Train(m_TrainingMatrixX,m_TrainingLabelMatrixY);\n    Eigen::MatrixXi classes = classifier->Predict(m_TestXPredict);\n\n    /* Testing the matching between the calculated\n    colunmvector and the result of the SVM */\n    unsigned int maxrows = classes.rows();\n\n    int count = 0;\n\n    for (unsigned int i = 0; i < maxrows; i++)\n    {\n      if(classes(i, 0) == m_TestYPredict(i, 0))\n        ++count;\n    }\n\n    MITK_INFO << 100*count/(double)(maxrows) << \"%\";\n    MITK_TEST_CONDITION(isEqual<int>(m_TestYPredict,classes),\"Expected vector and occured vector match.\");\n  }\n\n  // Method of testing for assertions.\n  template<typename T>\n  bool isEqual(Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> expected, Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> actual)\n  {\n    bool isSimilar = true;\n    unsigned int mrow = expected.rows();\n    unsigned int mcol = expected.cols();\n    for(unsigned int i = 0; i < mrow; i++){\n      for(unsigned int j = 0; j < mcol; j++){\n        if(expected(i,j) != actual(i,j)){\n          isSimilar = false;\n        }\n      }\n    }\n    return isSimilar;\n  }\n\n  // Method of intervalltesting\n  template<typename T>\n  bool isIntervall(Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> expected, Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> actual, double lowrange, double toprange)\n  {\n    bool isInIntervall = false;\n    int count = 0;\n    unsigned int rowRange = expected.rows();\n    unsigned int colRange = expected.cols();\n    for(unsigned int i = 0; i < rowRange; i++){\n      for(unsigned int j = 0; j < colRange; j++){\n        if(expected(i,j) == actual(i,j)){\n          count++;\n        }\n      }\n\n      double valueOfMatch = 100*count/(double)(rowRange);\n      if((lowrange <= valueOfMatch) && (toprange >= valueOfMatch)){\n        isInIntervall = true;\n      }\n    }\n    return isInIntervall;\n  }\n\n  /*\n  Train the classifier with the dataset of breastcancer patients from the\n  LibSVM Libary\n  */\n  void TrainSVMClassifier_BreastCancerDataSet_shouldReturnTrue()\n  {\n    /* Declarating an featurematrixdataset, the first matrix\n    of the matrixpair is the trainingmatrix and the second one is the testmatrix.*/\n    std::pair<MatrixDoubleType,MatrixDoubleType> matrixDouble;\n    matrixDouble = convertCSVToMatrix<double>(GetTestDataFilePath(\"Classification/FeaturematrixBreastcancer.csv\"),';',0.5,true);\n    m_TrainingMatrixX = matrixDouble.first;\n    m_TestXPredict = matrixDouble.second;\n\n    /* The declaration of the labelmatrixdataset is equivalent to the declaration\n    of the featurematrixdataset.*/\n    std::pair<MatrixIntType,MatrixIntType> matrixInt;\n    matrixInt = convertCSVToMatrix<int>(GetTestDataFilePath(\"Classification/LabelmatrixBreastcancer.csv\"),';',0.5,false);\n    m_TrainingLabelMatrixY = matrixInt.first;\n    m_TestYPredict = matrixInt.second;\n\n    /* Setting of the SVM-Parameters*/\n    classifier = mitk::LibSVMClassifier::New();\n    classifier->SetGamma(1/(double)(m_TrainingMatrixX.cols()));\n    classifier->SetSvmType(0);\n    classifier->SetKernelType(2);\n\n    /* Train the classifier, by giving trainingdataset for the labels and features.\n    The result in an colunmvector of the labels.*/\n    classifier->Train(m_TrainingMatrixX,m_TrainingLabelMatrixY);\n    Eigen::MatrixXi classes = classifier->Predict(m_TestXPredict);\n\n    /* Testing the matching between the calculated colunmvector and the result\n    of the SVM */\n    unsigned int maxrows = classes.rows();\n\n    int count = 0;\n\n    for (unsigned int i = 0; i < maxrows; i++)\n    {\n      if (classes(i, 0) == m_TestYPredict(i, 0))\n        ++count;\n    }\n\n    MITK_INFO << 100*count/(double)(maxrows) << \"%\";\n    MITK_TEST_CONDITION(isIntervall<int>(m_TestYPredict,classes,75,100),\"Testvalue is in range.\");\n  }\n\n  void TestThreadedDecisionForest()\n  {\n  }\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkLibSVMClassifier)\n", "meta": {"hexsha": "25a7f021a92d118be1048ae714ff85f6b41f3344", "size": 10892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/Classification/CLLibSVM/test/mitkLibSVMClassifierTest.cpp", "max_stars_repo_name": "zhaomengxiao/MITK", "max_stars_repo_head_hexsha": "a09fd849a4328276806008bfa92487f83a9e2437", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-03T12:03:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T12:03:32.000Z", "max_issues_repo_path": "Modules/Classification/CLLibSVM/test/mitkLibSVMClassifierTest.cpp", "max_issues_repo_name": "zhaomengxiao/MITK", "max_issues_repo_head_hexsha": "a09fd849a4328276806008bfa92487f83a9e2437", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-22T10:19:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T10:19:02.000Z", "max_forks_repo_path": "Modules/Classification/CLLibSVM/test/mitkLibSVMClassifierTest.cpp", "max_forks_repo_name": "zhaomengxiao/MITK_lancet", "max_forks_repo_head_hexsha": "a09fd849a4328276806008bfa92487f83a9e2437", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-27T09:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-27T09:41:18.000Z", "avg_line_length": 35.0225080386, "max_line_length": 197, "alphanum_fraction": 0.6735218509, "num_tokens": 2808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5260272105616797}}
{"text": "/**\n * @ file transformedconslaw_main.cc\n * @ brief NPDE exam problem\n * @ author Oliver Rietmann\n * @ date 05.08.2021\n * @ copyright Developed at SAM, ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <utility>\n\n#include \"transformedconslaw.h\"\n\nconst static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n                                       Eigen::DontAlignCols, \", \", \"\\n\");\n\nint main() {\n  // Setup\n  TRFCL::NonStdCauchyProblemCL prb;\n  int M = 500;\n  int N = 500;\n\n  // Compute cell points and inital data for plot\n  std::pair<double, double> limits = prb.domain();\n  Eigen::VectorXd x =\n      Eigen::VectorXd::LinSpaced(N, limits.first, limits.second);\n  auto z0 = [&prb](double y) { return prb.z0(y); };\n  Eigen::VectorXd zeta0 = x.unaryExpr(z0);\n\n  // Print conserved quantity\n  auto rho = [&prb](double z) { return prb.rho(z); };\n  auto rec = [rho, limits](double t, const Eigen::VectorXd &zeta) -> void {\n    Eigen::VectorXd weighted_samples = zeta.unaryExpr(rho) / (zeta.size() - 1);\n    double rho_z_integral =\n        weighted_samples.sum() * (limits.second - limits.first);\n    std::cout << \"Integral of rho(z(x,t)) at time t = \" << t << \":\\t\"\n              << rho_z_integral << std::endl;\n  };\n\n  // Compute solution at final time\n  std::cout << std::fixed;\n  Eigen::VectorXd zetaT = solveCauchyPrb(M, N, prb, rec);\n\n  // Write x, zeta0 and zetaT to .csv file\n  std::ofstream solution_file;\n  solution_file.open(CURRENT_BINARY_DIR \"/solution.csv\");\n  solution_file << x.transpose().format(CSVFormat) << std::endl;\n  solution_file << zeta0.transpose().format(CSVFormat) << std::endl;\n  solution_file << zetaT.transpose().format(CSVFormat) << std::endl;\n  solution_file.close();\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/solution.csv\" << std::endl;\n\n  // Plot from .csv file using plot.py\n  std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot.py \" CURRENT_BINARY_DIR\n              \"/solution.csv \" CURRENT_BINARY_DIR \"/solution.eps\");\n\n  return 0;\n}\n", "meta": {"hexsha": "c3225f0c7385399941fc4bc53e7828704094d620", "size": 2025, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/TransformedConsLaw/templates/transformedconslaw_main.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T10:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T10:59:19.000Z", "max_issues_repo_path": "homeworks/TransformedConsLaw/templates/transformedconslaw_main.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/TransformedConsLaw/templates/transformedconslaw_main.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6612903226, "max_line_length": 79, "alphanum_fraction": 0.6513580247, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.5260272072778586}}
{"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#ifdef _MSC_VER\n#  define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#include \"test.hpp\"\n#include <boost/multiprecision/mpfi.hpp>\n#include <boost/multiprecision/random.hpp>\n\nusing namespace boost::multiprecision;\nusing namespace boost::random;\n\nvoid test_exp()\n{\n   std::cout << \"Testing exp\\n\";\n\n   mpfr_float_50 val = 1.25;\n\n   for(unsigned i = 0; i < 2000; ++i)\n   {\n      mpfr_float_100 a(val);\n      mpfr_float_100 b = exp(a);\n      mpfi_float_50 in = val;\n      in = exp(in);\n      BOOST_CHECK((boost::math::isfinite)(in));\n      BOOST_CHECK(lower(in) <= b);\n      BOOST_CHECK(upper(in) >= b);\n      b = log(a);\n      in = val;\n      in = log(in);\n      BOOST_CHECK((boost::math::isfinite)(in));\n      BOOST_CHECK(lower(in) <= b);\n      BOOST_CHECK(upper(in) >= b);\n      val *= 1.01;\n   }\n   val = 1;\n   for(unsigned i = 0; i < 2000; ++i)\n   {\n      mpfr_float_100 a(val);\n      mpfr_float_100 b = exp(a);\n      mpfi_float_50 in = val;\n      in = exp(in);\n      BOOST_CHECK((boost::math::isfinite)(in));\n      BOOST_CHECK(lower(in) <= b);\n      BOOST_CHECK(upper(in) >= b);\n      b = log(a);\n      in = val;\n      in = log(in);\n      BOOST_CHECK((boost::math::isfinite)(in));\n      BOOST_CHECK(lower(in) <= b);\n      BOOST_CHECK(upper(in) >= b);\n      val /= 1.01;\n   }\n}\n\nvoid test_pow()\n{\n   std::cout << \"Testing pow function\\n\";\n\n   mt19937 gen;\n   uniform_real_distribution<mpfr_float_50> dist1(0, 400);\n\n   for(unsigned i = 0; i < 5000; ++i)\n   {\n      mpfr_float_50 base, p;\n      base = dist1(gen);\n      p = dist1(gen);\n      mpfr_float_100 a, b, r;\n      a = base;\n      b = p;\n      r = pow(a, b);\n      mpfi_float_50 ai, bi, ri;\n      ai = base;\n      bi = p;\n      ri = pow(ai, bi);\n      BOOST_CHECK((boost::math::isfinite)(ri));\n      BOOST_CHECK(lower(ri) <= r);\n      BOOST_CHECK(upper(ri) >= r);\n   }\n}\n\nvoid test_trig()\n{\n   std::cout << \"Testing trig functions\\n\";\n\n   mt19937 gen;\n   uniform_real_distribution<mpfr_float_50> dist1(-1.57079632679, 1.57079632679);\n   uniform_real_distribution<mpfr_float_50> dist2(-1, 1);\n\n   for(unsigned i = 0; i < 5000; ++i)\n   {\n      mpfr_float_50 val;\n      val = dist1(gen);\n      mpfr_float_100 a = val;\n      mpfr_float_100 b = sin(a);\n      mpfi_float_50 a2 = val;\n      mpfi_float_50 b2 = sin(a2);\n      BOOST_CHECK((boost::math::isfinite)(b2));\n      BOOST_CHECK(lower(b2) <= b);\n      BOOST_CHECK(upper(b2) >= b);\n      b = cos(a);\n      b2 = cos(a2);\n      BOOST_CHECK((boost::math::isfinite)(b2));\n      BOOST_CHECK(lower(b2) <= b);\n      BOOST_CHECK(upper(b2) >= b);\n      b = tan(a);\n      b2 = tan(a2);\n      BOOST_CHECK((boost::math::isfinite)(b2));\n      BOOST_CHECK(lower(b2) <= b);\n      BOOST_CHECK(upper(b2) >= b);\n   }\n   for(unsigned i = 0; i < 5000; ++i)\n   {\n      mpfr_float_50 val;\n      val = dist2(gen);\n      mpfr_float_100 a = val;\n      mpfr_float_100 b = asin(a);\n      mpfi_float_50 a2 = val;\n      mpfi_float_50 b2 = asin(a2);\n      BOOST_CHECK((boost::math::isfinite)(b2));\n      BOOST_CHECK(lower(b2) <= b);\n      BOOST_CHECK(upper(b2) >= b);\n      b = acos(a);\n      b2 = acos(a2);\n      BOOST_CHECK((boost::math::isfinite)(b2));\n      BOOST_CHECK(lower(b2) <= b);\n      BOOST_CHECK(upper(b2) >= b);\n      b = atan(a);\n      b2 = atan(a2);\n      BOOST_CHECK((boost::math::isfinite)(b2));\n      BOOST_CHECK(lower(b2) <= b);\n      BOOST_CHECK(upper(b2) >= b);\n   }\n}\n\nvoid test_hyp()\n{\n   std::cout << \"Testing hyperbolic trig functions\\n\";\n\n   mt19937 gen;\n   uniform_real_distribution<mpfr_float_50> dist1(-10, 10);\n   uniform_real_distribution<mpfr_float_50> dist2(-1, 1);\n\n   for(unsigned i = 0; i < 5000; ++i)\n   {\n      mpfr_float_50 val;\n      val = dist1(gen);\n      mpfr_float_100 a = val;\n      mpfr_float_100 b = sinh(a);\n      mpfi_float_50 a2 = val;\n      mpfi_float_50 b2 = sinh(a2);\n      BOOST_CHECK((boost::math::isfinite)(b2));\n      BOOST_CHECK(lower(b2) <= b);\n      BOOST_CHECK(upper(b2) >= b);\n      b = cosh(a);\n      b2 = cosh(a2);\n      BOOST_CHECK((boost::math::isfinite)(b2));\n      BOOST_CHECK(lower(b2) <= b);\n      BOOST_CHECK(upper(b2) >= b);\n      b = tanh(a);\n      b2 = tanh(a2);\n      BOOST_CHECK((boost::math::isfinite)(b2));\n      BOOST_CHECK(lower(b2) <= b);\n      BOOST_CHECK(upper(b2) >= b);\n   }\n}\n\nvoid test_intervals()\n{\n   mpfi_float_50 a(1, 2);\n   mpfi_float_50 b(1.5, 2.5);\n   BOOST_CHECK_EQUAL(lower(a), 1);\n   BOOST_CHECK_EQUAL(upper(a), 2);\n   BOOST_CHECK_EQUAL(median(a), 1.5);\n   BOOST_CHECK_EQUAL(width(a), 1);\n   mpfi_float_50 r = intersect(a, b);\n   BOOST_CHECK_EQUAL(lower(r), 1.5);\n   BOOST_CHECK_EQUAL(upper(r), 2);\n   r = hull(a, b);\n   BOOST_CHECK_EQUAL(lower(r), 1);\n   BOOST_CHECK_EQUAL(upper(r), 2.5);\n   BOOST_CHECK(overlap(a, b));\n   BOOST_CHECK(in(mpfr_float_50(1.5), a));\n   BOOST_CHECK(in(mpfr_float_50(1), a));\n   BOOST_CHECK(in(mpfr_float_50(2), a));\n   BOOST_CHECK(!zero_in(a));\n   b = mpfi_float_50(1.5, 1.75);\n   BOOST_CHECK(subset(b, a));\n   BOOST_CHECK(proper_subset(b, a));\n   BOOST_CHECK(!empty(a));\n   BOOST_CHECK(!singleton(a));\n   b = mpfi_float_50(5, 6);\n   r = intersect(a, b);\n   BOOST_CHECK(empty(r));\n}\n\n#ifdef TEST_SPECIAL\n#include \"math/table_type.hpp\"\n#include <boost/math/special_functions.hpp>\n\n#define T mpfi_float_50\n\ntypedef number<mpfi_float_backend<25> > mpfi_float_25;\n\nvoid test_log1p_expm1()\n{\n#  include \"../../math/test/log1p_expm1_data.ipp\"\n\n   std::cout << std::setprecision(std::numeric_limits<mpfi_float_25>::max_digits10);\n   std::cout << \"Testing log1p and expm1\\n\";\n\n   for(unsigned i = 0; i < log1p_expm1_data.size(); ++i)\n   {\n      mpfi_float_25 in(log1p_expm1_data[i][0]);\n      mpfi_float_25 out = boost::math::log1p(in);\n      mpfi_float_25 expected(log1p_expm1_data[i][1]);\n      if(!subset(expected, out))\n      {\n         std::cout << in << std::endl;\n         std::cout << out << std::endl;\n         std::cout << expected << std::endl;\n         BOOST_CHECK(lower(out) <= lower(expected));\n         BOOST_CHECK(upper(out) >= upper(expected));\n      }\n      out = boost::math::expm1(in);\n      expected = mpfi_float_25(log1p_expm1_data[i][2]);\n      if(!subset(expected, out))\n      {\n         std::cout << in << std::endl;\n         std::cout << out << std::endl;\n         std::cout << expected << std::endl;\n         BOOST_CHECK(lower(out) <= lower(expected));\n         BOOST_CHECK(upper(out) >= upper(expected));\n      }\n   }\n}\n\nvoid test_bessel()\n{\n#include \"../../math/test/bessel_i_int_data.ipp\"\n#include \"../../math/test/bessel_i_data.ipp\"\n\n   std::cout << std::setprecision(std::numeric_limits<mpfi_float_25>::max_digits10);\n   std::cout << \"Testing Bessel Functions\\n\";\n\n   for(unsigned i = 0; i < bessel_i_int_data.size(); ++i)\n   {\n      int v = boost::lexical_cast<int>(static_cast<const char*>(bessel_i_int_data[i][0]));\n      mpfi_float_25 in(bessel_i_int_data[i][1]);\n      mpfi_float_25 out = boost::math::cyl_bessel_i(v, in);\n      mpfi_float_25 expected(bessel_i_int_data[i][2]);\n      if(!subset(expected, out))\n      {\n         std::cout << in << std::endl;\n         std::cout << out << std::endl;\n         std::cout << expected << std::endl;\n         BOOST_CHECK(lower(out) <= lower(expected));\n         BOOST_CHECK(upper(out) >= upper(expected));\n      }\n   }\n}\n\n#endif\n\nint main()\n{\n#ifdef TEST_SPECIAL\n   test_log1p_expm1();\n   test_bessel();\n#endif\n   test_intervals();\n   test_exp();\n   test_pow();\n   test_trig();\n   test_hyp();\n   return boost::report_errors();\n}\n\n\n\n", "meta": {"hexsha": "ed1084724b8ce8c3ec8e90fd27bbb8a50c04c0f8", "size": 7643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/boost/libs/multiprecision/test/test_mpfi.cpp", "max_stars_repo_name": "alexhenrie/poedit", "max_stars_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "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": "deps/boost/libs/multiprecision/test/test_mpfi.cpp", "max_issues_repo_name": "alexhenrie/poedit", "max_issues_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "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": "deps/boost/libs/multiprecision/test/test_mpfi.cpp", "max_forks_repo_name": "alexhenrie/poedit", "max_forks_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "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": 26.8175438596, "max_line_length": 90, "alphanum_fraction": 0.5875964935, "num_tokens": 2314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5259942919097265}}
{"text": "//  (C) Copyright Gennadiy Rozental 2001-2005.\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//  File        : $RCSfile: floating_point_comparison.hpp,v $\n//\n//  Version     : $Revision: 1.23 $\n//\n//  Description : defines algoirthms for comparing 2 floating point values\n// ***************************************************************************\n\n#ifndef BOOST_TEST_FLOATING_POINT_COMPARISON_HPP_071894GER\n#define BOOST_TEST_FLOATING_POINT_COMPARISON_HPP_071894GER\n\n#include <boost/limits.hpp>  // for std::numeric_limits\n\n#include <boost/test/utils/class_properties.hpp>\n\n#include <boost/test/detail/suppress_warnings.hpp>\n\n//____________________________________________________________________________//\n\nnamespace boost {\n\nnamespace test_tools {\n\nusing unit_test::readonly_property;\n\n// ************************************************************************** //\n// **************        floating_point_comparison_type        ************** //\n// ************************************************************************** //\n\nenum floating_point_comparison_type { FPC_STRONG, FPC_WEAK };\n\n// ************************************************************************** //\n// **************                    details                   ************** //\n// ************************************************************************** //\n\nnamespace tt_detail {\n\ntemplate<typename FPT>\ninline FPT\nfpt_abs( FPT arg ) \n{\n    return arg < 0 ? -arg : arg;\n}\n\n//____________________________________________________________________________//\n\n// both f1 and f2 are unsigned here\ntemplate<typename FPT>\ninline FPT \nsafe_fpt_division( FPT f1, FPT f2 )\n{\n    return  (f2 < 1 && f1 > f2 * (std::numeric_limits<FPT>::max)())               ? (std::numeric_limits<FPT>::max)()\n            : ((f2 > 1 && f1 < f2 * (std::numeric_limits<FPT>::min)() || f1 == 0) ? 0\n                                                                                  : f1/f2 );\n}\n\n//____________________________________________________________________________//\n\n} // namespace tt_detail\n\n// ************************************************************************** //\n// **************             close_at_tolerance               ************** //\n// ************************************************************************** //\n\ntemplate<typename FPT, typename PersentType = FPT >\nclass close_at_tolerance {\npublic:\n    // Public typedefs\n    typedef bool result_type;\n\n    // Constructor\n    explicit    close_at_tolerance( PersentType percentage_tolerance, floating_point_comparison_type fpc_type = FPC_STRONG ) \n    : p_fraction_tolerance( static_cast<FPT>(0.01)*percentage_tolerance ), p_strong_or_weak( fpc_type ==  FPC_STRONG ) {}\n\n    bool        operator()( FPT left, FPT right ) const\n    {\n        FPT diff = tt_detail::fpt_abs( left - right );\n        FPT d1   = tt_detail::safe_fpt_division( diff, tt_detail::fpt_abs( right ) );\n        FPT d2   = tt_detail::safe_fpt_division( diff, tt_detail::fpt_abs( left ) );\n        \n        return p_strong_or_weak ? (d1 <= p_fraction_tolerance.get() && d2 <= p_fraction_tolerance.get()) \n                                : (d1 <= p_fraction_tolerance.get() || d2 <= p_fraction_tolerance.get());\n    }\n\n    // Public properties\n    readonly_property<FPT>  p_fraction_tolerance;\n    readonly_property<bool> p_strong_or_weak;\n};\n\n//____________________________________________________________________________//\n\n// ************************************************************************** //\n// **************               check_is_close                 ************** //\n// ************************************************************************** //\n\nstruct check_is_close_t {\n    // Public typedefs\n    typedef bool result_type;\n\n    template<typename FPT, typename PersentType>\n    bool\n    operator()( FPT left, FPT right, PersentType percentage_tolerance, floating_point_comparison_type fpc_type = FPC_STRONG )\n    {\n        close_at_tolerance<FPT,PersentType> pred( percentage_tolerance, fpc_type );\n\n        return pred( left, right );\n    }\n};\n\nnamespace {\ncheck_is_close_t check_is_close;\n}\n\n//____________________________________________________________________________//\n\n// ************************************************************************** //\n// **************               check_is_small                 ************** //\n// ************************************************************************** //\n\nstruct check_is_small_t {\n    // Public typedefs\n    typedef bool result_type;\n\n    template<typename FPT>\n    bool\n    operator()( FPT fpv, FPT tolerance )\n    {\n        return tt_detail::fpt_abs( fpv ) < tolerance;\n    }\n};\n\nnamespace {\ncheck_is_small_t check_is_small;\n}\n\n//____________________________________________________________________________//\n\n} // namespace test_tools\n\n} // namespace boost\n\n//____________________________________________________________________________//\n\n#include <boost/test/detail/enable_warnings.hpp>\n\n// ***************************************************************************\n//  Revision History :\n//  \n//  $Log: floating_point_comparison.hpp,v $\n//  Revision 1.23  2005/05/29 08:54:57  rogeeff\n//  allow bind usage\n//\n//  Revision 1.22  2005/02/21 10:21:40  rogeeff\n//  check_is_small implemented\n//  check functions implemented as function objects\n//\n//  Revision 1.21  2005/02/20 08:27:05  rogeeff\n//  This a major update for Boost.Test framework. See release docs for complete list of fixes/updates\n//\n//  Revision 1.20  2005/02/01 06:40:06  rogeeff\n//  copyright update\n//  old log entries removed\n//  minor stilistic changes\n//  depricated tools removed\n//\n//  Revision 1.19  2005/01/22 19:22:12  rogeeff\n//  implementation moved into headers section to eliminate dependency of included/minimal component on src directory\n//\n// ***************************************************************************\n\n#endif // BOOST_FLOATING_POINT_COMAPARISON_HPP_071894GER\n", "meta": {"hexsha": "6cef79bad03ad9a7126eb7cbc04c97bb9ed8f6aa", "size": 6146, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Source/boost_1_33_1/boost/test/floating_point_comparison.hpp", "max_stars_repo_name": "spxuw/RFIM", "max_stars_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_stars_repo_licenses": ["MIT"], "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/boost_1_33_1/boost/test/floating_point_comparison.hpp", "max_issues_repo_name": "spxuw/RFIM", "max_issues_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_issues_repo_licenses": ["MIT"], "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/boost_1_33_1/boost/test/floating_point_comparison.hpp", "max_forks_repo_name": "spxuw/RFIM", "max_forks_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_forks_repo_licenses": ["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.5280898876, "max_line_length": 125, "alphanum_fraction": 0.5579238529, "num_tokens": 1228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5259942857388898}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// Authors: Ilgweon Kang and Lutong Wang\n//          (respective Ph.D. advisors: Chung-Kuan Cheng, Andrew B. Kahng),\n//          based on Dr. Jingwei Lu with ePlace and ePlace-MS\n//\n//          Many subsequent improvements were made by Mingyu Woo\n//          leading up to the initial release.\n//\n// BSD 3-Clause License\n//\n// Copyright (c) 2018, The Regents of the University of California\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\n// 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#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <string>\n#include <ctime>\n\n#include \"global.h\"\n#include \"initPlacement.h\"\n#include \"plot.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/IterativeLinearSolvers>\n#include <unsupported/Eigen/IterativeSolvers>\n\nvoid initial_placement() {\n  using namespace Eigen;\n  printf(\"PROC:  Conjugate Gradient (CG) method to obtain the IP\\n\");\n\n  int itol = 1;\n  int itmax = 100;\n  int x_iter = 0, y_iter = 0;\n\n  prec tol = 0.000001;\n  prec target_tol = 0.000001;\n  prec x_err = 0, y_err = 0;\n\n  double time_s = 0;\n\n  HPWL_count();\n\n  if(isSkipIP) {\n    return;\n  }\n\n  printf(\"INFO:  The Initial HPWL is %.6lf\\n\", tot_HPWL);\n\n  if(tot_HPWL <= 0) {\n    printf(\"ERROR: HPWL <= 0, skip initial QP\\n\");\n    return;\n  }\n\n  printf(\"INFO:  The Matrix Size is %d\\n\", moduleCNT);\n  fflush(stdout);\n\n  // malloc to solve PCG\n  //\n  // Ax = b\n  //\n  // x : variable vector to solve\n  // b : constant vector\n  //\n\n  setNbThreads(numThread);\n\n  // BCGSTAB settings\n  SMatrix eMatX(moduleCNT, moduleCNT), eMatY(moduleCNT, moduleCNT);\n\n  VectorXf xcg_x(moduleCNT), xcg_b(moduleCNT), ycg_x(moduleCNT),\n      ycg_b(moduleCNT);\n\n  for(int i = 0;; i++) {\n    if(i >= numInitPlaceIter) {\n      break;\n    }\n\n    time_start(&time_s);\n    CreateSparseMatrix(xcg_x, xcg_b, ycg_x, ycg_b, eMatX, eMatY);\n\n    BiCGSTAB< SMatrix, IdentityPreconditioner > solver;\n    solver.setMaxIterations(itmax);\n\n    solver.compute(eMatX);\n    xcg_x = solver.solveWithGuess(xcg_b, xcg_x);\n    x_err = solver.error();\n\n    solver.compute(eMatY);\n    ycg_x = solver.solveWithGuess(ycg_b, ycg_x);\n    y_err = solver.error();\n\n    update_module(xcg_x, ycg_x);\n    update_pin_by_module();\n    update_net_by_pin();\n    HPWL_count();\n\n    if(isPlot && i % 5 == 0) {\n      SaveCellPlotAsJPEG(string(\"FIP - Iter: \") + to_string(i), false,\n                         string(dir_bnd) + string(\"/initPlace/initPlacement_\") +\n                             intoFourDigit(i));\n      // SavePlot( string(\"FIP - Iter: \") + to_string(i) );\n    }\n\n    time_end(&time_s);\n    printf(\"INFO:  IP%3d,  CG Error %.6lf,  HPWL %.6lf,  CPUtime %.2lf\\n\", i,\n           max(x_err, y_err), tot_HPWL, time_s);\n    fflush(stdout);\n\n    if(fabs(x_err) < target_tol && fabs(y_err) < target_tol && i > 4) {\n      break;\n    }\n  }\n}\n\nvoid build_data_struct(bool initCoordi) {\n  MODULE *mdp = NULL;\n  TERM *term = NULL;\n  PIN *pin = NULL;\n  NET *curNet = NULL;\n  FPOS pof;\n\n  prec min_x = 0;\n  prec min_y = 0;\n  prec max_x = 0;\n  prec max_y = 0;\n\n  for(int i = 0; i < terminalCNT; i++) {\n    term = &terminalInstance[i];\n\n    for(int j = 0; j < term->pinCNTinObject; j++) {\n      pin = term->pin[j];\n      pin->tier = 0;\n    }\n\n  }\n\n  for(int i = 0; i < moduleCNT; i++) {\n    mdp = &moduleInstance[i];\n\n    if(initCoordi) {\n      mdp->center = place.center;\n    }\n\n    mdp->pmin.x = mdp->center.x - 0.5 * mdp->size.x;\n    mdp->pmin.y = mdp->center.y - 0.5 * mdp->size.y;\n\n    mdp->pmax.x = mdp->center.x + 0.5 * mdp->size.x;\n    mdp->pmax.y = mdp->center.y + 0.5 * mdp->size.y;\n\n    for(int j = 0; j < mdp->pinCNTinObject; j++) {\n      pof = mdp->pof[j];\n      pin = mdp->pin[j];\n\n      pin->fp.x = mdp->center.x + pof.x;\n      pin->fp.y = mdp->center.y + pof.y;\n\n      pin->X_MIN = 0;\n      pin->X_MAX = 0;\n      pin->Y_MIN = 0;\n      pin->Y_MAX = 0;\n    }\n  }\n\n  term_pmin.x = PREC_MAX;\n  term_pmin.x = PREC_MAX;\n  term_pmax.x = 0;\n  term_pmax.y = 0;\n\n  for(int i = 0; i < terminalCNT; i++) {\n    term = &terminalInstance[i];\n\n    term->pmin.x = term->center.x - 0.5 * term->size.x;\n    term->pmin.y = term->center.y - 0.5 * term->size.y;\n\n    term->pmax.x = term->center.x + 0.5 * term->size.x;\n    term->pmax.y = term->center.y + 0.5 * term->size.y;\n\n    if(term_pmin.x > term->pmin.x)\n      term_pmin.x = term->pmin.x;\n    if(term_pmin.y > term->pmin.y)\n      term_pmin.y = term->pmin.y;\n    if(term_pmax.x < term->pmax.x)\n      term_pmax.x = term->pmax.x;\n    if(term_pmax.y < term->pmax.y)\n      term_pmax.y = term->pmax.y;\n\n    for(int j = 0; j < term->pinCNTinObject; j++) {\n      pof = term->pof[j];\n      pin = term->pin[j];\n\n      pin->fp.x = term->center.x + pof.x;\n      pin->fp.y = term->center.y + pof.y;\n\n      pin->X_MIN = 0;\n      pin->X_MAX = 0;\n      pin->Y_MIN = 0;\n      pin->Y_MAX = 0;\n    }\n  }\n\n  for(int i = 0; i < netCNT; i++) {\n    curNet = &netInstance[i];\n\n    min_x = PREC_MAX;\n    min_y = PREC_MAX;\n    max_x = PREC_MIN;\n    max_y = PREC_MIN;\n\n    PIN *pin_xmin = NULL;\n    PIN *pin_ymin = NULL;\n    PIN *pin_xmax = NULL;\n    PIN *pin_ymax = NULL;\n\n    for(int j = 0; j < curNet->pinCNTinObject; j++) {\n      pin = curNet->pin[j];\n      if(pin_xmin) {\n        if(min_x > pin->fp.x) {\n          min_x = pin->fp.x;\n          pin_xmin->X_MIN = 0;\n          pin_xmin = pin;\n          pin->X_MIN = 1;\n        }\n      }\n      else {\n        min_x = pin->fp.x;  // mdp->center.x ;\n        pin_xmin = pin;\n        pin->X_MIN = 1;\n      }\n\n      if(pin_ymin) {\n        if(min_y > pin->fp.y)  // mdp->center.y)\n        {\n          min_y = pin->fp.y;  // mdp->center.y ;\n          pin_ymin->Y_MIN = 0;\n          pin_ymin = pin;\n          pin->Y_MIN = 1;\n        }\n      }\n      else {\n        min_y = pin->fp.y;  // mdp->center.y ;\n        pin_ymin = pin;\n        pin->Y_MIN = 1;\n      }\n\n      if(pin_xmax) {\n        if(max_x < pin->fp.x)  // mdp->center.x)\n        {\n          max_x = pin->fp.x;  // mdp->center.x ;\n          pin_xmax->X_MAX = 0;\n          pin_xmax = pin;\n          pin->X_MAX = 1;\n        }\n      }\n      else {\n        max_x = pin->fp.x;  // mdp->center.x ;\n        pin_xmax = pin;\n        pin->X_MAX = 1;\n      }\n\n      if(pin_ymax) {\n        if(max_y < pin->fp.y)  // mdp->center.y)\n        {\n          max_y = pin->fp.y;  // mdp->center.y ;\n          pin_ymax->Y_MAX = 0;\n          pin_ymax = pin;\n          pin->Y_MAX = 1;\n        }\n      }\n      else {\n        max_y = pin->fp.y;  // mdp->center.y ;\n        pin_ymax = pin;\n        pin->Y_MAX = 1;\n      }\n    }\n\n    curNet->min_x = min_x;\n    curNet->min_y = min_y;\n\n    curNet->max_x = max_x;\n    curNet->max_y = max_y;\n  }\n}\n\nvoid update_module(VectorXf &xcg_x, VectorXf &ycg_x) {\n  MODULE *mdp = NULL;\n  for(int i = 0; i < moduleCNT; i++) {\n    mdp = &moduleInstance[i];\n\n    mdp->center.x = xcg_x(i);\n    mdp->center.y = ycg_x(i);\n\n    if((mdp->center.x + 0.5 * mdp->size.x) > place.end.x)\n      mdp->center.x = place.end.x - 0.5 * mdp->size.x - Epsilon;\n\n    if((mdp->center.y + 0.5 * mdp->size.y) > place.end.y)\n      mdp->center.y = place.end.y - 0.5 * mdp->size.y - Epsilon;\n\n    if((mdp->center.x - 0.5 * mdp->size.x) < place.org.x)\n      mdp->center.x = place.org.x + 0.5 * mdp->size.x + Epsilon;\n\n    if((mdp->center.y - 0.5 * mdp->size.y) < place.org.y)\n      mdp->center.y = place.org.y + 0.5 * mdp->size.y + Epsilon;\n\n    mdp->pmin.x = mdp->center.x - 0.5 * mdp->size.x;\n    mdp->pmin.y = mdp->center.y - 0.5 * mdp->size.y;\n\n    mdp->pmax.x = mdp->center.x + 0.5 * mdp->size.x;\n    mdp->pmax.y = mdp->center.y + 0.5 * mdp->size.y;\n  }\n}\n\nvoid update_pin_by_module(void) {\n  FPOS pof;\n  PIN *pin = NULL;\n  MODULE *mdp = NULL;\n\n  for(int i = 0; i < moduleCNT; i++) {\n    mdp = &moduleInstance[i];\n    for(int j = 0; j < mdp->pinCNTinObject; j++) {\n      pof = mdp->pof[j];\n      pin = mdp->pin[j];\n\n      if(pin->moduleID != i || pin->pinIDinModule != j || pin->term == 1) {\n        exit(1);\n      }\n\n      pin->fp.x = mdp->center.x + pof.x;\n      pin->fp.y = mdp->center.y + pof.y;\n\n      pin->X_MIN = 0;\n      pin->X_MAX = 0;\n      pin->Y_MIN = 0;\n      pin->Y_MAX = 0;\n    }\n  }\n}\n\nvoid update_net_by_pin() {\n  for(int i = 0; i < netCNT; i++) {\n    NET *curNet = &netInstance[i];\n\n    PIN *pin_xmin = NULL, *pin_ymin = NULL;\n    PIN *pin_xmax = NULL, *pin_ymax = NULL;\n\n    prec min_x = PREC_MAX, min_y = PREC_MAX;\n    prec max_x = PREC_MIN, max_y = PREC_MIN;\n\n    for(int j = 0; j < curNet->pinCNTinObject; j++) {\n      PIN *pin = curNet->pin[j];\n\n      if(pin_xmin) {\n        if(min_x > pin->fp.x)  // mdp->center.x)\n        {\n          min_x = pin->fp.x;  // mdp->center.x ;\n          pin_xmin->X_MIN = 0;\n          pin_xmin = pin;\n          pin->X_MIN = 1;\n        }\n      }\n      else {\n        min_x = pin->fp.x;  // mdp->center.x ;\n        pin_xmin = pin;\n        pin->X_MIN = 1;\n      }\n\n      if(pin_ymin) {\n        if(min_y > pin->fp.y)  // mdp->center.y)\n        {\n          min_y = pin->fp.y;  // mdp->center.y ;\n          pin_ymin->Y_MIN = 0;\n          pin_ymin = pin;\n          pin->Y_MIN = 1;\n        }\n      }\n      else {\n        min_y = pin->fp.y;  // mdp->center.y ;\n        pin_ymin = pin;\n        pin->Y_MIN = 1;\n      }\n\n      if(pin_xmax) {\n        if(max_x < pin->fp.x)  // mdp->center.x)\n        {\n          max_x = pin->fp.x;  // mdp->center.x ;\n          pin_xmax->X_MAX = 0;\n          pin_xmax = pin;\n          pin->X_MAX = 1;\n        }\n      }\n      else {\n        max_x = pin->fp.x;  // mdp->center.x ;\n        pin_xmax = pin;\n        pin->X_MAX = 1;\n      }\n\n      if(pin_ymax) {\n        if(max_y < pin->fp.y)  // mdp->center.y)\n        {\n          max_y = pin->fp.y;  // mdp->center.y ;\n          pin_ymax->Y_MAX = 0;\n          pin_ymax = pin;\n          pin->Y_MAX = 1;\n        }\n      }\n      else {\n        max_y = pin->fp.y;  // mdp->center.y ;\n        pin_ymax = pin;\n        pin->Y_MAX = 1;\n      }\n    }\n    curNet->min_x = min_x;\n    curNet->min_y = min_y;\n    curNet->max_x = max_x;\n    curNet->max_y = max_y;\n  }\n}\n\n//\n// CreateSparseMatrix Routine\n//\n// using current Pin's structure,\n// based on the B2B models,\n// it genereates Sparsematrix into Eigen formats.\n//\nvoid CreateSparseMatrix(VectorXf &xcg_x, VectorXf &xcg_b, VectorXf &ycg_x,\n                        VectorXf &ycg_b, SMatrix &eMatX, SMatrix &eMatY) {\n  int pinCNTinObject = 0;\n  int moduleID1 = 0;\n  int moduleID2 = 0;\n  int is_term1 = 0;\n  int is_term2 = 0;\n\n  prec common1;\n  prec common2;\n\n  NET *tempNet = NULL;\n  PIN *pin1 = NULL;\n  PIN *pin2 = NULL;\n\n  MODULE *mdp1 = NULL;\n  MODULE *mdp2 = NULL;\n  TERM *term1 = NULL;\n  TERM *term2 = NULL;\n\n  FPOS center1, center2;\n  FPOS fp1, fp2;\n\n  // to easily convert (i, j, value) -> CSR sparse Matrix.\n  // using Eigen library..\n  vector< T > tripletListX, tripletListY;\n  tripletListX.reserve(10000000);\n  tripletListY.reserve(10000000);\n\n  // xcg_x & ycg_x update\n  MODULE *curModule = NULL;\n  for(int i = 0; i < moduleCNT; i++) {\n    curModule = &moduleInstance[i];\n\n    // 1d prec array\n    xcg_x(i) = curModule->center.x;\n    ycg_x(i) = curModule->center.y;\n\n    xcg_b(i) = ycg_b(i) = 0;\n  }\n\n  for(int i = 0; i < netCNT; i++) {\n    tempNet = &netInstance[i];\n    pinCNTinObject = tempNet->pinCNTinObject;\n    common1 = 1.0 / ((prec)pinCNTinObject - 1.0);\n\n    for(int j = 0; j < pinCNTinObject; j++) {\n      pin1 = tempNet->pin[j];\n      moduleID1 = pin1->moduleID;\n      fp1 = pin1->fp;\n\n      // if is not Terminal -> moduleInstance\n      if(!pin1->term) {\n        mdp1 = &moduleInstance[moduleID1];\n        center1 = mdp1->center;\n        is_term1 = 0;\n      }\n      // is terminal -> terminalInstance\n      else {\n        term1 = &terminalInstance[moduleID1];\n        center1 = term1->center;\n        is_term1 = 1;\n      }\n\n      for(int k = j + 1; k < pinCNTinObject; k++) {\n        pin2 = tempNet->pin[k];\n        moduleID2 = pin2->moduleID;\n        fp2 = pin2->fp;\n\n        if(!pin2->term) {\n          mdp2 = &moduleInstance[moduleID2];\n          center2 = mdp2->center;\n          is_term2 = 0;\n        }\n        else {\n          term2 = &terminalInstance[moduleID2];\n          center2 = term2->center;\n          is_term2 = 1;\n        }\n\n        // there is no need to calculate (for same nodes)\n        if(moduleID1 == moduleID2 && is_term1 == is_term2) {\n          continue;\n        }\n\n        if(pin1->X_MIN || pin1->X_MAX || pin2->X_MIN || pin2->X_MAX) {\n          prec len_x = fabs(fp1.x - fp2.x);\n\n          prec wt_x = 0.0f;\n          if(dge(len_x, MIN_LEN)) {\n            wt_x = common1 / len_x;\n          }\n          else {\n            wt_x = common1 / MIN_LEN;\n          }\n\n          common2 = (-1.0) * wt_x;\n\n          if(wt_x < 0)\n            printf(\"ERROR WEIGHT\\n\");\n\n          // both is module\n          if(!is_term1 && !is_term2) {\n            tripletListX.push_back(T(moduleID1, moduleID1, wt_x));\n            tripletListX.push_back(T(moduleID2, moduleID2, wt_x));\n            tripletListX.push_back(T(moduleID1, moduleID2, common2));\n            tripletListX.push_back(T(moduleID2, moduleID1, common2));\n\n            xcg_b(moduleID1) +=\n                common2 * ((fp1.x - center1.x) - (fp2.x - center2.x));\n            xcg_b(moduleID2) +=\n                common2 * ((fp2.x - center2.x) - (fp1.x - center1.x));\n          }\n          // 1 is terminal, 2 is module\n          else if(is_term1 && !is_term2) {\n            tripletListX.push_back(T(moduleID2, moduleID2, wt_x));\n            xcg_b(moduleID2) += wt_x * (fp1.x - (fp2.x - center2.x));\n          }\n          // 2 is terminal, 1 is module\n          else if(!is_term1 && is_term2) {\n            tripletListX.push_back(T(moduleID1, moduleID1, wt_x));\n            xcg_b(moduleID1) += wt_x * (fp2.x - (fp1.x - center1.x));\n          }\n        }\n\n        if(pin1->Y_MIN || pin1->Y_MAX || pin2->Y_MIN || pin2->Y_MAX) {\n          prec len_y = fabs(fp1.y - fp2.y);\n\n          prec wt_y = 0.0f;\n          if(dge(len_y, MIN_LEN)) {\n            wt_y = common1 / len_y;\n          }\n          else {\n            wt_y = common1 / MIN_LEN;\n          }\n          common2 = (-1.0) * wt_y;\n\n          // both is module\n          if(!is_term1 && !is_term2) {\n            tripletListY.push_back(T(moduleID1, moduleID1, wt_y));\n            tripletListY.push_back(T(moduleID2, moduleID2, wt_y));\n            tripletListY.push_back(T(moduleID1, moduleID2, common2));\n            tripletListY.push_back(T(moduleID2, moduleID1, common2));\n\n            ycg_b(moduleID1) +=\n                common2 * ((fp1.y - center1.y) - (fp2.y - center2.y));\n            ycg_b(moduleID2) +=\n                common2 * ((fp2.y - center2.y) - (fp1.y - center1.y));\n          }\n          // 1 is terminal, 2 is module\n          else if(is_term1 && !is_term2) {\n            tripletListY.push_back(T(moduleID2, moduleID2, wt_y));\n            ycg_b(moduleID2) += wt_y * (fp1.y - (fp2.y - center2.y));\n          }\n          // 2 is terminal, 1 is module\n          else if(!is_term1 && is_term2) {\n            tripletListY.push_back(T(moduleID1, moduleID1, wt_y));\n            ycg_b(moduleID1) += wt_y * (fp2.y - (fp1.y - center1.y));\n          }\n        }\n      }\n    }\n  }\n\n  eMatX.setFromTriplets(tripletListX.begin(), tripletListX.end());\n  eMatY.setFromTriplets(tripletListY.begin(), tripletListY.end());\n}\n", "meta": {"hexsha": "dc4a4ea943e12ab5227d298a76744802838c5908", "size": 16814, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/initPlacement.cpp", "max_stars_repo_name": "puckbee/RePlAce", "max_stars_repo_head_hexsha": "67f505f8a858b8da430bbdc1debc264020edf8f2", "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/initPlacement.cpp", "max_issues_repo_name": "puckbee/RePlAce", "max_issues_repo_head_hexsha": "67f505f8a858b8da430bbdc1debc264020edf8f2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/initPlacement.cpp", "max_forks_repo_name": "puckbee/RePlAce", "max_forks_repo_head_hexsha": "67f505f8a858b8da430bbdc1debc264020edf8f2", "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.0321543408, "max_line_length": 80, "alphanum_fraction": 0.5405019627, "num_tokens": 5286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5259942795680532}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::detail::accumulator::statistics::mean_var_accumulator.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_ACCUMULATOR_STATISTICS_MEAN_VAR_ACCUMULATOR_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_ACCUMULATOR_STATISTICS_MEAN_VAR_ACCUMULATOR_HPP_ER_2009\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n\nnamespace boost{\nnamespace functional{\n\n    // This comes up often, so this saves a bit of time\n    template<typename T>\n    struct mean_var_accumulator{\n        typedef accumulators::stats<\n            accumulators::tag::mean,\n            accumulators::tag::variance\n        >  stat_;\n        typedef accumulators::accumulator_set<T,stat_> type;\n    };\n\n}// meta    \n}// boost\n\n#endif\n", "meta": {"hexsha": "6ea0a16bb6e4ca76fdc8eac4ebeaed094d92612f", "size": 1325, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "detail/accumulator/boost/statistics/detail/accumulator/statistics/mean_var_accumulator.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/accumulator/boost/statistics/detail/accumulator/statistics/mean_var_accumulator.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/accumulator/boost/statistics/detail/accumulator/statistics/mean_var_accumulator.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": 41.40625, "max_line_length": 87, "alphanum_fraction": 0.5901886792, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5259942749192521}}
{"text": "#include \"dSFMTsearch.hpp\"\n#include \"Annihilate.h\"\n#include <errno.h>\n#include <stdlib.h>\n#include <getopt.h>\n#include <errno.h>\n#include <NTL/GF2X.h>\n#include <NTL/GF2XFactoring.h>\n#include <MTToolBox/period.hpp>\n#include <MTToolBox/AlgorithmReducibleRecursionSearch.hpp>\n#include \"calc_fixpoint.h\"\n\nusing namespace MTToolBox;\nusing namespace std;\n\nw128_t calc_fixpoint(const dSFMT& dsfmt, const GF2X& irreducible,\n                     const GF2X& quotient)\n{\n    GF2X a, b, d;\n    dSFMT dsfmt_const(dsfmt);\n    /* a*irreducible + b*quotient = d */\n    XGCD(d, a, b, irreducible, quotient);\n    if (deg(d) != 0) {\n        cout << \"failure d != 1\" << endl;\n        throw new logic_error(\"failure d != 1\");\n    }\n    b *= quotient;\n    a *= irreducible;\n    dsfmt_const.setConst();\n    annihilate<w128_t>(&dsfmt_const, b);\n\n    GF2X t1(1, 1);\n    SetCoeff(t1, 0);\n    /* a*irreducible + b*t1 = d */\n    XGCD(d, a, b, irreducible, t1);\n    if (deg(d) != 0) {\n        cout << \"failure d != 1\" << endl;\n        cout << \"deg(d) = \" << dec << deg(d) << endl;\n        cout << \"deg(irreducible) = \" << dec << deg(irreducible) << endl;\n        cout << \"deg(t1) = \" << dec << deg(t1) << endl;\n        throw new logic_error(\"failure d != 1\");\n    }\n    annihilate<w128_t>(&dsfmt_const, b);\n    return dsfmt_const.getParityValue();\n}\n", "meta": {"hexsha": "41627ec4cbca219e663b44504af999cec554f903", "size": 1322, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/calc_fixpoint.cpp", "max_stars_repo_name": "MSaito/dSFMTSearchParam", "max_stars_repo_head_hexsha": "b0f5d02de7ff91a807f78fe79e9df1fd9c6e257a", "max_stars_repo_licenses": ["MIT"], "max_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_fixpoint.cpp", "max_issues_repo_name": "MSaito/dSFMTSearchParam", "max_issues_repo_head_hexsha": "b0f5d02de7ff91a807f78fe79e9df1fd9c6e257a", "max_issues_repo_licenses": ["MIT"], "max_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_fixpoint.cpp", "max_forks_repo_name": "MSaito/dSFMTSearchParam", "max_forks_repo_head_hexsha": "b0f5d02de7ff91a807f78fe79e9df1fd9c6e257a", "max_forks_repo_licenses": ["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.7391304348, "max_line_length": 73, "alphanum_fraction": 0.5915279879, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.5259455434217748}}
{"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/rectifier_function.hpp>\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#include <mlpack/methods/ann/layer/dropout_layer.hpp>\n\n#include <mlpack/methods/ann/cnn.hpp>\n#include <mlpack/methods/ann/trainer/trainer.hpp>\n#include <mlpack/methods/ann/optimizer/ada_delta.hpp>\n#include <mlpack/methods/ann/optimizer/rmsprop.hpp>\n#include <mlpack/methods/ann/init_rules/zero_init.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\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   * 24x24x6 convolution layer, 12x12x6 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<RMSPROP> convLayer0(1, 8, 5, 5);\n  BiasLayer2D<RMSPROP, ZeroInitialization> biasLayer0(8);\n  BaseLayer2D<PerformanceFunction> baseLayer0;\n  PoolingLayer<> poolingLayer0(2);\n\n  ConvLayer<RMSPROP> convLayer1(8, 12, 5, 5);\n  BiasLayer2D<RMSPROP, ZeroInitialization> biasLayer1(12);\n  BaseLayer2D<PerformanceFunction> baseLayer1;\n  PoolingLayer<> poolingLayer1(2);\n\n  LinearMappingLayer<RMSPROP> linearLayer0(192, 10);\n  BiasLayer<RMSPROP> 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      net(modules, outputLayer);\n\n  Trainer<decltype(net)> trainer(net, 50, 1, 0.7);\n  trainer.Train(input, Y, input, Y);\n\n  BOOST_REQUIRE_LE(trainer.ValidationError(), 0.7);\n}\n\n/**\n * Train the vanilla network on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(VanillaNetworkTest)\n{\n  BuildVanillaNetwork<LogisticFunction>();\n}\n\n/**\n * Train and evaluate a vanilla network with the specified structure.\n */\ntemplate<\n    typename PerformanceFunction\n>\nvoid BuildVanillaDropoutNetwork()\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   * 24x24x6 convolution layer, 12x12x6 pooling layer, 8x8x12 convolution layer,\n   * 8x8x12 Dropout Layer and a 4x4x12 pooling layer which is fully connected\n   * with the output layer. The network structure looks like:\n   *\n   * Input    Convolution  Dropout      Pooling     Convolution,     Output\n   * Layer    Layer        Layer        Layer       Dropout,         Layer\n   *                                                Pooling Layer\n   *          +---+        +---+        +---+\n   *          | +---+      | +---+      | +---+\n   * +---+    | | +---+    | | +---+    | | +---+                    +---+\n   * |   |    | | |   |    | | |   |    | | |   |                    |   |\n   * |   +--> +-+ |   +--> +-+ |   +--> +-+ |   +--> ............--> |   |\n   * |   |      +-+   |      +-+   |      +-+   |                    |   |\n   * +---+        +---+        +---+        +---+                    +---+\n   */\n\n  ConvLayer<AdaDelta> convLayer0(1, 4, 5, 5);\n  BiasLayer2D<AdaDelta, ZeroInitialization> biasLayer0(4);\n  DropoutLayer2D<> dropoutLayer0;\n  BaseLayer2D<PerformanceFunction> baseLayer0;\n  PoolingLayer<> poolingLayer0(2);\n\n  ConvLayer<AdaDelta> convLayer1(4, 8, 5, 5);\n  BiasLayer2D<AdaDelta, ZeroInitialization> biasLayer1(8);\n  BaseLayer2D<PerformanceFunction> baseLayer1;\n  PoolingLayer<> poolingLayer1(2);\n\n  LinearMappingLayer<AdaDelta> linearLayer0(128, 10);\n  BiasLayer<AdaDelta> biasLayer2(10);\n  SoftmaxLayer<> softmaxLayer0;\n\n  OneHotLayer outputLayer;\n\n  auto modules = std::tie(convLayer0, biasLayer0, dropoutLayer0, baseLayer0,\n                          poolingLayer0, convLayer1, biasLayer1, baseLayer1,\n                          poolingLayer1, linearLayer0, biasLayer2,\n                          softmaxLayer0);\n\n  CNN<decltype(modules), decltype(outputLayer)>\n      net(modules, outputLayer);\n\n  Trainer<decltype(net)> trainer(net, 50, 1, 0.7);\n  trainer.Train(input, Y, input, Y);\n\n  BOOST_REQUIRE_LE(trainer.ValidationError(), 0.7);\n}\n\n/**\n * Train the network on a larger dataset using dropout.\n */\nBOOST_AUTO_TEST_CASE(VanillaNetworkDropoutTest)\n{\n  BuildVanillaDropoutNetwork<RectifierFunction>();\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "5a2840c6b965004296cacabc4befbf7dcc309095", "size": 6984, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/convolutional_network_test.cpp", "max_stars_repo_name": "vj-ug/Contribution-to-mlpack", "max_stars_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "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/mlpack/tests/convolutional_network_test.cpp", "max_issues_repo_name": "vj-ug/Contribution-to-mlpack", "max_issues_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "vj-ug/Contribution-to-mlpack", "max_forks_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "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.6018099548, "max_line_length": 80, "alphanum_fraction": 0.5922107675, "num_tokens": 2098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5259455327431644}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// kernel::functional::detail::mean_accumulator.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_ESTIMATION_DETAIL_MEAN_ACCUMULATOR_H_ER_2009\n#define BOOST_STATISTICS_DETAIL_KERNEL_ESTIMATION_DETAIL_MEAN_ACCUMULATOR_H_ER_2009\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace kernel{\nnamespace detail{\n\n    // The Rosenblatt-Parzen estimator is a density estimator\n    template<typename T>\n    struct mean_accumulator{\n        typedef accumulators::stats<\n            accumulators::tag::mean\n        >  stat_;\n        typedef accumulators::accumulator_set<T,stat_> type;\n    };\n        \n}// detail\n}// kernel\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "d5382087d44a75195be519143d621359cd8fee04", "size": 1321, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kernel/boost/statistics/detail/kernel/estimation/detail/mean_accumulator.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/estimation/detail/mean_accumulator.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/estimation/detail/mean_accumulator.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": 37.7428571429, "max_line_length": 83, "alphanum_fraction": 0.5768357305, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5259455280399412}}
{"text": "#include \"hops/FileReader/SbmlReader.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <sbml/SBMLTypes.h>\n#include <sbml/packages/fbc/common/FbcExtensionTypes.h>\n\nEigen::SparseMatrix<double> parseStoichiometry(Model *model) {\n    std::map<const std::string, unsigned int> speciesIdAttributeToIndex;\n    for (unsigned int i = 0; i < model->getListOfSpecies()->size(); ++i) {\n        Species *species = model->getSpecies(i);\n        speciesIdAttributeToIndex.insert(std::make_pair(species->getIdAttribute(), i));\n    }\n\n    std::vector<Eigen::Triplet<double>> stoichiometricTriplets;\n    for (unsigned int i = 0; i < model->getListOfReactions()->size(); ++i) {\n        Reaction *reaction = model->getReaction(i);\n        ListOfSpeciesReferences *reactants = reaction->getListOfReactants();\n        for (unsigned int j = 0; j < reactants->size(); ++j) {\n            SimpleSpeciesReference *reactant = reactants->get(j);\n            std::string speciesIdAttribute;\n            reactant->getAttribute(\"species\", speciesIdAttribute);\n            unsigned int k = speciesIdAttributeToIndex.find(speciesIdAttribute)->second;\n            double value;\n            reactant->getAttribute(\"stoichiometry\", value);\n            stoichiometricTriplets.emplace_back(k, i, -value);\n        }\n        ListOfSpeciesReferences *products = reaction->getListOfProducts();\n        for (unsigned int j = 0; j < products->size(); ++j) {\n            SimpleSpeciesReference *product = products->get(j);\n            std::string speciesIdAttribute;\n            product->getAttribute(\"species\", speciesIdAttribute);\n            unsigned int k = speciesIdAttributeToIndex.find(speciesIdAttribute)->second;\n            double value;\n            product->getAttribute(\"stoichiometry\", value);\n            stoichiometricTriplets.emplace_back(k, i, value);\n        }\n    }\n    Eigen::SparseMatrix<double> stoichiometry(model->getListOfSpecies()->size(),\n                                              model->getListOfReactions()->size());\n    stoichiometry.setFromTriplets(stoichiometricTriplets.begin(), stoichiometricTriplets.end());\n    return stoichiometry;\n}\n\nstd::tuple<Eigen::SparseMatrix<double>, Eigen::VectorXd, Eigen::VectorXd, Eigen::VectorXd>\nparseConstraints(Model *model) {\n    unsigned int numberOfReactions = model->getListOfReactions()->size();\n    Eigen::VectorXd b(numberOfReactions * 2);\n    Eigen::VectorXd lb(numberOfReactions);\n    Eigen::VectorXd ub(numberOfReactions);\n    std::vector<Eigen::Triplet<double>> triplets;\n    for (unsigned int i = 0; i < numberOfReactions; ++i) {\n        Reaction *reaction = model->getReaction(i);\n        FbcReactionPlugin *fluxBalanceConstraintsPlugin = dynamic_cast<FbcReactionPlugin *>(reaction->getPlugin(\"fbc\"));\n        ub(i) = model->getParameter(fluxBalanceConstraintsPlugin->getUpperFluxBound())->getValue();\n        lb(i) = model->getParameter(fluxBalanceConstraintsPlugin->getLowerFluxBound())->getValue();\n        b(i) = model->getParameter(fluxBalanceConstraintsPlugin->getUpperFluxBound())->getValue();\n        b(i + numberOfReactions) = model->getParameter(fluxBalanceConstraintsPlugin->getLowerFluxBound())->getValue();\n        triplets.emplace_back(i, i, 1);\n        triplets.emplace_back(i + numberOfReactions, i, -1);\n    }\n\n    Eigen::SparseMatrix<double> C(2 * numberOfReactions, numberOfReactions);\n    C.setFromTriplets(triplets.begin(), triplets.end());\n    return std::make_tuple(C, b, ub, lb);\n}\n\ntemplate<typename MatrixType, typename VectorType>\nhops::SbmlModel<MatrixType, VectorType> hops::SbmlReader::readModel(const std::string &file) {\n    auto document = std::unique_ptr<SBMLDocument>(readSBML(file.c_str()));\n\n    if (document->getNumErrors() > 0) {\n        std::cerr << \"Encountered the following SBML errors:\" << std::endl;\n        document->printErrors(std::cerr);\n        throw std::runtime_error(\"SBML errors.\");\n    }\n\n    Model *model = document->getModel();\n\n    if (!model) {\n        throw std::runtime_error(\"No model present.\");\n    }\n\n    SbmlModel<MatrixType, VectorType> sbmlModel;\n\n    sbmlModel.setStoichiometry(MatrixType(parseStoichiometry(model).cast<typename MatrixType::Scalar>()));\n\n    auto constraints = parseConstraints(model);\n    sbmlModel.setLowerBounds(std::get<3>(constraints).cast<typename MatrixType::Scalar>());\n    sbmlModel.setUpperBounds(std::get<2>(constraints).cast<typename MatrixType::Scalar>());\n    sbmlModel.setConstraintVector(std::get<1>(constraints).cast<typename MatrixType::Scalar>());\n    sbmlModel.setConstraintMatrix(std::get<0>(constraints).cast<typename MatrixType::Scalar>());\n\n    return sbmlModel;\n}\n\ntemplate hops::SbmlModel<Eigen::MatrixXi, Eigen::VectorXi> hops::SbmlReader::readModel(const std::string &file);\n\ntemplate hops::SbmlModel<Eigen::Matrix<long, Eigen::Dynamic, Eigen::Dynamic>, Eigen::Matrix<long, Eigen::Dynamic, 1>>\nhops::SbmlReader::readModel(const std::string &file);\n\ntemplate hops::SbmlModel<Eigen::MatrixXf, Eigen::VectorXf> hops::SbmlReader::readModel(const std::string &file);\n\ntemplate hops::SbmlModel<Eigen::MatrixXd, Eigen::VectorXd> hops::SbmlReader::readModel(const std::string &file);\n\ntemplate hops::SbmlModel<Eigen::SparseMatrix<int>, Eigen::VectorXi>\nhops::SbmlReader::readModel(const std::string &file);\n\ntemplate hops::SbmlModel<Eigen::SparseMatrix<long>, Eigen::Matrix<long, Eigen::Dynamic, 1>>\nhops::SbmlReader::readModel(const std::string &file);\n\ntemplate hops::SbmlModel<Eigen::SparseMatrix<float>, Eigen::VectorXf>\nhops::SbmlReader::readModel(const std::string &file);\n\ntemplate hops::SbmlModel<Eigen::SparseMatrix<double>, Eigen::VectorXd>\nhops::SbmlReader::readModel(const std::string &file);\n", "meta": {"hexsha": "2e221163324b6034d5393f81d64a8b3d90e50da0", "size": 5661, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/hops/FileReader/SbmlReader.cpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "include/hops/FileReader/SbmlReader.cpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "include/hops/FileReader/SbmlReader.cpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.8017241379, "max_line_length": 120, "alphanum_fraction": 0.7004062886, "num_tokens": 1397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5259455233367177}}
{"text": "#include <iostream>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <dlib/matrix.h>\n\nusing namespace std;\nusing namespace dlib;\n\n/*\nint main()\n{\n    matrix<double,32,32> input;\n    matrix<double,28,28> output;\n    matrix<double,5,5> filter;   \n    \n    double acc;\n    \n    input = 1;\n    filter = 0.1;\n    \n    for (int i=0; i<28; i++)\n    {\n        for (int j=0; j<28; j++)\n        {\n            acc = 0;\n            for (int r=0; r<5;  r++)\n            {\n                for (int k=0; k<5; k++)\n                {\n                    acc += input(i+r,j+k) * filter(r,k);\n                }\n            }\n            output(i,j) = acc/25;\n        }\n    }\n    cout << input << endl;\n    cout << output << endl; \n}\n*/\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,1,84> input;\n    matrix<double,84,10> syn, tmp_syn, tmp;\n    matrix<double,1,10> output, y, a, e, g, delta;\n    \n    for (int i=0; i<84; i++)\n        for (int j=0; j<10; j++)\n            syn(i,j) = distribution(generator);\n    \n    output(0) = 0;\n    output(1) = 1;\n    output(2) = 0;\n    output(3) = -1;\n    output(4) = 0;\n    output(5) = 1;\n    output(6) = 0;\n    output(7) = -1;\n    output(8) = 0;\n    output(9) = 1;\n    \n    input = 1;\n    \n    // Learning \n    for (int i=0; i<100000; i++)\n    {\n        y = input * syn;\n        a = 1/(1+exp(-y));\n        e = output - a;\n        g = pointwise_multiply(a,(1 - a));\n        delta = pointwise_multiply(g, e);\n        //tmp = syn;\n        //tmp_syn = trans(input) * delta;\n        //syn = tmp + tmp_syn;\n        syn += trans(input) * delta;\n    }\n    cout << syn << endl;   \n}\n\n\n", "meta": {"hexsha": "77ce4cfed94e8df2252876c90c10911aa86b103e", "size": 1708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dlib_examples/convolution_layer.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/convolution_layer.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/convolution_layer.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": 19.8604651163, "max_line_length": 66, "alphanum_fraction": 0.456088993, "num_tokens": 537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5258761564902243}}
{"text": "#include <iostream>\n#include <mtl/mtl.h>\n#include <mtl/dense1D.h>\n\nusing namespace mtl;\n\n/*\n  example output:\n\n  5\n\n  */\n\nint\nmain()\n{\n  //begin\n  mtl::dense1D<float> x(10, 0.0);\n  x[5] = 1.0;\n  int i = max_index(x);\n  std::cout << i << std::endl;\n  //end\n  return 0;\n}\n\n", "meta": {"hexsha": "2e210545e8632bb9b81bb8542a400bb392aa5e07", "size": 271, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/vec_max_index.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/tools/mtl-2.0/contrib/examples/vec_max_index.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/tools/mtl-2.0/contrib/examples/vec_max_index.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": 10.4230769231, "max_line_length": 33, "alphanum_fraction": 0.5645756458, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5258481246659813}}
{"text": "#include \"conex/block_triangular_operations.h\"\n#include \"conex/supernodal_solver.h\"\n\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\nnamespace conex {\n\nusing Eigen::MatrixXd;\nusing T = TriangularMatrixOperations;\nusing B = BlockTriangularOperations;\n\nvoid RunningIntersectionClosure(std::vector<Clique>* path) {\n  if (path->size() < 2) {\n    return;\n  }\n  int n = path->size();\n  for (int i = 0; i < n - 2; i++) {\n    for (int j = n - 1; j > i + 1; j--) {\n      std::vector<int> temp;\n      IntersectionOfSorted(path->at(i), path->at(j), &temp);\n      if (temp.size() == 0) {\n        continue;\n      }\n      for (int k = j - 1; k > i; k--) {\n        path->at(k) = UnionOfSorted(path->at(k), temp);\n      }\n    }\n  }\n}\n\nstd::vector<int> ResidualSize(std::vector<Clique>& path) {\n  std::vector<int> y;\n  for (size_t j = 0; j < path.size() - 1; j++) {\n    std::vector<int> temp;\n    IntersectionOfSorted(path.at(j), path.at(j + 1), &temp);\n    y.push_back(path.at(j).size() - temp.size());\n  }\n  y.push_back(path.back().size());\n  return y;\n}\n\nSparseTriangularMatrix MakeSparseTriangularMatrix(\n    int N, const std::vector<Clique>& path_) {\n  auto path = path_;\n  Sort(&path);\n  RunningIntersectionClosure(&path);\n  auto supernode_size = ResidualSize(path);\n  return SparseTriangularMatrix(N, path, supernode_size);\n}\n\nSparseTriangularMatrix GetFillInPattern(\n    int N, const std::vector<Clique>& cliques_input) {\n  auto mat = MakeSparseTriangularMatrix(N, cliques_input);\n\n  for (int j = static_cast<int>(mat.path.size()) - 1; j >= 0; j--) {\n    // Initialize columns of super nodes.\n    mat.supernodes.at(j).setConstant(1);\n    mat.separator.at(j).setConstant(1);\n\n    // Update other columns: the (seperator, seperator) components.\n    int index = 0;\n    auto s_s = mat.workspace_.seperator_diagonal.at(j);\n    int n = mat.path.at(j).size();\n    for (int i = mat.supernode_size.at(j); i < n; i++) {\n      for (int k = i; k < n; k++) {\n        *s_s.at(index++) += 1;\n      }\n    }\n  }\n  return mat;\n}\n\nSparseTriangularMatrix RandomSparseMatrix(\n    int N, const std::vector<Clique>& cliques_input) {\n  auto mat = MakeSparseTriangularMatrix(N, cliques_input);\n\n  for (int j = static_cast<int>(mat.path.size()) - 1; j >= 0; j--) {\n    // Initialize columns of super nodes.\n    int r = mat.supernodes.at(j).rows();\n    int c = mat.supernodes.at(j).cols();\n    mat.supernodes.at(j) = MatrixXd::Random(r, c);\n    r = mat.separator.at(j).rows();\n    c = mat.separator.at(j).cols();\n    mat.separator.at(j) = MatrixXd::Random(r, c);\n  }\n  return mat;\n}\n\nint GetMax(const std::vector<Clique>& cliques) {\n  int max = cliques.at(0).at(0);\n  for (const auto& c : cliques) {\n    for (const auto ci : c) {\n      if (ci > max) {\n        max = ci;\n      }\n    }\n  }\n  return max;\n}\n\nvoid DoCholeskyTest(const std::vector<Clique>& cliques) {\n  auto mat = GetFillInPattern(GetMax(cliques) + 1, cliques);\n  for (auto& sn : mat.supernodes) {\n    sn.diagonal().array() += 100;\n  }\n\n  Eigen::MatrixXd x = T::ToDense(mat);\n  Eigen::LLT<MatrixXd> llt(x);\n  MatrixXd L = llt.matrixL();\n  EXPECT_TRUE(llt.info() == Eigen::Success);\n\n  B::BlockCholeskyInPlace(&mat.workspace_);\n  MatrixXd error = T::ToDense(mat) - L;\n  error = error.triangularView<Eigen::Lower>();\n  EXPECT_NEAR(error.norm(), 0, 1e-12);\n}\n\nGTEST_TEST(LowerTri, Cholesky) {\n  DoCholeskyTest({{0, 1, 2}, {2}});\n  DoCholeskyTest({{0, 1, 2, 4, 7}, {3, 4}, {5, 6, 7}});\n  DoCholeskyTest({{0, 1, 5}, {1, 2, 5}, {3, 4, 5}});\n  DoCholeskyTest({{0, 1, 2}, {1, 2, 3}, {3, 4, 2}});\n  DoCholeskyTest({{0, 1}, {2, 4}, {3, 4}, {5, 6, 7}, {7, 8, 9, 10}});\n}\n\nvoid DoInverseTest(const std::vector<Clique>& cliques) {\n  auto mat = GetFillInPattern(GetMax(cliques) + 1, cliques);\n  for (auto& sn : mat.supernodes) {\n    sn.diagonal().array() += 10;\n  }\n\n  Eigen::MatrixXd L = T::ToDense(mat).triangularView<Eigen::Lower>();\n  Eigen::VectorXd b;\n  b.setLinSpaced(L.rows(), -1, 1);\n\n  Eigen::VectorXd y2 = b;\n  B::ApplyBlockInverseInPlace(mat.workspace_, &y2);\n  EXPECT_NEAR((L * y2 - b).norm(), 0, 1e-12);\n}\n\nGTEST_TEST(LowerTri, InverseTest) {\n  DoInverseTest({{0, 1, 2, 3}, {3, 4, 5}});\n  DoInverseTest({{0, 1, 2, 3}});\n  DoInverseTest({{0, 1, 2, 3}, {3, 4}, {4, 5, 6}});\n}\n\nvoid DoInverseOfTransposeTest(const std::vector<Clique>& cliques) {\n  auto mat = GetFillInPattern(GetMax(cliques) + 1, cliques);\n  for (auto& sn : mat.supernodes) {\n    sn.diagonal().array() += 10;\n  }\n\n  Eigen::MatrixXd L = T::ToDense(mat).triangularView<Eigen::Lower>();\n  Eigen::VectorXd b;\n  b.setLinSpaced(L.rows(), -1, 1);\n\n  Eigen::VectorXd y2 = b;\n  B::ApplyBlockInverseOfTransposeInPlace(mat.workspace_, &y2);\n  EXPECT_NEAR((L.transpose() * y2 - b).norm(), 0, 1e-12);\n}\n\nGTEST_TEST(LowerTri, InverseOfTranspose) {\n  DoInverseOfTransposeTest({{0, 1, 2, 5}, {3, 4, 5}});\n  DoInverseOfTransposeTest({{0, 1, 2, 5}, {3, 4, 5}, {5, 6}});\n  DoInverseOfTransposeTest({{0, 1, 2, 3}});\n}\n\nMatrixXd Submatrix(const MatrixXd& T, const Clique& c) {\n  MatrixXd y(c.size(), c.size());\n  int i = 0;\n  for (auto ci : c) {\n    int j = 0;\n    for (auto cj : c) {\n      y(i, j) = T(ci, cj);\n      j++;\n    }\n    i++;\n  }\n  return y;\n}\n\nvoid DoLDLTTest(bool diagonal, const std::vector<Clique>& cliques) {\n  auto mat = GetFillInPattern(GetMax(cliques) + 1, cliques);\n\n  // Set to identity.\n  for (auto& sn : mat.workspace_.diagonal) {\n    if (diagonal) {\n      sn.setZero();\n    }\n    int n = sn.diagonal().size();\n    for (int i = 0; i < n; i++) {\n      sn.diagonal()(i) = -101 + i * 100;\n    }\n  }\n\n  if (diagonal) {\n    for (auto& sn : mat.workspace_.off_diagonal) {\n      sn.setZero();\n    }\n  }\n\n  Eigen::MatrixXd X = T::ToDense(mat).selfadjointView<Eigen::Lower>();\n\n  std::vector<Eigen::RLDLT<Eigen::Ref<MatrixXd>>> factorization;\n  B::BlockLDLTInPlace(&mat.workspace_, &factorization);\n\n  Eigen::VectorXd z = Eigen::VectorXd::Random(X.cols());\n  z.setConstant(0);\n  z(1) = 1;\n\n  Eigen::VectorXd y = X * z;\n  // X = M D M ^T z = y\n  // z = inv(M^{T}) (MD)^{-1} y\n  B::ApplyBlockInverseOfMD(mat.workspace_, factorization, &y);\n  B::ApplyBlockInverseOfMTranspose(mat.workspace_, factorization, &y);\n  EXPECT_NEAR((z - y).norm(), 0, 1e-12);\n}\n\nGTEST_TEST(LowerTri, LDLT) {\n  bool diagonal = true;\n  DoLDLTTest(diagonal, {{0, 1}});\n  DoLDLTTest(diagonal, {{0, 1, 2}, {2}});\n  DoLDLTTest(diagonal, {{0, 1, 2, 4, 7}, {3, 4}, {5, 6, 7}});\n  DoLDLTTest(diagonal, {{0, 1, 5}, {1, 2, 5}, {3, 4, 5}});\n  DoLDLTTest(diagonal, {{0, 1, 2}, {1, 2, 3}, {3, 4, 2}});\n  DoLDLTTest(diagonal, {{0, 1}, {2, 4}, {3, 4}, {5, 6, 7}, {7, 8, 9, 10}});\n\n  diagonal = false;\n  DoLDLTTest(diagonal, {{0, 1, 2}, {2}});\n  DoLDLTTest(diagonal, {{0, 1, 2, 4, 7}, {3, 4}, {5, 6, 7}});\n  DoLDLTTest(diagonal, {{0, 1, 5}, {1, 2, 5}, {3, 4, 5}});\n  DoLDLTTest(diagonal, {{0, 1, 2}, {1, 2, 3}, {3, 4, 2}});\n  DoLDLTTest(diagonal, {{0, 1}, {2, 4}, {3, 4}, {5, 6, 7}, {7, 8, 9, 10}});\n}\n\n}  // namespace conex\n", "meta": {"hexsha": "1277cffdf6bea531877aac8c568a20560c023b4b", "size": 6867, "ext": "cc", "lang": "C++", "max_stars_repo_path": "conex/test/block_triangular_operations_test.cc", "max_stars_repo_name": "frankpermenter/conex", "max_stars_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T20:41:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T20:41:20.000Z", "max_issues_repo_path": "conex/test/block_triangular_operations_test.cc", "max_issues_repo_name": "frankpermenter/conex", "max_issues_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conex/test/block_triangular_operations_test.cc", "max_forks_repo_name": "frankpermenter/conex", "max_forks_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_forks_repo_licenses": ["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.8529411765, "max_line_length": 75, "alphanum_fraction": 0.5956021552, "num_tokens": 2477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5258481091206464}}
{"text": "#include \"Sin.hh\"\n#include \"TypesFunctions.hh\"\n#include <Eigen/Core>\n\n/**\n * @brief Constructor.\n */\nSin::Sin() {\n    transformation_(\"sin\")\n        .input(\"points\")\n\t.output(\"result\")\n\t.types(TypesFunctions::ifPoints<0>, TypesFunctions::pass<0>)\n\t.func(&Sin::calculate)\n      ;\n}\n\nSin::Sin(OutputDescriptor& output) : Sin() {\n    transformations.front().inputs.front().connect(output);\n}\n\n/**\n * @brief Calculate the value of function.\n */\nvoid Sin::calculate(FunctionArgs& fargs){\n    fargs.rets[0].x = fargs.args[0].x.sin();\n}\n\n", "meta": {"hexsha": "63f345d1b17fe1a05f908f1037e754d4a23fc888", "size": 531, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/functions/Sin.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/functions/Sin.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/functions/Sin.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.9642857143, "max_line_length": 61, "alphanum_fraction": 0.6440677966, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5257814108297025}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2019 - 2021 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n#include \"ibtk/FEMapping.h\"\n#include \"ibtk/libmesh_utilities.h\"\n\n#include \"tbox/Utilities.h\"\n\n#include \"libmesh/dense_matrix.h\"\n#include \"libmesh/elem.h\"\n#include \"libmesh/enum_elem_type.h\"\n#include \"libmesh/enum_fe_family.h\"\n#include \"libmesh/enum_order.h\"\n#include \"libmesh/enum_quadrature_type.h\"\n#include \"libmesh/type_vector.h\"\n#include <libmesh/libmesh_version.h>\n#include <libmesh/point.h>\n#include <libmesh/quadrature.h>\n\n#include <Eigen/Dense>\n\n#include <algorithm>\n#include <cmath>\n#include <memory>\n\n#include \"ibtk/namespaces.h\"\n\nnamespace IBTK\n{\n//\n// Helper functions\n//\ntemplate <int dim, int spacedim>\ninline Eigen::Matrix<double, spacedim, dim>\ngetCovariant(const Eigen::Matrix<double, spacedim, dim>& contravariant)\n{\n    return contravariant * (contravariant.transpose() * contravariant).inverse();\n}\n\ntemplate <int dim>\ninline Eigen::Matrix<double, dim, dim>\ngetCovariant(const Eigen::Matrix<double, dim, dim>& contravariant)\n{\n    return contravariant.inverse().transpose();\n}\n\n//\n// PointMap\n//\n\ntemplate <int dim, int spacedim, int n_nodes>\nPointMap<dim, spacedim, n_nodes>::PointMap(const libMesh::ElemType elem_type,\n                                           const std::vector<libMesh::Point>& q_points)\n    : d_reference_q_points(q_points)\n{\n    const int n_nodes_ = n_nodes == -1 ? get_n_nodes(elem_type) : n_nodes;\n    const auto elem_order = get_default_order(elem_type);\n    d_phi.resize(n_nodes_, d_reference_q_points.size());\n    for (int i = 0; i < n_nodes_; ++i)\n    {\n        for (unsigned int q = 0; q < d_reference_q_points.size(); ++q)\n        {\n            using FE = libMesh::FE<dim, libMesh::LAGRANGE>;\n            d_phi(i, q) = FE::shape(elem_type, elem_order, i, d_reference_q_points[q]);\n        }\n    }\n}\n\ntemplate <int dim, int spacedim, int n_nodes>\nvoid\nPointMap<dim, spacedim, n_nodes>::getMappedQuadraturePoints(const libMesh::Point* nodes,\n                                                            const libMesh::Point* nodes_end,\n                                                            std::vector<libMesh::Point>& physical_q_points)\n{\n    if (n_nodes != -1) TBOX_ASSERT(nodes_end - nodes == n_nodes);\n    const int n_nodes_ = n_nodes == -1 ? nodes_end - nodes : n_nodes;\n    TBOX_ASSERT(d_reference_q_points.size() == physical_q_points.size());\n    TBOX_ASSERT(n_nodes_ == d_phi.rows());\n    // assumes same node ordering in the input node array as is stored in d_phi\n    for (unsigned int q = 0; q < d_reference_q_points.size(); ++q)\n    {\n        physical_q_points[q] = 0.0;\n        for (int i = 0; i < n_nodes_; ++i)\n        {\n            for (int d = 0; d < spacedim; ++d)\n            {\n                physical_q_points[q](d) += d_phi(i, q) * nodes[i](d);\n            }\n        }\n    }\n}\n\n//\n// QuadratureData\n//\n\nQuadratureData::QuadratureData(const QuadratureData::key_type quad_key) : d_key(quad_key)\n{\n    const ElemType elem_type = std::get<0>(d_key);\n    const QuadratureType quad_type = std::get<1>(d_key);\n    const Order order = std::get<2>(d_key);\n\n    const int dim = get_dim(elem_type);\n\n    std::unique_ptr<QBase> quad_rule = QBase::build(quad_type, dim, order);\n    quad_rule->init(elem_type);\n    d_points = quad_rule->get_points();\n    d_weights = quad_rule->get_weights();\n}\n\n//\n// FEMapping\n//\n\ntemplate <>\nstd::unique_ptr<FEMapping<2, 2> >\nFEMapping<2, 2>::build(const key_type key, const FEUpdateFlags update_flags)\n{\n    switch (std::get<0>(key))\n    {\n    case libMesh::ElemType::TRI3:\n        return std::unique_ptr<FEMapping<2, 2> >(new Tri3Mapping(key, update_flags));\n    case libMesh::ElemType::TRI6:\n        return std::unique_ptr<FEMapping<2, 2> >(new Tri6Mapping(key, update_flags));\n    case libMesh::ElemType::QUAD4:\n        return std::unique_ptr<FEMapping<2, 2> >(new Quad4Mapping(key, update_flags));\n    case libMesh::ElemType::QUAD9:\n        return std::unique_ptr<FEMapping<2, 2> >(new Quad9Mapping(key, update_flags));\n    default:\n        return std::unique_ptr<FEMapping<2, 2> >(new FELagrangeMapping<2, 2>(key, std::get<0>(key), update_flags));\n    }\n\n    return {};\n}\n\ntemplate <>\nstd::unique_ptr<FEMapping<3, 3> >\nFEMapping<3, 3>::build(const key_type key, const FEUpdateFlags update_flags)\n{\n    switch (std::get<0>(key))\n    {\n    case libMesh::ElemType::TET4:\n        return std::unique_ptr<FEMapping<3, 3> >(new Tet4Mapping(key, update_flags));\n    case libMesh::ElemType::TET10:\n        return std::unique_ptr<FEMapping<3, 3> >(new Tet10Mapping(key, update_flags));\n    case libMesh::ElemType::HEX8:\n        return std::unique_ptr<FEMapping<3, 3> >(\n            new FELagrangeMapping<3, 3, 8>(key, libMesh::ElemType::HEX8, update_flags));\n    case libMesh::ElemType::HEX27:\n        return std::unique_ptr<FEMapping<3, 3> >(new Hex27Mapping(key, update_flags));\n    default:\n        return std::unique_ptr<FEMapping<3, 3> >(new FELagrangeMapping<3, 3>(key, std::get<0>(key), update_flags));\n    }\n\n    return {};\n}\n\ntemplate <int dim, int spacedim>\nstd::unique_ptr<FEMapping<dim, spacedim> >\nFEMapping<dim, spacedim>::build(const key_type key, const FEUpdateFlags update_flags)\n{\n    return std::unique_ptr<FEMapping<dim, spacedim> >(\n        new FELagrangeMapping<dim, spacedim>(key, std::get<0>(key), update_flags));\n}\n\n//\n// FENodalMapping\n//\n\ntemplate <int dim, int spacedim, int n_nodes>\nFENodalMapping<dim, spacedim, n_nodes>::FENodalMapping(\n    const typename FENodalMapping<dim, spacedim, n_nodes>::key_type quad_key,\n    const libMesh::ElemType element_mapping_type,\n    const FEUpdateFlags update_flags)\n    : d_quadrature_data(quad_key), d_point_map(element_mapping_type, d_quadrature_data.d_points)\n{\n    d_update_flags = update_flags;\n\n    // make sure dependencies are satisfied. These dependencies are only true\n    // for Lagrange-type mappings.\n    {\n        if (d_update_flags | FEUpdateFlags::update_JxW) d_update_flags |= update_jacobians;\n\n        if (d_update_flags | FEUpdateFlags::update_jacobians) d_update_flags |= update_contravariants;\n\n        if (d_update_flags | FEUpdateFlags::update_covariants) d_update_flags |= update_contravariants;\n    }\n\n    if (d_update_flags | FEUpdateFlags::update_contravariants) d_contravariants.resize(this->d_quadrature_data.size());\n    if (d_update_flags | FEUpdateFlags::update_covariants) d_covariants.resize(this->d_quadrature_data.size());\n\n    if (d_update_flags | FEUpdateFlags::update_jacobians) d_Jacobians.resize(this->d_quadrature_data.size());\n\n    if (d_update_flags | FEUpdateFlags::update_JxW) d_JxW.resize(this->d_quadrature_data.size());\n\n    if (d_update_flags | FEUpdateFlags::update_quadrature_points)\n        d_quadrature_points.resize(this->d_quadrature_data.size());\n}\n\ntemplate <int dim, int spacedim, int n_nodes>\nvoid\nFENodalMapping<dim, spacedim, n_nodes>::reinit(const libMesh::Elem* elem)\n{\n    if (d_update_flags & FEUpdateFlags::update_contravariants || d_update_flags & FEUpdateFlags::update_covariants)\n        this->fillTransforms(elem);\n    if (d_update_flags & FEUpdateFlags::update_jacobians) this->fillJacobians();\n    if (d_update_flags & FEUpdateFlags::update_JxW) this->fillJxW();\n    if (d_update_flags & FEUpdateFlags::update_quadrature_points) this->fillQuadraturePoints(elem);\n}\n\ntemplate <int dim, int spacedim, int n_nodes>\nbool\nFENodalMapping<dim, spacedim, n_nodes>::isAffine() const\n{\n    return false;\n}\n\ntemplate <int dim, int spacedim, int n_nodes>\nvoid\nFENodalMapping<dim, spacedim, n_nodes>::fillJacobians()\n{\n    for (unsigned int q = 0; q < d_contravariants.size(); ++q)\n    {\n        if (dim == spacedim)\n        {\n            d_Jacobians[q] = d_contravariants[q].determinant();\n        }\n        else\n        {\n            Eigen::Matrix<double, dim, dim> Jac = d_contravariants[q].transpose() * d_contravariants[q];\n            d_Jacobians[q] = std::sqrt(Jac.determinant());\n        }\n        TBOX_ASSERT(d_Jacobians[q] > 0.0);\n\n        if (isAffine()) break;\n    }\n\n    if (isAffine()) std::fill(d_Jacobians.begin() + 1, d_Jacobians.end(), d_Jacobians[0]);\n\n    return;\n}\n\ntemplate <int dim, int spacedim, int n_nodes>\nvoid\nFENodalMapping<dim, spacedim, n_nodes>::fillJxW()\n{\n    for (unsigned int q = 0; q < d_Jacobians.size(); ++q) d_JxW[q] = d_quadrature_data.d_weights[q] * d_Jacobians[q];\n}\n\ntemplate <int dim, int spacedim, int n_nodes>\nvoid\nFENodalMapping<dim, spacedim, n_nodes>::fillQuadraturePoints(const libMesh::Elem* elem)\n{\n    libMesh::Point nodes[27];\n\n    // We occasionally (e.g., TET10 and TET4) want to call the lower-order\n    // mapping from the higher-order mapping, so permit elements with more\n    // nodes in that code\n    if (n_nodes != -1) TBOX_ASSERT(n_nodes <= static_cast<int>(elem->n_nodes()));\n    const int n_nodes_ = n_nodes == -1 ? elem->n_nodes() : n_nodes;\n    TBOX_ASSERT(n_nodes_ <= 27);\n    for (int node_n = 0; node_n < n_nodes_; ++node_n)\n    {\n        nodes[node_n] = static_cast<const libMesh::Point&>(*elem->node_ptr(node_n));\n    }\n\n    d_point_map.getMappedQuadraturePoints(std::begin(nodes), std::begin(nodes) + n_nodes_, d_quadrature_points);\n}\n\n//\n// FELagrangeMapping\n//\n\ntemplate <int dim, int spacedim, int n_nodes>\nFELagrangeMapping<dim, spacedim, n_nodes>::FELagrangeMapping(\n    const typename FELagrangeMapping<dim, spacedim, n_nodes>::key_type quad_key,\n    const libMesh::ElemType element_mapping_type,\n    const FEUpdateFlags update_flags)\n    : FENodalMapping<dim, spacedim, n_nodes>(quad_key, element_mapping_type, update_flags),\n      d_n_nodes(n_nodes == -1 ? get_n_nodes(std::get<0>(quad_key)) : n_nodes)\n{\n    if (n_nodes != -1) TBOX_ASSERT(d_n_nodes == n_nodes);\n#if LIBMESH_VERSION_LESS_THAN(1, 4, 0)\n    TBOX_ASSERT(d_n_nodes <= 27);\n#else\n    TBOX_ASSERT(d_n_nodes <= static_cast<int>(libMesh::Elem::max_n_nodes));\n#endif\n    typename decltype(d_dphi)::extent_gen extents;\n    d_dphi.resize(extents[d_n_nodes][this->d_quadrature_data.size()]);\n\n    for (int node_n = 0; node_n < d_n_nodes; ++node_n)\n    {\n        for (unsigned int q = 0; q < this->d_quadrature_data.size(); ++q)\n        {\n            for (unsigned int d = 0; d < dim; ++d)\n                d_dphi[node_n][q][d] =\n                    libMesh::FE<dim, libMesh::LAGRANGE>::shape_deriv(element_mapping_type,\n                                                                     get_default_order(element_mapping_type),\n                                                                     node_n,\n                                                                     d,\n                                                                     this->d_quadrature_data.d_points[q]);\n        }\n    }\n}\n\ntemplate <int dim, int spacedim, int n_nodes>\nvoid\nFELagrangeMapping<dim, spacedim, n_nodes>::fillTransforms(const libMesh::Elem* elem)\n{\n    TBOX_ASSERT(this->d_update_flags & FEUpdateFlags::update_contravariants);\n    TBOX_ASSERT(d_n_nodes <= static_cast<int>(elem->n_nodes()));\n\n    // max_n_nodes is a constant defined by libMesh - currently 27\n#if LIBMESH_VERSION_LESS_THAN(1, 4, 0)\n    double xs[27][spacedim];\n#else\n    double xs[libMesh::Elem::max_n_nodes][spacedim];\n#endif\n\n    const int n_nodes_ = n_nodes == -1 ? d_n_nodes : n_nodes;\n    for (int i = 0; i < n_nodes_; ++i)\n    {\n        const libMesh::Point p = elem->point(i);\n        for (unsigned int j = 0; j < spacedim; ++j) xs[i][j] = p(j);\n    }\n\n    for (unsigned int q = 0; q < this->d_JxW.size(); ++q)\n    {\n        auto& contravariant = this->d_contravariants[q];\n        contravariant.setZero();\n        for (int node_n = 0; node_n < n_nodes_; ++node_n)\n        {\n            for (unsigned int i = 0; i < spacedim; ++i)\n            {\n                for (unsigned int j = 0; j < dim; ++j)\n                {\n                    contravariant(i, j) += xs[node_n][i] * d_dphi[node_n][q][j];\n                }\n            }\n        }\n    }\n\n    if (this->d_update_flags & FEUpdateFlags::update_covariants)\n    {\n        for (unsigned int q = 0; q < this->d_JxW.size(); ++q)\n        {\n            this->d_covariants[q] = getCovariant(this->d_contravariants[q]);\n        }\n    }\n\n    return;\n}\n\n//\n// Tri3Mapping\n//\n\nTri3Mapping::Tri3Mapping(const key_type quad_key, const FEUpdateFlags update_flags)\n\n    : FENodalMapping<2, 2, 3>(quad_key, libMesh::TRI3, update_flags)\n{\n}\n\nvoid\nTri3Mapping::fillTransforms(const libMesh::Elem* elem)\n{\n    TBOX_ASSERT(this->d_update_flags & FEUpdateFlags::update_contravariants);\n    // also permit TRI6\n    const auto type = elem->type();\n    TBOX_ASSERT(type == libMesh::TRI3 || type == libMesh::TRI6);\n\n    const libMesh::Point p0 = elem->point(0);\n    const libMesh::Point p1 = elem->point(1);\n    const libMesh::Point p2 = elem->point(2);\n\n    Eigen::Matrix<double, 2, 2> contravariant;\n    contravariant(0, 0) = p1(0) - p0(0);\n    contravariant(0, 1) = p2(0) - p0(0);\n    contravariant(1, 0) = p1(1) - p0(1);\n    contravariant(1, 1) = p2(1) - p0(1);\n    std::fill(this->d_contravariants.begin(), this->d_contravariants.end(), contravariant);\n\n    if (this->d_update_flags & FEUpdateFlags::update_covariants)\n    {\n        const Eigen::Matrix<double, 2, 2> covariant = getCovariant(contravariant);\n        std::fill(this->d_covariants.begin(), this->d_covariants.end(), covariant);\n    }\n\n    return;\n}\n\nbool\nTri3Mapping::isAffine() const\n{\n    return true;\n}\n\n//\n// Tri6Mapping\n//\n\nTri6Mapping::Tri6Mapping(const key_type quad_key, const FEUpdateFlags update_flags)\n    : FELagrangeMapping<2, 2, 6>(quad_key, libMesh::ElemType::TRI6, update_flags), tri3_mapping(quad_key, update_flags)\n{\n}\n\nvoid\nTri6Mapping::reinit(const libMesh::Elem* elem)\n{\n    if (elem_is_affine(elem))\n    {\n        tri3_mapping.reinit(elem);\n        // If we ever add more fields to the mapping classes we will need to\n        // duplicate them here\n        std::swap(d_contravariants, tri3_mapping.d_contravariants);\n        std::swap(d_covariants, tri3_mapping.d_covariants);\n        std::swap(d_Jacobians, tri3_mapping.d_Jacobians);\n        std::swap(d_JxW, tri3_mapping.d_JxW);\n        std::swap(d_quadrature_points, tri3_mapping.d_quadrature_points);\n    }\n    else\n        FELagrangeMapping<2, 2, 6>::reinit(elem);\n}\n\nbool\nTri6Mapping::elem_is_affine(const libMesh::Elem* elem)\n{\n    std::array<libMesh::Point, 6> nodes;\n    for (unsigned int n = 0; n < nodes.size(); ++n) nodes[n] = elem->node_ref(n);\n\n    // try to determine the size of the coordinates to use as the tolerance.\n    double characteristic_point_size = 0.0;\n    for (int d = 0; d < LIBMESH_DIM; ++d)\n    {\n        characteristic_point_size += std::abs(nodes[0](d));\n        characteristic_point_size += std::abs(nodes[4](d));\n    }\n    const double tol = 1e-16 * characteristic_point_size;\n\n    return nodes[3].absolute_fuzzy_equals(0.5 * (nodes[0] + nodes[1]), tol) &&\n           nodes[4].absolute_fuzzy_equals(0.5 * (nodes[1] + nodes[2]), tol) &&\n           nodes[5].absolute_fuzzy_equals(0.5 * (nodes[0] + nodes[2]), tol);\n}\n\n//\n// Quad4Mapping\n//\n\nQuad4Mapping::Quad4Mapping(const key_type quad_key, const FEUpdateFlags update_flags)\n\n    : FENodalMapping<2, 2, 4>(quad_key, libMesh::QUAD4, update_flags)\n{\n}\n\nvoid\nQuad4Mapping::fillTransforms(const libMesh::Elem* elem)\n{\n    TBOX_ASSERT(this->d_update_flags & FEUpdateFlags::update_contravariants);\n    TBOX_ASSERT(elem->type() == std::get<0>(this->d_quadrature_data.d_key));\n\n    // calculate constants in Jacobians here\n    const libMesh::Point p0 = elem->point(0);\n    const libMesh::Point p1 = elem->point(1);\n    const libMesh::Point p2 = elem->point(2);\n    const libMesh::Point p3 = elem->point(3);\n\n    const double a_1 = 0.25 * (-p0(0) + p1(0) + p2(0) - p3(0));\n    const double b_1 = 0.25 * (-p0(0) - p1(0) + p2(0) + p3(0));\n    const double c_1 = 0.25 * (p0(0) - p1(0) + p2(0) - p3(0));\n    const double a_2 = 0.25 * (-p0(1) + p1(1) + p2(1) - p3(1));\n    const double b_2 = 0.25 * (-p0(1) - p1(1) + p2(1) + p3(1));\n    const double c_2 = 0.25 * (p0(1) - p1(1) + p2(1) - p3(1));\n\n    for (unsigned int i = 0; i < this->d_JxW.size(); i++)\n    {\n        // calculate Jacobians here\n        const double x = d_quadrature_data.d_points[i](0);\n        const double y = d_quadrature_data.d_points[i](1);\n\n        Eigen::Matrix<double, 2, 2>& contravariant = d_contravariants[i];\n        contravariant(0, 0) = a_1 + c_1 * y;\n        contravariant(0, 1) = b_1 + c_1 * x;\n        contravariant(1, 0) = a_2 + c_2 * y;\n        contravariant(1, 1) = b_2 + c_2 * x;\n    }\n\n    if (this->d_update_flags & FEUpdateFlags::update_covariants)\n    {\n        for (unsigned int q = 0; q < this->d_JxW.size(); ++q)\n        {\n            const auto& contravariant = this->d_contravariants[q];\n            d_covariants[q] = getCovariant(contravariant);\n        }\n    }\n\n    return;\n}\n\n//\n// Quad9Mapping\n//\n\nQuad9Mapping::Quad9Mapping(const Quad9Mapping::key_type quad_key, FEUpdateFlags update_flags)\n    : FENodalMapping<2, 2, 9>(quad_key, std::get<0>(quad_key), update_flags)\n{\n    // This code utilizes an implementation detail of\n    // QBase::tensor_product_quad where the x coordinate increases fastest to\n    // reconstruct the 1D quadrature rule\n    d_n_oned_q_points = static_cast<std::size_t>(std::round(std::sqrt(d_quadrature_data.d_points.size())));\n    TBOX_ASSERT(d_n_oned_q_points * d_n_oned_q_points == d_quadrature_data.d_points.size());\n    std::vector<libMesh::Point> oned_points(d_n_oned_q_points);\n    for (unsigned int q = 0; q < d_n_oned_q_points; ++q)\n    {\n        oned_points[q] = d_quadrature_data.d_points[q](0);\n    }\n\n    // verify that we really do have a tensor product rule\n    unsigned int q = 0;\n    for (unsigned int j = 0; j < d_n_oned_q_points; ++j)\n    {\n        for (unsigned int i = 0; i < d_n_oned_q_points; ++i)\n        {\n            TBOX_ASSERT(d_quadrature_data.d_points[q] == libMesh::Point(oned_points[i](0), oned_points[j](0)));\n            ++q;\n        }\n    }\n\n    d_phi.resize(3, d_n_oned_q_points);\n    d_dphi.resize(3, d_n_oned_q_points);\n    for (unsigned int i = 0; i < 3u; ++i)\n    {\n        for (unsigned int q = 0; q < oned_points.size(); ++q)\n        {\n            // This class orders the vertices in a different way to make\n            // writing tensor products easier: we do a left-to-right ordering\n            // 0 - 1 - 2 instead of 0 - 2 - 1.\n            constexpr int ibamr_to_libmesh_ordering[3] = { 0, 2, 1 };\n            using FE = libMesh::FE<1, libMesh::LAGRANGE>;\n            d_phi(i, q) = FE::shape(libMesh::EDGE3, libMesh::SECOND, ibamr_to_libmesh_ordering[i], oned_points[q]);\n            d_dphi(i, q) =\n                FE::shape_deriv(libMesh::EDGE3, libMesh::SECOND, ibamr_to_libmesh_ordering[i], 0, oned_points[q]);\n        }\n    }\n}\n\nvoid\nQuad9Mapping::fillTransforms(const libMesh::Elem* elem)\n{\n    TBOX_ASSERT(this->d_update_flags & FEUpdateFlags::update_contravariants);\n    TBOX_ASSERT(elem->type() == std::get<0>(this->d_quadrature_data.d_key));\n\n    constexpr std::size_t n_oned_shape_functions = 3;\n\n    // We index points in the following way:\n    //\n    // i = 2 +--+--+\n    //       |     |\n    // i = 1 +  +  +\n    //       |     |\n    // i = 0 +--+--+\n    //      j=0 1  2\n    //\n    // All 2D arrays created here are in row-major order.\n\n    double xs[n_oned_shape_functions][n_oned_shape_functions];\n    double ys[n_oned_shape_functions][n_oned_shape_functions];\n\n    libMesh::Point points[n_oned_shape_functions][n_oned_shape_functions];\n    points[0][0] = elem->point(0);\n    points[0][1] = elem->point(4);\n    points[0][2] = elem->point(1);\n    points[1][0] = elem->point(7);\n    points[1][1] = elem->point(8);\n    points[1][2] = elem->point(5);\n    points[2][0] = elem->point(3);\n    points[2][1] = elem->point(6);\n    points[2][2] = elem->point(2);\n\n    // j is the x index, i is the y index\n    for (unsigned int i = 0; i < n_oned_shape_functions; ++i)\n    {\n        for (unsigned int j = 0; j < n_oned_shape_functions; ++j)\n        {\n            xs[i][j] = points[i][j](0);\n            ys[i][j] = points[i][j](1);\n        }\n    }\n\n    for (unsigned int q = 0; q < this->d_JxW.size(); q++)\n    {\n        Eigen::Matrix<double, 2, 2>& contravariant = d_contravariants[q];\n        contravariant.setZero();\n        // Exploit the fact that Quad9 is a tensor product element by indexing\n        // the x component of each tensor product shape function with j and\n        // the y component with i\n        const unsigned int q_point_x = q % d_n_oned_q_points;\n        const unsigned int q_point_y = q / d_n_oned_q_points;\n        for (unsigned int i = 0; i < n_oned_shape_functions; ++i)\n        {\n            for (unsigned int j = 0; j < n_oned_shape_functions; ++j)\n            {\n                contravariant(0, 0) += xs[i][j] * d_dphi(j, q_point_x) * d_phi(i, q_point_y);\n                contravariant(0, 1) += xs[i][j] * d_phi(j, q_point_x) * d_dphi(i, q_point_y);\n                contravariant(1, 0) += ys[i][j] * d_dphi(j, q_point_x) * d_phi(i, q_point_y);\n                contravariant(1, 1) += ys[i][j] * d_phi(j, q_point_x) * d_dphi(i, q_point_y);\n            }\n        }\n    }\n\n    if (this->d_update_flags & FEUpdateFlags::update_covariants)\n    {\n        for (unsigned int q = 0; q < this->d_JxW.size(); ++q)\n        {\n            const auto& contravariant = this->d_contravariants[q];\n            d_covariants[q] = getCovariant(contravariant);\n        }\n    }\n\n    return;\n}\n\n//\n// Tet4Mapping\n//\n\nTet4Mapping::Tet4Mapping(const key_type quad_key, const FEUpdateFlags update_flags)\n\n    : FENodalMapping<3, 3, 4>(quad_key, libMesh::TET4, update_flags)\n{\n}\n\nvoid\nTet4Mapping::fillTransforms(const libMesh::Elem* elem)\n{\n    TBOX_ASSERT(this->d_update_flags & FEUpdateFlags::update_contravariants);\n    // also permit TET10\n    const auto type = elem->type();\n    TBOX_ASSERT(type == libMesh::TET4 || type == libMesh::TET10);\n\n    // calculate Jacobians here\n    const libMesh::Point p0 = elem->point(0);\n    const libMesh::Point p1 = elem->point(1);\n    const libMesh::Point p2 = elem->point(2);\n    const libMesh::Point p3 = elem->point(3);\n\n    Eigen::Matrix<double, 3, 3> contravariant;\n    contravariant(0, 0) = p1(0) - p0(0);\n    contravariant(0, 1) = p2(0) - p0(0);\n    contravariant(0, 2) = p3(0) - p0(0);\n    contravariant(1, 0) = p1(1) - p0(1);\n    contravariant(1, 1) = p2(1) - p0(1);\n    contravariant(1, 2) = p3(1) - p0(1);\n    contravariant(2, 0) = p1(2) - p0(2);\n    contravariant(2, 1) = p2(2) - p0(2);\n    contravariant(2, 2) = p3(2) - p0(2);\n    std::fill(d_contravariants.begin(), d_contravariants.end(), contravariant);\n\n    if (this->d_update_flags & FEUpdateFlags::update_covariants)\n    {\n        const Eigen::Matrix<double, 3, 3> covariant = getCovariant(contravariant);\n        std::fill(this->d_covariants.begin(), this->d_covariants.end(), covariant);\n    }\n\n    return;\n}\n\nbool\nTet4Mapping::isAffine() const\n{\n    return true;\n}\n\n//\n// Tet10Mapping\n//\n\nTet10Mapping::Tet10Mapping(const key_type quad_key, const FEUpdateFlags update_flags)\n    : FELagrangeMapping<3, 3, 10>(quad_key, libMesh::ElemType::TET10, update_flags),\n      tet4_mapping(quad_key, update_flags)\n{\n}\n\nvoid\nTet10Mapping::reinit(const libMesh::Elem* elem)\n{\n    if (elem_is_affine(elem))\n    {\n        tet4_mapping.reinit(elem);\n        // If we ever add more fields to the mapping classes we will need to\n        // duplicate them here\n        std::swap(d_contravariants, tet4_mapping.d_contravariants);\n        std::swap(d_covariants, tet4_mapping.d_covariants);\n        std::swap(d_Jacobians, tet4_mapping.d_Jacobians);\n        std::swap(d_JxW, tet4_mapping.d_JxW);\n        std::swap(d_quadrature_points, tet4_mapping.d_quadrature_points);\n    }\n    else\n        FELagrangeMapping<3, 3, 10>::reinit(elem);\n}\n\nbool\nTet10Mapping::elem_is_affine(const libMesh::Elem* elem)\n{\n    std::array<libMesh::Point, 10> nodes;\n    for (unsigned int n = 0; n < nodes.size(); ++n) nodes[n] = elem->node_ref(n);\n\n    // try to determine the size of the coordinates to use as the tolerance.\n    double characteristic_point_size = 0.0;\n    for (int d = 0; d < LIBMESH_DIM; ++d)\n    {\n        characteristic_point_size += std::abs(nodes[0](d));\n        characteristic_point_size += std::abs(nodes[3](d));\n    }\n    const double tol = 1e-16 * characteristic_point_size;\n\n    return nodes[4].absolute_fuzzy_equals(0.5 * (nodes[0] + nodes[1]), tol) &&\n           nodes[5].absolute_fuzzy_equals(0.5 * (nodes[1] + nodes[2]), tol) &&\n           nodes[6].absolute_fuzzy_equals(0.5 * (nodes[0] + nodes[2]), tol) &&\n           nodes[7].absolute_fuzzy_equals(0.5 * (nodes[0] + nodes[3]), tol) &&\n           nodes[8].absolute_fuzzy_equals(0.5 * (nodes[1] + nodes[3]), tol) &&\n           nodes[9].absolute_fuzzy_equals(0.5 * (nodes[2] + nodes[3]), tol);\n}\n\n//\n// Hex27Mapping\n//\n\nHex27Mapping::Hex27Mapping(const key_type quad_key, const FEUpdateFlags update_flags)\n    : FELagrangeMapping<3, 3, 27>(quad_key, libMesh::HEX27, update_flags),\n      hex8_mapping(quad_key, libMesh::HEX8, update_flags)\n{\n}\n\nvoid\nHex27Mapping::reinit(const libMesh::Elem* elem)\n{\n    if (elem_is_trilinear(elem))\n    {\n        hex8_mapping.reinit(elem);\n        // If we ever add more fields to the mapping classes we will need to\n        // duplicate them here\n        std::swap(d_contravariants, hex8_mapping.d_contravariants);\n        std::swap(d_covariants, hex8_mapping.d_covariants);\n        std::swap(d_Jacobians, hex8_mapping.d_Jacobians);\n        std::swap(d_JxW, hex8_mapping.d_JxW);\n        std::swap(d_quadrature_points, hex8_mapping.d_quadrature_points);\n    }\n    else\n        FELagrangeMapping<3, 3, 27>::reinit(elem);\n}\n\nbool\nHex27Mapping::elem_is_trilinear(const libMesh::Elem* elem)\n{\n    std::array<libMesh::Point, 27> nodes;\n    for (unsigned int n = 0; n < nodes.size(); ++n) nodes[n] = elem->node_ref(n);\n\n    // try to determine the size of the coordinates to use as the tolerance.\n    double characteristic_point_size = 0.0;\n    for (int d = 0; d < LIBMESH_DIM; ++d)\n    {\n        characteristic_point_size += std::abs(nodes[0](d));\n        characteristic_point_size += std::abs(nodes[6](d));\n    }\n    const double tol = 1e-16 * characteristic_point_size;\n\n    return\n        // line midpoints\n        nodes[8].absolute_fuzzy_equals(0.5 * (nodes[0] + nodes[1]), tol) &&\n        nodes[9].absolute_fuzzy_equals(0.5 * (nodes[1] + nodes[2]), tol) &&\n        nodes[10].absolute_fuzzy_equals(0.5 * (nodes[2] + nodes[3]), tol) &&\n        nodes[11].absolute_fuzzy_equals(0.5 * (nodes[0] + nodes[3]), tol) &&\n        nodes[12].absolute_fuzzy_equals(0.5 * (nodes[0] + nodes[4]), tol) &&\n        nodes[13].absolute_fuzzy_equals(0.5 * (nodes[1] + nodes[5]), tol) &&\n        nodes[14].absolute_fuzzy_equals(0.5 * (nodes[2] + nodes[6]), tol) &&\n        nodes[15].absolute_fuzzy_equals(0.5 * (nodes[3] + nodes[7]), tol) &&\n        nodes[16].absolute_fuzzy_equals(0.5 * (nodes[4] + nodes[5]), tol) &&\n        nodes[17].absolute_fuzzy_equals(0.5 * (nodes[5] + nodes[6]), tol) &&\n        nodes[18].absolute_fuzzy_equals(0.5 * (nodes[6] + nodes[7]), tol) &&\n        nodes[19].absolute_fuzzy_equals(0.5 * (nodes[4] + nodes[7]), tol) &&\n        // face midpoints\n        nodes[20].absolute_fuzzy_equals(0.5 * (nodes[8] + nodes[10]), tol) &&\n        nodes[21].absolute_fuzzy_equals(0.5 * (nodes[8] + nodes[16]), tol) &&\n        nodes[22].absolute_fuzzy_equals(0.5 * (nodes[9] + nodes[17]), tol) &&\n        nodes[23].absolute_fuzzy_equals(0.5 * (nodes[10] + nodes[18]), tol) &&\n        nodes[24].absolute_fuzzy_equals(0.5 * (nodes[11] + nodes[19]), tol) &&\n        nodes[25].absolute_fuzzy_equals(0.5 * (nodes[16] + nodes[18]), tol) &&\n        // cell center\n        nodes[26].absolute_fuzzy_equals(0.5 * (nodes[20] + nodes[25]), tol);\n}\n\n//\n// Instantiations\n//\n\ntemplate class FEMapping<1, 1>;\ntemplate class FEMapping<1, 2>;\ntemplate class FEMapping<1, 3>;\ntemplate class FEMapping<2, 2>;\ntemplate class FEMapping<2, 3>;\ntemplate class FEMapping<3, 3>;\n\ntemplate class FENodalMapping<1, 1>;\ntemplate class FENodalMapping<1, 2>;\ntemplate class FENodalMapping<1, 3>;\ntemplate class FENodalMapping<2, 2>;\ntemplate class FENodalMapping<2, 3>;\ntemplate class FENodalMapping<3, 3>;\n\ntemplate class FELagrangeMapping<1, 1>;\ntemplate class FELagrangeMapping<1, 2>;\ntemplate class FELagrangeMapping<1, 3>;\ntemplate class FELagrangeMapping<2, 2>;\ntemplate class FELagrangeMapping<2, 3>;\ntemplate class FELagrangeMapping<3, 3>;\n\ntemplate class FELagrangeMapping<2, 2, 6>;\ntemplate class FELagrangeMapping<3, 3, 10>;\n\ntemplate class FENodalMapping<2, 2, 3>;\ntemplate class FENodalMapping<2, 2, 4>;\ntemplate class FENodalMapping<2, 2, 6>;\ntemplate class FENodalMapping<2, 2, 9>;\ntemplate class FENodalMapping<3, 3, 4>;\n\n} // namespace IBTK\n", "meta": {"hexsha": "9c1221709e10b031f4af9056d8e49cd73a9344ef", "size": 29002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ibtk/src/lagrangian/FEMapping.cpp", "max_stars_repo_name": "akashdhruv/IBAMR", "max_stars_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 264.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T12:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:10:37.000Z", "max_issues_repo_path": "ibtk/src/lagrangian/FEMapping.cpp", "max_issues_repo_name": "akashdhruv/IBAMR", "max_issues_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1057.0, "max_issues_repo_issues_event_min_datetime": "2015-04-27T04:27:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:14:59.000Z", "max_forks_repo_path": "ibtk/src/lagrangian/FEMapping.cpp", "max_forks_repo_name": "drwells/IBAMR", "max_forks_repo_head_hexsha": "0ceda3873405a35da4888c99e7d2b24d132f9071", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 126.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T15:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T21:59:50.000Z", "avg_line_length": 34.6499402628, "max_line_length": 119, "alphanum_fraction": 0.6350251707, "num_tokens": 8760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5257814006913176}}
{"text": "//\n// Created by sauron on 7/27/18.\n//\n#include \"gtest/gtest.h\"\n#include \"server/query.h\"\n#include \"source/genkey.h\"\n#include \"client/verify_intersection.h\"\n#include \"client/verify_tree.h\"\n#include <NTL/ZZ_p.h>\n#include <NTL/ZZ.h>\n#include <exception>\n\n#define SETS_NUM 2\n#define size 100\n\n\nclass IntersectionTest: public ::testing::Test{\nprotected:\n    Key *k;\n    DataStructure *dataStructure;\n    std::vector<int> v;\n    Intersection *intersection;\n    VerifyTree *verifyTree;\n    VerifyIntersection *verifyIntersection;\n    void SetUp(int intersectionSize, int sets_no) {\n        try{\n            NTL::ZZ p = NTL::conv<NTL::ZZ>(\"16798108731015832284940804142231733909759579603404752749028378864165570215949\");\n            NTL::ZZ_p::init(p);\n            k = new Key(p);\n\n            dataStructure = new DataStructure(sets_no, k);\n            for(int i = 1; i <= intersectionSize; i++) {\n                NTL::ZZ_p j = NTL::random_ZZ_p();\n                for(int set_index = 0; set_index < dataStructure->m; set_index++) {\n                    dataStructure->insert(set_index, j, k->get_public_key(), k->get_secret_key());\n                }\n            }\n            for(int set_index = 0; set_index < dataStructure->m; set_index++)\n                for(int i = 1; i <= 9*size/10; i++) {\n                    NTL::ZZ_p j = NTL::random_ZZ_p();\n                    dataStructure->insert(set_index, j, k->get_public_key(), k->get_secret_key());\n                }\n\n            for(int set_index = 0; set_index < dataStructure->m; set_index++)\n                v.push_back(set_index);\n\n            intersection = new Intersection(v, k->get_public_key(), dataStructure);\n            intersection->intersect();\n            intersection->subset_witness();\n            intersection->completeness_witness();\n            verifyTree = new VerifyTree;\n            verifyTree->verifyTree(dataStructure, v);\n            //verify intersection\n            verifyIntersection = new VerifyIntersection(k->get_public_key(), intersection->I,\n                    intersection->W, intersection->Q, dataStructure->AuthD, dataStructure->m, intersection->indices);\n        }\n        catch(std::exception& e) {\n            std::cerr << e.what() << \"\\n\";\n        }\n    }\n\n    void TearDown(){\n        delete(verifyTree);\n        delete(verifyIntersection);\n        delete(intersection);\n        delete(dataStructure);\n        delete(k);\n    }\n};\n\nTEST_F(IntersectionTest, TwoSets) {\n    SetUp(size/10, SETS_NUM);\n    bool b = verifyIntersection->verify_intersection();\n    EXPECT_TRUE(b);\n    EXPECT_TRUE(verifyIntersection->completenesswitness);\n    EXPECT_TRUE(verifyIntersection->subsetwitness);\n    EXPECT_TRUE(verifyTree->verifiedtree);\n}\n\nTEST_F(IntersectionTest, WrongsubsetWitness) {\n    SetUp(size/10, SETS_NUM);\n    *(intersection->W[0]) *= 2;\n    verifyIntersection = new VerifyIntersection(k->get_public_key(), intersection->I,\n            intersection->W, intersection->Q, dataStructure->AuthD, dataStructure->m, intersection->indices);\n    bool b = verifyIntersection->verify_intersection();\n    EXPECT_FALSE(b);\n    EXPECT_FALSE(verifyIntersection->completenesswitness);\n    EXPECT_FALSE(verifyIntersection->subsetwitness);\n    EXPECT_TRUE(verifyTree->verifiedtree);\n}\n\nTEST_F(IntersectionTest, WrongCompletenessWitness) {\n    SetUp(size/10, SETS_NUM);\n    *(intersection->Q[0]) *= 2;\n    verifyIntersection = new VerifyIntersection(k->get_public_key(), intersection->I,\n            intersection->W, intersection->Q, dataStructure->AuthD, dataStructure->m, intersection->indices);\n    bool b = verifyIntersection->verify_intersection();\n    EXPECT_FALSE(b);\n    EXPECT_FALSE(verifyIntersection->completenesswitness);\n    EXPECT_TRUE(verifyIntersection->subsetwitness);\n    EXPECT_TRUE(verifyTree->verifiedtree);\n}\n\nTEST_F(IntersectionTest, EmptyIntersection){\n    SetUp(0, SETS_NUM);\n    verifyIntersection = new VerifyIntersection(k->get_public_key(), intersection->I,\n            intersection->W, intersection->Q, dataStructure->AuthD, dataStructure->m, intersection->indices);\n    bool b = verifyIntersection->verify_intersection();\n    EXPECT_TRUE(b);\n    EXPECT_TRUE(verifyIntersection->completenesswitness);\n    EXPECT_TRUE(verifyIntersection->subsetwitness);\n    EXPECT_TRUE(verifyTree->verifiedtree);\n}\n\nTEST_F(IntersectionTest, MultipleSets){\n    SetUp(size/10, 16);\n    v.clear();\n    for(int set_index = 0; set_index < dataStructure->m; set_index+=2)\n        v.push_back(set_index);\n\n    verifyIntersection = new VerifyIntersection(k->get_public_key(), intersection->I,\n            intersection->W, intersection->Q, dataStructure->AuthD, dataStructure->m, intersection->indices);\n    bool b = verifyIntersection->verify_intersection();\n    EXPECT_TRUE(b);\n    EXPECT_TRUE(verifyIntersection->completenesswitness);\n    EXPECT_TRUE(verifyIntersection->subsetwitness);\n    EXPECT_TRUE(verifyTree->verifiedtree);\n}\n\nTEST_F(IntersectionTest, MultipleSetsEmptyResult){\n    SetUp(size/10, 16);\n    v.clear();\n    for(int set_index = 0; set_index < dataStructure->m; set_index+=2)\n        v.push_back(set_index);\n\n    verifyIntersection = new VerifyIntersection(k->get_public_key(), intersection->I,\n                                                intersection->W, intersection->Q, dataStructure->AuthD, dataStructure->m, intersection->indices);\n    bool b = verifyIntersection->verify_intersection();\n    EXPECT_TRUE(b);\n    EXPECT_TRUE(verifyIntersection->completenesswitness);\n    EXPECT_TRUE(verifyIntersection->subsetwitness);\n    EXPECT_TRUE(verifyTree->verifiedtree);\n}\n\n", "meta": {"hexsha": "7a94cd48f1171f3652c401c14e62abef4f78365b", "size": 5566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tests/intersection.cpp", "max_stars_repo_name": "mahzoun/setops", "max_stars_repo_head_hexsha": "9966c208c7ca6789a08341b03ea19051ab60861d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-11-08T14:45:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T22:06:51.000Z", "max_issues_repo_path": "test/tests/intersection.cpp", "max_issues_repo_name": "mahzoun/SetOps", "max_issues_repo_head_hexsha": "9966c208c7ca6789a08341b03ea19051ab60861d", "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/tests/intersection.cpp", "max_forks_repo_name": "mahzoun/SetOps", "max_forks_repo_head_hexsha": "9966c208c7ca6789a08341b03ea19051ab60861d", "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.3862068966, "max_line_length": 145, "alphanum_fraction": 0.6676248653, "num_tokens": 1285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5257814006913176}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2013 Alec Jacobson <alecjacobson@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 \"grad.h\"\n#include <Eigen/Geometry>\n#include <vector>\n\ntemplate <typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::grad(const Eigen::PlainObjectBase<DerivedV>&V,\n                     const Eigen::PlainObjectBase<DerivedF>&F,\n                    Eigen::SparseMatrix<typename DerivedV::Scalar> &G)\n{\n  Eigen::PlainObjectBase<DerivedV > eperp21, eperp13;\n  eperp21.resize(F.rows(),3);\n  eperp13.resize(F.rows(),3);\n\n  for (int i=0;i<F.rows();++i)\n  {\n    // renaming indices of vertices of triangles for convenience\n    int i1 = F(i,0);\n    int i2 = F(i,1);\n    int i3 = F(i,2);\n\n    // #F x 3 matrices of triangle edge vectors, named after opposite vertices\n    Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v32 = V.row(i3) - V.row(i2);\n    Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v13 = V.row(i1) - V.row(i3);\n    Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v21 = V.row(i2) - V.row(i1);\n\n    // area of parallelogram is twice area of triangle\n    // area of parallelogram is || v1 x v2 ||\n    Eigen::Matrix<typename DerivedV::Scalar, 1, 3> n  = v32.cross(v13);\n\n    // This does correct l2 norm of rows, so that it contains #F list of twice\n    // triangle areas\n    double dblA = std::sqrt(n.dot(n));\n\n    // now normalize normals to get unit normals\n    Eigen::Matrix<typename DerivedV::Scalar, 1, 3> u = n / dblA;\n\n    // rotate each vector 90 degrees around normal\n    double norm21 = std::sqrt(v21.dot(v21));\n    double norm13 = std::sqrt(v13.dot(v13));\n    eperp21.row(i) = u.cross(v21);\n    eperp21.row(i) = eperp21.row(i) / std::sqrt(eperp21.row(i).dot(eperp21.row(i)));\n    eperp21.row(i) *= norm21 / dblA;\n    eperp13.row(i) = u.cross(v13);\n    eperp13.row(i) = eperp13.row(i) / std::sqrt(eperp13.row(i).dot(eperp13.row(i)));\n    eperp13.row(i) *= norm13 / dblA;\n  }\n\n  std::vector<int> rs;\n  rs.reserve(F.rows()*4*3);\n  std::vector<int> cs;\n  cs.reserve(F.rows()*4*3);\n  std::vector<double> vs;\n  vs.reserve(F.rows()*4*3);\n\n  // row indices\n  for(int r=0;r<3;r++)\n  {\n    for(int j=0;j<4;j++)\n    {\n      for(int i=r*F.rows();i<(r+1)*F.rows();i++) rs.push_back(i);\n    }\n  }\n\n  // column indices\n  for(int r=0;r<3;r++)\n  {\n    for(int i=0;i<F.rows();i++) cs.push_back(F(i,1));\n    for(int i=0;i<F.rows();i++) cs.push_back(F(i,0));\n    for(int i=0;i<F.rows();i++) cs.push_back(F(i,2));\n    for(int i=0;i<F.rows();i++) cs.push_back(F(i,0));\n  }\n\n  // values\n  for(int i=0;i<F.rows();i++) vs.push_back(eperp13(i,0));\n  for(int i=0;i<F.rows();i++) vs.push_back(-eperp13(i,0));\n  for(int i=0;i<F.rows();i++) vs.push_back(eperp21(i,0));\n  for(int i=0;i<F.rows();i++) vs.push_back(-eperp21(i,0));\n  for(int i=0;i<F.rows();i++) vs.push_back(eperp13(i,1));\n  for(int i=0;i<F.rows();i++) vs.push_back(-eperp13(i,1));\n  for(int i=0;i<F.rows();i++) vs.push_back(eperp21(i,1));\n  for(int i=0;i<F.rows();i++) vs.push_back(-eperp21(i,1));\n  for(int i=0;i<F.rows();i++) vs.push_back(eperp13(i,2));\n  for(int i=0;i<F.rows();i++) vs.push_back(-eperp13(i,2));\n  for(int i=0;i<F.rows();i++) vs.push_back(eperp21(i,2));\n  for(int i=0;i<F.rows();i++) vs.push_back(-eperp21(i,2));\n\n  // create sparse gradient operator matrix\n  G.resize(3*F.rows(),V.rows());\n  std::vector<Eigen::Triplet<typename DerivedV::Scalar> > triplets;\n  for (int i=0;i<(int)vs.size();++i)\n  {\n    triplets.push_back(Eigen::Triplet<typename DerivedV::Scalar>(rs[i],cs[i],vs[i]));\n  }\n  G.setFromTriplets(triplets.begin(), triplets.end());\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\n// template void igl::grad<double, int>(Eigen::Matrix<double, -1, -1, 0, -1,-1> const&, Eigen::Matrix<int, -1, -1, 0, -1, -1> const&,Eigen::SparseMatrix<double, 0, int>&);\ntemplate void igl::grad<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::SparseMatrix<Eigen::Matrix<double, -1, 3, 0, -1, 3>::Scalar, 0, int>&);\n//template void igl::grad<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::SparseMatrix<Eigen::Matrix<double, -1, 3, 0, -1, 3>::Scalar, 0, int>&);\ntemplate void igl::grad<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::SparseMatrix<Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, 0, int>&);\n#endif\n", "meta": {"hexsha": "d414e90a113dbab52ffda6d16de9a30cbf21e089", "size": 4991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/include/igl/grad.cpp", "max_stars_repo_name": "FabianRepository/SinusProject", "max_stars_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "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/include/igl/grad.cpp", "max_issues_repo_name": "FabianRepository/SinusProject", "max_issues_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/include/igl/grad.cpp", "max_forks_repo_name": "FabianRepository/SinusProject", "max_forks_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "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": 44.963963964, "max_line_length": 331, "alphanum_fraction": 0.6231216189, "num_tokens": 1756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830605, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5257777538275296}}
{"text": "#pragma once\n\n#include <string>\n#include <armadillo>\n\n#include \"equationofstate/equationofstatebase.hpp\"\n\n/*!\n * \\brief Implements the Benedict-Webb-Rubin-Starling (BWRS) equation of state.\n *\n * This class implements the\n * <a href=\"https://en.wikipedia.org/wiki/Benedict%E2%80%93Webb%E2%80%93Rubin_equation#The_BWRS_equation_of_state\">Benedict-Webb-Rubin-Starling</a>\n * (BWRS) equation of state. BWRS depends on 11 mixture parameters B_0 and A_0,\n * which are calculated from the pure component parameters \\f$A_{0i}\\f$ and\n * \\f$B_{0i}\\f$, as well as the binary interaction coefficients \\f$k_{ij}\\f$.\n *\n * More information on BWRS can be found in\n * <i>Fluid Properties for Light Petroleum Systems</i>\n * (Kenneth E. Starling, 1973, ISBN 978-0872012936).\n *\n * Critical properties refer to the critical temperature (`m_Tc`), critical\n * density (`m_rhoc`), critical pressure (`m_pc`), and accentric factor (`m_w`),\n * which are used in the evaluation of the BWRS equation. These are found in\n * Table 5 at page 223 of <i>Fluid Properties for Light Petroleum Systems</i>.\n */\nclass BWRS : public EquationOfStateBase\n{\npublic:\n    /*!\n     * \\brief Constructor that uses a string to select which mixture parameters\n     * \\f$A_0\\f$ and \\f$B_0\\f$, binary interaction coefficients \\f$k_{ij}\\f$,\n     * and critical properties \\f$T_c\\f$ etc. to use. The options are \"Calsep\",\n     * \"JFH\" and \"Starling\".\n     *\n     * \"Calsep\" refers to the parameters tuned for Statpipe, see\n     * <i>Tuning af parametre i BWRS-tilstandsligningen til brug i STATPIPES termodynamiske programpakke</i>\n     * (Jan Munch, 1985) for more info.\n     *\n     * \"JFH\" refer to the parameters found in the original code by Helgaker.\n     * These have been shown to give bad results after the solver was rewritten\n     * to use molar density (the original form used regular density), so I would\n     * recommend not using this.\n     *\n     * \"Staring\" refers to the parameters given by Starling in\n     * <i>Fluid Properties for Light Petroleum Systems</i>\n     * (Kenneth E. Starling, 1973, ISBN 978-0872012936).\n     *\n     * \\param composition Gas composition fraction, in order C1, C2, C3, iC4, nC4, iC5, nC5, C6, N2, CO2.\n     * \\param parameterSet Which parameter set to use (\"Starling\", \"Calsep\" or \"JFH\").\n     * \\return An instance of BWRS.\n     */\n    BWRS(\n        const arma::vec& composition = Composition::defaultComposition,\n        const std::string& parameterSet = \"Calsep\"\n    );\n\n    /*!\n     * \\brief Explicit BWRS constructor which allows specifying which files\n     * to load mixture parameters \\f$A_0\\f$ and \\f$B_0\\f$ and binary interaction\n     * coefficients \\f$k_{ij}\\f$ from, and which critical properties to use.\n     *\n     * \\see loadJFHCriticalProperties()\n     * \\see loadCalsepCriticalProperties()\n     * \\see loadStarlingCriticalProperties()\n     *\n     * \\param composition Gas composition fractions, in order C1, C2, C3, iC4, nC4, iC5, nC5, C6, N2, CO2.\n     * \\param ABparameterFile Path to file which contains the pure component parameters \\f$A_{0i}\\f$ and \\f$B_{0i}\\f$\n     * \\param binaryInteractionTableFile Path to file which contains the interaction parameters \\f$k_{ij}\\f$\n     * \\param criticalProperties Which set of critical gas properties should be used.\n     */\n    static BWRS fromFilePaths(\n        const arma::vec& composition = Composition::defaultComposition,\n        const std::string& ABparameterFile = std::string(TRANSFLOW_RESOURCE_PATH) + \"/equationofstate/bwrs/calsepABparameters.csv\",\n        const std::string& binaryInteractionTableFile = std::string(TRANSFLOW_RESOURCE_PATH) + \"/equationofstate/bwrs/calsepBinaryInteraction.csv\",\n        const std::string& criticalProperties = \"Starling\"\n    );\n\n    /*!\n     * \\brief Evaluate the BWRS equation of state at the given pressure and temperature.\n     * \\param pressure Gas pressure [Pa]\n     * \\param temperature Gas temperature [K]\n     * \\return See EquationOfStateBase::evaluate().\n     */\n    virtual arma::vec evaluate(\n            const double pressure,\n            const double temperature) const override;\n\n    /*!\n     * \\brief Calculate the compressibility factor (Z) of the gas at a given pressure and temperature.\n     *\n     * This function is useful if we just need the compressibility and not all\n     * the other properties we can find from the EOS.\n     *\n     * It contains a call to\n     * BWRS::findMolarDensity(),\n     * which contains some Newton-Raphson root finding, which are among the\n     * heaviest part of this whole class, so I don't expect much time-save over\n     * a call to evaluate().\n     *\n     * \\param pressure Gas pressure [Pa].\n     * \\param temperature Gas temperature [K].\n     * \\return Compressibility factor Z [-].\n     */\n    virtual double calculateCompressibility(\n            const double pressure,\n            const double temperature) const override;\n\n    /*!\n     * \\brief Set the composition of the EOS.\n     *\n     * This calls EquationOfStateBase::setComposition(), then updates the non-zero\n     * component indices BWRS::m_indices, calculates the new critical pressure\n     * and temperature of the gas mixture, before finally updating all the\n     * coefficients `m_A0`, `m_B0`, through `m_GAMMA`.\n     *\n     * \\param composition New gas composition.\n     * \\param force If the composition should be changed even if it's within machine precision of the previous composition.\n     * \\return True if composition was changed, else false.\n     */\n    virtual bool setComposition(const arma::vec& composition, const bool force = true) override;\n\n    /*!\n     * \\brief loadCriticalProperties Load a set of critical properties. Either\n     * \"Calsep\", \"JFH\" or \"Starling\".\n     * \\param name Name of critical properties. Either \"Calsep\", \"JFH\" or\n     * \"Starling\".\n     */\n    void loadCriticalProperties(const std::string name);\n\n    /*!\n     * \\brief loadParametersAndCriticalProperties Load parameters and critical\n     * properties.\n     * \\param parameterSet Name of parameter set. Either \"Calsep\", \"JFH\" or\n     * \"Starling\".\n     */\n    void loadParametersAndCriticalProperties(const std::string parameterSet);\n\n    /*!\n     * \\brief Load the critical properties from Starling.\n     *\n     * This function sets the values of `m_Tc`, `m_rhoc`, `m_w`, `m_pc`,\n     * `m_molarMass`, `m_expW`, and `m_R` according to the values found in\n     * <i>Fluid Properties for Light Petroleum Systems</i>\n     * (Kenneth E. Starling, 1973, ISBN 978-0872012936).\n     *\n     * The values set by this function have been found to produce the best results.\n     */\n    void loadStarlingCriticalProperties();\n\n    /*!\n     * \\brief Load the critical properties from Helgaker.\n     *\n     * This function sets the values of `m_Tc`, `m_rhoc`, `m_w`, `m_pc`,\n     * `m_molarMass`, `m_expW`, and `m_R` according to the values found in the\n     * original Helgaker Matlab code.\n     *\n     * \\warning The values set by this function have been found to produce bad results.\n     * This is likely due to the rewrite to a molar density based solver, as\n     * the equations are originally given by Starling.\n     * Use loadStarlingCriticalProperties() instead.\n     */\n    void loadJFHCriticalProperties();\n\n    /*!\n     * \\brief Load the critical properties from the Calsep report.\n     *\n     * This function sets the values of `m_Tc`, `m_rhoc`, `m_w`, `m_pc`,\n     * `m_molarMass`, `m_expW`, and `m_R` according to the values found in the\n     * original Helgaker Matlab code.\n     *\n     * \\warning The values set by this function have been found to produce bad results.\n     * This is likely due to the rewrite to a molar density based solver, as\n     * the equations are originally given by Starling.\n     * Use loadStarlingCriticalProperties() instead.\n     */\n    void loadCalsepCriticalProperties();\n\n    /*! Load the mixture parameters \\f$A_0\\f$ and \\f$B_0\\f$, and binary\n     * interaction coefficients \\f$k_{ij}\\f$ from Gassco.\n     */\n    void loadGasscoParameters();\n\n    /*! Load the mixture parameters \\f$A_0\\f$ and \\f$B_0\\f$, and binary\n     * interaction coefficients \\f$k_{ij}\\f$ from the Calsep report.\n     */\n    void loadCalsepParameters();\n\n    /*! Load the mixture parameters \\f$A_0\\f$ and \\f$B_0\\f$, and binary\n     * interaction coefficients \\f$k_{ij}\\f$ from the Starling BWRS book.\n     */\n    void loadStarlingParameters();\n\n    /*!\n     * \\brief Load mixture parameters \\f$A_0\\f$ and \\f$B_0\\f$, and binary\n     * interaction coefficients \\f$k_{ij}\\f$ coefficients from specific files.\n     * \\param ABparameterFile Path to AB parameter file.\n     * \\param binaryInteractionTableFile Path to binary interaction coefficients file.\n     */\n    void loadParameterFiles(\n            const std::string& ABparameterFile,\n            const std::string& binaryInteractionTableFile);\n\n    //! Enable constant heat capacity \\f$c_p\\f$ and \\f$c_v\\f$\n    void enableConstantHeatCapacities();\n\n    /*!\n     * \\brief Find the gas density at a given pressure and temperature.\n     *\n     * This is just a wrapper around findMolarDensity() and a conversion from\n     * molar density [mol/m3] to density [kg/m3]\n     *\n     * \\param pressure Gas pressure [Pa].\n     * \\param temperature Gas temperature [K].\n     * \\param tolerance Newton-Raphson tolerance.\n     * \\return Gas density [kg/m3].\n     */\n    double findDensity(\n            const double pressure,\n            const double temperature,\n            const double tolerance = 1e-4) const;\n\n//    double getDerivativeOfZwrtDensityAtConstantTemperature(const double density, const double temperature) const;\n\n    double getGasConstant() const { return m_R; } //!< Get the gas constant R.\n\n    //! Get the critical pressure of the gas mixture [Pa]\n    double getMixtureCriticalPressure() const { return m_criticalPressureOfMixture; }\n\n    //! Get the critical temperature of the gas mixture [K]\n    double getMixtureCriticalTemperature() const { return m_criticalTemperatureOfMixture; }\n\nprotected:\n\n    // parameters from Starling book\n    //                      C1          C2          C3          iC4         nC4         iC5         nC5         C6          N2          CO2\n\n    //! Critical temperature [K]\n    arma::vec m_Tc        = arma::vec({ 190.69,     305.39,     369.89,     408.13,     425.19,     460.37,     469.49,     507.29,     126.15,     304.15});           // critical temperature\n    //! Critical density [kg/m3]\n    arma::vec m_rhoc      = arma::vec({ 1.00500e+4, 6.75659e+3, 4.99936e+3, 3.80118e+3, 3.92132e+3, 3.24694e+3, 3.21491e+3, 2.71673e+3, 1.10992e+4, 1.06379e+4});       // critical molar density [mol/m3]\n    //! Accentric factor [-]\n    arma::vec m_w         = arma::vec({ 0.013,      0.1018,     0.157,      0.183,      0.197,      0.226,      0.252,      0.302,      0.035,      0.21});             // accentric factor\n    //! Critical pressure [Pa]\n    arma::vec m_pc        = arma::vec({ 45.96,      48.839,     42.5,       36.48,      37.96,      33.81,      33.69,      27.34,      33.99,      73.825})*1e5;       // critical pressure\n    //! Molar mass of the different gas components [g/mol]\n    arma::vec m_molarMass = arma::vec({ 16.042,     30.068,     44.094,     58.12,      58.12,      72.146,     72.146,     86.172,     28.016,     44.01});            // [g/mol]\n    //! Exponential of the accentric factor.\n    arma::vec m_expW = exp(-3.8*m_w);\n\n    /*!\n     * \\brief The gas constant [J/(K mol)]\n     *\n     * The exact value of the gas constant is approx 8.3145 J/Kmol,\n     * but if we are using the critical properties and other parameters from\n     * Starling, these have been determined using an older definition of the\n     * gas constant, which is 8.3160 J/Kmol.\n     */\n    double m_R = 8.3160; // gas constant from Starling [m3\u2009Pa\u2009/ K\u2009mol]\n\n    /*!\n     * \\brief Binary interaction coefficients \\f$k_{ij}\\f$.\n     *\n     * The binary interaction coefficients are stored in matrix of size 10x10,\n     * where the binary interactions between component i and j are stored at\n     * location \\f$(i, j)\\f$ in the matrix. The matrix is symmetric, so\n     * \\f$k(i, j) == k(j, i)\\f$. The components are in the usual order\n     * (C1, C2, C3, iC4, nC4, iC5, nC5, C6, N2, CO2).\n     *\n     * These can be found in Table 1 at page 227 of <i>Fluid Properties for Light Petroleum Systems</i>.\n     */\n    arma::mat m_binaryInteractionParameterTable;\n\n    /*!\n     * \\brief Pure component parameters Bi.\n     *\n     * From Table 1 at page 221 of <i>Fluid Properties for Light Petroleum Systems</i>.\n     */\n    arma::vec m_Bi;\n\n    /*!\n     * \\brief Pure component parameters Ai.\n     *\n     * From Table 1 at page 221 of <i>Fluid Properties for Light Petroleum Systems</i>.\n     */\n    arma::vec m_Ai;\n\n    double m_A0; //!< A coefficient used when evaluating the BWRS-equation. Independent of pressure and temperature.\n    double m_B0; //!< A coefficient used when evaluating the BWRS-equation. Independent of pressure and temperature.\n    double m_C0; //!< A coefficient used when evaluating the BWRS-equation. Independent of pressure and temperature.\n    double m_D0; //!< A coefficient used when evaluating the BWRS-equation. Independent of pressure and temperature.\n    double m_E0; //!< A coefficient used when evaluating the BWRS-equation. Independent of pressure and temperature.\n    double m_a; //!< A coefficient used when evaluating the BWRS-equation. Independent of pressure and temperature.\n    double m_b; //!< A coefficient used when evaluating the BWRS-equation. Independent of pressure and temperature.\n    double m_c; //!< A coefficient used when evaluating the BWRS-equation. Independent of pressure and temperature.\n    double m_d; //!< A coefficient used when evaluating the BWRS-equation. Independent of pressure and temperature.\n    double m_ALPHA; //!< A coefficient used when evaluating the BWRS-equation. Independent of pressure and temperature.\n    double m_GAMMA; //!< A coefficient used when evaluating the BWRS-equation. Independent of pressure and temperature.\n\n    double m_criticalPressureOfMixture; //!< Critical pressure of the gas mixture.\n    double m_criticalTemperatureOfMixture; //!< Critical temperature of the gas mixture.\n\n    bool m_useConstantHeatCapacities = false; //!< Flag to set if we want to use constant heat capacity \\f$c_p\\f$ and \\f$c_v\\f$.\n\n    /*!\n     * \\brief Calculates all the coefficients used for evaluating BWRS that are independent of pressure and temperature.\n     *\n     * A lot of different coefficients are used when evaluating the BWRS\n     * equation to find the compressibility and the partial derivatives of Z.\n     * Many of these are independent of pressure and temperature, so they can be\n     * tabulated for the current gas composition.\n     *\n     * This optimization is most effective if we use constant composition, but\n     * should also improve the evaluation of the formulas otherwise.\n     */\n    void calculateCoefficients();\n\n    /*!\n     * \\brief Set up BWRS::m_indices to reflect which gas fractions are non-zero.\n     *\n     * The BWRS equation has some issues if it is evaluated with gas fractions\n     * of zero, so to avoid this we store the indices of the non-zero fractions\n     * and only loop over those when evaluating the equation.\n     *\n     * Call this function to find the non-zero indices and store them in BWRS::m_indices.\n     */\n    void findNonZeroComponents();\n\n    arma::uvec m_indices; //!< The indices of the non-zero gas fractions (components).\n\n    /*!\n     * \\brief Find the molar density of the gas at a given pressure and temperature.\n     *\n     * This is most likely the most computationally heavy function in this\n     * class, since it contains a Newton-Raphson root finding, meaning that the\n     * BWRS equation will be evaluated multiple times until it reaches\n     * convergence.\n     *\n     * The convergence criterion is implemented as\n     *\n     *     if (std::abs(change/previous) < tolerance) break;\n     *\n     * \\param pressure Gas pressure [Pa].\n     * \\param temperature Gas temperature [K].\n     * \\param tolerance Convergence criterion for the Newton-Raphson method.\n     * \\return Molar density [mol/m3]\n     */\n    double findMolarDensity(\n            const double pressure,\n            const double temperature,\n            const double tolerance = 1e-4) const;\n};\n", "meta": {"hexsha": "45ac94470d5228bac12c799e515549901c8278a7", "size": 16345, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/equationofstate/bwrs.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/equationofstate/bwrs.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/equationofstate/bwrs.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": 46.4346590909, "max_line_length": 202, "alphanum_fraction": 0.6657693484, "num_tokens": 4249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830605, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5257777538275296}}
{"text": "#include \"Kernel.h\"\n#include \"Solver.h\"\n#include \"SupportVectorMachine.h\"\n#include <armadillo>\n#include <assert.h>\n#include <iostream>\n\nusing namespace arma;\n\nSupportVectorMachine::SupportVectorMachine(mat x, vec y, double regParaC,\n                                             KernelType type)\n    : x{x}, y{y}, 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  this->kernel = new Kernel(type);\n  this->solver = new SmoSolver(x, y, regParaC, kernel);\n}\n\nSupportVectorMachine::~SupportVectorMachine() {\n  delete this->kernel;\n  delete this->solver;\n}\n\nuword SupportVectorMachine::ExampleNumber() { return this->x.n_rows; }\n\nint SupportVectorMachine::Train() {\n  trained = true;\n  return this->solver->Train();\n}\n\n// SVM doesn't return probablity\nint SupportVectorMachine::Predict(vec &x) {\n  if (!this->trained) {\n    std::cerr << \"This model hasn't been trained\" << std::endl;\n    return 0.0;\n  }\n  vec bias = vec(\"1\");\n  vec input = x;\n  input.insert_rows(0, bias);\n  if (this->solver->Predict(input) >= 0) {\n    return 1;\n  } else {\n    return -1;\n  }\n}\n", "meta": {"hexsha": "3f2e32d022992d3ca282b0c3c2930f58f0ac9871", "size": 1193, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/SVM/SupportVectorMachine.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/SupportVectorMachine.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/SupportVectorMachine.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": 24.3469387755, "max_line_length": 73, "alphanum_fraction": 0.6462699078, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.525777749644528}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <functional>\n#include <numeric>\n#include <cmath>\n#include <cstdlib>\n#include <time.h>\n#include <string>\n#include <tr1/unordered_map>\n#include <Eigen/Core>\n#include <random>\n\n#include \"utils.h\"\n\n#define RHO 0.95\n#define EPSILON 0.000001\n#define RATE 0.05\n\nusing namespace std;\nusing namespace Eigen;\n\ntemplate <typename T> int sgn(T val) {\n  return (T(0) < val) - (val < T(0));\n}\n\n/* General parameters of the model */\ntemplate <typename T>\nclass Param {\n\n public:\n  T var;\n\n  void Init(const int& rows, const int& cols) {\n    if (cols == 1) {\n      var = (0.6 / sqrt (rows)) * T::Random(rows, 1);\n      _del_var = T::Zero(rows, 1);\n      _del_grad = T::Zero(rows, 1);\n    }\n    var = (0.6 / sqrt (rows + cols)) * T::Random(rows, cols);\n    _del_var = T::Zero(rows, cols);\n    _del_grad = T::Zero(rows, cols);\n    _grad_sum = T::Zero(rows, cols);\n    _epsilon = EPSILON * T::Ones(rows, cols);\n  }\n\n  void AdagradUpdate(const double& rate, const T& grad) {\n    _del_grad += grad.cwiseAbs2();\n    _grad_sum += grad;\n    var -= rate * grad.cwiseQuotient(_del_grad.cwiseSqrt());\n  }\n\n  void AdagradUpdateWithL1Reg(const double& rate, const T& grad,\n                              const double& l1_reg) {\n    _update_num += 1;\n    _del_grad += grad.cwiseAbs2();\n    _grad_sum += grad;\n    for (int i = 0; i < var.rows(); ++i) {\n      for (int j = 0; j < var.cols(); ++j) {\n        double diff = abs(_grad_sum(i, j)) - _update_num * l1_reg;\n        if (diff <= 0)\n          var(i, j) = 0;\n        else\n          var(i, j) = -sgn(_grad_sum(i, j)) * rate * diff / sqrt(_del_grad(i, j));\n      }\n    }\n  }\n\n  void AdagradUpdateWithL1RegNonNeg(const double& rate, const T& grad,\n                                    const double& l1_reg) {\n    _update_num += 1;\n    _del_grad += grad.cwiseAbs2();\n    _grad_sum += grad;\n    for (int i = 0; i < var.rows(); ++i) {\n      for (int j = 0; j < var.cols(); ++j) {\n        double diff = abs(_grad_sum(i, j)) - _update_num * l1_reg;\n        if (diff <= 0)\n          var(i, j) = 0;\n        else {\n          double temp = -sgn(_grad_sum(i, j)) * rate * diff /\n                        sqrt(_del_grad(i, j));\n          if (temp >= 0) var(i, j) = temp;\n          else var(i, j) = 0;\n        }\n      }\n    }\n  }\n\n  void WriteToFile(ofstream& out) {\n    out << var.rows() << \" \" << var.cols() << \" \";\n    for (unsigned i = 0; i < var.rows(); ++i) {\n      for(unsigned j = 0; j < var.cols(); ++j) \n        out << var(i, j) << \" \";\n    }\n    out << endl;\n  }\n\n  void ReadFromFile(ifstream& in) {\n    string line;\n    getline(in, line);\n    vector<string> data = split_line(line, ' ');\n    int rows = stoi(data[0]), cols = stoi(data[1]);\n    var = T::Zero(rows, cols);\n    for (int i = 2; i < data.size(); ++i)\n      var((i-2)/cols, (i-2)%cols) = stod(data[i]);\n  }\n\n private:\n  T _del_var, _del_grad, _grad_sum;  // updates/gradient memory\n  T _epsilon;\n  int _update_num = 0;\n};\n\n/* Main class definition that learns the word vectors */\nclass Model {\n\n public:\n  /* The parameters of the model */\n  vector<Param<Col> > atom;\n  Param<Mat> dict;\n  int vec_len, factor;\n      \n  Model(const int& times, const int& vector_len, const int& vocab_len) {\n    vec_len = vector_len;\n    factor = times;\n    dict.Init(vec_len, factor * vec_len);\n    /* Params initialization */\n    for (int i = 0; i < vocab_len; ++i) {\n      Param<Col> vec;\n      vec.Init(factor * vec_len, 1);\n      atom.push_back(vec);\n    }\n  }\n\n  template<typename T> void NonLinearity(T* vec) { ElemwiseHardTanh(vec); }\n\n  void PredictVector(const Col& word_vec, const int& word_index,\n                     Col* pred_vec) {\n    *pred_vec = dict.var * atom[word_index].var;\n  }\n\n  void UpdateParams(const int& word_index, const double& rate,\n                    const Col& diff_vec, const double& l1_reg,\n                    const double& l2_reg) {\n    Mat dict_grad = -2 * diff_vec * atom[word_index].var.transpose() +\n                    2 * l2_reg * dict.var;\n    dict.AdagradUpdate(rate, dict_grad);\n    Col atom_elem_grad = -2 * dict.var.transpose() * diff_vec;\n    atom[word_index].AdagradUpdateWithL1RegNonNeg(rate, atom_elem_grad,\n                                                  l1_reg);\n  }\n\n  void WriteVectorsToFile(const string& filename,\n                          const mapUnsignedStr& vocab) {\n    ofstream outfile(filename);\n    if (outfile.is_open()) {\n      outfile.precision(3);\n      for(unsigned i = 0; i < atom.size(); ++i) {\n        auto it = vocab.find(i);\n        outfile << it->second << \" \";\n        for (unsigned j = 0; j < atom[i].var.rows(); ++j)\n          outfile << atom[i].var[j] << \" \";\n        outfile << endl;\n      }\n      outfile.close();\n      cerr << \"\\nWritten vectors to: \" << filename;\n    } else {\n      cerr << \"\\nFailed to open \" << filename;\n    }\n  }\n\n  void WriteDictToFile(const string& filename) {\n    ofstream outfile(filename);\n    if (outfile.is_open()) {\n      outfile.precision(3);\n      dict.WriteToFile(outfile);\n      outfile.close();\n      cerr << \"\\nWritten atom to: \" << filename;\n    } else {\n      cerr << \"\\nFailed to open \" << filename;\n    }\n  }\n\n};\n\nvoid Train(const string& out_file, const int& factor,\n           const int& cores, const double& l1_reg, const double& l2_reg,\n           const vector<Col>& word_vecs, const mapUnsignedStr& vocab) {\n  Model model(factor, word_vecs[0].size(), word_vecs.size());\n  double avg_error = 1, prev_avg_err = 0;\n  int iter = 0;\n  while (iter < 20 || (avg_error > 0.05 && iter < 75 && abs(avg_error - prev_avg_err) > 0.001)) {\n    iter += 1;\n    cerr << \"\\nIteration: \" << iter << endl;\n    unsigned num_words = 0;\n    double total_error = 0, atom_l1_norm = 0;\n    int word_id;\n    #pragma omp parallel num_threads(cores) shared(total_error,atom_l1_norm)\n    #pragma omp for nowait private(word_id)\n    for (int word_id = 0; word_id < word_vecs.size(); ++word_id) {\n      /* Predict the i-th word and compute error */\n      Col pred_vec;\n      model.PredictVector(word_vecs[word_id], word_id, &pred_vec);\n      Col diff_vec = word_vecs[word_id] - pred_vec;\n      double error = diff_vec.squaredNorm();\n      #pragma omp critical\n      {\n        total_error += error;\n        num_words += 1;\n        atom_l1_norm += model.atom[word_id].var.lpNorm<1>();\n        cerr << num_words << \"\\r\";\n      }\n      model.UpdateParams(word_id, RATE, diff_vec, l1_reg, l2_reg);\n    }\n    prev_avg_err = avg_error;\n    avg_error = total_error / num_words;\n    cerr << \"\\nError per example: \"<< total_error / num_words;\n    cerr << \"\\nDict L2 norm: \" << model.dict.var.lpNorm<2>();\n    cerr << \"\\nAvg Atom L1 norm: \" << atom_l1_norm / num_words;\n  }\n  model.WriteVectorsToFile(out_file, vocab);\n  model.WriteDictToFile(out_file + \"_dict\");\n}\n\nint main(int argc, char **argv) {\n  mapUnsignedStr vocab;\n  vector<Col> word_vecs;\n  if (argc == 7) {\n    string vec_corpus = argv[1];\n    int factor = stoi(argv[2]);\n    double l1_reg = stod(argv[3]), l2_reg = stod(argv[4]);\n    int num_cores = stoi(argv[5]);\n    string outfilename = argv[6];\n\n    ReadVecsFromFile(vec_corpus, &vocab, &word_vecs);\n \n    cerr << \"Model specification\" << endl;\n    cerr << \"----------------\" << endl;\n    cerr << \"Vector length: \" << word_vecs[0].size() << endl;\n    cerr << \"Dictionary length: \" << factor * word_vecs[0].size() << endl;\n    cerr << \"L2 Reg (Dict): \" << l2_reg << endl;\n    cerr << \"L1 Reg (Atom): \" << l1_reg << endl;\n    cerr << \"Number of Cores: \" << num_cores << endl;\n    cerr << \"----------------\" << endl;\n\n    Train(outfilename, factor, num_cores, l1_reg, l2_reg, word_vecs, vocab);\n  } else {\n    cerr << \"Usage: \"<< argv[0] << \" vec_corpus factor l1_reg l2_reg \"\n         << \"num_cores outfilename\\n\";\n  }\n  return 1;\n}\n", "meta": {"hexsha": "2af6ca53bc67b012f77e9018e4545018a082afb8", "size": 7763, "ext": "cc", "lang": "C++", "max_stars_repo_path": "sparse-nonneg.cc", "max_stars_repo_name": "mfaruqui/sparse-coding", "max_stars_repo_head_hexsha": "838a898df0632ccd9d1fdb51bfc985fbb1126f01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62.0, "max_stars_repo_stars_event_min_datetime": "2015-03-26T14:31:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T09:04:39.000Z", "max_issues_repo_path": "sparse-nonneg.cc", "max_issues_repo_name": "mfaruqui/sparse-coding", "max_issues_repo_head_hexsha": "838a898df0632ccd9d1fdb51bfc985fbb1126f01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-08-10T19:48:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-08T11:52:48.000Z", "max_forks_repo_path": "sparse-nonneg.cc", "max_forks_repo_name": "mfaruqui/sparse-coding", "max_forks_repo_head_hexsha": "838a898df0632ccd9d1fdb51bfc985fbb1126f01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2015-05-06T23:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-17T14:45:58.000Z", "avg_line_length": 30.6837944664, "max_line_length": 97, "alphanum_fraction": 0.5712997552, "num_tokens": 2238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5257777395994395}}
{"text": "// Copyright (c) 2012-2017 VideoStitch SAS\n// Copyright (c) 2018 stitchEm\n\n#ifndef ROTATION_ESTIMATION_HPP_\n#define ROTATION_ESTIMATION_HPP_\n\n#include \"util/lmfit/lmmin.hpp\"\n\n#include <opencv2/core/core.hpp>\n#include <Eigen/Dense>\n\nnamespace VideoStitch {\nnamespace Calibration {\n\ntypedef std::pair<Eigen::Vector3d, Eigen::Vector3d> SpherePointMatch;\ntypedef std::vector<SpherePointMatch> MatchList;\n\nclass RotationEstimationProblem : public Util::SolverProblem {\n public:\n  explicit RotationEstimationProblem(const MatchList& matchList) : matchList(matchList) {}\n\n  virtual void eval(const double* params, int m_dat, double* fvec, const char* fFilter, int /*iterationNumber*/,\n                    bool* /* requestBreak */) const {\n    Eigen::Matrix3d R;\n    for (int i = 0; i < 3; i++) {\n      for (int j = 0; j < 3; j++) {\n        R(i, j) = params[i * 3 + j];\n      }\n    }\n\n    for (auto i = 0; i < m_dat; ++i) {\n      if (!fFilter || fFilter[i]) {\n        Eigen::Vector3d rotatedPoint = (Eigen::Vector3d)(R * matchList[i].first);\n        double y = (rotatedPoint.cross(matchList[i].second)).squaredNorm();\n        double x = rotatedPoint.dot(matchList[i].second);\n        // angular distance on the sphere\n        double error = atan2(y, x);\n        fvec[i] = error;\n      } else {\n        fvec[i] = 0.0;\n      }\n    }\n  }\n\n  virtual int numParams() const { return 9; }\n\n  virtual int getNumInputSamples() const { return (int)matchList.size(); }\n\n  virtual int getNumValuesPerSample() const { return 1; }\n\n  virtual int getNumAdditionalValues() const { return 0; }\n\n  MatchList getMatchList() const { return matchList; }\n\n private:\n  MatchList matchList;\n};\n\nclass RotationEstimationSolver : public Util::Solver<RotationEstimationProblem> {\n public:\n  RotationEstimationSolver(const RotationEstimationProblem& problem, const char* const sampleFilter,\n                           bool /*debug = false*/, bool /*useFloatPrecision = false*/)\n      : Solver(problem), sampleFilter(sampleFilter) {}\n\n  virtual bool run(std::vector<double>& params) {\n    MatchList matchList = problem.getMatchList();\n    const auto numberMatches = matchList.size();\n\n    auto numberSamples = 0;\n    // First count the number of samples that will be used\n    for (uint32_t i = 0; i < numberMatches; ++i) {\n      if (!sampleFilter || sampleFilter[i]) {\n        numberSamples++;\n      }\n    }\n\n    if (numberSamples < 3) {\n      return false;\n    }\n\n    /*\n     * Estimate the optimal rotation using the selected samples\n     *\n     * Least-Squares Rigid Motion Using SVD, Olga Sorkine\n     * http://igl.ethz.ch/projects/ARAP/svd_rot.pdf\n     */\n\n    /*Build the covariance matrix*/\n    Eigen::Matrix3d M;\n    M.fill(0);\n    for (uint32_t i = 0; i < numberMatches; ++i) {\n      if (!sampleFilter || sampleFilter[i]) {\n        Eigen::Vector3d first = matchList[i].first;\n        Eigen::Vector3d second = matchList[i].second;\n\n        for (int y = 0; y < 3; y++) {\n          for (int x = 0; x < 3; x++) {\n            M(y, x) += first(y) * second(x);\n          }\n        }\n      }\n    }\n\n    Eigen::JacobiSVD<Eigen::Matrix3d> svd(M, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::Matrix3d U = svd.matrixU();\n    Eigen::Matrix3d V = svd.matrixV();\n\n    /*Make sure we create a matrix with unit determinant*/\n    double determinant = (U * V.transpose()).determinant();\n    Eigen::Matrix3d D;\n    D.setIdentity();\n    D(2, 2) = 1.0 / determinant;\n    Eigen::Matrix3d R = U * D * V.transpose();\n    rotationToParam(params, R);\n\n    return true;\n  }\n\n private:\n  void rotationToParam(std::vector<double>& params, const Eigen::Matrix3d& R) const {\n    for (auto i = 0; i < 3; ++i) {\n      for (auto j = 0; j < 3; ++j) {\n        params[i + 3 * j] = R(i, j);\n      }\n    }\n  }\n\n  const char* const sampleFilter;\n};\n\n}  // namespace Calibration\n}  // namespace VideoStitch\n\n#endif\n", "meta": {"hexsha": "dc11c991c47a236d1d17ca514c40d3360d4360da", "size": 3855, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/src/calibration/rotationEstimation.hpp", "max_stars_repo_name": "tlalexander/stitchEm", "max_stars_repo_head_hexsha": "cdff821ad2c500703e6cb237ec61139fce7bf11c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 182.0, "max_stars_repo_stars_event_min_datetime": "2019-04-19T12:38:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T16:48:20.000Z", "max_issues_repo_path": "lib/src/calibration/rotationEstimation.hpp", "max_issues_repo_name": "doymcc/stitchEm", "max_issues_repo_head_hexsha": "20693a55fa522d7a196b92635e7a82df9917c2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107.0, "max_issues_repo_issues_event_min_datetime": "2019-04-23T10:49:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T18:12:28.000Z", "max_forks_repo_path": "lib/src/calibration/rotationEstimation.hpp", "max_forks_repo_name": "doymcc/stitchEm", "max_forks_repo_head_hexsha": "20693a55fa522d7a196b92635e7a82df9917c2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2019-06-04T11:27:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T23:49:49.000Z", "avg_line_length": 28.5555555556, "max_line_length": 112, "alphanum_fraction": 0.6194552529, "num_tokens": 1068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5257777395994395}}
{"text": "/* Copyright (C) 2019-2021 Junruoyu Zheng. Home page: https://junruoyu-zheng.gitee.io/ligral\n\n    Distributed under MIT license.\n    See file LICENSE for detail or copy at https://opensource.org/licenses/MIT\n*/\n\n#include <iostream>\n#include <Eigen/Dense>\nusing Eigen::Matrix;\n\n#include \"config.h\"\n\nint main() {\n    Matrix<double, n, 1> x;\n    x << 0, 1;\n    for (int i=0; i<10; i++) {\n        double t = ((double)i)*h;\n        x = integral(f, x, h);\n        std::cout << \"t = \" << t << std::endl;\n        std::cout << x << std::endl;\n    }\n    return 0;\n}", "meta": {"hexsha": "6e253d0d81fe4d36b1a8002713b55e0abfcc0ac8", "size": 555, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/main.cc", "max_stars_repo_name": "JRY-Zheng/ligral", "max_stars_repo_head_hexsha": "0653aede95f91f76b705d8ddb619af5e05adba00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-12-03T12:32:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-20T22:17:08.000Z", "max_issues_repo_path": "code/main.cc", "max_issues_repo_name": "JRY-Zheng/ligral", "max_issues_repo_head_hexsha": "0653aede95f91f76b705d8ddb619af5e05adba00", "max_issues_repo_licenses": ["MIT"], "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/main.cc", "max_forks_repo_name": "JRY-Zheng/ligral", "max_forks_repo_head_hexsha": "0653aede95f91f76b705d8ddb619af5e05adba00", "max_forks_repo_licenses": ["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.1304347826, "max_line_length": 92, "alphanum_fraction": 0.5765765766, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5257777395994395}}
{"text": "#include <iostream>\n#include <fstream>\n#include <stdio.h>\n#include <math.h>\n#include <omp.h>\n\n#include <random>\n#include <map>\n#include <string>\n#include <iomanip>\n\n#include <unistd.h>\n#include <string>\n#include <algorithm>\n#include <random>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <boost/random.hpp>\n#include <boost/program_options.hpp>\n#include <iterator>\n#include <armadillo>\n\n#include \"Sampling_functions.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace arma;\nnamespace po = boost::program_options;\n\nint main(int argc, char *argv[])\n{\n\n\tpo::options_description desc(\"Options\");\n\tdesc.add_options()\n\t(\"M\", po::value<int>()->required(), \"No. of markers\")\n\t(\"N\", po::value<int>()->required(), \"No. of individuals\")\n\t(\"num_feat\", po::value<int>()->default_value(3), \"No. of factors\")\n\t(\"iter\", po::value<int>()->default_value(100), \"No. of Gibbs iterations\")\n\t(\"burnin\", po::value<int>()->default_value(10), \"No. burnin iterations\")\n\t(\"b0_m\", po::value<double>()->default_value(2), \"b0_m\")\n\t(\"b0_u\", po::value<double>()->default_value(2), \"b0_u\")\n\t(\"input\", po::value<std::string>()->required(),\"Input filename\")\n\t(\"out\", po::value<std::string>()->default_value(\"BayesFactors_out\"),\"Output filename\")\n\t(\"scale\", \"perform scaling\")\n\t(\"missing\", \"missing data included?\")\n\t;\n\n\tsrand(time(0));\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc,argv,desc),vm);\n\tpo::notify(vm);\n\n\tint M=vm[\"M\"].as<int>();\n\tint N=vm[\"N\"].as<int>();\n\tint num_feat=vm[\"num_feat\"].as<int>();\n\tint iter=vm[\"iter\"].as<int>();\n\tint burnin=vm[\"burnin\"].as<int>();\n\tdouble b0_m=vm[\"b0_m\"].as<double>();\n\tdouble b0_u=vm[\"b0_u\"].as<double>();\n\tstring input=vm[\"input\"].as<string>();\n\tstring output=vm[\"out\"].as<string>();\n\n\tMatrixXd X(N,M);\n\n\tint i,j,k,l,m=0;\n\tauto timenow = chrono::system_clock::to_time_t(chrono::system_clock::now());\n\tcout<<\"Started analysis!\"<<endl;\n\ttimenow = chrono::system_clock::to_time_t(chrono::system_clock::now());\n\tcout << ctime(&timenow) << endl;\n\n//Read Genotype Matrix\n\tifstream f1(input+\".X\");\n\tif (f1){\n\t\tfor (int i = 0; i < N; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < M; j++)\n\t\t\t{\n\t\t\t\tf1 >> X(i,j);\n\t\t\t\t//cout<<X(i,j)<<endl;\n\t\t\t}\n\t\t}\n\t\tf1.close();\n\t\tcout<<\"finished reading matrix X!\"<<endl;\n\t\ttimenow = chrono::system_clock::to_time_t(chrono::system_clock::now());\n\t\tcout << ctime(&timenow) << endl;\n\t}else{\n\t\tcout<<\"the \"+input+\".X\"+\" file does not exist/cannot be opened!\"<<endl;\n\t\treturn 0;\n\t}\n//Read missing data indicator matrix\n\tMatrixXd Indicator(N,M);\n\n\tif (vm.count(\"missing\")) {\n\tifstream f2(input+\".Indicator\");\n\tif (f2){\n\t\tfor (int i = 0; i < N; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < M; j++)\n\t\t\t{\n\t\t\t\tf2 >> Indicator(i,j);\n\t\t\t\t//cout<<X(i,j)<<endl;\n\t\t\t}\n\t\t}\n\t\tf2.close();\n\t\tcout<<\"finished reading matrix Indicator!\"<<endl;\n\t\ttimenow = chrono::system_clock::to_time_t(chrono::system_clock::now());\n\t\tcout << ctime(&timenow) << endl;\n\t}else{\n\t\tcout<<\"the \"+input+\".Indicator\"+\" file does not exist/cannot be opened!\"<<endl;\n\t\treturn 0;\n\t}\n\t}\n\n\t//Normalize matrix X\n\tif (vm.count(\"scale\")) {\n\t\tif (vm.count(\"missing\")) {\n\t\t\tX=X.cwiseProduct(Indicator);\n\t\t\tRowVectorXd mean = X.colwise().sum().array()/Indicator.colwise().sum().array();\n\t\t\tRowVectorXd sqsum(M);\n\t\t\tRowVectorXd sd(M);\n\t\t\tsqsum.setZero();\n\t\t\tsd.setZero();\n\t\t\t//to calculate sd I add the squared deviations only for non-missing entries as specified in the Indicator matrix\n\t\t\tfor (int j = 0; j < M; j++)\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < N; i++)\n\t\t\t\t{\n\t\t\t\t\tsqsum[j] +=pow((X(i,j)-mean[j]),2)*Indicator(i,j);\n\t\t\t\t}\n\t\t\t\tsd[j]=sqrt((sqsum[j]/(Indicator.col(j).sum() - 1)));\n\t\t\t}\n\t\t\t//Divide by sd but make sure that sd!=0\n//Should be possible to integrate following code so that only one loop through M is done\n\t\t\tfor (int j = 0; j < M; j++)\n\t\t\t{\n\t\t\t\tif (sd[j]==0){\n\t\t\t\t\tfor (int i = 0; i < N; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tX(i,j) -= mean[j];\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tfor (int i = 0; i < N; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tX(i,j) -= mean[j];\n\t\t\t\t\t\tX(i,j) /= sd[j];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}else{\n\n\t\t\tRowVectorXd mean = X.colwise().mean();\n\t\t\tRowVectorXd sd = ((X.rowwise() - mean).array().square().colwise().sum() / (X.rows() - 1)).sqrt();\n\t\t\tX = (X.rowwise() - mean).array().rowwise() / sd.array();\n\t\t}\n\t}\n\n\tdouble Xglobalmean=X.mean();\n\t//Factor analysis\n\t//Initialization of latent variables. It can be done with ML estimates. Here its done just by sampling normal deviates.\n\tMatrixXd w1_M1_sample(M,num_feat);\n\tfor (int i = 0; i < M; i++)\n\t{\n\t\tfor (int j = 0; j < num_feat; j++)\n\t\t{\n\t\t\tw1_M1_sample(i,j)=rnorm(0,1);\n\t\t}\n\n\t}\n\tMatrixXd w1_P1_sample(N,num_feat);\n\tfor (int i = 0; i < N; i++)\n\t{\n\t\tfor (int j = 0; j < num_feat; j++)\n\t\t{\n\t\t\tw1_P1_sample(i,j)=rnorm(0,1);\n\t\t}\n\n\t}\n\n\t//Initialization of hyperparameters\n\tMatrixXd WI_u(num_feat,num_feat);\n\tVectorXd mu_u(num_feat);\n\tMatrixXd lambda_u(num_feat,num_feat);\n\tVectorXd mu0_u(num_feat);\n\n\tMatrixXd WI_m(num_feat,num_feat);\n\tVectorXd mu_m(num_feat);\n\tMatrixXd lambda_m(num_feat,num_feat);\n\tVectorXd mu0_m(num_feat);\n\n\tWI_m.setIdentity();\n\tlambda_m.setIdentity();\n\tlambda_u.setIdentity();\n\tWI_u.setIdentity();\n\n\tmu_m.setZero();\n\tmu0_m.setZero();\n\tmu_u.setZero();\n\tmu0_u.setZero();\n\n\tint df_m=num_feat;\n\tint df_u=num_feat;\n\n\t//Initialization of residual variance\n\tMatrixXd epsilon_t(N,M);\n\tdouble Xm=X.mean();\n\tepsilon_t=X-w1_P1_sample*w1_M1_sample.transpose();\n\t//double sigma2_e=2;\n\tdouble sigma2_e=sample_residual_variance_gamma(epsilon_t);\n\tVectorXd sigma2_e_rowvec(N);\n\tsample_residual_row_variance_gamma(epsilon_t, sigma2_e_rowvec);\n\n\t//Intialize running means of latent variables\n\tMatrixXd Ew1_M1_sample(M,num_feat);\n\tMatrixXd Ew1_P1_sample(N,num_feat);\n\n\tEw1_M1_sample=w1_M1_sample;\n\tEw1_P1_sample=w1_P1_sample;\n\n\n\t//create folder to put output\n\tint systemRet = system(\"mkdir -p BayesFactors_out\");\n\tif(systemRet == -1){\n\t\tcout<<\"system command to create folder to place output FAILED!\"<<endl;\n\t}\n\n\t//declare filestreams for output\n\tofstream file_lambda_u;\n\tofstream file_lambda_m;\n\tofstream file_mu_u;\n\tofstream file_mu_m;\n\tofstream file_latentInd;\n\tofstream file_latentSNPs;\n\tofstream file_sigma2_e;\n\tofstream file_sigma2_e_rowvec;\n\n\tofstream file_ElatentInd;\n\tofstream file_ElatentSNPs;\n\n\t//clear files for hyper-parameters\n\tfile_lambda_m.open (\"BayesFactors_out/\"+output+\"_lambda_m.txt\");\n\tfile_lambda_u.open (\"BayesFactors_out/\"+output+\"_lambda_u.txt\");\n\tfile_mu_m.open (\"BayesFactors_out/\"+output+\"_mu_m.txt\");\n\tfile_mu_u.open (\"BayesFactors_out/\"+output+\"_mu_u.txt\");\n\tfile_sigma2_e.open (\"BayesFactors_out/\"+output+\"_sigma2_e.txt\");\n\tfile_sigma2_e_rowvec.open (\"BayesFactors_out/\"+output+\"_sigma2_e_rowvec.txt\");\n\n\tfile_lambda_u.close();\n\tfile_lambda_m.close();\n\tfile_mu_u.close();\n\tfile_mu_m.close();\n\tfile_sigma2_e.close();\n\tfile_sigma2_e_rowvec.close();\n\n\t//appending sigma2_e\n\tfile_sigma2_e.open (\"BayesFactors_out/\"+output+\"_sigma2_e.txt\", std::ios_base::app);\n\tfile_sigma2_e_rowvec.open (\"BayesFactors_out/\"+output+\"_sigma2_e_rowvec.txt\", std::ios_base::app);\n\t//appending hyper-parameters\n\tfile_lambda_m.open (\"BayesFactors_out/\"+output+\"_lambda_m.txt\", std::ios_base::app);\n\tfile_lambda_u.open (\"BayesFactors_out/\"+output+\"_lambda_u.txt\", std::ios_base::app);\n\tfile_mu_m.open (\"BayesFactors_out/\"+output+\"_mu_m.txt\", std::ios_base::app);\n\tfile_mu_u.open (\"BayesFactors_out/\"+output+\"_mu_u.txt\", std::ios_base::app);\n\n\n\t//Burnin iterations\n\tcout<<\"Starting burning \"<<burnin<<\" iterations\"<<endl;\n\tfor (int i = 0; i < burnin; i++)\n\t{\n\t\t//update residual variance\n\t\tepsilon_t=X-w1_P1_sample*w1_M1_sample.transpose();\n\t\tsigma2_e=sample_residual_variance_gamma(epsilon_t);\n\t\tsample_residual_row_variance_gamma(epsilon_t, sigma2_e_rowvec);\n\n\t\t//update SNP hyperparameters\n\t\tsample_hyper(w1_M1_sample,WI_m,b0_m,mu0_m,df_m,mu_m,lambda_m);\n\t\t//update individual hyperparameters\n\t\tsample_hyper(w1_P1_sample,WI_u,b0_u,mu0_u,df_u,mu_u,lambda_u);\n\t\t//update individual parameters\n\n\t\t//sample_ind_missing (Xglobalmean,w1_M1_sample,w1_P1_sample,Indicator,X,N,M,num_feat,lambda_u,mu_u,sigma2_e_rowvec);\n\t\t//sample_SNP_missing (Xglobalmean,w1_P1_sample,w1_M1_sample,Indicator,X,N,M,num_feat,lambda_m,mu_m,sigma2_e);\n\n\t\t//update SNP parameters\n\t\tsample_ind (Xglobalmean,w1_M1_sample,w1_P1_sample,X,N,num_feat,lambda_u,mu_u,sigma2_e_rowvec);\n\t\tsample_SNP (Xglobalmean,w1_P1_sample,w1_M1_sample,X,M,num_feat,lambda_m,mu_m,sigma2_e);\n\t\t//update rows and columns together\n\t\t//sample_ind_SNP (w1_M1_sample,w1_P1_sample, X,N,M,num_feat,lambda_u,mu_u,lambda_m,mu_m,sigma2_e);\n\n\n\t}\n\n\t//Sampling iterations\n\tcout<<\"Finished burnin, starting sampling \"<<iter<<\" iterations\" <<endl;\n\n\tfor (int i = 0; i < iter; i++)\n\t{\n\n\t\t//write out for each iteration the factors\n\t\tfile_latentInd.open (\"BayesFactors_out/\"+output+\".iter\"+to_string(i+1)+\".factors\");\n\t\tfile_latentInd << w1_P1_sample << ' ';\n\n\t\tfile_latentInd << endl;\n\t\tfile_latentInd.close();\n\n\t\t//write out for each iteration the scores\n\t\tfile_latentSNPs.open (\"BayesFactors_out/\"+output+\".iter\"+to_string(i+1)+\".scores\");\n\t\tfile_latentSNPs << w1_M1_sample << ' ';\n\n\t\tfile_latentSNPs<< endl;\n\t\tfile_latentSNPs.close();\n\n\t\t//write-out hyperparameters (covariance matrices)\n\t\t//file_lambda_m << i <<\" \";\n\t\tfor (int j = 0; j < lambda_m.rows(); j++){\n\t\t\tfile_lambda_m << lambda_m.row(j) << \" \";\n\t\t}\n\t\tfile_lambda_m<<endl;\n\t\t//file_lambda_u << i<<\" \";\n\t\tfor (int j = 0; j <lambda_u.rows(); j++){\n\t\t\tfile_lambda_u  << lambda_u.row(j) << \" \";\n\t\t}\n\t\tfile_lambda_u<<endl;\n\n\t\t//write-out hyperparameters (means)\n\t\tfor (int j = 0; j <num_feat; j++){\n\t\t\tfile_mu_m<<mu_m[j]<<\" \";\n\t\t\tfile_mu_u<<mu_u[j]<<\" \";\n\t\t}\n\t\tfile_mu_m<<endl;\n\t\tfile_mu_u<<endl;\n\n\t\t//write-out residual variance\n\t\tfile_sigma2_e<<sigma2_e<<endl;\n\n\t\tfor (int j = 0; j <sigma2_e_rowvec.rows(); j++){\n\t\t\tfile_sigma2_e_rowvec  << sigma2_e_rowvec.row(j) << \" \";\n\t\t}\n\t\tfile_sigma2_e_rowvec<<endl;\n\n\n\t\t//GIBBS UPDATES\n\t\t//update residual variance\n\t\tepsilon_t=X-w1_P1_sample*w1_M1_sample.transpose();\n\t\tsigma2_e=sample_residual_variance_gamma(epsilon_t);\n\t\tsample_residual_row_variance_gamma(epsilon_t, sigma2_e_rowvec);\n\n\t\t//update SNP hyperparameters\n\t\tsample_hyper(w1_M1_sample,WI_m,b0_m,mu0_m,df_m,mu_m,lambda_m);\n\t\t//update individual hyperparameters\n\t\tsample_hyper(w1_P1_sample,WI_u,b0_u,mu0_u,df_u,mu_u,lambda_u);\n\n\t\t//update individual parameters\n\t\tsample_ind (Xglobalmean,w1_M1_sample,w1_P1_sample,X,N,num_feat,lambda_u,mu_u,sigma2_e_rowvec);\n\t\t//sample_ind_missing (Xglobalmean,w1_M1_sample,w1_P1_sample,Indicator,X,N,M,num_feat,lambda_u,mu_u,sigma2_e_rowvec);\n\t\t//sample_SNP_missing (Xglobalmean,w1_P1_sample,w1_M1_sample,Indicator,X,N,M,num_feat,lambda_m,mu_m,sigma2_e);\n\t\t//update SNP parameters\n\t\tsample_SNP (Xglobalmean,w1_P1_sample,w1_M1_sample,X,M,num_feat,lambda_m,mu_m,sigma2_e);\n\n\t\t//running average has +1 value (1 from burnin)\n\t\tEw1_M1_sample=Ew1_M1_sample+(w1_M1_sample-Ew1_M1_sample)/(i+2);\n\t\tEw1_P1_sample=Ew1_P1_sample+(w1_P1_sample-Ew1_P1_sample)/(i+2);\n\n\t}\n\n\t//write-out means for latent variables\n\tfile_ElatentInd.open (\"BayesFactors_out/\"+output+\"_Efactors.txt\");\n\tfile_ElatentSNPs.open (\"BayesFactors_out/\"+output+\"_Escores.txt\");\n\tfile_ElatentInd<<Ew1_P1_sample<<endl;\n\tfile_ElatentSNPs<<Ew1_M1_sample<<endl;\n\tfile_ElatentInd.close();\n\tfile_ElatentSNPs.close();\n\n\tfile_lambda_u.close();\n\tfile_lambda_m.close();\n\n\tfile_mu_u.close();\n\tfile_mu_m.close();\n\n\tfile_sigma2_e.close();\n\tfile_sigma2_e_rowvec.close();\n\n\n\tcout<<\"Finished!\"<<endl;\n\ttimenow = chrono::system_clock::to_time_t(chrono::system_clock::now());\n\tcout << ctime(&timenow) << endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "c21b05aa791e7956cb7efe976e3c944208eb9c13", "size": 11408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BayesFactors.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": "BayesFactors.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": "BayesFactors.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": 29.1764705882, "max_line_length": 120, "alphanum_fraction": 0.6946002805, "num_tokens": 3514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5257777379277098}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\nusing namespace Eigen;\n\nclass vectorOp {\n    private:\n        double a, b, c;\n    public:\n        VectorXd weightedSum(VectorXd x, VectorXd y, VectorXd z);\n        void setScalar(double a0, double b0, double c0);\n};\n", "meta": {"hexsha": "7dffac991c66b56a21b2047b8d468fcfe118d6cb", "size": 259, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "simpleVecOp.hpp", "max_stars_repo_name": "qingyun322/vector", "max_stars_repo_head_hexsha": "5dc84efbd0f9435e934b6778175fa1be8dfcdfb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simpleVecOp.hpp", "max_issues_repo_name": "qingyun322/vector", "max_issues_repo_head_hexsha": "5dc84efbd0f9435e934b6778175fa1be8dfcdfb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simpleVecOp.hpp", "max_forks_repo_name": "qingyun322/vector", "max_forks_repo_head_hexsha": "5dc84efbd0f9435e934b6778175fa1be8dfcdfb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5833333333, "max_line_length": 65, "alphanum_fraction": 0.6525096525, "num_tokens": 66, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.5257777354127592}}
{"text": "// #include <Eigen/Core>\n// #include <Eigen/Sparse>\n#include \"lumped_mass_matrix.h\"\n\n\n// Sparse Version LBS\nvoid lumped_mass_matrix(const Eigen::MatrixXd & V,\n        const Eigen::MatrixXi & T,\n        Eigen::SparseMatrix<double>& M) {\n\n        // lumped mass matrix\n        Eigen::SparseMatrix<double> Ms;\n        igl::massmatrix(V, T, igl::MASSMATRIX_TYPE_DEFAULT, Ms);\n        std::vector<Eigen::Triplet<double>> triplets;\n        triplets.reserve(V.rows()*V.cols());\n        M.resize(V.rows()*V.cols(),V.rows()*V.cols());\n        for (int k=0; k < Ms.outerSize(); ++k) {\n            for (Eigen::SparseMatrix<double>::InnerIterator it(Ms,k); it; ++it) {\n                Eigen::Triplet<double> trplt1(3 * it.row() + 0, 3 * it.col() + 0, it.value());\n                Eigen::Triplet<double> trplt2(3 * it.row() + 1, 3 * it.col() + 1, it.value());\n                Eigen::Triplet<double> trplt3(3 * it.row() + 2, 3 * it.col() + 2, it.value());\n\n                triplets.emplace_back(trplt1);\n                triplets.emplace_back(trplt2);\n                triplets.emplace_back(trplt3);\n            }\n        }\n        M.setFromTriplets(triplets.begin(), triplets.end());\n\n    }", "meta": {"hexsha": "ca2f2301c77df02164d353f8f8c202362f849fcc", "size": 1175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lumped_mass_matrix.cpp", "max_stars_repo_name": "seungbaebang/complementary-dynamics-cpp", "max_stars_repo_head_hexsha": "a80f9579d714352fe541518cf89554d62b72a4f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2021-08-23T21:46:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T09:29:19.000Z", "max_issues_repo_path": "src/lumped_mass_matrix.cpp", "max_issues_repo_name": "seungbaebang/complementary-dynamics-cpp", "max_issues_repo_head_hexsha": "a80f9579d714352fe541518cf89554d62b72a4f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lumped_mass_matrix.cpp", "max_forks_repo_name": "seungbaebang/complementary-dynamics-cpp", "max_forks_repo_head_hexsha": "a80f9579d714352fe541518cf89554d62b72a4f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-08-23T21:39:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T14:49:40.000Z", "avg_line_length": 39.1666666667, "max_line_length": 94, "alphanum_fraction": 0.5557446809, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.5257777337410307}}
{"text": "#ifndef FIXEDGRID3_HPP_6KPVVRZF\n#define FIXEDGRID3_HPP_6KPVVRZF\n\n#include <math.h>\n#include <stdint.h>\n\n#include <vector>\n\n#include <boost/shared_ptr.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <ros/console.h>\n\n#include <pcl_util/point_types.hpp>\n#include <geom_cast/geom_cast.hpp>\n\n#include \"scrollgrid/grid_types.hpp\"\n#include \"scrollgrid/box.hpp\"\n\nnamespace ca\n{\n\ntemplate<class Scalar>\nclass FixedGrid3 {\npublic:\n  typedef Scalar ScalarType; // TODO what is my convention for this?\n  typedef Eigen::Matrix<Scalar, 3, 1> Vec3;\n\n  typedef boost::shared_ptr<FixedGrid3> Ptr;\n  typedef boost::shared_ptr<const FixedGrid3> ConstPtr;\n\npublic:\n  FixedGrid3() :\n      box_(),\n      origin_(0, 0, 0),\n      dimension_(0, 0, 0),\n      num_cells_(0),\n      strides_(0, 0, 0),\n      resolution_(0)\n  { }\n\n  /**\n   * @param center: center of the grid in global frame\n   * @param dimension: number of grid cells along each coordinate\n   * @param resolution: size of each grid cell side. they are cubic.\n   */\n  FixedGrid3(const Vec3& center,\n             const Vec3Ix& dimension,\n             Scalar resolution) :\n      box_(center-(dimension.cast<Scalar>()*resolution)/2,\n           center+(dimension.cast<Scalar>()*resolution)/2),\n      origin_(center-box_.radius()),\n      dimension_(dimension),\n      num_cells_(dimension.prod()),\n      strides_(dimension.tail<2>().prod(), dimension[2], 1),\n      resolution_(resolution)\n  { }\n\n  virtual ~FixedGrid3() { }\n\n  FixedGrid3(const FixedGrid3& other) :\n      box_(other.box_),\n      origin_(other.origin_),\n      dimension_(other.dimension_),\n      num_cells_(other.num_cells_),\n      strides_(other.strides_),\n      resolution_(other.resolution_)\n  {\n  }\n\n  FixedGrid3& operator=(const FixedGrid3& other) {\n    if (this==&other) { return *this; }\n    box_ = other.box_;\n    origin_ = other.origin_;\n    dimension_ = other.dimension_;\n    num_cells_ = other.num_cells_;\n    strides_ = other.strides_;\n    resolution_ = other.resolution_;\n    return *this;\n  }\n\npublic:\n\n  /**\n   * see ctor for params\n   */\n  void reset(const Vec3& center,\n             const Vec3Ix& dimension,\n             Scalar resolution) {\n    box_.set_center(center);\n    box_.set_radius((dimension.template cast<Scalar>()*resolution)/2);\n    origin_ = center - box_.radius();\n    dimension_ = dimension;\n    num_cells_ = dimension.prod();\n    strides_ = Vec3Ix(dimension.tail<2>().prod(), dimension[2], 1);\n    resolution_ = resolution;\n  }\n\n\n  /**\n   * Is pt inside 3D box containing grid?\n   * @param pt point in same frame as center (probably world_view)\n   */\n  bool is_inside_box(const Vec3& pt) const {\n    return box_.contains(pt);\n  }\n\n  bool is_inside_box(Scalar x, Scalar y, Scalar z) const {\n    return box_.contains(Vec3(x, y, z));\n  }\n\n  template<class PointT>\n  bool is_inside_box(const PointT& pt) const {\n    return box_.contains(ca::point_cast<Eigen::Vector3d>(pt));\n  }\n\n  /**\n   * is i, j, k inside the grid limits?\n   */\n  bool is_inside_grid(const Vec3Ix& grid_ix) const {\n    return ((grid_ix.array() >= 0).all() &&\n            (grid_ix.array() < dimension_.array()).all());\n  }\n\n  bool is_inside_grid(grid_ix_t i, grid_ix_t j, grid_ix_t k) const {\n    return this->is_inside_grid(Vec3Ix(i, j, k));\n  }\n\n  /**\n   * Given position in world coordinates, return ijk grid coordinates.\n   * Note: does not check if point is inside grid.\n   */\n  Vec3Ix world_to_grid(const Vec3& xyz) const {\n    Vec3 tmp = ((xyz - origin_).array() - 0.5*resolution_)/resolution_;\n    //return tmp.cast<grid_ix_t>();\n    return Vec3Ix(round(tmp.x()), round(tmp.y()), round(tmp.z()));\n  }\n\n  Vec3Ix world_to_grid(Scalar x, Scalar y, Scalar z) const {\n    return this->world_to_grid(Vec3(x, y, z));\n  }\n\n  /**\n   * Given ijk grid coordinates resurn xyz world coordinates.\n   * xyz is center of corresponding voxel.\n   */\n  Vec3 grid_to_world(const Vec3Ix& grid_ix) const {\n    Vec3 w((grid_ix.cast<Scalar>()*resolution_ + origin_).array() + 0.5*resolution_);\n    return w;\n  }\n\n  Vec3 grid_to_world(grid_ix_t i, grid_ix_t j, grid_ix_t k) const {\n    return this->grid_to_world(Vec3Ix(i, j, k));\n  }\n\n  /**\n   * given grid ijk coordinate, return linear memory index.\n   */\n  mem_ix_t grid_to_mem(grid_ix_t i, grid_ix_t j, grid_ix_t k) const {\n    return this->grid_to_mem(Vec3Ix(i, j, k));\n  }\n\n  mem_ix_t grid_to_mem(const Vec3Ix& grid_ix) const {\n    return strides_.dot(grid_ix);\n  }\n\n  /**\n   * given linear memory index, return ijk coordinate.\n   */\n  Vec3Ix mem_to_grid(mem_ix_t mem_ix) const {\n    grid_ix_t i = mem_ix/strides_[0];\n    mem_ix -= i*strides_[0];\n    grid_ix_t j = mem_ix/strides_[1];\n    mem_ix -= j*strides_[1];\n    grid_ix_t k = mem_ix;\n\n    return Vec3Ix(i, j, k);\n  }\n\n  /**\n   * pack into grid_ix_t as [int16, int16, int16, 0]\n   * note grid_ix_it is a signed 64-bit type\n   * this gives range of [-32768, 32768] for each coordinate\n   * so if voxel is 5cm, [-1638.4 m, 1638.4 m] relative to origin_.\n   * this is useful as a unique hash.\n   * this is better than mem_ix because mem_ix is ambiguous for absolute ijk.\n   * if we use linear mem_ix as a hash,\n   * then because of scrolling there may be collisions, and mem_ix become\n   * invalidated once the corresponding voxel scrolls out.\n   */\n  grid_ix_t grid_to_hash(grid_ix_t i, grid_ix_t j, grid_ix_t k) const {\n    ROS_ASSERT( i > std::numeric_limits<int16_t>::min() && i < std::numeric_limits<int16_t>::max() );\n    ROS_ASSERT( j > std::numeric_limits<int16_t>::min() && j < std::numeric_limits<int16_t>::max() );\n    ROS_ASSERT( k > std::numeric_limits<int16_t>::min() && k < std::numeric_limits<int16_t>::max() );\n    // TODO get from scrollgrid3\n    return 0;\n  }\n\n public:\n  const ca::scrollgrid::Box<Scalar, 3>& box() const { return box_; }\n  grid_ix_t dim_i() const { return dimension_[0]; }\n  grid_ix_t dim_j() const { return dimension_[1]; }\n  grid_ix_t dim_k() const { return dimension_[2]; }\n  grid_ix_t first_i() const { return 0; }\n  grid_ix_t first_j() const { return 0; }\n  grid_ix_t first_k() const { return 0; }\n  grid_ix_t last_i() const { return dimension_[0]; }\n  grid_ix_t last_j() const { return dimension_[1]; }\n  grid_ix_t last_k() const { return dimension_[2]; }\n  const Vec3Ix& dimension() const { return dimension_; }\n  const Vec3& radius() const { return box_.radius(); }\n  const Vec3& origin() const { return origin_; }\n  Vec3 min_pt() const { return box_.min_pt(); }\n  Vec3 max_pt() const { return box_.max_pt(); }\n  const Vec3& center() const { return box_.center(); }\n  Scalar resolution() const { return resolution_; }\n\n  // basically equivalent to scroll_offset = (0, 0, 0)\n  grid_ix_t num_cells() const { return num_cells_; }\n\n private:\n  // 3d box enclosing grid. In whatever coordinates were given (probably\n  // world_view)\n  ca::scrollgrid::Box<Scalar, 3> box_;\n\n  // static origin of the grid coordinate system.\n  // it's center - box.radius\n  Vec3 origin_;\n\n  // number of grid cells along each axis\n  Vec3Ix dimension_;\n\n  // number of cells\n  grid_ix_t num_cells_;\n\n  // grid strides to translate from linear to 3D layout.\n  // C-ordering, ie x slowest, z fastest.\n  Vec3Ix strides_;\n\n  // size of grid cells\n  Scalar resolution_;\n\n};\n\ntypedef FixedGrid3<double> FixedGrid3d;\ntypedef FixedGrid3<float> FixedGrid3f;\n\n} /* ca */\n\n#endif /* end of include guard: FIXEDGRID3_HPP_6KPVVRZF */\n", "meta": {"hexsha": "2d8e5edf58f72c9cb5b5e3da39a4862b11b267b9", "size": 7340, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dependency/scrollgrid/include/scrollgrid/fixedgrid3.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/fixedgrid3.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/fixedgrid3.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": 29.0118577075, "max_line_length": 101, "alphanum_fraction": 0.6662125341, "num_tokens": 2045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5257777295543503}}
{"text": "#include \"HInfinityRobustController.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\n\n\nnamespace DQ_robotics\n{\n\n\n\nHInfinityRobustController::HInfinityRobustController( const DQ_kinematics& robot, const Matrix<double,8,1>& B, const double& gamma, const double& alpha ) : DQ_controller()\n{\n\n    //Initialization of argument parameters\n    robot_dofs_     = (robot.links() - robot.n_dummy());\n    robot_          = robot;\n    kp_             = MatrixXd::Zero(8,8);\n    B_              = B;\n    Bw_             = Matrix<double,8,1>::Zero();\n    gamma_          = gamma;\n    alpha_          = alpha;\n\n    //Initilization of remaining parameters\n    thetas_         = MatrixXd(robot_dofs_,1);\n    delta_thetas_   = MatrixXd::Zero(robot_dofs_,1);\n\n    old_reference_                  = DQ(0.0);\n    reference_state_variables_      = MatrixXd(8,1);\n    measured_state_variables_       = MatrixXd(8,1);\n\n    N_                 = MatrixXd(8,robot_dofs_);\n    task_jacobian_     = MatrixXd(8,robot_dofs_);\n    N_pseudoinverse_   = MatrixXd(robot_dofs_,8);\n\n    error_             = MatrixXd(8,1);\n\n    C8_        = C8(); \n    identity8_ = MatrixXd::Identity(8,8);\n\n    end_effector_pose_ = DQ(0,0,0,0,0,0,0,0);\n\n}\n\nVectorXd HInfinityRobustController::getNewJointPositions( const DQ reference, const VectorXd thetas)\n{\n\n    delta_thetas_ = getNewJointVelocities( reference, thetas);\n\n    // Send updated thetas to simulation\n    return (thetas_ + delta_thetas_);\n\n}\n\nVectorXd HInfinityRobustController::getNewJointVelocities( const DQ reference, const VectorXd thetas)\n{\n\n    ///--Remapping arguments\n    thetas_ = thetas;\n    reference_state_variables_ = reference.vec8();\n\n    ///--Controller Step\n           \n    //Calculate jacobian\n    task_jacobian_  = robot_.jacobian(thetas_);\n    \n    // Recalculation of measured data.\n    // End effectors pose\n    end_effector_pose_ = robot_.fkm(thetas_);\n    measured_state_variables_ = vec8(end_effector_pose_);\n\n    //Error\n    error_ = Hminus8(reference)*(C8_)*(reference_state_variables_ - measured_state_variables_);\n\n    N_ = Hminus8(reference)*(C8_)*task_jacobian_;\n\n    N_pseudoinverse_ = pseudoInverse(N_);\n    \n    //Recalculation of K (if reference changed)\n    if(old_reference_ != reference)\n    {\n      Bw_ = Hminus8(reference)*(C8_)*B_;\n      //std::cout << std::endl << (Bw_.transpose()*Bw_*sqrt(2.0)) << std::endl;\n      double bwtbwsqrt2 = (Bw_.transpose()*Bw_*sqrt(2.0)).coeff(0);\n      kp_ = (1.0/gamma_) * ( Bw_*Bw_.transpose() + (bwtbwsqrt2/4.0)*identity8_ )*(alpha_/sqrt(bwtbwsqrt2));\n      std::cout << std::endl << kp_ << std::endl;\n      old_reference_ = reference;\n    }\n           \n    delta_thetas_ = N_pseudoinverse_*kp_*error_;\n\n    return delta_thetas_;\n\n}\n\n\n\n\n\n}\n", "meta": {"hexsha": "c83000cd383664c79ef97670fd37eb2b3f4f5247", "size": 2751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros_dqrobotics/dq_robotics/include/dq_robotics/controllers/HInfinityRobustController.cpp", "max_stars_repo_name": "birlrobotics/birlBaxter_demos", "max_stars_repo_head_hexsha": "a4871cbf2587a759c958c8451746554e1663e829", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-12-29T11:17:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T00:49:10.000Z", "max_issues_repo_path": "ros_dqrobotics/dq_robotics/include/dq_robotics/controllers/HInfinityRobustController.cpp", "max_issues_repo_name": "birlrobotics/birlBaxter_demos", "max_issues_repo_head_hexsha": "a4871cbf2587a759c958c8451746554e1663e829", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-20T05:52:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-30T09:07:56.000Z", "max_forks_repo_path": "ros_dqrobotics/dq_robotics/include/dq_robotics/controllers/HInfinityRobustController.cpp", "max_forks_repo_name": "birlrobotics/birlBaxter_demos", "max_forks_repo_head_hexsha": "a4871cbf2587a759c958c8451746554e1663e829", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-02-10T06:12:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T11:56:07.000Z", "avg_line_length": 26.9705882353, "max_line_length": 171, "alphanum_fraction": 0.6423118866, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5257777295543503}}
{"text": "/**\n * \\file LinkwitzRileyFilter.hxx\n */\n\n#include \"LinkwitzRileyFilter.h\"\n\n#include <boost/math/tools/polynomial.hpp>\n\nnamespace ATK\n{\n  template<typename DataType>\n  LinkwitzRileyLowPassCoefficients<DataType>::LinkwitzRileyLowPassCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void LinkwitzRileyLowPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    CoeffDataType omega = boost::math::constants::pi<CoeffDataType>() * cut_frequency;\n    CoeffDataType kappa = omega / std::tan(omega / input_sampling_rate);\n    CoeffDataType delta = kappa * kappa + omega * omega + 2 * kappa * omega;\n\n    coefficients_in[2] = omega * omega / delta;\n    coefficients_in[1] = 2 * omega * omega / delta;\n    coefficients_in[0] = omega * omega / delta;\n    coefficients_out[1] = 2 * (kappa * kappa - omega * omega) / delta;\n    coefficients_out[0] = -(omega * omega + kappa * kappa - 2 * kappa * omega) / delta;\n  }\n\n  template<typename DataType>\n  LinkwitzRileyHighPassCoefficients<DataType>::LinkwitzRileyHighPassCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void LinkwitzRileyHighPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    CoeffDataType omega = boost::math::constants::pi<CoeffDataType>() * cut_frequency;\n    CoeffDataType kappa = omega / std::tan(omega / input_sampling_rate);\n    CoeffDataType delta = kappa * kappa + omega * omega + 2 * kappa * omega;\n    \n    coefficients_in[2] = kappa * kappa / delta;\n    coefficients_in[1] = - 2 * kappa * kappa / delta;\n    coefficients_in[0] = kappa * kappa / delta;\n    coefficients_out[1] = 2 * (kappa * kappa - omega * omega) / delta;\n    coefficients_out[0] = -(omega * omega + kappa * kappa - 2 * kappa * omega) / delta;\n  }\n\n  template<typename DataType>\n  LinkwitzRiley4LowPassCoefficients<DataType>::LinkwitzRiley4LowPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n  \n  template <typename DataType>\n  void LinkwitzRiley4LowPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    auto wc=2*boost::math::constants::pi<CoeffDataType>() * cut_frequency;\n    auto wc2=wc*wc;\n    auto wc3=wc2*wc;\n    auto wc4=wc2*wc2;\n    auto k=wc/std::tan(wc/2/input_sampling_rate);\n    auto k2=k*k;\n    auto k3=k2*k;\n    auto k4=k2*k2;\n    auto sqrt2=std::sqrt(CoeffDataType(2));\n    auto sq_tmp1=sqrt2*wc3*k;\n    auto sq_tmp2=sqrt2*wc*k3;\n    auto a_tmp=4*wc2*k2+2*sq_tmp1+k4+2*sq_tmp2+wc4;\n    \n    coefficients_out[3]=-(4*(wc4+sq_tmp1-k4-sq_tmp2))/a_tmp;\n    coefficients_out[2]=-(6*wc4-8*wc2*k2+6*k4)/a_tmp;\n    coefficients_out[1]=-(4*(wc4-sq_tmp1+sq_tmp2-k4))/a_tmp;\n    coefficients_out[0]=-(k4-2*sq_tmp1+wc4-2*sq_tmp2+4*wc2*k2)/a_tmp;\n    \n    coefficients_in[0] = coefficients_in[4] = wc4/a_tmp;\n    coefficients_in[1] = coefficients_in[3] = 4*wc4/a_tmp;\n    coefficients_in[2] = 6*wc4/a_tmp;\n  }\n  \n  template<typename DataType>\n  LinkwitzRiley4HighPassCoefficients<DataType>::LinkwitzRiley4HighPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n  \n  template <typename DataType>\n  void LinkwitzRiley4HighPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    auto wc=2*boost::math::constants::pi<CoeffDataType>() * cut_frequency;\n    auto wc2=wc*wc;\n    auto wc3=wc2*wc;\n    auto wc4=wc2*wc2;\n    auto k=wc/std::tan(wc/2/input_sampling_rate);\n    auto k2=k*k;\n    auto k3=k2*k;\n    auto k4=k2*k2;\n    auto sqrt2=std::sqrt(CoeffDataType(2));\n    auto sq_tmp1=sqrt2*wc3*k;\n    auto sq_tmp2=sqrt2*wc*k3;\n    auto a_tmp=4*wc2*k2+2*sq_tmp1+k4+2*sq_tmp2+wc4;\n    \n    coefficients_out[3]=-(4*(wc4+sq_tmp1-k4-sq_tmp2))/a_tmp;\n    coefficients_out[2]=-(6*wc4-8*wc2*k2+6*k4)/a_tmp;\n    coefficients_out[1]=-(4*(wc4-sq_tmp1+sq_tmp2-k4))/a_tmp;\n    coefficients_out[0]=-(k4-2*sq_tmp1+wc4-2*sq_tmp2+4*wc2*k2)/a_tmp;\n    \n    coefficients_in[0] = coefficients_in[4] = k4/a_tmp;\n    coefficients_in[1] = coefficients_in[3] = -4*k4/a_tmp;\n    coefficients_in[2] = 6*k4/a_tmp;\n  }\n}\n", "meta": {"hexsha": "0aae4afc3346643458f0bd9b6e9d6572f14200f2", "size": 4021, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "ATK/EQ/LinkwitzRileyFilter.hxx", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "ATK/EQ/LinkwitzRileyFilter.hxx", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "ATK/EQ/LinkwitzRileyFilter.hxx", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 32.6910569106, "max_line_length": 106, "alphanum_fraction": 0.6829146978, "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5257648128581327}}
{"text": "#include <iostream>\n#include <cassert>\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\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 boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> GraphTraits;\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, GraphTraits::edge_descriptor,\n                                                                              boost::property<boost::edge_weight_t, long>>>>>\n    Graph;\n\nvoid testcase()\n{\n  int n, m, s, f;\n  std::cin >> n >> m >> s >> f;\n  assert(n >= 2 && n <= 1e3 && m >= 0 && m <= 5e3);\n  const auto is_valid_node = [n](int i) { return i >= 0 && i < n; };\n  (void)is_valid_node;\n  assert(is_valid_node(s) && is_valid_node(f) && s != f);\n\n  Graph dijkstra_graph(n);\n  const auto add_dijkstra_edge = [&dijkstra_graph](int a, int b, long capacity, long distance) {\n    assert(a != b);\n    auto w_map = boost::get(boost::edge_weight, dijkstra_graph);\n    auto c_map = boost::get(boost::edge_capacity, dijkstra_graph);\n    const Graph::edge_descriptor e = boost::add_edge(a, b, dijkstra_graph).first;\n    const Graph::edge_descriptor rev_e = boost::add_edge(b, a, dijkstra_graph).first;\n    w_map[e] = distance;\n    w_map[rev_e] = distance;\n    c_map[e] = capacity;\n    c_map[rev_e] = capacity;\n  };\n\n  for (int i = 0; i < m; i++)\n  {\n    int a, b, c, d;\n    std::cin >> a >> b >> c >> d;\n    assert(is_valid_node(a) && is_valid_node(b));\n    assert(c >= 1 && c <= 1e4 && d >= 1 && d <= 1e4);\n    if (a != b)\n    {\n      add_dijkstra_edge(a, b, c, d);\n    }\n  }\n\n  std::vector<int> source_distances_by_node(n);\n  boost::dijkstra_shortest_paths(dijkstra_graph, s, boost::distance_map(boost::make_iterator_property_map(source_distances_by_node.begin(), boost::get(boost::vertex_index, dijkstra_graph))));\n\n  Graph flow_graph(n);\n  const auto add_flow_edge = [&flow_graph](int from, int to, long capacity) {\n    auto c_map = boost::get(boost::edge_capacity, flow_graph);\n    auto r_map = boost::get(boost::edge_reverse, flow_graph);\n    const Graph::edge_descriptor e = boost::add_edge(from, to, flow_graph).first;\n    const Graph::edge_descriptor rev_e = boost::add_edge(to, from, flow_graph).first;\n    c_map[e] = capacity;\n    c_map[rev_e] = 0;\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n  };\n\n  for (auto its = boost::edges(dijkstra_graph); its.first != its.second; its.first++)\n  {\n    const Graph::edge_descriptor edge = *its.first;\n    if (source_distances_by_node.at(edge.m_target) - source_distances_by_node.at(edge.m_source) == boost::get(boost::edge_weight, dijkstra_graph)[edge])\n    {\n      add_flow_edge(edge.m_source, edge.m_target, boost::get(boost::edge_capacity, dijkstra_graph)[edge]);\n    }\n  }\n\n  const int flow = boost::push_relabel_max_flow(flow_graph, s, f);\n  std::cout << flow << \"\\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    DEBUG(1, \"\");\n  }\n\n  return 0;\n}", "meta": {"hexsha": "ffb71eb46e447cce53ab8e3086750f856b74095b", "size": 3497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-13/marathon/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-13/marathon/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-13/marathon/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": 35.6836734694, "max_line_length": 191, "alphanum_fraction": 0.6148126966, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5257648128581326}}
{"text": "//  Copyright (c) 2017 Zahra Khatami \n//\n// Train your data, then record them in an output file stated in \"retrieving_weights_two_classes_into_txt_file\"\n\n#include <limits>\n#include <math.h>\n#include <iostream>\n#include <stdlib.h>\n#include <time.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Eigen>\n#include <Eigen/LU>\n\nusing namespace Eigen;\n#define MAX_FLOAT (std::numeric_limits<float>::max())\n\nclass learning_binary_regression_model {\n\n\tstd::size_t number_of_experiments;\n\tstd::size_t number_of_features;\n\tfloat threshold; \t\t\t\t\t\t\t//the convergence for estimating the final weights\n\tMatrixXf experimental_results; \t\t\t\t//the experimental values of the features of the training data\t\n\tMatrixXf experimental_results_trans;\t\t//transpose of experimental_results\n\tMatrixXf execution_times;\t\t\t\t\t//execution time for each class for each experiment\n\tMatrixXf weightsb; \t\t\t\t\t\t\t//weights of our learning network\n\tMatrixXf new_weightsb;\t\t\t\t\t\t//updated weights after each step\t\n\tMatrixXf targets_two_class;\t\t\t\t\t//outputs of the training data\n\tMatrixXf diag_weightsb; \t\t\t\t\t//used for updating weights\n\tMatrixXf M; \t\t\t\t\t\t\t\t//used for updating weights\n\tint* predicted_output_two_class;\t\t\t//predicted class of each experimental results\n\tfloat* averages;\t\t\t\t\t\t\t//parameters for normalization\n\tfloat* averages_2;\t\t\t\t\t\t\t//parameters for normalization\n\tfloat* var;\t\t\t\t\t\t\t\t\t//parameters for normalization\t\t\n\t\n\tvoid normalizing_samples_two_class();\n\tvoid updating_values_of_M_and_diag_weights();\n\tvoid updating_values_of_weights_two_class();\n\tvoid new_values_for_weightsb();\n\tfloat computing_new_least_squared_err_two_class();\t\n\tvoid learning_weights_two_classes();\n\tvoid printing_weights_two_class();\n\tvoid estimating_output_two_class();\n\tvoid printing_computed_values(std::size_t row, std::size_t col, MatrixXf& mat);\n\npublic:\n\tlearning_binary_regression_model(std::size_t number_of_expr, std::size_t number_of_ftrs, \n\t\t\t\t\t\t\t\t\tfloat th, float** expr_results, int* target_expr, float** exec_time) {\n\n\t\tnumber_of_experiments = number_of_expr;\n\t\tnumber_of_features = number_of_ftrs;\n\t\tthreshold = th;\n\n\t\tweightsb = Eigen::MatrixXf::Random((number_of_features +  1), 1);\n\t\tnew_weightsb = Eigen::MatrixXf::Random((number_of_features +  1), 1);\n\t\ttargets_two_class = Eigen::MatrixXf::Random(number_of_experiments, 1);\n\t\tdiag_weightsb = Eigen::MatrixXf::Random(number_of_experiments, number_of_experiments);\n\t\tM = Eigen::MatrixXf::Random(number_of_experiments, 1);\n\t\texperimental_results = Eigen::MatrixXf::Random(number_of_experiments, (number_of_features +  1));\n\t\texperimental_results_trans = Eigen::MatrixXf::Random((number_of_features + 1), number_of_experiments);\n\t\texecution_times = MatrixXf::Random(number_of_experiments, 2);\t\n\t\tpredicted_output_two_class = new int[number_of_experiments];\n\n\t\t//variance and average of each features value for normalization\n\t\taverages = new float[number_of_features];\n\t\taverages_2 = new float[number_of_features];\n\t\tvar = new float[number_of_features];\n\n\t\t//initializing weights\n\t\tfor(std::size_t i = 0; i < number_of_features +  1; i++) {\n\t\t\tweightsb(i, 0) = 0.1;\n\t\t}\n\n\t\tfor(std::size_t n = 0; n < number_of_experiments; n++) {\n\t\t\ttargets_two_class(n, 0) = (float)target_expr[n];\n\t\t\tM(n, 0) = 0.0;\n\n\t\t\t//initializing experimental_results\n\t\t\texperimental_results(n, 0) = 1.0; // 1 + wf + ....\n\t\t\tfor(std::size_t f = 1; f < number_of_features + 1; f++) {\n\t\t\t\texperimental_results(n, f) = expr_results[n][f - 1];\n\t\t\t}\n\n\t\t\t//initializing execution_times\n\t\t\tfor(std::size_t c = 0; c < 2; c++) {\n\t\t\t\texecution_times(n, c) = exec_time[n][c];\n\t\t\t}\n\n\t\t\t//initializing diag_weightsb\n\t\t\tfor(std::size_t j = 0; j < number_of_experiments; j++) {\n\t\t\t\tdiag_weightsb(n, j) = 0.0;\n\t\t\t}\n\t\t}\t\t\n\t}\n\n\t//two-class logistic regression\n\tvoid learning_two_classes();\n\tvoid retrieving_weights_two_classes_into_txt_file();\n\tvoid finalizing_two_classes();\n\tvoid printing_predicted_output_two_class();\n\tvoid finalizing_step();\n};\n\n//it prints computed values : for testing\nvoid learning_binary_regression_model::printing_computed_values(std::size_t row, std::size_t col, MatrixXf& mat) {\n\tif(row != 0 && col != 0) {\n\t\tfor(std::size_t r = 0; r < row; r++) {\n\t\t\tfor(std::size_t c = 0; c < col; c++) {\n\t\t\t\tprintf(\"%f, \", mat(r, c));\n\t\t\t}\n\t\t\tstd::cout<<std::endl;\n\t\t}\n\t}\n\telse if(row == 0 && col != 0){\n\t\tfor(std::size_t c = 0; c < col; c++) {\n\t\t\tprintf(\"%f, \", mat(0, c));\n\t\t}\n\t}\n\telse {\n\t\tfor(std::size_t r = 0; r < row; r++) {\n\t\t\tprintf(\"%f, \", mat(r, 0));\n\t\t}\n\t}\n\tstd::cout<<std::endl;\n}\n\nvoid learning_binary_regression_model::updating_values_of_M_and_diag_weights() {\n\tMatrixXf WX = MatrixXf::Random(1, number_of_experiments);\n\tMatrixXf weightsb_transpose = MatrixXf::Random(1, (number_of_features + 1));\n\tWX = weightsb_transpose * experimental_results_trans;\n\n\tfor(std::size_t n = 0; n < number_of_experiments; n++) {\n\t\tM(n, 0) = float(1.0 / (1.0 + exp((-1.0) *WX(0, n))));\n\t\tdiag_weightsb(n, n) = M(n, 0) * (1.0 - M(n, 0));\n\t}\n}\n\nvoid learning_binary_regression_model::new_values_for_weightsb() {\n\t//X^T * S\n\tMatrixXf X_TS = Eigen::MatrixXf::Random((number_of_features + 1), number_of_experiments);\n\tX_TS = experimental_results_trans * diag_weightsb;\n\n\t//X^T * S * X\n\tMatrixXf XSX = Eigen::MatrixXf::Random((number_of_features + 1), (number_of_features + 1));\n\tXSX = X_TS * experimental_results;\n\n\t//(X^T * S * X) ^ -1\n\tMatrixXf XSX_inv = Eigen::MatrixXf::Random((number_of_features + 1), (number_of_features + 1));\n\tXSX_inv = XSX.inverse();\n\n\t//(X^T * S * X) ^ -1  * X^T\n\tMatrixXf XSX_inv_X_T = Eigen::MatrixXf::Random((number_of_features + 1), number_of_experiments);\n\tXSX_inv_X_T = XSX_inv * experimental_results_trans;\n\n\t//S * X\n\tMatrixXf SX = Eigen::MatrixXf::Random(number_of_experiments, (number_of_features + 1));\n\tSX = diag_weightsb * experimental_results;\n\n\t//S * X * W\n\tMatrixXf SXW = Eigen::MatrixXf::Random(number_of_experiments, 1);\n\tSXW = SX * weightsb;\n\n\t//S * X * W + y - M\n\tMatrixXf SXW_y_M = Eigen::MatrixXf::Random(number_of_experiments, 1);\n\tSXW_y_M = SXW + targets_two_class - M;\n\n\t//W\n\tnew_weightsb = XSX_inv_X_T * SXW_y_M;\n}\n\nfloat learning_binary_regression_model::computing_new_least_squared_err_two_class() {\n\tfloat num_err = 0.0;\n\tfor(int n = 0; n < number_of_experiments; n++) {\n\t\tif(abs(execution_times(n, predicted_output_two_class[n]) - execution_times(n, targets_two_class(n, 0))) > 0.2) {\n\t\t\tnum_err++;\n\t\t}\n\t}\n\tfloat prec = float(num_err / number_of_experiments);\n\treturn prec;\n}\n\nvoid learning_binary_regression_model::updating_values_of_weights_two_class() {\n\tfor(std::size_t f = 0; f < number_of_features + 1; f++) {\n\t\tweightsb(f, 0) = new_weightsb(f, 0);\n\t}\n}\n\nvoid learning_binary_regression_model::printing_weights_two_class() {\n\tprinting_computed_values(number_of_features + 1, 0, weightsb);\n}\n\nvoid learning_binary_regression_model::estimating_output_two_class(){\n\tfor(std::size_t n = 0; n < number_of_experiments; n++) {\n\t\tfloat temp = 0.0;\n\t\tfor(std::size_t f = 0; f < number_of_features + 1; f++) {\n\t\t\ttemp += weightsb(f, 0) * experimental_results(n, f);\n\t\t}\n\t\tif(temp >= 0) {\n\t\t\tpredicted_output_two_class[n] = 1;\n\t\t}\n\t\telse {\n\t\t\tpredicted_output_two_class[n] = 0;\n\t\t}\n\t}\n}\n\n//this func applys experimental values of the training data on our learning network\nvoid learning_binary_regression_model::learning_weights_two_classes() {\n\tfloat least_squared_err = MAX_FLOAT;\t\n\tstd::size_t itr = 1;\n\twhile(threshold < least_squared_err) {\t\n\t\tupdating_values_of_M_and_diag_weights();\n\t\tnew_values_for_weightsb();\n\t\tupdating_values_of_weights_two_class();\t\n\t\testimating_output_two_class();\n\t\tleast_squared_err = computing_new_least_squared_err_two_class();\n\t\tstd::cout<<\"\\n(\"<<itr<<\"),\"<<\"Least_squared_err =\\t\" << least_squared_err<<std::endl;\t\t\t\n\t\tprinting_weights_two_class();\t\t\n\t\titr++;\t\t\n\t}\t\n}\n\nvoid learning_binary_regression_model::normalizing_samples_two_class() {\n\n\t//initializing\n\tfor(std::size_t i = 0; i < number_of_features; i++) {\n\t\taverages[i] = 0;\n\t\taverages_2[i] = 0;\n\t\tvar[i] = 0;\n\t}\n\n\t//computing average and variance values for each feature\n\tfor(std::size_t i = 0; i < number_of_experiments; i++) {\t\t\n\t\tfor(std::size_t j = 1; j < number_of_features + 1; j++) {\n\t\t\taverages[j - 1] += experimental_results(i, j);\n\t\t\taverages_2[j - 1] += (pow(experimental_results(i, j), 2.0));\n\t\t}\n\t}\n\tfor(std::size_t i = 0; i < number_of_features; i++) {\t\t\n\t\taverages[i] = float(averages[i]/number_of_experiments);\n\t\taverages_2[i] = float(averages_2[i]/number_of_experiments);\n\t\tvar[i] = sqrt(averages_2[i] - pow(averages[i], 2.0));\t\t\n\t}\n\n\tfor(std::size_t n = 0; n < number_of_experiments; n++) {\n\t\tfor(std::size_t f = 1; f < number_of_features + 1; f++) {\n\t\t\tif(var[f - 1] != 0) {\n\t\t\t\texperimental_results(n, f) = float((experimental_results(n, f) - averages[f - 1])/var[f - 1]);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid learning_binary_regression_model::learning_two_classes() {\n\tnormalizing_samples_two_class();\n\texperimental_results_trans = experimental_results.transpose();\n\tlearning_weights_two_classes();\n}\n\n//writes computed weight into the text file\nvoid learning_binary_regression_model::retrieving_weights_two_classes_into_txt_file() {\n\tstd::ofstream outputFile(\"inputs/par_if.dat\");\n\n\t//normalization parameters (variance and average) in the first line\n\toutputFile << \"1 0 \"; \n\tfor(std::size_t p = 0; p < number_of_features - 1; p++) {\n\t\toutputFile << var[p] << \" \" << averages[p] << \" \"; \n\t}\n\toutputFile << var[number_of_features - 1] << \" \" << averages[number_of_features - 1] << std::endl;\n\n\tfor(std::size_t w = 0; w < number_of_features; w++) {\n\t\toutputFile<<weightsb(w, 0)<<\" \";\n\t}\n\toutputFile<<weightsb(number_of_features, 0);\n}\n\nvoid learning_binary_regression_model::printing_predicted_output_two_class() {\n\tstd::size_t num_err = 0;\n\tfor(std::size_t n = 0; n < number_of_experiments; n++) {\n\t\tif(abs(execution_times(n, predicted_output_two_class[n]) - execution_times(n, targets_two_class(n, 0))) > 0.2) { \n\t\t\tnum_err++;\n\t\t\tstd::cout<<\"[\"<<n<<\"]\\t\"<<predicted_output_two_class[n]<<\",\"<<targets_two_class(n, 0)<<std::endl;\n\t\t}\t\t\n\t}\n\tstd::cout<<\"\\n number of error predicted is\\t\"<<num_err<<\" out of \"<<number_of_experiments<<std::endl;\n}\n\nvoid learning_binary_regression_model::finalizing_step() {\n\n\t//releasing memory\n\tdelete[] averages;\n\tdelete[] averages_2;\n\tdelete[] var;\n\tdelete[] predicted_output_two_class;\n}\n", "meta": {"hexsha": "a16a2bde0c1bf1bd56a1ee430bd07dd88b6e9972", "size": 10262, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "logisticRegressionModel/algorithms/models/binary_regression_model.hpp", "max_stars_repo_name": "STEllAR-GROUP/hpxML", "max_stars_repo_head_hexsha": "cce6478c2fe28e9917a67bab12af5ae54a254786", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-04-06T16:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-19T11:28:54.000Z", "max_issues_repo_path": "logisticRegressionModel/algorithms/models/binary_regression_model.hpp", "max_issues_repo_name": "STEllAR-GROUP/hpxML", "max_issues_repo_head_hexsha": "cce6478c2fe28e9917a67bab12af5ae54a254786", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-13T17:42:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-13T18:20:23.000Z", "max_forks_repo_path": "logisticRegressionModel/algorithms/models/binary_regression_model.hpp", "max_forks_repo_name": "STEllAR-GROUP/hpxML", "max_forks_repo_head_hexsha": "cce6478c2fe28e9917a67bab12af5ae54a254786", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-05-25T06:33:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-25T20:09:13.000Z", "avg_line_length": 34.6689189189, "max_line_length": 115, "alphanum_fraction": 0.7079516663, "num_tokens": 2989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5257648128581326}}
{"text": "// Copyright (c) 2015\n// Author: Chrono Law\n#include <std.hpp>\n#include <type_traits>\nusing namespace std;\n\n//////////////////////////////////////////\n\n#include <boost/rational.hpp>\nusing namespace boost;\n\nvoid case1()\n{\n    rational<int> a;\n    rational<int> b(20);\n    rational<int> c(31415, 10000);\n\n    rational<int> r;\n    r = 0x31;\n    r.assign(7, 8);\n}\n\n//////////////////////////////////////////\n\nvoid case2()\n{\n#if 0\n    rational<int> r(1.0);\n    cout << r << endl;\n\n    r = 3.14;\n    cout << r << endl;\n\n    r.assign(7.23, 100);\n    cout << r << endl;\n#endif\n}\n\n//////////////////////////////////////////\n\nvoid case3()\n{\n    rational<int>   a(3),b(65534),c(22,7);\n\n    b += a;\n    c -= a;\n    if (c >= 0)\n    {\n        c = c * b;\n        ++a;\n    }\n    assert(a == 4);\n}\n\n//////////////////////////////////////////\n\nvoid case4()\n{\n    rational<int> r(10);\n    if (r)\n    {\n        r -= 10;\n    }\n    assert(!r);\n}\n\n//////////////////////////////////////////\n\nvoid case5()\n{\n    rational<int> r(2718, 1000);\n    cout << rational_cast<int>(r) << endl;\n    cout << rational_cast<double>(r) << endl;\n\n    //double x = r;\n}\n\n//////////////////////////////////////////\n\nvoid case6()\n{\n    rational<int> r(22,7);\n    cout << r.numerator() << \":\" << r.denominator()\n          << \"=\" << rational_cast<double>(r);\n    cout << endl;\n}\n\n//////////////////////////////////////////\n\nvoid case7()\n{\n    rational<int> a(-1414,1000), pi(314, 100);\n\n    cout << \"abs=\" << abs(a) << endl;\n    cout << pow(rational_cast<double>(a), 2) << endl;\n    cout << cos(rational_cast<double>(pi)) << endl;\n\n}\n\n//////////////////////////////////////////\n#include <boost/format.hpp>\n\nvoid case8()\n{\n    int a = 37, b = 62;\n    format fmt(\"gcd(%1%, %2%) = %3%. lcm(%1%, %2%) = %4%\\n\");\n    cout << fmt % a % b % gcd(a,b) % lcm(a,b);\n}\n\nint main()\n{\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    case7();\n    case8();\n}\n\n", "meta": {"hexsha": "5eb59ec2fb5f94c9fbee3097bdd6986068229053", "size": 1933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/rational.cpp", "max_stars_repo_name": "xystar2012/boost_guide", "max_stars_repo_head_hexsha": "6e3d78054d9ade9545a875199d8687001cdb9c97", "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": "math/rational.cpp", "max_issues_repo_name": "xystar2012/boost_guide", "max_issues_repo_head_hexsha": "6e3d78054d9ade9545a875199d8687001cdb9c97", "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": "math/rational.cpp", "max_forks_repo_name": "xystar2012/boost_guide", "max_forks_repo_head_hexsha": "6e3d78054d9ade9545a875199d8687001cdb9c97", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.8442622951, "max_line_length": 61, "alphanum_fraction": 0.4014485256, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.525638711770738}}
{"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//! \\file\n//!\\brief Tests long mul/div of fixed_point negatable for BOOST_FIXED_POINT_DISABLE_WIDE_INTEGER_MATH.\n\n#define BOOST_FIXED_POINT_DISABLE_WIDE_INTEGER_MATH\n#define BOOST_FIXED_POINT_DISABLE_MULTIPRECISION\n#define BOOST_FIXED_POINT_DISABLE_IOSTREAM\n\n#define BOOST_TEST_MODULE test_negatable_basic_disable_wide_integer_math\n#define BOOST_LIB_DIAGNOSTIC\n\n#include <boost/cstdfloat.hpp>\n#include <boost/fixed_point/fixed_point.hpp>\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(test_negatable_basic_disable_wide_integer_math)\n{\n  typedef boost::fixed_point::negatable< 10,\n                                        -53,\n                                        boost::fixed_point::round::classic> fixed_point_type;\n\n  typedef boost::float64_t float_point_type;\n\n  using std::ldexp;\n\n  const float_point_type tol = ldexp(float_point_type(1), -15);\n\n  const fixed_point_type x(fixed_point_type(100U) /  70U);\n  const fixed_point_type y(fixed_point_type(456U) / 110U);\n\n  const fixed_point_type z_mul(x * y);\n  const fixed_point_type z_div(x / y);\n\n  BOOST_CONSTEXPR float_point_type xd(BOOST_FLOAT64_C(100.0) / BOOST_FLOAT64_C( 70.0));\n  BOOST_CONSTEXPR float_point_type yd(BOOST_FLOAT64_C(456.0) / BOOST_FLOAT64_C(110.0));\n\n  const fixed_point_type z_mul_control(xd * yd);\n  const fixed_point_type z_div_control(xd / yd);\n\n  BOOST_CHECK_CLOSE_FRACTION(float_point_type(z_mul), float_point_type(z_mul_control), tol); // 5.9220779220779220779220779220779\n  BOOST_CHECK_CLOSE_FRACTION(float_point_type(z_div), float_point_type(z_div_control), tol); // 0.34461152882205513784461152882206\n\n  BOOST_CHECK_EQUAL(z_mul.crepresentation(), z_mul_control.crepresentation()); // UINT64_C(0x00BD81A98EF606A8)\n  BOOST_CHECK_EQUAL(z_div.crepresentation(), z_div_control.crepresentation()); // UINT64_C(0x000B070EC1C3B071)\n\n  BOOST_CHECK_EQUAL(z_mul.crepresentation(), UINT64_C(0x00BD81A98EF606A8));\n  BOOST_CHECK_EQUAL(z_div.crepresentation(), UINT64_C(0x000B070EC1C3B071));\n}\n", "meta": {"hexsha": "57dd560a0bb68a2467d5fb0d99baed39cd531125", "size": 2268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_basic_disable_wide_integer_math.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_disable_wide_integer_math.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_disable_wide_integer_math.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.2363636364, "max_line_length": 130, "alphanum_fraction": 0.7535273369, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5256386946092358}}
{"text": "#include \"stdafx.h\"\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include \"contest_types.h\"\n#include \"solver_registry.h\"\n#include \"judge.h\"\n\nnamespace FlipAnnealingSolver {\n\nnamespace bg = boost::geometry;\nusing BoostPoint = bg::model::d2::point_xy<double>;\nusing BoostPolygon = bg::model::polygon<BoostPoint>;\nusing BoostLinestring = bg::model::linestring<BoostPoint>;\n\ntemplate <typename T>\nBoostPoint ToBoostPoint(const T& point) {\n  const auto [x, y] = point;\n  return BoostPoint(x, y);\n}\n\ntemplate <typename T>\nBoostPolygon ToBoostPolygon(const std::vector<T>& points) {\n  BoostPolygon polygon;\n  for (std::size_t i = 0; i <= points.size(); ++i) {\n    polygon.outer().push_back(ToBoostPoint(points[i % points.size()]));\n  }\n  if (bg::area(polygon) < 0.0) {\n    bg::reverse(polygon);\n  }\n  return polygon;\n}\n\ntemplate <typename T, typename U>\ndouble SquaredDistance(const T& vertex0, const U& vertex1) {\n  const auto [x0, y0] = vertex0;\n  const auto [x1, y1] = vertex1;\n  return (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);\n}\n\ntemplate <typename T>\ndouble SquaredEdgeLength(const T& vertices, const Edge& edge) {\n  const auto [a, b] = edge;\n  return SquaredDistance(vertices[a], vertices[b]);\n}\n\nclass Solver : public SolverBase {\n public:\n  SolverOutputs solve(const SolverArguments& args) override {\n    hole_ = args.problem->hole_polygon;\n    vertices_ = args.problem->vertices;\n    edges_ = args.problem->edges;\n    epsilon_ = args.problem->epsilon;\n    hole_polygon_ = ToBoostPolygon(hole_);\n\n    const int N = vertices_.size();\n    auto pose = vertices_;\n    double cost = std::numeric_limits<double>::infinity();\n    double best_feasible_cost = std::numeric_limits<double>::infinity();\n    std::vector<Point> best_feasible_pose;\n\n    const int num_iters = 100000;\n    const double T0 = 1.0e1;\n    const double T1 = 1.0e-2;\n    for (int iter = 0; iter < num_iters; ++iter) {\n      const double progress = 1.0 * iter / num_iters;\n      if (std::uniform_real_distribution(0.0, 1.0)(rng_) < 0.01) {\n        const int v0 = std::uniform_int_distribution(0, N - 1)(rng_);\n        const int v1 = std::uniform_int_distribution(0, N - 1)(rng_);\n        if (v0 == v1) continue;\n        auto pose_bak = pose;\n        auto reflect = [](Point a, Point c, Point v) {\n          return v - 2 * double(dot(v - c, a)) / double(dot(a, a)) * a;\n        };\n        auto diff = pose[v1] - pose[v0];\n        Point n = {get_y(diff), -get_x(diff)};\n        for (int v2 = 0; v2 < pose.size(); ++v2) {\n          if (ccw(pose[v0], pose[v1], pose[v2])) {\n            pose[v2] = reflect(n, pose[v0], pose[v2]);\n          }\n        }\n        const auto [feasible, updated_cost] = Evaluate(pose);\n        if (feasible && updated_cost < best_feasible_cost) {\n          best_feasible_cost = updated_cost;\n          best_feasible_pose = pose;\n        }\n        const double T = std::pow(T0, 1.0 - progress) * std::pow(T1, progress);\n        if (std::uniform_real_distribution(0.0, 1.0)(rng_) < std::exp(-(updated_cost - cost) / T)) {\n          cost = updated_cost;\n        } else {\n          pose = pose_bak;\n        }\n        continue;\n      }\n      const int v = std::uniform_int_distribution(0, N - 1)(rng_);\n      const int dx = std::uniform_int_distribution(-3, 3)(rng_);\n      const int dy = std::uniform_int_distribution(-3, 3)(rng_);\n      auto& [x, y] = pose[v];\n      x += dx;\n      y += dy;\n      const auto [feasible, updated_cost] = Evaluate(pose);\n      if (feasible && updated_cost < best_feasible_cost) {\n        best_feasible_cost = updated_cost;\n        best_feasible_pose = pose;\n      }\n      const double T = std::pow(T0, 1.0 - progress) * std::pow(T1, progress);\n      if (std::uniform_real_distribution(0.0, 1.0)(rng_) < std::exp(-(updated_cost - cost) / T)) {\n        cost = updated_cost;\n      } else {\n        x -= dx;\n        y -= dy;\n      }\n    }\n\n    SolverOutputs outputs;\n    if (best_feasible_pose.empty()) {\n      outputs.solution = args.problem->create_solution(pose);\n    } else {\n      outputs.solution = args.problem->create_solution(best_feasible_pose);\n    }\n    return outputs;\n  }\n\n  template <typename P>\n  std::tuple<bool, double> Evaluate(const std::vector<P>& pose) const {\n    double deformation_cost = 0.0;\n    double protrusion_cost = 0.0;\n    double dislikes_cost = 0.0;\n\n    const double tolerance = epsilon_ / 1'000'000.0;\n    for (const auto& vertex : pose) {\n      protrusion_cost += bg::distance(ToBoostPoint(vertex), hole_polygon_);\n    }\n    for (const auto& edge : edges_) {\n      const auto [a, b] = edge;\n      BoostLinestring linestring{ToBoostPoint(pose[a]), ToBoostPoint(pose[b])};\n      std::vector<BoostLinestring> differences;\n      bg::difference(linestring, hole_polygon_, differences);\n      for (const auto& segment : differences) {\n        protrusion_cost += 1.0e-2 * bg::length(segment);\n      }\n\n      const auto d0 = SquaredEdgeLength(vertices_, edge);\n      const auto d1 = SquaredEdgeLength(pose, edge);\n      deformation_cost += 1.0e1 * std::max(0.0, std::abs(d1 / d0 - 1.0) - tolerance);\n    }\n\n    for (const auto h : hole_) {\n      double best = std::numeric_limits<double>::infinity();\n      for (const auto v : pose) {\n        best = std::min(best, SquaredDistance(h, v));\n      }\n      dislikes_cost += best * 1.0e-5;\n    }\n\n    const bool feasible = deformation_cost + protrusion_cost == 0.0;\n    const double cost = deformation_cost + protrusion_cost + dislikes_cost;\n\n    return {feasible, cost};\n  }\n\n private:\n  std::mt19937 rng_;\n  std::vector<Point> hole_;\n  std::vector<Point> vertices_;\n  std::vector<Edge> edges_;\n  integer epsilon_;\n  BoostPolygon hole_polygon_;\n};\n\n}\n\nREGISTER_SOLVER(\"FlipAnnealingSolver\", FlipAnnealingSolver::Solver);\n// vim:ts=2 sw=2 sts=2 et ci\n", "meta": {"hexsha": "047aa8d187a3b2f6c02fdfd7a11b0e808de4c423", "size": 5823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/flip_annealing_solver.cpp", "max_stars_repo_name": "nodchip/icfpc2021", "max_stars_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T13:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T13:52:18.000Z", "max_issues_repo_path": "src/solvers/flip_annealing_solver.cpp", "max_issues_repo_name": "nodchip/icfpc2021", "max_issues_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solvers/flip_annealing_solver.cpp", "max_forks_repo_name": "nodchip/icfpc2021", "max_forks_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T08:49:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:49:18.000Z", "avg_line_length": 33.2742857143, "max_line_length": 100, "alphanum_fraction": 0.6292289198, "num_tokens": 1643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5255829157598643}}
{"text": "//  (C) Copyright Gennadiy Rozental 2001-2002.\r\n//  Permission to copy, use, modify, sell and distribute this software\r\n//  is granted provided this copyright notice appears in all copies.\r\n//  This software is provided \"as is\" without express or implied warranty,\r\n//  and with no claim as to its suitability for any purpose.\r\n\r\n//  See http://www.boost.org for most recent version including documentation.\r\n//\r\n//  File        : $RCSfile: floating_point_comparison.hpp,v $\r\n//\r\n//  Version     : $Id: floating_point_comparison.hpp,v 1.7 2002/11/02 19:31:04 rogeeff Exp $\r\n//\r\n//  Description : defines algoirthms for comparing 2 floating point values\r\n// ***************************************************************************\r\n\r\n#ifndef BOOST_FLOATING_POINT_COMPARISON_HPP\r\n#define BOOST_FLOATING_POINT_COMPARISON_HPP\r\n\r\n#include <boost/limits.hpp>  // for std::numareic_limits\r\n\r\n#include <boost/test/detail/class_properties.hpp>\r\n\r\ntemplate<typename FPT>\r\ninline FPT\r\nfpt_abs( FPT arg ) \r\n{\r\n    return arg < 0 ? -arg : arg;\r\n}\r\n\r\n//____________________________________________________________________________//\r\n\r\n// both f1 and f2 are unsigned here\r\ntemplate<typename FPT>\r\ninline FPT \r\nsafe_fpt_division( FPT f1, FPT f2 )\r\n{\r\n    return  (f2 < 1 && f1 > f2 * std::numeric_limits<FPT>::max())   ? std::numeric_limits<FPT>::max() :\r\n           ((f2 > 1 && f1 < f2 * std::numeric_limits<FPT>::min() || \r\n             f1 == 0)                                               ? 0                               :\r\n                                                                      f1/f2 );\r\n}\r\n\r\n//____________________________________________________________________________//\r\n\r\ntemplate<typename FPT>\r\nclass close_at_tolerance {\r\npublic:\r\n    explicit    close_at_tolerance( FPT tolerance, bool strong_or_weak = true ) \r\n    : p_tolerance( tolerance ), m_strong_or_weak( strong_or_weak ) {}\r\n\r\n    explicit    close_at_tolerance( int number_of_rounding_errors, bool strong_or_weak = true ) \r\n    : p_tolerance( std::numeric_limits<FPT>::epsilon() * number_of_rounding_errors/2 ), \r\n      m_strong_or_weak( strong_or_weak ) {}\r\n\r\n    bool        operator()( FPT left, FPT right ) const\r\n    {\r\n        FPT diff = fpt_abs( left - right );\r\n        FPT d1   = safe_fpt_division( diff, fpt_abs( right ) );\r\n        FPT d2   = safe_fpt_division( diff, fpt_abs( left ) );\r\n        \r\n        return m_strong_or_weak ? (d1 <= p_tolerance.get() && d2 <= p_tolerance.get()) \r\n                                : (d1 <= p_tolerance.get() || d2 <= p_tolerance.get());\r\n    }\r\n\r\n    // Data members\r\n    BOOST_READONLY_PROPERTY( FPT, 0, () )\r\n                p_tolerance;\r\nprivate:\r\n    bool        m_strong_or_weak;\r\n};\r\n\r\n//____________________________________________________________________________//\r\n\r\ntemplate<typename FPT, typename ToleranceSource>\r\nbool\r\ncheck_is_closed( FPT left, FPT right, ToleranceSource tolerance, bool strong_or_weak = true )\r\n{\r\n    close_at_tolerance<FPT> pred( tolerance, strong_or_weak );\r\n\r\n    return pred( left, right );\r\n}\r\n\r\n//____________________________________________________________________________//\r\n\r\ntemplate<typename FPT, typename ToleranceSource>\r\nFPT\r\ncompute_tolerance( ToleranceSource tolerance, FPT /* unfortunately we need to pass type information this way*/ )\r\n{\r\n    close_at_tolerance<FPT> pred( tolerance );\r\n\r\n    return pred.p_tolerance.get();\r\n}\r\n\r\n//____________________________________________________________________________//\r\n\r\n// ***************************************************************************\r\n//  Revision History :\r\n//  \r\n//  $Log: floating_point_comparison.hpp,v $\r\n//  Revision 1.7  2002/11/02 19:31:04  rogeeff\r\n//  merged into the main trank\r\n//\r\n\r\n// ***************************************************************************\r\n\r\n#endif // BOOST_FLOATING_POINT_COMAPARISON_HPP\r\n", "meta": {"hexsha": "403d6c2da506b2cbf0d2ae40675af2d763d1fa2a", "size": 3862, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/boost/test/floating_point_comparison.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T06:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:24:28.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/boost/test/floating_point_comparison.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/boost/test/floating_point_comparison.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-17T10:01:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-11T20:17:27.000Z", "avg_line_length": 36.0934579439, "max_line_length": 113, "alphanum_fraction": 0.619368203, "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5255401538806515}}
{"text": "//   GAMBIT: Global and Modular BSM Inference Tool\n//   *********************************************\n///  \\file\n///\n///  Helper utilities for FlavBit\n///\n///  *********************************************\n///\n///  Authors (add name and date if you modify):\n///\n///  \\author Marcin Chrzaszcz\n///          (mchrzasz@cern.ch)\n///  \\date 2016 August\n///\n///  \\author Pat Scott\n///          (p.scott@imperial.ac.uk)\n///  \\date 2017 Mar\n///\n///  *********************************************\n\n#ifndef __flav_utils_hpp__\n#define __flav_utils_hpp__\n\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n\nnamespace Gambit\n{\n\n  namespace FlavBit\n  {\n\n    /// Matrix inversion routine using Boost\n    template<class T>\n    bool InvertMatrix (const ublas::matrix<T>& input, ublas::matrix<T>& inverse)\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<T> 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.assign(identity_matrix<T>(A.size1()));\n\n      // backsubstitute to get the inverse\n      lu_substitute(A, pm, inverse);\n\n      return true;\n    }\n\n  }\n\n}\n\n#endif //#defined __flav_utils_hpp__\n", "meta": {"hexsha": "121bb8937a6df2bcf35617424ba10139445eb475", "size": 1445, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "FlavBit/include/gambit/FlavBit/flav_utils.hpp", "max_stars_repo_name": "aaronvincent/gambit_aaron", "max_stars_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "FlavBit/include/gambit/FlavBit/flav_utils.hpp", "max_issues_repo_name": "aaronvincent/gambit_aaron", "max_issues_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "FlavBit/include/gambit/FlavBit/flav_utils.hpp", "max_forks_repo_name": "aaronvincent/gambit_aaron", "max_forks_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 22.578125, "max_line_length": 80, "alphanum_fraction": 0.5702422145, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5255401422089527}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_DOUBLE_EXPONENTIAL_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_DOUBLE_EXPONENTIAL_RNG_HPP\n\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/fun/log1m.hpp>\n\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/scal/fun/sign.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Return a pseudorandom double exponential variate with the given location\n     * and scale using the specified random number generator.\n     *\n     * @tparam RNG class of random number generator\n     * @param mu location parameter\n     * @param sigma positive scale parameter\n     * @param rng random number generator\n     * @return double exponential random variate\n     * @throw std::domain_error if mu is infinite or sigma is nonpositive\n     */\n    template <class RNG>\n    inline double\n    double_exponential_rng(double mu,\n                           double sigma,\n                           RNG& rng) {\n      static const char* function(\"double_exponential_rng\");\n\n      using boost::variate_generator;\n      using boost::random::uniform_01;\n      using std::log;\n      using std::abs;\n\n      check_finite(function, \"Location parameter\", mu);\n      check_positive_finite(function, \"Scale parameter\", sigma);\n\n      variate_generator<RNG&, uniform_01<> >\n        rng_unit_01(rng, uniform_01<>());\n      double a = 0;\n      double laplaceRN = rng_unit_01();\n      if (0.5 - laplaceRN > 0)\n        a = 1.0;\n      else if (0.5 - laplaceRN < 0)\n        a = -1.0;\n      return mu - sigma * a * log1m(2 * abs(0.5 - laplaceRN));\n    }\n  }\n}\n#endif\n", "meta": {"hexsha": "ec28a94e88a838fd8a7cf18ba74b3a210ba21c6b", "size": 1976, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/double_exponential_rng.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/double_exponential_rng.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/double_exponential_rng.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4915254237, "max_line_length": 79, "alphanum_fraction": 0.6821862348, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5255401378307316}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include \"MatrixFreeOperator.hpp\"\n\nMatrixFreeOperator::MatrixFreeOperator(){}\n\n\n// virtual here : get a col of the operator\nEigen::VectorXd MatrixFreeOperator::col(int index) const\n{\n    throw std::runtime_error(\"MatrixFreeOperator.col() not defined in class\");\n}\n\nEigen::VectorXd MatrixFreeOperator::diagonal() const\n{\n    Eigen::VectorXd D = Eigen::VectorXd::Zero(_size,1);\n    Eigen::VectorXd col_data;\n    for(int i=0; i<_size;i++) {\n        col_data = this->col(i);\n        D(i) = col_data(i);\n    }\n    return D;\n}\n\n// get the full matrix if we have to\nEigen::MatrixXd MatrixFreeOperator::get_full_mat() const\n{\n\tEigen::MatrixXd matrix = Eigen::MatrixXd::Zero(_size,_size);\n\n    #pragma openmp parallel for\n    for(int i=0; i<_size; i++){\n        matrix.col(i) = this->col(i);\n    }\n    return matrix; \n}\n\n\n\n", "meta": {"hexsha": "82c46cda8200da027a7af85d8ecad896cd3a4433", "size": 879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MatrixFreeOperator.cpp", "max_stars_repo_name": "NLESC-JCER/DavidsonEigen", "max_stars_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T17:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T17:40:44.000Z", "max_issues_repo_path": "src/MatrixFreeOperator.cpp", "max_issues_repo_name": "NLESC-JCER/DavidsonEigen", "max_issues_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-07T14:45:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-07T14:45:08.000Z", "max_forks_repo_path": "src/MatrixFreeOperator.cpp", "max_forks_repo_name": "NLESC-JCER/DavidsonEigen", "max_forks_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-30T22:56:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T09:05:37.000Z", "avg_line_length": 21.975, "max_line_length": 78, "alphanum_fraction": 0.6689419795, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5255401315090064}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Framework/TestingFramework.hpp\"\n\n#include <boost/rational.hpp>\n#include <cmath>\n#include <cstddef>\n#include <cstdint>\n#include <limits>\n#include <random>\n#include <set>\n#include <vector>\n\n#include \"ErrorHandling/Assert.hpp\"\n#include \"Framework/TestHelpers.hpp\"\n#include \"Utilities/FractionUtilities.hpp\"\n\nnamespace {\ntemplate <typename Source>\nstd::vector<typename Source::value_type> collect(\n    Source source, const size_t limit = std::numeric_limits<size_t>::max()) {\n  std::vector<typename Source::value_type> result;\n  for (size_t count = 0; count < limit and source; ++count, ++source) {\n    result.push_back(*source);\n  }\n  return result;\n}\n}  // namespace\n\nSPECTRE_TEST_CASE(\"Unit.Utilities.FractionUtilities.ContinuedFraction\",\n                  \"[Utilities][Unit]\") {\n  using Rational = boost::rational<int64_t>;\n\n  CHECK((std::vector<int64_t>{1, 2, 4, 2}) ==\n        collect(ContinuedFraction<Rational>(Rational(29, 20))));\n  CHECK((std::vector<int64_t>{0, 8}) ==\n        collect(ContinuedFraction<double>(0.125)));\n  CHECK((std::vector<int64_t>{-1, 1, 7}) ==\n        collect(ContinuedFraction<double>(-0.125)));\n  CHECK(std::vector<int64_t>(20, 1) ==\n        collect(ContinuedFraction<double>(0.5 * (1. + sqrt(5.))), 20));\n  CHECK((std::vector<int64_t>{0}) ==\n        collect(ContinuedFraction<Rational>(Rational(0))));\n  CHECK((std::vector<int64_t>{0}) == collect(ContinuedFraction<double>(0.)));\n\n  // Check that the iterator terminates because of precision loss.\n  CHECK(collect(ContinuedFraction<double>(0.5 * (1. + sqrt(5.))), 100).size() <\n        100);\n\n  // Check that the iterator doesn't terminate prematurely\n  // because of precision loss.\n  const int64_t two_to_the_fourty = 1099511627776;\n  CHECK(std::vector<int64_t>{0, two_to_the_fourty} ==\n        collect(ContinuedFraction<double>(1. / two_to_the_fourty)));\n  CHECK(std::vector<int64_t>{1, two_to_the_fourty} ==\n        collect(ContinuedFraction<double>(1 + 1. / two_to_the_fourty)));\n  CHECK(std::vector<int64_t>{0, two_to_the_fourty, 2} ==\n        collect(ContinuedFraction<double>(1. / (two_to_the_fourty + 0.5))));\n\n  MAKE_GENERATOR(gen);\n  {\n    std::uniform_real_distribution<> dist(-10., 10.);\n    const double value = dist(gen);\n    // Set the scale because the fractional part of a negative number\n    // (defined as `x - floor(x)`) can be larger than the number.\n    auto approx_value = approx.scale(std::abs(std::floor(value)))(value);\n    ContinuedFractionSummer<Rational> summer;\n    bool should_be_smaller = true;\n    std::vector<int64_t> terms{};  // Only for output\n    std::vector<double> convergents{};  // Only for output\n    for (ContinuedFraction<double> source(value); source; ++source) {\n      summer.insert(*source);\n      terms.push_back(*source);\n      convergents.push_back(boost::rational_cast<double>(summer.value()));\n      CAPTURE(terms);\n      CAPTURE(convergents);\n\n      // Convergents to a continued fraction always alternate between\n      // over- and underestimates.\n      if (convergents.back() != approx_value) {\n        if (should_be_smaller) {\n          CHECK(convergents.back() <= value);\n        } else {\n          CHECK(convergents.back() >= value);\n        }\n      }\n      should_be_smaller = !should_be_smaller;\n    }\n    CAPTURE(terms);\n    CAPTURE(convergents);\n    CHECK(convergents.back() == approx_value);\n  }\n}\n\nSPECTRE_TEST_CASE(\"Unit.Utilities.FractionUtilities.ContinuedFractionSummer\",\n                  \"[Utilities][Unit]\") {\n  using Rational = boost::rational<int>;\n\n  const auto check = [](const int num, const int denom) {\n    const Rational value(num, denom);\n    ContinuedFractionSummer<Rational> summer;\n    for (ContinuedFraction<Rational> source(value); source; ++source) {\n      summer.insert(*source);\n    }\n    CHECK(summer.value() == value);\n  };\n\n  check(0, 1);\n  check(1, 1);\n  check(2, 1);\n  check(1, 2);\n  check(2, 3);\n  check(29, 20);\n}\n\nSPECTRE_TEST_CASE(\n    \"Unit.Utilities.FractionUtilities.simplest_fraction_in_interval\",\n    \"[Utilities][Unit]\") {\n  using Rational = boost::rational<int>;\n\n  const int denom_max = 20;\n\n  std::set<Rational> fractions;\n  for (int d = 1; d <= denom_max; ++d) {\n    for (int n = 0; n <= d; ++n) {\n      fractions.emplace(n, d);\n    }\n  }\n\n  for (auto end1 = fractions.begin(); end1 != fractions.end(); ++end1) {\n    // Worse than any considered value so will be immediately replaced.\n    Rational simplest(1, denom_max + 1);\n    for (auto end2 = end1; end2 != fractions.end(); ++end2) {\n      if (*end1 == 0 and *end2 == 1) {\n        // Correct answer not clear for the entire interval\n        continue;\n      }\n      ASSERT(end2->denominator() != simplest.denominator(),\n             \"Answer is not unique\");\n      if (end2->denominator() < simplest.denominator()) {\n        simplest = *end2;\n      }\n      CHECK(simplest_fraction_in_interval<Rational>(*end1, *end2) == simplest);\n      CHECK(simplest_fraction_in_interval<Rational>(*end2, *end1) == simplest);\n    }\n  }\n\n  // Quick check of non-exact input\n  CHECK(simplest_fraction_in_interval<Rational>(0.6, 0.9) == Rational(2, 3));\n}\n", "meta": {"hexsha": "299277c6d059cd3b0c49ab0ac40b27c987f93efe", "size": 5161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/Utilities/Test_FractionUtilities.cpp", "max_stars_repo_name": "tomwlodarczyk/spectre", "max_stars_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_stars_repo_licenses": ["MIT"], "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/Utilities/Test_FractionUtilities.cpp", "max_issues_repo_name": "tomwlodarczyk/spectre", "max_issues_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_issues_repo_licenses": ["MIT"], "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/Utilities/Test_FractionUtilities.cpp", "max_forks_repo_name": "tomwlodarczyk/spectre", "max_forks_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_forks_repo_licenses": ["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.9539473684, "max_line_length": 79, "alphanum_fraction": 0.6547180779, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5254369215929888}}
{"text": "// Copyright (c) 2015-2016 Vittorio Romeo\n// License: Academic Free License (\"AFL\") v. 3.0\n// AFL License page: http://opensource.org/licenses/AFL-3.0\n// http://vittorioromeo.info | vittorio.romeo@outlook.com\n\n#pragma once\n\n#include <cstddef>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <tuple>\n#include <vector>\n#include <algorithm>\n#include <limits>\n#include <vrm/core/static_if.hpp>\n\n\n#undef ARMA_USE_ATLAS\n#include <armadillo>\n\n\n#include \"multiples.hpp\"\n#include \"equations.hpp\"\n#include \"folds.hpp\"\n#include \"representations.hpp\"\n#include \"sorted_vector.hpp\"\n\nnamespace nc\n{\n    // Tipo vuoto per segnalare al costruttore della classe `matrix` che essa\n    // deve essere inizializzata come matrice identit\u00e0.\n    struct init_identity\n    {\n    };\n\n    // Tipo vuoto per segnalare al costruttore della classe `matrix` che essa\n    // non deve essere inizializzata.\n    struct dont_init\n    {\n    };\n\n    // Classe che rappresenta una matrice di tipo `T0` le cui dimensioni sono\n    // conosciute a tempo di compilazione.\n    template <typename T0, std::size_t TRowCount, std::size_t TColumnCount>\n    class matrix\n    {\n    public:\n        using value_type = T0;\n\n        // Restituisce il numero delle righe.\n        constexpr static auto row_count() noexcept { return TRowCount; }\n\n        // Restituisce il numero delle colonne.\n        constexpr static auto column_count() noexcept { return TColumnCount; }\n\n    private:\n        // Dati della matrice: conservati in un `array` unidimensionale\n        // standard.\n        std::array<T0, TRowCount * TColumnCount> _data;\n\n        // Dati un indice di riga, ed un indice di colonna, calcola\n        // l'equivalente indice unidimensionale per accedere all'array dei dati.\n        auto calc_index(std::size_t row, std::size_t column) const noexcept\n        {\n            assert(row < row_count());\n            assert(column < column_count());\n\n            return column + column_count() * row;\n        }\n\n        // Dato un indice unidimensionale, restituisce una tupla di indici\n        // bidimensionali equivalenti all'accesso corretto all'array dei dati.\n        auto calc_1d_index(std::size_t i) const noexcept\n        {\n            assert(i >= 0 && column_count() != 0);\n\n            auto y(i / column_count());\n            return std::make_tuple(y, i - y * column_count());\n        }\n\n        // Implementazione dell'iterazione sugli indici di una riga della\n        // matrice.\n        // (Fissa la riga, ed itera su essa).\n        template <typename TSelf, typename TF>\n        static void impl_for_row_idxs(TSelf&& self, std::size_t i, TF&& f)\n        {\n            constexpr auto self_column_count(self.column_count());\n            for(auto j(0); j < self_column_count; ++j)\n            {\n                f(i, j);\n            }\n        }\n\n        // Implementazione dell'iterazione sugli indici di una colonna della\n        // matrice.\n        // (Fissa la colonna, ed itera su essa).\n        template <typename TSelf, typename TF>\n        static void impl_for_column_idxs(TSelf&& self, std::size_t j, TF&& f)\n        {\n            constexpr auto self_row_count(self.row_count());\n            for(auto i(0); i < self_row_count; ++i)\n            {\n                f(i, j);\n            }\n        }\n\n        // Implementazione dell'iterazione su tutti gli indici di una matrice.\n        template <typename TSelf, typename TF>\n        static void impl_for_idxs(TSelf&& self, TF&& f)\n        {\n            constexpr auto self_row_count(self.row_count());\n            constexpr auto self_column_count(self.column_count());\n\n            for(auto i(0); i < self_row_count; ++i)\n                for(auto j(0); j < self_column_count; ++j)\n                {\n                    f(i, j);\n                }\n        }\n\n        template <typename TSelf, typename TTpl>\n        static auto& impl_at(TSelf&& self, const TTpl& t)\n        {\n            return self(std::get<0>(t), std::get<1>(t));\n        }\n\n    public:\n        // Restituisce `true` se la matrice \u00e8 quadrata.\n        constexpr auto static is_square() noexcept\n        {\n            return row_count() == column_count();\n        }\n\n        // Esegue una funzione `f` su tutti gli indici della matrice.\n        template <typename TF>\n        void for_idxs(TF&& f)\n        {\n            impl_for_idxs(*this, FWD(f));\n        }\n        template <typename TF>\n        void for_idxs(TF&& f) const\n        {\n            impl_for_idxs(*this, FWD(f));\n        }\n\n        // Esegue una funzione `f` su tutti gli indici di una riga.\n        // (Fissa la riga, ed itera su essa).\n        template <typename TF>\n        void for_row_idxs(std::size_t i, TF&& f)\n        {\n            impl_for_row_idxs(*this, i, FWD(f));\n        }\n        template <typename TF>\n        void for_row_idxs(std::size_t i, TF&& f) const\n        {\n            impl_for_row_idxs(*this, i, FWD(f));\n        }\n\n        // Esegue una funzione `f` su tutti gli indici di una colonna.\n        // (Fissa la colonna, ed itera su essa).\n        template <typename TF>\n        void for_column_idxs(std::size_t j, TF&& f)\n        {\n            impl_for_column_idxs(*this, j, FWD(f));\n        }\n        template <typename TF>\n        void for_column_idxs(std::size_t j, TF&& f) const\n        {\n            impl_for_column_idxs(*this, j, FWD(f));\n        }\n\n        // Pulisce la matrice, settando tutti i valori a `0`.\n        void clear()\n        {\n            for_idxs([this](auto i, auto j)\n                {\n                    (*this)(i, j) = 0;\n                });\n        }\n\n        // Pulisce la matrice, settandola come matrice identit\u00e0. La matrice deve\n        // essere quadrata.\n        void clear_to_identity()\n        {\n            static_assert(is_square(), \"\");\n\n            clear();\n\n            for(auto k(0); k < row_count(); ++k)\n            {\n                (*this)(k, k) = 1;\n            }\n        }\n\n        // Construttori.\n        matrix(dont_init) {}\n        matrix() { clear(); }\n        matrix(init_identity) { clear_to_identity(); }\n\n        // Operazioni di copia (default).\n        matrix(const matrix& rhs) = default;\n        matrix& operator=(const matrix& rhs) = default;\n\n        // Operazioni di spostamento (default).\n        matrix(matrix&& rhs) = default;\n        matrix& operator=(matrix&& rhs) = default;\n\n        // Restituisce il valore della matrice contenuto negli indici\n        // rappresentati da una tupla.\n        template <typename TTpl>\n        auto& at(const TTpl& t)\n        {\n            return impl_at(*this, t);\n        }\n        template <typename TTpl>\n        const auto& at(const TTpl& t) const\n        {\n            return impl_at(*this, t);\n        }\n\n        // Restituisce il valore presente negli indici passati.\n        auto& operator()(std::size_t row, std::size_t column)\n        {\n            return _data[calc_index(row, column)];\n        }\n        const auto& operator()(std::size_t row, std::size_t column) const\n        {\n            return _data[calc_index(row, column)];\n        }\n\n        // Riempie i valori della matrice da un numero variadico di argomenti.\n        template <typename... Ts>\n        void set_from_variadic(Ts&&... xs)\n        {\n            // Controlla che il numero di argomenti sia valido.\n            static_assert(sizeof...(xs) <= row_count() * column_count(), \"\");\n\n            // TODO:\n            std::vector<T0> vec{xs...};\n            for(auto i(0u); i < vec.size(); ++i)\n            {\n                (*this).at(calc_1d_index(i)) = vec[i];\n            }\n        }\n\n    private:\n        // Implementazione di operazioni semplici (somma, sottrazione) tra due\n        // matrici della stessa grandezza.\n        template <typename T1, typename TF>\n        auto impl_simple_binary_op(\n            const matrix<T1, TRowCount, TColumnCount>& rhs, TF&& f) const\n        {\n            // Tipo in comune tra i valori delle due matrici.\n            using common = std::common_type_t<T0, T1>;\n\n            // Alloca una nuova matrice non-inizializzata.\n            matrix<common, TRowCount, TColumnCount> result{dont_init{}};\n\n            // Per ogni indice delle matrici, esegue la funzione passata.\n            // Converva il risultato nella nuova matrice.\n            for_idxs([this, &rhs, &result, &f](auto i, auto j)\n                {\n                    result(i, j) = f((*this)(i, j), rhs(i, j));\n                });\n\n            return result;\n        }\n\n    public:\n        // Overload dell'operatore `+` per la somma di due matrici.\n        template <typename T1>\n        auto operator+(const matrix<T1, TRowCount, TColumnCount>& rhs) const\n        {\n            return impl_simple_binary_op(rhs, [](const auto& lv, const auto& rv)\n                {\n                    return lv + rv;\n                });\n        }\n\n        // Overload dell'operatore `-` per la sottrazione di due matrici.\n        template <typename T1>\n        auto operator-(const matrix<T1, TRowCount, TColumnCount>& rhs) const\n        {\n            return impl_simple_binary_op(rhs, [](const auto& lv, const auto& rv)\n                {\n                    return lv - rv;\n                });\n        }\n\n        // Overload dell'operatore `==` per l'uguaglianza di due matrici.\n        template <typename T1>\n        auto operator==(const matrix<T1, TRowCount, TColumnCount>& rhs) const\n        {\n            for(auto i(0); i < row_count(); ++i)\n                for(auto j(0); j < column_count(); ++j)\n                    if((*this)(i, j) != rhs(i, j))\n                    {\n                        return false;\n                    }\n\n            return true;\n        }\n\n        // Overload dell'operatore `!=` per la disuguaglianza di due matrici.\n        template <typename T1>\n        auto operator!=(const matrix<T1, TRowCount, TColumnCount>& rhs) const\n        {\n            return !(*this == rhs);\n        }\n\n        // Overload dell'operatore `*` per la moltiplicazione di due matrici.\n        template <typename T1, std::size_t TRhsColumnCount>\n        auto operator*(\n            const matrix<T1, TColumnCount, TRhsColumnCount>& rhs) const\n        {\n            // Tipo in comune tra i valori delle due matrici.\n            using common = std::common_type_t<T0, T1>;\n\n            // Alloca una nuova matrice non-inizializzata.\n            matrix<common, TRowCount, TRhsColumnCount> result{dont_init{}};\n\n            // Itera su ogni indice della nuova matrice.\n            for(std::size_t ri(0); ri < TRowCount; ++ri)\n                for(std::size_t rj(0); rj < TRhsColumnCount; ++rj)\n                {\n                    // Accumulatore per il valore a `(ri, rj)`.\n                    common x(0);\n\n                    // Step di accumulazione.\n                    for(auto k(0); k < TColumnCount; ++k)\n                    {\n                        x += ((*this)(ri, k) * rhs(k, rj));\n                    }\n\n                    // Setta il valore nella nuova matrice.\n                    result(ri, rj) = x;\n                }\n\n            return result;\n        }\n\n    private:\n        // Restituisci la somma dei valore assoluti in una colonna.\n        auto sum_abs_value_in_column(std::size_t j) const noexcept\n        {\n            T0 res(0);\n            for(auto i(0); i < TRowCount; ++i)\n            {\n                res += abs((*this)(i, j));\n            }\n\n            return res;\n        }\n\n        // Restituisci la somma dei valore assoluti in una riga.\n        auto sum_abs_value_in_row(std::size_t i) const noexcept\n        {\n            T0 res(0);\n            for(auto j(0); j < TColumnCount; ++j)\n            {\n                res += abs((*this)(i, j));\n            }\n\n            return res;\n        }\n\n    public:\n        // Calcolo della norma 1.\n        auto norm_1() const noexcept\n        {\n            T0 curr_max(0);\n            for(auto j(0); j < TColumnCount; ++j)\n            {\n                curr_max = std::max(curr_max, sum_abs_value_in_column(j));\n            }\n\n            return curr_max;\n        }\n\n        // Calcolo della norma infinita.\n        auto norm_inf() const noexcept\n        {\n            T0 curr_max(0);\n            for(auto i(0); i < TRowCount; ++i)\n            {\n                curr_max = std::max(curr_max, sum_abs_value_in_row(i));\n            }\n\n            return curr_max;\n        }\n\n        // Calcolo della norma 2.\n        // (Utilizza la libreria \"armadillo\".)\n        auto norm_2() const noexcept\n        {\n            std::vector<double> v;\n            for(const auto& x : _data) v.emplace_back(x);\n\n            auto m = arma::mat::fixed<TRowCount, TColumnCount>(v.data());\n            return arma::norm(m, 2);\n        }\n\n        // Calcolo della norma di Frobenius.\n        auto norm_frobenius() const noexcept\n        {\n            double acc(0);\n            for(auto i(0); i < row_count(); ++i)\n            {\n                for(auto j(0); j < column_count(); ++j)\n                {\n                    acc += std::abs(std::pow((*this)(i, j), 2));\n                }\n            }\n\n            return std::sqrt(acc);\n        }\n\n        // Restituisce l'ordine della matrice. Se la matrice non \u00e8 quadrata,\n        // restituisce la dimensione minore.\n        constexpr auto static order() noexcept\n        {\n            return column_count() < row_count() ? column_count() : row_count();\n        }\n\n        // Calcolo del minore di una matrice (taglia una riga ed una colonna).\n        auto calc_minor(\n            std::size_t row_to_skip, std::size_t column_to_skip) const noexcept\n        {\n            // Alloca la matrice minore (ordine inferiore di 1).\n            matrix<T0, order() - 1, order() - 1> result{dont_init{}};\n\n            // Prossimi indici da riempire nella matrice nuova.\n            std::size_t target_column(0);\n            std::size_t target_row(0);\n\n            // Iteriamo sulle nostre righe.\n            loop_skipping(0, order(), row_to_skip, [&](auto i)\n                {\n                    target_column = 0;\n\n                    auto set_inner_column = [&](auto j)\n                    {\n                        // Settiamo il valore nella matrice nuova.\n                        result(target_row, target_column) = (*this)(i, j);\n                        ++target_column;\n                    };\n\n                    // Iteriamo sulle nostre colonne.\n                    // Loop che salta la j-esima colonna.\n                    // Setta i valori della matrice `result`.\n                    loop_skipping(\n                        0, this->order(), column_to_skip, set_inner_column);\n\n                    ++target_row;\n                });\n\n            return result;\n        }\n\n        // Calcolo del determinante.\n        auto determinant() const noexcept\n        {\n            using namespace vrm::core;\n\n            // Usiamo un `if` a tempo di compilazione per fermare la ricorsione\n            // nel caso base in cui il nostro ordine sia uguale a `1`.\n            return static_if(bool_v<(order() == 1)>)\n                .then([](const auto& x)\n                    {\n                        // Se l'ordine \u00e8 uguale a `1`, restitusci il valore in\n                        // alto a sinistra.\n                        return x(0, 0);\n                    })\n                .else_([](const auto& x)\n                    {\n                        // Altrimenti...\n                        T0 result(0);\n\n                        // Itera sulle nostre righe.\n                        for(int i = 0; i < order(); i++)\n                        {\n                            // Prendi il minore tagliando la prima riga e\n                            // l'i-esima colonna.\n                            auto my_minor(x.calc_minor(0, i));\n\n                            // Calcola il segno del prossimo coefficiente.\n                            auto sign(i % 2 == 1 ? -1.0 : 1.0);\n\n                            // Aggiungi il coefficiente per il determinante del\n                            // minore all'accumulatore. (Ricorsione.)\n                            result += sign * x(0, i) * my_minor.determinant();\n                        }\n\n                        return result;\n                    })(*this);\n        }\n\n        // Calcola la matrice inversa.\n        auto inverse() const noexcept\n        {\n            // Alloca matrice vuota della stessa dimensione.\n            matrix<T0, TRowCount, TColumnCount> result{dont_init{}};\n\n            using namespace vrm::core;\n\n            // Usiamo un `if` a tempo di compilazione per il caso speciale in\n            // cui il nostro ordine \u00e8 uguale a `1`.\n            static_if(bool_v<(order() == 1)>)\n                .then([&result](const auto& x)\n                    {\n                        // Se l'ordine \u00e8 uguale a `1`, setta il valore in alto a\n                        // sinistra della matrice risultato al reciproco di\n                        // quello della matrice corrente.\n                        result(0, 0) = 1.0 / x(0, 0);\n                    })\n                .else_([&result](const auto& x)\n                    {\n                        // Altrimenti, calcola il reciproco del determinante.\n                        auto rec_det(1.0 / x.determinant());\n\n                        // Itera sulle colonne.\n                        for(int j = 0; j < x.order(); j++)\n                        {\n                            // Itera sulle righe.\n                            for(int i = 0; i < x.order(); i++)\n                            {\n                                // Calcola il minore tagliando la riga j e la\n                                // colonna i.\n                                auto my_minor(x.calc_minor(j, i));\n\n                                // Calcola il segno del prossimo coefficiente.\n                                auto sign((i + j) % 2 == 1 ? -1.0 : 1.0);\n\n                                // Setta il valore della matrice risultato.\n                                result(i, j) =\n                                    sign * rec_det * my_minor.determinant();\n                            }\n                        }\n                    })(*this);\n\n            return result;\n        }\n\n        // Calcola l'indice di perturbazione.\n        auto perturbation_index() const noexcept\n        {\n            auto result(norm_2() * inverse().norm_2());\n\n            assert(result >= 1);\n            return result;\n        }\n\n        // Risolve un sistema lineare usando il metodo di eliminazione di Gauss.\n        auto solve_gauss() const noexcept\n        {\n            // La matrice deve avere una colonna in pi\u00f9 delle righe.\n            // (La colonna dei termini noti.)\n            static_assert(column_count() == row_count() + 1, \"\");\n            constexpr auto n(row_count());\n\n            // Creiamo una copia della matrice corrente.\n            auto a(*this);\n\n            // Itera sull'ordine.\n            for(std::size_t i(0); i < n; i++)\n            {\n                // Cerca l'indice del valore assoluto massimo nella colonna i.\n                auto max_element(abs(a(i, i)));\n                auto max_row_index(i);\n\n                // Itera sulle righe (iteratore `k`).\n                for(auto k(i + 1); k < n; k++)\n                {\n                    auto curr_element(abs(a(k, i)));\n                    if(curr_element > max_element)\n                    {\n                        // Aggiorna il pivot.\n                        max_element = curr_element;\n                        max_row_index = k;\n                    }\n                }\n\n                // Scambia riga dell'elemento massimo con la riga corrente.\n                // (Colonna per colonna.)\n                for(auto k(i); k < n + 1; k++)\n                {\n                    std::swap(a(max_row_index, k), a(i, k));\n                }\n\n                // Rende `0` tutti gli elementi sotto il pivot corrente.\n                for(auto k(i + 1); k < n; k++)\n                {\n                    // Calcoliamo il fattore di annullamento dell'elemento `(k,\n                    // i)` sotto il pivot.\n                    auto c(-a(k, i) / a(i, i));\n\n                    // Itera sui valori sotto il pivot.\n                    for(auto j(i); j < n + 1; j++)\n                    {\n                        if(i == j)\n                        {\n                            // Se ci troviamo sulla diagonale, possiamo settare\n                            // il valore sotto il pivot direttamente a zero.\n                            a(k, j) = 0;\n                        }\n                        else\n                        {\n                            // Altrimenti, usiamo il fattore di annullamento per\n                            // azzerare i valori sotto il pivot.\n                            a(k, j) += c * a(i, j);\n                        }\n                    }\n                }\n            }\n\n            // Alloca un vettore per i risultati.\n            matrix<T0, n, 1> x;\n\n            // Risolvi l'equazione `Ax=b`.\n            // La matrice `a` adesso \u00e8 triangolare superiore.\n            for(int i(n - 1); i >= 0; i--)\n            {\n                // Setta `i`-esimo risultato.\n                // `a(i, n)` \u00e8 inizialmente un termine noto.\n                // `a(i, i)` \u00e8 inizialmente il coefficiente di un'incognita.\n                x(i, 0) = a(i, n) / a(i, i);\n\n                // Backward substitution.\n                for(int k(i - 1); k >= 0; k--)\n                {\n                    a(k, n) -= a(k, i) * x(i, 0);\n                }\n            }\n\n            return x;\n        }\n\n        // Risolvi un sistema lineare tramite il metodo di Jacobi.\n        template <typename TF>\n        auto solve_jacobi(std::size_t max_iterations, accuracy_type accuracy,\n            TF loop_fn) const noexcept\n        {\n            // La matrice deve avere una colonna in pi\u00f9 delle righe.\n            // (La colonna dei termini noti.)\n            static_assert(column_count() == row_count() + 1, \"\");\n            constexpr auto n(row_count());\n\n            // Inizializza i vettori delle soluzioni.\n            using vector_type = matrix<accuracy_type, n, 1>;\n            vector_type temp_solution;\n            vector_type solution = temp_solution;\n\n            divergence_loop(max_iterations, accuracy,\n                [this, &solution, &temp_solution, n, loop_fn](\n                                auto& max_divergence)\n                {\n                    // Itera sulle righe.\n                    for(std::size_t i(0); i < TRowCount; i++)\n                    {\n                        // Prende l'i-esimo valore della riga.\n                        auto x((*this)(i, n));\n\n                        // Itera sulle colonne, saltando `i == j`.\n                        loop_skipping(0, n, i, [&](auto j)\n                            {\n                                // Formula della sommatoria.\n                                x -= (*this)(i, j) * solution(j, 0);\n                            });\n\n                        // Parte finale della formula.\n                        x /= (*this)(i, i);\n\n                        // Setta la `i`-esima soluzione a `x`.\n                        temp_solution(i, 0) = x;\n\n                        // Aggiorna la divergenza massima se necessario.\n                        update_max_divergence(\n                            i, temp_solution, solution, max_divergence);\n                    }\n\n                    // Sostituisce la soluzione precendente con quella corrente.\n                    solution = temp_solution;\n                    loop_fn(solution);\n                });\n\n            return solution;\n        }\n\n        auto solve_jacobi(std::size_t max_iterations = 100000,\n            accuracy_type accuracy = 0.0001) const noexcept\n        {\n            return solve_jacobi(max_iterations, accuracy, [](const auto&)\n                {\n                });\n        }\n\n        template <typename TSolutions, typename TF>\n        auto solve_gauss_seidel(TSolutions phi, std::size_t max_iterations,\n            accuracy_type accuracy, TF loop_fn)\n        {\n            // La matrice deve avere una colonna in pi\u00f9 delle righe.\n            // (La colonna dei termini noti.)\n            static_assert(column_count() == row_count() + 1, \"\");\n            constexpr auto n(row_count());\n\n            // Inizializza i vettori delle soluzioni.\n            using vector_type = TSolutions;\n            TSolutions temp_phi = phi;\n            double sigma;\n\n            divergence_loop(max_iterations, accuracy,\n                [this, &phi, &temp_phi, &sigma, n, loop_fn](\n                                auto& max_divergence)\n                {\n                    // Itera sulle righe.\n                    for(int i = 0; i < n; ++i)\n                    {\n                        // Accumulatore sommatoria.\n                        sigma = 0.0;\n\n                        // Itera sulle colonne.\n                        loop_skipping(0, n, i, [&](auto j)\n                            {\n                                // Formula della sommatoria.\n                                sigma += (*this)(i, j) * phi(j, 0);\n                            });\n\n                        phi(i, 0) = ((*this)(i, n) - sigma) / (*this)(i, i);\n\n                        // Aggiorna la divergenza massima se necessario.\n                        update_max_divergence(i, temp_phi, phi, max_divergence);\n                    }\n\n                    // Sostituisce la soluzione precendente con quella corrente.\n                    temp_phi = phi;\n                    loop_fn(phi);\n                });\n\n            return phi;\n        }\n\n        template <typename TSolutions>\n        auto solve_gauss_seidel(TSolutions phi,\n            std::size_t max_iterations = 100000,\n            accuracy_type accuracy = 0.0001)\n        {\n            return solve_gauss_seidel(phi, max_iterations, accuracy,\n                [](const auto&)\n                {\n                });\n        }\n\n        auto solve_gauss_seidel(std::size_t max_iterations = 100000,\n            accuracy_type accuracy = 0.0001)\n        {\n            constexpr auto n(row_count());\n\n            // Inizializza i vettori delle soluzioni.\n            using vector_type = matrix<accuracy_type, n, 1>;\n            vector_type phi;\n\n            return solve_gauss_seidel(phi, max_iterations, accuracy);\n        }\n    };\n}\n", "meta": {"hexsha": "b09afe8ed4d82249cf63ecbb8c7cf311916fbd1c", "size": 26285, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/matrix.hpp", "max_stars_repo_name": "SuperV1234/UNIME_numerical_calculus", "max_stars_repo_head_hexsha": "f8f481641b0dfd9c5062bc819e127bd4fedf6f30", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-06-30T14:03:37.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-30T14:03:37.000Z", "max_issues_repo_path": "include/matrix.hpp", "max_issues_repo_name": "SuperV1234/UNIME_numerical_calculus", "max_issues_repo_head_hexsha": "f8f481641b0dfd9c5062bc819e127bd4fedf6f30", "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/matrix.hpp", "max_forks_repo_name": "SuperV1234/UNIME_numerical_calculus", "max_forks_repo_head_hexsha": "f8f481641b0dfd9c5062bc819e127bd4fedf6f30", "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": 34.2698826597, "max_line_length": 80, "alphanum_fraction": 0.4746433327, "num_tokens": 6026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5254369172846659}}
{"text": "#include <iostream>\n#include <set>\n#include <stack>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/assignment.hpp>\n\nnamespace linkedListAlgorithms\n{      \n      using namespace std;\n      \n      template <typename keyType,typename valueType>\n      struct Node \n      {\n            Node<keyType,valueType> *right;\n            Node<keyType,valueType> *left;\n            keyType key;\n            valueType value;\n      };\n      \n      template <typename keyType,typename valueType>\n      void printLinkedList(Node<keyType,valueType> &root)\n      {\n            Node<keyType,valueType> *runner = &root;\n            while (runner!=0)\n            {\n                  cout << runner->key << \"->\";\n                  runner=runner->right;\n            }\n            cout << endl;\n      };\n\n      // 2.1\n      template <typename keyType,typename valueType>\n      void removeDuplicate(Node<keyType,valueType> &root)\n      {\n            set<keyType> keySet;\n            keySet.insert(root.key);\n            Node<keyType,valueType> *runner;\n            runner = &root;\n            \n            while (runner->right != 0)\n            {\n                  if (keySet.find(runner->right->key) != keySet.end()) //contains key\n                  { runner->right = runner->right->right; }\n                  else\n                  { \n                        keySet.insert(runner->right->key); \n                        runner = runner->right;\n                  }\n            }\n      };\n\n      // 2.2\n      // k=1 returns the last element \n      template <typename keyType,typename valueType>\n      Node<keyType,valueType>* returnKthToLast(Node<keyType,valueType> &root,int k)\n      {\n            Node<keyType,valueType> *runner = &root;\n            Node<keyType,valueType> *frontRunner = &root;\n            \n            for (int i=0;i<k;i++) \n            {\n                  if (frontRunner!=0) { frontRunner = frontRunner->right; }\n                  else { return NULL; }\n            }\n            \n            while (frontRunner!=0)\n            {\n                  frontRunner = frontRunner->right;\n                  runner = runner->right;\n            }\n            return runner;\n      };\n \n      template <typename keyType,typename valueType>\n      void printKthToLast(Node<keyType,valueType> &root,int k)\n      {\n            cout << returnKthToLast(root,k)->key << endl;\n      };\n\n      //2.3\n      // delete a node given only access to it; return true if successful, \n      // false if target is last element\n      template <typename keyType,typename valueType>\n      bool deleteNode(Node<keyType,valueType> &target)\n      {\n            if (target.right == 0) {return false;}\n            target.key = target.right->key;\n            target.value = target.right->value;\n            target.right = target.right->right;\n            return true;\n      };\n      \n      //2.5\n      Node<int,int>* add(Node<int,int> &num1, Node<int,int> &num2)\n      {\n            int carry = 0;\n            int sum = 0;\n            Node<int,int> *runner1, *runner2, *runner3, *result, *tail;\n            result  = new Node<int,int>();\n            runner1 = &num1;\n            runner2 = &num2;\n            runner3 = result;\n            \n            while (true)\n            {     \n                  sum = runner1->key + runner2->key;\n                  if ( sum > 9) \n                  { runner3->key = (sum % 10)+ carry; carry = 1; }\n                  else \n                  { runner3->key = sum+carry; carry = 0; }\n                  runner2 = runner2->right;\n                  runner1 = runner1->right;\n                  if (runner1==0 || runner2==0) {break;}\n                  else\n                  {\n                        runner3->right = new Node<int,int>();\n                        runner3 = runner3->right;\n                  }\n            }\n            if (runner1==0 && runner2==0 && carry==1)\n            {\n                  runner3->right = new Node<int,int>();\n                  runner3 = runner3->right;\n                  runner3->key = carry;\n            }\n            \n            tail = max(runner1,runner2);\n            if (tail!=0)\n            { runner3->right = tail; runner3->key += carry; }\n            \n            return result;\n      };\n      \n      \n      //2.7\n      // slow runner fast runner\n      template <typename keyType,typename valueType>\n      bool isPalindrome(Node<keyType,valueType> &head)\n      {\n            Node<keyType,valueType> *slowRunner,*fastRunner;\n            slowRunner = &head;\n            fastRunner = &head;\n            bool result = true;\n            stack<keyType> keyStack;\n            \n            while (fastRunner!=0 && fastRunner->right !=0)\n            {\n                  keyStack.push(slowRunner->key);\n                  slowRunner = slowRunner->right;\n                  fastRunner = fastRunner->right->right;\n            }\n            \n            if (fastRunner!=0) // odd number of elements\n            {  slowRunner = slowRunner->right; }\n            \n            while (slowRunner!=0)\n            {\n                  result = result && (slowRunner->key == keyStack.top());\n                  keyStack.pop();\n                  slowRunner = slowRunner->right;\n            }\n            \n            return result;\n      };\n};\n\n\nint main()\n{\n      using namespace linkedListAlgorithms;\n      using namespace boost::numeric::ublas;\n      \n      matrix<int> entries(13,1);\n      entries <<= 0,1,2,3,4,4,5,4,4,3,2,1,0;\n      \n      Node<int,int> root = {0,0,entries(0,0),0};\n      Node<int,int> *runner = &root; \n      for (int i=1;i<entries.size1();i++)\n      {\n            runner->right = new Node<int,int>(); \n            runner->right->key = entries(i,0);\n            runner = runner->right;\n      }\n      \n      Node<int,int> root1 = {0,0,9,0};\n      runner = &root1; \n      for (int i=2;i<10;i++)\n      {\n            runner->right = new Node<int,int>(); \n            runner->right->key = rand()%10;\n            runner = runner->right;\n      }\n      \n      printLinkedList(root);\n      //printLinkedList(root1);\n      //removeDuplicate(root);\n      //printLinkedList(root);\n      //printKthToLast(root,3);\n      // runner = returnKthToLast(root,8);\n      //if (deleteNode(*runner)) { printLinkedList(root); } \n      //printLinkedList(*add(root,root1));\n      cout << isPalindrome<int>(root) << endl;\n      return 0;\n}", "meta": {"hexsha": "dee9494e5b47ea149dca86fbab0a63fdb1f00721", "size": 6367, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/linkedListAlgorithms.cpp", "max_stars_repo_name": "chaohan/code-samples", "max_stars_repo_head_hexsha": "0ae7da954a36547362924003d56a8bece845802c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/linkedListAlgorithms.cpp", "max_issues_repo_name": "chaohan/code-samples", "max_issues_repo_head_hexsha": "0ae7da954a36547362924003d56a8bece845802c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/linkedListAlgorithms.cpp", "max_forks_repo_name": "chaohan/code-samples", "max_forks_repo_head_hexsha": "0ae7da954a36547362924003d56a8bece845802c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0585365854, "max_line_length": 85, "alphanum_fraction": 0.4713365792, "num_tokens": 1479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.7217432122827967, "lm_q1q2_score": 0.5254113474753919}}
{"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 \ntemplate <typename Matrix, typename Vector>\nvoid test(const char* A_string, const char* v_string, const Matrix& A, const Vector&x)\n{\n    using mtl::io::tout;\n    tout << \"\\n\" << A_string << \"ly sized matrix and \" << v_string << \"ly sized vector\\nA is\\n\" << A;\n\n    // asm(\"#mat_add begins here!\");\n    Matrix B(A + A);\n    // asm(\"#mat_add ends here!\");\n    tout << \"A+A = \\n\" << B;\n    MTL_THROW_IF(B[0][0] != 4.0, mtl::runtime_error(\"wrong result in matrix addition.\"));\n\n    // asm(\"#mat_mult begins here!\");\n    B= A * A;\n    // asm(\"#mat_mult ends here!\");\n    tout << \"A*A = \\n\" << B;\n    MTL_THROW_IF(B[0][0] != 16.0, mtl::runtime_error(\"wrong result in matrix product.\"));\n\n    // asm(\"#vec_add begins here!\");\n    Vector w(x + x);\n    // asm(\"#vec_add ends here!\");\n    tout << \"x = \" << x << \"\\nw = x+x = \" << w << \"\\n\";\n    MTL_THROW_IF(w[0] != 6.0, mtl::runtime_error(\"wrong result in vector addition.\"));\n\n    // asm(\"#mat_vec_mult begins here!\");\n    w= A * x;\n    // asm(\"#mat_vec_mult ends here!\");\n\n\n    tout << \"A*x = \" << w << \"\\n\";\n    MTL_THROW_IF(w[0] != 18.0, mtl::runtime_error(\"wrong result in matrix vector product.\"));\n}\n\n\nint main(int , char**)\n{\n    using namespace mtl;\n    typedef mtl::vec::parameters<tag::col_major, mtl::vec::fixed::dimension<2>, true> fvec_para;\n    typedef mat::parameters<tag::row_major, mtl::index::c_index, mtl::fixed::dimensions<2, 2>, true> fmat_para;\n\n    float ma[2][2]= {{2., 3.}, {4., 5.}}, va[2]= {3., 4.};\n    \n    dense2D<float>                   A_dyn(ma);\n    dense2D<float, fmat_para>        A_stat(ma);\n    dense_vector<float>              v_dyn(va);\n    dense_vector<float, fvec_para>   v_stat(va);\n\n    typedef mtl::vec::parameters<tag::col_major, mtl::vec::fixed::dimension<4>, true> fvec_para4;\n    dense_vector<double, fvec_para4>   v_stat4, w_stat4;\n    v_stat4= 3;\n\n    w_stat4= v_stat4 + v_stat4;\n    io::tout << \"w_stat4 is \" << w_stat4 << '\\n';\n\n    test(\"dynamic\", \"dynamic\", A_dyn, v_dyn);\n    test(\"dynamic\", \"static\", A_dyn, v_stat);\n    test(\"static\", \"dynamic\", A_stat, v_dyn);\n    test(\"static\", \"static\", A_stat, v_stat);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "80f1f13bbd96422c2c39905c0c33aec2a1608cd2", "size": 2646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/fixed_size_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/fixed_size_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/fixed_size_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.4936708861, "max_line_length": 111, "alphanum_fraction": 0.6024187453, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5254113344041581}}
{"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 <boost/math/ccmath/modf.hpp>\n#include \"test_compile_result.hpp\"\n\nvoid compile_and_link_test()\n{\n   float i_f;\n   check_result<float>(boost::math::ccmath::modf(1.0f, &i_f));\n\n   double i_d;\n   check_result<double>(boost::math::ccmath::modf(1.0, &i_d));\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   long double i_ld;\n   check_result<long double>(boost::math::ccmath::modf(1.0l, &i_ld));\n#endif\n}\n", "meta": {"hexsha": "ac23cb73bc2075d91339015841887db19f290c42", "size": 640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/ccmath_modf_incl_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/compile_test/ccmath_modf_incl_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/compile_test/ccmath_modf_incl_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": 29.0909090909, "max_line_length": 69, "alphanum_fraction": 0.728125, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5253893745636762}}
{"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://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#include <algorithm>\n#include <iostream>\n#include <vector>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/algorithm/copy.hpp>\n#include <boost/compute/algorithm/sort.hpp>\n#include <boost/compute/container/vector.hpp>\n\nnamespace compute = boost::compute;\n\nint rand_int()\n{\n    return rand() % 100;\n}\n\n// this example demonstrates how to sort a vector of ints on the GPU\nint main()\n{\n    // create vector of random values on the host\n    std::vector<int, mi_stl_allocator<int>> host_vector(10);\n    std::generate(host_vector.begin(), host_vector.end(), rand_int);\n\n    // print out input vector\n    std::cout << \"input:  [ \";\n    for (size_t i = 0; i < host_vector.size(); i++)\n    {\n        std::cout << host_vector[i];\n\n        if (i != host_vector.size() - 1)\n        {\n            std::cout << \", \";\n        }\n    }\n    std::cout << \" ]\" << std::endl;\n\n    // transfer the values to the device\n    compute::vector<int> device_vector = host_vector;\n\n    // sort the values on the device\n    compute::sort(device_vector.begin(), device_vector.end());\n\n    // transfer the values back to the host\n    compute::copy(device_vector.begin(),\n                  device_vector.end(),\n                  host_vector.begin());\n\n    // print out the sorted vector\n    std::cout << \"output: [ \";\n    for (size_t i = 0; i < host_vector.size(); i++)\n    {\n        std::cout << host_vector[i];\n\n        if (i != host_vector.size() - 1)\n        {\n            std::cout << \", \";\n        }\n    }\n    std::cout << \" ]\" << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "41174bd4d91afffdda4c8927a9d2a9dce16b7ee0", "size": 1983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "compute/example/sort_vector.cpp", "max_stars_repo_name": "atksh/mimalloc-lgb", "max_stars_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "compute/example/sort_vector.cpp", "max_issues_repo_name": "atksh/mimalloc-lgb", "max_issues_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compute/example/sort_vector.cpp", "max_forks_repo_name": "atksh/mimalloc-lgb", "max_forks_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_forks_repo_licenses": ["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.1643835616, "max_line_length": 79, "alphanum_fraction": 0.5552193646, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.5253893698030455}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <boost/math/special_functions/hermite.hpp>\n#include <eve/function/hermite.hpp>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/platform.hpp>\n#include <cmath>\n\nTTS_CASE_TPL(\"Check eve::hermite return type\", EVE_TYPE)\n{\n  TTS_EXPR_IS(eve::hermite(0, T(0)), T);\n}\n\nTTS_CASE_TPL(\"Check eve::hermite behavior\", EVE_TYPE)\n{\n\n  auto eve__hermite =  [](auto n, auto x) { return eve::hermite(n, x); };\n  auto boost_hermite =  [](auto n, auto x) { return boost::math::hermite(n, x); };\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__hermite(2u, eve::minf(eve::as<T>())), eve::inf(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__hermite(2u, eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__hermite(3u, eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__hermite(3u, eve::inf(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__hermite(3u, eve::inf(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n\n  for(unsigned int i=0; i < 10; ++i)\n  {\n    TTS_ULP_EQUAL(eve__hermite(i, T(10)), T(boost_hermite(i, 10)), 1);\n    TTS_ULP_EQUAL(eve__hermite(i, T(5)), T(boost_hermite(i, 5)), 1);\n    TTS_ULP_EQUAL(eve__hermite(i, T(2)), T(boost_hermite(i, 2)), 1);\n    TTS_ULP_EQUAL(eve__hermite(i, T(1)), T(boost_hermite(i, 1)), 1);\n    TTS_ULP_EQUAL(eve__hermite(i, T(0)), T(boost_hermite(i, 0)), 1);\n  }\n}\n", "meta": {"hexsha": "659dabca80c3e4ed4e69ac007017f3dc3df29281", "size": 1762, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/core/hermite/regular/hermite.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "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/real/core/hermite/regular/hermite.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "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/real/core/hermite/regular/hermite.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["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.0454545455, "max_line_length": 100, "alphanum_fraction": 0.5766174801, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5253893526067879}}
{"text": "#pragma once\n\n#include <cstdint>\n#include <Eigen/Dense>\n\n// todo improve documentation on these\nclass RobotEstimator {\nprivate:\n    // X Y W bot velocities (m/s)\n    static constexpr int numStates = 3;\n\n    // Motor duty cycles (% max)\n    static constexpr int numInputs = 4;\n\n    // Motor encoders (rad/s), gyro angular vel (rad/s)\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<double, 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<double, numOutputs, 1> z);\n\n    /**\n     * @param state Matrix that the current guess will be saved into\n     */\n    void getState(Eigen::Matrix<double, numStates, 1>& state);\n\nprivate:\n    static constexpr double processNoise = 0.05;\n    static constexpr double encoderNoise = 0.04;\n    static constexpr double gyroNoise = 0.005;\n    static constexpr double initCovariance = 10.0;\n\n    Eigen::Matrix<double, numStates,  numStates>  F;\n    Eigen::Matrix<double, numStates,  numInputs>  B;\n    Eigen::Matrix<double, numOutputs, numStates>  H;\n    Eigen::Matrix<double, numStates,  numStates>  Q;\n    Eigen::Matrix<double, numOutputs, numOutputs> R;\n    Eigen::Matrix<double, numStates,  numStates>  P;\n\n    // Identity\n    Eigen::Matrix<double, numStates, numStates> I;\n\n    // Current estimate\n    Eigen::Matrix<double, numStates, 1> x_hat;\n};", "meta": {"hexsha": "bddd6666505b7a64110e647dcd63d0a1a9738bf5", "size": 1744, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "robot/control/Inc/motion-control/RobotEstimator.hpp", "max_stars_repo_name": "guyfleeman/robocup-firmware", "max_stars_repo_head_hexsha": "11e1e773cb9c549349fd2ad76939d6485b04590f", "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": "robot/control/Inc/motion-control/RobotEstimator.hpp", "max_issues_repo_name": "guyfleeman/robocup-firmware", "max_issues_repo_head_hexsha": "11e1e773cb9c549349fd2ad76939d6485b04590f", "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": "robot/control/Inc/motion-control/RobotEstimator.hpp", "max_forks_repo_name": "guyfleeman/robocup-firmware", "max_forks_repo_head_hexsha": "11e1e773cb9c549349fd2ad76939d6485b04590f", "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.6825396825, "max_line_length": 68, "alphanum_fraction": 0.6559633028, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5253365649739538}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/sum.hpp\n *\n * \\brief The \\c sum operation.\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_SUM_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_SUM_HPP\n\n\n#include <boost/numeric/ublas/detail/config.hpp>\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublasx/operation/begin.hpp>\n#include <boost/numeric/ublasx/operation/end.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/ublas/traits.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <cstddef>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\n//@{ Declarations\n\n//XXX: already implemented in vector_expression.hpp\n///**\n// * \\brief Compute the sum of the elements of the given vector expression.\n// * \\tparam VectorExprT The type of the vector expression.\n// * \\param ve The vector expression whose elements are summed up.\n// * \\return The sum of the elements of the vector expression.\n// *\n// * \\author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt;\n// */\n//template <typename VectorExprT>\n//typename vector_traits<VectorExprT>::value_type sum(vector_expression<VectorExprT> const& ve);\nusing ::boost::numeric::ublas::sum;\n\n\n/**\n * \\brief Compute the sum of the elements of the given matrix expression.\n * \\tparam MatrixExprT The type of the matrix expression.\n * \\param ve The matrix expression whose elements are summed up.\n * \\return The sum of the elements of the matrix expression.\n *\n * \\author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt;\n */\ntemplate <typename MatrixExprT>\ntypename matrix_traits<MatrixExprT>::value_type sum_all(matrix_expression<MatrixExprT> const& me);\n\n\n/**\n * \\brief Compute the sum of the elements over each column of the given matrix\n *  expression.\n * \\tparam MatrixExprT The type of the matrix expression.\n * \\param me The matrix expression whose elements are summed up by row.\n * \\return A vector containing the sum of the elements over each column in the\n *  given matrix expression.\n *\n * \\author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt;\n */\ntemplate <typename MatrixExprT>\nvector<typename matrix_traits<MatrixExprT>::value_type> sum(matrix_expression<MatrixExprT> const& me);\n\n\n/**\n * \\brief Compute the sum of the elements over each column in the given matrix\n *  expression.\n * \\tparam MatrixExprT The type of the matrix expression.\n * \\param me The matrix expression whose elements are summed up by row.\n * \\return A vector containing the sum of the elements over each column in the\n *  given matrix expression.\n *\n * \\author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt;\n */\ntemplate <typename MatrixExprT>\nvector<typename matrix_traits<MatrixExprT>::value_type> sum_rows(matrix_expression<MatrixExprT> const& me);\n\n\n/**\n * \\brief Compute the sum of the elements over each row in the given matrix\n *  expression.\n * \\tparam MatrixExprT The type of the matrix expression.\n * \\param me The matrix expression whose elements are summed up by column.\n * \\return A vector containing the sum of the elements over each row in the\n *  given matrix expression.\n *\n * \\author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt;\n */\ntemplate <typename MatrixExprT>\nvector<typename matrix_traits<MatrixExprT>::value_type> sum_columns(matrix_expression<MatrixExprT> const& me);\n\n\n/**\n * \\brief Compute the sum of the elements of the given matrix expression along\n *  the given dimension tag.\n * \\tparam MatrixExprT The type of the matrix expression.\n * \\param me The matrix expression whose elements are summed up by the given\n *  dimension.\n * \\return A vector containing the sum of the elements along the given dimension\n *  in the given matrix expression.\n *\n * \\author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt;\n */\ntemplate <typename TagT, typename MatrixExprT>\nvector<typename matrix_traits<MatrixExprT>::value_type> sum_by_tag(matrix_expression<MatrixExprT> const& me);\n\n//@} Declarations\n\n\nnamespace detail { namespace /*<unnamed>*/ {\n\n//@{ Declarations\n\n/**\n * \\brief Auxiliary class for computing the sum of the elements along the given\n *  dimension for a container of the given category.\n * \\tparam Dim The dimension number (starting from 1).\n * \\tparam CategoryT The category type (e.g., vector_tag).\n */\ntemplate < ::std::size_t Dim, typename CategoryT>\nstruct sum_by_dim_impl;\n\n/**\n * \\brief Auxiliary class for computing the sum of the elements along the given\n *  dimension tag for a container of the given category.\n * \\tparam TagT The dimension tag type (e.g., tag::major).\n * \\tparam CategoryT The category type (e.g., vector_tag).\n * \\tparam OrientationT The orientation category type (e.g., row_major_tag).\n */\ntemplate <typename TagT, typename CategoryT, typename OrientationT>\nstruct sum_by_tag_impl;\n\n//@} Declarations\n\n\n//@{ Definitions\n\ntemplate <>\nstruct sum_by_dim_impl<1, vector_tag>\n{\n\ttemplate <typename VectorExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename vector_traits<VectorExprT>::value_type> apply(vector_expression<VectorExprT> const& ve)\n\t{\n\t\ttypedef typename vector_traits<VectorExprT>::value_type value_type;\n\n\t\tvector<value_type> res(1);\n\n\t\tres(0) = sum(ve);\n\n\t\treturn res;\n\t}\n};\n\n\ntemplate <>\nstruct sum_by_dim_impl<1, matrix_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn sum_rows(me);\n\t}\n};\n\n\ntemplate <>\nstruct sum_by_dim_impl<2, matrix_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn sum_columns(me);\n\t}\n};\n\n\ntemplate <>\nstruct sum_by_tag_impl<tag::major, matrix_tag, row_major_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn sum_rows(me);\n\t}\n};\n\n\ntemplate <>\nstruct sum_by_tag_impl<tag::minor, matrix_tag, row_major_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn sum_columns(me);\n\t}\n};\n\n\ntemplate <>\nstruct sum_by_tag_impl<tag::leading, matrix_tag, row_major_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn sum_columns(me);\n\t}\n};\n\n\ntemplate <>\nstruct sum_by_tag_impl<tag::major, matrix_tag, column_major_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn sum_columns(me);\n\t}\n};\n\n\ntemplate <>\nstruct sum_by_tag_impl<tag::minor, matrix_tag, column_major_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn sum_rows(me);\n\t}\n};\n\n\ntemplate <>\nstruct sum_by_tag_impl<tag::leading, matrix_tag, column_major_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn sum_rows(me);\n\t}\n};\n\n\ntemplate <typename TagT>\nstruct sum_by_tag_impl<TagT, matrix_tag, unknown_orientation_tag>: sum_by_tag_impl<TagT, matrix_tag, row_major_tag>\n{\n\t// Empty\n};\n\n//@} Definitions\n\n}} // Namespace detail::<unnamed>\n\n\n//@{ Definitions\n\n//XXX: already implemented in vector_expression.hpp\n//template <typename VectorExprT>\n//BOOST_UBLAS_INLINE\n//typename vector_traits<VectorExprT>::value_type sum(vector_expression<VectorExprT> const& ve)\n//{\n//\ttypedef typename vector_traits<VectorExprT>::const_iterator iterator_type;;\n//\ttypedef typename vector_traits<VectorExprT>::value_type value_type;\n//\n//\titerator_type it_end = end(ve);\n//\tvalue_type s = 0;\n//\n//\tfor (iterator_type it = begin(ve); it != it_end; ++it)\n//\t{\n//\t\ts += *it;\n//\t}\n//\n//\treturn s;\n//}\n\n\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<MatrixExprT>::value_type sum_all(matrix_expression<MatrixExprT> const& me)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::size_type size_type;\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\n\tsize_type nr = num_rows(me);\n\tsize_type nc = num_columns(me);\n\n\tvalue_type s = 0;\n\tfor (size_type r = 0; r < nr; ++r)\n\t{\n\t\tfor (size_type c = 0; c < nc; ++c)\n\t\t{\n\t\t\ts += me()(r,c);\n\t\t}\n\t}\n\n\treturn s;\n}\n\n\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\nvector<typename matrix_traits<MatrixExprT>::value_type> sum(matrix_expression<MatrixExprT> const& me)\n{\n\treturn sum_rows(me);\n}\n\n\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\nvector<typename matrix_traits<MatrixExprT>::value_type> sum_rows(matrix_expression<MatrixExprT> const& me)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::size_type size_type;\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\n\tsize_type nr = num_rows(me);\n\tsize_type nc = num_columns(me);\n\n\tvector<value_type> s(nc);\n\tsize_type j = 0;\n\tfor (size_type c = 0; c < nc; ++c)\n\t{\n\t\t//s(j++) = sum(column(me, c)); //FIXME: don't work\n\n\t\tvalue_type cs = 0;\n\t\tfor (size_type r = 0; r < nr; ++r)\n\t\t{\n\t\t\tcs += me()(r,c);\n\t\t}\n\t\ts(j++) = cs;\n\t}\n\n\treturn s;\n}\n\n\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\nvector<typename matrix_traits<MatrixExprT>::value_type> sum_columns(matrix_expression<MatrixExprT> const& me)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::size_type size_type;\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\n\tsize_type nr = num_rows(me);\n\tsize_type nc = num_columns(me);\n\n\tvector<value_type> s(nr);\n\tsize_type j = 0;\n\tfor (size_type r = 0; r < nr; ++r)\n\t{\n\t\t//s(j++) = sum(row(me, r)); // FIXME don't work\n\n\t\tvalue_type rs = 0;\n\t\tfor (size_type c = 0; c < nc; ++c)\n\t\t{\n\t\t\trs += me()(r,c);\n\t\t}\n\t\ts(j++) = rs;\n\t}\n\n\treturn s;\n}\n\n\ntemplate <size_t Dim, typename VectorExprT>\nBOOST_UBLAS_INLINE\nvector<typename vector_traits<VectorExprT>::value_type> sum(vector_expression<VectorExprT> const& ve)\n{\n\treturn detail::sum_by_dim_impl<Dim, vector_tag>::template apply(ve);\n}\n\n\ntemplate <size_t Dim, typename MatrixExprT>\nBOOST_UBLAS_INLINE\nvector<typename matrix_traits<MatrixExprT>::value_type> sum(matrix_expression<MatrixExprT> const& me)\n{\n\treturn detail::sum_by_dim_impl<Dim, matrix_tag>::template apply(me);\n}\n\n\ntemplate <typename TagT, typename MatrixExprT>\n//template <typename MatrixExprT, typename TagT>\nBOOST_UBLAS_INLINE\nvector<typename matrix_traits<MatrixExprT>::value_type> sum_by_tag(matrix_expression<MatrixExprT> const& me)\n{\n\treturn detail::sum_by_tag_impl<TagT, matrix_tag, typename matrix_traits<MatrixExprT>::orientation_category>::template apply(me);\n}\n\n//@} Definitions\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_SUM_HPP\n", "meta": {"hexsha": "160b52ea783e06d16c6000afce11081a8b9273fc", "size": 11442, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/sum.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/sum.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/sum.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4388489209, "max_line_length": 129, "alphanum_fraction": 0.7538891802, "num_tokens": 2888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5253346040558216}}
{"text": "/*-----------------------------------------------------------------------------+\r\nInterval Container Library\r\nAuthor: Joachim Faulhaber\r\nCopyright (c) 2007-2010: 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 dynamic_interval.cpp \\file dynamic_interval.cpp\r\n    \\brief Intervals with dynamic interval bounds that can be changed at runtime.\r\n\r\n    Intervals types with dynamic interval bounds can represent closed and\r\n    open interval borders. Interval borders are not static or fixed for\r\n    the type but may change due to computations in interval containers.\r\n    Dynamically bounded intervals are the library default for interval\r\n    parameters in interval containers.\r\n\r\n    \\include dynamic_interval_/dynamic_interval.cpp\r\n*/\r\n//[example_dynamic_interval\r\n#include <iostream>\r\n#include <string>\r\n#include <math.h>\r\n#include <boost/type_traits/is_same.hpp>\r\n\r\n#include <boost/icl/interval_set.hpp>\r\n#include <boost/icl/split_interval_set.hpp>\r\n// Dynamically bounded intervals 'discrete_interval' and 'continuous_interval'\r\n// are indirectly included via interval containers as library defaults.\r\n#include \"../toytime.hpp\"\r\n#include <boost/icl/rational.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\nusing namespace boost::icl;\r\n\r\nint main()\r\n{\r\n    cout << \">>Interval Container Library: Sample interval.cpp <<\\n\";\r\n    cout << \"----------------------------------------------------\\n\";\r\n\r\n    // Dynamically bounded intervals are the library default for \r\n    // interval parameters in interval containers.\r\n    BOOST_STATIC_ASSERT((\r\n        boost::is_same< interval_set<int>::interval_type\r\n                      , discrete_interval<int> >::value\r\n                      )); \r\n\r\n\r\n    BOOST_STATIC_ASSERT((\r\n        boost::is_same< interval_set<float>::interval_type\r\n                      , continuous_interval<float> >::value\r\n                      )); \r\n\r\n    // As we can see the library default chooses the appropriate\r\n    // class template instance discrete_interval<T> or continuous_interval<T>\r\n    // dependent on the domain_type T. The library default for intervals\r\n    // is also available via the template 'interval':\r\n    BOOST_STATIC_ASSERT((\r\n        boost::is_same< interval<int>::type\r\n                      , discrete_interval<int> >::value\r\n                      )); \r\n\r\n    BOOST_STATIC_ASSERT((\r\n        boost::is_same< interval<float>::type\r\n                      , continuous_interval<float> >::value\r\n                      )); \r\n\r\n    // template interval also provides static functions for the four border types\r\n\r\n    interval<int>::type    int_interval  = interval<int>::closed(3, 7);\r\n    interval<double>::type sqrt_interval = interval<double>::right_open(1/sqrt(2.0), sqrt(2.0));\r\n    interval<string>::type city_interval = interval<string>::left_open(\"Barcelona\", \"Boston\");\r\n    interval<Time>::type   time_interval = interval<Time>::open(Time(monday,8,30), Time(monday,17,20));\r\n\r\n    cout << \"----- Dynamically bounded intervals ----------------------------------------\\n\";\r\n    cout << \"  discrete_interval<int>   : \" << int_interval  << endl;\r\n    cout << \"continuous_interval<double>: \" << sqrt_interval << \" does \" \r\n                                            << string(contains(sqrt_interval, sqrt(2.0))?\"\":\"NOT\") \r\n                                            << \" contain sqrt(2)\" << endl;\r\n    cout << \"continuous_interval<string>: \" << city_interval << \" does \"  \r\n                                            << string(contains(city_interval,\"Barcelona\")?\"\":\"NOT\") \r\n                                            << \" contain 'Barcelona'\" << endl;\r\n    cout << \"continuous_interval<string>: \" << city_interval << \" does \"  \r\n                                            << string(contains(city_interval, \"Berlin\")?\"\":\"NOT\") \r\n                                            << \" contain 'Berlin'\" << endl;\r\n    cout << \"  discrete_interval<Time>  : \" << time_interval << \"\\n\\n\";\r\n\r\n    // Using dynamically bounded intervals allows to apply operations\r\n    // with intervals and also with elements on all interval containers \r\n    // including interval containers of continuous domain types:\r\n\r\n    interval<rational<int> >::type unit_interval \r\n        = interval<rational<int> >::right_open(rational<int>(0), rational<int>(1));\r\n    interval_set<rational<int> > unit_set(unit_interval);\r\n    interval_set<rational<int> > ratio_set(unit_set);\r\n    ratio_set -= rational<int>(1,3); // Subtract 1/3 from the set\r\n\r\n    cout << \"----- Manipulation of single values in continuous sets ---------------------\\n\";\r\n    cout << \"1/3 subtracted from [0..1) : \" << ratio_set << endl;\r\n    cout << \"The set does \" << string(contains(ratio_set, rational<int>(1,3))?\"\":\"NOT\") \r\n                                            << \" contain '1/3'\" << endl;\r\n    ratio_set ^= unit_set;\r\n    cout << \"Flipping the holey set     : \" << ratio_set << endl;\r\n    cout << \"yields the subtracted      :     1/3\\n\\n\";\r\n\r\n    // Of course we can use interval types that are different from the\r\n    // library default by explicit instantiation:\r\n    split_interval_set<int, std::less, closed_interval<Time> > intuitive_times;\r\n    // Interval set 'intuitive_times' uses statically bounded closed intervals\r\n    intuitive_times += closed_interval<Time>(Time(monday,  9,00), Time(monday, 10,59));\r\n    intuitive_times += closed_interval<Time>(Time(monday, 10,00), Time(monday, 11,59));\r\n    cout << \"----- Here we are NOT using the library default for intervals --------------\\n\";\r\n    cout << intuitive_times << endl;\r\n\r\n    return 0;\r\n}\r\n\r\n// Program output:\r\n//>>Interval Container Library: Sample interval.cpp <<\r\n//----------------------------------------------------\r\n//----- Dynamically bounded intervals ----------------------------------------\r\n//  discrete_interval<int>   : [3,7]\r\n//continuous_interval<double>: [0.707107,1.41421) does NOT contain sqrt(2)\r\n//continuous_interval<string>: (Barcelona,Boston] does NOT contain 'Barcelona'\r\n//continuous_interval<string>: (Barcelona,Boston] does  contain 'Berlin'\r\n//  discrete_interval<Time>  : (mon:08:30,mon:17:20)\r\n//\r\n//----- Manipulation of single values in continuous sets ---------------------\r\n//1/3 subtracted from [0..1) : {[0/1,1/3)(1/3,1/1)}\r\n//The set does NOT contain '1/3'\r\n//Flipping the holey set     : {[1/3,1/3]}\r\n//yields the subtracted      :     1/3\r\n//\r\n//----- Here we are NOT using the library default for intervals --------------\r\n//{[mon:09:00,mon:09:59][mon:10:00,mon:10:59][mon:11:00,mon:11:59]}\r\n//]\r\n\r\n", "meta": {"hexsha": "d74e1afa7b8630fbc9a33a9781b0384ff9632dc0", "size": 6899, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/icl/example/dynamic_interval_/dynamic_interval.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/dynamic_interval_/dynamic_interval.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/dynamic_interval_/dynamic_interval.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": 48.9290780142, "max_line_length": 104, "alphanum_fraction": 0.5816785041, "num_tokens": 1478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5253345996500818}}
{"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://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestScan\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/lambda.hpp>\n#include <boost/compute/system.hpp>\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/algorithm/copy.hpp>\n#include <boost/compute/algorithm/exclusive_scan.hpp>\n#include <boost/compute/algorithm/inclusive_scan.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/iterator/counting_iterator.hpp>\n#include <boost/compute/iterator/transform_iterator.hpp>\n\n#include \"check_macros.hpp\"\n#include \"context_setup.hpp\"\n\nnamespace bc = boost::compute;\n\nBOOST_AUTO_TEST_CASE(inclusive_scan_int)\n{\n    int data[] = { 1, 2, 1, 2, 3 };\n    bc::vector<int> vector(data, data + 5, queue);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(5));\n\n    bc::vector<int> result(5, context);\n    BOOST_CHECK_EQUAL(result.size(), size_t(5));\n\n    // inclusive scan\n    bc::inclusive_scan(vector.begin(), vector.end(), result.begin());\n    CHECK_RANGE_EQUAL(int, 5, result, (1, 3, 4, 6, 9));\n\n    // in-place inclusive scan\n    CHECK_RANGE_EQUAL(int, 5, vector, (1, 2, 1, 2, 3));\n    bc::inclusive_scan(vector.begin(), vector.end(), vector.begin());\n    CHECK_RANGE_EQUAL(int, 5, vector, (1, 3, 4, 6, 9));\n}\n\nBOOST_AUTO_TEST_CASE(exclusive_scan_int)\n{\n    int data[] = { 1, 2, 1, 2, 3 };\n    bc::vector<int> vector(data, data + 5, queue);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(5));\n\n    bc::vector<int> result(5, context);\n    BOOST_CHECK_EQUAL(vector.size(), size_t(5));\n\n    // exclusive scan\n    bc::exclusive_scan(vector.begin(), vector.end(), result.begin());\n    CHECK_RANGE_EQUAL(int, 5, result, (0, 1, 3, 4, 6));\n\n    // in-place exclusive scan\n    CHECK_RANGE_EQUAL(int, 5, vector, (1, 2, 1, 2, 3));\n    bc::exclusive_scan(vector.begin(), vector.end(), vector.begin());\n    CHECK_RANGE_EQUAL(int, 5, vector, (0, 1, 3, 4, 6));\n}\n\nBOOST_AUTO_TEST_CASE(inclusive_scan_int2)\n{\n    using boost::compute::int2_;\n\n    int data[] = { 1, 2,\n                   3, 4,\n                   5, 6,\n                   7, 8,\n                   9, 0 };\n\n    boost::compute::vector<int2_> input(reinterpret_cast<int2_*>(data),\n                                        reinterpret_cast<int2_*>(data) + 5);\n    BOOST_CHECK_EQUAL(input.size(), size_t(5));\n\n    boost::compute::vector<int2_> output(5);\n    boost::compute::inclusive_scan(input.begin(), input.end(), output.begin());\n    CHECK_RANGE_EQUAL(\n        int2_, 5, output,\n        (int2_(1, 2), int2_(4, 6), int2_(9, 12), int2_(16, 20), int2_(25, 20))\n    );\n}\n\nBOOST_AUTO_TEST_CASE(inclusive_scan_counting_iterator)\n{\n    bc::vector<int> result(10, context);\n    bc::inclusive_scan(bc::make_counting_iterator(1),\n                       bc::make_counting_iterator(11),\n                       result.begin());\n    CHECK_RANGE_EQUAL(int, 10, result, (1, 3, 6, 10, 15, 21, 28, 36, 45, 55));\n}\n\nBOOST_AUTO_TEST_CASE(exclusive_scan_counting_iterator)\n{\n    bc::vector<int> result(10, context);\n    bc::exclusive_scan(bc::make_counting_iterator(1),\n                       bc::make_counting_iterator(11),\n                       result.begin());\n    CHECK_RANGE_EQUAL(int, 10, result, (0, 1, 3, 6, 10, 15, 21, 28, 36, 45));\n}\n\nBOOST_AUTO_TEST_CASE(inclusive_scan_transform_iterator)\n{\n    float data[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };\n    bc::vector<float> input(data, data + 5, queue);\n    bc::vector<float> output(5, context);\n\n    // normal inclusive scan of the input\n    bc::inclusive_scan(input.begin(), input.end(), output.begin());\n    bc::system::finish();\n    BOOST_CHECK_CLOSE(float(output[0]), 1.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(output[1]), 3.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(output[2]), 6.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(output[3]), 10.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(output[4]), 15.0f, 1e-4f);\n\n    // inclusive scan of squares of the input\n    using ::boost::compute::_1;\n\n    bc::inclusive_scan(bc::make_transform_iterator(input.begin(), pown(_1, 2)),\n                       bc::make_transform_iterator(input.end(), pown(_1, 2)),\n                       output.begin());\n    bc::system::finish();\n    BOOST_CHECK_CLOSE(float(output[0]), 1.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(output[1]), 5.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(output[2]), 14.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(output[3]), 30.0f, 1e-4f);\n    BOOST_CHECK_CLOSE(float(output[4]), 55.0f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(inclusive_scan_doctest)\n{\n//! [inclusive_scan_int]\n// setup input\nint data[] = { 1, 2, 3, 4 };\nboost::compute::vector<int> input(data, data + 4, queue);\n\n// setup output\nboost::compute::vector<int> output(4, context);\n\n// scan values\nboost::compute::inclusive_scan(\n    input.begin(), input.end(), output.begin(), queue\n);\n\n// output = [ 1, 3, 6, 10 ]\n//! [inclusive_scan_int]\n\n    CHECK_RANGE_EQUAL(int, 4, output, (1, 3, 6, 10));\n}\n\nBOOST_AUTO_TEST_CASE(exclusive_scan_doctest)\n{\n//! [exclusive_scan_int]\n// setup input\nint data[] = { 1, 2, 3, 4 };\nboost::compute::vector<int> input(data, data + 4, queue);\n\n// setup output\nboost::compute::vector<int> output(4, context);\n\n// scan values\nboost::compute::exclusive_scan(\n    input.begin(), input.end(), output.begin(), queue\n);\n\n// output = [ 0, 1, 3, 6 ]\n//! [exclusive_scan_int]\n\n    CHECK_RANGE_EQUAL(int, 4, output, (0, 1, 3, 6));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "89ea2833f309a854a08e8ecb2b6c4d18fae163aa", "size": 5755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_scan.cpp", "max_stars_repo_name": "msuchard/compute", "max_stars_repo_head_hexsha": "7009451dbf909291cec4ce3eb45cdcd90c1cf742", "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_scan.cpp", "max_issues_repo_name": "msuchard/compute", "max_issues_repo_head_hexsha": "7009451dbf909291cec4ce3eb45cdcd90c1cf742", "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_scan.cpp", "max_forks_repo_name": "msuchard/compute", "max_forks_repo_head_hexsha": "7009451dbf909291cec4ce3eb45cdcd90c1cf742", "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.1508379888, "max_line_length": 79, "alphanum_fraction": 0.62589053, "num_tokens": 1678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5253345996500818}}
{"text": "/*\n * concatenate Eigen matrices\n * by R. Falque\n * 03/07/2019\n */\n\n#ifndef EIGEN_CONCATENATE_HPP\n#define EIGEN_CONCATENATE_HPP\n\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n\n\n\n// https://stackoverflow.com/a/21496281/2562693\ntemplate <typename T>\ninline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> concatenate(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> in_1, \n                                                                    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> in_2, \n                                                                    int direction)\n{\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> out;\n    int cols, rows;\n    if (in_1.rows() == 0 & in_1.cols() ==0) {\n        rows = in_2.rows();\n        cols = in_2.cols();\n    } else if (in_2.rows() == 0 & in_2.cols() ==0) {\n        rows = in_1.rows();\n        cols = in_1.cols();\n    } else if (direction == 1 & in_1.cols() == in_2.cols()) {\n        rows = in_1.rows()+in_2.rows();\n        cols = in_1.cols();\n    } else if (direction == 2 & in_1.rows() == in_2.rows()) {\n        rows = in_1.rows();\n        cols = in_1.cols()+in_2.cols();\n    }\n\n    out.resize(rows, cols);\n    out << in_1, in_2;\n    \n    return out;\n};\n\n\n// https://stackoverflow.com/a/50353398/2562693\ntemplate <typename T>\ninline Eigen::SparseMatrix< T > concatenate(Eigen::SparseMatrix<T>in_1, Eigen::SparseMatrix<T>in_2, int direction)\n{\n    typedef typename Eigen::SparseMatrix<T>::InnerIterator SparseIterator;\n    \n    // first test if the input size are correct with respect to the direction:\n    if (direction == 1)\n        if (in_1.cols() != in_2.cols())\n        {\n            std::cout << \"Error: wrong input size, the cols size do not match.\\n\";\n            std::exit(0);\n        }\n    else if (direction == 2)\n        if (in_1.rows() != in_2.rows())\n        {\n            std::cout << \"Error: wrong input size, the rows size do not match.\\n\";\n            std::exit(0);\n        }\n    else {\n        std::cout << \"Error: wrong direction (direction should be 1 or 2).\\n\";\n        std::exit(0);\n    }\n\n    // start the concatenation process:\n    Eigen::SparseMatrix<T> out;\n\n    if (direction == 1) // vertical\n        out.resize(in_1.rows() + in_2.rows(), in_1.cols());\n    else // horizontal\n        out.resize(in_1.rows(), in_1.cols() + in_2.cols());\n    \n    out.reserve(in_1.nonZeros() + in_2.nonZeros());\n\n    std::vector< Eigen::Triplet<T, size_t> > triplets;\n    triplets.reserve(in_1.nonZeros() + in_2.nonZeros());\n\n    for (int k = 0; k < in_1.outerSize(); ++k) {\n        for (SparseIterator it(in_1, k); it; ++it) {\n            triplets.emplace_back(it.row(), it.col(), it.value());\n        }\n    }\n\n    for (int k = 0; k < in_2.outerSize(); ++k) {\n        for (SparseIterator it(in_2, k); it; ++it) {\n            if (direction == 1)\n                triplets.emplace_back(in_1.rows() + it.row(), it.col(), it.value());\n            else\n                triplets.emplace_back(it.row(), in_1.cols() + it.col(), it.value());\n        }\n    }\n\n    out.setFromTriplets(triplets.begin(), triplets.end());\n\n    return out;\n};\n\n#endif\n", "meta": {"hexsha": "f4350fd421146a0636bb05956d24830758222502", "size": 3125, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/EigenTools/concatenate.hpp", "max_stars_repo_name": "rFalque/normals_transfer", "max_stars_repo_head_hexsha": "c0c27fb6e3bce32123489442f3b606f9be00b56e", "max_stars_repo_licenses": ["MIT"], "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/EigenTools/concatenate.hpp", "max_issues_repo_name": "rFalque/normals_transfer", "max_issues_repo_head_hexsha": "c0c27fb6e3bce32123489442f3b606f9be00b56e", "max_issues_repo_licenses": ["MIT"], "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/EigenTools/concatenate.hpp", "max_forks_repo_name": "rFalque/normals_transfer", "max_forks_repo_head_hexsha": "c0c27fb6e3bce32123489442f3b606f9be00b56e", "max_forks_repo_licenses": ["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.0480769231, "max_line_length": 123, "alphanum_fraction": 0.54656, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5253345994549401}}
{"text": "//  (C) 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#ifndef BOOST_MATH_SPECIAL_CHEBYSHEV_HPP\n#define BOOST_MATH_SPECIAL_CHEBYSHEV_HPP\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n\n#if (__cplusplus > 201103) || (defined(_CPPLIB_VER) && (_CPPLIB_VER >= 610))\n#  define BOOST_MATH_CHEB_USE_STD_ACOSH\n#endif\n\n#ifndef BOOST_MATH_CHEB_USE_STD_ACOSH\n#  include <boost/math/special_functions/acosh.hpp>\n#endif\n\nnamespace boost { namespace math {\n\ntemplate<class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type chebyshev_next(T1 const & x, T2 const & Tn, T3 const & Tn_1)\n{\n    return 2*x*Tn - Tn_1;\n}\n\nnamespace detail {\n\ntemplate<class Real, bool second>\ninline Real chebyshev_imp(unsigned n, Real const & x)\n{\n#ifdef BOOST_MATH_CHEB_USE_STD_ACOSH\n    using std::acosh;\n#else\n   using boost::math::acosh;\n#endif\n    using std::cosh;\n    using std::pow;\n    using std::sqrt;\n    Real T0 = 1;\n    Real T1;\n    if (second)\n    {\n        if (x > 1 || x < -1)\n        {\n            Real t = sqrt(x*x -1);\n            return static_cast<Real>((pow(x+t, (int)(n+1)) - pow(x-t, (int)(n+1)))/(2*t));\n        }\n        T1 = 2*x;\n    }\n    else\n    {\n        if (x > 1)\n        {\n            return cosh(n*acosh(x));\n        }\n        if (x < -1)\n        {\n            if (n & 1)\n            {\n                return -cosh(n*acosh(-x));\n            }\n            else\n            {\n                return cosh(n*acosh(-x));\n            }\n        }\n        T1 = x;\n    }\n\n    if (n == 0)\n    {\n        return T0;\n    }\n\n    unsigned l = 1;\n    while(l < n)\n    {\n       std::swap(T0, T1);\n       T1 = boost::math::chebyshev_next(x, T0, T1);\n       ++l;\n    }\n    return T1;\n}\n} // namespace detail\n\ntemplate <class Real, class Policy>\ninline typename tools::promote_args<Real>::type\nchebyshev_t(unsigned n, Real const & x, const Policy&)\n{\n   typedef typename tools::promote_args<Real>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::chebyshev_imp<value_type, false>(n, static_cast<value_type>(x)), \"boost::math::chebyshev_t<%1%>(unsigned, %1%)\");\n}\n\ntemplate<class Real>\ninline typename tools::promote_args<Real>::type chebyshev_t(unsigned n, Real const & x)\n{\n    return chebyshev_t(n, x, policies::policy<>());\n}\n\ntemplate <class Real, class Policy>\ninline typename tools::promote_args<Real>::type\nchebyshev_u(unsigned n, Real const & x, const Policy&)\n{\n   typedef typename tools::promote_args<Real>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::chebyshev_imp<value_type, true>(n, static_cast<value_type>(x)), \"boost::math::chebyshev_u<%1%>(unsigned, %1%)\");\n}\n\ntemplate<class Real>\ninline typename tools::promote_args<Real>::type chebyshev_u(unsigned n, Real const & x)\n{\n    return chebyshev_u(n, x, policies::policy<>());\n}\n\ntemplate <class Real, class Policy>\ninline typename tools::promote_args<Real>::type\nchebyshev_t_prime(unsigned n, Real const & x, const Policy&)\n{\n   typedef typename tools::promote_args<Real>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   if (n == 0)\n   {\n      return result_type(0);\n   }\n   return policies::checked_narrowing_cast<result_type, Policy>(n * detail::chebyshev_imp<value_type, true>(n - 1, static_cast<value_type>(x)), \"boost::math::chebyshev_t_prime<%1%>(unsigned, %1%)\");\n}\n\ntemplate<class Real>\ninline typename tools::promote_args<Real>::type chebyshev_t_prime(unsigned n, Real const & x)\n{\n   return chebyshev_t_prime(n, x, policies::policy<>());\n}\n\n/*\n * This is Algorithm 3.1 of\n * Gil, Amparo, Javier Segura, and Nico M. Temme.\n * Numerical methods for special functions.\n * Society for Industrial and Applied Mathematics, 2007.\n * https://www.siam.org/books/ot99/OT99SampleChapter.pdf\n * However, our definition of c0 differs by a factor of 1/2, as stated in the docs. . .\n */\ntemplate<class Real, class T2>\ninline Real chebyshev_clenshaw_recurrence(const Real* const c, size_t length, const T2& x)\n{\n    using boost::math::constants::half;\n    if (length < 2)\n    {\n        if (length == 0)\n        {\n            return 0;\n        }\n        return c[0]/2;\n    }\n    Real b2 = 0;\n    Real b1 = c[length -1];\n    for(size_t j = length - 2; j >= 1; --j)\n    {\n        Real tmp = 2*x*b1 - b2 + c[j];\n        b2 = b1;\n        b1 = tmp;\n    }\n    return x*b1 - b2 + half<Real>()*c[0];\n}\n\n\n}}\n#endif\n", "meta": {"hexsha": "0f4d9f2dac003a9df84ba0e3d6def844daea0339", "size": 4760, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/special_functions/chebyshev.hpp", "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": "boost/math/special_functions/chebyshev.hpp", "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": "boost/math/special_functions/chebyshev.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 28.0, "max_line_length": 198, "alphanum_fraction": 0.6403361345, "num_tokens": 1390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5253345952443418}}
{"text": "#ifdef STAN_OPENCL\n\n#include <stan/math/opencl/kernel_generator.hpp>\n#include <test/unit/math/opencl/kernel_generator/reference_kernel.hpp>\n#include <stan/math/opencl/matrix_cl.hpp>\n#include <stan/math/opencl/copy.hpp>\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n#include <string>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing stan::math::diagonal;\nusing stan::math::matrix_cl;\n\n#define EXPECT_MATRIX_NEAR(A, B, DELTA) \\\n  EXPECT_EQ(A.rows(), B.rows());        \\\n  EXPECT_EQ(A.cols(), B.cols());        \\\n  for (int i = 0; i < A.size(); i++)    \\\n    EXPECT_NEAR(A(i), B(i), DELTA);\n\nTEST(KernelGenerator, diagonal_test) {\n  MatrixXd m = MatrixXd::Random(3, 4);\n\n  matrix_cl<double> m_cl(m);\n\n  matrix_cl<double> res_cl = diagonal(m_cl);\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  MatrixXd correct = m.diagonal();\n  EXPECT_MATRIX_NEAR(res, correct, 1e-9);\n}\n\nTEST(KernelGenerator, diagonal_multiple_operations_test) {\n  MatrixXd m = MatrixXd::Random(4, 3);\n\n  matrix_cl<double> m_cl(m);\n\n  matrix_cl<double> res_cl = diagonal(m_cl * 2);\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  MatrixXd correct = (2 * m).diagonal();\n  EXPECT_MATRIX_NEAR(res, correct, 1e-9);\n}\n\nTEST(KernelGenerator, diagonal_multiple_operations_accept_lvalue_test) {\n  MatrixXd m = MatrixXd::Random(3, 4);\n\n  matrix_cl<double> m_cl(m);\n\n  auto tmp = m_cl * 2;\n  matrix_cl<double> res_cl = diagonal(tmp);\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  MatrixXd correct = (2 * m).diagonal();\n  EXPECT_MATRIX_NEAR(res, correct, 1e-9);\n}\n\nTEST(KernelGenerator, diagonal_lhs_test) {\n  MatrixXd m = MatrixXd::Random(3, 4);\n  VectorXd v = VectorXd::Random(3);\n\n  matrix_cl<double> m_cl(m);\n  matrix_cl<double> v_cl(v);\n\n  diagonal(m_cl) = v_cl;\n  MatrixXd res = stan::math::from_matrix_cl(m_cl);\n\n  MatrixXd correct = m;\n  correct.diagonal() = v;\n  EXPECT_MATRIX_NEAR(res, correct, 1e-9);\n}\n\nTEST(KernelGenerator, diagonal_of_a_block_test) {\n  MatrixXd m = MatrixXd::Random(4, 4);\n\n  matrix_cl<double> m_cl(m);\n\n  diagonal(block(m_cl, 0, 1, 3, 3)) = diagonal(block(m_cl, 1, 0, 3, 3));\n  MatrixXd res = stan::math::from_matrix_cl(m_cl);\n\n  MatrixXd correct = m;\n  correct.diagonal(1) = correct.diagonal(-1);\n  EXPECT_MATRIX_NEAR(res, correct, 1e-9);\n}\n\n#endif\n", "meta": {"hexsha": "c8298a3582535e155dfef9c45d719a4913fef5ca", "size": 2268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/opencl/kernel_generator/diagonal_test.cpp", "max_stars_repo_name": "HaoZeke/math", "max_stars_repo_head_hexsha": "fdf7f70dceed60f3b3f93137c6ac123a457b80a3", "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/opencl/kernel_generator/diagonal_test.cpp", "max_issues_repo_name": "HaoZeke/math", "max_issues_repo_head_hexsha": "fdf7f70dceed60f3b3f93137c6ac123a457b80a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/opencl/kernel_generator/diagonal_test.cpp", "max_forks_repo_name": "HaoZeke/math", "max_forks_repo_head_hexsha": "fdf7f70dceed60f3b3f93137c6ac123a457b80a3", "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.7727272727, "max_line_length": 72, "alphanum_fraction": 0.69664903, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.525334591228885}}
{"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   testExtendedPose3.cpp\n * @brief  Unit tests for ExtendedPose3 class\n */\n\n#include <gtsam/geometry/ExtendedPose3.h>\n#include <gtsam/base/testLie.h>\n#include <gtsam/base/lieProxies.h>\n\n#include <boost/assign/std/vector.hpp> // for operator +=\nusing namespace boost::assign;\n\n#include <CppUnitLite/TestHarness.h>\n#include <cmath>\n\nusing namespace std;\nusing namespace gtsam;\n\nGTSAM_CONCEPT_TESTABLE_INST(ExtendedPose3)\nGTSAM_CONCEPT_LIE_INST(ExtendedPose3)\n\nstatic const Point3 V(3,0.4,-2.2);\nstatic const Point3 P(0.2,0.7,-2);\nstatic const Rot3 R = Rot3::Rodrigues(0.3,0,0);\nstatic const Point3 V2(-6.5,3.5,6.2);\nstatic const Point3 P2(3.5,-8.2,4.2);\nstatic const ExtendedPose3 T(R,V2,P2);\nstatic const ExtendedPose3 T2(Rot3::Rodrigues(0.3,0.2,0.1),V2,P2);\nstatic const ExtendedPose3 T3(Rot3::Rodrigues(-90, 0, 0), Point3(5,6,7), Point3(1, 2, 3));\nstatic const double tol=1e-5;\n\n/* ************************************************************************* */\nTEST( ExtendedPose3, equals)\n{\n  ExtendedPose3 pose2 = T3;\n  EXPECT(T3.equals(pose2));\n  ExtendedPose3 origin;\n  EXPECT(!T3.equals(origin));\n}\n\n/* ************************************************************************* */\n#ifndef GTSAM_POSE3_EXPMAP\nTEST( ExtendedPose3, retract_first_order)\n{\n  ExtendedPose3 id;\n  Vector xi = Z_9x1;\n  xi(0) = 0.3;\n  EXPECT(assert_equal(ExtendedPose3(R, Vector3(0,0,0), Point3(0,0,0)), id.retract(xi),1e-2));\n  xi(3)=3;xi(4)=0.4;xi(5)=-2.2;\n  xi(6)=0.2;xi(7)=0.7;xi(8)=-2;\n  EXPECT(assert_equal(ExtendedPose3(R, V, P),id.retract(v),1e-2));\n}\n#endif\n/* ************************************************************************* */\nTEST( ExtendedPose3, retract_expmap)\n{\n  Vector xi = Z_9x1; xi(0) = 0.3;\n  ExtendedPose3 pose = ExtendedPose3::Expmap(xi);\n  EXPECT(assert_equal(ExtendedPose3(R, Point3(0,0,0), Point3(0,0,0)), pose, 1e-2));\n  EXPECT(assert_equal(xi,ExtendedPose3::Logmap(pose),1e-2));\n}\n\n/* ************************************************************************* */\nTEST( ExtendedPose3, expmap_a_full)\n{\n  ExtendedPose3 id;\n  Vector xi = Z_9x1;\n  xi(0) = 0.3;\n  EXPECT(assert_equal(expmap_default<ExtendedPose3>(id, xi), ExtendedPose3(R, Vector3(0,0,0), Point3(0,0,0))));\n  xi(3)=-0.2;xi(4)=-0.394742;xi(5)=2.08998;\n  xi(6)=0.2;xi(7)=0.394742;xi(8)=-2.08998;\n  EXPECT(assert_equal(ExtendedPose3(R, -P, P),expmap_default<ExtendedPose3>(id, xi),1e-5));\n}\n\n/* ************************************************************************* */\nTEST( ExtendedPose3, expmap_a_full2)\n{\n  ExtendedPose3 id;\n  Vector xi = Z_9x1;\n  xi(0) = 0.3;\n  EXPECT(assert_equal(expmap_default<ExtendedPose3>(id, xi), ExtendedPose3(R, Point3(0,0,0), Point3(0,0,0))));\n  xi(3)=-0.2;xi(4)=-0.394742;xi(5)=2.08998;\n  xi(6)=0.2;xi(7)=0.394742;xi(8)=-2.08998;\n  EXPECT(assert_equal(ExtendedPose3(R, -P, P),expmap_default<ExtendedPose3>(id, xi),1e-5));\n}\n\n/* ************************************************************************* */\nTEST(ExtendedPose3, expmap_b)\n{\n  ExtendedPose3 p1(Rot3(), Vector3(-100, 0, 0), Point3(100, 0, 0));\n  ExtendedPose3 p2 = p1.retract((Vector(9) << 0.0, 0.0, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0).finished());\n  ExtendedPose3 expected(Rot3::Rodrigues(0.0, 0.0, 0.1), Point3(-100.0, 0.0, 0.0), Point3(100.0, 0.0, 0.0));\n  EXPECT(assert_equal(expected, p2,1e-2));\n}\n\n/* ************************************************************************* */\n// test case for screw motion in the plane\nnamespace screwExtendedPose3 {\n  double a=0.3, c=cos(a), s=sin(a), w=0.3;\n  Vector xi = (Vector(9) << 0.0, 0.0, w, w, 0.0, 1.0, w, 0.0, 1.0).finished();\n  Rot3 expectedR(c, -s, 0, s, c, 0, 0, 0, 1);\n  Point3 expectedV(0.29552, 0.0446635, 1);\n  Point3 expectedP(0.29552, 0.0446635, 1);\n  ExtendedPose3 expected(expectedR, expectedV, expectedP);\n}\n\n/* ************************************************************************* */\n// Checks correct exponential map (Expmap) with brute force matrix exponential\nTEST(ExtendedPose3, expmap_c_full)\n{\n  EXPECT(assert_equal(screwExtendedPose3::expected, expm<ExtendedPose3>(screwExtendedPose3::xi),1e-6));\n  EXPECT(assert_equal(screwExtendedPose3::expected, ExtendedPose3::Expmap(screwExtendedPose3::xi),1e-6));\n}\n\n/* ************************************************************************* */\n// assert that T*exp(xi)*T^-1 is equal to exp(Ad_T(xi))\nTEST(ExtendedPose3, Adjoint_full)\n{\n  ExtendedPose3 expected = T * ExtendedPose3::Expmap( screwExtendedPose3::xi) * T.inverse();\n  Vector xiprime = T.Adjoint( screwExtendedPose3::xi);\n  EXPECT(assert_equal(expected, ExtendedPose3::Expmap(xiprime), 1e-6));\n\n  ExtendedPose3 expected2 = T2 * ExtendedPose3::Expmap( screwExtendedPose3::xi) * T2.inverse();\n  Vector xiprime2 = T2.Adjoint( screwExtendedPose3::xi);\n  EXPECT(assert_equal(expected2, ExtendedPose3::Expmap(xiprime2), 1e-6));\n\n  ExtendedPose3 expected3 = T3 * ExtendedPose3::Expmap( screwExtendedPose3::xi) * T3.inverse();\n  Vector xiprime3 = T3.Adjoint( screwExtendedPose3::xi);\n  EXPECT(assert_equal(expected3, ExtendedPose3::Expmap(xiprime3), 1e-6));\n}\n\n/* ************************************************************************* */\n// assert that T*wedge(xi)*T^-1 is equal to wedge(Ad_T(xi))\nTEST(ExtendedPose3, Adjoint_hat)\n{\n  auto hat = [](const Vector& xi) { return ::wedge<ExtendedPose3>(xi); };\n  Matrix5 expected = T.matrix() * hat( screwExtendedPose3::xi) * T.matrix().inverse();\n  Matrix5 xiprime = hat(T.Adjoint( screwExtendedPose3::xi));\n\n  EXPECT(assert_equal(expected, xiprime, 1e-6));\n\n  Matrix5 expected2 = T2.matrix() * hat( screwExtendedPose3::xi) * T2.matrix().inverse();\n  Matrix5 xiprime2 = hat(T2.Adjoint( screwExtendedPose3::xi));\n  EXPECT(assert_equal(expected2, xiprime2, 1e-6));\n\n  Matrix5 expected3 = T3.matrix() * hat( screwExtendedPose3::xi) * T3.matrix().inverse(); \n\n  Matrix5 xiprime3 = hat(T3.Adjoint( screwExtendedPose3::xi));\n  EXPECT(assert_equal(expected3, xiprime3, 1e-6));\n}\n\n/* ************************************************************************* */\nTEST(ExtendedPose3, expmaps_galore_full)\n{\n  Vector xi; ExtendedPose3 actual;\n  xi = (Vector(9) << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9).finished();\n  actual = ExtendedPose3::Expmap(xi);\n  EXPECT(assert_equal(expm<ExtendedPose3>(xi), actual,1e-6));\n  EXPECT(assert_equal(xi, ExtendedPose3::Logmap(actual),1e-6));\n\n  xi = (Vector(9) << 0.1, -0.2, 0.3, -0.4, 0.5, -0.6, -0.7, -0.8, -0.9).finished();\n  for (double theta=1.0;0.3*theta<=M_PI;theta*=2) {\n    Vector txi = xi*theta;\n    actual = ExtendedPose3::Expmap(txi);\n    EXPECT(assert_equal(expm<ExtendedPose3>(txi,30), actual,1e-6));\n    Vector log = ExtendedPose3::Logmap(actual);\n    EXPECT(assert_equal(actual, ExtendedPose3::Expmap(log),1e-6));\n    EXPECT(assert_equal(txi,log,1e-6)); // not true once wraps\n  }\n\n  // Works with large v as well, but expm needs 10 iterations!\n  xi = (Vector(9) << 0.2, 0.3, -0.8, 100.0, 120.0, -60.0, 12, 14, 45).finished();\n  actual = ExtendedPose3::Expmap(xi);\n  EXPECT(assert_equal(expm<ExtendedPose3>(xi,10), actual,1e-5));\n  EXPECT(assert_equal(xi, ExtendedPose3::Logmap(actual),1e-9));\n}\n\n/* ************************************************************************* */\n// Check position and its pushforward\n\nTEST(ExtendedPose3, position) {\n  Matrix actualH;\n  EXPECT(assert_equal(Point3(3.5, -8.2, 4.2), T.position(actualH), 1e-8));\n  Matrix numericalH = numericalDerivative11<Point3, ExtendedPose3>(\n      boost::bind(&ExtendedPose3::position, _1, boost::none), T);\n  EXPECT(assert_equal(numericalH, actualH, 1e-6));\n}\n\n/* ************************************************************************* */\n// Check rotation and its pushforward\nTEST(ExtendedPose3, rotation) {\n  Matrix actualH;\n  EXPECT(assert_equal(R, T.rotation(actualH), 1e-8));\n\n  Matrix numericalH = numericalDerivative11<Rot3, ExtendedPose3>(\n      boost::bind(&ExtendedPose3::rotation, _1, boost::none), T);\n  EXPECT(assert_equal(numericalH, actualH, 1e-6));\n}\n\n/* ************************************************************************* */\n// Check velocity and its pushforward\nTEST(ExtendedPose3, velocity) {\n  Matrix actualH;\n  EXPECT(assert_equal(Point3(-6.5,3.5,6.2), T.velocity(actualH), 1e-8));\n  Matrix numericalH = numericalDerivative11<Point3, ExtendedPose3>(\n      boost::bind(&ExtendedPose3::velocity, _1, boost::none), T);\n  EXPECT(assert_equal(numericalH, actualH, 1e-6));\n}\n\n/* ************************************************************************* */\nTEST(ExtendedPose3, Adjoint_compose_full)\n{\n  // To debug derivatives of compose, assert that\n  // T1*T2*exp(Adjoint(inv(T2),x) = T1*exp(x)*T2\n  const ExtendedPose3& T1 = T;\n  Vector x = (Vector(9) << 0.1, 0.1, 0.1, 0.4, 0.2, 0.8, 0.4, 0.2, 0.8).finished();\n  ExtendedPose3 expected = T1 * ExtendedPose3::Expmap(x) * T2;\n  Vector y = T2.inverse().Adjoint(x);\n  ExtendedPose3 actual = T1 * T2 * ExtendedPose3::Expmap(y);\n  EXPECT(assert_equal(expected, actual, 1e-6));\n}\n\n/* ************************************************************************* */\n// Check compose and its pushforward\n// NOTE: testing::compose<ExtendedPose3>(t1,t2) = t1.compose(t2)  (see lieProxies.h)\nTEST( ExtendedPose3, compose )\n{\n  Matrix actual = (T2*T2).matrix();\n\n  Matrix expected = T2.matrix()*T2.matrix();\n  EXPECT(assert_equal(actual,expected,1e-8));\n\n  Matrix actualDcompose1, actualDcompose2;\n  T2.compose(T2, actualDcompose1, actualDcompose2);\n\n  Matrix numericalH1 = numericalDerivative21(testing::compose<ExtendedPose3>, T2, T2);\n\n  EXPECT(assert_equal(numericalH1,actualDcompose1,5e-3));\n  EXPECT(assert_equal(T2.inverse().AdjointMap(),actualDcompose1,5e-3));\n\n  Matrix numericalH2 = numericalDerivative22(testing::compose<ExtendedPose3>, T2, T2);\n  EXPECT(assert_equal(numericalH2,actualDcompose2,1e-4));\n}\n\n/* ************************************************************************* */\n// Check compose and its pushforward, another case\nTEST( ExtendedPose3, compose2 )\n{\n  const ExtendedPose3& T1 = T;\n  Matrix actual = (T1*T2).matrix();\n  Matrix expected = T1.matrix()*T2.matrix();\n  EXPECT(assert_equal(actual,expected,1e-8));\n\n  Matrix actualDcompose1, actualDcompose2;\n  T1.compose(T2, actualDcompose1, actualDcompose2);\n\n  Matrix numericalH1 = numericalDerivative21(testing::compose<ExtendedPose3>, T1, T2);\n  EXPECT(assert_equal(numericalH1,actualDcompose1,5e-3));\n  EXPECT(assert_equal(T2.inverse().AdjointMap(),actualDcompose1,5e-3));\n\n  Matrix numericalH2 = numericalDerivative22(testing::compose<ExtendedPose3>, T1, T2);\n  EXPECT(assert_equal(numericalH2,actualDcompose2,1e-5));\n}\n\n/* ************************************************************************* */\nTEST( ExtendedPose3, inverse)\n{\n  Matrix actualDinverse;\n  Matrix actual = T.inverse(actualDinverse).matrix();\n  Matrix expected = T.matrix().inverse();\n  EXPECT(assert_equal(actual,expected,1e-8));\n\n  Matrix numericalH = numericalDerivative11(testing::inverse<ExtendedPose3>, T);\n  EXPECT(assert_equal(numericalH,actualDinverse,5e-3));\n  EXPECT(assert_equal(-T.AdjointMap(),actualDinverse,5e-3));\n}\n\n/* ************************************************************************* */\nTEST( ExtendedPose3, inverseDerivatives2)\n{\n  Rot3 R = Rot3::Rodrigues(0.3,0.4,-0.5);\n  Vector3 v(3.5,-8.2,4.2);\n  Point3 p(3.5,-8.2,4.2);\n  ExtendedPose3 T(R,v,p);\n\n  Matrix numericalH = numericalDerivative11(testing::inverse<ExtendedPose3>, T);\n  Matrix actualDinverse;\n  T.inverse(actualDinverse);\n  EXPECT(assert_equal(numericalH,actualDinverse,5e-3));\n  EXPECT(assert_equal(-T.AdjointMap(),actualDinverse,5e-3));\n}\n\n/* ************************************************************************* */\nTEST( ExtendedPose3, compose_inverse)\n{\n  Matrix actual = (T*T.inverse()).matrix();\n  Matrix expected = I_5x5;\n  EXPECT(assert_equal(actual,expected,1e-8));\n}\n\n/* ************************************************************************* */\nTEST(ExtendedPose3, Retract_LocalCoordinates)\n{\n  Vector9 d;\n  d << 1,2,3,4,5,6,7,8,9; d/=10;\n  const Rot3 R = Rot3::Retract(d.head<3>());\n  ExtendedPose3 t = ExtendedPose3::Retract(d);\n  EXPECT(assert_equal(d, ExtendedPose3::LocalCoordinates(t)));\n}\n/* ************************************************************************* */\nTEST(ExtendedPose3, retract_localCoordinates)\n{\n  Vector9 d12;\n  d12 << 1,2,3,4,5,6,7,8,9; d12/=10;\n  ExtendedPose3 t1 = T, t2 = t1.retract(d12);\n  EXPECT(assert_equal(d12, t1.localCoordinates(t2)));\n}\n/* ************************************************************************* */\nTEST(ExtendedPose3, expmap_logmap)\n{\n  Vector d12 = Vector9::Constant(0.1);\n  ExtendedPose3 t1 = T, t2 = t1.expmap(d12);\n  EXPECT(assert_equal(d12, t1.logmap(t2)));\n}\n\n/* ************************************************************************* */\nTEST(ExtendedPose3, retract_localCoordinates2)\n{\n  ExtendedPose3 t1 = T;\n  ExtendedPose3 t2 = T3;\n  ExtendedPose3 origin;\n  Vector d12 = t1.localCoordinates(t2);\n  EXPECT(assert_equal(t2, t1.retract(d12)));\n  Vector d21 = t2.localCoordinates(t1);\n  EXPECT(assert_equal(t1, t2.retract(d21)));\n  EXPECT(assert_equal(d12, -d21));\n}\n/* ************************************************************************* */\nTEST(ExtendedPose3, manifold_expmap)\n{\n  ExtendedPose3 t1 = T;\n  ExtendedPose3 t2 = T3;\n  ExtendedPose3 origin;\n  Vector d12 = t1.logmap(t2);\n  EXPECT(assert_equal(t2, t1.expmap(d12)));\n  Vector d21 = t2.logmap(t1);\n  EXPECT(assert_equal(t1, t2.expmap(d21)));\n\n  // Check that log(t1,t2)=-log(t2,t1)\n  EXPECT(assert_equal(d12,-d21));\n}\n\n/* ************************************************************************* */\nTEST(ExtendedPose3, subgroups)\n{\n  // Frank - Below only works for correct \"Agrawal06iros style expmap\n  // lines in canonical coordinates correspond to Abelian subgroups in SE(3)\n   Vector d = (Vector(9) << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9).finished();\n  // exp(-d)=inverse(exp(d))\n   EXPECT(assert_equal(ExtendedPose3::Expmap(-d),ExtendedPose3::Expmap(d).inverse()));\n  // exp(5d)=exp(2*d+3*d)=exp(2*d)exp(3*d)=exp(3*d)exp(2*d)\n   ExtendedPose3 T2 = ExtendedPose3::Expmap(2*d);\n   ExtendedPose3 T3 = ExtendedPose3::Expmap(3*d);\n   ExtendedPose3 T5 = ExtendedPose3::Expmap(5*d);\n   EXPECT(assert_equal(T5,T2*T3));\n   EXPECT(assert_equal(T5,T3*T2));\n}\n\n/* ************************************************************************* */\nTEST( ExtendedPose3, between )\n{\n  ExtendedPose3 expected = T2.inverse() * T3;\n  Matrix actualDBetween1,actualDBetween2;\n  ExtendedPose3 actual = T2.between(T3, actualDBetween1,actualDBetween2);\n  EXPECT(assert_equal(expected,actual));\n\n  Matrix numericalH1 = numericalDerivative21(testing::between<ExtendedPose3> , T2, T3);\n  EXPECT(assert_equal(numericalH1,actualDBetween1,5e-3));\n\n  Matrix numericalH2 = numericalDerivative22(testing::between<ExtendedPose3> , T2, T3);\n  EXPECT(assert_equal(numericalH2,actualDBetween2,1e-5));\n}\n\n\n/* ************************************************************************* */\nTEST( ExtendedPose3, adjointMap) {\n  Matrix res = ExtendedPose3::adjointMap( screwExtendedPose3::xi);\n  Matrix wh = skewSymmetric( screwExtendedPose3::xi(0),  screwExtendedPose3::xi(1),  screwExtendedPose3::xi(2));\n  Matrix vh = skewSymmetric( screwExtendedPose3::xi(3),  screwExtendedPose3::xi(4),  screwExtendedPose3::xi(5));\n  Matrix rh = skewSymmetric( screwExtendedPose3::xi(6),  screwExtendedPose3::xi(7),  screwExtendedPose3::xi(8));\n  Matrix9 expected;\n  expected << wh, Z_3x3, Z_3x3, vh, wh, Z_3x3, rh, Z_3x3, wh;\n  EXPECT(assert_equal(expected,res,1e-5));\n}\n\n/* ************************************************************************* */\n\nTEST( ExtendedPose3, ExpmapDerivative1) {\n  Matrix9 actualH;\n  Vector9 w; w << 0.1, 0.2, 0.3, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0;\n  ExtendedPose3::Expmap(w,actualH);\n  Matrix expectedH = numericalDerivative21<ExtendedPose3, Vector9,\n      OptionalJacobian<9, 9> >(&ExtendedPose3::Expmap, w, boost::none);\n  EXPECT(assert_equal(expectedH, actualH));\n}\n\n/* ************************************************************************* */\nTEST( ExtendedPose3, LogmapDerivative) {\n  Matrix9 actualH;\n  Vector9 w; w << 0.1, 0.2, 0.3, 4.0, 5.0, 6.0,7.0,8.0,9.0;\n  ExtendedPose3 p = ExtendedPose3::Expmap(w);\n  EXPECT(assert_equal(w, ExtendedPose3::Logmap(p,actualH), 1e-5));\n  Matrix expectedH = numericalDerivative21<Vector9, ExtendedPose3,\n      OptionalJacobian<9, 9> >(&ExtendedPose3::Logmap, p, boost::none);\n  EXPECT(assert_equal(expectedH, actualH));\n}\n\n/* ************************************************************************* */\nTEST( ExtendedPose3, stream)\n{\n  ExtendedPose3 T;\n  std::ostringstream os;\n  os << T;\n  EXPECT(os.str() == \"\\n|1, 0, 0|\\n|0, 1, 0|\\n|0, 0, 1|\\nv:[0, 0, 0];\\np:[0, 0, 0];\\n\");\n}\n\n//******************************************************************************\nTEST(ExtendedPose3 , Invariants) {\n  ExtendedPose3 id;\n\n  EXPECT(check_group_invariants(id,id));\n  EXPECT(check_group_invariants(id,T3));\n  EXPECT(check_group_invariants(T2,id));\n  EXPECT(check_group_invariants(T2,T3));\n\n  EXPECT(check_manifold_invariants(id,id));\n  EXPECT(check_manifold_invariants(id,T3));\n  EXPECT(check_manifold_invariants(T2,id));\n  EXPECT(check_manifold_invariants(T2,T3));\n}\n\n//******************************************************************************\nTEST(ExtendedPose3 , LieGroupDerivatives) {\n  ExtendedPose3 id;\n\n  CHECK_LIE_GROUP_DERIVATIVES(id,id);\n  CHECK_LIE_GROUP_DERIVATIVES(id,T2);\n  CHECK_LIE_GROUP_DERIVATIVES(T2,id);\n  CHECK_LIE_GROUP_DERIVATIVES(T2,T3);\n}\n\n//******************************************************************************\nTEST(ExtendedPose3 , ChartDerivatives) {\n  ExtendedPose3 id;\n  if (ROT3_DEFAULT_COORDINATES_MODE == Rot3::EXPMAP) {\n    CHECK_CHART_DERIVATIVES(id,id);\n//    CHECK_CHART_DERIVATIVES(id,T2);\n//    CHECK_CHART_DERIVATIVES(T2,id);\n//    CHECK_CHART_DERIVATIVES(T2,T3);\n  }\n}\n\n\n/* ************************************************************************* */\nTEST(ExtendedPose3, interpolate) {\n  EXPECT(assert_equal(T2, interpolate(T2,T3, 0.0)));\n  EXPECT(assert_equal(T3, interpolate(T2,T3, 1.0)));\n}\n\n/* ************************************************************************* */\n\nTEST(ExtendedPose3, Create) {\n  Matrix93 actualH1, actualH2, actualH3;\n  ExtendedPose3 actual = ExtendedPose3::Create(R, V2, P2, actualH1, actualH2, actualH3);\n  EXPECT(assert_equal(T, actual));\n  boost::function<ExtendedPose3(Rot3,Point3,Point3)> create = boost::bind(ExtendedPose3::Create,_1,_2,_3,boost::none,boost::none,boost::none);\n  EXPECT(assert_equal(numericalDerivative31<ExtendedPose3,Rot3,Point3,Point3>(create, R, V2, P2), actualH1, 1e-9));\n  EXPECT(assert_equal(numericalDerivative32<ExtendedPose3,Rot3,Point3,Point3>(create, R, V2, P2), actualH2, 1e-9));\n  EXPECT(assert_equal(numericalDerivative33<ExtendedPose3,Rot3,Point3,Point3>(create, R, V2, P2), actualH3, 1e-9));\n}\n\n/* ************************************************************************* */\nTEST(ExtendedPose3, print) {\n  std::stringstream redirectStream;\n  std::streambuf* ssbuf = redirectStream.rdbuf();\n  std::streambuf* oldbuf  = std::cout.rdbuf();\n  // redirect cout to redirectStream\n  std::cout.rdbuf(ssbuf);\n\n  ExtendedPose3 pose(Rot3::identity(), Vector3(1, 2, 3), Point3(1, 2, 3));\n  // output is captured to redirectStream\n  pose.print();\n\n  // Generate the expected output\n  std::stringstream expected;\n  Vector3 velocity(1, 2, 3);\n  Point3 position(1, 2, 3);\n\n#ifdef GTSAM_TYPEDEF_POINTS_TO_VECTORS\n  expected << \"1\\n\"\n              \"2\\n\"\n              \"3;\\n\";\n#else\n  expected << \"v:[\" << velocity.x() << \", \" << velocity.y() << \", \" << velocity.z() << \"]';\\np:[\" << position.x() << \", \" << position.y() << \", \" << position.z() << \"]';\\n\";\n#endif\n\n  // reset cout to the original stream\n  std::cout.rdbuf(oldbuf);\n\n  // Get substring corresponding to position part\n  std::string actual = redirectStream.str().substr(38);\n  CHECK_EQUAL(expected.str(), actual);\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "149249db858e6eb27a12fe409474b569a78c2eb3", "size": 20404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/tests/testExtendedPose3.cpp", "max_stars_repo_name": "mbrossar/gtsam", "max_stars_repo_head_hexsha": "a5e8d5f7f9ed77032f521b75c728176a42f2766c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-10-07T05:59:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T13:40:00.000Z", "max_issues_repo_path": "gtsam/geometry/tests/testExtendedPose3.cpp", "max_issues_repo_name": "mbrossar/gtsam", "max_issues_repo_head_hexsha": "a5e8d5f7f9ed77032f521b75c728176a42f2766c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/geometry/tests/testExtendedPose3.cpp", "max_forks_repo_name": "mbrossar/gtsam", "max_forks_repo_head_hexsha": "a5e8d5f7f9ed77032f521b75c728176a42f2766c", "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.3533834586, "max_line_length": 173, "alphanum_fraction": 0.5931680063, "num_tokens": 6074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5253345868231453}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_CONSTANTS_RADINDEG_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_RADINDEG_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\n\nnamespace nt2\n{\n  namespace tag\n  {\n   /*!\n     @brief Radindeg generic tag\n\n     Represents the Radindeg constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    BOOST_SIMD_CONSTANT_REGISTER( Radindeg, double\n                                , 57, 0x42652ee1\n                                , 0x404ca5dc1a63c1f8ll\n                                )\n  }\n  namespace ext\n  {\n   template<class Site, class... Ts>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Radindeg, Site> dispatching_Radindeg(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n   {\n     return generic_dispatcher<tag::Radindeg, Site>();\n   }\n   template<class... Args>\n   struct impl_Radindeg;\n  }\n  /*!\n    Constant Radindeg : Degree in Radian multiplier, \\f$\\frac{180}\\pi\\f$.\n\n    @par Semantic:\n\n    For type T0:\n\n    @code\n    T0 r = Radindeg<T0>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T0 r = _180<T0>()/Pi<T0>();\n    @endcode\n\n    @see  @funcref{inrad}, @funcref{indeg}, @funcref{Radindegr}, @funcref{Deginrad}\n    @return a value of type T0\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Radindeg, Radindeg);\n}\n\nnamespace nt2\n{\n  /// INTERNAL ONLY\n}\n\n#endif\n\n", "meta": {"hexsha": "ca9ba1402006db1e572f499a074509bfa2969ba9", "size": 1954, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/radindeg.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/trigonometric/include/nt2/trigonometric/constants/radindeg.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/trigonometric/include/nt2/trigonometric/constants/radindeg.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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.7671232877, "max_line_length": 172, "alphanum_fraction": 0.5818833163, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.5253345864328619}}
{"text": "#include <iostream>\n#include <cassert>\n#include <vector>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/iterator/function_output_iterator.hpp>\n#include <boost/graph/biconnected_components.hpp>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph;\n\nvoid testcase()\n{\n  int n, m;\n  std::cin >> n >> m;\n  assert(n >= 0 && n <= 30000 && m >= 0 && m <= 30000);\n\n  Graph G(n + m);\n  std::vector<std::pair<int, int>> edges;\n  for (int i = 0; i < m; i++)\n  {\n    int start, end;\n    std::cin >> start >> end;\n    if (start > end)\n    {\n      std::swap(start, end);\n    }\n    assert(start >= 0 && start < n && end >= 0 && end < n && start < end);\n    edges.push_back(std::make_pair(start, end));\n    boost::add_edge(start, n + i, G);\n    boost::add_edge(n + i, end, G);\n  }\n\n  std::vector<std::pair<int, int>> critical_bridges;\n  auto on_articulation = [n, &critical_bridges, &edges](int vertex) {\n    if (vertex >= n)\n    {\n      critical_bridges.push_back(edges.at(vertex - n));\n    }\n  };\n  boost::articulation_points(G, boost::make_function_output_iterator(on_articulation));\n\n  std::cout << critical_bridges.size() << \"\\n\";\n  std::sort(critical_bridges.begin(), critical_bridges.end());\n  for (auto bridge : critical_bridges)\n  {\n    std::cout << bridge.first << \" \" << bridge.second << \"\\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": "a89bdab4212fcbe30e8fbf0f038b470f29052e65", "size": 1486, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-04/important-bridges/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/important-bridges/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/important-bridges/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": 24.3606557377, "max_line_length": 87, "alphanum_fraction": 0.6063257066, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5252903811406211}}
{"text": "#include <iostream>\n#include <fstream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <iomanip>\n#include <Eigen/Dense>\n#include <cmath>\n#include <vector>\n#include \"mnistrec.h\"\n\nusing namespace std;\nusing namespace MLP;\n\n", "meta": {"hexsha": "99f91a3fd105b57be4721fd081cc6c1e41319c07", "size": 221, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mnistrec.cpp", "max_stars_repo_name": "noasck/mnist_recognition_qt", "max_stars_repo_head_hexsha": "979337124a97b1a1dd3f788a209c42b8a3fc481d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-18T22:53:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T19:22:19.000Z", "max_issues_repo_path": "mnistrec.cpp", "max_issues_repo_name": "noasck/mnist_recognition_qt", "max_issues_repo_head_hexsha": "979337124a97b1a1dd3f788a209c42b8a3fc481d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mnistrec.cpp", "max_forks_repo_name": "noasck/mnist_recognition_qt", "max_forks_repo_head_hexsha": "979337124a97b1a1dd3f788a209c42b8a3fc481d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-03T04:32:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-03T04:32:20.000Z", "avg_line_length": 15.7857142857, "max_line_length": 22, "alphanum_fraction": 0.7330316742, "num_tokens": 51, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5252903713654111}}
{"text": "//  ================================================================\n//  Created by Gregory Kramida on 10/23/18.\n//  Copyright (c) 2018 Gregory Kramida\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#pragma once\n\n#include <Eigen/Eigen>\nnamespace eig = Eigen;\n\nnamespace math{\n\n//======================================================================================================================\n//\t\t                    Base Vector Structure (inspired by InfiniTAM ORUtils)\n//======================================================================================================================\n\ntemplate <class T> struct Vector2_{\n\tunion {\n\t\tstruct { T x, y; }; // standard names for components\n\t\tstruct { T s, t; }; // standard names for components\n\t\tstruct { T u, v; }; // standard names for components\n\t\tstruct { T width, height; }; // standard names for components\n\t\tT values[2];     // array access\n\t};\n};\n\ntemplate <class T> struct Vector3_{\n\tunion {\n\t\tstruct{ T x, y, z; }; // standard names for components\n\t\tstruct{ T r, g, b; }; // standard names for components\n\t\tstruct{ T s, t, p; }; // standard names for components\n\t\tstruct{ T u, v, w; }; // standard names for components\n\t\tT values[3];\n\t};\n};\n\ntemplate <class T> struct Vector4_ {\n\tunion {\n\t\tstruct { T fx, fy, cx, cy; }; // names for components of a projection matrix\n\t\tstruct { T x, y, z, w; }; // standard names for components\n\t\tstruct { T r, g, b, a; }; // standard names for components\n\t\tstruct { T s, t, p, q; }; // standard names for components\n\t\tstruct { T u_x, u_y, v_x, v_y; }; // names for gradients of a vector field with u and v fields\n\t\tT values[4];\n\t};\n};\n\ntemplate <class T> struct Vector6_ {\n\tunion {\n\t\tstruct { T min_x, min_y, min_z, max_x, max_y, max_z; };// standard names for components\n\t\tT values[6];\n\t};\n};\n\ntemplate <class T> struct Vector9_ {\n\tunion {\n\t\tstruct { T u_x, u_y, u_z, v_x, v_y, v_z, w_x, w_y, w_z;};// names for gradients of a vector field with u, v, and w fields\n\t\tT values[9];\n\t};\n};\n\ntemplate<class T, int s> struct VectorX_\n{\n\tT values[s];\n};\n\n\n}\n", "meta": {"hexsha": "c2d7a013b0211e9e629c08e2563a7754592cdd64", "size": 2633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/vector_base.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/vector_base.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/vector_base.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": 33.3291139241, "max_line_length": 123, "alphanum_fraction": 0.5689327763, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5252774184228098}}
{"text": "/**\n * @file transpsemilagr_test.cc\n * @brief NPDE homework TranspSemiLagr test file\n * @author Philippe Peter\n * @date November 2020\n * @copyright Developed at SAM, ETH Zurich\n */\n#include \"../transpsemilagr.h\"\n\n#include <gtest/gtest.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <cmath>\n#include <memory>\n\nnamespace TranspSemiLagr::test {\n\n// verifies that the vector u of nodal values satisfies zero boundary conditions\nvoid verify_zero_bc(\n    std::shared_ptr<const lf::uscalfe::UniformScalarFESpace<double>> fe_space,\n    const Eigen::VectorXd& u) {\n  auto mesh_p = fe_space->Mesh();\n  const auto& dof_h = fe_space->LocGlobMap();\n  auto boundary_nodes = lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 2);\n\n  for (int i = 0; i < u.size(); ++i) {\n    if (boundary_nodes(dof_h.Entity(i))) {\n      EXPECT_NEAR(u[i], 0.0, 1.0E-6);\n    }\n  }\n}\n\n// The first set of test cases verifies, that all methods produce solutions that\n// satisfy the zero dirichlet boundary conditions.\n\nTEST(ReactionStep, boundary_conditions) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u_function));\n  auto c_function = [](Eigen::VectorXd x) { return x(0) + x(1); };\n\n  verify_zero_bc(fe_space, u0_vector);\n  Eigen::VectorXd u_new = reaction_step(fe_space, u0_vector, c_function, 1.0);\n  verify_zero_bc(fe_space, u_new);\n}\n\nTEST(SemiLagrStep, boundary_conditions) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u_function));\n\n  auto v = [](Eigen::Vector2d x) {\n    return (Eigen::Vector2d() << -x(1) + 3.0 * x(0) * x(0), x(0)).finished();\n  };\n\n  verify_zero_bc(fe_space, u0_vector);\n  Eigen::VectorXd u_new = semiLagr_step(fe_space, u0_vector, v, 1.0);\n  verify_zero_bc(fe_space, u_new);\n}\n\nTEST(solverot, boundary_conditions) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  auto u_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u_function));\n\n  Eigen::VectorXd u_new = solverot(fe_space, u0_vector, 10, 1.0);\n  verify_zero_bc(fe_space, u_new);\n}\n\nTEST(solvetrp, boundary_conditions) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  auto u_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u_function));\n  Eigen::VectorXd u_new = solvetrp(fe_space, u0_vector, 10, 1.0);\n  verify_zero_bc(fe_space, u_new);\n}\n\n// The following two test cases test the reaction_step function\n// based on an exact solution u(x,t). Even though this exact solution\n// is a polynomial of degree four in x, it is still the case that\n// the approximate solution to the evolution problem is a good approximation\n// of the nodal projection of the exact solution at time T. Since\n// the reaction_step relies on a lumped mass matrix, the system of\n// equations decouble and for each component ODE the RK-scheme is applied.\n\n// u(x,t) = x0*(1-x0)*x1*(1-x1)*exp(2t)\nTEST(ReactionStep, exact_solution_constant_c) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  // solution function at initial time t=0\n  auto u0_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n\n  // solution function at final time t=1\n  auto u1_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0)) * std::exp(2 * 1.0);\n  };\n\n  // c function in the ODE:\n  auto c_function = [](Eigen::VectorXd /*x*/) { return 2.0; };\n\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u0_function));\n  Eigen::VectorXd u1_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u1_function));\n\n  // apply 100 reaction steps with time step 0.01\n  for (int i = 0; i < 100; ++i) {\n    u0_vector = reaction_step(fe_space, u0_vector, c_function, 0.01);\n  }\n  EXPECT_NEAR((u0_vector - u1_vector).norm(), 0.0, 1.0E-3);\n}\n\n// based on exact solution u(x,t) = x0*(1-x0)*x1*(1-x1)*exp(2t*x0 + t*x1))\nTEST(ReactionStep, exact_solution_linear_c) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  // solution function at initial time t=0\n  auto u0_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n\n  // solution function at final time t=1\n  auto u1_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0)) * std::exp(2 * x(0) + x(1));\n  };\n\n  // c function in the ODE:\n  auto c_function = [](Eigen::VectorXd x) { return 2.0 * x(0) + x(1); };\n\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u0_function));\n  Eigen::VectorXd u1_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u1_function));\n\n  // apply 100 reaction steps with time step 0.01\n  for (int i = 0; i < 100; ++i) {\n    u0_vector = reaction_step(fe_space, u0_vector, c_function, 0.01);\n  }\n  EXPECT_NEAR((u0_vector - u1_vector).norm(), 0.0, 1.0E-3);\n}\n\n// The following few testcases verify that solverot (and solvetrp) satisfy the\n// following: If solverot simulates N timesteps of the PDE on [0,T] with initial\n// condition u_0 the result should be the same as simulating N/2 timesteps on\n// [0,T/2] and then another N/2 timestpes on [0,T/2] with the updated initial\n// conditin, since all coefficients are indepentent of time.\nTEST(solverot, consistency_1) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u0_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u0_function));\n\n  Eigen::VectorXd sol_1 = solverot(fe_space, u0_vector, 2, 1.0);\n  Eigen::VectorXd sol_2 =\n      solverot(fe_space, solverot(fe_space, u0_vector, 1, 0.5), 1, 0.5);\n\n  EXPECT_NEAR((sol_1 - sol_2).norm(), 0.0, 1.0E-4);\n}\n\nTEST(solverot, consistency_2) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u0_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u0_function));\n\n  Eigen::VectorXd sol_1 = solverot(fe_space, u0_vector, 10, 1.0);\n  Eigen::VectorXd sol_2 =\n      solverot(fe_space, solverot(fe_space, u0_vector, 5, 0.5), 5, 0.5);\n\n  EXPECT_NEAR((sol_1 - sol_2).norm(), 0.0, 1.0E-4);\n}\n\nTEST(solverot, consistency_3) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u0_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u0_function));\n\n  Eigen::VectorXd sol_1 = solverot(fe_space, u0_vector, 10, 1.0);\n  Eigen::VectorXd sol_2 =\n      solverot(fe_space, solverot(fe_space, u0_vector, 1, 0.1), 9, 0.9);\n\n  EXPECT_NEAR((sol_1 - sol_2).norm(), 0.0, 1.0E-4);\n}\n\nTEST(solvetrp, consistency_1) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u0_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u0_function));\n\n  Eigen::VectorXd sol_1 = solvetrp(fe_space, u0_vector, 2, 1.0);\n  Eigen::VectorXd sol_2 =\n      solvetrp(fe_space, solvetrp(fe_space, u0_vector, 1, 0.5), 1, 0.5);\n\n  EXPECT_NEAR((sol_1 - sol_2).norm(), 0.0, 1.0E-4);\n}\n\nTEST(solvetrp, consistency_2) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u0_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u0_function));\n\n  Eigen::VectorXd sol_1 = solvetrp(fe_space, u0_vector, 10, 1.0);\n  Eigen::VectorXd sol_2 =\n      solvetrp(fe_space, solvetrp(fe_space, u0_vector, 5, 0.5), 5, 0.5);\n\n  EXPECT_NEAR((sol_1 - sol_2).norm(), 0.0, 1.0E-4);\n}\n\nTEST(solvetrp, consistency_3) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u0_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u0_function));\n\n  Eigen::VectorXd sol_1 = solvetrp(fe_space, u0_vector, 10, 1.0);\n  Eigen::VectorXd sol_2 =\n      solvetrp(fe_space, solvetrp(fe_space, u0_vector, 1, 0.1), 9, 0.9);\n\n  EXPECT_NEAR((sol_1 - sol_2).norm(), 0.0, 1.0E-4);\n}\n\n// The final set of test cases checks the output of solverot and solvetrp\n// against\n// a numerical refernce solution.\n\nTEST(solverot, reference_1) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u0_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u0_function));\n\n  Eigen::VectorXd u_ref(u0_vector.size());\n  u_ref << 0, 0, 0, 0, 0, 0.0159701, 0.0150475, 0, 0, 0.0171946, 0.0170436, 0,\n      0, 0, 0, 0;\n  Eigen::VectorXd u = solverot(fe_space, u0_vector, 1, 0.1);\n\n  EXPECT_NEAR((u - u_ref).norm(), 0.0, 1.0E-5);\n}\n\nTEST(solverot, reference_2) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u0_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u0_function));\n\n  Eigen::VectorXd u_ref(u0_vector.size());\n  u_ref << 0, 0, 0, 0, 0, 0.00860437, 0.00827551, 0, 0, 0.00910899, 0.00901993,\n      0, 0, 0, 0, 0;\n\n  Eigen::VectorXd u = solverot(fe_space, u0_vector, 10, 0.1);\n\n  EXPECT_NEAR((u - u_ref).norm(), 0.0, 1.0E-5);\n}\n\nTEST(solvetrp, reference_1) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u0_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u0_function));\n\n  Eigen::VectorXd u_ref(u0_vector.size());\n  u_ref << 0, 0, 0, 0, 0, 0.00993255, 0.00841276, 0, 0, 0.0105583, 0.00937419,\n      0, 0, 0, 0, 0;\n  Eigen::VectorXd u = solvetrp(fe_space, u0_vector, 1, 0.1);\n\n  EXPECT_NEAR((u - u_ref).norm(), 0.0, 1.0E-5);\n}\n\nTEST(solvetrp, reference_2) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto fe_space =\n      std::make_shared<const lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u0_function = [](Eigen::VectorXd x) {\n    return x(1) * x(0) * (1 - x(1)) * (1 - x(0));\n  };\n  Eigen::VectorXd u0_vector = lf::fe::NodalProjection(\n      *fe_space, lf::mesh::utils::MeshFunctionGlobal(u0_function));\n\n  Eigen::VectorXd u_ref(u0_vector.size());\n  u_ref << 0, 0, 0, 0, 0, 0.00670092, 0.00583407, 0, 0, 0.00707033, 0.00636342,\n      0, 0, 0, 0, 0;\n  Eigen::VectorXd u = solvetrp(fe_space, u0_vector, 10, 0.1);\n  EXPECT_NEAR((u - u_ref).norm(), 0.0, 1.0E-5);\n}\n\n}  // namespace TranspSemiLagr::test\n", "meta": {"hexsha": "ea407ed7ee3768bf1ca554a49a2688a9d0811b1d", "size": 13403, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/TranspSemiLagr/templates/test/transpsemilagr_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/TranspSemiLagr/templates/test/transpsemilagr_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/TranspSemiLagr/templates/test/transpsemilagr_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": 36.4211956522, "max_line_length": 80, "alphanum_fraction": 0.6626128479, "num_tokens": 4649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.5252774147775586}}
{"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 <Eigen/Core>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n#include <vector>\n\n#include \"gtest/gtest.h\"\n\n#include \"theia/math/util.h\"\n#include \"theia/util/random.h\"\n#include \"theia/util/util.h\"\n#include \"theia/matching/feature_correspondence.h\"\n#include \"theia/sfm/triangulation/triangulation.h\"\n#include \"theia/sfm/pose/test_util.h\"\n\nnamespace theia {\nusing Eigen::MatrixXd;\nusing Eigen::Matrix3d;\nusing Eigen::Quaterniond;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\nusing Eigen::Vector4d;\n\nnamespace {\n\nRandomNumberGenerator rng(59);\n\nenum TriangulationType {\n  STANDARD = 1,\n  DLT = 2,\n  MIDPOINT = 3\n};\n\ndouble ReprojectionError(const Matrix3x4d& pose,\n                         const Vector4d& world_point,\n                         const Vector2d& image_point) {\n  const Vector3d reprojected_point = pose * world_point;\n  const double sq_reproj_error =\n      (reprojected_point.hnormalized() - image_point).squaredNorm();\n  return sq_reproj_error;\n}\n\nvoid TestTriangulationBasic(const TriangulationType type,\n                            const Vector3d& point_3d,\n                            const Quaterniond& rel_rotation,\n                            const Vector3d& rel_translation,\n                            const double projection_noise,\n                            const double max_reprojection_error) {\n  Matrix3x4d pose1;\n  pose1 <<\n      rel_rotation.toRotationMatrix(), rel_translation.normalized();\n  const Matrix3x4d pose2 = Matrix3x4d::Identity();\n\n  // Reproject point into both image 2, assume image 1 is identity rotation at\n  // the origin.\n  Vector2d image_point1 =\n      (pose1 * point_3d.homogeneous()).eval().hnormalized();\n  Vector2d image_point2 =\n      (pose2 * point_3d.homogeneous()).eval().hnormalized();\n\n  // Add projection noise if required.\n  if (projection_noise) {\n    AddNoiseToProjection(projection_noise, &rng, &image_point1);\n    AddNoiseToProjection(projection_noise, &rng, &image_point2);\n  }\n\n  // Triangulate with Optimal.\n  Vector4d triangulated_point;\n  if (type == STANDARD) {\n    EXPECT_TRUE(Triangulate(pose1, pose2,\n                            image_point1, image_point2,\n                            &triangulated_point));\n  } else if (type == DLT) {\n    EXPECT_TRUE(\n        TriangulateDLT(pose1, pose2,\n                       image_point1, image_point2,\n                       &triangulated_point));\n  } else if (type == MIDPOINT) {\n    std::vector<Eigen::Vector3d> origins;\n    std::vector<Eigen::Vector3d> directions;\n\n    const Matrix3d rotation1 = pose1.block<3, 3>(0, 0);\n    origins.emplace_back(-rotation1.transpose() * pose1.col(3));\n    directions.emplace_back(\n        (rotation1.transpose() * image_point1.homogeneous()).normalized());\n    const Matrix3d rotation2 = pose2.block<3, 3>(0, 0);\n    origins.emplace_back(-rotation2.transpose() * pose2.col(3));\n    directions.emplace_back(\n        (rotation2.transpose() * image_point2.homogeneous()).normalized());\n    EXPECT_TRUE(\n        TriangulateMidpoint(origins, directions, &triangulated_point));\n  } else {\n    LOG(ERROR) << \"Incompatible Triangulation type!\";\n  }\n\n  // Check the reprojection error.\n  EXPECT_LE(\n      ReprojectionError(pose1, triangulated_point, image_point1),\n      max_reprojection_error);\n  EXPECT_LE(\n      ReprojectionError(pose2, triangulated_point, image_point2),\n      max_reprojection_error);\n}\n\nvoid TestTriangulationManyPoints(const double projection_noise,\n                                 const double max_reprojection_error) {\n  using Eigen::AngleAxisd;\n\n  static const int num_views = 8;\n\n  // Sets some test rotations and translations.\n  static const Quaterniond kRotations[num_views] = {\n    Quaterniond(\n        AngleAxisd(DegToRad(7.0), Vector3d(0.0, 0.0, 1.0).normalized())),\n    Quaterniond(\n        AngleAxisd(DegToRad(12.0), Vector3d(0.0, 1.0, 0.0).normalized())),\n    Quaterniond(\n        AngleAxisd(DegToRad(15.0), Vector3d(1.0, 0.0, 0.0).normalized())),\n    Quaterniond(\n        AngleAxisd(DegToRad(20.0), Vector3d(1.0, 0.0, 1.0).normalized())),\n    Quaterniond(\n        AngleAxisd(DegToRad(11.0), Vector3d(0.0, 1.0, 1.0).normalized())),\n    Quaterniond(\n        AngleAxisd(DegToRad(0.0), Vector3d(1.0, 1.0, 1.0).normalized())),\n    Quaterniond(\n        AngleAxisd(DegToRad(5.0), Vector3d(0.0, 1.0, 1.0).normalized())),\n    Quaterniond(AngleAxisd(DegToRad(0.0), Vector3d(1.0, 1.0, 1.0).normalized()))\n  };\n\n  static const Vector3d kTranslations[num_views] = {\n    Vector3d(1.0, 1.0, 1.0),\n    Vector3d(3.0, 2.0, 13.0),\n    Vector3d(4.0, 5.0, 11.0),\n    Vector3d(1.0, 2.0, 15.0),\n    Vector3d(3.0, 1.5, 91.0),\n    Vector3d(1.0, 7.0, 11.0),\n    Vector3d(0.0, 0.0, 0.0),  // Tests no translation.\n    Vector3d(0.0, 0.0, 0.0)  // Tests no translation and no rotation.\n  };\n\n  // Set up model points.\n  static const double kTestPoints[][3] = {\n    { -1.62, -2.99, 6.12 }, { 4.42, -1.53, 9.83 }, { 1.45, -0.59, 5.29 },\n    { 1.89, -1.10, 8.22 }, { -0.21, 2.38, 5.63 }, { 0.61, -0.97, 7.49 },\n    { 0.48, 0.70, 8.94 }, { 1.65, -2.56, 8.63 }, { 2.44, -0.20, 7.78 },\n    { 2.84, -2.58, 7.35 }, { -1.35, -2.84, 7.33 }, { -0.42, 1.54, 8.86 },\n    { 2.56, 1.72, 7.86 }, { 1.75, -1.39, 5.73 }, { 2.08, -3.91, 8.37 },\n    { -0.91, 1.36, 9.16 }, { 2.84, 1.54, 8.74 }, { -1.01, 3.02, 8.18 },\n    { -3.73, -0.62, 7.81 }, { -2.98, -1.88, 6.23 }, { 2.39, -0.19, 6.47 },\n    { -0.63, -1.05, 7.11 }, { -1.76, -0.55, 5.18 }, { -3.19, 3.27, 8.18 },\n    { 0.31, -2.77, 7.54 }, { 0.54, -3.77, 9.77 },\n  };\n\n  Eigen::Matrix3d calibration;\n  calibration <<\n      800.0, 0.0, 600.0,\n      0.0, 800.0, 400.0,\n      0.0, 0.0, 1.0;\n\n  // Set up pose matrices.\n  std::vector<Matrix3x4d> poses(num_views);\n  for (int i = 0; i < num_views; i++) {\n    poses[i] << kRotations[i].toRotationMatrix(), kTranslations[i];\n  }\n\n  for (int j = 0; j < THEIA_ARRAYSIZE(kTestPoints); j++) {\n    // Reproject model point into the images.\n    std::vector<Vector2d> image_points(num_views);\n    const Vector3d model_point(kTestPoints[j][0], kTestPoints[j][1],\n                               kTestPoints[j][2]);\n    for (int i = 0; i < num_views; i++) {\n      image_points[i] =\n          (poses[i] * model_point.homogeneous()).eval().hnormalized();\n    }\n\n    // Add projection noise if required.\n    if (projection_noise) {\n      for (int i = 0; i < num_views; i++) {\n        AddNoiseToProjection(projection_noise, &rng, &image_points[i]);\n      }\n    }\n\n    Vector4d triangulated_point;\n    ASSERT_TRUE(TriangulateNView(poses, image_points, &triangulated_point));\n\n    // Check the reprojection error.\n    for (int i = 0; i < num_views; i++) {\n      EXPECT_LE(ReprojectionError(poses[i],\n                                  triangulated_point, image_points[i]),\n                max_reprojection_error);\n    }\n  }\n}\n\nTEST(Triangulation, BasicTest) {\n  static const double kProjectionNoise = 0.0;\n  static const double kReprojectionTolerance = 1e-12;\n\n  // Set up model points.\n  const Vector3d points_3d[2] = { Vector3d(5.0, 20.0, 23.0),\n                                  Vector3d(-6.0, 16.0, 33.0) };\n\n  // Set up rotations.\n  const Quaterniond kRotation(Eigen::AngleAxisd(0.15, Vector3d(0.0, 1.0, 0.0)));\n\n  // Set up translations.\n  const Vector3d kTranslation(-3.0, 1.5, 11.0);\n\n  // Run the test.\n  for (int i = 0; i < 2; i++) {\n    TestTriangulationBasic(TriangulationType::STANDARD,\n                           points_3d[i],\n                           kRotation,\n                           kTranslation,\n                           kProjectionNoise,\n                           kReprojectionTolerance);\n  }\n}\n\nTEST(Triangulation, NoiseTest) {\n  static const double kProjectionNoise = 1.0 / 512.0;\n  static const double kReprojectionTolerance = 1e-5;\n\n  // Set up model points.\n  const Vector3d points_3d[2] = { Vector3d(5.0, 20.0, 23.0),\n                                  Vector3d(-6.0, 16.0, 33.0) };\n\n  // Set up rotations.\n  const Quaterniond kRotation(Eigen::AngleAxisd(0.15, Vector3d(0.0, 1.0, 0.0)));\n\n  // Set up translations.\n  const Vector3d kTranslation(-3.0, 1.5, 11.0);\n\n  // Run the test.\n  for (int i = 0; i < 2; i++) {\n    TestTriangulationBasic(TriangulationType::STANDARD,\n                           points_3d[i],\n                           kRotation,\n                           kTranslation,\n                           kProjectionNoise,\n                           kReprojectionTolerance);\n  }\n}\n\nTEST(TriangulationDLT, BasicTest) {\n  static const double kProjectionNoise = 0.0;\n  static const double kReprojectionTolerance = 1e-12;\n\n  // Set up model points.\n  const Vector3d points_3d[2] = { Vector3d(5.0, 20.0, 23.0),\n                                  Vector3d(-6.0, 16.0, 33.0) };\n\n  // Set up rotations.\n  const Quaterniond kRotation(Eigen::AngleAxisd(0.15, Vector3d(0.0, 1.0, 0.0)));\n\n  // Set up translations.\n  const Vector3d kTranslation(-3.0, 1.5, 11.0);\n\n  // Run the test.\n  for (int i = 0; i < 2; i++) {\n    TestTriangulationBasic(TriangulationType::DLT,\n                           points_3d[i],\n                           kRotation,\n                           kTranslation,\n                           kProjectionNoise,\n                           kReprojectionTolerance);\n  }\n}\n\nTEST(TriangulationDLT, NoiseTest) {\n  static const double kProjectionNoise = 1.0 / 512.0;\n  static const double kReprojectionTolerance = 1e-5;\n\n  // Set up model points.\n  const Vector3d points_3d[2] = { Vector3d(5.0, 20.0, 23.0),\n                                  Vector3d(-6.0, 16.0, 33.0) };\n\n  // Set up rotations.\n  const Quaterniond kRotation(Eigen::AngleAxisd(0.15, Vector3d(0.0, 1.0, 0.0)));\n\n  // Set up translations.\n  const Vector3d kTranslation(-3.0, 1.5, 11.0);\n\n  // Run the test.\n  for (int i = 0; i < 2; i++) {\n    TestTriangulationBasic(TriangulationType::DLT,\n                           points_3d[i],\n                           kRotation,\n                           kTranslation,\n                           kProjectionNoise,\n                           kReprojectionTolerance);\n  }\n}\n\nTEST(TriangulationMidpoint, BasicTest) {\n  static const double kProjectionNoise = 0.0;\n  static const double kReprojectionTolerance = 1e-12;\n\n  // Set up model points.\n  const Vector3d points_3d[2] = { Vector3d(5.0, 20.0, 23.0),\n                                  Vector3d(-6.0, 16.0, 33.0) };\n\n  // Set up rotations.\n  const Quaterniond kRotation(Eigen::AngleAxisd(0.15, Vector3d(0.0, 1.0, 0.0)));\n\n  // Set up translations.\n  const Vector3d kTranslation(-3.0, 1.5, 11.0);\n\n  // Run the test.\n  for (int i = 0; i < 2; i++) {\n    TestTriangulationBasic(TriangulationType::MIDPOINT,\n                           points_3d[i],\n                           kRotation,\n                           kTranslation,\n                           kProjectionNoise,\n                           kReprojectionTolerance);\n  }\n}\n\nTEST(TriangulationMidpoint, NoiseTest) {\n  static const double kProjectionNoise = 1.0 / 512.0;\n  static const double kReprojectionTolerance = 1e-5;\n\n  // Set up model points.\n  const Vector3d points_3d[2] = { Vector3d(5.0, 20.0, 23.0),\n                                  Vector3d(-6.0, 16.0, 33.0) };\n\n  // Set up rotations.\n  const Quaterniond kRotation(Eigen::AngleAxisd(0.15, Vector3d(0.0, 1.0, 0.0)));\n\n  // Set up translations.\n  const Vector3d kTranslation(-3.0, 1.5, 11.0);\n\n  // Run the test.\n  for (int i = 0; i < 2; i++) {\n    TestTriangulationBasic(TriangulationType::MIDPOINT,\n                           points_3d[i],\n                           kRotation,\n                           kTranslation,\n                           kProjectionNoise,\n                           kReprojectionTolerance);\n  }\n}\n\nTEST(TriangulationNView, BasicTest) {\n  static const double kProjectionNoise = 0.0;\n  static const double kReprojectionTolerance = 1e-12;\n\n  // Run the test.\n  TestTriangulationManyPoints(kProjectionNoise, kReprojectionTolerance);\n}\n\nTEST(TriangulationNView, NoiseTest) {\n  static const double kProjectionNoise = 1.0 / 512.0;\n  static const double kReprojectionTolerance = 5e-4;\n\n  // Run the test.\n  TestTriangulationManyPoints(kProjectionNoise, kReprojectionTolerance);\n}\n\nvoid TestIsTriangulatedPointInFrontOfCameras(\n    const Eigen::Vector3d& point3d,\n    const Eigen::Matrix3d& rotation,\n    const Eigen::Vector3d& translation,\n    const bool expected_outcome) {\n  FeatureCorrespondence correspondence;\n  correspondence.feature1.point_ = point3d.hnormalized();\n  correspondence.feature2.point_ =\n      (rotation * point3d + translation).hnormalized();\n  const Vector3d position = -rotation.transpose() * translation;\n  EXPECT_EQ(IsTriangulatedPointInFrontOfCameras(\n      correspondence,\n      rotation,\n      position),\n            expected_outcome);\n}\n\nTEST(IsTriangulatedPointInFrontOfCameras, InFront) {\n  const Matrix3d rotation = Matrix3d::Identity();\n  const Vector3d position(-1, 0, 0);\n  const Vector3d point(0, 0, 5);\n  TestIsTriangulatedPointInFrontOfCameras(point, rotation, position, true);\n}\n\nTEST(IsTriangulatedPointInFrontOfCameras, Behind) {\n  const Matrix3d rotation = Matrix3d::Identity();\n  const Vector3d position(-1, 0, 0);\n  const Vector3d point(0, 0, -5);\n  TestIsTriangulatedPointInFrontOfCameras(point, rotation, position, false);\n}\n\nTEST(IsTriangulatedPointInFrontOfCameras, OneInFrontOneBehind) {\n  const Matrix3d rotation = Matrix3d::Identity();\n  const Vector3d position(0, 0, -2);\n  const Vector3d point(0, 0, 1);\n  TestIsTriangulatedPointInFrontOfCameras(point, rotation, position, false);\n}\n\nTEST(SufficientTriangulationAngle, AllSufficient) {\n  static const double kMinSufficientAngle = 4.0;\n  static const double kAngleBetweenCameras = 5.0;\n\n  // Try varying numbers of cameras observing a 3d point from 2 to 50 cameras.\n  for (int i = 2; i < 50; i++) {\n    // Set up cameras on a unit circle so that the angles are known. Assume that\n    // the triangulated point is at (0, 0, 0).\n    std::vector<Vector3d> rays;\n    for (int j = 0; j < i; j++) {\n      rays.emplace_back(cos(DegToRad(j * kAngleBetweenCameras)),\n                        sin(DegToRad(j * kAngleBetweenCameras)),\n                        0.0);\n    }\n\n    EXPECT_TRUE(SufficientTriangulationAngle(rays, kMinSufficientAngle));\n  }\n}\n\nTEST(SufficientTriangulationAngle, AllInsufficient) {\n  static const double kMinSufficientAngle = 4.0;\n\n  // Try varying numbers of cameras observing a 3d point from 2 to 50 cameras.\n  for (int i = 2; i < 50; i++) {\n    // Set up cameras on a unit circle so that the angles are known. Assume that\n    // the triangulated point is at (0, 0, 0).\n    std::vector<Vector3d> rays;\n    const double angle = kMinSufficientAngle / static_cast<double>(i + 1e-4);\n    for (int j = 0; j < i; j++) {\n      rays.emplace_back(cos(DegToRad(j * angle)),\n                        sin(DegToRad(j * angle)),\n                        0.0);\n    }\n\n    EXPECT_FALSE(SufficientTriangulationAngle(rays, kMinSufficientAngle));\n  }\n}\n\nTEST(SufficientTriangulationAngle, SomeInsufficient) {\n  static const double kMinSufficientAngle = 4.0;\n\n  // Set up cameras on a unit circle so that the angles are known. Assume that\n  // the triangulated point is at (0, 0, 0).\n  std::vector<Vector3d> rays;\n  rays.emplace_back(cos(DegToRad(0)), sin(DegToRad(0)), 0.0);\n  rays.emplace_back(cos(DegToRad(5.0)), sin(DegToRad(5.0)), 0.0);\n  rays.emplace_back(cos(DegToRad(1.0)), sin(DegToRad(1.0)), 0.0);\n\n  // We only need one pair of rays to have a sufficient viewing angle, so this\n  // should return true since views 0 and 2 have a viewing angle of 5 degree.\n  EXPECT_TRUE(SufficientTriangulationAngle(rays, kMinSufficientAngle));\n}\n\nTEST(SufficientTriangulationAngle, TwoInsufficient) {\n  static const double kMinSufficientAngle = 4.0;\n\n  // Set up cameras on a unit circle so that the angles are known. Assume that\n  // the triangulated point is at (0, 0, 0).\n  std::vector<Vector3d> rays;\n  rays.emplace_back(cos(DegToRad(0)), sin(DegToRad(0)), 0.0);\n  rays.emplace_back(cos(DegToRad(1.0)), sin(DegToRad(1.0)), 0.0);\n\n  // We only need one pair of rays to have a sufficient viewing angle, so this\n  // should return true since views 0 and 2 have a viewing angle of 5 degree.\n  EXPECT_FALSE(SufficientTriangulationAngle(rays, kMinSufficientAngle));\n}\n\n}  // namespace\n}  // namespace theia\n", "meta": {"hexsha": "3b53c9dab98234c53e3bb7e94237b67ede7eedd0", "size": 17950, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/triangulation/triangulation_test.cc", "max_stars_repo_name": "Sergej91/TheiaSfM", "max_stars_repo_head_hexsha": "e603e16888456c3e565a2c197fa9f8643c176175", "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/theia/sfm/triangulation/triangulation_test.cc", "max_issues_repo_name": "Sergej91/TheiaSfM", "max_issues_repo_head_hexsha": "e603e16888456c3e565a2c197fa9f8643c176175", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/triangulation/triangulation_test.cc", "max_forks_repo_name": "Sergej91/TheiaSfM", "max_forks_repo_head_hexsha": "e603e16888456c3e565a2c197fa9f8643c176175", "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.8283433134, "max_line_length": 80, "alphanum_fraction": 0.6337604457, "num_tokens": 5319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5252774117010416}}
{"text": "#include \"pinocchio/math/multiprecision.hpp\"\n\n#include \"pinocchio/parsers/urdf.hpp\"\n\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#include <iostream>\n\n// PINOCCHIO_MODEL_DIR is defined by the CMake but you can define your own directory here.\n#ifndef PINOCCHIO_MODEL_DIR\n  #define PINOCCHIO_MODEL_DIR \"path_to_the_model_dir\"\n#endif\n\nint main(int argc, char ** argv)\n{\n  using namespace pinocchio;\n  \n  // You should change here to set up your own URDF file or just pass it as an argument of this example.\n  const std::string urdf_filename = (argc<=1) ? PINOCCHIO_MODEL_DIR + std::string(\"/example-robot-data/robots/ur_description/urdf/ur5_robot.urdf\") : argv[1];\n  \n  // Load the URDF model\n  Model model;\n  pinocchio::urdf::buildModel(urdf_filename,model);\n  \n  // Build a data related to model\n  Data data(model);\n  \n  // Define Model and Data for multiprecision types\n  typedef boost::multiprecision::cpp_dec_float_100 float_100;\n  typedef ModelTpl<float_100> ModelMulti;\n  typedef DataTpl<float_100> DataMulti;\n  \n  ModelMulti model_multi = model.cast<float_100>();\n  DataMulti data_multi(model_multi);\n  \n  // Sample a random joint configuration as well as random joint velocity and acceleration\n  ModelMulti::ConfigVectorType q_multi = randomConfiguration(model_multi);\n  ModelMulti::TangentVectorType v_multi = ModelMulti::TangentVectorType::Random(model.nv);\n  ModelMulti::TangentVectorType a_multi = ModelMulti::TangentVectorType::Random(model.nv);\n  \n  Model::ConfigVectorType q = q_multi.cast<double>();\n  Model::TangentVectorType v = v_multi.cast<double>();\n  Model::TangentVectorType a = a_multi.cast<double>();\n  \n  // Computes the inverse dynamics (aka RNEA)\n  rnea(model, data, q, v, a);\n  rnea(model_multi , data_multi , q_multi , v_multi , a_multi);\n  \n  // Get access to the joint torque with standard or multiprecision arithmetic and print sufficient decimals for both precisions\n  std::cout << \"Joint torque standard arithmetic:\\n\" << std::setprecision(std::numeric_limits<float_100>::max_digits10) << data.tau << std::endl;\n  std::cout << \"Joint torque multiprecision arithmetic:\\n\" << std::setprecision(std::numeric_limits<float_100>::max_digits10) << data_multi.tau << std::endl;\n}\n\n", "meta": {"hexsha": "ad605ef80acafa9c4b7704f5488e4d77f14828d3", "size": 2308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/multiprecision.cpp", "max_stars_repo_name": "Sreevis/pinocchio", "max_stars_repo_head_hexsha": "7e3f96e59047b40e678a53b3877b401af4b6d0bd", "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": "examples/multiprecision.cpp", "max_issues_repo_name": "Sreevis/pinocchio", "max_issues_repo_head_hexsha": "7e3f96e59047b40e678a53b3877b401af4b6d0bd", "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": "examples/multiprecision.cpp", "max_forks_repo_name": "Sreevis/pinocchio", "max_forks_repo_head_hexsha": "7e3f96e59047b40e678a53b3877b401af4b6d0bd", "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": 40.4912280702, "max_line_length": 157, "alphanum_fraction": 0.756932409, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5252774080557908}}
{"text": "#include \"advent.hpp\"\n\n#include <fmt/color.h>\n#include <fmt/ranges.h>\n#include <fstream>\n#include <gsl/gsl_util>\n#include <iostream>\n#include <tuple>\n#include <ranges>\n#include <scn/scn.h>\n#include <vector>\n\n#include <Eigen/Core>\n\nusing std::ifstream;\nusing std::pair;\nusing std::string;\nusing std::vector;\nusing std::ranges::views::iota;\n\nusing Eigen::Array;\n\nconstexpr i64 energy_level = 9;\n\nauto get_block(auto& m, auto i, auto j) -> std::tuple<i64, i64, i64, i64> {\n    auto x = std::max(0L, i-1);\n    auto y = std::max(0L, j-1);\n    return std::make_tuple(x, y,\n            std::min(3L - (i == 0), m.rows() - x),\n            std::min(3L - (j == 0), m.cols() - y));\n}\n\nauto flash(auto& m, auto& f, auto i, auto j) {\n    if (f(i, j) || m(i, j) <= energy_level) { return; }\n    f(i, j) = 1;\n    auto [x, y, w, h] = get_block(m, i, j);\n    m.block(x, y, w, h) += 1;\n    for (auto ii = x; ii < x + w; ++ii) {\n        for (auto jj = y; jj < y + h; ++jj) {\n            flash(m, f, ii, jj);\n        }\n    }\n};\n\nauto day11(int argc, char** argv) -> int\n{\n    if (argc < 2) {\n        fmt::print(\"Error: no input.\");\n        return 1;\n    }\n\n    ifstream infile(argv[1]); // NOLINT\n    string line;\n    std::getline(infile, line);\n    const i64 ncol = std::ssize(line);\n    const i64 nrow = std::count(std::istreambuf_iterator<char>(infile), std::istreambuf_iterator<char>(), '\\n');\n    infile.seekg(0); // rewind the input stream\n\n    Array<i64, -1, -1> map(nrow + 1, ncol);\n    i64 row{0};\n    while (std::getline(infile, line)) { // NOLINT\n        i64 col{0};\n        for (auto c : line) {\n            map(row, col++) = static_cast<int>(c - '0');\n        }\n        ++row;\n    }\n\n    decltype(map) flashed = decltype(map)::Zero(map.rows(), map.cols());\n\n    i64 part1{0};\n    i64 part2{0};\n    const i64 part1_steps{100};\n\n    for (auto s = 1L; ; ++s) {\n        flashed.fill(0);\n        map += 1;\n\n        for (auto i : iota(0L, map.rows())) {\n            for (auto j : iota(0L, map.cols())) {\n                flash(map, flashed, i, j);\n            }\n        }\n        map = (map > energy_level).select(0, map);\n        auto flashes = (map == 0).count();\n        if (s <= part1_steps) {\n            part1 += flashes;\n        }\n        if (flashes == map.size()) {\n            part2 = s;\n            break;\n        }\n    }\n    fmt::print(\"part 1: {}\\n\", part1);\n    fmt::print(\"part 2: {}\\n\", part2);\n    \n    return 0;\n}\n", "meta": {"hexsha": "df8c95f02c8744e4374614c80b2f784c1253c039", "size": 2417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/day11.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/day11.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/day11.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": 24.4141414141, "max_line_length": 112, "alphanum_fraction": 0.5064129086, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5252774044105393}}
{"text": "#include <elle/math.hh>\n\n#include <string>\n\n#include <boost/range/irange.hpp>\n\n#include <elle/range.hh>\n#include <elle/test.hh>\n\nstatic\nvoid\nsum()\n{\n  BOOST_TEST(elle::sum() == 0);\n  BOOST_TEST(elle::sum(1) == 1);\n  BOOST_TEST(elle::sum(1, 2) == 3);\n  BOOST_TEST(elle::sum(1, 2, 3) == 6);\n}\n\nstatic\nvoid\nproduct()\n{\n  BOOST_TEST(elle::product() == 1);\n  BOOST_TEST(elle::product(1) == 1);\n  BOOST_TEST(elle::product(1, 2) == 2);\n  BOOST_TEST(elle::product(1, 2, 3) == 6);\n  BOOST_TEST(elle::product(0, 1, 2, 3) == 0);\n}\n\nELLE_TEST_SUITE()\n{\n  auto& master = boost::unit_test::framework::master_test_suite();\n  master.add(BOOST_TEST_CASE(sum));\n  master.add(BOOST_TEST_CASE(product));\n}\n", "meta": {"hexsha": "6a509c26c230336347b4d5d4de139bb5a2a37c88", "size": 686, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/elle/math.cc", "max_stars_repo_name": "infinit/elle", "max_stars_repo_head_hexsha": "a8154593c42743f45b9df09daf62b44630c24a02", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 521.0, "max_stars_repo_stars_event_min_datetime": "2016-02-14T00:39:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T22:39:25.000Z", "max_issues_repo_path": "tests/elle/math.cc", "max_issues_repo_name": "mefyl/elle", "max_issues_repo_head_hexsha": "a8154593c42743f45b9df09daf62b44630c24a02", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-02-21T11:47:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-01T09:37:14.000Z", "max_forks_repo_path": "tests/elle/math.cc", "max_forks_repo_name": "mefyl/elle", "max_forks_repo_head_hexsha": "a8154593c42743f45b9df09daf62b44630c24a02", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2017-02-21T10:18:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:35:20.000Z", "avg_line_length": 18.5405405405, "max_line_length": 66, "alphanum_fraction": 0.6443148688, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925402, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5252717375313134}}
{"text": "#include \"drake/math/gradient_util.h\"\n\n#include <array>\n#include <random>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <gtest/gtest.h>\n\n#include \"drake/common/test_utilities/eigen_matrix_compare.h\"\n\nusing Eigen::Matrix;\nusing Eigen::MatrixXd;\n\nnamespace drake {\nnamespace math {\nnamespace {\n\nGTEST_TEST(DrakeGradientUtilTest, MatGradMult) {\n  const int nq = 34;\n  const int A_rows = 8;\n  const int A_cols = 6;\n  auto dA = MatrixXd::Random(A_rows * A_cols, nq).eval();\n  auto b = Matrix<double, A_cols, 1>::Random().eval();\n  auto dAb = matGradMult(dA, b).eval();\n  auto A = Matrix<double, A_rows, A_cols>::Random().eval();\n  auto db = MatrixXd::Zero(b.rows(), nq).eval();\n  auto dAb_check = matGradMultMat(A, b, dA, db);\n\n  EXPECT_TRUE(CompareMatrices(dAb, dAb_check, 1e-10,\n                              MatrixCompareType::absolute));\n}\n\nGTEST_TEST(DrakeGradientUtilTest, SetSubMatrixGradient) {\n  const int A_rows = 4;\n  const int A_cols = 4;\n  const int nq = 34;\n\n  std::array<int, 3> rows{{0, 1, 2}};\n  std::array<int, 3> cols{{0, 1, 2}};\n\n  int q_start = 2;\n  const int q_subvector_size = 3;\n  MatrixXd dA_submatrix =\n      MatrixXd::Random(rows.size() * cols.size(), q_subvector_size);\n\n  auto dA = Matrix<double, A_rows * A_cols, Eigen::Dynamic>::Random(\n                A_rows * A_cols, nq).eval();\n  setSubMatrixGradient<Eigen::Dynamic>(dA, dA_submatrix, rows, cols, A_rows,\n                                       q_start, q_subvector_size);\n\n  auto dA_submatrix_back = getSubMatrixGradient<Eigen::Dynamic>(\n      dA, rows, cols, A_rows, q_start, q_subvector_size);\n\n  EXPECT_TRUE(CompareMatrices(dA_submatrix_back, dA_submatrix, 1e-10,\n                              MatrixCompareType::absolute));\n}\n\n}  // namespace\n}  // namespace math\n}  // namespace drake\n", "meta": {"hexsha": "715561d338d74fae788d49c471e72e12baf5692b", "size": 1800, "ext": "cc", "lang": "C++", "max_stars_repo_path": "math/test/gradient_util_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/gradient_util_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/gradient_util_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": 28.5714285714, "max_line_length": 76, "alphanum_fraction": 0.66, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.52527173563456}}
{"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__BUNDLE_HPP_\n#define SMOOTH__INTERNAL__BUNDLE_HPP_\n\n#include <array>\n\n#include <Eigen/Core>\n\n#include \"common.hpp\"\n#include \"smooth/internal/utils.hpp\"\n\n/**\n * @brief Bundle Lie group\n *\n * Represents the direct product\n *  G1 x G2 x ... x Gk\n * for Lie groups G1 ... Gk.\n */\nnamespace smooth {\n\nusing std::get;\n\ntemplate<typename... GsImpl>\nstruct BundleImpl\n{\n  using Scalar = std::common_type_t<typename GsImpl::Scalar...>;\n\n  static_assert(\n    (std::is_same_v<Scalar, typename GsImpl::Scalar> && ...),\n    \"Implementation Scalar types must be the same\");\n\n  static constexpr std::array<Eigen::Index, sizeof...(GsImpl)> RepSizes{GsImpl::RepSize...};\n  static constexpr std::array<Eigen::Index, sizeof...(GsImpl)> Dofs{GsImpl::Dof...};\n  static constexpr std::array<Eigen::Index, sizeof...(GsImpl)> Dims{GsImpl::Dim...};\n\n  static constexpr auto RepSizesPsum = smooth::utils::array_psum(RepSizes);\n  static constexpr auto DofsPsum     = smooth::utils::array_psum(Dofs);\n  static constexpr auto DimsPsum     = smooth::utils::array_psum(Dims);\n\n  template<std::size_t Idx>\n  using PartImpl = std::tuple_element_t<Idx, std::tuple<GsImpl...>>;\n\n  static constexpr Eigen::Index RepSize = RepSizesPsum.back();\n  static constexpr Eigen::Index Dof     = DofsPsum.back();\n  static constexpr Eigen::Index Dim     = DimsPsum.back();\n\n  SMOOTH_DEFINE_REFS;\n\n  // clang-format off\n\n  static void setIdentity(GRefOut g_out)\n  {\n    smooth::utils::static_for<sizeof...(GsImpl)>([&](auto i) {\n      PartImpl<i>::setIdentity(\n        g_out.template segment<get<i>(RepSizes)>(get<i>(RepSizesPsum))\n      );\n    });\n  }\n\n  static void setRandom(GRefOut g_out)\n  {\n    smooth::utils::static_for<sizeof...(GsImpl)>([&](auto i) {\n      PartImpl<i>::setRandom(\n        g_out.template segment<get<i>(RepSizes)>(get<i>(RepSizesPsum))\n      );\n    });\n  }\n\n  static void matrix(GRefIn g_in, MRefOut m_out)\n  {\n    m_out.setZero();\n    smooth::utils::static_for<sizeof...(GsImpl)>([&](auto i) {\n      PartImpl<i>::matrix(\n        g_in.template segment<get<i>(RepSizes)>(get<i>(RepSizesPsum)),\n        m_out.template block<get<i>(Dims), get<i>(Dims)>(get<i>(DimsPsum), get<i>(DimsPsum))\n      );\n    });\n  }\n\n  static void composition(GRefIn g_in1, GRefIn g_in2, GRefOut g_out)\n  {\n    smooth::utils::static_for<sizeof...(GsImpl)>([&](auto i) {\n      PartImpl<i>::composition(\n        g_in1.template segment<get<i>(RepSizes)>(get<i>(RepSizesPsum)),\n        g_in2.template segment<get<i>(RepSizes)>(get<i>(RepSizesPsum)),\n        g_out.template segment<get<i>(RepSizes)>(get<i>(RepSizesPsum))\n      );\n    });\n  }\n\n  static void inverse(GRefIn g_in, GRefOut g_out)\n  {\n    smooth::utils::static_for<sizeof...(GsImpl)>([&](auto i) {\n      PartImpl<i>::inverse(\n        g_in.template segment<get<i>(RepSizes)>(get<i>(RepSizesPsum)),\n        g_out.template segment<get<i>(RepSizes)>(get<i>(RepSizesPsum))\n      );\n    });\n  }\n\n  static void log(GRefIn g_in, TRefOut a_out)\n  {\n    smooth::utils::static_for<sizeof...(GsImpl)>([&](auto i) {\n      PartImpl<i>::log(\n        g_in.template segment<get<i>(RepSizes)>(get<i>(RepSizesPsum)),\n        a_out.template segment<get<i>(Dofs)>(get<i>(DofsPsum))\n      );\n    });\n  }\n\n  static void Ad(GRefIn g_in, TMapRefOut A_out)\n  {\n    A_out.setZero();\n    smooth::utils::static_for<sizeof...(GsImpl)>([&](auto i) {\n      PartImpl<i>::Ad(\n        g_in.template segment<get<i>(RepSizes)>(get<i>(RepSizesPsum)),\n        A_out.template block<get<i>(Dofs), get<i>(Dofs)>(get<i>(DofsPsum), get<i>(DofsPsum))\n      );\n    });\n  }\n\n  static void exp(TRefIn a_in, GRefOut g_out)\n  {\n    smooth::utils::static_for<sizeof...(GsImpl)>([&](auto i) {\n      PartImpl<i>::exp(\n        a_in.template segment<get<i>(Dofs)>(get<i>(DofsPsum)),\n        g_out.template segment<get<i>(RepSizes)>(get<i>(RepSizesPsum))\n      );\n    });\n  }\n\n  static void hat(TRefIn a_in, MRefOut A_out)\n  {\n    A_out.setZero();\n    smooth::utils::static_for<sizeof...(GsImpl)>([&](auto i) {\n      PartImpl<i>::hat(\n        a_in.template segment<get<i>(Dofs)>(get<i>(DofsPsum)),\n        A_out.template block<get<i>(Dims), get<i>(Dims)>(get<i>(DimsPsum), get<i>(DimsPsum))\n      );\n    });\n  }\n\n  static void vee(MRefIn A_in, TRefOut a_out)\n  {\n    smooth::utils::static_for<sizeof...(GsImpl)>([&](auto i) {\n      PartImpl<i>::vee(\n        A_in.template block<get<i>(Dims), get<i>(Dims)>(get<i>(DimsPsum), get<i>(DimsPsum)),\n        a_out.template segment<get<i>(Dofs)>(get<i>(DofsPsum))\n      );\n    });\n  }\n\n  static void ad(TRefIn a_in, TMapRefOut A_out) {\n    A_out.setZero();\n    smooth::utils::static_for<sizeof...(GsImpl)>([&](auto i) {\n      PartImpl<i>::ad(\n        a_in.template segment<get<i>(Dofs)>(get<i>(DofsPsum)),\n        A_out.template block<get<i>(Dofs), get<i>(Dofs)>(get<i>(DofsPsum), get<i>(DofsPsum))\n      );\n    });\n  }\n\n  static void dr_exp(TRefIn a_in, TMapRefOut A_out) {\n    A_out.setZero();\n    smooth::utils::static_for<sizeof...(GsImpl)>([&](auto i) {\n      PartImpl<i>::dr_exp(\n        a_in.template segment<get<i>(Dofs)>(get<i>(DofsPsum)),\n        A_out.template block<get<i>(Dofs), get<i>(Dofs)>(get<i>(DofsPsum), get<i>(DofsPsum))\n      );\n    });\n  }\n\n  static void dr_expinv(TRefIn a_in, TMapRefOut A_out) {\n    A_out.setZero();\n    smooth::utils::static_for<sizeof...(GsImpl)>([&](auto i) {\n      PartImpl<i>::dr_expinv(\n        a_in.template segment<get<i>(Dofs)>(get<i>(DofsPsum)),\n        A_out.template block<get<i>(Dofs), get<i>(Dofs)>(get<i>(DofsPsum), get<i>(DofsPsum))\n      );\n    });\n  }\n\n  // clang-format on\n};\n\n}  // namespace smooth\n\n#endif  // SMOOTH__INTERNAL__BUNDLE_HPP_\n", "meta": {"hexsha": "4d45698247227ed16146a0807828e95cd48ef324", "size": 6884, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/internal/bundle.hpp", "max_stars_repo_name": "pettni/smooth", "max_stars_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T21:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T13:26:44.000Z", "max_issues_repo_path": "include/smooth/internal/bundle.hpp", "max_issues_repo_name": "pettni/lie", "max_issues_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2021-07-07T21:13:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T04:40:37.000Z", "max_forks_repo_path": "include/smooth/internal/bundle.hpp", "max_forks_repo_name": "pettni/lie", "max_forks_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-07-09T07:16:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T14:29:44.000Z", "avg_line_length": 32.3192488263, "max_line_length": 92, "alphanum_fraction": 0.6486054619, "num_tokens": 2007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.52527173563456}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <gtest/gtest.h>\n#include <cmath>\n#include <limits>\n\nTEST(MathFunctions, digamma) {\n  EXPECT_FLOAT_EQ(boost::math::digamma(0.5), stan::math::digamma(0.5));\n  EXPECT_FLOAT_EQ(boost::math::digamma(-1.5), stan::math::digamma(-1.5));\n}\n\nTEST(MathFunctions, digamma_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_TRUE(std::isnan(stan::math::digamma(nan)));\n\n  EXPECT_TRUE(std::isnan(stan::math::digamma(-1)));\n\n  EXPECT_TRUE(std::isnormal(stan::math::digamma(1.0E50)));\n}\n", "meta": {"hexsha": "20acf1aba327c39bc09d49c6e384f279a4326482", "size": 589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/digamma_test.cpp", "max_stars_repo_name": "christophernhill/math", "max_stars_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/math/prim/scal/fun/digamma_test.cpp", "max_issues_repo_name": "christophernhill/math", "max_issues_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/prim/scal/fun/digamma_test.cpp", "max_forks_repo_name": "christophernhill/math", "max_forks_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "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.0476190476, "max_line_length": 73, "alphanum_fraction": 0.7113752122, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5252717324556295}}
{"text": "/*\n * $Revision: 558 $ $Date: 2010-11-17 03:20:58 -0800 (Wed, 17 Nov 2010) $\n *\n * Copyright by Astos Solutions GmbH, Germany\n *\n * this file is published under the Astos Solutions Free Public License\n * For details on copyright and terms of use see \n * http://www.astos.de/Astos_Solutions_Free_Public_License.html\n */\n\n#include \"StarCatalog.h\"\n#include \"Spectrum.h\"\n#include \"Debug.h\"\n#include <Eigen/Core>\n#include <cmath>\n#include <algorithm>\n\nusing namespace vesta;\nusing namespace Eigen;\nusing namespace std;\n\n\n/** Create an empty star catalog.\n  */\nStarCatalog::StarCatalog()\n{\n}\n\n\nStarCatalog::~StarCatalog()\n{\n}\n\n\n// Convert a Johnson B-V color index to the effective surface temperature. Uses the\n// relation from Sekiguchi and Fukugita, \"A Study of the B-V Color-Temperature Relation.\"\n// (Astronomical Journal, Aug 2000).\n// http://iopscience.iop.org/1538-3881/120/2/1072/pdf/1538-3881_120_2_1072.pdf\n//\n// bv is the Johnson bv color index\n// metallicity is Fe/H\nstatic float BVColorIndexToTeff(float bv, float metallicity = 0.0f, float logG = 0.0f)\n{\n    const float c0 = 3.939654;\n    const float c1 = -0.395361;\n    const float c2 = 0.2082113;\n    const float c3 = -0.0604097;\n    const float f1 = 0.027153;\n    const float f2 = 0.005036;\n    const float g1 = 0.007367;\n    const float h1 = -0.01069;\n\n    float logT = c0 + c1 * bv + c2 * bv * bv + c3 * bv * bv * bv +\n                 f1 * metallicity + f2 * metallicity * metallicity +\n                 g1 * logG + h1 * bv * logG;\n\n    return pow(10.0f, logT);\n}\n\n\n// Convert the CIE chromaticity coordinates for a black body of the specified\n// temperature. The calculation uses a piecewise cubic approximation that is\n// valid for temperatures above 1667 K. For cooler temperatures, we simply clamp\n// them to 1667 K. This is adequate for our use the function to compute star\n// colors as only brown dwarf stars are cooler, and these are so faint that\n// they don't need to be represented in VESTA.\nstatic Vector2f planckianLocus(float T)\n{\n    // Clamp to a valid range\n    T = std::max(T, 1667.0f);\n\n    float t = 1000.0f / T;\n    float t2 = t * t;\n    float t3 = t2 * t;\n\n    float x;\n    if (T < 4000.0f)\n    {\n        x = -0.266162 * t3 - 0.2343580f * t2 + 0.8776956f * t + 0.179910f;\n    }\n    else\n    {\n        // Valid from 4000K - 25000K\n        x = -3.0258469f * t3 + 2.1070379f * t2 + 0.2226347f * t + 0.24039f;\n    }\n\n    float x2 = x * x;\n    float x3 = x2 * x;\n    float y;\n    if (T < 2222)\n    {\n        // Valid from 1667K - 2222K\n        y = -1.1063814f * x3 - 1.3481102 * x2  + 2.18555832f * x - 0.20219683f;\n    }\n    else if (T < 4000)\n    {\n        // Valid from 2222K - 4000K\n        y = -0.9549976f * x3 - 1.3741859f * x2 + 2.0913702f * x - 0.16748867f;\n    }\n    else\n    {\n        // Valid from 4000K - 25000K\n        y = 3.0817580f * x3 - 5.8338670f * x2 + 3.75112997f * x - 0.37001483f;\n    }\n\n    return Vector2f(x, y);\n}\n\n\nstatic Vector3f xyToXYZ(const Vector2f& xy)\n{\n    return Vector3f(xy.x() / xy.y(), 1.0f, (1.0f - xy.x() - xy.y()) / xy.y());\n}\n\n\nstatic Spectrum linearSrgbStarColor(float bv)\n{\n    float Teff = BVColorIndexToTeff(bv);\n    Vector2f ciexy = planckianLocus(Teff);\n    Vector3f cieXYZ = xyToXYZ(ciexy);\n\n    Spectrum srgb = Spectrum::XYZtoLinearSRGB(Spectrum(cieXYZ.x(), cieXYZ.y(), cieXYZ.z()));\n    srgb.normalize();\n    return srgb;\n}\n\n\n/** Add a new star to the catalog.\n  * @param ra the right ascension (in radians)\n  * @param dec the declination (in radians)\n  * @param vmag the apparent V magnitude in the Johnson photometric system (mean wavelength 540nm)\n  * @param bv the value of B-V color index in the Johnson photometric system\n  */\nvoid\nStarCatalog::addStar(v_uint32 identifier, double ra, double dec, double vmag, double bv)\n{\n    StarRecord star;\n    star.identifier = identifier;\n    star.RA = float(ra);\n    star.declination = float(dec);\n    star.apparentMagnitude = float(vmag);\n    star.bvColorIndex = float(bv);\n\n    m_starData.push_back(star);\n}\n\n\n/** Compute the approximate color of a star from it's Johnson B-V color index. The\n  * color returned is in the CIE XYZ color space.\n  */\nSpectrum StarCatalog::StarColor(float bv)\n{\n    float Teff = BVColorIndexToTeff(bv);\n    Vector2f ciexy = planckianLocus(Teff);\n    Vector3f cieXYZ = xyToXYZ(ciexy);\n\n    return Spectrum(cieXYZ.x(), cieXYZ.y(), cieXYZ.z());\n}\n\n\nclass StarIdPredicate\n{\npublic:\n    StarIdPredicate() {}\n    bool operator()(const StarCatalog::StarRecord& star0, const StarCatalog::StarRecord& star1) const\n    {\n        return star0.identifier < star1.identifier;\n    }\n};\n\n\n/** Index the star catalog by identifier. This method must be called before star lookups by identifier\n  * will work.\n  */\nvoid\nStarCatalog::buildCatalogIndex()\n{\n    sort(m_starData.begin(), m_starData.end(), StarIdPredicate());\n}\n\n\n/** Lookup a star by its identifier. Returns null if the star isn't present in the\n  * catalog. buildCatalogIndex() must be called once before findStarIdentifier will\n  * work.\n  */\nconst StarCatalog::StarRecord*\nStarCatalog::findStarIdentifier(v_uint32 id)\n{\n    StarRecord match;\n    match.identifier = id;\n\n    vector<StarRecord>::const_iterator pos = lower_bound(m_starData.begin(), m_starData.end(), match, StarIdPredicate());\n    if (pos == m_starData.end())\n    {\n        return NULL;\n    }\n    else\n    {\n        return &(*pos);\n    }\n}\n", "meta": {"hexsha": "62af498be8f1e8b2d8aa2f3812b7c7a3254678ba", "size": 5363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/vesta/StarCatalog.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "thirdparty/vesta/StarCatalog.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "thirdparty/vesta/StarCatalog.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 26.5495049505, "max_line_length": 121, "alphanum_fraction": 0.653925042, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5252530850199982}}
{"text": "/*\n * test_MACD.cpp\n *\n *  Created on: 2013-4-11\n *      Author: fasiondog\n */\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/MACD.h>\n#include <hikyuu/indicator/crt/PRICELIST.h>\n#include <hikyuu/indicator/crt/EMA.h>\n\nusing namespace hku;\n\n/**\n * @defgroup test_indicator_MACD test_indicator_MACD\n * @ingroup test_hikyuu_indicator_suite\n * @{\n */\n\n/** @par \u68c0\u6d4b\u70b9 */\nBOOST_AUTO_TEST_CASE( test_MACD ) {\n    PriceList d;\n    for (size_t i = 0; i < 20; ++i) {\n        d.push_back(i);\n    }\n\n    Indicator ind = PRICELIST(d);\n    Indicator macd, bar, diff, dea;\n    Indicator ema1, ema2, fast, slow, bmacd;\n\n    /** @arg \u6e90\u6570\u636e\u4e3a\u7a7a */\n    macd = MACD(Indicator(), 12, 26, 9);\n    BOOST_CHECK(macd.size() == 0);\n    BOOST_CHECK(macd.empty() == true);\n\n    /** @arg n1 = n2 = n3 = 1*/\n    macd = MACD(ind, 1, 1, 1);\n    BOOST_CHECK(macd.getResultNumber() == 3);\n    bar = macd.getResult(0);\n    diff = macd.getResult(1);\n    dea = macd.getResult(2);\n    BOOST_CHECK(bar.size() == 20);\n    BOOST_CHECK(diff.size() == 20);\n    BOOST_CHECK(dea.size() == 20);\n\n    BOOST_CHECK(diff[0] == 0);\n    BOOST_CHECK(diff[1] == 0);\n    BOOST_CHECK(diff[19] == 0);\n\n    BOOST_CHECK(dea[0] == 0);\n    BOOST_CHECK(dea[1] == 0);\n    BOOST_CHECK(dea[19] == 0);\n\n    BOOST_CHECK(bar[0] == 0);\n    BOOST_CHECK(bar[1] == 0);\n    BOOST_CHECK(bar[19] == 0);\n\n    /** @arg n1 = 1 n2 = 2 n3 = 3*/\n    macd = MACD(ind, 1, 2, 3);\n    BOOST_CHECK(macd.size() == 20);\n    BOOST_CHECK(macd.discard() == 0);\n    bar = macd.getResult(0);\n    diff = macd.getResult(1);\n    dea = macd.getResult(2);\n    ema1 = EMA(ind, 1);\n    ema2 = EMA(ind, 2);\n    fast = ema1 - ema2;\n    slow = EMA(fast, 3);\n    bmacd = fast - slow;\n    BOOST_CHECK(bar.size() == 20);\n    BOOST_CHECK(diff.size() == 20);\n    BOOST_CHECK(dea.size() == 20);\n\n    BOOST_CHECK(diff[0] == fast[0]);\n    BOOST_CHECK(diff[1] == fast[1]);\n    BOOST_CHECK(diff[19] == fast[19]);\n\n    BOOST_CHECK(dea[0] == slow[0]);\n    BOOST_CHECK(std::fabs(dea[1] - slow[1]) < 0.0001);\n    BOOST_CHECK(dea[19] == slow[19]);\n\n    BOOST_CHECK(bar[0] == bmacd[0]);\n    BOOST_CHECK(bar[1] == bmacd[1]);\n    BOOST_CHECK(bar[19] == bmacd[19]);\n\n    /** @arg n1 = 3 n2 = 2 n3 = 1*/\n    macd = MACD(ind, 3, 2, 1);\n    BOOST_CHECK(macd.size() == 20);\n    BOOST_CHECK(macd.discard() == 0);\n    bar = macd.getResult(0);\n    diff = macd.getResult(1);\n    dea = macd.getResult(2);\n    ema1 = EMA(ind, 3);\n    ema2 = EMA(ind, 2);\n    fast = ema1 - ema2;\n    slow = EMA(fast, 1);\n    bmacd = fast - slow;\n    BOOST_CHECK(bar.size() == 20);\n    BOOST_CHECK(diff.size() == 20);\n    BOOST_CHECK(dea.size() == 20);\n\n    BOOST_CHECK(diff[0] == fast[0]);\n    BOOST_CHECK(diff[1] == fast[1]);\n    BOOST_CHECK(diff[19] == fast[19]);\n\n    BOOST_CHECK(dea[0] == slow[0]);\n    BOOST_CHECK(dea[1] == slow[1]);\n    BOOST_CHECK(dea[19] == slow[19]);\n\n    BOOST_CHECK(bar[0] == bmacd[0]);\n    BOOST_CHECK(bar[1] == bmacd[1]);\n    BOOST_CHECK(bar[19] == bmacd[19]);\n\n    /** @arg n1 = 3 n2 = 5 n3 = 2*/\n    macd = MACD(ind, 3, 5, 2);\n    BOOST_CHECK(macd.size() == 20);\n    BOOST_CHECK(macd.discard() == 0);\n    bar = macd.getResult(0);\n    diff = macd.getResult(1);\n    dea = macd.getResult(2);\n    ema1 = EMA(ind, 3);\n    ema2 = EMA(ind, 5);\n    fast = ema1 - ema2;\n    slow = EMA(fast, 2);\n    bmacd = fast - slow;\n    BOOST_CHECK(bar.size() == 20);\n    BOOST_CHECK(diff.size() == 20);\n    BOOST_CHECK(dea.size() == 20);\n\n    BOOST_CHECK(diff[0] == fast[0]);\n    BOOST_CHECK(diff[1] == fast[1]);\n    BOOST_CHECK(diff[19] == fast[19]);\n\n    BOOST_CHECK(dea[0] == slow[0]);\n    BOOST_CHECK(dea[1] == slow[1]);\n    BOOST_CHECK(dea[19] == slow[19]);\n\n    BOOST_CHECK(bar[0] == bmacd[0]);\n    BOOST_CHECK(bar[1] == bmacd[1]);\n    BOOST_CHECK(bar[19] == bmacd[19]);\n\n    /** @arg operator() */\n    Indicator expect = MACD(ind, 3, 5, 2);\n    Indicator tmp = MACD(3, 5, 2);\n    Indicator result = tmp(ind);\n    BOOST_CHECK(result.size() == expect.size());\n    for (size_t i = 0; i < expect.size(); ++i) {\n        BOOST_CHECK(result.get(i, 0) == expect.get(i, 0));\n        BOOST_CHECK(result.get(i, 1) == expect.get(i, 1));\n        BOOST_CHECK(result.get(i, 2) == expect.get(i, 2));\n    }\n}\n\n/** @} */\n\n\n", "meta": {"hexsha": "698b685f24938dc2314663996203c39b32873c4b", "size": 4327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_MACD.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_MACD.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_MACD.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.2242424242, "max_line_length": 58, "alphanum_fraction": 0.5662121562, "num_tokens": 1517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893340314393, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5252530709498506}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/eigen.h>\n#include <Eigen/Dense>\n\n#include \"geometrycentral/surface/halfedge_mesh.h\"\n#include \"geometrycentral/surface/halfedge_factories.h\"\n#include \"geometrycentral/surface/meshio.h\"\n#include \"geometrycentral/surface/heat_method_distance.h\"\n#include \"geometrycentral/surface/fast_marching_method.h\"\n#include \"geometrycentral/surface/vertex_position_geometry.h\"\n#include \"exact_geodesic.h\"\n\nusing namespace std;\nusing namespace geometrycentral;\nusing namespace geometrycentral::surface;\nnamespace py = pybind11;\n\n// Geometry-central data\nstd::unique_ptr<HalfedgeMesh> mesh;\nstd::unique_ptr<VertexPositionGeometry> geometry;\n\n\n// Loads a mesh from a NumPy array\n// source: https://github.com/rubenwiersma/hsn/blob/master/vectorheat/src/main.cpp\nstd::tuple<std::unique_ptr<HalfedgeMesh>, std::unique_ptr<VertexPositionGeometry>>\nloadMesh_np(Eigen::MatrixXd& pos, Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& faces) {\n\n  // Set vertex positions\n  std::vector<Vector3> vertexPositions(pos.rows());\n  for (size_t i = 0; i < pos.rows(); i++) {\n    vertexPositions[i][0] = pos(i, 0);\n    vertexPositions[i][1] = pos(i, 1);\n    vertexPositions[i][2] = pos(i, 2);\n  }\n\n  // Get face list\n  std::vector<std::vector<size_t>> faceIndices(faces.rows());\n  for (size_t i = 0; i < faces.rows(); i++) {\n    faceIndices[i] = {faces(i, 0), faces(i, 1), faces(i, 2)};\n  }\n\n  return makeHalfedgeAndGeometry(faceIndices, vertexPositions);\n}\n\n// compute geodesic distance using the heat method\nEigen::MatrixXd get_heat_geodesics(Eigen::MatrixXd& pos, Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& faces){\n    // Load mesh\n    std::tie(mesh, geometry) = loadMesh_np(pos, faces);\n    int nverts = mesh->nVertices();\n\n    // Create the Heat Method solver\n    HeatMethodDistanceSolver heatSolver(*geometry);\n\n    // create output matrix\n    Eigen::MatrixXd geodesic_matrix(nverts, nverts);\n\n    // compute geodesic distances\n    int i = 0;\n    for (Vertex v : mesh->vertices()) {\n        VertexData<double> distToSource = heatSolver.computeDistance(v);\n        for (int j = 0; j < nverts; j++){\n            geodesic_matrix(i, j) = distToSource[j];\n        }\n        i++;\n    }\n\n    return geodesic_matrix;\n}\n\n\n// compute geodesic distance using the fast marching method\nEigen::MatrixXd get_fmm_geodesics(Eigen::MatrixXd& pos, Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& faces){\n    // Load mesh\n    std::tie(mesh, geometry) = loadMesh_np(pos, faces);\n    int nverts = mesh->nVertices();\n\n    // create output matrix\n    Eigen::MatrixXd geodesic_matrix(nverts, nverts);\n    double initial_dist = 0.;\n\n    // compute geodesic distances\n    int i = 0;\n    for (Vertex v : mesh->vertices()) {\n        std::vector<std::pair<Vertex, double>> input{std::make_pair(v, initial_dist)};\n        VertexData<double> distToSource = FMMDistance(*geometry, input);\n        for (int j = 0; j < nverts; j++)\n            geodesic_matrix(i, j) = distToSource[j];\n\n        i++;\n    }\n\n    return geodesic_matrix;\n}\n\n// compute geodesic distance using the Exact geodesic algorithm by Mitchell, Mount and Papadimitriou in 1987\nEigen::MatrixXd get_exact_geodesics(Eigen::MatrixXd& pos, Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& faces){\n    // utils vars\n    int nverts = pos.rows();\n    Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic> FS, FT;\n    Eigen::MatrixXi target(nverts, 1);\n    for (int i = 0; i < nverts; i++)\n        target(i, 0) = i;\n\n    // create output matrix\n    Eigen::MatrixXd geodesic_matrix(nverts, nverts);\n\n    // compute geodesic distances\n    for (int i = 0; i < nverts; i++){\n        Eigen::MatrixXi source(1, 1);\n        source(0, 0) = i;\n        Eigen::MatrixXd distToSource(nverts, 1);\n        igl::exact_geodesic(pos, faces, source, FS, target, FT, distToSource);\n\n        for (int j = 0; j < nverts; j++)\n            geodesic_matrix(i, j) = distToSource(j);\n    }\n\n    return geodesic_matrix;\n}\n\n\nPYBIND11_MODULE(tridesic, m) {\n    m.def(\"get_heat_geodesics\", &get_heat_geodesics, py::return_value_policy::copy,\n          \"Compute the geodesic matrix using the heat method\");\n    m.def(\"get_fmm_geodesics\", &get_fmm_geodesics, py::return_value_policy::copy,\n          \"Compute the geodesic matrix using the fast marching method\");\n    m.def(\"get_exact_geodesics\", &get_exact_geodesics, py::return_value_policy::copy,\n          \"Compute the geodesic matrix using the Exact geodesic algorithm by Mitchell et al.\");\n}\n", "meta": {"hexsha": "7efebf0d6657ad30a087cf513c9126e7d5b98687", "size": 4519, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "pvnieo/tridesic", "max_stars_repo_head_hexsha": "1988893068a61c25c5e96f383c0d572fbd31415c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-04T22:32:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T22:32:01.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "pvnieo/tridesic", "max_issues_repo_head_hexsha": "1988893068a61c25c5e96f383c0d572fbd31415c", "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": "pvnieo/tridesic", "max_forks_repo_head_hexsha": "1988893068a61c25c5e96f383c0d572fbd31415c", "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.4961832061, "max_line_length": 120, "alphanum_fraction": 0.6840008852, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5252530625051033}}
{"text": "#include <SBGATPolyhedronGravityModel.hpp>\n#include <SBGATPolyhedronGravityModelUQ.hpp>\n\n#include <vtkCleanPolyData.h>\n#include <vtkOBJReader.h>\n\n#include <json.hpp>\n#include <boost/progress.hpp>\n\n\nint main(){\n\n\tstd::ifstream i(\"input_file.json\");\n\tnlohmann::json input_data;\n\ti >> input_data;\n\n\tstd::string PATH_SHAPE = input_data[\"PATH_SHAPE\"];\n\tdouble CORRELATION_DISTANCE =  input_data[\"CORRELATION_DISTANCE\"];\n\n\tdouble ERROR_STANDARD_DEV  = input_data[\"ERROR_STANDARD_DEV\"];\n\tdouble DENSITY  = input_data[\"DENSITY\"];\n\tdouble STEP_SIZE  = input_data[\"STEP_SIZE\"];\n\n\tbool UNIT_IN_METERS  = input_data[\"UNIT_IN_METERS\"];\n\tbool HOLD_MASS_CONSTANT  = input_data[\"HOLD_MASS_CONSTANT\"];\n\n\n\tint PROJECTION_AXIS = input_data[\"PROJECTION_AXIS\"];\n\tint N_MONTE_CARLO = input_data[\"N_MONTE_CARLO\"];\n\n\tstd::string OUTPUT_DIR = input_data[\"OUTPUT_DIR\"];\n\n\tstd::cout << \"- Path to shape: \" << PATH_SHAPE << std::endl;\n\tstd::cout << \"- Standard deviation on point coordinates (m) : \" << ERROR_STANDARD_DEV << std::endl;\n\tstd::cout << \"- Correlation distance (m) : \" << CORRELATION_DISTANCE << std::endl;\n\tstd::cout << \"- Density (kg/m^3) : \" << DENSITY << std::endl;\n\tstd::cout << \"- Monte-Carlo draws : \" << N_MONTE_CARLO << std::endl;\n\tstd::cout << \"- Step size : \" << STEP_SIZE << std::endl;\n\tstd::cout << \"- Projection axis : \" << PROJECTION_AXIS << std::endl;\n\n\n\t// Reading\n\tvtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New();\n\treader -> SetFileName(PATH_SHAPE.c_str());\n\treader -> Update(); \n\n\t// An instance of SBGATPolyhedronGravityModel is created to evaluate the PGM of \n\t// the considered polytdata\n\tvtkSmartPointer<SBGATPolyhedronGravityModel> pgm_filter = vtkSmartPointer<SBGATPolyhedronGravityModel>::New();\n\tpgm_filter -> SetInputConnection(reader -> GetOutputPort());\n\tpgm_filter -> SetDensity(DENSITY);\n\n\t\n\tif(UNIT_IN_METERS){\n\t\tpgm_filter -> SetScaleMeters();\n\t} else{\n\t\tpgm_filter -> SetScaleKiloMeters();\n\t}\n\tpgm_filter -> Update();\n\n\t// An instance of SBGATPolyhedronGravityModelUQ is created to perform\n\t// uncertainty quantification from the PGM associated to the shape\n\tSBGATPolyhedronGravityModelUQ pgm_uq;\n\tpgm_uq.SetModel(pgm_filter);\n\tpgm_uq.PrecomputeMassPropertiesPartials();\n\t\n\t// Populate the shape vertices covariance\n\tpgm_uq.ComputeVerticesCovarianceGlobal(ERROR_STANDARD_DEV,CORRELATION_DISTANCE);\n\t// Regularizing the covariance\n\tint regularized_eigen_values = pgm_uq.RegularizeCovariance();\n\n\tstd::cout << regularized_eigen_values << \" eigenvalues were regularized\\n\";\n\t\n\tarma::mat C_CC = pgm_uq.GetCovarianceSquareRoot();\n\tarma::mat P_CC = pgm_uq.GetVerticesCovariance();\n\tstd::cout << \"Maximum absolute error in covariance square root: \" << arma::abs(P_CC - C_CC * C_CC.t()).max() << std::endl;\n\t\n\tstd::cout << \"Saving shape covariance ...\\n\";\n\tP_CC.save(OUTPUT_DIR + \"full_covariance.txt\",arma::raw_ascii);\n\n\t// Saving baseline slices\n\tpgm_uq.TakeAndSaveSlice(0,OUTPUT_DIR + \"baseline_slice_x.txt\",1e-6);\n\tpgm_uq.TakeAndSaveSlice(1,OUTPUT_DIR + \"baseline_slice_y.txt\",1e-6);\n\tpgm_uq.TakeAndSaveSlice(2,OUTPUT_DIR + \"baseline_slice_z.txt\",1e-6);\n\n\t// First, create the grid from the bounding box\n\tstd::vector<arma::vec::fixed<3> > grid;\n\tdouble xmin,xmax,ymin,ymax,zmin,zmax;\n\tpgm_filter -> GetBoundingBox(xmin,xmax,ymin,ymax,zmin,zmax);\n\t\n\t// Inflate\n\txmin *= 2.5;\n\txmax *= 2.5;\n\tymin *= 2.5;\n\tymax *= 2.5;\n\tzmin *= 2.5;\n\tzmax *= 2.5;\n\n\tdouble min_dim = std::min(xmin,std::min(ymin,zmin));\n\tdouble max_dim = std::max(xmax,std::max(ymax,zmax));\n\n\txmax = max_dim;\n\tymax = max_dim;\n\tzmax = max_dim;\n\n\txmin = min_dim;\n\tymin = min_dim;\n\tzmin = min_dim;\n\n\t// Define grid indices\n\tint i_max,j_max;\n\n\tif (PROJECTION_AXIS == 0){\n\t\ti_max = 1./STEP_SIZE * (ymax - ymin);\n\t\tj_max = 1./STEP_SIZE * (zmax - zmin);\n\n\t}\n\telse if (PROJECTION_AXIS == 1){\n\n\t\ti_max = 1./STEP_SIZE * (xmax - xmin);\n\t\tj_max = 1./STEP_SIZE * (zmax - zmin);\n\n\t}\n\telse if (PROJECTION_AXIS == 2){\n\n\t\ti_max = 1./STEP_SIZE * (xmax - xmin);\n\t\tj_max = 1./STEP_SIZE * (ymax - ymin);\n\n\t}\n\telse{\n\t\tthrow(std::runtime_error(\"PROJECTION_AXIS has to be either 0, 1 or 2. It can't be equal to \" + std::to_string(PROJECTION_AXIS)));\n\t}\n\n\t// Create the grid containers\n\tstd::vector<std::vector<int> > indices;\n\tarma::mat trace_sqrt_cov(i_max,j_max);\n\tarma::mat reference_acceleration(i_max,j_max);\n\tarma::mat uncertainty_over_reference_acc_percentage(i_max,j_max);\n\tarma::mat inside_outside(i_max,j_max);\n\t\n\n\n\t// Construct the grid (constant, uniform step size in both directions of space)\n\tfor (int i = 0; i < i_max; ++i){\n\t\tfor (int j = 0; j < j_max; ++j){\n\n\t\t\tarma::vec::fixed<3> point;\n\t\t\tif (PROJECTION_AXIS == 0){\n\n\t\t\t\tdouble y = ymin + i * STEP_SIZE;\n\t\t\t\tdouble z = zmin + j * STEP_SIZE;\n\n\n\t\t\t\tpoint(0) = 0;\n\t\t\t\tpoint(1) = y;\n\t\t\t\tpoint(2) = z;\n\t\t\t}\n\t\t\telse if (PROJECTION_AXIS == 1){\n\n\t\t\t\tdouble x = xmin + i * STEP_SIZE;\n\t\t\t\tdouble z = zmin + j * STEP_SIZE;\n\n\t\t\t\tpoint(0) = x;\n\t\t\t\tpoint(1) = 0;\n\t\t\t\tpoint(2) = z;\n\t\t\t}\n\t\t\telse{\n\n\t\t\t\tdouble x = xmin + i * STEP_SIZE;\n\t\t\t\tdouble y = ymin + j * STEP_SIZE;\n\n\t\t\t\tpoint(0) = x;\n\t\t\t\tpoint(1) = y;\n\t\t\t\tpoint(2) = 0;\n\t\t\t}\n\t\t\t\n\t\t\tgrid.push_back(point);\n\t\t\tindices.push_back(std::vector<int>({i,j}));\n\n\t\t\tif (pgm_filter -> Contains(point)){\n\t\t\t\tinside_outside(i,j) = 1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tinside_outside(i,j) = 0;\n\t\t\t}\n\t\t}\n\t}\n\tstd::cout << \"- Grid size: \" << grid.size() << std::endl;\n\t\n\t// Saving the grid to a file\n\tarma::mat grid_arma(3,grid.size());\n\tfor (unsigned int p = 0; p < grid.size(); ++p){\n\t\tgrid_arma.col(p) = grid[p];\n\t}\n\tgrid_arma.save(OUTPUT_DIR + \"grid.txt\",arma::raw_ascii);\n\n\t// Running a Monte Carlo on a subset of the grid\n\tstd::vector<std::vector<arma::vec::fixed<3> > > all_accelerations;\n\tstd::vector<std::vector<double > > all_potentials;\n\tstd::vector<arma::vec> deviations;\n\tstd::vector<double> densities;\n\n\n\tarma::vec::fixed<3> e0 = {1,0,0};\n\tarma::vec::fixed<3> e1 = {0,1,0};\n\tarma::vec::fixed<3> e2 = {0,0,1};\n\tarma::vec::fixed<3> e3 = arma::normalise(arma::vec({1,1,0}));\n\tarma::vec::fixed<3> e4 = arma::normalise(arma::vec({0,1,1}));\n\tarma::vec::fixed<3> e5 = arma::normalise(arma::vec({1,0,1}));\n\tarma::vec::fixed<3> e6 = arma::normalise(arma::vec({-1,1,0}));\n\tarma::vec::fixed<3> e7 = arma::normalise(arma::vec({0,-1,1}));\n\tarma::vec::fixed<3> e8 = arma::normalise(arma::vec({1,0,-1}));\n\n\n\tstd::vector<arma::vec::fixed<3> > all_positions;\n\tstd::vector<double> distances = {200,300,400,500,600};\n\tfor (auto dist : distances){\n\t\tall_positions.push_back(dist * e0);\n\t\tall_positions.push_back(dist * e1);\n\t\tall_positions.push_back(dist * e2);\n\t\tall_positions.push_back(dist * e3);\n\t\tall_positions.push_back(dist * e4);\n\t\tall_positions.push_back(dist * e5);\n\t\tall_positions.push_back(dist * e6);\n\t\tall_positions.push_back(dist * e7);\n\t\tall_positions.push_back(dist * e8);\n\t\tall_positions.push_back(- dist * e0);\n\t\tall_positions.push_back(- dist * e1);\n\t\tall_positions.push_back(- dist * e2);\n\t\tall_positions.push_back(- dist * e3);\n\t\tall_positions.push_back(- dist * e4);\n\t\tall_positions.push_back(- dist * e5);\n\t\tall_positions.push_back(- dist * e6);\n\t\tall_positions.push_back(- dist * e7);\n\t\tall_positions.push_back(- dist * e8);\n\t}\n\n\n\n\tstd::cout << \"Running MC ... \";\n\n\tauto start = std::chrono::system_clock::now();\n\tSBGATPolyhedronGravityModelUQ::RunMCUQAccelerationInertial(PATH_SHAPE,DENSITY,\n\t\tUNIT_IN_METERS,\n\t\tHOLD_MASS_CONSTANT,\n\t\tC_CC,\n\t\tN_MONTE_CARLO, \n\t\tall_positions,\n\t\tOUTPUT_DIR,\n\t\tstd::min(30,N_MONTE_CARLO),\n\t\tdeviations,\n\t\tdensities,\n\t\tall_accelerations);\n\tauto end = std::chrono::system_clock::now();\n\n\tstd::chrono::duration<double> elapsed_seconds = end-start;\n\n\tstd::cout << \"Done running MC in \" << elapsed_seconds.count() << \" s\\n\";\n\n// Computing MC Dispersions\n\tarma::vec KL_divergence_analytical_vs_mc(all_positions.size());\n\tarma::vec abs_value_cov_difference_analytical_vs_mc(all_positions.size());\n\tarma::vec rel_value_cov_difference_analytical_vs_mc(all_positions.size());\n\tarma::mat all_positions_arma(3,all_positions.size());\n\n#pragma omp parallel for\n\tfor (int e = 0; e < all_positions.size(); ++e){\n\n\t\tarma::mat accelerations_mc(3,N_MONTE_CARLO);\n\n\t\tfor (int sample = 0; sample < N_MONTE_CARLO; ++sample){\n\t\t\taccelerations_mc.col(sample) = all_accelerations[sample][e];\n\t\t}\n\n\t\tarma::mat mc_covariances_acc = arma::cov(accelerations_mc.t());\n\n\t\tarma::vec mc_mean_acc = arma::mean(accelerations_mc,1);\n\t\tarma::vec reference_acc = pgm_filter -> GetAcceleration(all_positions[e]);\n\n\t\tarma::mat cov_analytical = pgm_uq.GetCovarianceAcceleration(all_positions[e],HOLD_MASS_CONSTANT);\n\t\tKL_divergence_analytical_vs_mc(e) = SBGATFilterUQ::KLDivergence(reference_acc,mc_mean_acc,\tcov_analytical,mc_covariances_acc);\n\n\t\tabs_value_cov_difference_analytical_vs_mc(e) = arma::abs(arma::vectorise(cov_analytical - mc_covariances_acc)).max();\n\t\trel_value_cov_difference_analytical_vs_mc(e) = arma::norm(cov_analytical - mc_covariances_acc)/arma::trace(mc_covariances_acc) * 100;\n\t\tall_positions_arma.col(e) = all_positions[e];\n\t}\n\n\t\n\n\n\tstd::cout << \"- Evaluating analytical uncertainties over grid ...\\n\";\n\n\tstart = std::chrono::system_clock::now();\n\n\n\t\n\t// For every point in the grid, evaluate the analytical acceleration covariance and \n\t// run a monte carlo to get a statistical covariance to compare against\n\tboost::progress_display progress(grid.size());\n\n\t#pragma omp parallel for\n\tfor (int p = 0; p < grid.size(); ++p){\n\n\t\tint i = indices[p][0];\n\t\tint j = indices[p][1];\n\n\t\tconst arma::vec::fixed<3> & grid_point = grid[p];\n\n\t\tarma::vec::fixed<3> reference_acceleration_vector = pgm_filter -> GetAcceleration(grid_point);\n\t\tarma::mat::fixed<3,3> covariance_acceleration_analytical = pgm_uq.GetCovarianceAcceleration(grid_point,HOLD_MASS_CONSTANT);\n\t\t\n\t\treference_acceleration(i,j) = arma::norm(reference_acceleration_vector);\n\t\ttrace_sqrt_cov(i,j) = std::sqrt(arma::trace(covariance_acceleration_analytical)) ;\n\t\tuncertainty_over_reference_acc_percentage(i,j) = trace_sqrt_cov(i,j) / reference_acceleration(i,j) * 100;\n\n\t\t++progress;\n\t}\n\n\n\tend = std::chrono::system_clock::now();\n\telapsed_seconds = end-start;\n\tstd::cout << \"\\n-- Done evaluating over grid in \" << elapsed_seconds.count() << \" s\\n\";\n\n\n\ttrace_sqrt_cov.save(OUTPUT_DIR + \"trace_sqrt_cov.txt\",arma::raw_ascii);\n\treference_acceleration.save(OUTPUT_DIR + \"reference_acceleration.txt\",arma::raw_ascii);\n\tinside_outside.save(OUTPUT_DIR + \"inside_outside.txt\",arma::raw_ascii);\n\tuncertainty_over_reference_acc_percentage.save(OUTPUT_DIR + \"uncertainty_over_reference_acc_percentage.txt\",arma::raw_ascii);\n\n\tabs_value_cov_difference_analytical_vs_mc.save(OUTPUT_DIR + \"abs_value_cov_difference_analytical_vs_mc.txt\",arma::raw_ascii);\n\trel_value_cov_difference_analytical_vs_mc.save(OUTPUT_DIR + \"rel_value_cov_difference_analytical_vs_mc.txt\",arma::raw_ascii);\n\tKL_divergence_analytical_vs_mc.save(OUTPUT_DIR + \"KL_divergence_analytical_vs_mc.txt\",arma::raw_ascii);\n\tall_positions_arma.save(OUTPUT_DIR + \"all_positions_arma.txt\",arma::raw_ascii);\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "b9b800b14fea30ba10cd5dddb161b3ff2144b9f1", "size": 10919, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/PGMUncertainty/main.cpp", "max_stars_repo_name": "bbercovici/SBGAT", "max_stars_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T02:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T05:25:44.000Z", "max_issues_repo_path": "Examples/PGMUncertainty/main.cpp", "max_issues_repo_name": "bbercovici/SBGAT", "max_issues_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2017-02-09T15:38:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-25T20:53:37.000Z", "max_forks_repo_path": "Examples/PGMUncertainty/main.cpp", "max_forks_repo_name": "bbercovici/SBGAT", "max_forks_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T12:20:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T12:20:25.000Z", "avg_line_length": 32.3047337278, "max_line_length": 135, "alphanum_fraction": 0.7087645389, "num_tokens": 3229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5252530568664098}}
{"text": "#include <iostream>\n#include <list>\n#include <vector>\n#include <algorithm>\n#include <set>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/multi_point.hpp>\n#include <boost/geometry/geometries/multi_polygon.hpp>\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/geometry/algorithms/area.hpp>\n#include <boost/geometry/algorithms/assign.hpp>\n\n#include <boost/foreach.hpp>\n\n#include <stdlib.h>\n#include <bits/stdc++.h>\n\n\nnamespace bg = boost::geometry;\n\n// use the following two commands to compile:\n//\n//WARNING: DO NOT USE O2. IT DESTROYS bg::correct FUNCTIONALITY\n// g++ -lboost_system -c -fPIC polygoncalc.cpp -o polygoncalc.o -O2\n// g++ -lboost_system -shared -Wl,-soname,libpolygoncalc.so -o libpolygoncalc.so polygoncalc.o -O2\n// if it does not work, add -std=c++14 and add -I and -L directories\n\ntypedef boost::geometry::model::d2::point_xy<double> point_type;\n\ntypedef bg::model::polygon<point_type> polygon_type;\n\n\nvoid dump( const std::string & label, const std::list< std::set< unsigned long > > & values )\n{\n    std::cout << label << std::endl;\n    for( auto iter : values )\n    {\n        std::cout << \"{ \";\n        for( auto val : iter )\n            std::cout << val << \", \";\n        std::cout << \"}, \";\n    }\n    std::cout << std::endl;\n}\n\n\nvoid combine( std::list< std::set< unsigned long > > & values )\n{\n    for( std::list< std::set< unsigned long > >::iterator iter = values.begin(); iter != values.end(); ++iter )\n        for( std::list< std::set< unsigned long > >::iterator niter( iter ); ++niter != values.end(); )\n            if( std::find_first_of( iter->begin(), iter->end(), niter->begin(), niter->end() ) != iter->end() )\n            {\n                iter->insert( niter->begin(), niter->end() );\n                values.erase( niter );\n                niter = iter;\n            }\n}\n\nunsigned long merge(unsigned long* parent, unsigned long x)\n{\n    if (parent[x] == x)\n        return x;\n    return merge(parent, parent[x]);\n}\n\nvoid connectedcomponents(unsigned long n, std::vector<std::vector<unsigned long> >& edges, std::list<std::list<unsigned long>>& res)\n{\n        \n    unsigned long parent[n];\n    for (unsigned long i = 0; i < n; i++) {\n        parent[i] = i;\n    }\n    for (auto x : edges) {\n        parent[merge(parent, x[0])] = merge(parent, x[1]);\n    }\n\n    for (unsigned long i = 0; i < n; i++) {\n        parent[i] = merge(parent, parent[i]);\n    }\n    std::map<unsigned long, std::list<unsigned long> > m;\n    for (unsigned long i = 0; i < n; i++) {\n        m[parent[i]].push_back(i);\n    }\n    for (auto it = m.begin(); it != m.end(); it++) {\n        std::list<unsigned long> l = it->second;\n        \n        res.push_back(l);\n    }\n}\n\nclass PolygonCalc{\n\n    public:\n        const double helloworld(){\n            return 0.123;\n        }\n\n        double test_calc(){\n\n            polygon_type poly1 {{{0.0, 0.0}, {1.0, 0.0}, {1.0, 1.0}, {0.0, 1.0}}};\n            polygon_type poly2 {{{5.5, 0.5}, {6.5, 0.5}, {6.5, 1.5}, {5.5, 1.5}}};\n\n            bg::correct(poly1);\n            bg::correct(poly2);\n\n            std::deque<polygon_type> output;\n            bg::intersection(poly1, poly2, output);\n\n            double totalArea = 0.0;\n\n            BOOST_FOREACH(polygon_type const& p, output)\n            {\n\n                totalArea += bg::area(p);\n            }\n\n            double d = bg::distance(poly1, poly2);\n\n            std::cout << d << std::endl;\n\n            return totalArea;\n\n        }\n\n        int test_nparray(double *A, int n){\n\n            int i;\n            double sum = 0.0;\n\n            for (i=0; i<n; i++) {\n\n                sum += A[i];\n\n            }\n\n            std::cout << \"n: \" << n << std::endl;\n\n            std::cout << sum / n << std::endl;\n\n            return n;\n\n        }\n\n        double min_poly_distance(double *poly1x, double *poly1y, double *poly2x, double *poly2y, int m, int n){\n\n            int i;\n\n            std::vector<point_type> points1;\n            std::vector<point_type> points2;\n\n            for (i=0; i<m; i++) {\n                points1.push_back(point_type(poly1x[i], poly1y[i]));\n            }\n\n            for (i=0; i<n; i++) {\n                points2.push_back(point_type(poly2x[i], poly2y[i]));\n            }\n\n            polygon_type poly1;\n            polygon_type poly2;\n\n            bg::assign_points(poly1, points1);\n            bg::assign_points(poly2, points2);\n\n            bg::correct(poly1);\n            bg::correct(poly2);\n\n            std::deque<polygon_type> output;\n            bg::intersection(poly1, poly2, output);\n\n            double totalArea = 0.0;\n\n            BOOST_FOREACH(polygon_type const& p, output)\n            {\n                totalArea += bg::area(p);\n            }\n\n            if (totalArea > 0.0){\n                return 0.0;\n            }\n\n            return bg::distance(poly1, poly2);\n\n        }\n        \n        double poly_area(double *poly1x, double *poly1y, int m){\n\n            int i;\n\n            std::vector<point_type> points1;\n\n            for (i=0; i<m; i++) {\n                points1.push_back(point_type(poly1x[i], poly1y[i]));\n            }\n\n            polygon_type poly1;\n\n            bg::assign_points(poly1, points1);\n\n            bg::correct(poly1);\n\n            double totalArea = bg::area(poly1);\n\n            return totalArea;\n\n        }\n\n        double poly_intersection_area(double *poly1x, double *poly1y, double *poly2x, double *poly2y, int m, int n){\n\n            int i;\n\n            std::vector<point_type> points1;\n            std::vector<point_type> points2;\n\n            for (i=0; i<m; i++) {\n                points1.push_back(point_type(poly1x[i], poly1y[i]));\n            }\n\n            for (i=0; i<n; i++) {\n                points2.push_back(point_type(poly2x[i], poly2y[i]));\n            }\n\n            polygon_type poly1;\n            polygon_type poly2;\n\n            bg::assign_points(poly1, points1);\n            bg::assign_points(poly2, points2);\n\n            bg::correct(poly1);\n            bg::correct(poly2);\n\n            std::deque<polygon_type> output;\n            bg::intersection(poly1, poly2, output);\n\n            double totalArea = 0.0;\n\n            BOOST_FOREACH(polygon_type const& p, output)\n            {\n                totalArea += bg::area(p);\n            }\n\n            return totalArea;\n\n        }\n\n        double poly_intersection_area_ratio(double *poly1x, double *poly1y, double *poly2x, double *poly2y, int m, int n){\n\n            int i;\n\n            std::vector<point_type> points1;\n            std::vector<point_type> points2;\n\n            for (i=0; i<m; i++) {\n                points1.push_back(point_type(poly1x[i], poly1y[i]));\n            }\n\n            for (i=0; i<n; i++) {\n                points2.push_back(point_type(poly2x[i], poly2y[i]));\n            }\n\n            polygon_type poly1;\n            polygon_type poly2;\n\n            bg::assign_points(poly1, points1);\n            bg::assign_points(poly2, points2);\n\n            bg::correct(poly1);\n            bg::correct(poly2);\n\n            std::deque<polygon_type> output;\n            bg::intersection(poly1, poly2, output);\n\n            double totalArea = 0.0;\n\n            BOOST_FOREACH(polygon_type const& p, output)\n            {\n                totalArea += bg::area(p);\n            }\n\n            double area1 = bg::area(poly1);\n            double area2 = bg::area(poly2);\n\n            if (area1 > area2) {\n\n                return totalArea / area2;\n\n            } else {\n\n                return totalArea / area1;\n\n            }\n\n            return totalArea;\n\n        }\n\n        unsigned long* old_group_elements(unsigned long *a, unsigned long *b,\n            unsigned long *c, unsigned long *d, unsigned long n,\n            double threshold_dist)\n        {\n            \n            unsigned long *element_groups = new unsigned long[n];\n            \n            unsigned long i;\n            \n            std::vector<bool> v(n);\n            std::fill(v.begin(), v.begin() + 2, true);\n            \n            std::vector<unsigned long> w(2);\n            \n            std::vector<point_type> points1;\n            std::vector<point_type> points2;\n            \n            double height;\n                                    \n            double dist;\n            \n            double totalArea;\n            \n            std::vector< std::vector<unsigned long> > to_process = {};\n            \n            std::list< std::list<unsigned long> > res = {};\n\n            \n            std::cout << \"threshold_dist: \" << threshold_dist << std::endl;\n            \n            std::cout << \"Computing polygon distances...\" << std::endl;\n            \n            for (i = 0; i < n; i++) {\n                \n                to_process.push_back({i, i});\n                \n            }\n            \n            do {\n                                \n                w = {};\n                \n                points1 = {};\n                points2 = {};\n                                \n                for (i = 0; i < n; i++) {\n                    \n                    if (v[i]) {\n                        w.push_back(i);\n                    }\n                                        \n                }\n\n                points1.push_back(point_type(a[w[0]], b[w[0]]));\n                points1.push_back(point_type(c[w[0]], b[w[0]]));\n                points1.push_back(point_type(a[w[0]], d[w[0]]));\n                points1.push_back(point_type(c[w[0]], d[w[0]]));\n                \n                points2.push_back(point_type(a[w[1]], b[w[1]]));\n                points2.push_back(point_type(c[w[1]], b[w[1]]));\n                points2.push_back(point_type(a[w[1]], d[w[1]]));\n                points2.push_back(point_type(c[w[1]], d[w[1]]));\n                                \n                polygon_type poly1;\n                polygon_type poly2;\n\n                bg::assign_points(poly1, points1);\n                bg::assign_points(poly2, points2);\n\n                bg::correct(poly1);\n                bg::correct(poly2);\n                \n                height = std::min(abs(double(d[w[0]] - b[w[0]])), abs(double(d[w[1]] - b[w[1]])));\n                                \n                std::deque<polygon_type> output;\n                bg::intersection(poly1, poly2, output);\n\n                totalArea = 0.0;\n\n                BOOST_FOREACH(polygon_type const& p, output)\n                {\n                    totalArea += bg::area(p);\n                }\n\n                if (totalArea > 0.0){\n                    dist = 0.0;\n                } else {\n                    dist = bg::distance(poly1, poly2);\n                }\n                                \n                if (dist <= threshold_dist * height) {\n                    to_process.push_back(w);\n                }\n                        \n                \n            } while (std::prev_permutation(v.begin(), v.end()));\n                        \n            std::cout << \"Combining to nested list...\" << std::endl;\n            \n            connectedcomponents(n, to_process, res);\n            \n            i = 0;\n            \n            for (auto const& el: res) {\n                \n                for (auto const& itm: el) {\n                    element_groups[itm] = i;\n                }\n                \n                i++;\n                \n            }\n            \n            return element_groups;\n            \n        }\n        \n        unsigned long* group_elements(unsigned long *a, unsigned long *b,\n            unsigned long *c, unsigned long *d, unsigned long n,\n            double threshold_dist, double slov_ratio)\n        {\n            \n            unsigned long *element_groups = new unsigned long[n];\n            \n            unsigned long i;\n            \n            std::vector<bool> v(n);\n            std::fill(v.begin(), v.begin() + 2, true);\n            \n            std::vector<unsigned long> w(2);\n            \n            std::vector<point_type> points1;\n            std::vector<point_type> points2;\n            \n            double height, width, size_metric, min_height;\n            \n            double min_x_dist, min_y_dist, min_normal_dist;\n            \n            double pre_threshold_dist = std::max(5.0, threshold_dist);\n                                    \n            double dist;\n            \n            double totalArea;\n            \n            unsigned long y1, y2;\n            \n            std::vector< std::vector<unsigned long> > to_process = {};\n            \n            std::list< std::list<unsigned long> > res = {};\n\n            \n            std::cout << \"threshold_dist: \" << threshold_dist << std::endl;\n            \n            std::cout << \"Computing polygon distances...\" << std::endl;\n            \n            for (i = 0; i < n; i++) {\n                \n                to_process.push_back({i, i});\n                \n            }\n            \n            do {\n                                \n                w = {};\n                \n                points1 = {};\n                points2 = {};\n                \n                for (i = 0; i < n; i++) {\n                    \n                    if (v[i]) {\n                        w.push_back(i);\n                    }\n                                        \n                }\n                \n                height = std::max(abs(double(d[w[0]] - b[w[0]])), abs(double(d[w[1]] - b[w[1]])));\n                \n                min_height = std::min(abs(double(d[w[0]] - b[w[0]])), abs(double(d[w[1]] - b[w[1]])));\n                \n                width = std::max(abs(double(c[w[0]] - a[w[0]])), abs(double(c[w[1]] - a[w[1]])));\n                \n                size_metric = std::max(height, width);\n                \n                min_x_dist = std::min({abs(double(a[w[0]] - c[w[1]])), abs(double(c[w[0]] - a[w[1]])), abs(double(a[w[0]] - a[w[1]])), abs(double(c[w[0]] - c[w[1]]))});\n                \n                min_y_dist = std::min({abs(double(b[w[0] - d[w[1]]])), abs(double(d[w[0]] - b[w[1]])), abs(double(b[w[0] - b[w[1]]])), abs(double(d[w[0]] - d[w[1]]))});\n                \n                min_normal_dist = std::min(min_x_dist, min_y_dist);\n                \n                if (min_normal_dist > pre_threshold_dist * size_metric) {\n                    continue;\n                }\n\n                points1.push_back(point_type(a[w[0]], b[w[0]]));\n                points1.push_back(point_type(c[w[0]], b[w[0]]));\n                points1.push_back(point_type(a[w[0]], d[w[0]]));\n                points1.push_back(point_type(c[w[0]], d[w[0]]));\n                \n                points2.push_back(point_type(a[w[1]], b[w[1]]));\n                points2.push_back(point_type(c[w[1]], b[w[1]]));\n                points2.push_back(point_type(a[w[1]], d[w[1]]));\n                points2.push_back(point_type(c[w[1]], d[w[1]]));\n                                \n                polygon_type poly1;\n                polygon_type poly2;\n\n                bg::assign_points(poly1, points1);\n                bg::assign_points(poly2, points2);\n\n                bg::correct(poly1);\n                bg::correct(poly2);\n                                \n                std::deque<polygon_type> output;\n                bg::intersection(poly1, poly2, output);\n\n                totalArea = 0.0;\n\n                BOOST_FOREACH(polygon_type const& p, output)\n                {\n                    totalArea += bg::area(p);\n                }\n\n                if (totalArea > 0.0){\n                    dist = 0.0;\n                } else {\n                    dist = bg::distance(poly1, poly2);\n                }\n                \n                if (dist == 0) {\n                    to_process.push_back(w);\n                    continue;\n                }\n                \n                if (b[w[0]] < d[w[0]]) {\n                    y1 = b[w[0]];\n                    y2 = d[w[0]];\n                } else {\n                    y1 = d[w[0]];\n                    y2 = b[w[0]];\n                }\n                \n                if (slov_ratio >= 0) {\n                    if (! (((y1 <= b[w[1]] && b[w[1]] <= y2) && (y2 - b[w[1]]) / min_height >= slov_ratio ) || ((y1 <= d[w[1]] && d[w[1]] <= y2) && (d[w[1]] - y1) / min_height >= slov_ratio) || ((y1 <= b[w[1]]) && (y1 <= d[w[1]]) && (y2 >= b[w[1]]) && (y2 >= d[w[1]])))) {\n                        continue;\n                    }\n                }\n                                \n                if (dist <= threshold_dist * size_metric) {\n                    to_process.push_back(w);\n                }\n                        \n                \n            } while (std::prev_permutation(v.begin(), v.end()));\n                        \n            std::cout << \"Combining to nested list...\" << std::endl;\n            \n            connectedcomponents(n, to_process, res);\n            \n            i = 0;\n            \n            for (auto const& el: res) {\n                \n                for (auto const& itm: el) {\n                    element_groups[itm] = i;\n                }\n                \n                i++;\n                \n            }\n            \n            return element_groups;\n            \n        }\n        \n};\n\n\nextern \"C\" {\n    PolygonCalc* PolygonCalc_new(){ return new PolygonCalc; }\n    void PolygonCalc_delete(PolygonCalc *polygoncalc){ delete polygoncalc; }\n    const double PolygonCalc_helloworld(PolygonCalc* polygoncalc){ return polygoncalc->helloworld(); }\n    double PolygonCalc_test_calc(PolygonCalc* polygoncalc){ return polygoncalc->test_calc(); }\n    int PolygonCalc_test_nparray(double *A, int n, PolygonCalc* polygoncalc){ return polygoncalc->test_nparray(A, n); }\n    double PolygonCalc_min_poly_distance(PolygonCalc* polygoncalc, double *poly1x, double *poly1y, double *poly2x, double *poly2y, int m, int n){\n\n        return polygoncalc->min_poly_distance(poly1x, poly1y, poly2x, poly2y, m, n);\n\n    }\n    double PolygonCalc_poly_area(PolygonCalc* polygoncalc, double *poly1x, double *poly1y, int m){ return polygoncalc->poly_area(poly1x, poly1y, m); }\n    double PolygonCalc_poly_intersection_area(PolygonCalc* polygoncalc, double *poly1x, double *poly1y, double *poly2x, double *poly2y, int m, int n){\n\n        return polygoncalc->poly_intersection_area(poly1x, poly1y, poly2x, poly2y, m, n);\n\n    }\n    double PolygonCalc_poly_intersection_area_ratio(PolygonCalc* polygoncalc, double *poly1x, double *poly1y, double *poly2x, double *poly2y, int m, int n){\n\n        return polygoncalc->poly_intersection_area_ratio(poly1x, poly1y, poly2x, poly2y, m, n);\n\n    }\n    \n    unsigned long* PolygonCalc_group_elements(PolygonCalc* polygoncalc, unsigned long *a, unsigned long *b, unsigned long *c, unsigned long *d, unsigned long n, double threshold_dist, double slov_ratio) {\n        \n        return polygoncalc->group_elements(a, b, c, d, n, threshold_dist, slov_ratio);\n        \n    }\n    \n    void free_long_array(unsigned long* pointer){\n\n        delete[] pointer;\n\n    }\n    \n}\n\n", "meta": {"hexsha": "eec9d4b9646d2c9ae6381a11362248381d7df3b0", "size": 19094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/polygoncalc.cpp", "max_stars_repo_name": "ehtec/pie-chart-ocr", "max_stars_repo_head_hexsha": "ea36e29e9e585bd7a1779d7563578f190a6e0e65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polygoncalc.cpp", "max_issues_repo_name": "ehtec/pie-chart-ocr", "max_issues_repo_head_hexsha": "ea36e29e9e585bd7a1779d7563578f190a6e0e65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-22T18:34:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T18:34:42.000Z", "max_forks_repo_path": "src/polygoncalc.cpp", "max_forks_repo_name": "ehtec/pie-chart-ocr", "max_forks_repo_head_hexsha": "ea36e29e9e585bd7a1779d7563578f190a6e0e65", "max_forks_repo_licenses": ["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.8964401294, "max_line_length": 272, "alphanum_fraction": 0.4567403373, "num_tokens": 4468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.525253051227716}}
{"text": "\ufeff#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_3.h>\n#include <CGAL/Triangulation_vertex_base_with_info_3.h>\n#include <Eigen/Dense>\n#include <vtkPolyDataReader.h>\n#include <vtkPolyDataWriter.h>\n#include <vtkPolyData.h>\n#include <vtkCellArray.h>\n#include <vtkDoubleArray.h>\n#include <vtkSmartPointer.h>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Triangulation_vertex_base_with_info_3<unsigned,K> Vb;\ntypedef CGAL::Triangulation_data_structure_3<Vb> Tds;\ntypedef Tds::Vertex_handle Vertex_handle;\ntypedef Tds::Cell_handle Cell_handle;\ntypedef CGAL::Delaunay_triangulation_3<K, Tds> Delaunay;\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    clock_t t1;\n    t1 = clock();\n    for(auto i=0; i < 10000; ++i){\n        vtkNew<vtkPolyDataReader> reader;\n        reader->SetFileName(\"Bad.vtk\");\n        reader->Update();\n        auto poly = reader->GetOutput();\n        auto N = poly->GetNumberOfPoints();\n        auto pts = static_cast<double_t*>(poly->GetPoints()->GetData()->GetVoidPointer(0));\n        Map3Xd points(pts,3,N);\n\n        // Project points to unit sphere\n        points.colwise().normalize();\n\n        // Reset the center of the sphere to origin by translating\n        Vector3d center = points.rowwise().mean();\n        points = points.colwise() - center;\n\n        // Rotate all points so that the point in 0th column is along z-axis\n        Vector3d c = points.col(0);\n        double_t cos_t = c(2);\n        double_t sin_t = std::sqrt( 1 - cos_t*cos_t );\n        Vector3d axis;\n        axis << c(1), -c(0), 0.;\n        Matrix3d rotMat, axis_cross, outer;\n        axis_cross << 0. , -axis(2), axis(1),\n                        axis(2), 0., -axis(0),\n                        -axis(1), axis(0), 0.;\n\n        outer.noalias() = axis*axis.transpose();\n\n        rotMat = cos_t*Matrix3d::Identity() + sin_t*axis_cross +\n                (1-cos_t)*outer;\n        Matrix3Xd rPts(3,N);\n        rPts = rotMat*points; // The points on a sphere rotated\n\tpoints = rPts;\n\n        std::vector<std::pair<Point,unsigned>> spherePoints;\n        spherePoints.push_back(std::make_pair(Point(0.,0.,0.),N));\n        for( auto i=0; i < N; ++i){\n            spherePoints.push_back( std::make_pair(Point(points(0,i),\n                                                   points(1,i),\n                                                   points(2,i)),\n                                             i));\n        }\n\n        // Calculate the convex hull\n        Delaunay T(spherePoints.begin(),spherePoints.end());\n\n        // To extract the surface\n        std::vector<Cell_handle> cells;\n        T.tds().incident_cells( T.infinite_vertex(),\n                                std::back_inserter(cells) );\n\n        // Write to a vtk file\n        vtkNew<vtkCellArray> triangles;\n        for( auto c : cells ){\n            auto infv = c->index(T.infinite_vertex());\n            //triangles->InsertNextCell(3);\n            for( auto j=0; j < 4; ++j){\n                if (j == infv)\n                    continue;\n                triangles->InsertCellPoint(c->vertex(j)->info());\n            }\n        }\n        poly->SetPolys(triangles);\n        vtkNew<vtkPolyDataWriter> writer;\n        writer->SetFileName(\"Mesh.vtk\");\n        writer->SetInputData(poly);\n        writer->Write();\n    }\n    float diff(static_cast<float>(clock()) - static_cast<float>(t1));\n    std::cout << \"Time elapsed : \" << diff / CLOCKS_PER_SEC\n              << \" seconds\" << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "2a24a509d120560b682941d047a102f04ba1a6af", "size": 3705, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "CPP/cgal3d.cxx", "max_stars_repo_name": "amit112amit/learning-cgal", "max_stars_repo_head_hexsha": "a00b2a559cc9bd38fd041873353423f13406cb01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-01T06:55:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-18T15:54:13.000Z", "max_issues_repo_path": "CPP/cgal3d.cxx", "max_issues_repo_name": "amit112amit/learning-cgal", "max_issues_repo_head_hexsha": "a00b2a559cc9bd38fd041873353423f13406cb01", "max_issues_repo_licenses": ["MIT"], "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/cgal3d.cxx", "max_forks_repo_name": "amit112amit/learning-cgal", "max_forks_repo_head_hexsha": "a00b2a559cc9bd38fd041873353423f13406cb01", "max_forks_repo_licenses": ["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.3235294118, "max_line_length": 91, "alphanum_fraction": 0.5883940621, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5252425547376581}}
{"text": "\ufeff#include <cmath>\n#include <chrono>\n#include <thread>\n#include <ctime>\n#include <fstream>\n#include <chrono>\n\n#include <Eigen/Dense>\n\n#include <cinder/app/App.h>\n#include <cinder/app/RendererGl.h>\n#include <cinder/gl/gl.h>\n#include <cinder/CameraUi.h>\n#include <cinder/params/Params.h>\n#include <cinder/Log.h>\n#include <cinder/ObjLoader.h>\n\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/serialization/unique_ptr.hpp>\n\n#include <tinyformat.h>\n\n#include \"../resources/Resources.h\"\n#include <Utils.h>\n#include <BackgroundWorker.h>\n#include <TransferFunctionEditor.h>\n#include <Integration.h>\n#include <GridUtils.h>\n#include <TimeIntegrator.h>\n#include <SoftBodyGrid2D.h>\n#include <SoftBodyMesh2D.h>\n#include <SoftBody2DResults.h>\n\n#include <IInverseProblem.h>\n#include <InverseProblem_HumanSoftTissue.h>\n#include <InverseProblem_ProbabilisticElastography.h>\n#include <InverseProblem_Adjoint_YoungsModulus.h>\n#include <InverseProblem_Adjoint_InitialConfiguration.h>\n#include <InverseProblem_Adjoint_Dynamic.h>\n#include \"PartialObservations.h\"\n#include <GridVisualization.h>\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\nusing namespace ar;\nusing namespace Eigen;\n\nclass InverseSoftBodyApp : public App {\npublic:\n\tInverseSoftBodyApp();\n\tvoid setup() override;\n\tvoid keyDown(KeyEvent event) override;\n    void keyUp(KeyEvent event) override;\n\tvoid mouseDown( MouseEvent event ) override;\n\tvoid update() override;\n\tvoid draw() override;\n\nprivate:\n\n    typedef double real;\n\n\t//AntTweakBar settings\n\tparams::InterfaceGlRef\tparams;\n    bool printMode;\n \n    enum class ComputationMode\n    {\n        COMPUTATION_MODE_GRID = 1,\n        COMPUTATION_MODE_MESH = 2,\n        COMPUTATION_MODE_BOTH = 3\n    };\n    int computationMode;\n\n    //input - loading\n    std::unique_ptr<SoftBody2DResults> inputResults;\n    int inputTimestep;\n\n    //input - generate\n    int gridResolution;\n    bool fitObjectToGrid;\n    enum class Scene\n    {\n        SCENE_BAR,\n        SCENE_TORUS\n    };\n    Scene scene;\n    double torusOuterRadius;\n    double torusInnerRadius;\n    Vector2f rectCenter;\n    Vector2f rectHalfSize;\n    bool spaceBarPressed = false;\n    TimeIntegrator::Integrator timeIntegratorType;\n    TimeIntegrator::DenseLinearSolver denseLinearSolverType;\n    TimeIntegrator::SparseLinearSolver sparseLinearSolverType;\n    bool useSparseMatrices;\n    int sparseSolverIterations;\n    real sparseSolverTolerance;\n    SoftBodySimulation::RotationCorrection rotationCorrectionMode;\n    Vector2f gravity;\n    Vector2f neumannForce;\n    float youngsModulus;\n    float poissonsRatio;\n    float mass;\n    float dampingAlpha;\n    float dampingBeta;\n    float timestep;\n    bool gridExplicitDiffusion;\n    bool gridHardDirichletBoundaries;\n    SoftBodyGrid2D::AdvectionMode gridAdvectionMode;\n    bool solveForwardStatic;\n    SoftBodyMesh2D meshSolver;\n    SoftBodyGrid2D gridSolver;\n\n\tbool enableDirichletBoundaries_;\n\tbool enableCollision_;\n\treal groundPlaneHeight;\n\treal groundPlaneAngle;\n\treal groundStiffness_;\n\treal collisionSoftminAlpha_;\n\n\t//reconstruction\n\tenum class ReconstructionMode\n\t{\n\t\tHUMAN_SOFT_TISSUE, //human soft tissue algorithm\n\t\tPROBABILISTIC_ELASTOGRAPHY,\n        ADJOINT_YOUNGS_MODULUS,\n        ADJOINT_INITIAL_POSITIONS,\n\t\tADJOINT_DYNAMIC\n\t};\n\tReconstructionMode reconstructionMode;\n\tstd::map<ReconstructionMode, std::unique_ptr<IInverseProblem>> reconstructionAlgorithms;\n\tInverseProblemOutput resultMesh;\n\tInverseProblemOutput resultGrid;\n\tstd::optional<GridUtils2D::grid_t> cleanedSdf;\n    bool usePartialObservations;\n    PartialObservations partialObservations;\n\n    //rendering\n\tbool showGrid;\n\tenum class GridVisualizationMode\n\t{\n\t\tGRID_VISUALIZATION_U,\n\t\tGRID_VISUALIZATION_SOLUTION,\n\t\tGRID_VISUALIZATION_BOUNDARY,\n\t\t_GRID_VISUALIZATION_COUNT\n\t};\n\tGridVisualizationMode showGridSolution;\n\tbool showReconstructedSolution = false;\n\tstd::mutex invalidateRenderingMutex;\n\tstd::condition_variable invalidateRenderingConditionVariable;\n\t//visualization helpers\n\tGridVisualization visualization;\n\n    //processing\n    ar::BackgroundWorkerPtr worker;\n\tdouble meshElapsedSeconds = 0;\n\tdouble gridElapsedSeconds = 0;\n\n\n\tint reconstructSdfIterations = 5;\n\nprivate:\n    void invalidateRendering(bool wait);\n    void drawSimulation();\n\tvoid loadSimulation();\n\n    void resetSimulation();\n    void runSimulation();\n\n\tvoid resetReconstruction();\n\tvoid performReconstruction();\n\n\tvoid reconstructSDF(int mode, int iterations);\n    void testPlot();\n};\n\nInverseSoftBodyApp::InverseSoftBodyApp()\n{\n\t//initial config\n    printMode = false;\n    computationMode = (int)ComputationMode::COMPUTATION_MODE_GRID;\n    gridResolution = 22;\n    fitObjectToGrid = false;\n    scene = Scene::SCENE_BAR;\n    torusOuterRadius = 0.1;\n    torusInnerRadius = 0.03;\n    rectCenter << 0.5, 0.7;\n    rectHalfSize << 0.24, 0.06;\n    showGrid = true;\n    timeIntegratorType = TimeIntegrator::Integrator::Newmark1;\n    denseLinearSolverType = TimeIntegrator::DenseLinearSolver::PartialPivLU;\n    sparseLinearSolverType = TimeIntegrator::SparseLinearSolver::BiCGSTAB;\n    useSparseMatrices = false;\n    sparseSolverIterations = 100;\n    sparseSolverTolerance = 1e-5;\n    rotationCorrectionMode = SoftBodySimulation::RotationCorrection::Corotation;\n    inputTimestep = 0;\n\n    gridExplicitDiffusion = true;\n    gridHardDirichletBoundaries = false;\n    gridAdvectionMode = SoftBodyGrid2D::AdvectionMode::DIRECT_FORWARD;\n    gravity = Vector2f(0, -30);\n    neumannForce = Vector2f(0, 0);\n    youngsModulus = 200;\n    poissonsRatio = 0.45;\n    mass = 1.0;\n    dampingAlpha = 0.01;\n    dampingBeta = 0.01;\n    timestep = 0.01;\n\tsolveForwardStatic = false;\n\n\tenableDirichletBoundaries_ = true;\n\tenableCollision_ = false;\n\tgroundPlaneHeight = 0.6;\n\tgroundPlaneAngle = 0;\n\tgroundStiffness_ = 1000;\n\tcollisionSoftminAlpha_ = 100;\n\n\t//create reconstruction algorithms\n\treconstructionAlgorithms.emplace(ReconstructionMode::HUMAN_SOFT_TISSUE, std::make_unique<InverseProblem_HumanSoftTissue>());\n\treconstructionAlgorithms.emplace(ReconstructionMode::PROBABILISTIC_ELASTOGRAPHY, std::make_unique<InverseProblem_ProbabilisticElastography>());\n    reconstructionAlgorithms.emplace(ReconstructionMode::ADJOINT_YOUNGS_MODULUS, std::make_unique<InverseProblem_Adjoint_YoungsModulus>());\n    reconstructionAlgorithms.emplace(ReconstructionMode::ADJOINT_INITIAL_POSITIONS, std::make_unique<InverseProblem_Adjoint_InitialConfiguration>());\n\treconstructionAlgorithms.emplace(ReconstructionMode::ADJOINT_DYNAMIC, std::make_unique<InverseProblem_Adjoint_Dynamic>());\n\treconstructionMode = ReconstructionMode::ADJOINT_DYNAMIC;\n    usePartialObservations = true;\n\tshowGridSolution = GridVisualizationMode::GRID_VISUALIZATION_BOUNDARY;\n\n\tresetSimulation();\n}\n\nvoid InverseSoftBodyApp::setup()\n{\n\t//ANT TWEAK BAR\n\t//parameter ui, must happen before user-camera\n\tparams = params::InterfaceGl::create(getWindow(), \"Parameters\", ivec2(350, 800));\n    params->setOptions(\"\", \"refresh=0.05\");\n    params->addParam(\"PrintMode\", &printMode).label(\"Print Mode\");\n\n\t//input\n    params->addButton(\"LoadSimulation\", std::function<void()>([this]() {this->loadSimulation(); }), \"label='Load Simulation'\");\n    params->addParam(\"InputStep\", std::function<void(int)>([this](int v)\n    {\n        inputTimestep = v;\n\t\tshowReconstructedSolution = false;\n        invalidateRendering(false);\n    }), std::function<int()>([this]()\n    {\n        return inputTimestep;\n    })).label(\"Input Step\").min(0);\n    vector<string> computationModeEnums(4);\n    computationModeEnums[(int)ComputationMode::COMPUTATION_MODE_GRID] = \"grid\";\n    computationModeEnums[(int)ComputationMode::COMPUTATION_MODE_MESH] = \"mesh\";\n    computationModeEnums[(int)ComputationMode::COMPUTATION_MODE_BOTH] = \"overlay / both\";\n    params->addParam(\"Mode\", computationModeEnums, (int*)&computationMode, \"label='Mode'\");\n\n\t//Soft Body properties - Generate Inputs\n    params->addParam(\"InputResolution\",\n        std::function<void(int)>([this](int newValue) {this->gridResolution = newValue; this->resetSimulation(); }),\n        std::function<int()>([this]() {return this->gridResolution; })\n    ).min(4).group(\"Generate Input\").label(\"Grid resolution\").keyIncr(\"PGUP\").keyDecr(\"PGDOWN\");\n    params->addParam(\"FitObjectToGrid\",\n        std::function<void(bool)>([this](bool newValue) {this->fitObjectToGrid = newValue; this->resetSimulation(); }),\n        std::function<bool()>([this]() {return this->fitObjectToGrid; })\n    ).group(\"Generate Input\").label(\"Fit Object To Grid\");\n    vector<string> sceneEnums = { \"Bar\", \"Torus\" };\n    params->addParam(\"Scene\", sceneEnums, (int*)&scene).group(\"Generate Input\").label(\"Scene\")\n        .accessors(std::function<void(int)>([this](int v)\n    {\n        scene = (Scene)v;\n        resetSimulation();\n        if (scene == Scene::SCENE_TORUS) {\n            params->setOptions(\"InputTorusOuterRadius\", \"visible=true\");\n            params->setOptions(\"InputTorusInnerRadius\", \"visible=true\");\n            params->setOptions(\"InputRectCenterX\", \"visible=false\");\n            params->setOptions(\"InputRectHalfSizeX\", \"visible=false\");\n            params->setOptions(\"InputRectCenterY\", \"visible=false\");\n            params->setOptions(\"InputRectHalfSizeY\", \"visible=false\");\n        }\n        else {\n            params->setOptions(\"InputTorusOuterRadius\", \"visible=false\");\n            params->setOptions(\"InputTorusInnerRadius\", \"visible=false\");\n            params->setOptions(\"InputRectCenterX\", \"visible=true\");\n            params->setOptions(\"InputRectHalfSizeX\", \"visible=true\");\n            params->setOptions(\"InputRectCenterY\", \"visible=true\");\n            params->setOptions(\"InputRectHalfSizeY\", \"visible=true\");\n        }\n    }), std::function<int()>([this]() {return (int)scene; }));\n    params->addParam(\"InputTorusOuterRadius\",\n        std::function<void(double)>([this](double newValue) {this->torusOuterRadius = newValue; this->resetSimulation(); }),\n        std::function<double()>([this]() {return this->torusOuterRadius; })\n    ).min(0.01).max(0.5).step(0.01).group(\"Generate Input\").label(\"Torus outer radius\").visible(false);\n    params->addParam(\"InputTorusInnerRadius\",\n        std::function<void(double)>([this](double newValue) {this->torusInnerRadius = newValue; this->resetSimulation(); }),\n        std::function<double()>([this]() {return this->torusInnerRadius; })\n    ).min(0.01).max(0.5).step(0.01).group(\"Generate Input\").label(\"Torus inner radius\").visible(false);\n    params->addParam(\"InputRectCenterX\",\n        std::function<void(float)>([this](float newValue) {this->rectCenter.x() = newValue; this->resetSimulation(); }),\n        std::function<float()>([this]() {return this->rectCenter.x(); })\n    ).step(0.01).group(\"Generate Input\").label(\"Rect center X\").visible(true);\n    params->addParam(\"InputRectCenterY\",\n        std::function<void(float)>([this](float newValue) {this->rectCenter.y() = newValue; this->resetSimulation(); }),\n        std::function<float()>([this]() {return this->rectCenter.y(); })\n    ).step(0.01).group(\"Generate Input\").label(\"Rect center Y\").visible(true);\n    params->addParam(\"InputRectHalfSizeX\",\n        std::function<void(float)>([this](float newValue) {this->rectHalfSize.x() = newValue; this->resetSimulation(); }),\n        std::function<float()>([this]() {return this->rectHalfSize.x(); })\n    ).step(0.01).group(\"Generate Input\").label(\"Rect half size X\").visible(true);\n    params->addParam(\"InputRectHalfSizeY\",\n        std::function<void(float)>([this](float newValue) {this->rectHalfSize.y() = newValue; this->resetSimulation(); }),\n        std::function<float()>([this]() {return this->rectHalfSize.y(); })\n    ).step(0.01).group(\"Generate Input\").label(\"Rect half size Y\").visible(true);\n    params->addButton(\"InputReset\", std::function<void()>([this]() {this->resetSimulation(); }), \"label='Reset' group='Generate Input' key=r\");\n\n    params->addParam(\"SoftBodyGravity\", &gravity.y()).step(0.001).group(\"Generate Input\").label(\"Gravity\");\n    params->addParam(\"SoftBodyNeumannForce\", &neumannForce.y()).step(0.001).group(\"Generate Input\").label(\"Neumann Force\")\n        .accessors(std::function<void(float)>([this](float v)\n    {\n        neumannForce.y() = v;\n        resetSimulation();\n    }), std::function<float()>([this]() {\n        return (float)neumannForce.y();\n    }));\n    params->addParam(\"SoftBodyYoungsModulus\", &youngsModulus).min(0).step(0.01).group(\"Generate Input\").label(\"Young's modulus\");\n    params->addParam(\"SoftBodyPoissonsRatio\", &poissonsRatio).min(0.0001).max(0.4999).step(0.01).group(\"Generate Input\").label(\"Poisson's ratio\");\n    params->addParam(\"SoftBodyMass\", &mass).min(0.0001).step(0.01).group(\"Generate Input\").label(\"Mass\");\n    params->addParam(\"SoftBodyDampingAlpha\", &dampingAlpha).min(0).step(0.001).group(\"Generate Input\").label(\"Damping on mass\");\n    params->addParam(\"SoftBodyDampingBeta\", &dampingBeta).min(0).step(0.001).group(\"Generate Input\").label(\"Damping on stiffness\");\n    vector<string> timeIntegratorTypeNames = { \"Newmark 1\", \"Newmark 2\", \"Central Differences\", \"Linear Accelleration\", \"Newmark 3\", \"HHT-alpha\" };\n    params->addParam(\"SoftBodyTimeIntegration\", timeIntegratorTypeNames, (int*)&timeIntegratorType).group(\"Generate Input\").label(\"Time Integrator\")\n        .accessors(std::function<void(int)>([this](int v)\n    {\n        timeIntegratorType = (TimeIntegrator::Integrator)v;\n        resetSimulation();\n    }), std::function<int()>([this]() {return (int)timeIntegratorType; }));\n#if SOFT_BODY_SUPPORT_SPARSE_MATRICES==1\n    params->addParam(\"SoftBodyUseSparseMatrices\", std::function<void(bool)>([this](bool v)\n    {\n        useSparseMatrices = v;\n        if (v)\n        {\n            params->setOptions(\"SoftBodyDenseLinearSolver\", \"visible=false\");\n            params->setOptions(\"SoftBodySparseLinearSolver\", \"visible=true\");\n            params->setOptions(\"SoftBodySparseSolverIterations\", \"visible=true\");\n            params->setOptions(\"SoftBodySparseSolverTolerance\", \"visible=true\");\n        }\n        else\n        {\n            params->setOptions(\"SoftBodyDenseLinearSolver\", \"visible=true\");\n            params->setOptions(\"SoftBodySparseLinearSolver\", \"visible=false\");\n            params->setOptions(\"SoftBodySparseSolverIterations\", \"visible=false\");\n            params->setOptions(\"SoftBodySparseSolverTolerance\", \"visible=false\");\n        }\n    }), std::function<bool()>([this]()\n    {\n        return useSparseMatrices;\n    })).group(\"Generate Input\").label(\"Sparse matrices\");\n    vector<string> denseLinearSolverTypeNames = { \"PartialPivLU\", \"FullPivLU\", \"HouseholderQR\", \"ColPivHousholderQR\", \"FullPivHouseholderQR\", \"CompleteOrthogonalDecomposition\", \"LLT\", \"LDLT\" };\n    params->addParam(\"SoftBodyDenseLinearSolver\", denseLinearSolverTypeNames, (int*)&denseLinearSolverType).group(\"Generate Input\").label(\"Dense Linear Solver\");\n    vector<string> sparseLinearSolverTypeNames = { \"Conjugate Gradient\", \"BiCGSTAB \", \"Sparse-LU\" };\n    params->addParam(\"SoftBodySparseLinearSolver\", sparseLinearSolverTypeNames, (int*)&sparseLinearSolverType).group(\"Generate Input\").label(\"Sparse Linear Solver\");\n    params->addParam(\"SoftBodySparseSolverIterations\", &sparseSolverIterations).group(\"Generate Input\").label(\"Sparese Solver iterations\").min(0);\n    params->addParam(\"SoftBodySparseSolverTolerance\", &sparseSolverTolerance).group(\"Generate Input\").label(\"Sparese Solver tolerance\").min(0).step(0.00001);\n#else\n    vector<string> denseLinearSolverTypeNames = { \"PartialPivLU\", \"FullPivLU\", \"HouseholderQR\", \"ColPivHousholderQR\", \"FullPivHouseholderQR\", \"CompleteOrthogonalDecomposition\", \"LLT\", \"LDLT\" };\n    params->addParam(\"SoftBodyDenseLinearSolver\", denseLinearSolverTypeNames, (int*)&denseLinearSolverType).group(\"Generate Input\").label(\"Dense Linear Solver\");\n#endif\n    params->addParam(\"SoftBodyTimeStep\", &timestep).min(0.001).step(0.001).group(\"Generate Input\").label(\"Time step\");\n    params->addParam(\"SoftBodyGridExplicitDiffusion\", &gridExplicitDiffusion, \"group='Generate Input' label='Grid Displacement Diffusion' true='explicit (post-process)' false='implicit (matrix)'\");\n    params->addParam(\"SoftBodyGridHardDirichletBoundaries\", &gridHardDirichletBoundaries).group(\"Generate Input\").label(\"Grid Hard Dirichlet Boundaries\");\n    vector<string> softBodyAdvectionNames;\n    for (int i = 0; i < static_cast<int>(SoftBodyGrid2D::AdvectionMode::_COUNT_); ++i)\n        softBodyAdvectionNames.push_back(SoftBodyGrid2D::advectionModeName(static_cast<SoftBodyGrid2D::AdvectionMode>(i)));\n    params->addParam(\"SoftBodyAdvectionMode\", softBodyAdvectionNames, (int*)&gridAdvectionMode).group(\"Generate Input\").label(\"Grid Advection\");\n\n    vector<string> rotationCorrectionNames = { \"None\", \"Corotation\" };\n    params->addParam(\"SoftBodyRotationCorrection\", rotationCorrectionNames, (int*)&rotationCorrectionMode).group(\"Generate Input\").label(\"Rotation correction\");\n\n\tparams->addParam(\"SoftBodyDirichlet\",\n\t\tstd::function<void(bool)>([this](bool newValue) {this->enableDirichletBoundaries_ = newValue; this->resetSimulation(); }),\n\t\tstd::function<bool()>([this]() {return this->enableDirichletBoundaries_; }))\n\t\t.group(\"Generate Input\").label(\"Enable Dirichlet Boundaries\");\n\tparams->addParam(\"SoftBodyCollision\", &enableCollision_).group(\"Generate Input\").label(\"Enable Collision\");\n\tparams->addParam(\"InputGroundPlaneHeight\", &groundPlaneHeight).min(0).max(1).step(0.001).group(\"Generate Input\").label(\"Ground Height\");\n\tparams->addParam(\"InputGroundPlaneAngle\", &groundPlaneAngle).min(-1).max(1).step(0.001).group(\"Generate Input\").label(\"Ground Angle\");\n\tparams->addParam(\"SoftBodyCollisionGroundStiffness\", &groundStiffness_).group(\"Generate Input\").label(\"Ground Stiffness\").min(0).step(0.001);\n\tparams->addParam(\"SoftBodyCollisionSoftmaxAlpha\", &collisionSoftminAlpha_).group(\"Generate Input\").label(\"Collision Softmax-Alpha\").min(1).max(1000).step(0.001);\n\n\tparams->addParam(\"SoftBodyStaticDynamic\", &solveForwardStatic).group(\"Generate Input\").label(\"Solution Mode\").optionsStr(\"true='Static' false='Dynamic'\");\n\n\t//reconstruction\n\tvector<string> reconstructionModeNames = { \n\t    \"Human Soft Tissue\", \n\t    \"Probabilistic Elastography\",\n        \"Adjoint - Youngs Modulus\",\n        \"Adjoint - Initial Positions\",\n\t\t\"Adjoint - Dynamic\"\n\t};\n\tparams->addParam(\"ReconstructionAlgorithm\", reconstructionModeNames, (int*)&reconstructionMode)\n\t\t.group(\"Reconstruction\").label(\"Algorithm\")\n\t\t.accessors(std::function<void(int)>([this](int v) {\n\t\t\treconstructionAlgorithms[reconstructionMode]->setParamsVisibility(params, false);\n\t\t\treconstructionMode = static_cast<ReconstructionMode>(v);\n\t\t\treconstructionAlgorithms[reconstructionMode]->setParamsVisibility(params, true);\n\t\t\tresetReconstruction();\n\t\t}), std::function<int()>([this]() {\n\t\t\treturn static_cast<int>(reconstructionMode);\n\t\t}));\n\tfor (auto& p : reconstructionAlgorithms) {\n\t\tp.second->setupParams(params, \"Reconstruction\");\n\t\tp.second->setParamsVisibility(params, false);\n\t}\n\treconstructionAlgorithms[reconstructionMode]->setParamsVisibility(params, true);\n    params->addParam(\"ReconstructionUsePartialObservation\", &usePartialObservations).label(\"Partial Observation\").group(\"Reconstruction\");\n\tparams->addButton(\"ReconstructionRun\", std::function<void()>([this]() {this->performReconstruction(); }), \"group='Reconstruction' label='Solve' key=RETURN\");\n\tparams->addButton(\"ReconstructionCancel\", std::function<void()>([this]() {\n\t\tif (worker) worker->interrupt();\n\t}), \"group='Reconstruction' label='Cancel'\");\n\n    //partial observations\n    partialObservations.initParams(params);\n\n\t//rendering\n    params->addParam(\"RenderingShowGrid\", &showGrid).group(\"Rendering\").label(\"Show grid\");\n\tvector<string> gridVisualizationModeEnums((int)GridVisualizationMode::_GRID_VISUALIZATION_COUNT);\n\tgridVisualizationModeEnums[(int)GridVisualizationMode::GRID_VISUALIZATION_U] = \"u\";\n\tgridVisualizationModeEnums[(int)GridVisualizationMode::GRID_VISUALIZATION_SOLUTION] = \"solution\";\n\tgridVisualizationModeEnums[(int)GridVisualizationMode::GRID_VISUALIZATION_BOUNDARY] = \"boundary\";\n\tparams->addParam(\"RenderingShowGridSolutionMode\", gridVisualizationModeEnums, (int*)&showGridSolution, \"label='Grid solution' group=Rendering\");\n\tparams->addParam(\"RenderingShowSolution\", std::function<void(bool)>([this](bool v)\n\t{\n\t\tshowReconstructedSolution = v;\n\t\tinvalidateRendering(false);\n\t}), std::function<bool()>([this]()\n\t{\n\t\treturn showReconstructedSolution;\n\t})).label(\"Show Reconstruction\");\n\n\tparams->addParam(\"RecontructSdfIterations\", &reconstructSdfIterations).label(\"Reconstuct Sdf - Iterations\").min(0).group(\"Test\");\n\tparams->addButton(\"ReconstructSdfViscosity\", std::function<void()>([this]() {this->reconstructSDF(1, this->reconstructSdfIterations); }), \"label='Reconstruct SDF - Viscosity' group=Test \");\n\tparams->addButton(\"ReconstructSdfUpwind\", std::function<void()>([this]() {this->reconstructSDF(2, this->reconstructSdfIterations); }), \"label='Reconstruct SDF - Upwind' group=Test \");\n\tparams->addButton(\"ReconstructSdfSussmann\", std::function<void()>([this]() {this->reconstructSDF(3, this->reconstructSdfIterations); }), \"label='Reconstruct SDF - Sussmann' group=Test \");\n    params->addButton(\"ReconstructSdfFastMarching\", std::function<void()>([this]() {this->reconstructSDF(4, this->reconstructSdfIterations); }), \"label='Reconstruct SDF - Fast Marching' group=Test \");\n    params->addButton(\"TestPlot\", std::function<void()>([this]() {this->testPlot(); }), \"label='Test Plot' group=Test \");\n\tparams->setOptions(\"Test\", \"opened=false\");\n\n\tvisualization.setup();\n}\n\nvoid InverseSoftBodyApp::keyDown(KeyEvent event)\n{\n\tApp::keyDown(event);\n    if (event.isHandled()) return;\n\tif (event.getChar() == 'f') {\n\t\t// Toggle full screen when the user presses the 'f' key.\n\t\tsetFullScreen(!isFullScreen());\n\t}\n\telse if (event.getCode() == KeyEvent::KEY_ESCAPE) {\n\t\t// Exit full screen, or quit the application, when the user presses the ESC key.\n\t\tif (isFullScreen())\n\t\t\tsetFullScreen(false);\n\t\telse\n\t\t\tquit();\n\t}\n\telse if (event.getChar() == 'p') {\n\t\t//Screenshot\n\t\tSurface surface = copyWindowSurface();\n        //if (printMode) {\n        //    //only save the grid\n        //    int windowWidth = getWindow()->getWidth();\n        //    int windowHeight = getWindow()->getHeight();\n        //    int gridBoundary = 50;\n        //    int gridSize = std::min(windowWidth, windowHeight) - 2 * gridBoundary;\n        //    int gridOffsetX = windowWidth / 2;\n        //    int gridOffsetY = windowHeight / 2;\n        //    Surface surface2(gridSize + 10, gridSize + 10, false);\n        //    surface2.copyFrom(surface, Area(gridOffsetX - 5, gridOffsetY - 5, gridOffsetX + gridSize + 10, gridOffsetY + gridSize + 10));\n        //    surface = surface2;\n        //}\n\t\t//construct filename\n\t\ttime_t now = time(NULL);\n\t\tstruct tm tstruct;\n\t\tchar buf[100];\n\t\ttstruct = *localtime(&now);\n\t\tstrftime(buf, sizeof(buf), \"%d-%m-%Y_%H-%M-%S\", &tstruct);\n\t\tstring fileName = string(\"../screenshots/InverseSoftBodyApp-\") + string(buf) + \".png\";\n\t\t//write out\n\t\twriteImage(fileName, surface);\n        CI_LOG_I(\"Screenshot saved to \" << fileName);\n\t}\n    else if (event.getCode() == KeyEvent::KEY_SPACE)\n    {\n        spaceBarPressed = true;\n    }\n}\n\nvoid InverseSoftBodyApp::keyUp(KeyEvent event)\n{\n    App::keyUp(event);\n    if (event.isHandled()) return;\n    if (event.getCode() == KeyEvent::KEY_SPACE)\n    {\n        spaceBarPressed = false;\n    }\n}\n\nvoid InverseSoftBodyApp::mouseDown( MouseEvent event )\n{\n\tApp::mouseDown(event);\n}\n\nvoid InverseSoftBodyApp::update()\n{\n    //perform time stepping\n    if (spaceBarPressed) {\n\t\trunSimulation();\n    }\n\n\t//update transfer function editor\n\tvisualization.update();\n}\n\nvoid InverseSoftBodyApp::drawSimulation()\n{\n\t// Draw sdf\n\tif (computationMode & (int)ComputationMode::COMPUTATION_MODE_GRID)\n\t{\n\t\tvisualization.gridDrawSdf();\n\t\tif (showGrid)\n\t\t\tvisualization.gridDrawGridLines();\n\t\tif (showGridSolution == GridVisualizationMode::GRID_VISUALIZATION_BOUNDARY)\n\t\t\tvisualization.gridDrawObjectBoundary();\n\t\tif (!gridSolver.hasSolution())\n\t\t\tvisualization.gridDrawBoundaryConditions(gridSolver.getGridDirichlet(), gridSolver.getGridNeumannX(), gridSolver.getGridNeumannY());\n\t\tif (gridSolver.hasSolution() && showGridSolution == GridVisualizationMode::GRID_VISUALIZATION_U) {\n\t\t\tgl::ScopedColor c;\n\t\t\tif (printMode)\n\t\t\t\tgl::color(0, 0, 0.5);\n\t\t\telse\n\t\t\t\tgl::color(1, 1, 1);\n\t\t\tvisualization.gridDrawDisplacements();\n\t\t}\n\t}\n\n\t// Draw partial observations\n\tif (computationMode & (int)ComputationMode::COMPUTATION_MODE_GRID\n\t\t&& usePartialObservations) {\n\t\tgl::ScopedMatrices m;\n\t\tvisualization.applyTransformation();\n\t\tgl::ScopedColor c;\n\t\tpartialObservations.draw();\n\t}\n\n\t// Draw mesh\n\tif (computationMode & (int)ComputationMode::COMPUTATION_MODE_MESH) {\n\t\tvisualization.meshDraw();\n\t}\n\n\t// Draw ground\n\tif (enableCollision_)\n\t{\n\t\tvisualization.drawGround(groundPlaneHeight, groundPlaneAngle);\n\t}\n}\n\nvoid InverseSoftBodyApp::draw()\n{\n    using namespace ar::utils;\n    if (printMode)\n        gl::clear(Color(1, 1, 1));\n    else\n        gl::clear(Color(0, 0, 0));\n\t\n\t\n    // WINDOW SPACE\n    gl::disableDepthRead();\n    gl::disableDepthWrite();\n    gl::setMatricesWindow(getWindowSize(), true);\n\n    //draw the simulation\n    if (inputResults != nullptr)\n    {\n        drawSimulation();\n    }\n\n    // Draw the background worker's status\n    if (worker && !worker->isDone()) {\n        //draw waiting animation\n        {\n            gl::ScopedModelMatrix scopedMatrix;\n            gl::ScopedColor scopedColor;\n            gl::translate(25, getWindowHeight() - 50);\n            int step; double dummy; step = static_cast<int>(std::modf(getElapsedSeconds(), &dummy) * 8);\n            for (int i = 0; i < 8; ++i) {\n                float c = ((i + step)%8) / 7.0f;\n                gl::color(c, c, c);\n                gl::drawSolidRoundedRect(Rectf(5, -2, 15, 2), 2);\n                gl::rotate(-2.0f * M_PI / 8.0f);\n            }\n        }\n        //draw status\n        gl::ScopedColor scopedColor;\n        if (printMode)\n            gl::color(0, 0, 0);\n        else\n            gl::color(1, 1, 1);\n        gl::drawString(worker->getStatus(), vec2(50, getWindowHeight() - 50));\n    }\n\n\t//draw result\n\t{\n\t\tstatic Font font(\"Arial\", 20);\n\t\tstatic ColorA color(1, 1, 1, 1);\n\t\tgl::ScopedColor scopedColor;\n\t\tif (printMode)\n\t\t\tgl::color(0, 0, 0);\n\t\telse\n\t\t\tgl::color(1, 1, 1);\n\t\tint gridSize = std::min(getWindowWidth(), getWindowHeight()) - 100;\n\t\tint x = (getWindowWidth() + gridSize) / 2 + 50;\n\t\tint y = 50;\n\t\tint stepY = 15;\n\n\t\tgl::drawString(\"Results Mesh\", vec2(x, y), color, font); y += stepY;\n\t\tgl::drawString(\"<Prop>: <Computed> - <Truth> (<StdDev>)\", vec2(x, y), color, font); y += stepY;\n\t\tif (resultMesh.youngsModulus_.has_value()) {\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Young's Modulus: %.2f - %.2f (%.2f)\", resultMesh.youngsModulus_.value(), inputResults->settings_.youngsModulus_, resultMesh.youngsModulusStdDev_.value_or(0))\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tif (resultMesh.poissonsRatio_.has_value()) {\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Poisson Ratio: %.2f - %.2f\", resultMesh.poissonsRatio_.value(), inputResults->settings_.poissonsRatio_)\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tif (resultMesh.mass_.has_value()) {\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Mass: %.2f - %.2f (%.2f)\", resultMesh.mass_.value(), inputResults->settings_.mass_, resultMesh.massStdDev_.value_or(0))\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tif (resultMesh.dampingAlpha_.has_value()) {\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Mass Damping: %.2f - %.2f (%.2f)\", resultMesh.dampingAlpha_.value(), inputResults->settings_.dampingAlpha_, resultMesh.dampingAlphaStdDev_.value_or(0))\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tif (resultMesh.dampingBeta_.has_value()) {\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Stiffness Damping: %.2f - %.2f (%.2f)\", resultMesh.dampingBeta_.value(), inputResults->settings_.dampingBeta_, resultMesh.dampingBetaStdDev_.value_or(0))\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tif (resultMesh.groundHeight.has_value())\n\t\t{\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Ground Height: %.3f - %.3f\", resultMesh.groundHeight.value(), inputResults->settings_.groundPlaneHeight_)\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tif (resultMesh.groundAngle.has_value())\n\t\t{\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Ground Angle: %.3f - %.3f\", resultMesh.groundAngle.value(), inputResults->settings_.groundPlaneAngle_)\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tgl::drawString(tfm::format(\"Final Cost: %.3f\", resultMesh.finalCost_), vec2(x, y), color, font); y += stepY;\n\t\tif (meshElapsedSeconds > 0)\n\t\t\tgl::drawString(tfm::format(\"Time: %.2f sec\", meshElapsedSeconds), vec2(x, y), color, font); y += stepY;\n\n\t\ty += stepY;\n\t\tgl::drawString(\"Results Grid\", vec2(x, y), color, font); y += stepY;\n\t\tgl::drawString(\"<Prop>: <Computed> - <Truth> (<StdDev>)\", vec2(x, y), color, font); y += stepY;\n\t\tif (resultGrid.youngsModulus_.has_value()) {\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Young's Modulus: %.2f - %.2f (%.2f)\", resultGrid.youngsModulus_.value(), inputResults->settings_.youngsModulus_, resultGrid.youngsModulusStdDev_.value_or(0))\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tif (resultGrid.poissonsRatio_.has_value()) {\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Poisson Ratio: %.2f - %.2f\", resultMesh.poissonsRatio_.value(), inputResults->settings_.poissonsRatio_)\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tif (resultGrid.mass_.has_value()) {\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Mass: %.2f - %.2f (%.2f)\", resultGrid.mass_.value(), inputResults->settings_.mass_, resultGrid.massStdDev_.value_or(0))\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tif (resultGrid.dampingAlpha_.has_value()) {\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Mass Damping: %.2f - %.2f (%.2f)\", resultGrid.dampingAlpha_.value(), inputResults->settings_.dampingAlpha_, resultGrid.dampingAlphaStdDev_.value_or(0))\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tif (resultGrid.dampingBeta_.has_value()) {\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Stiffness Damping: %.2f - %.2f (%.2f)\", resultGrid.dampingBeta_.value(), inputResults->settings_.dampingBeta_, resultGrid.dampingBetaStdDev_.value_or(0))\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tif (resultGrid.groundHeight.has_value())\n\t\t{\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Ground Height: %.3f - %.3f\", resultGrid.groundHeight.value(), inputResults->settings_.groundPlaneHeight_)\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tif (resultGrid.groundAngle.has_value())\n\t\t{\n\t\t\tgl::drawString(\n\t\t\t\ttfm::format(\"Ground Angle: %.3f - %.3f\", resultGrid.groundAngle.value(), inputResults->settings_.groundPlaneAngle_)\n\t\t\t\t, vec2(x, y), color, font);\n\t\t\ty += stepY;\n\t\t}\n\t\tgl::drawString(tfm::format(\"Final Cost: %.3f\", resultGrid.finalCost_), vec2(x, y), color, font); y += stepY;\n\t\tif (gridElapsedSeconds > 0)\n\t\t\tgl::drawString(tfm::format(\"Time: %.2f sec\", gridElapsedSeconds), vec2(x, y), color, font); y += stepY;\n\t}\n\n\t// Draw the interface\n\tvisualization.setTfeVisible(!printMode);\n\tparams->draw();\n\tvisualization.drawTransferFunctionEditor();\n\n\t//notify waiting threads\n\tinvalidateRenderingConditionVariable.notify_all();\n}\n\nvoid InverseSoftBodyApp::invalidateRendering(bool wait)\n{\n\t//GRID\n\tSoftBodyGrid2D::grid_t referenceSdf = inputResults->gridReferenceSdf_;\n\tSoftBodyGrid2D::grid_t currentSdf;\n\tSoftBodyGrid2D::grid_t currentUx = GridUtils2D::grid_t::Zero(gridSolver.getGridResolution(), gridSolver.getGridResolution());\n\tSoftBodyGrid2D::grid_t currentUy = GridUtils2D::grid_t::Zero(gridSolver.getGridResolution(), gridSolver.getGridResolution());\n\tif (inputTimestep > 0) {\n\t\tif (cleanedSdf.has_value()) {\n\t\t\tcurrentSdf = cleanedSdf.value();\n\t\t}\n\t\telse if (showReconstructedSolution && resultGrid.resultGridSdf_.has_value()) {\n\t\t\tcurrentSdf = resultGrid.resultGridSdf_.value();\n\t\t}\n\t\telse if (showReconstructedSolution && resultGrid.initialGridSdf_.has_value()) {\n\t\t\tcurrentSdf = resultGrid.initialGridSdf_.value();\n\t\t}\n\t\telse {\n\t\t\tif (inputResults->gridResultsSdf_.size() > inputTimestep - 1) {\n\t\t\t\tcurrentSdf = inputResults->gridResultsSdf_[inputTimestep - 1];\n\t\t\t\tcurrentUx = inputResults->gridResultsUx_[inputTimestep - 1];\n\t\t\t\tcurrentUy = inputResults->gridResultsUy_[inputTimestep - 1];\n\t\t\t}\n\t\t\telse\n\t\t\t\tcurrentSdf = inputResults->gridReferenceSdf_;\n\t\t}\n\t}\n\telse\n\t{\n\t\tcurrentSdf = inputResults->gridReferenceSdf_;\n\t}\n\tif (gridSolver.hasSolution())\n\t{\n\t\tvisualization.setGrid(gridSolver.getSdfReference(), gridSolver.getSdfSolution(), gridSolver.getUGridX(), gridSolver.getUGridY());\n\t}\n\telse\n\t{\n\t\tGridUtils2D::grid_t z = GridUtils2D::grid_t::Zero(gridSolver.getGridResolution(), gridSolver.getGridResolution());\n\t\tvisualization.setGrid(gridSolver.getSdfReference(), gridSolver.getSdfReference(), z, z);\n\t}\n\n\t//MESH\n\tauto pos = inputResults->meshReferencePositions_;\n\tif (inputTimestep > 0) {\n\t\tif (showReconstructedSolution && resultMesh.resultMeshDisp_.has_value()) {\n\t\t\tfor (size_t i = 0; i < pos.size(); ++i)\n\t\t\t\tpos[i] += resultMesh.resultMeshDisp_.value()[i];\n\t\t}\n\t\telse if (showReconstructedSolution && resultMesh.initialMeshPositions_.has_value()) {\n\t\t\tpos = resultMesh.initialMeshPositions_.value();\n\t\t}\n\t\telse {\n\t\t\tif (inputResults->meshResultsDisplacement_.size() > inputTimestep - 1)\n\t\t\t\tfor (size_t i = 0; i < pos.size(); ++i)\n\t\t\t\t\tpos[i] += inputResults->meshResultsDisplacement_[inputTimestep - 1][i];\n\t\t}\n\t}\n\tvisualization.setMesh(pos, inputResults->meshReferenceIndices_, meshSolver.getNodeStates());\n\n\t//wait for the rendering to happen\n\tif (wait)\n\t{\n\t\tstd::unique_lock<std::mutex> lock(invalidateRenderingMutex);\n\t\tinvalidateRenderingConditionVariable.wait_for(lock, 50ms);\n\t}\n}\n\nvoid InverseSoftBodyApp::loadSimulation()\n{\n\t//get save path\n\tfs::path path = getOpenFilePath(fs::path(\"../saves/\"));\n\tif (path.empty()) {\n\t\tCI_LOG_W(\"Saving cancelled by the user\");\n\t\treturn;\n\t}\n\tstd::string pathS = path.string();\n\tCI_LOG_I(\"Load results from \" << pathS);\n\n\t//load it\n\tstd::ifstream ifs(pathS, std::ifstream::binary);\n\tboost::archive::binary_iarchive ia(ifs);\n\tia >> inputResults;\n\tCI_LOG_I(\"Results loaded\");\n    params->setOptions(\"InputStep\", \"max=\" + std::to_string(inputResults->numSteps_));\n\tinputTimestep = 0;\n\n\tresetReconstruction();\n}\n\nvoid InverseSoftBodyApp::resetSimulation()\n{\n\t//reset solution\n\tinputResults = std::make_unique<SoftBody2DResults>();\n\n\t//create scene\n\tswitch (scene)\n\t{\n\tcase Scene::SCENE_BAR:\n\t\tgridSolver = SoftBodyGrid2D::CreateBar(\n\t\t\trectCenter.cast<real>(), rectHalfSize.cast<real>(), gridResolution,\n\t\t\tfitObjectToGrid, enableDirichletBoundaries_, Vector2(0, 0), neumannForce.cast<real>());\n\t\tinputResults->initGridReference(gridSolver);\n\t\tmeshSolver = SoftBodyMesh2D::CreateBar(\n\t\t\trectCenter.cast<real>(), rectHalfSize.cast<real>(),\n\t\t\tgridResolution, fitObjectToGrid,\n\t\t\tenableDirichletBoundaries_, Vector2(0, 0), neumannForce.cast<real>());\n\t\tinputResults->initMeshReference(meshSolver);\n\t\tbreak;\n\tcase Scene::SCENE_TORUS:\n\t\tgridSolver = SoftBodyGrid2D::CreateTorus(\n\t\t\ttorusOuterRadius, torusInnerRadius, gridResolution,\n\t\t\tenableDirichletBoundaries_, Vector2(0, 0), neumannForce.cast<real>());\n\t\tinputResults->initGridReference(gridSolver);\n\t\tmeshSolver = SoftBodyMesh2D::CreateTorus(\n\t\t\ttorusOuterRadius, torusInnerRadius,\n\t\t\tgridResolution, enableDirichletBoundaries_, Vector2(0, 0), neumannForce.cast<real>().eval());\n\t\tinputResults->initMeshReference(meshSolver);\n\t}\n\n\tresetReconstruction();\n\t//invalidate texture and mesh\n\tshowReconstructedSolution = false;\n\tinputTimestep = 0;\n\tinvalidateRendering(false);\n}\n\nvoid InverseSoftBodyApp::runSimulation()\n{\n\tif (worker != nullptr && !worker->isDone()) {\n\t\t//still running\n\t\treturn;\n\t}\n\n\tif (solveForwardStatic && !enableDirichletBoundaries_)\n\t{\n\t\tCI_LOG_E(\"Can't solve for static solution if dirichlet boundaries are disabled\");\n\t\treturn;\n\t}\n\n\t//declare background task\n\tstd::function<void(BackgroundWorker*)> task = [this](BackgroundWorker* worker) {\n\t\t//pass arguments\n\t\tmeshSolver.setGravity(gravity.cast<real>());\n\t\tmeshSolver.setMaterialParameters(youngsModulus, poissonsRatio);\n\t\tmeshSolver.setMass(mass);\n\t\tmeshSolver.setDamping(dampingAlpha, dampingBeta);\n\t\tmeshSolver.setDenseLinearSolver(denseLinearSolverType);\n\t\tmeshSolver.setSparseLinearSolver(sparseLinearSolverType);\n\t\tmeshSolver.setTimeIntegrator(timeIntegratorType);\n\t\tmeshSolver.setUseSparseMatrices(useSparseMatrices);\n\t\tmeshSolver.setSparseSolveIterations(sparseSolverIterations);\n\t\tmeshSolver.setSparseSolveTolerance(sparseSolverTolerance);\n\t\tmeshSolver.setRotationCorrection(rotationCorrectionMode);\n\t\tmeshSolver.setTimestep(timestep);\n\t\tmeshSolver.setGroundPlane(groundPlaneHeight, groundPlaneAngle);\n\t\tmeshSolver.setEnableCollision(enableCollision_);\n\t\tmeshSolver.setCollisionResolution(SoftBodySimulation::CollisionResolution::SPRING_IMPLICIT);\n\t\tmeshSolver.setCollisionVelocityDamping(0);\n\t\tmeshSolver.setGroundStiffness(groundStiffness_);\n\t\tmeshSolver.setCollisionSoftmaxAlpha(collisionSoftminAlpha_);\n\t\tgridSolver.setGravity(gravity.cast<real>());\n\t\tgridSolver.setMaterialParameters(youngsModulus, poissonsRatio);\n\t\tgridSolver.setMass(mass);\n\t\tgridSolver.setDamping(dampingAlpha, dampingBeta);\n\t\tgridSolver.setDenseLinearSolver(denseLinearSolverType);\n\t\tgridSolver.setSparseLinearSolver(sparseLinearSolverType);\n\t\tgridSolver.setTimeIntegrator(timeIntegratorType);\n\t\tgridSolver.setUseSparseMatrices(useSparseMatrices);\n\t\tgridSolver.setSparseSolveIterations(sparseSolverIterations);\n\t\tgridSolver.setSparseSolveTolerance(sparseSolverTolerance);\n\t\tgridSolver.setExplicitDiffusion(gridExplicitDiffusion);\n\t\tgridSolver.setHardDirichletBoundaries(gridHardDirichletBoundaries);\n\t\tgridSolver.setAdvectionMode(gridAdvectionMode);\n\t\tgridSolver.setRotationCorrection(rotationCorrectionMode);\n\t\tgridSolver.setTimestep(timestep);\n\t\tgridSolver.setGroundPlane(groundPlaneHeight, groundPlaneAngle);\n\t\tgridSolver.setEnableCollision(enableCollision_);\n\t\tgridSolver.setCollisionResolution(SoftBodySimulation::CollisionResolution::SPRING_IMPLICIT);\n\t\tgridSolver.setCollisionVelocityDamping(0);\n\t\tgridSolver.setGroundStiffness(groundStiffness_);\n\t\tgridSolver.setCollisionSoftmaxAlpha(collisionSoftminAlpha_);\n\n\t\tinputResults->settings_ = gridSolver.getSettings();\n\n\t\t//solve it\n\t\tif (int(computationMode) & int(ComputationMode::COMPUTATION_MODE_MESH)) {\n\t\t\tauto start1 = std::chrono::steady_clock::now();\n\t\t\tif (solveForwardStatic) {\n\t\t\t\tmeshSolver.solveStaticSolution(worker);\n\t\t\t\tif (worker->isInterrupted()) return;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmeshSolver.solveDynamicSolution(worker);\n\t\t\t\tif (worker->isInterrupted()) return;\n\t\t\t}\n\t\t\tauto duration1 = std::chrono::duration_cast<chrono::milliseconds>(std::chrono::steady_clock::now() - start1);\n\t\t\tmeshElapsedSeconds = duration1.count() / 1000.0;\n\t\t\tinputResults->meshResultsDisplacement_.push_back(meshSolver.getCurrentDisplacements());\n\t\t\tinputResults->meshResultsVelocities_.push_back(meshSolver.getCurrentVelocities());\n\t\t}\n\n\t\tif (int(computationMode) & int(ComputationMode::COMPUTATION_MODE_GRID)) {\n\t\t\tauto start2 = std::chrono::steady_clock::now();\n\t\t\tif (solveForwardStatic) {\n\t\t\t\tgridSolver.solveStaticSolution(worker);\n\t\t\t\tif (worker->isInterrupted()) return;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tgridSolver.solveDynamicSolution(worker);\n\t\t\t\tif (worker->isInterrupted()) return;\n\t\t\t}\n\t\t\tauto duration2 = std::chrono::duration_cast<chrono::milliseconds>(std::chrono::steady_clock::now() - start2);\n            CI_LOG_D(\"Reference simulation result:\\n\" << gridSolver.getSdfSolution());\n            CI_LOG_D(\"Reference uX:\\n\" << gridSolver.getUGridX());\n            CI_LOG_D(\"Reference uY:\\n\" << gridSolver.getUGridY());\n            CI_LOG_D(\"Settings: \" << gridSolver.getSettings() << \" \" << gridSolver.getGridSettings());\n\t\t\tgridElapsedSeconds = duration2.count() / 1000.0;\n\t\t\tinputResults->gridResultsSdf_.push_back(gridSolver.getSdfSolution());\n\t\t\tinputResults->gridResultsUx_.push_back(gridSolver.getUGridX());\n\t\t\tinputResults->gridResultsUy_.push_back(gridSolver.getUGridY());\n\t\t\tinputResults->gridResultsUxy_.push_back(gridSolver.getUSolution());\n            partialObservations.setSdf(gridSolver.getSdfReference(), gridSolver.getSdfSolution(), gridSolver.getUGridX(), gridSolver.getUGridY());\n            inputResults->gridPartialObservations_.push_back(partialObservations.getObservations());\n\t\t}\n\n\t\tinputResults->numSteps_++;\n\t\tinputTimestep = inputResults->numSteps_;\n\t\tshowReconstructedSolution = false;\n\t\tparams->setOptions(\"InputStep\", \"max=\" + std::to_string(inputResults->numSteps_));\n\t\tinvalidateRendering(false);\n\t};\n\n\t//start background worker\n\tworker = make_shared<BackgroundWorker>(task);\n\tCI_LOG_I(\"Background worker started\");\n}\n\nvoid InverseSoftBodyApp::resetReconstruction()\n{\n\tCI_LOG_D(\"reset\");\n\tworker = nullptr;\n\n\tcleanedSdf.reset();\n\tresultMesh = InverseProblemOutput();\n\tresultGrid = InverseProblemOutput();\n\tmeshElapsedSeconds = 0;\n\tgridElapsedSeconds = 0;\n\tinvalidateRendering(false);\n}\n\nvoid InverseSoftBodyApp::performReconstruction()\n{\n\tif (worker != nullptr && !worker->isDone()) {\n\t\t//still running\n\t\treturn;\n\t}\n\n\tif (this->inputTimestep == 0) {\n\t\tCI_LOG_I(\"no timestep selected\");\n\t\treturn;\n\t}\n\n\tresetReconstruction();\n\n\t//declare background task\n\tstd::function<void(BackgroundWorker*)> task = [this](BackgroundWorker* worker) {\n\t\t//get algorithm\n\t\tIInverseProblem* alg = reconstructionAlgorithms[reconstructionMode].get();\n\t\talg->setInput(inputResults.get());\n        if (InverseProblem_Adjoint_Dynamic* algD = dynamic_cast<InverseProblem_Adjoint_Dynamic*>(alg))\n        {\n            algD->setGridUsePartialObservation(usePartialObservations);\n        }\n\t\t//run them\n\t\tif (computationMode & (int)ComputationMode::COMPUTATION_MODE_MESH) {\n\t\t\tauto start1 = std::chrono::steady_clock::now();\n\t\t\tresultMesh = alg->solveMesh(this->inputTimestep-1, worker, [this](const InverseProblemOutput& intermediateSolution)\n\t\t\t{\n\t\t\t\tshowReconstructedSolution = true;\n\t\t\t\tresultMesh = intermediateSolution;\n\t\t\t\tinvalidateRendering(true);\n\t\t\t});\n\t\t\tauto duration1 = std::chrono::duration_cast<chrono::milliseconds>(std::chrono::steady_clock::now() - start1);\n\t\t\tmeshElapsedSeconds = duration1.count() / 1000.0;\n\t\t\tif (worker->isInterrupted()) return;\n\t\t}\n\t\tif (computationMode & (int)ComputationMode::COMPUTATION_MODE_GRID) {\n\t\t\tauto start2 = std::chrono::steady_clock::now();\n\t\t\tresultGrid = alg->solveGrid(this->inputTimestep-1, worker, [this](const InverseProblemOutput& intermediateSolution)\n\t\t\t{\n\t\t\t\tshowReconstructedSolution = true;\n\t\t\t\tresultGrid = intermediateSolution;\n\t\t\t\tinvalidateRendering(true);\n\t\t\t});\n\t\t\tif (worker->isInterrupted()) return;\n\t\t\tauto duration2 = std::chrono::duration_cast<chrono::milliseconds>(std::chrono::steady_clock::now() - start2);\n\t\t\tgridElapsedSeconds = duration2.count() / 1000.0;\n\t\t}\n\t\tshowReconstructedSolution = true;\n\t\tinvalidateRendering(true);\n\t};\n\n\t//start background worker\n\tworker = make_shared<BackgroundWorker>(task);\n\tCI_LOG_I(\"Background worker started\");\n}\n\nvoid InverseSoftBodyApp::reconstructSDF(int mode, int iterations)\n{\n\tGridUtils2D::grid_t sdf;\n\tif (inputTimestep > 0) {\n\t\tif (showReconstructedSolution && resultGrid.resultGridSdf_.has_value()) {\n\t\t\tsdf = resultGrid.resultGridSdf_.value();\n\t\t}\n\t\telse if (showReconstructedSolution && resultGrid.initialGridSdf_.has_value()) {\n\t\t\tsdf = resultGrid.initialGridSdf_.value();\n\t\t}\n\t\telse {\n\t\t\tsdf = inputResults->gridResultsSdf_[inputTimestep - 1];\n\t\t}\n\t}\n\telse\n\t{\n\t\tsdf = inputResults->gridReferenceSdf_;\n\t}\n\n\treal viscosity = 0.01;\n\tif (iterations > 0) {\n        if (mode == 1)\n            sdf = GridUtils2D::recoverSDFViscosity(sdf, viscosity, iterations);\n        else if (mode == 2)\n            sdf = GridUtils2D::recoverSDFUpwind(sdf, iterations);\n        else if (mode == 3)\n            sdf = GridUtils2D::recoverSDFSussmann(sdf, viscosity, iterations);\n        else if (mode == 4)\n            sdf = GridUtils2D::recoverSDFFastMarching(sdf);\n\t}\n\n\tcleanedSdf = sdf;\n\tinvalidateRendering(false);\n\n\tCI_LOG_I(\"SDF cleaned up\");\n}\n\nvoid InverseSoftBodyApp::testPlot()\n{\n    std::function<void(BackgroundWorker*)> task = [this](BackgroundWorker* worker) {\n\t\t//get algorithm\n\t\tIInverseProblem* alg = reconstructionAlgorithms[reconstructionMode].get();\n\t\tif (InverseProblem_Adjoint_Dynamic* algD = dynamic_cast<InverseProblem_Adjoint_Dynamic*>(alg))\n        {\n            algD->setGridUsePartialObservation(usePartialObservations);\n        }\n        alg->setInput(inputResults.get());\n\t\t//run test plot\n\t\talg->testPlot(this->inputTimestep, worker);\n    };\n    worker = make_shared<BackgroundWorker>(task);\n    CI_LOG_I(\"Background worker started\");\n}\n\n#if 1\nCINDER_APP( InverseSoftBodyApp, RendererGl(RendererGl::Options().msaa(8)), [&](App::Settings *settings)\n{\n\tsettings->setWindowSize(1600, 900);\n} )\n#endif\n", "meta": {"hexsha": "462ab56c9c8cb520820ffc613d8d818632ae3992", "size": 44770, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "InverseSoftBodyApp/InverseSoftBodyApp.cpp", "max_stars_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_stars_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-03-08T18:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T20:32:56.000Z", "max_issues_repo_path": "InverseSoftBodyApp/InverseSoftBodyApp.cpp", "max_issues_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_issues_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "InverseSoftBodyApp/InverseSoftBodyApp.cpp", "max_forks_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_forks_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-26T01:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T13:32:46.000Z", "avg_line_length": 40.5893019039, "max_line_length": 200, "alphanum_fraction": 0.7146750056, "num_tokens": 11975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5252313685843252}}
{"text": "/**\n * \\ file SecondOrderFilter.cpp\n */\n\n#include <ATK/EQ/SecondOrderFilter.h>\n#include <ATK/EQ/IIRFilter.h>\n\n#include <ATK/Mock/FFTCheckerFilter.h>\n#include <ATK/Mock/SimpleSinusGeneratorFilter.h>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\n#define PROCESSSIZE (1024*64)\n\nBOOST_AUTO_TEST_CASE( IIRFilter_BandPassCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::SecondOrderBandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_Q(1);\n  filter.set_cut_frequency(100);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.31610222820014583));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_BandPassCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::SecondOrderBandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_Q(1);\n  filter.set_cut_frequency(100);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.8408964152537104));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_BandPassCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::SecondOrderBandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_Q(1);\n  filter.set_cut_frequency(100);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 0.22326595903140814));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_BandPassPeakCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::SecondOrderBandPassPeakCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_Q(1);\n  filter.set_cut_frequency(100);\n  filter.set_gain(2);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 1.0074946766389419));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_BandPassPeakCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::SecondOrderBandPassPeakCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_Q(1);\n  filter.set_cut_frequency(100);\n  filter.set_gain(2);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 1.4142135623730931));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_BandPassPeakCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::SecondOrderBandPassPeakCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_Q(1);\n  filter.set_cut_frequency(100);\n  filter.set_gain(2);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 1.0018333926095173));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_AllPassCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n\n  ATK::IIRFilter<ATK::SecondOrderAllPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_Q(.1);\n  filter.set_cut_frequency(100);\n\n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 1));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n\n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n\n  filter.process(1024*64);\n\n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_AllPassCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n\n  ATK::IIRFilter<ATK::SecondOrderAllPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_Q(.1);\n  filter.set_cut_frequency(100);\n\n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 1));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n\n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n\n  filter.process(1024*64);\n\n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_AllPassCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n\n  ATK::IIRFilter<ATK::SecondOrderAllPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_Q(.1);\n  filter.set_cut_frequency(100);\n\n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 1));\n  checker.set_checks(frequency_checks);\n\n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n\n  filter.process(1024*64);\n\n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_LowPassCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::SecondOrderLowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n\n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.09991943746806305));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_LowPassCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::SecondOrderLowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.8408964152537146));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_LowPassCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::SecondOrderLowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 0.04984673793807906));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_LowPassCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::SecondOrderLowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.49246840910199763));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_HighPassCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::SecondOrderHighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(1000);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.8697981291708585));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_HighPassCoefficients_10k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(10000);\n  \n  ATK::IIRFilter<ATK::SecondOrderHighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(1000);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(10000, 1.0344582218093583));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_HighPassCoefficients_500_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(500);\n  \n  ATK::IIRFilter<ATK::SecondOrderHighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(1000);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(500, 0.5091584471108357));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_LowShelvingCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::SecondOrderLowShelvingCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_gain(.5);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.9999157109896207));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_LowShelvingCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::SecondOrderLowShelvingCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_gain(.5);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.7951544465306409));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_LowShelvingCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::SecondOrderLowShelvingCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_gain(.5);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.9599245087100254));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_HighShelvingCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::SecondOrderHighShelvingCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(1000);\n  filter.set_gain(.5);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.7953107582465426));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_HighShelvingCoefficients_10k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(10000);\n  \n  ATK::IIRFilter<ATK::SecondOrderHighShelvingCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(1000);\n  filter.set_gain(.5);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(10000, 0.7071168098138222));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_HighShelvingCoefficients_500_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(500);\n  \n  ATK::IIRFilter<ATK::SecondOrderHighShelvingCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(1000);\n  filter.set_gain(.5);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(500, 0.960256352408842));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n", "meta": {"hexsha": "44ec277de257727ffc577b1c1469d9f0bf861f78", "size": 21445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/EQ/SecondOrderFilter.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": "tests/EQ/SecondOrderFilter.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": "tests/EQ/SecondOrderFilter.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.9923076923, "max_line_length": 75, "alphanum_fraction": 0.7744462579, "num_tokens": 5925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5252313594374436}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <config.h>\n#include <string>\n#include \"png_weight.hpp\"\n#include \"util.hpp\"\n#include \"neural_net.hpp\"\n#include \"mnist.hpp\"\n\nusing std::string;\nusing elem_t = float;\n\nvoid run() {\n    string train_images_fn = data_dir + \"/train-images-idx3-ubyte\";\n    string train_labels_fn = data_dir + \"/train-labels-idx1-ubyte\";\n    string test_images_fn = data_dir + \"/t10k-images-idx3-ubyte\";\n    string test_labels_fn = data_dir + \"/t10k-labels-idx1-ubyte\";\n\n    auto train_data = mnist<elem_t>::create(train_images_fn, train_labels_fn);\n    auto test_data = mnist<elem_t>::create(test_images_fn, test_labels_fn);\n    auto train_net = neural_net<elem_t>(train_data, 0.1);\n\n    // Train the neural net. Pass in a lambda to display progress\n    train_net.train(200, [&](size_t i, size_t max_itr) -> void {\n        // Display progress\n        if (i == 0 || i % 20 == 0 || i == max_itr - 1) {\n            std::cout << i << \" cost function = \" << train_net.cost()\n                      << \", percent correct: \" << train_net.predict()\n                      << std::endl;\n        }\n    });\n\n    std::cout << std::endl;\n\n    // Create a 2nd neural network using the learned weights from training data\n    auto test_net = neural_net<elem_t>(test_data);\n    test_net.theta1 = train_net.theta1;\n    test_net.theta2 = train_net.theta2;\n\n    auto percentage = test_net.predict();\n\n    std::cout << \"percentage correct: \" << percentage << std::endl;\n\n    // Write out the weight to a png file\n    weight_png(\"theta1.png\", no_bias(train_net.theta1), 28, 28, 2, 2);\n    weight_png(\"theta2.png\", no_bias(train_net.theta2), 8, 8, 2, 2);\n}\n\nint main(int, char**) {\n    try {\n        run();\n    } catch (std::runtime_error err) {\n        std::cerr << err.what() << std::endl;\n    }\n}\n", "meta": {"hexsha": "df4c040728cd96a747b9ebdc76954ba281321893", "size": 1802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "riskybacon/mnist_arma", "max_stars_repo_head_hexsha": "4921686adf2382d7fb87d41d25d5e7e6342e6ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-27T12:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-27T12:54:01.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "riskybacon/mnist_arma", "max_issues_repo_head_hexsha": "4921686adf2382d7fb87d41d25d5e7e6342e6ec3", "max_issues_repo_licenses": ["MIT"], "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": "riskybacon/mnist_arma", "max_forks_repo_head_hexsha": "4921686adf2382d7fb87d41d25d5e7e6342e6ec3", "max_forks_repo_licenses": ["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.1785714286, "max_line_length": 79, "alphanum_fraction": 0.6270810211, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5252076469688671}}
{"text": "#include \"NormalPrior.h\"\n\n#include <iomanip>\n\n#include <SmurffCpp/Utils/linop.h>\n#include <SmurffCpp/IO/MatrixIO.h>\n#include <SmurffCpp/Utils/counters.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <SmurffCpp/Utils/Distribution.h>\n#include <SmurffCpp/Utils/Error.h>\n\nusing namespace smurff;\n\n//  base class NormalPrior\n\nNormalPrior::NormalPrior(std::shared_ptr<Session> session, uint32_t mode, std::string name)\n   : ILatentPrior(session, mode, name)\n{\n\n}\n\nvoid NormalPrior::init()\n{\n   //does not look that there was such init previously\n   ILatentPrior::init();\n\n   const int K = num_latent();\n   m_mu = std::make_shared<Eigen::VectorXd>(K);\n   hyperMu().setZero();\n\n   Lambda.resize(K, K);\n   Lambda.setIdentity();\n   Lambda *= 10;\n\n   // parameters of Inv-Whishart distribution\n   WI.resize(K, K);\n   WI.setIdentity();\n   mu0.resize(K);\n   mu0.setZero();\n   b0 = 2;\n   df = K;\n\n   const auto &config = getSession().getConfig();\n   if (config.hasPropagatedPosterior(getMode()))\n   {\n      mu_pp = std::make_shared<Eigen::MatrixXd>(matrix_utils::dense_to_eigen(*config.getMuPropagatedPosterior(getMode())));\n      Lambda_pp = std::make_shared<Eigen::MatrixXd>(matrix_utils::dense_to_eigen(*config.getLambdaPropagatedPosterior(getMode())));\n      m_name += \" with posterior propagation\";\n   }\n}\n\nconst Eigen::VectorXd NormalPrior::fullMu(int n) const\n{\n   if (getSession().getConfig().hasPropagatedPosterior(getMode()))\n   {\n      return mu_pp->col(n);\n   }\n   //else\n   return hyperMu();\n}\n\nconst Eigen::MatrixXd NormalPrior::getLambda(int n) const\n{\n   if (getSession().getConfig().hasPropagatedPosterior(getMode()))\n   {\n      return Eigen::Map<Eigen::MatrixXd>(Lambda_pp->col(n).data(), num_latent(), num_latent());\n   }\n   //else\n   return Lambda;\n}\nvoid NormalPrior::update_prior()\n{\n   std::tie(hyperMu(), Lambda) = CondNormalWishart(num_item(), getUUsum(), getUsum(), mu0, b0, WI, df);\n}\n\n//n is an index of column in U matrix\nvoid  NormalPrior::sample_latent(int n)\n{\n   const auto &mu_u = fullMu(n);\n   const auto &Lambda_u = getLambda(n);\n\n   Eigen::VectorXd &rr = rrs.local();\n   Eigen::MatrixXd &MM = MMs.local();\n\n   rr.setZero();\n   MM.setZero();\n\n   // add pnm\n   data().getMuLambda(model(), m_mode, n, rr, MM);\n\n   // add hyperparams\n   rr.noalias() += Lambda_u * mu_u;\n   MM.noalias() += Lambda_u;\n\n   //Solve system of linear equations for x: MM * x = rr - not exactly correct  because we have random part\n   //Sample from multivariate normal distribution with mean rr and precision matrix MM\n\n   Eigen::LLT<Eigen::MatrixXd> chol;\n   {\n      chol = MM.llt(); // compute the Cholesky decomposition X = L * U\n      if(chol.info() != Eigen::Success)\n      {\n         THROWERROR(\"Cholesky Decomposition failed!\");\n      }\n   }\n\n   chol.matrixL().solveInPlace(rr); // solve for y: y = L^-1 * b\n   rr.noalias() += nrandn(num_latent());\n   chol.matrixU().solveInPlace(rr); // solve for x: x = U^-1 * y\n   \n   U().col(n).noalias() = rr; // rr is equal to x\n}\n\nstd::ostream &NormalPrior::status(std::ostream &os, std::string indent) const\n{\n   os << indent << m_name << std::endl;\n   os << indent << \"  mu: \" <<  hyperMu().transpose() << std::endl;\n   return os;\n}\n", "meta": {"hexsha": "e221eb5a6ec920bff956b06250b7fcaeb686d5bb", "size": 3190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/smurff-cpp/SmurffCpp/Priors/NormalPrior.cpp", "max_stars_repo_name": "msteijaert/smurff", "max_stars_repo_head_hexsha": "e6066d51e1640e9aad0118628ba72c9d662919fb", "max_stars_repo_licenses": ["MIT"], "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/smurff-cpp/SmurffCpp/Priors/NormalPrior.cpp", "max_issues_repo_name": "msteijaert/smurff", "max_issues_repo_head_hexsha": "e6066d51e1640e9aad0118628ba72c9d662919fb", "max_issues_repo_licenses": ["MIT"], "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/smurff-cpp/SmurffCpp/Priors/NormalPrior.cpp", "max_forks_repo_name": "msteijaert/smurff", "max_forks_repo_head_hexsha": "e6066d51e1640e9aad0118628ba72c9d662919fb", "max_forks_repo_licenses": ["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.9349593496, "max_line_length": 131, "alphanum_fraction": 0.6570532915, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028203, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5252076414736806}}
{"text": "#include \"Day16-FlawedFrequencyTransmission.h\"\n\n#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>\n\n__BEGIN_LIBRARIES_DISABLE_WARNINGS\n#include <boost/algorithm/string.hpp>\n\n#include <algorithm>\n#include <array>\n#include <numeric>\n#include <vector>\n#include <sstream>\n__END_LIBRARIES_DISABLE_WARNINGS\n\nnamespace\n{\nconst size_t NUM_ITERATIONS = 100;\nconst size_t PATTERN_OFFSET = 1;\nconst size_t BASE_PATTERN_SIZE = 4;\nconst std::array<int, BASE_PATTERN_SIZE> BASE_PATTERN{0, 1, 0, -1};\n\nconst size_t MULTIPLIER_OF_REAL_SIGNAL = 10'000;\n}\n\nnamespace AdventOfCode\n{\nnamespace Year2019\n{\nnamespace Day16\n{\n\nstd::vector<int> convertToVectorOfDigits(const std::string& s)\n{\n    std::vector<int> intVector;\n\n    for (auto c : s)\n    {\n        intVector.push_back(c - '0');\n    }\n\n    return intVector;\n}\n\nstd::string convertToString(std::vector<int> vec)\n{\n    std::ostringstream oss;\n\n    for (auto num : vec)\n    {\n        oss << num;\n    }\n\n    return oss.str();\n}\n\nstd::vector<int> getRepeatingPattern(size_t patternRepeatLength, size_t patternLength)\n{\n    std::vector<int> repeatingPattern;\n\n    for (size_t i = 0; i < patternLength; ++i)\n    {\n        int patternElement = BASE_PATTERN.at((PATTERN_OFFSET + i) / patternRepeatLength % BASE_PATTERN_SIZE);\n        repeatingPattern.push_back(patternElement);\n    }\n\n    return repeatingPattern;\n}\n\nint multiplyElementwiseAndSummarize(const std::vector<int>& v1, const std::vector<int>& v2)\n{\n    assert(v1.size() == v2.size());\n\n    std::vector<int> result;\n\n    std::transform(v1.cbegin(), v1.cend(), v2.begin(), std::back_inserter(result), std::multiplies<int>());\n\n    return std::accumulate(result.begin(), result.end(), 0);\n}\n\nstd::vector<int> applyPhase(const std::vector<int>& digits)\n{\n    std::vector<int> result;\n\n    for (size_t i = 0; i < digits.size(); ++i)\n    {\n        std::vector<int> repeatingPattern = getRepeatingPattern(i + 1, digits.size());\n\n        int reductionResult = multiplyElementwiseAndSummarize(digits, repeatingPattern);\n\n        result.push_back(std::abs(reductionResult) % 10);\n    }\n\n    return result;\n}\n\nstd::vector<int> applyPhaseToShortSuffix(const std::vector<int>& digits)\n{\n    std::vector<int> result;\n\n    // Calculate suffix sum\n    std::partial_sum(digits.crbegin(), digits.crend(), std::back_inserter(result));\n    std::reverse(result.begin(), result.end());\n\n    for (auto& i : result)\n    {\n        i %= 10;\n    }\n\n    return result;\n}\n\nstd::vector<int> extendToRealSignalRelevantPart(const std::string& signalString)\n{\n    std::vector<int> digits = convertToVectorOfDigits(signalString);\n    std::vector<int> extendedDigits;\n\n    for (size_t i = 0; i < MULTIPLIER_OF_REAL_SIGNAL; ++i)\n    {\n        std::copy(digits.begin(), digits.end(), std::back_inserter(extendedDigits));\n    }\n\n    std::vector<int> relevantDigits;\n    int messageOffset = std::stoi(signalString.substr(0, 7));\n    std::copy(extendedDigits.cbegin() + messageOffset, extendedDigits.cend(), std::back_inserter(relevantDigits));\n\n    return relevantDigits;\n}\n\nstd::string firstEightDigitsOfFinalOutput(const std::string& signalString)\n{\n    std::vector<int> digits = convertToVectorOfDigits(signalString);\n\n    for (size_t i = 0; i < NUM_ITERATIONS; ++i)\n    {\n        digits = applyPhase(digits);\n    }\n\n    std::string digitsAsString = convertToString(digits);\n\n    return digitsAsString.substr(0, 8);\n}\n\nstd::string messageInFinalOutputForRealSignal(const std::string& signalString)\n{\n    std::vector<int> relevantDigits = extendToRealSignalRelevantPart(signalString);\n\n    // Under this assumption, applying a phase becomes a simple prefix sum operation\n    assert(relevantDigits.size() < signalString.size() / 2);\n\n    for (size_t i = 0; i < NUM_ITERATIONS; ++i)\n    {\n        relevantDigits = applyPhaseToShortSuffix(relevantDigits);\n    }\n\n    std::string digitsAsString = convertToString(relevantDigits);\n\n    return digitsAsString.substr(0, 8);\n}\n\n}\n}\n}\n", "meta": {"hexsha": "f41123a47f82f1d94254f726a93fc917d83e1d70", "size": 3940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AdventOfCode2019/Day16-FlawedFrequencyTransmission/Day16-FlawedFrequencyTransmission.cpp", "max_stars_repo_name": "dbartok/advent-of-code-cpp", "max_stars_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AdventOfCode2019/Day16-FlawedFrequencyTransmission/Day16-FlawedFrequencyTransmission.cpp", "max_issues_repo_name": "dbartok/advent-of-code-cpp", "max_issues_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AdventOfCode2019/Day16-FlawedFrequencyTransmission/Day16-FlawedFrequencyTransmission.cpp", "max_forks_repo_name": "dbartok/advent-of-code-cpp", "max_forks_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1717791411, "max_line_length": 114, "alphanum_fraction": 0.6913705584, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5252076361646488}}
{"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_CHOLESKY_INCLUDE\n#define MTL_CHOLESKY_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/recursion/matrix_recursator.hpp>\n#include <boost/numeric/mtl/utility/glas_tag.hpp>\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/operation/dmat_dmat_mult.hpp>\n#include <boost/numeric/mtl/operation/assign_mode.hpp>\n#include <boost/numeric/mtl/matrix/transposed_view.hpp>\n#include <boost/numeric/mtl/recursion/base_case_cast.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace mtl { namespace matrix {\n\nnamespace with_bracket {\n\n    // ============================================================================\n    // Generic Cholesky factorization and operands for Cholesky on with submatrices\n    // ============================================================================\n\t\n    template < typename Matrix > \n    void cholesky_base (Matrix & matrix)\n    {\n\tvampir_trace<5001> tracer;\n\ttypedef typename  Collection<Matrix>::size_type    size_type;\n\tfor (size_type k = 0; k < matrix.num_cols(); k++) {\n\t    matrix[k][k] = sqrt (matrix[k][k]);\n\t    \n\t\tfor (size_type i = k + 1; i < matrix.num_rows(); i++) {\n\t\t    matrix[i][k] /= matrix[k][k];\n\t\t    typename Collection<Matrix>::value_type d = matrix[i][k];\n\n\t\t    for (size_type j = k + 1; j <= i; j++)\n\t\t\tmatrix[i][j] -= d * matrix[j][k];\n\t\t}\n\t}\n    }\n\t\n    \n    template < typename MatrixSW, typename MatrixNW > \n    void tri_solve_base(MatrixSW & SW, const MatrixNW & NW)\n    {\n\tvampir_trace<5002> tracer;\n\ttypedef typename  Collection<MatrixSW>::size_type    size_type;\n\tfor (size_type k = 0; k < NW.num_rows (); k++) {\n\t    \n\t    for (size_type i = 0; i < SW.num_rows (); i++) {\n\t\tSW[i][k] /= NW[k][k];\n\t\ttypename MatrixSW::value_type d = SW[i][k];\n\t\t\n\t\tfor (size_type j = k + 1; j < SW.num_cols (); j++)\n\t\t    SW[i][j] -= d * NW[j][k];\n\t    }\n\t}\n    }\n    \n\n    // Lower(SE) -= SW * SW^T\n    template < typename MatrixSE, typename MatrixSW > \n    void tri_schur_base(MatrixSE & SE, const MatrixSW & SW)\n    {\n\tvampir_trace<5003> tracer;\n\ttypedef typename  Collection<MatrixSE>::size_type    size_type;\n\tfor (size_type k = 0; k < SW.num_cols (); k++)\n\t    \n\t    for (size_type i = 0; i < SE.num_rows (); i++) {\n\t\t    typename MatrixSW::value_type d = SW[i][k];\n\t\t    for (size_type j = 0; j <= i; j++)\n\t\t\tSE[i][j] -= d * SW[j][k];\n\t    }\n    }\n\n\n    template < typename MatrixNE, typename MatrixNW, typename MatrixSW >\n    void schur_update_base(MatrixNE & NE, const MatrixNW & NW, const MatrixSW & SW)\n    {\n\tvampir_trace<5004> tracer;\n\ttypedef typename  Collection<MatrixNE>::size_type    size_type;\n\tfor (size_type k = 0; k < NW.num_cols (); k++) \n\t    for (size_type i = 0; i < NE.num_rows (); i++) {\n\t\ttypename MatrixNW::value_type d = NW[i][k];\n\t\tfor (size_type j = 0; j < NE.num_cols (); j++)\n\t\t    NE[i][j] -= d * SW[j][k];\n\t    }\n    }\n\n\n    // ======================\n    // Corresponding functors\n    // ======================\n    \n    struct cholesky_base_t\n    {\n\ttemplate < typename Matrix > \n\tvoid operator() (Matrix & matrix)\n\t{\n\t    cholesky_base(matrix);\n\t}\n    };\n    \n    struct tri_solve_base_t\n    {\n\ttemplate < typename MatrixSW, typename MatrixNW > \n\tvoid operator() (MatrixSW & SW, const MatrixNW & NW)\n\t{\n\t    tri_solve_base(SW, NW);\n\t}\n    };\n\n    struct tri_schur_base_t\n    {\n\ttemplate < typename MatrixSE, typename MatrixSW > \n\tvoid operator() (MatrixSE & SE, const MatrixSW & SW)\n\t{\n\t    tri_schur_base(SE, SW);\n\t}\n    };\n\n    struct schur_update_base_t\n    {\n\ttemplate < typename MatrixNE, typename MatrixNW, typename MatrixSW >\n\tvoid operator() (MatrixNE & NE, const MatrixNW & NW, const MatrixSW & SW)\n\t{\n\t    schur_update_base(NE, NW, SW);\n\t}\n    };\n\n} // namespace with_bracket\n\n#if 0\nnamespace with_iterator {\n\n    // ============================================================================\n    // Generic Cholesky factorization and operands for Cholesky on with submatrices\n    // ============================================================================\n    // CURRENTLY NOT SUPPORTED -- CAUSES SEGFAULT, e.g. with icc 11.0 in r8536 !!!!\n    // ============================================================================\n\n    template < typename Matrix > \n    void cholesky_base (Matrix& matrix)\n    {\n\tvampir_trace<5001> tracer;\n\ttypedef typename  Collection<Matrix>::size_type    size_type;\n\n\tusing namespace glas::tag; using mtl::traits::range_generator;\n\ttypedef tag::iter::all    all_it;\n\n        typedef typename Collection<Matrix>::value_type                         value_type;\n        typedef typename range_generator<col, Matrix>::type       cur_type;             \n        typedef typename range_generator<all_it, cur_type>::type    iter_type;            \n\n\ttypedef typename range_generator<row, Matrix>::type       rcur_type;\n\ttypedef typename range_generator<all_it, rcur_type>::type   riter_type;   \n\t\n\tsize_type k= 0;\n\tfor (cur_type kb= begin<col>(matrix), kend= end<col>(matrix); kb != kend; ++kb, ++k) {\n\n\t    iter_type ib= begin<all_it>(kb), iend= end<all_it>(kb); \n\t    ib+= k; // points now to matrix[k][k]\n\n\t    value_type root= sqrt (*ib);\n\t    *ib= root;\n\n\t    ++ib; // points now to matrix[k+1][k]\n\t    rcur_type rb= begin<row>(matrix); rb+= k+1; // to row k+1\n\t    for (size_type i= k + 1; ib != iend; ++ib, ++rb, ++i) {\n\t\t*ib = *ib / root;\n\t\ttypename Collection<Matrix>::value_type d = *ib;\n\t\triter_type it1= begin<all_it>(rb);    it1+= k+1;      // matrix[i][k+1]\n\t\triter_type it1end= begin<all_it>(rb); it1end+= i+1;   // matrix[i][i+1]\n\t\titer_type it2= begin<all_it>(kb);     it2+= k+1;      // matrix[k+1][k]\n\t\tfor (; it1 != it1end; ++it1, ++it2)\n\t\t    *it1 = *it1 - d * *it2;\n\t    }\n\t}\n    }\n\n    \n    template < typename MatrixSW, typename MatrixNW > \n    void tri_solve_base(MatrixSW & SW, const MatrixNW & NW)\n    {\n\tvampir_trace<5002> tracer;\n\ttypedef typename  Collection<MatrixSW>::size_type    size_type;\n\n\tusing namespace glas::tag; using mtl::traits::range_generator;\n\ttypedef tag::iter::all        all_it;\n\ttypedef tag::const_iter::all  all_cit;\n\n        typedef typename range_generator<col, MatrixNW>::type       ccur_type;             \n        typedef typename range_generator<all_cit, ccur_type>::type    citer_type;            \n\n\ttypedef typename range_generator<row, MatrixSW>::type       rcur_type;\n\ttypedef typename range_generator<all_it, rcur_type>::type     riter_type;   \n\n\tfor (size_type k = 0; k < NW.num_rows (); k++) \n\t    for (size_type i = 0; i < SW.num_rows (); i++) {\n\n\t\ttypename MatrixSW::value_type d = SW[i][k] /= NW[k][k];\n\n\t\trcur_type sw_i= begin<row>(SW);     sw_i+= i;  // row i\n\t\triter_type it1= begin<all_it>(sw_i);  it1+= k+1; // SW[i][k+1]\n\t\triter_type it1end= end<all_it>(sw_i);    \n\t\n\t\tccur_type nw_k= begin<col>(NW);     nw_k+= k;  // column k\n\t\tciter_type it2= begin<all_cit>(nw_k); it2+= k+1; // NW[k+1][k]\n\n\t\tfor(; it1 != it1end; ++it1, ++it2)\n\t\t    *it1 = *it1 - d * *it2;\n\t    }\n    }\n    \n\n    // Lower(SE) -= SW * SW^T\n    template < typename MatrixSE, typename MatrixSW > \n    void tri_schur_base(MatrixSE & SE, const MatrixSW & SW)\n    {\n\tvampir_trace<5003> tracer;\n\ttypedef typename  Collection<MatrixSE>::size_type    size_type;\n\n\tusing namespace glas::tag; using mtl::traits::range_generator;\n\ttypedef tag::iter::all        all_it;\n\ttypedef tag::const_iter::all  all_cit;\n\n        typedef typename range_generator<col, MatrixSW>::type       ccur_type;             \n        typedef typename range_generator<all_cit, ccur_type>::type    citer_type;            \n\n\ttypedef typename range_generator<row, MatrixSE>::type       rcur_type;\n\ttypedef typename range_generator<all_it, rcur_type>::type     riter_type;   \n\n\tfor (size_type k = 0; k < SW.num_cols (); k++)\n\t    for (size_type i = 0; i < SE.num_rows (); i++) {\n\t\ttypename MatrixSW::value_type d = SW[i][k];\n\n\t\trcur_type se_i= begin<row>(SE);       se_i+= i;      // row i\n\t\triter_type it1= begin<all_it>(se_i);                   // SE[i][0]\n\t\triter_type it1end= begin<all_it>(se_i); it1end+= i+1;  // SE[i][i+i]\n\n\t\tccur_type sw_k= begin<col>(SW);     sw_k+= k;        // column k\n\t\tciter_type it2= begin<all_cit>(sw_k);                  // SW[0][k]\n\n\t\tfor(; it1 != it1end; ++it1, ++it2)\n\t\t    *it1 = *it1 - d * *it2;\n\t    }\n    }\n\n\n    template < typename MatrixNE, typename MatrixNW, typename MatrixSW >\n    void schur_update_base(MatrixNE & NE, const MatrixNW & NW, const MatrixSW & SW)\n    {\n\tvampir_trace<5004> tracer;\n\ttypedef typename  Collection<MatrixNE>::size_type    size_type;\n\n\tusing namespace glas::tag; using mtl::traits::range_generator;\n\ttypedef tag::iter::all        all_it;\n\ttypedef tag::const_iter::all  all_cit;\n\n        typedef typename range_generator<col, MatrixSW>::type       ccur_type;             \n        typedef typename range_generator<all_cit, ccur_type>::type    citer_type;            \n\n\ttypedef typename range_generator<row, MatrixNE>::type       rcur_type;\n\ttypedef typename range_generator<all_it, rcur_type>::type     riter_type;   \n\n\tfor (size_type k = 0; k < NW.num_cols (); k++) \n\t    for (size_type i = 0; i < NE.num_rows (); i++) {\n\t\ttypename MatrixNW::value_type d = NW[i][k];\n#if 0\n\t\trcur_type ne_i= begin<row>(NE);       ne_i+= i;      // row i\n\t\triter_type it1= begin<all_it>(ne_i);                   // NE[i][0]\n\t\triter_type it1end= end<all_it>(ne_i);                  // NE[i][num_col]\n\n\t\tccur_type sw_k= begin<col>(SW);     sw_k+= k;        // column k\n\t\tciter_type it2= begin<all_cit>(sw_k);                  // SW[0][k]\n#endif\n\t\tfor (size_type j = 0; j < NE.num_cols (); j++)\n\t\t    NE[i][j] -= d * SW[j][k];\n\t    }\n    }\n\n\n    // ======================\n    // Corresponding functors\n    // ======================\n    \n    struct cholesky_base_t\n    {\n\ttemplate < typename Matrix > \n\tvoid operator() (Matrix & matrix)\n\t{\n\t    cholesky_base(matrix);\n\t}\n    };\n    \n    struct tri_solve_base_t\n    {\n\ttemplate < typename MatrixSW, typename MatrixNW > \n\tvoid operator() (MatrixSW & SW, const MatrixNW & NW)\n\t{\n\t    tri_solve_base(SW, NW);\n\t}\n    };\n\n    struct tri_schur_base_t\n    {\n\ttemplate < typename MatrixSE, typename MatrixSW > \n\tvoid operator() (MatrixSE & SE, const MatrixSW & SW)\n\t{\n\t    tri_schur_base(SE, SW);\n\t}\n    };\n\n    struct schur_update_base_t\n    {\n\ttemplate < typename MatrixNE, typename MatrixNW, typename MatrixSW >\n\tvoid operator() (MatrixNE & NE, const MatrixNW & NW, const MatrixSW & SW)\n\t{\n\t    schur_update_base(NE, NW, SW);\n\t}\n    };\n\n} // namespace with_iterator\n#endif\n\n\n// ==================================\n// Functor types for Cholesky visitor\n// ==================================\n\n\ntemplate <typename BaseTest, typename CholeskyBase, typename TriSolveBase, typename TriSchur, typename SchurUpdate>\nstruct recursive_cholesky_visitor_t\n{\n    typedef  BaseTest                   base_test;\n\n    template < typename Recursator > \n    bool is_base(const Recursator& recursator) const\n    {\n\treturn base_test()(recursator);\n    }\n\n    template < typename Matrix > \n    void cholesky_base(Matrix & matrix) const\n    {\n\tCholeskyBase()(matrix);\n    }\n\n    template < typename MatrixSW, typename MatrixNW > \n    void tri_solve_base(MatrixSW & SW, const MatrixNW & NW) const\n    {\n\tTriSolveBase()(SW, NW);\n    }\n\n    template < typename MatrixSE, typename MatrixSW > \n    void tri_schur_base(MatrixSE & SE, const MatrixSW & SW) const\n    {\n\tTriSchur()(SE, SW);\n    }\n\n    template < typename MatrixNE, typename MatrixNW, typename MatrixSW >\n    void schur_update_base(MatrixNE & NE, const MatrixNW & NW, const MatrixSW & SW) const\n    {\n\tSchurUpdate()(NE, NW, SW);\n    }\n};\n\n\nnamespace detail {\n\n    // Compute schur update with external multiplication; must have Assign == minus_mult_assign_t !!!\n    template <typename MatrixMult>\n    struct mult_schur_update_t\n    {\n\ttemplate < typename MatrixNE, typename MatrixNW, typename MatrixSW >\n\tvoid operator()(MatrixNE & NE, const MatrixNW & NW, const MatrixSW & SW)\n\t{\n\t    transposed_view<MatrixSW> trans_sw(const_cast<MatrixSW&>(SW)); \n\t    MatrixMult()(NW, trans_sw, NE);\n\t}\n    };\n\n} // detail\n\n\nnamespace with_bracket {\n    typedef recursive_cholesky_visitor_t<recursion::bound_test_static<64>, cholesky_base_t, tri_solve_base_t, \n\t\t\t\t\t tri_schur_base_t, schur_update_base_t > \n               recursive_cholesky_base_visitor_t;\n}\n\n#if 0\nnamespace with_iterator {\n    typedef recursive_cholesky_visitor_t<recursion::bound_test_static<64>, \n\t\t\t\t\t cholesky_base_t, tri_solve_base_t, tri_schur_base_t, schur_update_base_t>\n               recursive_cholesky_base_visitor_t;\n}\n#endif\n\ntypedef with_bracket::recursive_cholesky_base_visitor_t                    recursive_cholesky_default_visitor_t;\n\n\n\n\n\n\nnamespace with_recursator {\n\n    template <typename Recursator, typename Visitor>\n    void schur_update(Recursator E, Recursator W, Recursator N, Visitor vis)\n    {\n\tvampir_trace<5005> tracer;\n\tusing namespace recursion;\n\n\tif (E.is_empty() || W.is_empty() || N.is_empty())\n\t    return;\n\n\tif (vis.is_base(E)) {\n\t    typedef typename Visitor::base_test  base_test;\n\t    typedef typename base_case_matrix<typename Recursator::matrix_type, base_test>::type matrix_type;\n\t    \n\t    matrix_type  base_E(base_case_cast<base_test>(E.get_value())), \n\t\t         base_W(base_case_cast<base_test>(W.get_value())),\n\t\t         base_N(base_case_cast<base_test>(N.get_value()));\n\t    vis.schur_update_base(base_E, base_W, base_N);\n\t} else{\n\t    schur_update(     E.north_east(),W.north_west()     ,N.south_west()     , vis);\n\t    schur_update(     E.north_east(),     W.north_east(),     N.south_east(), vis);\n    \n\t    schur_update(E.north_west()     ,     W.north_east(),     N.north_east(), vis);\n\t    schur_update(E.north_west()     ,W.north_west()     ,N.north_west()     , vis);\n    \n\t    schur_update(E.south_west()     ,W.south_west()     ,N.north_west()     , vis);\n\t    schur_update(E.south_west()     ,     W.south_east(),     N.north_east(), vis);\n    \n\t    schur_update(     E.south_east(),     W.south_east(),     N.south_east(), vis);\n\t    schur_update(     E.south_east(),W.south_west()     ,N.south_west()     , vis);\n\t}\n    }\n\n\n    template <typename Recursator, typename Visitor>\n    void tri_solve(Recursator S, Recursator N, Visitor vis)\n    {\n\tusing namespace recursion;\n\tvampir_trace<5006> tracer;\n\n        if (S.is_empty())\n\t    return;\n\n        if (vis.is_base(S)) {   \n\t    typedef typename Visitor::base_test  base_test;\n\t    typedef typename base_case_matrix<typename Recursator::matrix_type, base_test>::type matrix_type;\n\t    \n\t    matrix_type  base_S(base_case_cast<base_test>(S.get_value())), \n\t\t         base_N(base_case_cast<base_test>(N.get_value()));\n\n\t    vis.tri_solve_base(base_S, base_N);\n        } else{\n     \n\t    tri_solve(S.north_west()     ,N.north_west(), vis);\n\t    schur_update(  S.north_east(),S.north_west()     ,N.south_west(), vis);\n\t    tri_solve(     S.north_east(),     N.south_east(), vis);\n\t    tri_solve(S.south_west()     ,N.north_west()     , vis);\n\t    schur_update(  S.south_east(),S.south_west()     ,N.south_west(), vis);\n\t    tri_solve(     S.south_east(),     N.south_east(), vis);\n\t}\n    }\n\n\n    template <typename Recursator, typename Visitor>\n    void tri_schur(Recursator E, Recursator W, Visitor vis)\n    { \n\tusing namespace recursion;\n\tvampir_trace<5007> tracer;\n\n        if (E.is_empty() || W.is_empty())\n\t    return;\n\n        if (vis.is_base(W)) {\n\t    typedef typename Visitor::base_test  base_test;\n\t    typedef typename base_case_matrix<typename Recursator::matrix_type, base_test>::type matrix_type;\n\t    \n\t    matrix_type  base_E(base_case_cast<base_test>(E.get_value())), \n               \t\t base_W(base_case_cast<base_test>(W.get_value()));\n\t    vis.tri_schur_base(base_E, base_W);\n        } else{ \n         \n\t    schur_update(E.south_west(),     W.south_west(),    W.north_west(), vis);\n\t    schur_update(E.south_west(),     W.south_east(),    W.north_east(), vis);\n\t    tri_schur(   E.south_east()     ,     W.south_east(), vis);\n\t    tri_schur(   E.south_east()     ,W.south_west()     , vis);\n\t    tri_schur(        E.north_west(),     W.north_east(), vis);\n\t    tri_schur(        E.north_west(),W.north_west()     , vis);\n        }\n    }\n\n\n    template <typename Recursator, typename Visitor>\n    void cholesky(Recursator recursator, Visitor vis)\n    {\n\tusing namespace recursion;\n\tvampir_trace<5008> tracer;\n\n        if (recursator.is_empty())\n\t    return;\n\n        if (vis.is_base (recursator)){    \n\t    typedef typename Visitor::base_test  base_test;\n\t    typedef typename base_case_matrix<typename Recursator::matrix_type, base_test>::type matrix_type;\n\t    \n\t    matrix_type  base_matrix(base_case_cast<base_test>(recursator.get_value()));\n\t    vis.cholesky_base (base_matrix);      \n        } else {\n\t    cholesky(recursator.north_west(), vis);\n\t    tri_solve(    recursator.south_west(),       recursator.north_west(), vis);\n\t    tri_schur(    recursator.south_east(), recursator.south_west(), vis);\n\t    cholesky(     recursator.south_east(), vis);\n        }\n    }\n        \n} // namespace with_recursator\n\n\n\ntemplate <typename Backup= with_bracket::cholesky_base_t>\nstruct recursive_cholesky_t\n{\n    template <typename Matrix>\n    void operator()(Matrix& matrix)\n    {\n\t(*this)(matrix, recursive_cholesky_default_visitor_t());\n    }\n\n    template <typename Matrix, typename Visitor>\n    void operator()(Matrix& matrix, Visitor vis)\n    {\n\tapply(matrix, vis, typename mtl::traits::category<Matrix>::type());\n    }   \n \nprivate:\n    // If the matrix is not sub-divisible then take backup function\n    template <typename Matrix, typename Visitor>\n    void apply(Matrix& matrix, Visitor, tag::universe)\n    {\n\tBackup()(matrix);\n    }\n\n    // Only if matrix is sub-divisible, otherwise backup\n    template <typename Matrix, typename Visitor>\n    void apply(Matrix& matrix, Visitor vis, tag::qsub_divisible)\n    {\n\tmatrix::recursator<Matrix>  recursator(matrix);\n\twith_recursator::cholesky(recursator, vis);\n    }\n};\n\n\ntemplate <typename Matrix, typename Visitor>\ninline void recursive_cholesky(Matrix& matrix, Visitor vis)\n{\n    recursive_cholesky_t<>()(matrix, vis);\n}\n\ntemplate <typename Matrix>\ninline void recursive_cholesky(Matrix& matrix)\n{\n    recursive_cholesky(matrix, recursive_cholesky_default_visitor_t());\n}\n\n\n\n\n\ntemplate <typename Matrix>\nvoid fill_matrix_for_cholesky(Matrix& matrix)\n{\n    vampir_trace<5008> tracer;\n    typedef typename Collection<Matrix>::size_type   size_type;\n    typedef typename Collection<Matrix>::value_type  value_type;\n\n    value_type   x= 1.0; \n    for (size_type i= 0; i < num_rows(matrix); i++) \n       for (size_type j= 0; j <= i; j++)\n\t   if (i != j) {\n\t       matrix[i][j]= x; matrix[j][i]= x; \n\t       x+= 1.0; \n\t   }\n  \n    for (size_type i= 0; i < num_rows(matrix); i++) {\n\tvalue_type rowsum= 0.0;\n\tfor (size_type j=0; j<matrix.num_cols(); j++)\n\t    if (i != j)\n\t\trowsum += matrix[i][j]; \n\tmatrix[i][i]= rowsum * 2;\n    }       \n}\n\n\n}} // namespace mtl::matrix\n\n\n\n\n#endif // MTL_CHOLESKY_INCLUDE\n", "meta": {"hexsha": "ce11965eaf7022afabe8074c1e1f81a684184ce6", "size": 19420, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/cholesky.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/cholesky.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/cholesky.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": 31.525974026, "max_line_length": 115, "alphanum_fraction": 0.6209062822, "num_tokens": 5395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.525207630483307}}
{"text": "#define DEBUG 1\n/**\n * File    : C.cpp\n * Author  : Kazune Takahashi\n * Created : 6/17/2020, 5:57:05 PM\n * Powered by Visual Studio Code\n */\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n// ----- boost -----\n#include <boost/integer/common_factor_rt.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/rational.hpp>\n// ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::integer::gcd; // for C++14 or for cpp_int\nusing boost::integer::lcm; // for C++14 or for cpp_int\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n// ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n// constexpr ll MOD{998'244'353LL}; // be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nbool ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\ntemplate <typename T>\nbool ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\n// ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(Mint const &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(Mint const &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(Mint const &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator/=(Mint const &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }\n  bool operator<(Mint const &a) const { return x < a.x; }\n  bool operator<=(Mint const &a) const { return x <= a.x; }\n  bool operator>(Mint const &a) const { return x > a.x; }\n  bool operator>=(Mint const &a) const { return x >= a.x; }\n  bool operator==(Mint const &a) const { return x == a.x; }\n  bool operator!=(Mint const &a) const { return !(*this == a); }\n  Mint power(ll N) const\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N / 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }\ntemplate <ll MOD>\nMint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }\n// ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i{2LL}; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i{1LL}; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\n// ----- for C++17 -----\ntemplate <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>\nsize_t popcount(T x) { return bitset<64>(x).count(); }\nsize_t popcount(string const &S) { return bitset<200010>{S}.count(); }\n// ----- Infty -----\ntemplate <typename T>\nconstexpr T Infty() { return numeric_limits<T>::max(); }\ntemplate <typename T>\nconstexpr T mInfty() { return numeric_limits<T>::min(); }\n// ----- frequently used constexpr -----\n// constexpr double epsilon{1e-10};\n// constexpr ll infty{1'000'000'000'000'010LL}; // or\n// constexpr int infty{1'000'000'010};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\n// ----- Solve -----\n\nclass Solve\n{\n\npublic:\n  Solve()\n  {\n  }\n\n  void flush()\n  {\n  }\n\nprivate:\n};\n\n// ----- main() -----\n\n/*\nint main()\n{\n  Solve solve;\n  solve.flush();\n}\n*/\n\nint main()\n{\n  int N;\n  cin >> N;\n  map<string, int> M;\n  for (auto i{0}; i < N; ++i)\n  {\n    string S;\n    cin >> S;\n    M[S];\n    M[S]++;\n  }\n  int maxi{0};\n  for (auto const &e : M)\n  {\n    ch_max(maxi, e.second);\n  }\n  for (auto const &e : M)\n  {\n    if (e.second == maxi)\n    {\n      cout << e.first << endl;\n    }\n  }\n}\n", "meta": {"hexsha": "4fb9d3f23b824a3aaa2c9416356cd5d70b6e9ce5", "size": 6092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/0303_ABC155/C.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2020/0303_ABC155/C.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/0303_ABC155/C.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 22.479704797, "max_line_length": 82, "alphanum_fraction": 0.5774786605, "num_tokens": 1917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5252076302971522}}
{"text": "#pragma once\n\n#include <polyfem/Problem.hpp>\n#include <polyfem/ProblemWithSolution.hpp>\n\n#include <vector>\n#include <Eigen/Dense>\n\nnamespace polyfem\n{\n\tclass ElasticProblem: public Problem\n\t{\n\tpublic:\n\t\tElasticProblem(const std::string &name);\n\n\t\tvoid rhs(const std::string &formulation, const Eigen::MatrixXd &pts,const double t, Eigen::MatrixXd &val) const override;\n\t\tbool is_rhs_zero() const override { return true; }\n\n\t\tvoid bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts,const double t, Eigen::MatrixXd &val) const override;\n\n\t\tbool has_exact_sol() const override { return false; }\n\t\tbool is_scalar() const override { return false; }\n\t};\n\n\tclass TorsionElasticProblem: public Problem\n\t{\n\tpublic:\n\t\tTorsionElasticProblem(const std::string &name);\n\n\t\tvoid rhs(const std::string &formulation, const Eigen::MatrixXd &pts,const double t, Eigen::MatrixXd &val) const override;\n\t\tbool is_rhs_zero() const override { return true; }\n\n\t\tvoid bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts,const double t, Eigen::MatrixXd &val) const override;\n\n\t\tbool has_exact_sol() const override { return false; }\n\t\tbool is_scalar() const override { return false; }\n\t\tbool is_linear_in_time() const override { return false; }\n\n\t\tvoid set_parameters(const json &params) override;\n\tprivate:\n\t\tdouble n_turns_ = 0.5;\n\t\tint coordiante_0_ = 0;\n\t\tint coordiante_1_ = 1;\n\t\tRowVectorNd trans_;\n\t};\n\n\tclass ElasticProblemZeroBC: public Problem\n\t{\n\tpublic:\n\t\tElasticProblemZeroBC(const std::string &name);\n\t\tbool is_rhs_zero() const override { return false; }\n\n\n\t\tvoid rhs(const std::string &formulation, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\t\tvoid bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\n\t\tbool has_exact_sol() const override { return false; }\n\t\tbool is_scalar() const override { return false; }\n\t};\n\n\n\tclass ElasticProblemExact: public ProblemWithSolution\n\t{\n\tpublic:\n\t\tElasticProblemExact(const std::string &name);\n\n\t\tVectorNd eval_fun(const VectorNd &pt) const override;\n\t\tAutodiffGradPt eval_fun(const AutodiffGradPt &pt) const override;\n\t\tAutodiffHessianPt eval_fun(const AutodiffHessianPt &pt) const override;\n\n\t\tbool is_scalar() const override { return false; }\n\t};\n\n\n\tclass CompressionElasticProblemExact: public ProblemWithSolution\n\t{\n\tpublic:\n\t\tCompressionElasticProblemExact(const std::string &name);\n\n\t\tVectorNd eval_fun(const VectorNd &pt) const override;\n\t\tAutodiffGradPt eval_fun(const AutodiffGradPt &pt) const override;\n\t\tAutodiffHessianPt eval_fun(const AutodiffHessianPt &pt) const override;\n\n\t\tbool is_scalar() const override { return false; }\n\t};\n\n\n\n\tclass QuadraticElasticProblemExact: public ProblemWithSolution\n\t{\n\tpublic:\n\t\tQuadraticElasticProblemExact(const std::string &name);\n\n\t\tVectorNd eval_fun(const VectorNd &pt) const override;\n\t\tAutodiffGradPt eval_fun(const AutodiffGradPt &pt) const override;\n\t\tAutodiffHessianPt eval_fun(const AutodiffHessianPt &pt) const override;\n\n\t\tbool is_scalar() const override { return false; }\n\t};\n\n\n\tclass LinearElasticProblemExact: public ProblemWithSolution\n\t{\n\tpublic:\n\t\tLinearElasticProblemExact(const std::string &name);\n\n\t\tVectorNd eval_fun(const VectorNd &pt) const override;\n\t\tAutodiffGradPt eval_fun(const AutodiffGradPt &pt) const override;\n\t\tAutodiffHessianPt eval_fun(const AutodiffHessianPt &pt) const override;\n\n\t\tbool is_scalar() const override { return false; }\n\t};\n\n\tclass GravityProblem: public Problem\n\t{\n\tpublic:\n\t\tGravityProblem(const std::string &name);\n\n\t\tvoid rhs(const std::string &formulation, const Eigen::MatrixXd &pts,const double t, Eigen::MatrixXd &val) const override;\n\t\tbool is_rhs_zero() const override { return false; }\n\n\t\tvoid bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts,const double t, Eigen::MatrixXd &val) const override;\n\t\tvoid velocity_bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\t\tvoid acceleration_bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\n\t\tvoid initial_solution(const Eigen::MatrixXd &pts, Eigen::MatrixXd &val) const override;\n\t\tvoid initial_velocity(const Eigen::MatrixXd &pts, Eigen::MatrixXd &val) const override;\n\t\tvoid initial_acceleration(const Eigen::MatrixXd &pts, Eigen::MatrixXd &val) const override;\n\n\t\tbool has_exact_sol() const override { return false; }\n\t\tbool is_scalar() const override { return false; }\n\t\tbool is_time_dependent() const override { return true; }\n\t};\n}\n\n", "meta": {"hexsha": "3619ff00e4366b82e2535d83d9c7665d675c76b7", "size": 4876, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/problem/ElasticProblem.hpp", "max_stars_repo_name": "ldXiao/polyfem", "max_stars_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problem/ElasticProblem.hpp", "max_issues_repo_name": "ldXiao/polyfem", "max_issues_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problem/ElasticProblem.hpp", "max_forks_repo_name": "ldXiao/polyfem", "max_forks_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_forks_repo_licenses": ["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.8529411765, "max_line_length": 184, "alphanum_fraction": 0.757588187, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619306896955, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5252076273634035}}
{"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//! OPENOR_INTERFACE_FILE(openOR_core)\n//****************************************************************************\n/**\n* @file\n* @author Christian Winne\n* @ingroup openOR_core\n*/\n\n#ifndef openOR_core_math_matrixfunctions_hpp\n#define openOR_core_math_matrixfunctions_hpp\n\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/void.hpp>\n#include <boost/type_traits/is_same.hpp>\n\n#include <openOR/Utility/conceptcheck.hpp>\n#include <openOR/Math/constants.hpp>\n#include <openOR/Math/utilities.hpp>\n#include <openOR/Math/matrix.hpp>\n#include <openOR/Math/matrixsetaxis.hpp>\n#include <openOR/Math/vector.hpp>\n#include <openOR/Math/vectorfunctions.hpp>\n#include <openOR/Math/create.hpp>\n\n#include <openOR/Math/determinant.hpp>\n#include <openOR/Math/detail/inverse_impl.hpp>\n\nnamespace openOR {\n\tnamespace Math {\n\n\t\t/**\n\t\t* @brief Returns the x-axis vector of a 3x3 or 4x4 matrix.\n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::ConstMatrix<Type>)),\n\t\t\t(typename MatrixTraits<Type>::Vector3Type))\n\t\t\txAxis(const Type& mat) {\n\t\t\t\treturn create<typename MatrixTraits<Type>::Vector3Type>(get<0, 0>(mat), get<1, 0>(mat), get<2, 0>(mat));\n\t\t}\n\n\n\t\t/**\n\t\t* @brief Returns the y-axis vector of a 3x3 or 4x4 matrix.\n\t\t* @ingroup openOR_core\n\t\t*/      \n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::ConstMatrix<Type>)),\n\t\t\t(typename MatrixTraits<Type>::Vector3Type))\n\t\t\tyAxis(const Type& mat) {\n\t\t\t\treturn create<typename MatrixTraits<Type>::Vector3Type>(get<0, 1>(mat), get<1, 1>(mat), get<2, 1>(mat));\n\t\t}\n\n\n\t\t/**\n\t\t* @brief Returns the z-axis vector of a 3x3 or 4x4 matrix.\n\t\t* @ingroup openOR_core\n\t\t*/      \n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::ConstMatrix<Type>)),\n\t\t\t(typename MatrixTraits<Type>::Vector3Type))\n\t\t\tzAxis(const Type& mat) {\n\t\t\t\treturn create<typename MatrixTraits<Type>::Vector3Type>(get<0, 2>(mat), get<1, 2>(mat), get<2, 2>(mat));\n\t\t}\n\n\n\t\t/**\n\t\t* @brief Returns the translation vector of a 4x4 matrix.\n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::ConstMatrix<Type>)),\n\t\t\t(typename MatrixTraits<Type>::Vector3Type))\n\t\t\ttranslation(const Type& mat) {\n\t\t\t\treturn create<typename MatrixTraits<Type>::Vector3Type>(get<0, 3>(mat), get<1, 3>(mat), get<2, 3>(mat));\n\t\t}\n\n\n\t\tnamespace Impl {\n\t\t\ttemplate <class Type, class Vec, int I, int Count>\n\t\t\tstruct SetScaleHelp {\n\t\t\t\tvoid operator()(Type& mat, const Vec& vec) const {\n\t\t\t\t\tget<I, I>(mat) = get<I>(vec);\n\t\t\t\t\tSetScaleHelp < Type, Vec, I + 1, Count > ()(mat, vec);\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\ttemplate <class Type, class Vec, int Count>\n\t\t\tstruct SetScaleHelp<Type, Vec, Count, Count> {\n\t\t\t\tvoid operator()(Type& mat, const Vec& vec) const {}\n\t\t\t};\n\t\t}\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type, class Vec>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>))\n\t\t\t((Concept::ConstVector<Vec>)),\n\t\t\t(void))\n\t\t\tsetScale(Type& mat, const Vec& vec) {\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::equal_to<typename MatrixTraits<Type>::RowDimension, typename MatrixTraits<Type>::ColDimension>));\n\t\t\t\tImpl::SetScaleHelp<Type, Vec, 0, MatrixTraits<Type>::RowDimension::value>()(mat, vec);\n\t\t}\n\n\n\t\tnamespace Impl {\n\t\t\ttemplate <class Type, class Vec, int J, int Count, int Row>\n\t\t\tstruct GetRowHelp {\n\t\t\t\tvoid operator()(Vec& vec, const Type& mat) const {\n\t\t\t\t\tget<J>(vec) = get<Row, J>(mat);\n\t\t\t\t\tGetRowHelp < Type, Vec, J + 1, Count, Row > ()(vec, mat);\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\ttemplate <class Type, class Vec, int Count, int Row>\n\t\t\tstruct GetRowHelp<Type, Vec, Count, Count, Row> {\n\t\t\t\tvoid operator()(Vec& vec, const Type& mat) const {}\n\t\t\t};\n\n\n\t\t\ttemplate <class Type, class Vec, int I, int Count, int Col>\n\t\t\tstruct GetColHelp {\n\t\t\t\tvoid operator()(Vec& vec, const Type& mat) const {\n\t\t\t\t\tget<I>(vec) = get<I, Col>(mat);\n\t\t\t\t\tGetColHelp < Type, Vec, I + 1, Count, Col > ()(vec, mat);\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\ttemplate <class Type, class Vec, int Count, int Col>\n\t\t\tstruct GetColHelp<Type, Vec, Count, Count, Col> {\n\t\t\t\tvoid operator()(Vec& vec, const Type& mat) const {}\n\t\t\t};\n\t\t}\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <int I, class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::ConstMatrix<Type>))\n\t\t\t((Concept::Vector<typename MatrixTraits<Type>::RowVectorType>)),\n\t\t\t(typename MatrixTraits<Type>::RowVectorType))\n\t\t\trow(const Type& mat) {\n\t\t\t\ttypedef typename MatrixTraits<Type>::RowVectorType VectorType;\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::less<boost::mpl::int_<I>, typename MatrixTraits<Type>::RowDimension>));\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::equal_to<typename VectorTraits<VectorType>::Dimension, typename MatrixTraits<Type>::RowDimension>));\n\n\t\t\t\tVectorType vec;\n\t\t\t\tImpl::GetRowHelp<Type, VectorType, 0, MatrixTraits<Type>::ColDimension::value, I>()(vec, mat);\n\t\t\t\treturn vec;\n\t\t}\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <int J, class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::ConstMatrix<Type>))\n\t\t\t((Concept::Vector<typename MatrixTraits<Type>::ColVectorType>)),\n\t\t\t(typename MatrixTraits<Type>::ColVectorType))\n\t\t\tcol(const Type& mat) {\n\t\t\t\ttypedef typename MatrixTraits<Type>::ColVectorType VectorType;\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::less<boost::mpl::int_<J>, typename MatrixTraits<Type>::ColDimension>));\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::equal_to<typename VectorTraits<VectorType>::Dimension, typename MatrixTraits<Type>::ColDimension>));\n\n\t\t\t\tVectorType vec;\n\t\t\t\tImpl::GetColHelp<Type, VectorType, 0, MatrixTraits<Type>::RowDimension::value, J>()(vec, mat);\n\t\t\t\treturn vec;\n\t\t}\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(void))\n\t\t\tsetRotationX(Type& mat, typename ScalarTraits<typename MatrixTraits<Type>::ValueType>::RealType angle) {\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::greater_equal<typename MatrixTraits<Type>::RowDimension, boost::mpl::int_<3> >));\n\t\t\t\tget<0, 0>(mat) = 1;\n\t\t\t\tget<0, 1>(mat) = 0;\n\t\t\t\tget<0, 2>(mat) = 0;\n\t\t\t\tget<1, 0>(mat) = 0;\n\t\t\t\tget<1, 1>(mat) = cos(angle);\n\t\t\t\tget<1, 2>(mat) = -sin(angle);\n\t\t\t\tget<2, 0>(mat) = 0;\n\t\t\t\tget<2, 1>(mat) = sin(angle);\n\t\t\t\tget<2, 2>(mat) = cos(angle);\n\t\t}\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(void))\n\t\t\tsetRotationY(Type& mat, typename ScalarTraits<typename MatrixTraits<Type>::ValueType>::RealType angle) {\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::greater_equal<typename MatrixTraits<Type>::RowDimension, boost::mpl::int_<3> >));\n\t\t\t\tget<0, 0>(mat) = cos(angle);\n\t\t\t\tget<0, 1>(mat) = 0;\n\t\t\t\tget<0, 2>(mat) = sin(angle);\n\t\t\t\tget<1, 0>(mat) = 0;\n\t\t\t\tget<1, 1>(mat) = 1;\n\t\t\t\tget<1, 2>(mat) = 0;\n\t\t\t\tget<2, 0>(mat) = -sin(angle);\n\t\t\t\tget<2, 1>(mat) = 0;\n\t\t\t\tget<2, 2>(mat) = cos(angle);\n\t\t}\n\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(void))\n\t\t\tsetRotationZ(Type& mat, typename ScalarTraits<typename MatrixTraits<Type>::ValueType>::RealType angle) {\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::greater_equal<typename MatrixTraits<Type>::RowDimension, boost::mpl::int_<3> >));\n\t\t\t\tget<0, 0>(mat) = cos(angle);\n\t\t\t\tget<0, 1>(mat) = -sin(angle);\n\t\t\t\tget<0, 2>(mat) = 0;\n\t\t\t\tget<1, 0>(mat) = sin(angle);\n\t\t\t\tget<1, 1>(mat) = cos(angle);\n\t\t\t\tget<1, 2>(mat) = 0;\n\t\t\t\tget<2, 0>(mat) = 0;\n\t\t\t\tget<2, 1>(mat) = 0;\n\t\t\t\tget<2, 2>(mat) = 1;\n\t\t}\n\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(void))\n\t\t\trotateX(Type& mat, typename ScalarTraits<typename MatrixTraits<Type>::ValueType>::RealType angle) {\n\t\t\t\tType rotMat = MatrixTraits<Type>::IDENTITY;\n\t\t\t\tsetRotationX(rotMat, angle);\n\t\t\t\tmat = Math::prod(rotMat, mat);\n\t\t}\n\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(void))\n\t\t\trotateY(Type& mat, typename ScalarTraits<typename MatrixTraits<Type>::ValueType>::RealType angle) {\n\t\t\t\tType rotMat = MatrixTraits<Type>::IDENTITY;\n\t\t\t\tsetRotationY(rotMat, angle);\n\t\t\t\tmat = Math::prod(rotMat, mat);\n\t\t}\n\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(void))\n\t\t\trotateZ(Type& mat, typename ScalarTraits<typename MatrixTraits<Type>::ValueType>::RealType angle) {\n\t\t\t\tType rotMat = MatrixTraits<Type>::IDENTITY;\n\t\t\t\tsetRotationZ(rotMat, angle);\n\t\t\t\tmat = Math::prod(rotMat, mat);\n\t\t}\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::ConstMatrix<Type>)),\n\t\t\t(typename MatrixTraits<Type>::Matrix33Type))\n\t\t\trotationAsMatrix(const Type& mat) {\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::greater_equal<typename MatrixTraits<Type>::RowDimension, boost::mpl::int_<3> >));\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::greater_equal<typename MatrixTraits<Type>::ColDimension, boost::mpl::int_<3> >));\n\n\t\t\t\ttypename MatrixTraits<Type>::Matrix33Type matResult;\n\t\t\t\tget<0, 0>(matResult) = get<0, 0>(mat);\n\t\t\t\tget<0, 1>(matResult) = get<0, 1>(mat);\n\t\t\t\tget<0, 2>(matResult) = get<0, 2>(mat);\n\t\t\t\tget<1, 0>(matResult) = get<1, 0>(mat);\n\t\t\t\tget<1, 1>(matResult) = get<1, 1>(mat);\n\t\t\t\tget<1, 2>(matResult) = get<1, 2>(mat);\n\t\t\t\tget<2, 0>(matResult) = get<2, 0>(mat);\n\t\t\t\tget<2, 1>(matResult) = get<2, 1>(mat);\n\t\t\t\tget<2, 2>(matResult) = get<2, 2>(mat);\n\t\t\t\treturn matResult;\n\t\t}\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type, class Type2>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>))\n\t\t\t((Concept::ConstMatrix<Type2>)),\n\t\t\t(void))\n\t\t\tsetRotation(Type& mat, const Type2& matRotation) {\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::greater_equal<typename MatrixTraits<Type>::RowDimension, boost::mpl::int_<3> >));\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::greater_equal<typename MatrixTraits<Type>::ColDimension, boost::mpl::int_<3> >));\n\t\t\t\tget<0, 0>(mat) = get<0, 0>(matRotation);\n\t\t\t\tget<0, 1>(mat) = get<0, 1>(matRotation);\n\t\t\t\tget<0, 2>(mat) = get<0, 2>(matRotation);\n\t\t\t\tget<1, 0>(mat) = get<1, 0>(matRotation);\n\t\t\t\tget<1, 1>(mat) = get<1, 1>(matRotation);\n\t\t\t\tget<1, 2>(mat) = get<1, 2>(matRotation);\n\t\t\t\tget<2, 0>(mat) = get<2, 0>(matRotation);\n\t\t\t\tget<2, 1>(mat) = get<2, 1>(matRotation);\n\t\t\t\tget<2, 2>(mat) = get<2, 2>(matRotation);\n\t\t}\n\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Mat, class Vec>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Mat>))\n\t\t\t((Concept::ConstVector<Vec>)),\n\t\t\t(void))\n\t\t\tsetRotation(Mat& mat, const Vec& vecAxis, typename ScalarTraits<typename MatrixTraits<Mat>::ValueType>::RealType angle) {\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::greater_equal<typename MatrixTraits<Mat>::RowDimension, boost::mpl::int_<3> >));\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::greater_equal<typename MatrixTraits<Mat>::RowDimension, boost::mpl::int_<3> >));\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::greater_equal<typename VectorTraits<Vec>::Dimension, boost::mpl::int_<3> >));\n\n\t\t\t\t//assert(std::abs(norm(vecAxis) - 1.0) <= 0.001);\n\n\t\t\t\tsetXAxis(mat, rotate3(create<Vec>(1, 0, 0), vecAxis, angle));\n\t\t\t\tsetYAxis(mat, rotate3(create<Vec>(0, 1, 0), vecAxis, angle));\n\t\t\t\tsetZAxis(mat, rotate3(create<Vec>(0, 0, 1), vecAxis, angle));\n\t\t}\n\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::ConstMatrix<Type>)),\n\t\t\t(boost::math::quaternion<typename ScalarTraits<typename MatrixTraits<Type>::ValueType>::RealType>))\n\t\t\trotationAsQuaternions(const Type& mat) {\n\n\t\t\t\ttypedef typename ScalarTraits<typename MatrixTraits<Type>::ValueType>::RealType RealType;\n\t\t\t\ttypedef boost::math::quaternion<RealType> Quaternions;\n\t\t\t\tQuaternions q;\n\n\t\t\t\tRealType tr = get<0, 0>(mat) + get<1, 1>(mat) + get<2, 2>(mat);\n\t\t\t\tRealType s;\n\t\t\t\tRealType w, x, y, z;\n\n\t\t\t\tif (tr > 0.0)\n\t\t\t\t{\n\t\t\t\t\ts = sqrt(tr + static_cast<RealType>(1));     \n\t\t\t\t\tw = s * static_cast<RealType>(0.5);\n\t\t\t\t\ts = static_cast<RealType>(0.5) / s;\n\t\t\t\t\tx = static_cast<RealType>((get<2, 1>(mat) - get<1, 2>(mat)) * s);\n\t\t\t\t\ty = static_cast<RealType>((get<0, 2>(mat) - get<2, 0>(mat)) * s);\n\t\t\t\t\tz = static_cast<RealType>((get<1, 0>(mat) - get<0, 1>(mat)) * s);\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t{\n\t\t\t\t\tif (get<0, 0>(mat) > get<1, 1>(mat) && get<0, 0>(mat) > get<2, 2>(mat))\n\t\t\t\t\t{\n\t\t\t\t\t\tRealType s = 2.0 * sqrt(1.0 + get<0, 0>(mat) - get<1, 1>(mat) - get<2, 2>(mat));\n\t\t\t\t\t\tw = (get<2, 1>(mat) - get<1, 2>(mat)) / s;\n\t\t\t\t\t\tx = 0.25 * s;\n\t\t\t\t\t\ty = (get<1, 0>(mat) + get<0, 1>(mat)) / s;\n\t\t\t\t\t\tz = (get<0, 2>(mat) + get<2, 0>(mat)) / s;\n\n\t\t\t\t\t} else if (get<1, 1>(mat) > get<2, 2>(mat)) {\n\t\t\t\t\t\tRealType s = 2.0 * sqrt(1.0 + get<1, 1>(mat) - get<0, 0>(mat) - get<2, 2>(mat));\n\t\t\t\t\t\tw = (get<0, 2>(mat) - get<2, 0>(mat)) / s;\n\t\t\t\t\t\tx = (get<1, 0>(mat) + get<0, 1>(mat)) / s;\n\t\t\t\t\t\ty = 0.25 * s;\n\t\t\t\t\t\tz = (get<2, 1>(mat) + get<1, 2>(mat)) / s;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tRealType s = 2.0 * sqrt(1.0 + get<2, 2>(mat) - get<0, 0>(mat) - get<1, 1>(mat));\n\t\t\t\t\t\tw = (get<1, 0>(mat) - get<0, 1>(mat)) / s;\n\t\t\t\t\t\tx = (get<0, 2>(mat) + get<2, 0>(mat)) / s;\n\t\t\t\t\t\ty = (get<2, 1>(mat) + get<1, 2>(mat)) / s;\n\t\t\t\t\t\tz = 0.25 * s;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn Quaternions(w, x, y, z);\n\t\t}\n\n\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::ConstMatrix<Type>)),\n\t\t\t(void))\n\t\t\trotationAsEulerAngles(const Type& mat, double& heading, double& attitude, double& bank) \n\t\t{\n\t\t\ttypedef typename ScalarTraits<typename MatrixTraits<Type>::ValueType>::RealType RealType;\n\t\t\t// Assuming the angles are in radians.\n\t\t\tif (get<1, 0>(mat) > static_cast<RealType>(0.998)) { // singularity at north pole\n\t\t\t\theading = atan2(get<0, 2>(mat), get<2, 2>(mat));\n\t\t\t\tattitude = PI / 2;\n\t\t\t\tbank = 0;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (get<1, 0>(mat) < static_cast<RealType>(-0.998)) { // singularity at south pole\n\t\t\t\theading = atan2(get<0, 2>(mat), get<2, 2>(mat));\n\t\t\t\tattitude = -PI / 2;\n\t\t\t\tbank = 0;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\theading = atan2(-get<2, 0>(mat), get<0, 0>(mat));\n\t\t\tbank = atan2(-get<1, 2>(mat), get<1, 1>(mat));\n\t\t\tattitude = asin(get<1, 0>(mat));\n\t\t}\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(void))\n\t\t\tsetRotation(Type& mat, const boost::math::quaternion<typename ScalarTraits<typename MatrixTraits<Type>::ValueType>::RealType>& quaternion) {\n\n\t\t\t\ttypedef typename ScalarTraits<typename MatrixTraits<Type>::ValueType>::RealType RealType;\n\t\t\t\ttypedef boost::math::quaternion<RealType> Quaternions;\n\n\t\t\t\tRealType s = static_cast<RealType>(2) / static_cast<RealType>(square(quaternion.R_component_1()) + \n\t\t\t\t\tsquare(quaternion.R_component_2()) + \n\t\t\t\t\tsquare(quaternion.R_component_3()) + \n\t\t\t\t\tsquare(quaternion.R_component_4()));\n\n\t\t\t\tRealType xs = quaternion.R_component_2() * s;\n\t\t\t\tRealType ys = quaternion.R_component_3() * s;\n\t\t\t\tRealType zs = quaternion.R_component_4() * s;\n\n\t\t\t\tRealType wx = quaternion.R_component_1() * xs;\n\t\t\t\tRealType wy = quaternion.R_component_1() * ys;\n\t\t\t\tRealType wz = quaternion.R_component_1() * zs;\n\n\t\t\t\tRealType xx = quaternion.R_component_2() * xs;\n\t\t\t\tRealType xy = quaternion.R_component_2() * ys;\n\t\t\t\tRealType xz = quaternion.R_component_2() * zs;\n\n\t\t\t\tRealType yy = quaternion.R_component_3() * ys;\n\t\t\t\tRealType yz = quaternion.R_component_3() * zs;\n\n\t\t\t\tRealType zz = quaternion.R_component_4() * zs;\n\n\t\t\t\tget<0, 0>(mat) = static_cast<RealType>(1) - (yy + zz);\n\t\t\t\tget<1, 0>(mat) = xy + wz;\n\t\t\t\tget<2, 0>(mat) = xz - wy;\n\n\t\t\t\tget<0, 1>(mat) = xy - wz;\n\t\t\t\tget<1, 1>(mat) = static_cast<RealType>(1) - (xx + zz);\n\t\t\t\tget<2, 1>(mat) = yz + wx;\n\n\t\t\t\tget<0, 2>(mat) = xz + wy;\n\t\t\t\tget<1, 2>(mat) = yz - wx;\n\t\t\t\tget<2, 2>(mat) = static_cast<RealType>(1) - (xx + yy);\n\t\t}\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(void))\n\t\t\tsetRotationAxis(Type& mat, const Math::Vector3d& axis, const double& angle) {\n\t\t\t\ttypename MatrixTraits<Type>::ValueType c = cos(angle), s = sin(angle);\n\t\t\t\ttypename MatrixTraits<Type>::ValueType cn = 1.0 - cos(angle);\n\t\t\t\tdouble nx = axis(0), ny = axis(1), nz = axis(2);\n\t\t\t\tdouble nxny = nx * ny, nxnz = nx * nz, nynz = ny * nz;\n\t\t\t\tdouble nxs = nx * s, nys = ny * s, nzs = nz * s;\n\n\t\t\t\tget<0, 0>(mat) = nx * nx * cn + c;\n\t\t\t\tget<0, 1>(mat) = nxny * cn - nzs;\n\t\t\t\tget<0, 2>(mat) = nxnz * cn + nys;\n\n\t\t\t\tget<1, 0>(mat) = nxny * cn + nzs;\n\t\t\t\tget<1, 1>(mat) = ny * ny * cn + c;\n\t\t\t\tget<1, 2>(mat) = nynz * cn - nxs;\n\n\t\t\t\tget<2, 0>(mat) = nxnz * cn - nys;\n\t\t\t\tget<2, 1>(mat) = nynz * cn + nxs;\n\t\t\t\tget<2, 2>(mat) = nz * nz * cn + c;\n\t\t}\n\n\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(void))\n\t\t\tsetRotationStationaryZYX(Type& mat, \n\t\t\tconst typename MatrixTraits<Type>::ValueType& radZ,\n\t\t\tconst typename MatrixTraits<Type>::ValueType& radY,\n\t\t\tconst typename MatrixTraits<Type>::ValueType& radX) \n\t\t{\n\t\t\t// angles must be in radians\n\t\t\tdouble cx = cos(radX);\n\t\t\tdouble sx = sin(radX);\n\t\t\tdouble cy = cos(radY);\n\t\t\tdouble sy = sin(radY);\n\t\t\tdouble cz = cos(radZ);\n\t\t\tdouble sz = sin(radZ);\n\n\t\t\t// describes the rotation with euler angles around stationary axes\n\t\t\t// is equal to R = Rx * Ry * Rz\n\n\t\t\tget<0, 0>(mat) = cy * cz;\n\t\t\tget<0, 1>(mat) = -cy * sz;\n\t\t\tget<0, 2>(mat) = -sy;\n\t\t\tget<1, 0>(mat) = -sx * sy * cz + cx * sz;\n\t\t\tget<1, 1>(mat) = sx * sy * sz + cx * cz;\n\t\t\tget<1, 2>(mat) = -sx * cy;\n\t\t\tget<2, 0>(mat) = cx * sy * cz + sx * sz;\n\t\t\tget<2, 1>(mat) = -cx * sy * sz + sx * cz;\n\t\t\tget<2, 2>(mat) = cx * cy;\n\t\t}\n\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::ConstMatrix<Type>)),\n\t\t\t(void))\n\t\t\trotationAsStationaryZYX(const Type& mat, double& radZ, double& radY, double& radX) \n\t\t{\n\t\t\ttypedef typename ScalarTraits<typename MatrixTraits<Type>::ValueType>::RealType RealType;\n\n\t\t\tdouble sx, sy, sz, cx, cy, cz, rx, ry, rz;\n\n\t\t\try = -asin(get<0, 2>(mat));\n\t\t\tcy = cos(ry);\n\n\t\t\tif (abs(cy) > 0.00005) {\n\t\t\t\tsx = -get<1, 2>(mat) / cy;\n\t\t\t\tcx = get<2, 2>(mat) / cy;\n\n\t\t\t\tsz = -get<0, 1>(mat) / cy;\n\t\t\t\tcz = get<0, 0>(mat) / cy;\n\n\t\t\t\trx = atan2(sx, cx);\n\t\t\t\trz = atan2(sz, cz);\n\t\t\t} else {\n\t\t\t\trx = 0;\n\n\t\t\t\tsz = get<1, 0>(mat);\n\t\t\t\tcz = get<2, 0>(mat);\n\t\t\t\trz = atan2(sz, cz);\n\t\t\t}\n\n\t\t\tradZ = rz; radY = ry; radX = rx;\n\t\t}\n\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(void))\n\t\t\tsetRotation(Type& mat, \n\t\t\tconst typename MatrixTraits<Type>::ValueType& heading,\n\t\t\tconst typename MatrixTraits<Type>::ValueType& attitude,\n\t\t\tconst typename MatrixTraits<Type>::ValueType& bank) \n\t\t{\n\t\t\t// angles must be in radians\n\t\t\tdouble ch = cos(heading);\n\t\t\tdouble sh = sin(heading);\n\t\t\tdouble ca = cos(attitude);\n\t\t\tdouble sa = sin(attitude);\n\t\t\tdouble cb = cos(bank);\n\t\t\tdouble sb = sin(bank);\n\n\t\t\tget<0, 0>(mat) = ch * ca;\n\t\t\tget<0, 1>(mat) = sh * sb - ch * sa * cb;\n\t\t\tget<0, 2>(mat) = ch * sa * sb + sh * cb;\n\t\t\tget<1, 0>(mat) = sa;\n\t\t\tget<1, 1>(mat) = ca * cb;\n\t\t\tget<1, 2>(mat) = -ca * sb;\n\t\t\tget<2, 0>(mat) = -sh * ca;\n\t\t\tget<2, 1>(mat) = sh * sa * cb + ch * sb;\n\t\t\tget<2, 2>(mat) = -sh * sa * sb + ch * cb;\n\t\t}\n\n\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(void))\n\t\t\tsetRotationYprDeg(Type& mat, \n\t\t\tconst typename MatrixTraits<Type>::ValueType& degYaw,\n\t\t\tconst typename MatrixTraits<Type>::ValueType& degPitch,\n\t\t\tconst typename MatrixTraits<Type>::ValueType& degRoll) \n\t\t{\n\t\t\ttypename MatrixTraits<Type>::ValueType cy, sy;\n\t\t\ttypename MatrixTraits<Type>::ValueType cp = cos(degPitch * M_PI / 180.0), sp = sin(degPitch * M_PI / 180.0);\n\t\t\ttypename MatrixTraits<Type>::ValueType cr = cos(degRoll * M_PI / 180.0), sr = sin(degRoll * M_PI / 180.0);\n\n\t\t\tcy = cos(degYaw * M_PI / 180.0); sy = sin(degYaw * M_PI / 180.0);\n\n\t\t\t// correct cos\n\t\t\tif (degYaw == 90.0 || degYaw == 270.0) cy = 0.0;\n\t\t\tif (degPitch == 90.0 || degPitch == 270.0) cp = 0.0;\n\t\t\tif (degRoll == 90.0 || degRoll == 270.0) cr = 0.0;\n\n\t\t\t// correct sin\n\t\t\tif (degYaw == 0.0 || degYaw == 180.0) sy = 0.0;\n\t\t\tif (degPitch == 0.0 || degPitch == 180.0) sp = 0.0;\n\t\t\tif (degRoll == 0.0 || degRoll == 180.0) sr = 0.0;\n\n\t\t\tget<0, 0>(mat) = cr * cp;\n\t\t\tget<0, 1>(mat) = cr * sp * sy - sr * cy;\n\t\t\tget<0, 2>(mat) = cr * sp * cy + sr * sy;\n\t\t\tget<1, 0>(mat) = sr * cp;\n\t\t\tget<1, 1>(mat) = sr * sp * sy + cr * cy;\n\t\t\tget<1, 2>(mat) = sr * sp * cy - cr * sy;\n\t\t\tget<2, 0>(mat) = -sp;\n\t\t\tget<2, 1>(mat) = cp * sy;\n\t\t\tget<2, 2>(mat) = cp * cy;\n\n\t\t\t//get<0, 0>(mat) = cp * cy;\n\t\t\t//get<0, 1>(mat) = cp * sy;\n\t\t\t//get<0, 2>(mat) = -sp;\n\t\t\t//get<1, 0>(mat) = sr * sp * cy - sr * cy;\n\t\t\t//get<1, 1>(mat) = sr * sp * sy + cr * cy;\n\t\t\t//get<1, 2>(mat) = sr * cp;\n\t\t\t//get<2, 0>(mat) = cr * sp * cy + sr * sy;\n\t\t\t//get<2, 1>(mat) = cr * sp * sy - sr * cy;\n\t\t\t//get<2, 2>(mat) = cr * cp;\n\t\t}\n\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::ConstMatrix<Type>)),\n\t\t\t(void))\n\t\t\trotationAsYpr(const Type& mat, double& radYaw, double& radPitch, double& radRoll) \n\t\t{\n\t\t\ttypedef typename ScalarTraits<typename MatrixTraits<Type>::ValueType>::RealType RealType;\n\n\t\t\tdouble sy, sp, sr, cy, cp, cr, ry, rp, rr;\n\n\t\t\trp = -asin(get<2, 0>(mat));\n\t\t\tcp = cos(rp);\n\t\t\tif (abs(cp) > 0.0005) {\n\t\t\t\tsy = get<2, 1>(mat) / cp;\n\t\t\t\tcy = get<2, 2>(mat) / cp;\n\n\t\t\t\tsr = get<1, 0>(mat) / cp;\n\t\t\t\tcr = get<0, 0>(mat) / cp;\n\n\t\t\t\try = atan2(sy, cy);\n\t\t\t\trr = atan2(sr, cr);\n\t\t\t} else {\n\t\t\t\tcy = get<0, 1>(mat);\n\t\t\t\tsy = get<1, 1>(mat);\n\n\t\t\t\trr = M_PI * -0.5;\n\t\t\t\try = atan2(sy, cy);\n\t\t\t}\n\n\t\t\tradYaw = ry; radPitch = rp; radRoll = rr;\n\t\t}\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate<class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(Type))\n\t\t\torthoInverse(const Type& mat) {\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::equal_to<typename MatrixTraits<Type>::RowDimension, typename MatrixTraits<Type>::ColDimension>));\n\t\t\t\t//assert(isHomogeneous(mat));\n\t\t\t\tType matResult;\n\t\t\t\tget<0, 0>(matResult) = get<0, 0>(mat);\n\t\t\t\tget<0, 1>(matResult) = get<1, 0>(mat);\n\t\t\t\tget<0, 2>(matResult) = get<2, 0>(mat);\n\t\t\t\tget<1, 0>(matResult) = get<0, 1>(mat);\n\t\t\t\tget<1, 1>(matResult) = get<1, 1>(mat);\n\t\t\t\tget<1, 2>(matResult) = get<2, 1>(mat);\n\t\t\t\tget<2, 0>(matResult) = get<0, 2>(mat);\n\t\t\t\tget<2, 1>(matResult) = get<1, 2>(mat);\n\t\t\t\tget<2, 2>(matResult) = get<2, 2>(mat);\n\t\t\t\tget<3, 0>(matResult) = 0;\n\t\t\t\tget<3, 1>(matResult) = 0;\n\t\t\t\tget<3, 2>(matResult) = 0;\n\t\t\t\tget<3, 3>(matResult) = 1;\n\t\t\t\tget<0, 3>(matResult) = -(get<0, 0>(mat) * get<0, 3>(mat) + get<1, 0>(mat) * get<1, 3>(mat) + get<2, 0>(mat) * get<2, 3>(mat));\n\t\t\t\tget<1, 3>(matResult) = -(get<0, 1>(mat) * get<0, 3>(mat) + get<1, 1>(mat) * get<1, 3>(mat) + get<2, 1>(mat) * get<2, 3>(mat));\n\t\t\t\tget<2, 3>(matResult) = -(get<0, 2>(mat) * get<0, 3>(mat) + get<1, 2>(mat) * get<1, 3>(mat) + get<2, 2>(mat) * get<2, 3>(mat));\n\t\t\t\treturn matResult;\n\t\t}\n\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(Type&))\n\t\t\torthoInvert(Type& mat) {\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::equal_to<typename MatrixTraits<Type>::RowDimension, typename MatrixTraits<Type>::ColDimension>));\n\t\t\t\tmat = orthoInverse(mat);\n\t\t\t\treturn mat;\n\t\t}      \n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(Type))\n\t\t\tinverse(const Type& mat) {\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::equal_to<typename MatrixTraits<Type>::RowDimension, typename MatrixTraits<Type>::ColDimension>));\n\t\t\t\treturn Impl::Inverse<Type, MatrixTraits<Type>::RowDimension::value>::get(mat);\n\t\t}\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate<class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(void))\n\t\t\tinvert(Type& mat) {\n\t\t\t\tmat = inverse(mat);\n\t\t}\n\n\n\t\tnamespace Impl {\n\t\t\ttemplate <class Mat, class MatSrc, int I, int J>\n\t\t\tstruct TransposeOp {\n\t\t\t\tinline void operator()(Mat& mat, const MatSrc& matSrc) const {\n\t\t\t\t\tMath::get<I, J>(mat) = Math::get<J, I>(matSrc);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate<class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(Type))\n\t\t\ttransposed(const Type& mat) {\n\t\t\t\ttypedef typename MatrixTraits<Type>::RowDimension RowDimension;\n\t\t\t\ttypedef typename MatrixTraits<Type>::ColDimension ColDimension;\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::equal_to<RowDimension, ColDimension>));\n\t\t\t\tType matTransposed;\n\t\t\t\tImpl::MatrixCompileTimeIterator<Type, 0, RowDimension::value, 0, ColDimension::value>().template apply<Impl::TransposeOp, Type>(matTransposed, mat);\n\t\t\t\treturn matTransposed;\n\t\t}\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate<class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(Type&))\n\t\t\ttranspose(Type& mat) {\n\t\t\t\tBOOST_MPL_ASSERT((boost::mpl::equal_to<typename MatrixTraits<Type>::RowDimension, typename MatrixTraits<Type>::ColDimension>));\n\t\t\t\tmat = transposed(mat);\n\t\t\t\treturn mat;\n\t\t}      \n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core_math\n\t\t*/\n\t\ttemplate<class Type, class Vec>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::ConstMatrix<Type>))\n\t\t\t((Concept::ConstVector<Vec>))\n\t\t\t((Concept::Vector<typename MatrixTraits<Type>::Vector3Type>)),\n\t\t\t(typename MatrixTraits<Type>::Vector3Type))\n\t\t\tprod44x3(const Type& mat, const Vec& vec) {\n\t\t\t\ttypename MatrixTraits<Type>::Vector3Type result;\n\t\t\t\tget<0>(result) = get<0, 0>(mat) * get<0>(vec) + get<0, 1>(mat) * get<1>(vec) + get<0, 2>(mat) * get<2>(vec) + get<0, 3>(mat);\n\t\t\t\tget<1>(result) = get<1, 0>(mat) * get<0>(vec) + get<1, 1>(mat) * get<1>(vec) + get<1, 2>(mat) * get<2>(vec) + get<1, 3>(mat);\n\t\t\t\tget<2>(result) = get<2, 0>(mat) * get<0>(vec) + get<2, 1>(mat) * get<1>(vec) + get<2, 2>(mat) * get<2>(vec) + get<2, 3>(mat);\n\t\t\t\treturn result;\n\t\t}\n\n\t\t/**\n\t\t* @brief \n\t\t* @ingroup openOR_core_math\n\t\t*/\n\t\ttemplate<class Type, class Vec>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::ConstMatrix<Type>))\n\t\t\t((Concept::ConstVector<Vec>))\n\t\t\t((Concept::Vector<typename MatrixTraits<Type>::Vector2Type>)),\n\t\t\t(typename MatrixTraits<Type>::Vector2Type))\n\t\t\tprod33x2(const Type& mat, const Vec& vec) {\n\t\t\t\ttypename MatrixTraits<Type>::Vector2Type result;\n\t\t\t\tget<0>(result) = get<0, 0>(mat) * get<0>(vec) + get<0, 1>(mat) * get<1>(vec) + get<0, 2>(mat);\n\t\t\t\tget<1>(result) = get<1, 0>(mat) * get<0>(vec) + get<1, 1>(mat) * get<1>(vec) + get<1, 2>(mat);\n\t\t\t\treturn result;\n\t\t}\n\n\n\t\ttemplate <class Type>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>)),\n\t\t\t(void))\n\t\t\tmakeHomogeneous(Type& mat, int unmodifiedAxis = 2) // 0: xAxis; 1: yAxis; 2: zAxis \n\t\t{\n\t\t\tget<3, 0>(mat) = 0;\n\t\t\tget<3, 1>(mat) = 0;\n\t\t\tget<3, 2>(mat) = 0;\n\t\t\tget<3, 3>(mat) = 1;\n\t\t\ttypename MatrixTraits<Type>::Vector3Type vecXAxis = xAxis(mat);\n\t\t\ttypename MatrixTraits<Type>::Vector3Type vecYAxis = yAxis(mat);\n\t\t\ttypename MatrixTraits<Type>::Vector3Type vecZAxis = zAxis(mat);\n\n\t\t\tswitch (unmodifiedAxis)\n\t\t\t{\n\t\t\tcase 0:                \n\t\t\t\tnormalize(vecXAxis);\n\t\t\t\tvecZAxis = cross(vecXAxis, vecYAxis);\n\t\t\t\tnormalize(vecZAxis);\n\t\t\t\tvecYAxis = cross(vecZAxis, vecXAxis);\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tnormalize(vecYAxis);\n\t\t\t\tvecZAxis = cross(vecXAxis, vecYAxis);\n\t\t\t\tnormalize(vecZAxis);\n\t\t\t\tvecXAxis = cross(vecYAxis, vecZAxis);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tnormalize(vecZAxis);\n\t\t\t\tvecXAxis = cross(vecYAxis, vecZAxis);\n\t\t\t\tnormalize(vecXAxis);\n\t\t\t\tvecYAxis = cross(vecZAxis, vecXAxis);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsetXAxis(mat, vecXAxis);\n\t\t\tsetYAxis(mat, vecYAxis);\n\t\t\tsetZAxis(mat, vecZAxis);\n\t\t}\n\n\n\t}\n}\n\n\n#endif\n", "meta": {"hexsha": "1f32d9f34e4ff09e4873ee1805dc695cb2a0a2a1", "size": 28299, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/include/openOR/Math/matrixfunctions.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/matrixfunctions.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/matrixfunctions.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": 29.946031746, "max_line_length": 152, "alphanum_fraction": 0.6033428743, "num_tokens": 9824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5252067297718938}}
{"text": "\n// BLAS level 2\n\n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <iostream>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include \"utils.h\" \n\nnamespace ublas = boost::numeric::ublas;\nnamespace blas = boost::numeric::bindings::blas;\n\nusing std::cout;\nusing std::endl; \n\ntypedef ublas::vector<double> vct_t;\ntypedef ublas::matrix<double, ublas::row_major> rm_t;\ntypedef ublas::matrix<double, ublas::column_major> cm_t;\n\nint main() {\n\n  cout << endl; \n\n  vct_t vx (2);\n  vct_t vy (4); \n\n  // row major matrix\n  rm_t rm (2, 4);\n  init_m (rm, const_val<double> (0)); \n  print_m (rm, \"row major matrix m\"); \n  cout << endl; \n\n  vx(0) = 1.; \n  vy(1) = 1.; \n  print_v (vx, \"vx\"); \n  cout << endl; \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // m += x y^T\n  blas::ger (1.0, vx, vy, rm); \n  print_m (rm, \"m += x y^T\"); \n  cout << endl << endl; \n\n  init_m (rm, const_val<double> (1)); \n  print_m (rm, \"m\"); \n  cout << endl; \n\n  blas::set (1., vx);\n  blas::set (1., vy);\n  print_v (vx, \"vx\"); \n  cout << endl; \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // m += 2 x y^T\n  blas::ger (2., vx, vy, rm); \n  print_m (rm, \"m += 2 x y^T\"); \n  cout << endl << endl; \n\n  init_v (vx, iplus1());\n  init_v (vy, iplus1());\n  print_v (vx, \"vx\"); \n  cout << endl; \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // m += x y^T\n  blas::ger ( 1.0, vx, vy, rm); \n  print_m (rm, \"m += x y^T\"); \n  cout << endl << endl; \n\n  // column major matrix\n  cm_t cm (2, 4);\n  init_m (cm, const_val<double> (0)); \n  print_m (cm, \"column major matrix m\"); \n  cout << endl; \n\n  vx(0) = 1.; \n  vy(1) = 1.; \n  print_v (vx, \"vx\"); \n  cout << endl; \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // m += x y^T\n  blas::ger ( 1.0, vx, vy, cm); \n  print_m (cm, \"m += x y^T\"); \n  cout << endl << endl; \n\n  init_m (cm, const_val<double> (1)); \n  print_m (cm, \"m\"); \n  cout << endl; \n\n  blas::set (1., vx);\n  blas::set (1., vy);\n  print_v (vx, \"vx\"); \n  cout << endl; \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // m += 2 x y^T\n  blas::ger (2., vx, vy, cm); \n  print_m (cm, \"m += 2 x y^T\"); \n  cout << endl << endl; \n\n  init_v (vx, iplus1());\n  init_v (vy, iplus1());\n  print_v (vx, \"vx\"); \n  cout << endl; \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // m += x y^T\n  blas::ger (1.0, vx, vy, cm); \n  print_m (cm, \"m += x y^T\"); \n  cout << endl << endl; \n\n}\n", "meta": {"hexsha": "0c7b64808447f2bdfe00a34b79a162ed6460a938", "size": 2460, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_matr2ger.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/atlas/ublas_matr2ger.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/atlas/ublas_matr2ger.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": 20.0, "max_line_length": 56, "alphanum_fraction": 0.5414634146, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.5252067297718936}}
{"text": "/**\n * @file boundarywave_test.cc\n * @brief NPDE homework \"BoundaryWave\" code\n * @author Philipp Lindenberger\n * @date 03.04.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include <memory>\n#include <utility>\n// Eigen includes\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n// Lehrfem++ includes\n#include <lf/assemble/assemble.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include \"../boundarywave.h\"\n\nnamespace BoundaryWave::test {\n\nauto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\nconst lf::io::GmshReader reader(std::move(mesh_factory),\n                                CURRENT_SOURCE_DIR \"/../../meshes/simple.msh\");\nauto mesh_p = reader.mesh();\n\nTEST(BoundaryWave, buildM) {\n  auto fe_space_p =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  lf::assemble::COOMatrix M_coo = buildM(fe_space_p);\n\n  Eigen::MatrixXd M = M_coo.makeDense();\n\n  // std::cout << M;\n  double eps = 1.0e-5;\n  Eigen::Matrix<double, 5, 5> reference_M;\n\n  reference_M << 0.666667, 0.166667, 0, 0.166667, 0, 0.166667, 0.666667,\n      0.166667, 0, 0, 0, 0.166667, 0.666667, 0.166667, 0, 0.166667, 0, 0.166667,\n      0.666667, 0, 0, 0, 0, 0, 0;\n  ASSERT_EQ(reference_M.size(), M.size());\n  ASSERT_NEAR((reference_M - M).lpNorm<Eigen::Infinity>(), 0.0, eps);\n}\n\nTEST(BoundaryWave, buildA) {\n  auto fe_space_p =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  lf::assemble::COOMatrix A_coo = buildA(fe_space_p);\n  Eigen::MatrixXd A = A_coo.makeDense();\n\n  double eps = 1.0e-5;\n  Eigen::Matrix<double, 5, 5> reference_A;\n\n  reference_A << 1.33333, 0, 0, 0, -1.33333, 0, 1.66667, 0, 0, -1.66667, 0, 0,\n      2, 0, -2, 0, 0, 0, 1.66667, -1.66667, -1.33333, -1.66667, -2, -1.66667,\n      6.66667;\n  ASSERT_EQ(reference_A.size(), A.size());\n  ASSERT_NEAR((reference_A - A).lpNorm<Eigen::Infinity>(), 0.0, eps);\n}\n\nTEST(BoundaryWave, InterpolateInitialData) {\n  auto fe_space_p =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u0 = [](const Eigen::Vector2d &x) -> double { return x[0]; };\n  auto v0 = [](const Eigen::Vector2d &x) -> double { return x[1]; };\n\n  std::pair<Eigen::VectorXd, Eigen::VectorXd> initialData =\n      interpolateInitialData(fe_space_p, std::move(u0), std::move(v0));\n\n  Eigen::VectorXd reference_u0(5);\n  reference_u0 << 0, 1, 1, 0, 0.5;\n\n  Eigen::VectorXd reference_v0(5);\n  reference_v0 << 0, 0, 1, 1, 0.5;\n\n  double eps = 1.0e-5;\n  ASSERT_TRUE(initialData.first.size() == reference_u0.size());\n  ASSERT_TRUE(initialData.second.size() == reference_v0.size());\n  for (int i = 0; i < 5; i++) {\n    ASSERT_NEAR(reference_u0(i), initialData.first(i), eps);\n    ASSERT_NEAR(reference_v0(i), initialData.second(i), eps);\n  }\n}\n\nTEST(BoundaryWave, solveBoundaryWave) {\n  auto fe_space_p =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto u0 = [](const Eigen::Vector2d &x) -> double { return x[0]; };\n  auto v0 = [](const Eigen::Vector2d &x) -> double { return x[1]; };\n\n  Eigen::VectorXd discrete_solution =\n      solveBoundaryWave(fe_space_p, u0, v0, 1.0, 100);\n\n  Eigen::VectorXd reference_solution(5);\n\n  reference_solution << 0.584002, 0.767904, 1.23746, 1.41064, 0.982673;\n\n  double eps = 1.0e-5;\n  ASSERT_EQ(reference_solution.rows(), discrete_solution.rows());\n  ASSERT_NEAR(\n      (reference_solution - discrete_solution).lpNorm<Eigen::Infinity>(), 0.0,\n      eps);\n}\n}  // namespace BoundaryWave::test\n", "meta": {"hexsha": "0ddf96d6346a0d59388332bde0f347f68c59ba4f", "size": 3492, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/BoundaryWave/templates/test/boundarywave_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/BoundaryWave/templates/test/boundarywave_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/BoundaryWave/templates/test/boundarywave_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": 31.1785714286, "max_line_length": 80, "alphanum_fraction": 0.662371134, "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5252067247323424}}
{"text": "/*\n * Copyright 2020 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\n#include <Eigen/Dense>\n#include <localization_error_monitor/node.hpp>\n\nLocalizationErrorMonitor::LocalizationErrorMonitor()\n{\n  pnh_.param<double>(\"scale\", scale_, 3);\n  pnh_.param<double>(\"error_ellipse_size\", error_ellipse_size_, 1.0);\n  pnh_.param<double>(\"warn_ellipse_size\", warn_ellipse_size_, 0.8);\n\n  pose_with_cov_sub_ =\n    pnh_.subscribe(\"input/pose_with_cov\", 1, &LocalizationErrorMonitor::onPoseWithCovariance, this);\n  ellipse_marker_pub_ = pnh_.advertise<visualization_msgs::Marker>(\"debug/ellipse_marker\", 1, true);\n\n  updater_.setHardwareID(\"localization_error_monitor\");\n  updater_.add(\n    \"localization_accuracy\",\n    boost::bind(&LocalizationErrorMonitor::checkLocalizationAccuracy, this, _1));\n\n  timer_ = pnh_.createTimer(ros::Duration(0.1), &LocalizationErrorMonitor::onTimer, this);\n}\n\nvoid LocalizationErrorMonitor::onTimer(const ros::TimerEvent & event) { updater_.force_update(); }\n\nvoid LocalizationErrorMonitor::checkLocalizationAccuracy(\n  diagnostic_updater::DiagnosticStatusWrapper & stat)\n{\n  stat.add(\"localization_accuracy\", ellipse_.long_radius);\n  int8_t diag_level = diagnostic_msgs::DiagnosticStatus::OK;\n  std::string diag_message = \"ellipse size is within the expected range\";\n  if (warn_ellipse_size_ <= ellipse_.long_radius) {\n    diag_level = diagnostic_msgs::DiagnosticStatus::WARN;\n    diag_message = \"ellipse size is too large\";\n  }\n  if (error_ellipse_size_ <= ellipse_.long_radius) {\n    diag_level = diagnostic_msgs::DiagnosticStatus::ERROR;\n    diag_message = \"ellipse size is over the expected range\";\n  }\n  stat.summary(diag_level, diag_message);\n}\n\nvisualization_msgs::Marker LocalizationErrorMonitor::createEllipseMarker(\n  const Ellipse & ellipse, const geometry_msgs::PoseWithCovarianceStamped & pose_with_cov)\n{\n  tf2::Quaternion quat;\n  quat.setEuler(0, 0, ellipse.yaw);\n\n  const double ellipse_long_radius = std::min(ellipse.long_radius, 30.0);\n  const double ellipse_short_radius = std::min(ellipse.short_radius, 30.0);\n  visualization_msgs::Marker marker;\n  marker.header = pose_with_cov.header;\n  marker.header.stamp = ros::Time();\n  marker.ns = \"error_ellipse\";\n  marker.id = 0;\n  marker.type = visualization_msgs::Marker::SPHERE;\n  marker.action = visualization_msgs::Marker::ADD;\n  marker.pose = pose_with_cov.pose.pose;\n  marker.pose.orientation = tf2::toMsg(quat);\n  marker.scale.x =  ellipse_long_radius * 2;\n  marker.scale.y = ellipse_short_radius * 2;\n  marker.scale.z = 0.01;\n  marker.color.a = 0.1;\n  marker.color.r = 0.0;\n  marker.color.g = 0.0;\n  marker.color.b = 1.0;\n  return marker;\n}\n\nvoid LocalizationErrorMonitor::onPoseWithCovariance(\n  const geometry_msgs::PoseWithCovarianceStamped::ConstPtr & input_msg)\n{\n  // create xy covariance (2x2 matrix)\n  // input geometry_msgs::PoseWithCovariance containe 6x6 matrix\n  Eigen::Matrix2d xy_covariance;\n  const auto cov = input_msg->pose.covariance;\n  xy_covariance(0, 0) = cov[0 * 6 + 0];\n  xy_covariance(0, 1) = cov[0 * 6 + 1];\n  xy_covariance(1, 0) = cov[1 * 6 + 0];\n  xy_covariance(1, 1) = cov[1 * 6 + 1];\n\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> eigensolver(xy_covariance);\n\n  // eigen values and vectors are sorted in ascending order\n  ellipse_.long_radius = scale_ * std::sqrt(eigensolver.eigenvalues()(1));\n  ellipse_.short_radius = scale_ * std::sqrt(eigensolver.eigenvalues()(0));\n\n  // principal component vector\n  const Eigen::Vector2d pc_vector = eigensolver.eigenvectors().col(1);\n  ellipse_.yaw = std::atan2(pc_vector.y(), pc_vector.x());\n\n  const auto ellipse_marker = createEllipseMarker(ellipse_, *input_msg);\n  ellipse_marker_pub_.publish(ellipse_marker);\n}\n", "meta": {"hexsha": "1dff015134d4b339212bbd0d820bc6278f8ee0ec", "size": 4231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "localization/localization_diagnostics/localization_error_monitor/src/node.cpp", "max_stars_repo_name": "hamlinzheng/AutowareArchitectureProposal.iv", "max_stars_repo_head_hexsha": "8a1343019aca3a648754fa50e6cab72b98db2df5", "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": "localization/localization_diagnostics/localization_error_monitor/src/node.cpp", "max_issues_repo_name": "hamlinzheng/AutowareArchitectureProposal.iv", "max_issues_repo_head_hexsha": "8a1343019aca3a648754fa50e6cab72b98db2df5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-08-09T14:15:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T07:56:14.000Z", "max_forks_repo_path": "localization/localization_diagnostics/localization_error_monitor/src/node.cpp", "max_forks_repo_name": "hamlinzheng/AutowareArchitectureProposal.iv", "max_forks_repo_head_hexsha": "8a1343019aca3a648754fa50e6cab72b98db2df5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-09T01:24:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-09T01:24:13.000Z", "avg_line_length": 38.8165137615, "max_line_length": 100, "alphanum_fraction": 0.7485228078, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5251932488318481}}
{"text": "#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <boost/range/algorithm.hpp>\n#include <boost/integer/common_factor_rt.hpp>\n#define MAX 100000000\n\nusing namespace std;\n\nint N;\n\nint main()\n{\n    while (cin >> N)\n    {\n        int A[N + 1], B[N];\n        for (int i = 0; i < N + 1; i++)\n        {\n            cin >> A[i];\n        }\n        for (int i = 0; i < N; i++)\n        {\n            cin >> B[i];\n        }\n        long long int sum = 0;\n        for (int i = N; i > 0; i--)\n        {\n            sum += min(A[i], B[i - 1]);\n            B[i - 1] -= min(A[i], B[i - 1]);\n            sum += min(A[i - 1], B[i - 1]);\n            A[i - 1] -= min(A[i - 1], B[i - 1]);\n        }\n        cout << sum << endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "dea1993cfe3d5f17cfa27738e3c78126c2fb14a2", "size": 800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc135_c/Main.cpp", "max_stars_repo_name": "mizo0203/atcoder", "max_stars_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "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": "abc135_c/Main.cpp", "max_issues_repo_name": "mizo0203/atcoder", "max_issues_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "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": "abc135_c/Main.cpp", "max_forks_repo_name": "mizo0203/atcoder", "max_forks_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "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.512195122, "max_line_length": 48, "alphanum_fraction": 0.42, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5251932203428246}}
{"text": "#ifndef BLOCK_TRIDIAGONAL_MATRICE_H_\n#define BLOCK_TRIDIAGONAL_MATRICE_H_\n\n#include \"tensor.hpp\"\n#include <Eigen/Dense>\n\nclass BlockTridiagonalMatrice {\npublic:\n  BlockTridiagonalMatrice(int size_block, int num_block);\n  Eigen::MatrixXd inverse();\n  void setA(const Eigen::Ref<const Eigen::MatrixXd> &block, int index);\n  void setB(const Eigen::Ref<const Eigen::MatrixXd> &block, int index);\n\nprivate:\n  const int sb_, nb_, ndim_;\n  Tensor tA_; // diagonal blocks\n  Tensor tB_; // upper off-diagonal blocks\n};\n\n#endif", "meta": {"hexsha": "c737eb3142507cb8e7a96ea145d946035d602e05", "size": 517, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/block_tridiagonal_matrice.hpp", "max_stars_repo_name": "pan3rock/InvBlockTridiagonalMatrice", "max_stars_repo_head_hexsha": "695d22cf990b9e66141c7d6b1acde5688f333724", "max_stars_repo_licenses": ["MIT"], "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/block_tridiagonal_matrice.hpp", "max_issues_repo_name": "pan3rock/InvBlockTridiagonalMatrice", "max_issues_repo_head_hexsha": "695d22cf990b9e66141c7d6b1acde5688f333724", "max_issues_repo_licenses": ["MIT"], "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/block_tridiagonal_matrice.hpp", "max_forks_repo_name": "pan3rock/InvBlockTridiagonalMatrice", "max_forks_repo_head_hexsha": "695d22cf990b9e66141c7d6b1acde5688f333724", "max_forks_repo_licenses": ["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.85, "max_line_length": 71, "alphanum_fraction": 0.7582205029, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5251932203428245}}
{"text": "#include <ros/ros.h>\n#include <ros/console.h>\n#include <Eigen/Eigen>\n#include <math.h>\n#include <time.h>\n#include <random>\n#include <sys/time.h>\n#include <nav_msgs/Odometry.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/search/impl/kdtree.hpp>\n#include <pcl_conversions/pcl_conversions.h>\n#include <quadrotor_msgs/PositionCommand.h>\n\nusing namespace std;\n\npcl::search::KdTree<pcl::PointXYZ> kdtreeLocalMap;\nvector<int>     pointIdxRadiusSearch;\nvector<float>   pointRadiusSquaredDistance;        \n\nrandom_device rd;\ndefault_random_engine eng(rd());\nuniform_real_distribution<double>  rand_x;\nuniform_real_distribution<double>  rand_y;\nuniform_real_distribution<double>  rand_w;\nuniform_real_distribution<double>  rand_h;\n\nros::Publisher _all_map_pub, _local_map_pub;\nros::Subscriber _map_sub, _odom_sub, _cmd_sub;\n\nvector<double> _state;\npcl::PointXYZ LstMapCenter;\n\nint _obsNum;\ndouble _x_l, _x_h, _y_l, _y_h, _w_l, _w_h, _h_l, _h_h;\ndouble _resolution, _sense_rate, _sensing_range, _field_of_view_vertical;\ndouble _init_x, _init_y, _end_x, _end_y;\n\nbool _is_map_ok   = false;\nbool _is_has_odom = false;\n\nsensor_msgs::PointCloud2 globalMap_pcd, localMap_pcd, localMap_nofloor_pcd;\npcl::PointCloud<pcl::PointXYZ> cloudMap;\n\nvoid RandomMapGeneration()\n{    \n   pcl::PointXYZ pt_random;\n\n   // Generate a random map, with vertical obstacles\n   rand_x = uniform_real_distribution<double>(_x_l, _x_h );\n   rand_y = uniform_real_distribution<double>(_y_l, _y_h );\n   rand_w = uniform_real_distribution<double>(_w_l, _w_h);\n   rand_h = uniform_real_distribution<double>(_h_l, _h_h);\n\n   for(int i = 0; i < _obsNum; i ++){\n      double x, y; \n      x    = rand_x(eng);\n      y    = rand_y(eng);\n\n      double w, h;\n      w    = rand_w(eng);\n\n      int widNum = ceil(w/_resolution);\n\n      for(int r = -widNum / 2; r < widNum / 2; r ++ )\n         for(int s = -widNum / 2; s < widNum / 2; s ++ ){\n            h    = rand_h(eng);  \n            //if(h < 1.0) continue;\n            int heiNum = ceil(h/_resolution);\n            for(int t = 0; t < heiNum; t ++ ){\n               pt_random.x = x + r * _resolution;\n               pt_random.y = y + s * _resolution;\n               pt_random.z = t * _resolution;\n               \n               if(sqrt( pow(pt_random.x - _init_x, 2) + pow(pt_random.y - _init_y, 2) ) < 2.0 \n               || sqrt( pow(pt_random.x - _end_x,  2) + pow(pt_random.y - _end_y,  2) ) < 2.0 ) \n                  continue;\n               \n               cloudMap.points.push_back( pt_random );\n            }\n         }\n   }\n\n   cloudMap.width = cloudMap.points.size();\n   cloudMap.height = 1;\n   cloudMap.is_dense = true;\n\n   ROS_WARN(\"[Map Generator] Finished generate random map \");\n   //cout<<cloudMap.size()<<endl;\n   kdtreeLocalMap.setInputCloud( cloudMap.makeShared() ); \n\n   _is_map_ok = true;\n}\n\nvoid rcvOdometryCallbck(const nav_msgs::Odometry odom)\n{\n   if (odom.child_frame_id == \"X\" || odom.child_frame_id == \"O\") return ;\n   _is_has_odom = true;\n\n   _state = {\n      odom.pose.pose.position.x, \n      odom.pose.pose.position.y, \n      odom.pose.pose.position.z, \n      odom.twist.twist.linear.x,\n      odom.twist.twist.linear.y,\n      odom.twist.twist.linear.z,\n      0.0, 0.0, 0.0\n   };\n}\n\nint global_map_vis_cnt = 0;\nvoid pubSensedPoints()\n{     \n   pcl::toROSMsg(cloudMap, globalMap_pcd);\n   globalMap_pcd.header.frame_id = \"map\";\n\n   if(global_map_vis_cnt < 20 ){\n      _all_map_pub.publish(globalMap_pcd);\n      sleep(0.01);\n   }\n\n   global_map_vis_cnt ++;\n   if(!_is_map_ok || !_is_has_odom)\n      return;\n\n   pcl::PointCloud<pcl::PointXYZ>::Ptr localMap(new pcl::PointCloud<pcl::PointXYZ>());\n   pcl::PointXYZ searchPoint(_state[0], _state[1], _state[2]);\n\n   pointIdxRadiusSearch.clear();\n   pointRadiusSquaredDistance.clear();\n   \n   pcl::PointXYZ ptInNoflation;\n\n   if ( kdtreeLocalMap.radiusSearch (searchPoint, _sensing_range, pointIdxRadiusSearch, pointRadiusSquaredDistance) > 0 ){\n      for (size_t i = 0; i < pointIdxRadiusSearch.size (); ++i){\n         ptInNoflation = cloudMap.points[pointIdxRadiusSearch[i]];      \n         if( abs(ptInNoflation.z - searchPoint.z ) >  _sensing_range * sin(_field_of_view_vertical/ 2.0 / 180.0 * M_PI) )\n            continue;\n\n         localMap->points.push_back(ptInNoflation);\n\n         if( sqrt(pow(ptInNoflation.x - LstMapCenter.x, 2) + pow(ptInNoflation.y - LstMapCenter.y, 2) + pow(ptInNoflation.z - LstMapCenter.z, 2) ) < _sensing_range )\n            continue;\n      }\n\n   }\n\n   localMap->width = localMap->points.size();\n   localMap->height = 1;\n   localMap->is_dense = true;\n      \n   pcl::toROSMsg(*localMap, localMap_pcd);\n   localMap_pcd.header.frame_id = \"map\";\n   _local_map_pub.publish(localMap_pcd);\n\n   LstMapCenter = pcl::PointXYZ(_state[0], _state[1], _state[2]);\n}\n\n\nint main (int argc, char** argv) \n{        \n   ros::init (argc, argv, \"random map generator\");\n   ros::NodeHandle nodehandle( \"~\" );\n\n   _local_map_pub =\n         nodehandle.advertise<sensor_msgs::PointCloud2>(\"RandomMap\", 1);                            \n   \n   _all_map_pub   =\n         nodehandle.advertise<sensor_msgs::PointCloud2>(\"all_map\", 1);  \n\n   _odom_sub      = \n         nodehandle.subscribe( \"odometry\", 50, rcvOdometryCallbck );\n\n   nodehandle.param(\"mapBoundary/lower_x\", _x_l,       0.0);\n   nodehandle.param(\"mapBoundary/upper_x\", _x_h,     100.0);\n   nodehandle.param(\"mapBoundary/lower_y\", _y_l,       0.0);\n   nodehandle.param(\"mapBoundary/upper_y\", _y_h,     100.0);\n   nodehandle.param(\"ObstacleShape/lower_rad\", _w_l,   0.3);\n   nodehandle.param(\"ObstacleShape/upper_rad\", _w_h,   0.8);\n   nodehandle.param(\"ObstacleShape/lower_hei\", _h_l,   3.0);\n   nodehandle.param(\"ObstacleShape/upper_hei\", _h_h,   7.0);\n   \n   nodehandle.param(\"sensing_radius\", _sensing_range,          10.0);\n   nodehandle.param(\"ObstacleNum\",    _obsNum,                 30  );\n   nodehandle.param(\"Resolution\",     _resolution,             0.2 );\n   nodehandle.param(\"SensingRate\",    _sense_rate,             10.0);\n   nodehandle.param(\"fov_vertical\",   _field_of_view_vertical, 30.0); \n   \n   nodehandle.param(\"init_x\", _init_x,  0.0); \n   nodehandle.param(\"init_y\", _init_y,  0.0); \n   nodehandle.param(\"end_x\",  _end_x,   0.0); \n   nodehandle.param(\"end_y\",  _end_y,   0.0); \n\n   RandomMapGeneration();\n   ros::Rate loop_rate(_sense_rate);\n   while (ros::ok())\n   {\n        pubSensedPoints();\n        ros::spinOnce();\n        loop_rate.sleep();\n   }\n}", "meta": {"hexsha": "62a7909018b01b7d22ee8cc75c7fa1b0eeff35c3", "size": 6481, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pointcloud_Traj/src/Planner/src/random_map_generator.cpp", "max_stars_repo_name": "Sunshinehualong/motion_Planning", "max_stars_repo_head_hexsha": "ea127de8cd8f32e9994538416d0c74b99054214f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-08-24T08:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T05:23:42.000Z", "max_issues_repo_path": "pointcloud_Traj/src/Planner/src/random_map_generator.cpp", "max_issues_repo_name": "lvhualong/motion_Planning", "max_issues_repo_head_hexsha": "ea127de8cd8f32e9994538416d0c74b99054214f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pointcloud_Traj/src/Planner/src/random_map_generator.cpp", "max_forks_repo_name": "lvhualong/motion_Planning", "max_forks_repo_head_hexsha": "ea127de8cd8f32e9994538416d0c74b99054214f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-08-24T08:28:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-19T12:47:20.000Z", "avg_line_length": 31.9261083744, "max_line_length": 165, "alphanum_fraction": 0.6426477395, "num_tokens": 1903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.5250583655950766}}
{"text": "//============================================================================\n// Name        : predict-radar-measurement.cpp\n// Author      : ddigges\n// Version     :\n// Copyright   : Your copyright notice\n// Description : Hello World in C++, Ansi-style\n//============================================================================\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n#include \"ukf.h\"\n\nusing namespace std;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing std::vector;\n\nint main() {\n\n\t//Create a UKF instance\n\tUKF ukf;\n\n/*******************************************************************************\n* Programming assignment calls\n*******************************************************************************/\n\n    VectorXd z_out = VectorXd(3);\n    MatrixXd S_out = MatrixXd(3, 3);\n    ukf.PredictRadarMeasurement(&z_out, &S_out);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "3df8b7e8540d223d6453effc2c74e6cd9e05063c", "size": 879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "P2-Unscented-Kalman-Filter/class-notes/predict-radar-measurement/src/predict-radar-measurement.cpp", "max_stars_repo_name": "Deborah-Digges/SDC-ND-term-2", "max_stars_repo_head_hexsha": "ebed581914957f1ab615edfedea0052dc55b0939", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-10-26T01:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-22T08:50:11.000Z", "max_issues_repo_path": "P2-Unscented-Kalman-Filter/class-notes/predict-radar-measurement/src/predict-radar-measurement.cpp", "max_issues_repo_name": "Deborah-Digges/SDC-ND-term-2", "max_issues_repo_head_hexsha": "ebed581914957f1ab615edfedea0052dc55b0939", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P2-Unscented-Kalman-Filter/class-notes/predict-radar-measurement/src/predict-radar-measurement.cpp", "max_forks_repo_name": "Deborah-Digges/SDC-ND-term-2", "max_forks_repo_head_hexsha": "ebed581914957f1ab615edfedea0052dc55b0939", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-05-28T20:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T09:01:54.000Z", "avg_line_length": 25.8529411765, "max_line_length": 80, "alphanum_fraction": 0.4311717861, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5250583548880433}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser 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 *     PCMSolver 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 Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#include \"catch.hpp\"\n\n#include <cmath>\n#include <iomanip>\n#include <limits>\n#include <sstream>\n\n\n#include <Eigen/Core>\n\n#include \"utils/cnpy.hpp\"\n#include \"cavity/Element.hpp\"\n#include \"cavity/GePolCavity.hpp\"\n#include \"bi_operators/IntegratorHelperFunctions.hpp\"\n#include \"utils/MathUtils.hpp\"\n#include \"TestingMolecules.hpp\"\n\nusing integrator::integrateS;\nusing integrator::integrateD;\n\ndouble constant(const Eigen::Vector3d & /* s */, const Eigen::Vector3d & /* p */);\ndouble one_over_r(double r, const Eigen::Vector3d & /* s */, const Eigen::Vector3d & /* p */);\n\nSCENARIO(\"Numerical quadrature of functions\", \"[numerical_quadrature]\")\n{\n    GIVEN(\"A function on the unit sphere\")\n    {\n        double radius = 1.55;\n        double area = 0.4;\n        Molecule point = dummy<0>(radius);\n        GePolCavity cavity(point, area, 0.0, 100.0, \"\");\n        Eigen::VectorXd results = Eigen::VectorXd::Zero(cavity.size());\n        /*! \\class NumericalQuadrature\n         *  \\test \\b NumericalQuadrature_sphere tests numerical quadrature on a sphere for integrand = 1.0\n         */\n        WHEN(\"The function is a constant\")\n        {\n            THEN(\"the integrals are the finite element areas\")\n            {\n                for (int i = 0; i < cavity.size(); ++i) {\n                    results(i) = integrateS<32, 16>(pcm::bind(constant, pcm::_1, pcm::_2), cavity.elements(i));\n                    double diff = results(i) - cavity.elementArea(i);\n                    if (std::abs(diff) > 1.0e-12) {\n                        WARN(\"Test versus area for single sphere\");\n                        WARN(\"Tessera n. \" << i+1);\n                        WARN(\"diff = \" << results(i) - cavity.elementArea(i));\n                    }\n                }\n                for (int i = 0; i < cavity.size(); ++i) {\n                    REQUIRE(results(i) == Approx(cavity.elementArea(i)));\n                }\n            }\n        }\n\n        /*! \\class NumericalQuadrature\n         *  \\test \\b NumericalQuadrature_sphere_1r tests numerical quadrature on a sphere for integrand 1.0/r\n         */\n        WHEN(\"The function is 1.0/r\")\n        {\n            THEN(\"the integrals are the finite element areas divided by the sphere radius\")\n            {\n                for (int i = 0; i < cavity.size(); ++i) {\n                    results(i) = integrateS<32, 16>(pcm::bind(one_over_r, 1.55, pcm::_1, pcm::_2), cavity.elements(i));\n                    double diff = results(i) - (cavity.elementArea(i)/radius);\n                    if (std::abs(diff) > 1.0e-11) {\n                        WARN(\"Test versus area divided by radius for single sphere\");\n                        WARN(\"Tessera n. \" << i+1);\n                        WARN(\"diff = \" << results(i) - (cavity.elementArea(i)/radius) );\n                    }\n                }\n                for (int i = 0; i < cavity.size(); ++i) {\n                    REQUIRE(results(i) == Approx(cavity.elementArea(i)/radius));\n                }\n            }\n        }\n    }\n\n    GIVEN(\"A function on a molecular surface\")\n    {\n        double area = 0.2;\n        double probeRadius = 1.385;\n        double minRadius = 0.2;\n        Molecule molecule = H2();\n        GePolCavity cavity(molecule, area, probeRadius, minRadius, \"\");\n        Eigen::VectorXd results = Eigen::VectorXd::Zero(cavity.size());\n        Eigen::VectorXd reference = Eigen::VectorXd::Zero(cavity.size());\n\n        /*! \\class NumericalQuadrature\n         *  \\test \\b NumericalQuadrature_molecule tests numerical quadrature function on H2 cavity\n         */\n        WHEN(\"The function is a constant\")\n        {\n            THEN(\"the integrals are the finite element areas\")\n            {\n                for (int i = 0; i < cavity.size(); ++i) {\n                    results(i) = integrateS<64, 16>(pcm::bind(constant, pcm::_1, pcm::_2), cavity.elements(i));\n                    double diff = results(i) - cavity.elementArea(i);\n                    if (std::abs(diff) > 1.0e-11) {\n                        WARN(\"Test versus area for H2 molecule\");\n                        WARN(\"Tessera n. \" << i+1);\n                        WARN(\"diff = \" << results(i) - cavity.elementArea(i));\n                    }\n                }\n                /*\n                // In case you need to update the reference files...\n                cnpy::custom::npy_save(\"molecule.npy\", results);\n                */\n                reference = cnpy::custom::npy_load<double>(\"molecule.npy\");\n\n                for (int i = 0; i < cavity.size(); ++i) {\n                    REQUIRE(results(i) == Approx(reference(i)));\n                }\n            }\n        }\n\n        /*! \\class NumericalQuadrature\n         *  \\test \\b NumericalQuadrature_molecule_1r tests numerical quadrature function on H2 cavity\n         */\n        WHEN(\"The function is 1.0/r\")\n        {\n            THEN(\"the integrals are the finite element areas divided by the sphere radius\")\n            {\n                for (int i = 0; i < cavity.size(); ++i) {\n                    results(i) = integrateS<64, 16>(pcm::bind(one_over_r, 1.20, pcm::_1, pcm::_2), cavity.elements(i));\n                    double diff = results(i) - (cavity.elementArea(i)/molecule.spheres(0).radius);\n                    if (std::abs(diff) > 1.0e-11) {\n                        WARN(\"Test versus area divided by radius for H2 molecule\");\n                        WARN(\"Tessera n. \" << i+1);\n                        WARN(\"diff = \" << results(i) - (cavity.elementArea(i)/molecule.spheres(0).radius) );\n                    }\n                }\n                /*\n                // In case you need to update the reference files...\n                cnpy::custom::npy_save(\"molecule_1r.npy\", results);\n                */\n                reference = cnpy::custom::npy_load<double>(\"molecule_1r.npy\");\n\n                for (int i = 0; i < cavity.size(); ++i) {\n                    REQUIRE(results(i) == Approx(reference(i)));\n                }\n            }\n        }\n    }\n}\n\ndouble constant(const Eigen::Vector3d & /* s */, const Eigen::Vector3d & /* p */) { return 1.0; }\ndouble one_over_r(double r, const Eigen::Vector3d & /* s */, const Eigen::Vector3d & /* p */) { return 1.0 / r; }\n", "meta": {"hexsha": "bc4d078a9fd328ddac9d76ce3bbb0c3bdccc181c", "size": 7293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/tests/numerical_quadrature/numerical_quadrature.cpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/tests/numerical_quadrature/numerical_quadrature.cpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/tests/numerical_quadrature/numerical_quadrature.cpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["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.1560693642, "max_line_length": 119, "alphanum_fraction": 0.5358563006, "num_tokens": 1748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5250583430324173}}
{"text": "#include <ros/ros.h>\n#include <geometry_msgs/Pose.h> \n#include <math.h>\n#include <time.h>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <Eigen/Eigen>\n\n#include \"origarm_ros/Command_Position.h\"\n#include \"origarm_ros/Command_ABL.h\"\n#include \"origarm_ros/modenumber.h\"\n#include \"origarm_ros/segnumber.h\"\n#include \"myGlobalData.h\"\n\n#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))\n\nusing namespace std;\n\nifstream inFile;\nconst int ms = 1000;  //1ms\nint ts = 50*ms;\n\nint mode_in;\nfloat x_in, y_in, z_in;\nfloat a_in[6], b_in[6], l_in[6];\n\nint flag = 1;\nint period = 100;\n\nvector<vector<float>> s_A;\nvector<vector<float>> s_B;\nvector<vector<float>> s_L;\n\nvector<vector<float>> state_A;\nvector<vector<float>> state_B;\nvector<vector<float>> state_L;\n\n//generate single point by defining starting and ending point\nstatic float lineardiffgenetraj(float ps, float pe, int step, int tstep)\n{\n\tfloat pm = ps + step*(pe-ps)/(tstep-1); \n\treturn pm;\n}\n\n//read state information from File\nstatic void readFromFile()\n{\n\tvector<float> s_a;\n\tvector<float> s_b;\n\tvector<float> s_l;\n\tvector<float> s_a1;\n\tvector<float> s_b1;\n\tvector<float> s_l1;\n\n\tinFile.open(\"/home/ubuntu/catkin_ws/src/origarm_ros/predefined_param/trajp_2seg_1.txt\", ios::in);\n\n\tif (!inFile)\n\t{\n\t\tprintf(\"%s\\n\", \"unable to open the file.\");\n\t\texit(1);\n\t}\n\telse\n\t{\n\t\twhile (true)\n\t\t{\n\t\t\tinFile>>mode_in>>x_in>>y_in>>z_in>>a_in[0]>>b_in[0]>>l_in[0]>>a_in[1]>>b_in[1]>>l_in[1]>>a_in[2]>>b_in[2]>>l_in[2]>>a_in[3]>>b_in[3]>>l_in[3]>>a_in[4]>>b_in[4]>>l_in[4]>>a_in[5]>>b_in[5]>>l_in[5];\n\t\t\n\t\t\tif ( inFile.eof() )\t\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\t\n\n\t\t\tfor (int i = 0; i < 6; i++)\n\t\t\t{\n\t\t\t\ts_a.push_back(a_in[i]);\n\t\t\t\ts_b.push_back(b_in[i]);\n\t\t\t\ts_l.push_back(l_in[i]);\n\t\t\t}\t\t\t\n\n\t\t\tif (s_a.size() < 6)\n\t\t\t{\n\t\t\t\tprintf(\"%s\\n\", \".............\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ts_a1.assign(s_a.end()-6, s_a.end());\n\t\t\t\ts_b1.assign(s_b.end()-6, s_b.end());\n\t\t\t\ts_l1.assign(s_l.end()-6, s_l.end());\n\n\t\t\t\ts_A.push_back(s_a1);\n\t\t\t\ts_B.push_back(s_b1);\n\t\t\t\ts_L.push_back(s_l1);\n\t\t\t}\t\n\t\t}\t\t\n\t}\n\n\tinFile.close();\t\n}\n\nstatic vector<vector<float>> TrajGeneration(vector<vector<float>> & vect1, int tstep)\n{\n\tint vectsize = vect1.size(); // return row size of 2d vector, size of timestamp read from file\n\t\n\tvector< vector<float> > state;\n\tvector<float> state1;\n\tvector<float> state_1;\n\n\tint t = 0;\n\n\tfor (int i = 0; i < 6; i++)\n\t{\n\t\tfor (int j = 0; j < vectsize-1; j++)\n\t\t{\n\t\t\tfloat ps = vect1[j][i];\n\t\t\tfloat pe = vect1[j+1][i];\n\t\t\t// printf(\"ps: %f, pe: %f\\n\", ps, pe);\n\n\t\t\tfor (int k = 0; k < tstep-1; k++)\n\t\t\t{\n\t\t\t\tfloat pm = lineardiffgenetraj(ps, pe, k, tstep);\n\t\t\t\tstate1.push_back(pm);\t\t\t\t\n\t\t\t\t// printf(\"state1[%d]: %f\\n\", t, state1[t]);\n\t\t\t\tt ++;\n\t\t\t}\t\t\t\t\t\n\t\t}\n\t\n\t\tint newvectorsize = (tstep-1)*(vectsize-1);\n\t\t\n\t\tif (state1.size() < newvectorsize)\n\t\t{\n\t\t\tprintf(\"%s\\n\", \"!.............\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstate_1.assign(state1.end() - newvectorsize, state1.end());\t\n\t\t\tstate.push_back(state_1);\n\t\t}\t\t\n\t\t\t\t\t\t\n\t}\n\n\treturn state;\t\t\t\t\t\n}\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"demo_trajectory_regenerate\");\n\tros::NodeHandle nh;\t\n\tros::Rate r(100);     //Hz\n\n\tros::Publisher  pub1 = nh.advertise<origarm_ros::Command_ABL>(\"Cmd_ABL_joy\", 100);\t\n\n\treadFromFile();\n\n\t// for (int i = 0; i < s_A.size(); i++)\n\t// {\n\t// \tfor (int j = 0; j < s_A[0].size(); j++)\n\t// \t{\n\t// \t\tprintf(\"state_A[%d][%d]: %f\\n\", i, j, s_A[i][j]);\n\t// \t}\t\t\n\t// }\n\n\tstate_A = TrajGeneration(s_A, period);\n\tstate_B = TrajGeneration(s_B, period);\n\tstate_L = TrajGeneration(s_L, period);\n\n\t// for (int i = 0; i < state_A.size(); i++)\n\t// {\n\t// \tfor (int j = 0; j < state_A[0].size(); j++)\n\t// \t{\n\t// \t\tprintf(\"state_A[%d][%d]: %f\\n\", i, j, state_A[i][j]);\n\t// \t}\t\t\n\t// }\n\n\twhile (ros::ok())\n\t{\n\t\torigarm_ros::Command_ABL Command_ABL_demo;\n\t\t\n\t\tif (flag == 1)\n\t\t{\n\t\t\tfor (int t = 0; t < 100; t++)\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < 6; i++)\n\t\t\t\t{\n\t\t\t\t\tCommand_ABL_demo.segment[i].A = state_A[i][0];\n\t\t\t\t\tCommand_ABL_demo.segment[i].B = state_B[i][0];\n\t\t\t\t\tCommand_ABL_demo.segment[i].L = state_L[i][0];\n\t\t\t\t}\n\t\t\t\tfor (int i = 6; i < 9; i++)\n\t\t\t\t{\n\t\t\t\t\tCommand_ABL_demo.segment[i].A = 0;\n\t\t\t\t\tCommand_ABL_demo.segment[i].B = 0;\n\t\t\t\t\tCommand_ABL_demo.segment[i].L = g_length0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tpub1.publish(Command_ABL_demo);\n\t\t\t\tusleep(ts);\n\t\t\t}\n\n\t\t\tflag = 2;\n\t\t}\n\t\telse if (flag == 2)\n\t\t{\n\t\t\tfor (int j = 0; j < state_A[0].size(); j++)\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < 6; i++)\n\t\t\t\t{\n\t\t\t\t\tCommand_ABL_demo.segment[i].A = state_A[i][j];\n\t\t\t\t\tCommand_ABL_demo.segment[i].B = state_B[i][j];\n\t\t\t\t\tCommand_ABL_demo.segment[i].L = state_L[i][j];\n\t\t\t\t}\n\t\t\t\tfor (int i = 6; i < 9; i++)\n\t\t\t\t{\n\t\t\t\t\tCommand_ABL_demo.segment[i].A = 0;\n\t\t\t\t\tCommand_ABL_demo.segment[i].B = 0;\n\t\t\t\t\tCommand_ABL_demo.segment[i].L = g_length0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tpub1.publish(Command_ABL_demo);\n\t\t\t\tusleep(ts);\n\t\t\t}\n\n\t\t\tflag = 0;\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int i = 0; i < 9; i++)\n\t\t\t{\n\t\t\t\tCommand_ABL_demo.segment[i].A = 0;\n\t\t\t\tCommand_ABL_demo.segment[i].B = 0;\n\t\t\t\tCommand_ABL_demo.segment[i].L = g_length0;\n\t\t\t}\n\t\t\t\n\t\t\tpub1.publish(Command_ABL_demo);\n\t\t\tusleep(ts);\n\t\t}\n\t\t\n\t\tr.sleep();\n\t}\n\n\tinFile.close();\t\n\treturn 0;\n}\n\n", "meta": {"hexsha": "d4a2d12306532cc6ebb26d0fc95a186fee36b14f", "size": 5095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/demo_trajectory_regenerate.cpp", "max_stars_repo_name": "XiaojiaoChen/origarm_ros", "max_stars_repo_head_hexsha": "59d1b05e9c13c50a9281ab2a670621f3f04d8cc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-30T10:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T10:05:38.000Z", "max_issues_repo_path": "src/demo_trajectory_regenerate.cpp", "max_issues_repo_name": "XiaojiaoChen/origarm_ros", "max_issues_repo_head_hexsha": "59d1b05e9c13c50a9281ab2a670621f3f04d8cc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-01T08:16:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T08:16:06.000Z", "max_forks_repo_path": "src/demo_trajectory_regenerate.cpp", "max_forks_repo_name": "XiaojiaoChen/softArmROS", "max_forks_repo_head_hexsha": "59d1b05e9c13c50a9281ab2a670621f3f04d8cc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-04-30T06:48:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-01T04:27:26.000Z", "avg_line_length": 20.7959183673, "max_line_length": 199, "alphanum_fraction": 0.5813542689, "num_tokens": 1821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5250583376789006}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2008-2014 Gael Guennebaud <gael.guennebaud@inria.fr>\r\n// Copyright (C) 2009 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// discard stack allocation as that too bypasses malloc\r\n#define EIGEN_STACK_ALLOCATION_LIMIT 0\r\n#define EIGEN_RUNTIME_NO_MALLOC\r\n#include \"main.h\"\r\n#include <Eigen/SVD>\r\n\r\n#define SVD_DEFAULT(M) JacobiSVD<M>\r\n#define SVD_FOR_MIN_NORM(M) JacobiSVD<M,ColPivHouseholderQRPreconditioner>\r\n#include \"svd_common.h\"\r\n\r\n// Check all variants of JacobiSVD\r\ntemplate<typename MatrixType>\r\nvoid jacobisvd(const MatrixType& a = MatrixType(), bool pickrandom = true)\r\n{\r\n  MatrixType m = a;\r\n  if(pickrandom)\r\n    svd_fill_random(m);\r\n\r\n  CALL_SUBTEST(( svd_test_all_computation_options<JacobiSVD<MatrixType, FullPivHouseholderQRPreconditioner> >(m, true)  )); // check full only\r\n  CALL_SUBTEST(( svd_test_all_computation_options<JacobiSVD<MatrixType, ColPivHouseholderQRPreconditioner>  >(m, false) ));\r\n  CALL_SUBTEST(( svd_test_all_computation_options<JacobiSVD<MatrixType, HouseholderQRPreconditioner>        >(m, false) ));\r\n  if(m.rows()==m.cols())\r\n    CALL_SUBTEST(( svd_test_all_computation_options<JacobiSVD<MatrixType, NoQRPreconditioner>               >(m, false) ));\r\n}\r\n\r\ntemplate<typename MatrixType> void jacobisvd_verify_assert(const MatrixType& m)\r\n{\r\n  svd_verify_assert<JacobiSVD<MatrixType> >(m);\r\n  typedef typename MatrixType::Index Index;\r\n  Index rows = m.rows();\r\n  Index cols = m.cols();\r\n\r\n  enum {\r\n    ColsAtCompileTime = MatrixType::ColsAtCompileTime\r\n  };\r\n\r\n\r\n  MatrixType a = MatrixType::Zero(rows, cols);\r\n  a.setZero();\r\n\r\n  if (ColsAtCompileTime == Dynamic)\r\n  {\r\n    JacobiSVD<MatrixType, FullPivHouseholderQRPreconditioner> svd_fullqr;\r\n    VERIFY_RAISES_ASSERT(svd_fullqr.compute(a, ComputeFullU|ComputeThinV))\r\n    VERIFY_RAISES_ASSERT(svd_fullqr.compute(a, ComputeThinU|ComputeThinV))\r\n    VERIFY_RAISES_ASSERT(svd_fullqr.compute(a, ComputeThinU|ComputeFullV))\r\n  }\r\n}\r\n\r\ntemplate<typename MatrixType>\r\nvoid jacobisvd_method()\r\n{\r\n  enum { Size = MatrixType::RowsAtCompileTime };\r\n  typedef typename MatrixType::RealScalar RealScalar;\r\n  typedef Matrix<RealScalar, Size, 1> RealVecType;\r\n  MatrixType m = MatrixType::Identity();\r\n  VERIFY_IS_APPROX(m.jacobiSvd().singularValues(), RealVecType::Ones());\r\n  VERIFY_RAISES_ASSERT(m.jacobiSvd().matrixU());\r\n  VERIFY_RAISES_ASSERT(m.jacobiSvd().matrixV());\r\n  VERIFY_IS_APPROX(m.jacobiSvd(ComputeFullU|ComputeFullV).solve(m), m);\r\n}\r\n\r\nvoid test_jacobisvd()\r\n{\r\n  CALL_SUBTEST_3(( jacobisvd_verify_assert(Matrix3f()) ));\r\n  CALL_SUBTEST_4(( jacobisvd_verify_assert(Matrix4d()) ));\r\n  CALL_SUBTEST_7(( jacobisvd_verify_assert(MatrixXf(10,12)) ));\r\n  CALL_SUBTEST_8(( jacobisvd_verify_assert(MatrixXcd(7,5)) ));\r\n  \r\n  CALL_SUBTEST_11(svd_all_trivial_2x2(jacobisvd<Matrix2cd>));\r\n  CALL_SUBTEST_12(svd_all_trivial_2x2(jacobisvd<Matrix2d>));\r\n\r\n  for(int i = 0; i < g_repeat; i++) {\r\n    CALL_SUBTEST_3(( jacobisvd<Matrix3f>() ));\r\n    CALL_SUBTEST_4(( jacobisvd<Matrix4d>() ));\r\n    CALL_SUBTEST_5(( jacobisvd<Matrix<float,3,5> >() ));\r\n    CALL_SUBTEST_6(( jacobisvd<Matrix<double,Dynamic,2> >(Matrix<double,Dynamic,2>(10,2)) ));\r\n\r\n    int r = internal::random<int>(1, 30),\r\n        c = internal::random<int>(1, 30);\r\n    \r\n    TEST_SET_BUT_UNUSED_VARIABLE(r)\r\n    TEST_SET_BUT_UNUSED_VARIABLE(c)\r\n    \r\n    CALL_SUBTEST_10(( jacobisvd<MatrixXd>(MatrixXd(r,c)) ));\r\n    CALL_SUBTEST_7(( jacobisvd<MatrixXf>(MatrixXf(r,c)) ));\r\n    CALL_SUBTEST_8(( jacobisvd<MatrixXcd>(MatrixXcd(r,c)) ));\r\n    (void) r;\r\n    (void) c;\r\n\r\n    // Test on inf/nan matrix\r\n    CALL_SUBTEST_7(  (svd_inf_nan<JacobiSVD<MatrixXf>, MatrixXf>()) );\r\n    CALL_SUBTEST_10( (svd_inf_nan<JacobiSVD<MatrixXd>, MatrixXd>()) );\r\n\r\n    // bug1395 test compile-time vectors as input\r\n    CALL_SUBTEST_13(( jacobisvd_verify_assert(Matrix<double,6,1>()) ));\r\n    CALL_SUBTEST_13(( jacobisvd_verify_assert(Matrix<double,1,6>()) ));\r\n    CALL_SUBTEST_13(( jacobisvd_verify_assert(Matrix<double,Dynamic,1>(r)) ));\r\n    CALL_SUBTEST_13(( jacobisvd_verify_assert(Matrix<double,1,Dynamic>(c)) ));\r\n  }\r\n\r\n  CALL_SUBTEST_7(( jacobisvd<MatrixXf>(MatrixXf(internal::random<int>(EIGEN_TEST_MAX_SIZE/4, EIGEN_TEST_MAX_SIZE/2), internal::random<int>(EIGEN_TEST_MAX_SIZE/4, EIGEN_TEST_MAX_SIZE/2))) ));\r\n  CALL_SUBTEST_8(( jacobisvd<MatrixXcd>(MatrixXcd(internal::random<int>(EIGEN_TEST_MAX_SIZE/4, EIGEN_TEST_MAX_SIZE/3), internal::random<int>(EIGEN_TEST_MAX_SIZE/4, EIGEN_TEST_MAX_SIZE/3))) ));\r\n\r\n  // test matrixbase method\r\n  CALL_SUBTEST_1(( jacobisvd_method<Matrix2cd>() ));\r\n  CALL_SUBTEST_3(( jacobisvd_method<Matrix3f>() ));\r\n\r\n  // Test problem size constructors\r\n  CALL_SUBTEST_7( JacobiSVD<MatrixXf>(10,10) );\r\n\r\n  // Check that preallocation avoids subsequent mallocs\r\n  CALL_SUBTEST_9( svd_preallocate<void>() );\r\n\r\n  CALL_SUBTEST_2( svd_underoverflow<void>() );\r\n}\r\n", "meta": {"hexsha": "02dd78f98d63a56e5aab9497deac6ccf937a7059", "size": 5149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/test/jacobisvd.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/test/jacobisvd.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/test/jacobisvd.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": 40.5433070866, "max_line_length": 193, "alphanum_fraction": 0.7218877452, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.5250277682985959}}
{"text": "#ifndef DPP_H\n#define DPP_H\n\n#include <stdlib.h>\n#include <cstdlib>\n#include <opencv2/imgproc.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <iostream>\n#include \"utils.hpp\"\n\nusing namespace cv;\nusing namespace std;\nusing namespace Eigen;\n\nclass DPP\n{\npublic:\n\tDPP();\n\tvector<MyTarget> run(vector<MyTarget> raw_detections, VectorXd &weights, MatrixXd &features, double epsilon = 0.1, double mu = 0.7, double lambda = 0.1);\n\tvector<MyTarget> run(vector<MyTarget> tracks, double epsilon, double mu, double lambda);\n\tvector<MyTarget> run(vector<MyTarget> tracks, double epsilon, Size img_size);\n\t//vector<MyTarget> run(vector<MyTarget> tracks, double epsilon);\nprivate:\n\tVectorXd getQualityTerm(VectorXd &weights, VectorXd &nPenalty);\n\tMatrixXd getSimilarityTerm(MatrixXd &features, MatrixXd &intersection, MatrixXd &sqrtArea, double mu);\n\tMatrixXd affinity_kernel(vector<MyTarget> tracks, Size img_size);\n\tMatrixXd squared_exponential_kernel(MatrixXd X, double nu, double sigma_f);\n\tvector<int> solve(VectorXd &qualityTerm, MatrixXd &similarityTerm, double epsilon);\n};\n\n#endif", "meta": {"hexsha": "81609cf7bd4060a8ca19993dc34fffcfa80c461c", "size": 1086, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/dpp/dpp.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/dpp/dpp.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/dpp/dpp.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": 33.9375, "max_line_length": 154, "alphanum_fraction": 0.773480663, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5250268096771008}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::::unnormalized_pdf::uniform.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_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_UNIFORM_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_UNIFORM_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#include <boost/math/distributions/uniform.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/numeric/conversion/converter.hpp>\n#include <boost/math/policies/policy.hpp>\n#include <boost/math/tools/precision.hpp>\n\nnamespace boost{\nnamespace math{\n\n    template<typename T,typename P>\n    T log_unnormalized_pdf(\n        const boost::math::uniform_distribution<T,P>& dist,\n        const T& x\n    )\n    {\n        T lower = dist.lower();\n        T upper = dist.upper();\n        T result; // of checks.\n        if(false == boost::math::detail::check_uniform(\n            \"boost::math::pdf(const uniform_distribution<%1%>&, %1%)\", \n            lower, upper, &result, P()))\n        {\n            return result;\n        }\n        if(false == boost::math::detail::check_uniform_x(\n            \"boost::math::pdf(const uniform_distribution<%1%>&, %1%)\",\n             x, &result, P()))\n        {\n            return result;\n        }\n\n        if((x < lower) || (x > upper) )\n        {\n            static T inf = std::numeric_limits<T>::infinity();\n            return (- inf);\n        }\n        else\n        {\n            return static_cast<T>(0);\n        }\n    } \n\n}// math\n}// boost\n\n#endif\n", "meta": {"hexsha": "291f8ce625445b14b7b33de589cfde6d0c1322d0", "size": 2020, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/uniform/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/uniform/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/uniform/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": 35.4385964912, "max_line_length": 93, "alphanum_fraction": 0.5237623762, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5250267918844608}}
{"text": "#include \"ceres/rotation.h\"\n#include \"ceres/jet.h\"\n#include <Eigen/Dense>\n#include <TooN/TooN.h>\n#include <cmath>\n#include <libv/lma/color/console.hpp>\n#include <libv/lma/string/string_utiliy.hpp>\n#include <libv/lma/time/tictoc.hpp>\n#include <libv/lma/numeric/ad/rt/ad.hpp>\n#include <libv/lma/numeric/ad/ct/adct.hpp>\n#include <typeinfo>\n\n  typedef Eigen::Matrix<double,9,1> Camera;\n  typedef Eigen::Matrix<double,3,1> Point3d;\n  typedef Eigen::Matrix<double,2,1> Point2d;\n  \n  template<class T>\n  void analytical_derivative(const Camera& camera_, const Point3d& point_, const Eigen::Vector2d& obs, Eigen::Matrix<double,2,12>& j)\n  {\n    const T camera[3] = {T(camera_[0],0),T(camera_[1],1),T(camera_[2],2)};\n    const T point[3] = {T(point_[0],9),T(point_[1],10),T(point_[2],11)};\n    T p[3];\n    ceres::AngleAxisRotatePoint(camera, point, p);\n    p[0] += T(camera_[3],3);\n    p[1] += T(camera_[4],4);\n    p[2] += T(camera_[5],5);\n    auto xp = - p[0] / p[2];\n    auto yp = - p[1] / p[2];\n    const T l1(camera_[7],7);\n    const T l2(camera_[8],8);\n    auto r2 = xp*xp + yp*yp;\n    auto distortion = T(1.0) + r2  * (l1 + l2  * r2);\n    T focal(camera_[6],6);\n    auto jacobx = focal * distortion * xp - T(obs.x());\n    auto jacoby = focal * distortion * yp - T(obs.y());\n    for(int i = 0 ; i < 12 ; ++i)\n    {\n      j(0,i) = jacobx.v[i];\n      j(1,i) = jacoby.v[i];\n    }\n  }\n\n  template<class T>\n  void analytical_derivative2(const Camera& camera_, const Point3d& point_, const Point2d& obs, TooN::Matrix<2,12,double>& j)\n  {\n    typedef T Scalar;\n    const std::array<T,9> c = {\n      T(camera_[0],0),T(camera_[1],1),T(camera_[2],2),\n      T(camera_[3],3),T(camera_[4],4),T(camera_[5],5),\n      T(camera_[6],6),T(camera_[7],7),T(camera_[8],8)};\n\n    const std::array<T,3> pt = {T(point_[0],9),T(point_[1],10),T(point_[2],11)};\n    \n    std::array<T,2> p;\n    \n    const T theta2 = c[0]*c[0] + c[1]*c[1] + c[2]*c[2];\n    if (theta2 > Scalar(std::numeric_limits<double>::epsilon()))\n    {\n      const T\n        theta = sqrt(theta2),\n        costheta = cos(theta),\n        sintheta = sin(theta),\n        theta_inverse = 1.0 / theta,\n        w[3] = { c[0] * theta_inverse, c[1] * theta_inverse, c[2] * theta_inverse },\n        tmp = (w[0] * pt[0] + w[1] * pt[1] + w[2] * pt[2]) * (Scalar(1.0) - costheta),\n        p2 =    pt[2] * costheta + (w[0] * pt[1] - w[1] * pt[0]) * sintheta + w[2] * tmp + c[5];\n      p[0] = - (pt[0] * costheta + (w[1] * pt[2] - w[2] * pt[1]) * sintheta + w[0] * tmp + c[3]) / p2;\n      p[1] = - (pt[1] * costheta + (w[2] * pt[0] - w[0] * pt[2]) * sintheta + w[1] * tmp + c[4]) / p2;\n    }\n    else\n    {\n      const T p2 = pt[2] + c[0] * pt[1] - c[1] * pt[0] + c[5];\n      p[0] = - (pt[0] + c[1] * pt[2] - c[2] * pt[1] + c[3]) / p2;\n      p[1] = - (pt[1] + c[2] * pt[0] - c[0] * pt[2] + c[4]) / p2;\n    }\n    \n    const T\n      r2 = p[0]*p[0] + p[1]*p[1],\n      fx = c[6] * (Scalar(1.0) + r2  * (c[7] + c[8]  * r2));\n      \n    const typename T::Array\n      jacobx = (fx * p[0] - Scalar(obs.x())).infinite(),\n      jacoby = (fx * p[1] - Scalar(obs.y())).infinite();\n\n    for(int i = 0 ; i < 12 ; ++i)\n    {\n      j(0,i) = jacobx[i];\n      j(1,i) = jacoby[i];\n    }\n  }\n  \n  template<class T> auto f(const T& a, const T& b, const T& c)\n  {\n    return - a * 2.5 * b * a * c * a - 2.0 * a * b * a * b / 10.0 + a /2.0 + a * sqrt(b * c * cos( sin( b * b + c) / a * c / 5.0));\n  }\n  \n  inline void test_adrt(double x, double y, double z, double d[3], double& r)\n  {\n    AdRt::Ad<double,3> a(x,0),b(y,1),c(z,2);\n    AdRt::Ad<double,3> derivatives = f(a,b,c);\n    d[0] = derivatives.infinite[0]; d[1] = derivatives.infinite[1]; d[2] = derivatives.infinite[2];\n    r = derivatives.value;\n  }\n  \n  inline void test_adct(double x, double y, double z, double d[3], double& r)\n  {\n    adct::Ad<double,3> a(x,0),b(y,1),c(z,2);\n    auto expr = f(a,b,c);\n    auto derivatives = expr.infinite();\n    d[0] = derivatives[0];d[1] = derivatives[1];d[2] = derivatives[2];\n    r = expr.value();\n  }\n  \n  inline void test_jet(double x, double y, double z, double d[3], double& r)\n  {\n    ceres::Jet<double,3> a(x,0),b(y,1),c(z,2);\n    auto derivatives = f(a,b,c);\n    d[0] = derivatives.v[0];d[1] = derivatives.v[1];d[2] = derivatives.v[2];\n    r = derivatives.a;\n  }\n  \n\n\nint main()\n{\n  std::cout << std::endl << std::endl;\n  double d[3] = {0,0,0};\n  double r = 0;\n  \n  size_t N = 1000000;\n  \n  utils::Tic<true> ticAdrt(\"Adrt\");\n  for(size_t i = 0 ; i < N; ++i)\n    test_adrt(i,i/2,i/3,d,r);\n  ticAdrt.disp();\n  \n  std::cout << color.red() << \" adrt dx,dy,dz = \" << d[0] << \",\" << d[1] << \",\" << d[2] << \",\" << r << color.reset() << std::endl;\n  d[0] = 0; d[1] = 0, d[2] = 0;\n  r = 0; \n  \n  utils::Tic<true> ticAd(\"AdCt\");\n  for(size_t i = 0 ; i < N; ++i)\n    test_adct(i,i/2,i/3,d,r);\n  ticAd.disp();\n  \n  std::cout << color.red() << \" adct dx,dy,dz = \" << d[0] << \",\" << d[1] << \",\" << d[2] << \",\" << r << color.reset() << std::endl;\n  \n  d[0] = 0; d[1] = 0, d[2] = 0;\n  r = 0;\n  utils::Tic<true> ticjet(\"jet\");\n  for(size_t i = 0 ; i < N; ++i)\n    test_jet(i,i/2,i/3,d,r);\n  ticjet.disp();\n  \n  \n  std::cout << color.red() << \" jet  dx,dy,dz = \" << d[0] << \",\" << d[1] << \",\" << d[2] << \",\" << r <<  color.reset() << std::endl;\n  \n\n  Camera cam; cam << 0,0,0,10,10,10,10,10,10;\n  Point3d pt; pt << 100,200,150;\n  Point2d obs; obs << 100,100;\n  \n\n  \n  {\n    Eigen::Matrix<double,2,12> jacob;\n    utils::Tic<true> jet_proj(\"Jet Proj\");\n    for(size_t i = 0 ; i < N; ++i)\n      analytical_derivative<ceres::Jet<double,12>>(cam,pt,obs,jacob);\n    jet_proj.disp();\n    std::cout << jacob << std::endl;\n  }\n  \n  {\n    TooN::Matrix<2,12,double> jacob;\n    utils::Tic<true> ad_proj(\"Ad Proj\");\n    for(size_t i = 0 ; i < N; ++i)\n      analytical_derivative2<adct::Ad<double,12>>(cam,pt,obs,jacob);\n    ad_proj.disp();\n    std::cout << jacob << std::endl;\n  }\n//   \n}\n\n", "meta": {"hexsha": "05e460a494af1d308bb485f215b498bbe19c658c", "size": 5865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/adct.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/adct.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/adct.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": 31.7027027027, "max_line_length": 133, "alphanum_fraction": 0.5169650469, "num_tokens": 2324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5250267876334704}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_TRACE_GEN_QUAD_FORM_HPP\n#define STAN_MATH_PRIM_MAT_FUN_TRACE_GEN_QUAD_FORM_HPP\n\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n\nnamespace stan {\n  namespace math {\n    /**\n     * Compute trace(D B^T A B).\n     **/\n    template<int RD, int CD, int RA, int CA, int RB, int CB>\n    inline double\n    trace_gen_quad_form(const Eigen::Matrix<double, RD, CD> &D,\n                        const Eigen::Matrix<double, RA, CA> &A,\n                        const Eigen::Matrix<double, RB, CB> &B) {\n      check_square(\"trace_gen_quad_form\", \"A\", A);\n      check_square(\"trace_gen_quad_form\", \"D\", D);\n      check_multiplicable(\"trace_gen_quad_form\",\n                          \"A\", A,\n                          \"B\", B);\n      check_multiplicable(\"trace_gen_quad_form\",\n                          \"B\", B,\n                          \"D\", D);\n      return (D*B.transpose()*A*B).trace();\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "4994570c39a4c3307921536cf73f7e5f57913db6", "size": 1098, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/trace_gen_quad_form.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/trace_gen_quad_form.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/trace_gen_quad_form.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2941176471, "max_line_length": 65, "alphanum_fraction": 0.5947176685, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5250267867935262}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2021 Alec Jacobson <alecjacobson@gmail.com>\n// Copyright (C) 2013 Alec Jacobson <alecjacobson@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 \"per_corner_normals.h\"\n#include \"vertex_triangle_adjacency.h\"\n#include \"per_face_normals.h\"\n#include \"PI.h\"\n#include \"parallel_for.h\"\n#include \"doublearea.h\"\n#include <Eigen/Geometry>\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedCN>\nIGL_INLINE void igl::per_corner_normals(\n  const Eigen::MatrixBase<DerivedV> & V,\n  const Eigen::MatrixBase<DerivedF> & F,\n  const typename DerivedV::Scalar corner_threshold_degrees,\n  Eigen::PlainObjectBase<DerivedCN> & CN)\n{\n  Eigen::Matrix<Eigen::Index,Eigen::Dynamic,1> VF,NK;\n  vertex_triangle_adjacency(F,V.rows(),VF,NK);\n  return per_corner_normals(V,F,corner_threshold_degrees,VF,NK,CN);\n}\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedVF,\n  typename DerivedNI,\n  typename DerivedCN>\nIGL_INLINE void igl::per_corner_normals(\n  const Eigen::MatrixBase<DerivedV> & V,\n  const Eigen::MatrixBase<DerivedF> & F,\n  const typename DerivedV::Scalar corner_threshold_degrees,\n  const Eigen::MatrixBase<DerivedVF> & VF,\n  const Eigen::MatrixBase<DerivedNI> & NI,\n  Eigen::PlainObjectBase<DerivedCN> & CN)\n{\n  typedef typename DerivedV::Scalar Scalar;\n  typedef Eigen::Index Index;\n  // unit normals\n  Eigen::Matrix<Scalar,Eigen::Dynamic,3,Eigen::RowMajor> FN(F.rows(),3);\n  // face areas\n  Eigen::Matrix<Scalar,Eigen::Dynamic,1> FA(F.rows());\n  igl::parallel_for(F.rows(),[&](const Index f)\n  {\n    const Eigen::Matrix<Scalar,1,3> v10 = V.row(F(f,1))-V.row(F(f,0));\n    const Eigen::Matrix<Scalar,1,3> v20 = V.row(F(f,2))-V.row(F(f,0));\n    const Eigen::Matrix<Scalar,1,3> n = v10.cross(v20);\n    const Scalar a = n.norm();\n    FA(f) = a;\n    FN.row(f) = n/a;\n  },10000);\n\n  // number of faces\n  const Index m = F.rows();\n  // valence of faces\n  const Index n = F.cols();\n  assert(n == 3);\n\n  // initialize output to ***zero***\n  CN.setZero(m*n,3);\n\n  const Scalar cos_thresh = cos(corner_threshold_degrees*igl::PI/180);\n  // loop over faces\n  //for(Index i = 0;i<m;i++)\n  igl::parallel_for(F.rows(),[&](const Index i)\n  {\n    // Normal of this face\n    const auto & fnhat = FN.row(i);\n    // loop over corners\n    for(Index j = 0;j<n;j++)\n    {\n      const auto & v = F(i,j);\n      for(int k = NI[v]; k<NI[v+1]; k++)\n      {\n        const auto & ifn = FN.row(VF[k]);\n        // dot product between face's normal and other face's normal\n        const Scalar dp = fnhat.dot(ifn);\n        // if difference in normal is slight then add to average\n        if(dp > cos_thresh)\n        {\n          // add to running sum\n          CN.row(i*n+j) += ifn*FA(VF[k]);\n        }\n      }\n      // normalize to take average\n      CN.row(i*n+j).normalize();\n    }\n  },10000);\n}\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedCI,\n  typename DerivedCC,\n  typename DerivedCN>\nIGL_INLINE void igl::per_corner_normals(\n  const Eigen::MatrixBase<DerivedV> & V,\n  const Eigen::MatrixBase<DerivedF> & F,\n  const Eigen::MatrixBase<DerivedCI> & CI,\n  const Eigen::MatrixBase<DerivedCC> & CC,\n  Eigen::PlainObjectBase<DerivedCN> & CN)\n{\n  typedef typename DerivedV::Scalar Scalar;\n  typedef Eigen::Index Index;\n  assert(CC.rows() == F.rows()*3+1);\n  // area weighted normals\n  Eigen::Matrix<Scalar,Eigen::Dynamic,3,Eigen::RowMajor> FN(F.rows(),3);\n  //for(Index f = 0;f<F.rows();f++)\n  igl::parallel_for(F.rows(),[&](const Index f)\n  {\n    const Eigen::Matrix<Scalar,1,3> v10 = V.row(F(f,1))-V.row(F(f,0));\n    const Eigen::Matrix<Scalar,1,3> v20 = V.row(F(f,2))-V.row(F(f,0));\n    FN.row(f) = v10.cross(v20);\n  },10000);\n\n  // number of faces\n  const Index m = F.rows();\n  // valence of faces\n  const Index n = F.cols();\n  assert(n == 3);\n\n  // initialize output to ***zero***\n  CN.setZero(m*n,3);\n  // loop over faces\n  igl::parallel_for(m*n,[&](const Index ci)\n  {\n    for(int k = CC(ci); k<CC(ci+1); k++)\n    {\n      // add to running sum\n      const auto cfk = CI(k);\n      CN.row(ci) += FN.row(cfk);\n    }\n    // normalize to take average\n    CN.row(ci).normalize();\n  },10000);\n}\n\ntemplate <typename DerivedNV, typename DerivedNF, typename DerivedCN>\nIGL_INLINE void igl::per_corner_normals(\n  const Eigen::MatrixBase<DerivedNV> & NV,\n  const Eigen::MatrixBase<DerivedNF> & NF,\n  Eigen::PlainObjectBase<DerivedCN> & CN)\n{\n  const auto m = NF.rows();\n  const auto nc = NF.cols();\n  CN.resize(m*nc,3);\n  for(Eigen::Index i = 0;i<m;i++)\n  {\n    for(Eigen::Index c = 0;c<nc;c++)\n    {\n      CN.row(i*nc+c) = NV.row(NF(i,c));\n    }\n  }\n}\n\ntemplate <\n  typename DerivedV, \n  typename DerivedI, \n  typename DerivedC, \n  typename DerivedN,\n  typename DerivedVV,\n  typename DerivedFF,\n  typename DerivedJ,\n  typename DerivedNN>\nIGL_INLINE void igl::per_corner_normals(\n  const Eigen::MatrixBase<DerivedV> & V,\n  const Eigen::MatrixBase<DerivedI> & I,\n  const Eigen::MatrixBase<DerivedC> & C,\n  const typename DerivedV::Scalar corner_threshold_degrees,\n  Eigen::PlainObjectBase<DerivedN>  & N,\n  Eigen::PlainObjectBase<DerivedVV> & VV,\n  Eigen::PlainObjectBase<DerivedFF> & FF,\n  Eigen::PlainObjectBase<DerivedJ>  & J,\n  Eigen::PlainObjectBase<DerivedNN> & NN)\n{\n  const Eigen::Index m = C.size()-1;\n  typedef Eigen::Index Index;\n  Eigen::MatrixXd FN;\n  per_face_normals(V,I,C,FN,VV,FF,J);\n  typedef typename DerivedN::Scalar Scalar;\n  Eigen::Matrix<Scalar,Eigen::Dynamic,1> AA;\n  doublearea(VV,FF,AA);\n  // VF[i](j) = p means p is the jth face incident on vertex i\n  // to-do micro-optimization to avoid vector<vector>\n  std::vector<std::vector<Eigen::Index>> VF(V.rows());\n  for(Eigen::Index p = 0;p<m;p++)\n  {\n    // number of faces/vertices in this simple polygon\n    const Index np = C(p+1)-C(p);\n    for(Eigen::Index i = 0;i<np;i++)\n    {\n      VF[I(C(p)+i)].push_back(p);\n    }\n  }\n\n  N.resize(I.rows(),3);\n  for(Eigen::Index p = 0;p<m;p++)\n  {\n    // number of faces/vertices in this simple polygon\n    const Index np = C(p+1)-C(p);\n    Eigen::Matrix<Scalar,3,1> fn = FN.row(p);\n    for(Eigen::Index i = 0;i<np;i++)\n    {\n      N.row(C(p)+i).setZero();\n      // Loop over faces sharing this vertex\n      for(const auto & n : VF[I(C(p)+i)])\n      {\n        Eigen::Matrix<Scalar,3,1> ifn = FN.row(n);\n        // dot product between face's normal and other face's normal\n        Scalar dp = fn.dot(ifn);\n        if(dp > cos(corner_threshold_degrees*igl::PI/180))\n        {\n          // add to running sum\n          N.row(C(p)+i) += AA(n) * ifn;\n        }\n      }\n      N.row(C(p)+i).normalize();\n    }\n  }\n\n  // Relies on order of FF \n  NN.resize(FF.rows()*3,3);\n  {\n    Eigen::Index k = 0;\n    for(Eigen::Index p = 0;p<m;p++)\n    {\n      // number of faces/vertices in this simple polygon\n      const Index np = C(p+1)-C(p);\n      for(Eigen::Index i = 0;i<np;i++)\n      {\n        assert(FF(k,0) == I(C(p)+((i+0)%np)));\n        assert(FF(k,1) == I(C(p)+((i+1)%np)));\n        assert(FF(k,2) == V.rows()+p);\n        NN.row(k*3+0) = N.row(C(p)+((i+0)%np));\n        NN.row(k*3+1) = N.row(C(p)+((i+1)%np));\n        NN.row(k*3+2) = FN.row(p);\n        k++;\n      }\n    }\n    assert(k == FF.rows());\n  }\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate void igl::per_corner_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate void igl::per_corner_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_corner_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, Eigen::MatrixBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_corner_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_corner_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\n// Clang thinks this is the same as the one below, but Windows doesn't?\n// template void igl::per_corner_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate void igl::per_corner_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, double, Eigen::PlainObjectBase< Eigen::Matrix<double, -1, -1, 0, -1, -1> > &);\n#endif\n", "meta": {"hexsha": "0cd0a37a4e51e7a99932c121cc91a765e8186867", "size": 11223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/depends/igl/headers/igl/per_corner_normals.cpp", "max_stars_repo_name": "GitZHCODE/zspace_modules", "max_stars_repo_head_hexsha": "2264cb837d2f05184a51b7b453c7e24288e88ee1", "max_stars_repo_licenses": ["MIT"], "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/depends/igl/headers/igl/per_corner_normals.cpp", "max_issues_repo_name": "GitZHCODE/zspace_modules", "max_issues_repo_head_hexsha": "2264cb837d2f05184a51b7b453c7e24288e88ee1", "max_issues_repo_licenses": ["MIT"], "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/depends/igl/headers/igl/per_corner_normals.cpp", "max_forks_repo_name": "GitZHCODE/zspace_modules", "max_forks_repo_head_hexsha": "2264cb837d2f05184a51b7b453c7e24288e88ee1", "max_forks_repo_licenses": ["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.3509433962, "max_line_length": 936, "alphanum_fraction": 0.6145415664, "num_tokens": 3876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5250267757717112}}
{"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/**\n * creates synthetic data\n * (1) creates factors according to a distribution\n * (2) creates 2 train matrices\n * (3) creates 1 test file\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\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\tstd::string outDir(\"/tmp/\");\n\n\n\n\t// parameters for the factorization\n\tmf_size_type size1 = 100000; \n\tmf_size_type size2 = 100000; \n\tmf_size_type nnzSmall = 1000000; \n\tmf_size_type nnzTest = 100000; \n\tmf_size_type r = 10;\n\n\n\n\tdouble sigma = sqrt(10); // standard deviation for a Normal distribution N(0,10)\n\n\n\n\t// generate original factors by sampling from a N(0,10) distribution\n\tstd::cout<<\"Generating Solution factors...\"<<std::endl;\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\t//std::cout<<\"Storing Solution factors...\"<<std::endl;\n\t//writeMatrix(outDir+\"solW.mma\",wIn);\n\t//writeMatrix(outDir+\"solH.mma\",hIn);\n\n//\tstd::cout<<\"reading solution factors...\"<<std::endl;\n//\tDenseMatrix wIn;\n//\tDenseMatrixCM hIn;\n//\treadMatrix(inDir+\"solW.mma\",wIn);\n//\treadMatrix(inDir+\"solH.mma\",hIn);\n\n\t// generate a sparse matrices by selecting random entries from the generated factors\n\t// and add small Gaussian noise\n\tSparseMatrix vSmall,vLarge;\n\tstd::cout<<\"Generating Small Matrix...\"<<std::endl;\n\tgenerateRandom(vSmall, nnzSmall, wIn, hIn, random);\n\tstd::cout<<\"adding noise...\"<<std::endl;\n\taddRandom(vSmall, random, boost::normal_distribution<>(0,1)); // the noise distribution is N(0,1)\n\tLOG4CXX_INFO(logger, \"Small Data matrix: \"\n\t\t\t<< vSmall.size1() << \" x \" << vSmall.size2() << \", \" << vSmall.nnz() << \" nonzeros\");\n\tstd::cout<<\"Storing Small Matrix...\"<<std::endl;\n\twriteMatrix(outDir+\"train.mmc\",vSmall);\n\n\n\n\n\t// create a test matrix (without noise)\n\tstd::cout<<\"Generating Test Matrix...\"<<std::endl;\n\tSparseMatrix vTest;\n\tgenerateRandom(vTest, nnzTest, wIn, hIn, random);\n\tLOG4CXX_INFO(logger, \"Test matrix: \"\n\t\t\t<< vTest.size1() << \" x \" << vTest.size2() << \", \" << vTest.nnz() << \" nonzeros\");\n\tstd::cout<<\"Storing Test Matrix...\"<<std::endl;\n\twriteMatrix(outDir+\"test.mmc\",vTest);\n\n\t// generate initial factors by sampling from a uniform[-0.5,0.5] distribution\n\tstd::cout<<\"Generating Initial Factors...\"<<std::endl;\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\tstd::cout<<\"Storing Initial Factors...\"<<std::endl;\n\twriteMatrix(outDir+\"W.mma\",w);\n\twriteMatrix(outDir+\"H.mma\",h);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "bdffe953ba467f17aa2d5f490483c216cce5fd61", "size": 3657, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tools/generateSyntheticData.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": "tools/generateSyntheticData.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": "tools/generateSyntheticData.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": 33.5504587156, "max_line_length": 98, "alphanum_fraction": 0.6994804485, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5249749826402856}}
{"text": "//  Copyright John Maddock 2012.\n//  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 <boost/integer.hpp>\n#include <iostream>\n\nint main()\n{\n std::cout << std::numeric_limits<boost::uint_t<65>::least>::digits;\n return 0;\n}\n", "meta": {"hexsha": "5d96c4b9d36afe3dbbb7991e180736aa1bfd7615", "size": 339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/integer/test/fail_uint_65.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/fail_uint_65.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/fail_uint_65.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": 24.2142857143, "max_line_length": 69, "alphanum_fraction": 0.7138643068, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059609645723, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5249749732460662}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <boost/multi_array.hpp>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\n// ------------------------------------------------------------\n#include \"aux/hash_specializations.hpp\"\n#include \"laguerren_impl.hpp\"\n\nnamespace boltzmann {\n\ntemplate <typename NUMERIC>\nclass LaguerreNKS\n{\n public:\n  typedef NUMERIC numeric_t;\n\n public:\n  LaguerreNKS(int K)\n      : Y_(K + 1)\n      , K_(K)\n      , is_initialized_(false)\n  { }\n\n  void compute(const std::vector<numeric_t>& x);\n\n  /**\n   *\n   * @param x evaluation points\n   * @param n number of evaluation points\n   * @param expw evaluation weight: e^(-r^2*expw)\n   */\n  void compute(const numeric_t* x, unsigned int n, numeric_t expw = numeric_t(0));\n\n  unsigned int get_npoints() const { return Y_[0].shape()[1]; }\n\n public:\n  typedef boost::multi_array<numeric_t, 2> array_t;\n\n public:\n  const NUMERIC* get(unsigned int k, unsigned int alpha) const;\n  void info() const;\n\n private:\n  std::vector<array_t> Y_;\n  unsigned int K_;\n  bool is_initialized_;\n};\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC>\nvoid\nLaguerreNKS<NUMERIC>::compute(const std::vector<numeric_t>& x)\n{\n  compute(x.data(), x.size());\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC>\nvoid\nLaguerreNKS<NUMERIC>::compute(const numeric_t* x, unsigned int n, numeric_t expw)\n{\n  std::vector<numeric_t> x2(n);\n  std::transform(x, x + n, x2.begin(), [](const numeric_t& v) { return v * v; });\n  // L_n-1\n  std::vector<numeric_t> Lnm1(n);\n  // L_n-2\n  std::vector<numeric_t> Lnm2(n);\n\n  for (unsigned int alpha = 0; alpha <= K_; ++alpha) {\n    Y_[alpha].resize(boost::extents[K_ / 2 + 1][n]);\n// init\n#pragma omp parallel for\n    for (size_t xi = 0; xi < n; ++xi) {\n      numeric_t fexp = 1;\n      if (::math::abs(expw) > 1e-16) fexp = ::math::exp(-expw * x2[xi]);\n      Y_[alpha][0][xi] = boost::math::laguerren(0, alpha, x2[xi]) * fexp;\n      Y_[alpha][1][xi] = boost::math::laguerren(1, alpha, x2[xi]) * fexp;\n    }\n\n    for (unsigned int kp = 2; kp <= K_ / 2; ++kp) {\n#pragma omp parallel for\n      for (size_t xi = 0; xi < n; ++xi) {\n        Y_[alpha][kp][xi] = boost::math::laguerren_next(\n            kp - 1, alpha, x2[xi], Y_[alpha][kp - 1][xi], Y_[alpha][kp - 2][xi]);\n      }\n    }\n  }\n\n  boost::multi_array<numeric_t, 2> powers_of_x(boost::extents[K_ + 1][n]);\n\n  for (unsigned int xi = 0; xi < n; ++xi) {\n    powers_of_x[0][xi] = 1.0;\n  }\n\n  for (unsigned int alpha = 1; alpha <= K_; ++alpha) {\n    for (unsigned int xi = 0; xi < n; ++xi) {\n      powers_of_x[alpha][xi] = x[xi] * powers_of_x[alpha - 1][xi];\n    }\n  }\n\n  // add factor x^(2j+k%2)\n  for (unsigned int alpha = 0; alpha <= K_; ++alpha) {\n    for (unsigned int kp = 0; kp <= K_ / 2; ++kp) {\n      int j = alpha / 2;\n      int k = 2 * kp + 2 * j + alpha % 2;\n      for (size_t xi = 0; xi < n; ++xi) {\n        Y_[alpha][kp][xi] *= powers_of_x[2 * j + k % 2][xi];\n      }\n    }\n  }\n\n  is_initialized_ = true;\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC>\nconst NUMERIC*\nLaguerreNKS<NUMERIC>::get(unsigned int k, unsigned int alpha) const\n{\n  assert(is_initialized_);\n  assert(alpha < Y_.size());\n  assert(k < Y_[alpha].shape()[0]);\n  return Y_[alpha][k].origin();\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC>\nvoid\nLaguerreNKS<NUMERIC>::info() const\n{\n  unsigned long long int nentries = 0;\n  for (unsigned int alpha = 0; alpha < Y_.size(); ++alpha) {\n    nentries += Y_[alpha].shape()[0] * Y_[alpha].shape()[1];\n  }\n\n  std::cout << \" LaguerreN uses \" << nentries * sizeof(NUMERIC) / 1e6 << \" MB\" << std::endl;\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "c03c78001d146356203e0053cf3ae354f9ff561b", "size": 3800, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/laguerren_ks.hpp", "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": "src/spectral/laguerren_ks.hpp", "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": "src/spectral/laguerren_ks.hpp", "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": 26.3888888889, "max_line_length": 92, "alphanum_fraction": 0.5486842105, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5249749655876217}}
{"text": "/*\n * Driver for ODE integration\n */\n\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <cassert>\n#include <boost/numeric/odeint.hpp>\n\n#include \"fast_detector_model.hpp\"\n\n/* The type of container used to hold the state vector */\ntypedef std::vector< double > state_type;\n\n/* the type returned by std::vector.size() */\ntypedef std::vector< double >::size_type T_vecsize;\n\n/* copy a carray into a vector */\nstd::vector< double >\ncarray_to_vector(const double *data, int N)\n{\n    std::vector< double > vec;\n    vec.assign(data, data+N);\n    return vec;\n}\n\n\n/* TODO: doc */\nstruct linear_interpolator {\n    double m_timestep;\n    std::vector< double > m_interpolation_values;\n    int m_mode;\n    T_vecsize N;\n\n    linear_interpolator( double timestep, std::vector< double > intvals, int mode) :\n                                    m_timestep(timestep),\n                                    m_interpolation_values(intvals),\n                                    m_mode(mode)\n    {\n        N = intvals.size();\n        /*\n        std::cout << \"linear interpolator init\\n\";\n        for(int ii=0; ii<10; ii++)\n        {\n            std::cout << ii << '\\t' << intvals[ii] << std::endl;\n        }\n        */\n\n    }\n\n    double operator() ( const double t )\n    {\n        double p, i1, i2, w1, w2, r;\n        T_vecsize ii1, ii2;\n        //linear interpolation\n        p = t/m_timestep;\n        if (p <= 0)\n        {\n            r = m_interpolation_values[0];\n        }\n        else if (p >= N-1)\n        {\n            r = m_interpolation_values[N-1];\n        }\n        else\n        {\n            /* piecewise-constant - return Y0 for t < 0 between t0 and t1\n                                           Y1 for t0 <= t < t1 , etc*/\n            if(m_mode == 0)\n            {\n                i1 = floor(p);\n                ii1 = (T_vecsize)i1 + 1;\n                r = m_interpolation_values[ii1];\n            }\n            /* linear interpolation */\n            else if (m_mode == 1)\n            {\n                i1 = floor(p);\n                i2 = ceil(p);\n                w2 = (p-i1);\n                w1 = 1.0-w2;\n                ii1 = (T_vecsize)i1;\n                ii2 = (T_vecsize)i2;\n                /*\n                std::cout << \"p:\" << p << \" t:\" << t << \"i1:\" << i1 << \" i2:\" << i2 << std::endl;\n                std::cout << w1 << \" \" << w2 << std::endl;\n                std::cout << m_interpolation_values[ii1] << \" \" << m_interpolation_values[ii2] << std::endl;\n                */\n                //std::cout << ii1 << \" \" << ii2 << std::endl;\n                r = w1*m_interpolation_values[ii1] + w2*m_interpolation_values[ii2];\n            }\n            /* invalid mode TODO: how to flag the error? */\n            else\n            {\n                assert(false);\n                r = INFINITY;\n            }\n        }\n        return r;\n    }\n};\n\n\n// calculate Na, Nb, Nc from generated code (copied from generated.c)\nvoid calc_NaNbNc(double t, double Nrn, double lamp,\n                 double &Na, double &Nb, double &Nc)\n{\n    using namespace std; //for math functions pow, exp\n    Na = Nrn*lamrn/(lama + lamp) - Nrn*lamrn*exp(-t*(lama + lamp))/(lama +\n            lamp);\n    Nb = Nrn*lama*lamrn/(lama*lamb + pow(lamp, 2) + lamp*(lama + lamb)) -\n            Nrn*lama*lamrn*exp(-t*(lamb + lamp))/(lama*lamb - pow(lamb, 2) +\n            lamp*(lama - lamb)) + Nrn*lama*lamrn*exp(-t*(lama + lamp))/\n            (pow(lama, 2) - lama*lamb + lamp*(lama - lamb));\n    Nc = Nrn*lama*lamb*lamrn/(lama*lamb*lamc + pow(lamp, 3) + pow(lamp, 2)*\n            (lama + lamb + lamc) + lamp*(lama*lamb + lamc*(lama + lamb))) -\n            Nrn*lama*lamb*lamrn*exp(-t*(lamc + lamp))/(lama*lamb*lamc +\n            pow(lamc, 3) - pow(lamc, 2)*(lama + lamb) + lamp*(lama*lamb +\n            pow(lamc, 2) - lamc*(lama + lamb))) + Nrn*lama*lamb*lamrn*\n            exp(-t*(lamb + lamp))/(lama*pow(lamb, 2) - pow(lamb, 3) -\n            lamc*(lama*lamb - pow(lamb, 2)) + lamp*(lama*lamb - pow(lamb, 2)\n            - lamc*(lama - lamb))) - Nrn*lama*lamb*lamrn*exp(-t*(lama + lamp))\n            /(pow(lama, 3) - pow(lama, 2)*lamb - lamc*(pow(lama, 2) - lama*lamb)\n             + lamp*(pow(lama, 2) - lama*lamb - lamc*(lama - lamb)));\n    return;\n}\n\n// Compute the steady-state solution for the state variable Y\n// returns Yss : state_type( [Nrnd, Nrn, Fa, Fb, Fc] )\n\nstate_type calc_steady_state(double Nrn, double Q, double rs, double lamp,\n                      double V_tank, double recoil_prob, double eff)\n{\n    double tt, Na, Nb, Nc, Fa, Fb, Fc;\n    state_type Yss;\n    double Acc_counts;\n    // transit time assuming plug flow in the tank\n    tt = V_tank / Q;\n    calc_NaNbNc(tt, Nrn, lamp, Na, Nb, Nc);\n\n    // expressions based on these lines from detector_state_rate_of_change\n    // dFadt = Q*rs*Na - Fa*lama\n    // dFbdt = Q*rs*Nb - Fb*lamb + Fa*lama * (1.0-recoil_prob)\n    // dFcdt = Q*rs*Nc - Fc*lamc + Fb*lamb\n    Fa = Na*Q*rs/lama;\n    Fb = (Q*rs*Nb + Fa*lama * (1.0-recoil_prob)) / lamb;\n    Fc = (Q*rs*Nc + Fb*lamb) / lamc;\n\n    // accumulated counts, in this case over one second\n    Acc_counts = eff*(Fa*lama + Fc*lamc);\n    // pack output into vector\n    Yss.push_back(Nrn);\n    Yss.push_back(Nrn);\n    Yss.push_back(Nrn);\n    Yss.push_back(Fa);\n    Yss.push_back(Fb);\n    Yss.push_back(Fc);\n    Yss.push_back(Acc_counts);\n    return Yss;\n}\n\n\n\n//[ rhs_class\n/* The rhs of x' = f(x) defined as a class */\nstruct two_filter_detector {\n\n    linear_interpolator m_bc;\n    linear_interpolator m_airt;\n    // parameters\n    double Q;\n    double rs;\n    double lamp;\n    double eff;\n    double Q_external;\n    double V_delay;\n    double V_delay_2;\n    double V_tank;\n    double t_delay;\n    double recoil_prob;\n    double cal_source_strength;\n    double cal_begin;\n    double cal_duration;\n    double inj_source_strength;\n    double inj_begin;\n    double inj_duration;\n\n    two_filter_detector( linear_interpolator bc,\n                         linear_interpolator airt,\n                         double * parameters ) : m_bc(bc), m_airt(airt)\n    {\n        // store parameters\n        Q = *parameters++;\n        rs = *parameters++;\n        lamp = *parameters++;\n        eff = *parameters++;\n        Q_external = *parameters++;\n        V_delay = *parameters++;\n        V_delay_2 = *parameters++;\n        V_tank = *parameters++;\n        t_delay = *parameters++;\n        recoil_prob = *parameters++;\n        cal_source_strength = *parameters++;\n        cal_begin = *parameters++;\n        cal_duration = *parameters++;\n        inj_source_strength = *parameters++;\n        inj_begin = *parameters++;\n        inj_duration = *parameters++;\n\n        /*\n        std::cout << \"Q: \" << Q << std::endl\n                  << \"rs: \" << rs << std::endl\n                  << \"lamp: \" << lamp << std::endl\n                  << \"eff: \" << eff << std::endl\n                  << \"Q_external: \" << Q_external << std::endl\n                  << \"V_delay: \" << V_delay << std::endl\n                  << \"V_delay_2: \" << V_delay_2 << std::endl\n                  << \"V_tank: \" << V_tank << std::endl\n                  << \"t_delay: \" << t_delay << std::endl\n                  << \"recoil_prob: \" << recoil_prob << std::endl;\n        */\n        /*\n        std::cout << \"t/60\\tT\\tdTdt\\tRn\\n\";\n        for (double t=-60; t<600; t+=60)\n        {\n            const double delt = 60;\n            const double T = m_airt(t);\n            double dTdt = (T - m_airt(t-delt)) / delt;\n            std::cout << t/60.0 << '\\t' << T << '\\t' << dTdt << '\\t'\n                      << m_bc(t)\n                      << std::endl;\n        }\n        */\n    }\n\n    void operator() ( const state_type &x , state_type &dxdt , const double t )\n    {\n        double Nrnd, Nrnd2, Nrn, Fa, Fb, Fc;\n        double Nrn_inj; //radon concentration from source injected at inlet\n        double Nrn_cal; //radon concentration from calibration source\n        double dNrnddt, dNrnd2dt, dNrndt, dFadt, dFbdt, dFcdt, dAcc_countsdt;\n        double tt, Na, Nb, Nc;\n        // boundary condition\n        double Nrn_ext = m_bc(t - t_delay);\n        // temperature and temperature change\n        double T = m_airt(t - t_delay);\n        // for computing temerature rate of change by finite-difference\n        const double delt = 60;\n        double dTdt = (T - m_airt(t-t_delay-delt)) / delt;\n        // copied from theoretical_model.py:detector_state_rate_of_change...\n        // unpack state vector\n        Nrnd = x[IDX_Nrnd];\n        Nrnd2 = x[IDX_Nrnd2];\n        Nrn = x[IDX_Nrn];\n        Fa = x[IDX_Fa];\n        Fb = x[IDX_Fb];\n        Fc = x[IDX_Fc];\n        // The radon concentration flowing into the inlet needs to be\n        // bumped up if the injection source is active\n        bool inj_is_active = inj_source_strength > 0.0\n                                && (t - t_delay) > inj_begin\n                                && (t - t_delay) <= inj_begin+inj_duration;\n        if(inj_is_active)\n        {\n            Nrn_inj = inj_source_strength / Q_external;\n        }\n        else\n        {\n            Nrn_inj = 0;\n        }\n\n        // The radon concentration flowing into the main tank needs to be\n        // bumped up if the calibration source is active\n        bool cal_is_active = cal_source_strength > 0.0\n                                && (t - t_delay) > cal_begin\n                                && (t - t_delay) <= cal_begin+cal_duration;\n        if(cal_is_active)\n        {\n            Nrn_cal = cal_source_strength / Q_external;\n        }\n        else\n        {\n            Nrn_cal = 0;\n        }\n\n        // make sure that we can't have V_delay_2 > 0 when V_delay == 0\n        if (V_delay == 0 && V_delay_2 > 0)\n        {\n          V_delay = V_delay_2;\n          V_delay_2 = 0;\n        }\n\n        // effect of delay and tank volumes (allow V_delay to be zero)\n        if (V_delay == 0.0) // no delay tanks\n        {\n            dNrndt = Q_external / V_tank * (Nrn_ext + Nrn_cal + Nrn_inj - Nrn)\n                     - Nrn*lamrn;\n            // Nrnd,Nrnd2 become unimportant, but we need to do something with them\n            // so just apply the same equation as for Nrn\n            dNrnddt = Q_external / V_tank * (Nrn_ext + Nrn_cal + Nrn_inj - Nrnd)\n                      - Nrnd*lamrn;\n            dNrnd2dt = Q_external / V_tank * (Nrn_ext + Nrn_cal + Nrn_inj - Nrnd2)\n                                - Nrnd2*lamrn;\n        }\n        else if (V_delay > 0.0 && V_delay_2 == 0.0) //one delay tank\n        {\n          dNrnddt = Q_external / V_delay * (Nrn_ext + Nrn_inj - Nrnd)\n                                                                - Nrnd*lamrn;\n          dNrndt = Q_external / V_tank * (Nrnd + Nrn_cal - Nrn) - Nrn*lamrn;\n          // unused, but apply same eqn as delay tank 1\n          dNrnd2dt = Q_external / V_delay * (Nrn_ext + Nrn_inj - Nrnd2)\n                                                               - Nrnd2*lamrn;\n        }\n        else // two delay tanks\n        {\n            dNrnddt = Q_external / V_delay * (Nrn_ext + Nrn_inj - Nrnd)\n                                                                  - Nrnd*lamrn;\n            dNrnd2dt = Q_external / V_delay_2 * (Nrnd - Nrnd2) - Nrnd2*lamrn;\n            dNrndt = Q_external / V_tank * (Nrnd2 + Nrn_cal - Nrn) - Nrn*lamrn;\n        }\n\n\n        // effect of temperature changes causing the tank to 'breathe'\n        dNrndt -= Nrnd * dTdt/T;\n        // Na, Nb, Nc from steady-state in tank\n        // transit time assuming plug flow in the tank\n        tt = V_tank / Q;\n        calc_NaNbNc(tt, Nrn, lamp, Na, Nb, Nc);\n        // compute rate of change of each state variable\n        dFadt = Q*rs*Na - Fa*lama;\n        dFbdt = Q*rs*Nb - Fb*lamb + Fa*lama * (1.0-recoil_prob);\n        dFcdt = Q*rs*Nc - Fc*lamc + Fb*lamb;\n        dAcc_countsdt = eff*(Fa*lama + Fc*lamc);\n        // pack into dxdt\n        dxdt[IDX_Nrnd] = dNrnddt;\n        dxdt[IDX_Nrnd2] = dNrnd2dt;\n        dxdt[IDX_Nrn] = dNrndt;\n        dxdt[IDX_Fa] = dFadt;\n        dxdt[IDX_Fb] = dFbdt;\n        dxdt[IDX_Fc] = dFcdt;\n        dxdt[IDX_Acc_counts] = dAcc_countsdt;\n        return;\n    }\n};\n//]\n\n\n//[ integrate_observer\nclass push_back_state_and_time\n{\n    std::vector< state_type >& m_states;\n    std::vector< double >& m_times;\n\n    public:\n    push_back_state_and_time( std::vector< state_type > &states ,\n                              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        // std::cout << t << std::endl;\n    }\n\n    double getval(T_vecsize idx_time, T_vecsize idx_statevec)\n    {\n        return m_states[idx_time][idx_statevec];\n    }\n};\n//]\n\n\n/* Interface function */\nint integrate_radon_detector(int N_times,\n                             double timestep,\n                             int interpolation_mode,\n                             double *external_radon_conc,\n                             double *airt,\n                             double *initial_state,\n                             double *state_history,\n                             double *parameters)\n{\n    using namespace boost::numeric::odeint;\n\n    // initialise the boundary conditions object\n    std::vector< double > intvals;\n    intvals = carray_to_vector(external_radon_conc, N_times);\n    linear_interpolator boundary_conditions(timestep, intvals, interpolation_mode);\n\n    // initialise the air temperature object (always use linear intrpolation)\n    std::vector< double > airt_intvals;\n    airt_intvals = carray_to_vector(airt, N_times);\n    linear_interpolator boundary_conditions_airt(timestep, airt_intvals, 1);\n\n    // copy initial state into a state_type object\n    state_type x0 = carray_to_vector(initial_state, NUM_STATE_VARIABLES);\n    double t0 = 0.0;\n    double t1 = timestep*N_times;\n\n    // initialise the RHS of the system of equations\n    two_filter_detector system_of_equations(boundary_conditions,\n                                            boundary_conditions_airt,\n                                            parameters);\n\n    // initialise the stepper (integrator)\n    // ref: http://www.boost.org/doc/libs/1_57_0/libs/numeric/odeint/doc/html/boost_numeric_odeint/odeint_in_detail/steppers.html\n    // (it would be nicer to use 'auto' for the type, but we'd need extra compiler flags)\n\n    // stepper options: http://www.boost.org/doc/libs/1_57_0/libs/numeric/odeint/doc/html/boost_numeric_odeint/odeint_in_detail/steppers.html#boost_numeric_odeint.odeint_in_detail.steppers.stepper_overview\n\n    //// OPTION 1: dense output stepper (step size can be larger than output grid)\n    //typedef boost::numeric::odeint::result_of::make_dense_output<\n    //    runge_kutta_dopri5< state_type > >::type dense_stepper_type;\n    //dense_stepper_type stepper = make_dense_output( 1.0e-6 , 1.0e-5 ,\n    //                                    runge_kutta_dopri5< state_type >() );\n\n    // OPTION 2: controlled stepper (error is controlled, but dt must be chosen\n    // such that the stepper ends up at exactly the endpoint)\n    typedef boost::numeric::odeint::result_of::make_controlled<\n        runge_kutta_dopri5< state_type > >::type controlled_stepper_type;\n    controlled_stepper_type stepper = make_controlled( 1.0e-6 , 1.0e-5 ,\n                                        runge_kutta_dopri5< state_type >() );\n\n\n\n    //initialise observer (i.e. container for recording output at each step)\n    std::vector< state_type > obs_x_vec;\n    std::vector< double > obs_times_vec;\n    obs_x_vec.reserve(N_times);\n    obs_times_vec.reserve(N_times);\n    push_back_state_and_time observer(obs_x_vec, obs_times_vec);\n\n    // integrate the system of odes\n    // ref: http://www.boost.org/doc/libs/1_57_0/libs/numeric/odeint/doc/html/boost_numeric_odeint/odeint_in_detail/integrate_functions.html\n    boost::numeric::odeint::integrate_const(stepper, system_of_equations,\n                                            x0, t0, t1, timestep, observer);\n\n    //copy the integration history from the observer into the output array\n    double *state_iter = state_history;\n    for (int ii=0; ii<N_times; ii++){\n        for (int jj=0; jj<NUM_STATE_VARIABLES; jj++){\n            *state_iter = observer.getval(ii,jj);\n            state_iter++;\n        }\n    }\n\n    return 0;\n}\n\n\n\n/* Function for testing the linear interpolation class */\ndouble linear_interpolation(double xi, int N, double timestep, const double *y, const int mode)\n{\n    assert(mode == 0 || mode == 1);\n    std::vector< double > intvals;\n    intvals = carray_to_vector(y, N);\n    /*\n    for(int ii=0; ii<N; ii++){\n        std::cout << intvals[ii] << \" \";\n    }\n    std::cout << std::endl;\n    */\n    linear_interpolator li(timestep, intvals, mode);\n    return li(xi);\n}\n", "meta": {"hexsha": "1f341ae9f3bcd1c256288dbe1931730dcf7607a9", "size": 16757, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rddeconv/fast_detector_model.cpp", "max_stars_repo_name": "agriff86/rd-deconvolve", "max_stars_repo_head_hexsha": "6d7772674886fe7391f66d6f89c03aca5e73d226", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rddeconv/fast_detector_model.cpp", "max_issues_repo_name": "agriff86/rd-deconvolve", "max_issues_repo_head_hexsha": "6d7772674886fe7391f66d6f89c03aca5e73d226", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rddeconv/fast_detector_model.cpp", "max_forks_repo_name": "agriff86/rd-deconvolve", "max_forks_repo_head_hexsha": "6d7772674886fe7391f66d6f89c03aca5e73d226", "max_forks_repo_licenses": ["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.7292110874, "max_line_length": 205, "alphanum_fraction": 0.5449066062, "num_tokens": 4556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5249749655876217}}
{"text": "// Copyright (C) 2014 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/estimators/estimate_uncalibrated_relative_pose.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <limits>\n#include <memory>\n#include <vector>\n\n#include \"theia/matching/feature_correspondence.h\"\n#include \"theia/sfm/create_and_initialize_ransac_variant.h\"\n#include \"theia/sfm/pose/eight_point_fundamental_matrix.h\"\n#include \"theia/sfm/pose/essential_matrix_utils.h\"\n#include \"theia/sfm/pose/fundamental_matrix_util.h\"\n#include \"theia/sfm/pose/util.h\"\n#include \"theia/sfm/triangulation/triangulation.h\"\n#include \"theia/solvers/estimator.h\"\n#include \"theia/solvers/sample_consensus_estimator.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\n\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\nnamespace {\n\n// An estimator for computing the relative pose from 8 feature correspondences\n// (via decomposition of the fundamental matrix).\n//\n// NOTE: Feature correspondences must be in pixel coordinates with the principal\n// point removed i.e. principal point at (0, 0). This also assumes negligible\n// skew (which is reasonable for most cameras).\nclass UncalibratedRelativePoseEstimator\n    : public Estimator<FeatureCorrespondence, UncalibratedRelativePose> {\n public:\n  UncalibratedRelativePoseEstimator() {}\n\n  // 8 correspondences are needed to determine a fundamental matrix and thus a\n  // relative pose.\n  double SampleSize() const { return 8; }\n\n  // Estimates candidate relative poses from correspondences.\n  bool EstimateModel(\n      const std::vector<FeatureCorrespondence>& centered_correspondences,\n      std::vector<UncalibratedRelativePose>* relative_poses) const {\n    std::vector<Eigen::Vector2d> image1_points, image2_points;\n    for (int i = 0; i < 8; i++) {\n      image1_points.emplace_back(centered_correspondences[i].feature1);\n      image2_points.emplace_back(centered_correspondences[i].feature2);\n    }\n\n    UncalibratedRelativePose relative_pose;\n    if (!NormalizedEightPointFundamentalMatrix(\n            image1_points, image2_points, &relative_pose.fundamental_matrix)) {\n      return false;\n    }\n\n    // Only consider fundamental matrices that we can decompose focal lengths\n    // from.\n    if (!FocalLengthsFromFundamentalMatrix(\n            relative_pose.fundamental_matrix.data(),\n            &relative_pose.focal_length1,\n            &relative_pose.focal_length2)) {\n      return false;\n    }\n\n    // TODO(cmsweeney): Should we check if the focal lengths are reasonable?\n\n    // Compose the essential matrix from the fundamental matrix and focal\n    // lengths.\n    Matrix3d essential_matrix;\n    EssentialMatrixFromFundamentalMatrix(\n        relative_pose.fundamental_matrix.data(),\n        relative_pose.focal_length1,\n        relative_pose.focal_length2,\n        essential_matrix.data());\n\n    // Normalize the centered_correspondences.\n    std::vector<FeatureCorrespondence> normalized_correspondences(\n        centered_correspondences.size());\n    for (int i = 0; i < centered_correspondences.size(); i++) {\n      normalized_correspondences[i].feature1 =\n          centered_correspondences[i].feature1 / relative_pose.focal_length1;\n      normalized_correspondences[i].feature2 =\n          centered_correspondences[i].feature2 / relative_pose.focal_length2;\n    }\n\n    GetBestPoseFromEssentialMatrix(essential_matrix,\n                                   normalized_correspondences,\n                                   &relative_pose.rotation,\n                                   &relative_pose.position);\n    relative_poses->emplace_back(relative_pose);\n    return true;\n  }\n\n  // The error for a correspondences given a model. This is the squared sampson\n  // error.\n  double Error(const FeatureCorrespondence& centered_correspondence,\n               const UncalibratedRelativePose& relative_pose) const {\n    FeatureCorrespondence normalized_correspondence;\n    normalized_correspondence.feature1 =\n        centered_correspondence.feature1 / relative_pose.focal_length1;\n    normalized_correspondence.feature2 =\n        centered_correspondence.feature2 / relative_pose.focal_length2;\n    if (!IsTriangulatedPointInFrontOfCameras(normalized_correspondence,\n                                             relative_pose.rotation,\n                                             relative_pose.position)) {\n      return std::numeric_limits<double>::max();\n    }\n\n    return SquaredSampsonDistance(relative_pose.fundamental_matrix,\n                                  centered_correspondence.feature1,\n                                  centered_correspondence.feature2);\n  }\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(UncalibratedRelativePoseEstimator);\n};\n\n}  // namespace\n\nbool EstimateUncalibratedRelativePose(\n    const RansacParameters& ransac_params,\n    const RansacType& ransac_type,\n    const std::vector<FeatureCorrespondence>& centered_correspondences,\n    UncalibratedRelativePose* relative_pose,\n    RansacSummary* ransac_summary) {\n  UncalibratedRelativePoseEstimator relative_pose_estimator;\n  std::unique_ptr<SampleConsensusEstimator<UncalibratedRelativePoseEstimator> >\n      ransac = CreateAndInitializeRansacVariant(ransac_type,\n                                                ransac_params,\n                                                relative_pose_estimator);\n\n  // Estimate essential matrix.\n  return ransac->Estimate(centered_correspondences,\n                          relative_pose,\n                          ransac_summary);\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "579fec10320d70fb6582493376c4b99a4dbe8f19", "size": 7223, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/estimators/estimate_uncalibrated_relative_pose.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/estimators/estimate_uncalibrated_relative_pose.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/estimators/estimate_uncalibrated_relative_pose.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.2742857143, "max_line_length": 80, "alphanum_fraction": 0.7193686834, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5249749614827791}}
{"text": "#include <opencv2/highgui/highgui.hpp>\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include <Eigen/Dense>\n#include <Eigen/Core>     // to use Eigen::Map\n#include \"contourDetection.h\"\n#include <iostream>\n#include <cmath>\n#include <fstream>\n\nusing namespace cv;\nusing namespace std;\n\nint canny_thresh = 100;\nImageROI roi = {350, 1100, 400, 1460};\nSegmentationType type(Black);\n\nint main(int argc, char const *argv[])\n{\n  if( argc != 3)  // load 2 images one as target and the another as current\n    {\n     cout <<\" Required two images input \" << endl;\n     return -1;\n    }\n  Mat target;\n  Mat current;\n  target = imread(argv[1], CV_LOAD_IMAGE_COLOR);\n  current = imread(argv[2], CV_LOAD_IMAGE_COLOR);\n  Mat targetContour = ContourDetect(target, type, roi, canny_thresh);\n  ofstream contourdata;\n  contourdata.open(\"contourdata.dat\");\n  contourdata << targetContour;\n  contourdata.close();\n  // sampling\n  int coldata = targetContour.cols;  // column size\n\tint rowdata = targetContour.rows;  // row size\n  Eigen::Map<Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> dataEigen(targetContour.ptr<int>(), rowdata, coldata);\n  double radius = 10.0;\n  int counterMax = 4;\n  int counter = 0;\n  Eigen::MatrixXi sampledata = dataEigen.block<1,2>(0,0);\n  for (int i = 0; i < dataEigen.rows(); ++i)\n  {\n    Eigen::RowVector2i v1 = dataEigen.block<1,2>(i,0) - sampledata.block<1,2>(sampledata.rows() - 1,0);\n    double disToPoint1 = v1.norm();\n    if (disToPoint1 > radius)\n    {\n      bool flag = 0;\n      for (int j = 0; j < sampledata.rows(); ++j)\n      {\n        Eigen::RowVector2i v2 = dataEigen.block<1,2>(i,0) - sampledata.block<1,2>(j,0);\n        double disToPoint2 = v2.norm();\n        if (disToPoint2 < radius)\n        {\n          flag = 1;\n          counter++;\n          break;\n        }\n      }\n      if (flag == 0)\n      {\n        Eigen::MatrixXi temp(sampledata.rows() + dataEigen.block<1,2>(i,0).rows(), sampledata.cols());\n        temp << sampledata, dataEigen.block<1,2>(i,0);\n        sampledata = temp;\n      }\n    }\n    if (counter > counterMax)\n    {\n      break;\n    }\n  }\n  ofstream sample;\n  sample.open(\"sample.dat\");\n  sample << sampledata;\n  sample.close();\n  return 0;\n}\n", "meta": {"hexsha": "6f7d7f8969c33de0efe830de78f48ffe7243510d", "size": 2200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Jihong-Zhu/dloContour", "max_stars_repo_head_hexsha": "3ef1a127e53a4e564b6b512b1df14278e9bcd641", "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": "Jihong-Zhu/dloContour", "max_issues_repo_head_hexsha": "3ef1a127e53a4e564b6b512b1df14278e9bcd641", "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": "Jihong-Zhu/dloContour", "max_forks_repo_head_hexsha": "3ef1a127e53a4e564b6b512b1df14278e9bcd641", "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.5714285714, "max_line_length": 136, "alphanum_fraction": 0.6254545455, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5249749602982452}}
{"text": "#include <tdp/testing/testing.h>\n#include <Eigen/Dense>\n\n#include <gtsam/slam/dataset.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/nonlinear/NonlinearEquality.h>\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/nonlinear/GaussNewtonOptimizer.h>\n#include <gtsam/nonlinear/DoglegOptimizer.h>\n#include <gtsam/nonlinear/ISAM2.h>\n\nTEST(setupRaw, KeyframeSLAM) {\n  gtsam::SharedNoiseModel model = gtsam::noiseModel::Diagonal::Variances(\n        (gtsam::Vector(6) << 1e-2, 1e-2, 1e-2, 1e-2, 1e-2, 1e-2).finished());\n\n  gtsam::Values::shared_ptr initials(new gtsam::Values);\n  gtsam::NonlinearFactorGraph::shared_ptr graph(new gtsam::NonlinearFactorGraph);\n\n  float a = 5.*M_PI/180.;\n  Eigen::Matrix3d Ra;\n  Ra << 1, 0, 0,\n       0, cos(a), -sin(a),\n       0, sin(a), cos(a);\n  a = 6.*M_PI/180.;\n  Eigen::Matrix3d Rb;\n  Rb << 1, 0, 0,\n       0, cos(a), -sin(a),\n       0, sin(a), cos(a);\n  \n  Eigen::Vector3d ta(0,0,1);\n  Eigen::Vector3d tb(0,0,1.1);\n  Eigen::Vector3d tc(0.01,0,1.1);\n\n  // setup Pose3s for GTSAM\n  gtsam::Pose3 poseA = gtsam::Pose3(gtsam::Rot3(Ra),ta);\n  gtsam::Pose3 poseB = gtsam::Pose3(gtsam::Rot3(Rb),tb);\n  gtsam::Pose3 poseC = gtsam::Pose3(gtsam::Rot3(Rb),tc);\n  gtsam::Pose3 poseAB = poseA.between(poseB);\n  gtsam::Pose3 poseAB_obs = poseA.between(poseC);\n\n  initials->insert(0, poseA);\n  initials->insert(1, poseB);\n\n  gtsam::PriorFactor<gtsam::Pose3>::shared_ptr factor0(\n      new gtsam::PriorFactor<gtsam::Pose3>(0, poseA, model));\n  graph->add(factor0);\n  gtsam::NonlinearFactor::shared_ptr factor01(\n      new gtsam::BetweenFactor<gtsam::Pose3>(0, 1, poseAB, model));\n  graph->push_back(factor01);\n  gtsam::NonlinearFactor::shared_ptr factor01_obs(\n      new gtsam::BetweenFactor<gtsam::Pose3>(0, 1, poseAB_obs, model));\n  graph->push_back(factor01_obs);\n\n  graph->print();\n\n  gtsam::GaussNewtonParams params;\n  params.setVerbosity(\"ERROR\"); \n  params.setMaxIterations(1);\n  gtsam::GaussNewtonOptimizer optimizer(*graph, *initials, params);\n  gtsam::Values results = optimizer.optimize();\n}\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "881618d14eee2f3c54b30dc7393c7eb8d7112d22", "size": 2134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/gtsamTest/test/keyframe_slam.cpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "3rdparty/gtsamTest/test/keyframe_slam.cpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "3rdparty/gtsamTest/test/keyframe_slam.cpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 31.8507462687, "max_line_length": 81, "alphanum_fraction": 0.6841611996, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059316231898, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5249749591137106}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_POLYNOMIALS_FUNCTIONS_SCALAR_HERMITE_HPP_INCLUDED\n#define NT2_POLYNOMIALS_FUNCTIONS_SCALAR_HERMITE_HPP_INCLUDED\n\n#include <nt2/polynomials/functions/hermite.hpp>\n#include <nt2/include/functions/scalar/oneplus.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A1 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( hermite_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_< integer_<A0> >)(scalar_< arithmetic_<A1> >)\n                            )\n  {\n\n    typedef typename boost::dispatch::meta::as_floating<A1>::type result_type;\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      return nt2::hermite(a0, result_type(a1));\n    }\n  };\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Implementation when type A1 is floating_\n  /////////////////////////////////////////////////////////////////////////////\n  BOOST_DISPATCH_IMPLEMENT  (hermite_, tag::cpu_,\n                             (A0)(A1),\n                             (scalar_< integer_<A0> > )(scalar_< floating_<A1> > )\n                            )\n  {\n    typedef A1 result_type;\n    NT2_FUNCTOR_CALL(2)\n    {\n      A1 p0 = One<A1>();\n      if(a0 == 0) return p0;\n      A1 p1 = a1+a1;\n      A0 c = 1;\n      while(c < a0)\n      {\n        std::swap(p0, p1);\n        p1 = hermite_next(c, a1, p0, p1);\n        ++c;\n      }\n      return p1;\n    }\n  private:\n    template <class T, class T1, class T2>\n    static inline T\n    hermite_next(const uint32_t& n, const T& x, const T1& Hn, const T2& Hnm1)\n    {\n      return (2 * x * Hn - 2 * n * Hnm1);\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "d1b770fe961293a6e33e4a0b656bae6f48c21844", "size": 2357, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/polynomials/include/nt2/polynomials/functions/scalar/hermite.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/polynomials/include/nt2/polynomials/functions/scalar/hermite.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/polynomials/include/nt2/polynomials/functions/scalar/hermite.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 33.1971830986, "max_line_length": 83, "alphanum_fraction": 0.4586338566, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5249539767054914}}
{"text": "#include <iostream>\n#include <Eigen>\n#include <fstream>\n#include <unistd.h>\n#include <cstdlib>\n#include \"denseBlocksJacobi.h\"\n#include \"denseOverlappingJacobi.h\"\n#include \"denseAsyncBlocksJacobi.h\"\n#include \"denseAsyncOverlappingJacobi.h\"\n#include \"denseAsyncJacobi.h\"\n#include \"denseParallelJacobi.h\"\n#include \"denseSerialJacobi.h\"\n#include \"sparseBlocksJacobi.h\"\n#include \"sparseOverlappingJacobi.h\"\n#include \"sparseAsyncBlocksJacobi.h\"\n#include \"sparseAsyncOverlappingJacobi.h\"\n#include \"sparseAsyncJacobi.h\"\n#include \"sparseParallelJacobi.h\"\n#include \"sparseSerialJacobi.h\"\n#include \"parser.h\"\n#include \"sparseOptimizedBlocksJacobi.h\"\n#include \"sparseOptimizedOverlappingJacobi.h\"\n#include \"denseOptimizedBlocksJacobi.h\"\n#include \"denseOptimizedOverlappingJacobi.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace Iterative;\n\n\nauto fromFile = false;\nauto debug = false;\nauto toCsv = false;\nstring filename;\nstring inputMatrix;\n\nulong matrixSize = 1024;\nulong iterations = 100;\ndouble tolerance = 0.000000001;\nint workers = 8;\nauto blockSize = 64;\n\nconst auto sequential = \"sequential\";\nconst auto parallel = \"parallel\";\nconst auto parallel_async = \"parallel_async\";\nconst auto blocks = \"blocks\";\nconst auto blocks_optimized = \"blocks_optimized\";\nconst auto blocks_async = \"blocks_async\";\nconst auto overlapping = \"overlapping\";\nconst auto overlapping_optimized = \"overlapping_optimized\";\nconst auto overlapping_async = \"overlapping_async\";\n\n\nenum methods {\n    SEQUENTIAL,\n    PARALLEL,\n    PARALLEL_ASYNC,\n    BLOCKS,\n    BLOCKS_OPTIMIZED,\n    BLOCKS_ASYNC,\n    OVERLAPPING,\n    OVERLAPPING_OPTIMIZED,\n    OVERLAPPING_ASYNC\n};\n\nauto method = SEQUENTIAL;\nstring methodString = sequential;\n\nvoid parse_args(int argc, char *argv[]);\nvoid write_csv(string fileName, std::chrono::duration<double> time, double error, long iteration);\n\nint main(int argc, char *argv[]) {\n\n    parse_args(argc, argv);\n\n    Eigen::setNbThreads(workers);\n    auto error = 0.;\n\n    chrono::time_point<chrono::high_resolution_clock> start_time;\n    chrono::time_point<chrono::high_resolution_clock> end_time;\n    ColumnVector<double, Dynamic> x;\n    srand(42);\n\n#ifdef DENSE\n\n\n    Matrix<double, Dynamic, Dynamic> A = Matrix<double, Dynamic, Dynamic>::Random(matrixSize, matrixSize);\n    ColumnVector<double, Dynamic> b = ColumnVector<double, Dynamic>::Random(matrixSize);\n\n#pragma omp parallel for schedule(static)\n    for (int i = 0; i < A.rows(); ++i) {\n        auto value = A.row(i).template lpNorm<1>();\n        A(i, i) = value;\n    }\n\n    denseSerialJacobi<double, Dynamic> serialJacobi(A, b, iterations, tolerance);\n    denseParallelJacobi<double, Dynamic> parallelJacobi(A, b, iterations, tolerance, workers);\n    denseAsyncJacobi<double, Dynamic> asyncJacobi(A, b, iterations, tolerance, workers);\n    denseBlocksJacobi<double, Dynamic> blocksJacobi(A, b, iterations, tolerance, workers, blockSize);\n    denseOptimizedBlocksJacobi<double, Dynamic> optimizedBlocksJacobi(A, b, iterations, tolerance, workers, blockSize);\n    denseOverlappingJacobi<double, Dynamic> overlappingJacobi(A, b, iterations, tolerance, workers, blockSize);\n    denseOptimizedOverlappingJacobi<double, Dynamic> optimizedOverlappingJacobi(A, b, iterations, tolerance, workers, blockSize);\n    denseAsyncBlocksJacobi<double, Dynamic> asyncBlocksJacobi(A, b, iterations, tolerance, workers, blockSize);\n    denseAsyncOverlappingJacobi<double, Dynamic> asyncOverlappingJacobi(A, b, iterations, tolerance, workers, blockSize);\n\n\n#endif\n\n\n#ifdef SPARSE\n\n        SparseMatrix<double>A;\n        if (fromFile){\n            ifstream input(inputMatrix);\n            read_matrix<double>(A, input);\n            input.close();\n\n        } else {\n\n            A.resize(matrixSize, matrixSize);\n            typedef Eigen::Triplet<double> T;\n\n            vector<T> triplets;\n\n            for (int i = 0; i < 100*matrixSize; ++i) {\n                triplets.emplace_back(T(abs(rand())%matrixSize,abs(rand())%matrixSize,(double)rand()*1000/RAND_MAX));\n                if(i<matrixSize)\n                    triplets.emplace_back(T(i,i,(double)rand()*1000/RAND_MAX));\n            }\n\n            A.setFromTriplets(triplets.begin(),triplets.end());\n\n            triplets.clear();\n\n            #pragma omp parallel for schedule(static)\n            for (int i = 0; i < matrixSize; ++i) {\n                auto sum=0.;\n                for (int j = 0; j < matrixSize; ++j) {\n                    sum+=abs(A.coeff(i,j));\n                }\n                A.coeffRef(i,i) = sum;\n            }\n        }\n\n        ColumnVector<double, Dynamic> b = ColumnVector<double, Dynamic>::Zero(A.cols());\n\n        if(!fromFile) b.setRandom();\n\n        sparseSerialJacobi<double> serialJacobi(A, b, iterations, tolerance);\n        sparseParallelJacobi<double> parallelJacobi(A, b, iterations, tolerance, workers);\n        sparseAsyncJacobi<double> asyncJacobi(A, b, iterations, tolerance, workers);\n        sparseBlocksJacobi<double> blocksJacobi(A, b, iterations, tolerance, workers, blockSize);\n        sparseOptimizedBlocksJacobi<double> optimizedBlocksJacobi(A, b, iterations, tolerance, workers, blockSize);\n        sparseOverlappingJacobi<double> overlappingJacobi(A, b, iterations, tolerance, workers, blockSize);\n        sparseOptimizedOverlappingJacobi<double> optimizedOverlappingJacobi(A, b, iterations, tolerance, workers, blockSize);\n        sparseAsyncBlocksJacobi<double> asyncBlocksJacobi(A, b, iterations, tolerance, workers, blockSize);\n        sparseAsyncOverlappingJacobi<double> asyncOverlappingJacobi(A, b, iterations, tolerance, workers, blockSize);\n\n#endif\n\n    auto iterationsPerformed = 0L;\n\n    switch (method){\n\n        case SEQUENTIAL:\n            methodString = sequential;\n            cout << \"Sequential\" << endl;\n            start_time = Time::now();\n            x = serialJacobi.solve();\n            end_time = Time::now();\n            error = (b-A*x).template lpNorm<1>()/matrixSize;\n            cout << \"error: \" << error << endl;\n            std::cout << \"time: \" << ' ' << dsec(end_time - start_time).count() << std::endl;\n            iterationsPerformed = serialJacobi.getIteration();\n            break;\n        case PARALLEL:\n            methodString = parallel;\n            cout << \"Parallel\" << endl;\n            start_time = Time::now();\n            x = parallelJacobi.solve();\n            end_time = Time::now();\n            error = (b - A * x).template lpNorm<1>() / matrixSize;\n            cout << \"error: \" << error << endl;\n            std::cout << \"time: \" << ' ' << dsec(end_time - start_time).count() << std::endl;\n            iterationsPerformed = parallelJacobi.getIteration();\n            break;\n        case PARALLEL_ASYNC:\n            methodString = parallel_async;\n            cout << \"Parallel async\" << endl;\n            start_time = Time::now();\n            x = asyncJacobi.solve();\n            end_time = Time::now();\n            error = (b - A * x).template lpNorm<1>() / matrixSize;\n            cout << \"error: \" << error << endl;\n            std::cout << \"time: \" << ' ' << dsec(end_time - start_time).count() << std::endl;\n            iterationsPerformed = asyncJacobi.getIteration();\n            break;\n        case BLOCKS:\n            methodString = blocks;\n            cout << \"Parallel blocks\" << endl;\n            start_time = Time::now();\n            x = blocksJacobi.solve();\n            end_time = Time::now();\n            error = (b - A * x).template lpNorm<1>() / matrixSize;\n            cout << \"error: \" << error << endl;\n            std::cout << \"time: \" << ' ' << dsec(end_time - start_time).count() << std::endl;\n            iterationsPerformed = blocksJacobi.getIteration();\n\n            break;\n        case BLOCKS_OPTIMIZED:\n            methodString = blocks_optimized;\n            cout << \"Parallel Optimized blocks\" << endl;\n            start_time = Time::now();\n            x = optimizedBlocksJacobi.solve();\n            end_time = Time::now();\n            error = (b - A * x).template lpNorm<1>() / matrixSize;\n            cout << \"error: \" << error << endl;\n            std::cout << \"time: \" << ' ' << dsec(end_time - start_time).count() << std::endl;\n            iterationsPerformed = optimizedBlocksJacobi.getIteration();\n            break;\n        case BLOCKS_ASYNC:\n            methodString = blocks_async;\n            cout << \"Parallel async blocks\" << endl;\n            start_time = Time::now();\n            x = asyncBlocksJacobi.solve();\n            end_time = Time::now();\n            error = (b - A * x).template lpNorm<1>() / matrixSize;\n            cout << \"error: \" << error << endl;\n            std::cout << \"time: \" << ' ' << dsec(end_time - start_time).count() << std::endl;\n            iterationsPerformed = asyncBlocksJacobi.getIteration();\n\n            break;\n        case OVERLAPPING:\n            methodString = overlapping;\n            cout << \"Parallel overlapping\" << endl;\n            start_time = Time::now();\n            x = overlappingJacobi.solve();\n            end_time = Time::now();\n            error = (b - A * x).template lpNorm<1>() / matrixSize;\n            cout << \"error: \" << error << endl;\n            std::cout << \"time: \" << ' ' << dsec(end_time - start_time).count() << std::endl;\n            iterationsPerformed = overlappingJacobi.getIteration();\n            break;\n        case OVERLAPPING_OPTIMIZED:\n            methodString = overlapping_optimized;\n            cout << \"Parallel optimized overlapping\" << endl;\n            start_time = Time::now();\n            x = optimizedOverlappingJacobi.solve();\n            end_time = Time::now();\n            error = (b - A * x).template lpNorm<1>() / matrixSize;\n            cout << \"error: \" << error << endl;\n            std::cout << \"time: \" << ' ' << dsec(end_time - start_time).count() << std::endl;\n            iterationsPerformed = optimizedOverlappingJacobi.getIteration();\n            break;\n        case OVERLAPPING_ASYNC:\n            methodString = overlapping_async;\n            cout << \"Parallel async overlapping blocks\" << endl;\n            start_time = Time::now();\n            x = asyncOverlappingJacobi.solve();\n            end_time = Time::now();\n            error = (b - A * x).template lpNorm<1>() / matrixSize;\n            cout << \"error: \" << error << endl;\n            std::cout << \"time: \" << ' ' << dsec(end_time - start_time).count() << std::endl;\n            iterationsPerformed = asyncOverlappingJacobi.getIteration();\n            break;\n    }\n\n    if(toCsv) write_csv(filename, dsec(end_time - start_time), error, iterationsPerformed);\n\n    if(debug) cout << x.transpose() << endl;\n\n\n//    cerr << \"OK\" << endl;\n\n    return 0;\n\n}\n\nvoid parse_args(int argc,  char *argv[]) {\n\n    string arg(argv[1]);\n    if (arg == sequential) method = SEQUENTIAL;\n    else if (arg == parallel) method = PARALLEL;\n    else if (arg == parallel_async) method = PARALLEL_ASYNC;\n    else if (arg == blocks) method = BLOCKS;\n    else if (arg == blocks_optimized) method = BLOCKS_OPTIMIZED;\n    else if (arg == blocks_async) method = BLOCKS_ASYNC;\n    else if (arg == overlapping) method = OVERLAPPING;\n    else if (arg == overlapping_optimized) method = OVERLAPPING_OPTIMIZED;\n    else if (arg == overlapping_async) method = OVERLAPPING_ASYNC;\n    else exit(1);\n\n    InputParser input(argc,argv);\n\n    if(input.cmdOptionExists(\"-w\")){\n\n        workers = (int) strtol(input.getCmdOption(\"-w\").c_str(), nullptr, 10);\n    }\n\n    if(input.cmdOptionExists(\"-s\")){\n\n        matrixSize = (ulong) strtol(input.getCmdOption(\"-s\").c_str(), nullptr, 10);\n    }\n\n    if(input.cmdOptionExists(\"-i\")){\n\n        iterations = (ulong) strtol(input.getCmdOption(\"-i\").c_str(), nullptr, 10);\n    }\n\n    if(input.cmdOptionExists(\"-t\")){\n\n        tolerance = stod(input.getCmdOption(\"-t\"));\n    }\n\n    if(input.cmdOptionExists(\"-b\")){\n\n        blockSize = (int) strtol(input.getCmdOption(\"-b\").c_str(), nullptr, 10);\n    }\n\n    if(input.cmdOptionExists(\"-p\")){\n        filename = input.getCmdOption(\"-p\");\n        toCsv = true;\n        cout << filename << endl;\n    }\n\n    if(input.cmdOptionExists(\"-d\")){\n        debug = true;\n    }\n\n    if(input.cmdOptionExists(\"-m\")){\n        inputMatrix = input.getCmdOption(\"-m\");\n        fromFile = true;\n    }\n\n}\n\nvoid write_csv(string fileName, std::chrono::duration<double> time, double error, long iteration){\n\n    ifstream test(fileName);\n    auto exists = test.good();\n    test.close();\n    ofstream outFile(fileName, ofstream::out | ofstream::app);\n\n    if(!exists){\n        outFile << \"algorithm,time,iterations,workers,error,size,blockSize\" << endl;\n    }\n\n    outFile << methodString << ',' << time.count() << ',' << iteration <<','<< workers << ',' << error << ','\n            << matrixSize << ',' << blockSize << endl;\n\n}\n", "meta": {"hexsha": "00ff9d567402d4dea47cbfc2328a0a1d967ba0f3", "size": 12761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "DiamonDinoia/parallelIterativeMethods", "max_stars_repo_head_hexsha": "74f1f3dafbb5b06b6ed9de59a234c2d481b38291", "max_stars_repo_licenses": ["MIT"], "max_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": "DiamonDinoia/parallelIterativeMethods", "max_issues_repo_head_hexsha": "74f1f3dafbb5b06b6ed9de59a234c2d481b38291", "max_issues_repo_licenses": ["MIT"], "max_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": "DiamonDinoia/parallelIterativeMethods", "max_forks_repo_head_hexsha": "74f1f3dafbb5b06b6ed9de59a234c2d481b38291", "max_forks_repo_licenses": ["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.2528409091, "max_line_length": 129, "alphanum_fraction": 0.6122560928, "num_tokens": 2999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.524953974446168}}
{"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_SQR_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SQR_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing sqr capabilities\n\n    Computes the square of its parameter.\n\n    @par semantic:\n    For any given value @c x of type @c T:\n\n    @code\n    T r = sqr(x);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    T r = x*x;\n    @endcode\n\n  **/\n  Value sqr(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sqr.hpp>\n#include <boost/simd/function/simd/sqr.hpp>\n\n#endif\n", "meta": {"hexsha": "f602428e4acb0b5625dd879516a90a3a29a51e0c", "size": 989, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sqr.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/sqr.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/sqr.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.0425531915, "max_line_length": 100, "alphanum_fraction": 0.5530839232, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5249539717394057}}
{"text": "//\n// Copyright \u00a9 2019 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include \"ParserFlatbuffersSerializeFixture.hpp\"\n#include \"../Deserializer.hpp\"\n\n#include <string>\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(Deserializer)\n\nstruct InstanceNormalizationFixture : public ParserFlatbuffersSerializeFixture\n{\n    explicit InstanceNormalizationFixture(const std::string &inputShape,\n                                          const std::string &outputShape,\n                                          const std::string &gamma,\n                                          const std::string &beta,\n                                          const std::string &epsilon,\n                                          const std::string &dataType,\n                                          const std::string &dataLayout)\n    {\n        m_JsonString = R\"(\n    {\n        inputIds: [0],\n        outputIds: [2],\n        layers: [\n           {\n            layer_type: \"InputLayer\",\n            layer: {\n                base: {\n                    layerBindingId: 0,\n                    base: {\n                        index: 0,\n                        layerName: \"InputLayer\",\n                        layerType: \"Input\",\n                        inputSlots: [{\n                            index: 0,\n                            connection: {sourceLayerIndex:0, outputSlotIndex:0 },\n                            }],\n                        outputSlots: [{\n                            index: 0,\n                            tensorInfo: {\n                                dimensions: )\" + inputShape + R\"(,\n                                dataType: \")\" + dataType + R\"(\",\n                                quantizationScale: 0.5,\n                                quantizationOffset: 0\n                                },\n                            }]\n                        },\n                    }\n                },\n            },\n        {\n        layer_type: \"InstanceNormalizationLayer\",\n        layer : {\n            base: {\n                index:1,\n                layerName: \"InstanceNormalizationLayer\",\n                layerType: \"InstanceNormalization\",\n                inputSlots: [{\n                        index: 0,\n                        connection: {sourceLayerIndex:0, outputSlotIndex:0 },\n                   }],\n                outputSlots: [{\n                    index: 0,\n                    tensorInfo: {\n                        dimensions: )\" + outputShape + R\"(,\n                        dataType: \")\" + dataType + R\"(\"\n                    },\n                    }],\n                },\n            descriptor: {\n                dataLayout: \")\" + dataLayout + R\"(\",\n                gamma: \")\" + gamma + R\"(\",\n                beta: \")\" + beta + R\"(\",\n                eps: )\" + epsilon + R\"(\n                },\n            },\n        },\n        {\n        layer_type: \"OutputLayer\",\n        layer: {\n            base:{\n                layerBindingId: 0,\n                base: {\n                    index: 2,\n                    layerName: \"OutputLayer\",\n                    layerType: \"Output\",\n                    inputSlots: [{\n                        index: 0,\n                        connection: {sourceLayerIndex:1, outputSlotIndex:0 },\n                    }],\n                    outputSlots: [ {\n                        index: 0,\n                        tensorInfo: {\n                            dimensions: )\" + outputShape + R\"(,\n                            dataType: \")\" + dataType + R\"(\"\n                        },\n                    }],\n                }\n            }},\n        }]\n    }\n)\";\n        SetupSingleInputSingleOutput(\"InputLayer\", \"OutputLayer\");\n    }\n};\n\nstruct InstanceNormalizationFloat32Fixture : InstanceNormalizationFixture\n{\n    InstanceNormalizationFloat32Fixture():InstanceNormalizationFixture(\"[ 2, 2, 2, 2 ]\",\n                                                                       \"[ 2, 2, 2, 2 ]\",\n                                                                       \"1.0\",\n                                                                       \"0.0\",\n                                                                       \"0.0001\",\n                                                                       \"Float32\",\n                                                                       \"NHWC\") {}\n};\n\nBOOST_FIXTURE_TEST_CASE(InstanceNormalizationFloat32, InstanceNormalizationFloat32Fixture)\n{\n    RunTest<4, armnn::DataType::Float32>(\n        0,\n         {\n             0.f,  1.f,\n             0.f,  2.f,\n\n             0.f,  2.f,\n             0.f,  4.f,\n\n             1.f, -1.f,\n            -1.f,  2.f,\n\n            -1.f, -2.f,\n             1.f,  4.f\n        },\n        {\n             0.0000000f, -1.1470304f,\n             0.0000000f, -0.2294061f,\n\n             0.0000000f, -0.2294061f,\n             0.0000000f,  1.6058424f,\n\n             0.9999501f, -0.7337929f,\n            -0.9999501f,  0.5241377f,\n\n            -0.9999501f, -1.1531031f,\n             0.9999501f,  1.3627582f\n        });\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4873fd1d2fab3d1395af12237f858b41d2056031", "size": 5084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/armnnDeserializer/test/DeserializeInstanceNormalization.cpp", "max_stars_repo_name": "Project-Xtended/external_armnn", "max_stars_repo_head_hexsha": "c5e1bbf9fc8ecbb8c9eb073a1550d4c8c15fce94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-09T15:14:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T01:37:53.000Z", "max_issues_repo_path": "src/armnnDeserializer/test/DeserializeInstanceNormalization.cpp", "max_issues_repo_name": "Project-Xtended/external_armnn", "max_issues_repo_head_hexsha": "c5e1bbf9fc8ecbb8c9eb073a1550d4c8c15fce94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/armnnDeserializer/test/DeserializeInstanceNormalization.cpp", "max_forks_repo_name": "Project-Xtended/external_armnn", "max_forks_repo_head_hexsha": "c5e1bbf9fc8ecbb8c9eb073a1550d4c8c15fce94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-23T11:34:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T15:51:37.000Z", "avg_line_length": 32.5897435897, "max_line_length": 90, "alphanum_fraction": 0.352281668, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5249539694800825}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/blas.hpp>\n#include <Eigen/Core>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/eigen/vector.hpp>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include <boost/numeric/bindings/remove_imaginary.hpp>\n#include \"random.hpp\"\n\ntemplate<typename T>\nstruct asum_cl {\n  static T asum(const T &x) {\n    return std::abs(x);\n  }\n};\n\ntemplate<typename T>\nstruct asum_cl<std::complex<T>> {\n  static T asum(const std::complex<T> &x) {\n    return std::abs(x.real())+std::abs(x.imag());\n  }\n};\n\ntemplate<typename Vec>\nint\niamax(const Vec &v) {\n  namespace bindings=boost::numeric::bindings;\n  typedef typename bindings::value_type<Vec>::type value_type;\n  auto i=bindings::begin(v);\n  auto i_end=bindings::end(v);\n  auto i_res=i;\n  for (; i!=i_end; ++i)\n    if (asum_cl<value_type>::asum(*i)>asum_cl<value_type>::asum(*i_res)) \n      i_res=i;\n  return std::distance(bindings::begin(v), i_res);\n}\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\ntypedef double real;\ntypedef std::complex<real> complex;\n\n\nint main(int argc, char *argv[]) {\n  {\n    typedef ublas::vector<real> vector;\n    typedef ublas::matrix<real> matrix;\n    typedef vector::size_type size_type;\n    rand_normal<real>::reset();\n    size_type n=8;\n    vector v(n);\n    for (size_type i=0; i<n; ++i)\n      v(i)=rand_normal<real>::get();\n    std::cout << \"ublas using vectors : iamax(v) = \" << iamax(v) << '\\n'\n\t      << \"blas using vectors  : iamax(v) = \" << blas::iamax(v) << '\\n';\n    matrix M(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i)\n    \tM(i, j)=0;\n    ublas::matrix_column<matrix> mc(M, 2);\n    ublas::matrix_row<matrix> mr(M, 3);\n    mc=v;\n    std::cout << \"blas using cols     : iamax(v) = \" << blas::iamax(mc) << '\\n';\n    mr=v;\n    std::cout << \"blas using rows     : iamax(v) = \" << blas::iamax(mr) << '\\n';\n  }\n  {\n    typedef ublas::vector<complex> vector;\n    typedef ublas::matrix<complex> matrix;\n    typedef vector::size_type size_type;\n    rand_normal<complex>::reset();\n    size_type n=8;\n    vector v(n);\n    for (size_type i=0; i<n; ++i)\n      v(i)=rand_normal<complex>::get();\n    std::cout << \"ublas using vectors : iamax(v) = \" << iamax(v) << '\\n'\n\t      << \"blas using vectors  : iamax(v) = \" << blas::iamax(v) << '\\n';\n    matrix M(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i)\n    \tM(i, j)=0;\n    ublas::matrix_column<matrix> mc(M, 2);\n    ublas::matrix_row<matrix> mr(M, 3);\n    mc=v;\n    std::cout << \"blas using cols     : iamax(v) = \" << blas::iamax(mc) << '\\n';\n    mr=v;\n    std::cout << \"blas using rows     : iamax(v) = \" << blas::iamax(mr) << '\\n';\n  }\n  {\n    typedef Eigen::Matrix<real, Eigen::Dynamic, 1> vector;\n    typedef Eigen::Matrix<real, Eigen::Dynamic, Eigen::Dynamic> matrix;\n    typedef int size_type;\n    rand_normal<real>::reset();\n    size_type n=8;\n    vector v(n);\n    for (size_type i=0; i<n; ++i)\n      v(i)=rand_normal<real>::get();\n    std::cout << \"eigen using vectors : iamax(v) = \" << iamax(v) << '\\n'\n\t      << \"blas using vectors  : iamax(v) = \" << blas::iamax(v) << '\\n';\n    matrix M(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i)\n    \tM(i, j)=0;\n    auto mc=M.col(2);\n    auto mr=M.row(3);\n    mc=v;\n    std::cout << \"blas using cols     : iamax(v) = \" << blas::iamax(mc) << '\\n';\n    mr=v;\n    std::cout << \"blas using rows     : iamax(v) = \" << blas::iamax(mr) << '\\n';\n  }\n  {\n    typedef Eigen::Matrix<complex, Eigen::Dynamic, 1> vector;\n    typedef Eigen::Matrix<complex, Eigen::Dynamic, Eigen::Dynamic> matrix;\n    typedef int size_type;\n    rand_normal<complex>::reset();\n    size_type n=8;\n    vector v(n);\n    for (size_type i=0; i<n; ++i)\n      v(i)=rand_normal<complex>::get();\n    std::cout << \"eigen using vectors : iamax(v) = \" << iamax(v) << '\\n'\n\t      << \"blas using vectors  : iamax(v) = \" << blas::iamax(v) << '\\n';\n    matrix M(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i)\n    \tM(i, j)=0;\n    auto mc=M.col(2);\n    auto mr=M.row(3);\n    mc=v;\n    std::cout << \"blas using cols     : iamax(v) = \" << blas::iamax(mc) << '\\n';\n    mr=v;\n    std::cout << \"blas using rows     : iamax(v) = \" << blas::iamax(mr) << '\\n';\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "48052d198b3f800bbb3cd2c75e5cc2a84e7b6e4c", "size": 4653, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/iamax.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/iamax.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/iamax.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.3125, "max_line_length": 80, "alphanum_fraction": 0.5918762089, "num_tokens": 1491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5249539694800825}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_CONSTANT_CONSTANTS_SQRT_2O_3_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_CONSTANTS_SQRT_2O_3_HPP_INCLUDED\n\n#include <boost/simd/include/functor.hpp>\n#include <boost/simd/constant/register.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n   /*!\n     @brief Sqrt_2o_3 generic tag\n\n     Represents the Sqrt_2o_3 constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    BOOST_SIMD_CONSTANT_REGISTER( Sqrt_2o_3, double, 0\n                                , 0x3f5105ec, 0x3fea20bd700c2c3ell\n                                )\n  }\n  namespace ext\n  {\n   template<class Site, class... Ts>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Sqrt_2o_3, Site> dispatching_Sqrt_2o_3(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n   {\n     return generic_dispatcher<tag::Sqrt_2o_3, Site>();\n   }\n   template<class... Args>\n   struct impl_Sqrt_2o_3;\n  }\n\n  /*!\n    Generates value \\f$\\frac{\\sqrt2}3\\f$\n\n    @par Semantic:\n\n    @code\n    T r = Sqrt_2o_3<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = T(sqrt(as_floating<T>(2)))/T(3);\n    @endcode\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(boost::simd::tag::Sqrt_2o_3, Sqrt_2o_3)\n} }\n\n#include <boost/simd/constant/common.hpp>\n\n#endif\n", "meta": {"hexsha": "757b5dac17a5a4d245adf610307c39007d604dad", "size": 1823, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/constant/constants/sqrt_2o_3.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/boost/simd/base/include/boost/simd/constant/constants/sqrt_2o_3.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/boost/simd/base/include/boost/simd/constant/constants/sqrt_2o_3.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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.0461538462, "max_line_length": 174, "alphanum_fraction": 0.5957213385, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5249539694800825}}
{"text": "#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file\n\n// std\n#include <iostream>\n#include <stdexcept>\n#include <algorithm>\n#include <utility>\n#include <memory>\n#include <chrono>\n#include <random>\n#include <catch2/catch.hpp>\n#include <GridPoint.hpp>\n#include <SHRS.hpp>\n\n// PCL\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n\n// Eigen\n#include <Eigen/Dense>\n\nusing namespace fsd;\n\nusing std::string;\nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::iota;\nusing std::numeric_limits;\nusing std::random_device;\nusing std::mt19937;\nusing std::uniform_real_distribution;\nusing std::uniform_int_distribution;\nusing std::unique_ptr;\nusing Eigen::Vector2d;\n\n/*\n * @brief get_random_coordinates generates num number of unique and\n * uniform distributed random coordinates in the range of width and height,\n * in O(n) time with knuth-fisher-yates shuffling\n * can be optimized further for num > (width * heigh - 1) / 2\n * @param width\n * @param height\n * @param num num of random coords\n * @return vector with positions\n */\nvector<GridPoint> generate_random_coordinates\n(GridPoint area_min, GridPoint area_max, size_t num) {\n    size_t width = std::abs(area_max.get_column() - area_min.get_column());\n    size_t height = std::abs(area_max.get_row() - area_min.get_row());\n    if(width == 0 || height == 0) {\n        throw std::logic_error(\"width or height cannot be zero\");\n    }\n    size_t max_val = width * height - 1;\n    if(max_val <= num) {\n        throw std::logic_error(\"number if random positions is bigger \"\n                               \" or equal than max possible\");\n    }\n    random_device rd;\n    mt19937 eng(rd());\n    vector<size_t> vals;\n    vector<GridPoint> positions;\n    vals.reserve(max_val + 1);\n    positions.reserve(num);\n    iota (begin(vals), end(vals), 0);\n    while(num) {\n        uniform_int_distribution<> u_distr(0, max_val);\n        auto rnd_number = u_distr(eng);\n        auto val_at_rnd = vals[rnd_number];\n        vals[rnd_number] = vals[max_val];\n        vals[max_val] = val_at_rnd;\n        auto x = val_at_rnd % width;\n        auto y = val_at_rnd / width;\n        positions.emplace_back(GridPoint(x, y));\n        max_val--;\n        num--;\n    }\n    return positions;\n}\n\n/**\n *@brief adaptor for pointclouds\n */\ntemplate <typename point_t>\nclass PCLSHRSAdaptor {\npublic:\n    using key_t = size_t;\n    using data = pcl::PointCloud<point_t>;\n    data const &pcl_ref;\n\n    PCLSHRSAdaptor\n    (data const &pcl_ref_) :\n        pcl_ref(pcl_ref_) {\n    }\n\n    inline Vector2d get_point(size_t i_point) const {\n        auto const &pnt = pcl_ref.at(i_point);\n        return { pnt.x, pnt.y };\n    }\n\n    inline void for_all_keys(std::function<void(key_t)> func) const {\n        for(size_t i = 0; i < pcl_ref.size(); i++) {\n            func(i);\n        }\n    }\n\n    inline bool find_point(size_t i_point) const {\n        return i_point < pcl_ref.size();\n    }\n\n    inline size_t size() const {\n        return pcl_ref.size();\n    }\n};\n\ndouble bench_shrs(const double search_radius_pcl,\n                  const Vector2d test_area_min_pcl,\n                  const Vector2d test_area_max_pcl,\n                  const size_t num_test_points_pcl,\n                  const size_t points_to_search_pcl) {\n    random_device rd;\n    mt19937 eng(rd());\n\n    using point_t = pcl::PointXYZ;\n    pcl::PointCloud<point_t> test_pcl;\n\n    SHRS<PCLSHRSAdaptor<point_t>> shrs_map(\n                PCLSHRSAdaptor<point_t>(test_pcl),\n                search_radius_pcl);\n\n    bool gen_new_cloud = true;\n    bool rw_cloud = false;\n    pcl::PointCloud<pcl::PointXYZ>::Ptr read_cloud\n            (new pcl::PointCloud<pcl::PointXYZ>);\n    if (pcl::io::loadPCDFile<pcl::PointXYZ>\n            (\"/home/hsa/shrs_test_pcl.pcd\", *read_cloud) == -1\n            || gen_new_cloud) {\n        // create new\n        cout << \"could not read cloud, creating new: \";\n        uniform_real_distribution<> dis_x(test_area_min_pcl.x(),\n                                          test_area_max_pcl.x());\n        uniform_real_distribution<> dis_y(test_area_min_pcl.y(),\n                                          test_area_max_pcl.y());\n        // to save\n        pcl::PointCloud<pcl::PointXYZ> save_cloud;\n        save_cloud.width = 10;\n        save_cloud.height = 100;\n        save_cloud.is_dense = false;\n        save_cloud.points.resize(num_test_points_pcl);\n        for(size_t n = 0; n < num_test_points_pcl; n++) {\n            pcl::PointXYZ tmp;\n            auto rnd_x = dis_x(eng);\n            auto rnd_y = dis_y(eng);\n            tmp.x = rnd_x;\n            tmp.y = rnd_y;\n            tmp.z = 0.;\n            save_cloud[n].x = tmp.x;\n            save_cloud[n].y = tmp.y;\n            save_cloud[n].z = 0;\n\n            test_pcl.push_back(tmp);\n        }\n        if(rw_cloud) {\n            pcl::io::savePCDFileASCII (\"/home/hsa/shrs_test_pcl.pcd\", save_cloud);\n        }\n    } else {\n        cout << \"read cloud from disk \" << \"\\n\"\"\";\n        test_pcl = *read_cloud;\n    }\n\n    auto begin_insert = std::chrono::steady_clock::now();\n\n    shrs_map.insert_all();\n\n    auto end_insert = std::chrono::steady_clock::now();\n    auto insert_span = std::chrono::duration <double, std::milli>\n            (end_insert - begin_insert).count();\n    cout << \"inserting \" << num_test_points_pcl << \" points took \" << insert_span\n         << \" ms \" << \"\\n\";\n\n    uniform_int_distribution<> u_distr_pcl(0, num_test_points_pcl - 1);\n    double avg_neigbours = 0;\n    double max_find = -std::numeric_limits<double>::infinity();\n    double min_find =  std::numeric_limits<double>::infinity();\n    double avg_find = 0;\n    for(size_t iRndPoint = 0; iRndPoint < points_to_search_pcl; iRndPoint++) {\n        bool random_idx = false;\n        size_t rnd_index = 0;\n        if(random_idx) {\n            rnd_index = u_distr_pcl(eng);\n        } else {\n            rnd_index = iRndPoint;\n        }\n        auto rnd_pnt = test_pcl[rnd_index];\n        vector<size_t> neighbours_shrs;\n        vector<size_t> neighbours_reference;\n\n        auto begin_find = std::chrono::steady_clock::now();\n\n        shrs_map.find_neighbours(rnd_index,\n                                 neighbours_shrs);\n\n        auto end_find = std::chrono::steady_clock::now();\n        double find_span = std::chrono::duration <double, std::milli>\n                (end_find - begin_find).count();\n\n        max_find = std::max(max_find, find_span);\n        min_find = std::min(min_find, find_span);\n        avg_find += find_span;\n        avg_neigbours += (double)neighbours_shrs.size();\n\n        sort(begin(neighbours_shrs), end(neighbours_shrs));\n\n        for(size_t iOtherPoint = 0; iOtherPoint < num_test_points_pcl; iOtherPoint++) {\n            if(iOtherPoint == rnd_index) {\n                continue;\n            }\n            Vector2d  rnd_pnt_vec = { rnd_pnt.x, rnd_pnt.y };\n            Vector2d  test_pcl_pnt_vec = { test_pcl[iOtherPoint].x,\n                                           test_pcl[iOtherPoint].y };\n            if((rnd_pnt_vec - test_pcl_pnt_vec).norm() <\n                    (search_radius_pcl)) {\n                neighbours_reference.push_back(iOtherPoint);\n            }\n        }\n        sort(begin(neighbours_reference), end(neighbours_reference));\n        if(neighbours_reference != neighbours_shrs) {\n            cout << \"found different neigbours \";\n        }\n        REQUIRE(neighbours_reference == neighbours_shrs);\n    }\n\n    avg_neigbours /= static_cast<double>(points_to_search_pcl);\n    avg_find /= static_cast<double>(points_to_search_pcl);\n    cout << \"found \" << avg_neigbours << \" neighbours on average,\"\n                                         \" one neighbour search took on average \"\n         << avg_find << \" ms, max \" << max_find << \" ms and min \"\n         << min_find << \" ms\" << endl;\n\n\n    // benchmark of adjacency matrix\n    unordered_map<size_t, vector<size_t>> adj_matrix;\n    auto begin_adj = std::chrono::steady_clock::now();\n\n    unique_ptr<SHRS<PCLSHRSAdaptor<point_t>>> bench_map =\n            unique_ptr<SHRS<PCLSHRSAdaptor<point_t>>>\n                                                    (new SHRS<PCLSHRSAdaptor<point_t>>(PCLSHRSAdaptor<point_t>(test_pcl),\n                                                                                       search_radius_pcl, &adj_matrix));\n\n    auto end_adj = std::chrono::steady_clock::now();\n    double adj_span = std::chrono::duration <double, std::milli>\n            (end_adj - begin_adj).count();\n\n    cout << \"calculating adjacency list of \" << num_test_points_pcl\n         << \" points with \" << avg_neigbours\n         << \" neighbours on average took \" << adj_span << \" ms\" << endl;\n    return adj_span;\n}\n\nTEST_CASE(\"shrs insert and search neigbours with pcl adaptor\") {\n\n    vector<size_t> point_sizes_to_test = { 100, 1000, 10000, 100000 };\n    vector<size_t> avg_neighbours_to_test = { 3, 7, 10, 20, 30, 50 };\n\n    vector<vector<double>> times;\n    auto const search_radius = 25.;\n    for(auto size : point_sizes_to_test) {\n        for(auto avg_neighbours : avg_neighbours_to_test) {\n            auto area_side_len = std::sqrt(M_PI * std::pow(search_radius, 2.)\n                                           * size\n                                           / static_cast<double>(avg_neighbours));\n            // to test also around the midpoint\n            auto min_pnt = Vector2d(-(area_side_len / 2.),\n                                    -(area_side_len / 2.));\n            auto max_pnt = Vector2d(area_side_len / 2., area_side_len / 2.);\n\n            cout << \"min_pnt: x: \" << min_pnt.x() << \", y: \" << min_pnt.y()\n                 << \"max_pnt: x: \" << max_pnt.x() << \", y: \" << max_pnt.y();\n            auto time_to_calc\n                    = bench_shrs(search_radius, min_pnt, max_pnt, size,\n                                 static_cast<size_t>(std::sqrt(size)));\n            times.push_back({static_cast<double>(size),\n                              static_cast<double>(avg_neighbours),\n                              static_cast<double>(time_to_calc) });\n        }\n    }\n\n    cout << \"times: \\n\";\n\n    for(auto const &time_struct : times) {\n        cout << \"size: \" << time_struct[0] << \", \"\n             << \"avg_neighbours: \" << time_struct[1] << \", \"\n             << \"time: \" << time_struct[2] << \" ms\\n\";\n    }\n}\n\n\n", "meta": {"hexsha": "e0cd48bacf043f4fbd31055ddec5da90e91af02c", "size": 10300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/SHRSTest.cpp", "max_stars_repo_name": "iv461/spatial_hashing", "max_stars_repo_head_hexsha": "639295a47e74285046c9a15e6c37039916901ae3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-26T23:16:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-26T23:16:37.000Z", "max_issues_repo_path": "test/SHRSTest.cpp", "max_issues_repo_name": "iv461/spatial_hashing", "max_issues_repo_head_hexsha": "639295a47e74285046c9a15e6c37039916901ae3", "max_issues_repo_licenses": ["MIT"], "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/SHRSTest.cpp", "max_forks_repo_name": "iv461/spatial_hashing", "max_forks_repo_head_hexsha": "639295a47e74285046c9a15e6c37039916901ae3", "max_forks_repo_licenses": ["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.5637583893, "max_line_length": 121, "alphanum_fraction": 0.5816504854, "num_tokens": 2549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.524953964513997}}
{"text": "#ifndef TVMTL_MANIFOLD_GRASSMANN_HPP\n#define TVMTL_MANIFOLD_GRASSMANN_HPP\n\n#include <cmath>\n#include <complex>\n#include <iostream>\n#include <functional>\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/SVD>\n#include <Eigen/QR>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <unsupported/Eigen/KroneckerProduct>\n\n//own includes\n#include \"enumerators.hpp\"\n#include \"matrix_utils.hpp\"\n\nnamespace tvmtl {\n\n// Specialization GRASSMANN\ntemplate <int N, int P>\nstruct Manifold< GRASSMANN, N, P> {\n    \n    public:\n\tstatic const MANIFOLD_TYPE MyType;\n\tstatic const int manifold_dim ;\n\tstatic const int value_dim; // TODO: maybe rename to embedding_dim \n\n\tstatic const bool non_isometric_embedding;\n\t\n\t// Scalar type of manifold\n\t//typedef double scalar_type;\n\ttypedef double scalar_type;\n\ttypedef double dist_type;\n\ttypedef std::complex<double> complex_type;\n\ttypedef std::vector<double> weight_list; \n\n\t// Value Typedef\n\ttypedef Eigen::Matrix< scalar_type, N, P>\t\t\t\tvalue_type;\n\ttypedef value_type&\t\t\t\t\t\t\tref_type;\n\ttypedef const value_type&\t\t\t\t\t\tcref_type;\n\ttypedef std::vector<value_type, Eigen::aligned_allocator<value_type> >\tvalue_list; \n\t\n\t// Tangent space typedefs\n\ttypedef Eigen::Matrix <scalar_type, N * P, P * (N - P) > tm_base_type;\n\ttypedef tm_base_type& tm_base_ref_type;\n\n\t// Derivative Typedefs\n\ttypedef value_type\t\t\t     deriv1_type;\n\ttypedef deriv1_type&\t\t\t     deriv1_ref_type;\n\t\n\ttypedef Eigen::Matrix<scalar_type, N*P, N*P>\t\t\t\tderiv2_type;\n\ttypedef deriv2_type&\t\t\t\t\t\t\tderiv2_ref_type;\n\ttypedef\tEigen::Matrix<scalar_type, P * (N - P), P * (N - P) >\t\trestricted_deriv2_type;\n\n\t// Helper Types\n\ttypedef Eigen::PermutationMatrix<N * P, N * P, int> perm_type;\n\n\tinline static perm_type ConstructPermutationMatrix();\n\n\t// Manifold distance functions (for IRLS)\n\tinline static dist_type dist_squared(cref_type x, cref_type y);\n\tinline static dist_type distPF_squared(cref_type x, cref_type y );\n\tinline static dist_type distGeod_squared( cref_type x, cref_type y );\n\n\tinline static void deriv1x_dist_squared(cref_type x, cref_type y, deriv1_ref_type result);\n\tinline static void deriv1y_dist_squared(cref_type x, cref_type y, deriv1_ref_type result);\n\n\tinline static void deriv2xx_dist_squared(cref_type x, cref_type y, deriv2_ref_type result);\n\tinline static void deriv2xy_dist_squared(cref_type x, cref_type y, deriv2_ref_type result);\n\tinline static void deriv2yy_dist_squared(cref_type x, cref_type y, deriv2_ref_type result);\n\n\tstatic const perm_type permutation_matrix;\n\n\t// Manifold exponentials und logarithms ( for Proximal point)\n\ttemplate <typename DerivedX, typename DerivedY>\n\tinline static void exp(const Eigen::MatrixBase<DerivedX>& x, const Eigen::MatrixBase<DerivedY>& y, Eigen::MatrixBase<DerivedX>& result);\n\tinline static void log(cref_type x, cref_type y, ref_type result);\n\t\n\tinline static void convex_combination(cref_type x, cref_type y, double t, ref_type result);\n\n\t// Implementations of the Karcher mean\n\t// Slow list version\n\tinline static void karcher_mean(ref_type x, const value_list& v, double tol=1e-10, int maxit=15);\n\tinline static void weighted_karcher_mean(ref_type x, const weight_list& w, const value_list& v, double tol=1e-10, int maxit=15);\n\t// Variadic templated version\n\ttemplate <typename V, class... Args>\n\tinline static void karcher_mean(V& x, const Args&... args);\n\ttemplate <typename V>\n\tinline static void variadic_karcher_mean_gradient(V& x, const V& y);\n\ttemplate <typename V, class... Args>\n\tinline static void variadic_karcher_mean_gradient(V& x, const V& y1, const Args&... args);\n\n\t// Basis transformation for restriction to tangent space\n\tinline static void tangent_plane_base(cref_type x, tm_base_ref_type result);\n\t\n\t// Projections\n\tinline static void horizontal_space_projector(cref_type x, ref_type a);\n\tinline static void projector(ref_type x);\n\n\t// Interpolation pre- and postprocessing\n\tinline static void interpolation_preprocessing(ref_type x) {};\n\tinline static void interpolation_postprocessing(ref_type x) {};\n\n};\n\n\n/*-----IMPLEMENTATION GRASSMANN----------*/\n\n// Static constants, Outside definition to avoid linker error\n\ntemplate <int N, int P>\nconst MANIFOLD_TYPE Manifold <GRASSMANN, N, P>::MyType = GRASSMANN; \n\ntemplate <int N, int P>\nconst int Manifold <GRASSMANN, N, P>::manifold_dim = (N - P) * P; \n\ntemplate <int N, int P>\nconst int Manifold <GRASSMANN, N, P>::value_dim = N * P; \n\ntemplate <int N, int P>\nconst bool Manifold <GRASSMANN, N, P>::non_isometric_embedding = false; \n\n// PermutationMatrix\ntemplate <int N, int P>\ntypename Manifold < GRASSMANN, N, P>::perm_type Manifold<GRASSMANN, N, P>::ConstructPermutationMatrix(){\n    \n    Eigen::Matrix<int, N * P, 1> indices;\n    indices.setZero();\n\n    int inc = 0;\n    for(int i=1; i< indices.size(); ++i){\n\tif(i % 2 == 0)\n\t    inc = -P;\n\telse\n\t    inc = N;\n\tindices(i) = indices(i-1) + inc;\n    }\n    \n    perm_type Perm(indices);\n    return Perm.transpose();\n}\n\ntemplate <int N, int P>\nconst typename Manifold < GRASSMANN, N, P>::perm_type Manifold<GRASSMANN, N, P>::permutation_matrix = ConstructPermutationMatrix(); \n\n\n// Squared GRASSMANN distance function\ntemplate <int N, int P>\ninline typename Manifold <GRASSMANN, N, P>::dist_type Manifold <GRASSMANN, N, P>::dist_squared( cref_type x, cref_type y ){\n    return distPF_squared(x,y); \n}\n\ntemplate <int N, int P>\ninline typename Manifold <GRASSMANN, N, P>::dist_type Manifold <GRASSMANN, N, P>::distGeod_squared( cref_type x, cref_type y ){\n    \n    // Geodesic distance\n     Eigen::JacobiSVD<Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> > svd(x.transpose() * y, Eigen::ComputeThinU | Eigen::ComputeThinV);\n     Eigen::Matrix<scalar_type, P, 1> sv= svd.singularValues();\n     for(int i=0; i<P; ++i){\n\tif(sv(i)>=1.0)\n\t    sv(i)=0;\n\telse if(sv(i)<=-1.0)\n\t    sv(i)=M_PI;\n\telse \n\t    sv(i)=std::acos(sv(i));\n    }\n    #ifdef TVMTL_MANIFOLD_DEBUG_GRASSMANN\n     std::cout << sv << std::endl;\n    #endif\n \n    return sv.squaredNorm();\n\n}\n\ntemplate <int N, int P>\ninline typename Manifold <GRASSMANN, N, P>::dist_type Manifold <GRASSMANN, N, P>::distPF_squared( cref_type x, cref_type y ){\n    \n    // Projection F-distance;\n    return 0.5 * (x * x.transpose() - y * y.transpose()).squaredNorm();\n}\n\n// Derivative of Squared GRASSMANN distance w.r.t. first argument\ntemplate <int N, int P>\ninline void Manifold <GRASSMANN, N, P>::deriv1x_dist_squared( cref_type x, cref_type y, deriv1_ref_type result){\n    result = 2.0 * (x * x.transpose() - y * y.transpose()) * x;\n}\n// Derivative of Squared GRASSMANN distance w.r.t. second argument\ntemplate <int N, int P>\ninline void Manifold <GRASSMANN, N, P>::deriv1y_dist_squared( cref_type x, cref_type y, deriv1_ref_type result){\n    result = 2.0 * (y * y.transpose() - x * x.transpose()) * y;\n}\n\n\n// Second Derivative of Squared GRASSMANN distance w.r.t first argument\ntemplate <int N, int P>\ninline void Manifold <GRASSMANN, N, P>::deriv2xx_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    deriv2_type XtXId, IdXXtmYYt, XtXP;\n    XtXId = Eigen::kroneckerProduct(x.transpose() * x, Eigen::Matrix<scalar_type, N, N>::Identity());\n    IdXXtmYYt = Eigen::kroneckerProduct(Eigen::Matrix<scalar_type, P, P>::Identity(), x * x.transpose() - y * y.transpose());\n    XtXP = Eigen::kroneckerProduct(x.transpose(), x) * permutation_matrix;\n    result = 2.0 * (XtXId + XtXP + IdXXtmYYt);\n}\n// Second Derivative of Squared GRASSMANN distance w.r.t first and second argument\ntemplate <int N, int P>\ninline void Manifold <GRASSMANN, N, P>::deriv2xy_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    result = -2.0 * (Eigen::kroneckerProduct(x.transpose() * y, Eigen::Matrix<scalar_type, N, N>::Identity()) + Eigen::kroneckerProduct(x.transpose(), y) * permutation_matrix);\n}\n// Second Derivative of Squared GRASSMANN distance w.r.t second argument\ntemplate <int N, int P>\ninline void Manifold <GRASSMANN, N, P>::deriv2yy_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    deriv2xx_dist_squared(y, x, result);\n}\n\n\n\n// Exponential and Logarithm Map\ntemplate <int N, int P>\ntemplate <typename DerivedX, typename DerivedY>\ninline void Manifold <GRASSMANN, N, P>::exp(const Eigen::MatrixBase<DerivedX>& x, const Eigen::MatrixBase<DerivedY>& y, Eigen::MatrixBase<DerivedX>& result){\n    Eigen::JacobiSVD<Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> > svd(y, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    value_type temp_result = x * svd.matrixV() * svd.singularValues().array().cos().matrix().asDiagonal() * svd.matrixV().transpose() + svd.matrixU() * svd.singularValues().array().sin().matrix().asDiagonal() * svd.matrixV().transpose();\n    // Reorthonormalization\n    Eigen::HouseholderQR<value_type> qr(temp_result);\n    result = qr.householderQ() * value_type::Identity();\n}\n\ntemplate <int N, int P>\ninline void Manifold <GRASSMANN, N, P>::log(cref_type x, cref_type y, ref_type result){\n    Eigen::Matrix<scalar_type, P, P> YtX = y.transpose() * x;\n    Eigen::Matrix<scalar_type, P, N> At = y.transpose() - YtX * x.transpose();\n\n    value_type B = YtX.householderQr().solve(At).transpose();\n\n    Eigen::JacobiSVD<Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> > svd(B, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    \n    #ifdef TVMTL_MANIFOLD_DEBUG_GRASSMANN\n        std::cout << \"\\n\\nB\\n\" << B << std::endl;\n\tstd::cout << \"U\\n\" << svd.matrixU() << std::endl;\n\tstd::cout << \"S\\n\" << svd.singularValues() << std::endl;\n\tstd::cout << \"Vt\\n\" << svd.matrixV().transpose() << std::endl;\n    #endif\n\n    result = svd.matrixU() * svd.singularValues().unaryExpr(std::function<scalar_type(scalar_type)>((scalar_type(*)(scalar_type))&std::atan)).asDiagonal() * svd.matrixV().transpose();\n}\n\n// Tangent Plane restriction\ntemplate <int N, int P>\ninline void Manifold <GRASSMANN, N, P>::tangent_plane_base(cref_type x, tm_base_ref_type result){\n    //value_type Hproj = (Eigen::Matrix<scalar_type, N, N>::Identity() - x * x.transpose()) * x; // x - xx^tx = x - x = 0 TODO: Check of that makes sense\n    //Eigen::JacobiSVD<value_type> svd(Hproj);\n    \n    // Compute X_orth by SVD \n   /* \n    Eigen::JacobiSVD<value_type> svd(x);\n    Eigen::Matrix<scalar_type, N, N - P> xorth = svd.matrixU().rightCols(N-P);\n    */\n\n    //Compute X_orth by QR\n    Eigen::HouseholderQR<value_type> qr(x);\n    Eigen::Matrix<scalar_type, N, N> Q = qr.householderQ();\n    Eigen::Matrix<scalar_type, N, N - P> xorth = Q.rightCols(N-P);\n    \n    int k = 0;\n    for(int r = 0; r < N - P; r++)\n\tfor(int c = 0; c < P; c++ ){\n\t    Eigen::Matrix<scalar_type, N, P> T = Eigen::Matrix<scalar_type, N, P>::Zero();\n\t    T.col(c) = xorth.col(r);\n\t    result.col(k) = Eigen::Map<Eigen::VectorXd>(T.data(), T.size());\n\t    ++k;\n\t}\n\n}\n\ntemplate <int N, int P>\ninline void Manifold <GRASSMANN, N, P>::horizontal_space_projector(cref_type x, ref_type a){\n\t    a = a - x * x.transpose() * a;\n}\n\n// Convex geodesic combinations\ntemplate <int N, int P>\ninline void Manifold <GRASSMANN, N, P>::convex_combination(cref_type x, cref_type y, double t, ref_type result){\n    value_type l;\n    log(x, y, l);\n    exp(x, l * t, result);\n}\n\n// Karcher mean implementations\ntemplate <int N, int P>\ninline void Manifold<GRASSMANN, N, P>::karcher_mean(ref_type x, const value_list& v, double tol, int maxit){\n    value_type L, temp;\n   \n    int k = 0;\n    double error = 0.0;\n    do{\n\tscalar_type m1 = x.sum();\n\tL = value_type::Zero();\n\tfor(int i = 0; i < v.size(); ++i){\n\t    log(x, v[i], temp);\n\t    L += temp;\n\t}\n\texp(x, 1.0 / v.size() * L, temp);\n\tx = temp;\n\terror = std::abs(x.sum() - m1);\n\t++k;\n    } while(error > tol && k < maxit);\n\n}\n\ntemplate <int N, int P>\ninline void Manifold<GRASSMANN, N, P>::weighted_karcher_mean(ref_type x, const weight_list& w, const value_list& v, double tol, int maxit){\n    value_type L, temp;\n   \n    int k = 0;\n    double error = 0.0;\n    do{\n\tscalar_type m1 = x.sum();\n\tL = value_type::Zero();\n\tfor(int i = 0; i < v.size(); ++i){\n\t    log(x, v[i], temp);\n\t    L += w[i] * temp;\n\t}\n\texp(x, 1.0 / v.size() * L, temp);\n\tx = temp;\n\terror = std::abs(x.sum() - m1);\n\t++k;\n    } while(error > tol && k < maxit);\n\n}\n\ntemplate <int N, int P>\ntemplate <typename V, class... Args>\ninline void Manifold<GRASSMANN, N, P>::karcher_mean(V& x, const Args&... args){\n    V temp, sum;\n    \n    int numArgs = sizeof...(args);\n    int k = 0;\n    double error = 0.0;    \n    double tol = 1e-10;\n    int maxit = 15;\n    do{\n\tscalar_type m1 = x.sum();\n\tsum = x;\n\tvariadic_karcher_mean_gradient(sum, args...);\n\texp(x, 1.0 / numArgs * sum, temp);\n\tx = temp;\n\terror = std::abs(x.sum() - m1);\n\t++k;\n    } while(error > tol && k < maxit);\n}\n\ntemplate <int N, int P>\ntemplate <typename V>\ninline void Manifold<GRASSMANN, N, P>::variadic_karcher_mean_gradient(V& x, const V& y){\n    V temp;\n    log(x, y, temp);\n    x = temp;\n}\n\ntemplate <int N, int P>\ntemplate <typename V, class... Args>\ninline void Manifold<GRASSMANN, N, P>::variadic_karcher_mean_gradient(V& x, const V& y1, const Args& ... args){\n    V temp1, temp2;\n    temp2 = x;\n    \n    log(x, y1, temp1);\n\n    variadic_karcher_mean_gradient(temp2, args...);\n    temp1 += temp2;\n    x = temp1;\n}\n\n\ntemplate <int N, int P>\ninline void Manifold <GRASSMANN, N, P>::projector(ref_type x){\n\t    Eigen::HouseholderQR<value_type> qr(x);\n\t    value_type thinQ = qr.householderQ() * value_type::Identity();\n\t    x = thinQ;\n}\n\n\n} // end namespace tvmtl\n\n\n\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "a523002a3adc24104bf8cafb24ea9579536626b0", "size": 13400, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mtvmtl/core/manifold_grassmann.hpp", "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": "mtvmtl/core/manifold_grassmann.hpp", "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": "mtvmtl/core/manifold_grassmann.hpp", "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": 34.0101522843, "max_line_length": 237, "alphanum_fraction": 0.6870149254, "num_tokens": 3998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.524953957288588}}
{"text": "/**\n * @file burgersequation_main.cc\n * @brief NPDE homework BurgersEquation code\n * @author Oliver Rietmann\n * @date 15.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\n#include \"burgersequation.h\"\n\nint main() {\n  /* SAM_LISTING_BEGIN_1 */\n  const unsigned int N = 100;\n  Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(N + 1, -1.0, 4.0);\n  Eigen::VectorXd mu03 = BurgersEquation::solveBurgersGodunov(0.3, N);\n  Eigen::VectorXd mu30 = BurgersEquation::solveBurgersGodunov(3.0, N);\n\n  // Write the solutions to a file that can be used for plotting.\n  //====================\n  // Your code goes here\n  \n  //====================\n  /* SAM_LISTING_END_1 */\n\n  /* SAM_LISTING_BEGIN_2 */\n  Eigen::Matrix<double, 3, 4> result = BurgersEquation::numexpBurgersGodunov();\n\n  // Write the result to a file that can be used for plotting.\n  //====================\n  // Your code goes here\n  //====================\n  /* SAM_LISTING_END_2 */\n\n  return 0;\n}\n", "meta": {"hexsha": "848f7959b0c83dbebea473ee08220912475a40db", "size": 1024, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/BurgersEquation/mysolution/burgersequation_main.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/BurgersEquation/mysolution/burgersequation_main.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/BurgersEquation/mysolution/burgersequation_main.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": 24.9756097561, "max_line_length": 79, "alphanum_fraction": 0.630859375, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145997, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5248802133212697}}
{"text": "#include <Geometry/ConvexPolygon.hpp>\n#include <Geometry/LineSegment.hpp>\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include <iostream>\n#include <cmath>\n\nTEST(ConvexPolygon, AddVerticesConstruction)\n{\n    using namespace pcv;\n\n    ConvexPolygon<int> polygon{};\n\n    polygon.addVertex(Eigen::Vector2i{2, 4});\n    polygon.addVertex(Eigen::Vector2i{3, 5});\n    polygon.addVertex(Eigen::Vector2i{4, 0});\n    polygon.addVertex(Eigen::Vector2i{0, 0});\n\n    ConvexPolygon<int> polygonReplica;\n    polygonReplica.addVertex(Eigen::Vector2i{2, 4});\n    polygonReplica.addVertex(Eigen::Vector2i{3, 5});\n    polygonReplica.addVertex(Eigen::Vector2i{4, 0});\n    polygonReplica.addVertex(Eigen::Vector2i{0, 0});\n\n    ASSERT_EQ(polygon, polygonReplica);\n}\n\n\nTEST(Triagle, SignedArea)\n{\n    using namespace pcv;\n    using namespace Eigen;\n\n    const double negativeArea = getTwiceSignedArea2D(Vector2d{2.0, 4.0}, Vector2d{3.0, 5.0}, Vector2d{4.0, 0.0});\n    ASSERT_EQ(negativeArea, -6.0);\n\n    const int positiveArea = getTwiceSignedArea2D(Vector2i{4, 0}, Vector2i{3, 5}, Vector2i{2, 4});\n    ASSERT_EQ(positiveArea, 6);\n}\n\nTEST(ConvexPolygon, PointContained)\n{\n    using namespace pcv;\n    using namespace Eigen;\n\n    ConvexPolygon<int> polygon{};\n\n    polygon.addVertex(Vector2i{2, 4});\n    polygon.addVertex(Vector2i{3, 5});\n    polygon.addVertex(Vector2i{4, 0});\n    polygon.addVertex(Vector2i{0, 0});\n\n    // Check that all the vertices are contained in the polygon.\n    ASSERT_TRUE(polygon.isPointContained(Vector2i{2, 4}.cast<double>()));\n    ASSERT_TRUE(polygon.isPointContained(Vector2d{3, 5}));\n    ASSERT_TRUE(polygon.isPointContained(Vector2d{4, 0}));\n    ASSERT_TRUE(polygon.isPointContained(Vector2d{0, 0}));\n\n    ASSERT_TRUE(polygon.isPointContained(Vector2d{2, 2}));\n    ASSERT_TRUE(polygon.isPointContained(Vector2d{1, 1}));\n    ASSERT_FALSE(polygon.isPointContained(Vector2d{5, 5}));\n}\n\n\nTEST(ConvexPolygon, RasterizeToEigen)\n{\n    using namespace pcv;\n    using namespace Eigen;\n\n    ConvexPolygon<int> polygon{};\n\n    polygon.addVertex(Vector2i{2, 4});\n    polygon.addVertex(Vector2i{3, 5});\n    polygon.addVertex(Vector2i{4, 0});\n    polygon.addVertex(Vector2i{0, 0});\n\n    MatrixXi autoMask = makePolygonIntersectionEigenGrid<int>({polygon}, 7, 7);\n\n    MatrixXi mask(7, 7);\n    mask <<\n        0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 1, 0, 0, 0,\n        0, 0, 1, 1, 0, 0, 0,\n        0, 0, 1, 1, 0, 0, 0,\n        0, 1, 1, 1, 0, 0, 0,\n        0, 1, 1, 1, 0, 0, 0,\n        1, 1, 1, 1, 1, 0, 0;\n\n    ASSERT_TRUE(mask == autoMask);\n}\n\n\nTEST(ConvexPolygon, RasterizeToOpenCV)\n{\n    using namespace pcv;\n    using namespace Eigen;\n\n    ConvexPolygon<int> polygon{};\n\n    polygon.addVertex(Vector2i{2, 4});\n    polygon.addVertex(Vector2i{3, 5});\n    polygon.addVertex(Vector2i{4, 0});\n    polygon.addVertex(Vector2i{0, 0});\n\n    cv::Mat_<int> autoMask;\n    makePolygonIntersectionOpencvGrid(\n        std::vector<ConvexPolygon<int>>({polygon}), 7, 7, autoMask);\n\n    cv::Mat_<int> mask(7, 7);\n    mask = (cv::Mat_<int>(7, 7) <<\n        0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 1, 0, 0, 0,\n        0, 0, 1, 1, 0, 0, 0,\n        0, 0, 1, 1, 0, 0, 0,\n        0, 1, 1, 1, 0, 0, 0,\n        0, 1, 1, 1, 0, 0, 0,\n        1, 1, 1, 1, 1, 0, 0);\n\n    cv::Mat diff = mask != autoMask;\n    ASSERT_TRUE(cv::countNonZero(diff) == 0);\n}\n\n\nTEST(ConvexPolygon, Transform)\n{\n    using namespace pcv;\n    using namespace Eigen;\n\n    ConvexPolygon<double> polygon{};\n\n    polygon.addVertex(Vector2d{0, 0});\n    polygon.addVertex(Vector2d{1.5, 2});\n    polygon.addVertex(Vector2d{3.5, 2});\n    polygon.addVertex(Vector2d{3.5, 0});\n\n    Matrix3d transform;\n    transform <<\n        2.0, 0.0, 1.0,\n        0.0, 2.0, 3.0,\n        0.0, 0.0, 2.0;\n\n    polygon.transform(transform);\n    const auto vertices = polygon.getVertices();\n\n    ASSERT_DOUBLE_EQ(vertices[0].x(), 0.5);\n    ASSERT_DOUBLE_EQ(vertices[0].y(), 1.5);\n\n    ASSERT_DOUBLE_EQ(vertices[1].x(), 2.0);\n    ASSERT_DOUBLE_EQ(vertices[1].y(), 3.5);\n\n    ASSERT_DOUBLE_EQ(vertices[2].x(), 4.0);\n    ASSERT_DOUBLE_EQ(vertices[2].y(), 3.5);\n\n    ASSERT_DOUBLE_EQ(vertices[3].x(), 4.0);\n    ASSERT_DOUBLE_EQ(vertices[3].y(), 1.5);\n}\n\n\nTEST(LineSegment, Intersection)\n{\n    using namespace pcv;\n    using namespace Eigen;\n\n    const auto intersection = getSegmentIntersectionPoint2(\n        Vector2i{0, 0},\n        Vector2i{2, 2},\n        Vector2i{0, 2},\n        Vector2i{2, 0});\n\n    ASSERT_TRUE(intersection);\n    ASSERT_DOUBLE_EQ(intersection->x(), 1.0);\n    ASSERT_DOUBLE_EQ(intersection->y(), 1.0);\n}\n\n\nTEST(ConvexPolygon, Intersection)\n{\n    using namespace pcv;\n    using namespace Eigen;\n\n    ConvexPolygon<double> polygonA{};\n    polygonA.addVertex(Vector2d{5, 14});\n    polygonA.addVertex(Vector2d{9, 8});\n    polygonA.addVertex(Vector2d{5, 3});\n    polygonA.addVertex(Vector2d{1, 7});\n\n    ConvexPolygon<double> polygonB{};\n    polygonB.addVertex(Vector2d{9, 14});\n    polygonB.addVertex(Vector2d{13, 9});\n    polygonB.addVertex(Vector2d{9, 4});\n    polygonB.addVertex(Vector2d{6, 9});\n\n    auto res = polygonA.getIntersectionWith(polygonB);\n\n    for (const auto &i : res.getVertices())\n    {\n        std::clog << i << std::endl << std::endl;\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": "e7c6ade68e2b9cf6bd295627e4a85c2a5c079b15", "size": 5301, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/Geometry/test/TestGeometry.cpp", "max_stars_repo_name": "Pratool/homography", "max_stars_repo_head_hexsha": "c9daeaa3364b7c658b39c225952288dd828c332e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-12T17:38:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-12T17:38:22.000Z", "max_issues_repo_path": "cpp/Geometry/test/TestGeometry.cpp", "max_issues_repo_name": "Pratool/homography", "max_issues_repo_head_hexsha": "c9daeaa3364b7c658b39c225952288dd828c332e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T15:43:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-04T03:22:47.000Z", "max_forks_repo_path": "cpp/Geometry/test/TestGeometry.cpp", "max_forks_repo_name": "Pratool/homography", "max_forks_repo_head_hexsha": "c9daeaa3364b7c658b39c225952288dd828c332e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3636363636, "max_line_length": 113, "alphanum_fraction": 0.6362950387, "num_tokens": 1794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5248802057437945}}
{"text": "\n#include <NTL/mat_GF2E.h>\n#include <NTL/vec_GF2XVec.h>\n#include <NTL/vec_long.h>\n#include <NTL/BasicThreadPool.h>\n\n\nNTL_START_IMPL\n\n//===========================================================\n\n\n\n#define PAR_THRESH (40000.0)\n\nstatic double\nGF2E_SizeInWords()\n{\n   return GF2E::WordLength();\n}\n\n\nstatic\nvoid mul_aux(Mat<GF2E>& X, const Mat<GF2E>& A, const Mat<GF2E>& B)  \n{  \n   long n = A.NumRows();  \n   long l = A.NumCols();  \n   long m = B.NumCols();  \n  \n   if (l != B.NumRows())  \n      LogicError(\"matrix mul: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n\n\n   GF2Context GF2_context;\n   GF2_context.save();\n   GF2EContext GF2E_context;\n   GF2E_context.save();\n   double sz = GF2E_SizeInWords();\n\n   bool seq = (double(n)*double(l)*double(m)*sz*sz < PAR_THRESH);\n\n   NTL_GEXEC_RANGE(seq, m, first, last)\n   NTL_IMPORT(n)\n   NTL_IMPORT(l)\n   NTL_IMPORT(m)\n\n   GF2_context.restore();\n   GF2E_context.restore();\n\n   long i, j, k;  \n   GF2X acc, tmp;  \n\n   Vec<GF2E> B_col;\n   B_col.SetLength(l);\n\n   for (j = first; j < last; j++) {\n      for (k = 0; k < l; k++) B_col[k] = B[k][j];\n\n      for (i = 0; i < n; i++) {\n         clear(acc);\n         for (k = 0; k < l; k++) {\n            mul(tmp, rep(A[i][k]), rep(B_col[k]));\n            add(acc, acc, tmp);\n         }\n         conv(X[i][j], acc);\n      }\n   }\n\n   NTL_GEXEC_RANGE_END\n}  \n\n\nvoid mul(mat_GF2E& X, const mat_GF2E& A, const mat_GF2E& B)  \n{  \n   if (&X == &A || &X == &B) {  \n      mat_GF2E tmp;  \n      mul_aux(tmp, A, B);  \n      X = tmp;  \n   }  \n   else  \n      mul_aux(X, A, B);  \n}  \n  \n\nvoid inv(GF2E& d, Mat<GF2E>& X, const Mat<GF2E>& A)\n{\n   long n = A.NumRows();\n\n   if (A.NumCols() != n)\n      LogicError(\"inv: nonsquare matrix\");\n\n   if (n == 0) {\n      set(d);\n      X.SetDims(0, 0);\n      return;\n   }\n\n   const GF2XModulus& G = GF2E::modulus();\n\n   GF2X t1, t2;\n   GF2X pivot;\n   GF2X pivot_inv;\n\n   Vec< GF2XVec > M;\n   // scratch space\n\n   M.SetLength(n);\n   for (long i = 0; i < n; i++) {\n      M[i].SetSize(n, 2*GF2E::WordLength());\n      for (long j = 0; j < n; j++) {\n         M[i][j] = rep(A[i][j]);\n      }\n   }\n\n   GF2X det;\n   det = 1;\n\n\n   Vec<long> P;\n   P.SetLength(n);\n   for (long k = 0; k < n; k++) P[k] = k;\n   // records swap operations\n   \n\n   GF2Context GF2_context;\n   GF2_context.save();\n   double sz = GF2E_SizeInWords();\n\n   bool seq = double(n)*double(n)*sz*sz < PAR_THRESH;\n\n   bool pivoting = false;\n\n   for (long k = 0; k < n; k++) {\n\n      long pos = -1;\n\n      for (long i = k; i < n; i++) {\n         rem(pivot, M[i][k], G);\n         if (pivot != 0) {\n            InvMod(pivot_inv, pivot, G);\n            pos = i;\n            break;\n         }\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n            negate(det, det); \n            P[k] = pos;\n            pivoting = true;\n         }\n\n         MulMod(det, det, pivot, G);\n\n         {\n            // multiply row k by pivot_inv\n            GF2X *y = &M[k][0];\n            for (long j = 0; j < n; j++) {\n               rem(t2, y[j], G);\n               MulMod(y[j], t2, pivot_inv, G);\n            }\n            y[k] = pivot_inv;\n         }\n\n\n         NTL_GEXEC_RANGE(seq, n, first, last)  \n         NTL_IMPORT(n)\n         NTL_IMPORT(k)\n\n         GF2_context.restore();\n\n         GF2X *y = &M[k][0]; \n         GF2X t1, t2;\n\n         for (long i = first; i < last; i++) {\n            if (i == k) continue; // skip row k\n\n            GF2X *x = &M[i][0]; \n            rem(t1, x[k], G);\n            negate(t1, t1); \n            x[k] = 0;\n            if (t1 == 0) continue;\n\n            // add t1 * row k to row i\n            for (long j = 0; j < n; j++) {\n               mul(t2, y[j], t1);\n               add(x[j], x[j], t2);\n            }\n         }\n         NTL_GEXEC_RANGE_END\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   if (pivoting) {\n      // pivot colums, using reverse swap sequence\n\n      for (long i = 0; i < n; i++) {\n         GF2X *x = &M[i][0]; \n\n         for (long k = n-1; k >= 0; k--) {\n            long pos = P[k];\n            if (pos != k) swap(x[pos], x[k]);\n         }\n      }\n   }\n\n   X.SetDims(n, n);\n   for (long i = 0; i < n; i++)\n      for (long j = 0; j < n; j++)\n         conv(X[i][j], M[i][j]);\n\n   conv(d, det);\n}\n\nstatic\nvoid solve_impl(GF2E& d, Vec<GF2E>& X, \n                const Mat<GF2E>& A, const Vec<GF2E>& b, bool trans)\n\n{\n   long n = A.NumRows();\n   if (A.NumCols() != n)\n      LogicError(\"solve: nonsquare matrix\");\n\n   if (b.length() != n)\n      LogicError(\"solve: dimension mismatch\");\n\n   if (n == 0) {\n      set(d);\n      X.SetLength(0);\n      return;\n   }\n\n   GF2X t1, t2;\n\n   const GF2XModulus& G = GF2E::modulus();\n\n   Vec< GF2XVec > M;\n\n   M.SetLength(n);\n\n   for (long i = 0; i < n; i++) {\n      M[i].SetSize(n+1, 2*GF2E::WordLength());\n\n      if (trans) \n         for (long j = 0; j < n; j++) M[i][j] = rep(A[j][i]);\n      else\n         for (long j = 0; j < n; j++) M[i][j] = rep(A[i][j]);\n\n      M[i][n] = rep(b[i]);\n   }\n\n   GF2X det;\n   set(det);\n\n   GF2Context GF2_context;\n   GF2_context.save();\n   double sz = GF2E_SizeInWords();\n\n   for (long k = 0; k < n; k++) {\n      long pos = -1;\n      for (long i = k; i < n; i++) {\n         rem(t1, M[i][k], G);\n         M[i][k] = t1;\n         if (pos == -1 && !IsZero(t1)) {\n            pos = i;\n         }\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n            negate(det, det); \n         }\n\n         MulMod(det, det, M[k][k], G);\n\n         // make M[k, k] == -1 mod G, and make row k reduced\n\n         InvMod(t1, M[k][k], G);\n         negate(t1, t1); \n         for (long j = k+1; j <= n; j++) {\n            rem(t2, M[k][j], G);\n            MulMod(M[k][j], t2, t1, G);\n         }\n\n         bool seq =\n            double(n-(k+1))*(n-(k+1))*sz*sz < PAR_THRESH;\n\n         NTL_GEXEC_RANGE(seq, n-(k+1), first, last)\n         NTL_IMPORT(n)\n         NTL_IMPORT(k)\n\n         GF2_context.restore();\n\n         GF2X t1, t2;\n\n         for (long ii = first; ii < last; ii++) {\n            long i = ii + k+1;\n\n            // M[i] = M[i] + M[k]*M[i,k]\n\n            t1 = M[i][k];   // this is already reduced\n\n            GF2X *x = M[i].elts() + (k+1);\n            GF2X *y = M[k].elts() + (k+1);\n\n            for (long j = k+1; j <= n; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               mul(t2, *y, t1);\n               add(*x, *x, t2);\n            }\n         }\n\n         NTL_GEXEC_RANGE_END\n\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   X.SetLength(n);\n   for (long i = n-1; i >= 0; i--) {\n      clear(t1);\n      for (long j = i+1; j < n; j++) {\n         mul(t2, rep(X[j]), M[i][j]);\n         add(t1, t1, t2);\n      }\n      sub(t1, t1, M[i][n]);\n      conv(X[i], t1);\n   }\n\n   conv(d, det);\n}\n\n\nvoid solve(GF2E& d, Vec<GF2E>& x, \n               const Mat<GF2E>& A, const Vec<GF2E>& b)\n{\n   solve_impl(d, x, A, b, true);\n}\n\nvoid solve(GF2E& d, const Mat<GF2E>& A, \n               Vec<GF2E>& x, const Vec<GF2E>& b)\n{\n   solve_impl(d, x, A, b, false);\n}\n\n\n\nlong gauss(Mat<GF2E>& M_in, long w)\n{\n   GF2X t1, t2;\n   GF2X piv;\n\n   long n = M_in.NumRows();\n   long m = M_in.NumCols();\n\n   if (w < 0 || w > m)\n      LogicError(\"gauss: bad args\");\n\n   const GF2XModulus& G = GF2E::modulus();\n\n   Vec< GF2XVec > M;\n\n   M.SetLength(n);\n   for (long i = 0; i < n; i++) {\n      M[i].SetSize(m, 2*GF2E::WordLength());\n      for (long j = 0; j < m; j++) {\n         M[i][j] = rep(M_in[i][j]);\n      }\n   }\n\n   GF2Context GF2_context;\n   GF2_context.save();\n   double sz = GF2E_SizeInWords();\n\n   long l = 0;\n   for (long k = 0; k < w && l < n; k++) {\n\n      long pos = -1;\n      for (long i = l; i < n; i++) {\n         rem(t1, M[i][k], G);\n         M[i][k] = t1;\n         if (pos == -1 && !IsZero(t1)) {\n            pos = i;\n         }\n      }\n\n      if (pos != -1) {\n         swap(M[pos], M[l]);\n\n         InvMod(piv, M[l][k], G);\n         negate(piv, piv);\n\n         for (long j = k+1; j < m; j++) {\n            rem(M[l][j], M[l][j], G);\n         }\n\n         bool seq =\n            double(n-(l+1))*double(m-(k+1))*sz*sz < PAR_THRESH;\n\n         NTL_GEXEC_RANGE(seq, n-(l+1), first, last)\n         NTL_IMPORT(m)\n         NTL_IMPORT(k)\n         NTL_IMPORT(l)\n\n         GF2_context.restore();\n\n         GF2X t1, t2;\n\n\n         for (long ii = first; ii < last; ii++) {\n            long i = ii + l+1;\n\n            // M[i] = M[i] + M[l]*M[i,k]*piv\n\n            MulMod(t1, M[i][k], piv, G);\n\n            clear(M[i][k]);\n\n            GF2X *x = M[i].elts() + (k+1);\n            GF2X *y = M[l].elts() + (k+1);\n\n            for (long j = k+1; j < m; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               mul(t2, *y, t1);\n               add(t2, t2, *x);\n               *x = t2;\n            }\n         }\n\n         NTL_GEXEC_RANGE_END\n\n         l++;\n      }\n   }\n   \n   for (long i = 0; i < n; i++)\n      for (long j = 0; j < m; j++)\n         conv(M_in[i][j], M[i][j]);\n\n   return l;\n}\n\n\nlong gauss(Mat<GF2E>& M)\n{\n   return gauss(M, M.NumCols());\n}\n\nvoid image(Mat<GF2E>& X, const Mat<GF2E>& A)\n{\n   Mat<GF2E> M;\n   M = A;\n   long r = gauss(M);\n   M.SetDims(r, M.NumCols());\n   X = M;\n}\n\n\n\nvoid kernel(Mat<GF2E>& X, const Mat<GF2E>& A)\n{\n   long m = A.NumRows();\n   long n = A.NumCols();\n\n   const GF2XModulus& G = GF2E::modulus();\n\n   Mat<GF2E> M;\n\n   transpose(M, A);\n   long r = gauss(M);\n\n   if (r == 0) {\n      ident(X, m);\n      return;\n   }\n\n   X.SetDims(m-r, m);\n\n   if (m-r == 0 || m == 0) return;\n\n\n   Vec<long> D;\n   D.SetLength(m);\n   for (long j = 0; j < m; j++) D[j] = -1;\n\n   Vec<GF2E> inverses;\n   inverses.SetLength(m);\n\n   for (long i = 0, j = -1; i < r; i++) {\n      do {\n         j++;\n      } while (IsZero(M[i][j]));\n\n      D[j] = i;\n      inv(inverses[j], M[i][j]); \n   }\n\n   GF2EContext GF2E_context;\n   GF2E_context.save();\n   GF2Context GF2_context;\n   GF2_context.save();\n   double sz = GF2E_SizeInWords();\n\n   bool seq = \n      double(m-r)*double(r)*double(r)*sz*sz < PAR_THRESH;\n\n   NTL_GEXEC_RANGE(seq, m-r, first, last)\n   NTL_IMPORT(m)\n   NTL_IMPORT(r)\n\n   GF2_context.restore();\n   GF2E_context.restore();\n\n   GF2X t1, t2;\n   GF2E T3;\n\n   for (long k = first; k < last; k++) {\n      Vec<GF2E>& v = X[k];\n      long pos = 0;\n      for (long j = m-1; j >= 0; j--) {\n         if (D[j] == -1) {\n            if (pos == k)\n               set(v[j]);\n            else\n               clear(v[j]);\n            pos++;\n         }\n         else {\n            long i = D[j];\n\n            clear(t1);\n\n            for (long s = j+1; s < m; s++) {\n               mul(t2, rep(v[s]), rep(M[i][s]));\n               add(t1, t1, t2);\n            }\n\n            conv(T3, t1);\n            mul(T3, T3, inverses[j]);\n            negate(v[j], T3); \n         }\n      }\n   }\n\n   NTL_GEXEC_RANGE_END\n}\n\n\n\n\nvoid determinant(GF2E& d, const Mat<GF2E>& M_in)\n{\n   GF2X t1, t2;\n\n   const GF2XModulus& G = GF2E::modulus();\n\n   long n = M_in.NumRows();\n\n   if (M_in.NumCols() != n)\n      LogicError(\"determinant: nonsquare matrix\");\n\n   if (n == 0) {\n      set(d);\n      return;\n   }\n\n   Vec< GF2XVec > M;\n\n   M.SetLength(n);\n   for (long i = 0; i < n; i++) {\n      M[i].SetSize(n, 2*GF2E::WordLength());\n      for (long j = 0; j < n; j++) { \n         M[i][j] = rep(M_in[i][j]);\n      }\n   }\n\n   GF2X det;\n   set(det);\n\n   GF2Context GF2_context;\n   GF2_context.save();\n   double sz = GF2E_SizeInWords();\n\n   for (long k = 0; k < n; k++) {\n      long pos = -1;\n      for (long i = k; i < n; i++) {\n         rem(t1, M[i][k], G);\n         M[i][k] = t1;\n         if (pos == -1 && !IsZero(t1))\n            pos = i;\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n            negate(det, det);\n         }\n\n         MulMod(det, det, M[k][k], G);\n\n         // make M[k, k] == -1 mod G, and make row k reduced\n\n         InvMod(t1, M[k][k], G);\n         negate(t1, t1);\n         for (long j = k+1; j < n; j++) {\n            rem(t2, M[k][j], G);\n            MulMod(M[k][j], t2, t1, G);\n         }\n\n\n         bool seq =\n            double(n-(k+1))*(n-(k+1))*sz*sz < PAR_THRESH;\n\n         NTL_GEXEC_RANGE(seq, n-(k+1), first, last)\n         NTL_IMPORT(n)\n         NTL_IMPORT(k)\n\n         GF2_context.restore();\n\n         GF2X t1, t2;\n\n         for (long ii = first; ii < last; ii++) {\n            long i = ii + k+1;\n\n            // M[i] = M[i] + M[k]*M[i,k]\n\n            t1 = M[i][k];   // this is already reduced\n\n            GF2X *x = M[i].elts() + (k+1);\n            GF2X *y = M[k].elts() + (k+1);\n\n            for (long j = k+1; j < n; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               mul(t2, *y, t1);\n               add(*x, *x, t2);\n            }\n         }\n\n         NTL_GEXEC_RANGE_END\n\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   conv(d, det);\n}\n\n\n\n\n\n\n\n//===========================================================\n\n  \nvoid add(mat_GF2E& X, const mat_GF2E& A, const mat_GF2E& B)  \n{  \n   long n = A.NumRows();  \n   long m = A.NumCols();  \n  \n   if (B.NumRows() != n || B.NumCols() != m)   \n      LogicError(\"matrix add: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n  \n   long i, j;  \n   for (i = 1; i <= n; i++)   \n      for (j = 1; j <= m; j++)  \n         add(X(i,j), A(i,j), B(i,j));  \n}  \n  \n  \n  \nstatic\nvoid mul_aux(vec_GF2E& x, const mat_GF2E& A, const vec_GF2E& b)  \n{  \n   long n = A.NumRows();  \n   long l = A.NumCols();  \n  \n   if (l != b.length())  \n      LogicError(\"matrix mul: dimension mismatch\");  \n  \n   x.SetLength(n);  \n  \n   long i, k;  \n   GF2X acc, tmp;  \n  \n   for (i = 1; i <= n; i++) {  \n      clear(acc);  \n      for (k = 1; k <= l; k++) {  \n         mul(tmp, rep(A(i,k)), rep(b(k)));  \n         add(acc, acc, tmp);  \n      }  \n      conv(x(i), acc);  \n   }  \n}  \n  \n  \nvoid mul(vec_GF2E& x, const mat_GF2E& A, const vec_GF2E& b)  \n{  \n   if (&b == &x || A.alias(x)) {\n      vec_GF2E tmp;\n      mul_aux(tmp, A, b);\n      x = tmp;\n   }\n   else\n      mul_aux(x, A, b);\n}  \n\nstatic\nvoid mul_aux(vec_GF2E& x, const vec_GF2E& a, const mat_GF2E& B)  \n{  \n   long n = B.NumRows();  \n   long l = B.NumCols();  \n  \n   if (n != a.length())  \n      LogicError(\"matrix mul: dimension mismatch\");  \n  \n   x.SetLength(l);  \n  \n   long i, k;  \n   GF2X acc, tmp;  \n  \n   for (i = 1; i <= l; i++) {  \n      clear(acc);  \n      for (k = 1; k <= n; k++) {  \n         mul(tmp, rep(a(k)), rep(B(k,i)));\n         add(acc, acc, tmp);  \n      }  \n      conv(x(i), acc);  \n   }  \n}  \n\nvoid mul(vec_GF2E& x, const vec_GF2E& a, const mat_GF2E& B)\n{\n   if (&a == &x) {\n      vec_GF2E tmp;\n      mul_aux(tmp, a, B);\n      x = tmp;\n   }\n   else\n      mul_aux(x, a, B);\n}\n\n     \n  \nvoid ident(mat_GF2E& X, long n)  \n{  \n   X.SetDims(n, n);  \n   long i, j;  \n  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= n; j++)  \n         if (i == j)  \n            set(X(i, j));  \n         else  \n            clear(X(i, j));  \n} \n\n\nlong IsIdent(const mat_GF2E& A, long n)\n{\n   if (A.NumRows() != n || A.NumCols() != n)\n      return 0;\n\n   long i, j;\n\n   for (i = 1; i <= n; i++)\n      for (j = 1; j <= n; j++)\n         if (i != j) {\n            if (!IsZero(A(i, j))) return 0;\n         }\n         else {\n            if (!IsOne(A(i, j))) return 0;\n         }\n\n   return 1;\n}\n            \n\nvoid transpose(mat_GF2E& X, const mat_GF2E& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   long i, j;\n\n   if (&X == & A) {\n      if (n == m)\n         for (i = 1; i <= n; i++)\n            for (j = i+1; j <= n; j++)\n               swap(X(i, j), X(j, i));\n      else {\n         mat_GF2E tmp;\n         tmp.SetDims(m, n);\n         for (i = 1; i <= n; i++)\n            for (j = 1; j <= m; j++)\n               tmp(j, i) = A(i, j);\n         X.kill();\n         X = tmp;\n      }\n   }\n   else {\n      X.SetDims(m, n);\n      for (i = 1; i <= n; i++)\n         for (j = 1; j <= m; j++)\n            X(j, i) = A(i, j);\n   }\n}\n   \n   \nvoid mul(mat_GF2E& X, const mat_GF2E& A, const GF2E& b_in)\n{\n   GF2E b = b_in;\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(n, m);\n\n   long i, j;\n   for (i = 0; i < n; i++)\n      for (j = 0; j < m; j++)\n         mul(X[i][j], A[i][j], b);\n}\n\nvoid mul(mat_GF2E& X, const mat_GF2E& A, GF2 b)\n{\n   X = A;\n   if (b == 0)\n      clear(X);\n}\n\nvoid diag(mat_GF2E& X, long n, const GF2E& d_in)  \n{  \n   GF2E d = d_in;\n   X.SetDims(n, n);  \n   long i, j;  \n  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= n; j++)  \n         if (i == j)  \n            X(i, j) = d;  \n         else  \n            clear(X(i, j));  \n} \n\nlong IsDiag(const mat_GF2E& A, long n, const GF2E& d)\n{\n   if (A.NumRows() != n || A.NumCols() != n)\n      return 0;\n\n   long i, j;\n\n   for (i = 1; i <= n; i++)\n      for (j = 1; j <= n; j++)\n         if (i != j) {\n            if (!IsZero(A(i, j))) return 0;\n         }\n         else {\n            if (A(i, j) != d) return 0;\n         }\n\n   return 1;\n}\n\n\nlong IsZero(const mat_GF2E& a)\n{\n   long n = a.NumRows();\n   long i;\n\n   for (i = 0; i < n; i++)\n      if (!IsZero(a[i]))\n         return 0;\n\n   return 1;\n}\n\nvoid clear(mat_GF2E& x)\n{\n   long n = x.NumRows();\n   long i;\n   for (i = 0; i < n; i++)\n      clear(x[i]);\n}\n\n\nmat_GF2E operator+(const mat_GF2E& a, const mat_GF2E& b)\n{\n   mat_GF2E res;\n   add(res, a, b);\n   NTL_OPT_RETURN(mat_GF2E, res);\n}\n\nmat_GF2E operator*(const mat_GF2E& a, const mat_GF2E& b)\n{\n   mat_GF2E res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(mat_GF2E, res);\n}\n\nmat_GF2E operator-(const mat_GF2E& a, const mat_GF2E& b)\n{\n   mat_GF2E res;\n   sub(res, a, b);\n   NTL_OPT_RETURN(mat_GF2E, res);\n}\n\n\nmat_GF2E operator-(const mat_GF2E& a)\n{\n   mat_GF2E res;\n   negate(res, a);\n   NTL_OPT_RETURN(mat_GF2E, res);\n}\n\n\nvec_GF2E operator*(const mat_GF2E& a, const vec_GF2E& b)\n{\n   vec_GF2E res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_GF2E, res);\n}\n\nvec_GF2E operator*(const vec_GF2E& a, const mat_GF2E& b)\n{\n   vec_GF2E res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_GF2E, res);\n}\n\n\nvoid inv(mat_GF2E& X, const mat_GF2E& A)\n{\n   GF2E d;\n   inv(d, X, A);\n   if (d == 0) ArithmeticError(\"inv: non-invertible matrix\");\n}\n\nvoid power(mat_GF2E& X, const mat_GF2E& A, const ZZ& e)\n{\n   if (A.NumRows() != A.NumCols()) LogicError(\"power: non-square matrix\");\n\n   if (e == 0) {\n      ident(X, A.NumRows());\n      return;\n   }\n\n   mat_GF2E T1, T2;\n   long i, k;\n\n   k = NumBits(e);\n   T1 = A;\n\n   for (i = k-2; i >= 0; i--) {\n      sqr(T2, T1);\n      if (bit(e, i))\n         mul(T1, T2, A);\n      else\n         T1 = T2;\n   }\n\n   if (e < 0)\n      inv(X, T1);\n   else\n      X = T1;\n}\n\nvoid random(mat_GF2E& x, long n, long m)\n{\n   x.SetDims(n, m);\n   for (long i = 0; i < n; i++) random(x[i], m);\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "1479ff289ff6898f318c85514c88ded2273b75e6", "size": 18651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/mat_GF2E.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "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": "homomorphic_evaluation/ntl-11.3.2/src/mat_GF2E.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "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": "LibSource/ExtendedNTL/src/mat_GF2E.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "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": 18.7635814889, "max_line_length": 74, "alphanum_fraction": 0.4246421103, "num_tokens": 6515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5248802009359012}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm algebra vector gradient\n#include <boost/test/unit_test.hpp>\n#include \"fern/core/data_customization_point/scalar.h\"\n#include \"fern/feature/core/data_customization_point/array.h\"\n#include \"fern/feature/core/data_customization_point/masked_raster.h\"\n#include \"fern/algorithm/algebra/vector/gradient.h\"\n#include \"fern/algorithm/core/if.h\"\n#include \"fern/algorithm/core/test/test_utils.h\"\n\n\nnamespace fa = fern::algorithm;\n\n\nBOOST_AUTO_TEST_CASE(algorithm)\n{\n    // Create input raster:\n    // +----+----+----+\n    // |  X |  1 |  2 |\n    // +----+----+----+\n    // |  3 |  X |  5 |\n    // +----+----+----+\n    // |  6 |  7 |  X |\n    // +----+----+----+\n    // |  9 | 10 | 11 |\n    // +----+----+----+\n    using MaskedRaster = fern::MaskedRaster<double, 2>;\n\n    size_t const nr_rows = 4;\n    size_t const nr_cols = 3;\n    auto extents = fern::extents[nr_rows][nr_cols];\n\n    double const cell_width = 2.0;\n    double const cell_height = 3.0;\n    double const west = 0.0;\n    double const north = 0.0;\n    MaskedRaster::Transformation transformation{{west, cell_width, north,\n        cell_height}};\n\n    MaskedRaster raster(extents, transformation);\n\n    std::iota(raster.data(), raster.data() + raster.num_elements(), 0);\n    raster.mask()[0][0] = true;\n    raster.mask()[1][1] = true;\n    raster.mask()[2][2] = true;\n\n    fa::ExecutionPolicy execution_policy = fa::SequentialExecutionPolicy{};\n\n    // Calculate gradient_x.\n    {\n        MaskedRaster result_we_got(extents, transformation, -9.0);\n        MaskedRaster result_we_want(extents, transformation);\n        result_we_want[0][0] =  -9.0;\n        result_we_want[0][1] = ( 2.0 - 1.0 ) / cell_width;\n        result_we_want[0][2] = ( 2.0 - 1.0 ) / cell_width;\n        result_we_want[1][0] =   0.0;\n        result_we_want[1][1] =  -9.0;\n        result_we_want[1][2] =   0.0;\n        result_we_want[2][0] = ( 7.0 - 6.0 ) / cell_width;\n        result_we_want[2][1] = ( 7.0 - 6.0 ) / cell_width;\n        result_we_want[2][2] =  -9.0;\n        result_we_want[3][0] = (10.0 - 9.0 ) / cell_width;\n        result_we_want[3][1] = (11.0 - 9.0 ) / (2 * cell_width);\n        result_we_want[3][2] = (11.0 - 10.0) / cell_width;\n        result_we_want.mask()[0][0] = true;\n        result_we_want.mask()[1][1] = true;\n        result_we_want.mask()[2][2] = true;\n\n        fa::core::if_(execution_policy, raster.mask(), true,\n            result_we_got.mask());\n\n        fa::InputNoDataPolicies<fa::DetectNoDataByValue<fern::Mask<2>>>\n             input_no_data_policy{{raster.mask(), true}};\n        fa::MarkNoDataByValue<fern::Mask<2>> output_no_data_policy(\n            result_we_got.mask(), true);\n\n        fa::algebra::gradient_x(input_no_data_policy, output_no_data_policy,\n            execution_policy, raster, result_we_got);\n        BOOST_CHECK(fern::compare(execution_policy, result_we_got,\n            result_we_want));\n    }\n\n    // Calculate gradient_y.\n    {\n        MaskedRaster result_we_got(extents, transformation, -9.0);\n        MaskedRaster result_we_want(extents, transformation);\n        result_we_want[0][0] =  -9.0;\n        result_we_want[0][1] =   0.0;\n        result_we_want[0][2] = ( 5.0 - 2.0) / cell_height;\n        result_we_want[1][0] = ( 6.0 - 3.0) / cell_height;\n        result_we_want[1][1] =  -9.0;\n        result_we_want[1][2] = ( 5.0 - 2.0) / cell_height;\n        result_we_want[2][0] = ( 9.0 - 3.0) / (2 * cell_height);\n        result_we_want[2][1] = (10.0 - 7.0) / cell_height;\n        result_we_want[2][2] =  -9.0;\n        result_we_want[3][0] = ( 9.0 - 6.0) / cell_height;\n        result_we_want[3][1] = (10.0 - 7.0) / cell_height;\n        result_we_want[3][2] =   0.0;\n        result_we_want.mask()[0][0] = true;\n        result_we_want.mask()[1][1] = true;\n        result_we_want.mask()[2][2] = true;\n\n        fa::core::if_(execution_policy, raster.mask(), true,\n            result_we_got.mask());\n\n        fa::InputNoDataPolicies<fa::DetectNoDataByValue<fern::Mask<2>>>\n            input_no_data_policy{{raster.mask(), true}};\n        fa::MarkNoDataByValue<fern::Mask<2>> output_no_data_policy(\n            result_we_got.mask(), true);\n\n        fa::algebra::gradient_y(input_no_data_policy, output_no_data_policy,\n            execution_policy, raster, result_we_got);\n        BOOST_CHECK(fern::compare(execution_policy, result_we_got,\n            result_we_want));\n    }\n}\n", "meta": {"hexsha": "8cd25fb1041f0b259efaa513de4051dfccc5df77", "size": 4851, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/vector/test/gradient_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/vector/test/gradient_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/vector/test/gradient_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["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.1209677419, "max_line_length": 80, "alphanum_fraction": 0.5856524428, "num_tokens": 1464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5248801885505322}}
{"text": "/*\r\n * Copyright (C) 2015 Hamza Merzi\u0107\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#define BOOST_TEST_DYN_LINK\r\n#define BOOST_TEST_MODULE DhTest\r\n\r\n#include \"dh_parameter.h\"\r\n\r\n#include <cmath>\r\n#include <vector>\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\nvoid CheckCloseTables(const std::vector<std::vector<float>>& vec_table_rot,\r\n                      const std::vector<float>& vec_table_trans,\r\n                      const DhParameter& dh_table, double eps = 0.1) {\r\n  const double small = 0.0001;\r\n  for(int i(0); i < 3; ++i)\r\n    for(int j(0); j < 3; ++j) {\r\n      double expected (vec_table_rot[i][j]),\r\n             returned (dh_table.rotation()(i, j));\r\n      if(std::fabs(expected) < small)\r\n        BOOST_CHECK_SMALL(returned, small);\r\n      else\r\n        BOOST_CHECK_CLOSE(expected, returned, eps);\r\n    }\r\n\r\n  for(int i(0); i < 3; ++i) {\r\n      double expected(vec_table_trans[i]),\r\n             returned(static_cast<double>(dh_table.translation()[i]));\r\n      if(std::fabs(expected) < small)\r\n        BOOST_CHECK_SMALL(returned, small);\r\n      else\r\n        BOOST_CHECK_CLOSE(expected, returned, eps);\r\n  }\r\n}\r\n\r\nvoid CheckCloseTransform(const EMatrix& R, const EVector& T,\r\n                         const EMatrix& R_exp, const EVector& T_exp,\r\n                         double eps = 0.1) {\r\n  const double small = 0.0001;\r\n  for(int i(0); i < 3; ++i)\r\n    for(int j(0); j < 3; ++j) {\r\n      double expected (R_exp(i, j)), returned (R(i, j));\r\n      if(std::fabs(expected) < small)\r\n        BOOST_CHECK_SMALL(returned, small);\r\n      else\r\n        BOOST_CHECK_CLOSE(expected, returned, eps);\r\n    }\r\n\r\n  for(int i(0); i < 3; ++i) {\r\n      double expected (T_exp(i)), returned (T(i));\r\n      if(std::fabs(expected) < small)\r\n        BOOST_CHECK_SMALL(returned, small);\r\n      else\r\n        BOOST_CHECK_CLOSE(expected, returned, eps);\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(constructor1) {\r\n  const double pi_6 = M_PI / 6;\r\n  CheckCloseTables({{0.866, 0.0,    0.5},\r\n                    {  0.5, 0.0, -0.866},\r\n                    {  0.0, 1.0,    0.0}},\r\n                   {0.217, 0.125, 0},\r\n                   DhParameter(pi_6, 0, 0.25, M_PI_2), 1.0);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(constructor2) {\r\n  const double pi_6 = M_PI / 6, pi_5 = M_PI / 5;\r\n  CheckCloseTables({{0.866, -0.404,  0.293},\r\n                    {  0.5,    0.7, -0.509},\r\n                    {  0.0,  0.587,  0.809}},\r\n                   {0.866, 0.5, 2.0},\r\n                   DhParameter(pi_6, 2, 1, pi_5), 1.0);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(transform) {\r\n  const double pi_6 = M_PI / 6, pi_5 = M_PI / 5;\r\n  DhParameter dh (pi_6, 2, 1, pi_5);\r\n  EMatrix R (EMatrix::Identity());\r\n  EVector T (1, 2, 3);\r\n  dh.Transform(R, T);\r\n\r\n  EMatrix R_exp;\r\n  R_exp << 0.86603, -0.40451,   0.29389,\r\n           0.50000,  0.70063,  -0.50904,\r\n           0.00000,  0.58779,   0.80902;\r\n  EVector T_exp (1.8660, 2.5, 5.0);\r\n  CheckCloseTransform(R, T, R_exp, T_exp);\r\n}", "meta": {"hexsha": "19435040adbeb013c135a555614c74e86e6a55f9", "size": 3460, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/dh_parameter_test.cc", "max_stars_repo_name": "hamzamerzic/repo", "max_stars_repo_head_hexsha": "e634335a5943c25115e4860988d5f98493bb3cf9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T14:09:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T03:09:06.000Z", "max_issues_repo_path": "src/dh_parameter_test.cc", "max_issues_repo_name": "hamzamerzic/repo", "max_issues_repo_head_hexsha": "e634335a5943c25115e4860988d5f98493bb3cf9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T07:44:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T07:44:09.000Z", "max_forks_repo_path": "src/dh_parameter_test.cc", "max_forks_repo_name": "hamzamerzic/repo", "max_forks_repo_head_hexsha": "e634335a5943c25115e4860988d5f98493bb3cf9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-02-06T07:08:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T02:01:25.000Z", "avg_line_length": 33.2692307692, "max_line_length": 76, "alphanum_fraction": 0.5708092486, "num_tokens": 1026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5248801865122205}}
{"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  cout << Matrix2d::Ones() << endl;\ncout << 6 * RowVector4i::Ones() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "99cfeeafd9fefce49197fc3b4ec9ddb4f43a5b09", "size": 226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_ones.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_ones.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_ones.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": 15.0666666667, "max_line_length": 40, "alphanum_fraction": 0.6504424779, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5248801865122203}}
{"text": "//\n//  Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n\n#include <random>\n#include <boost/numeric/ublas/tensor.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"utility.hpp\"\n\nBOOST_AUTO_TEST_SUITE ( test_tensor_static )\n\nusing test_types = zip<int,float,std::complex<float>>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_tensor_ctor, value,  test_types)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n//    auto a1 = ublas::tensor_static<value_type, ublas::extents<>,layout_type>{};\n//    BOOST_CHECK_EQUAL( a1.size() , 0ul );\n//    BOOST_CHECK( a1.empty() );\n\n    auto a2 = ublas::tensor_static<value_type, ublas::extents<1,1>,layout_type>{};\n    BOOST_CHECK_EQUAL(  a2.size() , 1 );\n    BOOST_CHECK( !a2.empty() );\n\n    auto a3 = ublas::tensor_static<value_type, ublas::extents<2,1>,layout_type>{};\n    BOOST_CHECK_EQUAL(  a3.size() , 2 );\n    BOOST_CHECK( !a3.empty() );\n\n    auto a4 = ublas::tensor_static<value_type, ublas::extents<1,2>,layout_type>{};\n    BOOST_CHECK_EQUAL(  a4.size() , 2 );\n    BOOST_CHECK( !a4.empty() );\n\n    auto a5 = ublas::tensor_static<value_type, ublas::extents<2,1>,layout_type>{};\n    BOOST_CHECK_EQUAL(  a5.size() , 2 );\n    BOOST_CHECK( !a5.empty() );\n\n    auto a6 = ublas::tensor_static<value_type, ublas::extents<4,3,2>,layout_type>{};\n    BOOST_CHECK_EQUAL(  a6.size() , 4*3*2 );\n    BOOST_CHECK( !a6.empty() );\n\n    auto a7 = ublas::tensor_static<value_type, ublas::extents<4,1,2>,layout_type>{};\n    BOOST_CHECK_EQUAL(  a7.size() , 4*1*2 );\n    BOOST_CHECK( !a7.empty() );\n\n}\n\n\nstruct fixture\n{\n    template<size_t... N>\n    using extents_type = boost::numeric::ublas::extents<N...>;\n\n    fixture()=default;\n\n    std::tuple<\n        extents_type<1,1>,   // 1\n        extents_type<2,3>,   // 2\n        extents_type<4,1,3>,  // 3\n        extents_type<4,2,3>,  // 4\n        extents_type<4,2,3,5>   // 5\n    > extents;\n};\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_ctor_extents, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n    for_each_in_tuple(extents, [](auto const& /*unused*/, auto& e){\n        using extents_type = std::decay_t<decltype(e)>;\n        auto t = ublas::tensor_static<value_type, extents_type, layout_type>{};\n\n        BOOST_CHECK_EQUAL (  t.size() , ublas::product(e) );\n        BOOST_CHECK_EQUAL (  t.rank() , ublas::size   (e) );\n        if(ublas::empty(e)) {\n            BOOST_CHECK       ( t.empty()    );\n        }\n        else{\n            BOOST_CHECK       ( !t.empty()    );\n        }\n    });\n\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_copy_ctor, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n\n    for_each_in_tuple(extents, [](auto const& /*unused*/, auto& e){\n        using extents_type = std::decay_t<decltype(e)>;\n        auto r = ublas::tensor_static<value_type, extents_type, layout_type>{0};\n\n        auto t = r;\n        BOOST_CHECK_EQUAL (  t.size() , r.size() );\n        BOOST_CHECK_EQUAL (  t.rank() , r.rank() );\n        BOOST_CHECK ( t.strides() == r.strides() );\n        BOOST_CHECK ( t.extents() == r.extents() );\n\n        if(ublas::empty(e)) {\n            BOOST_CHECK       ( t.empty()    );\n        }\n        else{\n            BOOST_CHECK       ( !t.empty()    );\n        }\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_TEST( t[i] == r[i]);\n\n    });\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_copy_ctor_layout, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using other_layout_type = std::conditional_t<std::is_same<ublas::layout::first_order,layout_type>::value, ublas::layout::last_order, ublas::layout::first_order>;\n\n\n    for_each_in_tuple(extents, [](auto const& /*unused*/, auto& e){\n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type, extents_type, layout_type>;\n        auto r = tensor_type{0};\n        ublas::tensor_static<value_type, extents_type, other_layout_type> t = r;\n        tensor_type q = t;\n\n        BOOST_CHECK_EQUAL (  t.size() , r.size() );\n        BOOST_CHECK_EQUAL (  t.rank() , r.rank() );\n        BOOST_CHECK ( t.extents() == r.extents() );\n\n        BOOST_CHECK_EQUAL (  q.size() , r.size() );\n        BOOST_CHECK_EQUAL (  q.rank() , r.rank() );\n        BOOST_CHECK ( q.strides() == r.strides() );\n        BOOST_CHECK ( q.extents() == r.extents() );\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_TEST( q[i] == r[i]);\n\n    });\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_copy_move_ctor, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n    auto check = [](auto const& /*unused*/, auto& e)\n    {\n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type, extents_type, layout_type>;\n        auto r = tensor_type{};\n        auto t = std::move(r);\n        BOOST_CHECK_EQUAL (  t.size() , ublas::product(e) );\n        BOOST_CHECK_EQUAL (  t.rank() , ublas::size   (e) );\n\n        if(ublas::empty(e)) {\n            BOOST_CHECK       ( t.empty()    );\n        }\n        else{\n            BOOST_CHECK       ( !t.empty()    );\n        }\n\n    };\n\n    for_each_in_tuple(extents,check);\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_ctor_extents_init, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n    std::random_device device{};\n    std::minstd_rand0 generator(device());\n\n    using distribution_type = std::conditional_t<std::is_integral_v<value_type>, std::uniform_int_distribution<>, std::uniform_real_distribution<> >;\n    auto distribution = distribution_type(1,6);\n\n    for_each_in_tuple(extents, [&](auto const& /*unused*/, auto const& e){\n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type, extents_type, layout_type>;\n        \n        auto r = value_type( static_cast< inner_type_t<value_type> >(distribution(generator)) );\n        auto t = tensor_type{r};\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL( t[i], r );\n\n    });\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_ctor_extents_array, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n    for_each_in_tuple(extents, [](auto const& /*unused*/, auto& e){\n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type, extents_type, layout_type>;\n        using container_type  = typename tensor_type::container_type;\n        \n        auto a = container_type();\n        auto v = value_type {};\n\n        for(auto& aa : a){\n            aa = v;\n            v += value_type{1};\n        }\n        auto t = tensor_type(a);\n        v = value_type{};\n\n        for(auto i = 0ul; i < t.size(); ++i, v+=value_type{1})\n            BOOST_CHECK_EQUAL( t[i], v);\n\n    });\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_read_write_single_index_access, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n    for_each_in_tuple(extents, [](auto const& /*unused*/, auto& e){\n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type, extents_type, layout_type>;\n        \n        auto t = tensor_type{};\n        auto v = value_type {};\n        for(auto i = 0ul; i < t.size(); ++i, v+=value_type{1}){\n            t[i] = v;\n            BOOST_CHECK_EQUAL( t[i], v );\n\n            t(i) = v;\n            BOOST_CHECK_EQUAL( t(i), v );\n        }\n\n    });\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_read_write_multi_index_access_at, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n    auto check1 = [](const auto& t)\n    {\n        auto v = value_type{};\n        for(auto k = 0ul; k < t.size(); ++k){\n            BOOST_CHECK_EQUAL(t[k], v);\n            v+=value_type{1};\n        }\n    };\n\n    auto check2 = [](const auto& t)\n    {\n      std::array<unsigned,2> k = {0,0};\n        auto r = std::is_same<layout_type,ublas::layout::first_order>::value ? 1 : 0;\n        auto q = std::is_same<layout_type,ublas::layout::last_order >::value ? 1 : 0;\n        auto v = value_type{};\n        for(k[r] = 0ul; k[r] < t.size(r); ++k[r]){\n            for(k[q] = 0ul; k[q] < t.size(q); ++k[q]){\n                BOOST_CHECK_EQUAL(t.at(k[0],k[1]), v);\n                v+=value_type{1};\n            }\n        }\n    };\n\n    auto check3 = [](const auto& t)\n    {\n        std::array<unsigned,3> k= {0,0,0};\n        using op_type = std::conditional_t<std::is_same_v<layout_type,ublas::layout::first_order>, std::minus<>, std::plus<>>;\n        auto r = std::is_same_v<layout_type,ublas::layout::first_order> ? 2 : 0;\n        auto o = op_type{};\n        auto v = value_type{};\n        for(k[r] = 0ul; k[r] < t.size(r); ++k[r]){\n            for(k[o(r,1)] = 0ul; k[o(r,1)] < t.size(o(r,1)); ++k[o(r,1)]){\n                for(k[o(r,2)] = 0ul; k[o(r,2)] < t.size(o(r,2)); ++k[o(r,2)]){\n                    BOOST_CHECK_EQUAL(t.at(k[0],k[1],k[2]), v);\n                    v+=value_type{1};\n                }\n            }\n        }\n    };\n\n    auto check4 = [](const auto& t)\n    {\n        std::array<unsigned,4> k= {0,0,0,0};\n        using op_type = std::conditional_t<std::is_same_v<layout_type,ublas::layout::first_order>, std::minus<>, std::plus<>>;\n        auto r = std::is_same_v<layout_type,ublas::layout::first_order> ? 3 : 0;\n        auto o = op_type{};\n        auto v = value_type{};\n        for(k[r] = 0ul; k[r] < t.size(r); ++k[r]){\n            for(k[o(r,1)] = 0ul; k[o(r,1)] < t.size(o(r,1)); ++k[o(r,1)]){\n                for(k[o(r,2)] = 0ul; k[o(r,2)] < t.size(o(r,2)); ++k[o(r,2)]){\n                    for(k[o(r,3)] = 0ul; k[o(r,3)] < t.size(o(r,3)); ++k[o(r,3)]){\n                        BOOST_CHECK_EQUAL(t.at(k[0],k[1],k[2],k[3]), v);\n                        v+=value_type{1};\n                    }\n                }\n            }\n        }\n    };\n\n    auto check = [check1,check2,check3,check4](auto const& /*unused*/, auto const& e) {\n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type, extents_type, layout_type>;\n        auto t = tensor_type{};\n        auto v = value_type {};\n        for(auto i = 0ul; i < t.size(); ++i){\n            t[i] = v;\n            v+=value_type{1};\n        }\n\n        if constexpr      ( std::tuple_size_v<extents_type> == 1) check1(t);\n        else if constexpr ( std::tuple_size_v<extents_type> == 2) check2(t);\n        else if constexpr ( std::tuple_size_v<extents_type> == 3) check3(t);\n        else if constexpr ( std::tuple_size_v<extents_type> == 4) check4(t);\n\n    };\n\n    for_each_in_tuple(extents,check);\n}\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_standard_iterator, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n    for_each_in_tuple(extents,[](auto const& /*unused*/, auto& e){\n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type, extents_type, layout_type>;\n        \n        auto v = value_type {} + value_type{1};\n        auto t = tensor_type{v};\n\n        BOOST_CHECK_EQUAL( std::distance(t.begin(),  t.end ()), t.size()  );\n        BOOST_CHECK_EQUAL( std::distance(t.rbegin(), t.rend()), t.size()  );\n\n        BOOST_CHECK_EQUAL( std::distance(t.cbegin(),  t.cend ()), t.size() );\n        BOOST_CHECK_EQUAL( std::distance(t.crbegin(), t.crend()), t.size() );\n\n        if(!t.empty()) {\n            BOOST_CHECK(  t.data() ==  std::addressof( *t.begin () )  ) ;\n            BOOST_CHECK(  t.data() ==  std::addressof( *t.cbegin() )  ) ;\n        }\n    });\n\n}\n\n//BOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_throw, value, test_types, fixture)\n//{\n//  namespace ublas = boost::numeric::ublas;\n//  using value_type  = typename value::first_type;\n//  using layout_type = typename value::second_type;\n//  using tensor_type = ublas::tensor_static<value_type, ublas::extents<5,5>, layout_type>;\n\n//  auto t = tensor_type{};\n//  auto i = ublas::index::index_type<4>{};\n//  BOOST_CHECK_THROW((void)t.operator()(i,i,i), std::runtime_error);\n\n//}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "653a2726bd4c53235a6a541992c9f3d84b05dbdb", "size": 13624, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_static_tensor.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_static_tensor.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_static_tensor.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 34.1453634085, "max_line_length": 165, "alphanum_fraction": 0.5967410452, "num_tokens": 3762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.5248801827234829}}
{"text": "#include \"camera_array/SystemDistributions.h\"\n#include <boost/foreach.hpp>\n\n#define POSE_DIM (PoseSE3::TangentDimension)\n\nnamespace argus\n{\n\nRobotTargetDistribution::Properties::Properties( bool targetPose, bool targetVel,\n                                                 bool robotPose, bool robotVel )\n: sampleTargetPoses( targetPose ), sampleTargetVelocities( targetVel ),\n  sampleRobotPose( robotPose ), sampleRobotVelocity( robotVel ) {}\n\nRobotTargetDistribution::RobotTargetDistribution( Properties props )\n: properties( props ), gaussian( 6 )\n{}\n\t\nvoid RobotTargetDistribution::SetMean( const RobotTargetState& b )\n{\n\tbase = b;\n}\n\t\nRobotTargetState RobotTargetDistribution::Sample()\n{\n\tRobotTargetState sample( base );\n\t\n\tif( properties.sampleRobotPose )\n\t{\n\t\tPoseSE3::CovarianceMatrix poseCov = \n\t\t    base.robot.covariance.topLeftCorner( POSE_DIM, POSE_DIM );\n\t\tsample.robot.pose = SamplePose( base.robot.pose, poseCov );\n\t}\n\tif( properties.sampleRobotVelocity )\n\t{\n\t\tPoseSE3::CovarianceMatrix velCov = \n\t\t    base.robot.covariance.block( POSE_DIM, POSE_DIM, POSE_DIM, POSE_DIM );\n\t\tsample.robot.velocity = SampleVelocity( base.robot.velocity, velCov );\n\t}\n\tif( properties.sampleTargetPoses )\n\t{\n\t\tBOOST_FOREACH( const RobotTargetState::TargetMap::value_type& item, base.targets )\n\t\t{\n\t\t\tconst std::string& name = item.first;\n\t\t\tconst TargetState& state = item.second;\n\t\t\tPoseSE3::CovarianceMatrix poseCov = \n\t\t\t    state.covariance.topLeftCorner( POSE_DIM, POSE_DIM );\n\t\t\tsample.targets[ name ].pose = SamplePose( state.pose, poseCov );\n\t\t}\n\t}\n\tif( properties.sampleTargetVelocities )\n\t{\n\t\tBOOST_FOREACH( const RobotTargetState::TargetMap::value_type& item, base.targets )\n\t\t{\n\t\t\tconst std::string& name = item.first;\n\t\t\tconst TargetState& state = item.second;\n\t\t\tPoseSE3::CovarianceMatrix velCov = \n\t\t\t    state.covariance.block( POSE_DIM, POSE_DIM, POSE_DIM, POSE_DIM );\n\t\t\tsample.targets[ name ].velocity = SampleVelocity( state.velocity, velCov );\n\t\t}\n\t}\n\treturn sample;\n}\n\nPoseSE3 \nRobotTargetDistribution::SamplePose( const PoseSE3& mean, \n                                     const PoseSE3::CovarianceMatrix& cov )\n{\n\tgaussian.SetCovariance( cov );\n\tPoseSE3::TangentVector d = gaussian.Sample(2.0); // Truncates to 3 standard deviations\n\treturn mean * PoseSE3::Exp( d );\n}\n\nPoseSE3::TangentVector\nRobotTargetDistribution::SampleVelocity( const PoseSE3::TangentVector& mean,\n                                         const PoseSE3::CovarianceMatrix& cov )\n{\n\tgaussian.SetCovariance( cov );\n\treturn mean + gaussian.Sample();\n}\n\n}\n", "meta": {"hexsha": "748dcb80ddfd934f8e4abb821c1023d5fa67ceae", "size": 2544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "camera_array/src/SystemDistributions.cpp", "max_stars_repo_name": "Humhu/argus", "max_stars_repo_head_hexsha": "8b112382038c6df1ecf15d9c872b6cc9b471cd22", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-08-02T20:32:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T09:33:33.000Z", "max_issues_repo_path": "camera_array/src/SystemDistributions.cpp", "max_issues_repo_name": "Humhu/argus", "max_issues_repo_head_hexsha": "8b112382038c6df1ecf15d9c872b6cc9b471cd22", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-12T22:57:59.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-13T02:52:36.000Z", "max_forks_repo_path": "camera_array/src/SystemDistributions.cpp", "max_forks_repo_name": "Humhu/argus", "max_forks_repo_head_hexsha": "8b112382038c6df1ecf15d9c872b6cc9b471cd22", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-03-25T08:36:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-23T00:28:16.000Z", "avg_line_length": 31.0243902439, "max_line_length": 87, "alphanum_fraction": 0.7099056604, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5248066866478194}}
{"text": "#pragma once\n\n#include <vector>\n#include <boost/math/differentiation/autodiff.hpp>\n\nnamespace hmc {\n\ntemplate<class MODEL, class T>\nvoid force_ad_1d(const MODEL& model, const std::vector<T>& x, std::vector<T> *f) {\n  auto x0_fvar = boost::math::differentiation::make_fvar<double, 1>(x[0]);\n  auto p = model.potential(x0_fvar);\n  (*f)[0] = -p.derivative(1);\n}\n\ntemplate<class MODEL, class T>\nvoid force_ad_2d(const MODEL& model, const std::vector<T>& x, std::vector<T> *f) {\n  auto const fvar = boost::math::differentiation::make_ftuple<double, 1, 1>(x[0], x[1]);\n  auto const& x0_fvar = std::get<0>(fvar);\n  auto const& x1_fvar = std::get<1>(fvar);\n  auto p = model.potential(x0_fvar, x1_fvar);\n  (*f)[0] = -p.derivative(1, 0);\n  (*f)[1] = -p.derivative(0, 1);\n}\n\n}", "meta": {"hexsha": "e47cf982a91d8cbe42cce11256fe4081d6b3d2eb", "size": 765, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "hmc/force.hpp", "max_stars_repo_name": "todo-group/hmc", "max_stars_repo_head_hexsha": "f7ac2529df15363406ec8739a33061920035a3f9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-02T15:05:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T15:05:48.000Z", "max_issues_repo_path": "hmc/force.hpp", "max_issues_repo_name": "todo-group/hmc", "max_issues_repo_head_hexsha": "f7ac2529df15363406ec8739a33061920035a3f9", "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": "hmc/force.hpp", "max_forks_repo_name": "todo-group/hmc", "max_forks_repo_head_hexsha": "f7ac2529df15363406ec8739a33061920035a3f9", "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.6, "max_line_length": 88, "alphanum_fraction": 0.6653594771, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.5248066762203009}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_BINOMIAL_COEFFICIENT_LOG_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_BINOMIAL_COEFFICIENT_LOG_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/scal/fun/inv.hpp>\n#include <stan/math/prim/scal/fun/lgamma.hpp>\n#include <stan/math/prim/scal/fun/multiply_log.hpp>\n#include <boost/math/tools/promotion.hpp>\n\nnamespace stan {\nnamespace math {\n/**\n * Return the log of the binomial coefficient for the specified\n * arguments.\n *\n * The binomial coefficient, \\f${N \\choose n}\\f$, read \"N choose n\", is\n * defined for \\f$0 \\leq n \\leq N\\f$ by\n *\n * \\f${N \\choose n} = \\frac{N!}{n! (N-n)!}\\f$.\n *\n * This function uses Gamma functions to define the log\n * and generalize the arguments to continuous N and n.\n *\n * \\f$ \\log {N \\choose n}\n * = \\log \\ \\Gamma(N+1) - \\log \\Gamma(n+1) - \\log \\Gamma(N-n+1)\\f$.\n *\n   \\f[\n   \\mbox{binomial\\_coefficient\\_log}(x, y) =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } y > x \\textrm{ or } y < 0\\\\\n     \\ln\\Gamma(x+1) & \\mbox{if } 0\\leq y \\leq x \\\\\n     \\quad -\\ln\\Gamma(y+1)& \\\\\n     \\quad -\\ln\\Gamma(x-y+1)& \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{binomial\\_coefficient\\_log}(x, y)}{\\partial x} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } y > x \\textrm{ or } y < 0\\\\\n     \\Psi(x+1) & \\mbox{if } 0\\leq y \\leq x \\\\\n     \\quad -\\Psi(x-y+1)& \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{binomial\\_coefficient\\_log}(x, y)}{\\partial y} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } y > x \\textrm{ or } y < 0\\\\\n     -\\Psi(y+1) & \\mbox{if } 0\\leq y \\leq x \\\\\n     \\quad +\\Psi(x-y+1)& \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n *\n * @param N total number of objects.\n * @param n number of objects chosen.\n * @return log (N choose n).\n */\ntemplate <typename T_N, typename T_n>\ninline return_type_t<T_N, T_n> binomial_coefficient_log(const T_N N,\n                                                        const T_n n) {\n  using std::log;\n  const double CUTOFF = 1000;\n  if (N - n < CUTOFF) {\n    const T_N N_plus_1 = N + 1;\n    return lgamma(N_plus_1) - lgamma(n + 1) - lgamma(N_plus_1 - n);\n  } else {\n    return_type_t<T_N, T_n> N_minus_n = N - n;\n    const double one_twelfth = inv(12);\n    return multiply_log(n, N_minus_n) + multiply_log((N + 0.5), N / N_minus_n)\n           + one_twelfth / N - n - one_twelfth / N_minus_n - lgamma(n + 1);\n  }\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "1077c2a7e4063bb361a79b937b8f18afcb3d2628", "size": 2611, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/binomial_coefficient_log.hpp", "max_stars_repo_name": "PhilClemson/math", "max_stars_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "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": "stan/math/prim/scal/fun/binomial_coefficient_log.hpp", "max_issues_repo_name": "PhilClemson/math", "max_issues_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "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": "src/stan/math/prim/scal/fun/binomial_coefficient_log.hpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2345679012, "max_line_length": 78, "alphanum_fraction": 0.5928762926, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5248066750668302}}
{"text": "/*\n* Copyright 2019 \u00a9 Centre Interdisciplinaire de d\u00e9veloppement en Cartographie des Oc\u00e9ans (CIDCO), Tous droits r\u00e9serv\u00e9s\n*/\n\n /*\n * \\author Christian Bouchard\n */\n\n#ifndef HULLOVERLAP_HPP\n#define HULLOVERLAP_HPP\n\n#include <iostream>\n#include <cstdint>\n\n#include <vector>\n\n#include <utility>      // std::pair, std::make_pair\n\n#include <limits>       // std::numeric_limits\n\n\n#include <pcl/common/common_headers.h>\n\n#include <pcl/point_types.h>\n#include <pcl/surface/concave_hull.h>\n\n#include <pcl/PointIndices.h>\n\n#include <pcl/ModelCoefficients.h>\n#include <pcl/filters/project_inliers.h>\n\n#include <pcl/segmentation/extract_polygonal_prism_data.h>\n\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry> // For cross product\n\n\n//-----------------------------------------------------------------------------------\n// Andrew's monotone chain convex hull algorithm\n// Adapted from\n// https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain#C++\n\ntypedef float coord_t;      // coordinate type (Use float because pcl::PointXYZ's coordinates are float)\ntypedef double coord2_t;    // must be big enough to hold 2*max(|coordinate|)^2\n\nstruct PointAndrews\n{\n\tcoord_t x;\n    coord_t y;\n    uint64_t index;\n\n\tbool operator <( const PointAndrews &p ) const\n    {\n\t\treturn x < p.x || (x == p.x && y < p.y);\n\t}\n};\n\n\n// 3D cross product of OA and OB vectors, (i.e z-component of their \"2D\" cross product,\n// but remember that it is not defined in \"2D\").\n// Returns a positive value, if OAB makes a counter-clockwise turn,\n// negative for clockwise turn, and zero if the points are collinear.\ncoord2_t cross( const PointAndrews &O, const PointAndrews &A, const PointAndrews &B )\n{\n\treturn (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);\n}\n\n// Returns a list of points on the convex hull in counter-clockwise order.\n// Note: the last point in the returned list is the same as the first one.\n// CB: vector points is modified by getting sorted.\nvoid AndrewsConvex_hull( std::vector<PointAndrews> & hull, std::vector<PointAndrews> & points )\n{\n\tsize_t n = points.size(), k = 0;\n\n    hull.clear();\n\n    if ( n <= 3 )\n    {\n        hull.reserve( n );\n\n        for ( int count = 0; count < n; count++ )\n            hull.push_back( points[ count ] );\n\n        return;\n    }\n\n    hull.resize( 2 * n );\n\n\t// Sort points lexicographically\n\tsort(points.begin(), points.end());\n\n\t// Build lower hull\n\tfor (size_t i = 0; i < n; ++i)\n    {\n\t\twhile (k >= 2 && cross(hull[k-2], hull[k-1], points[i]) <= 0)\n            k--;\n\n\t\thull[k++] = points[i];\n\t}\n\n\t// Build upper hull\n\tfor (size_t i = n-1, t = k+1; i > 0; --i)\n    {\n\t\twhile (k >= t && cross(hull[k-2], hull[k-1], points[i-1]) <= 0)\n            k--;\n\n\t\thull[k++] = points[i-1];\n\t}\n\n\thull.resize(k-1);\n\n}\n\n//-----------------------------------------------------------------------------------\n\n\n\nclass HullOverlap\n{\n\npublic:\n\n\t/**\n\t* Creates a HullOverlap\n\t*\n\t* @param line1In Point cloud for line #1\n\t* @param line2In Point cloud for line #2\n    * @param a projection plane coefficient 'a' in ax + by + cz + d = 0\n    * @param b projection plane coefficient 'b' in ax + by + cz + d = 0\n    * @param c projection plane coefficient 'c' in ax + by + cz + d = 0\n    * @param d projection plane coefficient 'd' in ax + by + cz + d = 0\n    * @param hullMethod Method to find the hulls, possible values: \"PCL ConcaveHull\", \"Andrew's\"\n    * @param alpha1 Concave hull computation parameter to use with line #1\n    * @param alpha2 Concave hull computation parameter to use with line #2\n\t*/\n    HullOverlap( pcl::PointCloud<pcl::PointXYZ>::ConstPtr line1In,\n                    pcl::PointCloud<pcl::PointXYZ>::ConstPtr line2In,\n                    double a, double b, double c, double d, std::string hullMethod = \"Andrew's\",\n                    double alphaLine1 = 1.0, double alphaLine2 = 1.0 )\n                    :   line1( line1In ), line2( line2In ),\n                        a( a ), b( b ), c( c ), d( d ),\n                        hullMethod( hullMethod ),\n\n                        alphaLine1( alphaLine1 ), alphaLine2( alphaLine2 ),\n\n                        coefficients ( new pcl::ModelCoefficients() ),\n\n                        line1InPlane (new pcl::PointCloud<pcl::PointXYZ>),\n                        line2InPlane (new pcl::PointCloud<pcl::PointXYZ>),\n\n                        line1InPlane2D (new pcl::PointCloud<pcl::PointXYZ>),\n                        line2InPlane2D (new pcl::PointCloud<pcl::PointXYZ>),\n\n                        hull1Vertices (new pcl::PointCloud<pcl::PointXYZ>),\n                        hull2Vertices (new pcl::PointCloud<pcl::PointXYZ>),\n\n                       // Initialize to dummy values\n                       vector1( 1, 0, 0 ), vector2( 0, 1, 0 ), refPoint( 0.0, 0.0, 0.0 )\n\n    {\n        coefficients->values.resize(4);\n        coefficients->values[0] = a;\n        coefficients->values[1] = b;\n        coefficients->values[2] = c;\n        coefficients->values[3] = d;\n\n        if ( hullMethod != \"PCL ConcaveHull\" && hullMethod != \"Andrew's\" )\n        {\n            std::cerr << \"\\n\\nHullOverlap::HullOverlap(), method \\\"\"<<  hullMethod\n                << \"\\\" is not a valid method to find the hull.\\n\\n\" << std::endl;\n            exit( 1 );\n        }\n\n\n\n    }\n\n\n\t/**\n\t* Returns a pair with the number of points in line #1 and in line #2 that are in the overlap area of the two lines.\n\t* The points are place in the point clouds pointed to by line1InBothHull and line2InBothHull\n    *\n\t* @param[out] line1InBothHull Point cloud of points in line #1 in the overlap area of the two lines\n\t* @param[out] line2InBothHull Point cloud of points in line #2 in the overlap area of the two lines\n\t*/\n    std::pair< uint64_t, uint64_t > computePointsInBothHulls( pcl::PointCloud<pcl::PointXYZ>::Ptr line1InBothHull,\n                                                              pcl::PointCloud<pcl::PointXYZ>::Ptr line2InBothHull )\n    {\n        return computeHullsAndPointsInBothHulls( line1InBothHull, line2InBothHull, true );\n    }\n\n\n\n\t/**\n\t* Returns a pair with the number of points in line #1 and in line #2 that are in the overlap area of the two lines,\n\t* the points are place in the point clouds pointed to by line1InBothHull and line2InBothHull\n    *\n\t* @param[out] line1InBothHull Point cloud of points in line #1 in the overlap area of the two lines\n\t* @param[out] line2InBothHull Point cloud of points in line #2 in the overlap area of the two lines\n    * @param[in] line2InBothHull minimalMemory bool variable, true to specify to try and minimize the memory usage\n\t*/\n    // Put back to public to be able to get indices to the points\n    std::pair< uint64_t, uint64_t > computeHullsAndPointsInBothHulls(\n                                                pcl::PointCloud<pcl::PointXYZ>::Ptr line1InBothHull = nullptr,\n                                                pcl::PointCloud<pcl::PointXYZ>::Ptr line2InBothHull = nullptr,\n                                                const bool minimalMemory = false )\n    {\n\n        if ( line1InBothHull != nullptr )\n            line1InBothHull->clear();\n\n        if ( line2InBothHull != nullptr )\n            line2InBothHull->clear();\n\n\n        std::cout << \"\\nProjecting line 1 in plane\\n\" << std::endl;\n\n        // Project line 1 in plane\n        createCloudFromProjectionInPlane( line1, line1InPlane );\n\n        std::cout << \"line1InPlane->points.size(): \" << line1InPlane->points.size() << \"\\n\" << std::endl;\n\n        computeTwoVectorsAndRefPoint();\n\n        std::cout << \"\\nExpressing points of line 1 in the projection plane using a 2D coordinate system\\n\" << std::endl;\n\n        createCloudInPlane2D( line1InPlane, line1InPlane2D );\n\n        if ( minimalMemory )\n        {\n            // Delete the dynamically allocated memory\n            line1InPlane.reset();\n            line1InPlane = nullptr;\n        }\n\n        std::cout << \"line1InPlane2D->points.size(): \" << line1InPlane2D->points.size() << \"\\n\" << std::endl;\n\n\n        std::cout << \"\\nProjecting line 2 in plane\\n\" << std::endl;\n\n        // Project line 2 in plane\n        createCloudFromProjectionInPlane( line2, line2InPlane );\n\n        std::cout << \"line2InPlane->points.size(): \" << line2InPlane->points.size() << \"\\n\" << std::endl;\n\n        std::cout << \"\\nExpressing points of line 2 in the projection plane using a 2D coordinate system\\n\" << std::endl;\n\n        createCloudInPlane2D( line2InPlane, line2InPlane2D );\n\n        if ( minimalMemory )\n        {\n            // Delete the dynamically allocated memory\n            line2InPlane.reset();\n            line2InPlane = nullptr;\n        }\n\n\n        std::cout << \"line2InPlane2D->points.size(): \" << line2InPlane2D->points.size() << \"\\n\" << std::endl;\n\n\n\n        // const std::string method = \"Andrew's\";\n\n        if ( hullMethod == \"PCL ConcaveHull\" )\n        {\n            //http://www.pointclouds.org/documentation/tutorials/hull_2d.php\n\n            std::cout << \"\\nFinding Hull 1\\n\" << std::endl;\n\n            // Create a Concave Hull for line 1\n            computeVerticesOfConcaveHull( line1InPlane2D, alphaLine1, hull1Vertices, hull1PointIndices, ! minimalMemory );\n\n\n            std::cout << \"Finding Hull 2\\n\" << std::endl;\n\n            // Create a Concave Hull for line 2\n            computeVerticesOfConcaveHull( line2InPlane2D, alphaLine2, hull2Vertices, hull2PointIndices, ! minimalMemory );\n        }\n        else if ( hullMethod == \"Andrew's\" )\n        {\n            std::cout << \"\\nFinding Hull 1\\n\" << std::endl;\n\n            // Create a Hull for line 1\n            computeVerticesOfHullAndrews( line1InPlane2D, hull1Vertices, hull1PointIndices, ! minimalMemory );\n\n\n            std::cout << \"Finding Hull 2\\n\" << std::endl;\n\n            // Create a Concave Hull for line 2\n            computeVerticesOfHullAndrews( line2InPlane2D, hull2Vertices, hull2PointIndices, ! minimalMemory );\n        }\n        else\n        {\n            std::cerr << \"\\n\\nHullOverlap::computeHullsAndPointsInBothHulls(), method \\\"\"<<  hullMethod\n                << \"\\\" is not a valid method to find the hull.\\n\\n\" << std::endl;\n            exit( 1 );\n        }\n\n\n\n\n        std::cout << \"hull1Vertices->points.size(): \" << hull1Vertices->points.size() << \"\\n\"\n            << \"hull2Vertices->points.size(): \" << hull2Vertices->points.size() << \"\\n\" << std::endl;\n\n\n        // If the hulls of the lines where found correctly, points of line 1 are within the hull of line 1.\n        // So only need to check that a point of line 1 is part of hull 2 to know that it is part of both hulls.\n        // Same idea for points of line 2.\n\n\n        if ( line1InBothHull != nullptr && line2InBothHull != nullptr )\n        {\n            if ( minimalMemory )\n            {\n                std::cout << \"Finding points of Line 1 inside Hull 2\\n\\n\" << std::endl;\n\n                findPointsInHullOnlyPoints( line1, line1InPlane2D, line1InBothHull, hull2Vertices );\n\n                // Delete the dynamically allocated memory\n                line1InPlane2D.reset();\n                line1InPlane2D = nullptr;\n\n                hull2Vertices.reset();\n                hull2Vertices = nullptr;\n\n                std::cout << \"Finding points of Line 2 inside Hull 1\\n\\n\" << std::endl;\n\n                findPointsInHullOnlyPoints( line2, line2InPlane2D, line2InBothHull, hull1Vertices );\n\n                // Delete the dynamically allocated memory\n                line2InPlane2D.reset();\n                line2InPlane2D = nullptr;\n\n                hull1Vertices.reset();\n                hull1Vertices = nullptr;\n\n                std::cout << \"line1InBothHull->points.size(): \" << line1InBothHull->points.size() << \"\\n\"\n                    << \"line2InBothHull->points.size(): \" << line2InBothHull->points.size() << \"\\n\" << std::endl;\n\n                return std::make_pair( line1InBothHull->size(), line2InBothHull->size() );\n\n            }\n            else\n            {\n\n                std::cout << \"Finding points of Line 1 inside Hull 2 (and the indices)\\n\\n\" << std::endl;\n\n                findPointsInHull( line1, line1InPlane2D, line1InBothHull, line1InBothHullPointIndices, hull2Vertices );\n\n\n                std::cout << \"Finding points of Line 2 inside Hull 1 (and the indices)\\n\\n\" << std::endl;\n\n                findPointsInHull( line2, line2InPlane2D, line2InBothHull, line2InBothHullPointIndices, hull1Vertices );\n\n\n                std::cout << \"line1InBothHull->points.size(): \" << line1InBothHull->points.size() << \"\\n\"\n                    << \"line2InBothHull->points.size(): \" << line2InBothHull->points.size() << \"\\n\" << std::endl;\n\n                return std::make_pair( line1InBothHull->size(), line2InBothHull->size() );\n\n\n            }\n\n\n        }\n        else\n        {\n            std::cout << \"Finding indices of points of Line 1 inside Hull 2\\n\\n\" << std::endl;\n\n            findPointsInHullOnlyPointIndices( line1InPlane2D, line1InBothHullPointIndices, hull2Vertices );\n\n\n            std::cout << \"Finding indices of points of Line 2 inside Hull 1\\n\\n\" << std::endl;\n\n            findPointsInHullOnlyPointIndices( line2InPlane2D, line2InBothHullPointIndices, hull1Vertices );\n\n\n            std::cout << \"line1InBothHullPointIndices.size(): \" << line1InBothHullPointIndices.size() << \"\\n\"\n                << \"line2InBothHullPointIndices.size(): \" << line2InBothHullPointIndices.size() << \"\\n\" << std::endl;\n\n            return std::make_pair( line1InBothHullPointIndices.size(), line2InBothHullPointIndices.size() );\n        }\n\n\n    }\n\n\n    // Uncommented to get access to the point indices\n    // const std::vector< uint64_t > * getConstPtrlineInBothHullPointIndices( const bool isLine1 )\n    const std::vector< uint64_t > * getConstPtrlineInBothHullPointIndices( const int lineNumber ) const\n    {\n\n        if ( lineNumber < 0 || lineNumber > 1 )\n        {\n            std::cout << \"\\n\\n----- Function HullOverlap::getConstPtrlineInBothHullPointIndices(): lineNumber parameter: \"\n                << lineNumber << \".\\nIt must be either 0 or 1. Returning nullptr\\n\" << std::endl;\n            return nullptr;\n        }\n\n        if ( lineNumber == 0 )\n            return & ( line1InBothHullPointIndices );\n        else\n            return & ( line2InBothHullPointIndices );\n\n        // if ( isLine1 )\n        //     return & ( line1InBothHullPointIndices );\n        // else\n        //     return & ( line2InBothHullPointIndices );\n    }\n\n    // pcl::PointCloud< pcl::PointXYZ >::ConstPtr getConstPtrlineInPlane2D( const bool isLine1 )\n    pcl::PointCloud< pcl::PointXYZ >::ConstPtr getConstPtrlineInPlane2D( const int lineNumber  ) const\n    {\n\n        if ( lineNumber < 0 || lineNumber > 1 )\n        {\n            std::cout << \"\\n\\n----- Function HullOverlap::getConstPtrlineInPlane2D(): lineNumber parameter: \"\n                << lineNumber << \".\\nIt must be either 0 or 1. Returning nullptr\\n\" << std::endl;\n            return nullptr;\n        }\n\n        if ( lineNumber == 0 )\n            return line1InPlane2D;\n        else\n            return line2InPlane2D;\n\n        // if ( isLine1 )\n        //     return line1InPlane2D;\n        // else\n        //     return line2InPlane2D;\n    }\n\n\n\n    pcl::PointCloud< pcl::PointXYZ >::ConstPtr getConstPtrlineInPlane3D( const int lineNumber  ) const\n    {\n\n        if ( lineNumber < 0 || lineNumber > 1 )\n        {\n            std::cout << \"\\n\\n----- Function HullOverlap::getConstPtrlineInPlane3D(): lineNumber parameter: \"\n                << lineNumber << \".\\nIt must be either 0 or 1. Returning nullptr\\n\" << std::endl;\n            return nullptr;\n        }\n\n        if ( lineNumber == 0 )\n            return line1InPlane;\n        else\n            return line2InPlane;\n    }\n\n\n    const std::vector< int > * getConstPtrVerticesIndices( const int lineNumber ) const\n    {\n        if ( lineNumber < 0 || lineNumber > 1 )\n        {\n            std::cout << \"\\n\\n----- Function HullOverlap::getConstPtrVerticesIndices(): lineNumber parameter: \"\n                << lineNumber << \".\\nIt must be either 0 or 1. Returning nullptr\\n\" << std::endl;\n            return nullptr;\n        }\n\n        if ( lineNumber == 0 )\n            return & ( hull1PointIndices.indices );\n        else\n            return & ( hull2PointIndices.indices );\n    }\n\n\n\n    bool getMinMaxPointsInOverlapPlane2D( pcl::PointXYZ & minPt, pcl::PointXYZ &maxPt )\n    {\n        bool OK = false;\n\n        // if there are points in both lines in the overlap\n        if ( line1InBothHullPointIndices.size() > 0 && line2InBothHullPointIndices.size() > 0 )\n        {\n\n            double xMin = std::numeric_limits<double>::max();\n            double xMax = std::numeric_limits<double>::min();\n\n            double yMin = std::numeric_limits<double>::max();\n            double yMax = std::numeric_limits<double>::min();\n\n            for ( uint64_t count = 0; count < line1InBothHullPointIndices.size(); count++ )\n            {\n                if ( line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].x < xMin )\n                    xMin = line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].x;\n\n                if ( line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].x > xMax )\n                    xMax = line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].x;\n\n\n                if ( line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].y < yMin )\n                    yMin = line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].y;\n\n                if ( line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].y > yMax )\n                    yMax = line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].y;\n            }\n\n            for ( uint64_t count = 0; count < line2InBothHullPointIndices.size(); count++ )\n            {\n                if ( line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].x < xMin )\n                    xMin = line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].x;\n\n                if ( line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].x > xMax )\n                    xMax = line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].x;\n\n\n                if ( line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].y < yMin )\n                    yMin = line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].y;\n\n                if ( line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].y > yMax )\n                    yMax = line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].y;\n            }\n\n            minPt.x = xMin;\n            minPt.y = yMin;\n            minPt.z = 0;\n\n            maxPt.x = xMax;\n            maxPt.y = yMax;\n            maxPt.z = 0;\n\n            OK = true;\n\n        }\n\n        return OK;\n    }\n\n\n    bool getMinMaxPointsInOverlapPlane3D( pcl::PointXYZ & minPt, pcl::PointXYZ &maxPt )\n    {\n        bool OK = false;\n\n        // if there are points in both lines in the overlap\n        if ( line1InBothHullPointIndices.size() > 0 && line2InBothHullPointIndices.size() > 0 )\n        {\n\n            double xMin = std::numeric_limits<double>::max();\n            double xMax = std::numeric_limits<double>::min();\n\n            double yMin = std::numeric_limits<double>::max();\n            double yMax = std::numeric_limits<double>::min();\n\n            double zMin = std::numeric_limits<double>::max();\n            double zMax = std::numeric_limits<double>::min();\n\n            for ( uint64_t count = 0; count < line1InBothHullPointIndices.size(); count++ )\n            {\n                if ( line1InPlane->points[ line1InBothHullPointIndices[ count ] ].x < xMin )\n                    xMin = line1InPlane->points[ line1InBothHullPointIndices[ count ] ].x;\n\n                if ( line1InPlane->points[ line1InBothHullPointIndices[ count ] ].x > xMax )\n                    xMax = line1InPlane->points[ line1InBothHullPointIndices[ count ] ].x;\n\n\n                if ( line1InPlane->points[ line1InBothHullPointIndices[ count ] ].y < yMin )\n                    yMin = line1InPlane->points[ line1InBothHullPointIndices[ count ] ].y;\n\n                if ( line1InPlane->points[ line1InBothHullPointIndices[ count ] ].y > yMax )\n                    yMax = line1InPlane->points[ line1InBothHullPointIndices[ count ] ].y;\n\n\n                if ( line1InPlane->points[ line1InBothHullPointIndices[ count ] ].z < zMin )\n                    zMin = line1InPlane->points[ line1InBothHullPointIndices[ count ] ].z;\n\n                if ( line1InPlane->points[ line1InBothHullPointIndices[ count ] ].z > zMax )\n                    zMax = line1InPlane->points[ line1InBothHullPointIndices[ count ] ].z;\n\n            }\n\n            for ( uint64_t count = 0; count < line2InBothHullPointIndices.size(); count++ )\n            {\n                if ( line2InPlane->points[ line2InBothHullPointIndices[ count ] ].x < xMin )\n                    xMin = line2InPlane->points[ line2InBothHullPointIndices[ count ] ].x;\n\n                if ( line2InPlane->points[ line2InBothHullPointIndices[ count ] ].x > xMax )\n                    xMax = line2InPlane->points[ line2InBothHullPointIndices[ count ] ].x;\n\n\n                if ( line2InPlane->points[ line2InBothHullPointIndices[ count ] ].y < yMin )\n                    yMin = line2InPlane->points[ line2InBothHullPointIndices[ count ] ].y;\n\n                if ( line2InPlane->points[ line2InBothHullPointIndices[ count ] ].y > yMax )\n                    yMax = line2InPlane->points[ line2InBothHullPointIndices[ count ] ].y;\n\n\n                if ( line2InPlane->points[ line2InBothHullPointIndices[ count ] ].z < zMin )\n                    zMin = line2InPlane->points[ line2InBothHullPointIndices[ count ] ].z;\n\n                if ( line2InPlane->points[ line2InBothHullPointIndices[ count ] ].z > zMax )\n                    zMax = line2InPlane->points[ line2InBothHullPointIndices[ count ] ].z;\n\n            }\n\n            minPt.x = xMin;\n            minPt.y = yMin;\n            minPt.z = zMin;\n\n            maxPt.x = xMax;\n            maxPt.y = yMax;\n            maxPt.z = zMax;\n\n            OK = true;\n\n        }\n\n        return OK;\n    }\n\n\n\n\n    uint64_t getNbPointsInOverlap( const int lineNumber ) const\n    {\n        if ( lineNumber < 0 || lineNumber > 1 )\n        {\n            std::cout << \"\\n\\n----- Function HullOverlap::getNbPointsInOverlap(): lineNumber parameter: \"\n                << lineNumber << \".\\nIt must be either 0 or 1. Returning 0\\n\" << std::endl;\n            return 0;\n        }\n\n\n        if ( lineNumber == 0 )\n            return line1InBothHullPointIndices.size();\n        else\n            return line2InBothHullPointIndices.size();\n    }\n\n\n\n\n//---------------------------------------------------------------------------------------------------------------------\n\nprivate:\n\n    // These functions were public when wanted to look at details of projection, etc\n    // pcl::PointCloud<pcl::PointXYZ>::ConstPtr getConstPtrLineInPlane( const bool isLine1 )\n    // {\n    //     if ( isLine1 )\n    //         return line1InPlane;\n    //     else\n    //         return line2InPlane;\n    // }\n\n\n\n\n\n\n\n\n\n\t/**\n\t* Computes the projection of a point cloud onto a plane\n    *\n    * @param[in] cloudIn Point cloud to project on the plane\n    * @param[out] cloudOut Point cloud resulting from the projection\n\t*/\n    void createCloudFromProjectionInPlane( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,\n                                                pcl::PointCloud<pcl::PointXYZ>::Ptr cloudOut )\n    {\n        cloudOut->clear();\n        cloudOut->reserve( cloudIn->points.size() );\n\n        // Create the filtering object\n        pcl::ProjectInliers<pcl::PointXYZ> proj;\n        proj.setModelType( pcl::SACMODEL_PLANE );\n\n        proj.setInputCloud( cloudIn );\n        proj.setModelCoefficients( coefficients );\n\n        proj.filter( *cloudOut );\n    }\n\n\n\t/**\n\t* Computes two vectors and sets a reference point used to express point positions on the\n    * projection plane using only two dimensions\n\t*/\n    void computeTwoVectorsAndRefPoint()\n    {\n\n        // Two vectors and a reference point to span the projection plane\n        // so that points in the projection plane can be expressed in\n        // a coordinate system with vector1, vector2, and refPoint.\n\n        refPoint = line1InPlane->points[ 0 ];\n\n        // Vector #1: from first point in line to last point in line, normalized\n\n        const uint64_t nbPointLine1 = line1InPlane->points.size();\n\n\n        vector1 << line1InPlane->points[ nbPointLine1 - 1 ].x - line1InPlane->points[ 0 ].x,\n                    line1InPlane->points[ nbPointLine1 - 1 ].y - line1InPlane->points[ 0 ].y,\n                    line1InPlane->points[ nbPointLine1 - 1 ].z - line1InPlane->points[ 0 ].z;\n\n        std::cout << \"vector1 before normalization:\\n\" << vector1 << \"\\n\\n\";\n\n\n        vector1 = vector1 / vector1.norm();\n\n        std::cout << \"vector1 after normalization:\\n\" << vector1 << \"\\n\\n\";\n\n\n        Eigen::Vector3d normalToPlane;\n\n        normalToPlane <<  a, b, c;\n\n        // Vector #2: perpendicular to the normal to the plane and to vector #1\n        vector2 = normalToPlane.cross( vector1 );\n\n        std::cout << \"vector2 before normalization:\\n\" << vector2 << \"\\n\\n\";\n\n\n        vector2 = vector2 / vector2.norm();\n\n        std::cout << \"vector2 after normalization:\\n\" << vector2 << \"\\n\\n\";\n\n        // Sanity check\n        std::cout << \"vector1 dot vector2: \" << vector1.dot( vector2 ) << \"    (should be 0)\\n\\n\";\n    }\n\n\n\t/**\n\t* Computes a 2D representation of points on the projection plane\n    *\n    * @param[in] cloudIn Point cloud on the projection plane expressed in 3D\n    * @param[out] cloudOut Point cloud on the projection plane expressed in 2D\n\t*/\n    void createCloudInPlane2D( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,\n                            pcl::PointCloud<pcl::PointXYZ>::Ptr cloudOut )\n    {\n        // Build a point cloud where points in the projection plane are expressed in\n        // the coordinate system with vector1, vector2, and refPoint.\n\n        cloudOut->clear();\n        cloudOut->reserve( cloudIn->points.size() );\n\n        for ( uint64_t count = 0; count < cloudIn->points.size(); count++ )\n        {\n            pcl::PointXYZ point;\n\n            // projection along vector 1\n            point.x = ( cloudIn->points[ count ].x - refPoint.x ) * vector1( 0 )\n                        + ( cloudIn->points[ count ].y - refPoint.y ) * vector1( 1 )\n                        + ( cloudIn->points[ count ].z - refPoint.z ) * vector1( 2 );\n\n            // projection along vector 2\n            point.y = ( cloudIn->points[ count ].x - refPoint.x ) * vector2( 0 )\n                        + ( cloudIn->points[ count ].y - refPoint.y ) * vector2( 1 )\n                        + ( cloudIn->points[ count ].z - refPoint.z ) * vector2( 2 );\n\n            point.z = 0;\n\n            cloudOut->push_back( point );\n\n        }\n    }\n\n\n\t/**\n\t* Computes the vertices of a concave hull for points on the projection plane\n    *\n    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D\n    * @param[in] alpha Concave hull computation parameter to use\n    * @param[out] hullVertices Computed vertices of the concave hull\n    * @param[out] hullPointIndices Indices of the points in cloudIn making up the hull\n    * @param[in] keepInformation bool variable, true to specify to put the indices of the points in cloudIn in hullPointIndices\n\t*/\n    void computeVerticesOfConcaveHull( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,\n                                        const double alpha,\n                                        pcl::PointCloud<pcl::PointXYZ>::Ptr hullVertices,\n                                        pcl::PointIndices & hullPointIndices, const bool keepInformation = true )\n    {\n        hullVertices->clear();\n\n        pcl::ConcaveHull<pcl::PointXYZ> concaveHull;\n\n        if ( keepInformation )\n            concaveHull.setKeepInformation( true ); // To be able to use function getHullPointIndices()\n\n        concaveHull.setInputCloud( cloudIn );\n        concaveHull.setAlpha( alpha );\n        concaveHull.reconstruct( * hullVertices );\n\n        if ( keepInformation )\n            // Get indices of points making the hull\n            concaveHull.getHullPointIndices( hullPointIndices );\n    }\n\n\n\t/**\n\t* Computes the vertices of a hull for points on the projection plane, using Andrew's monotone chain\n    *\n    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D\n    * @param[out] hullVertices Computed vertices of the concave hull\n    * @param[out] hullPointIndices Indices of the points in cloudIn making up the hull\n    * @param[in] keepInformation bool variable, true to specify to put the indices of the points in cloudIn in hullPointIndices\n\t*/\n    void computeVerticesOfHullAndrews( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,\n                                        pcl::PointCloud<pcl::PointXYZ>::Ptr hullVertices,\n                                        pcl::PointIndices & hullPointIndices, const bool keepInformation = true )\n    {\n\n        std::cout << \"\\nBefore building vector for Andrews\\n\" << std::endl;\n\n        std::vector< PointAndrews > points;\n        points.reserve( cloudIn->size() );\n\n        for ( uint64_t count = 0; count < cloudIn->size(); count++ )\n        {\n            PointAndrews point;\n\n            point.x = cloudIn->points[ count ].x;\n            point.y = cloudIn->points[ count ].y;\n            point.index = count;\n\n            points.push_back( point );\n        }\n\n        std::cout << \"\\nBefore calling Andrews\\n\" << std::endl;\n\n        std::vector< PointAndrews > hullAndrews;\n        AndrewsConvex_hull( hullAndrews, points );\n\n        hullVertices->clear();\n        hullVertices->reserve( hullAndrews.size() );\n\n        std::cout << \"\\nAfter calling Andrews\\n\" << std::endl;\n\n        for ( uint64_t count = 0; count < hullAndrews.size(); count++ )\n        {\n            pcl::PointXYZ point;\n\n            point.x = hullAndrews[ count ].x;\n            point.y = hullAndrews[ count ].y;\n            point.z = 0;\n            hullVertices->push_back( point );\n\n        }\n\n\n        if ( keepInformation )\n        {\n            // Get indices of points making the hull\n\n            hullPointIndices.indices.clear();\n            hullPointIndices.indices.reserve( hullAndrews.size() );\n\n            for ( uint64_t count = 0; count < hullAndrews.size(); count++ )\n                hullPointIndices.indices.push_back( static_cast< int >( hullAndrews[ count ].index ) );\n\n        }\n\n    }\n\n\n\n\t/**\n\t* Find points that are within a concave hull.\n    * Provides the points and their indices within the original line\n    *\n    * @param[in] lineOriginal Point cloud of points on the line\n    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D\n    * @param[out] cloudOut Point cloud of points on the line that are within the hull\n    * @param[out] indexPointInHull Indices of the points on the line that are within the hull\n    * @param[in] hullVertices Vertices of the concave hull\n\t*/\n    void findPointsInHull( pcl::PointCloud<pcl::PointXYZ>::ConstPtr lineOriginal,\n                                pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,\n                                pcl::PointCloud<pcl::PointXYZ>::Ptr cloudOut,\n                                std::vector< uint64_t > & indexPointInHull,\n                                pcl::PointCloud<pcl::PointXYZ>::ConstPtr hullVertices )\n    {\n        cloudOut->clear();\n        indexPointInHull.clear();\n\n        for ( uint64_t count = 0; count < cloudIn->points.size(); count++ )\n        {\n            if ( pcl::isXYPointIn2DXYPolygon( cloudIn->points[ count ], *hullVertices ) )\n            {\n                cloudOut->push_back( lineOriginal->points[ count ] );\n                indexPointInHull.push_back( count );\n            }\n        }\n\n    }\n\n\n\t/**\n\t* Find indices of points that are within a concave hull.\n    *\n    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D\n    * @param[out] indexPointInHull Indices of the points on the line that are within the hull\n    * @param[in] hullVertices Vertices of the concave hull\n\t*/\n    void findPointsInHullOnlyPointIndices( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,\n                                    std::vector< uint64_t > & indexPointInHull,\n                                    pcl::PointCloud<pcl::PointXYZ>::ConstPtr hullVertices )\n    {\n        indexPointInHull.clear();\n\n        for ( uint64_t count = 0; count < cloudIn->points.size(); count++ )\n        {\n            if ( pcl::isXYPointIn2DXYPolygon( cloudIn->points[ count ], *hullVertices ) )\n                indexPointInHull.push_back( count );\n        }\n\n    }\n\n\t/**\n\t* Find points that are within a concave hull.\n    *\n    * @param[in] lineOriginal Point cloud of points on the line\n    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D\n    * @param[out] cloudOut Point cloud of points on the line that are within the hull\n    * @param[in] hullVertices Vertices of the concave hull\n\t*/\n    void findPointsInHullOnlyPoints( pcl::PointCloud<pcl::PointXYZ>::ConstPtr lineOriginal,\n                                    pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,\n                                    pcl::PointCloud<pcl::PointXYZ>::Ptr cloudOut,\n                                    pcl::PointCloud<pcl::PointXYZ>::ConstPtr hullVertices )\n    {\n        cloudOut->clear();\n\n        for ( uint64_t count = 0; count < cloudIn->points.size(); count++ )\n        {\n            if ( pcl::isXYPointIn2DXYPolygon( cloudIn->points[ count ], *hullVertices ) )\n                cloudOut->push_back( lineOriginal->points[ count ] );\n        }\n\n    }\n\n\n\n\n// ----------------------------- Variables ------------------------------------------------\n\n    /**Point cloud for line #1*/\n    const pcl::PointCloud<pcl::PointXYZ>::ConstPtr line1;\n\n    /**Point cloud for line #2*/\n    const pcl::PointCloud<pcl::PointXYZ>::ConstPtr line2;\n\n\n    /**Projection plane coefficient 'a' in ax + by + cz + d = 0*/\n    const double a;\n\n    /**Projection plane coefficient 'b' in ax + by + cz + d = 0*/\n    const double b;\n\n    /**Projection plane coefficient 'c' in ax + by + cz + d = 0*/\n    const double c;\n\n    /**Projection plane coefficient 'd' in ax + by + cz + d = 0*/\n    const double d;\n\n    //** Method to find the hulls, possible values: \"PCL ConcaveHull\", \"Andrew's\"*/\n    std::string hullMethod;\n\n    /**Concave hull computation parameter to use with line #1*/\n    double alphaLine1; // Alpha value to compute the concave hull for line #1\n\n    /**Concave hull computation parameter to use with line #2*/\n    double alphaLine2; // Alpha value to compute the concave hull for line #2\n\n    /**Coefficients for the plane, ax + by + cz + d = 0 */\n    pcl::ModelCoefficients::Ptr coefficients;\n\n    /**Point cloud of the projection of line #1 on the plane, expressed in 3D*/\n    pcl::PointCloud<pcl::PointXYZ>::Ptr line1InPlane;\n\n    /**Point cloud of the projection of line #2 on the plane, expressed in 3D*/\n    pcl::PointCloud<pcl::PointXYZ>::Ptr line2InPlane;\n\n    /**Point cloud of the projection of line #1 on the plane, expressed in 2D*/\n    pcl::PointCloud<pcl::PointXYZ>::Ptr line1InPlane2D;\n\n    /**Point cloud of the projection of line #2 on the plane, expressed in 2D*/\n    pcl::PointCloud<pcl::PointXYZ>::Ptr line2InPlane2D;\n\n\n    /**Vertices of the concave hull for line #1*/\n    pcl::PointCloud<pcl::PointXYZ>::Ptr hull1Vertices;\n\n    /**Vertices of the concave hull for line #2*/\n    pcl::PointCloud<pcl::PointXYZ>::Ptr hull2Vertices;\n\n    /**Indices of the points in line #1 whose projection on the plane makes up its hull*/\n    pcl::PointIndices hull1PointIndices;\n\n    /**Indices of the points in line #2 whose projection on the plane makes up its hull*/\n    pcl::PointIndices hull2PointIndices;\n\n    /**Indices of the points in line #1 that are within both hulls*/\n    std::vector< uint64_t > line1InBothHullPointIndices;\n\n    /**Indices of the points in line #2 that are within both hulls*/\n    std::vector< uint64_t > line2InBothHullPointIndices;\n\n\n    /**First computed orthonormal vector used to express points on the projection plane in 2D*/\n    Eigen::Vector3d vector1;\n\n    /**Second computed orthonormal vector used to express points on the projection plane in 2D*/\n    Eigen::Vector3d vector2;\n\n    /**Referenced point used to express points on the projection plane in 2D*/\n    pcl::PointXYZ refPoint;\n\n};\n\n#endif\n", "meta": {"hexsha": "3ad684b6e1f0ee0221a16750f27e4c4b7deaf935", "size": 36514, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geometry/HullOverlap.hpp", "max_stars_repo_name": "HugoValcourt/MBES-lib", "max_stars_repo_head_hexsha": "1e3aaf873a03a2e57ebcd029a5f7461c26fc9bc8", "max_stars_repo_licenses": ["MIT"], "max_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/HullOverlap.hpp", "max_issues_repo_name": "HugoValcourt/MBES-lib", "max_issues_repo_head_hexsha": "1e3aaf873a03a2e57ebcd029a5f7461c26fc9bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geometry/HullOverlap.hpp", "max_forks_repo_name": "HugoValcourt/MBES-lib", "max_forks_repo_head_hexsha": "1e3aaf873a03a2e57ebcd029a5f7461c26fc9bc8", "max_forks_repo_licenses": ["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.9036381514, "max_line_length": 127, "alphanum_fraction": 0.5902393602, "num_tokens": 9231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5248066646393119}}
{"text": "#ifndef GMM_FIT_H\n#define GMM_FIT_H\n\n#include <Eigen/Dense>\n#include <math.h>\n#include <time.h>\n#include <stdlib.h>\n#include <iostream>\n#include <avatar_locomanipulation/helpers/pseudo_inverse.hpp>\n\n\nclass GMMFit{\npublic:\n  int dim;\n  int num_clus;\n  double num_data;\n  double pi = M_PI; //3.14159265358979323846; // M_PI;\n\n  std::vector<Eigen::VectorXd> list_of_datums_raw;\n  std::vector<Eigen::VectorXd> list_of_datums;\n  std::vector<Eigen::VectorXd> list_of_mus;\n  std::vector<Eigen::MatrixXd> list_of_Sigmas;\n\n  std::vector<Eigen::MatrixXd> list_of_Sigma_inverses;\n  std::vector<double> list_of_Sigma_determinants;\n\n\n  Eigen::VectorXd alphs;\n  Eigen::MatrixXd gam;\n  Eigen::VectorXd n;\n\n  Eigen::VectorXd data_mean;\n  Eigen::VectorXd data_mean_sum;\n  Eigen::VectorXd data_min;\n  Eigen::VectorXd data_max;\n  Eigen::VectorXd data_std_dev;\n  Eigen::VectorXd data_std_dev_sqrd;\n  Eigen::VectorXd data_std_dev_sum;\n\n  Eigen::VectorXd mu_sum;\n  Eigen::MatrixXd sig_sum;\n\n  double error_init = 1000.0;\n  double tol = 1e-4;\n  double error = 1000;\n  double llh_init = 0;\n  double llh_prev_init = 0;\n  double num_iter = 100;\n  double svd_tol = 1e-4;// Tolerance for the SVD when finding the pseudoinverse and the determinant\n\n  double gmm_scaling_factor_sum = 0.0;\n\n  GMMFit();\n  GMMFit(const std::vector<Eigen::VectorXd> & data_in, const int & num_clus_in);\n\n  ~GMMFit();\n\n\n\n  void setData(const std::vector<Eigen::VectorXd> & data_in); // This function lets you input a list of datums yourself, it does not work with the normalization routine (so don't use this one if you can avoid it)\n  double multivariateGuassian(const Eigen::VectorXd & x, const Eigen::VectorXd & mu, const Eigen::MatrixXd & Sigma); //This function is just the multivariate gaussian calc.\n  double multivariateGuassian(const Eigen::VectorXd & x, const int cluster_index);\n\n  void expectStep(); // expect step of the EM alg\n  void setIter(const int & iter_in);\n  void setTol(const double & tol_in);\n  void setSVDTol(const double & svd_tol_in); // Sets the singular value threshold to use when computing the pseudo inverse and determinant\n  void maxStep(); // maximization step of the EM alg\n  double logLike(); // calculates the log likelihood for the EM alg\n  void expectationMax(); // runs the full EM alg after being given data\n  void setDim(const int & dim_in); // Sets the dimension of the problem, must be run in the beginning\n  void setNumClusters(const int & num_clus_in); // sets the number of clusters to be found or input, must be run in the beginning\n  void setMu(const std::vector<Eigen::VectorXd> & list_of_mus_in); // allows you to input a list of mus if you already have a trained model\n  void setSigma(const std::vector<Eigen::MatrixXd> & list_of_Sigmas_in); // allows you to input a list of sigmas if you already have a trained model\n  void setAlpha(const Eigen::VectorXd & alphs_in); // allows you to input an eigen vector of weights if you already have a trained model\n  void randInitialGuess(); // initializes the random guess for the initial means of the clusters between -1 and 1\n  void addData(const Eigen::VectorXd & datum); // adds one single datum and adds it to the normalization variables\n  void prepData(); // calculates the norm and the standard deviation of the data\n  void initializeNormalization(); //Initializes normalization variables. Run after setting dimension\n  void normalizeData(); // normalizes the data after it has been added using addData and you have run prepData\n  void useRawData(); // lets you use the data without normalization\n  double mixtureModelProb(const Eigen::VectorXd & x_in); // given a particular state vector, outputs its \"probability\" given a mixture model.\n  void normalizeInputCalculate(const Eigen::VectorXd & x_in, Eigen::VectorXd & x_normalized); // lets you input an unnormalized vector and you get a normalized vector\n  void setDataParams(const Eigen::VectorXd & mean_in, const Eigen::VectorXd & std_dev_in); // allows you to input the data norm and standard deviation\n  void normalizeInputInverse(const Eigen::VectorXd & x_in, Eigen::VectorXd & x_unnormalized); // allows you to input a normalized datum and it returns the unnormalized vector\n\n\n  double mixtureDenominator(const int & cluster_index); // returns the denominator value of the specified cluster index\n  void computeScalingFactorSum(); // computes the sum of the scaling factors of the GMM\n  double getScalingFactorSum(); // returns the sum of the scaling factors of the GMM\n\n  double logCost(const Eigen::VectorXd & x_in); // computes and returns the logCost (AKA feasibility cost) defined as f(x) = log(gmm_scaling_factor_sum) -log(p(x)) which is always non-zero\n\n};\n\n#endif\n", "meta": {"hexsha": "5175af5fa0d5bd130dbd0155134ba73ad9e8a382", "size": 4677, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/avatar_locomanipulation/helpers/gmm_fit.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/gmm_fit.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/gmm_fit.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": 48.2164948454, "max_line_length": 212, "alphanum_fraction": 0.7564678213, "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5248066588488174}}
{"text": "//  (C) Copyright Eric Niebler 2005.\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// Test case for extended_p_square.hpp\r\n\r\n#include <iostream>\r\n#include <boost/random.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/accumulators/numeric/functional/vector.hpp>\r\n#include <boost/accumulators/numeric/functional/complex.hpp>\r\n#include <boost/accumulators/numeric/functional/valarray.hpp>\r\n#include <boost/accumulators/accumulators.hpp>\r\n#include <boost/accumulators/statistics/stats.hpp>\r\n#include <boost/accumulators/statistics/extended_p_square.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace unit_test;\r\nusing namespace boost::accumulators;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// test_stat\r\n//\r\nvoid test_stat()\r\n{\r\n    typedef accumulator_set<double, stats<tag::extended_p_square> > accumulator_t;\r\n\r\n    // tolerance\r\n    double epsilon = 3;\r\n\r\n    // a random number generator\r\n    boost::lagged_fibonacci607 rng;\r\n\r\n    std::vector<double> probs;\r\n\r\n    probs.push_back(0.001);\r\n    probs.push_back(0.01 );\r\n    probs.push_back(0.1  );\r\n    probs.push_back(0.25 );\r\n    probs.push_back(0.5  );\r\n    probs.push_back(0.75 );\r\n    probs.push_back(0.9  );\r\n    probs.push_back(0.99 );\r\n    probs.push_back(0.999);\r\n\r\n    accumulator_t acc(extended_p_square_probabilities = probs);\r\n\r\n    for (int i=0; i<10000; ++i)\r\n        acc(rng());\r\n\r\n    BOOST_CHECK_GE(extended_p_square(acc)[0], 0.0005);\r\n    BOOST_CHECK_LE(extended_p_square(acc)[0], 0.0015);\r\n    BOOST_CHECK_CLOSE(extended_p_square(acc)[1], probs[1], 15);\r\n    BOOST_CHECK_CLOSE(extended_p_square(acc)[2], probs[2], 5);\r\n\r\n    for (std::size_t i=3; i<probs.size(); ++i)\r\n    {\r\n        BOOST_CHECK_CLOSE(extended_p_square(acc)[i], probs[i], epsilon);\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// init_unit_test_suite\r\n//\r\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n    test_suite *test = BOOST_TEST_SUITE(\"extended_p_square test\");\r\n\r\n    test->add(BOOST_TEST_CASE(&test_stat));\r\n\r\n    return test;\r\n}\r\n\r\n", "meta": {"hexsha": "1621f14abcae1173f71b63353002af6a1309acc9", "size": 2301, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/accumulators/test/extended_p_square.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/accumulators/test/extended_p_square.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/accumulators/test/extended_p_square.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": 30.2763157895, "max_line_length": 83, "alphanum_fraction": 0.642329422, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5247977850228374}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.\n\n// This file was modified by Oracle on 2015.\n// Modifications copyright (c) 2015 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, 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#ifndef BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MATRIX_TRANSFORMERS_HPP\n#define BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MATRIX_TRANSFORMERS_HPP\n\n\n#include <cstddef>\n\n// Remove the ublas checking, otherwise the inverse might fail\n// (while nothing seems to be wrong)\n#define BOOST_UBLAS_TYPE_CHECK 0\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#if defined(__clang__)\n// Avoid warning about unused UBLAS function: boost_numeric_ublas_abs\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wunused-function\"\n#endif\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#if defined(__clang__)\n#pragma clang diagnostic pop\n#endif\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/select_coordinate_type.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\nnamespace strategy { namespace transform\n{\n\n/*!\n\\brief Affine transformation strategy in Cartesian system.\n\\details The strategy serves as a generic definition of affine transformation matrix\n         and procedure of application it to given point.\n\\see http://en.wikipedia.org/wiki/Affine_transformation\n     and http://www.devmaster.net/wiki/Transformation_matrices\n\\ingroup strategies\n\\tparam Dimension1 number of dimensions to transform from\n\\tparam Dimension2 number of dimensions to transform to\n */\ntemplate\n<\n    typename CalculationType,\n    std::size_t Dimension1,\n    std::size_t Dimension2\n>\nclass ublas_transformer\n{\n};\n\n\ntemplate <typename CalculationType>\nclass ublas_transformer<CalculationType, 2, 2>\n{\nprotected :\n    typedef CalculationType ct;\n    typedef geofeatures_boost::numeric::ublas::matrix<ct> matrix_type;\n    matrix_type m_matrix;\n\npublic :\n\n    inline ublas_transformer(\n                ct const& m_0_0, ct const& m_0_1, ct const& m_0_2,\n                ct const& m_1_0, ct const& m_1_1, ct const& m_1_2,\n                ct const& m_2_0, ct const& m_2_1, ct const& m_2_2)\n        : m_matrix(3, 3)\n    {\n        m_matrix(0,0) = m_0_0;   m_matrix(0,1) = m_0_1;   m_matrix(0,2) = m_0_2;\n        m_matrix(1,0) = m_1_0;   m_matrix(1,1) = m_1_1;   m_matrix(1,2) = m_1_2;\n        m_matrix(2,0) = m_2_0;   m_matrix(2,1) = m_2_1;   m_matrix(2,2) = m_2_2;\n    }\n\n    inline ublas_transformer(matrix_type const& matrix)\n        : m_matrix(matrix)\n    {}\n\n\n    inline ublas_transformer() : m_matrix(3, 3) {}\n\n    template <typename P1, typename P2>\n    inline bool apply(P1 const& p1, P2& p2) const\n    {\n        assert_dimension_greater_equal<P1, 2>();\n        assert_dimension_greater_equal<P2, 2>();\n\n        ct const& c1 = get<0>(p1);\n        ct const& c2 = get<1>(p1);\n\n        ct p2x = c1 * m_matrix(0,0) + c2 * m_matrix(0,1) + m_matrix(0,2);\n        ct p2y = c1 * m_matrix(1,0) + c2 * m_matrix(1,1) + m_matrix(1,2);\n\n        typedef typename geometry::coordinate_type<P2>::type ct2;\n        set<0>(p2, geofeatures_boost::numeric_cast<ct2>(p2x));\n        set<1>(p2, geofeatures_boost::numeric_cast<ct2>(p2y));\n\n        return true;\n    }\n\n    matrix_type const& matrix() const { return m_matrix; }\n};\n\n\n// It IS possible to go from 3 to 2 coordinates\ntemplate <typename CalculationType>\nclass ublas_transformer<CalculationType, 3, 2> : public ublas_transformer<CalculationType, 2, 2>\n{\n    typedef CalculationType ct;\n\npublic :\n    inline ublas_transformer(\n                ct const& m_0_0, ct const& m_0_1, ct const& m_0_2,\n                ct const& m_1_0, ct const& m_1_1, ct const& m_1_2,\n                ct const& m_2_0, ct const& m_2_1, ct const& m_2_2)\n        : ublas_transformer<CalculationType, 2, 2>(\n                    m_0_0, m_0_1, m_0_2,\n                    m_1_0, m_1_1, m_1_2,\n                    m_2_0, m_2_1, m_2_2)\n    {}\n\n    inline ublas_transformer()\n        : ublas_transformer<CalculationType, 2, 2>()\n    {}\n};\n\n\ntemplate <typename CalculationType>\nclass ublas_transformer<CalculationType, 3, 3>\n{\nprotected :\n    typedef CalculationType ct;\n    typedef geofeatures_boost::numeric::ublas::matrix<ct> matrix_type;\n    matrix_type m_matrix;\n\npublic :\n    inline ublas_transformer(\n                ct const& m_0_0, ct const& m_0_1, ct const& m_0_2, ct const& m_0_3,\n                ct const& m_1_0, ct const& m_1_1, ct const& m_1_2, ct const& m_1_3,\n                ct const& m_2_0, ct const& m_2_1, ct const& m_2_2, ct const& m_2_3,\n                ct const& m_3_0, ct const& m_3_1, ct const& m_3_2, ct const& m_3_3\n                )\n        : m_matrix(4, 4)\n    {\n        m_matrix(0,0) = m_0_0; m_matrix(0,1) = m_0_1; m_matrix(0,2) = m_0_2; m_matrix(0,3) = m_0_3;\n        m_matrix(1,0) = m_1_0; m_matrix(1,1) = m_1_1; m_matrix(1,2) = m_1_2; m_matrix(1,3) = m_1_3;\n        m_matrix(2,0) = m_2_0; m_matrix(2,1) = m_2_1; m_matrix(2,2) = m_2_2; m_matrix(2,3) = m_2_3;\n        m_matrix(3,0) = m_3_0; m_matrix(3,1) = m_3_1; m_matrix(3,2) = m_3_2; m_matrix(3,3) = m_3_3;\n    }\n\n    inline ublas_transformer() : m_matrix(4, 4) {}\n\n    template <typename P1, typename P2>\n    inline bool apply(P1 const& p1, P2& p2) const\n    {\n        ct const& c1 = get<0>(p1);\n        ct const& c2 = get<1>(p1);\n        ct const& c3 = get<2>(p1);\n\n        typedef typename geometry::coordinate_type<P2>::type ct2;\n\n        set<0>(p2, geofeatures_boost::numeric_cast<ct2>(\n            c1 * m_matrix(0,0) + c2 * m_matrix(0,1) + c3 * m_matrix(0,2) + m_matrix(0,3)));\n        set<1>(p2, geofeatures_boost::numeric_cast<ct2>(\n            c1 * m_matrix(1,0) + c2 * m_matrix(1,1) + c3 * m_matrix(1,2) + m_matrix(1,3)));\n        set<2>(p2, geofeatures_boost::numeric_cast<ct2>(\n            c1 * m_matrix(2,0) + c2 * m_matrix(2,1) + c3 * m_matrix(2,2) + m_matrix(2,3)));\n\n        return true;\n    }\n\n    matrix_type const& matrix() const { return m_matrix; }\n};\n\n\n/*!\n\\brief Strategy of translate transformation in Cartesian system.\n\\details Translate moves a geometry a fixed distance in 2 or 3 dimensions.\n\\see http://en.wikipedia.org/wiki/Translation_%28geometry%29\n\\ingroup strategies\n\\tparam Dimension1 number of dimensions to transform from\n\\tparam Dimension2 number of dimensions to transform to\n */\ntemplate\n<\n    typename CalculationType,\n    std::size_t Dimension1,\n    std::size_t Dimension2\n>\nclass translate_transformer\n{\n};\n\n\ntemplate<typename CalculationType>\nclass translate_transformer<CalculationType, 2, 2> : public ublas_transformer<CalculationType, 2, 2>\n{\npublic :\n    // To have translate transformers compatible for 2/3 dimensions, the\n    // constructor takes an optional third argument doing nothing.\n    inline translate_transformer(CalculationType const& translate_x,\n                CalculationType const& translate_y,\n                CalculationType const& = 0)\n        : ublas_transformer<CalculationType, 2, 2>(\n                1, 0, translate_x,\n                0, 1, translate_y,\n                0, 0, 1)\n    {}\n};\n\n\ntemplate <typename CalculationType>\nclass translate_transformer<CalculationType, 3, 3> : public ublas_transformer<CalculationType, 3, 3>\n{\npublic :\n    inline translate_transformer(CalculationType const& translate_x,\n                CalculationType const& translate_y,\n                CalculationType const& translate_z)\n        : ublas_transformer<CalculationType, 3, 3>(\n                1, 0, 0, translate_x,\n                0, 1, 0, translate_y,\n                0, 0, 1, translate_z,\n                0, 0, 0, 1)\n    {}\n\n};\n\n\n/*!\n\\brief Strategy of scale transformation in Cartesian system.\n\\details Scale scales a geometry up or down in all its dimensions.\n\\see http://en.wikipedia.org/wiki/Scaling_%28geometry%29\n\\ingroup strategies\n\\tparam Dimension1 number of dimensions to transform from\n\\tparam Dimension2 number of dimensions to transform to\n*/\ntemplate\n<\n    typename CalculationType,\n    std::size_t Dimension1,\n    std::size_t Dimension2\n>\nclass scale_transformer\n{\n};\n\n\ntemplate <typename CalculationType>\nclass scale_transformer<CalculationType, 2, 2> : public ublas_transformer<CalculationType, 2, 2>\n{\n\npublic :\n    inline scale_transformer(CalculationType const& scale_x,\n                CalculationType const& scale_y,\n                CalculationType const& = 0)\n        : ublas_transformer<CalculationType, 2, 2>(\n                scale_x, 0,       0,\n                0,       scale_y, 0,\n                0,       0,       1)\n    {}\n\n\n    inline scale_transformer(CalculationType const& scale)\n        : ublas_transformer<CalculationType, 2, 2>(\n                scale, 0,     0,\n                0,     scale, 0,\n                0,     0,     1)\n    {}\n};\n\n\ntemplate <typename CalculationType>\nclass scale_transformer<CalculationType, 3, 3> : public ublas_transformer<CalculationType, 3, 3>\n{\npublic :\n    inline scale_transformer(CalculationType const& scale_x,\n                CalculationType const& scale_y,\n                CalculationType const& scale_z)\n        : ublas_transformer<CalculationType, 3, 3>(\n                scale_x, 0,       0,       0,\n                0,       scale_y, 0,       0,\n                0,       0,       scale_z, 0,\n                0,       0,       0,       1)\n    {}\n\n\n    inline scale_transformer(CalculationType const& scale)\n        : ublas_transformer<CalculationType, 3, 3>(\n                scale, 0,     0,     0,\n                0,     scale, 0,     0,\n                0,     0,     scale, 0,\n                0,     0,     0,     1)\n    {}\n};\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\n\ntemplate <typename DegreeOrRadian>\nstruct as_radian\n{};\n\n\ntemplate <>\nstruct as_radian<radian>\n{\n    template <typename T>\n    static inline T get(T const& value)\n    {\n        return value;\n    }\n};\n\ntemplate <>\nstruct as_radian<degree>\n{\n    template <typename T>\n    static inline T get(T const& value)\n    {\n        typedef typename promote_floating_point<T>::type promoted_type;\n        return value * math::d2r<promoted_type>();\n    }\n\n};\n\n\ntemplate\n<\n    typename CalculationType,\n    std::size_t Dimension1,\n    std::size_t Dimension2\n>\nclass rad_rotate_transformer\n    : public ublas_transformer<CalculationType, Dimension1, Dimension2>\n{\npublic :\n    inline rad_rotate_transformer(CalculationType const& angle)\n        : ublas_transformer<CalculationType, Dimension1, Dimension2>(\n                 cos(angle), sin(angle), 0,\n                -sin(angle), cos(angle), 0,\n                 0,          0,          1)\n    {}\n};\n\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\n/*!\n\\brief Strategy for rotate transformation in Cartesian coordinate system.\n\\details Rotate rotates a geometry of specified angle about a fixed point (e.g. origin).\n\\see http://en.wikipedia.org/wiki/Rotation_%28mathematics%29\n\\ingroup strategies\n\\tparam DegreeOrRadian degree/or/radian, type of rotation angle specification\n\\note A single angle is needed to specify a rotation in 2D.\n      Not yet in 3D, the 3D version requires special things to allow\n      for rotation around X, Y, Z or arbitrary axis.\n\\todo The 3D version will not compile.\n */\ntemplate\n<\n    typename DegreeOrRadian,\n    typename CalculationType,\n    std::size_t Dimension1,\n    std::size_t Dimension2\n>\nclass rotate_transformer : public detail::rad_rotate_transformer<CalculationType, Dimension1, Dimension2>\n{\n\npublic :\n    inline rotate_transformer(CalculationType const& angle)\n        : detail::rad_rotate_transformer\n            <\n                CalculationType, Dimension1, Dimension2\n            >(detail::as_radian<DegreeOrRadian>::get(angle))\n    {}\n};\n\n\n}} // namespace strategy::transform\n\n\n}} // namespace geofeatures_boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MATRIX_TRANSFORMERS_HPP\n", "meta": {"hexsha": "4fd84ae9df9d8ccd0733b7c206aa0ec60da6122f", "size": 12603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/Headers/Private/GeoFeatures/boost/geometry/strategies/transform/matrix_transformers.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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": "Pods/Headers/Private/GeoFeatures/boost/geometry/strategies/transform/matrix_transformers.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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": "Pods/Headers/Private/GeoFeatures/boost/geometry/strategies/transform/matrix_transformers.hpp", "max_forks_repo_name": "xarvey/Yuuuuuge", "max_forks_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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.2230215827, "max_line_length": 116, "alphanum_fraction": 0.6595255098, "num_tokens": 3613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321936479701, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.52475244846419}}
{"text": "/* Copyright (c) 2017, Waterloo Autonomous Vehicles Laboratory (WAVELab),\n * Waterloo Intelligent Systems Engineering Lab (WISELab),\n * University of Waterloo.\n *\n * Refer to the accompanying LICENSE file for license information.\n *\n * ############################################################################\n ******************************************************************************\n |                                                                            |\n |                         /\\/\\__/\\_/\\      /\\_/\\__/\\/\\                       |\n |                         \\          \\____/          /                       |\n |                          '----________________----'                        |\n |                              /                \\                            |\n |                            O/_____/_______/____\\O                          |\n |                            /____________________\\                          |\n |                           /    (#UNIVERSITY#)    \\                         |\n |                           |[**](#OFWATERLOO#)[**]|                         |\n |                           \\______________________/                         |\n |                            |_\"\"__|_,----,_|__\"\"_|                          |\n |                            ! !                ! !                          |\n |                            '-'                '-'                          |\n |       __    _   _  _____  ___  __  _  ___  _    _  ___  ___   ____  ____   |\n |      /  \\  | | | ||_   _|/ _ \\|  \\| |/ _ \\| \\  / |/ _ \\/ _ \\ /     |       |\n |     / /\\ \\ | |_| |  | |  ||_||| |\\  |||_|||  \\/  |||_||||_|| \\===\\ |====   |\n |    /_/  \\_\\|_____|  |_|  \\___/|_| \\_|\\___/|_|\\/|_|\\___/\\___/ ____/ |____   |\n |                                                                            |\n ******************************************************************************\n * ############################################################################\n *\n * File: pose_cov_comp.hpp\n * Desc: File containing the function for pose composition with uncertainty.\n *\n * References:\n *       [1] J. Blanco, \u201cA tutorial on se (3) transformation parameterizations\n *           and on-manifold optimization,\u201d Univ. Malaga, Tech. Rep, no. 3,\n *           pp. 1\u201356, 2014.\n * Auth: Chunshang Li and Jordan Hu\n *\n * ############################################################################\n */\n\n#ifndef WAVE_UTILS_POSE_COV_COMP_HPP_\n#define WAVE_UTILS_POSE_COV_COMP_HPP_\n\n#include <Eigen/Dense>\n\nnamespace wave {\n\ntypedef Eigen::Matrix<double, 7, 1> Vector7;\ntypedef Eigen::Matrix<double, 6, 1> Vector6;\ntypedef Eigen::Matrix<double, 4, 1> Vector4;\ntypedef Eigen::Matrix<double, 3, 1> Vector3;\ntypedef Eigen::Matrix<double, 6, 6, Eigen::RowMajor> Matrix6x6;\ntypedef Eigen::Matrix<double, 6, 7, Eigen::RowMajor> Matrix6x7;\ntypedef Eigen::Matrix<double, 7, 6, Eigen::RowMajor> Matrix7x6;\ntypedef Eigen::Matrix<double, 4, 4, Eigen::RowMajor> Matrix4x4;\ntypedef Eigen::Matrix<double, 3, 4, Eigen::RowMajor> Matrix3x4;\ntypedef Eigen::Matrix<double, 7, 7, Eigen::RowMajor> Matrix7x7;\ntypedef Eigen::Matrix<double, 3, 7, Eigen::RowMajor> Matrix3x7;\ntypedef Eigen::Matrix<double, 3, 3, Eigen::RowMajor> Matrix3x3;\n\nstruct PoseWithCovariance {\n    Vector3 position;\n    Matrix3x3 rotation_matrix;\n    Matrix6x6 covariance;\n\n    PoseWithCovariance();\n    PoseWithCovariance(Vector6 &p, Matrix6x6 &q);\n    PoseWithCovariance(Vector3 &p, Matrix3x3 &r, Matrix6x6 &q);\n    Vector3 getPosition() const;\n    Vector3 getYPR() const;\n    Eigen::Quaterniond getQuaternion() const;\n    Vector7 getPoseQuaternion() const;\n    Eigen::Affine3d getTransformMatrix() const;\n};\n\n/** Calculates the pose composition of two poses and the estimated covariance.\n *  Based on [1].\n *\n *  @param p1 first pose with covariance\n *  @param p2 second pose with covariance\n *\n *  @return composed pose with predicted covariance\n *\n */\nPoseWithCovariance composePose(PoseWithCovariance &p1, PoseWithCovariance &p);\n\n/** The Jacobian of quaternion normalization function. Quaternion in the form of\n *  [qr, qx, qt, qz]\n *  Equation (1.7)\n *\n *  @param q quaternion vector\n *\n *  @return quaternion normal wrt q Jacobian\n */\nMatrix4x4 jacobian_Quat_Norm_wrt_q(const Vector4 &q);\n\n/** The Jacobian of normalized quaternion to rpy function.\n *  Equation (2.9) to Equation (2.10)\n *\n *  @param q quaternion vector\n *\n *  @return quaternion normal to roll pitch yaw wrt q Jacobian\n */\nMatrix3x4 jacobian_Quat_Norm_to_Rpy_wrt_q(const Vector4 &q);\n\n/** The Jacobian of p7 to p6 conversion.\n *  Equation (2.12)\n *\n *  @param p pose with position and quaternion\n *\n *  @return p7 to p6 wrt p Jacobian\n */\nMatrix6x7 jacobian_p7_to_p6_wrt_p(const Vector7 &p);\n\n/** Jacobian of composing a point to a p7.\n *  Equation (3.8)\n *\n *  @param p pose with position and quaternion\n *  @param a position\n *  @return p7 point composition wrt p Jacobian\n */\nMatrix3x7 jacobian_p7_Point_Composition_wrt_p(const Vector7 &p,\n                                              const Vector3 &a);\n/** Jacobian of the composition of p7 poses.\n *  Equation (5.8)\n *\n *  @param p1 pose with position and quaternion\n *  @param p2 pose with position and quaternion\n *  @return p7 p7 composition wrt p1 Jacobian\n */\nMatrix7x7 jacobian_p7_p7_Composition_wrt_p1(const Vector7 &p1,\n                                            const Vector7 &p2);\n\n/** Jacobian of composing a point to a p7.\n *  Equation (3.10)\n *\n *  @param p pose with position and quaternion\n *  @param a position\n *  @return p7 point composition wrt a Jacobian\n */\nMatrix3x3 jacobian_p7_Point_Composition_wrt_a(const Vector7 &p,\n                                              const Vector3 &a);\n\n/** Jacobian of the composition of p7 poses.\n *  Equation (5.9)\n *\n *  @param p1 pose with position and quaternion\n *  @param p2 pose with position and quaternion\n *\n *  @return p7 p7 composition wrt p2 Jacobian\n */\nMatrix7x7 jacobian_p7_p7_Composition_wrt_p2(const Vector7 &p1,\n                                            const Vector7 &p2);\n\n/** Jacobian of converting a p6 to a p7.\n *  Equation (2.8)\n *\n *  @param p pose with position and ypr\n *  @return p6 to p7 wrt p Jacobian\n */\nMatrix7x6 jacobian_p6_to_p7_wrt_p(const Vector6 &p);\n}  // namespace wave\n\nnamespace wave {\n\n/** NOTE: wave_geometry/ has a similar implementation of the following functions\n *  but these are made to match the methods proposed in [1]. These functions\n *  should ONLY be used for pose composition based on [1].\n *\n */\nnamespace pose_comp {\n\n/** Converts Quaternion to Yaw Pitch Roll angles.\n *  Note v(0) is yaw, v(1) is pitch, v(2) is roll\n *  Equation(2.9) and Equation(2.10)\n *\n *  @param q quaternion vector\n *\n *  @return yaw pitch roll angles in rad\n */\nVector3 quatToYPR(const Eigen::Quaterniond &q);\n\n/** Converts Yaw Pitch Roll angles to Quaternion.\n *  Equation(2.3), Equation(2.4), Equation(2.5), Equation(2.6)\n *\n *  @param ypr yaw pitch roll angles in rad\n *\n *  @return quaternion vector\n */\nEigen::Quaterniond yprToQuat(const Vector3 &ypr);\n\n/** Converts Yaw Pitch Roll angles to Rotation Matrix.\n *  Equation(2.18)\n *\n *  @param ypr yaw pitch roll angles in rad\n *\n *  @return rotation matrix\n */\nMatrix3x3 yprToRotMatrix(const Vector3 &ypr);\n\n/** Converts Rotation Matrix to Yaw Pitch Roll angles.\n *  Equation(2.20), Equation(2.21), Equation(2.22), and Equation(2.23)\n *\n *  @param p rotation matrix\n *\n *  @return yaw pitch roll angles in rad\n */\nVector3 rotMatrixToYPR(const Matrix3x3 &p);\n\n/** Converts Rotation Matrix to Quaternion. According to [1], fastest way to\n *  convert from Rotation Matrix to Quat is to convert\n *  Quaternion -> Euler Angles -> Rotation Matrix\n *\n *  @param p rotation matrix\n *\n *  @return: Quaternion vector\n */\nEigen::Quaterniond rotMatrixToQuat(const Matrix3x3 &p);\n}  // namespace pose_comp\n}  // namespace wave\n\n#endif  // WAVE_UTILS_POSE_COV_COMP_HPP_\n", "meta": {"hexsha": "c476b8118229ff613e3dd1de5c5d4af93e2167f0", "size": 7909, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "wave_utils/include/wave/utils/pose_cov_comp.hpp", "max_stars_repo_name": "wavelab/wavelib", "max_stars_repo_head_hexsha": "7bebff52859c8b77f088e39913223904988c141e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2017-03-12T18:57:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:44:33.000Z", "max_issues_repo_path": "wave_utils/include/wave/utils/pose_cov_comp.hpp", "max_issues_repo_name": "wavelab/wavelib", "max_issues_repo_head_hexsha": "7bebff52859c8b77f088e39913223904988c141e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 210.0, "max_issues_repo_issues_event_min_datetime": "2017-03-13T15:01:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T03:19:44.000Z", "max_forks_repo_path": "wave_utils/include/wave/utils/pose_cov_comp.hpp", "max_forks_repo_name": "wavelab/wavelib", "max_forks_repo_head_hexsha": "7bebff52859c8b77f088e39913223904988c141e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-08-14T16:54:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T06:44:16.000Z", "avg_line_length": 35.3080357143, "max_line_length": 80, "alphanum_fraction": 0.5588569984, "num_tokens": 2011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5247524454245026}}
{"text": "#define CATCH_CONFIG_ENABLE_BENCHMARKING\n\n#include <Eigen/Dense>\n#include <catch2/catch.hpp>\n#include <unsupported/Eigen/CXX11/Tensor>\n\nusing Point3 = Eigen::Matrix<float, 3, 1>;\n\ntemplate <int IP, int TP>\nEigen::TensorFixedSize<float, Eigen::Sizes<IP, IP, TP>> DistSq(Point3 const p)\n{\n  using KTensor = Eigen::TensorFixedSize<float, Eigen::Sizes<IP, IP, TP>>;\n  using KArray = Eigen::TensorFixedSize<float, Eigen::Sizes<IP>>;\n  using FixOne = Eigen::type2index<1>;\n  using FixIn = Eigen::type2index<IP>;\n  KArray indices;\n  std::iota(indices.data(), indices.data() + IP, -IP / 2); // Note INTEGER division\n  KTensor k;\n  if constexpr (TP > 1) {\n    constexpr Eigen::IndexList<FixIn, FixOne, FixOne> rshX;\n    constexpr Eigen::IndexList<FixOne, FixIn, FixIn> brdX;\n    constexpr Eigen::IndexList<FixOne, FixIn, FixOne> rshY;\n    constexpr Eigen::IndexList<FixIn, FixOne, FixIn> brdY;\n    constexpr Eigen::IndexList<FixOne, FixOne, FixIn> rshZ;\n    constexpr Eigen::IndexList<FixIn, FixIn, FixOne> brdZ;\n    auto const kx = (indices.constant(p[0]) - indices).square().reshape(rshX).broadcast(brdX);\n    auto const ky = (indices.constant(p[1]) - indices).square().reshape(rshY).broadcast(brdY);\n    auto const kz = (indices.constant(p[2]) - indices).square().reshape(rshZ).broadcast(brdZ);\n    k = kx + ky + kz;\n  } else {\n    constexpr Eigen::IndexList<FixIn, FixOne, FixOne> rshX;\n    constexpr Eigen::IndexList<FixOne, FixIn, FixOne> brdX;\n    constexpr Eigen::IndexList<FixOne, FixIn, FixOne> rshY;\n    constexpr Eigen::IndexList<FixIn, FixOne, FixOne> brdY;\n    auto const kx = (indices.constant(p[0]) - indices).square().reshape(rshX).broadcast(brdX);\n    auto const ky = (indices.constant(p[1]) - indices).square().reshape(rshY).broadcast(brdY);\n    k = kx + ky;\n  }\n  return k;\n}\n\nTEST_CASE(\"DistSq\")\n{\n  auto const z = Point3::Zero();\n\n  BENCHMARK(\"3-1\")\n  {\n    DistSq<3, 1>(z);\n  };\n\n  BENCHMARK(\"3-3\")\n  {\n    DistSq<3, 3>(z);\n  };\n\n  BENCHMARK(\"5-1\")\n  {\n    DistSq<5, 1>(z);\n  };\n\n  BENCHMARK(\"5-5\")\n  {\n    DistSq<5, 5>(z);\n  };\n}", "meta": {"hexsha": "94fbcff6ab96e5b8dec70dc836e923656ed99237", "size": 2044, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/kernel.cpp", "max_stars_repo_name": "spinicist/riesling", "max_stars_repo_head_hexsha": "fa98ef1380345aa47d57ba91c970f37fe8fc5405", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-02-08T21:28:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T08:08:50.000Z", "max_issues_repo_path": "bench/kernel.cpp", "max_issues_repo_name": "spinicist/riesling", "max_issues_repo_head_hexsha": "fa98ef1380345aa47d57ba91c970f37fe8fc5405", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2021-02-19T11:59:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T20:45:57.000Z", "max_forks_repo_path": "bench/kernel.cpp", "max_forks_repo_name": "spinicist/riesling", "max_forks_repo_head_hexsha": "fa98ef1380345aa47d57ba91c970f37fe8fc5405", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-29T14:54:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T10:59:05.000Z", "avg_line_length": 31.4461538462, "max_line_length": 94, "alphanum_fraction": 0.6648727984, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6513548578981939, "lm_q1q2_score": 0.5247524399720964}}
{"text": "#include <iostream>\n#include <functional>\n#include <cstring>\n#include <vector>\n#include <utility>\n#include <unordered_map>\n\n#include <El.hpp>\n#include <boost/mpi.hpp>\n\n#define SKYLARK_NO_ANY\n#include <skylark.hpp>\n\n#include \"utilities.hpp\"\n#include \"parser.hpp\"\n\n/*******************************************/\nnamespace bmpi =  boost::mpi;\nnamespace skys =  skylark::sketch;\nnamespace skyb =  skylark::base;\n/*******************************************/\n\n/* These were declared as extern in utilities.hpp --- defining it here */\nint int_params [NUM_INT_PARAMETERS];\nchar* chr_params[NUM_CHR_PARAMETERS];\n\n/** Typedef DistMatrix and Matrix */\ntypedef std::vector<int> IntContainer;\ntypedef std::vector<double> DblContainer;\ntypedef El::DistMatrix<double, El::CIRC, El::CIRC> MatrixType;\ntypedef El::DistMatrix<double, El::VC, El::STAR> DistMatrixType;\n\nint main (int argc, char** argv) {\n    /* Initialize Elemental */\n    El::Initialize (argc, argv);\n\n    /* MPI sends argc and argv everywhere --- parse everywhere */\n    parse_parameters (argc,argv);\n\n    /* Initialize skylark */\n    skyb::context_t context (int_params[RAND_SEED_INDEX]);\n\n    /* Create matrices A and B */\n    bmpi::communicator world;\n    MPI_Comm mpi_world(world);\n    El::Grid grid (mpi_world);\n    El::DistMatrix<double, El::VR, El::STAR> A(grid);\n    El::DistMatrix<double, El::VR, El::STAR> B(grid);\n\n    /** Only randomization is supported for now */\n    if (0==int_params[USE_RANDOM_INDEX]) {\n        /** TODO: Read the entries! */\n        std::cout << \"We don't support reading --- yet --\" << std::endl;\n    } else {\n        El::Uniform (A, int_params[M_INDEX], int_params[N_INDEX]);\n        El::Uniform (B, int_params[M_INDEX], int_params[N_RHS_INDEX]);\n    }\n\n    /**\n     * Depending on which sketch is requested, do the sketching.\n     */\n    if (0==strcmp(\"JLT\", chr_params[TRANSFORM_INDEX]) ) {\n\n        if (SKETCH_LEFT == int_params[SKETCH_DIRECTION_INDEX]) {\n\n            /* 1. Create the sketching matrix */\n            skys::JLT_t<DistMatrixType, MatrixType> JLT (int_params[M_INDEX],\n                int_params[S_INDEX], context);\n\n            /* 2. Create space for the sketched matrix */\n            MatrixType sketch_A(int_params[S_INDEX], int_params[N_INDEX]);\n\n            /* 3. Apply the transform */\n            try {\n                JLT.apply (A, sketch_A, skys::columnwise_tag());\n            } catch (skylark::base::skylark_exception ex) {\n                SKYLARK_PRINT_EXCEPTION_DETAILS(ex);\n                SKYLARK_PRINT_EXCEPTION_TRACE(ex);\n                errno = *(boost::get_error_info<skylark::base::error_code>(ex));\n                std::cout << \"Caught exception, exiting with error \" << errno << std::endl;\n                std::cout << skylark_strerror(errno) << std::endl;\n                return errno;\n            }\n\n            /* 4. Print and see the result (if small enough) */\n            if (int_params[S_INDEX] * int_params[N_INDEX] < 100 &&\n                world.rank() == 0)\n                El::Display(sketch_A);\n\n            /** TODO: Do that same to B, and solve the system! */\n\n        } else {\n            std::cout << \"We only have left sketching. Please retry\" << std::endl;\n        }\n    } else if (0==strcmp(\"FJLT\", chr_params[TRANSFORM_INDEX]) ) {\n        if (SKETCH_LEFT == int_params[SKETCH_DIRECTION_INDEX]) {\n            /* 1. Create the sketching matrix */\n            skys::FJLT_t<DistMatrixType, MatrixType> FJLT (int_params[M_INDEX],\n                int_params[S_INDEX], context);\n\n            /* 2. Create space for the sketched matrix */\n            MatrixType sketch_A(int_params[S_INDEX], int_params[N_INDEX]);\n\n            /* 3. Apply the transform */\n            FJLT.apply (A, sketch_A, skys::columnwise_tag());\n\n            /* 4. Print and see the result */\n            if (int_params[S_INDEX] * int_params[M_INDEX] < 100 &&\n                world.rank() == 0)\n                El::Display(sketch_A);\n\n            /** TODO: Do that same to B, and solve the system! */\n\n\n        }\n    } else if (0==strcmp(\"CWT\", chr_params[TRANSFORM_INDEX]) ) {\n        if (SKETCH_LEFT == int_params[SKETCH_DIRECTION_INDEX]) {\n\n            /* 1. Create the sketching matrix */\n            skys::CWT_t<DistMatrixType, MatrixType>\n                Sparse (int_params[M_INDEX], int_params[S_INDEX], context);\n\n            /* 2. Create space for the sketched matrix */\n            MatrixType sketch_A(int_params[S_INDEX], int_params[N_INDEX]);\n\n            /* 3. Apply the transform */\n            SKYLARK_BEGIN_TRY()\n                Sparse.apply (A, sketch_A, skys::columnwise_tag());\n            SKYLARK_END_TRY()\n            SKYLARK_CATCH_AND_RETURN_ERROR_CODE();\n\n            /* 4. Print and see the result */\n            if (int_params[S_INDEX] * int_params[M_INDEX] < 100 &&\n                world.rank() == 0)\n                El::Display(sketch_A);\n\n            /** TODO: Do that same to B, and solve the system! */\n\n\n        }\n    } else {\n        std::cout << \"We only have JLT/FJLT/Sparse sketching. Please retry\" <<\n            std::endl;\n    }\n\n    El::Finalize();\n\n    return 0;\n\n}\n", "meta": {"hexsha": "748f99aae9b9d4a54ab97f43cd3a04c001ef4305", "size": 5115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/elemental.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/elemental.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/elemental.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": 33.8741721854, "max_line_length": 91, "alphanum_fraction": 0.580058651, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5247524393451277}}
{"text": "#pragma once\n#include \"rigid_body.hpp\"\n\n#include <Eigen/Geometry>\n\n#include <autodiff/autodiff_types.hpp>\n#include <utils/not_implemented_error.hpp>\n\nnamespace ipc::rigid {\n\ntemplate <typename T>\nMatrixX<T>\nRigidBody::world_vertices(const MatrixMax3<T>& R, const VectorMax3<T>& p) const\n{\n    return (vertices * R.transpose()).rowwise() + p.transpose();\n}\n\ntemplate <typename T>\nVectorMax3<T> RigidBody::world_vertex(\n    const MatrixMax3<T>& R, const VectorMax3<T>& p, const int vertex_idx) const\n{\n    // compute X[i] = R(\u03b8) * r\u1d62 + X\n    return (vertices.row(vertex_idx) * R.transpose()) + p.transpose();\n}\n\ntemplate <typename DScalar>\nEigen::MatrixXd RigidBody::world_vertices_diff(\n    const PoseD& pose,\n    long rb_v0_i,\n    Eigen::MatrixXd& V,\n    Eigen::MatrixXd& jac,\n    Eigen::MatrixXd& hess) const\n{\n    // We will only use auto diff to compute the derivatives of the rotation\n    // matrix.\n    typedef AutodiffType<Eigen::Dynamic, /*maxN=*/3> Diff;\n    // Activate autodiff with the correct number of variables.\n    Diff::activate(rot_ndof());\n\n    assert(rb_v0_i >= 0 && rb_v0_i <= V.rows() - vertices.rows());\n    assert(V.cols() == dim());\n    assert(rb_v0_i <= jac.rows() - vertices.size());\n    assert(jac.cols() == ndof());\n    bool compute_hess = hess.size() >= vertices.size() * ndof()\n        && std::is_base_of<Diff::DDouble2, DScalar>();\n    assert(\n        !compute_hess || rb_v0_i <= (hess.size() / ndof()) - vertices.size());\n\n    auto R = construct_rotation_matrix(\n        VectorMax3<DScalar>(Diff::dTvars<DScalar>(0, pose.rotation)));\n    MatrixX<DScalar> V_diff = vertices * R.transpose();\n\n    for (int i = 0; i < V_diff.rows(); i++) {\n        for (int j = 0; j < V_diff.cols(); j++) {\n            V(rb_v0_i + i, j) = get_value(V_diff(i, j)) + pose.position(j);\n\n            // Fill in gradient of V(i, j) (\u2208 R\u2076 for 3D)\n            int vij_flat = (rb_v0_i + i) * V.cols() + j;\n            jac.row(vij_flat).head(pos_ndof()).setZero();\n            jac(vij_flat, j) = 1; // \u2207p V = I\n            jac.row(vij_flat).tail(rot_ndof()) = get_gradient(V_diff(i, j));\n\n            if (compute_hess) {\n                // Fill in hessian of V(i, j) (\u2208 R\u2076\u02e3\u2076 for 3D)\n                // Hessian of position is zero\n                // \u2207\u00b2_p V = \u2207_p\u2207_r V = \u2207_r\u2207_p V = 0\n                assert(hess.cols() == ndof());\n                hess.middleRows(ndof() * vij_flat, ndof()).setZero();\n                hess.block(\n                    /*i=*/ndof() * vij_flat + pos_ndof(), /*j=*/pos_ndof(),\n                    /*p=*/rot_ndof(), /*q=*/rot_ndof()) =\n                    get_hessian(V_diff(i, j));\n            }\n        }\n    }\n\n    return V;\n}\n\n} // namespace ipc::rigid\n", "meta": {"hexsha": "b7f3c875003a7181f7b2eb45e529ac50fc5bef58", "size": 2685, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/physics/rigid_body.tpp", "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/physics/rigid_body.tpp", "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/physics/rigid_body.tpp", "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": 33.1481481481, "max_line_length": 79, "alphanum_fraction": 0.5728119181, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5247524345196904}}
{"text": "/* test_bernoulli_distribution.cpp\n *\n * Copyright Steven Watanabe 2010\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$\n *\n */\n\n#include <boost/random/bernoulli_distribution.hpp>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::bernoulli_distribution<>\n#define BOOST_RANDOM_ARG1 p\n#define BOOST_RANDOM_ARG1_DEFAULT 0.5\n#define BOOST_RANDOM_ARG1_VALUE 0.25\n\n#define BOOST_RANDOM_DIST0_MIN false\n#define BOOST_RANDOM_DIST0_MAX true\n#define BOOST_RANDOM_DIST1_MIN false\n#define BOOST_RANDOM_DIST1_MAX true\n\n#define BOOST_RANDOM_TEST1_PARAMS (0.0)\n#define BOOST_RANDOM_TEST1_MIN false\n#define BOOST_RANDOM_TEST1_MAX false\n\n#define BOOST_RANDOM_TEST2_PARAMS (1.0)\n#define BOOST_RANDOM_TEST2_MIN true\n#define BOOST_RANDOM_TEST2_MAX true\n\n#include \"test_distribution.ipp\"\n", "meta": {"hexsha": "ca021ce62011add815ecabbb36bd7f751a2db0e8", "size": 885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_bernoulli_distribution.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/random/test/test_bernoulli_distribution.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/random/test/test_bernoulli_distribution.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": 26.8181818182, "max_line_length": 73, "alphanum_fraction": 0.8203389831, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5247524332657526}}
{"text": "#include <armadillo>\n#include \"sargparse/Parameter.h\"\n\nnamespace \n{\n\narma::mat44 makeTransform(double dx, double dy, double dz, double alphaX, double alphaY, double alphaZ) {\n\tarma::mat44 translation = arma::eye(4, 4);\n\ttranslation(0, 3) = dx;\n\ttranslation(1, 3) = dy;\n\ttranslation(2, 3) = dz;\n\n\t/* align z axis to current joint this might incorporate two rotations (first the rotation around x-axis is performed, then around the y axis and around the z axis) */\n\tarma::mat44 rotX = arma::eye(4, 4);\n\tarma::mat44 rotY = arma::eye(4, 4);\n\tarma::mat44 rotZ = arma::eye(4, 4);\n\n\tif (std::abs(alphaX) >= std::numeric_limits<double>::epsilon())\n\t{\n\t\tconst double cRotX = std::cos(alphaX);\n\t\tconst double sRotX = std::sin(alphaX);\n\t\trotX(1, 1) = cRotX;\n\t\trotX(1, 2) = -sRotX;\n\t\trotX(2, 1) = sRotX;\n\t\trotX(2, 2) = cRotX;\n\t}\n\n\tif (std::abs(alphaY) >= std::numeric_limits<double>::epsilon())\n\t{\n\t\tconst double cRotY = std::cos(alphaY);\n\t\tconst double sRotY = std::sin(alphaY);\n\t\trotY(0, 0) = cRotY;\n\t\trotY(0, 2) = sRotY;\n\t\trotY(2, 0) = -sRotY;\n\t\trotY(2, 2) = cRotY;\n\t}\n\n\tif (std::abs(alphaZ) >= std::numeric_limits<double>::epsilon())\n\t{\n\t\tconst double cRotZ = std::cos(alphaZ);\n\t\tconst double sRotZ = std::sin(alphaZ);\n\t\trotZ(0, 0) = cRotZ;\n\t\trotZ(0, 1) = -sRotZ;\n\t\trotZ(1, 0) = sRotZ;\n\t\trotZ(1, 1) = cRotZ;\n\t}\n\n\treturn translation * rotX * rotY * rotZ;\n}\n\narma::mat44 transform = arma::eye(4,4);\n\nsargp::Parameter<double> rotX {1., \"rotX\", \"how much to rotate around the x axis (degrees)\", []{ transform = makeTransform(0, 0, 0, *rotX * M_PI/180., 0, 0) * transform; }};\nsargp::Parameter<double> rotY {1., \"rotY\", \"how much to rotate around the y axis (degrees)\", []{ transform = makeTransform(0, 0, 0, 0, *rotY * M_PI/180., 0) * transform; }};\nsargp::Parameter<double> rotZ {1., \"rotZ\", \"how much to rotate around the z axis (degrees)\", []{ transform = makeTransform(0, 0, 0, 0, 0, *rotZ * M_PI/180.) * transform; }};\n\nsargp::Parameter<double> movX {1., \"movX\", \"how much to move along the x axis (degrees)\", []{ transform = makeTransform(*movX, 0, 0, 0, 0, 0) * transform; }};\nsargp::Parameter<double> movY {1., \"movY\", \"how much to move along the y axis (degrees)\", []{ transform = makeTransform(0, *movY, 0, 0, 0, 0) * transform; }};\nsargp::Parameter<double> movZ {1., \"movZ\", \"how much to move along the z axis (degrees)\", []{ transform = makeTransform(0, 0, *movZ, 0, 0, 0) * transform; }};\n\nsargp::Parameter<double> scale {1., \"scale\", \"scale the STL\", []{ transform = arma::mat44{{*scale, 0, 0, 0}, {0, *scale, 0, 0}, {0, 0, *scale, 0}, {0, 0, 0, 1}} * transform;}};\n\nsargp::Parameter<double> scaleX {1., \"scaleX\", \"scale the x components of the STL\", []{ transform = arma::mat44{{*scaleX, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}} * transform;}};\nsargp::Parameter<double> scaleY {1., \"scaleY\", \"scale the y components of the STL\", []{ transform = arma::mat44{{1, 0, 0, 0}, {0, *scaleY, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}} * transform;}};\nsargp::Parameter<double> scaleZ {1., \"scaleZ\", \"scale the z components of the STL\", []{ transform = arma::mat44{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, *scaleZ, 0}, {0, 0, 0, 1}} * transform;}};\n\n}\n\narma::mat44 const& getTransform() {\n    return transform;\n}", "meta": {"hexsha": "77b6798c34dfb16f225b29219c0b85830a3e9e0a", "size": 3202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/transformer.cpp", "max_stars_repo_name": "nerdmaennchen/stl_manipulator", "max_stars_repo_head_hexsha": "5cf411b1474ee567562c1a02957935a6f009ff48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/transformer.cpp", "max_issues_repo_name": "nerdmaennchen/stl_manipulator", "max_issues_repo_head_hexsha": "5cf411b1474ee567562c1a02957935a6f009ff48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transformer.cpp", "max_forks_repo_name": "nerdmaennchen/stl_manipulator", "max_forks_repo_head_hexsha": "5cf411b1474ee567562c1a02957935a6f009ff48", "max_forks_repo_licenses": ["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.0985915493, "max_line_length": 189, "alphanum_fraction": 0.6227357901, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.5247226242035882}}
{"text": "#include <cmath>\n#include <complex>\n#include <vector>\n#include <iostream>\n\n#include <Eigen/Geometry>\n#include <Magick++.h>\n\n#include \"Constants.h\"\n#include \"ImageGenerator.h\"\n#include \"FractalInstance.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace Magick;\n\nvector<FractalInstance> fractals;\n\n// user literal for millions (i.e. 1_m = 10000000)\nconstexpr unsigned long long operator \"\" _m(unsigned long long l) {\n  return l * 1000 * 1000;\n}\n\nint main(int argc, char** argv)\n{\n  InitializeMagick(*argv);\n  \n  auto theta(0.0);\n  auto delta(2 * M_PI / NUM_FRAMES);\n\n  auto offset1(0.0);\n  auto offset2(0.0);\n  auto offset3(0.0);\n  \n  Vector3f axis1(1, 0, 0);\n  Vector3f axis2(0, 1, 0);\n  Vector3f axis3(0, 0, 1);\n\n  axis1.normalize();\n  axis2.normalize();\n  axis3.normalize();\n\n  Vector3f vec(-1/6.0, 1/120.0, -1/5040.0);\n  auto vec1(vec);\n  auto vec2(vec);\n  auto vec3(vec);\n\n  FractalInstance::num_points = 10_m;\n  FractalInstance::complex_range = 6.0;\n  FractalInstance::default_iterations = 1e2;\n\n  /* FractalInstance fi( */\n  /*   {1, vec1.x(), vec1.y(), vec1.z()}, */\n  /*   {1, 2, 4, 6}, */\n  /*   {0, 0, 3.0, 3.0} */\n  /* ); */\n\n  /* ImageGenerator::generate(fi); */\n\n  for (auto frame(1); frame <= NUM_FRAMES; ++frame)\n  {\n    FractalInstance rfi(\n      {1, vec1.x(), vec1.y(), vec1.z()},\n      {1, 2, 4, 6},\n      {0, 0, 4.0, 4.0}\n    );\n\n    FractalInstance gfi(\n      {1, vec2.x(), vec2.y(), vec2.z()},\n      {1, 2, 4, 6},\n      {0, 0, 4.0, 4.0}\n    );\n\n    FractalInstance bfi(\n      {1, vec3.x(), vec3.y(), vec3.z()},\n      {1, 2, 4, 6},\n      {0, 0, 4.0, 4.0}\n    );\n\n    ImageGenerator::generate({rfi, gfi, bfi}, frame);\n\n    theta += delta;\n    auto t1(AngleAxis<float>(theta + offset1, axis1));\n    vec1 = t1 * vec;\n    auto t2(AngleAxis<float>(theta + offset2, axis2));\n    vec2 = t2 * vec;\n    auto t3(AngleAxis<float>(theta + offset3, axis3));\n    vec3 = t3 * vec;\n  }\n  \n  return 0;\n}\n", "meta": {"hexsha": "948d4b4be64c30871044e059a320c622fa676986", "size": 1919, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GreenFractals.cpp", "max_stars_repo_name": "ecssiah/Buddhabrot-Variations", "max_stars_repo_head_hexsha": "cdc6c9c273c0e33036acf1850c1ad87e8432c37e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GreenFractals.cpp", "max_issues_repo_name": "ecssiah/Buddhabrot-Variations", "max_issues_repo_head_hexsha": "cdc6c9c273c0e33036acf1850c1ad87e8432c37e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GreenFractals.cpp", "max_forks_repo_name": "ecssiah/Buddhabrot-Variations", "max_forks_repo_head_hexsha": "cdc6c9c273c0e33036acf1850c1ad87e8432c37e", "max_forks_repo_licenses": ["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.6344086022, "max_line_length": 67, "alphanum_fraction": 0.5831162064, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5247121522662189}}
{"text": "//////////////////////////////////////////////////////////////////////////////////\n// distribution::survival::models::importance_sampling::cg.hpp \t\t\t\t\t//\n//                                                                           \t//\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                \t//\n//  Software License, Version 1.0. (See accompanying file                    \t//\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         \t//\n//////////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_IMPORTANCE_SAMPLING_CG_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_IMPORTANCE_SAMPLING_CG_HPP_ER_2009\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/statistics/detail/accumulator/statistics/proportion_less_than.hpp>\n#include <boost/statistics/detail/importance_sampling/statistics/percentage_effective_sample_size.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace distribution{\nnamespace survival{\n\n\t// cook-gelman statistic\n    template<typename It_t,typename T>\n    T cg(It_t b_target,It_t e_target,const T& threshold){\n                \n        typedef accumulator::tag::proportion_less_than tag_plt_; \n        typedef boost::accumulators::stats<tag_plt_> stats_;\n        typedef boost::accumulators::accumulator_set<T,stats_> acc_; \n        acc_ a = std::for_each(\n            b_target,\n            e_target,\n            acc_(( accumulator::keyword::threshold = threshold ))\n        );\n\t\treturn boost::accumulators::extract_result<tag_plt_>(a);\n\t}\n    \n}// survival\n}// distribution\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "48628f9f9ffef8e80db833da58add1c906e2291a", "size": 1818, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_survival/boost/statistics/detail/distribution/survival/models/common/importance_sampling/cg.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_survival/boost/statistics/detail/distribution/survival/models/common/importance_sampling/cg.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_survival/boost/statistics/detail/distribution/survival/models/common/importance_sampling/cg.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.2790697674, "max_line_length": 102, "alphanum_fraction": 0.6303630363, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5247058525750371}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,\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#include <boost/config.hpp>\n#include <vector>\n#include <deque>\n#include <iostream>\n#include <boost/graph/topological_sort.hpp>\n#include <boost/graph/adjacency_list.hpp>\nint\nmain()\n{\n  using namespace boost;\n  const char *tasks[] = {\n    \"pick up kids from school\",\n    \"buy groceries (and snacks)\",\n    \"get cash at ATM\",\n    \"drop off kids at soccer practice\",\n    \"cook dinner\",\n    \"pick up kids from soccer\",\n    \"eat dinner\"\n  };\n  const int n_tasks = sizeof(tasks) / sizeof(char *);\n\n  adjacency_list < listS, vecS, directedS > g(n_tasks);\n\n  add_edge(0, 3, g);\n  add_edge(1, 3, g);\n  add_edge(1, 4, g);\n  add_edge(2, 1, g);\n  add_edge(3, 5, g);\n  add_edge(4, 6, g);\n  add_edge(5, 6, g);\n\n  std::deque < int >topo_order;\n\n  topological_sort(g, std::front_inserter(topo_order),\n                   vertex_index_map(identity_property_map()));\n\n  int n = 1;\n  for (std::deque < int >::iterator i = topo_order.begin();\n       i != topo_order.end(); ++i, ++n)\n    std::cout << tasks[*i] << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "4acfafe7fad1c3f34c4a58386b80eb60c081d3a1", "size": 1400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/topo-sort2.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/graph/example/topo-sort2.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/graph/example/topo-sort2.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": 27.4509803922, "max_line_length": 73, "alphanum_fraction": 0.5778571429, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.524516845616633}}
{"text": "/*\n *  Created by Andrea Bedini on 21/Nov/2008.\n *  Copyright 2008-2014 Andrea Bedini <andrea@andreabedini.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\n#ifndef POLYNOMIAL_HPP_\n#define POLYNOMIAL_HPP_\n\n#include <boost/operators.hpp>\n\n#include <iosfwd>\n#include <vector>\n\ntemplate<typename T>\nclass polynomial\n  : boost::ring_operators1< polynomial<T>\n  , boost::ring_operators2< polynomial<T>, T\n  , boost::equality_comparable< polynomial<T>\n  , boost::left_shiftable<polynomial<T>, unsigned int\n  > > > >\n{\n  /// Coefficients { c_0; ...; c_n } :\n  std::vector<T> impl_;\n\n  /// remove leading zero coefficients\n  void normalize()\n  {\n    std::size_t i = order();\n    // do not remove the constant term, even if it's zero\n    while (impl_[i] == 0 and i > 1)\n      i--;\n    order(i);\n  }\n\npublic:\n  // default constructor\n  explicit polynomial(const T& a = T(0))\n    : impl_{a}\n  {\n  }\n\n  polynomial(std::initializer_list<T> list)\n    : impl_(list)\n  {\n  }\n\n  // copy constructor\n  polynomial(polynomial<T> const& rhs)\n    : impl_(rhs.impl_)\n  {\n  }\n\n  // move constructor\n  polynomial(polynomial<T>&& rhs)\n    : impl_(std::move(rhs.impl_))\n  {\n  }\n  \n  // assignemnt\n  polynomial<T>& operator=(polynomial<T> const& rhs)\n  {\n    impl_ = rhs.impl_;\n    return *this;\n  }\n\n  polynomial<T>& operator=(polynomial<T>&& rhs)\n  {\n    impl_ = std::move(rhs.impl_);\n    return *this;\n  }\n\n  // conversions\n  template<typename T2>\n  friend class polynomial;\n\n  template<class T2>\n  explicit polynomial(T2 const& a)\n    : impl_{T(a)}\n  {\n  }\n\n  template<class T2>\n  explicit polynomial(polynomial<T2> const& rhs)\n  {\n    for (auto const& c : rhs.impl_) {\n      impl_.push_back(T(c));\n    }\n  }\n  template<class T2>\n  polynomial<T>& operator=(T2 const& rhs)\n  {\n    impl_ = {T(rhs)};\n    return *this;\n  }\n\n  template<class T2>\n  polynomial<T>& operator=(polynomial<T2> const& rhs)\n  {\n    impl_.clear();\n    for (auto const& c : rhs.impl_) {\n      impl_.push_back(T(c));\n    }\n    return *this;\n  }\n\n  std::size_t order() const\n  {\n    return impl_.size() - 1;\n  }\n\n  void order(std::size_t n)\n  {\n    impl_.resize(n + 1);\n  }\n\n  // iterators\n  decltype(impl_.begin()) begin() { return impl_.begin(); }\n  decltype(impl_.end())   end()   { return impl_.end(); }\n\n  decltype(impl_.cbegin()) begin() const { return impl_.begin(); }\n  decltype(impl_.cend())   end()   const { return impl_.end(); }\n\n  // indexing\n  T& operator[](std::size_t i)\n  {\n    return impl_[i];\n  }\n\n  const T& operator[](std::size_t i) const\n  {\n    return impl_[i];\n  }\n\n  // comparison\n  bool operator==(const polynomial<T>& rhs) const\n  {\n    return impl_ == rhs.impl_;\n  }\n\n  /// arithmetic\n  polynomial<T>& operator+=(const T& rhs)\n  {\n    impl_[0] += rhs;\n    return *this;\n  }\n\n  polynomial<T>& operator-=(const T& rhs)\n  {\n    impl_[0] -= rhs;\n    return *this;\n  }\n\n  polynomial<T>& operator*=(const T& rhs)\n  {\n    for (auto& c : impl_)\n      c *= rhs;\n    normalize();\n    return *this;\n  }\n\n  polynomial<T>& operator+=(const polynomial<T>& rhs)\n  {\n    order(std::max(order(), rhs.order()));\n    for (std::size_t i = 0; i <= rhs.order(); i++)\n      impl_[i] += rhs.impl_[i];\n    normalize();\n    return *this;\n  }\n\n  polynomial<T>& operator-=(const polynomial<T>& rhs)\n  {\n    order(std::max(order(), rhs.order()));\n    for (std::size_t i = 0; i <= rhs.order(); i++)\n      impl_[i] -= rhs.impl_[i];\n    normalize();\n    return *this;\n  }\n\n  polynomial<T>& operator*=(const polynomial<T>& rhs)\n  {\n    polynomial<T> product;\n    product.order(order() + rhs.order());\n    for (std::size_t i = 0; i <= order(); i++) {\n      for (std::size_t j = 0; j <= rhs.order(); j++)\n        product.impl_[i + j] += impl_[i] * rhs.impl_[j];\n    }\n    impl_.swap(product.impl_);\n    return *this;\n  }\n\n  // left_shiftable\n  polynomial<T>& operator<<=(std::size_t rhs)\n  {\n    impl_.insert(impl_.begin(), rhs, T(0));\n    return *this;\n  }\n\n  const polynomial<T> operator-() const\n  {\n    polynomial<T> y;\n    y.order(order());\n    for (std::size_t i = 0; i <= order(); i++)\n      y.impl_[i] = -impl_[i];\n    return y;\n  }\n\n};\n\ntemplate<class T>\nstd::ostream& operator<<(std::ostream& o, const polynomial<T>& p)\n{\n  for (auto i = 0u; i <= p.order(); i++) {\n    if (p[i] == T(0))\n      continue;\n    auto c = p[i];\n    if (c < 0) {\n      o << \"- \";\n      c = -c;\n    } else if (i > 0) {\n      o << \"+ \";\n    }\n    if (c != 1 or i == 0) {\n      o << c << \" \";\n    }\n    if (i > 0) {\n      o << \"x\";\n      if (i > 1)\n        o << \"^\" << i;\n      o << \" \";\n    }\n  }\n  return o;\n}\n\n#endif // POLYNOMIAL_HPP_\n", "meta": {"hexsha": "6a07bab0fb6d24b1f59b7914d03cb9151fe02ad8", "size": 5087, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utility/polynomial.hpp", "max_stars_repo_name": "andreabedini/longest-path", "max_stars_repo_head_hexsha": "98a7e9574ea0d99ce3deac95bc147ae591d4d481", "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/utility/polynomial.hpp", "max_issues_repo_name": "andreabedini/longest-path", "max_issues_repo_head_hexsha": "98a7e9574ea0d99ce3deac95bc147ae591d4d481", "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/utility/polynomial.hpp", "max_forks_repo_name": "andreabedini/longest-path", "max_forks_repo_head_hexsha": "98a7e9574ea0d99ce3deac95bc147ae591d4d481", "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.4297188755, "max_line_length": 76, "alphanum_fraction": 0.5771574602, "num_tokens": 1509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5245168410175175}}
{"text": "#include \"LogPoissonSplit.hh\"\n#include \"TypeClasses.hh\"\nusing namespace TypeClasses;\n#include \"TMath.h\"\n#include <Eigen/Core>\n#include <cmath>\n\nusing namespace Eigen;\n\nLogPoissonSplit::LogPoissonSplit(bool ln_approx) {\n  transformation_(\"poisson_const\")\n    .output(\"const\")\n    .types(new CheckSameTypesT<double>({0,-1}, \"shape\"))\n    .types(&LogPoissonSplit::checkTypesConst)\n    .func(ln_approx ? &LogPoissonSplit::calcPoissonConstApprox : &LogPoissonSplit::calcPoissonConst)\n    ;\n\n  transformation_(\"poisson\")\n    .output(\"poisson\")\n    .types(&LogPoissonSplit::checkTypes)\n    .func(&LogPoissonSplit::calcPoisson)\n    ;\n\n  auto poisson = transformations[\"poisson\"];\n  auto out = transformations[\"poisson_const\"].outputs[0];\n  poisson.input(out);\n\n  m_transform = t_[\"poisson\"];\n}\n\nvoid LogPoissonSplit::add(SingleOutput &theory, SingleOutput &data) {\n  auto poisson_const = transformations[\"poisson_const\"];\n  poisson_const.input(data);\n\n  auto poisson = transformations[\"poisson\"];\n  poisson.input(theory);\n  poisson.input(data);\n}\n\nvoid LogPoissonSplit::checkTypesConst(TypesFunctionArgs fargs) {\n  auto& rets=fargs.rets;\n  rets[0] = DataType().points().shape(1);\n}\n\nvoid LogPoissonSplit::checkTypes(TypesFunctionArgs fargs) {\n  auto& args=fargs.args;\n  auto& rets=fargs.rets;\n  if (args.size()%2 != 1) {\n    throw args.undefined();\n  }\n  if (args[0].kind!=DataKind::Undefined && args[0].size() != 1) {\n    throw rets.error(rets[0], \"lnPoisson const term size should be 1\");\n  }\n  for (size_t i = 1; i < args.size(); i+=2) {\n    if (args[i+1].shape != args[i+0].shape) {\n      throw rets.error(rets[0], \"data and theory have different shape\");\n    }\n  }\n  rets[0] = DataType().points().shape(1);\n}\n\ndouble lnPi(double num)\n{\n  return TMath::LnGamma(num + 1);\n}\n\ndouble lnFactorialStirling(double x)\n{\n  if (!(x == 0.0 || x == 1.0))\n  {\n    return x * std::log(x);\n  }\n  else\n    return 0;\n}\n\nvoid LogPoissonSplit::calcPoisson(FunctionArgs fargs) {\n  /***************************************************************************\n   *       Formula: log of Poisson\n   *        -2 * ln(Poisson) =\n   *             2 * sum(theory_j - data_i * log(theory_j) + ln data_i! )\n   *\n   ****************************************************************************/\n  auto& args=fargs.args;\n\n  double res=args[0].arr(0);\n  for (size_t i = 1; i < args.size(); i+=2) {\n    auto& theory=args[i+0].arr;\n    auto& data=args[i+1].arr;\n    res += (theory - data*theory.log()).sum();\n  }\n  fargs.rets[0].arr(0) = 2*res;\n}\n\nvoid LogPoissonSplit::calcPoissonConstApprox(FunctionArgs fargs) {\n  /***************************************************************************\n   *       Formula: log of Poisson\n   *        -2 * ln(Poisson) =\n   *            -2 * sum(data_i * log(theory_j) -  theory_j  - ln data_i! )\n   *\n   *       Compute: ln data_i! \u2248 data_i ln data_i\n   *\n   ****************************************************************************/\n  auto& args=fargs.args;\n\n  double res(0.0);\n  for (size_t i = 0; i < args.size(); ++i) {\n    res += (args[i].arr.unaryExpr(&lnFactorialStirling)).sum();\n  }\n  fargs.rets[0].arr(0) = res;\n}\n\nvoid LogPoissonSplit::calcPoissonConst(FunctionArgs fargs) {\n  /***************************************************************************\n   *       Formula: log of Poisson\n   *\n   *        -2 * ln(Poisson) =\n   *               -2 * sum(data_i * log(theory_j) -  theory_j  - ln data_i! )\n   *\n   *       Compute: ln data_i!\n   *\n   ****************************************************************************/\n  auto& args=fargs.args;\n\n  double res(0.0);\n  for (size_t i = 0; i < args.size(); ++i) {\n    res += args[i].arr.unaryExpr(&lnPi).sum();\n  }\n  fargs.rets[0].arr(0) = res;\n}\n\n", "meta": {"hexsha": "b1efaccf1781f8dc089be57f1947f93f610e3bc6", "size": 3716, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/stats/LogPoissonSplit.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/stats/LogPoissonSplit.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/stats/LogPoissonSplit.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.1515151515, "max_line_length": 100, "alphanum_fraction": 0.5444025834, "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6261241772283035, "lm_q1q2_score": 0.5244541052960735}}
{"text": "#include \"image_processing.h\"\n#include <numeric>\n#include <cfloat>\n#include <Eigen/LU>\n#include <QImage>\n\nnamespace ImageProcessing\n{\n\ntemplate <typename Scalar>\nScalar crop(Scalar x, Scalar min_x, Scalar max_x)\n{\n    return std::max(std::min(x, max_x), min_x);\n}\n\nvoid Image::force_unity()\n{\n    const double sum = std::accumulate(pixels.begin(), pixels.end(), 0.0);\n    assert(sum > 1e-16);\n    for (int x = 0; x < width(); ++ x) for (int y = 0; y < height(); ++ y)\n    {\n        set_pixel(x, y, get_pixel(x, y) / sum);\n    }\n}\n\nvoid Image::scale_to_unit()\n{\n    double max_value = - DBL_MAX;\n    double min_value = + DBL_MAX;\n\n    for (int x = 0; x < width(); ++ x) for (int y = 0; y < height(); ++ y)\n    {\n        const double value = get_pixel(x, y);\n        max_value = std::max(max_value, value);\n        min_value = std::min(min_value, value);\n    }\n    assert(max_value - min_value > 0.0);\n    for (int x = 0; x < width(); ++ x) for (int y = 0; y < height(); ++ y)\n    {\n        set_pixel(x, y, (get_pixel(x, y) - min_value) / (max_value - min_value));\n    }\n}\n\nvoid AbstractImage::save(const std::string &file_path) const\n{\n    QImage q_image(width(), height(), QImage::Format_ARGB32);\n    for (int x = 0; x < width(); ++ x) for (int y = 0; y < height(); ++ y)\n    {\n        const IntColor color = get_color(x, y);\n        q_image.setPixelColor(x, y, QColor(color(0), color(1), color(2), color(3)));\n    }\n    q_image.save(QString::fromStdString(file_path));\n}\n\nAbstractImage::IntColor Image::get_color(int x, int y) const\n{\n    const double value = crop(get_pixel(x, y), 0.0, 1.0);\n    return IntColor(value * 255, value * 255, value * 255, 255);\n}\n\nAbstractImage::IntColor ColorImage::get_color(int x, int y) const\n{\n    Eigen::Vector4d color = get_rgba(x, y);\n    for (int i : { 0, 1, 2, 3 }) color(i) = crop(color(i), 0.0, 1.0);\n    return IntColor(color(0) * 255, color(1) * 255, color(2) * 255, color(3) * 255);\n}\n\nColorImage::ColorImage(const std::string &file_path)\n{\n    QImage q_image(QString::fromStdString(file_path));\n    width_  = q_image.width();\n    height_ = q_image.height();\n\n    assert(width() > 0 && height() > 0);\n\n    rgba_ = std::vector<Image>(4, Image(width(), height()));\n    for (int x = 0; x < width(); ++ x) for (int y = 0; y < height(); ++ y)\n    {\n        const QColor q_color = q_image.pixelColor(x, y);\n        rgba_[0].set_pixel(x, y, q_color.redF());\n        rgba_[1].set_pixel(x, y, q_color.greenF());\n        rgba_[2].set_pixel(x, y, q_color.blueF());\n        rgba_[3].set_pixel(x, y, q_color.alphaF());\n    }\n}\n\nImage ColorImage::get_luminance() const\n{\n    Image new_image(width(), height());\n    for (int x = 0; x < width(); ++ x) for (int y = 0; y < height(); ++ y)\n    {\n        const double r = rgba_[0].get_pixel(x, y);\n        const double g = rgba_[1].get_pixel(x, y);\n        const double b = rgba_[2].get_pixel(x, y);\n\n        // https://en.wikipedia.org/wiki/Relative_luminance\n        const double luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n\n        new_image.set_pixel(x, y, luminance);\n    }\n    return new_image;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////\n\nImage apply_convolution(const Image& image, const Eigen::MatrixXd &kernel)\n{\n    const int w = image.width();\n    const int h = image.height();\n\n    const int kernel_size = kernel.rows();\n\n    assert(kernel_size % 2 == 1);\n    assert(kernel_size == kernel.cols());\n\n    Image new_image(w, h);\n\n    for (int x = 0; x < w; ++ x) for (int y = 0; y < h; ++ y)\n    {\n        double value = 0.0;\n        for (int kernel_x = 0; kernel_x < kernel_size; ++ kernel_x)\n        {\n            for (int kernel_y = 0; kernel_y < kernel_size; ++ kernel_y)\n            {\n                const int original_image_x = crop(x + kernel_x - ((kernel_size - 1) / 2), 0, w - 1);\n                const int original_image_y = crop(y + kernel_y - ((kernel_size - 1) / 2), 0, h - 1);\n\n                value += kernel(kernel_x, kernel_y) * image.get_pixel(original_image_x, original_image_y);\n            }\n        }\n        new_image.set_pixel(x, y, value);\n    }\n    return new_image;\n}\n\nImage calculate_guided_filter_kernel(const Image& image, int center_x, int center_y, int radius, double epsilon, bool force_positive)\n{\n    const int width  = image.width();\n    const int height = image.height();\n\n    const Image mean_I = ImageProcessing::apply_box_filter(image, radius);\n    const Image corr_I = ImageProcessing::apply_box_filter(ImageProcessing::square(image), radius);\n    const Image var_I  = ImageProcessing::subtract(corr_I, ImageProcessing::square(mean_I));\n    const double I_seed = image.get_pixel(center_x, center_y);\n\n    Image weight_map(width, height, 0.0);\n    for (int x = center_x - radius; x <= center_x + radius; ++ x)\n    {\n        for (int y = center_y - radius; y <= center_y + radius; ++ y)\n        {\n            if (x < 0 || x >= width || y < 0 || y >= height) continue;\n\n            const double I_j = image.get_pixel(x, y);\n            double weight = 0.0;\n            for (int k_x = 0; k_x < width; ++ k_x)\n            {\n                for (int k_y = 0; k_y < height; ++ k_y)\n                {\n                    bool range_j    = (k_x >= x - radius && k_x <= x + radius) && (k_y >= y - radius && k_y <= y + radius);\n                    bool range_seed = (k_x >= center_x - radius && k_x <= center_x + radius) && (k_y >= center_y - radius && k_y <= center_y + radius);\n                    if (!range_j || !range_seed) continue;\n\n                    const double mu_k  = mean_I.get_pixel(k_x, k_y);\n                    const double var_k = var_I.get_pixel(k_x, k_y);\n                    weight += 1.0 + ((I_seed - mu_k) * (I_j - mu_k)) / (epsilon + var_k);\n                }\n            }\n            if (force_positive) weight = std::max(0.0, weight);\n            weight_map.set_pixel(x, y, weight);\n        }\n    }\n    weight_map.force_unity();\n    return weight_map;\n}\n\nImage calculate_gradient_magnitude(const Image& image)\n{\n    const int width  = image.width();\n    const int height = image.height();\n    const Image sobel_x = ImageProcessing::apply_sobel_filter_x(image);\n    const Image sobel_y = ImageProcessing::apply_sobel_filter_y(image);\n\n    Image gradient_magnitude = Image(width, height);\n    for (int x = 0; x < width; ++ x)\n    {\n        for (int y = 0; y < height; ++ y)\n        {\n            const double g_x = sobel_x.get_pixel(x, y);\n            const double g_y = sobel_y.get_pixel(x, y);\n            const double value = std::sqrt(g_x * g_x + g_y * g_y);\n            gradient_magnitude.set_pixel(x, y, value);\n        }\n    }\n    return gradient_magnitude;\n}\n\nImage apply_guided_filter(const Image& input_image, const ColorImage& guidance_image, int radius, double epsilon)\n{\n    const int width  = input_image.width();\n    const int height = input_image.height();\n\n    assert(width == guidance_image.width());\n    assert(height == guidance_image.height());\n\n    const Image I_r = guidance_image.get_r();\n    const Image I_g = guidance_image.get_g();\n    const Image I_b = guidance_image.get_b();\n\n    const Image mean_I_r = apply_box_filter(I_r, radius);\n    const Image mean_I_g = apply_box_filter(I_g, radius);\n    const Image mean_I_b = apply_box_filter(I_b, radius);\n\n    const Image mean_p = apply_box_filter(input_image, radius);\n\n    const Image mean_Ip_r = apply_box_filter(multiply(I_r, input_image), radius);\n    const Image mean_Ip_g = apply_box_filter(multiply(I_g, input_image), radius);\n    const Image mean_Ip_b = apply_box_filter(multiply(I_b, input_image), radius);\n\n    const Image cov_Ip_r = subtract(mean_Ip_r, multiply(mean_I_r, mean_p));\n    const Image cov_Ip_g = subtract(mean_Ip_g, multiply(mean_I_g, mean_p));\n    const Image cov_Ip_b = subtract(mean_Ip_b, multiply(mean_I_b, mean_p));\n\n    const Image var_I_rr = subtract(apply_box_filter(multiply(I_r, I_r), radius), multiply(mean_I_r, mean_I_r));\n    const Image var_I_rg = subtract(apply_box_filter(multiply(I_r, I_g), radius), multiply(mean_I_r, mean_I_g));\n    const Image var_I_rb = subtract(apply_box_filter(multiply(I_r, I_b), radius), multiply(mean_I_r, mean_I_b));\n    const Image var_I_gg = subtract(apply_box_filter(multiply(I_g, I_g), radius), multiply(mean_I_g, mean_I_g));\n    const Image var_I_gb = subtract(apply_box_filter(multiply(I_g, I_b), radius), multiply(mean_I_g, mean_I_b));\n    const Image var_I_bb = subtract(apply_box_filter(multiply(I_b, I_b), radius), multiply(mean_I_b, mean_I_b));\n\n    Image a_r(width, height);\n    Image a_g(width, height);\n    Image a_b(width, height);\n    for (int x = 0; x < width; ++ x) for (int y = 0; y < height; ++ y)\n    {\n        Eigen::Matrix3d sigma;\n        sigma << var_I_rr.get_pixel(x, y), var_I_rg.get_pixel(x, y), var_I_rb.get_pixel(x, y),\n                 var_I_rg.get_pixel(x, y), var_I_gg.get_pixel(x, y), var_I_gb.get_pixel(x, y),\n                 var_I_rb.get_pixel(x, y), var_I_gb.get_pixel(x, y), var_I_bb.get_pixel(x, y);\n\n        const Eigen::Vector3d cov_Ip = { cov_Ip_r.get_pixel(x, y), cov_Ip_g.get_pixel(x, y), cov_Ip_b.get_pixel(x, y) };\n        const Eigen::Vector3d a_xy = (sigma + epsilon * Eigen::Matrix3d::Identity()).inverse() * cov_Ip;\n\n        a_r.set_pixel(x, y, a_xy(0));\n        a_g.set_pixel(x, y, a_xy(1));\n        a_b.set_pixel(x, y, a_xy(2));\n    }\n\n    const Image b = subtract(subtract(subtract(mean_p, multiply(a_r, mean_I_r)), multiply(a_g, mean_I_g)), multiply(a_b, mean_I_b));\n\n    Image q = apply_box_filter(b, radius);\n    q = add(q, multiply(apply_box_filter(a_r, radius), I_r));\n    q = add(q, multiply(apply_box_filter(a_g, radius), I_g));\n    q = add(q, multiply(apply_box_filter(a_b, radius), I_b));\n\n    return q;\n}\n\n\n}\n", "meta": {"hexsha": "844f92b66acfd1fcd7b8744bb0a1618488ff74c4", "size": 9714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unmixing/image_processing.cpp", "max_stars_repo_name": "yaochaorui/color-unmixing", "max_stars_repo_head_hexsha": "4bd59d5b48f856b3f5b4aa425a04e2d7d0cf48e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2018-09-02T16:33:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T15:08:44.000Z", "max_issues_repo_path": "unmixing/image_processing.cpp", "max_issues_repo_name": "yaochaorui/color-unmixing", "max_issues_repo_head_hexsha": "4bd59d5b48f856b3f5b4aa425a04e2d7d0cf48e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unmixing/image_processing.cpp", "max_forks_repo_name": "yaochaorui/color-unmixing", "max_forks_repo_head_hexsha": "4bd59d5b48f856b3f5b4aa425a04e2d7d0cf48e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-12-04T05:15:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T12:10:11.000Z", "avg_line_length": 37.3615384615, "max_line_length": 151, "alphanum_fraction": 0.6062384188, "num_tokens": 2731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5244541002200892}}
{"text": "// practice 5-8\n\n#include <iostream>\n#include <boost/type_traits/is_reference.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/type_traits/is_pointer.hpp>\n#include <boost/type_traits/is_float.hpp>\n#include <boost/type_traits/alignment_of.hpp>\n#include <boost/type_traits/remove_reference.hpp>\n#include <boost/type_traits/remove_pointer.hpp>\n#include <boost/type_traits/add_pointer.hpp>\n#include <boost/type_traits/is_function.hpp>\n#include <boost/type_traits/is_const.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/apply.hpp>\n\n#include <boost/mpl/vector_c.hpp>\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/transform.hpp>\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/not_equal_to.hpp>\n#include <boost/mpl/greater.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/or.hpp>\n#include <boost/mpl/and.hpp>\n#include <boost/mpl/multiplies.hpp>\n\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/next.hpp>\n#include <boost/mpl/prior.hpp>\n#include <boost/mpl/begin.hpp>\n#include <boost/mpl/end.hpp>\n#include <boost/mpl/advance.hpp>\n#include <boost/mpl/push_front.hpp>\n#include <boost/mpl/pop_front.hpp>\n#include <boost/mpl/insert.hpp>\n#include <boost/mpl/size.hpp>\n\n\nusing namespace boost::mpl::placeholders;\n#include <iterator>\n#include <utility>\n#include <list>\n#include <vector>\n#include <string>\n#include <assert.h>\n\nnamespace mpl = boost::mpl;\n\n\nstruct fibo_tag {};\nstruct fibo_series\n{\n\ttypedef fibo_tag tag;\n\ttypedef fibo_series type;\n};\n\ntemplate <int Value, int Pos>\nstruct fibo_iterator\n{\n\ttypedef fibo_tag tag;\n\ttypedef typename fibo_iterator type;\n\tstatic const int value = Value;\n\tstatic const int pos = Pos;\n};\n\ntemplate<int N>\nstruct fibo_val\n{\n\tstatic const int value = \n\t\tfibo_val<N-1>::value + \n\t\tfibo_val<N-2>::value;\n};\n\ntemplate<>\nstruct fibo_val<0> : mpl::int_<0>\n{};\n\ntemplate<>\nstruct fibo_val<1> : mpl::int_<1>\n{};\n\n\nnamespace boost { namespace mpl {\n\ttemplate<>\n\tstruct begin_impl< fibo_tag >\n\t{\n\t\ttemplate<class S>\n\t\tstruct apply\n\t\t{\n\t\t\ttypedef typename fibo_iterator<0,0> type;\n\t\t};\n\t};\n}}\n\n\nnamespace boost { namespace mpl {\n\ttemplate<>\n\tstruct advance_impl< fibo_tag >\n\t{\n\t\ttemplate<class It, class N>\n\t\tstruct apply\n\t\t{\n\t\t\ttypedef typename fibo_iterator< \n\t\t\t\tfibo_val< It::pos + N::value >::value\n\t\t\t\t, It::pos + N::value > type;\n\t\t};\n\t};\n}}\n\n\nnamespace boost { namespace mpl {\n\ttemplate<int Value, int PosValue>\n\tstruct deref< fibo_iterator<Value, PosValue> >\n\t{\n\t\ttypedef typename fibo_iterator<Value, PosValue> type;\n\t};\n}}\n\n// 0 1 1 2 3 5 8 13 21..\n//fibonacci_series\n// typedef mpl::advance_c< mpl::begin< fibon >::type, 6 >::type i;\n// mpl::deref<i>:;type::value == 8\n\n// typedef mpl::advance_c< i, 4 >::type j;\n// mpl::deref<j>::type::value == 55\n\ntypedef mpl::advance_c< \n\tmpl::begin< fibo_series >::type, 6 \n\t>::type i;\nBOOST_STATIC_ASSERT( mpl::deref<i>::type::value == 8 );\n\ntypedef mpl::advance_c< i, 4>::type j;\nBOOST_STATIC_ASSERT( mpl::deref<j>::type::value == 55 );\n\n\nvoid main()\n{\n\tint n = mpl::deref<i>::type::value;\n\n}\n", "meta": {"hexsha": "f68d139b9f6500957edcd6dd1c3c40ad9da815b7", "size": 3103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Ex5/Prac5.8/main.cpp", "max_stars_repo_name": "jjuiddong/TemplateMetaProgramming", "max_stars_repo_head_hexsha": "ccfa4b21205c8cd3da1906f64cdbeb200902812a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-31T05:50:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-31T05:50:22.000Z", "max_issues_repo_path": "Ex5/Prac5.8/main.cpp", "max_issues_repo_name": "jjuiddong/TemplateMetaProgramming", "max_issues_repo_head_hexsha": "ccfa4b21205c8cd3da1906f64cdbeb200902812a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ex5/Prac5.8/main.cpp", "max_forks_repo_name": "jjuiddong/TemplateMetaProgramming", "max_forks_repo_head_hexsha": "ccfa4b21205c8cd3da1906f64cdbeb200902812a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-31T05:50:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-31T05:50:41.000Z", "avg_line_length": 21.4, "max_line_length": 66, "alphanum_fraction": 0.7115694489, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.524454098684736}}
{"text": "#include <cstddef>\n#include <iostream>\n#include <iomanip>\n\n#include <eigen-checks/gtest.h>\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <cholmod.h>\n#include <SuiteSparseQR.hpp>\n\n#include \"truncated-svd-solver/tsvd-solver.h\"\n#include \"truncated-svd-solver/linear-algebra-helpers.h\"\n#include \"truncated-svd-solver/timing.h\"\n\nvoid evaluateSVDSPQRSolver(const Eigen::MatrixXd& A, const Eigen::VectorXd& b,\n    const Eigen::VectorXd& x, double tol = 1e-9) {\n  cholmod_common cholmod;\n  cholmod_l_start(&cholmod);\n  cholmod_sparse* A_CS = truncated_svd_solver::eigenDenseToCholmodSparseCopy(A,\n    &cholmod);\n  cholmod_dense b_CD;\n  truncated_svd_solver::eigenDenseToCholmodDenseView(b, &b_CD);\n  Eigen::VectorXd x_est;\n  truncated_svd_solver::TruncatedSvdSolver linearSolver;\n  for (std::ptrdiff_t i = 1; i < A.cols(); ++i) {\n    linearSolver.solve(A_CS, &b_CD, i, x_est);\n    double error = (b - A * x_est).norm();\n    ASSERT_NEAR(error, 0, tol);\n    linearSolver.getOptions().columnScaling = true;\n    linearSolver.solve(A_CS, &b_CD, i, x_est);\n    error = (b - A * x_est).norm();\n    linearSolver.getOptions().columnScaling = false;\n    ASSERT_NEAR(error, 0, tol);\n  }\n  cholmod_l_free_sparse(&A_CS, &cholmod);\n  cholmod_l_finish(&cholmod);\n\n  EXPECT_TRUE(EIGEN_MATRIX_NEAR(x_est, x, 1e-8));\n}\n\nvoid evaluateSVDSolver(const Eigen::MatrixXd& A, const Eigen::VectorXd& b,\n    const Eigen::VectorXd& x) {\n  const Eigen::JacobiSVD<Eigen::MatrixXd> svd(A,\n    Eigen::ComputeThinU | Eigen::ComputeThinV);\n  Eigen::VectorXd x_est = svd.solve(b);\n\n  EXPECT_TRUE(EIGEN_MATRIX_NEAR(x_est, x, 1e-8));\n}\n\nvoid evaluateSPQRSolver(const Eigen::MatrixXd& A,\n                                   const Eigen::VectorXd& b,\n                                   const Eigen::VectorXd& x) {\n  cholmod_common cholmod;\n  cholmod_l_start(&cholmod);\n  cholmod_sparse* A_CS =\n      truncated_svd_solver::eigenDenseToCholmodSparseCopy(A, &cholmod);\n  cholmod_dense b_CD;\n  truncated_svd_solver::eigenDenseToCholmodDenseView(b, &b_CD);\n  Eigen::VectorXd x_est;\n  SuiteSparseQR_factorization<double>* factor = SuiteSparseQR_factorize<double>(\n    SPQR_ORDERING_BEST, SPQR_DEFAULT_TOL, A_CS, &cholmod);\n  cholmod_dense* Qtb = SuiteSparseQR_qmult<double>(SPQR_QTX, factor, &b_CD,\n    &cholmod);\n  cholmod_dense* x_est_cd = SuiteSparseQR_solve<double>(SPQR_RETX_EQUALS_B,\n    factor, Qtb, &cholmod);\n  cholmod_l_free_dense(&Qtb, &cholmod);\n  truncated_svd_solver::cholmodDenseToEigenDenseCopy(x_est_cd, x_est);\n  cholmod_l_free_dense(&x_est_cd, &cholmod);\n  SuiteSparseQR_free(&factor, &cholmod);\n  cholmod_l_free_sparse(&A_CS, &cholmod);\n  cholmod_l_finish(&cholmod);\n\n  EXPECT_TRUE(EIGEN_MATRIX_NEAR(x_est, x, 1e-8));\n}\n\nvoid evaluateSPQRSolverDeterminedSystem(\n    const truncated_svd_solver::TruncatedSvdSolverOptions& options) {\n  // Create the system.\n  constexpr size_t kNumVariables = 10u;\n  constexpr double kXResult = 2.0;\n\n  Eigen::VectorXd Adiag(kNumVariables);\n  for(size_t i = 0; i < kNumVariables; ++i){\n    Adiag(i) =  kNumVariables - i;\n  }\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(kNumVariables, kNumVariables);\n  A.diagonal() = Adiag;\n\n  Eigen::VectorXd b = A * Eigen::VectorXd::Constant(kNumVariables, kXResult);\n\n  // Convert to cholmod types.\n  cholmod_common_struct cholmod;\n  cholmod_l_start(&cholmod);\n  cholmod_sparse* A_cm =\n      truncated_svd_solver::eigenDenseToCholmodSparseCopy(A, &cholmod);\n\n  cholmod_dense b_cm;\n  truncated_svd_solver::eigenDenseToCholmodDenseView(b, &b_cm);\n\n  // Solve this system and check the results.\n\n  truncated_svd_solver::TruncatedSvdSolver solver(options);\n\n  for (std::ptrdiff_t i = 0; i <= A.cols(); ++i) {\n    const size_t num_calib_vars = kNumVariables - i;\n\n    Eigen::VectorXd x;\n    solver.clear();\n    EXPECT_EQ(solver.getSVDRank(), -1);\n    EXPECT_EQ(solver.getSVDRankDeficiency(), -1);\n    EXPECT_EQ(solver.getQRRank(), 0);\n    EXPECT_EQ(solver.getQRRankDeficiency(), 0);\n    EXPECT_EQ(solver.getNullSpace().size(), 0);\n\n    solver.analyzeMarginal(A_cm, i);\n    EXPECT_EQ(solver.getSVDRank(), num_calib_vars);\n    EXPECT_EQ(solver.getQRRank(), i);\n    EXPECT_EQ(solver.getQRRankDeficiency(), 0);\n    EXPECT_EQ(solver.getSVDRankDeficiency(), 0);\n    EXPECT_EQ(solver.getNullSpace().size(), 0);\n\n    solver.clear();\n    EXPECT_EQ(solver.getSVDRank(), -1);\n    EXPECT_EQ(solver.getSVDRankDeficiency(), -1);\n    EXPECT_EQ(solver.getQRRank(), 0);\n    EXPECT_EQ(solver.getQRRankDeficiency(), 0);\n    EXPECT_EQ(solver.getNullSpace().size(), 0);\n\n    solver.solve(A_cm, &b_cm, i, x);\n    EXPECT_EQ(solver.getSVDRank(), num_calib_vars);\n    EXPECT_EQ(solver.getQRRank(), i);\n    EXPECT_EQ(solver.getQRRankDeficiency(), 0);\n    EXPECT_EQ(solver.getSVDRankDeficiency(), 0);\n    EXPECT_EQ(solver.getNullSpace().size(), 0);\n\n    Eigen::VectorXd expectedSingularValues;\n    if(options.columnScaling){\n      expectedSingularValues = Eigen::VectorXd::Ones(num_calib_vars);\n    }else{\n      expectedSingularValues =\n          Adiag.tail(num_calib_vars).array() * Adiag.tail(num_calib_vars).array();\n    }\n\n    EXPECT_TRUE(\n        EIGEN_MATRIX_NEAR(solver.getSingularValues(),\n                          expectedSingularValues, 1e-8));\n    EXPECT_TRUE(\n        EIGEN_MATRIX_NEAR(x, Eigen::VectorXd::Constant(kNumVariables,\n                                                       kXResult),\n                          1e-8));\n  }\n\n  cholmod_l_free_sparse(&A_cm, &cholmod);\n}\n\nTEST(TruncatedSvdSolver, DeterminedSystemWithoutColumnScaling) {\n  truncated_svd_solver::TruncatedSvdSolverOptions options;\n  options.columnScaling = false;\n  evaluateSPQRSolverDeterminedSystem(options);\n}\n\nTEST(TruncatedSvdSolver, DeterminedSystemWithColumnScaling) {\n  truncated_svd_solver::TruncatedSvdSolverOptions options;\n  options.columnScaling = true;\n  evaluateSPQRSolverDeterminedSystem(options);\n}\n\nTEST(TruncatedSvdSolver, OverdeterminedSystem) {\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(100, 30);\n  const Eigen::VectorXd x = Eigen::VectorXd::Random(30);\n  Eigen::VectorXd b = A * x;\n\n  std::cout << \"-------------------------------------------------\" << std::endl;\n  std::cout << \"|                  Standard case                |\" << std::endl;\n  std::cout << \"-------------------------------------------------\" << std::endl;\n  evaluateSVDSPQRSolver(A, b, x);\n  evaluateSVDSolver(A, b, x);\n  evaluateSPQRSolver(A, b, x);\n\n  std::cout << \"-------------------------------------------------\" << std::endl;\n  std::cout << \"|                 Badly scaled case             |\" << std::endl;\n  std::cout << \"-------------------------------------------------\" << std::endl;\n  A.col(2) = 1e6 * A.col(2);\n  A.col(28) = 1e6 * A.col(28);\n  b = A * x;\n  evaluateSVDSPQRSolver(A, b, x, 1e-3);\n  evaluateSVDSolver(A, b, x);\n  evaluateSPQRSolver(A, b, x);\n\n//  std::cout << \"-------------------------------------------------\" << std::endl;\n//  std::cout << \"|                 Rank-deficient case 1         |\" << std::endl;\n//  std::cout << \"-------------------------------------------------\" << std::endl;\n//  A = Eigen::MatrixXd::Random(100, 30);\n//  A.col(10) = Eigen::VectorXd::Zero(A.rows());\n//  b = A * x;\n//  evaluateSVDSPQRSolver(A, b, x, 1e-3);\n//  evaluateSVDSolver(A, b, x);\n//  evaluateSPQRSolver(A, b, x);\n\n//  std::cout << \"-------------------------------------------------\" << std::endl;\n//  std::cout << \"|                 Rank-deficient case 2         |\" << std::endl;\n//  std::cout << \"-------------------------------------------------\" << std::endl;\n//  A = Eigen::MatrixXd::Random(100, 30);\n//  A.col(10) = 2 * A.col(1) + 5 * A.col(20);\n//  b = A * x;\n//  evaluateSVDSPQRSolver(A, b, x, 1e-3);\n//  evaluateSVDSolver(A, b, x);\n//  evaluateSPQRSolver(A, b, x);\n\n//  std::cout << \"-------------------------------------------------\" << std::endl;\n//  std::cout << \"|                 Near rank-deficient case 1    |\" << std::endl;\n//  std::cout << \"-------------------------------------------------\" << std::endl;\n//  A = Eigen::MatrixXd::Random(100, 30);\n//  A.col(10) = Eigen::VectorXd::Zero(A.rows());\n//  b = A * x;\n//  A.col(10) = truncated_svd_solver::NormalDistribution<100>(\n//    Eigen::VectorXd::Zero(A.rows()),\n//    1e-6 * Eigen::MatrixXd::Identity(A.rows(), A.rows())).getSample();\n//  evaluateSVDSPQRSolver(A, b, x, 1e-3);\n//  evaluateSVDSolver(A, b, x);\n//  evaluateSPQRSolver(A, b, x);\n\n//  std::cout << \"-------------------------------------------------\" << std::endl;\n//  std::cout << \"|                 Near rank-deficient case 2    |\" << std::endl;\n//  std::cout << \"-------------------------------------------------\" << std::endl;\n//  A = Eigen::MatrixXd::Random(100, 30);\n//  A.col(10) = 2 * A.col(1) + 5 * A.col(20);\n//  b = A * x;\n//  A.col(10) = truncated_svd_solver::NormalDistribution<100>(A.col(10),\n//    1e-20 * Eigen::MatrixXd::Identity(A.rows(), A.rows())).getSample();\n//  evaluateSVDSPQRSolver(A, b, x, 1e-3);\n//  evaluateSVDSolver(A, b, x);\n//  evaluateSPQRSolver(A, b, x);\n}\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  google::InitGoogleLogging(argv[0]);\n  google::InstallFailureSignalHandler();\\\n  ::testing::FLAGS_gtest_death_test_style = \"threadsafe\";\n  FLAGS_alsologtostderr = true;\n  FLAGS_colorlogtostderr = true;\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "5540c59baf6a09db299a237a525552da53ea86ef", "size": 9266, "ext": "cc", "lang": "C++", "max_stars_repo_path": "truncated_svd_solver/test/test-tsvd-solver.cc", "max_stars_repo_name": "ethz-asl/truncated_svd_solver", "max_stars_repo_head_hexsha": "12772b2e3a0282e77022f12f67497401ca020f57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2017-02-06T18:05:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T01:56:49.000Z", "max_issues_repo_path": "truncated_svd_solver/test/test-tsvd-solver.cc", "max_issues_repo_name": "ethz-asl/truncated_svd_solver", "max_issues_repo_head_hexsha": "12772b2e3a0282e77022f12f67497401ca020f57", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T16:46:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-14T16:46:52.000Z", "max_forks_repo_path": "truncated_svd_solver/test/test-tsvd-solver.cc", "max_forks_repo_name": "ethz-asl/truncated_svd_solver", "max_forks_repo_head_hexsha": "12772b2e3a0282e77022f12f67497401ca020f57", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-12-27T09:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T23:22:28.000Z", "avg_line_length": 37.2128514056, "max_line_length": 82, "alphanum_fraction": 0.6166630693, "num_tokens": 2679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5244540936087522}}
{"text": "/**\n * @file matrix_geometry.hpp\n * @author Maximilien Naveau (maximilien.naveau@gmail.com)\n * @license License BSD-3-Clause\n * @copyright Copyright (c) 2019, New York University and Max Planck\n * Gesellschaft.\n * @date 2019-05-22\n */\n\n#ifndef MATRIX_GEOMETRY_HH\n#define MATRIX_GEOMETRY_HH\n\n#include <dynamic-graph/eigen-io.h>\n#include <dynamic-graph/linear-algebra.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#define MRAWDATA(x) x.data()\n\nnamespace dynamic_graph_manager\n{\ntypedef Eigen::Transform<double, 3, Eigen::Affine> MatrixHomogeneous;\ntypedef Eigen::Matrix<double, 3, 3> MatrixRotation;\ntypedef Eigen::AngleAxis<double> VectorUTheta;\ntypedef Eigen::Quaternion<double> VectorQuaternion;\ntypedef Eigen::Vector3d VectorRotation;\ntypedef Eigen::Vector3d VectorRollPitchYaw;\ntypedef Eigen::Matrix<double, 6, 6> MatrixForce;\ntypedef Eigen::Matrix<double, 6, 6> MatrixTwist;\n\ninline void buildFrom(const MatrixHomogeneous& MH, MatrixTwist& MT)\n{\n    Eigen::Vector3d _t = MH.translation();\n    MatrixRotation R(MH.linear());\n    Eigen::Matrix3d Tx;\n    Tx << 0, -_t(2), _t(1), _t(2), 0, -_t(0), -_t(1), _t(0), 0;\n    Eigen::Matrix3d sk;\n    sk = Tx * R;\n\n    MT.block<3, 3>(0, 0) = R;\n    MT.block<3, 3>(0, 3) = sk;\n    MT.block<3, 3>(3, 0).setZero();\n    MT.block<3, 3>(3, 3) = R;\n}\n}  // namespace dynamic_graph_manager\n\n#endif  // MATRIX_GEOMETRY_HH\n", "meta": {"hexsha": "0f15f5654973c0dada50138f2f7f87cf2816af80", "size": 1362, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ros_entities/matrix_geometry.hpp", "max_stars_repo_name": "andreadelprete/dynamic_graph_manager", "max_stars_repo_head_hexsha": "59a29462ea173d3a3456642799d965f8f1e2854e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T04:00:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T22:54:11.000Z", "max_issues_repo_path": "include/ros_entities/matrix_geometry.hpp", "max_issues_repo_name": "andreadelprete/dynamic_graph_manager", "max_issues_repo_head_hexsha": "59a29462ea173d3a3456642799d965f8f1e2854e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2019-11-01T17:35:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T13:58:45.000Z", "max_forks_repo_path": "include/ros_entities/matrix_geometry.hpp", "max_forks_repo_name": "andreadelprete/dynamic_graph_manager", "max_forks_repo_head_hexsha": "59a29462ea173d3a3456642799d965f8f1e2854e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-23T06:24:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T13:08:48.000Z", "avg_line_length": 28.375, "max_line_length": 69, "alphanum_fraction": 0.704845815, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5244239566576341}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE HandEyeCalibration_test\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <random>\n\n#include \"camodocal/calib/HandEyeCalibration.h\"\n#include \"camodocal/EigenUtils.h\"\n\nBOOST_AUTO_TEST_SUITE(HandEyeCalibration_test)\n\nBOOST_AUTO_TEST_CASE(FullMotion)\n{\n    camodocal::HandEyeCalibration::setVerbose(false);\n\n    Eigen::Matrix4d H_12_expected = Eigen::Matrix4d::Identity();\n    H_12_expected.block<3,3>(0,0) = Eigen::AngleAxisd(0.4, Eigen::Vector3d(0.1, 0.2, 0.3).normalized()).toRotationMatrix();\n    H_12_expected.block<3,1>(0,3) << 0.5, 0.6, 0.7;\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > rvecs1, tvecs1, rvecs2, tvecs2;\n    std::random_device rd;  //Will be used to obtain a seed for the random number engine\n    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()\n    std::uniform_int_distribution<> dis(-10.0, 10.0);\n    std::uniform_int_distribution<> dis1(-1.0, 1.0);\n\n    int motionCount = 2;\n    for (int i = 0; i < motionCount; ++i)\n    {\n\n        double droll = boost::math::constants::radian<double>()*dis(gen);\n        double dpitch = boost::math::constants::radian<double>()*dis(gen);\n        double dyaw = boost::math::constants::radian<double>()*dis(gen);\n        double dx = dis1(gen);\n        double dy = dis1(gen);\n        double dz = dis1(gen);\n\n        Eigen::Matrix3d R;\n        R = Eigen::AngleAxisd(dyaw, Eigen::Vector3d::UnitZ()) *\n            Eigen::AngleAxisd(dpitch, Eigen::Vector3d::UnitY()) *\n            Eigen::AngleAxisd(droll, Eigen::Vector3d::UnitX());\n\n        Eigen::Matrix4d H = Eigen::Matrix4d::Identity();\n        H.block<3,3>(0,0) = R;\n        H.block<3,1>(0,3) << dx, dy, dz;\n\n        Eigen::Matrix4d H_ = H.inverse();\n        H = H_;\n\n        Eigen::Vector3d rvec1, tvec1, rvec2, tvec2;\n\n        Eigen::AngleAxisd angleAxis1((H_12_expected * H * H_12_expected.inverse()).block<3,3>(0,0));\n        rvec1 = angleAxis1.angle() * angleAxis1.axis();\n\n        tvec1 = (H_12_expected * H * H_12_expected.inverse()).block<3,1>(0,3);\n\n        Eigen::AngleAxisd angleAxis2(H.block<3,3>(0,0));\n        rvec2 = angleAxis2.angle() * angleAxis2.axis();\n\n        tvec2 = H.block<3,1>(0,3);\n\n        rvecs1.push_back(rvec1);\n        tvecs1.push_back(tvec1);\n        rvecs2.push_back(rvec2);\n        tvecs2.push_back(tvec2);\n    }\n\n    Eigen::Matrix4d H_12;\n    camodocal::HandEyeCalibration::estimateHandEyeScrew(rvecs1, tvecs1, rvecs2, tvecs2, H_12);\n\n    for (int i = 0; i < 4; ++i)\n    {\n        for (int j = 0; j < 4; ++j)\n        {\n            BOOST_REQUIRE_CLOSE(H_12_expected(i,j),H_12(i,j),0.0000000001);        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(PlanarMotion)\n{\n    camodocal::HandEyeCalibration::setVerbose(false);\n\n    Eigen::Matrix4d H_12_expected = Eigen::Matrix4d::Identity();\n    H_12_expected.block<3,3>(0,0) = Eigen::AngleAxisd(0.4, Eigen::Vector3d(0.1, 0.2, 0.3).normalized()).toRotationMatrix();\n    H_12_expected.block<3,1>(0,3) << 0.5, 0.6, 0.7;\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > rvecs1, tvecs1, rvecs2, tvecs2;\n    std::random_device rd;  //Will be used to obtain a seed for the random number engine\n    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()\n    std::uniform_int_distribution<> dis10(-10.0, 10.0);\n    std::uniform_int_distribution<> dis1(-1.0, 1.0);\n\n    int motionCount = 2;\n    for (int i = 0; i < motionCount; ++i)\n    {\n        double droll = boost::math::constants::radian<double>()*dis10(gen);\n        droll = 0;\n        double dpitch = boost::math::constants::radian<double>()*dis10(gen);\n        dpitch = 0;\n        double dyaw = boost::math::constants::radian<double>()*dis10(gen);\n        double dx = dis1(gen);\n        double dy = dis1(gen);\n        double dz = dis1(gen);\n        dz = 0;\n\n        Eigen::Matrix3d R;\n        R = Eigen::AngleAxisd(dyaw, Eigen::Vector3d::UnitZ()) *\n            Eigen::AngleAxisd(dpitch, Eigen::Vector3d::UnitY()) *\n            Eigen::AngleAxisd(droll, Eigen::Vector3d::UnitX());\n\n        Eigen::Matrix4d H = Eigen::Matrix4d::Identity();\n        H.block<3,3>(0,0) = R;\n        H.block<3,1>(0,3) << dx, dy, dz;\n\n        Eigen::Matrix4d H_ = H.inverse();\n        H = H_;\n\n        Eigen::Vector3d rvec1, tvec1, rvec2, tvec2;\n\n        Eigen::AngleAxisd angleAxis1(H.block<3,3>(0,0));\n        rvec1 = angleAxis1.angle() * angleAxis1.axis();\n\n        tvec1 = H.block<3,1>(0,3);\n\n        Eigen::AngleAxisd angleAxis2((H_12_expected.inverse() * H * H_12_expected).block<3,3>(0,0));\n        rvec2 = angleAxis2.angle() * angleAxis2.axis();\n\n        tvec2 = (H_12_expected.inverse() * H * H_12_expected).block<3,1>(0,3);\n\n        rvecs1.push_back(rvec1);\n        tvecs1.push_back(tvec1);\n        rvecs2.push_back(rvec2);\n        tvecs2.push_back(tvec2);\n    }\n\n    Eigen::Matrix4d H_12;\n    camodocal::HandEyeCalibration::estimateHandEyeScrew(rvecs1, tvecs1, rvecs2, tvecs2, H_12, true);\n\n    for (int i = 0; i < 4; ++i)\n    {\n        for (int j = 0; j < 4; ++j)\n        {\n            if (i == 2 && j == 3) continue;\n            BOOST_REQUIRE_CLOSE(H_12_expected(i,j),H_12(i,j),0.0000000001);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(PlanarMotionWithNoise)\n{\n    camodocal::HandEyeCalibration::setVerbose(true);\n\n    Eigen::Matrix4d H_12_expected = Eigen::Matrix4d::Identity();\n    H_12_expected.block<3,3>(0,0) = Eigen::AngleAxisd(0.4, Eigen::Vector3d(0.1, 0.2, 0.3).normalized()).toRotationMatrix();\n    H_12_expected.block<3,1>(0,3) << 0.5, 0.6, 0.7;\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > rvecs1, tvecs1, rvecs2, tvecs2;\n\n    double scale = 1.5;\n    int motionCount = 200;\n    double sigma = 0.0005;\n\n    std::random_device rd;  //Will be used to obtain a seed for the random number engine\n    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()\n    std::uniform_int_distribution<> dis10(-10.0, 10.0);\n    std::uniform_int_distribution<> dis100(-100.0, 100.0);\n    std::normal_distribution<> gaussian(0,sigma);\n    for (int i = 0; i < motionCount; ++i)\n    {\n        double droll = boost::math::constants::radian<double>()*dis10(gen);\n        droll = 0;\n        double dpitch =  boost::math::constants::radian<double>()*dis10(gen);\n        dpitch = 0;\n        double dyaw =  boost::math::constants::radian<double>()*dis100(gen);\n        double dx = dis10(gen);\n        double dy = dis10(gen);\n        double dz = dis10(gen);\n        dz = 0;\n\n        Eigen::Matrix3d R;\n        R = Eigen::AngleAxisd(dyaw, Eigen::Vector3d::UnitZ()) *\n            Eigen::AngleAxisd(dpitch, Eigen::Vector3d::UnitY()) *\n            Eigen::AngleAxisd(droll, Eigen::Vector3d::UnitX());\n\n        Eigen::Matrix4d H = Eigen::Matrix4d::Identity();\n        H.block<3,3>(0,0) = R;\n        H.block<3,1>(0,3) << dx, dy, dz;\n\n        Eigen::Matrix4d H_ = H.inverse();\n        H = H_;\n\n        Eigen::Vector3d rvec1, tvec1, rvec2, tvec2;\n\n        Eigen::AngleAxisd angleAxis1(H.block<3,3>(0,0));\n        rvec1 = angleAxis1.angle() * angleAxis1.axis();\n\n        tvec1 = H.block<3,1>(0,3);\n\n        Eigen::AngleAxisd angleAxis2((H_12_expected.inverse() * H * H_12_expected).block<3,3>(0,0));\n        rvec2 = angleAxis2.angle() * angleAxis2.axis();\n        double roll, pitch, yaw;\n        camodocal::mat2RPY(angleAxis2.toRotationMatrix(), roll, pitch, yaw);\n\n        roll += gaussian(gen);\n        pitch += gaussian(gen);\n        yaw += gaussian(gen);\n\n        angleAxis2.fromRotationMatrix(camodocal::RPY2mat(roll, pitch, yaw));\n        rvec2 = angleAxis2.angle() * angleAxis2.axis();\n\n        tvec2 = (H_12_expected.inverse() * H * H_12_expected).block<3,1>(0,3);\n\n        rvecs1.push_back(rvec1);\n        tvecs1.push_back(tvec1);\n        rvecs2.push_back(rvec2);\n        tvecs2.push_back(tvec2);\n    }\n\n    Eigen::Matrix4d H_12;\n    camodocal::HandEyeCalibration::estimateHandEyeScrew(rvecs1, tvecs1, rvecs2, tvecs2, H_12, true);\n    Eigen::Matrix4d H1 = H_12_expected;\n    Eigen::Matrix4d H2 = H_12;\n    std::cout << \"# INFO: H_12_expected = \" << std::endl;\n    std::cout << H_12_expected << std::endl; ;\n//    std::cout << H1 << std::endl << H2 << std::endl;\n\n//    for (int i = 0; i < 4; ++i)\n//    {\n//        for (int j = 0; j < 4; ++j)\n//        {\n//            if (i == 2 && j == 3) continue;\n//            EXPECT_NEAR(H1(i,j),H2(i,j),0.0000000001) << \"Elements differ at (\" << i << \",\" << j << \")\";\n//        }\n//    }\n}\n\n/*\nTEST(HandEyeCalibration, EstimateWithUnitTranslation)\n{\n    Eigen::Matrix4d H_12_expected = Eigen::Matrix4d::Identity();\n//    H_12_expected.block<3,3>(0,0) = Eigen::AngleAxisd(0.4, Eigen::Vector3d(0.0, 0.0, 0.3).normalized()).toRotationMatrix();\n//    H_12_expected.block<3,3>(0,0) = Eigen::AngleAxisd(0.4, Eigen::Vector3d(1, 1, 0.3).normalized()).toRotationMatrix();\n    H_12_expected.block<3,1>(0,3) << 0.5, 0.6, 0.7;\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > rvecs1, tvecs1, rvecs2, tvecs2;\n\n    int motionCount = 2;\n    for (int i = 0; i < motionCount; ++i)\n    {\n        double droll = boost::math::constants::radian<double>()*dis10(gen));\n        double dpitch =  boost::math::constants::radian<double>()*dis10(gen));\n        double dyaw =  boost::math::constants::radian<double>()*dis10(gen));\n        double dx = dis1(gen);\n        double dy = dis1(gen);\n        double dz = dis1(gen);\n\n        Eigen::Matrix3d R;\n        R = Eigen::AngleAxisd(dyaw, Eigen::Vector3d::UnitZ()) *\n            Eigen::AngleAxisd(dpitch, Eigen::Vector3d::UnitY()) *\n            Eigen::AngleAxisd(droll, Eigen::Vector3d::UnitX());\n\n        Eigen::Matrix4d H = Eigen::Matrix4d::Identity();\n        H.block<3,3>(0,0) = R;\n        H.block<3,1>(0,3) << dx, dy, dz;\n\n        Eigen::Matrix4d H_ = H.inverse();\n        H = H_;\n\n        Eigen::Vector3d rvec1, tvec1, rvec2, tvec2;\n\n        Eigen::AngleAxisd angleAxis1((H_12_expected * H * H_12_expected.inverse()).block<3,3>(0,0));\n        rvec1 = angleAxis1.angle() * angleAxis1.axis();\n\n        tvec1 = (H_12_expected * H * H_12_expected.inverse()).block<3,1>(0,3);\n        tvec1.normalize();\n\n        Eigen::AngleAxisd angleAxis2(H.block<3,3>(0,0));\n        rvec2 = angleAxis2.angle() * angleAxis2.axis();\n\n        tvec2 = H.block<3,1>(0,3);\n\n        rvecs1.push_back(rvec1);\n        tvecs1.push_back(tvec1);\n        rvecs2.push_back(rvec2);\n        tvecs2.push_back(tvec2);\n    }\n\n    Eigen::Matrix4d H_12;\n    camodocal::HandEyeCalibration::estimateHandEyeScrew(rvecs1, tvecs1, rvecs2, tvecs2, H_12, true);\n\n    for (int i = 0; i < 4; ++i)\n    {\n        for (int j = 0; j < 4; ++j)\n        {\n            EXPECT_NEAR(H_12_expected(i,j),H_12(i,j),0.0000000001) << \"Elements differ at (\" << i << \",\" << j << \")\";\n        }\n    }\n}\n*/\n}\n", "meta": {"hexsha": "3d005d3c4c444240936a49e290c57e9914603cc2", "size": 10801, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/HandEyeCalibration_test.cpp", "max_stars_repo_name": "hany606/grl", "max_stars_repo_head_hexsha": "b99ee6fa72163f22dddc5547a09a461a914889ac", "max_stars_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_stars_count": 140.0, "max_stars_repo_stars_event_min_datetime": "2015-03-28T21:30:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T18:43:11.000Z", "max_issues_repo_path": "test/HandEyeCalibration_test.cpp", "max_issues_repo_name": "hany606/grl", "max_issues_repo_head_hexsha": "b99ee6fa72163f22dddc5547a09a461a914889ac", "max_issues_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_issues_count": 173.0, "max_issues_repo_issues_event_min_datetime": "2015-03-28T21:56:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-25T17:29:02.000Z", "max_forks_repo_path": "test/HandEyeCalibration_test.cpp", "max_forks_repo_name": "hany606/grl", "max_forks_repo_head_hexsha": "b99ee6fa72163f22dddc5547a09a461a914889ac", "max_forks_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-04-03T20:37:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T20:59:11.000Z", "avg_line_length": 35.8837209302, "max_line_length": 125, "alphanum_fraction": 0.6026293862, "num_tokens": 3537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5244239477658351}}
{"text": "#include \"Camera.h\"\n#include \"Utilities.h\"\n\n#include <Eigen/Geometry>\n\nnamespace sol {\n\nCamera::Camera(const Eigen::Vector3f &o, const Eigen::Vector3f &lookat, const Eigen::Vector3f &up, float fov, float aspect, float aperture, float focusDist) \n: origin(o) {\n    lensRadius = aperture / 2.0;\n    const auto theta = fov * M_PI/180;\n    const auto halfHeight = tan(theta/2);\n    const auto halfWidth = aspect * halfHeight;\n    w = (origin - lookat).normalized();\n    u = up.cross(w).normalized();\n    v = w.cross(u).normalized();\n    lowerLeftCorner = origin - halfWidth * focusDist * u - halfHeight * focusDist * v - focusDist * w;\n    horizontal = 2 * halfWidth * focusDist * u;\n    vertical = 2 * halfHeight * focusDist * v;\n}\n\nRay Camera::getRay(float s, float t) const {\n    const auto rd = lensRadius * randomInUnitSphere();\n    const auto offset = u * rd.x() + v * rd.y();\n    const auto o = origin + offset;\n    return Ray(o, lowerLeftCorner + s * horizontal + t * vertical - o);\n}\n\n}\n", "meta": {"hexsha": "4b83265b44b697778f6c7f5f1fbae8a0f6a6b499", "size": 992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Camera.cpp", "max_stars_repo_name": "polaris/sol", "max_stars_repo_head_hexsha": "32102c08adfa8da58be6b2f7d9a2f4680b404b6d", "max_stars_repo_licenses": ["MIT"], "max_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.cpp", "max_issues_repo_name": "polaris/sol", "max_issues_repo_head_hexsha": "32102c08adfa8da58be6b2f7d9a2f4680b404b6d", "max_issues_repo_licenses": ["MIT"], "max_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.cpp", "max_forks_repo_name": "polaris/sol", "max_forks_repo_head_hexsha": "32102c08adfa8da58be6b2f7d9a2f4680b404b6d", "max_forks_repo_licenses": ["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.0666666667, "max_line_length": 157, "alphanum_fraction": 0.6532258065, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929207108942, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5244139708504169}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// ars::detail::tangent_intersection.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_ARS_DETAIL_TANGENT_INTERSECTION_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_ARS_DETAIL_TANGENT_INTERSECTION_HPP_ER_2009\n#include <boost/ars/constant.hpp>\n#include <boost/ars/point.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace ars{\n\n        //    x1  x2  x3            point abscissae\n        //   / \\ / \\ / \\\n        //  z0  z1  z2  z3 = zn     tangent abscissae\n        //\n        // z0 = x_min\n        // zn = x_max\n        // Let tang[i](x) = y[i] + dy[i](x-x[i])\n        // z[i] solves : tang[i+1](z[i]) == tang[i](z[i])\n        // t[i] = tang[i](z[i])\n\ntemplate<typename T>\nstruct tangent_intersection{\n    typedef constant<T> const_;\n\n    tangent_intersection()\n    :z_(const_::zero_),\n    t_(const_::zero_),\n    cum_sum_(const_::zero_){}\n\n    tangent_intersection(const point<T>& a,const point<T>& b){\n        T eps = exp(const_::lmin_); //TODO numeric_smallest()?\n        if(fabs(a.y()-b.y()) <= eps){\n            z_ = (a.x() + b.x()) / const_::two_;\n            t_ = (a.y() + b.y()) / const_::two_;\n        }else{\n            T ddy = b.dy() - a.dy();\n            // For greater precision :\n            if(fabs(a.dy())<fabs(b.dy())){\n                z_ = b.x() + (a.y() - b.y() + a.dy() * (b.x() - a.x()))/ddy;\n                t_ = a.y() + a.dy() * (z_ - a.x());\n            }else{\n                z_ = a.x() + (a.y() - b.y() + b.dy() * (b.x() - a.x()))/ddy;\n                t_ = b.y() +  b.dy() * (z_ - b.x());\n            }\n        }\n    }\n\n    tangent_intersection(T z,T t)\n    :z_(z), t_(t),cum_sum_(const_::zero_){}\n\n    const T& z()const{ return z_; }\n    const T& t()const{ return t_; }\n\n    private:\n    T z_; //abscissa\n    T t_; //ordinate\n    public:\n    T cum_sum_; //area under exp tangent up to z_\n};\n\ntemplate <typename T>\nstd::ostream&\noperator<<(std::ostream& out, const tangent_intersection<T> &ti)\n{\n    out << '(' << ti.z() << ',' << ti.t() << ',' << ti.cum_sum_ << ')';\n    return out;\n}\n\ntemplate <typename T>\nbool operator<(\n    const tangent_intersection<T> &a,\n    const tangent_intersection<T> &b\n){\n    return (a.cum_sum_ < b.cum_sum_);\n}\n\n}// ars\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "680ea6ec456bbb5a7c44b1f667acc82bfa19d016", "size": 2746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "adaptive_rejection_sampling/boost/ars/detail/tangent_intersection.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": "adaptive_rejection_sampling/boost/ars/detail/tangent_intersection.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": "adaptive_rejection_sampling/boost/ars/detail/tangent_intersection.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.5111111111, "max_line_length": 79, "alphanum_fraction": 0.4752367079, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5244139622177173}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.\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// Triangulation Example - computes a delaunay triangulation and draws the\n// triangulation and the corresponding finite voronoi edges\n\n#include <fstream>\n#include <random>\n#include <vector>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/extensions/triangulation/triangulation.hpp>\n#include <boost/geometry/extensions/triangulation/geometries/voronoi_adaptor.hpp>\n\nconst int samples = 100;\n\nint main()\n{\n    namespace bg = boost::geometry;\n    typedef bg::model::point<double, 2, bg::cs::cartesian> point;\n    typedef bg::model::triangulation<point> triangulation;\n\n    std::default_random_engine gen(1);\n    std::uniform_real_distribution<> dist(0.0, 1.0);\n    std::vector<point> in;\n    for (int i = 0 ; i < samples ; ++i)\n    {\n        in.push_back(point(dist(gen), dist(gen)));\n    }\n    triangulation out(samples);\n    bg::delaunay_triangulation(in, out);\n\n    std::ofstream svg(\"triangulation.svg\");\n    bg::svg_mapper<point> mapper(svg, 720, 720);\n    mapper.add(point(0, 0));\n    mapper.add(point(1, 1));\n\n    for (auto const& f : bg::face_range(out))\n    {\n        mapper.map(f, \"fill-opacity:0.3;fill:rgb(102,102,201);stroke:rgb(51,51,152);\");\n    }\n\n    typedef bg::model::voronoi_face_view<triangulation> voronoi_face_view;\n    for (auto it = out.vertices_begin() ; it != out.vertices_end() ; ++it)\n    {\n        voronoi_face_view vfv(out, it);\n        mapper.map(voronoi_face_view(out, it), \"opacity:1.0;fill:none;stroke:rgb(255,0,0);stroke-width:1\");\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "9b984fb18efbdf536b2a6582cc6013a8d499f7ff", "size": 1795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/example/triangulation/triangulation_example.cpp", "max_stars_repo_name": "BoostGSoC19/geometry", "max_stars_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T19:33:37.000Z", "max_issues_repo_path": "extensions/example/triangulation/triangulation_example.cpp", "max_issues_repo_name": "BoostGSoC19/geometry", "max_issues_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "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": "extensions/example/triangulation/triangulation_example.cpp", "max_forks_repo_name": "BoostGSoC19/geometry", "max_forks_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T04:54:35.000Z", "avg_line_length": 31.4912280702, "max_line_length": 107, "alphanum_fraction": 0.686908078, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.5244139399777021}}
{"text": "#include \"Expression.h\"\n\n#include <iostream>\n\n#include <Eigen/Dense>\n\n#include <gmpxx.h>\n\ntypedef Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic> MatrixXq;\n\nstatic std::ostream& operator<<(std::ostream & stream, mpq_class const & rop) {\n  stream << rop.get_str();\n  return stream;\n}\n\nExpression Expression::ApplyGaugeSymmetry(Expression const & delta) const {\n  Expression gauge_term (*this);\n  gauge_term.MultiplyOther(delta);\n\n  gauge_term.SortMonomials();\n\n  gauge_term.EliminateEpsilonEpsilonI();\n  gauge_term.EliminateEpsilonI();\n\n  gauge_term.SortMonomials();\n  gauge_term.EliminateEtaEta();\n\n  gauge_term.SortMonomials();\n  gauge_term.EliminateDelta();\n\n  gauge_term.SortMonomials();\n  gauge_term.EliminateEpsilon();\n\n  gauge_term.ApplyMonomialSymmetries();\n\n  gauge_term.SortMonomials();\n  gauge_term.SortSummands();\n  gauge_term.CollectPrefactors();\n  gauge_term.CanonicalisePrefactors();\n  gauge_term.EliminateZeros();\n\n  gauge_term.ApplyMonomialSymmetriesToContractions();\n\n  gauge_term.ApplyMonomialSymmetries();\n  gauge_term.SortMonomials();\n  gauge_term.SortSummands();\n  gauge_term.CollectPrefactors();\n  gauge_term.CanonicalisePrefactors();\n  gauge_term.EliminateZeros();\n\n  gauge_term.EliminateEtaPartial();\n  gauge_term.EliminateEpsilon();\n\n  gauge_term.ApplyMonomialSymmetries();\n  gauge_term.SortMonomials();\n  gauge_term.SortSummands();\n  gauge_term.CollectPrefactors();\n  gauge_term.CanonicalisePrefactors();\n  gauge_term.EliminateZeros();\n\n  gauge_term.EliminateEtaRankOne();\n  gauge_term.RenameDummies();\n\n  gauge_term.ApplyMonomialSymmetries();\n  gauge_term.SortMonomials();\n  gauge_term.SortSummands();\n  gauge_term.CollectPrefactors();\n  gauge_term.CanonicalisePrefactors();\n  gauge_term.EliminateZeros();\n  gauge_term.SortSummandsByPrefactors();\n\n  std::cout << \"Gauge transform:\" << std::endl;\n  std::cout << delta.GetLatexString() << std::endl;\n\n  std::cout << \"The gauge term reads:\" << std::endl;\n  std::cout << gauge_term.GetLatexString() << std::endl;\n\n  std::cout << \"It has to vanish identically for each possible xi.\" << std::endl;\n\n  std::set<ScalarSum> sum_set;\n  std::set<size_t> coefficient_set;\n\n  std::for_each(gauge_term.summands->begin(), gauge_term.summands->end(),\n    [&coefficient_set,&sum_set] (auto const & a) {\n      coefficient_set.merge(a.second->CoefficientSet());\n      sum_set.insert(*a.second);\n    });\n\n\n  std::map<size_t, size_t> coefficient_map = GetCoefficientMap();\n\n  std::cout << \"number of different (not necessarily linear independent) equations : \" << sum_set.size() << std::endl;\n  std::cout << \"number of coefficients (e_.) in these equations                    : \" << coefficient_map.size() << std::endl;\n\n  std::vector<std::vector<Rational>> matrix;\n  std::for_each(sum_set.begin(), sum_set.end(), [&coefficient_map, &matrix](auto & a) {\n    matrix.push_back(a.CoefficientVector(coefficient_map));\n    });\n\n  MatrixXq mq(matrix.size(), coefficient_map.size());\n\n  for (size_t row_counter = 0; row_counter < matrix.size(); ++row_counter) {\n    for (size_t column_counter = 0; column_counter < coefficient_map.size(); ++column_counter) {\n      Fraction frac = matrix[row_counter][column_counter].get_fraction();\n      mq(row_counter, column_counter) = mpq_class(frac.first, frac.second);\n    }\n  }\n\n  Eigen::FullPivLU<MatrixXq> lu_decompq(mq);\n\n  std::cout << \"the rank of the matrix is : \" << lu_decompq.rank() << std::endl;\n  std::cout << \"null space basis: \" << std::endl;\n\n  MatrixXq kq = lu_decompq.kernel();\n\n  std::cout << kq << std::endl;\n\n  std::map<size_t, size_t> coefficient_rmap;\n  std::for_each(coefficient_map.begin(), coefficient_map.end(), [&coefficient_rmap](auto a) { coefficient_rmap.insert(std::make_pair(a.second, a.first)); });\n\n  std::map<size_t, ScalarSum> replace_map;\n\n  std::vector<std::vector<mpq_class>> kq_vec (kq.rows());\n  std::generate(kq_vec.begin(), kq_vec.end(),\n    [n=0,&kq] () mutable {\n      std::vector<mpq_class> vec_ret (kq.cols());\n      std::generate(vec_ret.begin(), vec_ret.end(),\n      [m=0,&kq,_n=n++] () mutable {\n        return kq(_n,m++);\n      });\n      return vec_ret;\n    });\n\n  std::for_each(kq_vec.cbegin(), kq_vec.cend(),\n    [&replace_map,coefficient_rmap,n=0] (auto const & a) mutable {\n      ScalarSum scalar_sum;\n      std::for_each(a.cbegin(), a.cend(),\n        [&scalar_sum, m=0] (auto const & b) mutable {\n          scalar_sum.AddScalar(Scalar(Rational(b), ++m));\n        });\n      replace_map[coefficient_rmap[n++]] = scalar_sum;\n    });\n\n  std::cout << \"Thus the \" << coefficient_map.size() << \" original constants can be parameterized as:\" << std::endl;\n  std::for_each(replace_map.begin(), replace_map.end(),\n    [](auto const & a) {\n      std::cout << \"e_\" << a.first << \" --> \" << a.second.ToString() << std::endl;\n    });\n\n  std::cout << \"With \" << kq.cols() << \" remaining constant\" << (kq.cols() == 1 ? \"\" : \"(s)\") << \".\" << std::endl;\n\n  Expression expression_copy = *this;\n\n  expression_copy.SubstituteVariables(replace_map);\n\n  expression_copy.CanonicalisePrefactors();\n  expression_copy.EliminateZeros();\n\n  return Expression(expression_copy);\n}\n", "meta": {"hexsha": "73ca1d2c6ebced9bf8c2e2ad0a9d7ef57606c1ac", "size": 5104, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ApplyGaugeSymmetry.cpp", "max_stars_repo_name": "nilsalex/tensor-algebra", "max_stars_repo_head_hexsha": "e878cb528dea7e17225f9a27c75e978d5a5aa216", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ApplyGaugeSymmetry.cpp", "max_issues_repo_name": "nilsalex/tensor-algebra", "max_issues_repo_head_hexsha": "e878cb528dea7e17225f9a27c75e978d5a5aa216", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-25T12:17:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-25T12:17:54.000Z", "max_forks_repo_path": "src/ApplyGaugeSymmetry.cpp", "max_forks_repo_name": "nilsalex/tensor-algebra", "max_forks_repo_head_hexsha": "e878cb528dea7e17225f9a27c75e978d5a5aa216", "max_forks_repo_licenses": ["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.701863354, "max_line_length": 157, "alphanum_fraction": 0.6867163009, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5243977063910656}}
{"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_REMAINDER_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REMAINDER_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing remainder capabilities\n\n    Computes the remainder of division.\n    The return value is x-n*y, where n is the value x/y,\n    rounded to the nearest integer (using round2even).\n\n    @par semantic:\n    For any given value @c x, @c y of type @c T:\n\n    @code\n    T r = remainder(x, y);\n    @endcode\n\n    For floating point values the code is similar to:\n\n    @code\n    T r = x-divround2even(x, y)*y;\n    @endcode\n\n    @par Note:\n\n    As r can be negative, @c remainder is not defined for unsigned types.\n\n    For floating entries:\n       -  if x is +/-inf , Nan is returned\n       -  If y is +/-0   , Nan is returned\n       -  If either argument is NaN, Nan is returned\n       -  If the returned value is 0, it will have the same sign as x.\n\n    If correct values for these limit cases do not matter for you, using the fast_ decorator\n    can gain some cycles.\n\n    @see mod, rem, modulo\n\n    @par Alias\n\n    @c drem\n\n    @par Decorators\n\n    fast_ for floating entries\n\n  **/\n  const boost::dispatch::functor<tag::remainder_> remainder = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/remainder.hpp>\n#include <boost/simd/function/simd/remainder.hpp>\n\n#endif\n", "meta": {"hexsha": "df413544739cc63383920482747e8330bbbcc1a8", "size": 1820, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/remainder.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/remainder.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/remainder.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.9315068493, "max_line_length": 100, "alphanum_fraction": 0.6071428571, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5243689825450338}}
{"text": "//\n// Created by michel on 27-04-21.\n//\n\n#include \"test-helper.h\"\n#include <boost/math/special_functions/relative_difference.hpp>\n#include <cmath>\n#include \"org-simple/util/dsp/iir-butterworth.h\"\n#include <vector>\n\n#include \"util/text/iir-coefficients-test-helper.h\"\n\nusing namespace org::simple::util::dsp;\n\nstruct FilterGainScenario : public FilterScenario {\n  size_t signal_period;\n  size_t filter_period;\n\n  const char *typeOfScenario() const override { return \"FilterGainScenario\"; }\n  void parameters(std::ostream &out) const override {\n    out << \"; signal_period=\" << signal_period\n        << \"; filter_period=\" << filter_period;\n  }\n\n  FilterGainScenario(size_t sp, size_t fp, FilterType t, unsigned o)\n      : FilterScenario(t, o), signal_period(sp), filter_period(fp) {}\n};\n\nconst std::vector<FilterGainScenario> getFilterGainScenarios() {\n  std::vector<FilterGainScenario> result;\n  for (size_t signal_period : get_test_periods()) {\n    for (size_t filter_period : get_test_periods()) {\n      result.emplace_back(FilterGainScenario(signal_period, filter_period,\n                                             FilterType::LOW_PASS, 1));\n      result.emplace_back(FilterGainScenario(signal_period, filter_period,\n                                             FilterType::HIGH_PASS, 1));\n      result.emplace_back(FilterGainScenario(signal_period, filter_period,\n                                             FilterType::LOW_PASS, 2));\n      result.emplace_back(FilterGainScenario(signal_period, filter_period,\n                                             FilterType::HIGH_PASS, 2));\n      result.emplace_back(FilterGainScenario(signal_period, filter_period,\n                                             FilterType::LOW_PASS, 4));\n      result.emplace_back(FilterGainScenario(signal_period, filter_period,\n                                             FilterType::HIGH_PASS, 4));\n    }\n  }\n  return result;\n}\n\ntemplate <size_t ORDER>\nbool verifyButterworthGain(size_t signal_period, size_t filter_period, FilterType type,\n                double &measured, double &calculated) {\n  double filterRelativeFrequency =\n      filter_period > 2 ? 1.0 / filter_period : 0.45;\n  double signalRelativeFrequency = 1.0 / signal_period;\n  size_t min_period = std::min(signal_period, filter_period);\n  double error = 1.0 / (1.0 - 1.0 / min_period);\n  FixedOrderCoefficients<double, ORDER> filter;\n  Butterworth::create(filter, filterRelativeFrequency, type, 1.0);\n  size_t filter_length;\n  measured = measureFilterGain(filter, signal_period, filter_length);\n  double gainSquared = measured * measured;\n  calculated = Butterworth::getGain(type, ORDER,\n                           signalRelativeFrequency / filterRelativeFrequency);\n  double minGain = std::min(measured, calculated) * error;\n  if (gainSquared < minGain && calculated < minGain) {\n    return true;\n  }\n  return false;\n}\n\nstatic double reference_high_pass_gain(size_t order, double rel) {\n  double alpha = pow(fabs(rel), order);\n  return alpha / sqrt(1.0 + alpha * alpha);\n}\n\nstatic double reference_low_pass_gain(size_t order, double rel) {\n  double alpha2 = pow(fabs(rel), order * 2);\n  return 1.0 / sqrt(1.0 + alpha2);\n}\n\nstruct GainScenario : public FilterScenario {\n  double relative;\n  double expected_gain;\n  bool ref;\n\n  double actual() const {\n    if (!ref) {\n      switch (type) {\n      case FilterType::LOW_PASS:\n        return Butterworth::getLowPassGain(order, relative, false);\n      case FilterType::HIGH_PASS:\n        return Butterworth::getHighPassGain(order, relative, false);\n      default:\n        return std::numeric_limits<double>::quiet_NaN();\n      }\n    } else {\n      switch (type) {\n      case FilterType::LOW_PASS:\n        return reference_low_pass_gain(order, relative);\n      case FilterType::HIGH_PASS:\n        return reference_high_pass_gain(order, relative);\n      default:\n        return std::numeric_limits<double>::quiet_NaN();\n      }\n    }\n  }\n\n  GainScenario(FilterType t, unsigned o, double rel, double expGain, bool isRef = false)\n      : FilterScenario(t, o), relative(rel), expected_gain(expGain),\n        ref(isRef) {}\n\n  const char *typeOfScenario() const override { return \"GainCalculationScenario\"; }\n  void parameters(std::ostream &out) const override {\n    out << \"; relative-frequency=\" << relative\n        << \"; expected gain=\" << expected_gain\n        << \"; reference=\" << (ref ? \"true\" : \"false\");\n  }\n};\n\n// static std::ostream &operator<<(std::ostream &out,\n//                                 const GainScenario &scenario) {\n//   out << \"GainScenario(type=\";\n//   switch (scenario.type) {\n//   case FilterType::LOW_PASS:\n//     out << \"low-pass\";\n//     break;\n//   case FilterType::HIGH_PASS:\n//     out << \"high-pass\";\n//     break;\n//   default:\n//     out << \"invalid\";\n//   }\n//   out << \"; order=\" << scenario.order;\n//   out << \"; w/w0=\" << scenario.relative;\n//   out << \"; gain=\" << scenario.expected_gain;\n//   out << \"; reference=\" << scenario.ref;\n//\n//   return out;\n// }\n\nstd::vector<GainScenario> createTestScenarios() {\n  std::vector<GainScenario> scenarios;\n\n  scenarios.emplace_back(GainScenario(FilterType::LOW_PASS, 1, 0, 1, true));\n  scenarios.emplace_back(GainScenario(FilterType::HIGH_PASS, 1, 0, 0, true));\n  scenarios.emplace_back(GainScenario(FilterType::LOW_PASS, 1,\n                                      std::numeric_limits<double>::epsilon(), 1,\n                                      true));\n  scenarios.emplace_back(\n      GainScenario(FilterType::HIGH_PASS, 1,\n                   1.0 / std::numeric_limits<double>::epsilon(), 1, true));\n\n  for (unsigned order = 1; Butterworth::isValidOrder(order); order++) {\n    scenarios.emplace_back(\n        GainScenario(FilterType::LOW_PASS, order, 1.0, M_SQRT1_2, true));\n    scenarios.emplace_back(\n        GainScenario(FilterType::HIGH_PASS, order, 1.0, M_SQRT1_2, true));\n  }\n\n  for (unsigned order = 1; Butterworth::isValidOrder(order); order++) {\n    for (double relative = 0.125; relative <= 8; relative *= 2) {\n      scenarios.emplace_back(\n          GainScenario(FilterType::LOW_PASS, order, relative,\n                       reference_low_pass_gain(order, relative)));\n      scenarios.emplace_back(\n          GainScenario(FilterType::HIGH_PASS, order, relative,\n                       reference_high_pass_gain(order, relative)));\n    }\n  }\n\n  return scenarios;\n}\n\nstatic bool same(double x, double y) {\n  return boost::math::relative_difference(x, y) <= 1e-11;\n}\n\nBOOST_AUTO_TEST_SUITE(org_simple_dsp_iir_butterworth_tests)\n\nBOOST_DATA_TEST_CASE(sample, createTestScenarios()) {\n  if (!same(sample.expected_gain, sample.actual())) {\n    BOOST_CHECK_EQUAL(sample.expected_gain, sample.actual());\n    double g1 = Butterworth::getLowPassGain(sample.order, sample.relative, false);\n    double g2 = reference_low_pass_gain(sample.order, sample.relative);\n    BOOST_CHECK_EQUAL(g1, g2);\n  } else {\n    BOOST_CHECK(same(sample.expected_gain, sample.actual()));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testSupportedFilterTypes) {\n  BOOST_CHECK(!Butterworth::isValidFilterType(FilterType::ALL_PASS));\n  BOOST_CHECK(Butterworth::isValidFilterType(FilterType::LOW_PASS));\n  BOOST_CHECK(!Butterworth::isValidFilterType(FilterType::LOW_SHELVE));\n  BOOST_CHECK(!Butterworth::isValidFilterType(FilterType::BAND_PASS));\n  BOOST_CHECK(!Butterworth::isValidFilterType(FilterType::PARAMETRIC));\n  BOOST_CHECK(!Butterworth::isValidFilterType(FilterType::HIGH_SHELVE));\n  BOOST_CHECK(Butterworth::isValidFilterType(FilterType::HIGH_PASS));\n}\n\nBOOST_DATA_TEST_CASE(testFirstOrderHighPass, getFilterGainScenarios()) {\n  double actualGain = 0.0;\n  double calculatedGain = 0.0;\n  if (verifyButterworthGain<1>(sample.signal_period, sample.filter_period,\n                               sample.type, actualGain, calculatedGain)) {\n    BOOST_CHECK(true);\n  } else {\n    BOOST_CHECK_EQUAL(actualGain, calculatedGain);\n  }\n}\n\n#ifdef ORG_SIMPLE_IIR_BUTTERWORTH_PRINT_FILTER_LENGTHS\n\ntemplate <unsigned ORDER>\nvoid printFilterLength(double hz, unsigned short bits, FilterType type) {\n  static constexpr double rate = 96000;\n  static constexpr size_t MAX_LENGTH = 1048576;\n  FixedOrderCoefficients<double, ORDER> coefficients;\n  double f = hz / rate;\n  double err = pow(0.5, bits);\n  Butterworth::create(coefficients, f, FilterType::LOW_PASS, 1.0);\n  size_t length = effectiveIRLength(coefficients, MAX_LENGTH, err);\n  std::cout << \"Impulse response length of low pass butterworth (order\" << ORDER\n            << \") @ \" << hz << \" Hz. (\" << f << \") for \" << bits\n            << \" bits accuracy is \" << length << \" samples \\t\"\n            << (1.0 * length / rate) << \" seconds \\t\" << (f * length)\n            << \" periods.\" << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(estimateFilterLength) {\n  FilterType types[2] = { FilterType::LOW_PASS, FilterType::HIGH_PASS };\n\n  for (FilterType type : types) {\n    printFilterLength<1>(0, 24, type);\n    printFilterLength<2>(0, 24, type);\n    printFilterLength<4>(0, 24, type);\n    for (double hz = 40; hz < 12000; hz *= 2) {\n      printFilterLength<1>(hz, 24, type);\n      printFilterLength<2>(hz, 24, type);\n      printFilterLength<4>(hz, 24, type);\n    }\n    printFilterLength<2>(80, 15, type);\n    printFilterLength<2>(80, 23, type);\n    printFilterLength<2>(80, 31, type);\n  }\n}\n\n#endif\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "818580b81b8dd84ba5514693c77e697ceb7cde8c", "size": 9292, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/util/dsp/iir-butterworth-tests.cc", "max_stars_repo_name": "emmef/org-simple-util", "max_stars_repo_head_hexsha": "80c7ad1c1241ce37c8a312ba1e990ffd5a2db619", "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/util/dsp/iir-butterworth-tests.cc", "max_issues_repo_name": "emmef/org-simple-util", "max_issues_repo_head_hexsha": "80c7ad1c1241ce37c8a312ba1e990ffd5a2db619", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-09-24T21:26:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-31T13:32:53.000Z", "max_forks_repo_path": "test/util/dsp/iir-butterworth-tests.cc", "max_forks_repo_name": "emmef/org-simple", "max_forks_repo_head_hexsha": "7b2e4337b68d784e23cecded3c0dfb2ed80ea64a", "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.873015873, "max_line_length": 88, "alphanum_fraction": 0.662505381, "num_tokens": 2264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5243689717588287}}
{"text": "/*\n Copyright 2011 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/*\n * Example of a 2D simulation of nonlinearly coupled oscillators.\n * Program just prints final energy which should be close to the initial energy (1.0).\n * No parallelization is employed here.\n * Run time on a 2.3GHz Intel Core-i5: about 10 seconds for 100 steps.\n * Compile simply via bjam or directly:\n * g++ -O3 -I${BOOST_ROOT} -I../../../../.. spreading.cpp\n */\n\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cstdlib>\n#include <sys/time.h>\n\n#include <boost/ref.hpp>\n#include <boost/numeric/odeint/stepper/symplectic_rkn_sb3a_mclachlan.hpp>\n\n// we use a vector< vector< double > > as state type,\n// for that some functionality has to be added for odeint to work\n#include \"nested_range_algebra.hpp\"\n#include \"vector_vector_resize.hpp\"\n\n// defines the rhs of our dynamical equation\n#include \"lattice2d.hpp\"\n/* dynamical equations (Hamiltonian structure):\ndqdt_{i,j} = p_{i,j}\ndpdt_{i,j} = - omega_{i,j}*q_{i,j} - \\beta*[ (q_{i,j} - q_{i,j-1})^3\n                                            +(q_{i,j} - q_{i,j+1})^3\n                                            +(q_{i,j} - q_{i-1,j})^3\n                                            +(q_{i,j} - q_{i+1,j})^3 ]\n*/\n\n\nusing namespace std;\n\nstatic const int MAX_N = 1024;//2048;\n\nstatic const size_t KAPPA = 2;\nstatic const size_t LAMBDA = 4;\nstatic const double W = 1.0;\nstatic const double gap = 0.0;\nstatic const size_t steps = 100;\nstatic const double dt = 0.1;\n\ndouble initial_e = 1.0;\ndouble beta = 1.0;\nint realization_index = 0;\n\n//the state type\ntypedef vector< vector< double > > state_type;\n\n//the stepper, choose a symplectic one to account for hamiltonian structure\n//use nested_range_algebra for calculations on vector< vector< ... > >\ntypedef boost::numeric::odeint::symplectic_rkn_sb3a_mclachlan<\n    state_type , state_type , double , state_type , state_type , double ,\n    nested_range_algebra< boost::numeric::odeint::range_algebra > ,\n    boost::numeric::odeint::default_operations > stepper_type;\n\ndouble time_diff_in_ms( timeval &t1 , timeval &t2 )\n{ return (t2.tv_sec - t1.tv_sec)*1000.0 + (t2.tv_usec - t1.tv_usec)/1000.0 + 0.5; }\n\n\nint main( int argc, const char* argv[] ) {\n\n    srand( time(NULL) );\n\n    lattice2d< KAPPA , LAMBDA > lattice( beta );\n\n\n    lattice.generate_pot( W , gap , MAX_N );\n\n    state_type q( MAX_N , vector< double >( MAX_N , 0.0 ) );\n\n    state_type p( q );\n\n    state_type energy( q );\n\n    p[MAX_N/2][MAX_N/2] = sqrt( 0.5*initial_e );\n    p[MAX_N/2+1][MAX_N/2] = sqrt( 0.5*initial_e );\n    p[MAX_N/2][MAX_N/2+1] = sqrt( 0.5*initial_e );\n    p[MAX_N/2+1][MAX_N/2+1] = sqrt( 0.5*initial_e );\n\n    cout.precision(10);\n\n    lattice.local_energy( q , p , energy );\n    double e=0.0;\n    for( size_t i=0 ; i<energy.size() ; ++i )\n        for( size_t j=0 ; j<energy[i].size() ; ++j )\n        {\n            e += energy[i][j];\n        }\n\n    cout << \"initial energy: \" << lattice.energy( q , p ) << endl;\n\n    timeval elapsed_time_start , elapsed_time_end;\n    gettimeofday(&elapsed_time_start , NULL);\n\n    stepper_type stepper;\n\n    for( size_t step=0 ; step<=steps ; ++step )\n    {\n        stepper.do_step( boost::ref( lattice ) ,\n                         make_pair( boost::ref( q ) , boost::ref( p ) ) ,\n                         0.0 , 0.1 );\n    }\n\n    gettimeofday(&elapsed_time_end , NULL);\n    double elapsed_time = time_diff_in_ms( elapsed_time_start , elapsed_time_end );\n    cout << steps << \" steps in \" << elapsed_time/1000 << \" s (energy: \" << lattice.energy( q , p ) << \")\" << endl;\n}\n", "meta": {"hexsha": "a7e8a14f74a8e08751d6ff76c3cf862c7974dc34", "size": 3731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/numeric/odeint/examples/2d_lattice/spreading.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/numeric/odeint/examples/2d_lattice/spreading.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/numeric/odeint/examples/2d_lattice/spreading.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": 30.3333333333, "max_line_length": 115, "alphanum_fraction": 0.6269096757, "num_tokens": 1093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5243689672019599}}
{"text": "#define BOOST_TEST_MODULE test_regularize\n#include <boost/test/included/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <mave/mave.hpp>\n#include <tests/generate_random_matrices.hpp>\n#include <tests/tolerance.hpp>\n\ntypedef boost::mpl::list<\n    mave::vector<double, 3>, mave::vector<float, 3>\n    > test_targets;\n\nconstexpr std::size_t N = 12000;\n\ntemplate<typename T, std::size_t N>\nT length_ref(const mave::vector<T, N>& v)\n{\n    T retval(0);\n    for(std::size_t i=0; i<v.size(); ++i)\n    {\n        retval += v[i] * v[i];\n    }\n    return std::sqrt(retval);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(regularize_1arg, T, test_targets)\n{\n    using real = typename T::value_type;\n    std::mt19937 mt(123456789);\n    const auto vectors = mave::test::generate_random<T>(N, mt);\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const auto& v = vectors.at(i);\n\n        const auto ref = length_ref(v);\n        const auto val = mave::regularize(v);\n\n        BOOST_TEST(ref == std::get<1>(val), mave::test::tolerance<real>());\n        BOOST_TEST(length_ref(std::get<0>(val)) == real(1.0),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val)[0] == v[0] / std::get<1>(val),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val)[1] == v[1] / std::get<1>(val),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val)[2] == v[2] / std::get<1>(val),\n                   mave::test::tolerance<real>());\n\n        BOOST_TEST(v.diagnosis());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(regularize_2arg, T, test_targets)\n{\n    using real = typename T::value_type;\n    std::mt19937 mt(123456789);\n    const auto vectors = mave::test::generate_random<T>(N, mt);\n\n    for(std::size_t i=0; i<N; i+=2)\n    {\n        const auto& v1 = vectors.at(i);\n        const auto& v2 = vectors.at(i+1);\n\n        const auto ref1 = length_ref(v1);\n        const auto ref2 = length_ref(v2);\n\n        const auto val = mave::regularize(v1, v2);\n        const auto& val1 = std::get<0>(val);\n        const auto& val2 = std::get<1>(val);\n\n        BOOST_TEST(ref1 == std::get<1>(val1), mave::test::tolerance<real>());\n        BOOST_TEST(ref2 == std::get<1>(val2), mave::test::tolerance<real>());\n\n        BOOST_TEST(length_ref(std::get<0>(val1)) == real(1.0),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(length_ref(std::get<0>(val2)) == real(1.0),\n                   mave::test::tolerance<real>());\n\n        BOOST_TEST(std::get<0>(val1)[0] == v1[0] / std::get<1>(val1),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val1)[1] == v1[1] / std::get<1>(val1),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val1)[2] == v1[2] / std::get<1>(val1),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val2)[0] == v2[0] / std::get<1>(val2),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val2)[1] == v2[1] / std::get<1>(val2),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val2)[2] == v2[2] / std::get<1>(val2),\n                   mave::test::tolerance<real>());\n\n\n        BOOST_TEST(v1.diagnosis());\n        BOOST_TEST(v2.diagnosis());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(regularize_3arg, T, test_targets)\n{\n    using real = typename T::value_type;\n    std::mt19937 mt(123456789);\n    const auto vectors = mave::test::generate_random<T>(N, mt);\n\n    for(std::size_t i=0; i<N; i+=3)\n    {\n        const auto& v1 = vectors.at(i);\n        const auto& v2 = vectors.at(i+1);\n        const auto& v3 = vectors.at(i+2);\n\n        const auto ref1 = length_ref(v1);\n        const auto ref2 = length_ref(v2);\n        const auto ref3 = length_ref(v3);\n\n        const auto val = mave::regularize(v1, v2, v3);\n        const auto& val1 = std::get<0>(val);\n        const auto& val2 = std::get<1>(val);\n        const auto& val3 = std::get<2>(val);\n\n        BOOST_TEST(ref1 == std::get<1>(val1), mave::test::tolerance<real>());\n        BOOST_TEST(ref2 == std::get<1>(val2), mave::test::tolerance<real>());\n        BOOST_TEST(ref3 == std::get<1>(val3), mave::test::tolerance<real>());\n\n        BOOST_TEST(length_ref(std::get<0>(val1)) == real(1.0),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(length_ref(std::get<0>(val2)) == real(1.0),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(length_ref(std::get<0>(val3)) == real(1.0),\n                   mave::test::tolerance<real>());\n\n        BOOST_TEST(std::get<0>(val1)[0] == v1[0] / std::get<1>(val1),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val1)[1] == v1[1] / std::get<1>(val1),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val1)[2] == v1[2] / std::get<1>(val1),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val2)[0] == v2[0] / std::get<1>(val2),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val2)[1] == v2[1] / std::get<1>(val2),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val2)[2] == v2[2] / std::get<1>(val2),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val3)[0] == v3[0] / std::get<1>(val3),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val3)[1] == v3[1] / std::get<1>(val3),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val3)[2] == v3[2] / std::get<1>(val3),\n                   mave::test::tolerance<real>());\n\n        BOOST_TEST(v1.diagnosis());\n        BOOST_TEST(v2.diagnosis());\n        BOOST_TEST(v3.diagnosis());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(regularize_4arg, T, test_targets)\n{\n    using real = typename T::value_type;\n    std::mt19937 mt(123456789);\n    const auto vectors = mave::test::generate_random<T>(N, mt);\n\n    for(std::size_t i=0; i<N; i+=4)\n    {\n        const auto& v1 = vectors.at(i);\n        const auto& v2 = vectors.at(i+1);\n        const auto& v3 = vectors.at(i+2);\n        const auto& v4 = vectors.at(i+3);\n\n        const auto ref1 = length_ref(v1);\n        const auto ref2 = length_ref(v2);\n        const auto ref3 = length_ref(v3);\n        const auto ref4 = length_ref(v4);\n\n        const auto val = mave::regularize(v1, v2, v3, v4);\n        const auto& val1 = std::get<0>(val);\n        const auto& val2 = std::get<1>(val);\n        const auto& val3 = std::get<2>(val);\n        const auto& val4 = std::get<3>(val);\n\n        BOOST_TEST(ref1 == std::get<1>(val1), mave::test::tolerance<real>());\n        BOOST_TEST(ref2 == std::get<1>(val2), mave::test::tolerance<real>());\n        BOOST_TEST(ref3 == std::get<1>(val3), mave::test::tolerance<real>());\n        BOOST_TEST(ref4 == std::get<1>(val4), mave::test::tolerance<real>());\n\n        BOOST_TEST(length_ref(std::get<0>(val1)) == real(1.0),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(length_ref(std::get<0>(val2)) == real(1.0),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(length_ref(std::get<0>(val3)) == real(1.0),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(length_ref(std::get<0>(val4)) == real(1.0),\n                   mave::test::tolerance<real>());\n\n        BOOST_TEST(std::get<0>(val1)[0] == v1[0] / std::get<1>(val1),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val1)[1] == v1[1] / std::get<1>(val1),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val1)[2] == v1[2] / std::get<1>(val1),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val2)[0] == v2[0] / std::get<1>(val2),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val2)[1] == v2[1] / std::get<1>(val2),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val2)[2] == v2[2] / std::get<1>(val2),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val3)[0] == v3[0] / std::get<1>(val3),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val3)[1] == v3[1] / std::get<1>(val3),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val3)[2] == v3[2] / std::get<1>(val3),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val4)[0] == v4[0] / std::get<1>(val4),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val4)[1] == v4[1] / std::get<1>(val4),\n                   mave::test::tolerance<real>());\n        BOOST_TEST(std::get<0>(val4)[2] == v4[2] / std::get<1>(val4),\n                   mave::test::tolerance<real>());\n\n        BOOST_TEST(v1.diagnosis());\n        BOOST_TEST(v2.diagnosis());\n        BOOST_TEST(v3.diagnosis());\n        BOOST_TEST(v4.diagnosis());\n    }\n}\n", "meta": {"hexsha": "be1491a8f059b9fdbe0e544be09634702c7117b7", "size": 8951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_regularize.cpp", "max_stars_repo_name": "ToruNiina/mave", "max_stars_repo_head_hexsha": "163cbf273003c3fb940338cf82b1fa154a3012c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T17:46:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T00:29:04.000Z", "max_issues_repo_path": "tests/test_regularize.cpp", "max_issues_repo_name": "ToruNiina/mave", "max_issues_repo_head_hexsha": "163cbf273003c3fb940338cf82b1fa154a3012c1", "max_issues_repo_licenses": ["MIT"], "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_regularize.cpp", "max_forks_repo_name": "ToruNiina/mave", "max_forks_repo_head_hexsha": "163cbf273003c3fb940338cf82b1fa154a3012c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-04T11:02:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T11:02:20.000Z", "avg_line_length": 39.9598214286, "max_line_length": 77, "alphanum_fraction": 0.5346888616, "num_tokens": 2832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5243689655294916}}
{"text": "#include \"lm/interpolate/tune_weights.hh\"\n\n#include \"lm/interpolate/tune_derivatives.hh\"\n#include \"lm/interpolate/tune_instances.hh\"\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpragmas\" // Older gcc doesn't have \"-Wunused-local-typedefs\" and complains.\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#include <Eigen/Dense>\n#pragma GCC diagnostic pop\n#include <boost/program_options.hpp>\n\n#include <iostream>\n\nnamespace lm { namespace interpolate {\nvoid TuneWeights(int tune_file, const std::vector<StringPiece> &model_names, const InstancesConfig &config, std::vector<float> &weights_out) {\n  Instances instances(tune_file, model_names, config);\n  Vector weights = Vector::Constant(model_names.size(), 1.0 / model_names.size());\n  Vector gradient;\n  Matrix hessian;\n  for (std::size_t iteration = 0; iteration < 10 /*TODO fancy stopping criteria */; ++iteration) {\n    std::cerr << \"Iteration \" << iteration << \": weights =\";\n    for (Vector::Index i = 0; i < weights.rows(); ++i) {\n      std::cerr << ' ' << weights(i);\n    }\n    std::cerr << std::endl;\n    std::cerr << \"Perplexity = \" << Derivatives(instances, weights, gradient, hessian) << std::endl;\n    // TODO: 1.0 step size was too big and it kept getting unstable.  More math.\n    weights -= 0.7 * hessian.inverse() * gradient;\n  }\n  weights_out.assign(weights.data(), weights.data() + weights.size());\n}\n}} // namespaces\n", "meta": {"hexsha": "72c93da19e2bf7df572ef59aa588beae4965431e", "size": 1411, "ext": "cc", "lang": "C++", "max_stars_repo_path": "kenlm/lm/interpolate/tune_weights.cc", "max_stars_repo_name": "cmedlock/deepspeech.pytorch", "max_stars_repo_head_hexsha": "7f0dbcdb3bcc41992136ebedfcd3e7d6fdb256d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 111.0, "max_stars_repo_stars_event_min_datetime": "2020-08-31T04:58:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T15:44:18.000Z", "max_issues_repo_path": "Part 02/001_LM/ngram_lm_lab/kenlm/lm/interpolate/tune_weights.cc", "max_issues_repo_name": "Kabongosalomon/AMMI-NLP", "max_issues_repo_head_hexsha": "00a0e47399926ad1951b84a11cd936598a9c7c3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2020-12-16T07:27:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T17:39:01.000Z", "max_forks_repo_path": "Part 02/001_LM/ngram_lm_lab/kenlm/lm/interpolate/tune_weights.cc", "max_forks_repo_name": "Kabongosalomon/AMMI-NLP", "max_forks_repo_head_hexsha": "00a0e47399926ad1951b84a11cd936598a9c7c3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2021-02-09T08:57:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T14:09:19.000Z", "avg_line_length": 41.5, "max_line_length": 142, "alphanum_fraction": 0.7009213324, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5243522687969572}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/random_device.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\nnamespace percepto\n{\n\t\n// For initializing vectors to random in a range\ntemplate <typename Derived>\nvoid randomize_vector( Eigen::DenseBase<Derived>& mat, \n                       double minRange = -1.0, double maxRange = 1.0 )\n{\n\tif( minRange == maxRange ) \n\t{ \n\t\tmat.setConstant( minRange );\n\t\treturn;\n\t}\n\tmat.setConstant( minRange );\n\n\tboost::random::mt19937 generator;\n\tboost::random::random_device rng;\n\tgenerator.seed( rng );\n\tboost::random::uniform_real_distribution<> xDist( minRange, maxRange );\n\n\tfor( unsigned int i = 0; i < mat.rows(); ++i )\n\t{\n\t\tfor( unsigned int j = 0; j < mat.cols(); ++j )\n\t\t{\n\t\t\tmat(i,j) = xDist( generator );\n\t\t}\n\t}\n}\n\n}", "meta": {"hexsha": "a51f2d46f74af7756c4e5d1d3eebe322ca9871b1", "size": 834, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/modprop/utils/Randomization.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/Randomization.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/Randomization.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": 21.9473684211, "max_line_length": 72, "alphanum_fraction": 0.6738609113, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5243207699272016}}
{"text": "#include <Rcpp.h>\n#include <RcppEigen.h>\n#include <Eigen/Cholesky>\n#include <Eigen/Sparse>\n#include <limits>\nusing namespace Rcpp;\nusing namespace RcppEigen;\nusing Eigen::Map;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\n\n// [[Rcpp::depends(RcppEigen)]]\n\n\nvoid updateS(Eigen::MatrixXd &S, Eigen::MatrixXd &S2, Eigen::MatrixXd &S0, Eigen::MatrixXd &M, Eigen::MatrixXd &delta0, Eigen::MatrixXd &delta1, const Eigen::VectorXd &x, int iter){\n  delta0 = x - M; // delta new point wrt old mean\n  M+= delta0/(double)iter;     // sample mean\n  delta1= x - M;      // delta new point wrt new mean\n  if (iter>1){\n    S2 +=(iter-1)/(double)(iter*iter)*(delta0*delta0.transpose())+(delta1*delta1.transpose());\n    S0=S;\n    S = S2/(double)(iter-1);           // sample covariance\n  }\n}\n\n\n\n\n\n\n\n// [[Rcpp::interfaces(r,cpp)]]\n\n//' Complex Polytope Gibbs Sampling\n//' This function draw uniform samples in a convex polytope with inequality constraints\n//'\n//' @param N the number of samples to generate\n//' @param A a matrix\n//' @param b a vector of length equals to nrow(A)\n//' @param x0 a vector of length equals to nrcol(A) that should be in the polytope, for example returned by \\code{\\link{chebycenter}}\n//' @param thin thinning interval\n//'\n//' @section Details:\n//' This function is based on an initial matlab code developped called CPRND\n//' (https://ch.mathworks.com/matlabcentral/fileexchange/34208-uniform-distribution-over-a-convex-polytope)\n//' It generates samples within the complex polytope defined by \\eqn{A \\cdot x \\leqslant   b}\n//'\n//' @return a matrix with one row per sample and one column per parameter\n//' @examples\n//' n <- 20\n//' A1 <- -diag(n)\n//' b1 <- as.matrix(rep(0,n))\n//' A2 <- diag(n)\n//' b2 <- as.matrix(rep(1,n))\n//' A <- rbind(A1,A2)\n//' b <- rbind(b1,b2)\n//' X0 <- chebycenter(A,b)\n//' x <- cpgs(1000,A,b,X0)\n//' @export\n//' @useDynLib cpgsR\n// [[Rcpp::export]]\n\n\nEigen::MatrixXd cpgs(const int N, const Eigen::MatrixXd &A ,const Eigen::VectorXd &b,const Eigen::VectorXd &x0, const int thin=1) {\n  int p=A.cols();\n  int m=A.rows();\n  double inf = std::numeric_limits<double>::max();\n\n  // Check input arguments\n  if (m < (p+1) || b.size()!=m || x0.size()!=p){\n    throw std::range_error(\"dimensions mismatch\");\n  }\n  // Initialisation\n  Eigen::MatrixXd X(N,p);\n  Eigen::MatrixXd x(p,1);\n  Eigen::MatrixXd y(p,1);\n  x=x0;\n\n  // Initialize variables for keeping track of sample mean, covariance\n  // and isotropic transform.\n  Eigen::MatrixXd M(p,1);\n  M.setZero();\n  Eigen::MatrixXd S2(p,p);\n  S2.setZero();\n\n  // outer products.\n  Eigen::MatrixXd S(p,p);\n  Eigen::MatrixXd S0(p,p);\n  S.setIdentity();\n\n  IntegerVector index=Rcpp::seq(0,p-1);\n\n  Eigen::MatrixXd T1(p,p);\n  Eigen::MatrixXd T2(p,p);\n  T1.setIdentity();\n  Eigen::MatrixXd W(m,p);\n\n  W = A;\n  bool adapt=true;\n  bool updatingS=true;\n  Eigen::MatrixXd d(m,1);\n  Eigen::MatrixXd d2(m,1);\n  Eigen::MatrixXd delta0(p,1);\n  Eigen::MatrixXd delta1(p,1);\n  Eigen::MatrixXd z(m,1);\n  Eigen::MatrixXd L(p,p);\n  Eigen::MatrixXd D(p,p);\n  Eigen::VectorXd Dtmp(p);\n  Eigen::VectorXd Dzero=VectorXd::Constant(p,1.0e-16);\n  Eigen::LDLT<MatrixXd> ldltOfS(S.cols());\n  int runup=0; //number of adapt\n  int discard=0; //number of discard\n  int isample=0; //number of sample\n  int n=0; //total number of iterations\n  int stage=0; //0 adapting phase, 1 discarding phase, 2 sampling\n  int runupmax= 10*p*(p+1);\n  int sampleit=0; //total number of iteration during sampling, useful for thin\n  int discardmax=runupmax;\n  double crit=0;\n  while (isample<N){               //sampling loop\n    //std::random_shuffle(index.begin(), index.end()); //we change the order to\n    //limit the influence of initial ordering\n    index=sample(index,p,false);\n    y=x;\n    NumericVector alea2=runif(p);\n    // compute approximate stochastic transformation\n    if ((stage==1 && discard==0) || (stage>0 && updatingS==true)){ //first true\n      //sample, we now make the isotropic transformation\n      ldltOfS.compute(S.transpose());\n      D=ldltOfS.vectorD().cwiseMax(Dzero).asDiagonal();\n      L=ldltOfS.matrixL();\n      T1=ldltOfS.transpositionsP().transpose()*L*D.sqrt();\n      T2=T1.inverse();\n      W = A*T1;\n    }\n    if (stage>0) y=T2*y; //otherwise y=I^-1 * y=y\n\n    // choose p new components\n    for (int ip=0;ip<p;++ip){\n      int i=index[ip];\n      //Find points where the line with the (p-1) components x_i\n      //fixed intersects the bounding polytope.\n      z = W.col(i); //prevent any divisions by 0\n      if (ip==0)\n        d2=(b - W*y);\n      d=d2.cwiseQuotient(z);\n      double tmin=-inf;\n      double tmax=inf;\n      for (int j=0;j<m;++j){\n        if (z(j)<0 && tmin<d(j)) tmin=d(j);\n        if (z(j)>0 && tmax>d(j)) tmax=d(j);\n     }\n      tmin=std::min(0.0, tmin);\n      tmax=std::max(0.0, tmax);\n\n\n      double delta = -y(i);\n      y(i) += (tmin+(tmax-tmin)*alea2(i));\n      y(i)=std::min(std::max(y(i),-inf),inf);\n      //Rcout<<tmin<<\" \"<<tmax<<\" \"<<y(i)<<std::endl;\n      delta += y(i);\n      d2 =d2- W.col(i)*delta; //we do this to avoid making a matrix\n      //multiplication for each parameter (we just update the value of the\n      //constraint with the delta of parameter)\n}\n    x=T1*y;\n\n    if (stage==0){//still in updating phase\n      ++runup;\n      if (updatingS) updateS(S, S2, S0, M, delta0, delta1, x, runup);\n      crit=(S0-S).norm()/S0.norm();\n      if(runup>p & crit<0.5){\n        stage=1;\n        updatingS=false;\n        Rcout<<\"########adapation successful after \"<<runup<<\" iterations\"<<std::endl;\n        discardmax=runup;\n      } else if (runup==runupmax){\n        stage=1;\n        M.setZero();\n        S2.setZero();\n        S.setIdentity();\n        Rcout<<\"########adapation unsuccessful after \"<<runup<<\" iterations\"<<std::endl;\n      }\n    } else if (stage==1){ //we are in adapting phase\n      ++discard;\n      if (updatingS) updateS(S, S2, S0, M, delta0, delta1, x, discard);\n      crit=(S0-S).norm()/S0.norm();\n      if (crit < 0.5) {\n        if (updatingS) Rcout<<\"##stop updating S during discarding phase\"<<std::endl;\n        updatingS=false;\n      }\n      if (discard==discardmax){\n        stage=2;\n        M.setZero();\n        S.setIdentity();\n        S2.setZero();\n        Rcout<<\"#######end of discarding phase\"<<std::endl;\n        if (updatingS) Rcout<<\"S still updated\"<<std::endl;\n      }\n    } else{ //we are in sampling phase\n      if ((sampleit % thin) == 0){\n        X.row(isample)=x.col(0);\n        ++isample;\n      }\n      if (updatingS) updateS(S, S2, S0, M, delta0, delta1, x, isample);\n      double crit=(S0-S).norm()/S0.norm();\n      if (crit < 0.5) {\n        if (updatingS) Rcout<<\"##stop updating S during sampling phase\"<<std::endl;\n        updatingS=false;\n      }\n      ++sampleit;\n    }\n    if (n % 100 == 0) Rcout<<\"##iteration \"<<n<<\" stage \"<<stage<<\" crit \"<<crit<<\" S0.norm \"<<S0.norm()<<\" S-S0 \"<<(S-S0).norm()<<std::endl;\n    ++n;\n  }\n  return X;\n}\n\n\nusing Eigen::FullPivLU;\n\n\n\n\n//' Complex Polytope Gibbs Sampling\n//' This function draw uniform samples in a convex polytope with both equality and inequality constraints\n//'\n//' @param N the number of samples to generate\n//' @param A a matrix of coefficients of inequality constants A.x<=b\n//' @param b a vector of length equals to nrow(A)\n//' @param C a matrix of coefficients of inequality constants C.x=v\n//' @param v a vector of length equals to nrow(C)\n//' @param x0 a vector of length equals to ncol(A) that should be in the polytope, for example returned by \\code{\\link{chebycenter}}\n//' @param thin the thinning interval\n//'\n//' @section Details:\n//' This function is based on an initial matlab code developped called CPRND\n//' (https://ch.mathworks.com/matlabcentral/fileexchange/34208-uniform-distribution-over-a-convex-polytope)\n//' It generates samples within the complex polytope defined by \\eqn{A \\cdot x \\leqslant   b}\n//'\n//' @return a matrix with one row per sample and one column per parameter\n//' @examples\n//' n <- 20\n//' A1 <- -diag(n)\n//' b1 <- as.matrix(rep(0,n))\n//' A2 <- diag(n)\n//' b2 <- as.matrix(rep(1,n))\n//' A <- rbind(A1,A2)\n//' b <- rbind(b1,b2)\n//' C <- rbind(c(1,1,rep(0,n-2)),c(0,0,1,1,rep(0,n-4)))\n//' v <- matrix(rep(0.2,2),2)\n//' X0 <- rep(0.1,n)\n//' x <- cpgsEquality(1000,A,b,C,v,X0)\n//' @export\n//' @useDynLib cpgsR\n// [[Rcpp::export]]\n\n\nEigen::MatrixXd cpgsEquality(const int N, const Eigen::MatrixXd &A,\n                             const Eigen::VectorXd &b, const Eigen::MatrixXd &C,\n                             const Eigen::VectorXd &v, const Eigen::VectorXd &x0,\n                             const int thin=1){\n  int p=A.cols();\n  int m=A.rows();\n  int p2=C.cols();\n  int m2=C.rows();\n\n  MatrixXd X(N,p);\n\n  // Check input arguments\n  if (m < (p+1) || b.size()!=m || x0.size()!=p){\n    throw std::range_error(\"dimensions mismatch\");\n  }\n  if (v.size()!=m2 || x0.size()!=p2){\n    throw std::range_error(\"dimensions mismatch\");\n  }\n  // Initialisation\n  FullPivLU<MatrixXd> lu(C);\n  MatrixXd Nt = lu.kernel();\n  MatrixXd Abis=A*Nt;\n  VectorXd bbis=b-A*x0;\n\n  VectorXd x0bis=VectorXd::Zero(Nt.cols());\n  MatrixXd x=cpgs(N, Abis, bbis, x0bis, thin);\n  for(int i=0;i<N;++i) {\n    X.row(i)=Nt*x.row(i).transpose()+x0;\n  }\n  return X;\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "35c8dd48d797d140f22ebd34bd9807b20365d105", "size": 9171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpgsR.cpp", "max_stars_repo_name": "Irstea/cpgsR", "max_stars_repo_head_hexsha": "96c1d99bd038b6ce28126b124dd3651e4d16f9e5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:15:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-10T13:15:26.000Z", "max_issues_repo_path": "src/cpgsR.cpp", "max_issues_repo_name": "Irstea/cpgsR", "max_issues_repo_head_hexsha": "96c1d99bd038b6ce28126b124dd3651e4d16f9e5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-29T00:05:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-29T00:05:52.000Z", "max_forks_repo_path": "src/cpgsR.cpp", "max_forks_repo_name": "Irstea/cpgsR", "max_forks_repo_head_hexsha": "96c1d99bd038b6ce28126b124dd3651e4d16f9e5", "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.8787878788, "max_line_length": 181, "alphanum_fraction": 0.6097481191, "num_tokens": 2789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5243207699272016}}
{"text": "#include <complex>\n#include <limits>\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <rsvd/ErrorEstimators.hpp>\n\nusing Rsvd::relativeFrobeniusNormError;\n\ntemplate <typename T> struct RelativeFrobeniusNormError : public ::testing::Test {\n  using RealType = typename Eigen::NumTraits<T>::Real;\n  using MatrixType = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\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(RelativeFrobeniusNormError, NumericalTypes, );\n\n/// \\brief Relative error between equal matrices must be zero.\nTYPED_TEST(RelativeFrobeniusNormError, SameMatrix) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  const MatrixType a = MatrixType::Identity(4, 4);\n  ASSERT_NEAR(relativeFrobeniusNormError(a, a), 0, TestFixture::macheps);\n}\n\nTYPED_TEST(RelativeFrobeniusNormError, DifferentMatrices) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  MatrixType reference = MatrixType::Zero(3, 4);\n  reference(0, 0) = 1;\n\n  MatrixType approx = MatrixType::Zero(3, 4);\n  approx(0, 0) = 1;\n  approx(2, 3) = 100;\n\n  const auto relErr = relativeFrobeniusNormError(reference, approx);\n  ASSERT_NEAR(relErr, 100, TestFixture::macheps);\n}\n\nTYPED_TEST(RelativeFrobeniusNormError, NonCommutativity) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  MatrixType a = MatrixType::Zero(2, 2);\n  a << 1, 2, 3, 4;\n\n  MatrixType b = MatrixType::Zero(2, 2);\n  b << 5, 6, 7, 8;\n\n  const auto relativeToA = relativeFrobeniusNormError(a, b);\n  const auto relativeToB = relativeFrobeniusNormError(b, a);\n\n  ASSERT_NEAR(relativeToA, 8 / sqrt(30), TestFixture::macheps);\n  ASSERT_NEAR(relativeToB, 8 / sqrt(174), TestFixture::macheps);\n}\n\n/// \\brief Relative error function asserts that the reference matrix has non-zero norm.\nTYPED_TEST(RelativeFrobeniusNormError, ZeroReferenceMatrix) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  const MatrixType a = MatrixType::Zero(4, 4);\n  ASSERT_DEATH(relativeFrobeniusNormError(a, a), \"Assertion `referenceNorm > 0' failed\");\n}\n", "meta": {"hexsha": "bf2819cc152daf23fef34e64a3d1e0382204fe8c", "size": 2149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ErrorEstimators.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/ErrorEstimators.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/ErrorEstimators.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": 32.0746268657, "max_line_length": 98, "alphanum_fraction": 0.7468590042, "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5243207695316416}}
{"text": "#define BOOST_TEST_MODULE matrix\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/matrix/static/StaticDenseRowMajor.h++>\n\n\ntypedef boost::mpl::list<\n\tfloat,\n\tdouble\n> scalar_list;\n\n\n\nBOOST_AUTO_TEST_SUITE(test_matrix)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( Declaration, Scalar, scalar_list )\n{\n\tmla::matrix::StaticDenseRowMajor<Scalar, 3, 3> m;\n\n\tBOOST_CHECK_EQUAL(m.rows(), 3);\n\tBOOST_CHECK_EQUAL(m.columns(), 3);\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( Clearing, Scalar, scalar_list )\n{\n\tmla::matrix::StaticDenseRowMajor<Scalar, 3, 3> m;\n\tm.setZero();\n\n\tfor(unsigned int i = 0; i < 3; i++)\n\t{\n\t\tfor(unsigned int j = 0; j < 3; j++)\n\t\t{\n\t\t\tBOOST_CHECK_EQUAL(m.getValue(i, j), 0.0);\n\t\t}\n\t}\n\t\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( Assigning, Scalar, scalar_list )\n{\n\tmla::matrix::StaticDenseRowMajor<Scalar, 3, 3> m;\n\tm.setZero();\n\n\tm(1,1) = 1.0;\t\n\n\tBOOST_CHECK_EQUAL(m.getValue(1, 1), 1.0);\n\n\tBOOST_CHECK_EQUAL(m.getValue(0, 1), 0.0);\n\tBOOST_CHECK_EQUAL(m.getValue(2, 1), 0.0);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "b7a0475830841804c94555766a251c9b75ebe84b", "size": 1075, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_matrix_StaticDenseRowMajor.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "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": "unit_tests/test_matrix_StaticDenseRowMajor.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/test_matrix_StaticDenseRowMajor.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "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.3387096774, "max_line_length": 65, "alphanum_fraction": 0.7079069767, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5243207673019702}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/pow2.hpp\n *\n * \\brief Apply the \\c std::pow2 function to a vector or matrix expression.\n *\n * Copyright (c) 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_POW2_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_POW2_HPP\n\n\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/expression/matrix_unary_functor.hpp>\n#include <boost/numeric/ublasx/expression/vector_unary_functor.hpp>\n#include <cmath>\n#include <complex>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\nnamespace detail {\n\ntemplate <typename VectorExprT>\nstruct vector_pow2_functor_traits\n{\n\ttypedef VectorExprT input_expression_type;\n\ttypedef typename vector_traits<input_expression_type>::value_type signature_argument_type;\n\ttypedef signature_argument_type signature_result_type;\n\ttypedef vector_unary_functor_traits<\n\t\t\t\tinput_expression_type,\n\t\t\t\tsignature_result_type (signature_argument_type)\n\t\t\t> unary_functor_expression_type;\n\ttypedef typename unary_functor_expression_type::result_type result_type;\n\ttypedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\ntemplate <typename MatrixExprT>\nstruct matrix_pow2_functor_traits\n{\n\ttypedef MatrixExprT input_expression_type;\n\ttypedef typename matrix_traits<input_expression_type>::value_type signature_argument_type;\n\ttypedef signature_argument_type signature_result_type;\n\ttypedef matrix_unary_functor_traits<\n\t\t\t\tinput_expression_type,\n\t\t\t\tsignature_result_type (signature_argument_type)\n\t\t\t> unary_functor_expression_type;\n\ttypedef typename unary_functor_expression_type::result_type result_type;\n\ttypedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\n//namespace /*<unnamed>*/ {\n\n/// Auxiliary function used to replace ::std::pow2 when that is not available.\ntemplate <typename T>\nBOOST_UBLAS_INLINE\nT pow2(T x)\n{\n\treturn ::std::pow(2,x);\n}\n\n/// Auxiliary function used to replace ::std::pow2 when that is not available.\ntemplate <typename T>\nBOOST_UBLAS_INLINE\n::std::complex<T> pow2(::std::complex<T> x)\n{\n\t// Use the complex exponentiation formula.\n\t// See:\n\t// - http://en.wikipedia.org/wiki/Exponentiation#Powers_of_complex_numbers\n\t// - http://mathworld.wolfram.com/ComplexExponentiation.html\n\n\tT c0 = ::std::pow(2,x.real());\n\tT c1 = x.imag()*::std::log(2);\n\treturn ::std::complex<T>(c0*::std::cos(c1),c0*::std::sin(c1));\n}\n\n//} // Namespace <unnamed>\n\n} // Namespace detail\n\n\n/**\n * \\brief Applies the \\c std::pow2 function to a given vector expression.\n *\n * \\tparam VectorExprT The type of the input vector expression.\n *\n * \\param ve The input vector expression.\n * \\return A vector expression representing the application of \\c std::pow2 to\n *  each element of \\a ve.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename detail::vector_pow2_functor_traits<VectorExprT>::result_type pow2(vector_expression<VectorExprT> const& ve)\n{\n\ttypedef typename detail::vector_pow2_functor_traits<VectorExprT>::expression_type expression_type;\n\ttypedef typename detail::vector_pow2_functor_traits<VectorExprT>::signature_argument_type signature_argument_type;\n\ttypedef typename detail::vector_pow2_functor_traits<VectorExprT>::signature_result_type signature_result_type;\n\n//\treturn expression_type(ve(), detail::pow2<signature_result_type>);\n//\tsignature_result_type (*)(ptr_pow2_fun)(signature_argument_type)(BOOST_NUMERIC_UBLASX_OPERATION_POW2_NS_::pow2); \n\ttypedef signature_result_type(*fun_ptr_type)(signature_argument_type);\n\tfun_ptr_type ptr_pow2_fun(&detail::pow2); \n\treturn expression_type(ve(), ptr_pow2_fun);\n}\n\n\n/**\n * \\brief Applies the \\c std::pow2 function to a given matrix expression.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param me The input matrix expression.\n * \\return A matrix expression representing the application of \\c std::pow2 to\n *  each element of \\a me.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename detail::matrix_pow2_functor_traits<MatrixExprT>::result_type pow2(matrix_expression<MatrixExprT> const& me)\n{\n\ttypedef typename detail::matrix_pow2_functor_traits<MatrixExprT>::expression_type expression_type;\n\ttypedef typename detail::matrix_pow2_functor_traits<MatrixExprT>::signature_argument_type signature_argument_type;\n\ttypedef typename detail::matrix_pow2_functor_traits<MatrixExprT>::signature_result_type signature_result_type;\n\n//\treturn expression_type(me(), detail::pow2<signature_result_type>(signature_argument_type));\n\ttypedef signature_result_type(*fun_ptr_type)(signature_argument_type);\n\tfun_ptr_type ptr_pow2_fun(&detail::pow2); \n\treturn expression_type(me(), ptr_pow2_fun);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_POW2_HPP\n", "meta": {"hexsha": "087579ff12e6902a9a2744b7765a76b276fb827f", "size": 5118, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/pow2.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/pow2.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/pow2.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5810810811, "max_line_length": 116, "alphanum_fraction": 0.7964048456, "num_tokens": 1210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5243207575921639}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// integrated_acf.hpp                                                        //\n//                                                                           //\n//  Copyright 2008 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_ACCUMULATORS_STATISTICS_INTEGRATED_ACF_HPP_ER_2008_04\n#define BOOST_ACCUMULATORS_STATISTICS_INTEGRATED_ACF_HPP_ER_2008_04\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/size_t.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/placeholders.hpp>\n\n#include <boost/call_traits.hpp>\n#include <boost/array.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/type_traits/add_const.hpp>\n\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n\n#include <boost/accumulators/statistics/acv0.hpp>\n#include <boost/accumulators/statistics/integrated_acvf.hpp>\n\nnamespace boost { namespace accumulators\n{\n\n\nnamespace impl\n{\n    ////////////////////////////////////////////////////////////////////////////\n    // integrated_acf_impl\n    template<typename T,typename I>\n    class integrated_acf_impl\n      : public accumulator_base\n    {\n    public:\n        typedef T                              result_type;\n\n        integrated_acf_impl(dont_care):val(static_cast<T>(0)){}\n\n        template<typename Args>\n        void operator ()(Args const &args)\n        {\n            T iacvf = integrated_acvf<I>(args[accumulator]);\n            T acv0_val = acv0<I>(args[accumulator]);\n            if(acv0_val>static_cast<T>(0)){\n                val = iacvf/acv0_val;\n            }else{\n                val = static_cast<T>(0);\n            }\n\t\t}\n\n        result_type result(dont_care) const{ \n            return val;\n        }\n\n    private:\n\t   T  val;\n\n    };\n\n} // namespace impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::integrated_acf\n//\n\nnamespace tag\n{\n\n    template <typename I = default_delay_discriminator>\n    struct integrated_acf\n      : depends_on<acv0<I>,integrated_acvf<I> >\n    {\n        /// INTERNAL ONLY\n      typedef\n        accumulators::impl::integrated_acf_impl<mpl::_1,I> impl;\n\n    };\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::integrated_acf\n//\n\nnamespace extract\n{\n\n  template<typename I,typename AccumulatorSet>\n  typename mpl::apply<\n    AccumulatorSet,tag::integrated_acf<I> >::type::result_type\n  integrated_acf(AccumulatorSet const& acc){\n    typedef tag::integrated_acf<I> the_tag;\n    return extract_result<the_tag>(acc);\n  }\n\n}\n\nusing extract::integrated_acf;\n\n\n}} // namespace boost::accumulators\n\n#endif\n", "meta": {"hexsha": "e953798c50bdb61ba7e5493d3be4ba97f7751c3c", "size": 3297, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "autocovariance/boost/accumulators/statistics/integrated_acf.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": "autocovariance/boost/accumulators/statistics/integrated_acf.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": "autocovariance/boost/accumulators/statistics/integrated_acf.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": 28.1794871795, "max_line_length": 80, "alphanum_fraction": 0.5723384895, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5242977476028979}}
{"text": "/*\n * Simulation of an ensemble of Roessler attractors using NT2 SIMD library\n * This requires the SIMD library headers.\n *\n * Copyright 2014 Mario Mulansky\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n *\n */\n\n\n#include <iostream>\n#include <vector>\n#include <random>\n\n#include <boost/timer.hpp>\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/simd/sdk/simd/pack.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <boost/simd/memory/allocator.hpp>\n#include <boost/simd/include/functions/splat.hpp>\n#include <boost/simd/include/functions/plus.hpp>\n#include <boost/simd/include/functions/multiplies.hpp>\n\n\nnamespace odeint = boost::numeric::odeint;\nnamespace simd = boost::simd;\n\ntypedef boost::timer timer_type;\n\nstatic const size_t dim = 3;  // roessler is 3D\n\ntypedef double fp_type;\n//typedef float fp_type;\n \ntypedef simd::pack<fp_type> simd_pack;\ntypedef boost::array<simd_pack, dim> state_type;\n// use the simd allocator to get properly aligned memory\ntypedef std::vector< state_type, simd::allocator< state_type > > state_vec;\n\nstatic const size_t pack_size = simd_pack::static_size;\n\n//---------------------------------------------------------------------------\nstruct roessler_system {\n    const fp_type m_a, m_b, m_c;\n\n    roessler_system(const fp_type a, const fp_type b, const fp_type c)\n        : m_a(a), m_b(b), m_c(c)\n    {}\n\n    void operator()(const state_type &x, state_type &dxdt, const fp_type t) const\n    {\n        dxdt[0] = -1.0*x[1] - x[2];\n        dxdt[1] = x[0] + m_a * x[1];\n        dxdt[2] = m_b + x[2] * (x[0] - m_c);\n    }\n};\n\n//---------------------------------------------------------------------------\nint main(int argc, char *argv[]) {\nif(argc<3)\n{\n    std::cerr << \"Expected size and steps as parameter\" << std::endl;\n    exit(1);\n}\nconst size_t n = atoi(argv[1]);\nconst size_t steps = atoi(argv[2]);\n\nconst fp_type dt = 0.01;\n\nconst fp_type a = 0.2;\nconst fp_type b = 1.0;\nconst fp_type c = 9.0;\n\n// random initial conditions on the device\nstd::vector<fp_type> x(n), y(n), z(n);\nstd::default_random_engine generator;\nstd::uniform_real_distribution<fp_type> distribution_xy(-8.0, 8.0);\nstd::uniform_real_distribution<fp_type> distribution_z(0.0, 20.0);\nauto rand_xy = std::bind(distribution_xy, std::ref(generator));\nauto rand_z = std::bind(distribution_z, std::ref(generator));\nstd::generate(x.begin(), x.end(), rand_xy);\nstd::generate(y.begin(), y.end(), rand_xy);\nstd::generate(z.begin(), z.end(), rand_z);\n\nstate_vec state(n/pack_size);\nfor(size_t i=0; i<n/pack_size; ++i)\n{\n    for(size_t p=0; p<pack_size; ++p)\n    {\n        state[i][0][p] = x[i*pack_size+p];\n        state[i][1][p] = y[i*pack_size+p];\n        state[i][2][p] = z[i*pack_size+p];\n    }\n}\n\nstd::cout << \"Systems: \" << n << std::endl;\nstd::cout << \"Steps: \" << steps << std::endl;\nstd::cout << \"SIMD pack size: \" << pack_size << std::endl;\n\nstd::cout << state[0][0] << std::endl;\n\n// Stepper type\nodeint::runge_kutta4_classic<state_type, fp_type, state_type, fp_type,\n                             odeint::array_algebra, odeint::default_operations,\n                             odeint::never_resizer> stepper;\n\nroessler_system sys(a, b, c);\n\ntimer_type timer;\n\nfp_type t = 0.0;\n\nfor(int step = 0; step < steps; step++)\n{\n    for(size_t i = 0; i < n/pack_size; ++i)\n    {\n        stepper.do_step(sys, state[i], t, dt);\n    }\n    t += dt;\n}\n\nstd::cout.precision(16);\n\nstd::cout << \"Integration finished, runtime for \" << steps << \" steps: \";\nstd::cout << timer.elapsed() << \" s\" << std::endl;\n\n// compute some accumulation to make sure all results have been computed\nsimd_pack s_pack = 0.0;\nfor(size_t i = 0; i < n/pack_size; ++i)\n{\n    s_pack += state[i][0];\n}\n\nfp_type s = 0.0;\nfor(size_t p=0; p<pack_size; ++p)\n{\n    s += s_pack[p];\n}\n\n\nstd::cout << state[0][0] << std::endl;\nstd::cout << s/n << std::endl;\n\n}\n", "meta": {"hexsha": "d79af4d8bf5b5481066f6c1657acb85099cbe0cc", "size": 3960, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/performance/SIMD/roessler_simd.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/performance/SIMD/roessler_simd.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/performance/SIMD/roessler_simd.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": 26.4, "max_line_length": 81, "alphanum_fraction": 0.6252525253, "num_tokens": 1134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5242977476028978}}
{"text": "#include \"socpInterface.hpp\"\n\n#include <array>\n#include <chrono>\n#include <fmt/format.h>\n\n#include <Eigen/Dense>\n\n// This example solves the portfolio optimization problem\n\nint main()\n{\n    std::vector<double> solve_times;\n\n    // assets, factors pair\n    std::vector<std::tuple<size_t, size_t, size_t>> sets = {{100, 5, 10000},\n                                                            {300, 10, 5000},\n                                                            {500, 20, 1000},\n                                                            {1000, 30, 100},\n                                                            {2000, 40, 100},\n                                                            {4000, 50, 100},\n                                                            {7500, 60, 50},\n                                                            {10000, 70, 25},\n                                                            {20000, 80, 10}};\n    for (auto [n, m, repetitions] : sets)\n    {\n        fmt::print(\"Running with assets: {}, factors: {}\\n\", n, m);\n\n        // Set up problem data.\n        double gamma = 0.5;      // risk aversion parameter\n        Eigen::VectorXd mu(n);   // vector of expected returns\n        Eigen::MatrixXd F(n, m); // factor-loading matrix\n        Eigen::VectorXd D(n);    // diagonal of idiosyncratic risk\n\n        mu.setRandom();\n        F.setRandom();\n        D.setRandom();\n        mu = mu.cwiseAbs();\n        F = F.cwiseAbs().transpose();\n        D = D.cwiseAbs().cwiseSqrt();\n\n        // Formulate SOCP.\n        auto t0 = std::chrono::high_resolution_clock::now();\n\n        op::SecondOrderConeProgram socp;\n\n        op::Variable x = socp.createVariable(\"x\", n);\n        op::Variable t = socp.createVariable(\"t\");\n        op::Variable s = socp.createVariable(\"s\");\n        op::Variable u = socp.createVariable(\"u\");\n        op::Variable v = socp.createVariable(\"v\");\n\n        socp.addConstraint(x >= 0.);\n        socp.addConstraint(op::sum(x) == op::Parameter(1.));\n        socp.addConstraint(op::norm2(op::Parameter(&D).cwiseProduct(x)) <= u);\n        socp.addConstraint(op::norm2(op::Parameter(&F) * x) <= v);\n        socp.addConstraint(op::norm2(op::vstack({op::Parameter(1.) + -t, op::Parameter(2.) * u})) <= op::Parameter(1.) + t);\n        socp.addConstraint(op::norm2(op::vstack({op::Parameter(1.) + -s, op::Parameter(2.) * v})) <= op::Parameter(1.) + s);\n\n        socp.addMinimizationTerm(-op::Parameter(&mu).transpose() * x);\n        socp.addMinimizationTerm(op::Parameter(gamma) * (t + s));\n\n        // Create and initialize the solver instance.\n        op::Solver solver(socp);\n        solver.initialize();\n\n        // Solve the problem and show solver output.\n        double total_time = 0.;\n        for (size_t rep = 0; rep < repetitions; rep++)\n        {\n            fmt::print(\"Repetition {}/{}\\n\", rep + 1, repetitions);\n            mu.setRandom();\n            F.setRandom();\n            D.setRandom();\n            mu = mu.cwiseAbs();\n            F = F.cwiseAbs().transpose();\n            D = D.cwiseAbs().cwiseSqrt();\n\n            t0 = std::chrono::high_resolution_clock::now();\n            const bool success = solver.solveProblem(false);\n            auto t1 = std::chrono::high_resolution_clock::now();\n            total_time += std::chrono::duration<double>(t1 - t0).count();\n        }\n        solve_times.push_back(total_time / repetitions);\n    }\n\n    fmt::print(\"\\nAverage times:\\n\");\n    for (size_t i = 0; i < sets.size(); i++)\n    {\n        fmt::print(\"{},\\n\", solve_times[i]);\n    }\n}", "meta": {"hexsha": "4b4200f416bfb6cfda27990c2a5c1afae4557ec2", "size": 3550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/portfolio_test.cpp", "max_stars_repo_name": "EmbersArc/socp_interface", "max_stars_repo_head_hexsha": "d569ca7315a808e1070d1d01148018f2148ce672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-08-24T00:50:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T21:35:17.000Z", "max_issues_repo_path": "src/tests/portfolio_test.cpp", "max_issues_repo_name": "EmbersArc/socp_interface", "max_issues_repo_head_hexsha": "d569ca7315a808e1070d1d01148018f2148ce672", "max_issues_repo_licenses": ["MIT"], "max_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/portfolio_test.cpp", "max_forks_repo_name": "EmbersArc/socp_interface", "max_forks_repo_head_hexsha": "d569ca7315a808e1070d1d01148018f2148ce672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-07-22T01:34:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T12:45:24.000Z", "avg_line_length": 38.5869565217, "max_line_length": 124, "alphanum_fraction": 0.4881690141, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.524297742374841}}
{"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_ARCH_COMMON_SCALAR_FUNCTION_LOG1P_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_LOG1P_HPP_INCLUDED\n#include <boost/simd/function/std.hpp>\n\n#include <boost/simd/detail/enforce_precision.hpp>\n#include <boost/simd/function/log.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( log1p_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      detail::enforce_precision<A0> enforcer;\n\n      if (Mone<A0>() > a0)   return Nan<A0>();\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      if (a0 == Inf<A0>())   return Inf<A0>();\n      #endif\n      if (a0 == Mone<A0>())   return Minf<A0>();\n      A0 u = inc(a0);\n      return log(u)+(a0-dec(u))/u;\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( log1p_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const std_tag &, A0 a0) const BOOST_NOEXCEPT\n    {\n      return std::log1p(a0);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "c8b87f558e8561d21c228494e77cf5a415504350", "size": 1939, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/log1p.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/arch/common/scalar/function/log1p.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/arch/common/scalar/function/log1p.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": 31.2741935484, "max_line_length": 100, "alphanum_fraction": 0.5301701908, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5242977371467837}}
{"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_ARCH_COMMON_SIMD_FUNCTION_AVERAGE_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_AVERAGE_HPP_INCLUDED\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/function/bitwise_and.hpp>\n#include <boost/simd/function/bitwise_xor.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/plus.hpp>\n#include <boost/simd/function/shift_right.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD_IF ( average_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::arithmetic_<A0>, X>\n                          , bs::pack_< bd::arithmetic_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT\n    {\n      return bitwise_and(a0, a1)+shift_right(bitwise_xor(a0, a1),1);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( average_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::floating_<A0>, X>\n                          , bs::pack_< bd::floating_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT\n    {\n      return fma(a0,Half<A0>(),a1*Half<A0>());\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "dda945fd1af2dddfa4d9651033bbbcb2dbf7fc28", "size": 2021, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/average.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/arch/common/simd/function/average.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/arch/common/simd/function/average.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": 34.8448275862, "max_line_length": 100, "alphanum_fraction": 0.5363681346, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5242977371467837}}
{"text": "/*--\n    PrimitiveFitUtils.cpp  \n\n    This file is part of the Cornucopia curve sketching library.\n    Copyright (C) 2010 Ilya Baran (baran37@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#include \"PrimitiveFitUtils.h\"\n\n#include \"Line.h\"\n#include \"Arc.h\"\n#include \"Clothoid.h\"\n#include \"Fresnel.h\"\n\n#include <Eigen/Eigenvalues>\n\nusing namespace std;\nusing namespace Eigen;\nNAMESPACE_Cornu\n\nvoid LineFitter::addPointW(const Vector2d &pt, double weight)\n{\n    ++_numPts;\n    _totWeight += weight;\n\n    _lastPoint = pt;\n    if(_numPts == 1)\n        _firstPoint = pt;\n\n    _sum += weight * pt;\n    _squaredSum[0] += weight * SQR(pt[0]);\n    _squaredSum[1] += weight * SQR(pt[1]);\n    _crossSum += weight * pt[0] * pt[1];\n}\n\nLinePtr LineFitter::getCurve() const\n{\n    if(_numPts < 2)\n        return LinePtr();\n\n    Matrix2d cov = Matrix2d::Zero();\n    double factor = 1. / double(_totWeight);\n    cov(0, 0) = _squaredSum[0] - SQR(_sum[0]) * factor;\n    cov(1, 1) = _squaredSum[1] - SQR(_sum[1]) * factor;\n    cov(0, 1) = cov(1, 0) = _crossSum - _sum[0] * _sum[1] * factor;\n    cov *= factor;\n\n    SelfAdjointEigenSolver<Matrix2d> eigenSolver(cov);\n\n    Vector2d eigVs = eigenSolver.eigenvalues();\n    Vector2d dir = eigenSolver.eigenvectors().col(1).normalized(); //1 is the index of the larger eigenvalue\n    Vector2d pt = _sum * factor;\n    Vector2d pt0 = pt + ((_firstPoint - pt).dot(dir)) * dir;\n    Vector2d pt1 = pt + ((_lastPoint - pt).dot(dir)) * dir;\n\n    return new Line(pt0, pt1);\n}\n\nvoid ArcFitter::addPointW(const Vector2d &pt, double weight)\n{\n    _pts.push_back(pt);\n\n    Vector3d pt3(pt[0] - _pts[0][0], pt[1] - _pts[0][1], (pt - _pts[0]).squaredNorm());\n\n    _totWeight += weight;\n    _sum += weight * pt3;\n    _squaredSum += weight * pt3 * pt3.transpose();\n}\n\nArcPtr ArcFitter::getCurve() const\n{\n    if((int)_pts.size() < 2)\n        return ArcPtr();\n\n    double factor = 1. / _totWeight;\n    Vector3d pt = _sum * factor;\n    Matrix3d cov = factor * _squaredSum - pt * pt.transpose();\n\n    SelfAdjointEigenSolver<Matrix3d> eigenSolver(cov);\n    Vector3d eigVs = eigenSolver.eigenvalues();\n\n    Vector3d dir = eigenSolver.eigenvectors().col(0); //0 is the index of the smallest eigenvalue\n    dir /= (1e-16 + dir[2]);\n\n    double dot = dir.dot(pt);\n    //circle equation is:\n    //dir[0] * x + dir[1] * y + (x^2+y^2) = dot\n    Vector2d center = -0.5 * Vector2d(dir[0], dir[1]);\n    double radius = sqrt(1e-16 + dot + center.squaredNorm());\n    center += _pts[0];\n\n    //TODO: convert code to use AngleUtils\n    //Now get the arc\n    Vector2d c[3] = { _pts[0], _pts[_pts.size() / 2], _pts.back() };\n    double angle[3];\n    for(int i = 0; i < 3; ++i) {\n        c[i] = (c[i] - center).normalized() * radius;\n        angle[i] = atan2(c[i][1], c[i][0]);\n    }\n    if(angle[2] < angle[0])\n        angle[2] += PI * 2.;\n    if(angle[1] < angle[0])\n        angle[1] += PI * 2.;\n    if(angle[1] <= angle[2]) { //OK--CCW arc\n        double a = angle[2] - angle[0];\n        return new Arc(c[0] + center, angle[0] + PI * 0.5, a * radius, 1. / radius);\n    }\n    else { //Backwards--CW arc\n        for(int i = 0; i < 3; ++i)\n            angle[i] = atan2(c[i][1], c[i][0]);\n        if(angle[0] <= angle[2])\n            angle[0] += PI * 2.;\n        if(angle[1] < angle[2])\n            angle[1] += PI * 2.;\n        assert(angle[1] <= angle[0]);\n        double a = angle[0] - angle[2];\n        return new Arc(c[0] + center, angle[0] - PI * 0.5, a * radius, -1. / radius);\n    }\n}\n\nvoid ClothoidFitter::addPoint(const Vector2d &pt)\n{\n    _pts.push_back(pt);\n\n    if((int)_pts.size() < 2)\n        return;\n\n    const Vector2d &prevPt = _pts[_pts.size() - 2];\n    double segmentLength = (pt - prevPt).norm();\n    _centerOfMass += (pt + prevPt) * (0.5 * segmentLength);\n\n    double angle = atan2(pt[1] - prevPt[1], pt[0] - prevPt[0]);\n    if(angle < _prevAngle) //make sure it's not far from the previous angle\n        angle += TWOPI * int(0.5 + (_prevAngle - angle) / TWOPI);\n    else\n        angle -= TWOPI * int(0.5 + (angle - _prevAngle) / TWOPI);\n    _prevAngle = angle;\n\n    double x0 = _totalLength;\n    double x1 = (_totalLength += segmentLength);\n\n    double y = angle;\n    double z = _angleIntegral - y * x0;\n    _rhs += _getRhs(x1, y, z) - _getRhs(x0, y, z);\n\n    _angleIntegral += segmentLength * angle;\n}\n\nClothoidPtr ClothoidFitter::getCurve() const\n{\n    Matrix4d lhs;\n\n    lhs = _getLhs(_totalLength);\n\n    Vector4d abcd = lhs.inverse() * _rhs;\n    return getClothoidWithParams(abcd);\n}\n\nClothoidPtr ClothoidFitter::getCurveWithZeroCurvature(double param) const\n{\n    Matrix<double, 5, 5> lhs;\n    Matrix<double, 5, 1> rhs;\n\n    Vector4d constraint;\n    constraint << 6 * param, 2, 0, 0; // second derivative of ax^3+bx^2+cx+d is 6ax+2b\n\n    //For constrained least squares,\n    //lhs is now [A^T A    C]\n    //           [ C^T     0]\n    lhs << _getLhs(_totalLength),   constraint,\n           constraint.transpose(),  0;\n    rhs << _rhs, 0;\n\n    Vector4d abcd = (lhs.inverse() * rhs).head<4>();\n    return getClothoidWithParams(abcd);\n}\n\nClothoidPtr ClothoidFitter::getClothoidWithParams(const Eigen::Vector4d &abcd) const\n{\n    Vector3d abc = Vector3d(abcd[0] * 3, abcd[1] * 2, abcd[2]);\n\n    double startAngle = abc[2];\n    double startCurvature = abc[1];\n    double endCurvature = 2 * abc[0] * _totalLength + abc[1];\n\n    //now compute the center of mass of the clothoid at 0\n    double x, y;\n\n    if(fabs(abc[0]) > 1e-8) //if it's a real clothoid\n    {\n        //The following comes from the expression that Mathematica generates with:\n        //Integrate[Integrate[{Cos[a x^2 + b x + c], Sin[a x^2 + b x + c]}, {x, 0, t}], {t, 0, s}]/s\n        bool negative = false;\n        if(abc[0] < 0)\n        {\n            negative = true;\n            abc = -abc;\n        }\n        double a = abc[0], b = abc[1], c = abc[2];\n        double s = _totalLength;\n\n        double invRtApi2 = 1. / sqrt(0.5 * PI * a);\n        \n        double f1s, f2s, f1c, f2c;\n        fresnelApprox(b * invRtApi2 * 0.5, &f1s, &f1c);\n        fresnelApprox((b + 2 * a * s) * invRtApi2 * 0.5, &f2s, &f2c);\n\n        double disc = b * b / (4 * a) - c;\n        double sind = sin(disc), cosd = cos(disc);\n\n        y = (cos(c + s * (b + a * s)) - cos(c)) / (2. * a);\n        y -= (b + 2 * a * s) * PI * 0.25 * (cosd * (f1s - f2s) + sind * (f2c - f1c)) * invRtApi2 / a;\n        if(negative)\n            y = -y;\n\n        x = (sin(c) - sin(c + s * (b + a * s))) / (2. * a);\n        x += (b + 2 * a * s) * PI * 0.25 * (-sind * (f1s - f2s) + cosd * (f2c - f1c)) * invRtApi2 / a;\n\n        x /= s;\n        y /= s;\n    }\n    else\n    {\n        double b = abc[1], c = abc[2];\n        double s = _totalLength;\n\n        if(fabs(b) < 1e-8) //line\n        {\n            x = cos(c) * s * 0.5;\n            y = sin(c) * s * 0.5;\n        }\n        else //arc\n        {\n            double c1 = cos(c), s1 = sin(c);\n            double c2 = cos(c + b * s), s2 = sin(c + b * s);\n\n            x = (c1 - c2) / (b * b * s) - s1 / b;\n            y = (s1 - s2) / (b * b * s) + c1 / b;\n        }\n    }\n\n    return new Clothoid(Vector2d(_centerOfMass[0] / _totalLength - x, _centerOfMass[1] / _totalLength - y),\n                        startAngle, _totalLength, startCurvature, endCurvature);\n}\n\nMatrix4d ClothoidFitter::_getLhs(double x)\n{\n    double xp[8] = {1, x, 0, 0, 0, 0, 0, 0 }; //powers of totalLength\n    for(int i = 2; i < 8; ++i)\n        xp[i] = xp[i - 1] * x;\n\n    Matrix4d out;\n\n    for(int i = 0; i < 4; ++i) for(int j = 0; j < 4; ++j)\n    {\n        int p = 7 - i - j;\n        out(i, j) = (2. / double(p)) * xp[p];\n    }\n\n    return out;\n}\n\nVector4d ClothoidFitter::_getRhs(double x, double y, double z)\n{\n    double xp[6] = {1, x, 0, 0, 0, 0 }; //powers of totalLength\n    for(int i = 2; i < 6; ++i)\n        xp[i] = xp[i - 1] * x;\n\n    Vector4d out;\n\n    out[0] = (2. / 5.) * y * xp[5] + 0.5 * z * xp[4];\n    out[1] = 0.5 * y * xp[4] + (2. / 3.) * z * xp[3];\n    out[2] = (2. / 3.) * y * xp[3] + z * xp[2];\n    out[3] = y * xp[2] + 2. * z * xp[1];\n\n    return out;\n}\n\nEND_NAMESPACE_Cornu\n", "meta": {"hexsha": "a6d3a405d59ed0d3b29f22d8d8be9c0498267678", "size": 8669, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/Cornucopia/PrimitiveFitUtils.cpp", "max_stars_repo_name": "davepagurek/StrokeStrip", "max_stars_repo_head_hexsha": "c9ae2ebac9ecbc6461952df58a05288bccc571a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2021-05-02T04:22:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T10:07:26.000Z", "max_issues_repo_path": "external/Cornucopia/PrimitiveFitUtils.cpp", "max_issues_repo_name": "davepagurek/StrokeStrip", "max_issues_repo_head_hexsha": "c9ae2ebac9ecbc6461952df58a05288bccc571a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-08-17T03:14:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-17T03:15:35.000Z", "max_forks_repo_path": "external/Cornucopia/PrimitiveFitUtils.cpp", "max_forks_repo_name": "davepagurek/StrokeStrip", "max_forks_repo_head_hexsha": "c9ae2ebac9ecbc6461952df58a05288bccc571a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-05-15T16:04:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T04:34:21.000Z", "avg_line_length": 29.5870307167, "max_line_length": 108, "alphanum_fraction": 0.5521974853, "num_tokens": 2999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5242977371467837}}
{"text": "/*\n * Copyright (c) 2015 Claus Christmann <hcc |\u00e4| gatech.edu>.  \n *   \n * Licensed under the Apache Lice*nse, 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\n#include \"gis.h\"\n\n#include <assert.h>\n#include <cmath>\n#include \"units.hpp\"\n#include \"commoncoordinatesystems.h\"\n#include <boost/concept_check.hpp>\n\n// Anoymous namespace to hide the chosen implementation for ecef2geodetic()\nnamespace {\n\nusing namespace AMG::GIS;  \n  \n\nvoid ecef2geodetic_iterativ(const double& x, const double& y, const double& z, double& lambda, double& phi, double& h)\n{\n  // NOTE: this function is a replication of ecef2geodetic.m from Matlab\n  //\n  //   function [phi, lambda, h] = ecef2geodetic(x, y, z, ellipsoid)\n  //   %ECEF2GEODETIC Convert geocentric (ECEF) to geodetic coordinates\n  //   %\n  //   %   [PHI, LAMBDA, H] = ECEF2GEODETIC(X, Y, Z, ELLIPSOID) converts point\n  //   %   locations in geocentric Cartesian coordinates, stored in the\n  //   %   coordinate arrays X, Y, Z, to geodetic coordinates PHI (geodetic\n  //   %   latitude in radians), LAMBDA (longitude in radians), and H (height\n  //   %   above the ellipsoid). The geodetic coordinates refer to the\n  //   %   reference ellipsoid specified by ELLIPSOID (a row vector with the\n  //   %   form [semimajor axis, eccentricity]). X, Y, and Z must use the same\n  //   %   units as the semimajor axis;  H will also be expressed in these\n  //   %   units.  X, Y, and Z must have the same shape; PHI, LAMBDA, and H\n  //   %   will have this shape also.\n  //   %\n  //   %   For a definition of the geocentric system, also known as\n  //   %   Earth-Centered, Earth-Fixed (ECEF), see the help for GEODETIC2ECEF.\n  //   %\n  //   %   See also ECEF2LV, GEODETIC2ECEF, GEOCENTRIC2GEODETICLAT, LV2ECEF.\n  // \n  //   % Copyright 2005-2009 The MathWorks, Inc.\n  //   % $Revision: 1.1.6.4 $  $Date: 2009/04/15 23:34:43 $\n  // \n  //   % Reference\n  //   % ---------\n  //   % Paul R. Wolf and Bon A. Dewitt, \"Elements of Photogrammetry with\n  //   % Applications in GIS,\" 3rd Ed., McGraw-Hill, 2000 (Appendix F-3).\n  // \n  //   % Implementation Notes from Rob Comer\n  //   % -----------------------------------\n  //   % The implementation below follows Wolf and DeWitt quite literally,\n  //   % with a few important exceptions required to ensure good numerical\n  //   % behavior:\n  //   %\n  //   % 1) I used ATAN2 rather than ATAN in the formulas for beta and phi.  This\n  //   %    avoids division by zero (or a very small number) for points on (or\n  //   %    near) the Z-axis.\n  //   %\n  //   % 2) Likewise, I used ATAN2 instead of ATAN when computing beta from phi\n  //   %    (conversion from geodetic to parametric latitude), ensuring\n  //   %    stability even for points at very high latitudes.\n  //   %\n  //   % 3) Finally, I avoided dividing by cos(phi) -- also problematic at high\n  //   %    latitudes -- in the calculation of h, the height above the ellipsoid.\n  //   %    Wold and Dewitt give\n  //   %\n  //   %                   h = sqrt(X^2 + Y^2)/cos(phi) - N.\n  //   %\n  //   %    The trick is to notice an alternative formula that involves division\n  //   %    by sin(phi) instead of cos(phi), then take a linear combination of the\n  //   %    two formulas weighted by cos(phi)^2 and sin(phi)^2, respectively. This\n  //   %    eliminates all divisions and, because of the identity cos(phi)^2 +\n  //   %    sin(phi)^2 = 1 and the fact that both formulas give the same h, the\n  //   %    linear combination is also equal to h.\n  //   %\n  //   %    To obtain the alternative formula, we simply rearrange\n  //   %\n  //   %                   Z = [N(1 - e^2) + h]sin(phi)\n  //   %    into\n  //   %                   h = Z/sin(phi) - N(1 - e^2).\n  //   %\n  //   %    The linear combination is thus\n  //   %\n  //   %        h = (sqrt(X^2 + Y^2)/cos(phi) - N) cos^2(phi)\n  //   %            + (Z/sin(phi) - N(1 - e^2))sin^2(phi)\n  //   %\n  //   %    which simplifies to\n  //   %\n  //   %      h = sqrt(X^2 + Y^2)cos(phi) + Zsin(phi) - N(1 - e^2sin^2(phi)).\n  //   %\n  //   %    From here it's not hard to verify that along the Z-axis we have\n  //   %    h = Z - b and in the equatorial plane we have h = sqrt(X^2 + Y^2) - a.\n  \n  // % Ellipsoid constants\n  // WGS84::a   % Semimajor axis\n  // WGS84::e2  % Square of first eccentricity\n  // WGS84::ep2 % Square of second eccentricity\n  // WGS84::f   % Flattening\n  // WGS84::b   % Semiminor axis\n\n\n\n  // Longitude\n  lambda = std::atan2(y,x);\n\n  // Distance from the z-axis\n  double rho = std::hypot(x,y);\n    \n  // Bowring's formula for initial parametric (beta) and geodetic (phi) latitudes\n  double beta = std::atan2(z, (1 - WGS84::f) * rho);\n  phi = std::atan2(z   + WGS84::b*WGS84::ep2 *std::pow(std::sin(beta),3) ,\n                   rho - WGS84::a*WGS84::e2  *std::pow(std::cos(beta),3) );\n\n  // Fixed-point iteration with Bowring's formula\n  // (typically converges within two or three iterations)\n  double betaNew = std::atan2((1 - WGS84::f)*std::sin(phi), std::cos(phi));\n  int count = 0;\n  while( beta != betaNew && count < 10 )\n  {\n    beta = betaNew;\n    phi = std::atan2(z   + WGS84::b * WGS84::ep2 * std::pow(std::sin(beta),3) ,\n                     rho - WGS84::a * WGS84::e2  * std::pow(std::cos(beta),3) );\n    betaNew = std::atan2((1 - WGS84::f)*std::sin(phi), std::cos(phi));\n    ++count;\n  }\n\n  // Calculate ellipsoidal height from the final value for latitude\n  double sinphi = std::sin(phi);\n  double N = WGS84::a / std::sqrt(1.0 - WGS84::e2 * sinphi*sinphi);\n  h = rho * std::cos(phi) + (z + WGS84::e2 * N * sinphi) * sinphi - N;\n\n}\n\n\nvoid ecef2geodetic_closedForm(const double& x, const double& y, const double& z, double& lambda, double& phi, double& h)\n{\n  //NOTE: This method is taken from\n  //  \n  // Markku Heikkinen, \"Geschlossene Formeln zur Berechnung r\u00e4umlicher \n  // geod\u00e4tischer Koordinaten aud rechtwinkeligen Koordinaten\", Zeitschrift f\u00fcr \n  // Vermessungswesen, Vol. 107, 5/1982, p. 207--2011, in German\n  \n  //NOTE: This method is only valid if the radius r3 = sqrt(x*x+y*y+z*z) is \n  // larger than ~43 km. (See the above mentioned paper for the related details.)\n  assert( std::sqrt(x*x+y*y+z*z) > 45e3 );\n  \n  //\n  // Ellipsoidal constants\n  //\n  long double a = WGS84::a;\n  long double b = WGS84::b;\n  long double e2 = WGS84::e2; // pos. definite\n  long double ep2 = WGS84::ep2;// pos. definite\n  long double E2 = e2*a*a; // alternative E2 = a*a-b*b; // pos. definite\n\n  //\n  // intermediaries\n  //\n  \n  long double r  = std::sqrt( (x*x)+(y*y) );\n\n  if( 0.0L == r ) // on N-S axis.\n  { \n    lambda = 0.0;\n   \n    phi =  static_cast<double>(M_PI_2l);\n    if( z < 0 )\n    { phi *= -1.0; }\n   \n    h = std::abs(z)-b;\n    return;\n  }\n  \n  long double F  = 54.0L*(b*b)*(z*z); // pos. definite\n  long double G  = (r*r)+(1.0L-e2)*(z*z)-e2*E2; // pos. definite\n  long double c  = (e2*e2)*F*(r*r)/(G*G*G)  ;\n  long double s  = std::pow( 1.0L+c+std::sqrt((c*c)+2.0L*c) ,(1.0L/3.0L)); // 3rd root \n  long double P  = F/( 3.0L*(1.0L+s+1.0L/s)*(1.0L+s+1.0L/s)*(G*G) );\n  long double Q  = std::sqrt( 1.0L+2.0L*(e2*e2)*P );\n  long double r0 = ((P*e2*r)/(1.0L+Q))\n    +std::sqrt( 0.5L*(a*a)*(1.0L+1.0L/Q)-(P*(1.0L-e2)*(z*z))/(Q*(1.0L+Q))-0.5L*P*(r*r) );\n  long double U  = std::sqrt( (z*z)+(r-e2*r0)*(r-e2*r0) );\n  long double V  = std::sqrt( (r-e2*r0)*(r-e2*r0)+(1.0L-e2)*(z*z) );\n  long double z0 = ((b*b)*z)/(a*V);\n\n  //NOTE: I introduced these 3 variables in order to save some typing\n  long double W  = z+ep2*z0; \n  long double sinphi = W/std::sqrt( (r*r)+(W*W) );\n  long double cosphi = r/std::sqrt( (r*r)+(W*W) );\n  \n  //\n  // final computations\n  //\n  h = double( U*(1.0L-(b*b)/(a*V)) );\n  \n  //NOTE: as both, sinphi and cosphi are given in the algorithm, I decided to \n  // invert the lower value, hoping that the higher slope in that region gives\n  // a better numerical result. Obviously, this is just a gutt feel, no real\n  // scienece involved... \n  if( sinphi<=cosphi )\n  {\n    phi = double(std::asin(sinphi));\n  }\n  else\n  {\n    phi = double(std::acos(cosphi));\n  }\n\n  //NOTE: same argument as above... Claus\n  if( x<=y )\n  {\n    lambda = double(std::acos(x/r));\n  }\n  else\n  {\n    lambda = double(std::asin(y/r));\n  }\n  \n}\n\n}\n\nnamespace AMG { namespace GIS {\n  \nstd::string convertToString ( const CompassPoint& cp )\n{\n  using CP=AMG::GIS::CompassPoint;\n  switch( cp )\n  {\n    case CP::N    : return \"N\"   ; //\"North\";\n    case CP::NbE  : return \"NbE\" ; //\"North by East\";\n    case CP::NNE  : return \"NNE\" ; //\"North-northeast\";\n    case CP::NEbN : return \"NEbN\"; //\"Northeast by North\";\n    case CP::NE   : return \"NE\"  ; //\"Northeast\";\n    case CP::NEbE : return \"NEbE\"; //\"Northeast by East\";\n    case CP::ENE  : return \"ENE\" ; //\"East-northeast\";\n    case CP::EbN  : return \"EbN\" ; //\"East by North\";\n    case CP::E    : return \"E\"   ; //\"East\";\n    case CP::EbS  : return \"EbS\" ; //\"South\";\n    case CP::ESE  : return \"ESE\" ; //\"East-southeast\";\n    case CP::SEbE : return \"SEbE\"; //\"Southeast by East\";\n    case CP::SE   : return \"SE\"  ; //\"Southeast\";\n    case CP::SEbS : return \"SEbS\"; //\"Southeast by South\";\n    case CP::SSE  : return \"SSE\" ; //\"South-southeast\";\n    case CP::SbE  : return \"SbE\" ; //\"South by East\";\n    case CP::S    : return \"S\"   ; //\"South\";\n    case CP::SbW  : return \"SbW\" ; //\"South by West\";\n    case CP::SSW  : return \"SSW\" ; //\"South-southwest\";\n    case CP::SWbS : return \"SWbS\"; //\"Southwest by South\";\n    case CP::SW   : return \"SW\"  ; //\"Southwest\";\n    case CP::SWbW : return \"SWbW\"; //\"Southwest by West\";\n    case CP::WSW  : return \"WSW\" ; //\"West-southwest\";\n    case CP::WbS  : return \"WbS\" ; //\"West by South\";\n    case CP::W    : return \"W\"   ; //\"West\";\n    case CP::WbN  : return \"WbN\" ; //\"West by North\";\n    case CP::WNW  : return \"WNW\" ; //\"West-northwest\";\n    case CP::NWbW : return \"NWbW\"; //\"Northwest by West\";\n    case CP::NW   : return \"NW\"  ; //\"Northwest\";\n    case CP::NWbN : return \"NWbN\"; //\"Northwest by North\";\n    case CP::NNW  : return \"NNW\" ; //\"North-norhtwest\";\n    case CP::NbW  : return \"NbW\" ; //\"North by West\";\n    \n    default: return std::string();\n  }\n  return std::string();\n}\n\ndouble ensureHeading ( const double& heading_deg )\n{\n // check for circular multiplicity, i.e. reduce heading to within one circle\n double hdg_deg = std::fmod(heading_deg,360.0);\n \n if( hdg_deg > 180.0 )\n {hdg_deg -=360.0;}\n else if( hdg_deg <= -180.0 )\n {hdg_deg += 360; }\n \n return hdg_deg;\n}\n\ndouble opposingHeading ( const double& heading_deg )\n{\n  return ensureHeading(heading_deg+180.0);\n}\n  \ndouble compassPointToHeading ( CompassPoint const & cp )\n{\n  double center_deg = static_cast<double>(cp)/100;\n  return ensureHeading(center_deg);\n}\n\nbool isInLeftHalfCircle ( const double& reference_deg, const double& heading_deg )\n{\n  double ref_deg  = ensureHeading(reference_deg );\n  double test_deg = ensureHeading(heading_deg);\n  \n  //NOTE: remember: left  is [ref-180,ref), i.e. the opposite heading is in \n  // both, the left and the right half circle!\n  \n  if( ref_deg == test_deg )\n  { return false; }\n  \n  if( ref_deg == 0.0 )\n  { return test_deg < 0  or test_deg == 180.0; } \n  \n  if( ref_deg > 0.0 )\n  { return  (ref_deg-180.0)<=test_deg && test_deg < ref_deg; } \n  \n  if( ref_deg < 0.0 )\n  { return !( ref_deg<test_deg && test_deg <(ref_deg+180.0) ) ; }\n  //NOTE: ---------------------------------^\n  // This is not a \"<=\" as we defined left as [ref-180,ref) !\n  \n  if( test_deg == opposingHeading (ref_deg) )\n  { return true; }\n  \n    \n  // catch all that shouldn't be reached.\n  return false;\n}\n\nbool isInRightHalfCircle ( const double& reference_deg, const double& heading_deg )\n{\n  double ref_deg  = ensureHeading(reference_deg );\n  double test_deg = ensureHeading(heading_deg);\n  \n  //NOTE: remember: right  is (ref,ref+180], i.e. the opposite heading is in \n  // both, the left and the right half circle!\n  \n  if( ref_deg == test_deg )\n  { return false; }\n  \n  if( ref_deg == 0.0 )\n  { return test_deg > 0  or test_deg == 180.0; } \n  \n  if( ref_deg > 0.0 )\n  { return  !( (ref_deg-180.0)<test_deg && test_deg < ref_deg ); } \n  //NOTE: --------------------^\n  // This is not a \"<=\" as we defined right as (ref,ref+180] !\n  \n  if( ref_deg < 0.0 )\n  { return ref_deg<test_deg && test_deg <=(ref_deg+180.0) ; }\n  \n  if( test_deg == opposingHeading (ref_deg) )\n  { return true; }\n  \n  // catch all that shouldn't be reached.\n  return false;\n}\n  \nCompassPoint headingToCompassPoint ( const double& heading_deg, int resolution )\n{\n  if( resolution != 4 or resolution != 8 /*or resolution != 16*/ )\n  { resolution = 8; }\n  \n  \n  double hdg_deg = ensureHeading(heading_deg);\n  \n  using CP=AMG::GIS::CompassPoint;  \n  CP cp = CP::N;\n  \n  auto inbetween = [hdg_deg](CP left,CP right)\n  { return compassPointToHeading(left)<hdg_deg && hdg_deg <= compassPointToHeading(right); };\n\n  if( inbetween(CP::SW, CP ::NW ) )\n  { cp = CP::W; \n     \n    if( resolution == 4 ){ /*break;*/ }\n    else if( inbetween(CP::SSW, CP::WSW) )\n    { cp = CP::SW; }\n    else if( inbetween(CP::WNW,CP::NNW) )\n    { cp = CP::NW; }\n      \n  }\n  else if( inbetween(CP::NW, CP::NE) )\n  { cp = CP::N;\n    \n    if( resolution == 4 ){ /*break;*/ }\n    else if( inbetween(CP::WNW,CP::NNW) )\n    { cp = CP::NW; }\n    else if( inbetween(CP::NNE,CP::ENE) )\n    { cp = CP::NE; }\n  \n  }\n  else if( inbetween(CP::NE,CP::SE) )\n  { cp = CP::E;\n    \n    if( resolution == 4 ){ /*break;*/ }\n    else if( inbetween(CP::NNE,CP::ENE) )\n    { cp = CP::NE; }\n    else if( inbetween(CP::ESE,CP::SSE) )\n    { cp = CP::SE; }\n  \n  }\n  else\n  { cp = CP::S;\n    \n    if( resolution == 4 ){ /*break;*/ }\n    else if( inbetween(CP::ESE,CP::SSE) )\n    { cp = CP::SE; }\n    else if( inbetween(CP::SSW,CP::WSW) )\n    { cp = CP::SW; }\n  \n  }  \n  \n    \n  return cp; \n}\n\nstd::string geodeticPositionString ( const AMG::Vector& position )\n{\n  CoordinateTupel ecefCoords = position.absoluteCoordsIn( AMG::CoSy::getECEF() );\n                  \n  double lat_rad,lon_rad,alt_m;\n  GIS::ecef2geodetic(ecefCoords[0],ecefCoords[1],ecefCoords[2],\n                          lon_rad,lat_rad,alt_m );\n\n  CompassPoint northSouth = CompassPoint::N;\n  if ( lat_rad < 0)\n  { // Southern hemisphere\n    northSouth = CompassPoint::S;\n          lat_rad *= -1.0;\n  }\n\n  CompassPoint eastWest = CompassPoint::E;\n  if ( lon_rad < 0)\n  { // Western hemisphere\n    eastWest = CompassPoint::W;\n          lon_rad *= -1.0;\n  }\n   \n  std::ostringstream stream;\n  stream << AMG::Units::radian2degree( lat_rad ) << \"\u00b0\" << convertToString(northSouth) << \", \"\n         << AMG::Units::radian2degree( lon_rad ) << \"\u00b0\" << convertToString(eastWest)   << \", \"\n         << alt_m << \" m WGS84\";\n  return stream.str();\n}\n\n\n\nvoid ecef2geodetic(const double& x, const double& y, const double& z, double& lambda, double& phi, double& h)\n{\n  ecef2geodetic_iterativ(x,y,z,lambda,phi,h);\n//   ecef2geodetic_closedForm(x,y,z,lambda,phi,h); // forward call to closed form algorithm.\n}\n  \n\n\nvoid geodetic2ecef(const double& lambda, const double& phi, const double& h, double& x, double& y, double& z)\n{\n  // NOTE: this function is a replication of ecef2geodetic.m from Matlab\n  //\n  //   function [x, y, z] = geodetic2ecef(phi, lambda, h, ellipsoid)\n  //   %GEODETIC2ECEF Convert geodetic to geocentric (ECEF) coordinates\n  //   %\n  //   %   [X, Y, Z] = GEODETIC2ECEF(PHI, LAMBDA, H, ELLIPSOID) converts geodetic\n  //   %   point locations specified by the coordinate arrays PHI (geodetic\n  //   %   latitude in radians), LAMBDA (longitude in radians), and H (ellipsoidal\n  //   %   height) to geocentric Cartesian coordinates X, Y, and Z.  The geodetic\n  //   %   coordinates refer to the reference ellipsoid specified by ELLIPSOID (a\n  //   %   row vector with the form [semimajor axis, eccentricity]).  H must use\n  //   %   the same units as the semimajor axis;  X, Y, and Z will be expressed in\n  //   %   these units also.\n  //   %\n  //   %   The geocentric Cartesian coordinate system is fixed with respect to the\n  //   %   Earth, with its origin at the center of the ellipsoid and its X-, Y-,\n  //   %   and Z-axes intersecting the surface at the following points:\n  //   %\n  //   %                PHI  LAMBDA\n  //   %      X-axis:    0     0      (Equator at the Prime Meridian)\n  //   %      Y-axis:    0   pi/2     (Equator at 90-degrees East)\n  //   %      Z-axis:  pi/2    0      (North Pole)\n  //   %\n  //   %   A common synonym is Earth-Centered, Earth-Fixed coordinates, or ECEF.\n  //   %\n  //   %   See also ECEF2GEODETIC, ECEF2LV, GEODETIC2GEOCENTRICLAT, LV2ECEF.\n  //   \n  //   % Copyright 2004-2009 The MathWorks, Inc.\n  //   % $Revision: 1.1.6.4 $  $Date: 2009/04/15 23:34:46 $\n  //   \n  //   % Reference\n  //   % ---------\n  //   % Paul R. Wolf and Bon A. Dewitt, \"Elements of Photogrammetry with\n  //   % Applications in GIS,\" 3rd Ed., McGraw-Hill, 2000 (Appendix F-3).\n  \n  // % Ellipsoid constants\n  // WGS84::a   % Semimajor axis\n  // WGS84::e2  % Square of first eccentricity\n  // WGS84::ep2 % Square of second eccentricity\n  // WGS84::f   % Flattening\n  // WGS84::b   % Semiminor axis\n  \n  double sinphi = std::sin(phi);\n  double cosphi = std::cos(phi);\n  \n  double N  = WGS84::a / std::sqrt(1.0 - WGS84::e2 * sinphi*sinphi);\n//   double N  = WGS84::e2 ;\n//   N *= sinphi;\n//   N *= sinphi;\n//   N = 1.0 - N;\n//   N = std::sqrt(N);\n//   N = WGS84::a / N;\n  \n  x = (N + h) * cosphi * std::cos(lambda);\n  y = (N + h) * cosphi * std::sin(lambda);\n  z = (N*(1 - WGS84::e2) + h) * sinphi;\n}\n\n\nvoid GudermannFunction(const double& yGudermann, double& phiGeocentric)\n{\n  phiGeocentric = std::asin( std::tanh( yGudermann ) );\n}\n\n\n\nvoid InverseGudermannFunction(const double& phiGeocentric, double& yGudermann)\n{\n  assert( (-M_PI_2l < phiGeocentric) && (phiGeocentric < M_PI_2l) );\n  yGudermann = std::asinh( std::tan( phiGeocentric ) );\n}\n\n\n\nvoid geocentric2mercator(const double& lambdaGeocentric,\n                                    const double& phiGeocentric,\n                                    const double& hGeocentric, \n                                          double& xGudermann, \n                                          double& yGudermann, \n                                          double& zGudermann)\n{\n  // longitude\n  xGudermann = lambdaGeocentric;\n  // latitude\n  InverseGudermannFunction(phiGeocentric,yGudermann);\n  // elevation\n  zGudermann = hGeocentric;\n}\n\nvoid mercator2geocentric(const double& xGudermann,\n                                    const double& yGudermann,\n                                    const double& zGudermann, \n                                          double& lambdaGeocentric,\n                                          double& phiGeocentric,\n                                          double& hGeocentric)\n{\n  // longitude\n  lambdaGeocentric = xGudermann;\n  // latitude\n  GudermannFunction(yGudermann,phiGeocentric);\n  // elevation\n  hGeocentric=zGudermann;  \n}\n\n\nvoid cartesian2spherical(const double& x,\n                                   const double& y,\n                                   const double& z,\n                                         double& azimuth,\n                                         double& elevation,\n                                         double& distance)\n{\n  double xy = std::hypot(x,y); // length of the projection in the xy-plane\n  distance  = std::hypot(z,xy);\n  azimuth   = std::atan2(y,x);\n  elevation = std::atan2(z,xy);\n}\n\n\nvoid spherical2cartesian(const double& azimuth,\n                                   const double& elevation,\n                                   const double& distance,\n                                         double& x,\n                                         double& y,\n                                         double& z)\n{\n  assert(-M_PIl <= azimuth && azimuth <= M_PIl);\n  assert(-M_PI_2l <= elevation && elevation <= M_PI_2l);\n  assert( 0.0 <= distance );\n  \n  \n  double xy = std::cos(elevation) * distance; // length of the projection in the xy-plane\n  z = std::sin(elevation) * distance;\n  y = std::sin(azimuth) * xy;\n  x = std::cos(azimuth) * xy;\n}\n\nvoid ecef2geocentric(const double& x, const double& y, const double& z, double& lambdaGeocentric, double& phiGeocentric, double& hGeocentric)\n{\n  // treat it as a regular cartesian2spherical conversion\n  double radialDistance(0.0);\n  cartesian2spherical(x,y,z,lambdaGeocentric,phiGeocentric,radialDistance);\n  \n  // subtract the raddius of the referecen sphere from the distance\n  hGeocentric = radialDistance-WGS84::a;\n}\n\n\nvoid geocentric2ecef(const double& lambdaGeocentric, const double& phiGeocentric, const double& hGeocentric, double& x, double& y, double& z)\n{\n  double radialDistance = hGeocentric+WGS84::a;\n  spherical2cartesian(lambdaGeocentric,phiGeocentric,radialDistance,x,y,z);\n}\n\n\nvoid geocentric2geodetic(const double& lambdaGeocentric, const double& phiGeocentric, const double& hGeocentric, double& lambda, double& phi, double& h)\n{\n double xTemp,yTemp,zTemp;\n \n geocentric2ecef(lambdaGeocentric,phiGeocentric,hGeocentric,xTemp,yTemp,zTemp);\n ecef2geodetic(xTemp,yTemp,zTemp,lambda,phi,h);\n}\n\n\nvoid geodetic2geocentric(const double& lambda, const double& phi, const double& h, double& lambdaGeocentric, double& phiGeocentric, double& hGeocentric)\n{\n  double xTemp,yTemp,zTemp;\n \n  geodetic2ecef(lambda, phi, h, xTemp, yTemp, zTemp);\n  ecef2geocentric(xTemp,yTemp,zTemp,lambdaGeocentric,phiGeocentric,hGeocentric);\n}\n\n\nvoid mercator2ecef(const double& xGudermann, const double& yGudermann, const double& zGudermann, double& x, double& y, double& z)\n{\n  double lambdaGeocentric, phiGeocentric, hGeocentric;\n  \n  mercator2geocentric(xGudermann,yGudermann,zGudermann,lambdaGeocentric,phiGeocentric,hGeocentric);\n  geocentric2ecef(lambdaGeocentric,phiGeocentric,hGeocentric,x,y,z);\n  \n}\n\nvoid ecef2mercator(const double& x, const double& y, const double& z, double& xGudermann, double& yGudermann, double& zGudermann)\n{\n  double lambdaGeocentric, phiGeocentric, hGeocentric;\n  \n  ecef2geocentric(x,y,z,lambdaGeocentric,phiGeocentric,hGeocentric);\n  geocentric2mercator(lambdaGeocentric,phiGeocentric,hGeocentric,xGudermann,yGudermann,zGudermann);\n}\n\n\nvoid mercator2geodetic(const double& xGudermann, const double& yGudermann, const double& zGudermann, double& lambda, double& phi, double& h)\n{\n  double lambdaGeocentric, phiGeocentric, hGeocentric;\n  \n  mercator2geocentric(xGudermann,yGudermann,zGudermann,lambdaGeocentric,phiGeocentric,hGeocentric);\n  geocentric2geodetic(lambdaGeocentric,phiGeocentric,hGeocentric,lambda,phi,h);\n\n}\n\nvoid geodetic2mercator(const double& lambda, const double& phi, const double& h, double& xGudermann, double& yGudermann, double& zGudermann)\n{\n  double lambdaGeocentric, phiGeocentric, hGeocentric;\n  \n  geodetic2geocentric(lambda,phi,h,lambdaGeocentric,phiGeocentric,hGeocentric);\n  geocentric2mercator(lambdaGeocentric,phiGeocentric,hGeocentric,xGudermann,yGudermann,zGudermann);\n}\n\n\n\n\n} // end namespace GIS\n} // end namespace AMG\n\n\n\n\n\nstd::ostream& operator<< ( std::ostream& out, const CompassPoint& cp )\n{\n  return out << AMG::GIS::convertToString(cp);\n}\n\n", "meta": {"hexsha": "57760eb85878ec7dd9b8f5bf813acb169dc8334a", "size": 23465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gis.cpp", "max_stars_repo_name": "mvsframework/amg", "max_stars_repo_head_hexsha": "fe4d39ccb60e1537a4c95a2a7ecfc88d4d24593a", "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": "gis.cpp", "max_issues_repo_name": "mvsframework/amg", "max_issues_repo_head_hexsha": "fe4d39ccb60e1537a4c95a2a7ecfc88d4d24593a", "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": "gis.cpp", "max_forks_repo_name": "mvsframework/amg", "max_forks_repo_head_hexsha": "fe4d39ccb60e1537a4c95a2a7ecfc88d4d24593a", "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.0566037736, "max_line_length": 152, "alphanum_fraction": 0.607713616, "num_tokens": 7502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5242977305195103}}
{"text": "/*=============================================================================\n\n  NifTK: A software platform for medical image computing.\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 <math.h>\n#include <float.h>\n#include <iomanip>\n\n#include <niftkConversionUtils.h>\n#include <niftkCommandLineParser.h>\n#include <itkCommandLineHelper.h>\n\n#include <itkCommand.h>\n#include <itkSimpleFilterWatcher.h>\n#include <itkImageRegionIterator.h>\n#include <itkImageRegionConstIterator.h>\n#include <itkBasicImageFeaturesImageFilter.h>\n#include <itkImageFileReader.h>\n#include <itkImageFileWriter.h>\n#include <itkNifTKImageIOFactory.h>\n#include <itkRescaleIntensityImageFilter.h>\n#include <itkImage.h>\n#include <itkUnaryFunctorImageFilter.h>\n#include <itkScalarToRGBBIFPixelFunctor.h>\n#include <itkScalarToRGBOBIFPixelFunctor.h>\n#if 0\n#include <itkMaskImageFilter.h>\n#endif\n#include <itkResampleImageFilter.h>\n#include <itkLinearInterpolateImageFunction.h>\n#include <itkIdentityTransform.h>\n#include <itkSliceBySliceImageFilterPatched.h>\n\n#include <boost/filesystem.hpp>\n\nstruct niftk::CommandLineArgumentDescription clArgList[] = {\n\n  {OPT_SWITCH, \"st\", NULL, \"Perform single threaded execution [multi-threaded].\"},\n  {OPT_SWITCH, \"resample\", NULL, \"Speed up the execution by resampling the image.\"},\n\n  {OPT_SWITCH, \"orientate\", NULL, \"Calculate orientated BIFs [no].\"},\n  {OPT_SWITCH, \"n72\", NULL, \"Calculate orientations in one degree increments [45degs].\"},\n\n  {OPT_SWITCH, \"vflip\", NULL, \"Flip the orientation vertically (e.g. for PA vs AP views).\"},\n  {OPT_SWITCH, \"hflip\", NULL, \"Flip the orientation horizontally (e.g. for ML vs LM views).\"},\n\n  {OPT_SWITCH, \"noSlope\", NULL, \"Ignore slopes, i.e. only classify as 2nd order.\"},\n\n  {OPT_INT,    \"slice\", \"dimension\",   \"The slice direction to process: 0:'x', 1:'y', 2:'z' [0].\"},\n\n  {OPT_DOUBLEx2, \"origin\", \"ox,oy\", \"Orientate relative to this origin in mm (0,0 = corner of the image).\"},\n\n  {OPT_FLOAT, \"sigma\", \"value\", \"The Guassian std. dev. in mm at which to compute the BIFs [1.0].\"},\n  {OPT_INT,   \"nscales\", \"n\",   \"The number of scales to process [1].\"},\n  {OPT_FLOAT, \"fscales\", \"value\", \"The multiplicative factor between scales [2.0].\"},\n\n  {OPT_FLOAT, \"e\", \"epsilon\", \"The noise suppression parameter [1e-05].\"},\n\n  {OPT_STRING, \"u2D\", \"filename\", \"Local reference orientation in 'x'.\"},\n  {OPT_STRING, \"v2D\", \"filename\", \"Local reference orientation in 'y'.\"},\n\n#if 0\n  {OPT_STRING, \"mask\", \"filename\", \"Only compute BIFs where the mask image is non-zero.\"},\n#endif\n\n  {OPT_FLOAT, \"t\",    \"threshold\", \"Only compute BIFs where the input image is greater than <threshold>.\"},\n#if 0\n  {OPT_STRING, \"om\", \"filename\", \"Write the computed mask image to a file.\"},\n#endif\n\n  {OPT_STRING, \"oS00\", \"filename\", \"Save the zero order smoothed image to a file.\"},\n  {OPT_STRING, \"oS10\", \"filename\", \"Save the first derivative in 'x' to a file.\"},\n  {OPT_STRING, \"oS01\", \"filename\", \"Save the first derivative in 'y' to a file.\"},\n  {OPT_STRING, \"oS11\", \"filename\", \"Save the second derivative in 'xy' to a file.\"},\n  {OPT_STRING, \"oS20\", \"filename\", \"Save the second derivative in 'xx' to a file.\"},\n  {OPT_STRING, \"oS02\", \"filename\", \"Save the second derivative in 'yy' to a file.\"},\n\n  {OPT_STRING, \"oFlat\", \"filename\", \"Save the flatness response to a file.\"},\n  {OPT_STRING, \"oSlope\", \"filename\", \"Save the slope-like response to a file.\"},\n  {OPT_STRING, \"oDarkBlob\", \"filename\", \"Save the dark blob response to a file.\"},\n  {OPT_STRING, \"oLightBlob\", \"filename\", \"Save the light blob response to a file.\"},\n  {OPT_STRING, \"oDarkLine\", \"filename\", \"Save the dark line response to a file.\"},\n  {OPT_STRING, \"oLightLine\", \"filename\", \"Save the light line response to a file.\"},\n  {OPT_STRING, \"oSaddle\", \"filename\", \"Save the saddlelike response to a file.\"},\n\n  {OPT_STRING, \"oOrient\", \"filename\", \"Save the continuous orientation image to a file.\"},\n  {OPT_STRING, \"oVar\", \"filename\", \"Save the BIF response variance image to a file.\"},\n\n  {OPT_STRING, \"oh\",   \"filename\", \"Write the histogram of BIFs to a file..\"},\n  {OPT_STRING, \"opng\", \"filename\", \"Write the label image as a colour PNG file for display purposes.\"},\n  {OPT_STRING, \"o\",    \"filename\", \"The output label image.\"},\n\n  {OPT_STRING|OPT_LONELY|OPT_REQ, NULL, \"filename\", \"The input image.\"},\n  \n  {OPT_DONE, NULL, NULL, \n   \"Program to compute basic image features for a 3D image.\\n\"\n  }\n};\n\n\nenum {\n  O_SINGLE_THREADED,\n  O_RESAMPLE_IMAGES,\n\n  O_ORIENTATE,\n  O_72_ORIENTATIONS,\n\n  O_FLIP_VERTICALLY,\n  O_FLIP_HORIZONTALLY,\n  \n  O_SECOND_ORDER_ONLY,\n\n  O_SLICE_DIMENSION,\n\n  O_ORIGIN,\n\n  O_SIGMA_IN_MM,\n  O_NUMBER_OF_SCALES,\n  O_SCALE_FACTOR,\n\n  O_EPSILON,\n\n  O_ORIENTATION_INX,\n  O_ORIENTATION_INY,\n\n#if 0\n  O_MASK,\n#endif\n\n  O_THRESHOLD,\n#if 0\n  O_OUTPUT_MASK,\n#endif\n\n  O_OUTPUT_S00,\n  O_OUTPUT_S10,\n  O_OUTPUT_S01,\n  O_OUTPUT_S11,\n  O_OUTPUT_S20,\n  O_OUTPUT_S02,\n\n  O_OUTPUT_FLAT,\n  O_OUTPUT_SLOPE,\n  O_OUTPUT_DARK_BLOB,\n  O_OUTPUT_LIGHT_BLOB,\n  O_OUTPUT_DARK_LINE,\n  O_OUTPUT_LIGHT_LINE,\n  O_OUTPUT_SADDLE,    \n\n  O_OUTPUT_ORIENTATION,\n  O_OUTPUT_VARIANCE,\n\n  O_OUTPUT_HISTOGRAM,\n  O_OUTPUT_COLOUR_IMAGE,\n  O_OUTPUT_IMAGE,\n\n  O_INPUT_IMAGE\n};\n\n\nstd::string AddScaleSuffix( std::string filename, float scale, int nScales ) \n{\n  if ( nScales > 1 ) {\n\n    char strScale[128];\n\n    boost::filesystem::path pathname( filename );\n    boost::filesystem::path ofilename;\n\n    std::string extension = pathname.extension().string();\n    std::string stem = pathname.stem().string();\n\n    if ( extension == std::string( \".gz\" ) ) {\n\n      extension = pathname.stem().extension().string() + extension;\n      stem = pathname.stem().stem().string();\n    }\n\n    sprintf(strScale, \"_%03gmm\", scale);\n\n    ofilename = pathname.parent_path() /\n      boost::filesystem::path( stem + std::string( strScale ) + extension );\n    \n    return ofilename.string();\n  }\n  else \n    return filename;\n}\n\n\nstd::string AddSuffix( std::string filename, std::string suffix ) \n{\n  boost::filesystem::path pathname( filename );\n  boost::filesystem::path ofilename;\n\n  std::string extension = pathname.extension().string();\n  std::string stem = pathname.stem().string();\n\n  if ( extension == std::string( \".gz\" ) ) {\n    \n    extension = pathname.stem().extension().string() + extension;\n    stem = pathname.stem().stem().string();\n  }\n\n  ofilename = pathname.parent_path() /\n    boost::filesystem::path( stem + suffix + extension );\n    \n  return ofilename.string();\n}\n\n\nvoid sliceCallBack(itk::Object* object, const itk::EventObject &, void*)\n{\n  // the same typedefs than in the main function - should be done in a nicer way\n  const unsigned int Dimension = 3;\n  const unsigned int SliceDimension = 2;\n  typedef float PixelType;\n  typedef itk::Image<PixelType, SliceDimension> InputSliceType;\n  typedef itk::Image<PixelType, SliceDimension> OutputSliceType;\n\n  typedef itk::Image< PixelType, Dimension >                   ImageType;\n  typedef itk::SliceBySliceImageFilter< ImageType, ImageType > SliceBySliceFilterType;\n  typedef itk::BasicImageFeaturesImageFilter< InputSliceType, OutputSliceType > BasicImageFeaturesFilterType;\n\n  \n  // real stuff begins here\n  // get the slice by slice filter and the median filter\n  SliceBySliceFilterType *sliceFilter = dynamic_cast< SliceBySliceFilterType * >( object );\n\n#if 0\n  BasicImageFeaturesFilterType *bifFilter = dynamic_cast< BasicImageFeaturesFilterType * >( sliceFilter->GetInputFilter() );\n  bifFilter->Print( std::cout );\n#endif\n\n  std::cout << std::endl << \"Processing slice: \" << sliceFilter->GetSliceIndex() << std::endl;\n}\n\n\nint main( int argc, char *argv[] )\n{\n  itk::NifTKImageIOFactory::Initialize();\n\n  bool flgSingleThreaded;\n  bool flgOrientate;\n  bool flgResampleImages;\n\n  bool flgFlipVertically;\n  bool flgFlipHorizontally;\n\n  bool flgN72;\n\n  bool flgSecondOrderOnly;\n\n  unsigned int iDim;\n  unsigned int sliceDimension = 0;\n\n  int iScale;\n  int nScales = 1;\n\n  float sigmaInMM = 1;\n  float scaleFactor = 2.;\n  float scaleFactorRelativeToInput = 1.;\n\n  float epsilon = 1.0e-05;\n\n  float threshold = 0.;\n\n  double *origin = 0;\n\n  std::string fileOrientationInX;\n  std::string fileOrientationInY;\n\n#if 0\n  std::string fileMask; \n  std::string fileOutputMask;\n#endif\n\n  std::string fileOutputS00;\n  std::string fileOutputS10;\n  std::string fileOutputS01;\n  std::string fileOutputS11;\n  std::string fileOutputS20;\n  std::string fileOutputS02;\n\n  std::string fileOutputFlat;\n  std::string fileOutputSlope;\n  std::string fileOutputDarkBlob;\n  std::string fileOutputLightBlob;\n  std::string fileOutputDarkLine;\n  std::string fileOutputLightLine;\n  std::string fileOutputSaddle;   \n\n  std::string fileOutputOrientation;\n  std::string fileOutputVariance;\n\n  std::string fileOutputHistogram;\n  std::string fileOutputImage;\n  std::string fileOutputColourImage;\n\n  std::string fileInputImage;\n  \n  // Create the command line parser, passing the\n  // 'CommandLineArgumentDescription' structure. The final boolean\n  // parameter indicates whether the command line options should be\n  // printed out as they are parsed.\n\n  niftk::CommandLineParser CommandLineOptions(argc, argv, clArgList, false);\n\n  CommandLineOptions.GetArgument( O_SINGLE_THREADED, flgSingleThreaded );\n  CommandLineOptions.GetArgument( O_RESAMPLE_IMAGES, flgResampleImages );\n\n  CommandLineOptions.GetArgument( O_ORIENTATE, flgOrientate );\n\n  CommandLineOptions.GetArgument( O_72_ORIENTATIONS, flgN72 );\n\n  CommandLineOptions.GetArgument( O_FLIP_VERTICALLY,   flgFlipVertically );\n  CommandLineOptions.GetArgument( O_FLIP_HORIZONTALLY, flgFlipHorizontally );\n\n  CommandLineOptions.GetArgument( O_SECOND_ORDER_ONLY, flgSecondOrderOnly);\n\n  CommandLineOptions.GetArgument( O_SLICE_DIMENSION, sliceDimension);\n\n  CommandLineOptions.GetArgument( O_ORIGIN, origin );\n\n  CommandLineOptions.GetArgument( O_SIGMA_IN_MM, sigmaInMM );\n  CommandLineOptions.GetArgument( O_NUMBER_OF_SCALES, nScales );\n  CommandLineOptions.GetArgument( O_SCALE_FACTOR, scaleFactor );\n\n  CommandLineOptions.GetArgument( O_EPSILON, epsilon );\n\n  CommandLineOptions.GetArgument( O_ORIENTATION_INX, fileOrientationInX );\n  CommandLineOptions.GetArgument( O_ORIENTATION_INY, fileOrientationInY );\n\n  if ( (fileOrientationInX.length() || fileOrientationInY.length()) && origin) {\n\n    std::cerr <<\"Command line options: -u2D and -v2D cannot be used with -origin\";\n    return EXIT_FAILURE;\n  }                \n    \n  if ( (fileOrientationInX.length() || fileOrientationInY.length()) \n       && ! (fileOrientationInX.length() && fileOrientationInY.length()) ) {\n\n    std::cerr <<\"Both command line options: -u2D and -v2D are required\";\n    return EXIT_FAILURE;\n  }                \n    \n#if 0\n  CommandLineOptions.GetArgument( O_MASK, fileMask );\n#endif\n\n  CommandLineOptions.GetArgument( O_THRESHOLD, threshold );\n#if 0\n  CommandLineOptions.GetArgument( O_OUTPUT_MASK, fileOutputMask );\n#endif\n\n  CommandLineOptions.GetArgument( O_OUTPUT_S00, fileOutputS00 );\n  CommandLineOptions.GetArgument( O_OUTPUT_S10, fileOutputS10 );\n  CommandLineOptions.GetArgument( O_OUTPUT_S01, fileOutputS01 );\n  CommandLineOptions.GetArgument( O_OUTPUT_S11, fileOutputS11 );\n  CommandLineOptions.GetArgument( O_OUTPUT_S20, fileOutputS20 );\n  CommandLineOptions.GetArgument( O_OUTPUT_S02, fileOutputS02 );\n\n  CommandLineOptions.GetArgument( O_OUTPUT_FLAT,       fileOutputFlat );\n  CommandLineOptions.GetArgument( O_OUTPUT_SLOPE,      fileOutputSlope );\n  CommandLineOptions.GetArgument( O_OUTPUT_DARK_BLOB,  fileOutputDarkBlob );\n  CommandLineOptions.GetArgument( O_OUTPUT_LIGHT_BLOB, fileOutputLightBlob );\n  CommandLineOptions.GetArgument( O_OUTPUT_DARK_LINE,  fileOutputDarkLine );\n  CommandLineOptions.GetArgument( O_OUTPUT_LIGHT_LINE, fileOutputLightLine );\n  CommandLineOptions.GetArgument( O_OUTPUT_SADDLE,     fileOutputSaddle );\n\n  CommandLineOptions.GetArgument( O_OUTPUT_ORIENTATION, fileOutputOrientation );\n  CommandLineOptions.GetArgument( O_OUTPUT_VARIANCE, fileOutputVariance );\n\n  CommandLineOptions.GetArgument( O_OUTPUT_HISTOGRAM, fileOutputHistogram );\n  CommandLineOptions.GetArgument( O_OUTPUT_COLOUR_IMAGE, fileOutputColourImage );\n  CommandLineOptions.GetArgument( O_OUTPUT_IMAGE, fileOutputImage );\n\n  CommandLineOptions.GetArgument( O_INPUT_IMAGE, fileInputImage );\n\n\n  // Read the input image\n  // ~~~~~~~~~~~~~~~~~~~~\n\n  // Define the dimension of the images\n  const unsigned int ImageDimension = 3;\n  \n  int dims = itk::PeekAtImageDimension(fileInputImage);\n  // Define the dimension of the images\n\n  if (dims != ImageDimension)\n  {\n    std::cerr << \"Unsupported image dimension.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  const unsigned int SliceDimension = 2;\n\n  typedef float InputPixelType;\n  typedef float OutputPixelType;\n\n  typedef itk::Image<InputPixelType, ImageDimension> InputImageType;\n  typedef itk::Image<OutputPixelType, ImageDimension> OutputImageType;\n\n  typedef itk::Image<InputPixelType, SliceDimension> InputSliceType;\n  typedef itk::Image<OutputPixelType, SliceDimension> OutputSliceType;\n\n  typedef itk::ImageFileReader< InputImageType > FileReaderType;\n  typedef itk::ImageFileReader< InputSliceType > SliceReaderType;\n\n  typedef itk::BasicImageFeaturesImageFilter< InputSliceType, OutputSliceType > BasicImageFeaturesFilterType;\n\n#if 0\n  typedef BasicImageFeaturesFilterType::MaskImageType MaskImageType;\n\n  typedef itk::ImageFileReader< MaskImageType > MaskReaderType;\n#endif\n\n  typedef itk::SliceBySliceImageFilter< InputImageType, OutputImageType > SliceBySliceImageFilterType;\n\n\n  FileReaderType::Pointer imageReader = FileReaderType::New();\n\n  imageReader->SetFileName(fileInputImage);\n\n  try\n  { \n    std::cout << \"Reading the input image\" << std::endl;\n    imageReader->Update();\n  }\n  catch (itk::ExceptionObject &ex)\n  { \n    std::cout << ex << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  InputImageType::SizeType    nPixelsInput;\n  InputImageType::SpacingType resnInput;\n  InputImageType::PointType   originInput;\n\n  nPixelsInput = imageReader->GetOutput()->GetLargestPossibleRegion().GetSize();\n  resnInput    = imageReader->GetOutput()->GetSpacing();\n  originInput  = imageReader->GetOutput()->GetOrigin();\n\n\n  // Set up the image resampler\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  InputImageType::SizeType    nPixelsResampled;\n  InputImageType::SpacingType resnResampled;\n  InputImageType::PointType   originResampled;\n\n  InputImageType::Pointer pInputImage;\n  \n  typedef itk::ResampleImageFilter< InputImageType, InputImageType > ResampleFilterType;\n  ResampleFilterType::Pointer resampleInputFilter = 0;\n\n  typedef itk::IdentityTransform< double, ImageDimension > IdentityTransformType;\n  IdentityTransformType::Pointer resampleIdentityTransform = 0;\n\n  typedef itk::LinearInterpolateImageFunction< InputImageType, double > ResampleInterpolatorType;\n  ResampleInterpolatorType::Pointer resampleInterpolator = 0;\n\n  if ( flgResampleImages ) {\n\n    for ( iDim=0; iDim<ImageDimension; iDim++) {\n      \n      nPixelsResampled[iDim] = nPixelsInput[iDim];\n      resnResampled[iDim]    = resnInput[iDim];\n      originResampled[iDim]  = originInput[iDim];\n    }\n\n    resampleInputFilter = ResampleFilterType::New();\n\n    resampleIdentityTransform = IdentityTransformType::New();\n    resampleInterpolator      = ResampleInterpolatorType::New();\n\n    resampleInputFilter->SetInput( imageReader->GetOutput() );\n    resampleInputFilter->SetOutputSpacing( resnResampled );\n    resampleInputFilter->SetOutputOrigin( originResampled );\n    resampleInputFilter->SetSize( nPixelsResampled );\n\n    resampleInputFilter->SetTransform( resampleIdentityTransform );\n    resampleInputFilter->SetInterpolator( resampleInterpolator );\n\n    resampleInputFilter->SetDefaultPixelValue( 0 );\n\n    InputImageType::DirectionType direction;\n    direction.SetIdentity();\n    resampleInputFilter->SetOutputDirection( direction );\n\n    try\n      { \n\tstd::cout << \"Resampling the input image\" << std::endl;\n\tresampleInputFilter->Update();\n      }\n    catch (itk::ExceptionObject &ex)\n      { \n\tstd::cout << ex << std::endl;\n\treturn EXIT_FAILURE;\n      }\n\n    pInputImage = resampleInputFilter->GetOutput();\n\n  }\n  else \n    pInputImage = imageReader->GetOutput();\n\n\n  // Read the local orientation images\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  SliceReaderType::Pointer xOrientReader, yOrientReader;\n\n  if ( (fileOrientationInX.length() > 0) && (fileOrientationInY.length() > 0) ) {\n\n    flgOrientate = true; \n\n    xOrientReader = SliceReaderType::New();\n\n    xOrientReader->SetFileName( fileOrientationInX );\n\n    try\n      { \n\tstd::cout << \"Reading the local orientation in 'x'\" << std::endl;\n\txOrientReader->Update();\n      }\n    catch (itk::ExceptionObject &ex)\n      { \n\tstd::cout << ex << std::endl;\n\treturn EXIT_FAILURE;\n      }\n\n    yOrientReader = SliceReaderType::New();\n\n    yOrientReader->SetFileName( fileOrientationInY );\n\n    try\n      { \n\tstd::cout << \"Reading the local orientation in 'y'\" << std::endl;\n\tyOrientReader->Update();\n      }\n    catch (itk::ExceptionObject &ex)\n      { \n\tstd::cout << ex << std::endl;\n\treturn EXIT_FAILURE;\n      }\n  }\n\n\n  // Read the mask\n  // ~~~~~~~~~~~~~\n\n#if 0\n  MaskImageType::Pointer pMaskImage = 0;\n  MaskReaderType::Pointer maskReader = 0;\n\n  if ( fileMask.length() > 0 ) {\n\n    maskReader = MaskReaderType::New();\n\n    maskReader->SetFileName(fileMask);\n\n    try\n      { \n\tstd::cout << \"Reading the mask image\" << std::endl;\n\tmaskReader->Update();\n      }\n    catch (itk::ExceptionObject &ex)\n      { \n\tstd::cout << ex << std::endl;\n\treturn EXIT_FAILURE;\n      }\n\n    pMaskImage = maskReader->GetOutput();\n  }\n\n  // Or create it by thresholding the input image\n\n  if ( threshold ) {\n\n    if ( ! pMaskImage ) {\n\n      pMaskImage = MaskImageType::New();\n\n      pMaskImage->SetRegions( pInputImage->GetLargestPossibleRegion() );\n      pMaskImage->SetSpacing( pInputImage->GetSpacing() );\n      pMaskImage->SetOrigin( pInputImage->GetOrigin() );\n\n      pMaskImage->Allocate( );\n      pMaskImage->FillBuffer( 1. );\n    }\n\n    typedef itk::ImageRegionConstIterator< InputImageType > InputIteratorType;\n  \n    InputIteratorType itInput( pInputImage, pInputImage->GetLargestPossibleRegion() );\n    \n    InputImageType::IndexType index;\n\n    itInput.GoToBegin();\n\n    while (! itInput.IsAtEnd() ) {\n      \n      index = itInput.GetIndex();\t\n\n      if ( itInput.Get() < threshold )\n\n\tpMaskImage->SetPixel( index, 0.);\n\n      ++itInput;\n    }\n  }\n\n  if ( pMaskImage && ( fileOutputMask.length() > 0 ) ) {\n\n    typedef itk::ImageFileWriter< MaskImageType > FileWriterType;\n\n    FileWriterType::Pointer writer = FileWriterType::New();\n\n    writer->SetFileName( fileOutputMask.c_str() );\n    writer->SetInput( pMaskImage );\n\n    try\n    {\n      std::cout << \"Writing: \" << fileOutputMask.c_str() << std::endl;\n      writer->Update();\n    }\n    catch (itk::ExceptionObject &e)\n    {\n      std::cerr << e << std::endl;\n    }\n  }\n#endif\n\n  // Create the basic image features filter\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  BasicImageFeaturesFilterType::Pointer BIFsFilter = BasicImageFeaturesFilterType::New();\n\n  if (flgSingleThreaded)\n    BIFsFilter->SetSingleThreadedExecution();\n\n  BIFsFilter->SetEpsilon( epsilon );\n\n  if (flgOrientate) {\n    BIFsFilter->CalculateOrientatedBIFs();\n\n    if ( flgN72 )\n      BIFsFilter->SetNumberOfOrientations( 72 );\n  }\n\n  if ( flgFlipVertically )   BIFsFilter->SetFlipVertically();\n  if ( flgFlipHorizontally ) BIFsFilter->SetFlipHorizontally();\n\n  if ( flgSecondOrderOnly ) BIFsFilter->SecondOrderOnly();\n\n  if (origin) {\n    BasicImageFeaturesFilterType::OriginType bifOrigin;\n\n    bifOrigin[0] = origin[0];\n    bifOrigin[1] = origin[1];\n\n    BIFsFilter->SetOrigin( bifOrigin );\n  }\n\n  if ( (fileOrientationInX.length() > 0) && (fileOrientationInY.length() > 0) )\n    BIFsFilter->SetLocalOrientation( xOrientReader->GetOutput(), \n\t\t\t\t     yOrientReader->GetOutput() );\n\n#if 0\n  if ( pMaskImage ) \n    BIFsFilter->SetMask( pMaskImage );\n#endif\n\n\n\n  // Run the filter at each scale\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  for (iScale=0; iScale<nScales; iScale++) {\n    \n    BIFsFilter->SetSigma( sigmaInMM );\n\n    // Create a slice by slice filter\n    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    SliceBySliceImageFilterType::Pointer sliceBySliceFilter = SliceBySliceImageFilterType::New();\n\n    sliceBySliceFilter->SetFilter( BIFsFilter );\n    sliceBySliceFilter->SetDimension( sliceDimension );\n\n    sliceBySliceFilter->SetInput( pInputImage );\n  \n    itk::CStyleCommand::Pointer command = itk::CStyleCommand::New();\n    command->SetCallback( *sliceCallBack );\n  \n    sliceBySliceFilter->AddObserver( itk::IterationEvent(), command );\n\n    itk::SimpleFilterWatcher watcher( sliceBySliceFilter, \"filter\" );\n\n    try\n      {\n\tstd::cout << \"Computing basic image features\";\n\tsliceBySliceFilter->Update();\n      }\n    catch (itk::ExceptionObject &e)\n      {\n\tstd::cerr << e << std::endl;\n      }\n  \n  \n    // Compute a histogram of the BIFs\n    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    if ( fileOutputHistogram.length() > 0 ) {\n\n      unsigned int iBin;\n      unsigned int nBins;\n\n      float nPixels = 0;\n      float *histogram;\n\n      OutputPixelType pixel;\n\n      OutputImageType::Pointer bifs = sliceBySliceFilter->GetOutput();\n\n      if (flgOrientate) {\n\tif ( flgN72 )\n\t  nBins = 183;\n\telse\n\t  nBins = 23;\n      }\n      else\n\tnBins = 7;\n\n      histogram = new float[nBins];\n\n      for (iBin=0; iBin<nBins; iBin++) \n\thistogram[ iBin ] = 0.;\n  \n#if 0\n      if ( pMaskImage ) \n      {\n\n\ttypedef itk::ImageRegionConstIterator< MaskImageType > MaskIteratorType;\n  \n\tMaskImageType::Pointer mask = pMaskImage;\n\n\tMaskIteratorType itMask( pMaskImage, pMaskImage->GetLargestPossibleRegion() );\n    \n\tMaskImageType::IndexType index;\n\n\titMask.GoToBegin();\n\n\twhile (! itMask.IsAtEnd() ) {\n      \n\t  index = itMask.GetIndex();\t\n\n\t  if ( itMask.Get() > 0 ) {\t// if inside the mask\n\n\t    pixel = bifs->GetPixel( index );\n\n\t    if ( (pixel < 0) || (pixel >= nBins) )\n\t      std::cerr << \"BIF value (\"\n\t\t\t<< niftk::ConvertToString(pixel)\n\t\t\t<< \") exceeds histogram range (0 to \"\n\t\t\t<< niftk::ConvertToString(nBins - 1) << \".\";\n\n\t    else {\n\t      nPixels++;\n\t      histogram[ (unsigned int) pixel ]++;\n\t    }\n\t  }\n\n\t  ++itMask;\n\t}\n      }\n      else \n#endif\n      {\n\ttypedef itk::ImageRegionConstIterator< OutputImageType > IteratorType;\n  \n\tIteratorType itBIFs( bifs, bifs->GetLargestPossibleRegion() );\n    \n\titBIFs.GoToBegin();\n\n\twhile (! itBIFs.IsAtEnd() ) {\n      \n\t  pixel = itBIFs.Get();\n\n\t  if ( (pixel < 0) || (pixel >= nBins) )\n\t    std::cerr <<std::string(\"BIF value (\")\n\t\t      << niftk::ConvertToString(pixel)\n\t\t      << \") exceeds histogram range (0 to \"\n\t\t      << niftk::ConvertToString(nBins - 1) + \".\";\n      \n\t  else {\n\t    nPixels++;\n\t    histogram[ (unsigned int) pixel ]++;\n\t  }\n\n\t  ++itBIFs;\n\t}\n\n      }\n\n      std::fstream fout;\n      fout.open( AddScaleSuffix( fileOutputHistogram, sigmaInMM, nScales ).c_str(), std::ios::out );\n\n      if ((! fout) || fout.bad()) {\n\tstd::cerr << \"Failed to open file: \"\n\t\t  << AddScaleSuffix( fileOutputHistogram, sigmaInMM, nScales ) << std::endl;\n\texit(1);\n      }\n  \n      std::cout << \"Writing: \" \n\t\t<< AddScaleSuffix( fileOutputHistogram, sigmaInMM, nScales ) << std::endl;\n      \n      for (iBin=0; iBin<nBins; iBin++) \n\n\tfout << std::setw(6) << iBin << \" \"\n\t     << histogram[ iBin ]/nPixels << std::endl;\n  \n      delete histogram;\n      fout.close();    \n    }\n\t\n\n    // Write the derivatives?\n    // ~~~~~~~~~~~~~~~~~~~~~~\n\n    if ( fileOutputS00.length() != 0 ) \n      BIFsFilter->WriteDerivativeToFile( 0, AddScaleSuffix( fileOutputS00, \n\t\t\t\t\t\t\t    sigmaInMM, nScales ) );\n    if ( fileOutputS10.length() != 0 ) \n      BIFsFilter->WriteDerivativeToFile( 1, AddScaleSuffix( fileOutputS10, \n\t\t\t\t\t\t\t    sigmaInMM, nScales ) );\n    if ( fileOutputS01.length() != 0 ) \n      BIFsFilter->WriteDerivativeToFile( 2, AddScaleSuffix( fileOutputS01, \n\t\t\t\t\t\t\t    sigmaInMM, nScales ) );\n    if ( fileOutputS11.length() != 0 ) \n      BIFsFilter->WriteDerivativeToFile( 3, AddScaleSuffix( fileOutputS11, \n\t\t\t\t\t\t\t    sigmaInMM, nScales ) );\n    if ( fileOutputS20.length() != 0 ) \n      BIFsFilter->WriteDerivativeToFile( 4, AddScaleSuffix( fileOutputS20, \n\t\t\t\t\t\t\t    sigmaInMM, nScales ) );\n    if ( fileOutputS02.length() != 0 ) \n      BIFsFilter->WriteDerivativeToFile( 5, AddScaleSuffix( fileOutputS02, \n\t\t\t\t\t\t\t    sigmaInMM, nScales ) );\n\n\n    // Write the filter responses?\n    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    if ( fileOutputFlat.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 0, AddScaleSuffix( fileOutputFlat, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n    if ( fileOutputSlope.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 1, AddScaleSuffix( fileOutputSlope, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n    if ( fileOutputDarkBlob.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 2, AddScaleSuffix( fileOutputDarkBlob, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n    if ( fileOutputLightBlob.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 3, AddScaleSuffix( fileOutputLightBlob, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n    if ( fileOutputLightLine.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 4, AddScaleSuffix( fileOutputLightLine, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n    if ( fileOutputDarkLine.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 5, AddScaleSuffix( fileOutputDarkLine, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n    if ( fileOutputSaddle.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 6, AddScaleSuffix( fileOutputSaddle, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n\n    // Write the BIF image?\n    // ~~~~~~~~~~~~~~~~~~~~\n\n    if (fileOutputImage.length() != 0) {\n\n      typedef itk::ImageFileWriter< OutputImageType > FileWriterType;\n\n      FileWriterType::Pointer writer = FileWriterType::New();\n\n      writer->SetFileName( AddScaleSuffix( fileOutputImage, sigmaInMM, nScales ) );\n      writer->SetInput( sliceBySliceFilter->GetOutput() );\n\n      try\n\t{\n\t  std::cout << \"Writing: \"\n\t\t    << AddScaleSuffix( fileOutputImage, sigmaInMM, nScales ) << std::endl;\n\t  writer->Update();\n\t}\n      catch (itk::ExceptionObject &e)\n\t{\n\t  std::cerr << e << std::endl;\n\t}\n    }\n\n    // Increase the scale used\n    // ~~~~~~~~~~~~~~~~~~~~~~~\n\n    sigmaInMM *= scaleFactor;    \n    scaleFactorRelativeToInput *= scaleFactor;  \n\n    \n    // Update the resampling?\n    // ~~~~~~~~~~~~~~~~~~~~~~\n\n    if ( flgResampleImages ) {\n      float actualSamplingFactor;\n\n      for ( iDim=0; iDim<ImageDimension; iDim++) {\n\t\n        nPixelsResampled[iDim] = static_cast<InputImageType::SizeType::SizeValueType>(ceil( ((float) nPixelsInput[iDim])\n               / scaleFactorRelativeToInput ));\n\n\tactualSamplingFactor = ((float) nPixelsInput[iDim]) / ((float) nPixelsResampled[iDim] );\n\n\tresnResampled[iDim]    = resnInput[iDim] * actualSamplingFactor;\n\n\toriginResampled[iDim]  = originInput[iDim] + resnResampled[iDim]/2. - resnInput[iDim]/2.;\n      }\n\n      resampleInputFilter->SetOutputSpacing( resnResampled );\n      resampleInputFilter->SetOutputOrigin( originResampled );\n      resampleInputFilter->SetSize( nPixelsResampled );\n\n      resampleInputFilter->SetInput( pInputImage );\n\n      try\n\t{ \n\t  std::cout << \"Resampling the input image by: \" << actualSamplingFactor << std::endl;\n\t  resampleInputFilter->UpdateLargestPossibleRegion();\n\t}\n      catch (itk::ExceptionObject &ex)\n\t{ \n\t  std::cout << ex << std::endl;\n\t  return EXIT_FAILURE;\n\t}\n    }    \n    \n  }\n}\n", "meta": {"hexsha": "e38a5aadadc399ff102fb16b58a2ad5f9bafa799", "size": 27750, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Applications/BasicImageFeatures3D/niftkBasicImageFeatures3D.cxx", "max_stars_repo_name": "NifTK/NifTK", "max_stars_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T13:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T19:17:39.000Z", "max_issues_repo_path": "Applications/BasicImageFeatures3D/niftkBasicImageFeatures3D.cxx", "max_issues_repo_name": "NifTK/NifTK", "max_issues_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/BasicImageFeatures3D/niftkBasicImageFeatures3D.cxx", "max_forks_repo_name": "NifTK/NifTK", "max_forks_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-08-20T07:06:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T07:55:27.000Z", "avg_line_length": 28.8461538462, "max_line_length": 124, "alphanum_fraction": 0.6802522523, "num_tokens": 7440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5242977252914534}}
{"text": "#include <boost/graph/spectrum.hpp>\n#include \"graph_types.hpp\"\n#include <boost/graph/python/graph.hpp>\n#include <boost/python.hpp>\n#include <vector>\n\nnamespace boost { namespace graph { namespace python {\n\ntemplate <typename Graph>\nboost::python::tuple\nspectrum\n  (Graph& g,\n   int first_eigenvector_index,\n   int num_eigenvectors,\n   double rel_tol = 100,\n   double abs_tol = 1000)\n{\n  using std::vector;\n  using boost::python::object;\n\n  typedef typename property_map<Graph, vertex_index_t>::const_type VertexIndexMap;\n  typedef vector_property_map<vertex_index_t, VertexIndexMap> IndexMap;\n  typedef std::vector<double> Vector;\n\n  int N = num_vertices(g);\n  std::vector<Vector> evecs(num_eigenvectors);\n  for (int i = 0; i < num_eigenvectors; i++)\n    evecs[i] = *(new Vector(N));\n  std::vector<double> evals(num_eigenvectors);\n\n  boost::spectrum<Graph, std::vector<Vector> >(g, first_eigenvector_index, num_eigenvectors, evecs, evals, rel_tol, abs_tol);\n\n  boost::python::list *evec;\n\n  boost::python::list eigenvectors;\n  for(int i = 0; i < num_eigenvectors; i++) {\n    evec = new boost::python::list();\n    for (int j = 0; j < N; j++)\n      evec->append(evecs[i][j]);\n    eigenvectors.append(*evec);\n  }\n\n  boost::python::list eigenvalues;\n  for(int i = 0; i < num_eigenvectors; i++) {\n      eigenvalues.append(evals[i]);\n  }\n  \n  return boost::python::make_tuple(eigenvalues, eigenvectors);\n}\n\nvoid export_spectrum()\n{\n  using boost::python::arg;\n  using boost::python::def;\n  using boost::python::object;\n\n  def(\"spectrum\", \n      &spectrum<Graph>,\n      (arg(\"graph\"), \n       arg(\"first_eigenvector_index\") = (int)1,\n       arg(\"num_eigenvectors\") = (int)1,\n       arg(\"rel_tol\") = (double)100,\n       arg(\"abs_tol\") = (double)1000)\n      );\n\n}\n\n} } } // end namespace boost::graph::python\n", "meta": {"hexsha": "7ef12da0f3f914c8f03aedf15464d596c28bee3a", "size": 1800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/spectrum.cpp", "max_stars_repo_name": "erwinvaneijk/bgl-python", "max_stars_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-06-19T08:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T11:09:05.000Z", "max_issues_repo_path": "src/spectrum.cpp", "max_issues_repo_name": "erwinvaneijk/bgl-python", "max_issues_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "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/spectrum.cpp", "max_forks_repo_name": "erwinvaneijk/bgl-python", "max_forks_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-07-13T07:50:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T15:08:03.000Z", "avg_line_length": 26.0869565217, "max_line_length": 125, "alphanum_fraction": 0.6722222222, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5242196799826482}}
{"text": "#include \"isd.h\"\n#include <algorithm>\n#include <boost/math/tools/roots.hpp>\n\nusing boost::math::tools::bisect;\n\nconst double tol = 1e-5;\nconst double epsilon = 1e-5;\nbool quantum = false;\n\nInformationSetDecoding::InformationSetDecoding(unsigned int as, double cr, double w,\n                                               const std::string& m, const std::string& a)\n{\n    if(AlphabetSizeCheck(as))\n        alphabetSize = as;\n    else\n        throw std::invalid_argument(\"Alphabet size needs to be greater or equal to 2.\");\n\n    if(MetricCheck(m))\n        metric = m;\n    else \n        throw std::invalid_argument(\"This metric is not offered. Allowed metrics are hamming and lee.\");\n\n    if(ParamCheck(cr))\n        codeRate = cr;\n    else\n        throw std::invalid_argument(\"Normalized value needs to be in the interval [0,1].\");\n\n    if(ParamCheck(w))\n        weight = w;\n    else\n        throw std::invalid_argument(\"Normalized value needs to be in the interval [0,1].\");\n    \n    if(AlgCheck(a))\n        algorithm = a;\n    else\n        throw std::invalid_argument(\"This algorithm is not offered. Allowed algorithms are prange, dumer and wagner.\");\n\n    space = VectorSpace(metric, alphabetSize);\n    surfaceW = space.SphereSurfArea(weight);\n    if (surfaceW == -1)\n    {\n        throw std::invalid_argument(\"Surface area surfaceW is not found.\");\n    }\n}\n\nInformationSetDecoding& InformationSetDecoding::operator=(const InformationSetDecoding& isd)\n{\n    if (this == &isd)\n        return *this;\n\n    alphabetSize = isd.alphabetSize;\n    codeRate = isd.codeRate;\n    weight = isd.weight;\n    metric = isd.metric;\n    algorithm = isd.algorithm;\n    space = isd.space;\n    surfaceW = isd.surfaceW;\n\n    return *this;\n}\n\ndouble InformationSetDecoding::BDayDecCost(double paramL, double paramP, double optLevelNum) const\n{\n    double distance1 = paramP / (codeRate + paramL);\n    if(!ParamCheck(distance1))\n    {\n        if (distance1 >= 1.0 && distance1 <= 1.0 + epsilon)\n        {\n            distance1 = 1.0;\n        }\n        else\n        {\n            std::cout << distance1 << std::endl;\n            throw std::runtime_error(\"Numerical issue on parameter paramP / (codeRate + paramL).\");\n        }\n    }\n\n    double surface1 = (codeRate + paramL) * space.SphereSurfArea(distance1);\n    if (surface1 == -1)\n    {\n        throw std::invalid_argument(\"Surface area surface1 is not found.\");\n    }\n\n    if (quantum)\n    {\n        return std::min(surface1 / (pow(2, optLevelNum) + 1), paramL / optLevelNum);\n    }\n    else\n    {\n        return std::min(surface1 / pow(2, optLevelNum), paramL / optLevelNum);\n    }\n}\n\ndouble InformationSetDecoding::SolsPerIter(double paramL, double paramP, double optLevelNum) const\n{\n    double distance1 = paramP / (codeRate + paramL);\n    if(!ParamCheck(distance1))\n    {\n        if (distance1 >= 1.0 && distance1 <= 1.0 + epsilon)\n        {\n            distance1 = 1.0;\n        }\n        else\n        {\n            std::cout << distance1 << std::endl;\n            throw std::runtime_error(\"Numerical issue on parameter paramP / (codeRate + paramL).\");\n        }\n    }\n\n    double surface1 = (codeRate + paramL) * space.SphereSurfArea(distance1);\n    if (surface1 == -1)\n    {\n        throw std::invalid_argument(\"Surface area surface1 is not found.\");\n    }\n\n    double bottomListSize;\n    if (quantum)\n    {\n        bottomListSize = std::min(surface1 / (pow(2, optLevelNum) + 1), paramL / optLevelNum);\n    }\n    else\n    {\n        bottomListSize = std::min(surface1 / pow(2, optLevelNum), paramL / optLevelNum);\n    }\n\n    double paramM = paramL - (optLevelNum - 1) * bottomListSize;\n    if (quantum)\n    {\n        return 3 * bottomListSize - paramM;\n    }\n    else\n    {\n        return 2 * bottomListSize - paramM;\n    }   \n}\n\ndouble InformationSetDecoding::IterCost(double paramL, double paramP, double optLevelNum) const\n{   \n    double distance1 = paramP / (codeRate + paramL);\n    if(!ParamCheck(distance1))\n    {\n        if (distance1 >= 1.0 && distance1 <= 1.0 + epsilon)\n        {\n            distance1 = 1.0;\n        }\n        else\n        {\n            std::cout << distance1 << std::endl;\n            throw std::runtime_error(\"Numerical issue on parameter paramP / (codeRate + paramL).\");\n        }\n    }\n\n    double surface1 = (codeRate + paramL) * space.SphereSurfArea(distance1);\n    if (surface1 == -1)\n    {\n        throw std::invalid_argument(\"Surface area surface1 is not found.\");\n    } \n\n    if (quantum)\n    {\n        return std::min(surface1 / (pow(2, optLevelNum) + 1), paramL / optLevelNum);\n    }\n    else\n    {\n        return std::min(surface1 / pow(2, optLevelNum), paramL / optLevelNum);\n    }\n}\n\ndouble InformationSetDecoding::SolsNum() const\n{\n    return std::max(surfaceW - (1 - codeRate), 0.0);\n}\n\ndouble InformationSetDecoding::PartSolProb(double paramL, double paramP) const\n{\n    double distance2 = (weight - paramP) / (1 - codeRate - paramL);\n    if(!ParamCheck(distance2))\n    {\n        if (distance2 >= 1.0 && distance2 <= 1.0 + epsilon)\n        {\n            distance2 = 1.0;\n        }\n        else\n        {\n            std::cout << distance2 << std::endl;\n            throw std::runtime_error(\"Numerical issue on parameter (weight - paramP) / (1 - codeRate - paramL).\");\n        }\n    }\n\n    double surface2 = (1 - codeRate - paramL) * space.SphereSurfArea(distance2);\n    if (surface2 == -1)\n    {\n        throw std::invalid_argument(\"Surface area surface2 is not found.\");\n    }\n\n    return surface2 - surfaceW + paramL;\n}\n\ndouble InformationSetDecoding::AnySolProb(double paramL, double paramP) const\n{\n    double distance2 = (weight - paramP) / (1 - codeRate - paramL);\n    if(!ParamCheck(distance2))\n    {\n        if (distance2 >= 1.0 && distance2 <= 1.0 + epsilon)\n        {\n            distance2 = 1.0;\n        }\n        else\n        {\n            std::cout << distance2 << std::endl;\n            throw std::runtime_error(\"Numerical issue on parameter (weight - paramP) / (1 - codeRate - paramL).\");\n        }\n    }\n\n    double surface2 = (1 - codeRate - paramL) * space.SphereSurfArea(distance2);\n    if (surface2 == -1)\n    {\n        throw std::invalid_argument(\"Surface area surface2 is not found.\");\n    }\n\n    return std::min(0.0, surface2 + paramL - std::min(1 - codeRate, surfaceW));\n}\n\ndouble InformationSetDecoding::RunTime(double paramL, double paramP, unsigned int& optLevelNum) const\n{\n    double distance1 = paramP / (codeRate + paramL);\n    if(!ParamCheck(distance1))\n    {\n        if (distance1 >= 1.0 && distance1 <= 1.0 + epsilon)\n        {\n            distance1 = 1.0;\n        }\n        else\n        {\n            std::cout << distance1 << std::endl;\n            throw std::runtime_error(\"Numerical issue on parameter paramP / (codeRate + paramL).\");\n        }\n    }\n\n    double surface1 = (codeRate + paramL) * space.SphereSurfArea(distance1);\n    if (surface1 == -1)\n    {\n        throw std::invalid_argument(\"Surface area surface1 is not found.\");\n    }\n\n    double distance2 = (weight - paramP) / (1 - codeRate - paramL);\n    if(!ParamCheck(distance2))\n    {\n        if (distance2 >= 1.0 && distance2 <= 1.0 + epsilon)\n        {\n            distance2 = 1.0;\n        }\n        else\n        {\n            std::cout << distance2 << std::endl;\n            throw std::runtime_error(\"Numerical issue on parameter (weight - paramP) / (1 - codeRate - paramL).\");\n        }\n    }\n\n    double surface2 = (1 - codeRate - paramL) * space.SphereSurfArea(distance2);\n    if (surface2 == -1)\n    {\n        throw std::invalid_argument(\"Surface area surface2 is not found.\");\n    }\n\n    auto theorem = [=](unsigned int optLevelNum) -> bool\n    {\n        return bool(paramL <= optLevelNum / pow(2.0, optLevelNum) * surface1);\n    };\n\n    if (!algorithm.compare(\"prange\") || !algorithm.compare(\"dumer\"))\n    {\n        optLevelNum = 1;\n    }\n    else\n    {\n        optLevelNum = 2;\n        while (theorem(optLevelNum))\n        {\n            optLevelNum++;\n        }\n        optLevelNum--;\n    }\n\n    double bottomListSize;\n    if (quantum)\n    {\n        bottomListSize = std::min(surface1 / (pow(2, optLevelNum) + 1), paramL / optLevelNum);\n    }\n    else\n    {\n        bottomListSize = std::min(surface1 / pow(2, optLevelNum), paramL / optLevelNum);\n    }\n\n    double paramM = paramL - (optLevelNum - 1) * bottomListSize;\n    if (quantum)\n    {\n        return bottomListSize - 0.5 * std::min(0.0, std::min(0.0, surface2 + paramL - std::min(1 - codeRate, surfaceW)) + 3 * bottomListSize - paramM);\n    }\n    else\n    {\n        return bottomListSize - std::min(0.0, std::min(0.0, surface2 + paramL - std::min(1 - codeRate, surfaceW)) + 2 * bottomListSize - paramM);\n    }\n}\n\ndouble InformationSetDecoding::GoldenSectionSearch(double& paramP, unsigned int& optLevelNum)\n{\n    double paramPLow = std::max(0.0, weight - (1 - codeRate));\n    double paramPHigh = std::min(weight, codeRate);\n    std::function<double(double)> runTimeFun = [&](double p) {return RunTime(0.0, p, optLevelNum); };\n    paramP = ::GoldenSectionSearch(paramPLow, paramPHigh, tol, runTimeFun);\n    \n    return log2(alphabetSize) * RunTime(0.0, paramP, optLevelNum);\n}\n\ndouble InformationSetDecoding::GoldenSectionSearch(double& paramL, double& paramP, unsigned int& optLevelNum)\n{\n    const double paramLLow = 0, paramLHigh = 1 - codeRate;\n    double a = paramLLow, b = paramLHigh;\n    const double gr = (sqrt(5) + 1) / 2;\n    double c = b - (b - a) / gr;\n    double d = a + (b - a) / gr;\n\n    while (std::abs(c - d) > tol)\n    {\n        double paramPLowC = std::max(0.0, weight - (1 - codeRate - c));\n        double paramPHighC = std::min(weight, codeRate + c);\n        std::function<double(double)> runTimeC = [&](double p) {return RunTime(c, p, optLevelNum); };\n        double optC = ::GoldenSectionSearch(paramPLowC, paramPHighC, tol, runTimeC);\n\n        double paramPLowD = std::max(0.0, weight - (1 - codeRate - d));\n        double paramPHighD = std::min(weight, codeRate + d);\n        std::function<double(double)> runTimeD = [&](double p) {return RunTime(d, p, optLevelNum); };\n        double optD = ::GoldenSectionSearch(paramPLowD, paramPHighD, tol, runTimeD);\n\n        if (RunTime(c, optC, optLevelNum) < RunTime(d, optD, optLevelNum))\n        {\n            b = d;\n        }\n        else\n        {\n            a = c;\n        }\n        c = b - (b - a) / gr;\n        d = a + (b - a) / gr;\n    }\n\n    paramL = (b + a) / 2;\n    std::function<double(double)> runTime = [&](double p) {return RunTime(paramL, p, optLevelNum); };\n    paramP = ::GoldenSectionSearch(std::max(0.0, weight - (1 - codeRate - paramL)),\n        std::min(weight, codeRate + paramL), tol, runTime);\n\n    return log2(alphabetSize) * RunTime(paramL, paramP, optLevelNum);\n}\n\nstruct TerminationCondition {\n    bool operator() (double min, double max) {\n        return std::abs(min - max) <= tol;\n    }\n};\n\ndouble AvgSolsNum(const VectorSpace& space, double distance, double codeRate)\n{\n    double surface = space.SphereSurfArea(distance);\n    if (surface == -1)\n    {\n        throw std::invalid_argument(\n            \"Surface area surface1 is not found.\");\n    }\n    return surface - (1 - codeRate);\n}\n\ndouble UpperRoot(std::string metric, unsigned int alphabetSize, double codeRate)\n{\n    VectorSpace space(metric, alphabetSize);\n    std::function<double(double)> avgSolsNumCR = [&](double cr) {return AvgSolsNum(space, 1 - epsilon, cr); };\n    std::pair<double, double> bracketsCR = bisect(avgSolsNumCR, 0.0, 1.0, TerminationCondition());\n    double highestCodeRate = (bracketsCR.first + bracketsCR.second) / 2;\n\n    if (codeRate > highestCodeRate)\n        return 1;\n    else\n    {\n        std::function<double(double)> avgSolsNumW = [&](double w) {return AvgSolsNum(space, w, codeRate); };\n        std::pair<double, double> bracketsW = bisect(avgSolsNumW, AvgVectorWeight(space, 1.0) / MaxWeight(space), 1.0, TerminationCondition());\n        return (bracketsW.first + bracketsW.second) / 2;\n    }\n}\n\ndouble LowerRoot(std::string metric, unsigned int alphabetSize, double codeRate)\n{\n    VectorSpace space(metric, alphabetSize);\n    std::function<double(double)> avgSolsNumW = [&](double w) {return AvgSolsNum(space, w, codeRate); };\n    std::pair<double, double> bracketsW = bisect(avgSolsNumW, 0.0, AvgVectorWeight(space, 1.0) / MaxWeight(space), TerminationCondition());\n    return (bracketsW.first + bracketsW.second) / 2;\n}\n\ndouble RunTime(std::string metric, std::string algorithm, unsigned int alphabetSize, double codeRate,\n    double& weight, double& paramL, double& paramP, unsigned int& optLevelNum)\n{\n    if(!MetricCheck(metric))\n        throw std::invalid_argument(\"This metric is not offered. Allowed metrics are hamming and lee.\");\n\n    double runTime;\n    if (!metric.compare(\"hamming\") && alphabetSize != 3)\n    {\n        weight = LowerRoot(metric, alphabetSize, codeRate) - epsilon;\n    }\n    else\n    {\n        weight = UpperRoot(metric, alphabetSize, codeRate) - epsilon;\n    }\n\n    InformationSetDecoding isd(alphabetSize, codeRate, weight, metric, algorithm);\n    if (!algorithm.compare(\"prange\"))\n    {\n        try\n        {\n            paramL = 0;\n            runTime = isd.GoldenSectionSearch(paramP, optLevelNum);\n        }\n        catch (std::runtime_error& e)\n        {\n            std::cout << e.what() << std::endl;\n            return -1;\n        }\n    }\n    else if (!algorithm.compare(\"dumer\") || !algorithm.compare(\"wagner\"))\n    {\n        try\n        {\n            runTime = isd.GoldenSectionSearch(paramL, paramP, optLevelNum);\n        }\n        catch (std::runtime_error& e)\n        {\n            std::cout << e.what() << std::endl;\n            return -1;\n        }\n    }\n    else\n    {\n        std::cout << \"This algorithm is not offered. Allowed algorithms are prange, dumer and wagner.\" << std::endl;\n        return -1;\n    }\n    return -runTime;\n}\n", "meta": {"hexsha": "aeeff6a74e063a4b3d003378afd84503c092b712", "size": 13821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/isd.cpp", "max_stars_repo_name": "setinski/Computational-Complexity-of-Generalized-Syndrome-Decoding-Problem", "max_stars_repo_head_hexsha": "8afdf9eb37e185630ed2511d94e8155dfa1184ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/isd.cpp", "max_issues_repo_name": "setinski/Computational-Complexity-of-Generalized-Syndrome-Decoding-Problem", "max_issues_repo_head_hexsha": "8afdf9eb37e185630ed2511d94e8155dfa1184ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/isd.cpp", "max_forks_repo_name": "setinski/Computational-Complexity-of-Generalized-Syndrome-Decoding-Problem", "max_forks_repo_head_hexsha": "8afdf9eb37e185630ed2511d94e8155dfa1184ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-05T08:00:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T08:00:22.000Z", "avg_line_length": 30.8504464286, "max_line_length": 151, "alphanum_fraction": 0.5969900875, "num_tokens": 3813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5242196749704687}}
{"text": "#include <geometry.h>\n#include <tiny_math_types.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\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(inside_cylinder_test)\n{\n  typedef tiny::MathTypes<double>   MT;\n  typedef MT::vector3_type          V;\n  typedef MT::real_type             T;\n\n  V const center = V::make(1.0, 2.0, 4.0);\n  V const axis   = V::make(0.0, 0.0, 1.0);\n  T const radius = 2.0;\n  T const height = 4.0;\n\n  geometry::Cylinder<V> const cylinder = geometry::make_cylinder(radius, height, axis, center);\n\n  BOOST_CHECK(geometry::is_valid(cylinder));\n\n  // on bottom surface\n  {\n    V    const p    = V::make( 1.0, 2.0, 2.0);\n    bool const test = geometry::inside_cylinder( p,  cylinder);\n    BOOST_CHECK( test );\n  }\n\n  // on top surface\n  {\n    V    const p    = V::make( 1.0, 2.0, 6.0);\n    bool const test = geometry::inside_cylinder( p,  cylinder);\n    BOOST_CHECK( test );\n  }\n\n  // on cylinder surface\n  {\n    V    const p    = V::make( 3.0, 2.0, 4.0);\n    bool const test = geometry::inside_cylinder( p,  cylinder);\n    BOOST_CHECK( test );\n  }\n\n\n  // inside\n  {\n    V    const p    = V::make( 1.0, 2.0, 2.1);\n    bool const test = geometry::inside_cylinder( p,  cylinder);\n    BOOST_CHECK( test );\n  }\n\n  // inside\n  {\n    V    const p    = V::make( 1.0, 2.0, 5.9);\n    bool const test = geometry::inside_cylinder( p,  cylinder);\n    BOOST_CHECK( test );\n  }\n\n  // inside\n  {\n    V    const p    = V::make( 2.9, 2.0, 4.0);\n    bool const test = geometry::inside_cylinder( p,  cylinder);\n    BOOST_CHECK( test );\n  }\n\n  // outside\n  {\n    V    const p    = V::make( 1.0, 2.0, 1.9);\n    bool const test = geometry::inside_cylinder( p,  cylinder);\n    BOOST_CHECK( !test );\n  }\n\n  // outside\n  {\n    V    const p    = V::make( 1.0, 2.0, 6.1);\n    bool const test = geometry::inside_cylinder( p,  cylinder);\n    BOOST_CHECK( !test );\n  }\n\n  // outside\n  {\n    V    const p    = V::make( 3.1, 2.0, 4.0);\n    bool const test = geometry::inside_cylinder( p,  cylinder);\n    BOOST_CHECK( !test );\n  }\n\n\n\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "15ee1f6366832f6f443d140328aa8ae88587f35f", "size": 2217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_inside_cylinder/geometry_inside_cylinder.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_inside_cylinder/geometry_inside_cylinder.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_inside_cylinder/geometry_inside_cylinder.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8556701031, "max_line_length": 95, "alphanum_fraction": 0.601262968, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5242196657247252}}
{"text": "/* Copyright Institute of Sound and Vibration Research - All rights reserved */\n\n/**\n* @file degree_radian_conversion.hpp\n* Provide cartesian<->spherical conversion without imposing particular data types.\n* @author Andreas Franck a.franck@soton.ac.uk\n*/\n\n\n#ifndef VISR_LIBEFL_DEGREE_RADIAN_CONVERSION_HPP_INCLUDED\n#define VISR_LIBEFL_DEGREE_RADIAN_CONVERSION_HPP_INCLUDED\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n\nnamespace visr\n{\nnamespace efl\n{\n\ntemplate< typename T >\nT degree2radian( T deg )\n{\n  return boost::math::constants::degree<T>( ) * deg;\n}\n\ntemplate< typename T >\nT radian2degree( T rad )\n{\n  return boost::math::constants::radian<T>( ) * rad;\n}\n\n} // namespace efl\n} // namespace visr\n\n#endif // #ifndef VISR_LIBEFL_DEGREE_RADIAN_CONVERSION_HPP_INCLUDED\n", "meta": {"hexsha": "dae80934fb5bc526f436aaa435e766eee669fcfd", "size": 792, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libefl/degree_radian_conversion.hpp", "max_stars_repo_name": "s3a-spatialaudio/VISR", "max_stars_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-12T14:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T01:16:23.000Z", "max_issues_repo_path": "src/libefl/degree_radian_conversion.hpp", "max_issues_repo_name": "s3a-spatialaudio/VISR", "max_issues_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_issues_repo_licenses": ["ISC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libefl/degree_radian_conversion.hpp", "max_forks_repo_name": "s3a-spatialaudio/VISR", "max_forks_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T12:53:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T10:08:08.000Z", "avg_line_length": 20.8421052632, "max_line_length": 82, "alphanum_fraction": 0.7626262626, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718435083355188, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5242196649461097}}
{"text": "#ifndef _COCONUT_PULP_PRIMITIVE_VECTOR_HPP_\n#define _COCONUT_PULP_PRIMITIVE_VECTOR_HPP_\n\n#include <iosfwd>\n\n#include <coconut-tools/serialisation.hpp>\n\n#include <boost/operators.hpp>\n#include \"detail/VectorType.hpp\"\n\nnamespace coconut {\nnamespace pulp {\nnamespace primitive {\n\nclass Vector : // TODO: clashes with pulp::math::Vector name\n\tboost::additive<Vector>,\n\tdetail::VectorType<4>\n{\npublic:\n\n\tVector() = default;\n\n\tVector(const Vec3& vector) :\n\t\tdetail::VectorType<4>(vector.x(), vector.y(), vector.z(), 0.0f)\n\t{\n\t}\n\n\tVector(const Vec4& vector) :\n\t\tdetail::VectorType<4>(vector.x(), vector.y(), vector.z(), 0.0f)\n\t{\n\t}\n\n\tVector(float x, float y, float z) :\n\t\tdetail::VectorType<4>(x, y, z, 0.0f)\n\t{\n\t}\n\n\tVector& operator+=(const Vector& rhs) {\n\t\tstatic_cast<detail::VectorType<4>&>(*this) += rhs;\n\t\treturn *this;\n\t}\n\n\tVector& operator-=(const Vector& rhs) {\n\t\tstatic_cast<detail::VectorType<4>&>(*this) -= rhs;\n\t\treturn *this;\n\t}\n\n\tVector cross(const Vector& rhs) const {\n\t\tauto lhsV3 = pulp::math::Vec3(x(), y(), z());\n\t\tconst auto rhsV3 = pulp::math::Vec3(rhs.x(), rhs.y(), rhs.z());\n\t\tlhsV3 = lhsV3.cross(rhsV3);\n\t\treturn Vector(lhsV3.x(), lhsV3.y(), lhsV3.z());\n\t}\n\n\tusing detail::VectorType<4>::normalise;\n\n\tfloat& x() {\n\t\treturn get<0>();\n\t}\n\n\tfloat x() const {\n\t\treturn get<0>();\n\t}\n\n\tfloat& y() {\n\t\treturn get<1>();\n\t}\n\n\tfloat y() const {\n\t\treturn get<1>();\n\t}\n\n\tfloat& z() {\n\t\treturn get<2>();\n\t}\n\n\tfloat z() const {\n\t\treturn get<2>();\n\t}\n\n\tusing detail::VectorType<4>::storeAs;\n\nprivate:\n\n\tfriend class Position;\n\n\tfriend std::ostream& operator<<(std::ostream& os, const Vector& vector) {\n\t\treturn os << static_cast<const detail::VectorType<4>&>(vector);\n\t}\n\n};\n\nCT_MAKE_SERIALISABLE(SerialiserType, serialiser, Vector, vector) {\n\tserialiser(SerialiserType::Label(\"x\"), vector.x());\n\tserialiser(SerialiserType::Label(\"y\"), vector.y());\n\tserialiser(SerialiserType::Label(\"z\"), vector.z());\n}\n\n} // namespace primitive\n\nusing primitive::Vector;\n\n} // namespace pulp\n} // namespace coconut\n\n#endif /* _COCONUT_PULP_PRIMITIVE_VECTOR_HPP_ */\n", "meta": {"hexsha": "7e5ebd109acb619325ec949236973fd365c7a2d4", "size": 2053, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "coconut-pulp-primitive/src/main/c++/coconut/pulp/primitive/Vector.hpp", "max_stars_repo_name": "mikosz/coconut", "max_stars_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T12:01:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T12:01:54.000Z", "max_issues_repo_path": "coconut-pulp-primitive/src/main/c++/coconut/pulp/primitive/Vector.hpp", "max_issues_repo_name": "mikosz/coconut", "max_issues_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coconut-pulp-primitive/src/main/c++/coconut/pulp/primitive/Vector.hpp", "max_forks_repo_name": "mikosz/coconut", "max_forks_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1869158879, "max_line_length": 74, "alphanum_fraction": 0.6604968339, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5242196649461097}}
{"text": "/*\n * Test tool for Toy Monte Carlo generation with CRAB submission\n *\n * \\author Luca Lista, INFN\n *\n */\n#include <boost/program_options.hpp>\n#include \"RooRandom.h\"\n#include \"RooRealVar.h\"\n#include \"RooGaussian.h\"\n#include \"RooExponential.h\"\n#include \"RooAddPdf.h\"\n#include \"RooDataSet.h\"\n#include \"RooDataHist.h\"\n#include \"RooGlobalFunc.h\" \n#include \"RooChi2Var.h\"\n#include \"RooMinuit.h\"\n#include \"RooPlot.h\"\n#include \"TCanvas.h\"\n#include \"TROOT.h\"\n#include <string>\n\nstatic const char * const kHelpOpt = \"help\";\nstatic const char * const kHelpCommandOpt = \"help,h\";\nstatic const char * const kSeedOpt = \"seed\";\nstatic const char * const kSeedCommandOpt = \"seed,s\";\n\nint main(int argc, char * argv[]) {\n  using namespace boost::program_options;\n  using namespace std;\n\n  gROOT->SetBatch(kTRUE);\n  gROOT->SetStyle(\"Plain\");\n  \n  string programName(argv[0]);\n  string descString(programName);\n  descString += \" [options] \";\n  options_description desc(descString);\n\n  desc.add_options()\n    (kHelpCommandOpt, \"produce help message\")\n    (kSeedCommandOpt, value<unsigned int>(), \"random generator seed\");\n\n  positional_options_description p;\n\n  p.add(kSeedOpt, -1);\n  \n  variables_map vm;\n  try {\n    store(command_line_parser(argc,argv).options(desc).positional(p).run(), vm);\n    notify(vm);\n  } catch(const error&) {\n    return 7000;\n  }\n\n  if(vm.count(kHelpOpt)) {\n    cout << desc <<std::endl;\n    return 0;\n  }\n\n  unsigned int seed = 123456;\n  if(vm.count(kSeedOpt)) {\n    seed = vm[kSeedOpt].as<unsigned int>();\n    cout << \"random seed specified by user as: \" << seed << endl;\n  } else {\n    cout << \"random seed set by default as: \" << seed << endl;\n  }\n\n  RooRandom::randomGenerator()->SetSeed(seed);\n\n  RooRealVar x(\"x\", \"x\", -10, 10);\n\n  RooRealVar mu(\"mu\", \"average\", 0, -1, 1);\n  RooRealVar sigma(\"sigma\", \"sigma\", 1, 0, 5);\n  RooGaussian gauss(\"gauss\",\"gaussian PDF\", x, mu, sigma);\n\n  RooRealVar lambda(\"lambda\", \"slope\", -0.1, -5., 0.);\n  RooExponential expo(\"expo\", \"exponential PDF\", x, lambda);\n\n  RooRealVar s(\"s\", \"signal yield\", 1000, 0, 10000);\n  RooRealVar b(\"b\", \"background yield\", 1000, 0, 10000);\n\n  cout << \"initial values: \" << endl;\n\n  mu.Print();\n  sigma.Print();\n  lambda.Print();\n  s.Print();\n  b.Print();\n\n  RooAddPdf sum(\"sum\", \"gaussian plus exponential PDF\", \n\t\tRooArgList(gauss, expo), RooArgList(s, b));\n\n  unsigned int nSample = RooRandom::randomGenerator()->Poisson(s.getVal() + b.getVal());\n  RooDataSet * data = sum.generate(x, nSample);\n  x.setBins(50);\n  RooDataHist hist(\"hist\", \"hist\", RooArgSet(x), *data);\n  RooChi2Var chi2(\"chi2\",\"chi2\", sum, hist, true);\n  RooMinuit minuit(chi2);\n  minuit.migrad();\n  minuit.hesse();\n\n  RooPlot * xFrame = x.frame() ;\n  hist.plotOn(xFrame) ;\n  sum.plotOn(xFrame) ;\n  sum.plotOn(xFrame, RooFit::Components(expo), RooFit::LineStyle(kDashed)) ;\n  TCanvas c;\n  xFrame->Draw();\n  c.SaveAs(\"binnedChi2Fit.eps\");\n  \n  sum.getVariables()->Print();\n  mu.Print();\n  sigma.Print();\n  lambda.Print();\n  s.Print();\n  b.Print();\n\n  return 0;\n}\n \n\n\n", "meta": {"hexsha": "4514310a14539c4608d848e54c9273b6c1f816b3", "size": 3019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PhysicsTools/RooStatsCms/test/testCrabToyMC.cpp", "max_stars_repo_name": "NTrevisani/cmssw", "max_stars_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-24T19:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-19T11:45:32.000Z", "max_issues_repo_path": "PhysicsTools/RooStatsCms/test/testCrabToyMC.cpp", "max_issues_repo_name": "NTrevisani/cmssw", "max_issues_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-03-20T23:18:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-27T11:00:06.000Z", "max_forks_repo_path": "PhysicsTools/RooStatsCms/test/testCrabToyMC.cpp", "max_forks_repo_name": "NTrevisani/cmssw", "max_forks_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-08-21T16:37:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-09T13:33:17.000Z", "avg_line_length": 24.5447154472, "max_line_length": 88, "alphanum_fraction": 0.6571712488, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355186, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5242196649461096}}
{"text": "// Copyright 2021, Autonomous Space Robotics Lab (ASRL)\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 * \\file polar_processing.hpp\r\n * \\brief Polar processing utility functions\r\n *\r\n * \\author Yuchen Wu, Autonomous Space Robotics Lab (ASRL)\r\n */\r\n#pragma once\r\n\r\n#include <cstdint>\r\n#include <cstdio>\r\n#include <ctime>\r\n#include <set>\r\n\r\n#define _USE_MATH_DEFINES\r\n#include <math.h>\r\n\r\n#include <Eigen/Dense>\r\n\r\n#include <vtr_lidar/cloud/cloud.hpp>\r\n#include <vtr_lidar/nanoflann/nanoflann.hpp>\r\n#include <vtr_lidar/pointmap/pointmap.hpp>\r\n\r\nnamespace vtr {\r\nnamespace lidar {\r\n\r\n// KDTree type definition\r\nusing PointXYZ_KDTree = nanoflann::KDTreeSingleIndexAdaptor<\r\n    nanoflann::L2_Simple_Adaptor<float, PointCloud>, PointCloud, 3>;\r\n\r\nvoid cart2Pol_(std::vector<PointXYZ>& xyz);\r\nPointXYZ cart2pol(const PointXYZ& p);\r\n\r\nvoid pca_features(std::vector<PointXYZ>& points,\r\n                  std::vector<float>& eigenvalues,\r\n                  std::vector<PointXYZ>& eigenvectors);\r\n\r\nvoid detect_outliers(std::vector<PointXYZ>& rtp, std::vector<float>& scores,\r\n                     int lidar_n_lines, float lidar_angle_res, float minTheta,\r\n                     int n_pass, float threshold);\r\n\r\nfloat get_lidar_angle_res(std::vector<PointXYZ>& rtp, float& minTheta,\r\n                          float& maxTheta, int lidar_n_lines);\r\n\r\nvoid scaleAndLogRadius(std::vector<PointXYZ>& rtp, float r_scale);\r\n\r\nvoid scaleHorizontal(std::vector<PointXYZ>& rtp, float h_scale);\r\n\r\nvoid extract_features_multi_thread(std::vector<PointXYZ>& points,\r\n                                   std::vector<PointXYZ>& normals,\r\n                                   std::vector<float>& planarity,\r\n                                   std::vector<float>& linearity,\r\n                                   int lidar_n_lines, float h_scale,\r\n                                   float r_scale, int verbose);\r\n/**\r\n * \\brief todo\r\n * \\param[in] points point cloud in cartesian\r\n * \\param[in] polar_pts point cloud in polar\r\n * \\param[in] normals point cloud normal\r\n * \\param[in] r0 ideal distance for estimating the normal\r\n * \\param[in] theta0 maximum incidence angle for estimating the normal\r\n * \\param[out] scores a score for each point based on normal direction\r\n */\r\nvoid smartNormalScore(const std::vector<PointXYZ>& points,\r\n                      const std::vector<PointXYZ>& polar_pts,\r\n                      const std::vector<PointXYZ>& normals, const float& r0,\r\n                      const float& theta0, std::vector<float>& scores);\r\n\r\nvoid smartICPScore(std::vector<PointXYZ>& polar_pts,\r\n                   std::vector<float>& scores);\r\n\r\nvoid compare_map_to_frame(std::vector<PointXYZ>& frame_points,\r\n                          std::vector<PointXYZ>& map_points,\r\n                          std::vector<PointXYZ>& map_normals,\r\n                          std::unordered_map<VoxKey, size_t>& map_samples,\r\n                          Eigen::Matrix3d R_d, Eigen::Vector3d T_d,\r\n                          float theta_dl, float phi_dl, float map_dl,\r\n                          std::vector<float>& movable_probs,\r\n                          std::vector<int>& movable_counts);\r\n\r\nvoid extractNormal(const std::vector<PointXYZ>& points,\r\n                   const std::vector<PointXYZ>& polar_pts,\r\n                   const std::vector<PointXYZ>& queries,\r\n                   const std::vector<PointXYZ>& polar_queries,\r\n                   const float polar_r, const int parallel_threads,\r\n                   std::vector<PointXYZ>& normals,\r\n                   std::vector<float>& norm_scores);\r\n\r\n}  // namespace lidar\r\n}  // namespace vtr", "meta": {"hexsha": "2cb2be480ce5b15f9aba6a2afa60a266cec01988", "size": 4147, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "main/src/vtr_lidar/include/vtr_lidar/polar_processing/polar_processing.hpp", "max_stars_repo_name": "utiasASRL/vtr3", "max_stars_repo_head_hexsha": "b4edca56a19484666d3cdb25a032c424bdc6f19d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T03:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:40:01.000Z", "max_issues_repo_path": "main/src/vtr_lidar/include/vtr_lidar/polar_processing/polar_processing.hpp", "max_issues_repo_name": "shimp-t/vtr3", "max_issues_repo_head_hexsha": "bdcad784ffe26fabfa737d0e195bcb3bacb930c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-09-18T19:18:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T11:15:40.000Z", "max_forks_repo_path": "main/src/vtr_lidar/include/vtr_lidar/polar_processing/polar_processing.hpp", "max_forks_repo_name": "shimp-t/vtr3", "max_forks_repo_head_hexsha": "bdcad784ffe26fabfa737d0e195bcb3bacb930c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T01:31:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T05:09:37.000Z", "avg_line_length": 40.2621359223, "max_line_length": 79, "alphanum_fraction": 0.6221364842, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5242196628293279}}
{"text": "/* adcpp_eigen.hpp\n *\n *  Created on: 21 Aug 2019\n *      Author: Fabian Meyer\n *     License: MIT\n */\n\n#ifndef ADCPP_ADCPP_EIGEN_HPP_\n#define ADCPP_ADCPP_EIGEN_HPP_\n\n#include <adcpp/adcpp.hpp>\n#include <Eigen/Core>\n\n#define ADCPP_GEN_NUMTRAITS(T) \\\n    template<>\\\n    struct NumTraits<T>\\\n    {\\\n        using ValueType = T::Scalar;\\\n        using Real = T;\\\n        using NonInteger = T;\\\n        using Nested = T;\\\n        using Literal = T;\\\n        enum {\\\n            IsInteger = std::is_integral<ValueType>::value ? 1 : 0,\\\n            IsSigned = std::is_signed<ValueType>::value ? 1 : 0,\\\n            IsComplex = 0,\\\n            RequireInitialization = 1,\\\n            ReadCost = 1,\\\n            AddCost = 3,\\\n            MulCost = 3\\\n        };\\\n        static Real epsilon()\\\n        {\\\n            return Real(std::numeric_limits<ValueType>::epsilon());\\\n        }\\\n        static Real highest()\\\n        {\\\n            return Real(std::numeric_limits<ValueType>::max());\\\n        }\\\n        static Real lowest()\\\n        {\\\n            return Real(std::numeric_limits<ValueType>::min());\\\n        }\\\n        static Real min_exponent()\\\n        {\\\n            return Real(std::numeric_limits<ValueType>::min_exponent);\\\n        }\\\n        static Real max_exponent()\\\n        {\\\n            return Real(std::numeric_limits<ValueType>::max_exponent);\\\n        }\\\n        static Real digits()\\\n        {\\\n            return Real(std::numeric_limits<ValueType>::digits);\\\n        }\\\n        static Real digits10()\\\n        {\\\n            return Real(std::numeric_limits<ValueType>::digits10);\\\n        }\\\n    }\n\nnamespace Eigen\n{\n    ADCPP_GEN_NUMTRAITS(adcpp::fwd::Double);\n    ADCPP_GEN_NUMTRAITS(adcpp::fwd::Float);\n\n    ADCPP_GEN_NUMTRAITS(adcpp::bwd::Double);\n    ADCPP_GEN_NUMTRAITS(adcpp::bwd::Float);\n}\n\nnamespace adcpp\n{\nnamespace fwd\n{\n    typedef Eigen::Matrix<Double, Eigen::Dynamic, Eigen::Dynamic> MatrixXd;\n    typedef Eigen::Matrix<Double, 2, 2> Matrix2d;\n    typedef Eigen::Matrix<Double, 3, 3> Matrix3d;\n    typedef Eigen::Matrix<Double, 4, 4> Matrix4d;\n    typedef Eigen::Matrix<Double, 5, 5> Matrix5d;\n\n    typedef Eigen::Matrix<Double, Eigen::Dynamic, 1> VectorXd;\n    typedef Eigen::Matrix<Double, 2, 1> Vector2d;\n    typedef Eigen::Matrix<Double, 3, 1> Vector3d;\n    typedef Eigen::Matrix<Double, 4, 1> Vector4d;\n    typedef Eigen::Matrix<Double, 5, 1> Vector5d;\n\n    typedef Eigen::Matrix<Float, Eigen::Dynamic, Eigen::Dynamic> MatrixXf;\n    typedef Eigen::Matrix<Float, 2, 2> Matrix2f;\n    typedef Eigen::Matrix<Float, 3, 3> Matrix3f;\n    typedef Eigen::Matrix<Float, 4, 4> Matrix4f;\n    typedef Eigen::Matrix<Float, 5, 5> Matrix5f;\n\n    typedef Eigen::Matrix<Float, Eigen::Dynamic, 1> VectorXf;\n    typedef Eigen::Matrix<Float, 2, 1> Vector2f;\n    typedef Eigen::Matrix<Float, 3, 1> Vector3f;\n    typedef Eigen::Matrix<Float, 4, 1> Vector4f;\n    typedef Eigen::Matrix<Float, 5, 1> Vector5f;\n}\n\nnamespace bwd\n{\n    typedef Eigen::Matrix<Double, Eigen::Dynamic, Eigen::Dynamic> MatrixXd;\n    typedef Eigen::Matrix<Double, 2, 2> Matrix2d;\n    typedef Eigen::Matrix<Double, 3, 3> Matrix3d;\n    typedef Eigen::Matrix<Double, 4, 4> Matrix4d;\n    typedef Eigen::Matrix<Double, 5, 5> Matrix5d;\n\n    typedef Eigen::Matrix<Double, Eigen::Dynamic, 1> VectorXd;\n    typedef Eigen::Matrix<Double, 2, 1> Vector2d;\n    typedef Eigen::Matrix<Double, 3, 1> Vector3d;\n    typedef Eigen::Matrix<Double, 4, 1> Vector4d;\n    typedef Eigen::Matrix<Double, 5, 1> Vector5d;\n\n    typedef Eigen::Matrix<Float, Eigen::Dynamic, Eigen::Dynamic> MatrixXf;\n    typedef Eigen::Matrix<Float, 2, 2> Matrix2f;\n    typedef Eigen::Matrix<Float, 3, 3> Matrix3f;\n    typedef Eigen::Matrix<Float, 4, 4> Matrix4f;\n    typedef Eigen::Matrix<Float, 5, 5> Matrix5f;\n\n    typedef Eigen::Matrix<Float, Eigen::Dynamic, 1> VectorXf;\n    typedef Eigen::Matrix<Float, 2, 1> Vector2f;\n    typedef Eigen::Matrix<Float, 3, 1> Vector3f;\n    typedef Eigen::Matrix<Float, 4, 1> Vector4f;\n    typedef Eigen::Matrix<Float, 5, 1> Vector5f;\n\n    template<typename Scalar, typename DerivedA, typename DerivedB>\n    inline void gradient(const Eigen::MatrixBase<DerivedA> &x,\n        const Number<Scalar> &f,\n        Eigen::MatrixBase<DerivedB> &grad)\n    {\n        assert(grad.size() == x.size());\n\n        typename bwd::Number<Scalar>::DerivativeMap derivative;\n        f.derivative(derivative);\n\n        grad.setZero();\n        for(long int i = 0; i < x.size(); ++i)\n        {\n            if(derivative.contains(x(i)))\n                grad(i) = derivative(x(i));\n        }\n    }\n\n    template<typename DerivedA, typename DerivedB, typename DerivedC>\n    inline void jacobian(const Eigen::MatrixBase<DerivedA> &x,\n        const Eigen::MatrixBase<DerivedB> &f,\n        Eigen::MatrixBase<DerivedC> &jac)\n    {\n        assert(jac.rows() == f.size());\n        assert(jac.cols() == x.size());\n\n        typename Eigen::MatrixBase<DerivedB>::Scalar::DerivativeMap derivative;\n        jac.setZero();\n        for(long int i = 0; i < f.size(); ++i)\n        {\n            f(i).derivative(derivative);\n            for(long int j = 0; j < x.size(); ++j)\n            {\n                if(derivative.contains(x(j)))\n                    jac(i, j) = derivative(x(j));\n            }\n        }\n    }\n}\n}\n\n#endif\n", "meta": {"hexsha": "75c2b7f6f33d3e55cf5ab6b12152937202198c7a", "size": 5266, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/adcpp/adcpp_eigen.hpp", "max_stars_repo_name": "Rookfighter/algorithmic-differentiation", "max_stars_repo_head_hexsha": "6392ff3c94f8d0e97986f1023a7478786ab76a9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-10-08T10:31:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T21:54:12.000Z", "max_issues_repo_path": "include/adcpp/adcpp_eigen.hpp", "max_issues_repo_name": "Rookfighter/algorithmic-differentiation-cpp", "max_issues_repo_head_hexsha": "6392ff3c94f8d0e97986f1023a7478786ab76a9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/adcpp/adcpp_eigen.hpp", "max_forks_repo_name": "Rookfighter/algorithmic-differentiation-cpp", "max_forks_repo_head_hexsha": "6392ff3c94f8d0e97986f1023a7478786ab76a9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-02T04:34:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T22:17:54.000Z", "avg_line_length": 31.3452380952, "max_line_length": 79, "alphanum_fraction": 0.6006456513, "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5242196557003664}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2011 Joel de Guzman\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#if !defined(PAWN_MAST_HPP)\n#define PAWN_MAST_HPP\n\n#include <boost/config/warning_disable.hpp>\n#include <boost/variant/recursive_variant.hpp>\n#include <boost/fusion/include/adapt_struct.hpp>\n#include <boost/fusion/include/io.hpp>\n#include <boost/optional.hpp>\n\n#include <iostream>\n#include <list>\n#include <map>\n#include <vector>\n\n#include <helper.hpp>\n\nnamespace client { namespace math { namespace ast\n{\n    struct nil {};\n    struct unary;\n    struct expr;\n\n    using variable = std::string;\n    using column = unsigned int;\n\n    typedef boost::variant<\n            nil\n          , double\n          , variable\n          , column\n          , boost::recursive_wrapper<unary>\n          , boost::recursive_wrapper<expr>\n        >\n    operand;\n\n    enum class optoken : int\n    {\n        plus,\n        minus,\n        times,\n        divide,\n        positive,\n        negative\n    };\n\n    struct unary\n    {\n        optoken operator_;\n        operand operand_;\n    };\n\n    struct operation\n    {\n        optoken operator_;\n        operand operand_;\n    };\n\n    struct expr\n    {\n        operand first;\n        std::list<operation> rest;\n    };\n\n    // print functions for debugging\n    inline std::ostream& operator<<(std::ostream& out, nil) { out << \"nil\"; return out; }\n    //inline std::ostream& operator<<(std::ostream& out, variable const& var) { out << var.name; return out; }\n\n    struct printer {\n        typedef void result_type;\n\n        void operator()(nil) const {std::cout << '_'; }\n        void operator()(double n) const { std::cout << n; }\n        void operator()(variable const& x) const { std::cout << '%' << x; }\n        void operator()(column const& x) const { std::cout << '$' << x; }\n\n        void operator()(optoken const &o) const {\n            switch (o)\n            {\n                case optoken::plus: std::cout << \" add\"; break;\n                case optoken::minus: std::cout << \" subt\"; break;\n                case optoken::times: std::cout << \" mult\"; break;\n                case optoken::divide: std::cout << \" div\"; break;\n                case optoken::positive: std::cout << \" pos\"; break;\n                case optoken::negative: std::cout << \" neg\"; break;\n            }\n        }\n\n        void operator()(unary const& x) const\n        {\n            boost::apply_visitor(*this, x.operand_);\n            (*this)(x.operator_);\n        }\n\n        void operator()(operation const& x) const\n        {\n            boost::apply_visitor(*this, x.operand_);\n            (*this)(x.operator_);\n        }\n\n        void operator()(expr const& x) const\n        {\n            boost::apply_visitor(*this, x.first);\n            for (const auto& oper : x.rest) {\n                std::cout << ' ';\n                (*this)(oper);\n            }\n        }\n    };\n\n    struct colsEval {\n    private:\n      using ColIndices = client::helper::ColIndices;\n      using Global = client::helper::Global;\n      const ColIndices &_pre;\n      const Global &_global;\n      bool _isInitial {true};\n      std::vector<std::string> _headers;\n    public:\n        using result_type = std::pair<ColIndices, std::string>;\n        colsEval(const ColIndices &v, const Global &g) : _pre{v}, _global{g} {}\n        void setHeaders(const std::vector<std::string>& h) { _headers = h; }\n        void notInitial() { _isInitial = false; }\n        result_type operator()(nil) const { BOOST_ASSERT(0); return result_type{}; }\n        result_type operator()(double n) const { return result_type{}; }\n        result_type operator()(variable const &x) const {\n          if (_global.gVarsN.find(x) != std::end(_global.gVarsN)) return result_type{};\n          auto jt = std::find(begin(_headers), end(_headers), x);\n          if (jt != std::end(_headers)) return (*this)((unsigned int)(jt - std::begin(_headers)) + 1);\n          auto it = std::find(std::begin(_pre.var), std::end(_pre.var), x);\n          if (it == std::end(_pre.var)) return std::make_pair(ColIndices{}, \"Error: \" + x + \" used before declaration.\");\n          return result_type{};\n        }\n        result_type operator()(column const &x) const {\n          if (!_isInitial) return std::make_pair(ColIndices{}, \"Can't access new input file columns via column name / index after reduce / zip.\");\n          ColIndices res;\n          res.num.push_back(x);\n          return std::make_pair(res, \"\");\n        }\n        result_type operator()(unary const& x) const {\n          return boost::apply_visitor(*this, x.operand_);\n        }\n        result_type operator()(operation const& x) const {\n            return boost::apply_visitor(*this, x.operand_);\n        }\n        result_type operator()(expr const& e) const {\n            result_type res{};\n            auto x = boost::apply_visitor(*this, e.first);\n            if (x.second.size() > 0) return x;\n            res.first.add(x.first);\n            for (const auto& oper : e.rest) {\n              x = (*this)(oper);\n              if (x.second.size() > 0) return x;\n              res.first.add(x.first);\n            }\n            return res;\n        }\n    };\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  The AST evaluator\n    ///////////////////////////////////////////////////////////////////////////\n    struct whatever {\n      whatever(double x) : _x{x} {}\n      auto operator() (const std::vector<double>&) { return _x; }\n    private:\n      double _x;\n    };\n\n    struct evaluator {\n    private:\n        const helper::positionTeller _index;\n        const helper::Global &_global;\n    public:\n        using retFnT = std::function<double(const std::vector<double>&)>;\n        typedef retFnT result_type;\n\n        evaluator(helper::positionTeller p, const helper::Global &g) : _index{p}, _global{g} {}\n        retFnT operator()(nil) const { BOOST_ASSERT(0); return whatever{0.0}; }\n        retFnT operator()(double n) const { return whatever{n}; }\n        retFnT operator()(variable const &x) const { \n          auto it = _global.gVarsN.find(x);\n          if (it != std::end(_global.gVarsN)) {\n            auto y = it->second;\n            return [y](const std::vector<double> &v) { return y; };\n          }\n          auto y = _index.var(x);\n          return [y](const std::vector<double> &v) { return v[y]; };\n        }\n        retFnT operator()(column const &x) const { \n          auto y = _index.num(x);\n          return [y](const std::vector<double> &v) { return v[y]; };\n        }\n\n        retFnT operator()(optoken const &o, retFnT const &lhs, retFnT const &rhs) const {\n            switch (o)\n            {\n                case optoken::plus: return [lhs, rhs](const std::vector<double> &v) { return lhs(v) + rhs(v); };\n                case optoken::minus: return [lhs, rhs](const std::vector<double> &v) { return lhs(v) - rhs(v); };\n                case optoken::times: return [lhs, rhs](const std::vector<double> &v) { return lhs(v) * rhs(v); };\n                case optoken::divide: return [lhs, rhs](const std::vector<double> &v) { return lhs(v) / rhs(v); };\n                default: BOOST_ASSERT(0); return rhs;\n            }\n            BOOST_ASSERT(0);\n            return rhs;\n        }\n\n        retFnT operator()(optoken const &o, retFnT const &rhs) const {\n            switch (o)\n            {\n                case optoken::positive: return [rhs](const std::vector<double> &v) { return rhs(v); };\n                case optoken::negative:  return [rhs](const std::vector<double> &v) { return - rhs(v); };\n                default: BOOST_ASSERT(0); return rhs;\n            }\n            BOOST_ASSERT(0);\n            return rhs;\n        }\n\n        retFnT operator()(unary const& x) const {\n            retFnT rhs = boost::apply_visitor(*this, x.operand_);\n            return (*this)(x.operator_, rhs);\n        }\n\n        retFnT operator()(operation const& x, retFnT const& lhs) const\n        {\n            retFnT rhs = boost::apply_visitor(*this, x.operand_);\n            return (*this)(x.operator_, lhs, rhs);\n        }\n        retFnT operator()(expr const& x) const\n        {\n            retFnT state = boost::apply_visitor(*this, x.first);\n            for (const auto& oper : x.rest) {\n                state = (*this)(oper, state);\n            }\n            return state;\n        }\n    };\n}}}\n\nBOOST_FUSION_ADAPT_STRUCT(\n    client::math::ast::unary,\n    (client::math::ast::optoken, operator_)\n    (client::math::ast::operand, operand_)\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n    client::math::ast::operation,\n    (client::math::ast::optoken, operator_)\n    (client::math::ast::operand, operand_)\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n    client::math::ast::expr,\n    (client::math::ast::operand, first)\n    (std::list<client::math::ast::operation>, rest)\n)\n#endif\n", "meta": {"hexsha": "ee81e60126f54bd634f44320a35eae2b47454db9", "size": 9052, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mast.hpp", "max_stars_repo_name": "haptork/pawn", "max_stars_repo_head_hexsha": "b0c2431118de05eda59343fb98118dba54222133", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-02T06:39:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-09T07:38:20.000Z", "max_issues_repo_path": "include/mast.hpp", "max_issues_repo_name": "haptork/pawn", "max_issues_repo_head_hexsha": "b0c2431118de05eda59343fb98118dba54222133", "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/mast.hpp", "max_forks_repo_name": "haptork/pawn", "max_forks_repo_head_hexsha": "b0c2431118de05eda59343fb98118dba54222133", "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.4182509506, "max_line_length": 146, "alphanum_fraction": 0.5320371189, "num_tokens": 2163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.5242196528049688}}
{"text": "// Copyright 2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// clang-format off\n\n//[ getting_started_listing_03\n\n#include <boost/format.hpp>\n#include <boost/histogram.hpp>\n#include <cassert>\n#include <iostream>\n#include <sstream>\n\nint main() {\n  using namespace boost::histogram;\n\n  /*\n    Create a profile. Profiles does not only count entries in each cell, but\n    also compute the mean of a sample value in each cell.\n  */\n  auto p = make_profile(axis::regular<>(5, 0.0, 1.0));\n\n  /*\n    Fill profile with data, usually this happens in a loop. You pass the sample\n    with the `sample` helper function. The sample can be the first or last\n    argument.\n  */\n  p(0.1, sample(1));\n  p(0.15, sample(3));\n  p(0.2, sample(4));\n  p(0.9, sample(5));\n\n  /*\n    Iterate over bins and print profile.\n  */\n  std::ostringstream os;\n  for (auto&& x : indexed(p)) {\n    os << boost::format(\"bin %i [%3.1f, %3.1f) count %i mean %g\\n\") \n          % x.index() % x.bin().lower() % x.bin().upper() \n          % x->count() % x->value();\n  }\n\n  std::cout << os.str() << std::flush;\n  assert(os.str() == \"bin 0 [0.0, 0.2) count 2 mean 2\\n\"\n                     \"bin 1 [0.2, 0.4) count 1 mean 4\\n\"\n                     \"bin 2 [0.4, 0.6) count 0 mean 0\\n\"\n                     \"bin 3 [0.6, 0.8) count 0 mean 0\\n\"\n                     \"bin 4 [0.8, 1.0) count 1 mean 5\\n\");\n}\n\n//]\n", "meta": {"hexsha": "f3ebfcd8c8d4ff11f4e1f7c6ab446f84d90cf4cd", "size": 1491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/histogram/examples/getting_started_listing_03.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/histogram/examples/getting_started_listing_03.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/histogram/examples/getting_started_listing_03.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": 27.1090909091, "max_line_length": 79, "alphanum_fraction": 0.583501006, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5241850742457496}}
{"text": "/**\n * @file\n * @brief We build a tensor product mesh on a torus and apply uniform refinement\n * @author Anian Ruoss\n * @date   2018-10-20 16:27:17\n * @copyright MIT License\n */\n\n#include <boost/program_options.hpp>\n#include <iostream>\n\n#include <lf/refinement/mesh_hierarchy.h>\n#include \"lf/io/io.h\"\n\nusing size_type = lf::base::size_type;\n\nint main(int argc, char **argv) {\n  // define allowed command line arguments:\n  namespace po = boost::program_options;\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()(\"help\", \"Produce this help message\")(\n      \"num_steps\", po::value<size_t>()->default_value(4),\n      \"Number of uniform refinement steps\")(\n      \"num_x_cells\", po::value<size_type>()->default_value(4),\n      \"Number of cells in x direction\")(\n      \"num_y_cells\", po::value<size_type>()->default_value(4),\n      \"Number of cells in y direction\")(\n      \"top_right_corner\",\n      po::value<std::vector<double>>()->multitoken()->default_value(\n          std::vector<double>{1., 4.}, \"1., 4.\"),\n      \"Coordinates of top right corner of rectangle with bottom left at (0,0)\");\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\") != 0u) {\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  const size_t num_steps = vm[\"num_steps\"].as<size_t>();\n  const size_type num_x_cells = vm[\"num_x_cells\"].as<size_type>();\n  const size_type num_y_cells = vm[\"num_y_cells\"].as<size_type>();\n  std::vector<double> top_right_corner_coords =\n      vm[\"top_right_corner\"].as<std::vector<double>>();\n\n  std::shared_ptr<lf::mesh::hybrid2d::MeshFactory> mesh_factory_ptr =\n      std::make_shared<lf::mesh::hybrid2d::MeshFactory>(3);\n\n  // build tensor product mesh by specifying rectangle from which torus will\n  // be generated by identifying opposite edges\n  lf::mesh::hybrid2d::TorusMeshBuilder builder(mesh_factory_ptr);\n  builder.setBottomLeftCorner(Eigen::Vector2d{0., 0.});\n  builder.setTopRightCorner(Eigen::Vector2d{top_right_corner_coords.data()});\n  builder.setNoXCells(num_x_cells);\n  builder.setNoYCells(num_y_cells);\n  std::shared_ptr<lf::mesh::Mesh> mesh_ptr = builder.Build();\n\n  // output mesh information\n  const lf::mesh::Mesh &mesh = *mesh_ptr;\n  lf::mesh::utils::PrintInfo(mesh, std::cout);\n  std::cout << std::endl;\n\n  // build mesh hierarchy\n  lf::refinement::MeshHierarchy multi_mesh(mesh_ptr, mesh_factory_ptr);\n\n  for (int step = 0; step < num_steps; ++step) {\n    // obtain pointer to mesh on finest level\n    const size_type n_levels = multi_mesh.NumLevels();\n    std::shared_ptr<const lf::mesh::Mesh> mesh_fine =\n        multi_mesh.getMesh(n_levels - 1);\n\n    // print number of entities of various co-dimensions\n    std::cout << \"Mesh on level \" << n_levels - 1 << \": \"\n              << mesh_fine->NumEntities(2) << \" nodes, \"\n              << mesh_fine->NumEntities(1) << \" edges, \"\n              << mesh_fine->NumEntities(0) << \" cells,\" << std::endl;\n\n    lf::io::writeMatplotlib(*mesh_fine, std::string(\"torus_refinement\") +\n                                            std::to_string(step) + \".csv\");\n\n    lf::io::VtkWriter vtk_writer(mesh_fine, std::string(\"torus_refinement\") +\n                                                std::to_string(step) + \".vtk\");\n\n    multi_mesh.RefineRegular();\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "ab9cd232a5c688708ff5b7c5b68c371c759ada1e", "size": 3337, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/refinement/torus_refinement_demo.cc", "max_stars_repo_name": "Pascal-So/lehrfempp", "max_stars_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/refinement/torus_refinement_demo.cc", "max_issues_repo_name": "Pascal-So/lehrfempp", "max_issues_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/refinement/torus_refinement_demo.cc", "max_forks_repo_name": "Pascal-So/lehrfempp", "max_forks_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6703296703, "max_line_length": 80, "alphanum_fraction": 0.6523823794, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.5241850742457496}}
{"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 <CppUnitLite/TestHarness.h>\n\n#include <tests/smallExample.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/linear/GaussianISAM.h>\n#include <gtsam/inference/Ordering.h>\n\n#include <boost/assign/std/list.hpp> // for operator +=\nusing namespace boost::assign;\n#include <boost/range/adaptor/map.hpp>\nnamespace br { using namespace boost::adaptors; using namespace boost::range; }\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace example;\n\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\n/* ************************************************************************* */\nTEST( ISAM, iSAM_smoother )\n{\n  Ordering ordering;\n  for (int t = 1; t <= 7; t++) ordering += X(t);\n\n  // Create smoother with 7 nodes\n  GaussianFactorGraph smoother = createSmoother(7);\n\n  // run iSAM for every factor\n  GaussianISAM actual;\n  for(boost::shared_ptr<GaussianFactor> factor: smoother) {\n    GaussianFactorGraph factorGraph;\n    factorGraph.push_back(factor);\n    actual.update(factorGraph);\n  }\n\n  // Create expected Bayes Tree by solving smoother with \"natural\" ordering\n  GaussianBayesTree expected = *smoother.eliminateMultifrontal(ordering);\n\n  // Verify sigmas in the bayes tree\n  for(const GaussianBayesTree::sharedClique& clique: expected.nodes() | br::map_values) {\n    GaussianConditional::shared_ptr conditional = clique->conditional();\n    EXPECT(!conditional->get_model());\n  }\n\n  // Check whether BayesTree is correct\n  EXPECT(assert_equal(GaussianFactorGraph(expected).augmentedHessian(), GaussianFactorGraph(actual).augmentedHessian()));\n\n  // obtain solution\n  VectorValues e; // expected solution\n  for (int t = 1; t <= 7; t++) e.insert(X(t), Vector::Zero(2));\n  VectorValues optimized = actual.optimize(); // actual solution\n  EXPECT(assert_equal(e, optimized));\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "07323e0fc6046b775c5d4a4c813e7ff5587d8c04", "size": 2526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testGaussianISAM.cpp", "max_stars_repo_name": "karamach/gtsam", "max_stars_repo_head_hexsha": "35f9b710163a1d14d8dc4fcf50b8dce6e0bf7e5b", "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/testGaussianISAM.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/testGaussianISAM.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": 33.2368421053, "max_line_length": 121, "alphanum_fraction": 0.6195566112, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5241850616670952}}
{"text": "#include <mtl/dense1D.h>\n#include <mtl/mtl.h>\n#include <mtl/utils.h>\n\n\n/*\n  example output:\n\n  [7,7,7,7,7,7,7,7,7,7]\n\n  */\n\nint\nmain()\n{\n  using namespace mtl;\n  //begin\n  dense1D< double > x(10,2);\n  dense1D< double > y(10,3);\n  add(scaled(x,2), y, y);\n  print_vector(y);\n  //end\n  return 0;\n}\n", "meta": {"hexsha": "29c55ebcdc94a6370db5830833ae92848e2a97ab", "size": 295, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/vecvec_add.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/tools/mtl-2.0/contrib/examples/vecvec_add.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/tools/mtl-2.0/contrib/examples/vecvec_add.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": 11.8, "max_line_length": 28, "alphanum_fraction": 0.5762711864, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5241850616670951}}
{"text": "#pragma once\n#include <tuple>\n#include <cfloat>\n#include <Eigen/Core>\n\n#include \"Node.hpp\"\n#include \"Context.hpp\"\n\nnamespace geos\n{\n\tnamespace geom\n\t{\n\t\tclass Geometry;\n\t\tclass Polygon;\n\t\tclass CoordinateArraySequence;\n\t}\n\tnamespace operation\n\t{\n\t\tnamespace buffer {}\n\t\tnamespace distance {}\n\t}\n}\n\nnamespace cgl\n{\n\tnamespace gg = geos::geom;\n\tnamespace gob = geos::operation::buffer;\n\tnamespace god = geos::operation::distance;\n\n\tbool ReadDouble(double& output, const std::string& name, const Record& record, std::shared_ptr<Context> environment);\n\n\tstd::tuple<double, double> ReadVec2Packed(const PackedRecord& record);\n\n\tstruct Path\n\t{\n\t\tstd::unique_ptr<gg::CoordinateArraySequence> cs;\n\t\tstd::vector<double> distances;\n\t};\n\n\tPath ReadPathPacked(const PackedRecord& record);\n\n\tstruct Transform\n\t{\n\t\tusing Mat3x3 = Eigen::Matrix<double, 3, 3, 0, 3, 3>;\n\n\t\tTransform()\n\t\t{\n\t\t\tinit();\n\t\t}\n\n\t\tTransform(double px, double py, double sx = 1, double sy = 1, double angle = 0)\n\t\t{\n\t\t\tinit(px, py, sx, sy, angle);\n\t\t}\n\n\t\tTransform(const Mat3x3& mat) :mat(mat) {}\n\n\t\tTransform(const Record& record, std::shared_ptr<Context> pEnv);\n\n\t\tvoid init(double px = 0, double py = 0, double sx = 1, double sy = 1, double angle = 0);\n\n\t\tTransform operator*(const Transform& other)const\n\t\t{\n\t\t\treturn static_cast<Mat3x3>(mat * other.mat);\n\t\t}\n\n\t\tEigen::Vector2d product(const Eigen::Vector2d& v)const;\n\n\t\tvoid printMat()const;\n\n\tprivate:\n\t\tMat3x3 mat;\n\t};\n\n\tstruct TransformPacked\n\t{\n\t\tusing Mat3x3 = Eigen::Matrix<double, 3, 3, 0, 3, 3>;\n\n\t\tTransformPacked()\n\t\t{\n\t\t\tinit();\n\t\t}\n\n\t\tTransformPacked(double px, double py, double sx = 1, double sy = 1, double angle = 0)\n\t\t{\n\t\t\tinit(px, py, sx, sy, angle);\n\t\t}\n\n\t\tTransformPacked(const Mat3x3& mat) :mat(mat) {}\n\n\t\tTransformPacked(const PackedRecord& record, std::shared_ptr<Context> pEnv);\n\n\t\tvoid init(double px = 0, double py = 0, double sx = 1, double sy = 1, double angle = 0);\n\n\t\tTransformPacked operator*(const TransformPacked& other)const\n\t\t{\n\t\t\treturn static_cast<Mat3x3>(mat * other.mat);\n\t\t}\n\n\t\tEigen::Vector2d product(const Eigen::Vector2d& v)const;\n\n\t\tvoid printMat()const;\n\n\tprivate:\n\t\tMat3x3 mat;\n\t};\n\n\tclass BoundingRect\n\t{\n\tpublic:\n\n\t\tBoundingRect() = default;\n\n\t\tBoundingRect(const Vector<Eigen::Vector2d>& vs)\n\t\t{\n\t\t\tadd(vs);\n\t\t}\n\n\t\tvoid add(const Eigen::Vector2d& v);\n\n\t\tvoid add(const Vector<Eigen::Vector2d>& vs);\n\n\t\tbool intersects(const BoundingRect& other)const\n\t\t{\n\t\t\treturn std::max(m_min.x(), other.m_min.x()) < std::min(m_max.x(), other.m_max.x())\n\t\t\t\t&& std::max(m_min.y(), other.m_min.y()) < std::min(m_max.y(), other.m_max.y());\n\t\t}\n\n\t\tbool includes(const Eigen::Vector2d& point)const\n\t\t{\n\t\t\treturn m_min.x() < point.x() && point.x() < m_max.x()\n\t\t\t\t&& m_min.y() < point.y() && point.y() < m_max.y();\n\t\t}\n\n\t\tEigen::Vector2d pos()const\n\t\t{\n\t\t\treturn m_min;\n\t\t}\n\n\t\tEigen::Vector2d center()const\n\t\t{\n\t\t\treturn (m_min + m_max)*0.5;\n\t\t}\n\n\t\tEigen::Vector2d width()const\n\t\t{\n\t\t\treturn m_max - m_min;\n\t\t}\n\n\t\tdouble area()const\n\t\t{\n\t\t\tconst auto wh = width();\n\t\t\treturn wh.x()*wh.y();\n\t\t}\n\n\tprivate:\n\t\tEigen::Vector2d m_min = Eigen::Vector2d(DBL_MAX, DBL_MAX);\n\t\tEigen::Vector2d m_max = Eigen::Vector2d(-DBL_MAX, -DBL_MAX);\n\t};\n\n\tbool ReadPolygon(Vector<Eigen::Vector2d>& output, const List& vertices, std::shared_ptr<Context> pEnv, const Transform& transform);\n\n\tvoid GetBoundingBoxImpl(BoundingRect& output, const List& list, std::shared_ptr<Context> pEnv, const Transform& transform);\n\n\tvoid GetBoundingBoxImpl(BoundingRect& output, const Record& record, std::shared_ptr<Context> pEnv, const Transform& parent = Transform());\n\n\tboost::optional<BoundingRect> GetBoundingBox(const Val& value, std::shared_ptr<Context> pEnv);\n\n\tusing PolygonsStream = std::multimap<double, std::string>;\n\t\n\tstd::string GetGeometryType(gg::Geometry* geometry);\n\n\tgg::Polygon* ToPolygon(const Vector<Eigen::Vector2d>& exterior);\n\n\tvoid GeosPolygonsConcat(std::vector<gg::Geometry*>& head, const std::vector<gg::Geometry*>& tail);\n\n\tstd::vector<gg::Geometry*> GeosFromRecord(const Val& value, std::shared_ptr<cgl::Context> pEnv, const cgl::Transform& transform = cgl::Transform());\n\n\tstd::vector<gg::Geometry*> GeosFromRecordPacked(const PackedVal& value, std::shared_ptr<cgl::Context> pEnv, const cgl::TransformPacked& transform = cgl::TransformPacked());\n\n\tRecord GetPolygon(const gg::Polygon* poly, std::shared_ptr<cgl::Context> pEnv);\n\n\tList GetShapesFromGeos(const std::vector<gg::Geometry*>& polygons, std::shared_ptr<cgl::Context> pEnv);\n\n\tPackedList GetPackedShapesFromGeos(const std::vector<gg::Geometry*>& polygons);\n\n\tbool OutputSVG(std::ostream& os, const Val& value, std::shared_ptr<Context> pEnv);\n\n\tbool OutputSVG2(std::ostream& os, const Val& value, std::shared_ptr<Context> pEnv, const std::string& name);\n}\n", "meta": {"hexsha": "e64be8dfc0cc258e07f732bcb79f65f545bbbfde", "size": 4755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Pita/Vectorizer.hpp", "max_stars_repo_name": "tsukimizake/Pita", "max_stars_repo_head_hexsha": "8da387004823589fd774c473b090cc052574b682", "max_stars_repo_licenses": ["MIT"], "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/Pita/Vectorizer.hpp", "max_issues_repo_name": "tsukimizake/Pita", "max_issues_repo_head_hexsha": "8da387004823589fd774c473b090cc052574b682", "max_issues_repo_licenses": ["MIT"], "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/Pita/Vectorizer.hpp", "max_forks_repo_name": "tsukimizake/Pita", "max_forks_repo_head_hexsha": "8da387004823589fd774c473b090cc052574b682", "max_forks_repo_licenses": ["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.8952879581, "max_line_length": 173, "alphanum_fraction": 0.6904311251, "num_tokens": 1415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5240258219635922}}
{"text": "// Eigen\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\n// OpenCV\n#include <opencv2/opencv.hpp>\n\n// ROS\n#include <ros/ros.h>\n#include <nodelet/nodelet.h>\n#include <image_transport/image_transport.h>\n#include <image_transport/subscriber_filter.h>\n#include <message_filters/subscriber.h>\n#include <message_filters/synchronizer.h>\n#include <message_filters/sync_policies/exact_time.h>\n#include <message_filters/sync_policies/approximate_time.h>\n#include <cv_bridge/cv_bridge.h>\n#include <std_msgs/Float64MultiArray.h>\n\n#include <crane_msgs/CranePendulumImagePoints.h>\n\nnamespace crane_vision\n{\nusing namespace sensor_msgs;\nusing namespace message_filters::sync_policies;\n\nusing ProjectionMatrix = Eigen::Matrix<double, 3, 4>;\nusing Vector3d = Eigen::Matrix<double, 3, 1>;\nusing StateVector = Eigen::Matrix<double, 6, 1>;\nusing TransitionMatrix = Eigen::Matrix<double, 6, 6>;\nusing CovarianceMatrix = Eigen::Matrix<double, 6, 6>;\nusing AccelerationVector = Eigen::Vector2d;\n\nVector3d dlt(const Eigen::Vector2d& c0, const Eigen::Vector2d& c1, const Eigen::Vector2d& c2,\n             const ProjectionMatrix& P0, const ProjectionMatrix& P1, const ProjectionMatrix P2)\n{\n  Eigen::Matrix<double, 6, 4> X;\n  X.row(0) = c0(0) * P0.row(2) - P0.row(0);\n  X.row(1) = c0(1) * P0.row(2) - P0.row(1);\n  X.row(2) = c1(0) * P1.row(2) - P1.row(0);\n  X.row(3) = c1(1) * P1.row(2) - P1.row(1);\n  X.row(4) = c2(0) * P2.row(2) - P2.row(0);\n  X.row(5) = c2(1) * P2.row(2) - P2.row(1);\n\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(X, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  Eigen::MatrixXd V = svd.matrixV();\n\n  Eigen::Vector3d L = Eigen::Vector3d::Zero();\n  double scale = V(3, 3);\n  if (scale > 1e-8)\n  {\n    L = V.col(3).topRows(3) / scale;\n  }\n  return L;\n}\n\nVector3d findLine(const Eigen::Vector2d& c01, const Eigen::Vector2d& c02, const Eigen::Vector2d& c11,\n                  const Eigen::Vector2d& c12, const Eigen::Vector2d& c21, const Eigen::Vector2d& c22,\n                  const ProjectionMatrix& P0, const ProjectionMatrix& P1, const ProjectionMatrix P2)\n{\n  Vector3d X1 = dlt(c01, c11, c21, P0, P1, P2);\n  Vector3d X2 = dlt(c02, c12, c22, P0, P1, P2);\n  Vector3d L = X2 - X1;\n  L.normalize();\n  return L;\n}\n\nStateVector fk(StateVector x, AccelerationVector u, double w, double L)\n{\n  double c0 = cos(x(0));\n  double c1 = cos(x(1));\n  double s0 = sin(x(0));\n  double s1 = sin(x(1));\n\n  StateVector x1 = StateVector::Zero();\n  x1(0) = x(2);\n  x1(1) = x(3);\n  x1(2) = (2.0 * x(2) * x(3) * s1 - w * s0 + (u(1) * c0 / L)) / c1;\n  x1(3) = -c1 * s1 * x(2) * x(2) - (u(0) * c1 + u(1) * s0 * s1) / L - w * c0 * s1;\n  return x1;\n}\n\nTransitionMatrix Fk(StateVector x, AccelerationVector u, double w, double L, double dt)\n{\n  double c0 = cos(x(0));\n  double c1 = cos(x(1));\n  double s0 = sin(x(0));\n  double s1 = sin(x(1));\n\n  TransitionMatrix X = TransitionMatrix::Identity();\n  X(0, 2) = dt;\n  X(1, 3) = dt;\n  X(2, 0) = -(dt * (w * c0 + (u(1) * s0) / L)) / c1;\n  X(2, 1) = 2.0 * dt * x(2) * x(3) + (dt * s1 * (2.0 * x(2) * x(3) * s1 - w * s0 + (u(1) * c0) / L)) / (c1 * c1);\n  X(2, 2) = (2.0 * dt * x(3) * s1) / c1 + 1.0;\n  X(2, 3) = (2.0 * dt * x(2) * s1) / c1;\n  X(3, 0) = dt * (w * s0 * s1 - (u[1] * c0 * s1) / L);\n  X(3, 1) = -dt * (x(2) * x(2) * c1 * c1 - x(2) * x(2) * s1 * s1 - (u(0) * s1 - u(1) * c1 * s0 / L) + w * c0 * c1);\n  X(3, 2) = -2.0 * dt * x(2) * c1 * s1;\n  return X;\n}\n\nauto ekf(Vector3d Lvec, AccelerationVector uk, Eigen::MatrixXd hat_Pkm1, Eigen::VectorXd hat_thetakm1, double r,\n         double dt)\n{\n  int D = 10;\n  double g = 9.81;\n  double L = r;\n  AccelerationVector u = uk;\n  Eigen::VectorXd x = hat_thetakm1;\n  Eigen::Matrix2d R;\n  R << 0.00377597, -0.00210312, -0.00210312, 0.00125147;\n\n  CovarianceMatrix Q = CovarianceMatrix::Zero();\n  Q.diagonal() << 0.00003, 0.00003, 0.0005, 0.0005, 0.0001, 0.0001;\n  Eigen::Matrix<double, 2, 6> H;\n  H << 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0;\n\n  TransitionMatrix Fi = Fk(x, u, g / r, L, dt);\n\n  Eigen::Vector2d zkp1;\n  zkp1 << atan2(-Lvec(1), Lvec(2)), atan2(Lvec(0), sqrt(Lvec(1) * Lvec(1) + Lvec(2) * Lvec(2)));\n\n  for (int i = 0; i < D; ++i)\n  {\n    x = x + fk(x, u, g / r, L) * dt / D;\n  }\n\n  Eigen::MatrixXd barP_kp1 = (Fi * hat_Pkm1 * Fi.transpose()) + Q;\n  Eigen::MatrixXd K_kp1 = barP_kp1 * H.transpose() * (R + H * barP_kp1 * H.transpose()).inverse();\n\n  Eigen::VectorXd hat_thetak = x + K_kp1 * (zkp1 - H * x);\n  Eigen::MatrixXd hat_Pk = (Eigen::Matrix<double, 6, 6>::Identity() - K_kp1 * H) * barP_kp1;\n\n  return std::make_tuple(hat_thetak, hat_Pk);\n}\n\nstruct CompareArea\n{\n  CompareArea(const std::vector<float>& areas) : areas_(&areas)\n  {\n  }\n  bool operator()(int a, int b) const\n  {\n    return (*areas_)[a] > (*areas_)[b];\n  }\n  const std::vector<float>* areas_;\n};\n\nclass CraneVisionEKF : public nodelet::Nodelet {\n\n  virtual void onInit();\n\n};\n\nclass CraneVisionNodelet : public nodelet::Nodelet\n{\n  virtual void onInit();\n\n  bool extractSphereCenters(const sensor_msgs::ImageConstPtr& image_msg,\n                            const sensor_msgs::CameraInfoConstPtr& info_msg, const cv::Rect& roi,\n                            std::vector<double>& points, bool debug, const std::string& winname);\n\n  void imageCb(const sensor_msgs::ImageConstPtr& image0_msg, const sensor_msgs::CameraInfoConstPtr& info0_msg,\n               const sensor_msgs::ImageConstPtr& image1_msg, const sensor_msgs::CameraInfoConstPtr& info1_msg,\n               const sensor_msgs::ImageConstPtr& image2_msg, const sensor_msgs::CameraInfoConstPtr& info2_msg);\n\n  boost::shared_ptr<image_transport::ImageTransport> it_;\n\n  /// Subscriptions\n  image_transport::SubscriberFilter image0_sub_, image1_sub_, image2_sub_;\n  message_filters::Subscriber<CameraInfo> image0_info_sub_, image1_info_sub_, image2_info_sub_;\n  typedef ExactTime<Image, CameraInfo, Image, CameraInfo, Image, CameraInfo> ExactPolicy;\n  typedef ApproximateTime<Image, CameraInfo, Image, CameraInfo, Image, CameraInfo> ApproximatePolicy;\n  typedef message_filters::Synchronizer<ExactPolicy> ExactSync;\n  typedef message_filters::Synchronizer<ApproximatePolicy> ApproximateSync;\n  boost::shared_ptr<ExactSync> exact_sync_;\n  boost::shared_ptr<ApproximateSync> approximate_sync_;\n\n  image_transport::CameraSubscriber camera_sub_;\n  ros::Publisher pub_;\n\n  int hmin_, hmax_, smin_, smax_, vmin_, vmax_;\n  cv::Rect roi0_, roi1_, roi2_;\n\n  Eigen::Matrix<double, 6, 6> hat_Pkm1_;\n  StateVector hat_thetakm1_;\n  ProjectionMatrix P0_, P1_, P2_;\n\n  bool debug_;\n};\n\nvoid CraneVisionNodelet::onInit()\n{\n  ros::NodeHandle& nh = getNodeHandle();\n  ros::NodeHandle& private_nh = getPrivateNodeHandle();\n  it_.reset(new image_transport::ImageTransport(nh));\n\n  // Synchronize inputs. Topic subscriptions happen on demand in the connection\n  // callback. Optionally do approximate synchronization.\n  int queue_size;\n  private_nh.param(\"queue_size\", queue_size, 5);\n  bool approx;\n  private_nh.param(\"approximate_sync\", approx, false);\n  if (approx)\n  {\n    approximate_sync_.reset(new ApproximateSync(ApproximatePolicy(queue_size), image0_sub_, image0_info_sub_,\n                                                image1_sub_, image1_info_sub_, image2_sub_, image2_info_sub_));\n    approximate_sync_->registerCallback(boost::bind(&CraneVisionNodelet::imageCb, this, _1, _2, _3, _4, _5, _6));\n  }\n  else\n  {\n    exact_sync_.reset(new ExactSync(ExactPolicy(queue_size), image0_sub_, image0_info_sub_, image1_sub_,\n                                    image1_info_sub_, image2_sub_, image2_info_sub_));\n    exact_sync_->registerCallback(boost::bind(&CraneVisionNodelet::imageCb, this, _1, _2, _3, _4, _5, _6));\n  }\n\n  std::vector<int> roi;\n  if (private_nh.getParam(\"roi0\", roi))\n  {\n    roi0_ = cv::Rect(roi[0], roi[1], roi[2], roi[3]);\n  }\n  else\n  {\n    NODELET_ERROR_STREAM(\"Did not find any roi0 parameters!\");\n  }\n  if (private_nh.getParam(\"roi1\", roi))\n  {\n    roi1_ = cv::Rect(roi[0], roi[1], roi[2], roi[3]);\n  }\n  else\n  {\n    NODELET_ERROR_STREAM(\"Did not find any roi1 parameters!\");\n  }\n  if (private_nh.getParam(\"roi2\", roi))\n  {\n    roi2_ = cv::Rect(roi[0], roi[1], roi[2], roi[3]);\n  }\n  else\n  {\n    NODELET_ERROR_STREAM(\"Did not find any roi2 parameters!\");\n  }\n\n  private_nh.param(\"debug\", debug_, false);\n\n  private_nh.param(\"hmin\", hmin_, 43);\n  private_nh.param(\"hmax\", hmax_, 73);\n  private_nh.param(\"smin\", smin_, 54);\n  private_nh.param(\"smax\", smax_, 250);\n  private_nh.param(\"vmin\", vmin_, 86);\n  private_nh.param(\"vmax\", vmax_, 255);\n\n  image0_sub_.subscribe(*it_, \"/camera0/image_raw\", 1);\n  image0_info_sub_.subscribe(nh, \"/camera0/camera_info\", 1);\n  image1_sub_.subscribe(*it_, \"/camera1/image_raw\", 1);\n  image1_info_sub_.subscribe(nh, \"/camera1/camera_info\", 1);\n  image2_sub_.subscribe(*it_, \"/camera2/image_raw\", 1);\n  image2_info_sub_.subscribe(nh, \"/camera2/camera_info\", 1);\n\n  pub_ = private_nh.advertise<crane_msgs::CranePendulumImagePoints>(\"points\", 1);\n\n  P0_ << 942.0, 0.0, 623.66, 0.0, 0.0, 942.0, 345.69, 0.0, 0.0, 0.0, 1.0, 0.0;\n  P1_ << 941.0, 0.0, 637.21, 220005.80000000002, 0.0, 941.0, 349.9, 0.0, 0.0, 0.0, 1.0, 0.0;\n  P2_ << 937.0, 0.0, 637.21, 437579.0, 0.0, 937.0, 381.54, 0.0, 0.0, 0.0, 1.0, 0.0;\n\n  hat_thetakm1_.setZero();\n  // hat_Pkm1_ << 0.0, 0.0, 0.0, 0.0, 0.04, -0.03;\n}\n\nbool CraneVisionNodelet::extractSphereCenters(const sensor_msgs::ImageConstPtr& image_msg,\n                                              const sensor_msgs::CameraInfoConstPtr& info_msg, const cv::Rect& roi,\n                                              std::vector<double>& points, bool debug, const std::string& winname)\n{\n  using namespace std;\n  using namespace cv;\n\n  Mat bgr8_image = cv_bridge::toCvShare(image_msg, \"bgr8\")->image;\n\n  Mat roi_image = bgr8_image(roi);\n\n  Mat hsv_image;\n  cvtColor(roi_image, hsv_image, CV_BGR2HSV);\n\n  Mat thresh_image;\n  inRange(hsv_image, Scalar(hmin_, smin_, vmin_), Scalar(hmax_, smax_, vmax_), thresh_image);\n\n  using Contours = vector<vector<Point> >;\n  using Hierarchy = vector<Vec4i>;\n  Contours contours;\n  Hierarchy hierarchy;\n\n  /// Find contours\n  findContours(thresh_image, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));\n  if (contours.size() > 1)\n  {\n    /// Get sort index based on contour area\n    vector<int> sort_idx(contours.size());\n    vector<float> areas(contours.size());\n    for (int n = 0; n < (int)contours.size(); n++)\n    {\n      sort_idx[n] = n;\n      areas[n] = contourArea(contours[n], false);\n    }\n    sort(sort_idx.begin(), sort_idx.end(), CompareArea(areas));\n\n    /// Get the moments\n    vector<Moments> mu(contours.size());\n    for (int i = 0; i < contours.size(); i++)\n    {\n      mu[i] = moments(contours[i], false);\n    }\n\n    ///  Get the mass centers:\n    vector<Point2d> mc(contours.size());\n    for (int i = 0; i < contours.size(); i++)\n    {\n      mc[i] = Point2d(mu[i].m10 / mu[i].m00, mu[i].m01 / mu[i].m00);\n    }\n\n    /// Swap to get right order\n    if (mc[sort_idx[1]].y > mc[sort_idx[0]].y)\n    {\n      points[0] = mc[sort_idx[1]].x;\n      points[1] = mc[sort_idx[1]].y;\n      points[2] = mc[sort_idx[0]].x;\n      points[3] = mc[sort_idx[0]].y;\n    }\n    else\n    {\n      points[0] = mc[sort_idx[0]].x;\n      points[1] = mc[sort_idx[0]].y;\n      points[2] = mc[sort_idx[1]].x;\n      points[3] = mc[sort_idx[1]].y;\n    }\n\n    if (debug)\n    {\n      circle(roi_image, Point2d(points[0], points[1]), 5, Scalar(0, 0, 255), -1, 8, 0);\n      circle(roi_image, Point2d(points[2], points[3]), 5, Scalar(255, 0, 0), -1, 8, 0);\n      imshow(winname, roi_image);\n      waitKey(30);\n    }\n  }\n}\n\nvoid CraneVisionNodelet::imageCb(const sensor_msgs::ImageConstPtr& image0_msg,\n                                 const sensor_msgs::CameraInfoConstPtr& info0_msg,\n                                 const sensor_msgs::ImageConstPtr& image1_msg,\n                                 const sensor_msgs::CameraInfoConstPtr& info1_msg,\n                                 const sensor_msgs::ImageConstPtr& image2_msg,\n                                 const sensor_msgs::CameraInfoConstPtr& info2_msg)\n{\n  using namespace std;\n  using namespace Eigen;\n\n  vector<double> points0{ 0.0, 0.0, 0.0, 0.0 };\n  vector<double> points1{ 0.0, 0.0, 0.0, 0.0 };\n  vector<double> points2{ 0.0, 0.0, 0.0, 0.0 };\n\n  extractSphereCenters(image0_msg, info0_msg, roi0_, points0, debug_, \"camera0\");\n  extractSphereCenters(image1_msg, info1_msg, roi1_, points1, debug_, \"camera1\");\n  extractSphereCenters(image2_msg, info2_msg, roi2_, points2, debug_, \"camera2\");\n\n  Vector2d center01 = Vector2d(points0[0] + roi0_.x, points0[1] + roi0_.y);\n  Vector2d center02 = Vector2d(points0[2] + roi0_.x, points0[3] + roi0_.y);\n  Vector2d center11 = Vector2d(points1[0] + roi1_.x, points1[1] + roi1_.y);\n  Vector2d center12 = Vector2d(points1[2] + roi1_.x, points1[3] + roi1_.x);\n  Vector2d center21 = Vector2d(points2[0] + roi2_.x, points2[1] + roi2_.y);\n  Vector2d center22 = Vector2d(points2[2] + roi2_.x, points2[3] + roi2_.y);\n\n  // Vector3d Lc0 = findLine(center01, center02, center11, center12, center21, center22, P0_, P1_, P2_);\n\n\n\n  // todo(Lars): Transform to inertial coordinatesA\n  // Vector3d Lvec = Lc0;\n\n  // std::tie(hat_thetakm1_, hat_Pkm1_) = ekf(Lvec, AccelerationVector(0.0,0.0), hat_thetakm1_, hat_Pkm1_, 1.05, 0.01);\n\n  crane_msgs::CranePendulumImagePoints msg;\n  // Reuse the synchronized time stamp\n  msg.header.stamp = image0_msg->header.stamp;\n  std::vector<double> data(12);\n  msg.points =\n      std::vector<double>{ points0[0] + roi0_.x, points0[1] + roi0_.y, points0[2] + roi0_.x, points0[3] + roi0_.y,\n                           points1[0] + roi1_.y, points1[1] + roi1_.y, points1[2] + roi1_.y, points1[3] + roi1_.y,\n                           points2[0] + roi2_.y, points2[1] + roi2_.y, points2[2] + roi2_.y, points2[3] + roi2_.y };\n  pub_.publish(msg);\n}\n\n}  // namespace crane_vision\n\n// Register nodelet\n#include <pluginlib/class_list_macros.h>\nPLUGINLIB_EXPORT_CLASS(crane_vision::CraneVisionNodelet, nodelet::Nodelet)", "meta": {"hexsha": "79507c8d40957d1ddd49ce8c5c2c96eca9abec47", "size": 13940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "crane_vision/src/crane_vision_nodelet.cpp", "max_stars_repo_name": "tingelst/crane", "max_stars_repo_head_hexsha": "e14bca2bd4e2397dce09180029223832aad9b070", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-22T08:50:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T03:04:18.000Z", "max_issues_repo_path": "crane_vision/src/crane_vision_nodelet.cpp", "max_issues_repo_name": "tingelst/crane", "max_issues_repo_head_hexsha": "e14bca2bd4e2397dce09180029223832aad9b070", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crane_vision/src/crane_vision_nodelet.cpp", "max_forks_repo_name": "tingelst/crane", "max_forks_repo_head_hexsha": "e14bca2bd4e2397dce09180029223832aad9b070", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-01-14T04:28:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T05:29:01.000Z", "avg_line_length": 35.2911392405, "max_line_length": 119, "alphanum_fraction": 0.6397417504, "num_tokens": 4830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5240258219635922}}
{"text": "// STL includes\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <vector>\n#include <random>\n#include <utility>\n#include <thread>\n\n// Local includes\n#include \"Merl.hpp\"\n#include <tests/Tests.hpp>\n#include <tests/SH.hpp>\n#include <include/Utils.hpp>\n#include <include/SphericalHarmonics.hpp>\n#include <include/DirectionsSampling.hpp>\n#include <include/SphericalIntegration.hpp>\n\n// GLM include\n#include <glm/glm.hpp>\n\n// Include Eigen\n#include <Eigen/Core>\n\nstruct MerlProjectionThread : public std::thread {\n\n   int order;\n   std::vector<Eigen::MatrixXf> cijs;\n\n   MerlProjectionThread(const MerlBRDF* brdf,\n                        const std::vector<Vector>* ws,\n                        int order, int skip, int nthread) :\n      std::thread(&MerlProjectionThread::run, this, brdf, ws, skip, order, nthread) {}\n\n   /* Pre-convolved the Zonal basis to perform smooth evaluation.\n    */\n   static void ApplyZonalFilter(Eigen::VectorXf& clm) {\n      const auto bmax = floor(sqrt(clm.size())-1);\n      for(unsigned int i=0; i<clm.size(); ++i) {\n         const auto b = floor(sqrt(i));\n         const auto f = exp(- pow(float(b)/float(bmax), 2));\n         clm[i] *= f;\n      }\n   }\n\n   void run(const MerlBRDF* brdf,\n            const std::vector<Vector>* dirs,\n            int skip, int order, int nthread) {\n\n      cijs = std::vector<Eigen::MatrixXf>(6, Eigen::MatrixXf::Zero(SH::Terms(order), SH::Terms(order)));\n\n      const int size = SH::Terms(order);\n      Eigen::VectorXf ylmo(size);\n      Eigen::VectorXf ylmi(size);\n      for(unsigned int i=skip; i<dirs->size(); i+=nthread) {\n         const Vector& wo = (*dirs)[i];\n\n         if(skip == 0) {\n            std::cout << \"Progress: \" << i << \" / \" << dirs->size() << \"     \\r\";\n            std::cout.flush();\n         }\n\n         // Skip below the horizon configuration\n         if(wo.z < 0.0) continue;\n         SH::FastBasis(wo, order, ylmo);\n\n         for(unsigned int j=0; j<dirs->size(); ++j) {\n            const Vector& wi = (*dirs)[j];\n            // Skip below the horizon configuration\n            if(wi.z < 0.0) continue;\n\n            // Evaluate the BRDF value\n            const auto rgb = brdf->value<Vector, Vector>(wi, wo);\n            SH::FastBasis(wi, order, ylmi);\n\n            // Apply filtering\n            //ApplyZonalFilter(ylmo);\n            //ApplyZonalFilter(ylmi);\n\n            Eigen::MatrixXf mat = ylmo * ylmi.transpose();\n#ifndef SYMMETRIZE\n            mat = 0.5f*(mat + mat.transpose());\n#endif\n            cijs[0] += rgb[0] * mat;\n            cijs[1] += rgb[1] * mat;\n            cijs[2] += rgb[2] * mat;\n            // Note: Here the correct weighting should be with respect to wi.z\n            // but I use wo.z since it allows to reduce the ringing drastically.\n#ifdef LOOKS_BETTER\n            cijs[3] += rgb[0] * wo.z * mat;\n            cijs[4] += rgb[1] * wo.z * mat;\n            cijs[5] += rgb[2] * wo.z * mat;\n#else // CORRECT\n            cijs[3] += rgb[0] * wi.z * mat;\n            cijs[4] += rgb[1] * wi.z * mat;\n            cijs[5] += rgb[2] * wi.z * mat;\n#endif\n         }\n      }\n   }\n};\n\nint MerlProjectionMatrix(const std::string& filename,\n                         int order = 15, int N = 1000) {\n\n   // Constants\n   const int size = SH::Terms(order);\n\n   // Load the BRDF\n   MerlBRDF brdf;\n   if(! brdf.read_brdf(filename)) {\n      std::cerr << \"Failed: unable to load the MERL brdf\" << std::endl;\n      return 1;\n   }\n\n   const auto k = filename.rfind('.');\n   std::string ofilename = filename;\n   ofilename.replace(k, std::string::npos, \".mats\");\n   std::cout << \"Will output to \\\"\" << ofilename << \"\\\"\" << std::endl;\n\n   // Values\n   std::vector<Eigen::MatrixXf> cijs(6, Eigen::MatrixXf::Zero(size, size));\n   const auto dirs = SamplingFibonacci<Vector>(N);\n\n   const int nbthreads = std::thread::hardware_concurrency();\n   std::vector<MerlProjectionThread*> threads;\n   for(int k=0; k<nbthreads; ++k) {\n      MerlProjectionThread* th = new MerlProjectionThread(&brdf, &dirs, order, k, nbthreads);\n      threads.push_back(th);\n   }\n\n   for(MerlProjectionThread* th : threads) {\n      th->join();\n      cijs[0] += th->cijs[0];\n      cijs[1] += th->cijs[1];\n      cijs[2] += th->cijs[2];\n      cijs[3] += th->cijs[3];\n      cijs[4] += th->cijs[4];\n      cijs[5] += th->cijs[5];\n      delete th;\n   }\n   const float factor = 16.0*M_PI*M_PI / float(N*N);\n   cijs[0] *= factor;\n   cijs[1] *= factor;\n   cijs[2] *= factor;\n   cijs[3] *= factor;\n   cijs[4] *= factor;\n   cijs[5] *= factor;\n\n   SaveMatrices(ofilename, cijs);\n\n   // Print values\n   std::string gfilename = filename;\n   gfilename.replace(k, std::string::npos, \".gnuplot\");\n   std::ofstream file(gfilename.c_str(), std::ios_base::trunc);\n   const float thetai = -0.5f*M_PI * 30.f/90.f;\n   const Vector wi(sin(thetai), 0, cos(thetai));\n   const auto ylmi = SH::FastBasis(wi, order);\n   Vector wo;\n   for(int i=0; i<90; ++i) {\n      const float theta = 0.5*M_PI * i / float(90);\n      wo.x = sin(theta);\n      wo.y = 0;\n      wo.z = cos(theta);\n\n      // Ref\n      const auto RGB = brdf.value<Vector, Vector>(wi, wo);\n      const float R = RGB[0];\n      const float G = RGB[1];\n      const float B = RGB[2];\n\n      // SH expansion\n      const auto ylmo = SH::FastBasis(wo, order);\n      const Eigen::VectorXf rlm = cijs[0] * ylmo;\n      const Eigen::VectorXf glm = cijs[1] * ylmo;\n      const Eigen::VectorXf blm = cijs[2] * ylmo;\n      const float r = ylmi.dot(rlm);\n      const float g = ylmi.dot(glm);\n      const float b = ylmi.dot(blm);\n\n      file << theta << \"\\t\" << r << \"\\t\" << g << \"\\t\" << b\n                    << \"\\t\" << R << \"\\t\" << G << \"\\t\" << B\n                    << std::endl;\n   }\n\n   int nb_fails = 0;\n   return nb_fails;\n}\n\nbool parseArguments(int argc, char** argv, std::string& filename,\n                    int& order, int& nb) {\n\n   // Loop over all the different elements of the command line and search for\n   // some patterns\n   for(int k=0; k<argc; ++k) {\n      if(argv[k] == std::string(\"-h\") || argv[k] == std::string(\"--help\")) {\n         std::cerr << \"Usage: merl2sh [options] filename.binary\" << std::endl;\n         return false;\n      }\n      if((argv[k] == std::string( \"-o\") || argv[k] == std::string(\"--order\")) && k+1<argc) {\n         order = std::atoi(argv[k+1]);\n      }\n      if((argv[k] == std::string( \"-n\") || argv[k] == std::string(\"--nb\")) && k+1<argc) {\n         nb = std::atoi(argv[k+1]);\n      }\n   }\n\n   // The filename to convert is the last argument of the command line.\n   if(argc > 1) {\n      filename = argv[argc-1];\n      return true;\n   } else {\n      return false;\n   }\n}\n\nint main(int argc, char** argv) {\n\n   int nb_fails = 0;\n   std::string filename;\n   int order = 3;\n   int nb = 1000;\n   if(! parseArguments(argc, argv, filename, order, nb)) {\n      return EXIT_SUCCESS;\n   }\n\n   // Load an example\n   nb_fails += MerlProjectionMatrix(argv[argc-1], order, nb);\n\n   if(nb_fails > 0) {\n      return EXIT_FAILURE;\n   } else {\n      return EXIT_SUCCESS;\n   }\n}\n", "meta": {"hexsha": "ef4a7ed5d8c2dfa029b21e58ba9a4a90dbabfc97", "size": 6992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/Merl2Sh.cpp", "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": "utils/Merl2Sh.cpp", "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": "utils/Merl2Sh.cpp", "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": 29.6271186441, "max_line_length": 104, "alphanum_fraction": 0.5514874142, "num_tokens": 2092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5240022293767795}}
{"text": "/*! \\file demo_boxplot_simple.cpp\n    \\brief An example to demonstrate simplest use of boxplot. See also boxplot_full.cpp for a wider range of use.\n*/\n\n// demo_boxplot_simple.cpp\n// \n// Copyright Jacob Voytko 2007\n// Copyright Paul A. Bristow 2008, 2009, 2021\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[boxplot_simple_1\n\n/*`\nBoxplot is a convenient way of graphically depicting groups of numerical data\nthrough their five-number summaries.\nShow 1st quartile, median and 3rd quartile as a box,\n95% confidence interval as whiskers,\noutliers and extreme outliers.\n\nSee [@http://en.wikipedia.org/wiki/Boxplot boxplot] and\n\nSome Implementations of the Boxplot\nMichael Frigge, David C. Hoaglin and Boris Iglewicz\nThe American Statistician, Vol. 43, No. 1 (Feb., 1989), pp. 50-54\n\nFirst we need a few includes to use Boost.Plot.\n*/\n\n#include <vector>\n // using std::vector;\n#include <cmath>\n//  using ::sin;\n#include <boost/svg_plot/svg_boxplot.hpp>\n\n#include <iostream>\n//  using std::cout;\n//  using std::endl;\n#include <exception>\n\n/*`Use two functions, 1/x and sin(x), to simulate distributions.\n*/\n\ndouble f(double x)\n{ // Effectively 1/x.\n  return 50 / x;\n}\n\ndouble g(double x)\n{ // Effectively sin(x).\n  return 60 + 25 * sin(x * 50);\n}\n//] [boxplot_simple_1]\n\nint main()\n{\n  using namespace boost::svg;\n  try\n  {\n//[boxplot_simple_2]\n/*`10 values are computed and stored in two `std::vector`s.\n*/\n  std::vector<double> data1;\n  std::vector<double> data2;\n\n  std::cout.precision(2);\n  for(double i = 0.1; i < 10; i += 0.1)\n  {   // Fill our vectors with 100 values:\n    double fv = f(i);\n    double gv = g(i);\n    // std::cout << i << ' ' << fv << ' ' << gv << std::endl; // Optionally display values?\n    data1.push_back(fv);\n    data2.push_back(gv);\n  }\n\n/*`A new boxplot is constructed and a few settings added.\n*/\n  svg_boxplot my_boxplot;\n\n  my_boxplot  // Title and axes labels.\n    .title(\"Boxplots of 1/x and sin(x) Functions\")\n    .x_label(\"Functions\")\n    .y_label(\"Population Size\")\n    .background_border_color(magenta);\n\n  my_boxplot.y_range(0, 100)  // Axis information.\n    .y_major_interval(20);\n\n/*`Add the two data series containers, and their labels, to the plot.\n*/\n  my_boxplot.plot(data1, \"[50 / x]\");\n  my_boxplot.plot(data2, \"[60 + 25 * sin(x * 50)]\");\n\n/*`Finally write the SVG plot to a file.\n*/\n  my_boxplot.write(\"boxplot_simple.svg\");\n/*`You can view the plot at boxplot_simple.svg.\"\n*/\n//] [boxplot_simple_2]\n  }\n  catch(const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n  \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n/*\n\nOutput:\n\nAutorun \"j:\\Cpp\\SVG\\debug\\demo_boxplot_simple.exe\"\n\nBuild Time 0:00\nBuild log was saved at \"file://j:\\Cpp\\SVG\\demo_boxplot_simple\\Debug\\BuildLog.htm\"\n\n\n*/\n\n", "meta": {"hexsha": "de7ac090f2d6a413c46bf40243b122345b731d35", "size": 3267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_boxplot_simple.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_boxplot_simple.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_boxplot_simple.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 24.9389312977, "max_line_length": 113, "alphanum_fraction": 0.6847260484, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.5240022281417159}}
{"text": "#include <Eigen/Core>\n#include <catch2/catch.hpp>\n\n#include <finitediff.hpp>\n\n#include <ipc/barrier/barrier.hpp>\n\nTEST_CASE(\"Test barrier derivatives\", \"[barrier]\")\n{\n    double dhat = GENERATE(range(-5, 2));\n    dhat = pow(10, dhat);\n\n    double d =\n        GENERATE_COPY(take(10, random(dhat / 2, 0.9 * dhat))); // \u2208 [0, d\u0302]\n    Eigen::Matrix<double, 1, 1> d_vec;\n    d_vec << d;\n\n    // Check gradient\n\n    Eigen::VectorXd fgrad(1);\n    fd::finite_gradient(\n        d_vec,\n        [&](const Eigen::VectorXd& d) { return ipc::barrier(d[0], dhat); },\n        fgrad);\n\n    Eigen::VectorXd grad(1);\n    grad << ipc::barrier_gradient(d, dhat);\n\n    CAPTURE(dhat, d, fgrad(0), grad(0));\n    CHECK(fd::compare_gradient(fgrad, grad));\n\n    // Check hessian\n\n    fd::finite_gradient(\n        d_vec,\n        [&](const Eigen::VectorXd& d) {\n            return ipc::barrier_gradient(d[0], dhat);\n        },\n        fgrad);\n\n    grad << ipc::barrier_hessian(d, dhat);\n\n    CAPTURE(dhat, d, fgrad(0), grad(0));\n    CHECK(fd::compare_gradient(fgrad, grad));\n}\n", "meta": {"hexsha": "c964630086026ed9b287fe1db1b0579637efccf5", "size": 1048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/barrier/test_barrier.cpp", "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": "tests/barrier/test_barrier.cpp", "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": "tests/barrier/test_barrier.cpp", "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": 22.7826086957, "max_line_length": 75, "alphanum_fraction": 0.5791984733, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.524002223480922}}
{"text": "#ifndef SPIRIT_SKIP_HTST\n\n#include <engine/HTST.hpp>\n#include <engine/Sparse_HTST.hpp>\n#include <engine/Vectormath.hpp>\n#include <engine/Manifoldmath.hpp>\n#include <engine/Hamiltonian_Heisenberg.hpp>\n#include <utility/Constants.hpp>\n#include <utility/Logging.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <GenEigsSolver.h>  // Also includes <MatOp/DenseGenMatProd.h>\n#include <SymEigsSolver.h>\n#include <MatOp/SparseSymMatProd.h>\n\n#include <GenEigsRealShiftSolver.h>\n\n#include <fmt/format.h>\n#include <fmt/ostream.h>\n\nnamespace C = Utility::Constants;\n\nnamespace Engine\n{\n    namespace Sparse_HTST\n    {\n\n        void Sparse_Get_Lowest_Eigenvector(const SpMatrixX & matrix, int nos, scalar & lowest_evalue, VectorX & lowest_evec)\n        {\n            Log(Utility::Log_Level::All, Utility::Log_Sender::HTST, \"        Using Spectra to compute lowest eigenmode...\");\n\n            VectorX evalues;\n            MatrixX evectors;\n\n            int n_steps = std::max(2, nos);\n\n            //  Create a Spectra solver\n            Spectra::SparseSymMatProd<scalar> op(matrix);\n            Spectra::SymEigsSolver< scalar, Spectra::SMALLEST_ALGE, Spectra::SparseSymMatProd<scalar> > matrix_spectrum(&op, 1, n_steps);\n\n            matrix_spectrum.init();\n            int nconv = matrix_spectrum.compute();\n\n            if (matrix_spectrum.info() == Spectra::SUCCESSFUL)\n            {\n                evalues = matrix_spectrum.eigenvalues().real();\n                evectors = matrix_spectrum.eigenvectors().real();\n            } else {\n                Log(Utility::Log_Level::All, Utility::Log_Sender::HTST, \"        Failed to calculate lowest eigenmode. Aborting!\");\n                return;\n            }\n\n            lowest_evalue = evalues[0];\n            lowest_evec = evectors.col(0);\n        }\n\n        // Project vector such that it is orthogonal to all vectors in orth\n        void _orth_project(VectorX & vector, const std::vector<VectorX> & orth)\n        {\n            for(const VectorX & cur : orth)\n            {\n                vector -= (vector.dot(cur)) * cur;\n            }\n        }\n\n        void Sparse_Get_Lowest_Eigenvectors_VP(const SpMatrixX & matrix, scalar max_evalue, scalarfield & evalues, std::vector<VectorX> & evecs)\n        {\n            Log(Utility::Log_Level::All, Utility::Log_Sender::HTST, fmt::format(\"    Computing eigenvalues smaller than {}\", max_evalue));\n\n            scalar tol = 1e-6;\n            scalar evalue_epsilon = 1e-4;\n            int n_log_step = 2500;\n            scalar cur = 2 * tol;\n            scalar m = 0.01;\n            scalar step_size = 1e-4;\n            int n_iter = 0;\n            int nos = matrix.rows()/2;\n\n            scalar sigma_shift = std::max(scalar(5.0), 2*scalar(max_evalue));\n\n            VectorX gradient      = VectorX::Zero(2*nos);\n            VectorX gradient_prev = VectorX::Zero(2*nos);\n            VectorX velocity      = VectorX::Zero(2*nos);\n            scalar cur_evalue_estimate;\n            scalar fnorm2, ratio, proj;\n            bool run = true;\n\n            // We try to find the lowest n_values eigenvalue/vector pairs\n            while(run)\n            {\n                VectorX x = VectorX::Random(2*nos); // Initialize solver with random normalized vector\n                x.normalize();\n\n                fnorm2 = 2*tol*tol;\n                n_iter = 0;\n                gradient_prev.setZero();\n                velocity.setZero();\n\n                bool search = true;\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST,     fmt::format(\"        Search for eigenpair\"));\n\n                while (search)\n                {\n                    // Compute gradient of unnormalized Rayleigh quotient\n                    gradient = 2 * matrix * x;\n\n                    cur_evalue_estimate = 0.5 * x.dot(gradient); // Update the current estimate of our evalue\n                    for (int i=0; i<evecs.size(); i++)\n                    {\n                        gradient += 2 * (sigma_shift - evalues[i]) * (evecs[i].dot(x)) * evecs[i]; // Add the shift so that we dont land on the same eigenvalues we had before. Effectively H -> H + (sigma - lambda) * v^T v, where (lambda, v) is an eigenvalue, eigenvector pair\n                    }\n\n                    // Project the gradient orthogonally wrt to x and the previous eigenvectors\n                    _orth_project(gradient, {x});\n\n                    velocity = 0.5 * (gradient + gradient_prev) / m;\n                    fnorm2 = gradient.squaredNorm();\n\n                    proj = velocity.dot(gradient);\n                    ratio = proj/fnorm2;\n\n                    if (proj<=0)\n                        velocity.setZero();\n                    else \n                        velocity = gradient*ratio;\n\n                    // Update x and renormalize\n                    x -= step_size * velocity + 0.5/m * step_size * gradient;\n                    x.normalize();\n\n                    // Update prev gradient\n                    gradient_prev = gradient;\n\n                    // Increment n_iter\n                    n_iter++;\n\n                    if(n_iter % n_log_step == 0)\n                        Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, fmt::format(\"        ... Iteration {}: Evalue estimate = {}, Grad. norm = {} (> {})\", n_iter, cur_evalue_estimate, std::sqrt(fnorm2), tol));\n\n                    search = (std::sqrt(fnorm2) > tol);\n                }\n\n                // Ideally we have found one eigenvalue/vector pair now\n                // We save the eigenvalue\n                evecs.push_back(x);\n                evalues.push_back(x.dot(matrix*x));\n\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST,     fmt::format(\"        Found an eigenpair after {} iterations\", n_iter));\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST,     fmt::format(\"        ... Eigenvalue  = {}\", evalues.back()));\n                if(2*nos>=4)\n                    Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, fmt::format(\"        ... Eigenvector = ({}, {}, {}, ..., {})\", evecs.back()[0], evecs.back()[1], evecs.back()[2], evecs.back()[2*nos-1]));\n                if (evalues.back() > max_evalue)\n                {\n                    Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, fmt::format(\"        No more eigenvalues < {} found. Stopping.\", max_evalue));\n                    run = false;\n                }\n            }\n        }\n\n        void Sparse_Get_Lowest_Eigenvector_VP(const SpMatrixX & matrix, int nos, const VectorX & init, scalar & lowest_evalue, VectorX & lowest_evec)\n        {\n            Log(Utility::Log_Level::All, Utility::Log_Sender::HTST, \"        Minimizing Rayleigh quotient to compute lowest eigenmode...\");\n            auto & x = lowest_evec;\n            x = init;\n            x.normalize();\n\n            scalar tol = 1e-6;\n            scalar cur = 2 * tol;\n            scalar m = 0.01;\n            scalar step_size = 1e-4;\n            int n_iter = 0;\n\n            VectorX gradient = VectorX::Zero(2*nos);\n            VectorX gradient_prev = VectorX::Zero(2*nos);\n            VectorX velocity = VectorX::Zero(2*nos);\n\n            VectorX mx; // temporary for matrix * x\n            scalar proj; // temporary for gradient * x\n            scalar fnorm2 = 2*tol*tol, ratio;\n\n            while (std::sqrt(fnorm2) > tol)\n            {\n                // Compute gradient of Rayleigh quotient\n                mx = matrix * x;\n                gradient = 2 * mx;\n                proj = gradient.dot(x);\n                gradient -= proj * x;\n\n                velocity = 0.5 * (gradient + gradient_prev) / m;\n                fnorm2 = gradient.squaredNorm();\n\n                proj = velocity.dot(gradient);\n                ratio = proj/fnorm2;\n\n                if (proj<=0)\n                    velocity.setZero();\n                else \n                    velocity = gradient*ratio;\n\n                // Update x and renormalize\n                x -= step_size * velocity + 0.5/m * step_size * gradient;\n                x.normalize();\n\n                // Update prev gradient\n                gradient_prev = gradient;\n\n                // Increment n_iter\n                lowest_evalue = x.dot(matrix * x);\n                n_iter++;\n            }\n\n            // Compute the eigenvalue\n            lowest_evalue = x.dot(matrix * x);\n            Log(Utility::Log_Level::All, Utility::Log_Sender::HTST, fmt::format(\"        Finished after {} iterations\", n_iter));\n        }\n\n        // Note the two images should correspond to one minimum and one saddle point\n        // Non-extremal images may yield incorrect Hessians and thus incorrect results\n        void Calculate(Data::HTST_Info & htst_info)\n        {\n            Log(Utility::Log_Level::All, Utility::Log_Sender::HTST, \"Sparse Prefactor calculation\");\n            bool lowest_mode_spectra = false;\n            htst_info.sparse = true;\n            htst_info.n_eigenmodes_keep = 0;\n\n            const scalar epsilon = 1e-4;\n            const scalar epsilon_force = 1e-8;\n\n            auto& image_minimum = *htst_info.minimum->spins;\n            auto& image_sp      = *htst_info.saddle_point->spins;\n\n            int nos = image_minimum.size();\n\n            Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Saving NO eigenvectors.\");\n\n            vectorfield force_tmp(nos, {0,0,0});\n            std::vector<std::string> block;\n\n            // TODO\n            bool is_afm = false;\n\n            // The gradient (unprojected)\n            Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Evaluation of the gradient at the initial configuration...\");\n            vectorfield gradient_minimum(nos, {0,0,0});\n            htst_info.minimum->hamiltonian->Gradient(image_minimum, gradient_minimum);\n\n            // Check if the configuration is actually an extremum\n            Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Checking if initial configuration is an extremum...\");\n            Vectormath::set_c_a(1, gradient_minimum, force_tmp);\n            Manifoldmath::project_tangential(force_tmp, image_minimum);\n            scalar fmax_minimum = Vectormath::max_norm(force_tmp);\n            if( fmax_minimum > epsilon_force )\n            {\n                Log(Utility::Log_Level::Error, Utility::Log_Sender::All, fmt::format(\n                    \"HTST: the initial configuration is not a converged minimum, its max. torque is above the threshold ({} > {})!\", fmax_minimum, epsilon_force ));\n                return;\n            }\n\n            // The gradient (unprojected)\n            Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Evaluation of the gradient at the transition configuration...\");\n            vectorfield gradient_sp(nos, {0,0,0});\n            htst_info.saddle_point->hamiltonian->Gradient(image_sp, gradient_sp);\n\n            // Check if the configuration is actually an extremum\n            Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Checking if transition configuration is an extremum...\");\n            Vectormath::set_c_a(1, gradient_sp, force_tmp);\n            Manifoldmath::project_tangential(force_tmp, image_sp);\n            scalar fmax_sp = Vectormath::max_norm(force_tmp);\n            if( fmax_sp > epsilon_force )\n            {\n                Log(Utility::Log_Level::Error, Utility::Log_Sender::All, fmt::format(\n                    \"HTST: the transition configuration is not a converged saddle point, its max. torque is above the threshold ({} > {})!\", fmax_sp, epsilon_force ));\n                return;\n            }\n\n            ////////////////////////////////////////////////////////////////////////\n            // Saddle point\n            int n_zero_modes_sp = 0;\n            scalarfield evalues_sp = scalarfield(0);\n            {\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"Calculation for the Saddle Point\");\n\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Evaluate tangent basis ...\");\n                SpMatrixX tangent_basis = SpMatrixX(3*nos, 2*nos);\n                Manifoldmath::sparse_tangent_basis_spherical(image_sp, tangent_basis);\n\n                // Evaluation of the Hessian...\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Evaluate the Hessian...\");\n                SpMatrixX sparse_hessian_sp(3*nos, 3*nos);\n                htst_info.saddle_point->hamiltonian->Sparse_Hessian(image_sp, sparse_hessian_sp);\n\n                // Transform into geodesic Hessian\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Transform Hessian into geodesic Hessian...\");\n                SpMatrixX sparse_hessian_sp_geodesic_3N(3*nos, 3*nos);\n                sparse_hessian_bordered_3N(image_sp, gradient_sp, sparse_hessian_sp, sparse_hessian_sp_geodesic_3N);\n                SpMatrixX sparse_hessian_sp_geodesic_2N = tangent_basis.transpose() * sparse_hessian_sp_geodesic_3N * tangent_basis;\n\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Evaluate lowest eigenmode of the Hessian...\");\n\n                std::vector<VectorX> evecs_sp = std::vector<VectorX>(0);\n                Sparse_Get_Lowest_Eigenvectors_VP(sparse_hessian_sp_geodesic_2N, epsilon, evalues_sp, evecs_sp);\n                scalar lowest_evalue = evalues_sp[0];\n                VectorX & lowest_evector = evecs_sp[0];\n\n                // Check if lowest eigenvalue < 0 (else it's not a SP)\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Check if actually a saddle point...\");\n                if( lowest_evalue > -epsilon )\n                {\n                    Log(Utility::Log_Level::Error, Utility::Log_Sender::All, fmt::format(\n                        \"HTST: the transition configuration is not a saddle point, its lowest eigenvalue is above the threshold ({} > {})!\", lowest_evalue, -epsilon ));\n                    return;\n                }\n                // Check if second-lowest eigenvalue < 0 (higher-order SP)\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Check if higher order saddle point...\");\n                int n_negative = 0;\n                for( int i=0; i < evalues_sp.size(); ++i )\n                    if( evalues_sp[i] < -epsilon )\n                        ++n_negative;\n\n                if( n_negative > 1 )\n                {\n                    Log(Utility::Log_Level::Error, Utility::Log_Sender::All, fmt::format(\n                        \"HTST: the image you passed is a higher order saddle point (N={})!\", n_negative ));\n                    return;\n                }\n\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Sparse LU Decomposition of geodesic Hessian...\");\n                Eigen::SparseLU<SpMatrixX, Eigen::COLAMDOrdering<int> > solver;\n                solver.analyzePattern(sparse_hessian_sp_geodesic_2N);\n                solver.factorize(sparse_hessian_sp_geodesic_2N);\n                htst_info.det_sp = solver.logAbsDeterminant() - std::log(-lowest_evalue);\n\n                // Perpendicular velocity\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Calculate dynamical contribution\");\n\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Evaluate the dynamical matrix\");\n                SpMatrixX velocity(3*nos, 3*nos);\n                Sparse_Calculate_Dynamical_Matrix(image_sp, htst_info.saddle_point->geometry->mu_s, sparse_hessian_sp_geodesic_3N, velocity);\n                SpMatrixX projected_velocity = tangent_basis.transpose() * velocity * tangent_basis;\n\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Solving H^-1 V q_1 ...\");\n                VectorX x(2*nos);\n                x = solver.solve(projected_velocity.transpose() * lowest_evector);\n                htst_info.s = std::sqrt(lowest_evector.transpose() * projected_velocity * x );\n            \n                // Checking for zero modes at the saddle point...\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Checking for zero modes at the saddle point...\");\n                for( int i=0; i < evalues_sp.size(); ++i )\n                {\n                    if( std::abs( evalues_sp[i] ) <= epsilon)\n                        ++n_zero_modes_sp;\n                }\n                // Deal with zero modes if any (calculate volume)\n                htst_info.volume_sp = 1;\n                if( n_zero_modes_sp > 0 )\n                {\n                    Log(Utility::Log_Level::All, Utility::Log_Sender::HTST, fmt::format(\"ZERO MODES AT SADDLE POINT (N={})\", n_zero_modes_sp));\n                    htst_info.volume_sp = HTST::Calculate_Zero_Volume(htst_info.saddle_point);\n                }\n            }\n\n            // TODO  // End saddle point\n            ////////////////////////////////////////////////////////////////////////\n\n            ////////////////////////////////////////////////////////////////////////\n            // Initial state minimum\n            int n_zero_modes_minimum = 0;\n            scalarfield evalues_min = scalarfield(0);\n            {\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"Calculation for the Minimum\");\n\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Evaluate tangent basis ...\");\n                SpMatrixX tangent_basis = SpMatrixX(3*nos, 2*nos);\n                Manifoldmath::sparse_tangent_basis_spherical(image_minimum, tangent_basis);\n\n                // Evaluation of the Hessian...\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Evaluate the Hessian...\");\n                SpMatrixX sparse_hessian_minimum = SpMatrixX(3*nos,3*nos);\n                htst_info.minimum->hamiltonian->Sparse_Hessian(image_minimum, sparse_hessian_minimum);\n\n                // Transform into geodesic Hessian\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Transforming Hessian into geodesic Hessian...\");\n                SpMatrixX sparse_hessian_geodesic_min_3N = SpMatrixX(3*nos, 3*nos);\n                sparse_hessian_bordered_3N(image_minimum, gradient_minimum, sparse_hessian_minimum, sparse_hessian_geodesic_min_3N);\n                SpMatrixX sparse_hessian_geodesic_min_2N = tangent_basis.transpose() * sparse_hessian_geodesic_min_3N * tangent_basis;\n\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Sparse LU Decomposition of geodesic Hessian...\");\n                Eigen::SparseLU<SpMatrixX, Eigen::COLAMDOrdering<int> > solver;\n                solver.analyzePattern(sparse_hessian_geodesic_min_2N);\n                solver.factorize(sparse_hessian_geodesic_min_2N);\n                htst_info.det_min = solver.logAbsDeterminant();\n\n                // Calculate modes at minimum (needed for zero-mode volume)\n                std::vector<VectorX> evecs_min = std::vector<VectorX>(0);\n                Sparse_Get_Lowest_Eigenvectors_VP(sparse_hessian_geodesic_min_2N, epsilon, evalues_min, evecs_min);\n\n                // Checking for zero modes at the minimum..\n                Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Checking for zero modes at the minimum ...\");\n                for( int i=0; i < evalues_min.size(); ++i )\n                {\n                    if( std::abs( evalues_min[i] ) <= epsilon)\n                        ++n_zero_modes_minimum;\n                    if( evalues_min[i] < 0 )\n                    {\n                        Log(Utility::Log_Level::Warning, Utility::Log_Sender::HTST, fmt::format(\"    Minimum has a negative mode with eigenvalue = {}!\", evalues_min[i])); // The Question is if we should terminate the calculation here or allow to continue since often the negatives cancel sqrt(-x) * sqrt(-x) = sqrt(x^2)\n                    }\n                }\n                // Deal with zero modes if any (calculate volume)\n                htst_info.volume_min = 1;\n                if( n_zero_modes_minimum > 0 )\n                {\n                    Log(Utility::Log_Level::All, Utility::Log_Sender::HTST, fmt::format(\"ZERO MODES AT MINIMUM (N={})\", n_zero_modes_minimum));\n                    htst_info.volume_min = HTST::Calculate_Zero_Volume(htst_info.minimum);\n                }\n            }\n            // End initial state minimum\n            ////////////////////////////////////////////////////////////////////////\n\n            ////////////////////////////////////////////////////////////////////////\n            // Calculation of the prefactor...\n            Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"Calculating prefactor...\");\n\n            // Calculate the exponent for the temperature-dependence of the prefactor\n            //      The exponent depends on the number of zero modes at the different states\n            htst_info.temperature_exponent = 0.5 * (n_zero_modes_minimum - n_zero_modes_sp);\n\n            // Calculate \"me\"\n            htst_info.me = std::pow(2*C::Pi * C::k_B, htst_info.temperature_exponent);\n\n            // Calculate Omega_0, i.e. the entropy contribution\n            htst_info.Omega_0 = std::sqrt(std::exp(htst_info.det_min - htst_info.det_sp));\n\n            scalar zero_mode_factor = 1;\n            for (int i=0; i<n_zero_modes_minimum; i++)\n                zero_mode_factor /= evalues_min[i];\n\n            for (int i=0; i<n_zero_modes_sp; i++)\n                zero_mode_factor *= evalues_sp[i+1];\n\n            zero_mode_factor = std::sqrt(zero_mode_factor);\n\n            htst_info.Omega_0 *= zero_mode_factor;\n\n            // Calculate the prefactor\n            htst_info.prefactor_dynamical = htst_info.me * htst_info.volume_sp / htst_info.volume_min * htst_info.s;\n            htst_info.prefactor = C::g_e / (C::hbar * 1e-12) * htst_info.Omega_0 * htst_info.prefactor_dynamical / ( 2*C::Pi );\n\n            Log.SendBlock(Utility::Log_Level::All, Utility::Log_Sender::HTST,\n                {\n                    \"---- Prefactor calculation successful!\",\n                    fmt::format(\"exponent      = {:^20e}\", htst_info.temperature_exponent),\n                    fmt::format(\"me            = {:^20e}\", htst_info.me),\n                    fmt::format(\"m = Omega_0   = {:^20e}\", htst_info.Omega_0),\n                    fmt::format(\"s             = {:^20e}\", htst_info.s),\n                    fmt::format(\"volume_sp     = {:^20e}\", htst_info.volume_sp),\n                    fmt::format(\"volume_min    = {:^20e}\", htst_info.volume_min),\n                    fmt::format(\"log |det_min| = {:^20e}\", htst_info.det_min),\n                    fmt::format(\"log |det_sp|  = {:^20e}\", htst_info.det_sp),\n                    fmt::format(\"0-mode factor = {:^20e}\", zero_mode_factor),\n                    fmt::format(\"hbar[meV*s]   = {:^20e}\", C::hbar*1e-12),\n                    fmt::format(\"v = dynamical prefactor = {:^20e}\", htst_info.prefactor_dynamical),\n                    fmt::format(\"prefactor               = {:^20e}\", htst_info.prefactor)\n                }, -1, -1);\n        }\n\n        void Sparse_Calculate_Dynamical_Matrix(const vectorfield & spins, const scalarfield & mu_s, const SpMatrixX & hessian, SpMatrixX & velocity)\n        {\n            constexpr scalar epsilon = 1e-10;\n            int nos = spins.size();\n\n            typedef Eigen::Triplet<scalar> T;\n            std::vector<T> tripletList;\n            tripletList.reserve(hessian.nonZeros());\n\n            auto levi_civita = [](int i, int j, int k) \n            {\n                return -0.5 * (j-i) * (k-j) * (i-k);\n            };\n\n            // We first compute the effective field temporary\n            auto b_eff = vectorfield(nos, {0,0,0});\n            for (int k=0; k<hessian.outerSize(); ++k)\n            {\n                for (SpMatrixX::InnerIterator it(hessian,k); it; ++it)\n                {\n                    int row = it.row(), col = it.col();\n                    scalar h = it.value();\n\n                    for(int nu=0; nu<3; nu++)\n                    {\n                        for(int gamma=0; gamma<3; gamma++)\n                        {\n                            if( (row-nu) % 3 != 0 || (col-gamma) % 3 != 0 || nu>row || gamma>col)\n                                continue;\n                            int i = (row-nu)/3.0;\n                            int j = (col-gamma)/3.0;\n                            b_eff[i][nu] += h * spins[j][gamma] / mu_s[i];\n                        }\n                    }\n                }\n            }\n\n            // Add the contributions from the effective field\n            for(int i=0; i<nos; i++)\n            {\n                for(int alpha=0; alpha<3; alpha++)\n                {\n                    for(int beta=0; beta<3; beta++)\n                    {\n                        for(int nu=0; nu<3; nu++)\n                        {\n                            scalar res = levi_civita(alpha, beta, nu) * b_eff[i][nu];\n                            if(std::abs(res) > epsilon)\n                                tripletList.push_back( T(3*i+alpha, 3*i+beta, res) );\n                        }\n                    }\n                }\n            }\n\n            // Iterate over non zero entries of hessian\n            for (int k=0; k<hessian.outerSize(); ++k)\n            {\n                for (SpMatrixX::InnerIterator it(hessian,k); it; ++it)\n                {\n                    int row = it.row(), col = it.col();\n                    scalar h = it.value();\n\n                    for( int mu = 0; mu < 3; mu++ )\n                    {\n                        for( int nu = 0; nu < 3; nu++ )\n                        {\n                            for( int alpha = 0; alpha < 3; alpha++ )\n                            {\n                                for( int beta = 0; beta < 3; beta++ )\n                                {\n                                    if( (row-nu) % 3 != 0 || (col-beta) % 3 != 0 || nu>row || beta>col )\n                                        continue;\n\n                                    int i = (row-nu)/3.0;\n                                    int j = (col-beta)/3.0;\n                                    scalar res = levi_civita(alpha, mu, nu) * spins[i][mu] * h / mu_s[i];\n                                    tripletList.push_back( T(3*i+alpha, 3*j+beta, res) );\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n\n            velocity.setFromTriplets(tripletList.begin(), tripletList.end());\n        }\n\n        void sparse_hessian_bordered_3N(const vectorfield & image, const vectorfield & gradient, const SpMatrixX & hessian, SpMatrixX & hessian_out)\n        {\n            // Calculates a 3Nx3N matrix in the bordered Hessian approach and transforms it into the tangent basis,\n            // making the result a 2Nx2N matrix. The bordered Hessian's Lagrange multipliers assume a local extremum.\n\n            int nos = image.size();\n            VectorX lambda(nos);\n            for (int i=0; i<nos; ++i)\n                lambda[i] = image[i].normalized().dot(gradient[i]);\n\n            // Construct hessian_out\n            typedef Eigen::Triplet<scalar> T;\n            std::vector<T> tripletList;\n            tripletList.reserve( hessian.nonZeros() + 3*nos );\n\n            // Iterate over non zero entries of hesiian\n            for (int k=0; k<hessian.outerSize(); ++k)\n            {\n                for (SpMatrixX::InnerIterator it(hessian,k); it; ++it)\n                {\n                    tripletList.push_back( T(it.row(), it.col(), it.value() ) );\n                }\n                int j = k % 3;\n                int i = (k - j) / 3;\n                tripletList.push_back( T(k,k, -lambda[i]) ); // Correction to the diagonal\n            }\n            hessian_out.setFromTriplets(tripletList.begin(), tripletList.end());\n        }\n\n        // NOTE WE ASSUME A SELFADJOINT MATRIX\n        void Sparse_Eigen_Decomposition(const SpMatrixX & matrix, VectorX & evalues, MatrixX & evectors)\n        {\n            // Create a Spectra solver\n            Eigen::SelfAdjointEigenSolver<SpMatrixX> matrix_solver(matrix);\n            evalues = matrix_solver.eigenvalues().real();\n            evectors = matrix_solver.eigenvectors().real();\n        }\n\n        void Sparse_Geodesic_Eigen_Decomposition(const vectorfield & image, const vectorfield & gradient, const SpMatrixX & hessian,\n            SpMatrixX & hessian_geodesic_3N, SpMatrixX & hessian_geodesic_2N, SpMatrixX & tangent_basis, VectorX & eigenvalues, MatrixX & eigenvectors)\n        {\n            Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"---------- Sparse Geodesic Eigen Decomposition\");\n\n            int nos = image.size();\n\n            // Calculate geodesic Hessian in 3N-representation\n            hessian_geodesic_3N = SpMatrixX(3*nos, 3*nos);\n            sparse_hessian_bordered_3N(image, gradient, hessian, hessian_geodesic_3N);\n\n            // Transform into geodesic Hessian\n            Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Transforming Hessian into geodesic Hessian...\");\n            hessian_geodesic_2N = SpMatrixX(2*nos, 2*nos);\n            hessian_geodesic_2N = tangent_basis.transpose() * hessian_geodesic_3N * tangent_basis;\n\n            // Calculate full eigenspectrum\n            Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"    Calculation of full eigenspectrum...\" );\n\n            eigenvalues = VectorX::Zero(2*nos);\n            eigenvectors = MatrixX::Zero(2*nos, 2*nos);\n\n            Sparse_Eigen_Decomposition(hessian_geodesic_2N, eigenvalues, eigenvectors);\n\n            Log(Utility::Log_Level::Info, Utility::Log_Sender::HTST, \"---------- Sparse Geodesic Eigen Decomposition Done\");\n        }\n\n    }\n}\n#endif", "meta": {"hexsha": "ae61b3568263d1e938fec0a47a41b03e6431cef8", "size": 29809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/engine/Sparse_HTST.cpp", "max_stars_repo_name": "bck2302000/spirit", "max_stars_repo_head_hexsha": "14ed7782bd23f4828bf23ab8136ae31a21037bb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2016-10-02T16:17:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T11:23:49.000Z", "max_issues_repo_path": "core/src/engine/Sparse_HTST.cpp", "max_issues_repo_name": "bck2302000/spirit", "max_issues_repo_head_hexsha": "14ed7782bd23f4828bf23ab8136ae31a21037bb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-09-24T12:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T18:27:18.000Z", "max_forks_repo_path": "core/src/engine/Sparse_HTST.cpp", "max_forks_repo_name": "bck2302000/spirit", "max_forks_repo_head_hexsha": "14ed7782bd23f4828bf23ab8136ae31a21037bb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2016-09-26T07:20:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T19:55:17.000Z", "avg_line_length": 47.924437299, "max_line_length": 319, "alphanum_fraction": 0.5326579221, "num_tokens": 6873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5239405517168885}}
{"text": "// std includes\n#include <vector>\n#include <iostream>\n#include <random> // random_device, default_random_engine, uniform_real_distribution\n#include <memory> // shared_ptr\n#include <cmath> // sin, cos\n// thirdparty includes\n#include <Eigen/Dense>\n// lib includes\n#include \"m0sh/uniform.h\"\n#include \"m0sh/structured_sub.h\"\n#include \"p0l/interpolation.h\"\n#include \"v0l/bin/file_data.h\"\n\nusing TypeScalar = double;\n// Space\nconst unsigned int DIM = 3;\nusing TypeVector = Eigen::Matrix<TypeScalar, DIM, 1>;\ntemplate<typename ...Args>\nusing TypeRef = Eigen::Ref<Args...>;\n// Mesh\ntemplate<typename ...Args>\nusing TypeContainer = std::vector<Args...>;\nusing TypeMeshStructured = m0sh::Structured<TypeVector, TypeRef, TypeContainer>;\nusing TypeMeshStructuredSub = m0sh::StructuredSub<TypeVector, TypeRef, TypeContainer>;\nusing TypeMeshStructuredUniform = m0sh::Uniform<TypeVector, TypeRef, TypeContainer>;\n// Data\nconst std::size_t order = 4; // interpolation order\n\ndouble f(const double x, const double y) {\n    return std::cos(x) + std::sin(y);\n}\n\nint main() { \n    // Init\n    v0l::FileData<float> data(\"../data/v.vtk\", 0);\n    // build length\n    std::vector<double> lengths(data.meta.spacing.size());\n    TypeVector origin;\n    for(unsigned int i = 0; i < lengths.size(); i++) {\n        lengths[i] = data.meta.spacing[i] * data.meta.dimensions[i];\n        origin[i] = data.meta.origin[i];\n    }\n    // build create mesh\n    std::shared_ptr<TypeMeshStructured> sMesh = std::make_shared<TypeMeshStructuredUniform>(data.meta.dimensions, lengths, origin, TypeContainer<bool>(DIM, true));\n    // interpolate\n    std::cout << \"interpolated value: \" << p0l::lagrangeMeshCell<TypeMeshStructured, v0l::FileData, float, TypeVector, TypeRef, TypeMeshStructuredSub>(sMesh, data, TypeVector::Random() * 0.5, order + 1) << std::endl;\n}\n", "meta": {"hexsha": "4542725f5a19e521320b85c4c8c34a2544d623b7", "size": 1820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/v0l/main.cpp", "max_stars_repo_name": "C0PEP0D/p0l", "max_stars_repo_head_hexsha": "090bfebd558c98e44ee5ecc583dad198a25e676b", "max_stars_repo_licenses": ["MIT"], "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/v0l/main.cpp", "max_issues_repo_name": "C0PEP0D/p0l", "max_issues_repo_head_hexsha": "090bfebd558c98e44ee5ecc583dad198a25e676b", "max_issues_repo_licenses": ["MIT"], "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/v0l/main.cpp", "max_forks_repo_name": "C0PEP0D/p0l", "max_forks_repo_head_hexsha": "090bfebd558c98e44ee5ecc583dad198a25e676b", "max_forks_repo_licenses": ["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.1428571429, "max_line_length": 216, "alphanum_fraction": 0.7098901099, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5239405499062029}}
{"text": "#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/topological_sort.hpp>\n#include <boost/range.hpp>\n#include <boost/range/adaptor/indexed.hpp>\n#include <deque>\n#include <iostream>\n#include <list>\n#include <string>\n#include <type_traits>\n#include <vector>\n\n// Couldn't find the actual example used in the text,\n// but the one from chapter 1 will do just fine it seems :-).\n// Mostly code serrouding the dfs visitor, which is a neat idea itself,\n// and a large part of chapter 3 of the boost::graph book.\n\nusing graph_type = boost::adjacency_list<boost::listS, boost::vecS, boost::directedS>;\n\ntypedef boost::graph_traits<graph_type>::vertex_descriptor vertex_t;\ntypedef boost::graph_traits<graph_type>::edge_descriptor edge_t;\n// white means undiscovered, gray means discovered but still searching descendants, and black\n// means the vertex and all of its descendants have been discovered.\nenum class color_type { white,\n    gray,\n    black };\n\nbool has_cycle_dfs(\n    const graph_type& g,\n    vertex_t u,\n    color_type* color)\n{\n    color[u] = color_type::gray;\n    boost::graph_traits<graph_type>::adjacency_iterator vi, vi_end;\n    for (boost::tie(vi, vi_end) = boost::adjacent_vertices(u, g); vi != vi_end; ++vi) {\n        if (color[*vi] == color_type::white) {\n            if (has_cycle_dfs(g, *vi, color)) {\n                return true;\n            } else if (color[*vi] == color_type::gray) {\n                return true;\n            }\n        }\n    }\n    color[u] = color_type::black;\n    return false;\n}\n\nbool has_cycle(const graph_type& g)\n{\n    std::vector<color_type> color(\n        boost::num_vertices(g),\n        color_type::white);\n\n    boost::graph_traits<graph_type>::vertex_iterator vi, vi_end;\n    for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {\n        if (color[*vi] == color_type::white) {\n            if (has_cycle_dfs(g, *vi, &color[0])) {\n                return true;\n            }\n        }\n    }\n\n    return false;\n}\n\ntemplate <typename Visitor>\nvoid dfs_v1(const graph_type& g, vertex_t u, color_type* color, Visitor vis)\n{\n    color[u] = color_type::gray;\n    vis.discover_vertex(u, g);\n\n    boost::graph_traits<graph_type>::out_edge_iterator ei, ei_end;\n    for (boost::tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei) {\n        // boost::target/ boost::source -> get start/end edge\n        if (color[boost::target(*ei, g)] == color_type::white) {\n            vis.tree_edge(*ei, g);\n            dfs_v1(g, target(*ei, g), color, vis);\n        } else if (color[target(*ei, g)] == color_type::gray) {\n            vis.back_edge(*ei, g);\n        } else {\n            vis.forward_or_cross_edge(*ei, g);\n        }\n    }\n\n    color[u] = color_type::black;\n    vis.finish_vertex(u, g);\n}\n\ntemplate <typename Visitor>\nvoid generic_dfs_v1(const graph_type& g, Visitor vis)\n{\n    std::vector<color_type> color(num_vertices(g), color_type::white);\n    boost::graph_traits<graph_type>::vertex_iterator vi, vi_end;\n    for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {\n        if (color[*vi] == color_type::white) {\n            dfs_v1(g, *vi, &color[0], vis);\n        }\n    }\n}\n\nstruct default_dfs_visitor {\n    template <typename V, typename G>\n    void discover_vertex(V, const G&) { }\n\n    template <typename E, typename G>\n    void tree_edge(E, const G&) { }\n\n    template <typename E, typename G>\n    void back_edge(E, const G&) { }\n\n    template <typename E, typename G>\n    void forward_or_cross_edge(E, const G&) { }\n\n    template <typename V, typename G>\n    void finish_vertex(V, const G&) { }\n};\n\nstruct topo_visitor : public default_dfs_visitor {\n    topo_visitor(vertex_t*& order)\n        : topo_order(order)\n    {\n    }\n\n    void finish_vertex(vertex_t u, const graph_type&)\n    {\n        *--topo_order = u;\n    }\n\n    vertex_t*& topo_order;\n};\n\nvoid topo_sort(const graph_type& g, vertex_t* topo_order)\n{\n    topo_visitor vis(topo_order);\n    generic_dfs_v1(g, vis);\n}\n\nstruct cycle_detector : public default_dfs_visitor{\n    cycle_detector(bool& cycle) : has_cycle(cycle) {}\n    void back_edge (edge_t, const graph_type&)\n    {\n        has_cycle = true;\n    }\n\n    bool& has_cycle;\n};\n\nbool has_cycle_vis(const graph_type& g)\n{\n    bool has_cycle = true;\n    cycle_detector vis(has_cycle);\n    generic_dfs_v1(g, vis);\n    return has_cycle;\n}\n\nint main()\n{\n    const char* tasks[] = {\n        \"pick up kids from school\",\n        \"buy groceries (and snack)\",\n        \"get cash at ATM\",\n        \"drop off kids at soccer practice\",\n        \"cook dinner\",\n        \"pick up kids from soccer\",\n        \"eat dinner\"\n    };\n\n    const int n_tasks = sizeof(tasks) / sizeof(char*);\n\n    graph_type g(n_tasks);\n    add_edge(0, 3, g);\n    add_edge(1, 3, g);\n    add_edge(1, 4, g);\n    add_edge(2, 1, g);\n    add_edge(3, 5, g);\n    add_edge(4, 6, g);\n    add_edge(5, 6, g);\n\n    std::cout << \"cycle detection: \" << (has_cycle(g) ? \"true\" : \"false\") << std::endl;\n    //std::deque<int> topo_order;\n\n    //topological_sort(g, std::front_inserter(topo_order),\n    //        vertex_index_map(identity_property_map()));\n\n    //for(const auto& [index, i] : topo_order\n    //        | boost::adaptors::indexed())\n    //{\n    //    std::cout << tasks[i.head] << std::endl;\n    //}\n\n    return 0;\n}\n", "meta": {"hexsha": "665e896f278d98e89c99d5bc33bc4c54fa0eeb87", "size": 5258, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "chapter3/visitor_dfs.cpp", "max_stars_repo_name": "Zilleplus/boost_graph", "max_stars_repo_head_hexsha": "65d6dee7d060fc9aa76a822fde55c244e9468b0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter3/visitor_dfs.cpp", "max_issues_repo_name": "Zilleplus/boost_graph", "max_issues_repo_head_hexsha": "65d6dee7d060fc9aa76a822fde55c244e9468b0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter3/visitor_dfs.cpp", "max_forks_repo_name": "Zilleplus/boost_graph", "max_forks_repo_head_hexsha": "65d6dee7d060fc9aa76a822fde55c244e9468b0d", "max_forks_repo_licenses": ["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.3854166667, "max_line_length": 93, "alphanum_fraction": 0.6173449981, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5238752239258961}}
{"text": "//  Copyright (c) 2014 Anton Bikineev\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//  Computes test data for the derivatives of the\n//  various bessel functions. v and x parameters are taken\n//  from bessel_*_data.ipp files. Results of derivatives\n//  are generated by the relations between the derivatives\n//  and Bessel functions, which actual implementation\n//  doesn't use. Results are printed to ~ 50 digits.\n//\n#include <fstream>\n#include <utility>\n#include <map>\n#include <iterator>\n#include <algorithm>\n\n#include <boost/multiprecision/mpfr.hpp>\n\n#include <boost/math/special_functions/bessel.hpp>\n\ntemplate <class T>\nT bessel_j_derivative_bare(T v, T x)\n{\n   return (v / x) * boost::math::cyl_bessel_j(v, x) - boost::math::cyl_bessel_j(v+1, x);\n}\n\ntemplate <class T>\nT bessel_y_derivative_bare(T v, T x)\n{\n   return (v / x) * boost::math::cyl_neumann(v, x) - boost::math::cyl_neumann(v+1, x);\n}\n\ntemplate <class T>\nT bessel_i_derivative_bare(T v, T x)\n{\n   return (v / x) * boost::math::cyl_bessel_i(v, x) + boost::math::cyl_bessel_i(v+1, x);\n}\n\ntemplate <class T>\nT bessel_k_derivative_bare(T v, T x)\n{\n   return (v / x) * boost::math::cyl_bessel_k(v, x) - boost::math::cyl_bessel_k(v+1, x);\n}\n\ntemplate <class T>\nT sph_bessel_j_derivative_bare(T v, T x)\n{\n   if((v < 0) || (floor(v) != v))\n      throw std::domain_error(\"\");\n   if(v == 0)\n      return -boost::math::sph_bessel(1, x);\n   return boost::math::sph_bessel(itrunc(v-1), x) - ((v + 1) / x) * boost::math::sph_bessel(itrunc(v), x);\n}\n\ntemplate <class T>\nT sph_bessel_y_derivative_bare(T v, T x)\n{\n   if((v < 0) || (floor(v) != v))\n      throw std::domain_error(\"\");\n   if(v == 0)\n      return -boost::math::sph_neumann(1, x);\n   return boost::math::sph_neumann(itrunc(v-1), x) - ((v + 1) / x) * boost::math::sph_neumann(itrunc(v), x);\n}\n\nusing FloatType = boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<200u> >;\n\nenum class BesselFamily: char\n{\n   J = 0,\n   Y,\n   I,\n   K,\n   j,\n   y\n};\n\nnamespace\n{\n\nconst unsigned kSignificand = 50u;\n\nconst std::map<BesselFamily, std::vector<std::string> > kSourceFiles = {\n   {BesselFamily::J, {\"bessel_j_data.ipp\", \"bessel_j_int_data.ipp\", \"bessel_j_large_data.ipp\"}},\n   {BesselFamily::Y, {\"bessel_y01_data.ipp\", \"bessel_yn_data.ipp\", \"bessel_yv_data.ipp\"}},\n   {BesselFamily::I, {\"bessel_i_data.ipp\", \"bessel_i_int_data.ipp\"}},\n   {BesselFamily::K, {\"bessel_k_data.ipp\", \"bessel_k_int_data.ipp\"}},\n   {BesselFamily::j, {\"sph_bessel_data.ipp\"}},\n   {BesselFamily::y, {\"sph_neumann_data.ipp\"}}\n};\n\nFloatType (*fp)(FloatType, FloatType) = ::bessel_j_derivative_bare;\n\nstd::string parseValue(std::string::iterator& iter)\n{\n   using std::isdigit;\n\n   auto value = std::string{};\n\n   while (!isdigit(*iter) && *iter != '-')\n      ++iter;\n   while (isdigit(*iter) || *iter == '.' || *iter == 'e' || *iter == '-' || *iter == '+')\n   {\n      value.push_back(*iter);\n      ++iter;\n   }\n   return value;\n}\n\nvoid replaceResultInLine(std::string& line)\n{\n   using std::isdigit;\n\n   auto iter = line.begin();\n\n   // parse v and x values from line and convert them to FloatType\n   auto v = FloatType{::parseValue(iter)};\n   auto x = FloatType{::parseValue(iter)};\n   auto result = fp(v, x).str(kSignificand);\n\n   while (!isdigit(*iter) && *iter != '-')\n      ++iter;\n   const auto where_to_write = iter;\n   while (isdigit(*iter) || *iter == '.' || *iter == 'e' || *iter == '-' || *iter == '+')\n      line.erase(iter);\n\n   line.insert(where_to_write, result.begin(), result.end());\n}\n\nvoid generateResultFile(const std::string& i_file, const std::string& o_file)\n{\n   std::ifstream in{i_file.c_str()};\n   std::ofstream out{o_file.c_str()};\n\n   auto line = std::string{};\n   while (!in.eof())\n   {\n      std::getline(in, line);\n      if (__builtin_expect(line.find(\"SC_\") != std::string::npos, 1))\n         ::replaceResultInLine(line);\n      out << line << std::endl;\n   }\n}\n\nvoid processFiles(BesselFamily family)\n{\n   const auto& family_files = kSourceFiles.find(family)->second;\n\n   std::for_each(std::begin(family_files), std::end(family_files),\n      [&](const std::string& src){\n         auto new_file = src;\n\n         const auto int_pos = new_file.find(\"int\");\n         const auto large_pos = new_file.find(\"large\");\n         const auto data_pos = new_file.find(\"data\");\n         const auto derivative_pos = (int_pos == std::string::npos ?\n            (large_pos == std::string::npos ? data_pos : large_pos) :\n            int_pos);\n\n         new_file.insert(derivative_pos, \"derivative_\");\n\n         ::generateResultFile(src, new_file);\n      });\n}\n\n} // namespace\n\nint main(int argc, char*argv [])\n{\n   auto functype = BesselFamily::J;\n   auto letter = std::string{\"J\"};\n\n   if(argc == 2)\n   {\n      if(std::strcmp(argv[1], \"--Y\") == 0)\n      {\n         functype = BesselFamily::Y;\n         fp = ::bessel_y_derivative_bare;\n         letter = \"Y\";\n      }\n      else if(std::strcmp(argv[1], \"--I\") == 0)\n      {\n         functype = BesselFamily::I;\n         fp = ::bessel_i_derivative_bare;\n         letter = \"I\";\n      }\n      else if(std::strcmp(argv[1], \"--K\") == 0)\n      {\n         functype = BesselFamily::K;\n         fp = ::bessel_k_derivative_bare;\n         letter = \"K\";\n      }\n      else if(std::strcmp(argv[1], \"--j\") == 0)\n      {\n         functype = BesselFamily::j;\n         fp = ::sph_bessel_j_derivative_bare;\n         letter = \"j\";\n      }\n      else if(std::strcmp(argv[1], \"--y\") == 0)\n      {\n         functype = BesselFamily::y;\n         fp = ::sph_bessel_y_derivative_bare;\n         letter = \"y\";\n      }\n      else\n         assert(0);\n   }\n\n   ::processFiles(functype);\n\n   return 0;\n}\n", "meta": {"hexsha": "a6cec8e69f8fa52eaaa5b4ee8fae1b1c03f87e30", "size": 5784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/tools/bessel_derivative_data_from_bessel_ipps.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/tools/bessel_derivative_data_from_bessel_ipps.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/tools/bessel_derivative_data_from_bessel_ipps.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": 27.0280373832, "max_line_length": 108, "alphanum_fraction": 0.6092669433, "num_tokens": 1725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5238752239258961}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// accumulator::statistics::variance_of_mean_normalized.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_IMPORTANCE_SAMPLING_STATISTICS_VARIANCE_OF_MEAN_NORMALIZED_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_IMPORTANCE_SAMPLING_STATISTICS_VARIANCE_OF_MEAN_NORMALIZED_HPP_ER_2009\n#include <boost/parameter/binding.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/apply.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/parameters/accumulator.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace accumulator{\n\nnamespace impl\n{\n\n    // Var(w/c) = Var(w) / c^2, where c = mean(w)\n    template<typename T>\n    class variance_of_mean_normalized \n            : public boost::accumulators::accumulator_base{\n        typedef boost::accumulators::dont_care dont_care_;\n    \n        typedef boost::accumulators::tag::variance tag_v_;\n        typedef boost::accumulators::tag::mean tag_m_;\n        typedef boost::accumulators::tag::accumulator tag_acc_;\n    \n        public:\n        typedef T result_type;\n        variance_of_mean_normalized(){}\n        variance_of_mean_normalized(dont_care_){}\n        void operator()(dont_care_)const{}\n\n        template<typename Args>\n        result_type result(const Args& args) const\n        {\n            typedef \n                typename boost::parameter::binding<Args,tag_acc_>::type cref_;\n            cref_ acc = args[boost::accumulators::accumulator];\n            T v = accumulators::extract_result<tag_v_>(acc);\n            T c = accumulators::extract_result<tag_m_>(acc);\n            return v / (c*c);\n        }\n    };\n\n}//impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::variance_of_mean_normalized\nnamespace tag\n{\n    struct variance_of_mean_normalized\n      : boost::accumulators::depends_on<\n        boost::accumulators::tag::mean,\n        boost::accumulators::tag::variance\n    >\n    {\n      typedef statistics::detail::accumulator::\n      \timpl::variance_of_mean_normalized<boost::mpl::_1> impl;\n\n    };\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::variance_of_mean_normalized\nnamespace extract\n{\n\n  template<typename AccSet>\n  typename\n    boost::mpl::apply<\n        AccSet,\n        tag::variance_of_mean_normalized\n    >::type::result_type\n    variance_of_mean_normalized(AccSet const& acc){\n        typedef tag::variance_of_mean_normalized the_tag;\n        return boost::accumulators::extract_result<the_tag>(acc);\n    }\n\n}\n\nusing extract::variance_of_mean_normalized;\n\n}// accumulator\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "3b8cdb6d671bbb4014642e8c4081790efda4d763", "size": 3470, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "importance_sampling/boost/statistics/detail/importance_sampling/statistics/variance_of_mean_normalized.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": "importance_sampling/boost/statistics/detail/importance_sampling/statistics/variance_of_mean_normalized.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": "importance_sampling/boost/statistics/detail/importance_sampling/statistics/variance_of_mean_normalized.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.3564356436, "max_line_length": 102, "alphanum_fraction": 0.621037464, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5238752228782638}}
{"text": "/*\n * point_kinematics.hpp\n *\n * Created on: Oct 24, 2018 23:05\n * Description: (reduced) point kinematics model, used for lattice generation\n *\n * Reference:\n *  [1] M. McNaughton and C. Urmson and J. M. Dolan and J. W. Lee. 2011.\n *    \u201cMotion Planning for Autonomous Driving with a Conformal Spatiotemporal\n * Lattice.\u201d In 2011 IEEE International Conference on Robotics and Automation,\n * 4889\u201395.\n *\n * Copyright (c) 2018 Ruixiang Du (rdu)\n */\n\n#ifndef POINT_KINEMATICS_HPP\n#define POINT_KINEMATICS_HPP\n\n#include <iostream>\n\n#include <eigen3/Eigen/Dense>\n\n#include <boost/numeric/odeint.hpp>\n\n#include \"state_lattice/details/motion_state.hpp\"\n\nnamespace robosw {\nclass PointKinematics {\n public:\n  struct Param {\n    Param(double _p0 = 0, double _p1 = 0, double _p2 = 0, double _p3 = 0,\n          double _sf = 0)\n        : p0(_p0), p1(_p1), p2(_p2), p3(_p3), sf(_sf) {}\n\n    double p0;\n    double p1;\n    double p2;\n    double p3;\n    double sf;\n\n    friend std::ostream &operator<<(std::ostream &os, const Param &p) {\n      os << \"(p0,p1,p2,p3,sf): \" << p.p0 << \" , \" << p.p1 << \" , \" << p.p2\n         << \" , \" << p.p3 << \" , \" << p.sf;\n      return os;\n    }\n  };\n\n  using state_type = std::vector<double>;\n\n  /////////////////////////////////////////////////////\n\n public:\n  PointKinematics() = default;\n  PointKinematics(double a, double b, double c, double d)\n      : a_(a), b_(b), c_(c), d_(d){};\n\n  // calculate intermediate parameters\n  void SetParameters(const Param &p);\n\n  // propagate system model\n  MotionState Propagate(const MotionState &init, const Param &p,\n                        double ds = 0.1);\n  StatePMatrix PropagateP(const StatePMatrix &init, const Param &p,\n                          double ds = 0.1);\n\n  // The following functions could be called externally ONLY when a_,b_,c_,d_\n  // have been set properly by\n  //  (1) construct the model with: PointKinematics(double a, double b, double\n  //  c, double d) (2) default construct and then use SetParameters() to set\n  //  parameters\n  inline MotionState Propagate(const MotionState &init, double sf, double ds) {\n    {\n      double sf_squared = sf * sf;\n\n      // theta_p and kappa_p could be calculated analytically\n      double theta_p = a_ * sf + b_ * sf_squared / 2.0 +\n                       c_ * sf_squared * sf / 3.0 +\n                       d_ * sf_squared * sf_squared / 4.0;\n      double kappa_p = a_ + b_ * sf + c_ * sf_squared + d_ * sf_squared * sf;\n\n      // calculate x_p, y_p numerically\n      double s = 0;\n      state_type x = {init.x, init.y};\n      while (s <= sf) {\n        // integrator_(*this, x, s, ds);\n        boost::numeric::odeint::integrate_const(\n            boost::numeric::odeint::runge_kutta4<state_type>(), *this, x, s,\n            s + ds, ds / 10.0);\n      }\n\n      return MotionState(x[0], x[1], theta_p, kappa_p);\n    }\n  }\n\n  std::vector<MotionState> GenerateTrajectoryPoints(const MotionState &init,\n                                                    double sf, double step,\n                                                    double ds = 0.1);\n\n  // Shall not be called by user, used for propagation by RK4 integrator class\n  void operator()(const state_type &x, state_type &xd, const double s);\n\n private:\n  double a_;\n  double b_;\n  double c_;\n  double d_;\n\n  inline void CalculateIntermediateParams(const Param &p);\n};\n}  // namespace robosw\n\n#endif /* POINT_KINEMATICS_HPP */\n", "meta": {"hexsha": "223b0866ddef80597a527d66e1e889afdf12a914", "size": 3404, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/planning/state_lattice/include/state_lattice/details/point_kinematics.hpp", "max_stars_repo_name": "rxdu/libnav", "max_stars_repo_head_hexsha": "d62c5d7d012cf891b4f1567087bdb1c8e2bfd625", "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/planning/state_lattice/include/state_lattice/details/point_kinematics.hpp", "max_issues_repo_name": "rxdu/libnav", "max_issues_repo_head_hexsha": "d62c5d7d012cf891b4f1567087bdb1c8e2bfd625", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-03-13T07:28:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T07:43:16.000Z", "max_forks_repo_path": "src/planning/state_lattice/include/state_lattice/details/point_kinematics.hpp", "max_forks_repo_name": "rxdu/libnav", "max_forks_repo_head_hexsha": "d62c5d7d012cf891b4f1567087bdb1c8e2bfd625", "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.1238938053, "max_line_length": 79, "alphanum_fraction": 0.5948883666, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5238752175452395}}
{"text": "#include <state_estimation/filters/ekf.h>\n#include <state_estimation/utilities/logging.h>\n#include <Eigen/Dense>\n\nnamespace state_estimation {\n\nvoid EKF::myPredict(const Eigen::VectorXd& u, double dt) {\n    system_model_->update(filter_state_.x, u, dt);\n\n    // Update the state and covariance\n    filter_state_.x = system_model_->g();\n    filter_state_.covariance =\n        system_model_->G() * filter_state_.covariance * system_model_->G().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 << \"EKF predicition update:\" << std::endl\n              << \"g=\" << printMatrix(system_model_->g()) << std::endl\n              << \"G=\" << std::endl\n              << printMatrix(system_model_->G()) << 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=\" << printMatrix(filter_state_.x) << std::endl\n              << \"Covariance=\" << std::endl\n              << printMatrix(filter_state_.covariance) << std::endl;\n#endif\n}\n\nvoid EKF::myCorrect(const Eigen::VectorXd& z, measurement_models::NonlinearMeasurementModel* model,\n                    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_H_T = filter_state_.covariance * model->H().transpose();\n    const Eigen::MatrixXd K = cov_H_T * (model->H() * cov_H_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 dx = K * model->subtractVectors(z, model->h());\n    filter_state_.x = system_model_->addVectors(filter_state_.x, dx);\n    filter_state_.covariance = (I - K * model->H()) * filter_state_.covariance;\n\n#ifdef DEBUG_STATE_ESTIMATION\n    std::cout << \"EKF measurement update:\" << std::endl\n              << \"h=\" << printMatrix(model->h()) << std::endl\n              << \"H=\" << std::endl\n              << printMatrix(model->H()) << std::endl\n              << \"Q=\" << std::endl\n              << printMatrix(model->covariance()) << std::endl\n              << \"K=\" << std::endl\n              << printMatrix(K) << std::endl\n              << \"Innovation=\" << printMatrix(dx) << 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": "33a8cf339a9bc40707aba34c61fdefd7d0d880e3", "size": 2785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/filters/ekf.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/ekf.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/ekf.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.8461538462, "max_line_length": 99, "alphanum_fraction": 0.5913824057, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5238752058315581}}
{"text": "#pragma once\n#include \"IntegerInterval.hpp\"\n#include \"Misc.hpp\"\n#include <algorithm>\n#include <boost/iterator/iterator_facade.hpp>\n#include <cassert>\n#include <vector>\n\nnamespace discreture\n{\n\n// An arithmetic progression is simply a set of the form\n// {a,a+d,a+2d,a+3d,...,a+kd}. Similar to python range(n,m,step).\ntemplate <class IntType>\nclass ArithmeticProgression\n{\npublic:\n    static_assert(std::is_integral<IntType>::value,\n                  \"Template parameter IntType must be integral\");\n    static_assert(std::is_signed<IntType>::value,\n                  \"Template parameter IntType must be signed\");\n    using value_type = IntType;\n    using difference_type = std::ptrdiff_t;\n    using size_type = difference_type;\n    class iterator;\n    using const_iterator = iterator;\n    using reverse_iterator = iterator;\n    using const_reverse_iterator = reverse_iterator;\n\npublic:\n    ////////////////////////////////////////////////////////////\n    /// \\brief Single integer constructor. It's usually better to use\n    /// integer_interval(n) instead (faster)\n    ///\n    /// \\param n is an integer >= 0\n    ///\n    /// \\return An abstract random-access container whose elements are\n    /// {0,1,2,...,n-1}\n    ///\n    ////////////////////////////////////////////////////////////\n    explicit ArithmeticProgression(IntType n) : from_(0), to_(n), step_(1)\n    {\n        assert(n >= 0);\n    }\n\n    //////////////////////////////////////////\n    /// \\brief Constructor. Automatically detects wheter step size is positive\n    /// or negative and adjusts accordingly \\param n is an integer \\return an\n    /// abstract random-access container whose elements are\n    /// {n,n+step,n+2*step,...} up to (and not including) t_to.\n    //////////////////////////////////////////\n    ArithmeticProgression(IntType from, IntType to, IntType step = 1)\n        : from_(from), to_(to), step_(step)\n    {\n        assert(step_ != 0);\n        if (step_ > 0 && to_ < from_)\n            to_ = from_;\n        if (step_ < 0 && to_ > from_)\n            to_ = from_;\n\n        auto d = modulo<IntType>(from_ - to_, step_);\n\n        if (step_ > 0)\n            to_ += d;\n        else\n        {\n            to_ += d + step_;\n            if (d == 0)\n                to_ -= step_;\n        }\n    }\n\n    size_type size() const\n    {\n        auto t = to_ + modulo<difference_type>(from_ - to_, step_);\n        return (t - from_)/step_;\n    }\n\n    ////////////////////////////////////////////////////////////\n    /// \\brief Random access iterator class.\n    ////////////////////////////////////////////////////////////\n    class iterator\n        : public boost::iterator_facade<iterator, const IntType&, boost::random_access_traversal_tag>\n    {\n    public:\n        explicit iterator(size_type t_from = 0, size_type t_step = 1)\n            : m_ID(t_from), step_(t_step)\n        {}\n\n        size_type step() const { return step_; }\n\n    private:\n        void increment() { m_ID += step_; }\n\n        void decrement() { m_ID -= step_; }\n\n        const IntType& dereference() const { return m_ID; }\n\n        void advance(difference_type n) { m_ID += n*step_; }\n\n        bool equal(const iterator& it) const { return m_ID == it.m_ID; }\n\n        difference_type distance_to(const iterator& it) const\n        {\n            assert(step_ != 0);\n            return (static_cast<difference_type>(it.m_ID) -\n                    static_cast<difference_type>(m_ID)) /\n              step_;\n        }\n\n    private:\n        IntType m_ID{0};\n        size_type step_{1};\n\n        friend class boost::iterator_core_access;\n        friend class ArithmeticProgression;\n    }; // end class iterator\n\n    iterator begin() const { return iterator(from_, step_); }\n    iterator end() const { return iterator(to_, step_); }\n\n    iterator rbegin() const { return iterator(to_ - step_, -step_); }\n    iterator rend() const { return iterator(from_ - step_, -step_); }\n\n    IntType operator[](size_type m) const { return from_ + step_*m; }\n\n    template <class Pred>\n    IntType partition_point(Pred p)\n    {\n        return *std::partition_point(begin(), end(), p);\n    }\n\nprivate:\n    IntType from_;\n    IntType to_;\n    IntType step_;\n}; // end class ArithmeticProgression\n\nusing arithmetic_progression = ArithmeticProgression<int>;\nusing big_arithmetic_progression = ArithmeticProgression<std::int64_t>;\n\n} // namespace discreture\n", "meta": {"hexsha": "4ae93e1d87025701222b145f3ee134efb4910694", "size": 4371, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Discreture/ArithmeticProgression.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/ArithmeticProgression.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/ArithmeticProgression.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": 30.5664335664, "max_line_length": 101, "alphanum_fraction": 0.5653168611, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5238025549186547}}
{"text": "// Copyright Paul Bristow 2007.\n// Copyright John Maddock 2006.\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_uniform.cpp\n\n#include <pch.hpp>\n\n#ifdef _MSC_VER\n#  pragma warning(disable: 4127) // conditional expression is constant.\n#  pragma warning(disable: 4100) // unreferenced formal parameter.\n#endif\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/floating_point_comparison.hpp>\n\n#include <boost/math/distributions/uniform.hpp>\n    using boost::math::uniform_distribution;\n#include <boost/math/tools/test.hpp>\n#include \"test_out_of_range.hpp\"\n\n#include <iostream>\n#include <iomanip>\n   using std::cout;\n   using std::endl;\n   using std::setprecision;\n#include <limits>\n  using std::numeric_limits;\n\ntemplate <class RealType>\nvoid check_uniform(RealType lower, RealType upper, RealType x, RealType p, RealType q, RealType tol)\n{\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::cdf(\n         uniform_distribution<RealType>(lower, upper),   // distribution.\n         x),  // random variable.\n         p,    // probability.\n         tol);   // tolerance.\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::cdf(\n         complement(\n            uniform_distribution<RealType>(lower, upper), // distribution.\n            x)),    // random variable.\n         q,    // probability complement.\n         tol);  // tolerance.\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::quantile(\n         uniform_distribution<RealType>(lower, upper),  // distribution.\n         p),   // probability.\n         x,  // random variable.\n         tol);  // tolerance.\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::quantile(\n         complement(\n            uniform_distribution<RealType>(lower, upper),  // distribution.\n            q)),     // probability complement.\n         x,                                             // random variable.\n         tol);  // tolerance.\n} // void check_uniform\n\ntemplate <class RealType>\nvoid test_spots(RealType)\n{\n   // Basic sanity checks\n   //\n   // These test values were generated for the normal distribution\n   // using the online calculator at\n   // http://espse.ed.psu.edu/edpsych/faculty/rhale/hale/507Mat/statlets/free/pdist.htm\n   //\n   // Tolerance is just over 5 decimal digits expressed as a fraction:\n   // that's the limit of the test data.\n   RealType tolerance = 2e-5f;\n   cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \" << tolerance << \".\" << endl;\n\n   using std::exp;\n\n   // Tests for PDF\n   //\n   BOOST_CHECK_CLOSE_FRACTION( // x == upper\n      pdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0)),\n      static_cast<RealType>(1),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION( // x == lower\n      pdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(1)),\n      static_cast<RealType>(1),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION( // x > upper\n      pdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(-1)),\n      static_cast<RealType>(0),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION( // x < lower\n      pdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(2)),\n      static_cast<RealType>(0),\n      tolerance);\n\n   if(std::numeric_limits<RealType>::has_infinity)\n    { // BOOST_CHECK tests for infinity using std::numeric_limits<>::infinity()\n      // Note that infinity is not implemented for real_concept, so these tests\n      // are only done for types, like built-in float, double.. that have infinity.\n    // Note that these assume that  BOOST_MATH_OVERFLOW_ERROR_POLICY is NOT throw_on_error.\n    // #define BOOST_MATH_OVERFLOW_ERROR_POLICY == throw_on_error would give a throw here.\n    // #define BOOST_MATH_DOMAIN_ERROR_POLICY == throw_on_error IS defined, so the throw path\n    // of error handling is tested below with BOOST_MATH_CHECK_THROW tests.\n\n     BOOST_MATH_CHECK_THROW( // x == infinity should NOT be OK.\n       pdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(std::numeric_limits<RealType>::infinity())),\n       std::domain_error);\n\n     BOOST_MATH_CHECK_THROW( // x == minus infinity should be OK too.\n       pdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(-std::numeric_limits<RealType>::infinity())),\n       std::domain_error);\n   }\n   if(std::numeric_limits<RealType>::has_quiet_NaN)\n   { // BOOST_CHECK tests for NaN using std::numeric_limits<>::has_quiet_NaN() - should throw.\n     BOOST_MATH_CHECK_THROW(\n       pdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(std::numeric_limits<RealType>::quiet_NaN())),\n       std::domain_error);\n     BOOST_MATH_CHECK_THROW(\n       pdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(-std::numeric_limits<RealType>::quiet_NaN())),\n       std::domain_error);\n   } // test for x = NaN using std::numeric_limits<>::quiet_NaN()\n\n   // cdf\n   BOOST_CHECK_EQUAL( // x < lower\n      cdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(-1)),\n      static_cast<RealType>(0) );\n   BOOST_CHECK_CLOSE_FRACTION(\n      cdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0)),\n      static_cast<RealType>(0),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      cdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0.5)),\n      static_cast<RealType>(0.5),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      cdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0.1)),\n      static_cast<RealType>(0.1),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      cdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0.9)),\n      static_cast<RealType>(0.9),\n      tolerance);\n   BOOST_CHECK_EQUAL( // x > upper\n      cdf(uniform_distribution<RealType>(0, 1), static_cast<RealType>(2)),\n      static_cast<RealType>(1));\n\n  // cdf complement\n   BOOST_CHECK_EQUAL( // x < lower\n      cdf(complement(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0))),\n      static_cast<RealType>(1));\n   BOOST_CHECK_EQUAL( // x == 0\n      cdf(complement(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0))),\n      static_cast<RealType>(1));\n   BOOST_CHECK_CLOSE_FRACTION( // x = 0.1\n      cdf(complement(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0.1))),\n      static_cast<RealType>(0.9),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION( // x = 0.5\n      cdf(complement(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0.5))),\n      static_cast<RealType>(0.5),\n      tolerance);\n   BOOST_CHECK_EQUAL( // x == 1\n      cdf(complement(uniform_distribution<RealType>(0, 1), static_cast<RealType>(1))),\n      static_cast<RealType>(0));\n   BOOST_CHECK_EQUAL( // x > upper\n      cdf(complement(uniform_distribution<RealType>(0, 1), static_cast<RealType>(2))),\n      static_cast<RealType>(0));\n\n   // quantile\n\n   BOOST_CHECK_CLOSE_FRACTION(\n      quantile(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0.9)),\n      static_cast<RealType>(0.9),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      quantile(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0.1)),\n      static_cast<RealType>(0.1),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      quantile(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0.5)),\n      static_cast<RealType>(0.5),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      quantile(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0)),\n      static_cast<RealType>(0),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      quantile(uniform_distribution<RealType>(0, 1), static_cast<RealType>(1)),\n      static_cast<RealType>(1),\n      tolerance);\n\n   // quantile complement\n\n   BOOST_CHECK_CLOSE_FRACTION(\n      quantile(complement(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0.1))),\n      static_cast<RealType>(0.9),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      quantile(complement(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0.9))),\n      static_cast<RealType>(0.1),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      quantile(complement(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0.5))),\n      static_cast<RealType>(0.5),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      quantile(complement(uniform_distribution<RealType>(0, 1), static_cast<RealType>(0))),\n      static_cast<RealType>(1),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      quantile(complement(uniform_distribution<RealType>(0, 1), static_cast<RealType>(1))),\n      static_cast<RealType>(0),\n      tolerance);\n\n   // Some tests using a different location & scale, neight zero or unity.\n   BOOST_CHECK_CLOSE_FRACTION( // x == mid\n      pdf(uniform_distribution<RealType>(-1, 2), static_cast<RealType>(1)),\n      static_cast<RealType>(0.3333333333333333333333333333333333333333333333333333),\n      tolerance);\n\n   BOOST_CHECK_CLOSE_FRACTION( // x == upper\n      pdf(uniform_distribution<RealType>(-1, 2), static_cast<RealType>(+2)),\n      static_cast<RealType>(0.3333333333333333333333333333333333333333333333333333),  // 1 / (2 - -1) = 1/3\n      tolerance);\n\n   BOOST_CHECK_CLOSE_FRACTION( // x == lower\n      cdf(uniform_distribution<RealType>(-1, 2), static_cast<RealType>(-1)),\n      static_cast<RealType>(0),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION( // x == upper\n      cdf(uniform_distribution<RealType>(-1, 2), static_cast<RealType>(0)),\n      static_cast<RealType>(0.3333333333333333333333333333333333333333333333333333),\n      tolerance);\n\n   BOOST_CHECK_CLOSE_FRACTION( // x == upper\n      cdf(uniform_distribution<RealType>(-1, 2), static_cast<RealType>(1)),\n      static_cast<RealType>(0.6666666666666666666666666666666666666666666666666667),\n      tolerance);\n\n   BOOST_CHECK_CLOSE_FRACTION( // x == lower\n      cdf(uniform_distribution<RealType>(-1, 2), static_cast<RealType>(2)),\n      static_cast<RealType>(1),\n      tolerance);\n\n   BOOST_CHECK_CLOSE_FRACTION( // x == upper\n      quantile(uniform_distribution<RealType>(-1, 2), static_cast<RealType>(0.6666666666666666666666666666666666666666666666666667)),\n      static_cast<RealType>(1),\n      tolerance);\n\n      check_uniform(\n      static_cast<RealType>(0),       // lower\n      static_cast<RealType>(1),       // upper\n      static_cast<RealType>(0.5),     // x\n      static_cast<RealType>(0.5),     // p\n      static_cast<RealType>(1 - 0.5), // q\n      tolerance);\n\n      // Some Not-standard uniform tests.\n      check_uniform(\n      static_cast<RealType>(-1),    // lower\n      static_cast<RealType>(1),     // upper\n      static_cast<RealType>(0),     // x\n      static_cast<RealType>(0.5),   // p\n      static_cast<RealType>(1 - 0.5), // q = 1 - p\n      tolerance);\n\n      check_uniform(\n      static_cast<RealType>(1),    // lower\n      static_cast<RealType>(3),     // upper\n      static_cast<RealType>(2),     // x\n      static_cast<RealType>(0.5),   // p\n      static_cast<RealType>(1 - 0.5), // q = 1 - p\n      tolerance);\n\n      check_uniform(\n      static_cast<RealType>(-1),    // lower\n      static_cast<RealType>(2),     // upper\n      static_cast<RealType>(1),     // x\n      static_cast<RealType>(0.66666666666666666666666666666666666666666667),   // p\n      static_cast<RealType>(0.33333333333333333333333333333333333333333333), // q = 1 - p\n      tolerance);\n   tolerance = (std::max)(\n      boost::math::tools::epsilon<RealType>(),\n      static_cast<RealType>(boost::math::tools::epsilon<double>())) * 5; // 5 eps as a fraction.\n    cout << \"Tolerance (as fraction) for type \" << typeid(RealType).name()  << \" is \" << tolerance << \".\" << endl;\n   uniform_distribution<RealType> distu01(0, 1);\n   RealType x = static_cast<RealType>(0.5);\n   using namespace std; // ADL of std names.\n   // mean:\n   BOOST_CHECK_CLOSE_FRACTION(\n      mean(distu01), static_cast<RealType>(0.5), tolerance);\n   // variance:\n   BOOST_CHECK_CLOSE_FRACTION(\n      variance(distu01), static_cast<RealType>(0.0833333333333333333333333333333333333333333), tolerance);\n   // std deviation:\n   BOOST_CHECK_CLOSE_FRACTION(\n    standard_deviation(distu01), sqrt(variance(distu01)), tolerance);\n   // hazard:\n   BOOST_CHECK_CLOSE_FRACTION(\n    hazard(distu01, x), pdf(distu01, x) / cdf(complement(distu01, x)), tolerance);\n   // cumulative hazard:\n   BOOST_CHECK_CLOSE_FRACTION(\n    chf(distu01, x), -log(cdf(complement(distu01, x))), tolerance);\n   // coefficient_of_variation:\n   BOOST_CHECK_CLOSE_FRACTION(\n    coefficient_of_variation(distu01), standard_deviation(distu01) / mean(distu01), tolerance);\n   // mode:\n   BOOST_CHECK_CLOSE_FRACTION(\n    mode(distu01), static_cast<RealType>(0), tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      median(distu01), static_cast<RealType>(0.5), tolerance);\n   // skewness:\n   BOOST_CHECK_EQUAL(\n    skewness(distu01), static_cast<RealType>(0));\n   // kertosis:\n   BOOST_CHECK_CLOSE_FRACTION(\n    kurtosis(distu01), kurtosis_excess(distu01) + static_cast<RealType>(3), tolerance);\n   // kertosis excess:\n   BOOST_CHECK_CLOSE_FRACTION(\n    kurtosis_excess(distu01), static_cast<RealType>(-1.2), tolerance);\n\n   if(std::numeric_limits<RealType>::has_infinity)\n  { // BOOST_CHECK tests for infinity using std::numeric_limits<>::infinity()\n    // Note that infinity is not implemented for real_concept, so these tests\n    // are only done for types, like built-in float, double, long double, that have infinity.\n    // Note that these assume that  BOOST_MATH_OVERFLOW_ERROR_POLICY is NOT throw_on_error.\n    // #define BOOST_MATH_OVERFLOW_ERROR_POLICY == throw_on_error would give a throw here.\n    // #define BOOST_MATH_DOMAIN_ERROR_POLICY == throw_on_error IS defined, so the throw path\n    // of error handling is tested below with BOOST_MATH_CHECK_THROW tests.\n\n    BOOST_MATH_CHECK_THROW(pdf(distu01, std::numeric_limits<RealType>::infinity()),  std::domain_error);\n    BOOST_MATH_CHECK_THROW(pdf(distu01, -std::numeric_limits<RealType>::infinity()),  std::domain_error);\n   } // test for infinity using std::numeric_limits<>::infinity()\n   else\n   { // real_concept case, does has_infinfity == false, so can't check it throws.\n     // cout << std::numeric_limits<RealType>::infinity() << ' '\n     // << (boost::math::fpclassify)(std::numeric_limits<RealType>::infinity()) << endl;\n     // value of std::numeric_limits<RealType>::infinity() is zero, so FPclassify is zero,\n     // so (boost::math::isfinite)(std::numeric_limits<RealType>::infinity()) does not detect infinity.\n     // so these tests would never throw.\n     //BOOST_MATH_CHECK_THROW(pdf(distu01, std::numeric_limits<RealType>::infinity()),  std::domain_error);\n     //BOOST_MATH_CHECK_THROW(pdf(distu01, std::numeric_limits<RealType>::quiet_NaN()),  std::domain_error);\n     // BOOST_MATH_CHECK_THROW(pdf(distu01, boost::math::tools::max_value<RealType>() * 2),  std::domain_error); // Doesn't throw.\n     BOOST_CHECK_EQUAL(pdf(distu01, boost::math::tools::max_value<RealType>()), 0);\n   }\n   // Special cases:\n   BOOST_CHECK(pdf(distu01, 0) == 1);\n   BOOST_CHECK(cdf(distu01, 0) == 0);\n   BOOST_CHECK(pdf(distu01, 1) == 1);\n   BOOST_CHECK(cdf(distu01, 1) == 1);\n   BOOST_CHECK(cdf(complement(distu01, 0)) == 1);\n   BOOST_CHECK(cdf(complement(distu01, 1)) == 0);\n   BOOST_CHECK(quantile(distu01, 0) == 0);\n   BOOST_CHECK(quantile(complement(distu01, 0)) == 1);\n   BOOST_CHECK(quantile(distu01, 1) == 1);\n   BOOST_CHECK(quantile(complement(distu01, 1)) == 0);\n\n   // Error checks:\n   if(std::numeric_limits<RealType>::has_quiet_NaN)\n   { // BOOST_CHECK tests for constructing with quiet_NaN (not for real_concept, for example - see notes above).\n     BOOST_MATH_CHECK_THROW(uniform_distribution<RealType>(0, std::numeric_limits<RealType>::quiet_NaN()), std::domain_error);\n     BOOST_MATH_CHECK_THROW(uniform_distribution<RealType>(0, -std::numeric_limits<RealType>::quiet_NaN()), std::domain_error);\n   }\n   BOOST_MATH_CHECK_THROW(uniform_distribution<RealType>(1, 0), std::domain_error); // lower > upper!\n   BOOST_MATH_CHECK_THROW(uniform_distribution<RealType>(1, 1), std::domain_error); // lower == upper!\n\n   check_out_of_range<uniform_distribution<RealType> >(1, 5);\n} // template <class RealType>void test_spots(RealType)\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n  // Check that can construct uniform distribution using the two convenience methods:\n  using namespace boost::math;\n  uniform unistd; // Using typedef\n  // == uniform_distribution<double> unistd;\n  BOOST_CHECK_EQUAL(unistd.lower(), 0); // Check defaults.\n  BOOST_CHECK_EQUAL(unistd.upper(), 1);\n   uniform_distribution<> myu01(0, 1); // Using default RealType double.\n  BOOST_CHECK_EQUAL(myu01.lower(), 0); // Check defaults again.\n  BOOST_CHECK_EQUAL(myu01.upper(), 1);\n\n  // Test on extreme values of random variate x, using just double because it has numeric_limit infinity etc..\n  // No longer allow x to be + or - infinity, then these tests should throw.\n  BOOST_MATH_CHECK_THROW(pdf(unistd, +std::numeric_limits<double>::infinity()), std::domain_error); // x = + infinity\n  BOOST_MATH_CHECK_THROW(pdf(unistd, -std::numeric_limits<double>::infinity()), std::domain_error); // x = - infinity\n  BOOST_MATH_CHECK_THROW(cdf(unistd, +std::numeric_limits<double>::infinity()), std::domain_error); // x = + infinity\n  BOOST_MATH_CHECK_THROW(cdf(unistd, -std::numeric_limits<double>::infinity()), std::domain_error); // x = - infinity\n\n  BOOST_CHECK_EQUAL(pdf(unistd, +(std::numeric_limits<double>::max)()), 0); // x = + max\n  BOOST_CHECK_EQUAL(pdf(unistd, -(std::numeric_limits<double>::min)()), 0); // x = - min\n  BOOST_CHECK_EQUAL(cdf(unistd, +(std::numeric_limits<double>::max)()), 1); // x = + max\n  BOOST_CHECK_EQUAL(cdf(unistd, -(std::numeric_limits<double>::min)()), 0); // x = - min\n#ifndef BOOST_NO_EXCEPTIONS\n  BOOST_MATH_CHECK_THROW(uniform_distribution<> zinf(0, +std::numeric_limits<double>::infinity()), std::domain_error); // zero to infinity using default RealType double.\n#else\n  BOOST_MATH_CHECK_THROW(uniform_distribution<>(0, +std::numeric_limits<double>::infinity()), std::domain_error); // zero to infinity using default RealType double.\n#endif\n   uniform_distribution<> zmax(0, +(std::numeric_limits<double>::max)()); // zero to max using default RealType double.\n  BOOST_CHECK_EQUAL(zmax.lower(), 0); // Check defaults again.\n  BOOST_CHECK_EQUAL(zmax.upper(), +(std::numeric_limits<double>::max)());\n\n  BOOST_CHECK_EQUAL(pdf(zmax, -1), 0); // pdf is 1/(0 - max) = almost zero for all x\n  BOOST_CHECK_EQUAL(pdf(zmax, 0), (std::numeric_limits<double>::min)()/4); // x =\n  BOOST_CHECK_EQUAL(pdf(zmax, 1), (std::numeric_limits<double>::min)()/4); // x =\n  BOOST_MATH_CHECK_THROW(pdf(zmax, +std::numeric_limits<double>::infinity()), std::domain_error); // pdf is 1/(0 - infinity) = zero for all x\n  BOOST_MATH_CHECK_THROW(pdf(zmax, -std::numeric_limits<double>::infinity()), std::domain_error);\n  BOOST_CHECK_EQUAL(pdf(zmax, +(std::numeric_limits<double>::max)()), (std::numeric_limits<double>::min)()/4); // x =\n  BOOST_CHECK_EQUAL(pdf(zmax, -(std::numeric_limits<double>::max)()), 0); // x =\n#ifndef BOOST_NO_EXCEPTIONS\n  // Ensure NaN throws an exception.\n  BOOST_MATH_CHECK_THROW(uniform_distribution<> zNaN(0, std::numeric_limits<double>::quiet_NaN()), std::domain_error);\n  BOOST_MATH_CHECK_THROW(pdf(unistd, std::numeric_limits<double>::quiet_NaN()), std::domain_error);\n#else\n  BOOST_MATH_CHECK_THROW(uniform_distribution<>(0, std::numeric_limits<double>::quiet_NaN()), std::domain_error);\n  BOOST_MATH_CHECK_THROW(pdf(unistd, std::numeric_limits<double>::quiet_NaN()), std::domain_error);\n#endif\n    // Basic sanity-check spot values.\n   // (Parameter value, arbitrarily zero, only communicates the floating point type).\n  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %\n  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n  test_spots(0.0L); // Test long double.\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(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/*\n\nOutput:\n\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\test_uniform.exe\"\nRunning 1 test case...\nTolerance for type float is 2e-005.\nTolerance (as fraction) for type float is 5.96046e-007.\nTolerance for type double is 2e-005.\nTolerance (as fraction) for type double is 1.11022e-015.\nTolerance for type long double is 2e-005.\nTolerance (as fraction) for type long double is 1.11022e-015.\nTolerance for type class boost::math::concepts::real_concept is 2e-005.\nTolerance (as fraction) for type class boost::math::concepts::real_concept is 1.11022e-015.\n*** No errors detected\n\n*/\n", "meta": {"hexsha": "432352ba21273823704baf9538cd2ea09198994a", "size": 21128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/math/test/test_uniform.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/math/test/test_uniform.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/math/test/test_uniform.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": 46.0305010893, "max_line_length": 169, "alphanum_fraction": 0.6953805377, "num_tokens": 5580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5238025455290577}}
{"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    Rot3.cpp\n * @brief   Rotation, common code between Rotation matrix and Quaternion\n * @author  Alireza Fathi\n * @author  Christian Potthast\n * @author  Frank Dellaert\n * @author  Richard Roberts\n */\n\n#include <gtsam/geometry/Rot3.h>\n#include <boost/math/constants/constants.hpp>\n#include <boost/random.hpp>\n#include <cmath>\n\nusing namespace std;\n\nnamespace gtsam {\n\nstatic const Matrix3 I3 = Matrix3::Identity();\n\n/* ************************************************************************* */\nvoid Rot3::print(const std::string& s) const {\n  gtsam::print((Matrix)matrix(), s);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::rodriguez(const Point3& w, double theta) {\n  return rodriguez((Vector)w.vector(),theta);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::rodriguez(const Unit3& w, double theta) {\n  return rodriguez(w.point3(),theta);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::Random(boost::mt19937 & rng) {\n  // TODO allow any engine without including all of boost :-(\n  Unit3 w = Unit3::Random(rng);\n  boost::uniform_real<double> randomAngle(-M_PI,M_PI);\n  double angle = randomAngle(rng);\n  return rodriguez(w,angle);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::rodriguez(const Vector& w) {\n  double t = w.norm();\n  if (t < 1e-10) return Rot3();\n  return rodriguez(w/t, t);\n}\n\n/* ************************************************************************* */\nbool Rot3::equals(const Rot3 & R, double tol) const {\n  return equal_with_abs_tol(matrix(), R.matrix(), tol);\n}\n\n/* ************************************************************************* */\nPoint3 Rot3::operator*(const Point3& p) const {\n  return rotate(p);\n}\n\n/* ************************************************************************* */\nUnit3 Rot3::rotate(const Unit3& p,\n    boost::optional<Matrix&> HR, boost::optional<Matrix&> Hp) const {\n  Unit3 q = Unit3(rotate(p.point3(Hp)));\n  if (Hp)\n    (*Hp) = q.basis().transpose() * matrix() * (*Hp);\n  if (HR)\n    (*HR) = -q.basis().transpose() * matrix() * p.skew();\n  return q;\n}\n\n/* ************************************************************************* */\nUnit3 Rot3::unrotate(const Unit3& p,\n    boost::optional<Matrix&> HR, boost::optional<Matrix&> Hp) const {\n  Unit3 q = Unit3(unrotate(p.point3(Hp)));\n  if (Hp)\n    (*Hp) = q.basis().transpose() * matrix().transpose () * (*Hp);\n  if (HR)\n    (*HR) = q.basis().transpose() * q.skew();\n  return q;\n}\n\n/* ************************************************************************* */\nUnit3 Rot3::operator*(const Unit3& p) const {\n  return rotate(p);\n}\n\n/* ************************************************************************* */\n// see doc/math.lyx, SO(3) section\nPoint3 Rot3::unrotate(const Point3& p,\n    boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n  Point3 q(transpose()*p.vector()); // q = Rt*p\n  if (H1) *H1 = skewSymmetric(q.x(), q.y(), q.z());\n  if (H2) *H2 = transpose();\n  return q;\n}\n\n/* ************************************************************************* */\n/// Follow Iserles05an, B10, pg 147, with a sign change in the second term (left version)\nMatrix3 Rot3::dexpL(const Vector3& v) {\n  if(zero(v)) return eye(3);\n  Matrix x = skewSymmetric(v);\n  Matrix x2 = x*x;\n  double theta = v.norm(), vi = theta/2.0;\n  double s1 = sin(vi)/vi;\n  double s2 = (theta - sin(theta))/(theta*theta*theta);\n  Matrix res = eye(3) - 0.5*s1*s1*x + s2*x2;\n  return res;\n}\n\n/* ************************************************************************* */\n/// Follow Iserles05an, B11, pg 147, with a sign change in the second term (left version)\nMatrix3 Rot3::dexpInvL(const Vector3& v) {\n  if(zero(v)) return eye(3);\n  Matrix x = skewSymmetric(v);\n  Matrix x2 = x*x;\n  double theta = v.norm(), vi = theta/2.0;\n  double s2 = (theta*tan(M_PI_2-vi) - 2)/(2*theta*theta);\n  Matrix res = eye(3) + 0.5*x - s2*x2;\n  return res;\n}\n\n\n/* ************************************************************************* */\nPoint3 Rot3::column(int index) const{\n  if(index == 3)\n    return r3();\n  else if(index == 2)\n    return r2();\n  else if(index == 1)\n    return r1(); // default returns r1\n  else\n    throw invalid_argument(\"Argument to Rot3::column must be 1, 2, or 3\");\n}\n\n/* ************************************************************************* */\nVector3 Rot3::xyz() const {\n  Matrix I;Vector3 q;\n  boost::tie(I,q)=RQ(matrix());\n  return q;\n}\n\n/* ************************************************************************* */\nVector3 Rot3::ypr() const {\n  Vector3 q = xyz();\n  return Vector3(q(2),q(1),q(0));\n}\n\n/* ************************************************************************* */\nVector3 Rot3::rpy() const {\n  return xyz();\n}\n\n/* ************************************************************************* */\nVector Rot3::quaternion() const {\n  Quaternion q = toQuaternion();\n  Vector v(4);\n  v(0) = q.w();\n  v(1) = q.x();\n  v(2) = q.y();\n  v(3) = q.z();\n  return v;\n}\n\n/* ************************************************************************* */\nMatrix3 Rot3::rightJacobianExpMapSO3(const Vector3& x)    {\n  // x is the axis-angle representation (exponential coordinates) for a rotation\n  double normx = norm_2(x); // rotation angle\n  Matrix3 Jr;\n  if (normx < 10e-8){\n    Jr = Matrix3::Identity();\n  }\n  else{\n    const Matrix3 X = skewSymmetric(x); // element of Lie algebra so(3): X = x^\n    Jr = Matrix3::Identity() - ((1-cos(normx))/(normx*normx)) * X +\n        ((normx-sin(normx))/(normx*normx*normx)) * X * X; // right Jacobian\n  }\n  return Jr;\n}\n\n/* ************************************************************************* */\nMatrix3 Rot3::rightJacobianExpMapSO3inverse(const Vector3& x)    {\n  // x is the axis-angle representation (exponential coordinates) for a rotation\n  double normx = norm_2(x); // rotation angle\n  Matrix3 Jrinv;\n\n  if (normx < 10e-8){\n    Jrinv = Matrix3::Identity();\n  }\n  else{\n    const Matrix3 X = skewSymmetric(x); // element of Lie algebra so(3): X = x^\n    Jrinv = Matrix3::Identity() +\n        0.5 * X + (1/(normx*normx) - (1+cos(normx))/(2*normx * sin(normx))   ) * X * X;\n  }\n  return Jrinv;\n}\n\n/* ************************************************************************* */\npair<Matrix3, Vector3> RQ(const Matrix3& A) {\n\n  double x = -atan2(-A(2, 1), A(2, 2));\n  Rot3 Qx = Rot3::Rx(-x);\n  Matrix3 B = A * Qx.matrix();\n\n  double y = -atan2(B(2, 0), B(2, 2));\n  Rot3 Qy = Rot3::Ry(-y);\n  Matrix3 C = B * Qy.matrix();\n\n  double z = -atan2(-C(1, 0), C(1, 1));\n  Rot3 Qz = Rot3::Rz(-z);\n  Matrix3 R = C * Qz.matrix();\n\n  Vector xyz = Vector3(x, y, z);\n  return make_pair(R, xyz);\n}\n\n/* ************************************************************************* */\nostream &operator<<(ostream &os, const Rot3& R) {\n  os << \"\\n\";\n  os << '|' << R.r1().x() << \", \" << R.r2().x() << \", \" << R.r3().x() << \"|\\n\";\n  os << '|' << R.r1().y() << \", \" << R.r2().y() << \", \" << R.r3().y() << \"|\\n\";\n  os << '|' << R.r1().z() << \", \" << R.r2().z() << \", \" << R.r3().z() << \"|\\n\";\n  return os;\n}\n\n/* ************************************************************************* */\n\n} // namespace gtsam\n\n", "meta": {"hexsha": "37aa78a7837efcf87e977c0a4d6b922b8c35ec7a", "size": 7639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Rot3.cpp", "max_stars_repo_name": "ashariati/gtsam-3.2.1", "max_stars_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T08:58:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T08:01:42.000Z", "max_issues_repo_path": "gtsam/geometry/Rot3.cpp", "max_issues_repo_name": "ashariati/gtsam-3.2.1", "max_issues_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T16:21:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-13T16:50:42.000Z", "max_forks_repo_path": "gtsam/geometry/Rot3.cpp", "max_forks_repo_name": "ashariati/gtsam-3.2.1", "max_forks_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2015-06-01T11:22:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T11:03:57.000Z", "avg_line_length": 31.5661157025, "max_line_length": 89, "alphanum_fraction": 0.449928001, "num_tokens": 2020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.523802540834259}}
{"text": "// Petter Strandmark 2012.\n\n#include <cstdio>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <memory>\n#include <random>\n#include <stdexcept>\n\n// GNU 4.8.1 define _X on Cygwin.\n// This breaks Eigen.\n// http://eigen.tuxfamily.org/bz/process_bug.cgi\n#ifdef _X\n#undef _X\n#endif\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Sparse>\n\n#include <spii/spii.h>\n#include <spii/solver.h>\n\nnamespace spii {\n\nvoid NewtonSolver::solve(const Function& function,\n                         SolverResults* results) const\n{\n\tdouble global_start_time = wall_time();\n\n\t// Random number engine for random pertubation.\n\tstd::mt19937 prng(unsigned(1));\n\tstd::uniform_real_distribution<double> uniform11(-1.0, 1.0);\n\tauto rand11 = std::bind(uniform11, prng);\n\n\t// Dimension of problem.\n\tsize_t n = function.get_number_of_scalars();\n\n\tif (n == 0) {\n\t\tresults->exit_condition = SolverResults::FUNCTION_TOLERANCE;\n\t\treturn;\n\t}\n\n\t// Determine whether to use sparse representation\n\t// and matrix factorization.\n\tbool use_sparsity;\n\tif (this->sparsity_mode == SparsityMode::DENSE) {\n\t\tuse_sparsity = false;\n\t}\n\telse if (this->sparsity_mode == SparsityMode::SPARSE) {\n\t\tuse_sparsity = true;\n\t}\n\telse {\n\t\tif (n <= 50) {\n\t\t\tuse_sparsity = false;\n\t\t}\n\t\telse {\n\t\t\tuse_sparsity = true;\n\t\t}\n\t}\n\n\tauto factorization_method = this->factorization_method;\n\tif (use_sparsity && this->factorization_method == FactorizationMethod::MESCHACH) {\n\t\tif (this->log_function) {\n\t\t\tthis->log_function(\"Can not use the Meschach library for sparse problems. Switching to iterative factorization.\");\n\t\t}\n\t\tfactorization_method = FactorizationMethod::ITERATIVE;\n\t}\n\n\t// Current point, gradient and Hessian.\n\tdouble fval   = std::numeric_limits<double>::quiet_NaN();;\n\tdouble fprev  = std::numeric_limits<double>::quiet_NaN();\n\tdouble normg0 = std::numeric_limits<double>::quiet_NaN();\n\tdouble normg  = std::numeric_limits<double>::quiet_NaN();\n\tdouble normdx = std::numeric_limits<double>::quiet_NaN();\n\n\tEigen::VectorXd x, g;\n\tEigen::MatrixXd H;\n\tEigen::SparseMatrix<double> sparse_H;\n\tif (use_sparsity) {\n\t\t// Create sparsity pattern for H.\n\t\tfunction.create_sparse_hessian(&sparse_H);\n\t\tif (this->log_function) {\n\t\t\tdouble nnz = double(sparse_H.nonZeros()) / double(n * n);\n\t\t\tchar str[1024];\n\t\t\tstd::sprintf(str, \"H is %dx%d with %d (%.5f%%) non-zeroes.\",\n\t\t\t\tsparse_H.rows(), sparse_H.cols(), sparse_H.nonZeros(), 100.0 * nnz);\n\t\t\tthis->log_function(str);\n\t\t}\n\t}\n\n\t// Copy the user state to the current point.\n\tfunction.copy_user_to_global(&x);\n\tEigen::VectorXd x2(n);\n\n\t// p will store the search direction.\n\tEigen::VectorXd p(function.get_number_of_scalars());\n\n\t// Dense and sparse Cholesky factorizers.\n\ttypedef Eigen::LLT<Eigen::MatrixXd> LLT;\n\ttypedef Eigen::SimplicialLLT<Eigen::SparseMatrix<double> > SparseLLT;\n\tstd::unique_ptr<LLT> factorization;\n\tstd::unique_ptr<SparseLLT> sparse_factorization;\n\tif (!use_sparsity) {\n\t\tfactorization.reset(new LLT(n));\n\t}\n\telse {\n\t\tsparse_factorization.reset(new SparseLLT);\n\t\t// The sparsity pattern of H is always the same. Therefore, it is enough\n\t\t// to analyze it once.\n\t\tsparse_factorization->analyzePattern(sparse_H);\n\t}\n\n\tFactorizationCache factorization_cache((int)n);\n\tCheckExitConditionsCache exit_condition_cache;\n\n\t//\n\t// START MAIN ITERATION\n\t//\n\tresults->startup_time   += wall_time() - global_start_time;\n\tresults->exit_condition = SolverResults::INTERNAL_ERROR;\n\tint iter = 0;\n\twhile (true) {\n\n\t\tint log_interval = 1;\n\t\tif (iter > 30) {\n\t\t\tlog_interval = 10;\n\t\t}\n\t\tif (iter > 200) {\n\t\t\tlog_interval = 100;\n\t\t}\n\t\tif (iter > 2000) {\n\t\t\tlog_interval = 1000;\n\t\t}\n\n\t\t//\n\t\t// Evaluate function and derivatives.\n\t\t//\n\t\tdouble start_time = wall_time();\n\t\tif (use_sparsity) {\n\t\t\tfval = function.evaluate(x, &g, &sparse_H);\n\t\t}\n\t\telse {\n\t\t\tfval = function.evaluate(x, &g, &H);\n\t\t}\n\n\t\tnormg = std::max(g.maxCoeff(), -g.minCoeff());\n\t\tif (iter == 0) {\n\t\t\tnormg0 = normg;\n\t\t}\n\n\t\t// Check for NaN.\n\t\tif (normg != normg) {\n\t\t\tresults->exit_condition = SolverResults::FUNCTION_NAN;\n\t\t\tbreak;\n\t\t}\n\n\t\tresults->function_evaluation_time += wall_time() - start_time;\n\n\t\t//\n\t\t// Test stopping criteriea\n\t\t//\n\t\tstart_time = wall_time();\n\t\tif (this->check_exit_conditions(fval, fprev, normg,\n\t\t\t                            normg0, x.norm(), normdx,\n\t\t\t                            true, &exit_condition_cache, results)) {\n\t\t\tbreak;\n\t\t}\n\t\tif (iter >= this->maximum_iterations) {\n\t\t\tresults->exit_condition = SolverResults::NO_CONVERGENCE;\n\t\t\tbreak;\n\t\t}\n\t\tif (this->callback_function) {\n\t\t\tCallbackInformation information;\n\t\t\tinformation.objective_value = fval;\n\t\t\tinformation.x = &x;\n\t\t\tinformation.g = &g;\n\t\t\tif (use_sparsity) {\n\t\t\t\tinformation.H_sparse = &sparse_H;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tinformation.H_dense = &H;\n\t\t\t}\n\n\t\t\tif (!callback_function(information)) {\n\t\t\t\tresults->exit_condition = SolverResults::USER_ABORT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tresults->stopping_criteria_time += wall_time() - start_time;\n\n\n\t\tint factorizations = 0;\n\t\tdouble tau = 0;\n\t\tdouble mindiag = 0;\n\t\tEigen::VectorXd dH;\n\t\tif (use_sparsity) {\n\t\t\tdH = sparse_H.diagonal();\n\t\t}\n\t\telse {\n\t\t\tdH = H.diagonal();\n\t\t}\n\t\tmindiag = dH.minCoeff();\n\n\t\tif (factorization_method == FactorizationMethod::ITERATIVE) {\n\t\t\t//\n\t\t\t// Attempt repeated Cholesky factorization until the Hessian\n\t\t\t// becomes positive semidefinite.\n\t\t\t//\n\t\t\t//start_time = wall_time();\n\t\t\tdouble beta = 1.0;\n\n\t\t\tif (mindiag > 0) {\n\t\t\t\ttau = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttau = -mindiag + beta;\n\t\t\t}\n\t\t\twhile (true) {\n\t\t\t\t// Add tau*I to the Hessian.\n\t\t\t\tif (tau > 0) {\n\t\t\t\t\tfor (size_t i = 0; i < n; ++i) {\n\t\t\t\t\t\tif (use_sparsity) {\n\t\t\t\t\t\t\tint ii = static_cast<int>(i);\n\t\t\t\t\t\t\tsparse_H.coeffRef(ii, ii) = dH(i) + tau;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tH(i, i) = dH(i) + tau;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Attempt Cholesky factorization.\n\t\t\t\tbool success;\n\t\t\t\tif (use_sparsity) {\n\t\t\t\t\tsparse_factorization->factorize(sparse_H);\n\t\t\t\t\tsuccess = sparse_factorization->info() == Eigen::Success;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfactorization->compute(H);\n\t\t\t\t\tsuccess = factorization->info() == Eigen::Success;\n\t\t\t\t}\n\t\t\t\tfactorizations++;\n\t\t\t\t// Check for success.\n\t\t\t\tif (success) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ttau = std::max(2*tau, beta);\n\n\t\t\t\tspii_assert(factorizations <= 100,\n\t\t\t\t            \"Solver::solve: factorization failed.\");\n\t\t\t}\n\t\t\n\n\t\t\tresults->matrix_factorization_time += wall_time() - start_time;\n\n\t\t\t//\n\t\t\t// Solve linear system to obtain search direction.\n\t\t\t//\n\t\t\tstart_time = wall_time();\n\n\t\t\tif (use_sparsity) {\n\t\t\t\tp = sparse_factorization->solve(-g);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tp = factorization->solve(-g);\n\t\t\t}\n\n\t\t\tresults->linear_solver_time += wall_time() - start_time;\n\t\t}\n\t\telse if (factorization_method == FactorizationMethod::MESCHACH) {\n\t\t\tspii_assert(!use_sparsity);\n\n\t\t\t// Performs a BKP block diagonal factorization, modifies it, and\n\t\t\t// solvers the linear system.\n\t\t\tthis->BKP_dense(H, g, factorization_cache, &p, results);\n\t\t\tfactorizations = 1;\n\t\t}\n\t\telse if (factorization_method == FactorizationMethod::SYM_ILDL) {\n\t\t\tfactorizations = 1;\n\t\t\tif (use_sparsity) {\n\t\t\t\tthis->BKP_sym_ildl(sparse_H, g, &p, results);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis->BKP_sym_ildl(H, g, &p, results);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthrow std::runtime_error(\"Unknown factorization method.\");\n\t\t}\n\n\t\t//\n\t\t// Perform line search.\n\t\t//\n\t\tstart_time = wall_time();\n\t\tdouble start_alpha = 1.0;\n\t\tdouble alpha = this->perform_linesearch(function, x, fval, g, p, &x2,\n\t\t                                        start_alpha);\n\n\t\tif (alpha <= 1e-15) {\n\n\t\t\t// Attempt a simple steepest descent instead.\n\t\t\tp = -g;\n\t\t\talpha = this->perform_linesearch(function, x, fval, g, p, &x2,\n\t\t\t                                 1.0);\n\t\t\tif (alpha <= 0) {\n\n\t\t\t\tif (this->log_function) {\n\t\t\t\t\tthis->log_function(\"Steepest descent step failed. Numerical problems?\");\n\t\t\t\t}\n\n\t\t\t\t// This happens in really rare cases with numerical problems or\n\t\t\t\t// incorrectly defined objective functions. In the latter case,\n\t\t\t\t// there is not much to do. In the former case, randomly perturbing\n\t\t\t\t// x has been effective.\n\t\t\t\tfor (size_t i = 0; i < n; ++i) {\n\t\t\t\t\tx[i] = x[i] + 1e-6 * rand11() * x[i];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\talpha = 0;\n\t\t\t}\n\t\t}\n\n\t\t// Record length of this step.\n\t\tnormdx = alpha * p.norm();\n\t\t// Update current point.\n\t\tx = x + alpha * p;\n\n\t\tresults->backtracking_time += wall_time() - start_time;\n\n\t\t//\n\t\t// Log the results of this iteration.\n\t\t//\n\t\tstart_time = wall_time();\n\n\t\tif (this->log_function && iter % log_interval == 0) {\n\t\t\tif (use_sparsity) {\n\t\t\t\tif (iter == 0) {\n\t\t\t\t\tthis->log_function(\"Itr        f        max|g_i|   alpha    fac    tau   min(H_ii)\");\n\t\t\t\t}\n\t\t\t\tthis->log_function(\n\t\t\t\t\tto_string(std::setw(4), iter) + \" \" +\n\t\t\t\t\tto_string(std::scientific, std::showpos, std::setprecision(6), std::setw(10), fval) + \" \" +\n\t\t\t\t\tto_string(std::scientific, std::setprecision(3), std::setw(9), normg) + \" \" +\n\t\t\t\t\tto_string(std::scientific, std::setprecision(3), std::setw(9), alpha) + \" \" +\n\t\t\t\t\tto_string(std::setw(3), factorizations) + \"   \" +\n\t\t\t\t\tto_string(std::scientific, std::setprecision(1), tau) + \" \" +\n\t\t\t\t\tto_string(std::scientific, std::showpos, std::setprecision(2), mindiag)\n\t\t\t\t\t);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdouble detH = H.determinant();\n\t\t\t\tdouble normH = H.norm();\n\n\t\t\t\tif (iter == 0) {\n\t\t\t\t\tthis->log_function(\"Itr        f        max|g_i|   ||H||     det(H)    min(H_ii)  alpha    fac\");\n\t\t\t\t}\n\n\t\t\t\tthis->log_function(\n\t\t\t\t\tto_string(std::setw(4), iter) + \" \" +\n\t\t\t\t\tto_string(std::scientific, std::showpos, std::setprecision(6), std::setw(10), fval) + \" \" +\n\t\t\t\t\tto_string(std::scientific, std::setprecision(3), std::setw(9), normg) + \" \" +\n\t\t\t\t\tto_string(std::scientific, std::setprecision(3), std::setw(9), normH) + \" \" +\n\t\t\t\t\tto_string(std::scientific, std::showpos, std::setprecision(3), std::setw(10), detH) + \" \" +\n\t\t\t\t\tto_string(std::scientific, std::showpos, std::setprecision(2), mindiag) + \" \" +\n\t\t\t\t\tto_string(std::scientific, std::setprecision(3), std::setw(9), alpha) + \" \" +\n\t\t\t\t\tto_string(std::setw(3), factorizations)\n\t\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tresults->log_time += wall_time() - start_time;\n\n\t\tfprev = fval;\n\t\titer++;\n\t}\n\n\tfunction.copy_global_to_user(x);\n\tresults->total_time += wall_time() - global_start_time;\n\n\tif (this->log_function) {\n\t\tchar str[1024];\n\t\tstd::sprintf(str, \" end %+10.6e %.3e\", fval, normg);\n\t\tthis->log_function(str);\n\t}\n}\n\n}  // namespace spii\n", "meta": {"hexsha": "9b25906dc045b44bd94081330f0b52e254f7c059", "size": 10287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/solver_newton.cpp", "max_stars_repo_name": "PetterS/spii", "max_stars_repo_head_hexsha": "98c5847223d7c3febea5a1aac6f4978dfef207ec", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-03-03T16:21:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T08:02:12.000Z", "max_issues_repo_path": "source/solver_newton.cpp", "max_issues_repo_name": "nashdingsheng/spii", "max_issues_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-07-16T14:41:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-09T19:27:22.000Z", "max_forks_repo_path": "source/solver_newton.cpp", "max_forks_repo_name": "nashdingsheng/spii", "max_forks_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-09-21T23:09:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T20:20:30.000Z", "avg_line_length": 26.5813953488, "max_line_length": 117, "alphanum_fraction": 0.6339068728, "num_tokens": 3036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.523767540365716}}
{"text": "#include <NTL/ZZ.h>\n\n\ntemplate<>\nvoid Elt<NTL::ZZ>::mul(const Elt& x) { NTL::mul(this->t, this->t, x.t); }\n\ntemplate<>\nvoid Elt<NTL::ZZ>::mod(const Elt& x) { NTL::QuickRem(this->t, x.t); }\n\ntemplate<>\nvoid Elt<NTL::ZZ>::div(const Elt& x) { NTL::div(this->t, this->t, x.t); }\n\ntemplate<>\nvoid Elt<NTL::ZZ>::mulmod(const Elt& x, const Elt& y) { NTL::MulMod(this->t, this->t, x.t, y.t); }\n", "meta": {"hexsha": "605612e5b828325c19ec53573b139884a08f27ba", "size": 386, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/elements/elt_NTL.tpp", "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": "src/elements/elt_NTL.tpp", "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": "src/elements/elt_NTL.tpp", "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": 25.7333333333, "max_line_length": 98, "alphanum_fraction": 0.5958549223, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.5237675178421063}}
{"text": "// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n/* least_squares.cc\n   Jeremy Barnes, 15 June 2003\n   Copyright (c) 2003 Jeremy Barnes.  All rights reserved.\n\n   Least squares solution of problems.  Various versions.\n*/\n\n#include \"least_squares.h\"\n\n\n#include \"mldb/plugins/jml/algebra/matrix_ops.h\"\n#include \"mldb/base/exc_assert.h\"\n#include \"svd.h\"\n#include <boost/timer.hpp>\n#include \"mldb/arch/timers.h\"\n#include \"lapack.h\"\n#include <cmath>\n#include \"mldb/utils/string_functions.h\"\n#include \"mldb/arch/simd_vector.h\"\n#include \"mldb/base/parallel.h\"\n\n\nusing namespace std;\n\n\nnamespace ML {\n\n#if 0\ntemplate<class Float>\ndistribution<Float>\nleast_squares_impl(const boost::multi_array<Float, 2> & A,\n                   const distribution<Float> & c,\n                   const boost::multi_array<Float, 2> & B,\n                   const distribution<Float> & d)\n{\n    using namespace LAPack;\n\n    size_t m = A.shape()[0];\n    size_t n = A.shape()[1];\n    size_t p = B.shape()[0];\n\n    //cerr << \"A: (mxn) \" << A.shape()[0] << \" x \" << A.shape()[1] << endl;\n    //cerr << \"B: (pxn) \" << B.shape()[0] << \" x \" << B.shape()[1] << endl;\n    //cerr << \"c: m     \" << c.size() << endl;\n    //cerr << \"d: p     \" << d.size() << endl;\n\n    if (c.size() != m || B.shape()[1] != n || d.size() != p)\n        throw Exception(\"least_squares: sizes didn't match\");\n\n    if (p > n || n > (m + p))\n        throw Exception(\"least_squares: overconstrained system\");\n\n    // todo: check that B has full row rank p and that the matrix (A B)' has\n    // full column rank n.\n\n    distribution<Float> result(n);\n\n    /* We need to transpose them for Fortran, but since they are destroyed\n       anyway it's no big deal since they would have been copied. */\n    boost::multi_array<Float, 2> AF = fortran(A);\n    boost::multi_array<Float, 2> BF = fortran(B);\n    distribution<Float> c2 = c;\n    distribution<Float> d2 = d;\n\n    int res = gglse(m, n, p,\n                    AF.data_begin(), AF.shape()[0],\n                    BF.data_begin(), BF.shape()[1],\n                    &c2[0], &d2[0], &result[0]);\n\n    if (res != 0)\n        throw Exception(format(\"least_squares(): gglse returned error in arg \"\n                               \"%d\", res));\n\n    return result;\n}\n\ndistribution<float>\nleast_squares(const boost::multi_array<float, 2> & A,\n              const distribution<float> & c,\n              const boost::multi_array<float, 2> & B,\n              const distribution<float> & d)\n{\n    return least_squares_impl(A, c, B, d);\n}\n\ndistribution<double>\nleast_squares(const boost::multi_array<double, 2> & A,\n              const distribution<double> & c,\n              const boost::multi_array<double, 2> & B,\n              const distribution<double> & d)\n{\n    return least_squares_impl(A, c, B, d);\n}\n#endif\n\ntemplate<class Float>\ndistribution<Float>\nleast_squares_impl(const boost::multi_array<Float, 2> & A, const distribution<Float> & b)\n{\n    using namespace std;\n\n    //boost::timer t;\n\n    if (A.shape()[0] != b.size()) {\n        cerr << \"A.shape()[0] = \" << A.shape()[0] << endl;\n        cerr << \"A.shape()[1] = \" << A.shape()[1] << endl;\n        cerr << \"b.size() = \" << b.size() << endl;\n        throw Exception(\"incompatible dimensions for least_squares\");\n    }\n\n    using namespace LAPack;\n    \n    int m = A.shape()[0];\n    int n = A.shape()[1];\n\n    distribution<Float> x = b;\n    x.resize(std::max<size_t>(m, n));\n\n    boost::multi_array<Float, 2> A2 = A;\n\n#if 0\n    using namespace std;\n    cerr << \"m = \" << m << \" n = \" << n << \" A2.shape()[0] = \" << A2.shape()[0]\n         << \" A2.shape()[1] = \" << A2.shape()[1] << endl;\n    cerr << \"A2 = \" << endl << A2 << endl;\n    cerr << \"b = \" << b << endl;\n#endif\n    int res = gels('T', n, m, 1, A2.data(), n, &x[0],\n                   x.size());\n\n    if (res < 0)\n        throw Exception(format(\"least_squares(): gels returned error in arg \"\n                               \"%d\", -res));\n\n    //if (debug_irls) {\n    //    (*debug_irls) << \"gels returned \" << res << endl;\n    //    (*debug_irls) << \"x = \" << x << endl;\n    //}\n\n    if (res > 0) {\n        //if (debug_irls)\n        //      (*debug_irls) << \"retrying; \" << res << \" are too small\" << endl;\n    \n        /* Rank-deficient matrix.  Use the more efficient routine. */\n        int rank;\n        Float rcond = -1.0;\n        Float sv[std::min(m, n)];\n        std::fill(sv, sv + std::min(m, n), 0.0);\n\n        // Rebuild A2, transposed this time\n        A2.resize(boost::extents[n][m]);\n        A2 = transpose(A);\n\n        // Rebuild x as it was previously overwritten\n        x = b;\n        x.resize(std::max<size_t>(m, n));\n\n        res = gelsd(m, n, 1, A2.data(), m, &x[0], x.size(), sv, rcond, rank);\n\n        //if (debug_irls)\n        //    (*debug_irls) << \"rcond: \" << rcond << \" rank: \"\n        //                  << rank << endl;\n    }\n\n    if (res < 0) {\n        throw Exception(format(\"least_squares(): gelsy returned error in arg \"\n                               \"%d\", -res));\n    }\n\n    x.resize(n);\n \n    //using namespace std;\n    //cerr << \"least_squares: took \" << t.elapsed() << \"s\" << endl;\n    \n    return x;\n    //cerr << \"least squares: gels returned \" << x2 << endl;\n    //cerr << \"least squares: A2 = \" << endl << A2 << endl;\n\n    //cerr << \"least_squares: \" << t.elapsed() << \"s\" << endl;\n    //distribution<Float> x3\n    //    = least_squares(A, b, boost::multi_array<Float, 2>(0, n), distribution<Float>());\n    \n    //cerr << \"least squares: gglse returned \" << x3 << endl;\n\n}\n\ndistribution<float>\nleast_squares(const boost::multi_array<float, 2> & A,\n              const distribution<float> & b)\n{\n    return least_squares_impl(A, b);\n}\n\ndistribution<double>\nleast_squares(const boost::multi_array<double, 2> & A,\n              const distribution<double> & b)\n{\n    return least_squares_impl(A, b);\n}\n\ntemplate<typename Float>\nvoid doDiagMultColumn(const boost::multi_array<Float, 2> & U,\n                      const distribution<Float> & d,\n                      const boost::multi_array<Float, 2> & V,\n                      boost::multi_array<Float, 2> & result,\n                      int j)\n{\n    size_t m = U.shape()[0], x = d.size();\n\n    Float Vj_values[x];\n    for (unsigned k = 0;  k < x;  ++k) {\n        Vj_values[k] = V[k][j];\n    }\n    for (unsigned i = 0;  i < m;  ++i) {\n        result[i][j] = MLDB::SIMD::vec_accum_prod3(&U[i][0], &d[0], Vj_values, x);\n    }\n}\n\ntemplate<class Float>\nboost::multi_array<Float, 2>\ndiag_mult_impl(const boost::multi_array<Float, 2> & U,\n               const distribution<Float> & d,\n               const boost::multi_array<Float, 2> & V,\n               bool parallel)\n{\n    size_t m = U.shape()[0], n = V.shape()[1], x = d.size();\n\n    boost::multi_array<Float, 2> result(boost::extents[m][n]);\n    \n    if (U.shape()[1] != x || V.shape()[0] != x)\n        throw Exception(\"diag_mult(): wrong shape\");\n\n    auto doColumn = std::bind(&doDiagMultColumn<Float>, \n                              std::cref(U),\n                              std::cref(d),\n                              std::cref(V),\n                              std::ref(result),\n                              std::placeholders::_1);\n\n    if (parallel)\n        MLDB::parallelMap(0, n, doColumn);\n    else {\n        for (unsigned j = 0;  j < n;  ++j)\n            doColumn(j);\n    }\n    \n    return result;\n}\n\nboost::multi_array<float, 2>\ndiag_mult(const boost::multi_array<float, 2> & U,\n          const distribution<float> & d,\n          const boost::multi_array<float, 2> & V,\n          bool parallel)\n{\n    return diag_mult_impl<float>(U, d, V, parallel);\n}\n\nboost::multi_array<double, 2>\ndiag_mult(const boost::multi_array<double, 2> & U,\n          const distribution<double> & d,\n          const boost::multi_array<double, 2> & V,\n          bool parallel)\n{\n    return diag_mult_impl<double>(U, d, V, parallel);\n}\n\ntemplate<typename Float>\nstruct RidgeRegressionIteration {\n    double lambda;\n    double current_lambda;\n    double total_mse_unbiased;\n    distribution<Float> x;\n\n    void run(const distribution<Float> & singular_values,\n             const boost::multi_array<Float, 2> & A,\n             const distribution<Float> & b,\n             const boost::multi_array<Float, 2> & VT,\n             const boost::multi_array<Float, 2> & U,\n             const boost::multi_array<Float, 2> & GK,\n             bool debug)\n    {\n        int m = A.shape()[0];\n        int n = A.shape()[1];\n\n        Timer t(debug);\n\n        auto doneStep = [&] (const std::string & where)\n        {\n            if (!debug)\n                return;\n            cerr << \"      \" << where << \": \" << t.elapsed() << endl;\n            t.restart();\n        };\n\n        //cerr << \"i = \" << i << \" current_lambda = \" << current_lambda << endl;\n        // Adjust the singular values for the new lambda\n        distribution<Float> my_singular = singular_values;\n        if (current_lambda != lambda)\n            my_singular += (current_lambda - lambda);\n\n        //boost::multi_array<Float, 2> GK_pinv\n        //    = U * diag((Float)1.0 / my_singular) * VT;\n\n        boost::multi_array<Float, 2> GK_pinv\n            = diag_mult(U, (Float)1.0 / my_singular, VT, true /* parallel */);\n\n        doneStep(\"diag_mult\");\n\n        // TODO: reduce GK by removing those basis vectors where the singular\n        // values are too close to lambda\n    \n        if (debug && false) {\n            cerr << \"GK_pinv = \" << endl << GK_pinv\n                 << endl;\n            cerr << \"prod = \" << endl << (GK * GK_pinv * GK) << endl;\n            cerr << \"prod2 = \" << endl << (GK_pinv * GK * GK) << endl;\n        }\n\n        boost::multi_array<Float, 2> A_pinv\n            = (m < n ? GK_pinv * A : A * GK_pinv);\n\n        doneStep(\"A_pinv\");\n\n        if (debug && false)\n            cerr << \"A_pinv = \" << endl << A_pinv << endl;\n\n        x = b * A_pinv;\n    \n        if (debug)\n            cerr << \"x = \" << x << endl;\n\n        distribution<Float> predictions = A * x;\n\n        //cerr << \"A: \" << A.shape()[0] << \"x\" << A.shape()[1] << endl;\n        //cerr << \"A_pinv: \" << A_pinv.shape()[0] << \"x\" << A_pinv.shape()[1]\n        //     << endl;\n\n        //boost::multi_array<Float, 2> A_A_pinv\n        //    = A * transpose(A_pinv);\n\n        doneStep(\"predictions\");\n\n#if 0\n        boost::multi_array<Float, 2> A_A_pinv\n        = multiply_transposed(A, A_pinv);\n\n        cerr << \"A_A_pinv: \" << A_A_pinv.shape()[0] << \"x\"\n        << A_A_pinv.shape()[1] << \" m = \" << m << endl;\n\n        if (debug && false)\n            cerr << \"A_A_pinv = \" << endl << A_A_pinv << endl;\n#else\n        // We only need the diagonal of A * A_pinv\n\n        distribution<Float> A_A_pinv_diag(m);\n        for (unsigned j = 0;  j < m;  ++j)\n            A_A_pinv_diag[j] = SIMD::vec_dotprod_dp(&A[j][0], &A_pinv[j][0], n);\n#endif\n\n        doneStep(\"A_A_pinv\");\n\n        // Now figure out the performance\n        double total_mse_biased = 0.0;\n        for (unsigned j = 0;  j < m;  ++j) {\n\n            if (j < 10 && false)\n                cerr << \"j = \" << j << \" b[j] = \" << b[j]\n                     << \" predictions[j] = \" << predictions[j]\n                     << endl;\n\n            double resid = b[j] - predictions[j];\n\n            // Adjust for the bias cause by training on this example.  This is\n            // A * pinv(A), which is A * \n\n            double factor = 1.0 - A_A_pinv_diag[j];\n\n            double resid_unbiased = resid / factor;\n\n            total_mse_biased += (1.0 / m) * resid * resid;\n            total_mse_unbiased += (1.0 / m) * resid_unbiased * resid_unbiased;\n        }\n\n        doneStep(\"mse\");\n\n        //cerr << \"lambda \" << current_lambda\n        //     << \" rmse_biased = \" << sqrt(total_mse_biased)\n        //     << \" rmse_unbiased = \" << sqrt(total_mse_unbiased)\n        //     << endl;\n\n        //if (sqrt(total_mse_biased) > 1.0) {\n        //    cerr << \"rmse_biased: x = \" << x << endl;\n        //}\n    \n#if 0\n        cerr << \"m = \" << m << endl;\n        cerr << \"total_mse_biased   = \" << total_mse_biased << endl;\n        cerr << \"total_mse_unbiased = \" << total_mse_unbiased << endl;\n        cerr << \"best_error = \" << best_error << endl;\n        cerr << \"x = \" << x << endl;\n#endif\n    };\n\n};\n\n// NOTE: this cumbersome construction is to keep clang 3.4 from\n// ICEing\ntemplate<typename Float>\nstruct RidgeRegressionIterations: public std::vector<RidgeRegressionIteration<Float> > {\n    void run(const distribution<Float> & singular_values,\n             const boost::multi_array<Float, 2> & A,\n             const distribution<Float> & b,\n             const boost::multi_array<Float, 2> & VT,\n             const boost::multi_array<Float, 2> & U,\n             const boost::multi_array<Float, 2> & GK,\n             bool debug,\n             int n)\n    {\n        this->at(n).run(singular_values, A, b, VT, U, GK, debug);\n    }\n};\n\ntemplate<class Float>\ndistribution<Float>\nridge_regression_impl(const boost::multi_array<Float, 2> & A,\n                      const distribution<Float> & b,\n                      float& lambda)\n{\n    using namespace std;\n    float initialLambda = lambda < 0 ? 1e-5 : lambda;\n    //cerr << \"ridge_regression: A = \" << A.shape()[0] << \"x\" << A.shape()[1]\n    //     << \" b = \" << b.size() << endl;\n\n    //cerr << \"b = \" << b << endl;\n    //cerr << \"A = \" << A << endl;\n\n    bool debug = false;\n    //debug = true;\n\n    Timer t(debug);\n\n    auto doneStep = [&] (const std::string & where)\n        {\n            if (!debug)\n                return;\n            cerr << where << \": \" << t.elapsed() << endl;\n            t.restart();\n        };\n\n    // Step 1: SVD\n\n    if (A.shape()[0] != b.size())\n        throw Exception(\"incompatible dimensions for least_squares\");\n\n    using namespace LAPack;\n    \n    int m = A.shape()[0];\n    int n = A.shape()[1];\n\n    int minmn = std::min(m, n);\n\n    // See http://www.clopinet.com/isabelle/Projects/ETH/KernelRidge.pdf\n\n    // The matrix to decompose is square\n    boost::multi_array<Float, 2> GK(boost::extents[minmn][minmn]);\n\n    \n    //cerr << \"m = \" << m << \" n = \" << n << endl;\n\n    \n    // Take either A * transpose(A) or (A transpose) * A, whichever is smaller\n    if (m < n) {\n        for (unsigned i1 = 0;  i1 < m;  ++i1)\n            for (unsigned i2 = 0;  i2 < m;  ++i2)\n                GK[i1][i2] = SIMD::vec_dotprod_dp(&A[i1][0], &A[i2][0], n);\n\n        //for (unsigned i1 = 0;  i1 < m;  ++i1)\n        //    for (unsigned i2 = 0;  i2 < m;  ++i2)\n        //        for (unsigned j = 0;  j < n;  ++j)\n        //            GK[i1][i2] += A[i1][j] * A[i2][j];\n    } else {\n        // TODO: vectorize and look at loop order\n        for (unsigned i = 0;  i < m;  ++i)\n            for (unsigned j1 = 0;  j1 < n;  ++j1)\n                for (unsigned j2 = 0;  j2 < n;  ++j2)\n                    GK[j1][j2] += A[i][j1] * A[i][j2];\n    }\n\n    doneStep(\"    square\");\n\n    if (debug)\n        cerr << \"GK = \" << endl << GK << endl;\n\n    //cerr << \"GK.shape()[0] = \" << GK.shape()[0] << endl;\n    //cerr << \"GK.shape()[1] = \" << GK.shape()[1] << endl;\n\n    // Add in the ridge\n    for (unsigned i = 0;  i < minmn;  ++i)\n        GK[i][i] += initialLambda;\n\n    if (debug)\n        cerr << \"GK with ridge = \" << endl << GK << endl;\n\n    // Decompose to get the pseudoinverse\n    distribution<Float> svalues(minmn);\n    boost::multi_array<Float, 2> VT(boost::extents[minmn][minmn]);\n    boost::multi_array<Float, 2> U(boost::extents[minmn][minmn]);\n    \n    svd_square(GK, VT, U, svalues);\n\n    distribution<Float> singular_values\n        (svalues.begin(), svalues.begin() + minmn);\n\n    if (debug)\n        cerr << \"singular values = \" << singular_values << endl;\n\n    if (debug) {\n        // Multiply decomposition back to make sure that we get the original\n        // matrix\n        boost::multi_array<Float, 2> D = diag(singular_values);\n\n        boost::multi_array<Float, 2> GK_test\n            = U * D * VT;\n\n        cerr << \"GK_test = \" << endl << GK_test << endl;\n        //cerr << \"errors = \" << endl << (GK_test - GK) << endl;\n    }\n\n    // Figure out the optimal value of lambda based upon leave-one-out cross\n    // validation\n    distribution<Float> x_best;\n    Float best_lambda = initialLambda;\n    typedef RidgeRegressionIteration<Float> Iteration;\n    if (lambda < 0) {\n        double current_lambda = 10.0;\n\n        RidgeRegressionIterations<Float> iterations;\n\n        for (; current_lambda >= 1e-14; current_lambda /= 10.0) {\n            Iteration iter;\n            iter.lambda = initialLambda;\n            iter.current_lambda = current_lambda;\n            iterations.push_back(iter);\n        };\n\n        MLDB::parallelMap(0, iterations.size(),\n                        std::bind(std::mem_fn(&RidgeRegressionIterations<Float>::run),\n                                  std::ref(iterations),\n                                  std::cref(singular_values),\n                                  std::cref(A), std::cref(b),\n                                  std::cref(VT), std::cref(U),\n                                  std::cref(GK), debug,\n                                  std::placeholders::_1));\n\n        //double best_lambda = -1000;\n        double best_error = 1000000;\n\n        for (unsigned i = 0;  i < iterations.size();  ++i) {\n\n            if (iterations[i].total_mse_unbiased < best_error || i == 0) {\n\n                //cerr << \"best_lambda \" << iterations[i].current_lambda << \" error : \" << iterations[i].total_mse_unbiased << endl;\n\n                x_best = iterations[i].x;\n                best_lambda = iterations[i].current_lambda;\n                best_error = iterations[i].total_mse_unbiased;\n            }\n        } \n    }\n    else {\n        Iteration iter;\n        iter.lambda = initialLambda;\n        iter.current_lambda = initialLambda;\n        iter.run(singular_values, A, b, VT, U, GK, debug);\n        x_best = iter.x;\n    }\n\n    doneStep(\"    lambda\");\n\n    //cerr << \"total: \" << t.elapsed() << endl;\n\n    lambda = best_lambda; //return the lambda we ended up using\n    return x_best;\n}\n\ndistribution<float>\nridge_regression(const boost::multi_array<float, 2> & A,\n                 const distribution<float> & b,\n                 float lambda)\n{\n    return ridge_regression_impl(A, b, lambda);\n}\n\ndistribution<double>\nridge_regression(const boost::multi_array<double, 2> & A,\n                 const distribution<double> & b,\n                 float lambda)\n{\n    return ridge_regression_impl(A, b, lambda);\n}\n\ntemplate<class Float>\ndistribution<Float>\nlasso_regression_impl(const boost::multi_array<Float, 2> & A,\n                      const distribution<Float> & b,\n                      float lambda,\n                      int maxIter,\n                      float epsilon)\n{ \n    // cerr << \"lasso_regression: A = \" << A.shape()[0] << \"x\" << A.shape()[1]\n    //     << \" b = \" << b.size() << \" lambda = \" << lambda <<\" maxIter = \"\n    //     << maxIter << \" epsilon = \" << epsilon << endl;\n\n    //  ref: https://www.coursera.org/learn/ml-regression/lecture/AsCvQ/coordinate-descent-for-lasso-unnormalized-features\n    //\n    //  on why standardisation might be required before using LASSO:\n    //  http://stats.stackexchange.com/q/86434/22296\n\n    int n = A.shape()[0];   //Number of samples\n    int p = A.shape()[1];   //Number of variables\n\n     distribution<Float> x(p, 0.); //our solution vector\n\n    if (lambda <= 0) {\n        x = ridge_regression_impl(A, b, lambda); //Use the ridge regression to determine lambda and use the result as initialization\n    }\n\n    Float halflambda = lambda / 2.0f;\n    distribution<Float> Atb(p, 0.);                        //Correlation of each variable with the target vector\n    boost::multi_array<Float, 2> AtA(boost::extents[p][p]); //Correlation betwen each variables\n\n    //Precompute Atb and AtA\n    for (int j = 0; j < p; ++j) {\n        for (int i = 0; i < n; ++i) {\n            Atb[j] += A[i][j] * b[i];\n        }\n        //each column dot each column\n        for (int i = 0; i < p; ++i) { //todo: optimise for triangular matrix\n            Float dotprod = 0.;\n            for (int r = 0; r < n; ++r) {\n                dotprod += A[r][i] * A[r][j];\n            }\n            AtA[j][i] = dotprod;\n        }\n    }\n\n    //Main lasso loop, which is really a coordinate descent where we optimize each variable independently.\n    //We do this in a roundrobin fashion.\n    int iter = 0;\n    do {\n        Float max_step = 0.;\n        distribution<Float> oldX(p);\n        oldX = x;\n\n        for (int j = 0; j < p; ++j) { //for each column / variable\n\n            Float rho = Atb[j];\n\n            for (int i = 0; i < p; ++i){    //scales with the number of variables\n                if (i != j)\n                    rho -= AtA[j][i] * x[i];\n            }\n\n            if (rho > halflambda) {\n                x[j] = (rho - halflambda) / (AtA[j][j]);\n            }\n            else if (rho < -halflambda) {\n                x[j] = (rho + halflambda) / (AtA[j][j]);\n            }\n            else {\n                x[j] = 0;\n            }\n\n\t        //cerr << \"x[j]: \" << x[j] << endl; \n            Float step = fabs(x[j] - oldX[j]);\n            if (step > max_step)\n                max_step = step;\n        }\n\n        // cerr << \"max_step: \" << max_step << endl;\n\n        // if the biggest step we took was smaller than our threshold, let's\n        // stop there and assume we have converged\n        if (max_step < epsilon) {\n            break;\n        }\n        if (iter >= maxIter) {\n            // if we stopped after max iteration and not because we have\n            // converge, let's issue a warning\n            cerr << MLDB::format(\"LASSO did not converge in %i iterations, last \"\n                               \" max_step > eps (%f > %f)\",\n                               iter, max_step, epsilon);\n            break;\n        }\n        iter++;\n    } while (true); //until convergence\n\n    return x;\n}\n\ndistribution<float>\nlasso_regression(const boost::multi_array<float, 2> & A,\n                 const distribution<float> & b,\n                 float lambda,\n                 int maxIter,\n                 float epsilon)\n{\n    return lasso_regression_impl(A, b, lambda, maxIter, epsilon);\n}\n\ndistribution<double>\nlasso_regression(const boost::multi_array<double, 2> & A,\n                 const distribution<double> & b,\n                 float lambda,\n                 int maxIter,\n                 float epsilon)\n{\n    return lasso_regression_impl(A, b, lambda, maxIter, epsilon);\n}\n\n//***********************************************\n\ntemplate<class Float>\nvoid doWeightedSquareRow(const boost::multi_array<Float, 2> & XT,\n                         const distribution<Float> & d,\n                         boost::multi_array<Float, 2> & result,\n                         int i)\n{\n    int chunk_size = 2048;  // ensure we fit in the cache\n\n    size_t nx = XT.shape()[1];\n    size_t nv = XT.shape()[0];\n\n    int x = 0;\n    while (x < nx) {\n        int nxc = std::min<size_t>(chunk_size, nx - x);\n        distribution<Float> Xid(chunk_size);\n        SIMD::vec_prod(&XT[i][x], &d[x], &Xid[0], nxc);\n            \n        for (unsigned j = 0;  j < nv;  ++j) {\n            result[i][j] += SIMD::vec_dotprod_dp(&XT[j][x], &Xid[0], nxc);\n        }\n\n        x += nxc;\n    }\n\n}\n\ntemplate<class Float>\nboost::multi_array<Float, 2>\nweighted_square_impl(const boost::multi_array<Float, 2> & XT,\n                     const distribution<Float> & d)\n{\n    if (XT.shape()[1] != d.size())\n        throw Exception(\"Incompatible matrix sizes for weighted_square\");\n\n    size_t nx = XT.shape()[1];\n    size_t nv = XT.shape()[0];\n\n    //cerr << \"nx = \" << nx << \" nv = \" << nv << endl;\n\n    boost::multi_array<Float, 2> result(boost::extents[nv][nv]);\n\n    if (false) {\n        int chunk_size = 2048;  // ensure we fit in the cache\n        distribution<Float> Xid(chunk_size);\n\n        int x = 0;\n        while (x < nx) {\n            int nxc = std::min<size_t>(chunk_size, nx - x);\n\n            for (unsigned i = 0;  i < nv;  ++i) {\n                SIMD::vec_prod(&XT[i][x], &d[x], &Xid[0], nxc);\n            \n                for (unsigned j = 0;  j < nv;  ++j) {\n                    result[i][j] += SIMD::vec_dotprod_dp(&XT[j][x], &Xid[0], nxc);\n                }\n            }\n\n            x += nxc;\n        }\n    } else {\n        MLDB::parallelMap(0, nv, std::bind(doWeightedSquareRow<Float>,\n                                                 std::cref(XT),\n                                                 std::cref(d),\n                                                 std::ref(result),\n                                                 std::placeholders::_1));\n    }\n    \n    return result;\n}\n\nboost::multi_array<float, 2>\nweighted_square(const boost::multi_array<float, 2> & XT,\n                const distribution<float> & d)\n{\n    return weighted_square_impl(XT, d);\n}\n\nboost::multi_array<double, 2>\nweighted_square(const boost::multi_array<double, 2> & XT,\n                const distribution<double> & d)\n{\n    return weighted_square_impl(XT, d);\n}\n\ntemplate<typename Float>\nvoid svd_square_impl(boost::multi_array<Float, 2> & X,\n                     boost::multi_array<Float, 2> & VT,\n                     boost::multi_array<Float, 2> & U,\n                     distribution<Float> & svalues)\n{\n    size_t minmn = X.shape()[0];\n    ExcAssertEqual(minmn, X.shape()[1]);\n\n    // Decompose to get the pseudoinverse\n    svalues.clear();\n    svalues.resize(minmn);\n\n    VT.resize(boost::extents[minmn][minmn]);\n    U.resize(boost::extents[minmn][minmn]);\n\n    // SVD\n    int result = LAPack::gesdd(\"S\", minmn, minmn,\n                               X.data(), minmn,\n                               &svalues[0],\n                               &VT[0][0], minmn,\n                               &U[0][0], minmn);\n\n    if (result != 0)\n        throw Exception(\"gesdd returned non-zero\");\n}\n\nvoid svd_square(boost::multi_array<float, 2> & X,\n                boost::multi_array<float, 2> & VT,\n                boost::multi_array<float, 2> & U,\n                distribution<float> & svalues)\n{\n    return svd_square_impl(X, VT, U, svalues);\n}\n\nvoid svd_square(boost::multi_array<double, 2> & X,\n                boost::multi_array<double, 2> & VT,\n                boost::multi_array<double, 2> & U,\n                distribution<double> & svalues)\n{\n    return svd_square_impl(X, VT, U, svalues);\n}\n\n} // namespace ML\n", "meta": {"hexsha": "d4ab5cd86500165e1921c44b0c0d7bfdabd3ff84", "size": 26357, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/jml/algebra/least_squares.cc", "max_stars_repo_name": "kstepanmpmg/mldb", "max_stars_repo_head_hexsha": "f78791cd34d01796705c0f173a14359ec1b2e021", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T12:39:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-29T12:39:34.000Z", "max_issues_repo_path": "plugins/jml/algebra/least_squares.cc", "max_issues_repo_name": "tomzhang/mldb", "max_issues_repo_head_hexsha": "a09cf2d9ca454d1966b9e49ae69f2fe6bf571494", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-20T05:52:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-15T17:52:54.000Z", "max_forks_repo_path": "plugins/jml/algebra/least_squares.cc", "max_forks_repo_name": "matebestek/mldb", "max_forks_repo_head_hexsha": "f78791cd34d01796705c0f173a14359ec1b2e021", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-23T20:03:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-23T20:03:38.000Z", "avg_line_length": 30.8629976581, "max_line_length": 132, "alphanum_fraction": 0.5105664529, "num_tokens": 7073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5237675177564585}}
{"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_IDIVROUND2EVEN_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_IDIVROUND2EVEN_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing idivround2even capabilities\n\n    Computes the integer conversion of the rounded to even\n    division 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 = idivround2even_(x, y);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    as_integer_t<T> r = toints(round2even(x/y));\n    @endcode\n\n    If y is @ref Zero, it returns @ref Valmax (resp. @ref Valmin)\n    if x is positive (resp. negative) and 0 if x is @ref Zero.\n\n    @see toints, round2even\n\n  **/\n  const boost::dispatch::functor<tag::idivround2even_> idivround2even = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/idivround2even.hpp>\n#include <boost/simd/function/simd/idivround2even.hpp>\n\n#endif\n", "meta": {"hexsha": "17bc57bae2d9f315359495af25af14d89b0d302a", "size": 1391, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/idivround2even.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/idivround2even.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/idivround2even.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.7592592593, "max_line_length": 100, "alphanum_fraction": 0.6110711718, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5237675122326156}}
{"text": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n\t//dynamic programming approach sacrificing storage space for execution\n\t//time , creating a table of optimal values for every weight and a \n\t//second table of sets with the items collected so far in the knapsack\n\t//the best value is in the bottom right corner of the values table,\n\t//the set of items in the bottom right corner of the sets' table.\n@@ begin question optimal_knapsack\n@@ description: use dynamic programming to find the best assingment of weights to the knapsack\n@@ points: 100\n@@ time: 40 minutes\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n@@ end question\n\tbestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n\treturn bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n", "meta": {"hexsha": "8dc535742dac4bef9ad827fddc258049f3026d0e", "size": 925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Student CL/examples/01knapsack.cpp", "max_stars_repo_name": "RaphaelArkadyMeyer/LiveCoding", "max_stars_repo_head_hexsha": "e8fb357d68e7118bf03ef950b66108febb4c07ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Student CL/examples/01knapsack.cpp", "max_issues_repo_name": "RaphaelArkadyMeyer/LiveCoding", "max_issues_repo_head_hexsha": "e8fb357d68e7118bf03ef950b66108febb4c07ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Student CL/examples/01knapsack.cpp", "max_forks_repo_name": "RaphaelArkadyMeyer/LiveCoding", "max_forks_repo_head_hexsha": "e8fb357d68e7118bf03ef950b66108febb4c07ad", "max_forks_repo_licenses": ["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.4166666667, "max_line_length": 138, "alphanum_fraction": 0.7016216216, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650247, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5237598035853978}}
{"text": "// All content Copyright (C) 2018 Genomics plc\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include \"caller/diploid/genotypeUtils.hpp\"\n#include \"utils/indexedProduct.hpp\"\n\nnamespace wecall\n{\nnamespace caller\n{\n    namespace model\n    {\n        std::vector< double > computeGenotypeLikelihoods( const variant::GenotypeVector & genotypes,\n                                                          const utils::matrix_t & probReadsGivenHaplotypes,\n                                                          const variant::HaplotypeVector & haplotypes )\n        {\n            std::vector< double > genotypeLikelihoods( genotypes.size() );\n            const auto nReads = probReadsGivenHaplotypes.size1();\n            WECALL_ASSERT( nReads > 0, \"Only makes sense to compute likelihoods if there is read-data\" );\n\n            for ( std::size_t genotypeIndex = 0; genotypeIndex < genotypes.size(); ++genotypeIndex )\n            {\n                double thisGenotypeLogLikelihood = 0.0;\n                const auto hapIndicies = genotypes.getHaplotypeIndices( genotypeIndex );\n\n                // prior probability of any haplotype (given genotype).  Assumes uniform distribution across haplotypes\n                const auto haplotypePriorProbability = 1.0 / static_cast< double >( hapIndicies.size() );\n\n                for ( std::size_t readIndex = 0; readIndex < nReads; ++readIndex )\n                {\n                    double sumReadLikelihoodsOverHaplotypes = 0.0;\n                    for ( const auto & hapIndex : hapIndicies )\n                    {\n                        sumReadLikelihoodsOverHaplotypes += probReadsGivenHaplotypes( readIndex, hapIndex );\n                    }\n                    thisGenotypeLogLikelihood +=\n                        std::log( sumReadLikelihoodsOverHaplotypes * haplotypePriorProbability );\n                }\n\n                genotypeLikelihoods[genotypeIndex] = thisGenotypeLogLikelihood;\n            }\n\n            // Now re-scale all the genotype likelihoods for this individual, to prevent underflows, and\n            rescaleLogLikelihoods( genotypeLikelihoods, nReads > 0 );\n\n            // store the likelihoods as non-log values\n            std::transform( genotypeLikelihoods.begin(), genotypeLikelihoods.end(), genotypeLikelihoods.begin(), exp );\n\n            if ( false )\n            {\n                // print likelihoods of genotypes\n                WECALL_LOG( SUPER_DEBUG, \"Genotype likelihoods:-\" );\n                for ( std::size_t genotypeIndex = 0; genotypeIndex < genotypes.size(); ++genotypeIndex )\n                {\n                    if ( genotypeLikelihoods[genotypeIndex] > 1e-6 )\n                    {\n                        WECALL_LOG( SUPER_DEBUG, std::to_string( genotypeLikelihoods[genotypeIndex] ) + \" for \" +\n                                                      genotypes[genotypeIndex]->toString( haplotypes ) );\n                    }\n                }\n            }\n\n            return genotypeLikelihoods;\n        }\n    }\n}\n}\n", "meta": {"hexsha": "7abc102460f837fc4f228e6e98dad7f1321cd2a5", "size": 3047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/caller/diploid/genotypeUtils.cpp", "max_stars_repo_name": "dylex/wecall", "max_stars_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-08T15:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T07:13:05.000Z", "max_issues_repo_path": "cpp/src/caller/diploid/genotypeUtils.cpp", "max_issues_repo_name": "dylex/wecall", "max_issues_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-05T09:16:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-09T12:32:56.000Z", "max_forks_repo_path": "cpp/src/caller/diploid/genotypeUtils.cpp", "max_forks_repo_name": "dylex/wecall", "max_forks_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T15:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T07:28:33.000Z", "avg_line_length": 44.1594202899, "max_line_length": 119, "alphanum_fraction": 0.5671151953, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.523759800580525}}
{"text": "#include \"fbstab/components/dense_cholesky_solver.h\"\n\n#include <Eigen/Dense>\n#include <cmath>\n\n#include \"fbstab/components/dense_data.h\"\n#include \"fbstab/components/full_residual.h\"\n#include \"fbstab/components/full_variable.h\"\n\nnamespace fbstab {\n\nDenseCholeskySolver::DenseCholeskySolver(int nz, int nl, int nv)\n    : ldlt_(nz + nl) {\n  if (nz <= 0 || nv <= 0 || nl < 0) {\n    throw std::runtime_error(\n        \"In DenseCholeskySolver: nz and nv must be > 0 and nl >= 0\");\n  }\n  nz_ = nz;\n  nl_ = nl;\n  nv_ = nv;\n\n  K_.resize(nz_ + nl_, nz_ + nl_);\n  E_.resize(nz_, nz_);\n  r1_.resize(nz_ + nl_);\n  r2_.resize(nv_);\n  Gamma_.resize(nv_);\n  mus_.resize(nv_);\n  gamma_.resize(nv_);\n  B_.resize(nv_, nz_);\n}\n\nbool DenseCholeskySolver::Initialize(const FullVariable& x,\n                                     const FullVariable& xbar, double sigma) {\n  NullDataCheck();\n  if (!x.SameSize(xbar)) {\n    throw std::runtime_error(\n        \"In DenseCholeskySolver::Factor: inputs must be the same size\");\n  }\n  if (xbar.nz_ != nz_ || xbar.nv_ != nv_) {\n    throw std::runtime_error(\n        \"In DenseCholeskySolver::Factor: inputs must match object size.\");\n  }\n  if (sigma <= 0) {\n    throw std::runtime_error(\n        \"In DenseCholeskySolver::Factor: sigma must be positive.\");\n  }\n  const auto& H = data_->H_;\n  const auto& G = data_->G_;\n  const auto& A = data_->A_;\n\n  // E = H + sigma I + A'*diag(Gamma(x))*A\n  E_ = H + sigma * Eigen::MatrixXd::Identity(nz_, nz_);\n  Eigen::Vector2d pfb_gradient;\n  for (int i = 0; i < nv_; i++) {\n    const double ys = x.y(i) + sigma * (x.v(i) - xbar.v(i));\n    pfb_gradient = PFBGradient(ys, x.v(i));\n    gamma_(i) = pfb_gradient(0);\n    mus_(i) = pfb_gradient(1) + sigma * pfb_gradient(0);\n    Gamma_(i) = gamma_(i) / mus_(i);\n  }\n  // B is used to avoid temporaries\n  B_.noalias() = Gamma_.asDiagonal() * A;\n  E_.noalias() += A.transpose() * B_;\n\n  // K = [E G']\n  //     [G -S]\n  K_.block(0, 0, nz_, nz_) = E_;\n  K_.block(nz_, 0, nl_, nz_) = G;\n  K_.block(nz_, nz_, nl_, nl_) = -sigma * Eigen::MatrixXd::Identity(nl_, nl_);\n\n  // Factor K = LDL'\n  ldlt_.compute(K_);\n  Eigen::ComputationInfo status = ldlt_.info();\n  if (status != Eigen::Success) {\n    return false;\n  } else {\n    return true;\n  }\n}\n\nbool DenseCholeskySolver::Solve(const FullResidual& r, FullVariable* x) const {\n  if (x == nullptr) {\n    throw std::runtime_error(\n        \"In DenseCholeskySolver::Solve: x cannot be null.\");\n  }\n  if (!r.SameSize(*x)) {\n    throw std::runtime_error(\n        \"In DenseCholeskySolver::Solve residual and variable objects must be \"\n        \"the same size\");\n  }\n  if (x->nz_ != nz_ || x->nv_ != nv_ || x->nl_ != nl_) {\n    throw std::runtime_error(\n        \"In DenseCholeskySolver::Factor: inputs must match object size.\");\n  }\n  const auto& A = data_->A_;\n  const auto& b = data_->b_;\n\n  // This method solves the system:\n  // [E G'] [z] = [rz - A'*D^-1 * rv]\n  // [G -S] [l]   [-rl              ]\n  // Dv = rv + C*A*z\n  // Where D = diag(mus), C = diag(gamma) and K has been precomputed by the\n  // factor routine. See (28) and (29) in https://arxiv.org/pdf/1901.04046.pdf\n\n  // Compute rz - A'*(rv./mus) and store it in r1_.\n  r2_ = r.v().cwiseQuotient(mus_);\n  // r1_.noalias() = r.z() - A.transpose() * r2_;\n  r1_.segment(0, nz_).noalias() = r.z() - A.transpose() * r2_;\n  r1_.segment(nz_, nl_) = -r.l();\n\n  // Solve using the precomputed factorization then extract\n  r1_ = ldlt_.solve(r1_);\n  x->z() = r1_.segment(0, nz_);\n  x->l() = r1_.segment(nz_, nl_);\n\n  // Compute v = diag(1/mus) * (rv + diag(gamma)*A*z)\n  // written so as to avoid temporary creation\n  r2_.noalias() = A * x->z();\n  r2_.noalias() = gamma_.asDiagonal() * r2_;\n  r2_.noalias() += r.v();\n  x->v() = r2_.cwiseQuotient(mus_);\n\n  // y = b - Az\n  x->y() = b - A * x->z();\n\n  return true;\n}\n\nEigen::Vector2d DenseCholeskySolver::PFBGradient(double a, double b) const {\n  const double r = sqrt(a * a + b * b);\n  const double d = 1.0 / sqrt(2.0);\n\n  Eigen::Vector2d v;\n  if (r < zero_tolerance_) {\n    v(0) = alpha_ * (1.0 - d);\n    v(1) = alpha_ * (1.0 - d);\n\n  } else if ((a > 0) && (b > 0)) {\n    v(0) = alpha_ * (1.0 - a / r) + (1.0 - alpha_) * b;\n    v(1) = alpha_ * (1.0 - b / r) + (1.0 - alpha_) * a;\n\n  } else {\n    v(0) = alpha_ * (1.0 - a / r);\n    v(1) = alpha_ * (1.0 - b / r);\n  }\n\n  return v;\n}\n\nvoid DenseCholeskySolver::NullDataCheck() const {\n  if (data_ == nullptr) {\n    throw std::runtime_error(\n        \"DenseCholeskySolver tried to access problem data before it's linked.\");\n  }\n}\n\n}  // namespace fbstab\n", "meta": {"hexsha": "3e6bdda51d5ddc458f526f56a8d2f94be2cfa5cf", "size": 4533, "ext": "cc", "lang": "C++", "max_stars_repo_path": "fbstab/components/dense_cholesky_solver.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/components/dense_cholesky_solver.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/components/dense_cholesky_solver.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": 28.6898734177, "max_line_length": 80, "alphanum_fraction": 0.5863666446, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5237597950295335}}
{"text": "//\n// Copyright (c) 2019 INRIA\n//\n\n#include \"pinocchio/multibody/model.hpp\"\n\n# include <eigen3/Eigen/Core>\n#include \"pinocchio/math/matrix.hpp\"\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_matrix_matrix_product)\n{\n  using namespace pinocchio;\n  using namespace Eigen;\n  const Eigen::DenseIndex m = 20, n = 100;\n  MatrixXd M1(MatrixXd::Ones(m,n)), M2(MatrixXd::Ones(n,m));\n  MatrixMatrixProduct<MatrixXd,MatrixXd>::type res = M1 * M2;\n  BOOST_CHECK(!res.eval().isZero());\n}\n\nBOOST_AUTO_TEST_CASE(test_scalar_matrix_product)\n{\n  using namespace pinocchio;\n  using namespace Eigen;\n  const Eigen::DenseIndex m = 20, n = 100;\n  MatrixXd M(MatrixXd::Ones(m,n));\n  const double alpha = 0.;\n  ScalarMatrixProduct<double,MatrixXd>::type res = alpha * M;\n  BOOST_CHECK(res.eval().isZero());\n}\n\nBOOST_AUTO_TEST_CASE(test_matrix_scalar_product)\n{\n  using namespace pinocchio;\n  using namespace Eigen;\n  const Eigen::DenseIndex m = 20, n = 100;\n  MatrixXd M(MatrixXd::Ones(m,n));\n  const double alpha = 1.;\n  MatrixScalarProduct<MatrixXd,double>::type res = M * alpha;\n  BOOST_CHECK(res.eval() == M);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "a02b2d140b5491e66d03bb171e9f01162c3fd5be", "size": 1218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/eigen-basic-op.cpp", "max_stars_repo_name": "shubhamsingh91/Pinocchio_ss", "max_stars_repo_head_hexsha": "683f6d1ea445cf65e74056f2b18eb65a4151ff0f", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-30T18:01:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-30T21:49:06.000Z", "max_issues_repo_path": "unittest/eigen-basic-op.cpp", "max_issues_repo_name": "shubhamsingh91/Pinocchio_ss", "max_issues_repo_head_hexsha": "683f6d1ea445cf65e74056f2b18eb65a4151ff0f", "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/eigen-basic-op.cpp", "max_forks_repo_name": "shubhamsingh91/Pinocchio_ss", "max_forks_repo_head_hexsha": "683f6d1ea445cf65e74056f2b18eb65a4151ff0f", "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": 24.8571428571, "max_line_length": 61, "alphanum_fraction": 0.7323481117, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5237597948001558}}
{"text": "\n#include <NTL/mat_GF2.h>\n#include <NTL/mat_lzz_p.h>\n\nNTL_CLIENT\n\n\nvoid random(mat_zz_p& X, long n, long m)\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         random(X[i][j]);\n}\n\nvoid random(vec_zz_p& X, long n)\n{\n   X.SetLength(n);\n   long i;\n\n   for (i = 0; i < n; i++)\n      random(X[i]);\n}\n\nvoid cvt(mat_GF2& x, const mat_zz_p& a)\n{\n   long n = a.NumRows();\n   long m = a.NumCols();\n\n   x.SetDims(n, m);\n\n   long i, j;\n\n   for (i = 0; i < n; i++)\n      for (j = 0; j < m; j++)\n         x.put(i, j, rep(a[i][j]));\n}\n\n\nvoid cvt(vec_GF2& x, const vec_zz_p& a)\n{\n   long n = a.length();\n\n   x.SetLength(n);\n\n   long i;\n\n   for (i = 0; i < n; i++)\n      x.put(i, rep(a[i]));\n}\n\nint main()\n{\n   zz_p::init(2);\n\n   long i;\n\n   vec_GF2 v;\n   v.SetLength(5);\n   v[1] = 1;\n   v[0] = v[1];\n\n   if (v[0] != v[1]) Error(\"BitMatTest not OK!!\");\n\n   for (i=0; i < 8; i++) {\n      mat_zz_p a, x;\n      mat_GF2 A, X, X1;\n\n      long n = RandomBnd(500) + 1;\n      long m = RandomBnd(500) + 1;\n      cerr << n << \" \" << m << \"\\n\";\n\n      double t;\n\n      random(a, n, m);\n\n      t = GetTime();\n      kernel(x, a);\n      t = GetTime() - t;  cerr << t << \"\\n\";\n\n      cvt(A, a);\n\n      t = GetTime();\n      kernel(X, A);\n      t = GetTime() - t;  cerr << t << \"\\n\";\n\n      cerr << x.NumRows() << \"\\n\";\n\n      cvt(X1, x);\n\n      if (X1 != X) Error(\"BitMatTest NOT OK!!\");\n\n      if (!IsZero(X*A)) Error(\"BitMatTest NOT OK!!\");\n\n      cerr << \"\\n\";\n   }\n\n   cerr << \"BitMatTest OK\\n\";\n\n}\n\n", "meta": {"hexsha": "edd64beed1bdbfae248ceb0cbe96596791d1b9a3", "size": 1522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/tests/BitMatTest.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/BitMatTest.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/BitMatTest.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.6346153846, "max_line_length": 53, "alphanum_fraction": 0.4415243101, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5237597892491647}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\n#include \"test.hpp\"\n#include <boost/math/special_functions/legendre.hpp>\n#include <eve/function/legendre.hpp>\n#include <eve/function/diff/legendre.hpp>\n#include <eve/function/is_odd.hpp>\n#include <cmath>\n\n //==================================================================================================\n //== Types tests\n //==================================================================================================\n EVE_TEST_TYPES( \"Check return types of legendre on wide\"\n         , eve::test::simd::ieee_reals\n\n         )\n <typename T>(eve::as<T>)\n {\n   using v_t = eve::element_type_t<T>;\n   using wi_t = eve::as_integer_t<T>;\n   using i_t  = eve::as_integer_t<v_t>;\n   TTS_EXPR_IS( eve::legendre(i_t(), T())  , T);\n   TTS_EXPR_IS( eve::legendre(wi_t(), T())  , T);\n   TTS_EXPR_IS( eve::legendre(i_t(), v_t())  , v_t);\n   TTS_EXPR_IS( eve::legendre(wi_t(), v_t())  , T);\n\n };\n\n //==================================================================================================\n //== legendre tests\n //==================================================================================================\n EVE_TEST( \"Check behavior of legendre p on wide\"\n         , eve::test::simd::ieee_reals\n         , eve::test::generate(eve::test::between(-1, 1), eve::test::as_integer(eve::test::ramp(0)))\n         )\n   <typename T, typename I>(T const& a0,I const & i0)\n {\n   using v_t = eve::element_type_t<T>;\n   auto eve__legendrev  =  [](auto n, auto x) { return eve::legendre(n, x); };\n   for(unsigned int n=0; n < 5; ++n)\n   {\n     auto boost_legendre =  [&](auto i, auto) { return boost::math::legendre_p(n, a0.get(i)); };\n     TTS_ULP_EQUAL(eve__legendrev(n, a0), T(boost_legendre), 100);\n   }\n   auto boost_legendrev =  [&](auto i, auto) { return boost::math::legendre_p(i0.get(i), a0.get(i)); };\n   TTS_ULP_EQUAL(eve__legendrev(i0    , a0), T(boost_legendrev), 100);\n   for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n   {\n     auto boost_legendre2 =  [&](auto i, auto) { return boost::math::legendre_p(i0.get(i), a0.get(j)); };\n     TTS_RELATIVE_EQUAL(eve__legendrev(i0 , a0.get(j)), T(boost_legendre2), 0.01);\n   }\n   for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n   {\n     for(unsigned int n=0; n < eve::cardinal_v<T>; ++n)\n     {\n       TTS_RELATIVE_EQUAL(eve__legendrev(i0.get(j) , a0.get(n)), v_t(boost::math::legendre_p(i0.get(j), a0.get(n))), 0.01);\n     }\n   }\n };\n\n //==================================================================================================\n //== legendre tests\n //==================================================================================================\n EVE_TEST( \"Check behavior of legendre q on wide\"\n         , eve::test::simd::ieee_reals\n         , eve::test::generate(eve::test::between(-1.0, 1.0), eve::test::as_integer(eve::test::ramp(0)))\n         )\n   <typename T, typename I>(T const& a0,I const & i0)\n {\n   using v_t = eve::element_type_t<T>;\n   auto eve__legendrev  =  [](auto n, auto x) { return eve::q_kind(eve::legendre)(n, x); };\n   for(unsigned int n=0; n < 5; ++n)\n   {\n     auto boost_legendre =  [&](auto i, auto) { return boost::math::legendre_q(n, a0.get(i)); };\n     TTS_ULP_EQUAL(eve__legendrev(n, a0), T(boost_legendre), 100);\n   }\n\n   auto boost_legendrev =  [&](auto i, auto) { return boost::math::legendre_q(i0.get(i), a0.get(i)); };\n   TTS_ULP_EQUAL(eve__legendrev(i0    , a0), T(boost_legendrev), 100);\n   for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n   {\n     auto boost_legendre2 =  [&](auto i, auto) { return boost::math::legendre_q(i0.get(i), a0.get(j)); };\n     TTS_RELATIVE_EQUAL(eve__legendrev(i0 , a0.get(j)), T(boost_legendre2),  0.01);\n   }\n\n   for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n   {\n     for(unsigned int n=0; n < eve::cardinal_v<T>; ++n)\n     {\n       TTS_RELATIVE_EQUAL(eve__legendrev(i0.get(j) , a0.get(n)), v_t(boost::math::legendre_q(i0.get(j), a0.get(n))), 0.01);\n     }\n   }\n };\n\n EVE_TEST( \"Check behavior of diff(legendre) on wide\"\n         , eve::test::simd::ieee_reals\n         , eve::test::generate(eve::test::between(-1, 1), eve::test::as_integer(eve::test::ramp(0)))\n         )\n   <typename T, typename I>(T const& a0,I const & i0)\n {\n   using v_t = eve::element_type_t<T>;\n   auto eve__legendrev  =  [](auto n, auto x) { return eve::diff(eve::legendre)(n, x); };\n   for(unsigned int n=0; n < 5; ++n)\n   {\n     auto boost_legendre =  [&](auto i, auto) { return boost::math::legendre_p_prime(n, a0.get(i)); };\n     TTS_ULP_EQUAL(eve__legendrev(n, a0), T(boost_legendre), 100);\n   }\n\n   auto boost_legendrev =  [&](auto i, auto) { return boost::math::legendre_p_prime(i0.get(i), a0.get(i)); };\n   TTS_ULP_EQUAL(eve__legendrev(i0    , a0), T(boost_legendrev), 100);\n\n   for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n   {\n     auto boost_legendre2 =  [i0, a0, j](auto i, auto) { return boost::math::legendre_p_prime(i0.get(i), a0.get(j)); };\n     TTS_RELATIVE_EQUAL(eve__legendrev(i0 , a0.get(j)), T(boost_legendre2), 0.01);\n   }\n\n   for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n   {\n     for(unsigned int n=0; n < eve::cardinal_v<T>; ++n)\n     {\n       TTS_RELATIVE_EQUAL(eve__legendrev(i0.get(j) , a0.get(n)), v_t(boost::math::legendre_p_prime(i0.get(j), a0.get(n))), 0.01);\n     }\n   }\n };\n\n/////////////associated p legendre\nEVE_TEST( \"Check behavior of associated legendre p on wide\"\n        , eve::test::simd::ieee_doubles\n        , eve::test::generate(eve::test::between(-1.0, 1.0)\n                             , eve::test::as_integer(eve::test::ramp(0))\n                             , eve::test::as_integer(eve::test::reverse_ramp(0)))\n        )\n <typename T, typename I>(T a0, I i0, I j0)\n{\n//   using v_t = eve::element_type_t<T>;\n  auto eve__legendrev  =  [](auto m, auto n, auto x) { return eve::legendre(m, n, x); };\n  auto cse__legendrev  =  [](auto m, auto n, auto x) { return eve::condon_shortey(eve::legendre)(m, n, x); };\n  auto boost_legendrev =  [](auto m, auto n, auto x) { return boost::math::legendre_p(m, n, x); };\n  auto std_assoc = [](auto m, auto n, auto x) { return std::assoc_legendre(m, n, x); };\n  for(unsigned int k=0; k < eve::cardinal_v < T > ; ++k)\n  {\n    for(unsigned int n=0; n < eve::cardinal_v < I > ; ++n)\n    {\n      for(unsigned int p=0; p < eve::cardinal_v < I > ; ++p)\n      {\n        TTS_ULP_EQUAL(eve__legendrev(n, p, a0.get(k)), std_assoc(n, p, a0.get(k)), 100);\n        TTS_RELATIVE_EQUAL(cse__legendrev(n, p, a0.get(k)), boost_legendrev(n, p, a0.get(k)), 0.01);\n      }\n    }\n  }\n  TTS_ULP_EQUAL(eve__legendrev(j0, i0, a0), map(std_assoc, j0, i0, a0), 100);\n  TTS_ULP_EQUAL(cse__legendrev(i0, j0, a0), map(boost_legendrev, i0, j0, a0), 100);\n};\n", "meta": {"hexsha": "e5478e4634ebbc8654d6a2bc9dc93078590a91a9", "size": 7020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/polynomial/legendre.cpp", "max_stars_repo_name": "microblink/eve", "max_stars_repo_head_hexsha": "26d50d59190d3e2817c3ca95614e3e74f6c6f30a", "max_stars_repo_licenses": ["MIT"], "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/real/polynomial/legendre.cpp", "max_issues_repo_name": "microblink/eve", "max_issues_repo_head_hexsha": "26d50d59190d3e2817c3ca95614e3e74f6c6f30a", "max_issues_repo_licenses": ["MIT"], "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/real/polynomial/legendre.cpp", "max_forks_repo_name": "microblink/eve", "max_forks_repo_head_hexsha": "26d50d59190d3e2817c3ca95614e3e74f6c6f30a", "max_forks_repo_licenses": ["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.602484472, "max_line_length": 129, "alphanum_fraction": 0.537037037, "num_tokens": 2111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.52375978392755}}
{"text": "// Copyright (c) 2013-2016. This code was produced by the\n// Australian Centre for Field Robotics, The University of Sydney under\n// the Future Flight Planning project, University Reference 13996, contract\n// NSW-CPS-2011-015264, Work Orders 5, 7 and 8. The intellectual property\n// ownership is as set out in these contracts, as registered with\n// Commercial Development and Industry Partnerships.\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <Eigen/Geometry>\n#include <comma/base/exception.h>\n#include \"../../math/range_bearing_elevation.h\"\n#include \"sample.h\"\n\nnamespace snark { namespace spherical {\n\nnamespace impl {\n\nboost::mt19937 generator;\nboost::uniform_real< double > distribution( 0, 1 );\nboost::variate_generator< boost::mt19937&, boost::uniform_real< double > > random( generator, distribution );\n\n} // namespace impl {\n\ncoordinates pretty_uniform_sample( const coordinates& centre, double radius ) \n{\n    if( radius >= M_PI ) { COMMA_THROW( comma::exception, \"support containing circle radius less than pi; got \" << radius ); }\n    const Eigen::Matrix3d& r1 = Eigen::AngleAxis< double >( centre.longitude, Eigen::Vector3d( 0, 0, 1 ) ).toRotationMatrix();\n    double a = ( impl::random() * 2 - 1 ) * radius; // double a = impl::random() * M_PI * 2;\n    double b = ( impl::random() * 2 - 1 ) * radius; // double b = std::sqrt( impl::random() ) * radius;\n    const Eigen::Vector3d& s = snark::range_bearing_elevation( 1, a, b ).to_cartesian(); // const Eigen::Vector3d& s = snark::range_bearing_elevation( 1, b * std::cos( a ), b * std::sin( a ) ).to_cartesian();\n    const Eigen::Matrix3d& r2 = Eigen::AngleAxis< double >( centre.latitude, Eigen::Vector3d( 0, -1, 0 ) ).toRotationMatrix();\n    return coordinates( r1 * r2 * s );\n}\n\n} } // namespace snark { namespace spherical {\n", "meta": {"hexsha": "0c1cdf095a872d00f58f6159804c0ccf423dbb14", "size": 1889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/spherical_geometry/sample.cpp", "max_stars_repo_name": "mission-systems-pty-ltd/snark", "max_stars_repo_head_hexsha": "2bc8a20292ee3684d3a9897ba6fee43fed8d89ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2015-01-14T14:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T09:56:03.000Z", "max_issues_repo_path": "math/spherical_geometry/sample.cpp", "max_issues_repo_name": "NEU-LC/snark", "max_issues_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2015-01-21T00:57:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T04:22:35.000Z", "max_forks_repo_path": "math/spherical_geometry/sample.cpp", "max_forks_repo_name": "NEU-LC/snark", "max_forks_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:17:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T17:13:35.000Z", "avg_line_length": 49.7105263158, "max_line_length": 208, "alphanum_fraction": 0.7056643727, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.52375977826187}}
{"text": "//  Copyright (c) 2006 Xiaogang Zhang\n//  Copyright (c) 2006 John Maddock\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//  History:\n//  XZ wrote the original of this file as part of the Google\n//  Summer of Code 2006.  JM modified it to fit into the\n//  Boost.Math conceptual framework better, and to correctly\n//  handle the various corner cases.\n//\n\n#ifndef BOOST_MATH_ELLINT_3_HPP\n#define BOOST_MATH_ELLINT_3_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/special_functions/ellint_rf.hpp>\n#include <boost/math/special_functions/ellint_rj.hpp>\n#include <boost/math/special_functions/ellint_1.hpp>\n#include <boost/math/special_functions/ellint_2.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/math/special_functions/atanh.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/tools/workaround.hpp>\n#include <boost/math/special_functions/round.hpp>\n\n// Elliptic integrals (complete and incomplete) of the third kind\n// Carlson, Numerische Mathematik, vol 33, 1 (1979)\n\nnamespace boost { namespace math { \n   \nnamespace detail{\n\ntemplate <typename T, typename Policy>\nT ellint_pi_imp(T v, T k, T vc, const Policy& pol);\n\n// Elliptic integral (Legendre form) of the third kind\ntemplate <typename T, typename Policy>\nT ellint_pi_imp(T v, T phi, T k, T vc, const Policy& pol)\n{\n   // Note vc = 1-v presumably without cancellation error.\n   BOOST_MATH_STD_USING\n\n   static const char* function = \"boost::math::ellint_3<%1%>(%1%,%1%,%1%)\";\n\n\n   T sphi = sin(fabs(phi));\n   T result = 0;\n\n   if (k * k * sphi * sphi > 1)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"Got k = %1%, function requires |k| <= 1\", k, pol);\n   }\n   // Special cases first:\n   if(v == 0)\n   {\n      // A&S 17.7.18 & 19\n      return (k == 0) ? phi : ellint_f_imp(phi, k, pol);\n   }\n   if((v > 0) && (1 / v < (sphi * sphi)))\n   {\n      // Complex result is a domain error:\n      return policies::raise_domain_error<T>(function,\n         \"Got v = %1%, but result is complex for v > 1 / sin^2(phi)\", v, pol);\n   }\n\n   if(v == 1)\n   {\n      if (k == 0)\n         return tan(phi);\n\n      // http://functions.wolfram.com/08.06.03.0008.01\n      T m = k * k;\n      result = sqrt(1 - m * sphi * sphi) * tan(phi) - ellint_e_imp(phi, k, pol);\n      result /= 1 - m;\n      result += ellint_f_imp(phi, k, pol);\n      return result;\n   }\n   if(phi == constants::half_pi<T>())\n   {\n      // Have to filter this case out before the next\n      // special case, otherwise we might get an infinity from\n      // tan(phi).\n      // Also note that since we can't represent PI/2 exactly\n      // in a T, this is a bit of a guess as to the users true\n      // intent...\n      //\n      return ellint_pi_imp(v, k, vc, pol);\n   }\n   if((phi > constants::half_pi<T>()) || (phi < 0))\n   {\n      // Carlson's algorithm works only for |phi| <= pi/2,\n      // use the integrand's periodicity to normalize phi\n      //\n      // Xiaogang's original code used a cast to long long here\n      // but that fails if T has more digits than a long long,\n      // so rewritten to use fmod instead:\n      //\n      // See http://functions.wolfram.com/08.06.16.0002.01\n      //\n      if(fabs(phi) > 1 / tools::epsilon<T>())\n      {\n         if(v > 1)\n            return policies::raise_domain_error<T>(\n            function,\n            \"Got v = %1%, but this is only supported for 0 <= phi <= pi/2\", v, pol);\n         //  \n         // Phi is so large that phi%pi is necessarily zero (or garbage),\n         // just return the second part of the duplication formula:\n         //\n         result = 2 * fabs(phi) * ellint_pi_imp(v, k, vc, pol) / constants::pi<T>();\n      }\n      else\n      {\n         T rphi = boost::math::tools::fmod_workaround(T(fabs(phi)), T(constants::half_pi<T>()));\n         T m = boost::math::round((fabs(phi) - rphi) / constants::half_pi<T>());\n         int sign = 1;\n         if((m != 0) && (k >= 1))\n         {\n            return policies::raise_domain_error<T>(function, \"Got k=1 and phi=%1% but the result is complex in that domain\", phi, pol);\n         }\n         if(boost::math::tools::fmod_workaround(m, T(2)) > 0.5)\n         {\n            m += 1;\n            sign = -1;\n            rphi = constants::half_pi<T>() - rphi;\n         }\n         result = sign * ellint_pi_imp(v, rphi, k, vc, pol);\n         if((m > 0) && (vc > 0))\n            result += m * ellint_pi_imp(v, k, vc, pol);\n      }\n      return phi < 0 ? T(-result) : result;\n   }\n   if(k == 0)\n   {\n      // A&S 17.7.20:\n      if(v < 1)\n      {\n         T vcr = sqrt(vc);\n         return atan(vcr * tan(phi)) / vcr;\n      }\n      else\n      {\n         // v > 1:\n         T vcr = sqrt(-vc);\n         T arg = vcr * tan(phi);\n         return (boost::math::log1p(arg, pol) - boost::math::log1p(-arg, pol)) / (2 * vcr);\n      }\n   }\n   if((v < 0) && fabs(k) <= 1)\n   {\n      //\n      // If we don't shift to 0 <= v <= 1 we get\n      // cancellation errors later on.  Use\n      // A&S 17.7.15/16 to shift to v > 0.\n      //\n      // Mathematica simplifies the expressions\n      // given in A&S as follows (with thanks to\n      // Rocco Romeo for figuring these out!):\n      //\n      // V = (k2 - n)/(1 - n)\n      // Assuming[(k2 >= 0 && k2 <= 1) && n < 0, FullSimplify[Sqrt[(1 - V)*(1 - k2 / V)] / Sqrt[((1 - n)*(1 - k2 / n))]]]\n      // Result: ((-1 + k2) n) / ((-1 + n) (-k2 + n))\n      //\n      // Assuming[(k2 >= 0 && k2 <= 1) && n < 0, FullSimplify[k2 / (Sqrt[-n*(k2 - n) / (1 - n)] * Sqrt[(1 - n)*(1 - k2 / n)])]]\n      // Result : k2 / (k2 - n)\n      //\n      // Assuming[(k2 >= 0 && k2 <= 1) && n < 0, FullSimplify[Sqrt[1 / ((1 - n)*(1 - k2 / n))]]]\n      // Result : Sqrt[n / ((k2 - n) (-1 + n))]\n      //\n      T k2 = k * k;\n      T N = (k2 - v) / (1 - v);\n      T Nm1 = (1 - k2) / (1 - v);\n      T p2 = -v * N;\n      T t;\n      if(p2 <= tools::min_value<T>())\n         p2 = sqrt(-v) * sqrt(N);\n      else\n         p2 = sqrt(p2);\n      T delta = sqrt(1 - k2 * sphi * sphi);\n      if(N > k2)\n      {\n         result = ellint_pi_imp(N, phi, k, Nm1, pol);\n         result *= v / (v - 1);\n         result *= (k2 - 1) / (v - k2);\n      }\n\n      if(k != 0)\n      {\n         t = ellint_f_imp(phi, k, pol);\n         t *= k2 / (k2 - v);\n         result += t;\n      }\n      t = v / ((k2 - v) * (v - 1));\n      if(t > tools::min_value<T>())\n      {\n         result += atan((p2 / 2) * sin(2 * phi) / delta) * sqrt(t);\n      }\n      else\n      {\n         result += atan((p2 / 2) * sin(2 * phi) / delta) * sqrt(fabs(1 / (k2 - v))) * sqrt(fabs(v / (v - 1)));\n      }\n      return result;\n   }\n   if(k == 1)\n   {\n      // See http://functions.wolfram.com/08.06.03.0013.01\n      result = sqrt(v) * atanh(sqrt(v) * sin(phi)) - log(1 / cos(phi) + tan(phi));\n      result /= v - 1;\n      return result;\n   }\n#if 0  // disabled but retained for future reference: see below.\n   if(v > 1)\n   {\n      //\n      // If v > 1 we can use the identity in A&S 17.7.7/8\n      // to shift to 0 <= v <= 1.  In contrast to previous\n      // revisions of this header, this identity does now work\n      // but appears not to produce better error rates in \n      // practice.  Archived here for future reference...\n      //\n      T k2 = k * k;\n      T N = k2 / v;\n      T Nm1 = (v - k2) / v;\n      T p1 = sqrt((-vc) * (1 - k2 / v));\n      T delta = sqrt(1 - k2 * sphi * sphi);\n      //\n      // These next two terms have a large amount of cancellation\n      // so it's not clear if this relation is useable even if\n      // the issues with phi > pi/2 can be fixed:\n      //\n      result = -ellint_pi_imp(N, phi, k, Nm1, pol);\n      result += ellint_f_imp(phi, k, pol);\n      //\n      // This log term gives the complex result when\n      //     n > 1/sin^2(phi)\n      // However that case is dealt with as an error above, \n      // so we should always get a real result here:\n      //\n      result += log((delta + p1 * tan(phi)) / (delta - p1 * tan(phi))) / (2 * p1);\n      return result;\n   }\n#endif\n   //\n   // Carlson's algorithm works only for |phi| <= pi/2,\n   // by the time we get here phi should already have been\n   // normalised above.\n   //\n   BOOST_ASSERT(fabs(phi) < constants::half_pi<T>());\n   BOOST_ASSERT(phi >= 0);\n   T x, y, z, p, t;\n   T cosp = cos(phi);\n   x = cosp * cosp;\n   t = sphi * sphi;\n   y = 1 - k * k * t;\n   z = 1;\n   if(v * t < 0.5)\n      p = 1 - v * t;\n   else\n      p = x + vc * t;\n   result = sphi * (ellint_rf_imp(x, y, z, pol) + v * t * ellint_rj_imp(x, y, z, p, pol) / 3);\n\n   return result;\n}\n\n// Complete elliptic integral (Legendre form) of the third kind\ntemplate <typename T, typename Policy>\nT ellint_pi_imp(T v, T k, T vc, const Policy& pol)\n{\n    // Note arg vc = 1-v, possibly without cancellation errors\n    BOOST_MATH_STD_USING\n    using namespace boost::math::tools;\n\n    static const char* function = \"boost::math::ellint_pi<%1%>(%1%,%1%)\";\n\n    if (abs(k) >= 1)\n    {\n       return policies::raise_domain_error<T>(function,\n            \"Got k = %1%, function requires |k| <= 1\", k, pol);\n    }\n    if(vc <= 0)\n    {\n       // Result is complex:\n       return policies::raise_domain_error<T>(function,\n            \"Got v = %1%, function requires v < 1\", v, pol);\n    }\n\n    if(v == 0)\n    {\n       return (k == 0) ? boost::math::constants::pi<T>() / 2 : ellint_k_imp(k, pol);\n    }\n\n    if(v < 0)\n    {\n       // Apply A&S 17.7.17:\n       T k2 = k * k;\n       T N = (k2 - v) / (1 - v);\n       T Nm1 = (1 - k2) / (1 - v);\n       T result = 0;\n       result = boost::math::detail::ellint_pi_imp(N, k, Nm1, pol);\n       // This next part is split in two to avoid spurious over/underflow:\n       result *= -v / (1 - v);\n       result *= (1 - k2) / (k2 - v);\n       result += ellint_k_imp(k, pol) * k2 / (k2 - v);\n       return result;\n    }\n\n    T x = 0;\n    T y = 1 - k * k;\n    T z = 1;\n    T p = vc;\n    T value = ellint_rf_imp(x, y, z, pol) + v * ellint_rj_imp(x, y, z, p, pol) / 3;\n\n    return value;\n}\n\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type ellint_3(T1 k, T2 v, T3 phi, const boost::false_type&)\n{\n   return boost::math::ellint_3(k, v, phi, policies::policy<>());\n}\n\ntemplate <class T1, class T2, class Policy>\ninline typename tools::promote_args<T1, T2>::type ellint_3(T1 k, T2 v, const Policy& pol, const boost::true_type&)\n{\n   typedef typename tools::promote_args<T1, T2>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(\n      detail::ellint_pi_imp(\n         static_cast<value_type>(v), \n         static_cast<value_type>(k),\n         static_cast<value_type>(1-v),\n         pol), \"boost::math::ellint_3<%1%>(%1%,%1%)\");\n}\n\n} // namespace detail\n\ntemplate <class T1, class T2, class T3, class Policy>\ninline typename tools::promote_args<T1, T2, T3>::type ellint_3(T1 k, T2 v, T3 phi, const Policy& pol)\n{\n   typedef typename tools::promote_args<T1, T2, T3>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(\n      detail::ellint_pi_imp(\n         static_cast<value_type>(v), \n         static_cast<value_type>(phi), \n         static_cast<value_type>(k),\n         static_cast<value_type>(1-v),\n         pol), \"boost::math::ellint_3<%1%>(%1%,%1%,%1%)\");\n}\n\ntemplate <class T1, class T2, class T3>\ntypename detail::ellint_3_result<T1, T2, T3>::type ellint_3(T1 k, T2 v, T3 phi)\n{\n   typedef typename policies::is_policy<T3>::type tag_type;\n   return detail::ellint_3(k, v, phi, tag_type());\n}\n\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type ellint_3(T1 k, T2 v)\n{\n   return ellint_3(k, v, policies::policy<>());\n}\n\n}} // namespaces\n\n#endif // BOOST_MATH_ELLINT_3_HPP\n\n", "meta": {"hexsha": "44c76afdf908f071074ad5ced8823e09d65c3280", "size": 12048, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/lib/include/boost/math/special_functions/ellint_3.hpp", "max_stars_repo_name": "mamil/demo", "max_stars_repo_head_hexsha": "32240d95b80175549e6a1904699363ce672a1591", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2019-02-12T12:53:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:14:38.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/boost/math/special_functions/ellint_3.hpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/boost/math/special_functions/ellint_3.hpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2020-02-27T14:07:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T07:53:36.000Z", "avg_line_length": 32.0425531915, "max_line_length": 135, "alphanum_fraction": 0.5540338645, "num_tokens": 3803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5237112789006725}}
{"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/literal.hpp>\n#include <fcppt/no_init.hpp>\n#include <fcppt/algorithm/fold.hpp>\n#include <fcppt/cast/size.hpp>\n#include <fcppt/cast/to_signed.hpp>\n#include <fcppt/container/grid/fill.hpp>\n#include <fcppt/container/grid/object.hpp>\n#include <fcppt/math/vector/comparison.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 <functional>\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\tcontainer_grid_fill\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::container::grid::object<\n\t\tint,\n\t\t2\n\t>\n\tint2_grid;\n\n\tint2_grid test(\n\t\tint2_grid::dim(\n\t\t\t2u,\n\t\t\t2u\n\t\t),\n\t\tfcppt::no_init{}\n\t);\n\n\ttypedef\n\tint2_grid::pos\n\tpos;\n\n\tfcppt::container::grid::fill(\n\t\ttest,\n\t\t[](\n\t\t\tpos const _pos\n\t\t)\n\t\t{\n\t\t\treturn\n\t\t\t\tfcppt::cast::size<\n\t\t\t\t\tint\n\t\t\t\t>(\n\t\t\t\t\tfcppt::cast::to_signed(\n\t\t\t\t\t\tfcppt::algorithm::fold(\n\t\t\t\t\t\t\t_pos.storage(),\n\t\t\t\t\t\t\tfcppt::literal<\n\t\t\t\t\t\t\t\tpos::value_type\n\t\t\t\t\t\t\t>(\n\t\t\t\t\t\t\t\t0\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tstd::plus<\n\t\t\t\t\t\t\t\tpos::value_type\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}\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\ttest[\n\t\t\tpos(\n\t\t\t\t0u,\n\t\t\t\t0u\n\t\t\t)\n\t\t],\n\t\t0\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\ttest[\n\t\t\tpos(\n\t\t\t\t1u,\n\t\t\t\t0u\n\t\t\t)\n\t\t],\n\t\t1\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\ttest[\n\t\t\tpos(\n\t\t\t\t0u,\n\t\t\t\t1u\n\t\t\t)\n\t\t],\n\t\t1\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\ttest[\n\t\t\tpos(\n\t\t\t\t1u,\n\t\t\t\t1u\n\t\t\t)\n\t\t],\n\t\t2\n\t);\n}\n", "meta": {"hexsha": "bd732dc575688936cd381c71eb5b9eaeeba56700", "size": 1755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/container/grid/fill.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/container/grid/fill.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/container/grid/fill.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.7478991597, "max_line_length": 61, "alphanum_fraction": 0.6256410256, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5237112666160287}}
{"text": "//\n// Copyright 2019 Mateusz Loskot <mateusz at loskot dot net>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#include <boost/gil.hpp>\n#include <boost/gil/extension/numeric/convolve.hpp>\n\n#include <tuple>\n#include <type_traits>\n\n#define BOOST_TEST_MODULE test_ext_numeric_colvolve_cols\n#include \"unit_test.hpp\"\n#include \"unit_test_utility.hpp\"\n#include \"test_fixture.hpp\"\n#include \"core/image/test_fixture.hpp\"\n\nnamespace gil = boost::gil;\nnamespace fixture = boost::gil::test::fixture;\n\nBOOST_AUTO_TEST_SUITE(convolve_cols)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(image_1x1_kernel_1x1_identity, Image, fixture::image_types)\n{\n    auto const img = fixture::create_image<Image>(1, 1, 7);\n    auto img_out = fixture::create_image<Image>(1, 1, 0);\n\n    using pixel_t = typename Image::value_type;\n    using channel_t = typename gil::channel_type<pixel_t>::type;\n    auto const kernel = fixture::create_kernel<channel_t>({1});\n    gil::convolve_cols<pixel_t>(const_view(img), kernel, view(img_out));\n\n    // 1x1 kernel reduces convolution to multiplication\n    BOOST_TEST(gil::const_view(img).front() == gil::const_view(img_out).front());\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(image_1x1_kernel_3x3_identity, Image, fixture::image_types)\n{\n    auto const img = fixture::create_image<Image>(1, 1, 7);\n    auto img_out = fixture::create_image<Image>(1, 1, 0);\n\n    using pixel_t = typename Image::value_type;\n    using channel_t = typename gil::channel_type<pixel_t>::type;\n    auto const kernel = fixture::create_kernel<channel_t>({0, 0, 0, 0, 1, 0, 0, 0, 0});\n    gil::convolve_cols<pixel_t>(const_view(img), kernel, view(img_out));\n\n    BOOST_TEST(gil::const_view(img).front() == gil::const_view(img_out).front());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "51b7aceea33d32454d074e13c4a3dfc9d89b43da", "size": 1841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/gil/test/extension/numeric/convolve_cols.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/gil/test/extension/numeric/convolve_cols.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/gil/test/extension/numeric/convolve_cols.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": 34.7358490566, "max_line_length": 89, "alphanum_fraction": 0.7398153178, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5237112666160286}}
{"text": "/*****************************************************************************\n *\n * ALPS DMFT Project\n *\n * Copyright (C) 2005 - 2009 by Emanuel Gull <gull@phys.columbia.edu>\n *                              Philipp Werner <werner@itp.phys.ethz.ch>,\n *                              Sebastian Fuchs <fuchs@theorie.physik.uni-goettingen.de>\n *                              Matthias Troyer <troyer@comp-phys.org>\n *\n *\n * This software is part of the ALPS Applications, published under the ALPS\n * Application License; you can use, redistribute it and/or modify it under\n * the terms of the license, either version 1 or (at your option) any later\n * version.\n * \n * You should have received a copy of the ALPS Application License along with\n * the ALPS Applications; see the file LICENSE.txt. If not, the license is also\n * available from http://alps.comp-phys.org/.\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, TITLE AND NON-INFRINGEMENT. IN NO EVENT \n * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE \n * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, \n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \n * DEALINGS IN THE SOFTWARE.\n *\n *****************************************************************************/\n\n\n#include <boost/numeric/bindings/ublas.hpp>\n#include <boost/numeric/bindings/lapack/driver/gesv.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <math.h>\n#include \"fouriertransform.h\"\n\nusing namespace Eigen;\n\ntypedef boost::numeric::ublas::matrix<double,boost::numeric::ublas::column_major> dense_matrix;\n\nFourierTransformer::FourierTransformer(const double beta, \n                                       const VectorXd &ftail)\n    : beta_(beta), c_(ftail) {\n  if (c_.size() < 3) \n    throw std::length_error(\"The tail should contains up to at least the third order\");\n}\n\n// backward_ft G(iwn)->G(tau) works for cluster Green's functions\nvoid FourierTransformer::backward_ft(const VectorXcd &G_omega, \n                                     VectorXd &G_tau, const int N_tau) const {\n  unsigned int N_omega = G_omega.size();\n  VectorXcd G_omega_no_model(G_omega);\n  double dt = beta_/N_tau;\n  \n  G_tau.resize(N_tau+1);\n  if (c_(0) == 0 && c_(1) == 0 && c_(2) == 0) {\n    //nothing happening in this gf.\n    for (int i = 0; i <= N_tau; i++) {\n      G_tau(i)=0.;\n    }\n  } else {\n    for (int k = 0; k < N_omega; k++) {\n      std::complex<double> iw(0,(2*k+1)*M_PI/beta_);\n      G_omega_no_model(k) -= f_omega(iw, c_(0),c_(1), c_(2));\n    }\n    for (int i=0; i<N_tau; i++) {\n      G_tau(i) = f_tau(i*dt, beta_, c_(0), c_(1), c_(2));\n      for (int k=0; k<N_omega; k++) {\n        double wt((2*k+1)*i*M_PI/N_tau);\n        G_tau(i) += 2/beta_*(cos(wt)*G_omega_no_model(k).real()+\n                             sin(wt)*G_omega_no_model(k).imag());\n      }\n    }\n    G_tau(N_tau) = -c_[0];\n    G_tau(N_tau)-= G_tau(0);\n  }\n}\n\nvoid generate_spline_matrix(dense_matrix & spline_matrix, double dt) {\n  // spline_matrix has dimension (N+1)x(N+1)\n  int Np1 = spline_matrix.size1();\n  //std::cout<<\"spline matrix size is: \"<<Np1<<std::endl;\n  // A is the matrix whose inverse defines spline_matrix\n  //   \n  //      6                   6\n  //      1  4  1\n  //         1  4  1\n  // A =        ...\n  //\n  //                    1  4  1\n  //     -2 -1     0       1  2\n  spline_matrix.clear(); \n  dense_matrix A = 4*dt/6.*boost::numeric::ublas::identity_matrix<double>(Np1);\n  \n  for (int i=1; i<Np1-1; i++) {\n    A(i,i-1) = dt/6.;\n    A(i,i+1) = dt/6.;\n  }\n  A(0,0) = 1.;\n  A(0, Np1-1) = 1.;\n  A(Np1-1, 0) = -2.*dt/6.;\n  A(Np1-1, 1) = -1.*dt/6.;\n  A(Np1-1, Np1-2) = 1*dt/6.;\n  A(Np1-1, Np1-1) = 2*dt/6.;\n  \n  // solve A*spline_matrix=I\n  // gesv solves A*X=B, input for B is I, output (=solution X) is spline_matrix\n  spline_matrix = boost::numeric::ublas::identity_matrix<double>(Np1);   \n  boost::numeric::ublas::vector<fortran_int_t> ipivot(A.size1());\n  boost::numeric::bindings::lapack::gesv(A, ipivot,spline_matrix);\n}\n\nvoid evaluate_second_derivatives(double dt, dense_matrix & spline_matrix, \n    std::vector<double> & g, std::vector<double> & second_derivatives, \n    const double c1g, const double c2g, const double c3g) {\n  // g, rhs and second_derivatives have dimension N+1\n  int Np1 = spline_matrix.size1();\n  //assert(c1g==1); \n  // rhs is the vector containing the data of the curve y = g(tau), which allows to \n  // compute the vector of second derivatives y'' at times tau_n by evaluating\n  // y'' = spline_matrix * rhs(y)\n  //\n  //                         0                                \n  //                         y0 - 2*y1 + y2\n  //                         y1 - 2*y2 + y3\n  // rhs = 6/(delta_tau)^2 * ...\n  //\n  //                         yNp1-3 - 2*yNp1-2 + yNp1-1\n  //                         y0 - y1 + yNp1-2 - yNp1-1     \n  \n  std::vector<double> rhs(Np1, 0);\n  std::cout<<\"constants: \"<<c1g<<\" \"<<c2g<<\" \"<<c3g<<std::endl;\n  rhs[0] = -c3g; //G''(0)+G''(beta)=-c3\n  for (int i=1; i<Np1-1; i++) {\n    rhs[i] = (g[i-1]-2*g[i]+g[i+1])/dt;\n  }\n  rhs[Np1-1] = c2g -1./dt*(-g[0] + g[1] -g[Np1-2] + g[Np1-1]);\n  \n  for (int i=0; i<Np1; i++) {\n    second_derivatives[i]=0;\n    for (int j=0; j<Np1; j++) {\n      second_derivatives[i] += spline_matrix(i,j)*rhs[j];\n    }\n  }\n}\n\n// \n// calculations following Armin Comadac's thesis (see the thesis for details)\n// S1 = G'(0) + G'(beta) = y'(0) + y'(L)\n// S2 = G''(0) + G''(beta) = y''(0) + y''(L)\n// remember that S1 and S2 can be different from the Green's function's tail\n// in details: S1 = G2\n//             S2 = -G3\n//\nVectorXd ArminGetSecondDerivative(const VectorXd &y, \n    const double beta, const double S1, const double S2) {\n  const int L = y.size()-1;\n  double dx = beta/L;\n\n  VectorXd X(L+1), Y(L), Z(L);\n  // coefficients for L, U matrices (Armin's notations)\n  VectorXd a(L), b(L), d(L);\n  Y.setZero();\n  Z.setZero();\n  Y(0) = 6. * ((y[1]-y[0]+y[L]-y[L-1]-S1*dx) / (dx*dx) + S2/3.);\n  Z(0) = Y(0);\n  a(0) = 4.;\n  b(0) = -1./a(0);\n  d(0) = -1.;\n  for (int i = 1; i < L-1; ++i) {\n    a(i) = 4. - 1./a(i-1);\n    b(i) = -b(i-1)/a(i);\n    d(i) = -d(i-1)/a(i-1);\n    Y(i) = 6. * (y(i+1) - 2*y(i) + y(i-1)) / (dx*dx);\n    Z(i) = Y(i) - Z(i-1)/a(i-1);\n  }\n  Y(L-1) = 6. * ((y(L) - 2*y(L-1) + y(L-2)) / (dx*dx) - S2 / 6.);\n  a(L-1) = 4.;\n  b(L-2) = (1.-b(L-3))/a(L-2);\n  d(L-2) = 1. - d(L-3)/a(L-3);\n  for (int i = 0; i < L-1; ++i)\n    a(L-1) -= b(i)*d(i);\n  Z(L-1) = Y(L-1);\n  for (int i = 0; i < L-1; ++i)\n    Z(L-1) -= b(i)*Z(i);\n\n  X(L-1) = Z(L-1) / a(L-1);\n  X(L-2) = (Z(L-2)-d(L-2)*X(L-1)) / a(L-2);\n  for (int i = L-3; i >= 0; --i)\n    X(i) = (Z(i) - X(i+1) - d(i)*X(L-1))/a(i);\n  X(L) = S2 - X(0);\n\n  return X;\n}\n\n\n// forward_ft G(tau)->G(iwn) works for cluster Green's functions\nvoid FourierTransformer::Armin_forward_ft(const VectorXd &gtau, VectorXcd &gomega,\n                                          const int num_matsubara) const {\n  int N = gtau.size()-1;\n  double dt = beta_/N;\n  VectorXcd v_omega(num_matsubara);\n  gomega.resize(num_matsubara);\n  VectorXd v2(ArminGetSecondDerivative(gtau, beta_, c_(1), -c_(2)));\n\n  // DEBUG\n//  const VectorXd &v(gtau);\n//  std::cout<<\"c1 is: \"<<c_(0)<<\" computed: \"<<-v[0]-v[N]<<std::endl;\n//  std::cout<<\"c2 is: \"<<c_(1)<<\" computed: \"<<(v[1]-v[0]+v[N]-v[N-1])/dt<<std::endl;\n//  std::cout<<\"c3 is: \"<<c_(2)<<\" computed: \"<<-(v[2]-2*v[1]+v[0]+v[N-2]-2*v[N-1]+v[N])/(dt*dt)<<std::endl;\n\n  v_omega.setZero();\n  for (int k = 0; k < num_matsubara; ++k) {\n    std::complex<double> iw(0, M_PI*(2*k+1)/beta_);\n    for (int n = 1; n < N; n++) {\n      //partial integration, four times. \n      //Then approximate the fourth derivative by finite differences\n      v_omega(k) += exp(iw*(n*dt))*(v2(n+1)-2*v2(n)+v2(n-1)); \n    }\n    // the third derivative, on the boundary\n    v_omega(k) += (v2(1) - v2(0) + v2(N) - v2(N-1)); \n    v_omega(k) *= 1./(dt*iw*iw*iw*iw);\n    // the boundary terms of the first, second, and third partial integration.\n    v_omega(k) += f_omega(iw, c_(0), c_(1), c_(2)); \n    //std::cout<<\"derivative at boundary: \"<<-v2[1] + v2[0] + v2[N] - v2[N-1]<<\" divisor: \"<< 1./(dt*iw*iw*iw*iw)<<std::endl;\n    // the proper convention for the self consistency loop here.\n    gomega(k)=v_omega(k); \n  }\n} \n\n// forward_ft G(tau)->G(iwn) works for cluster Green's functions\nvoid FourierTransformer::forward_ft(const VectorXd &gtau, VectorXcd &gomega,\n                                    const int num_matsubara) const {\n  std::vector<double> v(gtau.size());\n  std::vector<std::complex<double> > v_omega(num_matsubara);\n  int Np1 = v.size();\n  int N = Np1-1;\n  int N_omega = v_omega.size();\n  double dt = beta_/N;\n\n  gomega.resize(num_matsubara);\n  for(int tau=0;tau<Np1;++tau) {\n    v[tau]=gtau(tau);\n  }\n  \n  dense_matrix spline_matrix(Np1, Np1);\n  generate_spline_matrix(spline_matrix, dt);\n  // matrix containing the second derivatives y'' \n  // of interpolated y=v[tau] at points tau_n \n  std::vector<double> v2(Np1, 0); \n  evaluate_second_derivatives(dt/*,beta_*/, spline_matrix, v, v2, \n      c_(0), c_(1), c_(2));\n  v_omega.assign(N_omega, 0);\n  for (int k=0; k<N_omega; k++) {\n    std::complex<double> iw(0, M_PI*(2*k+1)/beta_);\n    for (int n=1; n<N; n++) {\n      //partial integration, four times. \n      //Then approximate the fourth derivative by finite differences\n      v_omega[k] += exp(iw*(n*dt))*(v2[n+1]-2*v2[n]+v2[n-1]); \n    }\n    // the third derivative, on the boundary\n    v_omega[k] += (v2[1] - v2[0] + v2[N] - v2[N-1]); \n    v_omega[k] *= 1./(dt*iw*iw*iw*iw);\n    // the boundary terms of the first, second, and third partial integration.\n    v_omega[k] += f_omega(iw, c_(0), c_(1), c_(2)); \n    //std::cout<<\"derivative at boundary: \"<<-v2[1] + v2[0] + v2[N] - v2[N-1]<<\" divisor: \"<< 1./(dt*iw*iw*iw*iw)<<std::endl;\n    // the proper convention for the self consistency loop here.\n    gomega(k)=v_omega[k]; \n  }\n} \n\n", "meta": {"hexsha": "1919da61da4c3357308be6929a12a5d9037578a3", "size": 10012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppext/cubic_spline_ft/fouriertransform.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/cubic_spline_ft/fouriertransform.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/cubic_spline_ft/fouriertransform.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": 36.8088235294, "max_line_length": 125, "alphanum_fraction": 0.5578306033, "num_tokens": 3497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.5236695399456255}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SCALAR_REMAINDER_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SCALAR_REMAINDER_HPP_INCLUDED\n#include <boost/simd/toolbox/arithmetic/functions/remainder.hpp>\n#include <boost/simd/include/functions/scalar/abs.hpp>\n#include <boost/simd/include/functions/scalar/negate.hpp>\n#include <boost/simd/include/functions/scalar/idivround.hpp>\n#include <boost/simd/include/functions/scalar/divround.hpp>\n/////////////////////////////////////////////////////////////////////////////\n// The remainder() function computes the remainder of dividing x by y.  The\n// return value is x-n*y, where n is the value x / y, rounded to the nearest\n// integer.  If the boost::simd::absolute value of x-n*y is 0.5, n is chosen to be even.\n// The drem function is just an alias for the same thing.\n/////////////////////////////////////////////////////////////////////////////\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::remainder_, tag::cpu_\n                            , (A0)\n                            , (scalar_< arithmetic_<A0> >)(scalar_< arithmetic_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      if (!a1) return a0;\n      return a0-idivround(a0, a1)*a1;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::remainder_, tag::cpu_\n                            , (A0)\n                            , (scalar_< floating_<A0> >)(scalar_< floating_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return a0-divround(a0, a1)*a1;\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "91a16f3b2b97071588d6990090d4d876fe87eaad", "size": 2212, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/remainder.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/remainder.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/remainder.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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.7358490566, "max_line_length": 88, "alphanum_fraction": 0.5519891501, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5236695396570525}}
{"text": "// Copyright 2022 Haruki Uchiito\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\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell 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\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 DEALINGS\n// IN THE SOFTWARE.\n\n// clang-format off\n#include <ndt_2d_slam/scan_matcher_2d.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\n#include <algorithm>\n#include <tuple>\n#include <vector>\n// clang-format on\n\nnamespace NDT2DSLAM {\n\nCovarianceMat correctMatrix(const CovarianceMat& original, double smaller,\n                            double bigger, double minimum) {\n    double nsmaller = smaller;\n    if (smaller < minimum)\n        nsmaller = minimum;\n    else\n        return original;\n    double dsum = (nsmaller * nsmaller - bigger * bigger) / (nsmaller - bigger);\n    double a11 = dsum / 2;\n    double a22 = dsum - a11;\n    double a212 = sqrt(bigger * bigger - dsum * bigger + a11 * a22);\n\n    CovarianceMat corrected;\n    corrected << a11, a212, a212, a22;\n\n    return corrected;\n}\n\nvoid Cell::addPoint(double x, double y) {\n    Eigen::Index nCol = points.cols();\n    for (auto i = 0; i < nCol; ++i)  // avoid adding same point\n        if (points(0, i) == x && points(1, i) == y) return;\n    points.conservativeResize(Eigen::NoChange, nCol + 1);\n    points(0, nCol) = x;\n    points(1, nCol) = y;\n}\n\nvoid Cell::ndt() {\n    if (points.cols() > 0) mean = points.rowwise().mean();\n\n    if (points.cols() < 3) {\n        validity = false;\n        return;\n    }\n\n    Eigen::MatrixXd diff = points.colwise() - mean;\n    covariance =\n        (diff * diff.adjoint()) / static_cast<double>(points.cols() - 1);\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> solver(covariance);\n    Eigen::Vector2d evs = solver.eigenvalues();\n    // std::cout << \"evs: \\n\" << evs << std::endl;\n    // std::cout << \"evec \\n\" << solver.eigenvectors() << std::endl;\n\n    const double seThreshold = 0.001;\n    double smaller = std::min(evs(0), evs(1));\n    double bigger = std::max(evs(0), evs(1));\n    double minimum = bigger * seThreshold;\n    if (smaller < minimum) {  // correction required\n        covariance = correctMatrix(covariance, smaller, bigger, minimum);\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> fixed(covariance);\n        // std::cout << \"fixed cov: \\n\" << covariance << std::endl;\n        // std::cout << \"fixed evs: \\n\" << fixed.eigenvalues() << std::endl;\n        // std::cout << \"fixed evec: \\n\" << fixed.eigenvectors() <<\n        // std::endl;\n    }\n    iCovariance = covariance.inverse();\n\n    validity = true;\n}\n\nvoid Cell::calcCenterOfGravity() {\n    if (points.cols() > 0) mean = points.rowwise().mean();\n}\n\nCellGridFilter::CellGridFilter(double gridSize, const Scan2D& scan,\n                               std::ostream& outStream)\n    : _gridSize(gridSize), _outStream(outStream) {\n    std::cerr << \"[cell grid filter]\" << std::endl;\n    std::cerr << \"scan size: \" << scan.size() << std::endl;\n    // process reference scan\n    const std::vector<double>& xv = scan.getXVec();\n    _minX = *std::min_element(xv.begin(), xv.end());\n    _maxX = *std::max_element(xv.begin(), xv.end());\n    const std::vector<double>& yv = scan.getYVec();\n    _minY = *std::min_element(yv.begin(), yv.end());\n    _maxY = *std::max_element(yv.begin(), yv.end());\n\n    // range of pointcloud\n    double rangeX = _maxX - _minX;\n    double rangeY = _maxY - _minY;\n\n    // number of cells in both direction\n    _nCellX = 1 + static_cast<int>(rangeX / _gridSize);\n    _nCellY = 1 + static_cast<int>(rangeY / _gridSize);\n\n    _cells.resize(_nCellX * _nCellY);\n\n    // distribute points to each cells\n    for (size_t i = 0; i < scan.size(); ++i) {\n        double x = scan.points(0, i);\n        double y = scan.points(1, i);\n        auto [ix, iy] = xy2cellXYIdx(x, y);\n        int idx = iy * _nCellX + ix;\n        if (idx >= 0 && idx < static_cast<int>(_cells.size()))\n            _cells[idx].addPoint(x, y);\n    }\n\n    std::vector<double> xs, ys;\n    for (auto& cell : _cells) {\n        if (cell.points.size() == 0) continue;\n        cell.calcCenterOfGravity();\n        xs.emplace_back(cell.mean(0));\n        ys.emplace_back(cell.mean(1));\n    }\n    _result = Scan2D(xs, ys);\n}\n\nstd::tuple<int, int> CellGridFilter::xy2cellXYIdx(double x, double y) const {\n    int xIdx = static_cast<int>((x - _minX) / _gridSize) + 1;\n    int yIdx = static_cast<int>((y - _minY) / _gridSize) + 1;\n\n    return {xIdx, yIdx};\n}\n\n// NDTScanMatcher implementation\nNDTScanMatcher::NDTScanMatcher(double gridSize, double epsilonTranslation,\n                               double epsilonRotation, const Scan2D& refScan,\n                               std::ostream& outStream = std::cout)\n    : _debug(false),\n      _debugOut(\"\"),\n      _gridSize(gridSize),\n      _halfGridSize(gridSize / 2.0),\n      _epsilonTranslation(epsilonTranslation),\n      _epsilonRotation(epsilonRotation),\n      _outStream(outStream) {\n    // process reference scan\n    const std::vector<double>& xv = refScan.getXVec();\n    _minX = *std::min_element(xv.begin(), xv.end());\n    _maxX = *std::max_element(xv.begin(), xv.end());\n    const std::vector<double>& yv = refScan.getYVec();\n    _minY = *std::min_element(yv.begin(), yv.end());\n    _maxY = *std::max_element(yv.begin(), yv.end());\n\n    // range of pointcloud\n    double rangeX = _maxX - _minX;\n    double rangeY = _maxY - _minY;\n    // number of cells in both direction\n    _nCellX =\n        2 + static_cast<int>((rangeX + _halfGridSize - _halfGridSize * 0.01) /\n                             _halfGridSize);\n    _nCellY =\n        2 + static_cast<int>((rangeY + _halfGridSize - _halfGridSize * 0.01) /\n                             _halfGridSize);\n\n    _cells.resize(_nCellX * _nCellY);\n    // distribute points to each cells\n    for (Eigen::Index i = 0; i < refScan.points.cols(); ++i) {\n        double x = refScan.points(0, i);\n        double y = refScan.points(1, i);\n        // base cell index for x, y direction\n        auto [bcxIdx, bcyIdx] = xy2cellXYIdx(x, y);\n        // each point must be corresponds to 4 cells\n        for (int j = 0; j < 4; ++j) {\n            try {\n                int idx = cellXYIdx2Idx({bcxIdx + _dx[j], bcyIdx + _dy[j]});\n                _cells[idx].addPoint(x, y);\n            } catch (const std::out_of_range& e) {\n                // just skip\n            }\n        }\n    }\n\n    // transform points to normal distribution on each cell\n    for (auto& cell : _cells) cell.ndt();\n\n    return;\n\n    _outStream << \"[init]\" << std::endl;\n    int cnt = 0;\n    for (auto& cell : _cells) {\n        if (cell.validity) {\n            _outStream << \"idx: \" << cnt << std::endl;\n            _outStream << \"pnum: \" << cell.points.cols() << std::endl;\n            _outStream << \"points:\\n\" << cell.points << std::endl;\n            _outStream << \"mean: \" << cell.mean.transpose() << std::endl;\n            _outStream << \"covariance:\\n\" << cell.covariance << std::endl;\n            Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> fixed(\n                cell.covariance);\n            _outStream << \"fixed evs: \" << fixed.eigenvalues().transpose()\n                       << std::endl;\n            return;\n\n            // std::cout << \"fixed evec: \\n\" << fixed.eigenvectors() <<\n        }\n        cnt++;\n    }\n}\n\nTransform2D NDTScanMatcher::match(const Transform2D& initialGuess,\n                                  const Scan2D& currentScan) {\n    _outStream << \"[matching]\" << std::endl;\n    _outStream << initialGuess << std::endl;\n    Transform2D currentGuess = initialGuess;\n\n    iterationCount = 0;\n    const int iterMax = 50;\n    while (iterationCount++ < iterMax) {\n        auto transformedCurrentScan = currentScan.transformBy(currentGuess);\n\n        double sinT = sin(currentGuess.theta);\n        double cosT = cos(currentGuess.theta);\n        Eigen::MatrixXd partialRP(3, 2);\n        partialRP << 1, 0, 0, 1, 0, 0;\n        Eigen::MatrixXd hesse1 = Eigen::MatrixXd::Zero(3, 3);\n        Eigen::MatrixXd hesse23 = Eigen::MatrixXd::Zero(3, 3);\n\n        double score = 0.0;  // of ndt scan matching\n        Eigen::VectorXd gradient = Eigen::VectorXd::Zero(3);\n        Eigen::MatrixXd hessian = Eigen::MatrixXd::Zero(3, 3);\n\n        int cnt = 0;\n        for (size_t i = 0; i < transformedCurrentScan.size(); ++i) {\n            const double ox = currentScan.getX(i), oy = currentScan.getY(i);\n            const double tx = transformedCurrentScan.getX(i);\n            const double ty = transformedCurrentScan.getY(i);\n\n            Eigen::Vector2d partialRP3(1, 2);\n            // partialRP3 << -sinT * ox - cosT * oy, cosT * ox - sinT * oy;\n            partialRP(2, 0) = -sinT * ox - cosT * oy;\n            partialRP(2, 1) = cosT * ox - sinT * oy;\n            Eigen::MatrixXd elem33(1, 2);\n            elem33 << -cosT * ox + sinT * oy, -sinT * ox - cosT * oy;\n\n            // base cell index for x, y direction\n            auto [bcxIdx, bcyIdx] = xy2cellXYIdx(tx, ty);\n            for (int j = 0; j < 4; ++j) {\n                try {\n                    int idx = cellXYIdx2Idx({bcxIdx + _dx[j], bcyIdx + _dy[j]});\n                    // _cells[idx] is the corresponding cell to point(xy)\n                    if (!_cells[idx].validity) continue;\n                    cnt++;\n\n                    // from cell\n                    Eigen::Vector2d residual =\n                        Eigen::Vector2d{tx, ty} - _cells[idx].mean;\n                    Eigen::Matrix2d invCovariance = _cells[idx].iCovariance;\n                    auto icovRes = invCovariance * residual;\n\n                    double expin = -0.5 * residual.transpose() * icovRes;\n                    double expN = std::exp(expin);\n\n                    // update score\n                    score += expN;\n                    // update gradient\n                    gradient += partialRP * icovRes * expN;\n\n                    // update Hessian\n                    auto elem33ans = elem33 * icovRes;\n                    // assert(elem33.cols() == 1 && elem33.rows() == 1);\n                    hesse1(2, 2) = elem33ans(0, 0);\n\n                    for (int ii = 0; ii < 3; ++ii) {\n                        auto ppi = partialRP.block<1, 2>(ii, 0);\n                        auto ppiicov = ppi * invCovariance;\n                        auto ppiicovRes = ppi * icovRes;\n                        for (int jj = 0; jj < 3; ++jj) {\n                            auto ppj = partialRP.block<1, 2>(jj, 0);\n                            auto hresult = ppiicov * ppj.transpose() +\n                                           ppiicovRes * ppj * icovRes;\n                            // assert(hresult.cols() == 1 &&\n                            // hresult.rows() == 1);\n                            hesse23(ii, jj) = hresult(0, 0);\n                        }\n                    }\n\n                    hessian += expN * (hesse1 + hesse23);\n                } catch (const std::out_of_range& e) {\n                    // just skip\n                }\n            }\n        }\n        assert(score == score);\n        _outStream << \"\\nscore: \" << score << std::endl;\n        _outStream << \"cnt: \" << cnt << std::endl;\n        _outStream << \"gradient: \" << gradient.transpose() << std::endl;\n        // _debugOut << \"hessian:\\n\" << hessian << std::endl;\n        Eigen::EigenSolver<Eigen::Matrix3d> fixed;\n        fixed.compute(hessian, false);\n        _outStream << \"h eig: \" << fixed.eigenvalues().transpose() << std::endl;\n        double min_eigenvalue = 0;\n        for (int kk = 0; kk < 3; kk++)\n            if (fixed.eigenvalues()[kk].real() < min_eigenvalue)\n                min_eigenvalue = fixed.eigenvalues()[kk].real();\n        if (min_eigenvalue < 0) {\n            double lambda = 1.1 * min_eigenvalue - 1;\n            hessian += Eigen::Vector3d(-lambda, -lambda, -lambda).asDiagonal();\n            fixed.compute(hessian, false);\n            _outStream << \"h eig fixed: \" << fixed.eigenvalues().transpose()\n                       << std::endl;\n        }\n\n        _outStream << \"hessian inv:\\n\" << hessian.inverse() << std::endl;\n        auto dp = -hessian.inverse() * gradient;\n        _outStream << \"dp: \" << dp.transpose() << std::endl;\n\n        currentGuess += NDT2DSLAM::Transform2D(dp(0), dp(1), dp(2));\n        _outStream << currentGuess << std::endl;\n\n        // terminate if criteria is met\n        if ((std::max(fabs(dp(0)), fabs(dp(1))) < _epsilonTranslation) ||\n            (fabs(dp(2)) < _epsilonRotation)) {\n            break;\n        }\n    }\n    _outStream << \"iterCnt: \" << iterationCount << std::endl;\n    _outStream << \"final \" << currentGuess << std::endl;\n\n    return currentGuess;\n}\n\nint NDTScanMatcher::cellXYIdx2Idx(std::tuple<int, int> xIdx_yIdx) {\n    int xIdx = std::get<0>(xIdx_yIdx);\n    int yIdx = std::get<1>(xIdx_yIdx);\n    int idx = yIdx * _nCellX + xIdx;\n    if (idx < 0 || static_cast<int>(_cells.size()) <= idx)\n        throw std::out_of_range(\"no corresponding cell exists\");\n    return idx;\n}\n\nstd::tuple<int, int> NDTScanMatcher::xy2cellXYIdx(double x, double y) {\n    int xIdx = static_cast<int>((x - _minX) / _halfGridSize) + 1;\n    int yIdx = static_cast<int>((y - _minY) / _halfGridSize) + 1;\n\n    return {xIdx, yIdx};\n}\n\ndouble NDTScanMatcher::scoreDifference(const Eigen::Vector2d& residual,\n                                       const Eigen::Matrix2d& invCovariance) {\n    double inExp = -0.5 * residual.transpose() * invCovariance * residual;\n    return std::exp(inExp);\n}\n\n}  // namespace NDT2DSLAM\n", "meta": {"hexsha": "052d4617e3061b74a6472bdc82e85bed14fbb077", "size": 14269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/scan_matcher_2d.cpp", "max_stars_repo_name": "HarukiUchito/ndt_2d_slam", "max_stars_repo_head_hexsha": "7063044fc11a3ba1e0d708741615334afcbb102a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/scan_matcher_2d.cpp", "max_issues_repo_name": "HarukiUchito/ndt_2d_slam", "max_issues_repo_head_hexsha": "7063044fc11a3ba1e0d708741615334afcbb102a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scan_matcher_2d.cpp", "max_forks_repo_name": "HarukiUchito/ndt_2d_slam", "max_forks_repo_head_hexsha": "7063044fc11a3ba1e0d708741615334afcbb102a", "max_forks_repo_licenses": ["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.7744565217, "max_line_length": 80, "alphanum_fraction": 0.5617772794, "num_tokens": 3879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5236695396570524}}
{"text": "#include <iostream>\n#include <fstream>\n\n#include <boost/program_options.hpp>\n\n#include <mav_trajectory_generation/polynomial_optimization_linear.h>\n#include <mav_trajectory_generation/polynomial_optimization_nonlinear.h>\n\n\nusing namespace Eigen;\n\n// see https://stackoverflow.com/questions/34247057/how-to-read-csv-file-and-assign-to-eigen-matrix\ntemplate<typename M>\nM load_csv (const std::string & path) {\n  std::ifstream indata;\n  indata.open(path);\n  std::string line;\n  std::vector<double> values;\n  uint rows = 0;\n  while (std::getline(indata, line)) {\n    std::stringstream lineStream(line);\n    std::string cell;\n    while (std::getline(lineStream, cell, ',')) {\n      values.push_back(std::stod(cell));\n    }\n    ++rows;\n  }\n  return Map<const Matrix<typename M::Scalar, M::RowsAtCompileTime, M::ColsAtCompileTime, RowMajor>>(values.data(), rows, values.size()/rows);\n}\n\nint main(int argc, char **argv)\n{\n  std::string inputFile;\n  std::string outputFile;\n  double v_max;\n  double a_max;\n\n  namespace po = boost::program_options;\n\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help\", \"produce help message\")\n    (\"input,i\", po::value<std::string>(&inputFile)->required(), \"path to list of waypoints\")\n    (\"output,o\", po::value<std::string>(&outputFile)->required(), \"path to output files\")\n    (\"v_max\", po::value<double>(&v_max)->default_value(1.0), \"maximum velocity [m/s]\")\n    (\"a_max\", po::value<double>(&a_max)->default_value(1.0), \"maximum velocity [m/s^2]\")\n  ;\n\n  try\n  {\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n      std::cout << desc << \"\\n\";\n      return 0;\n    }\n  }\n  catch(po::error& e)\n  {\n    std::cerr << e.what() << std::endl << std::endl;\n    std::cerr << desc << std::endl;\n    return 1;\n  }\n\n\n  mav_trajectory_generation::Vertex::Vector vertices;\n  const int dimension = 3;\n  const int derivative_to_optimize = mav_trajectory_generation::derivative_order::JERK;\n\n  // create vertices with their constraints\n  auto input = load_csv<Matrix<double, Dynamic, 3> >(inputFile);\n\n  if (input.rows() < 2) {\n    std::cerr << \"Not enough datapoints given!\" << std::endl;\n    return 1;\n  }\n\n  if (input.rows() == 2) {\n    mav_trajectory_generation::Vertex v1(dimension);\n    v1.makeStartOrEnd(input.row(0), derivative_to_optimize);\n    vertices.push_back(v1);\n\n    mav_trajectory_generation::Vertex v2(dimension);\n    auto middle = (input.row(1) - input.row(0)) * 0.5 + input.row(0);\n    v2.addConstraint(mav_trajectory_generation::derivative_order::POSITION, middle);\n    vertices.push_back(v2);\n\n    mav_trajectory_generation::Vertex v3(dimension);\n    v3.makeStartOrEnd(input.row(1), derivative_to_optimize);\n    vertices.push_back(v3);\n  } else {\n    // at least 3 points given\n    for (int row = 0; row < input.rows(); ++row) {\n      // std::cout << input.row(row) << std::endl;\n      mav_trajectory_generation::Vertex vertex(dimension);\n      if (row == 0 || row == input.rows() - 1) {\n        vertex.makeStartOrEnd(input.row(row), derivative_to_optimize);\n      } else {\n        vertex.addConstraint(mav_trajectory_generation::derivative_order::POSITION, input.row(row));\n      }\n      vertices.push_back(vertex);\n    }\n  }\n\n  // compute segment times\n  std::vector<double> segment_times;\n  const double magic_fabian_constant = 6.5; // A tuning parameter.\n  segment_times = estimateSegmentTimes(vertices, v_max, a_max, magic_fabian_constant);\n\n  // solve\n  const int N = 8;\n  mav_trajectory_generation::Segment::Vector segments;\n\n#if SOLVE_LINEAR\n  mav_trajectory_generation::PolynomialOptimization<N> opt(dimension);\n  opt.setupFromVertices(vertices, segment_times, derivative_to_optimize);\n  opt.solveLinear();\n\n  // Obtain the polynomial segments.\n  opt.getSegments(&segments);\n#else\n  mav_trajectory_generation::NonlinearOptimizationParameters parameters;\n  parameters.max_iterations = 1000;\n  parameters.f_rel = 0.05;\n  parameters.x_rel = 0.1;\n  parameters.time_penalty = 500.0;\n  parameters.initial_stepsize_rel = 0.1;\n  parameters.inequality_constraint_tolerance = 0.1;\n\n  mav_trajectory_generation::PolynomialOptimizationNonLinear<N> opt(dimension, parameters, false);\n  opt.setupFromVertices(vertices, segment_times, derivative_to_optimize);\n  opt.addMaximumMagnitudeConstraint(mav_trajectory_generation::derivative_order::VELOCITY, v_max);\n  opt.addMaximumMagnitudeConstraint(mav_trajectory_generation::derivative_order::ACCELERATION, a_max);\n  opt.optimize();\n\n  // Obtain the polynomial segments.\n  opt.getPolynomialOptimizationRef().getSegments(&segments);\n#endif\n\n  std::ofstream output(outputFile);\n\n  output << \"Duration,x^0,x^1,x^2,x^3,x^4,x^5,x^6,x^7,y^0,y^1,y^2,y^3,y^4,y^5,y^6,y^7,z^0,z^1,z^2,z^3,z^4,z^5,z^6,z^7,yaw^0,yaw^1,yaw^2,yaw^3,yaw^4,yaw^5,yaw^6,yaw^7\" << std::endl;\n  Eigen::IOFormat csv_fmt(Eigen::StreamPrecision, Eigen::DontAlignCols, \",\", \",\", \"\", \"\", \"\", \"\");\n\n  for (const auto& segment : segments) {\n    output << segment.getTime() << \",\";\n    for (const auto& polynomial : segment.getPolynomialsRef()) {\n      Eigen::VectorXd coefficients = polynomial.getCoefficients();\n      output << coefficients.format(csv_fmt) << \",\";\n    }\n    output << \"0,0,0,0,0,0,0,0\" << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "fa771e001b372b72d0328a4f7ed023aeff2f856a", "size": 5289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/genTrajectory.cpp", "max_stars_repo_name": "jonasdn/uav_trajectories", "max_stars_repo_head_hexsha": "4b7b126cdec40076c404574bc04536cbd525594f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/genTrajectory.cpp", "max_issues_repo_name": "jonasdn/uav_trajectories", "max_issues_repo_head_hexsha": "4b7b126cdec40076c404574bc04536cbd525594f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/genTrajectory.cpp", "max_forks_repo_name": "jonasdn/uav_trajectories", "max_forks_repo_head_hexsha": "4b7b126cdec40076c404574bc04536cbd525594f", "max_forks_repo_licenses": ["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.4746835443, "max_line_length": 180, "alphanum_fraction": 0.6918131972, "num_tokens": 1419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5236695343932004}}
{"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 KalmanFilter.cpp\n *\n * @brief Simple linear Kalman filter.\n * Implemented using factor graphs, i.e., does Cholesky-based SRIF, really.\n *\n * @date Sep 3, 2011\n * @author Stephen Williams\n * @author Frank Dellaert\n */\n\n#include <gtsam/linear/KalmanFilter.h>\n#include <gtsam/linear/GaussianBayesNet.h>\n#include <gtsam/linear/JacobianFactor.h>\n#include <gtsam/linear/HessianFactor.h>\n#include <gtsam/base/Testable.h>\n\n#include <boost/make_shared.hpp>\n#include <boost/assign/list_of.hpp>\n\nusing namespace boost::assign;\nusing namespace std;\n\nnamespace gtsam {\n\n/* ************************************************************************* */\n// Auxiliary function to solve factor graph and return pointer to root conditional\nKalmanFilter::State //\nKalmanFilter::solve(const GaussianFactorGraph& factorGraph) const {\n\n  // Eliminate the graph using the provided Eliminate function\n  Ordering ordering(factorGraph.keys());\n  GaussianBayesNet::shared_ptr bayesNet = //\n      factorGraph.eliminateSequential(ordering, function_);\n\n  // As this is a filter, all we need is the posterior P(x_t).\n  // This is the last GaussianConditional in the resulting BayesNet\n  GaussianConditional::shared_ptr posterior = *(--bayesNet->end());\n  return boost::make_shared<GaussianDensity>(*posterior);\n}\n\n/* ************************************************************************* */\n// Auxiliary function to create a small graph for predict or update and solve\nKalmanFilter::State //\nKalmanFilter::fuse(const State& p, GaussianFactor::shared_ptr newFactor) const {\n\n  // Create a factor graph\n  GaussianFactorGraph factorGraph;\n  factorGraph += p, newFactor;\n\n  // Eliminate graph in order x0, x1, to get Bayes net P(x0|x1)P(x1)\n  return solve(factorGraph);\n}\n\n/* ************************************************************************* */\nKalmanFilter::State KalmanFilter::init(const Vector& x0,\n    const SharedDiagonal& P0) const {\n\n  // Create a factor graph f(x0), eliminate it into P(x0)\n  GaussianFactorGraph factorGraph;\n  factorGraph += JacobianFactor(0, I_, x0, P0); // |x-x0|^2_diagSigma\n  return solve(factorGraph);\n}\n\n/* ************************************************************************* */\nKalmanFilter::State KalmanFilter::init(const Vector& x, const Matrix& P0) const {\n\n  // Create a factor graph f(x0), eliminate it into P(x0)\n  GaussianFactorGraph factorGraph;\n  factorGraph += HessianFactor(0, x, P0); // 0.5*(x-x0)'*inv(Sigma)*(x-x0)\n  return solve(factorGraph);\n}\n\n/* ************************************************************************* */\nvoid KalmanFilter::print(const string& s) const {\n  cout << \"KalmanFilter \" << s << \", dim = \" << n_ << endl;\n}\n\n/* ************************************************************************* */\nKalmanFilter::State KalmanFilter::predict(const State& p, const Matrix& F,\n    const Matrix& B, const Vector& u, const SharedDiagonal& model) const {\n\n  // The factor related to the motion model is defined as\n  // f2(x_{t},x_{t+1}) = (F*x_{t} + B*u - x_{t+1}) * Q^-1 * (F*x_{t} + B*u - x_{t+1})^T\n  Key k = step(p);\n  return fuse(p,\n      boost::make_shared<JacobianFactor>(k, -F, k + 1, I_, B * u, model));\n}\n\n/* ************************************************************************* */\nKalmanFilter::State KalmanFilter::predictQ(const State& p, const Matrix& F,\n    const Matrix& B, const Vector& u, const Matrix& Q) const {\n\n#ifndef NDEBUG\n  DenseIndex n = F.cols();\n  assert(F.rows() == n);\n  assert(B.rows() == n);\n  assert(B.cols() == u.size());\n  assert(Q.rows() == n);\n  assert(Q.cols() == n);\n#endif\n\n  // The factor related to the motion model is defined as\n  // f2(x_{t},x_{t+1}) = (F*x_{t} + B*u - x_{t+1}) * Q^-1 * (F*x_{t} + B*u - x_{t+1})^T\n  // See documentation in HessianFactor, we have A1 = -F,  A2 = I_, b = B*u:\n  // TODO: starts to seem more elaborate than straight-up KF equations?\n  Matrix M = Q.inverse(), Ft = trans(F);\n  Matrix G12 = -Ft * M, G11 = -G12 * F, G22 = M;\n  Vector b = B * u, g2 = M * b, g1 = -Ft * g2;\n  double f = dot(b, g2);\n  Key k = step(p);\n  return fuse(p,\n      boost::make_shared<HessianFactor>(k, k + 1, G11, G12, g1, G22, g2, f));\n}\n\n/* ************************************************************************* */\nKalmanFilter::State KalmanFilter::predict2(const State& p, const Matrix& A0,\n    const Matrix& A1, const Vector& b, const SharedDiagonal& model) const {\n  // Nhe factor related to the motion model is defined as\n  // f2(x_{t},x_{t+1}) = |A0*x_{t} + A1*x_{t+1} - b|^2\n  Key k = step(p);\n  return fuse(p, boost::make_shared<JacobianFactor>(k, A0, k + 1, A1, b, model));\n}\n\n/* ************************************************************************* */\nKalmanFilter::State KalmanFilter::update(const State& p, const Matrix& H,\n    const Vector& z, const SharedDiagonal& model) const {\n  // The factor related to the measurements would be defined as\n  // f2 = (h(x_{t}) - z_{t}) * R^-1 * (h(x_{t}) - z_{t})^T\n  //    = (x_{t} - z_{t}) * R^-1 * (x_{t} - z_{t})^T\n  Key k = step(p);\n  return fuse(p, boost::make_shared<JacobianFactor>(k, H, z, model));\n}\n\n/* ************************************************************************* */\nKalmanFilter::State KalmanFilter::updateQ(const State& p, const Matrix& H,\n    const Vector& z, const Matrix& Q) const {\n  Key k = step(p);\n  Matrix M = Q.inverse(), Ht = trans(H);\n  Matrix G = Ht * M * H;\n  Vector g = Ht * M * z;\n  double f = dot(z, M * z);\n  return fuse(p, boost::make_shared<HessianFactor>(k, G, g, f));\n}\n\n/* ************************************************************************* */\n\n} // \\namespace gtsam\n\n", "meta": {"hexsha": "c0d294adf7f987c4beb6466c643f3d0523aa9f08", "size": 5984, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/KalmanFilter.cpp", "max_stars_repo_name": "karamach/gtsam", "max_stars_repo_head_hexsha": "35f9b710163a1d14d8dc4fcf50b8dce6e0bf7e5b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 105.0, "max_stars_repo_stars_event_min_datetime": "2017-12-02T14:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T18:20:25.000Z", "max_issues_repo_path": "trunk/gtsam/linear/KalmanFilter.cpp", "max_issues_repo_name": "shaolinbit/PPP-BayesTree", "max_issues_repo_head_hexsha": "6f469775277a1a33447bf4c19603c796c2c63c75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-04T15:15:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-08T08:51:02.000Z", "max_forks_repo_path": "trunk/gtsam/linear/KalmanFilter.cpp", "max_forks_repo_name": "shaolinbit/PPP-BayesTree", "max_forks_repo_head_hexsha": "6f469775277a1a33447bf4c19603c796c2c63c75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2018-01-10T03:21:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T06:18:35.000Z", "avg_line_length": 37.1677018634, "max_line_length": 87, "alphanum_fraction": 0.5529745989, "num_tokens": 1583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5236695285522024}}
{"text": "#ifndef ISOMON_TEST_MONEY_CALC_HPP\n#define ISOMON_TEST_MONEY_CALC_HPP\n\n#include \"money_calc.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::unit_test;\nusing namespace isomon;\n\n\nBOOST_AUTO_TEST_CASE( roundhalfout_test )\n{\n  money m(2, 0, \"USD\");\n\n  m = round(m * 1.5);\n  BOOST_CHECK_EQUAL(m.total_minors(), 300);\n\n  money m2 = round(m * 1.001);\n  BOOST_CHECK_EQUAL(m2.total_minors(), 300);\n\n  m2 = round(m * 1.002);\n  BOOST_CHECK_EQUAL(m2.total_minors(), 301);\n}\n\nBOOST_AUTO_TEST_CASE( multiply_test )\n{\n  money m(3, 0, \"USD\");\n  money_calc<double> mc(1.5, \"USD\");\n\n  BOOST_CHECK_EQUAL( round(m * 2.0), round(mc * 4) );\n}\n\nBOOST_AUTO_TEST_CASE( addition_test )\n{\n  money_calc<double> one_third_dollar( 1.0/3.0, \"USD\" );\n  money buck(1, 0, \"USD\");\n\n  BOOST_CHECK_EQUAL( buck, round(3 * one_third_dollar) );\n  money_calc<double> sum = one_third_dollar + one_third_dollar;\n  sum += one_third_dollar;\n  BOOST_CHECK_EQUAL( buck, round(sum) );\n}\n\nBOOST_AUTO_TEST_CASE( negation_test )\n{\n  money thirty_three_cents(0, 33, \"USD\");\n  money neg_thirty_three_cents(0, -33, \"USD\");\n  money buck(1, 0, \"USD\");\n  money_calc<double> one_third_dollar( 1.0/3.0, \"USD\" );\n  money_calc<double> neg_one_third_dollar( -1.0/3.0, \"USD\" );\n\n  BOOST_CHECK_EQUAL( -thirty_three_cents, neg_thirty_three_cents );\n  BOOST_CHECK_EQUAL( buck - thirty_three_cents, money(0, 67, \"USD\") );\n  BOOST_CHECK_EQUAL( -buck + thirty_three_cents, -money(0, 67, \"USD\") );\n  BOOST_CHECK_EQUAL( round(-one_third_dollar), round(neg_one_third_dollar) );\n}\n\nBOOST_AUTO_TEST_CASE( mutlicurrency_nonaddition_test )\n{\n  money bad = money(1, 0, \"USD\") + money(1, 0, \"EUR\");\n  BOOST_CHECK( bad.unit().is_no_currency() ); \n}\n\n\n#endif\n\n", "meta": {"hexsha": "8a8166dfef44e3703158a36135565cc32cd8e1d6", "size": 1742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test-money_calc.cpp", "max_stars_repo_name": "castedo/isomon", "max_stars_repo_head_hexsha": "2db5f7b701161bfd65b064d540c0ec0c96a80892", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-10-05T04:24:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-27T09:44:50.000Z", "max_issues_repo_path": "test/test-money_calc.cpp", "max_issues_repo_name": "castedo/isomon", "max_issues_repo_head_hexsha": "2db5f7b701161bfd65b064d540c0ec0c96a80892", "max_issues_repo_licenses": ["MIT"], "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-money_calc.cpp", "max_forks_repo_name": "castedo/isomon", "max_forks_repo_head_hexsha": "2db5f7b701161bfd65b064d540c0ec0c96a80892", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-08T09:16:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-08T09:16:23.000Z", "avg_line_length": 24.8857142857, "max_line_length": 77, "alphanum_fraction": 0.7101033295, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5236477462851717}}
{"text": "//Written by John G Baker NASA-GSFC (2017)\n//This is to test the shaped gaussian proposal distribution.\n\n#include \"proposal_distribution.hh\"\n#include \"chain.hh\"\n#include <Eigen/Eigen>\n\nshared_ptr<Random> globalRNG;//used for some debugging... \n\nint main(int argc, char*argv[]){\n\n  int ndim=5;\n  int ndraws=2100000;\n  double temp=10.;\n\n  //Randomly construct a covariance matrix\n  Eigen::MatrixXd cov(ndim,ndim);\n  cov=Eigen::MatrixXd::Random(ndim,ndim);\n  //cov.Random();        //draw a random matrix\n  cov=cov.transpose()*cov; //and turn it into something symmetric and positive semidefinite.\n  cov*=temp;\n    \n  //Next we define the proposal\n  gaussian_prop p(cov);\n\n  //We need a chain, to allow draws, just a dummy, but some setup is needed.\n  ProbabilityDist::setSeed(.224);\n  stateSpace ss(ndim);\n  state s(&ss,vector<double>(ndim,0));\n  gaussian_dist_product prior(&ss);\n  MH_chain c(&prior,&prior);\n  c.resetTemp(1/temp);\n\n  //perform draws compute stats\n  Eigen::MatrixXd covsum=Eigen::MatrixXd::Zero(ndim,ndim);\n  Eigen::VectorXd sum=Eigen::VectorXd::Zero(ndim);\n  Eigen::VectorXd min=Eigen::VectorXd::Constant(ndim,+1e100);\n  Eigen::VectorXd max=Eigen::VectorXd::Constant(ndim,-1e100);\n  valarray<double> statedata;\n  valarray<double> statedata0;\n  s.get_params_array(statedata0);\n  Eigen::Map<Eigen::VectorXd> vec0(&statedata0[0],statedata0.size());\n  state draw;\n  \n  for(int n=1;n<=ndraws;n++){\n    draw=p.draw(s,&c);\n    draw.get_params_array(statedata);\n    Eigen::Map<Eigen::VectorXd> vec(&statedata[0],statedata.size());\n    draw.get_params_array(statedata);\n    //Eigen::Map<Eigen::VectorXd> vec0(&statedata0[0],statedata0.size());\n    //cout<<\"vec0:(\"<<vec0.rows()<<\",\"<<vec0.cols()<<\") vec:(\"<<vec.rows()<<\",\"<<vec.cols()<<\")\"<<endl;\n    Eigen::VectorXd dvec=vec-vec0;\n    Eigen::MatrixXd covdelta(ndim,ndim);\n    //cout<<\"dvec=\\n\"<<dvec<<endl;\n    sum+=dvec;\n    for(int i=0;i<ndim;i++)for(int j=0;j<ndim;j++)covdelta(i,j)=dvec(i)*dvec(j);\n    covsum+=covdelta;\n    for(int i=0;i<ndim;i++){\n      if(min(i)>vec(i))min(i)=vec(i);\n      if(max(i)<vec(i))max(i)=vec(i);\n    }\n    if((n & (n - 1))==0){\n      Eigen::MatrixXd coverr(ndim,ndim);\n      coverr=covsum/n-cov;\n      cout<<\"cov=\\n\"<<coverr+cov<<endl;\n      cout<<\"coverr=\\n\"<<coverr<<endl;\n      double coverrnorm=(coverr*coverr).trace();\n      double coverrdiagnorm=0;\n      for(int i=0;i<ndim;i++)coverrdiagnorm+=coverr(i,i)*coverr(i,i);\n      cout<<\"min:\"<<min.transpose()<<endl;\n      cout<<\"max:\"<<max.transpose()<<endl;\n      cout<<n<<\": errnorm=\"<<coverrnorm<<\"\\terrdiagnorm=\"<<coverrdiagnorm<<endl;\n      \n    }\n  }\n}\n\n  \n  \n", "meta": {"hexsha": "68d3899d980158b61bc740b88d5398c132c94993", "size": 2612, "ext": "cc", "lang": "C++", "max_stars_repo_path": "testGaussian.cc", "max_stars_repo_name": "renlliang3/ptmcmc", "max_stars_repo_head_hexsha": "440e2f28a34ac285c310dd17ead271ff1bcf1d0f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T13:00:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T13:03:25.000Z", "max_issues_repo_path": "testGaussian.cc", "max_issues_repo_name": "JohnGBaker/ptmcmc", "max_issues_repo_head_hexsha": "a8878d6a79019fa5e2144a0b5fb88c04d4659e7e", "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": "testGaussian.cc", "max_forks_repo_name": "JohnGBaker/ptmcmc", "max_forks_repo_head_hexsha": "a8878d6a79019fa5e2144a0b5fb88c04d4659e7e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-06-07T20:47:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T09:55:04.000Z", "avg_line_length": 32.65, "max_line_length": 103, "alphanum_fraction": 0.6477794793, "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.523647741501181}}
{"text": "#include <memory>\n#define CATCH_CONFIG_MAIN\n#include <catch.hpp>\n#include <tbb/tbb.h>\n\n#include <Eigen/Dense>\n#include <Eigen/src/Eigenvalues/ComplexEigenSolver.h>\n#include <Eigen/src/QR/HouseholderQR.h>\n#include <random>\n\n#include \"EDP/ConstructSparseMat.hpp\"\n#include \"EDP/LocalHamiltonian.hpp\"\n\n#include \"common.hpp\"\n\n#include \"yavque/Circuit.hpp\"\n#include \"yavque/operators.hpp\"\n\nusing namespace Eigen;\n\ntbb::global_control gc(tbb::global_control::max_allowed_parallelism, 2);\n\nTEST_CASE(\"test single qubit operator\", \"[single-qubit-operator]\")\n{\n\tusing namespace yavque;\n\tconstexpr uint32_t N = 3;\n\tconstexpr uint32_t dim = 1u << N;\n\tconstexpr cx_double I(0, 1.0);\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\tstd::uniform_int_distribution<uint32_t> index_dist(0, N - 1);\n\n\t// test using sparse matrix construction\n\tfor(uint32_t instance_idx = 0; instance_idx < 100; ++instance_idx)\n\t{\n\t\tauto op = random_unitary(4, re);\n\t\tauto i = index_dist(re);\n\t\tauto j = index_dist(re);\n\t\twhile(i == j)\n\t\t{\n\t\t\tj = index_dist(re);\n\t\t}\n\t\tauto m1 = TwoQubitOperator(op, N, i, j);\n\n\t\tauto st = random_vector(dim, re);\n\n\t\tedp::LocalHamiltonian<cx_double> lh(N, 2);\n\t\tlh.addTwoSiteTerm({i, j}, op.sparseView());\n\t\tauto m = edp::constructSparseMat<cx_double>(dim, lh);\n\n\t\tREQUIRE((m1.apply_right(st) - m * st).norm() < 1e-6);\n\n\t\tm1.dagger_in_place();\n\t\tREQUIRE((m1.apply_right(st) - m.adjoint() * st).norm() < 1e-6);\n\t}\n}\n", "meta": {"hexsha": "423d2defddffe929eab554fa43111f944b10d2cd", "size": 1426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/TestTwoQubitOperator.cpp", "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": "Tests/TestTwoQubitOperator.cpp", "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": "Tests/TestTwoQubitOperator.cpp", "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": 25.0175438596, "max_line_length": 72, "alphanum_fraction": 0.7047685835, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.523647741188855}}
{"text": "#include \"lwtnn/LightweightNeuralNetwork.hh\"\n\n#include <Eigen/Dense>\n\n#include <iostream>\n\nint main(int argc, char* argv[]) {\n\n  std::vector<double> weights{\n    0, 0, 0, 1,\n    0, 0, 1, 0,\n    0, 1, 0, 0,\n    1, 0, 0, 0};\n  lwt::LayerConfig layer1{weights};\n  std::vector<lwt::Input> input_conf{\n    {\"1\", 0, 1}, {\"2\", 0, 1}, {\"3\", 0, 1}, {\"4\", 0, 1}};\n  std::vector<std::string> outputs{\"1\", \"2\", \"3\", \"4\"};\n\n  lwt::LightweightNeuralNetwork tagger(input_conf, {layer1}, outputs);\n  lwt::ValueMap input{ {\"1\", 1}, {\"2\", 2}, {\"3\", 3}, {\"4\", 4} };\n  auto out = tagger.compute(input);\n  for (const auto& op: out) {\n    std::cout << op.first << \" \" << op.second << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "ebb650d6dffa8525318d0f2d5485a40bc91325ef", "size": 691, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/lwtnn-test-hlwrapper.cxx", "max_stars_repo_name": "mickypaganini/lwtnn", "max_stars_repo_head_hexsha": "7032e70aeb7d21e2074830f87d37696b407cf519", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T00:31:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T00:31:00.000Z", "max_issues_repo_path": "src/lwtnn-test-hlwrapper.cxx", "max_issues_repo_name": "mickypaganini/lwtnn", "max_issues_repo_head_hexsha": "7032e70aeb7d21e2074830f87d37696b407cf519", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-05-09T07:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-09T08:25:10.000Z", "max_forks_repo_path": "src/lwtnn-test-hlwrapper.cxx", "max_forks_repo_name": "mickypaganini/lwtnn", "max_forks_repo_head_hexsha": "7032e70aeb7d21e2074830f87d37696b407cf519", "max_forks_repo_licenses": ["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.5925925926, "max_line_length": 70, "alphanum_fraction": 0.5542691751, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5236477300592421}}
{"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_ARCH_X86_SSE2_SIMD_FUNCTION_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_RSQRT_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/raw.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/if_nan_else.hpp>\n#include <boost/simd/function/if_zero_else.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/refine_rsqrt.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/ratio.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd =  boost::dispatch;\n  namespace bs =  boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( rsqrt_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::raw_tag\n                          , bs::pack_<bd::double_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (raw_tag const&\n                                    , const A0 & a0) const BOOST_NOEXCEPT\n    {\n      return _mm_cvtps_pd(_mm_rsqrt_ps(_mm_cvtpd_ps(a0))); //The maximum error for this approximation is 1.5e-12\n    }\n  };\n\n   BOOST_DISPATCH_OVERLOAD ( rsqrt_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::double_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const A0 & a00) const BOOST_NOEXCEPT\n    {\n      // To obtain accuracy we need 3 Newton steps or one Halley step followed by one Newton from the raw estimate\n      // the second method is a bit faster by half a cycle\n      A0 a0 =  raw_(rsqrt)(a00);\n      A0 y = sqr(a0)*a00;\n      a0 = a0*Ratio<A0, 1, 8>()*fnms(y, fnms(A0(3), y, A0(10)), A0(15)); //this is Halley cubically convergent iteration\n      a0 = refine_rsqrt(a00, a0);\n#ifndef BOOST_SIMD_NO_INFINITIES\n      a0 = if_zero_else(a00 == Inf<A0>(),a0);\n#endif\n      return if_else(is_eqz(a00), Inf<A0>(), a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( rsqrt_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pedantic_tag\n                          , bs::pack_<bd::double_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (pedantic_tag const&\n                                    ,const A0 & a00) const BOOST_NOEXCEPT\n    {\n      A0 a01 =  a00;\n      auto is_den = bs::abs(a00) < Smallestposval<A0>();\n      #ifndef BOOST_SIMD_NO_DENORMALS\n      a01 *= if_else(is_den, Denormalfactor<A0>(), One<A0>());\n      #endif\n      A0 a0 =  raw_(rsqrt)(a01);\n      A0 y = sqr(a0)*a01;\n      a0 = a0*Ratio<A0, 1, 8>()*fnms(y, fnms(A0(3), y, A0(10)), A0(15)); //this is Halley cubically convergent iteration\n      a0 = refine_rsqrt(a00, a0);\n      #ifndef BOOST_SIMD_NO_DENORMALS\n      a0 *= if_else(is_den, Denormalsqrtfactor<A0>(), One<A0>());\n      #endif\n\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      a0 = if_zero_else(a00 == Inf<A0>(),a0);\n      #endif\n      return if_else(is_eqz(a00), Inf<A0>(), a0);\n    }\n  };\n} } }\n\n#endif\n\n", "meta": {"hexsha": "3c400ec7a011292fb9835d0dc90b548ba30b4d92", "size": 3551, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/x86/sse2/simd/function/rsqrt.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/arch/x86/sse2/simd/function/rsqrt.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/arch/x86/sse2/simd/function/rsqrt.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": 36.2346938776, "max_line_length": 120, "alphanum_fraction": 0.55364686, "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5236477297469159}}
{"text": "#pragma once\n\n#include <functional>\n#include <Eigen/Dense>\n\n#include \"vector/vector.hpp\"\n#include \"polyline/interpolation.hpp\"\n#include \"polyline/polyline_2d.hpp\"\n#include \"spline/basis.hpp\"\n\n\nnamespace euklid::spline {\n        \n\ntemplate<typename Base, typename T>\nclass SplineCurve {\n    public:\n        SplineCurve(PolyLine2D);\n\n        Vector2D get(double);\n        PolyLine2D get_sequence(size_t);\n\n        PolyLine2D controlpoints;\n        T copy() const;\n\n        static T fit(const PolyLine2D&, size_t);\n\n        void set_numpoints(size_t);\n        int get_numpoints();\n    \n    private:\n        Base& get_base();\n        Base base;\n};\n\nclass BezierCurve : public SplineCurve<BezierBase, BezierCurve> {\n        using SplineCurve<BezierBase, BezierCurve>::SplineCurve;\n};\n\ntemplate<size_t degree>\nclass BSplineCurve : public SplineCurve<BSplineBase<degree>, BSplineCurve<degree>> {\n    using SplineCurve<BSplineBase<degree>, BSplineCurve<degree>>::SplineCurve;\n    \n    public:\n        Interpolation get_curvature(size_t) const;\n        typename std::conditional<(degree>1), BSplineCurve<degree-1>, BSplineCurve<1>>::type get_derivate() const;\n};\n\n\ntemplate<typename SplineClass, typename T>\nclass SymmetricSpline {\n    public:\n        SymmetricSpline(PolyLine2D);\n\n        Vector2D get(double);\n        PolyLine2D get_sequence(size_t);\n\n        PolyLine2D controlpoints;\n        T copy() const;\n\n        static T fit(const PolyLine2D&, size_t);\n        \n        void set_numpoints(size_t);\n        int get_numpoints();\n    \n    protected:\n        void apply();\n        SplineClass spline_curve;\n};\n\ntemplate<size_t degree>\nclass SymmetricBSplineCurve : public SymmetricSpline<BSplineCurve<degree>, SymmetricBSplineCurve<degree>> {\n    using SymmetricSpline<BSplineCurve<degree>, SymmetricBSplineCurve<degree>>::SymmetricSpline;\n    public:\n        Interpolation get_curvature(size_t);\n};\n\nclass SymmetricBezierCurve : public SymmetricSpline<BezierCurve, SymmetricBezierCurve> {\n    using SymmetricSpline<BezierCurve, SymmetricBezierCurve>::SymmetricSpline;\n};\n\n} // namespace euklid::spline", "meta": {"hexsha": "4bb52645a1d06eae8b441b90f1af0f780f2d9780", "size": 2098, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spline/spline.hpp", "max_stars_repo_name": "airgproducts/euklid", "max_stars_repo_head_hexsha": "a2c53fbbc844f37adfb7945efaa88a4f1314c7e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spline/spline.hpp", "max_issues_repo_name": "airgproducts/euklid", "max_issues_repo_head_hexsha": "a2c53fbbc844f37adfb7945efaa88a4f1314c7e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T14:08:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T15:54:43.000Z", "max_forks_repo_path": "src/spline/spline.hpp", "max_forks_repo_name": "airgproducts/euklid", "max_forks_repo_head_hexsha": "a2c53fbbc844f37adfb7945efaa88a4f1314c7e3", "max_forks_repo_licenses": ["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.5853658537, "max_line_length": 114, "alphanum_fraction": 0.6973307912, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5236477243382726}}
{"text": "#ifndef PYTHONIC_INCLUDE_NUMPY_LOG1P_HPP\n#define PYTHONIC_INCLUDE_NUMPY_LOG1P_HPP\n\n#include \"pythonic/include/utils/functor.hpp\"\n#include \"pythonic/include/types/ndarray.hpp\"\n#include \"pythonic/include/utils/numpy_traits.hpp\"\n#include <boost/simd/function/log1p.hpp>\n\nPYTHONIC_NS_BEGIN\n\nnamespace numpy\n{\n\n  namespace wrapper\n  {\n    template <class T>\n    std::complex<T> log1p(std::complex<T> const &val)\n    {\n      return std::log(val + 1);\n    }\n    template <class T>\n    auto log1p(T const &val) -> decltype(boost::simd::log1p(val))\n    {\n      return boost::simd::log1p(val);\n    }\n  }\n\n#define NUMPY_NARY_FUNC_NAME log1p\n#define NUMPY_NARY_FUNC_SYM wrapper::log1p\n#include \"pythonic/include/types/numpy_nary_expr.hpp\"\n}\nPYTHONIC_NS_END\n\n#endif\n", "meta": {"hexsha": "9d700ce04f9c8e3a51cb179246bd58ccb163f063", "size": 753, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pythran/pythonic/include/numpy/log1p.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-24T00:33:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-24T00:33:03.000Z", "max_issues_repo_path": "pythran/pythonic/include/numpy/log1p.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": "pythran/pythonic/include/numpy/log1p.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "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.5142857143, "max_line_length": 65, "alphanum_fraction": 0.7290836653, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.523647718617303}}
{"text": "//   Copyright (c) 2018 Shahrzad Shirzad\n//\n//   Distributed under the Boost Software License, Version 1.0.0. (See accompanying\n//   file LICENSE_1_0.0.txt or copy at http://www.boost.org/LICENSE_1_0.0.txt)\n\n#include <phylanx/phylanx.hpp>\n#include <hpx/hpx_init.hpp>\n\n#include <iostream>\n\n#include <blaze/Math.h>\n#include <boost/program_options.hpp>\n\n#include <hpx/include/agas.hpp>\n#include <hpx/runtime_fwd.hpp>\n\n#include <cstddef>\n#include <cstdint>\n#include <iostream>\n#include <map>\n#include <vector>\n#include <string>\n#include <utility>\n\n///////////////////////////////////////////////////////////////////////////////\nchar const* const read_x_code = R\"(\n    //\n    // Read input-data from given CSV file\n    //\n    define(read_x, filepath, row_start, row_stop, col_start, col_stop,\n        slice(file_read_csv(filepath), make_list(row_start , row_stop),\n              make_list(col_start , col_stop))\n    )\n    read_x\n)\";\n\n\nchar const* const als_explicit = R\"(\n    //\n    // Alternating Least squares algorithm (ALS)\n    //\n    define(als_explicit, ratings, regularization, num_factors, iterations, alpha,\n        enable_output,\n        block(\n            define(num_users, shape(ratings, 0)),\n            define(num_items, shape(ratings, 1)),\n            define(conf, alpha * ratings),\n\n            define(conf_u, constant(0.0, make_list(num_items))),\n            define(conf_i, constant(0.0, make_list(num_users))),\n\n            define(c_u, constant(0.0, make_list(num_items, num_items))),\n            define(c_i, constant(0.0, make_list(num_users, num_users))),\n            define(p_u, constant(0.0, make_list(num_items))),\n            define(p_i, constant(0.0, make_list(num_users))),\n\n            set_seed(0),\n            define(X, random(make_list(num_users, num_factors))),\n            define(Y, random(make_list(num_items, num_factors))),\n            define(I_f, identity(num_factors)),\n            define(I_i, identity(num_items)),\n            define(I_u, identity(num_users)),\n            define(k, 0),\n            define(i, 0),\n            define(u, 0),\n\n            define(XtX, constant(0.0, make_list(num_factors, num_factors))),\n            define(YtY, constant(0.0, make_list(num_factors, num_factors))),\n            define(A, constant(0.0, make_list(num_factors, num_factors))),\n            define(b, constant(0.0, make_list(num_factors))),\n\n            while(k < iterations,\n                block(\n                    if(enable_output,\n                            block(\n                                    cout(\"iteration \", k, u),\n                                    cout(\"X: \",X),\n                                    cout(\"Y: \",Y)\n                            )\n                    ),\n                    store(YtY, dot(transpose(Y), Y) + regularization * I_f),\n                    store(XtX, dot(transpose(X), X) + regularization * I_f),\n\n                    while(u < num_users,\n                        block(\n                            store(conf_u, slice_row(conf, u)),\n                            store(c_u, diag(conf_u)),\n                            store(p_u, __ne(conf_u, 0.0, true)),\n                            store(A, dot(dot(transpose(Y), c_u), Y)+ YtY),\n                            store(b, dot(dot(transpose(Y),(c_u + I_i)), transpose(p_u))),\n                            store(slice(X, list(u, u + 1, 1),nil), dot(inverse(A), b)),\n                            store(u, u + 1)\n                        )\n                    ),\n                    store(u, 0),\n                    while(i < num_items,\n                        block(\n                            store(conf_i, slice_column(conf, i)),\n                            store(c_i, diag(conf_i)),\n                            store(p_i, __ne(conf_i, 0.0, true)),\n                            store(A, dot(dot(transpose(X),c_i), X) + XtX),\n                            store(b, dot(dot(transpose(X),(c_i + I_u)), transpose(p_i))),\n                            store(slice(Y, list(i, i + 1, 1),nil), dot(inverse(A), b)),\n                            store(i, i + 1)\n                        )\n                    ),\n                    store(i, 0),\n                    store(k, k + 1)\n                )\n            ),\n            list(X, Y)\n        )\n    )\n    als_explicit\n)\";\n\nstd::string const als_direct = R\"(\n    //\n    // Alternating Least squares algorithm (ALS) (direct implementation)\n    //\n    define(als_direct, ratings, regularization, num_factors, iterations, alpha,\n        enable_output, als(ratings, regularization, num_factors, iterations, alpha,\n        enable_output)\n    )\n    als_direct\n)\";\n\n///////////////////////////////////////////////////////////////////////////////\n// Find the line/column position in the source code from a given iterator\n// pointing into it.\n//\nstd::pair<std::size_t, std::size_t> get_pos(std::string const& code,\n    std::tuple<std::size_t, std::size_t, std::int64_t> const& tags)\n{\n    // Column might be given directly, in that case line is given as well\n    if (std::get<2>(tags) != -1)\n    {\n        return std::make_pair(std::get<1>(tags), std::get<2>(tags));\n    }\n\n    // Otherwise the given value is the offset into the code\n    std::size_t pos = std::get<1>(tags);\n    std::size_t line = 1;\n    std::size_t column = 1;\n\n    for (std::int64_t i = 0; i != pos && i != code.size(); ++i)\n    {\n        if (code[i] == '\\r' || code[i] == '\\n')    // CR/LF\n        {\n            ++line;\n            column = 1;\n        }\n        else\n        {\n            ++column;\n        }\n    }\n\n    return std::make_pair(line, column);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Find offset into code as given by the tags argument\n//\nstd::size_t get_offset(std::string const& code,\n    std::tuple<std::size_t, std::size_t, std::size_t> const& tags)\n{\n    // Offset might be given directly\n    if (std::get<2>(tags) == -1)\n    {\n        return std::get<1>(tags);\n    }\n\n    // Otherwise the given value is the line/column position in the code\n    std::size_t offset = 0;\n    std::size_t line = 1;\n    std::size_t column = 0;\n\n    for (std::int64_t i = 0; i != code.size(); ++i, ++offset)\n    {\n        if (code[i] == '\\r' || code[i] == '\\n')    // CR/LF\n        {\n            ++line;\n            column = 0;\n        }\n        else\n        {\n            ++column;\n        }\n\n        if (std::get<1>(tags) == line && std::get<2>(tags) == column)\n        {\n            break;\n        }\n    }\n\n    return offset;\n}\n\n// Extract the compile_id/tag pair from a given primitive instance name.\n//\n// The compile_id is a sequence number tracking invocations of the\n// function phylanx::execution_tree::compile (needed to link back to the\n// concrete source code compiled).\n//\n// The tag is an index into the array of iterators filled by\n// phylanx::ast::generate_ast. It allows to find the iterator referring\n// to the construct in the source code a particular primitive instance was\n// created by.\n//\nstd::tuple<std::size_t, std::size_t, std::size_t> extract_tags(\n    std::string const& name)\n{\n    auto data = phylanx::execution_tree::compiler::parse_primitive_name(name);\n    return std::make_tuple(data.compile_id, data.tag1, data.tag2);\n}\n\n// The symbolic names registered in AGAS that identify the created\n// primitive instances have the following structure:\n//\n// /phylanx/<primitive>$<sequence-nr>[$<instance>]/<compile_id>$<tag1>[$<tag2>]\n//\n//  where:\n//      <primitive>:   the name of primitive type representing the given\n//                     node in the expression tree\n//      <sequence-nr>: the sequence number of the corresponding instance\n//                     of type <primitive>\n//      <instance>:    (optional), some primitives have additional instance\n//                     names, for instance references to function arguments\n//                     have the name of the argument as their <instance>\n//      <compile_id>:  the sequence number of the invocation of the\n//                     function phylanx::execution_tree::compile\n//      <tag1>:        if <tag2> == -1: the position inside the compiled code\n//                     block where the referring to the point of usage of the\n//                     primitive in the compiled source code\n//                     if <tag2> != -1: the line number in the compiled code\n//                     block where the referring to the point of usage of the\n//                     primitive in the compiled source code\n//      <tag2>:        (optional) if <tag2> != -1 or not given: the column\n//                      offset in the given line (default: -1)\n//\nvoid print_instrumentation(char const* const name, int compile_id,\n    std::string const& code,\n    phylanx::execution_tree::compiler::function const& func,\n    std::map<std::string, hpx::id_type> const& entries)\n{\n    std::cout << \"Instrumentation information for function: \" << name << \"\\n\";\n\n    for (auto const& e : entries)\n    {\n        // Extract compile_id and iterator index (tag) from the symbolic name\n        auto tags = extract_tags(e.first);\n        if (std::get<0>(tags) != compile_id)\n            continue;\n\n        // Find real position of given symbol in source code\n        if (std::get<1>(tags) != std::size_t(-1))\n        {\n            auto pos = get_pos(code, tags);\n            std::cout << e.first << \": \" << name << \"(\" << pos.first << \", \"\n                      << pos.second << \"): \";\n\n            // Show the next (at max) 20 characters\n            auto offset = get_offset(code, tags);\n            auto end = code.begin() + offset;\n            for (int i = 0; end != code.end() && i != 20; ++end, ++i)\n            {\n                if (*end == '\\n' || *end == '\\r')\n                    break;\n            }\n            std::cout << std::string(code.begin() + offset, end) << \" ...\\n\";\n        }\n        else\n        {\n            std::cout << e.first << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n\n    std::cout << \"Tree information for function: \" << name << \"\\n\";\n    std::cout << phylanx::execution_tree::newick_tree(\n                     name, func.get_expression_topology())\n              << \"\\n\\n\";\n\n    std::cout << phylanx::execution_tree::dot_tree(\n                     name, func.get_expression_topology())\n              << \"\\n\\n\";\n}\n\nvoid print_performance_counter_data_csv(\n    std::vector<std::string> const& existing_primitive_instances)\n{\n    std::cout << std::endl << \"Primitive Performance Counter Data in CSV:\";\n\n    // CSV Header\n    std::cout << \"\\nprimitive_instance,display_name,count,time,eval_direct\\n\";\n\n    // Print performance data\n    for (auto const& entry :\n        phylanx::util::retrieve_counter_data(existing_primitive_instances))\n    {\n        std::cout << \"\\\"\" << entry.first << \"\\\",\\\"\"\n                  << phylanx::execution_tree::compiler::primitive_display_name(\n                         entry.first)\n                  << \"\\\"\";\n        for (auto const& counter_value : entry.second)\n        {\n            std::cout << \",\" << counter_value;\n        }\n        std::cout << std::endl;\n    }\n\n    std::cout << std::endl;\n}\n\nint hpx_main(boost::program_options::variables_map& vm)\n{\n    if (vm.count(\"data_csv\") == 0)\n    {\n        std::cerr << \"Please specify '--data_csv=data-file'\";\n        return hpx::finalize();\n    }\n\n    // compile the given code\n    phylanx::execution_tree::compiler::function_list snippets_read_x;\n    auto const& code_read_x =\n        phylanx::execution_tree::compile(\"read_x\", read_x_code, snippets_read_x);\n\n    phylanx::execution_tree::compiler::function_list snippets_als;\n    auto const& code_als = phylanx::execution_tree::compile(\n        vm.count(\"direct\") != 0 ? als_direct : als_explicit, snippets_als);\n\n    // Enable collection of performance data for all existing primitives\n    auto primitives = phylanx::util::enable_measurements();\n\n    auto read_x = code_read_x.run();\n    auto als = code_als.run();\n\n    // Print instrumentation information, if enabled\n    if (vm.count(\"instrument\") != 0)\n    {\n        auto entries = hpx::agas::find_symbols(hpx::launch::sync, \"/phylanx/*\");\n\n        print_instrumentation(\"als\", 0,\n            vm.count(\"direct\") != 0 ? als_direct : als_explicit, als, entries);\n    }\n\n    // evaluate generated execution tree\n    auto row_start = static_cast<int64_t>(0);\n    auto col_start = static_cast<int64_t>(0);\n    auto row_stop = vm[\"row_stop\"].as<std::int64_t>();\n    auto col_stop = vm[\"col_stop\"].as<std::int64_t>();\n\n    auto regularization = vm[\"regularization\"].as<double>();\n    auto iterations = vm[\"iterations\"].as<int64_t>();\n    auto num_factors = vm[\"factors\"].as<int64_t>();\n    auto alpha = vm[\"alpha\"].as<double>();\n    auto filepath = vm[\"data_csv\"].as<std::string>();\n\n    bool enable_output = vm.count(\"enable_output\") != 0;\n\n    // Read the data from the files\n    auto ratings = read_x(filepath, row_start, row_stop, col_start, col_stop);\n\n    // Measure execution time\n    hpx::util::high_resolution_timer t;\n\n    // Evaluate ALS using the read data\n    auto result =\n        als(ratings, regularization, num_factors, iterations, alpha, enable_output);\n    auto elapsed = t.elapsed();\n\n    // Print performance counter data in CSV\n    if (vm.count(\"instrument\") != 0)\n    {\n        print_performance_counter_data_csv(primitives);\n    }\n\n    // Make sure all counters are properly initialized, don't reset current\n    // counter values\n    hpx::reinit_active_counters(false);\n\n    auto result_r = phylanx::execution_tree::extract_list_value(result);\n    auto it = result_r.begin();\n    std::cout << \"X: \\n\"\n              << phylanx::execution_tree::extract_numeric_value(*it++)\n              << \"\\nY: \\n\"\n              << phylanx::execution_tree::extract_numeric_value(*it)\n              << std::endl;\n    std::cout << \"time: \" << t.elapsed() << std::endl;\n\n    return hpx::finalize();\n}\n\nint main(int argc, char* argv[])\n{\n    // command line handling\n    boost::program_options::options_description desc(\"usage: als [options]\");\n    desc.add_options()(\"enable_output,e\",\n        \"enable progress output (default: false)\")(\"instrument,i\",\n        \"print instrumentation information (default: false)\")(\"direct,d\",\n        \"use direct implementation of ALS (default: false)\")(\"iterations,n\",\n        boost::program_options::value<std::int64_t>()->default_value(3),\n        \"number of iterations (default: 10.0)\")(\"factors,f\",\n        boost::program_options::value<std::int64_t>()->default_value(10),\n        \"number of factors (default: 10)\")(\"alpha,a\",\n        boost::program_options::value<double>()->default_value(40),\n        \"alpha (default: 40)\")(\"regularization,r\",\n        boost::program_options::value<double>()->default_value(0.1),\n        \"regularization (default: 0.1)\")(\"data_csv\",\n        boost::program_options::value<std::string>(),\n        \"file name for reading data\")(\"row_stop\",\n        boost::program_options::value<std::int64_t>()->default_value(10),\n        \"row_stop (default: 10)\")(\"col_stop\",\n        boost::program_options::value<std::int64_t>()->default_value(100),\n        \"col_stop (default: 100)\");\n    return hpx::init(desc, argc, argv);\n}\n", "meta": {"hexsha": "145512d5e7a5cd429a2906ac102977122c13f75b", "size": 15121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/algorithms/als/als_csv_instrumented.cpp", "max_stars_repo_name": "diehlpk/phylanx", "max_stars_repo_head_hexsha": "7eba54f0f22dc66d18addac0b24f006380d0f798", "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/algorithms/als/als_csv_instrumented.cpp", "max_issues_repo_name": "diehlpk/phylanx", "max_issues_repo_head_hexsha": "7eba54f0f22dc66d18addac0b24f006380d0f798", "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/algorithms/als/als_csv_instrumented.cpp", "max_forks_repo_name": "diehlpk/phylanx", "max_forks_repo_head_hexsha": "7eba54f0f22dc66d18addac0b24f006380d0f798", "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.0023809524, "max_line_length": 89, "alphanum_fraction": 0.5532041532, "num_tokens": 3583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.5236477186173029}}
{"text": "/// Implement some functions that absent in the origin HElib.\n#ifndef CRYPT_GMM_HELIB_HPP\n#define CRYPT_GMM_HELIB_HPP\n#include <vector>\n#include <NTL/lzz_p.h>\nclass FHEcontext;\nclass FHESecKey;\nclass Ctxt;\nnamespace NTL { class zz_pX; class ZZX; }\n/// encode and decode without using the G(X) as the EncrypedArray does.\nvoid rawEncode(NTL::zz_pX &out, \n               std::vector<NTL::zz_pX> const& slots, \n               FHEcontext const& context);\nvoid rawEncode(NTL::ZZX &out, \n               std::vector<NTL::zz_pX> const& slots, \n               FHEcontext const& context);\nvoid rawDecode(std::vector<NTL::zz_pX> &out, \n               NTL::zz_pX const& poly, \n               FHEcontext const& context);\nvoid rawDecode(std::vector<NTL::zz_pX> &out, \n               NTL::ZZX const& poly, \n               FHEcontext const& context);\nvoid rawDecode(std::vector<NTL::ZZX> &out, \n               NTL::ZZX const& poly, \n               FHEcontext const& context);\n\nstruct GMMPrecompTable {\n    std::vector<long> beta_powers;\n    NTL::mulmod_t inv_p;\n};\n\nstd::vector<GMMPrecompTable> precompute_gmm_tables(FHEcontext const& context);\n/// Extract inner products from the decrypted polynomial\nvoid extract_inner_products(std::vector<long> &out,\n                            NTL::ZZX const& poly,\n                            std::vector<GMMPrecompTable> const& tables,\n                            FHEcontext const& context);\n\nvoid faster_decrypt(NTL::Vec<long> &out, FHESecKey const& key, Ctxt const &ctx);\n\nvoid extract_inner_products(std::vector<long> &out,\n                            NTL::Vec<long> const& poly,\n                            std::vector<GMMPrecompTable> const& tables,\n                            FHEcontext const& context);\n#endif //CRYPT_GMM_HELIB_HPP\n", "meta": {"hexsha": "8662cade70777daa6090f93b410992cb2eebe013", "size": 1763, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/SMP/HElib.hpp", "max_stars_repo_name": "Vampsj/SMP", "max_stars_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/SMP/HElib.hpp", "max_issues_repo_name": "Vampsj/SMP", "max_issues_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/SMP/HElib.hpp", "max_forks_repo_name": "Vampsj/SMP", "max_forks_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3260869565, "max_line_length": 80, "alphanum_fraction": 0.6199659671, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736771, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5236305004732259}}
{"text": "#include <boost/math/distributions/skew_normal.hpp>\n", "meta": {"hexsha": "7b8104376dd9b8913d8ab3fc1da22edd8fc238ae", "size": 52, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_skew_normal.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_skew_normal.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_skew_normal.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.0, "max_line_length": 51, "alphanum_fraction": 0.8269230769, "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5236304963233046}}
{"text": "\n\n#define _USE_MATH_DEFINES\n\n#include \"fastRect.h\"\n\n\n\n\n\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n\n\n\nstd::vector<std::vector<fast::calPoint>> fast::rectROI(int center_x, int center_y, double angle, int range, int distance, bool direction, int skip_pixels) {\n\n\n\n    if (range == 0) {\n        HVERROR(error, \"Invalid box roi range\");\n    }\n\n    if (distance == 0) {\n        HVERROR(error, \"Invalid box distance\");\n    }\n\n    if (skip_pixels == 0) {\n        HVERROR(error, \"Invalid search step\");\n    }\n\n\n    int dimension = range * distance;\n\n    int roi_mid_width = range / 2;\n    int roi_mid_height = distance / 2;\n\n\n    int start_x1 = 0;\n    int start_y1 = 0;\n    int end_x1 = 0;\n    int end_y1 = 0;\n\n\n    int start_x2 = 0;\n    int start_y2 = 0;\n    int end_x2 = 0;\n    int end_y2 = 0;\n\n\n    if (direction == false) {\n        start_x1 = center_x - roi_mid_width;\n        start_y1 = center_y + roi_mid_height;\n\n        start_x2 = center_x + roi_mid_width;\n        start_y2 = center_y + roi_mid_height;\n\n        end_x1 = center_x - roi_mid_width;\n        end_y1 = center_y - roi_mid_height;\n\n        end_x2 = center_x + roi_mid_width;\n        end_y2 = center_y - roi_mid_height;\n    }\n    else {\n        start_x1 = center_x - roi_mid_width;\n        start_y1 = center_y - roi_mid_height;\n\n        start_x2 = center_x + roi_mid_width;\n        start_y2 = center_y - roi_mid_height;\n\n        end_x1 = center_x - roi_mid_width;\n        end_y1 = center_y + roi_mid_height;\n\n        end_x2 = center_x + roi_mid_width;\n        end_y2 = center_y + roi_mid_height;\n    }\n\n\n\n\n    int size = 4;\n\n    Eigen::MatrixXd trigonometric_matrix(2, 2);\n\n    //trigonometric_matrix\n    trigonometric_matrix(0, 0) = cos(angle * M_PI / 180);\n    trigonometric_matrix(0, 1) = -sin(angle * M_PI / 180);\n    trigonometric_matrix(1, 0) = sin(angle * M_PI / 180);\n    trigonometric_matrix(1, 1) = cos(angle * M_PI / 180);\n\n    //rotation_matrix\n    Eigen::MatrixXd rotation_matrix(2, size);\n\n    //base_matrix\n    Eigen::MatrixXd base_matrix(2, size);\n\n    rotation_matrix(0, 0) = start_x1 - center_x; // x           Start X1\n    rotation_matrix(1, 0) = start_y1 - center_y; // y\n\n    rotation_matrix(0, 1) = start_x2 - center_x; // x\n    rotation_matrix(1, 1) = start_y2 - center_y; // y\n\n    rotation_matrix(0, 2) = end_x1 - center_x;// x\n    rotation_matrix(1, 2) = end_y1 - center_y; // y\n\n    rotation_matrix(0, 3) = end_x2 - center_x; // x\n    rotation_matrix(1, 3) = end_y2 - center_y; /// y\n\n    // No problem\n    for (int index = 0; index < 4; index++) {\n        base_matrix(0, index) = center_x;\n        base_matrix(1, index) = center_y;\n    }\n\n    Eigen::MatrixXd result = trigonometric_matrix * rotation_matrix + base_matrix;\n\n\n    double rotated_start_x1 = result(0, 0);\n    double rotated_start_y1 = result(1, 0);\n\n    double rotated_start_x2 = result(0, 1);\n    double rotated_start_y2 = result(1, 1);\n\n    double rotated_end_x1 = result(0, 2);\n    double rotated_end_y1 = result(1, 2);\n\n    double rotated_end_x2 = result(0, 3);\n    double rotated_end_y2 = result(1, 3);\n\n\n    //startx1 = rotated_start_x1;\n    //starty1 = rotated_start_y1;\n    //startx2 = rotated_start_x2;\n    //starty2 = rotated_start_y2;\n    //endx1 = rotated_end_x1;\n    //endy1 = rotated_end_y1;\n    //endx2 = rotated_end_x2;\n    //endy2 = rotated_end_y2;\n\n    double diff_start_x = rotated_start_x2 - rotated_start_x1;\n    double diff_start_y = rotated_start_y2 - rotated_start_y1;\n\n    double increase_rate_x = diff_start_x / range;\n    double increase_rate_y = diff_start_y / range;\n\n\n    //Start Line Points\n    //Start Line Points\n    //Start Line Points\n    //Start Line Points\n    int range_align_size = (range)+(range % 4);\n    std::vector<double> range_vec(range_align_size * 2);\n    for (int index = 0; index < range * 2; index += 2) {\n        int current_index = index;\n        range_vec[index] = current_index / 2;\n        range_vec[index + 1] = current_index / 2;\n    }\n\n    std::vector<fast::calPoint> start_line_xy(range_align_size);\n    std::vector<fast::calPoint> end_line_xy(range_align_size);\n\n    std::vector<double> increase_rate_xy_vec = { increase_rate_x, increase_rate_y,increase_rate_x, increase_rate_y };\n    const __m256d simd_increase_rate_xy = _mm256_load_pd(increase_rate_xy_vec.data());\n\n    std::vector<double> simd_start_xy_vec = { rotated_start_x1 , rotated_start_y1, rotated_start_x1 , rotated_start_y1 };\n    const __m256d simd_start_xy = _mm256_load_pd(simd_start_xy_vec.data());\n\n    std::vector<double> simd_end_xy_vec = { rotated_end_x1 , rotated_end_y1, rotated_end_x1 , rotated_end_y1 };\n    const __m256d simd_end_xy = _mm256_load_pd(simd_end_xy_vec.data());\n\n\n    const double* range_ptr = &range_vec[0];\n\n    const fast::calPoint* start_result_xy_ptr = start_line_xy.data();\n    const fast::calPoint* end_result_xy_ptr = end_line_xy.data();\n\n    int chunk_size = sizeof(double) * 4;\n    for (int index = 0; index < range * 2; index += 4) {\n\n        __m256d range_chunk = _mm256_load_pd(range_ptr + index);\n\n        __m256d chunk_mul = _mm256_mul_pd(simd_increase_rate_xy, range_chunk);\n\n        // Start Line\n        __m256d start_result = _mm256_add_pd(chunk_mul, simd_start_xy);\n\n        // End Line\n        __m256d end_result = _mm256_add_pd(chunk_mul, simd_end_xy);\n        memcpy(((double*)start_result_xy_ptr + index), &start_result, chunk_size);\n        memcpy(((double*)end_result_xy_ptr + index), &end_result, chunk_size);\n    }\n\n    //Start Line Points\n    //Start Line Points\n    //Start Line Points\n    //Start Line Points\n\n    int distance_align_size = (distance)+(distance % 4);\n    std::vector<double> distance_vec(distance_align_size * 2);\n    for (int index = 0; index < distance * 2; index += 2) {\n        int current_index = index;\n        distance_vec[index] = current_index / 2;\n        distance_vec[index + 1] = current_index / 2;\n    }\n\n    std::vector<std::vector<fast::calPoint>> combine_vertical_xy;\n\n    double diff_virtical_start_x = rotated_end_x1 - rotated_start_x1;\n    double diff_virtical_start_y = rotated_end_y1 - rotated_start_y1;\n\n    double increase_virtical_rate_x = diff_virtical_start_x / distance;\n    double increase_virtical_rate_y = diff_virtical_start_y / distance;\n\n    std::vector<double> increase_vertical_rate_xy_vec = { increase_virtical_rate_x, increase_virtical_rate_y,increase_virtical_rate_x, increase_virtical_rate_y };\n    const __m256d simd_increase_vertical_rate_xy = _mm256_load_pd(increase_vertical_rate_xy_vec.data());\n\n    for (int range_index = 0; range_index < range; range_index += skip_pixels) {\n\n        auto start_vertical_point = start_line_xy[range_index];\n        std::vector<double> simd_vertical_xy_vec = { start_vertical_point.x , start_vertical_point.y, start_vertical_point.x , start_vertical_point.y };\n        const __m256d simd_vertical_xy = _mm256_load_pd(simd_vertical_xy_vec.data());\n\n        const double* distance_ptr = &distance_vec[0];\n\n        std::vector<fast::calPoint> vertical_xy;\n        vertical_xy.resize(distance_align_size);\n        const fast::calPoint* start_vertical_xy_ptr = vertical_xy.data();\n\n        for (int index = 0; index < distance * 2; index += 4) {\n            __m256d distance_chunk = _mm256_load_pd(distance_ptr + index);\n            __m256d chunk_mul = _mm256_mul_pd(simd_increase_vertical_rate_xy, distance_chunk);\n            __m256d start_result = _mm256_add_pd(chunk_mul, simd_vertical_xy);\n            memcpy((((double*)start_vertical_xy_ptr) + index), &start_result, chunk_size);\n        }\n\n        combine_vertical_xy.push_back(vertical_xy);\n    }\n\n    return combine_vertical_xy;\n}", "meta": {"hexsha": "f58567a0b4b67330bb39a49b504d7a01a814e35e", "size": 7613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FastROI/fastROI/fastRect.cpp", "max_stars_repo_name": "boa9448/FastROI", "max_stars_repo_head_hexsha": "11609a19271e7e23edf597a14b56ea459c865012", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FastROI/fastROI/fastRect.cpp", "max_issues_repo_name": "boa9448/FastROI", "max_issues_repo_head_hexsha": "11609a19271e7e23edf597a14b56ea459c865012", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FastROI/fastROI/fastRect.cpp", "max_forks_repo_name": "boa9448/FastROI", "max_forks_repo_head_hexsha": "11609a19271e7e23edf597a14b56ea459c865012", "max_forks_repo_licenses": ["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.458677686, "max_line_length": 162, "alphanum_fraction": 0.6733219493, "num_tokens": 2115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782092, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5235727395130617}}
{"text": "// From : https://raw.githubusercontent.com/Smorodov/Multitarget-tracker/master/KalmanFilter/Kalman.h\n#pragma once\n#include <opencv2/opencv.hpp>\n//#include <Eigen/Geometry>\n// http://www.morethantechnical.com/2011/06/17/simple-kalman-filter-for-tracking-using-opencv-2-2-w-code/\nclass TKalmanFilter\n{\n\tpublic:\n\t\tTKalmanFilter(const cv::Point3f &p, float dt = 0.05, float Accel_noise_mag = 0.5);\n\t\tcv::Point3f GetPrediction();\n\t\tcv::Point3f Update(const cv::Point3f &p);\n\t//\tvoid adjustPrediction(const Eigen::Transform<double, 3, Eigen::Isometry> &delta_robot);\n\t\tvoid adjustPrediction(const cv::Point3f &delta_pos);\n\tprivate:\n\t\tcv::KalmanFilter kalman;\n};\n\n", "meta": {"hexsha": "2877bcb8b7521aebe9d185c75d79bfb7d0e2ad81", "size": 658, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "common/kalman.hpp", "max_stars_repo_name": "mattwalstra/2019RobotCode", "max_stars_repo_head_hexsha": "44f2543876b95428a68dc84820f931571244e49d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-25T18:30:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T04:50:16.000Z", "max_issues_repo_path": "common/kalman.hpp", "max_issues_repo_name": "mattwalstra/2019RobotCode", "max_issues_repo_head_hexsha": "44f2543876b95428a68dc84820f931571244e49d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2021-03-20T01:10:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T22:51:05.000Z", "max_forks_repo_path": "common/kalman.hpp", "max_forks_repo_name": "mattwalstra/2019RobotCode", "max_forks_repo_head_hexsha": "44f2543876b95428a68dc84820f931571244e49d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-29T01:13:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T21:53:06.000Z", "avg_line_length": 36.5555555556, "max_line_length": 105, "alphanum_fraction": 0.7507598784, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5235250392750167}}
{"text": "//\n//  Copyright Markus Rickert 2008\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/numeric/ublas/io.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/vector_proxy.hpp>\n#include <boost/numeric/bindings/blas/level3/gemm.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/bindings/std/valarray.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\n\nnamespace bindings = boost::numeric::bindings;\n\nint\nmain(int argc, char** argv)\n{\n  {\n    // a * b' = C ; a' * b = d\n\n    boost::numeric::ublas::vector<double> a(3);\n    for(std::size_t i = 0; i < a.size(); ++i) a(i) = i;\n    std::cout << \"a=\" << a << std::endl;\n\n    boost::numeric::ublas::vector<double> b(3);\n    for(std::size_t i = 0; i < b.size(); ++i) b(i) = i;\n    std::cout << \"b=\" << b << std::endl;\n\n    boost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> c(3, 3);\n    boost::numeric::bindings::blas::gemm(\n      1.0, a, bindings::trans(b), 0.0, c\n    );\n    std::cout << \"c=\" << c << std::endl;\n\n    boost::numeric::ublas::vector<double> d(1);\n    boost::numeric::bindings::blas::gemm(\n      1.0, bindings::trans(a), b, 0.0, d\n    );\n    std::cout << \"d=\" << d << std::endl;\n  }\n\n  std::cout << std::endl;\n\n  {\n    // a * b' = C ; a' * b = d\n\n    std::vector<double> a(3);\n    for(std::size_t i = 0; i < a.size(); ++i) a[i] = i;\n    std::cout << \"a=[\" << a.size() << \"](\";\n    for(std::size_t i = 0; i < a.size(); ++i) std::cout << (i > 0 ? \",\" : \"\") << a[i];\n    std::cout << \")\" << std::endl;\n\n    std::valarray<double> b(3);\n    for(std::size_t i = 0; i < b.size(); ++i) b[i] = i;\n    std::cout << \"b=[\" << b.size() << \"](\";\n    for(std::size_t i = 0; i < b.size(); ++i) std::cout << (i > 0 ? \",\" : \"\") << b[i];\n    std::cout << \")\" << std::endl;\n\n    boost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> c(3, 3);\n    boost::numeric::bindings::blas::gemm(\n      1.0, a, bindings::trans(b), 0.0, c\n    );\n    std::cout << \"c=\" << c << std::endl;\n\n    std::vector<double> d(1);\n    boost::numeric::bindings::blas::gemm(\n      1.0, bindings::trans(a), b, 0.0, d\n    );\n    std::cout << \"d=[\" << d.size() << \"](\";\n    for(std::size_t i = 0; i < d.size(); ++i) std::cout << (i > 0 ? \",\" : \"\") << d[i];\n    std::cout << \")\" << std::endl;\n  }\n\n  std::cout << std::endl;\n\n  {\n    // a * b' = C ; a' * b = d\n\n    double a[3];\n    for(std::size_t i = 0; i < 3; ++i) a[i] = i;\n    std::cout << \"a=[\" << 3 << \"](\";\n    for(std::size_t i = 0; i < 3; ++i) std::cout << (i > 0 ? \",\" : \"\") << a[i];\n    std::cout << \")\" << std::endl;\n\n    std::vector<double> b(3);\n    for(std::size_t i = 0; i < b.size(); ++i) b[i] = i;\n    std::cout << \"b=[\" << b.size() << \"](\";\n    for(std::size_t i = 0; i < b.size(); ++i) std::cout << (i > 0 ? \",\" : \"\") << b[i];\n    std::cout << \")\" << std::endl;\n\n    boost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> c(3, 3);\n    boost::numeric::bindings::blas::gemm(\n      1.0, a, bindings::trans(b), 0.0, c\n    );\n    std::cout << \"c=\" << c << std::endl;\n\n    std::valarray<double> d(1);\n    boost::numeric::bindings::blas::gemm(\n      1.0, bindings::trans(a), b, 0.0, d\n    );\n    std::cout << \"d=[\" << d.size() << \"](\";\n    for(std::size_t i = 0; i < d.size(); ++i) std::cout << (i > 0 ? \",\" : \"\") << d[i];\n    std::cout << \")\" << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "8d80c06d770cad15b99b7db2cdb0cc7a0e13dbf0", "size": 3612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/blas/test/vector2.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/blas/test/vector2.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/blas/test/vector2.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": 31.6842105263, "max_line_length": 87, "alphanum_fraction": 0.5157807309, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5235074843203024}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Triangulation_2.h>\n#include <CGAL/Projection_traits_xy_3.h>\n#include <CGAL/boost/graph/graph_traits_Triangulation_2.h>\n#include <CGAL/boost/graph/iterator.h>\n\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/foreach.hpp>\n\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Epic;\ntypedef CGAL::Projection_traits_xy_3<Epic>  K;\ntypedef K::Point_2 Point;\n\ntypedef CGAL::Triangulation_2<K> Triangulation;\n\n\ntypedef boost::graph_traits<Triangulation>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<Triangulation>::halfedge_descriptor halfedge_descriptor;\ntypedef boost::graph_traits<Triangulation>::halfedge_iterator halfedge_iterator;\ntypedef boost::graph_traits<Triangulation>::face_descriptor face_descriptor;\ntypedef boost::graph_traits<Triangulation>::vertex_iterator vertex_iterator;\ntypedef boost::graph_traits<Triangulation>::face_iterator face_iterator;\ntypedef boost::graph_traits<Triangulation>::edge_iterator edge_iterator;\ntypedef boost::graph_traits<Triangulation>::edge_descriptor edge_descriptor;\n\ntypedef std::map<vertex_descriptor,int> VertexIndexMap;\nVertexIndexMap vertex_id_map;\n\ntypedef boost::associative_property_map<VertexIndexMap> VertexIdPropertyMap;\nVertexIdPropertyMap vertex_index_pmap(vertex_id_map);\n\ntypedef std::map<halfedge_descriptor,int> HalfedgeIndexMap;\nHalfedgeIndexMap halfedge_id_map;\n\ntypedef boost::associative_property_map<HalfedgeIndexMap> HalfedgeIdPropertyMap;\nHalfedgeIdPropertyMap halfedge_index_pmap(halfedge_id_map);\n\nint\nmain(int,char*[])\n{\n  Triangulation t;\n\n  t.insert(Point(0.1,0,1));\n  t.insert(Point(1,0,1));\n  t.insert(Point(0.2,0.2, 2));\n  t.insert(Point(0,1,2));\n  t.insert(Point(0,2,3));\n\n  vertex_iterator vit, ve;\n  // Associate indices to the vertices\n  int index = 0;\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(vit,ve) = vertices(t); vit!=ve; ++vit ){\n    vertex_descriptor  vd = *vit;\n    if(! t.is_infinite(vd)){\n      vertex_id_map[vd]= index++;\n    }\n  }\n\n  std::cerr << index << \" vertices\" << std::endl;\n  index = 0;\n  face_iterator fit,fe;\n  for(boost::tie(fit,fe) = faces(t); fit!= fe; ++fit){\n    face_descriptor fd = *fit;\n    halfedge_descriptor hd = halfedge(fd,t);\n    halfedge_descriptor n = next(hd,t);\n    \n    halfedge_descriptor nn = next(n,t);\n    if(next(nn,t) != hd){\n      std::cerr << \"the face is not a triangle\" << std::endl;\n    }\n    \n    ++index;\n  }\n  \n  std::cerr << index << \" faces\" << std::endl;\n  index = 0;\n\n  edge_iterator eit,ee;\n  for(boost::tie(eit,ee) = edges(t); eit!= ee; ++eit){\n    edge_descriptor ed = *eit;\n    vertex_descriptor vd = source(ed,t);\n    CGAL_USE(vd);\n    ++index;\n  }\n\n  std::cerr << index << \" edges\" << std::endl;\n  index = 0;\n\n  halfedge_iterator hit,he;\n  for(boost::tie(hit,he) = halfedges(t); hit!= he; ++hit){\n    halfedge_descriptor hd = *hit;\n    vertex_descriptor vd = source(hd,t);\n    CGAL_USE(vd);\n    ++index;\n  }\n  std::cerr << index << \" halfedges\" << std::endl;\n\n  std::cerr << num_vertices(t) << \" \" << num_edges(t) << \" \" << num_halfedges(t) << \" \" << num_faces(t) << std::endl;\n\n  typedef boost::property_map<Triangulation, boost::vertex_point_t>::type Ppmap;\n  Ppmap ppmap = get(boost::vertex_point, t);\n \n\n  BOOST_FOREACH(vertex_descriptor vd, vertices_around_target(*vertices(t).first, t)){\n    std::cout <<  ppmap[vd] << std::endl;\n  }\n\n\n  ppmap[*(++vertices(t).first)] = Point(78,1,2);\n  std::cout << \" changed point of vertex \" << ppmap[*(++vertices(t).first)] << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "1e84a5089149690068c0aae49e617ae9eb58eb9a", "size": 3661, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_triangulation_2/face_graph.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_triangulation_2/face_graph.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_triangulation_2/face_graph.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": 31.2905982906, "max_line_length": 117, "alphanum_fraction": 0.7112810707, "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.5235074791542587}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n#include <memory>\n#include \"../include/trainer.h\"\n#include \"../include/model.h\"\n#include \"../include/optimizer.h\"\n#include \"../datasets/include/mnist.h\"\n\nvoid display_history(MyDL::Trainer& trainer);\n\nint main()\n{\n    using namespace Eigen;\n    using namespace MyDL;\n    using std::cout;\n    using std::endl;\n    using std::shared_ptr;\n    using std::make_shared;\n\n    int batch_size = 100;\n    int input_size = 28*28;\n    vector<int> hidden_size = {50};\n    int output_size = 10;\n    double lambda = 2.0;\n\n    double learning_rate = 0.1;\n    int epochs = 2;\n\n    auto model = make_shared<MultiLayerModel>(input_size, hidden_size, output_size, lambda);\n    auto optimizer = make_shared<SGD>(learning_rate);\n    auto dataset = make_shared<MnistEigenDataset>(batch_size);\n\n    Trainer trainer(model, optimizer, dataset, epochs=epochs);\n\n    trainer.train();\n\n    display_history(trainer);\n\n    return 0;\n}\n\n\n// util.cpp\u3092\u4f5c\u6210\u3057\u3001\u305d\u306e\u4e2d\u306b\u8a18\u8ff0\u3059\u308b\uff1f\nvoid display_history(MyDL::Trainer& trainer)\n{\n    using std::cout;\n    using std::endl;\n\n    cout << \"Train acc history: \";\n    for (const auto &item : trainer.train_acc_history)\n    {\n        cout << item << \" \";\n    }\n    cout << endl;\n\n    cout << \"Test acc history: \";\n    for (const auto &item : trainer.test_acc_history)\n    {\n        cout << item << \" \";\n    }\n    cout << endl;\n}", "meta": {"hexsha": "2adfd4241c93cf4f3779df53283e2df17af45bfe", "size": 1381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_trainer_multi_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": "test/test_trainer_multi_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": "test/test_trainer_multi_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": 21.9206349206, "max_line_length": 92, "alphanum_fraction": 0.6430123099, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5235074775386162}}
{"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_POWER_EXPLICIT_INCLUDE\n#define MTL_POWER_EXPLICIT_INCLUDE\n\n#include <boost/numeric/linear_algebra/algebraic_concepts.hpp>\n#include <boost/numeric/linear_algebra/concepts.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/linear_algebra/inverse.hpp>\n\n\n\nnamespace mtl {\n\ntemplate <typename Op, typename Element, typename Exponent>\n  _GLIBCXX_WHERE( std::Integral<Exponent> \n\t    && std::Callable2<Op, Element, Element>\n\t    && std::Assignable<Element, std::Callable2<Op, Element, Element>::result_type>)            \ninline Element power(const Element& base, Exponent n, Op op) \n{\n    if (n < 1) throw \"In power: exponent must be greater than 0\";\n    // std::cout << \"[Magma] \";\n    \n    Element value= base;\n    for (; n > 1; --n)\n\tvalue= op(value, base);\n    return value;\n}\n\n\n# ifndef __GXX_CONCEPTS__\n#   ifdef LA_SHOW_WARNINGS\n#     warning \"Automatic dispatching only works with concept compiler\"\n#     warning \"If structure is a Monoid you can call square_and_multiply directly\"\n#   endif\n# else\n\ntemplate <typename Op, typename Element, typename Exponent>\n    where algebra::SemiGroup<Op, Element> && std::Integral<Exponent>\n          && std::Callable2<Op, Element, Element>\n          && std::Assignable<Element, std::Callable2<Op, Element, Element>::result_type>            \ninline Element power(const Element& base, Exponent n, Op op)\n{\n    // std::cout << \"[SemiGroup] \";\n\n    if (n <= 0) throw \"In recursive_multiply_and_square: exponent must greater than 0\";\n\n    Exponent half= n >> 1;\n\n    // If halt is 0 then n must be 1 and the result is base\n    if (half == 0)\n\treturn base;\n\n    // compute power of downward rounded exponent and square the result\n    Element value= power(base, half, op);\n    value= op(value, value);\n\n    // if odd another multiplication with base is needed\n    if (n & 1) \n\tvalue= op(value, base);\n    return value;\n}\n\n// {Op, Element} must be a Monoid\ntemplate <typename Op, typename Element, typename Exponent>\n    where algebra::Monoid<Op, Element> \n          && std::Integral<Exponent>\n          && std::Callable2<Op, Element, Element>\n          && std::Assignable<Element, std::Callable2<Op, Element, Element>::result_type>\n// && std::Assignable<Element, algebdra::Monoid<Op, Element>::identity_result_type>\n          && std::Assignable<Element, Element>\ninline Element multiply_and_square(const Element& base, Exponent n, Op op) \n{\n    // Same as the simpler form except that the first multiplication is made before \n    // the loop and one squaring is saved this way\n    if (n < 0) throw \"In multiply_and_square: negative exponent\";\n\n    using math::identity;\n    Element value= identity(op, base), square= identity(op, base);\n\n    if (n & 1)\n        value= base;\n\n    for (n>>= 1; n > 0; n>>= 1) {\n\tsquare= op(square, square); \n\tif (n & 1) \n\t    value= op(value, square);\n    }\n    return value;  \n} \n\ntemplate <typename Op, typename Element, typename Exponent>\n    where algebra::Monoid<Op, Element> && std::Integral<Exponent>\n          && std::Callable2<Op, Element, Element>\n          && std::Assignable<Element, std::Callable2<Op, Element, Element>::result_type>            \n          && std::Assignable<Element, Element>\ninline Element power(const Element& base, Exponent n, Op op)\n{\n    return multiply_and_square(base, n, op);\n}\n\ntemplate <typename Op, typename Element, typename Exponent>\n    where algebra::Group<Op, Element> && std::SignedIntegral<Exponent>\n          && std::Callable2<Op, Element, Element>\n          && std::Assignable<Element, std::Callable2<Op, Element, Element>::result_type>            \n          && std::Assignable<Element, Element>\ninline Element power(const Element& base, Exponent n, Op op)\n{\n    using math::inverse;\n\n    return n >= 0 ? multiply_and_square(base, n, op) \n\t          : multiply_and_square(inverse(op, base), -n, op);\n}\n\n\n# endif   // __GXX_CONCEPTS__\n\n} // namespace mtl\n\n#endif // MTL_POWER_EXPLICIT_INCLUDE\n", "meta": {"hexsha": "2a8f6d1044c4879028b54ff09faa05e7ee986282", "size": 4393, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/linear_algebra/test/power_explicit.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": "libs/numeric/linear_algebra/test/power_explicit.hpp", "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/linear_algebra/test/power_explicit.hpp", "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.534351145, "max_line_length": 100, "alphanum_fraction": 0.6722057819, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5235074759229733}}
{"text": "#define BOOST_TEST_MODULE \"test_lennard_jones_wall_potential\"\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 <mjolnir/forcefield/external/LennardJonesWallPotential.hpp>\n\nBOOST_AUTO_TEST_CASE(LennardJonesWallPotential_double)\n{\n    using real_type = double;\n    constexpr static std::size_t N   = 10000;\n    constexpr static real_type   h   = 1e-6;\n    constexpr static real_type   tol = 1e-5;\n\n    const real_type sigma   = 1.0;\n    const real_type epsilon = 1.0;\n    const std::vector<std::pair<std::size_t, std::pair<real_type, real_type>>>\n        sigma_epsilon{{0u, {sigma, epsilon}}};\n\n    mjolnir::LennardJonesWallPotential<real_type> ljw(2.5, sigma_epsilon);\n\n    const real_type cutoff_length = ljw.max_cutoff_length();\n    const real_type z_min         = sigma * 0.5;\n    const real_type z_max         = cutoff_length;\n    const real_type dz            = (z_max - z_min) / N;\n\n    real_type z = z_min;\n    for(std::size_t i = 0; i < N; ++i)\n    {\n        const real_type pot1 = ljw.potential(0, z + h);\n        const real_type pot2 = ljw.potential(0, z - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = ljw.derivative(0, z);\n\n        if(std::abs(deri) > tol)\n        {\n            BOOST_TEST(dpot == deri, boost::test_tools::tolerance(tol));\n        }\n        else\n        {\n            BOOST_TEST(deri == 0.0, boost::test_tools::tolerance(tol));\n        }\n        z += dz;\n    }\n}\n", "meta": {"hexsha": "e71ba35a11a2ec634a19f2a20ddb5cc88b606f6d", "size": 1519, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_lennard_jones_wall_potential.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_lennard_jones_wall_potential.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_lennard_jones_wall_potential.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": 31.0, "max_line_length": 78, "alphanum_fraction": 0.6313364055, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5235074759229733}}
{"text": "// BSD 3-Clause License\n\n// Copyright (c) 2020, Chenyu\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,\n// 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\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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#include \"clustering/spectral_cluster.h\"\n\n#include <Spectra/SymEigsSolver.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <algorithm>\n\n#include \"clustering/kmeans.h\"\n// #include <Spectra/GenEigsSolver.h>\n#include <Spectra/MatOp/SparseSymMatProd.h>\n// #include <Spectra/MatOp/SparseGenMatProd.h>\n#include <glog/logging.h>\n\n#include \"util/timer.h\"\n\nnamespace DAGSfM {\n\nstd::unordered_map<int, int> SpectralCluster::ComputeCluster(\n    const std::vector<std::pair<int, int>>& edges,\n    const std::vector<int>& weights, const int num_partitions) {\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  // 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 = node_mapper_[edges[i].first], dst = node_mapper_[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] += 1;\n    degrees[dst] += 1;\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: \"\n            << 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: \"\n            << 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>>\n      eigs(&op, k, 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++;\n    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  // 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(id, id) = it->second;\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 /\n    // it->second; D_sqrt.insert(node_mapper_.at(id), node_mapper_.at(id)) =\n    // -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 DAGSfM", "meta": {"hexsha": "f7bc864d01ada576ef5b06c51f001b0d291a52a0", "size": 6069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/clustering/spectral_cluster.cpp", "max_stars_repo_name": "Yzhbuaa/DAGSfM", "max_stars_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 255.0, "max_stars_repo_stars_event_min_datetime": "2018-12-14T05:59:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-04T12:15:32.000Z", "max_issues_repo_path": "src/clustering/spectral_cluster.cpp", "max_issues_repo_name": "Yzhbuaa/DAGSfM", "max_issues_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2018-12-25T03:02:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T03:33:25.000Z", "max_forks_repo_path": "src/clustering/spectral_cluster.cpp", "max_forks_repo_name": "Yzhbuaa/DAGSfM", "max_forks_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2018-12-14T06:09:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T08:29:31.000Z", "avg_line_length": 34.095505618, "max_line_length": 80, "alphanum_fraction": 0.686933597, "num_tokens": 1588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5235074759229733}}
{"text": "#ifndef SSMPACK_MODEL_SWITCHING_ADDITIVE_LINEAR_GAUSSIAN_HPP\n#define SSMPACK_MODEL_SWITCHING_ADDITIVE_LINEAR_GAUSSIAN_HPP\n\n#include <armadillo>\n\nnamespace ssmkit {\nnamespace map {\n\nstruct SwitchingAdditiveLinearGaussian {\n  using TParameter = std::tuple<arma::vec, arma::mat>;\n  using TConditionVAR = arma::vec;\n\n  SwitchingAdditiveLinearGaussian(arma::mat trans, arma::mat cov, arma::mat b)\n      : biases{b}, transfer{trans}, covariance{cov} {}\n  // should not be overloaded, should not be template\n  TParameter operator()(const TConditionVAR &x, const int &k) const {\n    return std::make_tuple(transfer * x + biases.col(k), covariance);\n  }\n\n  arma::mat biases;\n  arma::mat transfer;\n  arma::mat covariance;\n};\n\n\n} // namespace map\n} // namespace ssmkit\n\n#endif // SSMPACK_MODEL_SWITCHING_ADDITIVE_LINEAR_GAUSSIAN_HPP\n", "meta": {"hexsha": "db15d88f1d609955468f0e4f42543e6799d068f1", "size": 822, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ssmkit/map/switching_additive_linear_gaussian.hpp", "max_stars_repo_name": "vahid-bastani/ssmpack", "max_stars_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-07-08T09:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-10T06:46:55.000Z", "max_issues_repo_path": "src/ssmkit/map/switching_additive_linear_gaussian.hpp", "max_issues_repo_name": "vahidbas/ssmkit", "max_issues_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ssmkit/map/switching_additive_linear_gaussian.hpp", "max_forks_repo_name": "vahidbas/ssmkit", "max_forks_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T17:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T17:46:08.000Z", "avg_line_length": 27.4, "max_line_length": 78, "alphanum_fraction": 0.7542579075, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5235074655908859}}
{"text": "// Copyright (c) 2020 Graphcore Ltd. All rights reserved.\n//\n#include <popsolver/Model.hpp>\n#define BOOST_TEST_MODULE Mod\n#include <boost/test/unit_test.hpp>\n\nusing namespace popsolver;\n\nBOOST_AUTO_TEST_CASE(Mod) {\n  Model m;\n  auto a = m.addConstant(1);\n  auto b = m.addConstant(1);\n  auto c = m.mod(a, b);\n  auto s = m.minimize(c);\n  BOOST_CHECK_EQUAL(s[c], DataType{0});\n}\n\nBOOST_AUTO_TEST_CASE(Mod0) {\n  Model m;\n  auto a = m.addConstant(1);\n  auto b = m.addConstant(0);\n  auto c = m.mod(a, b);\n  auto s = m.minimize(c);\n  // Can't divide by zero\n  BOOST_CHECK(!s.validSolution());\n}\n\nBOOST_AUTO_TEST_CASE(ModAEqualB) {\n  Model m;\n  auto a = m.addConstant(4);\n  auto b = m.addConstant(4);\n  auto c = m.mod(a, b);\n  auto s = m.minimize(c);\n  BOOST_CHECK_EQUAL(s[c], DataType{0});\n}\n\nBOOST_AUTO_TEST_CASE(ModBEqual1) {\n  Model m;\n  auto a = m.addConstant(4);\n  auto b = m.addConstant(1);\n  auto c = m.mod(a, b);\n  auto s = m.minimize(c);\n  BOOST_CHECK_EQUAL(s[c], DataType{0});\n}\n\nBOOST_AUTO_TEST_CASE(ModAGreaterThanB) {\n  Model m;\n  auto a = m.addConstant(8);\n  auto b = m.addConstant(4);\n  auto c = m.mod(a, b);\n  auto s = m.minimize(c);\n  BOOST_CHECK_EQUAL(s[c], DataType{0});\n}\n\nBOOST_AUTO_TEST_CASE(ModAGreaterThanBNonZero) {\n  Model m;\n  auto a = m.addConstant(7);\n  auto b = m.addConstant(4);\n  auto c = m.mod(a, b);\n  auto s = m.minimize(c);\n  BOOST_CHECK_EQUAL(s[c], DataType{3});\n}\n\nBOOST_AUTO_TEST_CASE(ModALessThanB) {\n  Model m;\n  auto a = m.addConstant(4);\n  auto b = m.addConstant(8);\n  auto c = m.mod(a, b);\n  auto s = m.minimize(c);\n  BOOST_CHECK_EQUAL(s[c], DataType{4});\n}\n", "meta": {"hexsha": "b931cab932ee63bf70fab4b07c8471e34b966337", "size": 1595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/popsolver/Mod.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/popsolver/Mod.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/popsolver/Mod.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": 22.1527777778, "max_line_length": 57, "alphanum_fraction": 0.6570532915, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.523464506913486}}
{"text": "#include \"Calibration.h\"\n#include <Eigen/Core>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/opencv.hpp>\n#include <iostream>\n#include <QDir>\n#include <QTime>\n\nusing namespace std;\nusing namespace cv;\n\nextern struct VISION_PARAM vision_param;\n\n//https://github.com/CompileSense/StereoCamera\nconst int imageWidth = 752; //\u6444\u50cf\u5934\u7684\u5206\u8fa8\u7387\nconst int imageHeight = 480;\nconst int boardWidth = 9;                         //\u6a2a\u5411\u7684\u89d2\u70b9\u6570\u76ee\nconst int boardHeight = 6;                        //\u7eb5\u5411\u7684\u89d2\u70b9\u6570\u636e\nconst int boardCorner = boardWidth * boardHeight; //\u603b\u7684\u89d2\u70b9\u6570\u636e\nconst int squareSize = 25;                        //\u6807\u5b9a\u677f\u9ed1\u767d\u683c\u5b50\u7684\u5927\u5c0f \u5355\u4f4dmm\nconst Size imageSize = Size(imageWidth, imageHeight);\n\nconst Size boardSize = Size(boardWidth, boardHeight);\nMat intrinsicL;                   //\u76f8\u673a\u5185\u53c2\u6570\nMat distortion_coeffL;            //\u76f8\u673a\u7578\u53d8\u53c2\u6570\nvector<Mat> rvecsL;               //\u65cb\u8f6c\u5411\u91cf\nvector<Mat> tvecsL;               //\u5e73\u79fb\u5411\u91cf\nvector<vector<Point2f>> cornersL; //\u5404\u4e2a\u56fe\u50cf\u627e\u5230\u7684\u89d2\u70b9\u7684\u96c6\u5408 \u548cobjRealPoint \u4e00\u4e00\u5bf9\u5e94\n\nMat intrinsicR;                   //\u76f8\u673a\u5185\u53c2\u6570\nMat distortion_coeffR;            //\u76f8\u673a\u7578\u53d8\u53c2\u6570\nvector<Mat> rvecsR;               //\u65cb\u8f6c\u5411\u91cf\nvector<Mat> tvecsR;               //\u5e73\u79fb\u5411\u91cf\nvector<vector<Point2f>> cornersR; //\u5404\u4e2a\u56fe\u50cf\u627e\u5230\u7684\u89d2\u70b9\u7684\u96c6\u5408 \u548cobjRealPoint \u4e00\u4e00\u5bf9\u5e94\nvector<Mat> intrinsics, distortion_coeffs;\n\nvector<vector<Point3f>> objRealPoint; //\u5404\u526f\u56fe\u50cf\u7684\u89d2\u70b9\u7684\u5b9e\u9645\u7269\u7406\u5750\u6807\u96c6\u5408\n\nvector<Point2f> cornerL; //\u67d0\u4e00\u526f\u56fe\u50cf\u627e\u5230\u7684\u89d2\u70b9\nvector<Point2f> cornerR; //\u67d0\u4e00\u526f\u56fe\u50cf\u627e\u5230\u7684\u89d2\u70b9\n\nMat R, T, E, F;                 //R \u65cb\u8f6c\u77e2\u91cf T\u5e73\u79fb\u77e2\u91cf E\u672c\u5f81\u77e9\u9635 F\u57fa\u7840\u77e9\u9635\nMat Rl, Rr, Pl, Pr, Q;          //\u6821\u6b63\u65cb\u8f6c\u77e9\u9635R\uff0c\u6295\u5f71\u77e9\u9635P \u91cd\u6295\u5f71\u77e9\u9635Q (\u4e0b\u9762\u6709\u5177\u4f53\u7684\u542b\u4e49\u89e3\u91ca\uff09\nMat mapLx, mapLy, mapRx, mapRy; //\u6620\u5c04\u8868\nRect validROIL, validROIR;      //\u56fe\u50cf\u6821\u6b63\u4e4b\u540e\uff0c\u4f1a\u5bf9\u56fe\u50cf\u8fdb\u884c\u88c1\u526a\uff0c\u8fd9\u91cc\u7684validROI\u5c31\u662f\u6307\u88c1\u526a\u4e4b\u540e\u7684\u533a\u57df\n\n//\u76f8\u673a\u5185\u53c2\u77e9\u9635\nMat cameraMatrixL;\nMat distCoeffL;\nMat cameraMatrixR;\nMat distCoeffR;\n\nMatrix34d PS[CAM_NUM_MAX];\nMatrix33d RS[CAM_NUM_MAX];\nVector3d TS[CAM_NUM_MAX];\n\nvector<vector<Point2f>> corners; //\u5404\u4e2a\u56fe\u50cf\u627e\u5230\u7684\u89d2\u70b9\u7684\u96c6\u5408 \u548cobjRealPoint \u4e00\u4e00\u5bf9\u5e94\nvector<float> vrms;\n\nCalibration::Calibration()\n{\n}\n\n/*\u8ba1\u7b97\u6807\u5b9a\u677f\u4e0a\u6a21\u5757\u7684\u5b9e\u9645\u7269\u7406\u5750\u6807*/\nstatic void calRealPoint(vector<vector<Point3f>> &obj, int boardwidth, int boardheight, int imgNumber, int squaresize)\n{\n    //  Mat imgpoint(boardheight, boardwidth, CV_32FC3,Scalar(0,0,0));\n    vector<Point3f> imgpoint;\n    for (int rowIndex = 0; rowIndex < boardheight; rowIndex++)\n    {\n        for (int colIndex = 0; colIndex < boardwidth; colIndex++)\n        {\n            imgpoint.push_back(Point3f(colIndex * squaresize, rowIndex * squaresize, 0));\n        }\n    }\n    for (int imgIndex = 0; imgIndex < imgNumber; imgIndex++)\n    {\n        obj.push_back(imgpoint);\n    }\n}\n\nQStringList Calibration::checkFile(QString path)\n{\n    char buff[100];\n    QString dirPath;\n    QStringList nameFilters;\n    nameFilters << \"*.png\";\n    QStringList files;\n    for (int i = 0; i < setting->camNumber; i++)\n    {\n        dirPath = path + \"/camera\" + QString::number(i);\n        if (EasyTool::isDirExist(dirPath) == false)\n        {\n            msg(\"calibr check not found \" + dirPath + \",exit\");\n            return files;\n        }\n        else\n        {\n            if (i == 0)\n            {\n                QDir dir(dirPath);\n                files = dir.entryList(nameFilters, QDir::Files | QDir::Readable, QDir::Name);\n                if (files.size() < 1)\n                {\n                    msg(\"calibr check error,files.size < 1,exit\");\n                }\n            }\n            else\n            {\n                for (int ii = 0; ii < files.size(); ii++)\n                {\n                    if (EasyTool::isFileExist(dirPath + \"/\" + files.at(ii)) == false)\n                    {\n                        msg(\"calibr check not found \" + dirPath + \"/\" + files.at(ii) + \",exit\");\n                        return files;\n                    }\n                }\n            }\n        }\n    }\n    return files;\n}\n\nvoid Calibration::calibrStart(QString path)\n{\n    int goodFrameCount = 0;\n    Mat imgL, boardimgL;\n    Mat imgR, boardimgR;\n    Matrix33d cameraMatrix;\n    Mat img;\n    Matrix43d PSTMP;\n    Matrix43d RTS43d;\n    double calibrateCameraError[setting->camNumber];\n\n    vector<QMap<uint8_t, vector<Point2f>>> camcorners;\n\n    //\u6307\u5b9a\u4e9a\u50cf\u7d20\u8ba1\u7b97\u8fed\u4ee3\u6807\u6ce8\n    cv::TermCriteria criteria = cv::TermCriteria(\n        cv::TermCriteria::MAX_ITER + cv::TermCriteria::EPS,\n        300, 0.01);\n\n    msg(\"Calibration Start\");\n\n    QStringList files = checkFile(path);\n    if (files.size() == 0)\n    {\n        goto exit;\n    }\n\n    for (int i = 0; i < setting->camNumber; i++)\n    {\n        QMap<uint8_t, vector<Point2f>> corners;\n        for (int ii = 0; ii < files.size(); ii++)\n        {\n            QString imgPath = path + \"/camera\" + QString::number(i) + \"/\" + files.at(ii);\n            if (EasyTool::isFileExist(imgPath) == false)\n            {\n                msg(\"calibr not not found \" + imgPath + \",exit\");\n                return;\n            }\n            img = imread(string((const char *)imgPath.toLocal8Bit()), IMREAD_GRAYSCALE);\n            if (img.data)\n            {\n                vector<Point2f> corner;\n                bool isFind = findChessboardCornersSB(img, boardSize, corner,\n                                                      CALIB_CB_NORMALIZE_IMAGE | CALIB_CB_EXHAUSTIVE | CALIB_CB_ACCURACY);\n\n                if (isFind)\n                {\n\n                    corners.insert(ii, corner);\n                    msg(\"findChessboardCorners \" + imgPath + \" success \" + QString::number(corner.size()));\n\n                    // if(i == 0)\n                    // {\n                    //     drawChessboardCorners(img, boardSize, corner, isFind);\n                    //     namedWindow(string((const char *)imgPath.toLocal8Bit()));\n                    //     imshow(string((const char *)imgPath.toLocal8Bit()), img);\n                    // }\n                }\n                else\n                {\n                    msg(\"findChessboardCorners \" + imgPath + \" fail\");\n                }\n            }\n        }\n        camcorners.push_back(corners);\n    }\n\n    msg(\"camcorners size \" + QString::number(camcorners.size()));\n\n    if (camcorners.size() != setting->camNumber)\n    {\n        return;\n    }\n\n    for (int i = 0; i < camcorners.size(); i++)\n    {\n        msg(\"corners \" + QString::number(i) + \" : \" + QString::number(camcorners.at(i).size()));\n    }\n\n    intrinsics.clear();\n    distortion_coeffs.clear();\n\n    for (int i = 0; i < camcorners.size(); i++)\n    {\n        goodFrameCount = camcorners.at(i).size();\n        /*\u8ba1\u7b97\u5b9e\u9645\u7684\u6821\u6b63\u70b9\u7684\u4e09\u7ef4\u5750\u6807*/\n        objRealPoint.clear();\n        calRealPoint(objRealPoint, boardWidth, boardHeight, goodFrameCount, squareSize);\n        corners.clear();\n        for (int ii = 0; ii < files.size(); ii++)\n        {\n            if (camcorners.at(i).contains(ii))\n            {\n                corners.push_back(camcorners.at(i).find(ii).value());\n            }\n        }\n        Mat intrinsic, distortion_coeff;\n        vector<Mat> rvecs; //\u65cb\u8f6c\u5411\u91cf\n        vector<Mat> tvecs; //\u5e73\u79fb\u5411\u91cf\n        Matrix33d cami;\n        Matrix<double, 1, 5> camk;\n\n        msg(\"calibrate camera\" + QString::number(i) + \" start..\");\n\n        calibrateCameraError[i] = calibrateCamera(objRealPoint, corners, imageSize, intrinsic, distortion_coeff, rvecs, tvecs);\n\n        cv2eigen(intrinsic, cami);\n        cv2eigen(distortion_coeff, camk);\n        //msg(\"corners size\" + QString::number(i) + \": \\r\\n\" + QString::number(corners.size()));\n        msg(\"intrinsic\" + QString::number(i) + \": \\r\\n\" + EasyTool::MatToString(cami));\n        msg(\"distortion_coeff\" + QString::number(i) + \": \\r\\n\" + EasyTool::MatToString(camk));\n        msg(\"cailbr : camera\" + QString::number(i) + \" error : \" + QString::number(calibrateCameraError[i]));\n\n        intrinsics.push_back(intrinsic);\n        distortion_coeffs.push_back(distortion_coeff);\n    }\n\n    vrms.clear();\n    for (int i = 0; i < camcorners.size() - 1; i++)\n    {\n        cornersL.clear();\n        cornersR.clear();\n        for (int ii = 0; ii < files.size(); ii++)\n        {\n            if (camcorners.at(0).contains(ii) && camcorners.at(i + 1).contains(ii))\n            {\n                cornersL.push_back(camcorners.at(0).find(ii).value());\n                cornersR.push_back(camcorners.at(i + 1).find(ii).value());\n            }\n        }\n\n        msg(\"cailbr : camera\" + QString::number(0) + \" to camera\" + QString::number(i + 1) + \" start..\");\n        goodFrameCount = cornersL.size();\n\n        /*\u8ba1\u7b97\u5b9e\u9645\u7684\u6821\u6b63\u70b9\u7684\u4e09\u7ef4\u5750\u6807*/\n        objRealPoint.clear();\n        calRealPoint(objRealPoint, boardWidth, boardHeight, goodFrameCount, squareSize);\n\n        QTime time;\n        time.start();\n\n        // calibrateCamera(objRealPoint, cornersL, Size(boardWidth, boardHeight), intrinsicL, distortion_coeffL, rvecsL, tvecsL, 0);\n        // calibrateCamera(objRealPoint, cornersR, Size(boardWidth, boardHeight), intrinsicR, distortion_coeffR, rvecsR, tvecsR, 0);\n\n        //\u6807\u5b9a\u6444\u50cf\u5934\n        float rms = stereoCalibrate(objRealPoint, cornersL, cornersR,\n                                    intrinsics.at(0), distortion_coeffs.at(0),\n                                    intrinsics.at(i + 1), distortion_coeffs.at(i + 1),\n                                    imageSize, R, T, E, F,\n                                    CALIB_FIX_INTRINSIC,\n                                    TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 1000, 1e-20));\n\n        // float rms = stereoCalibrate(objRealPoint, cornersL, cornersR,\n        //                             intrinsics.at(0), distortion_coeffs.at(0),\n        //                             intrinsics.at(i + 1), distortion_coeffs.at(i + 1),\n        //                             Size(imageWidth, imageHeight), R, T, E, F,\n        //                             0,\n        //                             TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 1000, 1e-20));\n\n        vrms.push_back(rms);\n\n        //\u7acb\u4f53\u6821\u6b63\u7684\u65f6\u5019\u9700\u8981\u4e24\u5e45\u56fe\u50cf\u5171\u9762\u5e76\u4e14\u884c\u5bf9\u51c6 \u4ee5\u4f7f\u5f97\u7acb\u4f53\u5339\u914d\u66f4\u52a0\u7684\u53ef\u9760\n        //\u4f7f\u5f97\u4e24\u5e45\u56fe\u50cf\u5171\u9762\u7684\u65b9\u6cd5\u5c31\u662f\u628a\u4e24\u4e2a\u6444\u50cf\u5934\u7684\u56fe\u50cf\u6295\u5f71\u5230\u4e00\u4e2a\u516c\u5171\u6210\u50cf\u9762\u4e0a\uff0c\u8fd9\u6837\u6bcf\u5e45\u56fe\u50cf\u4ece\u672c\u56fe\u50cf\u5e73\u9762\u6295\u5f71\u5230\u516c\u5171\u56fe\u50cf\u5e73\u9762\u90fd\u9700\u8981\u4e00\u4e2a\u65cb\u8f6c\u77e9\u9635R\n        //stereoRectify \u8fd9\u4e2a\u51fd\u6570\u8ba1\u7b97\u7684\u5c31\u662f\u4ece\u56fe\u50cf\u5e73\u9762\u6295\u5f71\u90fd\u516c\u5171\u6210\u50cf\u5e73\u9762\u7684\u65cb\u8f6c\u77e9\u9635Rl,Rr\u3002 Rl,Rr\u5373\u4e3a\u5de6\u53f3\u76f8\u673a\u5e73\u9762\u884c\u5bf9\u51c6\u7684\u6821\u6b63\u65cb\u8f6c\u77e9\u9635\u3002\n        //\u5de6\u76f8\u673a\u7ecf\u8fc7Rl\u65cb\u8f6c\uff0c\u53f3\u76f8\u673a\u7ecf\u8fc7Rr\u65cb\u8f6c\u4e4b\u540e\uff0c\u4e24\u5e45\u56fe\u50cf\u5c31\u5df2\u7ecf\u5171\u9762\u5e76\u4e14\u884c\u5bf9\u51c6\u4e86\u3002\n        //\u5176\u4e2dPl,Pr\u4e3a\u4e24\u4e2a\u76f8\u673a\u7684\u6295\u5f71\u77e9\u9635\uff0c\u5176\u4f5c\u7528\u662f\u5c063D\u70b9\u7684\u5750\u6807\u8f6c\u6362\u5230\u56fe\u50cf\u76842D\u70b9\u7684\u5750\u6807:P*[X Y Z 1]' =[x y w]\n        //Q\u77e9\u9635\u4e3a\u91cd\u6295\u5f71\u77e9\u9635\uff0c\u5373\u77e9\u9635Q\u53ef\u4ee5\u628a2\u7ef4\u5e73\u9762(\u56fe\u50cf\u5e73\u9762)\u4e0a\u7684\u70b9\u6295\u5f71\u52303\u7ef4\u7a7a\u95f4\u7684\u70b9:Q*[x y d 1] = [X Y Z W]\u3002\u5176\u4e2dd\u4e3a\u5de6\u53f3\u4e24\u5e45\u56fe\u50cf\u7684\u65f6\u5dee\n\n        // stereoRectify(\n        // intrinsics.at(0), distortion_coeffs.at(0),\n        // intrinsics.at(i + 1), distortion_coeffs.at(i + 1), imageSize, R, T, Rl, Rr, Pl, Pr, Q,\n        //               CALIB_ZERO_DISPARITY, -1, imageSize, &validROIL, &validROIR);\n\n        // cout << \"R: \" << R << endl;\n        // cout << \"T: \" << T << endl;\n        // cout << \"Pl: \" << Pl << endl;\n        // cout << \"Pr: \" << Pr << endl;\n        // cout << \"intrinsics: \" << intrinsics.at(i) << endl;\n        // cout << \"distortion_coeffs: \" << distortion_coeffs.at(i) << endl;\n\n        if (i == 0)\n        {\n            RS[0] << 1, 0, 0,\n                0, 1, 0,\n                0, 0, 1;\n            TS[0] << (double)0.0, (double)0.0, (double)0.0;\n            RS[0].transposeInPlace();\n            RTS43d = EasyTool::getRT43d(RS[0], TS[0]);\n            cv2eigen(intrinsics.at(0), cameraMatrix);\n            PS[0] = (RTS43d * cameraMatrix.transpose()).transpose();\n        }\n\n        cv2eigen(R, RS[i + 1]);\n        cv2eigen(T, TS[i + 1]);\n        RS[i + 1].transposeInPlace();\n\n        RTS43d = EasyTool::getRT43d(RS[i + 1], TS[i + 1]);\n        cv2eigen(intrinsics.at(i + 1), cameraMatrix);\n        PS[i + 1] = (RTS43d * cameraMatrix.transpose()).transpose();\n\n        if (i == 0)\n        {\n            vision_param.R[i] << RS[i];\n            vision_param.T[i] << TS[i];\n            vision_param.P[i] << PS[i];\n            vision_param.ERR[i] = calibrateCameraError[i];\n            cv2eigen(intrinsics.at(i), vision_param.I[i]);\n            cv2eigen(distortion_coeffs.at(i), vision_param.K[i]);\n            \n            msg(\"I\" + QString::number(i) + \": \\r\\n\" + EasyTool::MatToString(vision_param.I[i]));\n            msg(\"K\" + QString::number(i) + \": \\r\\n\" + EasyTool::MatToString(vision_param.K[i]));\n            msg(\"P\" + QString::number(i) + \": \\r\\n\" + EasyTool::MatToString(vision_param.P[i]));\n            msg(\"R\" + QString::number(i) + \": \\r\\n\" + EasyTool::MatToString(vision_param.R[i]));\n            msg(\"T\" + QString::number(i) + \": \\r\\n\" + EasyTool::MatToString(vision_param.T[i]));\n\n            // cout << std::setprecision(16) << \"P\" << i << \": \" << vision_param.P[i] << endl;\n            // cout << std::setprecision(16) << \"R\" << i << \": \" << vision_param.R[i] << endl;\n            // cout << std::setprecision(16) << \"T\" << i << \": \" << vision_param.T[i] << endl;\n        }\n\n        vision_param.R[i + 1] << RS[i + 1];\n        vision_param.T[i + 1] << TS[i + 1];\n        vision_param.P[i + 1] << PS[i + 1];\n        vision_param.ERR[i + 1] = calibrateCameraError[i + 1];\n        cv2eigen(intrinsics.at(i + 1), vision_param.I[i + 1]);\n        cv2eigen(distortion_coeffs.at(i + 1), vision_param.K[i + 1]);\n\n        msg(\"I\" + QString::number(i + 1) + \": \\r\\n\" + EasyTool::MatToString(vision_param.I[i + 1]));\n        msg(\"K\" + QString::number(i + 1) + \": \\r\\n\" + EasyTool::MatToString(vision_param.K[i + 1]));\n        msg(\"P\" + QString::number(i + 1) + \": \\r\\n\" + EasyTool::MatToString(vision_param.P[i + 1]));\n        msg(\"R\" + QString::number(i + 1) + \": \\r\\n\" + EasyTool::MatToString(vision_param.R[i + 1]));\n        msg(\"T\" + QString::number(i + 1) + \": \\r\\n\" + EasyTool::MatToString(vision_param.T[i + 1]));\n\n        // cout << std::setprecision(16) << \"P\" << i + 1 << \": \" << vision_param.P[i + 1] << endl;\n        // cout << std::setprecision(16) << \"R\" << i + 1 << \": \" << vision_param.R[i + 1] << endl;\n        // cout << std::setprecision(16) << \"T\" << i + 1 << \": \" << vision_param.T[i + 1] << endl;\n\n        vision_param.RMS[i] = vrms.at(i);\n\n        msg(\"take time \" + QString::number(time.elapsed() / 1000.0) + \"s\");\n        msg(\"Stereo Calibration done with RMS error = \" + QString::number(rms, 'f', 6));\n    }\n\n    for (int i = 0; i < camcorners.size() - 1; i++)\n    {\n        msg(QString::number(0) + \" to \" + QString::number(i + 1) + \" rms error = \" + QString::number(vrms.at(i), 'f', 6));\n    }\n\nexit:\n    msg(\"Calibration Exit\");\n}\n\nvoid Calibration::msg(QString msg)\n{\n    mlog->show(msg);\n    emit logSignal(msg);\n}\n", "meta": {"hexsha": "0227a0495fcce4f4c13641d2896957f1d745eb3b", "size": 14308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/calibration/Calibration.cpp", "max_stars_repo_name": "guanglun/GLMocap", "max_stars_repo_head_hexsha": "7c690a4ff5bf51ed263d587bbb6fa96445c8a845", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-10-30T05:01:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T18:04:08.000Z", "max_issues_repo_path": "src/calibration/Calibration.cpp", "max_issues_repo_name": "guanglun/GLMocap", "max_issues_repo_head_hexsha": "7c690a4ff5bf51ed263d587bbb6fa96445c8a845", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calibration/Calibration.cpp", "max_forks_repo_name": "guanglun/GLMocap", "max_forks_repo_head_hexsha": "7c690a4ff5bf51ed263d587bbb6fa96445c8a845", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-10-09T08:47:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T07:45:33.000Z", "avg_line_length": 37.2604166667, "max_line_length": 132, "alphanum_fraction": 0.5411657814, "num_tokens": 4409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5234645059255465}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/cond.hpp\n *\n * \\brief Matrix condition number with respect to inversion.\n *\n * The condition number of a function, with respect to an argument, measures\n * the asymptotically worst case of how much the function can change in\n * proportion to small changes in the argument.\n * The \"function\" is the solution of a problem and the \"arguments\" are the data\n * in the problem.\n * A problem with a low condition number is said to be\n * <em>well-conditioned</em>, while a problem with a high condition number is\n * said to be <em>ill-conditioned</em>.\n * As a general rule of thumb, if the condition number \\f$\\kappa(A) = 10k\\f$,\n * then you lose \\f$k\\f$ digits of accuracy on top of what would be lost to the\n * numerical method due to loss of precision from arithmetic methods.\n *\n * The condition number of a matrix measures the sensitivity of the solution of\n * a system of linear equations to errors in the data.\n * It gives an indication of the accuracy of the results from matrix inversion\n * and the linear equation solution.\n * Condition numbers near 1 indicate a well-conditioned matrix.\n * Mathematically, the condition number of a matrix \\f$A\\f$, with respect to a\n * given matrix p-norm, is defined as:\n * \\f{equation}\n *  \\kappa(A) = \\begin{cases}\n *  \t\t\t \\|A\\|_p \\|A^{-1}\\|_p & A \\text{ is not singular},\\\\\n *  \t\t\t +\\infty, & A \\text{ is singular}\n *  \t\t\t\\end{cases}\n * \\f}\n *\n * <hr/>\n *\n * Copyright (c) 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_COND_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_COND_HPP\n\n\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/fwd.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/operation/any.hpp>\n#include <boost/numeric/ublasx/operation/inv.hpp>\n#include <boost/numeric/ublasx/operation/max.hpp>\n#include <boost/numeric/ublasx/operation/min.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/svd.hpp>\n#include <functional>\n#include <limits>\n#include <stdexcept>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\nnamespace detail { namespace /*<unnamed>*/ {\n\nenum norm_categories\n{\n\tnorm_inf_category = -1,\n\tnorm_frobenius_category = 0,\n\tnorm_1_category = 1,\n\tnorm_2_category = 2\n};\n\n\ntemplate <int Norm, typename MatrixExprT>\ntypename type_traits<typename matrix_traits<MatrixExprT>::value_type>::real_type cond_impl(matrix_expression<MatrixExprT> const& A)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\ttypedef typename type_traits<value_type>::real_type real_type;\n\n\t// pre: A is square OR (A is rectangular AND norm is 2)\n\tif (num_rows(A) != num_columns(A) && Norm != norm_2_category)\n\t{\n\t\tthrow ::std::invalid_argument(\"[boost::numeric::ublasx::detail::cond_impl] For rectangular matrices use the 2 norm.\");\n\t}\n\n\treal_type c;\n\n\tswitch (Norm)\n\t{\n\t\tcase norm_frobenius_category: // Frobenius norm\n\t\t\ttry\n\t\t\t{\n\t\t\t\tc = norm_frobenius(A)*norm_frobenius(inv(A));\n\t\t\t}\n\t\t\tcatch (...)\n\t\t\t{\n\t\t\t\tc = ::std::numeric_limits<real_type>::infinity();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase norm_inf_category: // Infinity norm\n\t\t\ttry\n\t\t\t{\n\t\t\t\tc = norm_inf(A)*norm_inf(inv(A));\n\t\t\t}\n\t\t\tcatch (...)\n\t\t\t{\n\t\t\t\tc = ::std::numeric_limits<real_type>::infinity();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase norm_1_category: // 1-norm\n\t\t\ttry\n\t\t\t{\n\t\t\t\tc = norm_1(A)*norm_1(inv(A));\n\t\t\t}\n\t\t\tcatch (...)\n\t\t\t{\n\t\t\t\tc = ::std::numeric_limits<real_type>::infinity();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase norm_2_category: // 2-norm\n\t\t\t{\n\t\t\t\tvector<real_type> s = svd_values(A);\n\t\t\t\tif (any(s, ::std::bind2nd(::std::equal_to<real_type>(), 0)))\n\t\t\t\t{\n\t\t\t\t\t// Singular matrix\n\t\t\t\t\tc = ::std::numeric_limits<real_type>::infinity();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tc = max(s)/min(s);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t}\n\n\treturn c;\n}\n\n}} // Namespace detail::<unnamed>\n\n\n/**\n * \\brief The 1-norm matrix condition number with respect to inversion.\n *\n * \\tparam MatrixExprT The matrix expression type.\n * \\param A The input matrix expression.\n * \\return The 1-norm condition number if \\a A is not singular; otherwise,\n *  \\f$+\\infty\\f$.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename type_traits<typename matrix_traits<MatrixExprT>::value_type>::real_type cond_1(matrix_expression<MatrixExprT> const& A)\n{\n\treturn detail::cond_impl<detail::norm_1_category>(A);\n}\n\n\n/**\n * \\brief The 2-norm matrix condition number with respect to inversion.\n *\n * \\tparam MatrixExprT The matrix expression type.\n * \\param A The input matrix expression.\n * \\return The 2-norm condition number if \\a A is not singular; otherwise,\n *  \\f$+\\infty\\f$.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename type_traits<typename matrix_traits<MatrixExprT>::value_type>::real_type cond_2(matrix_expression<MatrixExprT> const& A)\n{\n\treturn detail::cond_impl<detail::norm_2_category>(A);\n}\n\n\n/**\n * \\brief The infinity norm matrix condition number with respect to inversion.\n *\n * \\tparam MatrixExprT The matrix expression type.\n * \\param A The input matrix expression.\n * \\return The infinity norm condition number if \\a A is not singular;\n *  otherwise, \\f$+\\infty\\f$.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename type_traits<typename matrix_traits<MatrixExprT>::value_type>::real_type cond_inf(matrix_expression<MatrixExprT> const& A)\n{\n\treturn detail::cond_impl<detail::norm_inf_category>(A);\n}\n\n\n/**\n * \\brief The Frobenius norm matrix condition number with respect to inversion.\n *\n * \\tparam MatrixExprT The matrix expression type.\n * \\param A The input matrix expression.\n * \\return The Frobenius norm condition number if \\a A is not singular;\n *  otherwise, \\f$+\\infty\\f$.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename type_traits<typename matrix_traits<MatrixExprT>::value_type>::real_type cond_frobenius(matrix_expression<MatrixExprT> const& A)\n{\n\treturn detail::cond_impl<detail::norm_frobenius_category>(A);\n}\n\n\n/**\n * \\brief The 2-norm matrix condition number with respect to inversion.\n *\n * \\tparam MatrixExprT The matrix expression type.\n * \\param A The input matrix expression.\n * \\return The 2-norm condition number if \\a A is not singular; otherwise,\n *  \\f$+\\infty\\f$.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename type_traits<typename matrix_traits<MatrixExprT>::value_type>::real_type cond(matrix_expression<MatrixExprT> const& A)\n{\n\treturn detail::cond_impl<detail::norm_2_category>(A);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_COND_HPP\n", "meta": {"hexsha": "791ed2ddec218f6525149fc17e8f631cd4e06d1f", "size": 7154, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/cond.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/cond.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/cond.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": 29.8083333333, "max_line_length": 136, "alphanum_fraction": 0.7235113223, "num_tokens": 1934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5234644959244676}}
{"text": "/**\n * @file cv_test.cpp\n *\n * Unit tests for the cross-validation module.\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\n#include <type_traits>\n\n#include <mlpack/core/cv/meta_info_extractor.hpp>\n#include <mlpack/core/cv/metrics/accuracy.hpp>\n#include <mlpack/core/cv/metrics/mse.hpp>\n#include <mlpack/core/optimizers/rmsprop/rmsprop.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/init_rules/zero_init.hpp>\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/decision_tree/decision_tree.hpp>\n#include <mlpack/methods/hoeffding_trees/hoeffding_tree.hpp>\n#include <mlpack/methods/lars/lars.hpp>\n#include <mlpack/methods/linear_regression/linear_regression.hpp>\n#include <mlpack/methods/logistic_regression/logistic_regression.hpp>\n#include <mlpack/methods/softmax_regression/softmax_regression.hpp>\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace mlpack::ann;\nusing namespace mlpack::cv;\nusing namespace mlpack::optimization;\nusing namespace mlpack::regression;\nusing namespace mlpack::tree;\n\nBOOST_AUTO_TEST_SUITE(CVTest);\n\n/*\n * Test the accuracy metric.\n */\nBOOST_AUTO_TEST_CASE(AccuracyTest)\n{\n  // Making linearly separable data.\n  arma::mat data =\n    arma::mat(\"1 0; 2 0; 3 0; 4 0; 5 0; 1 1; 2 1; 3 1; 4 1; 5 1\").t();\n  arma::Row<size_t> trainingLabels(\"0 0 0 0 0 1 1 1 1 1\");\n\n  LogisticRegression<> lr(data, trainingLabels);\n\n  arma::Row<size_t> labels(\"0 0 1 0 0 1 0 1 0 1\"); // 70%-correct labels\n\n  BOOST_REQUIRE_CLOSE(Accuracy::Evaluate(lr, data, labels), 0.7, 1e-5);\n}\n\n/*\n * Test the mean squared error.\n */\nBOOST_AUTO_TEST_CASE(MSETest)\n{\n  // Making two points that define the linear function f(x) = x - 1\n  arma::mat trainingData(\"0 1\");\n  arma::rowvec trainingResponses(\"-1 0\");\n\n  LinearRegression lr(trainingData, trainingResponses);\n\n  // Making three responses that differ from the correct ones by 0, 1, and 2\n  // respectively\n  arma::mat data(\"2 3 4\");\n  arma::rowvec responses(\"1 3 5\");\n\n  double expectedMSE = (0 * 0 + 1 * 1 + 2 * 2) / 3.0;\n\n  BOOST_REQUIRE_CLOSE(MSE::Evaluate(lr, data, responses), expectedMSE, 1e-5);\n}\n\n/*\n * Test the mean squared error with matrix responses.\n */\nBOOST_AUTO_TEST_CASE(MSEMatResponsesTest)\n{\n  arma::mat data(\"1 2\");\n  arma::mat trainingResponses(\"1 2; 3 4\");\n\n  FFN<MeanSquaredError<>, ZeroInitialization> ffn;\n  ffn.Add<Linear<>>(1, 2);\n  ffn.Add<IdentityLayer<>>();\n\n  RMSProp opt(0.2);\n  opt.Shuffle() = false;\n  ffn.Train(data, trainingResponses, opt);\n\n  // Making four responses that differ from the correct ones by 0, 1, 2 and 3\n  // respectively\n  arma::mat responses(\"1 3; 5 7\");\n\n  double expectedMSE = (0 * 0 + 1 * 1 + 2 * 2 + 3 * 3) / 4.0;\n\n  BOOST_REQUIRE_CLOSE(MSE::Evaluate(ffn, data, responses), expectedMSE, 1e-1);\n}\n\ntemplate<typename Class,\n         typename ExpectedPT,\n         typename PassedMT = arma::mat,\n         typename PassedPT = arma::Row<size_t>>\nvoid CheckPredictionsType()\n{\n  using Extractor = MetaInfoExtractor<Class, PassedMT, PassedPT>;\n  using ActualPT = typename Extractor::PredictionsType;\n  static_assert(std::is_same<ExpectedPT, ActualPT>::value,\n      \"Should be the same\");\n}\n\nBOOST_AUTO_TEST_CASE(PredictionsTypeTest)\n{\n  CheckPredictionsType<LinearRegression, arma::rowvec>();\n  // CheckPredictionsType<FFN<>, arma::mat>();\n\n  CheckPredictionsType<LogisticRegression<>, arma::Row<size_t>>();\n  CheckPredictionsType<SoftmaxRegression, arma::Row<size_t>>();\n  CheckPredictionsType<HoeffdingTree<>, arma::Row<size_t>, arma::mat>();\n  CheckPredictionsType<HoeffdingTree<>, arma::Row<size_t>, arma::imat>();\n  CheckPredictionsType<DecisionTree<>, arma::Row<size_t>, arma::mat,\n      arma::Row<size_t>>();\n  CheckPredictionsType<DecisionTree<>, arma::Row<char>, arma::mat,\n      arma::Row<char>>();\n}\n\ntemplate<typename Class,\n         typename ExpectedWT,\n         typename PassedMT = arma::mat,\n         typename PassedPT = arma::Row<size_t>,\n         typename PassedWT = arma::rowvec>\nvoid CheckWeightsType()\n{\n  using Extractor = MetaInfoExtractor<Class, PassedMT, PassedPT, PassedWT>;\n  using ActualWT = typename Extractor::WeightsType;\n  static_assert(std::is_same<ExpectedWT, ActualWT>::value,\n      \"Should be the same\");\n}\n\nBOOST_AUTO_TEST_CASE(WeightsTypeTest)\n{\n  CheckWeightsType<LinearRegression, arma::rowvec>();\n  CheckWeightsType<DecisionTree<>, arma::rowvec>();\n  CheckWeightsType<DecisionTree<>, arma::Row<float>, arma::mat,\n      arma::Row<size_t>, arma::Row<float>>();\n\n  CheckWeightsType<FFN<>, void>();\n  CheckWeightsType<LARS, void>();\n  CheckWeightsType<LogisticRegression<>, void>();\n}\n\nBOOST_AUTO_TEST_CASE(TakesDatasetInfoTest)\n{\n  static_assert(MetaInfoExtractor<DecisionTree<>>::TakesDatasetInfo,\n      \"Value should be true\");\n  static_assert(!MetaInfoExtractor<LinearRegression>::TakesDatasetInfo,\n      \"Value should be false\");\n  static_assert(!MetaInfoExtractor<SoftmaxRegression>::TakesDatasetInfo,\n      \"Value should be false\");\n}\n\nBOOST_AUTO_TEST_CASE(TakesNumClassesTest)\n{\n  static_assert(MetaInfoExtractor<DecisionTree<>>::TakesNumClasses,\n      \"Value should be true\");\n  static_assert(MetaInfoExtractor<SoftmaxRegression>::TakesNumClasses,\n      \"Value should be true\");\n  static_assert(!MetaInfoExtractor<LinearRegression>::TakesNumClasses,\n      \"Value should be false\");\n  static_assert(!MetaInfoExtractor<LARS>::TakesNumClasses,\n      \"Value should be false\");\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "a138059d3ddc472ec4957239bcd93b31d24163da", "size": 5639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/cv_test.cpp", "max_stars_repo_name": "17minutes/mlpack", "max_stars_repo_head_hexsha": "8f4af1ec454a662dd7c990cf2146bfeb1bd0cb3a", "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": "2021-09-22T18:12:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:39:58.000Z", "max_issues_repo_path": "src/mlpack/tests/cv_test.cpp", "max_issues_repo_name": "kosmaz/Mlpack", "max_issues_repo_head_hexsha": "62100ddca45880a57e7abb0432df72d285e5728b", "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/cv_test.cpp", "max_forks_repo_name": "kosmaz/Mlpack", "max_forks_repo_head_hexsha": "62100ddca45880a57e7abb0432df72d285e5728b", "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.0397727273, "max_line_length": 78, "alphanum_fraction": 0.7224685228, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6477982179521105, "lm_q1q2_score": 0.5234644949365287}}
{"text": "#pragma once\n\n#include <polyfem/Common.hpp>\n\n#include <polyfem/ElementAssemblyValues.hpp>\n#include <polyfem/ElementBases.hpp>\n\n#include <polyfem/AutodiffTypes.hpp>\n\n#include <Eigen/Dense>\n#include <functional>\n\n\nnamespace polyfem\n{\n\tclass LinearElasticity\n\t{\n\tpublic:\n\t\t// res is R^{dim\u00b2}\n\t\tEigen::Matrix<double, Eigen::Dynamic, 1, 0, 9, 1>\n\t\tassemble(const ElementAssemblyValues &vals, const int i, const int j, const QuadratureVector &da) const;\n\n\t\tEigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1>\n\t\tcompute_rhs(const AutodiffHessianPt &pt) const;\n\n\t\tvoid compute_von_mises_stresses(const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &stresses) const;\n\t\tvoid compute_stress_tensor(const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &tensor) const;\n\n\t\tinline int &size() { return size_; }\n\t\tinline int size() const { return size_; }\n\n\t\tinline double &mu() { return mu_; }\n\t\tinline double mu() const { return mu_; }\n\n\t\tinline double &lambda() { return lambda_; }\n\t\tinline double lambda() const { return lambda_; }\n\n\t\tvoid set_parameters(const json &params);\n\tprivate:\n\t\tint size_ = 2;\n\t\tdouble mu_ = 1;\n\t\tdouble lambda_ = 1;\n\n\t\tvoid assign_stress_tensor(const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, const int all_size, Eigen::MatrixXd &all, const std::function<Eigen::MatrixXd(const Eigen::MatrixXd &)> &fun) const;\n\t};\n}\n", "meta": {"hexsha": "11ec030f1064f30d8a1214b8239af56be26612d9", "size": 1568, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/assembler/LinearElasticity.hpp", "max_stars_repo_name": "ldXiao/polyfem", "max_stars_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/assembler/LinearElasticity.hpp", "max_issues_repo_name": "ldXiao/polyfem", "max_issues_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/assembler/LinearElasticity.hpp", "max_forks_repo_name": "ldXiao/polyfem", "max_forks_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_forks_repo_licenses": ["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.3617021277, "max_line_length": 264, "alphanum_fraction": 0.7366071429, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5234644949365286}}
{"text": "#include \"fitline.h\"\n#include \"ransac.h\"\n#include <cstdlib>\n#include <cstdio>\n#include <ctime>\n#include <sstream>\n#include <fstream>\n#include <string>\n#include <iostream>\n\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#define PI (3.1415926535897932346f)\n\nint main()\n{\n    // Read calibration data\n    double id, score, x, y, z, roll, yaw, pitch;\n    double  x_0, y_0, z_0, roll_0, yaw_0, pitch_0;\n\n    ifstream calib_FileA(\"../data/calib_data.txt\");\n    int filecount = 0;\n    while (!calib_FileA.eof())\n    {\n        calib_FileA >> id >> score >> x >> y >> z >> roll >> pitch >> yaw;\n        filecount++;\n    }\n    calib_FileA.close();\n\n    cout << \"Read \" << filecount << \" data\" << endl;\n\n    ifstream calib_File(\"../data/calib_data.txt\");\n    int count = 0;\n\n    Point2D32f points_x[filecount];\n    Point2D32f points_y[filecount];\n    Point2D32f points_z[filecount];\n\n    Point2D32f points_roll[filecount];\n    Point2D32f points_pitch[filecount];\n    Point2D32f points_yaw[filecount];\n\n    while (!calib_File.eof())\n    {\n        calib_File >> id >> score >> x >> y >> z >> roll >> pitch >> yaw;\n\n        points_x[count].x = id;\n        points_x[count].y = x;\n\n        points_y[count].x = id;\n        points_y[count].y = y;\n\n        points_z[count].x = id;\n        points_z[count].y = z;\n\n        points_roll[count].x = id;\n        points_roll[count].y = roll;\n\n        points_pitch[count].x = id;\n        points_pitch[count].y = pitch;\n\n        points_yaw[count].x = id;\n        points_yaw[count].y = yaw;\n\n        x_0+=x;\n        y_0+=y;\n        z_0+=z;\n        roll_0+=roll;\n        pitch_0+=pitch;\n        yaw_0+=yaw;\n\n        count++;\n    }\n\n    x_0=x_0/filecount;\n    y_0=y_0/filecount;\n    z_0=z_0/filecount;\n    roll_0=roll_0/filecount;\n    pitch_0=pitch_0/filecount;\n    yaw_0=yaw_0/filecount;\n\n     /*   float lines[4] = {0.0}; //line parameters\n    int numForEstimate = 5;\n    float successProbability = 0.9999f;\n    float maxOutliersPercentage = 0.9; //(float)outlierCnt/COUNT; 0.9\n    float a, b;\n\n    Ransac(points_x, filecount, lines, numForEstimate, successProbability, maxOutliersPercentage);\n    a = lines[1] / lines[0];\n    b = lines[3] - a * lines[2];\n    printf(\"x ransac fit(including outliers): a: %f  x: %f\\n\", a, b);\n    x = b;\n\n    Ransac(points_y, filecount, lines, numForEstimate, successProbability, maxOutliersPercentage);\n    a = lines[1] / lines[0];\n    b = lines[3] - a * lines[2];\n    printf(\"y ransac fit(including outliers): a: %f  y: %f\\n\", a, b);\n    y = b;\n\n    Ransac(points_z, filecount, lines, numForEstimate, successProbability, maxOutliersPercentage);\n    a = lines[1] / lines[0];\n    b = lines[3] - a * lines[2];\n    printf(\"z ransac fit(including outliers): a: %f  z: %f\\n\", a, b);\n    z = b;\n\n    Ransac(points_roll, filecount, lines, numForEstimate, successProbability, maxOutliersPercentage);\n    a = lines[1] / lines[0];\n    b = lines[3] - a * lines[2];\n    printf(\"roll ransac fit(including outliers): a: %f  roll: %f\\n\", a, b);\n    roll = b;\n\n    Ransac(points_pitch, filecount, lines, numForEstimate, successProbability, maxOutliersPercentage);\n    a = lines[1] / lines[0];\n    b = lines[3] - a * lines[2];\n    printf(\"pitch ransac fit(including outliers): a: %f  pitch: %f\\n\", a, b);\n    pitch = b;\n\n    Ransac(points_yaw, filecount, lines, numForEstimate, successProbability, maxOutliersPercentage);\n    a = lines[1] / lines[0];\n    b = lines[3] - a * lines[2];\n    printf(\"yaw ransac fit(including outliers): a: %f  yaw: %f\\n\", a, b);\n    yaw = b;\n    */\n\n    calib_File.close();\n    cout << endl;\n    cout << \"RANSAC Result (x,y,z,roll,pitch,yaw): \" << x << \", \" << y << \", \" << z << \", \" << roll << \", \" << pitch << \", \" << yaw << endl;\n    Eigen::Matrix<double, 3, 1> T;\n\n    //EulerAngles to RotationMatrix\n    ::Eigen::Vector3d ea0(yaw, pitch, roll);\n    ::Eigen::Matrix3d R;\n    R = ::Eigen::AngleAxisd(ea0[0], ::Eigen::Vector3d::UnitZ()) * ::Eigen::AngleAxisd(ea0[1], ::Eigen::Vector3d::UnitY()) * ::Eigen::AngleAxisd(ea0[2], ::Eigen::Vector3d::UnitX());\n\n    // cout << R << endl << endl;\n    T << x, y, z;\n    Eigen::Matrix4d tf = Eigen::Matrix4d::Identity();\n    tf.block(0, 0, 3, 3) = R;\n    tf.block(0, 3, 3, 1) = T;\n\n    cout << \"----------------------------------\" << endl;\n    cout << \"Result Matrix:\" << endl;\n    cout << tf << endl;\n    return 0;\n}\n", "meta": {"hexsha": "44f9b03566ca252a3e1e4c346f8fd541aed62a47", "size": 4350, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ransac/main.cpp", "max_stars_repo_name": "lhypds/livox-auto-calibration-dev", "max_stars_repo_head_hexsha": "e39461ac56d6f35c8c90d1a52fe017719bf89bad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-08-15T15:55:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T00:29:25.000Z", "max_issues_repo_path": "src/ransac/main.cpp", "max_issues_repo_name": "lhypds/livox-auto-calibration-dev", "max_issues_repo_head_hexsha": "e39461ac56d6f35c8c90d1a52fe017719bf89bad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ransac/main.cpp", "max_forks_repo_name": "lhypds/livox-auto-calibration-dev", "max_forks_repo_head_hexsha": "e39461ac56d6f35c8c90d1a52fe017719bf89bad", "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.3918918919, "max_line_length": 180, "alphanum_fraction": 0.583908046, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245618, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5234526258767783}}
{"text": "#include <vector>\n#include \"aabb.h\"\n#include <iostream>\n#include \"model.h\"\n#include <Eigen/Core>\nusing namespace std;\nusing namespace Eigen;\n\n\n\n\nint main(int argc, char** argv){\n  const string filename = argv[1];\n  Scene scene(filename.c_str());\n\n  for(auto& model_ptr : scene.models){\n    size_t num_tris = model_ptr->tris_.size();\n    vector<tri_aabb> aabbs(num_tris);\n\n    #pragma omp parallel for\n    for(size_t i = 0; i < num_tris; ++i){\n      aabbs[i] = tri_aabb(model_ptr->tris_[i]->id_, model_ptr->tris_[i]->p_.col(0),model_ptr->tris_[i]->p_.col(1), model_ptr->tris_[i]->p_.col(2));\n    }\n    #pragma omp parallel for    \n    for(size_t i = 0; i < num_tris; ++i){\n      for(size_t j = 0; j < 3; ++j){\n        for(size_t k = 0; k < 3; ++k){\n          assert(model_ptr->tris_[i]->p_(k, j) <= aabbs[i].up_bd_(k) &&\n                 model_ptr->tris_[i]->p_(k, j) >= aabbs[i].low_bd_(k));\n        }\n      }\n    }\n  }\n  cout <<\"pass\" << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "b918f8ce8e128ae00cef6d42e2a10643c4830dad", "size": 960, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/test/test_aabb.cc", "max_stars_repo_name": "Chongyao/Monte-Carlo-Ray-Tracing", "max_stars_repo_head_hexsha": "d175300f089a4ed61c9548e5a2587e63cd843403", "max_stars_repo_licenses": ["MIT"], "max_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_aabb.cc", "max_issues_repo_name": "Chongyao/Monte-Carlo-Ray-Tracing", "max_issues_repo_head_hexsha": "d175300f089a4ed61c9548e5a2587e63cd843403", "max_issues_repo_licenses": ["MIT"], "max_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_aabb.cc", "max_forks_repo_name": "Chongyao/Monte-Carlo-Ray-Tracing", "max_forks_repo_head_hexsha": "d175300f089a4ed61c9548e5a2587e63cd843403", "max_forks_repo_licenses": ["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.2631578947, "max_line_length": 147, "alphanum_fraction": 0.578125, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5234360487049063}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TOOLBOX_EXPONENTIAL_CONSTANTS_EXP_1_HPP_INCLUDED\n#define NT2_TOOLBOX_EXPONENTIAL_CONSTANTS_EXP_1_HPP_INCLUDED\n/*!\n * \\file\n**/\n#include <boost/simd/sdk/constant/constant.hpp>\n#include <boost/simd/sdk/constant/register.hpp>\n\n/*!\n * \\ingroup expon_constant\n * \\defgroup expon_constant_exp_1 Exp_1\n *\n * \\par Description\n * Constant exp_1 : \\f$e = \\exp(1)\\f$ constant.\n * \\par\n * The value of this constant is type dependant. This means that for different\n * types it does not represent the same mathematical number.\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/exp_1.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class T,class A0>\n *     meta::call<tag::exp_1_(A0)>::type\n *     exp_1();\n * }\n * \\endcode\n *\n *\n * \\param T template parameter of Exp_1\n *\n * \\return type T value\n *\n *\n**/\n\nnamespace nt2\n{\n  namespace tag\n  {\n    BOOST_SIMD_CONSTANT_REGISTER( Exp_1, double\n                                , 2, 0x402df854\n                                , 0x4005bf0a8b145769LL\n                                );\n  }\n\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Exp_1, Exp_1);\n}\n\n#endif\n", "meta": {"hexsha": "33d7059d4af3d3f029ef339cff94c63d0e04ed64", "size": 1673, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/toolbox/exponential/constants/exp_1.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/exponential/include/nt2/toolbox/exponential/constants/exp_1.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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": "modules/core/exponential/include/nt2/toolbox/exponential/constants/exp_1.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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.9701492537, "max_line_length": 80, "alphanum_fraction": 0.5666467424, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5234360366141386}}
{"text": "/******************************************************************************\n * Author:   Laurent Kneip                                                    *\n * Contact:  kneip.laurent@gmail.com                                          *\n * License:  Copyright (c) 2013 Laurent Kneip, ANU. 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 * * 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 ANU nor the names of its contributors may be         *\n *   used to endorse or promote products derived from this software without   *\n *   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 ANU OR THE 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         *\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 * \\file Sturm.hpp\n * \\brief Class for evaluating Sturm chains on polynomials, and bracketing the\n *        real roots.\n */\n\n#ifndef OPENGV_STURM_HPP_\n#define OPENGV_STURM_HPP_\n\n#include <memory>\n#include <stdlib.h>\n#include <vector>\n#include <list>\n#include <Eigen/Eigen>\n#include <Eigen/src/Core/util/DisableStupidWarnings.h>\n\n/**\n * \\brief The namespace of this library.\n */\nnamespace opengv\n{\n/**\n * \\brief The namespace of the math tools.\n */\nnamespace math\n{\n\nclass Bracket\n{\npublic:\n  typedef std::shared_ptr<Bracket> Ptr;\n  typedef std::shared_ptr<const Bracket> ConstPtr;\n\n  Bracket( double lowerBound, double upperBound );\n  Bracket( double lowerBound, double upperBound, size_t changes, bool setUpperBoundChanges );\n  virtual ~Bracket();\n\n  bool dividable( double eps ) const;\n  void divide( std::list<Ptr> & brackets ) const;\n  double lowerBound() const;\n  double upperBound() const;\n  bool lowerBoundChangesComputed() const;\n  bool upperBoundChangesComputed() const;\n  void setLowerBoundChanges( size_t changes );\n  void setUpperBoundChanges( size_t changes );\n  size_t numberRoots() const;\n\nprivate:\n  double _lowerBound;\n  double _upperBound;\n  bool _lowerBoundChangesComputed;\n  bool _upperBoundChangesComputed;\n  size_t _lowerBoundChanges;\n  size_t _upperBoundChanges;\n};\n\n/**\n * Sturm is initialized over polynomials of arbitrary order, and used to compute\n * the real roots of the polynomial.\n */\nclass Sturm\n{\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  /** A pair of values bracketing a real root */\n  typedef std::pair<double,double> bracket_t;\n\n  /**\n   * \\brief Contructor.\n   * \\param[in] p The polynomial coefficients (poly = p(0,0)*x^n + p(0,1)*x^(n-1) ...).\n   */\n  Sturm( const Eigen::MatrixXd & p );\n  /**\n   * \\brief Contructor.\n   * \\param[in] p The polynomial coefficients (poly = p[0]*x^n + p[1]*x^(n-1) ...).\n   */\n  Sturm( const std::vector<double> & p );\n  /**\n   * \\brief Destructor.\n   */\n  virtual ~Sturm();\n\n  void findRoots2( std::vector<double> & roots, double eps_x = 0.001, double eps_val = 0.001 );\n  /**\n   * \\brief Finds the roots of the polynomial.\n   * \\return An array with the real roots of the polynomial.\n   */\n  std::vector<double> findRoots();\n  /**\n   * \\brief Finds brackets for the real roots of the polynomial.\n   * \\return A list of brackets for the real roots of the polynomial.\n   */\n  void bracketRoots( std::vector<double> & roots, double eps = -1.0 );\n  /**\n   * \\brief Evaluates the Sturm chain at a single bound.\n   * \\param[in] bound The bound.\n   * \\return The number of sign changes on the bound.\n   */\n  size_t evaluateChain( double bound );\n  /**\n   * \\brief Evaluates the Sturm chain at a single bound.\n   * \\param[in] bound The bound.\n   * \\return The number of sign changes on the bound.\n   */\n  size_t evaluateChain2( double bound );\n  /**\n   * \\brief Composes an initial bracket for all the roots of the polynomial.\n   * \\return The maximum of the absolute values of the bracket-values (That's\n   *         what the Lagrangian bound is able to find).\n   */\n  double computeLagrangianBound();\n\nprivate:\n  /**\n   * \\brief Internal function used for composing the Sturm chain\n   * \\param[in] p1 First polynomial.\n   * \\param[in] p2 Second polynomial.\n   * \\param[out] r The negated remainder of the polynomial division p1/p2.\n   */\n  void computeNegatedRemainder(\n      const Eigen::MatrixXd & p1,\n      const Eigen::MatrixXd & p2,\n      Eigen::MatrixXd & r );\n\n  /** A matrix containing the coefficients of the Sturm-chain of the polynomial */\n  Eigen::MatrixXd _C;\n  /** The dimension _C, which corresponds to (polynomial order+1) */\n  size_t _dimension;\n};\n\n}\n}\n\n#endif /* OPENGV_STURM_HPP_ */\n", "meta": {"hexsha": "29976be0f3c31239fdf1ad91004c778c243707f4", "size": 5999, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/opengv/math/Sturm.hpp", "max_stars_repo_name": "skn123/opengv", "max_stars_repo_head_hexsha": "91f4b19c73450833a40e463ad3648aae80b3a7f3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 794.0, "max_stars_repo_stars_event_min_datetime": "2015-01-16T22:25:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T23:59:20.000Z", "max_issues_repo_path": "include/opengv/math/Sturm.hpp", "max_issues_repo_name": "skn123/opengv", "max_issues_repo_head_hexsha": "91f4b19c73450833a40e463ad3648aae80b3a7f3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 77.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T11:09:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T13:31:39.000Z", "max_forks_repo_path": "include/opengv/math/Sturm.hpp", "max_forks_repo_name": "skn123/opengv", "max_forks_repo_head_hexsha": "91f4b19c73450833a40e463ad3648aae80b3a7f3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 276.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:18:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T09:05:06.000Z", "avg_line_length": 36.1385542169, "max_line_length": 95, "alphanum_fraction": 0.6274379063, "num_tokens": 1336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5234360315561931}}
{"text": "\n\n// Local private PANACEA includes\n#include \"vector_eigen.hpp\"\n\n// Third party includes\n#include <Eigen/Dense>\n\n// Standard includes\n#include <cassert>\n#include <iostream>\n#include <memory>\n\nnamespace panacea {\n\nVectorEigen::VectorEigen() { vector_ = std::make_unique<Eigen::VectorXd>(); }\n\nconst VectorType VectorEigen::type() const { return VectorType::Eigen; }\n\nvoid VectorEigen::setZero() { vector_->setZero(); }\n\nvoid VectorEigen::resize(const int size) {\n  assert(vector_->rows() >= 0);\n  vector_->resize(size);\n}\n\nVectorEigen &VectorEigen::operator=(const Vector &vec) {\n  this->resize(vec.rows());\n  for (int row = 0; row < vec.rows(); ++row) {\n    this->operator()(row) = vec(row);\n  }\n  return *this;\n}\n\ndouble &VectorEigen::operator()(const int index) {\n  assert(index >= 0);\n  assert(index < vector_->rows());\n  return (*vector_)(index);\n}\n\ndouble VectorEigen::operator()(const int index) const {\n  assert(index >= 0);\n  assert(index < vector_->rows());\n  return (*vector_)(index);\n}\n\nint VectorEigen::rows() const {\n  if (direction_ == Direction::AlongRows) {\n    return vector_->rows();\n  } else {\n    return 1;\n  }\n}\n\nDirection VectorEigen::direction() const { return direction_; }\n\nint VectorEigen::cols() const {\n  if (direction_ == Direction::AlongRows) {\n    return 1;\n  } else {\n    return vector_->rows();\n  }\n}\n\nvoid VectorEigen::print() const { std::cout << (*vector_) << std::endl; }\n} // namespace panacea\n", "meta": {"hexsha": "77bd4458a08812b05abcb89fb2ed0b9bedf96502", "size": 1432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libpanacea/vector/vector_eigen.cpp", "max_stars_repo_name": "lanl/PANACEA", "max_stars_repo_head_hexsha": "9779bdb6dcc3be41ea7b286ae55a21bb269e0339", "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/libpanacea/vector/vector_eigen.cpp", "max_issues_repo_name": "lanl/PANACEA", "max_issues_repo_head_hexsha": "9779bdb6dcc3be41ea7b286ae55a21bb269e0339", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libpanacea/vector/vector_eigen.cpp", "max_forks_repo_name": "lanl/PANACEA", "max_forks_repo_head_hexsha": "9779bdb6dcc3be41ea7b286ae55a21bb269e0339", "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.3731343284, "max_line_length": 77, "alphanum_fraction": 0.6620111732, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6757646010190477, "lm_q1q2_score": 0.5234360315561931}}
{"text": "/**\n * @file \tex5.cpp\n * @author \tFabian Wegscheider\n * @date \tJun 5, 2017\n */\n\n#include <iostream>\n#include <fstream>\n#include <boost/timer/timer.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing namespace std;\nusing namespace boost;\n\n/**\n * main function which reads a graph from a .gph file, then calculates shortest\n * paths from all vertices to the first vertex with the dijsktra algorithm\n * and prints the furthest vertex together with its distance\n * to the standard output\n * @param numargs number of inputs on command line\n * @param args array of inputs on command line\n * @return whether the function operated successfully\n */\nint main(int numargs, char *args[]) {\n\n\n\ttimer::cpu_timer t;\n\n\tif (numargs != 2) {\n\t\tcout << \"Usage: \" << args[0] << \" filename\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tifstream inputFile;\n\tinputFile.open(args[1]);\t\t\t\t\t\t\t//trying to read file\n\tif (inputFile.fail()) {\n\t\tcerr << \"file could not be read\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\ttypedef adjacency_list<vecS, vecS, undirectedS,\n\t\t\tno_property, property<edge_weight_t, double>> Graph;\n\ttypedef pair<int,int> Edge;\n\n\tint numVertices;\n\tint numEdges;\n\n\tstring line;\n\tgetline(inputFile, line);\t\t\t\t\t//first line is read\n\tvector<string> parts;\n\tsplit(parts, line, is_any_of(\" \"));\n\n\tif (parts.size() != 2) {\n\t\tcerr << \"error in file: first line should consist of two integers!\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\ttry {\n\t\tnumVertices = stoi(parts[0]);\t\t//information from the first line\n\t\tnumEdges = stoi(parts[1]);\t\t\t//are stored\n\t} catch (...) {\n\t\tcerr << \"error in file: first line should consist of two integers!\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tEdge *edges =  new Edge[numEdges];\t\t\t//in these arrays all information about\n\tdouble *weights = new double[numEdges];\t\t//the edges are stored\n\n\tint i = 0;\n\n\t//read line by line\n\twhile (getline(inputFile, line)) {\n\t\tsplit(parts, line, is_any_of(\" \"));\n\t\tif (parts.size() != 3) {\n\t\t\tcerr << \"error in line \" << (i+2) << \": line should consists of \"\n\t\t\t\t\t\"two integers and a double!\" << endl;\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\ttry {\n\t\t\tedges[i] = Edge(stoi(parts[0])-1, stoi(parts[1])-1);\n\t\t\tweights[i] = stod(parts[2]);\n\t\t} catch(...) {\n\t\t\tcerr << \"error in line \" << (i+2) << \": line should consists of \"\n\t\t\t\t\t\"two integers and a double!\" << endl;\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\t++i;\n\t}\n\n\t//undirected graph is constructed with all edges and their weights\n\tGraph g(edges, edges + numEdges , weights, numVertices);\n\n\tvector<double> distances(numVertices);\n\n\t//call of dijsktra\n\tdijkstra_shortest_paths(g, *(vertices(g).first), distance_map(&distances[0]));\n\n\tproperty_map<Graph, vertex_index_t>::type index = get(vertex_index, g);\n\n\tdouble maxDist = 0;\n\tint maxIdx = 0;\n\tgraph_traits<Graph>::vertex_iterator it;\n\n\t//search for furthest vertex\n\tfor (it = vertices(g).first+1; it != vertices(g).second; ++it) {\n\t\tdouble tmp = distances[*it];\n\t\tif (tmp > maxDist) {\n\t\t\tmaxDist = tmp;\n\t\t\tmaxIdx = index(*it);\n\t\t}\n\t}\n\n\tcout << \"RESULT VERTEX \" << (maxIdx+1) << endl;\n\tcout << \"RESULT DIST \" << maxDist << endl;\n\tcout << endl << t.format() <<  endl;\n\n\texit(EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "556cc74214978a270634980f39908a2ec35dea6a", "size": 3232, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Wegscheider/Ex5/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": "Wegscheider/Ex5/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": "Wegscheider/Ex5/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": 26.4918032787, "max_line_length": 79, "alphanum_fraction": 0.6649133663, "num_tokens": 894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5234360264982474}}
{"text": "\ufeff\n\n/*\n********************************************************************\n\u7248\u672c\u58f0\u660e\uff1a\n\t\t\t\t\t\t\t\t   \u256d\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256e\n\t\t\t\t\t\t\t\t  \u2551         \u3016\u8bfe\u9898\u8bbe\u8ba1\uff1a\u3017         \u2551\n\t\t \u256d\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2524\u8bbe\u8ba1\u65f6\u95f4\uff1a2020.4.17 \u251c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256e\n\t\t\u2551                        \u2551   \u8bbe\u8ba1\u4eba\uff1a  2016\u7ea7\u5de5\u4e1a\u5de5\u7a0b\u4e13\u4e1a \u909d\u4f1f\u675cTridu\u00b3\u00b3     \u2551                            \u2551\n\t\t\u2551                        \u2570\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256f                            \u2551\n\t  \u3000\u2551                                        \u2605    \u5173\u4e8e    Code     \u2605                                         \u2551\n\t\t\u2551   @\u8ba1\u7b97\u673a\u914d\u7f6e\uff1awindows 10 \u6559\u80b2\u7248 64\u4f4d\u64cd\u4f5c\u7cfb\u7edf \u5185\u5b58\uff1a4G CPU \uff1ai3--6100\t\t                            \u2551\n\t\t\u2551   @\u8fd0\u884c\u73af\u5883\uff1aMicrosoft Visual C++ 2010\t\t\t\t                                                    \u2551\n\t\t\u2551   @\u8bbe\u8ba1\u601d\u8def\uff1a\u5efa\u7acb\u591a\u4e2a\u5b50\u51fd\u6570\uff0c\u5206\u522b\u7528\u4f5c\u7f13\u51b2\u533a\u65e0\u9650\u7684\u4e32\u884c\u751f\u4ea7\u7ebf\u5efa\u6a21.\t\t\t\t                            \u2551\n  \u3000  \u3000\u2551--------------------------------------------------------------------------------------------------------- \u2551\n\t  \u3000\u2551                                        \u2605      @\u4e3b\u8981\u51fd\u6570       \u2605                                        \u2551\n  \u3000    \u2551                              |----------------------------------------------|                            \u2551\n\t\t\u2551\t\t\t\t1 \u6781\u5927\u4ee3\u6570\u6cd5\u7684\u4e58\u6cd5MP_RealNumberTimes\u30012 \u6781\u5927\u4ee3\u6570\u7cfb\u7edf\u7684\u77e9\u9635\u4e58\u6cd5MP_MaTimesMb\u3001\t\t\t\t\u2551\n\t\t\u2551\t\t\t    3 \u6781\u5927\u4ee3\u6570\u6cd5\u7684\u52a0\u6cd5MP_RealNumberPlus\u30014 \u77e9\u9635A\u7684\u6781\u5927\u4ee3\u6570\u6cd5k\u6b21\u5e42MP_AKpower\u3001\t\t\t    \t\u2551\n\t\t\u2551\t\t\t\t5 \u6781\u5927\u4ee3\u6570\u77e9\u9635\u7684\u661f\u8fd0\u7b97MP_Mastar\u30016 \u5224\u65ad\u77e9\u9635\u7684\u53ef\u7b80\u7ea6\u6027\u5e76\u7ed9\u51fa\u4e0d\u53ef\u7b80\u7ea6\u77e9\u9635\u7684\u7279\u5f81\u503cMP_MaValue\u3001 \u2551\n\t\t\u2551\t\t\t\t7 \u8ba1\u7b97\u4e32\u884c\u751f\u4ea7\u7ebf\u5f00\u73af\u7cfb\u7edf\u7684\u53c2\u6570\u77e9\u9635ABC:T2ABCmatrix\u3001\t                            \t\t\t\u2551\n\t\t\u2551\t\t\t\t8 \u7ed9\u51fa\u53cd\u9988\u77e9\u9635K\u8ba1\u7b97\u95ed\u73af\u7ebf\u6027\u6a21\u578bM,N\u77e9\u9635MP_KT2MN\t\t\t                                \t\u2551\n\t\t\u2551\t\t\t    \u4e3b\u51fd\u6570\u63a7\u5236\u7ba1\u7406\u4e86\u5404\u4e2a\u51fd\u6570\u7ed3\u6784\uff0c\u5176\u5b9e\u9700\u8981\u5916\u90e8\u4f7f\u7528\uff0c\t\t\t                            \t\u2551\n\t\t\u2551\t\t\t    \u53ea\u9700\u8981\u628a\u529f\u80fd\u51fd\u6570extern\uff0c\u5199\u6210dll\u63d0\u4f9b\u7ed9\u5176\u4ed6\u51fd\u6570\u8c03\u7528\u5c31\u884c\u5728\u4e3b\u51fd\u6570t_main(GUI\u5e94\u7528\u672c\u8d28\u5c31\u662f\u901a\u8fc7\u5404\u79cd \u2551\n\t\t\u2551  \u7ec4\u4ef6\u8c03\u7528\u51fd\u6570\u4f20\u9012\u53c2\u6570\uff0c\u5176\u5b9e\u903b\u8f91\u7c7b\u4f3c\uff0c\u8fd9\u91cc\u76ee\u6807\u662f\u8bf4\u660e\u529f\u80fdGUI\u5e94\u7528\u61d2\u5f97\u6574\u4e86)\u4e2d\uff0c\u53ef\u4ee5\u4ee51\u30012\u30013\u30014\u30015\u30016\u30017\u30018\u3001\u2551\n\t\t\u2551  9\u300110\u6570\u5b57\u952e\u5206\u522b\u53ef\u4ee5\u6267\u884c\u67d0\u4e2a\u529f\u80fd\u6a21\u5757\u3002                                                                   \u2551\n\t\t\u2551\t\t\t\t\u9650\u6559\u5b66\u4f7f\u7528\u4ea4\u6d41\uff01\u8bf7\u52ff\u7528\u4e8e\u5546\u4e1a\u76ee\u7684\u3002                                                          \u2551\n\u3000      \u2551----------------------------------------------------------------------------------------------------------\u2551\n\t\t\u2551                          \u6b22\u8fce\u63d0\u51fa\u60a8\u7684\u5efa\u8bae\u6216\u610f\u89c1\uff0c\u8bf7\u53d1\u90ae\u4ef6:2055969978@qq.com                              \u2551\n\t\t\u2551----------------------------------------------------------------------------------------------------------\u2551\n\t\u3000\u3000\u2551                                                                                                          \u2551\n\t\t\u2551                     \u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e                     \u2551\n\t\t\u2570\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2524   \u2605\u2605\u2605\u2605\u2605\u2605  Tridu\u00b3\u00b3\uff0ctridu33@qq.com\u2605\u2605\u2605\u2605\u2605\u2605\u2605     \u251c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256f\n\t\t\t\t\t\t\t  \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n\n\n******************************************************************\n*/\n\n// MaxPlus_ABC.cpp : \u5b9a\u4e49\u63a7\u5236\u53f0\u5e94\u7528\u7a0b\u5e8f\u7684\u5165\u53e3\u70b9\u3002\n//\n#define _CRT_SECURE_NO_WARNINGS ; \n// \u5305\u62ec SDKDDKVer.h \u5c06\u5b9a\u4e49\u53ef\u7528\u7684\u6700\u9ad8\u7248\u672c\u7684 Windows \u5e73\u53f0\u3002\n\n// \u5982\u679c\u8981\u4e3a\u4ee5\u524d\u7684 Windows \u5e73\u53f0\u751f\u6210\u5e94\u7528\u7a0b\u5e8f\uff0c\u8bf7\u5305\u62ec WinSDKVer.h\uff0c\u5e76\u5c06\n// WIN32_WINNT \u5b8f\u8bbe\u7f6e\u4e3a\u8981\u652f\u6301\u7684\u5e73\u53f0\uff0c\u7136\u540e\u518d\u5305\u62ec SDKDDKVer.h\u3002\n//\u5728\u6b64\u5904\u5f15\u7528\u7a0b\u5e8f\u9700\u8981\u7684\u5176\u4ed6\u5934\u6587\u4ef6\n//\u7f16\u8bd1\u7a0b\u5e8f\u4f1a\u5148\u4ece\u5f53\u524d\u76ee\u5f55\u4e2d\u627e\u6587\u4ef6\uff0c\u751f\u6210\u9884\u7f16\u8bd1\u5934\u6587\u4ef6\uff01\u9884\u7f16\u8bd1\uff0c\u662f\u4e3a\u4e86\u63d0\u9ad8\u7f16\u8bd1\u901f\u5ea6\uff01\n#include <SDKDDKVer.h>\n#include <stdio.h>\n#include <tchar.h>//\u4e00\u822c\u662f\u7528\u53cc\u5f15\u53f7\u6765\u5f15\u7528\u81ea\u5df1\u7f16\u5199\u7684\u6587\u4ef6\uff0c\u800c\u7528\u5c16\u62ec\u53f7\u5f15\u7528\u7cfb\u7edf\u6807\u51c6\u7684\u6587\u4ef6\u3002\n#include<stdlib.h>//\u7528\u4e8e\u6570\u503c\u8f6c\u6362\u3001\u5185\u5b58\u5206\u914d\u4ee5\u53ca\u5177\u6709\u5176\u4ed6\u76f8\u4f3c\u4efb\u52a1\u7684\u51fd\u6570\u3002free()\n#include<conio.h>//Console Input/Output\uff08\u63a7\u5236\u53f0\u8f93\u5165\u8f93\u51fa\uff09\u7684\u7b80\u5199\uff0c\u5176\u4e2d\u5b9a\u4e49\u4e86\u901a\u8fc7\u63a7\u5236\u53f0\u8fdb\u884c\u6570\u636e\u8f93\u5165\u548c\u6570\u636e\u8f93\u51fa\u7684\u51fd\u6570\uff0c\u4e3b\u8981\u662f\u4e00\u4e9b\u7528\u6237\u901a\u8fc7\u6309\u952e\u76d8\u4ea7\u751f\u7684\u5bf9\u5e94\u64cd\u4f5c\uff0c\u6bd4\u5982getch()\u51fd\u6570\u7b49\u7b49\u3002\n#include<string.h>//\u5b57\u7b26\u4e32\u5904\u7406\n#include<dos.h>//\u5305\u542b\u4e86\u5f88\u591aBIOS\u548cDOS\u8c03\u7528\u51fd\u6570\n#include<windows.h>//windows\n#include <ctype.h>//\n#include <iostream>\n//Eigen3\n#include <regex>\n#include <string>\n#include <vector>\n#include <Eigen/Dense>\n#include<fstream>// Save to local file.\n#include <sstream> // stringstream, getline\n\n#include <limits.h>//\u6574\u578b\u65e0\u7a77\u5927\u5c0f\uff0cINT_MAX\u8868\u793a\u6b63\u65e0\u7a77\uff0c-DBL_MAX\u8868\u793a\u8d1f\u65e0\u7a77\n#include <float.h>//double \u578b\u7684\u65e0\u7a77\u5927\u5c0f\uff0c\u7528DBL_MAX\u8868\u793a\u6b63\u65e0\u7a77\uff0c-DBL_MAX\u8868\u793a\u8d1f\u65e0\u7a77(\u6ce8\u610f\u4e0d\u662fDBL_MIN)\n\n\nusing namespace Eigen;\nusing namespace std;\n\n\n//\u58f0\u660e\u51fd\u6570\t\n/*\n1 \u6781\u5927\u4ee3\u6570\u6cd5\u7684\u4e58\u6cd5MP_RealNumberTimes();\n2 \u6781\u5927\u4ee3\u6570\u7cfb\u7edf\u7684\u77e9\u9635\u4e58\u6cd5MP_MaTimesMb();\n3 \u6781\u5927\u4ee3\u6570\u6cd5\u7684\u52a0\u6cd5MP_RealNumberPlus();\n4 \u77e9\u9635A\u7684\u6781\u5927\u4ee3\u6570\u6cd5k\u6b21\u5e42MP_AKpower();\n5 \u6781\u5927\u4ee3\u6570\u77e9\u9635\u7684\u661f\u8fd0\u7b97MP_Mastar();\n6 \u5224\u65ad\u77e9\u9635\u7684\u53ef\u7b80\u7ea6\u6027\u5e76\u7ed9\u51fa\u4e0d\u53ef\u7b80\u7ea6\u77e9\u9635\u7684\u7279\u5f81\u503cMP_MaValue();\n7 \u8ba1\u7b97\u4e32\u884c\u751f\u4ea7\u7ebf\u5f00\u73af\u7cfb\u7edf\u7684\u53c2\u6570\u77e9\u9635ABC:T2ABCmatrix();\n8 \u7ed9\u51fa\u53cd\u9988\u77e9\u9635K\u8ba1\u7b97\u95ed\u73af\u7ebf\u6027\u6a21\u578bM,N\u77e9\u9635MP_KT2MN();\n\n*/\n\n\n//-------------------------------------------------------------------------\n//Octave\u7f16\u7a0b\u8bed\u8a00\u7701\u7565\u4e86\u7e41\u7410\u7684\u53d8\u91cf\u58f0\u660e\u548c\u51fd\u6570\u8c03\u7528\uff0c\u5728\u628aOctave\u4ee3\u7801\u7f16\u7a0b\u5b9e\u73b0\u4e3aC++\u7684\u8fc7\u7a0b\u4e2d\uff0c\u9700\u8981\u589e\u52a0\u4ee3\u7801\u4e2d\u7684Octave\u5e93\u7684\u7ed3\u6784\u4f53\u548c\u51fd\u6570\uff0cOctave\u4ee3\u7801\u4e0d\u80fd\u751f\u6210exe\u6216\u8005dll,\u8001\u5e08\u5efa\u8bae\u6211\u7528c++\u9020\u4e00\u904d\u8f6e\u5b50\uff0c\u6211\u89c9\u5f97\u4e5f\u8bb8c++\u5927\u578b\u6570\u636e\u7ed3\u6784\u7cbe\u5ea6\u8ba1\u7b97\u4f18\u5316\u53ef\u80fd\u4f1a\u597d\u4e00\u4e9b\u5427\u3002\n//\u6839\u636ecode\uff0c\u9700\u8981\u5b9a\u4e49\u7684\u7ed3\u6784\u4f53\u548c\u51fd\u6570(\u8f6e\u5b50)\uff1a\n//col collist(k)\u5217\u5411\u91cf\u7ed3\u6784\u4f53=\u4e00\u7ef4\u6570\u7ec4=\u7279\u6b8a\u7684\u4e8c\u7ef4\u77e9\u9635\n//row rowlist(k)\u884c\u5411\u91cf\u7ed3\u6784\u4f53=\u4e00\u7ef4\u6570\u7ec4=\u7279\u6b8a\u7684\u4e8c\u7ef4\u77e9\u9635\n//matrix\u77e9\u9635\u7ed3\u6784\u4f53=\u4e8c\u7ef4\u6570\u636e\n//\u6cdb\u578b\u51fd\u6570max\n//int result = max(collist)\u53d6\u884c\u5411\u91cf\u5927\u503c\n//max(rowlist)\u53d6\u5217\u5411\u91cf\u5927\u503c\n//max(matrix)\u53d6\u4e8c\u7ef4\u6570\u7ec4matrix\u6700\u5927\u503c\n//collist diag(matrix H)\n//\u8fd4\u56de\u503c[int m,int n]=\u51fd\u6570\u540dsize(arg*\u53c2\u6570matrix matrix_mn)\u53d6\u5927\u5c0f\n//[matrix matrix_ones]=ones(int m,int n);\n//......\u592a\u9ebb\u70e6\u4e86\uff0c\u6240\u4ee5\uff1a\n//\u4eba\u751f\u82e6\u77ed\uff0c\u6211\u9009Eigen!\nMatrixXd readMatrixFromTXT(string dir);\nint colT = 0;//T\u6bcf\u5217\u6570\u521d\u59cb0\nint rowT = 0;//T\u6bcf\u884c\u6570\u91cf\u521d\u59cb\u503c0,\u53d8\u91cf\u4f5c\u7528\u57df\nMatrixXd readMatrixFromTXT(string dir) {\n\tstring line;\n\tifstream in(dir);  //\u8bfb\u5165\u6587\u4ef6\n\tregex pat_regex(\"[[:digit:]]+\");  //\u5339\u914d\u539f\u5219\uff0c\u8fd9\u91cc\u4ee3\u8868\u4e00\u4e2a\u6216\u591a\u4e2a\u6570\u5b57\n\t//\u83b7\u53d6\u77e9\u9635rowT,colT\n\twhile (getline(in, line)) {  //\u6309\u884c\u8bfb\u53d6\n\t\trowT++;\n\t\tcolT = 0;//\u6bcf\u884c\u5217\u6570\u8bbe\u7f6e\u521d\u59cb0,\u53d8\u91cf\u4f5c\u7528\u57df\n\t\tfor (sregex_iterator it(line.begin(), line.end(), pat_regex), end_it; it != end_it; ++it) {  //\u8868\u8fbe\u5f0f\u5339\u914d\uff0c\u5339\u914d\u4e00\u884c\u4e2d\u6240\u6709\u6ee1\u8db3\u6761\u4ef6\u7684\u5b57\u7b26\n\t\t\tcolT++;//colT++\n\t\t}\n\t};\n\tMatrixXd T = MatrixXd::Ones(rowT, colT);//\u6ce8\u610f\u884c\u5217\u6570\u4ece0\u5f00\u59cb\n\t//\u8d4b\u503c\n\tint i = 0;//\u6bcf\u5217 index\u521d\u59cb0\n\tint j = 0;//\u6bcf\u884c index\u521d\u59cb\u503c0\n\tifstream in2(dir);\n\twhile (getline(in2, line)) {  //\u6309\u884c\u8bfb\u53d6\n\t\ti++;\n\t\tj = 0;\n\t\tfor (sregex_iterator it(line.begin(), line.end(), pat_regex), end_it; it != end_it; ++it) {  //\u8868\u8fbe\u5f0f\u5339\u914d\uff0c\u5339\u914d\u4e00\u884c\u4e2d\u6240\u6709\u6ee1\u8db3\u6761\u4ef6\u7684\u5b57\u7b26\n\t\t\t//cout << it->str() << \" \";  //\u8f93\u51fa\u5339\u914d\u6210\u529f\u7684\u6570\u636e\n\t\t\tj++;\n\t\t\tT(i - 1, j - 1) = stoi(it->str());  //\u5c06\u6570\u636e\u8f6c\u5316\u4e3aint\u578b\u5e76\u5b58\u5165\n\t\t}\n\t};\n\tin.close(); in2.close();\n\treturn T;\n}\n\n\n\n/*\u975e\u5e38\u4e0d\u597d\u7528\u7684Octave\u6df7\u5408\u7f16\u7a0b\n#include <oct.h>\nint mystandlone (void)\n{\n  std::cout << \"Hello Octave world!\\n\";\n\n  int n = 2;\n  Matrix a_matrix = Matrix (n, n);\n\n  for (octave_idx_type i = 0; i < n; i++)\n    for (octave_idx_type j = 0; j < n; j++)\n      a_matrix(i,j) = (i + 1) * 10 + (j + 1);\n\n  std::cout << a_matrix;\n\n  return 0;\n} \n*/\n\n//-------------------------------------------------------------------------\n\nvoid menu();\n\n//\u83dc\u5355MatrixXd\n\nint MP_RealNumberTimes(int a,int b);//1\nMatrixXd  MP_MaTimesMb(MatrixXd Ma, MatrixXd Mb);//2\nint MP_RealNumberPlus(int a, int b);//3\nMatrixXd  MP_AKpower(MatrixXd A, int k);\t//4\nMatrixXd MP_Mastar(MatrixXd A);//5\ndouble MP_MaValue(MatrixXd A);//6\nvoid T2ABCmatrix(MatrixXd T);//7\nMatrixXd T2Amatrix(MatrixXd T);\nMatrixXd T2Bmatrix(MatrixXd T);\nMatrixXd T2Cmatrix(MatrixXd T);\nvoid MP_KT2MN( MatrixXd K, MatrixXd T);//8\n\nvoid exit();//9\nvoid showtxt();//10\n\n\n//-------------------------------------------------------------------------\n\nvoid menu() {\n\n\tsystem(\"cls\");    //\u6e05\u5c4f\n\tsystem(\"mode con cols=150 lines=45\");\n\tsystem(\"color f0\");//\u6539\u53d8\u63a7\u5236\u53f0\u524d\u666f\uff0c\u80cc\u666f\u989c\u8272\n\tsystem(\"title \u57fa\u4e8e\u6781\u5927\u4ee3\u6570\u6cd5\u7684\u4e32\u884c\u751f\u4ea7\u7ebf\u8ba1\u7b97\u5de5\u5177\u5305\");\n\t//system(\"\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t date /T\");//\u663e\u793a\u7cfb\u7edf\u5f53\u524d\u65e5\u671f\n\t//system(\"\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t time /T\");//\u663e\u793a\u7cfb\u7edf\u5f53\u524d\u65f6\u95f4\uff0c\\t\u662f\u6ca1\u6709\u53cd\u5e94\u7684\n\tprintf(\"\\n\\n\\n\\n\\n\");\n\tprintf(\"\\t\\t\\t\\t \u256d\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256e\\n\");\n\tprintf(\"\\t\\t\\t\\t            \u3016\u8bfe\u9898\u8bbe\u8ba1\uff1aMaxPlus_ABC\u3017          \\n\");\n\tprintf(\"\\t \u256d\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2524  \u8bbe\u8ba1\u65f6\u95f4\uff1a2020.4.20 \u251c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256e\\n\");\n\tprintf(\"\\t\\t\\t\\t               \u8bbe\u8ba1\u4eba\uff1aTridu33                                                                              \\n\");\n\tprintf(\"\\t\\t\\t\\t\u2570 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256f                             \\n\");\n\tprintf(\"\\t\u2551---------------------------------------------------------------------------------------------------------- \u2551\\n\");\n\tprintf(\"\\t\u2551                                        \u2605    Menu\u83dc\u5355     \u2605                                              \u2551\\n\");\n\tprintf(\"\\t\u2551---------------------------------------------------------------------------------------------------------- \u2551\\n\");\n\tprintf(\"\\t\u2551                                    1.\u6781\u5927\u4ee3\u6570\u6cd5\u7684\u4e58\u6cd5MP_RealNumberTimes();                                \u2551\\n\");\n\tprintf(\"\\t\u2551                                    2.\u6781\u5927\u4ee3\u6570\u7cfb\u7edf\u7684\u77e9\u9635\u4e58\u6cd5MP_MaTimesMb();                                \u2551\\n\");\n\tprintf(\"\\t\u2551                                    3.\u6781\u5927\u4ee3\u6570\u6cd5\u7684\u52a0\u6cd5MP_RealNumberPlus();                                 \u2551\\n\");\n\tprintf(\"\\t\u2551                                    4.\u77e9\u9635A\u7684\u6781\u5927\u4ee3\u6570\u6cd5k\u6b21\u5e42MP_AKpower();                                  \u2551\\n\");\n\tprintf(\"\\t\u2551                                    5.\u6781\u5927\u4ee3\u6570\u77e9\u9635\u7684\u661f\u8fd0\u7b97MP_Mastar();                                     \u2551\\n\");\n\tprintf(\"\\t\u2551                                    6.\u5224\u65ad\u77e9\u9635\u7684\u53ef\u7b80\u7ea6\u6027\u5e76\u7ed9\u51fa\u4e0d\u53ef\u7b80\u7ea6\u77e9\u9635\u7684\u7279\u5f81\u503cMP_MaValue();            \u2551\\n\");\n\tprintf(\"\\t\u2551                                    7.\u8ba1\u7b97\u4e32\u884c\u751f\u4ea7\u7ebf\u5f00\u73af\u7cfb\u7edf\u7684\u53c2\u6570\u77e9\u9635ABC:T2ABCmatrix();                   \u2551\\n\");\n\tprintf(\"\\t\u2551                                    8.\u7ed9\u51fa\u53cd\u9988\u77e9\u9635K\u8ba1\u7b97\u95ed\u73af\u7ebf\u6027\u6a21\u578bM,N\u77e9\u9635MP_KT2MN();                      \u2551\\n\");\n\tprintf(\"\\t\u2551                                    9.exit\u9000\u51fa                                                             \u2551\\n\");\n\tprintf(\"\\t\u2551                                    10.\u5173\u4e8e                                                                \u2551\\n\");\n\tprintf(\"\\t\u2551\\t     \u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e              \u2551\\n\");\n\tprintf(\"\\t\u2551\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2524 \u2605\u2605\u2605\u2605\u2605\u2605  \u6b22\u8fce\u63d0\u51fa\u60a8\u7684\u5efa\u8bae\u6216\u610f\u89c1\uff0c\u8bf7\u53d1\u90ae\u4ef6:tridu33@qq.com    \u2605\u2605\u2605\u2605\u2605\u2605\u2605\u251c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2551\\n\");\n\tprintf(\"\\t\u2551\\t     \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\\n\\n\\n\\n\");\n\n\tprintf(\"\\t\\t\\t\u8bf7\u60a8\u9009\u62e9(1-10):\\t\");\n}\n\n\n//-------------------------------------------------------------------------MatrixXd\n//1 \u6781\u5927\u4ee3\u6570\u6cd5\u7684\u4e58\u6cd5MP_RealNumberTimes();\n\nint MP_RealNumberTimes(int a, int b) {\n\tprintf(\"\\n\u6781\u5927\u4ee3\u6570\u6cd5\u7684\u4e58\u6cd5MP_RealNumberTimes\\n\");\n\treturn a + b;\n};\n/*\n\nfunction c=MP_RealNumberTimes(a,b)\n  c=a+b;\nendfunction\n\n*/\n\n\n//-------------------------------------------------------------------------\n//2 \u6781\u5927\u4ee3\u6570\u7cfb\u7edf\u7684\u77e9\u9635\u4e58\u6cd5MP_MaTimesMb();\nMatrixXd MP_MaTimesMb(MatrixXd Ma, MatrixXd Mb) {\n\t//printf(\"\u6781\u5927\u4ee3\u6570\u7cfb\u7edf\u7684\u77e9\u9635\u4e58\u6cd5MP_MaTimesMb\\n \");\n\tMatrixXd MaTimesMb = MatrixXd::Ones(Ma.rows(), Mb.cols()); \n\tint m = Ma.rows(); int n = Mb.cols();\n\tMatrixXd tmplist = MatrixXd::Ones(1,Ma.cols());\n\tif(Ma.cols()!=Mb.rows())\n\t\tcout<<\"Horizontal dimension of a should equal to vertical dimension of b.\"<<endl;\n\telse\n\t{\n\t\tfor (int i = 0; i <  m; i++) {\n\t\t\tfor (int j = 0; j <  n; j++) {\n\t\t\t\tfor (int k = 0; k<Ma.cols();k++) {\n\t\t\t\t\tif (Ma(i, k) != -DBL_MAX && Mb(k, j) != -DBL_MAX)\n\t\t\t\t\t\ttmplist(0, k) = Ma(i, k) + Mb(k, j);\n\t\t\t\t\t//-DBL_MAX\u4f1a\u6ea2\u51fa\u5bfc\u81f4\u7ed3\u679c0\uff0c\u800c\u4e0d\u4f1a\u51fa\u73b0\u4fdd\u6301-DBL_MAX\u7684\u7ed3\u679c\uff0c\u6240\u4ee5\u9700\u8981\u81ea\u5b9a\u4e49\uff0c-DBL_MAX\u9047\u5230\u4ec0\u4e48\u6570\u5b57\u76f8\u52a0\u90fd==-DBL_MAX\n\t\t\t\t\telse //\u5176\u4e2d\u6709\u4e00\u4e2a\u52a0\u6570\u662f-DBL_MAX,\u7ed3\u679c\u4e0d\u7528\u7b97\u6570\u8ba1\u7b97,\u6ea2\u51fa\uff0c\u800c\u5e94\u8be5\u76f4\u63a5\u4ee4\u7ed3\u679c\u4e3a-DBL_MAX\n\t\t\t\t\t\ttmplist(0, k) = -DBL_MAX;\n\t\t\t\t}\n\t\t\t\tdouble result = -DBL_MAX;\n\t\t\t\tint length = tmplist.cols();\n\t\t\t\tfor (int i = 0; i < length; i++) {\n\t\t\t\t\tif (result < tmplist(0,i)) result = tmplist(0,i);//double 2 int ,lose message\n\t\t\t\t}\n\t\t\t\tMaTimesMb(i, j) = result;\n\t\t\t\t//cout <<\"MaTimesMb(i, j):\" <<MaTimesMb(i, j) << endl;\n\t\t\t}\n\t\t}\n\t}\n\t//cout<<MaTimesMb<<endl;\n\treturn MaTimesMb;\n};//\n\n\n\n/*\n\n%%\u77e9\u9635A(m*r)\u6781\u5927\u4ee3\u6570\u4e58\u77e9\u9635B(r*n)=MaTimesMb(m*n)\nfunction MaTimesMb=MP_MaTimesMb(a,b)\n  [m,c1]=size(a);\n  [r2,n]=size(b);\n  if (c1==r2)\n\tfor i=1:m\n\t  for j=1:n\n\t\tfor k=1:c1\n\t\ttmplist(k)=a(i,k)+b(k,j);\n\t\tendfor\n\t\tMaTimesMb(i,j)=max(tmplist);\n\t  endfor\n\tendfor\n  elseif\n\tdisp('Horizontal dimension of a should equal to vertical dimension of b.');\n  endif\nendfunction\n\n*/\n\n\n//-------------------------------------------------------------------------\n//3 \u6781\u5927\u4ee3\u6570\u6cd5\u7684\u52a0\u6cd5MP_RealNumberPlus();\nint MP_RealNumberPlus(int a,int b) {\n\t//printf(\"\\n\u6781\u5927\u4ee3\u6570\u6cd5\u7684\u52a0\u6cd5MP_RealNumberPlus\\n\");\n\treturn max(a,b);\n};//\n\n\n/*\nfunction c=MP_RealNumberPlus(a,b)\n  c=max(a,b);\nendfunction\n\n\u77e9\u9635\u52a0\u6cd5\u5176\u5b9e\u5c31\u662f\u53d6\u5927\u64cd\u4f5c\uff0c\u540e\u7eed\u61d2\u5f97\u5199\u51fa\u6765\uff0c\u76f4\u63a5\u5199\u4e86\u5728\u9700\u8981\u8c03\u7528\u7684\u5730\u65b9\nfunction MaPlusMb=MP_MaPlusMb(a,b)\n  [m,r1]=size(a);\n  [r2,n]=size(b);\n  if ((r1==r2) ^(m==n) ^(m=r1))\n\t\t\t\tfor i=1:m\n\tfor j=1:m\n\tif(a(i,j)<b(i,j))\n\ta(i,j)=b(i,j);\n\tendif\n\tendfor\n\tendfor\n  elseif\n\tdisp('dimension of a should equal to dimension of b,and both square matrix.');\n  endif\nendfunction\n*/\n\n//-------------------------------------------------------------------------\n//4 \u77e9\u9635A\u7684\u6781\u5927\u4ee3\u6570\u6cd5k\u6b21\u5e42MP_AKpower();\n\tMatrixXd  MP_AKpower(MatrixXd A, int k) {\n\t\t//printf(\"\\n\u77e9\u9635A\u7684\u6781\u5927\u4ee3\u6570\u6cd5k\u6b21\u5e42MP_AKpower\\n \");\n\t\tint m = A.rows(); k = k - 1;\n\t\tMatrixXd AK= -DBL_MAX*MatrixXd::Ones(m, m);\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tAK(i, i) = 0;\n\t\t}//AK\u521d\u59cb\u503cE\u77e9\u9635\n\t\t//cout << \"\u521d\u59cb\u503cAK=E\\n\"<<AK << endl;\n\t\tif (A.rows() == A.cols()) {\n\t\t\tfor (int j = 0; j <= k ; j++) {\n\t\t\t//cout << \"the\" << j << \"turns:\\n\" << A << endl;\n\t\t\tAK = MP_MaTimesMb(AK, A);\n\t\t\t//cout << AK << endl;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tprintf(\"Horizontal dimension of A should equal to vertical dimension\");\n\t\treturn AK;\n\t}//\n/*\n\n%\u77e9\u9635A\u7684\u6781\u5927\u4ee3\u6570\u6cd5k\u6b21\u5e42\nfunction AK=MP_AKpower(A,k)\n  [m,n]=size(A);\nif(m==n)\n\t\t  E=-inf*ones(m,m);\n\t\t  for i=1:m \n\t\t\tE(i,i)=0;\n\t\t  endfor\n\t\t  AK=E;\n\t\t  for j=1:k\n\t\t  AK=MP_MaTimesMb(AK,A);\n\t\t  endfor\nelseif\n  disp('Horizontal dimension of A should equal to vertical dimension');\nendif\nendfunction\n\n*/\n\n//-------------------------------------------------------------------------\n//5 \u6781\u5927\u4ee3\u6570\u77e9\u9635\u7684\u661f\u8fd0\u7b97MP_Mastar();\n\n\nMatrixXd MP_Mastar(MatrixXd A) {\n\t//printf(\"\\n\u6781\u5927\u4ee3\u6570\u77e9\u9635\u7684\u661f\u8fd0\u7b97MP_Mastar\\n \");\n\tint m = A.rows(); int n = A.cols();\n\tMatrixXd AK = MatrixXd::Ones(m, m);//\u521d\u59cb\u5316\u77e9\u9635\u5927\u5c0f,\u6700\u540e\u4e0d\u53d6all 1\n\tMatrixXd E = -DBL_MAX * MatrixXd::Ones(m, m);\n\tfor (int i = 0; i < m; i++) {\n\t\tE(i, i) = 0;\n\t}\n\tMatrixXd Astr = E;\n\tif (m == n) {\n\t\tfor (int k = 1; k < m; k++) {//k\u4e0d\u662f\u4e0b\u6807\uff0c\u4e0d\u8bb8-1\n\t\t//cout<<\"k=\"<<k<<endl;\n\t\tAK = MP_AKpower(A, k);// A\u7684k\u6b21\u5e42\uff0ck = 0; < dim(A) - 1,Astr\u662f\u7d2f\u8ba1\u7684\u77e9\u9635\u7ed3\u679c,AK\u662f\u6bcf\u6b21\u6781\u5927\u4ee3\u6570\u52a0\u6cd5\u65b0\u8fdb\u53bb\u7684\u77e9\u9635\n\t//\tcout <<\"AK=\"<<AK<< endl;//MaPlusMb\u77e9\u9635\u7684\u6781\u5927\u4ee3\u6570\u52a0\u6cd5Astronauts\uff0cAstr\n\t\t\t\tfor (int i = 0; i < m; i++) {\n\t\t\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\t\t\tif (Astr(i, j) < AK(i, j))\n\t\t\t\t\t\t\tAstr(i, j) = AK(i, j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//cout<<\"Astr=\"<<Astr<<endl;\n\t\t}\n\t}\n\telse\n\t\tprintf(\"A should be square matrix.\");\nreturn Astr;\n}\n\t\n\n\n\n\n/*\n\n%%\u6781\u5927\u4ee3\u6570\u7684\u65b9\u9635\u661f\u8fd0\u7b97\u5b9e\u73b0\nfunction Astr=MP_Mastar(A)\n[m,n]=size(A);\nif m==n\n\tE=-inf*ones(m,m);\n\tfor i=1:m\n\t  E(i,i)=0;\n\tendfor\n Astr=E;\n for k=1:m-1\n AK=MP_AKpower(A,k);%%A\u7684k\u6b21\u5e42\uff0ck=1:dim(A)-1\n\tfor i=1: m\n\t  for j=1:m\n\t\tif(Astr(i,j)<AK(i,j))\n\t\tAstr(i,j)=AK(i,j);\n\t\tendif\n\t  endfor\n\tendfor\n endfor\nelseif\n  disp('A should be square matrix.');\nendif\nendfunction\n\n*/\n//------------------------------------------------------------------------\n//6 \u5224\u65ad\u77e9\u9635\u7684\u53ef\u7b80\u7ea6\u6027\u5e76\u7ed9\u51fa\u4e0d\u53ef\u7b80\u7ea6\u77e9\u9635\u7684\u7279\u5f81\u503cMP_MaValue();\n\n\ndouble MP_MaValue(MatrixXd A) {\n\tprintf(\"\\n\u5224\u65ad\u77e9\u9635\u7684\u53ef\u7b80\u7ea6\u6027\u5e76\u7ed9\u51fa\u4e0d\u53ef\u7b80\u7ea6\u77e9\u9635\u7684\u7279\u5f81\u503cMP_MaValue\\n \"); double Alambda = 0;\n\tMatrixXd H = A;\n\tMatrixXd Ak = A;\n\tint m = A.rows(); int n = A.cols();\n\tif (m == n) {\n\t\tfor (int k = 2; k < m; k++) {//\u4e0d\u662f\u4e0b\u6807\u4e0d\u8bb8-1\n\t\t\tAk = MP_MaTimesMb(Ak, A);\n\t\t\tfor (int i = 0; i < m; i++) {\n\t\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\t\tif ((H(i, j) < Ak(i, j) / k)) H(i, j) = Ak(i, j) / k;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint x = 0;\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tif (H(i, j) == (-DBL_MAX)) x = 1; break;\n\t\t\t}\n\t\t}\n\n\t\tif (x == 0) {\n\t\t\tdouble maxValue=0;\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tif (H(j, j)> maxValue) maxValue = H(j,j) ;//double 2 int lose messgae\n\t\t\t\t//int j = 0; j < m; j++\u5faa\u73af\u53d8\u91cf-1\u5c31\u4e0d\u9700\u8981\u4e0b\u6807\u53d8\u52a8\uff0c\u4f46\u662f\u6bd4\u8f83\u9ebb\u70e6\u7684\u4e0b\u6807\u63a8\u7406\u7684\u60c5\u51b5\u4e0b\uff1a\u8fd8\u662f\u7528\u7684\u4e0b\u6807-1\uff0c\u5faa\u73af\u6761\u4ef6\u4e0d\u53d8\u6bd4\u8f83\u597d\u3002\n\t\t\t};\n\t\t\tAlambda = maxValue;\n\t\t}\n\t\telse {\n\t\t\tcout << \"Matrix is a Reducible matrix.\" << endl;;\n\t\t\tAlambda = -DBL_MAX;\n\t\t}\n\t}\n\telse{\n\t\tcout<<\"A should be square matrix.\"<<endl;\n\t}\n\treturn Alambda;\n\n}\n\n\n/*\n\n%\u5224\u65ad\u77e9\u9635\u7684\u53ef\u7b80\u7ea6\u6027\uff0c\u5e76\u7ed9\u51fa\u4e0d\u53ef\u7b80\u7ea6\u77e9\u9635\u7684\u7279\u5f81\u503c\nfunction Alambda=MP_MaValue(A)\nH=A;\nAk=A;\n[m,n]=size(A);\nif m==n\n\tfor k=2:m\n\t  Ak=MP_MaTimesMb(Ak,A);\n\t  for i=1:m\n\t\tfor j=1:m\n\t\t  if (H(i,j)<Ak(i,j)/k)\n\t\t\t H(i,j)=Ak(i,j)/k;\n\t\tend\n\t  end\n\tend\n  end\n  x=0;\n  for i=1:m\n\tfor j=1:m\n\t  if (H(i,j)==(-inf))\n\t\t  x=1;break;\n\t  end\n\tend\n  end\n\tif(x==0)\n\t  Alambda=max(diag(H));\n\telse\n\t  disp('Matrix is a Reducible matrix.');\n\t  Alambda=-inf;\n\tend\nelse\n   disp('A should be square matrix.');\nend\n##\n##>> M\n##M =\n##\n##     7  -Inf  -Inf     7     7     4\n##    10     6  -Inf    10    10     7\n##    10     9     8    10    10     7\n##     6     6     5     6  -Inf  -Inf\n##     9     9     8     9     8  -Inf\n##    10     9     8    10    10     7\n##\n##>> N\n##N =\n##\n##  -Inf  -Inf     5  -Inf  -Inf  -Inf     4  -Inf  -Inf\n##  -Inf  -Inf     5  -Inf  -Inf  -Inf     4     3  -Inf\n##  -Inf  -Inf     6  -Inf  -Inf  -Inf     5     4     0\n##  -Inf  -Inf     5  -Inf  -Inf     3     4  -Inf  -Inf\n##  -Inf  -Inf     8  -Inf  -Inf     6     7     4  -Inf\n##  -Inf  -Inf    11  -Inf  -Inf     8    10     9     5\n##  -Inf  -Inf     8  -Inf  -Inf     6     7  -Inf     0\n##  -Inf  -Inf    12  -Inf  -Inf    10    11     6     4\n##  -Inf  -Inf    15  -Inf  -Inf    13    14    12     8\n##\n##>> Nlambda=MP_MaValue(N)\n##Matrix is a Reducible matrix.\n##Nlambda = -Inf\n##>> Mlambda=MP_MaValue(M)\n##Mlambda =  9.5000\n##\n##\n\n*/\n\n\n//-------------------------------------------------------------------------\n//7 \u8ba1\u7b97\u4e32\u884c\u751f\u4ea7\u7ebf\u5f00\u73af\u7cfb\u7edf\u7684\u53c2\u6570\u77e9\u9635ABC:T2ABCmatrix();\n\n\n\n\nvoid T2ABCmatrix(MatrixXd T) {\n\tint m = T.rows(); int n = T.cols();\n\tcout << \"A is:\\n\" << T2Amatrix(T) << endl;\n\tcout << \"\\nB is:\\n\" << T2Bmatrix(T) << endl;\n\tcout << \"\\nC is:\\n\" << T2Cmatrix(T) << endl;\n\n}\n\nMatrixXd T2Amatrix(MatrixXd T) {\n\tint m = T.rows(); int n = T.cols();\n\n\t//\u6784\u9020\u77e9\u9635A:\n\tMatrixXd A = -DBL_MAX * MatrixXd::Ones(m*n,m*n);\n\tfor (int k = 0; k<=(m - 1);k++) {\n\t\tfor (int j = 0; j <= (m - 1);j++) {\n\t\t\tif (j == k) {\n\t\t\t\tfor (int i = 1; i <=( n - 1);i++) {\n\t\t\t\t\tA(k * n + i + 1 - 1, j * n + i - 1) = T((k + 1 - 1), i - 1);//\u6700\u5feb\u7684\u65b9\u6cd5\u662f\u53ea\u6539\u4e0b\u6807-1\uff0c\u5faa\u73af\u6761\u4ef6\u4e0d\u53d8\uff0c\u6539\u524dA(k*n+i+1,j*n+i)=T((k+1),i);\n\t\t\t\t};\n\t\t\t}\n\t\t\telse if(1 + j == k) {\n\t\t\t\tfor (int i = 1; i <= n; i++) {\n\t\t\t\t\tA(k * n + i - 1, j * n + i - 1) = T(k - 1, i - 1);//\u6700\u5feb\u7684\u65b9\u6cd5\u662f\u53ea\u6539\u4e0b\u6807-1\uff0c\u5faa\u73af\u6761\u4ef6\u4e0d\u53d8\uff0c\u6539\u524dA(k*n+i,j*n+i)=T(k,i);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\t;\n\t\t}\n\t}\n\treturn A;\n}\n\nMatrixXd T2Bmatrix(MatrixXd T) {\n\tint m = T.rows(); int n = T.cols();\n\tMatrixXd B = -DBL_MAX * MatrixXd::Ones(m * n, m + n); //\u6784\u9020\u77e9\u9635B:\n\tfor (int i = 1; i <= n; i++) {\n\t\tB(i - 1, i - 1) = 0;//-1\n\t}\n\tfor (int i = 1; i <= m; i++) {\n\t\tB(n * (i - 1) + 1 - 1, n + i - 1) = 0;//-1\n\t}\n\treturn B;\n}\n\nMatrixXd T2Cmatrix(MatrixXd T) {\n\tint m = T.rows(); int n = T.cols();\n\tMatrixXd C = -DBL_MAX * MatrixXd::Ones(m + n, m * n);//\u6784\u9020\u77e9\u9635C:\n\tfor (int i = 1; i <= n; i++) {\n\t\tC(i - 1, (m - 1) * n + i - 1) = T(m - 1, i - 1);//-1\n\t}\n\tfor (int i = 1; i <= m; i++) {\n\t\tC(n + i - 1, i * n - 1) = T(i - 1, n - 1);\n\t}\n\treturn C;\n}\n\n\n/*\n\n%% \u4e32\u884c\u751f\u4ea7\u7ebf\u5f00\u73af\u7cfb\u7edf\u7684\u53c2\u6570\u77e9\u9635\u5b9e\u73b0\nfunction [A,B,C]=T2ABCmatrix(T)\n  [m,n]=size(T);%%\u6784\u9020\u77e9\u9635A:\n  A=-inf*ones(m*n);\n  for k=0:m-1\n\tfor j=0:m-1\n\t  if(j==k)%%k*n+i=j*n+i\u5bf9\u89d2\u5143\u7d20\u4e0b\u65b9\u5143\u7d20\u4e0b\u6807k*n+i+1,j*n+i\n\t\t\tfor i=1:n-1%%\u5bf9\u89d2\u5206\u5757t_x1-t_x(n-1)\n\t\t\tA(k*n+i+1,j*n+i)=T((k+1),i);\n\t\t\tendfor;\n\t  elseif(1+j==k)\n\t\t\tfor i=1:n %%\u5bf9\u7126\u5206\u5757\u7684\u5de6\u4e0b\u5206\u5757t_x1-t_xn\n\t\t\tA(k*n+i,j*n+i)=T(k,i);\n\t\t\tendfor\n\t  %endif%\u5982\u679c\u7b2c11\u884c\u5199\u6210else if\u7406\u89e3\u4e3a\u4e24\u4e2aif else\u8bed\u53e5\n\t  endif%if\n\tendfor\n  endfor\n\n  B=-inf*ones(m*n,m+n); %%\u6784\u9020\u77e9\u9635B:\n\tfor i=1:n\n\t  B(i,i)=0;\n\tend\n\tfor i=1:m\n\t  B(n*(i-1)+1,n+i)=0;\n\tend\n\n  C=-inf*ones(m+n,m*n);%%\u6784\u9020\u77e9\u9635C:\n\tfor i=1:n\n\t  C(i,(m-1)*n+i)=T(m,i);\n\tend\n\tfor i=1:m\n\t  C(n+i,i*n)=T(i,n);\n\tend\n\nendfunction\n\n##\n##>> T=[25 60 40;35 45 45;45 70 70;40 65 60]\n##T =\n##\n##   25   60   40\n##   35   45   45\n##   45   70   70\n##   40   65   60\n##\n##>> [A,B,C]=openmatrix(T)\n##A =\n##\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##    25  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf    60  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##    25  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf    60  -Inf    35  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf    40  -Inf    45  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf    35  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf    45  -Inf    45  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf    45  -Inf    70  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf    45  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf    70  -Inf    40  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf    70  -Inf    65  -Inf\n##\n##B =\n##\n##     0  -Inf  -Inf     0  -Inf  -Inf  -Inf\n##  -Inf     0  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf     0  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf     0  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf     0  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf     0\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##\n##C =\n##\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf    40  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf    65  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf    60\n##  -Inf  -Inf    40  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf    45  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf    70  -Inf  -Inf  -Inf\n##  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf  -Inf    60\n\n\n*/\n//-------------------------------------------------------------------------\n//8 \u7ed9\u51fa\u53cd\u9988\u77e9\u9635K\u8ba1\u7b97\u95ed\u73af\u7ebf\u6027\u6a21\u578bM,N\u77e9\u9635MP_KT2MN();\n\n\n\nvoid MP_KT2MN(MatrixXd K, MatrixXd T){\n\tprintf(\"\\n\u7ed9\u51fa\u53cd\u9988\u77e9\u9635K\u8ba1\u7b97\u95ed\u73af\u7ebf\u6027\u6a21\u578bM,N\u77e9\u9635MP_KT2MN\\n\");\n\tint m = T.rows(); int n = T.cols();\n\tMatrixXd A = T2Amatrix(T);\n\tMatrixXd B = T2Bmatrix(T) ;\n\tMatrixXd C = T2Cmatrix(T) ;\n\tMatrixXd M = MP_MaTimesMb(C, MP_MaTimesMb(MP_Mastar(A), MP_MaTimesMb(B, K))); cout << \"M:\\n\"<<M << endl;\n\tMatrixXd N = MP_MaTimesMb(MP_Mastar(A), MP_MaTimesMb(B, MP_MaTimesMb(K, C))); cout << \"N:\\n\" << N << endl;\n\t\n};//\n\n\n/*\n\n%%\u6781\u5927\u4ee3\u6570\uff0c\u7ed9\u51fa\u53cd\u9988\u77e9\u9635K\u8ba1\u7b97M,N\u77e9\u9635\nfunction [M,N]=MP_KT2MN(K,T)\n  [A,B,C]=T2ABCmatrix(T);\n  M=MP_MaTimesMb(C,MP_MaTimesMb(MP_Mastar(A),MP_MaTimesMb(B,K)));\n  N=MP_MaTimesMb(MP_Mastar(A),MP_MaTimesMb(B,MP_MaTimesMb(K,C)));\n\n\n##>> T=[0 1 5;3 2 3;4 3 0]\n##T =\n##\n##   0   1   5\n##   3   2   3\n##   4   3   0\n##\n##>> K=-inf*ones(6,6);\n##>> for i=1:6\n##K(i,i)=0;\n##endfor\n##>> [M,N]=MP_KT2MN(K,T)\n##M =\n##\n##     7  -Inf  -Inf     7     7     4\n##    10     6  -Inf    10    10     7\n##    10     9     8    10    10     7\n##     6     6     5     6  -Inf  -Inf\n##     9     9     8     9     8  -Inf\n##    10     9     8    10    10     7\n##\n##N =\n##\n##  -Inf  -Inf     5  -Inf  -Inf  -Inf     4  -Inf  -Inf\n##  -Inf  -Inf     5  -Inf  -Inf  -Inf     4     3  -Inf\n##  -Inf  -Inf     6  -Inf  -Inf  -Inf     5     4     0\n##  -Inf  -Inf     5  -Inf  -Inf     3     4  -Inf  -Inf\n##  -Inf  -Inf     8  -Inf  -Inf     6     7     4  -Inf\n##  -Inf  -Inf    11  -Inf  -Inf     8    10     9     5\n##  -Inf  -Inf     8  -Inf  -Inf     6     7  -Inf     0\n##  -Inf  -Inf    12  -Inf  -Inf    10    11     6     4\n##  -Inf  -Inf    15  -Inf  -Inf    13    14    12     8\n\n\n*/\n//\nvoid exit() {\n\tprintf(\"\\n9.exit \\n\");\n\tsystem(\"exit\");\n}\n\n//-------------------------------------------------------------------------\nvoid showtxt() {\n\tsystem(\"cls\");\n\t//system(\"title \u8f93\u51650\u8fd4\u56de\u4e3b\u83dc\u5355\");\n\tchar c;\n\t//\u6587\u4ef6\u8f93\u5165\n\tfreopen(\"readme.txt\", \"r\", stdin);\n\twhile (scanf(\"%c\", &c) != EOF) {\n\t\tprintf(\"%c\", c);\n\t}\n\tfreopen(\"CON\", \"r\", stdin); //https://blog.csdn.net/pqleo/article/details/23031337 \u5361\u4e86\u4e09\u5929\u7684\u95ee\u9898\u539f\u6765\u5728\u8fd9\u513f\uff01\uff01\uff01\uff01\u8ba9\u6d41\u56de\u5230\u63a7\u5236\u53f0?\u4f7f\u7528freopen\u540e\u5982\u4f55\u5c06stdout\u8f93\u51fa\u6d41\u8fd8\u539f\u56de\u5c4f\u5e55\uff1f\n\t//break;//\u6b65\u8fdb\u6ca1\u95ee\u9898\uff0c\u4f46\u662f\u4e0d\u77e5\u9053\u4e3a\u4ec0\u4e48\u4e0d\u80fd\u53ea\u6267\u884c\u4e00\u6b21\uff0c\u6b7b\u5faa\u73af\n\tprintf(\"\\n\\n\");\n\tsystem(\"pause\");\n\t//exit(1);\n}\n\n//-------------------------------------------------------------------------\n\n/*\u672c\u4eba\u7cbe\u901a\u9762\u5411\u4f5b\u7cfb\u7684\u7f16\u7a0b\u8bed\u8a00\uff0c\u6709\u7a7a\u4ea4\u6d41\n\n\t\t\t\t\t   _oo0oo_\n\t\t\t\t\t  o8888888o\n\t\t\t\t\t  88\" . \"88\n\t\t\t\t\t  (| -_- |)\n\t\t\t\t\t  0\\  =  /0\n\t\t\t\t\t___/`---'\\___\n\t\t\t\t  .' \\\\|     |// '.\n\t\t\t\t / \\\\|||  :  |||// \\\n\t\t\t\t/ _||||| -:- |||||- \\\n\t\t\t   |   | \\\\\\  -  /// |   |\n\t\t\t   | \\_|  ''\\---/''  |_/ |\n\t\t\t   \\  .-\\__  '-'  ___/-. /\n\t\t\t ___'. .'  /--.--\\  `. .'___\n\t\t  .\"\" '<  `.___\\_<|>_/___.' >' \"\".\n\t\t | | :  `- \\`.;`\\ _ /`;.`/ - ` : | |\n\t\t \\  \\ `_.   \\_ __\\ /__ _/   .-` /  /\n\t =====`-.____`.___ \\_____/___.-`___.-'=====\n\t\t\t\t\t   `=---='\n\n\t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\t\t\t   \u4f5b\u7956\u4fdd\u4f51         \u6c38\u65e0BUG\n*/\n///////////////////////////////////////////////////////////////////////////////////////////////\nvoid welcomevoice();\nvoid welcomevoice() {\n\tchar uerInputData[2][100] = { \"\u6b22\u8fce\u4f7f\u7528\" };\n\tint welcome = 0;\n\twhile (1) {\n\t\tFILE* pFile = fopen(\"voice.vbs\", \"w\");//msgbox\"\u81ea\"//CreateObject(\"SAPI.SpVoice\").Speak\"\u80fd\"//CreatObject(\"SAPI.SpVoice\").Speak+\"User_Input\";\n\t\tfprintf(pFile, \"CreateObject(\\\"SAPI.SpVoice\\\").Speak\\\"%s\\\"\", uerInputData[welcome++]);//fprintf(pFile,\"msgbox(\\\"%s\\\")\",uerInputData[i++]);//main(1)\u51fd\u6570\u5916\u53ea\u80fd\u5b9a\u4e49\u5168\u5c40\u53d8\u91cf\u6216\u8005\u5bf9\u8c61\uff0c\u800c\u4e0d\u80fd\u6267\u884c\u8bed\u53e5\u53ca\u8c03\u7528\u51fd\u6570\u3002//cmd system\n\t\tfclose(pFile);\n\t\tsystem(\"voice.vbs\");//run vbs\n\t\tsystem(\"del voice.vbs\");//del vbs\n\t\tif (welcome < 2)\n\t\t\tcontinue;\n\t\telse\n\t\t\tbreak;\n\t}\n};\n\n\n\n\n\nint _tmain(int argc, _TCHAR* argv[]) {\n\tMatrixXd Tread = readMatrixFromTXT(\"T.txt\");\n\tcout << \"T is :\\n\" << Tread << endl;\n\tcout << \"T\u77e9\u9635\u6709\" << rowT << \"\u884c\" << colT << \"\u5217\" << endl;\n\t\n\tMatrixXd Kread = -DBL_MAX*MatrixXd::Ones(6,6);\n\tfor (int i = 0; i < Kread.rows(); i++) {\n\t\tKread(i, i) = 0;\n\t}\n\tcout << \"K is :\\n\" << Kread << endl;\n\tcout << \"K\u77e9\u9635\u6709\" << Kread.rows() << \"\u884c\" << Kread.cols() << \"\u5217\" << endl;\n//-------------------------------\u8bfb\u53d6\u77e9\u9635T,\u83b7\u5f97\u53d8\u91cfrowT,colT,\u77e9\u9635K,\u83b7\u5f97\u53d8\u91cfrowK,colK---------------------------------------//\n\tint c;\n\tchar ch[7];\n\tint i, n;\n\tsystem(\"color 0f\");//\u6539\u53d8\u63a7\u5236\u53f0\u524d\u666f\uff0c\u80cc\u666f\u989c\u8272\n\tsystem(\"title MaxPlus_ABC\");\n\twelcomevoice();//\u6b22\u8fce\u4f7f\u7528\n\tprintf(\"\\t\\t\\t password(111):\");\n\t//---------\n\t\n\tfor (i = 0; i < 3; i++) {\n\t\t//\u83b7\u53d6ch\n\t\tfor (n = 0; n < 3; n++) {\n\t\t\tch[n] = _getch();\n\t\t\tprintf(\"*\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tch[n] = '\\0';\n\t\t//\u5339\u914dch\u548cpassword\n\t\t//if (0 == 0) {\n\t\tif (0 == strcmp(ch, \"111\")) {\n\t\t\tmenu();\n\t\t\t//mystandlone();//octave.h call Octave Function\n\t\t\tscanf(\"%d\", &c);\n\t\t\twhile (c) {\n\t\t\t\tswitch (c) {\n\t\t\t\tcase 1: cout << MP_RealNumberTimes(1, 2)<< endl; printf(\"\\nPress any key for continue...\");  break;\n\t\t\t\tcase 2: {\n\t\t\t\t\tint Marow = 2; int Macol = 3;\n\t\t\t\t\tMatrixXd Ma = MatrixXd::Random(Marow, Macol); Ma(0, 0) = -DBL_MAX; Ma(0, 1) = -DBL_MAX; Ma(0, 2) = -DBL_MAX;\n\t\t\t\t\tint Mbrow = 3; int Mbcol = 2;\n\t\t\t\t\tMatrixXd Mb = MatrixXd::Ones(Mbrow,Mbcol); Mb(0, 0) = -DBL_MAX; Mb(1, 0) = -DBL_MAX; Mb(2, 0) = -DBL_MAX;\n\t\t\t\t\tcout << Ma << endl;\n\t\t\t\t\tcout << Mb << endl;\n\t\t\t\t\tcout << MP_MaTimesMb(Ma, Mb) << endl;\n\t\t\t\t\tprintf(\"\\nPress any key for continue...\");\n\t\t\t\t} break;\n\t\t\t\tcase 3: cout<<MP_RealNumberPlus(1,2)<<endl; printf(\"\\nPress any key for continue...\"); break;\n\t\t\t\tcase 4: {\n\t\t\t\t\tint tmprow = 3; int tmpcol = 3; \n\t\t\t\t\tMatrixXd tmpE = -DBL_MAX * MatrixXd::Ones(tmprow, tmpcol);\n\t\t\t\t\tfor (int i = 0; i < tmprow;i++) { tmpE(i, i) = 0; }\n\t\t\t\t\tMatrixXd testA = -DBL_MAX*MatrixXd::Ones(tmprow, tmpcol);\n\t\t\t\t\ttestA << 1, 2, 2,\n\t\t\t\t\t\t-DBL_MAX, 2, 3,\n\t\t\t\t\t\t1, -DBL_MAX, 8;\n\t\t\t\t\tcout << \"\u77e9\u9635\uff1a\\n\"<< testA <<endl;\n\t\t\t\t\tcout << \"\u77e9\u9635\u81ea\u8eab\u77e9\u9635\u76f8\u4e58k=0\u6b21\uff1a\\n\" << tmpE << endl;\n\t\t\t\t\tcout << \"\u77e9\u9635\u81ea\u8eab\u77e9\u9635\u76f8\u4e58k=1\u6b21\uff1a\\n\" << MP_AKpower(testA, 1) << endl;\n\t\t\t\t\tcout << \"\u77e9\u9635\u81ea\u8eab\u77e9\u9635\u76f8\u4e58k=2\u6b21\uff1a\\n\" << MP_AKpower(testA, 2) << endl;\n\t\t\t\t\tcout << \"\u77e9\u9635\u81ea\u8eab\u77e9\u9635\u76f8\u4e58k=3\u6b21\uff1a\\n\" << MP_AKpower(testA, 3) << endl;\n\t\t\t\t\tprintf(\"\\nPress any key for continue...\");\n\t\t\t\t\tbreak; \n\t\t\t\t}\n\t\t\t\tcase 5: {\n\t\t\t\t\tcout << Tread << endl;\n\t\t\t\t\tMatrixXd tmp = T2Amatrix(Tread);\n\t\t\t\t\tcout << \"T\u7684A\u77e9\u9635\uff1a\\n\" << tmp << endl; \n\t\t\t\t\tcout << \"\u77e9\u9635\u661f\u8fd0\u7b97\uff1a\\n\" << MP_Mastar(tmp) << endl; \n\t\t\t\t\tprintf(\"\\nPress any key for continue...\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 6: {\n\t\t\t\t\tint tmprow = 3; int tmpcol = 3;\n\t\t\t\t\tMatrixXd tmp = MatrixXd::Ones(tmprow, tmpcol);\n\t\t\t\t\ttmp << 1, 2, 2,\n\t\t\t\t\t\t-DBL_MAX, 2, 3,\n\t\t\t\t\t\t1, -DBL_MAX, 8;\n\t\t\t\t\tcout << \"\u77e9\u9635\uff1a\\n\" << tmp << endl; \n\t\t\t\t\tcout << \"A\u77e9\u9635\u7279\u5f81\u503c(8\u9ed8\u8ba4\u503c)\uff1a\" << MP_MaValue(tmp) << endl; printf(\"\\nPress any key for continue...\"); break;\n\t\t\t\t}\n\t\t\t\tcase 7: T2ABCmatrix(Tread); printf(\"\\nPress any key for continue...\"); break;\n\t\t\t\tcase 8: MP_KT2MN(Kread, Tread); printf(\"\\nPress any key for continue...\"); break;\n\t\t\t\tcase 10: showtxt(); break;\n\t\t\t\tdefault:  printf(\"\u8be5\u7f16\u53f7\u7684\u65b0\u529f\u80fd\u6709\u5f85\u5f00\u53d1\u4e2d...\"); break;\n\t\t\t\tcase 9: return 0;\n\t\t\t\t};\n\t\t\t\t_getch();//\u4f1a\u7b49\u5f85\u4f60\u6309\u4e0b\u4efb\u610f\u952e\uff0c\u518d\u7ee7\u7eed\u6267\u884c\u4e0b\u9762\u7684\u8bed\u53e5\n\t\t\t\tmenu();\n\t\t\t\tscanf(\"%d\", &c);//\u53ef\u4ee5\u6362\u6210sscanf_(\"%d\",&n);'scanf': This function or variable may be unsafe. \t\t\n\t\t\t};\n\t\t}\n\n\t\telse {\n\t\t\tprintf(\"\u5bc6\u7801\u9519\u8bef,\u8bf7\u91cd\u65b0\u8f93\u5165\\n\");\n\t\t}\n\n\t}\n\tif (i == 3) {\n\t\tprintf(\"\u4f60\u8f93\u5165\u7684\u9519\u8bef\u7684\u5bc6\u7801\u6b21\u6570\u8fbe\u5230\u4e0a\u9650\uff0c\u7cfb\u7edf\u81ea\u52a8\u9000\u51fa\uff01\u8bf7\u8054\u7cfb\u7ba1\u7406\u5458\uff01\");\n\t\tsystem(\"pause\");\n\t\texit(1);\n\t}\n\treturn 0;\n}\n\n\n\n\n\n///////////   //                                       //    //\n   //        //                                       //   //\n  //        ////////     ////////      /////////     //  //        //////\n //        //     //    //     //     //      //    /////        //     \n//        //     //    //     //     //      //    //  //          ////\n//        //     //    //     //     //      //    //     //            //\n//        //     //     ///////////  //      //    //        //   //////\n/////////////////////////////////////////////////////////////////////////////////////////////\n\n\n", "meta": {"hexsha": "6e51bed00be3febf4274cdda2c1a3e1ef5551905", "size": 28046, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "VS2019/MaxPlus_ABC.cpp", "max_stars_repo_name": "Tridu33/MaxPlusAlgebra_TK_ABC_MN", "max_stars_repo_head_hexsha": "3d73753170ad007858427768eb069331f1ab22e7", "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": "VS2019/MaxPlus_ABC.cpp", "max_issues_repo_name": "Tridu33/MaxPlusAlgebra_TK_ABC_MN", "max_issues_repo_head_hexsha": "3d73753170ad007858427768eb069331f1ab22e7", "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": "VS2019/MaxPlus_ABC.cpp", "max_forks_repo_name": "Tridu33/MaxPlusAlgebra_TK_ABC_MN", "max_forks_repo_head_hexsha": "3d73753170ad007858427768eb069331f1ab22e7", "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.4600840336, "max_line_length": 190, "alphanum_fraction": 0.4518647936, "num_tokens": 11742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5234360264982474}}
{"text": "\ufeff#include <cmath>\n#include <chrono>\n#include <thread>\n#include <ctime>\n#include <fstream>\n#include <chrono>\n\n#include <Eigen/Dense>\n\n#include <cinder/app/App.h>\n#include <cinder/app/RendererGl.h>\n#include <cinder/gl/gl.h>\n#include <cinder/CameraUi.h>\n#include <cinder/params/Params.h>\n#include <cinder/Log.h>\n#include <cinder/ObjLoader.h>\n\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/serialization/unique_ptr.hpp>\n\n#include \"../resources/Resources.h\"\n#include <Utils.h>\n#include <BackgroundWorker.h>\n#include <TransferFunctionEditor.h>\n#include <Integration.h>\n#include <GridUtils.h>\n#include <TimeIntegrator.h>\n#include <SoftBodyGrid2D.h>\n#include <SoftBodyMesh2D.h>\n#include <SoftBody2DResults.h>\n#include <GridVisualization.h>\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\nusing namespace ar;\nusing namespace Eigen;\n\nclass SoftBodyCutFEM2DApp : public App {\npublic:\n\tSoftBodyCutFEM2DApp();\n\tvoid setup() override;\n\tvoid keyDown(KeyEvent event) override;\n    void keyUp(KeyEvent event) override;\n\tvoid mouseDown( MouseEvent event ) override;\n\tvoid update() override;\n\tvoid draw() override;\n\nprivate:\n\n    typedef double real;\n\n\t//AntTweakBar settings\n\tparams::InterfaceGlRef\tparams;\n    bool printMode;\n    int gridResolution;\n    bool fitObjectToGrid;\n    enum class Scene\n    {\n        SCENE_BAR,\n        SCENE_TORUS\n    };\n    Scene scene;\n    double torusOuterRadius;\n    double torusInnerRadius;\n    Vector2f rectCenter;\n    Vector2f rectHalfSize;\n\treal groundPlaneHeight;\n\treal groundPlaneAngle;\n    enum class ComputationMode\n    {\n        COMPUTATION_MODE_GRID = 1,\n        COMPUTATION_MODE_MESH = 2,\n        COMPUTATION_MODE_BOTH = 3\n    };\n    int computationMode;\n    bool showGrid;\n    enum class GridVisualizationMode\n    {\n        GRID_VISUALIZATION_U,\n        GRID_VISUALIZATION_SOLUTION,\n\t\tGRID_VISUALIZATION_BOUNDARY,\n        _GRID_VISUALIZATION_COUNT\n    };\n    GridVisualizationMode showGridSolution;\n    bool spaceBarPressed = false;\n    TimeIntegrator::Integrator timeIntegratorType;\n    TimeIntegrator::DenseLinearSolver denseLinearSolverType;\n    TimeIntegrator::SparseLinearSolver sparseLinearSolverType;\n    bool useSparseMatrices;\n    int sparseSolverIterations;\n    real sparseSolverTolerance;\n    SoftBodySimulation::RotationCorrection rotationCorrectionMode;\n\n    //soft body properties\n    enum Boundary\n    {\n        FREE = 0,\n        NEUMANN = 1,\n        DIRICHLET = 2\n    };\n    Vector2f gravity;\n    Vector2f neumannForce;\n    float youngsModulus;\n    float poissonsRatio;\n    float mass;\n    float dampingAlpha;\n    float dampingBeta;\n    float timestep;\n\tbool enableDirichletBoundaries;\n\tbool enableCollision;\n\tSoftBodySimulation::CollisionResolution collisionResolutionMode;\n\tfloat collisionVelocityDamping;\n    real groundStiffness_;\n    real softmaxAlpha_;\n    int step;\n\n    //grid\n    SoftBodyGrid2D gridSolver;\n    //true: diffusion of displacements into empty cells is done as a post-processing step (matrix contains only cells containing the object)\n    //false: diffusion is included in the matrix, matrix spans the whole grid\n    bool gridExplicitDiffusion;\n    bool gridHardDirichletBoundaries;\n    SoftBodyGrid2D::AdvectionMode gridAdvectionMode;\n    double gridElapsedSeconds = 0;\n\n    //triangles\n    SoftBodyMesh2D meshSolver;\n    double meshElapsedSeconds = 0;\n\n\t//output saving\n\tstd::unique_ptr<SoftBody2DResults> results;\n\n    //processing\n    ar::BackgroundWorkerPtr worker;\n\n    //visualization helpers\n\tGridVisualization visualization;\n\nprivate:\n    //Resets the simulation:\n    //- Creates the input grid and configuration\n    //- Resets the frame counter\n    void reset();\n    void invalidateRendering();\n    void performStep(float stepsize); //stepsize=0 -> static solution\n\n    void initGridWithTorus(); //initializes the SDF\n    void initGridWithRect();\n\n    void initTriMeshWithTorus(); //creates the vertices and inidices of the tri mesh\n    void initTriMeshWithGrid();\n\n\tvoid saveResults();\n};\n\nSoftBodyCutFEM2DApp::SoftBodyCutFEM2DApp()\n{\n\t//initial config\n    printMode = false;\n    gridResolution = 18;\n    fitObjectToGrid = false;\n    scene = Scene::SCENE_BAR;\n    torusOuterRadius = 0.1;\n    torusInnerRadius = 0.03;\n    rectCenter << 0.5, 0.74;\n    rectHalfSize << 0.3, 0.06;\n\n\tgroundPlaneHeight = 0.58;\n\tgroundPlaneAngle = 0;\n\n    computationMode = (int)ComputationMode::COMPUTATION_MODE_GRID;\n    showGrid = true;\n    showGridSolution = GridVisualizationMode::GRID_VISUALIZATION_BOUNDARY;\n    timeIntegratorType = TimeIntegrator::Integrator::Newmark1;\n    denseLinearSolverType = TimeIntegrator::DenseLinearSolver::PartialPivLU;\n    sparseLinearSolverType = TimeIntegrator::SparseLinearSolver::BiCGSTAB;\n    useSparseMatrices = false;\n    sparseSolverIterations = 100;\n    sparseSolverTolerance = 1e-5;\n\n    rotationCorrectionMode = SoftBodySimulation::RotationCorrection::Corotation;\n\n    gridExplicitDiffusion = true;\n    gridHardDirichletBoundaries = false;\n    gridAdvectionMode = SoftBodyGrid2D::AdvectionMode::DIRECT_FORWARD;\n\n    gravity = Vector2f(0, -10);\n    neumannForce = Vector2f(0, 0);\n    youngsModulus = 200;\n    poissonsRatio = 0.45;\n    mass = 1.0;\n    dampingAlpha = 0.001;\n    dampingBeta = 0.001;\n    timestep = 0.01;\n\tenableDirichletBoundaries = false;\n\tenableCollision = true;\n\tcollisionResolutionMode = SoftBodySimulation::CollisionResolution::SPRING_IMPLICIT;\n\tcollisionVelocityDamping = 0.5;\n    groundStiffness_ = 1000;\n    softmaxAlpha_ = 100;\n\n    step = 0;\n}\n\nvoid SoftBodyCutFEM2DApp::setup()\n{\n\t//parameter ui, must happen before user-camera\n\tparams = params::InterfaceGl::create(getWindow(), \"Parameters\", toPixels(ivec2(300, 600)));\n    params->setOptions(\"\", \"refresh=0.05\");\n    params->addParam(\"PrintMode\", &printMode).label(\"Print Mode\");\n\n    vector<string> computationModeEnums(4);\n    computationModeEnums[(int)ComputationMode::COMPUTATION_MODE_GRID] = \"grid\";\n    computationModeEnums[(int)ComputationMode::COMPUTATION_MODE_MESH] = \"mesh\";\n    computationModeEnums[(int)ComputationMode::COMPUTATION_MODE_BOTH] = \"overlay / both\";\n    params->addParam(\"Mode\", computationModeEnums, (int*)&computationMode, \"label='Mode'\");\n\n    params->addParam(\"InputResolution\", \n        std::function<void(int)>([this](int newValue) {this->gridResolution = newValue; this->reset(); }), \n        std::function<int()>([this]() {return this->gridResolution; })\n    ).min(4).group(\"Input\").label(\"Grid resolution\").keyIncr(\"PGUP\").keyDecr(\"PGDOWN\");\n    params->addParam(\"FitObjectToGrid\",\n        std::function<void(bool)>([this](bool newValue) {this->fitObjectToGrid = newValue; this->reset(); }),\n        std::function<bool()>([this]() {return this->fitObjectToGrid; })\n    ).group(\"Input\").label(\"Fit Object To Grid\");\n    vector<string> sceneEnums = { \"Bar\", \"Torus\" };\n    params->addParam(\"Scene\", sceneEnums, (int*)&scene).group(\"Input\").label(\"Scene\")\n        .accessors(std::function<void(int)>([this](int v)\n    {\n        scene = (Scene)v;\n        reset();\n        if (scene == Scene::SCENE_TORUS) {\n            params->setOptions(\"InputTorusOuterRadius\", \"visible=true\");\n            params->setOptions(\"InputTorusInnerRadius\", \"visible=true\");\n            params->setOptions(\"InputRectCenterX\", \"visible=false\");\n            params->setOptions(\"InputRectHalfSizeX\", \"visible=false\");\n            params->setOptions(\"InputRectCenterY\", \"visible=false\");\n            params->setOptions(\"InputRectHalfSizeY\", \"visible=false\");\n        } else {\n            params->setOptions(\"InputTorusOuterRadius\", \"visible=false\");\n            params->setOptions(\"InputTorusInnerRadius\", \"visible=false\");\n            params->setOptions(\"InputRectCenterX\", \"visible=true\");\n            params->setOptions(\"InputRectHalfSizeX\", \"visible=true\");\n            params->setOptions(\"InputRectCenterY\", \"visible=true\");\n            params->setOptions(\"InputRectHalfSizeY\", \"visible=true\");\n        }\n    }), std::function<int()>([this]() {return (int)scene; }));\n    params->addParam(\"InputTorusOuterRadius\",\n        std::function<void(double)>([this](double newValue) {this->torusOuterRadius = newValue; this->reset(); }),\n        std::function<double()>([this]() {return this->torusOuterRadius; })\n    ).min(0.01).max(0.5).step(0.01).group(\"Input\").label(\"Torus outer radius\").visible(false);\n    params->addParam(\"InputTorusInnerRadius\",\n        std::function<void(double)>([this](double newValue) {this->torusInnerRadius = newValue; this->reset(); }),\n        std::function<double()>([this]() {return this->torusInnerRadius; })\n    ).min(0.01).max(0.5).step(0.01).group(\"Input\").label(\"Torus inner radius\").visible(false);\n    params->addParam(\"InputRectCenterX\",\n        std::function<void(float)>([this](float newValue) {this->rectCenter.x() = newValue; this->reset(); }),\n        std::function<float()>([this]() {return this->rectCenter.x(); })\n    ).step(0.01).group(\"Input\").label(\"Rect center X\").visible(true);\n    params->addParam(\"InputRectCenterY\",\n        std::function<void(float)>([this](float newValue) {this->rectCenter.y() = newValue; this->reset(); }),\n        std::function<float()>([this]() {return this->rectCenter.y(); })\n    ).step(0.01).group(\"Input\").label(\"Rect center Y\").visible(true);\n    params->addParam(\"InputRectHalfSizeX\",\n        std::function<void(float)>([this](float newValue) {this->rectHalfSize.x() = newValue; this->reset(); }),\n        std::function<float()>([this]() {return this->rectHalfSize.x(); })\n    ).step(0.01).group(\"Input\").label(\"Rect half size X\").visible(true);\n    params->addParam(\"InputRectHalfSizeY\",\n        std::function<void(float)>([this](float newValue) {this->rectHalfSize.y() = newValue; this->reset(); }),\n        std::function<float()>([this]() {return this->rectHalfSize.y(); })\n    ).step(0.01).group(\"Input\").label(\"Rect half size Y\").visible(true);\n\tparams->addParam(\"InputGroundPlaneHeight\", &groundPlaneHeight).step(0.001).group(\"Input\").label(\"Ground Height\");\n\tparams->addParam(\"InputGroundPlaneAngle\", &groundPlaneAngle).step(0.001).group(\"Input\").label(\"Ground Angle\");\n    params->addButton(\"InputReset\", std::function<void()>([this]() {this->reset(); }), \"label='Reset' group=Input key=r\");\n\n    params->addParam(\"SoftBodyGravity\", &gravity.y()).step(0.001).group(\"Soft Body\").label(\"Gravity\");\n    params->addParam(\"SoftBodyNeumannForce\", &neumannForce.y()).step(0.001).group(\"Soft Body\").label(\"Neumann Force\")\n        .accessors(std::function<void(float)>([this](float v)\n    {\n        neumannForce.y() = v;\n        reset();\n    }), std::function<float()>([this]() {\n        return (float)neumannForce.y();\n    }));\n    params->addParam(\"SoftBodyYoungsModulus\", &youngsModulus).min(0).step(0.01).group(\"Soft Body\").label(\"Young's modulus\");\n    params->addParam(\"SoftBodyPoissonsRatio\", &poissonsRatio).min(0.0001).max(0.4999).step(0.01).group(\"Soft Body\").label(\"Poisson's ratio\");\n    params->addParam(\"SoftBodyMass\", &mass).min(0.0001).step(0.01).group(\"Soft Body\").label(\"Mass\");\n    params->addParam(\"SoftBodyDampingAlpha\", &dampingAlpha).min(0).step(0.001).group(\"Soft Body\").label(\"Damping on mass\");\n    params->addParam(\"SoftBodyDampingBeta\", &dampingBeta).min(0).step(0.001).group(\"Soft Body\").label(\"Damping on stiffness\");\n    vector<string> timeIntegratorTypeNames = { \"Newmark 1\", \"Newmark 2\", \"Central Differences\", \"Linear Accelleration\", \"Newmark 3\", \"HHT-alpha\" };\n    params->addParam(\"SoftBodyTimeIntegration\", timeIntegratorTypeNames, (int*)&timeIntegratorType).group(\"Soft Body\").label(\"Time Integrator\")\n        .accessors(std::function<void(int)>([this](int v)\n    {\n        timeIntegratorType = (TimeIntegrator::Integrator)v;\n        reset();\n    }), std::function<int()>([this]() {return (int)timeIntegratorType; }));\n#if SOFT_BODY_SUPPORT_SPARSE_MATRICES==1\n    params->addParam(\"SoftBodyUseSparseMatrices\", std::function<void(bool)>([this](bool v)\n    {\n        useSparseMatrices = v;\n        if (v)\n        {\n            params->setOptions(\"SoftBodyDenseLinearSolver\", \"visible=false\");\n            params->setOptions(\"SoftBodySparseLinearSolver\", \"visible=true\");\n            params->setOptions(\"SoftBodySparseSolverIterations\", \"visible=true\");\n            params->setOptions(\"SoftBodySparseSolverTolerance\", \"visible=true\");\n        } else\n        {\n            params->setOptions(\"SoftBodyDenseLinearSolver\", \"visible=true\");\n            params->setOptions(\"SoftBodySparseLinearSolver\", \"visible=false\");\n            params->setOptions(\"SoftBodySparseSolverIterations\", \"visible=false\");\n            params->setOptions(\"SoftBodySparseSolverTolerance\", \"visible=false\");\n        }\n    }), std::function<bool()>([this]()\n    {\n        return useSparseMatrices;\n    })).group(\"Soft Body\").label(\"Sparse matrices\");\n    vector<string> denseLinearSolverTypeNames = { \"PartialPivLU\", \"FullPivLU\", \"HouseholderQR\", \"ColPivHousholderQR\", \"FullPivHouseholderQR\", \"CompleteOrthogonalDecomposition\", \"LLT\", \"LDLT\" };\n    params->addParam(\"SoftBodyDenseLinearSolver\", denseLinearSolverTypeNames, (int*)&denseLinearSolverType).group(\"Soft Body\").label(\"Dense Linear Solver\");\n    vector<string> sparseLinearSolverTypeNames = { \"Conjugate Gradient\", \"BiCGSTAB \", \"Sparse-LU\" };\n    params->addParam(\"SoftBodySparseLinearSolver\", sparseLinearSolverTypeNames, (int*)&sparseLinearSolverType).group(\"Soft Body\").label(\"Sparse Linear Solver\");\n    params->addParam(\"SoftBodySparseSolverIterations\", &sparseSolverIterations).group(\"Soft Body\").label(\"Sparese Solver iterations\").min(0);\n    params->addParam(\"SoftBodySparseSolverTolerance\", &sparseSolverTolerance).group(\"Soft Body\").label(\"Sparese Solver tolerance\").min(0).step(0.00001);\n#else\n    vector<string> denseLinearSolverTypeNames = { \"PartialPivLU\", \"FullPivLU\", \"HouseholderQR\", \"ColPivHousholderQR\", \"FullPivHouseholderQR\", \"CompleteOrthogonalDecomposition\", \"LLT\", \"LDLT\" };\n    params->addParam(\"SoftBodyDenseLinearSolver\", denseLinearSolverTypeNames, (int*)&denseLinearSolverType).group(\"Soft Body\").label(\"Dense Linear Solver\");\n#endif\n    params->addParam(\"SoftBodyTimeStep\", &timestep).min(0.001).step(0.001).group(\"Soft Body\").label(\"Time step\");\n    params->addParam(\"SoftBodyGridExplicitDiffusion\", &gridExplicitDiffusion, \"group='Soft Body' label='Grid Displacement Diffusion' true='explicit (post-process)' false='implicit (matrix)'\");\n    params->addParam(\"SoftBodyGridHardDirichletBoundaries\", &gridHardDirichletBoundaries).group(\"Soft Body\").label(\"Grid Hard Dirichlet Boundaries\");\n    vector<string> softBodyAdvectionNames;\n    for (int i = 0; i < static_cast<int>(SoftBodyGrid2D::AdvectionMode::_COUNT_); ++i)\n        softBodyAdvectionNames.push_back(SoftBodyGrid2D::advectionModeName(static_cast<SoftBodyGrid2D::AdvectionMode>(i)));\n    params->addParam(\"SoftBodyAdvectionMode\", softBodyAdvectionNames, (int*)&gridAdvectionMode).group(\"Soft Body\").label(\"Grid Advection\");\n\n    vector<string> rotationCorrectionNames = { \"None\", \"Corotation\"};\n    params->addParam(\"SoftBodyRotationCorrection\", rotationCorrectionNames, (int*)&rotationCorrectionMode).group(\"Soft Body\").label(\"Rotation correction\");\n\n\tparams->addParam(\"SoftBodyDirichlet\", \n\t\tstd::function<void(bool)>([this](bool newValue) {this->enableDirichletBoundaries = newValue; this->reset(); }),\n\t\tstd::function<bool()>([this]() {return this->enableDirichletBoundaries; }))\n\t.group(\"Soft Body\").label(\"Enable Dirichlet Boundaries\");\n\tparams->addParam(\"SoftBodyCollision\", &enableCollision).group(\"Soft Body\").label(\"Enable Collision\");\n\tvector<string> collisionResolutionNames(&SoftBodySimulation::CollisionResolutionNames[0], &SoftBodySimulation::CollisionResolutionNames[0]+size_t(SoftBodySimulation::CollisionResolution::_COUNT_));\n\tparams->addParam(\"SoftBodyCollisionResolution\", collisionResolutionNames, (int*)&collisionResolutionMode).group(\"Soft Body\").label(\"Collision Resolution\");\n\tparams->addParam(\"SoftBodyCollisionVelDamping\", &collisionVelocityDamping).group(\"Soft Body\").label(\"Col. Vel. Damping\").min(0).max(1).step(0.001);\n    params->addParam(\"SoftBodyCollisionGroundStiffness\", &groundStiffness_).group(\"Soft Body\").label(\"Col. Ground Stiffness\").min(0).step(0.001);\n    params->addParam(\"SoftBodyCollisionSoftmaxAlpha\", &softmaxAlpha_).group(\"Soft Body\").label(\"Col. Softmax-Alpha\").min(1).max(1000).step(0.001);\n\n    params->addButton(\"SoftBodyStep\", std::function<void()>([this]() {this->performStep(timestep); }), \"group='Soft Body' label='Single step'\");\n    params->addButton(\"SoftBodyStatic\", std::function<void()>([this]() {this->performStep(0); }), \"group='Soft Body' label='Static solution' key=RETURN\");\n\n    params->addParam(\"RenderingShowGrid\", &showGrid).group(\"Rendering\").label(\"Show grid\");\n    vector<string> gridVisualizationModeEnums((int)GridVisualizationMode::_GRID_VISUALIZATION_COUNT);\n    gridVisualizationModeEnums[(int)GridVisualizationMode::GRID_VISUALIZATION_U] = \"u\";\n    gridVisualizationModeEnums[(int)GridVisualizationMode::GRID_VISUALIZATION_SOLUTION] = \"solution\";\n\tgridVisualizationModeEnums[(int)GridVisualizationMode::GRID_VISUALIZATION_BOUNDARY] = \"boundary\";\n    params->addParam(\"RenderingShowGridSolutionMode\", gridVisualizationModeEnums, (int*)&showGridSolution, \"label='Grid solution' group=Rendering\");\n\n    params->addParam(\"TimingMesh\", &meshElapsedSeconds, true).group(\"Timings\").label(\"Mesh simulation (sec)\").precision(3);\n    params->addParam(\"TimingGrid\", &gridElapsedSeconds, true).group(\"Timings\").label(\"Grid simulation (sec)\").precision(3);\n\n\tparams->addButton(\"SaveResults\", std::function<void()>([this]() {this->saveResults(); }), \"label='Save Results'\");\n\n\tvisualization.setup();\n\n    //initialize grid\n    reset();\n}\n\nvoid SoftBodyCutFEM2DApp::keyDown(KeyEvent event)\n{\n\tApp::keyDown(event);\n    if (event.isHandled()) return;\n\tif (event.getChar() == 'f') {\n\t\t// Toggle full screen when the user presses the 'f' key.\n\t\tsetFullScreen(!isFullScreen());\n\t}\n\telse if (event.getCode() == KeyEvent::KEY_ESCAPE) {\n\t\t// Exit full screen, or quit the application, when the user presses the ESC key.\n\t\tif (isFullScreen())\n\t\t\tsetFullScreen(false);\n\t\telse\n\t\t\tquit();\n\t}\n\telse if (event.getChar() == 'p') {\n\t\t//Screenshot\n\t\tSurface surface = copyWindowSurface();\n        //if (printMode) {\n        //    //only save the grid\n        //    int windowWidth = getWindow()->getWidth();\n        //    int windowHeight = getWindow()->getHeight();\n        //    int gridBoundary = 50;\n        //    int gridSize = std::min(windowWidth, windowHeight) - 2 * gridBoundary;\n        //    int gridOffsetX = windowWidth / 2;\n        //    int gridOffsetY = windowHeight / 2;\n        //    Surface surface2(gridSize + 10, gridSize + 10, false);\n        //    surface2.copyFrom(surface, Area(gridOffsetX - 5, gridOffsetY - 5, gridOffsetX + gridSize + 10, gridOffsetY + gridSize + 10));\n        //    surface = surface2;\n        //}\n\t\t//construct filename\n\t\ttime_t now = time(NULL);\n\t\tstruct tm tstruct;\n\t\tchar buf[100];\n\t\ttstruct = *localtime(&now);\n\t\tstrftime(buf, sizeof(buf), \"%d-%m-%Y_%H-%M-%S\", &tstruct);\n\t\tstring fileName = string(\"../screenshots/SoftBodyFEM2DApp-\") + string(buf) + \".png\";\n\t\t//write out\n\t\twriteImage(fileName, surface);\n        CI_LOG_I(\"Screenshot saved to \" << fileName);\n\t}\n    else if (event.getCode() == KeyEvent::KEY_SPACE)\n    {\n        spaceBarPressed = true;\n    }\n}\n\nvoid SoftBodyCutFEM2DApp::keyUp(KeyEvent event)\n{\n    App::keyUp(event);\n    if (event.isHandled()) return;\n    if (event.getCode() == KeyEvent::KEY_SPACE)\n    {\n        spaceBarPressed = false;\n    }\n}\n\nvoid SoftBodyCutFEM2DApp::mouseDown( MouseEvent event )\n{\n\tApp::mouseDown(event);\n}\n\nvoid SoftBodyCutFEM2DApp::update()\n{\n    //perform time stepping\n    if (spaceBarPressed) {\n        performStep(timestep);\n    }\n\n    //update transfer function editor\n\tvisualization.update();\n}\n\nvoid SoftBodyCutFEM2DApp::draw()\n{\n    using namespace ar::utils;\n    if (printMode)\n        gl::clear(Color(1, 1, 1));\n    else\n        gl::clear(Color(0, 0, 0));\n\t\n\t\n    // WINDOW SPACE\n    gl::disableDepthRead();\n    gl::disableDepthWrite();\n    gl::setMatricesWindow(getWindowSize(), true);\n\n    //grid bounds\n    int windowWidth = getWindow()->getWidth();\n    int windowHeight = getWindow()->getHeight();\n    int gridBoundary = 50;\n    int gridSize = std::min(windowWidth, windowHeight) - 2 * gridBoundary;\n    int gridOffsetX = windowWidth / 2;\n    int gridOffsetY = windowHeight / 2;\n\n    Color colors[3];\n    colors[FREE] = Color(1, 0, 0);\n    colors[NEUMANN] = Color(1, 1, 0);\n    colors[DIRICHLET] = Color(0, 1, 0.2);\n\n    // Draw sdf\n\tif (computationMode & (int)ComputationMode::COMPUTATION_MODE_GRID)\n\t{\n\t\tvisualization.gridDrawSdf();\n\t\tif (showGrid)\n\t\t\tvisualization.gridDrawGridLines();\n\t\tif (showGridSolution == GridVisualizationMode::GRID_VISUALIZATION_BOUNDARY)\n\t\t\tvisualization.gridDrawObjectBoundary();\n\t\tif (!gridSolver.hasSolution())\n\t\t\tvisualization.gridDrawBoundaryConditions(gridSolver.getGridDirichlet(), gridSolver.getGridNeumannX(), gridSolver.getGridNeumannY());\n\t\tif (gridSolver.hasSolution() && showGridSolution == GridVisualizationMode::GRID_VISUALIZATION_U) {\n\t\t\tgl::ScopedColor c;\n\t\t\tif (printMode)\n\t\t\t\tgl::color(0, 0, 0.5);\n\t\t\telse\n\t\t\t\tgl::color(1, 1, 1);\n\t\t\tvisualization.gridDrawDisplacements();\n\t\t}\n\t}\n\n    // Draw mesh\n    if (computationMode & (int)ComputationMode::COMPUTATION_MODE_MESH) {\n\t\tvisualization.meshDraw();\n    }\n\n\t// Draw ground\n\tif (enableCollision)\n\t{\n\t\tvisualization.drawGround(groundPlaneHeight, groundPlaneAngle);\n\t}\n\n    // Draw the background worker's status\n    if (worker && !worker->isDone()) {\n        //draw waiting animation\n        {\n            gl::ScopedModelMatrix scopedMatrix;\n            gl::ScopedColor scopedColor;\n            gl::translate(25, getWindowHeight() - 50);\n            int step; double dummy; step = static_cast<int>(std::modf(getElapsedSeconds(), &dummy) * 8);\n            for (int i = 0; i < 8; ++i) {\n                float c = ((i + step)%8) / 7.0f;\n                gl::color(c, c, c);\n                gl::drawSolidRoundedRect(Rectf(5, -2, 15, 2), 2);\n                gl::rotate(-2.0f * M_PI / 8.0f);\n            }\n        }\n        //draw status\n        gl::ScopedColor scopedColor;\n        if (printMode)\n            gl::color(0, 0, 0);\n        else\n            gl::color(1, 1, 1);\n        gl::drawString(worker->getStatus(), vec2(50, getWindowHeight() - 50));\n    }\n\n\t// Draw the interface\n\tvisualization.setTfeVisible(!printMode);\n\tparams->draw();\n\tvisualization.drawTransferFunctionEditor();\n}\n\nvoid SoftBodyCutFEM2DApp::reset()\n{\n    CI_LOG_I(\"reset\");\n    worker = nullptr;\n    step = 0;\n\n\t//reset solution\n\tresults = std::make_unique<SoftBody2DResults>();\n\n    //create and initialize grid\n    if (scene == Scene::SCENE_BAR)\n        initGridWithRect();\n    else if (scene == Scene::SCENE_TORUS)\n        initGridWithTorus();\n\n    //create and initialize tri mesh\n    if (scene == Scene::SCENE_BAR)\n        initTriMeshWithGrid();\n    else if (scene == Scene::SCENE_TORUS)\n        initTriMeshWithTorus();\n\n    //invalidate texture and mesh\n    invalidateRendering();\n}\n\nvoid SoftBodyCutFEM2DApp::invalidateRendering()\n{\n\tif (gridSolver.hasSolution())\n\t{\n\t\tvisualization.setGrid(gridSolver.getSdfReference(), gridSolver.getSdfSolution(), gridSolver.getUGridX(), gridSolver.getUGridY());\n\t} else\n\t{\n\t\tGridUtils2D::grid_t z = GridUtils2D::grid_t::Zero(gridSolver.getGridResolution(), gridSolver.getGridResolution());\n\t\tvisualization.setGrid(gridSolver.getSdfReference(), gridSolver.getSdfReference(), z, z);\n\t}\n\n\tauto& pos = meshSolver.hasSolution() ? meshSolver.getCurrentPositions() : meshSolver.getReferencePositions();\n\tvisualization.setMesh(pos, meshSolver.getTriangles(), meshSolver.getNodeStates());\n}\n\nvoid SoftBodyCutFEM2DApp::performStep(float stepsize)\n{\n\tif (stepsize == 0 && !enableDirichletBoundaries)\n\t{\n\t\tCI_LOG_E(\"Can't solve for static solution if dirichlet boundaries are disabled\");\n\t\treturn;\n\t}\n\n    if (worker != nullptr && !worker->isDone()) {\n        //still running\n        return;\n    }\n\n    //declare background task\n    std::function<void(BackgroundWorker*)> task = [this, stepsize](BackgroundWorker* worker) {\n        //pass arguments\n        meshSolver.setGravity(gravity.cast<real>());\n        meshSolver.setMaterialParameters(youngsModulus, poissonsRatio);\n        meshSolver.setMass(mass);\n        meshSolver.setDamping(dampingAlpha, dampingBeta);\n        meshSolver.setDenseLinearSolver(denseLinearSolverType);\n        meshSolver.setSparseLinearSolver(sparseLinearSolverType);\n        meshSolver.setTimeIntegrator(timeIntegratorType);\n        meshSolver.setUseSparseMatrices(useSparseMatrices);\n        meshSolver.setSparseSolveIterations(sparseSolverIterations);\n        meshSolver.setSparseSolveTolerance(sparseSolverTolerance);\n        meshSolver.setRotationCorrection(rotationCorrectionMode);\n        meshSolver.setTimestep(stepsize==0 ? 1 : stepsize);\n\t\tmeshSolver.setGroundPlane(groundPlaneHeight, groundPlaneAngle);\n\t\tmeshSolver.setEnableCollision(enableCollision);\n\t\tmeshSolver.setCollisionResolution(collisionResolutionMode);\n\t\tmeshSolver.setCollisionVelocityDamping(collisionVelocityDamping);\n        meshSolver.setGroundStiffness(groundStiffness_);\n        meshSolver.setCollisionSoftmaxAlpha(softmaxAlpha_);\n\n        gridSolver.setGravity(gravity.cast<real>());\n        gridSolver.setMaterialParameters(youngsModulus, poissonsRatio);\n        gridSolver.setMass(mass);\n        gridSolver.setDamping(dampingAlpha, dampingBeta);\n        gridSolver.setDenseLinearSolver(denseLinearSolverType);\n        gridSolver.setSparseLinearSolver(sparseLinearSolverType);\n        gridSolver.setTimeIntegrator(timeIntegratorType);\n        gridSolver.setUseSparseMatrices(useSparseMatrices);\n        gridSolver.setSparseSolveIterations(sparseSolverIterations);\n        gridSolver.setSparseSolveTolerance(sparseSolverTolerance);\n        gridSolver.setExplicitDiffusion(gridExplicitDiffusion);\n        gridSolver.setHardDirichletBoundaries(gridHardDirichletBoundaries);\n        gridSolver.setAdvectionMode(gridAdvectionMode);\n        gridSolver.setRotationCorrection(rotationCorrectionMode);\n        gridSolver.setTimestep(stepsize == 0 ? 1 : stepsize);\n\t\tgridSolver.setGroundPlane(groundPlaneHeight, groundPlaneAngle);\n\t\tgridSolver.setEnableCollision(enableCollision);\n\t\tgridSolver.setCollisionResolution(collisionResolutionMode);\n\t\tgridSolver.setCollisionVelocityDamping(collisionVelocityDamping);\n        gridSolver.setGroundStiffness(groundStiffness_);\n        gridSolver.setCollisionSoftmaxAlpha(softmaxAlpha_);\n\n\t\tresults->settings_ = gridSolver.getSettings();\n\n        //solve it\n        if (int(computationMode) & int(ComputationMode::COMPUTATION_MODE_MESH)) {\n            auto start1 = std::chrono::steady_clock::now();\n            if (stepsize == 0) {\n                meshSolver.solveStaticSolution(worker);\n                if (worker->isInterrupted()) return;\n\t\t\t\tinvalidateRendering();\n            }\n            else {\n                meshSolver.solveDynamicSolution(worker);\n                if (worker->isInterrupted()) return;\n\t\t\t\tinvalidateRendering();\n            }\n            auto duration1 = std::chrono::duration_cast<chrono::milliseconds>(std::chrono::steady_clock::now() - start1);\n            meshElapsedSeconds = duration1.count() / 1000.0;\n            results->meshResultsDisplacement_.push_back(meshSolver.getCurrentDisplacements());\n        }\n\n        if (int(computationMode) & int(ComputationMode::COMPUTATION_MODE_GRID)) {\n            auto start2 = std::chrono::steady_clock::now();\n            if (stepsize == 0) {\n                gridSolver.solveStaticSolution(worker);\n                if (worker->isInterrupted()) return;\n\t\t\t\tinvalidateRendering();\n            }\n            else {\n                gridSolver.solveDynamicSolution(worker);\n                if (worker->isInterrupted()) return;\n\t\t\t\tinvalidateRendering();\n            }\n            auto duration2 = std::chrono::duration_cast<chrono::milliseconds>(std::chrono::steady_clock::now() - start2);\n            gridElapsedSeconds = duration2.count() / 1000.0;\n            results->gridResultsSdf_.push_back(gridSolver.getSdfSolution());\n            results->gridResultsUxy_.push_back(gridSolver.getUSolution());\n        }\n\n\t\tresults->numSteps_++;\n    };\n\n    //start background worker\n    //worker = make_shared<BackgroundWorker>(task);\n\tBackgroundWorker w;\n\ttask(&w);\n\n    CI_LOG_I(\"Background worker started\");\n}\n\nvoid SoftBodyCutFEM2DApp::initGridWithTorus()\n{\n    gridSolver = SoftBodyGrid2D::CreateTorus(\n        torusOuterRadius, torusInnerRadius, gridResolution,\n\t\tenableDirichletBoundaries, Vector2(0, 0), neumannForce.cast<real>());\n    results->initGridReference(gridSolver);\n}\n\nvoid SoftBodyCutFEM2DApp::initGridWithRect()\n{\n    gridSolver = SoftBodyGrid2D::CreateBar(\n        rectCenter.cast<real>(), rectHalfSize.cast<real>(), gridResolution,\n        fitObjectToGrid, enableDirichletBoundaries, Vector2(0, 0), neumannForce.cast<real>());\n    results->initGridReference(gridSolver);\n}\n\nvoid SoftBodyCutFEM2DApp::initTriMeshWithTorus()\n{\n    meshSolver = SoftBodyMesh2D::CreateTorus(\n        torusOuterRadius, torusInnerRadius, \n        gridResolution, enableDirichletBoundaries, Vector2(0, 0), neumannForce.cast<real>().eval());\n    results->initMeshReference(meshSolver);\n}\n\nvoid SoftBodyCutFEM2DApp::initTriMeshWithGrid()\n{\n    meshSolver = SoftBodyMesh2D::CreateBar(\n        rectCenter.cast<real>(), rectHalfSize.cast<real>(),\n        gridResolution, fitObjectToGrid,\n\t\tenableDirichletBoundaries, Vector2(0, 0), neumannForce.cast<real>());\n    results->initMeshReference(meshSolver);\n}\n\nvoid SoftBodyCutFEM2DApp::saveResults()\n{\n\t//get save path\n\tfs::path path = getSaveFilePath(fs::path(\"../saves/\"), std::vector<std::string>({ \".dat\" }));\n\tif (path.empty()) {\n\t\tCI_LOG_W(\"Saving cancelled by the user\");\n\t\treturn;\n\t}\n\tstd::string pathS = path.string();\n\tCI_LOG_I(\"Save results to \" << pathS);\n\n\t//save it\n\tstd::ofstream ofs(pathS, std::ofstream::binary | std::ofstream::trunc);\n\tboost::archive::binary_oarchive oa(ofs);\n\toa << results;\n\tCI_LOG_I(\"Results saved\");\n}\n\n#if 1\nCINDER_APP( SoftBodyCutFEM2DApp, RendererGl, [&](App::Settings *settings)\n{\n\tsettings->setWindowSize(1280, 720);\n} )\n#endif\n", "meta": {"hexsha": "3e6b7b4b0308ce66276566b078348e83fe0e2dff", "size": 30226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SoftBodyFEMApp/SoftBodyFEM2DApp.cpp", "max_stars_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_stars_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-03-08T18:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T20:32:56.000Z", "max_issues_repo_path": "SoftBodyFEMApp/SoftBodyFEM2DApp.cpp", "max_issues_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_issues_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SoftBodyFEMApp/SoftBodyFEM2DApp.cpp", "max_forks_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_forks_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-26T01:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T13:32:46.000Z", "avg_line_length": 41.0679347826, "max_line_length": 198, "alphanum_fraction": 0.6943360021, "num_tokens": 7804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5234360144074794}}
{"text": "//  (C) Copyright Nick Thompson 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <random>\n#include <array>\n#include <vector>\n#include <iostream>\n#include <benchmark/benchmark.h>\n#include <boost/math/tools/quartic_roots.hpp>\n\nusing boost::math::tools::quartic_roots;\n\ntemplate<class Real>\nvoid QuarticRoots(benchmark::State& state)\n{\n    std::random_device rd;\n    auto seed = rd();\n    // This seed generates 3 real roots:\n    //uint32_t seed = 416683252;\n    std::mt19937_64 mt(seed);\n    std::uniform_real_distribution<Real> unif(-10, 10);\n\n    Real a = unif(mt);\n    Real b = unif(mt);\n    Real c = unif(mt);\n    Real d = unif(mt);\n    Real e = unif(mt);\n    for (auto _ : state)\n    {\n        auto roots = quartic_roots(a,b,c,d, e);\n        benchmark::DoNotOptimize(roots[0]);\n    }\n}\n\nBENCHMARK_TEMPLATE(QuarticRoots, float);\nBENCHMARK_TEMPLATE(QuarticRoots, double);\nBENCHMARK_TEMPLATE(QuarticRoots, long double);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "fe2f3ffbc15f0f37bf1787753737316cabcd8470", "size": 1097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reporting/performance/quartic_roots_performance.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": "reporting/performance/quartic_roots_performance.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": "reporting/performance/quartic_roots_performance.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": 26.119047619, "max_line_length": 68, "alphanum_fraction": 0.6864175023, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5234327866618791}}
{"text": "#include <gtest/gtest.h>\n#include <Eigen/Dense>\n\n#include \"refill/filters/particle_filter.h\"\n#include \"refill/measurement_models/linear_measurement_model.h\"\n#include \"refill/system_models/linear_system_model.h\"\n#include \"refill/utility/resample_methods.h\"\n\nnamespace refill {\n\nclass ParticleFilterTest : public ::testing::Test {\n public:\n  ParticleFilterTest()\n      : initial_dist_(1),\n        system_noise_(1),\n        measurement_noise_(1),\n        system_model_(2 * Eigen::MatrixXd::Identity(1, 1),\n                      system_noise_, Eigen::MatrixXd::Identity(1, 1)),\n        measurement_model_(Eigen::MatrixXd::Identity(1, 1),\n                           measurement_noise_),\n        expected_initial_particles_(1, 2),\n        expected_propagated_particles_(1, 2),\n        expected_propagated_particles_with_input_(1, 2),\n        expected_updated_weights_(Eigen::Vector2d::Constant(0.5)),\n        input_(Eigen::VectorXd::Constant(1, 1.0)),\n        measurement_(Eigen::VectorXd::Zero(1)) {\n    this->ResetRngs();\n\n    for (int i = 0; i < 2; ++i) {\n      expected_initial_particles_.col(i) = initial_dist_.drawSample();\n    }\n\n    Eigen::VectorXd likelihoods = measurement_model_.getLikelihoodVectorized(\n        expected_initial_particles_, measurement_);\n    expected_updated_weights_ =\n        expected_updated_weights_.cwiseProduct(likelihoods);\n    expected_updated_weights_ /= expected_updated_weights_.sum();\n\n    for (int i = 0; i < 2; ++i) {\n      expected_propagated_particles_.col(i) = 2\n          * expected_initial_particles_.col(i)\n          + system_model_.getNoise()->drawSample();\n      expected_propagated_particles_with_input_.col(i) =\n          expected_propagated_particles_.col(i) + input_;\n    }\n\n    this->ResetRngs();\n  }\n\n  void ResetRngs() {\n    std::mt19937 rng(1);\n    initial_dist_.setRng(rng);\n    system_noise_.setRng(rng);\n    measurement_noise_.setRng(rng);\n\n    system_model_.getNoise()->setRng(rng);\n    measurement_model_.getNoise()->setRng(rng);\n  }\n\n  GaussianDistribution initial_dist_;\n  GaussianDistribution system_noise_;\n  GaussianDistribution measurement_noise_;\n\n  LinearSystemModel system_model_;\n  LinearMeasurementModel measurement_model_;\n\n  Eigen::MatrixXd expected_initial_particles_;\n  Eigen::MatrixXd expected_propagated_particles_;\n  Eigen::MatrixXd expected_propagated_particles_with_input_;\n  Eigen::Vector2d expected_updated_weights_;\n\n  Eigen::VectorXd input_;\n  Eigen::VectorXd measurement_;\n};\n\nTEST_F(ParticleFilterTest, DefaultConstructorTest) {\n  ParticleFilter filter;\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::MatrixXd::Zero(0, 0), particles);\n  EXPECT_EQ(Eigen::VectorXd::Zero(0), weights);\n}\n\nTEST_F(ParticleFilterTest, TwoArgumentsConstructorTest) {\n  ParticleFilter filter(2, &initial_dist_);\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(expected_initial_particles_, particles);\n}\n\nTEST_F(ParticleFilterTest, ThreeArgumentConstructorTest) {\n  ParticleFilter filter(2, &initial_dist_, SamplingFunctorBase());\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(expected_initial_particles_, particles);\n\n  filter.update(measurement_model_, measurement_);\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(expected_updated_weights_, weights);\n  EXPECT_EQ(expected_initial_particles_, particles);\n}\n\nTEST_F(ParticleFilterTest, FiveArgumentsConstructorTest) {\n  ParticleFilter filter(\n      2,\n      &initial_dist_,\n      SamplingFunctorBase(),\n      std::unique_ptr<LinearSystemModel>(new LinearSystemModel(system_model_)),\n      std::unique_ptr<Likelihood>(\n          new LinearMeasurementModel(measurement_model_)));\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(expected_initial_particles_, particles);\n\n  filter.predict();\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(expected_propagated_particles_, particles);\n\n  filter.setParticles(expected_initial_particles_);\n  filter.update(measurement_);\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(expected_updated_weights_, weights);\n  EXPECT_EQ(expected_initial_particles_, particles);\n}\n\nTEST_F(ParticleFilterTest, TwoArgumentsParameterSetterTest) {\n  ParticleFilter filter;\n  filter.setFilterParameters(2, &initial_dist_);\n\n  Eigen::VectorXd weights;\n  Eigen::MatrixXd particles;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(expected_initial_particles_, particles);\n}\n\nTEST_F(ParticleFilterTest, ThreeArgumentsParameterSetterTest) {\n  ParticleFilter filter;\n  filter.setFilterParameters(2, &initial_dist_, SamplingFunctorBase());\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.update(measurement_model_, measurement_);\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(expected_updated_weights_, weights);\n  EXPECT_EQ(expected_initial_particles_, particles);\n}\n\nTEST_F(ParticleFilterTest, FiveArgumentsParameterSetterTest) {\n  ParticleFilter filter;\n  filter.setFilterParameters(\n      2,\n      &initial_dist_,\n      SamplingFunctorBase(),\n      std::unique_ptr<LinearSystemModel>(new LinearSystemModel(system_model_)),\n      std::unique_ptr<Likelihood>(\n          new LinearMeasurementModel(measurement_model_)));\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(expected_initial_particles_, particles);\n\n  filter.predict();\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(expected_propagated_particles_, particles);\n\n  filter.setParticles(expected_initial_particles_);\n  filter.update(measurement_);\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(expected_updated_weights_, weights);\n  EXPECT_EQ(expected_initial_particles_, particles);\n}\n\nTEST_F(ParticleFilterTest, SetParticlesTest) {\n  ParticleFilter filter(2, &initial_dist_);\n  filter.setParticles(Eigen::MatrixXd::Zero(1, 2));\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(Eigen::MatrixXd::Zero(1, 2), particles);\n}\n\nTEST_F(ParticleFilterTest, SetParticlesAndWeightsTest) {\n  ParticleFilter filter(2, &initial_dist_);\n  filter.setParticlesAndWeights(Eigen::MatrixXd::Constant(1, 2, 2),\n                                Eigen::Vector2d::Constant(0.5));\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(Eigen::MatrixXd::Constant(1, 2, 2), particles);\n}\n\nTEST_F(ParticleFilterTest, ReinitializeParticlesTest) {\n  ParticleFilter filter(2, &initial_dist_);\n  filter.setParticlesAndWeights(Eigen::MatrixXd::Constant(1, 2, 2),\n                                Eigen::Vector2d::Constant(0.5));\n\n  ResetRngs();\n  filter.reinitializeParticles(&initial_dist_);\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(expected_initial_particles_, particles);\n}\n\nTEST_F(ParticleFilterTest, DefaultPredictorTest) {\n  ParticleFilter filter(\n      2,\n      &initial_dist_,\n      SamplingFunctorBase(),\n      std::unique_ptr<LinearSystemModel>(new LinearSystemModel(system_model_)),\n      std::unique_ptr<Likelihood>(\n          new LinearMeasurementModel(measurement_model_)));\n\n  filter.predict();\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(expected_propagated_particles_, particles);\n}\n\nTEST_F(ParticleFilterTest, DefaultPredictorWithInputTest) {\n  ParticleFilter filter(\n      2,\n      &initial_dist_,\n      SamplingFunctorBase(),\n      std::unique_ptr<LinearSystemModel>(new LinearSystemModel(system_model_)),\n      std::unique_ptr<Likelihood>(\n          new LinearMeasurementModel(measurement_model_)));\n\n  filter.predict(input_);\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(expected_propagated_particles_with_input_, particles);\n}\n\nTEST_F(ParticleFilterTest, SystemModelPredictionTest) {\n  ParticleFilter filter(2, &initial_dist_);\n  filter.predict(system_model_);\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(expected_propagated_particles_, particles);\n}\n\nTEST_F(ParticleFilterTest, SystemModelWithInputPredictionTest) {\n  ParticleFilter filter(2, &initial_dist_);\n  filter.predict(system_model_, input_);\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(expected_propagated_particles_with_input_, particles);\n}\n\nTEST_F(ParticleFilterTest, DefaultUpdateTest) {\n  ParticleFilter filter(\n      2,\n      &initial_dist_,\n      SamplingFunctorBase(),\n      std::unique_ptr<LinearSystemModel>(new LinearSystemModel(system_model_)),\n      std::unique_ptr<Likelihood>(\n          new LinearMeasurementModel(measurement_model_)));\n  filter.update(measurement_);\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(expected_updated_weights_, weights);\n  EXPECT_EQ(expected_initial_particles_, particles);\n}\n\nTEST_F(ParticleFilterTest, MeasurementModelUpdateTest) {\n  ParticleFilter filter(2, &initial_dist_);\n  filter.update(measurement_model_, measurement_);\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(expected_updated_weights_, weights);\n  EXPECT_EQ(expected_initial_particles_, particles);\n}\n\nTEST_F(ParticleFilterTest, GetExpectationTest) {\n  ParticleFilter filter(2, &initial_dist_);\n  filter.setParticlesAndWeights(Eigen::MatrixXd::Constant(1, 2, 1.0),\n                                Eigen::VectorXd::Constant(2, 0.5));\n\n  Eigen::VectorXd expectation = filter.getExpectation();\n\n  EXPECT_EQ(Eigen::VectorXd::Constant(1, 1.0), expectation);\n}\n\nTEST_F(ParticleFilterTest, GetMaxWeightSampleTest) {\n  ParticleFilter filter(2, &initial_dist_);\n\n  Eigen::MatrixXd particles(1, 2);\n  Eigen::VectorXd weights(2);\n\n  particles << 1.0, 2.0;\n  weights << 0.75, 0.25;\n\n  filter.setParticlesAndWeights(particles, weights);\n\n  Eigen::VectorXd max_weight_particle = filter.getMaxWeightParticle();\n\n  EXPECT_EQ(Eigen::VectorXd::Constant(1, 1.0), max_weight_particle);\n}\n\nTEST_F(ParticleFilterTest, GetParticlesTest) {\n  ParticleFilter filter(2, &initial_dist_);\n\n  Eigen::MatrixXd particles = filter.getParticles();\n\n  EXPECT_EQ(expected_initial_particles_, particles);\n}\n\nTEST_F(ParticleFilterTest, GetParticlesAndWeightsTest) {\n  ParticleFilter filter(2, &initial_dist_);\n\n  Eigen::MatrixXd particles;\n  Eigen::VectorXd weights;\n\n  filter.getParticlesAndWeights(&particles, &weights);\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(0.5), weights);\n  EXPECT_EQ(expected_initial_particles_, particles);\n}\n\n}  // namespace refill\n", "meta": {"hexsha": "9655319a7f1986a2cdc1fe70c39a616fdbaafbeb", "size": 11905, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/particle_filter_test.cc", "max_stars_repo_name": "jwidauer/refill", "max_stars_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-13T07:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T11:26:34.000Z", "max_issues_repo_path": "src/tests/particle_filter_test.cc", "max_issues_repo_name": "jwidauer/refill", "max_issues_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/particle_filter_test.cc", "max_forks_repo_name": "jwidauer/refill", "max_forks_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T13:21:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T20:33:20.000Z", "avg_line_length": 29.7625, "max_line_length": 79, "alphanum_fraction": 0.7507769845, "num_tokens": 2751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5234327866618791}}
{"text": "#include <boost/math/special_functions/airy.hpp>\n", "meta": {"hexsha": "8de3be21e373dd782eed37a185411d30e53ecd5c", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_airy.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_airy.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_airy.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8163265306, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5234327808865434}}
{"text": "#include \"MovementSystem.h\"\n#include <iostream>\n#include <Eigen/Dense>\n\nMovementSystem::MovementSystem(entt::registry& registry) : System(registry) {}\n\nvoid MovementSystem::update(double dt)\n{\n\tmRegistry.view<moveCommand, position, stats>().each([&](auto entity, auto& moveCom, auto& pos, auto& statsComponent) {\n\t\tpos.x += (float)moveCom.dir(0) * statsComponent.movespeed * (float)dt;\n\t\tpos.y += (float)moveCom.dir(1) * statsComponent.movespeed * (float)dt;\n\t\tmRegistry.remove<moveCommand>(entity);\n\t\t}); \n}\n", "meta": {"hexsha": "1e614b99eaff6af6682b46fe698a28ac333de465", "size": 509, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Game/src/sys/MovementSystem.cpp", "max_stars_repo_name": "rguessford/SDLapp", "max_stars_repo_head_hexsha": "c43983ff28f48cf2f3da127bf568f399a90e0e13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-02T13:39:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T13:39:50.000Z", "max_issues_repo_path": "Game/src/sys/MovementSystem.cpp", "max_issues_repo_name": "rguessford/SDLapp", "max_issues_repo_head_hexsha": "c43983ff28f48cf2f3da127bf568f399a90e0e13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Game/src/sys/MovementSystem.cpp", "max_forks_repo_name": "rguessford/SDLapp", "max_forks_repo_head_hexsha": "c43983ff28f48cf2f3da127bf568f399a90e0e13", "max_forks_repo_licenses": ["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.9333333333, "max_line_length": 119, "alphanum_fraction": 0.721021611, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5234327698430352}}
{"text": "#include <Eigen/Dense>\n#include<dart/dart.hpp>\n#include \"Parameter.h\"\n#include \"Environment/EnvironmentHelper.h\"\n#include \"Helper/Functions.h\"\n\ndouble getDeepMimicReward(SkeletonPtr physicsSkel, SkeletonPtr kinematicsSkel){\n\t// Position and velocities differences\n\tEigen::VectorXd p_diff = physicsSkel->getPositionDifferences(kinematicsSkel->getPositions(), physicsSkel->getPositions());\n\tEigen::VectorXd v_diff = physicsSkel->getPositionDifferences(kinematicsSkel->getVelocities(), physicsSkel->getVelocities());\n\tEigen::VectorXd p_diff_reward(Parameter::rewardBodies.size() * 3);\n\tEigen::VectorXd v_diff_reward(Parameter::rewardBodies.size() * 3);\n\n\tfor(int i = 0; i < (int)Parameter::rewardBodies.size(); i++){\n\t\tint idx = physicsSkel->getBodyNode(Parameter::rewardBodies[i])->getParentJoint()->getIndexInSkeleton(0);\n\t\tp_diff_reward.segment<3>(3*i) = p_diff.segment<3>(idx);\n\t\tv_diff_reward.segment<3>(3*i) = v_diff.segment<3>(idx);\n\t}\n\n\t// COM differences\n\tEigen::Vector3d com_diff = physicsSkel->getCOM() - kinematicsSkel->getCOM();\n\n\t// End-effector position differences\n\tEigen::VectorXd ee_diff(Parameter::endEffectors.size() * 3);\n\tfor (int i = 0; i < (int)Parameter::endEffectors.size(); i++){\n\t\tEigen::Isometry3d diff = physicsSkel->getBodyNode(Parameter::endEffectors[i])->getWorldTransform().inverse() * \n\t\t\tkinematicsSkel->getBodyNode(Parameter::endEffectors[i])->getWorldTransform();\n\t\tee_diff.segment<3>(3 * i) = diff.translation();\n\t}\n\n\t// Evaluate total reward\n\tdouble scale = 1.0;\n\tdouble sig_p = 0.1 * scale;   // 2\n\tdouble sig_v = 1.0 * scale;   // 3\n\tdouble sig_com = 0.3 * scale; // 4\n\tdouble sig_ee = 0.3 * scale;  // 8\n\n\tdouble r_p = DPhy::exp_of_squared(p_diff_reward, sig_p);\n\tdouble r_v = DPhy::exp_of_squared(v_diff_reward, sig_v);\n\tdouble r_com = DPhy::exp_of_squared(com_diff, sig_com);\n\tdouble r_ee = DPhy::exp_of_squared(ee_diff, sig_ee);\n\n\tdouble r_tot = r_p*r_v*r_com*r_ee;\n\tif(dart::math::isNan(r_tot)) return 0;\n\treturn r_tot;\n}\n\nbool getDeepMimicEarlyTerminate(SkeletonPtr physicsSkel, SkeletonPtr kinematicsSkel, int flag){\n\t// Nan check\n\tEigen::VectorXd position = physicsSkel->getPositions();\n\tEigen::VectorXd velocity = physicsSkel->getVelocities();\n\tif(dart::math::isNan(position) || dart::math::isNan(velocity)){\n\t\treturn true;\n\t}\n\n\t// Early termination\n\t// Height limit\n\tdouble root_y = position[4];\n\tif (flag&ROOT_HEIGHT && (root_y < Parameter::rootHeightLowerLimit || root_y > Parameter::rootHeightUpperLimit)){\n//\t\tthis->mTerminationReason = TerminationReason::ROOT_HEIGHT;\n\t\treturn true;\n\t}\n\n\t// root distance limit\n\tEigen::Isometry3d root_diff = physicsSkel->getRootBodyNode()->getWorldTransform().inverse()\n\t\t* kinematicsSkel->getRootBodyNode()->getWorldTransform();\n\tEigen::Vector3d root_pos_diff = root_diff.translation();\n\tif (flag&ROOT_DIFF && (root_pos_diff.norm() > Parameter::rootDiffThreshold)){\n//\t\tthis->mTerminationReason = TerminationReason::ROOT_DIFF;\n\t\treturn true;\n\t}\n\n\t// root rotation limit\n\tEigen::AngleAxisd root_diff_aa(root_diff.linear());\n\tdouble angle = DPhy::RadianClamp(Eigen::AngleAxisd(root_diff.linear()).angle());\n\tif (flag&ROOT_ANGLE_DIFF && (std::abs(angle) > Parameter::rootAngleDiffThreshold)){\n//\t\tthis->mTerminationReason = TerminationReason::ROOT_ANGLE_DIFF;\n\t\treturn true;\n\t}\n\treturn false;\n}\n", "meta": {"hexsha": "31c5ce828bd2ec4c76c0fa46f9eeaac190a848fd", "size": 3281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bipedenv/cpp/Environment/EnvironmentHelper.cpp", "max_stars_repo_name": "snumrl/DistributedDeepMimic", "max_stars_repo_head_hexsha": "364d07dbdd5378b6d46d944e472e1632712ef5f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bipedenv/cpp/Environment/EnvironmentHelper.cpp", "max_issues_repo_name": "snumrl/DistributedDeepMimic", "max_issues_repo_head_hexsha": "364d07dbdd5378b6d46d944e472e1632712ef5f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bipedenv/cpp/Environment/EnvironmentHelper.cpp", "max_forks_repo_name": "snumrl/DistributedDeepMimic", "max_forks_repo_head_hexsha": "364d07dbdd5378b6d46d944e472e1632712ef5f6", "max_forks_repo_licenses": ["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.012195122, "max_line_length": 125, "alphanum_fraction": 0.7403230722, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.52338039336204}}
{"text": "#pragma once\n\n#if defined(SICO_USE_HOLTHAUS_UNITS)\n\n#pragma warning(push)\n#pragma warning(disable : 4514) // deleted inline functions\n#pragma warning(disable : 4710) // deleted inline functions\n#pragma warning(disable : 4820) // fill bytes in time.h\n#include <units/units.h>\n#pragma warning(pop)\nnamespace sico {\nnamespace literals = units::literals;\n\nusing meters     = units::length::meter_t;\nusing meters_ps  = units::velocity::meters_per_second_t;\nusing meters_ps2 = units::acceleration::meters_per_second_squared_t;\nusing radians    = units::angle::radian_t;\nusing radians_ps = units::angular_velocity::radians_per_second_t;\nusing degrees    = units::angle::degree_t;\nusing seconds    = units::time::second_t;\n\ntemplate<class U>\ndouble raw(U const& v)\n{\n    return v.value();\n}\n\n} // namespace sico\n#elif defined(SICO_USE_BOOST_UNITS)\n#include <boost/units/cmath.hpp>\n#include <boost/units/io.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/angle/degrees.hpp>\n#include <boost/units/systems/si/acceleration.hpp>\n#include <boost/units/systems/si/angular_velocity.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/plane_angle.hpp>\n#include <boost/units/systems/si/time.hpp>\n#include <boost/units/systems/si/velocity.hpp>\n#include <cmath>\n\nnamespace sico {\nnamespace units = boost::units;\ntemplate<typename T>\nstruct q : units::quantity<T> {\n    explicit q(double v = 0.)\n        : units::quantity<T>(v * T::unit())\n    {\n    }\n    q(units::quantity<T> const& o)\n        : units::quantity<T>(o)\n    {\n    }\n    template<typename T2>\n    q(units::quantity<T2> const& o);\n    explicit operator double() const { return value(); }\n    template<typename T2>\n    q<T>& operator=(units::quantity<T2> o)\n    {\n        *this = (q<T>)o;\n        return *this;\n    }\n    template<typename T2>\n    operator units::quantity<T2>() const;\n};\nusing meters     = q<units::si::length>;\nusing meters_ps  = q<units::si::velocity>;\nusing meters_ps2 = q<units::si::acceleration>;\nusing radians    = q<units::si::plane_angle>;\nusing radians_ps = q<units::si::angular_velocity>;\nusing degrees    = q<units::degree::plane_angle>;\nusing seconds    = q<units::si::time>;\ntemplate<typename T>\ndouble raw(units::quantity<T> const& v)\n{\n    return v.value();\n}\ntemplate<>\ntemplate<>\ninline q<units::si::plane_angle>::q(units::quantity<units::degree::plane_angle> const& v)\n    : q<units::si::plane_angle>(v.value() * 0.01745329251994329576923690768489)\n{\n}\ntemplate<>\ntemplate<>\ninline q<units::degree::plane_angle>::q(units::quantity<units::si::plane_angle> const& v)\n    : q<units::degree::plane_angle>(v.value() * 57.295779513082320876798154814105)\n{\n}\n/*template<>\ntemplate<>\ninline radians::operator units::quantity<units::degree::plane_angle>() const\n{\n    return degrees { value() * 57.295779513082320876798154814105 };\n}\ntemplate<>\ntemplate<>\ninline degrees::operator units::quantity<units::si::plane_angle>() const\n{\n    return radians { value() * 0.01745329251994329576923690768489 };\n}*/\nnamespace literals {\ninline meters operator\"\" _m(long double v)\n{\n    return meters((double)v);\n}\ninline seconds operator\"\" _s(long double v)\n{\n    return seconds { (double)v };\n}\ninline degrees operator\"\" _deg(long double v)\n{\n    return degrees { (double)v };\n}\ninline radians operator\"\" _rad(long double v)\n{\n    return radians { (double)v };\n}\ninline meters operator\"\" _m(unsigned long long int v)\n{\n    return meters { (double)v };\n}\ninline seconds operator\"\" _s(unsigned long long int v)\n{\n    return seconds { (double)v };\n}\ninline degrees operator\"\" _deg(unsigned long long int v)\n{\n    return degrees { (double)v };\n}\ninline radians operator\"\" _rad(unsigned long long int v)\n{\n    return radians { (double)v };\n}\n} // namespace literals\n} // namespace sico\n\n#else\n#include <cmath>\n#include <ostream>\n\nnamespace sico {\nnamespace units {\n/// basic quantity class\ntemplate<typename T>\nstruct q {\n    q()\n        : v(0)\n    {\n    }\n    q(double v)\n        : v(v)\n    {\n    }\n    double   v;\n    explicit operator double() const { return v; }\n\n    q  operator+(q const& o) const { return { v + o.v }; }\n    q& operator+=(q const& o)\n    {\n        v += o.v;\n        return *this;\n    }\n    q  operator-(q const& o) const { return { v - o.v }; }\n    q& operator-=(q const& o)\n    {\n        v -= o.v;\n        return *this;\n    }\n    q  operator-() const { return { -v }; }\n    q  operator*(double f) const { return { v * f }; }\n    q& operator*=(double f)\n    {\n        v *= f;\n        return *this;\n    }\n    q  operator/(double f) const { return { v / f }; }\n    q& operator/=(double f)\n    {\n        v /= f;\n        return *this;\n    }\n    bool operator>(q const& o) const { return { v > o.v }; }\n    bool operator>=(q const& o) const { return { v >= o.v }; }\n    bool operator<(q const& o) const { return { v < o.v }; }\n    bool operator<=(q const& o) const { return { v <= o.v }; }\n    bool operator==(q const& o) const { return { v == o.v }; }\n    bool operator!=(q const& o) const { return { v != o.v }; }\n    template<typename T2>\n    operator q<T2>() const;\n};\ntemplate<typename T>\nq<T> operator+(double f, q<T> const& u)\n{\n    return u + f;\n}\ntemplate<typename T>\nq<T> operator-(double f, q<T> const& u)\n{\n    return f + (-u);\n}\ntemplate<typename T>\nq<T> operator*(double f, q<T> const& u)\n{\n    return u * f;\n}\ntemplate<typename T>\nq<T> operator/(double f, q<T> const& u)\n{\n    return { f / u.v };\n}\ntemplate<typename T>\nq<T> abs(q<T> const& t)\n{\n    return { std::abs(t.v) };\n}\n\nstruct meter {\n};\nstruct meter_per_second {\n};\nstruct meter_per_second_squared {\n};\nstruct radians_per_second {\n};\nstruct second {\n};\nstruct radian {\n};\nstruct degree {\n};\n} // namespace units\n\ntemplate<class U>\ndouble raw(units::q<U> const& v)\n{\n    return v.v;\n}\n\nusing meters     = units::q<units::meter>;\nusing meters_ps  = units::q<units::meter_per_second>;\nusing meters_ps2 = units::q<units::meter_per_second_squared>;\nusing radians_ps = units::q<units::radians_per_second>;\nusing seconds    = units::q<units::second>;\nusing radians    = units::q<units::radian>;\nusing degrees    = units::q<units::degree>;\n\nnamespace units {\ninline std::ostream& operator<<(std::ostream& os, meters const& u)\n{\n    return os << u.v << \" m\";\n}\ninline std::ostream& operator<<(std::ostream& os, meters_ps const& u)\n{\n    return os << u.v << \" m/s\";\n}\ninline std::ostream& operator<<(std::ostream& os, seconds const& u)\n{\n    return os << u.v << \" s\";\n}\ninline std::ostream& operator<<(std::ostream& os, radians const& u)\n{\n    return os << u.v << \" rad\";\n}\ninline std::ostream& operator<<(std::ostream& os, degrees const& u)\n{\n    return os << u.v << \" deg\";\n}\ntemplate<>\ntemplate<>\ninline q<radian>::operator q<degree>() const\n{\n    return { v * 57.295779513082320876798154814105 };\n}\ntemplate<>\ntemplate<>\ninline q<degree>::operator q<radian>() const\n{\n    return { v * 0.01745329251994329576923690768489 };\n}\n} // namespace units\ninline meters operator*(meters_ps const& v, seconds const& s)\n{\n    return { v.v * s.v };\n}\ninline meters_ps operator*(meters_ps2 const& v, seconds const& s)\n{\n    return { v.v * s.v };\n}\ninline meters_ps operator/(meters const& v, seconds const& s)\n{\n    return { v.v / s.v };\n}\ninline meters_ps2 operator/(meters_ps const& v, seconds const& s)\n{\n    return { v.v / s.v };\n}\nnamespace literals {\ninline meters operator\"\" _m(long double v)\n{\n    return { (double)v };\n}\ninline seconds operator\"\" _s(long double v)\n{\n    return { (double)v };\n}\ninline degrees operator\"\" _deg(long double v)\n{\n    return { (double)v };\n}\ninline radians operator\"\" _rad(long double v)\n{\n    return { (double)v };\n}\ninline meters operator\"\" _m(unsigned long long int v)\n{\n    return { (double)v };\n}\ninline seconds operator\"\" _s(unsigned long long int v)\n{\n    return { (double)v };\n}\ninline degrees operator\"\" _deg(unsigned long long int v)\n{\n    return { (double)v };\n}\ninline radians operator\"\" _rad(unsigned long long int v)\n{\n    return { (double)v };\n}\n} // namespace literals\n} // namespace sico\n#endif\n\nnamespace sico {\n\n/// Used to compare positions to the millimeter\ninline bool approx_eq(meters const& v1, meters const& v2, meters const& p = meters(0.001))\n{\n    return abs(v1 - v2) < p;\n}\n/// Used to compare lat/lon in radians with around 6 millimiters precision\ninline bool approx_eq(radians const& v1, radians const& v2, radians const& p = radians(1e-9))\n{\n    return abs(v1 - v2) < p;\n}\n\n} // namespace sico\n\n//\n// Simulation-Coordinates library\n// Author F.Jacomme\n// MIT Licensed\n//", "meta": {"hexsha": "e1dec7f04c38fcf71c34736f7d4144e9312cd0fa", "size": 8518, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sico/types/units.hpp", "max_stars_repo_name": "fjacomme/sico", "max_stars_repo_head_hexsha": "501b8f08313e4394ac8585167b74374e2ae3da09", "max_stars_repo_licenses": ["MIT"], "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/sico/types/units.hpp", "max_issues_repo_name": "fjacomme/sico", "max_issues_repo_head_hexsha": "501b8f08313e4394ac8585167b74374e2ae3da09", "max_issues_repo_licenses": ["MIT"], "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/sico/types/units.hpp", "max_forks_repo_name": "fjacomme/sico", "max_forks_repo_head_hexsha": "501b8f08313e4394ac8585167b74374e2ae3da09", "max_forks_repo_licenses": ["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.0621468927, "max_line_length": 93, "alphanum_fraction": 0.6490960319, "num_tokens": 2345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.523369423716321}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/include/functions/sin.hpp>\n\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <complex>\n#include <nt2/sdk/complex/complex.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/i.hpp>\n\n#include <nt2/include/functions/mul_i.hpp>\n#include <nt2/include/functions/mul_minus_i.hpp>\n\nNT2_TEST_CASE_TPL ( sin,  NT2_REAL_TYPES)\n{\n\n  using nt2::sin;\n  using nt2::tag::sin_;\n  typedef std::complex<T> cT;\n  typedef typename nt2::meta::call<sin_(cT)>::type r_t;\n  typedef typename nt2:: meta::as_complex<T>::type wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(nt2::sin(cT(nt2::Inf<T>())), cT(nt2::Nan<T>()), 2);\n  NT2_TEST_ULP_EQUAL(nt2::sin(cT(nt2::Minf<T>())), cT(nt2::Nan<T>()), 2);\n  NT2_TEST_ULP_EQUAL(nt2::sin(cT(1, 1)),std::sin(cT(1.0, 1.0)), 2);\n  NT2_TEST_ULP_EQUAL(nt2::sin(cT(1, 2)),std::sin(cT(1.0, 2.0)), 2);\n  NT2_TEST_ULP_EQUAL(nt2::sin(cT(2, 1)),std::sin(cT(2.0, 1.0)), 2);\n  NT2_TEST_ULP_EQUAL(nt2::sin(cT(2, 2)),std::sin(cT(2.0, 2.0)), 2);\n  NT2_TEST_ULP_EQUAL(nt2::sin(cT(0, 1)),std::sin(cT(0.0, 1.0)), 2);\n  NT2_TEST_ULP_EQUAL(nt2::sin(cT(0, 2)),std::sin(cT(0.0, 2.0)), 2);\n  NT2_TEST_ULP_EQUAL(nt2::sin(cT(2, 0)),std::sin(cT(2.0, 0.0)), 2);\n\n  const int N = 20;\n  cT inputs[N] =\n    { cT(nt2::Zero<T>(),nt2::Zero<T>()),cT(nt2::Inf<T>(),nt2::Zero<T>()),cT(nt2::Minf<T>(),nt2::Zero<T>()),cT(nt2::Nan<T>(),nt2::Zero<T>()),\n      cT(nt2::Zero<T>(),nt2::Inf<T>()), cT(nt2::Inf<T>(),nt2::Inf<T>()), cT(nt2::Minf<T>(),nt2::Inf<T>()), cT(nt2::Nan<T>(),nt2::Inf<T>()),\n      cT(nt2::Zero<T>(),nt2::Minf<T>()),cT(nt2::Inf<T>(),nt2::Minf<T>()),cT(nt2::Minf<T>(),nt2::Minf<T>()),cT(nt2::Nan<T>(),nt2::Minf<T>()),\n      cT(nt2::Zero<T>(),nt2::Nan<T>()), cT(nt2::Inf<T>(),nt2::Nan<T>()), cT(nt2::Minf<T>(),nt2::Nan<T>()), cT(nt2::Nan<T>(),nt2::Nan<T>()),\n      cT(nt2::Zero<T>(),nt2::Pi <T>()), cT(nt2::Inf<T>(),nt2::Pi <T>()), cT(nt2::Minf<T>(),nt2::Pi <T>()), cT(nt2::Nan<T>(),nt2::Pi <T>()),\n    };\n\n  for(int i=0; i < N; i++)\n   {\n     NT2_TEST_ULP_EQUAL(nt2::sin(-inputs[i]), -nt2::sin(inputs[i]), 3.5);\n     NT2_TEST_ULP_EQUAL(nt2::sin(inputs[i]), nt2::mul_minus_i(nt2::sinh(nt2::mul_i(inputs[i]))), 3);\n   }\n } // end of test for floating_\n\n", "meta": {"hexsha": "62a5f71e96ab56535e16236b16c788017cb8bad0", "size": 3185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/trigonometric/unit/scalar/sin.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/type/complex/trigonometric/unit/scalar/sin.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/type/complex/trigonometric/unit/scalar/sin.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 45.5, "max_line_length": 140, "alphanum_fraction": 0.5896389325, "num_tokens": 1150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5233694159802919}}
{"text": "//Copyright (C) 2011 Pierre Moulon\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#ifndef LIBS_SVD_EIGENWRAPPER_H_\n#define LIBS_SVD_EIGENWRAPPER_H_\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\nnamespace EigenWrapper  {\n\n/// Solve the linear system Ax = 0 via SVD. Store the solution in x, such that\n/// ||x|| = 1.0. Return true if the ratio of singular value SV(0)/SV(N-2) < ratio.\n/// The return value allow to know if many solution are possible\n/// Destroys A and resizes x if necessary.\ntemplate <typename TMat, typename TVec>\nbool Nullspace(TMat *A, TVec *nullspace, double dRatio = 1e-5) {\n  if (A->rows() >= A->cols()) {\n    Eigen::JacobiSVD<TMat> svd(*A, Eigen::ComputeFullV);\n    (*nullspace) = svd.matrixV().col(A->cols()-1);\n    double a = svd.singularValues()(A->cols()-2);\n    double c = svd.singularValues()(0);\n    return !(a < dRatio * c);\n  }\n  // Extend A with rows of zeros to make it square. It's a hack, but is\n  // necessary until Eigen supports SVD with more columns than rows.\n  TMat A_extended(A->cols(), A->cols());\n  A_extended.block(A->rows(), 0, A->cols() - A->rows(), A->cols()).setZero();\n  A_extended.block(0,0, A->rows(), A->cols()) = (*A);\n  return Nullspace(&A_extended, nullspace);\n}\n\n/// Singular values of square matrix\ntemplate <typename TMat, typename TVec>\nvoid SingularValues(TMat *A, TVec *sing) {\n  Eigen::JacobiSVD<TMat> svd(*A);\n  *sing = svd.singularValues();\n}\n\n/// Solve the linear system Ax = 0 via SVD. Finds two solutions, x1 and x2, such\n/// that x1 is the best solution and x2 is the next best solution (in the L2\n/// norm sense). Store the solution in x1 and x2, such that ||x|| = 1.0. Return\n/// the singular value corresponding to the solution x1.  Destroys A and resizes\n/// x if necessary.\ntemplate <typename TMat, typename TVec1, typename TVec2>\ninline double Nullspace2(TMat *A, TVec1 *x1, TVec2 *x2) {\n  if (A->rows() >= A->cols()) {\n    Eigen::JacobiSVD<TMat> svd(*A,Eigen::ComputeFullV);\n    TMat V = svd.matrixV();\n    *x1 = V.col(A->cols() - 1);\n    *x2 = V.col(A->cols() - 2);\n    return svd.singularValues()(A->cols()-1);\n  }\n  // Extend A with rows of zeros to make it square. It's a hack, but is\n  // necessary until Eigen supports SVD with more columns than rows.\n  TMat A_extended(A->cols(), A->cols());\n  A_extended.block(A->rows(), 0, A->cols() - A->rows(), A->cols()).setZero();\n  A_extended.block(0,0, A->rows(), A->cols()) = (*A);\n  return Nullspace2(&A_extended, x1, x2);\n}\n\ntemplate <typename TMat>\ninline void EnforceRank2_3x3(const TMat & A, TMat * out)\n{\n  if (A.cols() == A.rows() && A.cols() == 3)\n  {\n    typedef Eigen::Matrix<double, 3, 3> Mat3;\n    Eigen::JacobiSVD<Mat3> USV(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::VectorXd d = USV.singularValues();\n    d[2] = 0.0;\n    (*out) = USV.matrixU() * d.asDiagonal() * USV.matrixV().transpose();\n  }\n}\n\n} // namespace EigenWrapper\n\n#endif  // LIBS_SVD_EIGENWRAPPER_H_\n", "meta": {"hexsha": "1ca4b515c311d75c77d50e13e6f3485836810a7e", "size": 3509, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "OrsaHomography/third_party/svd/eigenWrapper.hpp", "max_stars_repo_name": "alicevision/KVLD", "max_stars_repo_head_hexsha": "3323458197cb29223f3a09a7906c92aab0b3916b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2015-06-01T12:14:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-25T02:27:26.000Z", "max_issues_repo_path": "OrsaHomography/third_party/svd/eigenWrapper.hpp", "max_issues_repo_name": "Zhe-LIU-Imagine/MRMS_online", "max_issues_repo_head_hexsha": "fe406cc3aea20aa186e57c03e809773e922978aa", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-05-09T07:20:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T04:59:39.000Z", "max_forks_repo_path": "OrsaHomography/third_party/svd/eigenWrapper.hpp", "max_forks_repo_name": "Zhe-LIU-Imagine/KVLD", "max_forks_repo_head_hexsha": "77eb60c50a911c2c4bd9dc770ba8cce1cf33f6f2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-01-14T15:40:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T16:01:01.000Z", "avg_line_length": 38.9888888889, "max_line_length": 82, "alphanum_fraction": 0.6751211171, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5233694082442625}}
{"text": "#include <iostream>\n#include <cstring>\n#include <string>\n#include <iomanip>\n#include <vector>\n#include <cmath>\n#include <openssl/bn.h>\n#include <openssl/sha.h>\n#include <openssl/rand.h>\n#include <openssl/ossl_typ.h>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::cpp_dec_float;\nusing boost::multiprecision::cpp_int;\ntypedef boost::multiprecision::number<cpp_dec_float<100>> mp_type;  //\u0434\u043b\u044f \u0440\u0430\u0431\u043e\u0442\u044b \u0441 \u0431\u0435\u0441\u043a\u043e\u043d\u0435\u0447\u043d\u044b\u043c\u0438 \u0434\u0440\u043e\u0431\u044f\u043c\u0438 \u0432 \u043f\u043e\u043b\u0438\u043d\u043e\u043c\u0438\u0430\u043b\u044c\u043d\u043e\u0439 \u0444\u0443\u043d\u043a\u0446\u0438\u0438\n\n/* Split \u0441\u0442\u0440\u043e\u043a\u0438 \u043f\u043e \u043f\u0440\u043e\u0431\u0435\u043b\u0430\u043c */\nstd::vector<std::string> split(std::string line) {\n    std::vector<std::string> words;\n    std::string buffer = \"\";      //\u0431\u0443\u0444\u0444\u0435\u0440\u043d\u0430\u044f \u0441\u0442\u0440\u043e\u043a\u0430\n    for(int i=0; i <= line.size(); i++){\n        if(line[i] != ' '){      // \" \" \u0441\u043f\u043b\u0438\u0442\u0442\u0435\u0440\n            buffer += line[i];\n        }\n        else{\n            words.push_back(buffer);\n            buffer = \"\";\n        }\n    }\n    words.push_back(buffer);\n    return words;\n}\n\n/* \u0412\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 SHA-256 hash */\nstd::string sha256(const std::string str) {\n    unsigned char hash[SHA256_DIGEST_LENGTH];\n    SHA256_CTX sha256;\n    SHA256_Init(&sha256);\n    SHA256_Update(&sha256, str.c_str(), str.size());\n    SHA256_Final(hash, &sha256);\n    std::stringstream ss;\n    for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)\n    {\n        ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];\n    }\n    return ss.str();\n}\n\n/* \u0413\u0435\u043d\u0435\u0440\u0430\u0446\u0438\u044f \u043f\u0440\u0438\u0432\u0430\u0442\u043d\u043e\u0433\u043e \u043a\u043b\u044e\u0447\u0430 ECDSA \u0441urve25519 */\nstd::string curve25519_pr_key_gen() {\n    unsigned char buf[32];\n    RAND_bytes(buf, 32);  //\u0433\u0435\u043d\u0435\u0440\u0438\u0440\u0443\u0435\u043c 32 \u0440\u0430\u043d\u0434\u043e\u043c\u043d\u044b\u0445 \u0431\u0430\u0439\u0442\u0430\n    std::string s_buf;\n    s_buf += std::string(buf, buf+32);  //\u043f\u0435\u0440\u0435\u0432\u043e\u0434\u0438\u043c unsigned char buf \u0432 std::string\n    std::string curve25519_pr_key = sha256(s_buf);\n    return curve25519_pr_key;\n}\n\n/* \u0412\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u043f\u043e\u043b\u0438\u043d\u043e\u043c\u0430 n-1 \u0441\u0442\u0435\u043f\u0435\u043d\u0438 \u043e\u0442 x: f(x) = secret + a(1) * x + a(2) * x^2 + ... + a(n-1) * x^(n-1) */\nBIGNUM *polinom(std::vector<std::string> coefs, std::string secr, int x) {\n    BIGNUM *result = NULL;\n    BN_dec2bn(&result, \"0\");\n    int j = 1;  //\u0442\u0435\u043a\u0443\u0449\u0430\u044f \u0441\u0442\u0435\u043f\u0435\u043d\u044c x\n\n    BIGNUM *sum = NULL;  //\u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u043f\u043e\u043b\u0438\u043d\u043e\u043c\u0430 \u0431\u0435\u0437 \u0441\u043b\u043e\u0436\u0435\u043d\u0438\u044f \u0441 \u0441\u0435\u043a\u0440\u0435\u0442\u043e\u043c\n    BN_dec2bn(&sum, \"0\");\n\n    for (auto i: coefs) {\n        BN_CTX *ctx = BN_CTX_new();\n        BIGNUM *coef_pov_res = NULL;\n        BIGNUM *coef_res = NULL;\n\n        const char * c = i.c_str();\n        BN_hex2bn(&coef_res, c);  //\u043f\u0435\u0440\u0435\u0432\u043e\u0434\u0438\u043c \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442 \u0432 BIGNUM(hex)\n\n        BIGNUM *pow = NULL;  //\u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0432\u043e\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u044f \u0432 \u0441\u0442\u0435\u043f\u0435\u043d\u044c x\n        BN_dec2bn(&pow, \"1\");\n\n        std::string x_str = std::to_string(x);\n        char const *x_char = x_str.c_str();\n        BIGNUM *our_x = NULL;\n        BN_dec2bn(&our_x, x_char);\n        for (int cur_pow=1; cur_pow<=j; cur_pow++) {  //\u0432\u043e\u0437\u0432\u043e\u0434\u0438\u043c x \u0432 \u0441\u0442\u0435\u043f\u0435\u043d\u044c j\n            BN_mul(pow, our_x, pow, ctx);\n        }\n\n        BN_mul(coef_res, pow, coef_res, ctx);  //\u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 x*a(j)\n        BN_add(sum, sum, coef_res);  //\u043d\u0430\u043a\u0430\u043f\u043b\u0438\u0432\u0430\u0435\u043c \u0441\u0443\u043c\u043c\u0443 a(j)*x^j\n\n        j++;\n        BN_free(coef_pov_res);\n        BN_free(coef_res);\n    }\n\n    BIGNUM *p = NULL;  //\u043f\u0435\u0440\u0435\u0432\u043e\u0434\u0438\u043c secret \u0432 BIGNUM\n    const char *pr_key = secr.c_str();\n    BN_hex2bn(&p, pr_key);\n    BN_add(result, p, sum);  //\u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u043f\u043e\u043b\u0438\u043d\u043e\u043c\u0430\n\n    return result;\n}\n\n/* \u0420\u0430\u0437\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u0441\u0435\u043a\u0440\u0435\u0442\u0430 \u043d\u0430 N \u0447\u0430\u0441\u0442\u0435\u0439 */\nstd::vector<std::pair<int, std::string>> split(std::string secret, uint16_t n, uint16_t t) {\n    std::vector<std::pair<int, std::string>> shares_bignum;  //\u043a\u0443\u0441\u043a\u0438 - \u0442\u043e\u0447\u043a\u0438 \u0442\u0438\u043f\u0430 (int; BIGNUM)\n\n    std::vector<std::string> coefs;  //\u043c\u0430\u0441\u0441\u0438\u0432 \u0440\u0430\u043d\u0434\u043e\u043c\u043d\u044b\u0445 \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u043e\u0432 \u043f\u043e\u043b\u0438\u043d\u043e\u043c\u0430\n\n    for (int i=1; i<t; i++) {  //\u0433\u0435\u043d\u0435\u0440\u0430\u0446\u0438\u044f t-1 \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u043e\u0432\n        unsigned char buf[16];\n        RAND_bytes(buf, 16);  //\u0433\u0435\u043d\u0435\u0440\u0438\u0440\u0443\u0435\u043c 32 \u0440\u0430\u043d\u0434\u043e\u043c\u043d\u044b\u0445 \u0431\u0430\u0439\u0442\u0430 \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u0430\n        std::string str_buf((char*)buf);\n        std::string cur_cof = sha256(str_buf);  //\u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442 - sha256(random 32 bytes)\n        coefs.push_back(cur_cof);\n    }\n\n    for (int i=0; i<n; i++) {  //\u0437\u0430\u043f\u0438\u0441\u044c n \u043a\u0443\u0441\u043a\u043e\u0432 \u0432 \u043c\u0430\u0441\u0441\u0438\u0432 \u043f\u0430\u0440 shares_bignum\n        BIGNUM *share = BN_new();\n        share = polinom(coefs, secret, i+1);\n\n        char * number_str = BN_bn2hex(share);\n        std::string str(number_str);\n        shares_bignum.push_back({ i+1, str});  //\u0437\u0430\u043f\u0438\u0441\u044b\u0432\u0430\u0435\u043c \u0442\u043e\u0447\u043a\u0443 (i+1; share[i+1])\n\n        BN_free(share);\n        OPENSSL_free(number_str);\n    }\n\n    return shares_bignum;\n}\n\n/* \u0412\u043e\u0441\u0441\u0442\u0430\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435 \u0441\u0435\u043a\u0440\u0435\u0442\u0430 \u043f\u043e T \u0447\u0430\u0441\u0442\u044f\u043c */\nstd::string recover(std::vector<std::pair<int, std::string>> shares) {\n    std::vector<double> x;  //\u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u044b x \u0447\u0430\u0441\u0442\u0435\u0439 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\n    std::vector<std::string> y;  //\u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u044b y \u0447\u0430\u0441\u0442\u0435\u0439 \u0441\u0435\u043a\u0440\u0435\u0442\u0430\n\n    for (auto i: shares) {\n        x.push_back(i.first*1.0);\n    }\n    for (auto i: shares) {\n        y.push_back(i.second);\n    }\n\n    /* \u0412\u043e\u0437\u0432\u0440\u0430\u0449\u0435\u043d\u0438\u0435 \u0438\u0441\u0445\u043e\u0434\u043d\u043e\u0439 \u043f\u043e\u043b\u0438\u043d\u043e\u043c\u0438\u0430\u043b\u044c\u043d\u043e\u0439 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 */\n    std::vector<mp_type> x_divs;\n    for (int j=0; j<x.size(); j++) {  //\u0441\u0447\u0438\u0442\u0430\u0435\u043c \u0447\u0430\u0441\u0442\u043d\u044b\u0435\n        mp_type result = 1.0;\n        for (int i = 0; i < x.size(); i++) {\n            int m = i;\n            if (m != j) {\n                mp_type x_m(x[m]);\n                mp_type x_j(x[j]);\n                mp_type slag = (0 - x_m) / (x_j - x_m);\n                result *= slag;\n            }\n        }\n        x_divs.push_back(result);\n    }\n\n    int ind_cur_y = 0;\n    mp_type result(\"0\");\n    for (auto i : x_divs) {  //\u0443\u043c\u043d\u043e\u0436\u0430\u0435\u043c \u043a\u0430\u0436\u0434\u044b\u0439 x \u043d\u0430 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0439 y\n\n        BIGNUM *cur_y = NULL;\n        const char * cur_y_char = y[ind_cur_y].c_str();\n        BN_hex2bn(&cur_y, cur_y_char);\n        cur_y_char = BN_bn2dec(cur_y);\n        mp_type boost_y_double(cur_y_char);\n\n        mp_type mul_result = i*boost_y_double;\n        result += mul_result;  //\u0441\u043a\u043b\u0430\u0434\u044b\u0432\u0430\u0435\u043c \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b \u0443\u043c\u043d\u043e\u0436\u0435\u043d\u0438\u0439\n\n        ind_cur_y++;\n    }\n    cpp_int res_int(result+1);  //\u0438\u0437-\u0437\u0430 \u043e\u043a\u0440\u0443\u0433\u043b\u0435\u043d\u0438\u044f double \u043f\u0440\u0438\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u043f\u0440\u0438\u0431\u0430\u0432\u043b\u044f\u0442\u044c \u0435\u0434\u0438\u043d\u0438\u0446\u0443\n    std::stringstream stream;\n    stream << std::hex << res_int;\n    std::string result_private_key = stream.str();\n\n    return result_private_key;\n}\n\nint main(int argc, char* argv[]) {\n\n    if ((std::string(argv[1]) != \"split\") && (std::string(argv[1]) != \"recover\")) {\n        std::cout << \"\u041f\u0440\u043e\u0432\u0435\u0440\u044c\u0442\u0435 \u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u0432\u0432\u0435\u0434\u0435\u043d\u043d\u044b\u0445 \u0432\u0430\u043c\u0438 \u0434\u0430\u043d\u043d\u044b\u0445!\\n\";\n        return 1;\n    }\n\n    if (std::string(argv[1]) == \"split\") {  //mode: split\n        uint16_t N;\n        uint16_t T;\n        std::string curve25519_private_key = curve25519_pr_key_gen();  //\u0433\u0435\u043d\u0435\u0440\u0430\u0446\u0438\u044f \u043f\u0440\u0438\u0432\u0430\u0442\u043d\u043e\u0433\u043e \u043a\u043b\u044e\u0447\u0430\n        std::cout << \"stdin:\\n\" << curve25519_private_key << std::endl;\n        std::cin >> N >> T;\n\n        std::vector<std::pair<int, std::string>> shares = split(curve25519_private_key, N,\n                                                                T);  //\u0440\u0430\u0437\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u043f\u0440\u0438\u0432\u0430\u0442\u043d\u043e\u0433\u043e \u043a\u043b\u044e\u0447\u0430 \u043d\u0430 N \u043a\u0443\u0441\u043a\u043e\u0432\n\n        std::cout << \"\\nstdout:\\n\";\n        for (auto share : shares) {\n            std::cout << share.first << \" \" << share.second << \"\\n\";\n        }\n    }\n\n    if (std::string(argv[1]) == \"recover\") {  //mode: recover\n        std::vector<std::pair<int, std::string>> recover_parts;\n\n        std::string input_share;\n        std::cout << \"stdin:\\n\";\n        getline(std::cin, input_share);\n        while (input_share != \"\") {  //\u0432\u0432\u043e\u0434 \u0447\u0430\u0441\u0442\u0435\u0439 \u0432 \u0440\u0435\u0436\u0438\u043c\u0435 recover \u0441 \u043a\u043b\u0430\u0432\u0438\u0430\u0442\u0443\u0440\u044b\n            std::vector<std::string> split_result = split(input_share);\n            int x_point = stoi(split_result[0]);\n            recover_parts.push_back({x_point, split_result[1]});\n            getline(std::cin, input_share);\n        }\n\n        std::string private_key_recover = recover(recover_parts);\n        std::cout << \"\\nstdout:\\n\";\n        std::locale loc;\n        for (std::string::size_type i=0; i<private_key_recover.length(); ++i)\n            std::cout << std::tolower(private_key_recover[i],loc);\n        std::cout << \"\\n\";\n    }\n\n    return 0;\n}", "meta": {"hexsha": "fa7a880cc5e494b3b1f3737ed81570c25c1d1be1", "size": 7565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shamir.cpp", "max_stars_repo_name": "catcatcat8/shamir_scheme", "max_stars_repo_head_hexsha": "09751d32887ff88461c6037eb3a2c0bab4fc1c5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T02:28:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T01:24:42.000Z", "max_issues_repo_path": "shamir.cpp", "max_issues_repo_name": "catcatcat8/shamir_scheme", "max_issues_repo_head_hexsha": "09751d32887ff88461c6037eb3a2c0bab4fc1c5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-12-16T03:37:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-19T00:38:39.000Z", "max_forks_repo_path": "shamir.cpp", "max_forks_repo_name": "catcatcat8/shamir_scheme", "max_forks_repo_head_hexsha": "09751d32887ff88461c6037eb3a2c0bab4fc1c5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-12T02:28:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T16:06:08.000Z", "avg_line_length": 33.0349344978, "max_line_length": 128, "alphanum_fraction": 0.5907468605, "num_tokens": 2349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5233562449540161}}
{"text": "#include <sodium/sodium.h>\n#include <boost/hana/functional/curry.hpp>\n#include <boost/numeric/odeint.hpp>\n#include <catch/catch.hpp>\n\n#include \"../include/Plant.hpp\"\n#include \"../include/util/util-sim.hpp\"\n\nusing boost::hana::curry;\nusing sim::PState;\nnamespace odeint = boost::numeric::odeint;\n\nTEST_CASE(\n    \"Study terminal velocity without spring term. Starting from rest at the \"\n    \"origin \u2026\") {\n  // The plant models a point mass with a static force and a quadratic drag\n  // term.\n  // (*)  Fs - \u03b7 v = m dv/dt\n  //     where\n  //       * Fs is the static force,\n  //       * \u03b7 is the drag coefficient,\n  //       * m is the inertial mass, and\n  //       * v is the linear speed.\n  // The terminal velocity is apparent in (*), since dv/dt will be 0:\n  // (\u2020) v = (Fs / \u03b7)\n\n  constexpr auto do_step =\n      curry<4>(util::do_step_with<odeint::runge_kutta4<PState>>);\n  constexpr double dt = 0.1;\n  constexpr PState x0{0., 0., 0.};\n\n  constexpr double convergenceTolerance = 1E-12;\n  constexpr auto v_diff_not_within_tolerance = [](PState last, PState current) {\n    return (current[1] - last[1]) > convergenceTolerance;\n  };\n\n  SECTION(\"and given (Fs, \u03b7) = (4, 1), the terminal velocity should be \u2248 4.\") {\n    const auto plant = sim::Plant(4., 1., 0.);\n    odeint::runge_kutta4<PState> stepper;\n\n    const auto plant_step = do_step(plant, stepper, dt);\n    PState atTerminalVel =\n        util::step_while(v_diff_not_within_tolerance, plant_step, x0);\n    REQUIRE(atTerminalVel[1] == Approx(4));\n  }\n\n  SECTION(\"and given (Fs, \u03b7) = (9, 1), the terminal velocity should be \u2248 9.\") {\n    const auto plant = sim::Plant(9., 1., 0.);\n    odeint::runge_kutta4<PState> stepper;\n\n    const auto plant_step = do_step(plant, stepper, dt);\n    PState atTerminalVel =\n        util::step_while(v_diff_not_within_tolerance, plant_step, x0);\n    REQUIRE(atTerminalVel[1] == Approx(9));\n  }\n}\n", "meta": {"hexsha": "60f394adb4d0a5bb3d9f7493788ca038f1c8ebe3", "size": 1882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/utest-numerics-Plant.cpp", "max_stars_repo_name": "timtro/pid-unfolding", "max_stars_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_stars_repo_licenses": ["MIT"], "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/utest-numerics-Plant.cpp", "max_issues_repo_name": "timtro/pid-unfolding", "max_issues_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_issues_repo_licenses": ["MIT"], "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/utest-numerics-Plant.cpp", "max_forks_repo_name": "timtro/pid-unfolding", "max_forks_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_forks_repo_licenses": ["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.0175438596, "max_line_length": 80, "alphanum_fraction": 0.6530286929, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5232701072526427}}
{"text": "// Standard includes\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <string>\n#include <vector>\n\n// For date parsing\n#include <boost/date_time/local_time/local_time.hpp>\n\n// For converting WGS84 <-> LTP coordinates\n#include <GeographicLib/Geocentric.hpp>\n#include <GeographicLib/LocalCartesian.hpp>\n\n// Main entry point\nint main(int argc, char* argv[])\n{\n\t// We are in science here :)\n\tstd::cout.precision(16);\n\n\t// Base station coordinates (Friday)\n\tdouble org_lat = 51.710979902;\n\tdouble org_lon = -0.210839049;   \n\tdouble org_alt = 141.1027;\n\n\t// Setup a converter\n\tGeographicLib::Geocentric wgs84_ecef(\n\t\tGeographicLib::Constants::WGS84_a(), \n\t\tGeographicLib::Constants::WGS84_f()\n\t);\n\tGeographicLib::LocalCartesian   wgs84_enu(\n\t\torg_lat, \n\t\torg_lon, \n\t\torg_alt, \n\t\twgs84_ecef\n\t); \n\t\n\t// Argument check\n\tif (argc < 2)\n\t{\n\t\tstd::cout << \"Usage: \" << argv[0] << \" <file> \" << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::ifstream \tnamefile(argv[1]);\n\tstd::string \tinput;\n\tint counter     = 0;\n\tint line        = 0;\n\n\t\n  \tboost::posix_time::ptime epoch(boost::gregorian::date(1970,1,1)); \n    \n\t// Now process the data\n\tstd::string Date, Time, debug1, debug2, debug3, debug4;\n\tdouble x, y, z;\n\tdouble lat, lon, alt, en, ee, eu, ede, edn, edu, age, ratio;\n\tdouble AnglePitch, AngleRoll, AngleYaw,\tPitchReference, RollReference, YawReference,\n\t\tAngVelPitch, AngVelRoll, AngVelYaw, TotalAccX, TotalAccY, TotalAccZ, TransAccX,\tTransAccY,\t\n\t\tTransAccZ,\tTotalAcc,\t Height,\t dHeight,\tHeightReference, dHeightReference, Latitude,\t\n\t\tLongitude,\tGPSHeight,\t SpeedX,\tSpeedY, HorizontalAccuracy, Battery1, Battery2;\n\tlong SystemTimestamp, Status, FlightMode, Pressure, TempGyro, TempADC, Pitch, Roll, Yaw, Thrust, GPSStatus;\n\twhile(namefile\n\t\t>> Date\t \n\t\t>> Time\t \n\t\t>> SystemTimestamp\n\t\t>> AnglePitch\n\t\t>> AngleRoll\n\t\t>> AngleYaw\t \n\t\t>> PitchReference\t\n\t\t>> RollReference\n\t\t>> YawReference\t\n\t\t>> AngVelPitch\n\t\t>> AngVelRoll\t\n\t\t>> AngVelYaw\t\n\t\t>> TotalAccX\t\n\t\t>> TotalAccY\t\n\t\t>> TotalAccZ\t\n\t\t>> TransAccX\t\n\t\t>> TransAccY\t\n\t\t>> TransAccZ\t\n\t\t>> TotalAcc\t \n\t\t>> Height\n\t\t>> dHeight\t\n\t\t>> HeightReference\t\n\t\t>> dHeightReference\n\t\t>> Latitude\t\n\t\t>> Longitude\t\n\t\t>> GPSHeight\t \t \n\t\t>> SpeedX\t\n\t\t>> SpeedY\t\n\t\t>> HorizontalAccuracy\t\n\t\t>> GPSStatus\t\n\t\t>> Battery1\n\t\t>> Battery2\t\n\t\t>> Status\t\n\t\t>> FlightMode\n\t\t>> Pressure\t\n\t\t>> TempGyro\t\n\t\t>> TempADC\t\n\t\t>> Pitch\t \n\t\t>> Roll\t \n\t\t>> Yaw\t\n\t\t>> Thrust\n\t\t>> debug1\n\t\t>> debug2\t\n\t\t>> debug3\t\n\t\t>> debug4)\n\t{\n\t\t// Extract a meaningful value in seconds\n\t    std::stringstream ss;\n\t    boost::local_time::local_date_time ldt(boost::local_time::not_a_date_time);\n\t    boost::local_time::local_time_input_facet* input_facet = new boost::local_time::local_time_input_facet();\n\t    input_facet->format(\"%d.%m.%Y %H:%M:%s\");\n\t    ss.imbue(std::locale(ss.getloc(), input_facet));\n\t\tss << Date << \" \" << Time;\n \t\tss >> ldt;\n\n \t\tboost::posix_time::ptime a = ldt.utc_time();\n    \tboost::posix_time::ptime epoch(boost::gregorian::date(1970,1,1));\n    \tdouble ms = (a - epoch).total_milliseconds();\n    \tms /= 1e3;\n\n \t\t// Convert value to LTP\n\t\twgs84_enu.Forward(\n\t\t\tLatitude, \n\t\t\tLongitude, \n\t\t\tGPSHeight,\n\t\t\tx,\n\t\t\ty,\n\t\t\tz\n\t\t);\n\n\t\t// Print seconds, WGS84 and LTP\n\t\tstd::cout << ms << \",\" << Latitude << \",\" << Longitude << \",\" << GPSHeight << \",\" << x << \",\" << y  << \",\" << z << std::endl;\n\t}\n\n\t// Success\n\treturn 0;\n}\n", "meta": {"hexsha": "a4c86c1b10e064363174d2fd93d37e52d5fe4b5e", "size": 3361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/waypoint_test/fcs_sync.cpp", "max_stars_repo_name": "jiangchenzhu/crates_zhejiang", "max_stars_repo_head_hexsha": "711c9fafbdc775114345ab0ca389656db9d20df7", "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": "thirdparty/waypoint_test/fcs_sync.cpp", "max_issues_repo_name": "jiangchenzhu/crates_zhejiang", "max_issues_repo_head_hexsha": "711c9fafbdc775114345ab0ca389656db9d20df7", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/waypoint_test/fcs_sync.cpp", "max_forks_repo_name": "jiangchenzhu/crates_zhejiang", "max_forks_repo_head_hexsha": "711c9fafbdc775114345ab0ca389656db9d20df7", "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.8368794326, "max_line_length": 127, "alphanum_fraction": 0.6447485867, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5232701019804435}}
{"text": "// 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 NETKET_ACTIVATIONS_HPP\n#define NETKET_ACTIVATIONS_HPP\n\n#include <Eigen/Dense>\n#include <complex>\n#include <iostream>\n#include <random>\n#include <vector>\n\nnamespace netket {\n\n/**\n  Abstract class for Activations.\n*/\nclass AbstractActivation {\n public:\n  using VectorType = Eigen::Matrix<std::complex<double>, Eigen::Dynamic, 1>;\n  using VectorRefType = Eigen::Ref<VectorType>;\n  using VectorConstRefType = Eigen::Ref<const VectorType>;\n\n  virtual void operator()(VectorConstRefType Z, VectorRefType A) const = 0;\n\n  // Z is the layer output before applying nonlinear function\n  // A = nonlinearfunction(Z)\n  // F = dL/dA is the derivative of A wrt the output L = log(psi(v))\n  // G is the place to write the output i.e. G = dL/dZ = dL/dA * dA/dZ\n  virtual void ApplyJacobian(VectorConstRefType Z, VectorConstRefType A,\n                             VectorConstRefType F, VectorRefType G) const = 0;\n  virtual ~AbstractActivation() {}\n};\n\ninline double lncosh(double x) {\n  const double xp = std::abs(x);\n  if (xp <= 12.) {\n    return std::log(std::cosh(xp));\n  } else {\n    const static double log2v = std::log(2.);\n    return xp - log2v;\n  }\n}\n\n// ln(cos(x)) for std::complex argument\n// the modulus is computed by means of the previously defined function\n// for real argument\ninline std::complex<double> lncosh(std::complex<double> x) {\n  const double xr = x.real();\n  const double xi = x.imag();\n\n  std::complex<double> res = lncosh(xr);\n  res += std::log(\n      std::complex<double>(std::cos(xi), std::tanh(xr) * std::sin(xi)));\n\n  return res;\n}\n\nclass Identity : public AbstractActivation {\n  using VectorType = typename AbstractActivation::VectorType;\n\n public:\n  // A = Z\n  inline void operator()(VectorConstRefType Z, VectorRefType A) const override {\n    A.noalias() = Z;\n  }\n\n  // Apply the (derivative of activation function) matrix J to a vector F\n  // A = Z\n  // J = dA / dZ = I\n  // G = J * F = F\n  inline void ApplyJacobian(VectorConstRefType /*Z*/, VectorConstRefType /*A*/,\n                            VectorConstRefType F,\n                            VectorRefType G) const override {\n    G.noalias() = F;\n  }\n};\n\nclass Lncosh : public AbstractActivation {\n  using VectorType = typename AbstractActivation::VectorType;\n\n public:\n  std::string name = \"Lncosh\";\n  // A = Lncosh(Z)\n  inline void operator()(VectorConstRefType Z, VectorRefType A) const override {\n    for (int i = 0; i < A.size(); ++i) {\n      A(i) = lncosh(Z(i));\n    }\n  }\n\n  // Apply the (derivative of activation function) matrix J to a vector F\n  // A = Lncosh(Z)\n  // J = dA / dZ\n  // G = J * F\n  inline void ApplyJacobian(VectorConstRefType Z, VectorConstRefType /*A*/,\n                            VectorConstRefType F,\n                            VectorRefType G) const override {\n    G.array() = F.array() * Z.array().tanh();\n  }\n};\n\nclass Tanh : public AbstractActivation {\n  using VectorType = typename AbstractActivation::VectorType;\n\n public:\n  std::string name = \"Tanh\";\n  // A = Tanh(Z)\n  inline void operator()(VectorConstRefType Z, VectorRefType A) const override {\n    A.array() = Z.array().tanh();\n  }\n\n  // Apply the (derivative of activation function) matrix J to a vector F\n  // A = Tanh(Z)\n  // J = dA / dZ\n  // G = J * F\n  inline void ApplyJacobian(VectorConstRefType /*Z*/, VectorConstRefType A,\n                            VectorConstRefType F,\n                            VectorRefType G) const override {\n    G.array() = F.array() * (1 - A.array() * A.array());\n  }\n};\n\nclass Relu : public AbstractActivation {\n  using VectorType = typename AbstractActivation::VectorType;\n\n  double theta1_ = std::atan(1) * 3;\n  double theta2_ = -std::atan(1);\n\n public:\n  std::string name = \"Relu\";\n  // A = Z\n  inline void operator()(VectorConstRefType Z, VectorRefType A) const override {\n    for (int i = 0; i < Z.size(); ++i) {\n      A(i) =\n          (std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? Z(i) : 0.0;\n    }\n  }\n\n  // Apply the (derivative of activation function) matrix J to a vector F\n  // A = Z\n  // J = dA / dZ = I\n  // G = J * F = F\n  inline void ApplyJacobian(VectorConstRefType Z, VectorConstRefType /*A*/,\n                            VectorConstRefType F,\n                            VectorRefType G) const override {\n    for (int i = 0; i < Z.size(); ++i) {\n      G(i) =\n          (std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? F(i) : 0.0;\n    }\n  }\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "c59a0e281c9fdd68a4151ddb63a70558372e015f", "size": 5057, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Machine/activations.hpp", "max_stars_repo_name": "GTorlai/netket", "max_stars_repo_head_hexsha": "0c35bfaadeb1253f611f8052b53c9b3d3d9aec9f", "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": "NetKet/Machine/activations.hpp", "max_issues_repo_name": "GTorlai/netket", "max_issues_repo_head_hexsha": "0c35bfaadeb1253f611f8052b53c9b3d3d9aec9f", "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": "NetKet/Machine/activations.hpp", "max_forks_repo_name": "GTorlai/netket", "max_forks_repo_head_hexsha": "0c35bfaadeb1253f611f8052b53c9b3d3d9aec9f", "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.2814371257, "max_line_length": 80, "alphanum_fraction": 0.6308087799, "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5232701007194237}}
{"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_COTH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_COTH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-hyperbolic\n\n    This unction object returns the hyperbolic cotangent:\n    \\f$(e^{x}+e^{-x})/(e^{x}-e^{-x})\\f$\n\n    @par Header <boost/simd/function/coth.hpp>\n\n    @see sinh, cosh, sinhcosh\n\n    @par Example:\n\n      @snippet coth.cpp coth\n\n    @par Possible output:\n\n      @snippet coth.txt coth\n\n  **/\n  IEEEValue coth(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/coth.hpp>\n#include <boost/simd/function/simd/coth.hpp>\n\n#endif\n", "meta": {"hexsha": "5e4e0bcd2e8df96a38cb20b8437503fa5fa898e5", "size": 1026, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/coth.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/function/coth.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/function/coth.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": 22.8, "max_line_length": 100, "alphanum_fraction": 0.5604288499, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973932, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5232519698225304}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 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_ARCH_COMMON_FUNCTION_SCALAR_ASINH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_ASINH_HPP_INCLUDED\n\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/oneosqrteps.hpp>\n#include <boost/simd/constant/sqrteps.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/scalar/bitofsign.hpp>\n#include <boost/simd/function/scalar/bitwise_xor.hpp>\n#include <boost/simd/function/scalar/fma.hpp>\n#include <boost/simd/function/scalar/hypot.hpp>\n#include <boost/simd/function/scalar/log.hpp>\n#include <boost/simd/function/scalar/log1p.hpp>\n#include <boost/simd/function/scalar/rec.hpp>\n#include <boost/simd/function/scalar/sqr.hpp>\n#include <boost/simd/function/scalar/sqrt.hpp>\n#include <boost/simd/function/horn.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( asinh_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::double_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 x = bs::abs(a0);\n      if  (BOOST_UNLIKELY(x < bs::Sqrteps<A0>() ))\n      {\n        return a0;\n      }\n      else\n      {\n        A0 z;\n        if (x < 0.5)\n        {\n          A0 invx = bs::rec(x);\n          z = bs::log1p(x + x/(invx + bs::sqrt(fma(invx, invx, bs::One<A0>()))));\n        }\n        else if (BOOST_UNLIKELY(x > Oneosqrteps<A0>()))\n        {\n          z = log(x)+Log_2<A0>();\n        }\n        else\n        {\n          z =  log(x+hypot(One<A0>(), x));\n        }\n        return bitwise_xor(z, bitofsign(a0));\n      }\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( asinh_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::single_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      // Exhaustive test for: boost::dispatch::functor<bs::tag::asinh_, boost::simd::tag::sse4_2_>\n      //              versus:  float(boost::math::asinh(double)\n      //              With T: float\n      //            in range: [-3.40282e+38, 3.40282e+38]\n      // 4278190078 values computed.\n      // 3628470338 values (84.81%)  within 0.0 ULPs\n      //  649693884 values (15.19%)  within 0.5 ULPs\n      //      25856 values ( 0.00%)  within 1.0 ULPs\n      A0 x = bs::abs(a0);\n      A0 x2 = bs::sqr(x);\n      A0 z = Zero<A0>();\n\n      if( x < 0.5f)\n      {\n        z = horn<A0\n          , 0x3f800000\n          , 0xbe2aa9ad\n          , 0x3d9949b1\n          , 0xbd2ee581\n          , 0x3ca4d6e6\n          > (x2)*x;\n      }\n      else if (BOOST_UNLIKELY(x > Oneosqrteps<A0>()))\n      {\n        z = log(x)+Log_2<A0>();\n      }\n      else\n      {\n        z =  log(x+hypot(One<A0>(), x));\n      }\n      return bitwise_xor(z, bitofsign(a0));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "ba2310404784dd3f59a9393c32f7bc67735b63d1", "size": 3544, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/asinh.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/arch/common/scalar/function/asinh.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/arch/common/scalar/function/asinh.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": 30.2905982906, "max_line_length": 100, "alphanum_fraction": 0.5301918736, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5232519585831554}}
{"text": "\n// g++-4.4 bench_gemm.cpp -I .. -O2 -DNDEBUG -lrt -fopenmp && OMP_NUM_THREADS=2  ./a.out\n// icpc bench_gemm.cpp -I .. -O3 -DNDEBUG -lrt -openmp  && OMP_NUM_THREADS=2  ./a.out\n\n#include <iostream>\n#include <Eigen/Core>\n#include <bench/BenchTimer.h>\n\nusing namespace std;\nusing namespace Eigen;\n\n#ifndef SCALAR\n#define SCALAR float\n#endif\n\ntypedef SCALAR Scalar;\ntypedef Matrix<Scalar,Dynamic,Dynamic> M;\n\n#ifdef HAVE_BLAS\n\nextern \"C\" {\n  #include <bench/btl/libs/C_BLAS/blas.h>\n}\n\nstatic float fone = 1;\nstatic float fzero = 0;\nstatic double done = 1;\nstatic double szero = 0;\nstatic char notrans = 'N';\nstatic char trans = 'T';\nstatic char nonunit = 'N';\nstatic char lower = 'L';\nstatic char right = 'R';\nstatic int intone = 1;\n\nvoid blas_gemm(const MatrixXf& a, const MatrixXf& b, MatrixXf& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  sgemm_(&notrans,&notrans,&M,&N,&K,&fone,\n         const_cast<float*>(a.data()),&lda,\n         const_cast<float*>(b.data()),&ldb,&fone,\n         c.data(),&ldc);\n}\n\nvoid blas_gemm(const MatrixXd& a, const MatrixXd& b, MatrixXd& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  dgemm_(&notrans,&notrans,&M,&N,&K,&done,\n         const_cast<double*>(a.data()),&lda,\n         const_cast<double*>(b.data()),&ldb,&done,\n         c.data(),&ldc);\n}\n\n#endif\n\ntemplate<typename M>\nvoid gemm(const M& a, const M& b, M& c)\n{\n  c.noalias() += a * b;\n}\n\nint main(int argc, char ** argv)\n{\n  std::ptrdiff_t l1 = ei_queryL1CacheSize();\n  std::ptrdiff_t l2 = ei_queryTopLevelCacheSize();\n  std::cout << \"L1 cache size    = \" << (l1>0 ? l1/1024 : -1) << \" KB\\n\";\n  std::cout << \"L2/L3 cache size = \" << (l2>0 ? l2/1024 : -1) << \" KB\\n\";\n\n  int rep = 1;    // number of repetitions per try\n  int tries = 2;  // number of tries, we keep the best\n\n  int s = 2048;\n  int cache_size = -1;\n\n  bool need_help = false;\n  for (int i=1; i<argc; ++i)\n  {\n    if(argv[i][0]=='s')\n      s = atoi(argv[i]+1);\n    else if(argv[i][0]=='c')\n      cache_size = atoi(argv[i]+1);\n    else if(argv[i][0]=='t')\n      tries = atoi(argv[i]+1);\n    else if(argv[i][0]=='p')\n      rep = atoi(argv[i]+1);\n    else\n      need_help = true;\n  }\n\n  if(need_help)\n  {\n    std::cout << argv[0] << \" s<matrix size> c<cache size> t<nb tries> p<nb repeats>\\n\";\n    return 1;\n  }\n\n  if(cache_size>0)\n    setCpuCacheSizes(cache_size,32*cache_size);\n\n  int m = s;\n  int n = s;\n  int p = s;\n  M a(m,n); a.setRandom();\n  M b(n,p); b.setRandom();\n  M c(m,p); c.setOnes();\n\n  std::cout << \"Matrix sizes = \" << m << \"x\" << p << \" * \" << p << \"x\" << n << \"\\n\";\n  std::ptrdiff_t cm(m), cn(n), ck(p);\n  computeProductBlockingSizes<Scalar,Scalar>(ck, cm, cn);\n  std::cout << \"blocking size = \" << cm << \" x \" << ck << \"\\n\";\n\n  M r = c;\n\n  // check the parallel product is correct\n  #ifdef EIGEN_HAS_OPENMP\n  int procs = omp_get_max_threads();\n  if(procs>1)\n  {\n    #ifdef HAVE_BLAS\n    blas_gemm(a,b,r);\n    #else\n    omp_set_num_threads(1);\n    r.noalias() += a * b;\n    omp_set_num_threads(procs);\n    #endif\n    c.noalias() += a * b;\n    if(!r.isApprox(c)) std::cerr << \"Warning, your parallel product is crap!\\n\\n\";\n  }\n  #endif\n\n  #ifdef HAVE_BLAS\n  BenchTimer tblas;\n  BENCH(tblas, tries, rep, blas_gemm(a,b,c));\n  std::cout << \"blas  cpu         \" << tblas.best(CPU_TIMER)/rep  << \"s  \\t\" << (double(m)*n*p*rep*2/tblas.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << tblas.total(CPU_TIMER)  << \"s)\\n\";\n  std::cout << \"blas  real        \" << tblas.best(REAL_TIMER)/rep << \"s  \\t\" << (double(m)*n*p*rep*2/tblas.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << tblas.total(REAL_TIMER) << \"s)\\n\";\n  #endif\n\n  BenchTimer tmt;\n  BENCH(tmt, tries, rep, gemm(a,b,c));\n  std::cout << \"eigen cpu         \" << tmt.best(CPU_TIMER)/rep  << \"s  \\t\" << (double(m)*n*p*rep*2/tmt.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << tmt.total(CPU_TIMER)  << \"s)\\n\";\n  std::cout << \"eigen real        \" << tmt.best(REAL_TIMER)/rep << \"s  \\t\" << (double(m)*n*p*rep*2/tmt.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << tmt.total(REAL_TIMER) << \"s)\\n\";\n\n  #ifdef EIGEN_HAS_OPENMP\n  if(procs>1)\n  {\n    BenchTimer tmono;\n    //omp_set_num_threads(1);\n    Eigen::setNbThreads(1);\n    BENCH(tmono, tries, rep, gemm(a,b,c));\n    std::cout << \"eigen mono cpu    \" << tmono.best(CPU_TIMER)/rep  << \"s  \\t\" << (double(m)*n*p*rep*2/tmono.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << tmono.total(CPU_TIMER)  << \"s)\\n\";\n    std::cout << \"eigen mono real   \" << tmono.best(REAL_TIMER)/rep << \"s  \\t\" << (double(m)*n*p*rep*2/tmono.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << tmono.total(REAL_TIMER) << \"s)\\n\";\n    std::cout << \"mt speed up x\" << tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER)  << \" => \" << (100.0*tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER))/procs << \"%\\n\";\n  }\n  #endif\n\n  return 0;\n}\n\n", "meta": {"hexsha": "4142236e94403e2118e22101573ca98908d271d3", "size": 4883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/bench/bench_gemm.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/bench_gemm.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/bench_gemm.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": 30.1419753086, "max_line_length": 187, "alphanum_fraction": 0.5777186156, "num_tokens": 1720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5231702059546722}}
{"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):       Cl\u00e9ment Maria\n *\n *    Copyright (C) 2014 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/distance_functions.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Persistent_cohomology.h>\n#include <gudhi/Points_off_io.h>\n\n#include <boost/program_options.hpp>\n\n#include <string>\n#include <vector>\n#include <limits>  // infinity\n#include <utility>  // for pair\n#include <map>\n\n// ----------------------------------------------------------------------------\n// rips_persistence_step_by_step is an example of each step that is required to\n// build a Rips over a Simplex_tree. Please refer to rips_persistence to see\n// how to do the same thing with the Rips_complex wrapper for less detailed\n// steps.\n// ----------------------------------------------------------------------------\n\n// Types definition\nusing Simplex_tree = Gudhi::Simplex_tree<Gudhi::Simplex_tree_options_fast_persistence>;\nusing Vertex_handle = Simplex_tree::Vertex_handle;\nusing Filtration_value = Simplex_tree::Filtration_value;\nusing Proximity_graph = Gudhi::Proximity_graph<Simplex_tree>;\n\nusing Field_Zp = Gudhi::persistent_cohomology::Field_Zp;\nusing Persistent_cohomology = Gudhi::persistent_cohomology::Persistent_cohomology<Simplex_tree, Field_Zp >;\nusing Point = std::vector<double>;\nusing Points_off_reader = Gudhi::Points_off_reader<Point>;\n\nvoid program_options(int argc, char * argv[]\n                     , std::string & off_file_points\n                     , std::string & filediag\n                     , Filtration_value & threshold\n                     , int & dim_max\n                     , int & p\n                     , Filtration_value & min_persistence);\n\nint main(int argc, char * argv[]) {\n  std::string off_file_points;\n  std::string filediag;\n  Filtration_value threshold;\n  int dim_max;\n  int p;\n  Filtration_value min_persistence;\n\n  program_options(argc, argv, off_file_points, filediag, threshold, dim_max, p, min_persistence);\n\n  // Extract the points from the file filepoints\n  Points_off_reader off_reader(off_file_points);\n\n  // Compute the proximity graph of the points\n  Proximity_graph prox_graph = Gudhi::compute_proximity_graph<Simplex_tree>(off_reader.get_point_cloud(),\n                                                                            threshold,\n                                                                            Gudhi::Euclidean_distance());\n\n  // Construct the Rips complex in a Simplex Tree\n  Simplex_tree st;\n  // insert the proximity graph in the simplex tree\n  st.insert_graph(prox_graph);\n  // expand the graph until dimension dim_max\n  st.expansion(dim_max);\n\n  std::cout << \"The complex contains \" << st.num_simplices() << \" simplices \\n\";\n  std::cout << \"   and has dimension \" << st.dimension() << \" \\n\";\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 pcoh(st);\n  // initializes the coefficient field for homology\n  pcoh.init_coefficients(p);\n\n  pcoh.compute_persistent_cohomology(min_persistence);\n\n  // Output the diagram in filediag\n  if (filediag.empty()) {\n    pcoh.output_diagram();\n  } else {\n    std::ofstream out(filediag);\n    pcoh.output_diagram(out);\n    out.close();\n  }\n\n  return 0;\n}\n\nvoid program_options(int argc, char * argv[]\n                     , std::string & off_file_points\n                     , std::string & filediag\n                     , Filtration_value & threshold\n                     , int & dim_max\n                     , int & p\n                     , Filtration_value & min_persistence) {\n  namespace po = boost::program_options;\n  po::options_description hidden(\"Hidden options\");\n  hidden.add_options()\n      (\"input-file\", po::value<std::string>(&off_file_points),\n       \"Name of an OFF file containing a point set.\\n\");\n\n  po::options_description visible(\"Allowed options\", 100);\n  visible.add_options()\n      (\"help,h\", \"produce help message\")\n      (\"output-file,o\", po::value<std::string>(&filediag)->default_value(std::string()),\n       \"Name of file in which the persistence diagram is written. Default print in std::cout\")\n      (\"max-edge-length,r\",\n       po::value<Filtration_value>(&threshold)->default_value(std::numeric_limits<Filtration_value>::infinity()),\n       \"Maximal length of an edge for the Rips complex construction.\")\n      (\"cpx-dimension,d\", po::value<int>(&dim_max)->default_value(1),\n       \"Maximal dimension of the Rips complex we want to compute.\")\n      (\"field-charac,p\", po::value<int>(&p)->default_value(11),\n       \"Characteristic p of the coefficient field Z/pZ for computing homology.\")\n      (\"min-persistence,m\", po::value<Filtration_value>(&min_persistence),\n       \"Minimal lifetime of homology feature to be recorded. Default is 0. Enter a negative value to see zero length intervals\");\n\n  po::positional_options_description pos;\n  pos.add(\"input-file\", 1);\n\n  po::options_description all;\n  all.add(visible).add(hidden);\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).\n            options(all).positional(pos).run(), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\") || !vm.count(\"input-file\")) {\n    std::cout << std::endl;\n    std::cout << \"Compute the persistent homology with coefficient field Z/pZ \\n\";\n    std::cout << \"of a Rips complex defined on a set of input points.\\n \\n\";\n    std::cout << \"The output diagram contains one bar per line, written with the convention: \\n\";\n    std::cout << \"   p   dim b d \\n\";\n    std::cout << \"where dim is the dimension of the homological feature,\\n\";\n    std::cout << \"b and d are respectively the birth and death of the feature and \\n\";\n    std::cout << \"p is the characteristic of the field Z/pZ used for homology coefficients.\" << std::endl << std::endl;\n\n    std::cout << \"Usage: \" << argv[0] << \" [options] input-file\" << std::endl << std::endl;\n    std::cout << visible << std::endl;\n    exit(-1);\n  }\n}\n", "meta": {"hexsha": "02db05ec322819966a5da745790135202f84ac13", "size": 6239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Persistent_cohomology/example/rips_persistence_step_by_step.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/example/rips_persistence_step_by_step.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/example/rips_persistence_step_by_step.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": 40.2516129032, "max_line_length": 129, "alphanum_fraction": 0.646257413, "num_tokens": 1485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.523170192939194}}
{"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 joint_distribution_id.hpp\n * \\date Febuary 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#pragma once\n\n\n#include <Eigen/Dense>\n\n#include <fl/util/meta.hpp>\n#include <fl/util/traits.hpp>\n#include <fl/distribution/interface/moments.hpp>\n\nnamespace fl\n{\n\n// Forward declaration\ntemplate <typename...Distribution> class JointDistribution;\n\n/**\n * \\internal\n *\n * Traits of JointDistribution<Distribution...>\n */\ntemplate <typename...Distribution>\nstruct Traits<JointDistribution<Distribution...>>\n{\n    enum : signed int\n    {\n        JointSize = JoinSizes<SizeOf<typename Distribution::Variate>::Value...>::Size\n    };\n\n    typedef typename FirstTypeIn<\n                typename Distribution::Variate...\n            >::Type::Scalar Scalar;\n\n    typedef Eigen::Matrix<Scalar, JointSize, 1> Variate;\n};\n\n/**\n * \\ingroup distributions\n */\ntemplate <typename...Distribution>\nclass JointDistribution\n    : public Moments<typename Traits<JointDistribution<Distribution...>>::Variate>\n{\npublic:\n    typedef typename Traits<JointDistribution<Distribution...>>::Variate Variate;\n    typedef typename Moments<Variate>::SecondMoment SecondMoment;\n    typedef std::tuple<Distribution...> MarginalDistributions;\n\npublic:\n    JointDistribution(Distribution...distributions)\n        : distributions_(distributions...)\n    { }\n\n    /**\n     * \\brief Overridable default destructor\n     */\n    virtual ~JointDistribution() noexcept { }\n\n    virtual Variate mean() const\n    {\n        Variate mu = Variate(dimension(), 1);\n\n        mean_<sizeof...(Distribution)>(distributions_, mu);\n\n        return mu;\n    }\n\n    virtual SecondMoment covariance() const\n    {\n        SecondMoment cov = SecondMoment::Zero(dimension(), dimension());\n\n        covariance<sizeof...(Distribution)>(distributions_, cov);\n\n        return cov;\n    }\n\n    virtual int dimension() const\n    {\n        return expend_dimension(CreateIndexSequence<sizeof...(Distribution)>());\n    }\n\n    MarginalDistributions& distributions()\n    {\n        return distributions_;\n    }\n\n    const MarginalDistributions& distributions() const\n    {\n        return distributions_;\n    }\n\nprotected:\n    MarginalDistributions distributions_;\n\nprivate:\n    template <int...Indices>\n    int expend_dimension(IndexSequence<Indices...>) const\n    {\n        const auto& dims = { std::get<Indices>(distributions_).dimension()... };\n\n        int joint_dim = 0;\n        for (auto dim : dims) { joint_dim += dim; }\n\n        return joint_dim;\n    }\n\n    template <int Size, int k = 0>\n    void mean_(const MarginalDistributions& distr_tuple,\n               Variate& mu,\n               int offset = 0) const\n    {\n        auto&& distribution = std::get<k>(distr_tuple);\n        const int dim = distribution.dimension();\n\n        mu.middleRows(offset, dim) = distribution.mean();\n\n        if (Size == k + 1) return;\n\n        mean_<Size, k + (k + 1 < Size ? 1 : 0)>(distr_tuple, mu, offset + dim);\n    }\n\n    template <int Size, int k = 0>\n    void covariance(const MarginalDistributions& distr,\n                    SecondMoment& cov,\n                    const int offset = 0) const\n    {\n        auto& distribution = std::get<k>(distr);\n        const int dim = distribution.dimension();\n\n        cov.block(offset, offset, dim, dim) = distribution.covariance();\n\n        if (Size == k + 1) return;\n\n        covariance<Size, k + (k + 1 < Size ? 1 : 0)>(distr, cov, offset + dim);\n    }\n};\n\n}\n", "meta": {"hexsha": "1210a93b447abbd4031c6035842d95a7a6b718d8", "size": 3851, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/distribution/joint_distribution_id.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/distribution/joint_distribution_id.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/distribution/joint_distribution_id.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": 24.5286624204, "max_line_length": 85, "alphanum_fraction": 0.6372370813, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5231511601310841}}
{"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_SINHC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SINHC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-hyperbolic\n    Function object implementing sinhc capabilities\n\n    Returns hyperbolic cardinal sine: \\f$\\sinh(x)/x\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type @c T\n\n    @code\n    T r = sinhc(x);\n    @endcode\n\n    @see sinh\n\n  **/\n  Value sinhc(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sinhc.hpp>\n#include <boost/simd/function/simd/sinhc.hpp>\n\n#endif\n", "meta": {"hexsha": "6ea53ea74e7e4d3a304f2d5897096f8e65673dcf", "size": 974, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sinhc.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/sinhc.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/sinhc.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": 22.1363636364, "max_line_length": 100, "alphanum_fraction": 0.5667351129, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5231511594293705}}
{"text": "#include <vector>\n#include <Eigen/Dense>\n#include \"matplotlibcpp.h\"\nnamespace plt = matplotlibcpp;\n\nint main() {\n\n  const unsigned n = 100;\n  Eigen::MatrixXd A(n / 2, n);\n  std::vector<std::vector<double>> B;\n\n  for (unsigned i = 0; i < n / 2; ++i) {\n    A(i, i) = 1;\n    std::vector<double> row(n);\n    row[i] = 1;\n\n    if (i < n / 2) {\n      A(i, i + n / 2) = 1;\n      row[i + n / 2] = 1;\n    }\n    B.push_back(row);\n  }\n\n  for (unsigned i = 0; i < n / 2; ++i) {\n    for (unsigned j = 0; j < n; ++j) {\n      if (A(i, j) != B[i][j]) {\n        std::cout << i << \",\" << j << \" differ!\\n\";\n      }\n    }\n  }\n\n  plt::figure();\n  plt::title(\"Eigen\");\n  plt::spy(A);\n\n  plt::figure();\n  plt::title(\"vector\");\n  plt::spy(B);\n  plt::show();\n  return 0;\n}\n", "meta": {"hexsha": "3a2bea6635a10daaabc579e137afa6d4252d5dbb", "size": 748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/spy.cpp", "max_stars_repo_name": "LucaMac1/matplotlib-cpp", "max_stars_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spy.cpp", "max_issues_repo_name": "LucaMac1/matplotlib-cpp", "max_issues_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spy.cpp", "max_forks_repo_name": "LucaMac1/matplotlib-cpp", "max_forks_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_forks_repo_licenses": ["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.8095238095, "max_line_length": 51, "alphanum_fraction": 0.4652406417, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5231511594293705}}
{"text": "#ifndef TDHH_ROUTER_HPP\n#define TDHH_ROUTER_HPP\n\n#include <string>\n#include \"PacketsReader.hpp\"\n#include \"Hyperloglog.hpp\"\n#include \"Heap.hpp\"\n#include <map>\n#include <boost/functional/hash.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <boost/algorithm/string/predicate.hpp>\n#include \"Utils.hpp\"\n\nnamespace TDHH {\n    using namespace std;\n    using namespace hll;\n\n    const int ITERATIONS = 1;\n\n    class Router {\n\n    private:\n        DATASET dataset;\n\n    protected:\n        string filename;\n        PacketsReader pr;\n\n    public:\n        explicit Router(const string &filename, DATASET dataset) :\n                filename(filename),\n                pr(filename, dataset),\n                dataset(dataset) {}\n\n        void reset() {\n            pr.reset();\n        }\n\n        map<int, map<int, vector<double>>> volumeEstimation(vector<int> counters) {\n            map<int, map<int, vector<double>>> res;\n            std::random_device rd;\n            map<int, vector<HyperLogLog> > counter_to_hll_arr;\n            for (const int c : counters) {\n                auto bits = static_cast<int>(log2(c));\n                vector<HyperLogLog> hll_arr;\n                for (int I = 0; I < ITERATIONS; I++) {\n                    HyperLogLog hll(static_cast<uint8_t>(bits));\n                    hll.set_seed(rd());\n                    hll_arr.push_back(hll);\n                }\n                counter_to_hll_arr.insert(pair<int, vector<HyperLogLog>>(c, hll_arr));\n            }\n            auto pkt = pr.getNextIPPacket();\n            int num_pkts = 0;\n            while (pkt != nullptr) {\n                ++num_pkts;\n                const auto &pkt_string = pkt->getReprString();\n                for (const int c: counters) {\n                    for (auto &hll : counter_to_hll_arr.at(c)) {\n                        hll.add(pkt_string.c_str(), static_cast<int>(pkt_string.size()));\n                    }\n                }\n                delete pkt;\n                if (num_pkts % 1000000 == 0) {\n                    for (const int c: counters) {\n                        for (const auto &hll : counter_to_hll_arr.at(c)) {\n                            res[c][num_pkts].push_back(hll.estimate());\n                        }\n                    }\n                }\n                pkt = pr.getNextIPPacket();\n            }\n            for (const int c: counters) {\n                for (const auto &hll : counter_to_hll_arr.at(c)) {\n                    res[c][num_pkts].push_back(hll.estimate());\n                }\n            }\n            return res;\n        }\n\n        map<pair<double, double>, vector<map<string, double>>> heavy_hitters(vector<pair<double, double>> params) {\n            map<pair<double, double>, vector<map<string, double>>> res;\n\n            map<pair<double, double>, vector<Heap *>> param_to_heap_arr;\n            for (const auto &param : params) {\n                double eps = param.first;\n                double delta = param.second;\n                auto chi = static_cast<unsigned int>(ceil(9.0 / (eps * eps) * log2(2.0 / (delta * eps))));\n                vector<Heap *> heap_arr;\n                for (int I = 0; I < ITERATIONS; I++) {\n                    auto *heap = new Heap(chi);\n                    heap_arr.push_back(heap);\n                }\n                param_to_heap_arr.insert(pair<pair<double, double>, vector<Heap *>>(param, heap_arr));\n            }\n\n            unsigned int num_pkts = 0;\n            auto pkt = pr.getNextIPPacket();\n            while (pkt != nullptr) {\n                for (const auto &param : params) {\n                    for (auto &heap : param_to_heap_arr.at(param)) {\n                        heap->Add(pkt->getReprString());\n                    }\n                }\n                delete pkt;\n                pkt = pr.getNextIPPacket();\n                ++num_pkts;\n            }\n\n            for (const auto &param : params) {\n                vector<map<string, double>> samples;\n                for (auto &heap : param_to_heap_arr.at(param)) {\n                    samples.push_back(heap->GetSample());\n                }\n                res.insert(pair<pair<double, double>, vector<map<string, double>>>(param, samples));\n            }\n\n            for (const auto &param : params) {\n                for (auto &heap : param_to_heap_arr.at(param)) {\n                    delete heap;\n                }\n            }\n\n            return res;\n        }\n\n        int doNothing() {\n            auto pkt = pr.getNextIPPacket();\n            int num_pkts = 0;\n            while (pkt != nullptr) {\n                ++num_pkts;\n                const auto &pkt_string = pkt->getReprString();\n                delete pkt;\n                pkt = pr.getNextIPPacket();\n            }\n            return num_pkts;\n        }\n\n        map<pair<double, double>, vector<map<string, double>>>\n        frequencyEstimation(vector<pair<double, double>> params) {\n            map<pair<double, double>, vector<map<string, double>>> res;\n            std::random_device rd;\n\n            map<pair<double, double>, vector<HyperLogLog>> param_to_hll_arr;\n            for (const auto &param : params) {\n                double eps = param.first;\n                double delta = param.second;\n                auto counters = static_cast<int>(pow((3 / eps), 2));\n                auto bits = static_cast<int>(log2(counters));\n                vector<HyperLogLog> hll_arr;\n                for (int I = 0; I < ITERATIONS; I++) {\n                    HyperLogLog hll(static_cast<uint8_t>(bits));\n                    hll.set_seed(rd());\n                    hll_arr.push_back(hll);\n                }\n                param_to_hll_arr.insert(pair<pair<double, double>, vector<HyperLogLog>>(param, hll_arr));\n            }\n\n            map<pair<double, double>, vector<Heap *>> param_to_heap_arr;\n            for (const auto &param : params) {\n                double eps = param.first;\n                double delta = param.second;\n                auto chi = static_cast<unsigned int>(ceil(3.0 / (eps / 2 * eps / 2) * log2(2.0 / delta / 2)));\n                vector<Heap *> heap_arr;\n                for (int I = 0; I < ITERATIONS; I++) {\n                    auto *heap = new Heap(chi);\n                    heap_arr.push_back(heap);\n                }\n                param_to_heap_arr.insert(pair<pair<double, double>, vector<Heap *>>(param, heap_arr));\n            }\n\n            int num_pkts = 0;\n            std::clock_t start;\n            start = std::clock();\n            double duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;\n            cout << \"pkts:\" << num_pkts << \" duration:\" << duration << \"[s]\" << endl;\n            auto pkt = pr.getNextIPPacket();\n            while (pkt != nullptr) {\n                ++num_pkts;\n                if (num_pkts > stoi(getFrequencyLimit(dataset))) {\n                    break;\n                }\n                const auto &pkt_string = pkt->getReprString();\n                for (const auto &param : params) {\n                    for (auto &hll : param_to_hll_arr.at(param)) {\n                        hll.add(pkt_string.c_str(), static_cast<int>(pkt_string.size()));\n                    }\n                    for (auto &heap : param_to_heap_arr.at(param)) {\n                        heap->Add(pkt->getReprString());\n                    }\n                }\n                delete pkt;\n                if (num_pkts % 1000000 == 0) {\n                    duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;\n                    cout << \"pkts:\" << num_pkts << \" duration:\" << duration << \"[s]\" << endl;\n                }\n                pkt = pr.getNextIPPacket();\n            }\n            for (const auto &param : params) {\n                double eps = param.first;\n                double delta = param.second;\n                double chi = ceil(3.0 / (eps / 2 * eps / 2) * log2(2.0 / delta / 2));\n                cout << eps << \" \" << delta << \" \" << chi << endl;\n\n                vector<double> Ps;\n                vector<map<string, double>> samples;\n\n                for (auto &hll : param_to_hll_arr.at(param)) {\n                    double d = hll.estimate();\n                    cout << \"hll.estimate:\" << d << endl;\n                    Ps.push_back(chi / hll.estimate());\n                }\n                for (auto &heap : param_to_heap_arr.at(param)) {\n                    const auto &s = heap->GetSample();\n                    samples.push_back(s);\n                }\n\n                for (int k = 0; k < samples.size(); ++k) {\n                    auto &sample = samples[k];\n                    auto p = Ps[k];\n                    cout << \"p:\" << p << endl;\n                    for (const auto &s : sample) {\n                        cout << \"flow:\" << s.first << endl;\n                        cout << \"sampled_frequency:\" << s.second << endl;\n                        double estimated_frequency = s.second / p;\n                        sample[s.first] = estimated_frequency;\n                        cout << \"estimated_frequency:\" << estimated_frequency << endl;\n                    }\n                    res[param] = samples;\n                }\n            }\n            cout << \"Finished preparing samples\" << endl;\n\n            for (const auto &param : params) {\n                for (auto &heap : param_to_heap_arr.at(param)) {\n                    delete heap;\n                }\n            }\n            cout << \"Finished deleting heaps\" << endl;\n            return res;\n        }\n    };\n}\n\n#endif //TDHH_ROUTER_HPP\n", "meta": {"hexsha": "11013983a998f2566a2824c73308b40b461d6399", "size": 9503, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Router.hpp", "max_stars_repo_name": "jalilm/TDHH", "max_stars_repo_head_hexsha": "3b10cdde18103573949d1b334afa304c539ada3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-12-12T12:55:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T09:20:14.000Z", "max_issues_repo_path": "src/Router.hpp", "max_issues_repo_name": "jalilm/TDHH", "max_issues_repo_head_hexsha": "3b10cdde18103573949d1b334afa304c539ada3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Router.hpp", "max_forks_repo_name": "jalilm/TDHH", "max_forks_repo_head_hexsha": "3b10cdde18103573949d1b334afa304c539ada3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-05T01:50:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T01:50:25.000Z", "avg_line_length": 38.6300813008, "max_line_length": 115, "alphanum_fraction": 0.462380301, "num_tokens": 2026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5231511532918888}}
{"text": "//  Copyright John Maddock 2006.\n//  Copyright Paul A. Bristow 2007\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/test/included/test_exec_monitor.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/special_functions/erf.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 \"test_erf_hooks.hpp\"\n#include \"handle_test_result.hpp\"\n\n//\n// DESCRIPTION:\n// ~~~~~~~~~~~~\n//\n// This file tests the functions erf, erfc, and the inverses\n// erf_inv and erfc_inv.  There are two sets of tests, spot\n// tests which compare our results with selected values computed\n// using the online special function calculator at\n// functions.wolfram.com, while the bulk of the accuracy tests\n// use values generated with NTL::RR at 1000-bit precision\n// and our generic versions of these functions.\n//\n// Note that when this file is first run on a new platform many of\n// these tests will fail: the default accuracy is 1 epsilon which\n// is too tight for most platforms.  In this situation you will\n// need to cast a human eye over the error rates reported and make\n// a judgement as to whether they are acceptable.  Either way please\n// report the results to the Boost mailing list.  Acceptable rates of\n// error are marked up below as a series of regular expressions that\n// identify the compiler/stdlib/platform/data-type/test-data/test-function\n// along with the maximum expected peek and RMS mean errors for that\n// test.\n//\n\nvoid expected_results()\n{\n   //\n   // Define the max and mean errors expected for\n   // various compilers and platforms.\n   //\n   const char* largest_type;\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())\n   {\n      largest_type = \"(long\\\\s+)?double|real_concept\";\n   }\n   else\n   {\n      largest_type = \"long double|real_concept\";\n   }\n#else\n   largest_type = \"(long\\\\s+)?double\";\n#endif\n   //\n   // On MacOS X erfc has much higher error levels than\n   // expected: given that the implementation is basically\n   // just a rational function evaluation combined with\n   // exponentiation, we conclude that exp and pow are less\n   // accurate on this platform, especially when the result \n   // is outside the range of a double.\n   //\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"Mac OS\",                      // platform\n      largest_type,                  // test type(s)\n      \"Erf Function:.*Large.*\",      // test data group\n      \"boost::math::erfc\", 4300, 1300);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"Mac OS\",                      // platform\n      largest_type,                  // test type(s)\n      \"Erf Function:.*\",             // test data group\n      \"boost::math::erfc\", 40, 10);  // test function\n\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"real_concept\",                // test type(s)\n      \"Erf Function:.*\",             // test data group\n      \"boost::math::erfc?\", 20, 6);   // test function\n   add_expected_result(\n      \".*\",                           // compiler\n      \".*\",                           // stdlib\n      \".*\",                           // platform\n      \"real_concept\",                 // test type(s)\n      \"Inverse Erfc.*\",               // test data group\n      \"boost::math::erfc_inv\", 80, 10);  // test function\n\n\n   //\n   // Catch all cases come last:\n   //\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \".*\",                          // test type(s)\n      \"Erf Function:.*\",             // test data group\n      \"boost::math::erfc?\", 2, 2);   // test function\n   add_expected_result(\n      \".*aCC.*\",                     // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \".*\",                          // test type(s)\n      \"Inverse Erfc.*\",               // test data group\n      \"boost::math::erfc_inv\", 80, 10);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \".*\",                          // test type(s)\n      \"Inverse Erf.*\",               // test data group\n      \"boost::math::erfc?_inv\", 18, 4);  // test function\n\n   //\n   // Finish off by printing out the compiler/stdlib/platform names,\n   // we do this to make it easier to mark up expected error rates.\n   //\n   std::cout << \"Tests run with \" << BOOST_COMPILER << \", \"\n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << std::endl;\n}\n\ntemplate <class T>\nvoid do_test_erf(const T& data, const char* type_name, const char* test_name)\n{\n   typedef typename T::value_type row_type;\n   typedef typename row_type::value_type value_type;\n\n   typedef value_type (*pg)(value_type);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::erf<value_type>;\n#else\n   pg funcp = boost::math::erf;\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 erf against data:\n   //\n   result = boost::math::tools::test(\n      data,\n      bind_func(funcp, 0),\n      extract_result(1));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::erf\", test_name);\n#ifdef TEST_OTHER\n   if(::boost::is_floating_point<value_type>::value){\n      funcp = other::erf;\n      result = boost::math::tools::test(\n         data,\n         bind_func(funcp, 0),\n         extract_result(1));\n      print_test_result(result, data[result.worst()], result.worst(), type_name, \"other::erf\");\n   }\n#endif\n   //\n   // test erfc against data:\n   //\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   funcp = boost::math::erfc<value_type>;\n#else\n   funcp = boost::math::erfc;\n#endif\n   result = boost::math::tools::test(\n      data,\n      bind_func(funcp, 0),\n      extract_result(2));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::erfc\", test_name);\n#ifdef TEST_OTHER\n   if(::boost::is_floating_point<value_type>::value){\n      funcp = other::erfc;\n      result = boost::math::tools::test(\n         data,\n         bind(funcp, 0),\n         extract_result(2));\n      print_test_result(result, data[result.worst()], result.worst(), type_name, \"other::erfc\");\n   }\n#endif\n   std::cout << std::endl;\n}\n\ntemplate <class T>\nvoid do_test_erf_inv(const T& data, const char* type_name, const char* test_name)\n{\n   typedef typename T::value_type row_type;\n   typedef typename row_type::value_type value_type;\n\n   typedef value_type (*pg)(value_type);\n\n   boost::math::tools::test_result<value_type> result;\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n   //\n   // test erf_inv against data:\n   //\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::erf_inv<value_type>;\n#else\n   pg funcp = boost::math::erf_inv;\n#endif\n   result = boost::math::tools::test(\n      data,\n      bind_func(funcp, 0),\n      extract_result(1));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::erf_inv\", test_name);\n   std::cout << std::endl;\n}\n\ntemplate <class T>\nvoid do_test_erfc_inv(const T& data, const char* type_name, const char* test_name)\n{\n   typedef typename T::value_type row_type;\n   typedef typename row_type::value_type value_type;\n\n   typedef value_type (*pg)(value_type);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::erf<value_type>;\n#else\n   pg funcp = boost::math::erf;\n#endif\n\n   boost::math::tools::test_result<value_type> result;\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n   //\n   // test erfc_inv against data:\n   //\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   funcp = boost::math::erfc_inv<value_type>;\n#else\n   funcp = boost::math::erfc_inv;\n#endif\n   result = boost::math::tools::test(\n      data,\n      bind_func(funcp, 0),\n      extract_result(1));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::erfc_inv\", test_name);\n   std::cout << std::endl;\n}\n\ntemplate <class T>\nvoid test_erf(T, const char* name)\n{\n   //\n   // The actual test data is rather verbose, so it's in a separate file\n   //\n   // The contents are as follows, each row of data contains\n   // three items, input value a, input value b and erf(a, b):\n   //\n#  include \"erf_small_data.ipp\"\n\n   do_test_erf(erf_small_data, name, \"Erf Function: Small Values\");\n\n#  include \"erf_data.ipp\"\n\n   do_test_erf(erf_data, name, \"Erf Function: Medium Values\");\n\n#  include \"erf_large_data.ipp\"\n\n   do_test_erf(erf_large_data, name, \"Erf Function: Large Values\");\n\n#  include \"erf_inv_data.ipp\"\n\n   do_test_erf_inv(erf_inv_data, name, \"Inverse Erf Function\");\n\n#  include \"erfc_inv_data.ipp\"\n\n   do_test_erfc_inv(erfc_inv_data, name, \"Inverse Erfc Function\");\n\n#  include \"erfc_inv_big_data.ipp\"\n\n   if(std::numeric_limits<T>::min_exponent <= -4500)\n   {\n      do_test_erfc_inv(erfc_inv_big_data, name, \"Inverse Erfc Function: extreme values\");\n   }\n}\n\ntemplate <class T>\nvoid test_spots(T, const char* t)\n{\n   std::cout << \"Testing basic sanity checks for type \" << t << std::endl;\n   //\n   // basic sanity checks, tolerance is 10 epsilon expressed as a percentage:\n   //\n   T tolerance = boost::math::tools::epsilon<T>() * 1000;\n   BOOST_CHECK_CLOSE(::boost::math::erfc(static_cast<T>(0.125)), static_cast<T>(0.85968379519866618260697055347837660181302041685015L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::erfc(static_cast<T>(0.5)), static_cast<T>(0.47950012218695346231725334610803547126354842424204L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::erfc(static_cast<T>(1)), static_cast<T>(0.15729920705028513065877936491739074070393300203370L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::erfc(static_cast<T>(5)), static_cast<T>(1.5374597944280348501883434853833788901180503147234e-12L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::erfc(static_cast<T>(-0.125)), static_cast<T>(1.1403162048013338173930294465216233981869795831498L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::erfc(static_cast<T>(-0.5)), static_cast<T>(1.5204998778130465376827466538919645287364515757580L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::erfc(static_cast<T>(0)), static_cast<T>(1), tolerance);\n\n   BOOST_CHECK_CLOSE(::boost::math::erf(static_cast<T>(0.125)), static_cast<T>(0.14031620480133381739302944652162339818697958314985L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::erf(static_cast<T>(0.5)), static_cast<T>(0.52049987781304653768274665389196452873645157575796L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::erf(static_cast<T>(1)), static_cast<T>(0.84270079294971486934122063508260925929606699796630L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::erf(static_cast<T>(5)), static_cast<T>(0.9999999999984625402055719651498116565146166211099L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::erf(static_cast<T>(-0.125)), static_cast<T>(-0.14031620480133381739302944652162339818697958314985L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::erf(static_cast<T>(-0.5)), static_cast<T>(-0.52049987781304653768274665389196452873645157575796L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::erf(static_cast<T>(0)), static_cast<T>(0), tolerance);\n\n   tolerance = boost::math::tools::epsilon<T>() * 100 * 200; // 200 eps %.\n#if defined(__CYGWIN__)\n   // some platforms long double is only reliably accurate to double precision:\n   if(sizeof(T) == sizeof(long double))\n      tolerance = boost::math::tools::epsilon<double>() * 100 * 200; // 200 eps %.\n#endif\n\n   for(T i = -0.95f; i < 1; i += 0.125f)\n   {\n      T inv = boost::math::erf_inv(i);\n      T b = boost::math::erf(inv);\n      BOOST_CHECK_CLOSE(b, i, tolerance);\n   }\n   for(T j = 0.125f; j < 2; j += 0.125f)\n   {\n      T inv = boost::math::erfc_inv(j);\n      T b = boost::math::erfc(inv);\n      BOOST_CHECK_CLOSE(b, j, tolerance);\n   }\n}\n\nint test_main(int, char* [])\n{\n   BOOST_MATH_CONTROL_FP;\n   test_spots(0.0F, \"float\");\n   test_spots(0.0, \"double\");\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   test_spots(0.0L, \"long double\");\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n   test_spots(boost::math::concepts::real_concept(0.1), \"real_concept\");\n#endif\n#endif\n\n   expected_results();\n\n   test_erf(0.1F, \"float\");\n   test_erf(0.1, \"double\");\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   test_erf(0.1L, \"long double\");\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n   test_erf(boost::math::concepts::real_concept(0.1), \"real_concept\");\n#endif\n#endif\n#else\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\n      \"either because the long double overloads of the usual math functions are \"\n      \"not available at all, or because they are too inaccurate for these tests \"\n      \"to pass.</note>\" << std::cout;\n#endif\n   return 0;\n}\n\n/*\n\nOutput:\n\ntest_erf.cpp\nCompiling manifest to resources...\nLinking...\nEmbedding manifest...\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\test_erf.exe\"\nRunning 1 test case...\nTesting basic sanity checks for type float\nTesting basic sanity checks for type double\nTesting basic sanity checks for type long double\nTesting basic sanity checks for type real_concept\nTests run with Microsoft Visual C++ version 8.0, Dinkumware standard library version 405, Win32\nTesting Erf Function: Small Values with type float\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf<float> Max = 0 RMS Mean=0\nboost::math::erfc<float> Max = 0 RMS Mean=0\nTesting Erf Function: Medium Values with type float\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf<float> Max = 0 RMS Mean=0\nboost::math::erfc<float> Max = 0 RMS Mean=0\nTesting Erf Function: Large Values with type float\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf<float> Max = 0 RMS Mean=0\nboost::math::erfc<float> Max = 0 RMS Mean=0\nTesting Inverse Erf Function with type float\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf_inv<float> Max = 0 RMS Mean=0\nTesting Inverse Erfc Function with type float\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erfc_inv<float> Max = 0 RMS Mean=0\nTesting Erf Function: Small Values with type double\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf<double> Max = 0 RMS Mean=0\nboost::math::erfc<double> Max = 0.7857 RMS Mean=0.06415\n    worst case at row: 149\n    { 0.3343, 0.3636, 0.6364 }\nTesting Erf Function: Medium Values with type double\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf<double> Max = 0.9219 RMS Mean=0.1016\n    worst case at row: 273\n    { 0.5252, 0.5424, 0.4576 }\nboost::math::erfc<double> Max = 1.08 RMS Mean=0.3224\n    worst case at row: 287\n    { 0.8461, 0.7685, 0.2315 }\nTesting Erf Function: Large Values with type double\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf<double> Max = 0 RMS Mean=0\nboost::math::erfc<double> Max = 1.048 RMS Mean=0.2032\n    worst case at row: 50\n    { 20.96, 1, 4.182e-193 }\nTesting Inverse Erf Function with type double\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf_inv<double> Max = 1.124 RMS Mean=0.5082\n    worst case at row: 98\n    { 0.9881, 1.779 }\nTesting Inverse Erfc Function with type double\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erfc_inv<double> Max = 1.124 RMS Mean=0.5006\n    worst case at row: 98\n    { 1.988, -1.779 }\nTesting Erf Function: Small Values with type long double\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf<long double> Max = 0 RMS Mean=0\nboost::math::erfc<long double> Max = 0.7857 RMS Mean=0.06415\n    worst case at row: 149\n    { 0.3343, 0.3636, 0.6364 }\nTesting Erf Function: Medium Values with type long double\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf<long double> Max = 0.9219 RMS Mean=0.1016\n    worst case at row: 273\n    { 0.5252, 0.5424, 0.4576 }\nboost::math::erfc<long double> Max = 1.08 RMS Mean=0.3224\n    worst case at row: 287\n    { 0.8461, 0.7685, 0.2315 }\nTesting Erf Function: Large Values with type long double\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf<long double> Max = 0 RMS Mean=0\nboost::math::erfc<long double> Max = 1.048 RMS Mean=0.2032\n    worst case at row: 50\n    { 20.96, 1, 4.182e-193 }\nTesting Inverse Erf Function with type long double\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf_inv<long double> Max = 1.124 RMS Mean=0.5082\n    worst case at row: 98\n    { 0.9881, 1.779 }\nTesting Inverse Erfc Function with type long double\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erfc_inv<long double> Max = 1.124 RMS Mean=0.5006\n    worst case at row: 98\n    { 1.988, -1.779 }\nTesting Erf Function: Small Values with type real_concept\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf<real_concept> Max = 1.271 RMS Mean=0.5381\n    worst case at row: 144\n    { 0.0109, 0.0123, 0.9877 }\nboost::math::erfc<real_concept> Max = 0.7857 RMS Mean=0.07777\n    worst case at row: 149\n    { 0.3343, 0.3636, 0.6364 }\nTesting Erf Function: Medium Values with type real_concept\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf<real_concept> Max = 22.5 RMS Mean=4.224\n    worst case at row: 233\n    { -0.7852, -0.7332, 1.733 }\nPeak error greater than expected value of 20\ni:/boost-sandbox/math_toolkit/libs/math/test/handle_test_result.hpp(146): error in \"test_main_caller( argc, argv )\": check bounds.first >= max_error_found failed\nboost::math::erfc<real_concept> Max = 97.77 RMS Mean=8.373\n    worst case at row: 289\n    { 0.9849, 0.8363, 0.1637 }\nPeak error greater than expected value of 20\ni:/boost-sandbox/math_toolkit/libs/math/test/handle_test_result.hpp(146): error in \"test_main_caller( argc, argv )\": check bounds.first >= max_error_found failed\nMean error greater than expected value of 6\ni:/boost-sandbox/math_toolkit/libs/math/test/handle_test_result.hpp(151): error in \"test_main_caller( argc, argv )\": check bounds.second >= mean_error_found failed\nTesting Erf Function: Large Values with type real_concept\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf<real_concept> Max = 0 RMS Mean=0\nboost::math::erfc<real_concept> Max = 1.395 RMS Mean=0.2908\n    worst case at row: 11\n    { 10.99, 1, 1.87e-054 }\nTesting Inverse Erf Function with type real_concept\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erf_inv<real_concept> Max = 1.124 RMS Mean=0.5082\n    worst case at row: 98\n    { 0.9881, 1.779 }\nTesting Inverse Erfc Function with type real_concept\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nboost::math::erfc_inv<real_concept> Max = 1.124 RMS Mean=0.5006\n    worst case at row: 98\n    { 1.988, -1.779 }\nTest suite \"Test Program\" failed with:\n  181 assertions out of 184 passed\n  3 assertions out of 184 failed\n  1 test case out of 1 failed\n  Test case \"test_main_caller( argc, argv )\" failed with:\n    181 assertions out of 184 passed\n    3 assertions out of 184 failed\nBuild Time 0:15\n\n*/\n", "meta": {"hexsha": "70880439c14bfddae186623bb374e5880ee295e3", "size": 20505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_erf.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/math/test/test_erf.cpp", "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": 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_erf.cpp", "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": 40.2058823529, "max_line_length": 163, "alphanum_fraction": 0.6125335284, "num_tokens": 5549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.5231511532918887}}
{"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_ASINPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASINPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing asinpi capabilities\n\n    inverse sine in \\f$\\pi\\f$ multiples.\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = asinpi(x);\n    @endcode\n\n    Returns the arc @c r in the interval\n    \\f$[-0.5, 0.5[\\f$ such that <tt>cos(r) == x</tt>.\n    If @c x is outside \\f$[-1, 1[\\f$ the result is Nan.\n\n    @see asin, asind, sinpi\n  **/\n  Value asinpi(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/asinpi.hpp>\n#include <boost/simd/function/simd/asinpi.hpp>\n\n#endif\n", "meta": {"hexsha": "4727d7849276da1932d75dea3196711e248295fd", "size": 1131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/asinpi.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/asinpi.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/asinpi.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.5869565217, "max_line_length": 100, "alphanum_fraction": 0.5694076039, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5231511532918887}}
{"text": "/** @file components.cc\n * @author David F. Gleich\n * @date 2006-04-19\n * @copyright Stanford University, 2006-2008\n * Implement wrappers for connected component functions\n */\n\n/** History\n *  2006-04-19: Initial version\n *  2007-07-09: Updated to use simple_csr_matrix graph type\n */\n\n#include \"include/matlab_bgl.h\"\n\n#include <yasmic/simple_csr_matrix_as_graph.hpp>\n#include <yasmic/iterator_utility.hpp>\n#include <boost/graph/biconnected_components.hpp>\n#include <boost/graph/strong_components.hpp>\n\nint strong_components(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, /* connectivity params */\n    mbglIndex* ci)\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  strong_components(g, make_iterator_property_map(ci, get(vertex_index, g)));\n\n  return 0;\n}\n\n/**\n * Wrap a boost graph library call to biconnected_components.\n *\n * the ja and ia arrays specify the connectivity of the underlying graph,\n * ia is a length (nverts+1) array with the indices in ja that start the\n * nonzeros in each row.  ja is a length (ia(nverts)) array with the\n * columns of the connectivity.\n *\n * if a or ci is NULL, then that parameter is not computed.\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 a an array which will store the articulaion points of the graph\n *     the array length should be n\n * @param ci the component index array which is length (nnz)\n * @return an error code if possible\n */\n\nint biconnected_components(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, /* connectivity params */\n    mbglIndex* a, mbglIndex* ci)\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 (a) {\n    if (ci) {\n      std::size_t num_bicomps;\n      mbglIndex *oi;\n      boost::tie(num_bicomps, oi) = biconnected_components(g,\n          make_iterator_property_map(ci, get(edge_index, g)), a);\n    } else {\n      articulation_points(g, a);\n    }\n  } else {\n    biconnected_components(g,\n        make_iterator_property_map(ci, get(edge_index, g)));\n  }\n\n  return 0;\n}\n\n", "meta": {"hexsha": "bcd77f55093c07beb96cf4f796e3b8d7f011308b", "size": 2319, "ext": "cc", "lang": "C++", "max_stars_repo_path": "2A/Graphes/TPs/matlab_bgl/libmbgl/components.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/components.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/components.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": 28.6296296296, "max_line_length": 77, "alphanum_fraction": 0.7128072445, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.5231190885283131}}
{"text": "#include \"gtest/gtest.h\"\n#include <Eigen/Core>\n#include \"MeshFactory.h\"\n\nnamespace {\n\n  using namespace Geotree;\n  \n  class MeshFactoryTest : public ::testing::Test {\n  protected:\n    MeshFactoryTest()\n    {\n    }\n    ~MeshFactoryTest()\n    {\n    }\n    MeshFactory factory;\n  };\n\n  void verifyCube(Mesh cube, double x, double y, double z)\n  {\n    EXPECT_EQ(12, cube.size());\n    EXPECT_EQ(12, cube.rowcount());\n    EXPECT_EQ(8, cube.V.rows());\n\n    EXPECT_EQ(4*(x+y+z), cube.V.sum());\n\n    EXPECT_TRUE( (cube.V.array() == x ||\n\t\t  cube.V.array() == y ||\n\t\t  cube.V.array() == z ||\n\t\t  cube.V.array() == 0.0).all());\n\n    EXPECT_GE((cube.V.array() == x).count(), 4);\n    EXPECT_GE((cube.V.array() == y).count(), 4);\n    EXPECT_GE((cube.V.array() == z).count(), 4);\n    EXPECT_EQ(12, (cube.V.array() == 0.0).count());\n\n    EXPECT_EQ(1, (cube.V.rowwise().sum().array() == 0.0).count());\n    EXPECT_GE((cube.V.rowwise().sum().array() == x).count(), 1);\n    EXPECT_GE((cube.V.rowwise().sum().array() == y).count(), 1);\n    EXPECT_GE((cube.V.rowwise().sum().array() == z).count(), 1);\n    EXPECT_GE((cube.V.rowwise().sum().array() == x+y).count(), 1);\n    EXPECT_GE((cube.V.rowwise().sum().array() == x+z).count(), 1);\n    EXPECT_GE((cube.V.rowwise().sum().array() == y+z).count(), 1);\n    EXPECT_GE((cube.V.rowwise().sum().array() == x+y+z).count(), 1);\n\n    EXPECT_EQ(x*4, cube.V.col(0).sum());\n    EXPECT_EQ(y*4, cube.V.col(1).sum());\n    EXPECT_EQ(z*4, cube.V.col(2).sum());\n  }\n\n  void nullCube(Mesh cube)\n  {\n    EXPECT_EQ(0, cube.size());\n    EXPECT_EQ(0, cube.V.rows());\n    EXPECT_EQ(0, cube.rowcount());\n  }\n\n  TEST_F(MeshFactoryTest, cube)\n  {\n    Mesh cube = factory.makeCube(10,10,10);\n    \n    EXPECT_EQ(12, cube.size());\n    EXPECT_EQ(8, cube.V.rows());\n\n    EXPECT_EQ(120.0, cube.V.sum());\n\t\n    EXPECT_EQ(12,(cube.V.array() == 10.0).count() );\n\n    EXPECT_EQ(1, (cube.V.rowwise().sum().array() == 30.0).count());\n    EXPECT_EQ(3, (cube.V.rowwise().sum().array() == 20.0).count());\n    EXPECT_EQ(3, (cube.V.rowwise().sum().array() == 10.0).count());\n\n    EXPECT_EQ(40.0, cube.V.col(0).sum());\n    EXPECT_EQ(40.0, cube.V.col(1).sum());\n    EXPECT_EQ(40.0, cube.V.col(2).sum());\n  }\n\n  TEST_F(MeshFactoryTest, cubesVerify)\n  {\n    verifyCube(factory.makeCube(10, 10, 10), 10.0, 10.0, 10.0);\n    verifyCube(factory.makeCube(1.0, 2.0, 3.0), 1.0, 2.0, 3.0);\n    verifyCube(factory.makeCube(1.0, 1.0, 2.0), 1.0, 1.0, 2.0);\n    verifyCube(factory.makeCube(1.0, 2.0, 1.0), 1.0, 2.0, 1.0);\n    verifyCube(factory.makeCube(0.0001, 0.567, 100.3), 0.0001, 0.567, 100.3);\n  }\n\n  TEST_F(MeshFactoryTest, cubeInvalid)\n  {\n    nullCube(factory.makeCube(0,0,0));\n    nullCube(factory.makeCube(0.0, 10, 10));\n    nullCube(factory.makeCube(10, 0.0, 10));\n    nullCube(factory.makeCube(10, 10, 0.0));\n    nullCube(factory.makeCube(-1.0, 10, 10));\n    nullCube(factory.makeCube(10, -1.0, 10));\n    nullCube(factory.makeCube(10, 10, -1.0));\n  }\n\n    TEST_F(MeshFactoryTest, tetra)\n    {\n      Mesh tetra = factory.makeTetra(10);\n    }\n\n  TEST_F(MeshFactoryTest, DISABLED_sphere)\n  {\n    Mesh sphere = factory.makeSphere(10);\n\n    EXPECT_EQ(20, sphere.size());\n  }\n\n  TEST_F(MeshFactoryTest, DISABLED_cylinder)\n  {\n    Mesh cylinder = factory.makeCylinder(10, 10);\n\n    EXPECT_EQ(20, cylinder.size());\n  }\n\n    //  TEST_F(MeshTest, translate)\n//  {\n//    Mesh cube = mf.makeCube(10,10,10);\n//    Mesh cubeTranslate;\n//\n//    cubeTranslate = cube;\n//    cubeTranslate.translate(Vertex(10,0,0));\n//    verifyTranslate(cube, cubeTranslate, 10,0,0);\n//\n//    cubeTranslate = cube;\n//    cubeTranslate.translate(Vertex(0,0,0));\n//    verifyTranslate(cube, cubeTranslate, 0,0,0);\n//\n//    cubeTranslate = cube;\n//    cubeTranslate.translate(Vertex(-10.1, -55.2, -3.2));\n//    verifyTranslate(cube, cubeTranslate, -10.1, -55.2, -3.2);\n//  }\n}\n", "meta": {"hexsha": "88b91a3a0f2711a4146ff56b676c5a0832f74f24", "size": 3823, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/meshfactory.cc", "max_stars_repo_name": "untaugh/geotree", "max_stars_repo_head_hexsha": "4600a1cb4115094ed5c4c1500c6221a458e68be8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-27T00:58:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T22:26:10.000Z", "max_issues_repo_path": "test/meshfactory.cc", "max_issues_repo_name": "untaugh/geotree", "max_issues_repo_head_hexsha": "4600a1cb4115094ed5c4c1500c6221a458e68be8", "max_issues_repo_licenses": ["MIT"], "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/meshfactory.cc", "max_forks_repo_name": "untaugh/geotree", "max_forks_repo_head_hexsha": "4600a1cb4115094ed5c4c1500c6221a458e68be8", "max_forks_repo_licenses": ["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.1102941176, "max_line_length": 77, "alphanum_fraction": 0.5919434999, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.523119079607742}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2006 - 2020 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\n\n// @sect3{Include files and global variables}  \n\n// \u5173\u4e8e\u5305\u542b\u6587\u4ef6\u7684\u89e3\u91ca\uff0c\u8bfb\u8005\u5e94\u8be5\u53c2\u8003\u793a\u4f8b\u7a0b\u5e8f  step-1  \u5230  step-4  \u3002\u5b83\u4eec\u7684\u6807\u51c6\u987a\u5e8f\u662f  <code>base</code> -- <code>lac</code> -- <code>grid</code>  --  <code>dofs</code> -- <code>fe</code> -- <code>numerics</code>  \uff08\u56e0\u4e3a\u6bcf\u4e00\u7c7b\u5927\u81f4\u90fd\u662f\u5efa\u7acb\u5728\u524d\u9762\u7684\u57fa\u7840\u4e0a\uff09\uff0c\u7136\u540e\u662f\u4e00\u4e9b\u7528\u4e8e\u6587\u4ef6\u8f93\u5165/\u8f93\u51fa\u548c\u5b57\u7b26\u4e32\u6d41\u7684C++\u5934\u6587\u4ef6\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/utilities.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\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_values.h> \n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n\n#include <fstream> \n#include <iostream> \n\n// \u6700\u540e\u4e00\u6b65\u548c\u4ee5\u524d\u6240\u6709\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\n\nnamespace Step25 \n{ \n  using namespace dealii; \n// @sect3{The <code>SineGordonProblem</code> class template}  \n\n// \u89e3\u51b3\u95ee\u9898\u7684\u6574\u4e2a\u7b97\u6cd5\u88ab\u5c01\u88c5\u5728\u8fd9\u4e2a\u7c7b\u4e2d\u3002\u548c\u4ee5\u524d\u7684\u4f8b\u5b50\u7a0b\u5e8f\u4e00\u6837\uff0c\u8fd9\u4e2a\u7c7b\u5728\u58f0\u660e\u65f6\u6709\u4e00\u4e2a\u6a21\u677f\u53c2\u6570\uff0c\u5c31\u662f\u7a7a\u95f4\u7ef4\u5ea6\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u5728\u4e00\u4e2a\u3001\u4e24\u4e2a\u6216\u4e09\u4e2a\u7a7a\u95f4\u7ef4\u5ea6\u4e0a\u89e3\u51b3\u6b63\u5f26-\u6208\u767b\u65b9\u7a0b\u3002\u5173\u4e8e\u8fd9\u4e2a\u95ee\u9898\u7684\u72ec\u7acb\u4e8e\u7ef4\u5ea6\u7684\u7c7b\u5c01\u88c5\u7684\u66f4\u591a\u4fe1\u606f\uff0c\u8bfb\u8005\u5e94\u8be5\u53c2\u8003  step-3  \u548c  step-4  \u3002\n\n// \u4e0e step-23 \u548c step-24 \u76f8\u6bd4\uff0c\u5728\u7a0b\u5e8f\u7684\u603b\u4f53\u7ed3\u6784\u4e2d\u6ca1\u6709\u4efb\u4f55\u503c\u5f97\u6ce8\u610f\u7684\u5730\u65b9\uff08\u5f53\u7136\uff0c\u5728\u5404\u79cd\u51fd\u6570\u7684\u5185\u90e8\u8fd0\u4f5c\u4e2d\u4e5f\u6709\uff01\uff09\u3002\u6700\u660e\u663e\u7684\u533a\u522b\u662f\u51fa\u73b0\u4e86\u4e24\u4e2a\u65b0\u7684\u51fd\u6570 <code>compute_nl_term</code> \u548c <code>compute_nl_matrix</code> \uff0c\u8ba1\u7b97\u7cfb\u7edf\u77e9\u9635\u7684\u975e\u7ebf\u6027\u8d21\u732e\u548c\u7b2c\u4e00\u4e2a\u65b9\u7a0b\u7684\u53f3\u624b\u8fb9\uff0c\u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u90a3\u6837\u3002\u6b64\u5916\uff0c\u6211\u4eec\u8fd8\u5fc5\u987b\u6709\u4e00\u4e2a\u5411\u91cf <code>solution_update</code> \uff0c\u5b83\u5305\u542b\u5728\u6bcf\u4e2a\u725b\u987f\u6b65\u9aa4\u4e2d\u5bf9\u89e3\u5411\u91cf\u7684\u975e\u7ebf\u6027\u66f4\u65b0\u3002\n\n// \u6b63\u5982\u4ecb\u7ecd\u4e2d\u4e5f\u63d0\u5230\u7684\uff0c\u6211\u4eec\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u4e0d\u5b58\u50a8\u901f\u5ea6\u53d8\u91cf\uff0c\u800c\u662f\u8d28\u91cf\u77e9\u9635\u4e58\u4ee5\u901f\u5ea6\u3002\u8fd9\u662f\u5728 <code>M_x_velocity</code> \u53d8\u91cf\u4e2d\u5b8c\u6210\u7684\uff08\"x \"\u662f\u4ee3\u8868 \"\u6b21\u6570\"\uff09\u3002\n\n// \u6700\u540e\uff0c <code>output_timestep_skip</code> \u53d8\u91cf\u5b58\u50a8\u4e86\u5728\u751f\u6210\u56fe\u5f62\u8f93\u51fa\u524d\u6bcf\u6b21\u6240\u9700\u7684\u65f6\u95f4\u6b65\u6570\u3002\u8fd9\u4e00\u70b9\u5728\u4f7f\u7528\u7cbe\u7ec6\u7f51\u683c\uff08\u56e0\u6b64\u65f6\u95f4\u6b65\u6570\u8f83\u5c0f\uff09\u65f6\u975e\u5e38\u91cd\u8981\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u4f1a\u8fd0\u884c\u5927\u91cf\u7684\u65f6\u95f4\u6b65\u6570\uff0c\u5e76\u521b\u5efa\u5927\u91cf\u7684\u8f93\u51fa\u6587\u4ef6\uff0c\u8fd9\u4e9b\u6587\u4ef6\u4e2d\u7684\u89e3\u51b3\u65b9\u6848\u5728\u540e\u7eed\u6587\u4ef6\u4e2d\u770b\u8d77\u6765\u51e0\u4e4e\u662f\u4e00\u6837\u7684\u3002\u8fd9\u53ea\u4f1a\u5835\u585e\u6211\u4eec\u7684\u53ef\u89c6\u5316\u7a0b\u5e8f\uff0c\u6211\u4eec\u5e94\u8be5\u907f\u514d\u521b\u5efa\u6bd4\u6211\u4eec\u771f\u6b63\u611f\u5174\u8da3\u7684\u66f4\u591a\u7684\u8f93\u51fa\u3002\u56e0\u6b64\uff0c\u5982\u679c\u8fd9\u4e2a\u53d8\u91cf\u88ab\u8bbe\u7f6e\u4e3a\u5927\u4e8e1\u7684\u503c $n$ \uff0c\u90a3\u4e48\u53ea\u6709\u5728\u6bcf\u4e00\u4e2a $n$ \u7684\u65f6\u95f4\u6b65\u957f\u65f6\u624d\u4f1a\u4ea7\u751f\u8f93\u51fa\u3002\n\n  template <int dim> \n  class SineGordonProblem \n  { \n  public: \n    SineGordonProblem(); \n    void run(); \n\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\n    Triangulation<dim> triangulation; \n    FE_Q<dim>          fe; \n    DoFHandler<dim>    dof_handler; \n\n    SparsityPattern      sparsity_pattern; \n    SparseMatrix<double> system_matrix; \n    SparseMatrix<double> mass_matrix; \n    SparseMatrix<double> laplace_matrix; \n\n    const unsigned int n_global_refinements; \n\n    double       time; \n    const double final_time, time_step; \n    const double theta; \n\n    Vector<double> solution, solution_update, old_solution; \n    Vector<double> M_x_velocity; \n    Vector<double> system_rhs; \n\n    const unsigned int output_timestep_skip; \n  }; \n// @sect3{Initial conditions}  \n\n// \u5728\u4e0b\u9762\u4e24\u7c7b\u4e2d\uff0c\u6211\u4eec\u9996\u5148\u5b9e\u73b0\u4e86\u672c\u7a0b\u5e8f\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\u4e00\u7ef4\u3001\u4e8c\u7ef4\u548c\u4e09\u7ef4\u7684\u7cbe\u786e\u89e3\u3002\u5982\u679c\u60f3\u901a\u8fc7\u6bd4\u8f83\u6570\u503c\u89e3\u548c\u5206\u6790\u89e3\u6765\u6d4b\u8bd5\u7a0b\u5e8f\u7684\u51c6\u786e\u6027\uff0c\u90a3\u4e48\u8fd9\u4e2a\u65f6\u7a7a\u89e3\u53ef\u80fd\u4f1a\u6709\u72ec\u7acb\u7684\u610f\u4e49\uff08\u4f46\u662f\u8bf7\u6ce8\u610f\uff0c\u7a0b\u5e8f\u4f7f\u7528\u7684\u662f\u6709\u9650\u57df\uff0c\u800c\u8fd9\u4e9b\u662f\u65e0\u754c\u57df\u7684\u5206\u6790\u89e3\uff09\u3002\u4f8b\u5982\uff0c\u8fd9\u53ef\u4ee5\u7528 VectorTools::integrate_difference \u51fd\u6570\u6765\u5b8c\u6210\u3002\u518d\u6b21\u6ce8\u610f\uff08\u6b63\u5982\u5728 step-23 \u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u7684\uff09\uff0c\u6211\u4eec\u5982\u4f55\u5c06\u65f6\u7a7a\u51fd\u6570\u63cf\u8ff0\u4e3a\u4f9d\u8d56\u4e8e\u65f6\u95f4\u53d8\u91cf\u7684\u7a7a\u95f4\u51fd\u6570\uff0c\u8be5\u53d8\u91cf\u53ef\u4ee5\u4f7f\u7528FunctionTime\u57fa\u7c7b\u7684 FunctionTime::set_time() \u548c FunctionTime::get_time() \u6210\u5458\u51fd\u6570\u8fdb\u884c\u8bbe\u7f6e\u548c\u67e5\u8be2\u3002\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\n    virtual double value(const Point<dim> &p, \n                         const unsigned int /*component*/ = 0) const override \n    { \n      const double t = this->get_time(); \n\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\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\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\n          default: \n            Assert(false, ExcNotImplemented()); \n            return -1e8; \n        } \n    } \n  }; \n\n// \u5728\u672c\u8282\u7684\u7b2c\u4e8c\u90e8\u5206\uff0c\u6211\u4eec\u63d0\u4f9b\u521d\u59cb\u6761\u4ef6\u3002\u6211\u4eec\u5f88\u61d2\u60f0\uff08\u4e5f\u5f88\u8c28\u614e\uff09\uff0c\u4e0d\u60f3\u7b2c\u4e8c\u6b21\u5b9e\u73b0\u4e0e\u4e0a\u9762\u76f8\u540c\u7684\u51fd\u6570\u3002\u76f8\u53cd\uff0c\u5982\u679c\u6211\u4eec\u88ab\u67e5\u8be2\u5230\u521d\u59cb\u6761\u4ef6\uff0c\u6211\u4eec\u4f1a\u521b\u5efa\u4e00\u4e2a\u5bf9\u8c61 <code>ExactSolution</code> \uff0c\u5c06\u5176\u8bbe\u7f6e\u4e3a\u6b63\u786e\u7684\u65f6\u95f4\uff0c\u5e76\u8ba9\u5b83\u8ba1\u7b97\u5f53\u65f6\u7684\u7cbe\u786e\u89e3\u7684\u4efb\u4f55\u503c\u3002\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\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override \n    { \n      return ExactSolution<dim>(1, this->get_time()).value(p, component); \n    } \n  }; \n// @sect3{Implementation of the <code>SineGordonProblem</code> class}  \n\n// \u8ba9\u6211\u4eec\u7ee7\u7eed\u8ba8\u8bba\u4e3b\u7c7b\u7684\u5b9e\u73b0\uff0c\u56e0\u4e3a\u5b83\u5b9e\u73b0\u4e86\u4ecb\u7ecd\u4e2d\u6982\u8ff0\u7684\u7b97\u6cd5\u3002\n\n//  @sect4{SineGordonProblem::SineGordonProblem}  \n\n// \u8fd9\u662f <code>SineGordonProblem</code> \u7c7b\u7684\u6784\u9020\u51fd\u6570\u3002\u5b83\u6307\u5b9a\u4e86\u6240\u9700\u7684\u6709\u9650\u5143\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\uff0c\u5173\u8054\u4e86\u4e00\u4e2a <code>DoFHandler</code> to the <code>triangulation</code> \u5bf9\u8c61\uff08\u5c31\u50cf\u5728\u793a\u4f8b\u7a0b\u5e8f step-3 \u548c step-4 \u4e2d\u4e00\u6837\uff09\uff0c\u521d\u59cb\u5316\u4e86\u5f53\u524d\u6216\u521d\u59cb\u65f6\u95f4\u3001\u6700\u7ec8\u65f6\u95f4\u3001\u65f6\u95f4\u6b65\u957f\uff0c\u4ee5\u53ca\u65f6\u95f4\u6b65\u957f\u65b9\u6848\u7684 $\\theta$ \u503c\u3002\u7531\u4e8e\u6211\u4eec\u5728\u8fd9\u91cc\u8ba1\u7b97\u7684\u89e3\u662f\u65f6\u95f4\u5468\u671f\u6027\u7684\uff0c\u6240\u4ee5\u5f00\u59cb\u65f6\u95f4\u7684\u5b9e\u9645\u503c\u5e76\u4e0d\u91cd\u8981\uff0c\u6211\u4eec\u9009\u62e9\u5b83\u662f\u4e3a\u4e86\u8ba9\u6211\u4eec\u5728\u4e00\u4e2a\u6709\u8da3\u7684\u65f6\u95f4\u5f00\u59cb\u3002\n\n// \u8bf7\u6ce8\u610f\uff0c\u5982\u679c\u6211\u4eec\u9009\u62e9\u663e\u5f0f\u6b27\u62c9\u65f6\u95f4\u6b65\u8fdb\u65b9\u6848\uff08 $\\theta = 0$ \uff09\uff0c\u90a3\u4e48\u6211\u4eec\u5fc5\u987b\u9009\u62e9\u4e00\u4e2a\u65f6\u95f4\u6b65\u8fdb $k \\le h$ \uff0c\u5426\u5219\u8be5\u65b9\u6848\u4e0d\u7a33\u5b9a\uff0c\u89e3\u4e2d\u53ef\u80fd\u51fa\u73b0\u632f\u8361\u3002Crank-Nicolson\u65b9\u6848\uff08 $\\theta = \\frac{1}{2}$ \uff09\u548c\u9690\u5f0fEuler\u65b9\u6848\uff08 $\\theta=1$ \uff09\u4e0d\u5b58\u5728\u8fd9\u4e2a\u7f3a\u9677\uff0c\u56e0\u4e3a\u5b83\u4eec\u662f\u65e0\u6761\u4ef6\u7a33\u5b9a\u7684\u3002\u7136\u800c\uff0c\u5373\u4f7f\u5982\u6b64\uff0c\u65f6\u95f4\u6b65\u957f\u4e5f\u5e94\u9009\u62e9\u5728 $h$ \u7684\u6570\u91cf\u7ea7\u4e0a\uff0c\u4ee5\u83b7\u5f97\u4e00\u4e2a\u597d\u7684\u89e3\u51b3\u65b9\u6848\u3002\u7531\u4e8e\u6211\u4eec\u77e5\u9053\u6211\u4eec\u7684\u7f51\u683c\u662f\u7531\u77e9\u5f62\u7684\u5747\u5300\u7ec6\u5206\u800c\u6765\uff0c\u6211\u4eec\u53ef\u4ee5\u5f88\u5bb9\u6613\u5730\u8ba1\u7b97\u51fa\u8fd9\u4e2a\u65f6\u95f4\u6b65\u957f\uff1b\u5982\u679c\u6211\u4eec\u6709\u4e00\u4e2a\u4e0d\u540c\u7684\u57df\uff0c step-24 \u4e2d\u7684\u6280\u672f\u4f7f\u7528 GridTools::minimal_cell_diameter \u4e5f\u662f\u53ef\u4ee5\u7684\u3002\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// @sect4{SineGordonProblem::make_grid_and_dofs}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u521b\u5efa\u4e86\u4e00\u4e2a <code>dim</code> \u7ef4\u5ea6\u7684\u77e9\u5f62\u7f51\u683c\uff0c\u5e76\u5bf9\u5176\u8fdb\u884c\u4e86\u591a\u6b21\u7ec6\u5316\u3002\u540c\u65f6\uff0c\u4e00\u65e6\u81ea\u7531\u5ea6\u88ab\u96c6\u5408\u8d77\u6765\uff0c <code>SineGordonProblem</code> \u7c7b\u7684\u6240\u6709\u77e9\u9635\u548c\u5411\u91cf\u6210\u5458\u90fd\u88ab\u521d\u59cb\u5316\u4e3a\u76f8\u5e94\u7684\u5927\u5c0f\u3002\u50cf step-24 \u4e00\u6837\uff0c\u6211\u4eec\u4f7f\u7528 <code>MatrixCreator</code> \u51fd\u6570\u6765\u751f\u6210\u8d28\u91cf\u77e9\u9635 $M$ \u548c\u62c9\u666e\u62c9\u65af\u77e9\u9635 $A$ \uff0c\u5e76\u5728\u7a0b\u5e8f\u7684\u5269\u4f59\u65f6\u95f4\u91cc\u5c06\u5b83\u4eec\u5b58\u50a8\u5728\u9002\u5f53\u7684\u53d8\u91cf\u4e2d\u3002\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\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\n    dof_handler.distribute_dofs(fe); \n\n    std::cout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << std::endl; \n\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\n    system_matrix.reinit(sparsity_pattern); \n    mass_matrix.reinit(sparsity_pattern); \n    laplace_matrix.reinit(sparsity_pattern); \n\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\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// @sect4{SineGordonProblem::assemble_system}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u4e3a\u725b\u987f\u65b9\u6cd5\u7684\u6bcf\u6b21\u8fed\u4ee3\u7ec4\u88c5\u7cfb\u7edf\u77e9\u9635\u548c\u53f3\u624b\u5411\u91cf\u3002\u5173\u4e8e\u7cfb\u7edf\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u660e\u786e\u516c\u5f0f\uff0c\u8bfb\u8005\u5e94\u8be5\u53c2\u8003\u5bfc\u8bba\u3002\n\n// \u8bf7\u6ce8\u610f\uff0c\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\uff0c\u6211\u4eec\u5fc5\u987b\u628a\u5bf9\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u5404\u79cd\u8d21\u732e\u52a0\u8d77\u6765\u3002\u4e0e step-23 \u548c step-24 \u76f8\u6bd4\uff0c\u8fd9\u9700\u8981\u96c6\u5408\u66f4\u591a\u7684\u9879\uff0c\u56e0\u4e3a\u5b83\u4eec\u53d6\u51b3\u4e8e\u524d\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u6216\u524d\u4e00\u4e2a\u975e\u7ebf\u6027\u6b65\u9aa4\u7684\u89e3\u3002\u6211\u4eec\u4f7f\u7528\u51fd\u6570 <code>compute_nl_matrix</code> \u548c <code>compute_nl_term</code> \u6765\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u800c\u672c\u51fd\u6570\u63d0\u4f9b\u4e86\u9876\u5c42\u903b\u8f91\u3002\n\n  template <int dim> \n  void SineGordonProblem<dim>::assemble_system() \n  { \n\n// \u9996\u5148\u6211\u4eec\u7ec4\u88c5\u96c5\u5404\u5e03\u77e9\u9635 $F'_h(U^{n,l})$  \uff0c\u5176\u4e2d $U^{n,l}$ \u4e3a\u65b9\u4fbf\u8d77\u89c1\u88ab\u50a8\u5b58\u5728\u5411\u91cf <code>solution</code> \u4e2d\u3002\n\n    system_matrix.copy_from(mass_matrix); \n    system_matrix.add(std::pow(time_step * theta, 2), laplace_matrix); \n\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\n// \u63a5\u4e0b\u6765\u6211\u4eec\u8ba1\u7b97\u53f3\u624b\u8fb9\u7684\u5411\u91cf\u3002\u8fd9\u53ea\u662f\u4ecb\u7ecd\u4e2d\u5bf9 $-F_h(U^{n,l})$ \u7684\u63cf\u8ff0\u6240\u6697\u793a\u7684\u77e9\u9635-\u5411\u91cf\u7684\u7ec4\u5408\u3002\n\n    system_rhs = 0.; \n\n    Vector<double> tmp_vector(solution.size()); \n\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\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\n    system_rhs.add(-time_step, M_x_velocity); \n\n    compute_nl_term(old_solution, solution, tmp_vector); \n    system_rhs.add(std::pow(time_step, 2) * theta, tmp_vector); \n\n    system_rhs *= -1.; \n  } \n// @sect4{SineGordonProblem::compute_nl_term}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u8ba1\u7b97\u5411\u91cf $S(\\cdot,\\cdot)$ \uff0c\u5b83\u51fa\u73b0\u5728\u5206\u88c2\u516c\u5f0f\u7684\u4e24\u4e2a\u65b9\u7a0b\u7684\u975e\u7ebf\u6027\u9879\u4e2d\u3002\u8fd9\u4e2a\u51fd\u6570\u4e0d\u4ec5\u7b80\u5316\u4e86\u8fd9\u4e2a\u9879\u7684\u91cd\u590d\u8ba1\u7b97\uff0c\u800c\u4e14\u4e5f\u662f\u6211\u4eec\u5728\u65f6\u95f4\u6b65\u957f\u4e3a\u9690\u5f0f\u65f6\u4f7f\u7528\u7684\u975e\u7ebf\u6027\u8fed\u4ee3\u6c42\u89e3\u5668\u7684\u57fa\u672c\u7ec4\u6210\u90e8\u5206\uff08\u5373 $\\theta\\ne 0$  \uff09\u3002\u6b64\u5916\uff0c\u6211\u4eec\u5fc5\u987b\u5141\u8bb8\u8be5\u51fd\u6570\u63a5\u6536\u4e00\u4e2a \"\u65e7 \"\u548c\u4e00\u4e2a \"\u65b0 \"\u7684\u89e3\u51b3\u65b9\u6848\u4f5c\u4e3a\u8f93\u5165\u3002\u8fd9\u4e9b\u53ef\u80fd\u4e0d\u662f\u5b58\u50a8\u5728 <code>old_solution</code> and <code>solution</code> \u4e2d\u7684\u95ee\u9898\u7684\u5b9e\u9645\u89e3\u51b3\u65b9\u6848\uff0c\u800c\u53ea\u662f\u6211\u4eec\u7ebf\u6027\u5316\u7684\u4e24\u4e2a\u51fd\u6570\u3002\u4e3a\u4e86\u8fd9\u4e2a\u51fd\u6570\u7684\u76ee\u7684\uff0c\u8ba9\u6211\u4eec\u5728\u4e0b\u9762\u8fd9\u4e2a\u7c7b\u7684\u6587\u6863\u4e2d\u5206\u522b\u8c03\u7528\u524d\u4e24\u4e2a\u53c2\u6570  $w_{\\mathrm{old}}$  \u548c  $w_{\\mathrm{new}}$  \u3002\n\n// \u4f5c\u4e3a\u4e00\u4e2a\u65c1\u6ce8\uff0c\u4e5f\u8bb8\u503c\u5f97\u7814\u7a76\u4e00\u4e0b\u4ec0\u4e48\u9636\u6b21\u7684\u6b63\u4ea4\u516c\u5f0f\u6700\u9002\u5408\u8fd9\u79cd\u7c7b\u578b\u7684\u79ef\u5206\u3002\u7531\u4e8e $\\sin(\\cdot)$ \u4e0d\u662f\u4e00\u4e2a\u591a\u9879\u5f0f\uff0c\u53ef\u80fd\u6ca1\u6709\u6b63\u4ea4\u516c\u5f0f\u53ef\u4ee5\u51c6\u786e\u5730\u79ef\u5206\u8fd9\u4e9b\u9879\u3002\u901a\u5e38\u53ea\u9700\u786e\u4fdd\u53f3\u624b\u8fb9\u7684\u79ef\u5206\u8fbe\u5230\u4e0e\u79bb\u6563\u5316\u65b9\u6848\u76f8\u540c\u7684\u7cbe\u5ea6\u5373\u53ef\uff0c\u4f46\u901a\u8fc7\u9009\u62e9\u66f4\u7cbe\u786e\u7684\u6b63\u4ea4\u516c\u5f0f\uff0c\u4e5f\u8bb8\u53ef\u4ee5\u6539\u5584\u6e10\u8fd1\u6536\u655b\u58f0\u660e\u4e2d\u7684\u5e38\u6570\u3002\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\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\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\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        local_nl_term = 0; \n\n// \u4e00\u65e6\u6211\u4eec\u5c06 <code>FEValues</code> \u5b9e\u4f8b\u5316\u91cd\u65b0\u521d\u59cb\u5316\u5230\u5f53\u524d\u5355\u5143\u683c\uff0c\u6211\u4eec\u5c31\u5229\u7528 <code>get_function_values</code> \u4f8b\u7a0b\u6765\u83b7\u53d6 \"\u65e7 \"\u6570\u636e\uff08\u5927\u6982\u5728 $t=t_{n-1}$ \uff09\u548c \"\u65b0 \"\u6570\u636e\uff08\u5927\u6982\u5728 $t=t_n$ \uff09\u5728\u6240\u9009\u6b63\u4ea4\u516c\u5f0f\u8282\u70b9\u7684\u503c\u3002\n\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\n// \u73b0\u5728\uff0c\u6211\u4eec\u53ef\u4ee5\u7528\u6240\u9700\u7684\u6b63\u4ea4\u516c\u5f0f\u6765\u8bc4\u4f30  $\\int_K \\sin\\left[\\theta w_{\\mathrm{new}} + (1-\\theta) w_{\\mathrm{old}}\\right] \\,\\varphi_j\\,\\mathrm{d}x$  \u3002\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            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\n// \u6211\u4eec\u901a\u8fc7\u5c06\u5404\u5355\u5143\u7684\u79ef\u5206\u5bf9\u5168\u5c40\u79ef\u5206\u7684\u8d21\u732e\u76f8\u52a0\u6765\u5f97\u51fa\u7ed3\u8bba\u3002\n\n        cell->get_dof_indices(local_dof_indices); \n\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// @sect4{SineGordonProblem::compute_nl_matrix}  \n\n// \u8fd9\u662f\u5904\u7406\u975e\u7ebf\u6027\u65b9\u6848\u7684\u7b2c\u4e8c\u4e2a\u51fd\u6570\u3002\u5b83\u8ba1\u7b97\u77e9\u9635  $N(\\cdot,\\cdot)$  \uff0c\u5b83\u51fa\u73b0\u5728  $F(\\cdot)$  \u7684\u96c5\u5404\u5e03\u9879\u7684\u975e\u7ebf\u6027\u9879\u4e2d\u3002\u6b63\u5982 <code>compute_nl_term</code> \u4e00\u6837\uff0c\u6211\u4eec\u5fc5\u987b\u8ba9\u8fd9\u4e2a\u51fd\u6570\u63a5\u6536\u4e00\u4e2a \"\u65e7 \"\u548c\u4e00\u4e2a \"\u65b0 \"\u7684\u89e3\u51b3\u65b9\u6848\u4f5c\u4e3a\u8f93\u5165\uff0c\u6211\u4eec\u518d\u6b21\u5c06\u5176\u5206\u522b\u79f0\u4e3a $w_{\\mathrm{old}}$ \u548c $w_{\\mathrm{new}}$ \uff0c\u5982\u4e0b\u3002\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\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\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\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        local_nl_matrix = 0; \n\n// \u540c\u6837\uff0c\u9996\u5148\u6211\u4eec\u5c06\u6211\u4eec\u7684 <code>FEValues</code> \u5b9e\u4f8b\u5316\u91cd\u65b0\u521d\u59cb\u5316\u4e3a\u5f53\u524d\u5355\u5143\u3002\n\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\n// \u7136\u540e\uff0c\u6211\u4eec\u7528\u6240\u9700\u7684\u6b63\u4ea4\u516c\u5f0f\u8bc4\u4f30 $\\int_K \\cos\\left[\\theta w_{\\mathrm{new}} + (1-\\theta) w_{\\mathrm{old}}\\right]\\, \\varphi_i\\, \\varphi_j\\,\\mathrm{d}x$ \u3002\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            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\n// \u6700\u540e\uff0c\u6211\u4eec\u5c06\u5404\u5355\u5143\u7684\u79ef\u5206\u5bf9\u5168\u5c40\u79ef\u5206\u7684\u8d21\u732e\u76f8\u52a0\u3002\n\n        cell->get_dof_indices(local_dof_indices); \n\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\n//  @sect4{SineGordonProblem::solve}  \n\n// \u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u8fd9\u4e2a\u51fd\u6570\u5728\u7ebf\u6027\u65b9\u7a0b\u7ec4\u4e0a\u4f7f\u7528CG\u8fed\u4ee3\u6c42\u89e3\u5668\uff0c\u8be5\u65b9\u7a0b\u7ec4\u662f\u7531\u725b\u987f\u65b9\u6cd5\u7684\u6bcf\u4e2a\u8fed\u4ee3\u7684\u6709\u9650\u5143\u7a7a\u95f4\u79bb\u6563\u5316\u4ea7\u751f\u7684\uff0c\u7528\u4e8e\u5206\u5272\u516c\u5f0f\u4e2d\u7684\uff08\u975e\u7ebf\u6027\uff09\u7b2c\u4e00\u4e2a\u65b9\u7a0b\u3002\u8be5\u7cfb\u7edf\u7684\u89e3\u5b9e\u9645\u4e0a\u662f $\\delta U^{n,l}$ \uff0c\u6240\u4ee5\u5b83\u88ab\u5b58\u50a8\u5728 <code>solution_update</code> and used to update <code>solution</code> \u7684 <code>run</code> \u51fd\u6570\u4e2d\u3002\n\n// \u6ce8\u610f\uff0c\u6211\u4eec\u5728\u6c42\u89e3\u524d\u5c06\u89e3\u7684\u66f4\u65b0\u503c\u91cd\u65b0\u8bbe\u7f6e\u4e3a\u96f6\u3002\u8fd9\u662f\u6ca1\u6709\u5fc5\u8981\u7684\uff1a\u8fed\u4ee3\u6c42\u89e3\u5668\u53ef\u4ee5\u4ece\u4efb\u4f55\u4e00\u70b9\u5f00\u59cb\u5e76\u6536\u655b\u5230\u6b63\u786e\u7684\u89e3\u3002\u5982\u679c\u5bf9\u7ebf\u6027\u7cfb\u7edf\u7684\u89e3\u6709\u4e00\u4e2a\u5f88\u597d\u7684\u4f30\u8ba1\uff0c\u90a3\u4e48\u4ece\u8fd9\u4e2a\u5411\u91cf\u5f00\u59cb\u53ef\u80fd\u662f\u503c\u5f97\u7684\uff0c\u4f46\u662f\u4f5c\u4e3a\u4e00\u4e2a\u4e00\u822c\u7684\u89c2\u5bdf\uff0c\u8d77\u70b9\u5e76\u4e0d\u662f\u5f88\u91cd\u8981\uff1a\u5b83\u5fc5\u987b\u662f\u4e00\u4e2a\u975e\u5e38\u975e\u5e38\u597d\u7684\u731c\u6d4b\uff0c\u4ee5\u51cf\u5c11\u8d85\u8fc7\u51e0\u4e2a\u8fed\u4ee3\u7684\u6b21\u6570\u3002\u4e8b\u5b9e\u8bc1\u660e\uff0c\u5bf9\u4e8e\u8fd9\u4e2a\u95ee\u9898\uff0c\u4f7f\u7528\u4e4b\u524d\u7684\u975e\u7ebf\u6027\u66f4\u65b0\u4f5c\u4e3a\u8d77\u70b9\u5b9e\u9645\u4e0a\u4f1a\u635f\u5bb3\u6536\u655b\u6027\u5e76\u589e\u52a0\u6240\u9700\u7684\u8fed\u4ee3\u6b21\u6570\uff0c\u6240\u4ee5\u6211\u4eec\u7b80\u5355\u5730\u5c06\u5176\u8bbe\u7f6e\u4e3a\u96f6\u3002\n\n// \u8be5\u51fd\u6570\u8fd4\u56de\u6536\u655b\u5230\u4e00\u4e2a\u89e3\u51b3\u65b9\u6848\u6240\u9700\u7684\u8fed\u4ee3\u6b21\u6570\u3002\u8fd9\u4e2a\u6570\u5b57\u4ee5\u540e\u5c06\u88ab\u7528\u6765\u5728\u5c4f\u5e55\u4e0a\u751f\u6210\u8f93\u51fa\uff0c\u663e\u793a\u6bcf\u6b21\u975e\u7ebf\u6027\u8fed\u4ee3\u9700\u8981\u591a\u5c11\u6b21\u8fed\u4ee3\u3002\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<Vector<double>> cg(solver_control); \n\n    PreconditionSSOR<SparseMatrix<double>> preconditioner; \n    preconditioner.initialize(system_matrix, 1.2); \n\n    cg.solve(system_matrix, solution_update, system_rhs, preconditioner); \n\n    return solver_control.last_step(); \n  } \n// @sect4{SineGordonProblem::output_results}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u5c06\u7ed3\u679c\u8f93\u51fa\u5230\u4e00\u4e2a\u6587\u4ef6\u3002\u5b83\u4e0e  step-23  \u548c  step-24  \u4e2d\u7684\u76f8\u5e94\u51fd\u6570\u57fa\u672c\u76f8\u540c\u3002\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\n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \"u\"); \n    data_out.build_patches(); \n\n    const std::string filename = \n      \"solution-\" + Utilities::int_to_string(timestep_number, 3) + \".vtu\"; \n    DataOutBase::VtkFlags vtk_flags; \n    vtk_flags.compression_level = \n      DataOutBase::VtkFlags::ZlibCompressionLevel::best_speed; \n    data_out.set_flags(vtk_flags); \n    std::ofstream output(filename); \n    data_out.write_vtu(output); \n  } \n// @sect4{SineGordonProblem::run}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u5bf9\u4e00\u5207\u90fd\u6709\u6700\u9ad8\u7ea7\u522b\u7684\u63a7\u5236\uff1a\u5b83\u8fd0\u884c\uff08\u5916\u90e8\uff09\u65f6\u95f4\u6b65\u957f\u5faa\u73af\uff0c\uff08\u5185\u90e8\uff09\u975e\u7ebf\u6027\u6c42\u89e3\u5668\u5faa\u73af\uff0c\u5e76\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u540e\u8f93\u51fa\u89e3\u3002\n\n  template <int dim> \n  void SineGordonProblem<dim>::run() \n  { \n    make_grid_and_dofs(); \n\n// \u4e3a\u4e86\u786e\u8ba4\u521d\u59cb\u6761\u4ef6\uff0c\u6211\u4eec\u5fc5\u987b\u4f7f\u7528\u51fd\u6570  $u_0(x)$  \u6765\u8ba1\u7b97  $U^0$  \u3002\u4e3a\u6b64\uff0c\u4e0b\u9762\u6211\u4eec\u5c06\u521b\u5efa\u4e00\u4e2a <code>InitialValues</code> \u7c7b\u578b\u7684\u5bf9\u8c61\uff1b\u6ce8\u610f\uff0c\u5f53\u6211\u4eec\u521b\u5efa\u8fd9\u4e2a\u5bf9\u8c61\uff08\u5b83\u6765\u81ea <code>Function</code> \u7c7b\uff09\u65f6\uff0c\u6211\u4eec\u5c06\u5176\u5185\u90e8\u7684\u65f6\u95f4\u53d8\u91cf\u8bbe\u7f6e\u4e3a $t_0$ \uff0c\u4ee5\u8868\u660e\u521d\u59cb\u6761\u4ef6\u662f\u5728 $t=t_0$ \u5904\u8bc4\u4f30\u7684\u7a7a\u95f4\u548c\u65f6\u95f4\u7684\u51fd\u6570\u3002\n\n// \u7136\u540e\u6211\u4eec\u901a\u8fc7\u4f7f\u7528 <code>VectorTools::project</code> \u5c06 $u_0(x)$ \u6295\u5f71\u5230\u7f51\u683c\u4e0a\uff0c\u4ea7\u751f $U^0$ \u3002\u6211\u4eec\u5fc5\u987b\u4f7f\u7528\u4e0e step-21 \u76f8\u540c\u7684\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u7ed3\u6784\uff1a VectorTools::project \u51fd\u6570\u9700\u8981\u4e00\u4e2a\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u5bf9\u8c61\uff0c\u4f46\u4e3a\u4e86\u4f7f\u7528\u5b83\uff0c\u6211\u4eec\u9996\u5148\u9700\u8981\u5173\u95ed\u5b83\u3002\n\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\n// \u4e3a\u4e86\u5b8c\u6574\u8d77\u89c1\uff0c\u6211\u4eec\u50cf\u5176\u4ed6\u65f6\u95f4\u6b65\u957f\u4e00\u6837\uff0c\u5c06\u7b2c2\u4e2a\u65f6\u95f4\u6b65\u957f\u8f93\u51fa\u5230\u4e00\u4e2a\u6587\u4ef6\u3002\n\n    output_results(0); \n\n// \u73b0\u5728\u6211\u4eec\u8fdb\u884c\u65f6\u95f4\u6b65\u8fdb\uff1a\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u8fdb\u4e2d\uff0c\u6211\u4eec\u89e3\u51b3\u4e0e\u95ee\u9898\u7684\u6709\u9650\u5143\u79bb\u6563\u5316\u76f8\u5bf9\u5e94\u7684\u77e9\u9635\u65b9\u7a0b\uff0c\u7136\u540e\u6839\u636e\u6211\u4eec\u5728\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u65f6\u95f4\u6b65\u8fdb\u516c\u5f0f\u63a8\u8fdb\u6211\u4eec\u7684\u89e3\u51b3\u65b9\u6848\u3002\n\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\n        std::cout << std::endl \n                  << \"Time step #\" << timestep_number << \"; \" \n                  << \"advancing to t = \" << time << \".\" << std::endl; \n\n// \u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u5f00\u59cb\uff0c\u6211\u4eec\u5fc5\u987b\u901a\u8fc7\u725b\u987f\u65b9\u6cd5\u6c42\u89e3\u62c6\u5206\u516c\u5f0f\u4e2d\u7684\u975e\u7ebf\u6027\u65b9\u7a0b---\u5373\u5148\u6c42\u89e3 $\\delta U^{n,l}$ \uff0c\u7136\u540e\u518d\u8ba1\u7b97 $U^{n,l+1}$ \uff0c\u5982\u6b64\u53cd\u590d\u3002\u8fd9\u79cd\u975e\u7ebf\u6027\u8fed\u4ee3\u7684\u505c\u6b62\u6807\u51c6\u662f\uff1a $\\|F_h(U^{n,l})\\|_2 \\le 10^{-6} \\|F_h(U^{n,0})\\|_2$  \u3002\u56e0\u6b64\uff0c\u6211\u4eec\u9700\u8981\u8bb0\u5f55\u7b2c\u4e00\u6b21\u8fed\u4ee3\u4e2d\u6b8b\u5dee\u7684\u89c4\u8303\u3002\n\n// \u5728\u6bcf\u6b21\u8fed\u4ee3\u7ed3\u675f\u65f6\uff0c\u6211\u4eec\u5411\u63a7\u5236\u53f0\u8f93\u51fa\u6211\u4eec\u82b1\u4e86\u591a\u5c11\u6b21\u7ebf\u6027\u6c42\u89e3\u5668\u7684\u8fed\u4ee3\u3002\u5f53\u4e0b\u9762\u7684\u5faa\u73af\u5b8c\u6210\u540e\uff0c\u6211\u4eec\u6709\uff08\u4e00\u4e2a\u8fd1\u4f3c\u7684\uff09 $U^n$  \u3002\n\n        double initial_rhs_norm = 0.; \n        bool   first_iteration  = true; \n        do \n          { \n            assemble_system(); \n\n            if (first_iteration == true) \n              initial_rhs_norm = system_rhs.l2_norm(); \n\n            const unsigned int n_iterations = solve(); \n\n            solution += solution_update; \n\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\n        std::cout << \" CG iterations per nonlinear step.\" << std::endl; \n\n// \u5728\u5f97\u5230\u95ee\u9898\u7684\u7b2c\u4e00\u4e2a\u65b9\u7a0b $t=t_n$ \u7684\u89e3\u540e\uff0c\u6211\u4eec\u5fc5\u987b\u66f4\u65b0\u8f85\u52a9\u901f\u5ea6\u53d8\u91cf  $V^n$  \u3002\u7136\u800c\uff0c\u6211\u4eec\u4e0d\u8ba1\u7b97\u548c\u5b58\u50a8 $V^n$ \uff0c\u56e0\u4e3a\u5b83\u4e0d\u662f\u6211\u4eec\u5728\u95ee\u9898\u4e2d\u76f4\u63a5\u4f7f\u7528\u7684\u6570\u91cf\u3002\u56e0\u6b64\uff0c\u4e3a\u4e86\u7b80\u5355\u8d77\u89c1\uff0c\u6211\u4eec\u76f4\u63a5\u66f4\u65b0 $MV^n$ \u3002\n\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\n        laplace_matrix.vmult(tmp_vector, old_solution); \n        M_x_velocity.add(-time_step * (1 - theta), tmp_vector); \n\n        compute_nl_term(old_solution, solution, tmp_vector); \n        M_x_velocity.add(-time_step, tmp_vector); \n\n// \u5f88\u591a\u65f6\u5019\uff0c\u7279\u522b\u662f\u5bf9\u4e8e\u7ec6\u7f51\u683c\uff0c\u6211\u4eec\u5fc5\u987b\u9009\u62e9\u76f8\u5f53\u5c0f\u7684\u65f6\u95f4\u6b65\u957f\uff0c\u4ee5\u4f7f\u65b9\u6848\u7a33\u5b9a\u3002\u56e0\u6b64\uff0c\u6709\u5f88\u591a\u65f6\u95f4\u6b65\u957f\uff0c\u5728\u89e3\u7684\u8fc7\u7a0b\u4e2d \"\u6ca1\u6709\u4ec0\u4e48\u6709\u8da3\u7684\u4e8b\u60c5\u53d1\u751f\"\u3002\u4e3a\u4e86\u63d0\u9ad8\u6574\u4f53\u6548\u7387--\u7279\u522b\u662f\u52a0\u5feb\u7a0b\u5e8f\u901f\u5ea6\u548c\u8282\u7701\u78c1\u76d8\u7a7a\u95f4--\u6211\u4eec\u6bcf\u9694 <code>output_timestep_skip</code> \u4e2a\u65f6\u95f4\u6b65\u6570\u624d\u8f93\u51fa\u89e3\u3002\n\n        if (timestep_number % output_timestep_skip == 0) \n          output_results(timestep_number); \n      } \n  } \n} // namespace Step25 \n// @sect3{The <code>main</code> function}  \n\n// \u8fd9\u662f\u8be5\u7a0b\u5e8f\u7684\u4e3b\u51fd\u6570\u3002\u5b83\u521b\u5efa\u4e00\u4e2a\u9876\u5c42\u7c7b\u7684\u5bf9\u8c61\u5e76\u8c03\u7528\u5176\u4e3b\u51fd\u6570\u3002\u5982\u679c\u5728\u6267\u884c <code>SineGordonProblem</code> \u7c7b\u7684\u8fd0\u884c\u65b9\u6cd5\u65f6\u629b\u51fa\u4e86\u5f02\u5e38\uff0c\u6211\u4eec\u4f1a\u5728\u8fd9\u91cc\u6355\u83b7\u5e76\u62a5\u544a\u5b83\u4eec\u3002\u5173\u4e8e\u5f02\u5e38\u7684\u66f4\u591a\u4fe1\u606f\uff0c\u8bfb\u8005\u5e94\u8be5\u53c2\u8003  step-6  \u3002\n\nint main() \n{ \n  try \n    { \n      using namespace Step25; \n\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\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\n", "meta": {"hexsha": "45d1f855818765ae48b93fdf34837b3b3cecb52a", "size": 22269, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-25/step-25.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-25/step-25.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-25/step-25.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.9318181818, "max_line_length": 326, "alphanum_fraction": 0.6142170731, "num_tokens": 8341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.52311907127218}}
{"text": "// see also <http://web.mit.edu/fwtools_v3.1.0/www/H5.intro.html>\n\n#include <string>\n#include <memory>\n#include <Eigen/Dense>\n#include <H5Cpp.h>\n\n#include <iostream>\n\nusing namespace H5;\nconst H5std_string FILE_NAME(\"states.h5\");\nconst H5std_string DATASET_NAME(\"States\");\nPredType dType {PredType::NATIVE_DOUBLE};\ntypedef double data_t;\n\nconst int FSPACE_RANK = 2; // Dataset rank as it is stored in the file\nconst int FSPACE_DIM1 = 5; // Dimension sizes of the dataset as it is\nconst int FSPACE_DIM2 = 3; // stored in the file\n\nconst int MSPACE_RANK = 1; // Rank of dataset in memory\nconst int MSPACE_DIM = FSPACE_DIM1 * FSPACE_DIM2; // Dataset size in memory\n\nvoid readfile();\nvoid writefile();\nvoid testEigen();\nEigen::MatrixXd mk_mat();\n\nusing std::cout;\nusing std::endl;\n\nusing RowMatrixXd = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\nint main()\n{\n    cout << \"> Test Eigen...\" << endl;\n    Eigen::MatrixXd m {mk_mat()};\n    cout << \"MatrixXd @ \" << m.data() << \":\\n\" << m << endl;\n\n    cout << \"> Write data to \" << FILE_NAME << \"...\" << endl;\n    writefile();\n\n    cout << \"> Read data from \" << FILE_NAME << \"...\" << endl;\n    readfile();\n\n    return 0;\n}\n\n\nEigen::MatrixXd mk_mat()\n{\n    Eigen::MatrixXd m(FSPACE_DIM1, FSPACE_DIM2);\n    int c = 0;\n    for (int i = 0; i < FSPACE_DIM1; ++i)\n        for (int j = 0; j < FSPACE_DIM2; ++j)\n        {\n            ++c;\n            m(i,j) = c;\n        }\n\n    cout << \"MatrixXd @ \" << m.data() << \":\\n\" << m << endl;\n    return m;\n}\n\n\nvoid testEigen()\n{\n    Eigen::MatrixXd m(FSPACE_DIM1, FSPACE_DIM2);\n    int c = 0;\n    for (int i = 0; i < FSPACE_DIM1; ++i)\n        for (int j = 0; j < FSPACE_DIM2; ++j)\n        {\n            ++c;\n            m(i,j) = c;\n        }\n\n    cout << \"MatrixXd:\\n\" << m << endl;\n}\n\n\nvoid writefile()\n{\n    H5File file(FILE_NAME, H5F_ACC_TRUNC);\n    // Create dataspace for the dataset in the file\n    hsize_t fdim[] = {FSPACE_DIM1, FSPACE_DIM2};\n    DataSpace fspace(FSPACE_RANK, fdim);\n    // Create dataset and write it into the file\n    DataSet dataset(file.createDataSet(DATASET_NAME, dType, fspace));\n    // Select hyperslab for the dataset in the file\n    hsize_t start[2] = {0, 0}; // Start of hyperslab\n    hsize_t stride[2] = {FSPACE_DIM1, FSPACE_DIM2}; // Stride of hyperslab\n    hsize_t block[2] = {FSPACE_DIM1, FSPACE_DIM2};  // Block sizes\n    hsize_t count[2] = {1, 1};  // Block count\n\n    hsize_t mdim[] = {MSPACE_DIM};  // Dimension size of the first dataset\n    DataSpace mspace(MSPACE_RANK, mdim);\n    // data\n    Eigen::MatrixXd m(FSPACE_DIM1, FSPACE_DIM2);\n    int c = 0;\n    for (int i = 0; i < FSPACE_DIM1; ++i)\n        for (int j = 0; j < FSPACE_DIM2; ++j)\n        {\n            ++c;\n            m(i,j) = c;\n        }\n\n    cout << \"MatrixXd m:\\n\" << m << endl;\n    data_t* data {m.data()};\n\n    cout << \"MatrixXd internal storage order:\" << endl;\n    for (c = 0; c < MSPACE_DIM; ++c)\n        cout << data[c] << \", \";\n    cout << endl;\n\n    fspace.selectHyperslab(H5S_SELECT_SET, count, start, stride, block);\n    dataset.write(m.data(), dType, mspace, fspace);\n\n    // Reset the selection for the file dataspace\n    fspace.selectNone();\n}\n\nvoid readfile()\n{\n    // Open the file\n    H5File file(FILE_NAME, H5F_ACC_RDONLY);\n    // Open the dataset.\n    DataSet dataset(file.openDataSet(DATASET_NAME));\n    // Get dataspace of the dataset\n    DataSpace fspace {dataset.getSpace()};\n    int rank = fspace.getSimpleExtentNdims();\n    hsize_t* fdims = new hsize_t[rank];\n    fspace.getSimpleExtentDims(fdims);\n\n    cout << \"r/rank = \" << rank << endl;\n    cout << \"r/dims = \";\n    int d = 0;\n    for (; d < rank; ++d)\n        cout << fdims[d] << \", \";\n    const hsize_t n_rows = fdims[0], n_cols = fdims[1];\n    delete [] fdims;\n\n    // Read data into a vector\n    hsize_t mdim[] = {n_rows * n_cols};\n    DataSpace mspace(MSPACE_RANK, mdim);\n\n    Eigen::MatrixXd mat(n_rows, n_cols);\n    dataset.read(mat.data(), dType, mspace, fspace);\n    cout << \"MatrixXd mat:\\n\" << mat << endl;\n}\n", "meta": {"hexsha": "e39d6f48fccdd83d8b730aabef7ade3ad6c1fd66", "size": 4015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Cpp/hdf5/test_row_mat.cpp", "max_stars_repo_name": "AlQuemiste/Sourcery", "max_stars_repo_head_hexsha": "19cf230ee8134bf8a963949f02d02319dc2ee763", "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": "Cpp/hdf5/test_row_mat.cpp", "max_issues_repo_name": "AlQuemiste/Sourcery", "max_issues_repo_head_hexsha": "19cf230ee8134bf8a963949f02d02319dc2ee763", "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": "Cpp/hdf5/test_row_mat.cpp", "max_forks_repo_name": "AlQuemiste/Sourcery", "max_forks_repo_head_hexsha": "19cf230ee8134bf8a963949f02d02319dc2ee763", "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": 26.9463087248, "max_line_length": 91, "alphanum_fraction": 0.598007472, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5231190711259278}}
{"text": "//\n// MIT License\n// \n// Copyright (c) Deif Lou\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 <Eigen/Sparse>\n\n#include \"cubicsplineinterpolator1D.h\"\n\nnamespace ibp {\nnamespace misc {\n\nCubicSplineInterpolator1D::CubicSplineInterpolator1D() :\n    BaseSplineInterpolator1D(),\n    mFloorBoundaryConditions(BoundaryConditions_Natural),\n    mCeilBoundaryConditions(BoundaryConditions_Natural),\n    mFloorBoundaryConditionsValue(0.),\n    mCeilBoundaryConditionsValue(0.),\n    mIsDirty(true)\n{\n}\n\nInterpolator1D * CubicSplineInterpolator1D::clone() const\n{\n    CubicSplineInterpolator1D * si = new CubicSplineInterpolator1D();\n    if (!si)\n        return 0;\n    si->mKnots = mKnots;\n    si->mFloorExtrapolationMode = mFloorExtrapolationMode;\n    si->mCeilExtrapolationMode = mCeilExtrapolationMode;\n    si->mFloorExtrapolationValue = mFloorExtrapolationValue;\n    si->mCeilExtrapolationValue = mCeilExtrapolationValue;\n    si->mFloorBoundaryConditions = mFloorBoundaryConditions;\n    si->mCeilBoundaryConditions = mCeilBoundaryConditions;\n    si->mFloorBoundaryConditionsValue = mFloorBoundaryConditionsValue;\n    si->mCeilBoundaryConditionsValue = mCeilBoundaryConditionsValue;\n    si->mCoefficients = mCoefficients;\n    si->mIsDirty = mIsDirty;\n    return si;\n}\n\ndouble CubicSplineInterpolator1D::F(double x)\n{\n    if (mIsDirty)\n        calculateCoefficients();\n    const int piece = pieceForValue(x);\n    const double w = x - mKnots[piece].x();\n    return ((mCoefficients[piece].a * w + mCoefficients[piece].b) * w +\n            mCoefficients[piece].c) * w + mCoefficients[piece].d;\n}\n\ndouble CubicSplineInterpolator1D::floorExtrapolate(double x)\n{\n    if (mFloorExtrapolationMode == ExtrapolationMode_Constant)\n        return mFloorExtrapolationValue;\n    else if (mFloorExtrapolationMode == ExtrapolationMode_FollowTangent && mKnots.size() > 1)\n    {\n        if (mIsDirty)\n            calculateCoefficients();\n        return mCoefficients.first().c * (x - mKnots[0].x()) + mKnots[0].y();\n    }\n    else if (mFloorExtrapolationMode == ExtrapolationMode_Repeat && mKnots.size() > 1)\n        x = fmod(x - mKnots.first().x(), mKnots.last().x() - mKnots.first().x()) + mKnots.last().x();\n    else if (mFloorExtrapolationMode == ExtrapolationMode_Mirror && mKnots.size() > 1)\n    {\n        const double a = (mKnots.last().x() - mKnots.first().x()) * 2.;\n        const double b = (x - mKnots.first().x()) / a;\n        x = fabs(b - floor(b + .5)) * a + mKnots.first().x();\n    }\n    else\n        return mKnots.first().y();\n    return F(x);\n}\n\ndouble CubicSplineInterpolator1D::ceilExtrapolate(double x)\n{\n    if (mCeilExtrapolationMode == ExtrapolationMode_Constant)\n        return mCeilExtrapolationValue;\n    else if (mCeilExtrapolationMode == ExtrapolationMode_FollowTangent && mKnots.size() > 1)\n    {\n        if (mIsDirty)\n            calculateCoefficients();\n        const double lkp = mKnots.last().x() - mKnots[mKnots.size() - 2].x();\n        return ((3. * mCoefficients.last().a * lkp + 2. * mCoefficients.last().b) * lkp + mCoefficients.last().c) *\n               (x - mKnots.last().x()) + mKnots.last().y();\n    }\n    else if (mCeilExtrapolationMode == ExtrapolationMode_Repeat && mKnots.size() > 1)\n        x = fmod(x - mKnots.first().x(), mKnots.last().x() - mKnots.first().x()) + mKnots.first().x();\n    else if (mCeilExtrapolationMode == ExtrapolationMode_Mirror && mKnots.size() > 1)\n    {\n        const double a = (mKnots.last().x() - mKnots.first().x()) * 2.;\n        const double b = (x - mKnots.first().x()) / a;\n        x = fabs(b - floor(b + .5)) * a + mKnots.first().x();\n    }\n    else\n        return mKnots.last().y();\n    return F(x);\n}\n\nvoid CubicSplineInterpolator1D::calculateCoefficients()\n{\n    if (mKnots.size() < 1) return;\n\n    register int kSize = mKnots.size();\n    bool isPeriodic = mFloorBoundaryConditions == BoundaryConditions_Periodic &&\n                      mCeilBoundaryConditions == BoundaryConditions_Periodic;\n\n    mCoefficients.clear();\n    mCoefficients.resize(kSize > 1 ? kSize - 1 : 1);\n\n    if (kSize == 1)\n    {\n        // ------------------------------------------\n        // constant, the final value is extrapolated\n        // from the unique knot\n        // ------------------------------------------\n        mCoefficients[0].a = mCoefficients[0].b = mCoefficients[0].c = 0.;\n        mCoefficients[0].d = mKnots[0].y();\n    }\n    else if (kSize == 2)\n    {\n        // ------------------------------------------\n        // linear interpolation\n        // ------------------------------------------\n        mCoefficients[0].a = mCoefficients[0].b = 0.;\n        mCoefficients[0].c = (mKnots[1].y() - mKnots[0].y()) / (mKnots[1].x() - mKnots[0].x());\n        mCoefficients[0].d = mKnots[0].y();\n    }\n    else\n    {\n        // ------------------------------------------\n        // cubic interpolation\n        // ------------------------------------------\n        std::vector<Eigen::Triplet<double> > tripletList;\n        Eigen::SparseMatrix<double> AMatrix;\n        Eigen::VectorXd bVector;\n        Eigen::VectorXd xVector;\n        register float dx0, dx1, dx2, dy0, dy1;\n\n        // ------------------------------------------\n        // if is periodic, we need to solve a\n        // (ksize - 1) x (ksize - 1) system; otherwise,\n        // the system is (ksize - 2) x (ksize - 2)\n        // ------------------------------------------\n        if (isPeriodic)\n        {\n            tripletList.reserve((kSize - 1) * 3);\n            bVector = Eigen::VectorXd(kSize - 1);\n\n            // ------------------------------------------\n            // fill the A matrix and the b vector\n            // ------------------------------------------\n            for (int i = 1; i < kSize - 2; i++)\n            {\n                // distances between knots\n                dx0 = mKnots[i].x() - mKnots[i - 1].x();\n                dx1 = mKnots[i + 1].x() - mKnots[i].x();\n                dx2 = dx0 + dx1;\n                dy0 = mKnots[i].y() - mKnots[i - 1].y();\n                dy1 = mKnots[i + 1].y() - mKnots[i].y();\n                // diagonal\n                tripletList.push_back(Eigen::Triplet<double>(i, i, 2. * dx2));\n                // upper diagonal\n                tripletList.push_back(Eigen::Triplet<double>(i, i + 1, dx1));\n                // lower diagonal\n                tripletList.push_back(Eigen::Triplet<double>(i + 1, i, dx1));\n                // b vector\n                bVector(i) = 6. * (dy1 / dx1 - dy0 / dx0);\n            }\n\n            // ------------------------------------------\n            // fill the (0, 0), (0, 1), (0, n - 1),\n            // (1, 0), (n - 1, 0), (n - 1, n - 1) entries\n            // of A and the 0 and n - 1 entries of b\n            // ------------------------------------------\n            dx0 = mKnots[kSize - 1].x() - mKnots[kSize - 2].x();\n            dx1 = mKnots[1].x() - mKnots[0].x();\n            dx2 = dx0 + dx1;\n            dy0 = mKnots[0].y() - mKnots[kSize - 2].y();\n            dy1 = mKnots[1].y() - mKnots[0].y();\n            tripletList.push_back(Eigen::Triplet<double>(0, 0, 2. * dx2));\n            tripletList.push_back(Eigen::Triplet<double>(0, 1, dx1));\n            tripletList.push_back(Eigen::Triplet<double>(0, kSize - 2, dx0));\n            tripletList.push_back(Eigen::Triplet<double>(1, 0, dx1));\n            bVector(0) = 6. * (dy1 / dx1 - dy0 / dx0);\n            dx0 = mKnots[kSize - 2].x() - mKnots[kSize - 3].x();\n            dx1 = mKnots[kSize - 1].x() - mKnots[kSize - 2].x();\n            dx2 = dx0 + dx1;\n            dy0 = mKnots[kSize - 2].y() - mKnots[kSize - 3].y();\n            dy1 = mKnots[0].y() - mKnots[kSize - 2].y();\n            tripletList.push_back(Eigen::Triplet<double>(kSize - 2, 0, dx1));\n            tripletList.push_back(Eigen::Triplet<double>(kSize - 2, kSize - 2, 2. * dx2));\n            bVector(kSize - 2) = 6. * (dy1 / dx1 - dy0 / dx0);\n\n            // ------------------------------------------\n            // solve system and copy solution to vector x\n            // ------------------------------------------\n            AMatrix = Eigen::SparseMatrix<double>(kSize - 1, kSize - 1);\n            AMatrix.setFromTriplets(tripletList.begin(), tripletList.end());\n            Eigen::SparseLU<Eigen::SparseMatrix<double> > solver(AMatrix);\n            xVector = solver.solve(bVector);\n        }\n        else\n        {\n            tripletList.reserve((kSize - 2) * 3 - 2);\n            bVector = Eigen::VectorXd(kSize - 2);\n            xVector = Eigen::VectorXd(kSize);\n\n            // ------------------------------------------\n            // fill the A matrix and the b vector\n            // ------------------------------------------\n            for (int i = 0; i < kSize - 2; i++)\n            {\n                // distances between knots\n                dx0 = mKnots[i + 1].x() - mKnots[i].x();\n                dx1 = mKnots[i + 2].x() - mKnots[i + 1].x();\n                dx2 = dx0 + dx1;\n                dy0 = mKnots[i + 1].y() - mKnots[i].y();\n                dy1 = mKnots[i + 2].y() - mKnots[i + 1].y();\n                // diagonal\n                tripletList.push_back(Eigen::Triplet<double>(i, i, 2. * dx2));\n                if (i < kSize - 3)\n                {\n                    // upper diagonal\n                    tripletList.push_back(Eigen::Triplet<double>(i, i + 1, dx1));\n                    // lower diagonal\n                    tripletList.push_back(Eigen::Triplet<double>(i + 1, i, dx1));\n                }\n                // b vector\n                bVector(i) = 6. * (dy1 / dx1 - dy0 / dx0);\n            }\n\n            // ------------------------------------------\n            // modify A matrix and b vector subject to\n            // the end point constraints\n            // ------------------------------------------\n            dx0 = mKnots[1].x() - mKnots[0].x();\n            dx1 = mKnots[kSize - 1].x() - mKnots[kSize - 2].x();\n            dy0 = mKnots[1].y() - mKnots[0].y();\n            dy1 = mKnots[kSize - 1].y() - mKnots[kSize - 2].y();\n            if (mFloorBoundaryConditions == BoundaryConditions_Fixed1stDerivatives)\n            {\n                bVector(0) -= 3. * (dy0 / dx0 - mFloorBoundaryConditionsValue);\n                tripletList.at(0) = Eigen::Triplet<double>(0, 0, tripletList.at(0).value() - dx0 / 2.);\n            }\n            else if (mFloorBoundaryConditions == BoundaryConditions_Fixed2ndDerivatives)\n                bVector(0) -= dx0 * mFloorBoundaryConditionsValue;\n            else if (mFloorBoundaryConditions == BoundaryConditions_Copy)\n                tripletList.at(0) = Eigen::Triplet<double>(0, 0, tripletList.at(0).value() + dx0);\n            else if (mFloorBoundaryConditions == BoundaryConditions_Extrapolate && kSize > 3)\n            {\n                dx2 = dx0 * dx0 / (mKnots[2].x() - mKnots[1].x());\n                tripletList.at(0) = Eigen::Triplet<double>(0, 0, tripletList.at(0).value() + dx0 + dx2);\n                tripletList.at(1) = Eigen::Triplet<double>(0, 1, tripletList.at(1).value() - dx2);\n            }\n            // EndPointConstraints_Natural, EndPointConstraints_Extrapolate && kSize == 3\n            else\n                xVector(0) = 0.;\n\n            if (mCeilBoundaryConditions == BoundaryConditions_Fixed1stDerivatives)\n            {\n                bVector(kSize - 3) -= 3. * (mCeilBoundaryConditionsValue - dy1 / dx1);\n                tripletList.at(tripletList.size() - 1) = Eigen::Triplet<double>(kSize - 3, kSize - 3,\n                                                         tripletList.at(tripletList.size() - 1).value() - dx1 / 2.);\n            }\n            else if (mCeilBoundaryConditions == BoundaryConditions_Fixed2ndDerivatives)\n                bVector(kSize - 3) -= dx1 * mCeilBoundaryConditionsValue;\n            else if (mCeilBoundaryConditions == BoundaryConditions_Copy)\n                tripletList.at(tripletList.size() - 1) = Eigen::Triplet<double>(kSize - 3, kSize - 3,\n                                                         tripletList.at(tripletList.size() - 1).value() + dx1);\n            else if (mCeilBoundaryConditions == BoundaryConditions_Extrapolate && kSize > 3)\n            {\n                dx2 = dx1 * dx1 / (mKnots[kSize - 2].x() - mKnots[kSize - 3].x());\n                tripletList.at(tripletList.size() - 1) = Eigen::Triplet<double>(kSize - 3, kSize - 3,\n                                                         tripletList.at(tripletList.size() - 1).value() + dx1 + dx2);\n                tripletList.at(tripletList.size() - 2) = Eigen::Triplet<double>(kSize - 3, kSize - 4,\n                                                         tripletList.at(tripletList.size() - 2).value() - dx2);\n            }\n            // EndPointConstraints_Natural, EndPointConstraints_Extrapolate && kSize == 3\n            else\n                xVector(kSize - 1) = 0.;\n\n            // ------------------------------------------\n            // solve system and copy solution to vector x\n            // ------------------------------------------\n            AMatrix = Eigen::SparseMatrix<double>(kSize - 2, kSize - 2);\n            AMatrix.setFromTriplets(tripletList.begin(), tripletList.end());\n            Eigen::SparseLU<Eigen::SparseMatrix<double> > solver(AMatrix);\n            Eigen::VectorXd xVector2 = solver.solve(bVector);\n            for (int i = 0; i < kSize - 2; i++)\n                xVector(i + 1) = xVector2(i);\n\n            // ------------------------------------------\n            // fix the values of the second derivatives\n            // at the first and last knots based on\n            // the computed second derivatives at the\n            // interiot knots\n            // ------------------------------------------\n            if (mFloorBoundaryConditions == BoundaryConditions_Fixed1stDerivatives)\n                xVector(0) = (3. / dx0) * (dy0 / dx0 - mFloorBoundaryConditionsValue) - (xVector(1) / 2.);\n            else if (mFloorBoundaryConditions == BoundaryConditions_Fixed2ndDerivatives)\n                xVector(0) = mFloorBoundaryConditionsValue;\n            else if (mFloorBoundaryConditions == BoundaryConditions_Copy)\n                xVector(0) = xVector(1);\n            else if (mFloorBoundaryConditions == BoundaryConditions_Extrapolate && kSize > 3)\n                xVector(0) = xVector(1) - dx0 * (xVector(2) - xVector(1)) / (mKnots[2].x() - mKnots[1].x());\n\n            if (mCeilBoundaryConditions == BoundaryConditions_Fixed1stDerivatives)\n                xVector(kSize - 1) = (3. / dx1) * (mCeilBoundaryConditionsValue - dy1 / dx1) -\n                        (xVector(kSize - 2) / 2.);\n            else if (mCeilBoundaryConditions == BoundaryConditions_Fixed2ndDerivatives)\n                xVector(kSize - 1) = mCeilBoundaryConditionsValue;\n            else if (mCeilBoundaryConditions == BoundaryConditions_Copy)\n                xVector(kSize - 1) = xVector(kSize - 2);\n            else if (mCeilBoundaryConditions == BoundaryConditions_Extrapolate && kSize > 3)\n                xVector(kSize - 1) = xVector(kSize - 2) + dx1 * (xVector(kSize - 2) - xVector(kSize - 3)) /\n                                     (mKnots[kSize - 2].x() - mKnots[kSize - 3].x());\n        }\n\n        // ------------------------------------------\n        // compute polynomial coefficients\n        // ------------------------------------------\n        for (int i = 0; i < kSize - 1; i++)\n        {\n            // distances between knots\n            dx1 = mKnots[i + 1].x() - mKnots[i].x();\n            dy1 = mKnots[i + 1].y() - mKnots[i].y();\n            // compute coefficients\n            dx2 = isPeriodic && i == kSize - 2 ? xVector(0) : xVector(i + 1);\n            mCoefficients[i].a = (dx2 - xVector(i)) / (6. * dx1);\n            mCoefficients[i].b = xVector(i) / 2.;\n            mCoefficients[i].c = dy1 / dx1 - dx1 * (2. * xVector(i) + dx2) / 6.;\n            mCoefficients[i].d = mKnots[i].y();\n        }\n    }\n\n    mIsDirty = false;\n}\n\nbool CubicSplineInterpolator1D::setKnots(const Interpolator1DKnots &k)\n{\n    bool b = BaseSplineInterpolator1D::setKnots(k);\n    if (b) mIsDirty = true;\n    return b;\n}\n\nbool CubicSplineInterpolator1D::setKnot(int i, const Interpolator1DKnot &k)\n{\n    bool b = BaseSplineInterpolator1D::setKnot(i, k);\n    if (b) mIsDirty = true;\n    return b;\n}\n\nbool CubicSplineInterpolator1D::setKnot(int i, double nx, double ny)\n{\n    bool b = BaseSplineInterpolator1D::setKnot(i, nx, ny);\n    if (b) mIsDirty = true;\n    return b;\n}\n\nbool CubicSplineInterpolator1D::setKnot(double x, const Interpolator1DKnot &k)\n{\n    bool b = BaseSplineInterpolator1D::setKnot(x, k);\n    if (b) mIsDirty = true;\n    return b;\n}\n\nbool CubicSplineInterpolator1D::setKnot(double x, double nx, double ny)\n{\n    bool b = BaseSplineInterpolator1D::setKnot(x, nx, ny);\n    if (b) mIsDirty = true;\n    return b;\n}\n\nbool CubicSplineInterpolator1D::addKnot(const Interpolator1DKnot &k, bool replace, int * index)\n{\n    bool b = BaseSplineInterpolator1D::addKnot(k, replace, index);\n    if (b) mIsDirty = true;\n    return b;\n}\n\nbool CubicSplineInterpolator1D::addKnot(double nx, double ny, bool replace, int * index)\n{\n    bool b = BaseSplineInterpolator1D::addKnot(nx, ny, replace, index);\n    if (b) mIsDirty = true;\n    return b;\n}\n\nbool CubicSplineInterpolator1D::removeKnot(double x)\n{\n    bool b = BaseSplineInterpolator1D::removeKnot(x);\n    if (b) mIsDirty = true;\n    return b;\n}\n\nbool CubicSplineInterpolator1D::removeKnot(int i)\n{\n    bool b = BaseSplineInterpolator1D::removeKnot(i);\n    if (b) mIsDirty = true;\n    return b;\n}\n\nCubicSplineInterpolator1D::BoundaryConditions CubicSplineInterpolator1D::floorBoundaryConditions() const\n{\n    return mFloorBoundaryConditions;\n}\n\nCubicSplineInterpolator1D::BoundaryConditions CubicSplineInterpolator1D::ceilBoundaryConditions() const\n{\n    return mCeilBoundaryConditions;\n}\n\ndouble CubicSplineInterpolator1D::floorBoundaryConditionsValue() const\n{\n    return mFloorBoundaryConditionsValue;\n}\n\ndouble CubicSplineInterpolator1D::ceilBoundaryConditionsValue() const\n{\n    return mCeilBoundaryConditionsValue;\n}\n\nvoid CubicSplineInterpolator1D::setBoundaryConditions(BoundaryConditions f, BoundaryConditions c,\n                                                     double fv, double cv)\n{\n    mFloorBoundaryConditions = f;\n    mCeilBoundaryConditions = c;\n    mFloorBoundaryConditionsValue = fv;\n    mCeilBoundaryConditionsValue = cv;\n    mIsDirty = true;\n}\n\n}}\n", "meta": {"hexsha": "6bbb49ef09e15b5d89fdf30872bf949770f9dcef", "size": 19414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ibp/misc/cubicsplineinterpolator1D.cpp", "max_stars_repo_name": "deiflou/ibp", "max_stars_repo_head_hexsha": "9728f7569b59aa261dcaffc8332a1b02c2cd5fbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T18:44:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T15:57:40.000Z", "max_issues_repo_path": "src/ibp/misc/cubicsplineinterpolator1D.cpp", "max_issues_repo_name": "deiflou/ibp", "max_issues_repo_head_hexsha": "9728f7569b59aa261dcaffc8332a1b02c2cd5fbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ibp/misc/cubicsplineinterpolator1D.cpp", "max_forks_repo_name": "deiflou/ibp", "max_forks_repo_head_hexsha": "9728f7569b59aa261dcaffc8332a1b02c2cd5fbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-22T10:01:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T05:23:46.000Z", "avg_line_length": 42.8565121413, "max_line_length": 117, "alphanum_fraction": 0.5457401875, "num_tokens": 5401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.5231190667387684}}
{"text": "#define BOOST_TEST_MODULE test_fm\n\n#include <boost/test/unit_test.hpp>\n#include <smtrat-common/smtrat-common.h>\n#include <smtrat-qe/fm/qe.h>\n#include <iostream>\n\nusing namespace smtrat;\n\nBOOST_AUTO_TEST_SUITE( FMQE );\n\nBOOST_AUTO_TEST_CASE( FMQE_eliminate_single_variable )\n{\n    carl::Variable x = carl::freshRealVariable(\"x\");\n    carl::Variable y = carl::freshRealVariable(\"y\");\n    carl::Variable z = carl::freshRealVariable(\"z\");\n\n    ConstraintT c1 = ConstraintT(Poly(x) - Poly(y) + Poly(z), carl::Relation::GEQ);\n    ConstraintT c2 = ConstraintT(Poly(x) + Poly(y) + Poly(-5), carl::Relation::LEQ);\n\n    FormulasT constraints;\n    constraints.emplace_back(c1);\n    constraints.emplace_back(c2);\n\n    FormulaT inFormula = FormulaT(carl::FormulaType::AND, constraints);\n\n    std::cout << \"Formula: \" << inFormula << \", eliminate \" << x << std::endl;\n\n    qe::QEQuery query;\n    query.emplace_back(std::make_pair(qe::QuantifierType::EXISTS,std::vector<carl::Variable>{x}));\n\n    auto newFormula = qe::fm::eliminateQuantifiers(inFormula, query);\n\n    std::cout << \"New formula: \" << newFormula << std::endl;\n\n    BOOST_TEST(true, \"Ran successfully.\");\n}\n\nBOOST_AUTO_TEST_CASE( FMQE_eliminate_to_true )\n{\n    carl::Variable x = carl::freshRealVariable(\"x\");\n    carl::Variable y = carl::freshRealVariable(\"y\");\n\n    ConstraintT c1 = ConstraintT(Poly(x) - Poly(y), carl::Relation::GEQ);\n    ConstraintT c2 = ConstraintT(Poly(x) - Poly(y) + Poly(-5), carl::Relation::LEQ);\n\n    FormulasT constraints;\n    constraints.emplace_back(c1);\n    constraints.emplace_back(c2);\n\n    FormulaT inFormula = FormulaT(carl::FormulaType::AND, constraints);\n\n    std::cout << \"Formula: \" << inFormula << \", eliminate \" << x << std::endl;\n\n    qe::QEQuery query;\n    query.emplace_back(std::make_pair(qe::QuantifierType::EXISTS,std::vector<carl::Variable>{x}));\n\n    auto newFormula = qe::fm::eliminateQuantifiers(inFormula, query);\n\n    std::cout << \"New formula: \" << newFormula << std::endl;\n\n    BOOST_TEST((newFormula == FormulaT(carl::FormulaType::TRUE)));\n}\n\nBOOST_AUTO_TEST_CASE( FMQE_eliminate_to_true_with_remaining_constraint )\n{\n    carl::Variable x = carl::freshRealVariable(\"x\");\n    carl::Variable y = carl::freshRealVariable(\"y\");\n    carl::Variable z = carl::freshRealVariable(\"z\");\n\n    ConstraintT c1 = ConstraintT(Poly(x) - Poly(y), carl::Relation::GEQ);\n    ConstraintT c2 = ConstraintT(Poly(x) - Poly(y) + Poly(-5), carl::Relation::LEQ);\n    ConstraintT c3 = ConstraintT(Poly(y) - Poly(z), carl::Relation::LEQ);\n\n    FormulasT constraints;\n    constraints.emplace_back(c1);\n    constraints.emplace_back(c2);\n    constraints.emplace_back(c3);\n\n    FormulaT inFormula = FormulaT(carl::FormulaType::AND, constraints);\n\n    std::cout << \"Formula: \" << inFormula << \", eliminate \" << x << std::endl;\n\n    qe::QEQuery query;\n    query.emplace_back(std::make_pair(qe::QuantifierType::EXISTS,std::vector<carl::Variable>{x}));\n\n    auto newFormula = qe::fm::eliminateQuantifiers(inFormula, query);\n\n    std::cout << \"New formula: \" << newFormula << std::endl;\n\n    BOOST_TEST((newFormula == FormulaT(c3)));\n}\n\nBOOST_AUTO_TEST_CASE( FMQE_eliminate_several_variables )\n{\n    carl::Variable x = carl::freshRealVariable(\"x\");\n    carl::Variable y = carl::freshRealVariable(\"y\");\n    carl::Variable z = carl::freshRealVariable(\"z\");\n\n    ConstraintT c1 = ConstraintT(Poly(x) - Poly(y) + Poly(z), carl::Relation::GEQ);\n    ConstraintT c2 = ConstraintT(Poly(y), carl::Relation::GEQ);\n    ConstraintT c3 = ConstraintT(Poly(x) + Poly(y) + Poly(-5), carl::Relation::LEQ);\n\n    FormulasT constraints;\n    constraints.emplace_back(c1);\n    constraints.emplace_back(c2);\n    constraints.emplace_back(c3);\n\n    FormulaT inFormula = FormulaT(carl::FormulaType::AND, constraints);\n\n    std::cout << \"Formula: \" << inFormula << std::endl;\n\n    qe::QEQuery query;\n    query.emplace_back(std::make_pair(qe::QuantifierType::EXISTS,std::vector<carl::Variable>{x,y}));\n\n    auto newFormula = qe::fm::eliminateQuantifiers(inFormula, query);\n\n    std::cout << \"New formula: \" << newFormula << std::endl;\n\n    BOOST_TEST(true, \"Ran successfully.\");\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "536d7121558ff4eb86bc5b27839749e63ec84b90", "size": 4151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/fourierMotzkinQE/Test_fmqe.cpp", "max_stars_repo_name": "minemebarsha/smtrat", "max_stars_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-21T23:02:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T15:15:13.000Z", "max_issues_repo_path": "src/tests/fourierMotzkinQE/Test_fmqe.cpp", "max_issues_repo_name": "minemebarsha/smtrat", "max_issues_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-03-16T11:00:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T14:51:57.000Z", "max_forks_repo_path": "src/tests/fourierMotzkinQE/Test_fmqe.cpp", "max_forks_repo_name": "minemebarsha/smtrat", "max_forks_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_forks_repo_licenses": ["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.4758064516, "max_line_length": 100, "alphanum_fraction": 0.6820043363, "num_tokens": 1158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5231164539141936}}
{"text": "#include \"../DynAutoDiff/CeresOptimizer.hpp\"\n#include \"../DynAutoDiff/DynAutoDiff.hpp\"\n#include <algorithm>\n#include <boost/test/tools/old/interface.hpp>\n#include <eigen3/Eigen/Core>\n#include <iostream>\n#include <ostream>\n#include <vector>\n\n#define BOOST_TEST_MODULE Normal_Test\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#define TL 1e-10\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace DynAutoDiff;\n\nBOOST_AUTO_TEST_SUITE(Eigen_Helper_Test)\n\nBOOST_AUTO_TEST_CASE(load_mat_test) {\n    auto X = std::make_shared<Var<>>(\"X.txt\");\n    auto y = std::make_shared<Var<>>(\"y.txt\");\n    auto theta = pvec(X->cols()), c = psca();\n    auto loss = mse_loss(X * theta + c, y);\n\n    CeresOptimizer opt(loss);\n    opt.run();\n    std::cout << theta->val() << endl << c->v() << endl;\n}\n\nBOOST_AUTO_TEST_CASE(logistic_regression) {\n    auto X = std::make_shared<Var<>>(\"Xb.txt\");\n    auto y = std::make_shared<Var<>>(\"yb.txt\");\n    auto theta = pvec(X->cols()), c = psca();\n    auto loss = binary_cross_entropy(sigmoid(X * theta + c), y);\n\n    CeresOptimizer opt(loss);\n    opt.run();\n    std::cout << theta->val() << endl << c->v() << endl;\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "513441a53250db3bf6eb325cde88e541a619cea4", "size": 1228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_ceres_optimizer.cpp", "max_stars_repo_name": "kilasuelika/DynAutoDiff", "max_stars_repo_head_hexsha": "1da36182e93f4893201389c5841941500586e3ea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-26T06:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T06:13:56.000Z", "max_issues_repo_path": "test/test_ceres_optimizer.cpp", "max_issues_repo_name": "kilasuelika/DynAutoDiff", "max_issues_repo_head_hexsha": "1da36182e93f4893201389c5841941500586e3ea", "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/test_ceres_optimizer.cpp", "max_forks_repo_name": "kilasuelika/DynAutoDiff", "max_forks_repo_head_hexsha": "1da36182e93f4893201389c5841941500586e3ea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5581395349, "max_line_length": 64, "alphanum_fraction": 0.6783387622, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5231164473863332}}
{"text": "#include <boost/python/module.hpp>\n#include <boost/python/def.hpp>\n\nnamespace {\n\n  long\n  factorial(int n)\n  {\n    long fact = 1;\n    for(int i=2;i<=n;i++) {\n      fact *= i;\n    }\n    return fact;\n  }\n\n  double\n  power(double x, int n)\n  {\n    double pow = x;\n    for(int i=1;i<n;i++) {\n      pow *= x;\n    }\n    return pow;\n  }\n\n  double\n  sin(double x, int n_terms)\n  {\n    double result = x;\n    int sign = -1;\n    int pow = 3;\n    for(int i=1;i<n_terms;i++) {\n      result += power(x,pow)/(sign*factorial(pow));\n      sign *= -1;\n      pow += 2;\n    }\n    return result;\n  }\n\n  double\n  run_c_plus_plus(int n, int n_terms)\n  {\n    double result = 0;\n    while (n--) {\n      for(int i=0;i<180;i++) {\n        result += sin(i * 3.14159265359/180, n_terms);\n      }\n    }\n    return result;\n  }\n\n} // namespace anonymous\n\nBOOST_PYTHON_MODULE(boost_python_hybrid_times_ext)\n{\n  using namespace boost::python;\n  def(\"run_c_plus_plus\", run_c_plus_plus);\n}\n", "meta": {"hexsha": "f80610da83c6976f67e501f8ff6bf8645f173da6", "size": 954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost_adaptbx/hybrid_times_ext.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "boost_adaptbx/hybrid_times_ext.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "boost_adaptbx/hybrid_times_ext.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 16.1694915254, "max_line_length": 54, "alphanum_fraction": 0.5513626834, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5231164436548904}}
{"text": "// Copyright Andr\u00e1s Vukics 2006\u20132020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#define BOOST_TEST_MODULE StateVector\n#include <boost/test/unit_test.hpp>\n\n#include \"NonOrthogonalStateVector.h\"\n\nusing namespace quantumdata;\n\ntypedef CArray<1> Array1;\ntypedef CArray<2> Array2;\ntypedef NonOrthogonalStateVector<1, Array2> NOSV_Array2;\ntypedef transformation::Identity<1> I1;\ntypedef NonOrthogonalStateVector<1, I1> NOSV_I1;\ntypedef transformation::Identity<2> I2;\ntypedef NonOrthogonalStateVector<2, I2> NOSV_I2;\n\nBOOST_AUTO_TEST_CASE(Dual)\n{\n    // Create Transformation Matrix\n    Array2 T(3);\n    T = 1,0,0,\n        0,1,dcomp(0.5,-0.3),\n        0,dcomp(0.5,0.3),1;\n\n    // Create StateVector\n    Array1 x(3);\n    x = 1,2,3;\n    NOSV_Array2 sv1(x,T,byReference);\n\n    // Calculate and check dual vector\n    sv1.update();\n    Array1 dual = sv1.dual();\n    BOOST_CHECK_EQUAL(dual(0), x(0)*T(0,0)+x(1)*T(0,1)+x(2)*T(0,2));\n    BOOST_CHECK_EQUAL(dual(1), x(0)*T(1,0)+x(1)*T(1,1)+x(2)*T(1,2));\n    BOOST_CHECK_EQUAL(dual(2), x(0)*T(2,0)+x(1)*T(2,1)+x(2)*T(2,2));\n\n    // Check norm\n    BOOST_CHECK_EQUAL(sv1.norm(), sqrt(real(\n                                    sv1()(0)*conj(dual(0)) +\n                                    sv1()(1)*conj(dual(1)) +\n                                    sv1()(2)*conj(dual(2))\n                                    )));\n};\n\nBOOST_AUTO_TEST_CASE(CompositeStateVector)\n{\n    // Create Transformation Matrix\n    Array2 T(3,3);\n    T = 1,0,0,\n        0,1,dcomp(0.5,-0.5),\n        0,dcomp(0.5,0.5),1;\n\n    // Create StateVectors\n    Array1 x(3);\n    x = 1,2,3;\n    NOSV_Array2 sv1(x,T,byReference);\n\n    Array2 y(3,3);\n    y = 1,2,\n        3,1;\n    I2 i2;\n    NOSV_I2 sv2(y,i2,byReference);\n\n    typedef TensorType<NOSV_I2, NOSV_Array2>::type Result;\n    typedef Result::StateVectorLow ResultArray;\n    Result res1(sv2*sv1);\n\n    // Calculate all dual vectors.\n    res1.update();\n    sv1.update();\n    sv2.update();\n\n    // Check Composite StateVector\n    ResultArray res2(blitzplusplus::doDirect(sv2.dual(), sv1.dual(),\n                                    blitzplusplus::dodirect::Mul()));\n    blitz::Array<bool,3> b(3,3,3);\n    BOOST_CHECK(blitz::all(res1.dual()==res2));\n}\n\nBOOST_AUTO_TEST_CASE(vectorspace_operations)\n{\n    Array1 x(3), y(3);\n    x=1,2,3;\n    y=2,3,1;\n    I1 i1;\n    NOSV_I1 sv1(x, i1, byReference);\n    NOSV_I1 sv2(y, i1, byReference);\n    NOSV_I1 result_p(sv1 + sv2);\n    BOOST_CHECK_EQUAL(result_p()(0), x(0)+y(0));\n    BOOST_CHECK_EQUAL(result_p()(1), x(1)+y(1));\n    BOOST_CHECK_EQUAL(result_p()(2), x(2)+y(2));\n\n    NOSV_I1 result_m(sv1 - sv2);\n    BOOST_CHECK_EQUAL(result_m()(0), x(0)-y(0));\n    BOOST_CHECK_EQUAL(result_m()(1), x(1)-y(1));\n    BOOST_CHECK_EQUAL(result_m()(2), x(2)-y(2));\n\n    NOSV_I1 result_mul(sv1*dcomp(4));\n    BOOST_CHECK_EQUAL(result_mul()(0), x(0)*dcomp(4));\n    BOOST_CHECK_EQUAL(result_mul()(1), x(1)*dcomp(4));\n    BOOST_CHECK_EQUAL(result_mul()(2), x(2)*dcomp(4));\n}\n\n\n\nBOOST_AUTO_TEST_CASE(tensorproduct)\n{\n    I1 i1;\n    I2 i2;\n    Array1 x(3);\n    x = 1,2,3;\n    Array2 y(3,3);\n    y = 4,3,2,\n        5,4,3,\n        6,1,2;\n\n    NOSV_I1 sv1(x, i1, byReference);\n    NOSV_I2 sv2(y, i2, byReference);\n\n    typedef TensorType<NOSV_I1,NOSV_I2>::type NOSV_I1I2;\n    NOSV_I1I2 sv_i1i2(sv1*sv2);\n    typedef TensorType<NOSV_I2,NOSV_I1>::type NOSV_I2I1;\n    NOSV_I2I1 sv_i2i1(sv2*sv1);\n    typedef TensorType<NOSV_I1I2,NOSV_I1>::type NOSV_I1I2I1_a;\n    typedef TensorType<NOSV_I1,NOSV_I2I1>::type NOSV_I1I2I1_b;\n    BOOST_MPL_ASSERT(( boost::is_same<NOSV_I1I2I1_a, NOSV_I1I2I1_b> ));\n    typedef NOSV_I1I2I1_a NOSV_I1I2I1;\n    NOSV_I1I2I1(sv_i1i2*sv1);\n    NOSV_I1I2I1(sv1*sv_i2i1);\n\n    typedef StateVector<1> OSV;\n    OSV osv(x, ByReference());\n    NOSV_I2I1 mixed_a(sv2*osv);\n    NOSV_I1I2 mixed_b(osv*sv2);\n    typedef TensorType<NOSV_I2, OSV>::type NOSV_I2I1_orth;\n    typedef TensorType<OSV, NOSV_I2>::type NOSV_I1I2_orth;\n}\n\n\n\n", "meta": {"hexsha": "1e8f52b3f0e0990f48662accf3e895b3e62dcf76", "size": 3958, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CPPQEDcore/testsuite/NonOrthogonalStateVector.cc", "max_stars_repo_name": "bartoszek/cppqed", "max_stars_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T14:00:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T15:12:11.000Z", "max_issues_repo_path": "CPPQEDcore/testsuite/NonOrthogonalStateVector.cc", "max_issues_repo_name": "bartoszek/cppqed", "max_issues_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-04-14T11:18:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T20:11:23.000Z", "max_forks_repo_path": "CPPQEDcore/testsuite/NonOrthogonalStateVector.cc", "max_forks_repo_name": "bartoszek/cppqed", "max_forks_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T10:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T18:29:01.000Z", "avg_line_length": 28.0709219858, "max_line_length": 132, "alphanum_fraction": 0.6225366347, "num_tokens": 1452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.5231164415575773}}
{"text": "#include <algorithm>\n#include <fstream>\n#include <functional>\n#include <iostream>\n#include <iterator>\n#include <numeric>\n#include <set>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include <boost/range/counting_range.hpp>\n\nusing Location = std::string;\nusing LocationID = unsigned;\nusing Distance = unsigned;\n\nstruct Route {\n\tLocationID id1, id2;\n\tDistance distance;\n};\n\nstruct RouteEntry {\n\tLocation location_A, location_B;\n\tDistance distance;\n};\n\nauto& operator>>(std::istream& in, RouteEntry& entry) {\n\treturn in >> entry.location_A >> entry.location_B >> entry.distance;\n}\n\ntemplate<typename T>\nauto factorial(T n) {\n\tconst auto range = boost::counting_range<T>(2, (n + 1));\n\treturn std::accumulate(range.begin(), range.end(), T{1}, std::multiplies{});\n}\n\ntemplate<typename T>\nauto triangle(T n) {\n\treturn n * (n - 1) / 2;\n}\n\ntemplate<typename T>\nauto triangle_index(T a, T b) {\n\tconst auto& [min, max] = std::minmax(a, b);\n\treturn min + triangle(max);\n}\n\nint main() {\n\n\tconst auto filename = std::string{\"locations.txt\"};\n\tauto file = std::fstream{filename};\n\n\tif(file.is_open()) {\n\n\t\tauto locations = std::set<LocationID>{};\n\n\t\tconst auto add_location = [&locations] (const auto& location) {\n\n\t\t\tstatic auto location_id = LocationID{};\n\t\t\tstatic auto geo_map = std::unordered_map<Location, LocationID>{};\n\n\t\t\tconst auto pos = geo_map.try_emplace(location, 0);\n\n\t\t\tauto& current_id = pos.first->second;\n\n\t\t\tconst auto is_new_location = pos.second;\n\n\t\t\tif(is_new_location) {\n\t\t\t\t// the ids start from 0, hence the postfix increment\n\t\t\t\tcurrent_id = location_id++;\n\t\t\t\tlocations.insert(current_id);\n\t\t\t}\n\n\t\t\treturn current_id;\n\t\t};\n\n\t\tauto routes = std::vector<Route>{};\n\n\t\tRouteEntry entry;\n\n\t\twhile(file >> entry) {\n\t\t\troutes.push_back({\n\t\t\t\tadd_location(entry.location_A),\n\t\t\t\tadd_location(entry.location_B),\n\t\t\t\tentry.distance\n\t\t\t});\n\t\t}\n\n\t\t// ========================================\n\t\t// find shortest path through all locations\n\t\t// ========================================\n\n\t\t// will be used for various calculations\n\t\tconst auto size = locations.size();\n\n\t\t// 1) creates a lookup table for distances of all routes\n\t\t// 2) doing triangle instead of (size*size) halves the memory footprint,\n\t\t// but at the expense of doing additional calculation for each access\n\t\tauto chart = std::vector<Distance>(triangle(size));\n\n\t\t// log the distance for any given route between two locations\n\t\tfor(const auto& route : routes) {\n\t\t\tconst auto& index = triangle_index(route.id1, route.id2);\n\t\t\tchart[index] = route.distance;\n\t\t}\n\n\t\tauto itinerary = std::vector<LocationID>{locations.begin(), locations.end()};\n\t\tauto min_distance = Distance{std::numeric_limits<Distance>::max()};\n\n\t\t// only a subset of all possible permutations of routes is relevant for us,\n\t\t// so we create an upper limit to count down from when looping through permutations\n\t\tauto limit = (factorial(size) / size) * (size - 1);\n\n\t\tdo {\n\t\t\tconst auto begin1 = itinerary.begin();\n\t\t\tconst auto end1\t  = std::prev(itinerary.end());\n\t\t\tconst auto begin2 = std::next(begin1);\n\t\t\tconst auto acc\t  = Distance{};\n\t\t\tconst auto op1\t  = std::plus{};\n\t\t\tconst auto op2\t  = [&chart] (auto a, auto b) { return chart[triangle_index(a, b)]; };\n\n\t\t\t// inner_product resolves to acc = op1(acc, op2(begin1, begin2)) in a loop\n\t\t\tconst auto tmp_distance = std::inner_product(begin1, end1, begin2, acc, op1, op2);\n\n\t\t\tmin_distance = std::min(min_distance, tmp_distance);\n\n\t\t} while(((limit--) > 0) && std::next_permutation(itinerary.begin(), itinerary.end()));\n\n\t\tstd::cout << min_distance << std::endl;\n\n\t} else {\n\t\tstd::cerr << \"Error! Could not open \\\"\" << filename << \"\\\"!\" << std::endl;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "33048a26c85171866dfa3d8c93c679a80137df38", "size": 3676, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 09 Part 1/main.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 09 Part 1/main.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 09 Part 1/main.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6376811594, "max_line_length": 88, "alphanum_fraction": 0.6659412405, "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.5231164364279262}}
{"text": "#ifndef PROJECTION_HPP\n#define PROJECTION_HPP\n\n/**\n * \\file projection.hpp\n * \\brief Utilities for conversion from coordinates in an image to\n * geographical coordinates.\n * \\author Le Bars, Yoann\n * \\version 1.0\n * \\date 2013/06/27\n * \\date 2013/06/28\n * \\date 2014/03/06\n */\n\n#include <boost/concept_check.hpp>\n#include <cassert>\n#include <vector>\n#include <eigen3/Eigen/Dense>\n\n/// \\brief Namespace for projection computations.\nnamespace Projection {\n  /// \\brief Class for 2D points.\n  class Point2D {\n    public:\n      /**\n       * \\brief Construct a point with two double.\n       * \\param _x Abscissa.\n       * \\param _y Ordinate.\n       */\n      Point2D (double _x = 0., double _y = 0.): x_ (_x), y_ (_y) {}\n\n      /**\n       * \\brief Copy constructor.\n       * \\param p Point2D to be copied.\n       */\n      Point2D (const Point2D &p): x_ (p.x_), y_ (p.y_) {}\n\n      /// \\brief Destructor.\n      ~Point2D () {}\n\n      /// \\brief Access to abscissa, modification is not possible.\n      double x () const {return x_;}\n\n      /// \\brief Access to abscissa, modification is possible.\n      double &x () {return x_;}\n\n      /// \\brief Access to ordinate, modification is not possible.\n      double y () const {return y_;}\n\n      /// \\brief Access to ordinate, modification is possible.\n      double &y () {return y_;}\n\n      /**\n       * \\brief Copy operator.\n       * \\param p Point2D to be copied.\n       * \\return A reference to current point.\n       */\n      Point2D &operator = (const Point2D &p) {\n        x_ = p.x_;\n        y_ = p.y_;\n        return *this;\n      }\n\n    private:\n      /// \\brief Abscissa.\n      double x_;\n\n      /// \\brief Ordinate;\n      double y_;\n  };\n\n  /// \\brief Type for projection coefficients.\n  typedef Eigen::Matrix<double, 3, 2> Coefficients;\n\n  /**\n   * \\brief Compute the projection coefficients.\n   * \\param r1 Vector containing reference points in image coordinates.\n   * \\param r2 Vector containing reference points in geographical coordinates.\n   * \\return Vector containing projection coefficients.\n   *\n   * Information on coefficients can be found at:\n   * <http://en.wikipedia.org/wiki/World_file>\n   */\n  inline Coefficients computeCoefficients (const std::vector<Point2D> &r1,\n                                           const std::vector<Point2D> &r2) {\n    assert(r1.size() == 3);\n    assert(r2.size() == 3);\n    /* Matrix to compute coefficients. */\n    Eigen::Matrix3d a;\n    a << r1[0].x(), r1[0].y(), 1.,\n         r1[1].x(), r1[1].y(), 1.,\n         r1[2].x(), r1[2].y(), 1.;\n    /* Matrix of points in geographical coordinates. */\n    Coefficients b;\n    b << r2[0].x(), r2[0].y(),\n         r2[1].x(), r2[1].y(),\n         r2[2].x(), r2[2].y();\n//     return a.fullPivLu().solve(b);\n    return a.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n  }\n}\n\n#endif  // #ifndef PROJECTION_HPP\n", "meta": {"hexsha": "122d66f48e7330aeb7a1a6dc51f4cd3feab5e3d6", "size": 2856, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/projection.hpp", "max_stars_repo_name": "ylebars/GeoDesk", "max_stars_repo_head_hexsha": "7154f676c95910c51adad37d36439624e3d521bd", "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/projection.hpp", "max_issues_repo_name": "ylebars/GeoDesk", "max_issues_repo_head_hexsha": "7154f676c95910c51adad37d36439624e3d521bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/projection.hpp", "max_forks_repo_name": "ylebars/GeoDesk", "max_forks_repo_head_hexsha": "7154f676c95910c51adad37d36439624e3d521bd", "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.4615384615, "max_line_length": 78, "alphanum_fraction": 0.5864845938, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5230519185657002}}
{"text": "#ifndef NBT_SIMULATOR_HPP\n#define NBT_SIMULATOR_HPP\n\n#include <vector>\n#include <queue>\n#include <cstdint>\n\n#include <Eigen>\n#include \"integrator.hpp\"\n#include \"dynamics_engine.hpp\"\n#include \"rigidbody.hpp\"\n#include \"octree.hpp\"\n\n/**\n * Simulator object to control simulations.\n * Add objects using addObject().\n * Step simulation using step().\n */\nclass Simulator {\n    private:\n        Integrator* const integrator;         //!< Integrator used in this simulation.\n        DynamicsEngine* const dynamicsEngine; //!< dynamicsEngine use in this simulation.\n\n        double timeStep; //!< dt value used in integrators.\n\n        // Structure of arrays for object properties\n        Eigen::Matrix<double, 1, Eigen::Dynamic> m;     //!< Mass of each object packed into a 1 x N vector.\n        Eigen::Matrix<double, 1, Eigen::Dynamic> r;     //!< Radius of each object packed into a 1 x N vector.\n        Eigen::Matrix<double, 3, Eigen::Dynamic> pos;   //!< 3D position of each object packed into a 3 x N matrix.\n        Eigen::Matrix<double, 3, Eigen::Dynamic> v;     //!< 3D velocity of each object packed into a 3 x N matrix.\n        Eigen::Matrix<double, 3, Eigen::Dynamic> a;     //!< 3D acceleration of each object packed into a 3 x N matrix.\n    \n        uint64_t iteration = 0;                 //!< Current iteration of the simulation.\n        \n        RigidbodyIdx nextIdx = 0;               //!< Index of next available column in the structure of arrays. Also serves as a counter of active objects.\n        Rigidbody    nextID = 0;                //!< Next available ID to be assigned to a newly created Rigidbody.\n        std::vector<Rigidbody>    idx2id;       //!< Maps index to associated ID\n        std::vector<RigidbodyIdx> id2idx;       //!< Maps ID to associated index\n        std::queue<Rigidbody> availableUsedIDs; //!< Stores IDs of destroyed objects for reallocation\n       \n        /*! Returns slice of array structure component with only active objects. */\n        Eigen::Ref<Eigen::MatrixXd> active(Eigen::Ref<Eigen::MatrixXd> mat);\n\n        /*! Computes force between each object using #forceComputer. #a is updated. */\n        void updateAccelerations();\n    public:\n        const Rigidbody maxObjects;         //!< Maximum number of objects in the simulation. Sets the dimensions of the sstructure of arrays.\n\n        /*! Constructs a Simulator object. */\n        Simulator(double timeStep, uint64_t maxObjects, Integrator* integrator, DynamicsEngine* dynamicsEngine);\n        \n        /*! Destroys a Simulator object and deallocates all used memory. */\n        ~Simulator();\n\n        /*! Returns sum of kinetic energies of the particles in the system. */\n        double totalKineticEnergy();\n\n        /*! Returns sum of potential energies of each particle in the sytem */\n        double totalPotentialEnergy();\n\n        /*! Returns the sum of totalKineticEnergy() and totalPotentialEnergy() */\n        double totalEnergy();\n\n        /*! Returns sum of moments of inertia of each particle in the system */\n        double totalMomentOfInertia();\n\n        /*! Returns number of active objects */\n        Rigidbody nObjects();\n\n        /*! Adds an object to the simulation. Can be done during the simulation if the #maxObjects is not met. */\n        Rigidbody addObject(double m, double r, const Eigen::Vector3d& p0, const Eigen::Vector3d& v0);\n        \n        /*! Deletes an object from the simulation. */\n        void delObject(Rigidbody id);\n        \n        /*! Objects combine into id1 and momentum is conserved. */\n        void collideObject(Rigidbody id1, Rigidbody id2); // TODO collideObject remember to conserve momentum\n\n        /*! Returns if rigidbody with this id exists. */\n        bool rb_exists(Rigidbody id);\n\n        /*! Returns the position vector of a rigidbody. */\n        Eigen::Ref<const Eigen::Vector3d> rb_pos(Rigidbody id);\n\n        /*! Returns the velocity vector of a rigidbody. */\n        Eigen::Ref<const Eigen::Vector3d> rb_v(Rigidbody id);\n\n        /*! Returns the acceleration vector of a rigidbody. */\n        Eigen::Ref<const Eigen::Vector3d> rb_a(Rigidbody id);\n\n        /*! Returns the mass of a rigidbody. */\n        double rb_m(Rigidbody id);\n\n        /*! Returns the radius of a rigidbody. */\n        double rb_r(Rigidbody id);\n\n        /*! Returns Eigen::Matrix ref of object positions */\n        Eigen::Ref<const Eigen::Matrix3Xd> activePos();\n\n        /*! Returns Eigen::Matrix ref of object velocities */\n        Eigen::Ref<const Eigen::Matrix3Xd> activeV();\n\n        /*! Returns Eigen::Matrix ref of object accelerations */\n        Eigen::Ref<const Eigen::Matrix3Xd> activeA();\n\n        /*! Returns Eigen::Matrix ref of object masses */\n        Eigen::Ref<const Eigen::RowVectorXd> activeM();\n\n        /*! Returns Eigen::Matrix ref of object radii */\n        Eigen::Ref<const Eigen::RowVectorXd> activeR();\n\n        /*! Steps simulation */\n        void step();\n};\n\n#endif", "meta": {"hexsha": "40a10d1ef3fa4a8f163e318a2e1260e1c3282f00", "size": 4938, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/simulator.hpp", "max_stars_repo_name": "tdude92/nbody-tool", "max_stars_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-12T08:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:37:44.000Z", "max_issues_repo_path": "include/simulator.hpp", "max_issues_repo_name": "tdude92/nbody-tool", "max_issues_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_issues_repo_licenses": ["MIT"], "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/simulator.hpp", "max_forks_repo_name": "tdude92/nbody-tool", "max_forks_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_forks_repo_licenses": ["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.5689655172, "max_line_length": 155, "alphanum_fraction": 0.6413527744, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5230519185657002}}
{"text": "/* Copyright (C) 2019-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\n// This is a sample program for education purposes only.\n// It attempts to show the various basic mathematical\n// operations that can be performed on both ciphertexts\n// and plaintexts.\n\n#include <iostream>\n#include <boost/lexical_cast.hpp>\n#include <helib/helib.h>\n#include <time.h> \n\nint main(int argc, char* argv[])\n{\n  /*  Example of BGV scheme  */\n\n  if( argc != 3 && argc != 4 )\n  {std::cout << \"not enough args: need p and m\" << std::endl;\n\t\texit(-1);\n  }\n  // Plaintext prime modulus\n  unsigned long p = boost::lexical_cast<long>(argv[1]);\n  // Cyclotomic polynomial - defines phi(m)\n  unsigned long m = boost::lexical_cast<long>(argv[2]);\n  // Hensel lifting (default = 1)\n  unsigned long r = 1;\n  // Number of bits of the modulus chain\n  unsigned long bits = argc == 3 ? 300 : boost::lexical_cast<long>(argv[3]);\n  // Number of columns of Key-Switching matrix (default = 2 or 3)\n  unsigned long c = 2;\n\n\tclock_t start = clock();\n  // Initialize context\n  // This object will hold information about the algebra created from the\n  // previously set parameters\n  helib::Context context(m, p, r);\n  std::cout << \"Initialising context object...\" << (double)(clock()-start)/CLOCKS_PER_SEC << std::endl;\n  // Modify the context, adding primes to the modulus chain\n  // This defines the ciphertext space\n  buildModChain(context, bits, c);\n\tstd::cout << \"Building modulus chain...\" << (double)(clock()-start)/CLOCKS_PER_SEC << std::endl;\n\n  // Print the context\n  context.zMStar.printout();\n  std::cout << std::endl;\n\n  // Print the security level\n  std::cout << \"Security: \" << context.securityLevel() << std::endl;\n\n  //FIXME: really should make this a separate progrm but too lazy for that\n  if( argc == 3)\n    exit(0);\n\n\n  // Secret key management\n  std::cout << \"Creating secret key...\" << std::endl;\n  // Create a secret key associated with the context\n  helib::SecKey secret_key(context);\n  // Generate the secret key\n  secret_key.GenSecKey();\n  // Compute key-switching matrices that we need\n  helib::addSome1DMatrices(secret_key);\n  std::cout << \"Generating key-switching matrices...\" << (double)(clock()-start)/CLOCKS_PER_SEC << std::endl;\n\n  // Public key management\n  // Set the secret key (upcast: SecKey is a subclass of PubKey)\n  const helib::PubKey& public_key = secret_key;\n\n  // Get the EncryptedArray of the context\n  const helib::EncryptedArray& ea = *(context.ea);\n\n  // Get the number of slot (phi(m))\n  long nslots = ea.size();\n  std::cout << \"Number of slots: \" << nslots << std::endl;\n\n  // Create a vector of long with nslots elements\n  helib::Ptxt<helib::BGV> ptxt(context);\n  // Set it with numbers 0..nslots - 1\n  // ptxt = [0] [1] [2] ... [nslots-2] [nslots-1]\n  for (int i = 0; i < ptxt.size(); ++i) {\n    ptxt[i] = i;\n  }\n\n  // Create a ciphertext object\n\tstart = clock();\n  helib::Ctxt ctxt(public_key);\n  // Encrypt the plaintext using the public_key\n  public_key.Encrypt(ctxt, ptxt);\n\tstd::cout << \"Done encrypting: \" << (double)(clock()-start)/CLOCKS_PER_SEC << std::endl;\n\n  // ********** Operations ********** \n  // Ciphertext and plaintext operations are performed\n  // \"entry-wise\".\n\n  // Square the ciphertext\n  // [0] [1] [2] [3] [4] ... [nslots-1]\n  // -> [0] [1] [4] [9] [16] ... [(nslots-1)*(nslots-1)]\n\tstart = clock();\n\tctxt.multiplyBy(ctxt);\n  std::cout << \"Power: \" << (double)(clock()-start)/CLOCKS_PER_SEC << std::endl;\n \n  // Raise the copy to the exponent 2\n  // Note: 0 is a special case because 0^n = 0 for any power n\n  //ctxt.power(2);\n\n  // Subtract it from itself (result should be 0)\n\tstart = clock();\n  ctxt += ctxt;\n\tstd::cout << \"Subtract: \" << (double)(clock()-start)/CLOCKS_PER_SEC << std::endl;\n\n  // Create a plaintext for decryption\n  start = clock();\n  helib::Ptxt<helib::BGV> plaintext_result(context);\n  // Decrypt the modified ciphertext\n  secret_key.Decrypt(plaintext_result, ctxt);\n\tstd::cout << \"Decryt: \" << (double)(clock()-start)/CLOCKS_PER_SEC << std::endl;\n\n  // Print the decrypted plaintext\n  std::cout << \"Decrypted Result: \" << plaintext_result << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "55b596e40f498594835cdcf7c596b11b25290476", "size": 4695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/secur/secur.cpp", "max_stars_repo_name": "nabulator/HElib", "max_stars_repo_head_hexsha": "3c7b89a94bbc129d7d4a71177e46aebf4041bed9", "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/secur/secur.cpp", "max_issues_repo_name": "nabulator/HElib", "max_issues_repo_head_hexsha": "3c7b89a94bbc129d7d4a71177e46aebf4041bed9", "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/secur/secur.cpp", "max_forks_repo_name": "nabulator/HElib", "max_forks_repo_head_hexsha": "3c7b89a94bbc129d7d4a71177e46aebf4041bed9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-16T21:52:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T21:52:47.000Z", "avg_line_length": 35.3007518797, "max_line_length": 109, "alphanum_fraction": 0.6685835996, "num_tokens": 1294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5230519185657001}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2004 Ferdinando Ametrano\n Copyright (C) 2005, 2006 StatPro Italia srl\n Copyright (C) 2007 Giorgio Facchinetti\n Copyright (C) 2009 Dimitri Reiswich\n Copyright (C) 2014 Peter Caspers\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 \"interpolations.hpp\"\n#include \"utilities.hpp\"\n#include <ql/utilities/dataformatters.hpp>\n#include <ql/utilities/null.hpp>\n#include <ql/math/interpolations/linearinterpolation.hpp>\n#include <ql/math/interpolations/bicubicsplineinterpolation.hpp>\n#include <ql/math/interpolations/backwardflatinterpolation.hpp>\n#include <ql/math/interpolations/forwardflatinterpolation.hpp>\n#include <ql/math/interpolations/cubicinterpolation.hpp>\n#include <ql/math/interpolations/multicubicspline.hpp>\n#include <ql/math/interpolations/sabrinterpolation.hpp>\n#include <ql/math/interpolations/kernelinterpolation.hpp>\n#include <ql/math/interpolations/kernelinterpolation2d.hpp>\n#include <ql/math/interpolations/lagrangeinterpolation.hpp>\n#include <ql/math/integrals/simpsonintegral.hpp>\n#include <ql/math/kernelfunctions.hpp>\n#include <ql/math/functional.hpp>\n#include <ql/math/richardsonextrapolation.hpp>\n#include <ql/math/randomnumbers/sobolrsg.hpp>\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/experimental/volatility/noarbsabrinterpolation.hpp>\n#include <boost/foreach.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\n#define BEGIN(x) (x+0)\n#define END(x) (x+LENGTH(x))\n\nnamespace {\n\n    std::vector<Real> xRange(Real start, Real finish, Size points) {\n        std::vector<Real> x(points);\n        Real dx = (finish-start)/(points-1);\n        for (Size i=0; i<points-1; i++)\n            x[i] = start+i*dx;\n        x[points-1] = finish;\n        return x;\n    }\n\n    std::vector<Real> gaussian(const std::vector<Real>& x) {\n        std::vector<Real> y(x.size());\n        for (Size i=0; i<x.size(); i++)\n            y[i] = std::exp(-x[i]*x[i]);\n        return y;\n    }\n\n    std::vector<Real> parabolic(const std::vector<Real>& x) {\n        std::vector<Real> y(x.size());\n        for (Size i=0; i<x.size(); i++)\n            y[i] = -x[i]*x[i];\n        return y;\n    }\n\n    template <class I, class J>\n    void checkValues(const char* type,\n                     const CubicInterpolation& cubic,\n                     I xBegin, I xEnd, J yBegin) {\n        Real tolerance = 2.0e-15;\n        while (xBegin != xEnd) {\n            Real interpolated = cubic(*xBegin);\n            if (std::fabs(interpolated-*yBegin) > tolerance) {\n                BOOST_ERROR(type << \" interpolation failed at x = \" << *xBegin\n                            << QL_SCIENTIFIC\n                            << \"\\n    interpolated value: \" << interpolated\n                            << \"\\n    expected value:     \" << *yBegin\n                            << \"\\n    error:              \"\n                            << std::fabs(interpolated-*yBegin));\n            }\n            ++xBegin; ++yBegin;\n        }\n    }\n\n    void check1stDerivativeValue(const char* type,\n                                 const CubicInterpolation& cubic,\n                                 Real x,\n                                 Real value) {\n        Real tolerance = 1.0e-14;\n        Real interpolated = cubic.derivative(x);\n        Real error = std::fabs(interpolated-value);\n        if (error > tolerance) {\n            BOOST_ERROR(type << \" interpolation first derivative failure\\n\"\n                        << \"at x = \" << x\n                        << \"\\n    interpolated value: \" << interpolated\n                        << \"\\n    expected value:     \" << value\n                        << QL_SCIENTIFIC\n                        << \"\\n    error:              \" << error);\n        }\n    }\n\n    void check2ndDerivativeValue(const char* type,\n                                 const CubicInterpolation& cubic,\n                                 Real x,\n                                 Real value) {\n        Real tolerance = 1.0e-13;\n        Real interpolated = cubic.secondDerivative(x);\n        Real error = std::fabs(interpolated-value);\n        if (error > tolerance) {\n            BOOST_ERROR(type << \" interpolation second derivative failure\\n\"\n                        << \"at x = \" << x\n                        << \"\\n    interpolated value: \" << interpolated\n                        << \"\\n    expected value:     \" << value\n                        << QL_SCIENTIFIC\n                        << \"\\n    error:              \" << error);\n        }\n    }\n\n    void checkNotAKnotCondition(const char* type,\n                                const CubicInterpolation& cubic) {\n        Real tolerance = 1.0e-14;\n        const std::vector<Real>& c = cubic.cCoefficients();\n        if (std::fabs(c[0]-c[1]) > tolerance) {\n            BOOST_ERROR(type << \" interpolation failure\"\n                        << \"\\n    cubic coefficient of the first\"\n                        << \" polinomial is \" << c[0]\n                        << \"\\n    cubic coefficient of the second\"\n                        << \" polinomial is \" << c[1]);\n        }\n        Size n = c.size();\n        if (std::fabs(c[n-2]-c[n-1]) > tolerance) {\n            BOOST_ERROR(type << \" interpolation failure\"\n                        << \"\\n    cubic coefficient of the 2nd to last\"\n                        << \" polinomial is \" << c[n-2]\n                        << \"\\n    cubic coefficient of the last\"\n                        << \" polinomial is \" << c[n-1]);\n        }\n    }\n\n    void checkSymmetry(const char* type,\n                       const CubicInterpolation& cubic,\n                       Real xMin) {\n        Real tolerance = 1.0e-15;\n        for (Real x = xMin; x < 0.0; x += 0.1) {\n            Real y1 = cubic(x), y2 = cubic(-x);\n            if (std::fabs(y1-y2) > tolerance) {\n                BOOST_ERROR(type << \" interpolation not symmetric\"\n                            << \"\\n    x = \" << x\n                            << \"\\n    g(x)  = \" << y1\n                            << \"\\n    g(-x) = \" << y2\n                            << \"\\n    error:  \" << std::fabs(y1-y2));\n            }\n        }\n    }\n\n    template <class F>\n    class errorFunction : public std::unary_function<Real,Real> {\n      public:\n        errorFunction(const F& f) : f_(f) {}\n        Real operator()(Real x) const {\n            Real temp = f_(x)-std::exp(-x*x);\n            return temp*temp;\n        }\n      private:\n        F f_;\n    };\n\n    template <class F>\n    errorFunction<F> make_error_function(const F& f) {\n        return errorFunction<F>(f);\n    }\n\n    Real multif(Real s, Real t, Real u, Real v, Real w) {\n        return std::sqrt(s * std::sinh(std::log(t)) +\n                         std::exp(std::sin(u) * std::sin(3 * v)) +\n                         std::sinh(std::log(v * w)));\n    }\n\n    Real epanechnikovKernel(Real u){\n\n        if(std::fabs(u)<=1){\n            return (3.0/4.0)*(1-u*u);\n        }else{\n            return 0.0;\n        }\n    }\n\n}\n\n\n/* See J. M. Hyman, \"Accurate monotonicity preserving cubic interpolation\"\n   SIAM J. of Scientific and Statistical Computing, v. 4, 1983, pp. 645-654.\n   http://math.lanl.gov/~mac/papers/numerics/H83.pdf\n*/\nvoid InterpolationTest::testSplineErrorOnGaussianValues() {\n\n    BOOST_TEST_MESSAGE(\"Testing spline approximation on Gaussian data sets...\");\n\n    Size points[]                = {      5,      9,     17,     33 };\n\n    // complete spline data from the original 1983 Hyman paper\n    Real tabulatedErrors[]     = { 3.5e-2, 2.0e-3, 4.0e-5, 1.8e-6 };\n    Real toleranceOnTabErr[]   = { 0.1e-2, 0.1e-3, 0.1e-5, 0.1e-6 };\n\n    // (complete) MC spline data from the original 1983 Hyman paper\n    // NB: with the improved Hyman filter from the Dougherty, Edelman, and\n    //     Hyman 1989 paper the n=17 nonmonotonicity is not filtered anymore\n    //     so the error agrees with the non MC method.\n    Real tabulatedMCErrors[]   = { 1.7e-2, 2.0e-3, 4.0e-5, 1.8e-6 };\n    Real toleranceOnTabMCErr[] = { 0.1e-2, 0.1e-3, 0.1e-5, 0.1e-6 };\n\n    SimpsonIntegral integral(1e-12, 10000);\n    std::vector<Real> x, y;\n\n    // still unexplained scale factor needed to obtain the numerical\n    // results from the paper\n    Real scaleFactor = 1.9;\n\n    for (Size i=0; i<LENGTH(points); i++) {\n        Size n = points[i];\n        std::vector<Real> x = xRange(-1.7, 1.9, n);\n        std::vector<Real> y = gaussian(x);\n\n        // Not-a-knot\n        CubicInterpolation f(x.begin(), x.end(), y.begin(),\n                             CubicInterpolation::Spline, false,\n                             CubicInterpolation::NotAKnot, Null<Real>(),\n                             CubicInterpolation::NotAKnot, Null<Real>());\n        f.update();\n        Real result = std::sqrt(integral(make_error_function(f), -1.7, 1.9));\n        result /= scaleFactor;\n        if (std::fabs(result-tabulatedErrors[i]) > toleranceOnTabErr[i])\n            BOOST_ERROR(\"Not-a-knot spline interpolation \"\n                        << \"\\n    sample points:      \" << n\n                        << \"\\n    norm of difference: \" << result\n                        << \"\\n    it should be:       \" << tabulatedErrors[i]);\n\n        // MC not-a-knot\n        f = CubicInterpolation(x.begin(), x.end(), y.begin(),\n                               CubicInterpolation::Spline, true,\n                               CubicInterpolation::NotAKnot, Null<Real>(),\n                               CubicInterpolation::NotAKnot, Null<Real>());\n        f.update();\n        result = std::sqrt(integral(make_error_function(f), -1.7, 1.9));\n        result /= scaleFactor;\n        if (std::fabs(result-tabulatedMCErrors[i]) > toleranceOnTabMCErr[i])\n            BOOST_ERROR(\"MC Not-a-knot spline interpolation \"\n                        << \"\\n    sample points:      \" << n\n                        << \"\\n    norm of difference: \" << result\n                        << \"\\n    it should be:       \"\n                        << tabulatedMCErrors[i]);\n    }\n\n}\n\n/* See J. M. Hyman, \"Accurate monotonicity preserving cubic interpolation\"\n   SIAM J. of Scientific and Statistical Computing, v. 4, 1983, pp. 645-654.\n   http://math.lanl.gov/~mac/papers/numerics/H83.pdf\n*/\nvoid InterpolationTest::testSplineOnGaussianValues() {\n\n    BOOST_TEST_MESSAGE(\"Testing spline interpolation on a Gaussian data set...\");\n\n    Real interpolated, interpolated2;\n    Size n = 5;\n\n    std::vector<Real> x(n), y(n);\n    Real x1_bad=-1.7, x2_bad=1.7;\n\n    for (Real start = -1.9, j=0; j<2; start+=0.2, j++) {\n        x = xRange(start, start+3.6, n);\n        y = gaussian(x);\n\n        // Not-a-knot spline\n        CubicInterpolation f(x.begin(), x.end(), y.begin(),\n                             CubicInterpolation::Spline, false,\n                             CubicInterpolation::NotAKnot, Null<Real>(),\n                             CubicInterpolation::NotAKnot, Null<Real>());\n        f.update();\n        checkValues(\"Not-a-knot spline\", f,\n                    x.begin(), x.end(), y.begin());\n        checkNotAKnotCondition(\"Not-a-knot spline\", f);\n        // bad performance\n        interpolated = f(x1_bad);\n        interpolated2= f(x2_bad);\n        if (interpolated>0.0 && interpolated2>0.0 ) {\n            BOOST_ERROR(\"Not-a-knot spline interpolation \"\n                        << \"bad performance unverified\"\n                        << \"\\nat x = \" << x1_bad\n                        << \" interpolated value: \" << interpolated\n                        << \"\\nat x = \" << x2_bad\n                        << \" interpolated value: \" << interpolated\n                        << \"\\n at least one of them was expected to be < 0.0\");\n        }\n\n        // MC not-a-knot spline\n        f = CubicInterpolation(x.begin(), x.end(), y.begin(),\n                               CubicInterpolation::Spline, true,\n                               CubicInterpolation::NotAKnot, Null<Real>(),\n                               CubicInterpolation::NotAKnot, Null<Real>());\n        f.update();\n        checkValues(\"MC not-a-knot spline\", f,\n                    x.begin(), x.end(), y.begin());\n        // good performance\n        interpolated = f(x1_bad);\n        if (interpolated<0.0) {\n            BOOST_ERROR(\"MC not-a-knot spline interpolation \"\n                        << \"good performance unverified\\n\"\n                        << \"at x = \" << x1_bad\n                        << \"\\ninterpolated value: \" << interpolated\n                        << \"\\nexpected value > 0.0\");\n        }\n        interpolated = f(x2_bad);\n        if (interpolated<0.0) {\n            BOOST_ERROR(\"MC not-a-knot spline interpolation \"\n                        << \"good performance unverified\\n\"\n                        << \"at x = \" << x2_bad\n                        << \"\\ninterpolated value: \" << interpolated\n                        << \"\\nexpected value > 0.0\");\n        }\n    }\n}\n\n\n/* See J. M. Hyman, \"Accurate monotonicity preserving cubic interpolation\"\n   SIAM J. of Scientific and Statistical Computing, v. 4, 1983, pp. 645-654.\n   http://math.lanl.gov/~mac/papers/numerics/H83.pdf\n*/\nvoid InterpolationTest::testSplineOnRPN15AValues() {\n\n    BOOST_TEST_MESSAGE(\"Testing spline interpolation on RPN15A data set...\");\n\n    const Real RPN15A_x[] = {\n        7.99,       8.09,       8.19,      8.7,\n        9.2,     10.0,     12.0,     15.0,     20.0\n    };\n    const Real RPN15A_y[] = {\n        0.0, 2.76429e-5, 4.37498e-5, 0.169183,\n        0.469428, 0.943740, 0.998636, 0.999919, 0.999994\n    };\n\n    Real interpolated;\n\n    // Natural spline\n    CubicInterpolation f = CubicInterpolation(\n                                    BEGIN(RPN15A_x), END(RPN15A_x),\n                                    BEGIN(RPN15A_y),\n                                    CubicInterpolation::Spline, false,\n                                    CubicInterpolation::SecondDerivative, 0.0,\n                                    CubicInterpolation::SecondDerivative, 0.0);\n    f.update();\n    checkValues(\"Natural spline\", f,\n                BEGIN(RPN15A_x), END(RPN15A_x), BEGIN(RPN15A_y));\n    check2ndDerivativeValue(\"Natural spline\", f,\n                            *BEGIN(RPN15A_x), 0.0);\n    check2ndDerivativeValue(\"Natural spline\", f,\n                            *(END(RPN15A_x)-1), 0.0);\n    // poor performance\n    Real x_bad = 11.0;\n    interpolated = f(x_bad);\n    if (interpolated<1.0) {\n        BOOST_ERROR(\"Natural spline interpolation \"\n                    << \"poor performance unverified\\n\"\n                    << \"at x = \" << x_bad\n                    << \"\\ninterpolated value: \" << interpolated\n                    << \"\\nexpected value > 1.0\");\n    }\n\n\n    // Clamped spline\n    f = CubicInterpolation(BEGIN(RPN15A_x), END(RPN15A_x), BEGIN(RPN15A_y),\n                           CubicInterpolation::Spline, false,\n                           CubicInterpolation::FirstDerivative, 0.0,\n                           CubicInterpolation::FirstDerivative, 0.0);\n    f.update();\n    checkValues(\"Clamped spline\", f,\n                BEGIN(RPN15A_x), END(RPN15A_x), BEGIN(RPN15A_y));\n    check1stDerivativeValue(\"Clamped spline\", f,\n                            *BEGIN(RPN15A_x), 0.0);\n    check1stDerivativeValue(\"Clamped spline\", f,\n                            *(END(RPN15A_x)-1), 0.0);\n    // poor performance\n    interpolated = f(x_bad);\n    if (interpolated<1.0) {\n        BOOST_ERROR(\"Clamped spline interpolation \"\n                    << \"poor performance unverified\\n\"\n                    << \"at x = \" << x_bad\n                    << \"\\ninterpolated value: \" << interpolated\n                    << \"\\nexpected value > 1.0\");\n    }\n\n\n    // Not-a-knot spline\n    f = CubicInterpolation(BEGIN(RPN15A_x), END(RPN15A_x), BEGIN(RPN15A_y),\n                           CubicInterpolation::Spline, false,\n                           CubicInterpolation::NotAKnot, Null<Real>(),\n                           CubicInterpolation::NotAKnot, Null<Real>());\n    f.update();\n    checkValues(\"Not-a-knot spline\", f,\n                BEGIN(RPN15A_x), END(RPN15A_x), BEGIN(RPN15A_y));\n    checkNotAKnotCondition(\"Not-a-knot spline\", f);\n    // poor performance\n    interpolated = f(x_bad);\n    if (interpolated<1.0) {\n        BOOST_ERROR(\"Not-a-knot spline interpolation \"\n                    << \"poor performance unverified\\n\"\n                    << \"at x = \" << x_bad\n                    << \"\\ninterpolated value: \" << interpolated\n                    << \"\\nexpected value > 1.0\");\n    }\n\n\n    // MC natural spline values\n    f = CubicInterpolation(BEGIN(RPN15A_x), END(RPN15A_x),\n                           BEGIN(RPN15A_y),\n                           CubicInterpolation::Spline, true,\n                           CubicInterpolation::SecondDerivative, 0.0,\n                           CubicInterpolation::SecondDerivative, 0.0);\n    f.update();\n    checkValues(\"MC natural spline\", f,\n                BEGIN(RPN15A_x), END(RPN15A_x), BEGIN(RPN15A_y));\n    // good performance\n    interpolated = f(x_bad);\n    if (interpolated>1.0) {\n        BOOST_ERROR(\"MC natural spline interpolation \"\n                    << \"good performance unverified\\n\"\n                    << \"at x = \" << x_bad\n                    << \"\\ninterpolated value: \" << interpolated\n                    << \"\\nexpected value < 1.0\");\n    }\n\n\n    // MC clamped spline values\n    f = CubicInterpolation(BEGIN(RPN15A_x), END(RPN15A_x), BEGIN(RPN15A_y),\n                           CubicInterpolation::Spline, true,\n                           CubicInterpolation::FirstDerivative, 0.0,\n                           CubicInterpolation::FirstDerivative, 0.0);\n    f.update();\n    checkValues(\"MC clamped spline\", f,\n                BEGIN(RPN15A_x), END(RPN15A_x), BEGIN(RPN15A_y));\n    check1stDerivativeValue(\"MC clamped spline\", f,\n                            *BEGIN(RPN15A_x), 0.0);\n    check1stDerivativeValue(\"MC clamped spline\", f,\n                            *(END(RPN15A_x)-1), 0.0);\n    // good performance\n    interpolated = f(x_bad);\n    if (interpolated>1.0) {\n        BOOST_ERROR(\"MC clamped spline interpolation \"\n                    << \"good performance unverified\\n\"\n                    << \"at x = \" << x_bad\n                    << \"\\ninterpolated value: \" << interpolated\n                    << \"\\nexpected value < 1.0\");\n    }\n\n\n    // MC not-a-knot spline values\n    f = CubicInterpolation(BEGIN(RPN15A_x), END(RPN15A_x), BEGIN(RPN15A_y),\n                           CubicInterpolation::Spline, true,\n                           CubicInterpolation::NotAKnot, Null<Real>(),\n                           CubicInterpolation::NotAKnot, Null<Real>());\n    f.update();\n    checkValues(\"MC not-a-knot spline\", f,\n                BEGIN(RPN15A_x), END(RPN15A_x), BEGIN(RPN15A_y));\n    // good performance\n    interpolated = f(x_bad);\n    if (interpolated>1.0) {\n        BOOST_ERROR(\"MC clamped spline interpolation \"\n                    << \"good performance unverified\\n\"\n                    << \"at x = \" << x_bad\n                    << \"\\ninterpolated value: \" << interpolated\n                    << \"\\nexpected value < 1.0\");\n    }\n}\n\n/* Blossey, Frigyik, Farnum \"A Note On CubicSpline Splines\"\n   Applied Linear Algebra and Numerical Analysis AMATH 352 Lecture Notes\n   http://www.amath.washington.edu/courses/352-winter-2002/spline_note.pdf\n*/\nvoid InterpolationTest::testSplineOnGenericValues() {\n\n    BOOST_TEST_MESSAGE(\"Testing spline interpolation on generic values...\");\n\n    const Real generic_x[] = { 0.0, 1.0, 3.0, 4.0 };\n    const Real generic_y[] = { 0.0, 0.0, 2.0, 2.0 };\n    const Real generic_natural_y2[] = { 0.0, 1.5, -1.5, 0.0 };\n\n    Real interpolated, error;\n    Size i, n = LENGTH(generic_x);\n    std::vector<Real> x35(3);\n\n    // Natural spline\n    CubicInterpolation f(BEGIN(generic_x), END(generic_x),\n                         BEGIN(generic_y),\n                         CubicInterpolation::Spline, false,\n                         CubicInterpolation::SecondDerivative,\n                         generic_natural_y2[0],\n                         CubicInterpolation::SecondDerivative,\n                         generic_natural_y2[n-1]);\n    f.update();\n    checkValues(\"Natural spline\", f,\n                BEGIN(generic_x), END(generic_x), BEGIN(generic_y));\n    // cached second derivative\n    for (i=0; i<n; i++) {\n        interpolated = f.secondDerivative(generic_x[i]);\n        error = interpolated - generic_natural_y2[i];\n        if (std::fabs(error)>3e-16) {\n            BOOST_ERROR(\"Natural spline interpolation \"\n                        << \"second derivative failed at x=\" << generic_x[i]\n                        << \"\\ninterpolated value: \" << interpolated\n                        << \"\\nexpected value:     \" << generic_natural_y2[i]\n                        << \"\\nerror:              \" << error);\n        }\n    }\n    x35[1] = f(3.5);\n\n\n    // Clamped spline\n    Real y1a = 0.0, y1b = 0.0;\n    f = CubicInterpolation(BEGIN(generic_x), END(generic_x), BEGIN(generic_y),\n                    CubicInterpolation::Spline, false,\n                    CubicInterpolation::FirstDerivative, y1a,\n                    CubicInterpolation::FirstDerivative, y1b);\n    f.update();\n    checkValues(\"Clamped spline\", f,\n                BEGIN(generic_x), END(generic_x), BEGIN(generic_y));\n    check1stDerivativeValue(\"Clamped spline\", f,\n                            *BEGIN(generic_x), 0.0);\n    check1stDerivativeValue(\"Clamped spline\", f,\n                            *(END(generic_x)-1), 0.0);\n    x35[0] = f(3.5);\n\n\n    // Not-a-knot spline\n    f = CubicInterpolation(BEGIN(generic_x), END(generic_x), BEGIN(generic_y),\n                           CubicInterpolation::Spline, false,\n                           CubicInterpolation::NotAKnot, Null<Real>(),\n                           CubicInterpolation::NotAKnot, Null<Real>());\n    f.update();\n    checkValues(\"Not-a-knot spline\", f,\n                BEGIN(generic_x), END(generic_x), BEGIN(generic_y));\n    checkNotAKnotCondition(\"Not-a-knot spline\", f);\n\n    x35[2] = f(3.5);\n\n    if (x35[0]>x35[1] || x35[1]>x35[2]) {\n        BOOST_ERROR(\"Spline interpolation failure\"\n                    << \"\\nat x = \" << 3.5\n                    << \"\\nclamped spline    \" << x35[0]\n                    << \"\\nnatural spline    \" << x35[1]\n                    << \"\\nnot-a-knot spline \" << x35[2]\n                    << \"\\nvalues should be in increasing order\");\n    }\n}\n\n\nvoid InterpolationTest::testSimmetricEndConditions() {\n\n    BOOST_TEST_MESSAGE(\"Testing symmetry of spline interpolation \"\n                       \"end-conditions...\");\n\n    Size n = 9;\n\n    std::vector<Real> x, y;\n    x = xRange(-1.8, 1.8, n);\n    y = gaussian(x);\n\n    // Not-a-knot spline\n    CubicInterpolation f(x.begin(), x.end(), y.begin(),\n                         CubicInterpolation::Spline, false,\n                         CubicInterpolation::NotAKnot, Null<Real>(),\n                         CubicInterpolation::NotAKnot, Null<Real>());\n    f.update();\n    checkValues(\"Not-a-knot spline\", f,\n                x.begin(), x.end(), y.begin());\n    checkNotAKnotCondition(\"Not-a-knot spline\", f);\n    checkSymmetry(\"Not-a-knot spline\", f, x[0]);\n\n\n    // MC not-a-knot spline\n    f = CubicInterpolation(x.begin(), x.end(), y.begin(),\n                           CubicInterpolation::Spline, true,\n                           CubicInterpolation::NotAKnot, Null<Real>(),\n                           CubicInterpolation::NotAKnot, Null<Real>());\n    f.update();\n    checkValues(\"MC not-a-knot spline\", f,\n                x.begin(), x.end(), y.begin());\n    checkSymmetry(\"MC not-a-knot spline\", f, x[0]);\n}\n\n\nvoid InterpolationTest::testDerivativeEndConditions() {\n\n    BOOST_TEST_MESSAGE(\"Testing derivative end-conditions \"\n                       \"for spline interpolation...\");\n\n    Size n = 4;\n\n    std::vector<Real> x, y;\n    x = xRange(-2.0, 2.0, n);\n    y = parabolic(x);\n\n    // Not-a-knot spline\n    CubicInterpolation f(x.begin(), x.end(), y.begin(),\n                         CubicInterpolation::Spline, false,\n                         CubicInterpolation::NotAKnot, Null<Real>(),\n                         CubicInterpolation::NotAKnot, Null<Real>());\n    f.update();\n    checkValues(\"Not-a-knot spline\", f,\n                x.begin(), x.end(), y.begin());\n    check1stDerivativeValue(\"Not-a-knot spline\", f,\n                            x[0], 4.0);\n    check1stDerivativeValue(\"Not-a-knot spline\", f,\n                            x[n-1], -4.0);\n    check2ndDerivativeValue(\"Not-a-knot spline\", f,\n                            x[0], -2.0);\n    check2ndDerivativeValue(\"Not-a-knot spline\", f,\n                            x[n-1], -2.0);\n\n\n    // Clamped spline\n    f = CubicInterpolation(x.begin(), x.end(), y.begin(),\n                           CubicInterpolation::Spline, false,\n                           CubicInterpolation::FirstDerivative,  4.0,\n                           CubicInterpolation::FirstDerivative, -4.0);\n    f.update();\n    checkValues(\"Clamped spline\", f,\n                x.begin(), x.end(), y.begin());\n    check1stDerivativeValue(\"Clamped spline\", f,\n                            x[0], 4.0);\n    check1stDerivativeValue(\"Clamped spline\", f,\n                            x[n-1], -4.0);\n    check2ndDerivativeValue(\"Clamped spline\", f,\n                            x[0], -2.0);\n    check2ndDerivativeValue(\"Clamped spline\", f,\n                            x[n-1], -2.0);\n\n\n    // SecondDerivative spline\n    f = CubicInterpolation(x.begin(), x.end(), y.begin(),\n                           CubicInterpolation::Spline, false,\n                           CubicInterpolation::SecondDerivative, -2.0,\n                           CubicInterpolation::SecondDerivative, -2.0);\n    f.update();\n    checkValues(\"SecondDerivative spline\", f,\n                x.begin(), x.end(), y.begin());\n    check1stDerivativeValue(\"SecondDerivative spline\", f,\n                            x[0], 4.0);\n    check1stDerivativeValue(\"SecondDerivative spline\", f,\n                            x[n-1], -4.0);\n    check2ndDerivativeValue(\"SecondDerivative spline\", f,\n                            x[0], -2.0);\n    check2ndDerivativeValue(\"SecondDerivative spline\", f,\n                            x[n-1], -2.0);\n\n    // MC Not-a-knot spline\n    f = CubicInterpolation(x.begin(), x.end(), y.begin(),\n                           CubicInterpolation::Spline, true,\n                           CubicInterpolation::NotAKnot, Null<Real>(),\n                           CubicInterpolation::NotAKnot, Null<Real>());\n    f.update();\n    checkValues(\"MC Not-a-knot spline\", f,\n                x.begin(), x.end(), y.begin());\n    check1stDerivativeValue(\"MC Not-a-knot spline\", f,\n                            x[0], 4.0);\n    check1stDerivativeValue(\"MC Not-a-knot spline\", f,\n                            x[n-1], -4.0);\n    check2ndDerivativeValue(\"MC Not-a-knot spline\", f,\n                            x[0], -2.0);\n    check2ndDerivativeValue(\"MC Not-a-knot spline\", f,\n                            x[n-1], -2.0);\n\n\n    // MC Clamped spline\n    f = CubicInterpolation(x.begin(), x.end(), y.begin(),\n                           CubicInterpolation::Spline, true,\n                           CubicInterpolation::FirstDerivative,  4.0,\n                           CubicInterpolation::FirstDerivative, -4.0);\n    f.update();\n    checkValues(\"MC Clamped spline\", f,\n                x.begin(), x.end(), y.begin());\n    check1stDerivativeValue(\"MC Clamped spline\", f,\n                            x[0], 4.0);\n    check1stDerivativeValue(\"MC Clamped spline\", f,\n                            x[n-1], -4.0);\n    check2ndDerivativeValue(\"MC Clamped spline\", f,\n                            x[0], -2.0);\n    check2ndDerivativeValue(\"MC Clamped spline\", f,\n                            x[n-1], -2.0);\n\n\n    // MC SecondDerivative spline\n    f = CubicInterpolation(x.begin(), x.end(), y.begin(),\n                           CubicInterpolation::Spline, true,\n                           CubicInterpolation::SecondDerivative, -2.0,\n                           CubicInterpolation::SecondDerivative, -2.0);\n    f.update();\n    checkValues(\"MC SecondDerivative spline\", f,\n                x.begin(), x.end(), y.begin());\n    check1stDerivativeValue(\"MC SecondDerivative spline\", f,\n                            x[0], 4.0);\n    check1stDerivativeValue(\"MC SecondDerivative spline\", f,\n                            x[n-1], -4.0);\n    check2ndDerivativeValue(\"SecondDerivative spline\", f,\n                            x[0], -2.0);\n    check2ndDerivativeValue(\"MC SecondDerivative spline\", f,\n                            x[n-1], -2.0);\n\n}\n\n\n/* See R. L. Dougherty, A. Edelman, J. M. Hyman,\n   \"Nonnegativity-, Monotonicity-, or Convexity-Preserving CubicSpline and Quintic\n   Hermite Interpolation\"\n   Mathematics Of Computation, v. 52, n. 186, April 1989, pp. 471-494.\n*/\nvoid InterpolationTest::testNonRestrictiveHymanFilter() {\n\n    BOOST_TEST_MESSAGE(\"Testing non-restrictive Hyman filter...\");\n\n    Size n = 4;\n\n    std::vector<Real> x, y;\n    x = xRange(-2.0, 2.0, n);\n    y = parabolic(x);\n    Real zero=0.0, interpolated, expected=0.0;\n\n    // MC Not-a-knot spline\n    CubicInterpolation f(x.begin(), x.end(), y.begin(),\n                         CubicInterpolation::Spline, true,\n                         CubicInterpolation::NotAKnot, Null<Real>(),\n                         CubicInterpolation::NotAKnot, Null<Real>());\n    f.update();\n    interpolated = f(zero);\n    if (std::fabs(interpolated-expected)>1e-15) {\n        BOOST_ERROR(\"MC not-a-knot spline\"\n                    << \" interpolation failed at x = \" << zero\n                    << \"\\n    interpolated value: \" << interpolated\n                    << \"\\n    expected value:     \" << expected\n                    << \"\\n    error:              \"\n                    << std::fabs(interpolated-expected));\n    }\n\n\n    // MC Clamped spline\n    f = CubicInterpolation(x.begin(), x.end(), y.begin(),\n                           CubicInterpolation::Spline, true,\n                           CubicInterpolation::FirstDerivative,  4.0,\n                           CubicInterpolation::FirstDerivative, -4.0);\n    f.update();\n    interpolated = f(zero);\n    if (std::fabs(interpolated-expected)>1e-15) {\n        BOOST_ERROR(\"MC clamped spline\"\n                    << \" interpolation failed at x = \" << zero\n                    << \"\\n    interpolated value: \" << interpolated\n                    << \"\\n    expected value:     \" << expected\n                    << \"\\n    error:              \"\n                    << std::fabs(interpolated-expected));\n    }\n\n\n    // MC SecondDerivative spline\n    f = CubicInterpolation(x.begin(), x.end(), y.begin(),\n                           CubicInterpolation::Spline, true,\n                           CubicInterpolation::SecondDerivative, -2.0,\n                           CubicInterpolation::SecondDerivative, -2.0);\n    f.update();\n    interpolated = f(zero);\n    if (std::fabs(interpolated-expected)>1e-15) {\n        BOOST_ERROR(\"MC SecondDerivative spline\"\n                    << \" interpolation failed at x = \" << zero\n                    << \"\\n    interpolated value: \" << interpolated\n                    << \"\\n    expected value:     \" << expected\n                    << \"\\n    error:              \"\n                    << std::fabs(interpolated-expected));\n    }\n\n}\n\nvoid InterpolationTest::testMultiSpline() {\n    BOOST_TEST_MESSAGE(\"Testing N-dimensional cubic spline...\");\n\n    std::vector<Size> dim(5);\n    dim[0] = 6; dim[1] = 5; dim[2] = 5; dim[3] = 6; dim[4] = 4;\n\n    std::vector<Real> args(5), offsets(5);\n    offsets[0] = 1.005; offsets[1] = 14.0; offsets[2] = 33.005;\n    offsets[3] = 35.025; offsets[4] = 19.025;\n\n    Real &s = args[0] = offsets[0],\n         &t = args[1] = offsets[1],\n         &u = args[2] = offsets[2],\n         &v = args[3] = offsets[3],\n         &w = args[4] = offsets[4];\n\n    Size i, j, k, l, m;\n\n    SplineGrid grid(5);\n\n    Real r = 0.15;\n\n    for (i = 0; i < 5; ++i) {\n        Real temp = offsets[i];\n        for (j = 0; j < dim[i]; temp += r, ++j)\n            grid[i].push_back(temp);\n    }\n\n    MultiCubicSpline<5>::data_table y5(dim);\n\n    for (i = 0; i < dim[0]; ++i)\n        for (j = 0; j < dim[1]; ++j)\n            for (k = 0; k < dim[2]; ++k)\n                for (l = 0; l < dim[3]; ++l)\n                    for (m = 0; m < dim[4]; ++m)\n                        y5[i][j][k][l][m] =\n                            multif(grid[0][i], grid[1][j], grid[2][k],\n                                   grid[3][l], grid[4][m]);\n\n    MultiCubicSpline<5> cs(grid, y5);\n    /* it would fail with\n    for (i = 0; i < dim[0]; ++i)\n        for (j = 0; j < dim[1]; ++j)\n            for (k = 0; k < dim[2]; ++k)\n                for (l = 0; l < dim[3]; ++l)\n                    for (m = 0; m < dim[4]; ++m) {\n    */\n    for (i = 1; i < dim[0]-1; ++i)\n        for (j = 1; j < dim[1]-1; ++j)\n            for (k = 1; k < dim[2]-1; ++k)\n                for (l = 1; l < dim[3]-1; ++l)\n                    for (m = 1; m < dim[4]-1; ++m) {\n                        s = grid[0][i];\n                        t = grid[1][j];\n                        u = grid[2][k];\n                        v = grid[3][l];\n                        w = grid[4][m];\n                        Real interpolated = cs(args);\n                        Real expected = y5[i][j][k][l][m];\n                        Real error = std::fabs(interpolated-expected);\n                        Real tolerance = 1e-16;\n                        if (error > tolerance) {\n                            BOOST_ERROR(\n                                \"\\n  At (\"\n                                << s << \",\" << t << \",\" << u << \",\"\n                                            << v << \",\" << w << \"):\"\n                                << \"\\n    interpolated: \" << interpolated\n                                << \"\\n    actual value: \" << expected\n                                << \"\\n       error: \" << error\n                                << \"\\n    tolerance: \" << tolerance);\n                        }\n                    }\n\n\n    unsigned long seed = 42;\n    SobolRsg rsg(5, seed);\n\n    Real tolerance = 1.7e-4;\n    // actually tested up to 2^21-1=2097151 Sobol draws\n    for (i = 0; i < 1023; ++i) {\n        const std::vector<Real>& next = rsg.nextSequence().value;\n        s = grid[0].front() + next[0]*(grid[0].back()-grid[0].front());\n        t = grid[1].front() + next[1]*(grid[1].back()-grid[1].front());\n        u = grid[2].front() + next[2]*(grid[2].back()-grid[2].front());\n        v = grid[3].front() + next[3]*(grid[3].back()-grid[3].front());\n        w = grid[4].front() + next[4]*(grid[4].back()-grid[4].front());\n        Real interpolated = cs(args), expected = multif(s, t, u, v, w);\n        Real error = std::fabs(interpolated-expected);\n        if (error > tolerance) {\n            BOOST_ERROR(\n                \"\\n  At (\"\n                << s << \",\" << t << \",\" << u << \",\" << v << \",\" << w << \"):\"\n                << \"\\n    interpolated: \" << interpolated\n                << \"\\n    actual value: \" << expected\n                << \"\\n    error:        \" << error\n                << \"\\n    tolerance:    \" << tolerance);\n        }\n    }\n}\n\nnamespace {\n\n    struct NotThrown {};\n\n}\n\nvoid InterpolationTest::testAsFunctor() {\n\n    BOOST_TEST_MESSAGE(\"Testing use of interpolations as functors...\");\n\n    const Real x[] = { 0.0, 1.0, 2.0, 3.0, 4.0 };\n    const Real y[] = { 5.0, 4.0, 3.0, 2.0, 1.0 };\n\n   Interpolation f = LinearInterpolation(BEGIN(x), END(x), BEGIN(y));\n    f.update();\n\n    const Real x2[] = { -2.0, -1.0, 0.0, 1.0, 3.0, 4.0, 5.0, 6.0, 7.0 };\n    Size N = LENGTH(x2);\n    std::vector<Real> y2(N);\n    Real tolerance = 1.0e-12;\n\n    // case 1: extrapolation not allowed\n    try {\n        std::transform(BEGIN(x2), END(x2), y2.begin(), f);\n        throw NotThrown();\n    }\n    catch (Error&) {\n        // as expected; do nothing\n    }\n    catch (NotThrown&) {\n        QL_FAIL(\"failed to throw exception when trying to extrapolate\");\n    }\n\n    // case 2: enable extrapolation\n    f.enableExtrapolation();\n    y2 = std::vector<Real>(N);\n    std::transform(BEGIN(x2), END(x2), y2.begin(), f);\n    for (Size i=0; i<N; i++) {\n        Real expected = 5.0-x2[i];\n        if (std::fabs(y2[i]-expected) > tolerance)\n            BOOST_ERROR(\n                \"failed to reproduce \" << io::ordinal(i+1) << \" expected datum\"\n                << QL_FIXED\n                << \"\\n    expected:   \" << expected\n                << \"\\n    calculated: \" << y2[i]\n                << QL_SCIENTIFIC\n                << \"\\n    error:      \" << std::fabs(y2[i]-expected));\n    }\n}\n\n\nvoid InterpolationTest::testBackwardFlat() {\n\n    BOOST_TEST_MESSAGE(\"Testing backward-flat interpolation...\");\n\n    const Real x[] = { 0.0, 1.0, 2.0, 3.0, 4.0 };\n    const Real y[] = { 5.0, 4.0, 3.0, 2.0, 1.0 };\n\n    Interpolation f = BackwardFlatInterpolation(BEGIN(x), END(x), BEGIN(y));\n    f.update();\n\n    Size N = LENGTH(x);\n    Size i;\n    Real tolerance = 1.0e-12;\n\n    // at original points\n    for (i=0; i<N; i++) {\n        Real p = x[i];\n        Real calculated = f(p);\n        Real expected = y[i];\n        if (std::fabs(expected-calculated) > tolerance)\n            BOOST_ERROR(\n                \"failed to reproduce \" << io::ordinal(i+1) << \" datum\"\n                << QL_FIXED\n                << \"\\n    expected:   \" << expected\n                << \"\\n    calculated: \" << calculated\n                << QL_SCIENTIFIC\n                << \"\\n    error:      \" << std::fabs(calculated-expected));\n    }\n\n    // at middle points\n    for (i=0; i<N-1; i++) {\n        Real p = (x[i]+x[i+1])/2;\n        Real calculated = f(p);\n        Real expected = y[i+1];\n        if (std::fabs(expected-calculated) > tolerance)\n            BOOST_ERROR(\n                \"failed to interpolate correctly at \" << p\n                << QL_FIXED\n                << \"\\n    expected:   \" << expected\n                << \"\\n    calculated: \" << calculated\n                << QL_SCIENTIFIC\n                << \"\\n    error:      \" << std::fabs(calculated-expected));\n    }\n\n    // outside the original range\n    f.enableExtrapolation();\n\n    Real p = x[0] - 0.5;\n    Real calculated = f(p);\n    Real expected = y[0];\n    if (std::fabs(expected-calculated) > tolerance)\n        BOOST_ERROR(\n            \"failed to extrapolate correctly at \" << p\n            << QL_FIXED\n            << \"\\n    expected:   \" << expected\n            << \"\\n    calculated: \" << calculated\n            << QL_SCIENTIFIC\n            << \"\\n    error:      \" << std::fabs(calculated-expected));\n\n    p = x[N-1] + 0.5;\n    calculated = f(p);\n    expected = y[N-1];\n    if (std::fabs(expected-calculated) > tolerance)\n        BOOST_ERROR(\n            \"failed to extrapolate correctly at \" << p\n            << QL_FIXED\n            << \"\\n    expected:   \" << expected\n            << \"\\n    calculated: \" << calculated\n            << QL_SCIENTIFIC\n            << \"\\n    error:      \" << std::fabs(calculated-expected));\n\n    // primitive at original points\n    calculated = f.primitive(x[0]);\n    expected = 0.0;\n    if (std::fabs(expected-calculated) > tolerance)\n        BOOST_ERROR(\n            \"failed to calculate primitive at \" << x[0]\n            << QL_FIXED\n            << \"\\n    expected:   \" << expected\n            << \"\\n    calculated: \" << calculated\n            << QL_SCIENTIFIC\n            << \"\\n    error:      \" << std::fabs(calculated-expected));\n\n    Real sum = 0.0;\n    for (i=1; i<N; i++) {\n        sum += (x[i]-x[i-1])*y[i];\n        Real calculated = f.primitive(x[i]);\n        Real expected = sum;\n        if (std::fabs(expected-calculated) > tolerance)\n            BOOST_ERROR(\n                \"failed to calculate primitive at \" << x[i]\n                << QL_FIXED\n                << \"\\n    expected:   \" << expected\n                << \"\\n    calculated: \" << calculated\n                << QL_SCIENTIFIC\n                << \"\\n    error:      \" << std::fabs(calculated-expected));\n    }\n\n    // primitive at middle points\n    sum = 0.0;\n    for (i=0; i<N-1; i++) {\n        Real p = (x[i]+x[i+1])/2;\n        sum += (x[i+1]-x[i])*y[i+1]/2;\n        Real calculated = f.primitive(p);\n        Real expected = sum;\n        sum += (x[i+1]-x[i])*y[i+1]/2;\n        if (std::fabs(expected-calculated) > tolerance)\n            BOOST_ERROR(\n                \"failed to calculate primitive at \" << x[i]\n                << QL_FIXED\n                << \"\\n    expected:   \" << expected\n                << \"\\n    calculated: \" << calculated\n                << QL_SCIENTIFIC\n                << \"\\n    error:      \" << std::fabs(calculated-expected));\n    }\n\n}\n\nvoid InterpolationTest::testForwardFlat() {\n\n    BOOST_TEST_MESSAGE(\"Testing forward-flat interpolation...\");\n\n    const Real x[] = { 0.0, 1.0, 2.0, 3.0, 4.0 };\n    const Real y[] = { 5.0, 4.0, 3.0, 2.0, 1.0 };\n\n    Interpolation f = ForwardFlatInterpolation(BEGIN(x), END(x), BEGIN(y));\n    f.update();\n\n    Size N = LENGTH(x);\n    Size i;\n    Real tolerance = 1.0e-12;\n\n    // at original points\n    for (i=0; i<N; i++) {\n        Real p = x[i];\n        Real calculated = f(p);\n        Real expected = y[i];\n        if (std::fabs(expected-calculated) > tolerance)\n            BOOST_ERROR(\n                \"failed to reproduce \" << io::ordinal(i+1) << \" datum\"\n                << QL_FIXED\n                << \"\\n    expected:   \" << expected\n                << \"\\n    calculated: \" << calculated\n                << QL_SCIENTIFIC\n                << \"\\n    error:      \" << std::fabs(calculated-expected));\n    }\n\n    // at middle points\n    for (i=0; i<N-1; i++) {\n        Real p = (x[i]+x[i+1])/2;\n        Real calculated = f(p);\n        Real expected = y[i];\n        if (std::fabs(expected-calculated) > tolerance)\n            BOOST_ERROR(\n                \"failed to interpolate correctly at \" << p\n                << QL_FIXED\n                << \"\\n    expected:   \" << expected\n                << \"\\n    calculated: \" << calculated\n                << QL_SCIENTIFIC\n                << \"\\n    error:      \" << std::fabs(calculated-expected));\n    }\n\n    // outside the original range\n    f.enableExtrapolation();\n\n    Real p = x[0] - 0.5;\n    Real calculated = f(p);\n    Real expected = y[0];\n    if (std::fabs(expected-calculated) > tolerance)\n        BOOST_ERROR(\n            \"failed to extrapolate correctly at \" << p\n            << QL_FIXED\n            << \"\\n    expected:   \" << expected\n            << \"\\n    calculated: \" << calculated\n            << QL_SCIENTIFIC\n            << \"\\n    error:      \" << std::fabs(calculated-expected));\n\n    p = x[N-1] + 0.5;\n    calculated = f(p);\n    expected = y[N-1];\n    if (std::fabs(expected-calculated) > tolerance)\n        BOOST_ERROR(\n            \"failed to extrapolate correctly at \" << p\n            << QL_FIXED\n            << \"\\n    expected:   \" << expected\n            << \"\\n    calculated: \" << calculated\n            << QL_SCIENTIFIC\n            << \"\\n    error:      \" << std::fabs(calculated-expected));\n\n    // primitive at original points\n    calculated = f.primitive(x[0]);\n    expected = 0.0;\n    if (std::fabs(expected-calculated) > tolerance)\n        BOOST_ERROR(\n            \"failed to calculate primitive at \" << x[0]\n            << QL_FIXED\n            << \"\\n    expected:   \" << expected\n            << \"\\n    calculated: \" << calculated\n            << QL_SCIENTIFIC\n            << \"\\n    error:      \" << std::fabs(calculated-expected));\n\n    Real sum = 0.0;\n    for (i=1; i<N; i++) {\n        sum += (x[i]-x[i-1])*y[i-1];\n        Real calculated = f.primitive(x[i]);\n        Real expected = sum;\n        if (std::fabs(expected-calculated) > tolerance)\n            BOOST_ERROR(\n                \"failed to calculate primitive at \" << x[i]\n                << QL_FIXED\n                << \"\\n    expected:   \" << expected\n                << \"\\n    calculated: \" << calculated\n                << QL_SCIENTIFIC\n                << \"\\n    error:      \" << std::fabs(calculated-expected));\n    }\n\n    // primitive at middle points\n    sum = 0.0;\n    for (i=0; i<N-1; i++) {\n        Real p = (x[i]+x[i+1])/2;\n        sum += (x[i+1]-x[i])*y[i]/2;\n        Real calculated = f.primitive(p);\n        Real expected = sum;\n        sum += (x[i+1]-x[i])*y[i]/2;\n        if (std::fabs(expected-calculated) > tolerance)\n            BOOST_ERROR(\n                \"failed to calculate primitive at \" << p\n                << QL_FIXED\n                << \"\\n    expected:   \" << expected\n                << \"\\n    calculated: \" << calculated\n                << QL_SCIENTIFIC\n                << \"\\n    error:      \" << std::fabs(calculated-expected));\n    }\n}\n\nvoid InterpolationTest::testSabrInterpolation(){\n\n    BOOST_TEST_MESSAGE(\"Testing Sabr interpolation...\");\n\n    // Test SABR function against input volatilities\n    Real tolerance = 1.0e-12;\n    std::vector<Real> strikes(31);\n    std::vector<Real> volatilities(31);\n    // input strikes\n    strikes[0] = 0.03 ; strikes[1] = 0.032 ; strikes[2] = 0.034 ;\n    strikes[3] = 0.036 ; strikes[4] = 0.038 ; strikes[5] = 0.04 ;\n    strikes[6] = 0.042 ; strikes[7] = 0.044 ; strikes[8] = 0.046 ;\n    strikes[9] = 0.048 ; strikes[10] = 0.05 ; strikes[11] = 0.052 ;\n    strikes[12] = 0.054 ; strikes[13] = 0.056 ; strikes[14] = 0.058 ;\n    strikes[15] = 0.06 ; strikes[16] = 0.062 ; strikes[17] = 0.064 ;\n    strikes[18] = 0.066 ; strikes[19] = 0.068 ; strikes[20] = 0.07 ;\n    strikes[21] = 0.072 ; strikes[22] = 0.074 ; strikes[23] = 0.076 ;\n    strikes[24] = 0.078 ; strikes[25] = 0.08 ; strikes[26] = 0.082 ;\n    strikes[27] = 0.084 ; strikes[28] = 0.086 ; strikes[29] = 0.088;\n    strikes[30] = 0.09;\n    // input volatilities\n    volatilities[0] = 1.16725837321531 ; volatilities[1] = 1.15226075991385 ; volatilities[2] = 1.13829711098834 ;\n    volatilities[3] = 1.12524190877505 ; volatilities[4] = 1.11299079244474 ; volatilities[5] = 1.10145609357162 ;\n    volatilities[6] = 1.09056348513411 ; volatilities[7] = 1.08024942745106 ; volatilities[8] = 1.07045919457758 ;\n    volatilities[9] = 1.06114533019077 ; volatilities[10] = 1.05226642581503 ; volatilities[11] = 1.04378614411707 ;\n    volatilities[12] = 1.03567243073732 ; volatilities[13] = 1.0278968727451 ; volatilities[14] = 1.02043417226345 ;\n    volatilities[15] = 1.01326171139321 ; volatilities[16] = 1.00635919013311 ; volatilities[17] = 0.999708323124949 ;\n    volatilities[18] = 0.993292584155381 ; volatilities[19] = 0.987096989695393 ; volatilities[20] = 0.98110791455717 ;\n    volatilities[21] = 0.975312934134512 ; volatilities[22] = 0.969700688771689 ; volatilities[23] = 0.964260766651027;\n    volatilities[24] = 0.958983602256592 ; volatilities[25] = 0.953860388001395 ; volatilities[26] = 0.948882997029509 ;\n    volatilities[27] = 0.944043915545469 ; volatilities[28] = 0.939336183299237 ; volatilities[29] = 0.934753341079515 ;\n    volatilities[30] = 0.930289384251337;\n\n    Time expiry = 1.0;\n    Real forward = 0.039;\n    // input SABR coefficients (corresponding to the vols above)\n    Real initialAlpha = 0.3;\n    Real initialBeta = 0.6;\n    Real initialNu = 0.02;\n    Real initialRho = 0.01;\n    // calculate SABR vols and compare with input vols\n    for(Size i=0; i< strikes.size(); i++){\n        Real calculatedVol = sabrVolatility(strikes[i], forward, expiry,\n                                            initialAlpha, initialBeta,\n                                            initialNu, initialRho);\n        if (std::fabs(volatilities[i]-calculatedVol) > tolerance)\n        BOOST_ERROR(\n            \"failed to calculate Sabr function at strike \" << strikes[i]\n            << \"\\n    expected:   \" << volatilities[i]\n            << \"\\n    calculated: \" << calculatedVol\n            << \"\\n    error:      \" << std::fabs(calculatedVol-volatilities[i]));\n    }\n\n    // Test SABR calibration against input parameters\n    // Use default values (but not null, since then parameters\n    // will then not be fixed during optimization, see the\n    // interpolation constructor, thus rendering the test cases\n    // with fixed parameters non-sensical)\n    Real alphaGuess = std::sqrt(0.2);\n    Real betaGuess = 0.5;\n    Real nuGuess = std::sqrt(0.4);\n    Real rhoGuess = 0.0;\n\n    const bool vegaWeighted[]= {true, false};\n    const bool isAlphaFixed[]= {true, false};\n    const bool isBetaFixed[]= {true, false};\n    const bool isNuFixed[]= {true, false};\n    const bool isRhoFixed[]= {true, false};\n\n    Real calibrationTolerance = 5.0e-8;\n    // initialize optimization methods\n    std::vector<boost::shared_ptr<OptimizationMethod> > methods_;\n    methods_.push_back( boost::shared_ptr<OptimizationMethod>(new Simplex(0.01)));\n    methods_.push_back( boost::shared_ptr<OptimizationMethod>(new LevenbergMarquardt(1e-8, 1e-8, 1e-8)));\n    // Initialize end criteria\n    boost::shared_ptr<EndCriteria> endCriteria(new\n                  EndCriteria(100000, 100, 1e-8, 1e-8, 1e-8));\n    // Test looping over all possibilities\n    for (Size j=0; j<methods_.size(); ++j) {\n      for (Size i=0; i<LENGTH(vegaWeighted); ++i) {\n        for (Size k_a=0; k_a<LENGTH(isAlphaFixed); ++k_a) {\n          for (Size k_b=0; k_b<LENGTH(isBetaFixed); ++k_b) {\n            for (Size k_n=0; k_n<LENGTH(isNuFixed); ++k_n) {\n              for (Size k_r=0; k_r<LENGTH(isRhoFixed); ++k_r) {\n                  // to meet the tough calibration tolerance we need to lower the default\n                  // error threshold for accepting a calibration (to be more specific, some\n                  // of the new test cases arising from fixing a subset of the model's\n                  // parameters do not calibrate with the desired error using the initial\n                  // guess (i.e. optimization runs into a local minimum) - then a series of\n                  // random start values for optimization is chosen until our tight custom\n                  // error threshold is satisfied.\n                  SABRInterpolation sabrInterpolation(\n                      strikes.begin(), strikes.end(), volatilities.begin(),\n                      expiry, forward, isAlphaFixed[k_a] ? initialAlpha : alphaGuess,\n                      isBetaFixed[k_b] ? initialBeta : betaGuess,\n                      isNuFixed[k_n] ? initialNu : nuGuess,\n                      isRhoFixed[k_r] ? initialRho : rhoGuess, isAlphaFixed[k_a],\n                      isBetaFixed[k_b], isNuFixed[k_n], isRhoFixed[k_r],\n                      vegaWeighted[i], endCriteria, methods_[j], 1E-10);\n                  sabrInterpolation.update();\n\n                // Recover SABR calibration parameters\n                bool failed = false;\n                Real calibratedAlpha = sabrInterpolation.alpha();\n                Real calibratedBeta = sabrInterpolation.beta();\n                Real calibratedNu = sabrInterpolation.nu();\n                Real calibratedRho = sabrInterpolation.rho();\n                Real error;\n\n                // compare results: alpha\n                error = std::fabs(initialAlpha-calibratedAlpha);\n                if (error > calibrationTolerance) {\n                    BOOST_ERROR(\"\\nfailed to calibrate alpha Sabr parameter:\" <<\n                                \"\\n    expected:        \" << initialAlpha <<\n                                \"\\n    calibrated:      \" << calibratedAlpha <<\n                                \"\\n    error:           \" << error);\n                    failed = true;\n                }\n                // Beta\n                error = std::fabs(initialBeta-calibratedBeta);\n                if (error > calibrationTolerance) {\n                    BOOST_ERROR(\"\\nfailed to calibrate beta Sabr parameter:\" <<\n                                \"\\n    expected:        \" << initialBeta <<\n                                \"\\n    calibrated:      \" << calibratedBeta <<\n                                \"\\n    error:           \" << error);\n                    failed = true;\n                }\n                // Nu\n                error = std::fabs(initialNu-calibratedNu);\n                if (error > calibrationTolerance) {\n                    BOOST_ERROR(\"\\nfailed to calibrate nu Sabr parameter:\" <<\n                                \"\\n    expected:        \" << initialNu <<\n                                \"\\n    calibrated:      \" << calibratedNu <<\n                                \"\\n    error:           \" << error);\n                    failed = true;\n                }\n                // Rho\n                error = std::fabs(initialRho-calibratedRho);\n                if (error > calibrationTolerance) {\n                    BOOST_ERROR(\"\\nfailed to calibrate rho Sabr parameter:\" <<\n                                \"\\n    expected:        \" << initialRho <<\n                                \"\\n    calibrated:      \" << calibratedRho <<\n                                \"\\n    error:           \" << error);\n                    failed = true;\n                }\n\n                if (failed)\n                    BOOST_FAIL(\"\\nSabr calibration failure:\" <<\n                               \"\\n    isAlphaFixed:    \" << isAlphaFixed[k_a] <<\n                               \"\\n    isBetaFixed:     \" << isBetaFixed[k_b] <<\n                               \"\\n    isNuFixed:       \" << isNuFixed[k_n] <<\n                               \"\\n    isRhoFixed:      \" << isRhoFixed[k_r] <<\n                               \"\\n    vegaWeighted[i]: \" << vegaWeighted[i]);\n\n              }\n            }\n          }\n        }\n      }\n    }\n}\n\n\nvoid InterpolationTest::testKernelInterpolation() {\n\n    BOOST_TEST_MESSAGE(\"Testing kernel 1D interpolation...\");\n\n    std::vector<Real> deltaGrid(5); // x-values, here delta in FX\n    deltaGrid[0]=0.10; deltaGrid[1]=0.25; deltaGrid[2]=0.50;\n    deltaGrid[3]=0.75; deltaGrid[4]=0.90;\n\n    std::vector<Real> yd1(deltaGrid.size()); // test y-values 1\n    yd1[0]=11.275; yd1[1]=11.125; yd1[2]=11.250;\n    yd1[3]=11.825; yd1[4]=12.625;\n\n    std::vector<Real> yd2(deltaGrid.size()); // test y-values 2\n    yd2[0]=16.025; yd2[1]=13.450; yd2[2]=11.350;\n    yd2[3]=10.150; yd2[4]=10.075;\n\n    std::vector<Real> yd3(deltaGrid.size()); // test y-values 3\n    yd3[0]=10.3000; yd3[1]=9.6375; yd3[2]=9.2000;\n    yd3[3]=9.1125; yd3[4]=9.4000;\n\n    std::vector<std::vector<Real> > yd;\n    yd.push_back(yd1);\n    yd.push_back(yd2);\n    yd.push_back(yd3);\n\n    std::vector<Real> lambdaVec(5);\n    lambdaVec[0]=0.05; lambdaVec[1]=0.50; lambdaVec[2]=0.75;\n    lambdaVec[3]=1.65; lambdaVec[4]=2.55;\n\n    Real tolerance = 2.0e-5;\n\n    Real expectedVal;\n    Real calcVal;\n\n    // Check that y-values at knots are exactly the feeded y-values,\n    // irrespective of kernel parameters\n    for (Size i=0; i<lambdaVec.size(); ++i) {\n        GaussianKernel myKernel(0,lambdaVec[i]);\n\n        for (Size j=0; j<yd.size(); ++j) {\n\n            std::vector<Real> currY = yd[j];\n            KernelInterpolation f(deltaGrid.begin(), deltaGrid.end(),\n                                  currY.begin(), myKernel);\n            f.update();\n\n            for (Size dIt=0; dIt< deltaGrid.size(); ++dIt) {\n                expectedVal=currY[dIt];\n                calcVal=f(deltaGrid[dIt]);\n\n                if (std::fabs(expectedVal-calcVal)>tolerance) {\n\n                    BOOST_ERROR(\"Kernel interpolation failed at x = \"\n                                << deltaGrid[dIt]\n                                << QL_SCIENTIFIC\n                                << \"\\n    interpolated value: \" << calcVal\n                                << \"\\n    expected value:     \" << expectedVal\n                                << \"\\n    error:              \"\n                                << std::fabs(expectedVal-calcVal));\n                }\n            }\n        }\n    }\n\n    std::vector<Real> testDeltaGrid(deltaGrid.size());\n    testDeltaGrid[0]=0.121; testDeltaGrid[1]=0.279; testDeltaGrid[2]=0.678;\n    testDeltaGrid[3]=0.790; testDeltaGrid[4]=0.980;\n\n    // Gaussian Kernel values for testDeltaGrid with a standard\n    // deviation of 2.05 (the value is arbitrary.)  Source: parrallel\n    // implementation in R, no literature sources found\n\n    std::vector<Real> ytd1(testDeltaGrid.size());\n    ytd1[0]=11.23847; ytd1[1]=11.12003; ytd1[2]=11.58932;\n    ytd1[3]=11.99168; ytd1[4]=13.29650;\n\n    std::vector<Real> ytd2(testDeltaGrid.size());\n    ytd2[0]=15.55922; ytd2[1]=13.11088; ytd2[2]=10.41615;\n    ytd2[3]=10.05153; ytd2[4]=10.50741;\n\n    std::vector<Real> ytd3(testDeltaGrid.size());\n    ytd3[0]= 10.17473; ytd3[1]= 9.557842; ytd3[2]= 9.09339;\n    ytd3[3]= 9.149687; ytd3[4]= 9.779971;\n\n    std::vector<std::vector<Real> > ytd;\n    ytd.push_back(ytd1);\n    ytd.push_back(ytd2);\n    ytd.push_back(ytd3);\n\n    GaussianKernel myKernel(0,2.05);\n\n    for (Size j=0; j< ytd.size(); ++j) {\n        std::vector<Real> currY=yd[j];\n        std::vector<Real> currTY=ytd[j];\n\n        // Build interpolation according to original grid + y-values\n        KernelInterpolation f(deltaGrid.begin(), deltaGrid.end(),\n                              currY.begin(), myKernel);\n        f.update();\n\n        // test values at test Grid\n        for (Size dIt=0; dIt< testDeltaGrid.size(); ++dIt) {\n\n            expectedVal=currTY[dIt];\n            f.enableExtrapolation();// allow extrapolation\n\n            calcVal=f(testDeltaGrid[dIt]);\n            if (std::fabs(expectedVal-calcVal)>tolerance) {\n\n                BOOST_ERROR(\"Kernel interpolation failed at x = \"\n                            << deltaGrid[dIt]\n                            << QL_SCIENTIFIC\n                            << \"\\n    interpolated value: \" << calcVal\n                            << \"\\n    expected value:     \" << expectedVal\n                            << \"\\n    error:              \"\n                            << std::fabs(expectedVal-calcVal));\n            }\n        }\n    }\n}\n\n\nvoid InterpolationTest::testKernelInterpolation2D(){\n\n    // No test values known from the literature.\n    // Testing for consistency of input output data\n    // at the nodes\n\n    BOOST_TEST_MESSAGE(\"Testing kernel 2D interpolation...\");\n\n    Real mean=0.0, var=0.18;\n    GaussianKernel myKernel(mean,var);\n\n    std::vector<Real> xVec(10);\n    xVec[0] = 0.10; xVec[1] = 0.20; xVec[2] = 0.30; xVec[3] = 0.40;\n    xVec[4] = 0.50; xVec[5] = 0.60; xVec[6] = 0.70; xVec[7] = 0.80;\n    xVec[8] = 0.90; xVec[9] = 1.00;\n\n    std::vector<Real> yVec(3);\n    yVec[0] = 1.0; yVec[1] = 2.0; yVec[2] = 3.5;\n\n    Matrix M(xVec.size(),yVec.size());\n\n    M[0][0]=0.25; M[1][0]=0.24; M[2][0]=0.23; M[3][0]=0.20; M[4][0]=0.19;\n    M[5][0]=0.20; M[6][0]=0.21; M[7][0]=0.22; M[8][0]=0.26; M[9][0]=0.29;\n\n    M[0][1]=0.27; M[1][1]=0.26; M[2][1]=0.25; M[3][1]=0.22; M[4][1]=0.21;\n    M[5][1]=0.22; M[6][1]=0.23; M[7][1]=0.24; M[8][1]=0.28; M[9][1]=0.31;\n\n    M[0][2]=0.21; M[1][2]=0.22; M[2][2]=0.27; M[3][2]=0.29; M[4][2]=0.24;\n    M[5][2]=0.28; M[6][2]=0.25; M[7][2]=0.22; M[8][2]=0.29; M[9][2]=0.30;\n\n    KernelInterpolation2D kernel2D(xVec.begin(),xVec.end(),\n                                   yVec.begin(),yVec.end(),M,myKernel);\n\n    Real calcVal,expectedVal;\n    Real tolerance = 1.0e-10;\n\n    for(Size i=0;i<M.rows();++i){\n        for(Size j=0;j<M.columns();++j){\n\n            calcVal=kernel2D(xVec[i],yVec[j]);\n            expectedVal=M[i][j];\n\n            if(std::fabs(expectedVal-calcVal)>tolerance){\n\n                BOOST_ERROR(\"2D Kernel interpolation failed at x = \" << xVec[i]\n                            << \", y = \" << yVec[j]\n                            << \"\\n    interpolated value: \" << calcVal\n                            << \"\\n    expected value:     \" << expectedVal\n                            << \"\\n    error:              \"\n                            << std::fabs(expectedVal-calcVal));\n            }\n        }\n    }\n\n    // alternative data set\n    std::vector<Real> xVec1(4);\n    xVec1[0] = 80.0; xVec1[1] = 90.0; xVec1[2] = 100.0; xVec1[3] = 110.0;\n\n    std::vector<Real> yVec1(8);\n    yVec1[0] = 0.5; yVec1[1] = 0.7; yVec1[2] = 1.0; yVec1[3] = 2.0;\n    yVec1[4] = 3.5; yVec1[5] = 4.5; yVec1[6] = 5.5; yVec1[7] = 6.5;\n\n    Matrix M1(xVec1.size(),yVec1.size());\n    M1[0][0]=10.25; M1[1][0]=12.24;M1[2][0]=14.23;M1[3][0]=17.20;\n    M1[0][1]=12.25; M1[1][1]=15.24;M1[2][1]=16.23;M1[3][1]=16.20;\n    M1[0][2]=12.25; M1[1][2]=13.24;M1[2][2]=13.23;M1[3][2]=17.20;\n    M1[0][3]=13.25; M1[1][3]=15.24;M1[2][3]=12.23;M1[3][3]=19.20;\n    M1[0][4]=14.25; M1[1][4]=16.24;M1[2][4]=13.23;M1[3][4]=12.20;\n    M1[0][5]=15.25; M1[1][5]=17.24;M1[2][5]=14.23;M1[3][5]=12.20;\n    M1[0][6]=16.25; M1[1][6]=13.24;M1[2][6]=15.23;M1[3][6]=10.20;\n    M1[0][7]=14.25; M1[1][7]=14.24;M1[2][7]=16.23;M1[3][7]=19.20;\n\n    // test with function pointer\n    KernelInterpolation2D kernel2DEp(xVec1.begin(),xVec1.end(),\n                                     yVec1.begin(),yVec1.end(),M1,\n                                     &epanechnikovKernel);\n\n    for(Size i=0;i<M1.rows();++i){\n        for(Size j=0;j<M1.columns();++j){\n\n            calcVal=kernel2DEp(xVec1[i],yVec1[j]);\n            expectedVal=M1[i][j];\n\n            if(std::fabs(expectedVal-calcVal)>tolerance){\n\n                BOOST_ERROR(\"2D Epanechnkikov Kernel interpolation failed at x = \" << xVec1[i]\n                            << \", y = \" << yVec1[j]\n                            << \"\\n    interpolated value: \" << calcVal\n                            << \"\\n    expected value:     \" << expectedVal\n                            << \"\\n    error:              \"\n                            << std::fabs(expectedVal-calcVal));\n            }\n        }\n    }\n\n    // test updating mechanism by changing initial variables\n    xVec1[0] = 60.0; xVec1[1] = 95.0; xVec1[2] = 105.0; xVec1[3] = 135.0;\n\n    yVec1[0] = 12.5; yVec1[1] = 13.7; yVec1[2] = 15.0; yVec1[3] = 19.0;\n    yVec1[4] = 26.5; yVec1[5] = 27.5; yVec1[6] = 29.2; yVec1[7] = 36.5;\n\n    kernel2DEp.update();\n\n    for(Size i=0;i<M1.rows();++i){\n        for(Size j=0;j<M1.columns();++j){\n\n            calcVal=kernel2DEp(xVec1[i],yVec1[j]);\n            expectedVal=M1[i][j];\n\n            if(std::fabs(expectedVal-calcVal)>tolerance){\n\n                BOOST_ERROR(\"2D Epanechnkikov Kernel updated interpolation failed at x = \" << xVec1[i]\n                            << \", y = \" << yVec1[j]\n                            << \"\\n    interpolated value: \" << calcVal\n                            << \"\\n    expected value:     \" << expectedVal\n                            << \"\\n    error:              \"\n                            << std::fabs(expectedVal-calcVal));\n            }\n        }\n    }\n}\n\n\nvoid InterpolationTest::testBicubicDerivatives() {\n    BOOST_TEST_MESSAGE(\"Testing bicubic spline derivatives...\");\n\n    std::vector<Real> x(100), y(100);\n    for (Size i=0; i < 100; ++i) {\n        x[i] = y[i] = i/20.0;\n    }\n\n    Matrix f(100, 100);\n    for (Size i=0; i < 100; ++i)\n        for (Size j=0; j < 100; ++j)\n            f[i][j] = y[i]/10*std::sin(x[j])+std::cos(y[i]);\n\n    const Real tol=0.005;\n    BicubicSpline spline(x.begin(), x.end(), y.begin(), y.end(), f);\n\n    for (Size i=5; i < 95; i+=10) {\n        for (Size j=5; j < 95; j+=10) {\n            Real f_x  = spline.derivativeX(x[j],y[i]);\n            Real f_xx = spline.secondDerivativeX(x[j],y[i]);\n            Real f_y  = spline.derivativeY(x[j],y[i]);\n            Real f_yy = spline.secondDerivativeY(x[j],y[i]);\n            Real f_xy = spline.derivativeXY(x[j],y[i]);\n\n            if (std::fabs(f_x - y[i]/10*std::cos(x[j])) > tol) {\n                BOOST_ERROR(\"Failed to reproduce f_x\");\n            }\n            if (std::fabs(f_xx + y[i]/10*std::sin(x[j])) > tol) {\n                BOOST_ERROR(\"Failed to reproduce f_xx\");\n            }\n            if (std::fabs(f_y - (std::sin(x[j])/10-std::sin(y[i]))) > tol) {\n                BOOST_ERROR(\"Failed to reproduce f_y\");\n            }\n            if (std::fabs(f_yy + std::cos(y[i])) > tol) {\n                BOOST_ERROR(\"Failed to reproduce f_yy\");\n            }\n            if (std::fabs(f_xy - std::cos(x[j])/10) > tol) {\n                BOOST_ERROR(\"Failed to reproduce f_xy\");\n            }\n        }\n    }\n}\n\n\nvoid InterpolationTest::testBicubicUpdate() {\n    BOOST_TEST_MESSAGE(\"Testing that bicubic splines actually update...\");\n\n    Size N=6;\n    std::vector<Real> x(N), y(N);\n    for (Size i=0; i < N; ++i) {\n        x[i] = y[i] = i*0.2;\n    }\n\n    Matrix f(N, N);\n    for (Size i=0; i < N; ++i)\n        for (Size j=0; j < N; ++j)\n            f[i][j] = x[j]*(x[j] + y[i]);\n\n    BicubicSpline spline(x.begin(), x.end(), y.begin(), y.end(), f);\n\n    Real old_result = spline(x[2]+0.1, y[4]);\n\n    // modify input matrix and update.\n    f[4][3] += 1.0;\n    spline.update();\n\n    Real new_result = spline(x[2]+0.1, y[4]);\n    if (std::fabs(old_result-new_result) < 0.5) {\n        BOOST_ERROR(\"Failed to update bicubic spline\");\n    }\n}\n\nnamespace {\n    Real f(Real h) {\n        return std::pow( 1.0 + h, 1/h);\n    }\n}\n\nvoid InterpolationTest::testRichardsonExtrapolation() {\n    BOOST_TEST_MESSAGE(\"Testing Richardson extrapolation...\");\n\n    /* example taken from\n     * http://www.ipvs.uni-stuttgart.de/abteilungen/bv/lehre/\n     *      lehrveranstaltungen/vorlesungen/WS0910/\n     *      NSG_termine/dateien/Richardson.pdf\n     */\n\n    const Real stepSize = 0.1;\n    const Real orderOfConvergence = 1.0;\n    const RichardsonExtrapolation extrap(f, stepSize, orderOfConvergence);\n\n\n    Real tol = 0.00002;\n    Real expected = 2.71285;\n\n    const Real scalingFactor = 2.0;\n    Real calculated = extrap(scalingFactor);\n\n    if (std::fabs(expected-calculated) > tol) {\n        BOOST_ERROR(\"failed to reproduce Richardson extrapolation\");\n    }\n\n    calculated = extrap();\n    if (std::fabs(expected-calculated) > tol) {\n        BOOST_ERROR(\"failed to reproduce Richardson extrapolation\");\n    }\n\n    expected = 2.721376;\n    const Real scalingFactor2 = 4.0;\n    calculated = extrap(scalingFactor2, scalingFactor);\n\n    if (std::fabs(expected-calculated) > tol) {\n        BOOST_ERROR(\"failed to reproduce Richardson extrapolation\");\n    }\n}\n\nvoid InterpolationTest::testNoArbSabrInterpolation(){\n\n    BOOST_TEST_MESSAGE(\"Testing no-arbitrage Sabr interpolation...\");\n\n    // Test SABR function against input volatilities\n    Real tolerance = 1.0e-12;\n    std::vector<Real> strikes(31);\n    std::vector<Real> volatilities(31), volatilities2(31);\n    // input strikes\n    strikes[0] = 0.03 ; strikes[1] = 0.032 ; strikes[2] = 0.034 ;\n    strikes[3] = 0.036 ; strikes[4] = 0.038 ; strikes[5] = 0.04 ;\n    strikes[6] = 0.042 ; strikes[7] = 0.044 ; strikes[8] = 0.046 ;\n    strikes[9] = 0.048 ; strikes[10] = 0.05 ; strikes[11] = 0.052 ;\n    strikes[12] = 0.054 ; strikes[13] = 0.056 ; strikes[14] = 0.058 ;\n    strikes[15] = 0.06 ; strikes[16] = 0.062 ; strikes[17] = 0.064 ;\n    strikes[18] = 0.066 ; strikes[19] = 0.068 ; strikes[20] = 0.07 ;\n    strikes[21] = 0.072 ; strikes[22] = 0.074 ; strikes[23] = 0.076 ;\n    strikes[24] = 0.078 ; strikes[25] = 0.08 ; strikes[26] = 0.082 ;\n    strikes[27] = 0.084 ; strikes[28] = 0.086 ; strikes[29] = 0.088;\n    strikes[30] = 0.09;\n    // input volatilities for noarb sabr (other than above\n    // alpha is 0.2 here due to the restriction sigmaI <= 1.0 !)\n    volatilities[0] = 0.773729077752926;\n    volatilities[1] = 0.763916242454194;\n    volatilities[2] = 0.754773878663612;\n    volatilities[3] = 0.746222305031368;\n    volatilities[4] = 0.738193023523582;\n    volatilities[5] = 0.730629785825930;\n    volatilities[6] = 0.723484825471685;\n    volatilities[7] = 0.716716812668892;\n    volatilities[8] = 0.710290301049393;\n    volatilities[9] = 0.704174528906769;\n    volatilities[10] = 0.698342635400901;\n    volatilities[11] = 0.692771033345972;\n    volatilities[12] = 0.687438902593476;\n    volatilities[13] = 0.682327777297265;\n    volatilities[14] = 0.677421206991904;\n    volatilities[15] = 0.672704476238547;\n    volatilities[16] = 0.668164371832768;\n    volatilities[17] = 0.663788984329375;\n    volatilities[18] = 0.659567547226380;\n    volatilities[19] = 0.655490294349232;\n    volatilities[20] = 0.651548341349061;\n    volatilities[21] = 0.647733583657137;\n    volatilities[22] = 0.644038608699086;\n    volatilities[23] = 0.640456620061898;\n    volatilities[24] = 0.636981371712714;\n    volatilities[25] = 0.633607110719560;\n    volatilities[26] = 0.630328527192861;\n    volatilities[27] = 0.627140710386248;\n    volatilities[28] = 0.624039110072250;\n    volatilities[29] = 0.621019502453590;\n    volatilities[30] = 0.618077959983455;\n\n    Time expiry = 1.0;\n    Real forward = 0.039;\n    // input SABR coefficients (corresponding to the vols above)\n    Real initialAlpha = 0.2;\n    Real initialBeta = 0.6;\n    Real initialNu = 0.02;\n    Real initialRho = 0.01;\n    // calculate SABR vols and compare with input vols\n    NoArbSabrSmileSection noarbSabr(expiry, forward,\n                                    boost::assign::list_of(initialAlpha)(\n                                        initialBeta)(initialNu)(initialRho));\n    for (Size i = 0; i < strikes.size(); i++) {\n        Real calculatedVol = noarbSabr.volatility(strikes[i]);\n        if (std::fabs(volatilities[i]-calculatedVol) > tolerance)\n        BOOST_ERROR(\n            \"failed to calculate noarb-Sabr function at strike \" << strikes[i]\n            << \"\\n    expected:   \" << volatilities[i]\n            << \"\\n    calculated: \" << calculatedVol\n            << \"\\n    error:      \" << std::fabs(calculatedVol-volatilities[i]));\n    }\n\n    // Test SABR calibration against input parameters\n    Real betaGuess = 0.5;\n    Real alphaGuess = 0.2 / std::pow(forward,betaGuess-1.0); // new default value for alpha\n    Real nuGuess = std::sqrt(0.4);\n    Real rhoGuess = 0.0;\n\n    const bool vegaWeighted[]= {true, false};\n    const bool isAlphaFixed[]= {true, false};\n    const bool isBetaFixed[]= {true, false};\n    const bool isNuFixed[]= {true, false};\n    const bool isRhoFixed[]= {true, false};\n\n    Real calibrationTolerance = 5.0e-6;\n    // initialize optimization methods\n    std::vector<boost::shared_ptr<OptimizationMethod> > methods_;\n    methods_.push_back( boost::shared_ptr<OptimizationMethod>(new Simplex(0.01)));\n    methods_.push_back( boost::shared_ptr<OptimizationMethod>(new LevenbergMarquardt(1e-8, 1e-8, 1e-8)));\n    // Initialize end criteria\n    boost::shared_ptr<EndCriteria> endCriteria(new\n                  EndCriteria(100000, 100, 1e-8, 1e-8, 1e-8));\n    // Test looping over all possibilities\n    for (Size j=1; j<methods_.size(); ++j) { // skip simplex (gets caught in some cases)\n        for (Size i=0; i<LENGTH(vegaWeighted); ++i) {\n            for (Size k_a=0; k_a<LENGTH(isAlphaFixed); ++k_a) {\n                for (Size k_b=0; k_b<1/*LENGTH(isBetaFixed)*/; ++k_b) { // keep beta fixed (all 4 params free is a problem for this kind of test)\n                    for (Size k_n=0; k_n<LENGTH(isNuFixed); ++k_n) {\n                        for (Size k_r=0; k_r<LENGTH(isRhoFixed); ++k_r) {\n                            NoArbSabrInterpolation noarbSabrInterpolation(\n                                                                          strikes.begin(), strikes.end(),\n                                                                          volatilities.begin(), expiry, forward,\n                                                                          isAlphaFixed[k_a] ? initialAlpha\n                                                                          : alphaGuess,\n                                                                          isBetaFixed[k_b] ? initialBeta\n                                                                          : betaGuess,\n                                                                          isNuFixed[k_n] ? initialNu : nuGuess,\n                                                                          isRhoFixed[k_r] ? initialRho : rhoGuess,\n                                                                          isAlphaFixed[k_a], isBetaFixed[k_b],\n                                                                          isNuFixed[k_n], isRhoFixed[k_r],\n                                                                          vegaWeighted[i], endCriteria,\n                                                                          methods_[j], 1E-10);\n                            noarbSabrInterpolation.update();\n\n                            // Recover SABR calibration parameters\n                            bool failed = false;\n                            Real calibratedAlpha = noarbSabrInterpolation.alpha();\n                            Real calibratedBeta = noarbSabrInterpolation.beta();\n                            Real calibratedNu = noarbSabrInterpolation.nu();\n                            Real calibratedRho = noarbSabrInterpolation.rho();\n                            Real error;\n\n                            // compare results: alpha\n                            error = std::fabs(initialAlpha-calibratedAlpha);\n                            if (error > calibrationTolerance) {\n                                BOOST_ERROR(\"\\nfailed to calibrate alpha Sabr parameter:\" <<\n                                            \"\\n    expected:        \" << initialAlpha <<\n                                            \"\\n    calibrated:      \" << calibratedAlpha <<\n                                            \"\\n    error:           \" << error);\n                                failed = true;\n                            }\n                            // Beta\n                            error = std::fabs(initialBeta-calibratedBeta);\n                            if (error > calibrationTolerance) {\n                                BOOST_ERROR(\"\\nfailed to calibrate beta Sabr parameter:\" <<\n                                            \"\\n    expected:        \" << initialBeta <<\n                                            \"\\n    calibrated:      \" << calibratedBeta <<\n                                            \"\\n    error:           \" << error);\n                                failed = true;\n                            }\n                            // Nu\n                            error = std::fabs(initialNu-calibratedNu);\n                            if (error > calibrationTolerance) {\n                                BOOST_ERROR(\"\\nfailed to calibrate nu Sabr parameter:\" <<\n                                            \"\\n    expected:        \" << initialNu <<\n                                            \"\\n    calibrated:      \" << calibratedNu <<\n                                            \"\\n    error:           \" << error);\n                                failed = true;\n                            }\n                            // Rho\n                            error = std::fabs(initialRho-calibratedRho);\n                            if (error > calibrationTolerance) {\n                                BOOST_ERROR(\"\\nfailed to calibrate rho Sabr parameter:\" <<\n                                            \"\\n    expected:        \" << initialRho <<\n                                            \"\\n    calibrated:      \" << calibratedRho <<\n                                            \"\\n    error:           \" << error);\n                                failed = true;\n                            }\n\n                            if (failed)\n                                BOOST_TEST_MESSAGE(\"\\nnoarb-Sabr calibration failure:\" <<\n                                           \"\\n    isAlphaFixed:    \" << isAlphaFixed[k_a] <<\n                                           \"\\n    isBetaFixed:     \" << isBetaFixed[k_b] <<\n                                           \"\\n    isNuFixed:       \" << isNuFixed[k_n] <<\n                                           \"\\n    isRhoFixed:      \" << isRhoFixed[k_r] <<\n                                           \"\\n    vegaWeighted[i]: \" << vegaWeighted[i]);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n}\n\n\nvoid InterpolationTest::testSabrSingleCases() {\n\n    BOOST_TEST_MESSAGE(\"Testing Sabr calibration single cases...\");\n\n    // case #1\n    // this fails with an exception thrown in 1.4, fixed in 1.5\n\n    using namespace boost::assign;\n    std::vector<Real> strikes, vols;\n    strikes += 0.01, 0.01125, 0.0125, 0.01375, 0.0150;\n    vols += 0.1667, 0.2020, 0.2785, 0.3279, 0.3727;\n\n    Real tte = 0.3833;\n    Real forward = 0.011025;\n\n    SABRInterpolation s0(strikes.begin(), strikes.end(), vols.begin(), tte, forward,\n                         Null<Real>(), 0.25, Null<Real>(), Null<Real>(),\n                         false, true, false, false);\n    s0.update();\n\n    if (s0.maxError() > 0.01 || s0.rmsError() > 0.01) {\n        BOOST_ERROR(\"Sabr case #1 failed with max error (\"\n                      << s0.maxError() << \") and rms error (\" << s0.rmsError()\n                      << \"), both should be < 0.01\");\n    }\n\n}\n\nvoid InterpolationTest::testTransformations() {\n\n    BOOST_TEST_MESSAGE(\"Testing Sabr and no-arbitrage Sabr transformation functions...\");\n\n    Real size = 25.0; // test inputs from [-size,size]^4\n\n    Size N = 100000;\n\n    Array x(4), y(4), z(4);\n    std::vector<Real> s;\n    std::vector<bool> fixed(4, false);\n    std::vector<Real> params(4, 0.0);\n    Real forward = 0.03;\n\n    HaltonRsg h(4, 42, false, false);\n\n    for (Size i = 0; i < 1E6; ++i) {\n\n        s = h.nextSequence().value;\n        for (Size j = 0; j < 4; ++j)\n            x[j] = 2.0 * size * s[j] - size;\n\n        // sabr\n        y = detail::SABRSpecs().direct(x, fixed, params, forward);\n        validateSabrParameters(y[0], y[1], y[2], y[3]);\n        z = detail::SABRSpecs().inverse(y, fixed, params, forward);\n        z = detail::SABRSpecs().direct(z, fixed, params, forward);\n        if (!close(z[0], y[0], N) || !close(z[1], y[1], N) || !close(z[2], y[2], N) ||\n            !close(z[3], y[3], N))\n            BOOST_ERROR(\"SabrInterpolation: direct(inverse(\"\n                        << y[0] << \",\" << y[1] << \",\" << y[2] << \",\" << y[3]\n                        << \")) = (\" << z[0] << \",\" << z[1] << \",\" << z[2] << \",\"\n                        << z[3] << \"), difference is (\" << z[0] - y[0] << \",\"\n                        << z[1] - y[1] << \",\" << z[2] - y[2] << \",\"\n                        << z[3] - y[3] << \")\");\n\n        // noarb sabr\n        y = detail::NoArbSabrSpecs().direct(x, fixed, params, forward);\n\n        // we can not invoke the constructor, this would be too slow, so\n        // we copy the parameter check here ...\n        Real alpha = y[0];\n        Real beta = y[1];\n        Real nu = y[2];\n        Real rho = y[3];\n        QL_REQUIRE(beta >= detail::NoArbSabrModel::beta_min &&\n                       beta <= detail::NoArbSabrModel::beta_max,\n                   \"beta (\" << beta << \") out of bounds\");\n        Real sigmaI = alpha * std::pow(forward, beta - 1.0);\n        QL_REQUIRE(sigmaI >= detail::NoArbSabrModel::sigmaI_min &&\n                       sigmaI <= detail::NoArbSabrModel::sigmaI_max,\n                   \"sigmaI = alpha*forward^(beta-1.0) (\"\n                       << sigmaI << \") out of bounds, alpha=\" << alpha\n                       << \" beta=\" << beta << \" forward=\" << forward);\n        QL_REQUIRE(nu >= detail::NoArbSabrModel::nu_min &&\n                       nu <= detail::NoArbSabrModel::nu_max,\n                   \"nu (\" << nu << \") out of bounds\");\n        QL_REQUIRE(rho >= detail::NoArbSabrModel::rho_min &&\n                       rho <= detail::NoArbSabrModel::rho_max,\n                   \"rho (\" << rho << \") out of bounds\");\n\n        z = detail::NoArbSabrSpecs().inverse(y, fixed, params, forward);\n        z = detail::NoArbSabrSpecs().direct(z, fixed, params, forward);\n        if (!close(z[0], y[0], N) || !close(z[1], y[1], N) || !close(z[2], y[2], N) ||\n            !close(z[3], y[3], N))\n            BOOST_ERROR(\"NoArbSabrInterpolation: direct(inverse(\"\n                        << y[0] << \",\" << y[1] << \",\" << y[2] << \",\" << y[3]\n                        << \")) = (\" << z[0] << \",\" << z[1] << \",\" << z[2] << \",\"\n                        << z[3] << \"), difference is (\" << z[0] - y[0] << \",\"\n                        << z[1] - y[1] << \",\" << z[2] - y[2] << \",\"\n                        << z[3] - y[3] << \")\");\n    }\n\n}\n\nnamespace {\n    Real lagrangeTestFct(Real x) {\n        return std::fabs(x) + 0.5*x - x*x;\n    }\n}\n\nvoid InterpolationTest::testLagrangeInterpolation() {\n\n    BOOST_TEST_MESSAGE(\"Testing Lagrange interpolation...\");\n\n    const Real x[] = {-1.0 , -0.5, -0.25, 0.1, 0.4, 0.75, 0.96};\n    Array y(LENGTH(x));\n    std::transform(x, x+LENGTH(x), y.begin(), &lagrangeTestFct);\n\n    LagrangeInterpolation interpl(&x[0], x+LENGTH(x), y.begin());\n\n    // reference results are taken from R package pracma\n    const Real references[] = {\n        -0.5000000000000000,-0.5392414024347419,-0.5591485962711904,\n        -0.5629199661387594,-0.5534414777017116,-0.5333043347921566,\n        -0.5048221831582063,-0.4700478608272949,-0.4307896950846587,\n        -0.3886273460669714,-0.3449271969711449,-0.3008572908782903,\n        -0.2574018141928359,-0.2153751266968088,-0.1754353382192734,\n        -0.1380974319209344,-0.1037459341938971,-0.0726471311765894,\n        -0.0449608318838433,-0.0207516779521373,0.0000000000000000,\n        0.0173877793964286,0.0315691961126723,0.0427562482700356,\n        0.0512063534145595,0.0572137590808174,0.0611014067405497,\n        0.0632132491361394,0.0639070209989264,0.0635474631523613,\n        0.0625000000000000,0.0611248703983366,0.0597717119144768,\n        0.0587745984686508,0.0584475313615655,0.0590803836865967,\n        0.0609352981268212,0.0642435381368876,0.0692027925097279,\n        0.0759749333281079,0.0846842273010179,0.0954160004849021,\n        0.1082157563897290,0.1230887474699003,0.1400000000000001,\n        0.1588747923353829,0.1795995865576031,0.2020234135046815,\n        0.2259597111862140,0.2511886165833182,0.2774597108334206,\n        0.3044952177998833,0.3319936560264689,0.3596339440766487,\n        0.3870799592577457,0.4139855497299214,0.4400000000000001,\n        0.4647739498001331,0.4879657663513030,0.5092483700116673,\n        0.5283165133097421,0.5448945133624253,0.5587444376778583,\n        0.5696747433431296,0.5775493695968156,0.5822972837863635,\n        0.5839224807103117,0.5825144353453510,0.5782590089582251,\n        0.5714498086024714,0.5625000000000000,0.5519545738075141,\n        0.5405030652677689,0.5289927272456703,0.5184421566492137,\n        0.5100553742352614,0.5052363578001620,0.5056040287552059,\n        0.5130076920869246\n    };\n\n    const Real tol = 50*QL_EPSILON;\n    for (Size i=0; i < 79; ++i) {\n        const Real xx = -1.0 + i*0.025;\n        const Real calculated = interpl(xx);\n        if (   boost::math::isnan(calculated)\n            || std::fabs(references[i] - calculated) > tol) {\n            BOOST_FAIL(\"failed to reproduce the Lagrange interpolation\"\n                    << \"\\n    x         : \" << xx\n                    << \"\\n    calculated: \" << calculated\n                    << \"\\n    expected  : \" << references[i]);\n        }\n    }\n}\n\nvoid InterpolationTest::testLagrangeInterpolationAtSupportPoint() {\n    BOOST_TEST_MESSAGE(\n        \"Testing Lagrange interpolation at supporting points...\");\n\n    const Size n=5;\n    Array x(n), y(n);\n    for (Size i=0; i < n; ++i) {\n        x[i] = i/Real(n);\n        y[i] = 1.0/(1.0 - x[i]);\n    }\n    LagrangeInterpolation interpl(x.begin(), x.end(), y.begin());\n\n    const Real relTol = 5e-12;\n\n    for (Size i=1; i < n-1; ++i) {\n        for (Real z = x[i] - 100*QL_EPSILON;\n            z < x[i] + 100*QL_EPSILON; z+=2*QL_EPSILON) {\n            const Real expected = 1.0/(1.0 - x[i]);\n            const Real calculated = interpl(z);\n\n            if (   boost::math::isnan(calculated)\n                || std::fabs(expected - calculated) > relTol) {\n                BOOST_FAIL(\"failed to reproduce the Lagrange interplation\"\n                        << \"\\n    x         : \" << z\n                        << \"\\n    calculated: \" << calculated\n                        << \"\\n    expected  : \" << expected);\n            }\n        }\n    }\n}\n\nvoid InterpolationTest::testLagrangeInterpolationDerivative() {\n    BOOST_TEST_MESSAGE(\n        \"Testing Lagrange interpolation derivatives...\");\n\n    Array x(5), y(5);\n    x[0] = -1.0; y[0] = 2.0;\n    x[1] = -0.3; y[1] = 3.0;\n    x[2] =  0.1; y[2] = 6.0;\n    x[3] =  0.3; y[3] = 3.0;\n    x[4] =  0.9; y[4] =-1.0;\n\n    LagrangeInterpolation interpl(x.begin(), x.end(), y.begin());\n\n    const Real eps = std::sqrt(QL_EPSILON);\n    for (Real x=-1.0; x <= 0.9; x+=0.01) {\n        const Real calculated = interpl.derivative(x, true);\n        const Real expected = (interpl(x+eps, true)\n            - interpl(x-eps, true))/(2*eps);\n\n        if (   boost::math::isnan(calculated)\n            || std::fabs(expected - calculated) > 25*eps) {\n            BOOST_FAIL(\"failed to reproduce the Lagrange\"\n                    \" interplation derivative\"\n                    << \"\\n    x         : \" << x\n                    << \"\\n    calculated: \" << calculated\n                    << \"\\n    expected  : \" << expected);\n        }\n    }\n}\n\nvoid InterpolationTest::testLagrangeInterpolationOnChebyshevPoints() {\n    BOOST_TEST_MESSAGE(\n        \"Testing Lagrange interpolation on Chebyshev points...\");\n\n    // Test example taken from\n    // J.P. Berrut, L.N. Trefethen, Barycentric Lagrange Interpolation\n    // https://people.maths.ox.ac.uk/trefethen/barycentric.pdf\n\n    const Size n=50;\n    Array x(n+1), y(n+1);\n    for (Size i=0; i <= n; ++i) {\n        // Chebyshev points\n        x[i] = std::cos( (2*i+1)*M_PI/(2*n+2) );\n        y[i] = std::exp(x[i])/std::cos(x[i]);\n    }\n\n    LagrangeInterpolation interpl(x.begin(), x.end(), y.begin());\n\n    const Real tol = 1e-13;\n\n    for (Real x=-1.0; x <= 1.0; x+=0.01) {\n        const Real calculated = interpl(x, true);\n        const Real expected = std::exp(x)/std::cos(x);\n\n        if (   boost::math::isnan(calculated)\n            || std::fabs(expected - calculated) > tol) {\n            BOOST_FAIL(\"failed to reproduce the Lagrange\"\n                    \" interplation on Chebyshev points\"\n                    << \"\\n    x         : \" << x\n                    << \"\\n    calculated: \" << calculated\n                    << \"\\n    expected  : \" << expected);\n        }\n\n        const Real calculatedDeriv = interpl.derivative(x, true);\n        const Real expectedDeriv = std::exp(x)*(std::cos(x) + std::sin(x))\n                / square<Real>()(std::cos(x));\n\n        if (   boost::math::isnan(calculated)\n            || std::fabs(expected - calculated) > tol) {\n            BOOST_FAIL(\"failed to reproduce the Lagrange\"\n                    \" interplation derivative on Chebyshev points\"\n                    << \"\\n    x         : \" << x\n                    << \"\\n    calculated: \" << calculatedDeriv\n                    << \"\\n    expected  : \" << expectedDeriv);\n        }\n    }\n}\n\n\ntest_suite* InterpolationTest::suite() {\n    test_suite* suite = BOOST_TEST_SUITE(\"Interpolation tests\");\n\n    suite->add(QUANTLIB_TEST_CASE(\n                        &InterpolationTest::testSplineOnGenericValues));\n    suite->add(QUANTLIB_TEST_CASE(\n                        &InterpolationTest::testSimmetricEndConditions));\n    suite->add(QUANTLIB_TEST_CASE(\n                        &InterpolationTest::testDerivativeEndConditions));\n    suite->add(QUANTLIB_TEST_CASE(\n                        &InterpolationTest::testNonRestrictiveHymanFilter));\n    suite->add(QUANTLIB_TEST_CASE(\n                        &InterpolationTest::testSplineOnRPN15AValues));\n    suite->add(QUANTLIB_TEST_CASE(\n                        &InterpolationTest::testSplineOnGaussianValues));\n    suite->add(QUANTLIB_TEST_CASE(\n                        &InterpolationTest::testSplineErrorOnGaussianValues));\n    suite->add(QUANTLIB_TEST_CASE(&InterpolationTest::testMultiSpline));\n    suite->add(QUANTLIB_TEST_CASE(&InterpolationTest::testAsFunctor));\n    suite->add(QUANTLIB_TEST_CASE(&InterpolationTest::testBackwardFlat));\n    suite->add(QUANTLIB_TEST_CASE(&InterpolationTest::testForwardFlat));\n    suite->add(QUANTLIB_TEST_CASE(&InterpolationTest::testSabrInterpolation));\n    suite->add(QUANTLIB_TEST_CASE(&InterpolationTest::testKernelInterpolation));\n    suite->add(QUANTLIB_TEST_CASE(\n                              &InterpolationTest::testKernelInterpolation2D));\n    suite->add(QUANTLIB_TEST_CASE(&InterpolationTest::testBicubicDerivatives));\n    suite->add(QUANTLIB_TEST_CASE(&InterpolationTest::testBicubicUpdate));\n    suite->add(QUANTLIB_TEST_CASE(\n                            &InterpolationTest::testRichardsonExtrapolation));\n    suite->add(QUANTLIB_TEST_CASE(&InterpolationTest::testNoArbSabrInterpolation));\n    suite->add(QUANTLIB_TEST_CASE(&InterpolationTest::testSabrSingleCases));\n    suite->add(QUANTLIB_TEST_CASE(&InterpolationTest::testTransformations));\n    suite->add(QUANTLIB_TEST_CASE(\n        &InterpolationTest::testLagrangeInterpolation));\n    suite->add(QUANTLIB_TEST_CASE(\n        &InterpolationTest::testLagrangeInterpolationAtSupportPoint));\n    suite->add(QUANTLIB_TEST_CASE(\n        &InterpolationTest::testLagrangeInterpolationDerivative));\n\n    suite->add(QUANTLIB_TEST_CASE(\n        &InterpolationTest::testLagrangeInterpolationOnChebyshevPoints));\n\n    return suite;\n}\n", "meta": {"hexsha": "e905b3505397e2f05b269927e07c9b7f7bae3894", "size": 89574, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/interpolations.cpp", "max_stars_repo_name": "sfondi/QuantLib", "max_stars_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "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-suite/interpolations.cpp", "max_issues_repo_name": "sfondi/QuantLib", "max_issues_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/interpolations.cpp", "max_forks_repo_name": "sfondi/QuantLib", "max_forks_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "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.7154545455, "max_line_length": 145, "alphanum_fraction": 0.5108960189, "num_tokens": 24705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5230519136176083}}
{"text": "//\n//  cal_strain_energy_density_hpp.hpp\n//  hybrid_fem_bie\n//\n//  Created by Max on 2/7/18.\n//\n//\n\n#ifndef cal_strain_energy_density_hpp\n#define cal_strain_energy_density_hpp\n\n#include <stdio.h>\n#include <Eigen/Eigen>\n\nusing namespace Eigen;\nvoid cal_strain_energy_density(std::vector<MatrixXd> &coord ,double E, double nu,std::vector<double>&se_out, std::vector<double> &exx_out,std::vector<double> &eyy_out,  int n_el, MatrixXi &index_store, double q, VectorXd &u_n);\n#endif /* cal_strain_energy_density */\n", "meta": {"hexsha": "b463732b2b35c191a7d07a40acb04160e06e80c1", "size": 510, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/fem/cal_strain_energy_density.hpp", "max_stars_repo_name": "XiaoMaResearch/hybrid_tpv14", "max_stars_repo_head_hexsha": "074a0f079120af818eaab7e23acf35c6c068a876", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fem/cal_strain_energy_density.hpp", "max_issues_repo_name": "XiaoMaResearch/hybrid_tpv14", "max_issues_repo_head_hexsha": "074a0f079120af818eaab7e23acf35c6c068a876", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fem/cal_strain_energy_density.hpp", "max_forks_repo_name": "XiaoMaResearch/hybrid_tpv14", "max_forks_repo_head_hexsha": "074a0f079120af818eaab7e23acf35c6c068a876", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 227, "alphanum_fraction": 0.7607843137, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5230519136176082}}
{"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_EXPECTATION_HPP_INCLUDED\n#define NDHIST_STATS_EXPECTATION_HPP_INCLUDED 1\n\n#include <cmath>\n\n#include <boost/python.hpp>\n\n#include <boost/numpy/ndarray.hpp>\n#include <boost/numpy/iterators/multi_flat_iterator.hpp>\n\n#include <ndhist/detail/bin_iter_value_type_traits.hpp>\n#include <ndhist/ndhist.hpp>\n\nnamespace ndhist {\nnamespace stats {\n\nnamespace detail {\n\n/**\n * Calculates the n'th order expectation value along the given axis of the given\n * ndhist object weighted by the sum of weights in each bin.\n * It generates a projection along the given axis and then calculates the n'th\n * order expectation value.\n * In statistics the n'th order expectation is defined as the expectation of\n * x^n, i.e. ``E[x^n]``, where x is the bin center axis value in this case.\n */\ntemplate <typename AxisValueType, typename WeightValueType>\ndouble\ncalc_axis_expectation_impl(\n    ndhist const & h\n  , intptr_t const n\n  , intptr_t const axis\n)\n{\n    // Project the given histogram to the given axis (if nd > 1).\n    ndhist const proj = (h.get_nd() == 1 ? h : h.project(bp::object(axis)));\n\n    // Iterate over the bins (which are along the given axis) and exclude\n    // possible under- and overflow bins.\n    Axis const & theaxis = *proj.get_axes()[0];\n    intptr_t nbins = theaxis.get_n_bins();\n    if(theaxis.has_underflow_bin()) --nbins;\n    if(theaxis.has_overflow_bin()) --nbins;\n    bn::ndarray proj_bincenters_arr = theaxis.get_bincenters_ndarray();\n    bn::ndarray proj_bc_arr = proj.bc_.construct_ndarray(proj.bc_.get_dtype(), 0, /*owner=*/NULL, /*set_owndata_flag=*/false);\n    typedef bn::iterators::multi_flat_iterator<2>::impl<\n                bn::iterators::single_value<AxisValueType>\n              , ::ndhist::detail::bin_iter_value_type_traits<WeightValueType>\n            >\n            multi_iter_t;\n    multi_iter_t iter(\n        proj_bincenters_arr\n      , proj_bc_arr\n      , bn::detail::iter_operand::flags::READONLY::value\n      , bn::detail::iter_operand::flags::READONLY::value\n    );\n\n    // Skip the underflow bin.\n    if(theaxis.has_underflow_bin()) ++iter;\n\n    double expectation = 0;\n    double sow_sum = 0;\n    while(nbins > 0)\n    {\n        typename multi_iter_t::multi_references_type multi_value = *iter;\n        typename multi_iter_t::value_ref_type_0 axis_bincenter_value = multi_value.value_0;\n        typename multi_iter_t::value_ref_type_1 bin                  = multi_value.value_1;\n\n        sow_sum += *bin.sow_;\n        expectation += *bin.sow_ * (n == 1 ? axis_bincenter_value\n                                 : (n == 2 ? axis_bincenter_value*axis_bincenter_value\n                                 : (n == 3 ? axis_bincenter_value*axis_bincenter_value*axis_bincenter_value\n                                 : std::pow(axis_bincenter_value, n))));\n\n        ++iter;\n        --nbins;\n    }\n    expectation /= sow_sum;\n    return expectation;\n}\n\n}// namespace detail\n\nnamespace py {\n\n/**\n * @brief Calculates the n'th order expectation value along the given axis of\n *     the given ndhist object weighted by the sum of weights in each bin.\n *     It generates a projection along the given axis and then calculates the\n *     n'th order expectation value.\n *     In statistics the n'th order expectation value is defined as the\n *     expectation of x^n, i.e. ``E[x^n]``, where x is the bin center axis\n *     value in this case.\n *     If None is given as axis, the expectation value for all 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\nexpectation(\n    ndhist const & h\n  , intptr_t const n = 1\n  , boost::python::object const & axis = boost::python::object()\n);\n\n}// namespace py\n}// namespace stats\n}// namespace ndhist\n\n#endif // !NDHIST_STATS_EXPECTATION_HPP_INCLUDED\n", "meta": {"hexsha": "6a0d0c6147dcc84aa25dc56515c56696fc11190a", "size": 4176, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ndhist/stats/expectation.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/expectation.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/expectation.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": 33.6774193548, "max_line_length": 126, "alphanum_fraction": 0.6762452107, "num_tokens": 1028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5230168450395452}}
{"text": "//\n//  Copyright Karl Meerbergen, 2008\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 \"../../blas/test/random.hpp\"\n\n#include <boost/numeric/bindings/lapack/driver/ptsv.hpp>\n#include <boost/numeric/bindings/lapack/computational/pttrf.hpp>\n#include <boost/numeric/bindings/lapack/computational/pttrs.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <iostream>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\n\nstruct apply_real {\n  template< typename VectorD, typename VectorE, typename MatrixB >\n  static inline std::ptrdiff_t pttrs( const char uplo, const VectorD& d,\n        const VectorE& e, MatrixB& b ) {\n    return lapack::pttrs( d, e, b );\n  }\n};\n\nstruct apply_complex {\n  template< typename VectorD, typename VectorE, typename MatrixB >\n  static inline std::ptrdiff_t pttrs( const char uplo, const VectorD& d,\n        const VectorE& e, MatrixB& b ) {\n    return lapack::pttrs( uplo, d, e, b );\n  }\n};\n\ntemplate <typename B, typename X>\nbool check_residual( B const& b, X const& x ) {\n  typedef typename B::value_type value_type ;\n\n  ublas::matrix<value_type, ublas::column_major> res( b ) ;\n  row(res,0).minus_assign( value_type(2.0) * row(x,0) - row(x,1) ) ;\n  for (int i=1; i<res.size1()-1; ++i) {\n    row(res,i).minus_assign( value_type(2.0) * row(x,i) - row(x,i+1) - row(x,i-1) ) ;\n  }\n  row(res,res.size1()-1).minus_assign( value_type(2.0) * row(x,res.size1()-1) - row(x,res.size1()-2) ) ;\n\n  return norm_frobenius(res)<norm_frobenius(b)*1.e-5 ;\n} // check_residual()\n\ntemplate <typename T>\nint do_value_type() {\n   typedef typename boost::mpl::if_<boost::is_complex<T>, apply_complex, apply_real>::type apply_t;\n   const int n = 8 ;\n   typedef typename bindings::remove_imaginary<T>::type real_type ;\n\n   typedef ublas::matrix<T, ublas::column_major>     matrix_type ;\n\n   // Set matrix\n   int const nrhs = 1 ;\n   matrix_type b( n, nrhs );\n   ublas::vector< real_type > d( n );\n   ublas::vector<T>           e( n-1 );\n\n   std::fill( d.begin(), d.end(), 2.0 ) ;\n   std::fill( e.begin(), e.end(), -1.0 ) ;\n\n   for (int i=0; i<b.size1(); ++i) b(i,0) = random_value<T>() ;\n\n   // Factorize and solve\n   matrix_type x( b );\n   if( lapack::ptsv( d, e, x ) ) return -1 ;\n   if (!check_residual(b,x)) return 1 ;\n\n   // Restart computations\n   std::fill( d.begin(), d.end(), 2.0 ) ;\n   std::fill( e.begin(), e.end(), -1.0 ) ;\n\n   // Compute factorization.\n   if( lapack::pttrf( d, e ) ) return -1 ;\n\n   // Compute solve\n   x.assign( b ) ;\n   if( apply_t::pttrs( 'U', d, e, x ) ) return -2 ;\n\n   if (!check_residual(b,x)) return 1 ;\n\n   x.assign( b ) ;\n   if( apply_t::pttrs( 'L', d, e, x ) ) return -3 ;\n\n   if (!check_residual(b,x)) return 2 ;\n\n   return 0 ;\n} // do_value_type()\n\n\nint main() {\n   // Run tests for different value_types\n   std::cout << \"double\\n\" ;\n   if (do_value_type< double >()) return 255;\n\n   std::cout << \"float\\n\" ;\n   if (do_value_type< float >()) return 255;\n\n   std::cout << \"complex<double>\\n\" ;\n   if (do_value_type< std::complex<double> >()) return 255;\n\n   std::cout << \"complex<float>\\n\" ;\n   if (do_value_type< std::complex<float> >()) return 255;\n\n   std::cout << \"Regression test succeeded\\n\" ;\n   return 0;\n}\n\n", "meta": {"hexsha": "609593563263d39f93f931667ce7c5e7f6500402", "size": 3618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_ptsv.cpp", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-08-02T14:21:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-05T10:34:45.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_ptsv.cpp", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T21:30:35.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-08T19:44:18.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_ptsv.cpp", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-28T21:11:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-28T21:11:52.000Z", "avg_line_length": 29.6557377049, "max_line_length": 104, "alphanum_fraction": 0.6478717523, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5228858308198006}}
{"text": "#include <iostream>\n#include <chrono>\n#include <vector>\n#include <unordered_map>\n#include <fstream>\n#include <cstdlib>\n#include <ctime>\n#include <cmath>\n#include <utility>\n#include <boost/heap/fibonacci_heap.hpp>\n#include <boost/heap/binomial_heap.hpp>\n\nusing namespace std::chrono;\nusing namespace boost::heap;\n\nusing uint_pair = std::pair<unsigned int, unsigned int>;\n\ntemplate <class Heap>\nuint_pair test_with_elements(int n) {\n\tHeap heap;\n\t\n\tauto start = high_resolution_clock::now();\n\n\tfor (int i = 0; i < n; i++) {\n\t\theap.push(std::rand());\n\t}\n\n\tauto end = high_resolution_clock::now();\n\n\tunsigned int full = duration_cast<nanoseconds>(end - start).count();\n\n\n\tstart = high_resolution_clock::now();\n\theap.push(std::rand());\n\tend = high_resolution_clock::now();\n\n\tunsigned int last = duration_cast<nanoseconds>(end - start).count();\n\n\treturn {full, last};\n}\n\ntemplate <class Heap>\nvoid run_experiment(std::ostream& output, const std::string& heap_name) {\n\tfor (int i = 0; i < 1000; i++) {\n\t\tint n = 100 * (i + 1);\n\t\t\n\t\tfor (int j = 0; j < 30; j++) {\n\t\t\tuint_pair result = test_with_elements<Heap>(n);\n\n\t\t\toutput << heap_name << \",\" << n << \",\" << result.first << \",\" << result.second << \"\\n\";\n\t\t}\n\t}\n}\n\nint main(int argc, char** argv) {\n\tstd::srand(std::time(nullptr));\n\tstd::ofstream output(\"experiments.csv\");\n\n\toutput << \"heap,n,full,last\\n\";\n\n\trun_experiment<binomial_heap<int>>(output, \"binomial\");\n\trun_experiment<fibonacci_heap<int>>(output, \"fibonacci\");\n}\n", "meta": {"hexsha": "4b3adc568b29badf7daa8e9ade37ea20c8560e74", "size": 1470, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Binomial vs Fibonacci/main.cpp", "max_stars_repo_name": "concatto/complexidade", "max_stars_repo_head_hexsha": "1a31d68cc6b30ab1ce18d8520b5eae03bb3e1cc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Binomial vs Fibonacci/main.cpp", "max_issues_repo_name": "concatto/complexidade", "max_issues_repo_head_hexsha": "1a31d68cc6b30ab1ce18d8520b5eae03bb3e1cc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Binomial vs Fibonacci/main.cpp", "max_forks_repo_name": "concatto/complexidade", "max_forks_repo_head_hexsha": "1a31d68cc6b30ab1ce18d8520b5eae03bb3e1cc8", "max_forks_repo_licenses": ["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.96875, "max_line_length": 90, "alphanum_fraction": 0.6721088435, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5228858183917523}}
{"text": "/*\n *  This file is a part of HAXX\n *  \n *  Copyright (c) 2017 David Williams-Young\n *  All rights reserved.\n *  \n *  See LICENSE.txt \n */\n\n\n#ifdef BOOST_TEST_MODULE\n  #undef BOOST_TEST_MODULE\n#endif\n\n#define BOOST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <boost/iterator/counting_iterator.hpp>\n\n#include \"haxx.hpp\"\n\n#include <random>\n#include <iterator>\n#include <iostream>\n#include <limits>\n#include <chrono>\n\n// Length constants\n#define HBLAS1_VECLEN 100\n#define HBLAS2_MATLEN (HBLAS1_VECLEN) * (HBLAS1_VECLEN)\n#define HBLAS1_RAND_MIN -20\n#define HBLAS1_RAND_MAX 54\n\n// Setup Random Number generator\nstatic std::random_device rd;\nstatic std::mt19937 gen(rd());\nstatic std::uniform_real_distribution<> dis(HBLAS1_RAND_MIN,HBLAS1_RAND_MAX);\n\ntemplate <typename _F> _F genRandom();\ntemplate<> inline double genRandom<double>(){ return double(dis(gen)); }\ntemplate<> inline std::complex<double> genRandom<std::complex<double>>(){ \n  return std::complex<double>(dis(gen),dis(gen)); \n}\ntemplate<> inline HAXX::quaternion<double> genRandom<HAXX::quaternion<double>>(){ \n  return HAXX::quaternion<double>(dis(gen),dis(gen),dis(gen),dis(gen)); \n}\n\n\n\n// Index list for HBLAS1 UT conformation\nstatic std::vector<int> indx(boost::counting_iterator<int>(0),\n  boost::counting_iterator<int>(HBLAS1_VECLEN));\n\n// Strides to be tested\nstatic std::vector<size_t> strides = {1,2,3,5,9};\n\n#define COMPARE_TOL 1e-12\n#define CMP_Q(a,b) ( HAXX::norm(((a) * HAXX::inv(b))- 1.) < COMPARE_TOL )\n", "meta": {"hexsha": "bc85759d0c74c1c84f68816f59802a5d21a84b92", "size": 1486, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/haxx_ut.hpp", "max_stars_repo_name": "wavefunction91/HAXX", "max_stars_repo_head_hexsha": "e0c282b70ee009a2a01871979f505bcca89713ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-11-05T22:20:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-28T22:22:55.000Z", "max_issues_repo_path": "tests/haxx_ut.hpp", "max_issues_repo_name": "wavefunction91/HAXX", "max_issues_repo_head_hexsha": "e0c282b70ee009a2a01871979f505bcca89713ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/haxx_ut.hpp", "max_forks_repo_name": "wavefunction91/HAXX", "max_forks_repo_head_hexsha": "e0c282b70ee009a2a01871979f505bcca89713ba", "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.186440678, "max_line_length": 82, "alphanum_fraction": 0.7288021534, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5228858164509254}}
{"text": "/* This file is part of the Tomographer project, which is distributed under the\n * terms of the MIT license.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 ETH Zurich, Institute for Theoretical Physics, Philippe Faist\n * Copyright (c) 2017 Caltech, Institute for Quantum Information and Matter, Philippe Faist\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include <cmath>\n\n#include <string>\n#include <iostream>\n#include <random>\n\n#include <boost/math/constants/constants.hpp>\n\n// definitions for Tomographer test framework -- this must be included before any\n// <Eigen/...> or <tomographer/...> header\n#include \"test_tomographer.h\"\n\n#include <tomographer/tools/eigenutil.h>\n#include <tomographer/tools/cxxutil.h>\n\n\n\n// -----------------------------------------------------------------------------\n// fixture(s)\n\n\n// -----------------------------------------------------------------------------\n// test suites\n\n\nBOOST_AUTO_TEST_SUITE(test_mathtools_eigenutil)\n\nBOOST_AUTO_TEST_CASE(denseRandom)\n{\n  std::mt19937 rng;\n  std::uniform_real_distribution<double> dist(0.0, 1.0);\n  std::uniform_real_distribution<float> distf(0.f, 1.f);\n\n  constexpr int N = 10000;\n\n  Eigen::VectorXd v(Tomographer::Tools::denseRandom<Eigen::VectorXd>(rng, dist, N));\n  MY_BOOST_CHECK_FLOATS_EQUAL(v.sum(), 0.5*N, 2.0/std::sqrt(N)) ;\n\n  Eigen::VectorXd v2(Tomographer::Tools::denseRandom<Eigen::Matrix<double,N,1> >(rng, dist, N));\n  MY_BOOST_CHECK_FLOATS_EQUAL(v2.sum(), 0.5*N, 2.0/std::sqrt(N)) ;\n\n  Eigen::Matrix<float,N,1> v3(Tomographer::Tools::denseRandom<Eigen::Matrix<float,Eigen::Dynamic,1> >(rng, distf, N));\n  MY_BOOST_CHECK_FLOATS_EQUAL(v3.sum(), 0.5*N, 2.f/std::sqrt((float)N)) ;\n}\n\nBOOST_AUTO_TEST_CASE(canonicalBasisVec_1)\n{\n  auto v1 = Tomographer::Tools::canonicalBasisVec<Eigen::VectorXd>(3, 10);\n  Eigen::VectorXd v2(10); v2 << 0,0,0,1,0,0,0,0,0,0;\n  MY_BOOST_CHECK_EIGEN_EQUAL(v1, v2, tol);\n}\nBOOST_AUTO_TEST_CASE(canonicalBasisVec_2)\n{\n  auto v1 = Tomographer::Tools::canonicalBasisVec<Eigen::Matrix<double,10,1> >(3, 10);\n  Eigen::VectorXd v2(10); v2 << 0,0,0,1,0,0,0,0,0,0;\n  MY_BOOST_CHECK_EIGEN_EQUAL(v1, v2, tol);\n}\nBOOST_AUTO_TEST_CASE(canonicalBasisVec_mat)\n{\n  auto m1 = Tomographer::Tools::canonicalBasisVec<Eigen::Matrix<double,3,3> >(1,2, 3,3);\n  Eigen::Matrix3d m2; m2 << 0,0,0, 0,0,1, 0,0,0 ;\n  MY_BOOST_CHECK_EIGEN_EQUAL(m1, m2, tol);\n}\n\nBOOST_AUTO_TEST_SUITE(powersOfTwo)\n\nBOOST_AUTO_TEST_CASE(basic)\n{\n  Eigen::VectorXd v1 = Tomographer::Tools::powersOfTwo<Eigen::VectorXd>(10);\n  Eigen::VectorXd v2(10); v2 << 1, 2, 4, 8, 16, 32, 64, 128, 256, 512;\n  MY_BOOST_CHECK_EIGEN_EQUAL(v1, v2, tol);\n}\nBOOST_AUTO_TEST_CASE(mat)\n{\n  Eigen::Matrix3d m1 = Tomographer::Tools::powersOfTwo<Eigen::Matrix3d>();\n  Eigen::Matrix3d m2;\n  m2 << 1,  8, 64,\n        2, 16, 128, \n        4, 32, 256;\n  MY_BOOST_CHECK_EIGEN_EQUAL(m1, m2, tol);\n}\nBOOST_AUTO_TEST_CASE(fixed)\n{\n  Eigen::Array<double,1,9> twopows = Tomographer::Tools::powersOfTwo<Eigen::Array<double,1,9> >().transpose();\n  Eigen::Array<double,1,9> correct_twopows;\n  correct_twopows << 1, 2, 4, 8, 16, 32, 64, 128, 256;\n\n  MY_BOOST_CHECK_EIGEN_EQUAL(twopows, correct_twopows, tol);\n}\n\nBOOST_AUTO_TEST_CASE(dyn_vector)\n{\n  Eigen::VectorXd twopows(6);\n  twopows = Tomographer::Tools::powersOfTwo<Eigen::VectorXd>(6);\n  BOOST_MESSAGE(\"twopows = \" << twopows);\n  Eigen::VectorXd correct_twopows(6);\n  (correct_twopows << 1, 2, 4, 8, 16, 32).finished();\n\n  MY_BOOST_CHECK_EIGEN_EQUAL(twopows, correct_twopows, tol);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "df1e60e1150a516cfeffa6d9b7a64eb26766cf60", "size": 4573, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/test_tools_eigenutil.cxx", "max_stars_repo_name": "Tomographer/tomographer", "max_stars_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T02:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T02:26:00.000Z", "max_issues_repo_path": "test/test_tools_eigenutil.cxx", "max_issues_repo_name": "Tomographer/tomographer", "max_issues_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-12T15:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-21T15:14:59.000Z", "max_forks_repo_path": "test/test_tools_eigenutil.cxx", "max_forks_repo_name": "Tomographer/tomographer", "max_forks_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-10-12T15:32:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-08T11:39:49.000Z", "avg_line_length": 33.8740740741, "max_line_length": 118, "alphanum_fraction": 0.7021648808, "num_tokens": 1355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5228858136021274}}
{"text": "//\n// Copyright 2021 Prathamesh Tagore <prathameshtagore@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/extension/io/jpeg.hpp>\n#include <boost/gil.hpp>\n\nnamespace gil = boost::gil;\n\n// Demonstrates the use of a rasterizer to generate an image of an ellipse\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 is a generalisation of the midpoint algorithm often used for drawing circle.\n// This examples also shows how to create images with various pixel depth, as well as the behaviour\n// in case of the rasterization of a curve that doesn't fit in a view.\n// See also:\n// rasterizer_circle.cpp - Demonstrates the use of a rasterizer to generate an image of a circle\n// rasterizer_line.cpp - Demonstrates the use of a rasterizer to generate an image of a line\n\n\nint main()\n{\n    // Syntax for usage :- \n    // auto rasterizer = gil::midpoint_elliptical_rasterizer{};\n    // rasterizer(img_view, colour, center, semi-axes_length);\n    // Where\n    // img_view : gil view of the image on which ellipse is to be drawn.\n    // colour : Vector containing channel intensity values for img_view. Number of colours \n    // provided must be equal to the number of channels present in img_view.\n    // center : Array containing positive integer x co-ordinate and y co-ordinate of the center\n    // respectively.\n    // semi-axes_length : Array containing positive integer lengths of horizontal semi-axis\n    // and vertical semi-axis respectively.\n\n    gil::gray8_image_t gray_buffer_image(256, 256);\n    auto gray_elliptical_rasterizer = gil::midpoint_elliptical_rasterizer{};\n    gray_elliptical_rasterizer(view(gray_buffer_image), {128}, {128, 128}, {100, 50});\n\n    gil::rgb8_image_t rgb_buffer_image(256, 256);\n    auto rgb_elliptical_rasterizer = gil::midpoint_elliptical_rasterizer{};\n    rgb_elliptical_rasterizer(view(rgb_buffer_image), {0, 0, 255}, {128, 128}, {50, 100});\n\n    gil::rgb8_image_t rgb_buffer_image_out_of_bound(256, 256);\n    auto rgb_elliptical_rasterizer_out_of_bound = gil::midpoint_elliptical_rasterizer{};\n    rgb_elliptical_rasterizer_out_of_bound(view(rgb_buffer_image_out_of_bound), {255, 0, 0},\n        {100, 100}, {160, 160});\n\n    gil::write_view(\"rasterized_ellipse_gray.jpg\", view(gray_buffer_image), gil::jpeg_tag{});\n    gil::write_view(\"rasterized_ellipse_rgb.jpg\", view(rgb_buffer_image), gil::jpeg_tag{});\n    gil::write_view(\"rasterized_ellipse_rgb_out_of_bound.jpg\", view(rgb_buffer_image_out_of_bound),\n        gil::jpeg_tag{});\n}\n", "meta": {"hexsha": "1b31a5e5de6ad2d1cb10afba13d9b01d3f8df1e5", "size": 2805, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/rasterizer_ellipse.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_ellipse.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_ellipse.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": 49.2105263158, "max_line_length": 99, "alphanum_fraction": 0.7500891266, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5228858136021273}}
{"text": "/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2017-2020 Inviwo Foundation\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 *********************************************************************************/\n\n#include <modules/eigenutils/processors/eigennormalize.h>\n\n#include <Eigen/Geometry>\n\nnamespace inviwo {\n\n// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme\nconst ProcessorInfo EigenNormalize::processorInfo_{\n    \"org.inviwo.EigenNormalize\",  // Class identifier\n    \"Matrix Normalization\",       // Display name\n    \"Eigen\",                      // Category\n    CodeState::Experimental,      // Code state\n    \"Eigen\",                      // Tags\n};\nconst ProcessorInfo EigenNormalize::getProcessorInfo() const { return processorInfo_; }\n\nEigenNormalize::EigenNormalize()\n    : Processor()\n    , in_(\"in\")\n    , out_(\"out\")\n\n    , method_(\"method\", \"Method\",\n              {{\"maxelement\", \"Max Element\", Method::MaxElement},\n               {\"minmaxelement\", \"Min/Max Element\", Method::MinMaxElement},\n               {\"normalize\", \"Normalize\", Method::Normalize}}) {\n\n    addPort(in_);\n    addPort(out_);\n\n    addProperty(method_);\n}\n\nvoid EigenNormalize::process() {\n    auto m = in_.getData();\n    switch (method_.get()) {\n        case Method::MaxElement: {\n            auto maxV = m->maxCoeff();\n            out_.setData(std::make_shared<Eigen::MatrixXf>((*m) / maxV));\n            break;\n        }\n        case Method::MinMaxElement: {\n            auto minV = m->minCoeff();\n            auto maxV = m->maxCoeff();\n            auto m2 = std::make_shared<Eigen::MatrixXf>(*m);\n            m2->array() -= minV;\n            m2->array() /= maxV - minV;\n            out_.setData(m2);\n            break;\n        }\n        case Method::Normalize:\n            out_.setData(std::make_shared<Eigen::MatrixXf>(m->normalized()));\n            break;\n    }\n}\n\n}  // namespace inviwo\n", "meta": {"hexsha": "ab4997ef709c33933580cd9ddbc44421ab151c0b", "size": 3290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/eigenutils/src/processors/eigennormalize.cpp", "max_stars_repo_name": "ImagiaViz/inviwo", "max_stars_repo_head_hexsha": "a00bb6b0551bc1cf26dc0366c827c1a557a9603d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-21T11:56:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-21T11:56:55.000Z", "max_issues_repo_path": "modules/eigenutils/src/processors/eigennormalize.cpp", "max_issues_repo_name": "ImagiaViz/inviwo", "max_issues_repo_head_hexsha": "a00bb6b0551bc1cf26dc0366c827c1a557a9603d", "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": "modules/eigenutils/src/processors/eigennormalize.cpp", "max_forks_repo_name": "ImagiaViz/inviwo", "max_forks_repo_head_hexsha": "a00bb6b0551bc1cf26dc0366c827c1a557a9603d", "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.2558139535, "max_line_length": 87, "alphanum_fraction": 0.6300911854, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5228858116613002}}
{"text": "//\n// Created by Ragesh on 5/17/18.\n//\n\n#ifndef PROJECT_RAY_TRACE_ITERATOR_HPP\n#define PROJECT_RAY_TRACE_ITERATOR_HPP\n\n/**\n * This is the header file which defines the prototype of class and functions for performing\n * ray tracing operation on laser beam rays. The main class is a iterator which is derived from\n * iterator_facade class which a part of the iterator module in the boost library.\n */\n\n\n// Boost libraries\n#include <boost/iterator/iterator_facade.hpp>\n\n// C libraries\n#include <cassert>\n#include <cmath>\n#include <cstdlib>\n#include <cstdio>\n\n\n// C++ libraries\n#include <limits>\n#include <stdexcept>\n#include <utility>\n\nnamespace NS_occupancy_grid {\n\ntemplate<typename T>\ninline int signum(T val) {\n  /// A template based implementation signum function.\n  /// T is the template type\n  /**\n   * \\param val : the input to the signum function\n   *\n   */\n  return ((T(0) < val) - (val < T(0)));\n}\n\ntemplate<typename real_t, typename int_t>\nclass ray_trace_iterator : public boost::iterator_facade<ray_trace_iterator<real_t, int_t>, std::pair<int_t, int_t>,\n                           boost::forward_traversal_tag, std::pair<int_t, int_t>>\n{\n\nprivate:\n\ntypedef typename boost::iterator_facade<ray_trace_iterator<real_t, int_t>, std::pair<int_t, int_t>,\nboost::forward_traversal_tag, std::pair<int_t, int_t>> super_t;\n// Input arguments\nreal_t px_, py_, dx_, dy_, origin_x, origin_y, cell_size_x, cell_size_y;\n\n// Intermediate variables for faster computation\n\n/// integral steps (direction) (-1, 0, 1) in both x and y\nint_t dir_x, dir_y;\n/// distance to the nearest grid line\nreal_t ex_, ey_;\n/// Maximum time to collision (from one grid line to next)\nreal_t Tx_, Ty_;\n\n// State of iterator\n/// Grid index\nint_t i_, j_;\n/// time to collision to next grid line\nreal_t tx_, ty_;\n\npublic:\n\n// constructor\nray_trace_iterator(real_t px, real_t py, real_t dx, real_t dy, real_t origin_x_, real_t origin_y_,\n    real_t cell_size_x_, real_t cell_size_y_) :\npx_{px}, py_{py},\ndx_{dx}, dy_{dy},\norigin_x{origin_x_}, origin_y{origin_y_},\ncell_size_x{cell_size_x_}, cell_size_y{cell_size_y_} {\n/**\n * The constructor for the ray trace iterator.\n *\n * \\param px : the start point x coordinate\n * \\param py : the start point y coordinate\n * \\param dx : the increment along x axis\n * \\param dy : the increment along y axis\n * \\param origin_x_ : the x coordinate of the map bottom left corner\n * \\param origin_y_ : the y coordinate of the map bottom left corner\n * \\param cell_size_x_ : the size of the cell along x\n * \\param cell_size_y_ : the size of the cell along y\n *\n */\n\n// shift the coordinates to zero the origin\npx = px - origin_x_;\npy = py - origin_y_;\n\n// grid cell containing (px,py)\ni_ = static_cast<int_t>(std::floor(px / cell_size_x_));\nj_ = static_cast<int_t>(std::floor(py / cell_size_y_));\n\ndir_x = signum(dx);\ndir_y = signum(dy);\n\n// whether the grid line we are going to hit is floor() or ceil()\n// depends on the direction in which the ray is moving\n// using the fact that ceil() = floor() + 1\nint_t floor_or_ceil_x = (dir_x > 0) ? 1 : 0;\nint_t floor_or_ceil_y = (dir_y > 0) ? 1 : 0;\n\n// uncomment lines below for debugging\n//printf(\"\\n Cell: (%i, %i), dx dy: (%f,%f) \\n\", i_, j_, dx, dy);\n\n// distance to the nearest grid line\nex_ = std::fabs((i_ + floor_or_ceil_x) * cell_size_x_ - px);\ney_ = std::fabs((j_ + floor_or_ceil_y) * cell_size_y_ - py);\n\n// (max) time to collision from one grid line to another\nTx_ = (dx == 0) ? std::numeric_limits<real_t>::infinity() : cell_size_x_ / std::fabs(dx);\nTy_ = (dy == 0) ? std::numeric_limits<real_t>::infinity() : cell_size_y_ / std::fabs(dy);\n\n// time to collision from this position\ntx_ = (dx == 0) ? std::numeric_limits<real_t>::infinity() : ex_ / fabs(dx);\nty_ = (dy == 0) ? std::numeric_limits<real_t>::infinity() : ey_ / fabs(dy);\n\nif (!((tx_ >= 0) && (ty_ >= 0))) {\nprintf(\"t:(%f, %f), direction:(%f, %f), position:(%f, %f), cell:(%d, %d), cell size:(%f, %f)\\n\",\ntx_, ty_, dx, dy, px, py, i_, j_, cell_size_x, cell_size_y);\nthrow std::logic_error(\"tx < 0 or ty < 0\");\n}\n\n// time is always positive\nassert(tx_ >= 0);\nassert(ty_ >= 0);\n\n}\n\ntypename super_t::reference dereference() const {\n  return std::make_pair(i_, j_);\n}\n\nbool equal(ray_trace_iterator it) const {\n  /// function to check if the objects are equal\n  return ((it.i_ == i_) && (it.j_ == j_) &&\n      (it.tx_ == tx_) && (it.ty_ == ty_) &&\n      (it.Tx_ == Tx_) && (it.Ty_ == Ty_) &&\n      (it.dir_x == dir_x) && (it.dir_y == dir_y));\n}\n\n/// overload the == operator\n//      friend bool operator== (const ray_trace_iterator<real_t, int_t>& it1,\n//                              const ray_trace_iterator<real_t, int_t>& it2);\nfriend bool operator==(const ray_trace_iterator<real_t, int_t> &it1, const ray_trace_iterator<real_t, int_t> &it2) {\n  return ((it1.i_ == it2.i_) && (it1.j_ == it2.j_) &&\n      (it1.tx_ == it2.tx_) && (it1.ty_ == it2.ty_) &&\n      (it1.Tx_ == it2.Tx_) && (it1.Ty_ == it2.Ty_) &&\n      (it1.dir_x == it2.dir_x) && (it1.dir_y == it2.dir_y));\n}\n\nvoid increment();\n\nstd::pair<real_t, real_t> real_position() const;\n\n};\n\ntemplate<typename real_t, typename int_t>\nvoid ray_trace_iterator<real_t, int_t>::increment() {\n  if (tx_ < ty_) {\n    i_ += dir_x;\n    ty_ = ty_ - tx_;\n    tx_ = Tx_;\n  } else {\n    j_ += dir_y;\n    tx_ = tx_ - ty_;\n    ty_ = Ty_;\n  }\n}\n\ntemplate<typename real_t, typename int_t>\nstd::pair<real_t, real_t> ray_trace_iterator<real_t, int_t>::real_position() const {\n\n  // whether the grid line we are going to hit is floor() or ceil()\n  // depends on the direction ray is moving\n  int_t floor_or_ceil_x = (dir_x > 0) ? 1 : 0;\n  int_t floor_or_ceil_y = (dir_y > 0) ? 1 : 0;\n\n  real_t ex = (dx_ == 0) ? ex_ // error is same as starting point\n                         : tx_ * fabs(dx_);\n  real_t ey = (dy_ == 0) ? ey_\n                         : ty_ * fabs(dy_);\n\n  real_t px = (i_ + floor_or_ceil_x) * cell_size_x - ex * dir_x;\n  real_t py = (j_ + floor_or_ceil_y) * cell_size_y - ey * dir_y;\n\n  // shift coordinates\n  px = px + origin_x;\n  py = py + origin_y;\n\n  return std::make_pair(px, py);\n}\n\n}\n\n\n#endif //PROJECT_RAY_TRACE_ITERATOR_HPP\n", "meta": {"hexsha": "a1f0812b73de984966c7597a048ab95e3f2b0583", "size": 6107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ray_trace_iterator.hpp", "max_stars_repo_name": "ragesh88/ros_swarm_mapping_TRO", "max_stars_repo_head_hexsha": "1f649a1e78027ac1dfd83f1dbf63a2aec0a9754c", "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/ray_trace_iterator.hpp", "max_issues_repo_name": "ragesh88/ros_swarm_mapping_TRO", "max_issues_repo_head_hexsha": "1f649a1e78027ac1dfd83f1dbf63a2aec0a9754c", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/ray_trace_iterator.hpp", "max_forks_repo_name": "ragesh88/ros_swarm_mapping_TRO", "max_forks_repo_head_hexsha": "1f649a1e78027ac1dfd83f1dbf63a2aec0a9754c", "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.7902439024, "max_line_length": 116, "alphanum_fraction": 0.6594072376, "num_tokens": 1842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5228858107533289}}
{"text": "#ifndef __SCHEME_UTILITY_RATIONALTYPE\n#define __SCHEME_UTILITY_RATIONALTYPE\n#include \"utility/bigint.hpp\"\n#include <boost/operators.hpp>\n#include <iosfwd>\n\nclass RationalType: public\n                    boost::totally_ordered<RationalType, \n                    boost::arithmetic<RationalType>\n                    >\n{\n    BigInt up_, down_;\n    void reduce();\n    void lazyreduce();\n    public:\n    RationalType();\n    RationalType(const BigInt& num);\n    RationalType(const BigInt& up, const BigInt& down);\n    explicit RationalType(double a);\n    RationalType& operator += (const RationalType& b);\n    RationalType& operator -= (const RationalType& b);\n    RationalType& operator *= (const RationalType& b);\n    RationalType& operator /= (const RationalType& b);\n    bool operator == (const RationalType& b) const;\n    bool operator < (const RationalType& b) const;\n    friend std::istream& operator >>(std::istream& i, RationalType& a);\n    friend std::ostream& operator <<(std::ostream& o, const RationalType& a);\n    operator long double() const;\n    RationalType operator -();\n    bool getSign() const;\n    bool isInt() const;\n    BigInt getUp() const;\n    BigInt getDown() const;\n    BigInt toInt() const;\n};\n\n\n#endif\n", "meta": {"hexsha": "cbed9053b455ffe9c425a28e6a5f6249a2ea7859", "size": 1224, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utility/rationaltype.hpp", "max_stars_repo_name": "htfy96/htscheme", "max_stars_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T01:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T10:45:01.000Z", "max_issues_repo_path": "utility/rationaltype.hpp", "max_issues_repo_name": "htfy96/htscheme", "max_issues_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utility/rationaltype.hpp", "max_forks_repo_name": "htfy96/htscheme", "max_forks_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_forks_repo_licenses": ["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.3846153846, "max_line_length": 77, "alphanum_fraction": 0.6633986928, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5228858040228771}}
{"text": "/*\n * Chaos \n *\n * Copyright 2015 Operating Systems Laboratory EPFL\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 <cstdio>\n#include <boost/thread/thread.hpp>\n#include \"defs.h\"\n#include \"options.h\"\n#include \"util.h\"\n#include \"output.h\"\n#include \"prng/splittable_mrg.h\"\n#include \"prng/utils.h\"\n\nstatic void generate_edge(mrg_state *pstate, const int scale,\n                          double a, double b, double c, double d,\n                          struct edge_struct *edge) {\n  vertex_t i = 0, j = 0;\n  vertex_t bit = (vertex_t) 1 << (scale - 1);\n\n  while (true) {\n    double r = mrg_get_double_orig(pstate);\n    if (r > a) {               /* outside quadrant 1 */\n      if (r <= a + b)          /* in quadrant 2 */\n        j |= bit;\n      else if (r <= a + b + c) /* in quadrant 3 */\n        i |= bit;\n      else {                   /* in quadrant 4 */\n        j |= bit;\n        i |= bit;\n      }\n    }\n\n    if (1 == bit) break;\n\n    /*\n     * Noise is introduced by modifying the probabilites by +/- 5%\n     * and normalising them.\n     */\n#ifdef NOISE\n    r  = mrg_get_double_orig(pstate);\n    a *= 0.95 + r/10;\n    r  = mrg_get_double_orig(pstate);\n    b *= 0.95 + r/10;\n    r  = mrg_get_double_orig(pstate);\n    c *= 0.95 + r/10;\n    r  = mrg_get_double_orig(pstate);\n    d *= 0.95 + r/10;\n\n    double norm = 1.0 / (a + b + c + d);\n    a *= norm;\n    b *= norm;\n    c *= norm;\n    d = 1.0 - (a + b + c);\n#endif\n\n    /* Iterates scale times. */\n    bit >>= 1;\n  }\n\n  edge->src = i;\n  edge->dst = j;\n#ifdef WEIGHT\n  edge->weight = (value_t)mrg_get_double_orig(pstate);\n#endif\n}\n\n// ugly, but max 10 args to functions allowed in boost::thread\nstatic unsigned int xscale_interval;\nstatic unsigned int xscale_node;\n\nstatic void generate(thread_buffer *buffer, const mrg_state &state, const int\nscale, const edge_t start, const edge_t end,\n                     const double a, const double b, const double c, /*const\n                     double d,*/ const bool symmetric) {\n  const double d = 1 - (a + b + c);\n  for (edge_t ei = start; ei < end; ++ei) {\n    if (ei % xscale_interval != xscale_node) { continue; }\n    mrg_state new_state = state;\n    mrg_skip(&new_state, 0, ei, 0);\n    struct edge_struct *edge = buffer->edge_struct();\n    generate_edge(&new_state, scale, a, b, c, d, edge);\n    if (symmetric) {\n      struct edge_struct *reverse_edge = buffer->edge_struct();\n      reverse_edge->src = edge->dst;\n      reverse_edge->dst = edge->src;\n#ifdef WEIGHT\n      reverse_edge->weight = edge->weight;\n#endif\n    }\n  }\n  buffer->flush();\n}\n\nint main(int argc, char **argv) {\n  struct options options;\n  if (process_options(argc, argv, true, &options) != 0)\n    return 0;\n\n  if (options.rmat.a + options.rmat.b + options.rmat.c >= 1) {\n    printf(\"Error: The sum of probabilities must equal 1\\n\");\n    return 0;\n  }\n  double d = 1 - (options.rmat.a + options.rmat.b + options.rmat.c);\n  xscale_node = options.rmat.xscale_node;\n  xscale_interval = options.rmat.xscale_interval;\n  uint_fast32_t seed[5];\n  make_mrg_seed(options.rng.userseed1, options.rng.userseed2, seed);\n  mrg_state state;\n  mrg_seed(&state, seed);\n  //mrg_skip(&new_state, 50, 7, 0); // Do an initial skip?\n\n  edge_t total_edges = options.rmat.edges;\n  if ((total_edges % options.rmat.xscale_interval) > options.rmat.xscale_node) {\n    total_edges /= options.rmat.xscale_interval;\n    total_edges++;\n  }\n  else {\n    total_edges /= options.rmat.xscale_interval;\n  }\n\n  if (options.global.symmetric) {\n    total_edges *= 2;\n  }\n\n  printf(\"Generator type: R-MAT\\n\");\n  printf(\"Scale: %d (%\" PRIu64 \" vertices)\\n\", options.rmat.scale, ((uint64_t) 1 << options.rmat.scale));\n  printf(\"Edges: %\" PRIet \"\\n\", total_edges);\n  printf(\"Probabilities: A=%4.2f, B=%4.2f, C=%4.2f, D=%4.2f\\n\", options.rmat.a, options.rmat.b, options.rmat.c, d);\n\n  double start = get_time();\n\n  // io thread\n  size_t buffer_size = calculate_buffer_size(options.global.buffer_size);\n  buffer_queue flushq;\n  buffer_manager manager(&flushq, options.global.buffers_per_thread, buffer_size);\n  io_thread_func io_func(options.global.graphname.c_str(), total_edges, &flushq, &manager, buffer_size);\n  boost::thread io_thread(boost::ref(io_func));\n\n  // worker threads\n  int nthreads = options.global.nthreads;\n  edge_t edges_per_thread = options.rmat.edges / nthreads;\n  threadid_t *workers[nthreads];\n  boost::thread *worker_threads[nthreads];\n  for (int i = 0; i < nthreads; i++) {\n    workers[i] = new threadid_t(i);\n    thread_buffer *buffer = manager.register_thread(*workers[i]);\n    // last thread gets the remainder (if any)\n    edge_t start = i * edges_per_thread;\n    edge_t end = (i == nthreads - 1) ? (options.rmat.edges) : ((i + 1) * edges_per_thread);\n    worker_threads[i] = new boost::thread(generate, buffer,\n                                          state, options.rmat.scale, start, end,\n                                          options.rmat.a, options.rmat.b, options.rmat.c, /*d,*/\n                                          options.global.symmetric);\n  }\n\n  // Wait until work completes\n  for (int i = 0; i < nthreads; i++) {\n    worker_threads[i]->join();\n  }\n  io_func.stop();\n  io_thread.join();\n\n  // cleanup\n  for (int i = 0; i < nthreads; i++) {\n    manager.unregister_thread(*workers[i]);\n    delete worker_threads[i];\n    delete workers[i];\n  }\n\n  double elapsed = get_time() - start;\n  printf(\"Generation time: %fs\\n\", elapsed);\n\n  make_ini_file(options.global.graphname.c_str(), (uint64_t) 1 << options.rmat.scale, total_edges);\n\n  return 0;\n}\n\n", "meta": {"hexsha": "8d52a80b904a16a5af5b4bb7bb5adb47461fbb2c", "size": 6037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "generators/rmat.cpp", "max_stars_repo_name": "epfl-labos/chaos", "max_stars_repo_head_hexsha": "5d091343f62393cb7dfc92a357e2fc7ef95d1855", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 55.0, "max_stars_repo_stars_event_min_datetime": "2015-10-22T22:45:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T12:55:20.000Z", "max_issues_repo_path": "generators/rmat.cpp", "max_issues_repo_name": "epfl-labos/chaos", "max_issues_repo_head_hexsha": "5d091343f62393cb7dfc92a357e2fc7ef95d1855", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2016-04-21T12:56:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-07T00:58:41.000Z", "max_forks_repo_path": "generators/rmat.cpp", "max_forks_repo_name": "epfl-labos/chaos", "max_forks_repo_head_hexsha": "5d091343f62393cb7dfc92a357e2fc7ef95d1855", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2015-11-09T08:07:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T12:55:45.000Z", "avg_line_length": 31.4427083333, "max_line_length": 115, "alphanum_fraction": 0.6258075203, "num_tokens": 1668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5228857963844541}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/assert.hpp>\n#include <boost/hana/pair.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [make<Pair>]\nBOOST_HANA_CONSTEXPR_CHECK(first(make<Pair>(1, 'x')) == 1);\nBOOST_HANA_CONSTEXPR_CHECK(second(make<Pair>(1, 'x')) == 'x');\n//! [make<Pair>]\n\n}{\n\n//! [make_pair]\nBOOST_HANA_CONSTEXPR_CHECK(make_pair(1, 'x') == make<Pair>(1, 'x'));\n//! [make_pair]\n\n}{\n\n//! [comparable]\nBOOST_HANA_CONSTEXPR_CHECK(make<Pair>(1, 'x') == make<Pair>(1, 'x'));\nBOOST_HANA_CONSTEXPR_CHECK(make<Pair>(2, 'x') != make<Pair>(1, 'x'));\nBOOST_HANA_CONSTEXPR_CHECK(make<Pair>(1, 'y') != make<Pair>(1, 'x'));\n//! [comparable]\n\n}{\n\n//! [orderable]\nBOOST_HANA_CONSTEXPR_CHECK(make<Pair>(1, 'x') < make<Pair>(1, 'y'));\nBOOST_HANA_CONSTEXPR_CHECK(make<Pair>(1, 'x') < make<Pair>(10, 'x'));\nBOOST_HANA_CONSTEXPR_CHECK(make<Pair>(1, 'y') < make<Pair>(10, 'x'));\n//! [orderable]\n\n}{\n\n//! [foldable]\nBOOST_HANA_CONSTEXPR_CHECK(foldl(make<Pair>(1, 3), 0, plus) == 4);\nBOOST_HANA_CONSTEXPR_CHECK(foldr(make<Pair>(1, 3), 0, minus) == -2);\n//! [foldable]\n\n}{\n\n//! [product]\nBOOST_HANA_CONSTEXPR_CHECK(first(make<Pair>(1, 'x')) == 1);\nBOOST_HANA_CONSTEXPR_CHECK(second(make<Pair>(1, 'x')) == 'x');\n//! [product]\n\n}\n\n}\n", "meta": {"hexsha": "b087415288befd73a7c547565544e1b49ae47815", "size": 1378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/pair.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/pair.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/pair.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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.9666666667, "max_line_length": 78, "alphanum_fraction": 0.6560232221, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.522863571391082}}
{"text": "//=======================================================================\n// Copyright 2007 Aaron Windsor\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#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map.hpp>\n#include <boost/ref.hpp>\n#include <vector>\n\n#include <boost/graph/planar_canonical_ordering.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n\n\nusing namespace boost;\n\n\nint main(int argc, char** argv)\n{\n\n  typedef adjacency_list\n    < vecS,\n      vecS,\n      undirectedS,\n      property<vertex_index_t, int>,\n      property<edge_index_t, int>\n    > \n    graph;\n\n  // Create a maximal planar graph on 6 vertices\n  graph g(6);\n\n  add_edge(0,1,g);\n  add_edge(1,2,g);\n  add_edge(2,3,g);\n  add_edge(3,4,g);\n  add_edge(4,5,g);\n  add_edge(5,0,g);\n\n  add_edge(0,2,g);\n  add_edge(0,3,g);\n  add_edge(0,4,g);\n\n  add_edge(1,3,g);\n  add_edge(1,4,g);\n  add_edge(1,5,g);\n\n  // Initialize the interior edge index\n  property_map<graph, edge_index_t>::type e_index = get(edge_index, g);\n  graph_traits<graph>::edges_size_type edge_count = 0;\n  graph_traits<graph>::edge_iterator ei, ei_end;\n  for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n    put(e_index, *ei, edge_count++);\n  \n\n  // Test for planarity - we know it is planar, we just want to \n  // compute the planar embedding as a side-effect\n  typedef std::vector< graph_traits<graph>::edge_descriptor > vec_t;\n  std::vector<vec_t> embedding(num_vertices(g));\n  if (boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n                                   boyer_myrvold_params::embedding = \n                                       &embedding[0]\n                                   )\n      )\n    std::cout << \"Input graph is planar\" << std::endl;\n  else\n    std::cout << \"Input graph is not planar\" << std::endl;\n\n  typedef std::vector<graph_traits<graph>::vertex_descriptor> \n    ordering_storage_t;\n  \n  ordering_storage_t ordering;\n  planar_canonical_ordering(g, &embedding[0], std::back_inserter(ordering));\n\n  ordering_storage_t::iterator oi, oi_end;\n  oi_end = ordering.end();\n  std::cout << \"The planar canonical ordering is: \";\n  for(oi = ordering.begin(); oi != oi_end; ++oi)\n    std::cout << *oi << \" \";\n  std::cout << std::endl;\n\n  return 0;  \n}\n", "meta": {"hexsha": "04f96635c473c6228e97a57e0797b1aac38bc5e0", "size": 2524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/canonical_ordering.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/graph/example/canonical_ordering.cpp", "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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/graph/example/canonical_ordering.cpp", "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": 28.3595505618, "max_line_length": 76, "alphanum_fraction": 0.6192551506, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5228635631048913}}
{"text": "// Copyright (C) 2006-2009 Dmitry Bufistov and Andrey Parfenov\r\n\r\n// Use, modification and distribution is subject to the Boost Software\r\n// License, 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 <cassert>\r\n#include <ctime>\r\n#include <boost/random/mersenne_twister.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/random.hpp>\r\n#include <boost/graph/howard_cycle_ratio.hpp>\r\n\r\n/**\r\n * @author Dmitry Bufistov\r\n * @author Andrey Parfenov\r\n */\r\n\r\nusing namespace boost;\r\ntypedef adjacency_list<\r\n    listS, listS, directedS,\r\n    property<vertex_index_t, int>,\r\n    property<\r\n        edge_weight_t, double, property<edge_weight2_t, double>\r\n    >\r\n> grap_real_t;\r\n\r\ntemplate <typename TG>\r\nvoid gen_rand_graph(TG &g, size_t nV, size_t nE)\r\n{\r\n    g.clear();\r\n    mt19937 rng;\r\n    rng.seed(uint32_t(time(0)));\r\n    boost::generate_random_graph(g, nV, nE, rng, true, true);\r\n    boost::uniform_real<> ur(-1,10);\r\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<> >   ew1rg(rng, ur);\r\n    randomize_property<edge_weight_t>(g, ew1rg);\r\n    boost::uniform_int<size_t> uint(1,5);\r\n    boost::variate_generator<boost::mt19937&, boost::uniform_int<size_t> >      ew2rg(rng, uint);\r\n    randomize_property<edge_weight2_t>(g, ew2rg);\r\n}\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n    using std::cout;\r\n    using std::endl;\r\n    const double epsilon = 0.0000001;\r\n    double min_cr, max_cr; ///Minimum and maximum cycle ratio\r\n    typedef std::vector<graph_traits<grap_real_t>::edge_descriptor> ccReal_t;\r\n    ccReal_t cc; ///critical cycle\r\n\r\n    grap_real_t tgr;\r\n    property_map<grap_real_t, vertex_index_t>::type vim = get(vertex_index, tgr);\r\n    property_map<grap_real_t, edge_weight_t>::type ew1 = get(edge_weight, tgr);\r\n    property_map<grap_real_t, edge_weight2_t>::type ew2 = get(edge_weight2, tgr);\r\n\r\n    gen_rand_graph(tgr, 1000, 30000);\r\n    cout << \"Vertices number: \" << num_vertices(tgr) << endl;\r\n    cout << \"Edges number: \" << num_edges(tgr) << endl;\r\n    int i = 0;\r\n    graph_traits<grap_real_t>::vertex_iterator vi, vi_end;\r\n    for (boost::tie(vi, vi_end) = vertices(tgr); vi != vi_end; vi++) {\r\n        vim[*vi] = i++; ///Initialize vertex index property\r\n    }\r\n    max_cr = maximum_cycle_ratio(tgr, vim, ew1, ew2);\r\n    cout << \"Maximum cycle ratio is \" << max_cr << endl;\r\n    min_cr = minimum_cycle_ratio(tgr, vim, ew1, ew2, &cc);\r\n    cout << \"Minimum cycle ratio is \" << min_cr << endl;\r\n    std::pair<double, double> cr(.0,.0);\r\n    cout << \"Critical cycle:\\n\";\r\n    for (ccReal_t::iterator itr = cc.begin(); itr != cc.end(); ++itr)\r\n    {\r\n        cr.first += ew1[*itr];\r\n        cr.second += ew2[*itr];\r\n        std::cout << \"(\" << vim[source(*itr, tgr)] << \",\" <<\r\n            vim[target(*itr, tgr)] << \") \";\r\n    }\r\n    cout << endl;\r\n    assert(std::abs(cr.first / cr.second - min_cr) < epsilon);\r\n    return EXIT_SUCCESS;\r\n}\r\n\r\n", "meta": {"hexsha": "0f4528e7c75a7b5e9c084d1c2ee63de397ef07e7", "size": 3006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/cycle_ratio_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/cycle_ratio_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/cycle_ratio_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": 35.7857142857, "max_line_length": 98, "alphanum_fraction": 0.6440452428, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5228635586207356}}
{"text": "/*\n\nCopyright (c) 2013  Ghassen Hamrouni\n\nAbstract:\n\nThis module provides a weighted undirected graph G (possibly with loops)\n\nAuthor:\n\nGhassen Hamrouni <ghamrouni.iptech@gmail.com> 23-07-2013\n\nRevision History:\n\n*/\n\n#ifndef R_1_PUBLIC_GRAPH_H_\n#define R_1_PUBLIC_GRAPH_H_\n\n#include <Eigen/Dense>\n#include \"MinCutClusterAnalyzer.hpp\"\n#include \"ClusterCollection.hpp\"\n\n#include <random>\n#include <fstream>\n#include <string>\n#include <set>\n#include <unordered_set>\n\nnamespace R1 {\n\n\t//\n\t// Graph: A weighted undirected graph G (possibly with loops)\n\t//\n\tclass Graph {\n\n\tpublic:\n\n\t\tvirtual ~Graph() {}\n\n\t\tGraph() {}\n\n\t\tGraph(int NVertex) : n_vertex(NVertex), n_edges(0) {\n\t\t\tadjacency_matrix = Eigen::MatrixXf(NVertex, NVertex);\n\t\t\tadjacency_matrix.setZero();\n\t\t}\n\n\t\tvoid setSize(int NVertex) {\n\t\t\tn_vertex = (NVertex);\n\t\t\tn_edges  = (0);\n\t\t\tadjacency_matrix = Eigen::MatrixXf(NVertex, NVertex);\n\t\t\tadjacency_matrix.setZero();\n\t\t}\n\n\t\tvoid connect(int u, int v) {\n\t\t\tif (u >= n_vertex) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (v >= n_vertex) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tadjacency_matrix(u, v) = 1.0;\n\t\t\tadjacency_matrix(v, u) = 1.0;\n\n\t\t\tn_edges = n_edges + 1;\n\t\t}\n\n\t\tvoid connect(int u, int v, float weight) {\n\t\t\tif (u >= n_vertex) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (v >= n_vertex) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tadjacency_matrix(u, v) = weight;\n\t\t\tadjacency_matrix(v, u) = weight;\n\n\t\t\tn_edges = n_edges + 1;\n\t\t}\n\n\t\tfloat degree(int v) {\n\t\t\tfloat n = 0.0f;\n\n\t\t\tif (v >= n_vertex) {\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tfor (int u = 0; u < n_vertex; u++) {\n\t\t\t\tn += adjacency_matrix(u, v);\n\t\t\t}\n\n\t\t\treturn n;\n\t\t}\n\n\t\tbool is_connected(int u, int v) {\n\t\t\tif (u >= n_vertex) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (v >= n_vertex) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn (adjacency_matrix(u, v) >= 1.0);\n\t\t}\n\n\t\t// A graph is said to be nontrivial if it contains at least\n\t\t// one edge.\n\t\tbool is_trivial() {\n\t\t\treturn n_edges == 0;\n\t\t}\n\n\t\tvoid generateRandomSpanningTree()\n\t\t{\n\t\t\tstd::random_device rd;\n\t\t\tstd::mt19937 gen(rd());\n\t\t\tstd::uniform_int_distribution<> vdist(0, n_vertex - 1);\n\t\t\tint current_vertex = vdist(gen);\n\n\t\t\tstd::vector<int> P;\n\t\t\tstd::vector<int> V;\n\n\t\t\tfor (int i = 0; i < n_vertex; i++)\n\t\t\t{\n\t\t\t\tif (i != current_vertex)\n\t\t\t\t\tP.push_back(i);\n\t\t\t}\n\n\t\t\tV.push_back(current_vertex);\n\n\t\t\twhile (!P.empty())\n\t\t\t{\n\t\t\t\tstd::uniform_int_distribution<> distP(0, P.size() - 1);\n\n\t\t\t\tint j_index = distP(gen);\n\t\t\t\tint j = P[j_index];\n\n\t\t\t\tstd::swap(P[j_index], P.back());\n\t\t\t\tP.pop_back();\n\n\t\t\t\tstd::uniform_int_distribution<> distV(0, V.size() - 1);\n\n\t\t\t\tint u_index = distV(gen);\n\t\t\t\tint u = V[u_index];\n\n\t\t\t\tconnect(u, j);\n\t\t\t\t\n\t\t\t\tV.push_back(j);\n\t\t\t}\n\t\t}\n\n\t\tvoid generateUniformRandomSpanningTree()\n\t\t{\n\t\t\tstd::random_device rd;\n\t\t\tstd::mt19937 gen(rd());\n\t\t\tstd::uniform_int_distribution<> vdist(0, n_vertex - 1);\n\n\t\t\tint current_vertex = vdist(gen);\n\t\t\tstd::vector<int> V;\n\n\t\t\tint n_edge = n_vertex - 1;\n\n\t\t\tfor (int i = 0; i < n_vertex; i++)\n\t\t\t{\n\t\t\t\tV.push_back(0);\n\t\t\t}\n\n\t\t\tV[current_vertex] = 1;\n\n\t\t\twhile (n_edge)\n\t\t\t{\n\t\t\t\tint j = vdist(gen);\n\n\t\t\t\tif (V[j] == 0)\n\t\t\t\t{\n\t\t\t\t\tV[j] = 1;\n\t\t\t\t\tconnect(current_vertex, j);\n\t\t\t\t\tn_edge--;\n\t\t\t\t}\n\n\t\t\t\tcurrent_vertex = j;\n\t\t\t}\n\t\t}\n\n\t\tvoid generateRandomGraph(int n_random_edges)\n\t\t{\n\t\t\tstd::random_device rd;\n\t\t\tstd::mt19937 gen(rd());\n\t\t\tstd::uniform_int_distribution<> vdist(0, n_vertex - 1);\n\t\t\t\n\t\t\twhile (n_random_edges > 0)\n\t\t\t{\n\t\t\t\tint i = vdist(gen);\n\t\t\t\tint j = vdist(gen);\n\n\t\t\t\tconnect(i, j);\n\n\t\t\t\tn_random_edges--;\n\t\t\t}\n\t\t}\n\n\t\tClusterCollection cluster(double alpha = 0.5)\n\t\t{\n\t\t\treturn MinCutClusterAnalyzer::cluster(adjacency_matrix, alpha);\n\t\t}\n\n\t\tstd::vector<ClusterCollection> hierarchicalCluster(double alpha = 0.5, double decay = 0.5)\n\t\t{\n\t\t\tstd::vector<ClusterCollection> clusters;\n\t\t\tint prev_cluster_nb = 0;\n\n\t\t\tfor (int i = 0; ; i++)\n\t\t\t{\n\t\t\t\tClusterCollection cl = MinCutClusterAnalyzer::cluster(adjacency_matrix, alpha);\n\n\t\t\t\tif (cl.size != prev_cluster_nb)\n\t\t\t\t{\n\t\t\t\t\tprev_cluster_nb = cl.size;\n\t\t\t\t\tclusters.push_back(cl);\n\t\t\t\t}\n\n\t\t\t\tif (cl.size == 1) // One cluster\n\t\t\t\t\tbreak;\n\n\t\t\t\tif (alpha <= 0.0)\n\t\t\t\t\tbreak;\n\n\t\t\t\talpha *= decay;\n\t\t\t}\n\n\t\t\treturn clusters;\n\t\t}\n\n\tprotected:\n\t\tEigen::MatrixXf adjacency_matrix;\n\n\t\tint\t\tn_vertex;\n\t\tint\t\tn_edges;\n\n\t};\n}\n#endif", "meta": {"hexsha": "154b81aaff3b97ff55a054e0ec56fd090220ffe7", "size": 4183, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Graph.hpp", "max_stars_repo_name": "GHamrouni/R7", "max_stars_repo_head_hexsha": "338ab32e7fc952c5ba87cf17e9b69c8dd18064e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-07-21T19:10:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-07T00:02:57.000Z", "max_issues_repo_path": "src/Graph.hpp", "max_issues_repo_name": "GHamrouni/R7", "max_issues_repo_head_hexsha": "338ab32e7fc952c5ba87cf17e9b69c8dd18064e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Graph.hpp", "max_forks_repo_name": "GHamrouni/R7", "max_forks_repo_head_hexsha": "338ab32e7fc952c5ba87cf17e9b69c8dd18064e5", "max_forks_repo_licenses": ["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.0040650407, "max_line_length": 92, "alphanum_fraction": 0.6057853215, "num_tokens": 1310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5228635548187005}}
{"text": "//==============================================================================\n//         Copyright 2015 J.T. Lapreste\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/exponential/include/functions/significants.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <nt2/sdk/meta/as_floating.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n\nNT2_TEST_CASE_TPL ( significants,  BOOST_SIMD_REAL_TYPES)\n{\n\n  using nt2::significants;\n  using nt2::tag::significants_;\n  typedef typename nt2::meta::as_integer<T>::type iT;\n  typedef typename boost::dispatch::meta::call<significants_(T, iT)>::type r_t;\n  typedef T wished_r_t;\n\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS( r_t, wished_r_t );\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_ULP_EQUAL(significants(nt2::Inf<T>(), 1), nt2::Inf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::Minf<T>(), 1), nt2::Minf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::Nan<T>(), 1), nt2::Nan<r_t>(), 0.5);\n#endif\n  NT2_TEST_ULP_EQUAL(significants(T(0), 1), T(0), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(T(25.34), 1), T(30), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(T(25.34), 2), T(25), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(T(25.34), 3), T(25.3), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(T(25.34), 4), T(25.34), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(T(-25.34), 1), T(-30), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(T(-25.34), 2), T(-25), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(T(-25.34), 3), T(-25.3), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(T(-25.34), 4), T(-25.34), 0.5);\n}\n\n", "meta": {"hexsha": "6a171d88a0cc0a53ede5ee0ccedc2537bd106e52", "size": 2042, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/unit/scalar/significants.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/exponential/unit/scalar/significants.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/exponential/unit/scalar/significants.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 40.84, "max_line_length": 80, "alphanum_fraction": 0.6376101861, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.522863545850389}}
{"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//[distance\r\n//` Shows calculation of distance of point to some other geometries\r\n\r\n#include <iostream>\r\n#include <list>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/linestring.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/multi/geometries/multi_point.hpp>\r\n#include <boost/geometry/multi/geometries/multi_polygon.hpp>\r\n\r\n#include <boost/geometry/io/wkt/wkt.hpp>\r\n\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    typedef boost::geometry::model::polygon<point_type> polygon_type;\r\n    typedef boost::geometry::model::linestring<point_type> linestring_type;\r\n    typedef boost::geometry::model::multi_point<point_type> multi_point_type;\r\n\r\n    point_type p(1,2);\r\n    polygon_type poly;\r\n    linestring_type line;\r\n    multi_point_type mp;\r\n\r\n    boost::geometry::read_wkt(\r\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)\"\r\n            \"(4.0 2.0, 4.2 1.4, 4.8 1.9, 4.4 2.2, 4.0 2.0))\", poly);\r\n    line.push_back(point_type(0,0));\r\n    line.push_back(point_type(0,3));\r\n    mp.push_back(point_type(0,0));\r\n    mp.push_back(point_type(3,3));\r\n\r\n    std::cout \r\n        << \"Point-Poly: \" << boost::geometry::distance(p, poly) << std::endl\r\n        << \"Point-Line: \" << boost::geometry::distance(p, line) << std::endl\r\n        << \"Point-MultiPoint: \" << boost::geometry::distance(p, mp) << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[distance_output\r\n/*`\r\nOutput:\r\n[pre\r\nPoint-Poly: 1.22066\r\nPoint-Line: 1\r\nPoint-MultiPoint: 2.23607\r\n]\r\n*/\r\n//]\r\n\r\n", "meta": {"hexsha": "4f79d4f613c1f9ac1e584b467f75758cdfac5368", "size": 2035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/distance.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/algorithms/distance.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/algorithms/distance.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": 29.4927536232, "max_line_length": 108, "alphanum_fraction": 0.6624078624, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5228635451682679}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/include/functions/sqrt1pm1.hpp>\n\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <complex>\n#include <nt2/sdk/complex/complex.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/basic.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/sqrt_2.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/i.hpp>\n\nNT2_TEST_CASE_TPL ( sqrt1pm1_real,  NT2_REAL_TYPES)\n{\n  using nt2::sqrt1pm1;\n  using nt2::tag::sqrt1pm1_;\n  typedef typename std::complex<T> cT;\n  typedef typename nt2::meta::call<sqrt1pm1_(cT)>::type r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, cT);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n    NT2_TEST_ULP_EQUAL(sqrt1pm1(nt2::Inf<cT>()),  cT(nt2::Inf<T>()), 0);\n    NT2_TEST_ULP_EQUAL(sqrt1pm1(nt2::Minf<cT>()),  cT(-1, nt2::Inf<T>()), 0);\n    NT2_TEST_ULP_EQUAL(sqrt1pm1(nt2::Nan<cT>()),  cT(nt2::Nan<T>(), nt2::Nan<T>()), 0);\n#endif\n    NT2_TEST_ULP_EQUAL(sqrt1pm1(nt2::Mone<cT>()),  cT(nt2::Mone<T>()), 0);\n    NT2_TEST_ULP_EQUAL(sqrt1pm1(nt2::One<cT>()),  cT(nt2::Sqrt_2<T>()-nt2::One<T>()), 2);\n    NT2_TEST_ULP_EQUAL(sqrt1pm1(cT(nt2::Eps<T>())), cT(nt2::Eps<T>()*nt2::Half<T>()), 2);\n    NT2_TEST_ULP_EQUAL(sqrt1pm1(cT(-1, 2)), cT(0, 1), 2);\n    NT2_TEST_ULP_EQUAL(sqrt1pm1(nt2::Zero<cT>()),  cT(nt2::Zero<T>()), 0);\n}\n", "meta": {"hexsha": "2a2a2986a507ff726d245c5c86f2c6e1a136a026", "size": 2359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/exponential/unit/scalar/sqrt1pm1.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/type/complex/exponential/unit/scalar/sqrt1pm1.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/type/complex/exponential/unit/scalar/sqrt1pm1.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 42.125, "max_line_length": 89, "alphanum_fraction": 0.6422212802, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5228635410251726}}
{"text": "//=========================================================================\n//\n// Copyright 2018 Kitware, Inc.\n// Author: Guilbert Pierre (spguilbert@gmail.com)\n//         Laurenson Nick (nlaurenson5@gmail.com)\n// Date: 03-27-2018\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 \"SpinningSensorKeypointExtractor.h\"\n\n#include <numeric>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nnamespace {\n//-----------------------------------------------------------------------------\ntemplate <typename T>\nstd::vector<size_t> sortIdx(const std::vector<T> &v)\n{\n  // initialize original index locations\n  std::vector<size_t> idx(v.size());\n  std::iota(idx.begin(), idx.end(), 0);\n\n  // sort indexes based on comparing values in v\n  std::sort(idx.begin(), idx.end(),\n       [&v](size_t i1, size_t i2) {return v[i1] > v[i2];});\n\n  return idx;\n}\n\n//-----------------------------------------------------------------------------\nclass LineFitting\n{\npublic:\n  // Fitting using PCA\n  bool FitPCA(std::vector<Eigen::Vector3d >& points);\n\n  // Futting using very local line and\n  // check if this local line is consistent\n  // in a more global neighborhood\n  bool FitPCAAndCheckConsistency(std::vector<Eigen::Vector3d >& points);\n\n  // Poor but fast fitting using\n  // extremities of the distribution\n  void FitFast(std::vector<Eigen::Vector3d >& points);\n\n  // Direction and position\n  Eigen::Vector3d Direction;\n  Eigen::Vector3d Position;\n  Eigen::Matrix3d SemiDist;\n  Eigen::Matrix3d I3 = Eigen::Matrix3d::Identity();\n  double MaxDistance = 0.02;\n  double MaxSinAngle = 0.65;\n};\n\n//-----------------------------------------------------------------------------\nbool LineFitting::FitPCA(std::vector<Eigen::Vector3d >& points)\n{\n  // Compute PCA to determine best line approximation\n  // of the points distribution\n  Eigen::MatrixXd data(points.size(), 3);\n\n  for (unsigned int k = 0; k < points.size(); k++)\n  {\n    data.row(k) = points[k];\n  }\n  // Position\n  this->Position = data.colwise().mean();\n  Eigen::MatrixXd centered = data.rowwise() - this->Position.transpose();\n  Eigen::Matrix3d varianceCovariance = centered.transpose() * centered;\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig(varianceCovariance);\n\n  // Direction\n  this->Direction = eig.eigenvectors().col(2).normalized();\n\n  // Semi distance matrix\n  // (polar form associated to\n  // a bilineare symmetric positive\n  // semi-definite matrix)\n  this->SemiDist = (this->I3 - this->Direction * this->Direction.transpose());\n\n  bool isLineFittingAccurate = true;\n\n  // if a point of the neighborhood is too far from\n  // the fitting line we considere the neighborhood as\n  // non flat\n  double squaredMaxDistance = std::pow(this->MaxDistance, 2);\n  for (unsigned int k = 0; k < points.size(); k++)\n  {\n    double d = (points[k] - this->Position).transpose() * this->SemiDist * (points[k] - this->Position);\n    if (d > squaredMaxDistance)\n    {\n      isLineFittingAccurate = false;\n    }\n  }\n  return isLineFittingAccurate;\n}\n\n//-----------------------------------------------------------------------------\nbool LineFitting::FitPCAAndCheckConsistency(std::vector<Eigen::Vector3d >& points)\n{\n  bool isLineFittingAccurate = true;\n\n  // first check if the neighborhood is straight\n  Eigen::Vector3d U, V;\n  U = (points[1] - points[0]).normalized();\n  for (unsigned int index = 1; index < points.size() - 1; index++)\n  {\n    V = (points[index + 1] - points[index]).normalized();\n    double sinAngle = (U.cross(V)).norm();\n    if (sinAngle > this->MaxSinAngle)\n    {\n      isLineFittingAccurate = false;\n    }\n  }\n\n  // Then fit with PCA\n  isLineFittingAccurate &= this->FitPCA(points);\n  return isLineFittingAccurate;\n}\n\n//-----------------------------------------------------------------------------\nvoid LineFitting::FitFast(std::vector<Eigen::Vector3d >& points)\n{\n  // Take the two extrems points of the neighborhood\n  // i.e the farest and the closest to the current point\n  Eigen::Vector3d U = points[0];\n  Eigen::Vector3d V = points[points.size() - 1];\n\n  // direction\n  this->Direction = (V - U).normalized();\n\n  // position\n  this->Position = U;\n\n  // Semi distance matrix\n  // (polar form associated to\n  // a bilineare symmetric positive\n  // semi-definite matrix)\n  this->SemiDist = (this->I3 - this->Direction * this->Direction.transpose());\n  this->SemiDist = this->SemiDist.transpose() * this->SemiDist;\n}\n}\n\n\n//-----------------------------------------------------------------------------\nvoid SpinningSensorKeypointExtractor::PrepareDataForNextFrame()\n{\n  // Reset the pcl format pointcloud to store the new frame\n  this->pclCurrentFrameByScan.resize(this->NLasers);\n  for (unsigned int k = 0; k < this->NLasers; ++k)\n  {\n    this->pclCurrentFrameByScan[k].reset(new pcl::PointCloud<Point>());\n  }\n\n  this->EdgesPoints.reset(new pcl::PointCloud<Point>());\n  this->PlanarsPoints.reset(new pcl::PointCloud<Point>());\n  this->BlobsPoints.reset(new pcl::PointCloud<Point>());\n\n  this->Angles.clear();\n  this->Angles.resize(this->NLasers);\n  this->SaillantPoint.clear();\n  this->SaillantPoint.resize(this->NLasers);\n  this->DepthGap.clear();\n  this->DepthGap.resize(this->NLasers);\n  this->IntensityGap.clear();\n  this->IntensityGap.resize(this->NLasers);\n  this->IsPointValid.clear();\n  this->IsPointValid.resize(this->NLasers);\n  this->Label.clear();\n  this->Label.resize(this->NLasers);\n}\n\n//-----------------------------------------------------------------------------\nvoid SpinningSensorKeypointExtractor::ConvertAndSortScanLines()\n{\n  int nbPoints = this->pclCurrentFrame->size();\n  double frameStartTime = this->pclCurrentFrame->points[0].time;\n  double frameDuration = this->pclCurrentFrame->points[nbPoints-1].time - frameStartTime;\n\n  for (size_t index = 0; index < nbPoints; ++index)\n  {\n    const Point& oldPoint = this->pclCurrentFrame->points[index];\n    int id = this->LaserIdMapping[oldPoint.laserId];\n    // modify the point so that:\n    // - laserId is corrected with the laserIdMapping\n    // - time become a relative advancement time (between 0 and 1)\n    Point newPoint(oldPoint);\n    newPoint.laserId = id;\n    newPoint.time = (oldPoint.time - frameStartTime) / frameDuration;\n\n    // add the current point to its corresponding laser scan\n    this->pclCurrentFrameByScan[id]->push_back(newPoint);\n  }\n}\n\n//-----------------------------------------------------------------------------\nvoid SpinningSensorKeypointExtractor::ComputeKeyPoints(pcl::PointCloud<Point>::Ptr pc, std::vector<size_t> laserIdMapping)\n{\n  if (this->LaserIdMapping.empty())\n  {\n    this->NLasers = laserIdMapping.size();\n    this->LaserIdMapping = laserIdMapping;\n  }\n  this->pclCurrentFrame = pc;\n  this->PrepareDataForNextFrame();\n  this->ConvertAndSortScanLines();\n  // Initialize the vectors with the correct length\n  for (unsigned int k = 0; k < this->NLasers; ++k)\n  {\n    size_t nbPoint = this->pclCurrentFrameByScan[k]->size();\n    this->IsPointValid[k].resize(nbPoint, 1);\n    this->Label[k].resize(nbPoint, 0);\n    this->Angles[k].resize(nbPoint, 0);\n    this->SaillantPoint[k].resize(nbPoint, 0);\n    this->DepthGap[k].resize(nbPoint, 0);\n    this->IntensityGap[k].resize(nbPoint, 0);\n  }\n\n  // Invalid points with bad criteria\n  this->InvalidPointWithBadCriteria();\n\n  // compute keypoints scores\n  this->ComputeCurvature();\n\n  // labelize keypoints\n  this->SetKeyPointsLabels();\n}\n\n//-----------------------------------------------------------------------------\nvoid SpinningSensorKeypointExtractor::ComputeCurvature()\n{\n  double squaredDistToLineThreshold = std::pow(this->DistToLineThreshold, 2);\n  double squaredDepthDistCoeff = 0.25;\n  // loop over scans lines\n  for (unsigned int scanLine = 0; scanLine < this->NLasers; ++scanLine)\n  {\n    Point currentPoint, nextPoint, previousPoint;\n    Eigen::Vector3d X, centralPoint;\n    LineFitting leftLine, rightLine, farNeighborsLine;\n\n    // We will compute the line that fit the neighbors located\n    // previously the current. We will do the same for the\n    // neighbors located after the current points. We will then\n    // compute the angle between these two lines as an approximation\n    // of the \"sharpness\" of the current point.\n    std::vector<Eigen::Vector3d> leftNeighbor(this->NeighborWidth);\n    std::vector<Eigen::Vector3d> rightNeighbor(this->NeighborWidth);\n    std::vector<Eigen::Vector3d> farNeighbors;\n    farNeighbors.reserve(3 * this->NeighborWidth);\n\n    // loop over points in the current scan line\n    int Npts = this->pclCurrentFrameByScan[scanLine]->size();\n\n    // if the line is almost empty, skip it\n    if (Npts < 2 * this->NeighborWidth + 1)\n    {\n      continue;\n    }\n\n    for (int index = this->NeighborWidth; (index + this->NeighborWidth) < Npts; ++index)\n    {\n      // Skip curvature computation for invalid points\n      if (this->IsPointValid[scanLine][index] == 0)\n      {\n        continue;\n      }\n\n      // central point\n      currentPoint = this->pclCurrentFrameByScan[scanLine]->points[index];\n      centralPoint << currentPoint.x, currentPoint.y, currentPoint.z;\n\n      // compute intensity gap\n      nextPoint = this->pclCurrentFrameByScan[scanLine]->points[index + 1];\n      previousPoint = this->pclCurrentFrameByScan[scanLine]->points[index - 1];\n      this->IntensityGap[scanLine][index] = std::abs(nextPoint.intensity - previousPoint.intensity);\n\n      // Fill right and left neighborhood\n      // /!\\ The way the neighbors are added\n      // to the vectors matters. Especially when\n      // computing the saillancy\n      for (int j = index - this->NeighborWidth; j < index; ++j)\n      {\n        currentPoint = this->pclCurrentFrameByScan[scanLine]->points[j];\n        leftNeighbor[j -index + this->NeighborWidth] << currentPoint.x, currentPoint.y, currentPoint.z;\n      }\n      for (int j = index + 1; j <= index + this->NeighborWidth; ++j)\n      {\n        currentPoint = this->pclCurrentFrameByScan[scanLine]->points[j];\n        rightNeighbor[j - index - 1] << currentPoint.x, currentPoint.y, currentPoint.z;\n      }\n\n      // Fit line on the neighborhood and\n      // Indicate if the left and right side\n      // neighborhood of the current point is flat or not\n      bool leftFlat = leftLine.FitPCAAndCheckConsistency(leftNeighbor);\n      bool rightFlat = rightLine.FitPCAAndCheckConsistency(rightNeighbor);\n\n      // Measurement of the gap\n      double dist1 = 0; double dist2 = 0;\n\n      // if both neighborhood are flat we can compute\n      // the angle between them as an approximation of the\n      // sharpness of the current point\n      if (rightFlat && leftFlat)\n      {\n        // We check that the current point is not too far from its\n        // neighborhood lines. This is because we don't want a point\n        // to be considered as a angles point if it is due to gap\n        dist1 = (centralPoint - leftLine.Position).transpose() * leftLine.SemiDist * (centralPoint - leftLine.Position);\n        dist2 = (centralPoint - rightLine.Position).transpose() * rightLine.SemiDist * (centralPoint - rightLine.Position);\n\n        if ((dist1 < squaredDistToLineThreshold) && (dist2 < squaredDistToLineThreshold))\n          this->Angles[scanLine][index] = std::abs((leftLine.Direction.cross(rightLine.Direction)).norm()); // sin of angle actually\n      }\n      // Here one side of the neighborhood is non flat\n      // Hence it is not worth to estimate the sharpness.\n      // Only the gap will be considered here.\n      else if (rightFlat && !leftFlat)\n      {\n        dist1 = std::numeric_limits<double>::max();\n        for (unsigned int neighIndex = 0; neighIndex < leftNeighbor.size(); ++neighIndex)\n        {\n          dist1 = std::min(dist1,\n                  ((leftNeighbor[neighIndex] - rightLine.Position).transpose() * rightLine.SemiDist * (leftNeighbor[neighIndex] - rightLine.Position))(0));\n        }\n        dist1 = squaredDepthDistCoeff * dist1;\n      }\n      else if (!rightFlat && leftFlat)\n      {\n        dist2 = std::numeric_limits<double>::max();\n        for (unsigned int neighIndex = 0; neighIndex < leftNeighbor.size(); ++neighIndex)\n        {\n          dist2 = std::min(dist2,\n                  ((rightNeighbor[neighIndex] - leftLine.Position).transpose() * leftLine.SemiDist * (rightNeighbor[neighIndex] - leftLine.Position))(0));\n        }\n        dist2 = squaredDepthDistCoeff * dist2;\n      }\n      else\n      {\n        // Compute saillant point score\n        double currDepth = centralPoint.norm();\n        unsigned int diffDepth = 0;\n        bool canLeftBeAdded = true; bool hasLeftEncounteredDepthGap = false;\n        bool canRightBeAdded = true; bool hasRightEncounteredDepthGap = false;\n\n        // The saillant point score is the distance between the current point\n        // and the points that have a depth gap with the current point\n        farNeighbors.resize(0);\n        for (unsigned int neighIndex = 0; neighIndex < leftNeighbor.size(); ++neighIndex)\n        {\n          // Left neighborhood depth gap computation\n          if ((std::abs(leftNeighbor[leftNeighbor.size() - 1 - neighIndex].norm() - currDepth) > 1.5) && canLeftBeAdded)\n          {\n            hasLeftEncounteredDepthGap = true;\n            diffDepth++;\n            farNeighbors.emplace_back(leftNeighbor[neighIndex]);\n          }\n          else\n          {\n            if (hasLeftEncounteredDepthGap)\n            {\n              canLeftBeAdded = false;\n            }\n          }\n          // Right neigborhood depth gap computation\n          if ((std::abs(rightNeighbor[neighIndex].norm() - currDepth) > 1.5) && canRightBeAdded)\n          {\n            hasRightEncounteredDepthGap = true;\n            diffDepth++;\n            farNeighbors.emplace_back(rightNeighbor[neighIndex]);\n          }\n          else\n          {\n            if (hasRightEncounteredDepthGap)\n            {\n              canRightBeAdded = false;\n            }\n          }\n        }\n\n        // If there is enought neighbors with a big depth gap\n        // we propose to compute the saillancy of the current\n        // as the distance between the line that fits the neighbors\n        // with a depth gap and the current point\n        if (static_cast<double>(diffDepth) / (2.0 * this->NeighborWidth) > 0.5)\n        {\n          farNeighborsLine.FitPCA(farNeighbors);\n          this->SaillantPoint[scanLine][index] =\n            (centralPoint - farNeighborsLine.Position).transpose() * farNeighborsLine.SemiDist * (centralPoint - farNeighborsLine.Position);\n        }\n      }\n      this->DepthGap[scanLine][index] = std::max(dist1, dist2);\n    }\n  }\n}\n\n//-----------------------------------------------------------------------------\nvoid SpinningSensorKeypointExtractor::InvalidPointWithBadCriteria()\n{\n  // Temporary variables used in the next loop\n  Eigen::Vector3d dX, X, Xn, Xp, Xproj, dXproj;\n  Eigen::Vector3d Y, Yn, Yp, dY;\n  double L, Ln, expectedLength, dLn, dLp;\n  Point currentPoint, nextPoint, previousPoint;\n  Point temp;\n\n  // loop over scan lines\n  for (unsigned int scanLine = 0; scanLine < this->NLasers; ++scanLine)\n  {\n    int Npts = this->pclCurrentFrameByScan[scanLine]->size();\n\n    // if the line is almost empty, skip it\n    if (Npts < 3 * this->NeighborWidth)\n    {\n      continue;\n    }\n    // invalidate first and last points\n    for (int index = 0; index <= this->NeighborWidth; ++index)\n    {\n      this->IsPointValid[scanLine][index] = 0;\n    }\n    for (int index = Npts - 1 - this->NeighborWidth - 1; index < Npts; ++index)\n    {\n      this->IsPointValid[scanLine][index] = 0;\n    }\n\n    // loop over points into the scan line\n    for (int index = this->NeighborWidth; index <  Npts - this->NeighborWidth - 1; ++index)\n    {\n      currentPoint = this->pclCurrentFrameByScan[scanLine]->points[index];\n      nextPoint = this->pclCurrentFrameByScan[scanLine]->points[index + 1];\n      previousPoint = this->pclCurrentFrameByScan[scanLine]->points[index - 1];\n      X << currentPoint.x, currentPoint.y, currentPoint.z;\n      Xn << nextPoint.x, nextPoint.y, nextPoint.z;\n      Xp << previousPoint.x, previousPoint.y, previousPoint.z;\n      dX = Xn - X;\n      L = X.norm();\n      Ln = Xn.norm();\n      dLn = dX.norm();\n\n      // the expected length between two firing of the same laser\n      // depend on the distance and the angular resolution of the\n      // sensor.\n      expectedLength = 2.0 *  std::tan(this->AngleResolution / 2.0) * L;\n      double ratioExpectedLength = 10.0;\n\n      // if the length between the two firing\n      // is more than n-th the expected length\n      // it means that there is a gap. We now must\n      // determine if the gap is due to the geometry of\n      // the scene or if the gap is due to an occluded area\n      if (dLn > ratioExpectedLength * expectedLength)\n      {\n        // Project the next point onto the\n        // sphere of center 0 and radius =\n        // norm of the current point. If the\n        // gap has disappeared it means that\n        // the gap was due to an occlusion\n        Xproj = L / Ln * Xn;\n        dXproj = Xproj - X;\n        // it is a depth gap, invalidate the part which belong\n        // to the occluded area (farest)\n        // invalid next part\n        if (L < Ln)\n        {\n          for (int i = index + 1; i <= index + this->NeighborWidth; ++i)\n          {\n            if (i > index + 1)\n            {\n              temp = this->pclCurrentFrameByScan[scanLine]->points[i - 1];\n              Yp << temp.x, temp.y, temp.z;\n              temp = this->pclCurrentFrameByScan[scanLine]->points[i];\n              Y << temp.x, temp.y, temp.z;\n              dY = Y - Yp;\n              // if there is a gap in the neihborhood\n              // we do not invalidate the rest of neihborhood\n              if (dY.norm() > ratioExpectedLength * expectedLength)\n              {\n                break;\n              }\n            }\n            this->IsPointValid[scanLine][i] = 0;\n          }\n        }\n        // invalid previous part\n        else\n        {\n          for (int i = index - this->NeighborWidth; i <= index; ++i)\n          {\n            if (i < index)\n            {\n              temp = this->pclCurrentFrameByScan[scanLine]->points[i + 1];\n              Yn << temp.x, temp.y, temp.z;\n              temp = this->pclCurrentFrameByScan[scanLine]->points[i];\n              Y << temp.x, temp.y, temp.z;\n              dY = Yn - Y;\n              // if there is a gap in the neihborhood\n              // we do not invalidate the rest of neihborhood\n              if (dY.norm() > ratioExpectedLength * expectedLength)\n              {\n                break;\n              }\n            }\n            this->IsPointValid[scanLine][i] = 0;\n          }\n        }\n      }\n      // Invalid points which are too close from the sensor\n      if (L < this->MinDistanceToSensor)\n      {\n        this->IsPointValid[scanLine][index] = 0;\n      }\n\n      // Invalid points which are on a planar\n      // surface nearly parallel to the laser\n      // beam direction\n      dLp = (X - Xp).norm();\n      if ((dLp > 1 / 4.0 * ratioExpectedLength * expectedLength) && (dLn > 1 / 4.0 * ratioExpectedLength * expectedLength))\n      {\n        this->IsPointValid[scanLine][index] = 0;\n      }\n    }\n  }\n}\n\n//-----------------------------------------------------------------------------\nvoid SpinningSensorKeypointExtractor::SetKeyPointsLabels()\n{\n  this->EdgesIndex.clear(); this->EdgesIndex.resize(0);\n  this->PlanarIndex.clear(); this->PlanarIndex.resize(0);\n  this->BlobIndex.clear(); this->BlobIndex.resize(0);\n  double squaredEdgeDepthGapThreshold = std::pow(this->EdgeDepthGapThreshold, 2);\n\n  // loop over the scan lines\n  for (unsigned int scanLine = 0; scanLine < this->NLasers; ++scanLine)\n  {\n    int Npts = this->pclCurrentFrameByScan[scanLine]->size();\n    unsigned int nbrEdgePicked = 0;\n    unsigned int nbrPlanarPicked = 0;\n\n    // We split the validity of points between the edges\n    // keypoints and planar keypoints. This allows to take\n    // some points as planar keypoints even if they are close\n    // to an edge keypoint.\n    std::vector<double> IsPointValidForPlanar = this->IsPointValid[scanLine];\n\n    // if the line is almost empty, skip it\n    if (Npts < 3 * this->NeighborWidth)\n    {\n      continue;\n    }\n\n    // Sort the curvature score in a decreasing order\n    std::vector<size_t> sortedDepthGapIdx = sortIdx<double>(this->DepthGap[scanLine]);\n    std::vector<size_t> sortedAnglesIdx = sortIdx<double>(this->Angles[scanLine]);\n    std::vector<size_t> sortedSaillancyIdx = sortIdx<double>(this->SaillantPoint[scanLine]);\n    std::vector<size_t> sortedIntensityGap = sortIdx<double>(this->IntensityGap[scanLine]);\n\n    double depthGap, sinAngle, saillancy, intensity;\n    int index = 0;\n\n    // Edges using depth gap\n    for (int k = 0; k < Npts; ++k)\n    {\n      index = sortedDepthGapIdx[k];\n      depthGap = this->DepthGap[scanLine][index];\n\n      // thresh\n      if (depthGap < squaredEdgeDepthGapThreshold)\n      {\n        break;\n      }\n\n      // if the point is invalid continue\n      if (this->IsPointValid[scanLine][index] == 0)\n      {\n        continue;\n      }\n\n      // else indicate that the point is an edge\n      this->Label[scanLine][index] = 4;\n      this->EdgesIndex.push_back(std::pair<int, int>(scanLine, index));\n      nbrEdgePicked++;\n      //IsPointValidForPlanar[index] = 0;\n\n      // invalid its neighborhod\n      int indexBegin = index - this->NeighborWidth + 1;\n      int indexEnd = index + this->NeighborWidth - 1;\n      indexBegin = std::max(0, indexBegin);\n      indexEnd = std::min(Npts - 1, indexEnd);\n      for (int j = indexBegin; j <= indexEnd; ++j)\n      {\n        this->IsPointValid[scanLine][j] = 0;\n      }\n    }\n\n    // Edges using angles\n    for (int k = 0; k < Npts; ++k)\n    {\n      index = sortedAnglesIdx[k];\n      sinAngle = this->Angles[scanLine][index];\n\n      // thresh\n      if (sinAngle < this->EdgeSinAngleThreshold)\n      {\n        break;\n      }\n\n      // if the point is invalid continue\n      if (this->IsPointValid[scanLine][index] == 0)\n      {\n        continue;\n      }\n\n      // else indicate that the point is an edge\n      this->Label[scanLine][index] = 4;\n      this->EdgesIndex.push_back(std::pair<int, int>(scanLine, index));\n      nbrEdgePicked++;\n      //IsPointValidForPlanar[index] = 0;\n\n      // invalid its neighborhod\n      int indexBegin = index - this->NeighborWidth;\n      int indexEnd = index + this->NeighborWidth;\n      indexBegin = std::max(0, indexBegin);\n      indexEnd = std::min(Npts - 1, indexEnd);\n      for (int j = indexBegin; j <= indexEnd; ++j)\n      {\n        this->IsPointValid[scanLine][j] = 0;\n      }\n    }\n\n    // Edges using saillancy\n    for (int k = 0; k < Npts; ++k)\n    {\n      index = sortedSaillancyIdx[k];\n      saillancy = this->SaillantPoint[scanLine][index];\n\n      // thresh\n      if (saillancy < this->SaillancyThreshold)\n      {\n        break;\n      }\n\n      // if the point is invalid continue\n      if (this->IsPointValid[scanLine][index] == 0)\n      {\n        continue;\n      }\n\n      // else indicate that the point is an edge\n      this->Label[scanLine][index] = 4;\n      this->EdgesIndex.push_back(std::pair<int, int>(scanLine, index));\n      nbrEdgePicked++;\n      //IsPointValidForPlanar[index] = 0;\n\n      // invalid its neighborhod\n      int indexBegin = index - this->NeighborWidth + 1;\n      int indexEnd = index + this->NeighborWidth - 1;\n      indexBegin = std::max(0, indexBegin);\n      indexEnd = std::min(Npts - 1, indexEnd);\n      for (int j = indexBegin; j <= indexEnd; ++j)\n      {\n        this->IsPointValid[scanLine][j] = 0;\n      }\n    }\n\n    // Edges using intensity\n    for (int k = 0; k < Npts; ++k)\n    {\n      index = sortedIntensityGap[k];\n      intensity = this->IntensityGap[scanLine][index];\n\n      // thresh\n      if (intensity < 50.0)\n      {\n        break;\n      }\n\n      // if the point is invalid continue\n      if (this->IsPointValid[scanLine][index] == 0)\n      {\n        continue;\n      }\n\n      // else indicate that the point is an edge\n      this->Label[scanLine][index] = 4;\n      this->EdgesIndex.push_back(std::pair<int, int>(scanLine, index));\n      nbrEdgePicked++;\n      //IsPointValidForPlanar[index] = 0;\n\n      // invalid its neighborhood\n      int indexBegin = index - 1;\n      int indexEnd = index + 1;\n      indexBegin = std::max(0, indexBegin);\n      indexEnd = std::min(Npts - 1, indexEnd);\n      for (int j = indexBegin; j <= indexEnd; ++j)\n      {\n        this->IsPointValid[scanLine][j] = 0;\n      }\n    }\n\n    // Blobs Points\n//    if (!this->FastSlam)\n//    {\n      for (int k = 0; k < Npts; k = k + 3)\n      {\n        this->BlobIndex.push_back(std::pair<int, int>(scanLine, k));\n      }\n//    }\n\n    // Planes\n    for (int k = Npts - 1; k >= 0; --k)\n    {\n      index = sortedAnglesIdx[k];\n      sinAngle = this->Angles[scanLine][index];\n\n      // thresh\n      if (sinAngle > this->PlaneSinAngleThreshold)\n      {\n        break;\n      }\n\n      // if the point is invalid continue\n      if (IsPointValidForPlanar[index] == 0)\n      {\n        continue;\n      }\n\n      // else indicate that the point is a planar one\n      if ((this->Label[scanLine][index] != 4) && (this->Label[scanLine][index] != 3))\n        this->Label[scanLine][index] = 2;\n      this->PlanarIndex.push_back(std::pair<int, int>(scanLine, index));\n      IsPointValidForPlanar[index] = 0;\n      this->IsPointValid[scanLine][index] = 0;\n\n      // Invalid its neighbor so that we don't have too\n      // many planar keypoints in the same region. This is\n      // required because of the k-nearest search + plane\n      // approximation realized in the odometry part. Indeed,\n      // if all the planar points are on the same scan line the\n      // problem is degenerated since all the points are distributed\n      // on a line.\n      int indexBegin = index - 4;\n      int indexEnd = index + 4;\n      indexBegin = std::max(0, indexBegin);\n      indexEnd = std::min(Npts - 1, indexEnd);\n      for (int j = indexBegin; j <= indexEnd; ++j)\n      {\n        IsPointValidForPlanar[j] = 0;\n      }\n      nbrPlanarPicked++;\n    }\n  }\n\n  // add keypoints in increasing scan id order\n  std::sort(this->EdgesIndex.begin(), this->EdgesIndex.end());\n  std::sort(this->PlanarIndex.begin(), this->PlanarIndex.end());\n  std::sort(this->BlobIndex.begin(), this->BlobIndex.end());\n\n  // fill the keypoints vectors and compute the max dist keypoints\n  this->FarestKeypointDist = 0.0;\n  Point p;\n  for (unsigned int k = 0; k < this->EdgesIndex.size(); ++k)\n  {\n    p = this->pclCurrentFrameByScan[this->EdgesIndex[k].first]->points[this->EdgesIndex[k].second];\n    this->EdgesPoints->push_back(p);\n    this->FarestKeypointDist = std::max(this->FarestKeypointDist, static_cast<double>(std::pow(p.x, 2) + std::pow(p.y, 2) + std::pow(p.z, 2)));\n  }\n  for (unsigned int k = 0; k < this->PlanarIndex.size(); ++k)\n  {\n    p = this->pclCurrentFrameByScan[this->PlanarIndex[k].first]->points[this->PlanarIndex[k].second];\n    this->PlanarsPoints->push_back(p);\n    this->FarestKeypointDist = std::max(this->FarestKeypointDist, static_cast<double>(std::pow(p.x, 2) + std::pow(p.y, 2) + std::pow(p.z, 2)));\n  }\n  for (unsigned int k = 0; k < this->BlobIndex.size();  ++k)\n  {\n    p = this->pclCurrentFrameByScan[this->BlobIndex[k].first]->points[this->BlobIndex[k].second];\n    this->BlobsPoints->push_back(p);\n    this->FarestKeypointDist = std::max(this->FarestKeypointDist, static_cast<double>(std::pow(p.x, 2) + std::pow(p.y, 2) + std::pow(p.z, 2)));\n  }\n  this->FarestKeypointDist = std::sqrt(this->FarestKeypointDist);\n\n  // keypoints extraction informations\n  std::cout << \"Extracted Edges: \" << this->EdgesPoints->size() << \" Planars: \"\n            << this->PlanarsPoints->size() << \" Blobs: \"\n            << this->BlobsPoints->size() << std::endl;\n}\n\n//-----------------------------------------------------------------------------\nstd::unordered_map<std::string, std::vector<double> >\nSpinningSensorKeypointExtractor::GetDebugArray()\n{\n  auto get1DVector =  [this](std::vector<std::vector<double>> array) {\n    std::vector<double> v (this->pclCurrentFrame->size());\n    std::vector<int> indexPerByScanLine(this->NLasers, 0);\n    for (int i = 0; i < this->pclCurrentFrame->size(); i++)\n    {\n      double laserId = this->LaserIdMapping[this->pclCurrentFrame->points[i].laserId];\n      v[i] = array[laserId][indexPerByScanLine[laserId]];\n      indexPerByScanLine[laserId]++;\n    }\n    return v;\n  }; // end of lambda expression\n\n  std::unordered_map<std::string, std::vector<double> > map;\n  map[\"angles_line\"]    = get1DVector(this->Angles);\n  map[\"saillant_point\"] = get1DVector(this->SaillantPoint);\n  map[\"depth_gap\"]      = get1DVector(this->DepthGap);\n  map[\"intensity_gap\"]  = get1DVector(this->IntensityGap);\n  map[\"is_point_valid\"] = get1DVector(this->IsPointValid);\n  map[\"keypoint_label\"] = get1DVector(this->Label);\n  return map;\n}\n", "meta": {"hexsha": "c3607e3f3aa745aa56201addfe7b227c0a2914b7", "size": 29400, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "LidarPlugin/Filter/Slam/SpinningSensorKeypointExtractor.cxx", "max_stars_repo_name": "Pandinosaurus/LidarView", "max_stars_repo_head_hexsha": "9b9b2976e9ac5dcd891a604dabbb79bd6fc6a57a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T11:14:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-13T11:14:18.000Z", "max_issues_repo_path": "LidarPlugin/Filter/Slam/SpinningSensorKeypointExtractor.cxx", "max_issues_repo_name": "yxw027/LidarView", "max_issues_repo_head_hexsha": "9267729e62886a324ba7f2e3fed50db38b24f001", "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": "LidarPlugin/Filter/Slam/SpinningSensorKeypointExtractor.cxx", "max_forks_repo_name": "yxw027/LidarView", "max_forks_repo_head_hexsha": "9267729e62886a324ba7f2e3fed50db38b24f001", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-30T10:07:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-30T10:07:35.000Z", "avg_line_length": 35.5501813785, "max_line_length": 155, "alphanum_fraction": 0.6074489796, "num_tokens": 7678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5228069546984222}}
{"text": "/**\n *  testReachset.cpp\n *\n *  Test the reachable set computation of a two-link scara manipulator.\n *\n *  Created by Yinan Li on July 05, 2020.\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n\n#include <iostream>\n#include <cmath>\n\n#include <array>\n#include <boost/numeric/odeint.hpp>\n\n#include \"src/system.hpp\"\n#include \"src/csolver.h\"\n\n#include \"scara.h\"\n\ntypedef std::array<double, 4> state_type;\nstruct scara_vf {\n    rocs::Rn _u;\n    scara_vf(rocs::Rn u) : _u(u) {}\n    void operator()(state_type &x, state_type &dxdt, double t) const {\n\tdouble z1 = I1+I2+m1*r1*r1+m2*(l1*l1+r2*r2);\n\tdouble z2 = m2*l1*r2;\n\tdouble z3 = I2+m2*r2*r2;\n\tdouble detM = z3*(z1-z3) - z2*z2*std::cos(x[1])*std::cos(x[1]);\n\tdouble a = z2*std::sin(x[1])*(2*x[2]+x[3])*x[3];\n\tdouble b = z2*std::cos(x[1]);\n\tdouble c = z2*x[2]*std::sin(x[1])-_u[1];\n\t\n\tdxdt[0] = x[2];\n\tdxdt[1] = x[3];\n\tdxdt[2] = (z3*_u[0] + z3*a + (z3+b)*c) / detM;\n\tdxdt[3] = ((z1+2*b)*(-c) - (z3+b)*(_u[0]+a)) / detM;\n    }\n};\n\n\nint main() {\n\n    /* set the state space */\n    double xlb[4] = {0, -M_PI, -0.5, -0.5};\n    double xub[4] = {M_PI, M_PI, 0.5, 0.5};\n    \n    /* set the control values */\n    double ulb[2] = {-0.001, -0.001};\n    double uub[2] = {0.001, 0.001};\n    double mu[2] = {0.0002, 0.0002};\n\n    /* set the sampling time and disturbance */\n    double t = 0.05;\n    double delta = 0.01;\n    /* parameters for computing the flow */\n    int kmax = 5;\n    double tol = 0.01;\n    double alpha = 0.5;\n    double beta = 2;\n    rocs::params controlparams(kmax, tol, alpha, beta);\n    \n    /* define the control system */\n    rocs::CTCntlSys<scaraode> scara(\"inverted pendulum\", t,\n\t\t\t\t    scaraode::n, scaraode::nu,\n\t\t\t\t    delta, &controlparams);\n    scara.init_workspace(xlb, xub);\n    scara.init_inputset(mu, ulb, uub);\n    scara.allocate_flows();\n\n    /* test if reachable set covers the nominal trajectory */\n    /* compute reachable set */\n    // rocs::ivec x0 = {rocs::interval(0.09, 0.11),\n    // \t\t     rocs::interval(-0.01, 0.01),\n    // \t\t     rocs::interval(-0.01, 0.01),\n    // \t\t     rocs::interval(-0.01, 0.01)};\n    rocs::ivec x0 = {rocs::interval(0.6172, 0.63),\n    \t\t     rocs::interval(1.61, 1.63),\n    \t\t     rocs::interval(-0.005, 0.005),\n\t\t     rocs::interval(-0.005, 0.005)};\n    std::vector<rocs::ivec> x(scara._ugrid._nv, rocs::ivec(4));\n    std::cout << \"The initial interval: \" << x0 << '\\n';\n    std::cout << \"The integrating time: \" << t << '\\n';\n    scara.get_reach_set(x, x0);\n\n    // double dt{0.001};\n    // for (size_t i = 0; i < x.size(); ++i) {\n    // \t/* integrate the nominal trajectory */\n    // \tstate_type y{0.1, 0, 0, 0};\n    // \trocs::Rn u(scara._ugrid._data[i]);\n    // \tboost::numeric::odeint::runge_kutta_cash_karp54<state_type> rk45;\n    // \tboost::numeric::odeint::integrate_const(rk45, scara_vf(u),\n    // \t\t\t\t\t\ty, 0.0, t, dt);\n    // \tstd::cout << \"x(t)= [\" << y[0] << ','<< y[1] << ',' << y[2] << ',' << y[3] << \"]\\n\";\n    // \tstd::cout << \"R(t, x0, [\" << scara._ugrid._data[i][0] << ','\n    // \t\t  << scara._ugrid._data[i][1] << \"])= \";\n    // \tstd::cout << x[i] <<'\\n';\n    // \tstd::cout << \"Check: \";\n    // \tfor (int j = 0; j < 4; ++j) {\n    // \t    if (y[j] > x[i][j].getinf() && y[j] < x[i][j].getsup())\n    // \t\tstd::cout << true << ' ';\n    // \t    else\n    // \t\tstd::cout << false << ' ';\n    // \t}\n    // \tstd::cout << '\\n';\n    // }\n    \n    scara.release_flows();\n    \n    return 0;\n}\n", "meta": {"hexsha": "5eca7f972ed5b275a64d71912554f4dcc620e891", "size": 3411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/scara/testReachset.cpp", "max_stars_repo_name": "yinanl/rocs", "max_stars_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "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/scara/testReachset.cpp", "max_issues_repo_name": "yinanl/rocs", "max_issues_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/scara/testReachset.cpp", "max_forks_repo_name": "yinanl/rocs", "max_forks_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "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.185840708, "max_line_length": 92, "alphanum_fraction": 0.5288771621, "num_tokens": 1289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5228069546984222}}
{"text": "//\n// author: Ed Valeev (eduard@valeyev.net)\n// date  : July 8, 2014\n// the use of this software is permitted under the conditions GNU General Public License (GPL) version 2\n//\n\n// standard C++ headers\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n#include <vector>\n#include <chrono>\n\n// OpenMP\n#include <omp.h>\n\n// Eigen matrix algebra library\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\n// Libint Gaussian integrals library\n#include <libint2.hpp>\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n        Matrix;  // import dense, dynamically sized Matrix type from Eigen;\n                 // this is a matrix with row-major storage (http://en.wikipedia.org/wiki/Row-major_order)\n                 // to meet the layout of the integrals returned by the Libint integral library\n\nstruct Atom {\n    int atomic_number;\n    double x, y, z;\n};\n\nstd::vector<Atom> read_geometry(const std::string& filename);\nstd::vector<libint2::Shell> make_sto3g_basis(const std::vector<Atom>& atoms);\nsize_t nbasis(const std::vector<libint2::Shell>& shells);\nstd::vector<size_t> map_shell_to_basis_function(const std::vector<libint2::Shell>& shells);\nMatrix compute_soad(const std::vector<Atom>& atoms);\nMatrix compute_1body_ints(const std::vector<libint2::Shell>& shells,\n                          libint2::Operator t,\n                          const std::vector<Atom>& atoms = std::vector<Atom>());\nMatrix compute_2body_fock(const std::vector<libint2::Shell>& shells,\n                                 const Matrix& D);\n\nint main(int argc, char *argv[]) {\n\n  using std::cout;\n  using std::cerr;\n  using std::endl;\n\n  using libint2::Shell;\n  using libint2::BasisSet;\n  using libint2::Engine;\n  using libint2::Operator;\n\n  double fock_time = 0.0;\n  double start;\n\n  try {\n\n    /*** =========================== ***/\n    /*** initialize molecule         ***/\n    /*** =========================== ***/\n\n    // read geometry from a file; by default read from h2o.geom, else take filename (.xyz or .geom) from the command line\n    const auto filename = (argc > 1) ? argv[1] : \"h2o.geom\";\n    std::vector<Atom> atoms = read_geometry(filename);\n\n    // count the number of electrons\n    auto nelectron = 0;\n    for (auto i = 0; i < atoms.size(); ++i)\n      nelectron += atoms[i].atomic_number;\n    const auto ndocc = nelectron / 2;\n\n    // compute the nuclear repulsion energy\n    auto enuc = 0.0;\n    for (auto i = 0; i < atoms.size(); i++)\n      for (auto j = i + 1; j < atoms.size(); j++) {\n        auto xij = atoms[i].x - atoms[j].x;\n        auto yij = atoms[i].y - atoms[j].y;\n        auto zij = atoms[i].z - atoms[j].z;\n        auto r2 = xij*xij + yij*yij + zij*zij;\n        auto r = sqrt(r2);\n        enuc += atoms[i].atomic_number * atoms[j].atomic_number / r;\n      }\n    cout << \"\\tNuclear repulsion energy = \" << enuc << endl;\n\n    /*** =========================== ***/\n    /*** create basis set            ***/\n    /*** =========================== ***/\n\n    auto shells = make_sto3g_basis(atoms);\n    size_t nao = 0;\n    for (auto s=0; s<shells.size(); ++s)\n      nao += shells[s].size();\n\n    /*** =========================== ***/\n    /*** compute 1-e integrals       ***/\n    /*** =========================== ***/\n\n    // initializes the Libint integrals library ... now ready to compute\n    libint2::initialize();\n\n    // compute overlap integrals\n    auto S = compute_1body_ints(shells, Operator::overlap);\n\n    // compute kinetic-energy integrals\n    auto T = compute_1body_ints(shells, Operator::kinetic);\n\n    // compute nuclear-attraction integrals\n    Matrix V = compute_1body_ints(shells, Operator::nuclear, atoms);\n\n    // Core Hamiltonian = T + V\n    Matrix H = T + V;\n\n    // T and V no longer needed, free up the memory\n    T.resize(0,0);\n    V.resize(0,0);\n\n    /*** =========================== ***/\n    /*** build initial-guess density ***/\n    /*** =========================== ***/\n\n    const auto use_hcore_guess = false;  // use core Hamiltonian eigenstates to guess density?\n                                         // set to true to match the result of versions 0, 1, and 2 of the code\n                                         // HOWEVER !!! even for medium-size molecules hcore will usually fail !!!\n                                         // thus set to false to use Superposition-Of-Atomic-Densities (SOAD) guess\n    Matrix D;\n    if (use_hcore_guess) { // hcore guess\n      // solve H C = e S C\n      Eigen::GeneralizedSelfAdjointEigenSolver<Matrix> gen_eig_solver(H, S);\n      auto eps = gen_eig_solver.eigenvalues();\n      auto C = gen_eig_solver.eigenvectors();\n\n      // compute density, D = C(occ) . C(occ)T\n      auto C_occ = C.leftCols(ndocc);\n      D = C_occ * C_occ.transpose();\n    }\n    else {  // SOAD as the guess density, assumes STO-nG basis\n      D = compute_soad(atoms);\n    }\n\n    /*** =========================== ***/\n    /*** main iterative loop         ***/\n    /*** =========================== ***/\n\n    const auto maxiter = 100;\n    const auto conv = 1e-12;\n    auto iter = 0;\n    auto rmsd = 0.0;\n    auto ediff = 0.0;\n    auto ehf = 0.0;\n    do {\n      const auto tstart = std::chrono::high_resolution_clock::now();\n      ++iter;\n\n      // Save a copy of the energy and the density\n      auto ehf_last = ehf;\n      auto D_last = D;\n\n      // build a new Fock matrix\n      auto F = H;\n      start = omp_get_wtime();\n      F += compute_2body_fock(shells, D);\n      fock_time += omp_get_wtime() - start;\n\n      // solve F C = e S C\n      Eigen::GeneralizedSelfAdjointEigenSolver<Matrix> gen_eig_solver(F, S);\n      auto eps = gen_eig_solver.eigenvalues();\n      auto C = gen_eig_solver.eigenvectors();\n\n      // compute density, D = C(occ) . C(occ)T\n      auto C_occ = C.leftCols(ndocc);\n      D = C_occ * C_occ.transpose();\n\n      // compute HF energy\n      ehf = 0.0;\n      for (auto i = 0; i < nao; i++)\n        for (auto j = 0; j < nao; j++)\n          ehf += D(i,j) * (H(i,j) + F(i,j));\n\n      // compute difference with last iteration\n      ediff = ehf - ehf_last;\n      rmsd = (D - D_last).norm();\n\n      const auto tstop = std::chrono::high_resolution_clock::now();\n      const std::chrono::duration<double> time_elapsed = tstop - tstart;\n\n      if (iter == 1)\n        std::cout <<\n        \"\\n\\n Iter        E(elec)              E(tot)               Delta(E)             RMS(D)         Time(s)\\n\";\n      printf(\" %02d %20.12f %20.12f %20.12f %20.12f %10.5lf\\n\", iter, ehf, ehf + enuc,\n             ediff, rmsd, time_elapsed.count());\n\n    } while (((fabs(ediff) > conv) || (fabs(rmsd) > conv)) && (iter < maxiter));\n\n    printf(\"** Hartree-Fock energy = %20.12f\\n\", ehf + enuc);\n\n    libint2::finalize(); // done with libint\n\n  } // end of try block; if any exceptions occurred, report them and exit cleanly\n\n  catch (const char* ex) {\n    cerr << \"caught exception: \" << ex << endl;\n    return 1;\n  }\n  catch (std::string& ex) {\n    cerr << \"caught exception: \" << ex << endl;\n    return 1;\n  }\n  catch (std::exception& ex) {\n    cerr << ex.what() << endl;\n    return 1;\n  }\n  catch (...) {\n    cerr << \"caught unknown exception\\n\";\n    return 1;\n  }\n\n  printf(\"\\n\\nFock build time = %.2f\\n\", fock_time);\n\n  return 0;\n}\n\n// this reads the geometry in the same format used in older versions of the code\nstd::vector<Atom> read_dotgeom(std::istream& is) {\n  size_t natom;\n  is >> natom;\n\n  std::vector<Atom> atoms(natom);\n  for (auto i = 0; i < natom; i++)\n    is >> atoms[i].atomic_number >> atoms[i].x >> atoms[i].y >> atoms[i].z;\n\n  return atoms;\n}\n\n// this reads the geometry in the standard xyz format supported by most chemistry software\nstd::vector<Atom> read_dotxyz(std::istream& is) {\n  // line 1 = # of atoms\n  size_t natom;\n  is >> natom;\n  // read off the rest of line 1 and discard\n  std::string rest_of_line;\n  std::getline(is, rest_of_line);\n\n  // line 2 = comment (possibly empty)\n  std::string comment;\n  std::getline(is, comment);\n\n  std::vector<Atom> atoms(natom);\n  for (auto i = 0; i < natom; i++) {\n    std::string element_label;\n    double x, y, z;\n    is >> element_label >> x >> y >> z;\n\n    // .xyz files report element labels, hence convert to atomic numbers\n    int Z;\n    if (element_label == \"H\")\n      Z = 1;\n    else if (element_label == \"C\")\n      Z = 6;\n    else if (element_label == \"N\")\n      Z = 7;\n    else if (element_label == \"O\")\n      Z = 8;\n    else if (element_label == \"F\")\n      Z = 9;\n    else if (element_label == \"S\")\n      Z = 16;\n    else if (element_label == \"Cl\")\n      Z = 17;\n    else {\n      std::cerr << \"read_dotxyz: element label \\\"\" << element_label << \"\\\" is not recognized\" << std::endl;\n      throw \"Did not recognize element label in .xyz file\";\n    }\n\n    atoms[i].atomic_number = Z;\n\n    // .xyz files report Cartesian coordinates in angstroms; convert to bohr\n    const auto angstrom_to_bohr = 1 / 0.52917721092; // 2010 CODATA value\n    atoms[i].x = x * angstrom_to_bohr;\n    atoms[i].y = y * angstrom_to_bohr;\n    atoms[i].z = z * angstrom_to_bohr;\n  }\n\n  return atoms;\n}\n\nstd::vector<Atom> read_geometry(const std::string& filename) {\n\n  std::cout << \"Will read geometry from \" << filename << std::endl;\n  std::ifstream is(filename);\n  assert(is.good());\n\n  // to prepare for MPI parallelization, we will read the entire file into a string that can be\n  // broadcast to everyone, then converted to an std::istringstream object that can be used just like std::ifstream\n  std::ostringstream oss;\n  oss << is.rdbuf();\n  // use ss.str() to get the entire contents of the file as an std::string\n  // broadcast\n  // then make an std::istringstream in each process\n  std::istringstream iss(oss.str());\n\n  // check the extension: if .xyz, assume the standard XYZ format, otherwise use the same format used by hf.v1\n  if ( filename.rfind(\".xyz\") != std::string::npos)\n    return read_dotxyz(iss);\n  else if ( filename.rfind(\".geom\") != std::string::npos)\n    return read_dotgeom(iss);\n  else\n    throw std::invalid_argument(\"unknown filename extension\");\n}\n\nstd::vector<libint2::Shell> make_sto3g_basis(const std::vector<Atom>& atoms) {\n\n  using libint2::Shell;\n\n  std::vector<Shell> shells;\n\n  for(auto a=0; a<atoms.size(); ++a) {\n\n    // STO-3G basis set\n    // cite: W. J. Hehre, R. F. Stewart, and J. A. Pople, The Journal of Chemical Physics 51, 2657 (1969)\n    //       doi: 10.1063/1.1672392\n    // obtained from https://bse.pnl.gov/bse/portal\n    switch (atoms[a].atomic_number) {\n      case 1: // Z=1: hydrogen\n        shells.push_back(\n            {\n              {3.425250910, 0.623913730, 0.168855400}, // exponents of primitive Gaussians\n              {  // contraction 0: s shell (l=0), spherical=false, contraction coefficients\n                {0, false, {0.15432897, 0.53532814, 0.44463454}}\n              },\n              {{atoms[a].x, atoms[a].y, atoms[a].z}}   // origin coordinates\n            }\n        );\n        break;\n\n      case 6: // Z=6: carbon\n        shells.push_back(\n            {\n              {71.616837000, 13.045096000, 3.530512200},\n              {\n                {0, false, {0.15432897, 0.53532814, 0.44463454}}\n              },\n              {{atoms[a].x, atoms[a].y, atoms[a].z}}\n            }\n        );\n        shells.push_back(\n            {\n              {2.941249400, 0.683483100, 0.222289900},\n              {\n                {0, false, {-0.09996723, 0.39951283, 0.70011547}}\n              },\n              {{atoms[a].x, atoms[a].y, atoms[a].z}}\n            }\n        );\n        shells.push_back(\n            {\n              {2.941249400, 0.683483100, 0.222289900},\n              { // contraction 0: p shell (l=1), spherical=false\n                {1, false, {0.15591627, 0.60768372, 0.39195739}}\n              },\n              {{atoms[a].x, atoms[a].y, atoms[a].z}}\n            }\n        );\n        break;\n\n      case 7: // Z=7: nitrogen\n        shells.push_back(\n            {\n              {99.106169000, 18.052312000, 4.885660200},\n              {\n                {0, false, {0.15432897, 0.53532814, 0.44463454}}\n              },\n              {{atoms[a].x, atoms[a].y, atoms[a].z}}\n            }\n        );\n        shells.push_back(\n            {\n              {3.780455900, 0.878496600, 0.285714400},\n              {\n                {0, false, {-0.09996723, 0.39951283, 0.70011547}}\n              },\n              {{atoms[a].x, atoms[a].y, atoms[a].z}}\n            }\n        );\n        shells.push_back(\n            {\n          {3.780455900, 0.878496600, 0.285714400},\n              { // contraction 0: p shell (l=1), spherical=false\n                {1, false, {0.15591627, 0.60768372, 0.39195739}}\n              },\n              {{atoms[a].x, atoms[a].y, atoms[a].z}}\n            }\n        );\n        break;\n\n      case 8: // Z=8: oxygen\n        shells.push_back(\n            {\n              {130.709320000, 23.808861000, 6.443608300},\n              {\n                {0, false, {0.15432897, 0.53532814, 0.44463454}}\n              },\n              {{atoms[a].x, atoms[a].y, atoms[a].z}}\n            }\n        );\n        shells.push_back(\n            {\n              {5.033151300, 1.169596100, 0.380389000},\n              {\n                {0, false, {-0.09996723, 0.39951283, 0.70011547}}\n              },\n              {{atoms[a].x, atoms[a].y, atoms[a].z}}\n            }\n        );\n        shells.push_back(\n            {\n              {5.033151300, 1.169596100, 0.380389000},\n              { // contraction 0: p shell (l=1), spherical=false\n                {1, false, {0.15591627, 0.60768372, 0.39195739}}\n              },\n              {{atoms[a].x, atoms[a].y, atoms[a].z}}\n            }\n        );\n        break;\n\n      default:\n        throw \"do not know STO-3G basis for this Z\";\n    }\n\n  }\n\n  return shells;\n}\n\nsize_t nbasis(const std::vector<libint2::Shell>& shells) {\n  size_t n = 0;\n  for (const auto& shell: shells)\n    n += shell.size();\n  return n;\n}\n\nsize_t max_nprim(const std::vector<libint2::Shell>& shells) {\n  size_t n = 0;\n  for (auto shell: shells)\n    n = std::max(shell.nprim(), n);\n  return n;\n}\n\nint max_l(const std::vector<libint2::Shell>& shells) {\n  int l = 0;\n  for (auto shell: shells)\n    for (auto c: shell.contr)\n      l = std::max(c.l, l);\n  return l;\n}\n\nstd::vector<size_t> map_shell_to_basis_function(const std::vector<libint2::Shell>& shells) {\n  std::vector<size_t> result;\n  result.reserve(shells.size());\n\n  size_t n = 0;\n  for (auto shell: shells) {\n    result.push_back(n);\n    n += shell.size();\n  }\n\n  return result;\n}\n\n// computes Superposition-Of-Atomic-Densities guess for the molecular density matrix\n// in minimal basis; occupies subshell by smearing electrons evenly over the orbitals\nMatrix compute_soad(const std::vector<Atom>& atoms) {\n\n  // compute number of atomic orbitals\n  size_t nao = 0;\n  for(const auto& atom: atoms) {\n    const auto Z = atom.atomic_number;\n    if (Z == 1 || Z == 2) // H, He\n      nao += 1;\n    else if (Z <= 10) // Li - Ne\n      nao += 5;\n    else\n      throw \"SOAD with Z > 10 is not yet supported\";\n  }\n\n  // compute the minimal basis density\n  Matrix D = Matrix::Zero(nao, nao);\n  size_t ao_offset = 0; // first AO of this atom\n  for(const auto& atom: atoms) {\n    const auto Z = atom.atomic_number;\n    if (Z == 1 || Z == 2) { // H, He\n      D(ao_offset, ao_offset) = Z; // all electrons go to the 1s\n      ao_offset += 1;\n    }\n    else if (Z <= 10) {\n      D(ao_offset, ao_offset) = 2; // 2 electrons go to the 1s\n      D(ao_offset+1, ao_offset+1) = (Z == 3) ? 1 : 2; // Li? only 1 electron in 2s, else 2 electrons\n      // smear the remaining electrons in 2p orbitals\n      const double num_electrons_per_2p = (Z > 4) ? (double)(Z - 4)/3 : 0;\n      for(auto xyz=0; xyz!=3; ++xyz)\n        D(ao_offset+2+xyz, ao_offset+2+xyz) = num_electrons_per_2p;\n      ao_offset += 5;\n    }\n  }\n\n  return D * 0.5; // we use densities normalized to # of electrons/2\n}\n\nMatrix compute_1body_ints(const std::vector<libint2::Shell>& shells,\n                          libint2::Operator obtype,\n                          const std::vector<Atom>& atoms)\n{\n  using libint2::Shell;\n  using libint2::Engine;\n  using libint2::Operator;\n\n  const auto n = nbasis(shells);\n  Matrix result(n,n);\n\n  // construct the overlap integrals engine\n  Engine engine(obtype, max_nprim(shells), max_l(shells), 0);\n  // nuclear attraction ints engine needs to know where the charges sit ...\n  // the nuclei are charges in this case; in QM/MM there will also be classical charges\n  if (obtype == Operator::nuclear) {\n    std::vector<std::pair<double,std::array<double,3>>> q;\n    for(const auto& atom : atoms) {\n      q.push_back( {static_cast<double>(atom.atomic_number), {{atom.x, atom.y, atom.z}}} );\n    }\n    engine.set_params(q);\n  }\n\n  auto shell2bf = map_shell_to_basis_function(shells);\n\n  // buf[0] points to the target shell set after every call  to engine.compute()\n  const auto& buf = engine.results();\n\n  // loop over unique shell pairs, {s1,s2} such that s1 >= s2\n  // this is due to the permutational symmetry of the real integrals over Hermitian operators: (1|2) = (2|1)\n  for(auto s1=0; s1!=shells.size(); ++s1) {\n\n    auto bf1 = shell2bf[s1]; // first basis function in this shell\n    auto n1 = shells[s1].size();\n\n    for(auto s2=0; s2<=s1; ++s2) {\n\n      auto bf2 = shell2bf[s2];\n      auto n2 = shells[s2].size();\n\n      // compute shell pair\n      engine.compute(shells[s1], shells[s2]);\n      if (buf[0] == nullptr)\n        continue;  // if all integrals screened out, skip to next quartet\n\n      // \"map\" buffer to a const Eigen Matrix, and copy it to the corresponding blocks of the result\n      Eigen::Map<const Matrix> buf_mat(buf[0], n1, n2);\n      result.block(bf1, bf2, n1, n2) = buf_mat;\n      if (s1 != s2) // if s1 >= s2, copy {s1,s2} to the corresponding {s2,s1} block, note the transpose!\n      result.block(bf2, bf1, n2, n1) = buf_mat.transpose();\n\n    }\n  }\n\n  return result;\n}\n\nMatrix compute_2body_fock(const std::vector<libint2::Shell>& shells,\n                          const Matrix& D) {\n  using libint2::Shell;\n  using libint2::Engine;\n  using libint2::Operator;\n\n  auto time_elapsed = std::chrono::duration<double>::zero();\n\n  const auto n = nbasis(shells);\n  auto shell2bf = map_shell_to_basis_function(shells);\n  Matrix Gtotal = Matrix::Zero(n,n);\n\n\n#pragma omp parallel\n// or try this if you do not want all variables shared by default\n//#pragma omp parallel default(none) shared(shells,shell2bf,D,Gtotal,time_elapsed)\n  {\n    const int tid = omp_get_thread_num();\n    const int nthread = omp_get_num_threads();\n    long count = 0;\n\n    // construct the 2-electron repulsion integrals engine\n    Engine engine(Operator::coulomb, max_nprim(shells), max_l(shells), 0);\n    Matrix G = Matrix::Zero(n,n);\n\n    // buf[0] points to the target shell set after every call  to engine.compute()\n    const auto &buf = engine.results();\n\n    // The problem with the simple Fock builder is that permutational symmetries of the Fock,\n    // density, and two-electron integrals are not taken into account to reduce the cost.\n    // To make the simple Fock builder efficient we must rearrange our computation.\n    // The most expensive step in Fock matrix construction is the evaluation of 2-e integrals;\n    // hence we must minimize the number of computed integrals by taking advantage of their permutational\n    // symmetry. Due to the multiplicative and Hermitian nature of the Coulomb kernel (and realness\n    // of the Gaussians) the permutational symmetry of the 2-e ints is given by the following relations:\n    //\n    // (12|34) = (21|34) = (12|43) = (21|43) = (34|12) = (43|12) = (34|21) = (43|21)\n    //\n    // (here we use chemists' notation for the integrals, i.e in (ab|cd) a and b correspond to\n    // electron 1, and c and d -- to electron 2).\n    //\n    // It is easy to verify that the following set of nested loops produces a permutationally-unique\n    // set of integrals:\n    // foreach a = 0 .. n-1\n    //   foreach b = 0 .. a\n    //     foreach c = 0 .. a\n    //       foreach d = 0 .. (a == c ? b : c)\n    //         compute (ab|cd)\n    //\n    // The only complication is that we must compute integrals over shells. But it's not that complicated ...\n    //\n    // The real trick is figuring out to which matrix elements of the Fock matrix each permutationally-unique\n    // (ab|cd) contributes. STOP READING and try to figure it out yourself. (to check your answer see below)\n\n    // loop over permutatinally-unique set of shells\n    for (auto s1 = 0; s1 != shells.size(); ++s1) {\n\n      auto bf1_first = shell2bf[s1]; // first basis function in this shell\n      auto n1 = shells[s1].size();   // number of basis functions in this shell\n\n      for (auto s2 = 0; s2 <= s1; ++s2) {\n\n        auto bf2_first = shell2bf[s2];\n        auto n2 = shells[s2].size();\n\n        for (auto s3 = 0; s3 <= s1; ++s3) {\n\n          auto bf3_first = shell2bf[s3];\n          auto n3 = shells[s3].size();\n\n          const auto s4_max = (s1 == s3) ? s2 : s3;\n          for (auto s4 = 0; s4 <= s4_max; ++s4, ++count) {\n\n            if (tid == (count%nthread)) {\n              auto bf4_first = shell2bf[s4];\n              auto n4 = shells[s4].size();\n\n              // compute the permutational degeneracy (i.e. # of equivalents) of the given shell set\n              auto s12_deg = (s1 == s2) ? 1.0 : 2.0;\n              auto s34_deg = (s3 == s4) ? 1.0 : 2.0;\n              auto s12_34_deg = (s1 == s3) ? (s2 == s4 ? 1.0 : 2.0) : 2.0;\n              auto s1234_deg = s12_deg * s34_deg * s12_34_deg;\n\n              const auto tstart = std::chrono::high_resolution_clock::now();\n\n              engine.compute(shells[s1], shells[s2], shells[s3], shells[s4]);\n              const auto *buf_1234 = buf[0];\n              if (buf_1234 == nullptr)\n                continue; // if all integrals screened out, skip to next quartet\n\n              const auto tstop = std::chrono::high_resolution_clock::now();\n              time_elapsed += tstop - tstart;\n\n              // ANSWER\n              // 1) each shell set of integrals contributes up to 6 shell sets of the Fock matrix:\n              //    F(a,b) += (ab|cd) * D(c,d)\n              //    F(c,d) += (ab|cd) * D(a,b)\n              //    F(b,d) -= 1/4 * (ab|cd) * D(a,c)\n              //    F(b,c) -= 1/4 * (ab|cd) * D(a,d)\n              //    F(a,c) -= 1/4 * (ab|cd) * D(b,d)\n              //    F(a,d) -= 1/4 * (ab|cd) * D(b,c)\n              // 2) each permutationally-unique integral (shell set) must be scaled by its degeneracy,\n              //    i.e. the number of the integrals/sets equivalent to it\n              // 3) the end result must be symmetrized\n              for (auto f1 = 0, f1234 = 0; f1 != n1; ++f1) {\n                const auto bf1 = f1 + bf1_first;\n                for (auto f2 = 0; f2 != n2; ++f2) {\n                  const auto bf2 = f2 + bf2_first;\n                  for (auto f3 = 0; f3 != n3; ++f3) {\n                    const auto bf3 = f3 + bf3_first;\n                    for (auto f4 = 0; f4 != n4; ++f4, ++f1234) {\n                      const auto bf4 = f4 + bf4_first;\n\n                      const auto value = buf_1234[f1234];\n\n                      const auto value_scal_by_deg = value * s1234_deg;\n\n                      G(bf1, bf2) += D(bf3, bf4) * value_scal_by_deg;\n                      G(bf3, bf4) += D(bf1, bf2) * value_scal_by_deg;\n                      G(bf1, bf3) -= 0.25 * D(bf2, bf4) * value_scal_by_deg;\n                      G(bf2, bf4) -= 0.25 * D(bf1, bf3) * value_scal_by_deg;\n                      G(bf1, bf4) -= 0.25 * D(bf2, bf3) * value_scal_by_deg;\n                      G(bf2, bf3) -= 0.25 * D(bf1, bf4) * value_scal_by_deg;\n                    }\n                  }\n                }\n              }\n            }\n\n          }\n        }\n      }\n    }\n\n#pragma omp critical\n    { Gtotal += G; }\n\n  } // OMP parallel section\n\n  // symmetrize the result and return\n  Matrix Gtotal_t = Gtotal.transpose();\n  return 0.5 * (Gtotal + Gtotal_t);\n}\n", "meta": {"hexsha": "58baf2a555b206fe600499ec233cb3c1f93d6703", "size": 23955, "ext": "cc", "lang": "C++", "max_stars_repo_path": "OldHPCSummerSchool/Hartree-Fock/hf.v3.omp/scf.cc", "max_stars_repo_name": "wadejong/Summer-School-Materials", "max_stars_repo_head_hexsha": "82469995a79c667e940313d423e93c7c675e0a7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T22:18:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-15T06:04:43.000Z", "max_issues_repo_path": "OldHPCSummerSchool/Hartree-Fock/hf.v3.omp/scf.cc", "max_issues_repo_name": "wadejong/Summer-School-Materials", "max_issues_repo_head_hexsha": "82469995a79c667e940313d423e93c7c675e0a7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OldHPCSummerSchool/Hartree-Fock/hf.v3.omp/scf.cc", "max_forks_repo_name": "wadejong/Summer-School-Materials", "max_forks_repo_head_hexsha": "82469995a79c667e940313d423e93c7c675e0a7c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-07-30T17:21:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-21T15:54:16.000Z", "avg_line_length": 33.5974754558, "max_line_length": 121, "alphanum_fraction": 0.5587977458, "num_tokens": 6930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563824, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5228069406729525}}
{"text": "\n\n\n#ifndef HELPERSDNA \n#define HELPERSDNA\n\n#include <boost/operators.hpp>\n#include <iostream>\n#include <ostream>\n#include <boost/bimap.hpp>\n#include <string>\n#include <map>\n#include<vector>\n\nusing namespace std;\n\n\ntemplate<class vectt>\nunsigned hamming_distance(vectt& v1,vectt& v2){\n\tassert(v1.size()=v2.size());\n\tunsigned hd = 0;\n\tfor(unsigned i=0;i<v1.size();++i)\n\t\tif(v1[i] != v2[i]) hd++;\n\treturn hd;\n}\n\ntemplate<class vectt>\nvoid flipvecdir(vectt& v){\n\tvectt tmp = v;\n\tfor(unsigned i=0;i<v.size();++i){\n\t\tv[i] = tmp[v.size()-1-i];\n\t}\n}\n\n\n// convert decimal number to a number with another base\ntemplate<class base_t>\nvector<base_t> tobase(unsigned nu, unsigned base, unsigned size){\n\t\n\tvector<base_t> nn(size,(base_t) 0 ); \n\tif(nu == 0) return nn;\n\t\n\tunsigned div = nu;\n\tunsigned i = 0;\n\twhile(div != 0){\n\t\tnn[i] = base_t(div % base); // rest\n\t\tdiv = div/base;\t\n\t\ti++;\n\t}\n\treturn nn;\n};\n\n\n// convert vector of numbers in some basis to \ntemplate<class base_t>\nunsigned frombase(const vector<base_t>& nn,unsigned base){\n\tint nu = 0;\n\t//base_t adf =  nn[0];\n\t//int adfi =  (int) adf;\n\tunsigned basepow = 1;\n\tfor(unsigned i=0;i<nn.size();++i) {\n\t\t\n\t\tbase_t adf = nn[i];\n\t\tnu += ((unsigned)adf) * basepow;//((unsigned) (adf)) * ((int) pow((double) base,(int) i));\n\t\tbasepow *= base;\n\t}\n\treturn nu;\n};\n\n// converts each 2 characters in data_char to 3 elements of GF(47), which are appended at \ntemplate<class pfe>\nvoid char2pfe(string& data_char, vector<pfe>& data_b47){\n    if((data_char.size() % 2) != 0 )data_char.push_back('\\n');\n   \n    data_b47.resize(0);\n\t// convert vector of char to vector with base 47;\n    // every 2 char's are coded to three pfe's \n    for(unsigned i=0;i<data_char.size()/2; ++i){\n        // the unsigned char type below is important, otherwise errors occur when converting..\n\t\tunsigned indec = frombase(vector<unsigned char>(data_char.begin()+i*2, data_char.begin()+i*2+2),256);\n        vector<char> adf(data_char.begin()+i*2, data_char.begin()+i*2+2);\n        //for(unsigned j=0;j<adf.size();++j) cout << adf[j];\n        //cout << endl;\n        \n        vector<pfe> tmpvec = tobase<pfe>(indec,47,3);\n        data_b47.insert(data_b47.begin()+i*3,tmpvec.begin(),tmpvec.end());\n    \t//cout << i*3 << \"  \" << data_b47.size() << endl;\n\t}\n};\n\n\ntemplate<class pfe>\nvoid pfe2char(string& data_char, vector<pfe>& data_b47){\n    \n    assert(data_b47.size() % 3  == 0);\n\n    data_char.resize(2*(data_char.size()/3) );\n    // convert vector of char to vector with base 47;\n    // every 2 char's are coded to three pfe's \n    for(unsigned i=0;i<data_b47.size()/3; ++i){\n        unsigned indec = frombase(vector<pfe>(data_b47.begin()+i*3, data_b47.begin()+i*3+3),47);\n        //vector<char> adf(data_b47.begin()+i*3, data_b47.begin()+i*3+3);\n        //for(unsigned j=0;j<adf.size();++j) cout << adf[j];\n        //cout << endl;\n        \n        vector<char> tmpvec = tobase<char>(indec,256,2);\n        data_char.insert(data_char.begin()+i*2,tmpvec.begin(),tmpvec.end());\n    }\n\n};\n\n\n\n/*\nmaps each element of GF(47) to a string with letters {A,C,G,T} where \n*/\n\ntemplate<class PFE>\nclass DNAmap{\nprivate: \n\t//typedef boost::bimap< PFE , std::string > mapdna_type;\n\t//mapdna_type mapdna;\n\t\n\tmap<PFE,string> pfetostr;\n\tmap<string,PFE> strtopfe;\n\npublic: \n\tDNAmap(){\n\t\t//initialize map\n\t\tunsigned prime = 47;\n\t\t\n\t\tchar nucl[] = \"ACGT\"; // nucleotides\t\n\n\t\tvector<string> allpos(4*4*4);\n\t\tfor(unsigned i=0;i<allpos.size();++i){\n\t\t\tchar cur[] = \"AAA\";\n\t\t\tcur[0] = nucl[i % 4];\n\t\t\tcur[1] = nucl[(i/4) % 4];\n\t\t\tcur[2] = nucl[(i/16) % 4];\n\t\t\tallpos[i] = string(cur);\n\t\t}\n\t\t\n\t\tunsigned j = 0;\n\t\tfor(unsigned i=0;i<prime;++i){\n\t\t\twhile( allpos[j][1] == allpos[j][2]) j++;\n\t\t\t//mapdna.insert( typename mapdna_type::value_type(PFE(i), allpos[j] ));\n\t\t\tpfetostr[PFE(i)] = allpos[j];\n\t\t\tstrtopfe[allpos[j]] = PFE(i);\n\t\t\t\n\t\t\tj++;\n\t\t}\n\t\t//print_map(mapdna.right, \" \", cout);\n\t}\n\n\t/*\n\tvoid printmap(){\n\t\tfor(auto it = pfetostr.cbegin(); it != pfetostr.cend(); ++it){\n    \t\tstd::cout << it->first << \" \" << it->second << std::endl;\n\t\t}\n\t}\n\t*/\n\n\t// codeword to DNA fragment\n\tvoid cw2frag(const vector<PFE>& cw, string& frag ){\n\t\tfrag.resize(0);\n\t\tfor(unsigned i=0;i<cw.size();++i){\n\t\t\tfrag.append(pfetostr[cw[i]]); //mapdna.left.at(cw[i]); \n\t\t}\n\t}\n\t\n\t// DNA fragment to codeword\n\tvoid frag2cw(vector<PFE>& cw, const string& frag ){\n\t\tassert( (frag.size() % 3) == 0   );\n\t\tcw.resize(frag.size()/3);\n\t\tfor(unsigned i=0;i<cw.size();++i){ \n\t\t\n\t\t\t//char charartmp[] = \"AAA\"; // nucleotides\t\n\t\t\t//charartmp[0] = frag[i*3];\n\t\t\t//charartmp[1] = frag[i*3+1];\n\t\t\t//charartmp[2] = frag[i*3+2];\n\t\t\t//string tmp(charartmp);\n\t\t\tstring tmp = string(frag.begin()+i*3, frag.begin()+i*3+3  );\n\t\t\t\t\n\t\t\t//print_map(mapdna.right, \" \", cout);\n\t\t\t\n\t\t\t//cout <<  mapdna.right.at(tmp )  << endl; \n\t\t\t//cw[i] = PFE( mapdna.right.at(tmp ) ); \n\t\t\tcw[i] = strtopfe[tmp];\n\t\t\t//cout << cw[i] << endl;\n\t\t}\n\t}\n\n\n\n\n\n\n\n};\n\n#endif\n", "meta": {"hexsha": "b1ef43d6013b9eaa5fbc47f6b2189c57eac7f78b", "size": 4890, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "DNA_data_storage/include/helpers.hpp", "max_stars_repo_name": "reinhardh/dna_data_storage", "max_stars_repo_head_hexsha": "e701abccf44119dcd8402b407d7dfd3b597f3a69", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-12-12T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T17:58:00.000Z", "max_issues_repo_path": "DNA_data_storage/include/helpers.hpp", "max_issues_repo_name": "reinhardh/dna_data_storage", "max_issues_repo_head_hexsha": "e701abccf44119dcd8402b407d7dfd3b597f3a69", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-22T19:55:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T19:55:28.000Z", "max_forks_repo_path": "DNA_data_storage/include/helpers.hpp", "max_forks_repo_name": "reinhardh/dna_data_storage", "max_forks_repo_head_hexsha": "e701abccf44119dcd8402b407d7dfd3b597f3a69", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-21T23:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-21T23:57:51.000Z", "avg_line_length": 24.2079207921, "max_line_length": 103, "alphanum_fraction": 0.6024539877, "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867825403176, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.522728327429206}}
{"text": "#include <boost/mp11/mpl.hpp>\n#include <type_traits>\n#include <string>\n\ntemplate <int I>\nusing int_ = std::integral_constant<int, I>;\n\nusing namespace boost::mp11;\n\ntemplate <typename Sequence, typename Value>\nstruct index_of_impl\n{\n\tusing index = mp_find<Sequence, Value>;\n\tusing size = mp_size<Sequence>;\n\tusing index_smaller_than_size = mp_less<index, size>;\n\tusing type = mp_if<index_smaller_than_size, index, int_<-1>>;\n};\n\ntemplate <typename Sequence, typename Value>\nusing index_of = typename index_of_impl<Sequence, Value>::type;\n\nint main()\n{\n\tusing l = mp_list<std::string, int, bool>;\n\n\tconstexpr int r1 = index_of<l, bool>::value;\n\tstatic_assert(r1 == 2);\n\n\tconstexpr int r2 = index_of<l, double>::value;\n\tstatic_assert(r2 == -1);\n}\n", "meta": {"hexsha": "b70f4772aa4ff301a3dd8dd32114ed33bdc54b41", "size": 745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "07_mp11_with_types/main.cpp", "max_stars_repo_name": "BorisSchaeling/boost-meta-programming-2020", "max_stars_repo_head_hexsha": "1bb70e88070953daa4bc19f91f891b43583df06e", "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": "07_mp11_with_types/main.cpp", "max_issues_repo_name": "BorisSchaeling/boost-meta-programming-2020", "max_issues_repo_head_hexsha": "1bb70e88070953daa4bc19f91f891b43583df06e", "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": "07_mp11_with_types/main.cpp", "max_forks_repo_name": "BorisSchaeling/boost-meta-programming-2020", "max_forks_repo_head_hexsha": "1bb70e88070953daa4bc19f91f891b43583df06e", "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.28125, "max_line_length": 63, "alphanum_fraction": 0.7302013423, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5227283251969282}}
{"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 <ceres/ceres.h>\n#include <ceres/rotation.h>\n#include <sophus/se3.hpp>\n#include <chrono>\n\nusing namespace std;\nusing namespace cv;\n\n// void 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\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 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  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  detector->detect(img_1, keypoints_1);\n  detector->detect(img_2, keypoints_2);\n\n  descriptor->compute(img_1, keypoints_1, descriptors_1);\n  descriptor->compute(img_2, keypoints_2, descriptors_2);\n\n  vector<DMatch> match;\n  // BFMatcher matcher ( NORM_HAMMING );\n  matcher->match(descriptors_1, descriptors_2, match);\n\n  double min_dist = 10000, max_dist = 0;\n\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  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\n\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\ntypedef vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> VecVector3d;\n\n\nstruct ProjectionError\n{\n  ProjectionError(const Eigen::Vector2d& measurement, const Eigen::Vector3d& point,\n                  const Eigen::Matrix3d& K) : _x(measurement), _X(point), _K(K)\n    {}\n\n  template <class T>\n  bool operator() (const T* const params, T* residuals) const\n  {\n    T X[3] = {T(_X.x()), T(_X.y()), T(_X.z())};\n    T rot_X[3];\n    ceres::UnitQuaternionRotatePoint(params, X, rot_X);\n    rot_X[0] += params[4];\n    rot_X[1] += params[5];\n    rot_X[2] += params[6];\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    \n    // T fx = T(_K(0, 0));\n    // T fy = T(_K(1, 1));\n    // T cx = T(_K(0, 2));\n    // T cy = T(_K(1, 2));\n\n    residuals[0] = _x[0] - ((rot_X[0] / rot_X[2]) * fx + cx); // parentheses have importance but do not known why\n    residuals[1] = _x[1] - ((rot_X[1] / rot_X[2]) * fy + cy);\n\n\n    // T rot[9];\n    // ceres::QuaternionToRotation(params, rot);\n    // Eigen::Matrix<T, 3, 3> R;\n    // R << rot[0], rot[1], rot[2],\n    //      rot[3], rot[4], rot[5],\n    //      rot[6], rot[7], rot[8];\n\n    // Eigen::Matrix<T, 3, 1> p(T(_X.x()), T(_X.y()), T(_X.z()));\n    // Eigen::Matrix<T, 3, 1> t(params[4], params[5], params[6]);\n\n    // Eigen::Matrix<T, 3, 3> K;\n    // K << T(_K(0, 0)),  T(_K(0, 1)),  T(_K(0, 2)),\n    //      T(_K(1, 0)),  T(_K(1, 1)),  T(_K(1, 2)),\n    //      T(_K(2, 0)),  T(_K(2, 1)),  T(_K(2, 2));\n    // Eigen::Matrix<T, 3, 1> p2 = K * (R * p + t);\n\n    // residuals[0] = _x[0] - p2.x()/p2.z();\n    // residuals[1] = _x[1] - p2.y()/p2.z();\n\n    return true;\n  }\n\n  private:\n    Eigen::Vector2d _x;\n    Eigen::Vector3d _X;\n    Eigen::Matrix3d _K;\n};\n\n\n\n\nvoid pose_refinement_ceres(const VecVector3d& points_3d, const VecVector2d& points_2d, const Eigen::Matrix3d& K, Sophus::SE3d& pose)\n{\n  Eigen::Vector3d trans = pose.translation();\n  Eigen::Quaterniond quat = pose.so3().unit_quaternion();\n\n  double pose_params[7] = {\n    quat.w(), quat.x(), quat.y(), quat.z(), trans.x(), trans.y(), trans.z()\n  };\n\n  ceres::Problem problem;\n  for (int i = 0; i < points_3d.size(); ++i)\n  {\n    problem.AddResidualBlock(\n      new ceres::AutoDiffCostFunction<ProjectionError, 2, 7>(\n      // new ceres::NumericDiffCostFunction<ProjectionError, ceres::CENTRAL, 2, 7>(\n        new ProjectionError(points_2d[i], points_3d[i], K)\n      ),\n      nullptr,\n      pose_params\n    );\n  }\n  auto *quat_t_parameterization = new ceres::ProductParameterization(new ceres::QuaternionParameterization(),\n                                                                     new ceres::IdentityParameterization(3));\n  problem.SetParameterization(pose_params, quat_t_parameterization);\n\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;\n  options.minimizer_progress_to_stdout = false;\n\n  ceres::Solver::Summary summary;\n  chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n  ceres::Solve(options, &problem, &summary);\n  chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n  \n  chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double >>(t2 - t1);\n  cout << \"optimization with ceres costs time: \" << time_used.count() << \" seconds.\" << endl;\n  std::cout << summary.BriefReport() << std::endl;\n\n  Eigen::Quaterniond q(pose_params[0], pose_params[1], pose_params[2], pose_params[3]);\n  Eigen::Vector3d t(pose_params[4], pose_params[5], pose_params[6]);\n\n  pose = Sophus::SE3d(q.toRotationMatrix(), t);\n}\n\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  string f1 = \"../1.png\"; //argv[1];\n  string f2 = \"../2.png\"; //argv[2];\n  string f3 = \"../1_depth.png\"; //argv[3];\n  Mat img_1 = imread(f1, CV_LOAD_IMAGE_COLOR);\n  Mat img_2 = imread(f2, 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\n  Mat d1 = imread(f3, CV_LOAD_IMAGE_UNCHANGED);\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);\n  Mat R;\n  cv::Rodrigues(r, R);\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\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  Eigen::Matrix3d K_eigen;\n  K_eigen << 520.9, 0, 325.1,\n             0, 521.0, 249.7,\n             0, 0, 1;\n\n  // Ceres\n  cout << \"Custom Ceres\" << endl;\n  Sophus::SE3d pose_ceres;\n  pose_refinement_ceres(pts_3d_eigen, pts_2d_eigen, K_eigen, pose_ceres);\n  Eigen::Vector3d t_ceres = pose_ceres.translation();\n  Eigen::Matrix3d R_ceres = pose_ceres.so3().unit_quaternion().toRotationMatrix();\n  cout << \"R_ceres = \" << endl << R_ceres << endl;\n  cout << \"t_ceres = \" << endl << t_ceres << endl;\n\n  return 0;\n}\n\n", "meta": {"hexsha": "44710a138ba61b41b9218e1492b2d4195898d333", "size": 8363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7/pose_estimation_3d2d_ceres_quat.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": "ch7/pose_estimation_3d2d_ceres_quat.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": "ch7/pose_estimation_3d2d_ceres_quat.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": 33.1865079365, "max_line_length": 132, "alphanum_fraction": 0.6208298457, "num_tokens": 2788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867825403177, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5227283220529775}}
{"text": "\n#include <alglib/ap.h>\n#include <alglib/interpolation.h>\n\n#include \"spline-1d.hpp\"\n\n#define This Spline1d\n\nnamespace perceive\n{\n// ----------------------------------------------------------- inclusive-between\n\n// inclusive_between<int>(5, x, 8);\ntemplate<typename T>\ninline bool\ninclusive_between(const T& low_bound, const T& value, const T& high_bound)\n{\n   return value <= high_bound && value >= low_bound;\n}\n\n// ----------------------------------------------------------------------- Pimpl\n\nclass This::Pimpl\n{\n public:\n   Pimpl()\n       : is_init(false)\n       , n_control_points(0)\n       , approx_length(dNAN)\n   {}\n\n   bool is_init;\n   uint n_control_points;\n   double approx_length;\n   alglib::spline1dinterpolant spline_x;\n   alglib::spline1dfitreport rep_x;\n\n   double min_x{0.0};\n   double max_x{1.0};\n   double range_inv{1.0}; // 1.0 / (max_x - min_x)\n\n   void update_range_inv() { range_inv = 1.0 / (max_x - min_x); }\n};\n\n// ---------------------------------------------------------------- Construction\n\nThis::Spline1d()\n    : pimpl(make_unique<Pimpl>())\n{}\n\nThis::Spline1d(const Spline1d& rhs)\n    : Spline1d()\n{\n   *this = rhs;\n}\n\nThis::Spline1d(Spline1d&& rhs)\n    : pimpl{nullptr}\n{\n   *this = std::move(rhs);\n}\n\nThis::Spline1d(const std::vector<double>& ps, double rho, int M_factor)\n    : Spline1d()\n{\n   init(ps, rho, M_factor);\n}\nThis::Spline1d(const std::vector<float>& ps, double rho, int M_factor)\n    : Spline1d()\n{\n   init(ps, rho, M_factor);\n}\nThis::Spline1d(const std::vector<Vector2>& ps, double rho, int M_factor)\n    : Spline1d()\n{\n   init(ps, rho, M_factor);\n}\nThis::Spline1d(const std::deque<double>& ps, double rho, int M_factor)\n    : Spline1d()\n{\n   init(ps, rho, M_factor);\n}\nThis::Spline1d(const std::deque<float>& ps, double rho, int M_factor)\n    : Spline1d()\n{\n   init(ps, rho, M_factor);\n}\nThis::Spline1d(const std::deque<Vector2>& ps, double rho, int M_factor)\n    : Spline1d()\n{\n   init(ps, rho, M_factor);\n}\n\nThis::Spline1d(const std::vector<array<double, 6>>& coefficients)\n    : Spline1d()\n{\n   init(coefficients);\n}\n\nThis::~Spline1d() = default;\n\nSpline1d& This::operator=(const Spline1d& rhs)\n{\n   if(this != &rhs) *pimpl = *rhs.pimpl;\n   return *this;\n}\n\nSpline1d& This::operator=(Spline1d&& rhs) = default;\n\n// ------------------------------------------------------------------- Accessors\n\nbool This::is_init() const { return pimpl->is_init; }\nuint This::n_control_points() const { return pimpl->n_control_points; }\ndouble This::approx_length() const { return pimpl->approx_length; }\n\ndouble This::rms_error() const { return pimpl->rep_x.rmserror; }\ndouble This::avg_error() const { return pimpl->rep_x.avgerror; }\ndouble This::avg_rel_error() const { return pimpl->rep_x.avgrelerror; }\ndouble This::max_error() const { return pimpl->rep_x.maxerror; }\n\nreal This::min_x() const { return pimpl->min_x; }\nreal This::max_x() const { return pimpl->max_x; }\nvoid This::set_min_x(real x)\n{\n   pimpl->min_x = x;\n   pimpl->update_range_inv();\n}\nvoid This::set_max_x(real x)\n{\n   pimpl->max_x = x;\n   pimpl->update_range_inv();\n}\n\n// -------------------------------------------------------------------- p-spline\n\n/*************************************************************************\nFitting by penalized cubic spline.\n\nEquidistant grid with M nodes on [min(x,xc),max(x,xc)] is  used  to  build\nbasis functions. Basis functions are cubic splines with  natural  boundary\nconditions. Problem is regularized by  adding non-linearity penalty to the\nusual least squares penalty function:\n\n    S(x) = arg min { LS + P }, where\n    LS   = SUM { w[i]^2*(y[i] - S(x[i]))^2 } - least squares penalty\n    P    = C*10^rho*integral{ S''(x)^2*dx } - non-linearity penalty\n    rho  - tunable constant given by user\n    C    - automatically determined scale parameter,\n           makes penalty invariant with respect to scaling of X, Y, W.\n\nINPUT PARAMETERS:\n    X   -   points, array[0..N-1].\n    Y   -   function values, array[0..N-1].\n    N   -   number of points (optional):\n            * N>0\n            * if given, only first N elements of X/Y are processed\n            * if not given, automatically determined from X/Y sizes\n    M   -   number of basis functions ( = number_of_nodes), M>=4.\n    Rho -   regularization  constant  passed   by   user.   It   penalizes\n            nonlinearity in the regression spline. It  is  logarithmically\n            scaled,  i.e.  actual  value  of  regularization  constant  is\n            calculated as 10^Rho. It is automatically scaled so that:\n            * Rho=2.0 corresponds to moderate amount of nonlinearity\n            * generally, it should be somewhere in the [-8.0,+8.0]\n            If you do not want to penalize nonlineary,\n            pass small Rho. Values as low as -15 should work.\n\nOUTPUT PARAMETERS:\n    Info-   same format as in LSFitLinearWC() subroutine.\n            * Info>0    task is solved\n            * Info<=0   an error occured:\n                        -4 means inconvergence of internal SVD or\n                           Cholesky decomposition; problem may be\n                           too ill-conditioned (very rare)\n    S   -   spline interpolant.\n    Rep -   Following fields are set:\n            * RMSError      rms error on the (X,Y).\n            * AvgError      average error on the (X,Y).\n            * AvgRelError   average relative error on the non-zero Y\n            * MaxError      maximum error\n                            NON-WEIGHTED ERRORS ARE CALCULATED\n\nIMPORTANT:\n    this subroitine doesn't calculate task's condition number for K<>0.\n\nNOTE 1: additional nodes are added to the spline outside  of  the  fitting\ninterval to force linearity when x<min(x,xc) or x>max(x,xc).  It  is  done\nfor consistency - we penalize non-linearity  at [min(x,xc),max(x,xc)],  so\nit is natural to force linearity outside of this interval.\n\nNOTE 2: function automatically sorts points,  so  caller may pass unsorted\narray.\n\n  -- ALGLIB PROJECT --\n     Copyright 18.08.2009 by Bochkanov Sergey\n*************************************************************************/\n\ntemplate<typename U>\nbool init_pspline(Spline1d& curve,\n                  const U& container,\n                  double rho,\n                  unsigned M_factor)\n{\n   curve.pimpl->n_control_points = 0;\n   curve.pimpl->is_init          = false;\n   curve.pimpl->approx_length    = dNAN;\n\n   const uint32_t len = uint32_t(container.size());\n   if(len < 5) return false;\n\n   alglib::real_1d_array T;\n   alglib::real_1d_array X;\n   T.setlength(len);\n   X.setlength(len);\n\n   alglib::ae_int_t counter = 0;\n   double t                 = 0.0;\n   double dt                = 1.0 / double(len - 1);\n   for(const auto& p : container) {\n      T[counter] = t;\n      X[counter] = real(p);\n      t += dt;\n      counter++;\n   }\n\n   alglib::ae_int_t info_x;\n   alglib::ae_int_t M = std::max<int>(4, int(M_factor));\n\n   alglib::spline1dfitpenalized(\n       T, X, M, rho, info_x, curve.pimpl->spline_x, curve.pimpl->rep_x);\n\n   curve.pimpl->n_control_points = unsigned(M);\n\n   if(info_x > 0) {\n      curve.pimpl->is_init       = true;\n      curve.pimpl->approx_length = 0.0;\n      double dt                  = 0.1 / double(M - 1);\n      real p                     = curve.evaluate_t(0.0);\n      for(double t = dt; t <= 1.0; t += dt) {\n         real q = curve.evaluate_t(t);\n         curve.pimpl->approx_length += fabs(p - q);\n         p = q;\n      }\n   }\n\n   return curve.pimpl->is_init;\n}\n\ntemplate<typename U>\nbool init_pspline_xy(Spline1d& curve,\n                     const U& container,\n                     double rho,\n                     unsigned M_factor)\n{\n   curve.pimpl->n_control_points = 0;\n   curve.pimpl->is_init          = false;\n   curve.pimpl->approx_length    = dNAN;\n\n   const unsigned len = unsigned(container.size());\n   if(len < 5) return false;\n\n   alglib::real_1d_array X;\n   alglib::real_1d_array Y;\n   X.setlength(len);\n   Y.setlength(len);\n\n   double min_x = std::numeric_limits<double>::max();\n   double max_x = std::numeric_limits<double>::lowest();\n\n   uint counter = 0;\n   for(const auto& p : container) {\n      X[counter] = p.x;\n      Y[counter] = p.y;\n      if(p.x < min_x) min_x = p.x;\n      if(p.x > max_x) max_x = p.x;\n      counter++;\n   }\n\n   double range_inv = 1.0 / (max_x - min_x);\n\n   // Now scale the 'X' values\n   for(unsigned i = 0; i < len; ++i) X[i] = (X[i] - min_x) * range_inv;\n\n   alglib::ae_int_t info_x;\n   alglib::ae_int_t M = std::max<int>(4, int(M_factor));\n\n   alglib::spline1dfitpenalized(\n       X, Y, M, rho, info_x, curve.pimpl->spline_x, curve.pimpl->rep_x);\n\n   curve.pimpl->n_control_points = unsigned(M);\n\n   if(info_x > 0) {\n      curve.pimpl->is_init       = true;\n      curve.pimpl->approx_length = 0.0;\n      curve.set_min_x(min_x);\n      curve.set_max_x(max_x);\n   }\n\n   return curve.pimpl->is_init;\n}\n\n// ------------------------------------------------------------------------ Init\n\nbool This::init(const std::vector<double>& ps, double rho, int M_factor)\n{\n   return init_pspline(*this, ps, rho, unsigned(M_factor));\n}\n\nbool This::init(const std::deque<double>& ps, double rho, int M_factor)\n{\n   return init_pspline(*this, ps, rho, unsigned(M_factor));\n}\n\nbool This::init(const std::vector<float>& ps, double rho, int M_factor)\n{\n   return init_pspline(*this, ps, rho, unsigned(M_factor));\n}\n\nbool This::init(const std::deque<float>& ps, double rho, int M_factor)\n{\n   return init_pspline(*this, ps, rho, unsigned(M_factor));\n}\n\nbool This::init(const std::vector<Vector2>& ps, double rho, int M_factor)\n{\n   return init_pspline_xy(*this, ps, rho, unsigned(M_factor));\n}\n\nbool This::init(const std::deque<Vector2>& ps, double rho, int M_factor)\n{\n   return init_pspline_xy(*this, ps, rho, unsigned(M_factor));\n}\n\n// -------------------------------------------------------------------- Evaluate\n\nreal This::evaluate_t(double t) const\n{\n   // assert(t >= 0.0 && t <= 1.0);\n   return is_init() ? real(alglib::spline1dcalc(pimpl->spline_x, t))\n                    : real(NAN);\n}\n\nreal This::evaluate(double x) const\n{\n   // assert(min-x >= 0.0 && max-x <= 1.0);\n   // cout << format(\"t = {}\", (x - pimpl->min_x) * pimpl->range_inv) << endl;\n   return evaluate_t((x - pimpl->min_x) * pimpl->range_inv);\n}\n\n// ---------------------------------------------------------------------- Unpack\n\nstd::vector<array<double, 6>> This::unpack() const\n{\n   std::vector<array<double, 6>> out;\n   unpack(out);\n   return out;\n}\n\nvoid This::unpack(std::vector<array<double, 6>>& out) const\n{\n   alglib::ae_int_t nx{0};\n   alglib::real_2d_array tbl_x;\n   spline1dunpack(pimpl->spline_x, nx, tbl_x);\n\n   size_t N = size_t(tbl_x.rows());\n\n   out.resize(N + 1);\n   for(size_t ind = 0; ind < N; ++ind) {\n      auto& coeff = out[size_t(ind)];\n      auto ptr    = &coeff[0];\n      for(unsigned i = 0; i < 6; ++i) *ptr++ = tbl_x(alglib::ae_int_t(ind), i);\n   }\n\n   std::fill(out[N].begin(), out[N].end(), 0.0);\n   out[N][0] = pimpl->min_x;\n   out[N][1] = pimpl->max_x;\n}\n\nvoid This::init(const std::vector<array<double, 6>>& coefficients)\n{\n   using alglib::spline1dinterpolant;\n   auto make_interpolant = [&](spline1dinterpolant& interpolant) {\n      const unsigned n = unsigned(coefficients.size());\n      alglib::real_1d_array x, y, d; // (x, f(x), f'(x))\n      x.setlength(n);\n      y.setlength(n);\n      d.setlength(n);\n      unsigned pos = 0; // write position\n\n      auto write = [&](double t,\n                       double X0,\n                       double X1,\n                       double C0,\n                       double C1,\n                       double C2,\n                       double C3) {\n         x(pos) = X0 + t * (X1 - X0);\n         y(pos) = C0 + C1 * t + C2 * t * t + C3 * t * t * t;\n         d(pos) = C1 + 2.0 * C2 * t + 3.0 * C3 * t * t;\n         pos++;\n      };\n\n      for(unsigned ind = 0; ind < coefficients.size() - 1; ++ind) {\n         const auto& CC = coefficients[ind];\n         auto X0        = CC[0];\n         auto X1        = CC[1];\n         auto C0        = CC[2];\n         auto C1        = CC[3];\n         auto C2        = CC[4];\n         auto C3        = CC[5];\n         write(0.0, X0, X1, C0, C1, C2, C3);\n\n         // Write that final coefficient\n         if(ind == coefficients.size() - 2) write(1.0, X0, X1, C0, C1, C2, C3);\n      }\n\n      if(pos != n) { FATAL(format(\"pos = {} != {} = n\", pos, n)); }\n\n      alglib::spline1dbuildhermite(x, y, d, interpolant);\n   };\n\n   make_interpolant(pimpl->spline_x);\n\n   pimpl->is_init           = true;\n   pimpl->n_control_points  = unsigned(coefficients.size());\n   pimpl->rep_x.rmserror    = 0.0;\n   pimpl->rep_x.avgerror    = 0.0;\n   pimpl->rep_x.maxerror    = 0.0;\n   pimpl->rep_x.avgrelerror = 0.0;\n   pimpl->min_x             = coefficients.back()[0];\n   set_max_x(coefficients.back()[1]);\n}\n\n// ----------------------------------------------------------------- Interpolate\n\nvoid This::interpolate_t(unsigned n,\n                         std::vector<real>& out,\n                         double min_t,\n                         double max_t)\n{\n   assert(min_t >= 0.0 && min_t <= 1.0);\n   assert(max_t >= 0.0 && max_t <= 1.0);\n   assert(min_t <= max_t);\n\n   out.reserve(n);\n\n   if(n == 0)\n      return;\n   else if(n == 1)\n      out.push_back(evaluate_t(max_t));\n   else {\n      double t  = min_t;\n      double dt = (max_t - min_t) / double(n - 1);\n      for(unsigned i = 0; i < n - 1; ++i) {\n         out.push_back(evaluate_t(clamp(t, min_t, max_t)));\n         t += dt;\n      }\n      out.push_back(evaluate_t(max_t));\n   }\n\n   assert(out.size() == n);\n}\n\n// ---------------------------------------------------------------------- Smooth\n\nbool This::smooth(std::vector<real>& path, double rho, int M_factor)\n{\n   if(path.size() < 5) return false;\n   Spline1d spline;\n   if(!spline.init(path, rho, M_factor)) return false;\n   std::vector<real> t;\n   spline.interpolate_t(unsigned(path.size()), t);\n   if(!(t.size() == path.size()))\n      FATAL(format(\"Container size mismatch: expected {}, but got {}\",\n                   path.size(),\n                   t.size()));\n   auto src = t.begin();\n   auto dst = path.begin();\n   while(src != t.end()) *src++ = *dst++;\n   return true;\n}\n\n} // namespace perceive\n", "meta": {"hexsha": "800caff9ed69d176dcdb7f9cade901a8950bb5fe", "size": 14183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/geometry/splines/spline-1d.cpp", "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/splines/spline-1d.cpp", "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/splines/spline-1d.cpp", "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": 29.3037190083, "max_line_length": 80, "alphanum_fraction": 0.5573573997, "num_tokens": 3946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5227283135327981}}
{"text": "/*!\n * Copyright (C) tkornuta, IBM Corporation 2015-2019\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 mnist_convnet_features_visualization_test.cpp\n * @brief Program for visualization of features of convolutional neural net trained on MNIST digits.\n * @author tkornuta\n * @date:   03-04-2017\n *\n * Copyright (c) 2017, Tomasz Kornuta, IBM Corporation. All rights reserved.\n *\n */\n\n#include <boost/thread/thread.hpp>\n#include <boost/bind.hpp>\n\n#include <importers/MNISTMatrixImporter.hpp>\n\n#include <logger/Log.hpp>\n#include <logger/ConsoleOutput.hpp>\nusing namespace mic::logger;\n\n#include <application/ApplicationState.hpp>\n\n#include <configuration/ParameterServer.hpp>\n\n#include <opengl/visualization/WindowManager.hpp>\n#include <opengl/visualization/WindowGrayscaleBatch.hpp>\n#include <opengl/visualization/WindowCollectorChart.hpp>\nusing namespace mic::opengl::visualization;\n\n// Neural net.\n#include <mlnn/BackpropagationNeuralNetwork.hpp>\nusing namespace mic::mlnn;\n\n// Encoders.\n#include <encoders/MatrixXfMatrixXfEncoder.hpp>\n#include <encoders/UIntMatrixXfEncoder.hpp>\n\n/// Windows for displaying activations.\nWindowGrayscaleBatch<float> *w_conv10, *w_conv11, *w_conv12, *w_conv13, *w_conv14, *w_conv15, *w_conv16;\nWindowGrayscaleBatch<float> *w_conv20, *w_conv21, *w_conv22, *w_conv23, *w_conv24, *w_conv25;\nWindowGrayscaleBatch<float> *w_conv30, *w_conv31, *w_conv32, *w_conv33, *w_conv34, *w_conv35;\n/// Window for displaying chart with statistics.\nWindowCollectorChart<float>* w_chart;\n/// Data collector.\nmic::utils::DataCollectorPtr<std::string, float> collector_ptr;\n\n\n/// MNIST importer.\nmic::importers::MNISTMatrixImporter<float>* importer;\n/// Multi-layer neural network.\nBackpropagationNeuralNetwork<float> neural_net;\n\n/// MNIST matrix encoder.\nmic::encoders::MatrixXfMatrixXfEncoder* mnist_encoder;\n/// Label 2 matrix encoder (1 hot).\nmic::encoders::UIntMatrixXfEncoder* label_encoder;\n\nconst size_t batch_size = 1;\nconst char* convent_filename = \"nn_convent.txt\";\nconst char* convnet_log = \"nn_convent_log.csv\";\n\n\n/*!\n * \\brief Function for batch sampling.\n * \\author tkornuta\n */\nvoid batch_function (void) {\n\n/*\tif (neural_net.load(convent_filename)) {\n\t\tLOG(LINFO) << \"Loaded neural network from a file\";\n\t} else {*/\n\t\t{\n\t\t\tneural_net.pushLayer(new mic::mlnn::convolution::Cropping<float>(28, 28, 1, 2));\n\t\t\tneural_net.pushLayer(new mic::mlnn::convolution::Convolution<float>(24, 24, 1, 9, 5, 1));\n\t\t\tneural_net.pushLayer(new ELU<float>(20, 20, 9));\n\t\t\tneural_net.pushLayer(new mic::mlnn::convolution::MaxPooling<float>(20, 20, 9, 2));\n\n\t\t\tneural_net.pushLayer(new mic::mlnn::convolution::Convolution<float>(10, 10, 9, 16, 7, 1));\n\t\t\tneural_net.pushLayer(new ELU<float>(4, 4, 16));\n\t\t\tneural_net.pushLayer(new mic::mlnn::convolution::MaxPooling<float>(4, 4, 16, 2));\n\n\t\t\tneural_net.pushLayer(new Linear<float>(2, 2, 16, 10, 1, 1));\n\t\t\tneural_net.pushLayer(new Softmax<float>(10));\n\n\t\t\tif (!neural_net.verify())\n\t\t\t\texit(-1);\n\n\n\t\t\tneural_net.setLoss<  mic::neural_nets::loss::SquaredErrorLoss<float> >();\n\t\t\tneural_net.setOptimization<  mic::neural_nets::optimization::Adam<float> >();\n\n\t\tLOG(LINFO) << \"Generated new neural network\";\n\t}//: else\n\n\t// Import data from datasets.\n\tif (!importer->importData())\n\t\texit(-1);\n\n\n\tsize_t iteration = 0;\n\n\t// Retrieve the next minibatch.\n\t//mic::types::MNISTBatch bt = importer->getNextBatch();\n\t//importer->setNextSampleIndex(5);\n\n\t// Main application loop.\n\twhile (!APP_STATE->Quit()) {\n\n\t\t// If not paused.\n\t\tif (!APP_STATE->isPaused()) {\n\n\t\t\t// If single step mode - pause after the step.\n\t\t\tif (APP_STATE->isSingleStepModeOn())\n\t\t\t\tAPP_STATE->pressPause();\n\n\t\t\t{ // Enter critical section - with the use of scoped lock from AppState!\n\t\t\t\tAPP_DATA_SYNCHRONIZATION_SCOPED_LOCK();\n\n\t\t\t\t// Retrieve the next minibatch.\n\t\t\t\tmic::types::MNISTBatch<float> bt = importer->getRandomBatch();\n\n\t\t\t\t// Encode data.\n\t\t\t\tmic::types::MatrixXfPtr encoded_batch = mnist_encoder->encodeBatch(bt.data());\n\t\t\t\tmic::types::MatrixXfPtr encoded_labels = label_encoder->encodeBatch(bt.labels());\n\n/*\t\t\t\tmic::types::MatrixPtr<float> encoded_batch = MAKE_MATRIX_PTR(float, patch_size*patch_size, 1);\n\t\t\t\tfor (size_t i=0; i<patch_size*patch_size; i++)\n\t\t\t\t\t(*encoded_batch)[i]= 1.0 -(float)i/(patch_size*patch_size);*/\n\t\t\t\t/*mic::types::MatrixPtr<float> encoded_labels = MAKE_MATRIX_PTR(float, output_size, 1);\n\t\t\t\tencoded_labels->setZero();\n\t\t\t\t(*encoded_labels)[0]= 1.0;*/\n\t\t\t\t/*(*encoded_labels)[6]= 1.0;\n\t\t\t\t(*encoded_labels)[9]= 1.0;\n\t\t\t\t(*encoded_labels)[15]= 1.0;*/\n\n\t\t\t\t// Train the autoencoder.\n\t\t\t\tfloat loss = neural_net.train (encoded_batch, encoded_labels, 0.001, 0.0001);\n\n\t\t\t\t// Get reconstruction.\n\t\t\t\t/*mic::types::MatrixXfPtr encoded_reconstruction = neural_net.getPredictions();\n\t\t\t\tstd::vector<mic::types::MatrixXfPtr> decoded_reconstruction = mnist_encoder->decodeBatch(encoded_reconstruction);\n\t\t\t\tw_reconstruction->setBatchUnsynchronized(decoded_reconstruction);*/\n\n\t\t\t\tif (iteration%10 == 0) {\n\t\t\t\t\t// Visualize the weights.\n\t\t\t\t\t//std::shared_ptr<Layer<float> > layer1 = neural_net.getLayer(3);\n\n\t\t\t\t\tstd::shared_ptr<mic::mlnn::convolution::Convolution<float> > conv1 =\n\t\t\t\t\t\t\tneural_net.getLayer<mic::mlnn::convolution::Convolution<float> >(1);\n\t\t\t\t\tw_conv10->setBatchUnsynchronized(conv1->getInputActivations());\n\t\t\t\t\tw_conv11->setBatchUnsynchronized(conv1->getInputGradientActivations());\n\t\t\t\t\tw_conv12->setBatchUnsynchronized(conv1->getWeightActivations());\n\t\t\t\t\tw_conv13->setBatchUnsynchronized(conv1->getWeightGradientActivations());\n\t\t\t\t\tw_conv14->setBatchUnsynchronized(conv1->getOutputActivations());\n                    w_conv15->setBatchUnsynchronized(conv1->getOutputGradientActivations());\n\n\t\t\t\t\t// Similarity.\n\t\t\t\t\tmic::types::MatrixPtr<float> similarity = conv1->getFilterSimilarityMatrix();\n\t\t\t\t\tw_conv16->setSampleUnsynchronized(similarity);\n\n\t\t\t\t\tfloat max_similarity = 0;\n\t\t\t\t\tfloat mean_similarity = 0;\n\t\t\t\t\tfor (size_t i=0; i<9; i++)\n\t\t\t\t\t\tfor (size_t j=0; j<i; j++) {\n\t\t\t\t\t\t\tstd::string label = \"Similarity \" + std::to_string(i) + \"-\" +std::to_string(j);\n\t\t\t\t\t\t\tcollector_ptr->addDataToContainer(label, (*similarity)(i,j));\n\t\t\t\t\t\t\tmean_similarity += (*similarity)(i,j);\n\t\t\t\t\t\t\tmax_similarity = ((*similarity)(i,j) > max_similarity) ? (*similarity)(i,j) : max_similarity;\n\t\t\t\t\t\t}//: for\n\n\t\t\t\t\tcollector_ptr->addDataToContainer(\"Similarity max\", max_similarity);\n\t\t\t\t\tmean_similarity /= (1+2+3+4+5+6+7+8);\n\t\t\t\t\tcollector_ptr->addDataToContainer(\"Similarity mean\", mean_similarity);\n\n\n\t\t\t\t\tstd::shared_ptr<mic::mlnn::convolution::Convolution<float> > conv2 =\n\t\t\t\t\t\t\tneural_net.getLayer<mic::mlnn::convolution::Convolution<float> >(4);\n\t\t\t\t\tw_conv20->setBatchUnsynchronized(conv2->getInputActivations());\n\t\t\t\t\tw_conv21->setBatchUnsynchronized(conv2->getInputGradientActivations());\n\t\t\t\t\tw_conv22->setBatchUnsynchronized(conv2->getWeightActivations());\n\t\t\t\t\tw_conv23->setBatchUnsynchronized(conv2->getWeightGradientActivations());\n\t\t\t\t\tw_conv24->setBatchUnsynchronized(conv2->getOutputActivations());\n\t\t\t\t\tw_conv25->setBatchUnsynchronized(conv2->getOutputGradientActivations());\n\n\t\t\t\t\tstd::shared_ptr<mic::mlnn::fully_connected::Linear<float> > lin1 =\n\t\t\t\t\t\t\tneural_net.getLayer<mic::mlnn::fully_connected::Linear<float> >(7);\n\t\t\t\t\tw_conv30->setBatchUnsynchronized(lin1->getInputActivations());\n\t\t\t\t\tw_conv31->setBatchUnsynchronized(lin1->getInputGradientActivations());\n\t\t\t\t\tw_conv32->setBatchUnsynchronized(lin1->getWeightActivations());\n\t\t\t\t\tw_conv33->setBatchUnsynchronized(lin1->getWeightGradientActivations());\n\n\t\t\t\t\tstd::shared_ptr<Layer<float> > sm1 = neural_net.getLayer(7);\n\t\t\t\t\tw_conv34->setBatchUnsynchronized(sm1->getOutputActivations());\n\t\t\t\t\tw_conv35->setBatchUnsynchronized(sm1->getOutputGradientActivations());\n\n\t\t\t\t\t// Add data to chart window.\n\t\t\t\t\tcollector_ptr->addDataToContainer(\"Loss\", loss);\n\t\t\t\t\t//float reconstruction_error = neural_net.getLayer<mic::mlnn::fully_connected::Linear<float> >(1)->calculateMeanReconstructionError();\n\t\t\t\t\t//collector_ptr->addDataToContainer(\"Reconstruction Error\", reconstruction_error);\n\n\t\t\t\t\t// Export to file.\n\t\t\t\t\tcollector_ptr->exportDataToCsv(convnet_log);\n\t\t\t\t}//: if\n\n\t\t\t\titeration++;\n\t\t\t\t//float reconstruction_error = neural_net.getLayer<mic::mlnn::fully_connected::Linear<float> >(1)->calculateMeanReconstructionError();\n\n\t\t\t\tLOG(LINFO) << \"Iteration: \" << iteration << \" loss =\" << loss;// << \" reconstruction error =\" << reconstruction_error;\n\t\t\t}//: end of critical section\n\n\t\t}//: if\n\n\t\t// Sleep.\n\t\tAPP_SLEEP();\n\t}//: while\n\n}//: image_encoder_and_visualization_test\n\n\n\n/*!\n * \\brief Main program function. Runs two threads: main (for GLUT) and another one (for data processing).\n * \\author tkornuta\n * @param[in] argc Number of parameters (passed to glManaged).\n * @param[in] argv List of parameters (passed to glManaged).\n * @return (not used)\n */\nint main(int argc, char* argv[]) {\n\t// Set console output to logger.\n\tLOGGER->addOutput(new ConsoleOutput());\n\tLOG(LINFO) << \"Logger initialized. Starting application\";\n\n\t// Parse parameters.\n\tPARAM_SERVER->parseApplicationParameters(argc, argv);\n\n\t// Initilize application state (\"touch it\") ;)\n\tAPP_STATE;\n\n\t// Load dataset.\n\timporter = new mic::importers::MNISTMatrixImporter<float>();\n\timporter->setBatchSize(batch_size);\n\n\t// Initialize the encoders.\n\tmnist_encoder = new mic::encoders::MatrixXfMatrixXfEncoder(28, 28);\n\tlabel_encoder = new mic::encoders::UIntMatrixXfEncoder(10);\n\n\t// Set parameters of all property-tree derived objects - USER independent part.\n\tPARAM_SERVER->loadPropertiesFromConfiguration();\n\n\t// Initialize property-dependent variables of all registered property-tree objects - USER dependent part.\n\tPARAM_SERVER->initializePropertyDependentVariables();\n\n\t// Initialize GLUT! :]\n\tVGL_MANAGER->initializeGLUT(argc, argv);\n\n\t// Create batch visualization window.\n\tw_conv10 = new WindowGrayscaleBatch<float>(\"Conv1 x\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 50, 50, 256, 256);\n\tw_conv11 = new WindowGrayscaleBatch<float>(\"Conv1 dx\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 316, 50, 256, 256);\n\tw_conv12 = new WindowGrayscaleBatch<float>(\"Conv1 W\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 562, 50, 256, 256);\n\tw_conv13 = new WindowGrayscaleBatch<float>(\"Conv1 dW\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 818, 50, 256, 256);\n\tw_conv14 = new WindowGrayscaleBatch<float>(\"Conv1 y\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 1074, 50, 256, 256);\n\tw_conv15 = new WindowGrayscaleBatch<float>(\"Conv1 dy\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 1330, 50, 256, 256);\n\tw_conv16 = new WindowGrayscaleBatch<float>(\"Conv1 similarity\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 1586, 50, 256, 256);\n\n\tw_conv20 = new WindowGrayscaleBatch<float>(\"Conv2 x\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 50, 336, 256, 256);\n\tw_conv21 = new WindowGrayscaleBatch<float>(\"Conv2 dx\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 316, 336, 256, 256);\n\tw_conv22 = new WindowGrayscaleBatch<float>(\"Conv2 W\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 562, 336, 256, 256);\n\tw_conv23 = new WindowGrayscaleBatch<float>(\"Conv2 dW\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 818, 336, 256, 256);\n\tw_conv24 = new WindowGrayscaleBatch<float>(\"Conv2 y\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 1074, 336, 256, 256);\n\tw_conv25 = new WindowGrayscaleBatch<float>(\"Conv2 dy\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 1330, 336, 256, 256);\n\n\tw_conv30 = new WindowGrayscaleBatch<float>(\"L1 x\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 50, 622, 256, 256);\n\tw_conv31 = new WindowGrayscaleBatch<float>(\"L1 dx\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 316, 622, 256, 256);\n\tw_conv32 = new WindowGrayscaleBatch<float>(\"L1 W\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 562, 622, 256, 256);\n\tw_conv33 = new WindowGrayscaleBatch<float>(\"L1 dW\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 818, 622, 256, 256);\n\tw_conv34 = new WindowGrayscaleBatch<float>(\"SM y\", WindowGrayscaleBatch<float>::Norm_None, WindowGrayscaleBatch<float>::Grid_Both, 1074, 622, 256, 256);\n\tw_conv35 = new WindowGrayscaleBatch<float>(\"SM dy\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 1330, 622, 256, 256);\n\n\t// Chart.\n\tw_chart = new WindowCollectorChart<float>(\"Statistics\", 60, 878, 512, 256);\n\tcollector_ptr= std::make_shared < mic::utils::DataCollector<std::string, float> >( );\n\tw_chart->setDataCollectorPtr(collector_ptr);\n\n\t// Create data containers.\n\tcollector_ptr->createContainer(\"Loss\", mic::types::color_rgba(0, 100, 0, 180));\n\t//collector_ptr->createContainer(\"Reconstruction Error\", mic::types::color_rgba(255, 255, 255, 180));\n\tcollector_ptr->createContainer(\"Similarity max\", mic::types::color_rgba(255, 0, 0, 180));\n\tcollector_ptr->createContainer(\"Similarity mean\", mic::types::color_rgba(0, 0, 255, 180));\n\tfor (size_t i=0; i<9; i++)\n\t\tfor (size_t j=0; j<i; j++) {\n\t\t\tstd::string label = \"Similarity \" + std::to_string(i) + \"-\" +std::to_string(j);\n\t\t\tcollector_ptr->createContainer(label, mic::types::color_rgba(255*(9*i+j)/81, 255*(9*i+j)/81, 255*(9*i+j)/81, 180));\n\t\t}\n\n\tboost::thread batch_thread(boost::bind(&batch_function));\n\n\t// Start visualization thread.\n\tVGL_MANAGER->startVisualizationLoop();\n\n\tLOG(LINFO) << \"Waiting for threads to join...\";\n\t// End test thread.\n\tbatch_thread.join();\n\tLOG(LINFO) << \"Threads joined - ending application\";\n}//: main\n", "meta": {"hexsha": "11190062de8e8901aa99ecdef6a17ed95d884759", "size": 14516, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/mnist_convnet_features_visualization_test.cpp", "max_stars_repo_name": "Bhaskers-Blu-Org1/mi-neural-nets", "max_stars_repo_head_hexsha": "30bc73dbd9e5d6c05a9c3c1cb1483abcb883272d", "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/mnist_convnet_features_visualization_test.cpp", "max_issues_repo_name": "Bhaskers-Blu-Org1/mi-neural-nets", "max_issues_repo_head_hexsha": "30bc73dbd9e5d6c05a9c3c1cb1483abcb883272d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-26T21:32:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-28T19:39:37.000Z", "max_forks_repo_path": "src/tests/mnist_convnet_features_visualization_test.cpp", "max_forks_repo_name": "IBM/mi-neural-nets", "max_forks_repo_head_hexsha": "30bc73dbd9e5d6c05a9c3c1cb1483abcb883272d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-01-02T21:38:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:28:52.000Z", "avg_line_length": 45.5047021944, "max_line_length": 167, "alphanum_fraction": 0.7345687517, "num_tokens": 4058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5227283135327981}}
{"text": "/**\n *  @file    Parameters.hpp\n *  @brief   Definition of the diffusion problem.\n *  @author  Francois Roy\n *  @date    12/04/2019\n */\n#ifndef PARAMETERS_H\n#define PARAMETERS_H\n\n#include <vector>\n#include <Eigen/Core>\n#include \"spdlog/spdlog.h\"\n\n\nnamespace numerical \n{\nnamespace fdm \n{\n\n/**\n* Defines the parameters for the scalar finite difference problem.\n*/\ntemplate<typename T>\nstruct Parameters\n{\n    T alpha, theta;\n    std::vector<std::vector<T>> lengths;\n    T t0, tend;\n    int nt;\n    std::vector<int> n;\n    Parameters()\n    {\n    \t// default parameters\n    \talpha = 1.0;\n        theta = 0.5;\n        // unit cube\n    \tlengths = {{0.0, 1.0}, {0.0, 1.0}, {0.0, 1.0}};\n        // 10 divisions per dimensions\n    \tn = {10, 10, 10};\n        // initial time\n    \tt0 = 0.0;\n        // final time\n    \ttend = 1.0;\n        // number of uniform time step\n    \tnt = 10;\n    }\n};\n\n} // end namespace fdm\n}  // end namesapce numerical\n\n#endif  // PARAMETERS_H\n", "meta": {"hexsha": "f349b7fbc4fbbca211bfd60fa44a927b84e60391", "size": 961, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "numerical/fdm/Parameters.hpp", "max_stars_repo_name": "dbeat/numerical", "max_stars_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical/fdm/Parameters.hpp", "max_issues_repo_name": "dbeat/numerical", "max_issues_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical/fdm/Parameters.hpp", "max_forks_repo_name": "dbeat/numerical", "max_forks_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1320754717, "max_line_length": 66, "alphanum_fraction": 0.5785639958, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.5227283119608228}}
{"text": "#include <iostream>\n#include <string>\n#include <fstream> \n#include <iomanip>\n\nusing namespace std;\n\n// abs(i), labs(l)                     Absolute value\n// acos(d), acosl(ld)                  Inverse cosine\n// acosh(d)                            Inverse hyperbolic cosine\n// asin(d), asinl(ld)                  Inverse sine\n// asinh(d)                            Inverse hyperbolic sine\n// atan(d), atanl(ld)                  Inverse tangent\n// atan2(d,d), atan2l(ld,ld)           Inverse tangent\n// atanh(d)                            Inverse hyperbolic tangent\n// _class(d)                           Classification of floating-point values\n// cbrt(x)                             Cube root\n// ceil(d), ceill(ld)                  Smallest f-int not less than x\n// cos(d), cosl(ld)                    Cosine\n// cosh(d), coshl(ld)                  Hyperbolic cosine\n// copysign(d,d)                       Return 1st arg with same sign as 2nd\n// drem(x,x)                           IEEE remainder\n// exp(d), expl(ld)                    Exponential\n// expm1(d)                            Exp(x)-1     \n// erf(d), erfl(ld)                    Error function\n// erfc(d), erfcl(ld)                  Complementary error function\n// fabs(d), fabsl(ld)                  Floating point absolute value\n// int finite(d)                       Nonzero if finite\n// floor(d), floor(ld)                 Largest f-int not greater than x\n// fmod(d,d), fmodl(ld,ld)             Floating point remainder\n// frexp(d, int* e)                    Break into mantissa/exponent  (*)\n// frexpl(ld, int* e)                  Break into mantissa/exponent  (*)\n// gammaFunc(d)                        Gamma function (** needs special \n//                                     implementation using lgamma)\n// hypot(d,d)                          Hypotenuse: sqrt(x*x+y*y)\n// int ilogb(d)                        Integer unbiased exponent\n// int isnan(d)                        Nonzero if NaNS or NaNQ\n// int itrunc(d)                       Truncate and convert to integer\n// j0(d)                               Bessel function first kind, order 0\n// j1(d)                               Bessel function first kind, order 1\n// jn(int, double)                     Bessel function first kind, order i\n// ldexp(d,i), ldexpl(ld,i)            Compute d * 2^i\n// lgamma(d), lgammal(ld)              Log absolute gamma\n// log(d), logl(ld)                    Natural logarithm\n// logb(d)                             Unbiased exponent (IEEE)\n// log1p(d)                            Compute log(1 + x)\n// log10(d), log10l(ld)                Logarithm base 10\n// modf(d, int* i), modfl(ld, int* i)  Break into integral/fractional part\n// double nearest(double)              Nearest floating point integer\n// nextafter(d, d)                     Next representable neighbor of 1st\n//                                     in direction of 2nd\n// pow(d,d), powl(ld,ld)               Computes x ^ y\n// d remainder(d,d)                    IEEE remainder\n// d rint(d)                           Round to f-integer (depends on mode)\n// d rsqrt(d)                          Reciprocal square root\n// d scalb(d,d)                        Return x * (2^y)\n// sin(d), sinl(ld)                    Sine \n// sinh(d), sinhl(ld)                  Hyperbolic sine\n// sqr(x)                              Return x * x\n// sqrt(d), sqrtl(ld)                  Square root\n// tan(d), tanl(ld)                    Tangent\n// tanh(d), tanhl(ld)                  Hyperbolic tangent\n// trunc(d)                            Nearest f-int in the direction of 0\n// unsigned uitrunc(d)                 Truncate and convert to unsigned\n// int unordered(d,d)                  Nonzero if comparison is unordered\n// y0(d)                               Bessel function 2nd kind, order 0\n// y1(d)                               Bessel function 2nd kind, order 1\n// yn(i,d)                             Bessel function 2nd kind, order d\n\nofstream ofs;\n\nconst int ldflag = 1;\nconst int cflag = 2;\nconst int ieeeflag = 3;\nconst int bsdflag = 4;\nconst int cflag1 = 5;\nconst int cflag2 = 6;\nconst int nofuncflag = 7;\n\nvoid one(const char* applicName, const char* specialization, const char* funcName,\n    const char* returnType, const char* comment, int flag=0, int noCastFlag=0)\n{\n    if (specialization != 0 && !strlen(specialization))\n        specialization = 0;\n    if (returnType != 0 && !strlen(returnType))\n        returnType = 0;\n    if (comment != 0 && !strlen(comment))\n        comment = 0;\n\n    ofs << \"// \" << applicName << \"(\";\n    if (specialization)\n        ofs << specialization;\n    else\n        ofs << \"P_numtype1\";\n    ofs << \")\";\n    if (comment)\n        ofs << \"    \" << comment;\n    ofs << std::endl;\n\n    if (flag == cflag)\n        ofs << \"#ifdef BZ_HAVE_COMPLEX_FCNS\" << std::endl;\n    else if (flag == cflag1)\n        ofs << \"#ifdef BZ_HAVE_COMPLEX_MATH1\" << std::endl;\n    else if (flag == cflag2)\n        ofs << \"#ifdef BZ_HAVE_COMPLEX_MATH2\" << std::endl;\n    else if (flag == ieeeflag)\n        ofs << \"#ifdef BZ_HAVE_IEEE_MATH\" << std::endl;\n    else if (flag == bsdflag)\n        ofs << \"#ifdef BZ_HAVE_SYSTEM_V_MATH\" << std::endl;\n//    else if (flag == ldflag)\n//        ofs << \"#ifdef BZ_LONGDOUBLE128\" << std::endl;\n\n    if (!specialization)\n    {\n        ofs << \"template<typename P_numtype1>\" << std::endl;\n    }\n    else {\n        ofs << \"template<>\" << std::endl;\n    }\n    ofs << \"class _bz_\" << applicName;     \n    if (specialization)\n        ofs << \"<\" << specialization << \">\";\n\n    ofs << \" : public OneOperandApplicativeTemplatesBase {\" << std::endl;\n\n    ofs << \"public:\" << std::endl;\n    ofs << \"    typedef \";\n    if (specialization)\n        ofs << specialization;\n    else \n        ofs << \"P_numtype1\";\n    ofs << \" T_numtype1;\" << std::endl;\n\n    ofs << \"    typedef \";\n    if (returnType)\n        ofs << returnType;\n    else if (specialization)\n        ofs << specialization;\n    else\n        ofs << \"P_numtype1\";\n    ofs << \" T_numtype;\" << std::endl;\n\n    if (strcmp(applicName,\"blitz_isnan\") == 0) // Special case nan\n    {\n        ofs << std::endl << \"    static inline T_numtype apply(T_numtype1 x)\"\n            << std::endl << \"    {\" << std::endl;\n        ofs << \"#ifdef isnan\" << std::endl;\n        ofs << \"        \"\n            << \"// Some platforms define isnan as a macro, which causes the\"\n            << std::endl << \"        \"\n            << \"// BZ_IEEEMATHFN_SCOPE macro to break.\" << std::endl;\n        ofs << \"        return isnan(x);\" << std::endl;\n        ofs << \"#else\" << std::endl;\n        ofs << \"        return BZ_IEEEMATHFN_SCOPE(isnan)(x);\" << std::endl;\n        ofs << \"#endif\" << std::endl << \"    }\" << std::endl;\n    }\n    else \n    {\n        ofs << std::endl << \"    static inline T_numtype apply(T_numtype1 x)\"\n            << std::endl << \"    { return \";\n\n        if (noCastFlag == nofuncflag)\n        {\n            ofs << funcName;\n        }\n        else {\n        if ((flag == cflag) || (flag == cflag1) || (flag == cflag2))\n            ofs << \"BZ_CMATHFN_SCOPE(\";\n        else if ((flag == ieeeflag) || (flag == bsdflag))\n            ofs << \"BZ_IEEEMATHFN_SCOPE(\";\n        else \n            ofs << \"BZ_MATHFN_SCOPE(\";\n    \n        ofs << funcName << \")(\";\n        if (specialization != 0)\n            ofs << \"(\" << specialization << \")\";\n        else if ((returnType)&&(!noCastFlag))\n            ofs << \"(\" << returnType << \")\";\n\n        ofs << \"x)\";\n        }\n        ofs << \"; }\" << std::endl;\n    }\n\n    ofs << std::endl << \"    template<typename T1>\" << std::endl\n        << \"    static void prettyPrint(BZ_STD_SCOPE(string) &str, prettyPrintFormat& format,\"\n        << std::endl\n        << \"        const T1& a)\" << std::endl\n        << \"    {\" << std::endl\n        << \"        str += \\\"\" << funcName;\n      ofs  << \"(\\\";\" << std::endl\n        << \"        a.prettyPrint(str,format);\" << std::endl\n        << \"        str += \\\")\\\";\" << std::endl\n        << \"    }\" << std::endl\n        << \"};\" << std::endl;\n\n   if ((flag != ldflag) && (flag != 0))\n        ofs << \"#endif\" << std::endl;\n\n    ofs << std::endl;\n}\n\nvoid two(const char* applicName, const char* specialization, const char* funcName,\n    const char* returnType, const char* comment, int flag=0, int noCastFlag=0)\n{\n    if (specialization != 0 && !strlen(specialization))\n        specialization = 0;\n    if (returnType != 0 && !strlen(returnType))\n        returnType = 0;\n    if (comment != 0 && !strlen(comment))\n        comment = 0;\n\n    ofs << \"// \" << applicName << \"(\";\n    if (specialization)\n        ofs << specialization << \", \" << specialization;\n    else\n        ofs << \"P_numtype1, P_numtype2\";\n    ofs << \")\";\n    if (comment)\n        ofs << \"    \" << comment;\n    ofs << std::endl;\n\n    if (flag == cflag)\n        ofs << \"#ifdef BZ_HAVE_COMPLEX_FCNS\" << std::endl;\n    else if (flag == cflag1)\n        ofs << \"#ifdef BZ_HAVE_COMPLEX_MATH1\" << std::endl;\n    else if (flag == cflag2)\n        ofs << \"#ifdef BZ_HAVE_COMPLEX_MATH2\" << std::endl;\n    else if (flag == ieeeflag)\n        ofs << \"#ifdef BZ_HAVE_IEEE_MATH\" << std::endl;\n    else if (flag == bsdflag)\n        ofs << \"#ifdef BZ_HAVE_SYSTEM_V_MATH\" << std::endl;\n//    else if (flag == ldflag)\n//        ofs << \"#ifdef BZ_LONGDOUBLE128\" << std::endl;\n\n    if (!specialization)\n    {\n        ofs << \"template<typename P_numtype1, typename P_numtype2>\" << std::endl;\n    }\n    else {\n        ofs << \"template<>\" << std::endl;\n    }\n    ofs << \"class _bz_\" << applicName;\n    if (specialization)\n        ofs << \"<\" << specialization  << \", \" << specialization << \" >\";\n    ofs << \" : public TwoOperandApplicativeTemplatesBase {\" << std::endl;\n\n    ofs << \"public:\" << std::endl;\n    ofs << \"    typedef \";\n    if (specialization)\n        ofs << specialization;\n    else\n        ofs << \"P_numtype1\";\n    ofs << \" T_numtype1;\" << std::endl;\n\n    ofs << \"    typedef \";\n    if (specialization)\n        ofs << specialization;\n    else\n        ofs << \"P_numtype2\";\n    ofs << \" T_numtype2;\" << std::endl;\n\n    ofs << \"    typedef \";\n    if (returnType)\n        ofs << returnType;\n    else if (specialization)\n        ofs << specialization;\n    else\n        ofs << \"BZ_PROMOTE(T_numtype1, T_numtype2)\";\n    ofs << \" T_numtype;\" << std::endl;\n\n    ofs << std::endl << \"    static inline T_numtype apply(T_numtype1 x, T_numtype2 y)\"\n        << std::endl << \"    { return \";\n\n    if ((flag == cflag) || (flag == cflag1) || (flag == cflag2))\n        ofs << \"BZ_CMATHFN_SCOPE(\";\n    else if ((flag == ieeeflag) || (flag == bsdflag))\n        ofs << \"BZ_IEEEMATHFN_SCOPE(\";\n    else\n        ofs << \"BZ_MATHFN_SCOPE(\";\n\n    ofs << funcName << \")(\";\n\n    if (specialization != 0)\n        ofs << \"(\" << specialization << \")\";\n    else if ((returnType) && (!noCastFlag))\n        ofs << \"(\" << returnType << \")\";\n\n    ofs << \"x,\";\n    if (specialization != 0)\n        ofs << \"(\" << specialization << \")\";\n    else if ((returnType) && (!noCastFlag))\n        ofs << \"(\" << returnType << \")\";\n    ofs << \"y); }\" << std::endl;\n\n    ofs << std::endl << \"    template<typename T1, typename T2>\" << std::endl\n        << \"    static void prettyPrint(BZ_STD_SCOPE(string) &str, prettyPrintFormat& format,\"\n        << std::endl\n        << \"        const T1& a, const T2& b)\" << std::endl\n        << \"    {\" << std::endl\n        << \"        str += \\\"\" << funcName;\n      ofs  << \"(\\\";\" << std::endl\n        << \"        a.prettyPrint(str,format);\" << std::endl\n        << \"        str += \\\",\\\";\" << std::endl\n        << \"        b.prettyPrint(str,format);\" << std::endl\n        << \"        str += \\\")\\\";\" << std::endl\n        << \"    }\" << std::endl;\n\n    ofs << \"};\" << std::endl;\n\n    if ((flag != ldflag) && (flag != 0))\n        ofs << \"#endif\" << std::endl;\n\n    ofs << std::endl;\n}\n\nint main()\n{\n    std::cout << \"Generating <mathfunc.h>\" << std::endl;\n\n    ofs.open(\"../mathfunc.h\");\n\n    ofs <<  \n\"// Generated: \" << __FILE__ << \" \" << __DATE__ << \" \" << __TIME__ \n                 << std::endl << std::endl <<\n\"#ifndef BZ_MATHFUNC_H\\n\"\n\"#define BZ_MATHFUNC_H\\n\"\n\"\\n\"\n\"#ifndef BZ_APPLICS_H\\n\"\n\" #error <blitz/mathfunc.h> should be included via <blitz/applics.h>\\n\"\n\"#endif\\n\\n\"\n\"\\n\"\n\"#ifndef BZ_PRETTYPRINT_H\\n\"\n\" #include <blitz/prettyprint.h>\\n\"\n\"#endif\\n\\n\"\n\"BZ_NAMESPACE(blitz)\\n\\n\";\n\n    one(\"abs\", 0, \"abs\", 0, \"Absolute value\");\n    one(\"abs\",\"long\",\"labs\",\"long\", 0);\n    one(\"abs\",\"float\"       ,\"fabs\",    \"float\",       0);\n\none(\"abs\"    ,\"double\"      ,\"fabs\"    ,\"double\"       ,\"\");\none(\"abs\"    ,\"long double\" ,\"fabs\"   ,\"long double\"  ,\"\", ldflag);\none(\"abs\"    ,\"complex<float> \", \"abs\",\"float\", \"\", cflag);\none(\"abs\"    ,\"complex<double> \", \"abs\", \"double\", \"\", cflag);\none(\"abs\"    ,\"complex<long double> \", \"abs\", \"long double\", \"\", cflag);\none(\"acos\"   ,\"\"            ,\"acos\"    ,\"double\"       ,\"Inverse cosine\");\none(\"acos\"   ,\"float\"       ,\"acos\"  ,\"float\"         ,\"\");\none(\"acos\"   ,\"long double\" ,\"acos\"   ,\"long double\"  ,\"\", ldflag);\none(\"acos\"   ,\"complex<float> \", \"acos\", \"complex<float>\", \"\", cflag2);\none(\"acos\"   ,\"complex<double> \", \"acos\", \"complex<double>\", \"\", cflag2);\none(\"acos\", \"complex<long double> \", \"acos\", \"complex<long double>\", \"\", cflag2);\none(\"acosh\"  ,\"\"            ,\"acosh\"   ,\"double\"       ,\"Inverse hyperbolic cosine\", ieeeflag);\none(\"asin\"   ,\"\"            ,\"asin\"    ,\"double\"       ,\"Inverse sine\");\none(\"asin\",   \"float\",       \"asin\",    \"float\", \"\");\none(\"asin\"   ,\"long double\" ,\"asin\"   ,\"long double\"  ,\"\", ldflag);\none(\"asin\"   ,\"complex<float> \", \"asin\", \"complex<float>\", \"\", cflag2);\none(\"asin\"   ,\"complex<double> \", \"asin\", \"complex<double>\", \"\", cflag2);\none(\"asin\", \"complex<long double> \", \"asin\", \"complex<long double>\", \"\", cflag2);\none(\"asinh\"  ,\"\"            ,\"asinh\"   ,\"double\"       ,\"Inverse hyperbolic sine\", ieeeflag);\none(\"arg\",   \"\"            ,\"0\"    ,0             ,\"\", cflag, nofuncflag);\none(\"arg\",   \"complex<float> \", \"arg\", \"float\", \"\", cflag, 0);\none(\"arg\",   \"complex<double> \", \"arg\", \"double\", \"\", cflag, 0);\none(\"arg\",   \"complex<long double> \", \"arg\", \"long double\", \"\", cflag, 0);\none(\"atan\"   ,\"\"            ,\"atan\"    ,\"double\"       ,\"Inverse tangent\");\none(\"atan\",   \"float\",       \"atan\",    \"float\",        \"\");\none(\"atan\"   ,\"long double\" ,\"atan\"   ,\"long double\"  ,\"\", ldflag);\none(\"atan\"   ,\"complex<float> \", \"atan\", \"complex<float>\", \"\", cflag2);\none(\"atan\"   ,\"complex<double> \", \"atan\", \"complex<double>\", \"\", cflag2);\none(\"atan\", \"complex<long double> \", \"atan\", \"complex<long double>\", \"\", cflag2);\none(\"atanh\"  ,\"\"            ,\"atanh\"   ,\"double\"       ,\"Inverse hyperbolic tangent\", ieeeflag);\ntwo(\"atan2\"  ,\"\"            ,\"atan2\"   ,\"double\"       ,\"Inverse tangent\");\ntwo(\"atan2\"  ,\"float\"       ,\"atan2\"   ,\"float\"        ,\"\");\ntwo(\"atan2\"  ,\"long double\" ,\"atan2\"   ,\"long double\"  ,\"\");\none(\"_class\" ,\"\"            ,\"_class\"  ,\"int\"          ,\"Classification of float-point value (FP_xxx)\", bsdflag,1);\none(\"cbrt\"   ,\"\"            ,\"cbrt\"    ,\"double\"       ,\"Cube root\", ieeeflag);\none(\"ceil\"   ,\"\"            ,\"ceil\"    ,\"double\"       ,\"Ceiling\");\none(\"ceil\",   \"float\",       \"ceil\",    \"float\",       \"\");\none(\"ceil\"   ,\"long double\" ,\"ceil\"   ,\"long double\"  ,\"\", ldflag);\none(\"conj\",   \"\"            ,\"conj\"    ,0             ,\"\", cflag);\none(\"cos\"    ,\"\"            ,\"cos\"     ,\"double\"       ,\"Cosine\");\none(\"cos\",    \"float\",       \"cos\",     \"float\",       \"\");\none(\"cos\"    ,\"long double\" ,\"cos\"    ,\"long double\"  ,\"\", ldflag);\none(\"cos\"   ,\"complex<float> \", \"cos\", \"complex<float>\", \"\", cflag1);\none(\"cos\"   ,\"complex<double> \", \"cos\", \"complex<double>\", \"\", cflag1);\n ofs << \"#ifndef __PGI\\n\";\none(\"cos\", \"complex<long double> \", \"cos\", \"complex<long double>\", \"\", cflag1);\n ofs << \"#endif\\n\";\ntwo(\"copysign\", \"\"          ,\"copysign\",\"double\"       ,\"\", bsdflag);\none(\"cosh\"   ,\"\"            ,\"cosh\"    ,\"double\"       ,\"Hyperbolic cosine\");\none(\"cosh\",   \"float\",       \"cosh\",    \"float\", \"\");\none(\"cosh\"   ,\"long double\" ,\"cosh\"   ,\"long double\"  ,\"\", ldflag);\none(\"cosh\"   ,\"complex<float> \", \"cosh\", \"complex<float>\", \"\", cflag1);\none(\"cosh\"   ,\"complex<double> \", \"cosh\", \"complex<double>\", \"\", cflag1);\n ofs << \"#ifndef __PGI\\n\";\none(\"cosh\", \"complex<long double> \", \"cosh\", \"complex<long double>\", \"\", cflag1);\n ofs << \"#endif\\n\";\ntwo(\"drem\"   ,\"\"            ,\"drem\"    ,\"double\"       ,\"Remainder\", bsdflag);\none(\"exp\"    ,\"\"            ,\"exp\"     ,\"double\"       ,\"Exponential\");\none(\"exp\",    \"float\",       \"exp\",     \"float\",       \"\");\none(\"exp\"    ,\"long double\" ,\"exp\"    ,\"long double\"  ,\"\", ldflag      );\none(\"exp\"   ,\"complex<float> \", \"exp\", \"complex<float>\", \"\", cflag1);\none(\"exp\"   ,\"complex<double> \", \"exp\", \"complex<double>\", \"\", cflag1);\n ofs << \"#ifndef __PGI\\n\";\none(\"exp\", \"complex<long double> \", \"exp\", \"complex<long double>\", \"\", cflag1);\n ofs << \"#endif\\n\";\none(\"expm1\"  ,\"\"            ,\"expm1\"   ,\"double\"       ,\"Exp(x)-1\", ieeeflag);\none(\"erf\"    ,\"\"            ,\"erf\"     ,\"double\"       ,\"Error function\", ieeeflag);\none(\"erfc\"   ,\"\"            ,\"erfc\"    ,\"double\"       ,\"Complementary error function\", ieeeflag);\n\n// blitz-bugs/archive/0189.html\n// one(\"finite\" ,\"\"            ,\"finite\"  ,\"int\"          ,\"Nonzero if finite\", ieeeflag,1);\n\none(\"floor\"  ,\"\"            ,\"floor\"   ,\"double\"       ,\"Floor function\");\none(\"floor\",  \"float\",       \"floor\",   \"float\",        \"\");\none(\"floor\"  ,\"long double\" ,\"floor\"   ,\"long double\"  ,\"\");\ntwo(\"fmod\"   ,\"\"            ,\"fmod\"    ,\"double\"       ,\"Modulo remainder\");\ntwo(\"hypot\"  ,\"\"            ,\"hypot\"   ,\"double\"       ,\"sqrt(x*x+y*y)\",bsdflag);\none(\"ilogb\"  ,\"\"            ,\"ilogb\"   ,\"int\"          ,\"Integer unbiased exponent\", ieeeflag,1);\none(\"blitz_isnan\"  ,\"\"            ,\"blitz_isnan\"   ,\"int\"          ,\"Nonzero if NaNS or NaNQ\", ieeeflag,nofuncflag);\none(\"itrunc\" ,\"\"            ,\"itrunc\"  ,\"int\"          ,\"Truncate and convert to integer\", bsdflag,1);\none(\"j0\"     ,\"\"            ,\"j0\"      ,\"double\"       ,\"Bessel function first kind, order 0\", ieeeflag);\none(\"j1\"     ,\"\"            ,\"j1\"      ,\"double\"       ,\"Bessel function first kind, order 1\", ieeeflag);\none(\"lgamma\" ,\"\"            ,\"lgamma\"  ,\"double\"       ,\"Log absolute gamma\", ieeeflag);\none(\"log\"    ,\"\"            ,\"log\"     ,\"double\"       ,\"Natural logarithm\");\none(\"log\",    \"float\",       \"log\",     \"float\",        \"\");\none(\"log\"    ,\"long double\" ,\"log\"     ,\"long double\"  ,\"\", ldflag);\none(\"log\"   ,\"complex<float> \", \"log\", \"complex<float>\", \"\", cflag1);\none(\"log\"   ,\"complex<double> \", \"log\", \"complex<double>\", \"\", cflag1);\n ofs << \"#ifndef __PGI\\n\";\none(\"log\", \"complex<long double> \", \"log\", \"complex<long double>\", \"\", cflag1);\n ofs << \"#endif\\n\";\none(\"logb\"   ,\"\"            ,\"logb\"    ,\"double\"       ,\"Unbiased exponent (IEEE)\", ieeeflag);\none(\"log1p\"  ,\"\"            ,\"log1p\"   ,\"double\"       ,\"Compute log(1 + x)\", ieeeflag);\none(\"log10\"  ,\"\"            ,\"log10\"   ,\"double\"       ,\"Logarithm base 10\");\none(\"log10\",  \"float\",       \"log10\",   \"float\",        \"\");\none(\"log10\"  ,\"long double\" ,\"log10\"  ,\"long double\"  ,\"\", ldflag);\none(\"log10\"   ,\"complex<float> \", \"log10\", \"complex<float>\", \"\", cflag2);\none(\"log10\"   ,\"complex<double> \", \"log10\", \"complex<double>\", \"\", cflag2);\none(\"log10\", \"complex<long double> \", \"log10\", \"complex<long double>\", \"\", cflag2);\none(\"nearest\", \"\"           ,\"nearest\" ,\"double\"       ,\"Nearest floating point integer\", bsdflag);\ntwo(\"nextafter\", \"\",         \"nextafter\", \"double\",     \"Next representable number after x towards y\", bsdflag);\n\nofs <<\n\"template<typename P_numtype>\\n\"\n\"class _bz_negate : public OneOperandApplicativeTemplatesBase {\\n\"\n\"public:\\n\"\n\"    typedef BZ_SIGNEDTYPE(P_numtype) T_numtype;\\n\\n\"\n\"    static inline T_numtype apply(T_numtype x)\\n\"\n\"    { return -x; }\\n\\n\"\n\"        template<typename T1>\\n\"\n\"        \"\n\"static void prettyPrint(BZ_STD_SCOPE(string) &str, prettyPrintFormat& format, const T1& a)\\n\"\n\"        {\\n\"\n\"                str += \\\"-(\\\";\\n\"\n\"                       a.prettyPrint(str,format);\\n\"\n\"                       str += \\\")\\\";\\n\"\n\"        }\\n\"\n\"};\\n\\n\"\n;\n\none(\"norm\",   \"\"            ,\"norm\"    ,0             ,\"\", cflag);\n\ntwo(\"polar\"  ,\"\"            ,\"polar\"   ,\"complex<T_numtype1>\", \"\", cflag, 1);\ntwo(\"pow\"    ,\"\"            ,\"pow\"     ,\"double\"       ,\"Power\");\n ofs << \"#ifndef __PGI\\n\";\ntwo(\"pow\"    ,\"float\"       ,\"pow\"     ,\"float\"        ,\"\");\n ofs << \"#endif\\n\";\ntwo(\"pow\"    ,\"long double\" ,\"pow\"     ,\"long double\"  ,\"\");\ntwo(\"pow\"    ,\"complex<float>\",\"pow\"   ,\"complex<float>\" ,\"\",cflag1);\ntwo(\"pow\"    ,\"complex<double>\",\"pow\"  ,\"complex<double>\",\"\",cflag1);\n ofs << \"#ifndef __PGI\\n\";\ntwo(\"pow\"    ,\"complex<long double>\",\"pow\",\"complex<long double>\",\"\",cflag1);\n ofs << \"#endif\\n\";\ntwo(\"remainder\", \"\",         \"remainder\", \"double\",     \"Remainder\", bsdflag);\n\none(\"rint\"   ,\"\"            ,\"rint\"    ,\"double\"       ,\"Round to floating point integer\", ieeeflag);\none(\"rsqrt\"  ,\"\"            ,\"rsqrt\"   ,\"double\"       ,\"Reciprocal square root\", bsdflag);\ntwo(\"scalb\"  ,\"\"            ,\"scalb\"   ,\"double\"       ,\"x * (2**y)\", bsdflag);\none(\"sin\"    ,\"\"            ,\"sin\"     ,\"double\"       ,\"Sine\");\none(\"sin\",    \"float\",       \"sin\",     \"float\",       \"\");\none(\"sin\"    ,\"long double\" ,\"sin\"    ,\"long double\"  ,\"\", ldflag);\none(\"sin\"   ,\"complex<float> \", \"sin\", \"complex<float>\", \"\", cflag1);\none(\"sin\"   ,\"complex<double> \", \"sin\", \"complex<double>\", \"\", cflag1);\n ofs << \"#ifndef __PGI\\n\";\none(\"sin\", \"complex<long double> \", \"sin\", \"complex<long double>\", \"\", cflag1);\n ofs << \"#endif\\n\";\none(\"sinh\"   ,\"\"            ,\"sinh\"    ,\"double\"       ,\"Hyperbolic sine\");\none(\"sinh\",   \"float\",       \"sinh\",    \"float\",        \"\");\none(\"sinh\"   ,\"long double\" ,\"sinh\"   ,\"long double\"  ,\"\", ldflag);\none(\"sinh\"   ,\"complex<float> \", \"sinh\", \"complex<float>\", \"\", cflag1);\none(\"sinh\"   ,\"complex<double> \", \"sinh\", \"complex<double>\", \"\", cflag1);\n ofs << \"#ifndef __PGI\\n\";\none(\"sinh\", \"complex<long double> \", \"sinh\", \"complex<long double>\", \"\", cflag1);\n ofs << \"#endif\\n\";\n\nofs << \n\"template<typename P_numtype>\\n\"\n\"class _bz_sqr : public OneOperandApplicativeTemplatesBase {\\n\"\n\"public:\\n\"\n\"    typedef P_numtype T_numtype;\\n\\n\"\n\"    static inline T_numtype apply(T_numtype x)\\n\"\n\"    { return x*x; }\\n\"\n\"    template<typename T1>\\n\"\n\"    static void prettyPrint(BZ_STD_SCOPE(string) &str, prettyPrintFormat& format,\\n\"\n\"        const T1& a)\\n\"\n\"    {\\n\"\n\"        str += \\\"sqr(\\\";\\n\"\n\"        a.prettyPrint(str,format);\\n\"\n\"        str += \\\")\\\";\\n\"\n\"    }\\n\"\n\"};\\n\\n\"\n\"#ifdef BZ_HAVE_COMPLEX\\n\"\n\"// Specialization of _bz_sqr for complex<T>\\n\"\n\"template<typename T>\\n\"\n\"class _bz_sqr<complex<T> > : public OneOperandApplicativeTemplatesBase {\\n\"\n\"public:\\n\"\n\"    typedef complex<T> T_numtype;\\n\\n\"\n\"    static inline T_numtype apply(T_numtype x)\\n\"\n\"    {\\n\"\n\"        T r = x.real();  T i = x.imag();\\n\"\n\"        return T_numtype(r*r-i*i, 2*r*i);\\n\"\n\"    }\\n\"\n\"    template<typename T1>\\n\"\n\"    static void prettyPrint(BZ_STD_SCOPE(string) &str, prettyPrintFormat& format,\\n\"\n\"        const T1& a)\\n\"\n\"    {\\n\"\n\"        str += \\\"sqr(\\\";\\n\"\n\"        a.prettyPrint(str,format);\\n\"\n\"        str += \\\")\\\";\\n\"\n\"    }\\n\"\n\"};\\n\"\n\"#endif\\n\\n\"\n;\n\none(\"sqrt\"   ,\"\"            ,\"sqrt\"    ,\"double\"       ,\"Square root\");\none(\"sqrt\",   \"float\",       \"sqrt\",    \"float\",        \"\");\none(\"sqrt\"   ,\"long double\" ,\"sqrt\"   ,\"long double\"  ,\"\", ldflag);\none(\"sqrt\"   ,\"complex<float> \", \"sqrt\", \"complex<float>\", \"\", cflag1);\none(\"sqrt\"   ,\"complex<double> \", \"sqrt\", \"complex<double>\", \"\", cflag1);\n ofs << \"#ifndef __PGI\\n\";\none(\"sqrt\", \"complex<long double> \", \"sqrt\", \"complex<long double>\", \"\", cflag1);\n ofs << \"#endif\\n\";\none(\"tan\"    ,\"\"            ,\"tan\"     ,\"double\"       ,\"Tangent\");\none(\"tan\",    \"float\",       \"tan\",    \"float\",         \"\");\none(\"tan\"    ,\"long double\" ,\"tan\"    ,\"long double\"  ,\"\");\none(\"tan\"   ,\"complex<float> \", \"tan\", \"complex<float>\", \"\", cflag1);\none(\"tan\"   ,\"complex<double> \", \"tan\", \"complex<double>\", \"\", cflag1);\n ofs << \"#ifndef __PGI\\n\";\none(\"tan\", \"complex<long double> \", \"tan\", \"complex<long double>\", \"\", cflag1);\n ofs << \"#endif\\n\";\none(\"tanh\"   ,\"\"            ,\"tanh\"    ,\"double\"       ,\"Hyperbolic tangent\");\none(\"tanh\",   \"float\",       \"tanh\",    \"float\",        \"\");\none(\"tanh\"   ,\"long double\" ,\"tanh\"   ,\"long double\"  ,\"\", ldflag);\none(\"tanh\"   ,\"complex<float> \", \"tanh\", \"complex<float>\", \"\", cflag1);\none(\"tanh\"   ,\"complex<double> \", \"tanh\", \"complex<double>\", \"\", cflag1);\n ofs << \"#ifndef __PGI\\n\";\none(\"tanh\", \"complex<long double> \", \"tanh\", \"complex<long double>\", \"\", cflag1);\n ofs << \"#endif\\n\";\n\n// blitz-bugs/archive/0189.html\n// one(\"trunc\"  ,\"\"            ,\"trunc\"   ,\"double\"       ,\"Nearest floating integer in the direction of zero\", ieeeflag);\n\none(\"uitrunc\", \"\"           ,\"uitrunc\" ,\"unsigned\"     ,\"Truncate and convert to unsigned\", bsdflag);\ntwo(\"unordered\", \"\",         \"unordered\", \"int\",       \"True if a comparison of x and y would be unordered\", bsdflag,1);\none(\"y0\"     ,\"\"            ,\"y0\"      ,\"double\"       ,\"Bessel function of the second kind, order zero\", ieeeflag);\none(\"y1\"     ,\"\"            ,\"y1\"      ,\"double\"       ,\"Bessel function of the second kind, order one\", ieeeflag);\n\n    ofs << std::endl << std::endl <<\n\"BZ_NAMESPACE_END\\n\\n\"\n\"#endif // BZ_MATHFUNC_H\\n\";\n\n    return 0;\n}\n\n", "meta": {"hexsha": "0f0cef508f76e019805e154f11dc2b0d926681c4", "size": 25309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scipy/weave/blitz/blitz/generate/genmathfunc.cpp", "max_stars_repo_name": "lesserwhirls/scipy-cwt", "max_stars_repo_head_hexsha": "ee673656d879d9356892621e23ed0ced3d358621", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 73.0, "max_stars_repo_stars_event_min_datetime": "2019-12-22T03:09:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:13:46.000Z", "max_issues_repo_path": "scipy/weave/blitz/blitz/generate/genmathfunc.cpp", "max_issues_repo_name": "lesserwhirls/scipy-cwt", "max_issues_repo_head_hexsha": "ee673656d879d9356892621e23ed0ced3d358621", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-07-22T23:29:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-17T07:12:00.000Z", "max_forks_repo_path": "scipy/weave/blitz/blitz/generate/genmathfunc.cpp", "max_forks_repo_name": "lesserwhirls/scipy-cwt", "max_forks_repo_head_hexsha": "ee673656d879d9356892621e23ed0ced3d358621", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-07-01T14:29:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T14:20:41.000Z", "avg_line_length": 43.9392361111, "max_line_length": 122, "alphanum_fraction": 0.4991109882, "num_tokens": 7361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.522700248897888}}
{"text": "#include <sbrandom.h>\r\n\r\n#include <boost/random.hpp>\r\n#include <boost/random/uniform_int_distribution.hpp>\r\n#include <boost/random/uniform_real_distribution.hpp>\r\n\r\nnamespace Scenebuilder{;\r\n\r\n///////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\nclass SamplerImpl{\r\npublic:\r\n\tboost::random::mt19937                     rng;\r\n\tboost::random::uniform_int_distribution<>  uniInt;\r\n\tboost::random::uniform_real_distribution<> uniReal;\r\n\tboost::random::normal_distribution<>       normal;\r\n\r\npublic:\r\n\tvoid   Seed          (int    _seed);\r\n\tint    SampleInt     (int    _min, int    _max);\r\n\treal_t SampleReal    (real_t _min, real_t _max);\r\n\treal_t SampleNormal  ();\r\n\r\n};\r\n\r\nvoid SamplerImpl::Seed(int _seed){\r\n\trng.seed(_seed);\r\n}\r\n\r\nint SamplerImpl::SampleInt (int _min, int _max){\r\n\tif(_min >= _max)\r\n\t\treturn _min;\r\n\r\n\tuniInt.param(boost::random::uniform_int_distribution<>::param_type(_min, _max));\r\n\treturn uniInt(rng);\r\n}\r\n\r\nreal_t SamplerImpl::SampleReal(real_t _min, real_t _max){\r\n\tif(_min >= _max)\r\n\t\treturn _min;\r\n\r\n\tuniReal.param(boost::random::uniform_real_distribution<>::param_type(_min, _max));\r\n\treturn uniReal(rng);\r\n}\r\n\r\nreal_t SamplerImpl::SampleNormal(){\r\n\treturn normal(rng);\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\nSampler::Sampler(){\r\n\timpl = new SamplerImpl();\r\n}\r\n\r\nSampler::~Sampler(){\r\n\tdelete impl;\r\n}\r\n\r\nvoid Sampler::Seed(int _seed){\r\n\timpl->Seed(_seed);\r\n}\r\n\r\nbool Sampler::SampleBool(){\r\n\treturn (bool)SampleInt(0, 1);\r\n}\r\n\r\nint Sampler::SampleInt(int _min, int _max){\r\n\treturn impl->SampleInt(_min, _max);\r\n}\r\n\r\nreal_t Sampler::SampleReal(real_t _min, real_t _max){\r\n\treturn impl->SampleReal(_min, _max);\r\n}\r\n\r\nreal_t Sampler::SampleNormal(){\r\n\treturn impl->SampleNormal();\r\n}\r\n\r\n}\r\n", "meta": {"hexsha": "6200a821b796cd52d5e3698727d63f40658ebb8d", "size": 1834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sbrandom.cpp", "max_stars_repo_name": "ytazz/Scenebuilder", "max_stars_repo_head_hexsha": "82942a096283abd9e253e27ced82ba18185370ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sbrandom.cpp", "max_issues_repo_name": "ytazz/Scenebuilder", "max_issues_repo_head_hexsha": "82942a096283abd9e253e27ced82ba18185370ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sbrandom.cpp", "max_forks_repo_name": "ytazz/Scenebuilder", "max_forks_repo_head_hexsha": "82942a096283abd9e253e27ced82ba18185370ee", "max_forks_repo_licenses": ["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.6419753086, "max_line_length": 100, "alphanum_fraction": 0.5965103599, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.522700248897888}}
{"text": "/*\n   confidence_intervals.cc\n   Copyright (c) 2011 mldb.ai inc.  All rights reserved.\n   This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n*/\n\n#include \"mldb/utils/confidence_intervals.h\"\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/math/distributions/normal.hpp> // for normal_distribution\n#include <math.h>\n#include \"mldb/arch/exception.h\"\n#include \"mldb/utils/string_functions.h\"\n#include <random>\n\n\nusing namespace std;\nusing namespace boost;\nusing boost::math::normal; // typedef provides default type is double.\n\nnamespace MLDB\n{\n\nConfidenceIntervals::\nConfidenceIntervals(float alpha, std::string m) : alpha_(alpha) {\n    init(m);\n}\n\nvoid ConfidenceIntervals::init(std::string m) {\n    if(m==\"wilson\") {\n        method = WILSON;\n\n        // Construct a standard normal distribution s\n        normal s; // (default mean = zero, and standard deviation = unity)\n        const double b = quantile(s, 1-alpha_);\n        const double d = pow(b, 2);\n        const double a = d / 2;\n        const double c = d / 4;\n\n        wilsonFnct = [=] (double sumNum, double sumDenom, double sign)\n            {\n                return (a/sumDenom+sumNum/sumDenom+b*\n                        sign*sqrt(c/(sumDenom*sumDenom)+(sumNum*\n                        (1-sumNum/sumDenom))/(sumDenom*sumDenom)))/(1+d/sumDenom);\n            };\n    }\n    else if (m==\"clopper_pearson\") {\n        method = CLOPPER_PEARSON;\n    }\n    else {\n        throw MLDB::Exception(MLDB::format(\"Unknown confidence interval method '%s'\", m.c_str()));\n    }\n}\n\nunsigned\nConfidenceIntervals::getMethod()\n{\n    return method;\n}\n\ndouble\nConfidenceIntervals::\nwilsonBinomialUpperLowerBound(int trials,\n        int successes, WilsonBoundDirection dir) const\n{\n    double sumNum = (double)successes;\n    double sumDenom = (double)trials;\n    double sign = (double)dir;\n    return wilsonFnct(sumNum, sumDenom, sign);\n}\n\ndouble\nConfidenceIntervals::\nbinomialUpperBound(int trials, int successes) const\n{\n    switch(method){\n    case WILSON:          return wilsonBinomialUpperLowerBound(trials, successes, UPPER);\n    case CLOPPER_PEARSON: return math::binomial_distribution<>::find_upper_bound_on_p(trials, successes, alpha_);\n    }\n    throw MLDB::Exception(MLDB::format(\"Unknown method '%s'\", method));\n}\n\ndouble\nConfidenceIntervals::\nbinomialLowerBound(int trials, int successes) const\n{\n    switch(method){\n    case WILSON:          return wilsonBinomialUpperLowerBound(trials, successes, LOWER);\n    case CLOPPER_PEARSON: return math::binomial_distribution<>::find_lower_bound_on_p(trials, successes, alpha_);\n    }\n    throw MLDB::Exception(MLDB::format(\"Unknown method '%s'\", method));\n}\n\npair<double,double>\nConfidenceIntervals::\nbinomialTwoSidedBound(int trials, int successes) const\n{\n    assertClopperPearson();\n    return make_pair(\n            math::binomial_distribution<>::find_lower_bound_on_p(trials, successes, alpha_/2.0),\n            math::binomial_distribution<>::find_upper_bound_on_p(trials, successes, alpha_/2.0)\n        );\n}\n\nvector<double>\nConfidenceIntervals::\ncreateBootstrapSamples(const vector<double>& sample, int replications,\n        int resampleSize) const\n{\n    assertClopperPearson();\n    int sampleSize = sample.size();\n\n    if(sampleSize ==0)\n    {\n        throw MLDB::Exception(\"Can't compute bootstrap mean from empty sample\");\n    }\n\n    std::mt19937 rng;\n\n    vector<double> resampleMeans;\n    for(int i=0; i<replications;i++)\n    {\n        double accumulator = 0;\n        for(int j=0;j<resampleSize;j++)\n        {\n            accumulator += sample[rng() % sampleSize];\n        }\n        resampleMeans.push_back(accumulator/resampleSize);\n    }\n    sort(resampleMeans.begin(), resampleMeans.end());\n    return resampleMeans;\n}\n\ndouble\nConfidenceIntervals::\nbootstrapMeanUpperBound(const vector<double>& sample, int replications,\n        int resampleSize) const\n{\n    assertClopperPearson();\n    vector<double> resampleMeans = createBootstrapSamples(sample, replications, resampleSize);\n    return resampleMeans[replications*(1-alpha_)];\n}\n\ndouble\nConfidenceIntervals::\nbootstrapMeanLowerBound(const vector<double>& sample, int replications,\n        int resampleSize) const\n{\n    assertClopperPearson();\n    vector<double> resampleMeans = createBootstrapSamples(sample, replications, resampleSize);\n    return resampleMeans[replications*alpha_];\n}\n\npair<double,double>\nConfidenceIntervals::\nbootstrapMeanTwoSidedBound(const vector<double>& sample, int replications,\n        int resampleSize) const\n{\n    assertClopperPearson();\n    vector<double> resampleMeans = createBootstrapSamples(sample, replications, resampleSize);\n    return make_pair(\n            resampleMeans[replications*(alpha_/2.0)],resampleMeans[replications*(1-alpha_/2.0)]\n        );\n}\n\nvoid ConfidenceIntervals::assertClopperPearson() const\n{\n    if (method != CLOPPER_PEARSON)\n        throw MLDB::Exception(\"Can only use this method with Clopper-Peason method!\");\n}\n        \nstd::string ConfidenceIntervals::\nprint(Method m) const\n{\n    switch(m) {\n    case WILSON:          return \"wilson\";\n    case CLOPPER_PEARSON: return \"clopper_pearson\";\n    default:\n        throw MLDB::Exception(\"Unknown method\");\n    }\n}\n\n#if 0\nvoid ConfidenceIntervals::\nserialize(MLDB::DB::Store_Writer & store) const\n{\n    int version = 1;\n    store << version << print(method) << alpha_;\n}\n\nvoid ConfidenceIntervals::\nreconstitute(MLDB::DB::Store_Reader & store)\n{\n    int version;\n    int REQUIRED_V = 1;\n    store >> version;\n    if(version!=REQUIRED_V) {\n        throw MLDB::Exception(MLDB::format(\n                    \"invalid ConfidenceInterval version! exptected %d, got %d\", \n                    REQUIRED_V, version));\n    }\n\n    string method;\n    store >> method >> alpha_;\n    init(method);\n}\n#endif\n\n}\n\n", "meta": {"hexsha": "bb00ed267be53db62dbc4b8687c1f2ade8ead057", "size": 5804, "ext": "cc", "lang": "C++", "max_stars_repo_path": "utils/confidence_intervals.cc", "max_stars_repo_name": "kstepanmpmg/mldb", "max_stars_repo_head_hexsha": "f78791cd34d01796705c0f173a14359ec1b2e021", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 665.0, "max_stars_repo_stars_event_min_datetime": "2015-12-09T17:00:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:46:46.000Z", "max_issues_repo_path": "utils/confidence_intervals.cc", "max_issues_repo_name": "tomzhang/mldb", "max_issues_repo_head_hexsha": "a09cf2d9ca454d1966b9e49ae69f2fe6bf571494", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 797.0, "max_issues_repo_issues_event_min_datetime": "2015-12-09T19:48:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T02:19:47.000Z", "max_forks_repo_path": "utils/confidence_intervals.cc", "max_forks_repo_name": "matebestek/mldb", "max_forks_repo_head_hexsha": "f78791cd34d01796705c0f173a14359ec1b2e021", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 103.0, "max_forks_repo_forks_event_min_datetime": "2015-12-25T04:39:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T02:55:22.000Z", "avg_line_length": 27.6380952381, "max_line_length": 113, "alphanum_fraction": 0.6802205376, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5227002439047419}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    cpp_int x, k, d; cin >> x >> k >> d;\n    if (x < 0) x *= -1;\n    cpp_int a = min(x / d, k);\n    k -= a, x -= a * d;\n    if (k % 2 == 0) cout << x << endl;\n    else cout << abs(x - d) << endl;\n}\n", "meta": {"hexsha": "df64175eb7cb5754d3f716f8df2fdc965eb4995d", "size": 391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc175/c/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/abc175/c/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/abc175/c/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": 24.4375, "max_line_length": 43, "alphanum_fraction": 0.5652173913, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5227002389115954}}
{"text": "#include <iostream>\n#include <fstream>\nusing namespace std;\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <Eigen/Geometry> \n#include <boost/format.hpp>  // for formating strings\n#include <pcl/point_types.h> \n#include <pcl/io/pcd_io.h> \n#include <pcl/visualization/pcl_visualizer.h>\n\nint main( int argc, char** argv )\n{\n    vector<cv::Mat> colorImgs, depthImgs;    // \u5f69\u8272\u56fe\u548c\u6df1\u5ea6\u56fe\n    // \u95ee\u9898\uff1a\u4ec0\u4e48\u662faligned_allocator?\n    // STL compatible allocator to use with types requiring a non standrad alignment.\n    // TO-DO: \u5bf9\u9f50\u65b9\u5f0f\u53ef\u4ee5\u52a8\u6001\u9009\u62e9\uff0c\u4e3b\u8981\u539f\u56e0\u662f\u9632\u6b62\u5927\u5c0f\u4e0d\u540c\u5bfc\u81f4\u7684\u5185\u5b58\u9519\u8bef\n    vector<Eigen::Isometry3d, Eigen::aligned_allocator<Eigen::Isometry3d>> poses; // \u76f8\u673a\u4f4d\u59ff\n    \n    // \u8bfb\u53d6txt\u6587\u4ef6\n    ifstream fin(\"./pose.txt\");\n    // \u4e5f\u53ef\u4ee5\u5199\u6210if(!fin.is_open())\n    if (!fin)\n    {\n        cerr<<\"\u8bf7\u5728\u6709pose.txt\u7684\u76ee\u5f55\u4e0b\u8fd0\u884c\u6b64\u7a0b\u5e8f\"<<endl;\n        // \u6709error\u65f6\u5019return 1\u6216\u8005-1\n        return 1;\n    }\n    \n    // \u5206\u522b\u5904\u74065\u5f20\u56fe\u7247\n    for ( int i=0; i<5; i++ )\n    {\n        // \u8fd9\u662f\u5b9a\u4e49\u4e86\u8bfb\u56fe\u7247\u7684\u683c\u5f0f\uff0callows formatted i/o\n        // \u8fd9\u4e2a\u8bfbrgb,depth\u56fe\u7684\u65b9\u6cd5\u5f88\u72ec\u7279\uff0c\u672c\u8d28\u4e0a\u548cscanf\u5dee\u4e0d\u591a\uff0c\u5b66\u4e60\u4e0b\n        boost::format fmt( \"./%s/%d.%s\" ); //\u56fe\u50cf\u6587\u4ef6\u683c\u5f0f\n        \n        // TO-DO: emplace_back\u636e\u8bf4\u529f\u80fd\u4e00\u6837\uff0c\u4f46\u662f\u6548\u7387\u66f4\u9ad8\uff0c\u6709\u5f85\u8003\u5bdf\u3002\u3002\n        colorImgs.push_back( cv::imread( (fmt%\"color\"%(i+1)%\"png\").str() ));\n        // VIP: imread\u5206\u4e3a\u4e0d\u540c\u7684flags\uff0c\u5176\u4e2d-1\u8868\u793a\u539f\u56fe\u8f93\u5165\uff0c0\u8868\u793a\u7070\u5ea6\u56fe\uff0c1\u8868\u793aRGB\u4e09\u901a\u9053\n        // -1 returns the loaded image as is (with alpha channel, otherwise it gets cropped)\n        // ppm(Portable PixMap) can be one byte per pixel (up to 2 bytes), which stores RGB\n        // pgm(Portable GreyMap) stores grayscale info, one value per pixel - up to 2 bytes\n        // \u8fd9\u91cc\u53ef\u4ee5\u7528-1\u6216\u80052\uff0c\u90fd\u662f\u4e00\u4e2a\u6548\u679c\uff0c2\u4e5f\u53ef\u4ee5\u628a\u4ed6\u4eec\u8f6c\u6362\u62102 bytes\n        depthImgs.push_back( cv::imread( (fmt%\"depth\"%(i+1)%\"pgm\").str(), -1 )); // \u4f7f\u7528-1\u8bfb\u53d6\u539f\u59cb\u56fe\u50cf\n        \n        // \u6b63\u5f0f\u8bfb\u53d6txt\u6587\u4ef6\u7684\u5185\u5bb9\uff0c\u4ee5\u6570\u7ec4\u7684\u5f62\u5f0f\u8bfb\u53d6\n        // \u9759\u6001\u5206\u914d--\u6570\u7ec4\u521d\u59cb\u5316\u65b9\u6cd5\uff0c\u9ed8\u8ba4\u90fd\u662f0\n        double data[7] = {0};\n        \n        \n        // for(auto x:v) where, v is data, x is defined variable     \n        // auto+&\u8868\u793a\u4f7f\u7528\u5f15\u7528\uff0c\u56e0\u4e3a\u540e\u7eed\u8981\u4fee\u6539data!\n        for ( auto& d:data ){\n            fin>>d;\n        }\n\n        // \u5b9a\u4e49\u4e86\u65cb\u8f6c\u77e9\u9635\u7684\u56db\u5143\u6570\n        // pose\u6587\u4ef6\u7684\u6784\u6210\uff1a\u524d\u4e09\u4e2a\u662fXYZ\uff0c\u540e\u56db\u4e2a\u8868\u5f81\u56db\u5143\u6570(3\u4e2a\u865a\u90e8+1\u4e2a\u5b9e\u90e8)\n        Eigen::Quaterniond q( data[6], data[3], data[4], data[5] );\n        // cout<<\"quaternion = \\n\"<<q.coeffs() <<endl;\n        Eigen::Isometry3d T(q);\n\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( data[0], data[1], data[2] ));\n        \n        // \u901a\u8fc7push_back\u4fdd\u5b58\u5404\u4e2a\u56fe\u50cf\u7684\u521d\u59cb\u4f4d\u59ff\uff01\n        poses.push_back( T );\n    }\n    \n    // \u8ba1\u7b97\u70b9\u4e91\u5e76\u62fc\u63a5\n    // \u76f8\u673a\u5185\u53c2 \n    double cx = 325.5; // \u8fd9\u4e2a\u503c\u633a\u6709\u610f\u601d\uff0c\u5e76\u4e0d\u662f640/2\n    double cy = 253.5;\n    double fx = 518.0;\n    double fy = 519.0;\n    // \u8bf4\u660e\u4e00\u5f00\u59cbdepth\u662f\u4ee5mm\u8ba1\u7684\uff0c\u540e\u9762\u8981\u8f6c\u6362\u6210meter\n    double depthScale = 1000.0;\n    \n    cout<<\"\u6b63\u5728\u5c06\u56fe\u50cf\u8f6c\u6362\u4e3a\u70b9\u4e91...\"<<endl;\n    \n    // \u5b9a\u4e49\u70b9\u4e91\u4f7f\u7528\u7684\u683c\u5f0f\uff1a\u8fd9\u91cc\u7528\u7684\u662fXYZRGB\n    typedef pcl::PointXYZRGB PointT; \n    typedef pcl::PointCloud<PointT> PointCloud;\n    \n    // \u65b0\u5efa\u4e00\u4e2a\u70b9\u4e91\uff0c\u7528\u5230\u4e86new\n    // \u8fd9\u4e2a\u6784\u9020\u51fd\u6570\u7684\u8f93\u5165\u662f\u4e00\u4e2a\u6307\u9488\uff0c\u6700\u540e\u8fd4\u56de\u4e00\u4e2a\u6307\u9488\n    // PointCloud (PointCloud< PointT > &pc)\n    PointCloud::Ptr pointCloud( new PointCloud ); \n    // \u5904\u7406\u6bcf\u5bf9RGBD\u6570\u636e\uff0c\u5e76\u6dfb\u52a0\u81f3\u70b9\u4e91\u4e2d\n    for ( int i=0; i<5; i++ )\n    {\n        cout<<\"\u8f6c\u6362\u56fe\u50cf\u4e2d: \"<<i+1<<endl; \n        // \u83b7\u53d6\u539f\u59cb\u6570\u636e\n        cv::Mat color = colorImgs[i]; \n        cv::Mat depth = depthImgs[i];\n        // \u83b7\u53d6pose\u6570\u636e\n        Eigen::Isometry3d T = poses[i];\n\n        // \u6309\u7167\u884c\u5217\u7684\u65b9\u5f0f\u5bf9\u4e8e\u6bcf\u4e2a\u50cf\u7d20\u8fdb\u884c\u64cd\u4f5c\n        for ( int v=0; v<color.rows; v++ )\n            for ( int u=0; u<color.cols; u++ )\n            {\n                // depth\u662f\u4ee5mm\u4e3a\u5355\u4f4d\uff0cunsigned int\u8303\u56f4\u662f0~2^32-1\n                // \u5148\u7528depth.ptr<>(v)\u53d6\u5230\u6307\u9488\uff0c\u7136\u540e[u]\u53d6\u5230\u503c\n                unsigned int d = depth.ptr<unsigned short> ( v )[u]; // \u6df1\u5ea6\u503c\n\n                if ( d==0 ) continue; // \u4e3a0\u8868\u793a\u6ca1\u6709\u6d4b\u91cf\u5230\n\n                // \u4ee5\u4e0b\u662f\u5c06\u56fe\u50cf\u5750\u6807\u7cfb\u8f6c\u6362\u6210\u76f8\u673a\u5750\u6807\u7cfb\n                Eigen::Vector3d point; \n                point[2] = double(d)/depthScale; // \u7531mm\u8f6c\u6362\u6210m\n                point[0] = (u-cx)*point[2]/fx;\n                point[1] = (v-cy)*point[2]/fy; \n\n                // \u5c06\u76f8\u673a\u5750\u6807\u7cfb\u8f6c\u6362\u6210\u4e16\u754c\u5750\u6807\u7cfb\n                Eigen::Vector3d pointWorld = T*point;\n                \n                // \u5728\u70b9\u4e91\u4e2d\u5b9a\u4e49\u6bcf\u4e00\u4e2a\u50cf\u7d20\u70b9\u5bf9\u5e94\u7684\u4e09\u7ef4\u7a7a\u95f4\u70b9\n                PointT p ;\n                p.x = pointWorld[0];\n                p.y = pointWorld[1];\n                p.z = pointWorld[2];\n\n                // data\u8868\u5f81cv::Mat\u91ccPointer to the user data\n                // step\u8868\u5f81cv::Mat\u91ccNumber of bytes each matrix row occupies\n                // RGB\u6bcf\u4e2a\u90fd\u662f1byte\uff0c\u7528color\u56fe\u5bf9\u5e94\u50cf\u7d20\u70b9\u7684\u503c\u8d4b\u503c\u7f62\u4e86\n                // VIP: opencv\u987a\u5e8f\u662fBGR\uff01\n                p.b = color.data[ v*color.step+u*color.channels() ];\n                p.g = color.data[ v*color.step+u*color.channels()+1 ];\n                p.r = color.data[ v*color.step+u*color.channels()+2 ];\n\n                // ->\u548c*ptr.\u7684\u6548\u7528\u662f\u4e00\u6837\u7684\n                // points\u662fPointCloud\u7684parameter\uff0c\u662fPCL\u6700\u57fa\u672c\u7684\u6570\u636e\u7c7b\u578b\n                // \u4e4b\u540e\u4e5f\u53ef\u4ee5\u901a\u8fc7pointCloud->points[i]\u53d6\u5230\u7b2ci\u4e2a\u6570\u636e\n                pointCloud->points.push_back( p );\n            }\n    }\n    \n    pointCloud->is_dense = false;\n    cout<<\"\u70b9\u4e91\u5171\u6709\"<<pointCloud->size()<<\"\u4e2a\u70b9.\"<<endl;\n    // \u6700\u540e\u8c03\u7528save\u51fd\u6570\u5c06\u5efa\u597d\u7684\u70b9\u4e91\u5b58\u5230\u672c\u5730\n    pcl::io::savePCDFileBinary(\"map.pcd\", *pointCloud );\n    return 0;\n}\n", "meta": {"hexsha": "3101f3d318365b4adb838dd6fbe1a5531e235b0d", "size": 4991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch5/joinMap/joinMap.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": "ch5/joinMap/joinMap.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": "ch5/joinMap/joinMap.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": 34.1849315068, "max_line_length": 94, "alphanum_fraction": 0.5535964737, "num_tokens": 1836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5226592501178903}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2017, 2018, Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\r\n\r\n// Licensed under the Boost Software License version 1.0.\r\n// http://www.boost.org/users/license.html\r\n\r\n#ifndef BOOST_TEST_MODULE\r\n#define BOOST_TEST_MODULE test_distance_geographic_pointlike_pointlike\r\n#endif\r\n\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\n#include \"test_distance_geo_common.hpp\"\r\n#include \"test_empty_geometry.hpp\"\r\n\r\n//===========================================================================\r\n\r\ntemplate <typename Point, typename Strategy>\r\nvoid test_distance_point_point(Strategy const& strategy)\r\n{\r\n\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl;\r\n    std::cout << \"point/point distance tests\" << std::endl;\r\n#endif\r\n    typedef test_distance_of_geometries<Point, Point> tester;\r\n\r\n    tester::apply(\"p-p-01\",\r\n                  \"POINT(1 1)\",\r\n                  \"POINT(0 0)\",\r\n                  strategy.apply(Point(1,1), Point(0,0)),\r\n                  strategy, true, false, false);\r\n}\r\n\r\n//===========================================================================\r\n\r\ntemplate <typename Point, typename Strategy>\r\nvoid test_distance_multipoint_point(Strategy const& strategy)\r\n{\r\n\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl;\r\n    std::cout << \"multipoint/point distance tests\" << std::endl;\r\n#endif\r\n    typedef bg::model::multi_point<Point> multi_point_type;\r\n\r\n    typedef test_distance_of_geometries<multi_point_type, Point> tester;\r\n\r\n    tester::apply(\"mp-p-01\",\r\n                  \"MULTIPOINT(1 1,1 2,2 3)\",\r\n                  \"POINT(0 0)\",\r\n                  pp_distance<Point>(\"POINT(0 0)\",\"POINT(1 1)\",strategy),\r\n                  strategy, true, false, false);\r\n\r\n    tester::apply(\"mp-p-01\",\r\n                  \"MULTIPOINT(0 0,0 2,2 0,2 2)\",\r\n                  \"POINT(1.1 1.1)\",\r\n                  pp_distance<Point>(\"POINT(1.1 1.1)\",\"POINT(2 2)\",strategy),\r\n                  strategy, true, false, false);\r\n}\r\n\r\n//===========================================================================\r\n\r\ntemplate <typename Point, typename Strategy>\r\nvoid test_distance_multipoint_multipoint(Strategy const& strategy)\r\n{\r\n\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl;\r\n    std::cout << \"multipoint/multipoint distance tests\" << std::endl;\r\n#endif\r\n    typedef bg::model::multi_point<Point> multi_point_type;\r\n\r\n    typedef test_distance_of_geometries<multi_point_type, multi_point_type> tester;\r\n\r\n    tester::apply(\"mp-mp-01\",\r\n                  \"MULTIPOINT(1 1,1 2,2 3)\",\r\n                  \"MULTIPOINT(0 0, 0 -1)\",\r\n                  pp_distance<Point>(\"POINT(0 0)\",\"POINT(1 1)\",strategy),\r\n                  strategy, true, false, false);\r\n}\r\n\r\n//===========================================================================\r\n//===========================================================================\r\n//===========================================================================\r\n\r\ntemplate <typename Point, typename Strategy>\r\nvoid test_all_pl_pl(Strategy pp_strategy)\r\n{\r\n    test_distance_point_point<Point>(pp_strategy);\r\n    test_distance_multipoint_point<Point>(pp_strategy);\r\n    test_distance_multipoint_multipoint<Point>(pp_strategy);\r\n\r\n    test_more_empty_input_pointlike_pointlike<Point>(pp_strategy);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_all_pointlike_pointlike )\r\n{\r\n    typedef bg::model::point\r\n            <\r\n                double, 2,\r\n                bg::cs::spherical_equatorial<bg::degree>\r\n            > sph_point;\r\n\r\n    test_all_pl_pl<sph_point>(spherical_pp());\r\n\r\n    typedef bg::model::point\r\n            <\r\n                double, 2,\r\n                bg::cs::geographic<bg::degree>\r\n            > geo_point;\r\n\r\n    test_all_pl_pl<geo_point>(vincenty_pp());\r\n    test_all_pl_pl<geo_point>(thomas_pp());\r\n    test_all_pl_pl<geo_point>(andoyer_pp());\r\n}\r\n", "meta": {"hexsha": "f67ccfeef0bf9358451bc0f441fabfa3e192c1c8", "size": 3985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/algorithms/distance/distance_se_geo_pl_pl.cpp", "max_stars_repo_name": "Talustus/boost_src", "max_stars_repo_head_hexsha": "ffe074de008f6e8c46ae1f431399cf932164287f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "third_party/boost/libs/geometry/test/algorithms/distance/distance_se_geo_pl_pl.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "third_party/boost/libs/geometry/test/algorithms/distance/distance_se_geo_pl_pl.cpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 32.9338842975, "max_line_length": 84, "alphanum_fraction": 0.5550815558, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5226592460237451}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <sway/math.h>\n\nusing namespace sway;\n\nBOOST_AUTO_TEST_SUITE(TVector4TestSuite)\n\n/*!\n * \\brief\n *    \u0423\u0431\u0435\u0436\u0434\u0430\u0435\u043c\u0441\u044f, \u0447\u0442\u043e \u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u043e\u0440 \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e \u043f\u0440\u0438\u0432\u043e\u0434\u0438\u0442 \u0432\u0441\u0435 \u043a\u043e\u043c\u043f\u043e\u043d\u0435\u043d\u0442\u044b \u043a \u043d\u0443\u043b\u044e.\n */\nBOOST_AUTO_TEST_CASE(TVector4TestCase_DefaultConstructor) {\n\tconst math::vec4i_t vec4;\n\n\tBOOST_CHECK_EQUAL(vec4.getX(), 0);\n\tBOOST_CHECK_EQUAL(vec4.getY(), 0);\n\tBOOST_CHECK_EQUAL(vec4.getZ(), 0);\n\tBOOST_CHECK_EQUAL(vec4.getW(), 0);\n}\n\n/*!\n * \\brief\n *    \u0423\u0431\u0435\u0436\u0434\u0430\u0435\u043c\u0441\u044f, \u0447\u0442\u043e \u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u043e\u0440 \u0443\u0441\u0442\u0430\u043d\u0430\u0432\u043b\u0438\u0432\u0430\u0435\u0442 \u0432\u0441\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043a\u043e\u043c\u043f\u043e\u043d\u0435\u043d\u0442\u043e\u0432 \u0432 \u0442\u0435, \n *    \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0431\u044b\u043b\u0438 \u0437\u0430\u0434\u0430\u043d\u044b.\n */\nBOOST_AUTO_TEST_CASE(TVector4TestCase_ComponentConstructor) {\n\tconst s32_t x = 1, y = 2, z = 3, w = 4;\n\tconst math::vec4i_t vec4(x, y, z, w);\n\n\tBOOST_CHECK_EQUAL(vec4.getX(), x);\n\tBOOST_CHECK_EQUAL(vec4.getY(), y);\n\tBOOST_CHECK_EQUAL(vec4.getZ(), z);\n\tBOOST_CHECK_EQUAL(vec4.getW(), w);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ba5fe1b46b5c6e03d365c3f7c1e14f45bd457d87", "size": 901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/vector4.spec.cpp", "max_stars_repo_name": "timcogames/sway.module_math", "max_stars_repo_head_hexsha": "1e9f8045952b8521146cf32cabf5b839354ea767", "max_stars_repo_licenses": ["MIT"], "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/vector4.spec.cpp", "max_issues_repo_name": "timcogames/sway.module_math", "max_issues_repo_head_hexsha": "1e9f8045952b8521146cf32cabf5b839354ea767", "max_issues_repo_licenses": ["MIT"], "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/vector4.spec.cpp", "max_forks_repo_name": "timcogames/sway.module_math", "max_forks_repo_head_hexsha": "1e9f8045952b8521146cf32cabf5b839354ea767", "max_forks_repo_licenses": ["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.7105263158, "max_line_length": 79, "alphanum_fraction": 0.7291897891, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5226592292088579}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"algorithms/math/bitwise_operators.hpp\"\n\nBOOST_AUTO_TEST_SUITE(BitwiseOperations)\n\nBOOST_AUTO_TEST_CASE(add)\n{\n    BOOST_CHECK(0 == BitwiseOperators::BitwiseAdd(0, 0));\n    BOOST_CHECK(0 == BitwiseOperators::BitwiseAddRecursive(0, 0));\n\n    BOOST_CHECK(1 == BitwiseOperators::BitwiseAdd(1, 0));\n    BOOST_CHECK(1 == BitwiseOperators::BitwiseAddRecursive(1, 0));\n\n    BOOST_CHECK(1 == BitwiseOperators::BitwiseAdd(0, 1));\n    BOOST_CHECK(1 == BitwiseOperators::BitwiseAddRecursive(0, 1));\n\n    BOOST_CHECK(2 == BitwiseOperators::BitwiseAdd(1, 1));\n    BOOST_CHECK(2 == BitwiseOperators::BitwiseAddRecursive(1, 1));\n\n    BOOST_CHECK(5 == BitwiseOperators::BitwiseAdd(2, 3));\n    BOOST_CHECK(5 == BitwiseOperators::BitwiseAddRecursive(2, 3));\n}\n\nBOOST_AUTO_TEST_CASE(abs) {\n    BOOST_CHECK(0 == BitwiseOperators::BitwiseAbs(0));\n    BOOST_CHECK(1 == BitwiseOperators::BitwiseAbs(1));\n    BOOST_CHECK(1 == BitwiseOperators::BitwiseAbs(-1));\n    BOOST_CHECK(16894 == BitwiseOperators::BitwiseAbs(16894));\n    BOOST_CHECK(78953 == BitwiseOperators::BitwiseAbs(-78953));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "799a00afe89957865a023490cad5734a1c067288", "size": 1140, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/math/test_bitwise_operators.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_bitwise_operators.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_bitwise_operators.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": 34.5454545455, "max_line_length": 66, "alphanum_fraction": 0.7315789474, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5226033346017519}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2013 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#include <geometry_test_common.hpp>\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n\n#include <boost/geometry/extensions/nsphere/nsphere.hpp>\n\ntemplate <typename P, typename T>\nvoid test_comparable_margin_circle()\n{\n    bg::model::nsphere<P, T> c;\n\n    bg::set<0>(c.center(), 0);\n    bg::set<1>(c.center(), 0);\n    c.radius(2);\n\n    double d = bg::index::detail::comparable_margin(c);\n    BOOST_CHECK_CLOSE(d, 2, 0.001);\n}\n\ntemplate <typename P, typename T>\nvoid test_comparable_margin_sphere()\n{\n    bg::model::nsphere<P, T> s;\n\n    bg::set<0>(s, 0);\n    bg::set<1>(s, 0);\n    bg::set<2>(s, 0);\n    bg::set_radius<0>(s, 2);\n\n    double d = bg::index::detail::comparable_margin(s);\n    BOOST_CHECK_CLOSE(d, 4, 0.001);\n}\n\nint test_main(int, char* [])\n{\n    test_comparable_margin_circle<bg::model::point<double, 2, bg::cs::cartesian>, double>();\n    test_comparable_margin_sphere<bg::model::point<double, 3, bg::cs::cartesian>, double>();\n    return 0;\n}\n", "meta": {"hexsha": "6dbe3db1bdc76a580d74216f0f8b1dc96156e53e", "size": 1392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/nsphere/nsphere-index_margin.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-index_margin.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-index_margin.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 27.2941176471, "max_line_length": 92, "alphanum_fraction": 0.6867816092, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.522603329498386}}
{"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/collision/gjk/gjk_reduce_triangle.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\n#include <cmath>\r\n\r\nusing namespace OpenTissue;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_collision_gjk_reduce_triangle);\r\n\r\nBOOST_AUTO_TEST_CASE(case_by_case_test)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n  typedef math_types::vector3_type                         vector3_type;\r\n  typedef math_types::real_type                            real_type;\r\n\r\n  typedef OpenTissue::gjk::Simplex<vector3_type>           simplex_type;\r\n\r\n\r\n\r\n  // Inside face-region new simplex should be ABC\r\n  {\r\n    vector3_type const a = vector3_type(-1.0, -1.0, 0.0);\r\n    vector3_type const b = vector3_type( 1.0, -1.0, 0.0);\r\n    vector3_type const c = vector3_type( 0.5,  0.1, 0.0);\r\n\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\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          real_type u = i*0.1;\r\n          real_type v = j*0.1;\r\n          real_type w = k*0.1;\r\n\r\n          real_type lgh = u + v +w;\r\n          u /= lgh;\r\n          v /= lgh;\r\n          w /= lgh;\r\n\r\n          vector3_type const p = u*a + v*b + w*c;\r\n\r\n          OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n          BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n          int bit_A    = 0;\r\n          size_t idx_A = 0;\r\n          int bit_B    = 0;\r\n          size_t idx_B = 0;\r\n          int bit_C    = 0;\r\n          size_t idx_C = 0;\r\n          OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n          BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n          BOOST_CHECK(S.m_v[idx_A] == a);\r\n          BOOST_CHECK(S.m_a[idx_A] == a);\r\n          BOOST_CHECK(S.m_b[idx_A] == a);\r\n\r\n          BOOST_CHECK(S.m_v[idx_B] == b);\r\n          BOOST_CHECK(S.m_a[idx_B] == b);\r\n          BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n          BOOST_CHECK(S.m_v[idx_C] == c);\r\n          BOOST_CHECK(S.m_a[idx_C] == c);\r\n          BOOST_CHECK(S.m_b[idx_C] == c);\r\n\r\n          BOOST_CHECK_CLOSE(S.m_w[idx_A], u, 0.01);\r\n          BOOST_CHECK_CLOSE(S.m_w[idx_B], v, 0.01);\r\n          BOOST_CHECK_CLOSE(S.m_w[idx_C], w, 0.01);\r\n\r\n        }\r\n  }\r\n\r\n\r\n  // First we create a simplex that represents an triangle\r\n  vector3_type const a = vector3_type(-1.0, -1.0, 0.0);\r\n  vector3_type const b = vector3_type( 1.0, -1.0, 0.0);\r\n  vector3_type const c = vector3_type( 0.0,  1.0, 0.0);\r\n\r\n  // Inside face-region new simplex should be ABC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = vector3_type( 0.0, 0.0,  1.0);\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    int bit_C    = 0;\r\n    size_t idx_C = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n\r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK(S.m_v[idx_C] == c);\r\n    BOOST_CHECK(S.m_a[idx_C] == c);\r\n    BOOST_CHECK(S.m_b[idx_C] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.25, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.25, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.5, 0.01);\r\n  }\r\n  // Inside A voronoi region new simplex should be A\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = vector3_type( -2.0, -1.0,  1.0);\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A);\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\r\n  }\r\n  // Inside B voronoi region new simplex should be B\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = vector3_type(  2.0, -1.0,  1.0);\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A);\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.00, 0.01);\r\n  }\r\n  // Inside C voronoi region new simplex should be C\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = vector3_type(  0.0, 2.0,  1.0);\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A  );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A);\r\n    BOOST_CHECK(S.m_v[idx_A] == c);\r\n    BOOST_CHECK(S.m_a[idx_A] == c);\r\n    BOOST_CHECK(S.m_b[idx_A] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\r\n  }\r\n  // Inside AB voronoi region new simplex should be AB\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = vector3_type( 0.0, -2.0,  1.0);\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n\r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n  // Inside BC voronoi region new simplex should be BC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = vector3_type( 1.5, 0.5,  1.0);\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n\r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n  // Inside AC voronoi region new simplex should be AC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = vector3_type( -1.5, 0.5,  1.0);\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n\r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n\r\n  // On vertex A new simplex should be A\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( a, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A);\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\r\n  }\r\n  // On vertex B new simplex should be B\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( b, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A);\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.00, 0.01);\r\n  }\r\n  // On vertex C new simplex should be C\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( c, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A  );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A);\r\n    BOOST_CHECK(S.m_v[idx_A] == c);\r\n    BOOST_CHECK(S.m_a[idx_A] == c);\r\n    BOOST_CHECK(S.m_b[idx_A] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\r\n  }\r\n  // On edge AB new simplex should be AB\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = vector3_type( 0.0, -1.0,  1.0);\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n\r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n  // On edge BC new simplex should be BC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = vector3_type( 0.5, 0.0,  1.0);\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n\r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n  // On edge AC new simplex should be AC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = vector3_type( -0.5, 0.0,  1.0);\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n\r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n\r\n  // Assymmetric test cases\r\n\r\n  { // New simplex should be AB\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = 0.4*a + 0.6*b;\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n\r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.4, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.6, 0.01);\r\n  }\r\n  // New simplex should be BC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = 0.4*b + 0.6*c;\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n\r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.4, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.6, 0.01);\r\n  }\r\n  // New simplex should be AC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = 0.6*a + 0.4*c;\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n\r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.6, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.4, 0.01);\r\n  }\r\n\r\n\r\n  // New simplex should be ABC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n\r\n    vector3_type const p = 0.1*a + 0.2*b + 0.7*c;\r\n\r\n    OpenTissue::gjk::detail::reduce_triangle( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    int bit_C    = 0;\r\n    size_t idx_C = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n\r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK(S.m_v[idx_C] == c);\r\n    BOOST_CHECK(S.m_a[idx_C] == c);\r\n    BOOST_CHECK(S.m_b[idx_C] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.1, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.2, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.7, 0.01);\r\n  }\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "27979beb94e96a4a0110fefa4ebef45bc0923d93", "size": 18774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/collision/gjk/reduce_triangle/src/unit_reduce_triangle.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/collision/gjk/reduce_triangle/src/unit_reduce_triangle.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/collision/gjk/reduce_triangle/src/unit_reduce_triangle.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": 30.2806451613, "max_line_length": 103, "alphanum_fraction": 0.5958240119, "num_tokens": 6300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5225526334947461}}
{"text": "#include <iostream> \n#include <cstdlib>\n#include <cmath>\n#include <fstream>   \n#include <sstream>   \n#include <iomanip>\n#include <string>\n#include <boost/multi_array.hpp>\n\n# if not defined MATRIX_CLASS_H\n# define MATRIX_CLASS_H\n\nusing namespace std;\n\n/* predefined Boost multi-array types */\ntypedef boost::multi_array<double, 3> boost_array3d_t;\ntypedef boost::array<boost_array3d_t::index, 3> boost_array3d_ind_t;\ntypedef boost::multi_array<double, 2> boost_array2d_t;\ntypedef boost::multi_array<double, 1> boost_array1d_t;\n\n/* print 3D array in Paraview format */\nvoid print_vtk(boost_array3d_t&, string, const int);\nvoid print_vtk(std::vector<double>&, const int, const int, const int, string);\n\n/* print 3D array in standard csv format */\nvoid print_array_slice(boost_array3d_t &arr, string filename, int slice_ind);\nvoid print_array_full(boost_array3d_t &arr, string filename);\n\ndouble l2_norm(boost_array3d_t& data);\ndouble sum_elements(boost_array3d_t& data);\n\n# endif", "meta": {"hexsha": "319d3c33817afe0b4971846d4dda94ca8e22e4e7", "size": 976, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/matrix.hpp", "max_stars_repo_name": "madagra/brain-tumor-simulation", "max_stars_repo_head_hexsha": "134eacd34034a65a48e8aad1b42dc2fb701892a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/matrix.hpp", "max_issues_repo_name": "madagra/brain-tumor-simulation", "max_issues_repo_head_hexsha": "134eacd34034a65a48e8aad1b42dc2fb701892a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/matrix.hpp", "max_forks_repo_name": "madagra/brain-tumor-simulation", "max_forks_repo_head_hexsha": "134eacd34034a65a48e8aad1b42dc2fb701892a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-11T14:24:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-11T14:24:26.000Z", "avg_line_length": 30.5, "max_line_length": 78, "alphanum_fraction": 0.7756147541, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5225526253316016}}
{"text": "//\n// Created by a.kiryanenko on 3/10/20.\n//\n\n#include <iostream>\n#include \"../SpuUltraGraphAdapter.h\"\n#include \"../SpuUltraGraphProperty.h\"\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n\n\nusing namespace std;\nusing namespace SPU_GRAPH;\nusing namespace boost;\n\n\n// \u041a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u043f\u0435\u0447\u0430\u0442\u0438 \u0441\u0432\u043e\u0439\u0441\u0442\u0432 \u0432\u0435\u0440\u0448\u0438\u043d\u044b \u0434\u043b\u044f graphvis\nclass vertex_property_writer {\n    const SpuUltraGraph &_g;\npublic:\n    vertex_property_writer(SpuUltraGraph &g) : _g(g) {}\n    void operator()(std::ostream& out, const SpuUltraGraph::vertex_descriptor &v) const {\n        out << \"[label=\\\"\" << v << \"\\\"]\";\n    }\n};\n\n// \u041a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u043f\u0435\u0447\u0430\u0442\u0438 \u0441\u0432\u043e\u0439\u0441\u0442\u0432 \u0440\u0435\u0431\u0440\u0430 \u0434\u043b\u044f graphvis\nclass edge_property_writer {\n    const SpuUltraGraph &_g;\npublic:\n    edge_property_writer(SpuUltraGraph &g) : _g(g) {}\n    void operator()(std::ostream& out, const SpuUltraGraph::edge_descriptor &e) const {\n        out << \"[label=\\\"\" << get(edge_weight, _g, e) << \"\\\"]\";\n    }\n};\n\n\nint main()\n{\n    SpuUltraGraph graph;\n\n    graph.add_vertex(1);\n    graph.add_vertex(2);\n    graph.add_vertex(3);\n    graph.add_vertex(4);\n    graph.add_vertex(5);\n    graph.add_vertex(10);\n\n    graph.add_edge(graph.get_free_edge_descriptor(2), 1, 2);\n    graph.add_edge(graph.get_free_edge_descriptor(1), 1, 3);\n    graph.add_edge(graph.get_free_edge_descriptor(8), 1, 10);\n    graph.add_edge(graph.get_free_edge_descriptor(1), 2, 2);\n    graph.add_edge(graph.get_free_edge_descriptor(1), 2, 3);\n    graph.add_edge(graph.get_free_edge_descriptor(2), 2, 4);\n    graph.add_edge(graph.get_free_edge_descriptor(5), 3, 4);\n    graph.add_edge(graph.get_free_edge_descriptor(6), 3, 5);\n    graph.add_edge(graph.get_free_edge_descriptor(3), 4, 10);\n    graph.add_edge(graph.get_free_edge_descriptor(7), 5, 10);\n\n\n    // \u0421 \u043f\u043e\u043c\u043e\u0449\u044c\u044e GraphViz \u0441\u043e\u0437\u0434\u0430\u0434\u0438\u043c svg \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0435 \u0433\u0440\u0430\u0444\u0430\n    vertex_property_writer vpw(graph);\n    edge_property_writer epw(graph);\n    std::ofstream f(\"graph.dot\");\n    boost::write_graphviz(f, graph, vpw, epw);\n    f.close();\n    system(\"dot graph.dot -Kcirco -Tsvg -o graph.svg\");\n\n\n    // \u0421\u043e\u0437\u0434\u0430\u044e \u0441\u0432\u043e\u0439\u0441\u0442\u0432\u043e \u043f\u0440\u0435\u0434\u0448\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u0438\u043a \u0434\u043b\u044f \u0432\u0435\u0440\u0448\u0438\u043d\n    map<SpuUltraGraph::vertex_descriptor, SpuUltraGraph::vertex_descriptor> vertex_to_predecessor;\n    associative_property_map<map<SpuUltraGraph::vertex_descriptor, SpuUltraGraph::vertex_descriptor>> predecessor_property_map(vertex_to_predecessor);\n    // \u0421\u043e\u0437\u0434\u0430\u044e \u0441\u0432\u043e\u0439\u0441\u0442\u0432\u043e \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0435 \u0434\u043b\u044f \u0432\u0435\u0440\u0448\u0438\u043d\n    map<SpuUltraGraph::vertex_descriptor, size_t> vertex_to_distance;\n    associative_property_map<map<SpuUltraGraph::vertex_descriptor, size_t>> distance_property_map(vertex_to_distance);\n\n    // \u0412\u044b\u043f\u043e\u043b\u043d\u044f\u044e \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u0434\u0435\u0439\u043a\u0441\u0442\u0440\u0430 \u0434\u043b\u044f \u043f\u043e\u0434\u0441\u0447\u0435\u0442\u0430 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0439 \u043e\u0442 \u0432\u0435\u0440\u0448\u0438\u043d\u044b #1 \u0434\u043e \u043e\u0441\u0442\u0430\u043b\u044c\u043d\u044b\u0445\n    dijkstra_shortest_paths_no_color_map(graph, 1, predecessor_map(predecessor_property_map).distance_map(distance_property_map));\n\n    std::cout << \"Distances and parents:\" << std::endl;\n    for (auto v: graph.vertices()) {\n        cout << \"Vertex \" << v << \" Distance = \" << vertex_to_distance[v] << \", parent = \" << vertex_to_predecessor[v] + 1 << endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "dc0c69facd40b31174c1cf07d950ee263954f241", "size": 3052, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dijkstra_example.cpp", "max_stars_repo_name": "kiryanenko/graph-api", "max_stars_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T19:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-29T19:42:34.000Z", "max_issues_repo_path": "examples/dijkstra_example.cpp", "max_issues_repo_name": "kiryanenko/graph-api", "max_issues_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_issues_repo_licenses": ["MIT"], "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/dijkstra_example.cpp", "max_forks_repo_name": "kiryanenko/graph-api", "max_forks_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_forks_repo_licenses": ["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.488372093, "max_line_length": 150, "alphanum_fraction": 0.7169069463, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5225526111758794}}
{"text": "// Copyright Oleg Maximenko 2014.\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://github.com/svgpp/svgpp for library home page.\n\n#pragma once\n\n#include <svgpp/definitions.hpp>\n#include <boost/math/constants/constants.hpp>\n\nnamespace svgpp { namespace traits\n{\n\ntemplate<class Src, class Dst, class Number = double>\nstruct angle_conversion_coefficient\n{\n  static BOOST_CONSTEXPR Number value() \n  { \n    return angle_conversion_coefficient<Src, tag::angle_units::deg>::value() \n      / angle_conversion_coefficient<Dst, tag::angle_units::deg>::value();\n  }\n};\n\ntemplate<class Src, class Number>\nstruct angle_conversion_coefficient<Src, Src, Number>\n{ static BOOST_CONSTEXPR Number value() { return static_cast<Number>(1); } };\n\ntemplate<class Number>\nstruct angle_conversion_coefficient<tag::angle_units::grad, tag::angle_units::deg, Number>\n{ static BOOST_CONSTEXPR Number value() { return static_cast<Number>(0.9); } };\n\ntemplate<class Number>\nstruct angle_conversion_coefficient<tag::angle_units::rad, tag::angle_units::deg, Number>\n{ static BOOST_CONSTEXPR Number value() { return boost::math::constants::radian<Number>(); } };\n\n}}", "meta": {"hexsha": "aa0b1fd127beb40db665b84f94427276531e77f6", "size": 1259, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/svgpp/traits/angle_units.hpp", "max_stars_repo_name": "RichardCory/svgpp", "max_stars_repo_head_hexsha": "801e0142c61c88cf2898da157fb96dc04af1b8b0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 428.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:25:47.000Z", "max_issues_repo_path": "include/svgpp/traits/angle_units.hpp", "max_issues_repo_name": "andrew2015/svgpp", "max_issues_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T14:32:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T16:55:11.000Z", "max_forks_repo_path": "include/svgpp/traits/angle_units.hpp", "max_forks_repo_name": "andrew2015/svgpp", "max_forks_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2015-05-19T04:56:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:42:50.000Z", "avg_line_length": 33.1315789474, "max_line_length": 95, "alphanum_fraction": 0.7545671168, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5225363625769375}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"mesh/mesh.h\"\n\nnamespace telef::mesh {\nvoid ColorMesh::applyTransform(Eigen::MatrixXf transform) {\n  Eigen::Map<Eigen::Matrix3Xf> v(position.data(), 3, position.size() / 3);\n  Eigen::Matrix3Xf result =\n      (transform * v.colwise().homogeneous()).colwise().hnormalized();\n  position = Eigen::Map<Eigen::VectorXf>{result.data(), result.size()};\n}\n} // namespace telef::mesh", "meta": {"hexsha": "f26798529f0a2c0bbae58fdf5292113f7510975c", "size": 431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mesh/mesh.cpp", "max_stars_repo_name": "ycjungSubhuman/Kinect-Face", "max_stars_repo_head_hexsha": "b582bd8572e998617b5a0d197b4ac9bd4a9b42be", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-12T22:05:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T08:39:32.000Z", "max_issues_repo_path": "src/mesh/mesh.cpp", "max_issues_repo_name": "ycjungSubhuman/Kinect-Face", "max_issues_repo_head_hexsha": "b582bd8572e998617b5a0d197b4ac9bd4a9b42be", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mesh/mesh.cpp", "max_forks_repo_name": "ycjungSubhuman/Kinect-Face", "max_forks_repo_head_hexsha": "b582bd8572e998617b5a0d197b4ac9bd4a9b42be", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-14T08:29:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-01T07:11:17.000Z", "avg_line_length": 33.1538461538, "max_line_length": 74, "alphanum_fraction": 0.6983758701, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5224651455198956}}
{"text": "//\n// Copyright 2019 Miral Shah <miralshah2211@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/extension/io/jpeg.hpp>\n#include <boost/gil/image_processing/threshold.hpp>\n\nusing namespace boost::gil;\n\n// Demonstrates thresholding\n// Thresholding can either attribute an arbitrary value to pixels whose values are greater than the threshold\n// or can truncate the pixel values at an arbitrary maximum.\n// In particular, the function threshold_truncate accepts a mode and a direction.\n// Passing threshold_truncate_mode::threshold effectively truncates the values to the threshold, whereas\n// threshold_truncate_mode::zero sets them to 0.\n// The combination of mode and direction controls which pixels are modified:\n//     - threshold and regular: truncates the pixels whose values are greater than the threshold\n//     - threshold and inverse: truncates the pixels whose values are less than the threshold\n//     - zero and regular: zeroes the pixels whose values are less than the threshold\n//     - zero and inverse: zeroes the pixels whose values are greater than the threshold \n// See also:\n// adaptive_threshold.cpp - Adaptive thresholding\n\nint main()\n{\n    rgb8_image_t img;\n    read_image(\"test.jpg\",img, jpeg_tag{});\n    rgb8_image_t img_out(img.dimensions());\n\n//    performing binary threshold on each channel of the image\n//    if the pixel value is more than 150 than it will be set to 255 else to 0\n    boost::gil::threshold_binary(const_view(img), view(img_out), 150, 255);\n    write_view(\"out-threshold-binary.jpg\", view(img_out), jpeg_tag{});\n\n//    if the pixel value is more than 150 than it will be set to 150 else no change\n    boost::gil::threshold_truncate(const_view(img), view(img_out), 150, threshold_truncate_mode::threshold);\n    write_view(\"out-threshold-binary_inv.jpg\", view(img_out), jpeg_tag{});\n\n    return 0;\n}\n", "meta": {"hexsha": "b71f071ba6108a11d2406cd96a82997c2d545f91", "size": 2021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/threshold.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/threshold.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/threshold.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": 44.9111111111, "max_line_length": 109, "alphanum_fraction": 0.7516081148, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5224039918771277}}
{"text": "/*\n * Copyright Andrey Semashev 2020\n *\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/*!\n * \\file pow2.hpp\n *\n * This header includes all algorithms for operating on integral powers of 2.\n */\n\n#ifndef BOOST_BIT_OPS_POW2_HPP_INCLUDED_\n#define BOOST_BIT_OPS_POW2_HPP_INCLUDED_\n\n#include <boost/bit_ops/pow2/bit_ceil.hpp>\n#include <boost/bit_ops/pow2/bit_floor.hpp>\n#include <boost/bit_ops/pow2/bit_width.hpp>\n#include <boost/bit_ops/pow2/is_power_of_2.hpp>\n#include <boost/bit_ops/pow2/has_single_bit.hpp>\n\n#endif // BOOST_BIT_OPS_POW2_HPP_INCLUDED_\n", "meta": {"hexsha": "ca95c03479701702bdee3a237a562ab1e5232ace", "size": 664, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/bit_ops/pow2.hpp", "max_stars_repo_name": "Lastique/bit_ops", "max_stars_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops/pow2.hpp", "max_issues_repo_name": "Lastique/bit_ops", "max_issues_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops/pow2.hpp", "max_forks_repo_name": "Lastique/bit_ops", "max_forks_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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.6666666667, "max_line_length": 77, "alphanum_fraction": 0.7756024096, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5224039872965385}}
{"text": "#include \"vdp_sim.hpp\"\n\n#include <algorithm>\n#include <filesystem>\n#include <random>\n\n#include <boost/numeric/odeint.hpp>\n\nconst vdp_sim::input_type\nvdp_sim::interp1d(const std::vector<time>& u_t,\n                const std::vector<input_type>& u,\n                time t)\n{\n    const auto it = std::lower_bound(u_t.cbegin(),\n                            u_t.cend(),\n                            t);\n    if (it==u_t.cend())\n        return u.back();\n    else if (it==u_t.cbegin())\n        return u.front();\n    else{\n        const auto idx = std::distance(u_t.cbegin(),it);\n        input_type result;\n        time dt = u_t[idx]-u_t[idx-1];\n\n        for(size_t i=0; i < result.size(); ++i)\n            result[i] = u[idx-1][i]\n                + ((u[idx][i]-u[idx-1][i])/dt)\n                    *(t-u_t[idx-1]);\n        \n        return result;\n    }\n}\n\nvoid\nvdp_sim::generate_data(const std::string& dir, size_t n)\n{\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::normal_distribution<> noise{0., 1.};\n    std::uniform_real_distribution<> initial{-1.,1.};\n\n    boost::numeric::odeint::runge_kutta4<state_type> stepper;\n    auto vdp =\n        [this](const state_type &x,\n                state_type &dxdt,\n                time t)\n        {\n            input_type aux = interp1d(u_t, u, t);\n\n            dxdt[0] = 2.*x[1];\n            dxdt[1] = -0.8*x[0] + 2.*x[1]\n                    - 10.*x[0]*x[0]*x[1] + aux[0];\n        };\n\n    std::filesystem::create_directory(dir);\n\n    auto print_step =\n        [this](const state_type& x, const double t)\n        {\n            data_stream << t << \",\";\n            for(const auto& e : x)\n                data_stream << e << \",\";\n            data_stream << std::endl;\n        };\n\n    for(size_t i=0; i<n; ++i){\n        std::generate(u.begin(),\n                    u.end(),\n                    [&noise,&gen]() {\n                        input_type aux;\n                        for(auto& e : aux)\n                            e = noise(gen);\n                        return aux;\n                    });\n    \n        data_stream.open(dir+\"Input_\"+std::to_string(i)+\".csv\");\n        for(size_t j=0; j<u.size(); ++j){\n            data_stream << u_t[j] << \",\";\n            for(const auto& e : u[j])\n                data_stream << e << \",\";\n            data_stream << std::endl;\n        }\n        data_stream.close();\n\n        state_type x0;\n        std::generate(x0.begin(),x0.end(),\n            [&initial, &gen](){return initial(gen);});\n\n        data_stream.open(\n            dir+\"Output_\"+std::to_string(i)+\".csv\");\n        boost::numeric::odeint::\n            integrate_const(stepper,\n                            vdp,\n                            x0,\n                            0.0,\n                            period,\n                            ts,\n                            print_step);\n        data_stream.close();\n    }\n}", "meta": {"hexsha": "efb56d7d3d32ef729e60688dfdeffa6115a665f4", "size": 2868, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "koopman_cpp/vdp_sim.cpp", "max_stars_repo_name": "sergiovaneg/Koopman", "max_stars_repo_head_hexsha": "5cd9ce489b21b67a01a1ad62340e15c2c9ad6467", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "koopman_cpp/vdp_sim.cpp", "max_issues_repo_name": "sergiovaneg/Koopman", "max_issues_repo_head_hexsha": "5cd9ce489b21b67a01a1ad62340e15c2c9ad6467", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "koopman_cpp/vdp_sim.cpp", "max_forks_repo_name": "sergiovaneg/Koopman", "max_forks_repo_head_hexsha": "5cd9ce489b21b67a01a1ad62340e15c2c9ad6467", "max_forks_repo_licenses": ["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.1176470588, "max_line_length": 64, "alphanum_fraction": 0.4351464435, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5224039872965385}}
{"text": "// geometry_test.cpp : Defines the entry point for the console application.\r\n//\r\n\r\n#include <fstream>\r\nstd::ostream& logger()\r\n{\r\n\tstatic std::ofstream instance(\"geometry_log.hpp\");\r\n\treturn instance;\r\n}\r\n\r\n// Boost.Test\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\n#include \"private_allocator_tests.hpp\"\r\n\r\n#include \"product_tests.hpp\"\r\n// \r\n// //#include \"access_time_tests.hpp\"\r\n// //#include \"linear_algebra_timings.hpp\"\r\n//  \r\n// #include \"lup_decomposition_test.hpp\"\r\n#include \"proto_expression_tests.hpp\"\r\n// // \r\n#include \"tensor_tests.hpp\"\r\n#include \"point_example.hpp\"\r\n#include \"point_tests.hpp\"\r\n#include \"matrix_traits_test.hpp\"\r\n#include \"transform_tests.hpp\"\r\n// //#include \"numeric_cast_traits_test.hpp\"\r\n// \r\n#include \"utility_tests.hpp\"\r\n#include \"point_example_multi_type.hpp\"\r\n// \r\n#include \"tolerance_comparison_tests.hpp\"\r\n//#include \"constant_tests.hpp\"\r\n#include \"distance_tests.hpp\"\r\n// #include \"bsp_test.hpp\"\r\n// #include \"member_fusion_adaptor.hpp\"\r\n#include \"intersection_tests.hpp\"\r\n// \r\n// #include \"reference_frame_tests.hpp\"\r\n// \r\n// //#include \"kd_tree_test.hpp\"\r\n// // #include \"convex_hull_test.hpp\"\r\n#include \"segment_interval_test.hpp\"\r\n// // #include \"trapezoidal_decomposition_test.hpp\"\r\n#include \"eberly_triangle_aabb_intersection_tests.hpp\"\r\n// //#include \"boolean_operation_bsp_test.hpp\"\r\n// \r\n// //#include \"compose_matrix_test.hpp\"\r\n// \r\n#include \"vector_point_arithmetic_tests.hpp\"\r\n// \r\n#include \"grid_tests.hpp\"\r\n#include \"mesh_2d_tests.hpp\"\r\n// #include \"as_tests.hpp\"\r\n#include \"sorting_tests.hpp\"\r\n#include \"units_tests.hpp\"\r\n #include \"tagged_quantity_tests.hpp\"\r\n\r\n#include \"point_sequence_tests.hpp\"\r\n#include \"segment_intersection_tests.hpp\"\r\n\r\nusing namespace geometrix;\r\n\r\ntypedef point_double_2d point2;\r\ntypedef vector_double_2d vector2;\r\ntypedef segment_double_2d segment2;\r\ntypedef polyline<point2> polyline2;\r\ntypedef polygon<point2> polygon2;\r\n\r\ndouble vec_length(vector2 const& v)\r\n{\r\n\tusing namespace geometrix;\r\n\treturn sqrt(get<0>(v)*get<0>(v) + get<1>(v)*get<1>(v));\r\n}\r\n\r\ndouble p2p_distance(point2 const& p1, point2 const& p2)\r\n{\r\n\tusing namespace geometrix;\r\n\treturn point_point_distance(p1, p2);\r\n}\r\n\r\ndouble p2p_angle(point2 const& p1, point2 const& p2)\r\n{\r\n\tusing namespace geometrix;\r\n\treturn angle_from_a_to_b(p1, p2);\r\n}\r\n\r\ndouble vec_angle(vector2 const& v)\r\n{\r\n\treturn geometrix::vector_angle(v);\r\n}\r\n\r\ndouble seg_length(const segment2& seg)\r\n{\r\n\tusing namespace geometrix;\r\n\treturn point_point_distance(seg.get_start(), seg.get_end());\r\n}\r\n\r\ndouble seg2p_distance(const segment2& seg, const point2& p)\r\n{\r\n\tusing namespace geometrix;\r\n\treturn point_segment_distance(p, seg);\r\n}\r\n\r\nvoid write_point(const point2& p)\r\n{\r\n\tlogger() << p << std::endl;\r\n}\r\n\r\nvoid write_vector(const vector2& p)\r\n{\r\n\tlogger() << p << std::endl;\r\n}\r\n\r\nvoid write_segment(const segment2& s)\r\n{\r\n\tlogger() << s << std::endl;\r\n}\r\n\r\nvoid write_polygon(const polygon2& p)\r\n{\r\n\tlogger() << p << std::endl;\r\n}\r\n\r\nvoid write_polyline(const polyline2& p)\r\n{\r\n\tlogger() << p << std::endl;\r\n}\r\n\r\nvoid write_triangle(const std::array<point2,3>& p)\r\n{\r\n\tlogger() << polygon2(p.begin(), p.end()) << std::endl;\r\n}\r\n\r\nvoid write_mesh(const geometrix::mesh_2d<double>& mesh)\r\n{\r\n\tlogger() << \"-------start mesh \\n\";\r\n\tfor (int i = 0; i < mesh.get_number_triangles(); ++i) {\r\n\t\twrite_triangle(mesh.get_triangle_vertices(i));\r\n\t}\r\n\tlogger() << \"-------end mesh\" << std::endl;\r\n}\r\n\r\n\r\nvoid StandardExceptionTranslator(const std::exception& e)\r\n{\r\n\tBOOST_TEST_MESSAGE(e.what());\r\n}\r\n\r\nboost::unit_test::test_suite* init_unit_test_suite(int, char*[])\r\n{\r\n\tboost::unit_test::unit_test_log.set_threshold_level(boost::unit_test::log_messages);\r\n\tboost::unit_test::unit_test_monitor.register_exception_translator<std::exception>(&StandardExceptionTranslator);\r\n\tboost::unit_test::framework::master_test_suite().p_name.value = \"Geometrix Testing Framework\";\r\n\r\n\t//with explicit registration we could specify a test case timeout\r\n\t//boost::unit_test::framework::master_test_suite().add( BOOST_TEST_CASE( &infinite_loop ), 0, /* timeout */ 2 );\r\n\r\n\treturn 0;\r\n}", "meta": {"hexsha": "b955c0ccd6aac8cd3b57a0011743aa616320d3ab", "size": 4093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geometry_test/geometry_test.cpp", "max_stars_repo_name": "brandon-kohn/Geometrix", "max_stars_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometry_test/geometry_test.cpp", "max_issues_repo_name": "brandon-kohn/Geometrix", "max_issues_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometry_test/geometry_test.cpp", "max_forks_repo_name": "brandon-kohn/Geometrix", "max_forks_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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.2654320988, "max_line_length": 114, "alphanum_fraction": 0.7095040313, "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5224039827159491}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"pythagoricien.h\"\n#include \"utilitaires.h\"\n\nBOOST_AUTO_TEST_SUITE(test_pythagoricien)\n\n    struct fixture_pythagoricien {\n        std::set<std::tuple<size_t, size_t, size_t>> triplets;\n\n        fixture_pythagoricien() {\n            triplets = std::set<std::tuple<size_t, size_t, size_t>>\n                    {\n                            std::make_tuple(3, 4, 5),\n                            std::make_tuple(5, 12, 13),\n                            std::make_tuple(8, 15, 17),\n                            std::make_tuple(7, 24, 25),\n\n                            std::make_tuple(20, 21, 29),\n                            std::make_tuple(12, 35, 37),\n                            std::make_tuple(9, 40, 41),\n                            std::make_tuple(28, 45, 53),\n\n                            std::make_tuple(11, 60, 61),\n                            std::make_tuple(16, 63, 65),\n                            std::make_tuple(33, 56, 65),\n                            std::make_tuple(48, 55, 73),\n\n                            std::make_tuple(13, 84, 85),\n                            std::make_tuple(36, 77, 85),\n                            std::make_tuple(39, 80, 89),\n                            std::make_tuple(65, 72, 97)\n                    };\n        }\n    };\n\n    BOOST_FIXTURE_TEST_CASE(nombres_pythagoricien, fixture_pythagoricien) {\n        Pythagoricien pythagoricien(100);\n        std::set<std::tuple<size_t, size_t, size_t>> resultat;\n        for (auto t: pythagoricien) {\n            resultat.insert(t);\n        }\n\n        BOOST_CHECK_EQUAL_COLLECTIONS(triplets.begin(), triplets.end(), resultat.begin(), resultat.end());\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4b8ab1306db752104bf35d5416ccd776450b32fe", "size": 1708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/pythagoricien.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/pythagoricien.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/pythagoricien.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5833333333, "max_line_length": 106, "alphanum_fraction": 0.4707259953, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5224039735547703}}
{"text": "#ifndef STAN_MATH_REV_FUN_FFT_HPP\n#define STAN_MATH_REV_FUN_FFT_HPP\n\n#include <stan/math/prim/fun/Eigen.hpp>\n#include <stan/math/prim/fun/typedefs.hpp>\n#include <stan/math/rev/meta.hpp>\n#include <stan/math/prim/fun/fft.hpp>\n#include <stan/math/prim/fun/to_complex.hpp>\n#include <Eigen/Dense>\n#include <complex>\n#include <type_traits>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the discrete Fourier transform of the specified complex\n * vector.\n *\n * Given an input complex vector `x[0:N-1]` of size `N`, the discrete\n * Fourier transform computes entries of the resulting complex\n * vector `y[0:N-1]` by\n *\n * ```\n * y[n] = SUM_{i < N} x[i] * exp(-n * i * 2 * pi * sqrt(-1) / N)\n * ```\n *\n * The adjoint computation is given by\n * ```\n * adjoint(x) += length(y) * inv_fft(adjoint(y))\n * ```\n *\n * If the input is of size zero, the result is a size zero vector.\n *\n * @tparam V type of complex vector argument\n * @param[in] x vector to transform\n * @return discrete Fourier transform of `x`\n */\ntemplate <typename V, require_eigen_vector_vt<is_complex, V>* = nullptr,\n          require_var_t<base_type_t<value_type_t<V>>>* = nullptr>\ninline plain_type_t<V> fft(const V& x) {\n  if (unlikely(x.size() <= 1)) {\n    return plain_type_t<V>(x);\n  }\n\n  arena_t<V> arena_v = x;\n  arena_t<V> res = fft(to_complex(arena_v.real().val(), arena_v.imag().val()));\n\n  reverse_pass_callback([arena_v, res]() mutable {\n    auto adj_inv_fft = inv_fft(to_complex(res.real().adj(), res.imag().adj()));\n    adj_inv_fft *= res.size();\n    arena_v.real().adj() += adj_inv_fft.real();\n    arena_v.imag().adj() += adj_inv_fft.imag();\n  });\n\n  return plain_type_t<V>(res);\n}\n\n/**\n * Return the inverse discrete Fourier transform of the specified\n * complex vector.\n *\n * Given an input complex vector `y[0:N-1]` of size `N`, the inverse\n * discrete Fourier transform computes entries of the resulting\n * complex vector `x[0:N-1]` by\n *\n * ```\n * x[n] = SUM_{i < N} y[i] * exp(n * i * 2 * pi * sqrt(-1) / N)\n * ```\n *\n *  * The adjoint computation is given by\n * ```\n * adjoint(y) += (1 / length(x)) * fft(adjoint(x))\n * ```\n *\n * If the input is of size zero, the result is a size zero vector.\n * The only difference between the discrete DFT and its inverse is\n * the sign of the exponent.\n *\n * @tparam V type of complex vector argument\n * @param[in] y vector to inverse transform\n * @return inverse discrete Fourier transform of `y`\n */\ntemplate <typename V, require_eigen_vector_vt<is_complex, V>* = nullptr,\n          require_var_t<base_type_t<value_type_t<V>>>* = nullptr>\ninline plain_type_t<V> inv_fft(const V& y) {\n  if (unlikely(y.size() <= 1)) {\n    return plain_type_t<V>(y);\n  }\n\n  arena_t<V> arena_v = y;\n  arena_t<V> res\n      = inv_fft(to_complex(arena_v.real().val(), arena_v.imag().val()));\n\n  reverse_pass_callback([arena_v, res]() mutable {\n    auto adj_fft = fft(to_complex(res.real().adj(), res.imag().adj()));\n    adj_fft /= res.size();\n\n    arena_v.real().adj() += adj_fft.real();\n    arena_v.imag().adj() += adj_fft.imag();\n  });\n  return plain_type_t<V>(res);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "ebf092f4aea0857afecfbd4fea31d685cda41795", "size": 3135, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/rev/fun/fft.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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": "stan/math/rev/fun/fft.hpp", "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": "stan/math/rev/fun/fft.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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.7614678899, "max_line_length": 79, "alphanum_fraction": 0.6551834131, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5223859996252881}}
{"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//[c_array\n//` Small example showing the combination of an array with a Boost.Geometry algorithm\n\n#include <iostream>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian) \n\nint main()\n{\n    int a[3] = {1, 2, 3};\n    int b[3] = {2, 3, 4};\n\n    std::cout << boost::geometry::distance(a, b) << std::endl;\n    \n    return 0;\n}\n\n//]\n\n//[c_array_output\n/*`\nOutput:\n[pre\n1.73205\n]\n*/\n//]\n", "meta": {"hexsha": "335346b891cd435103feafd2b148e7d8a8f349c3", "size": 802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/geometry/doc/src/examples/geometries/adapted/c_array.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/geometries/adapted/c_array.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/geometries/adapted/c_array.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": 20.5641025641, "max_line_length": 85, "alphanum_fraction": 0.6932668329, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5223519288656536}}
{"text": "//C System-Headers\n//\n//C++ System headers\n#include <vector>//vector\n#include <string>//string\n#include <fstream>//iss*\n#include <chrono>// timing functions\n#include <cmath>//sqrt, abs\n#include <iostream>//cout\n#include <typeinfo>//typeid\n#include <algorithm> // transform, find\n#include <functional> // plus/minus\n#include <utility>//std::make_pair\n//Qt Headers\n//\n//OpenCV Headers\n//\n//Boost Headers\n#include <boost/algorithm/string.hpp>//split() and is_any_of for parsing .csv files\n#include <boost/lexical_cast.hpp>//lexical cast (unsurprisingly)\n//Project specific headers\n#include \"datatransformations.h\"\n\nstd::vector < data_triple<double> > power_to_data_triples( std::vector< double > power_list, double cavity_length, double min_freq, double max_freq ) {\n\n    uint number_of_points = power_list.size();\n\n    std::vector< data_triple<double> > processed;\n    processed.reserve( number_of_points );\n\n    for( uint i = 0; i < number_of_points ; i++ ) {\n\n        double i_f = static_cast<double>(i);\n        double num_points_f = static_cast<double>(number_of_points);\n\n        double frequency = (i_f + 1.0)*(max_freq - min_freq)/(num_points_f) + min_freq;\n        double power = power_list.at(i);\n\n        processed.push_back( data_triple<double>( round(frequency), cavity_length, power ) );\n    }\n\n    return processed;\n\n}\n\nstd::vector < float > string_to_power_list( std::string raw_data ) {\n\n    std::istringstream iss (raw_data);\n\n    while (iss) {\n        std::string input;\n        std::getline(iss, input);\n\n        std::vector<std::string> strs;\n        //split on comma delimiter\n        boost::split(strs, input, boost::is_any_of(\",\"));\n\n        std::vector< float > processed;\n        processed.reserve( strs.size() );\n\n        for( uint i = 0; i < strs.size() ; i ++ ) {\n            processed.push_back( boost::lexical_cast<float>( strs[i]) );\n        }\n\n        return processed;\n    }\n\n}\n", "meta": {"hexsha": "8f05ee07b628c2b088e3a9b62acdaf3acc360fca", "size": 1909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DataTransformatoions/datatransformations.cpp", "max_stars_repo_name": "SashaNullptr/Tiger-Acquire", "max_stars_repo_head_hexsha": "af1de6852e64a8df89a1fa20dfe01e541a84c887", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DataTransformatoions/datatransformations.cpp", "max_issues_repo_name": "SashaNullptr/Tiger-Acquire", "max_issues_repo_head_hexsha": "af1de6852e64a8df89a1fa20dfe01e541a84c887", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DataTransformatoions/datatransformations.cpp", "max_forks_repo_name": "SashaNullptr/Tiger-Acquire", "max_forks_repo_head_hexsha": "af1de6852e64a8df89a1fa20dfe01e541a84c887", "max_forks_repo_licenses": ["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.6666666667, "max_line_length": 151, "alphanum_fraction": 0.6589837611, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5223519240289808}}
{"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_REDUCTION_HPP_INCLUDED\n#define BOOST_SIMD_REDUCTION_HPP_INCLUDED\n\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-functions\n    @defgroup group-reduction Reduction Functions\n\n    These functions provide algorithms for in-register reduction and prefix-scan operations.\n    Those functions are usually only defined for SIMD types but may, in some cases such as sum or\n    product, have a valid scalar semantic.\n  **/\n\n} }\n\n#include <boost/simd/function/all.hpp>\n#include <boost/simd/function/any.hpp>\n#include <boost/simd/function/compare_equal.hpp>\n#include <boost/simd/function/compare_greater_equal.hpp>\n#include <boost/simd/function/compare_greater.hpp>\n#include <boost/simd/function/compare_less_equal.hpp>\n#include <boost/simd/function/compare_less.hpp>\n#include <boost/simd/function/compare_not_equal.hpp>\n#include <boost/simd/function/cummax.hpp>\n#include <boost/simd/function/cummin.hpp>\n#include <boost/simd/function/cumprod.hpp>\n#include <boost/simd/function/cumsum.hpp>\n#include <boost/simd/function/dot.hpp>\n#include <boost/simd/function/hmsb.hpp>\n#include <boost/simd/function/is_included_c.hpp>\n#include <boost/simd/function/is_included.hpp>\n#include <boost/simd/function/maximum.hpp>\n#include <boost/simd/function/minimum.hpp>\n#include <boost/simd/function/nbtrue.hpp>\n#include <boost/simd/function/none.hpp>\n#include <boost/simd/function/prod.hpp>\n#include <boost/simd/function/sum.hpp>\n\n#endif\n", "meta": {"hexsha": "37e5fc393ddc55458cb84d4443177dd69cde6e32", "size": 1835, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/reduction.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/reduction.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/reduction.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": 35.2884615385, "max_line_length": 100, "alphanum_fraction": 0.6942779292, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5223519213246781}}
{"text": "#include \"odd_or_even.hpp\"\r\n//#include <boost/numeric/meta_math/odd_or_even.hpp>\r\n#include<iostream>\r\nusing namespace std;\r\nint main(){\r\n        const long long n=6174;\r\n        cout<<n<<\" is \"<<(meta_math::odd_or_even<n>::value ? \"ODD\":\"EVEN\")<<'\\n';     \r\n        return 0;\r\n    }\r\n", "meta": {"hexsha": "a295fc1182374a45b3db0b40f3193545bd08864a", "size": 284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/linear_algebra/test/odd_or_even_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/linear_algebra/test/odd_or_even_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/linear_algebra/test/odd_or_even_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": 28.4, "max_line_length": 87, "alphanum_fraction": 0.5915492958, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5223519041103573}}
{"text": "#include <wmtk/TriMesh.h>\n#include <wmtk/utils/VectorUtils.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <wmtk/ExecutionScheduler.hpp>\n#include \"EdgeOperations2d.h\"\n\nusing namespace Edge2d;\nusing namespace wmtk;\n// get the quadrix in form of an array of 10 floating point numbers\nEigen::MatrixXd compute_Q_f(const EdgeOperations2d& m, const wmtk::TriMesh::Tuple& f_tuple)\n{\n    auto conn_indices = m.oriented_tri_vertices(f_tuple);\n    Eigen::Vector3d A = m.vertex_attrs[conn_indices[0].vid(m)].pos;\n    Eigen::Vector3d B = m.vertex_attrs[conn_indices[1].vid(m)].pos;\n    Eigen::Vector3d C = m.vertex_attrs[conn_indices[2].vid(m)].pos;\n\n    Eigen::Vector3d n = ((A - B).cross(C - B)).normalized();\n    Eigen::Vector4d p;\n    p(0) = n(0);\n    p(1) = n(1);\n    p(2) = n(2);\n    p(3) = -n.dot(B);\n    return p * p.transpose();\n}\n\n\nEigen::MatrixXd compute_Q_v(const EdgeOperations2d& m, const TriMesh::Tuple& v_tuple)\n{\n    auto conn_tris = m.get_one_ring_tris_for_vertex(v_tuple);\n    Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(4, 4);\n    auto Q_t = [](auto& m, auto& f_tuple) {\n        auto conn_indices = m.oriented_tri_vertices(f_tuple);\n        Eigen::Vector3d A = m.vertex_attrs[conn_indices[0].vid(m)].pos;\n        Eigen::Vector3d B = m.vertex_attrs[conn_indices[1].vid(m)].pos;\n        Eigen::Vector3d C = m.vertex_attrs[conn_indices[2].vid(m)].pos;\n\n        Eigen::Vector3d n = ((A - B).cross(C - B)).normalized();\n        Eigen::Vector4d p;\n        p(0) = n(0);\n        p(1) = n(1);\n        p(2) = n(2);\n        p(3) = -n.dot(B);\n\n        return (p * p.transpose());\n    };\n    for (auto tri : conn_tris) {\n        auto Q_tmp = compute_Q_f(m, tri);\n        Q += Q_tmp;\n    }\n    return Q;\n}\n\ndouble Edge2d::EdgeOperations2d::compute_cost_for_e(const TriMesh::Tuple& v_tuple)\n{\n    Eigen::MatrixXd Q = compute_Q_v(*this, v_tuple);\n    Q += compute_Q_v(*this, v_tuple.switch_vertex(*this));\n\n    Eigen::Vector4d t(0.0, 0.0, 0.0, 1.0);\n    Eigen::MatrixXd vQ = Q;\n    vQ.row(3) = t;\n\n    Eigen::Vector4d v;\n    if (vQ.determinant() < 1e-6) {\n        Eigen::Vector3d tmp =\n            (vertex_attrs[v_tuple.vid(*this)].pos + vertex_attrs[switch_vertex(v_tuple).vid(*this)].pos) / 2;\n        v << tmp, 1.0;\n    }\n\n    else\n        v = vQ.inverse() * t;\n\n    // wmtk::logger().info(\"Q is \\n {} \\n v is \\n {}\", Q, v);\n    Eigen::Vector3d newv = v.head(3);\n\n    return (v.transpose() * Q * v);\n}\n\nbool Edge2d::EdgeOperations2d::collapse_qec(int target)\n{\n    // find the valid pairs (for each vertex)\n    size_t vertex_number = vert_capacity();\n    auto collect_all_ops = std::vector<std::pair<std::string, Tuple>>();\n    for (auto& loc : get_edges()) collect_all_ops.emplace_back(\"edge_collapse\", loc);\n\n    auto executor = wmtk::ExecutePass<EdgeOperations2d, wmtk::ExecutionPolicy::kSeq>();\n    executor.renew_neighbor_tuples = [](auto& m, auto op, auto& tris) {\n        auto edges = m.new_edges_after(tris);\n        auto optup = std::vector<std::pair<std::string, TriMesh::Tuple>>();\n        // for (auto& e : edges) optup.emplace_back(op, e);\n        return optup;\n    };\n\n    executor.priority = [this](auto& m, auto _, auto& e) {\n        //     return -(m.vertex_attrs.pos[e.vid(*this)] -\n        //     m.vertex_attrs.pos[e.switch_vertex(m).vid(*this)])\n        //                 .norm();\n        // };\n\n        // wmtk::logger().info(\n        //     \"{} \\n{}\\n {}\",\n        //     vertex_attrs->m_attributes[e.vid(*this)].pos,\n        //     vertex_attrs->m_attributes[e.switch_vertex(m).vid(*this)].pos,\n        //     compute_cost_for_e(e));\n        return -compute_cost_for_e(e);\n    };\n    executor.is_weight_up_to_date = [&collect_all_ops, this](auto& m, auto& ele) {\n        auto& [val, op, e] = ele;\n\n        if (val > 0) return false; // priority is negated.\n        double pri = -compute_cost_for_e(e);\n        if ((val - pri) < 1e-5) {\n            wmtk::logger().info(\"the priority is different\");\n            return false;\n        }\n        for (auto edge : get_edges()) {\n            if (pri < -compute_cost_for_e(edge)) {\n                wmtk::logger().info(\"!!!! should not happen !!!!\");\n                return false;\n            }\n        }\n\n        return true;\n    };\n    executor.stopping_criterion_checking_frequency = 1000;\n    executor.stopping_criterion = [&target](auto& m) {\n        if (m.get_vertices().size() < target) return true;\n        return false;\n    };\n\n    executor(*this, collect_all_ops);\n    return true;\n}\n", "meta": {"hexsha": "fcb194e7f7a6ca2ce55d8ce17230dce5c53cf3e4", "size": 4466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "attic/EdgeOperations2d/QEC.cpp", "max_stars_repo_name": "wildmeshing/wildmeshing-toolkit", "max_stars_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T08:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:19:41.000Z", "max_issues_repo_path": "attic/EdgeOperations2d/QEC.cpp", "max_issues_repo_name": "wildmeshing/wildmeshing-toolkit", "max_issues_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 86.0, "max_issues_repo_issues_event_min_datetime": "2021-12-03T01:46:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T19:33:17.000Z", "max_forks_repo_path": "attic/EdgeOperations2d/QEC.cpp", "max_forks_repo_name": "wildmeshing/wildmeshing-toolkit", "max_forks_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-26T08:29:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T22:10:42.000Z", "avg_line_length": 33.328358209, "max_line_length": 109, "alphanum_fraction": 0.5893416928, "num_tokens": 1302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5223483870189196}}
{"text": "#pragma once\r\n\r\n#include <Eigen/Dense>\r\n\r\nnamespace AQSystemSolver {\r\n    template<typename MatrixType=Eigen::MatrixXd, typename VectorType=Eigen::VectorXd, typename RowVectorType=Eigen::RowVectorXd>\r\n    class Tableau;\r\n\r\n    template<typename T>\r\n    using TableauType=T;\r\n    //concept TableauType = SM_utils::is_base_of_template<T, Tableau>::value;   \r\n\r\n    template<typename MatrixType, typename VectorType, typename RowVectorType>\r\n    class Tableau{\r\n    private:\r\n        MatrixType coefficients;\r\n        VectorType constants;\r\n    public:\r\n        void assignRowFromTableau(Eigen::Index lhsRowIndex, const auto& rhsTableau, Eigen::Index rhsRowIndex) {\r\n            coefficients.row(lhsRowIndex)=rhsTableau.getCoefficients().row(rhsRowIndex);\r\n            constants.coeffRef(lhsRowIndex)=rhsTableau.getConstants().coeff(rhsRowIndex);\r\n        }\r\n        void assignRow(Eigen::Index lhsRowIndex, const auto& row, typename std::decay_t<decltype(row)>::Scalar constant) {\r\n            coefficients.row(lhsRowIndex)=row;\r\n            constants.coeffRef(lhsRowIndex)=constant;\r\n        }         \r\n        [[nodiscard]] const auto& getCoefficients() const {\r\n            return coefficients;\r\n        }\r\n        [[nodiscard]] const auto& getCoefficient(Eigen::Index row, Eigen::Index column) const {\r\n            return coefficients.coeff(row, column);\r\n        }\r\n        [[nodiscard]] const auto& getConstants() const {\r\n            return constants;\r\n        }\r\n        [[nodiscard]] const auto& getConstant(Eigen::Index i) const {\r\n            return constants.coeff(i);\r\n        }\r\n        [[nodiscard]] auto rows() const {\r\n            return constants.rows();\r\n        }\r\n        [[nodiscard]] auto cols() const {\r\n            return coefficients.cols();\r\n        }\r\n        template<int implicitPower>\r\n        void groupTerm(Eigen::Index row, Eigen::Index column){\r\n            auto& power=coefficients.coeffRef(row, column);\r\n            if(power==implicitPower-1){\r\n                return; //it won't do anything, so we skip it.\r\n            }\r\n            if(power==implicitPower){\r\n                throw std::runtime_error(\"Power is the same as the implicit power, and we are trying to eliminate a replacement. This is probably a Gibbs Rule violation.\");\r\n            }\r\n            const auto factor=1/(implicitPower-power);\r\n            coefficients.row(row)*=factor;\r\n            constants.coeffRef(row)=pow(constants.coeff(row), factor);\r\n            power=0;\r\n        }\r\n\r\n        [[nodiscard]] VectorType evalTerms(const RowVectorType& x) const {\r\n            MatrixType terms(coefficients.rows(),coefficients.cols());\r\n            for(Eigen::Index i=0; i<coefficients.rows(); ++i){\r\n                terms.row(i)=pow(x.array(), coefficients.row(i).array());\r\n            }\r\n            return terms.rowwise().prod().array()*constants.array();\r\n        }\r\n        [[nodiscard]] MatrixType evalAddends(VectorType speciesConcentrations) const {\r\n            return coefficients.array().colwise()*speciesConcentrations.array();\r\n        }\r\n        [[nodiscard]] RowVectorType eval(const RowVectorType& x) const {\r\n            return evalAddends(evalTerms(x)).colwise().sum();\r\n        }\r\n        [[nodiscard]] RowVectorType eval(const VectorType& speciesConcentrations) const {\r\n            return evalAddends(speciesConcentrations).colwise().sum();\r\n        }\r\n        [[nodiscard]] RowVectorType eval(const MatrixType& addends) const {\r\n            return addends.colwise().sum();\r\n        }\r\n        void resize(Eigen::Index rows, Eigen::Index cols) {\r\n            coefficients.resize(rows, cols);\r\n            constants.resize(rows);\r\n        }\r\n        void conservativeResize(Eigen::Index rows, Eigen::Index cols) {\r\n            coefficients.conservativeResize(rows, cols);\r\n            constants.conservativeResize(rows);\r\n        }\r\n\r\n        template<bool eliminate_column=false>\r\n        void substituteRowAndCol(const /*TableauType*/ auto& replacementTableau, Eigen::Index row, const /*TableauType*/ auto& originalTableau, Eigen::Index col){\r\n            coefficients+=originalTableau.getCoefficients().col(col)*replacementTableau.getCoefficients().row(row);\r\n            if constexpr(eliminate_column){\r\n                coefficients.col(col)-=originalTableau.getCoefficients().col(col);\r\n            }\r\n            constants.array()*=pow(replacementTableau.getConstants().coeff(row), originalTableau.getCoefficients().col(col).array());\r\n        }\r\n        [[nodiscard]] auto reducedCopy(const auto& v1, const auto& v2) const {\r\n            return Tableau{coefficients(v1, v2), constants(v1)};\r\n        }\r\n        [[nodiscard]] auto reducedCopy(const decltype(Eigen::all)& v1, const auto& v2) const {\r\n            return Tableau{coefficients(v1, v2), constants};\r\n        }\r\n        [[nodiscard]] bool operator==(const auto& rhs) const {\r\n            return coefficients==rhs.getCoefficients() && constants==rhs.getConstants();\r\n        }\r\n        Tableau(MatrixType coefficients_, VectorType constants_) : coefficients{std::move(coefficients_)}, constants{std::move(constants_)} {}\r\n        Tableau() = default;\r\n    };\r\n    template<typename MatrixType=Eigen::MatrixXd, typename VectorType=Eigen::VectorXd, typename RowVectorType=Eigen::RowVectorXd>\r\n    class TableauWithTotals : private Tableau<MatrixType, VectorType, RowVectorType>{\r\n    private:\r\n        using parent=Tableau<MatrixType, VectorType, RowVectorType>;\r\n        RowVectorType totals;\r\n    public:\r\n        [[nodiscard]] const auto& getTotals(){\r\n            return totals;\r\n        }\r\n        [[nodiscard]] const auto& getTotal(Eigen::Index col){\r\n            return totals.coeff(col);\r\n        }\r\n        using parent::assignRowFromTableau;\r\n        using parent::assignRow;\r\n        using parent::getCoefficients;\r\n        using parent::getCoefficient;\r\n        using parent::getConstants;\r\n        using parent::getConstant;\r\n        using parent::rows;\r\n        using parent::cols;\r\n        using parent::evalTerms;\r\n        using parent::evalAddends;\r\n\r\n        [[nodiscard]] auto reducedCopy(const auto& v1, const auto& v2) const {\r\n            return TableauWithTotals{parent::reducedCopy(v1, v2), totals(v2)};\r\n        }\r\n        [[nodiscard]] auto reducedCopy(const auto& v1, const decltype(Eigen::all)& v2) const {\r\n            return TableauWithTotals{parent::reducedCopy(v1, v2), totals};\r\n        }\r\n        [[nodiscard]] auto reducedCopy(const decltype(Eigen::all)& v1, const auto& v2) const {\r\n            return TableauWithTotals{parent::reducedCopy(v1, v2), totals(v2)};\r\n        }\r\n        template<bool eliminate_column>\r\n        void substituteRowAndCol(const /*TableauType*/ auto& replacementTableau, Eigen::Index row, const TableauWithTotals& originalTableau, Eigen::Index col) {\r\n            static_assert(!eliminate_column);\r\n            parent::template substituteRowAndCol<false>(replacementTableau, row, originalTableau, col);\r\n            totals+=originalTableau.totals.coeff(col)*replacementTableau.getCoefficients().row(row);\r\n        }\r\n        [[nodiscard]] RowVectorType eval(const auto& x) const {\r\n            return parent::eval(x)-totals;\r\n        }\r\n        [[nodiscard]] RowVectorType evalWithoutTotal(const auto& x) const {\r\n            return parent::eval(x);\r\n        }\r\n        void resize(Eigen::Index rows, Eigen::Index cols){\r\n            parent::resize(rows, cols);\r\n            totals.resize(cols); \r\n        }\r\n        void conservativeResize(Eigen::Index rows, Eigen::Index cols){\r\n            parent::conservativeResize(rows, cols);\r\n            totals.conservativeResize(cols); \r\n        }\r\n        [[nodiscard]] bool operator==(const TableauWithTotals& rhs) const {\r\n            return parent::operator==(rhs) && totals==rhs.totals;\r\n        }\r\n        TableauWithTotals(parent tableau_, RowVectorType totals_) : parent{std::move(tableau_)}, totals{std::move(totals_)} {}\r\n        TableauWithTotals() = default;\r\n    };\r\n} // namespace AQSystemSolver", "meta": {"hexsha": "55306f020487a6ac586d210e87b84d6777503d19", "size": 8005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Tableau.hpp", "max_stars_repo_name": "FreeQL/AQSystemSolver", "max_stars_repo_head_hexsha": "3d98837d7cac9c5c0da57ed896a3145ed0c49a97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tableau.hpp", "max_issues_repo_name": "FreeQL/AQSystemSolver", "max_issues_repo_head_hexsha": "3d98837d7cac9c5c0da57ed896a3145ed0c49a97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tableau.hpp", "max_forks_repo_name": "FreeQL/AQSystemSolver", "max_forks_repo_head_hexsha": "3d98837d7cac9c5c0da57ed896a3145ed0c49a97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.2228915663, "max_line_length": 173, "alphanum_fraction": 0.6192379763, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.769080247656264, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5223429321531414}}
{"text": "#include <gtest/gtest.h>\n\n#include \"scheme/numeric/util.hh\"\n#include \"scheme/io/dump_pdb_atom.hh\"\n\n#include \"scheme/numeric/geom_4d.hh\"\n\n#include <Eigen/Dense>\n#include <random>\n\n#include \"scheme/util/Timer.hh\"\n\n#include <fstream>\n\nnamespace scheme { namespace nest { namespace pmap {\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl;\n\nTEST( geom_4d, quat_half_cell ){\n\tASSERT_EQ( -0.0, 0.0 );\n\tASSERT_EQ( numeric::to_half_cell(Eigen::Quaterniond( -1, 1, 1, 1 ) ).w(), 1.0 );\n\tASSERT_EQ( numeric::to_half_cell(Eigen::Quaterniond(  0,-1, 1, 1 ) ).x(), 1.0 );\n\tASSERT_EQ( numeric::to_half_cell(Eigen::Quaterniond(  0, 0,-1, 1 ) ).y(), 1.0 );\n\tASSERT_EQ( numeric::to_half_cell(Eigen::Quaterniond(  0, 0, 0,-1 ) ).z(), 1.0 );\n}\n\n\n\nTEST( geom_4d , tetracontoctachoron_cell_lookup )\n{\n\ttypedef double Float;\n\ttypedef uint64_t Index;\n\ttypedef Eigen::Matrix<Float,4,1> V4;\n\n\tMap<Matrix<Float,48,4,RowMajor>const> t24( numeric::get_raw_48cell<Float>() );\n\t// ASSERT_EQ( V4(0,0,0,-1), t24.row(7).transpose() );\n\t// for(int i = 0; i < 48; ++i) ASSERT_FLOAT_EQ( t24.row(i).norm(), 1.0 );\n\n\t// std::ofstream out(\"test.pdb\");\n\t// for(int i = 0; i < 48; ++i){\n\t// \tif( t24.row(i).block(0,0,1,3).norm() < 0.9 )\n\t// \t\tio::dump_pdb_atom(out,i,10*t24.row(i));\n\t// }\n\t// out.close();\n\n\tstd::mt19937 mt((unsigned int)time(0));\n\tstd::normal_distribution<> rnorm;\n\tstd::uniform_real_distribution<> runif;\n\n\tint NITER = 200*1000;\n\t#ifdef SCHEME_BENCHMARK\n\t\tNITER *= 50;\n\t#endif\n\n\tstd::vector<V4> samp(NITER);\n\tstd::vector<Index> cell(NITER),cell2(NITER);\n\n\tfor(int i = 0; i < NITER; ++i){\n\t\tV4 quat(rnorm(mt),rnorm(mt),rnorm(mt),rnorm(mt));\n\t\tsamp[i] = quat.normalized();\n\t}\n\t\t// V4 const quat_pos = quat.cwiseAbs();\n\n\tutil::Timer<> naive;\n\tfor(int i = 0; i < NITER; ++i){\n\t\t// (t24*samp[i]).cwiseAbs().maxCoeff(&cell[i]);\n\t\t(t24*samp[i]).maxCoeff(&cell[i]);\t\t\n\t}\n\tcout << \"bt24 naive rate:  \" << (Float)NITER / naive.elapsed_nano() << endl;\n\n\tutil::Timer<> clever;\n\tfor(int i = 0; i < NITER; ++i){\n\t\tnumeric::get_cell_48cell( samp[i], cell2[i] );\n\t\t// this is slower !?!\n\t\t// Float mx = std::max(std::max(hyperface_dist,corner_dist),edge_dist);\n\t\t// cell2[i] = hyperface_dist==mx ? facecell : (corner_dist==mx ? cornercell+8 : edgecell+24);\n\n\n\t}\n\tcout << \"bt24 clever rate: \" << (double)NITER / clever.elapsed_nano() << endl;\n\n\tfor(int i = 0; i < NITER; ++i){\n\t\tif( cell[i] != cell2[i] ){\n\t\t\tASSERT_FLOAT_EQ(\n\t\t\t     t24.row(cell [i]).dot(samp[i]) ,\n\t\t\t     t24.row(cell2[i]).dot(samp[i]) );\n\t\t} else { \n\t\t\tASSERT_EQ( cell[i], cell2[i] );\n\t\t}\n\t}\n\n}\n\nTEST( geom_4d , tetracontoctachoron_half_cell_lookup )\n{\n\ttypedef double Float;\n\ttypedef uint64_t Index;\n\ttypedef Eigen::Matrix<Float,4,1> V4;\n\n\tMap<Matrix<Float,24,4,RowMajor>const> t24h( numeric::get_raw_48cell_half<Float>() );\n\n\tfor(int i = 0; i < 24; ++i){\n\t\tsize_t cell;\n\t\tV4 tmp = t24h.row(i);\n\t\tnumeric::get_cell_48cell_half( tmp, cell );\n\t\tASSERT_EQ( cell, i );\n\t\t// if( i > 11 ) continue;\n\t\ttmp = -tmp;\n\t\tnumeric::get_cell_48cell_half( tmp, cell );\n\t\tASSERT_EQ( cell, i );\n\t}\n\n\t// ASSERT_EQ( V4(0,0,0,-1), t24h.row(7).transpose() );\n\t// for(int i = 0; i < 48; ++i) ASSERT_FLOAT_EQ( t24h.row(i).norm(), 1.0 );\n\n\t// std::ofstream out(\"test.pdb\");\n\t// for(int i = 0; i < 24; ++i){\n\t// \tif( t24h.row(i).block(0,0,1,3).norm() < 0.9 )\n\t// \t\tio::dump_pdb_atom(out,i,10*t24h.row(i));\n\t// }\n\t// out.close();\n\n\tstd::mt19937 mt((unsigned int)time(0));\n\tstd::normal_distribution<> rnorm;\n\tstd::uniform_real_distribution<> runif;\n\n\tint NITER = 200*1000;\n\t#ifdef SCHEME_BENCHMARK\n\t\tNITER *= 50;\n\t#endif\n\n\tstd::vector<V4> samp(NITER);\n\tstd::vector<Index> cell(NITER),cell2(NITER);\n\n\tfor(int i = 0; i < NITER; ++i){\n\t\tV4 quat(rnorm(mt),rnorm(mt),rnorm(mt),rnorm(mt));\n\t\tsamp[i] = quat.normalized();\n\t}\n\t\t// V4 const quat_pos = quat.cwiseAbs();\n\n\tutil::Timer<> naive;\n\tfor(int i = 0; i < NITER; ++i){\n\t\t// (t24h*samp[i]).cwiseAbs().maxCoeff(&cell[i]);\n\t\t(t24h*samp[i]).cwiseAbs().maxCoeff(&cell[i]);\t\t\n\t}\n\tcout << \"hbt24 naive rate:  \" << (Float)NITER / naive.elapsed_nano() << endl;\n\n\tutil::Timer<> clever;\n\tfor(int i = 0; i < NITER; ++i){\n\t\tnumeric::get_cell_48cell_half( samp[i], cell2[i] );\n\t}\n\tcout << \"hbt24 clever rate: \" << (double)NITER / clever.elapsed_nano() << endl;\n\n\tfor(int i = 0; i < NITER; ++i){\n\t\t// if( cell[i] > 11 ) continue;\n\t\t// if( cell[i] < 12 ) ASSERT_EQ( cell[i], cell2[i] );\n\t\tif( cell[i] != cell2[i] ){\n\t\t\tASSERT_FLOAT_EQ(\n\t\t\t     t24h.row(cell [i]).dot(samp[i]) ,\n\t\t\t     t24h.row(cell2[i]).dot(samp[i]) );\n\t\t} else { \n\t\t\tASSERT_EQ( cell[i], cell2[i] );\n\t\t}\n\t}\n\n}\n\n}}}\n", "meta": {"hexsha": "b2114caa16bf7b5c7e112c2d32a50c3bbd8bac97", "size": 4526, "ext": "cc", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/numeric/geom_4d.gtest.cc", "max_stars_repo_name": "YaoYinYing/rifdock", "max_stars_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T01:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:16:08.000Z", "max_issues_repo_path": "schemelib/scheme/numeric/geom_4d.gtest.cc", "max_issues_repo_name": "YaoYinYing/rifdock", "max_issues_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-30T17:45:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:02:44.000Z", "max_forks_repo_path": "schemelib/scheme/numeric/geom_4d.gtest.cc", "max_forks_repo_name": "YaoYinYing/rifdock", "max_forks_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T01:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:56:17.000Z", "avg_line_length": 26.4678362573, "max_line_length": 95, "alphanum_fraction": 0.6137870084, "num_tokens": 1627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5223429199694355}}
{"text": "// (C) Copyright Jeremy Siek 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// Sample output:\n//  mask =      101010101010\n//  Enter a 12-bit bitset in binary: 100110101101\n//  x =        100110101101\n//  As ulong:  2477\n//  And with mask: 100010101000\n//  Or with mask:  101110101111\n\n\n#include <iostream>\n#include <boost/dynamic_bitset.hpp>\n\nint main(int, char*[]) {\n  const boost::dynamic_bitset<> mask(12, 2730ul); \n  std::cout << \"mask = \" << mask << std::endl;\n\n  boost::dynamic_bitset<> x(12);\n  std::cout << \"x.size()=\" << x.size() << std::endl;\n\n  std::cout << \"Enter a 12-bit bitset in binary: \" << std::flush;\n  if (std::cin >> x) {\n    std::cout << \"input number:     \" << x << std::endl;\n    std::cout << \"As unsigned long: \" << x.to_ulong() << std::endl;\n    std::cout << \"And with mask:    \" << (x & mask) << std::endl;\n    std::cout << \"Or with mask:     \" << (x | mask) << std::endl;\n    std::cout << \"Shifted left:     \" << (x << 1) << std::endl;\n    std::cout << \"Shifted right:    \" << (x >> 1) << std::endl;\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "c667e3c08b4da91f75b59a20fb03cfd305be2e86", "size": 1176, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/boost_1_33_1/libs/dynamic_bitset/example/example3.cpp", "max_stars_repo_name": "spxuw/RFIM", "max_stars_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T13:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T02:55:10.000Z", "max_issues_repo_path": "Source/boost_1_33_1/libs/dynamic_bitset/example/example3.cpp", "max_issues_repo_name": "spxuw/RFIM", "max_issues_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_issues_repo_licenses": ["MIT"], "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/boost_1_33_1/libs/dynamic_bitset/example/example3.cpp", "max_forks_repo_name": "spxuw/RFIM", "max_forks_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T14:34:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T08:25:58.000Z", "avg_line_length": 32.6666666667, "max_line_length": 67, "alphanum_fraction": 0.5799319728, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5223429149752}}
{"text": "#include <iostream>\n#include <vector>\n#include <list>\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n#include \"hmm.h\"\n\nusing namespace std;\nusing namespace rtHMM;\n\n#include \"hmm_example/hmm_matrices.h\"\n\n/* TODO:\n *\n * The following things still need test cases:\n *\n *   - if the predecessors are created correctly\n *   - if resetting a transition works correctly\n *   - if tied observation distributions are created correctly\n *\n */\n\n\nTEST(hmm_constructor_tests, test_num_states)\n{\n    const size_t num_states = 3;\n    hmm my_hmm(num_states);\n    ASSERT_EQ(my_hmm.num_states(), num_states);\n}\n\ntemplate<typename T, typename HMM_T>\nvoid check_prior(const T& prior, const HMM_T& my_hmm)\n{\n    size_t i = 0;\n    for (auto p : prior) {\n        ASSERT_DOUBLE_EQ(my_hmm.prior(i), p);\n        ++i;\n    }\n}\n\nTEST(hmm_constructor_tests, test_prior_vector)\n{\n    const vector<double> prior{PRIOR};\n\n    hmm my_hmm(prior);\n    ASSERT_EQ(my_hmm.num_states(), prior.size());\n    check_prior(prior, my_hmm);\n}\n\nTEST(hmm_constructor_tests, test_prior_list)\n{\n    const list<double> prior{PRIOR};\n\n    hmm my_hmm(prior);\n    ASSERT_EQ(my_hmm.num_states(), prior.size());\n    check_prior(prior, my_hmm);\n}\n\nclass hmm_test : public ::testing::Test {\n    protected:\n        virtual void SetUp() {\n\n            dense_vector prior(STATE_COUNT);\n            prior << PRIOR;\n            dense_matrix trans(STATE_COUNT, STATE_COUNT);\n            trans << TRANSITION;\n            dense_matrix obs(STATE_COUNT, ALPHABET_SIZE);\n            obs << OBSERVATION;\n\n            simple_hmm = new hmm(prior, trans, obs);\n        }\n\n        virtual void TearDown() {\n            delete simple_hmm;\n        }\n\n        hmm* simple_hmm;\n};\n\n\nTEST_F(hmm_test, prior_probability_test)\n{\n    double correct_prior_probs[] = {PRIOR};\n\n    for (size_t i = 0; i < simple_hmm->num_states(); ++i) {\n        ASSERT_DOUBLE_EQ(correct_prior_probs[i], simple_hmm->prior(i));\n    }\n}\n\n\nTEST_F(hmm_test, successors_test)\n{\n    double correct_trans_probs[] = {TRANSITION};\n\n    for (size_t i = 0; i < simple_hmm->num_states(); ++i) {\n        size_t k = 0;\n        auto& successors = simple_hmm->successors(i);\n\n        for (size_t j = 0; j < simple_hmm->num_states(); ++j) {\n            double correct_p = correct_trans_probs[i * STATE_COUNT + j];\n            if (correct_p > 0.0) {\n                auto& succ = successors[k];\n                ASSERT_EQ(succ.state_id, j);\n                ASSERT_DOUBLE_EQ(succ.probability, correct_p); ++k;\n            }\n        }\n    }\n}\n\n\nTEST_F(hmm_test, observation_probability_test)\n{\n    double correct_observation_probs[] = {OBSERVATION};\n    size_t obs[] = ALPHABET;\n\n    for (size_t state_id = 0; state_id < simple_hmm->num_states(); ++state_id) {\n        for (size_t obs_id = 0; obs_id < ALPHABET_SIZE; ++obs_id) {\n            auto& dist = simple_hmm->observation_distribution(state_id);\n            double correct_p = correct_observation_probs[state_id * ALPHABET_SIZE + obs_id];\n            ASSERT_DOUBLE_EQ(correct_p, dist->probability(obs[obs_id]));\n        }\n    }\n}\n", "meta": {"hexsha": "412385ffb9bab0041c02670313f7e8b6dea3bfa1", "size": 3062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/hmm_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/hmm_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/hmm_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": 24.6935483871, "max_line_length": 92, "alphanum_fraction": 0.6306335728, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5223429121761994}}
{"text": "#ifndef MOCHIMOCHI_NHERD_HPP_\n#define MOCHIMOCHI_NHERD_HPP_\n\n#include <Eigen/Dense>\n#include <boost/serialization/serialization.hpp>\n#include <boost/serialization/nvp.hpp>\n#include <boost/serialization/split_member.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <fstream>\n#include <functional>\n#include \"../../functions/enumerate.hpp\"\n\nclass NHERD {\nprivate :\n  const std::size_t kDim;\n  const double kC;\n  const int kDiagonal;\n\nprivate :\n  Eigen::VectorXd _covariances;\n  Eigen::VectorXd _means;\n\nprivate :\n  std::function<double(double, double, double)> _compute_covariance;\n\npublic :\n  NHERD(const std::size_t dim, const double C, const int diagonal = 0)\n    : kDim(dim),\n      kC(C),\n      kDiagonal(diagonal),\n      _covariances(Eigen::VectorXd::Ones(kDim)),\n      _means(Eigen::VectorXd::Zero(kDim)) {\n\n    static_assert(std::numeric_limits<decltype(dim)>::max() > 0, \"Dimension Error. (Dimension > 0)\");\n    static_assert(std::numeric_limits<decltype(C)>::max() > 0, \"Hyper Parameter Error. (C > 0)\");\n\n    // int diagonal : switching the diagonal covariance\n    // 0 : Full covariance\n    // 1 : Exact covariance\n    // 2 : Project covariance\n    // 3 : Drop covariance\n    switch(kDiagonal) {\n    case 0 :\n      _compute_covariance = [=](const auto covariance, const auto confidence, const auto value) {\n        const auto v = covariance * value;\n        return covariance - (v * v * (kC * kC * confidence + 2 * kC) / std::pow((1.0 + kC * confidence), 2));\n      };\n      break;\n    case 1 :\n      _compute_covariance = [=](const auto covariance, const auto confidence, const auto value) {\n        return covariance / std::pow(1.0 + kC * value * value * covariance, 2);\n      };\n      break;\n    case 2 :\n      _compute_covariance = [=](const auto covariance, const auto confidence, const auto value) {\n        return 1.0 / ((1.0 / covariance) + (2 * kC + kC * kC * confidence) * value * value);\n      };\n      break;\n    case 3 :\n      _compute_covariance = [=](const auto covariance, const auto confidence, const auto value) {\n        const auto v = (std::pow(covariance * value, 2) * (kC * kC * confidence + 2 * kC) / std::pow(1.0 + kC * confidence, 2));\n        return covariance - v;\n      };\n      break;\n    default:\n      std::runtime_error(\"Error in switching the diagonal covariance.\");\n    }\n\n  }\n\n  virtual ~NHERD() { }\n\nprivate :\n\n  double suffer_loss(const double margin, const int label) const {\n    return margin * label;\n  }\n\n  double compute_margin(const Eigen::VectorXd& x) const {\n    return _means.dot(x);\n  }\n\n  double compute_confidence(const Eigen::VectorXd& feature) const {\n    auto confidence = 0.0;\n    functions::enumerate(feature.data(), feature.data() + feature.size(), 0,\n                         [&](const int index, const double value) {\n                           confidence += _covariances[index] * value * value;\n                         });\n    return confidence;\n  }\n\npublic :\n\n  bool update(const Eigen::VectorXd& feature, const int label) {\n    const auto margin = compute_margin(feature);\n\n    if (suffer_loss(margin, label) >= 1.0) { return false; }\n\n    const auto confidence = compute_confidence(feature);\n    const auto alpha = std::max(0.0, 1.0 - label * margin) / (confidence + 1 / kC) ;\n\n    functions::enumerate(feature.data(), feature.data() + feature.size(), 0,\n                       [&](const std::size_t index, const double value) {\n                         _means[index] += alpha * label * _covariances[index] * value;\n                         _covariances[index] = _compute_covariance(_covariances[index], confidence, value);\n                       });\n    return true;\n  }\n\n  int predict(const Eigen::VectorXd& x) const {\n    return compute_margin(x) > 0.0 ? 1 : -1;\n  }\n\n  Eigen::VectorXd get_means(void) const {\n    return _means;\n  }\n\n  void save(const std::string& filename) {\n    std::ofstream ofs(filename);\n    assert(ofs);\n    boost::archive::text_oarchive oa(ofs);\n    oa << *this;\n    ofs.close();\n  }\n\n  void load(const std::string& filename) {\n    std::ifstream ifs(filename);\n    assert(ifs);\n    boost::archive::text_iarchive ia(ifs);\n    ia >> *this;\n    ifs.close();\n  }\n\nprivate :\n  friend class boost::serialization::access;\n  BOOST_SERIALIZATION_SPLIT_MEMBER();\n  template <class Archive>\n  void save(Archive& ar, const unsigned int version) const {\n    std::vector<double> covariances_vector(_covariances.data(), _covariances.data() + _covariances.size());\n    std::vector<double> means_vector(_means.data(), _means.data() + _means.size());\n    ar & boost::serialization::make_nvp(\"covariances\", covariances_vector);\n    ar & boost::serialization::make_nvp(\"means\", means_vector);\n    ar & boost::serialization::make_nvp(\"dimension\", const_cast<std::size_t&>(kDim));\n    ar & boost::serialization::make_nvp(\"C\", const_cast<double&>(kC));\n  }\n\n  template <class Archive>\n  void load(Archive& ar, const unsigned int version) {\n    std::vector<double> covariances_vector;\n    std::vector<double> means_vector;\n    ar & boost::serialization::make_nvp(\"covariances\", covariances_vector);\n    ar & boost::serialization::make_nvp(\"means\", means_vector);\n    ar & boost::serialization::make_nvp(\"dimension\", const_cast<std::size_t&>(kDim));\n    ar & boost::serialization::make_nvp(\"C\", const_cast<double&>(kC));\n    _covariances = Eigen::Map<Eigen::VectorXd>(&covariances_vector[0], covariances_vector.size());\n    _means = Eigen::Map<Eigen::VectorXd>(&means_vector[0], means_vector.size());\n  }\n};\n\n#endif //MOCHIMOCHI_NHERD_HPP_\n", "meta": {"hexsha": "d2a1bc13e0329e611ce36fff958920d0cff64301", "size": 5605, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mochimochi/classifier/binary/nherd.hpp", "max_stars_repo_name": "olanleed/MochiMochi", "max_stars_repo_head_hexsha": "830d361fa352f6ac336ec97a80588018c8164916", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-05-17T04:33:04.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-02T11:18:58.000Z", "max_issues_repo_path": "mochimochi/classifier/binary/nherd.hpp", "max_issues_repo_name": "olanleed/MochiMochi", "max_issues_repo_head_hexsha": "830d361fa352f6ac336ec97a80588018c8164916", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-05-24T10:14:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-23T14:40:08.000Z", "max_forks_repo_path": "mochimochi/classifier/binary/nherd.hpp", "max_forks_repo_name": "olanleed/MochiMochi", "max_forks_repo_head_hexsha": "830d361fa352f6ac336ec97a80588018c8164916", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-30T13:10:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-30T13:10:29.000Z", "avg_line_length": 34.3865030675, "max_line_length": 128, "alphanum_fraction": 0.647279215, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6370308082623216, "lm_q1q2_score": 0.522297308858928}}
{"text": "//  justanhduc\n// Oct 2020\n\n#include <Eigen/Core>\n#include <cmath>\n#include <ctime>\n\n#include \"TSDFVolume.hpp\"\n#include \"GPURaycaster.hpp\"\n#include \"opencv2/opencv.hpp\"\n\n#define MAX_PATH 260  // for linux\n\n\nint main() {\n    using namespace Eigen;\n\n    const int dim_x = 101, dim_y = 139, dim_z = 106;\n    const int n_max_frame = 30;\n    const int width = 1024;\n    const int height = 1024;\n    const int n_samples = 3;  // for anti-aliasing. 1 == no anti-aliasing\n\n    GPURaycaster r{width, height};\n    Vector3f light_source{0, 3, 3};\n    auto eye = Vector3f{0.5, 0, 2};  // view point\n    Camera cam((float) width / 2, (float) height / 2, (float) (width - 1) / 2,\n             (float) (height - 1) / 2);\n    cam.move_to(eye);\n    cam.look_at(0.5, 0.5, 0.5);\n\n    TSDFVolume volume(dim_x, dim_y, dim_z, dim_x * .01, dim_y * .01, dim_z * .01);\n    volume.set_truncation_distance(.1);  // set low threshold as the step size may be large\n\n    char stmp[MAX_PATH];\n    float ftemp[8];\n    auto total_time = 0.;\n    for (int i = 0; i < n_max_frame; i++) {\n        // reading tsdf files\n        auto *tsdf = new float[dim_x * dim_y * dim_z * n_max_frame];\n        sprintf(stmp, \"../volume/_tsdf_multi_%03d.bin\", i);  // for linux\n        FILE *fp;\n        fp = fopen(stmp, \"rb\");  // for linux\n        if (fp == nullptr) {\n            printf(\"Cannot read file %s\\n\", stmp);\n            exit(-1);\n        }\n        fread(ftemp, sizeof(float), 8, fp);\n        fread(tsdf, dim_x * dim_y * dim_z, sizeof(float), fp);\n        fclose(fp);\n\n        // start\n        auto start = std::time(nullptr);\n        // set tsdf to volume\n        volume.set_distance_data(tsdf);\n\n        // define containers for normals and vertices\n        Eigen::Matrix<float, 3, Eigen::Dynamic> vertices;\n        Eigen::Matrix<float, 3, Eigen::Dynamic> normals;\n\n        // raycast + shading + rendering\n        auto *scene = new uint8_t[height * width];\n        r.render_with_shading(volume, cam, vertices, normals, light_source, n_samples, scene);\n\n        // done\n        total_time += std::difftime(std::time(nullptr), start);\n\n        // display\n        cv::Mat frame(height, width, 0, scene);\n        cv::imshow(\"Frame\", frame);\n        auto c = (char) cv::waitKey(1);\n        if (c == 27)\n            break;\n    }\n\n    std::cout << \"FPS: \" << 1 / (total_time / n_max_frame) << std::endl;\n    return 0;\n}\n\n", "meta": {"hexsha": "8badf743a3e882a7a152764bd0ccf8892ae7e133", "size": 2377, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main_gpu.cpp", "max_stars_repo_name": "justanhduc/ray-casting", "max_stars_repo_head_hexsha": "25ea97f3ff10d2b0cb3c9e935f1adb9201e42908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T22:38:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T22:38:06.000Z", "max_issues_repo_path": "main_gpu.cpp", "max_issues_repo_name": "justanhduc/ray-casting", "max_issues_repo_head_hexsha": "25ea97f3ff10d2b0cb3c9e935f1adb9201e42908", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-12T02:19:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T02:46:41.000Z", "max_forks_repo_path": "main_gpu.cpp", "max_forks_repo_name": "justanhduc/ray-casting", "max_forks_repo_head_hexsha": "25ea97f3ff10d2b0cb3c9e935f1adb9201e42908", "max_forks_repo_licenses": ["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.7125, "max_line_length": 94, "alphanum_fraction": 0.5750946571, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5222973032519649}}
{"text": "#include \"quadrotor_simulator/Quadrotor.h\"\n#include <Eigen/Geometry>\n\nint main(int argc, char **argv)\n{\n  double dt = 0.001;\n  QuadrotorSimulator::Quadrotor quad;\n  QuadrotorSimulator::Quadrotor::State state = quad.getState();\n\n  const double m = quad.getMass();\n  const double g = quad.getGravity();\n  const double kf = quad.getPropellerThrustCoefficient();\n\n  const double hover_rpm = std::sqrt(m*g/(4*kf));\n  std::cerr << \"hover rpm: \" << hover_rpm << std::endl;\n  state.motor_rpm = Eigen::Array4d(hover_rpm, hover_rpm, hover_rpm, hover_rpm);\n  quad.setState(state);\n\n  double thrust = m*g;\n  double rpm = std::sqrt(thrust/(4*kf));\n  quad.setInput(rpm, rpm, rpm, rpm);\n\n  struct timespec ts_start, ts1, ts2, ts_sleep, ts_end;\n  clock_gettime(CLOCK_MONOTONIC, &ts1);\n  int64_t time_taken = 0;\n\n  double KP = 8.0;\n  double KD = 2.5;\n  const double z_des = 0.5;\n  clock_gettime(CLOCK_MONOTONIC, &ts_start);\n  for(int i = 0; i < 6000; i++)\n  {\n    state = quad.getState();\n    thrust = m*g + KP*(z_des - state.x(2)) + KD*(0 - state.v(2));\n    rpm = std::sqrt(thrust/(4*kf));\n    if( i < 3000)\n      quad.setExternalForce(Eigen::Vector3d(0, 0, -KP*z_des));\n    else\n      quad.setExternalForce(Eigen::Vector3d(0, 0, 0));\n    quad.setInput(rpm, rpm, rpm, rpm);\n    quad.step(dt);\n    Eigen::Vector3d euler = state.R.eulerAngles(2,1,0);\n    std::cout << i*dt << \", \" << state.x(2) << \", \" << euler(0) << \", \" << euler(1) << \", \" << euler(2) << \", \" <<\n        state.omega(0) << \", \" << state.omega(1) << \", \" << state.omega(2) << \", \" << state.motor_rpm(0) << std::endl;\n\n    clock_gettime(CLOCK_MONOTONIC, &ts2);\n    time_taken += ((ts2.tv_sec-ts1.tv_sec)*1000000000UL + (ts2.tv_nsec-ts1.tv_nsec));\n    int64_t time_sleep = i*dt/2*1e9 - time_taken;\n    clock_gettime(CLOCK_MONOTONIC, &ts1);\n    if(time_sleep > 0)\n    {\n      ts_sleep.tv_sec = time_sleep/1000000000UL;\n      ts_sleep.tv_nsec = time_sleep - ts_sleep.tv_sec*1000000000UL;\n      //nanosleep(&ts_sleep, NULL);\n    }\n  }\n  clock_gettime(CLOCK_MONOTONIC, &ts_end);\n  std::cerr << \"Time: \" << (ts_end.tv_sec-ts_start.tv_sec)*1e6 + (ts_end.tv_nsec-ts_start.tv_nsec)/1e3 << \" usec\" <<std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "8d845309e736dd11255664310fa89b3a99450f1c", "size": 2165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/src/test_dynamics/test_dynamics.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/src/test_dynamics/test_dynamics.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/src/test_dynamics/test_dynamics.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": 34.9193548387, "max_line_length": 126, "alphanum_fraction": 0.6318706697, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5222972918664518}}
{"text": "#include \"cuNDArray_math.h\"\n#include \"cuPartialDerivativeOperator.h\"\n#include \"osLALMSolver.h\"\n#include \"cuSolverUtils.h\"\n#include <boost/program_options.hpp>\n#include \"hoNDArray_fileio.h\"\n#include \"cuNlcgSolver.h\"\n#include \"identityOperator.h\"\nusing namespace Gadgetron;\ntypedef cuNDArray<float> ARRAY_TYPE;\ntypedef float REAL;\ntypedef std::vector<std::vector<boost::shared_ptr<linearOperator<cuNDArray<float >>>>> RG;\n\n\tvoid denoise(ARRAY_TYPE& x, ARRAY_TYPE& s, REAL scaling,REAL avg_lambda, int inner_iterations, RG& regularization_groups){\n\t\tstd::cout << \"scaling \" << scaling << std::endl;\n\t\tREAL tau=1e-4;\n\t\tREAL gam=0.35/(scaling*avg_lambda);\n\t\tREAL sigma = 1;\n\t\tREAL alpha = 0;\n\t\tARRAY_TYPE g(x.get_dimensions());\n\n\t\tfor (auto it = 0u; it < inner_iterations; it++){\n\t\t\tclear(&g);\n\n\n\t\t\tfor (auto & reg_group : regularization_groups){\n\t\t\t\tstd::vector<ARRAY_TYPE> datas(reg_group.size());\n\t\t\t\tREAL val = 0;\n\t\t\t\tfor (auto i = 0u; i < reg_group.size(); i++){\n\t\t\t\t\tdatas[i] = ARRAY_TYPE(reg_group[i]->get_codomain_dimensions());\n\t\t\t\t\treg_group[i]->mult_M(&x,&datas[i]);\n\t\t\t\t\tdatas[i] *= sigma*reg_group[i]->get_weight()/avg_lambda;\n\t\t\t\t}\n\t\t\t\t//updateFgroup is the resolvent operators on the group\n\t\t\t\tupdateFgroup(datas,alpha,sigma);\n\n\t\t\t\tfor (auto i = 0u; i < reg_group.size(); i++){\n\t\t\t\t\tdatas[i] *= reg_group[i]->get_weight()/avg_lambda;\n\t\t\t\t\treg_group[i]->mult_MH(&datas[i],&g,true);\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t//updateG is the resolvent operator on the |x-s| part of the optimization\n\taxpy(-tau,&g,&x);\n\t\t\tg = s;\n\n\t\t\taxpy(tau/(scaling*avg_lambda),&g,&x);\n\n\t\t\t//g = precon;\n\t\t\tfill(&g,1.0f);\n\n\t\t\treciprocal_inplace(&g);\n\t\t\tg *= tau/(scaling*avg_lambda);\n\t\t\tg += REAL(1);\n\t\t\tx /= g;\n\t\t\t//x *= 1/(1+tau/(scaling*avg_lambda));\n\t\t\tREAL theta = 1/std::sqrt(1+2*gam*tau);\n\t\t\ttau *= theta;\n\t\t\tsigma /= theta;\n\t\t}\n\n\n\n\t};\n\nnamespace po = boost::program_options;\n\nint main(int argc, char** argv){\n\tstd::string filename;\n\tstd::string outputFile;\n\tint iterations;\n\tfloat tv_weight;\n\tpo::options_description desc(\"Allowed options\");\n\n\tdesc.add_options()\n    \t\t\t\t(\"help\", \"produce help message\")\n    \t\t\t\t(\"filename,f\",po::value<std::string>(&filename)->default_value(\"lena.real\"),\"input filename\")\n    \t\t\t\t(\"output,o\", po::value<std::string>(&outputFile)->default_value(\"reconstruction.real\"), \"Output filename\")\n    \t\t\t\t(\"TV\",po::value<float>(&tv_weight)->default_value(0),\"Total variation weight\")\n    \t\t\t\t(\"iterations,i\",po::value<int>(&iterations)->default_value(10),\"Denoising iterations\")\n    \t\t\t\t;\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm);\n\n\tauto img = cuNDArray<float>(*read_nd_array<float>(filename.c_str()));\n\timg *= 1e-5f;\n\tauto dims = *img.get_dimensions();\n\tauto Dx = boost::make_shared<cuPartialDerivativeOperator<float,2>>(0);\n\tDx->set_weight(tv_weight);\n\tDx->set_domain_dimensions(&dims);\n\tDx->set_codomain_dimensions(&dims);\n\tauto Dy = boost::make_shared<cuPartialDerivativeOperator<float,2>>(1);\n\tDy->set_weight(tv_weight);\n\tDy->set_domain_dimensions(&dims);\n\tDy->set_codomain_dimensions(&dims);\n\n\tstd::vector<boost::shared_ptr<linearOperator<cuNDArray<float>>>> reg_group({Dx,Dy});\n\n\tcuNDArray<float> out(img);\n\n\tRG group({reg_group});\n\n\tdenoise(out,img,1.0f,tv_weight,iterations,group);\n\n\t/*\n\tcuNlcgSolver<float> solver;\n\tauto id = boost::make_shared<identityOperator<cuNDArray<float>>>();\n\tid->set_codomain_dimensions(&dims);\n\tid->set_domain_dimensions(&dims);\n\tsolver.set_encoding_operator(id);\n\n\tsolver.add_regularization_group_operator(Dx);\n\tsolver.add_regularization_group_operator(Dy);\n\tsolver.add_group(1);\n\n\tsolver.set_max_iterations(iterations);\n\tauto out = solver.solve(&img);\n*/\n\twrite_nd_array(out.to_host().get(),outputFile.c_str());\n\n}\n", "meta": {"hexsha": "89f41314a8c52cc13366aaaaff174b28e52fe965", "size": 3709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xray/denoise_TV.cpp", "max_stars_repo_name": "ahsanjav/gt-tomography", "max_stars_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-06-26T13:41:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-10T11:06:27.000Z", "max_issues_repo_path": "xray/denoise_TV.cpp", "max_issues_repo_name": "ahsanjav/gt-tomography", "max_issues_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xray/denoise_TV.cpp", "max_forks_repo_name": "ahsanjav/gt-tomography", "max_forks_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T14:37:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T14:37:29.000Z", "avg_line_length": 29.672, "max_line_length": 123, "alphanum_fraction": 0.6904826099, "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5222972806525261}}
{"text": "// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-\n\n#include <RcppArmadillo.h>\n#include <random>\n#include <boost/math/distributions/normal.hpp>\n#include \"myrng.h\"\n\nusing namespace Rcpp;\nusing namespace RcppArmadillo;\nusing namespace boost::math;\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::depends(BH)]]\n// [[Rcpp::plugins(cpp11)]]\n\n// accesses myrng.h to make a random uniform variable\n// [[Rcpp::export]]\narma::colvec crunif(unsigned int n, unsigned int seed) {\n    Uniform unif(seed);\n    arma::colvec out(n, arma::fill::none);\n    for(auto i = 0; i < n; i++) {\n        out[i] = unif.draw();\n    }\n    return out;\n}\n\n// Pseudocode 2 of Finley et al. 2019\n// [[Rcpp::export]]\nRcpp::List csolve_for_A_and_D(arma::sp_mat& cov_cur,\n                              Rcpp::List& neighbor_list) {\n    int s = cov_cur.n_rows;\n    arma::sp_mat A = arma::sp_mat(s, s);\n    arma::sp_mat D = arma::sp_mat(s, s);\n    arma::uvec N;\n    int sizen;\n    D[0] = cov_cur[0];\n\n    for(auto i = 0; i < (s-1); i++) {\n        // minus 1 because 0 vs 1-based indexing\n        N = as<arma::uvec>(neighbor_list[i+1]) - 1;\n        sizen = N.size()-1;\n        A.row(i+1).cols(N[0], N[sizen]) = arma::solve(arma::mat(cov_cur.cols(N[0], N[sizen]).rows(N[0], N[sizen])), arma::colvec(cov_cur.col(i+1).rows(N[0], N[sizen]))).t();\n        D.row(i+1).col(i+1) = cov_cur.col(i+1).row(i+1) - dot(arma::rowvec(cov_cur.cols(N[0], N[sizen]).row(i+1)), A.cols(N[0], N[sizen]).row(i+1));\n    }\n    return Rcpp::List::create(\n        Rcpp::Named(\"A\") = A,\n        Rcpp::Named(\"D\") = D);\n}\n\n// [[Rcpp::export]]\ndouble csparse_quadratic_form_symm(arma::colvec& u,\n                                      arma::sp_mat& A,\n                                      arma::colvec& D,\n                                      Rcpp::List& neighbor_list) {\n    double tmp = pow(u[0], 2) / D[0];\n    int n = u.n_elem;\n    arma::uvec N;\n    int sizen;\n    for(auto i = 1; i < n; i++) {\n        N = as<arma::uvec>(neighbor_list[i]) - 1;\n        sizen = N.size()-1;\n        tmp += pow(u[i] - arma::dot(A.cols(N[0], N[sizen]).row(i), u.elem(N).t()), 2) / D[i];\n    }\n    return(tmp);\n}\n\n// [[Rcpp::export]]\ndouble csparse_quadratic_form_asymm(arma::colvec u,\n                                    arma::colvec v,\n                                    arma::sp_mat A,\n                                    arma::colvec D,\n                                    Rcpp::List neighbor_list) {\n    double tmp = u[0] * v[0] / D[0];\n    int n = u.n_elem;\n    arma::uvec N;\n    int sizen;\n    for(auto i = 1; i < n; i++) {\n        N = as<arma::uvec>(neighbor_list[i]) - 1;\n        sizen = N.size()-1;\n        tmp += (u[i] - arma::dot(A.cols(N[0], N[sizen]).row(i), u.elem(N).t())) *\n            (v[i] - arma::dot(A.cols(N[0], N[sizen]).row(i), v.elem(N).t())) / D[i];\n    }\n    return(tmp);\n}\n\n// [[Rcpp::export]]\nRcpp::List csolve_for_B_and_b(arma::mat& y,\n                              arma::mat& X,\n                              arma::sp_mat& A,\n                              arma::colvec& D,\n                              Rcpp::List& neighbor_list,\n                              arma::mat& precision_beta) {\n    int p = X.n_cols;\n    arma::colvec b(p, arma::fill::ones);\n    arma::mat B(p, p, arma::fill::ones);\n    arma::colvec ybar = mean(y, 1);\n\n    for(auto i = 0; i < p; i++) {\n        b[i] = csparse_quadratic_form_asymm(X.col(i), ybar, A, D, neighbor_list);\n        for(auto j = 0; j < p; j++) {\n            B.col(j).row(i) = csparse_quadratic_form_asymm(X.col(i), X.col(j), A, D, neighbor_list);\n        }\n    }\n\n\n    return(Rcpp::List::create(\n            Rcpp::Named(\"B\") = B + precision_beta,\n            Rcpp::Named(\"b\") = b)\n               );\n}\n\n// [[Rcpp::export]]\narma::mat cmake_one_pred_sparse(Rcpp::List& neighbor_list,\n                                arma::mat& y,\n                                arma::mat& s,\n                                arma::mat& X,\n                                arma::mat& cond_cov,\n                                int BOOT,\n                                unsigned int SEED) {\n    int n = y.n_rows;\n    arma::mat L;\n\n    arma::mat uniform_rv;\n    uniform_rv = arma::reshape(crunif(n * BOOT, SEED), n, BOOT);\n    arma::mat z(n, BOOT, arma::fill::none);\n    arma::mat preds(n, BOOT, arma::fill::none);\n    normal standard_normal;\n\n    for(auto i = 0; i < n; i++) {\n        for(auto j = 0; j < BOOT; j++) {\n            z(i,j) = quantile(standard_normal, uniform_rv(i,j));\n        }\n    }\n\n    arma::uvec Nidx;\n    int sizen;\n    preds.row(0) = sqrt(cond_cov[0]) * z.row(0);\n    for(auto i = 1; i < n; i++) {\n        Nidx = as<arma::uvec>(neighbor_list[i]) - 1;\n        sizen = Nidx.size()-1;\n        L = arma::chol(cond_cov.cols(Nidx[0], Nidx[sizen]).rows(Nidx[0], Nidx[sizen]), \"upper\");\n        preds.row(i) = L.col(L.n_cols-1).t() * (z.rows(Nidx[0], Nidx[sizen]));\n    }\n\n    return(preds);\n}\n\n// [[Rcpp::export]]\nRcpp::List csolve_for_A_and_D_2d(arma::sp_mat& cov_cur,\n                                 Rcpp::List& neighbor_list) {\n    int s = cov_cur.n_rows;\n    arma::mat cov_cur_dense = arma::mat(cov_cur);\n\n    arma::mat A = arma::mat(s, s);\n    arma::sp_mat D = arma::sp_mat(s, s);\n    arma::uvec N;\n\n    D[0] = cov_cur[0];\n    arma::uvec v = { 1 };\n    for(auto i = 0; i < (s-1); i++) {\n        // minus 1 because 0 vs 1-based indexing\n        N = as<arma::uvec>(neighbor_list[i+1]) - 1;\n        A.submat(v, N) = arma::solve(cov_cur_dense.submat(N, N), arma::colvec(cov_cur_dense.submat(N, v))).t();\n        D.row(i+1).col(i+1) = cov_cur_dense.col(i+1).row(i+1) - dot(arma::rowvec(cov_cur_dense.submat(v, N)), A.submat(v, N));\n        v = v+1;\n    }\n\n    return Rcpp::List::create(\n        Rcpp::Named(\"A\") = arma::sp_mat(A),\n        Rcpp::Named(\"D\") = D);\n}\n\n// [[Rcpp::export]]\ndouble csparse_quadratic_form_symm_2d(arma::colvec& u,\n                                   arma::sp_mat& A,\n                                   arma::colvec& D,\n                                   Rcpp::List& neighbor_list) {\n    double tmp = pow(u[0], 2) / D[0];\n    int n = u.n_elem;\n    arma::uvec N;\n    int sizen;\n\n    arma::mat A_dense = arma::mat(A);\n    arma::uvec v = { 1 };\n    for(auto i = 1; i < n; i++) {\n        N = as<arma::uvec>(neighbor_list[i]) - 1;\n        sizen = N.size()-1;\n        tmp += pow(u[i] - arma::dot(A_dense.submat(v, N), u.elem(N).t()), 2) / D[i];\n        v = v+1;\n    }\n    return(tmp);\n}\n\n// [[Rcpp::export]]\ndouble csparse_quadratic_form_asymm_2d(arma::colvec u,\n                                    arma::colvec v,\n                                    arma::sp_mat A,\n                                    arma::colvec D,\n                                    Rcpp::List neighbor_list) {\n    double tmp = u[0] * v[0] / D[0];\n    int n = u.n_elem;\n    arma::uvec N;\n    int sizen;\n\n    arma::mat A_dense = arma::mat(A);\n    arma::uvec vv = { 1 };\n    for(auto i = 1; i < n; i++) {\n        N = as<arma::uvec>(neighbor_list[i]) - 1;\n        sizen = N.size()-1;\n        tmp += (u[i] - arma::dot(A_dense.submat(vv, N), u.elem(N).t())) *\n            (v[i] - arma::dot(A_dense.submat(vv, N), v.elem(N).t())) / D[i];\n        vv = vv+1;\n    }\n    return(tmp);\n}\n\n// [[Rcpp::export]]\nRcpp::List csolve_for_B_and_b_2d(arma::mat& y,\n                              arma::mat& X,\n                              arma::sp_mat& A,\n                              arma::colvec& D,\n                              Rcpp::List& neighbor_list,\n                              arma::mat& precision_beta) {\n    int p = X.n_cols;\n    arma::colvec b(p, arma::fill::ones);\n    arma::mat B(p, p, arma::fill::ones);\n    arma::colvec ybar = mean(y, 1);\n\n    for(auto i = 0; i < p; i++) {\n        b[i] = csparse_quadratic_form_asymm_2d(X.col(i), ybar, A, D, neighbor_list);\n        for(auto j = 0; j < p; j++) {\n            B.col(j).row(i) = csparse_quadratic_form_asymm_2d(X.col(i), X.col(j), A, D, neighbor_list);\n        }\n    }\n\n\n    return(Rcpp::List::create(\n            Rcpp::Named(\"B\") = B + precision_beta,\n            Rcpp::Named(\"b\") = b)\n    );\n}\n", "meta": {"hexsha": "1fc79ab56e42d82215a6f1e7d0ce84f310a2bf09", "size": 8037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sparse_gpcpp.cpp", "max_stars_repo_name": "hillarykoch/locdiffr", "max_stars_repo_head_hexsha": "2d30c09c7a1e4d14f91bdc35d17b805bcb0d0aa5", "max_stars_repo_licenses": ["Artistic-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/sparse_gpcpp.cpp", "max_issues_repo_name": "hillarykoch/locdiffr", "max_issues_repo_head_hexsha": "2d30c09c7a1e4d14f91bdc35d17b805bcb0d0aa5", "max_issues_repo_licenses": ["Artistic-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/sparse_gpcpp.cpp", "max_forks_repo_name": "hillarykoch/locdiffr", "max_forks_repo_head_hexsha": "2d30c09c7a1e4d14f91bdc35d17b805bcb0d0aa5", "max_forks_repo_licenses": ["Artistic-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.3485477178, "max_line_length": 173, "alphanum_fraction": 0.478661192, "num_tokens": 2481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5222671853995784}}
{"text": "#include \"mode_calc_pca.hpp\"\n\n#include <mill/util/cmdarg.hpp>\n#include <mill/math/Vector.hpp>\n// #include <mill/math/EigenSolver.hpp>\n#include <mill/traj.hpp>\n#include <toml/toml.hpp>\n#include <numeric>\n\n#include <Eigen/Dense>\n\nnamespace mill\n{\n\nconst char* mode_calc_pca_usage() noexcept\n{\n    return \"usage: mill calc pca {trajectory} [--top=(3 by default)] [--top-contribution=(95% by default)] [--output=(\\\"{base name of trajectory}_pca.dat\\\" by default)]\\n\"\n           \"         determines principal component from traj file.\\n\"\n           \"         --top=N specifies the number of component will be written out.\\n\"\n           \"         --top-contribution=% specifies the number of component via the accumulated contribution rate.\\n\"\n           \"         if you specify `--top=3 --top-contribution=95` and it would be found that top 5 components are\\n\"\n           \"         needed to achieve 95% contribution, 5 components are written.\\n\"\n           \"     $ mill calc pca {input.toml}\\n\"\n           \"         determines principal component using customized input.\\n\"\n           \"         ```toml\\n\"\n           \"         input  = \\\"traj.dcd\\\"\\n\"\n           \"         output_basename = \\\"pca.dat\\\"\\n\"\n           \"         # (optional) how many components are reported.\\n\"\n           \"         # by default, 3.\\n\"\n           \"         top    = 10\\n\"\n           \"         # (optional) instead of `top`, output top N% contributing PCs.\\n\"\n           \"         top_contribution = 95 # %\\n\"\n           \"         # (optional) indices of particles to be used.\\n\"\n           \"         # by default, all the particles are used.\\n\"\n           \"         # {first, last} specifies the range. last is not included.\\n\"\n           \"         use    = [0, 2, 5, {first=10, last=20}]\\n\"\n           \"         ```\";\n}\n\nint mode_calc_pca(std::deque<std::string_view> args)\n{\n    using namespace std::literals::string_literals;\n\n    auto top_n_opt       = pop_argument<std::size_t>(args, \"top\");\n    auto top_contrib_opt = pop_argument<double     >(args, \"top-contribution\");\n    auto output_opt      = pop_argument<std::string>(args, \"output\");\n    std::vector<std::size_t> particles_to_be_used;\n\n    if(args.empty())\n    {\n        log::error(\"mill calc pca: too few arguments.\");\n        log::error(mode_calc_pca_usage());\n        return 1;\n    }\n\n    for(const auto& arg : args)\n    {\n        if(arg.substr(0, 2) == \"--\")\n        {\n            log::error(\"unknown argument \", arg, \" found. It will be ignored. please check it.\");\n        }\n    }\n\n    const std::string fname(args.front());\n    if(fname == \"help\")\n    {\n        log::info(mode_calc_pca_usage());\n        return 0;\n    }\n\n    std::string trajfile;\n    if(extension_of(fname) == \".toml\")\n    {\n        const auto data = toml::parse(fname);\n\n        trajfile = toml::find<std::string>(data, \"input\");\n\n        if(data.contains(\"top\"))\n        {\n            top_n_opt = toml::find<std::size_t>(data, \"top\");\n        }\n\n        if(data.contains(\"top_contribution\"))\n        {\n            top_contrib_opt = toml::find<double>(data, \"top_contribution\");\n        }\n        if(data.contains(\"top-contribution\"))\n        {\n            top_contrib_opt = toml::find<double>(data, \"top-contribution\");\n        }\n\n        if(data.contains(\"output_basename\"))\n        {\n            output_opt = toml::find<std::string>(data, \"output_basename\");\n        }\n        if(data.contains(\"use\"))\n        {\n            for(auto&& elem : toml::find<toml::array>(data, \"use\"))\n            {\n                if(elem.is_integer())\n                {\n                    particles_to_be_used.push_back(elem.as_integer());\n                }\n                else\n                {\n                    for(std::size_t i=elem.at(\"first\").as_integer(), e=elem.at(\"last\").as_integer(); i<e; ++i)\n                    {\n                        particles_to_be_used.push_back(i);\n                    }\n                }\n            }\n        }\n        else\n        {\n            particles_to_be_used.resize(reader(trajfile).read_frame()->size(), 0);\n            std::iota(particles_to_be_used.begin(), particles_to_be_used.end(), 0);\n        }\n    }\n    else\n    {\n        trajfile = std::string(fname);\n        particles_to_be_used.resize(reader(trajfile).read_frame()->size(), 0);\n        std::iota(particles_to_be_used.begin(), particles_to_be_used.end(), 0);\n    }\n\n    if(not output_opt.has_value())\n    {\n        output_opt = std::string(base_name_of(trajfile));\n    }\n\n    const std::string output_basename = output_opt.value();\n\n    log::info(\"It will use \", particles_to_be_used.size(), \" particles in total.\");\n    if(top_n_opt.has_value())\n    {\n        log::info(\"It will output \", top_n_opt.value(), \" components\");\n    }\n    if(top_contrib_opt.has_value())\n    {\n        log::info(\"It will output top \", top_contrib_opt.value(), \"% contributing components.\");\n    }\n    log::info(\"The results will be written in \", output_basename);\n\n    // we will use this `traj` to write the movement corresponds to the principal components.\n    Trajectory traj = reader(trajfile).read();\n\n    log::debug(\"input files are loaded.\");\n    log::info(\"trajectory has \", traj.size(), \" snapshots.\");\n\n    // -----------------------------------------------------------------------\n    // constructing covariance matrix\n\n    std::size_t num_frames = 0;\n    std::vector<double> means(particles_to_be_used.size() * 3, 0.0);\n    for(const auto frame : traj)\n    {\n#pragma omp parallel for\n        for(std::size_t i=0; i<particles_to_be_used.size(); ++i)\n        {\n            means[i*3+0] += frame.at(particles_to_be_used[i]).position()[0];\n            means[i*3+1] += frame.at(particles_to_be_used[i]).position()[1];\n            means[i*3+2] += frame.at(particles_to_be_used[i]).position()[2];\n        }\n        num_frames += 1;\n    }\n\n    const double normalize = 1.0 / num_frames;\n#pragma omp parallel for\n    for(std::size_t i=0; i<means.size(); ++i)\n    {\n        auto& mean = means[i];\n        mean *= normalize;\n    }\n\n    log::info(\"mean positions are calculated\");\n\n    // {x1, y1, z1, x2, y2, z2, ...}\n    Eigen::MatrixXd mat = Eigen::MatrixXd::Zero(particles_to_be_used.size() * 3,\n                                                particles_to_be_used.size() * 3);\n\n    for(const auto frame : traj)\n    {\n        // the matrix often will be large enough for this\n#pragma omp parallel for\n        for(std::size_t i=0; i<particles_to_be_used.size(); ++i)\n        {\n            const auto pix = frame.at(particles_to_be_used[i]).position()[0] - means[i*3+0];\n            const auto piy = frame.at(particles_to_be_used[i]).position()[1] - means[i*3+1];\n            const auto piz = frame.at(particles_to_be_used[i]).position()[2] - means[i*3+2];\n\n            for(std::size_t j=i; j<particles_to_be_used.size(); ++j)\n            {\n                const auto pjx = frame.at(particles_to_be_used[j]).position()[0] - means[j*3+0];\n                const auto pjy = frame.at(particles_to_be_used[j]).position()[1] - means[j*3+1];\n                const auto pjz = frame.at(particles_to_be_used[j]).position()[2] - means[j*3+2];\n\n                mat(i*3+0, j*3+0) += pix * pjx;\n                mat(i*3+0, j*3+1) += pix * pjy;\n                mat(i*3+0, j*3+2) += pix * pjz;\n\n                mat(i*3+1, j*3+0) += piy * pjx;\n                mat(i*3+1, j*3+1) += piy * pjy;\n                mat(i*3+1, j*3+2) += piy * pjz;\n\n                mat(i*3+2, j*3+0) += piz * pjx;\n                mat(i*3+2, j*3+1) += piz * pjy;\n                mat(i*3+2, j*3+2) += piz * pjz;\n            }\n        }\n    }\n\n#pragma omp parallel for\n    for(std::size_t i=0; i<particles_to_be_used.size() * 3; ++i)\n    {\n        mat(i, i) *= normalize;\n        for(std::size_t j=i+1; j<particles_to_be_used.size() * 3; ++j)\n        {\n            mat(i, j) *= normalize;\n            mat(j, i) = mat(i, j);\n        }\n    }\n\n    log::info(\"co-variance matrix is constructed\");\n\n    // -----------------------------------------------------------------------\n    // calculating eigenvalues of covariance matrix\n\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(mat);\n    std::vector<std::pair<double, Eigen::VectorXd>> eigens(particles_to_be_used.size() * 3);\n\n#pragma omp parallel for\n    for(std::size_t i=0; i<particles_to_be_used.size() * 3; ++i)\n    {\n        eigens[i].first  = solver.eigenvalues()[i];\n        eigens[i].second = solver.eigenvectors().col(i);\n    }\n\n    std::sort(eigens.begin(), eigens.end(), [](const auto& lhs, const auto& rhs) {\n            return lhs.first > rhs.first;\n        });\n\n    log::info(\"eigenvalues are calculated\");\n\n    // -----------------------------------------------------------------------\n    // determining contribution rate\n\n    const auto sum_eigenvalues = std::accumulate(eigens.begin(), eigens.end(),\n        0.0, [](const auto& acc, const auto& elem) {\n            return acc + elem.first;\n        }) * 0.01; // scale to the per-cent\n    std::vector<double> contribution_rate(eigens.size());\n    std::transform(eigens.begin(), eigens.end(), contribution_rate.begin(),\n            [sum_eigenvalues](const auto& eigenpair) noexcept -> double {\n                return eigenpair.first / sum_eigenvalues;\n            });\n\n    std::vector<double> accumulated_contribution_rate(eigens.size());\n    const double contribution_threshold = top_contrib_opt.value_or(95.0);\n    std::size_t top_contributions = 0;\n    double accum = 0.0;\n    std::transform(contribution_rate.begin(), contribution_rate.end(),\n            accumulated_contribution_rate.begin(),\n            [&accum, &top_contributions, contribution_threshold](const auto& rate) {\n                if(accum <= contribution_threshold)\n                {\n                    top_contributions += 1;\n                }\n                accum += rate;\n                return accum;\n            });\n\n    std::size_t num_components = std::max<std::size_t>(3, top_contributions);\n    if(top_n_opt.has_value())\n    {\n        num_components = top_n_opt.value();\n    }\n    if(top_contrib_opt.has_value())\n    {\n        num_components = top_contributions;\n    }\n    if(top_n_opt.has_value() && top_contrib_opt.has_value())\n    {\n        num_components = std::max(top_contributions, top_n_opt.value());\n    }\n\n    if(num_components < eigens.size())\n    {\n        eigens.resize(num_components);\n    }\n\n    log::info(\"top \", num_components, \" components (\",\n            accumulated_contribution_rate.at(num_components), \"% contribution) will be written\");\n\n    // ------------------------------------------------------------------------\n    // determine direction (sign) of eigenvector to make the trajectory (-)->(+)\n\n    for(auto& [eigval, eigvec] : eigens)\n    {\n        Eigen::VectorXd first_frame = Eigen::VectorXd::Zero(particles_to_be_used.size() * 3);\n        for(std::size_t i=0; i<particles_to_be_used.size(); ++i)\n        {\n            first_frame[i*3+0] = traj.front().at(particles_to_be_used[i]).position()[0] - means[i*3+0];\n            first_frame[i*3+1] = traj.front().at(particles_to_be_used[i]).position()[1] - means[i*3+1];\n            first_frame[i*3+2] = traj.front().at(particles_to_be_used[i]).position()[2] - means[i*3+2];\n        }\n        Eigen::VectorXd  last_frame = Eigen::VectorXd::Zero(particles_to_be_used.size() * 3);\n        for(std::size_t i=0; i<particles_to_be_used.size(); ++i)\n        {\n            last_frame[i*3+0] = traj.back().at(particles_to_be_used[i]).position()[0] - means[i*3+0];\n            last_frame[i*3+1] = traj.back().at(particles_to_be_used[i]).position()[1] - means[i*3+1];\n            last_frame[i*3+2] = traj.back().at(particles_to_be_used[i]).position()[2] - means[i*3+2];\n        }\n\n        const auto first = eigvec.dot(first_frame);\n        const auto  last = eigvec.dot( last_frame);\n        if(last < first)\n        {\n            eigvec *= -1.0;\n        }\n    }\n\n    // -----------------------------------------------------------------------\n    // writing trajectory along the eigenvector\n\n    std::vector<std::pair<double, double>> component_range(eigens.size(),\n            std::make_pair(std::numeric_limits<double>::max(),\n                          -std::numeric_limits<double>::max()));\n\n    std::ofstream ofs(output_basename + \"_PCA.dat\"s);\n    if(not ofs.good())\n    {\n        log::fatal(\"file open error: \", output_basename + \"_PCA.dat\"s);\n    }\n\n    ofs << '#';\n    for(std::size_t i=0; i<eigens.size(); ++i)\n    {\n        ofs << \" PC\" << i;\n    }\n    ofs << '\\n';\n\n    ofs << '#';\n    for(std::size_t i=0; i<eigens.size(); ++i)\n    {\n        ofs << \" \" << std::fixed << std::setprecision(5) << contribution_rate.at(i) << \"%\";\n    }\n    ofs << '\\n';\n\n    for(const auto frame : traj)\n    {\n        Eigen::VectorXd snapshot = Eigen::VectorXd::Zero(particles_to_be_used.size() * 3);\n        for(std::size_t i=0; i<particles_to_be_used.size(); ++i)\n        {\n            snapshot[i*3+0] = frame.at(particles_to_be_used[i]).position()[0] - means[i*3+0];\n            snapshot[i*3+1] = frame.at(particles_to_be_used[i]).position()[1] - means[i*3+1];\n            snapshot[i*3+2] = frame.at(particles_to_be_used[i]).position()[2] - means[i*3+2];\n        }\n\n        std::size_t idx=0;\n        for(const auto& eigen : eigens)\n        {\n            const auto component = snapshot.dot(eigen.second);\n            ofs << component << ' ';\n\n            component_range.at(idx).first  = std::min(component, component_range.at(idx).first);\n            component_range.at(idx).second = std::max(component, component_range.at(idx).second);\n\n            ++idx;\n        }\n        ofs << '\\n';\n    }\n\n    log::info(\"trajectory along PCs are written in \", output_basename + \"_PCA.dat\");\n\n    // -----------------------------------------------------------------------\n    // output principal motion\n\n    // freeze the trajectory at the mean position to see the movement of selected particles\n    auto& init = traj.at(0);\n    for(std::size_t i=1; i<traj.size(); ++i)\n    {\n        const auto frame = traj.at(i);\n        for(std::size_t p_idx=0; p_idx<frame.size(); ++p_idx)\n        {\n            init.at(p_idx).position() += frame.at(p_idx).position();\n        }\n    }\n    for(std::size_t p_idx=0; p_idx<init.size(); ++p_idx)\n    {\n        init.at(p_idx).position() *= normalize;\n    }\n\n    const std::size_t PC_movement_len = std::min<std::size_t>(1000, traj.size());\n    traj.snapshots().resize(PC_movement_len);\n\n    for(std::size_t i=1; i<traj.size(); ++i)\n    {\n        traj.at(i) = init;\n    }\n\n    // construct movement along PCs\n\n    std::size_t idx=0;\n    for(const auto& eigen : eigens)\n    {\n        const auto [lower, upper] = component_range.at(idx);\n\n        const auto dx = (upper - lower) / PC_movement_len;\n        for(std::size_t t=0; t<PC_movement_len; ++t)\n        {\n            auto& frame = traj.at(t);\n\n            const auto x = lower + dx * t;\n            for(std::size_t i=0; i<particles_to_be_used.size(); ++i)\n            {\n                frame.at(particles_to_be_used[i]).position()[0] = means.at(i*3+0) + eigen.second[i*3+0] * x;\n                frame.at(particles_to_be_used[i]).position()[1] = means.at(i*3+1) + eigen.second[i*3+1] * x;\n                frame.at(particles_to_be_used[i]).position()[2] = means.at(i*3+2) + eigen.second[i*3+2] * x;\n            }\n        }\n        const auto outtrajname = output_basename + \"_PC\"s +\n            std::to_string(idx+1) + std::string(extension_of(trajfile));\n        auto w = writer(outtrajname);\n        w.write(traj);\n\n        log::info(\"structure change along PC\", idx+1, \" (\", contribution_rate.at(idx) , \"% contribution) is written in \", outtrajname);\n\n        ++idx;\n    }\n\n    // -----------------------------------------------------------------------\n    // output principal vectors as a trajectory\n\n    // normally, number of Eigen vectors to be written is smaller than 1000...\n    traj.snapshots().resize(eigens.size());\n    for(std::size_t i=0; i<eigens.size(); ++i)\n    {\n        const auto& [val, vec] = eigens.at(i);\n\n        auto& frame = traj.at(i);\n        for(auto& p : frame)\n        {\n            p.position() = Vector<double, 3>(0, 0, 0); // clear frame\n        }\n        // write eigen vector\n        for(std::size_t i=0; i<particles_to_be_used.size(); ++i)\n        {\n            frame.at(particles_to_be_used[i]).position()[0] = vec[i*3+0];\n            frame.at(particles_to_be_used[i]).position()[1] = vec[i*3+1];\n            frame.at(particles_to_be_used[i]).position()[2] = vec[i*3+2];\n        }\n    }\n    const auto eigen_vec_name = output_basename + \"_EigenVectors\" +\n                                std::string(extension_of(trajfile));\n    auto w = writer(eigen_vec_name);\n    w.write(traj);\n\n    return 0;\n}\n\n} // mill\n", "meta": {"hexsha": "417482e7713ca3355aa06dbdc495220dd5ea9eca", "size": 16734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mode_calc_pca.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": "src/mode_calc_pca.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": "src/mode_calc_pca.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": 36.2207792208, "max_line_length": 171, "alphanum_fraction": 0.5375283853, "num_tokens": 4254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.6406358548398982, "lm_q1q2_score": 0.5222671742127347}}
{"text": "/// @file types.hpp Simple typedefs used by Biggles\n\n#ifndef BIGGLES_TYPES_HPP__\n#define BIGGLES_TYPES_HPP__\n\n#include <Eigen/Dense>\n\nnamespace biggles {\n\ntypedef Eigen::Matrix2f matrix2f;\ntypedef Eigen::Matrix4f matrix4f;\ntypedef Eigen::Matrix<float, 2, 4> matrix2x4f;\ntypedef Eigen::Matrix<float, 4, 2> matrix4x2f;\n\ntypedef Eigen::Vector4f state_t; // the underlying state vector type: [x, x', y, y']'\n\n\n\n\n\nnamespace model {\n\n/// @brief A tuple representing the model parameters.\n///\n/// The model parameters are represented by the tuple \\f$ ( \\lambda_b, \\lambda_f, p_s, p_d, R ) \\f$ where\n///\n/// - \\f$ \\lambda_b \\f$: the mean number of new tracks appearing per frame.\n/// - \\f$ \\lambda_f \\f$: the mean number of false observations per frame.\n/// - \\f$ p_s \\f$: the probability that a target will survive from frame \\f$ t \\f$ to \\f$ t+1 \\f$.\n/// - \\f$ p_d \\f$: the probability that a target will generate an observation.\n/// - \\f$ r \\f$: the constraint radius.\n/*\ntypedef boost::tuples::tuple<float, float, float, float, matrix2f, float, matrix4f> parameters;\n*/\n\nstruct parameters {\n    float birth_rate;\n    float clutter_rate;\n    float survival_probability;\n    float observation_probability;\n    matrix2f observation_error_covariance;\n    float constraint_radius;\n    matrix4f process_noise_covariance;\n    bool operator==(const parameters &other) const {\n        return\n        other.birth_rate == birth_rate and\n        other.clutter_rate == clutter_rate and\n        other.survival_probability == survival_probability and\n        other.observation_probability == observation_probability and\n        other.constraint_radius == constraint_radius and\n        other.observation_error_covariance == observation_error_covariance and\n        other.process_noise_covariance == process_noise_covariance;\n    }\n};\n\n}\n\n}\n\n#endif // BIGGLES_MODEL_HPP__\n", "meta": {"hexsha": "aa1c2774fceb83faf96fb685c57a735de9a4bae7", "size": 1851, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/biggles/types.hpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "include/biggles/types.hpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/biggles/types.hpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3442622951, "max_line_length": 105, "alphanum_fraction": 0.715289033, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5222671681443907}}
{"text": "#pragma once\n\n#include <boost/optional.hpp>\n#include <math/Plane.hpp>\n#include <math/Ray.hpp>\n#include <math/Vec.hpp>\n\ntemplate <int n, class T>\ninline boost::optional<Vec<n, T> > intersection(Ray<n, T> const & ray, Plane<n, T> const & plane) {\n\tT denom = dot(ray.get_dir(), plane.get_normal());\n\tif (denom == 0) {\n        if (plane.contains(ray.get_start())) { return ray.get_start(); }\n        else { return boost::none; }\n    }\n\n\tT t = (plane.get_dist() - dot(ray.get_start(), plane.get_normal())) / denom;\n    if (t < 0) { return boost::none; }\n\treturn ray(t);\n}\n\ntemplate <int n, class T>\ninline boost::optional<Vec<n, T> > intersection(Plane<n, T> const & plane, Ray<n, T> const & ray) {\n\treturn intersection(ray, plane);\n}\n", "meta": {"hexsha": "6bed3d31428a28af3effe1bbd2dfe650b7b736d2", "size": 730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math/intersection.hpp", "max_stars_repo_name": "bracket/circles", "max_stars_repo_head_hexsha": "2e358244ef7823eb7fa836bac88c868ca8b37e21", "max_stars_repo_licenses": ["MIT"], "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/intersection.hpp", "max_issues_repo_name": "bracket/circles", "max_issues_repo_head_hexsha": "2e358244ef7823eb7fa836bac88c868ca8b37e21", "max_issues_repo_licenses": ["MIT"], "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/intersection.hpp", "max_forks_repo_name": "bracket/circles", "max_forks_repo_head_hexsha": "2e358244ef7823eb7fa836bac88c868ca8b37e21", "max_forks_repo_licenses": ["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.2, "max_line_length": 99, "alphanum_fraction": 0.6369863014, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5222671630258906}}
{"text": "#include <stdio.h>\r\n#include \"EM.h\"\r\n#include <cstdlib>\r\n#include <string>\r\n#include <time.h>\r\n#include <boost/random.hpp>\r\n\r\nusing namespace ai::em;\r\nusing namespace std;\r\nint main(int argc, char** argv)\r\n{\r\n    Parameters param[6];\r\n    // peff[j][i]: probability of effect #i = 0 given gender = j\r\n\t// j = 0 for male, j=1 for female\r\n\t// i = 0 for height, i = 1 for weight\r\n\t// so peff[0][0] is the probability of height > 55  given male gender\r\n\t//    peff[0][1] is the probability of weight > 130 given male gender\r\n\t//    peff[1][0] is the probability of height > 55  given female gender\r\n\t//    peff[1][1] is the probability of weight > 130 given female gender\r\n    param[0].pg0 = 0.7;\r\n    param[0].peff[0][0] = 0.7; // height 0 (>55) given male\r\n    param[0].peff[0][1] = 0.8; // weight 0 (>130) given male\r\n    param[0].peff[1][0] = 0.3; // height 0 (>55) given female\r\n    param[0].peff[1][1] = 0.4; // weight 0 (>130) given female\r\n\r\n    if(argc == 7)\r\n    {\r\n        param[0].pg0 = atof(argv[2]);\r\n        param[0].peff[0][0] = atof(argv[3]); // height 0 (>55) given male\r\n        param[0].peff[0][1] = atof(argv[4]); // weight 0 (>130) given male\r\n        param[0].peff[1][0] = atof(argv[5]); // height 0 (>55) given female\r\n        param[0].peff[1][1] = atof(argv[6]); // weight 0 (>130) given female\r\n    }\r\n//    //generating five random parameters set\r\n    time_t timer;\r\n    time(&timer);  /* get current time; same as: timer = time(NULL)  */\r\n    boost::mt19937 seed( (int)timer );\r\n    boost::uniform_real<> dist(0.0,1.0);\r\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<> > random(seed,dist);\r\n    for (int i=1; i <6 ; ++i)\r\n    {\r\n        param[i].pg0 = random();\r\n        param[i].peff[0][0] = random(); // height 0 (>55) given male\r\n        param[i].peff[0][1] = random(); // weight 0 (>130) given male\r\n        param[i].peff[1][0] = random();// height 0 (>55) given female\r\n        param[i].peff[1][1] = random();// weight 0 (>130) given female\r\n    }\r\n    EM em;\r\n    em.read_input(argv[1]);\r\n    // five more random starting parameters\r\n//    cout<<\"random number 1 = \"<<random()<<endl;\r\n//    cout<<\"random number 2 = \"<<random()<<endl;\r\n//    cout<<\"random number 3= \"<<random()<<endl;\r\n    for (int i=0; i <6 ; ++i)\r\n    {\r\n\r\n        std::cout <<\"Starting parameter set \"<<i<<\": \" << endl;\r\n        em.setParameters(param[i]);\r\n        //em.read_input(argv[1]);\r\n        Parameters final_param = em.optimize();\r\n        printf (\"%40s\\t %20s\\t %20s\\n\", \"Probability\", \"Starting parameter\", \"final parameters\");\r\n        printf (\"%40s\\t %20.6f\\t %20.6f\\n\", \"P(gender=M)\" ,  param[i].pg0, final_param.pg0);\r\n        printf (\"%40s\\t %20.6f\\t %20.6f\\n\", \"P(weight=greater_than_130|gender=M)\", param[i].peff[0][0], final_param.peff[0][0]);\r\n        printf (\"%40s\\t %20.6f\\t %20.6f\\n\", \"P(weight=greater_than_130|gender=F)\", param[i].peff[0][1], final_param.peff[0][1]);\r\n        printf (\"%40s\\t %20.6f\\t %20.6f\\n\", \"P(height= greater_than_55|gender=M)\", param[i].peff[1][0], final_param.peff[1][0]);\r\n        printf (\"%40s\\t %20.6f\\t %20.6f\\n\", \"P(height= greater_than_55|gender=F)\", param[i].peff[1][1], final_param.peff[1][1]);\r\n    }\r\n\r\n\r\n\r\n\r\n    return 0;\r\n\r\n}\r\n", "meta": {"hexsha": "10351bae15e9135b42e4f17c01135a09842a5295", "size": 3210, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bayes_main.cpp", "max_stars_repo_name": "ninalu/ExpectationMaximization", "max_stars_repo_head_hexsha": "acc45daf7676316eebd59909d72cacb36cc81c7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bayes_main.cpp", "max_issues_repo_name": "ninalu/ExpectationMaximization", "max_issues_repo_head_hexsha": "acc45daf7676316eebd59909d72cacb36cc81c7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bayes_main.cpp", "max_forks_repo_name": "ninalu/ExpectationMaximization", "max_forks_repo_head_hexsha": "acc45daf7676316eebd59909d72cacb36cc81c7a", "max_forks_repo_licenses": ["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.8, "max_line_length": 129, "alphanum_fraction": 0.5669781931, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893520001, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5222671627092766}}
{"text": "// arrayopt.cpp : This file contains the 'main' function. Program execution begins and ends there.\n//\n\n\n#define FMT_HEADER_ONLY\n#define CXXOPTIONS_NO_EXCEPTIONS\n#include <iostream>\n#include <filesystem>\n#include <complex>\n#include <fmt/format.h> //while waiting for official C++20 support\n#include <Eigen/Dense>\n#include <boost/math/quadrature/gauss.hpp>\n#include <cxxopts.hpp>\n\nnamespace bmq = boost::math::quadrature;\n\n#define pi EIGEN_PI\n\nconstexpr int EXIT_UNRECOGNIZED_OPTION = 2;\nconstexpr int EXIT_LINALG_FAILURE = 3;\n\nstd::string header(const size_t width, const std::string msg)\n{\n    std::string hdr = \"\";\n    size_t hmn = (width - msg.size()-4);\n    if (hmn % 2 == 1)\n    {\n        hmn += 1;\n    }\n    hdr += \"\\n\";\n    for (int i = 0; i < hmn / 2; i++)\n    {\n        hdr += \"-\";\n    }\n    hdr += \" \" + msg + \" \";\n    while (!(hdr.size() == width))\n    {\n        hdr += \"-\";\n    }\n    hdr += \"\\n\";\n    return hdr;\n}\n\ndouble f_dipole(double theta, double phi)\n{\n    return std::sin(theta);\n}\n\nstd::complex<double> blm_integrand(double k, double theta, double phi, double xl, double xm, double yl, double ym)\n{\n    double amp = std::pow(f_dipole(theta, phi), 2);\n    double tmx = k * (xl - xm) * std::sin(theta) * std::cos(phi);\n    double tmy = k * (yl - ym) * std::sin(theta) * std::sin(phi);\n    std::complex<double> arg(0, -(tmx+tmy)); //-i(tmx+tmy)\n    \n    return amp * std::exp(arg);\n}\n\nstd::complex<double> blm(double k, double xl, double xm, double yl, double ym)\n{\n    // what are our options to do the double integral here??\n    // https://royalsocietypublishing.org/doi/pdf/10.1098/rspa.2016.0401\n    // delunay integration https://scholarworks.gsu.edu/cgi/viewcontent.cgi?article=1158&context=math_theses\n    // monte carlo brute force?\n    // can we get this in closed form for dipole /\n    return std::complex(nan(\"\"), nan(\"\"));\n}\n\nstd::string efstr = \"\\n**ERROR! {}\\n\";\nstd::string msg;\n\nint main(int argc, char** argv)\n{\n    cxxopts::Options options(\"arrayopt\", \"Uses M.T. Ma's approach to compute array currents for optimal directivity.\");\n    options.add_options()\n        (\"help\", \"Print this screen\")\n        (\"freq\", \"Frequency in MHz\", cxxopts::value<double>()->default_value(\"1.8\"))\n        (\"az\", \"Target azimuth angle, degrees\", cxxopts::value<double>()->default_value(\"0.0\"))\n        (\"el\", \"Target elevation angle, degrees\", cxxopts::value<double>()->default_value(\"0.0\"))\n        (\"file\", \"Wire description file, EZNEC export format, units in meters/mm\", cxxopts::value<std::string>())\n        ;\n    \n    double az, el, azrad, elrad, freq;\n    std::string fn;\n    try\n    {\n        auto opts = options.parse(argc, argv);\n        if (opts.count(\"help\"))\n        {\n            std::cout << options.help() << std::endl;\n            return EXIT_FAILURE;\n        }\n        az = opts[\"az\"].as<double>();\n        el = opts[\"el\"].as<double>();\n        freq = opts[\"freq\"].as<double>();\n        azrad = pi * az / 180;\n        elrad = pi * az / 180;\n    }\n    catch (cxxopts::OptionParseException& e)\n    {\n        std::cout << fmt::format(efstr, e.what()) << std::endl;\n        return EXIT_UNRECOGNIZED_OPTION;\n    }\n\n    msg = \"N3OX / M.T. Ma optimal directivity array calculator\";\n    std::cout << header(80, msg) << std::endl;\n    \n    double k0 = 2 * pi / (freq * 1e6); //wavenumber\n\n    msg = \"azimuth: {0:.3f} degrees, elevation: {1:.3f} degrees, freq: {2:.3f} MHz, wavenumber: {3:.3e}/m\";\n    std::cout << fmt::format(msg, az, el, freq, k0) << std::endl;\n\n    // ==== hardcode some element positions for now ====\n    std::vector<double> elx; \n    std::vector<double> ely;\n    for (int i = 0; i < 3; i++)\n    {\n        elx.push_back(20.0 * i);\n        ely.push_back(0.0);\n    }\n    if (!(elx.size() == ely.size()))\n    {\n        std::cout << fmt::format(efstr, \"Element x, y coordinates not the same size!\") << std::endl;\n    }\n    size_t Nel = elx.size();\n\n    // ==== B matrix ====\n    Eigen::MatrixXcd B;\n    B.resize(Nel, Nel);\n\n    for (size_t l = 0; l < Nel; l++)\n    {\n        for (size_t m = 0; m < Nel; m++)\n        {\n            B(l, m) = std::complex(l / 10.0, m / 10.0);\n        }\n    }\n    \n    std::cout << B << std::endl;\n\n    std::cout << header(80, \"Finished\");\n    return EXIT_SUCCESS;\n}\n\n// Run program: Ctrl + F5 or Debug > Start Without Debugging menu\n// Debug program: F5 or Debug > Start Debugging menu\n\n// Tips for Getting Started: \n//   1. Use the Solution Explorer window to add/manage files\n//   2. Use the Team Explorer window to connect to source control\n//   3. Use the Output window to see build output and other messages\n//   4. Use the Error List window to view errors\n//   5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project\n//   6. In the future, to open this project again, go to File > Open > Project and select the .sln file\n", "meta": {"hexsha": "d9dcd945067bc7eadefb0254a4831dd6610f3743", "size": 4876, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "arrayopt/arrayopt/arrayopt.cpp", "max_stars_repo_name": "danzimmerman/array-opt", "max_stars_repo_head_hexsha": "28528d2a79b84025b715ae6520c829d251dd2b6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "arrayopt/arrayopt/arrayopt.cpp", "max_issues_repo_name": "danzimmerman/array-opt", "max_issues_repo_head_hexsha": "28528d2a79b84025b715ae6520c829d251dd2b6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arrayopt/arrayopt/arrayopt.cpp", "max_forks_repo_name": "danzimmerman/array-opt", "max_forks_repo_head_hexsha": "28528d2a79b84025b715ae6520c829d251dd2b6c", "max_forks_repo_licenses": ["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.4580645161, "max_line_length": 135, "alphanum_fraction": 0.5939294504, "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5222671627092766}}
{"text": "/**\n * @file fastmks_test.cpp\n * @author Ryan Curtin\n *\n * Ensure that fast max-kernel search is correct.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/fastmks/fastmks.hpp>\n#include <mlpack/methods/fastmks/fastmks_model.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n#include \"serialization.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::tree;\nusing namespace mlpack::fastmks;\nusing namespace mlpack::kernel;\nusing namespace mlpack::metric;\n\nBOOST_AUTO_TEST_SUITE(FastMKSTest);\n\n/**\n * Compare single-tree and naive.\n */\nBOOST_AUTO_TEST_CASE(SingleTreeVsNaive)\n{\n  // First create a random dataset.\n  arma::mat data;\n  data.randn(5, 1000);\n  LinearKernel lk;\n\n  // Now run FastMKS naively.\n  FastMKS<LinearKernel> naive(data, lk, false, true);\n\n  arma::Mat<size_t> naiveIndices;\n  arma::mat naiveProducts;\n  naive.Search(10, naiveIndices, naiveProducts);\n\n  // Now run it in single-tree mode.\n  FastMKS<LinearKernel> single(data, lk, true);\n\n  arma::Mat<size_t> singleIndices;\n  arma::mat singleProducts;\n  single.Search(10, singleIndices, singleProducts);\n\n  // Compare the results.\n  for (size_t q = 0; q < singleIndices.n_cols; ++q)\n  {\n    for (size_t r = 0; r < singleIndices.n_rows; ++r)\n    {\n      BOOST_REQUIRE_EQUAL(singleIndices(r, q), naiveIndices(r, q));\n      BOOST_REQUIRE_CLOSE(singleProducts(r, q), naiveProducts(r, q), 1e-5);\n    }\n  }\n}\n\n/**\n * Compare dual-tree and naive.\n */\nBOOST_AUTO_TEST_CASE(DualTreeVsNaive)\n{\n  // First create a random dataset.\n  arma::mat data;\n  data.randn(10, 5000);\n  LinearKernel lk;\n\n  // Now run FastMKS naively.\n  FastMKS<LinearKernel> naive(data, lk, false, true);\n\n  arma::Mat<size_t> naiveIndices;\n  arma::mat naiveProducts;\n  naive.Search(10, naiveIndices, naiveProducts);\n\n  // Now run it in dual-tree mode.\n  FastMKS<LinearKernel> tree(data, lk);\n\n  arma::Mat<size_t> treeIndices;\n  arma::mat treeProducts;\n  tree.Search(10, treeIndices, treeProducts);\n\n  for (size_t q = 0; q < treeIndices.n_cols; ++q)\n  {\n    for (size_t r = 0; r < treeIndices.n_rows; ++r)\n    {\n      BOOST_REQUIRE_EQUAL(treeIndices(r, q), naiveIndices(r, q));\n      BOOST_REQUIRE_CLOSE(treeProducts(r, q), naiveProducts(r, q), 1e-5);\n    }\n  }\n}\n\n/**\n * Compare dual-tree and single-tree on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(DualTreeVsSingleTree)\n{\n  // First create a random dataset.\n  arma::mat data;\n  data.randu(8, 5000);\n  PolynomialKernel pk(5.0, 2.5);\n\n  FastMKS<PolynomialKernel> single(data, pk, true);\n\n  arma::Mat<size_t> singleIndices;\n  arma::mat singleProducts;\n  single.Search(10, singleIndices, singleProducts);\n\n  // Now run it in dual-tree mode.\n  FastMKS<PolynomialKernel> tree(data, pk);\n\n  arma::Mat<size_t> treeIndices;\n  arma::mat treeProducts;\n  tree.Search(10, treeIndices, treeProducts);\n\n  for (size_t q = 0; q < treeIndices.n_cols; ++q)\n  {\n    for (size_t r = 0; r < treeIndices.n_rows; ++r)\n    {\n      BOOST_REQUIRE_EQUAL(treeIndices(r, q), singleIndices(r, q));\n      BOOST_REQUIRE_CLOSE(treeProducts(r, q), singleProducts(r, q), 1e-5);\n    }\n  }\n}\n\n/**\n * Test sparse FastMKS (how useful is this, I'm not sure).\n */\nBOOST_AUTO_TEST_CASE(SparseFastMKSTest)\n{\n  // First create a random sparse dataset.\n  arma::sp_mat dataset;\n  dataset.sprandu(10, 100, 0.3);\n\n  FastMKS<LinearKernel, arma::sp_mat> sparsemks(dataset);\n\n  arma::mat denseset(dataset);\n  FastMKS<LinearKernel> densemks(denseset);\n\n  // Store the results in these.\n  arma::Mat<size_t> sparseIndices, denseIndices;\n  arma::mat sparseKernels, denseKernels; \n\n  // Do the searches.\n  sparsemks.Search(3, sparseIndices, sparseKernels);\n  densemks.Search(3, denseIndices, denseKernels);\n\n  // Make sure the results are the same.\n  for (size_t i = 0; i < sparseIndices.n_cols; ++i)\n  {\n    for (size_t j = 0; j < sparseIndices.n_rows; ++j)\n    {\n      if (std::abs(sparseKernels(j, i)) > 1e-15)\n        BOOST_REQUIRE_CLOSE(sparseKernels(j, i), denseKernels(j, i), 1e-5);\n      else\n        BOOST_REQUIRE_SMALL(denseKernels(j, i), 1e-15);\n      BOOST_REQUIRE_EQUAL(sparseIndices(j, i), denseIndices(j, i));\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SparsePolynomialFastMKSTest)\n{\n  // Do it again with the polynomial kernel, just to be sure.\n  arma::sp_mat dataset;\n  dataset.sprandu(10, 100, 0.3);\n  arma::mat denseset(dataset);\n\n  PolynomialKernel pk(3);\n\n  for (size_t i = 0; i < 100; ++i)\n    for (size_t j = 0; j < 100; ++j)\n      if (std::abs(pk.Evaluate(dataset.col(i), dataset.col(j))) < 1e-10)\n        BOOST_REQUIRE_SMALL(pk.Evaluate(denseset.col(i), denseset.col(j)), 1e-10);\n      else\n        BOOST_REQUIRE_CLOSE(pk.Evaluate(dataset.col(i), dataset.col(j)),\n                            pk.Evaluate(denseset.col(i), denseset.col(j)),\n                            1e-5);\n\n  FastMKS<PolynomialKernel, arma::sp_mat> sparsepoly(dataset);\n  FastMKS<PolynomialKernel> densepoly(denseset);\n\n  // Store the results in these.\n  arma::Mat<size_t> sparseIndices, denseIndices;\n  arma::mat sparseKernels, denseKernels; \n\n  // Do the searches.\n  sparsepoly.Search(3, sparseIndices, sparseKernels);\n  densepoly.Search(3, denseIndices, denseKernels);\n\n  // Make sure the results are the same.\n  for (size_t i = 0; i < sparseIndices.n_cols; ++i)\n  {\n    for (size_t j = 0; j < sparseIndices.n_rows; ++j)\n    {\n      if (std::abs(sparseKernels(j, i)) > 1e-15)\n        BOOST_REQUIRE_CLOSE(sparseKernels(j, i), denseKernels(j, i), 1e-5);\n      else\n        BOOST_REQUIRE_SMALL(denseKernels(j, i), 1e-15);\n      BOOST_REQUIRE_EQUAL(sparseIndices(j, i), denseIndices(j, i));\n    }\n  }\n}\n\n// Make sure the empty constructor works.\nBOOST_AUTO_TEST_CASE(EmptyConstructorTest)\n{\n  FastMKS<LinearKernel> f;\n\n  arma::mat queryData = arma::randu<arma::mat>(5, 100);\n  arma::Mat<size_t> indices;\n  arma::mat products;\n  BOOST_REQUIRE_THROW(f.Search(queryData, 3, indices, products),\n      std::invalid_argument);\n}\n\n// Make sure the simplest overload of Train() works.\nBOOST_AUTO_TEST_CASE(SimpleTrainTest)\n{\n  arma::mat referenceSet = arma::randu<arma::mat>(5, 100);\n\n  FastMKS<LinearKernel> f(referenceSet);\n  FastMKS<LinearKernel> f2;\n  f2.Train(referenceSet);\n\n  arma::Mat<size_t> indices, indices2;\n  arma::mat products, products2;\n\n  arma::mat querySet = arma::randu<arma::mat>(5, 20);\n\n  f.Search(querySet, 3, indices, products);\n  f2.Search(querySet, 3, indices2, products2);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, indices2.n_rows);\n  BOOST_REQUIRE_EQUAL(products.n_rows, products2.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, indices2.n_cols);\n  BOOST_REQUIRE_EQUAL(products.n_cols, products2.n_cols);\n\n  for (size_t i = 0; i < products.n_elem; ++i)\n  {\n    if (std::abs(products[i]) < 1e-5)\n      BOOST_REQUIRE_SMALL(products2[i], 1e-5);\n    else\n      BOOST_REQUIRE_CLOSE(products[i], products2[i], 1e-5);\n\n    BOOST_REQUIRE_EQUAL(indices[i], indices2[i]);\n  }\n}\n\n// Test the Train() overload that takes a kernel too.\nBOOST_AUTO_TEST_CASE(SimpleTrainKernelTest)\n{\n  arma::mat referenceSet = arma::randu<arma::mat>(5, 100);\n  GaussianKernel gk(2.0);\n\n  FastMKS<GaussianKernel> f(referenceSet, gk);\n  FastMKS<GaussianKernel> f2;\n  f2.Train(referenceSet, gk);\n\n  arma::Mat<size_t> indices, indices2;\n  arma::mat products, products2;\n\n  arma::mat querySet = arma::randu<arma::mat>(5, 20);\n\n  f.Search(querySet, 3, indices, products);\n  f2.Search(querySet, 3, indices2, products2);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, indices2.n_rows);\n  BOOST_REQUIRE_EQUAL(products.n_rows, products2.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, indices2.n_cols);\n  BOOST_REQUIRE_EQUAL(products.n_cols, products2.n_cols);\n\n  for (size_t i = 0; i < products.n_elem; ++i)\n  {\n    if (std::abs(products[i]) < 1e-5)\n      BOOST_REQUIRE_SMALL(products2[i], 1e-5);\n    else\n      BOOST_REQUIRE_CLOSE(products[i], products2[i], 1e-5);\n\n    BOOST_REQUIRE_EQUAL(indices[i], indices2[i]);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SerializationTest)\n{\n  arma::mat dataset = arma::randu<arma::mat>(5, 200);\n\n  FastMKS<LinearKernel> f(dataset);\n\n  FastMKS<LinearKernel> fXml, fText, fBinary;\n  arma::mat otherDataset = arma::randu<arma::mat>(3, 10);\n  fBinary.Train(otherDataset);\n\n  SerializeObjectAll(f, fXml, fText, fBinary);\n\n  arma::mat kernels, xmlKernels, textKernels, binaryKernels;\n  arma::Mat<size_t> indices, xmlIndices, textIndices, binaryIndices;\n\n  arma::mat querySet = arma::randu<arma::mat>(5, 100);\n\n  f.Search(querySet, 5, indices, kernels);\n  fXml.Search(querySet, 5, xmlIndices, xmlKernels);\n  fText.Search(querySet, 5, textIndices, textKernels);\n  fBinary.Search(querySet, 5, binaryIndices, binaryKernels);\n\n  CheckMatrices(indices, xmlIndices, textIndices, binaryIndices);\n  CheckMatrices(kernels, xmlKernels, textKernels, binaryKernels);\n}\n\n// Make sure that we get an exception if we try to build the wrong FastMKSModel.\nBOOST_AUTO_TEST_CASE(FastMKSModelWrongModelTest)\n{\n  PolynomialKernel pk(2.0);\n  arma::mat data = arma::randu<arma::mat>(5, 5);\n\n  FastMKSModel m(FastMKSModel::LINEAR_KERNEL);\n  BOOST_REQUIRE_THROW(m.BuildModel(data, pk, false, false, 2.0),\n      std::invalid_argument);\n}\n\n// Test the linear kernel mode of the FastMKSModel.\nBOOST_AUTO_TEST_CASE(FastMKSModelLinearTest)\n{\n  LinearKernel lk;\n  arma::mat referenceData = arma::randu<arma::mat>(10, 100);\n\n  FastMKS<LinearKernel> f(referenceData, lk);\n\n  FastMKSModel m(FastMKSModel::LINEAR_KERNEL);\n  FastMKSModel mNaive(FastMKSModel::LINEAR_KERNEL);\n  FastMKSModel mSingle(FastMKSModel::LINEAR_KERNEL);\n\n  m.BuildModel(referenceData, lk, false, false, 2.0);\n  mNaive.BuildModel(referenceData, lk, false, true, 2.0);\n  mSingle.BuildModel(referenceData, lk, true, false, 2.0);\n\n  // Now search, first monochromatically.\n  arma::Mat<size_t> indices, mIndices, mNaiveIndices, mSingleIndices;\n  arma::mat kernels, mKernels, mNaiveKernels, mSingleKernels;\n\n  f.Search(3, indices, kernels);\n  m.Search(3, mIndices, mKernels);\n  mNaive.Search(3, mNaiveIndices, mNaiveKernels);\n  mSingle.Search(3, mSingleIndices, mSingleKernels);\n\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);\n\n  for (size_t i = 0; i < indices.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);\n\n    if (std::abs(kernels[i]) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);\n    }\n  }\n\n  // Now test with a different query set.\n  arma::mat querySet = arma::randu<arma::mat>(10, 50);\n\n  f.Search(querySet, 3, indices, kernels);\n  m.Search(querySet, 3, mIndices, mKernels, 2.0);\n  mNaive.Search(querySet, 3, mNaiveIndices, mNaiveKernels, 2.0);\n  mSingle.Search(querySet, 3, mSingleIndices, mSingleKernels, 2.0);\n\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);\n\n  for (size_t i = 0; i < indices.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);\n\n    if (std::abs(kernels[i]) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);\n    }\n  }\n}\n\n// Test the polynomial kernel mode of the FastMKSModel.\nBOOST_AUTO_TEST_CASE(FastMKSModelPolynomialTest)\n{\n  PolynomialKernel pk(2.0);\n  arma::mat referenceData = arma::randu<arma::mat>(10, 100);\n\n  FastMKS<PolynomialKernel> f(referenceData, pk);\n\n  FastMKSModel m(FastMKSModel::POLYNOMIAL_KERNEL);\n  FastMKSModel mNaive(FastMKSModel::POLYNOMIAL_KERNEL);\n  FastMKSModel mSingle(FastMKSModel::POLYNOMIAL_KERNEL);\n\n  m.BuildModel(referenceData, pk, false, false, 2.0);\n  mNaive.BuildModel(referenceData, pk, false, true, 2.0);\n  mSingle.BuildModel(referenceData, pk, true, false, 2.0);\n\n  // Now search, first monochromatically.\n  arma::Mat<size_t> indices, mIndices, mNaiveIndices, mSingleIndices;\n  arma::mat kernels, mKernels, mNaiveKernels, mSingleKernels;\n\n  f.Search(3, indices, kernels);\n  m.Search(3, mIndices, mKernels);\n  mNaive.Search(3, mNaiveIndices, mNaiveKernels);\n  mSingle.Search(3, mSingleIndices, mSingleKernels);\n\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);\n\n  for (size_t i = 0; i < indices.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);\n\n    if (std::abs(kernels[i]) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);\n    }\n  }\n\n  // Now test with a different query set.\n  arma::mat querySet = arma::randu<arma::mat>(10, 50);\n\n  f.Search(querySet, 3, indices, kernels);\n  m.Search(querySet, 3, mIndices, mKernels, 2.0);\n  mNaive.Search(querySet, 3, mNaiveIndices, mNaiveKernels, 2.0);\n  mSingle.Search(querySet, 3, mSingleIndices, mSingleKernels, 2.0);\n\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);\n\n  for (size_t i = 0; i < indices.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);\n\n    if (std::abs(kernels[i]) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);\n    }\n  }\n}\n\n// Test the cosine distance mode of the FastMKSModel.\nBOOST_AUTO_TEST_CASE(FastMKSModelCosineTest)\n{\n  CosineDistance ck;\n  arma::mat referenceData = arma::randu<arma::mat>(10, 100);\n\n  FastMKS<CosineDistance> f(referenceData, ck);\n\n  FastMKSModel m(FastMKSModel::COSINE_DISTANCE);\n  FastMKSModel mNaive(FastMKSModel::COSINE_DISTANCE);\n  FastMKSModel mSingle(FastMKSModel::COSINE_DISTANCE);\n\n  m.BuildModel(referenceData, ck, false, false, 2.0);\n  mNaive.BuildModel(referenceData, ck, false, true, 2.0);\n  mSingle.BuildModel(referenceData, ck, true, false, 2.0);\n\n  // Now search, first monochromatically.\n  arma::Mat<size_t> indices, mIndices, mNaiveIndices, mSingleIndices;\n  arma::mat kernels, mKernels, mNaiveKernels, mSingleKernels;\n\n  f.Search(3, indices, kernels);\n  m.Search(3, mIndices, mKernels);\n  mNaive.Search(3, mNaiveIndices, mNaiveKernels);\n  mSingle.Search(3, mSingleIndices, mSingleKernels);\n\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);\n\n  for (size_t i = 0; i < indices.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);\n\n    if (std::abs(kernels[i]) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);\n    }\n  }\n\n  // Now test with a different query set.\n  arma::mat querySet = arma::randu<arma::mat>(10, 50);\n\n  f.Search(querySet, 3, indices, kernels);\n  m.Search(querySet, 3, mIndices, mKernels, 2.0);\n  mNaive.Search(querySet, 3, mNaiveIndices, mNaiveKernels, 2.0);\n  mSingle.Search(querySet, 3, mSingleIndices, mSingleKernels, 2.0);\n\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);\n\n  for (size_t i = 0; i < indices.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);\n\n    if (std::abs(kernels[i]) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);\n    }\n  }\n}\n\n// Test the Gaussian kernel mode of the FastMKSModel.\nBOOST_AUTO_TEST_CASE(FastMKSModelGaussianTest)\n{\n  GaussianKernel gk(1.5);\n  arma::mat referenceData = arma::randu<arma::mat>(10, 100);\n\n  FastMKS<GaussianKernel> f(referenceData, gk);\n\n  FastMKSModel m(FastMKSModel::GAUSSIAN_KERNEL);\n  FastMKSModel mNaive(FastMKSModel::GAUSSIAN_KERNEL);\n  FastMKSModel mSingle(FastMKSModel::GAUSSIAN_KERNEL);\n\n  m.BuildModel(referenceData, gk, false, false, 2.0);\n  mNaive.BuildModel(referenceData, gk, false, true, 2.0);\n  mSingle.BuildModel(referenceData, gk, true, false, 2.0);\n\n  // Now search, first monochromatically.\n  arma::Mat<size_t> indices, mIndices, mNaiveIndices, mSingleIndices;\n  arma::mat kernels, mKernels, mNaiveKernels, mSingleKernels;\n\n  f.Search(3, indices, kernels);\n  m.Search(3, mIndices, mKernels);\n  mNaive.Search(3, mNaiveIndices, mNaiveKernels);\n  mSingle.Search(3, mSingleIndices, mSingleKernels);\n\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);\n\n  for (size_t i = 0; i < indices.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);\n\n    if (std::abs(kernels[i]) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);\n    }\n  }\n\n  // Now test with a different query set.\n  arma::mat querySet = arma::randu<arma::mat>(10, 50);\n\n  f.Search(querySet, 3, indices, kernels);\n  m.Search(querySet, 3, mIndices, mKernels, 2.0);\n  mNaive.Search(querySet, 3, mNaiveIndices, mNaiveKernels, 2.0);\n  mSingle.Search(querySet, 3, mSingleIndices, mSingleKernels, 2.0);\n\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);\n\n  for (size_t i = 0; i < indices.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);\n\n    if (std::abs(kernels[i]) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);\n    }\n  }\n}\n\n// Test the Epanechnikov kernel mode of the FastMKSModel.\nBOOST_AUTO_TEST_CASE(FastMKSModelEpanTest)\n{\n  EpanechnikovKernel ek(2.5);\n  arma::mat referenceData = arma::randu<arma::mat>(10, 100);\n\n  FastMKS<EpanechnikovKernel> f(referenceData, ek);\n\n  FastMKSModel m(FastMKSModel::EPANECHNIKOV_KERNEL);\n  FastMKSModel mNaive(FastMKSModel::EPANECHNIKOV_KERNEL);\n  FastMKSModel mSingle(FastMKSModel::EPANECHNIKOV_KERNEL);\n\n  m.BuildModel(referenceData, ek, false, false, 2.0);\n  mNaive.BuildModel(referenceData, ek, false, true, 2.0);\n  mSingle.BuildModel(referenceData, ek, true, false, 2.0);\n\n  // Now search, first monochromatically.\n  arma::Mat<size_t> indices, mIndices, mNaiveIndices, mSingleIndices;\n  arma::mat kernels, mKernels, mNaiveKernels, mSingleKernels;\n\n  f.Search(3, indices, kernels);\n  m.Search(3, mIndices, mKernels);\n  mNaive.Search(3, mNaiveIndices, mNaiveKernels);\n  mSingle.Search(3, mSingleIndices, mSingleKernels);\n\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);\n\n  for (size_t i = 0; i < indices.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);\n\n    if (std::abs(kernels[i]) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);\n    }\n  }\n\n  // Now test with a different query set.\n  arma::mat querySet = arma::randu<arma::mat>(10, 50);\n\n  f.Search(querySet, 3, indices, kernels);\n  m.Search(querySet, 3, mIndices, mKernels, 2.0);\n  mNaive.Search(querySet, 3, mNaiveIndices, mNaiveKernels, 2.0);\n  mSingle.Search(querySet, 3, mSingleIndices, mSingleKernels, 2.0);\n\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);\n\n  for (size_t i = 0; i < indices.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);\n\n    if (std::abs(kernels[i]) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);\n    }\n  }\n}\n\n// Test the triangular kernel mode of the FastMKSModel.\nBOOST_AUTO_TEST_CASE(FastMKSModelTriangularTest)\n{\n  TriangularKernel tk(2.0);\n  arma::mat referenceData = arma::randu<arma::mat>(10, 100);\n\n  FastMKS<TriangularKernel> f(referenceData, tk);\n\n  FastMKSModel m(FastMKSModel::TRIANGULAR_KERNEL);\n  FastMKSModel mNaive(FastMKSModel::TRIANGULAR_KERNEL);\n  FastMKSModel mSingle(FastMKSModel::TRIANGULAR_KERNEL);\n\n  m.BuildModel(referenceData, tk, false, false, 2.0);\n  mNaive.BuildModel(referenceData, tk, false, true, 2.0);\n  mSingle.BuildModel(referenceData, tk, true, false, 2.0);\n\n  // Now search, first monochromatically.\n  arma::Mat<size_t> indices, mIndices, mNaiveIndices, mSingleIndices;\n  arma::mat kernels, mKernels, mNaiveKernels, mSingleKernels;\n\n  f.Search(3, indices, kernels);\n  m.Search(3, mIndices, mKernels);\n  mNaive.Search(3, mNaiveIndices, mNaiveKernels);\n  mSingle.Search(3, mSingleIndices, mSingleKernels);\n\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);\n\n  for (size_t i = 0; i < indices.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);\n\n    if (std::abs(kernels[i]) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);\n    }\n  }\n\n  // Now test with a different query set.\n  arma::mat querySet = arma::randu<arma::mat>(10, 50);\n\n  f.Search(querySet, 3, indices, kernels);\n  m.Search(querySet, 3, mIndices, mKernels, 2.0);\n  mNaive.Search(querySet, 3, mNaiveIndices, mNaiveKernels, 2.0);\n  mSingle.Search(querySet, 3, mSingleIndices, mSingleKernels, 2.0);\n\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);\n  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);\n\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);\n  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);\n  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);\n\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);\n  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);\n\n  for (size_t i = 0; i < indices.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);\n    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);\n\n    if (std::abs(kernels[i]) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);\n      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "11f93f0c05448e58ba7c3ee2bad13c42c765ee29", "size": 32658, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/fastmks_test.cpp", "max_stars_repo_name": "decltypeme/mlpack", "max_stars_repo_head_hexsha": "e3b418918fffce382ce9d8ceee9d9349ca199611", "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:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:28.000Z", "max_issues_repo_path": "src/mlpack/tests/fastmks_test.cpp", "max_issues_repo_name": "decltypeme/mlpack", "max_issues_repo_head_hexsha": "e3b418918fffce382ce9d8ceee9d9349ca199611", "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/fastmks_test.cpp", "max_forks_repo_name": "decltypeme/mlpack", "max_forks_repo_head_hexsha": "e3b418918fffce382ce9d8ceee9d9349ca199611", "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": 34.1253918495, "max_line_length": 82, "alphanum_fraction": 0.7306019964, "num_tokens": 9657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5222671457707037}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n#include \"IO/readPLY.h\"\n#include \"IO/writePLY.h\"\n\n#include \"visualization/plotMesh.h\"\n#include \"visualization/plotTwoMeshes.h\"\n\n#include \"mesh/computeNormals.h\"\n#include \"mesh/computeFacesCentroids.h\"\n#include \"sdf.h\"\n\nint main() {\n    bool visualization = true;\n    int grid_resolution = 100;\n    double bounding_box_scale = 1;\n\n    // IO: load files\n    std::cout << \"Progress: load data\\n\";\n    Eigen::MatrixXd V, faces_V;\n    Eigen::MatrixXi F;\n    Eigen::MatrixXd N, faces_N;\n    Eigen::MatrixXi RGB;\n\n    readPLY(\"../data/Lucy100k.ply\", V, F, N, RGB);\n\n    faces_V = compute_faces_centroids(V,F);\n    faces_N = compute_faces_normals(V,F);\n\n    if (visualization)\n        plot_mesh(V,F);\n\n    // grid_resolution is used to define the number of grids\n\n    SDF sdf(faces_V, faces_N, grid_resolution, bounding_box_scale);\n    \n    Eigen::MatrixXd graph_V;\n    Eigen::MatrixXi graph_E;\n    sdf.generate_graph(graph_V, graph_E);\n    sdf.print_to_folder(\"../data/sdf/\");\n\n}\n", "meta": {"hexsha": "015e51662d4482049dac09e39097dda210d6c6e4", "size": 1058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/test_sdf.cpp", "max_stars_repo_name": "rFalque/voxelization_and_sdf", "max_stars_repo_head_hexsha": "6ae111412f2383244b7caf04affd561f64ce9a4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2020-02-13T04:42:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T23:27:05.000Z", "max_issues_repo_path": "app/test_sdf.cpp", "max_issues_repo_name": "rFalque/voxelization_and_sdf", "max_issues_repo_head_hexsha": "6ae111412f2383244b7caf04affd561f64ce9a4f", "max_issues_repo_licenses": ["MIT"], "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/test_sdf.cpp", "max_forks_repo_name": "rFalque/voxelization_and_sdf", "max_forks_repo_head_hexsha": "6ae111412f2383244b7caf04affd561f64ce9a4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-01-15T10:32:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T01:44:27.000Z", "avg_line_length": 23.5111111111, "max_line_length": 67, "alphanum_fraction": 0.6843100189, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.640635841117624, "lm_q1q2_score": 0.5222671457707037}}
{"text": "// File: recursator.cpp\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/mtl/recursion/matrix_recursator.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl; using std::cout;\n\n    // Z-order matrix\n    typedef morton_dense<double, recursion::morton_z_mask>  matrix_type;\n    matrix_type                                             A(10, 10);\n    mat::hessian_setup(A, 3.0);\n\n    // Define a recursator over A\n    mat::recursator<matrix_type>                          rec(A);\n\n    // Access a quadrant of the matrix\n    cout << \"Upper right quadrant (north_east) of A is \\n\" << *north_east(rec) << \"\\n\";\n\n    // Access a quadrant's quadrant of the matrix\n    cout << \"Lower left (south_west) of upper right quadrant (north_east) of A is \\n\" \n\t << *south_west(north_east(rec)) << \"\\n\";\n\n    cout << \"The virtual bound of 'rec' is \" << rec.bound() << \"\\n\";\n\n    return 0;\n}\n\n", "meta": {"hexsha": "acc7f2783b792ac367bccd90530824f9d1de339f", "size": 907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/recursator.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/recursator.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/recursator.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.2580645161, "max_line_length": 87, "alphanum_fraction": 0.6030871003, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5222226630532791}}
{"text": "#define BOOST_TEST_MODULE test_mul\n#include <boost/test/included/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <mave/mave.hpp>\n#include <tests/generate_random_matrices.hpp>\n#include <tests/tolerance.hpp>\n\ntypedef boost::mpl::list<\n    mave::vector<double, 3>,    mave::vector<float, 3>,\n    mave::matrix<double, 3, 3>, mave::matrix<float, 3, 3>\n    > test_targets;\n\nconstexpr std::size_t N = 12000;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(multiplication_1arg, T, test_targets)\n{\n    std::mt19937 mt(123456789);\n    const auto scalars = mave::test::generate_random<typename T::value_type>(N, mt);\n    const auto vectors = mave::test::generate_random<T>(N, mt);\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const auto& s  = scalars.at(i);\n        const auto& v1 = vectors.at(i);\n\n        const auto v2 = s * v1;\n        for(std::size_t j=0; j<v1.size(); ++j)\n        {\n            BOOST_TEST(v2[j] == s * v1[j],\n                       mave::test::tolerance<typename T::value_type>());\n        }\n\n        const auto v3 = v1 * s;\n        for(std::size_t j=0; j<v1.size(); ++j)\n        {\n            BOOST_TEST(v3[j] == v1[j] * s,\n                       mave::test::tolerance<typename T::value_type>());\n        }\n        BOOST_TEST(v1.diagnosis());\n        BOOST_TEST(v2.diagnosis());\n        BOOST_TEST(v3.diagnosis());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(multiplication_2arg, T, test_targets)\n{\n    std::mt19937 mt(123456789);\n    const auto scalars = mave::test::generate_random<typename T::value_type>(N, mt);\n    const auto vectors = mave::test::generate_random<T>(N, mt);\n\n    for(std::size_t i=0; i<N; i+=2)\n    {\n        const auto& s1 = scalars.at(i);\n        const auto& s2 = scalars.at(i+1);\n        const auto& v11 = vectors.at(i);\n        const auto& v12 = vectors.at(i+1);\n\n        const auto v2 = std::make_tuple(s1, s2) * std::tie(v11, v12);\n\n        const auto v21 = std::get<0>(v2);\n        const auto v22 = std::get<1>(v2);\n\n        for(std::size_t j=0; j<v21.size(); ++j)\n        {\n            BOOST_TEST(v21[j] == s1 * v11[j],\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v22[j] == s2 * v12[j],\n                       mave::test::tolerance<typename T::value_type>());\n        }\n\n        const auto v3 = std::tie(v11, v12) * std::make_tuple(s1, s2);\n\n        const auto v31 = std::get<0>(v3);\n        const auto v32 = std::get<1>(v3);\n\n        for(std::size_t j=0; j<v31.size(); ++j)\n        {\n            BOOST_TEST(v31[j] == v11[j] * s1,\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v32[j] == v12[j] * s2,\n                       mave::test::tolerance<typename T::value_type>());\n        }\n        BOOST_TEST(v11.diagnosis());\n        BOOST_TEST(v12.diagnosis());\n        BOOST_TEST(v21.diagnosis());\n        BOOST_TEST(v22.diagnosis());\n        BOOST_TEST(v31.diagnosis());\n        BOOST_TEST(v32.diagnosis());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(multiplication_3arg, T, test_targets)\n{\n    std::mt19937 mt(123456789);\n    const auto scalars = mave::test::generate_random<typename T::value_type>(N, mt);\n    const auto vectors = mave::test::generate_random<T>(N, mt);\n\n    for(std::size_t i=0; i<N; i+=3)\n    {\n        const auto& s1  = scalars.at(i);\n        const auto& s2  = scalars.at(i+1);\n        const auto& s3  = scalars.at(i+2);\n        const auto& v11 = vectors.at(i);\n        const auto& v12 = vectors.at(i+1);\n        const auto& v13 = vectors.at(i+2);\n\n        const auto v2 = std::make_tuple(s1, s2, s3) * std::tie(v11, v12, v13);\n\n        const auto v21 = std::get<0>(v2);\n        const auto v22 = std::get<1>(v2);\n        const auto v23 = std::get<2>(v2);\n\n        for(std::size_t j=0; j<v21.size(); ++j)\n        {\n            BOOST_TEST(v21[j] == s1 * v11[j],\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v22[j] == s2 * v12[j],\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v23[j] == s3 * v13[j],\n                       mave::test::tolerance<typename T::value_type>());\n        }\n\n        const auto v3 = std::tie(v11, v12, v13) * std::make_tuple(s1, s2, s3);\n\n        const auto v31 = std::get<0>(v3);\n        const auto v32 = std::get<1>(v3);\n        const auto v33 = std::get<2>(v3);\n\n        for(std::size_t j=0; j<v31.size(); ++j)\n        {\n            BOOST_TEST(v31[j] == v11[j] * s1,\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v32[j] == v12[j] * s2,\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v33[j] == v13[j] * s3,\n                       mave::test::tolerance<typename T::value_type>());\n        }\n        BOOST_TEST(v11.diagnosis());\n        BOOST_TEST(v12.diagnosis());\n        BOOST_TEST(v13.diagnosis());\n\n        BOOST_TEST(v21.diagnosis());\n        BOOST_TEST(v22.diagnosis());\n        BOOST_TEST(v23.diagnosis());\n\n        BOOST_TEST(v31.diagnosis());\n        BOOST_TEST(v32.diagnosis());\n        BOOST_TEST(v33.diagnosis());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(multiplication_4arg, T, test_targets)\n{\n    std::mt19937 mt(123456789);\n    const auto scalars = mave::test::generate_random<typename T::value_type>(N, mt);\n    const auto vectors = mave::test::generate_random<T>(N, mt);\n\n    for(std::size_t i=0; i<N; i+=4)\n    {\n        const auto& s1  = scalars.at(i);\n        const auto& s2  = scalars.at(i+1);\n        const auto& s3  = scalars.at(i+2);\n        const auto& s4  = scalars.at(i+3);\n        const auto& v11 = vectors.at(i);\n        const auto& v12 = vectors.at(i+1);\n        const auto& v13 = vectors.at(i+2);\n        const auto& v14 = vectors.at(i+3);\n\n        const auto v2 = std::make_tuple(s1, s2, s3, s4) * std::tie(v11, v12, v13, v14);\n\n        const auto v21 = std::get<0>(v2);\n        const auto v22 = std::get<1>(v2);\n        const auto v23 = std::get<2>(v2);\n        const auto v24 = std::get<3>(v2);\n\n        for(std::size_t j=0; j<v21.size(); ++j)\n        {\n            BOOST_TEST(v21[j] == s1 * v11[j],\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v22[j] == s2 * v12[j],\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v23[j] == s3 * v13[j],\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v24[j] == s4 * v14[j],\n                       mave::test::tolerance<typename T::value_type>());\n        }\n\n        const auto v3 = std::tie(v11, v12, v13, v14) * std::make_tuple(s1, s2, s3, s4);\n\n        const auto v31 = std::get<0>(v3);\n        const auto v32 = std::get<1>(v3);\n        const auto v33 = std::get<2>(v3);\n        const auto v34 = std::get<3>(v3);\n\n        for(std::size_t j=0; j<v31.size(); ++j)\n        {\n            BOOST_TEST(v31[j] == v11[j] * s1,\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v32[j] == v12[j] * s2,\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v33[j] == v13[j] * s3,\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v34[j] == v14[j] * s4,\n                       mave::test::tolerance<typename T::value_type>());\n        }\n        BOOST_TEST(v11.diagnosis());\n        BOOST_TEST(v12.diagnosis());\n        BOOST_TEST(v13.diagnosis());\n        BOOST_TEST(v14.diagnosis());\n\n        BOOST_TEST(v21.diagnosis());\n        BOOST_TEST(v22.diagnosis());\n        BOOST_TEST(v23.diagnosis());\n        BOOST_TEST(v24.diagnosis());\n\n        BOOST_TEST(v31.diagnosis());\n        BOOST_TEST(v32.diagnosis());\n        BOOST_TEST(v33.diagnosis());\n        BOOST_TEST(v34.diagnosis());\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(mul_assign_1arg, T, test_targets)\n{\n    std::mt19937 mt(123456789);\n    const auto scalars = mave::test::generate_random<typename T::value_type>(N, mt);\n    const auto vectors = mave::test::generate_random<T>(N, mt);\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const auto& s  = scalars.at(i);\n        const auto& v1 = vectors.at(i);\n\n        auto v2 = v1;\n        v2 *= s;\n        for(std::size_t j=0; j<v1.size(); ++j)\n        {\n            BOOST_TEST(v2[j] == v1[j] * s,\n                       mave::test::tolerance<typename T::value_type>());\n        }\n        BOOST_TEST(v1.diagnosis());\n        BOOST_TEST(v2.diagnosis());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(mul_assign_2arg, T, test_targets)\n{\n    std::mt19937 mt(123456789);\n    const auto scalars = mave::test::generate_random<typename T::value_type>(N, mt);\n    const auto vectors = mave::test::generate_random<T>(N, mt);\n\n    for(std::size_t i=0; i<N; i+=2)\n    {\n        const auto& s1 = scalars.at(i);\n        const auto& s2 = scalars.at(i+1);\n        const auto& v11 = vectors.at(i);\n        const auto& v12 = vectors.at(i+1);\n\n        auto v21(v11);\n        auto v22(v12);\n        std::tie(v21, v22) *= std::make_tuple(s1, s2);\n\n        for(std::size_t j=0; j<v21.size(); ++j)\n        {\n            BOOST_TEST(v21[j] == v11[j] * s1,\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v22[j] == v12[j] * s2,\n                       mave::test::tolerance<typename T::value_type>());\n        }\n\n        BOOST_TEST(v11.diagnosis());\n        BOOST_TEST(v12.diagnosis());\n\n        BOOST_TEST(v21.diagnosis());\n        BOOST_TEST(v22.diagnosis());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(mul_assign_3arg, T, test_targets)\n{\n    std::mt19937 mt(123456789);\n    const auto scalars = mave::test::generate_random<typename T::value_type>(N, mt);\n    const auto vectors = mave::test::generate_random<T>(N, mt);\n\n    for(std::size_t i=0; i<N; i+=3)\n    {\n        const auto& s1  = scalars.at(i);\n        const auto& s2  = scalars.at(i+1);\n        const auto& s3  = scalars.at(i+2);\n        const auto& v11 = vectors.at(i);\n        const auto& v12 = vectors.at(i+1);\n        const auto& v13 = vectors.at(i+2);\n\n        auto v21(v11);\n        auto v22(v12);\n        auto v23(v13);\n        std::tie(v21, v22, v23) *= std::make_tuple(s1, s2, s3);\n\n        for(std::size_t j=0; j<v21.size(); ++j)\n        {\n            BOOST_TEST(v21[j] == v11[j] * s1,\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v22[j] == v12[j] * s2,\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v23[j] == v13[j] * s3,\n                       mave::test::tolerance<typename T::value_type>());\n        }\n\n        BOOST_TEST(v11.diagnosis());\n        BOOST_TEST(v12.diagnosis());\n        BOOST_TEST(v13.diagnosis());\n\n        BOOST_TEST(v21.diagnosis());\n        BOOST_TEST(v22.diagnosis());\n        BOOST_TEST(v23.diagnosis());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(mul_assign_4arg, T, test_targets)\n{\n    std::mt19937 mt(123456789);\n    const auto scalars = mave::test::generate_random<typename T::value_type>(N, mt);\n    const auto vectors = mave::test::generate_random<T>(N, mt);\n\n    for(std::size_t i=0; i<N; i+=4)\n    {\n        const auto& s1  = scalars.at(i);\n        const auto& s2  = scalars.at(i+1);\n        const auto& s3  = scalars.at(i+2);\n        const auto& s4  = scalars.at(i+3);\n        const auto& v11 = vectors.at(i);\n        const auto& v12 = vectors.at(i+1);\n        const auto& v13 = vectors.at(i+2);\n        const auto& v14 = vectors.at(i+3);\n\n        auto v21(v11);\n        auto v22(v12);\n        auto v23(v13);\n        auto v24(v14);\n        std::tie(v21, v22, v23, v24) *= std::make_tuple(s1, s2, s3, s4);\n\n        for(std::size_t j=0; j<v21.size(); ++j)\n        {\n            BOOST_TEST(v21[j] == v11[j] * s1,\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v22[j] == v12[j] * s2,\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v23[j] == v13[j] * s3,\n                       mave::test::tolerance<typename T::value_type>());\n            BOOST_TEST(v24[j] == v14[j] * s4,\n                       mave::test::tolerance<typename T::value_type>());\n        }\n\n        BOOST_TEST(v11.diagnosis());\n        BOOST_TEST(v12.diagnosis());\n        BOOST_TEST(v13.diagnosis());\n        BOOST_TEST(v14.diagnosis());\n\n        BOOST_TEST(v21.diagnosis());\n        BOOST_TEST(v22.diagnosis());\n        BOOST_TEST(v23.diagnosis());\n        BOOST_TEST(v24.diagnosis());\n    }\n}\n\n\n", "meta": {"hexsha": "af8d8db47bd6448607623c4a17e52fccc2290342", "size": 12485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_mul.cpp", "max_stars_repo_name": "ToruNiina/mave", "max_stars_repo_head_hexsha": "163cbf273003c3fb940338cf82b1fa154a3012c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T17:46:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T00:29:04.000Z", "max_issues_repo_path": "tests/test_mul.cpp", "max_issues_repo_name": "ToruNiina/mave", "max_issues_repo_head_hexsha": "163cbf273003c3fb940338cf82b1fa154a3012c1", "max_issues_repo_licenses": ["MIT"], "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_mul.cpp", "max_forks_repo_name": "ToruNiina/mave", "max_forks_repo_head_hexsha": "163cbf273003c3fb940338cf82b1fa154a3012c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-04T11:02:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T11:02:20.000Z", "avg_line_length": 33.8346883469, "max_line_length": 87, "alphanum_fraction": 0.5370444533, "num_tokens": 3604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5222226352506127}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#define BOOST_UBLAS_NO_ELEMENT_PROXIES\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/blas/level3.hpp>\n#include <boost/numeric/bindings/lower.hpp>\n#include <boost/numeric/bindings/upper.hpp>\n#include <boost/numeric/bindings/unit_lower.hpp>\n#include <boost/numeric/bindings/unit_upper.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/bindings/conj.hpp>\n#include <boost/numeric/bindings/left.hpp>\n#include <boost/numeric/bindings/right.hpp>\n#include \"print.hpp\"\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef std::complex<double> complex;\n    typedef ublas::vector<complex> vector;\n    typedef ublas::matrix<complex, ublas::column_major> matrix;\n    typedef typename vector::size_type size_type;\n    rand_normal<complex>::reset();\n    size_type n=8;\n    matrix A_l(n, n), A_u(n, n), B(n, n);\n    for (size_type j=0; j<n; ++j) {\n      for (size_type i=0; i<j; ++i) {\n    \tA_u(i, j)=rand_normal<complex>::get();\n\tA_l(j, i)=rand_normal<complex>::get();\n      }\n      A_u(j, j)=rand_normal<complex>::get();\n      A_l(j, j)=rand_normal<complex>::get();\n      for (size_type i=j+1; i<n; ++i) {\n    \tA_u(i, j)=0;\n\tA_l(j, i)=0;\n      }\n    }\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i)\n\tB(j, i)=rand_normal<complex>::get();\n    complex alpha=rand_normal<complex>::get();\n    {\n      matrix B1(alpha*ublas::prod(A_l, B));\n      matrix B2(B);\n      blas::trmm(blas::left(), alpha, blas::lower(A_l), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (left multiply, lower):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left multiply, lower):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(A_u, B));\n      matrix B2(B);\n      blas::trmm(blas::left(), alpha, blas::upper(A_u), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (left multiply, upper):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left multiply, upper):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(ublas::trans(A_l), B));\n      matrix B2(B);\n      blas::trmm(blas::left(), alpha, blas::trans(blas::lower(A_l)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (left multiply, lower):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left multiply, lower):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(ublas::trans(A_u), B));\n      matrix B2(B);\n      blas::trmm(blas::left(), alpha, blas::trans(blas::upper(A_u)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (left multiply, upper):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left multiply, upper):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(ublas::conj(ublas::trans(A_l)), B));\n      matrix B2(B);\n      blas::trmm(blas::left(), alpha, blas::conj(blas::lower(A_l)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (left multiply, lower):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left multiply, lower):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(ublas::conj(ublas::trans(A_u)), B));\n      matrix B2(B);\n      blas::trmm(blas::left(), alpha, blas::conj(blas::upper(A_u)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (left multiply, upper):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left multiply, upper):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n\n    {\n      matrix B1(alpha*ublas::prod(B, A_l));\n      matrix B2(B);\n      blas::trmm(blas::right(), alpha, blas::lower(A_l), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (right multiply, lower):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (right multiply, lower):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(B, A_u));\n      matrix B2(B);\n      blas::trmm(blas::right(), alpha, blas::upper(A_u), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (right multiply, upper):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (right multiply, upper):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(B, ublas::trans(A_l)));\n      matrix B2(B);\n      blas::trmm(blas::right(), alpha, blas::trans(blas::lower(A_l)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (right multiply, lower):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (right multiply, lower):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(B, ublas::trans(A_u)));\n      matrix B2(B);\n      blas::trmm(blas::right(), alpha, blas::trans(blas::upper(A_u)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (right multiply, upper):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (right multiply, upper):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(B, ublas::conj(ublas::trans(A_l))));\n      matrix B2(B);\n      blas::trmm(blas::right(), alpha, blas::conj(blas::lower(A_l)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (right multiply, lower):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (right multiply, lower):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(B, ublas::conj(ublas::trans(A_u))));\n      matrix B2(B);\n      blas::trmm(blas::right(), alpha, blas::conj(blas::upper(A_u)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (right multiply, upper):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (right multiply, upper):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n\n    for (size_type i=0; i<n; ++i) {\n      A_l(i, i)=1;\n      A_u(i, i)=1;\n    }\n\n    {\n      matrix B1(alpha*ublas::prod(A_l, B));\n      matrix B2(B);\n      blas::trmm(blas::left(), alpha, blas::unit_lower(A_l), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (left multiply, unit_lower):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left multiply, unit_lower):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(A_u, B));\n      matrix B2(B);\n      blas::trmm(blas::left(), alpha, blas::unit_upper(A_u), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (left multiply, unit_upper):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left multiply, unit_upper):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(ublas::trans(A_l), B));\n      matrix B2(B);\n      blas::trmm(blas::left(), alpha, blas::trans(blas::unit_lower(A_l)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (left multiply, unit_lower):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left multiply, unit_lower):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(ublas::trans(A_u), B));\n      matrix B2(B);\n      blas::trmm(blas::left(), alpha, blas::trans(blas::unit_upper(A_u)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (left multiply, unit_upper):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left multiply, unit_upper):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(ublas::conj(ublas::trans(A_l)), B));\n      matrix B2(B);\n      blas::trmm(blas::left(), alpha, blas::conj(blas::unit_lower(A_l)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (left multiply, unit_lower):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left multiply, unit_lower):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(ublas::conj(ublas::trans(A_u)), B));\n      matrix B2(B);\n      blas::trmm(blas::left(), alpha, blas::conj(blas::unit_upper(A_u)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (left multiply, unit_upper):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left multiply, unit_upper):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n\n    {\n      matrix B1(alpha*ublas::prod(B, A_l));\n      matrix B2(B);\n      blas::trmm(blas::right(), alpha, blas::unit_lower(A_l), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (right multiply, unit_lower):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (right multiply, unit_lower):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(B, A_u));\n      matrix B2(B);\n      blas::trmm(blas::right(), alpha, blas::unit_upper(A_u), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (right multiply, unit_upper):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (right multiply, unit_upper):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(B, ublas::trans(A_l)));\n      matrix B2(B);\n      blas::trmm(blas::right(), alpha, blas::trans(blas::unit_lower(A_l)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (right multiply, unit_lower):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (right multiply, unit_lower):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(B, ublas::trans(A_u)));\n      matrix B2(B);\n      blas::trmm(blas::right(), alpha, blas::trans(blas::unit_upper(A_u)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (right multiply, unit_upper):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (right multiply, unit_upper):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(B, ublas::conj(ublas::trans(A_l))));\n      matrix B2(B);\n      blas::trmm(blas::right(), alpha, blas::conj(blas::unit_lower(A_l)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (right multiply, unit_lower):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (right multiply, unit_lower):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix B1(alpha*ublas::prod(B, ublas::conj(ublas::trans(A_u))));\n      matrix B2(B);\n      blas::trmm(blas::right(), alpha, blas::conj(blas::unit_upper(A_u)), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n     \t\t<< \"using ublas (right multiply, unit_upper):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (right multiply, unit_upper):\\n\" << print_mat(B2) << '\\n'\n    \t\t<< '\\n';\n    }\n    \n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "17ebbe8b4ce6cec528c6f279c4f0fa71af17a3fa", "size": 10968, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/trmm.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/trmm.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/trmm.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.8836363636, "max_line_length": 80, "alphanum_fraction": 0.5591721371, "num_tokens": 3493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6584175139669998, "lm_q1q2_score": 0.5221948486910757}}
{"text": "<<<<<<< HEAD\r\n/*    Copyright (c) 2010-2018, Delft University of Technology\r\n=======\r\n/*    Copyright (c) 2010-2019, Delft University of Technology\r\n>>>>>>> origin/master\r\n *    All rigths reserved\r\n *\r\n *    This file is part of the Tudat. Redistribution and use in source and\r\n *    binary forms, with or without modification, are permitted exclusively\r\n *    under the terms of the Modified BSD license. You should have received\r\n *    a copy of the license with this file. If not, please or visit:\r\n *    http://tudat.tudelft.nl/LICENSE.\r\n *\r\n */\r\n\r\n#include <cmath>\r\n#include <limits>\r\n#include <stdexcept>\r\n\r\n#include <boost/math/constants/constants.hpp>\r\n\r\n#include <Eigen/Core>\r\n\r\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\r\n\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\r\n#include \"Tudat/Astrodynamics/Gravitation/centralGravityModel.h\"\r\n#include \"Tudat/Astrodynamics/Gravitation/centralJ2GravityModel.h\"\r\n#include \"Tudat/Astrodynamics/Gravitation/centralJ2J3GravityModel.h\"\r\n#include \"Tudat/Astrodynamics/Gravitation/sphericalHarmonicsGravityModel.h\"\r\n#include \"Tudat/Mathematics/BasicMathematics/coordinateConversions.h\"\r\n#include \"Tudat/Mathematics/BasicMathematics/legendrePolynomials.h\"\r\n#include \"Tudat/Mathematics/BasicMathematics/sphericalHarmonics.h\"\r\n\r\nnamespace tudat\r\n{\r\n\r\nnamespace gravitation\r\n{\r\n\r\n//! Compute gravitational acceleration due to multiple spherical harmonics terms, defined using geodesy-normalization.\r\nEigen::Vector3d computeGeodesyNormalizedGravitationalAccelerationSum(\r\n        const Eigen::Vector3d& positionOfBodySubjectToAcceleration,\r\n        const double gravitationalParameter,\r\n        const double equatorialRadius,\r\n        const Eigen::MatrixXd& cosineHarmonicCoefficients,\r\n        const Eigen::MatrixXd& sineHarmonicCoefficients,\r\n        std::shared_ptr< basic_mathematics::SphericalHarmonicsCache > sphericalHarmonicsCache,\r\n        std::map< std::pair< int, int >, Eigen::Vector3d >& accelerationPerTerm,\r\n        const bool saveSeparateTerms,\r\n        const Eigen::Matrix3d& accelerationRotation )\r\n{\r\n    // Set highest degree and order.\r\n    const int highestDegree = cosineHarmonicCoefficients.rows( );\r\n    const int highestOrder = cosineHarmonicCoefficients.cols( );\r\n\r\n    // Declare spherical position vector.\r\n    Eigen::Vector3d sphericalpositionOfBodySubjectToAcceleration = coordinate_conversions::\r\n            convertCartesianToSpherical( positionOfBodySubjectToAcceleration );\r\n    sphericalpositionOfBodySubjectToAcceleration( 1 ) = mathematical_constants::PI / 2.0 -\r\n            sphericalpositionOfBodySubjectToAcceleration( 1 );\r\n\r\n    double sineOfAngle = std::sin( sphericalpositionOfBodySubjectToAcceleration( 1 ) );\r\n    sphericalHarmonicsCache->update( sphericalpositionOfBodySubjectToAcceleration( 0 ),\r\n                                     sineOfAngle,\r\n                                     sphericalpositionOfBodySubjectToAcceleration( 2 ),\r\n                                     equatorialRadius );\r\n\r\n    std::shared_ptr< basic_mathematics::LegendreCache > legendreCacheReference =\r\n            sphericalHarmonicsCache->getLegendreCache( );\r\n\r\n    // Compute gradient premultiplier.\r\n    const double preMultiplier = gravitationalParameter / equatorialRadius;\r\n\r\n    // Initialize gradient vector.\r\n    Eigen::Vector3d sphericalGradient = Eigen::Vector3d::Zero( );\r\n\r\n    Eigen::Matrix3d transformationToCartesianCoordinates = coordinate_conversions::getSphericalToCartesianGradientMatrix(\r\n                positionOfBodySubjectToAcceleration );\r\n\r\n    // Loop through all degrees.\r\n    for ( int degree = 0; degree < highestDegree; degree++ )\r\n    {\r\n        // Loop through all orders.\r\n        for ( int order = 0; ( order <= degree ) && ( order < highestOrder ); order++ )\r\n        {\r\n            // Compute geodesy-normalized Legendre polynomials.\r\n            const double legendrePolynomial = legendreCacheReference->getLegendrePolynomial( degree, order );\r\n\r\n            // Compute geodesy-normalized Legendre polynomial derivative.\r\n            const double legendrePolynomialDerivative = legendreCacheReference->getLegendrePolynomialDerivative(\r\n                        degree, order );\r\n\r\n            // Compute the potential gradient of a single spherical harmonic term.\r\n            if( saveSeparateTerms )\r\n            {\r\n                accelerationPerTerm[ std::make_pair( degree, order ) ] =\r\n                        basic_mathematics::computePotentialGradient(\r\n                            sphericalpositionOfBodySubjectToAcceleration,\r\n                            preMultiplier,\r\n                            degree,\r\n                            order,\r\n                            cosineHarmonicCoefficients( degree, order ),\r\n                            sineHarmonicCoefficients( degree, order ),\r\n                            legendrePolynomial,\r\n                            legendrePolynomialDerivative, sphericalHarmonicsCache );\r\n                sphericalGradient += accelerationPerTerm[ std::make_pair( degree, order ) ];\r\n                accelerationPerTerm[ std::make_pair( degree, order ) ] =\r\n                        accelerationRotation * (\r\n                            transformationToCartesianCoordinates * accelerationPerTerm[ std::make_pair( degree, order ) ] );\r\n            }\r\n            else\r\n            {\r\n                // Compute the potential gradient of a single spherical harmonic term.\r\n                sphericalGradient += basic_mathematics::computePotentialGradient(\r\n                            sphericalpositionOfBodySubjectToAcceleration,\r\n                            preMultiplier,\r\n                            degree,\r\n                            order,\r\n                            cosineHarmonicCoefficients( degree, order ),\r\n                            sineHarmonicCoefficients( degree, order ),\r\n                            legendrePolynomial,\r\n                            legendrePolynomialDerivative, sphericalHarmonicsCache );\r\n            }\r\n        }\r\n    }\r\n\r\n\r\n    // Convert from spherical gradient to Cartesian gradient (which equals acceleration vector) and\r\n    // return the resulting acceleration vector.\r\n    return accelerationRotation * ( transformationToCartesianCoordinates * sphericalGradient );\r\n}\r\n\r\n//! Compute gravitational acceleration due to single spherical harmonics term.\r\nEigen::Vector3d computeSingleGeodesyNormalizedGravitationalAcceleration(\r\n        const Eigen::Vector3d& positionOfBodySubjectToAcceleration,\r\n        const double gravitationalParameter,\r\n        const double equatorialRadius,\r\n        const int degree,\r\n        const int order,\r\n        const double cosineHarmonicCoefficient,\r\n        const double sineHarmonicCoefficient,\r\n        std::shared_ptr< basic_mathematics::SphericalHarmonicsCache > sphericalHarmonicsCache )\r\n{\r\n    // Declare spherical position vector.\r\n    Eigen::Vector3d sphericalpositionOfBodySubjectToAcceleration = coordinate_conversions::\r\n            convertCartesianToSpherical( positionOfBodySubjectToAcceleration );\r\n    sphericalpositionOfBodySubjectToAcceleration( 1 ) = mathematical_constants::PI / 2.0 -\r\n            sphericalpositionOfBodySubjectToAcceleration( 1 );\r\n\r\n\r\n    double sineOfAngle = std::sin( sphericalpositionOfBodySubjectToAcceleration( 1 ) );\r\n    sphericalHarmonicsCache->update( sphericalpositionOfBodySubjectToAcceleration( 0 ),\r\n                                     sineOfAngle,\r\n                                     sphericalpositionOfBodySubjectToAcceleration( 2 ),\r\n                                     equatorialRadius );\r\n\r\n    // Compute gradient premultiplier.\r\n    const double preMultiplier = gravitationalParameter / equatorialRadius;\r\n\r\n    // Compute geodesy-normalized Legendre polynomials.\r\n    const double legendrePolynomial = sphericalHarmonicsCache->getLegendreCache( )->getLegendrePolynomial( degree, order );\r\n\r\n    // Compute geodesy-normalized Legendre polynomial derivative.\r\n    const double legendrePolynomialDerivative =\r\n            sphericalHarmonicsCache->getLegendreCache( )->getLegendrePolynomialDerivative( degree, order );\r\n\r\n    // Compute the potential gradient of a single spherical harmonic term.\r\n    Eigen::Vector3d sphericalGradient = basic_mathematics::computePotentialGradient(\r\n                sphericalpositionOfBodySubjectToAcceleration,\r\n                preMultiplier,\r\n                degree,\r\n                order,\r\n                cosineHarmonicCoefficient,\r\n                sineHarmonicCoefficient,\r\n                legendrePolynomial,\r\n                legendrePolynomialDerivative, sphericalHarmonicsCache );\r\n\r\n    // Convert from spherical gradient to Cartesian gradient (which equals acceleration vector),\r\n    // and return resulting acceleration vector.\r\n    return coordinate_conversions::convertSphericalToCartesianGradient(\r\n                sphericalGradient, positionOfBodySubjectToAcceleration );\r\n}\r\n\r\n} // namespace gravitation\r\n\r\n} // namespace tudat\r\n", "meta": {"hexsha": "fec4a7b7508570554be8ebeb6c7a0434c90f1522", "size": 9019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Gravitation/sphericalHarmonicsGravityModel.cpp", "max_stars_repo_name": "ViktorJordanov/tudat", "max_stars_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Gravitation/sphericalHarmonicsGravityModel.cpp", "max_issues_repo_name": "ViktorJordanov/tudat", "max_issues_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Gravitation/sphericalHarmonicsGravityModel.cpp", "max_forks_repo_name": "ViktorJordanov/tudat", "max_forks_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.9734042553, "max_line_length": 125, "alphanum_fraction": 0.6672580109, "num_tokens": 1738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5221948380592392}}
{"text": "/* vim: set sw=4 sts=4 et foldmethod=syntax : */\n\n#include <gcs/constraints/all_different.hh>\n#include <gcs/constraints/comparison.hh>\n#include <gcs/constraints/linear_equality.hh>\n#include <gcs/problem.hh>\n#include <gcs/solve.hh>\n\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n#include <boost/program_options.hpp>\n\nusing namespace gcs;\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::ifstream;\nusing std::pair;\nusing std::stoi;\nusing std::vector;\n\nnamespace po = boost::program_options;\n\nauto main(int argc, char * argv[]) -> int\n{\n    po::options_description display_options{ \"Program options\" };\n    display_options.add_options()\n        (\"help\", \"Display help information\")\n        (\"prove\", \"Create a proof\")\n        (\"all-different\", \"Use AllDifferent rather than inequalities\");\n\n    po::options_description all_options{ \"All options\" };\n    all_options.add_options()\n        (\"size\", po::value<int>()->default_value(5), \"Size of the problem to solve\")\n        ;\n\n    all_options.add(display_options);\n\n    po::positional_options_description positional_options;\n    positional_options\n        .add(\"size\", -1);\n\n    po::variables_map options_vars;\n\n    try {\n        po::store(po::command_line_parser(argc, argv)\n                .options(all_options)\n                .positional(positional_options)\n                .run(), options_vars);\n        po::notify(options_vars);\n    }\n    catch (const po::error & e) {\n        cerr << \"Error: \" << e.what() << endl;\n        cerr << \"Try \" << argv[0] << \" --help\" << endl;\n        return EXIT_FAILURE;\n    }\n\n    if (options_vars.count(\"help\")) {\n        cout << \"Usage: \" << argv[0] << \" [options] [size]\" << endl;\n        cout << endl;\n        cout << display_options << endl;\n        return EXIT_SUCCESS;\n    }\n\n    cout << \"Replicating the MiniCP Magic Square benchmark.\" << endl;\n    cout << \"See Laurent D. Michel, Pierre Schaus, Pascal Van Hentenryck:\" << endl;\n    cout << \"\\\"MiniCP: a lightweight solver for constraint programming.\\\"\" << endl;\n    cout << \"Math. Program. Comput. 13(1): 133-184 (2021).\" << endl;\n    cout << \"This should take 6042079 recursions with default options.\" << endl;\n    cout << endl;\n\n    int size = options_vars[\"size\"].as<int>();\n    Problem p = options_vars.count(\"prove\") ? Problem{ Proof{ \"magic_square.opb\", \"magic_square.veripb\" } } : Problem{ };\n    Integer m{ size * (size * size + 1) / 2 };\n\n    vector<vector<IntegerVariableID> > grid;\n    vector<IntegerVariableID> grid_flat;\n    for (int x = 0 ; x < size ; ++x) {\n        grid.emplace_back();\n        for (int y = 0 ; y < size ; ++y) {\n            auto var = p.create_integer_variable(1_i, Integer{ size * size });\n            grid[x].push_back(var);\n            grid_flat.push_back(var);\n        }\n    }\n\n    // As far as I can tell, the statistics reported in the paper only make\n    // sense for non-GAC all-different.\n    if (options_vars.count(\"all-different\")) {\n        p.post(AllDifferent{ grid_flat });\n    }\n    else {\n        for (unsigned x = 0 ; x < grid_flat.size() ; ++x)\n            for (unsigned y = x + 1 ; y < grid_flat.size() ; ++y)\n                p.post(NotEquals{ grid_flat[x], grid_flat[y] });\n    }\n\n    for (int x = 0 ; x < size ; ++x) {\n        Linear coeff_vars;\n        for (int y = 0 ; y < size ; ++y)\n            coeff_vars.emplace_back(1_i, grid[x][y]);\n        p.post(LinearEquality{ move(coeff_vars), m });\n    }\n\n    for (int y = 0 ; y < size ; ++y) {\n        Linear coeff_vars;\n        for (int x = 0 ; x < size ; ++x)\n            coeff_vars.emplace_back(1_i, grid[x][y]);\n        p.post(LinearEquality{ move(coeff_vars), m });\n    }\n\n    Linear coeff_vars1, coeff_vars2;\n    for (int xy = 0 ; xy < size ; ++xy) {\n        coeff_vars1.emplace_back(1_i, grid[xy][xy]);\n        coeff_vars2.emplace_back(1_i, grid[size - xy - 1][xy]);\n    }\n    p.post(LinearEquality{ move(coeff_vars1), m });\n    p.post(LinearEquality{ move(coeff_vars2), m });\n\n    p.post(LessThan{ grid[0][size - 1], grid[size - 1][0] });\n    p.post(LessThan{ grid[0][0], grid[size - 1][size - 1] });\n    p.post(LessThan{ grid[0][0], grid[size - 1][0] });\n\n    p.branch_on(grid_flat);\n\n    unsigned long long n_solutions = 0;\n    auto stats = solve_with(p, SolveCallbacks{\n            .solution = [&] (const State &) -> bool {\n                return ++n_solutions < 10000;\n            },\n            .guess = [&] (const State & state, IntegerVariableID var) -> vector<Literal> {\n                return vector<Literal>{ var == state.lower_bound(var), var != state.lower_bound(var) };\n            }\n            } );\n\n    cout << stats;\n\n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "e9ea2e401094bed5d6a415e6ea0ea7df9ad64c08", "size": 4659, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/magic_square/magic_square.cc", "max_stars_repo_name": "ciaranm/glasgow-constraint-solver", "max_stars_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-08-13T11:36:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T11:13:04.000Z", "max_issues_repo_path": "examples/magic_square/magic_square.cc", "max_issues_repo_name": "ciaranm/glasgow-constraint-solver", "max_issues_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_issues_repo_licenses": ["MIT"], "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/magic_square/magic_square.cc", "max_forks_repo_name": "ciaranm/glasgow-constraint-solver", "max_forks_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_forks_repo_licenses": ["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.1310344828, "max_line_length": 121, "alphanum_fraction": 0.5851040996, "num_tokens": 1229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6187804267137442, "lm_q1q2_score": 0.5221857765190564}}
{"text": "//\n// Created by Samuel Jackson on 08/03/2016.\n//\n\n#include <memory>\n#include <iostream>\n#include <Eigen/Dense>\n\n#include \"Molecule.h\"\n#include \"SystemParameters.h\"\n#include \"Simulation.h\"\n\nusing namespace Eigen;\nusing namespace Molly;\n\nSimulation::Simulation(SystemParameters params)\n        : params(params), step_limit(10), step_count(0), vir_sum(0), u_sum(0), cell_matrix(params.r_cutoff) {\n\n}\n\nvoid Simulation::set_up() {\n    print_header();\n    init_props();\n    init_cells();\n    init_coordinates();\n}\n\n\n\nvoid Simulation::init_props() {\n    // create unit cell of volume x * y * z\n    unit_cell << 10, 10, 1;\n    // scale the unit cell size by density to create the bound box\n    region = unit_cell * (1. / sqrt(params.density));\n    // one cell for each unit of volume\n    num_mols = unit_cell.prod();\n    mols.resize(num_mols);\n\n    initial_magnitude = std::sqrt(3 * (1. - 1./num_mols) * params.temperature);\n}\n\nvoid Simulation::init_cells() {\n    // create cells proportional to cell cut off distance.\n    cell_size = region / params.r_cutoff ;\n    cell_size(0) = std::ceil(cell_size(0));\n    cell_size(1) = std::ceil(cell_size(1));\n    cell_size(2) = std::ceil(cell_size(2));\n    cell_matrix.resize(cell_size(0), cell_size(1), cell_size(2));\n}\n\nvoid Simulation::init_coordinates() {\n    Vector3d gap = region.cwiseQuotient(unit_cell);\n    std::vector<Molecule_ptr> mols;\n    mols.resize(num_mols);\n\n    int n = 0;\n    for (int nx = 0; nx < unit_cell(0); ++nx) {\n        for (int ny = 0; ny < unit_cell(1); ++ny) {\n            for(int nz = 0; nz < unit_cell(2); ++nz) {\n                // set up position\n                mols[n] = std::make_shared<Molecule>();\n                mols[n]->r(0) = nx+0.5;\n                mols[n]->r(1) = ny+0.5;\n                mols[n]->r(2) = nz+0.5;\n\n                mols[n]->r = mols[n]->r.cwiseProduct(gap);\n                mols[n]->r += -0.5 * region;\n\n                // set up initial velocity\n                mols[n]->rv = Vector3d::Random();\n                mols[n]->rv.normalize();\n                mols[n]->rv *= initial_magnitude;\n                ++n;\n            }\n        }\n    }\n}\n\nvoid Simulation::run() {\n    int n = 0;\n    while(n < step_limit) {\n        single_step(n);\n        ++n;\n    }\n\n}\n\nvoid Simulation::single_step(int step) {\n    step_count = step;\n    time_now = step_count * params.delta_time;\n\n    integrate(1);\n    apply_boundary_checks();\n    compute_forces();\n    integrate(2);\n    evaluate_properties();\n\n    if (step_count % params.step_average == 0) {\n        average_properties();\n        print_summary();\n        clear_properties();\n    }\n}\n\nvoid Simulation::compute_forces() {\n    Vector3d dr = Vector3d::Zero();\n    double rr = 0.;\n    double cut_off = params.r_cutoff * params.r_cutoff;\n\n    // reset sums for this iteration\n    u_sum = 0.;\n    vir_sum = 0.;\n\n    // reset acceleration vectors\n    for(auto iter = mols.begin(); iter != mols.end(); ++iter) {\n        iter->ra.fill(0);\n    }\n\n    // compute interactions between molecules\n    for (int i=0; i < mols.size()-1; ++i) {\n        for(int j=i+1; j < mols.size(); ++j) {\n            // find difference between mols i and j\n            dr = mols[i].r - mols[j].r;\n            // apply boundary checks to position difference\n            apply_boundary_check(dr);\n\n            rr = dr.squaredNorm();\n\n            if(rr < cut_off) {\n                dr*= potential(rr);\n                mols[i].ra += dr;\n                mols[j].ra -= dr;\n            }\n        }\n    }\n}\n\n/**\n * Lennard Jones potential function\n */\ndouble Simulation::potential(double rr) {\n    double rri = 1./rr;\n    double rri3 = rri * rri * rri;\n    double fc_val = 48. * rri3 * (rri3 - 0.5) * rri;\n    u_sum += 4. * rri3 * (rri3 - 1.) + 1.;\n    vir_sum += fc_val * rr;\n    return fc_val;\n}\n\n/**\n * Uses leapfrog integration method.\n *\n */\nvoid Simulation::integrate(int part) {\n\n    for (auto iter = mols.begin(); iter != mols.end(); ++iter) {\n        Molecule mol = *iter;\n        switch(part) {\n            case 1:\n                // update velocity to by half a time step.\n                // update position one whole step.\n                mol.rv += 0.5 * params.delta_time * mol.ra;\n                mol.r += params.delta_time * mol.rv;\n                *iter = mol;\n                break;\n            case 2:\n                // just update velocity by half a time step.\n                mol.rv += 0.5 * params.delta_time * mol.ra;\n                *iter = mol;\n                break;\n            default:\n                throw std::runtime_error(\"Invalid part operation for integrate\");\n        }\n    }\n}\n\nvoid Simulation::apply_boundary_checks() {\n    for(auto iter = mols.begin(); iter != mols.end(); ++iter) {\n        apply_boundary_check(iter->r);\n    }\n}\n\nvoid Simulation::apply_boundary_check(Vector3d& vector) {\n    update_bound(vector(0), region(0));\n    update_bound(vector(1), region(1));\n    update_bound(vector(2), region(2));\n}\n\nvoid Simulation::update_bound(double& value, const double& bound) {\n    value = (value >= 0.5 * bound) ? value - bound : value;\n    value = (value < -0.5 * bound) ? value + bound : value;\n}\n\nvoid Simulation::evaluate_properties() {\n    v_sum = Vector3d::Zero();\n    double v_sqrd_sum = 0.;\n\n    for(auto iter = mols.cbegin(); iter != mols.cend(); ++iter) {\n        v_sum += iter->rv;\n        v_sqrd_sum += iter->rv.squaredNorm();\n    }\n\n    double kin_energy = 0.5 * v_sqrd_sum / num_mols;\n    kinetic_energy.set_value(kin_energy);\n    total_energy.set_value(kin_energy + (u_sum / num_mols));\n    pressure.set_value(params.density * (v_sqrd_sum + vir_sum) / (num_mols / 3));\n}\n\nvoid Simulation::average_properties() {\n    kinetic_energy.average(params.step_average);\n    total_energy.average(params.step_average);\n    pressure.average(params.step_average);\n}\n\nvoid Simulation::print_summary() {\n    printf(\"%5d %8.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f\\n\",\n           step_count,\n           time_now,\n           v_sum.sum() / num_mols,\n           total_energy.get_sum(),\n           total_energy.get_sum_sqrd(),\n           kinetic_energy.get_sum(),\n           kinetic_energy.get_sum_sqrd(),\n           pressure.get_sum(),\n           pressure.get_sum_sqrd());\n}\n\nvoid Simulation::clear_properties() {\n    kinetic_energy.clear();\n    total_energy.clear();\n    pressure.clear();\n}\n\nvoid Simulation::print_header() {\n    printf(\"MOLLY\\n--------------------------------------------------------------------------------------------\\n\");\n    printf(\"%5s %8s %7s %7s %7s %7s %7s %7s %7s\\n\",\n           \"step\", \"time\", \"sum\", \"tot_sum\", \"tot_sq\", \"kin_sum\", \"kin_sq\", \"press_sum\", \"press_sq\");\n}\n", "meta": {"hexsha": "b12d73fae183910a845ccafad89a41aebcde0f71", "size": 6636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Simulation.cpp", "max_stars_repo_name": "samueljackson92/molly", "max_stars_repo_head_hexsha": "6799990e3479da7e5d6e3372b0200bb198af4f8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Simulation.cpp", "max_issues_repo_name": "samueljackson92/molly", "max_issues_repo_head_hexsha": "6799990e3479da7e5d6e3372b0200bb198af4f8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Simulation.cpp", "max_forks_repo_name": "samueljackson92/molly", "max_forks_repo_head_hexsha": "6799990e3479da7e5d6e3372b0200bb198af4f8e", "max_forks_repo_licenses": ["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.7656903766, "max_line_length": 116, "alphanum_fraction": 0.5581675708, "num_tokens": 1750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5221857727342928}}
{"text": "/*********************************************************************\n*\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2016, Guan-Horng Liu.\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 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 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* Author:  Guan-Horng Liu\n*********************************************************************/\n\n\n#include \"r_s_planner/reeds_shepp.h\"\n#include <boost/math/constants/constants.hpp>\n\n\nnamespace\n{\n    // The comments, variable names, etc. use the nomenclature from the Reeds & Shepp paper.\n\n    const double pi = boost::math::constants::pi<double>();\n    const double twopi = 2. * pi;\n    const double RS_EPS = 1e-6;\n    const double ZERO = 10*std::numeric_limits<double>::epsilon();\n\n    inline double mod2pi(double x)\n    {\n        double v = fmod(x, twopi);\n        if (v < -pi)\n            v += twopi;\n        else\n            if (v > pi)\n                v -= twopi;\n        return v;\n    }\n    inline void polar(double x, double y, double &r, double &theta)\n    {\n        r = sqrt(x*x + y*y);\n        theta = atan2(y, x);\n    }\n    inline void tauOmega(double u, double v, double xi, double eta, double phi, double &tau, double &omega)\n    {\n        double delta = mod2pi(u-v), A = sin(u) - sin(delta), B = cos(u) - cos(delta) - 1.;\n        double t1 = atan2(eta*A - xi*B, xi*A + eta*B), t2 = 2. * (cos(delta) - cos(v) - cos(u)) + 3;\n        tau = (t2<0) ? mod2pi(t1+pi) : mod2pi(t1);\n        omega = mod2pi(tau - u + v - phi) ;\n    }\n\n    // formula 8.1 in Reeds-Shepp paper\n    inline bool LpSpLp(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        polar(x - sin(phi), y - 1. + cos(phi), u, t);\n        if (t >= -ZERO)\n        {\n            v = mod2pi(phi - t);\n            if (v >= -ZERO)\n            {\n                assert(fabs(u*cos(t) + sin(phi) - x) < RS_EPS);\n                assert(fabs(u*sin(t) - cos(phi) + 1 - y) < RS_EPS);\n                assert(fabs(mod2pi(t+v - phi)) < RS_EPS);\n                return true;\n            }\n        }\n        return false;\n    }\n    // formula 8.2\n    inline bool LpSpRp(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double t1, u1;\n        polar(x + sin(phi), y - 1. - cos(phi), u1, t1);\n        u1 = u1*u1;\n        if (u1 >= 4.)\n        {\n            double theta;\n            u = sqrt(u1 - 4.);\n            theta = atan2(2., u);\n            t = mod2pi(t1 + theta);\n            v = mod2pi(t - phi);\n            assert(fabs(2*sin(t) + u*cos(t) - sin(phi) - x) < RS_EPS);\n            assert(fabs(-2*cos(t) + u*sin(t) + cos(phi) + 1 - y) < RS_EPS);\n            assert(fabs(mod2pi(t-v - phi)) < RS_EPS);\n            return t>=-ZERO && v>=-ZERO;\n        }\n        return false;\n    }\n    void CSC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath &path)\n    {\n        double t, u, v, Lmin = path.length(), L;\n        if (LpSpLp(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[14], t, u, v);\n            Lmin = L;\n        }\n        if (LpSpLp(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[14], -t, -u, -v);\n            Lmin = L;\n        }\n        if (LpSpLp(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[15], t, u, v);\n            Lmin = L;\n        }\n        if (LpSpLp(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[15], -t, -u, -v);\n            Lmin = L;\n        }\n        if (LpSpRp(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[12], t, u, v);\n            Lmin = L;\n        }\n        if (LpSpRp(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[12], -t, -u, -v);\n            Lmin = L;\n        }\n        if (LpSpRp(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[13], t, u, v);\n            Lmin = L;\n        }\n        if (LpSpRp(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[13], -t, -u, -v);\n    }\n    // formula 8.3 / 8.4  *** TYPO IN PAPER ***\n    inline bool LpRmL(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double xi = x - sin(phi), eta = y - 1. + cos(phi), u1, theta;\n        polar(xi, eta, u1, theta);\n        if (u1 <= 4.)\n        {\n            u = -2.*asin(.25 * u1);\n            t = mod2pi(theta + .5 * u + pi);\n            v = mod2pi(phi - t + u);\n            assert(fabs(2*(sin(t) - sin(t-u)) + sin(phi) - x) < RS_EPS);\n            assert(fabs(2*(-cos(t) + cos(t-u)) - cos(phi) + 1 - y) < RS_EPS);\n            assert(fabs(mod2pi(t-u+v - phi)) < RS_EPS);\n            return t>=-ZERO && u<=ZERO;\n        }\n        return false;\n    }\n    void CCC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath &path)\n    {\n        double t, u, v, Lmin = path.length(), L;\n        if (LpRmL(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[0], t, u, v);\n            Lmin = L;\n        }\n        if (LpRmL(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[0], -t, -u, -v);\n            Lmin = L;\n        }\n        if (LpRmL(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[1], t, u, v);\n            Lmin = L;\n        }\n        if (LpRmL(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[1], -t, -u, -v);\n            Lmin = L;\n        }\n\n        // backwards\n        double xb = x*cos(phi) + y*sin(phi), yb = x*sin(phi) - y*cos(phi);\n        if (LpRmL(xb, yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[0], v, u, t);\n            Lmin = L;\n        }\n        if (LpRmL(-xb, yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[0], -v, -u, -t);\n            Lmin = L;\n        }\n        if (LpRmL(xb, -yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[1], v, u, t);\n            Lmin = L;\n        }\n        if (LpRmL(-xb, -yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[1], -v, -u, -t);\n    }\n    // formula 8.7\n    inline bool LpRupLumRm(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double xi = x + sin(phi), eta = y - 1. - cos(phi), rho = .25 * (2. + sqrt(xi*xi + eta*eta));\n        if (rho <= 1.)\n        {\n            u = acos(rho);\n            tauOmega(u, -u, xi, eta, phi, t, v);\n            assert(fabs(2*(sin(t)-sin(t-u)+sin(t-2*u))-sin(phi) - x) < RS_EPS);\n            assert(fabs(2*(-cos(t)+cos(t-u)-cos(t-2*u))+cos(phi)+1 - y) < RS_EPS);\n            assert(fabs(mod2pi(t-2*u-v - phi)) < RS_EPS);\n            return t>=-ZERO && v<=ZERO;\n        }\n        return false;\n    }\n    // formula 8.8\n    inline bool LpRumLumRp(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double xi = x + sin(phi), eta = y - 1. - cos(phi), rho = (20. - xi*xi - eta*eta) / 16.;\n        if (rho>=0 && rho<=1)\n        {\n            u = -acos(rho);\n            if (u >= -.5 * pi)\n            {\n                tauOmega(u, u, xi, eta, phi, t, v);\n                assert(fabs(4*sin(t)-2*sin(t-u)-sin(phi) - x) < RS_EPS);\n                assert(fabs(-4*cos(t)+2*cos(t-u)+cos(phi)+1 - y) < RS_EPS);\n                assert(fabs(mod2pi(t-v - phi)) < RS_EPS);\n                return t>=-ZERO && v>=-ZERO;\n            }\n        }\n        return false;\n    }\n    void CCCC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath &path)\n    {\n        double t, u, v, Lmin = path.length(), L;\n        if (LpRupLumRm(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[2], t, u, -u, v);\n            Lmin = L;\n        }\n        if (LpRupLumRm(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[2], -t, -u, u, -v);\n            Lmin = L;\n        }\n        if (LpRupLumRm(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[3], t, u, -u, v);\n            Lmin = L;\n        }\n        if (LpRupLumRm(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v))) // timeflip + reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[3], -t, -u, u, -v);\n            Lmin = L;\n        }\n\n        if (LpRumLumRp(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[2], t, u, u, v);\n            Lmin = L;\n        }\n        if (LpRumLumRp(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[2], -t, -u, -u, -v);\n            Lmin = L;\n        }\n        if (LpRumLumRp(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[3], t, u, u, v);\n            Lmin = L;\n        }\n        if (LpRumLumRp(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v))) // timeflip + reflect\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[3], -t, -u, -u, -v);\n    }\n    // formula 8.9\n    inline bool LpRmSmLm(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double xi = x - sin(phi), eta = y - 1. + cos(phi), rho, theta;\n        polar(xi, eta, rho, theta);\n        if (rho >= 2.)\n        {\n            double r = sqrt(rho*rho - 4.);\n            u = 2. - r;\n            t = mod2pi(theta + atan2(r, -2.));\n            v = mod2pi(phi - .5*pi - t);\n            assert(fabs(2*(sin(t)-cos(t))-u*sin(t)+sin(phi) - x) < RS_EPS);\n            assert(fabs(-2*(sin(t)+cos(t))+u*cos(t)-cos(phi)+1 - y) < RS_EPS);\n            assert(fabs(mod2pi(t+pi/2+v-phi)) < RS_EPS);\n            return t>=-ZERO && u<=ZERO && v<=ZERO;\n        }\n        return false;\n    }\n    // formula 8.10\n    inline bool LpRmSmRm(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double xi = x + sin(phi), eta = y - 1. - cos(phi), rho, theta;\n        polar(-eta, xi, rho, theta);\n        if (rho >= 2.)\n        {\n            t = theta;\n            u = 2. - rho;\n            v = mod2pi(t + .5*pi - phi);\n            assert(fabs(2*sin(t)-cos(t-v)-u*sin(t) - x) < RS_EPS);\n            assert(fabs(-2*cos(t)-sin(t-v)+u*cos(t)+1 - y) < RS_EPS);\n            assert(fabs(mod2pi(t+pi/2-v-phi)) < RS_EPS);\n            return t>=-ZERO && u<=ZERO && v<=ZERO;\n        }\n        return false;\n    }\n    void CCSC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath &path)\n    {\n        double t, u, v, Lmin = path.length() - .5*pi, L;\n        if (LpRmSmLm(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[4], t, -.5*pi, u, v);\n            Lmin = L;\n        }\n        if (LpRmSmLm(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[4], -t, .5*pi, -u, -v);\n            Lmin = L;\n        }\n        if (LpRmSmLm(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[5], t, -.5*pi, u, v);\n            Lmin = L;\n        }\n        if (LpRmSmLm(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[5], -t, .5*pi, -u, -v);\n            Lmin = L;\n        }\n\n        if (LpRmSmRm(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[8], t, -.5*pi, u, v);\n            Lmin = L;\n        }\n        if (LpRmSmRm(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[8], -t, .5*pi, -u, -v);\n            Lmin = L;\n        }\n        if (LpRmSmRm(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[9], t, -.5*pi, u, v);\n            Lmin = L;\n        }\n        if (LpRmSmRm(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[9], -t, .5*pi, -u, -v);\n            Lmin = L;\n        }\n\n        // backwards\n        double xb = x*cos(phi) + y*sin(phi), yb = x*sin(phi) - y*cos(phi);\n        if (LpRmSmLm(xb, yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[6], v, u, -.5*pi, t);\n            Lmin = L;\n        }\n        if (LpRmSmLm(-xb, yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[6], -v, -u, .5*pi, -t);\n            Lmin = L;\n        }\n        if (LpRmSmLm(xb, -yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[7], v, u, -.5*pi, t);\n            Lmin = L;\n        }\n        if (LpRmSmLm(-xb, -yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[7], -v, -u, .5*pi, -t);\n            Lmin = L;\n        }\n\n        if (LpRmSmRm(xb, yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[10], v, u, -.5*pi, t);\n            Lmin = L;\n        }\n        if (LpRmSmRm(-xb, yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[10], -v, -u, .5*pi, -t);\n            Lmin = L;\n        }\n        if (LpRmSmRm(xb, -yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[11], v, u, -.5*pi, t);\n            Lmin = L;\n        }\n        if (LpRmSmRm(-xb, -yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[11], -v, -u, .5*pi, -t);\n    }\n    // formula 8.11 *** TYPO IN PAPER ***\n    inline bool LpRmSLmRp(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double xi = x + sin(phi), eta = y - 1. - cos(phi), rho, theta;\n        polar(xi, eta, rho, theta);\n        if (rho >= 2.)\n        {\n            u = 4. - sqrt(rho*rho - 4.);\n            if (u <= ZERO)\n            {\n                t = mod2pi(atan2((4-u)*xi -2*eta, -2*xi + (u-4)*eta));\n                v = mod2pi(t - phi);\n                assert(fabs(4*sin(t)-2*cos(t)-u*sin(t)-sin(phi) - x) < RS_EPS);\n                assert(fabs(-4*cos(t)-2*sin(t)+u*cos(t)+cos(phi)+1 - y) < RS_EPS);\n                assert(fabs(mod2pi(t-v-phi)) < RS_EPS);\n                return t>=-ZERO && v>=-ZERO;\n            }\n        }\n        return false;\n    }\n    void CCSCC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath &path)\n    {\n        double t, u, v, Lmin = path.length() - pi, L;\n        if (LpRmSLmRp(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[16], t, -.5*pi, u, -.5*pi, v);\n            Lmin = L;\n        }\n        if (LpRmSLmRp(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[16], -t, .5*pi, -u, .5*pi, -v);\n            Lmin = L;\n        }\n        if (LpRmSLmRp(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[17], t, -.5*pi, u, -.5*pi, v);\n            Lmin = L;\n        }\n        if (LpRmSLmRp(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[17], -t, .5*pi, -u, .5*pi, -v);\n    }\n\n    ReedsSheppStateSpace::ReedsSheppPath reedsShepp(double x, double y, double phi)\n    {\n        ReedsSheppStateSpace::ReedsSheppPath path;\n        CSC(x, y, phi, path);\n        CCC(x, y, phi, path);\n        CCCC(x, y, phi, path);\n        CCSC(x, y, phi, path);\n        CCSCC(x, y, phi, path);\n        return path;\n    }\n}\n\nconst ReedsSheppStateSpace::ReedsSheppPathSegmentType\nReedsSheppStateSpace::reedsSheppPathType[18][5] = {\n    { RS_LEFT, RS_RIGHT, RS_LEFT, RS_NOP, RS_NOP },             // 0\n    { RS_RIGHT, RS_LEFT, RS_RIGHT, RS_NOP, RS_NOP },            // 1\n    { RS_LEFT, RS_RIGHT, RS_LEFT, RS_RIGHT, RS_NOP },           // 2\n    { RS_RIGHT, RS_LEFT, RS_RIGHT, RS_LEFT, RS_NOP },           // 3\n    { RS_LEFT, RS_RIGHT, RS_STRAIGHT, RS_LEFT, RS_NOP },        // 4\n    { RS_RIGHT, RS_LEFT, RS_STRAIGHT, RS_RIGHT, RS_NOP },       // 5\n    { RS_LEFT, RS_STRAIGHT, RS_RIGHT, RS_LEFT, RS_NOP },        // 6\n    { RS_RIGHT, RS_STRAIGHT, RS_LEFT, RS_RIGHT, RS_NOP },       // 7\n    { RS_LEFT, RS_RIGHT, RS_STRAIGHT, RS_RIGHT, RS_NOP },       // 8\n    { RS_RIGHT, RS_LEFT, RS_STRAIGHT, RS_LEFT, RS_NOP },        // 9\n    { RS_RIGHT, RS_STRAIGHT, RS_RIGHT, RS_LEFT, RS_NOP },       // 10\n    { RS_LEFT, RS_STRAIGHT, RS_LEFT, RS_RIGHT, RS_NOP },        // 11\n    { RS_LEFT, RS_STRAIGHT, RS_RIGHT, RS_NOP, RS_NOP },         // 12\n    { RS_RIGHT, RS_STRAIGHT, RS_LEFT, RS_NOP, RS_NOP },         // 13\n    { RS_LEFT, RS_STRAIGHT, RS_LEFT, RS_NOP, RS_NOP },          // 14\n    { RS_RIGHT, RS_STRAIGHT, RS_RIGHT, RS_NOP, RS_NOP },        // 15\n    { RS_LEFT, RS_RIGHT, RS_STRAIGHT, RS_LEFT, RS_RIGHT },      // 16\n    { RS_RIGHT, RS_LEFT, RS_STRAIGHT, RS_RIGHT, RS_LEFT }       // 17\n};\n\nReedsSheppStateSpace::ReedsSheppPath::ReedsSheppPath(const ReedsSheppPathSegmentType* type,\n    double t, double u, double v, double w, double x)\n    : type_(type)\n{\n    length_[0] = t; length_[1] = u; length_[2] = v; length_[3] = w; length_[4] = x;\n    totalLength_ = fabs(t) + fabs(u) + fabs(v) + fabs(w) + fabs(x);\n}\n\n\ndouble ReedsSheppStateSpace::distance(double q0[3], double q1[3])\n{\n    return rho_ * reedsShepp(q0, q1).length();\n}\n\nReedsSheppStateSpace::ReedsSheppPath ReedsSheppStateSpace::reedsShepp(double q0[3], double q1[3])\n{\n    double dx = q1[0] - q0[0], dy = q1[1] - q0[1], dth = q1[2] - q0[2];\n    double c = cos(q0[2]), s = sin(q0[2]);\n    double x = c*dx + s*dy, y = -s*dx + c*dy;\n    return ::reedsShepp(x/rho_, y/rho_, dth);\n}\n\nstd::vector<ReedsSheppStateSpace::ReedsSheppPathSegmentType> ReedsSheppStateSpace::type(double q0[3], double q1[3])\n{\n    ReedsSheppPath path = reedsShepp(q0, q1);\n    std::vector<ReedsSheppStateSpace::ReedsSheppPathSegmentType> type_list;\n    for (int i=0;i<5;++i)\n        type_list.push_back(path.type_[i]);\n    return type_list;\n}\n\nvoid ReedsSheppStateSpace::sample(double q0[3], double q1[3], double step_size, double &length, std::vector<std::vector<double> > &points)\n{\n    ReedsSheppPath path = reedsShepp(q0, q1);\n    length = rho_ * path.length();\n\n    for (double seg=0.0; seg<=length; seg+=step_size) {\n        double qnew[3] = {};\n        interpolate(q0, path, seg/rho_, qnew);\n        std::vector<double> v(qnew, qnew + sizeof qnew / sizeof qnew[0]);\n        points.push_back(v);\n    }\n    return;\n}\n\nvoid ReedsSheppStateSpace::interpolate(double q0[3], ReedsSheppPath &path, double seg, double s[3])\n{\n\n    if (seg < 0.0) seg = 0.0;\n    if (seg > path.length()) seg = path.length();\n\n    double phi, v;\n\n    s[0] = s[1] = 0.0;\n    s[2] = q0[2];\n\n    for (unsigned int i=0; i<5 && seg>0; ++i)\n    {\n        if (path.length_[i]<0)\n        {\n            v = std::max(-seg, path.length_[i]);\n            seg += v;\n        }\n        else\n        {\n            v = std::min(seg, path.length_[i]);\n            seg -= v;\n        }\n        phi = s[2];\n        switch(path.type_[i])\n        {\n            case RS_LEFT:\n                s[0] += ( sin(phi+v) - sin(phi));\n                s[1] += (-cos(phi+v) + cos(phi));\n                s[2] = phi + v;\n                break;\n            case RS_RIGHT:\n                s[0] += (-sin(phi-v) + sin(phi));\n                s[1] += ( cos(phi-v) - cos(phi));\n                s[2] = phi - v;\n                break;\n            case RS_STRAIGHT:\n                s[0] += (v * cos(phi));\n                s[1] += (v * sin(phi));\n                break;\n            case RS_NOP:\n                break;\n        }\n    }\n\n    s[0] = s[0] * rho_ + q0[0];\n    s[1] = s[1] * rho_ + q0[1];\n}\n", "meta": {"hexsha": "c4743c62ccd612a2c82b0559350c185d75d00685", "size": 25670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/reeds_shepp.cpp", "max_stars_repo_name": "NEU-ZJX/car_geometric_planner", "max_stars_repo_head_hexsha": "e83aa0e92b13bc987f4a2e2542dc44a81273d623", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2019-06-04T10:30:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T18:21:47.000Z", "max_issues_repo_path": "src/reeds_shepp.cpp", "max_issues_repo_name": "yinflight/car_geometric_planner", "max_issues_repo_head_hexsha": "e83aa0e92b13bc987f4a2e2542dc44a81273d623", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-04-06T12:18:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-06T02:14:59.000Z", "max_forks_repo_path": "src/reeds_shepp.cpp", "max_forks_repo_name": "yinflight/car_geometric_planner", "max_forks_repo_head_hexsha": "e83aa0e92b13bc987f4a2e2542dc44a81273d623", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2018-11-08T02:08:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T09:30:32.000Z", "avg_line_length": 41.2038523274, "max_line_length": 138, "alphanum_fraction": 0.5081417998, "num_tokens": 8481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5221857703049338}}
{"text": "#include <boost/mpl11/integer.hpp>\n\n\nusing size_t = decltype(sizeof(int));\n\nconstexpr struct plus_ {\n    template <typename X, typename Y>\n    constexpr auto operator()(X x, Y y) { return x + y; }\n} plus{};\n\ntemplate <typename T, size_t N, typename F, typename State>\nconstexpr State homogeneous_foldl(F f, State s, const T (&array)[N]) {\n    for (size_t i = 0; i < N; ++i)\n        s = f(s, array[i]);\n    return s;\n}\n\ntemplate <typename ...xs>\nusing sum = boost::mpl11::integer_c<\n    decltype(homogeneous_foldl<size_t, sizeof...(xs)>(plus, 0, {xs::value...})),\n    homogeneous_foldl<size_t, sizeof...(xs)>(plus, 0, {xs::value...})\n>;\n\n<%= render('_main.erb') %>", "meta": {"hexsha": "063e3efb5e13361c5a6aa40dd13a55790ca9ca50", "size": 663, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/sum/constexpr.erb.cpp", "max_stars_repo_name": "ldionne/benchcc", "max_stars_repo_head_hexsha": "87cd508b47b39c9da5fb2152ec3f07de62297771", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-12T11:54:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-12T11:54:43.000Z", "max_issues_repo_path": "benchmarks/sum/constexpr.erb.cpp", "max_issues_repo_name": "ldionne/benchcc", "max_issues_repo_head_hexsha": "87cd508b47b39c9da5fb2152ec3f07de62297771", "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": "benchmarks/sum/constexpr.erb.cpp", "max_forks_repo_name": "ldionne/benchcc", "max_forks_repo_head_hexsha": "87cd508b47b39c9da5fb2152ec3f07de62297771", "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.625, "max_line_length": 80, "alphanum_fraction": 0.6304675716, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5221857678755748}}
{"text": "/* Boost test/det.cpp\n * test protected and unprotected rounding on an unstable determinant\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/test/minimal.hpp>\n#include \"bugs.hpp\"\n\n#define size 8\n\ntemplate<class I>\nvoid det(I (&mat)[size][size]) {\n  for(int i = 0; i < size; i++)\n    for(int j = 0; j < size; j++)\n      mat[i][j] = I(1) / I(i + j + 1);\n\n  for(int i = 0; i < size - 1; i++) {\n    int m = i, n = i;\n    typename I::base_type v = 0;\n    for(int a = i; a < size; a++)\n      for(int b = i; b < size; b++) {\n        typename I::base_type  w = abs(mat[a][b]).lower();\n        if (w > v) { m = a; n = b; v = w; }\n      }\n    if (n != i)\n      for(int a = 0; a < size; a++) {\n        I t = mat[a][n];\n        mat[a][n] = mat[a][i];\n        mat[a][i] = t;\n      }\n    if (m != i)\n      for(int b = i; b < size; b++) {\n        I t = mat[m][b];\n        mat[m][b] = mat[m][i];\n        mat[m][i] = t;\n      }\n    if (((m + n) & 1) == 1) { };\n    I c = mat[i][i];\n    for(int j = i + 1; j < size; j++) {\n      I f = mat[j][i] / c;\n      for(int k = i; k < size; k++)\n        mat[j][k] -= f * mat[i][k];\n    }\n    if (in_zero(c)) return;\n  }\n}\n\nnamespace my_namespace {\n\nusing namespace boost;\nusing namespace numeric;\nusing namespace interval_lib;\n\ntemplate<class T>\nstruct variants {\n  typedef interval<T> I_op;\n  typedef typename change_rounding<I_op, save_state<rounded_arith_std<T> > >::type I_sp;\n  typedef typename unprotect<I_op>::type I_ou;\n  typedef typename unprotect<I_sp>::type I_su;\n  typedef T type;\n};\n\n}\n\ntemplate<class T>\nbool test() {\n  typedef my_namespace::variants<double> types;\n  types::I_op mat_op[size][size];\n  types::I_sp mat_sp[size][size];\n  types::I_ou mat_ou[size][size];\n  types::I_su mat_su[size][size];\n  det(mat_op);\n  det(mat_sp);\n  { types::I_op::traits_type::rounding rnd; det(mat_ou); }\n  { types::I_sp::traits_type::rounding rnd; det(mat_su); }\n  for(int i = 0; i < size; i++)\n    for(int j = 0; j < size; j++) {\n      typedef types::I_op I;\n      I d_op = mat_op[i][j];\n      I d_sp = mat_sp[i][j];\n      I d_ou = mat_ou[i][j];\n      I d_su = mat_su[i][j];\n      if (!(equal(d_op, d_sp) && equal(d_sp, d_ou) && equal(d_ou, d_su)))\n        return false;\n    }\n  return true;\n}\n\nint test_main(int, char *[]) {\n  BOOST_CHECK(test<float>());\n  BOOST_CHECK(test<double>());\n  BOOST_CHECK(test<long double>());\n# ifdef __BORLANDC__\n  ::detail::ignore_warnings();\n# endif\n  return 0;\n}\n", "meta": {"hexsha": "ba87d26676f8a84c3c5f509650bd54652afa9d59", "size": 2636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/boost_1_33_1/libs/numeric/interval/test/det.cpp", "max_stars_repo_name": "spxuw/RFIM", "max_stars_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T13:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T02:55:10.000Z", "max_issues_repo_path": "Source/boost_1_33_1/libs/numeric/interval/test/det.cpp", "max_issues_repo_name": "spxuw/RFIM", "max_issues_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_issues_repo_licenses": ["MIT"], "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/boost_1_33_1/libs/numeric/interval/test/det.cpp", "max_forks_repo_name": "spxuw/RFIM", "max_forks_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T14:34:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T08:25:58.000Z", "avg_line_length": 25.3461538462, "max_line_length": 88, "alphanum_fraction": 0.5625948407, "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.522130884111649}}
{"text": "#include \"solvers/SolverBoxPGS.h\"\n\n#include \"contact/Contact.h\"\n#include \"rigidbody/RigidBody.h\"\n#include \"rigidbody/RigidBodySystem.h\"\n\n#include <Eigen/Dense>\n\n\nnamespace\n{\n    static inline void multAndSub(const JBlock& G, const Eigen::Vector3f& x, const Eigen::Vector3f& y, const float a, Eigen::VectorXf& b)\n    {\n            b -= a * G.col(0) * x(0);\n            b -= a * G.col(1) * x(1);\n            b -= a * G.col(2) * x(2);\n            b -= a * G.col(3) * y(0);\n            b -= a * G.col(4) * y(1);\n            b -= a * G.col(5) * y(2);\n    }\n\n\n\t// Computes the right-hand side vector of the Schur complement system: \n    //      b = gamma*phi/h - J*vel - dt*JMinvJT*force\n    //\n    static inline void buildRHS(Contact* c, float h, Eigen::VectorXf& b)\n    {\n        const float gamma = h * c->k / (h * c->k + c->b);       // error reduction parameter\n        b = -gamma * c->phi / h;\n\n        multAndSub(c->J0, c->body0->xdot, c->body0->omega, 1.0f, b);\n        multAndSub(c->J1, c->body1->xdot, c->body1->omega, 1.0f, b);\n\n        if( !c->body0->fixed )\n        {\n            multAndSub(c->J0Minv, c->body0->f, c->body0->tau, h, b);\n        }\n        if( !c->body1->fixed )\n        {\n            multAndSub(c->J1Minv, c->body1->f, c->body1->tau, h, b);\n        }\n    }\n\n    // Loop over all other contacts for a body and compute modifications to the rhs vector b: \n    //           x -= (JMinv*Jother^T) * lambda_other\n    //\n    static inline void accumulateCoupledContacts(Contact* c, const JBlock& JMinv, RigidBody* body, Eigen::VectorXf& b)\n    {\n        if( body->fixed )\n            return;\n\n        for(Contact* cc : body->contacts)\n        {\n            if( cc != c )\n            {\n                if( body == cc->body0 )\n                    b -= JMinv * (cc->J0.transpose() * cc->lambda);\n                else\n                    b -= JMinv * (cc->J1.transpose() * cc->lambda);\n            }\n        }\n    }\n\n    // Solve the Boxed LCP problem for a single contact and isotropic Coulomb friction.\n    // The solution vector, @a x, contains the impulse the non-interpenetration constraint in x(0), and\n    // the friction constraints in x(1) and x(2)\n    // \n    // The solution is projected to the lower and upper bounds imposed by the box model.\n    // \n    // Inputs: \n    //    x - contains three impulse variables (non-interpenetration + two friction)\n    //    b - rhs vector\n    //    mu - the friction coefficient\n    static inline void solveContact(const Eigen::Matrix3f& A, const Eigen::VectorXf& b, Eigen::VectorXf& x, const float mu)\n    {\n        // Normal impulse is projected to [0, inf]\n        //\n        x(0) = std::max(0.0f, (b(0) - A(0,1) * x(1) - A(0,2) * x(2) ) / A(0,0) );\n\n        // Next, friction impulses are projected to [-mu * x(0), mu * x(1)]\n        //\n        x(1) = std::max(-mu*x(0), std::min(mu*x(0), ( b(1) - A(1,0) * x(0) - A(1,2) * x(2) ) / A(1,1) ));\n        x(2) = std::max(-mu*x(0), std::min(mu*x(0), ( b(2) - A(2,0) * x(0) - A(2,1) * x(1) ) / A(2,2) ));\n    }\n}\n\nSolverBoxPGS::SolverBoxPGS(RigidBodySystem* _rigidBodySystem) : Solver(_rigidBodySystem)\n{\n\n}\n\nvoid SolverBoxPGS::solve(float h)\n{\n    std::vector<Contact*>& contacts = m_rigidBodySystem->getContacts();\n    const int numContacts = contacts.size();\n\n    // Build array of 3x3 diagonal matrices, one for each contact.\n    // \n    std::vector<Eigen::Matrix3f> Acontactii;\n    if( numContacts > 0 )\n    {\n        // Build diagonal matrices\n        Acontactii.resize(numContacts);\n        for(int i = 0; i < numContacts; ++i)\n        {\n            Contact* c = contacts[i];\n            const float eps = 1.0f / (h * h * c->k + h * c->b);    // constraint force mixing\n\n            // Compute the diagonal term : Aii = J0*Minv0*J0^T + J1*Minv1*J1^T\n            //\n            Acontactii[i].setZero(3,3);\n            Acontactii[i](0,0) += eps;\n\n            if( !c->body0->fixed )\n            {\n                Acontactii[i] += c->J0Minv * c->J0.transpose();\n            }\n            if( !c->body1->fixed )\n            {\n                Acontactii[i] += c->J1Minv * c->J1.transpose();\n            }\n        }\n\n        std::vector<Eigen::VectorXf> b;\n        b.resize(numContacts);\n\n        // Compute the right-hand side vector : \n        //      b = -gamma*phi/h - J*vel - dt*JMinvJT*force\n        //\n        for(int i = 0; i < numContacts; ++i)\n        {\n            Contact* c = contacts[i];\n            buildRHS(c, h, b[i]);\n            c->lambda.setZero();\n        }\n\n        // PGS main loop.\n        // There is no convergence test here.\n        // Stop after @a maxIter iterations.\n        //\n        for(int iter = 0; iter < m_maxIter; ++iter)\n        {\n            // For each contact, compute an updated value of contacts[i]->lambda\n            //      using matrix-free pseudo-code provided in the course notes.\n            //\n            for(int i = 0; i < numContacts; ++i)\n            {\n                Contact* c = contacts[i];\n\n                // Initialize current solution as x = b[i]\n                Eigen::VectorXf x = b[i];\n\n                accumulateCoupledContacts(c, c->J0Minv, c->body0, x);\n                accumulateCoupledContacts(c, c->J1Minv, c->body1, x);\n                solveContact(Acontactii[i], x, c->lambda, c->mu);\n            }\n        }\n    }\n}\n\n", "meta": {"hexsha": "1dc76c6a01d67ebbd82af8df47635e82b0ea9fc9", "size": 5303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/SolverBoxPGS.cpp", "max_stars_repo_name": "sheldona/contactFrictionSim", "max_stars_repo_head_hexsha": "40374728b863c488d5fb780a90fc1feafe320fed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2022-03-14T03:51:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T17:47:44.000Z", "max_issues_repo_path": "src/solvers/SolverBoxPGS.cpp", "max_issues_repo_name": "sheldona/contactFrictionSim", "max_issues_repo_head_hexsha": "40374728b863c488d5fb780a90fc1feafe320fed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solvers/SolverBoxPGS.cpp", "max_forks_repo_name": "sheldona/contactFrictionSim", "max_forks_repo_head_hexsha": "40374728b863c488d5fb780a90fc1feafe320fed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-03-24T10:55:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:08:16.000Z", "avg_line_length": 32.9378881988, "max_line_length": 137, "alphanum_fraction": 0.5080143315, "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.52213086641715}}
{"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/bessel.hpp>\n#include <boost/math/special_functions/airy.hpp>\n\nEVE_TEST_TYPES( \"Check return types of airy_ai\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  TTS_EXPR_IS(eve::airy_ai(T(0)), T);\n  TTS_EXPR_IS(eve::airy_ai(v_t(0)), v_t);\n};\n\n EVE_TEST( \"Check behavior of airy_ai on wide\"\n         , eve::test::simd::ieee_reals\n         , eve::test::generate(eve::test::randoms(-20.0, 0.0),\n                               eve::test::randoms(0.0, 20.0)\n                              )\n         )\n   <typename T>(T a0, T a1)\n{\n  using v_t = eve::element_type_t<T>;\n  v_t abstol = 1000*eve::eps(eve::as<v_t>());\n  auto eve__airy_ai =  [](auto x) { return eve::airy_ai(x); };\n  auto std__airy_ai =  [](auto x)->v_t { return boost::math::airy_ai(x); };\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__airy_ai(eve::minf(eve::as<v_t>())), eve::zero(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__airy_ai(eve::inf(eve::as<v_t>())), v_t(0), 0);\n    TTS_ULP_EQUAL(eve__airy_ai(eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__airy_ai(eve::minf(eve::as< T>())), eve::zero(eve::as< T>()), 0);\n    TTS_ULP_EQUAL(eve__airy_ai(eve::inf(eve::as< T>())),  T(0), 0);\n    TTS_ULP_EQUAL(eve__airy_ai(eve::nan(eve::as< T>())), eve::nan(eve::as< T>()), 0);\n  }\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(1500)), std__airy_ai(v_t(1500)), 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(500)), std__airy_ai(v_t(500)), 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(10)),  std__airy_ai(v_t(10))  , 13.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(5)),  std__airy_ai(v_t(5))   , 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(2)),  std__airy_ai(v_t(2))   , 35.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(1.5)),std__airy_ai(v_t(1.5)) , 11.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(0.5)),std__airy_ai(v_t(0.5)) , 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(1)),  std__airy_ai(v_t(1))   , 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(0)),  v_t(0.355028053887817), 0.5);\n\n  TTS_ULP_EQUAL(eve__airy_ai( T(1500)), T(std__airy_ai(v_t(1500))), 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(500)),  T(std__airy_ai(v_t(500)) ), 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(10)) ,  T(std__airy_ai( v_t(10)) ), 13.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(5))  ,  T(std__airy_ai( v_t(5))  ), 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(2))  ,  T(std__airy_ai( v_t(2))  ), 37.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(1.5)),  T(std__airy_ai( v_t(1.5))), 11.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(0.5)),  T(std__airy_ai( v_t(0.5))), 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(1))  ,  T(std__airy_ai( v_t(1))  ), 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(0))  ,  T(0.355028053887817), 0.5);\n\n  TTS_ABSOLUTE_EQUAL(eve__airy_ai(v_t(-1500)), std__airy_ai(v_t(-1500)), abstol);\n  TTS_ABSOLUTE_EQUAL(eve__airy_ai(v_t(-500)), std__airy_ai(v_t(-500)), abstol);\n  TTS_ABSOLUTE_EQUAL(eve__airy_ai(v_t(-10)),  std__airy_ai(v_t(-10)), abstol);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(-5)),  std__airy_ai(v_t(-5))   , 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(-2)),  std__airy_ai(v_t(-2))   , 35.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(-1.5)),std__airy_ai(v_t(-1.5)) , 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(-0.5)),std__airy_ai(v_t(-0.5)) , 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(-1)),  std__airy_ai(v_t(-1))   , 10.0);\n\n\n  TTS_ABSOLUTE_EQUAL(eve__airy_ai( T(-1500)), T(std__airy_ai(v_t(-1500))), abstol);\n  TTS_ABSOLUTE_EQUAL(eve__airy_ai( T(-500)),  T(std__airy_ai(v_t(-500)) ), abstol);\n  TTS_ABSOLUTE_EQUAL(eve__airy_ai( T(-10)) ,  T(std__airy_ai( v_t(-10)) ), abstol);\n  TTS_ULP_EQUAL(eve__airy_ai( T(-5))  ,  T(std__airy_ai( v_t(-5))  ), 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(-2))  ,  T(std__airy_ai( v_t(-2))  ), 36.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(-1.5)),  T(std__airy_ai( v_t(-1.5))), 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(-0.5)),  T(std__airy_ai( v_t(-0.5))), 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(-1))  ,  T(std__airy_ai( v_t(-1))  ), 10.0);\n\n\n   TTS_ABSOLUTE_EQUAL(eve__airy_ai(a0), map(std__airy_ai, a0), 0.0001);\n   TTS_RELATIVE_EQUAL(eve__airy_ai(a1), map(std__airy_ai, a1), 0.0001);\n\n};\n\nEVE_TEST( \"Check behavior of diff(airy_ai) on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(-20.0, 0.0),\n                              eve::test::randoms(0.0, 20.0)\n                             )\n        )\n  <typename T>(T a0, T a1)\n{\n  using v_t = eve::element_type_t<T>;\n  v_t reltol = 50000000*eve::eps(eve::as<v_t>());\n  auto eve__airy_ai =  [](auto x) { return eve::diff(eve::airy_ai)(x); };\n  auto std__airy_ai =  [](auto x)->v_t { return boost::math::airy_ai_prime(x); };\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__airy_ai(eve::minf(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__airy_ai(eve::inf(eve::as<v_t>())), eve::zero(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__airy_ai(eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__airy_ai(eve::minf(eve::as< T>())), eve::nan(eve::as< T>()), 0);\n    TTS_ULP_EQUAL(eve__airy_ai(eve::inf(eve::as< T>())), eve::zero(eve::as< T>()), 0);\n    TTS_ULP_EQUAL(eve__airy_ai(eve::nan(eve::as< T>())), eve::nan(eve::as< T>()), 0);\n  }\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(1500)), std__airy_ai(v_t(1500)), 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(500)), std__airy_ai(v_t(500)), 10.0);\n\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(10)),  std__airy_ai(v_t(10)) , 50.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(5)),  std__airy_ai(v_t(5))   , 50.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(2)),  std__airy_ai(v_t(2))   , 50.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(1.5)),std__airy_ai(v_t(1.5)) , 50.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(0.5)),std__airy_ai(v_t(0.5)) , 51.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(1)),  std__airy_ai(v_t(1))   , 50.0);\n  TTS_ULP_EQUAL(eve__airy_ai(v_t(0)),  v_t(-0.258819403792807), 0.5);\n\n  TTS_ULP_EQUAL(eve__airy_ai( T(1500)), T(std__airy_ai(v_t(1500))), 10.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(500)),  T(std__airy_ai(v_t(500)) ), 10.0);\n\n  TTS_ULP_EQUAL(eve__airy_ai( T(10)) ,  T(std__airy_ai( v_t(10)) ),  50.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(5))  ,  T(std__airy_ai( v_t(5))  ),  50.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(2))  ,  T(std__airy_ai( v_t(2))  ),  50.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(1.5)),  T(std__airy_ai( v_t(1.5))),  50.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(0.5)),  T(std__airy_ai( v_t(0.5))),  51.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(1))  ,  T(std__airy_ai( v_t(1))  ),  50.0);\n  TTS_ULP_EQUAL(eve__airy_ai( T(0))  ,  T(-0.258819403792807), 0.5);\n\n  TTS_RELATIVE_EQUAL(eve__airy_ai(v_t(-1500)), std__airy_ai(v_t(-1500)), reltol);\n  TTS_RELATIVE_EQUAL(eve__airy_ai(v_t(-500)), std__airy_ai(v_t(-500)), reltol);\n  TTS_RELATIVE_EQUAL(eve__airy_ai(v_t(-10)),  std__airy_ai(v_t(-10)) , reltol);\n  TTS_RELATIVE_EQUAL(eve__airy_ai(v_t(-5)),  std__airy_ai(v_t(-5))   , reltol);\n  TTS_RELATIVE_EQUAL(eve__airy_ai(v_t(-2)),  std__airy_ai(v_t(-2))   , reltol);\n  TTS_RELATIVE_EQUAL(eve__airy_ai(v_t(-1.5)),std__airy_ai(v_t(-1.5)) , reltol);\n  TTS_RELATIVE_EQUAL(eve__airy_ai(v_t(-0.5)),std__airy_ai(v_t(-0.5)) , reltol);\n  TTS_RELATIVE_EQUAL(eve__airy_ai(v_t(-1)),  std__airy_ai(v_t(-1))   , reltol);\n\n\n  TTS_ABSOLUTE_EQUAL(eve__airy_ai( T(-1500)), T(std__airy_ai(v_t(-1500))), reltol);\n  TTS_ABSOLUTE_EQUAL(eve__airy_ai( T(-500)),  T(std__airy_ai(v_t(-500)) ), reltol);\n  TTS_ABSOLUTE_EQUAL(eve__airy_ai( T(-10)) ,  T(std__airy_ai( v_t(-10)) ), reltol);\n  TTS_RELATIVE_EQUAL(eve__airy_ai( T(-5))  ,  T(std__airy_ai( v_t(-5))  ), reltol);\n  TTS_RELATIVE_EQUAL(eve__airy_ai( T(-2))  ,  T(std__airy_ai( v_t(-2))  ), reltol);\n  TTS_RELATIVE_EQUAL(eve__airy_ai( T(-1.5)),  T(std__airy_ai( v_t(-1.5))), reltol);\n  TTS_RELATIVE_EQUAL(eve__airy_ai( T(-0.5)),  T(std__airy_ai( v_t(-0.5))), reltol);\n  TTS_RELATIVE_EQUAL(eve__airy_ai( T(-1))  ,  T(std__airy_ai( v_t(-1))  ), reltol);\n\n\n  TTS_ABSOLUTE_EQUAL(eve__airy_ai(a0), map(std__airy_ai, a0), 0.0001);\n  TTS_RELATIVE_EQUAL(eve__airy_ai(a1), map(std__airy_ai, a1), 0.0001);\n};\n", "meta": {"hexsha": "b9f42d64ce56c9d48399024146ef247a37f6bf36", "size": 8361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/bessel/airy_ai.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/bessel/airy_ai.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/bessel/airy_ai.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": 53.5961538462, "max_line_length": 100, "alphanum_fraction": 0.6372443488, "num_tokens": 3357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5221308616051505}}
{"text": "/* +---------------------------------------------------------------------------+\n|                     Mobile Robot Programming Toolkit (MRPT)               |\n|                          http://www.mrpt.org/                             |\n|                                                                           |\n| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file        |\n| See: http://www.mrpt.org/Authors - All rights reserved.                   |\n| Released under BSD License. See details in http://www.mrpt.org/License    |\n+---------------------------------------------------------------------------+ */\n\n#include \"vision-precomp.h\"   // Precompiled headers\n#include <iostream>\n#include <mrpt/utils/types_math.h> // Eigen must be included first via MRPT to enable the plugin system\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\n#include \"posit.h\"\n\n\nmrpt::vision::pnp::posit::posit(Eigen::MatrixXd obj_pts_, Eigen::MatrixXd img_pts_, Eigen::MatrixXd camera_intrinsic_, int n0)\n{\n\t\tobj_pts=obj_pts_;\n\t\timg_pts=img_pts_.block(0,0,n0,2);\n\t\tcam_intrinsic=camera_intrinsic_;\n\t\tR=Eigen::MatrixXd::Identity(3,3);\n\t\tt=Eigen::VectorXd::Zero(3);\n\t\tf=(cam_intrinsic(0,0)+cam_intrinsic(1,1))/2;\n\t\t\n\t\tobj_matrix=(obj_pts.transpose() * obj_pts).inverse() * obj_pts.transpose();\n\t\n\t\tn=n0;\n\t\t\n\t\tobj_vecs=Eigen::MatrixXd::Zero(n0,3);\n\t\t\n\t\tfor(int i=0;i<n;i++)\n\t\t\tobj_vecs.row(i)=obj_pts.row(i)-obj_pts.row(0);\n\t\t\n\t\timg_vecs = Eigen::MatrixXd::Zero(n0,2);\n\t\timg_vecs_old=img_vecs;\n\t\t\n\t\tepsilons=Eigen::VectorXd::Zero(n);\n}\n\nvoid mrpt::vision::pnp::posit::POS()\n{\n\tEigen::Vector3d I0, J0 , r1, r2, r3;\n\tdouble I0_norm, J0_norm;\n\t\n\tint i;\n\tdouble scale;\n\t\n\tfor(i=0;i<3;i++)\n\t{\n\t\tI0(i)=obj_matrix.row(i).dot(img_vecs.col(0));\n\t\tJ0(i)=obj_matrix.row(i).dot(img_vecs.col(1));\n\t}\n\t\n    \n\tI0_norm=I0.norm();\n\tJ0_norm=J0.norm();\n\t\n\tscale=(I0_norm + J0_norm)/2;\n\t\n\t/*Computing TRANSLATION */\n\tt(0)=img_pts(0,0)/scale;\n\tt(1)=img_pts(0,1)/scale;\n\tt(2)=f/scale;\n\t\n\t/* Computing ROTATION */\n\tr1=I0/I0_norm;\n\tr2=J0/J0_norm;\n\tr3=r1.cross(r2);\n\t\n\tR.row(0)=r1;\n\tR.row(1)=r2;\n\tR.row(2)=r3;\n}\n\n/** \nIterate over results obtained by the POS function;\nsee paper \"Model-Based Object Pose in 25 Lines of Code\", IJCV 15, pp. 123-141, 1995.\n*/\nbool mrpt::vision::pnp::posit::compute_pose(Eigen::Ref<Eigen::Matrix3d> R_, Eigen::Ref<Eigen::Vector3d> t_)\n{\n\tEigen::FullPivLU<Eigen::MatrixXd> lu(obj_pts);\n\tif(lu.rank()<3)\n\t\treturn false;\n\t\t\n\tint i, iCount;\n\tlong imageDiff=1000;\n\t\n\tfor(iCount=0; iCount<LOOP_MAX_COUNT;iCount++)\n\t{\n\t\tif(iCount==0)\n\t\t{\n\t\t\tfor(i=0;i<img_vecs.rows();i++)\n\t\t\t\timg_vecs.row(i)=img_pts.row(i)-img_pts.row(0);\n\t\t}\n\t\t\n\t\telse\n\t\t{\n\t\t\t// Compute new image vectors\n\t\t\tepsilons.setZero();\n\t\t\tfor(i=0; i<n; i++)\n\t\t\t{\n\t\t\t\tepsilons(i)+=obj_vecs.row(i).dot(R.row(2));\n\t\t\t}\n\t\t\tepsilons/=t(2);\n\t\t\t\n\t\t\t// Corrected image vectors \t\n\t\t\tfor(i=0; i<n; i++)\n\t\t\t{\n\t\t\t\timg_vecs.row(i)= img_pts.row(i) * (1+epsilons(i)) -img_pts.row(0);\n\t\t\t}\n\t\t\t\n\t\t\timageDiff=this->get_img_diff();\n\t\t\t\n\t\t}\n\t\t\n\t\timg_vecs_old=img_vecs;\n\t\t\n\t\tthis->POS();\n\t\t\n\t\tif(iCount>0 && imageDiff==0)\n\t\t\tbreak;\n\t\t\t\n\t\tif(iCount==LOOP_MAX_COUNT)\n\t\t{\n\t\t\tstd::cout<<\"Solution Not converged\"<<std::endl<<std::endl;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t}\n\tR_=R;\n\tt_=t;\n\n\treturn true;\n}\n\nlong mrpt::vision::pnp::posit::get_img_diff()\n{\n\tint i, j;\n\tlong sumOfDiffs = 0;\n\t\n\tfor (i=0;i<n;i++){\n\t\tfor (j=0;j<2;j++){\n\t\t\tsumOfDiffs += std::abs(floor(0.5+img_vecs(i,j))-floor(0.5+img_vecs_old(i,j)));\n\t\t}\n\t}\n\treturn sumOfDiffs;\n\t\n}\n\n\n\n\n\n", "meta": {"hexsha": "75b9271fc1b4187e0316de64a33e61a854aeae88", "size": 3455, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/vision/src/pnp/posit.cpp", "max_stars_repo_name": "yhexie/mrpt", "max_stars_repo_head_hexsha": "0bece2883aa51ad3dc88cb8bb84df571034ed261", "max_stars_repo_licenses": ["OLDAP-2.3"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-25T18:09:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-22T08:14:48.000Z", "max_issues_repo_path": "libs/vision/src/pnp/posit.cpp", "max_issues_repo_name": "yhexie/mrpt", "max_issues_repo_head_hexsha": "0bece2883aa51ad3dc88cb8bb84df571034ed261", "max_issues_repo_licenses": ["OLDAP-2.3"], "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/vision/src/pnp/posit.cpp", "max_forks_repo_name": "yhexie/mrpt", "max_forks_repo_head_hexsha": "0bece2883aa51ad3dc88cb8bb84df571034ed261", "max_forks_repo_licenses": ["OLDAP-2.3"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-16T11:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T11:50:47.000Z", "avg_line_length": 22.0063694268, "max_line_length": 126, "alphanum_fraction": 0.5748191027, "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5221308612430952}}
{"text": "/******************************************************************************\n * Copyright (C) 2013 by Jerome Maye                                          *\n * jerome.maye@gmail.com                                                      *\n ******************************************************************************/\n\n#include <boost/math/distributions/gamma.hpp>\n\n#include \"aslam/calibration/statistics/Randomizer.h\"\n#include \"aslam/calibration/functions/LogGammaFunction.h\"\n#include \"aslam/calibration/functions/DigammaFunction.h\"\n#include \"aslam/calibration/functions/IncompleteGammaPFunction.h\"\n#include \"aslam/calibration/exceptions/BadArgumentException.h\"\n#include \"aslam/calibration/exceptions/InvalidOperationException.h\"\n\nnamespace aslam {\n  namespace calibration {\n\n/******************************************************************************/\n/* Constructors and Destructor                                                */\n/******************************************************************************/\n\n    template <typename T>\n    GammaDistribution<T>::GammaDistribution(const T& shape, double invScale) {\n      setShape(shape);\n      setInvScale(invScale);\n    }\n\n    template <typename T>\n    GammaDistribution<T>::GammaDistribution(const GammaDistribution& other) :\n        mShape(other.mShape),\n        mInvScale(other.mInvScale),\n        mNormalizer(other.mNormalizer) {\n    }\n\n    template <typename T>\n    GammaDistribution<T>& GammaDistribution<T>::operator =\n        (const GammaDistribution& other) {\n      if (this != &other) {\n        mShape = other.mShape;\n        mInvScale = other.mInvScale;\n        mNormalizer = other.mNormalizer;\n      }\n      return *this;\n    }\n\n    template <typename T>\n    GammaDistribution<T>::~GammaDistribution() {\n    }\n\n/******************************************************************************/\n/* Stream operations                                                          */\n/******************************************************************************/\n\n    template <typename T>\n    void GammaDistribution<T>::read(std::istream& stream) {\n    }\n\n    template <typename T>\n    void GammaDistribution<T>::write(std::ostream& stream) const {\n      stream << \"shape: \" << mShape << std::endl\n        << \"inverse scale: \" << mInvScale;\n    }\n\n    template <typename T>\n    void GammaDistribution<T>::read(std::ifstream& stream) {\n    }\n\n    template <typename T>\n    void GammaDistribution<T>::write(std::ofstream& stream) const {\n    }\n\n/******************************************************************************/\n/* Accessors                                                                  */\n/******************************************************************************/\n\n    template <typename T>\n    void GammaDistribution<T>::setShape(const T& shape) {\n      if (shape <= 0)\n        throw BadArgumentException<T>(shape,\n          \"GammaDistribution::setShape(): shape must be strictly positive\",\n          __FILE__, __LINE__);\n      mShape = shape;\n      computeNormalizer();\n    }\n\n    template <typename T>\n    const T& GammaDistribution<T>::getShape() const {\n      return mShape;\n    }\n\n    template <typename T>\n    void GammaDistribution<T>::setInvScale(double invScale) {\n      if (invScale <= 0)\n        throw BadArgumentException<double>(invScale,\n          \"GammaDistribution::setScale(): inverse scale must be \"\n          \"strictly positive\",\n          __FILE__, __LINE__);\n      mInvScale = invScale;\n      computeNormalizer();\n    }\n\n    template <typename T>\n    double GammaDistribution<T>::getInvScale() const {\n      return mInvScale;\n    }\n\n    template <typename T>\n    void GammaDistribution<T>::computeNormalizer() {\n      LogGammaFunction<T> logGammaFunction;\n      mNormalizer = logGammaFunction(mShape) - mShape * log(mInvScale);\n    }\n\n    template <typename T>\n    double GammaDistribution<T>::getNormalizer() const {\n      return mNormalizer;\n    }\n\n    template <typename T>\n    double GammaDistribution<T>::pdf(const RandomVariable& value) const {\n      if (value < 0)\n        return 0.0;\n      else\n        return exp(logpdf(value));\n    }\n\n    template <typename T>\n    double GammaDistribution<T>::logpdf(const RandomVariable& value) const {\n      if (value == 0 && mShape == T(1))\n        return -mNormalizer;\n      else\n        return (mShape - 1) * log(value) - value * mInvScale - mNormalizer;\n    }\n\n    template <typename T>\n    double GammaDistribution<T>::cdf(const RandomVariable& value) const {\n      const IncompleteGammaPFunction incGammaPFunction(mShape);\n      if (value <= 0)\n        return 0.0;\n      else\n        return incGammaPFunction(value * mInvScale);\n    }\n\n    template <typename T>\n    typename GammaDistribution<T>::RandomVariable\n        GammaDistribution<T>::invcdf(double probability) const {\n      if (probability < 0 || probability > 1)\n        throw BadArgumentException<double>(probability,\n          \"GammaDistribution::invcdf(): probability must lie in [0, 1]\",\n          __FILE__, __LINE__);\n        return boost::math::quantile(boost::math::gamma_distribution<>(\n          mShape, 1.0 / mInvScale), probability);\n    }\n\n    template <typename T>\n    typename GammaDistribution<T>::RandomVariable\n        GammaDistribution<T>::getSample() const {\n      const static Randomizer<double> randomizer;\n      return randomizer.sampleGamma(mShape, mInvScale);\n    }\n\n    template <typename T>\n    typename GammaDistribution<T>::Mean GammaDistribution<T>::getMean() const {\n      return mShape / mInvScale;\n    }\n\n    template <typename T>\n    typename GammaDistribution<T>::Mode GammaDistribution<T>::getMode() const {\n      if (mShape >= 1)\n        return (mShape - 1) / mInvScale;\n      else\n        throw InvalidOperationException(\"GammaDistribution<T>::getMode(): \"\n          \"shape must be bigger or equal than 1\");\n    }\n\n    template <typename T>\n    typename GammaDistribution<T>::Variance GammaDistribution<T>::getVariance()\n        const {\n      return mShape / (mInvScale * mInvScale);\n    }\n\n    template <typename T>\n    double GammaDistribution<T>::KLDivergence(const GammaDistribution<T>& other)\n        const {\n      LogGammaFunction<T> logGammaFunction;\n      const DigammaFunction<T> digammaFunction;\n      return (mShape - 1) * digammaFunction(mShape) -\n        (other.mShape - 1) * digammaFunction(other.mShape) -\n        logGammaFunction(mShape) +\n        logGammaFunction(other.mShape) + other.mShape *\n        (log(mInvScale) - log(other.mInvScale)) +\n        mShape * (1.0 / mInvScale - 1.0 / other.mInvScale) * other.mInvScale;\n    }\n\n  }\n}\n", "meta": {"hexsha": "ff1e8a96cd0fe84565b93a4c723236f81aea211d", "size": 6615, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "incremental_calibration/include/aslam/calibration/statistics/GammaDistribution.tpp", "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/include/aslam/calibration/statistics/GammaDistribution.tpp", "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/include/aslam/calibration/statistics/GammaDistribution.tpp", "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": 33.75, "max_line_length": 80, "alphanum_fraction": 0.5635676493, "num_tokens": 1359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5221308612430952}}
{"text": "/*\n * MODULE : bayesFilter - Bayesian Filtering\n * Provides a MuPAD module interface to a filtering class\n */\n\n// Shut up VC++, it has its own problems!\n#if defined(_MSC_VER) && _MSC_VER <= 1200\n#pragma warning(disable:4786)\t// indentifier more 255 chars\n#endif\n\n#include <typeinfo.h>\n#include <string>\n#include <map>\n\t\t\t\t\t\t\t\t// MF macro is define by MuPAD module system\n#undef MF\n#include \"BayesFilter/allFlt.h\" // Include all of Bayesian Filtering library\n#include <boost/random.hpp>\t\t// Fast and good random numbers\n#include \"TNear.h\"\t\t\t\t// Nearest neighbour\n#include \"MuPadConvert.h\"\n\nMMG( info = \"Module: Bayesian Filtering\" ) \n\nnamespace MuC = MuPAD_convert;\nnamespace FM = Bayesian_filter_matrix;\n\n\nclass MuFilter\n/*\n * MuPAD Runtime abstract filter\n *  Polymorphic filter created at Runtime\n *  By forceing all filter classes used at runtime we avoid the need for RTTI\n *  support in filtering library\n */\n{\npublic:\n\tvirtual ~MuFilter() = 0 {}; \n\tvoid checkdef(const Bayesian_filter::Bayes_filter_base* derived) const;\n};\n\n\nvoid MuFilter::checkdef(const Bayesian_filter::Bayes_filter_base* derived) const\n/*\n * Check that derived is defined. If it isn't generate MFerror based on base name\n */\n{\n\tstatic std::string error;\n\tif (!derived) {\n\t\terror = std::string(\"Operation undefine on filter type: \") + typeid(*this).name();\n\t\tMFerror( error.c_str() );\n\t}\n}\n\nstruct Mu_SIR : public MuFilter, public Bayesian_filter::SIR_filter\n{\n\tMu_SIR(unsigned x, unsigned s, Bayesian_filter::SIR_random& r) :\n\t\tSIR_filter(x,s,r) {}\n};\n\nstruct Mu_SIR_kalman : public MuFilter, public Bayesian_filter::SIR_kalman_filter\n{\n\tMu_SIR_kalman(unsigned x, unsigned s, Bayesian_filter::SIR_random& r) :\n\t\tSIR_kalman_filter(x,s,r) {}\n};\n\nstruct Mu_Unscented : public MuFilter, public Bayesian_filter::Unscented_filter\n{\n\tMu_Unscented(unsigned x) : Unscented_filter(x) {}\n};\n\nstruct Mu_Cov : public MuFilter, public Bayesian_filter::Covariance_filter\n{\n\tMu_Cov(unsigned x) : Covariance_filter(x) {}\n};\n\nstruct Mu_Inf : public MuFilter, public Bayesian_filter::Information_filter\n{\n\tMu_Inf(unsigned x) : Information_filter(x) {}\n};\n\nstruct Mu_InfJo : public MuFilter, public Bayesian_filter::Information_joseph_filter\n{\n\tMu_InfJo(unsigned x) : Information_joseph_filter(x) {}\n};\n\nstruct Mu_SRIF : public MuFilter, public Bayesian_filter::Information_root_filter\n{\n\tMu_SRIF(unsigned x) : Information_root_filter(x) {}\n};\n\nstruct Mu_UD : public MuFilter, public Bayesian_filter::UD_filter\n{\n\tMu_UD(unsigned x) : UD_filter(x, x) {}\n};\n\n\n\nclass BFilter_handler\n/*\n * MuPAD interface for Bayesian Filter object\n * Allow them to be accessed by integer handles\n *  Handles start at 1 and increment with each make\n * TODO: Balance the map by using random handles\n */\n{\npublic:\n\tBFilter_handler();\n\tint make (MuFilter*);\n\tMuFilter* remove (MTcell arg);\n\tMuFilter* get_filter(MTcell arg);\nprivate:\n\ttypedef std::map<int,MuFilter*> Flt_map;\n\tFlt_map fltmap;\n\tunsigned handle;\n};\n\nBFilter_handler::BFilter_handler()\n{\n\thandle = 0;\n}\n\nint BFilter_handler::make (MuFilter* f)\n/*\n * Make a handle for a filter\n * Handle overflow by warning and return 0 if handle already in use;\n */\n{\n\t++handle;\n\tif (handle == 0)\n\t{\n\t\tMFputs( \"Filter handle overflow: may prevent creation of more filters\" );\n\t\t++handle;\n\t}\n\n\tstd::pair<Flt_map::iterator, bool> i = fltmap.insert(std::make_pair(handle, f));\n\tif (i.second)\n\t\treturn handle;\n\telse\n\t{\t// Not inserted\n\t\tMFputs( \"Could create unique handle for filter: no filter created\" );\n\t\treturn 0;\n\t}\n};\n\nMuFilter*  BFilter_handler::remove (MTcell arg)\n/*\n * Remove a handle for a filter and return filter pointer if valid\n */\n{\n\tif (!MFisInt(arg))\n\t\tMFerror( \"Filter handle not an Int\" );\n\tconst int h = MFint(arg);\n\tif (h <=0) {\n\t\tMFerror( \"Filter handle incorrect\" );\n\t\treturn 0;\t// Never reached\n\t}\n\tFlt_map::iterator e = fltmap.find(h);\n\tif (e ==fltmap.end()) {\n\t\tMFerror( \"Filter handle incorrect\" );\n\t\treturn 0;\t// Never reached\n\t}\n\n\tMuFilter* f = (*e).second;\n\tfltmap.erase(e);\n\n\treturn f;\n}\n\nMuFilter* BFilter_handler::get_filter (MTcell arg)\n/*\n * Convert a handle into a filter pointer\n */\n{\n\tif (!MFisInt(arg))\n\t\tMFerror( \"Filter handle not an Int\" );\n\tconst int h = MFint(arg);\n\tif (h <=0) {\n\t\tMFerror( \"Filter handle incorrect\" );\n\t\treturn 0;\t// Never reached\n\t}\n\tFlt_map::iterator e = fltmap.find(h);\n\tif (e ==fltmap.end()) {\n\t\tMFerror( \"Filter handle incorrect\" );\n\t\treturn 0;\t// Never reached\n\t}\n\n\treturn (*e).second;\n}\n\n// Maintain state of handles functions innovations\nBFilter_handler Handles;\n\n\n\nclass Boost_random\n/*\n * Random number distributions\n */\n{\npublic:\n\tBoost_random() : gen_normal(rng), gen_uniform(rng)\n\t{\n\t}\n\tdouble normal(const double mean, const double sigma)\n\t{\n\t\tboost::normal_distribution<boost::mt19937> gen(rng, mean, sigma);\n\t\treturn gen();\n\t}\n\tvoid normal(FM::Vec& v)\n\t{\n\t\tstd::generate (v.begin(), v.end(), gen_normal);\n\t}\n\tvoid uniform_01(FM::Vec& v)\n\t{\n\t\tstd::generate (v.begin(), v.end(), gen_uniform);\n\t}\nprivate:\n\tboost::mt19937 rng;\n\tboost::normal_distribution<boost::mt19937> gen_normal;\n\tboost::uniform_01<boost::mt19937> gen_uniform;\n};\n\n// Maintain state of random numbers between function innovations\nstatic Boost_random Random;\n\n\nclass MuPAD_function_model : public Bayesian_filter::Function_model\n/*\n * Function model rapper for a MuPad function\n */\n{\npublic:\n\tMuPAD_function_model(const MTcell ff);\n\tvirtual const FM::Vec& fx(const FM::Vec& x) const;\n\t// Note: Reference return value as a speed optimisation, MUST be copied by caller.\nprivate:\n\tconst MTcell Mu_fn;\n\tmutable FM::Vec rfx;\n};\n\nMuPAD_function_model::MuPAD_function_model(const MTcell ff) :\n\tMu_fn(ff), rfx(FM::Empty)\n{}\n\nconst FM::Vec& MuPAD_function_model::fx(const FM::Vec& x) const\n{\n\tMTcell xarray = MuC::Array(x);\n\tMTcell fxarray = MFcall( MFcopy(Mu_fn), 1, xarray );\n\n\tif (MFisExpr(fxarray))\n\t\tMFerror (\"prediction function not found\");\t// ISSUE: MFerror may leak arrays\n\n\trfx = MuC::Vector(fxarray);\n\tMFfree(xarray);\n\tMFfree(fxarray);\n\treturn rfx;\n};\n\n\n\nclass Likelihood_observe_MuPAD : public Bayesian_filter::Likelihood_observe_model\n/*\n * Likelihood observe model using a MuPad expression\n */\n{\npublic:\n\tLikelihood_observe_MuPAD(unsigned z_size, const MTcell f);\n\t~Likelihood_observe_MuPAD();\n\tFloat L(const FM::Vec& x) const;\n\tvoid Lz(const FM::Vec& z);\nprivate:\n\tconst MTcell Mu_fn;\n\tMTcell Mu_z;\n};\n\nLikelihood_observe_MuPAD::Likelihood_observe_MuPAD(unsigned z_size, const MTcell f) :\n\tLikelihood_observe_model(z_size),\n\tMu_fn(f)\n{\n\tMu_z = 0;\n}\n\nLikelihood_observe_MuPAD::~Likelihood_observe_MuPAD()\n{\n\tif (Mu_z)\n\t\tMFfree(Mu_z);\n}\n\nLikelihood_observe_MuPAD::Float Likelihood_observe_MuPAD::L(const FM::Vec& x) const\n{\n\tMTcell Mu_x = MuC::Array(x);\n\tMTcell Mu_L = MFcall( MFcopy(Mu_fn), 2, MFcopy(Mu_z), Mu_x );\n\n\tif (MFisExpr(Mu_L))\n\t\tMFerror (\"Likelihood observe function not found\");\t// ISSUE: MFerror may leak arrays\n\n\tFloat L = MFdouble(Mu_L);\t\t// ISSUE: Assume Float is double\n\tMFfree(Mu_x);\n\tMFfree(Mu_L);\n\treturn L;\n};\n\nvoid Likelihood_observe_MuPAD::Lz(const FM::Vec& z)\n{\n\tif (Mu_z)\n\t\tMFfree(Mu_z);\n\tMu_z = MuC::Array(z);\n};\n\n\n\n\nclass Boost_SIR_random_helper : public Bayesian_filter::SIR_filter::Random\n/*\n * Random number generator for SIR_filter\n * Uses global Random\n */\n{\npublic:\n\tBoost_SIR_random_helper()\n\t{}\n\tvoid normal(FM::Vec& v)\n\t{\n\t\t::Random.normal(v);\n\t}\n\tvoid uniform_01(FM::Vec& v)\n\t{\n\t\t::Random.uniform_01(v);\n\t}\n};\n\nclass Boost_Predict_random_helper : public Bayesian_filter::General_LiAd_predict_model::Random\n/*\n * Random number generator for General_LiAd_predict_model\n * Uses global Random\n */\n{\npublic:\n\tvoid normal(FM::Vec& v)\n\t{\n\t\t::Random.normal(v);\n\t}\n};\n\n\n\nclass Filter_maker\n/*\n * Make instances of Bayes filters by name\n */\n{\npublic:\n\tFilter_maker();\n\ttypedef MuFilter* Filter;\n\tFilter make (MTcell args);\nprivate:\n\tMTcell MVargs;\t\t// Same name as in MuPAD function so macros work!\n\tunsigned state_size();\n\tBoost_SIR_random_helper randomHelper;\n\n\ttypedef Filter (Filter_maker::* pMake_mem)();\n\ttypedef std::map<std::string, pMake_mem> Make_map;\n\tMake_map filterMakers;\n\n\t// Filter makers\n\tFilter make_SIR();\n\tFilter make_SIR_Kalman();\n\tFilter make_Unscented();\n\tFilter make_Covariance();\n\tFilter make_Information();\n\tFilter make_Information_joseph();\n\tFilter make_SRIF();\n\tFilter make_UD();\n};\n\n\nFilter_maker::Filter_maker()\n/*\n * Construct name-> make mapping\n */\n{\n\tfilterMakers[\"SIR\"] = &Filter_maker::make_SIR;\n\tfilterMakers[\"SIR_Kalman\"] = &Filter_maker::make_SIR_Kalman;\n\tfilterMakers[\"Unscented\"] = &Filter_maker::make_Unscented;\n\tfilterMakers[\"Covariance\"] = &Filter_maker::make_Covariance;\n\tfilterMakers[\"Information\"] = &Filter_maker::make_Information;\n\tfilterMakers[\"InformationJoseph\"] = &Filter_maker::make_Information_joseph;\n\tfilterMakers[\"SRIF\"] = &Filter_maker::make_SRIF;\n\tfilterMakers[\"UD\"] = &Filter_maker::make_UD;\n}\n\nFilter_maker::Filter\n Filter_maker::make (MTcell args)\n/*\n * Use arg to Make instance of a filter\n */\n{\n\tMVargs = args;\t\t\t\t\t// Allow MFarg macros to work in instance\n\tif (MVnargs < 1)\n\t\tMFerror(\"No filter name argument\");\n\tMFargCheck (1, DOM_STRING);\n\n\tstd::string filterTypeName(MFstring(MFarg(1)));\n\t\t\t\t\t\t\t\t// Find the entry in filterMakers map\n\tMake_map::iterator i = filterMakers.find (filterTypeName);\n\n\tFilter f = 0;\n\tif (i != filterMakers.end())\n\t{\t// Call the make member function found to create a filter\n\t\tpMake_mem pmake = i->second;\n\t\tf = (this->*pmake)();\n\t}\n\treturn f;\n};\n\t\n\n\nunsigned Filter_maker::state_size()\n{\n\tMFargCheck (2, DOM_INT);\n\tint ss = MFint(MFarg(2));\n\tif (!(ss > 0))\n\t\tMFerror ( \"state_size must > 0\" );\n\treturn unsigned(ss);\n}\n\nFilter_maker::Filter\n Filter_maker::make_SIR()\n{\n\tMFnargsCheckRange (4,6);\n\n\t\t\t\t// Initialise Sample S with state and covariance\n\tFM::Vec init_x = MuC::Vector(MFarg(3));\n\tFM::Matrix init_X = MuC::Matrix(MFarg(4));\n\t\t\t\t// Defaultable parameters\n\tint sample_size = 1000;\n\tdouble rougheningK = -1;\n\tif (MVnargs >=5)\n\t{\n\t\tMFargCheck (5, DOM_INT);\n\t\tsample_size = MFint(MFarg(5));\n\t\tif (!(sample_size > 0))\n\t\t\tMFerror ( \"sample_size must > 0\" );\n\t}\n\tif (MVnargs >=6)\n\t{\n\t\tMFargCheck (6, DOM_FLOAT);\n\t\trougheningK = MFdouble(MFarg(6));\n\t\tif (!(rougheningK >= 0))\n\t\t\tMFerror ( \"rougheningK must >= 0\" );\n\t}\n\n\tMu_SIR* f = new Mu_SIR(state_size(), sample_size, randomHelper);\n\n\t// Use a temporary filter to create samples\n\tBayesian_filter::SIR_kalman_filter tempS(f->S.size1(), f->S.size2(), randomHelper);\n\ttempS.init_kalman (init_x,init_X);\n\tf->init(tempS.S);\n\t\t\t\t// Overide filter default\n\tif (rougheningK != -1.)\n\t\tf->rougheningK = rougheningK;\n\n\treturn f;\n}\n\nFilter_maker::Filter\n Filter_maker::make_SIR_Kalman()\n{\n\tMFnargsCheckRange (4,6);\n\n\t\t\t\t// Initialise Sample S with state and covariance\n\tFM::Vec init_x = MuC::Vector(MFarg(3));\n\tFM::Matrix init_X = MuC::Matrix(MFarg(4));\n\t\t\t\t// Defaultable parameters\n\tint sample_size = 1000;\n\tdouble rougheningK = -1;\n\tif (MVnargs >=5)\n\t{\n\t\tMFargCheck (5, DOM_INT);\n\t\tsample_size = MFint(MFarg(5));\n\t\tif (!(sample_size > 0))\n\t\t\tMFerror ( \"sample_size must > 0\" );\n\t}\n\tif (MVnargs >=6)\n\t{\n\t\tMFargCheck (6, DOM_FLOAT);\n\t\trougheningK = MFdouble(MFarg(6));\n\t\tif (!(rougheningK >= 0))\n\t\t\tMFerror ( \"rougheningK must >= 0\" );\n\t}\n\n\tMu_SIR_kalman* f = new Mu_SIR_kalman(state_size(), sample_size, randomHelper);\n\n\tf->init_kalman (init_x,init_X);\n\t\t\t\t// Overide filter default\n\tif (rougheningK != -1.)\n\t\tf->rougheningK = rougheningK;\n\n\treturn f;\n}\n\nFilter_maker::Filter\n Filter_maker::make_Unscented()\n{\n\tMFnargsCheck (4);\n\n\t// Initialise with state and covariance\n\tFM::Vec init_x = MuC::Vector(MFarg(3));\n\tFM::Matrix init_X = MuC::Matrix(MFarg(4));\n\t\n\tMu_Unscented* f = new Mu_Unscented(state_size());\n\tf->init_kalman (init_x,init_X);\n\treturn f;\n}\n\nFilter_maker::Filter\n Filter_maker::make_Covariance()\n{\n\tMFnargsCheck (4);\n\n\t// Initialise with state and covariance\n\tFM::Vec init_x = MuC::Vector(MFarg(3));\n\tFM::Matrix init_X = MuC::Matrix(MFarg(4));\n\n\tMu_Cov* f = new Mu_Cov(state_size());\n\tf->init_kalman (init_x,init_X);\n\treturn f;\n}\n\nFilter_maker::Filter\n Filter_maker::make_Information()\n{\n\tMFnargsCheck (4);\n\n\t// Initialise with state and covariance\n\tFM::Vec init_x = MuC::Vector(MFarg(3));\n\tFM::Matrix init_X = MuC::Matrix(MFarg(4));\n\n\tMu_Inf* f = new Mu_Inf(state_size());\n\tf->init_kalman (init_x,init_X);\n\treturn f;\n}\n\nFilter_maker::Filter\n Filter_maker::make_Information_joseph()\n{\n\tMFnargsCheck (4);\n\n\t// Initialise with state and covariance\n\tFM::Vec init_x = MuC::Vector(MFarg(3));\n\tFM::Matrix init_X = MuC::Matrix(MFarg(4));\n\n\tMu_InfJo* f = new Mu_InfJo(state_size());\n\tf->init_kalman (init_x,init_X);\n\treturn f;\n}\n\nFilter_maker::Filter\n Filter_maker::make_SRIF()\n{\n\tMFnargsCheck (4);\n\n\t// Initialise with state and covariance\n\tFM::Vec init_x = MuC::Vector(MFarg(3));\n\tFM::Matrix init_X = MuC::Matrix(MFarg(4));\n\n\tMu_SRIF* f = new Mu_SRIF(state_size());\n\tf->init_kalman (init_x,init_X);\n\treturn f;\n}\n\nFilter_maker::Filter\n Filter_maker::make_UD()\n{\n\tMFnargsCheck (4);\n\n\t// Initialise Sample S with state and covariance\n\tFM::Vec init_x = MuC::Vector(MFarg(3));\n\tFM::Matrix init_X = MuC::Matrix(MFarg(4));\n\n\tMu_UD* f = new Mu_UD(state_size());\n\tf->init_kalman (init_x,init_X);\n\treturn f;\n}\n\n\n// Maintain a set of default filters to make\nFilter_maker DefaultFilters;\n\n\n//\n// Module functions definitions\n//\n\nMFUNC( bfilter, MCnop )\n/*\n * DOM_INT bfilter(String filterTypeName, DOM_INT nstate, DOM_INT nsamples)\n * Create a filter from its names type and return its handle (Int)\n */\n{\n\t// Construct Filter  - Must catch exceptions for MuPAD kernel\n\tMuFilter* filter;\n\ttry\n\t{\n\t\tfilter = DefaultFilters.make (MVargs);\n\t\tif (!filter)\n\t\t\tMFerror( \"Unknown filter type name\" );\n\t}\n\tcatch (Bayesian_filter::Bayes_filter_exception fe)\n\t{\n\t\tMFerror( fe.what() );\n\t}\n\tcatch (...)\n\t{\n\t\tMFerror( \"Caused a system exception\" );\n\t}\n\n\t// Make a handle to return.\n\tconst int h = Handles.make (filter);\n\tif (!h)\t\t// Not Created\n\t\tdelete filter;\n\tMFreturn (MFint(h));\n} MFEND \n\n\nMFUNC( free, MCnop )\n/*\n * DOM_NULL free(DOM_INT hFtiler)\n * free the resources associated with a filter handle\n * The handle thus invalidated\n */\n{\n\tMFnargsCheck( 1 );\n\tMuFilter* filter = Handles.remove(MFarg(1));\n\n\tif (filter)\n\t{\n\t\tdelete filter;\n\t}\n\n\tMFreturn (MFcopy(MVnull));\n} MFEND\n\n\nMFUNC( predict_functional, MCnop )\n/*\n * DOM_NULL predict_functional (DOM_INT hFilter, DOM_PROC f)\n *  Predict filter with zero noise through function f(x)\n */\n{\n\tMFnargsCheck (2);\n\tMuFilter* filter = Handles.get_filter(MFarg(1));\n\n\t// Must be a Functional filter\n\tBayesian_filter::Functional_filter* f = dynamic_cast<Bayesian_filter::Functional_filter*>(filter);\n\tfilter->checkdef(f);\n\n\tclass FF : public Bayesian_filter::Functional_predict_model\n\t{\t// Functional form\n\t\tBayesian_filter::Function_model& ff;\n\tpublic:\n\t\tFF (Bayesian_filter::Function_model& f_init) :\n\t\t\tff(f_init)\n\t\t{}\n\t\tvirtual const FM::Vec& fx(const FM::Vec& x) const\n\t\t{\treturn ff.fx(x);\n\t\t}\n\t};\n\n\ttry\n\t{\n\t\t// Predict filter using MuPAD expression\n\t\tMuPAD_function_model mu_f(MFarg(2));\n\n\t\tf->predict (FF(mu_f));\n\t\tMFreturn (MFcopy(MVnull));\n\t}\n\tcatch (Bayesian_filter::Bayes_filter_exception fe)\n\t{\n\t\tMFerror( fe.what() );\n\t}\n} MFEND\n\n\nMFUNC( predict_additive, MCnop )\n/*\n * DOM_REAL predict_additive (DOM_INT hFilter, DOM_PROC f, DOM_Array q, DOM_Array G)\n *  Predict filter with additive noise Gq\n */\n{\n\tMFnargsCheck (4);\n\tMuFilter* filter = Handles.get_filter(MFarg(1));\n\tFM::Vec    q = MuC::Vector(MFarg(3));\n\tFM::Matrix G = MuC::Matrix(MFarg(4));\n\n\t// Check matrix conformance\n\t{\n\t\tBayesian_filter::State_filter* f = dynamic_cast<Bayesian_filter::State_filter*>(filter);\n\t\tfilter->checkdef(f);\n\n\t\tif (f->x.size() != G.size1())\n\t\t\tMFerror(\"Mismatch in x and G size\");\n\t\tif (q.size() != G.size2())\n\t\t\tMFerror(\"Mismatch in q and G size\");\n\t}\n\n\tbool bFilterOp = false;\t\t\t// Flag operation complete to avoid MFerror in try block\n\tdouble rcond;\n\ttry\n\t{\n\t\t// Predict filter using MuPAD expression\n\t\tMuPAD_function_model mu_f(MFarg(2));\n\t\tBayesian_filter::Simple_additive_predict_model model(mu_f, G, q);\n\t\tMFerror (\"Not implemented\");\n\n#ifdef UNIMPLEMENTED\n// TODO Requires General_LzAd_predict_model\n\t\tBoost_Predict_random_helper predict_random;\n\t\tBayesian_filter::General_LzAd_predict_model Lmodel(G.size1(), q.size(), predict_random);\n\t\t// Use mu_f to construct Lmodel\n\t\tFM::copy (model.q, Lmodel.q);\n\t\tFM::copy (model.G, Lmodel.G);\n\n\t\t// Must be a Sample filter\n\t\tif (Bayesian_filter::Sample_filter* f = dynamic_cast<Bayesian_filter::Sample_filter*>(filter)) {\n\t\t\tbFilterOp = true;\n\t\t\tf->predict (Lmodel);\n\t\t\trcond = 0.;\n\t\t}\n#endif\n\t}\n\tcatch (Bayesian_filter::Bayes_filter_exception fe)\n\t{\n\t\tMFerror( fe.what() );\n\t}\n\n\tif (bFilterOp) {\n\t\tMFreturn (MFdouble(rcond));\n\t}\n\telse {\n\t\tfilter->checkdef(0);\n\t}\n} MFEND\n\n\nMFUNC( predict_linear, MCnop )\n/*\n * DOM_REAL predict_linear (DOM_INT hFilter, DOM_Array F, DOM_Array G, DOM_Array q)\n *  Predict filter with additive noise Gq\n */\n{\n\tMFnargsCheck (4);\n\tMuFilter* filter = Handles.get_filter(MFarg(1));\n\tFM::Matrix Fx = MuC::Matrix(MFarg(2));\n\tFM::Matrix G = MuC::Matrix(MFarg(3));\n\tFM::Vec    q = MuC::Vector(MFarg(4));\n\n\t// Check matrix conformance\n\t{\n\t\tBayesian_filter::State_filter* f = dynamic_cast<Bayesian_filter::State_filter*>(filter);\n\t\tfilter->checkdef(f);\n\n\t\tif (f->x.size() != Fx.size1())\n\t\t\tMFerror(\"Mismatch in x and Fx matrix\");\n\t\tif (Fx.size1() != Fx.size2())\n\t\t\tMFerror(\"Mismatch Fx not square\");\n\t\tif (f->x.size() != G.size1())\n\t\t\tMFerror(\"Mismatch in x and G size\");\n\t\tif (q.size() != G.size2())\n\t\t\tMFerror(\"Mismatch in q and G size\");\n\t}\n\n\tbool bFilterOp = false;\t\t\t// Flag operation complete to avoid MFerror in try block\n\tdouble rcond;\n\ttry\n\t{\n\t\t// Predict filter \n\t\tBoost_Predict_random_helper random;\n\t\tBayesian_filter::General_LiAd_predict_model model(Fx.size1(), q.size(), random);\n\t\tmodel.Fx = Fx;\n\t\tmodel.q = q;\n\t\tmodel.G = G;\n\n\t\t// Must be a Likelihood, or Sample filter\n\t\tif (Bayesian_filter::Sample_filter* f = dynamic_cast<Bayesian_filter::Sample_filter*>(filter)) {\n\t\t\tbFilterOp = true;\n\t\t\tf->predict (model);\n\t\t\trcond = 0.;\n\t\t}\n\t\telse\n\t\tif (Bayesian_filter::Linrz_filter* f = dynamic_cast<Bayesian_filter::Linrz_filter*>(filter)) {\n\t\t\tbFilterOp = true;\n\t\t\trcond = f->predict (model);\n\t\t}\n\t}\n\tcatch (Bayesian_filter::Bayes_filter_exception fe)\n\t{\n\t\tMFerror( fe.what() );\n\t}\n\n\tif (bFilterOp) {\n\t\tMFreturn (MFdouble(rcond));\n\t}\n\telse {\n\t\tfilter->checkdef(0);\n\t}\n} MFEND\n\n\nMFUNC( observe_likelihood, MCnop )\n/*\n * DOM_REAL observe_likelihood (DOM_INT hFilter, DOM_PROC L, DOM_ARRAY z)\n *  Observe filter with Likelihood L(z,x)\n */\n{\n\tMFnargsCheck (3);\n\tMuFilter* filter = Handles.get_filter(MFarg(1));\n\tFM::Vec    z = MuC::Vector(MFarg(3));\n\n\t// Must be a Sample filter\n\tBayesian_filter::Sample_filter* f = dynamic_cast<Bayesian_filter::Sample_filter*>(filter);\n\tfilter->checkdef(f);\n\n\ttry\n\t{\n\t\t// Observe filter using MuPAD expression\n\t\tLikelihood_observe_MuPAD model(z.size(), MFarg(2));\n\t\tf->observe(model, z);\n\t\tdouble rcond;\n\t\tf->update (rcond);\n\t\tMFreturn (MFdouble(rcond));\n\t}\n\tcatch (Bayesian_filter::Bayes_filter_exception fe)\n\t{\n\t\tMFerror( fe.what() );\n\t}\n} MFEND\n\n\nMFUNC( observe_linear_uncorrelated, MCnop )\n/*\n * DOM_REAL observe_linear_uncorrelated (DOM_INT hFilter, DOM_ARRAY H, DOM_ARRAY z, DOM_ARRAY Zd)\n *  Observe z with noise Zv through linear H\n */\n{\n\tMFnargsCheck (4);\n\tMuFilter* filter = Handles.get_filter(MFarg(1));\n\tFM::Matrix H = MuC::Matrix(MFarg(2));\n\tFM::Vec    z = MuC::Vector(MFarg(3));\n\tFM::Vec\t  Zv = MuC::Vector(MFarg(4));\n\n\t{\n\t\tconst Bayesian_filter::State_filter* f = dynamic_cast<const Bayesian_filter::State_filter*>(filter);\n\t\tfilter->checkdef(f);\n\n\t\t// Check matrix conformance\n\t\tif (f->x.size() != H.size2())\n\t\t\tMFerror(\"Mismatch in x and H matrix\");\n\t\tif (z.size() != H.size1())\n\t\t\tMFerror(\"Mismatch in z and H matrix\");\n\t\tif (Zv.size() != z.size())\n\t\t\tMFerror(\"Mismatch in z and Zv size\");\n\t}\n\n\tbool bFilterOp = false;\t\t\t// Flag operation to avoid MFerror in try block\n\tdouble rcond;\n\ttry\n\t{\n\t\t// Observe filter\n\t\tBayesian_filter::General_LiUnAd_observe_model model(H.size2(), z.size());\n\t\tmodel.Hx = H;\n\t\tmodel.Zv = Zv;\n\n\t\t// Must be a Sample, Linrz filter\n\t\tif (Bayesian_filter::Sample_filter* f = dynamic_cast<Bayesian_filter::Sample_filter*>(filter)) {\n\t\t\tbFilterOp = true;\n\t\t\tf->observe (model, z);\n\t\t\tdouble rcond;\n\t\t\tf->update (rcond);\n\t\t}\n\t\telse\n\t\tif (Bayesian_filter::Linrz_filter* f = dynamic_cast<Bayesian_filter::Linrz_filter*>(filter)) {\n\t\t\tbFilterOp = true;\n\t\t\trcond = f->observe (model, z);\n\t\t}\n\t}\n\tcatch (Bayesian_filter::Bayes_filter_exception fe)\n\t{\n\t\tMFerror( fe.what() );\n\t}\n\n\tif (bFilterOp) {\n\t\tMFreturn (MFdouble(rcond));\n\t}\n\telse {\n\t\tfilter->checkdef(0);\n\t}\n} MFEND\n\n\nMFUNC( observe_linear_correlated, MCnop )\n/*\n * DOM_REAL observe_linear_correlated (DOM_INT hFilter, DOM_ARRAY H, DOM_ARRAY z, DOM_ARRAY Z)\n *  Observe z with noise Zv through linear H\n */\n{\n\tMFnargsCheck (4);\n\tMuFilter* filter = Handles.get_filter(MFarg(1));\n\tFM::Matrix H = MuC::Matrix(MFarg(2));\n\tFM::Vec    z = MuC::Vector(MFarg(3));\n\tFM::Matrix Z = MuC::Matrix(MFarg(4));\n\n\t{\n\t\tconst Bayesian_filter::State_filter* f = dynamic_cast<const Bayesian_filter::State_filter*>(filter);\n\t\tfilter->checkdef(f);\n\n\t\t// Check matrix conformance\n\t\tif (f->x.size() != H.size2())\n\t\t\tMFerror(\"Mismatch in x and H matrix\");\n\t\tif (z.size() != H.size1())\n\t\t\tMFerror(\"Mismatch in z and H matrix\");\n\t\tif (Z.size1() != z.size())\n\t\t\tMFerror(\"Mismatch in z and Z size\");\n\t\tif (Z.size1() != Z.size2())\n\t\t\tMFerror(\"Mismatch Z not square\");\n\t}\n\n\tbool bFilterOp = false;\t\t\t// Flag operation to avoid MFerror in try block\n\tdouble rcond;\n\ttry\n\t{\n\t\t// Observe filter \n\t\tBayesian_filter::General_LiCoAd_observe_model model(H.size2(), z.size());\n\t\tmodel.Hx = H;\n\t\tmodel.Z = Z;\n\t\t// Must be a Sample, Linrz filter\n\t\tif (Bayesian_filter::Sample_filter* f = dynamic_cast<Bayesian_filter::Sample_filter*>(filter)) {\n\t\t\tbFilterOp = true;\n\t\t\tf->observe (model, z);\n\t\t\tf->update (rcond);\n\t\t}\n\t\telse\n\t\tif (Bayesian_filter::Linrz_filter* f = dynamic_cast<Bayesian_filter::Linrz_filter*>(filter)) {\n\t\t\tbFilterOp = true;\n\t\t\trcond = f->observe (model, z);\n\t\t}\n\t}\n\tcatch (Bayesian_filter::Bayes_filter_exception fe)\n\t{\n\t\tMFerror( fe.what() );\n\t}\n\n\tif (bFilterOp) {\n\t\tMFreturn (MFdouble(rcond));\n\t}\n\telse {\n\t\tfilter->checkdef(0);\n\t}\n} MFEND\n\n\nMFUNC( mean, MCnop )\n/*\n * DOM_ARRAY mean(DOM_INT hFilter)\n *  mean of filter state\n */\n{\n\tMFnargsCheck( 1 );\n\tMuFilter* filter = Handles.get_filter(MFarg(1));\n\n\t// Must be a State filter\n\tBayesian_filter::State_filter* f = dynamic_cast<Bayesian_filter::State_filter*>(filter);\n\tfilter->checkdef(f);\n\n\t// Process Filter  - Must catch exceptions for MuPAD kernel\n\ttry\n\t{\n\t\tf->update();\n\t\tMFreturn(MuC::Array(f->x));\n\t}\n\tcatch (Bayesian_filter::Bayes_filter_exception fe)\n\t{\n\t\tMFerror( fe.what() );\n\t}\n} MFEND \n\n\nMFUNC( covariance, MCnop )\n/*\n * DOM_ARRAY covariance (DOM_INT hFilter)\n *  covariance of filter state\n */\n{\n\tMFnargsCheck( 1 );\n\tMuFilter* filter = Handles.get_filter(MFarg(1));\n\n\t// Must be a Kalman filter\n\tBayesian_filter::Kalman_filter* f = dynamic_cast<Bayesian_filter::Kalman_filter*>(filter);\n\tfilter->checkdef(f);\n\n\t// Process Filter  - Must catch exceptions for MuPAD kernel\n\ttry\n\t{\n\t\tf->update();\n\t\tMFreturn(MuC::Array(f->X));\n\t}\n\tcatch (Bayesian_filter::Bayes_filter_exception fe)\n\t{\n\t\tMFerror( fe.what() );\n\t}\n} MFEND \n\n\nMFUNC( unique_samples, MCnop )\n/*\n * DOM_INT unique_samples (DOM_INT hFilter)\n *  no of unique (different value) samples in Filter\n */\n{\n\tMFnargsCheck( 1 );\n\tMuFilter* filter = Handles.get_filter(MFarg(1));\n\n\t// Must be a Sample filter\n\tBayesian_filter::Sample_filter* f = dynamic_cast<Bayesian_filter::Sample_filter*>(filter);\n\tfilter->checkdef(f);\n\n\t// Process Filter  - Must catch exceptions for MuPAD kernel\n\ttry\n\t{\n\t\tunsigned nsample = f->unique_samples();\n\t\tMFreturn(MFint(nsample));\n\t}\n\tcatch (Bayesian_filter::Bayes_filter_exception fe)\n\t{\n\t\tMFerror( fe.what() );\n\t}\n} MFEND \n\n\nMFUNC( stochastic_samples, MCnop )\n/*\n * DOM_INT stochastic_samples (DOM_INT hFilter)\n *  no of unique (stochastic history) samples in Filter\n */\n{\n\tMFnargsCheck( 1 );\n\tMuFilter* filter = Handles.get_filter(MFarg(1));\n\n\t// Must be a SIR filter\n\tBayesian_filter::SIR_filter* f = dynamic_cast<Bayesian_filter::SIR_filter*>(filter);\n\tfilter->checkdef(f);\n\n\t// Process Filter  - Must catch exceptions for MuPAD kernel\n\ttry\n\t{\n\t\tunsigned nsample = f->stochastic_samples;\n\t\tMFreturn(MFint(nsample));\n\t}\n\tcatch (Bayesian_filter::Bayes_filter_exception fe)\n\t{\n\t\tMFerror( fe.what() );\n\t}\n} MFEND \n\n\nMFUNC( sample, MCnop )\n/*\n * DOM_LIST sample (DOM_INT hFilter)\n *  Return samples (list of lists) reresenting filters state probability distribution.\n *  If the filter is represented by samples these direcly used\n *  otherwise a set of samples are generated to represent it\n */\n{\n\tconst unsigned GenerateSamples = 1000;\n\tMFnargsCheck( 1 );\n\tMuFilter* filter = Handles.get_filter(MFarg(1));\n\n\t// Process filter by type - Must catch exceptions for MuPAD kernel\n\ttry\n\t{\n\t\t// Sample filter is easy\n\t\t{\n\t\t\tBayesian_filter::Sample_filter* sf = dynamic_cast<Bayesian_filter::Sample_filter*>(filter);\n\t\t\tif (sf) {\n\t\t\t\tMFreturn(MuC::ListTranspose(sf->S));\n\t\t\t}\n\t\t}\n\n\t\t// Kalman filter requres more work. Create Samples from a mean and covariance of Kalman filter\n\t\t{\n\t\t\tBayesian_filter::Kalman_filter* kf = dynamic_cast<Bayesian_filter::Kalman_filter*>(filter);\n\t\t\tif (kf) {\n\t\t\t\tkf->update();\n\t\t\t\tBoost_SIR_random_helper randomHelper;\n\t\t\t\tBayesian_filter::SIR_kalman_filter tempS(kf->x.size(), GenerateSamples, randomHelper);\n\t\t\t\ttempS.init_kalman (kf->x, kf->X);\n\t\t\t\tMFreturn(MuC::ListTranspose(tempS.S));\n\t\t\t}\n\t\t}\n\n\t\t// Fall through if type unknown\n\t\tfilter->checkdef(0);\n\t}\n\tcatch (Bayesian_filter::Bayes_filter_exception fe)\n\t{\n\t\tMFerror( fe.what() );\n\t}\n} MFEND \n\n\n#error This is wrong V must be a pointer like object\nclass V  \n{\t// Vector proxy and difference for Neariest Neighbour\npublic:\n\ttypedef FM::ColMatrix::const_Column NNVec;\n\n\tdouble distance (const V& o) const\n\t{\n\t\tdouble d = 0.;\n\t\tNNVec::const_iterator oi = (o.dp).begin();\n\t\tfor (NNVec::const_iterator vi = (dp).begin(); vi != (dp).end(); ++vi, ++oi) {\n\t\t\tconst double diff = *vi - *oi;\n\t\t\td += diff*diff;\n\t\t}\n\t\treturn sqrt(d);\n\t}\n\tV()\t// Empty for return value\n\t{\n\t}\n\tV( const FM::ColMatrix& colmat, std::size_t i) : dp(colmat,i)\n\t{\n\t}\n\tNNVec dp;\t// Vec data pointer\n};\n\nFM::Vec find_nearest(const FM::ColMatrix& S, double radius, const FM::Vec& loc)\n/*\n * Find the nearest neighbour to loc in S\n */\n{\n\t// Construct NN tree of samples\n\tCNearTree<V> sampleTree;\n\tfor (std::size_t si = 0; si != S.size2(); ++si) {\n\t\tsampleTree.m_fnInsert( V(S,si) );\n\t}\n\t// Create a location as same type as a sample\n\tFM::ColMatrix cmloc(S.size1(),1);\n\tFM::column(cmloc,0) = loc;\n\n\t// Find NN\n\tV nn;\n\tif (sampleTree.m_bfnNearestNeighbor(radius, nn, V(cmloc,0)) )\n\t{\n\t\tFM::Vec rnn(S.size1());\n\t\trnn = nn.dp;\n\t\treturn rnn;\n\t}\n\telse\n\t{\t// No NN\n\t\tFM::Vec rnn(FM::Empty);\n\t\treturn rnn;\n\n\t}\n}\n\nMFUNC( nearest_sample, MCnop )\n/*\n * Find nearest neighbour in a sample\n */\n{\n\tMFnargsCheck( 3 );\n\tMuFilter* filter = Handles.get_filter(MFarg(1));\n\tdouble\t  radius = MFdouble(MFarg(2));\n\tFM::Vec   loc = MuC::Vector(MFarg(3));\n\n\t// Process filter by type - Must catch exceptions for MuPAD kernel\n\ttry\n\t{\n\t\t// Sample filter is easy\n\t\t{\n\t\t\tBayesian_filter::Sample_filter* sf = dynamic_cast<Bayesian_filter::Sample_filter*>(filter);\n\t\t\tif (sf) {\n\t\t\t\tMFreturn( MuC::List(find_nearest(sf->S, radius, loc)) );\n\t\t\t}\n\t\t}\n\n\t\t// Fall through if type unknown\n\t\tfilter->checkdef(0);\n\t}\n\tcatch (Bayesian_filter::Bayes_filter_exception fe)\n\t{\n\t\tMFerror( fe.what() );\n\t}\n} MFEND\n\n\nMFUNC( _test, MCnop )\n/*\n * testing\n */\n{\n\tMFnargsCheck( 0 );\n\n\tMFreturn (MFcopy(MVnull));\n\n\t//FM::Vec v = MuC::Vector(MFarg(2)); \n\t//MFreturn (MuC::List(v));\n\n} MFEND\n", "meta": {"hexsha": "3e14a493d51d2394cbd7068e9bf9e2ffcae83cae", "size": 27637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MuPad/bfilter.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": "MuPad/bfilter.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": "MuPad/bfilter.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": 22.8593879239, "max_line_length": 102, "alphanum_fraction": 0.6934906104, "num_tokens": 8317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6442251064863698, "lm_q1q2_score": 0.5221308612430952}}
{"text": "#include <stan/math/rev.hpp>\n#include <gtest/gtest.h>\n#include <test/unit/math/rev/util.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <vector>\n\ntemplate <typename T_x>\nstd::vector<T_x> fill_vec(Eigen::Matrix<T_x, -1, 1> inp) {\n  std::vector<T_x> ret_vec;\n  ret_vec.reserve(inp.rows());\n  for (int i = 0; i < inp.rows(); ++i)\n    ret_vec.push_back(inp(i));\n  return ret_vec;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, -1, -1> create_mat(Eigen::VectorXd inp, T alpha, T len,\n                                    T jitter) {\n  std::vector<double> test_inp = fill_vec(inp);\n  Eigen::Matrix<T, -1, -1> test_mat_dense\n      = stan::math::cov_exp_quad(test_inp, alpha, len);\n  for (int i = 0; i < inp.rows(); ++i)\n    test_mat_dense(i, i) = test_mat_dense(i, i) + jitter;\n  return test_mat_dense;\n}\n\nstruct gp_chol {\n  Eigen::VectorXd inp, mean, y;\n  gp_chol(Eigen::VectorXd inp_, Eigen::VectorXd mean_, Eigen::VectorXd y_)\n      : inp(inp_), mean(mean_), y(y_) {}\n  template <typename T>\n  T operator()(Eigen::Matrix<T, -1, 1> x) const {\n    Eigen::Matrix<T, -1, -1> x_c = create_mat(inp, x[0], x[1], x[2]);\n    Eigen::Matrix<T, -1, -1> L = stan::math::cholesky_decompose(x_c);\n    T lp = stan::math::multi_normal_cholesky_lpdf(y, mean, L);\n    return lp;\n  }\n};\n\nstruct chol_functor {\n  int i, j, K;\n  chol_functor(int i_, int j_, int K_) : i(i_), j(j_), K(K_) {}\n  template <typename T>\n  T operator()(Eigen::Matrix<T, -1, 1> x) const {\n    using stan::math::cholesky_decompose;\n    using stan::math::cov_matrix_constrain;\n    T lp(0.0);\n    Eigen::Matrix<T, -1, -1> x_c = cov_matrix_constrain(x, K, lp);\n    Eigen::Matrix<T, -1, -1> L = cholesky_decompose(x_c);\n    lp += L(i, j);\n    return lp;\n  }\n};\n\nstruct chol_functor_mult_scal {\n  int K;\n  Eigen::VectorXd vec;\n  chol_functor_mult_scal(int K_, Eigen::VectorXd vec_) : K(K_), vec(vec_) {}\n  template <typename T>\n  T operator()(Eigen::Matrix<T, -1, 1> x) const {\n    using stan::math::cholesky_decompose;\n    using stan::math::cov_matrix_constrain;\n    using stan::math::multiply;\n    using stan::math::transpose;\n    T lp(0.0);\n    Eigen::Matrix<T, -1, -1> x_c = cov_matrix_constrain(x, K, lp);\n    Eigen::Matrix<T, -1, -1> L = cholesky_decompose(x_c);\n    lp += multiply(transpose(vec), multiply(L, vec));\n    return lp;\n  }\n};\n\nstruct chol_functor_2 {\n  int K;\n  explicit chol_functor_2(int K_) : K(K_) {}\n  template <typename T>\n  T operator()(Eigen::Matrix<T, -1, 1> x) const {\n    using stan::math::cholesky_decompose;\n    using stan::math::cov_matrix_constrain;\n    using stan::math::multi_normal_cholesky_log;\n    T lp(0.0);\n    Eigen::Matrix<T, -1, -1> x_c = cov_matrix_constrain(x, K, lp);\n    Eigen::Matrix<T, -1, -1> L = cholesky_decompose(x_c);\n    Eigen::Matrix<double, -1, 1> vec(K);\n    Eigen::Matrix<double, -1, 1> mu(K);\n    vec.setZero();\n    mu.setOnes();\n    lp += multi_normal_cholesky_log(vec, mu, L);\n    return lp;\n  }\n};\n\nstruct chol_functor_simple {\n  int i, j, K;\n  chol_functor_simple(int i_, int j_, int K_) : i(i_), j(j_), K(K_) {}\n  template <typename T>\n  T operator()(Eigen::Matrix<T, -1, 1> x) const {\n    using stan::math::cholesky_decompose;\n    Eigen::Matrix<T, -1, -1> x_c(K, K);\n    int pos = 0;\n    for (int n = 0; n < K; ++n)\n      for (int m = 0; m < K; ++m) {\n        x_c(m, n) = x(pos++);\n        x_c(n, m) = x_c(m, n);\n      }\n    Eigen::Matrix<T, -1, -1> L = cholesky_decompose(x_c);\n    return L(i, j);\n  }\n};\n\nstruct chol_functor_simple_vec {\n  int K;\n  Eigen::VectorXd vec;\n  chol_functor_simple_vec(int K_, Eigen::VectorXd vec_) : K(K_), vec(vec_) {}\n  template <typename T>\n  T operator()(Eigen::Matrix<T, -1, 1> x) const {\n    using stan::math::cholesky_decompose;\n    using stan::math::multiply;\n    using stan::math::transpose;\n    Eigen::Matrix<T, -1, -1> x_c(K, K);\n    int pos = 0;\n    for (int n = 0; n < K; ++n)\n      for (int m = 0; m < K; ++m) {\n        x_c(m, n) = x(pos++);\n        x_c(n, m) = x_c(m, n);\n      }\n    Eigen::Matrix<T, -1, -1> L = cholesky_decompose(x_c);\n    T lp = multiply(transpose(vec), multiply(L, vec));\n    return lp;\n  }\n};\n\nvoid test_gradients(int size, double prec) {\n  std::vector<std::vector<chol_functor> > functors;\n  std::vector<std::vector<Eigen::Matrix<double, -1, 1> > > grads_ad;\n  std::vector<std::vector<Eigen::Matrix<double, -1, 1> > > grads_fd;\n  Eigen::Matrix<double, -1, -1> evals_ad(size, size);\n  Eigen::Matrix<double, -1, -1> evals_fd(size, size);\n  functors.resize(size);\n  grads_ad.resize(size);\n  grads_fd.resize(size);\n\n  for (int i = 0; i < size; ++i)\n    for (int j = 0; j < size; ++j) {\n      functors[i].push_back(chol_functor(i, j, size));\n      grads_fd[i].push_back(Eigen::Matrix<double, -1, 1>(size));\n      grads_ad[i].push_back(Eigen::Matrix<double, -1, 1>(size));\n    }\n\n  int numels = size + size * (size - 1) / 2;\n  Eigen::Matrix<double, -1, 1> x(numels);\n  for (int i = 0; i < numels; ++i)\n    x(i) = i % 10 / 100.0;\n\n  for (size_t i = 0; i < static_cast<size_t>(size); ++i) {\n    for (size_t j = 0; j < static_cast<size_t>(size); ++j) {\n      stan::math::gradient(functors[i][j], x, evals_ad(i, j), grads_ad[i][j]);\n      stan::math::finite_diff_gradient(functors[i][j], x, evals_fd(i, j),\n                                       grads_fd[i][j]);\n\n      for (int k = 0; k < numels; ++k)\n        EXPECT_NEAR(grads_fd[i][j](k), grads_ad[i][j](k), prec);\n      EXPECT_FLOAT_EQ(evals_fd(i, j), evals_ad(i, j));\n    }\n  }\n}\n\nvoid test_gradients_simple(int size, double prec) {\n  std::vector<std::vector<chol_functor_simple> > functors;\n  std::vector<std::vector<Eigen::Matrix<double, -1, 1> > > grads_ad;\n  std::vector<std::vector<Eigen::Matrix<double, -1, 1> > > grads_fd;\n  Eigen::Matrix<double, -1, -1> evals_ad(size, size);\n  Eigen::Matrix<double, -1, -1> evals_fd(size, size);\n  functors.resize(size);\n  grads_ad.resize(size);\n  grads_fd.resize(size);\n\n  for (int i = 0; i < size; ++i)\n    for (int j = 0; j < size; ++j) {\n      functors[i].push_back(chol_functor_simple(i, j, size));\n      grads_fd[i].push_back(Eigen::Matrix<double, -1, 1>(size));\n      grads_ad[i].push_back(Eigen::Matrix<double, -1, 1>(size));\n    }\n\n  stan::math::welford_covar_estimator estimator(size);\n\n  boost::random::mt19937 rng;\n  for (int i = 0; i < 1000; ++i) {\n    Eigen::VectorXd q(size);\n    for (int j = 0; j < size; ++j)\n      q(j) = stan::math::normal_rng(0.0, 1.0, rng);\n    estimator.add_sample(q);\n  }\n\n  Eigen::MatrixXd covar(size, size);\n  estimator.sample_covariance(covar);\n\n  Eigen::Matrix<double, -1, 1> x(size * size);\n  int pos = 0;\n  for (int j = 0; j < size; ++j)\n    for (int i = 0; i < size; ++i)\n      x(pos++) = covar(i, j);\n\n  for (size_t j = 0; j < static_cast<size_t>(size); ++j) {\n    for (size_t i = j; i < static_cast<size_t>(size); ++i) {\n      stan::math::gradient(functors[i][j], x, evals_ad(i, j), grads_ad[i][j]);\n      stan::math::finite_diff_gradient(functors[i][j], x, evals_fd(i, j),\n                                       grads_fd[i][j]);\n\n      for (int k = 0; k < size; ++k)\n        EXPECT_NEAR(grads_fd[i][j](k), grads_ad[i][j](k), prec);\n      EXPECT_FLOAT_EQ(evals_fd(i, j), evals_ad(i, j));\n    }\n  }\n}\n\nvoid test_gp_grad(int mat_size, double prec) {\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n  using stan::math::var;\n\n  Eigen::VectorXd test_vec(mat_size);\n  Eigen::VectorXd mean_vec(mat_size);\n  Eigen::VectorXd draw_vec(mat_size);\n  Eigen::VectorXd test_vals(3);\n  test_vals[0] = 1;\n  test_vals[1] = 1.5;\n  test_vals[2] = 10;\n\n  boost::random::mt19937 rng(2);\n\n  for (int i = 0; i < mat_size; ++i) {\n    test_vec(i) = stan::math::normal_rng(0.0, 0.1, rng);\n    mean_vec(i) = 0;\n    draw_vec(i) = stan::math::normal_rng(0.0, 0.1, rng);\n  }\n\n  Eigen::MatrixXd cov_mat\n      = create_mat(test_vec, test_vals[0], test_vals[1], test_vals[2]);\n  Eigen::MatrixXd chol_cov = cov_mat.llt().matrixL();\n  Eigen::VectorXd y_vec = chol_cov * draw_vec;\n\n  gp_chol gp_fun(test_vec, mean_vec, y_vec);\n  double val_ad;\n  Eigen::VectorXd grad_ad;\n  stan::math::gradient(gp_fun, test_vals, val_ad, grad_ad);\n\n  VectorXd grad_fd;\n  double val_fd;\n\n  stan::math::finite_diff_gradient(gp_fun, test_vals, val_fd, grad_fd);\n  EXPECT_NEAR(val_fd, val_ad, 1e-10);\n  for (int i = 0; i < grad_ad.size(); ++i) {\n    EXPECT_NEAR(grad_fd(i), grad_ad(i), prec);\n  }\n}\n\nvoid test_chol_mult(int mat_size, double prec) {\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n  using stan::math::var;\n\n  int vec_size = mat_size * (mat_size + 1) / 2;\n  Eigen::VectorXd test_vec(mat_size);\n  Eigen::VectorXd test_vals(vec_size);\n\n  boost::random::mt19937 rng(2);\n\n  for (int i = 0; i < test_vals.size(); ++i) {\n    if (i < test_vec.size()) {\n      test_vec(i) = stan::math::normal_rng(0.0, 0.1, rng);\n    }\n    test_vals(i) = i % 10 / 100.0;\n  }\n\n  chol_functor_mult_scal mult_fun(mat_size, test_vec);\n  double val_ad;\n  Eigen::VectorXd grad_ad;\n  stan::math::gradient(mult_fun, test_vals, val_ad, grad_ad);\n\n  VectorXd grad_fd;\n  double val_fd;\n\n  stan::math::finite_diff_gradient(mult_fun, test_vals, val_fd, grad_fd);\n  EXPECT_NEAR(val_fd, val_ad, 1e-10);\n  for (int i = 0; i < grad_ad.size(); ++i) {\n    EXPECT_NEAR(grad_fd(i), grad_ad(i), prec);\n  }\n}\n\nvoid test_simple_vec_mult(int size, double prec) {\n  Eigen::VectorXd test_vec(size);\n  boost::random::mt19937 rng(2);\n\n  for (int i = 0; i < test_vec.size(); ++i)\n    test_vec(i) = stan::math::normal_rng(0.0, 0.1, rng);\n\n  chol_functor_simple_vec f(size, test_vec);\n\n  stan::math::welford_covar_estimator estimator(size);\n\n  for (int i = 0; i < 1000; ++i) {\n    Eigen::VectorXd q(size);\n    for (int j = 0; j < size; ++j)\n      q(j) = stan::math::normal_rng(0.0, 1.0, rng);\n    estimator.add_sample(q);\n  }\n\n  Eigen::MatrixXd covar(size, size);\n  estimator.sample_covariance(covar);\n\n  Eigen::Matrix<double, -1, 1> x(size * size);\n  int pos = 0;\n  for (int j = 0; j < size; ++j)\n    for (int i = 0; i < size; ++i)\n      x(pos++) = covar(i, j);\n\n  double eval_ad;\n  Eigen::VectorXd grad_ad;\n  stan::math::gradient(f, x, eval_ad, grad_ad);\n  double eval_fd;\n  Eigen::VectorXd grad_fd;\n  stan::math::finite_diff_gradient(f, x, eval_fd, grad_fd);\n\n  EXPECT_FLOAT_EQ(eval_fd, eval_ad);\n  for (int k = 0; k < grad_fd.size(); ++k)\n    EXPECT_NEAR(grad_fd(k), grad_ad(k), prec) << \" for k=\" << k;\n}\n\ndouble test_gradient(int size, double prec) {\n  chol_functor_2 functown(size);\n  Eigen::Matrix<double, -1, 1> grads_ad;\n  Eigen::Matrix<double, -1, 1> grads_fd;\n  double evals_ad;\n  double evals_fd;\n\n  int numels = size + size * (size - 1) / 2;\n  Eigen::Matrix<double, -1, 1> x(numels);\n  for (int i = 0; i < numels; ++i)\n    x(i) = i / 100.0;\n\n  stan::math::gradient(functown, x, evals_ad, grads_ad);\n  stan::math::finite_diff_gradient(functown, x, evals_fd, grads_fd);\n\n  for (int k = 0; k < numels; ++k)\n    EXPECT_NEAR(grads_fd(k), grads_ad(k), prec) << \" for k=\" << k;\n  EXPECT_FLOAT_EQ(evals_fd, evals_ad);\n  return grads_ad.sum();\n}\n\nTEST(AgradRevMatrix, mat_cholesky) {\n  using stan::math::cholesky_decompose;\n  using stan::math::matrix_v;\n  using stan::math::singular_values;\n  using stan::math::transpose;\n\n  // symmetric\n  matrix_v X(2, 2);\n  stan::math::var a = 3.0;\n  stan::math::var b = -1.0;\n  stan::math::var c = -1.0;\n  stan::math::var d = 1.0;\n  X << a, b, c, d;\n\n  matrix_v L = cholesky_decompose(X);\n\n  matrix_v LL_trans = multiply(L, transpose(L));\n  EXPECT_FLOAT_EQ(a.val(), LL_trans(0, 0).val());\n  EXPECT_FLOAT_EQ(b.val(), LL_trans(0, 1).val());\n  EXPECT_FLOAT_EQ(c.val(), LL_trans(1, 0).val());\n  EXPECT_FLOAT_EQ(d.val(), LL_trans(1, 1).val());\n\n  EXPECT_NO_THROW(singular_values(X));\n}\n\nTEST(AgradRevMatrix, exception_mat_cholesky) {\n  stan::math::matrix_v m;\n\n  // not positive definite\n  m.resize(2, 2);\n  m << 1.0, 2.0, 2.0, 3.0;\n  EXPECT_THROW(stan::math::cholesky_decompose(m), std::domain_error);\n\n  // zero size\n  m.resize(0, 0);\n  EXPECT_NO_THROW(stan::math::cholesky_decompose(m));\n\n  // not square\n  m.resize(2, 3);\n  EXPECT_THROW(stan::math::cholesky_decompose(m), std::invalid_argument);\n\n  // not symmetric\n  m.resize(2, 2);\n  m << 1.0, 2.0, 3.0, 4.0;\n  EXPECT_THROW(stan::math::cholesky_decompose(m), std::domain_error);\n}\n\nTEST(AgradRevMatrix, exception_varmat_cholesky) {\n  stan::math::matrix_d m;\n\n  // not positive definite\n  m.resize(2, 2);\n  m << 1.0, 2.0, 2.0, 3.0;\n  stan::math::var_value<stan::math::matrix_d> mv1(m);\n  EXPECT_THROW(stan::math::cholesky_decompose(mv1), std::domain_error);\n\n  // zero size\n  m.resize(0, 0);\n  stan::math::var_value<stan::math::matrix_d> mv2(m);\n  EXPECT_NO_THROW(stan::math::cholesky_decompose(mv2));\n\n  // not square\n  m.resize(2, 3);\n  stan::math::var_value<stan::math::matrix_d> mv3(m);\n  EXPECT_THROW(stan::math::cholesky_decompose(mv3), std::invalid_argument);\n\n  // not symmetric\n  m.resize(2, 2);\n  m << 1.0, 2.0, 3.0, 4.0;\n  stan::math::var_value<stan::math::matrix_d> mv4(m);\n  EXPECT_THROW(stan::math::cholesky_decompose(mv4), std::domain_error);\n}\n\nTEST(AgradRevMatrix, mat_cholesky_1st_deriv_small) {\n  test_gradients(9, 1e-10);\n  test_gradients_simple(10, 1e-10);\n  test_gradient(15, 1e-10);\n  test_gp_grad(20, 1e-10);\n}\n\nTEST(AgradRevMatrix, check_varis_on_stack_small) {\n  stan::math::matrix_v X(2, 2);\n  X << 3, -1, -1, 1;\n\n  test::check_varis_on_stack(stan::math::cholesky_decompose(X));\n}\n\nTEST(AgradRevMatrix, mat_cholesky_1st_deriv_large_gradients) {\n  test_gradient(36, 1e-08);\n  test_gp_grad(100, 1e-08);\n  test_gp_grad(1000, 1e-08);\n  test_chol_mult(37, 1e-08);\n  test_simple_vec_mult(45, 1e-08);\n}\n\nTEST(AgradRevMatrix, cholesky_replicated_input) {\n  using stan::math::var;\n\n  auto f = [](int size, const auto& y) {\n    auto m = stan::math::diag_matrix(stan::math::rep_vector(y, size));\n    auto L = stan::math::cholesky_decompose(m);\n    return stan::math::sum(L);\n  };\n\n  double ydbl = 1.5;\n  double dx = 1e-5;\n  var y = ydbl;\n  int size = 4;\n  var s = f(size, y);\n  s.grad();\n\n  double fd_ref = (f(size, ydbl + dx) - f(size, ydbl - dx)) / (2.0 * dx);\n  EXPECT_FLOAT_EQ(y.adj(), fd_ref);\n\n  stan::math::set_zero_all_adjoints();\n  size = 40;\n  s = f(size, y);\n  s.grad();\n\n  fd_ref = (f(size, ydbl + dx) - f(size, ydbl - dx)) / (2.0 * dx);\n  EXPECT_FLOAT_EQ(y.adj(), fd_ref);\n}\n", "meta": {"hexsha": "60e7f54aa3515f287cd2dc7ed9787581ceb7b594", "size": 14175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/rev/fun/cholesky_decompose_test.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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/fun/cholesky_decompose_test.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": "test/unit/math/rev/fun/cholesky_decompose_test.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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.8421052632, "max_line_length": 78, "alphanum_fraction": 0.6239858907, "num_tokens": 4822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.522130861243095}}
{"text": "/*\n// Copyright (c) 2016 Intel Corporation\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.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 <gtest/gtest.h>\n#include \"api/CPP/memory.hpp\"\n#include <api/CPP/input_layout.hpp>\n#include \"api/CPP/lstm.hpp\"\n#include <api/CPP/split.hpp>\n#include <api/CPP/crop.hpp>\n#include <api/CPP/concatenation.hpp>\n#include <api/CPP/topology.hpp>\n#include <api/CPP/tensor.hpp>\n#include <api/CPP/network.hpp>\n#include <api/CPP/engine.hpp>\n#include \"test_utils/test_utils.h\"\n#include <api/CPP/data.hpp>\n#include \"instrumentation.h\"\n#include <boost/filesystem.hpp>\n\n#include <sstream>\n#include <iomanip>\n\n\nusing namespace cldnn;\nusing namespace tests;\n\n#define FERROR 1E-4\n\nnamespace {\n    float sigmoid(float x) {\n        return 1.f / (1.f + (float)std::exp((float)(-x)));\n    }\n}\n\nstruct offset_order {\n    size_t it, ot, ft, zt;\n    offset_order(size_t scale, const cldnn_lstm_offset_order& t = cldnn_lstm_offset_order_iofz) {\n        static const std::map<cldnn_lstm_offset_order, std::vector<size_t>> offset_map{\n            { cldnn_lstm_offset_order_iofz,{ 0, 1, 2, 3 } },\n            { cldnn_lstm_offset_order_ifoz,{ 0, 2, 1, 3 } }\n        };\n        std::vector<size_t> v = offset_map.at(t);\n        it = v[0] * scale;\n        ot = v[1] * scale;\n        ft = v[2] * scale;\n        zt = v[3] * scale;\n    }\n};\ncldnn_lstm_offset_order default_offset_type = cldnn_lstm_offset_order_iofz;\n\n// [ARIEL] TODO: use move semantics when required\n\ntemplate<typename T>\nT clip(T val, T threshold) {\n    if (threshold > 0) {\n        if (val > threshold) return threshold;\n        if (val < -threshold) return -threshold;\n    }\n    return val;\n}\n\ntemplate <typename T>\nVVVVF<T> lstm_elt_reference(VVVVF<T>& tempGEMM, VVVVF<T>& cell, bool hasCell = true, float clip_threshold = 0, bool input_forget = false) {\n    size_t hidden_size = tempGEMM[0][0][0].size() / 4;\n    size_t batch_size = tempGEMM.size();\n    VVVVF<T> tempOut(batch_size, VVVF<T>(2, VVF<T>(1, VF<T>(hidden_size))));\n    offset_order off(hidden_size, default_offset_type);\n\n    for (size_t b = 0; b < batch_size; ++b) {\n        T *it = &tempGEMM[b][0][0][off.it];\n        T *ot = &tempGEMM[b][0][0][off.ot];\n        T *ft = &tempGEMM[b][0][0][off.ft];\n        T *zt = &tempGEMM[b][0][0][off.zt];\n        for (size_t h = 0; h < hidden_size; ++h) {\n            T val = sigmoid(clip(it[h], clip_threshold)) * std::tanh((float)clip(zt[h], clip_threshold));\n            if (input_forget) {\n                val *= (1 - ft[h]);\n            }\n            if (hasCell) {\n                val += cell[b][0][0][h] * sigmoid(clip(ft[h], clip_threshold));\n            }\n            tempOut[b][0][0][h] = std::tanh((float)val) * sigmoid(ot[h]);\n            tempOut[b][1][0][h] = val;\n        }\n    }\n    return tempOut;\n}\n\ntemplate <typename T>\nVVVVF<T> lstm_gemm_reference(VVVVF<T>& input, VVVVF<T>& weights, VVVVF<T>& recurrent, VVVVF<T>& bias, VVVVF<T>& hidden,\n    bool hasBias = true, bool hasHidden = true) {\n    size_t input_size = input[0][0][0].size();\n    size_t hidden_size = hidden[0][0][0].size();\n    size_t batch_size = input.size();\n\n    // Temporary output from GEMM operations [f, i, o, z]\n    VVVVF<T> tempGEMM(batch_size, VVVF<T>(1, VVF<T>(1, VF<T>(4 * hidden_size))));\n    for (size_t b = 0; b < batch_size; ++b) {\n        for (size_t y = 0; y < 4 * hidden_size; ++y) {\n            T res = 0;\n            for (size_t x = 0; x < input_size; ++x) {\n                res += (T)weights[0][0][y][x] * (T)input[b][0][0][x];\n            }\n            if (hasHidden) {\n                for (size_t x = 0; x < hidden_size; ++x) {\n                    res += (T)recurrent[0][0][y][x] * (T)hidden[b][0][0][x];\n                }\n            }\n            if (hasBias) {\n                res += (T)bias[0][0][0][y];\n            }\n            tempGEMM[b][0][0][y] = res;\n        }\n    }\n    return tempGEMM;\n}\n\n\ntemplate<typename T>\nvoid print(const std::string& s, VVVVF<T>& input) {\n    printf(\"%s -------------\\n\", s.c_str());\n    printf(\"Size = [%d, %d, %d, %d]\\n\", (int)input.size(), (int)input[0].size(), (int)input[0][0].size(), (int)input[0][0][0].size());\n    for (size_t b = 0; b < input.size(); ++b) {\n        for (size_t f = 0; f < input[0].size(); ++f) {\n            for (size_t y = 0; y < input[0][0].size(); ++y) {\n                for (size_t x = 0; x < input[0][0][0].size(); ++x) {\n                    printf(\"%f \", input[b][f][y][x]);\n                }\n                printf(\"\\n\");\n            }\n        }\n    }\n    printf(\"---------------------------------------\\n\");\n}\n\ntemplate<typename T>\nVVVVF<T> lstm_split_reference(VVVVF<T>& input, size_t idx, size_t bufferId) {\n    VVVVF<T> tempOut;\n    switch (idx) {\n    case 0:\n        tempOut = VVVVF<T>(input.size(), VVVF<T>(input[0].size(), VVF<T>(1, VF<T>(input[0][0][0].size()))));\n        for (size_t i = 0; i < input.size(); i++)\n            tempOut[i][0] = input[i][bufferId];\n        break;\n    case 1:\n        tempOut = VVVVF<T>(input.size(), VVVF<T>(1, VVF<T>(1, VF<T>(input[0][0][0].size()))));\n        //tempOut[0][0] = input[0][bufferId];\n        for (size_t i = 0; i < input.size(); i++)\n            tempOut[i][0] = input[i][bufferId];\n        break;\n    case 2:\n        tempOut = VVVVF<T>(1, VVVF<T>(1, VVF<T>(1, VF<T>(input[0][0][0].size()))));\n        tempOut[0][0][0] = input[0][0][bufferId];\n        break;\n    }\n    return tempOut;\n}\n\ntemplate <typename T>\nvoid lstm_reference(VVVVF<T>& input, VVVVF<T>& hidden, VVVVF<T>& cell, VVVVF<T>& weights, VVVVF<T>& recurrent, VVVVF<T>& bias,\n    VVVVF<T>& output, VVVVF<T>& last_hidden, VVVVF<T>& last_cell,\n    bool hasBias = true, bool hasInitialHidden = true, bool hasInitialCell = true,\n    float clip_threshold = 0, bool input_forget = false) {\n\n    size_t sequence_len = input[0].size();\n    size_t dir_len = weights[0].size();\n    size_t batch = input.size();\n    for (size_t dir = 0; dir < dir_len; ++dir) {\n        for (size_t seq = 0; seq < sequence_len; ++seq) {\n            VVVVF<T> splitInput = lstm_split_reference(input, 1, seq);\n            VVVVF<T> tempGEMM = lstm_gemm_reference(splitInput, weights, recurrent, bias, hidden, hasBias, hasInitialHidden);\n            VVVVF<T> tempOutput = lstm_elt_reference(tempGEMM, cell, hasInitialCell, clip_threshold, input_forget);\n            for (size_t i = 0; i < batch; i++)\n                output[i][seq] = tempOutput[i][0]; // hidden, output[dir,seq] = tempOutput[0,dir,batch,hidden]\n            hidden = lstm_split_reference(tempOutput, 0, 0);\n            cell = lstm_split_reference(tempOutput, 0, 1);\n            hasInitialHidden = true;\n            hasInitialCell = true;\n        }\n    }\n\n    last_hidden = hidden;\n    last_cell = cell;\n}\n\n\n\ntemplate<typename T>\nvoid generic_lstm_gemm_gpu_test(int sequence_len, int direction, int batch_size, int input_size, int hidden_size,\n    bool hasBias = true, bool hasHidden = true) {\n    int min_random = -2, max_random = 2;\n\n    VVVVF<T> ref_input = generate_random_4d<T>(batch_size, sequence_len, 1, input_size, min_random, max_random);\n    VVVVF<T> ref_weights = generate_random_4d<T>(1, direction, 4 * hidden_size, input_size, min_random, max_random);\n    VVVVF<T> ref_recurrent = generate_random_4d<T>(1, direction, 4 * hidden_size, hidden_size, min_random, max_random);\n    VVVVF<T> ref_bias = generate_random_4d<T>(1, 1, direction, 4 * hidden_size, min_random, max_random);\n    VVVVF<T> ref_hidden = generate_random_4d<T>(batch_size, direction, 1, hidden_size, min_random, max_random);\n    VF<T> ref_input_vec = flatten_4d<T>(cldnn::format::bfyx, ref_input);\n    VF<T> ref_weights_vec = flatten_4d<T>(cldnn::format::bfyx, ref_weights);\n    VF<T> ref_recurrent_vec = flatten_4d<T>(cldnn::format::bfyx, ref_recurrent);\n    VF<T> ref_bias_vec = flatten_4d<T>(cldnn::format::bfyx, ref_bias);\n    VF<T> ref_hidden_vec = flatten_4d<T>(cldnn::format::bfyx, ref_hidden);\n\n    VVVVF<T> ref_output = lstm_gemm_reference(ref_input, ref_weights, ref_recurrent, ref_bias, ref_hidden, hasBias, hasHidden);\n\n    engine engine;\n    memory input = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ batch_size,   sequence_len,  input_size,      1 } });\n    memory weights = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1,            direction,     input_size,      4 * hidden_size } });\n    memory recurrent = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1,            direction,     hidden_size,     4 * hidden_size } });\n    memory biases = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1,            1,             4 * hidden_size, direction } });\n    memory hidden = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ batch_size,   direction,     hidden_size,     1 } });\n\n    set_values(input, ref_input_vec);\n    set_values(weights, ref_weights_vec);\n    set_values(recurrent, ref_recurrent_vec);\n    set_values(biases, ref_bias_vec);\n    set_values(hidden, ref_hidden_vec);\n\n    topology topology;\n    topology.add(input_layout(\"input\", input.get_layout()));\n    topology.add(data(\"weights\", weights));\n    topology.add(data(\"recurrent\", recurrent));\n    if (hasBias) {\n        topology.add(data(\"biases\", biases));\n    }\n    if (hasHidden) {\n        topology.add(input_layout(\"hidden\", hidden.get_layout()));\n    }\n\n    topology.add(lstm_gemm(\"lstm_gemm\", \"input\", \"weights\", \"recurrent\", hasBias ? \"biases\" : \"\", hasHidden ? \"hidden\" : \"\"));\n\n    network network(engine, topology);\n    network.set_input_data(\"input\", input);\n    if (hasHidden) {\n        network.set_input_data(\"hidden\", hidden);\n    }\n\n    auto outputs = network.execute();\n    EXPECT_EQ(outputs.size(), size_t(1));\n\n    auto output = outputs.begin()->second.get_memory();\n    auto output_ptr = output.pointer<T>();\n    int i = 0;\n    for (int b = 0; b < batch_size; ++b) {\n        for (int x = 0; x < 4 * hidden_size; ++x)\n            EXPECT_EQ(ref_output[b][0][0][x], output_ptr[i++]);\n    }\n}\n\ntemplate<typename T>\nvoid generic_lstm_elt_gpu_test(int sequence_len, int direction, int batch_size, int input_size, int hidden_size, bool hasCell = true,\n    float clip_threshold = 0.f, bool input_forget = false) {\n    // tempGEMM  = [        1, direction,           batch, 4 * hidden_size ] input\n    // cell      = [        1, direction,           batch,     hidden_size ] optional\n    // output    = [        2, direction,           batch,     hidden_size ] output concat[hidden, cell]\n    int min_random = -2, max_random = 2;\n\n    VVVVF<T> ref_tempGEMM = generate_random_4d<T>(batch_size, direction, 1, 4 * hidden_size, min_random, max_random);\n    VVVVF<T> ref_cell = generate_random_4d<T>(batch_size, direction, 1, hidden_size, min_random, max_random);\n    VF<T> ref_tempGEMM_vec = flatten_4d<T>(cldnn::format::bfyx, ref_tempGEMM);\n    VF<T> ref_cell_vec = flatten_4d<T>(cldnn::format::bfyx, ref_cell);\n\n    VVVVF<T> ref_output = lstm_elt_reference(ref_tempGEMM, ref_cell, hasCell, clip_threshold, input_forget);\n\n    engine engine;\n    memory tempGEMM = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ batch_size,    direction, 4 * hidden_size, 1 } });\n    memory cell = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ batch_size,    direction,     hidden_size, 1 } });\n    set_values(tempGEMM, ref_tempGEMM_vec);\n    set_values(cell, ref_cell_vec);\n\n    topology topology;\n    topology.add(input_layout(\"tempGEMM\", tempGEMM.get_layout()));\n    if (hasCell) {\n        topology.add(input_layout(\"cell\", cell.get_layout()));\n    }\n    topology.add(lstm_elt(\"lstm_elt\", \"tempGEMM\", hasCell ? \"cell\" : \"\", clip_threshold, input_forget));\n\n    network network(engine, topology);\n    network.set_input_data(\"tempGEMM\", tempGEMM);\n    if (hasCell) {\n        network.set_input_data(\"cell\", cell);\n    }\n\n    auto outputs = network.execute();\n    EXPECT_EQ(outputs.size(), size_t(1));\n\n    auto output = outputs.begin()->second.get_memory();\n    auto output_ptr = output.pointer<T>();\n    for (int b = 0; b < batch_size; ++b) {\n        for (int j = 0; j < 2; ++j) {\n            for (int x = 0; x < hidden_size; ++x)\n            {\n                auto idx = b * 2 * hidden_size + j * hidden_size + x;\n                EXPECT_NEAR(ref_output[b][j][0][x], output_ptr[idx], FERROR);\n            }\n        }\n    }\n}\n\nstd::string getIdString(size_t i) {\n    std::stringstream ss;\n    ss << std::setw(5) << std::setfill('0') << i;\n    return ss.str();\n}\n\n\n// --------------- Manually constructed LSTM ----------------------------------------\n// This function manually generates an lstm node sequence by conbining lstm_gemm and lstm_elt nodes\n// it requires that the output of the lstm_elt node is croped to obtain the corresponding hidden and cell outputs\nvoid generate_lstm_topology(topology& t, memory& input, memory& hidden, memory& cell,\n    memory& weights, memory& recurrent, memory& biases, int sequence_len,\n    bool hasBias = true, bool hasInitialHidden = true, bool hasInitialCell = true) {\n    auto hidden_size = hidden.get_layout().size;\n    t.add(input_layout(\"input\", input.get_layout()));\n    std::vector<std::pair<primitive_id, tensor>> input_ids_offsets;\n    std::vector<primitive_id> output_ids_offsets;\n    for (int i = 0; i < sequence_len; ++i)\n        input_ids_offsets.push_back({ getIdString(i),{ 0, i, 0, 0 } });\n    t.add(split(\"inputSplit\", \"input\", input_ids_offsets));\n    t.add(data(\"weights\", weights));\n    t.add(data(\"recurrent\", recurrent));\n\n    std::string biasStr = \"\";\n    std::string hiddenStr = \"\";\n    std::string cellStr = \"\";\n    if (hasBias)\n    {\n        t.add(data(\"biases\", biases));\n        biasStr = \"biases\";\n    }\n    if (hasInitialHidden)\n    {\n        t.add(input_layout(\"hidden\", hidden.get_layout()));\n        hiddenStr = \"hidden\";\n    }\n    if (hasInitialCell)\n    {\n        t.add(input_layout(\"cell\", cell.get_layout()));\n        cellStr = \"cell\";\n    }\n    for (int i = 0; i < sequence_len; ++i) {\n        std::string lstm_gemm_id = \"lstm_gemm\" + getIdString(i);\n        std::string lstm_elt_id = \"lstm_elt\" + getIdString(i);\n        std::string crop_id = \"crop\" + getIdString(i);\n\n        t.add(lstm_gemm(lstm_gemm_id, \"inputSplit:\" + getIdString(i), \"weights\", \"recurrent\", biasStr, hiddenStr));\n        t.add(lstm_elt(lstm_elt_id, lstm_gemm_id, cellStr));\n\n        hiddenStr = crop_id + \":hidden\";\n        t.add(crop(hiddenStr, lstm_elt_id, hidden_size, tensor{ 0,0,0,0 }));\n        if (i < sequence_len - 1) {\n            cellStr = crop_id + \":cell\";\n            t.add(crop(cellStr, lstm_elt_id, hidden_size, tensor{ 0,1,0,0 }));\n        }\n        output_ids_offsets.push_back(hiddenStr);\n    }\n    t.add(concatenation(\"concatenation\", output_ids_offsets, concatenation::along_f));\n}\n\n\ntemplate<typename T>\nvoid generic_lstm_custom_gpu_test(int sequence_len, int direction, int batch_size, int input_size, int hidden_size,\n    bool hasBias = true, bool hasInitialHidden = true, bool hasInitialCell = true) {\n    std::cout << \"Input Size = \" << input_size << \" Hidden Size = \" << hidden_size << \" Sequence Len = \" << sequence_len << \" Batch Size = \" << batch_size << std::endl;\n    int min_random = -2, max_random = 2;\n    VVVVF<T> ref_input = generate_random_4d<T>(batch_size, sequence_len, 1, input_size, min_random, max_random);\n    VVVVF<T> ref_weights = generate_random_4d<T>(1, direction, 4 * hidden_size, input_size, min_random, max_random);\n    VVVVF<T> ref_recurrent = generate_random_4d<T>(1, direction, 4 * hidden_size, hidden_size, min_random, max_random);\n    VVVVF<T> ref_bias = generate_random_4d<T>(1, 1, direction, 4 * hidden_size, min_random, max_random);\n    VVVVF<T> ref_hidden = generate_random_4d<T>(batch_size, direction, 1, hidden_size, min_random, max_random);\n    VVVVF<T> ref_cell = generate_random_4d<T>(batch_size, direction, 1, hidden_size, min_random, max_random);\n    VVVVF<T> ref_output(batch_size, VVVF<T>(sequence_len, VVF<T>(direction, VF<T>(hidden_size))));\n    VVVVF<T> last_hidden(batch_size, VVVF<T>(direction, VVF<T>(1, VF<T>(hidden_size))));\n    VVVVF<T> last_cell(batch_size, VVVF<T>(direction, VVF<T>(1, VF<T>(hidden_size))));\n\n    VF<T> ref_input_vec = flatten_4d<T>(cldnn::format::bfyx, ref_input);\n    VF<T> ref_weights_vec = flatten_4d<T>(cldnn::format::bfyx, ref_weights);\n    VF<T> ref_recurrent_vec = flatten_4d<T>(cldnn::format::bfyx, ref_recurrent);\n    VF<T> ref_bias_vec = flatten_4d<T>(cldnn::format::bfyx, ref_bias);\n    VF<T> ref_hidden_vec = flatten_4d<T>(cldnn::format::bfyx, ref_hidden);\n    VF<T> ref_cell_vec = flatten_4d<T>(cldnn::format::bfyx, ref_cell);\n    lstm_reference(ref_input, ref_hidden, ref_cell, ref_weights, ref_recurrent, ref_bias, ref_output, last_hidden, last_cell,\n        hasBias, hasInitialHidden, hasInitialCell);\n\n    engine engine;\n    memory input = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ batch_size, sequence_len,  input_size,       1 } });\n    memory weights = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1,          direction,     input_size,       4 * hidden_size } });\n    memory recurrent = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1,          direction,     hidden_size,      4 * hidden_size } });\n    memory biases = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1,          1,             4 * hidden_size,  direction } });\n    memory hidden = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ batch_size, direction,     hidden_size,      1 } });\n    memory cell = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ batch_size, direction,     hidden_size,      1 } });\n    set_values(input, ref_input_vec);\n    set_values(weights, ref_weights_vec);\n    set_values(recurrent, ref_recurrent_vec);\n    set_values(biases, ref_bias_vec);\n    set_values(hidden, ref_hidden_vec);\n    set_values(cell, ref_cell_vec);\n\n    topology topology;\n    generate_lstm_topology(topology, input, hidden, cell, weights, recurrent, biases, sequence_len,\n        hasBias, hasInitialHidden, hasInitialCell);\n\n    network network(engine, topology);\n    network.set_input_data(\"input\", input);\n    if (hasInitialHidden) network.set_input_data(\"hidden\", hidden);\n    if (hasInitialCell) network.set_input_data(\"cell\", cell);\n    auto outputs = network.execute();\n\n    ASSERT_EQ(outputs.size(), size_t(1));\n    size_t output_size = outputs.begin()->second.get_memory().size() / sizeof(T);\n    ASSERT_EQ(output_size, size_t(hidden_size * sequence_len * batch_size * direction));\n\n    auto output = outputs.begin()->second.get_memory();\n    auto output_ptr = output.pointer<T>();\n    int i = 0;\n    for (int b = 0; b < batch_size; ++b) {\n        for (int s = 0; s < sequence_len; ++s) {\n            for (int x = 0; x < hidden_size; ++x) {\n                for (int d = 0; d < direction; ++d) {\n                    ASSERT_NEAR(ref_output[b][s][d][x], output_ptr[i++], FERROR);\n                }\n            }\n        }\n    }\n}\n\n// -------------------------------------------------------\n\ntemplate<typename T>\nvoid generic_lstm_gpu_test(int sequence_len, int direction, int batch_size, int input_size, int hidden_size,\n    bool hasBias = true, bool hasInitialHidden = true, bool hasInitialCell = true,\n    float clip_threshold = 0, bool input_forget = false) {\n    std::cout << \"Input Size = \" << input_size << \" Hidden Size = \" << hidden_size << \" Sequence Len = \" << sequence_len << \" Batch Size = \" << batch_size << std::endl;\n    int min_random = -2, max_random = 2;\n    VVVVF<T> ref_input = generate_random_4d<T>(batch_size, sequence_len, 1, input_size, min_random, max_random);\n    VVVVF<T> ref_weights = generate_random_4d<T>(1, direction, 4 * hidden_size, input_size, min_random, max_random);\n    VVVVF<T> ref_recurrent = generate_random_4d<T>(1, direction, 4 * hidden_size, hidden_size, min_random, max_random);\n    VVVVF<T> ref_bias = generate_random_4d<T>(1, 1, direction, 4 * hidden_size, min_random, max_random);\n    VVVVF<T> ref_hidden = generate_random_4d<T>(batch_size, direction, 1, hidden_size, min_random, max_random);\n    VVVVF<T> ref_cell = generate_random_4d<T>(batch_size, direction, 1, hidden_size, min_random, max_random);\n    VVVVF<T> ref_output(batch_size, VVVF<T>(sequence_len, VVF<T>(direction, VF<T>(hidden_size))));\n    VVVVF<T> last_hidden(batch_size, VVVF<T>(direction, VVF<T>(1, VF<T>(hidden_size))));\n    VVVVF<T> last_cell(batch_size, VVVF<T>(direction, VVF<T>(1, VF<T>(hidden_size))));\n\n    VF<T> ref_input_vec = flatten_4d<T>(cldnn::format::bfyx, ref_input);\n    VF<T> ref_weights_vec = flatten_4d<T>(cldnn::format::bfyx, ref_weights);\n    VF<T> ref_recurrent_vec = flatten_4d<T>(cldnn::format::bfyx, ref_recurrent);\n    VF<T> ref_bias_vec = flatten_4d<T>(cldnn::format::bfyx, ref_bias);\n    VF<T> ref_hidden_vec = flatten_4d<T>(cldnn::format::bfyx, ref_hidden);\n    VF<T> ref_cell_vec = flatten_4d<T>(cldnn::format::bfyx, ref_cell);\n    lstm_reference(ref_input, ref_hidden, ref_cell, ref_weights, ref_recurrent, ref_bias, ref_output, last_hidden, last_cell,\n        hasBias, hasInitialHidden, hasInitialCell, clip_threshold, input_forget);\n\n    engine engine;\n\n    memory input = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ batch_size,    sequence_len,   input_size,      1 } });\n    memory weights = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1,             direction,      input_size,      4 * hidden_size } });\n    memory recurrent = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1,             direction,      hidden_size,     4 * hidden_size } });\n    memory biases = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1,             1,              4 * hidden_size, direction } });\n    memory hidden = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ batch_size,    direction,      hidden_size,     1 } });\n    memory cell = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ batch_size,    direction,      hidden_size,     1 } });\n\n    set_values(input, ref_input_vec);\n    set_values(weights, ref_weights_vec);\n    set_values(recurrent, ref_recurrent_vec);\n    if (hasBias) set_values(biases, ref_bias_vec);\n    if (hasInitialHidden) set_values(hidden, ref_hidden_vec);\n    if (hasInitialCell) set_values(cell, ref_cell_vec);\n\n    topology topology;\n    std::vector<std::pair<primitive_id, tensor>> input_ids_offsets;\n    std::vector<primitive_id> lstm_inputs;\n    std::vector<primitive_id> output_ids_offsets;\n\n    topology.add(input_layout(\"input\", input.get_layout()));\n    for (int i = 0; i < sequence_len; ++i) {\n        input_ids_offsets.push_back({ getIdString(i),{ 0, i, 0, 0 } });\n        lstm_inputs.push_back(\"inputSplit:\" + getIdString(i));\n    }\n    topology.add(split(\"inputSplit\", \"input\", input_ids_offsets));\n    topology.add(data(\"weights\", weights));\n    topology.add(data(\"recurrent\", recurrent));\n    if (hasBias) topology.add(data(\"biases\", biases));\n    if (hasInitialHidden) topology.add(input_layout(\"hidden\", hidden.get_layout()));\n    if (hasInitialCell) topology.add(input_layout(\"cell\", cell.get_layout()));\n    topology.add(lstm(\"lstm\", lstm_inputs, \"weights\", \"recurrent\",\n        hasBias ? \"biases\" : \"\", hasInitialHidden ? \"hidden\" : \"\", hasInitialCell ? \"cell\" : \"\", \"\", clip_threshold, input_forget, {}, {}, default_offset_type));\n\n    network network(engine, topology);\n    network.set_input_data(\"input\", input);\n    if (hasInitialHidden) network.set_input_data(\"hidden\", hidden);\n    if (hasInitialCell) network.set_input_data(\"cell\", cell);\n    auto outputs = network.execute();\n\n    ASSERT_EQ(outputs.size(), size_t(1));\n    size_t output_size = outputs.begin()->second.get_memory().size() / sizeof(T);\n    ASSERT_EQ(output_size, size_t(hidden_size * sequence_len * batch_size * direction));\n\n    auto output = outputs.begin()->second.get_memory();\n    auto output_ptr = output.pointer<T>();\n    int i = 0;\n    for (int b = 0; b < batch_size; ++b) {\n        for (int s = 0; s < sequence_len; ++s) {\n            for (int x = 0; x < hidden_size; ++x) {\n                for (int d = 0; d < direction; ++d) {\n                    ASSERT_NEAR(ref_output[b][s][d][x], output_ptr[i++], FERROR);\n                }\n            }\n        }\n    }\n}\n\nTEST(lstm_gemm_gpu, generic_lstm_gemm_test_f32) {\n    generic_lstm_gemm_gpu_test<float>(1, 1, 3, 6, 2, true, true);\n}\n\nTEST(lstm_gemm_gpu, generic_lstm_gemm_no_bias_f32) {\n    generic_lstm_gemm_gpu_test<float>(1, 1, 3, 6, 2, false, true);\n}\n\nTEST(lstm_gemm_gpu, generic_lstm_gemm_no_hidden_f32) {\n    generic_lstm_gemm_gpu_test<float>(1, 1, 3, 6, 2, true, false);\n}\n\nTEST(lstm_gemm_gpu, generic_lstm_gemm_no_hidden_bias_f32) {\n    generic_lstm_gemm_gpu_test<float>(1, 1, 3, 6, 2, false, false);\n}\n\nTEST(lstm_elt_gpu, generic_lstm_elt_test_clip_f32) {\n    generic_lstm_elt_gpu_test<float>(1, 1, 4, 6, 3, true, 0.3f);\n}\n\nTEST(lstm_elt_gpu, generic_lstm_elt_test_input_forget_f32) {\n    generic_lstm_elt_gpu_test<float>(1, 1, 4, 6, 3, true, 0.f, 1);\n}\n\nTEST(lstm_elt_gpu, generic_lstm_elt_test_clip_input_forget_f32) {\n    generic_lstm_elt_gpu_test<float>(1, 1, 4, 6, 3, true, 0.5f, 1);\n}\n\nTEST(lstm_elt_gpu, generic_lstm_elt_test_f32) {\n    generic_lstm_elt_gpu_test<float>(1, 1, 4, 6, 3, true);\n}\n\nTEST(lstm_elt_gpu, generic_lstm_elt_no_cell_f32) {\n    generic_lstm_elt_gpu_test<float>(1, 1, 4, 6, 3, false);\n}\n\nTEST(lstm_custom_gpu, generic_lstm_custom_f32) {\n    generic_lstm_custom_gpu_test<float>(3, 1, 3, 3, 2, true, true, true);\n}\n\nTEST(lstm_custom_gpu, generic_lstm_custom_no_biasf32) {\n    generic_lstm_custom_gpu_test<float>(3, 1, 3, 3, 2, false, true, true);\n}\n\nTEST(lstm_custom_gpu, generic_lstm_custom_no_hidden_f32) {\n    generic_lstm_custom_gpu_test<float>(3, 1, 3, 3, 2, true, false, true);\n}\n\nTEST(lstm_custom_gpu, generic_lstm_custom_no_bias_hidden_f32) {\n    generic_lstm_custom_gpu_test<float>(3, 1, 3, 3, 2, false, false, true);\n}\n\nTEST(lstm_custom_gpu, generic_lstm_custom_no_cell_f32) {\n    generic_lstm_custom_gpu_test<float>(3, 1, 3, 3, 2, true, true, false);\n}\n\nTEST(lstm_custom_gpu, generic_lstm_custom_no_bias_cell_f32) {\n    generic_lstm_custom_gpu_test<float>(3, 1, 3, 3, 2, false, true, false);\n}\n\nTEST(lstm_custom_gpu, generic_lstm_custom_no_hidden_cell_f32) {\n    generic_lstm_custom_gpu_test<float>(3, 1, 3, 3, 2, true, false, false);\n}\n\nTEST(lstm_custom_gpu, generic_lstm_custom_no_bias_hidden_cell_f32) {\n    generic_lstm_custom_gpu_test<float>(3, 1, 3, 3, 2, false, false, false);\n}\n\nTEST(lstm_gpu, generic_lstm_f32) {\n    generic_lstm_gpu_test<float>(3, 1, 3, 3, 2, true, true, true);\n}\n\nTEST(lstm_gpu, generic_lstm_no_bias_f32) {\n    generic_lstm_gpu_test<float>(3, 1, 3, 3, 2, false, true, true);\n}\n\nTEST(lstm_gpu, generic_lstm_no_hidden_f32) {\n    generic_lstm_gpu_test<float>(3, 1, 5, 4, 3, true, false, true);\n}\n\nTEST(lstm_gpu, generic_lstm_no_bias_hidden_f32) {\n    generic_lstm_gpu_test<float>(3, 1, 5, 4, 3, false, false, true);\n}\n\nTEST(lstm_gpu, generic_lstm_no_cell_f32) {\n    generic_lstm_gpu_test<float>(3, 1, 5, 4, 3, true, true, false);\n}\n\nTEST(lstm_gpu, generic_lstm_no_bias_cell_f32) {\n    generic_lstm_gpu_test<float>(3, 1, 5, 4, 3, false, true, false);\n}\n\nTEST(lstm_gpu, generic_lstm_no_hidden_cell_f32) {\n    generic_lstm_gpu_test<float>(3, 1, 5, 4, 3, true, false, false);\n}\n\nTEST(lstm_gpu, generic_lstm_no_bias_hidden_cell_f32) {\n    generic_lstm_gpu_test<float>(3, 1, 5, 4, 3, false, false, false);\n}\n\nTEST(lstm_gpu, generic_lstm_clip_f32) {\n    generic_lstm_gpu_test<float>(3, 1, 3, 3, 2, true, true, true, 0.3f, 0);\n}\n\nTEST(lstm_gpu, generic_lstm_input_forget_f32) {\n    generic_lstm_gpu_test<float>(3, 1, 3, 3, 2, true, true, true, 0.f, 1);\n}\n\nTEST(lstm_gpu, generic_lstm_clip_input_forget_f32) {\n    generic_lstm_gpu_test<float>(3, 1, 3, 3, 2, true, true, true, 0.3f, 1);\n}\n\nTEST(lstm_gpu, generic_lstm_offset_order_ifoz_f32) {\n    default_offset_type = cldnn_lstm_offset_order_ifoz;\n    generic_lstm_gpu_test<float>(3, 1, 3, 3, 2, true, true, true);\n    default_offset_type = cldnn_lstm_offset_order_iofz;\n}\n\n// TODO: Add tests for the following:\n// optional concatenate output\n// optional last hidden\n// optional last cell\n// optional activation list\n\n", "meta": {"hexsha": "8ec45f1aed21afa311a5016a3b6af584bfdbf032", "size": 28864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "inference-engine/thirdparty/clDNN/tests/test_cases/lstm_gpu_test.cpp", "max_stars_repo_name": "mypopydev/dldt", "max_stars_repo_head_hexsha": "8cd639116b261adbbc8db860c09807c3be2cc2ca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-08T09:03:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T10:34:17.000Z", "max_issues_repo_path": "inference-engine/thirdparty/clDNN/tests/test_cases/lstm_gpu_test.cpp", "max_issues_repo_name": "openvino-pushbot/dldt", "max_issues_repo_head_hexsha": "e607ee70212797cf9ca51dac5b7ac79f66a1c73f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-11-13T18:59:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T02:14:53.000Z", "max_forks_repo_path": "inference-engine/thirdparty/clDNN/tests/test_cases/lstm_gpu_test.cpp", "max_forks_repo_name": "openvino-pushbot/dldt", "max_forks_repo_head_hexsha": "e607ee70212797cf9ca51dac5b7ac79f66a1c73f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-14T07:56:02.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-14T07:56:02.000Z", "avg_line_length": 44.3379416283, "max_line_length": 168, "alphanum_fraction": 0.644193459, "num_tokens": 8372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5221308501708736}}
{"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 <fstream>\r\n#include <iostream>\r\n#include <vector>\r\n#include <iomanip>\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/graphviz.hpp>\r\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\r\n\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  typedef adjacency_list<vecS, vecS, directedS, no_property,\r\n    property< edge_weight_t, int, property< edge_weight2_t, int > > > Graph;\r\n  const int V = 6;\r\n  typedef std::pair < int, int >Edge;\r\n  Edge edge_array[] =\r\n    { Edge(0, 1), Edge(0, 2), Edge(0, 3), Edge(0, 4), Edge(0, 5),\r\n    Edge(1, 2), Edge(1, 5), Edge(1, 3), Edge(2, 4), Edge(2, 5),\r\n    Edge(3, 2), Edge(4, 3), Edge(4, 1), Edge(5, 4)\r\n  };\r\n  const std::size_t E = sizeof(edge_array) / sizeof(Edge);\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  // VC++ can't handle the iterator constructor\r\n  Graph g(V);\r\n  for (std::size_t j = 0; j < E; ++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 + E, V);\r\n#endif\r\n\r\n  property_map < Graph, edge_weight_t >::type w = get(edge_weight, g);\r\n  int weights[] = { 0, 0, 0, 0, 0, 3, -4, 8, 1, 7, 4, -5, 2, 6 };\r\n  int *wp = weights;\r\n\r\n  graph_traits < Graph >::edge_iterator e, e_end;\r\n  for (boost::tie(e, e_end) = edges(g); e != e_end; ++e)\r\n    w[*e] = *wp++;\r\n\r\n  std::vector < int >d(V, (std::numeric_limits < int >::max)());\r\n  int D[V][V];\r\n  johnson_all_pairs_shortest_paths(g, D, distance_map(&d[0]));\r\n\r\n  std::cout << \"       \";\r\n  for (int k = 0; k < V; ++k)\r\n    std::cout << std::setw(5) << k;\r\n  std::cout << std::endl;\r\n  for (int i = 0; i < V; ++i) {\r\n    std::cout << std::setw(3) << i << \" -> \";\r\n    for (int j = 0; j < V; ++j) {\r\n      if (D[i][j] == (std::numeric_limits<int>::max)())\r\n        std::cout << std::setw(5) << \"inf\";\r\n      else\r\n        std::cout << std::setw(5) << D[i][j];\r\n    }\r\n    std::cout << std::endl;\r\n  }\r\n\r\n  std::ofstream fout(\"figs/johnson-eg.dot\");\r\n  fout << \"digraph A {\\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  graph_traits < Graph >::edge_iterator ei, ei_end;\r\n  for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\r\n    fout << source(*ei, g) << \" -> \" << target(*ei, g)\r\n      << \"[label=\" << get(edge_weight, g)[*ei] << \"]\\n\";\r\n\r\n  fout << \"}\\n\";\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "785731b59f4fcbbd1316f953f376950ca2a02712", "size": 2825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/johnson-eg.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/johnson-eg.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/johnson-eg.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.0361445783, "max_line_length": 77, "alphanum_fraction": 0.534159292, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5220978637448068}}
{"text": "#pragma once\n\n#include <limits>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/type_traits/is_same.hpp>\n\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n\n#include \"fmmtl/numeric/Vec.hpp\"\n#include \"fmmtl/numeric/Complex.hpp\"\n\nnamespace fmmtl {\n\nstatic boost::random::mt19937 default_generator;\n\nusing boost::enable_if;\nusing boost::is_integral;\nusing boost::is_floating_point;\n\ntemplate <typename T, class Enable = void>\nstruct random;\n\ntemplate <typename T>\nstruct random<T, typename enable_if<is_integral<T> >::type> {\n  typedef T result_type;\n  result_type operator()(T a, T b) const { return get(a,b); }\n  result_type operator()()         const { return get();    }\n\n  static result_type get(T a, T b) {\n    boost::random::uniform_int_distribution<T> dist(a, b);\n    return dist(default_generator);\n  }\n  static result_type get() {\n    return get(T(0), std::numeric_limits<T>::max());\n  }\n};\n\ntemplate <typename T>\nstruct random<T, typename enable_if<is_floating_point<T> >::type> {\n  typedef T result_type;\n  result_type operator()(T a, T b) const { return get(a,b); }\n  result_type operator()()         const { return get();    }\n\n  static result_type get(T a, T b) {\n    boost::random::uniform_real_distribution<T> dist(a, b);\n    return dist(default_generator);\n  }\n  static result_type get() {\n    return get(T(0), T(1));\n  }\n};\n\ntemplate <typename T>\nstruct random<complex<T> > {\n  typedef complex<T> result_type;\n  result_type operator()(T a, T b) const { return get(a,b); }\n  result_type operator()()         const { return get();    }\n\n  static result_type get(T a, T b) {\n    return complex<T>(random<T>::get(a,b), random<T>::get(a,b));\n  }\n  static result_type get() {\n    return get(T(0), T(1));\n  }\n};\n\ntemplate <typename T>\nstruct random<std::complex<T> > {\n  typedef std::complex<T> result_type;\n  result_type operator()(T a, T b) const { return get(a,b); }\n  result_type operator()()         const { return get();    }\n\n  static result_type get(T a, T b) {\n    return std::complex<T>(random<T>::get(a,b), random<T>::get(a,b));\n  }\n  static result_type get() {\n    return get(T(0), T(1));\n  }\n};\n\ntemplate <std::size_t N, typename T>\nstruct random<Vec<N,T> > {\n  typedef Vec<N,T> result_type;\n  result_type operator()(T a, T b) const { return get(a,b); }\n  result_type operator()()         const { return get();    }\n\n  static result_type get(T a, T b) {\n    Vec<N,T> v;\n    for (std::size_t i = 0; i != N; ++i)\n      v[i] = fmmtl::random<T>::get(a, b);\n    return v;\n  }\n  static result_type get() {\n    return get(T(0), T(1));\n  }\n};\n\n\nclass random_n {\n  template <typename T>\n  struct generator {\n    T operator()(const std::size_t&) const { return random<T>::get(); }\n  };\n  std::size_t N;\n\n public:\n  random_n(const std::size_t& _N) : N(_N) {}\n\n  template <typename Container>\n  operator Container() const {\n    typedef typename Container::value_type value_type;\n    return Container(\n        boost::make_transform_iterator(\n            boost::make_counting_iterator(std::size_t(0)),\n            generator<value_type>()),\n        boost::make_transform_iterator(\n            boost::make_counting_iterator(std::size_t(N)),\n            generator<value_type>()));\n  }\n};\n\n\n} // end namespace fmmtl\n", "meta": {"hexsha": "8b33a1c039a6b437f01e04e837098aeea8e0c9d9", "size": 3484, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/fmmtl/fmmtl/numeric/random.hpp", "max_stars_repo_name": "sergeneren/BubbleH", "max_stars_repo_head_hexsha": "e018e5a008e101221a4f8a3bbb25e7ec03fc9662", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2019-10-06T17:25:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T23:01:13.000Z", "max_issues_repo_path": "source/fmmtl/fmmtl/numeric/random.hpp", "max_issues_repo_name": "sergeneren/BubbleH", "max_issues_repo_head_hexsha": "e018e5a008e101221a4f8a3bbb25e7ec03fc9662", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-08T18:44:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T07:48:31.000Z", "max_forks_repo_path": "source/fmmtl/fmmtl/numeric/random.hpp", "max_forks_repo_name": "sergeneren/BubbleH", "max_forks_repo_head_hexsha": "e018e5a008e101221a4f8a3bbb25e7ec03fc9662", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-10-07T16:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T01:09:47.000Z", "avg_line_length": 26.8, "max_line_length": 71, "alphanum_fraction": 0.6567164179, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5220978591162552}}
{"text": "#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include \"point.h\"\n#include \"node.h\"\n#include \"decision_tree.h\"\n#include <fstream>\n\n\n\nvoid test_decision_tree()\n{\n  std::cout << \"test_decision_tree\\n\";\n\n  using Label = int;\n  std::vector<Point<Label>> datapoints {{-2, 1.5, 0},\n                                       {1, 1, 0},\n                                       {0, 1.5, 0},\n                                       {0.5, -0.5, 1},\n                                       {1, -1, 1},\n                                       {-1, -2, 1},\n                                       {1, 2, 0}};\n\n  // stream out\n  std::ofstream out(\"data/data.txt\");\n  for(std::size_t i = 0; i < datapoints.size(); ++i)\n  {\n    out << datapoints[i].x << \" \" << datapoints[i].y << \" \"\n        << datapoints[i].label << \"\\n\";\n  }\n  out.close();\n\n  Node<Label> root(datapoints);\n  Decision_tree<Label> tree(&root);\n  tree.fit();\n}\n\n\nvoid test_decision_tree2()\n{\n  std::cout << \"test_decision_tree\\n\";\n\n  using Label = int;\n  std::vector<Point<Label>> datapoints {{0, 1, 0},\n                                        {1, 0, 1}};\n\n  // stream out\n  std::ofstream out(\"data/data.txt\");\n  for(std::size_t i = 0; i < datapoints.size(); ++i)\n  {\n    out << datapoints[i].x << \" \" << datapoints[i].y << \" \"\n        << datapoints[i].label << \"\\n\";\n  }\n  out.close();\n\n  Node<Label> root(datapoints);\n  Decision_tree<Label> tree(&root);\n  tree.fit();\n  // todo: assert line b1 = 1, b0 = 0\n}\n\n\nvoid test_decision_tree_outlier()\n{\n  std::cout << \"test_decision_tree_outlier\\n\";\n\n  using Label = int;\n  std::vector<Point<Label>> datapoints {{-2, 1.5, 0}, //0\n                                       {1, 1, 0},  //1\n                                       {0, 1.5, 0}, //2\n                                       {0.5, -0.5, 1}, //3\n                                       {1, -1, 1}, //4\n                                       {-1, -2, 1}, //5\n                                       {1, 2, 0}, //6\n                                       {-1, 2, 1}}; // outlier\n\n\n\n  // stream out\n  std::ofstream out(\"data/data.txt\");\n  for(std::size_t i = 0; i < datapoints.size(); ++i)\n  {\n    out << datapoints[i].x << \" \" << datapoints[i].y << \" \"\n        << datapoints[i].label << \"\\n\";\n  }\n  out.close();\n\n  Node<Label> root(datapoints);\n  Decision_tree<Label> tree(&root);\n  tree.fit();\n}\n\n\n\nint main()\n{\n\n  test_decision_tree();\n  test_decision_tree2();\n  test_decision_tree_outlier();\n  return 0;\n}\n\n", "meta": {"hexsha": "e63d78ead2a0fea3c4f432294990db341c0e82d0", "size": 2460, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_fitting.cpp", "max_stars_repo_name": "kkatrio/DecisionTree", "max_stars_repo_head_hexsha": "2fa2e0090eec06ce313a080cf3ac70a081483cf6", "max_stars_repo_licenses": ["MIT"], "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_fitting.cpp", "max_issues_repo_name": "kkatrio/DecisionTree", "max_issues_repo_head_hexsha": "2fa2e0090eec06ce313a080cf3ac70a081483cf6", "max_issues_repo_licenses": ["MIT"], "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_fitting.cpp", "max_forks_repo_name": "kkatrio/DecisionTree", "max_forks_repo_head_hexsha": "2fa2e0090eec06ce313a080cf3ac70a081483cf6", "max_forks_repo_licenses": ["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.6538461538, "max_line_length": 62, "alphanum_fraction": 0.4382113821, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5220978557523345}}
{"text": "#ifndef mesh_reader\n#define mesh_reader\n\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <string>\n#include <math.h>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\nusing namespace boost::numeric::ublas;\n\nnamespace mesh {\n\n    matrix<double> read_vertices() {\n        /* index # is vertix id, contains x and y\n        coordinate respectively of vertix, and\n        a flag, 1 if boundary point 0 if not */\n        std::ifstream infile(\"../triangle/circle.1.node\");\n        std::string line;\n        double a, b, c, d, line_nb = 0;\n        std::getline(infile, line);\n        std::istringstream iss(line);\n        iss >> a >> b >> c;\n        int nb_nodes = a;\n        matrix<double> vertices(nb_nodes, 3);\n\n        while (std::getline(infile, line)) {\n            std::istringstream iss(line);\n            if (iss >> a >> b >> c >> d) {\n                vertices(line_nb, 0) = b;\n                vertices(line_nb, 1) = c;\n                vertices(line_nb, 2) = d;\n            }\n            else {\n                // std::cout << \"ERROR: in .1.node file\" << std::endl;\n                break;\n            }\n            line_nb += 1;\n        }\n\n        return vertices;\n    }\n\n    matrix<double> read_triangles(matrix<double> &vertices) {\n        /* index # is triangle id, contains\n        the 3 vertix id's of the corner nodes  and\n        the area of the triangle, calculated using\n        the vertices matrix */\n        std::ifstream infile(\"../triangle/circle.1.ele\");\n        std::string line;\n        int a, b, c, d, line_nb = 0;\n        std::getline(infile, line);\n        std::istringstream iss(line);\n        iss >> a >> b >> c;\n        int nb_triangles = a;\n        matrix<double> triangles(nb_triangles, 4);\n\n        while (std::getline(infile, line)) {\n            std::istringstream iss(line);\n            if (iss >> a >> b >> c >> d) {\n                triangles(line_nb, 0) = b-1;\n                triangles(line_nb, 1) = c-1;\n                triangles(line_nb, 2) = d-1;\n                triangles(line_nb, 3) = 0.5*fabs(vertices(b-1, 0)*(vertices(c-1, 1) - vertices(d-1, 1)) +\n                    vertices(c-1, 0)*(vertices(d-1, 1) - vertices(b-1, 1)) +\n                    vertices(d-1, 0)*(vertices(b-1, 1) - vertices(c-1, 1)));\n            }\n            else {\n                // std::cout << \"ERROR: in .1.ele file\" << std::endl;\n                break;\n            }\n            line_nb += 1;\n        }\n\n        return triangles;\n    }\n\n    matrix<int> read_boundaries(matrix<double> &vertices) {\n        /* index # is triangle id, contains\n        the 3 vertix id's of the corner nodes  and\n        the area of the triangle, calculated using\n        the vertices matrix */\n        std::ifstream infile(\"../triangle/circle.1.poly\");\n        std::string line;\n        int a, b, c, d, count = 0;\n        std::getline(infile, line);\n        std::getline(infile, line);\n        std::istringstream iss(line);\n        iss >> a >> b;\n        int nb_boundaries = a;\n        matrix<int> boundaries(nb_boundaries, 2);\n\n        while (std::getline(infile, line)) {\n            std::istringstream iss(line);\n            if (iss >> a >> b >> c >> d) {\n                if (vertices(b-1, 0) != 0 || vertices(c-1, 0) != 0) {\n                  boundaries(count, 0) = b-1;\n                  boundaries(count, 1) = c-1;\n                  count += 1;\n                }\n            }\n            else {\n                // std::cout << \"ERROR: in .1.poly file\" << std::endl;\n                break;\n            }\n        }\n\n        matrix<int> boundaries_red(count, 2);\n        boundaries_red = project(boundaries, range(0, count), range(0, 2));\n        return boundaries_red;\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "bbd1eed3836ee8a48fb460a6f6a63ab07a6c69ef", "size": 3783, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/deprecated/mesh_reader.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/mesh_reader.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/mesh_reader.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": 31.7899159664, "max_line_length": 105, "alphanum_fraction": 0.502246894, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5220978557523345}}
{"text": "// Copyright (c) 2016 Graphcore Ltd. All rights reserved.\n// Simple test case for test log of softmax\n//\n#define BOOST_TEST_MODULE NonLinearityTest\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <limits>\n#include <poplar/Engine.hpp>\n#include <poplibs_support/TestDevice.hpp>\n#include <poplibs_test/Util.hpp>\n#include <poplin/codelets.hpp>\n#include <popnn/LogSoftmax.hpp>\n#include <popnn/codelets.hpp>\n#include <popops/codelets.hpp>\n#include <poputil/TileMapping.hpp>\n\nusing namespace poplar;\nusing namespace poplar::program;\nusing namespace poputil;\nusing namespace popnn;\nusing namespace poplibs_test;\nusing namespace poplibs_test::util;\nusing namespace poplibs_support;\n\nnamespace utf = boost::unit_test;\nnamespace fpc = boost::test_tools::fpc;\n\n#define TOL 0.1\n#define FLOAT_ATOL 1e-20\n#define HALF_ATOL 1e-7\n\nvoid validateLogSoftmax(unsigned batchSize, unsigned numChannels) {\n  auto device = createTestDevice(TEST_TARGET);\n  auto &target = device.getTarget();\n  Graph graph(target);\n  popnn::addCodelets(graph);\n  popops::addCodelets(graph);\n  poplin::addCodelets(graph);\n\n  auto actF = graph.addVariable(FLOAT, {batchSize, numChannels}, \"actF\");\n  auto actH = graph.addVariable(HALF, {batchSize, numChannels}, \"actH\");\n\n  // arbitrary mappings\n  mapTensorLinearly(graph, actF);\n  mapTensorLinearly(graph, actH);\n\n  graph.createHostWrite(\"inF\", actF);\n  graph.createHostWrite(\"inH\", actH);\n  graph.createHostRead(\"outF\", actF);\n  graph.createHostRead(\"outH\", actH);\n\n  std::vector<std::pair<std::string, char *>> tmap;\n  Sequence uploadProg, downloadProg;\n\n  auto rawHActF = allocateHostMemoryForTensor(actF, \"actF\", graph, uploadProg,\n                                              downloadProg, tmap);\n  auto rawHActH = allocateHostMemoryForTensor(actH, \"actH\", graph, uploadProg,\n                                              downloadProg, tmap);\n\n  boost::multi_array<double, 2> hActIn(boost::extents[batchSize][numChannels]),\n      hOutRef(boost::extents[batchSize][numChannels]),\n      hActOutF(boost::extents[batchSize][numChannels]),\n      hActOutH(boost::extents[batchSize][numChannels]);\n\n  // Reference computation\n  for (unsigned b = 0; b < batchSize; ++b) {\n    double maxBatch = std::numeric_limits<double>::lowest();\n    for (unsigned c = 0; c < numChannels; ++c) {\n      double sample = (1.0 - 2 * (c & 1)) * (1 + b) * 0.01 * c;\n      hActIn[b][c] = sample;\n      maxBatch = std::max(maxBatch, sample);\n    }\n    // compute sum of exponent\n    double sum = 0.0;\n    for (unsigned c = 0; c < numChannels; ++c) {\n      sum += std::exp(hActIn[b][c] - maxBatch);\n    }\n\n    for (unsigned c = 0; c < numChannels; ++c) {\n      hOutRef[b][c] = hActIn[b][c] - maxBatch - std::log(sum);\n    }\n  }\n\n  // To test 1D\n  if (batchSize == 1) {\n    actF = actF.squeeze({0});\n    actH = actH.squeeze({0});\n  }\n\n  // build and run the target code: non-inplace followed by in-place\n  auto prog = Sequence();\n  auto outF = popnn::logSoftmax(graph, actF, prog);\n  auto outH = popnn::logSoftmax(graph, actH, prog);\n  popnn::logSoftmaxInPlace(graph, actF, prog);\n  popnn::logSoftmaxInPlace(graph, actH, prog);\n\n  auto rawHOutF = allocateHostMemoryForTensor(outF, \"outF\", graph, uploadProg,\n                                              downloadProg, tmap);\n  auto rawHOutH = allocateHostMemoryForTensor(outH, \"outH\", graph, uploadProg,\n                                              downloadProg, tmap);\n\n  copy(target, hActIn, FLOAT, rawHActF.get());\n  copy(target, hActIn, HALF, rawHActH.get());\n\n  Engine fwdEng(graph, Sequence{uploadProg, prog, downloadProg});\n  attachStreams(fwdEng, tmap);\n  device.bind([&](const Device &d) { fwdEng.loadAndRun(d); });\n\n  // inplace variant\n  copy(target, FLOAT, rawHActF.get(), hActOutF);\n  copy(target, HALF, rawHActH.get(), hActOutH);\n  BOOST_TEST(checkIsClose(\"actOutF\", hActOutF, hOutRef, TOL, FLOAT_ATOL));\n  BOOST_TEST(checkIsClose(\"actOutH\", hActOutH, hOutRef, TOL, HALF_ATOL));\n\n  // non-inplace variant\n  copy(target, FLOAT, rawHOutF.get(), hActOutF);\n  copy(target, HALF, rawHOutH.get(), hActOutH);\n  BOOST_TEST(checkIsClose(\"actOutF\", hActOutF, hOutRef, TOL, FLOAT_ATOL));\n  BOOST_TEST(checkIsClose(\"actOutH\", hActOutH, hOutRef, TOL, HALF_ATOL));\n}\n\nBOOST_AUTO_TEST_CASE(logSoftmax_1D) { validateLogSoftmax(1, 100); }\n\nBOOST_AUTO_TEST_CASE(logSoftmax_2D) { validateLogSoftmax(4, 100); }\n", "meta": {"hexsha": "c01eb330ea6ce5837847df66a3a910215e84a2fc", "size": 4353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/popnn/LogSoftmaxTest.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/popnn/LogSoftmaxTest.cpp", "max_issues_repo_name": "graphcore/poplibs", "max_issues_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_issues_repo_licenses": ["MIT"], "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/popnn/LogSoftmaxTest.cpp", "max_forks_repo_name": "graphcore/poplibs", "max_forks_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "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": 34.824, "max_line_length": 79, "alphanum_fraction": 0.6779232713, "num_tokens": 1265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5220978544877034}}
{"text": "/*\n# Copyright (c) 2020-2021 Juan J. Garcia Mesa <juanjosegarciamesa@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 MATRIX_HPP\n#define MATRIX_HPP\n\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace coati {\n\nusing Matrix64f = Eigen::Matrix<float, 64, 64>;\nusing float_t = float;\n\ntemplate <class T>\nclass Matrix {\n   public:\n    Matrix() = default;\n    Matrix(std::size_t rows, std::size_t cols, T value = static_cast<T>(0))\n        : rows_(rows), cols_(cols), data_(rows*cols, value) { }\n    Matrix(std::size_t rows, std::size_t cols, Matrix64f& eigen_m)\n        : rows_(rows), cols_(cols) {\n        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> m(\n            eigen_m);\n        data_.resize(rows_ * cols_);\n        for(std::size_t i = 0; i < rows_ * cols_; i++) {\n            data_[i] = m(i);\n        }\n    }\n    // copy constructor\n    Matrix(const Matrix &) = default;\n    // move constructor\n    Matrix(Matrix &&) = default;\n    // assignment operator\n    Matrix & operator=(const Matrix &) = default;\n    // move assignment operator\n    Matrix & operator=(Matrix &&) = default;\n    // destructor\n    ~Matrix() = default;\n\n    T operator()(std::size_t row, std::size_t col) const {\n        assert(row < rows_ && col < cols_);\n        return data_[row * cols_ + col];\n    }\n    T& operator()(std::size_t row, std::size_t col) {\n        assert(row < rows_ && col < cols_);\n        return data_[row * cols_ + col];\n    }\n    bool operator==(const Matrix& mat) const {\n        if((rows_ != mat.rows_) || (cols_ != mat.cols_)) {\n            return false;\n        }\n\n        for(std::size_t i = 0; i < rows_ * cols_; i++) {\n            if(data_[i] != mat.data_[i]) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    void resize(std::size_t rows, std::size_t cols,\n                T value = static_cast<T>(0)) {\n        rows_ = rows;\n        cols_ = cols;\n        data_.resize(rows * cols);\n        data_.assign(data_.size(), value);\n    }\n\n    std::size_t rows() const { return rows_; }\n    std::size_t cols() const { return cols_; }\n\n   private:\n    std::size_t rows_{0}, cols_{0};\n    std::vector<T> data_;\n};  // class matrix\n\n////////////////////////////////////////////////////////////////////////////////\n\n// template <class T>\ntemplate <class T>\nclass Tensor {\n   public:\n    Tensor(std::size_t dims, std::size_t rows, std::size_t cols, T value = 0.0f)\n        : dims_(dims), rows_(rows), cols_(cols) {\n        data_.resize(dims_ * rows_ * cols_);\n        data_.assign(data_.size(), value);\n    }\n    // copy constructor\n    Tensor(const Tensor& tens)\n        : dims_(tens.dims_), rows_(tens.rows_), cols_(tens.cols_) {\n        memcpy(&data_[0], &tens.data_[0], dims_ * rows_ * cols_ * sizeof(T));\n    }\n    // move constructor\n    Tensor(Tensor&& tens) noexcept\n        : dims_(tens.dims_),\n          rows_(tens.rows_),\n          cols_(tens.cols_),\n          data_(std::move(tens.data_)) {}\n    // destructor\n    ~Tensor() = default;\n    // assignment operator\n    Tensor& operator=(const Tensor& tens) {\n        if(&tens != this) {\n            memcpy(&data_[0], &tens.data_[0],\n                   dims_ * rows_ * cols_ * sizeof(T));\n        }\n        return *this;\n    }\n    // move assignment operator\n    Tensor& operator=(Tensor&& tens) noexcept {\n        dims_ = tens.dims_;\n        rows_ = tens.rows_;\n        cols_ = tens.cols_;\n        data_ = std::move(tens.data_);\n        return *this;\n    }\n    T operator()(std::size_t dims, std::size_t row, std::size_t col) const {\n        return data_[dims * rows_ * cols_ + row * cols_ + col];\n    }\n    T& operator()(std::size_t dims, std::size_t row, std::size_t col) {\n        return data_[dims * rows_ * cols_ + row * cols_ + col];\n    }\n    bool operator==(const Tensor& tens) const;\n\n   private:\n    std::size_t dims_, rows_, cols_;\n    std::vector<T> data_;\n};  // class Tensor\n\nusing Matrixf = Matrix<float_t>;\nusing Matrixi = Matrix<int>;\nusing Tensorf = Tensor<float_t>;\n\n}  // namespace coati\n#endif\n", "meta": {"hexsha": "7e72359e96a61ab8204c1f9e7ae5cd5d8b7a8dd3", "size": 5058, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/coati/matrix.hpp", "max_stars_repo_name": "CartwrightLab/coa", "max_stars_repo_head_hexsha": "b8a68e2eb70103666e937bb5086374482a2c06db", "max_stars_repo_licenses": ["MIT"], "max_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/coati/matrix.hpp", "max_issues_repo_name": "CartwrightLab/coa", "max_issues_repo_head_hexsha": "b8a68e2eb70103666e937bb5086374482a2c06db", "max_issues_repo_licenses": ["MIT"], "max_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/coati/matrix.hpp", "max_forks_repo_name": "CartwrightLab/coa", "max_forks_repo_head_hexsha": "b8a68e2eb70103666e937bb5086374482a2c06db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-14T21:53:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-14T21:53:55.000Z", "avg_line_length": 32.4230769231, "max_line_length": 80, "alphanum_fraction": 0.6026097272, "num_tokens": 1296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5220978544877034}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2018, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_LINE_INTERPOLATE_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_LINE_INTERPOLATE_HPP\n\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/srs/spheroid.hpp>\n#include <boost/geometry/strategies/line_interpolate.hpp>\n#include <boost/geometry/strategies/geographic/parameters.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace line_interpolate\n{\n\n\n/*!\n\\brief Interpolate point on a geographic segment.\n\\ingroup strategies\n\\tparam FormulaPolicy The geodesic formulas used internally.\n\\tparam Spheroid The spheroid model.\n\\tparam CalculationType \\tparam_calculation\n\n\\qbk{\n[heading See also]\n\\* [link geometry.reference.algorithms.line_interpolate.line_interpolate_4_with_strategy line_interpolate (with strategy)]\n\\* [link geometry.reference.srs.srs_spheroid srs::spheroid]\n}\n */\ntemplate\n<\n    typename FormulaPolicy = strategy::andoyer,\n    typename Spheroid = srs::spheroid<double>,\n    typename CalculationType = void\n>\nclass geographic\n{\npublic:\n    geographic()\n        : m_spheroid()\n    {}\n\n    explicit geographic(Spheroid const& spheroid)\n        : m_spheroid(spheroid)\n    {}\n\n    // point-point strategy getters\n    struct distance_pp_strategy\n    {\n        typedef distance::geographic<FormulaPolicy, Spheroid, CalculationType> type;\n    };\n\n    inline typename distance_pp_strategy::type get_distance_pp_strategy() const\n    {\n        typedef typename distance_pp_strategy::type distance_type;\n        return distance_type(m_spheroid);\n    }\n\n    template <typename Point, typename Fraction, typename Distance>\n    inline void apply(Point const& p0,\n                      Point const& p1,\n                      Fraction const& fraction, //fraction of segment\n                      Point & p,\n                      Distance const& distance) const\n    {\n        typedef typename select_calculation_type_alt\n            <\n                CalculationType,\n                Point\n            >::type calc_t;\n\n        typedef typename FormulaPolicy::template inverse\n                <calc_t, false, true, false, false, false> inverse_t;\n\n        calc_t azimuth = inverse_t::apply(get_as_radian<0>(p0), get_as_radian<1>(p0),\n                                          get_as_radian<0>(p1), get_as_radian<1>(p1),\n                                          m_spheroid).azimuth;\n\n        typedef typename FormulaPolicy::template direct\n                <calc_t, true, false, false, false> direct_t;\n\n        typename direct_t::result_type\n        dir_r = direct_t::apply(get_as_radian<0>(p0), get_as_radian<1>(p0),\n                                distance * fraction, azimuth,\n                                m_spheroid);\n\n        set_from_radian<0>(p, dir_r.lon2);\n        set_from_radian<1>(p, dir_r.lat2);\n    }\n\nprivate:\n    Spheroid m_spheroid;\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <>\nstruct default_strategy<geographic_tag>\n{\n    typedef strategy::line_interpolate::geographic<> type;\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::line_interpolate\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_LINE_INTERPOLATE_HPP\n", "meta": {"hexsha": "d5f0e04c933e7b02a3977871281b4b72d5555c69", "size": 3710, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/geographic/line_interpolate.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/geographic/line_interpolate.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/geographic/line_interpolate.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": 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.5384615385, "max_line_length": 122, "alphanum_fraction": 0.6900269542, "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5220668639206539}}
{"text": "/*\n * BlueNoise.hpp\n *\n *  Created on: Feb 6, 2012\n *      Author: david\n */\n\n#ifndef BLUENOISE_HPP_\n#define BLUENOISE_HPP_\n//----------------------------------------------------------------------------//\n#include <Slimage/Slimage.hpp>\n#include <Danvil/Tools/FunctionCache.h>\n#include <Eigen/Dense>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n//----------------------------------------------------------------------------//\nnamespace pds {\n//----------------------------------------------------------------------------//\n\nnamespace fattal\n{\n\t// need to change some other functions too!!!\n\tconstexpr unsigned int D = 2;\n\n\tstruct Point {\n\t\tfloat x, y;\n\t\tfloat weight;\n\t\tfloat scale;\n\t};\n\n\tconstexpr float KernelRange = 2.5f;\n\n\tconstexpr float cMaxRefinementScale = 10.0f;\n\n\tconstexpr float cPi = 3.141592654f;\n\n\t/** phi(x) = exp(-pi*x*x) */\n\tinline\n\tfloat KernelFunctorImpl(float d) {\n\t\treturn std::exp(-cPi*d*d);\n\t}\n\n\t/**\n\t * Warning: only defined for y <= 1!\n\t */\n\tinline float KernelFunctorInverse(float y) {\n\t\treturn std::sqrt(- std::log(y) / cPi);\n\t}\n\n\tinline\n\tfloat KernelFunctor(float d) {\n\t\tstatic Danvil::FunctionCache<float,1> cache(0.0f, KernelRange, &KernelFunctorImpl);\n\t\treturn cache(std::abs(d));\n\t}\n\n\tinline\n\tfloat KernelFunctorSquareImpl(float d) {\n\t\treturn std::exp(-cPi*d);\n\t}\n\n\tinline\n\tfloat KernelFunctorSquare(float d) {\n\t\tstatic Danvil::FunctionCache<float,1> cache(0.0f, KernelRange*KernelRange, &KernelFunctorSquareImpl);\n\t\treturn cache(d);\n\t}\n\n\tinline\n\tfloat ZeroBorderAccess(const Eigen::MatrixXf& density, int x, int y) {\n\t\tif(0 <= x && x < int(density.rows()) && 0 <= y && y < int(density.cols())) {\n\t\t\treturn density(x, y);\n\t\t}\n\t\telse {\n\t\t\treturn 0.0f;\n\t\t}\n\t}\n\n\tinline\n\tfloat ZeroBorderAccess(const Eigen::MatrixXf& density, float x, float y) {\n\t\treturn ZeroBorderAccess(density, (int)std::round(x), (int)std::round(y));\n\t}\n\n\tinline\n\tfloat KernelScaleFunction(float roh, float weight) {\n//\t\treturn std::pow(roh / weight, -1.0f / float(D));\n\t\treturn 1.0f / std::sqrt(roh / weight);\n\t}\n\n\tinline\n\tfloat ScalePowerD(float s) {\n\t\t//return std::pow(s, -float(D));\n\t\treturn 1.0f / (s*s);\n\t}\n\n\tfloat EnergyApproximation(const std::vector<Point>& pnts, float x, float y);\n\n\tfloat Energy(const std::vector<Point>& pnts, const Eigen::MatrixXf& density);\n\n\tfloat EnergyDerivative(const std::vector<Point>& pnts, const Eigen::MatrixXf& density, unsigned int i, float& result_dE_x, float& result_dE_y);\n\n\tstd::vector<Point> PlacePoints(const Eigen::MatrixXf& density, unsigned int p);\n\n\tvoid Refine(std::vector<Point>& points, const Eigen::MatrixXf& density, unsigned int iterations);\n\n\tstd::vector<Point> Split(const std::vector<Point>& points, const Eigen::MatrixXf& density, bool& result_added);\n\n\tstd::vector<Point> Compute(const Eigen::MatrixXf& density);\n\n\tstruct Color {\n\t\tunsigned char r,g,b;\n\t};\n\n\tvoid PlotPoints(const std::vector<Point>& points, const slimage::Image1ub& img, unsigned char grey=0, bool plot_1px=true);\n\n\tvoid PlotPoints(const std::vector<Point>& points, const slimage::Image3ub& img, const slimage::Pixel3ub& color=slimage::Pixel3ub{{0,0,0}}, bool plot_1px=true);\n\n}\n\n//----------------------------------------------------------------------------//\n}\n//----------------------------------------------------------------------------//\n#endif\n", "meta": {"hexsha": "2fce37967339819b88fe000c9ce2e4d204b2cbff", "size": 3293, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib_dasp/lib_dasp_pds/pds/Fattal.hpp", "max_stars_repo_name": "jbellis/superpixel-benchmark", "max_stars_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2016-12-16T10:11:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:08:14.000Z", "max_issues_repo_path": "lib_dasp/lib_dasp_pds/pds/Fattal.hpp", "max_issues_repo_name": "jbellis/superpixel-benchmark", "max_issues_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2018-02-15T19:34:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-31T17:04:48.000Z", "max_forks_repo_path": "lib_dasp/lib_dasp_pds/pds/Fattal.hpp", "max_forks_repo_name": "jbellis/superpixel-benchmark", "max_forks_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 111.0, "max_forks_repo_forks_event_min_datetime": "2016-12-08T07:19:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:08:16.000Z", "avg_line_length": 26.7723577236, "max_line_length": 160, "alphanum_fraction": 0.6091709687, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5220668639206539}}
{"text": "/**\n * @file tests/gan_test.cpp\n * @author Kris Singh\n * @author Shikhar Jaiswal\n *\n * Tests the GAN network.\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\n#include <mlpack/methods/ann/init_rules/gaussian_init.hpp>\n#include <mlpack/methods/ann/loss_functions/sigmoid_cross_entropy_error.hpp>\n#include <mlpack/methods/ann/gan/gan.hpp>\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/softmax_regression/softmax_regression.hpp>\n\n#include <ensmallen.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::ann;\nusing namespace mlpack::math;\nusing namespace mlpack::regression;\nusing namespace std::placeholders;\n\nBOOST_AUTO_TEST_SUITE(GANNetworkTest);\n\n/*\n * Load pre trained network values\n * for generating distribution that\n * is close to N(4, 0.5)\n */\nBOOST_AUTO_TEST_CASE(GANTest)\n{\n  size_t generatorHiddenLayerSize = 8;\n  size_t discriminatorHiddenLayerSize = 8;\n  size_t generatorOutputSize = 1;\n  size_t discriminatorOutputSize = 1;\n  size_t discriminatorPreTrain = 0;\n  size_t batchSize = 8;\n  size_t noiseDim = 1;\n  size_t generatorUpdateStep = 1;\n  size_t numSamples = 10000;\n  double multiplier = 1;\n\n  arma::mat trainData(1, 10000);\n  trainData.imbue( [&]() { return arma::as_scalar(RandNormal(4, 0.5));});\n  trainData = arma::sort(trainData);\n\n  // Create the Discriminator network.\n  FFN<SigmoidCrossEntropyError<> > discriminator;\n  discriminator.Add<Linear<> > (\n      generatorOutputSize, discriminatorHiddenLayerSize * 2);\n  discriminator.Add<ReLULayer<> >();\n  discriminator.Add<Linear<> > (\n      discriminatorHiddenLayerSize * 2, discriminatorHiddenLayerSize * 2);\n  discriminator.Add<ReLULayer<> >();\n  discriminator.Add<Linear<> > (\n      discriminatorHiddenLayerSize * 2, discriminatorHiddenLayerSize * 2);\n  discriminator.Add<ReLULayer<> >();\n  discriminator.Add<Linear<> > (\n      discriminatorHiddenLayerSize * 2, discriminatorOutputSize);\n\n  // Create the Generator network.\n  FFN<SigmoidCrossEntropyError<> > generator;\n  generator.Add<Linear<> >(noiseDim, generatorHiddenLayerSize);\n  generator.Add<SoftPlusLayer<> >();\n  generator.Add<Linear<> >(generatorHiddenLayerSize, generatorOutputSize);\n\n  // Create GAN.\n  GaussianInitialization gaussian(0, 0.1);\n  std::function<double ()> noiseFunction = [](){ return math::Random(-8, 8) +\n      math::RandNormal(0, 1) * 0.01;};\n  GAN<FFN<SigmoidCrossEntropyError<> >,\n      GaussianInitialization,\n      std::function<double()> >\n  gan(generator, discriminator, gaussian, noiseFunction, noiseDim, batchSize,\n      generatorUpdateStep, discriminatorPreTrain, multiplier);\n  gan.ResetData(trainData);\n\n  Log::Info << \"Loading Parameters\" << std::endl;\n  arma::mat parameters, generatorParameters;\n  parameters.load(\"preTrainedGAN.arm\");\n  gan.Parameters() = parameters;\n\n  // Generate samples.\n  Log::Info << \"Sampling...\" << std::endl;\n  arma::mat noise(noiseDim, batchSize);\n\n  size_t dim = std::sqrt(trainData.n_rows);\n  arma::mat generatedData(2 * dim, dim * numSamples);\n\n  for (size_t i = 0; i < numSamples; i++)\n  {\n    arma::mat samples;\n    noise.imbue( [&]() { return noiseFunction(); } );\n\n    gan.Generator().Forward(noise, samples);\n    samples.reshape(dim, dim);\n    samples = samples.t();\n\n    generatedData.submat(0, i * dim, dim - 1, i * dim + dim - 1) = samples;\n\n    samples = trainData.col(math::RandInt(0, trainData.n_cols));\n    samples.reshape(dim, dim);\n    samples = samples.t();\n\n    generatedData.submat(dim,\n        i * dim, 2 * dim - 1, i * dim + dim - 1) = samples;\n  }\n\n  double generatedMean = arma::as_scalar(arma::mean(\n      generatedData.rows(0, dim - 1), 1));\n  double originalMean = arma::as_scalar(arma::mean(\n      generatedData.rows(dim, 2 * dim - 1), 1));\n  double generatedStd = arma::as_scalar(arma::stddev(\n      generatedData.rows(0, dim - 1), 0, 1));\n  double originalStd = arma::as_scalar(arma::stddev(\n      generatedData.rows(dim, 2 * dim - 1), 0, 1));\n\n  BOOST_REQUIRE_LE(generatedMean - originalMean, 0.2);\n  BOOST_REQUIRE_LE(generatedStd - originalStd, 0.2);\n}\n\n/*\n * Tests the GAN implementation of the O'Reilly Test on the MNIST dataset.\n * It's not viable to train on bigger parameters due to time constraints.\n * Please refer mlpack/models repository for the tutorial.\n */\nBOOST_AUTO_TEST_CASE(GANMNISTTest)\n{\n  size_t dNumKernels = 32;\n  size_t discriminatorPreTrain = 5;\n  size_t batchSize = 5;\n  size_t noiseDim = 100;\n  size_t generatorUpdateStep = 1;\n  size_t numSamples = 10;\n  double stepSize = 0.0003;\n  double eps = 1e-8;\n  size_t numEpoches = 1;\n  double tolerance = 1e-5;\n  int datasetMaxCols = 10;\n  bool shuffle = true;\n  double multiplier = 10;\n\n  Log::Info << std::boolalpha\n      << \" batchSize = \" << batchSize << std::endl\n      << \" generatorUpdateStep = \" << generatorUpdateStep << std::endl\n      << \" noiseDim = \" << noiseDim << std::endl\n      << \" numSamples = \" << numSamples << std::endl\n      << \" stepSize = \" << stepSize << std::endl\n      << \" numEpoches = \" << numEpoches << std::endl\n      << \" tolerance = \" << tolerance << std::endl\n      << \" shuffle = \" << shuffle << std::endl;\n\n  arma::mat trainData;\n  trainData.load(\"mnist_first250_training_4s_and_9s.arm\");\n  Log::Info << arma::size(trainData) << std::endl;\n\n  trainData = trainData.cols(0, datasetMaxCols - 1);\n\n  size_t numIterations = trainData.n_cols * numEpoches;\n  numIterations /= batchSize;\n\n  Log::Info << \"Dataset loaded (\" << trainData.n_rows << \", \"\n            << trainData.n_cols << \")\" << std::endl;\n  Log::Info << trainData.n_rows << \"--------\" << trainData.n_cols << std::endl;\n\n  // Create the Discriminator network.\n  FFN<SigmoidCrossEntropyError<> > discriminator;\n  discriminator.Add<Convolution<> >(1, dNumKernels, 5, 5, 1, 1, 2, 2, 28, 28);\n  discriminator.Add<ReLULayer<> >();\n  discriminator.Add<MeanPooling<> >(2, 2, 2, 2);\n  discriminator.Add<Convolution<> >(dNumKernels, 2 * dNumKernels, 5, 5, 1, 1,\n      2, 2, 14, 14);\n  discriminator.Add<ReLULayer<> >();\n  discriminator.Add<MeanPooling<> >(2, 2, 2, 2);\n  discriminator.Add<Linear<> >(7 * 7 * 2 * dNumKernels, 1024);\n  discriminator.Add<ReLULayer<> >();\n  discriminator.Add<Linear<> >(1024, 1);\n\n  // Create the Generator network.\n  FFN<SigmoidCrossEntropyError<> > generator;\n  generator.Add<Linear<> >(noiseDim, 3136);\n  generator.Add<BatchNorm<> >(3136);\n  generator.Add<ReLULayer<> >();\n  generator.Add<Convolution<> >(1, noiseDim / 2, 3, 3, 2, 2, 1, 1, 56, 56);\n  generator.Add<BatchNorm<> >(39200);\n  generator.Add<ReLULayer<> >();\n  generator.Add<BilinearInterpolation<> >(28, 28, 56, 56, noiseDim / 2);\n  generator.Add<Convolution<> >(noiseDim / 2, noiseDim / 4, 3, 3, 2, 2, 1, 1,\n      56, 56);\n  generator.Add<BatchNorm<> >(19600);\n  generator.Add<ReLULayer<> >();\n  generator.Add<BilinearInterpolation<> >(28, 28, 56, 56, noiseDim / 4);\n  generator.Add<Convolution<> >(noiseDim / 4, 1, 3, 3, 2, 2, 1, 1, 56, 56);\n  generator.Add<TanHLayer<> >();\n\n  // Create GAN.\n  GaussianInitialization gaussian(0, 1);\n  ens::Adam optimizer(stepSize, batchSize, 0.9, 0.999, eps, numIterations,\n      tolerance, shuffle);\n  std::function<double()> noiseFunction = [] () {\n      return math::RandNormal(0, 1);};\n  GAN<FFN<SigmoidCrossEntropyError<> >, GaussianInitialization,\n      std::function<double()> > gan(generator, discriminator,\n      gaussian, noiseFunction, noiseDim, batchSize, generatorUpdateStep,\n      discriminatorPreTrain, multiplier);\n\n  Log::Info << \"Training...\" << std::endl;\n  std::stringstream stream;\n  double objVal = gan.Train(trainData, optimizer, ens::ProgressBar(70, stream));\n  BOOST_REQUIRE_GT(stream.str().length(), 0);\n  BOOST_REQUIRE_EQUAL(std::isfinite(objVal), true);\n\n  // Generate samples.\n  Log::Info << \"Sampling...\" << std::endl;\n  arma::mat noise(noiseDim, batchSize);\n  size_t dim = std::sqrt(trainData.n_rows);\n  arma::mat generatedData(2 * dim, dim * numSamples);\n\n  for (size_t i = 0; i < numSamples; i++)\n  {\n    arma::mat samples;\n    noise.imbue( [&]() { return noiseFunction(); } );\n\n    gan.Generator().Forward(noise, samples);\n    samples.reshape(dim, dim);\n    samples = samples.t();\n\n    generatedData.submat(0, i * dim, dim - 1, i * dim + dim - 1) = samples;\n\n    samples = trainData.col(math::RandInt(0, trainData.n_cols));\n    samples.reshape(dim, dim);\n    samples = samples.t();\n\n    generatedData.submat(dim,\n        i * dim, 2 * dim - 1, i * dim + dim - 1) = samples;\n  }\n\n  Log::Info << \"Output generated!\" << std::endl;\n\n  // Check that Serialization is working correctly.\n  arma::mat orgPredictions;\n  gan.Predict(noise, orgPredictions);\n\n  GAN<FFN<SigmoidCrossEntropyError<> >, GaussianInitialization,\n      std::function<double()> > ganText(generator, discriminator,\n      gaussian, noiseFunction, noiseDim, batchSize, generatorUpdateStep,\n      discriminatorPreTrain, multiplier);\n\n  GAN<FFN<SigmoidCrossEntropyError<> >, GaussianInitialization,\n      std::function<double()> > ganXml(generator, discriminator,\n      gaussian, noiseFunction, noiseDim, batchSize, generatorUpdateStep,\n      discriminatorPreTrain, multiplier);\n\n  GAN<FFN<SigmoidCrossEntropyError<> >, GaussianInitialization,\n      std::function<double()> > ganBinary(generator, discriminator,\n      gaussian, noiseFunction, noiseDim, batchSize, generatorUpdateStep,\n      discriminatorPreTrain, multiplier);\n\n  SerializeObjectAll(gan, ganXml, ganText, ganBinary);\n\n  arma::mat predictions, xmlPredictions, textPredictions, binaryPredictions;\n  gan.Predict(noise, predictions);\n  ganXml.Predict(noise, xmlPredictions);\n  ganText.Predict(noise, textPredictions);\n  ganBinary.Predict(noise, binaryPredictions);\n\n  CheckMatrices(orgPredictions, predictions);\n  CheckMatrices(orgPredictions, xmlPredictions);\n  CheckMatrices(orgPredictions, textPredictions);\n  CheckMatrices(orgPredictions, binaryPredictions);\n}\n\n/*\n * Create GAN network and test for memory sharing\n * between discriminator and gan predictors.\n */\nBOOST_AUTO_TEST_CASE(GANMemorySharingTest)\n{\n  size_t generatorHiddenLayerSize = 8;\n  size_t discriminatorHiddenLayerSize = 8;\n  size_t generatorOutputSize = 1;\n  size_t discriminatorOutputSize = 1;\n  size_t discriminatorPreTrain = 0;\n  size_t batchSize = 8;\n  size_t noiseDim = 1;\n  size_t generatorUpdateStep = 1;\n  double multiplier = 1;\n  double eps = 1e-8;\n  double stepSize = 0.0003;\n  size_t numIterations = 8;\n  double tolerance = 1e-5;\n  bool shuffle = true;\n\n  arma::mat trainData(1, 10000);\n  trainData.imbue( [&]() { return arma::as_scalar(RandNormal(4, 0.5));});\n  trainData = arma::sort(trainData);\n\n  // Create the Discriminator network.\n  FFN<SigmoidCrossEntropyError<> > discriminator;\n  discriminator.Add<Linear<> > (\n      generatorOutputSize, discriminatorHiddenLayerSize * 2);\n  discriminator.Add<ReLULayer<> >();\n  discriminator.Add<Linear<> > (\n      discriminatorHiddenLayerSize * 2, discriminatorHiddenLayerSize * 2);\n  discriminator.Add<ReLULayer<> >();\n  discriminator.Add<Linear<> > (\n      discriminatorHiddenLayerSize * 2, discriminatorHiddenLayerSize * 2);\n  discriminator.Add<ReLULayer<> >();\n  discriminator.Add<Linear<> > (\n      discriminatorHiddenLayerSize * 2, discriminatorOutputSize);\n\n  // Create the Generator network.\n  FFN<SigmoidCrossEntropyError<> > generator;\n  generator.Add<Linear<> >(noiseDim, generatorHiddenLayerSize);\n  generator.Add<SoftPlusLayer<> >();\n  generator.Add<Linear<> >(generatorHiddenLayerSize, generatorOutputSize);\n\n  // Create GAN.\n  GaussianInitialization gaussian(0, 0.1);\n  ens::Adam optimizer(stepSize, batchSize, 0.9, 0.999, eps, numIterations,\n      tolerance, shuffle);\n  std::function<double ()> noiseFunction = [](){ return math::Random(-8, 8) +\n      math::RandNormal(0, 1) * 0.01;};\n  GAN<FFN<SigmoidCrossEntropyError<> >,\n      GaussianInitialization,\n      std::function<double()> >\n  gan(generator, discriminator, gaussian, noiseFunction,\n      noiseDim, batchSize, generatorUpdateStep, discriminatorPreTrain,\n      multiplier);\n\n  gan.Train(trainData, optimizer);\n\n  CheckMatrices(gan.Predictors().head_cols(trainData.n_cols), trainData);\n  CheckMatrices(gan.Predictors(), gan.Discriminator().Predictors());\n  gan.Shuffle();\n  CheckMatrices(gan.Predictors(), gan.Discriminator().Predictors());\n  CheckMatricesNotEqual(gan.Predictors().head_cols(trainData.n_cols),\n      trainData);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "3705e11570c7da6fd362930ee576134b1bd33058", "size": 12624, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/gan_test.cpp", "max_stars_repo_name": "KimSangYeon-DGU/mlpack", "max_stars_repo_head_hexsha": "defa29791f43d3372b019f552134abc39def234a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mlpack/tests/gan_test.cpp", "max_issues_repo_name": "KimSangYeon-DGU/mlpack", "max_issues_repo_head_hexsha": "defa29791f43d3372b019f552134abc39def234a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/gan_test.cpp", "max_forks_repo_name": "KimSangYeon-DGU/mlpack", "max_forks_repo_head_hexsha": "defa29791f43d3372b019f552134abc39def234a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T13:27:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-23T09:44:31.000Z", "avg_line_length": 35.8636363636, "max_line_length": 80, "alphanum_fraction": 0.6962135615, "num_tokens": 3505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5220668639206538}}
{"text": "#include <mex.h> \n#include <math.h>\n#include <iostream>\n#include <vector>\n\n#include <igl/matlab/MexStream.h>\n#include <igl/matlab/parse_rhs.h>\n#include <igl/matlab/prepare_lhs.h>\n#include <igl/matlab/validate_arg.h>\n\n#include <igl/PI.h>\n#include <igl/forward_kinematics.h>\n#include <igl/directed_edge_parents.h>\n\n#include <Eigen/Core>\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid euler_to_quat(const Eigen::Vector3d& euler, Eigen::Quaterniond& q) {\n\n  q = Eigen::AngleAxisd(euler(2), Eigen::Vector3d::UnitZ())\n      * Eigen::AngleAxisd(euler(1), Eigen::Vector3d::UnitY())\n      * Eigen::AngleAxisd(euler(0), Eigen::Vector3d::UnitX());\n}\n\n\nvoid euler_to_quat(const Eigen::Vector3d& euler, const Eigen::Affine3d& a, Eigen::Quaterniond& q) {\n  q = Eigen::AngleAxisd(euler(2), a.rotation().col(2))\n      * Eigen::AngleAxisd(euler(1), a.rotation().col(1))\n      * Eigen::AngleAxisd(euler(0), a.rotation().col(0));\n}\n\n\nvoid read_bone_anim(std::string anim_file,\n    const Eigen::MatrixXd& C,\n    const Eigen::MatrixXi& BE,\n    const Eigen::VectorXi& P,\n    std::vector<Eigen::MatrixXd>& T_list)\n{\n  FILE* file;\n  file= fopen(anim_file.c_str(), \"rb\");\n\n  double degree2radian = igl::PI/180.0;\n\n  int num_bone, num_frame;\n  double val = 0;\n\n  typedef std::vector<Eigen::Quaterniond,\n      Eigen::aligned_allocator<Eigen::Quaterniond> > RotationList;\n\n\n  fscanf(file, \"%d %d\\n\", &num_bone, &num_frame);\n  T_list.resize(num_frame);\n  RotationList rot_list(num_bone);\n  std::vector<Eigen::Vector3d> tran_list(num_bone);\n  std::vector<Eigen::Affine3d> rest_list(num_bone);\n\n  Eigen::Vector3d root_rest_tran;\n  Eigen::Affine3d root_affine;\n  for (int j = 0; j < 3; j++) {\n    fscanf(file, \"%lf\", &val);\n    root_rest_tran(j) = val;\n  }\n  Eigen::Vector3d euler;\n  for (int j = 0; j < 3; j++) {\n    fscanf(file, \"%lf\", &val);\n    euler(j) = val;\n  }\n  euler = euler.array() * degree2radian;\n  Eigen::Quaterniond q;\n  euler_to_quat(euler, q);\n  root_affine = Eigen::Affine3d::Identity();\n  root_affine.rotate(q);\n\n  for (int i = 0; i < num_bone; i++) {\n    Eigen::Vector3d euler;\n    for (int j = 0; j < 3; j++) {\n      fscanf(file, \"%lf\", &val);\n      euler(j) = val;\n    }\n    euler = euler.array() * degree2radian;\n    Eigen::Quaterniond q;\n    euler_to_quat(euler, q);\n    Eigen::Affine3d a = Eigen::Affine3d::Identity();\n    a.rotate(q);\n    rest_list[i] = a;\n  }\n  //Eigen::Affine3d root_affine = rest_list[0];\n  Eigen::Vector3d root_tran, root_rot;\n  for (int k = 0; k < num_frame; k++) {\n    for (int j = 0; j < 3; j++) {\n      fscanf(file, \"%lf\", &val);\n      root_rot(j) = val;\n    }\n    for (int j = 0; j < 3; j++) {\n      fscanf(file, \"%lf\", &val);\n      root_tran(j) = val;\n    }\n    root_rot = root_rot.array() * degree2radian;\n    Eigen::Quaterniond root_q;\n    euler_to_quat(root_rot, root_affine, root_q);\n\n    for (int i = 0; i < num_bone; i++) {\n      Eigen::Vector3d euler;\n      for (int j = 0; j < 3; j++) {\n        fscanf(file, \"%lf\", &val);\n        euler(j) = val;\n      }\n      euler = euler.array() * degree2radian;\n      Eigen::Quaterniond q;\n      euler_to_quat(euler, rest_list[i], q);\n\n      if(P(i)==-1){\n        int root_cnt = 0;\n        for(int ii=0; ii<num_bone; ii++)\n          if(P(ii)==-1)\n            root_cnt++;\n        if(root_cnt>1)\n          q = q*root_q;\n        tran_list[i] = root_tran - root_rest_tran;\n      }\n      else\n        tran_list[i] = Eigen::Vector3d::Zero();\n      rot_list[i] = q;\n    }\n    RotationList vQ;\n    std::vector<Eigen::Vector3d> vT;\n    igl::forward_kinematics(C, BE, P, rot_list, tran_list, vQ, vT);\n\n    Eigen::MatrixXd T(num_bone * 4, 3);\n    for (int i = 0; i < num_bone; i++) {\n      Eigen::Affine3d a = Eigen::Affine3d::Identity();\n      a.translate(vT[i]);\n      a.rotate(vQ[i]);\n      T.block(i * 4, 0, 4, 3) = a.matrix().transpose().block(0, 0, 4, 3);\n    }\n    T_list[k] = T;\n  }\n  fclose(file);\n}\n\nvoid read_bone_anim(std::string anim_file,\n    const Eigen::MatrixXd& C,\n    const Eigen::MatrixXi& BE,\n    const Eigen::VectorXi& P,\n    const Eigen::VectorXd& center,\n    const double& scale,\n    std::vector<Eigen::MatrixXd>& T_list)\n{\n  FILE* file;\n  file= fopen(anim_file.c_str(), \"rb\");\n\n  double degree2radian = igl::PI/180.0;\n\n  int num_bone, num_frame;\n  double val = 0;\n\n  typedef std::vector<Eigen::Quaterniond,\n      Eigen::aligned_allocator<Eigen::Quaterniond> > RotationList;\n\n\n  fscanf(file, \"%d %d\\n\", &num_bone, &num_frame);\n  T_list.resize(num_frame);\n  RotationList rot_list(num_bone);\n  std::vector<Eigen::Vector3d> tran_list(num_bone);\n  std::vector<Eigen::Affine3d> rest_list(num_bone);\n\n  Eigen::Vector3d root_rest_tran;\n  Eigen::Affine3d root_affine;\n  for (int j = 0; j < 3; j++) {\n    fscanf(file, \"%lf\", &val);\n    root_rest_tran(j) = val;\n  }\n  root_rest_tran = (root_rest_tran-center)/scale;\n\n  Eigen::Vector3d euler;\n  for (int j = 0; j < 3; j++) {\n    fscanf(file, \"%lf\", &val);\n    euler(j) = val;\n  }\n  euler = euler.array() * degree2radian;\n  Eigen::Quaterniond q;\n  euler_to_quat(euler, q);\n  root_affine = Eigen::Affine3d::Identity();\n  root_affine.rotate(q);\n\n  for (int i = 0; i < num_bone; i++) {\n    Eigen::Vector3d euler;\n    for (int j = 0; j < 3; j++) {\n      fscanf(file, \"%lf\", &val);\n      euler(j) = val;\n    }\n    euler = euler.array() * degree2radian;\n    Eigen::Quaterniond q;\n    euler_to_quat(euler, q);\n    Eigen::Affine3d a = Eigen::Affine3d::Identity();\n    a.rotate(q);\n    rest_list[i] = a;\n  }\n  //Eigen::Affine3d root_affine = rest_list[0];\n  Eigen::Vector3d root_tran, root_rot;\n  for (int k = 0; k < num_frame; k++) {\n    for (int j = 0; j < 3; j++) {\n      fscanf(file, \"%lf\", &val);\n      root_rot(j) = val;\n    }\n    for (int j = 0; j < 3; j++) {\n      fscanf(file, \"%lf\", &val);\n      root_tran(j) = val;\n    }\n    root_tran = (root_tran - center)/scale;\n    root_rot = root_rot.array() * degree2radian;\n    Eigen::Quaterniond root_q;\n    euler_to_quat(root_rot, root_affine, root_q);\n\n    for (int i = 0; i < num_bone; i++) {\n      Eigen::Vector3d euler;\n      for (int j = 0; j < 3; j++) {\n        fscanf(file, \"%lf\", &val);\n        euler(j) = val;\n      }\n      euler = euler.array() * degree2radian;\n      Eigen::Quaterniond q;\n      euler_to_quat(euler, rest_list[i], q);\n\n      if(P(i)==-1){\n        int root_cnt = 0;\n        for(int ii=0; ii<num_bone; ii++)\n          if(P(ii)==-1)\n            root_cnt++;\n        if(root_cnt>1)\n          q = q*root_q;\n        tran_list[i] = root_tran - root_rest_tran;\n      }\n      else\n        tran_list[i] = Eigen::Vector3d::Zero();\n      rot_list[i] = q;\n    }\n    RotationList vQ;\n    std::vector<Eigen::Vector3d> vT;\n    igl::forward_kinematics(C, BE, P, rot_list, tran_list, vQ, vT);\n\n    Eigen::MatrixXd T(num_bone * 4, 3);\n    for (int i = 0; i < num_bone; i++) {\n      Eigen::Affine3d a = Eigen::Affine3d::Identity();\n      a.translate(vT[i]);\n      a.rotate(vQ[i]);\n      T.block(i * 4, 0, 4, 3) = a.matrix().transpose().block(0, 0, 4, 3);\n    }\n    T_list[k] = T;\n\n  }\n  fclose(file);\n}\n\n\n\nvoid mexFunction(\n  int          nlhs,\n  mxArray      *plhs[],\n  int          nrhs,\n  const mxArray *prhs[])\n{\n    Eigen::MatrixXd C;\n    Eigen::MatrixXi BE;\n    Eigen::VectorXi P;\n    Eigen::VectorXd center;\n    double scale;\n    char* anim_file = mxArrayToString(prhs[0]);\n\n    igl::matlab::parse_rhs_double(prhs+1, C);\n    igl::matlab::parse_rhs_index(prhs+2, BE);\n\n    igl::matlab::parse_rhs_double(prhs+3, center);\n    scale = (double) *mxGetPr(prhs[4]);\n\n    igl::directed_edge_parents(BE, P);\n\n    std::vector<Eigen::MatrixXd> T_list;\n    read_bone_anim(anim_file, C,BE,P,center,scale, T_list);\n    //read_bone_anim(anim_file, C,BE,P, T_list);\n\n\n    plhs[0] = mxCreateCellMatrix(T_list.size(),1);\n\n    mxArray *x;\n    for(int i=0; i<T_list.size(); i++){\n        const int m = T_list[i].rows();\n        const int n = T_list[i].cols();\n        x = mxCreateDoubleMatrix(m,n, mxREAL);\n        Eigen::Map< Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > map(mxGetPr(x),m,n);\n        map = T_list[i].template cast<double>();\n        mxSetCell(plhs[0], i, x);\n    }\n    return;\n}", "meta": {"hexsha": "3576be7b2e782cdfd1675f1e7ebd4d714a557ab3", "size": 8062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab-include/mex/read_3d_bone_anim.cpp", "max_stars_repo_name": "ErisZhang/complementary-dynamics", "max_stars_repo_head_hexsha": "87d11804b79d37199669645dd12ce6f00fce513c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T11:03:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T00:58:26.000Z", "max_issues_repo_path": "matlab-include/mex/read_3d_bone_anim.cpp", "max_issues_repo_name": "ErisZhang/complementary-dynamics", "max_issues_repo_head_hexsha": "87d11804b79d37199669645dd12ce6f00fce513c", "max_issues_repo_licenses": ["MIT"], "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-include/mex/read_3d_bone_anim.cpp", "max_forks_repo_name": "ErisZhang/complementary-dynamics", "max_forks_repo_head_hexsha": "87d11804b79d37199669645dd12ce6f00fce513c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-25T06:39:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-18T03:19:00.000Z", "avg_line_length": 27.1447811448, "max_line_length": 99, "alphanum_fraction": 0.5924088316, "num_tokens": 2632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.85391273808085, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5220668548288817}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// This file is manually converted from PROJ4\n\n// Copyright (c) 2008-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// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Geometry Library by Barend Gehrels (Geodan, Amsterdam)\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#ifndef BOOST_GEOMETRY_PROJECTIONS_PJ_MLFN_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_PJ_MLFN_HPP\n\n\n\n#include <boost/geometry/util/math.hpp>\n\n\nnamespace boost { namespace geometry { namespace projections {\n\nnamespace detail {\n\n/* meridinal distance for ellipsoid and inverse\n**    8th degree - accurate to < 1e-5 meters when used in conjuction\n**        with typical major axis values.\n**    Inverse determines phi to EPS (1e-11) radians, about 1e-6 seconds.\n*/\nstatic const double C00 = 1.;\nstatic const double C02 = .25;\nstatic const double C04 = .046875;\nstatic const double C06 = .01953125;\nstatic const double C08 = .01068115234375;\nstatic const double C22 = .75;\nstatic const double C44 = .46875;\nstatic const double C46 = .01302083333333333333;\nstatic const double C48 = .00712076822916666666;\nstatic const double C66 = .36458333333333333333;\nstatic const double C68 = .00569661458333333333;\nstatic const double C88 = .3076171875;\nstatic const double EPS = 1e-11;\nstatic const int MAX_ITER = 10;\nstatic const int EN_SIZE = 5;\n\ninline bool pj_enfn(double es, double* en)\n{\n    double t; //, *en;\n\n    //if (en = (double *)pj_malloc(EN_SIZE * sizeof(double)))\n    {\n        en[0] = C00 - es * (C02 + es * (C04 + es * (C06 + es * C08)));\n        en[1] = es * (C22 - es * (C04 + es * (C06 + es * C08)));\n        en[2] = (t = es * es) * (C44 - es * (C46 + es * C48));\n        en[3] = (t *= es) * (C66 - es * C68);\n        en[4] = t * es * C88;\n    }\n    // return en;\n    return true;\n}\n\ninline double pj_mlfn(double phi, double sphi, double cphi, const double *en)\n{\n    cphi *= sphi;\n    sphi *= sphi;\n    return(en[0] * phi - cphi * (en[1] + sphi*(en[2]\n        + sphi*(en[3] + sphi*en[4]))));\n}\n\ninline double pj_inv_mlfn(double arg, double es, const double *en)\n{\n    double s, t, phi, k = 1./(1.-es);\n    int i;\n\n    phi = arg;\n    for (i = MAX_ITER; i ; --i) { /* rarely goes over 2 iterations */\n        s = sin(phi);\n        t = 1. - es * s * s;\n        phi -= t = (pj_mlfn(phi, s, cos(phi), en) - arg) * (t * sqrt(t)) * k;\n        if (geometry::math::abs(t) < EPS)\n            return phi;\n    }\n    throw proj_exception(-17);\n    return phi;\n}\n\n} // namespace detail\n}}} // namespace boost::geometry::projections\n\n#endif\n", "meta": {"hexsha": "c4bbf266efa7904f677976690e41c5cc3b2e6ff5", "size": 3946, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/impl/pj_mlfn.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T05:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T05:02:05.000Z", "max_issues_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/impl/pj_mlfn.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "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": "3party/boost/boost/geometry/extensions/gis/projections/impl/pj_mlfn.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": 34.9203539823, "max_line_length": 79, "alphanum_fraction": 0.6819564116, "num_tokens": 1093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5220668548288816}}
{"text": "/*\n *  utils.hpp\n *\n *\tAuthor(s): Tamas D. Nagy\n *\tCreated on: 2016-11-08\n *\n *  Useful functions to provide compatibility\n *  of basic datatypes, mainly in matematical\n *  calculations.\n *\n */\n\n#ifndef DVRK_UTILS_HPP_\n#define DVRK_UTILS_HPP_\n\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <Eigen/Dense>\n#include <Eigen/Geometry> \n#include <limits>\n#include \"irob_utils/pose.hpp\"\n\n#include <std_msgs/Float32.h>\n#include <irob_msgs/FloatArray.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/Point.h>\n#include <geometry_msgs/PointStamped.h>\n#include <irob_msgs/ToolPose.h>\n#include <irob_msgs/ToolPoseStamped.h>\n#include <irob_msgs/Environment.h>\n\nnamespace saf {\n\ntypedef enum InterpolationMethod \n{LINEAR, BEZIER} InterpolationMethod;\n\ninline double degToRad(double deg) {\n  return (deg / 180.0) * M_PI;\n}\n\ninline double radToDeg(double rad) {\n  return (rad * 180.0) / M_PI;\n}\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& out, const std::vector<T>& v) {\n  out << \"[\";\n  size_t last = v.size() - 1;\n  for(size_t i = 0; i < v.size(); ++i) {\n    out << v[i];\n    if (i != last)\n      out << \", \";\n  }\n  out << \"]\";\n  return out;\n}\n\n// Interpolation\ntemplate<typename T>\ninline T interpolate(double a, T const& x1, T const& x2) {\n  return ((1.0-a) * x1) + ((a) * x2);\n}\n\ntemplate <>\ninline Pose interpolate(double a, const Pose& x1, const Pose& x2) {\n  return x1.interpolate(a, x2);\n}\n\ntemplate <>\ninline Eigen::Quaternion<double> interpolate(double a,\n                                             const Eigen::Quaternion<double>& x1,\n                                             const Eigen::Quaternion<double>& x2) {\n  return x1.slerp(a, x2);\n}\n\n// Distance\ntemplate<typename T>\ninline double distanceEuler(T const& x1, T const& x2) {\n  return std::abs(x2 - x1);\n}\n\n\ntemplate <>\ninline double distanceEuler(const Pose& x1, const Pose& x2) {\n  Pose::Distance d = x1.dist(x2);\n  double weighted_cartesian = std::abs(d.cartesian) * 10000.0;\n  double weighted_angle = std::abs(d.angle);\n  double weighted_jaw = radToDeg(std::abs(d.jaw));\n  if (weighted_cartesian >= weighted_angle\n      && weighted_cartesian >= weighted_jaw)\n    return std::abs(d.cartesian);\n  if (weighted_angle >= weighted_jaw)\n    // in degrees, should be converted to rad?\n    return std::abs(d.angle);\n  return std::abs(d.jaw);\n}\n\ntemplate <>\ninline double distanceEuler(const Eigen::Vector3d& x1,\n                            const Eigen::Vector3d& x2) {\n  return std::abs((x2-x1).norm());\n}\n\n// Conversion from ROS msg\ntemplate<typename MsgT, typename DataT>\ninline DataT unwrapMsg(const MsgT& msg);\n\ntemplate <>\ninline irob_msgs::Environment unwrapMsg(const irob_msgs::Environment& msg){\n  return msg;\n}\n\ntemplate <>\ninline double unwrapMsg(const std_msgs::Float32& msg){\n  return msg.data;\n}\n\ntemplate <>\ninline Pose unwrapMsg(const geometry_msgs::Pose& msg){\n  Pose ret(msg, 0);\n  return ret;\n}\n\ntemplate <>\ninline Pose unwrapMsg(const irob_msgs::ToolPose& msg){\n  Pose ret(msg);\n  return ret;\n}\n\ntemplate <>\ninline Pose unwrapMsg(const geometry_msgs::PoseStamped& msg){\n  Pose ret(msg, 0);\n  return ret;\n}\n\ntemplate <>\ninline Pose unwrapMsg(const irob_msgs::ToolPoseStamped& msg){\n  Pose ret(msg);\n  return ret;\n}\n\ntemplate <>\ninline Eigen::Vector3d unwrapMsg(const geometry_msgs::Point& msg){\n  Eigen::Vector3d ret(msg.x, msg.y, msg.z);\n  return ret;\n}\n\ntemplate <>\ninline Eigen::Vector3d unwrapMsg(const geometry_msgs::PointStamped& msg){\n  Eigen::Vector3d ret(msg.point.x, msg.point.y, msg.point.z);\n  return ret;\n}\n\ntemplate <>\ninline Eigen::Quaternion<double> unwrapMsg(const geometry_msgs::Quaternion& msg){\n  Eigen::Quaternion<double> ret(msg.w, msg.x, msg.y, msg.z);\n  return ret;\n}\n\ntemplate <>\ninline std::vector<double> unwrapMsg(const irob_msgs::FloatArray& msg){\n  return msg.data;\n}\n\n\n// Conversion to ROS msg\ntemplate<typename MsgT, typename DataT>\ninline MsgT wrapToMsg(const DataT& data);\n\ntemplate <>\ninline std_msgs::Float32 wrapToMsg(const double& data){\n  std_msgs::Float32 msg;\n  msg.data = data;\n  return msg;\n}\n\ntemplate <>\ninline geometry_msgs::Pose wrapToMsg(const Pose& data){\n  return data.toRosPose();\n}\n\ntemplate <>\ninline irob_msgs::ToolPose wrapToMsg(const Pose& data){\n  return data.toRosToolPose();\n}\n\ntemplate <>\ninline geometry_msgs::Point wrapToMsg(const Eigen::Vector3d& data){\n  geometry_msgs::Point msg;\n  msg.x = data.x();\n  msg.y = data.y();\n  msg.z = data.z();\n  return msg;\n}\n\ntemplate <>\ninline geometry_msgs::PointStamped wrapToMsg(const Eigen::Vector3d& data){\n  geometry_msgs::PointStamped msg;\n  msg.point.x = data.x();\n  msg.point.y = data.y();\n  msg.point.z = data.z();\n  return msg;\n}\n\ntemplate <>\ninline geometry_msgs::Quaternion wrapToMsg(\n    const Eigen::Quaternion<double>& data){\n  geometry_msgs::Quaternion msg;\n  msg.w = data.w();\n  msg.x = data.x();\n  msg.y = data.y();\n  msg.z = data.z();\n  return msg;\n}\n\n// NaN\ntemplate<typename DataT>\ninline DataT makeNaN();\n\n\ntemplate <>\ninline double makeNaN(){\n  return std::numeric_limits<double>::quiet_NaN();\n}\n\ntemplate <>\ninline Pose makeNaN(){\n  Pose ret(std::numeric_limits<double>::quiet_NaN(),\n           std::numeric_limits<double>::quiet_NaN(),\n           std::numeric_limits<double>::quiet_NaN(),\n           std::numeric_limits<double>::quiet_NaN(),\n           std::numeric_limits<double>::quiet_NaN(),\n           std::numeric_limits<double>::quiet_NaN(),\n           std::numeric_limits<double>::quiet_NaN(),\n           std::numeric_limits<double>::quiet_NaN());\n  return ret;\n}\n\n\ntemplate <>\ninline Eigen::Vector3d makeNaN(){\n  Eigen::Vector3d ret(std::numeric_limits<double>::quiet_NaN(),\n                      std::numeric_limits<double>::quiet_NaN(),\n                      std::numeric_limits<double>::quiet_NaN());\n  return ret;\n}\n\n\ntemplate <>\ninline Eigen::Quaternion<double> makeNaN(){\n  Eigen::Quaternion<double> ret(std::numeric_limits<double>::quiet_NaN(),\n                                std::numeric_limits<double>::quiet_NaN(),\n                                std::numeric_limits<double>::quiet_NaN(),\n                                std::numeric_limits<double>::quiet_NaN());\n  return ret;\n}\n\ntemplate <>\ninline std_msgs::Float32 makeNaN(){\n  std_msgs::Float32 msg;\n  msg.data = std::numeric_limits<double>::quiet_NaN();\n  return msg;\n}\n\ntemplate <>\ninline irob_msgs::FloatArray makeNaN(){\n  irob_msgs::FloatArray msg;\n  msg.data.push_back(std::numeric_limits<double>::quiet_NaN());\n  return msg;\n}\n\ntemplate <>\ninline geometry_msgs::Pose makeNaN(){\n  Pose nanp = makeNaN<Pose>();\n  return nanp.toRosPose();\n}\n\ntemplate <>\ninline irob_msgs::ToolPose makeNaN(){\n  Pose nanp = makeNaN<Pose>();\n  return nanp.toRosToolPose();\n}\n\ntemplate <>\ninline irob_msgs::Environment makeNaN(){\n  irob_msgs::Environment nanp;\n  nanp.valid = irob_msgs::Environment::INVALID;\n  return nanp;\n}\n\ntemplate <>\ninline geometry_msgs::Point makeNaN(){\n  geometry_msgs::Point msg;\n  msg.x = std::numeric_limits<double>::quiet_NaN();\n  msg.y = std::numeric_limits<double>::quiet_NaN();\n  msg.z = std::numeric_limits<double>::quiet_NaN();\n  return msg;\n}\n\ntemplate <>\ninline geometry_msgs::PointStamped makeNaN(){\n  geometry_msgs::PointStamped msg;\n  msg.point.x = std::numeric_limits<double>::quiet_NaN();\n  msg.point.y = std::numeric_limits<double>::quiet_NaN();\n  msg.point.z = std::numeric_limits<double>::quiet_NaN();\n  return msg;\n}\n\ntemplate <>\ninline geometry_msgs::Quaternion makeNaN(){\n  geometry_msgs::Quaternion msg;\n  msg.w = std::numeric_limits<double>::quiet_NaN();\n  msg.x = std::numeric_limits<double>::quiet_NaN();\n  msg.y = std::numeric_limits<double>::quiet_NaN();\n  msg.z = std::numeric_limits<double>::quiet_NaN();\n  return msg;\n}\n\n\n// isnan\ntemplate<typename DataT>\ninline bool isnan(const DataT& d);\n\n\ntemplate <>\ninline bool isnan(const double& d)\n{\n  return std::isnan(d);\n}\n\ntemplate <>\ninline bool isnan(const Pose& d)\n{\n  return (std::isnan(d.position.x())\n          || std::isnan(d.position.y())\n          || std::isnan(d.position.z())\n          || std::isnan(d.orientation.x())\n          || std::isnan(d.orientation.y())\n          || std::isnan(d.orientation.z())\n          || std::isnan(d.orientation.w())\n          || std::isnan(d.jaw));\n}\n\n\ntemplate <>\ninline bool isnan(const Eigen::Vector3d& d)\n{\n  return (std::isnan(d.x())\n          || std::isnan(d.y())\n          || std::isnan(d.z()));\n}\n\n\ntemplate <>\ninline bool isnan(const Eigen::Quaternion<double>& d)\n{\n  return (std::isnan(d.x())\n          || std::isnan(d.y())\n          || std::isnan(d.z())\n          || std::isnan(d.w()));\n}\n\ntemplate <>\ninline bool isnan(const std_msgs::Float32& d)\n{\n\n  return (std::isnan(d.data));\n}\n\ntemplate <>\ninline bool isnan(const geometry_msgs::Pose& d)\n{\n  return (std::isnan(d.position.x)\n          || std::isnan(d.position.y)\n          || std::isnan(d.position.z)\n          || std::isnan(d.orientation.x)\n          || std::isnan(d.orientation.y)\n          || std::isnan(d.orientation.z)\n          || std::isnan(d.orientation.w));\n}\n\ntemplate <>\ninline bool isnan(const irob_msgs::ToolPose& d)\n{\n  return (std::isnan(d.position.x)\n          || std::isnan(d.position.y)\n          || std::isnan(d.position.z)\n          || std::isnan(d.orientation.x)\n          || std::isnan(d.orientation.y)\n          || std::isnan(d.orientation.z)\n          || std::isnan(d.orientation.w)\n          || std::isnan(d.jaw));\n}\n\ntemplate <>\ninline bool isnan(const geometry_msgs::Point& d)\n{\n  return (std::isnan(d.x)\n          || std::isnan(d.y)\n          || std::isnan(d.z) );\n}\n\ntemplate <>\ninline bool isnan(const geometry_msgs::PointStamped& d)\n{\n  return isnan<geometry_msgs::Point>(d.point);\n}\n\ntemplate <>\ninline bool isnan(const geometry_msgs::Quaternion& d)\n{\n  return (std::isnan(d.x)\n          || std::isnan(d.y)\n          || std::isnan(d.z)\n          || std::isnan(d.w));\n}\n\n// Unit vector + rotation to quat\ntemplate<typename QuatT, typename VecT>\ninline QuatT vecToQuat(const VecT& vec, double angle);\n\ntemplate <>\ninline Eigen::Quaternion<double> vecToQuat(const Eigen::Vector3d& vec,\n                                           double angle){\n  Eigen::Quaternion<double> quat_start(0.0, 0.707107, 0.707106, 0.0);\n  double angle_rad = (angle / 180.0) * M_PI;\n  Eigen::Matrix3d R1m;\n  R1m = Eigen::AngleAxisd(0.0, Eigen::Vector3d::UnitX())\n      * Eigen::AngleAxisd(0.0,  Eigen::Vector3d::UnitY())\n      * Eigen::AngleAxisd(angle_rad, Eigen::Vector3d::UnitZ());\n  Eigen::Quaternion<double> R1(R1m);\n\n  Eigen::Quaternion<double> ret = R1 * quat_start;\n\n  Eigen::Vector3d vec_start(0.0, 0.0, -1.0);\n  Eigen::Quaternion<double> R2 =\n      Eigen::Quaternion<double>::FromTwoVectors(vec_start, vec);\n  ret = R2 * ret;\n  return ret;\n}\n\n// Quat to unit vector\ntemplate<typename QuatT, typename VecT>\ninline VecT quatToVec(const QuatT& quat);\n\ntemplate <>\ninline Eigen::Vector3d quatToVec(const Eigen::Quaternion<double>& quat){\n\n  Eigen::Quaternion<double> quat_start(0.0, 0.707107, 0.707106, 0.0);\n\n  Eigen::Quaternion<double> R = quat * quat_start.inverse();\n\n  Eigen::Vector3d vec_start(0.0, 0.0, -1.0);\n  Eigen::Vector3d ret = R * vec_start;\n  return ret;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}\n\n#endif /* DVRK_UTILS_HPP_ */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "93e5bc4b94f0e9764354e2eb47061f0afb9627a4", "size": 11219, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "irob_utils/include/irob_utils/utils.hpp", "max_stars_repo_name": "BenGab/irob-saf", "max_stars_repo_head_hexsha": "3a0fee98239bd935aa99c9d9526eb9b4cfc8963c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "irob_utils/include/irob_utils/utils.hpp", "max_issues_repo_name": "BenGab/irob-saf", "max_issues_repo_head_hexsha": "3a0fee98239bd935aa99c9d9526eb9b4cfc8963c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "irob_utils/include/irob_utils/utils.hpp", "max_forks_repo_name": "BenGab/irob-saf", "max_forks_repo_head_hexsha": "3a0fee98239bd935aa99c9d9526eb9b4cfc8963c", "max_forks_repo_licenses": ["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.3932135729, "max_line_length": 83, "alphanum_fraction": 0.6502362064, "num_tokens": 2910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.5220446240929401}}
{"text": "/*\n* Implementation for AD of convolution-related operations, that will typically\n* be used in a CNN. This also includes corresponding node types.\n*/\n\n#pragma once\n\n#include \"autodiff.hpp\"\n#include \"utils.hpp\"\n\n#include <vector>\n#include <memory>\n#include <iostream>\n\n#include <Eigen/Dense>\n\n// Enum for channel splitting directions in CNN\n// (declared outside for now because scoped enum declarationb seems\n// impossible)\nenum class ts::ChannelSplit : int {\n\tNOSPLIT,\n\tSPLIT_HOR,\t// Splits lines\n\tSPLIT_VERT\t// Splits columns\n};\n\n\nnamespace ts {\n\n\ttemplate <typename T>\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> convArray(\n\t\tconst Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &mat,\n\t\tconst Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &ker\n\t);\n\n\ttemplate <typename T> class ConvolutionNode;\n\ttemplate <typename T>\n\tts::Tensor<T> convolution(const ts::Tensor<T> &mat, const ts::Tensor<T> &ker);\n\n\ttemplate <typename T> class SplitNode;\n\ttemplate <typename T>\n\tstd::vector<ts::Tensor<T>> split(\n\t\tconst ts::Tensor<T> &x,\n\t\tChannelSplit channelSplit,\n\t\tunsigned nInputChannels\n\t);\n\n\ttemplate <typename T> class PoolingNode;\n\ttemplate <typename T>\n\tts::Tensor<T> maxPooling(const ts::Tensor<T> &x, std::vector<unsigned> pool);\n\n\ttemplate <typename T> class VertCatNode;\n\ttemplate <typename T>\n\tts::Tensor<T> vertCat(const std::vector<ts::Tensor<T>> &x);\n\n\ttemplate <typename T> class FlatteningNode;\n\ttemplate <typename T>\n\tts::Tensor<T> flattening(const ts::Tensor<T> &x);\n\n\ttemplate <typename T> class Im2ColNode;\n\ttemplate <typename T>\n\tts::Tensor<T> im2col(\n\t\tconst std::vector<ts::Tensor<T>> &x,\n\t\tstd::vector<unsigned> kernelDim\n\t);\n\n\ttemplate <typename T> class Col2ImNode;\n\ttemplate <typename T>\n\tstd::vector<ts::Tensor<T>> col2im(\n\t\tconst ts::Tensor<T> &x,\n\t\tstd::vector<unsigned> outputDim\n\t);\n}\n\n\n\n\t// ts::ConvolutionNode\n\ntemplate <typename T>\nclass ts::ConvolutionNode : public ts::Node<T> {\nprivate:\n\tusing ts::Node<T>::Node;\n\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> incrementGradient(\n\t\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &childDerivative,\n\t\t\tunsigned &j\n\t);\n};\n\n\n\n\t// ts::PoolingNode\n\ntemplate <typename T>\nclass ts::PoolingNode : public ts::Node<T> {\nprivate:\n\tusing ts::Node<T>::Node;\n\n\tPoolingNode(\n\t\tstd::vector<long> shape,\n\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> xVal, int xDep,\n\t\tstd::vector<unsigned> newPool\n\t);\n\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> incrementGradient(\n\t\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &childDerivative,\n\t\t\tunsigned &j\n\t);\n\n\tstd::vector<unsigned> pool = {};\n\n\tfriend ts::Tensor<T> ts::maxPooling<>(\n\t\tconst ts::Tensor<T> &x, std::vector<unsigned> pool\n\t);\n};\n\n\n\n\t// ts::SplitNode\n\ntemplate <typename T>\nclass ts::SplitNode : public ts::Node<T> {\nprivate:\n\tusing ts::Node<T>::Node;\n\n\tSplitNode(\n\t\tstd::vector<long> shape,\n\t\tint xDep,\n\t\tstd::vector<long> originalShape,\n\t\tChannelSplit newSplitDirection,\n\t\tunsigned newPosition\n\t);\n\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> incrementGradient(\n\t\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &childDerivative,\n\t\t\tunsigned &j\n\t);\n\n\tlong originalRows, originalCols;\n\tChannelSplit splitDirection;\n\tunsigned position;\n\n\tfriend std::vector<ts::Tensor<T>> ts::split<>(\n\t\tconst ts::Tensor<T> &x,\n\t\tChannelSplit channelSplit,\n\t\tunsigned nInputChannels\n\t);\n};\n\n\n\n\t// ts::VertCatNode\n\ntemplate <typename T>\nclass ts::VertCatNode : public ts::Node<T> {\nprivate:\n\tusing ts::Node<T>::Node;\n\n\t// This node can have n parents !\n\tVertCatNode(\n\t\tstd::vector<long> shape,\n\t\tstd::vector<int> newDependencies,\n\t\tstd::vector<long> newHeights\n\t);\n\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> incrementGradient(\n\t\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &childDerivative,\n\t\t\tunsigned &j\n\t);\n\n\tstd::vector<long> heights = {};\n\n\tfriend ts::Tensor<T> ts::vertCat<>(const std::vector<ts::Tensor<T>> &x);\n};\n\n\n\n\t// ts::FlatteningNode\n\ntemplate <typename T>\nclass ts::FlatteningNode : public ts::Node<T> {\nprivate:\n\tusing ts::Node<T>::Node;\n\n\tFlatteningNode(\n\t\tstd::vector<long> shape,\n\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> xVal, int xDep,\n\t\tstd::vector<long> newSize\n\t);\n\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> incrementGradient(\n\t\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &childDerivative,\n\t\t\tunsigned &j\n\t);\n\n\tstd::vector<long> size = {};\n\n\tfriend ts::Tensor<T> ts::flattening<>(const ts::Tensor<T> &x);\n};\n\n\n\n\t// ts::Im2ColNode\n\ntemplate <typename T>\nclass ts::Im2ColNode : public ts::Node<T> {\nprivate:\n\tusing ts::Node<T>::Node;\n\n\t// This node can have n parents !\n\tIm2ColNode(\n\t\tstd::vector<long> shape,\n\t\tstd::vector<int> newDependencies,\n\t\tstd::vector<long> newKernelDim,\n\t\tstd::vector<long> newMatrixDim,\n\t\tunsigned newNChannels\n\t);\n\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> incrementGradient(\n\t\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &childDerivative,\n\t\t\tunsigned &j\n\t);\n\n\tstd::vector<long> kernelDim = {};\n\tstd::vector<long> matrixDim = {};\t// Size of one channel\n\tunsigned nChannels;\t// Input nChannels\n\n\tfriend ts::Tensor<T> ts::im2col<>(\n\t\tconst std::vector<ts::Tensor<T>> &x,\n\t\tstd::vector<unsigned> kernelDim\n\t);\n};\n\n\n\n\t// ts::Col2ImNode\n\ntemplate <typename T>\nclass ts::Col2ImNode : public ts::Node<T> {\nprivate:\n\tusing ts::Node<T>::Node;\n\n\t// This node can have n parents !\n\tCol2ImNode(\n\t\tstd::vector<long> shape,\n\t\tint xDep,\n\t\tunsigned newPosition,\n\t\tlong newNChannels\n\t);\n\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> incrementGradient(\n\t\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &childDerivative,\n\t\t\tunsigned &j\n\t);\n\n\tunsigned position;\n\tunsigned nChannels;\n\n\tfriend std::vector<ts::Tensor<T>> ts::col2im<>(\n\t\tconst ts::Tensor<T> &x,\n\t\tstd::vector<unsigned> outputDim\n\t) ;\n};\n", "meta": {"hexsha": "d016529a1843423e35d412f4ba06b840f0676d72", "size": 5713, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/convolution.hpp", "max_stars_repo_name": "PurplePachyderm/tensorslow", "max_stars_repo_head_hexsha": "3ccd881700b301b81154a5b1a787ec91461a6436", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-10-19T08:57:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-26T17:50:50.000Z", "max_issues_repo_path": "include/convolution.hpp", "max_issues_repo_name": "PurplePachyderm/tensorslow", "max_issues_repo_head_hexsha": "3ccd881700b301b81154a5b1a787ec91461a6436", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-10-23T14:50:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T12:28:11.000Z", "max_forks_repo_path": "include/convolution.hpp", "max_forks_repo_name": "PurplePachyderm/tensorslow", "max_forks_repo_head_hexsha": "3ccd881700b301b81154a5b1a787ec91461a6436", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-26T17:49:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T00:51:09.000Z", "avg_line_length": 21.7224334601, "max_line_length": 79, "alphanum_fraction": 0.6942061964, "num_tokens": 1606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5220446187701513}}
{"text": "// [[Rcpp::depends(BH)]]\n\n#include <cmath>\n#include <boost/math/special_functions/beta.hpp>\n\n#include \"include/lm.h\"\n\ndouble pval_t(double t, double df) {\n    if (df > 50) {\n        return 1 + boost::math::erf(-std::abs(t) / sqrt(2));\n    }\n    double x = df / (t * t + df);\n    return boost::math::ibeta(df / 2, 0.5, x);\n}\n\nlm::lm(unsigned _n) :lt(_n * 2), b(_n), v(_n), vM(_n), R(4), Q(_n * 2), n(_n) {}\n\ndouble lm::norm(const std::vector<double>& v) {\n    double value = 0.0;\n    for (double x: v) {\n        value += x * x;\n    }\n    return std::sqrt(value);\n}\n\nvoid lm::set(int i, double x, double y, double w, bool bias) {\n    double sq = std::sqrt(w);\n    if (bias) {\n        lt[i] = sq;\n    }\n    lt[i + n] = x * sq;\n    b[i] = y * sq;\n}\n\nvoid lm::solve() {\n    preprocess(v, lt, 0, n, 0);\n\n    // Q_1 * A\n    std::vector<double> RM(n);\n    double cross = 0.0;\n    for (int j = 0; j < n; j++) {\n        cross += v[j] * lt[n + j];\n    }\n    for (int i = 1; i < n; i++) {\n        RM[i] = lt[n + i] - 2 * v[i] * cross;\n    }\n\n    vM[0] = 0;\n    preprocess(vM, RM, 0, n, 1);\n    compute_Q();\n    compute_R();\n    solve_system();\n}\n\nvoid lm::preprocess(std::vector<double>& ret, const std::vector<double>& lt, int l, int r, int s) {\n    int n = r - l;\n    for (int i = s; i < n; i++) {\n        ret[i] = lt[i + l];\n    }\n    ret[s] -= norm(ret);\n    double l2 = norm(ret);\n    if (l2 > 0) {\n        for (int i = 0; i < n; i++) {\n            ret[i] /= l2;\n        }\n    }\n}\n\nvoid lm::compute_Q() {\n    double cross = 0.0;\n    for (int k = 0; k < n; k++) {\n        cross += v[k] * vM[k];\n    }\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < 2; j++) {\n            double sum = 0;\n            sum += 4 * v[i] * vM[j] * cross;\n            Q[i + j * n] = sum - 2 * (v[i] * v[j] + vM[i] * vM[j]);\n        }\n    }\n    Q[0] += 1;\n    Q[n + 1] += 1;\n}\n\nvoid lm::compute_R() {\n    for (int i = 0; i < 2; i++) {\n        for (int j = 0; j < 2; j++) {\n            if (i == 1 && j == 0) {\n                continue;\n            }\n            double sum = 0;\n            for (int k = 0; k < n; k++) {\n                sum += Q[k + i * n] * lt[k + j * n];\n            }\n            R[i + j * 2] = sum;\n        }\n    }\n    R[1] = 0;\n\n}\n\nvoid lm::solve_system() {\n    double b1 = 0.0;\n    double b2 = 0.0;\n    for (int i = 0; i < n; i++) {\n        b1 += Q[i] * b[i];\n        b2 += Q[i + n] * b[i];\n    }\n    k = b2 / R[3];\n    bias = (b1 - k * R[2]) / R[0];\n}\n\ndouble lm::compute_t(double df) {\n    double a = R[0] * R[0];\n    double b = R[0] * R[2];\n    double c = R[2] * R[2] + R[3] * R[3];\n    double inv =  a / (a * c - b * b);\n    return k / std::sqrt((compute_rss() / df) * inv);\n\n}\n\ndouble lm::compute_rss() {\n    double rss = 0;\n    for (int i = 0; i < n; i++) {\n        rss += pow(bias * lt[i] + k * lt[n + i] - b[i], 2.0);\n    }\n    return rss;\n}\n\ndouble lm::get_lambda() {\n    return k;\n}\n\ndouble lm::get_bias() {\n    return bias;\n}\n\n", "meta": {"hexsha": "d9f7e35e117da9f795b7164569028e678c03cdc8", "size": 2940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lm.cpp", "max_stars_repo_name": "alexloboda/SVDFunctions", "max_stars_repo_head_hexsha": "ed0e2d44f3c413f1777ad80a9b864efa59abd22a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-11-15T09:52:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-07T14:46:32.000Z", "max_issues_repo_path": "src/lm.cpp", "max_issues_repo_name": "alexloboda/SVDFunctions", "max_issues_repo_head_hexsha": "ed0e2d44f3c413f1777ad80a9b864efa59abd22a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-05T18:57:15.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T18:57:16.000Z", "max_forks_repo_path": "src/lm.cpp", "max_forks_repo_name": "alexloboda/SVDFunctions", "max_forks_repo_head_hexsha": "ed0e2d44f3c413f1777ad80a9b864efa59abd22a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-01T19:22:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-01T19:22:34.000Z", "avg_line_length": 21.3043478261, "max_line_length": 99, "alphanum_fraction": 0.4108843537, "num_tokens": 1107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.52204461169844}}
{"text": "// Petter Strandmark 2012.\n\n#include <algorithm>\n#include <cstdio>\n#include <iostream>\n#include <limits>\n#include <stdexcept>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include <spii/spii.h>\n#include <spii/solver.h>\n\nnamespace spii {\n\n// Holds a point in the Nelder-Mead simplex.\n// Equipped with a comparison operator for sorting.\nstruct SimplexPoint\n{\n\tEigen::VectorXd x;\n\tdouble value;\n\n\tbool operator<(const SimplexPoint& rhs) const\n\t{\n\t\treturn this->value < rhs.value;\n\t}\n};\n\n// If required for debugging.\nstd::ostream& operator<<(std::ostream& out, const SimplexPoint& point)\n{\n\tout << point.x.transpose() << \" : \" << point.value;\n\treturn out;\n}\n\n}  // namespace spii\n\nnamespace std\n{\n\ttemplate<>\n\tvoid swap<spii::SimplexPoint>(spii::SimplexPoint& lhs, spii::SimplexPoint& rhs)\n\t{\n\t\tlhs.x.swap(rhs.x);\n\t\tswap(lhs.value, rhs.value);\n\t}\n}\n\nnamespace spii {\n\nvoid initialize_simplex(const Function& function,\n                        const Eigen::VectorXd& x0,\n                        std::vector<SimplexPoint>* simplex)\n{\n\tsize_t n = function.get_number_of_scalars();\n\tEigen::VectorXd absx0 = x0;\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tabsx0[i] = std::abs(x0[i]);\n\t}\n\tdouble scale = std::max(absx0.maxCoeff(), 1.0);\n\tconst double nd = static_cast<double>(n);\n\tdouble alpha1 = scale / (nd * std::sqrt(2.0)) * (std::sqrt(nd+1)- 1 + nd);\n\tdouble alpha2 = scale / (nd * std::sqrt(2.0)) * (std::sqrt(nd+1) - 1);\n\tEigen::VectorXd alpha2_vec(x0.size());\n\talpha2_vec.setConstant(alpha2);\n\n\tsimplex->at(0).x = x0;\n\tfor (size_t i = 1; i < n + 1; ++i) {\n\t\tsimplex->at(i).x  = x0 + alpha2_vec;\n\t\tsimplex->at(i).x[i-1] = x0[i-1] + alpha1;\n\t}\n\n\tfor (size_t i = 0; i < n + 1; ++i) {\n\t\tsimplex->at(i).value = function.evaluate(simplex->at(i).x);\n\t}\n\n\tstd::sort(simplex->begin(), simplex->end());\n}\n\nvoid NelderMeadSolver::solve(const Function& function,\n                             SolverResults* results) const\n{\n\tdouble global_start_time = wall_time();\n\n\t// Dimension of problem.\n\tsize_t n = function.get_number_of_scalars();\n\n\tif (n == 0) {\n\t\tresults->exit_condition = SolverResults::FUNCTION_TOLERANCE;\n\t\treturn;\n\t}\n\n\t// The Nelder-Mead simplex.\n\tstd::vector<SimplexPoint> simplex(n + 1);\n\n\t// Copy the user state to the current point.\n\tEigen::VectorXd x;\n\tfunction.copy_user_to_global(&x);\n\n\tinitialize_simplex(function, x, &simplex);\n\n\tSimplexPoint mean_point;\n\tSimplexPoint reflection_point;\n\tSimplexPoint expansion_point;\n\tmean_point.x.resize(n);\n\treflection_point.x.resize(n);\n\texpansion_point.x.resize(n);\n\n\tdouble fmin  = std::numeric_limits<double>::quiet_NaN();\n\tdouble fmax  = std::numeric_limits<double>::quiet_NaN();\n\tdouble fval  = std::numeric_limits<double>::quiet_NaN();\n\tdouble area  = std::numeric_limits<double>::quiet_NaN();\n\tdouble area0 = std::numeric_limits<double>::quiet_NaN();\n\tdouble length  = std::numeric_limits<double>::quiet_NaN();\n\tdouble length0 = std::numeric_limits<double>::quiet_NaN();\n\n\tEigen::MatrixXd area_mat(n, n);\n\n\t//\n\t// START MAIN ITERATION\n\t//\n\tresults->startup_time   += wall_time() - global_start_time;\n\tresults->exit_condition = SolverResults::INTERNAL_ERROR;\n\tint iter = 0;\n\tint n_shrink_in_a_row = 0;\n\twhile (true) {\n\n\t\t//\n\t\t// In each iteration, the worst point in the simplex\n\t\t// is replaced with a new one.\n\t\t//\n\t\tdouble start_time = wall_time();\n\n\t\tmean_point.x.setZero();\n\t\tfval = 0;\n\t\t// Compute the mean of the best n points.\n\t\tfor (size_t i = 0; i < n; ++i) {\n\t\t\tmean_point.x += simplex[i].x;\n\t\t\tfval         += simplex[i].value;\n\t\t}\n\t\tfval         /= double(n);\n\t\tmean_point.x /= double(n);\n\t\tfmin = simplex[0].value;\n\t\tfmax = simplex[n].value;\n\n\t\tconst char* iteration_type = \"n/a\";\n\n\t\t// Compute the reflexion point and evaluate it.\n\t\treflection_point.x = 2.0 * mean_point.x - simplex[n].x;\n\t\treflection_point.value = function.evaluate(reflection_point.x);\n\n\t\tbool is_shrink = false;\n\t\tif (simplex[0].value <= reflection_point.value &&\n\t\t\treflection_point.value < simplex[n - 1].value) {\n\t\t\t// Reflected point is neither better nor worst in the\n\t\t\t// new simplex.\n\t\t\tstd::swap(reflection_point, simplex[n]);\n\t\t\titeration_type = \"Reflect 1\";\n\t\t}\n\t\telse if (reflection_point.value < simplex[0].value) {\n\t\t\t// Reflected point is better than the current best; try\n\t\t\t// to go farther along this direction.\n\n\t\t\t// Compute expansion point.\n\t\t\texpansion_point.x = 3.0 * mean_point.x - 2.0 * simplex[n].x;\n\t\t\texpansion_point.value = function.evaluate(expansion_point.x);\n\n\t\t\tif (expansion_point.value < reflection_point.value) {\n\t\t\t\tstd::swap(expansion_point, simplex[n]);\n\t\t\t\titeration_type = \"Expansion\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstd::swap(reflection_point, simplex[n]);\n\t\t\t\titeration_type = \"Reflect 2\";\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// Reflected point is still worse than x[n]; contract.\n\t\t\tbool success = false;\n\n\t\t\tif (simplex[n - 1].value <= reflection_point.value &&\n\t\t\t    reflection_point.value < simplex[n].value) {\n\t\t\t\t// Try to perform \"outside\" contraction.\n\t\t\t\texpansion_point.x = 1.5 * mean_point.x - 0.5 * simplex[n].x;\n\t\t\t\texpansion_point.value = function.evaluate(expansion_point.x);\n\n\t\t\t\tif (expansion_point.value <= reflection_point.value) {\n\t\t\t\t\tstd::swap(expansion_point, simplex[n]);\n\t\t\t\t\tsuccess = true;\n\t\t\t\t\titeration_type = \"Outside contraction\";\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Try to perform \"inside\" contraction.\n\t\t\t\texpansion_point.x = 0.5 * mean_point.x + 0.5 * simplex[n].x;\n\t\t\t\texpansion_point.value = function.evaluate(expansion_point.x);\n\n\t\t\t\tif (expansion_point.value < simplex[n].value) {\n\t\t\t\t\tstd::swap(expansion_point, simplex[n]);\n\t\t\t\t\tsuccess = true;\n\t\t\t\t\titeration_type = \"Inside contraction\";\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (! success) {\n\t\t\t\t// Neither outside nor inside contraction was acceptable;\n\t\t\t\t// shrink the simplex toward the best point.\n\t\t\t\tfor (size_t i = 1; i < n + 1; ++i) {\n\t\t\t\t\tsimplex[i].x = 0.5 * (simplex[0].x + simplex[i].x);\n\t\t\t\t\tsimplex[i].value = function.evaluate(simplex[i].x);\n\t\t\t\t\titeration_type = \"Shrink\";\n\t\t\t\t\tis_shrink = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstd::sort(simplex.begin(), simplex.end());\n\n\t\tresults->function_evaluation_time += wall_time() - start_time;\n\n\t\t//\n\t\t// Test stopping criteriea\n\t\t//\n\t\tstart_time = wall_time();\n\t\t\n\t\t// Compute the area of the simplex.\n\t\tlength = 0;\n\t\tfor (size_t i = 0; i < n; ++i) {\n\t\t\tarea_mat.col(i) = simplex[i].x - simplex[n].x;\n\t\t\tlength = std::max(length, area_mat.col(i).norm());\n\t\t}\n\t\tarea = std::abs(area_mat.determinant());\n\t\tif (iter == 0) {\n\t\t\tarea0 = area;\n\t\t\tlength0 = length;\n\t\t}\n\n\t\tif (area / area0 < this->area_tolerance) {\n\t\t\tresults->exit_condition = SolverResults::GRADIENT_TOLERANCE;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (area == 0) {\n\t\t\tresults->exit_condition = SolverResults::GRADIENT_TOLERANCE;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (length / length0 < this->length_tolerance) {\n\t\t\tresults->exit_condition = SolverResults::GRADIENT_TOLERANCE;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (is_shrink) {\n\t\t\tn_shrink_in_a_row++;\n\t\t}\n\t\telse {\n\t\t\tn_shrink_in_a_row = 0;\n\t\t}\n\t\tif (n_shrink_in_a_row > 50) {\n\t\t\tresults->exit_condition = SolverResults::GRADIENT_TOLERANCE;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (iter >= this->maximum_iterations) {\n\t\t\tresults->exit_condition = SolverResults::NO_CONVERGENCE;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (this->callback_function) {\n\t\t\tCallbackInformation information;\n\t\t\tinformation.objective_value = simplex[0].value;\n\t\t\tinformation.x = &simplex[0].x;\n\n\t\t\tif (!callback_function(information)) {\n\t\t\t\tresults->exit_condition = SolverResults::USER_ABORT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tresults->stopping_criteria_time += wall_time() - start_time;\n\n\t\t//\n\t\t// Restarting\n\t\t//\n\t\t//if (area / area1 < 1e-10) {\n\t\t//\tx = simplex[0].x;\n\t\t//\tinitialize_simplex(function, x, &simplex);\n\t\t//\tarea1 = area;\n\t\t//\tif (this->log_function) {\n\t\t//\t\tthis->log_function(\"Restarted.\");\n\t\t//\t}\n\t\t//}\n\n\t\t//\n\t\t// Log the results of this iteration.\n\t\t//\n\t\tstart_time = wall_time();\n\n\t\tint log_interval = 1;\n\t\tif (iter > 30) {\n\t\t\tlog_interval = 10;\n\t\t}\n\t\tif (iter > 200) {\n\t\t\tlog_interval = 100;\n\t\t}\n\t\tif (iter > 2000) {\n\t\t\tlog_interval = 1000;\n\t\t}\n\t\tif (this->log_function && iter % log_interval == 0) {\n\t\t\tchar str[1024];\n\t\t\t\tif (iter == 0) {\n\t\t\t\t\tthis->log_function(\"Itr     min(f)     avg(f)     max(f)    area    length   type\");\n\t\t\t\t}\n\t\t\t\tstd::sprintf(str, \"%6d %+.3e %+.3e %+.3e %.3e %.3e %s\",\n\t\t\t\t\titer, fmin, fval, fmax, area, length, iteration_type);\n\t\t\tthis->log_function(str);\n\t\t}\n\t\tresults->log_time += wall_time() - start_time;\n\n\t\titer++;\n\t}\n\n\t// Return the best point as solution.\n\tfunction.copy_global_to_user(simplex[0].x);\n\tresults->total_time += wall_time() - global_start_time;\n\n\tif (this->log_function) {\n\t\tchar str[1024];\n\t\tstd::sprintf(str, \" end   %+.3e                       %.3e %.3e\", fval, area, length);\n\t\tthis->log_function(str);\n\t}\n}\n\n}  // namespace spii\n", "meta": {"hexsha": "bd449df6c7be733468ddb1e62138b784489ef5b6", "size": 8634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/solver_nelder_mead.cpp", "max_stars_repo_name": "PetterS/spii", "max_stars_repo_head_hexsha": "98c5847223d7c3febea5a1aac6f4978dfef207ec", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-03-03T16:21:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T08:02:12.000Z", "max_issues_repo_path": "source/solver_nelder_mead.cpp", "max_issues_repo_name": "nashdingsheng/spii", "max_issues_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-07-16T14:41:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-09T19:27:22.000Z", "max_forks_repo_path": "source/solver_nelder_mead.cpp", "max_forks_repo_name": "nashdingsheng/spii", "max_forks_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-09-21T23:09:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T20:20:30.000Z", "avg_line_length": 25.8502994012, "max_line_length": 89, "alphanum_fraction": 0.645355571, "num_tokens": 2553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5220446019273243}}
{"text": "/**\n * @file particle.hpp\n * @author Vahid Bastani\n *\n * Generic particle filter.\n */\n#ifndef SSMPACK_FILTER_PARTICLE_HPP\n#define SSMPACK_FILTER_PARTICLE_HPP\n\n#include \"ssmkit/distribution/conditional.hpp\"\n#include \"ssmkit/filter/recursive_bayesian_base.hpp\"\n#include \"ssmkit/process/hierarchical.hpp\"\n#include \"ssmkit/process/markov.hpp\"\n#include \"ssmkit/process/memoryless.hpp\"\n#include <armadillo>\n\n#include <tuple>\n\nnamespace ssmkit {\nnamespace filter {\n\nusing process::Hierarchical;\nusing process::Markov;\nusing process::Memoryless;\nusing distribution::Conditional;\n\n/** Particle Filter.\n */\ntemplate <class Process, class Resampler>\nclass Particle : public RecursiveBayesianBase<Particle<Process, Resampler>> {\n public:\n  /** Type of the state posterior\n   *\n   * \\f$ \\{\\mathbf{x}^{(i)}_t,\\omega^{(i)}\\}_{i=1}^{M}\\f$\n   */\n  using CompeleteState = std::tuple<arma::mat, arma::vec>;\n\n private:\n  //! Particle weights \\f$ \\{\\omega^{(i)}\\}_{i=1}^{M}\\f$.\n  arma::vec w_;\n  //! State particles \\f$ \\{\\mathbf{x}^{(i)}_t\\}_{i=1}^{M}\\f$.\n  arma::mat state_par_;\n  //! The process model\n  Process process_;\n  //! Resampling algorithm\n  Resampler resampler_;\n  //! Number of particles \\f$M\\f$.\n  unsigned long num_;\n\n private:\n  //! Normalizes the sum of weights to one\n  void normalizeWeights(void) { w_ = w_ / arma::sum(w_); }\n\n public:\n  /** Constructor\n   *\n   * returns a Particle filter object.\n   *\n   * @param process The process model object that the PF is defined for\n   * @param resampler The resampling algorithm\n   * @param particles_num Number of particles \\f$M\\f$\n   */\n  Particle(Process process, Resampler resampler, unsigned long particles_num)\n      : process_{process}, resampler_{resampler}, num_{particles_num} {\n    // initialized w_ and state_par_\n    w_.resize(num_);\n    // take one sample to find out dimension\n    auto tmp = process_.template getProcess<0>().getInitialPDF().random();\n    state_par_.resize(tmp.size(), num_);\n  }\n  /** Prediction\n   *\n   * Performs prediction step.\n   * \\f{equation}{\\mathbf{x}^{(i)}_t \\sim p(\\mathbf{x}_t| \\tilde{\\mathbf{x}}^{(i)}_{t-1}, y^d_1, \\cdots, y^d_{N_d})\n   * \\quad \\text{for} \\quad i=1,\\cdots,M\\f}\n   *\n   * @param args... Control variables \\f$y^d_1, \\cdots, y^d_{N_d}\\f$ of the dynamic process, if any.\n   */\n  template <class... Args>\n  void predict(const Args &... args) {\n    state_par_.each_col([this, &args...](arma::vec &v, const Args &... args) {\n      v = process_.template getProcess<0>().getCPDF().random(v, args...);\n    });\n  }\n  /** Correction\n   *\n   * Performs correction step.\n   *\n   * \\f{equation}{ \\omega^{(i)} = \\tilde{\\omega}^{(i)} p(\\mathbf{z}_t| \\mathbf{x}^{(i)}_t, y^m_1, \\cdots, y^m_{N_m}) \\f}\n   * \\f{equation}{\\{\\mathbf{x}^{(i)}_t,\\omega^{(i)}\\}_{i=1}^{M}\n   * \\overset{\\mbox{resample}}{\\longrightarrow}\n   * \\{\\tilde{\\mathbf{x}}^{(i)}_t,\\tilde{\\omega}^{(i)}\\}_{i=1}^{M}\\f}\n   *\n   * @param measurement Measurement vector \\f$\\mathbf{z}_t\\f$.\n   * @param args... Control variables \\f$y^m_1, \\cdots, y^m_{N_m}\\f$ of the measurement process, if any.\n   * @return Estimated state \\f$\\{\\tilde{\\mathbf{x}}^{(i)}_t,\\tilde{\\omega}^{(i)}\\}_{i=1}^{M}\\f$\n   */\n  template <class Measurement, class... TArgs>\n  CompeleteState correct(const Measurement &measurement,\n                         const TArgs &... args) {\n    unsigned long cnt = 0;\n    w_.for_each([this, &cnt, &measurement, &args...](double &e) {\n      e *= process_.template getProcess<1>().getCPDF().likelihood(\n          measurement, state_par_.col(cnt++), args...);\n    });\n\n    normalizeWeights();\n\n    resampler_(state_par_, w_);\n\n    return std::make_tuple(state_par_, w_);\n  }\n  /** Initialization\n   *\n   * @return Estimated state \\f$\\{\\tilde{\\mathbf{x}}^{(i)}_0,\\tilde{\\omega}^{(i)}\\}_{i=1}^{M}\\f$\n   */\n  CompeleteState initialize() {\n    state_par_.each_col([this](arma::vec &v) {\n      v = process_.template getProcess<0>().getInitialPDF().random();\n    });\n\n    unsigned long cnt = 0;\n    w_.for_each([this, &cnt](double &e) {\n      e = process_.template getProcess<0>().getInitialPDF().likelihood(\n          state_par_.col(cnt++));\n    });\n\n    normalizeWeights();\n\n    return std::make_tuple(state_par_, w_);\n  }\n  //! @return Estimated state \\f$\\{\\tilde{\\omega}^{(i)}\\}_{i=1}^{M}\\f$\n  const arma::vec &getWeights(void) const { return w_; }\n  //! @return Estimated state \\f$\\{\\tilde{\\mathbf{x}}^{(i)}_t\\}_{i=1}^{M}\\f$\n  const arma::mat &getStateParticles(void) const { return state_par_; }\n};\n\n/**\n */\ntemplate <class StatePDF, class StateParamMap, class InitialPDF,\n          class MeasurementPDF, class MeasurementParamMap, class Resampler>\nauto makeParticle(\n    Hierarchical<Markov<StatePDF, StateParamMap, InitialPDF>,\n                 Memoryless<MeasurementPDF, MeasurementParamMap>> process,\n    Resampler resampler, unsigned long particle_num) {\n  return Particle<Hierarchical<Markov<StatePDF, StateParamMap, InitialPDF>,\n                               Memoryless<MeasurementPDF, MeasurementParamMap>>,\n                  Resampler>(process, resampler, particle_num);\n}\n\n} // namespace filter\n} // namespace ssmkit\n\n#endif // SSMPACK_FILTER_PARTICLE_HPP\n", "meta": {"hexsha": "1a380898d2d11981a92fc8f09b5ffee3b5ade87e", "size": 5124, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ssmkit/filter/particle.hpp", "max_stars_repo_name": "vahid-bastani/ssmpack", "max_stars_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-07-08T09:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-10T06:46:55.000Z", "max_issues_repo_path": "src/ssmkit/filter/particle.hpp", "max_issues_repo_name": "vahidbas/ssmkit", "max_issues_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ssmkit/filter/particle.hpp", "max_forks_repo_name": "vahidbas/ssmkit", "max_forks_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T17:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T17:46:08.000Z", "avg_line_length": 33.0580645161, "max_line_length": 120, "alphanum_fraction": 0.6428571429, "num_tokens": 1528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.5220446019273243}}
{"text": "#include <nistpp/math_helpers.h>\n\n#include <boost/math/special_functions/gamma.hpp>\n\nnamespace nistpp\n{\n\ndouble igamc(double a, double z)\n{\n    return  boost::math::gamma_q(a, z);\n}\n\n} // namespace nistpp", "meta": {"hexsha": "ba38a7b719c296ee12e88d73c6e8fc8dae12effb", "size": 204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nistpp/src/math_helpers.cpp", "max_stars_repo_name": "Omnissi/NISTPP", "max_stars_repo_head_hexsha": "9f74a8607ae8a25df094bb9d3397b85083166b06", "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": "nistpp/src/math_helpers.cpp", "max_issues_repo_name": "Omnissi/NISTPP", "max_issues_repo_head_hexsha": "9f74a8607ae8a25df094bb9d3397b85083166b06", "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": "nistpp/src/math_helpers.cpp", "max_forks_repo_name": "Omnissi/NISTPP", "max_forks_repo_head_hexsha": "9f74a8607ae8a25df094bb9d3397b85083166b06", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.6923076923, "max_line_length": 49, "alphanum_fraction": 0.7156862745, "num_tokens": 56, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.5219940021537885}}
{"text": "/*\nLICENSE: see isogeometric_application/LICENSE.txt\n*/\n\n//\n//   Project Name:        Kratos\n//   Last modified by:    $Author: hbui $\n//   Date:                $Date: Nov 11, 2017 $\n//   Revision:            $Revision: 1.1 $\n//\n//\n\n\n// System includes\n#include <string>\n\n// External includes\n#include <boost/foreach.hpp>\n#include <boost/python.hpp>\n#include <boost/python/stl_iterator.hpp>\n#include <boost/python/operators.hpp>\n\n// Project includes\n#include \"includes/define.h\"\n#include \"custom_utilities/control_point.h\"\n#include \"custom_utilities/control_grid.h\"\n#include \"custom_utilities/fespace.h\"\n#include \"custom_utilities/patch_interface.h\"\n#include \"custom_utilities/isogeometric_utility.h\"\n#include \"custom_utilities/nurbs/domain_manager.h\"\n#include \"custom_utilities/nurbs/domain_manager_2d.h\"\n#include \"custom_utilities/nurbs/structured_control_grid.h\"\n#include \"custom_utilities/nurbs/bsplines_fespace.h\"\n#include \"custom_utilities/nurbs/bsplines_fespace_library.h\"\n#include \"custom_utilities/nurbs/bending_strip_nurbs_patch.h\"\n#include \"custom_utilities/nurbs/nurbs_test_utils.h\"\n#include \"custom_python/iga_define_python.h\"\n#include \"custom_python/add_nurbs_to_python.h\"\n\n\nnamespace Kratos\n{\n\nnamespace Python\n{\n\nusing namespace boost::python;\n\n////////////////////////////////////////\n\ntemplate<int TDim, int TWhichDim>\nboost::python::list BSplinesFESpace_GetKnotVector(BSplinesFESpace<TDim>& rDummy)\n{\n    boost::python::list knot_list;\n\n    if (TWhichDim < TDim)\n    {\n        const typename BSplinesFESpace<TDim>::knot_container_t& knot_vector = rDummy.KnotVector(TWhichDim);\n\n        for (std::size_t i = 0; i < knot_vector.size(); ++i)\n            knot_list.append(knot_vector[i]);\n    }\n\n    return knot_list;\n}\n\ntemplate<int TDim, int TWhichDim>\nvoid BSplinesFESpace_SetKnotVector(BSplinesFESpace<TDim>& rDummy, boost::python::list knot_list)\n{\n    if (TWhichDim < TDim)\n    {\n        std::vector<double> knot_vec;\n        typedef boost::python::stl_input_iterator<double> iterator_value_type;\n        BOOST_FOREACH(const iterator_value_type::value_type& v, std::make_pair(iterator_value_type(knot_list), iterator_value_type() ) )\n        {\n            knot_vec.push_back(v);\n        }\n\n        rDummy.SetKnotVector(TWhichDim, knot_vec);\n    }\n}\n\n////////////////////////////////////////\n\nBSplinesFESpace<1>::Pointer BSplinesFESpaceLibrary_CreatePrimitiveFESpace1(BSplinesFESpaceLibrary& rDummy, const std::size_t& order_u)\n{\n    std::vector<std::size_t> orders(1);\n    orders[0] = order_u;\n    return rDummy.CreatePrimitiveFESpace<1>(orders);\n}\n\nBSplinesFESpace<2>::Pointer BSplinesFESpaceLibrary_CreatePrimitiveFESpace2(BSplinesFESpaceLibrary& rDummy, const std::size_t& order_u, const std::size_t& order_v)\n{\n    std::vector<std::size_t> orders(2);\n    orders[0] = order_u;\n    orders[1] = order_v;\n    return rDummy.CreatePrimitiveFESpace<2>(orders);\n}\n\nBSplinesFESpace<3>::Pointer BSplinesFESpaceLibrary_CreatePrimitiveFESpace3(BSplinesFESpaceLibrary& rDummy, const std::size_t& order_u, const std::size_t& order_v, const std::size_t& order_w)\n{\n    std::vector<std::size_t> orders(3);\n    orders[0] = order_u;\n    orders[1] = order_v;\n    orders[2] = order_w;\n    return rDummy.CreatePrimitiveFESpace<3>(orders);\n}\n\nBSplinesFESpace<1>::Pointer BSplinesFESpaceLibrary_CreateUniformFESpace1(BSplinesFESpaceLibrary& rDummy,\n    const std::size_t& number_u, const std::size_t& order_u)\n{\n    std::vector<std::size_t> numbers(1);\n    numbers[0] = number_u;\n    std::vector<std::size_t> orders(1);\n    orders[0] = order_u;\n    return rDummy.CreateUniformFESpace<1>(numbers, orders);\n}\n\nBSplinesFESpace<2>::Pointer BSplinesFESpaceLibrary_CreateUniformFESpace2(BSplinesFESpaceLibrary& rDummy,\n    const std::size_t& number_u, const std::size_t& order_u,\n    const std::size_t& number_v, const std::size_t& order_v)\n{\n    std::vector<std::size_t> numbers(2);\n    numbers[0] = number_u;\n    numbers[1] = number_v;\n    std::vector<std::size_t> orders(2);\n    orders[0] = order_u;\n    orders[1] = order_v;\n    return rDummy.CreateUniformFESpace<2>(numbers, orders);\n}\n\nBSplinesFESpace<3>::Pointer BSplinesFESpaceLibrary_CreateUniformFESpace3(BSplinesFESpaceLibrary& rDummy,\n    const std::size_t& number_u, const std::size_t& order_u,\n    const std::size_t& number_v, const std::size_t& order_v,\n    const std::size_t& number_w, const std::size_t& order_w)\n{\n    std::vector<std::size_t> numbers(3);\n    numbers[0] = number_u;\n    numbers[1] = number_v;\n    numbers[2] = number_w;\n    std::vector<std::size_t> orders(3);\n    orders[0] = order_u;\n    orders[1] = order_v;\n    orders[2] = order_w;\n    return rDummy.CreateUniformFESpace<3>(numbers, orders);\n}\n\n//////////////////////////////////////////////////\n\nvoid DomainManager2D_AddCell(DomainManager2D& rDummy, const double& x1, const double& x2, const double& y1, const double& y2)\n{\n    std::vector<double> box(4);\n    box[0] = x1;\n    box[1] = x2;\n    box[2] = y1;\n    box[3] = y2;\n\n    rDummy.AddCell(box);\n}\n\nbool DomainManager2D_IsInside(DomainManager2D& rDummy, const double& x1, const double& x2, const double& y1, const double& y2)\n{\n    std::vector<double> box(4);\n    box[0] = x1;\n    box[1] = x2;\n    box[2] = y1;\n    box[3] = y2;\n\n    return rDummy.IsInside(box);\n}\n\n//////////////////////////////////////////////////\n\ntemplate<int TDim>\nvoid NURBSTestUtils_ProbeAndTestValuesOnPatch(NURBSTestUtils<TDim>& dummy, typename Patch<TDim>::Pointer pPatch,\n    ModelPart::ConditionsContainerType& rConditions, const int& integration_order, const double& tol)\n{\n    GeometryData::IntegrationMethod integration_method = IsogeometricUtility::GetIntegrationMethod(integration_order);\n    dummy.ProbeAndTestValuesOnPatch(pPatch, rConditions, integration_method, tol);\n}\n\n//////////////////////////////////////////////////\n\ntemplate<int TDim, typename TDataType>\nstruct StructuredControlGrid_Helper\n{\n    static boost::python::list GetValue(StructuredControlGrid<TDim, TDataType>& rDummy)\n    {\n        KRATOS_THROW_ERROR(std::logic_error, __FUNCTION__, \"not implemented\")\n    }\n\n    static void SetValue(StructuredControlGrid<TDim, TDataType>& rDummy, boost::python::list values)\n    {\n        KRATOS_THROW_ERROR(std::logic_error, __FUNCTION__, \"not implemented\")\n    }\n};\n\ntemplate<typename TDataType>\nstruct StructuredControlGrid_Helper<1, TDataType>\n{\n    static boost::python::list GetValue(StructuredControlGrid<1, TDataType>& rDummy)\n    {\n        boost::python::list output;\n\n        for (std::size_t i = 0; i < rDummy.size(); ++i)\n        {\n            boost::python::list v = ControlValue_Helper<TDataType>::GetValue(rDummy.GetValue(i));\n            output.append(v);\n        }\n\n        return output;\n    }\n\n    static void SetValue(StructuredControlGrid<1, TDataType>& rDummy, boost::python::list values)\n    {\n        KRATOS_THROW_ERROR(std::logic_error, __FUNCTION__, \"not implemented\")\n    }\n\n    static void SetValue1D(StructuredControlGrid<1, TDataType>& rDummy, const std::size_t& i, const TDataType& value)\n    {\n        rDummy.SetValue(i, value);\n    }\n\n    static TDataType GetValue1D(StructuredControlGrid<1, TDataType>& rDummy, const std::size_t& i)\n    {\n        return rDummy.GetValue(i);\n    }\n};\n\ntemplate<typename TDataType>\nstruct StructuredControlGrid_Helper<2, TDataType>\n{\n    static boost::python::list GetValue(StructuredControlGrid<2, TDataType>& rDummy)\n    {\n        boost::python::list output;\n\n        for (std::size_t j = 0; j < rDummy.Size(1); ++j)\n        {\n            boost::python::list row;\n            for (std::size_t i = 0; i < rDummy.Size(0); ++i)\n            {\n                boost::python::list v = ControlValue_Helper<TDataType>::GetValue(rDummy.GetValue(i, j));\n                row.append(v);\n            }\n            output.append(row);\n        }\n\n        return output;\n    }\n\n    static void SetValue(StructuredControlGrid<2, TDataType>& rDummy, boost::python::list values)\n    {\n        KRATOS_THROW_ERROR(std::logic_error, __FUNCTION__, \"not implemented\")\n    }\n\n    static void SetValue2D(StructuredControlGrid<2, TDataType>& rDummy, const std::size_t& i, const std::size_t& j, const TDataType& value)\n    {\n        rDummy.SetValue(i, j, value);\n    }\n\n    static TDataType GetValue2D(StructuredControlGrid<2, TDataType>& rDummy, const std::size_t& i, const std::size_t& j)\n    {\n        return rDummy.GetValue(i, j);\n    }\n};\n\ntemplate<typename TDataType>\nstruct StructuredControlGrid_Helper<3, TDataType>\n{\n    static boost::python::list GetValue(StructuredControlGrid<3, TDataType>& rDummy)\n    {\n        boost::python::list output;\n\n        for (std::size_t k = 0; k < rDummy.Size(2); ++k)\n        {\n            boost::python::list row;\n            for (std::size_t j = 0; j < rDummy.Size(1); ++j)\n            {\n                boost::python::list col;\n                for (std::size_t i = 0; i < rDummy.Size(0); ++i)\n                {\n                    boost::python::list v = ControlValue_Helper<TDataType>::GetValue(rDummy.GetValue(i, j, k));\n                    col.append(v);\n                }\n                row.append(col);\n            }\n            output.append(row);\n        }\n\n        return output;\n    }\n\n    static void SetValue(StructuredControlGrid<3, TDataType>& rDummy, boost::python::list values)\n    {\n        KRATOS_THROW_ERROR(std::logic_error, __FUNCTION__, \"not implemented\")\n    }\n\n    static void SetValue3D(StructuredControlGrid<3, TDataType>& rDummy, const std::size_t& i, const std::size_t& j, const std::size_t& k, const TDataType& value)\n    {\n        rDummy.SetValue(i, j, k, value);\n    }\n\n    static TDataType GetValue3D(StructuredControlGrid<3, TDataType>& rDummy, const std::size_t& i, const std::size_t& j, const std::size_t& k)\n    {\n        return rDummy.GetValue(i, j, k);\n    }\n};\n\nvoid IsogeometricApplication_AddStructuredControlGridsToPython()\n{\n    /////////////////////////////////////////////////////////////////////////////////////////////////\n\n    class_<BaseStructuredControlGrid<ControlPoint<double> >, BaseStructuredControlGrid<ControlPoint<double> >::Pointer, bases<ControlGrid<ControlPoint<double> > >, boost::noncopyable>\n    (\"BaseStructuredControlPointGrid\", init<>())\n    .def(self_ns::str(self))\n    ;\n\n    class_<BaseStructuredControlGrid<double>, BaseStructuredControlGrid<double>::Pointer, bases<ControlGrid<double> >, boost::noncopyable>\n    (\"BaseStructuredDoubleControlGrid\", init<>())\n    .def(self_ns::str(self))\n    ;\n\n    class_<BaseStructuredControlGrid<array_1d<double, 3> >, BaseStructuredControlGrid<array_1d<double, 3> >::Pointer, bases<ControlGrid<array_1d<double, 3> > >, boost::noncopyable>\n    (\"BaseStructuredArray1DControlGrid\", init<>())\n    .def(self_ns::str(self))\n    ;\n\n    class_<BaseStructuredControlGrid<Vector>, BaseStructuredControlGrid<Vector>::Pointer, bases<ControlGrid<Vector> >, boost::noncopyable>\n    (\"BaseStructuredVectorControlGrid\", init<>())\n    .def(self_ns::str(self))\n    ;\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////\n\n    class_<StructuredControlGrid<1, ControlPoint<double> >, StructuredControlGrid<1, ControlPoint<double> >::Pointer, bases<BaseStructuredControlGrid<ControlPoint<double> > >, boost::noncopyable>\n    (\"StructuredControlPointGrid1D\", init<const std::size_t&>())\n    .add_property(\"ControlValues\", &StructuredControlGrid_Helper<1, ControlPoint<double> >::GetValue, &StructuredControlGrid_Helper<1, ControlPoint<double> >::SetValue)\n    .def(\"SetValue\", &StructuredControlGrid_Helper<1, ControlPoint<double> >::SetValue1D)\n    .def(\"GetValue\", &StructuredControlGrid_Helper<1, ControlPoint<double> >::GetValue1D)\n    .def(self_ns::str(self))\n    ;\n\n    class_<StructuredControlGrid<1, double>, StructuredControlGrid<1, double>::Pointer, bases<BaseStructuredControlGrid<double> >, boost::noncopyable>\n    (\"StructuredDoubleControlGrid1D\", init<const std::size_t&>())\n    .add_property(\"ControlValues\", &StructuredControlGrid_Helper<1, double>::GetValue, &StructuredControlGrid_Helper<1, double>::SetValue)\n    .def(\"SetValue\", &StructuredControlGrid_Helper<1, double>::SetValue1D)\n    .def(\"GetValue\", &StructuredControlGrid_Helper<1, double>::GetValue1D)\n    .def(self_ns::str(self))\n    ;\n\n    class_<StructuredControlGrid<1, array_1d<double, 3> >, StructuredControlGrid<1, array_1d<double, 3> >::Pointer, bases<BaseStructuredControlGrid<array_1d<double, 3> > >, boost::noncopyable>\n    (\"StructuredArray1DControlGrid1D\", init<const std::size_t&>())\n    .add_property(\"ControlValues\", &StructuredControlGrid_Helper<1, array_1d<double, 3> >::GetValue, &StructuredControlGrid_Helper<1, array_1d<double, 3> >::SetValue)\n    .def(\"SetValue\", &StructuredControlGrid_Helper<1, array_1d<double, 3> >::SetValue1D)\n    .def(\"GetValue\", &StructuredControlGrid_Helper<1, array_1d<double, 3> >::GetValue1D)\n    .def(self_ns::str(self))\n    ;\n\n    class_<StructuredControlGrid<1, Vector>, StructuredControlGrid<1, Vector>::Pointer, bases<BaseStructuredControlGrid<Vector> >, boost::noncopyable>\n    (\"StructuredVectorControlGrid1D\", init<const std::size_t&>())\n    .add_property(\"ControlValues\", &StructuredControlGrid_Helper<1, Vector>::GetValue, &StructuredControlGrid_Helper<1, Vector>::SetValue)\n    .def(\"SetValue\", &StructuredControlGrid_Helper<1, Vector>::SetValue1D)\n    .def(\"GetValue\", &StructuredControlGrid_Helper<1, Vector>::GetValue1D)\n    .def(self_ns::str(self))\n    ;\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////\n\n    class_<StructuredControlGrid<2, ControlPoint<double> >, StructuredControlGrid<2, ControlPoint<double> >::Pointer, bases<BaseStructuredControlGrid<ControlPoint<double> > >, boost::noncopyable>\n    (\"StructuredControlPointGrid2D\", init<const std::size_t&, const std::size_t&>())\n    .add_property(\"ControlValues\", &StructuredControlGrid_Helper<2, ControlPoint<double> >::GetValue, &StructuredControlGrid_Helper<2, ControlPoint<double> >::SetValue)\n    .def(\"SetValue\", &StructuredControlGrid_Helper<2, ControlPoint<double> >::SetValue2D)\n    .def(\"GetValue\", &StructuredControlGrid_Helper<2, ControlPoint<double> >::GetValue2D)\n    .def(self_ns::str(self))\n    ;\n\n    class_<StructuredControlGrid<2, double>, StructuredControlGrid<2, double>::Pointer, bases<BaseStructuredControlGrid<double> >, boost::noncopyable>\n    (\"StructuredDoubleControlGrid2D\", init<const std::size_t&, const std::size_t&>())\n    .add_property(\"ControlValues\", &StructuredControlGrid_Helper<2, double>::GetValue, &StructuredControlGrid_Helper<2, double>::SetValue)\n    .def(\"SetValue\", &StructuredControlGrid_Helper<2, double>::SetValue2D)\n    .def(\"GetValue\", &StructuredControlGrid_Helper<2, double>::GetValue2D)\n    .def(self_ns::str(self))\n    ;\n\n    class_<StructuredControlGrid<2, array_1d<double, 3> >, StructuredControlGrid<2, array_1d<double, 3> >::Pointer, bases<BaseStructuredControlGrid<array_1d<double, 3> > >, boost::noncopyable>\n    (\"StructuredArray1DControlGrid2D\", init<const std::size_t&, const std::size_t&>())\n    .add_property(\"ControlValues\", &StructuredControlGrid_Helper<2, array_1d<double, 3> >::GetValue, &StructuredControlGrid_Helper<2, array_1d<double, 3> >::SetValue)\n    .def(\"SetValue\", &StructuredControlGrid_Helper<2, array_1d<double, 3> >::SetValue2D)\n    .def(\"GetValue\", &StructuredControlGrid_Helper<2, array_1d<double, 3> >::GetValue2D)\n    .def(self_ns::str(self))\n    ;\n\n    class_<StructuredControlGrid<2, Vector>, StructuredControlGrid<2, Vector>::Pointer, bases<BaseStructuredControlGrid<Vector> >, boost::noncopyable>\n    (\"StructuredVectorControlGrid2D\", init<const std::size_t&, const std::size_t&>())\n    .add_property(\"ControlValues\", &StructuredControlGrid_Helper<2, Vector>::GetValue, &StructuredControlGrid_Helper<2, Vector>::SetValue)\n    .def(\"SetValue\", &StructuredControlGrid_Helper<2, Vector>::SetValue2D)\n    .def(\"GetValue\", &StructuredControlGrid_Helper<2, Vector>::GetValue2D)\n    .def(self_ns::str(self))\n    ;\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////\n\n    class_<StructuredControlGrid<3, ControlPoint<double> >, StructuredControlGrid<3, ControlPoint<double> >::Pointer, bases<BaseStructuredControlGrid<ControlPoint<double> > >, boost::noncopyable>\n    (\"StructuredControlPointGrid3D\", init<const std::size_t&, const std::size_t&, const std::size_t&>())\n    .add_property(\"ControlValues\", &StructuredControlGrid_Helper<3, ControlPoint<double> >::GetValue, &StructuredControlGrid_Helper<3, ControlPoint<double> >::SetValue)\n    .def(\"SetValue\", &StructuredControlGrid_Helper<3, ControlPoint<double> >::SetValue3D)\n    .def(\"GetValue\", &StructuredControlGrid_Helper<3, ControlPoint<double> >::GetValue3D)\n    .def(self_ns::str(self))\n    ;\n\n    class_<StructuredControlGrid<3, double>, StructuredControlGrid<3, double>::Pointer, bases<BaseStructuredControlGrid<double> >, boost::noncopyable>\n    (\"StructuredDoubleControlGrid3D\", init<const std::size_t&, const std::size_t&, const std::size_t&>())\n    .add_property(\"ControlValues\", &StructuredControlGrid_Helper<3, double>::GetValue, &StructuredControlGrid_Helper<3, double>::SetValue)\n    .def(\"SetValue\", &StructuredControlGrid_Helper<3, double>::SetValue3D)\n    .def(\"GetValue\", &StructuredControlGrid_Helper<3, double>::GetValue3D)\n    .def(self_ns::str(self))\n    ;\n\n    class_<StructuredControlGrid<3, array_1d<double, 3> >, StructuredControlGrid<3, array_1d<double, 3> >::Pointer, bases<BaseStructuredControlGrid<array_1d<double, 3> > >, boost::noncopyable>\n    (\"StructuredArray1DControlGrid3D\", init<const std::size_t&, const std::size_t&, const std::size_t&>())\n    .add_property(\"ControlValues\", &StructuredControlGrid_Helper<1, array_1d<double, 3> >::GetValue, &StructuredControlGrid_Helper<1, array_1d<double, 3> >::SetValue)\n    .def(\"SetValue\", &StructuredControlGrid_Helper<3, array_1d<double, 3> >::SetValue3D)\n    .def(\"GetValue\", &StructuredControlGrid_Helper<3, array_1d<double, 3> >::GetValue3D)\n    .def(self_ns::str(self))\n    ;\n\n    class_<StructuredControlGrid<3, Vector>, StructuredControlGrid<3, Vector>::Pointer, bases<BaseStructuredControlGrid<Vector> >, boost::noncopyable>\n    (\"StructuredVectorControlGrid3D\", init<const std::size_t&, const std::size_t&, const std::size_t&>())\n    .add_property(\"ControlValues\", &StructuredControlGrid_Helper<3, Vector>::GetValue, &StructuredControlGrid_Helper<3, Vector>::SetValue)\n    .def(\"SetValue\", &StructuredControlGrid_Helper<3, Vector>::SetValue3D)\n    .def(\"GetValue\", &StructuredControlGrid_Helper<3, Vector>::GetValue3D)\n    .def(self_ns::str(self))\n    ;\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////\n}\n\n//////////////////////////////////////////////////\n\ntemplate<int TDim>\nvoid IsogeometricApplication_AddBSplinesFESpaceToPython()\n{\n    std::stringstream ss;\n    ss.str(std::string());\n    ss << \"BSplinesFESpace\" << TDim << \"D\";\n    class_<BSplinesFESpace<TDim>, typename BSplinesFESpace<TDim>::Pointer, bases<FESpace<TDim> >, boost::noncopyable>\n    (ss.str().c_str(), init<>())\n    .def(\"Number\", &BSplinesFESpace<TDim>::Number)\n    .add_property(\"KnotU\", BSplinesFESpace_GetKnotVector<TDim, 0>, BSplinesFESpace_SetKnotVector<TDim, 0>)\n    .add_property(\"KnotV\", BSplinesFESpace_GetKnotVector<TDim, 1>, BSplinesFESpace_SetKnotVector<TDim, 1>)\n    .add_property(\"KnotW\", BSplinesFESpace_GetKnotVector<TDim, 2>, BSplinesFESpace_SetKnotVector<TDim, 2>)\n    .def(self_ns::str(self))\n    ;\n}\n\n//////////////////////////////////////////////////\n\ntemplate<int TDim>\nvoid IsogeometricApplication_AddBendingStripNURBSToPython()\n{\n    std::stringstream ss;\n\n    ss.str(std::string());\n    ss << \"BendingStripNURBSPatch\" << TDim << \"D\";\n    class_<BendingStripNURBSPatch<TDim>, bases<PatchInterface<TDim>, Patch<TDim> > >\n    // class_<BendingStripNURBSPatch<TDim>, typename BendingStripNURBSPatch<TDim>::Pointer >\n    (ss.str().c_str(), init<const std::size_t&, const int&>())\n    .def(init<const std::size_t&, typename Patch<TDim>::Pointer, const BoundarySide&, typename Patch<TDim>::Pointer, const BoundarySide&, const int&>())\n    // .def(self_ns::str(self_ns::self))\n    .def(self_ns::str(self))\n    ;\n\n    ss.str(std::string());\n    ss << \"BendingStripNURBSPatch\" << TDim << \"DPointer\";\n    class_<typename BendingStripNURBSPatch<TDim>::Pointer>\n    (ss.str().c_str(), init<typename BendingStripNURBSPatch<TDim>::Pointer>())\n    .def(\"GetReference\", GetReference<BendingStripNURBSPatch<TDim> >, return_value_policy<reference_existing_object>())\n    .def(self_ns::str(self))\n    ;\n}\n\n//////////////////////////////////////////////////\n\ntemplate<int TDim>\nvoid IsogeometricApplication_AddNURBSTestUtilsToPython()\n{\n    std::stringstream ss;\n\n    ss.str(std::string());\n    ss << \"NURBSTestUtils\" << TDim << \"D\";\n    class_<NURBSTestUtils<TDim>, typename NURBSTestUtils<TDim>::Pointer, boost::noncopyable>\n    (ss.str().c_str(), init<>())\n    .def(\"ProbeAndTestValuesOnPatch\", &NURBSTestUtils_ProbeAndTestValuesOnPatch<TDim>)\n    .def(self_ns::str(self))\n    ;\n}\n\n//////////////////////////////////////////////////\n\nvoid IsogeometricApplication_AddNURBSToPython()\n{\n    /////////////////////////////////////////////////////////////////\n    ///////////////////////SUPPORT DOMAIN////////////////////////////\n    /////////////////////////////////////////////////////////////////\n\n    class_<DomainManager, DomainManager::Pointer, boost::noncopyable>\n    (\"DomainManager\", init<std::size_t>())\n    ;\n\n    class_<DomainManager2D, DomainManager2D::Pointer, boost::noncopyable>\n    (\"DomainManager2D\", init<std::size_t>())\n    .def(\"AddXcoord\", &DomainManager2D::AddXcoord)\n    .def(\"AddYcoord\", &DomainManager2D::AddYcoord)\n    .def(\"AddCell\", &DomainManager2D_AddCell)\n    .def(\"IsInside\", &DomainManager2D_IsInside)\n    .def(self_ns::str(self))\n    ;\n\n    /////////////////////////////////////////////////////////////////\n    ///////////////////////CONTROL GRIDS/////////////////////////////\n    /////////////////////////////////////////////////////////////////\n\n    IsogeometricApplication_AddStructuredControlGridsToPython();\n\n    /////////////////////////////////////////////////////////////////\n    ///////////////////////FESpace///////////////////////////////////\n    /////////////////////////////////////////////////////////////////\n\n    IsogeometricApplication_AddBSplinesFESpaceToPython<1>();\n    IsogeometricApplication_AddBSplinesFESpaceToPython<2>();\n    IsogeometricApplication_AddBSplinesFESpaceToPython<3>();\n\n    class_<BSplinesFESpaceLibrary, BSplinesFESpaceLibrary::Pointer, boost::noncopyable>\n    (\"BSplinesFESpaceLibrary\", init<>())\n    .def(\"CreateLinearFESpace\", &BSplinesFESpaceLibrary_CreatePrimitiveFESpace1) // backward compatibility\n    .def(\"CreateRectangularFESpace\", &BSplinesFESpaceLibrary_CreatePrimitiveFESpace2) // backward compatibility\n    .def(\"CreateCubicFESpace\", &BSplinesFESpaceLibrary_CreatePrimitiveFESpace3) // backward compatibility\n    .def(\"CreatePrimitiveFESpace\", &BSplinesFESpaceLibrary_CreatePrimitiveFESpace1)\n    .def(\"CreatePrimitiveFESpace\", &BSplinesFESpaceLibrary_CreatePrimitiveFESpace2)\n    .def(\"CreatePrimitiveFESpace\", &BSplinesFESpaceLibrary_CreatePrimitiveFESpace3)\n    .def(\"CreateUniformFESpace\", &BSplinesFESpaceLibrary_CreateUniformFESpace1)\n    .def(\"CreateUniformFESpace\", &BSplinesFESpaceLibrary_CreateUniformFESpace2)\n    .def(\"CreateUniformFESpace\", &BSplinesFESpaceLibrary_CreateUniformFESpace3)\n    ;\n\n    /////////////////////////////////////////////////////////////////\n    ///////////////////////Bending Strip NURBS Patch/////////////////\n    /////////////////////////////////////////////////////////////////\n\n    IsogeometricApplication_AddBendingStripNURBSToPython<2>();\n    IsogeometricApplication_AddBendingStripNURBSToPython<3>();\n\n    /////////////////////////////////////////////////////////////////\n    ///////////////////////NURBS Tets Utils//////////////////////////\n    /////////////////////////////////////////////////////////////////\n\n    IsogeometricApplication_AddNURBSTestUtilsToPython<1>();\n    // IsogeometricApplication_AddNURBSTestUtilsToPython<2>();\n    // IsogeometricApplication_AddNURBSTestUtilsToPython<3>();\n\n}\n\n}  // namespace Python.\n\n} // Namespace Kratos\n\n", "meta": {"hexsha": "3f928bb317c768a108205a5ae80482880f50bc1a", "size": 24242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "custom_python/add_nurbs_to_python.cpp", "max_stars_repo_name": "rwilliams01/isogeometric_application", "max_stars_repo_head_hexsha": "e505061603b56b4f426220946da5ec551dc6c142", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "custom_python/add_nurbs_to_python.cpp", "max_issues_repo_name": "rwilliams01/isogeometric_application", "max_issues_repo_head_hexsha": "e505061603b56b4f426220946da5ec551dc6c142", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "custom_python/add_nurbs_to_python.cpp", "max_forks_repo_name": "rwilliams01/isogeometric_application", "max_forks_repo_head_hexsha": "e505061603b56b4f426220946da5ec551dc6c142", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-25T08:31:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T08:31:06.000Z", "avg_line_length": 42.7548500882, "max_line_length": 195, "alphanum_fraction": 0.6616203284, "num_tokens": 6263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.521887096346915}}
{"text": "// This ray-tracing code is adapted from Hugues Thomas' project.\n#include <math.h>\n#include <iostream>\n#include <unordered_map>\n#include <algorithm>\n#include <set>\n#include <cstdint>\n#include <cstdio>\n#include <boost/algorithm/string.hpp>\n#include \"ray_tracing.hpp\"\n#include \"estimation.hpp\"\n#include \"utils.hpp\"\n#include \"pointmatcher/PointMatcher.h\"\n\nstatic Eigen::Vector3d max_point(Eigen::MatrixXd & pc) {\n    Eigen::Vector3d maxP = Eigen::Vector3d::Zero();\n    for (uint i = 0; i < pc.cols(); ++i) {\n        if (pc(0, i) > maxP(0))\n            maxP(0) = pc(0, i);\n        if (pc(1, i) > maxP(1))\n            maxP(1) = pc(1, i);\n        if (pc(2, i) > maxP(2))\n            maxP(2) = pc(2, i);\n    }\n    return maxP;\n}\n\nstatic Eigen::Vector3d min_point(Eigen::MatrixXd & pc) {\n    Eigen::Vector3d minP = Eigen::Vector3d::Zero();\n    for (uint i = 0; i < pc.cols(); ++i) {\n        if (pc(0, i) < minP(0))\n            minP(0) = pc(0, i);\n        if (pc(1, i) < minP(1))\n            minP(1) = pc(1, i);\n        if (pc(2, i) < minP(2))\n            minP(2) = pc(2, i);\n    }\n    return minP;\n}\n\nstatic void cart2pol_(Eigen::MatrixXd &cart_frame, Eigen::MatrixXd &polar_frame) {\n    polar_frame = Eigen::MatrixXd::Ones(cart_frame.rows(), cart_frame.cols());\n    for (uint i = 0; i < cart_frame.cols(); ++i) {\n        Eigen::Vector3d p = cart_frame.block(0, i, 3, 1);\n        float rho = p.norm();\n        float phi = atan2f(p(1), p(0));\n        float theta = atan2f(sqrt(p(0) * p(0) + p(1) * p(1)), p(2));\n        polar_frame(0, i) = rho;\n        polar_frame(1, i) = theta;\n        polar_frame(2, i) = phi + M_PI / 2;\n    }\n}\n\nstatic Eigen::Vector3d cart2pol(Eigen::Vector3d &p) {\n    float rho = p.norm();\n    float phi = atan2f(p(1), p(0));\n    float theta = atan2f(sqrt(p(0) * p(0) + p(1) * p(1)), p(2));\n    return Eigen::Vector3d(rho, theta, phi + M_PI / 2);\n}\n\nstatic void compare_map_to_frame(Eigen::MatrixXd &aligned_frame, Eigen::MatrixXd &map_points,\n    Eigen::MatrixXd &map_normals, Eigen::Matrix4d T_sensor_map, std::unordered_map<VoxKey, size_t> &map_samples,\n    float theta_dl, float phi_dl, float map_dl, std::vector<float> &movable_probs, std::vector<int> &movable_counts) {\n\n    float inv_theta_dl = 1.0 / theta_dl;\n    float inv_phi_dl = 1.0 / phi_dl;\n    float inv_map_dl = 1.0 / map_dl;\n    float max_angle = 5 * M_PI / 12;\n    float min_vert_cos = cos(M_PI / 3);\n\n    // Mask of the map points not updated yet\n    std::vector<bool> not_updated(map_points.cols(), true);\n\n    // Get limits\n    Eigen::Vector3d min_P = min_point(aligned_frame) - Eigen::Vector3d(map_dl, map_dl, map_dl);\n    Eigen::Vector3d max_P = max_point(aligned_frame) + Eigen::Vector3d(map_dl, map_dl, map_dl);\n\n    // Update full voxels\n    // Loop over aligned_frame\n    VoxKey k0, k;\n    for (uint i = 0; i < aligned_frame.cols(); ++i) {\n        // Corresponding key\n        k0.x = (int)floor(aligned_frame(0, i) * inv_map_dl);\n        k0.y = (int)floor(aligned_frame(1, i) * inv_map_dl);\n        k0.z = (int)floor(aligned_frame(2, i) * inv_map_dl);\n        // Update the adjacent cells\n        for (k.x = k0.x - 1; k.x < k0.x + 2; k.x++) {\n            for (k.y = k0.y - 1; k.y < k0.y + 2; k.y++) {\n                for (k.z = k0.z - 1; k.z < k0.z + 2; k.z++) {\n                    // Update count and movable at this point\n                    if (map_samples.count(k) > 0) {\n                        // Only update once\n                        size_t i0 = map_samples[k];\n                        if (not_updated[i0]) {\n                            not_updated[i0] = false;\n                            movable_counts[i0] += 1;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // Create the free frustum grid\n\n    // get frame in polar coordinates\n    Eigen::MatrixXd frame = T_sensor_map * aligned_frame;\n    Eigen::MatrixXd polar_frame;\n    cart2pol_(frame, polar_frame);\n\n    // Get grid limits\n    Eigen::Vector3d minCorner = min_point(polar_frame);\n    Eigen::Vector3d maxCorner = max_point(polar_frame);\n    Eigen::Vector3d originCorner = minCorner - Eigen::Vector3d(0, 0.5 * theta_dl, 0.5 * phi_dl);\n\n    // Dimensions of the grid\n    size_t grid_n_theta = (size_t)floor((maxCorner(1) - originCorner(1)) / theta_dl) + 1;\n    size_t grid_n_phi = (size_t)floor((maxCorner(2) - originCorner(2)) / phi_dl) + 1;\n\n    // Initialize variables\n    std::vector<float> frustrum_radiuses(grid_n_theta * grid_n_phi, -1.0);\n\n    // Fill the frustrum radiuses\n    for (uint i = 0; i < polar_frame.cols(); ++i) {\n        // Corresponding key\n        Eigen::Vector3d p = polar_frame.block(0, i, 3, 1);\n        // Position of point in grid\n        size_t i_theta = (size_t)floor((p(1) - originCorner(1)) * inv_theta_dl);\n        size_t i_phi = (size_t)floor((p(2) - originCorner(2)) * inv_phi_dl);\n        size_t gridIdx = i_theta + grid_n_theta * i_phi;\n\n        // Update the radius in cell\n        if (frustrum_radiuses[gridIdx] < 0)\n            frustrum_radiuses[gridIdx] = p(0);\n        else if (p(0) < frustrum_radiuses[gridIdx])\n            frustrum_radiuses[gridIdx] = p(0);\n    }\n\n    // Apply margin to free ranges\n    float margin = map_dl;\n    float frustrum_alpha = theta_dl / 2;\n    for (auto &r : frustrum_radiuses) {\n        float adapt_margin = r * frustrum_alpha;\n        if (margin < adapt_margin)\n            r -= adapt_margin;\n        else\n            r -= margin;\n    }\n\n    // Apply frustum casting\n\n    // update free pixels\n    float min_r = 2 * map_dl;\n    Eigen::Matrix3d C_sensor_map = T_sensor_map.block(0, 0, 3, 3);\n\n    for (uint i = 0; i < map_points.cols(); ++i) {\n        // Ignore points updated just now\n        if (!not_updated[i])\n            continue;\n        Eigen::Vector4d p = map_points.block(0, i, 4, 1);\n        // Ignore points outside area of the frame\n        if (p(0) > max_P(0) || p(1) > max_P(1) || p(2) > max_P(2) ||\n            p(0) < min_P(0) || p(1) < min_P(1) || p(2) < min_P(2)) {\n            continue;\n        }\n\n        // Align point in frame coordinates (and normal)\n        p = T_sensor_map * p;\n        Eigen::Vector3d xyz = p.block(0, 0, 3, 1);\n        Eigen::Vector3d nxyz = C_sensor_map * map_normals.block(0, i, 3, 1);\n\n        // Project in polar coordinates\n        Eigen::Vector3d rtp = cart2pol(xyz);\n\n        // Position of point in grid\n        size_t i_theta = (size_t)floor((rtp(1) - originCorner(1)) * inv_theta_dl);\n        size_t i_phi = (size_t)floor((rtp(2) - originCorner(2)) * inv_phi_dl);\n        size_t gridIdx = i_theta + grid_n_theta * i_phi;\n\n        // Update movable prob\n        if (rtp(0) > min_r && rtp(0) < frustrum_radiuses[gridIdx]) {\n            // Do not update if normal is horizontal and perpendicular to ray (to avoid removing walls)\n            if (abs(nxyz(2)) > min_vert_cos) {\n                movable_counts[i] += 1;\n                movable_probs[i] += 1.0;\n            } else {\n                float angle = acos(std::min(fabs(xyz.dot(nxyz) / rtp(0)), 1.0));\n                if (angle < max_angle) {\n                    movable_counts[i] += 1;\n                    movable_probs[i] += 1.0;\n                }\n            }\n        }\n    }\n}\n\nstatic void getNameFromPath(std::string path, std::string &name) {\n    std::vector<std::string> parts;\n    boost::split(parts, path, boost::is_any_of(\"/\"));\n    std::string endy_bit = parts[parts.size() - 1];\n    boost::split(parts, endy_bit, boost::is_any_of(\".\"));\n    name = parts[0];\n}\n\nint main(int argc, const char *argv[]) {\n    std::string root, config;\n    std::string new_map_name = \"map_no_movable.ply\";\n    validateArgs(argc, argv, root, config);\n    // Params:\n    float map_dl = 0.15;\n    float theta_dl = 1.29 * M_PI / 180;\n    float phi_dl = 0.1 * M_PI / 180;\n\n    // Init point map\n    std::cout << \"Loading map...\" << std::endl;\n    DP map = DP::load(root + \"map/map.ply\");\n    std::cout << \"Finished loading map\" << std::endl;\n\n    // Create the pointmap voxels\n    std::unordered_map<VoxKey, size_t> map_samples;\n    uint N = map.features.cols();\n    map_samples.reserve(N);\n    float inv_map_dl = 1.0 / map_dl;\n    VoxKey k0;\n\n    for (uint i = 0; i < N; ++i) {\n        k0.x = (int)floor(map.features(0, i) * inv_map_dl);\n        k0.y = (int)floor(map.features(1, i) * inv_map_dl);\n        k0.z = (int)floor(map.features(2, i) * inv_map_dl);\n        if (map_samples.count(k0) < 1) {\n            map_samples.emplace(k0, i);\n        }\n    }\n\n    // Init map movable probabilities and counts\n    std::vector<float> movable_probs(N, 0);\n    std::vector<int> movable_counts(N, 0);\n\n    // Calculate normal vectors for the map\n    std::shared_ptr<PM::DataPointsFilter> normalFilter = PM::get().DataPointsFilterRegistrar.create(\n        \"SurfaceNormalDataPointsFilter\", {{\"knn\", toParam(10)}, {\"epsilon\", toParam(5)}, {\"keepNormals\", toParam(1)},\n        {\"keepDensities\", toParam(0)}});\n\n    std::cout << \"Calculating normals for the entire map...\" << std::endl;\n    map = normalFilter->filter(map);\n    std::cout << \"Finished calculating normals\" << std::endl;\n    uint norm_row = map.getDescriptorStartingRow(\"normals\");\n    Eigen::MatrixXd map_normals = map.descriptors.block(norm_row, 0, 3, N);\n\n    // Start movable detection\n\n    std::vector<std::string> frame_names;\n    getMapFrames(root, frame_names);\n\n    for (uint i = 0; i < frame_names.size(); ++i) {\n        std::cout << \"Ray tracing frame \" << i << \" / \" << frame_names.size() - 1 << std::endl;\n        // Load frame / ply file\n        DP frame = DP::load(frame_names[i]);\n        // Load pose for this frame\n        Eigen::Matrix4d T_map_sensor = Eigen::Matrix4d::Identity();\n        std::string name;\n        getNameFromPath(frame_names[i], name);\n        load_transform(root + \"map/frame_poses/\" + name + \".txt\", T_map_sensor);\n        Eigen::Matrix4d T_sensor_map = get_inverse_tf(T_map_sensor);\n        // Perform ray-tracing to identity movable points\n        compare_map_to_frame(frame.features, map.features, map_normals, T_sensor_map,\n            map_samples, theta_dl, phi_dl, map_dl, movable_probs, movable_counts);\n    }\n\n    for (uint i = 0; i < movable_probs.size(); ++i) {\n        movable_probs[i] = movable_probs[i] / (movable_counts[i] + 1e-6);\n        if (movable_counts[i] < 1e-6)\n            movable_probs[i] = -1;\n    }\n    map.allocateDescriptor(\"movable\", 1);\n    uint movable_row = map.getDescriptorStartingRow(\"movable\");\n    for (uint i = 0; i < movable_probs.size(); ++i) {\n        map.descriptors(movable_row, i) = movable_probs[i];\n    }\n    std::cout << \"Adding movable descriptor to the existing map...\" << std::endl;\n    map.removeDescriptor(\"normals\");  // Get rid of normals\n    map.save(root + \"map/map.ply\");\n\n    std::cout << \"Removing movable points from the map...\" << std::endl;\n    uint feat_dim = map.features.rows();\n    map.removeDescriptor(\"movable\");\n    uint desc_dim = map.descriptors.rows();\n    uint j = 0;\n    for (uint i = 0; i < movable_probs.size(); ++i) {\n        if (movable_probs[i] < 0.8) {\n            map.features.block(0, j, feat_dim, 1) = map.features.block(0, i, feat_dim, 1);\n            map.descriptors.block(0, j, desc_dim, 1) = map.descriptors.block(0, i, desc_dim, 1);\n            j++;\n        }\n    }\n    map.conservativeResize(j);\n\n    std::cout << \"Saving the filtered map...\" << std::endl;\n    map.save(root + \"map/\" + new_map_name);\n}\n", "meta": {"hexsha": "48d6dd591f2607cea68c017113c15d36ae29dcf9", "size": 11364, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ray_tracing.cpp", "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": "src/ray_tracing.cpp", "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": "src/ray_tracing.cpp", "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": 37.7541528239, "max_line_length": 118, "alphanum_fraction": 0.5789334741, "num_tokens": 3358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5217996753817815}}
{"text": "//\n// Created by jachu on 31.01.18.\n//\n\n#ifndef PLANELOC_CONCAVEHULL_HPP\n#define PLANELOC_CONCAVEHULL_HPP\n\n//#define CGAL_DISABLE_ROUNDING_MATH_CHECK\n\nclass ConcaveHull;\n\n#include <vector>\n\n#include <boost/serialization/vector.hpp>\n\n#include <Eigen/Eigen>\n\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/impl/point_types.hpp>\n#include <pcl/point_cloud.h>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/algorithm.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Alpha_shape_2.h>\n#include <CGAL/IO/io.h>\n#include <CGAL/Polygon_with_holes_2.h>\n#include <CGAL/Polyline_simplification_2/simplify.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n\n#include \"Types.hpp\"\n#include \"Serialization.hpp\"\n\nclass ConcaveHull {\n\npublic:\n    typedef CGAL::Exact_predicates_exact_constructions_kernel  K;\n    typedef K::FT                                                FT;\n    typedef K::Point_2                                           Point_2;\n    typedef K::Segment_2                                         Segment_2;\n    typedef CGAL::Polygon_2<K>                                   Polygon_2;\n    typedef CGAL::Polygon_with_holes_2<K>                        Polygon_holes_2;\n    typedef CGAL::Polyline_simplification_2::Stop_above_cost_threshold Stop;\n    typedef CGAL::Polyline_simplification_2::Squared_distance_cost     Cost;\n    \n    typedef CGAL::Exact_predicates_inexact_constructions_kernel    Kie;\n    typedef Kie::FT                                                FTie;\n    typedef Kie::Point_2                                           Point_2ie;\n    typedef Kie::Segment_2                                         Segment_2ie;\n    typedef CGAL::Polygon_2<Kie>                                   Polygon_2ie;\n    typedef CGAL::Polygon_with_holes_2<Kie>                        Polygon_holes_2ie;\n    typedef CGAL::Alpha_shape_vertex_base_2<Kie>                   Vb;\n    typedef CGAL::Alpha_shape_face_base_2<Kie>                     Fb;\n    typedef CGAL::Triangulation_data_structure_2<Vb,Fb>            Tds;\n    typedef CGAL::Delaunay_triangulation_2<Kie,Tds>                Triangulation_2;\n    typedef CGAL::Alpha_shape_2<Triangulation_2>                 Alpha_shape_2;\n    typedef Alpha_shape_2::Alpha_shape_edges_iterator            Alpha_shape_edges_iterator;\n    typedef Alpha_shape_2::Alpha_shape_vertices_iterator         Alpha_shape_vertices_iterator;\n    \n    ConcaveHull();\n    \n    ConcaveHull(pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr ipoints3d,\n                const Eigen::Vector4d &planeEq);\n    \n    ConcaveHull(const std::vector<Polygon_2> &polygons,\n                    const std::vector<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> &polygons3d,\n                    const Eigen::Vector3d &plNormal,\n                    double plD,\n                    const Eigen::Vector3d &origin,\n                    const Eigen::Vector3d &xAxis,\n                    const Eigen::Vector3d &yAxis);\n    \n    ConcaveHull(const ConcaveHull &other);\n    \n    void init(pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr ipoints3d,\n              const Eigen::Vector4d &planeEq);\n    \n    void init(const std::vector<Polygon_2> &polygons,\n              const std::vector<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> &polygons3d,\n              const Eigen::Vector3d &plNormal,\n              double plD,\n              const Eigen::Vector3d &origin,\n              const Eigen::Vector3d &xAxis,\n              const Eigen::Vector3d &yAxis);\n    \n    const std::vector<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> &getPolygons3d() const {\n        return polygons3d;\n    }\n    \n    const std::vector<double> &getAreas() const {\n        return areas;\n    }\n    \n    double getTotalArea() const {\n        return totalArea;\n    }\n\n    ConcaveHull intersect(const ConcaveHull &other,\n                          double areaThresh = 0.05) const;\n    \n    ConcaveHull intersect(const std::vector<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> &otherPolygons3d,\n                          double areaThresh = 0.05) const;\n    \n    ConcaveHull clipToCameraFrustum(const cv::Mat K,\n                                    int rows,\n                                    int cols,\n                                    double minZ);\n    \n    ConcaveHull transform(const Vector7d &transform) const;\n    \n    double minDistance(const ConcaveHull &other) const;\n    \n    void display(pcl::visualization::PCLVisualizer::Ptr viewer,\n                 int vp,\n                 double r = 0.0,\n                 double g = 1.0,\n                 double b = 0.0) const ;\n    \n    void cleanDisplay(pcl::visualization::PCLVisualizer::Ptr viewer,\n                      int vp) const;\n    \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n    void computeFrame();\n    \n    Point_2 point3dTo2d(const Eigen::Vector3d &point3d) const;\n    \n    Point_2ie point3dTo2die(const Eigen::Vector3d &point3d) const;\n    \n    Eigen::Vector3d point2dTo3d(const Point_2 &point2d) const;\n    \n    std::vector<Polygon_2> polygons;\n    std::vector<double> areas;\n    double totalArea;\n    std::vector<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> polygons3d;\n    \n    Eigen::Vector3d plNormal;\n    double plD;\n    // point on the plane nearest to origin\n    Eigen::Vector3d origin;\n    Eigen::Vector3d xAxis, yAxis;\n    \n    friend class boost::serialization::access;\n    \n    template<class Archive>\n    void serialize(Archive & ar, const unsigned int version)\n    {\n        ar & polygons;\n        ar & areas;\n        ar & totalArea;\n        ar & polygons3d;\n        ar & plNormal;\n        ar & plD;\n        ar & origin;\n        ar & xAxis;\n        ar & yAxis;\n    }\n};\n\n\n#endif //PLANELOC_CONCAVEHULL_HPP\n", "meta": {"hexsha": "9447f6c43232a63cf2e4c951d7c0cafe08654f84", "size": 5680, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ConcaveHull.hpp", "max_stars_repo_name": "richard5635/PlaneLoc", "max_stars_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-08-29T06:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T07:42:31.000Z", "max_issues_repo_path": "include/ConcaveHull.hpp", "max_issues_repo_name": "richard5635/PlaneLoc", "max_issues_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-03-26T06:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T01:59:41.000Z", "max_forks_repo_path": "include/ConcaveHull.hpp", "max_forks_repo_name": "richard5635/PlaneLoc", "max_forks_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-04-24T08:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T07:56:58.000Z", "avg_line_length": 35.0617283951, "max_line_length": 101, "alphanum_fraction": 0.5998239437, "num_tokens": 1376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115783, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5217996669696348}}
{"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_TWO_ADD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_TWO_ADD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-arithmetic\n    This function object computes two reals of the type of the inputs\n    (in an std::pair) @c r0 and @c r1 such that:\n\n    @code\n    r0 = x + y\n    r1 = r0 -(x + y)\n    @endcode\n\n    using perfect arithmetic.\n\n    Its main usage is to be able to compute\n    sum of reals and the residual error using IEEE 754 arithmetic.\n\n\n    @par Header <boost/simd/function/two_add.hpp>\n\n    @par Example:\n\n      @snippet two_add.cpp two_add\n\n    @par Possible output:\n\n      @snippet two_add.txt two_add\n\n\n  **/\n  std::pair<Value, Value> two_add(Value const& x, Value const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/two_add.hpp>\n#include <boost/simd/function/simd/two_add.hpp>\n\n#endif\n", "meta": {"hexsha": "ebc4b4f7cefe388473afe522c554aae2a14541be", "size": 1277, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/two_add.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/function/two_add.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/function/two_add.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": 23.2181818182, "max_line_length": 100, "alphanum_fraction": 0.5888801879, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5217678980953503}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nusing namespace Eigen;\n\ntemplate <class Type>\nMatrix<Type, Dynamic, Dynamic, RowMajor>* load_img(const std::string& path, int num_channels, int img_length) {\n    using Mat = Matrix<Type, Dynamic, Dynamic, RowMajor>;\n\n    Mat* img = new Mat[num_channels];\n\n    int cellno = 0, c = 0;\n    int img_size = img_length * img_length;\n\n    std::ifstream in(path);\n    std::string line;\n    std::vector<Type> values(img_size);\n    while (std::getline(in, line)) {\n        std::stringstream ss(line);\n        std::string cell;\n        while (std::getline(ss, cell, ',')) {\n            Type val = Type(std::stod(cell));\n            values[cellno++] = val;\n\n            if (cellno == img_size) {\n                cellno = 0;\n                img[c] = Map<Mat>(values.data(), img_length, img_length);\n                values.clear();\n                ++c;\n            }\n        }\n    }\n\n    return img;\n}\n\ntemplate <class Type>\nMatrix<Type, Dynamic, Dynamic, RowMajor>** load_conv_weights(const std::string& path, int num_channels, int num_kernels, int kernel_length) {\n    using Mat = Matrix<Type, Dynamic, Dynamic, RowMajor>;\n\n    Mat** kernels = new Mat*[num_kernels];\n    for (int k = 0; k < num_kernels; ++k) {\n        kernels[k] = new Mat[num_channels];\n    }\n\n    int cellno = 0, c = 0, k = 0;\n    int kernel_size = kernel_length * kernel_length;\n\n    std::ifstream in(path);\n    std::string line;\n    std::vector<Type> values;\n    while (std::getline(in, line)) {\n        std::stringstream ss(line);\n        std::string cell;\n        while (std::getline(ss, cell, ',')) {\n            Type val = Type(std::stod(cell));\n            values.push_back(val);\n            ++cellno;\n\n            if (cellno == kernel_size) {\n                cellno = 0;\n                kernels[k][c] = Map<Mat>(values.data(), kernel_length, kernel_length);\n                values.clear();\n                ++c;\n                if (c == num_channels) {\n                    c = 0;\n                    ++k;\n                }\n            }\n        }\n    }\n    return kernels;\n}\n\ntemplate <class Type>\nMatrix<Type, 1, Dynamic, RowMajor> load_conv_biases(const std::string& path, int num_kernels) {\n    using RowVec = Matrix<Type, 1, Dynamic, RowMajor>;\n\n    std::ifstream in(path);\n    std::string cell;\n    std::vector<Type> values;\n    while (std::getline(in, cell, ',')) {\n        Type val = Type(std::stod(cell));\n        values.push_back(val);\n    }\n    return Map<RowVec>(values.data(), 1, num_kernels);\n}\n\ntemplate <class Type>\nMatrix<Type, Dynamic, Dynamic, RowMajor> load_fc(const std::string& path, int M, int N) {\n    std::ifstream indata(path);\n    std::string line;\n    std::vector<Type> values;\n    while (std::getline(indata, line)) {\n        std::stringstream lineStream(line);\n        std::string cell;\n        while (std::getline(lineStream, cell, ',')) {\n            Type val = Type(std::stod(cell));\n            values.push_back(val);\n        }\n    }\n    return Map<Matrix<Type, Dynamic, Dynamic, RowMajor>>(values.data(), M, N);\n}\n", "meta": {"hexsha": "51a6c210d51013825cf6efb56b181d3d528c4a37", "size": 3106, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Reader.hpp", "max_stars_repo_name": "uiuc-arc/DeepJ", "max_stars_repo_head_hexsha": "1c0493511b12394ca6f9a0098d3401cdcab50806", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-20T15:46:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T16:51:37.000Z", "max_issues_repo_path": "src/Reader.hpp", "max_issues_repo_name": "uiuc-arc/DeepJ", "max_issues_repo_head_hexsha": "1c0493511b12394ca6f9a0098d3401cdcab50806", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Reader.hpp", "max_forks_repo_name": "uiuc-arc/DeepJ", "max_forks_repo_head_hexsha": "1c0493511b12394ca6f9a0098d3401cdcab50806", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-31T02:02:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T02:02:43.000Z", "avg_line_length": 29.0280373832, "max_line_length": 141, "alphanum_fraction": 0.5598840953, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5217678957721588}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <dlib/svm.h>\n#include <dlib/statistics.h>\n#include <dlib/global_optimization.h>\n\n#include <sampml/data.hpp>\n#include <sampml/random_forest.hpp>\n\n#include \"common.hpp\"\n#include \"transform.hpp\"\n\nusing sample_type = output_vector;\n\nvoid train() {\n    std::cout << \"TRAINING:\\n\";\n\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    sampml::trainer::random_forest<sample_type> model;\n    model.set_samples(data_positive_train, data_negative_train);\n    //model.cross_validate();\n    model.train();\n\n    model.serialize(std::string(rf_model.begin(), rf_model.end()));\n    std::cout << \"\\n\\n\";\n}\n\nvoid test() {\n    const float cutoff = 0.5;\n\n    std::cout << \"TESTING:\\n\";\n    sampml::data::reader<sample_type> data_positive_test(positive_test_data);\n    sampml::data::reader<sample_type> data_negative_test(negative_test_data);\n\n    sampml::trainer::random_forest<sample_type> model;\n    model.deserialize(std::string(rf_model.begin(), rf_model.end()));\n\n    int true_positives = 0,\n        false_positives = 0,\n        true_negatives = 0,\n        false_negatives = 0;\n    dlib::running_stats<double> values;\n    for(const auto& v : data_positive_test) {\n        double prob = model.test(v);\n        if(prob > cutoff)\n            true_positives++;\n        else\n            false_negatives++;\n        values.add(prob);\n    }\n    std::cout << \"positive test set statistics: \" << '\\n';\n    std::cout << \"average: \" << values.mean() << \", stddev: \" << values.stddev() << '\\n'\n              << \"min: \" << values.min() << \", max: \" << values.max()  << '\\n'\n              << \"skewness: \" << values.skewness() << \", excess kurtosis: \" << values.ex_kurtosis() << '\\n';\n    values.clear();\n\n    for(const auto& v : data_negative_test) {\n        double prob = model.test(v);\n        if(prob < cutoff)\n            true_negatives++;\n        else\n            false_positives++;\n        values.add(prob);\n    }\n    std::cout << \"negative test set statistics: \" << '\\n';\n    std::cout << \"average: \" << values.mean() << \", stddev: \" << values.stddev() << '\\n'\n              << \"min: \" << values.min() << \", max: \" << values.max()  << '\\n'\n              << \"skewness: \" << values.skewness() << \", excess kurtosis: \" << values.ex_kurtosis() << '\\n';\n\n    int num_correct = true_positives + true_negatives,\n        num_wrong = false_positives + false_negatives;\n    std::cout << \"\\n\\n\";\n    std::cout << \"true positives: \" << true_positives << \", false positives: \" << false_positives << '\\n';\n    std::cout << \"true negatives: \" << true_negatives << \", false negatives: \" << false_negatives << '\\n';\n    std::cout << \"number of samples classified corretly: \" << num_correct << '\\n';\n    std::cout << \"number of samples classified incorrectly: \" << num_wrong << '\\n';\n    std::cout << \"accuracy: \" << num_correct/float(num_correct + num_wrong) << '\\n';\n}\n\nint main () {\n    train();\n    test();\n    return 0;\n}", "meta": {"hexsha": "c03fc6f638f505e95fa088824e0749b366477d0a", "size": 3047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/anti-aimbot/training/rf.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/rf.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/rf.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": 35.0229885057, "max_line_length": 108, "alphanum_fraction": 0.6019035117, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.5217646772340051}}
{"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/Cache.h\"\n\nusing namespace Scine::Molassembler;\n\nunsigned int ackermann(unsigned int m, unsigned int n) {\n  if (m == 0) {\n    return n + 1;\n  }\n  if (n == 0) {\n    return ackermann(m - 1, 1);\n  }\n  return ackermann(m - 1, ackermann(m, n - 1));\n}\n\n/* Sample class with mutable Cache member and a generatable cache object\n * Also includes an example of how to modify a cache object\n */\nclass Foo {\nprivate:\n  /* 2 */\n  mutable Temple::Cache<std::string> cache_ {\n    std::make_pair(\n      \"bigNumber\",\n      [this]() {\n        return (this -> determineMe_());\n      }\n    )\n  };\n\n  unsigned determineMe_() {\n    return ackermann(3, 2);\n  }\n\npublic:\n  unsigned getAckermann() const {\n    /* 4 */\n    return cache_.getGeneratable<unsigned>(\"bigNumber\");\n  }\n\n  void changeCacheValue() {\n    /* 5 */\n    cache_.changeGeneratable<unsigned>(\n      \"bigNumber\",\n      [](unsigned* value) {\n        *value = 4;\n      }\n    );\n  }\n};\n\nBOOST_AUTO_TEST_CASE(SimpleCacheTest, *boost::unit_test::label(\"Temple\")) {\n  using namespace std::string_literals;\n\n  /* 1 */\n  Temple::Cache<std::string> cache;\n\n  /* 3 */\n  std::vector<std::string> keys {\"number\", \"string\", \"vector\"};\n  cache.add(\"number\", 5);\n  cache.add(\"string\", \"fsldkf\"s);\n  cache.add(\"vector\", std::vector<unsigned>({4, 9}));\n\n  /* 8 */\n  if(auto number = cache.getOption<int>(\"number\")) { // op (bool) is true\n    BOOST_CHECK(number.value() == 5);\n  }\n\n  if(auto number = cache.getOption<int>(\"non-existent number\")) { // op (bool) is false\n    // this should not be executed\n    BOOST_REQUIRE(false);\n  }\n\n  /* 9 */\n  BOOST_CHECK(\n    std::all_of(\n      keys.begin(),\n      keys.end(),\n      [&cache](const std::string& key) {\n        return cache.has(key);\n      }\n    )\n  );\n\n  /* 6 */\n  cache.invalidate(\"number\");\n  BOOST_CHECK(!cache.has(\"number\"));\n\n  /* 7 */\n  cache.invalidate();\n  BOOST_CHECK(\n    std::none_of(\n      keys.begin(),\n      keys.end(),\n      [&cache](const std::string& key) {\n        return cache.has(key);\n      }\n    )\n  );\n\n  /* 2, 4, 5 */\n  Foo bar;\n  bar.getAckermann();\n\n  // test modification of the cache\n  bar.changeCacheValue();\n  BOOST_CHECK(bar.getAckermann() == 4);\n}\n", "meta": {"hexsha": "a7bee457f1a216aa908a80525b520c3712d323ea", "size": 2415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Temple/Cache.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/Cache.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/Cache.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": 20.8189655172, "max_line_length": 87, "alphanum_fraction": 0.5950310559, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5217646766038495}}
{"text": "/*\n * DIPlib 3.0\n * This file contains definitions for functions that do matrix computations using Eigen\n *\n * (c)2016-2017, Cris Luengo.\n * Based on original DIPlib code: (c)1995-2014, Delft University of Technology.\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 <array>\n#include \"diplib/library/numeric.h\"\n\n#if defined(__GNUG__) || defined(__clang__)\n// For this file, turn off -Wsign-conversion, Eigen is really bad at this!\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-conversion\"\n#if __GNUC__ == 11\n#pragma GCC diagnostic ignored \"-Wmaybe-uninitialized\"\n#endif\n#endif\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/SVD>\n\nnamespace dip {\n\nnamespace {\n\ntemplate< class T >\nstruct GreaterMagnitude {\n   bool operator()( T const& a, T const& b ) const {\n      return std::abs( a ) > std::abs( b );\n   }\n};\n\n} // namespace\n\nvoid SymmetricEigenDecomposition(\n      dip::uint n,\n      ConstSampleIterator< dfloat > input,\n      SampleIterator< dfloat > lambdas,\n      SampleIterator< dfloat > vectors\n) {\n   DIP_ASSERT( input.Stride() >= 0 ); // TODO: (here and other asserts in this file) Eigen doesn't support negative strides, but there's a ticket for that: https://gitlab.com/libeigen/eigen/-/issues/747\n   Eigen::Map< Eigen::MatrixXd const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), n, n, Eigen::InnerStride<>( input.Stride() ));\n   if( vectors ) {\n      Eigen::SelfAdjointEigenSolver< Eigen::MatrixXd > eigensolver( matrix );\n      //if( eigensolver.info() != Eigen::Success ) { abort(); }\n      Eigen::VectorXd const& eigenvalues = eigensolver.eigenvalues();\n      Eigen::MatrixXd const& eigenvectors = eigensolver.eigenvectors();\n      std::vector< dip::uint > indices( n );\n      std::iota( indices.begin(), indices.end(), 0 );\n      std::sort( indices.begin(), indices.end(), [ & ]( dip::uint a, dip::uint b ) { return std::abs( eigenvalues[ b ] ) < std::abs( eigenvalues[ a ] ); } );\n      for( dip::uint ii = 0; ii < n; ++ii ) {\n         dip::uint kk = indices[ ii ];\n         lambdas[ ii ] = eigenvalues[ kk ];\n         dip::uint offset = ii * n;\n         for( dip::uint jj = 0; jj < n; ++jj ) {\n            vectors[ jj + offset ] = eigenvectors( jj, kk );\n         }\n      }\n   } else {\n      DIP_ASSERT( lambdas.Stride() >= 0 );\n      Eigen::Map< Eigen::VectorXd, 0, Eigen::InnerStride<> > eigenvalues( lambdas.Pointer(), n, Eigen::InnerStride<>( lambdas.Stride() ));\n      eigenvalues = matrix.selfadjointView< Eigen::Lower >().eigenvalues();\n      std::sort( lambdas, lambdas + n, GreaterMagnitude< dfloat >() );\n   }\n}\n\nvoid SymmetricEigenDecomposition2(\n      ConstSampleIterator< dfloat > input,\n      SampleIterator< dfloat > lambdas,\n      SampleIterator< dfloat > vectors\n) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::Matrix2d const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), Eigen::InnerStride<>( input.Stride() ));\n   if( vectors ) {\n      Eigen::SelfAdjointEigenSolver< Eigen::Matrix2d > eigensolver( matrix );\n      //if( eigensolver.info() != Eigen::Success ) { abort(); }\n      Eigen::Vector2d const& eigenvalues = eigensolver.eigenvalues();\n      Eigen::Matrix2d const& eigenvectors = eigensolver.eigenvectors();\n      dip::uint indices0 = 0;\n      dip::uint indices1 = 1;\n      if( std::abs( eigenvalues[ 0 ] ) < std::abs( eigenvalues[ 1 ] )) {\n         indices0 = 1;\n         indices1 = 0;\n      }\n      lambdas[ 0 ] = eigenvalues[ indices0 ];\n      lambdas[ 1 ] = eigenvalues[ indices1 ];\n      vectors[ 0 ] = eigenvectors( 0, indices0 );\n      vectors[ 1 ] = eigenvectors( 1, indices0 );\n      vectors[ 2 ] = eigenvectors( 0, indices1 );\n      vectors[ 3 ] = eigenvectors( 1, indices1 );\n   } else {\n      DIP_ASSERT( lambdas.Stride() >= 0 );\n      Eigen::Map< Eigen::Vector2d, 0, Eigen::InnerStride<> > eigenvalues( lambdas.Pointer(), Eigen::InnerStride<>( lambdas.Stride() ));\n      eigenvalues = matrix.selfadjointView< Eigen::Lower >().eigenvalues();\n      if( std::abs( lambdas[ 0 ] ) < std::abs( lambdas[ 1 ] )) {\n         std::swap( lambdas[ 0 ], lambdas[ 1 ] );\n      }\n   }\n}\n\nvoid SymmetricEigenDecomposition3(\n      ConstSampleIterator< dfloat > input,\n      SampleIterator< dfloat > lambdas,\n      SampleIterator< dfloat > vectors\n) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::Matrix3d const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), Eigen::InnerStride<>( input.Stride() ));\n   if( vectors ) {\n      Eigen::SelfAdjointEigenSolver< Eigen::Matrix3d > eigensolver( matrix );\n      //if( eigensolver.info() != Eigen::Success ) { abort(); }\n      Eigen::Vector3d const& eigenvalues = eigensolver.eigenvalues();\n      Eigen::Matrix3d const& eigenvectors = eigensolver.eigenvectors();\n      std::array< dip::uint, 3 > indices{{ 0, 1, 2 }};\n      std::sort( indices.begin(), indices.end(), [ & ]( dip::uint a, dip::uint b ) { return std::abs( eigenvalues[ b ] ) < std::abs( eigenvalues[ a ] ); } );\n      for( dip::uint ii = 0; ii < 3; ++ii ) {\n         dip::uint kk = indices[ ii ];\n         lambdas[ ii ] = eigenvalues[ kk ];\n         dip::uint offset = ii * 3;\n         for( dip::uint jj = 0; jj < 3; ++jj ) {\n            vectors[ jj + offset ] = eigenvectors( jj, kk );\n         }\n      }\n   } else {\n      DIP_ASSERT( lambdas.Stride() >= 0 );\n      Eigen::Map< Eigen::Vector3d, 0, Eigen::InnerStride<> > eigenvalues( lambdas.Pointer(), Eigen::InnerStride<>( lambdas.Stride() ));\n      eigenvalues = matrix.selfadjointView< Eigen::Lower >().eigenvalues();\n      std::sort( lambdas, lambdas + 3, GreaterMagnitude< dfloat >() );\n   }\n}\n\nvoid LargestEigenvector(\n      dip::uint n,\n      ConstSampleIterator< dfloat > input,\n      SampleIterator< dfloat > vector\n) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXd const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), n, n, Eigen::InnerStride<>( input.Stride() ));\n   Eigen::SelfAdjointEigenSolver< Eigen::MatrixXd > eigensolver( matrix );\n   //if( eigensolver.info() != Eigen::Success ) { abort(); }\n   Eigen::VectorXd const& eigenvalues = eigensolver.eigenvalues();\n   Eigen::MatrixXd const& eigenvectors = eigensolver.eigenvectors();\n   std::vector< dip::uint > indices( n );\n   std::iota( indices.begin(), indices.end(), 0 );\n   std::sort( indices.begin(), indices.end(), [ & ]( dip::uint a, dip::uint b ) { return std::abs( eigenvalues[ b ] ) < std::abs( eigenvalues[ a ] ); } );\n   dip::uint kk = indices[ 0 ];\n   for( dip::uint jj = 0; jj < n; ++jj ) {\n      vector[ jj ] = eigenvectors( jj, kk );\n   }\n}\n\nvoid SmallestEigenvector(\n      dip::uint n,\n      ConstSampleIterator< dfloat > input,\n      SampleIterator< dfloat > vector\n) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXd const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), n, n, Eigen::InnerStride<>( input.Stride() ));\n   Eigen::SelfAdjointEigenSolver< Eigen::MatrixXd > eigensolver( matrix );\n   //if( eigensolver.info() != Eigen::Success ) { abort(); }\n   Eigen::VectorXd const& eigenvalues = eigensolver.eigenvalues();\n   Eigen::MatrixXd const& eigenvectors = eigensolver.eigenvectors();\n   std::vector< dip::uint > indices( n );\n   std::iota( indices.begin(), indices.end(), 0 );\n   std::sort( indices.begin(), indices.end(), [ & ]( dip::uint a, dip::uint b ) { return std::abs( eigenvalues[ b ] ) < std::abs( eigenvalues[ a ] ); } );\n   dip::uint kk = indices.back();\n   for( dip::uint jj = 0; jj < n; ++jj ) {\n      vector[ jj ] = eigenvectors( jj, kk );\n   }\n}\n\nvoid EigenDecomposition(\n      dip::uint n,\n      ConstSampleIterator< dfloat > input,\n      SampleIterator< dcomplex > lambdas,\n      SampleIterator< dcomplex > vectors\n) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXd const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), n, n, Eigen::InnerStride<>( input.Stride() ));\n   if( vectors ) {\n      Eigen::EigenSolver< Eigen::MatrixXd > eigensolver( matrix );\n      Eigen::VectorXcd const& eigenvalues = eigensolver.eigenvalues();\n      Eigen::MatrixXcd const& eigenvectors = eigensolver.eigenvectors();\n      std::vector< dip::uint > indices( n );\n      std::iota( indices.begin(), indices.end(), 0 );\n      std::sort( indices.begin(), indices.end(), [ & ]( dip::uint a, dip::uint b ) { return std::abs( eigenvalues[ b ] ) < std::abs( eigenvalues[ a ] ); } );\n      for( dip::uint ii = 0; ii < n; ++ii ) {\n         dip::uint kk = indices[ ii ];\n         lambdas[ ii ] = eigenvalues[ kk ];\n         dip::uint offset = ii * n;\n         for( dip::uint jj = 0; jj < n; ++jj ) {\n            vectors[ jj + offset ] = eigenvectors( jj, kk );\n         }\n      }\n   } else {\n      DIP_ASSERT( lambdas.Stride() >= 0 );\n      Eigen::Map< Eigen::VectorXcd, 0, Eigen::InnerStride<> > eigenvalues( lambdas.Pointer(), n, Eigen::InnerStride<>( lambdas.Stride() ));\n      eigenvalues = matrix.eigenvalues();\n      std::sort( lambdas, lambdas + n, GreaterMagnitude< dcomplex >() );\n   }\n}\n\nvoid EigenDecomposition(\n      dip::uint n,\n      ConstSampleIterator< dcomplex > input,\n      SampleIterator< dcomplex > lambdas,\n      SampleIterator< dcomplex > vectors\n) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXcd const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), n, n, Eigen::InnerStride<>( input.Stride() ));\n   if( vectors ) {\n      Eigen::ComplexEigenSolver< Eigen::MatrixXcd > eigensolver( matrix );\n      Eigen::VectorXcd const& eigenvalues = eigensolver.eigenvalues();\n      Eigen::MatrixXcd const& eigenvectors = eigensolver.eigenvectors();\n      std::vector< dip::uint > indices( n );\n      std::iota( indices.begin(), indices.end(), 0 );\n      std::sort( indices.begin(), indices.end(), [ & ]( dip::uint a, dip::uint b ) { return std::abs( eigenvalues[ b ] ) < std::abs( eigenvalues[ a ] ); } );\n      for( dip::uint ii = 0; ii < n; ++ii ) {\n         dip::uint kk = indices[ ii ];\n         lambdas[ ii ] = eigenvalues[ kk ];\n         dip::uint offset = ii * n;\n         for( dip::uint jj = 0; jj < n; ++jj ) {\n            vectors[ jj + offset ] = eigenvectors( jj, kk );\n         }\n      }\n   } else {\n      DIP_ASSERT( lambdas.Stride() >= 0 );\n      Eigen::Map< Eigen::VectorXcd, 0, Eigen::InnerStride<> > eigenvalues( lambdas.Pointer(), n, Eigen::InnerStride<>( lambdas.Stride() ));\n      eigenvalues = matrix.eigenvalues();\n      std::sort( lambdas, lambdas + n, GreaterMagnitude< dcomplex >() );\n   }\n}\n\ndfloat Determinant( dip::uint n, ConstSampleIterator< dfloat > input ) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXd const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), n, n, Eigen::InnerStride<>( input.Stride() ));\n   return matrix.determinant();\n}\n\ndcomplex Determinant( dip::uint n, ConstSampleIterator< dcomplex > input ) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXcd const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), n, n, Eigen::InnerStride<>( input.Stride() ));\n   return matrix.determinant();\n}\n\nvoid SingularValueDecomposition(\n      dip::uint m,\n      dip::uint n,\n      ConstSampleIterator< dfloat > input,\n      SampleIterator< dfloat > Sout,\n      SampleIterator< dfloat > Uout,\n      SampleIterator< dfloat > Vout\n) {\n   dip::uint p = std::min( m, n );\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXd const, 0, Eigen::InnerStride<> > M( input.Pointer(), m, n, Eigen::InnerStride<>( input.Stride() ));\n   Eigen::JacobiSVD< Eigen::MatrixXd > svd( M, Eigen::ComputeThinU | Eigen::ComputeThinV );\n   DIP_ASSERT( Sout.Stride() >= 0 );\n   Eigen::Map< Eigen::VectorXd, 0, Eigen::InnerStride<> > S( Sout.Pointer(), p, Eigen::InnerStride<>( Sout.Stride() ));\n   S = svd.singularValues();\n   if( Uout && Vout ) {\n      DIP_ASSERT( Uout.Stride() >= 0 );\n      Eigen::Map< Eigen::MatrixXd, 0, Eigen::InnerStride<> > U( Uout.Pointer(), m, p, Eigen::InnerStride<>( Uout.Stride() ));\n      DIP_ASSERT( Vout.Stride() >= 0 );\n      Eigen::Map< Eigen::MatrixXd, 0, Eigen::InnerStride<> > V( Vout.Pointer(), n, p, Eigen::InnerStride<>( Vout.Stride() ));\n      U = svd.matrixU();\n      V = svd.matrixV();\n   }\n}\n\nvoid SingularValueDecomposition(\n      dip::uint m,\n      dip::uint n,\n      ConstSampleIterator< dcomplex > input,\n      SampleIterator< dcomplex > Sout,\n      SampleIterator< dcomplex > Uout,\n      SampleIterator< dcomplex > Vout\n) {\n   dip::uint p = std::min( m, n );\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXcd const, 0, Eigen::InnerStride<> > M( input.Pointer(), m, n, Eigen::InnerStride<>( input.Stride() ));\n   Eigen::JacobiSVD< Eigen::MatrixXcd > svd( M, Eigen::ComputeThinU | Eigen::ComputeThinV );\n   DIP_ASSERT( Sout.Stride() >= 0 );\n   Eigen::Map< Eigen::VectorXcd, 0, Eigen::InnerStride<> > S( Sout.Pointer(), p, Eigen::InnerStride<>( Sout.Stride() ));\n   S = svd.singularValues();\n   if( Uout && Vout ) {\n      DIP_ASSERT( Uout.Stride() >= 0 );\n      Eigen::Map< Eigen::MatrixXcd, 0, Eigen::InnerStride<> > U( Uout.Pointer(), m, p, Eigen::InnerStride<>( Uout.Stride() ));\n      DIP_ASSERT( Vout.Stride() >= 0 );\n      Eigen::Map< Eigen::MatrixXcd, 0, Eigen::InnerStride<> > V( Vout.Pointer(), n, p, Eigen::InnerStride<>( Vout.Stride() ));\n      U = svd.matrixU();\n      V = svd.matrixV();\n   }\n}\n\nvoid Inverse( dip::uint n, ConstSampleIterator< dfloat > input, SampleIterator< dfloat > output ) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXd const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), n, n, Eigen::InnerStride<>( input.Stride() ));\n   DIP_ASSERT( output.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXd, 0, Eigen::InnerStride<> > result( output.Pointer(), n, n, Eigen::InnerStride<>( output.Stride() ));\n   result = matrix.inverse();\n}\n\nvoid Inverse( dip::uint n, ConstSampleIterator< dcomplex > input, SampleIterator< dcomplex > output ) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXcd const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), n, n, Eigen::InnerStride<>( input.Stride() ));\n   DIP_ASSERT( output.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXcd, 0, Eigen::InnerStride<> > result( output.Pointer(), n, n, Eigen::InnerStride<>( output.Stride() ));\n   result = matrix.inverse();\n}\n\nvoid PseudoInverse(\n      dip::uint m,\n      dip::uint n,\n      ConstSampleIterator< dfloat > input,\n      SampleIterator< dfloat > output,\n      dfloat tolerance\n) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXd const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), m, n, Eigen::InnerStride<>( input.Stride() ));\n   Eigen::JacobiSVD< Eigen::MatrixXd > svd( matrix, Eigen::ComputeThinU | Eigen::ComputeThinV );\n   tolerance = tolerance * static_cast< dfloat >( std::max( m, n )) * svd.singularValues().array().abs()( 0 );\n   DIP_ASSERT( output.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXd, 0, Eigen::InnerStride<> > result( output.Pointer(), n, m, Eigen::InnerStride<>( output.Stride() ));\n   result = svd.matrixV() *\n            ( svd.singularValues().array().abs() > tolerance ).select( svd.singularValues().array().inverse(), 0 )\n                                                              .matrix().asDiagonal()\n            * svd.matrixU().adjoint();\n}\n\nvoid PseudoInverse(\n      dip::uint m,\n      dip::uint n,\n      ConstSampleIterator< dcomplex > input,\n      SampleIterator< dcomplex > output,\n      dfloat tolerance\n) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXcd const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), m, n, Eigen::InnerStride<>( input.Stride() ));\n   Eigen::JacobiSVD< Eigen::MatrixXcd > svd( matrix, Eigen::ComputeThinU | Eigen::ComputeThinV );\n   tolerance = tolerance * static_cast< dfloat >( std::max( m, n )) * svd.singularValues().array().abs()( 0 );\n   DIP_ASSERT( output.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXcd, 0, Eigen::InnerStride<> > result( output.Pointer(), n, m, Eigen::InnerStride<>( output.Stride() ));\n   result = svd.matrixV() *\n            ( svd.singularValues().array().abs() > tolerance ).select( svd.singularValues().array().inverse(), 0 )\n                                                              .matrix().asDiagonal()\n            * svd.matrixU().adjoint();\n}\n\ndip::uint Rank( dip::uint m, dip::uint n, ConstSampleIterator< dfloat > input ) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXd const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), m, n, Eigen::InnerStride<>( input.Stride() ));\n   Eigen::CompleteOrthogonalDecomposition< Eigen::MatrixXd > decomposition( matrix );\n   return static_cast< dip::uint >( decomposition.rank() );\n}\n\ndip::uint Rank( dip::uint m, dip::uint n, ConstSampleIterator< dcomplex > input ) {\n   DIP_ASSERT( input.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXcd const, 0, Eigen::InnerStride<> > matrix( input.Pointer(), m, n, Eigen::InnerStride<>( input.Stride() ));\n   Eigen::CompleteOrthogonalDecomposition< Eigen::MatrixXcd > decomposition( matrix );\n   return static_cast< dip::uint >( decomposition.rank() );\n}\n\nvoid Solve(\n      dip::uint m,\n      dip::uint n,\n      ConstSampleIterator< dfloat > A,\n      ConstSampleIterator< dfloat > b,\n      SampleIterator< dfloat > output\n) {\n   DIP_ASSERT( A.Stride() >= 0 );\n   DIP_ASSERT( b.Stride() >= 0 );\n   Eigen::Map< Eigen::MatrixXd const, 0, Eigen::InnerStride<> > matrix( A.Pointer(), m, n, Eigen::InnerStride<>( A.Stride() ));\n   Eigen::JacobiSVD< Eigen::MatrixXd > svd( matrix, Eigen::ComputeThinU | Eigen::ComputeThinV );\n   Eigen::Map< Eigen::VectorXd const, 0, Eigen::InnerStride<> > vector( b.Pointer(), m, Eigen::InnerStride<>( b.Stride() ));\n   Eigen::Map< Eigen::VectorXd, 0, Eigen::InnerStride<> > result( output.Pointer(), n, Eigen::InnerStride<>( output.Stride() ));\n   result = svd.solve( vector );\n}\n\n} // namespace dip\n\n\n#if defined(__GNUG__) || defined(__clang__)\n#pragma GCC diagnostic pop\n#endif\n\n\n#ifdef DIP_CONFIG_ENABLE_DOCTEST\n#include \"doctest.h\"\n\nDOCTEST_TEST_CASE(\"[DIPlib] testing the EigenDecomposition functions\") {\n   // Test generic symmetric code with 2x2 matrix\n   dip::dfloat matrix2[] = { 4, 8, 0 };\n   dip::dfloat lambdas[ 3 ];\n   dip::dfloat vectors[ 9 ];\n   dip::SymmetricEigenDecompositionPacked( 2, matrix2, lambdas );\n   DOCTEST_CHECK( lambdas[ 0 ] == 8 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 4 );\n   dip::SymmetricEigenDecompositionPacked( 2, matrix2, lambdas, vectors );\n   DOCTEST_CHECK( lambdas[ 0 ] == 8 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 4 );\n   DOCTEST_CHECK( vectors[ 0 ] == 0 );\n   DOCTEST_CHECK( vectors[ 1 ] == 1 );\n   DOCTEST_CHECK( vectors[ 2 ] == 1 );\n   DOCTEST_CHECK( vectors[ 3 ] == 0 );\n   matrix2[ 0 ] = 8;\n   matrix2[ 1 ] = 4;\n   dip::SymmetricEigenDecompositionPacked( 2, matrix2, lambdas );\n   DOCTEST_CHECK( lambdas[ 0 ] == 8 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 4 );\n   dip::SymmetricEigenDecompositionPacked( 2, matrix2, lambdas, vectors );\n   DOCTEST_CHECK( lambdas[ 0 ] == 8 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 4 );\n   DOCTEST_CHECK( vectors[ 0 ] == 1 );\n   DOCTEST_CHECK( vectors[ 1 ] == 0 );\n   DOCTEST_CHECK( vectors[ 2 ] == 0 );\n   DOCTEST_CHECK( vectors[ 3 ] == 1 );\n   matrix2[ 0 ] = 3;\n   matrix2[ 1 ] = 3;\n   matrix2[ 2 ] = -1;\n   dip::SymmetricEigenDecompositionPacked( 2, matrix2, lambdas );\n   DOCTEST_CHECK( lambdas[ 0 ] == 4 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 2 );\n   dip::SymmetricEigenDecompositionPacked( 2, matrix2, lambdas, vectors );\n   DOCTEST_CHECK( lambdas[ 0 ] == 4 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 2 );\n   DOCTEST_CHECK( vectors[ 0 ] == doctest::Approx(  std::cos( dip::pi/4 ))); // signs might be different here...\n   DOCTEST_CHECK( vectors[ 1 ] == doctest::Approx( -std::sin( dip::pi/4 )));\n   DOCTEST_CHECK( vectors[ 2 ] == doctest::Approx(  std::sin( dip::pi/4 )));\n   DOCTEST_CHECK( vectors[ 3 ] == doctest::Approx(  std::cos( dip::pi/4 )));\n\n   // Test 2x2-specific symmetric code\n   dip::dfloat matrix2f[] = { 4, 0, 0, 8 };\n   dip::SymmetricEigenDecomposition2( matrix2f, lambdas );\n   DOCTEST_CHECK( lambdas[ 0 ] == 8 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 4 );\n   dip::SymmetricEigenDecomposition2( matrix2f, lambdas, vectors );\n   DOCTEST_CHECK( lambdas[ 0 ] == 8 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 4 );\n   DOCTEST_CHECK( vectors[ 0 ] == 0 );\n   DOCTEST_CHECK( vectors[ 1 ] == 1 );\n   DOCTEST_CHECK( vectors[ 2 ] == 1 );\n   DOCTEST_CHECK( vectors[ 3 ] == 0 );\n   matrix2f[ 0 ] = 8;\n   matrix2f[ 3 ] = 4;\n   dip::SymmetricEigenDecomposition2( matrix2f, lambdas );\n   DOCTEST_CHECK( lambdas[ 0 ] == 8 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 4 );\n   dip::SymmetricEigenDecomposition2( matrix2f, lambdas, vectors );\n   DOCTEST_CHECK( lambdas[ 0 ] == 8 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 4 );\n   DOCTEST_CHECK( vectors[ 0 ] == 1 );\n   DOCTEST_CHECK( vectors[ 1 ] == 0 );\n   DOCTEST_CHECK( vectors[ 2 ] == 0 );\n   DOCTEST_CHECK( vectors[ 3 ] == 1 );\n   matrix2f[ 0 ] = 3;\n   matrix2f[ 1 ] = -1;\n   matrix2f[ 2 ] = -1;\n   matrix2f[ 3 ] = 3;\n   dip::SymmetricEigenDecomposition2( matrix2f, lambdas );\n   DOCTEST_CHECK( lambdas[ 0 ] == 4 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 2 );\n   dip::SymmetricEigenDecomposition2( matrix2f, lambdas, vectors );\n   DOCTEST_CHECK( lambdas[ 0 ] == 4 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 2 );\n   DOCTEST_CHECK( vectors[ 0 ] == doctest::Approx(  std::cos( dip::pi/4 ))); // signs might be different here...\n   DOCTEST_CHECK( vectors[ 1 ] == doctest::Approx( -std::sin( dip::pi/4 )));\n   DOCTEST_CHECK( vectors[ 2 ] == doctest::Approx(  std::sin( dip::pi/4 )));\n   DOCTEST_CHECK( vectors[ 3 ] == doctest::Approx(  std::cos( dip::pi/4 )));\n\n   // Test generic symmetric code with 3x3 matrix\n   dip::dfloat matrix3[] = { 3, 1.5, 1.5, 0.0, 0.0, -0.5 };\n   dip::SymmetricEigenDecompositionPacked( 3, matrix3, lambdas );\n   DOCTEST_CHECK( lambdas[ 0 ] == 3 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 2 );\n   DOCTEST_CHECK( lambdas[ 2 ] == 1 );\n   dip::SymmetricEigenDecompositionPacked( 3, matrix3, lambdas, vectors );\n   DOCTEST_CHECK( lambdas[ 0 ] == 3 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 2 );\n   DOCTEST_CHECK( lambdas[ 2 ] == 1 );\n   DOCTEST_CHECK( vectors[ 0 ] == doctest::Approx(  1.0 ));\n   DOCTEST_CHECK( vectors[ 1 ] == doctest::Approx(  0.0 ));\n   DOCTEST_CHECK( vectors[ 2 ] == doctest::Approx(  0.0 ));\n   DOCTEST_CHECK( vectors[ 3 ] == doctest::Approx(  0.0 ));\n   DOCTEST_CHECK( vectors[ 4 ] == doctest::Approx(  1.0 / std::sqrt( 2.0 )));\n   DOCTEST_CHECK( vectors[ 5 ] == doctest::Approx( -1.0 / std::sqrt( 2.0 )));\n   DOCTEST_CHECK( vectors[ 6 ] == doctest::Approx(  0.0 ));\n   DOCTEST_CHECK( vectors[ 7 ] == doctest::Approx(  1.0 / std::sqrt( 2.0 )));\n   DOCTEST_CHECK( vectors[ 8 ] == doctest::Approx(  1.0 / std::sqrt( 2.0 )));\n\n   // Test 3x3-specific symmetric code\n   dip::dfloat matrix3f[] = { 3, 0.0, 0.0, 0.0, 1.5, -0.5, 0.0, -0.5, 1.5 };\n   dip::SymmetricEigenDecomposition3( matrix3f, lambdas );\n   DOCTEST_CHECK( lambdas[ 0 ] == 3 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 2 );\n   DOCTEST_CHECK( lambdas[ 2 ] == 1 );\n   dip::SymmetricEigenDecomposition3( matrix3f, lambdas, vectors );\n   DOCTEST_CHECK( lambdas[ 0 ] == 3 );\n   DOCTEST_CHECK( lambdas[ 1 ] == 2 );\n   DOCTEST_CHECK( lambdas[ 2 ] == 1 );\n   DOCTEST_CHECK( vectors[ 0 ] == doctest::Approx(  1.0 ));\n   DOCTEST_CHECK( vectors[ 1 ] == doctest::Approx(  0.0 ));\n   DOCTEST_CHECK( vectors[ 2 ] == doctest::Approx(  0.0 ));\n   DOCTEST_CHECK( vectors[ 3 ] == doctest::Approx(  0.0 ));\n   DOCTEST_CHECK( vectors[ 4 ] == doctest::Approx(  1.0 / std::sqrt( 2.0 )));\n   DOCTEST_CHECK( vectors[ 5 ] == doctest::Approx( -1.0 / std::sqrt( 2.0 )));\n   DOCTEST_CHECK( vectors[ 6 ] == doctest::Approx(  0.0 ));\n   DOCTEST_CHECK( vectors[ 7 ] == doctest::Approx(  1.0 / std::sqrt( 2.0 )));\n   DOCTEST_CHECK( vectors[ 8 ] == doctest::Approx(  1.0 / std::sqrt( 2.0 )));\n\n   // Test generic non-symmetric code with 2x2 matrix\n   dip::dfloat matrix22[] = { 3, -1, -1, 3 };\n   dip::dcomplex c_lambdas[ 2 ];\n   dip::dcomplex c_vectors[ 4 ];\n   dip::EigenDecomposition( 2, matrix22, c_lambdas, c_vectors );\n   DOCTEST_CHECK( c_lambdas[ 0 ].real() == doctest::Approx( 4.0 ));\n   DOCTEST_CHECK( c_lambdas[ 1 ].real() == doctest::Approx( 2.0 ));\n   DOCTEST_CHECK( c_vectors[ 0 ].real() == doctest::Approx(  cos( dip::pi/4 ))); // signs might be different here...\n   DOCTEST_CHECK( c_vectors[ 1 ].real() == doctest::Approx( -sin( dip::pi/4 )));\n   DOCTEST_CHECK( c_vectors[ 2 ].real() == doctest::Approx(  sin( dip::pi/4 )));\n   DOCTEST_CHECK( c_vectors[ 3 ].real() == doctest::Approx(  cos( dip::pi/4 )));\n   DOCTEST_CHECK( c_lambdas[ 0 ].imag() == 0 );\n   DOCTEST_CHECK( c_lambdas[ 1 ].imag() == 0 );\n   DOCTEST_CHECK( c_vectors[ 0 ].imag() == 0 );\n   DOCTEST_CHECK( c_vectors[ 1 ].imag() == 0 );\n   DOCTEST_CHECK( c_vectors[ 2 ].imag() == 0 );\n   DOCTEST_CHECK( c_vectors[ 3 ].imag() == 0 );\n\n}\n\nDOCTEST_TEST_CASE(\"[DIPlib] testing the SingularValueDecomposition and related functions\") {\n   dip::dfloat matrix22[] = { 4, 0, 0, 8 };\n   dip::dfloat S[ 2 ];\n   dip::dfloat U[ 4 ];\n   dip::dfloat V[ 6 ];\n   dip::SingularValueDecomposition( 2, 2, matrix22, S, U, V );\n   DOCTEST_CHECK( S[ 0 ] == 8 );\n   DOCTEST_CHECK( S[ 1 ] == 4 );\n   DOCTEST_CHECK( U[ 0 ] == 0 );\n   DOCTEST_CHECK( U[ 1 ] == 1 );\n   DOCTEST_CHECK( U[ 2 ] == 1 );\n   DOCTEST_CHECK( U[ 3 ] == 0 );\n   DOCTEST_CHECK( V[ 0 ] == 0 );\n   DOCTEST_CHECK( V[ 1 ] == 1 );\n   DOCTEST_CHECK( V[ 2 ] == 1 );\n   DOCTEST_CHECK( V[ 3 ] == 0 );\n\n   dip::dfloat matrix23[] = { 3, 2, 2, 3, 2, -2 };\n   dip::SingularValueDecomposition( 2, 3, matrix23, S, U, V );\n   DOCTEST_CHECK( S[ 0 ] == doctest::Approx( 5.0 ));\n   DOCTEST_CHECK( S[ 1 ] == doctest::Approx( 3.0 ));\n   DOCTEST_CHECK( U[ 0 ] == doctest::Approx( -1.0 / std::sqrt( 2 ))); // signs might be different here...\n   DOCTEST_CHECK( U[ 1 ] == doctest::Approx( -1.0 / std::sqrt( 2 )));\n   DOCTEST_CHECK( U[ 2 ] == doctest::Approx( 1.0 / std::sqrt( 2 )));\n   DOCTEST_CHECK( U[ 3 ] == doctest::Approx( -1.0 / std::sqrt( 2 )));\n   DOCTEST_CHECK( V[ 0 ] == doctest::Approx( -1.0 / std::sqrt( 2 )));\n   DOCTEST_CHECK( V[ 1 ] == doctest::Approx( -1.0 / std::sqrt( 2 )));\n   DOCTEST_CHECK( V[ 2 ] == doctest::Approx( 0.0 ));\n   DOCTEST_CHECK( V[ 3 ] == doctest::Approx( 1.0 / std::sqrt( 18 )));\n   DOCTEST_CHECK( V[ 4 ] == doctest::Approx( -1.0 / std::sqrt( 18 )));\n   DOCTEST_CHECK( V[ 5 ] == doctest::Approx( 4.0 / std::sqrt( 18 )));\n\n   DOCTEST_CHECK( dip::Rank( 2, 3, matrix23 ) == 2 );\n\n   dip::dfloat matrix32[ 6 ];\n   dip::PseudoInverse( 2, 3, matrix23, matrix32 );\n   DOCTEST_CHECK( matrix32[ 0 ] == doctest::Approx( 28.0 / 180.0 ));\n   DOCTEST_CHECK( matrix32[ 1 ] == doctest::Approx(  8.0 / 180.0 ));\n   DOCTEST_CHECK( matrix32[ 2 ] == doctest::Approx( 40.0 / 180.0 ));\n   DOCTEST_CHECK( matrix32[ 3 ] == doctest::Approx(  8.0 / 180.0 ));\n   DOCTEST_CHECK( matrix32[ 4 ] == doctest::Approx( 28.0 / 180.0 ));\n   DOCTEST_CHECK( matrix32[ 5 ] == doctest::Approx(-40.0 / 180.0 ));\n\n   dip::dfloat b[ 3 ] = { 44.0 / 180.0, 64.0 / 180.0, -40.0 / 180.0 };\n   dip::dfloat x[ 2 ];\n   dip::Solve( 3, 2, matrix32, b, x );\n   DOCTEST_CHECK( x[ 0 ] == doctest::Approx( 1.0 ));\n   DOCTEST_CHECK( x[ 1 ] == doctest::Approx( 2.0 ));\n}\n\n#endif // DIP_CONFIG_ENABLE_DOCTEST\n", "meta": {"hexsha": "56371c3e231df6f6bf57942ed10d4271516d7ff2", "size": 27571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/support/matrix.cpp", "max_stars_repo_name": "DIPlib/diplib", "max_stars_repo_head_hexsha": "eaf03372264f050bcda2d49bdf443702308ba303", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 140.0, "max_stars_repo_stars_event_min_datetime": "2017-04-04T23:10:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T18:21:34.000Z", "max_issues_repo_path": "src/support/matrix.cpp", "max_issues_repo_name": "DIPlib/diplib", "max_issues_repo_head_hexsha": "eaf03372264f050bcda2d49bdf443702308ba303", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 98.0, "max_issues_repo_issues_event_min_datetime": "2018-01-13T23:16:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T14:45:37.000Z", "max_forks_repo_path": "src/support/matrix.cpp", "max_forks_repo_name": "DIPlib/diplib", "max_forks_repo_head_hexsha": "eaf03372264f050bcda2d49bdf443702308ba303", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2017-04-11T20:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T18:21:36.000Z", "avg_line_length": 46.3378151261, "max_line_length": 202, "alphanum_fraction": 0.6158644953, "num_tokens": 8860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5217646766038495}}
{"text": "\n#include <cmath>\n#include <memory>\n#include <vector>\n\n#include <Eigen/Core>\n#include <gtest/gtest.h>\n\n#include \"test/utils.hpp\"\n\n#include \"ldaplusplus/Document.hpp\"\n#include \"ldaplusplus/em/FastSupervisedEStep.hpp\"\n#include \"ldaplusplus/Parameters.hpp\"\n#include \"ldaplusplus/em/SupervisedEStep.hpp\"\n#include \"ldaplusplus/e_step_utils.hpp\"\n\nusing namespace Eigen;\nusing namespace ldaplusplus;\n\n\n// T will be available as TypeParam in TYPED_TEST functions\ntemplate <typename T>\nclass TestExpectationStep : public ParameterizedTest<T> {};\n\nTYPED_TEST_CASE(TestExpectationStep, ForFloatAndDouble);\n\nTYPED_TEST(TestExpectationStep, ComputeH) {\n    VectorXi X(10);\n    X << 10, 9, 8, 7, 6, 5, 4, 3, 2, 1;\n    VectorX<TypeParam> X_ratio = X.cast<TypeParam>() / X.sum();\n\n    MatrixX<TypeParam> eta = MatrixX<TypeParam>::Random(5, 3);\n    MatrixX<TypeParam> phi = MatrixX<TypeParam>::Random(5, 10);\n    phi.array() -= phi.minCoeff();\n    phi = phi.array().rowwise() / phi.colwise().sum().array();\n    VectorX<TypeParam> h(5);\n\n    e_step_utils::compute_h<TypeParam>(X, X_ratio, eta, phi, h);\n\n    VectorX<TypeParam> hphi = h.transpose() * phi;\n\n    TypeParam hphi_actual = 0;\n    for (int y=0; y<3; y++) {\n        TypeParam p = 1;\n        for (int n=0; n<10; n++) {\n            TypeParam t = 0;\n            for (int k=0; k<5; k++) {\n                t += phi(k, n) * exp( X.cast<TypeParam>()(n)/X.sum() * eta(k, y) );\n            }\n            p *= t;\n        }\n        hphi_actual += p;\n    }\n\n    EXPECT_NEAR(hphi_actual, hphi(9), 1e-2);\n}\n\n\nTYPED_TEST(TestExpectationStep, ComputeLikelihood) {\n    for (int i=0; i<100; i++) {\n        VectorX<TypeParam> Xtmp = VectorX<TypeParam>::Random(10).array().abs() * 5;\n        VectorXi X = Xtmp.template cast<int>();\n        VectorX<TypeParam> X_ratio = X.cast<TypeParam>() / X.sum();\n        int y = 0;\n        VectorX<TypeParam> alpha = VectorX<TypeParam>::Constant(5, 0.1);\n        MatrixX<TypeParam> beta = MatrixX<TypeParam>::Random(5, 10);\n        MatrixX<TypeParam> eta = MatrixX<TypeParam>::Random(5, 3);\n        MatrixX<TypeParam> phi = MatrixX<TypeParam>::Constant(5, 10, 0.1);\n        VectorX<TypeParam> gamma = VectorX<TypeParam>::Constant(5, X.sum() / 5.0);\n\n        // normalize beta, phi\n        phi.array() -= phi.minCoeff() - 0.001;\n        phi.array().rowwise() /= phi.colwise().sum().array();\n        beta.array() -= beta.minCoeff() - 0.001;\n        beta.array().rowwise() /= beta.colwise().sum().array();\n\n        TypeParam likelihood = e_step_utils::compute_supervised_likelihood(\n            X,\n            y,\n            alpha,\n            beta,\n            eta,\n            phi,\n            gamma\n        );\n\n        ASSERT_FALSE(std::isnan(likelihood)) << phi.array().log();\n        EXPECT_GT(0, likelihood);\n    }\n}\n\n\nTYPED_TEST(TestExpectationStep, DocEStep) {\n    return;\n\n    VectorX<TypeParam> Xtmp = VectorX<TypeParam>::Random(10).array().abs() * 5;\n    VectorXi X = Xtmp.template cast<int>();\n    int y = 0;\n\n    auto doc = std::make_shared<corpus::ClassificationDecorator>(\n        std::make_shared<corpus::EigenDocument>(X),\n        y\n    );\n\n    VectorX<TypeParam> alpha = VectorX<TypeParam>::Constant(5, 0.2);\n    MatrixX<TypeParam> beta = MatrixX<TypeParam>::Random(5, 10);\n    MatrixX<TypeParam> eta = MatrixX<TypeParam>::Zero(5, 3);\n\n    // normalize beta\n    beta.array() -= beta.minCoeff() - 0.001;\n    beta.array().rowwise() /= beta.colwise().sum().array();\n\n    auto model = std::make_shared<parameters::SupervisedModelParameters<TypeParam> >(\n        alpha,\n        beta,\n        eta\n    );\n\n    size_t fixed_point_iterations = 5;\n    TypeParam convergence_tolerance = -10;\n    std::vector<TypeParam> likelihoods(10);\n    for (int i=0; i<10; i++) {\n        em::SupervisedEStep<TypeParam> e_step(\n            i,\n            convergence_tolerance,\n            fixed_point_iterations\n        );\n        auto vp = std::static_pointer_cast<parameters::VariationalParameters<TypeParam> >(\n            e_step.doc_e_step(\n                doc,\n                model\n            )\n        );\n\n        likelihoods[i] = e_step_utils::compute_supervised_likelihood<TypeParam>(\n            doc->get_words(),\n            doc->get_class(),\n            model->alpha,\n            model->beta,\n            model->eta,\n            vp->phi,\n            vp->gamma\n        );\n    }\n    for (int i=1; i<10; i++) {\n        EXPECT_GT(likelihoods[i], likelihoods[i-1]);\n    }\n}\n\n\nTYPED_TEST(TestExpectationStep, FastDocEStep) {\n    return;\n\n    VectorX<TypeParam> Xtmp = VectorX<TypeParam>::Random(10).array().abs() * 5;\n    VectorXi X = Xtmp.template cast<int>();\n    int y = 0;\n\n    auto doc = std::make_shared<corpus::ClassificationDecorator>(\n        std::make_shared<corpus::EigenDocument>(X),\n        y\n    );\n\n    VectorX<TypeParam> alpha = VectorX<TypeParam>::Constant(5, 0.1);\n    MatrixX<TypeParam> beta = MatrixX<TypeParam>::Random(5, 10);\n    MatrixX<TypeParam> eta = MatrixX<TypeParam>::Random(5, 3);\n\n    // normalize beta\n    beta.array() -= beta.minCoeff() - 0.001;\n    beta.array().rowwise() /= beta.colwise().sum().array();\n\n    auto model = std::make_shared<parameters::SupervisedModelParameters<TypeParam> >(\n        alpha,\n        beta,\n        eta\n    );\n\n    VectorX<TypeParam> h(beta.rows());\n\n    int fixed_point_iterations = 10;\n    TypeParam convergence_tolerance = 0;\n    std::vector<TypeParam> likelihoods(10);\n    for (int i=0; i<10; i++) {\n        em::FastSupervisedEStep<TypeParam> e_step(\n            i,\n            convergence_tolerance,\n            fixed_point_iterations\n        );\n        auto vp = std::static_pointer_cast<parameters::VariationalParameters<TypeParam> >(\n            e_step.doc_e_step(\n                doc,\n                model\n            )\n        );\n        likelihoods[i] = e_step_utils::compute_supervised_likelihood<TypeParam>(\n            doc->get_words(),\n            doc->get_class(),\n            model->alpha,\n            model->beta,\n            model->eta,\n            vp->phi,\n            vp->gamma,\n            h\n        );\n    }\n    for (int i=1; i<10; i++) {\n        EXPECT_GT(likelihoods[i], likelihoods[i-1]);\n    }\n}\n", "meta": {"hexsha": "6998b269b2ed490d3e546712bfa9106f6be3b097", "size": 6144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_expectation_step.cpp", "max_stars_repo_name": "angeloskath/supervised-lda", "max_stars_repo_head_hexsha": "fe3a39bb0d6c7d0c2a33f069440869ad70774da8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-05-25T11:59:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T08:51:41.000Z", "max_issues_repo_path": "test/test_expectation_step.cpp", "max_issues_repo_name": "angeloskath/supervised-lda", "max_issues_repo_head_hexsha": "fe3a39bb0d6c7d0c2a33f069440869ad70774da8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2016-06-30T15:51:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T10:43:16.000Z", "max_forks_repo_path": "test/test_expectation_step.cpp", "max_forks_repo_name": "angeloskath/supervised-lda", "max_forks_repo_head_hexsha": "fe3a39bb0d6c7d0c2a33f069440869ad70774da8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-09-28T14:58:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T14:22:38.000Z", "avg_line_length": 29.3971291866, "max_line_length": 90, "alphanum_fraction": 0.5828450521, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5217646662367728}}
{"text": "/**\n * @file Sonar.cpp\n * @brief Projection functions for imaging sonar, e.g. DIDSON\n * @author: Michael Kaess\n * @date: Aug 2014\n */\n\n#include <iostream>\n#include <vector>\n#include <utility>\n\n#include <Eigen/Dense>\n\n#include \"Sonar.h\"\n\nusing namespace std;\nusing namespace isam;\nusing namespace Eigen;\n\nnamespace sonar {\n\nSonar::Sonar(double rMin, double rMax, double bearingFov, double elevationFov,\n    int numBearings, int numRanges) :\n    _rMin(rMin), _rMax(rMax), _bearingFov(bearingFov), _elevationFov(\n        elevationFov), _numBearings(numBearings), _numRanges(numRanges) {\n  if (rMax <= rMin) {\n    cout << \"ERROR: rMax must be larger than rMin\" << endl;\n    exit(1);\n  }\n  if (bearingFov <= 0 || elevationFov <= 0) {\n    cout << \"ERROR: bearingFov and elevationFov must be positive\" << endl;\n    exit(1);\n  }\n  if (numBearings <= 0 || numRanges <= 0) {\n    cout << \"ERROR: numBearing and numRanges must be positive\" << endl;\n    exit(1);\n  }\n}\n\nvector<Point3d> Sonar::getFrustum(const isam::Pose3d& pose) const {\n  vector<Point3d> frustum;\n  vector<double> range(2);\n  range[0] = _rMin; range[1] = _rMax;\n  vector<pair<double, double> > angles;\n  double yaw = 0.5 * _bearingFov;\n  double pitch = 0.5 * _elevationFov;\n  angles.push_back(make_pair(-yaw, -pitch));\n  angles.push_back(make_pair(yaw, -pitch));\n  angles.push_back(make_pair(yaw, pitch));\n  angles.push_back(make_pair(-yaw, pitch));\n\n  for (int r = 0; r < 2; r++) {\n    for (int a = 0; a < 4; a++) {\n      yaw = angles[a].first;\n      pitch = angles[a].second;\n      Point3d p_local = Point3d(range[r], 0, 0);\n      Point3d p_sonar = Pose3d(0, 0, 0, yaw, pitch, 0).transform_from(p_local);\n      frustum.push_back(pose.transform_from(p_sonar));\n    }\n  }\n\n  return frustum;\n}\n\nbool Sonar::project(const isam::Pose3d& pose, const isam::Point3d& point,\n    isam::Point2d& projection) const {\n  Point3d point_sonar = pose.transform_to(point);\n  double range = point_sonar.vector().norm();\n  double x = point_sonar.x();\n  double y = point_sonar.y();\n  double z = point_sonar.z();\n  Vector2d direction(point_sonar.x(), point_sonar.y());\n  direction.normalize();\n  Vector2d mapping = direction * range;\n\n  double u = mapping(0);\n  double v = mapping(1);\n  double b = (atan2(v, u) / _bearingFov + 0.5) * _numBearings;\n  double r = (range - _rMin) / (_rMax - _rMin) * _numRanges;\n  double elevation = atan2(z, sqrt(x * x + y * y)) / _elevationFov;\n\n  projection = Point2d(b, r);\n\n  // projection within field of view of sensor?\n  if (b >= 0 && b < _numBearings && r >= 0 && r < _numRanges\n      && elevation >= -0.5 && elevation <= 0.5) {\n    return true;\n  }\n\n  return false;\n}\n\n} /* namespace sonar */\n", "meta": {"hexsha": "4fb929ab9cb5fb567fc7b6caeba5a9e5f7770907", "size": 2668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ts-sonar/Sonar.cpp", "max_stars_repo_name": "mattjr/structured", "max_stars_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "ts-sonar/Sonar.cpp", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "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": "ts-sonar/Sonar.cpp", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 28.3829787234, "max_line_length": 79, "alphanum_fraction": 0.6488005997, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5217646597929234}}
{"text": "// Copyright 2004 The Trustees of Indiana University.\r\n\r\n// Use, modification and distribution is subject to the Boost Software\r\n// License, 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//  Authors: Douglas Gregor\r\n//           Andrew Lumsdaine\r\n\r\n#include <boost/graph/use_mpi.hpp>\r\n#include <boost/throw_exception.hpp>\r\n#include <boost/graph/distributed/page_rank.hpp>\r\n#include <boost/test/minimal.hpp>\r\n#include <boost/graph/distributed/adjacency_list.hpp>\r\n#include <boost/graph/distributed/mpi_process_group.hpp>\r\n#include <boost/test/minimal.hpp>\r\n#include <vector>\r\n#include <iostream>\r\n#include <stdlib.h>\r\n\r\n#ifdef BOOST_NO_EXCEPTIONS\r\nvoid\r\nboost::throw_exception(std::exception const& ex)\r\n{\r\n    std::cout << ex.what() << std::endl;\r\n    abort();\r\n}\r\n#endif\r\n\r\nusing namespace boost;\r\nusing boost::graph::distributed::mpi_process_group;\r\n\r\nbool close_to(double x, double y)\r\n{\r\n  double diff = x - y;\r\n  if (diff < 0) diff = -diff;\r\n  double base = (y == 0? x : y);\r\n  if (base != 0) return diff / base < 0.01;\r\n  else return true;\r\n}\r\n\r\n// Make convenient labels for the vertices\r\nenum vertex_id_t { A, B, C, D, N };\r\n\r\nvoid test_distributed_page_rank(int iterations)\r\n{\r\n  using namespace boost::graph;\r\n\r\n  // create a typedef for the Graph type\r\n  typedef adjacency_list<vecS, \r\n                         distributedS<mpi_process_group, vecS>,\r\n                         bidirectionalS \r\n                         > Graph;\r\n  typedef graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n\r\n  // writing out the edges in the graph\r\n  typedef std::pair<int, int> Edge;\r\n  Edge edge_array[] =\r\n    { Edge(A,B), Edge(A,C), Edge(B,C), Edge(C,A), Edge(D,C) };\r\n  const int num_edges = sizeof(edge_array)/sizeof(edge_array[0]);\r\n\r\n  // declare a graph object\r\n  Graph g(edge_array, edge_array + num_edges, N);\r\n\r\n  std::vector<double> ranks(num_vertices(g));\r\n\r\n  page_rank(g,\r\n            make_iterator_property_map(ranks.begin(),\r\n                                       get(boost::vertex_index, g)),\r\n            n_iterations(iterations), 0.85, N);\r\n  \r\n  double local_sum = 0.0;\r\n  for(unsigned int i = 0; i < num_vertices(g); ++i) {\r\n    std::cout << (char)('A' + g.distribution().global(i)) << \" = \" \r\n              << ranks[i] << std::endl;\r\n    local_sum += ranks[i];\r\n  }\r\n  double sum=0.;\r\n  boost::mpi::reduce(communicator(g.process_group()),\r\n                     local_sum, sum, std::plus<double>(), 0);\r\n  if (process_id(g.process_group()) == 0) {\r\n    std::cout << \"Sum = \" << sum << \"\\n\\n\";\r\n    BOOST_CHECK(close_to(sum, 4)); // 1 when alpha=0\r\n  }\r\n\r\n  //   double expected_ranks0[N] = {0.400009, 0.199993, 0.399998, 0.0};\r\n  double expected_ranks[N] = {1.49011, 0.783296, 1.5766, 0.15};\r\n  for (int i = 0; i < N; ++i) {\r\n    vertex_descriptor v = vertex(i, g);\r\n    if (v != Graph::null_vertex()\r\n        && owner(v) == process_id(g.process_group())) {\r\n      BOOST_CHECK(close_to(ranks[local(v)], expected_ranks[i]));\r\n    }\r\n  }\r\n}\r\n\r\nint test_main(int argc, char* argv[])\r\n{\r\n  mpi::environment env(argc, argv);\r\n\r\n  int iterations = 50;\r\n  if (argc > 1) {\r\n    iterations = atoi(argv[1]);\r\n  }\r\n\r\n  test_distributed_page_rank(iterations);\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "6dc826320b452b1ae668c6db258135e53b2c3be1", "size": 3255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph_parallel/test/distributed_page_rank_test.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_parallel/test/distributed_page_rank_test.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_parallel/test/distributed_page_rank_test.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": 29.5909090909, "max_line_length": 75, "alphanum_fraction": 0.6129032258, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.5217410029010334}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/asinh.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/valmax.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <cmath>\n\nSTF_CASE_TPL (\" asinh\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::asinh;\n  using r_t = decltype(asinh(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t,T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(asinh(bs::Inf<T>()), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(asinh(bs::Minf<T>()), bs::Minf<r_t>(), 0);\n  STF_ULP_EQUAL(asinh(bs::Nan<T>()), bs::Nan<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(asinh(bs::Zero<T>()), bs::Zero<r_t>(), 0);\n  STF_ULP_EQUAL(asinh(bs::Valmax<T>()), std::asinh(bs::Valmax<T>()), 0.5);\n  STF_ULP_EQUAL(asinh(bs::rec(bs::Sqrteps<T>())*2),  std::asinh(bs::rec(bs::Sqrteps<T>())*2), 0.5);\n  STF_ULP_EQUAL(asinh(bs::Eps<T>()), bs::Eps<T>(), 0.5);\n for(T i=T(0.1); i <= T(1.1); i+= T(0.5))\n {\n   T ri =  bs::rec(i);\n   STF_ULP_EQUAL(asinh(i), std::asinh(i), 0.5);\n   STF_ULP_EQUAL(asinh(ri), std::asinh(ri), 0.5);\n }\n}\n\n", "meta": {"hexsha": "ecb0ea90357e5d4d687c729d6d98f571fa701780", "size": 1755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/asinh.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/scalar/asinh.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/asinh.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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": 34.4117647059, "max_line_length": 100, "alphanum_fraction": 0.5948717949, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5217409989537249}}
{"text": "/*\n * Copyright (c) 2010-2012 Steffen Kie\u00df\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\n * THE SOFTWARE.\n */\n\n#ifndef MATH_DIAGMATRIX3_HPP_INCLUDED\n#define MATH_DIAGMATRIX3_HPP_INCLUDED\n\n// Math::DiagMatrix3<T> is a 3x3 matrix where all non-diagonal entries are zero.\n//\n// The difference to Math::Vector3<T> is mostly the effect of operations\n// (Vector3<T> * Vector3<T> is a dot product while DiagMatrix3<T> * Vector3<T>\n// is a matrix-vector-multiplication / an elementwise multiplication)\n\n#include <Core/Assert.hpp>\n#include <Core/Util.hpp>\n\n#include <Math/Forward.hpp>\n#include <Math/DiagMatrix3.hpp>\n\n#include <complex>\n\n#include <boost/type_traits/is_convertible.hpp>\n#include <boost/utility/enable_if.hpp>\n\nnamespace Math {\n  template <typename T> class DiagMatrix3 {\n    Vector3<T> diag_;\n\n    class PrivateType {\n      friend class DiagMatrix3;\n      PrivateType () {}\n    };\n\n  public:\n    DiagMatrix3 () {}\n    explicit DiagMatrix3 (T v) : diag_ (v, v, v) {}\n    DiagMatrix3 (T x, T y, T z) : diag_ (x, y, z) {}\n    template <typename U> explicit DiagMatrix3 (const Vector3<U>& diag) : diag_ (diag) {}\n#if (defined (__clang__) || GCC_VERSION_IS_ATLEAST(4, 6)) && !defined (__CUDACC__)\n#pragma GCC diagnostic push\n#endif\n#pragma GCC diagnostic ignored \"-Wconversion\"\n    template <typename U> DiagMatrix3 (DiagMatrix3<U> v, UNUSED typename boost::enable_if<boost::is_convertible<U, T>, PrivateType>::type dummy = PrivateType ()) : diag_ (v.diag ()) {}\n    template <typename U> explicit DiagMatrix3 (DiagMatrix3<U> v, UNUSED typename boost::disable_if<boost::is_convertible<U, T>, PrivateType>::type dummy = PrivateType ()) : diag_ (v.diag ()) {}\n#if (defined (__clang__) || GCC_VERSION_IS_ATLEAST(4, 6)) && !defined (__CUDACC__)\n#pragma GCC diagnostic pop\n#endif\n\n    const Vector3<T>& diag () const {\n      return diag_;\n    }\n    Vector3<T>& diag () {\n      return diag_;\n    }\n\n    T m11 () const {\n      return diag ().x ();\n    }\n    T m22 () const {\n      return diag ().y ();\n    }\n    T m33 () const {\n      return diag ().z ();\n    }\n\n    T& m11 () {\n      return diag ().x ();\n    }\n    T& m22 () {\n      return diag ().y ();\n    }\n    T& m33 () {\n      return diag ().z ();\n    }\n\n    // off-diagonal entries (read-only, = 0)\n    T m12 () const { return T (); }\n    T m13 () const { return T (); }\n    T m21 () const { return T (); }\n    T m23 () const { return T (); }\n    T m31 () const { return T (); }\n    T m32 () const { return T (); }\n\n    // Return the inverse matrix\n    DiagMatrix3<T> inverse () const {\n      return DiagMatrix3<T> (T (1) / m11 (), T (1) / m22 (), T (1) / m33 ());\n    }\n\n    // Access values on the diagonal\n    const T& operator[] (size_t i) const {\n      return diag ()[i];\n    }\n    T& operator[] (size_t i) {\n      return diag ()[i];\n    }\n  };\n\n  // Operations on DiagMatrix3\n\n#define RTS(op) DECLTYPE ((*(T*)NULL) op (*(U*)NULL))\n#define RT(op) DiagMatrix3<RTS(op)>\n  template <typename T, typename U> inline RT(+) operator+ (DiagMatrix3<T> v1, DiagMatrix3<U> v2) {\n    return RT(+) (v1.m11 () + v2.m11 (), v1.m22 () + v2.m22 (), v1.m33 () + v2.m33 ());\n  }\n\n  template <typename T, typename U> inline DiagMatrix3<T>& operator+= (DiagMatrix3<T>& v1, DiagMatrix3<U> v2) {\n    v1.m11 () += v2.m11 (); v1.m22 () += v2.m22 (); v1.m33 () += v2.m33 ();\n    return v1;\n  }\n\n\n  template <typename T, typename U> inline RT(-) operator- (DiagMatrix3<T> v1, DiagMatrix3<U> v2) {\n    return RT(-) (v1.m11 () - v2.m11 (), v1.m22 () - v2.m22 (), v1.m33 () - v2.m33 ());\n  }\n\n  template <typename T, typename U> inline DiagMatrix3<T>& operator-= (DiagMatrix3<T>& v1, DiagMatrix3<U> v2) {\n    v1.m11 () -= v2.m11 (); v1.m22 () -= v2.m22 (); v1.m33 () -= v2.m33 ();\n    return v1;\n  }\n\n\n  template <typename T, typename U> inline RT(*) operator* (DiagMatrix3<T> v, U scalar) {\n    return RT(*) (v.m11 () * scalar, v.m22 () * scalar, v.m33 () * scalar);\n  }\n\n  template <typename T, typename U> inline RT(*) operator* (T scalar, DiagMatrix3<U> v) {\n    return RT(*) (scalar * v.m11 (), scalar * v.m22 (), scalar * v.m33 ());\n  }\n\n  template <typename T, typename U> inline DiagMatrix3<T>& operator*= (DiagMatrix3<T>& v, U scalar) {\n    v.m11 () *= scalar; v.m22 () *= scalar; v.m33 () *= scalar;\n    return v;\n  }\n\n  template <typename T, typename U> inline RT(/) operator/ (DiagMatrix3<T> v, U scalar) {\n    return RT(/) (v.m11 () / scalar, v.m22 () / scalar, v.m33 () / scalar);\n  }\n\n  template <typename T, typename U> inline DiagMatrix3<T>& operator/= (DiagMatrix3<T>& v, U scalar) {\n    v.m11 () /= scalar; v.m22 () /= scalar; v.m33 () /= scalar;\n    return v;\n  }\n\n  template <typename T> inline bool operator== (DiagMatrix3<T> v1, DiagMatrix3<T> v2) {\n    return v1.m11 () == v2.m11 () && v1.m22 () == v2.m22 () && v1.m33 () == v2.m33 ();\n  }\n  template <typename T> inline bool operator!= (DiagMatrix3<T> v1, DiagMatrix3<T> v2) {\n    return !(v1 == v2);\n  }\n\n  /*\n  template <typename T> struct Abs2Impl<DiagMatrix3<T> > {\n    static DECLTYPE(Math::abs2 (*(T*)0)) apply (DiagMatrix3<T> v) {\n      return Math::abs2 (v.m11 ()) + Math::abs2 (v.m22 ()) + Math::abs2 (v.m33 ());\n    }\n  };\n  */\n\n  // Matrix-Matrix multiplication\n  template <typename T, typename U> inline RT(*) operator* (DiagMatrix3<T> v1, DiagMatrix3<U> v2) {\n    return RT(*) (v1.m11 () * v2.m11 (), v1.m22 () * v2.m22 (), v1.m33 () * v2.m33 ());\n  }\n\n  // Matrix-Vector multiplication\n  template <typename T, typename U> inline Vector3<RTS(*)> operator* (DiagMatrix3<T> v1, Vector3<U> v2) {\n    return Vector3<RTS(*)> (v1.m11 () * v2.x (), v1.m22 () * v2.y (), v1.m33 () * v2.z ());\n  }\n\n#undef RTS\n#undef RT\n\n  // Unary +/-\n  template <typename T> inline DiagMatrix3<T> operator+ (DiagMatrix3<T> v) {\n    return DiagMatrix3<T> (+v.m11 (), +v.m22 (), +v.m33 ());\n  }\n  template <typename T> inline DiagMatrix3<T> operator- (DiagMatrix3<T> v) {\n    return DiagMatrix3<T> (-v.m11 (), -v.m22 (), -v.m33 ());\n  }\n\n  template <typename F> DiagMatrix3<F> real (DiagMatrix3<std::complex<F> > v) {\n    return DiagMatrix3<F> (real (v.m11 ()), real (v.m22 ()), real (v.m33 ()));\n  }\n\n  template <typename F> DiagMatrix3<F> imag (DiagMatrix3<std::complex<F> > v) {\n    return DiagMatrix3<F> (imag (v.m11 ()), imag (v.m22 ()), imag (v.m33 ()));\n  }\n}\n\n#endif // !MATH_DIAGMATRIX3_HPP_INCLUDED\n", "meta": {"hexsha": "cd970105bf2326f55d1a8f80957675f142d0a3e0", "size": 7313, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/PluginHDF5/Math/DiagMatrix3.hpp", "max_stars_repo_name": "voxie-viewer/voxie", "max_stars_repo_head_hexsha": "d2b5e6760519782e9ef2e51f5322a3baa0cb1198", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-06-03T18:41:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T20:28:58.000Z", "max_issues_repo_path": "src/PluginHDF5/Math/DiagMatrix3.hpp", "max_issues_repo_name": "voxie-viewer/voxie", "max_issues_repo_head_hexsha": "d2b5e6760519782e9ef2e51f5322a3baa0cb1198", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PluginHDF5/Math/DiagMatrix3.hpp", "max_forks_repo_name": "voxie-viewer/voxie", "max_forks_repo_head_hexsha": "d2b5e6760519782e9ef2e51f5322a3baa0cb1198", "max_forks_repo_licenses": ["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.1586538462, "max_line_length": 194, "alphanum_fraction": 0.6208122522, "num_tokens": 2240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5217409928193786}}
{"text": "//\n// Created by \u53f6\u74a8\u94ed on 2022/3/31.\n//\n#include \"cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/ClosestPoint.hpp\"\n#include \"gtest/gtest.h\"\n//#include <boost/log/trivial.hpp>\n#include <numeric>\n#include <random>\n#include <sstream>\nnamespace cn::edu::SUSTech::YeCanming::Algs::DivideAndConquer{\n    class GTestClosestPoint : public ::testing::Test {\n    protected:\n        ClosestPoint closestPoint;\n        std::vector<std::array<double, 2>> vec2d1 = {{1, 2},{3, 4}, {2.5, 10}, {10, 2.5}};\n\n        //random\n        std::random_device rd;\n    };\n    TEST_F(GTestClosestPoint, TestClosestPoint2DRandomlyWithND){\n        auto m = int(1e7);\n        std::mt19937 mt(rd());\n        std::uniform_int_distribution<> dis(-m, m);\n\n    }\n#define TEST_TestClosestPoint2DWhenXAreEqual_single(Name, ...) \\\n  TEST_F(GTestClosestPoint, TestClosestPoint2DWhenXAreEqualSingle##Name) { \\\n            std::vector<double> vec1d = { __VA_ARGS__ };                  \\\n           ASSERT_NE(vec1d.size(), 0);                                                        \\\n            std::vector<std::array<double, 2>> data(vec1d.size());                   \\\n            for (int j = 0; j < vec1d.size(); ++j) {\\\n                data[j] = {20.0, vec1d[j]};\\\n            }\\\n            std::stringstream ss;\\\n            std::copy(vec1d.begin(), vec1d.end(), std::ostream_iterator<double>(ss, \", \"));\\\n            ss<<std::endl;\\\n            auto resultExpected = closestPoint.findClosestPointPairND<double, 2>(data);\\\n            auto resultActually = closestPoint.findClosestPointPair2D<double>(data);\\\n            EXPECT_EQ(std::get<1>(resultExpected),std::get<1>(resultActually))<<ss.str();\\\n    }\n#define TEST_TestClosestPoint2DWhenXAreEqual(Name, m, n, times)\\\n    TEST_F(GTestClosestPoint, TestClosestPoint2DWhenXAreEqual##Name){\\\n        std::mt19937 mt(rd());\\\n        std::uniform_int_distribution<> dis(-(m), m);\\\n        auto N = n;\\\n        std::vector<double> vec1d(N);\\\n        for (int i = 0; i < (times); ++i) {\\\n            std::generate(vec1d.begin(), vec1d.end(), std::bind(dis, std::ref(mt)));\\\n            std::vector<std::array<double, 2>> data(N);\\\n            for (int j = 0; j < N; ++j) {\\\n                data[j] = {20.0, vec1d[j]};\\\n            }\\\n            std::stringstream ss;\\\n            std::copy(vec1d.begin(), vec1d.end(), std::ostream_iterator<double>(ss, \", \"));\\\n            ss<<std::endl;\\\n            auto resultExpected = closestPoint.findClosestPointPair1D<double>(vec1d);\\\n            auto resultActually = closestPoint.findClosestPointPair2D<double>(data);\\\n            EXPECT_EQ(std::get<1>(resultExpected),std::get<1>(resultActually))<<ss.str();\\\n        }\\\n    }\n    TEST_TestClosestPoint2DWhenXAreEqual(1, 100, 10, 100)\n    TEST_TestClosestPoint2DWhenXAreEqual(2, 1000, 20, 100)\n    TEST_TestClosestPoint2DWhenXAreEqual(3, 1000, 100, 100)\n    TEST_TestClosestPoint2DWhenXAreEqual(4, 1e7, 1e3, 50)\n    TEST_TestClosestPoint2DWhenXAreEqual(5, 1e7, 1e4, 5)\n\n    //\u4e3a\u4ec0\u4e48\u8fc7\u4e0d\u4e86\uff0c\u56e0\u4e3a\u539f\u7406\u9519\u4e86\u3002\u5f53x\u76f8\u7b49\u65f6\u5019\uff0c\u4e0d\u53ef\u80fd\u53ea\u770b6\u4e2a\u3002\u4e5f\u4e0d\u80fd\u53ea\u770b15\u4e2a\u3002 \u9664\u975e\u4e00\u5f00\u59cb\u6392\u5e8f\u7684\u65f6\u5019\uff0c\u8fdb\u884c\u5148x\u540ey\u7684\u540c\u6bd4\u6392\u5e8f\uff0c\u5173\u7cfb\u624d\u6210\u7acb\u3002\n    TEST_TestClosestPoint2DWhenXAreEqual_single(1, 32, 123, 827, 224, 686, 351, 171, 154, 678, 941, 574, 421, 769, 374, 905, 357, 215, 386, 885, 233)\n\n    TEST_F(GTestClosestPoint, TestClosestPoint2D){\n#define Index(it) std::distance(vec2d1.cbegin(),it)\n        auto [cl, d] = closestPoint.findClosestPointPair2D<double>(vec2d1);\n        EXPECT_EQ(d, 2*sqrt(2));\n        EXPECT_EQ(Index(cl[0])+Index(cl[1]), 1);\n        EXPECT_EQ(std::max(Index(cl[0]),Index(cl[1]))-std::min(Index(cl[0]),Index(cl[1])), 1);\n    }\n//    TEST_F(GTestClosestPoint, CanLog){\n//        BOOST_LOG_TRIVIAL(trace) << \"A trace severity message\";\n//        BOOST_LOG_TRIVIAL(debug) << \"A debug severity message\";\n//        BOOST_LOG_TRIVIAL(info) << \"An informational severity message\";\n//        BOOST_LOG_TRIVIAL(warning) << \"A warning severity message\";\n//        BOOST_LOG_TRIVIAL(error) << \"An error severity message\";\n//        BOOST_LOG_TRIVIAL(fatal) << \"A fatal severity message\";\n//    }\n}\nint main(int argc, char* argv[])\n{\n    testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}", "meta": {"hexsha": "78df69ea5cbc407ddcd173214f48e8f76d071157", "size": 4127, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/cpp/cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/GTestClosestPoint.cpp", "max_stars_repo_name": "2catycm/P_Algorithm_Design_and_Analysis_cpp", "max_stars_repo_head_hexsha": "d1678d4db6f59a11215a8c790c2852bf9ad852dd", "max_stars_repo_licenses": ["MulanPSL-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/test/cpp/cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/GTestClosestPoint.cpp", "max_issues_repo_name": "2catycm/P_Algorithm_Design_and_Analysis_cpp", "max_issues_repo_head_hexsha": "d1678d4db6f59a11215a8c790c2852bf9ad852dd", "max_issues_repo_licenses": ["MulanPSL-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/test/cpp/cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/GTestClosestPoint.cpp", "max_forks_repo_name": "2catycm/P_Algorithm_Design_and_Analysis_cpp", "max_forks_repo_head_hexsha": "d1678d4db6f59a11215a8c790c2852bf9ad852dd", "max_forks_repo_licenses": ["MulanPSL-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": 46.3707865169, "max_line_length": 149, "alphanum_fraction": 0.6081899685, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934765, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.5217409910591075}}
{"text": "/*\n * Copyright 2011 Nate Koenig & Andrew Howard\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/* Desc: Random number generator\n * Author: Nate Koenig\n * Date: 27 May 2009\n */\n\n#ifndef RAND_HH\n#define RAND_HH\n\n#include <boost/random.hpp>\n\nnamespace gazebo\n{\n  namespace math\n  {\n    typedef boost::mt19937 GeneratorType;\n    typedef boost::uniform_real<double> UniformRealDist;\n    typedef boost::normal_distribution<double> NormalRealDist;\n    typedef boost::uniform_int<int> UniformIntDist;\n\n    typedef boost::variate_generator<GeneratorType&, UniformRealDist > URealGen;\n    typedef boost::variate_generator<GeneratorType&, NormalRealDist > NRealGen;\n    typedef boost::variate_generator<GeneratorType&, UniformIntDist > UIntGen;\n\n    /// \\addtogroup gazebo_math\n    /// \\{\n    /// \\brief Random number generator class\n    class Rand\n    {\n      /// \\brief Get a double from a uniform distribution\n      /// \\param min Minimum bound for the random number\n      /// \\param max Maximum bound for the random number\n      public: static double GetDblUniform(double _min = 0, double _max = 1);\n\n      /// \\brief Get a double from a normal distribution\n      /// \\param mean Mean value for the distribution\n      /// \\param sigma Sigma value for the distribution\n      public: static double GetDblNormal(double _mean = 0, double _sigma = 1);\n\n      /// \\brief Get a integer from a uniform distribution\n      /// \\param min Minimum bound for the random number\n      /// \\param max Maximum bound for the random number\n      public: static int GetIntUniform(int _min, int _max);\n\n      /// \\brief Get a double from a normal distribution\n      /// \\param mean Mean value for the distribution\n      /// \\param sigma Sigma value for the distribution\n      public: static int GetIntNormal(int _mean, int _sigma);\n\n      // The random number generator\n      private: static GeneratorType *randGenerator;\n    };\n    /// \\}\n  }\n}\n#endif\n\n", "meta": {"hexsha": "be66731e7e17074ee2a4aeaa76c4f5933f9c5c12", "size": 2444, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/math/Rand.hh", "max_stars_repo_name": "nherment/gazebo", "max_stars_repo_head_hexsha": "fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-01-17T20:41:39.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-01T12:02:58.000Z", "max_issues_repo_path": "src/math/Rand.hh", "max_issues_repo_name": "nherment/gazebo", "max_issues_repo_head_hexsha": "fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/Rand.hh", "max_forks_repo_name": "nherment/gazebo", "max_forks_repo_head_hexsha": "fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-09-29T02:30:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:11:22.000Z", "avg_line_length": 33.4794520548, "max_line_length": 80, "alphanum_fraction": 0.7029459902, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.521740989601083}}
{"text": "\ufeff#ifdef WIN32\n#define NOMINMAX\n#endif\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n#include <app.h>\n\n#include <NewtonFunctionMinimizer.h>\n#include <RigidBodySimulation.h>\n#include <MechanismOptimizer.h>\n\n#include \"mechanisms.h\"\n\n#include <iostream>\n#include <chrono>\n#include <algorithm>\n\n#include <Eigen/Core>\n\nusing Eigen::Vector2f;\nusing Eigen::Vector2d;\nusing Eigen::VectorXd;\n\n#define PLOT_N 100 // number of data points in plot\n\nclass MoveRigidBodyObj : public ObjectiveFunction\n{\npublic:\n    MoveRigidBodyObj(Vector2d pTarget, Vector2d pLocal)\n        : rb({0, 1.0}), pTarget(pTarget), pLocal(pLocal) {\n    }\n\n    double evaluate(const VectorXd& x) const override {\n        return (pTarget - rb.pWorld(x, pLocal)).squaredNorm();\n    }\n\npublic:\n    RigidBody rb;\n    Vector2d pTarget, pLocal;\n};\n\nclass RigidBodyApp : public App\n{\npublic:\n\tRigidBodyApp(int width, int height, const char * title, float pixelRatio = 0.f)\n\t\t: App(width, height, title, pixelRatio), base(width) {\n\n\t\tclear_color = ImVec4(0.8f, 0.8f, 0.8f, 1.00f);\n\t\tlastFrame = std::chrono::high_resolution_clock::now();\n\n\t\tfont = nvgCreateFont(vg, \"sans\", DATA_FOLDER\"/Roboto-Regular.ttf\");\n\t\tif (font == -1) {\n\t\t\tprintf(\"Could not add font.\\n\");\n\t\t}\n\n\t\tfor (float & d : dataEnergy)\n\t\t\td = 0;\n\n\t\tsim = make4barSim();\n\t\tmechOpt = MechanismOptimizer(sim);\n\t}\n\n    void process() override{\n\t\t// move image if right mouse button is pressed\n\t\tif(mouseDown[GLFW_MOUSE_BUTTON_RIGHT]){\n\t\t\tauto dw = (int)(cursorPos[0] - cursorPosDown[0]);\n\t\t\tauto dh = (int)(cursorPos[1] - cursorPosDown[1]);\n\t\t\ttranslation[0] += dw/(double)base;\n\t\t\ttranslation[1] -= dh/(double)base;\n\t\t\tcursorPosDown[0] = cursorPos[0];\n\t\t\tcursorPosDown[1] = cursorPos[1];\n\t\t}\n\n\t\t// run at 60fps, or in slow mo\n\t\tstd::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();\n\t\tif(std::chrono::duration_cast<std::chrono::milliseconds>(now-lastFrame).count() > ((slowMo) ? 320 : 16)){\n\n\t\t\tif(selectedRb != -1){\n\t\t\t\tdouble scale = 1.0;\n\t\t\t\tif(keyDown[GLFW_KEY_UP])\n\t\t\t\t\tscale = 1.01;\n\t\t\t\telse if(keyDown[GLFW_KEY_DOWN])\n\t\t\t\t\tscale = 0.99;\n\t\t\t\tif(scale != 1.0){\n\t\t\t\t\tsim.scaleRigidBody(selectedRb, scale);\n\n\t\t\t\t\tif(sim.motorIdx != -1)\n                        trackedTrajectory = sim.recordTrajectory();\n\t\t\t\t\t\tcout << \"trackedTrajectory: \" << trackedTrajectory << endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(sim.motorIdx != -1){\n\t\t\t\tif(keyDown[GLFW_KEY_LEFT])\n\t\t\t\t\tsim.fixedAngle()[sim.motorIdx].angle += 4 * M_PI / 180;\n\t\t\t\tif(keyDown[GLFW_KEY_RIGHT])\n\t\t\t\t\tsim.fixedAngle()[sim.motorIdx].angle -= 4 * M_PI / 180;\n\n\t\t\t\tif(sim.fixedAngle()[sim.motorIdx].angle > 2*M_PI)\n\t\t\t\t\tsim.fixedAngle()[sim.motorIdx].angle -= 2*M_PI;\n\t\t\t\tif(sim.fixedAngle()[sim.motorIdx].angle < 0)\n\t\t\t\t\tsim.fixedAngle()[sim.motorIdx].angle += 2*M_PI;\n\t\t\t}\n\n\n\t\t\tif(mouseDown[GLFW_MOUSE_BUTTON_LEFT] && selectedRb != -1){\n\n                Vector2d pos = fromScreen(cursorPos[0], cursorPos[1]);\n                const auto &rb = sim.rigidbodies()[selectedRb];\n                MoveRigidBodyObj obj({pos, selectedRbLocal});\n                GradientDescentVariableStep gd;\n                VectorXd xRb = sim.x.segment<3>(rb.dofIdx);\n                gd.minimize(&obj, xRb, false);\n                sim.x.segment<3>(rb.dofIdx) = xRb;\n\t\t\t}\n\n\t\t\tif(runSim){\n\t\t\t\tsim.run();\n\t\t\t}\n\n\t\t\tenergy = sim.energy.evaluate(sim.x);\n\t\t\tdataCounter %= PLOT_N;\n\t\t\tdataEnergy.at(dataCounter++) = (float)energy;\n\n\t\t\tlastFrame = now;\n\t\t}\n\t}\n\n    void drawScene() override {\n\n\t\t// this is the GUI\n\t\t{\n\t\t\tImGui::Begin(\"Assignement 1\");\n\n\t\t\tImGui::TextColored(ImVec4(1.f, 1.f, 1.f, 0.5f), \"left mouse:  Select rigid bodies, apply forces\");\n\t\t\tImGui::TextColored(ImVec4(1.f, 1.f, 1.f, 0.5f), \"right mouse: move around\");\n\t\t\tImGui::TextColored(ImVec4(1.f, 1.f, 1.f, 0.5f), \"mouse wheel: zoom\");\n\t\t\tImGui::TextColored(ImVec4(1.f, 1.f, 1.f, 0.5f), \"space bar:   play/pause\");\n\n\t\t\t//Define the mechanisms to include in main app.\n\t\t\tconst RigidBodySimulation sims[] = {\n\t\t\t\tmakeJansenSim(),\n\t\t\t\tmake4barSim(),\n\t\t\t\tmakePrismaticSim1(),\n\t\t\t\tmakePrismaticSim2(),\n\t\t\t\tmakePrismaticSim3(),\n\t\t\t\tmakePrismaticSim4_XY(),\n\t\t\t\tmakePrismaticSim5_XY(),\n\t\t\t\tmakePrismaticSim6_XYLoop(),\n\t\t\t\tmakeTangentSim1(),\n\t\t\t\tmakeTangentSim2(),\n\t\t\t};\n\t\t\tconst int numberOfSims = 10;\n\n\t\t\t//Construct the dropdown list based on the included function\n\t\t\tchar* items[numberOfSims];\n\t\t\tfor (int i = 0; i < numberOfSims; i++) {\n\t\t\t\titems[i] = sims[i].name;\n\t\t\t}\n\t\t\t\n\t\t\tif(ImGui::Combo(\"Mechanism\", &loadMech, items, numberOfSims)){\n\t\t\t\tsim = sims[loadMech];\n\t\t\t\ttargetTrajectory.resize(0, 2);\n\t\t\t\t//if (loadMech == 0) {\n\t\t\t\t//\ttargetTrajectory = makeJansenTargetPath();\n\t\t\t\t//\tsim.energy.fixedAngleEnabled = true;\n\t\t\t\t//\ttrackedTrajectory = sim.recordTrajectory();\n\t\t\t\t//}\n\t\t\t\tmechOpt = MechanismOptimizer(sim);\n\t\t\t}\n\n            if(ImGui::CollapsingHeader(\"Simulation\")){\n                ImGui::Checkbox(\"run simulation\", &runSim);\n                ImGui::PlotLines(\"Energy\", dataEnergy.data(), PLOT_N, dataCounter, \"energy\", 0, 1.0, ImVec2(0, 100));\n                ImGui::Separator();\n\n\n                if(sim.motorIdx != -1){\n                    ImGui::Checkbox(\"Fixed Angles enabled\", &sim.energy.fixedAngleEnabled);\n                    auto &fixedAngle = sim.fixedAngle()[sim.motorIdx];\n                    float angle = (sim.energy.fixedAngleEnabled) ?\n                                fixedAngle.angle :\n                                sim.rigidbodies()[fixedAngle.rbIdx].theta(sim.x);\n                    if(ImGui::SliderAngle(\"angle\", &angle, 0, 360)){\n                        fixedAngle.angle = angle;\n                        sim.rigidbodies()[fixedAngle.rbIdx].theta(sim.x) = angle;\n                    }\n                    ImGui::Separator();\n                }\n            }\n\n   //         if(sim.motorIdx != -1 && ImGui::CollapsingHeader(\"Design Optimization\")){\n\n\t\t\t//\tImGui::Checkbox(\"Run optimization\", &isMechOpt);\n\t\t\t//\tif(isMechOpt){\n   //                 mechOpt.targetPath = targetTrajectory;\n   //                 mechOpt.optimizeTrajectory();\n\t\t\t//\t\tVectorXd p = sim.getDesignParameters();\n\t\t\t//\t\tif((p-mechOpt.p).norm() > 1e-10){\n\t\t\t//\t\t\tsim.setDesignParameters(mechOpt.p);\n   //                     trackedTrajectory = sim.recordTrajectory();\n\t\t\t//\t\t}\n\t\t\t//\t}\n\n   //             if(ImGui::Button(\"print link lengths\"))\n   //                 std::cout << \"Link lengths:\" << std::endl <<\n   //                              sim.getDesignParameters() << std::endl;\n\t\t\t//}\n\n\t\t\tImGui::Text(\"Application average %.3f ms/frame (%.1f FPS)\", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);\n\t\t\tImGui::End();\n\t\t}\n\n\t\tfor (const auto &f : sim.fixedAngle()) {\n\t\t\tnvgResetTransform(vg);\n\t\t\tnvgBeginPath(vg);\n\t\t\tconst auto &rb = sim.rigidbodies()[f.rbIdx];\n\t\t\tVector2d p = rb.pos(sim.x);\n\n\t\t\tnvgCircle(vg, toScreen(p.x(), 0), toScreen(p.y(), 1), toScreen(0.5));\n\t\t\tnvgFillColor(vg, (sim.motorIdx == -1) ? nvgRGBAf(0, 0, 1, 0.5) : nvgRGBAf(0, 1, 1, 0.5));\n\t\t\tnvgFill(vg);\n\t\t}\n\n\t\tint i = 0;\n\t\tfor (const auto &rb : sim.rigidbodies()) {\n\t\t\tnvgResetTransform(vg);\n\t\t\tVector2d p = rb.pos(sim.x);\n\t\t\tnvgTranslate(vg, toScreen(p.x(), 0), toScreen(p.y(), 1));\n\t\t\tnvgRotate(vg, -rb.theta(sim.x));\n\t\t\tnvgBeginPath(vg);\n\t\t\tdouble r = rb.width/2;\n\t\t\tnvgRoundedRect(vg, toScreen(-rb.length*0.5 - r), toScreen(-rb.width*0.5), toScreen(rb.length + 2*r), toScreen(rb.width), toScreen(r));\n\t\t\tif(i == selectedRb)\n\t\t\t\tnvgFillColor(vg, nvgRGBAf(1.0, 0.9, 0.7, 0.5));\n\t\t\telse\n\t\t\t\tnvgFillColor(vg, nvgRGBAf(0.5, 0.5, 0.5, 0.5));\n\t\t\tnvgFill(vg);\n\t\t\tnvgStrokeColor(vg, nvgRGBAf(0, 0, 0, 1));\n\t\t\tnvgStrokeWidth(vg, 2*pixelRatio);\n\t\t\tnvgStroke(vg);\n\n\t\t\tnvgFontSize(vg, toScreen(0.3));\n\t\t\tnvgFontFace(vg, \"sans\");\n\n\t\t\tnvgFillColor(vg, nvgRGBAf(0,0,0,1));\n\t\t\tnvgText(vg, 0, 100/zoom, rb.name.c_str(), nullptr);\n\t\t\ti++;\n\t\t}\n\n\t\tfor (const auto &joint : sim.hingeJoints()) {\n\t\t\tnvgResetTransform(vg);\n\t\t\tnvgBeginPath(vg);\n\t\t\tconst auto &rb0 = sim.rigidbodies()[joint.rbIdx[0]];\n\t\t\tconst auto &rb1 = sim.rigidbodies()[joint.rbIdx[1]];\n\t\t\tVector2d p0 = rb0.pWorld(sim.x, joint.local[0]);\n\t\t\tVector2d p1 = rb1.pWorld(sim.x, joint.local[1]);\n\t\t\tnvgMoveTo(vg, toScreen(p0.x(), 0), toScreen(p0.y(), 1));\n\t\t\tnvgLineTo(vg, toScreen(p1.x(), 0), toScreen(p1.y(), 1));\n\t\t\tnvgStrokeColor(vg, nvgRGBAf(1, 0, 0, 0.5));\n\t\t\tnvgStrokeWidth(vg, 2.0*pixelRatio);\n\t\t\tnvgStroke(vg);\n\n\t\t\tnvgBeginPath(vg);\n\t\t\tnvgCircle(vg, toScreen(p0.x(), 0), toScreen(p0.y(), 1), toScreen(rb0.width/3));\n\t\t\tnvgCircle(vg, toScreen(p1.x(), 0), toScreen(p1.y(), 1), toScreen(rb1.width/3));\n\t\t\tnvgStrokeColor(vg, nvgRGBAf(1, 0, 0, 0.5));\n\t\t\tnvgStrokeWidth(vg, 2.0*pixelRatio);\n\t\t\tnvgStroke(vg);\n\t\t}\n\n\t\t//Added Draw Point On Line Joint Graphics\n\t\tfor (const auto &joint : sim.pointOnLineJoints()) {\n\t\t\tnvgResetTransform(vg);\n\n\t\t\tnvgBeginPath(vg);\n\t\t\tconst auto &rb0 = sim.rigidbodies()[joint.rbIdx[0]];\n\n\t\t\tVector2d p0_bgn = rb0.pWorld(sim.x, joint.local0Point);\n\t\t\tVector2d p0_end = rb0.pWorld(sim.x, joint.local0Point + joint.local0Vector);\n\t\t\tnvgMoveTo(vg, toScreen(p0_bgn.x(), 0), toScreen(p0_bgn.y(), 1));\n\t\t\tnvgLineTo(vg, toScreen(p0_end.x(), 0), toScreen(p0_end.y(), 1));\n\t\t\tnvgStrokeColor(vg, nvgRGBAf(0, 0, 1, 0.5));\n\t\t\tnvgStrokeWidth(vg, 2.0*pixelRatio);\n\t\t\tnvgStroke(vg);\n\t\t\t\n\t\t\t//Draw circle on rb1 point\n\t\t\tconst auto &rb1 = sim.rigidbodies()[joint.rbIdx[1]];\n\t\t\tVector2d p1 = rb1.pWorld(sim.x, joint.local1Point);\n\n\t\t\tnvgBeginPath(vg);\n\t\t\tnvgCircle(vg, toScreen(p1.x(), 0), toScreen(p1.y(), 1), toScreen(rb1.width / 3));\n\t\t\tnvgStrokeColor(vg, nvgRGBAf(0, 0, 1, 0.5));\n\t\t\tnvgStrokeWidth(vg, 2.0*pixelRatio);\n\t\t\tnvgStroke(vg);\n\t\t}\n\n\t\tfor (const auto &f : sim.fixed()) {\n\t\t\tnvgResetTransform(vg);\n\t\t\tnvgBeginPath(vg);\n\t\t\tconst auto &rb = sim.rigidbodies()[f.rbIdx];\n\t\t\tVector2d p0 = rb.pWorld(sim.x, f.localPos);\n\t\t\tVector2d p1 = f.pos;\n\t\t\tnvgMoveTo(vg, toScreen(p0.x(), 0), toScreen(p0.y(), 1));\n\t\t\tnvgLineTo(vg, toScreen(p1.x(), 0), toScreen(p1.y(), 1));\n\t\t\tnvgStrokeColor(vg, nvgRGBAf(0.2, 0.2, 0, 0.5));\n\t\t\tnvgStrokeWidth(vg, 2.0*pixelRatio);\n\t\t\tnvgStroke(vg);\n\n\t\t\tnvgBeginPath(vg);\n\t\t\tnvgCircle(vg, toScreen(p0.x(), 0), toScreen(p0.y(), 1), toScreen(rb.width/4));\n\t\t\tnvgCircle(vg, toScreen(p1.x(), 0), toScreen(p1.y(), 1), toScreen(rb.width/4));\n\t\t\tnvgStrokeColor(vg, nvgRGBAf(0.2, 0.2, 0, 0.5));\n\t\t\tnvgStrokeWidth(vg, 2.0*pixelRatio);\n\t\t\tnvgStroke(vg);\n\t\t}\n\n\t\t// draw tracked point\n\t\tif(sim.trackRBPoint.rbIdx >= 0){\n\t\t\tnvgResetTransform(vg);\n\t\t\tnvgBeginPath(vg);\n\t\t\tconst auto &rb = sim.rigidbodies()[sim.trackRBPoint.rbIdx];\n\t\t\tVector2d p = rb.pWorld(sim.x, sim.trackRBPoint.local);\n\t\t\tnvgCircle(vg, toScreen(p.x(), 0), toScreen(p.y(), 1), 2.0);\n\t\t\tnvgFillColor(vg, nvgRGBAf(0.2, 0.8, 0.2, 0.5));\n\t\t\tnvgFill(vg);\n\t\t}\n\n\t\tauto draw_path = [=](const Matrix<double, -1, 2> &path, NVGcolor color){\n\t\t\tif(path.rows() > 0){\n\t\t\t\tnvgBeginPath(vg);\n\n\t\t\t\tnvgMoveTo(vg, toScreen(path(0, 0), 0), toScreen(path(0, 1), 1));\n\t\t\t\tfor (int i = 0; i < path.rows(); i++) {\n\t\t\t\t\tnvgLineTo(vg, toScreen(path(i, 0), 0), toScreen(path(i, 1), 1));\n\t\t\t\t}\n\t\t\t\tnvgStrokeColor(vg, color);\n\t\t\t\tnvgStrokeWidth(vg, 2);\n\t\t\t\tnvgStroke(vg);\n\n\t\t\t\tnvgBeginPath(vg);\n\t\t\t\tfor (int i = 0; i < path.rows(); i++)\n\t\t\t\t\tnvgCircle(vg, toScreen(path(i, 0), 0), toScreen(path(i, 1), 1), toScreen(0.07));\n\t\t\t\tnvgFillColor(vg, color);\n\t\t\t\tnvgFill(vg);\n\t\t\t}\n\t\t};\n\n\n        draw_path(trackedTrajectory, nvgRGBAf(0.2, 0.8, 0.2, 0.5));\n        draw_path(targetTrajectory, nvgRGBAf(0.8, 0.5, 0.2, 0.5));\n\n\t}\n\nprotected:\n    void keyPressed(int key, int  /*mods*/) override {\n\t\t// play / pause with space bar\n\t\tif(key == GLFW_KEY_SPACE)\n\t\t\trunSim = !runSim;\n\t}\n\n    void mousePressed(int button) override {\n\t\tcursorPosDown[0] = cursorPos[0];\n\t\tcursorPosDown[1] = cursorPos[1];\n\n\t\tif(button == GLFW_MOUSE_BUTTON_LEFT){\n\t\t\tVector2d cursor = fromScreen(cursorPos[0], cursorPos[1]);\n\n            int i = 0;\n            selectedRb = -1;\n            for (const auto &rb : sim.rigidbodies()) {\n                auto rot = rotationMatrix(-rb.theta(sim.x));\n                Vector2d d = rot * (cursor - rb.pos(sim.x));\n                if(std::abs(d.x()) <= rb.length/2 && std::abs(d.y()) <= rb.width/2){\n                    selectedRb = i;\n                    selectedRbLocal = d;\n                    break;\n                }\n                i++;\n            }\n\t\t}\n\t}\n\n    void mouseReleased(int  /*button*/) override {\n\t}\n\n    void scrollWheel(double  /*xoffset*/, double yoffset) override {\n\t\tdouble zoomOld = zoom;\n\t\tzoom *= std::pow(1.10, yoffset);\n\t\tfor (int dim = 0; dim < 2; ++dim) {\n\t\t\tdouble c = cursorPos[dim]/(double) ((dim == 0) ? base : -base);\n\t\t\ttranslation[dim] = c - zoomOld/zoom * (c-translation[dim]);\n\t\t}\n\t}\n\n    void windowResized(int /*w*/, int /*h*/) override {\n\t}\n\n\nprivate:\n\n\tVectorXd fromScreen(int i, int j, int w, int h) const {\n\t\tVectorXd x(2);\n\t\tx[0] = ((double)i/(double)w - translation[0])*zoom/pixelRatio;\n\t\tx[1] = (-(double)j/(double)h - translation[1])*zoom/pixelRatio;\n\t\treturn x;\n\t}\n\n\ttemplate<class S>\n\tVectorXd fromScreen(S i, S j) const {\n\t\treturn fromScreen((double)i, (double)j, base, base);\n\t}\n\n\tdouble toScreen(double s, int dim) const {\n\t\treturn (s/zoom*pixelRatio + translation[dim]) * (double)((dim == 0) ? base : -base);\n\t}\n\n\tdouble toScreen(double s) const {\n\t\treturn s/zoom*pixelRatio * base;\n\t}\n\nprivate:\n\tint font = -1;\n\n\tint loadMech = 0;\n\tbool runSim = false;\n\tstd::chrono::high_resolution_clock::time_point lastFrame;\n\tbool slowMo = false;\n\n\tdouble cursorPosDown[2]{};\n\tdouble translation[2] = {0.75*pixelRatio, -0.25*pixelRatio};\n\tdouble zoom = 24;\n\tint base;\n\n\tint selectedRb = -1;\n    Vector2d selectedRbLocal;\n\n\tbool isMechOpt = false;\n\npublic:\n\t// optimization\n\tdouble energy = 0;\n\tint dataCounter = 0;\n\tstd::array<float, PLOT_N> dataEnergy{};\n\n\tRigidBodySimulation sim;\n\n    Matrix<double, -1, 2> trackedTrajectory, targetTrajectory;\n\tMechanismOptimizer mechOpt;\n};\n\nint main(int, char**)\n{\n\t// If you have high DPI screen settings, you can change the pixel ratio\n\t// accordingly. E.g. for 200% scaling use `pixelRatio = 2.f`\n\tRigidBodyApp app(1080, 720, \"Assignement 1\");\n\n\tapp.run();\n\treturn 0;\n}\n", "meta": {"hexsha": "2e39ad0c278aea87014daaa0175e5e7a151cb246", "size": 14003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/app/main.cpp", "max_stars_repo_name": "yck011522/modular_ik_solver", "max_stars_repo_head_hexsha": "285020b6e549d7fb8c3acc6b54bfd90ff3a43fd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/app/main.cpp", "max_issues_repo_name": "yck011522/modular_ik_solver", "max_issues_repo_head_hexsha": "285020b6e549d7fb8c3acc6b54bfd90ff3a43fd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/app/main.cpp", "max_forks_repo_name": "yck011522/modular_ik_solver", "max_forks_repo_head_hexsha": "285020b6e549d7fb8c3acc6b54bfd90ff3a43fd3", "max_forks_repo_licenses": ["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.3095238095, "max_line_length": 137, "alphanum_fraction": 0.6097979004, "num_tokens": 4591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.521740989601083}}
{"text": "// Copyright (C) 2013  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n\r\n#include <dlib/matrix.h>\r\n#include <sstream>\r\n#include <string>\r\n#include <ctime>\r\n#include <vector>\r\n#include <dlib/statistics.h>\r\n\r\n#include \"tester.h\"\r\n#include <dlib/svm.h>\r\n\r\n\r\nnamespace  \r\n{\r\n\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n\r\n    logger dlog(\"test.svr_linear_trainer\");\r\n\r\n    typedef matrix<double, 0, 1> sample_type;\r\n    typedef std::vector<std::pair<unsigned int, double> > sparse_sample_type;\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    double sinc(double x)\r\n    {\r\n        if (x == 0)\r\n            return 1;\r\n        return sin(x)/x;\r\n    }\r\n\r\n    template <typename scalar_type>\r\n    void test1()\r\n    {\r\n        typedef matrix<scalar_type,0,1> sample_type;\r\n\r\n        typedef radial_basis_kernel<sample_type> kernel_type;\r\n\r\n        print_spinner();\r\n\r\n        std::vector<sample_type> samples;\r\n        std::vector<scalar_type> targets;\r\n\r\n        // The first thing we do is pick a few training points from the sinc() function.\r\n        sample_type m(1);\r\n        for (scalar_type x = -10; x <= 4; x += 1)\r\n        {\r\n            m(0) = x;\r\n\r\n            samples.push_back(m);\r\n            targets.push_back(sinc(x)+1.1);\r\n        }\r\n\r\n        randomize_samples(samples, targets);\r\n\r\n        empirical_kernel_map<kernel_type> ekm;\r\n        ekm.load(kernel_type(0.1), samples);\r\n\r\n        for (unsigned long i = 0; i < samples.size(); ++i)\r\n            samples[i] = ekm.project(samples[i]);\r\n\r\n        svr_linear_trainer<linear_kernel<sample_type> > linear_trainer;\r\n        linear_trainer.set_epsilon(0.0001);\r\n        linear_trainer.set_c(30);\r\n        linear_trainer.set_epsilon_insensitivity(0.001);\r\n\r\n        matrix<double> res = cross_validate_regression_trainer(linear_trainer, samples, targets, 5);\r\n        dlog << LINFO << \"MSE and R-Squared: \"<< res;\r\n        DLIB_TEST(res(0) < 1e-4);\r\n        DLIB_TEST(res(1) > 0.99);\r\n\r\n        dlib::rand rnd;\r\n\r\n        samples.clear();\r\n        targets.clear();\r\n        std::vector<scalar_type> noisefree_targets;\r\n        for (scalar_type x = 0; x <= 5; x += 0.1)\r\n        {\r\n            m(0) = x;\r\n            samples.push_back(matrix_cast<scalar_type>(linpiece(m, linspace(0,5,20))));\r\n            targets.push_back(x*x + rnd.get_random_gaussian());\r\n            noisefree_targets.push_back(x*x);\r\n        }\r\n        linear_trainer.set_learns_nonnegative_weights(true);\r\n        linear_trainer.set_epsilon_insensitivity(1.0);\r\n        decision_function<linear_kernel<sample_type> > df2 = linear_trainer.train(samples, targets);\r\n\r\n        print_spinner();\r\n        res = test_regression_function(df2, samples, noisefree_targets);\r\n        dlog << LINFO << \"MSE and R-Squared: \"<< res;\r\n        DLIB_TEST(res(0) < 0.15);\r\n        DLIB_TEST(res(1) > 0.98);\r\n        DLIB_TEST(df2.basis_vectors.size()==1);\r\n        DLIB_TEST(max(df2.basis_vectors(0)) >= 0);\r\n\r\n        linear_trainer.force_last_weight_to_1(true);\r\n        df2 = linear_trainer.train(samples, targets);\r\n        DLIB_TEST(std::abs(df2.basis_vectors(0)(samples[0].size()-1) - 1.0) < 1e-14);\r\n\r\n        res = test_regression_function(df2, samples, noisefree_targets);\r\n        dlog << LINFO << \"MSE and R-Squared: \"<< res;\r\n        DLIB_TEST(res(0) < 0.20);\r\n        DLIB_TEST(res(1) > 0.98);\r\n\r\n\r\n        // convert into sparse vectors and try it out\r\n        typedef std::vector<std::pair<unsigned long, scalar_type> > sparse_samp;\r\n        std::vector<sparse_samp> ssamples;\r\n        for (unsigned long i = 0; i < samples.size(); ++i)\r\n        {\r\n            sparse_samp s;\r\n            for (long j = 0; j < samples[i].size(); ++j)\r\n                s.push_back(make_pair(j,samples[i](j)));\r\n            ssamples.push_back(s);\r\n        }\r\n\r\n        svr_linear_trainer<sparse_linear_kernel<sparse_samp> > strainer;\r\n        strainer.set_learns_nonnegative_weights(true);\r\n        strainer.set_epsilon_insensitivity(1.0);\r\n        strainer.set_c(30);\r\n        decision_function<sparse_linear_kernel<sparse_samp> > df;\r\n        df = strainer.train(ssamples, targets);\r\n        res = test_regression_function(df, ssamples, noisefree_targets);\r\n        dlog << LINFO << \"MSE and R-Squared: \"<< res;\r\n        DLIB_TEST(res(0) < 0.15);\r\n        DLIB_TEST(res(1) > 0.98);\r\n        DLIB_TEST(df2.basis_vectors.size()==1);\r\n        DLIB_TEST(max(sparse_to_dense(df2.basis_vectors(0))) >= 0);\r\n    }\r\n\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    class tester_svr_linear_trainer : public tester\r\n    {\r\n    public:\r\n        tester_svr_linear_trainer (\r\n        ) :\r\n            tester (\"test_svr_linear_trainer\",\r\n                    \"Runs tests on the svr_linear_trainer.\")\r\n        {}\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            dlog << LINFO << \"TEST double\";\r\n            test1<double>();\r\n            dlog << LINFO << \"TEST float\";\r\n            test1<float>();\r\n        }\r\n    } a;\r\n\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "1044c80538a27855676303432be800123fed2eeb", "size": 5146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/svr_linear_trainer.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": "dlib/test/svr_linear_trainer.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": "dlib/test/svr_linear_trainer.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": 31.7654320988, "max_line_length": 101, "alphanum_fraction": 0.5567431014, "num_tokens": 1268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5217409849247618}}
{"text": "/*\n * concatenate Eigen matrices\n * by R. Falque\n * 03/07/2019\n */\n\n#ifndef EIGEN_CAST_HPP\n#define EIGEN_CAST_HPP\n\n#include <iostream>\n#include <Eigen/Core>\n\n\n\n//https://stackoverflow.com/a/21068014/2562693\ntemplate <typename T>\ninline void cast_to_matrix(std::vector< std::vector <T> > input, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& output)\n{\n    const int numRows = input.size();\n    const int numCols = input[0].size();\n\n    //output = Eigen::Map<Eigen::Matrix<T, input.size(), input[0].size()>, Eigen::Unaligned>(input.data(), input.size());\n    output.resize(numRows, numCols);\n\n    for (int i=0; i<numRows; i++)\n        for (int j=0; j<numCols; j++)\n            output(i,j) = input[i][j];\n}\n\n#endif\n\n\n\n", "meta": {"hexsha": "b09063599af6253ee38b7d86a83e093630d15deb", "size": 718, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/EigenTools/cast_vector_to_matrix.hpp", "max_stars_repo_name": "rFalque/normals_transfer", "max_stars_repo_head_hexsha": "c0c27fb6e3bce32123489442f3b606f9be00b56e", "max_stars_repo_licenses": ["MIT"], "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/EigenTools/cast_vector_to_matrix.hpp", "max_issues_repo_name": "rFalque/normals_transfer", "max_issues_repo_head_hexsha": "c0c27fb6e3bce32123489442f3b606f9be00b56e", "max_issues_repo_licenses": ["MIT"], "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/EigenTools/cast_vector_to_matrix.hpp", "max_forks_repo_name": "rFalque/normals_transfer", "max_forks_repo_head_hexsha": "c0c27fb6e3bce32123489442f3b606f9be00b56e", "max_forks_repo_licenses": ["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.1176470588, "max_line_length": 122, "alphanum_fraction": 0.643454039, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.5217409817064659}}
{"text": "#include \"utils/math_utils.h\"\n#include \"utils/algorithms.hpp\"\n#include <boost/program_options.hpp>\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <iterator>\n#include <fstream>\n#include <algorithm>\n#include <map>\n#include <string>\n\ntemplate<typename It, typename T>\nbool verify(It from, It to, T min, T max)\n{\n    return std::all_of(from, to, [min, max](auto val) {\n                    return val >= min && val <= max;\n                }\n            );\n}\n\nstruct program_args\n{\n    enum norm_type {\n        MIN_MAX, MAX, Z_NORM, NONE\n    };\n\n    norm_type type = NONE;\n    double min = 0;\n    double max = 1;\n    std::string in_file;\n\n    program_args() = default;\n    program_args(norm_type t, double mn, double mx, const std::string& p) :\n            type(t), min(mn), max(mx), in_file(p)\n    {\n    }\n\n    static norm_type type_convert(const std::string& from) {\n            static const std::map<std::string, norm_type> convertion{\n                {\"minmax\", MIN_MAX}, {\"max\", MAX}, {\"znorm\", Z_NORM}\n            };\n            auto i = convertion.find(from);\n            return i == std::end(convertion) ? NONE : i->second;\n    }\n};\n\nnamespace po = boost::program_options;\nprogram_args process_args(int argc, char** argv)\n{\n    program_args args;\n    po::options_description desc(\"Allowed options\");\n    std::string algo;\n    desc.add_options()\n        (\"help,h\", \"test usage:\")\n        (\"min,m\", po::value<double>(&args.min)->default_value(args.min),\n         \"algorithm min value (for min/max norm only)\")\n        (\"max,x\", po::value<double>(&args.max)->default_value(args.max),\n         \"max value (for min/max  norm only\")\n        (\"file,f\", po::value<std::string>(&args.in_file),\n         \"input file to read data from\")\n        (\"algo,a\", po::value<std::string>(&algo),\n         \"normalization algoritm, select from 'minmax' 'max' or 'znorm'\");\n    po::variables_map cli;\n    if (argc == 1 || cli.count(\"help\")) {\n        std::cerr<<desc<<std::endl;\n        throw std::runtime_error{\"no args\"};;\n    }\n    try {\n        po::store(po::command_line_parser(argc, argv).options(desc).run(), cli);\n        po::notify(cli);\n    } catch (const std::exception& e) {\n        std::cerr<<\"error - invalid command line: \"<<e.what()<<\"\\n\"<<desc<<std::endl;\n        throw e; \n    }\n    if (algo.empty()) {\n        std::cerr<<\"algorithm type not set\\n\"<<desc<<std::endl;\n        throw std::runtime_error{\"missing args\"};\n    } else {\n        auto a = program_args::type_convert(algo);\n        if (a == program_args::NONE) {\n            std::cerr<<\"invalid algorithm: \"<<algo<<\"\\n\"<<desc<<std::endl;\n            throw std::runtime_error{\"invalid algortihm\"};\n        }\n        args.type = a;\n        return args;\n    }\n}\n\nint process_min_max(const std::vector<double>& data, double min, double max)\n{\n    auto out = utils::min_max_normalization(data, min, max);\n    std::cout<<\"after normalization:\\n\";\n    out_range(std::cout, out);\n    std::cout<<std::endl;\n    if (verify(std::begin(out), std::end(out), min, max)) {\n        std::cout<<\"all values after norm are valid\"<<std::endl;\n        return 0;\n    } else {\n        std::cout<<\"verification failed - we have values that are out of range [\"<<min<<\", \"<<max<<\"]\\n\";\n        return -1;\n    }\n}\n\nint process_max(const std::vector<double>& data, double)\n{\n    auto out = utils::max_normalization(data);\n    std::cout<<\"after normalization:\\n\";\n    out_range(std::cout, out);\n    std::cout<<std::endl;\n    return 0;\n}\n\nint process_znorm(const std::vector<double>& data)\n{\n    auto out = utils::z_normalization(data);\n    std::cout<<\"after normalization:\\n\";\n    out_range(std::cout, out);\n    std::cout<<std::endl;\n    return 0;\n}\n\nint process(const program_args& args)\n{\n    std::ifstream input(args.in_file.c_str());\n    if (!input) {\n        std::cerr<<\"failed to open \"<<args.in_file<<\" for reading\\n\";\n        return -1;\n    }\n    std::cout<<\"reading input from \"<<args.in_file<<std::endl;\n    const std::vector<double> data{std::istream_iterator<double>(input), \n                                   std::istream_iterator<double>()\n    };\n    if (data.empty()) {\n        std::cerr<<\"failed  to read from \"<<args.in_file<<std::endl;\n        return -1;\n    }\n    std::cout<<\"before data:\\n\";\n    out_range(std::cout, data); \n    std::cout<<std::endl;\n    switch (args.type) {\n        case program_args::MAX:\n            return process_max(data, args.max);\n            utils::max_normalization(data);\n            break;\n            case program_args::MIN_MAX:\n                return process_min_max(data, args.min, args.max);\n            case program_args::Z_NORM:\n                return process_znorm(data); \n            default:\n                throw std::runtime_error{\"invalid algorithm type\"};\n    }\n}\n\nint main(int argc, char** argv)\n{\n    try {\n        auto args = process_args(argc, argv);\n        return process(args);\n    } catch (const std::exception&) {\n        return -1;\n    }\n#if 0\n    if (argc != 4) {\n        std::cerr<<\"usage: \"<<argv[0]<<\" <input file> <min> <max>\\n\";\n        return -1;\n    }\n#endif\n}\n", "meta": {"hexsha": "fb126810006bb6b2f481f676d12a40b00b36b6a1", "size": 5086, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/test_norm/main.cpp", "max_stars_repo_name": "boazsade/machine_learinig_models", "max_stars_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_stars_repo_licenses": ["MIT"], "max_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_norm/main.cpp", "max_issues_repo_name": "boazsade/machine_learinig_models", "max_issues_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_issues_repo_licenses": ["MIT"], "max_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_norm/main.cpp", "max_forks_repo_name": "boazsade/machine_learinig_models", "max_forks_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_forks_repo_licenses": ["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.9176470588, "max_line_length": 105, "alphanum_fraction": 0.5729453401, "num_tokens": 1289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.521721859357928}}
{"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#include <boost/simd/pack.hpp>\n#include <boost/simd/function/nthroot.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/meta/cardinal_of.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/half.hpp>\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& runtime)\n{\n\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using iT =  bd::as_integer_t<T>;\n  using p_t = bs::pack<T, N>;\n  using pi_t= bs::pack<iT, N>;\n\n  T a1[N], b[N];\n  iT a2[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i) : bs::rec(T(i));\n    a2[i] = i+2;\n    b[i] = bs::nthroot(a1[i], a2[i]) ;\n  }\n  p_t aa1(&a1[0], &a1[0]+N);\n  pi_t aa2(&a2[0], &a2[0]+N);\n  p_t bb (&b[0], &b[0]+N);\n\n  STF_ULP_EQUAL(bs::nthroot(aa1, aa2), bb, 1);\n  STF_ULP_EQUAL(bs::raw_(bs::nthroot)(aa1, aa2), bb, 1);\n}\n\nSTF_CASE_TPL(\"Check nthroot on pack\" , STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  using p_t = bs::pack<T>;\n  static const std::size_t N = bs::cardinal_of<p_t>::value;\n  test<T, N>(runtime);\n  test<T, N/2>(runtime);\n  test<T, N*2>(runtime);\n}\n\nSTF_CASE_TPL (\" nthroot\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::nthroot;\n  using p_t = bs::pack<T>;\n  using pi_t = bd::as_integer_t<p_t>;\n  using r_t = decltype(nthroot(p_t(), pi_t()));\n\n  // return type conformity test\n STF_TYPE_IS(r_t, p_t);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(nthroot(bs::Inf<p_t>(),pi_t(3)), bs::Inf<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Inf<p_t>(),pi_t(4)), bs::Inf<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Minf<p_t>(),pi_t(3)), bs::Minf<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Minf<p_t>(),pi_t(4)), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Nan<p_t>(),pi_t(3)), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Nan<p_t>(),pi_t(4)), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Mone<p_t>(),pi_t(4)), bs::Nan<r_t>(), 0.5);\n#endif\n  STF_ULP_EQUAL(nthroot(bs::Mone<p_t>(),pi_t(0)), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::One <p_t>(),pi_t(0)), bs::One<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Half<p_t>(),pi_t(0)), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Two <p_t>(),pi_t(0)), bs::Inf <r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Zero<p_t>(),pi_t(0)), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Two <p_t>(),pi_t(0)), bs::Inf<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Half<p_t>(),pi_t(0)), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Mone<p_t>(),pi_t(3)), bs::Mone<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::One<p_t>(),pi_t(3)), bs::One<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::One<p_t>(),pi_t(4)), bs::One<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Zero<p_t>(),pi_t(3)), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Zero<p_t>(),pi_t(4)), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(p_t(-8),pi_t(3)), r_t(-2), 0.5);\n  STF_ULP_EQUAL(nthroot(p_t(256),pi_t(4)), r_t(4), 0.5);\n  STF_ULP_EQUAL(nthroot(p_t(8),pi_t(3)), r_t(2), 0.5);\n  STF_ULP_EQUAL(nthroot(p_t(0.5), pi_t(4)), r_t(0.84089641525371454303112547623321), 0.5);\n}\n\n\n\n", "meta": {"hexsha": "731a1f793668e71313098131f5019a5217423a8b", "size": 3845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/nthroot.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/simd/nthroot.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/simd/nthroot.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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": 36.619047619, "max_line_length": 100, "alphanum_fraction": 0.6117035111, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5217218593579278}}
{"text": "#include <unistd.h>\t// sleep\n#include <armadillo>\n#include <vector>\n#include <deque>\n#include <algorithm>    // std::min\n\n#include \"Functions.h\"\n\nusing namespace arma;\nusing namespace std;\n\n\nvec eta(const vec &v, const double tau){\t\n\tvec out(size(v),fill::zeros);\n\n\tuvec ind = find(abs(v) > tau);\n\tout(ind) = sign(v(ind))%(abs(v(ind)) - tau );\n\treturn out;\n}\n\nvec eta_deriv(const vec &v, const double tau){\t\n\tvec out(size(v),fill::zeros);\n\n\tuvec ind = find(abs(v) > tau);\n\tout(ind).ones();\n\treturn out;\n}\n\n\nvec eta(const vec &v, const vec tau){\t\n\tvec out(size(v),fill::zeros);\n\n\tuvec ind = find(abs(v) > tau);\n\tout(ind) = sign(v(ind))%(abs(v(ind)) - tau(ind) );\n\treturn out;\n}\n\nvec eta_deriv(const vec &v, const vec tau){\t\n\tvec out(size(v),fill::zeros);\n\n\tuvec ind = find(abs(v) > tau);\n\tout(ind).ones();\n\treturn out;\n}\n\nvec AMP(const mat &A, const vec &y, const int sparsity, const unsigned int max_iter,\n\tconst double tol, unsigned int &num_iters, const simulation_parameters simulation_params){\n\n\tconst unsigned int N = A.n_cols;   \t// signal dimension\n\tconst unsigned int M = y.n_elem;\t// number of measurements\n\t//const double delta = double(num_measurements)/sig_dim;\n\tunsigned int i = 0;\n\tvec x_t(N,fill::zeros);\n\tvec z_t = y;\n\tdouble tau = .1;\n\tbool done = false;\n\tvec pseudo_data (N,fill::zeros);\n\n\twhile(!done){\n\t\ti++;\t\t\n\t\tz_t = y - A*x_t + z_t * sum (eta_deriv( pseudo_data,tau) ) / M;\n\t\tpseudo_data = A.t() * z_t + x_t;\n\t\ttau = tau * sum(eta_deriv(pseudo_data,tau)) / M;\n\t\tx_t = eta(pseudo_data,tau) ;\n\n\t\tif (norm (y - A*x_t) < tol || i >= max_iter){\n\t\t\tdone = true;\n\t\t}\n\t}\n\n\tnum_iters = i;\n\treturn x_t;\n}\n\n\n// J. Zhu, R. Pilgrim and D. Baron, \"An overview of multi-processor approximate message passing,\"\n// http://ieeexplore.ieee.org/document/7926166/\nvec R_MP_AMP(const mat &A, const vec &y, const int sparsity, const unsigned int max_iter,\n\tconst double tol, unsigned int &num_iters, const simulation_parameters simulation_params){\n\tuvec slow_cores;\n\tset_slow_cores(slow_cores, simulation_params);\n\n\n\tconst unsigned int N = A.n_cols;\n\tconst unsigned int M = y.n_elem;\n\tconst unsigned int P = simulation_params.num_cores;\n\tunsigned int i = 0;\n\tbool done = false;\n\tvec x_t(N,fill::zeros);\n\tdouble g_t = M;\n\tdouble tau = .1;\n\n\tvector <vec> pseudo_data (P,vec(N,fill::zeros));\n\t// parallel section of the code starts here\n\t#pragma omp parallel num_threads(simulation_params.num_cores) \n\t{\n\t// initializing variables in local memory\n\tconst int p = omp_get_thread_num();\n\tmat A_p = A.rows(M*p/P , M*(p+1)/P -1 ); \n\tvec y_p = y.subvec( M*p/P  , M*(p+1)/P -1 ); \n\t\n\tvec z_t_p = y_p;\n\t// R_MP_AMP itearations\n\twhile(!done){\n\t\t//AT processor p:\n\t\tz_t_p = y_p - A_p*x_t + z_t_p * g_t / M;\n\t\tpseudo_data[p] = A_p.t() * z_t_p + x_t/P;\n\t\t\n\t\t//slow cores sleep for  simulation_params.sleep_slow_cores microseconds\n\t\tif (any( slow_cores == omp_get_thread_num()) ){\n\t\t\tusleep(simulation_params.sleep_slow_cores);\n\t\t}\n\t\t\n\n\t\t#pragma omp barrier\n\t\t//AT fusion center:\n\t\t#pragma omp single\n\t\t{\t\n\t\t\ti++;\n\t\t\tvec pseudo_data_total(N,fill::zeros);\n\t\t\tfor (unsigned int j = 0; j < P; j++){\n\t\t\t\tpseudo_data_total = pseudo_data_total + pseudo_data[j];\n\t\t\t}\n\t\t\n\t\t\ttau = tau * sum(eta_deriv(pseudo_data_total,tau)) / M;\n\t\t\tg_t = sum(eta_deriv(pseudo_data_total,tau));\n\t\t\tx_t = eta(pseudo_data_total,tau);\n\t\t\tif (norm (y - A*x_t) < tol || i >= max_iter){\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t}\n\t\t#pragma omp barrier\n\t}\n\t// parallel section of the code ends here\n\n\t}\n\n\tnum_iters = i;\n\treturn x_t;\n}\n\n\n\n", "meta": {"hexsha": "f50c8b297571bf0cbc12f70c9be525570ec9ae1f", "size": 3473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Parallel_AMP.cpp", "max_stars_repo_name": "LCWN-Lab/Parallel-Sparse-Recovery", "max_stars_repo_head_hexsha": "b5dd6b98977bcb437164f1c0109bc892f1d7141d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Parallel_AMP.cpp", "max_issues_repo_name": "LCWN-Lab/Parallel-Sparse-Recovery", "max_issues_repo_head_hexsha": "b5dd6b98977bcb437164f1c0109bc892f1d7141d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Parallel_AMP.cpp", "max_forks_repo_name": "LCWN-Lab/Parallel-Sparse-Recovery", "max_forks_repo_head_hexsha": "b5dd6b98977bcb437164f1c0109bc892f1d7141d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-24T04:15:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T17:25:19.000Z", "avg_line_length": 24.1180555556, "max_line_length": 97, "alphanum_fraction": 0.6605240426, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5217218542095051}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_BITWISE_FUNCTIONS_SCALAR_ILOG2_HPP_INCLUDED\n#define BOOST_SIMD_BITWISE_FUNCTIONS_SCALAR_ILOG2_HPP_INCLUDED\n\n#include <boost/simd/bitwise/functions/ilog2.hpp>\n#include <boost/simd/include/functions/scalar/clz.hpp>\n#include <boost/simd/include/functions/scalar/exponent.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/mpl/less_equal.hpp>\n#include <boost/mpl/sizeof.hpp>\n#include <boost/mpl/size_t.hpp>\n#include <boost/assert.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT         ( ilog2_, tag::cpu_, (A0)\n                            , (scalar_< floating_<A0> >)\n                            )\n  {\n    typedef typename dispatch::meta::as_integer<A0>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n      {\n        return exponent(a0);\n      }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT         ( ilog2_, tag::cpu_\n                            , (A0)\n                            , (scalar_< arithmetic_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      BOOST_ASSERT_MSG( a0 > 0, \"Logarithm is not defined for zero or negative values.\" );\n      return result_type(sizeof(A0)*8-boost::simd::clz(a0)-1);\n    }\n  };\n\n#if defined(BOOST_MSVC)\n  BOOST_DISPATCH_IMPLEMENT_IF         ( ilog2_, tag::cpu_\n                            , (A0)\n                            , (mpl::less_equal< mpl::sizeof_<A0>, mpl::size_t<4> >)\n                            , (scalar_< integer_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      BOOST_ASSERT_MSG( a0 > 0, \"Logarithm is not defined for zero or negative values.\" );\n      __assume( a0 > 0 );\n      unsigned long index;\n      BOOST_VERIFY(::_BitScanReverse(&index, a0));\n      return result_type(index);\n    }\n  };\n#endif\n\n#if defined(BOOST_MSVC) && defined(_WIN64)\n  BOOST_DISPATCH_IMPLEMENT         ( ilog2_, tag::cpu_\n                            , (A0)\n                            , (scalar_< ints64_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      BOOST_ASSERT_MSG( a0 > 0, \"Logarithm is not defined for zero or negative values.\" );\n      __assume( a0 > 0 );\n      unsigned long index;\n      BOOST_VERIFY(::_BitScanReverse64(&index, a0));\n      return index;\n    }\n  };\n#endif\n\n} } }\n\n#endif\n\n", "meta": {"hexsha": "f9e07e961ddb2837e930f76782b410422a8580f7", "size": 2882, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/bitwise/functions/scalar/ilog2.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/bitwise/functions/scalar/ilog2.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/boost/simd/base/include/boost/simd/bitwise/functions/scalar/ilog2.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 32.75, "max_line_length": 90, "alphanum_fraction": 0.5478834143, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5217218542095051}}
{"text": "/// ---------------------------------------------------------------------------\n/// @section LICENSE\n///  \n/// Copyright (c) 2016 Georgia Tech Research Institute (GTRI) \n///               All Rights Reserved\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 \n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \n/// DEALINGS IN THE SOFTWARE.\n/// ---------------------------------------------------------------------------\n/// @file filename.ext\n/// @author Kevin DeMarco <kevin.demarco@gtri.gatech.edu> \n/// @author Eric Squires <eric.squires@gtri.gatech.edu>\n/// @version 1.0\n/// ---------------------------------------------------------------------------\n/// @brief A brief description.\n/// \n/// @section DESCRIPTION\n/// A long description.\n/// ---------------------------------------------------------------------------\n\n#include <gtest/gtest.h>\n#include <gmock/gmock.h>\n#include <scrimmage/math/Quaternion.h>\n#include <scrimmage/math/Angles.h>\n#include <Eigen/Dense>\n#define _USE_MATH_DEFINES\n#include <cmath>\n\nusing Eigen::Vector3d;\nnamespace sc = scrimmage;\n\nTEST(test_quaternion, rotation) {\n    Vector3d vector = Vector3d(1, 0, 0);\n    sc::Quaternion quaternion(Vector3d(1, 1, 1), 2 * M_PI / 3);\n    Vector3d rotated_vector = quaternion.rotate(vector);\n    EXPECT_NEAR(rotated_vector(0), 0, 1e-10);\n    EXPECT_NEAR(rotated_vector(1), 1, 1e-10);\n    EXPECT_NEAR(rotated_vector(2), 0, 1e-10);\n}\n\nTEST(test_quaternion, reverse_rotation) {\n    Vector3d vector = Vector3d(1, 0, 0);\n    sc::Quaternion quaternion(Vector3d(1, 1, 1), -2 * M_PI / 3);\n    Vector3d rotated_vector = quaternion.rotate_reverse(vector);\n    EXPECT_NEAR(rotated_vector(0), 0, 1e-10);\n    EXPECT_NEAR(rotated_vector(1), 1, 1e-10);\n    EXPECT_NEAR(rotated_vector(2), 0, 1e-10);\n}\n\nTEST(test_quaternion, euler_convert) {\n    double roll = 0.3;\n    double pitch = 0.2;\n    double yaw = 0.1;\n    sc::Quaternion quaternion(roll, pitch, yaw);\n    EXPECT_NEAR(roll, quaternion.roll(), 1e-10);\n    EXPECT_NEAR(pitch, quaternion.pitch(), 1e-10);\n    EXPECT_NEAR(yaw, quaternion.yaw(), 1e-10);\n}\n\nTEST(test_quaternion, frames) {\n    Vector3d vec1(0, 0, 0);\n    Vector3d vec2(1, 0, 1);\n    Vector3d vec_diff = vec2 - vec1;\n\n    // pointing upward with negative pitch\n    sc::Quaternion q1(0, -sc::Angles::deg2rad(45), 0);  \n\n    Vector3d vec_diff_local1 = q1.rotate_reverse(vec_diff);\n    EXPECT_NEAR(sqrt(2), vec_diff_local1(0), 1e-10);\n    EXPECT_NEAR(0, vec_diff_local1(1), 1e-10);\n    EXPECT_NEAR(0, vec_diff_local1(2), 1e-10);\n\n    Vector3d vec_diff_global = q1.rotate(vec_diff_local1);\n    EXPECT_NEAR(vec_diff(0), vec_diff_global(0), 1e-10);\n    EXPECT_NEAR(vec_diff(1), vec_diff_global(1), 1e-10);\n    EXPECT_NEAR(vec_diff(2), vec_diff_global(2), 1e-10);\n}\n", "meta": {"hexsha": "03de7a8db815a632b1e77fcadbe38e30359aad75", "size": 3238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scrimmage/test/test_quaternion.cpp", "max_stars_repo_name": "ddfan/swarm_evolve", "max_stars_repo_head_hexsha": "cd2d972c021e9af5946673363fbfd39cff18f13f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T03:01:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T03:11:30.000Z", "max_issues_repo_path": "scrimmage/test/test_quaternion.cpp", "max_issues_repo_name": "lyers179/swarm_evolve", "max_issues_repo_head_hexsha": "cd2d972c021e9af5946673363fbfd39cff18f13f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-29T02:14:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T02:36:14.000Z", "max_forks_repo_path": "scrimmage/test/test_quaternion.cpp", "max_forks_repo_name": "lyers179/swarm_evolve", "max_forks_repo_head_hexsha": "cd2d972c021e9af5946673363fbfd39cff18f13f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-10-29T02:07:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T06:37:53.000Z", "avg_line_length": 37.6511627907, "max_line_length": 79, "alphanum_fraction": 0.6275478691, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5217218490610822}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_LBFGS_HPP\n#define MCL_LBFGS_HPP 1\n\n#include <Eigen/Dense>\n#include <vector>\n#include <functional>\n\nnamespace mcl\n{\n\n// L-BFGS implementation based on Nocedal & Wright Numerical Optimization book (Section 7.2)\n//\n// Function pointers are meant to be used with lambdas, e.g.\n//   LBFGS<MatrixXd> lbfgs;\n//   lbfgs.gradient = [&](const MatrixXd &x, MatrixXd &g)->Scalar { return ... };\n//   double obj = lbfgs.minimize(x);\n//\n// If the g arg is not sized, don't compute gradient\n//\ntemplate <typename MatrixType>\nclass LBFGS\n{\npublic:\n    typedef typename MatrixType::Scalar Scalar;\n\n\tstruct Options\n\t{\n\t\tint min_iters;\n\t\tint max_iters;\n\t\tScalar abs_tol; // absolute tol if converged(...) not set\n\t\tScalar rel_tol; // relative tol if converged(...) not set\n\t\tint M; // history window size\n\t\tScalar gamma; // init Hessian = gamma * I\n\t\tOptions() :\n\t\t\tmin_iters(0),\n\t\t\tmax_iters(100),\n\t\t\tabs_tol(1e-5),\n\t\t\trel_tol(0),\n\t\t\tM(6),\n\t\t\tgamma(1)\n\t\t\t{}\n\t} options;\n\n\tLBFGS();\n\n\t// Output from the last call to minimize(...)\n\tint iters() const { return num_iters; }\n\tScalar gamma() const { return gamma_k; }\n\n\t// Resizes buffers and sets to zero.\n\t// Called during minimize(...) ONLY if there is a change in dof or M.\n\t// Otherwise it's assumed you're picking up where you left off\n\t// on the previous call to minimize(...)\n\tvoid reset(int rows, int cols);\n\n\t// Required:\n\t// computes objective value and gradient\n\t//   obj = gradient(x, g)\n\t// If the g arg is not sized, don't compute gradient\n\tstd::function<Scalar(const MatrixType&, MatrixType&)> gradient;\n\n\t// Optional:\n\t// Returns true if the solver should exit, default uses ||g||<abs_tol or ||g||<||x||rel_tol\n\t//   is_converged = converged(obj, x_prev, x, grad)\n\tstd::function<bool(Scalar obj, const MatrixType&, const MatrixType&, const MatrixType&)> converged;\n\n\t// Optional:\n\t// Linesearch function, default uses bracketing weak wolfe (slow!)\n\t//   obj_k1 = (x, grad, descent, alpha)\n\t// Returns new objective value and updates both x AND gradient\n\tstd::function<Scalar(MatrixType&, MatrixType&, const MatrixType&, Scalar&)> linesearch;\n\n\t// Optional:\n\t// Filter descent direction, p = B(p)\n\t// Otherwise p = gamma_k * p is used.\n\tstd::function<void(MatrixType&)> filter;\n\n\t// Calls initialize(x) once and iterate(x) until converged\n\tScalar minimize(MatrixType& x);\n\n\t// Initialize the solver\n\tvoid initialize(MatrixType& x);\n\n\t// Take an iteration\n\t// Returns objective\n\tScalar iterate(MatrixType& x);\n\n\t// i.e. bisection with weak Wolfe conditions\n\tScalar bracketing_weakwolfe(\n\t\tMatrixType& x,\n\t\tMatrixType& grad,\n\t\tconst MatrixType& p,\n\t\tScalar &alpha) const;\n\n\t// Used if converged not set\n\t// Returns true if:\n\t// grad.norm <= abs_tol\n\t// or\n\t// grad.norm() <= rel_tol * x.norm()\n\tbool default_converged(\n\t\tScalar curr_obj,\n\t\tconst MatrixType& xprev,\n\t\tconst MatrixType& x,\n\t\tconst MatrixType& grad) const;\n\n\tScalar inner(\n\t\tconst MatrixType &a,\n\t\tconst MatrixType &b) const;\n\nprotected:\n\tbool initialized;\n\tint num_iters, max_iters, k;\n\tScalar gamma_k, obj_0, obj_k;\n\tstd::vector<MatrixType> s;\n\tstd::vector<MatrixType> y;\n\tEigen::Matrix<Scalar,Eigen::Dynamic,1> alpha;\n\tEigen::Matrix<Scalar,Eigen::Dynamic,1> rho;\n\tMatrixType grad;\n\tMatrixType q;\n\tMatrixType descent;\n\tMatrixType grad_old;\n\tMatrixType x_old;\n\tMatrixType x_last;\n\tMatrixType s_temp;\n\tMatrixType y_temp;\n\n}; // end class LBFGS\n\n//\n// Implementation\n//\n\ntemplate <typename MatrixType>\nLBFGS<MatrixType>::LBFGS() :\n\tinitialized(false),\n\tnum_iters(0),\n\tmax_iters(0),\n\tk(0),\n\tgamma_k(1),\n\tobj_0(0),\n\tobj_k(0)\n\t{}\n\ntemplate <typename MatrixType>\nvoid LBFGS<MatrixType>::reset(int rows, int cols)\n{\n    using namespace Eigen;\n\tnum_iters = 0;\n\tmax_iters = 0;\n\tk = 0;\n\tgamma_k = 1;\n\tobj_0 = std::numeric_limits<Scalar>::max();\n\tobj_k = std::numeric_limits<Scalar>::max();\n\tint M = options.M;\n\ts = std::vector<MatrixType>(M, MatrixType::Zero(rows,cols));\n\ty = std::vector<MatrixType>(M, MatrixType::Zero(rows,cols));\n\talpha = VectorXd::Zero(M);\n\trho = VectorXd::Zero(M);\n\tgrad = MatrixType::Zero(rows, cols);\n\tq = MatrixType::Zero(rows, cols); // inv descent\n\tdescent = q;\n\tgrad_old = MatrixType::Zero(rows, cols);\n\tx_old = MatrixType::Zero(rows, cols);\n\tx_last = MatrixType::Zero(rows, cols);\n\ts_temp = MatrixType::Zero(rows, cols);\n\ty_temp = MatrixType::Zero(rows, cols);\n}\n\n// Returns number of iterations used\ntemplate <typename MatrixType>\ntypename LBFGS<MatrixType>::Scalar\nLBFGS<MatrixType>::minimize(MatrixType &x)\n{\n\tinitialize(x);\n\n\t// Did we start at the initializer?\n\tif (num_iters >= options.min_iters &&\n\t\tconverged(obj_k,x_last,x,grad))\n\t{\n\t\tnum_iters = 1;\n\t\treturn obj_k;\n\t}\n\n\tfor (; k<max_iters; ++k)\n\t{\n\t\titerate(x);\n\t} // end loop lbfgs iters\n\n\treturn obj_k;\n\n} // end minimize\n\ntemplate <typename MatrixType>\nvoid LBFGS<MatrixType>::initialize(MatrixType& x)\n{\n\tinitialized = true;\n\n\tif (gradient == nullptr) {\n\t    throw std::runtime_error(\"no gradient function\");\n\t}\n\n\tif (converged == nullptr)\n\t{\n\t\tusing namespace std::placeholders;\n\t\tconverged = std::bind(&LBFGS::default_converged, this, _1, _2, _3, _4);\n\t}\n\n\tif (linesearch == nullptr)\n\t{\n\t\tusing namespace std::placeholders;\n\t\tlinesearch = std::bind(&LBFGS::bracketing_weakwolfe, this, _1, _2, _3, _4);\n\t}\n\n\t// Resize/resize variables?\n\tif (alpha.rows() != options.M ||\n\t\tgrad.rows() != x.rows() ||\n\t\tgrad.cols() != x.cols()) {\n\t\treset(x.rows(), x.cols());\n\t}\n\n\tnum_iters = 0;\n\tmax_iters = std::max(options.min_iters, options.max_iters);\n\tgamma_k = options.gamma;\n\tobj_0 = gradient(x, grad);\n\tobj_k = obj_0;\n\tk = 0;\n}\n\ntemplate <typename MatrixType>\ntypename LBFGS<MatrixType>::Scalar\nLBFGS<MatrixType>::iterate(MatrixType& x)\n{\n\tif (!initialized) {\n\t\tthrow std::runtime_error(\"not initialized\");\n\t}\n\n\tx_old = x;\n\tgrad_old = grad;\n\tq = grad;\n\tnum_iters++;\n\n\t//\n\t// Two-loop recursion\n\t//\n\t{\n\t\t// L-BFGS first - loop recursion\t\t\n\t\tint iter = std::min(options.M, k);\n\t\tfor(int i = iter - 1; i >= 0; --i)\n\t\t{\n\t\t\tScalar denom = inner(s[i], y[i]);\n\t\t\tif (std::abs(denom) <= 0.0)\n\t\t\t{\n\t\t\t\trho(i) = 0;\n\t\t\t\talpha(i) = 0;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\trho(i) = 1.0 / denom;\n\t\t\talpha(i) = rho(i)*inner(s[i], q);\n\t\t\tq -= alpha(i) * y[i];\n\t\t}\n\n\t\tif (filter != nullptr) { filter(q); }\n\t\telse { q = gamma_k*q; }\n\n\t\t// L-BFGS second - loop recursion\n\t\tfor(int i = 0; i < iter; ++i)\n\t\t{\n\t\t\tScalar beta = rho(i)*inner(q, y[i]);\n\t\t\tq += (alpha(i) - beta)*s[i];\n\t\t}\n\t}\n\n\t//\n\t// Perform step\n\t//\n\t{\n\t\t// If our hess approx is bad and we start going in\n\t\t// the wrong direction, restart memory\n\t\tScalar step_size = 1.0;\n\t\tScalar dir = inner(q, grad);\n\t\tif (dir <= 0)\n\t\t{\n\t\t\tq = grad;\n\t\t\tmax_iters -= k; // Restart memory\n\t\t\tk = 0;\n\t\t\tstep_size = std::min(1.0, 1.0 / grad.template lpNorm<Eigen::Infinity>() );\n\t\t}\n\n\t\t// We've hit local minima, we have to exit\n\t\tif (q.squaredNorm() <= 0.0) {\n\t\t\treturn obj_k;\n\t\t}\n\n\t\tdescent = -q;\n\t\tx_last = x;\n\t\tobj_k = linesearch(x, grad, descent, step_size);\n\t\tif (num_iters >= options.min_iters && converged(obj_k,x_last,x,grad)) {\n\t\t\treturn obj_k;\n\t\t}\n\t}\n\n\t//\n\t// Correction term\n\t//\n\t{\n\t\ts_temp = x - x_old;\n\t\ty_temp = grad - grad_old;\n\n\t\t// update the history\n\t\tif (k < options.M)\n\t\t{\n\t\t\ts[k] = s_temp;\n\t\t\ty[k] = y_temp;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int i=0; i<options.M - 1; ++i)\n\t\t\t{\n\t\t\t\ts[i] = s[i+1];\n\t\t\t\ty[i] = y[i+1];\n\t\t\t}\n\t\t\ts.back() = s_temp;\n\t\t\ty.back() = y_temp;\n\t\t}\n\n\t\tScalar denom = inner(y_temp, y_temp);\n\t\tif (std::abs(denom) > 0.0)\n\t\t{\n\t\t\tgamma_k = inner(s_temp, y_temp) / denom;\n\t\t}\n\t}\n\n\treturn obj_k;\n}\n\ntemplate <typename MatrixType>\ntypename LBFGS<MatrixType>::Scalar\nLBFGS<MatrixType>::bracketing_weakwolfe(\n\t\tMatrixType& x,\n\t\tMatrixType& g,\n\t\tconst MatrixType &drt,\n\t\tScalar &step) const\n{\n    using namespace Eigen;\n\n\tScalar c1 = 10e-4;\n\tScalar c2 = 0.9;\n\tif (step <= 0.0) { step = 1.0; }\n    int x_cols = x.cols();\n\n\tg = MatrixType::Zero(x.rows(), x_cols);\n\tMatrixType xp = x;\n\tconst Scalar fx_init = gradient(x,g);\n\tScalar fx = fx_init;\n\t\n\tScalar dg_init = inner(g, drt);\n    if (dg_init > 0) {\n        throw std::runtime_error(\"direction increases objective\");\n    }\n\n\tconst Scalar test_decr = c1 * dg_init;\n\tScalar lower = 0;\n\tScalar upper = std::numeric_limits<Scalar>::infinity();\n\tint maxiter = 200;\n\tint iter = 0;\n\tfor (iter = 0; iter < maxiter; iter++)\n\t{\n\t\tx = xp + step * drt;\n\t\tfx = gradient(x, g);\n\t\tif (fx > fx_init + step * test_decr) { // Armijo rule\n\t\t\tupper = step;\n\t\t}\n\t\telse\n\t\t{\t\t\n\t\t\tScalar dg = inner(g, drt);\t\t\t\n\t\t\tif(dg < c2 * dg_init){ // Weak wolfe\n\t\t\t\tlower = step;\n\t\t\t} else {\n\t\t\t\tbreak; // both met\n\t\t\t}\n\t\t}\n\t\tstep = std::isinf(upper) ? 2*step : lower/2 + upper/2;\n\t}\n\treturn fx;\n\n} // end linesearch\n\ntemplate <typename MatrixType>\nbool LBFGS<MatrixType>::default_converged(\n\t\tScalar curr_obj,\n\t\tconst MatrixType& xprev,\n\t\tconst MatrixType& x,\n\t\tconst MatrixType& g) const\n{\n\t(void)(curr_obj);\n\t(void)(xprev);\n\tScalar gnorm = g.norm();\n\tif (gnorm <= options.abs_tol) {\n\t    return true;\n\t}\n\tScalar xnorm = x.norm();\n\tif (gnorm < options.rel_tol * xnorm) {\n\t    return true;\n\t}\n\treturn false;\n}\n\ntemplate <typename MatrixType>\ntypename LBFGS<MatrixType>::Scalar\nLBFGS<MatrixType>::inner(\n    const MatrixType &a,\n    const MatrixType &b) const\n{\n    int cols = std::min(a.cols(), b.cols());\n    Scalar dot = 0;\n    for (int i=0; i<cols; ++i) {\n        dot += a.col(i).dot(b.col(i));\n    }\n    return dot;\n} // end inner product\n\n} // end ns mcl\n\n#endif\n", "meta": {"hexsha": "ae165ad06d305da268155869dc28eacc2e0c9088", "size": 9379, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/LBFGS.hpp", "max_stars_repo_name": "mattoverby/mclgeom", "max_stars_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/MCL/LBFGS.hpp", "max_issues_repo_name": "mattoverby/mclgeom", "max_issues_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-26T22:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T02:54:23.000Z", "max_forks_repo_path": "include/MCL/LBFGS.hpp", "max_forks_repo_name": "mattoverby/mclgeom", "max_forks_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9135514019, "max_line_length": 100, "alphanum_fraction": 0.6450581085, "num_tokens": 2913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5215845113132972}}
{"text": "#ifndef PLAN_H\n#define PLAN_H\n\n#include <cmath>\n#include \"nubot/core/core.hpp\"\n#include \"nubot/nubot_control/behaviour.hpp\"\n#include <boost/ptr_container/ptr_list.hpp>\n\nusing namespace std;\nnamespace nubot{\nclass WolrdModeliInfo\n{\n    public:\n           WolrdModeliInfo()\n               :active_robot_num_(0),is_robot_stuck_(false),ball_info_state_(0),\n                 game_ctrl_(CTRL_STOP),indist_(0)\n           {\n               robot_pos_ = DPoint(0.0,0.0);\n               robot_ori_ = Angle(0.0);\n               robot_vel_ = DPoint(0.0,0.0);\n               ball_pos_  = DPoint(0.0,0.0);\n               ball_vel_  = DPoint(0.0,0.0);\n               obs_pos_.reserve(10);\n               target_    = DPoint(0.0,0.0);\n               target_orientation_ = 0.0;\n           }\n           ~WolrdModeliInfo()\n           {}\n    public:\n\n           int    active_robot_num_;   //current active robot number\n\n           DPoint robot_pos_;          //robot position\n           Angle  robot_ori_;          //robot orientation\n           DPoint robot_vel_;          //robot velocity\n           bool   is_robot_stuck_;     //stuck check\n\n           DPoint ball_pos_;           //ball position\n           DPoint ball_vel_;           //ball velocity\n           int    ball_info_state_;    //ball information state    local ?  share ? or cannot see\n\n\n           std::vector<DPoint> obs_pos_;            //obstacle information\n\n           unsigned char game_ctrl_;   //current order\n\n           double    indist_;\n           DPoint    target_;             //target from coach\n           float     target_orientation_; //the orientation of the specified target\n\n\n};\n\n    class Plan\n    {\n    public:\n        Plan();\n        /*******************catch ball******************/\n        void \n        traceBall();      // trace\n        void\n        interceptBall();  // intercept\n\n        void\n        catchBall();\n        void\n        catchBallSlowly();\n        void\n        catchBallForCoop();\n        void\n        catchMovingBall();\n        void \n        catchMotionlessBall();\n\n        void\n        positionAvoidObs(DPoint target, float theta, float stopdis, float stoptheta);\n\n        DPoint\n        avoidRelOble(DPoint target, double theta, double ro, double vel, bool includeball);\n        void\n        driblleControl(DPoint target,double acc,double sacc,double lvel,double maxvel);\n\n        void\n            move2Positionwithobs(DPoint target, float maxvel, float maxacc);  // move to the target point with obstacles avoidance\n        void\n            move2Positionwithobs_noball(DPoint target, float maxvel, float maxacc, bool avoid_ball=false);\n        //subtargets\n        int\n        Min_num(int n,double *q);\n        double\n        Min(int n,double *q);\n        int\n        Max_num(int n,double *q);\n        double\n        Max(int n,double *q);\n        void\n        subtarget(double *obs,double *pos_robot,double *pos_target,double *pos_subtarget);\n        void\n        subtargets(DPoint target,DPoint robotpos);\n        void\n        subtargets_withball(DPoint target,DPoint robotpos);\n        void\n        subtargets2(DPoint target,DPoint robotpos);\n\n\n\n        double\n               CaculatediffS(double &s, double &rho,double &phid,\n                             double v0,double c ,  double alpha ,\n                             double p,double q,double  diffp,double diffq);\n               double\n               CaculatediffS(double &s, double &rho,double &phid,\n                             double lamda,double v0,double p,\n                             double q,double  diffp,double diffq);\n               double\n               CaculatePhid(double  rho,double basic_phid ,\n                            double thetar , double eps);\n              \n\n              double\n               Curvature(double diffp , double diffq, double double_diffp,double double_diffq);\n\n               \n\n\n           boost::ptr_list<DPoint> Active_ControlPointList;\n               boost::ptr_list<DPoint> Passive_ControlPointList;\n\n               double\n               Bernstein(double s , int i , int N);\n               void\n               Bezier(double s,boost::ptr_list<DPoint> &controlpoint,\n                      double &p ,double &q, double &diffp,double &diffq,\n                      double &double_diffp, double &double_diffq); //  \u00bf\u00d8\u00d6\u00c6\u00b5\u00e3 \u00a3\u00ac \u00bf\u017d\u00ca\u00c7\u0152\u017e\u0153\u00d7\u00b5\u00c4bezier\u00c7\u00fa\u00cf\u00df ...\n\n               void\n               Bezier(double s,boost::ptr_list<DPoint> &controlpoint,\n                      double &p ,double &q, double &diffp,double &diffq);\n               bool\n               BezierPathFollow( boost::ptr_list<DPoint> &controlpoint ,\n                                 double v0,double c , double alpha ,double k,\n                                 double lamda ,double eps); //s\n               void\n               FromPath2Trajectory(double &s,double &rtheta ,double vr,\n                                   double wr,double diffp,double diffq,\n                                   double double_diffp,double double_diffq,\n                                   double vprofile ,double aprofile);//\n               //bool\n               //BezierTrajectoryTracking4Pass(boost::ptr_list<DPoint> &controlpoint ,double v0,double a);\n                bool\n                BezierTrajectoryTracking(boost::ptr_list<DPoint> &controlpoint ,double v0,double a);\n\n                double\n                PECrossBackMIdlleLine(double direction);\n                double\n                PEOutField(double diretion);\n                double\n                PEInOurPenaty(double direction);\n                double\n                PObleDirection4OurField(double direction, double predictlen,double cobledirection,\n                                               double kobledirection);\n\n\n                bool\n                SearchMinPE4PassThroughforOurField(double &direction,double pridictlen,\n                                                          DPoint trap[4],double step,int flg);\n\n                bool\n                SearchMinPE4PassThrough(double &direction,double pridictlen,\n                                        DPoint trap[4],double step,int flg);\n\n\n\n\n                bool\n                IsNullInTrap(double direction,double swidth,double lwidth,double len);\n                bool\n                checkinOurField(DPoint mypos);\n                bool\n                checkinOppField(DPoint mypos);\n                bool\n                checkinOurPenalty(DPoint object);\n                double\n                PObleDirection(double direction, double predictlen, double cobledirection,double kobledirection);\n\n                DPoint\n                FindBstDirectionForAvoid(DPoint target);\n                double\n                FindBstDirectionForAvoid();\n                double\n                FindBstDirectionForAvoid2(DPoint target);\n                double\n                SearchDirectionforMinPEPoint(double oridirection,double step,int lefttime,int righttime);\n                int\n                GetAvoidState();\n\n    public:\n        Behaviour m_behaviour_;\n        WolrdModeliInfo* worldmodelinfo_;\n\n        DPoint   subtargets_pos_;\n        DPoint   subtargets2_pos_;\n\n        bool inourfield_;\n        bool inoppfield_;\n        double lastdirection;\n        double pe1_;\n        double pe2_;\n        bool   isnull_;\n\n\n        double bezier_s;\n        bool   bezier_updateflag;\n        double bezier_vr ,bezier_wr ;\n        double bezier_vm ;\n        double bezier_p ,bezier_q ,bezier_rtheta ;  //  \u017d\u00cb\u017d\u0160\u00d3\u00c3\u00b5\u00c4\u00ca\u00c7static \u00a3\u00ac\u00b1\u00d8\u00d0\u00eb\u017e\u00c4\u00b1\u00e4\u00b2\u00c5\u00d0\u00d0\n        double last_bezier_rtheta;\n\n        float kp;\n        float kalpha;\n        float kbeta;\n\n        vector<DPoint> target_;\n\n    public:\n        bool   isinposition_;\n\n    };\n}\n#endif // PLAN_H\n", "meta": {"hexsha": "03f0512359b54be5ce4b8f67ece2effcd89084f3", "size": 7690, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/robot_code/nubot_control/include/nubot/nubot_control/plan.hpp", "max_stars_repo_name": "SaligiaR/simatch", "max_stars_repo_head_hexsha": "a295a39500518ec220fa511ebfb2b50daab84b4e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2016-09-17T13:18:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T01:19:49.000Z", "max_issues_repo_path": "src/robot_code/nubot_control/include/nubot/nubot_control/plan.hpp", "max_issues_repo_name": "SaligiaR/simatch", "max_issues_repo_head_hexsha": "a295a39500518ec220fa511ebfb2b50daab84b4e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2016-09-09T14:40:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T08:10:44.000Z", "max_forks_repo_path": "src/robot_code/nubot_control/include/nubot/nubot_control/plan.hpp", "max_forks_repo_name": "SaligiaR/simatch", "max_forks_repo_head_hexsha": "a295a39500518ec220fa511ebfb2b50daab84b4e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2016-09-09T14:49:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T15:02:54.000Z", "avg_line_length": 33.29004329, "max_line_length": 130, "alphanum_fraction": 0.5361508453, "num_tokens": 1665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.847967769904032, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5215746771370123}}
{"text": "\n#include <bitset>\n \n#include <boost/utility/enable_if.hpp>\n#include <boost/integer.hpp>\n#include <boost/integer/static_log2.hpp>\n#include <boost/integer/static_min_max.hpp>\n#include <boost/integer_traits.hpp>\n\nnamespace boost {\n\ttemplate <class T>\n\tclass integer_traits<const T> : public integer_traits<T> { };\n}\n\ntemplate <size_t N, class Type = void, class Enable = void>\nstruct is_power_of_two {\n\tstatic const bool value = false;\n};\ntemplate <size_t N, class Type>\nstruct is_power_of_two<N, Type, typename boost::enable_if_c<(N & (N - 1)) == 0>::type> {\n\tstatic const bool value = true;\n\ttypedef Type type;\n};\n\ntemplate <size_t N, class Enable = void>\nstruct log_next_power_of_two {\n\tstatic const size_t value = boost::static_log2<N>::value + 1;\n};\ntemplate <size_t N>\nstruct log_next_power_of_two<N, typename boost::enable_if<is_power_of_two<N> >::type> {\n\tstatic const size_t value = boost::static_log2<N>::value;\n};\n\ntemplate <size_t N, class Enable = void>\nstruct next_power_of_two {\n\tstatic const size_t value = size_t(1) << (boost::static_log2<N>::value + 1);\n};\ntemplate <size_t N>\nstruct next_power_of_two<N, typename boost::enable_if<is_power_of_two<N> >::type> {\n\tstatic const size_t value = N;\n};\n\n\nstruct fast_integers {\n\t\nprivate:\n\t\n\ttemplate <size_t Bits, class Dummy = void> struct _impl { };\n\ttemplate <class Dummy> struct _impl<8, Dummy> { typedef uint_fast8_t type; };\n\ttemplate <class Dummy> struct _impl<16, Dummy> { typedef uint_fast16_t type; };\n\ttemplate <class Dummy> struct _impl<32, Dummy> { typedef uint_fast32_t type; };\n\ttemplate <class Dummy> struct _impl<64, Dummy> { typedef uint_fast64_t type; };\n\ttemplate <class Dummy> struct _impl<128, Dummy> { typedef __uint128_t type; };\n\t\npublic:\n\t\n\ttemplate <size_t Bits>\n\tstruct bits : public _impl<boost::static_unsigned_max<8, next_power_of_two<Bits>::value>::value> { };\n\t\n};\n\nstruct exact_integers {\n\t\nprivate:\n\t\n\ttemplate <size_t Bits, class Dummy = void> struct _impl { };\n\ttemplate <class Dummy> struct _impl<8, Dummy> { typedef uint8_t type; };\n\ttemplate <class Dummy> struct _impl<16, Dummy> { typedef uint16_t type; };\n\ttemplate <class Dummy> struct _impl<32, Dummy> { typedef uint32_t type; };\n\ttemplate <class Dummy> struct _impl<64, Dummy> { typedef uint64_t type; };\n\ttemplate <class Dummy> struct _impl<128, Dummy> { typedef __uint128_t type; };\n\t\npublic:\n\t\n\ttemplate <size_t Bits>\n\tstruct bits : public _impl<boost::static_unsigned_max<8, next_power_of_two<Bits>::value>::value> { };\n\t\n};\n\nstruct bitset_types {\n\t\n\ttemplate <size_t Bits>\n\tstruct bits {\n\t\ttypedef std::bitset<Bits> type;\n\t};\n\t\n};\n\n\n/*!\n * Converter that rearranges bits in an integer.\n *\n * Conversion is reduced to a minimal number of mask & shift operations at compile-time. \n *\n * Usage:\n *\n *  bitset_converter&lt;&gt; is an empty converter list (cannot be used without adding at least one mappings).\n *  (list)::add::map&lt;from, to&gt maps the from'th input bit to the to'th output bit.\n *\n *  Convenience function to add a continous region of mappings:\n *  bitset_converter&lt;&gt;::add::value&lt;to2&gt; is equivalent to bitset_converter&lt;&gt;::add::map&lt;0, to2&gt;\n *  (list)::add::map&lt;from, to&gt::add::value&lt;to2&gt; is equivalent to ::add::map&lt;from, to&gt::add::map&lt;from + 1, to2&gt;\n *\n *  Inut bits without a corresponding \"from\" entry are ignored.\n *  Output bit without a corresponding \"to\" entry are always zero.\n *\n *  The same input/output bit can appear in multiple mappings.\n *\n *  Invoke the converter: (list)::convert(integer)\n *\n * Limitations:\n *\n *  Input bits must fit in a native integer type provided by in_types::bits&lt;bits&gt;.\n *\n *  Output bits must fit in an integer type selected by out_types::bits&lt;bits&gt;.\n *\n * Example:\n *\n *  // Create a converter that swaps the first two bits, keeps the next one and ignores all others.\n *  typedef bitset_converter<>::add::map<0, 1>::add::map<1, 0>::add::value<2> Converter;\n *\n *  // Convert something.\n *  Converter::convert(3);\n * \n */\ntemplate <class out_types = fast_integers, class in_types = fast_integers>\nstruct bitset_converter {\n\t\nprivate:\n\t\n\ttypedef ptrdiff_t shift_type;\n\ttypedef size_t index_type;\n\t\n\ttemplate <class Combiner, class Entry>\n\tstruct IterateEntries {\n\t\tstatic const typename Combiner::type value = Combiner::template combine<Entry, (IterateEntries<Combiner, typename Entry::next>::value)>::value;\n\t};\n\ttemplate <class Combiner> struct IterateEntries<Combiner, void> { static const typename Combiner::type value = Combiner::base; };\n\ttemplate <class Type, Type Base> struct Combiner { typedef Type type; static const Type base = Base; };\n\t\n\ttemplate<class Getter, class Type>\n\tstruct MaxCombiner : public Combiner<Type, boost::integer_traits<Type>::const_min> {\n\t\ttemplate <class Entry, Type accumulator>\n\t\tstruct combine { static const Type value = boost::static_signed_max<Getter::template get<Entry>::value, accumulator>::value; };\n\t};\n\t\n\ttemplate<class Getter, class Type>\n\tstruct MinCombiner : public Combiner<Type, boost::integer_traits<Type>::const_max> {\n\t\ttemplate <class Entry, Type accumulator>\n\t\tstruct combine { static const Type value = boost::static_signed_min<Getter::template get<Entry>::value, accumulator>::value; };\n\t};\n\t\n\tstruct ShiftGetter { template<class Entry> struct get { static const shift_type value = Entry::shift; }; };\n\tstruct FromGetter { template<class Entry> struct get { static const index_type value = Entry::from; }; };\n\tstruct ToGetter { template<class Entry> struct get { static const index_type value = Entry::to; }; };\n\t\n\ttemplate<shift_type Shift, class Type>\n\tstruct ShiftMaskCombiner : public Combiner<Type, Type(0)> {\n\t\ttemplate <class Entry, Type mask>\n\t\tstruct combine { static const Type value = mask | ( (Entry::shift == Shift) ? (Type(1) << Entry::from) : Type(0) ); };\n\t};\n\t\n\ttemplate<class List>\n\tstruct Builder;\n\t\n\ttemplate<index_type From, index_type To, class Next = void>\n\tstruct Entry {\n\t\t\n\t\ttypedef Entry<From, To, Next> This;\n\t\t\n\t\tstatic const index_type from = From;\n\t\tstatic const index_type to = To;\n\t\ttypedef Next next;\n\t\t\n\t\tstatic const shift_type shift = shift_type(from) - shift_type(to);\n\t\t\n\t\tstatic const shift_type max_shift = IterateEntries<MaxCombiner<ShiftGetter, shift_type>, This>::value;\n\t\tstatic const shift_type min_shift = IterateEntries<MinCombiner<ShiftGetter, shift_type>, This>::value;\n\t\t\n\t\tstatic const index_type in_bits = IterateEntries<MaxCombiner<FromGetter, index_type>, This>::value + 1;\n\t\ttypedef typename in_types::template bits<in_bits>::type in_type;\n\t\t\n\t\tstatic const index_type out_bits = IterateEntries<MaxCombiner<ToGetter, index_type>, This>::value + 1;\n\t\ttypedef typename out_types::template bits<out_bits>::type out_type;\n\t\t\n\t\ttemplate<shift_type Shift>\n\t\tstruct ShiftMask { static const in_type value = IterateEntries<ShiftMaskCombiner<Shift, in_type>, This>::value; };\n\t\t\n\t\ttemplate <shift_type Shift>\n\t\tinline static typename boost::enable_if_c<(Shift >= shift_type(0)), out_type>::type evaluate(in_type value) {\n\t\t\treturn out_type((value & ShiftMask<Shift>::value) >> Shift);\n\t\t}\n\t\ttemplate <shift_type Shift>\n\t\tinline static typename boost::enable_if_c<(Shift < shift_type(0)), out_type>::type evaluate(in_type value) {\n\t\t\treturn out_type(value & ShiftMask<Shift>::value) << (-Shift); \n\t\t}\n\t\t\n\t\ttemplate<shift_type Shift, class Enable = void>\n\t\tstruct NextShift { static const shift_type value = Shift + 1; };\n\t\ttemplate<shift_type Shift>\n\t\tstruct NextShift<Shift, typename boost::enable_if_c<Shift != max_shift && ShiftMask<Shift + 1>::value == in_type(0)>::type > {\n\t\t\tstatic const shift_type value = NextShift<Shift + 1>::value;\n\t\t};\n\t\t\n\t\ttemplate <shift_type Shift>\n\t\tinline static typename boost::enable_if_c<(NextShift<Shift>::value != max_shift + 1), out_type>::type map(in_type value) {\n\t\t\treturn evaluate<Shift>(value) | (map<NextShift<Shift>::value>(value));\n\t\t}\n\t\ttemplate <shift_type Shift>\n\t\tinline static typename boost::enable_if_c<(NextShift<Shift>::value == max_shift + 1), out_type>::type map(in_type value) {\n\t\t\treturn evaluate<Shift>(value);\n\t\t}\n\t\t\n\tpublic:\n\t\t\n\t\ttypedef Builder<This> add;\n\t\t\n\t\tstatic out_type convert(in_type value) {\n\t\t\treturn map<min_shift>(value);\n\t\t}\n\t\t\n\t};\n\t\n\ttemplate<class List>\n\tstruct Builder {\n\t\t\n\t\ttemplate<index_type From, index_type To>\n\t\tstruct map : public Entry<From, To, List> { };\n\t\t\n\t\ttemplate<index_type To, class Current = List>\n\t\tstruct value : public Entry<Current::from + 1, To, Current> { };\n\t\t\n\t\ttemplate<index_type To>\n\t\tstruct value<To, void> : public Entry<0, To> { };\n\t\t\n\t};\n\t\npublic:\n\t\n\ttypedef Builder<void> add;\n\t\n};\n", "meta": {"hexsha": "a4af7ae43c9c1dafe84d9218858ac6e74616c86a", "size": 8578, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/bitset_converter.hpp", "max_stars_repo_name": "dscharrer/void", "max_stars_repo_head_hexsha": "80a0281f18dd8d32db8ceb5e7db31f4c8af096f6", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T02:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T20:52:15.000Z", "max_issues_repo_path": "c++/bitset_converter.hpp", "max_issues_repo_name": "dscharrer/void", "max_issues_repo_head_hexsha": "80a0281f18dd8d32db8ceb5e7db31f4c8af096f6", "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": "c++/bitset_converter.hpp", "max_forks_repo_name": "dscharrer/void", "max_forks_repo_head_hexsha": "80a0281f18dd8d32db8ceb5e7db31f4c8af096f6", "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": 35.3004115226, "max_line_length": 145, "alphanum_fraction": 0.7173000699, "num_tokens": 2248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5215746747738026}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <stdio.h>\n#include <time.h>\n\n// OpenCV headers\n#include <cv.h>\n#include <highgui.h>\n\n#include <opencv2/contrib/contrib.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/video/tracking.hpp>\n\n#include <opencv_workbench/syllo/syllo.h>\n//\n#include <opencv_workbench/utils/AnnotationParser.h>\n#include <opencv_workbench/plot/Plot.h>\n#include <opencv_workbench/track/Dynamics.h>\n#include <opencv_workbench/track/KalmanFilter.h>\n#include <opencv_workbench/track/EKF.h>\n\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n\nusing std::cout;\nusing std::endl;\n\nint main(int argc, char *argv[])\n{\n     cout << \"Kalman Filter Test\" << endl;     \n\n     double t0 = 0;\n     double dt = 0.1;\n     double tend = 10;\n \n     // Setup boost RNG\n     boost::mt19937 rng;\n     boost::normal_distribution<> nd(0,1.0);\n     boost::variate_generator<boost::mt19937&, \n                              boost::normal_distribution<> > var_nor(rng,nd);\n     \n     ///////////////////////////////////////////////////////\n     // Setup Cart Model \n     Dynamics::state_5d_type input;\n     input[0] = 5;\n     input[1] = 3.14159265359/20;//0\n          \n     Dynamics dyn;\n     dyn.set_time(t0, dt, tend);\n     dyn.set_model(Dynamics::cart);\n     dyn.set_input(input);\n     dyn.set_process_noise(0.0);\n     dyn.set_measurement_noise(0.1);\n     \n     dyn.compute_trajectory();     \n     std::vector<cv::Point2d> truth = dyn.truth_points();\n     std::vector<cv::Point2d> measured = dyn.measured_points();\n\n     ////////////////////////////////////////////////////////\n     // Setup Kalman Filter\n     // Kalman filter setup...\n\n     syllo::KalmanFilter kf;\n     Eigen::MatrixXf A;     // system matrix\n     Eigen::MatrixXf B;     // input matrix\n     Eigen::MatrixXf H;     // measurement matrix\n     Eigen::MatrixXf Q;     // process noise matrix\n     Eigen::MatrixXf R;     // measurement noise matrix\n     Eigen::MatrixXf x0;    // initial position\n     Eigen::MatrixXf covar; // initial state covariance matrix \n     \n     A.resize(4,4);\n     B.resize(4,2);\n     H.resize(2,4);\n     Q.resize(4,4);\n     R.resize(2,2);\n     x0.resize(4,1);\n     covar.resize(4,4);\n          \n     double T = dt;     \n     A << 1, 0, T, 0,\n          0, 1, 0, T,\n          0, 0, 1, 0,\n          0, 0, 0, 1;\n     \n     B << 0, 0,\n          1, 0,\n          0, 0,\n          0, 1;\n     \n     H << 1, 0, 0, 0,\n          0, 1, 0, 0;\n     \n     Q = Eigen::MatrixXf::Identity(A.rows(), A.cols()) * 1e-4;\n     \n     //R << 10, 0,\n     //     0, 10;\n     R << .001, 0,\n          0, .001;\n     \n     //x = [x, y, x_dot, y_dot]\n     x0 << 0, \n           0,\n           0,\n           0;\n     \n     covar << 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     kf.setModel(A,B,H,Q,R);\n     kf.init(x0, covar);\n\n     // Setup OpenCV's kalman filter tracker\n     cv::KalmanFilter opencv_kf = cv::KalmanFilter(4, 2, 0);          \n     cv::Mat_<float> transition_matrix = cv::Mat_<float>(4,4);\n     transition_matrix  << 1,0,T,0,   \n                           0,1,0,T,  \n                           0,0,1,0,  \n                           0,0,0,1;\n     \n     opencv_kf.transitionMatrix = transition_matrix;\n\n     opencv_kf.statePre.at<float>(0) = 0;\n     opencv_kf.statePre.at<float>(1) = 0;\n     opencv_kf.statePre.at<float>(2) = 2;\n     opencv_kf.statePre.at<float>(3) = 0;\n     cv::setIdentity(opencv_kf.measurementMatrix);\n     cv::setIdentity(opencv_kf.processNoiseCov, cv::Scalar::all(1e-4));\n     cv::setIdentity(opencv_kf.measurementNoiseCov, cv::Scalar::all(0.001));\n     cv::setIdentity(opencv_kf.errorCovPost, cv::Scalar::all(0.1));\n\n     /////////////////////////////////////////////////////////\n     // Process the measured points with the kalman filter\n     std::vector<cv::Point2d> kf_points;\n     std::vector<cv::Point2d> opencv_kf_points;\n     std::vector<cv::Point2d> kf_var_x;\n     std::vector<cv::Point2d> kf_var_y;\n     std::vector<cv::Point2d> error;\n     std::vector<cv::Point2d>::iterator it = measured.begin();\n     std::vector<cv::Point2d>::iterator it_truth = truth.begin();\n     double t = t0;\n     for(; it != measured.end(); it++) {\n          Eigen::MatrixXf u, z;\n          u.resize(2,1);\n          u << 0,\n               0;\n          \n          z.resize(2,1);\n          z << it->x , it->y;\n          \n          kf.predict(u);\n          kf.update(z);\n\n          //////////////////////////////////////////\n          // Opencv\n          cv::Mat prediction = opencv_kf.predict();\n          cv::Point predictPt(prediction.at<float>(0),prediction.at<float>(1));\n\n          // correct tracker update using the newly computed centroid.\n          cv::Mat_<float> measurement(2,1);\n          measurement(0) = it->x;\n          measurement(1) = it->y;\n          \n          cv::Mat estimated = opencv_kf.correct(measurement);\n          cv::Point2d est_centroid = cv::Point2d(estimated.at<float>(0),estimated.at<float>(1));\n          opencv_kf_points.push_back(est_centroid);\n          ////////////////////////////////////////////\n                    \n          Eigen::MatrixXf state = kf.state();          \n          kf_points.push_back(cv::Point2d(state(0,0),state(1,0)));\n\n          Eigen::MatrixXf covar = kf.covariance();\n          kf_var_x.push_back(cv::Point2d(t,covar(0,0)));\n          kf_var_y.push_back(cv::Point2d(t,covar(1,1)));\n\n          double err = sqrt( pow(state(0,0) - it_truth->x, 2) + pow(state(1,0) - it_truth->y, 2) );\n          error.push_back(cv::Point2d(t,err));\n          \n          it_truth++;          \n          t += dt;\n          \n#if 0\n          std::string temp;\n          std::cin >> temp;\n#endif\n     }\n    \n     /////////////////////////////////////////////////////////     \n     // Plot the tracks\n     std::vector< std::vector<cv::Point2d> > vectors;     \n     const std::string title = \"Tracks\";\n     std::vector<std::string> labels;\n     std::vector<std::string> styles;\n     \n     vectors.push_back(truth);\n     labels.push_back(\"Truth\");\n     styles.push_back(\"points\");\n     \n     vectors.push_back(measured);\n     labels.push_back(\"Measured\");\n     styles.push_back(\"points\");\n\n     vectors.push_back(kf_points);\n     labels.push_back(\"KF\");\n     styles.push_back(\"linespoints\");\n\n     vectors.push_back(opencv_kf_points);\n     labels.push_back(\"OPENCV KF\");\n     styles.push_back(\"linespoints\");\n     \n     syllo::Plot plot;\n     plot.plot(vectors, title, labels, styles);\n     \n     ////////////////////////////////////////////////////\n     vectors.clear() ; labels.clear(); styles.clear();\n     const std::string title_covar = \"Covariance\";\n\n     vectors.push_back(kf_var_x);\n     labels.push_back(\"X Var\");\n     styles.push_back(\"points\");\n          \n     vectors.push_back(kf_var_y);\n     labels.push_back(\"Y Var\");\n     styles.push_back(\"points\");\n\n     vectors.push_back(error);\n     labels.push_back(\"Error\");\n     styles.push_back(\"points\");\n     \n     syllo::Plot plot_covar;\n     plot_covar.plot(vectors, title_covar, labels, styles);          \n     return 0;\n}\n", "meta": {"hexsha": "783255a099cf6663e12a2d8586818b6b5c676de0", "size": 7150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "share/ekf-test/main.cpp", "max_stars_repo_name": "SyllogismRXS/opencv-workbench", "max_stars_repo_head_hexsha": "2fb5b0d67589642d438f21f1cf58aaa761d15757", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-10-05T04:33:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-20T02:47:36.000Z", "max_issues_repo_path": "share/ekf-test/main.cpp", "max_issues_repo_name": "SyllogismRXS/opencv-workbench", "max_issues_repo_head_hexsha": "2fb5b0d67589642d438f21f1cf58aaa761d15757", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "share/ekf-test/main.cpp", "max_forks_repo_name": "SyllogismRXS/opencv-workbench", "max_forks_repo_head_hexsha": "2fb5b0d67589642d438f21f1cf58aaa761d15757", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2015-07-18T16:01:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-28T11:56:02.000Z", "avg_line_length": 30.0420168067, "max_line_length": 99, "alphanum_fraction": 0.5267132867, "num_tokens": 1981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5215746724105927}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <memory>\n#include \"fastenvelope/FastEnvelope.h\"\n\nnamespace GEO {\nclass MeshFacetsAABBWithEps;\nclass Mesh;\n} // namespace GEO\n\nnamespace sample_envelope {\nclass SampleEnvelope\n{\npublic:\n    SampleEnvelope(bool exact = false)\n        : use_exact(exact){};\n    double eps2 = 1e-6;\n    double sampling_dist = 1e-3;\n    bool use_exact = false;\n    void init(\n        const std::vector<Eigen::Vector3d>& m_ver,\n        const std::vector<Eigen::Vector3i>& m_faces,\n        const double);\n    bool is_outside(const std::array<Eigen::Vector3d, 3>& tris);\n    bool is_outside(const Eigen::Vector3d& pts);\n\nprivate:\n    std::shared_ptr<GEO::MeshFacetsAABBWithEps> geo_tree_ptr_;\n    std::shared_ptr<GEO::Mesh> geo_polyhedron_ptr_;\n    std::vector<int> geo_vertex_ind;\n    std::vector<int> geo_face_ind;\nprivate:\n    fastEnvelope::FastEnvelope exact_envelope;\n};\n} // namespace sample_envelope", "meta": {"hexsha": "c18f265c4dd9212ffcefcbc5f024651614834f32", "size": 926, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "app/ShortestEdgeCollapse/src/sec/envelope/SampleEnvelope.hpp", "max_stars_repo_name": "wildmeshing/wildmeshing-toolkit", "max_stars_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T08:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:19:41.000Z", "max_issues_repo_path": "app/ShortestEdgeCollapse/src/sec/envelope/SampleEnvelope.hpp", "max_issues_repo_name": "wildmeshing/wildmeshing-toolkit", "max_issues_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 86.0, "max_issues_repo_issues_event_min_datetime": "2021-12-03T01:46:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T19:33:17.000Z", "max_forks_repo_path": "app/ShortestEdgeCollapse/src/sec/envelope/SampleEnvelope.hpp", "max_forks_repo_name": "wildmeshing/wildmeshing-toolkit", "max_forks_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-26T08:29:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T22:10:42.000Z", "avg_line_length": 25.7222222222, "max_line_length": 64, "alphanum_fraction": 0.7062634989, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.521574665320963}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <vector>\n#include \"kws.h\"\n#include \"ctc_utils.h\"\n\nnamespace {\n\nstatic const float neginf = -std::numeric_limits<float>::infinity();\n\ninline float log_add(float a, float b) {\n    if (a == neginf) return b;\n    if (b == neginf) return a;\n    if (a > b)\n        return log1p(exp(b-a)) + a;\n    else\n        return log1p(exp(a-b)) + b;\n}\n\n}\n\n/* Computes forward probabilities for a given keyword.\n * Scores keyword as *keyword* allowing for arbitrary\n * pre and post characters.\n * *NB* undefined if keyword is empty string.\n */\nfloat cscore_kws(const float* probs,\n                 const int T, const int alphabet_size,\n                 const int blank,\n                 const std::vector<int>& labels) {\n\n    std::vector<int> labels_w_blanks;\n    std::vector<int> e_inc;\n    std::vector<int> s_inc;\n    int repeats = setup_labels(labels, blank, labels_w_blanks,\n                               s_inc, e_inc);\n\n    const int S = labels_w_blanks.size();\n    float* prev_alphas = new float[S];\n    float* next_alphas = new float[S];\n\n    std::fill(prev_alphas, prev_alphas + S, neginf);\n\n    int start =  (((S /2) + repeats - T) < 0) ? 0 : 1,\n            end = S > 1 ? 2 : 1;\n\n    for (int i = start; i < end; ++i) {\n        if (i == 0) {\n            prev_alphas[i] = std::log(1 - probs[labels_w_blanks[1]]);\n        } else {\n            int l = labels_w_blanks[i];\n            prev_alphas[i] = std::log(probs[l]);\n        }\n    }\n\n    for(int t = 1; t < T; ++t) {\n        std::fill(next_alphas, next_alphas + S, neginf);\n\n        int remain = (S / 2) + repeats - (T - t);\n        if(remain >= 0)\n            start += s_inc[remain];\n        if(t <= (S / 2) + repeats)\n            end += e_inc[t - 1];\n        int startloop = start;\n        int idx = t * alphabet_size;\n\n        if (start == 0) {\n            float star_score = std::log(1 - probs[idx + labels_w_blanks[1]]);\n            next_alphas[0] = prev_alphas[0] + star_score;\n            startloop += 1;\n        }\n\n        for(int i = startloop; i < end; ++i) {\n            int l = labels_w_blanks[i];\n            float prev_sum = log_add(prev_alphas[i], prev_alphas[i-1]);\n\n            // Skip two if not on blank and not on repeat.\n            if (l != blank && i != 1 &&\n                    l != labels_w_blanks[i-2])\n                prev_sum = log_add(prev_sum, prev_alphas[i-2]);\n\n            next_alphas[i] = prev_sum;\n            if (i == labels_w_blanks.size() - 1) {\n                float nl_score = probs[idx + labels_w_blanks[i-1]];\n                next_alphas[i] += std::log(1 - nl_score);\n            } else {\n                next_alphas[i] += std::log(probs[l + idx]);\n            }\n        }\n        std::swap(prev_alphas, next_alphas);\n    }\n\n    float loglike = neginf;\n    for(int i = start; i < end; ++i) {\n        loglike = log_add(loglike, prev_alphas[i]);\n    }\n\n    // Cleanup\n    delete[] prev_alphas;\n    delete[] next_alphas;\n\n    return -loglike;\n}\n\n#ifdef PYTHON\n#include <boost/python.hpp>\n#include <boost/python/extract.hpp>\n#include <boost/python/numeric.hpp>\n#include <numpy/noprefix.h>\n\nnamespace py = boost::python;\nnamespace np = boost::python::numeric;\n\nfloat score_kws(np::array probs, py::list labels,\n                const int blank) {\n    // *NB* logits must be type float and row-major.\n    py::object shape = probs.attr(\"shape\");\n\n    unsigned int time = py::extract<unsigned int>(shape[0]);\n    unsigned int num_classes = py::extract<unsigned int>(shape[1]);\n    \n    float* data = static_cast<float*>(PyArray_DATA(probs.ptr()));\n\n    std::vector<int> label_vec;\n    for (int i = 0; i < len(labels); i++) \n        label_vec.push_back(py::extract<int>(labels[i]));\n\n    return cscore_kws(data, time, num_classes,\n                      blank, label_vec);\n}\n\nBOOST_PYTHON_MODULE(kws) {\n    np::array::set_module_and_type(\"numpy\", \"ndarray\");\n    py::def(\"score_kws\", &score_kws);\n}\n#endif\n", "meta": {"hexsha": "35ffaff5e6afe9240356bb32b116c97b24ff62a2", "size": 3926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "decoder/kws.cpp", "max_stars_repo_name": "gaoyiyeah/KWS-CTC", "max_stars_repo_head_hexsha": "28fdc2062281996d6408e41a9b49febf3334d730", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-23T19:07:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-23T19:07:16.000Z", "max_issues_repo_path": "decoder/kws.cpp", "max_issues_repo_name": "gaoyiyeah/KWS-CTC", "max_issues_repo_head_hexsha": "28fdc2062281996d6408e41a9b49febf3334d730", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:13:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:31:21.000Z", "max_forks_repo_path": "decoder/kws.cpp", "max_forks_repo_name": "gaoyiyeah/KWS-CTC", "max_forks_repo_head_hexsha": "28fdc2062281996d6408e41a9b49febf3334d730", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-23T18:14:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-23T18:14:41.000Z", "avg_line_length": 28.6569343066, "max_line_length": 77, "alphanum_fraction": 0.5555272542, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.521574665320963}}
{"text": "#include <vector>\n#include <string>\n#include <iostream>\n#include <limits>\n#include <typeinfo>\n#include <iomanip>\nstd::string demangle(const char *name);\n\n#ifdef __GNUC__\n#include <cxxabi.h>\nstd::string demangle(const char *name) {\n    int     status = -1;\n    char   *realname;\n    realname = abi::__cxa_demangle(name, 0, 0, &status);\n    \n    std::string res(name);\n    \n    if(status == 0){\n        res.assign(realname);\n        delete realname;\n    };\n    \n    return res;\n}\n#else \n#include <boost/core/demangle.hpp>\n\nstd::string demangle(const char *name) {\n    return boost::core::demangle(name);\n}\n#endif\n\n#define type_desc2(t)  #t\n#define type_desc(t) type_desc2(t)\n\n#define TYPE size_t\n\n\ntemplate<class T>\nsize_t type_string_length_info(std::ostream& os, const char* name_from_preprocessor=0)\n{\n    os << \"type: \";\n    if(name_from_preprocessor)\n        os<<name_from_preprocessor<<\" ==> \";\n    os<<typeid(T).name()<<\" ==> \"<<demangle(typeid(T).name());\n    os <<\"\\n  size in bytes: \"<<sizeof(T);\n    if(std::numeric_limits<T>::is_specialized) {\n        \n        size_t max_string_representation_length = ((std::numeric_limits<T>::is_integer)?std::numeric_limits<T>::digits10:std::numeric_limits<T>::max_digits10)+1+std::numeric_limits<T>::is_signed;\n\n        os\n        <<\"\\n                \"<<'<'<<std::string(max_string_representation_length-2,'-')<<'>'\n        <<\"\\n  min value:    \"<<std::numeric_limits<T>::min()\n        <<\"\\n  max value:    \"<<std::numeric_limits<T>::max()    \n        <<\"\\n  is signed:    \"<<(std::numeric_limits<T>::is_signed?\"yes\":\"no\")\n        <<\"\\n  digits10:     \"<<std::numeric_limits<T>::digits10\n        <<\"\\n  digits:       \"<<std::numeric_limits<T>::digits\n        <<\"\\n  max digits10: \"<<std::numeric_limits<T>::max_digits10\n        <<\"\\n  radix:        \"<<std::numeric_limits<T>::radix\n        << '\\n'\n        << '\\n';\n        return max_string_representation_length;\n    } else {\n        os<<\" have no info about type\\n\";\n    }\n    return 0;\n}\n\n#define  TYPE_STR_INFO(t) type_string_length_info<t>(std::cout, type_desc(t));\n\nint main()\n{\n    TYPE_STR_INFO(int);\n    TYPE_STR_INFO(char);\n    TYPE_STR_INFO(unsigned char);\n    TYPE_STR_INFO(unsigned long long);\n    TYPE_STR_INFO(size_t);\n    TYPE_STR_INFO(ptrdiff_t);\n    //TYPE_STR_INFO(std::nullptr_t);\n\n    return 0;\n}", "meta": {"hexsha": "7889465de76aa17ca2b56a3dbb4806c7ec5739cb", "size": 2316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "integet_types_string_length_calc.cpp", "max_stars_repo_name": "Kerogi/cpp", "max_stars_repo_head_hexsha": "3823bac5846946b242c24bdca2932d4e618bbfb5", "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": "integet_types_string_length_calc.cpp", "max_issues_repo_name": "Kerogi/cpp", "max_issues_repo_head_hexsha": "3823bac5846946b242c24bdca2932d4e618bbfb5", "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": "integet_types_string_length_calc.cpp", "max_forks_repo_name": "Kerogi/cpp", "max_forks_repo_head_hexsha": "3823bac5846946b242c24bdca2932d4e618bbfb5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.243902439, "max_line_length": 195, "alphanum_fraction": 0.6088082902, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.5215496935015996}}
{"text": "#ifndef COVMAT_HPP\n#define COVMAT_HPP\n\n#include <iostream>\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n\n/*\n * This class stores a precision matrix, along with some functionals\n * of it used to compute the pdf of a normal r.v.\n */\nclass PrecMat\n{\nprotected:\n    MatrixXd prec;\n    LLT<MatrixXd> cho_factor;\n    MatrixXd cho_factor_eval;\n    double log_det;\n\npublic:\n    PrecMat() {}\n    ~PrecMat() {}\n\n    PrecMat(const MatrixXd &prec);\n\n    MatrixXd get_prec() const;\n\n    LLT<MatrixXd> get_cho_factor() const;\n\n    const MatrixXd &get_cho_factor_eval() const;\n\n    double get_log_det() const;\n};\n\nstd::ostream &operator<<(std::ostream &output, const PrecMat &p);\n\n#endif", "meta": {"hexsha": "27f046b2a57a77af01c40e6e598bd70be778df1a", "size": 674, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mcmc_utils/cpp/precmat.hpp", "max_stars_repo_name": "mberaha/utils", "max_stars_repo_head_hexsha": "9be102383d0288f08bd3ccfc4c46ecaf958987ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mcmc_utils/cpp/precmat.hpp", "max_issues_repo_name": "mberaha/utils", "max_issues_repo_head_hexsha": "9be102383d0288f08bd3ccfc4c46ecaf958987ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mcmc_utils/cpp/precmat.hpp", "max_forks_repo_name": "mberaha/utils", "max_forks_repo_head_hexsha": "9be102383d0288f08bd3ccfc4c46ecaf958987ac", "max_forks_repo_licenses": ["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.7368421053, "max_line_length": 68, "alphanum_fraction": 0.6943620178, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5215496882467345}}
{"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 * @date 2015\n * @author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n * Max-Planck-Institute for Intelligent Systems\n */\n\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\n#include <fl/util/math/linear_algebra.hpp>\n\n#include <fl/filter/particle/particle_filter.hpp>\n#include <fl/filter/gaussian/gaussian_filter_linear.hpp>\n#include <fl/model/transition/linear_transition.hpp>\n#include <fl/model/sensor/linear_gaussian_sensor.hpp>\n\ntemplate<typename Vector, typename Matrix>\nbool moments_are_similar(Vector mean_a, Matrix cov_a,\n                         Vector mean_b, Matrix cov_b, fl::Real epsilon = 0.1)\n{\n    Matrix cov_delta = cov_a.inverse() * cov_b;\n    bool are_similar = cov_delta.isApprox(Matrix::Identity(), epsilon);\n\n    Matrix square_root = fl::matrix_sqrt(cov_a);\n    fl::Real max_mean_delta =\n            (square_root.inverse() * (mean_a-mean_b)).cwiseAbs().maxCoeff();\n\n    are_similar = are_similar && max_mean_delta < epsilon;\n\n    return are_similar;\n}\n\nEigen::Matrix<fl::Real, 3, 3> some_rotation()\n{\n    fl::Real angle = 2 * M_PI * fl::Real(rand()) / fl::Real(RAND_MAX);\n\n    Eigen::Matrix<fl::Real, 3, 3> R = Eigen::Matrix<fl::Real, 3, 3>::Identity();\n\n    R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitX());\n    R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitZ());\n    R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitY());\n    return R;\n}\n\nclass ParticleFilterTest\n    : public ::testing::Test\n{\nprotected:\n\n    typedef Eigen::Matrix<fl::Real, 3, 1> State;\n    typedef Eigen::Matrix<fl::Real, 3, 1> Observation;\n    typedef Eigen::Matrix<fl::Real, 3, 1> Input;\n\n    typedef Eigen::Matrix<fl::Real, 3, 3> Matrix;\n\n    typedef fl::LinearTransition<State, State, Input> Transition;\n    typedef fl::LinearGaussianSensor<Observation, State> Sensor;\n\n    // particle filter\n    typedef fl::ParticleFilter<Transition, Sensor> ParticleFilter;\n    typedef ParticleFilter::Belief ParticleBelief;\n\n    // gaussian filter\n    typedef fl::GaussianFilter<Transition, Sensor> GaussianFilter;\n    typedef GaussianFilter::Belief GaussianBelief;\n\n    ParticleFilterTest()\n        : transition(create_transition()),\n          sensor(create_sensor()),\n          particle_filter(transition, sensor),\n          gaussian_filter(transition, sensor)\n\n    {\n        N_particles = 10000;\n        N_steps = 10;\n        delta_time = 1;\n\n        // create intial beliefs\n        gaussian_belief.set_standard();\n        particle_belief.from_distribution(gaussian_belief, N_particles);\n    }\n\n    Transition create_transition()\n    {\n        srand(0);\n\n        Transition transition;\n\n        transition.dynamics_matrix(some_rotation());\n\n        Matrix R = some_rotation();\n        Matrix D = Eigen::DiagonalMatrix<fl::Real, 3>(1, 3.5, 1.2);\n\n        transition.noise_matrix(R*D);\n\n        return transition;\n    }\n\n    Sensor create_sensor()\n    {\n        srand(0);\n\n        Sensor sensor;\n\n        sensor.sensor_matrix(some_rotation());\n\n        Matrix R = some_rotation();\n        Matrix D = Eigen::DiagonalMatrix<fl::Real, 3>(3.1, 1.0, 1.3);\n\n        sensor.noise_covariance(R*D*R.transpose());\n\n        return sensor;\n    }\n\n    Transition transition;\n    Sensor sensor;\n\n    ParticleFilter particle_filter;\n    GaussianFilter gaussian_filter;\n\n    GaussianBelief gaussian_belief;\n    ParticleBelief particle_belief;\n\n    size_t N_particles;\n    size_t N_steps;\n    size_t delta_time;\n\n};\n\nTEST_F(ParticleFilterTest, predict)\n{\n    // run prediction\n    for(size_t i = 0; i < N_steps; i++)\n    {\n        particle_filter.predict(particle_belief, Input::Zero(), particle_belief);\n        gaussian_filter.predict(gaussian_belief, Input::Zero(), gaussian_belief);\n\n        EXPECT_TRUE(moments_are_similar(\n                        particle_belief.mean(), particle_belief.covariance(),\n                        gaussian_belief.mean(), gaussian_belief.covariance()));\n    }\n}\n\nTEST_F(ParticleFilterTest, update)\n{\n    // run prediction\n    for(size_t i = 0; i < N_steps; i++)\n    {\n        Observation observation(0.5, 0.5, 0.5);\n\n        particle_filter.update(particle_belief, observation, particle_belief);\n        gaussian_filter.update(gaussian_belief, observation, gaussian_belief);\n\n        EXPECT_TRUE(moments_are_similar(\n                        particle_belief.mean(), particle_belief.covariance(),\n                        gaussian_belief.mean(), gaussian_belief.covariance()));\n    }\n}\n\nTEST_F(ParticleFilterTest, predict_and_update)\n{\n    fl::StandardGaussian<State> standard_gaussian;\n    State state = gaussian_belief.sample();\n    // run prediction\n    for(size_t i = 0; i < N_steps; i++)\n    {\n        // simulate system\n        state = transition.state(state,\n                                    standard_gaussian.sample(),\n                                    Input::Zero());\n        Observation observation =\n                sensor.observation(state, standard_gaussian.sample());\n\n        // predict\n        particle_filter.predict(particle_belief, State::Zero(), particle_belief);\n        gaussian_filter.predict(gaussian_belief, State::Zero(), gaussian_belief);\n\n        // update\n        particle_filter.update(particle_belief, observation, particle_belief);\n        gaussian_filter.update(gaussian_belief, observation, gaussian_belief);\n    }\n\n    State delta = particle_belief.mean() - gaussian_belief.mean();\n    fl::Real mh_distance = delta.transpose() * gaussian_belief.precision() * delta;\n\n    // make sure that the estimate of the pf is within one std dev\n    EXPECT_TRUE(std::sqrt(mh_distance) <= 1.0);\n}\n", "meta": {"hexsha": "b98090843207eea3d5131ae32053571a94750a39", "size": 5969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/particle_filter/particle_filter_fixture_test.cpp", "max_stars_repo_name": "filtering-library/fl", "max_stars_repo_head_hexsha": "9117e240361b43bdead8b506b755235fb6d5e699", "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": "test/particle_filter/particle_filter_fixture_test.cpp", "max_issues_repo_name": "filtering-library/fl", "max_issues_repo_head_hexsha": "9117e240361b43bdead8b506b755235fb6d5e699", "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": "test/particle_filter/particle_filter_fixture_test.cpp", "max_forks_repo_name": "filtering-library/fl", "max_forks_repo_head_hexsha": "9117e240361b43bdead8b506b755235fb6d5e699", "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": 29.2598039216, "max_line_length": 83, "alphanum_fraction": 0.6577316133, "num_tokens": 1410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.521549677737004}}
{"text": "/**************************************************************************\n** This file is a part of our work (Siggraph'16 paper, binary, code and dataset):\n**\n** Roto++: Accelerating Professional Rotoscoping using Shape Manifolds\n** Wenbin Li, Fabio Viola, Jonathan Starck, Gabriel J. Brostow and Neill D.F. Campbell\n**\n** w.li AT cs.ucl.ac.uk\n** http://visual.cs.ucl.ac.uk/pubs/rotopp\n**\n** Copyright (c) 2016, Wenbin Li\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 and data must retain the above\n**    copyright 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**\n** THIS WORK AND THE RELATED SOFTWARE, SOURCE CODE AND DATA IS PROVIDED BY\n** THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN\n** NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n** INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n** BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n** USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** 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,\n** EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***************************************************************************/\n\n#ifndef GPLVM_HPP\n#define GPLVM_HPP\n\n#include \"ceres/ceres.h\"\n#include \"glog/logging.h\"\n#include \"ceres/solver.h\"\n\nusing ceres::AutoDiffCostFunction;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solver;\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include <Eigen/Eigenvalues>\n\n#include <array>\n#include <random>\n#include <iostream>\n#include <cmath>\n#include <fstream>\n#include <cassert>\n#include <chrono>\n\n#include \"include/rotoSolver/kernel.hpp\"\n#include \"include/rotoSolver/baseDefs.hpp\"\n\nusing namespace std;\n\nclass NoiseHyperPriorFunction\n{\npublic:\n    virtual double getHyperPrior(const double logBeta) const = 0;\n    virtual double getHyperPriorDerivative(const double logBeta) const = 0;\n};\n\nclass GaussianNoiseHyperPriorFunction : public NoiseHyperPriorFunction\n{\nprivate:\n    double _logOffset;\n    double _logScaleSq;\n\npublic:\n    GaussianNoiseHyperPriorFunction(double logOffset = 0.0, double logScale = 1.0) :\n        _logOffset(logOffset), _logScaleSq(logScale * logScale)\n    {}\n\n    virtual double getHyperPrior(const double logBeta) const\n    {\n        double b = logBeta - _logOffset;\n        return (0.5 * _logScaleSq * b * b);\n    }\n\n    virtual double getHyperPriorDerivative(const double logBeta) const\n    {\n        return (_logScaleSq * logBeta);\n    }\n};\n\nclass GPLVM {\npublic:\n    typedef Eigen::VectorXd Vector;\n    typedef Eigen::MatrixXd Matrix;\n    typedef Eigen::SparseMatrix<double> SparseMatrix;\n    explicit GPLVM(const Matrix& Y, const int Q,\n                   shared_ptr<Kernel> kernel,\n                   const double initBeta = 1,\n                   shared_ptr<NoiseHyperPriorFunction> noisePriorFunc =\n     shared_ptr<NoiseHyperPriorFunction>(new GaussianNoiseHyperPriorFunction())) :\n        _Y(Y), _N(_Y.rows()), _Q(Q), _kernel(kernel), _beta(initBeta),\n        _noisePriorFunc(noisePriorFunc)\n    {\n        assert (_N > 0);\n        assert (_Q > 0);\n\n        const double N = double(_Y.rows());\n\n        _Ymean = _Y.array().colwise().mean();\n        _Y = _Y.array().rowwise() - _Ymean.array().colwise().mean();\n        _Ystd = (_Y.array().pow(2.0).colwise().sum() / (N-1.0)).sqrt();\n        _Y = _Y.array().rowwise() / _Ystd.array().colwise().mean();\n\n#ifdef CHECK_NORMALISATION\n        {\n            vdbg(_Ymean);\n            vdbg(_Ystd);\n            vdbg(_Y.transpose());\n\n            Matrix yy_mean = _Y;\n            yy_mean = yy_mean.array().rowwise() * _Ystd.array().colwise().mean();\n            yy_mean = yy_mean.array().rowwise() + _Ymean.array().colwise().mean();\n\n            vdbg((yy_mean - Y).norm());\n        }\n#endif // CHECK_NORMALISATION\n\n        _X = GetDefaultXInit();\n\n        resetCachedValues();\n    }\n\n    void Print() const\n    {\n        std::cout << \"GPLVM: \";\n        std::cout << \" N = \" << _N;\n        std::cout << \" Q = \" << _Q;\n        std::cout << \" beta = \" << _beta << std::endl;\n        _kernel->Print();\n    }\n\n    void SetInternalsFromMatlabStructure(std::map<string, shared_ptr<Eigen::MatrixXd> >& S)\n    {\n        _Y = *S[\"Y\"];\n        _Ymean = *S[\"Y_mean\"];\n        _Ystd = *S[\"Y_std\"];\n\n        _X = *S[\"X\"];\n\n        resetCachedValues();\n    }\n\n    inline int NumParameters() const\n    {\n        return NumPreDataParameters() + (_N * _Q);\n    }\n\n    inline int NumPreDataParameters() const\n    {\n        return (_kernel->NumberOfParameters() + 1);\n    }\n\n    int GetN() const { return _N; }\n\n    int GetQ() const { return _Q; }\n\n    // Cannot return ref due to normalisation so don't call too often..\n    Matrix GetY() const\n    {\n        Matrix Y(_Y);\n        Y = Y.array().rowwise() * _Ystd.array().colwise().mean();\n        Y = Y.array().rowwise() + _Ymean.array().colwise().mean();\n        return Y;\n    }\n\n    Matrix GetX() const { return _X; }\n\n    double GetBeta() const { return _beta; }\n\n    void SetBeta(const double newBeta)\n    {\n        _beta = newBeta;\n\n        resetCachedValues();\n    }\n\n    template<typename Derived>\n    Matrix Predict(const Eigen::MatrixBase<Derived>& x,\n                   Vector* y_var_ptr = NULL,\n                   std::vector<Matrix>* dy_dx_vec_ptr = NULL) const\n    {\n        assert (x.cols() == _Q);\n        assert (x.rows() > 0);\n\n        Matrix K_x_X = _kernel->GetKernelMatrix(x, _X, NULL);\n\n        const Matrix& KinvY = GetKinvY();\n\n        Matrix y_mean = K_x_X * KinvY;\n\n        if (y_var_ptr) {\n            Vector& y_var = *(y_var_ptr);\n            y_var.resize(x.rows());\n\n            const Matrix& Kinv = GetKinv();\n\n            Vector K_xx_xx_diag = _kernel->GetDiagonalOfKernel(x);\n\n            y_var = K_xx_xx_diag.array() -\n                    (K_x_X.array() * (K_x_X * Kinv.transpose()).array()).rowwise().sum().array();\n            y_var.array() += (1.0 / _beta);\n        }\n\n        y_mean = y_mean.array().rowwise() * _Ystd.array().colwise().mean();\n        y_mean = y_mean.array().rowwise() + _Ymean.array().colwise().mean();\n\n        if (dy_dx_vec_ptr)\n        {\n            std::vector<Matrix>& dy_dx_vec = *(dy_dx_vec_ptr);\n            dy_dx_vec.clear();\n\n            const Matrix& Kinv = GetKinv();\n\n            const int D = _Y.cols();\n            const int P = x.rows();\n\n            dy_dx_vec.reserve(P);\n\n            for (int p = 0; p < P; ++p)\n            {\n                shared_ptr<SparseMatrix> dK_dx = _kernel->GetGradientWrtSecondTerm(_X, x.row(p), K_x_X.row(p).transpose());\n\n                Matrix dy_dx = (*dK_dx) * KinvY;\n\n                dy_dx = dy_dx.array().rowwise() * _Ystd.array().colwise().mean();\n\n                dy_dx_vec.push_back(dy_dx);\n            }\n        }\n\n        return y_mean;\n    }\n\n    void SaveToMatFile(std::string matFilename) const\n    {\n        std::cerr << \"UNSUPPORTED: UNABLE TO WRITE GPLVM MATLAB DATA TO \\\"\" << matFilename << \"\\\".\" << std::endl;\n    }\n\nprivate:\n    Matrix _Y;\n    Matrix _Ymean;\n    Matrix _Ystd;\n    const int _N;\n    const int _Q;\n    shared_ptr<Kernel> _kernel;\n    double _beta;\n    Matrix _X;\n    shared_ptr<NoiseHyperPriorFunction> _noisePriorFunc;\n\nprivate:\n    // Cached values (hence mutable)..\n    mutable shared_ptr<Matrix> _KinvY_ptr;\n    mutable shared_ptr<Matrix> _Kinv_ptr;\n\n    void resetCachedValues()\n    {\n        _KinvY_ptr.reset();\n        _Kinv_ptr.reset();\n    }\n\nprotected:\n\n    class CostFunction : public ceres::FirstOrderFunction\n    {\n    private:\n        GPLVM* _gplvm;\n        shared_ptr<Kernel> _kernel;\n\n    public:\n        explicit CostFunction(GPLVM* gplvm) :\n            _gplvm(gplvm),\n            _kernel(gplvm->_kernel->createCopy())\n        {\n        }\n\n        virtual bool Evaluate(const double* parameters,\n                              double* cost,\n                              double* gradient) const {\n            const int numParams = _gplvm->NumPreDataParameters();\n            const int numKernelParams = _kernel->NumberOfParameters();\n            const int N = _gplvm->_N;\n            const int Q = _gplvm->_Q;\n            const Matrix& Y = _gplvm->_Y;\n\n            const double logBeta = parameters[0];\n            const double beta = exp(logBeta);\n            const Eigen::Map< const Vector > logKernelParams(&parameters[1], numKernelParams);\n\n            _kernel->SetParameters(logKernelParams);\n\n            const Eigen::Map< const Matrix > X(&parameters[numParams], N, Q);\n            const Eigen::Map< const Vector > Xvec(&parameters[numParams], N * Q);\n\n            // Create noise free copy of K and prepare extra data\n            Matrix DDmat;\n            Matrix KK = _kernel->GetKernelMatrix(X, X, &DDmat);\n            Matrix K(KK);\n\n            const double Nd = N;\n            const double Dd = Y.cols();\n\n            K.diagonal().array() += (1.0 / beta);\n            Matrix L = K.llt().matrixL();\n\n            double logDet = 2.0 * (L.diagonal().array().log()).sum();\n\n            Matrix LinvY = K.llt().matrixL().solve(Y);\n            double trace_Kinv_YYt = LinvY.squaredNorm();\n\n            double hyperPriorNoise = _gplvm->_noisePriorFunc->getHyperPrior(logBeta);\n\n            double hyperPriorParams = 0.5 * (logKernelParams.array() * logKernelParams.array()).sum();\n\n            double hyperPriorData = 0.5 * X.squaredNorm();\n\n            double LogLike = (0.5 * Dd * Nd) * log(2.0 * M_PI);\n            LogLike += 0.5 * Dd * logDet;\n            LogLike += 0.5 * trace_Kinv_YYt;\n            LogLike += hyperPriorParams;\n            LogLike += hyperPriorNoise;\n\n            LogLike += hyperPriorData;\n\n            cost[0] = LogLike;\n\n            if (gradient != NULL)\n            {\n                // The beta gradient\n                double& dL_dlogBeta = gradient[0];\n\n                // The kernel params gradient\n                Eigen::Map< Eigen::VectorXd > dL_dlogKernParams(&gradient[1], numKernelParams);\n\n                // The final data gradient\n                Eigen::Map< Eigen::VectorXd > dL_dX(&gradient[numParams], N*Q);\n\n\n                Matrix dK_dbeta(Matrix::Identity(N, N));\n                dK_dbeta.diagonal() /= - beta;\n\n                // std::vector< shared_ptr< Matrix > >\n                auto dK_dlogKernParams = _kernel->GetGradientWrtParams(X, KK, &DDmat);\n\n                // shared_ptr< Eigen::SparseMatrix<double> >\n                auto dK_dX_ptr = _kernel->GetGradientWrtData(X, KK, &DDmat);\n\n                Matrix KinvY = K.llt().matrixL().transpose().solve(LinvY);\n\n                Matrix dL_dK = - 0.5 * (KinvY * KinvY.transpose() - (Dd * K.llt().solve(Matrix::Identity(N, N))));\n\n                dL_dlogBeta = (dL_dK.array() * dK_dbeta.array()).sum();\n                dL_dlogBeta += _gplvm->_noisePriorFunc->getHyperPriorDerivative(logBeta);\n\n                for (int i = 0; i < numKernelParams; ++i)\n                {\n                    dL_dlogKernParams[i] = (dL_dK.array() * (*(dK_dlogKernParams[i])).array()).sum() + logKernelParams[i];\n                }\n\n                Eigen::Map< Vector > dL_dK_vec(dL_dK.data(), N*N);\n\n                dL_dX = (*dK_dX_ptr) * dL_dK_vec;\n\n                // Add hyperPriorData gradient\n                dL_dX += Xvec;\n            }\n\n            return true;\n        }\n\n        virtual int NumParameters() const\n        {\n            return _gplvm->NumParameters();\n        }\n    };\n\nprivate:\n\n    Matrix GetDefaultXInit() const\n    {\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(_Y * _Y.transpose());\n        Matrix X0 = es.eigenvectors().rowwise().reverse().block(0, 0, _N, _Q);\n\n        const double scaling = ((X0.array().pow(2.0).colwise().sum() / (double(_N)-1.0)).sqrt()).mean();\n        X0 /= scaling;\n\n        return X0;\n    }\n\n    Vector GetParameterVector() const\n    {\n        Vector p(NumParameters());\n\n        p[0] = log(_beta);\n\n        Vector logKernParams;\n        _kernel->GetParameters(logKernParams);\n        p.block(1, 0, _kernel->NumberOfParameters(), 1) = logKernParams;\n\n        const Eigen::Map< const Vector > Xvec(_X.data(), _N*_Q);\n        p.block(NumPreDataParameters(), 0, _N*_Q, 1) = Xvec;\n\n        return p;\n    }\n\n    void SetFromParameterVector(const Vector& p)\n    {\n        _beta = exp(p[0]);\n\n        Vector logKernParams = p.block(1, 0, _kernel->NumberOfParameters(), 1);\n        _kernel->SetParameters(logKernParams);\n\n        Eigen::Map< Vector > Xvec(_X.data(), _N*_Q);\n        Xvec = p.block(NumPreDataParameters(), 0, _N*_Q, 1);\n\n        resetCachedValues();\n    }\n\n    const Matrix& GetKinvY() const\n    {\n        if (!_KinvY_ptr.get())\n        {\n            std::cout << \"Computing KinvY cached value..\" << std::endl;\n\n            Matrix DDmat;\n            Matrix K = _kernel->GetKernelMatrix(_X, _X, &DDmat);\n\n            K.diagonal().array() += (1.0 / _beta);\n\n            Matrix LinvY = K.llt().matrixL().solve(_Y);\n\n            shared_ptr<Matrix> tmp(new Matrix(K.llt().matrixL().transpose().solve(LinvY)));\n\n            _KinvY_ptr.swap(tmp);\n        }\n\n        return (*_KinvY_ptr);\n    }\n\n    const Matrix& GetKinv() const\n    {\n        if (!_Kinv_ptr.get()) {\n            std::cout << \"Computing Kinv cached value..\" << std::endl;\n\n            Matrix DDmat;\n            Matrix K = _kernel->GetKernelMatrix(_X, _X, &DDmat);\n\n            K.diagonal().array() += (1.0 / _beta);\n\n            Matrix Linv = K.llt().matrixL().solve(Matrix::Identity(_N, _N));\n            shared_ptr<Matrix> tmp(new Matrix(Linv.transpose() * Linv));\n\n            _Kinv_ptr.swap(tmp);\n\n#ifdef TEST_OTHER_INV_METHOD\n//            vdbg(K * (*_Kinv_ptr));\n//            vdbg((*_Kinv_ptr) * K);\n\n//            vdbg((K * (*_Kinv_ptr) - Matrix::Identity(_N,_N)).norm());\n//            vdbg(((*_Kinv_ptr) * K - Matrix::Identity(_N,_N)).norm());\n            vdbg((K * Kinv - Matrix::Identity(_N,_N)).norm());\n            vdbg((Kinv * K - Matrix::Identity(_N,_N)).norm());\n\n            start = std::chrono::high_resolution_clock::now();\n            Matrix Kinv2 = K.inverse();\n            stop = std::chrono::high_resolution_clock::now();\n            vdbg(std::chrono::duration_cast<std::chrono::microseconds>(stop-start).count());\n\n//            vdbg(K * Kinv);\n//            vdbg(Kinv * K);\n\n            vdbg((K * Kinv2 - Matrix::Identity(_N,_N)).norm());\n            vdbg((Kinv2 * K - Matrix::Identity(_N,_N)).norm());\n#endif // TEST_OTHER_INV_METHOD\n        }\n\n        return (*_Kinv_ptr);\n    }\n\npublic:\n\n    void TestGplvmGradients(const double step = 1e-8)\n    {\n        using std::cout; using std::endl;\n        cout << endl << \" TESTING GPLVM GRADIENTS \";\n        cout << endl << \" ======================= \" << endl;\n\n        CostFunction costFunc(this);\n\n        Vector parameters(GetParameterVector());\n\n        parameters.setRandom();\n\n        double C0 = 0.0;\n        Vector gradients(NumParameters());\n\n        bool r = costFunc.Evaluate(parameters.data(), &C0, gradients.data());\n        assert (r);\n\n        vdbg(C0);\n        vdbg(gradients.transpose());\n\n        Vector estGradients(NumParameters());\n        estGradients.setZero();\n\n        for (int i = 0, I = NumParameters(); i < I; ++i)\n        {\n            Vector p(parameters);\n            p[i] += step;\n            double C = 0;\n\n            bool r = costFunc.Evaluate(p.data(), &C, NULL);\n            assert (r);\n\n            estGradients[i] = (C - C0) / step;\n        }\n\n        vdbg(estGradients.transpose());\n\n        vdbg((estGradients - gradients).transpose());\n        vdbg((estGradients - gradients).norm() / gradients.norm());\n\n        assert ((estGradients - gradients).norm() / gradients.norm() < 1e-4);\n\n        cout << \" ======================= \" << endl << endl;\n    }\n\n    void TestPredictionGradients(Matrix x = Matrix(0,0), const double step = 1e-8)\n    {\n        using std::cout; using std::endl;\n        cout << endl << \" TESTING PREDICTION GRADIENTS \";\n        cout << endl << \" ============================ \" << endl;\n\n        if (x.size() == 0)\n        {\n            x = GetX();\n        }\n\n        Vector yVar;\n        std::vector<Matrix> dy_dx_vec;\n        Matrix y = Predict(x, &yVar, &dy_dx_vec);\n\n        const int P = x.rows();\n\n        for (int p = 0; p < P; ++p)\n        {\n            Matrix xx = x.row(p);\n            xx = xx + Matrix::Constant(xx.rows(), xx.cols(), step);\n            Matrix yy = (Predict(xx) - y.row(p));\n            yy /= step;\n\n            vdbg((yy - dy_dx_vec[p]).norm());\n\n            assert ((yy - dy_dx_vec[p]).norm() / (dy_dx_vec[p]).norm() < (10 * step));\n        }\n\n        cout << \" ============================ \" << endl << endl;\n    }\n\n    // Optimise to convergence or until the first of the specified limits is reached..\n    void LearnParameters(const double maxSolverTimeInSeconds = 1.0,\n                         const int maxNumIterations = 10000,\n                         const bool showProgress = false)\n    {\n        ceres::GradientProblem problem(new CostFunction(this));\n\n        Vector parameters(GetParameterVector());\n\n        ceres::GradientProblemSolver::Options options;\n        options.minimizer_progress_to_stdout = showProgress;\n\n        options.function_tolerance = 1e-6;\n        options.gradient_tolerance = 1e-4;\n\n        options.max_num_iterations = maxNumIterations;\n        options.max_solver_time_in_seconds = maxSolverTimeInSeconds;\n\n        ceres::GradientProblemSolver::Summary summary;\n        ceres::Solve(options, problem, parameters.data(), &summary);\n\n        SetFromParameterVector(parameters);\n    }\n\n};\n\n#endif // GPLVM_HPP\n", "meta": {"hexsha": "9ddcefdf85006e8f9a2e4f9718d9de71573cd26a", "size": 18212, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rotoSolver/gplvm.hpp", "max_stars_repo_name": "vinben/Rotopp", "max_stars_repo_head_hexsha": "f0c25db5bd25074c55ff0f67539a2452d92aaf72", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-07-27T07:22:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T13:08:19.000Z", "max_issues_repo_path": "include/rotoSolver/gplvm.hpp", "max_issues_repo_name": "vinben/Rotopp", "max_issues_repo_head_hexsha": "f0c25db5bd25074c55ff0f67539a2452d92aaf72", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-09-24T06:04:39.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-25T10:34:19.000Z", "max_forks_repo_path": "include/rotoSolver/gplvm.hpp", "max_forks_repo_name": "vinben/Rotopp", "max_forks_repo_head_hexsha": "f0c25db5bd25074c55ff0f67539a2452d92aaf72", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2016-07-27T10:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T21:08:33.000Z", "avg_line_length": 30.3533333333, "max_line_length": 123, "alphanum_fraction": 0.5659455304, "num_tokens": 4602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.521549677737004}}
{"text": "/*\n * \n * Copyright (c) Kresimir Fresl 2002, 2003\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 * Author acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_CBLAS2_OVERLOADS_HPP\n#define BOOST_NUMERIC_BINDINGS_CBLAS2_OVERLOADS_HPP\n\n#include <complex> \n#include <boost/numeric/bindings/atlas/cblas_inc.hpp>\n#include <boost/numeric/bindings/traits/type.hpp>\n\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace atlas { namespace detail {\n\n\n    // y <- alpha * op (A) * x + beta * y\n\n    inline \n    void gemv (CBLAS_ORDER const Order, \n               CBLAS_TRANSPOSE const TransA, int const M, int const N,\n               float const alpha, float const* A, int const lda,\n               float const* X, int const incX, \n               float const beta, float* Y, int const incY) \n    {\n      cblas_sgemv (Order, TransA, M, N, alpha, A, lda, \n                   X, incX,\n                   beta, Y, incY); \n    }\n    \n    inline \n    void gemv (CBLAS_ORDER const Order, \n               CBLAS_TRANSPOSE const TransA, int const M, int const N,\n               double const alpha, double const* A, int const lda,\n               double const* X, int const incX, \n               double const beta, double* Y, int const incY) \n    {\n      cblas_dgemv (Order, TransA, M, N, alpha, A, lda, \n                   X, incX,\n                   beta, Y, incY); \n    }\n    \n    inline \n    void gemv (CBLAS_ORDER const Order, \n               CBLAS_TRANSPOSE const TransA, int const M, int const N,\n               traits::complex_f const& alpha, \n               traits::complex_f const* A, int const lda,\n               traits::complex_f const* X, int const incX, \n               traits::complex_f const& beta, \n               traits::complex_f* Y, int const incY) \n    {\n      cblas_cgemv (Order, TransA, M, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (A), lda, \n                   static_cast<void const*> (X), incX,\n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (Y), incY); \n    }\n    \n    inline \n    void gemv (CBLAS_ORDER const Order, \n               CBLAS_TRANSPOSE const TransA, int const M, int const N,\n               traits::complex_d const& alpha, \n               traits::complex_d const* A, int const lda,\n               traits::complex_d const* X, int const incX, \n               traits::complex_d const& beta, \n               traits::complex_d* Y, int const incY) \n    {\n      cblas_zgemv (Order, TransA, M, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (A), lda, \n                   static_cast<void const*> (X), incX,\n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (Y), incY); \n    }\n\n\n    // y <- alpha * A * x + beta * y\n    // A real symmetric\n\n    inline \n    void symv (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, float const alpha, float const* A,\n               int const lda, float const* X, int const incX,\n               float const beta, float* Y, int const incY) \n    {\n      cblas_ssymv (Order, Uplo, N, alpha, A, lda, \n                   X, incX, beta, Y, incY);\n    }\n\n    inline \n    void symv (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, double const alpha, double const* A,\n               int const lda, double const* X, int const incX,\n               double const beta, double* Y, int const incY) \n    {\n      cblas_dsymv (Order, Uplo, N, alpha, A, lda, \n                   X, incX, beta, Y, incY);\n    }\n\n\n    // y <- alpha * A * x + beta * y\n    // A real symmetric in packed form \n\n    inline\n    void spmv (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, float const alpha, float const* Ap,\n               float const* X, int const incX,\n               float const beta, float* Y, int const incY) \n    {\n      cblas_sspmv (Order, Uplo, N, alpha, Ap, X, incX, beta, Y, incY);\n    }\n\n    inline\n    void spmv (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, double const alpha, double const* Ap,\n               double const* X, int const incX,\n               double const beta, double* Y, int const incY) \n    {\n      cblas_dspmv (Order, Uplo, N, alpha, Ap, X, incX, beta, Y, incY);\n    }\n\n\n    // y <- alpha * A * x + beta * y\n    // A complex hermitian \n\n    inline \n    void hemv (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, traits::complex_f const& alpha, \n               traits::complex_f const* A, int const lda, \n               traits::complex_f const* X, int const incX,\n               traits::complex_f const& beta, \n               traits::complex_f* Y, int const incY) \n    {\n      cblas_chemv (Order, Uplo, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (A), lda, \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (Y), incY);\n    }\n\n    inline \n    void hemv (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, traits::complex_d const& alpha, \n               traits::complex_d const* A, int const lda, \n               traits::complex_d const* X, int const incX,\n               traits::complex_d const& beta, \n               traits::complex_d* Y, int const incY) \n    {\n      cblas_zhemv (Order, Uplo, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (A), lda, \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (Y), incY);\n    }\n\n\n    // y <- alpha * A * x + beta * y\n    // A complex hermitian in packed form \n\n    inline \n    void hpmv (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, traits::complex_f const& alpha, \n               traits::complex_f const* Ap, \n               traits::complex_f const* X, int const incX,\n               traits::complex_f const& beta, \n               traits::complex_f* Y, int const incY) \n    {\n      cblas_chpmv (Order, Uplo, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (Ap), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (Y), incY);\n    }\n\n    inline \n    void hpmv (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, traits::complex_d const& alpha, \n               traits::complex_d const* Ap, \n               traits::complex_d const* X, int const incX,\n               traits::complex_d const& beta, \n               traits::complex_d* Y, int const incY) \n    {\n      cblas_zhpmv (Order, Uplo, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (Ap), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (Y), incY);\n    }\n\n\n    // A <- alpha * x * y^T + A \n    // .. real types:    calls cblas_xger\n    // .. complex types: calls cblas_xgeru\n\n    inline \n    void ger (CBLAS_ORDER const Order, int const M, int const N,\n              float const alpha, float const* X, int const incX,\n              float const* Y, int const incY, float* A, int const lda)\n    {\n      cblas_sger (Order, M, N, alpha, X, incX, Y, incY, A, lda); \n    }\n\n    inline \n    void ger (CBLAS_ORDER const Order, int const M, int const N,\n              double const alpha, double const* X, int const incX,\n              double const* Y, int const incY, double* A, int const lda)\n    {\n      cblas_dger (Order, M, N, alpha, X, incX, Y, incY, A, lda); \n    }\n\n    inline \n    void ger (CBLAS_ORDER const Order, int const M, int const N,\n              traits::complex_f const& alpha, \n              traits::complex_f const* X, int const incX,\n              traits::complex_f const* Y, int const incY, \n              traits::complex_f* A, int const lda)\n    {\n      cblas_cgeru (Order, M, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (Y), incY, \n                   static_cast<void*> (A), lda); \n    }\n\n    inline \n    void ger (CBLAS_ORDER const Order, int const M, int const N,\n              traits::complex_d const& alpha, \n              traits::complex_d const* X, int const incX,\n              traits::complex_d const* Y, int const incY, \n              traits::complex_d* A, int const lda)\n    {\n      cblas_zgeru (Order, M, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (Y), incY, \n                   static_cast<void*> (A), lda); \n    }\n\n    // A <- alpha * x * y^T + A \n    // .. complex types only \n\n    inline \n    void geru (CBLAS_ORDER const Order, int const M, int const N,\n               traits::complex_f const& alpha, \n               traits::complex_f const* X, int const incX,\n               traits::complex_f const* Y, int const incY, \n               traits::complex_f* A, int const lda)\n    {\n      cblas_cgeru (Order, M, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (Y), incY, \n                   static_cast<void*> (A), lda); \n    }\n\n    inline \n    void geru (CBLAS_ORDER const Order, int const M, int const N,\n               traits::complex_d const& alpha, \n               traits::complex_d const* X, int const incX,\n               traits::complex_d const* Y, int const incY, \n               traits::complex_d* A, int const lda)\n    {\n      cblas_zgeru (Order, M, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (Y), incY, \n                   static_cast<void*> (A), lda); \n    }\n    \n    // A <- alpha * x * y^H + A \n    // .. complex types only \n\n    inline \n    void gerc (CBLAS_ORDER const Order, int const M, int const N,\n               traits::complex_f const& alpha, \n               traits::complex_f const* X, int const incX,\n               traits::complex_f const* Y, int const incY, \n               traits::complex_f* A, int const lda)\n    {\n      cblas_cgerc (Order, M, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (Y), incY, \n                   static_cast<void*> (A), lda); \n    }\n\n    inline \n    void gerc (CBLAS_ORDER const Order, int const M, int const N,\n               traits::complex_d const& alpha, \n               traits::complex_d const* X, int const incX,\n               traits::complex_d const* Y, int const incY, \n               traits::complex_d* A, int const lda)\n    {\n      cblas_zgerc (Order, M, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (Y), incY, \n                   static_cast<void*> (A), lda); \n    }\n\n\n    // A <- alpha * x * x^T + A \n    // A real symmetric \n\n    inline \n    void syr (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n              int const N, float const alpha, \n              float const* X, int const incX, float* A, int const lda)\n    {\n      cblas_ssyr (Order, Uplo, N, alpha, X, incX, A, lda); \n    }\n\n    inline \n    void syr (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n              int const N, double const alpha, \n              double const* X, int const incX, double* A, int const lda)\n    {\n      cblas_dsyr (Order, Uplo, N, alpha, X, incX, A, lda); \n    }\n\n\n    // A <- alpha * x * x^T + A \n    // A real symmetric in packed form \n    \n    inline \n    void spr (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n              int const N, float const alpha, \n              float const* X, int const incX, float* Ap)\n    {\n      cblas_sspr (Order, Uplo, N, alpha, X, incX, Ap); \n    }\n\n    inline \n    void spr (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n              int const N, double const alpha, \n              double const* X, int const incX, double* Ap)\n    {\n      cblas_dspr (Order, Uplo, N, alpha, X, incX, Ap); \n    }\n\n\n    // A <- alpha * x * y^T + alpha * y * x^T + A \n    // A real symmetric \n\n    inline \n    void syr2 (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, float const alpha, \n               float const* X, int const incX, \n               float const* Y, int const incY, \n               float* A, int const lda)\n    {\n      cblas_ssyr2 (Order, Uplo, N, alpha, X, incX, Y, incY, A, lda); \n    }\n\n    inline \n    void syr2 (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, double const alpha, \n               double const* X, int const incX, \n               double const* Y, int const incY, \n               double* A, int const lda)\n    {\n      cblas_dsyr2 (Order, Uplo, N, alpha, X, incX, Y, incY, A, lda); \n    }\n\n\n    // A <- alpha * x * y^T + alpha * y * x^T + A \n    // A real symmetric in packed form \n    \n    inline \n    void spr2 (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, float const alpha, \n               float const* X, int const incX, \n               float const* Y, int const incY, float* Ap)\n    {\n      cblas_sspr2 (Order, Uplo, N, alpha, X, incX, Y, incY, Ap); \n    }\n\n    inline \n    void spr2 (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, double const alpha, \n               double const* X, int const incX, \n               double const* Y, int const incY, double* Ap)\n    {\n      cblas_dspr2 (Order, Uplo, N, alpha, X, incX, Y, incY, Ap); \n    }\n\n\n    // A <- alpha * x * x^H + A \n    // A hermitian\n\n    inline \n    void her (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n              int const N, float const alpha, \n              traits::complex_f const* X, int const incX, \n              traits::complex_f* A, int const lda)\n    {\n      cblas_cher (Order, Uplo, N, alpha, \n                  static_cast<void const*> (X), incX, \n                  static_cast<void*> (A), lda); \n    }\n\n    inline \n    void her (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n              int const N, double const alpha, \n              traits::complex_d const* X, int const incX, \n              traits::complex_d* A, int const lda)\n    {\n      cblas_zher (Order, Uplo, N, alpha, \n                  static_cast<void const*> (X), incX, \n                  static_cast<void*> (A), lda); \n    }\n\n\n    // A <- alpha * x * x^H + A \n    // A hermitian in packed form \n    \n    inline \n    void hpr (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n              int const N, float const alpha, \n              traits::complex_f const* X, int const incX, \n              traits::complex_f* Ap)\n    {\n      cblas_chpr (Order, Uplo, N, alpha, \n                  static_cast<void const*> (X), incX, \n                  static_cast<void*> (Ap)); \n    }\n\n    inline \n    void hpr (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n              int const N, double const alpha, \n              traits::complex_d const* X, int const incX, \n              traits::complex_d* Ap)\n    {\n      cblas_zhpr (Order, Uplo, N, alpha, \n                  static_cast<void const*> (X), incX, \n                  static_cast<void*> (Ap)); \n    }\n\n\n    // A <- alpha * x * y^H + y * (alpha * x)^H + A \n    // A hermitian\n\n    inline \n    void her2 (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, traits::complex_f const& alpha, \n               traits::complex_f const* X, int const incX, \n               traits::complex_f const* Y, int const incY, \n               traits::complex_f* A, int const lda)\n    {\n      cblas_cher2 (Order, Uplo, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (Y), incY, \n                   static_cast<void*> (A), lda); \n    }\n\n    inline \n    void her2 (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, traits::complex_d const& alpha, \n               traits::complex_d const* X, int const incX, \n               traits::complex_d const* Y, int const incY, \n               traits::complex_d* A, int const lda)\n    {\n      cblas_zher2 (Order, Uplo, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (Y), incY, \n                   static_cast<void*> (A), lda); \n    }\n\n\n    // A <- alpha * x * y^H + y * (alpha * x)^H + A \n    // A hermitian in packed form \n    \n    inline \n    void hpr2 (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, traits::complex_f const& alpha, \n               traits::complex_f const* X, int const incX, \n               traits::complex_f const* Y, int const incY, \n               traits::complex_f* Ap)\n    {\n      cblas_chpr2 (Order, Uplo, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (Y), incY, \n                   static_cast<void*> (Ap)); \n    }\n\n    inline \n    void hpr2 (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, traits::complex_d const& alpha, \n               traits::complex_d const* X, int const incX, \n               traits::complex_d const* Y, int const incY, \n               traits::complex_d* Ap)\n    {\n      cblas_zhpr2 (Order, Uplo, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void const*> (Y), incY, \n                   static_cast<void*> (Ap)); \n    }\n\n\n  }} // namepaces detail & atlas\n\n}}} \n\n\n#endif // BOOST_NUMERIC_BINDINGS_CBLAS2_OVERLOADS_HPP\n", "meta": {"hexsha": "e102a2e3f8f1ed0380cf96739cce28a084da6a2d", "size": 18385, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/atlas/cblas2_overloads.hpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-11-13T16:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T15:37:19.000Z", "max_issues_repo_path": "openrave/plugins/include/boost/numeric/bindings/atlas/cblas2_overloads.hpp", "max_issues_repo_name": "jdsika/holy", "max_issues_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-06-13T01:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-14T00:38:27.000Z", "max_forks_repo_path": "openrave/plugins/include/boost/numeric/bindings/atlas/cblas2_overloads.hpp", "max_forks_repo_name": "jdsika/holy", "max_forks_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "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": 35.019047619, "max_line_length": 72, "alphanum_fraction": 0.5267337503, "num_tokens": 4932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5215346198264591}}
{"text": "#include <iostream>\n#include <Eigen/Sparse>\n#include <functional>\n\n\ntemplate <class func, class Vector>\nvoid fixed_point_step(func&& A, const Vector & b, const\nVector & x, Vector & x_new){\n\tint  n= x.size();\n\tEigen::SparseMatrix<double> A_eval(n,n) = A(x);\n\tx_new = x - ( A_eval + x*x.transposed()/x.norm()).cwiseInverse()*(A_eval*x-b);\n};\n\nint main(){\n\tEigen::VectorXd x, b, x_new, x_old;\n\tb=Eigen::VectorXd::Random(10,10);\n\tx_new = b;\n\tdouble tol =2e-15;\n\t\n\t\n\tauto A = [ x_new ] (const Eigen::VectorXd & x) ->\n\tEigen::SparseMatrix<double> & {\n\tint const n = x.size();\n\tEigen::SparseMatrix<double, n, n> A;\n\tdouble x_norm = x.norm();\n\tx_norm +=3;\n\tA(0,0)=x_norm;A(0,1)=1;\n\tA(n-1,n-1)=x_norm;A(n-1,n-2)=1;\n\tfor (int i= 1; i<n-1; i++){\n\t\tA(i,i)=x_norm;\n\t\tA(i+1,i)=1;\n\t\tA(i,i+1)=1;\t\t\n\t}\n\treturn A;\n\t};\n\t\n\tint j=0;\n\twhile (std::abs(x_old.norm()-x.norm())<tol){\n\t\ti++\n\t\tfixed_point_step(A, b, x, x_new)\n\t\tx_old=x;\n\t\tx=x_new;\n\t}\n\tstd::cout << x << std::endl;\n\t\n\treturn 0;\n\n}\n", "meta": {"hexsha": "66b40e66466fedd0544b3757a0dedb7acc0fbb39", "size": 970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS5/quasilin.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS5/quasilin.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS5/quasilin.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7959183673, "max_line_length": 79, "alphanum_fraction": 0.5979381443, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5214597254658292}}
{"text": "/**\n * @author Tomas Polasek, David Hrusa\n * @date 1.14.2020\n * @version 1.0\n * @brief gui rendering and helper classes.\n */\n\n#include \"TreeStats.h\"\n\n#include <queue>\n\n#include <boost/random.hpp>\n#include <boost/math/distributions.hpp>\n\n#include \"TreeScene.h\"\n#include \"TreeRenderSystemRT.h\"\n\nnamespace treestat\n{\n\nnamespace impl\n{\n\n/// @brief Internal implementation of the DistributionEngine.\nstruct DistributionEngineImpl\n{\n    /// @brief Randomness engine used.\n    using EngineT = boost::mt19937;\n\n    /// @brief Type used for variate generators.\n    template <typename DistT>\n    using VariateGenerator = boost::variate_generator<EngineT, DistT>;\n\n    /// Instance of the engine.\n    EngineT engine{ };\n}; // struct DistributionEngineImpl\n\n/// @brief Normal Gaussian distribution.\nstruct NormalDistribution : public DistributionProperties\n{\n    /// Unique identifier of this distribution.\n    static constexpr auto IDENTIFIER{ \"Normal\" };\n    /// @brief Type used for sampling the distribution.\n    using DistT = boost::math::normal_distribution<RealType>;\n\n    /// @brief Initialize normal distribution with mean and standard deviation.\n    NormalDistribution(DistributionEngineImpl &engine,\n        RealType mean = 0, RealType sigma = 1);\n\n    /// @brief Initialize normal distribution from serialized representation.\n    NormalDistribution(DistributionEngineImpl &engine,\n        const std::string &serialized);\n\n    // Implement interface:\n    virtual std::string serialize() const override final;\n    virtual void deserialize(const std::string &serialized) override final;\n    virtual void setEngine(DistributionEngineImpl &engine) override final;\n    virtual RealType cdf(const RealType &x) const override final;\n    virtual RealType sample() override final;\n\n    /// @brief Intitialize the internal structure using provided parameters.\n    void initialize(RealType mean, RealType sigma);\n\n    /// Distribution implementation.\n    DistT distribution{ };\n    /// Sample generator for the distribution.\n    DistributionEngineImpl::EngineT generator{ };\n}; // struct NormalDistribution\n\nNormalDistribution::NormalDistribution(DistributionEngineImpl &engine,\n    RealType mean, RealType sigma) :\n    generator{ engine.engine }\n{ initialize(mean, sigma); }\n\nNormalDistribution::NormalDistribution(DistributionEngineImpl &engine,\n    const std::string &serialized) :\n    generator{ engine.engine }\n{ deserialize(serialized); }\n\nstd::string NormalDistribution::serialize() const\n{\n    return treeio::json{\n        { \"distribution\", IDENTIFIER },\n        { \"mean\", distribution.mean() },\n        { \"sigma\", distribution.standard_deviation() },\n    }.dump();\n}\n\nvoid NormalDistribution::deserialize(const std::string &serialized)\n{\n    const auto data{ treeio::json::parse(serialized) };\n\n    if (data.at(\"distribution\").get<std::string>() != IDENTIFIER)\n    { throw StochasticException(\"Deserializing with unknown distribution identifier!\"); }\n\n    initialize(\n        data.at(\"mean\").get<RealType>(),\n        data.at(\"sigma\").get<RealType>()\n    );\n}\n\nvoid NormalDistribution::setEngine(DistributionEngineImpl &engine)\n{ generator = engine.engine; }\n\nNormalDistribution::RealType NormalDistribution::cdf(const RealType &x) const\n{ return boost::math::cdf<RealType>(distribution, x); }\n\nNormalDistribution::RealType NormalDistribution::sample()\n{ return boost::math::quantile<RealType>(distribution, generator()); }\n\nvoid NormalDistribution::initialize(RealType mean, RealType sigma)\n{ distribution = DistT{ mean, sigma }; }\n\n\n\nstd::shared_ptr<DistributionProperties>\n    DistributionProperties::normalDistribution(DistributionEngineImpl &engine,\n        RealType mean, RealType sigma)\n{ return std::make_shared<NormalDistribution>(engine, mean, sigma); }\n\nstd::shared_ptr<DistributionProperties>\n    DistributionProperties::deserializeDistribution(\n        DistributionEngineImpl &engine, const std::string &serialized)\n{\n    const auto data{ treeio::json::parse(serialized) };\n    const auto name{ data.at(\"distribution\").get<std::string>() };\n\n    if (name == NormalDistribution::IDENTIFIER)\n    { return std::make_shared<NormalDistribution>(engine, serialized); }\n    else\n    { throw StochasticException(\"Unknown distribution is being deserialized!\"); }\n}\n\n} // namespace impl\n\nStochasticEngine::StochasticEngine(uint32_t seed)\n{ reset(seed); }\nStochasticEngine::~StochasticEngine()\n{ /* Automatic */ }\n\nvoid StochasticEngine::reset(uint32_t seed)\n{\n    if (!mImpl)\n    { mImpl = std::make_shared<impl::DistributionEngineImpl>(); }\n\n    if (seed)\n    { mImpl->engine.seed(seed); }\n    else\n    { mImpl->engine.seed(); }\n}\n\nstd::string ImageData::valueTypeToStr(const ValueType &type)\n{\n    switch (type)\n    {\n        default:\n        case ValueType::UInt:\n        { return \"UInt\"; }\n        case ValueType::Float:\n        { return \"Float\"; }\n    }\n}\n\nvoid ImageData::saveTo(treeio::json &out) const\n{\n    out[\"image\"] = {\n        { \"width\", width },\n        { \"height\", height },\n        { \"channels\", channels },\n        { \"valueType\", valueTypeToStr(valueType) },\n        { \"data\", data.empty() ? std::string{ } : treeutil::encodeBinaryJSON(data) },\n    };\n}\n\nstd::size_t branchingToOrdinal(const Branching &branching)\n{\n    switch (branching)\n    {\n        default:\n        case Branching::Monopodial:\n        { return 0u; }\n        case Branching::SympodialMonochasial:\n        { return 1u; }\n        case Branching::SympodialDichasial:\n        { return 2u; }\n    }\n}\n\nBranching ordinalToBranching(std::size_t ordinal)\n{\n    switch (ordinal)\n    {\n        default:\n        case 0u:\n        { return Branching::Monopodial; }\n        case 1u:\n        { return Branching::SympodialMonochasial; }\n        case 2u:\n        { return Branching::SympodialDichasial; }\n    }\n}\n\nstd::size_t ramificationToOrdinal(const Ramification &ramification)\n{\n    switch (ramification)\n    {\n        default:\n        case Ramification::Continuous:\n        { return 0u; }\n        case Ramification::Rhythmic:\n        { return 1u; }\n        case Ramification::Diffuse:\n        { return 2u; }\n    }\n}\n\nRamification ordinalToRamification(std::size_t ordinal)\n{\n    switch (ordinal)\n    {\n        default:\n        case 0u:\n        { return Ramification::Continuous; }\n        case 1u:\n        { return Ramification::Rhythmic; }\n        case 2u:\n        { return Ramification::Diffuse; }\n    }\n}\n\nvoid TreeStatValues::saveTo(treeio::json &out) const\n{\n    forEach([&out] (const auto &var)\n    {\n        auto &varOut{ out[var.name] };\n        varOut[\"name\"] = var.name;\n        varOut[\"description\"] = var.description;\n\n        var.var.saveTo(varOut);\n        var.hist.saveTo(varOut);\n    });\n\n    auto &commonOut{ out[\"common\"] };\n    commonOut = {\n        { \"treeAge\", treeAge },\n        { \"trunkLength\", trunkLength },\n        { \"interNodeLength\", interNodeLengthEstimate },\n        { \"interNodeVariance\", interNodeLengthVariance },\n        { \"leafCount\", leafCount },\n        { \"branching\", branchingToOrdinal(branching) },\n        { \"ramification\", ramificationToOrdinal(ramification) },\n    };\n\n    auto &visualOut{ out[\"visual\"] };\n    shadowImprint.saveTo(visualOut[\"shadowImprint\"]);\n}\n\nTreeStats::TreeStats()\n{ /* Automatic */ }\n\nTreeStats::TreeStats(const treeio::ArrayTree &tree)\n{ calculateStatistics(tree); }\n\nTreeStats::~TreeStats()\n{ /* Automatic */ }\n\nvoid printChains(std::size_t currentChainIdx, const treeutil::TreeChains &chains, std::size_t maxDepth,\n    const std::string &indent = \"\", std::size_t currentDepth = 0u)\n{\n    const auto &currentChain{ chains.chains()[currentChainIdx] };\n\n    const auto newline{ std::string{ \"\\n\" } + indent + \"\\t\" };\n    Info << indent << \"[ Chain \" << currentChainIdx\n        << newline << \"depth: \" << currentDepth\n        << \"; nodeCount: \" << currentChain.nodes.size()\n        << \"; gOrder: \" << currentChain.graveliusOrder\n        << \"; gDepth: \" << currentChain.graveliusDepth\n        << newline << \"children (\" << currentChain.childChains.size() << \"): [ \\n\";\n\n    if (currentDepth + 1u < maxDepth)\n    {\n        if (currentChain.childChains.empty())\n        { Info << indent << \"\\tNo Child Chains\"; }\n        else\n        {\n            for (const auto &childChainIdx: currentChain.childChains)\n            { printChains(childChainIdx, chains, maxDepth, indent + \"\\t\", currentDepth + 1u); Info << \"\\n\"; }\n        }\n    }\n    else\n    { Info << indent << \"\\tMaximum Depth Reached\"; }\n\n    Info << newline << \" ]\"\n        << \"\\n\" << indent << \" ]\";\n\n    if (currentDepth == 0u)\n    { Info << std::endl; }\n}\n\nvoid TreeStats::calculateStatistics(const treeio::ArrayTree &tree)\n{\n    treeutil::Timer profilingTimer{ };\n\n    /* Phase 0 Initialize structures */\n    mStats = { };\n    if (tree.empty()) { return; }\n\n    /* Phase 1 Prepare helper tree data */\n    const auto [chains, chainDataStorage]{ prepareTree(mStats, mSettings, tree) };\n    if (chainDataStorage.empty()) { return; }\n\n    const auto timePreparation{ profilingTimer.reset() };\n\n    /* Phase 2 Calculate basic statistics */\n    calculateBasicStats(mStats, mSettings, chains, chainDataStorage);\n\n    const auto timeBasicStats{ profilingTimer.reset() };\n\n    /* Phase 3 Calculate visual statistics */\n    calculateVisualStats(mStats, mSettings, tree);\n\n    const auto timeVisualStats{ profilingTimer.reset() };\n\n    /* Phase 4 Calculate derived statistics */\n    calculateDerivedStats(mStats, mSettings, chains, chainDataStorage);\n\n    const auto timeDerivedStats{ profilingTimer.reset() };\n\n    /* Phase 5 Calculate growth statistics */\n    calculateGrowthStats(mStats, mSettings, chains, chainDataStorage);\n\n    const auto timeGrowthStats{ profilingTimer.reset() };\n\n    /* Phase 6 Finalize and clean up */\n    finalizeStats(mStats, mSettings);\n\n    const auto timeFinalizeStats{ profilingTimer.reset() };\n\n    const auto timeTotalNoVisual{\n        timePreparation + timeBasicStats +\n        timeDerivedStats + timeGrowthStats +\n        timeFinalizeStats\n    };\n    const auto timeTotal{ timeTotalNoVisual + timeVisualStats };\n\n    Info << \"[Prof] timePreparation: \" << timePreparation << std::endl;\n    Info << \"[Prof] timeBasicStats: \" << timeBasicStats << std::endl;\n    Info << \"[Prof] timeVisualStats: \" << timeVisualStats << std::endl;\n    Info << \"[Prof] timeDerivedStats: \" << timeDerivedStats << std::endl;\n    Info << \"[Prof] timeGrowthStats: \" << timeGrowthStats << std::endl;\n    Info << \"[Prof] timeFinalizeStats: \" << timeFinalizeStats << std::endl;\n    Info << \"[Prof] timeTotalNoVisual: \" << timeTotalNoVisual << std::endl;\n    Info << \"[Prof] timeTotal: \" << timeTotal << std::endl;\n}\n\nvoid TreeStats::saveStatisticsToDynamic(treeio::ArrayTree &tree)\n{\n    auto &dynamic{ tree.metaData().dynamicData() };\n\n    auto &statsOut{ dynamic[\"stats\"] };\n    mStats.saveTo(statsOut);\n}\n\nstd::pair<treeutil::TreeChains, std::vector<TreeStats::ChainData>>\n    TreeStats::prepareTree(TreeStatValues &stats, const StatsSettings &settings,\n        const treeio::ArrayTree &tree)\n{\n    treeutil::TreeChains chains{ tree };\n\n    //printChains(0u, chains, 3u);\n\n    if (chains.chains().empty())\n    { return { }; }\n\n    std::vector<ChainData> chainDataStorage{ };\n    chainDataStorage.resize(chains.chains().size());\n\n    // Calculate forward pass information - root -> leaves.\n    prepareTreeForwardPass(chains, chainDataStorage, stats, settings);\n\n    // Calculate backward pass information - leaves -> root.\n    prepareTreeBackwardPass(chains, chainDataStorage, stats, settings);\n\n    return { chains, chainDataStorage };\n}\n\nvoid TreeStats::prepareTreeForwardPass(treeutil::TreeChains &chains, std::vector<ChainData> &chainDataStorage,\n    TreeStatValues &stats, const StatsSettings &settings)\n{\n    const auto &chainsTree{ chains.internalTree() };\n\n    for (std::size_t chainIdx = 0u; chainIdx < chains.chains().size(); ++chainIdx)\n    { // Go through chains and pre-calculate data.\n        const auto &chain{ chains.chains()[chainIdx] };\n        auto &chainData{ chainDataStorage[chainIdx] };\n\n        float length{ 0.0f };\n        float volume{ 0.0f };\n        float angleSum{ 0.0f };\n        float angleAbsSum{ 0.0f };\n        float lengthAverageThickness{ 0.0f };\n        Vector3D startToEnd{ };\n        if (chain.nodes.size() > 1u)\n        {\n            const auto &firstNodeData{ chainsTree.getNode(chain.nodes[0u]).data() };\n            const auto &secondNodeData{ chainsTree.getNode(chain.nodes[1u]).data() };\n            const auto &lastNodeData{ chainsTree.getNode(chain.nodes.back()).data() };\n\n            chainData.segmentData.reserve(chain.nodes.size() - 1u);\n            auto lastNodePos{ firstNodeData.pos };\n            auto lastNodeThickness{ firstNodeData.thickness };\n            startToEnd = (lastNodeData.pos - lastNodePos);\n            auto lastToCurrent{ (secondNodeData.pos - lastNodePos).normalized() };\n\n            chainData.minThickness = std::min<float>(\n                chainData.minThickness, firstNodeData.thickness);\n            chainData.maxThickness = std::max<float>(\n                chainData.maxThickness, firstNodeData.thickness);\n            chainData.firstDirection = lastToCurrent;\n\n            for (auto it = chain.nodes.begin() + 1u; it != chain.nodes.end(); ++it)\n            {\n                const auto currentNodePos{ chainsTree.getNode(*it).data().pos };\n                const auto currentDirection{ (currentNodePos - lastNodePos).normalized() };\n                const auto lastToCurrentAngle{\n                    treeutil::angleBetweenNormVectorsRad<float>(lastToCurrent, currentDirection)\n                };\n\n                const auto segmentLength{ lastNodePos.distanceTo(currentNodePos) };\n                length += segmentLength;\n                angleSum += lastToCurrentAngle;\n                angleAbsSum += std::abs(lastToCurrentAngle);\n\n                auto thickness{ chainsTree.getNode(*it).data().thickness };\n                if (std::isnan(thickness) || std::isinf(thickness))\n                { thickness = 0.0f; }\n\n                volume += treeutil::circularConeFrustumVolume(\n                    segmentLength, lastNodeThickness, thickness);\n\n                lengthAverageThickness += segmentLength * thickness;\n                stats.segmentThickness.observeSample(thickness);\n                chainData.minThickness = std::min<float>(\n                    chainData.minThickness, thickness);\n                chainData.maxThickness = std::max<float>(\n                    chainData.maxThickness, thickness);\n\n                chainData.segmentData.emplace_back(SegmentData{\n                    segmentLength, lastNodeThickness, thickness\n                });\n\n                lastNodePos = currentNodePos;\n                lastNodeThickness = thickness;\n                lastToCurrent = currentDirection;\n\n                // Try to find a better first direction, when first few nodes are at the exact same position.\n                if (!treeutil::aboveEpsilon(chainData.firstDirection.length()))\n                { chainData.firstDirection = lastToCurrent; }\n            }\n\n            chainData.lastDirection = lastToCurrent;\n        }\n\n        chainData.length = length;\n        chainData.angleSum = angleSum;\n        chainData.angleAbsSum = angleAbsSum;\n        chainData.lengthAverageThickness = lengthAverageThickness;\n        chainData.volume = volume;\n        chainData.startToEnd = startToEnd;\n    }\n}\n\nvoid TreeStats::prepareTreeBackwardPass(treeutil::TreeChains &chains, std::vector<ChainData> &chainDataStorage,\n    TreeStatValues &stats, const StatsSettings &settings)\n{\n    using ChainIdxT = treeutil::TreeChains::NodeChain::ChainIdxT;\n    static constexpr auto INVALID_CHAIN_IDX{ treeutil::TreeChains::NodeChain::INVALID_CHAIN_IDX };\n\n    std::vector<std::size_t> finalizedChildChains{ };\n    finalizedChildChains.resize(chains.chains().size(), 0u);\n    std::queue<ChainIdxT> toProcess{ };\n    for (const auto &leafChainIdx : chains.leafChains())\n    { toProcess.push(leafChainIdx); }\n\n    while (!toProcess.empty())\n    { // Process all chains from leaves to root.\n        const auto currentChainIdx{ toProcess.front() }; toProcess.pop();\n        auto &currentChain{ chains.chains()[currentChainIdx] };\n        auto &currentChainData{ chainDataStorage[currentChainIdx] };\n\n        for (const auto &ccIdx : currentChain.childChains)\n        { // Aggregate data from child chains.\n            const auto &childChain{ chains.chains()[ccIdx] };\n            const auto &childChainData{ chainDataStorage[ccIdx] };\n\n            currentChainData.subtreeLength += childChainData.subtreeLength;\n            currentChainData.subtreeVolume += childChainData.subtreeVolume;\n            currentChainData.subtreeLeafCount += childChainData.subtreeLeafCount;\n        }\n\n        // Set fixed value for leaf chains.\n        if (currentChain.childChains.empty())\n        {\n            currentChainData.subtreeLeafCount = 1u;\n            currentChainData.subtreeLength = currentChainData.length;\n            currentChainData.subtreeVolume = currentChainData.volume;\n        }\n\n        // Check parent node finalization..\n        const auto parentChainIdx{ currentChain.parentChain };\n        if (parentChainIdx != INVALID_CHAIN_IDX)\n        { // We have parent -> Not currently at the root node.\n            const auto &parentChain{ chains.chains()[parentChainIdx] };\n            finalizedChildChains[parentChainIdx]++;\n\n            // Check if all of the parents children have necessary calculations finished.\n            if (finalizedChildChains[parentChainIdx] >= parentChain.childChains.size())\n            { // All children are finished -> Add parent for processing.\n                toProcess.push(parentChainIdx);\n            }\n        }\n    }\n}\n\nvoid TreeStats::calculateBasicStats(TreeStatValues &stats, const StatsSettings &settings,\n    const treeutil::TreeChains &chains, const std::vector<ChainData> &chainDataStorage)\n{\n    for (std::size_t chainIdx = 0u; chainIdx < chains.chains().size(); ++chainIdx)\n    { // Go through the tree using non-branching sequences of segments -> chains.\n        const auto &chain{ chains.chains()[chainIdx] };\n        const auto &chainData{ chainDataStorage[chainIdx] };\n\n        const auto segmentCount{ static_cast<uint32_t>(chain.nodes.size() - 1u) };\n        const auto chainDepth{ static_cast<uint32_t>(chain.chainDepth) };\n\n        stats.segmentsPerChain.observeSample(segmentCount);\n        stats.chainsPerDepth.observeSample(chainDepth);\n        if (treeutil::aboveEpsilon(chainData.length))\n        { stats.chainLength.observeSample(chainData.length); }\n        if (treeutil::aboveEpsilon(chainData.startToEnd.length()))\n        { stats.chainTotalLength.observeSample(chainData.startToEnd.length()); }\n        stats.chainDeformation.observeSample(chainData.angleAbsSum);\n\n        for (const auto &segment : chainData.segmentData)\n        { // Approximate volume of each segment with circular cone frustum volume.\n            const auto volume{\n                treeutil::circularConeFrustumVolume(\n                    segment.length, segment.startThickness, segment.endThickness)\n            };\n            stats.segmentVolume.observeSample({ segment.startThickness, volume });\n            stats.segmentVolume.observeSample({ segment.endThickness, volume });\n        }\n\n        if (chain.nodes.size() > 2u && treeutil::aboveEpsilon(chainData.startToEnd.length()) &&\n            treeutil::aboveEpsilon(chainData.length))\n        { stats.chainStraightness.observeSample(chainData.startToEnd.length() / chainData.length); }\n        if (treeutil::aboveEpsilon(chainData.startToEnd.length()))\n        {\n            stats.chainSlope.observeSample(\n                treeutil::angleBetweenVectorsRad<float>(\n                    chainData.startToEnd, Vector3D{ 0.0f, 1.0f, 0.0f }\n                )\n            );\n        }\n\n        if (chainData.minThickness < std::numeric_limits<float>::max())\n        { stats.chainMinThickness.observeSample(chainData.minThickness); }\n        if (chainData.maxThickness > std::numeric_limits<float>::min())\n        { stats.chainMaxThickness.observeSample(chainData.maxThickness); }\n        if (chainData.minThickness < std::numeric_limits<float>::max() &&\n            chainData.maxThickness > std::numeric_limits<float>::min())\n        { stats.chainMinMaxThicknessRatio.observeSample(chainData.minThickness / chainData.maxThickness); }\n\n        if (chain.parentChain != chain.INVALID_CHAIN_IDX)\n        { // Calculate child-parent statistics.\n            const auto &parentChain{ chains.chains()[chain.parentChain] };\n            const auto &parentChainData{ chainDataStorage[chain.parentChain] };\n\n            const auto parentChildAngle{ treeutil::angleBetweenVectorsRad<float>(\n                parentChainData.startToEnd, chainData.startToEnd\n            ) };\n\n            if (treeutil::aboveEpsilon(chainData.length) && treeutil::aboveEpsilon(parentChainData.length))\n            { stats.chainLengthRatio.observeSample(chainData.length / parentChainData.length); }\n            if (treeutil::aboveEpsilon(chainData.angleSum) && treeutil::aboveEpsilon(parentChainData.angleSum))\n            { stats.chainAngleSumDelta.observeSample(chainData.angleSum - parentChainData.angleSum); }\n            stats.chainParentChildAngle.observeSample(parentChildAngle);\n\n            const auto tropismBranch{ Vector3D::dotProduct(\n                (chainData.startToEnd - chainData.firstDirection).normalized(),\n                StatsSettings::DEFAULT_HORIZON_UP_DIRECTION.normalized()\n            ) };\n            stats.chainTropismBranch.observeSample(tropismBranch);\n\n            const auto tropismHorizon{ Vector3D::dotProduct(\n                chainData.firstDirection.normalized(),\n                StatsSettings::DEFAULT_HORIZON_UP_DIRECTION.normalized()\n            ) };\n            stats.chainTropismHorizon.observeSample(tropismHorizon);\n\n            const auto tropismParent{ Vector3D::dotProduct(\n                    parentChainData.lastDirection.normalized(),\n                    chainData.startToEnd.normalized()\n            ) };\n            stats.chainTropismParent.observeSample(tropismParent);\n        }\n        if (chain.childChains.size() > 1u)\n        { // Calculate child statistics.\n            auto minChildAngle{ std::numeric_limits<float>::max() };\n            auto maxChildAngle{ std::numeric_limits<float>::lowest() };\n            auto minChildAngleTotal{ std::numeric_limits<float>::max() };\n            auto maxChildAngleTotal{ std::numeric_limits<float>::lowest() };\n\n            auto minParentAngle{ std::numeric_limits<float>::max() };\n            auto maxParentAngle{ std::numeric_limits<float>::lowest() };\n            auto minParentAngleTotal{ std::numeric_limits<float>::max() };\n            auto maxParentAngleTotal{ std::numeric_limits<float>::lowest() };\n\n            for (std::size_t idx1 = 0u; idx1 < chain.childChains.size(); ++idx1)\n            {\n                const auto &cChainIdx1{ chain.childChains[idx1] };\n                const auto &cChainData1{ chainDataStorage[cChainIdx1] };\n\n                auto minSiblingAngle{ std::numeric_limits<float>::max() };\n                auto maxSiblingAngle{ std::numeric_limits<float>::lowest() };\n                auto minSiblingAngleTotal{ std::numeric_limits<float>::max() };\n                auto maxSiblingAngleTotal{ std::numeric_limits<float>::lowest() };\n\n                const auto parentChainAngle{ treeutil::angleBetweenVectorsRad<float>(\n                    chainData.lastDirection, cChainData1.firstDirection)};\n                const auto parentChainAngleTotal{ treeutil::angleBetweenVectorsRad<float>(\n                    chainData.startToEnd, cChainData1.startToEnd)};\n\n                if (treeutil::aboveEpsilon(cChainData1.firstDirection.length()) &&\n                    treeutil::aboveEpsilon(chainData.lastDirection.length()))\n                {\n                    stats.chainParentAngle.observeSample(parentChainAngle);\n                    minParentAngle = std::min<float>(minParentAngle, parentChainAngle);\n                    maxParentAngle = std::max<float>(maxChildAngle, parentChainAngle);\n                }\n\n                if (treeutil::aboveEpsilon(cChainData1.startToEnd.length()) &&\n                    treeutil::aboveEpsilon(chainData.startToEnd.length()))\n                {\n                    stats.chainParentAngleTotal.observeSample(parentChainAngleTotal);\n                    minParentAngleTotal = std::min<float>(minParentAngleTotal, parentChainAngleTotal);\n                    maxParentAngleTotal = std::max<float>(maxParentAngleTotal, parentChainAngleTotal);\n                }\n\n                for (std::size_t idx2 = 0u; idx2 < chain.childChains.size(); ++idx2)\n                {\n                    const auto &cChainIdx2{ chain.childChains[idx2] };\n                    const auto &cChainData2{ chainDataStorage[cChainIdx2] };\n\n                    const auto childChainAngle{ treeutil::angleBetweenVectorsRad<float>(\n                        cChainData1.firstDirection, cChainData2.firstDirection)};\n                    const auto childChainAngleTotal{ treeutil::angleBetweenVectorsRad<float>(\n                        cChainData1.startToEnd, cChainData2.startToEnd)};\n\n                    if (treeutil::aboveEpsilon(cChainData1.firstDirection.length()) &&\n                        treeutil::aboveEpsilon(cChainData2.firstDirection.length()))\n                    {\n                        stats.chainSiblingAngle.observeSample(childChainAngle);\n                        minSiblingAngle = std::min<float>(minSiblingAngle, childChainAngle);\n                        maxSiblingAngle = std::max<float>(maxSiblingAngle, childChainAngle);\n                    }\n\n                    if (treeutil::aboveEpsilon(cChainData1.startToEnd.length()) &&\n                        treeutil::aboveEpsilon(cChainData2.startToEnd.length()))\n                    {\n                        stats.chainSiblingAngleTotal.observeSample(childChainAngleTotal);\n                        minSiblingAngleTotal = std::min<float>(minSiblingAngleTotal, childChainAngleTotal);\n                        maxSiblingAngleTotal = std::max<float>(maxSiblingAngleTotal, childChainAngleTotal);\n                    }\n\n                    if (treeutil::aboveEpsilon(chainData.subtreeLeafCount))\n                    {\n                        const auto leafAsymmetry{\n                            (cChainData1.subtreeLeafCount - cChainData2.subtreeLeafCount) /\n                            static_cast<float>(chainData.subtreeLeafCount)\n                        };\n                        stats.chainAsymmetryLeaf.observeSample(leafAsymmetry);\n                    }\n\n                    if (treeutil::aboveEpsilon(chainData.subtreeLength))\n                    {\n                        const auto lengthAsymmetry{\n                            (cChainData1.subtreeLength - cChainData2.subtreeLength) /\n                            static_cast<float>(chainData.subtreeLength)\n                        };\n                        stats.chainAsymmetryLength.observeSample(lengthAsymmetry);\n                    }\n\n                    if (treeutil::aboveEpsilon(chainData.subtreeVolume))\n                    {\n                        const auto volumeAsymmetry{\n                            (cChainData1.subtreeVolume - cChainData2.subtreeVolume) /\n                            static_cast<float>(chainData.subtreeVolume)\n                        };\n                        stats.chainAsymmetryVolume.observeSample(volumeAsymmetry);\n                    }\n                }\n                if (minSiblingAngle < std::numeric_limits<float>::max())\n                {\n                    stats.chainMinSiblingAngle.observeSample(minSiblingAngle);\n                    minChildAngle = std::min<float>(minChildAngle, minSiblingAngle);\n                }\n                if (maxSiblingAngle > std::numeric_limits<float>::lowest())\n                {\n                    stats.chainMaxSiblingAngle.observeSample(maxSiblingAngle);\n                    maxChildAngle = std::max<float>(maxChildAngle, maxSiblingAngle);\n                }\n                if (minSiblingAngleTotal < std::numeric_limits<float>::max())\n                {\n                    stats.chainMinSiblingAngleTotal.observeSample(minSiblingAngleTotal);\n                    minChildAngleTotal = std::min<float>(minChildAngleTotal, minSiblingAngleTotal);\n                }\n                if (maxSiblingAngleTotal > std::numeric_limits<float>::lowest())\n                {\n                    stats.chainMaxSiblingAngleTotal.observeSample(maxSiblingAngleTotal);\n                    maxChildAngleTotal = std::max<float>(maxChildAngleTotal, maxSiblingAngleTotal);\n                }\n            }\n\n            if (minChildAngle < std::numeric_limits<float>::max())\n            { stats.chainMinChildAngle.observeSample(minChildAngle); }\n            if (maxChildAngle > std::numeric_limits<float>::lowest())\n            { stats.chainMaxChildAngle.observeSample(maxChildAngle); }\n            if (minChildAngleTotal < std::numeric_limits<float>::max())\n            { stats.chainMinChildAngleTotal.observeSample(minChildAngleTotal); }\n            if (maxChildAngleTotal > std::numeric_limits<float>::lowest())\n            { stats.chainMaxChildAngleTotal.observeSample(maxChildAngleTotal); }\n\n            if (minParentAngle < std::numeric_limits<float>::max())\n            { stats.chainMinParentAngle.observeSample(minParentAngle); }\n            if (maxParentAngle > std::numeric_limits<float>::lowest())\n            { stats.chainMaxParentAngle.observeSample(maxParentAngle); }\n            if (minParentAngleTotal < std::numeric_limits<float>::max())\n            { stats.chainMinParentAngleTotal.observeSample(minParentAngleTotal); }\n            if (maxParentAngleTotal > std::numeric_limits<float>::lowest())\n            { stats.chainMaxParentAngleTotal.observeSample(maxParentAngleTotal); }\n        }\n    }\n}\n\nvoid TreeStats::calculateGrowthStats(TreeStatValues &stats, const StatsSettings &settings,\n    const treeutil::TreeChains &chains, const std::vector<ChainData> &chainDataStorage)\n{\n    const auto branchingPointDelta{ stats.interNodeLengthEstimate * settings.growthBranchingPointDelta };\n    const auto compactChains{ chains.generateCompactChains(branchingPointDelta) };\n    const auto &chainsTree{ chains.internalTree() };\n    const auto &fullChains{ chains.chains() };\n\n    for (const auto &compactChain : compactChains)\n    { // Pre-calculate statistics on the compact chains, skipping leaves.\n        if (compactChain.childChains.empty())\n        { continue; }\n\n        const auto maxCompactedChainLength{ calculateMaxCompactChainLength(\n            fullChains, chainsTree, compactChain) };\n        const auto internodesInChain{ maxCompactedChainLength / stats.interNodeLengthEstimate };\n        stats.chainInternodeCount.observeSample(internodesInChain);\n    }\n\n    // Calculate required statistics from the first run.\n    const auto averageInternodeStats{ stats.chainInternodeCount.var.properties() };\n\n    for (const auto &compactChain : compactChains)\n    { // Go through all compacted chains, skipping leaves.\n        if (compactChain.childChains.empty())\n        { continue; }\n        if (compactChain.childChains.size() == 1u)\n        { Warning << \"Found compact chain with one child chain!\" << std::endl; }\n\n        std::vector<float> branchContinuationWeights{ };\n        std::vector<float> branchSizeWeights{ };\n\n        for (const auto &childChainRec : compactChain.childChains)\n        { // Calculate weights for child chains.\n            const auto parentChainInfo{ compactChain.compactedChains[childChainRec.originIdx] };\n            const auto parentChainIdx{ parentChainInfo.chainIdx };\n            const auto &parentChain{ fullChains[parentChainIdx] };\n            const auto &parentChainData{ chainDataStorage[parentChainIdx] };\n\n            const auto childChainIdx{ childChainRec.chainIdx };\n            const auto &childChain{ fullChains[childChainIdx] };\n            const auto &childChainData{ chainDataStorage[childChainIdx] };\n\n            const auto childContinuationWeight{ Vector3D::dotProduct(\n                parentChainData.lastDirection, childChainData.firstDirection) };\n            branchContinuationWeights.push_back(childContinuationWeight);\n\n            const auto childSizeWeight{ childChainData.subtreeLeafCount };\n            branchSizeWeights.push_back(childSizeWeight);\n        }\n\n        // Determine branching categories.\n        const auto [ mpFitness, mpSameAxis, mpHigherAxis ]{\n            calculateMonopodialFitness(branchContinuationWeights, branchSizeWeights) };\n        const auto [ smFitness, smSameAxis, smHigherAxis ]{\n            calculateSympodialMonochasialFitness(branchContinuationWeights, branchSizeWeights) };\n        const auto [ sdFitness, sdSameAxis, sdHigherAxis ]{\n            calculateSympodialDichasialFitness(branchContinuationWeights, branchSizeWeights) };\n\n        // Observe branching results.\n        stats.chainMonopodialBranchingFitness.observeSample(mpFitness);\n        stats.aggregateBranchingFitness.observeSample(\n            { branchingToOrdinal(Branching::Monopodial), mpFitness });\n        stats.chainSympodialMonochasialBranchingFitness.observeSample(smFitness);\n        stats.aggregateBranchingFitness.observeSample(\n            { branchingToOrdinal(Branching::SympodialMonochasial), smFitness });\n        stats.chainSympodialDichasialBranchingFitness.observeSample(sdFitness);\n        stats.aggregateBranchingFitness.observeSample(\n            { branchingToOrdinal(Branching::SympodialDichasial), sdFitness });\n\n        // Calculate how many internodes does this chain contain before branching.\n        const auto maxCompactedChainLength{ calculateMaxCompactChainLength(\n            fullChains, chainsTree, compactChain) };\n        const auto internodesInChain{ maxCompactedChainLength / stats.interNodeLengthEstimate };\n\n        // Determine ramification categories.\n        const auto continuousFitness{ calculateContinuousFitness(internodesInChain,\n            averageInternodeStats.mean, averageInternodeStats.variance,\n            averageInternodeStats.min, averageInternodeStats.max) };\n        const auto rhythmicFitness{ calculateRhythmicFitness(internodesInChain,\n            averageInternodeStats.mean, averageInternodeStats.variance,\n            averageInternodeStats.min, averageInternodeStats.max) };\n        const auto diffuseFitness{ calculateDiffuseFitness(internodesInChain,\n            averageInternodeStats.mean, averageInternodeStats.variance,\n            averageInternodeStats.min, averageInternodeStats.max) };\n\n        // Observe ramification results.\n        stats.chainContinuousRamificationFitness.observeSample(continuousFitness);\n        stats.aggregateRamificationFitness.observeSample(\n            { ramificationToOrdinal(Ramification::Continuous), continuousFitness });\n        stats.chainRhythmicRamificationFitness.observeSample(rhythmicFitness);\n        stats.aggregateRamificationFitness.observeSample(\n            { ramificationToOrdinal(Ramification::Rhythmic), rhythmicFitness });\n        stats.chainDiffuseRamificationFitness.observeSample(diffuseFitness);\n        stats.aggregateRamificationFitness.observeSample(\n            { ramificationToOrdinal(Ramification::Diffuse), diffuseFitness });\n    }\n}\n\n/*(\n * prumer kmene\n * krivost retezu\n * oproti horizontu\n * Minimalni pocet featur ktere koreluji\n * vetvici uhel pro ruzne urovne by mel byt konstantni\n *   vypocitat rozdil oproti prumerne hodnote -> variance\n *   vynechat prvni uroven\n * Vypocitat featury pouze pro uroven 1 a 2\n * Vaha - tluste vetve pod kmenem jsou dulezitejsi.\n *      - vahovat pomoci objemu.\n * Apicalni dominance explicitni feature\n *\n * Pomery bb v shadow obrazu a ve 3D\n *\n * Overleaf:\n *  Tabulka\n *  Delky/tloustky, uhly, krivosti, objemy.\n *  Globalni, lokalni\n */\n\nfloat TreeStats::calculateMaxCompactChainLength(\n    const treeutil::TreeChains::ChainStorage &fullChains,\n    const treeutil::TreeChains::InternalArrayTree &chainsTree,\n    const treeutil::TreeChains::CompactNodeChain &compactChain)\n{\n    auto maxCompactedChainLength{ std::numeric_limits<float>::lowest() };\n\n    /// @brief Helper for calculating lengths of compacted chains.\n    struct ChainLengthHelper\n    {\n        /// Next index to be processed.\n        std::size_t nextIdx{ 0u };\n        /// Currently accumulated length.\n        float accumulatedLength{ 0.0f };\n    }; // struct ChainLengthHelper\n\n    std::queue<ChainLengthHelper> compactedChainQueue{ };\n    compactedChainQueue.push(ChainLengthHelper{ 0u, 0.0f });\n    while (!compactedChainQueue.empty())\n    {\n        const auto chainLengthHelper{ compactedChainQueue.front() }; compactedChainQueue.pop();\n        const auto subChainRec{ compactChain.compactedChains[chainLengthHelper.nextIdx] };\n        const auto &subChain{ fullChains[subChainRec.chainIdx] };\n\n        const auto chainLength{\n            chainLengthHelper.accumulatedLength +\n            subChain.calculateChainLength(chainsTree)\n        };\n\n        auto foundChild{ false };\n        for (std::size_t iii = 0u; iii < compactChain.compactedChains.size(); ++iii)\n        {\n            const auto &subChainChildRec{ compactChain.compactedChains[iii] };\n            if (subChainChildRec.originIdx == chainLengthHelper.nextIdx)\n            { foundChild = true; compactedChainQueue.push(ChainLengthHelper{ iii, chainLength }); }\n        }\n\n        if (!foundChild)\n        { maxCompactedChainLength = std::max(maxCompactedChainLength, chainLength); }\n    }\n\n    return maxCompactedChainLength;\n}\n\nstd::tuple<float, TreeStats::BranchIdxList, TreeStats::BranchIdxList>\nTreeStats::calculateMonopodialFitness(\n        const std::vector<float> &branchContinuationWeights,\n        const std::vector<float> &branchSizeWeights)\n{\n    /*\n     * Monopodial:\n     *\n     *  \\ | /\n     *   \\|/\n     *    |\n     *\n     *  * One primary branch with high size/continuation - same axis.\n     *  * Two or more child branches with the same size weights - higher axis.\n     */\n\n    BranchIdxList sameAxis{ };\n    BranchIdxList higherAxis{ };\n\n    const auto [minPrimary, argMinPrimary, maxPrimary, argMaxPrimary]{\n        treeutil::argMinMax(branchSizeWeights) };\n    const auto [minContinuation, argMinContinuation, maxContinuation, argMaxContinuation]{\n        treeutil::argMinMax(branchContinuationWeights) };\n    const auto allSame{ !treeutil::aboveEpsilon(maxPrimary - minPrimary) };\n    const auto primaryBranchIdx{ allSame ? argMaxContinuation : argMaxPrimary };\n    const auto maxDifference{\n        allSame ?\n        1.0f :\n        (maxPrimary - minPrimary)\n    };\n\n    const auto secondaryBranchCount{ branchSizeWeights.size() - 1u };\n    auto meanSecondarySizeWeight{ 0.0f };\n    auto secondMaxPrimary{ minPrimary };\n    for (std::size_t iii = 0u; iii < branchSizeWeights.size(); ++iii)\n    {\n        if (iii == primaryBranchIdx) { continue; }\n        meanSecondarySizeWeight += branchSizeWeights[iii];\n        secondMaxPrimary = std::max(secondMaxPrimary, branchSizeWeights[iii]);\n    }\n    meanSecondarySizeWeight /= static_cast<float>(secondaryBranchCount);\n\n    const auto primaryBranchFitness{\n        (allSame ? 1.0f : ((branchSizeWeights[primaryBranchIdx] - secondMaxPrimary) / maxDifference)) *\n        ((branchContinuationWeights[primaryBranchIdx] + 1.0f) / 2.0f)\n    };\n    sameAxis.push_back(primaryBranchIdx);\n\n    auto secondaryBranchFitness{ 0.0f };\n    for (std::size_t iii = 0u; iii < branchSizeWeights.size(); ++iii)\n    {\n        if (iii == primaryBranchIdx) { continue; }\n        const auto branchFitness{ branchSizeWeights[iii] - meanSecondarySizeWeight };\n        secondaryBranchFitness += 1.0f - (branchFitness * branchFitness) / (maxDifference * maxDifference);\n        higherAxis.push_back(iii);\n    }\n    secondaryBranchFitness /= static_cast<float>(std::max<std::size_t>(2u, secondaryBranchCount));\n\n    const auto monopodialFitness{ primaryBranchFitness * secondaryBranchFitness };\n\n    return { monopodialFitness, sameAxis, higherAxis };\n}\n\nstd::tuple<float, TreeStats::BranchIdxList, TreeStats::BranchIdxList>\nTreeStats::calculateSympodialMonochasialFitness(\n    const std::vector<float> &branchContinuationWeights,\n    const std::vector<float> &branchSizeWeights)\n{\n    /*\n     * Sympodial Monochasial:\n     *\n     *  \\ |/\n     *   \\|\n     *    |\n     *\n     *  * One primary branch - same axis.\n     *  * One secondary branch - higher axis.\n     */\n\n    BranchIdxList sameAxis{ };\n    BranchIdxList higherAxis{ };\n\n    const auto [minPrimary, argMinPrimary, maxPrimary, argMaxPrimary]{\n        treeutil::argMinMax(branchSizeWeights) };\n    const auto [minContinuation, argMinContinuation, maxContinuation, argMaxContinuation]{\n        treeutil::argMinMax(branchContinuationWeights) };\n    const auto allSame{ !treeutil::aboveEpsilon(maxPrimary - minPrimary) };\n    const auto primaryBranchIdx{ allSame ? argMaxContinuation : argMaxPrimary };\n    const auto maxDifference{\n        allSame ?\n        1.0f :\n        (maxPrimary - minPrimary)\n    };\n\n    const auto secondaryBranchCount{ branchSizeWeights.size() - 1u };\n    auto secondMaxPrimary{ minPrimary };\n    std::size_t argSecondMaxPrimary{ 1u };\n    for (std::size_t iii = 0u; iii < branchSizeWeights.size(); ++iii)\n    {\n        if (iii == primaryBranchIdx) { continue; }\n        const auto sizeValue{ branchSizeWeights[iii] };\n        if (secondMaxPrimary >= sizeValue)\n        { secondMaxPrimary = sizeValue; argSecondMaxPrimary = iii; }\n    }\n    const auto secondaryBranchIdx{ argSecondMaxPrimary };\n\n    const auto primaryBranchFitness{\n        (allSame ? 1.0f : ((branchSizeWeights[primaryBranchIdx] - secondMaxPrimary) / maxDifference)) *\n        ((branchContinuationWeights[primaryBranchIdx] + 1.0f) / 2.0f)\n    };\n    sameAxis.push_back(primaryBranchIdx);\n    higherAxis.push_back(secondaryBranchIdx);\n\n    auto secondaryBranchFitnessPenalization{ 0.0f };\n    for (std::size_t iii = 0u; iii < branchSizeWeights.size(); ++iii)\n    {\n        if (iii == primaryBranchIdx || iii == secondaryBranchIdx) { continue; }\n        const auto branchFitness{ branchSizeWeights[iii] };\n        secondaryBranchFitnessPenalization += branchFitness / maxDifference;\n        higherAxis.push_back(iii);\n    }\n    const auto secondaryBranchFitness{\n        secondaryBranchCount >= 2u ?\n        1.0f - secondaryBranchFitnessPenalization / static_cast<float>(secondaryBranchCount - 1u) :\n        1.0f\n    };\n\n    const auto sympodialMonochasialFitness{ primaryBranchFitness * secondaryBranchFitness };\n\n    return { sympodialMonochasialFitness, sameAxis, higherAxis };\n}\n\nstd::tuple<float, TreeStats::BranchIdxList, TreeStats::BranchIdxList>\nTreeStats::calculateSympodialDichasialFitness(\n    const std::vector<float> &branchContinuationWeights,\n    const std::vector<float> &branchSizeWeights)\n{\n    /*\n     * Sympodial Dichasial:\n     *\n     *  \\   /\n     *   \\|/\n     *    |\n     *\n     *  * Two secondary branches with same size weight, low continuation - higher axis.\n     *  * Optional one lower size weight branch - same axis.\n     */\n\n    BranchIdxList sameAxis{ };\n    BranchIdxList higherAxis{ };\n\n    const auto [minPrimary, argMinPrimary, maxPrimary, argMaxPrimary]{\n        treeutil::argMinMax(branchSizeWeights) };\n    const auto allSame{ !treeutil::aboveEpsilon(maxPrimary - minPrimary) };\n    const auto primaryBranchIdx{ argMaxPrimary };\n    const auto maxDifference{\n        allSame ?\n        1.0f :\n        (maxPrimary - minPrimary)\n    };\n\n    const auto secondaryBranchCount{ branchSizeWeights.size() - 1u };\n    auto secondMaxPrimary{ minPrimary };\n    std::size_t argSecondMaxPrimary{ 1u };\n    for (std::size_t iii = 0u; iii < branchSizeWeights.size(); ++iii)\n    {\n        if (iii == primaryBranchIdx) { continue; }\n        const auto sizeValue{ branchSizeWeights[iii] };\n        if (secondMaxPrimary >= sizeValue)\n        { secondMaxPrimary = sizeValue; argSecondMaxPrimary = iii; }\n    }\n    const auto secondaryBranchIdx{ argSecondMaxPrimary };\n\n    const auto primaryBranchFitness{\n        (secondMaxPrimary / branchSizeWeights[primaryBranchIdx]) *\n        (1.0f - (std::abs(\n            branchContinuationWeights[primaryBranchIdx] -\n            branchContinuationWeights[secondaryBranchIdx]\n        ) / 2.0f))\n    };\n    higherAxis.push_back(primaryBranchIdx);\n    higherAxis.push_back(secondaryBranchIdx);\n\n    auto secondaryBranchFitnessPenalization{ 0.0f };\n    for (std::size_t iii = 0u; iii < branchSizeWeights.size(); ++iii)\n    {\n        if (iii == primaryBranchIdx || iii == secondaryBranchIdx) { continue; }\n        const auto branchFitness{ branchSizeWeights[iii] };\n        secondaryBranchFitnessPenalization += (branchFitness / maxDifference) *\n                                              ((branchContinuationWeights[iii] + 1.0f) / 2.0f);\n        sameAxis.push_back(iii);\n    }\n    const auto secondaryBranchFitness{\n        secondaryBranchCount >= 2u ?\n        1.0f - secondaryBranchFitnessPenalization / static_cast<float>(secondaryBranchCount - 1u) :\n        1.0f\n    };\n\n    const auto sympodialDichasialFitness{ primaryBranchFitness * secondaryBranchFitness };\n\n    return { sympodialDichasialFitness, sameAxis, higherAxis };\n}\n\nImageData copyModality(const treert::RayTracer::OutputModality<float> &modality)\n{\n    ImageData result{ };\n\n    result.width = modality.width;\n    result.height = modality.height;\n    result.channels = 1u;\n    result.valueType = ImageData::ValueType::Float;\n\n    const auto dataSize{ modality.dataBuffer.size() * sizeof(float) };\n    result.data.resize(dataSize);\n    std::memcpy(result.data.data(), modality.dataBuffer.data(), dataSize);\n\n    return result;\n}\n\nImageData copyModality(const treert::RayTracer::OutputModality<Vector3D> &modality)\n{\n    ImageData result{ };\n\n    result.width = modality.width;\n    result.height = modality.height;\n    result.channels = 3u;\n    result.valueType = ImageData::ValueType::Float;\n\n    const auto dataSize{ modality.dataBuffer.size() * sizeof(Vector3D) };\n    result.data.resize(dataSize);\n    std::memcpy(result.data.data(), modality.dataBuffer.data(), dataSize);\n\n    return result;\n}\n\nImageData copyModality(const treert::RayTracer::OutputModality<uint32_t> &modality)\n{\n    ImageData result{ };\n\n    result.width = modality.width;\n    result.height = modality.height;\n    result.channels = 1u;\n    result.valueType = ImageData::ValueType::UInt;\n\n    const auto dataSize{ modality.dataBuffer.size() * sizeof(uint32_t) };\n    result.data.resize(dataSize);\n    std::memcpy(result.data.data(), modality.dataBuffer.data(), dataSize);\n\n    return result;\n}\n\ntemplate <typename ModalityT>\nImageData createEmpty(std::size_t w, std::size_t h)\n{ ModalityT modality(w, h, 1); return copyModality(modality); }\n\nvoid TreeStats::calculateVisualStats(TreeStatValues &stats,\n    const StatsSettings &settings, const treeio::ArrayTree &inputTree)\n{\n    if (!settings.visualEnabled)\n    {\n        stats.shadowImprint = createEmpty<treert::RayTracer::VolumeModality>(1u, 1u);\n        return;\n    }\n\n    // Prepare ray-tracer with tree reconstruction placed in the scene.\n    const auto rayTracerPtr{\n        treerndr::RenderSystemRT::prepareTreeRayTracer(\n            inputTree, settings.visualTreeScale)\n    };\n    auto &rayTracer{ *rayTracerPtr };\n\n    // Setup ray-tracer.\n    rayTracer.setVerbose(settings.visualVerbose);\n    rayTracer.setSampling(settings.visualSampleCount);\n\n    // Prepare modalities.\n    rayTracer.traceModalities({ treert::TracingModality::Volume });\n    treert::RayTracer::VolumeModality tracedAccumulator{ };\n\n    // Prepare progress printing for long jobs.\n    treeutil::ProgressBar progressBar{ \"Views \" };\n    static constexpr auto PROGRESS_PRINT_STEP{ 10u };\n    treeutil::ProgressPrinter progressPrinter{ progressBar,\n        std::max<std::size_t>(PROGRESS_PRINT_STEP, settings.visualViewCount),\n        PROGRESS_PRINT_STEP\n    };\n\n    // Ray-trace requested views.\n    const auto basePos{ settings.visualTreeScale / 2.0f };\n    for (std::size_t viewIdx = 0u; viewIdx < settings.visualViewCount; ++viewIdx)\n    { // Ray-trace each view independently.\n        const auto t{ viewIdx / static_cast<float>(settings.visualViewCount) };\n\n        // Position the camera.\n        const auto cameraPosition{\n            Vector3D{\n                std::sin(t * 2.0f * treeutil::PI<float>) * basePos,\n                basePos,\n                std::cos(t * 2.0f * treeutil::PI<float>) * basePos\n            }\n        };\n        const auto cameraFocus{ Vector3D{ 0.0f, basePos, 0.0f } };\n\n        // Prepare ray-tracing context for current view.\n        const auto ctx{\n            rayTracer.generateOrthoContext(\n                settings.visualViewWidth, settings.visualViewHeight,\n                cameraPosition, cameraFocus\n            )\n        };\n\n        // Perform ray tracing.\n        rayTracer.traceRays(ctx);\n\n        // Accumulate results.\n        const auto &tracedData{ rayTracer.volumeModality() };\n        if (tracedAccumulator.dataBuffer.empty())\n        { tracedAccumulator = tracedData; }\n        else\n        {\n            for (std::size_t jjj = 0u; jjj < tracedAccumulator.dataBuffer.size(); ++jjj)\n            { tracedAccumulator.dataBuffer[jjj] += tracedData.dataBuffer[jjj]; }\n        }\n\n        // Report on progress.\n        if (settings.visualViewCount >= PROGRESS_PRINT_STEP)\n        { progressPrinter.printProgress(Info, viewIdx + 1u); }\n    }\n\n    // Finalize processing of modalities.\n    for (auto &volume : tracedAccumulator.dataBuffer)\n    { volume /= static_cast<float>(settings.visualViewCount); }\n\n    // Save results into buffers.\n    stats.shadowImprint = copyModality(tracedAccumulator);\n\n    if (settings.visualExportResults)\n    { // Export the results.\n        tracedAccumulator.exportToFile(settings.visualExportPath + \"/shadowImprint.png\");\n    }\n}\n\nvoid TreeStats::calculateDerivedStats(TreeStatValues &stats, const StatsSettings &settings,\n    const treeutil::TreeChains &chains, const std::vector<ChainData> &chainDataStorage)\n{\n    const auto &chainLengths{ stats.chainLength.var.observations() };\n    // Get trunk chain length, which is always the first.\n    stats.trunkLength = chainLengths.empty() ? 0.0f : chainLengths.front();\n\n    // Estimate inter-node length, without including the trunk.\n    const auto [lengthMean, lengthVariance]{\n        chainLengths.empty() ?\n            std::make_pair(0.0f, 0.0f) :\n            utils::sampleMeanVariance<float>(\n                chainLengths.begin() + 1u,\n                chainLengths.end()\n            )\n    };\n    stats.interNodeLengthEstimate = lengthMean;\n    stats.interNodeLengthVariance = lengthVariance;\n\n    // Find the deepest leaf chain.\n    std::size_t deepestLeafChain{ 0u };\n    for (const auto &leafChainIdx : chains.leafChains())\n    { deepestLeafChain = std::max(deepestLeafChain, chains.chains()[leafChainIdx].chainDepth); }\n\n    // Estimate crown age by using the deepest leaf chain, without the trunk.\n    const auto crownAge{ deepestLeafChain - 1u };\n    // Estimate trunk age by dividing it into corresponding inter-node sizes.\n    const auto trunkAge{ static_cast<std::size_t>(std::ceil(stats.trunkLength / stats.interNodeLengthEstimate)) };\n\n    // Total age is the age of the crown + age of the trunk...\n    stats.treeAge = crownAge + trunkAge;\n\n    // Determine number of leaves.\n    stats.leafCount = chains.leafChains().size();\n}\n\nfloat TreeStats::calculateContinuousFitness(float internodeCount, float mean, float var, float min, float max)\n{\n    /*\n     * Continuous ramification is defined by regular branching, specifically\n     * 1 internode per branch.\n     */\n\n    // Calculate fitness as distance from optimal value - 1 internode per branching.\n    const auto diff{ std::abs(1.0f - internodeCount) };\n    const auto fitness{ treeutil::smoothstep<float>(1.0f - diff) };\n\n    return fitness;\n}\n\nfloat TreeStats::calculateRhythmicFitness(float internodeCount, float mean, float var, float min, float max)\n{\n    /*\n     * Rhythmic ramification is defined by regular branching, which is other\n     * than 1 internode per branch.\n     */\n\n    // Calculate regularity as distance from optimal value - average internodes per branching.\n    const auto regularityDiff{ std::abs(mean - internodeCount) };\n    const auto regularityFitness{ treeutil::smoothstep<float>(1.0f - regularityDiff) };\n\n    // Calculate rhythmic nature as distance from 1 internode per branch.\n    const auto rhythmicDiff{ std::abs(1.0f - internodeCount) };\n    const auto rhythmicFitness{ treeutil::smoothstep<float>(rhythmicDiff) };\n\n    // Resulting fitness is combination of the two attributes.\n    const auto fitness{ regularityFitness * rhythmicFitness };\n    return fitness;\n}\n\nfloat TreeStats::calculateDiffuseFitness(float internodeCount, float mean, float var, float min, float max)\n{\n    /*\n     * Diffuse ramification is defined by irregular branching.\n     */\n\n    // Calculate irregularity as distance from optimal value - average internodes per branching.\n    const auto diff{ std::abs(mean - internodeCount) };\n    const auto fitness{ treeutil::smoothstep<float>(diff) };\n\n    return fitness;\n}\n\nvoid TreeStats::finalizeStats(TreeStatValues &stats, const StatsSettings &settings)\n{\n    // Calculate the rest of the histograms.\n    stats.forEach([] (auto &var)\n    { var.var.properties(); if (!var.histPrepared) { var.calculateHistogram(MIN_BUCKETS); } });\n\n    // Calculate properties and clean up unnecessary data:\n    stats.forEach([] (auto &var)\n    // TODO - Clear observations after saving?\n    { /* var.var.clearObservations(true); */ });\n\n    // Determine aggregate stats.\n    stats.branching = ordinalToBranching(stats.aggregateBranchingFitness.hist.maxBucket().first);\n    stats.ramification = ordinalToRamification(stats.aggregateRamificationFitness.hist.maxBucket().first);\n}\n\nTreeStats::StatsSettings &TreeStats::settings()\n{ return mSettings; }\nconst TreeStats::StatsSettings &TreeStats::settings() const\n{ return mSettings; }\n\n} // namespace treestat\n", "meta": {"hexsha": "23c8723f078250f13cfc66dce6c08ea834447732", "size": 54108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TreeIO/src/TreeIO/impl/TreeStats.cpp", "max_stars_repo_name": "PolasekT/ICTree", "max_stars_repo_head_hexsha": "d13ad603101805bcc288411504ecffd6f2e1f365", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-09T22:37:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T13:40:44.000Z", "max_issues_repo_path": "TreeIO/src/TreeIO/impl/TreeStats.cpp", "max_issues_repo_name": "PolasekT/ICTree", "max_issues_repo_head_hexsha": "d13ad603101805bcc288411504ecffd6f2e1f365", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TreeIO/src/TreeIO/impl/TreeStats.cpp", "max_forks_repo_name": "PolasekT/ICTree", "max_forks_repo_head_hexsha": "d13ad603101805bcc288411504ecffd6f2e1f365", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-09T22:37:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T14:38:39.000Z", "avg_line_length": 39.8732498158, "max_line_length": 114, "alphanum_fraction": 0.6609373845, "num_tokens": 12280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5214597132346789}}
{"text": "#ifndef ZSVM_SPHERICAL_ECG_JACOBI_VARIATIONAL_OPTIMIZER_HPP_INCLUDED\n#define ZSVM_SPHERICAL_ECG_JACOBI_VARIATIONAL_OPTIMIZER_HPP_INCLUDED\n\n// C++ standard library headers\n#include <chrono>\n#include <cstddef> // for std::size_t\n#include <random> // for std::random_device\n#include <string>\n#include <vector>\n\n// OpenMP multithreading headers\n#include <omp.h>\n\n// Boost library headers\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/random.hpp> // for boost::random::independent_bits_engine etc.\n\n// Project-specific headers\n#include \"Restrict.hpp\"\n#include \"AmoebaOptimizer.hpp\"\n#include \"RealVariationalSolver.hpp\"\n#include \"SphericalECGJacobiContext.hpp\"\n\nnamespace zsvm {\n\n    template <typename T>\n    class SphericalECGJacobiVariationalOptimizer {\n\n        typedef boost::random::mt19937 random_generator_t;\n\n        typedef std::array<\n                random_generator_t::result_type,\n                random_generator_t::state_size> random_state_t;\n\n        typedef boost::random::independent_bits_engine<\n                random_generator_t,\n                std::numeric_limits<T>::digits,\n                boost::multiprecision::cpp_int> random_engine_t;\n\n    private: // ================================================================\n\n        const std::size_t num_particles;\n        const std::size_t num_parameters;\n        SphericalECGJacobiContext<T> context;\n        RealVariationalSolver<T> solver;\n        std::vector<std::vector<T>> basis;\n        std::vector<std::vector<T>> basis_matrices;\n        random_engine_t random_engine;\n        boost::random::normal_distribution<T> correlation_distribution;\n\n        static random_engine_t properly_seeded_random_engine() {\n            random_state_t seed_data;\n            std::random_device nondet_random_source;\n            std::generate(seed_data.begin(), seed_data.end(),\n                          std::ref(nondet_random_source));\n            seed_data[0] = static_cast<random_generator_t::result_type>(\n                    std::chrono::duration_cast<std::chrono::nanoseconds>(\n                            std::chrono::system_clock::now().time_since_epoch()\n                    ).count() % std::numeric_limits<\n                            random_generator_t::result_type>::max());\n            boost::random::seed_seq seed_sequence(seed_data.begin(),\n                                                  seed_data.end());\n            random_engine_t random_engine(seed_sequence);\n            return random_engine;\n        }\n\n    public: // =================================================================\n\n        explicit SphericalECGJacobiVariationalOptimizer(\n                long long int space_dimension,\n                const std::vector<zsvm::Particle<T>> &particles,\n                const std::string &mass_carrier,\n                const std::string &charge_carrier)\n                : num_particles(particles.size()),\n                  num_parameters(num_particles * (num_particles - 1) / 2),\n                  context(SphericalECGJacobiContext<T>::create(\n                          particles, mass_carrier, charge_carrier,\n                          space_dimension)),\n                  random_engine(properly_seeded_random_engine()),\n                  correlation_distribution(0, 3) {}\n\n        T get_ground_state_energy() {\n            return solver.get_eigenvalue(0);\n        }\n\n    public: // =================================================================\n\n        const std::vector<std::vector<T>> &get_basis() {\n            return basis;\n        }\n\n        void set_basis(const std::vector<std::vector<T>> &input_basis) {\n            basis = input_basis;\n            recompute_basis_matrices();\n            recompute_solver_matrices();\n        }\n\n        T augmented_ground_state_energy(\n                const T *RESTRICT new_basis_matrix) {\n            if (solver.empty()) {\n                T overlap_element, hamiltonian_element;\n                context.evaluate_matrix_elements(\n                        overlap_element, hamiltonian_element,\n                        new_basis_matrix, new_basis_matrix);\n                return hamiltonian_element / overlap_element;\n            }\n            const std::size_t basis_size = basis_matrices.size();\n            std::vector<T> new_overlap_column(basis_size + 1);\n            std::vector<T> new_hamiltonian_column(basis_size + 1);\n            for (std::size_t i = 0; i < basis_size; ++i) {\n                context.evaluate_matrix_elements(\n                        new_overlap_column[i], new_hamiltonian_column[i],\n                        basis_matrices[i].data(), new_basis_matrix);\n            }\n            context.evaluate_matrix_elements(\n                    new_overlap_column[basis_size],\n                    new_hamiltonian_column[basis_size],\n                    new_basis_matrix, new_basis_matrix);\n            return solver.minimum_augmented_eigenvalue(\n                    new_overlap_column.data(),\n                    new_hamiltonian_column.data());\n        }\n\n        void random_basis_element(T *RESTRICT basis_element) {\n            for (std::size_t i = 0; i < num_parameters; ++i) {\n                basis_element[i] = correlation_distribution(random_engine);\n            }\n        }\n\n        void construct_basis_matrix(\n                T *RESTRICT basis_matrix,\n                const T *RESTRICT basis_element) {\n            context.gaussian_parameter_matrix(basis_element, basis_matrix);\n        }\n\n        void add_basis_element(const std::vector<T> &basis_element) {\n            basis.push_back(basis_element);\n            std::vector<T> basis_matrix(num_parameters);\n            construct_basis_matrix(basis_matrix.data(), basis_element.data());\n            basis_matrices.push_back(basis_matrix);\n            const std::size_t basis_size = basis.size();\n            solver.set_basis_size_conservative(basis_size);\n            for (std::size_t i = 0; i < basis_size - 1; ++i) {\n                context.evaluate_matrix_elements(\n                        solver.overlap_matrix_element(i, basis_size - 1),\n                        solver.hamiltonian_matrix_element(i, basis_size - 1),\n                        basis_matrices[i].data(),\n                        basis_matrices[basis_size - 1].data());\n                solver.overlap_matrix_element(basis_size - 1, i) =\n                        solver.overlap_matrix_element(i, basis_size - 1);\n                solver.hamiltonian_matrix_element(basis_size - 1, i) =\n                        solver.hamiltonian_matrix_element(i, basis_size - 1);\n            }\n            context.evaluate_matrix_elements(\n                    solver.overlap_matrix_element(\n                            basis_size - 1, basis_size - 1),\n                    solver.hamiltonian_matrix_element(\n                            basis_size - 1, basis_size - 1),\n                    basis_matrices[basis_size - 1].data(),\n                    basis_matrices[basis_size - 1].data());\n        }\n\n        void replace_basis_element(const std::vector<T> &basis_element) {\n            const std::size_t basis_size = basis.size();\n            basis[basis_size - 1] = basis_element;\n            construct_basis_matrix(basis_matrices[basis_size - 1].data(),\n                                   basis_element.data());\n            for (std::size_t i = 0; i < basis_size - 1; ++i) {\n                context.evaluate_matrix_elements(\n                        solver.overlap_matrix_element(i, basis_size - 1),\n                        solver.hamiltonian_matrix_element(i, basis_size - 1),\n                        basis_matrices[i].data(),\n                        basis_matrices[basis_size - 1].data());\n                solver.overlap_matrix_element(basis_size - 1, i) =\n                        solver.overlap_matrix_element(i, basis_size - 1);\n                solver.hamiltonian_matrix_element(basis_size - 1, i) =\n                        solver.hamiltonian_matrix_element(i, basis_size - 1);\n            }\n            context.evaluate_matrix_elements(\n                    solver.overlap_matrix_element(\n                            basis_size - 1, basis_size - 1),\n                    solver.hamiltonian_matrix_element(\n                            basis_size - 1, basis_size - 1),\n                    basis_matrices[basis_size - 1].data(),\n                    basis_matrices[basis_size - 1].data());\n        }\n\n        std::vector<T> last_basis_element() {\n            return basis.back();\n        }\n\n        bool expand_amoeba(std::size_t num_trials,\n                           const T &initial_step_size,\n                           std::size_t max_steps) {\n            std::vector<T> new_basis_element(num_parameters);\n            std::vector<T> best_basis_element;\n            T best_energy = solver.empty()\n                            ? std::numeric_limits<T>::max()\n                            : solver.get_eigenvalue(0);\n            for (std::size_t trial = 0; trial < num_trials; ++trial) {\n                random_basis_element(new_basis_element.data());\n                const T new_energy = refine_amoeba(\n                        new_basis_element.data(), initial_step_size, max_steps);\n                if (new_energy < best_energy) {\n                    best_basis_element = new_basis_element;\n                    best_energy = new_energy;\n                }\n            }\n            if (!best_basis_element.empty()) {\n                add_basis_element(best_basis_element);\n                return true;\n            } else {\n                return false;\n            }\n        }\n\n    public: // =================================================================\n\n        T refine_amoeba(T *RESTRICT basis_element,\n                        const T &initial_step_size,\n                        std::size_t max_steps) {\n            std::vector<T> basis_matrix(num_parameters);\n            dznl::AmoebaOptimizer<T> amoeba(\n                    basis_element, num_parameters, initial_step_size,\n                    [&](const T *b) {\n                        construct_basis_matrix(basis_matrix.data(), b);\n                        return augmented_ground_state_energy(\n                                basis_matrix.data());\n                    });\n            for (std::size_t step = 0; step < max_steps; ++step) {\n                amoeba.step();\n            }\n            return amoeba.current_minimum(basis_element);\n        }\n\n        void recompute_basis_matrices() {\n            basis_matrices.clear();\n            for (const auto &basis_element : basis) {\n                std::vector<T> basis_matrix(num_parameters);\n                construct_basis_matrix(basis_matrix.data(),\n                                       basis_element.data());\n                basis_matrices.push_back(basis_matrix);\n            }\n        }\n\n        void recompute_solver_matrices() {\n            const std::size_t num_basis_matrices = basis_matrices.size();\n            solver.set_basis_size_destructive(num_basis_matrices);\n            for (std::size_t i = 0; i < num_basis_matrices; ++i) {\n                for (std::size_t j = 0; j < num_basis_matrices; ++j) {\n                    context.evaluate_matrix_elements(\n                            solver.overlap_matrix_element(i, j),\n                            solver.hamiltonian_matrix_element(i, j),\n                            basis_matrices[i].data(),\n                            basis_matrices[j].data());\n                }\n            }\n        }\n\n    }; // class SphericalECGJacobiVariationalOptimizer\n\n} // namespace zsvm\n\n#endif // ZSVM_SPHERICAL_ECG_JACOBI_VARIATIONAL_OPTIMIZER_HPP_INCLUDED\n", "meta": {"hexsha": "dc6af2152faa01218faef6adb94fdc4366dc396c", "size": 11584, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SphericalECGJacobiVariationalOptimizer.hpp", "max_stars_repo_name": "dzhang314/zsvm", "max_stars_repo_head_hexsha": "cf7155627e446e095b5888f828ea879378834eaa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SphericalECGJacobiVariationalOptimizer.hpp", "max_issues_repo_name": "dzhang314/zsvm", "max_issues_repo_head_hexsha": "cf7155627e446e095b5888f828ea879378834eaa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SphericalECGJacobiVariationalOptimizer.hpp", "max_forks_repo_name": "dzhang314/zsvm", "max_forks_repo_head_hexsha": "cf7155627e446e095b5888f828ea879378834eaa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7132075472, "max_line_length": 80, "alphanum_fraction": 0.5473929558, "num_tokens": 2211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.5214597132346788}}
{"text": "/**\n * @file\n * @brief Interface describing a three-layer feedforward neural network.\n * @author Arno Bastenhof\n */\n\n#ifndef NEURAL_HPP_\n#define NEURAL_HPP_\n\n#include <cmath>\n#include <stdexcept>\n#include <cstdint>\n\n#include <armadillo>\n\nnamespace mnist {\n\nclass NeuralNet {\npublic:\n  explicit          NeuralNet();\n                    NeuralNet(const NeuralNet &) = delete;\n                    NeuralNet(NeuralNet &&) = delete;\n  NeuralNet&        operator=(const NeuralNet &) = delete;\n  NeuralNet&        operator=(NeuralNet&&) = delete;\n  void              LearnWeights(const arma::Mat<uint8_t>& data,\n                        const double rate, const double reg, int epochs);\n  double            Evaluate(const arma::Mat<uint8_t>& data) const;\nprivate:\n  enum {\n    kBatchSz = 50,\n    kInputLayerSz = 784,\n    kHiddenLayerSz = 30,\n    kOutputLayerSz = 10,\n    kWeightsHeadSz = kHiddenLayerSz * (kInputLayerSz + 1),  // rows * cols\n    kWeightsTailSz = kOutputLayerSz * (kHiddenLayerSz + 1), // rows * cols\n    kWeightsSz = kWeightsHeadSz + kWeightsTailSz\n  };\n  arma::vec         weights_;\n  mutable arma::mat activ_l1_;\n  mutable arma::mat activ_l2_;\n  mutable arma::mat activ_l3_;\n  static void       ValidateSize(const arma::Mat<uint8_t>&);\n  void              InitWeights();          // randomly initializes weights\n  void              ForwardProp(const arma::Mat<uint8_t>&) const;\n  arma::vec         BackProp(const arma::Col<uint8_t>&, const double) const;\n};\n\n/**\n * @brief Default constructor.\n */\ninline NeuralNet::NeuralNet()\n  : weights_(kWeightsSz)\n  , activ_l1_(kBatchSz, kInputLayerSz + 1)\n  , activ_l2_(kBatchSz, kHiddenLayerSz + 1)\n  , activ_l3_(kBatchSz, kOutputLayerSz)\n{\n  // set bias activations\n  activ_l1_.col(0).ones();\n  activ_l2_.col(0).ones();\n}\n\ninline void NeuralNet::ValidateSize(const arma::Mat<uint8_t>& data)\n{\n  // Training- and test set sizes known from the MNIST database\n  if (data.n_rows % kBatchSz != 0) {\n    throw std::runtime_error{\"Unexpected dimensions of input data\"};\n  }\n}\n\n} // namespace mnist\n\n#endif // NEURAL_HPP_\n", "meta": {"hexsha": "1ae3764baefb4a15cef257c8484b63eb78801086", "size": 2068, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/neural.hpp", "max_stars_repo_name": "deryger/mnist", "max_stars_repo_head_hexsha": "d51b8bb617a81ffd11d78da161d41f23edaf3217", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-16T11:49:58.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-16T11:50:11.000Z", "max_issues_repo_path": "src/neural.hpp", "max_issues_repo_name": "deryger/mnist", "max_issues_repo_head_hexsha": "d51b8bb617a81ffd11d78da161d41f23edaf3217", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/neural.hpp", "max_forks_repo_name": "deryger/mnist", "max_forks_repo_head_hexsha": "d51b8bb617a81ffd11d78da161d41f23edaf3217", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-05-13T00:05:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-18T12:49:42.000Z", "avg_line_length": 28.3287671233, "max_line_length": 76, "alphanum_fraction": 0.6503868472, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5213843739105658}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace std;\nint main(int, char**)\n{\n    mtl::dense2D<double>    A(3, 4), A_t(3, 4), S(3, 3), V(3, 4), D(4,4);\n    A= 0;\n\n    A[0][0]=1;  A[0][1]=1;  A[0][2]=1;  A[0][3]=4; \n    A[1][0]=1;  A[1][1]=2;  A[1][2]=2;  A[1][3]=3;\n    A[2][0]=9;  A[2][1]=3;  A[2][2]=2;  A[2][3]=4;       \n    std::cout<<\"A=\\n\"<< A <<\"\\n\";\n\n    boost::tie(S, V, D)= svd(A, 1.e-10)= svd(A);  //second argument is optional (missmatch of upper R (A= Q*R))\n    std::cout<<\"Matrix  S=\\n\"<< S <<\"\\n\";\n    std::cout<<\"Matrix  V=\\n\"<< V <<\"\\n\";\n    std::cout<<\"Matrix  D=\\n\"<< D <<\"\\n\";\n    A_t= S*V*trans(D);\n    std::cout<<\"Matrix  A=S*V*D'=\\n\"<< A_t <<\"\\n\";\n\n    return 0;\n}\n\n", "meta": {"hexsha": "02555c514c6ca34cb2c04fa196d709d2f7ffb6e8", "size": 714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/svd_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/svd_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/svd_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": 28.56, "max_line_length": 111, "alphanum_fraction": 0.4565826331, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5213843722703067}}
{"text": "#ifndef H_CONVEX_MPC\n#define H_CONVEX_MPC\n\n// Standard\n#include <math.h>\n#include <iostream>\n#include <stdio.h>\n\n// Timer\n#include <chrono>\n\n// QP Solver\n#include <ExternalSource/myOptimizer/Goldfarb/QuadProg++.hh>\n\n// Eigen\n#include <Eigen/Dense>\n#include <eigen3/unsupported/Eigen/MatrixFunctions>\n\n// Gait Cycle\n#include <PnC/GaitCycle/GaitCycle.hpp>\n#include <memory>\n\n// Reaction Force Schedule\n#include <PnC/MPC/ReactionForceSchedule.hpp>\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 convex model-predictive control.\" \n// 2018 IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS). IEEE, 2018.\n\n// We modify the formulation to smoothen the solutions at each iteration.\n//  There is also an optional setting to smoothen the current solution from the previous solution \n\nclass CMPC{\npublic: \n\tCMPC();\n\t~CMPC();\n\n\tdouble robot_mass; // kg mass of the robot\n\tEigen::MatrixXd I_robot; // Robot inertia\n\n\tint horizon;// mpc horizon (number of steps);\n\tdouble mpc_dt; // mpc time interval per horizon steo\n\tdouble mu; // coefficient of friction\n\tdouble fz_max; // maximum z reaction force for one force vector.\n\tdouble control_alpha_; // Regularization term on the controls\n\tdouble delta_smooth_; // Parameter to smoothen the reaction force results\n\n\tbool smooth_from_prev_result_; // Whether to smooth the solution of the MPC iteration using the previous result\n\n\n\tbool custom_smoothing_; // Enable user-speicified custom smoothing matrix\n\tEigen::MatrixXd Dc1; // Custom smoothing for the entire horizon\n\n\tbool rotate_inertia; // whether or not the inertia needs to be rotated to the world frame. \n\t\t\t\t\t\t // If the inertia is expressed in body frame this needs to be true.\n\t\t\t\t\t\t // Otherwise if the inertia is already updated to be in the world frame, this can be set to false.\n\n\tEigen::VectorXd latest_f_vec_out; // Container holding the the latest computed force output for control (not to be confused with the force at the end of the horizon)\n\tEigen::VectorXd f_prev; // Previous reaction force vector for the first horizon.\n\n\tEigen::VectorXd X_pred; // dimension: (13*horizon) state prediction over the horizon. [x_{k+1}, x_{k+2}, ..., x_{k+horizon}]\n\tEigen::VectorXd F_out;  // dimension: (n_Fr*horizon) forces to exert over the horizon. [f_{k}, f_{k+1}, ..., f_{k - 1 + horizon}]\n\n\tstd::shared_ptr<GaitCycle> gait_cycle_ptr; // pointer to the gait cycle object\n\tstd::shared_ptr<ReactionForceSchedule> reaction_force_schedule_ptr; // pointer to the reaction force schedule\n\n  \t// Vector cost for the MPC: <<  th1,  th2,  th3,  px,  py,  pz,   w1,  w2,   w3,   dpx,  dpy,  dpz,  g\n\t// last term is gravity and should always be 0,0\n\t// cost_vec << 0.25, 0.25, 10.0, 2.0, 2.0, 50.0, 0.0, 0.0, 0.30, 0.20, 0.2, 0.10, 0.0;\n\tEigen::VectorXd cost_vec;  \n\n\tbool use_terminal_cost; // if true, will use the custom terminal cost\n\tEigen::VectorXd terminal_cost_vec; \t\n\n\t// Returns the state vector size of the MPC per horizon.\n\tint getStateVecDim(){return 13;}\n\n\t// Helper function which returns a 13-vector given the state of the robot. \n\t// x = [Theta, p, omega, pdot, g] \\in \\mathbf{R}^13\t\n\tEigen::VectorXd getx0(const double roll, const double pitch, const double yaw,\n\t\t\t\t\t\t  const double com_x, const double com_y, const double com_z,\n\t\t\t\t\t\t  const double roll_rate, const double pitch_rate, const double yaw_rate,\n\t\t\t\t\t\t  const double com_x_rate, const double com_y_rate, const double com_z_rate);\n\n\t// Gets the latest computed ground forces for control\n\tEigen::VectorXd getComputedGroundForces(){return latest_f_vec_out;}\n\t// Get computed ground forces in matrix form where the columns are the ground reaction forces\n\t// in the same order as r_feet. \n\tEigen::MatrixXd getMatComputedGroundForces();\n\n\t// Gets the computed forces over the horizon\n\tEigen::VectorXd getForcesOverHorizon(){return F_out;}\n\t// Gets the predicted state evolution over the horizon\n\tEigen::VectorXd getXpredOverHorizon(){return X_pred;}\n\n\n\tvoid setRobotMass(const double robot_mass_in){ robot_mass = robot_mass_in; }\n\t// Whether or not the inertia needs to be rotated to the world frame. \n\tvoid rotateBodyInertia(bool rotate_inertia_in){ rotate_inertia = rotate_inertia_in; }\n\n\tvoid setRobotInertia(const Eigen::MatrixXd & inertia_in){ I_robot = inertia_in; }\n\tvoid setDt(const double mpc_dt_in){mpc_dt = mpc_dt_in;}\t// MPC dt interval per horizon\n\tvoid setHorizon(const int & horizon_in);\t// MPC horizon (number of steps)\n\n\tvoid setMu(const double mu_in){ mu = mu_in;} // Set the coefficient of friction\n\tvoid setMaxFz(const double fz_max_in); // Set the maximum z reaction force for one force vector\n\tvoid setSmoothFromPrevResult(const bool smooth_prev_in){smooth_from_prev_result_ = smooth_prev_in;} // Sets whether to smoothen the current solution using the previous solution\n\n\t// Set preview start time for the gate cycle\n\tvoid setPreviewStartTime(const double t_preview_start_in);\n\tvoid setCustomGaitCycle(std::shared_ptr<GaitCycle> gait_cycle_ptr_in);\n\tvoid setCustomReactionForceSchedule(std::shared_ptr<ReactionForceSchedule> reaction_force_schedule_ptr_in);\n\n  \t// Vector cost for the MPC: <<  th1,  th2,  th3,  px,  py,  pz,   w1,  w2,   w3,   dpx,  dpy,  dpz,  g\n\tvoid setCostVec(const Eigen::VectorXd & cost_vec_in); // Sets the cost vector.\n\n  \t// Set Terminal vector cost for the MPC: <<  th1,  th2,  th3,  px,  py,  pz,   w1,  w2,   w3,   dpx,  dpy,  dpz,  g\n\t// use_terminal_cost_in : if true, will use the terminal cost specified.\n\tvoid setTerminalCostVec(const bool use_terminal_cost_in, const Eigen::VectorXd & terminal_cost_vec_in); // Sets the cost vector.\n\n\tvoid setControlAlpha(const double control_alpha_in){control_alpha_ = control_alpha_in;}\n\tvoid setDeltaSmooth(const double delta_smooth_in){delta_smooth_ = delta_smooth_in;}\n\n\tvoid enableCustomSmoothing(const bool enable_custom_smoothing){custom_smoothing_ = enable_custom_smoothing;}\t\n\tvoid setCustomSmoothing(const Eigen::MatrixXd & Dc1_in){ Dc1 = Dc1_in; }\n\n\t// Human readable prints out of f_vec_out. \n\tvoid print_f_vec(int & n_Fr, const Eigen::VectorXd & f_vec_out);\n\n\t// Helper function which transforms a constant x_des to a constant trajectory reference\n\t// Input: x_des \\in \\mathbf{R}^{13}\n\t// Ouput: X_ref \\in \\mathbf{R}^{13*horizon}\n\tvoid get_constant_desired_x(const Eigen::VectorXd & x_des, Eigen::VectorXd & X_ref);\n\n\t// The main solve MPC routine \n\t// All the values are in world frame\n\t// Inputs:\n\t// \t\tx0 = [Theta, p, omega, pdot, g] \\in \\mathbf{R}^{13}    (Starting state of the system) \t\t\n\t// \t\tX_des \\in \\mathbf{R}^{13*horizon} \t\t\t\t     (Reference or desired state evolution) \n\t// \t\tr_feet \\in \\mathbf{R}^{3 x number_of_point_contacts} (Matrix of point contact locations where each column is the xyz location of the contact)\n\t// Outputs:\n\t//\t\tx_pred \\in \\mathbf{R}^{13} - The predicted state after a time interval of mpc_dt has dimension  \n\t//\t\tf_vec_out \\mathbf{R}^{3 x number_of_point_contacts} The xyz forces needed to be exerted at the contact points to track X_des.\n\n\tvoid solve_mpc(const Eigen::VectorXd & x0, const Eigen::VectorXd & X_des, const Eigen::MatrixXd & r_feet,\n\t               Eigen::VectorXd & x_pred, Eigen::VectorXd & f_vec_out);\n\n\t// For testing\n\tvoid simulate_toy_mpc();\n\n\tvoid assemble_vec_to_matrix(const int & n, const int & m, const Eigen::VectorXd & vec, Eigen::MatrixXd & mat_out);\n\tvoid integrate_robot_dynamics(const double & dt, const Eigen::VectorXd & x_current, const Eigen::MatrixXd & f_Mat, const Eigen::MatrixXd & r_feet,\n\t                              Eigen::VectorXd & x_next);\n\nprivate:\n\tEigen::MatrixXd r_feet_; // Store the value of r_feet locally.\n\tdouble t_preview_start; // store start time of the preview.\n\n\tdouble gravity_acceleration;\n  \tEigen::MatrixXd R_roll(const double & phi);\n\tEigen::MatrixXd R_pitch(const double & theta);\n\tEigen::MatrixXd R_yaw(const double & psi);\n\tEigen::MatrixXd skew_sym_mat(const Eigen::VectorXd & v);\n\n\tvoid cont_time_state_space(const Eigen::VectorXd & x_current,\n\t                           const Eigen::MatrixXd & r_feet, \n\t                           Eigen::MatrixXd & A, Eigen::MatrixXd & B);\n\tvoid discrete_time_state_space(const Eigen::MatrixXd & A, const Eigen::MatrixXd & B, Eigen::MatrixXd & Adt, Eigen::MatrixXd & Bdt);\n\n\tvoid qp_matrices(const Eigen::MatrixXd & Adt, const Eigen::MatrixXd & Bdt, Eigen::MatrixXd & Aqp, Eigen::MatrixXd & Bqp);\n\tvoid get_force_constraints(const int & n_Fr, Eigen::MatrixXd & CMat, Eigen::VectorXd & cvec);\n\tvoid get_qp_constraints(const Eigen::MatrixXd & CMat, const Eigen::VectorXd & cvec, Eigen::MatrixXd & Cqp, Eigen::VectorXd & cvec_qp);\n\tvoid get_qp_costs(const int & n, const int & m, const Eigen::VectorXd & vecS_cost, const double & control_alpha, Eigen::MatrixXd & Sqp, Eigen::MatrixXd & Kqp, Eigen::MatrixXd& D0);\n\n\t// Converts location of the feet expressed in world frame to the CoM frame. We assume the CoM orientation frame is always aligned with world.\n\tvoid convert_r_feet_to_com_frame(const Eigen::VectorXd & p_com, const Eigen::MatrixXd & r_feet, Eigen::MatrixXd & r_feet_com);\n\n\tvoid solve_mpc_qp(const Eigen::MatrixXd & Aqp,  const Eigen::MatrixXd & Bqp, const Eigen::VectorXd & X_ref, \n\t\t\t\t\t  const Eigen::VectorXd & x0,   const Eigen::MatrixXd & Sqp, const Eigen::MatrixXd & Kqp, \n                      const Eigen::MatrixXd& D0, const Eigen::VectorXd& f_prev_in,\n\t\t\t\t\t  const Eigen::MatrixXd & Cqp, const Eigen::VectorXd & cvec_qp,\n\t\t\t\t\t  Eigen::VectorXd & f_vec_out);\n\n\n};\n\n#endif", "meta": {"hexsha": "4b0fa6b2d68c07d067d9722dc2005ed57e31a314", "size": 9554, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PnC/MPC/CMPC.hpp", "max_stars_repo_name": "stevenjj/PnC", "max_stars_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T22:36:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T22:36:54.000Z", "max_issues_repo_path": "PnC/MPC/CMPC.hpp", "max_issues_repo_name": "stevenjj/PnC", "max_issues_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PnC/MPC/CMPC.hpp", "max_forks_repo_name": "stevenjj/PnC", "max_forks_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.2842105263, "max_line_length": 181, "alphanum_fraction": 0.7317353988, "num_tokens": 2518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5213843672240339}}
{"text": "#include <SBGATPolyhedronGravityModel.hpp>\n#include <SBGATPolyhedronGravityModelUQ.hpp>\n#include <SBGATObjWriter.hpp>\n\n#include <vtkCleanPolyData.h>\n#include <vtkOBJReader.h>\n\n#include <json.hpp>\n#include <boost/progress.hpp>\n\n#include <armadillo>\n\nint main(){\n\n\tstd::ifstream i(\"input_file.json\");\n\tnlohmann::json input_data;\n\ti >> input_data;\n\n\tstd::string PATH_SHAPE = input_data[\"PATH_SHAPE\"];\n\tdouble CORRELATION_DISTANCE =  input_data[\"CORRELATION_DISTANCE\"];\n\n\tdouble ERROR_STANDARD_DEV  = input_data[\"ERROR_STANDARD_DEV\"];\n\tdouble DENSITY  = input_data[\"DENSITY\"];\n\n\tbool UNIT_IN_METERS  = input_data[\"UNIT_IN_METERS\"];\n\tbool HOLD_MASS_CONSTANT  = input_data[\"HOLD_MASS_CONSTANT\"];\n\n\n\tint N_MONTE_CARLO = input_data[\"N_MONTE_CARLO\"];\n\n\tstd::string OUTPUT_DIR = input_data[\"OUTPUT_DIR\"];\n\n\tstd::cout << \"- Path to shape: \" << PATH_SHAPE << std::endl;\n\tstd::cout << \"- Standard deviation on point coordinates (m) : \" << ERROR_STANDARD_DEV << std::endl;\n\tstd::cout << \"- Correlation distance (m) : \" << CORRELATION_DISTANCE << std::endl;\n\tstd::cout << \"- Density (kg/m^3) : \" << DENSITY << std::endl;\n\tstd::cout << \"- Monte Carlo Draws : \" << N_MONTE_CARLO << std::endl;\n\n\n\n\n\t// Reading\n\tvtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New();\n\treader -> SetFileName(PATH_SHAPE.c_str());\n\treader -> Update(); \n\n\t// An instance of SBGATPolyhedronGravityModel is created to evaluate the PGM of \n\t// the considered polytdata\n\tvtkSmartPointer<SBGATPolyhedronGravityModel> pgm_filter = vtkSmartPointer<SBGATPolyhedronGravityModel>::New();\n\tpgm_filter -> SetInputConnection(reader -> GetOutputPort());\n\tpgm_filter -> SetDensity(DENSITY);\n\n\t\n\tif(UNIT_IN_METERS){\n\t\tpgm_filter -> SetScaleMeters();\n\t} else{\n\t\tpgm_filter -> SetScaleKiloMeters();\n\t}\n\n\tstd::cout << \"Building pgm ...\\n\";\n\tpgm_filter -> Update();\n\n\n\t// An instance of SBGATPolyhedronGravityModelUQ is created to perform\n\t// uncertainty quantification from the PGM associated to the shape\n\tSBGATPolyhedronGravityModelUQ pgm_uq;\n\tpgm_uq.SetModel(pgm_filter);\n\tpgm_uq.PrecomputeMassPropertiesPartials();\n\tstd::cout << \"Populating shape covariance ...\\n\";\n\n\t// Populate the shape vertices covariance\n\tpgm_uq.ComputeVerticesCovarianceGlobal(ERROR_STANDARD_DEV,CORRELATION_DISTANCE);\n\t// Regularizing the covariance\n\tint regularized_eigen_values = pgm_uq.RegularizeCovariance();\n\n\tstd::cout << regularized_eigen_values << \" eigenvalues were regularized\\n\";\n\n\tstd::cout << \"Saving non-zero partition of shape covariance ...\\n\";\n\n\t// Save the covariance\n\tpgm_uq.SaveNonZeroVerticesCovariance(OUTPUT_DIR + \"shape_covariance.json\");\n\n\t// Saving baseline slices\n\tpgm_uq.TakeAndSaveSlice(0,OUTPUT_DIR + \"baseline_slice_x.txt\",0);\n\tpgm_uq.TakeAndSaveSlice(1,OUTPUT_DIR + \"baseline_slice_y.txt\",0);\n\tpgm_uq.TakeAndSaveSlice(2,OUTPUT_DIR + \"baseline_slice_z.txt\",0);\n\n\tstd::vector<arma::vec::fixed<3> > all_positions = {\n\t\tarma::vec::fixed<3>({300,0,0}),\n\t\tarma::vec::fixed<3>({400,0,0}),\n\t\tarma::vec::fixed<3>({500,0,0}),\n\t\tarma::vec::fixed<3>({-300,0,0}),\n\t\tarma::vec::fixed<3>({-400,0,0}),\n\t\tarma::vec::fixed<3>({-500,0,0}),\n\t\tarma::vec::fixed<3>({0,300,0}),\n\t\tarma::vec::fixed<3>({0,400,0}),\n\t\tarma::vec::fixed<3>({0,500,0}),\n\t\tarma::vec::fixed<3>({0,-300,0}),\n\t\tarma::vec::fixed<3>({0,-400,0}),\n\t\tarma::vec::fixed<3>({0,-500,0}),\n\t\tarma::vec::fixed<3>({0,0,300}),\n\t\tarma::vec::fixed<3>({0,0,400}),\n\t\tarma::vec::fixed<3>({0,0,500}),\n\t\tarma::vec::fixed<3>({0,0,-300}),\n\t\tarma::vec::fixed<3>({0,0,-400}),\n\t\tarma::vec::fixed<3>({0,0,-500}),\n\t};\n\n\n\t// Analytical UQ\n\n\tstd::vector<arma::mat::fixed<3,3> > analytical_covariances_acc(all_positions.size());\n\tstd::vector<double> analytical_variances_pot(all_positions.size());\n\n\tstd::cout << \"Computing analytical uncertainties ... \";\n\tauto start = std::chrono::system_clock::now();\n\t#pragma omp parallel for\n\tfor (int e = 0; e < all_positions.size(); ++e){\n\t\tanalytical_variances_pot[e] = pgm_uq.GetVariancePotential(all_positions[e],HOLD_MASS_CONSTANT);\n\t\tanalytical_covariances_acc[e] = pgm_uq.GetCovarianceAcceleration(all_positions[e],HOLD_MASS_CONSTANT);\n\t}\n\tauto end = std::chrono::system_clock::now();\n\n\tstd::chrono::duration<double> elapsed_seconds = end-start;\n\tstd::cout << \"Done computing analytical uncertainties in \" << elapsed_seconds.count() << \" s\\n\";\n\n\t// Running a Monte Carlo to compare againnst\n\tstd::vector<arma::vec> deviations;\n\tstd::vector<double> densities;\n\tstd::vector<std::vector<arma::vec::fixed<3> > >  all_accelerations;\n\tstd::vector < std::vector<double> > all_potentials;\n\tstd::vector<vtkSmartPointer<vtkPolyData > > saved_shapes(10);\n\n\tstd::cout << \"Running MC ... \";\n\n\t\n\tstart = std::chrono::system_clock::now();\n\tSBGATPolyhedronGravityModelUQ::RunMCUQPotentialAccelerationInertial(PATH_SHAPE,DENSITY,\n\t\tUNIT_IN_METERS,\n\t\tHOLD_MASS_CONSTANT,\n\t\tpgm_uq.GetCovarianceSquareRoot(),\n\t\tN_MONTE_CARLO, \n\t\tall_positions,\n\t\tOUTPUT_DIR,\n\t\tstd::min(30,N_MONTE_CARLO),\n\t\tdeviations,\n\t\tdensities,\n\t\tall_accelerations,\n\t\tall_potentials);\n\n\tend = std::chrono::system_clock::now();\n\n\telapsed_seconds = end-start;\n\n\tstd::cout << \"Done running MC in \" << elapsed_seconds.count() << \" s\\n\";\n\n\t\n\n\tstd::vector<double> mc_variances_pot(all_positions.size());\n\tstd::vector<arma::mat > mc_covariances_acc(all_positions.size());\n\n\tstd::cout << \"Computing MC dispersions...\\n\";\n\t\n\t#pragma omp parallel for\n\tfor (int e = 0; e < mc_variances_pot.size(); ++e){\n\n\t\tarma::vec potentials_mc(N_MONTE_CARLO);\n\t\tarma::mat accelerations_mc(3,N_MONTE_CARLO);\n\n\t\tfor (int sample = 0; sample < N_MONTE_CARLO; ++sample){\n\t\t\tpotentials_mc(sample) = all_potentials[sample][e];\n\t\t\taccelerations_mc.col(sample) = all_accelerations[sample][e];\n\t\t}\n\n\t\tmc_variances_pot[e] = arma::var(potentials_mc);\n\t\tmc_covariances_acc[e] = arma::cov(accelerations_mc.t());\n\n\t}\n\n\tstd::cout << \"\\t After \" << N_MONTE_CARLO << \" MC outcomes:\\n\";\n\n\tfor (int e = 0; e < all_positions.size(); ++e){\n\t\tall_positions[e].t().print(\"\\t At: \");\n\t\tstd::cout << \"\\t\\tMC variance in potential: \" << mc_variances_pot[e] << std::endl;\n\t\tstd::cout << \"\\t\\tAnalytical variance in potential: \" << analytical_variances_pot[e] << std::endl;\n\n\t\tstd::cout << \"\\t\\tError (%): \" << (mc_variances_pot[e] - analytical_variances_pot[e])/analytical_variances_pot[e] * 100 << std::endl;\n\n\t\tstd::cout << \"\\t\\tMC Covariance in acceleration: \\n\" << mc_covariances_acc[e] << std::endl;\n\t\tstd::cout << \"\\t\\tAnalytical covariance in acceleration: \\n\" << analytical_covariances_acc[e] << std::endl;\n\t\t\n\t\tstd::cout << \"\\t\\tError (%): \" << arma::norm(mc_covariances_acc[e] - analytical_covariances_acc[e])/arma::trace(mc_covariances_acc[e]) * 100 << std::endl;\n\t}\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "bbe8aa72d86e7c49bb602345bcfbfbfa3309121d", "size": 6628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/PGMUncertaintyMCGlobal/main.cpp", "max_stars_repo_name": "bbercovici/SBGAT", "max_stars_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T02:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T05:25:44.000Z", "max_issues_repo_path": "Examples/PGMUncertaintyMCGlobal/main.cpp", "max_issues_repo_name": "bbercovici/SBGAT", "max_issues_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2017-02-09T15:38:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-25T20:53:37.000Z", "max_forks_repo_path": "Examples/PGMUncertaintyMCGlobal/main.cpp", "max_forks_repo_name": "bbercovici/SBGAT", "max_forks_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T12:20:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T12:20:25.000Z", "avg_line_length": 33.4747474747, "max_line_length": 156, "alphanum_fraction": 0.7041339771, "num_tokens": 1954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5213843621777611}}
{"text": "/* boost random/lognormal_distribution.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Permission to use, copy, modify, sell, and distribute this software\n * is hereby granted without fee provided that the above copyright notice\n * appears in all copies and that both that copyright notice and this\n * permission notice appear in supporting documentation,\n *\n * Jens Maurer makes no representations about the suitability of this\n * software for any purpose. It is provided \"as is\" without express or\n * implied warranty.\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: lognormal_distribution.hpp 11696 2001-11-14 21:53:38Z jmaurer $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_LOGNORMAL_DISTRIBUTION_HPP\n#define BOOST_RANDOM_LOGNORMAL_DISTRIBUTION_HPP\n\n#include <cmath>      // std::exp, std::sqrt\n#include <cassert>\n#include <boost/random/normal_distribution.hpp>\n\n#ifdef BOOST_NO_STDC_NAMESPACE\nnamespace std {\n  using ::log;\n  using ::sqrt;\n}\n#endif\n\nnamespace boost {\n\n#if defined(__GNUC__) && (__GNUC__ < 3)\n// Special gcc workaround: gcc 2.95.x ignores using-declarations\n// in template classes (confirmed by gcc author Martin v. Loewis)\n  using std::sqrt;\n  using std::exp;\n#endif\n\ntemplate<class UniformRandomNumberGenerator, class RealType = double>\nclass lognormal_distribution\n{\npublic:\n  typedef UniformRandomNumberGenerator base_type;\n  typedef RealType result_type;\n  lognormal_distribution(base_type & rng, result_type mean, \n                         result_type sigma)\n    : _rng(rng, std::log(mean*mean/std::sqrt(sigma*sigma + mean*mean)),\n           std::sqrt(std::log(sigma*sigma/mean/mean+1)))\n  { \n    assert(mean > 0);\n  }\n  // compiler-generated copy constructor is fine\n  // normal_distribution cannot be assigned, neither can this class\n  result_type operator()()\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    // allow for Koenig lookup\n    using std::exp;\n#endif\n    return exp(_rng());\n  }\n\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\n  friend bool operator==(const lognormal_distribution& x, \n                         const lognormal_distribution& y)\n  { return x._rng == y._rng; }\n#else\n  // Use a member function\n  bool operator==(const lognormal_distribution& rhs) const\n  { return _rng == rhs._rng;  }\n#endif\nprivate:\n  normal_distribution<base_type, result_type> _rng;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_LOGNORMAL_DISTRIBUTION_HPP\n", "meta": {"hexsha": "3109c5c73319233d30c5d2e47b3d1f9705a3853d", "size": 2474, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/random/lognormal_distribution.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vegastrike/boost/1_28/boost/random/lognormal_distribution.hpp", "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vegastrike/boost/1_28/boost/random/lognormal_distribution.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["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.4523809524, "max_line_length": 76, "alphanum_fraction": 0.7320129345, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5213843621777611}}
{"text": "#include \"frc971/control_loops/drivetrain/improved_down_estimator.h\"\n\n#include <Eigen/Geometry>\n#include <random>\n\n#include \"frc971/control_loops/quaternion_utils.h\"\n#include \"aos/testing/random_seed.h\"\n#include \"frc971/control_loops/drivetrain/drivetrain_test_lib.h\"\n#include \"frc971/control_loops/runge_kutta.h\"\n#include \"glog/logging.h\"\n#include \"gtest/gtest.h\"\n\nnamespace frc971 {\nnamespace control_loops {\nnamespace testing {\n\nnamespace {\n// Check if two quaternions are logically equal, to within some reasonable\n// tolerance. This is needed because a single rotation can be represented by two\n// quaternions.\nbool QuaternionEqual(const Eigen::Quaterniond &a, const Eigen::Quaterniond &b,\n                     double tolerance) {\n  // If a == b, then a.inverse() * b will be the identity. The identity\n  // quaternion is the only time where the vector portion of the quaternion is\n  // zero.\n  return (a.inverse() * b).vec().norm() <= tolerance;\n}\n}  // namespace\n\n// Do a known transformation to see if quaternion integration is working\n// correctly.\nTEST(DownEstimatorTest, QuaternionIntegral) {\n  Eigen::Vector3d ux = Eigen::Vector3d::UnitX();\n  Eigen::Vector3d uy = Eigen::Vector3d::UnitY();\n  Eigen::Vector3d uz = Eigen::Vector3d::UnitZ();\n\n  Eigen::Quaternion<double> q(\n      Eigen::AngleAxis<double>(0.5 * M_PI, Eigen::Vector3d::UnitY()));\n\n  Eigen::Quaternion<double> q0(\n      Eigen::AngleAxis<double>(0, Eigen::Vector3d::UnitY()));\n\n  auto qux = q * ux;\n\n  VLOG(1) << \"Q is w: \" << q.w() << \" vec: \" << q.vec();\n  VLOG(1) << \"ux is \" << ux;\n  VLOG(1) << \"qux is \" << qux;\n\n  // Start by rotating around the X body vector for pi/2\n  Eigen::Quaternion<double> integral1(\n      RungeKutta(std::bind(&drivetrain::DrivetrainUkf::QuaternionDerivative, ux,\n                           std::placeholders::_1),\n                 q0.coeffs(), 0.5 * M_PI));\n\n  VLOG(1) << \"integral1 * uz => \" << integral1 * uz;\n\n  // Then rotate around the Y body vector for pi/2\n  Eigen::Quaternion<double> integral2(\n      RungeKutta(std::bind(&drivetrain::DrivetrainUkf::QuaternionDerivative, uy,\n                           std::placeholders::_1),\n                 integral1.normalized().coeffs(), 0.5 * M_PI));\n\n  VLOG(1) << \"integral2 * uz => \" << integral2 * uz;\n\n  // Then rotate around the X body vector for -pi/2\n  Eigen::Quaternion<double> integral3(\n      RungeKutta(std::bind(&drivetrain::DrivetrainUkf::QuaternionDerivative,\n                           -ux, std::placeholders::_1),\n                 integral2.normalized().coeffs(), 0.5 * M_PI));\n\n  integral1.normalize();\n  integral2.normalize();\n  integral3.normalize();\n\n  VLOG(1) << \"Integral is w: \" << integral1.w() << \" vec: \" << integral1.vec()\n          << \" norm \" << integral1.norm();\n\n  VLOG(1) << \"Integral is w: \" << integral3.w() << \" vec: \" << integral3.vec()\n          << \" norm \" << integral3.norm();\n\n  VLOG(1) << \"ux => \" << integral3 * ux;\n  EXPECT_NEAR(0.0, (ux - integral1 * ux).norm(), 5e-2);\n  EXPECT_NEAR(0.0, (uz - integral1 * uy).norm(), 5e-2);\n  EXPECT_NEAR(0.0, (-uy - integral1 * uz).norm(), 5e-2);\n\n  EXPECT_NEAR(0.0, (uy - integral2 * ux).norm(), 5e-2);\n  EXPECT_NEAR(0.0, (uz - integral2 * uy).norm(), 5e-2);\n  EXPECT_NEAR(0.0, (ux - integral2 * uz).norm(), 5e-2);\n\n  EXPECT_NEAR(0.0, (uy - integral3 * ux).norm(), 5e-2);\n  EXPECT_NEAR(0.0, (-ux - integral3 * uy).norm(), 5e-2);\n  EXPECT_NEAR(0.0, (uz - integral3 * uz).norm(), 5e-2);\n}\n\nTEST(DownEstimatorTest, UkfConstantRotation) {\n  drivetrain::DrivetrainUkf dtukf(\n      drivetrain::testing::GetTestDrivetrainConfig());\n  const Eigen::Vector3d ux = Eigen::Vector3d::UnitX();\n  EXPECT_EQ(0.0,\n            (Eigen::Vector3d(0.0, 0.0, 1.0) - dtukf.H(dtukf.X_hat().coeffs()))\n                .norm());\n  Eigen::Matrix<double, 3, 1> measurement;\n  measurement.setZero();\n  for (int ii = 0; ii < 200; ++ii) {\n    dtukf.Predict(ux * M_PI_2, measurement, std::chrono::milliseconds(5));\n  }\n  const Eigen::Quaterniond expected(Eigen::AngleAxis<double>(M_PI_2, ux));\n  EXPECT_TRUE(QuaternionEqual(expected, dtukf.X_hat(), 0.01))\n      << \"Expected: \" << expected.coeffs()\n      << \" Got: \" << dtukf.X_hat().coeffs();\n  EXPECT_NEAR(\n      0.0,\n      (Eigen::Vector3d(0.0, 1.0, 0.0) - dtukf.H(dtukf.X_hat().coeffs())).norm(),\n      1e-10);\n}\n\n// Tests that the euler angles in the status message are correct.\nTEST(DownEstimatorTest, UkfEulerStatus) {\n  drivetrain::DrivetrainUkf dtukf(\n      drivetrain::testing::GetTestDrivetrainConfig());\n  const Eigen::Vector3d ux = Eigen::Vector3d::UnitX();\n  const Eigen::Vector3d uy = Eigen::Vector3d::UnitY();\n  const Eigen::Vector3d uz = Eigen::Vector3d::UnitZ();\n  // First, rotate 3 radians in the yaw axis, then 0.5 radians in the pitch\n  // axis, and then 0.1 radians about the roll axis.\n  // The down estimator should ignore any of the pitch movement.\n  constexpr double kYaw = 3.0;\n  constexpr double kPitch = 0.5;\n  constexpr double kRoll = 0.1;\n  Eigen::Matrix<double, 3, 1> measurement;\n  measurement.setZero();\n  aos::monotonic_clock::time_point now = aos::monotonic_clock::epoch();\n  const std::chrono::milliseconds dt(5);\n  // Run a bunch of one-second rotations at the appropriate rate to cause the\n  // total pitch/roll/yaw to be kPitch/kRoll/kYaw.\n  for (int ii = 0; ii < 200; ++ii) {\n    dtukf.UpdateIntegratedPositions(now);\n    now += dt;\n    dtukf.Predict(uz * kYaw, measurement, dt);\n  }\n  for (int ii = 0; ii < 200; ++ii) {\n    dtukf.UpdateIntegratedPositions(now);\n    now += dt;\n    dtukf.Predict(uy * kPitch, measurement, dt);\n  }\n  EXPECT_FLOAT_EQ(kYaw, dtukf.yaw());\n  for (int ii = 0; ii < 200; ++ii) {\n    dtukf.UpdateIntegratedPositions(now);\n    now += dt;\n    dtukf.Predict(ux * kRoll, measurement, dt);\n  }\n  EXPECT_FLOAT_EQ(kYaw, dtukf.yaw());\n  const Eigen::Quaterniond expected(Eigen::AngleAxis<double>(kPitch, uy) *\n                                    Eigen::AngleAxis<double>(kRoll, ux));\n  flatbuffers::FlatBufferBuilder fbb;\n  fbb.ForceDefaults(true);\n  fbb.Finish(dtukf.PopulateStatus(&fbb, now));\n\n  aos::FlatbufferDetachedBuffer<drivetrain::DownEstimatorState> state(\n      fbb.Release());\n  EXPECT_EQ(kPitch, state.message().longitudinal_pitch());\n  // The longitudinal pitch is not actually the same number as the roll, so we\n  // don't check it here.\n\n  EXPECT_TRUE(QuaternionEqual(expected, dtukf.X_hat(), 0.0001))\n      << \"Expected: \" << expected.coeffs()\n      << \" Got: \" << dtukf.X_hat().coeffs();\n}\n\n// Tests that if the gyro indicates no movement but that the accelerometer shows\n// that we are slightly rotated, that we eventually adjust our estimate to be\n// correct.\nTEST(DownEstimatorTest, UkfAccelCorrectsBias) {\n  drivetrain::DrivetrainUkf dtukf(\n      drivetrain::testing::GetTestDrivetrainConfig());\n  const Eigen::Vector3d ux = Eigen::Vector3d::UnitX();\n  Eigen::Matrix<double, 3, 1> measurement;\n  // Supply the accelerometer with a slightly off reading to ensure that we\n  // don't require exactly 1g to work.\n  measurement << 0.01, 0.99, 0.0;\n  EXPECT_TRUE(\n      QuaternionEqual(Eigen::Quaterniond::Identity(), dtukf.X_hat(), 0.0))\n      << \"X_hat: \" << dtukf.X_hat().coeffs();\n  EXPECT_EQ(0.0,\n            (Eigen::Vector3d(0.0, 0.0, 1.0) - dtukf.H(dtukf.X_hat().coeffs()))\n                .norm());\n  for (int ii = 0; ii < 200; ++ii) {\n    dtukf.Predict({0.0, 0.0, 0.0}, measurement, std::chrono::milliseconds(5));\n  }\n  const Eigen::Quaterniond expected(Eigen::AngleAxis<double>(M_PI_2, ux));\n  EXPECT_TRUE(QuaternionEqual(expected, dtukf.X_hat(), 0.01))\n      << \"Expected: \" << expected.coeffs()\n      << \" Got: \" << dtukf.X_hat().coeffs();\n}\n\n// Tests that if the accelerometer is reading values with a magnitude that isn't\n// ~1g, that we are slightly rotated, that we eventually adjust our estimate to\n// be correct.\nTEST(DownEstimatorTest, UkfIgnoreBadAccel) {\n  drivetrain::DrivetrainUkf dtukf(\n      drivetrain::testing::GetTestDrivetrainConfig());\n  const Eigen::Vector3d uy = Eigen::Vector3d::UnitY();\n  Eigen::Matrix<double, 3, 1> measurement;\n  // Set up a scenario where, if we naively took the accelerometer readings, we\n  // would think that we were rotated. But the gyro readings indicate that we\n  // are only rotating about the Y (pitch) axis.\n  measurement << 0.3, 1.0, 0.0;\n  for (int ii = 0; ii < 200; ++ii) {\n    dtukf.Predict({0.0, M_PI_2, 0.0}, measurement,\n                  std::chrono::milliseconds(5));\n  }\n  const Eigen::Quaterniond expected(Eigen::AngleAxis<double>(M_PI_2, uy));\n  EXPECT_TRUE(QuaternionEqual(expected, dtukf.X_hat(), 1e-1))\n      << \"Expected: \" << expected.coeffs()\n      << \" Got: \" << dtukf.X_hat().coeffs();\n  EXPECT_NEAR(\n      0.0,\n      (Eigen::Vector3d(-1.0, 0.0, 0.0) - dtukf.H(dtukf.X_hat().coeffs()))\n          .norm(),\n      1e-10)\n      << dtukf.H(dtukf.X_hat().coeffs());\n}\n\n// Tests that computing sigma points, and then computing the mean and covariance\n// returns the original answer.\nTEST(DownEstimatorTest, SigmaPoints) {\n  const Eigen::Quaternion<double> mean(\n      Eigen::AngleAxis<double>(M_PI / 2.0, Eigen::Vector3d::UnitX()));\n\n  Eigen::Matrix<double, 3, 3> covariance;\n  covariance << 0.4, -0.1, 0.2, -0.1, 0.6, 0.0, 0.2, 0.0, 0.5;\n  covariance *= 0.1;\n\n  const Eigen::Matrix<double, 4, 3 * 2 + 1> vectors =\n      drivetrain::GenerateSigmaPoints(mean, covariance);\n\n  const Eigen::Matrix<double, 4, 1> calculated_mean =\n      frc971::controls::QuaternionMean(vectors);\n\n  VLOG(1) << \"actual mean: \" << mean.coeffs();\n  VLOG(1) << \"calculated mean: \" << calculated_mean;\n\n  Eigen::Matrix<double, 3, 3 * 2 + 1> Wprime;\n  Eigen::Matrix<double, 3, 3> calculated_covariance =\n      drivetrain::ComputeQuaternionCovariance(\n          Eigen::Quaternion<double>(calculated_mean), vectors, &Wprime);\n\n  EXPECT_NEAR(1.0,\n              (mean.conjugate().coeffs() * calculated_mean.transpose()).norm(),\n              1e-4);\n\n  EXPECT_NEAR(0.0, (calculated_covariance - covariance).norm(), 1e-8);\n}\n\n// Tests that computing sigma points with a large covariance that will precisely\n// wrap, that we do clip the perturbations.\nTEST(DownEstimatorTest, ClippedSigmaPoints) {\n  const Eigen::Quaternion<double> mean(\n      Eigen::AngleAxis<double>(M_PI / 2.0, Eigen::Vector3d::UnitX()));\n\n  Eigen::Matrix<double, 3, 3> covariance;\n  covariance << 0.4, -0.1, 0.2, -0.1, 0.6, 0.0, 0.2, 0.0, 0.5;\n  covariance *= 100.0;\n\n  const Eigen::Matrix<double, 4, 3 * 2 + 1> vectors =\n      drivetrain::GenerateSigmaPoints(mean, covariance);\n\n  const Eigen::Matrix<double, 4, 1> calculated_mean =\n      frc971::controls::QuaternionMean(vectors);\n\n  Eigen::Matrix<double, 3, 3 * 2 + 1> Wprime;\n  Eigen::Matrix<double, 3, 3> calculated_covariance =\n      drivetrain::ComputeQuaternionCovariance(\n          Eigen::Quaternion<double>(calculated_mean), vectors, &Wprime);\n\n  EXPECT_NEAR(1.0,\n              (mean.conjugate().coeffs() * calculated_mean.transpose()).norm(),\n              1e-4);\n\n  const double calculated_covariance_norm = calculated_covariance.norm();\n  const double covariance_norm = covariance.norm();\n  EXPECT_LT(calculated_covariance_norm, covariance_norm / 2.0)\n      << \"Calculated covariance should be much smaller than the original \"\n         \"covariance.\";\n}\n\n}  // namespace testing\n}  // namespace control_loops\n}  // namespace frc971\n", "meta": {"hexsha": "8aed6b2b9c085b5d983ce39647389ca89ee33394", "size": 11235, "ext": "cc", "lang": "C++", "max_stars_repo_path": "frc971/control_loops/drivetrain/improved_down_estimator_test.cc", "max_stars_repo_name": "AustinSchuh/971-Robot-Code", "max_stars_repo_head_hexsha": "99abc66fd2d899c0bdab338dc6f57dc5def9be8d", "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": "frc971/control_loops/drivetrain/improved_down_estimator_test.cc", "max_issues_repo_name": "AustinSchuh/971-Robot-Code", "max_issues_repo_head_hexsha": "99abc66fd2d899c0bdab338dc6f57dc5def9be8d", "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": "frc971/control_loops/drivetrain/improved_down_estimator_test.cc", "max_forks_repo_name": "AustinSchuh/971-Robot-Code", "max_forks_repo_head_hexsha": "99abc66fd2d899c0bdab338dc6f57dc5def9be8d", "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.7413793103, "max_line_length": 80, "alphanum_fraction": 0.6540275923, "num_tokens": 3398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5213843621777611}}
{"text": "#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <array>\n#include <vector>\n\n#include \"Box.h\"\n#include \"Exceptions.h\"\n\nTEST(Box, BasicProperties) {\n  cpet::Box b({1.3, 2.4, 2});\n\n  ASSERT_EQ(b.type(), \"box\") << \"Incorrectly describes the volume type\";\n  ASSERT_EQ(b.description(), \"Box: 1.300000 2.400000 2.000000\")\n      << \"Incorrect description and or formatting\";\n\n  EXPECT_DOUBLE_EQ(b.maxDim(), 2.4) << \"Expected maximum dimension \" << 2.4;\n  EXPECT_NEAR(b.diagonal(), 6.76756973, 0.0000001)\n      << \"Diagonal off by expected \" << 6.76756973 << \" by more than tolerance \"\n      << 0.0000001;\n\n  Eigen::Vector3d point{0, 0, 0};\n  EXPECT_TRUE(b.isInside(point)) << \"Origin is not within the box\";\n\n  point = {1.2, -2, 1};\n  EXPECT_TRUE(b.isInside(point))\n      << \"Point \" << point.transpose() << \" not within \" << b.description();\n\n  point = {-1.3, 2.4, 2.1};\n  EXPECT_FALSE(b.isInside(point))\n      << \"Point \" << point.transpose() << \" within \" << b.description();\n\n  for (int i = 0; i < 100; i++) {\n    EXPECT_TRUE(b.isInside(b.randomPoint()));\n  }\n\n  constexpr double STEP_SIZE = 0.001;\n  const double max_distance = b.diagonal() / STEP_SIZE;\n  for (int i = 0; i < 10; i++) {\n    EXPECT_TRUE(b.randomDistance(STEP_SIZE) <= max_distance);\n  }\n}\n\nTEST(Box, Displaced) {\n  cpet::Box b({1, 1, 1}, {0, 1, 0});\n  ASSERT_TRUE(b.isInside({0, 1, 0}));\n  EXPECT_TRUE(b.isInside({0, .5, 0}));\n  EXPECT_FALSE(b.isInside({-0.5, -0.5, -0.5}));\n  EXPECT_TRUE(b.isInside({0.5, 1.5, 0}));\n\n  for (int i = 0; i < 100; i++) {\n    EXPECT_TRUE(b.isInside(b.randomPoint()));\n  }\n  constexpr double STEP_SIZE = 0.001;\n  const double max_distance = b.diagonal() / STEP_SIZE;\n  for (int i = 0; i < 10; i++) {\n    EXPECT_TRUE(b.randomDistance(STEP_SIZE) <= max_distance);\n  }\n}\n\nTEST(Box, Partition) {\n  const std::array<double, 3> sides = {2, 3, 5};\n  const std::array<int, 3> density = {10, 10, 10};\n  const cpet::Box b(sides);\n\n  std::vector<Eigen::Vector3d> expected_partition;\n  double x = -1 * sides[0];\n  while (x <= sides[0]) {\n    double y = -1 * sides[1];\n    while (y <= sides[1]) {\n      double z = -1 * sides[2];\n      while (z <= sides[2]) {\n        expected_partition.emplace_back(x, y, z);\n        z += static_cast<double>(static_cast<float>(sides[2] / density[2]));\n      }\n      y += (sides[1] / density[1]);\n    }\n    x += (sides[0] / density[0]);\n  }\n\n  const auto result = b.partition(density);\n  ASSERT_EQ(result.size(), expected_partition.size());\n  for (size_t i = 0; i < result.size(); i++) {\n    double difference = (result.at(i) - expected_partition.at(i)).norm();\n    EXPECT_NEAR(difference, 0.0, 0.000001);\n  }\n}\n\nTEST(Box, PartitionDisplaced) {\n  const std::array<double, 3> sides = {3, 3, 2};\n  const std::array<int, 3> density = {15, 15, 10};\n  const Eigen::Vector3d center = {1, 0, 1};\n  const cpet::Box b(sides, center);\n\n  std::vector<Eigen::Vector3d> expected_partition;\n  expected_partition.reserve(\n      static_cast<size_t>(abs(density[0] * density[1] * density[2])));\n\n  double x = -1 * sides[0];\n  while (x <= sides[0]) {\n    double y = -1 * sides[1];\n    while (y <= sides[1]) {\n      double z = -1 * sides[2];\n      while (z <= sides[2]) {\n        expected_partition.emplace_back((x + 1), y, (z + 1));\n        z += static_cast<double>(static_cast<float>(sides[2] / density[2]));\n      }\n      y += (sides[1] / density[1]);\n    }\n    x += (sides[0] / density[0]);\n  }\n\n  const auto result = b.partition(density);\n  ASSERT_EQ(result.size(), expected_partition.size());\n  for (size_t i = 0; i < result.size(); i++) {\n    const double difference = (result.at(i) - expected_partition.at(i)).norm();\n    EXPECT_NEAR(difference, 0.0, 0.000001);\n  }\n}\n\nTEST(Box, InvalidParameters) {\n  EXPECT_THROW(cpet::Box({-1.5, 2, 3}), cpet::value_error);\n  EXPECT_THROW(cpet::Box({1.5, -2, 3}), cpet::value_error);\n  EXPECT_THROW(cpet::Box({1.5, 2, -3}), cpet::value_error);\n  EXPECT_THROW(cpet::Box({-1.5, 2, -3}), cpet::value_error);\n}\n", "meta": {"hexsha": "b0b1181d179a7db31c8f4c1f067f0741b46f440b", "size": 3952, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_volume.cpp", "max_stars_repo_name": "santi921/CPET", "max_stars_repo_head_hexsha": "717c8db51578801288332aa6e49ff56e84058027", "max_stars_repo_licenses": ["MIT"], "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_volume.cpp", "max_issues_repo_name": "santi921/CPET", "max_issues_repo_head_hexsha": "717c8db51578801288332aa6e49ff56e84058027", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-25T00:38:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-25T00:38:24.000Z", "max_forks_repo_path": "tests/test_volume.cpp", "max_forks_repo_name": "santi921/CPET", "max_forks_repo_head_hexsha": "717c8db51578801288332aa6e49ff56e84058027", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-15T21:04:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T21:04:34.000Z", "avg_line_length": 31.1181102362, "max_line_length": 80, "alphanum_fraction": 0.6014676113, "num_tokens": 1296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5213334868671825}}
{"text": "#include \"sequence.hpp\"\n#include \"pow2.hpp\"\n#include \"multiply.hpp\"\n#include <boost/hana/integral_constant.hpp>\n#include <array>\n\nusing namespace boost::hana::literals;\n\nstd::array<int, 5> a{{1, 2, 3, 4, 5}};\n\ntemplate <typename UnderlyingExpr>\nstruct add_expr\n{\n    constexpr explicit add_expr(UnderlyingExpr const& expr, unsigned value) :\n        expr{expr}, value{value} {};\n\n    auto operator()(size_t index) const {\n        return expr(index) + value;\n    }\n\n    UnderlyingExpr const& expr;\n    unsigned value;\n};\n\ntemplate <typename UnderlyingExpr>\nauto operator+(multiply_expr<UnderlyingExpr> const& m, unsigned value)\n{\n    return add_expr{m, value};\n}\n\nint main()\n{\n    auto s = sequence(a);\n    auto e = (2 * (s ^ 2_c)) + 1;\n\n    auto x = e(0);\n    return x;\n}\n", "meta": {"hexsha": "139e323cecb245578fc42e0bd8921dc3387cba8a", "size": 771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "4_manual_expression_templates/main5.cpp", "max_stars_repo_name": "rgrover/yap-demos", "max_stars_repo_head_hexsha": "d4e100f9fb835bea2a6505f2ed9b8e87ee1ee928", "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": "4_manual_expression_templates/main5.cpp", "max_issues_repo_name": "rgrover/yap-demos", "max_issues_repo_head_hexsha": "d4e100f9fb835bea2a6505f2ed9b8e87ee1ee928", "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": "4_manual_expression_templates/main5.cpp", "max_forks_repo_name": "rgrover/yap-demos", "max_forks_repo_head_hexsha": "d4e100f9fb835bea2a6505f2ed9b8e87ee1ee928", "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.7692307692, "max_line_length": 77, "alphanum_fraction": 0.6588845655, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338727, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5212340944975518}}
{"text": "#pragma once\n\n#include <iostream>\n#include <complex>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <assert.h>\n#include <memory>\n#include <iomanip>\n#include <fstream>\n\n#include <Eigen/CXX11/Tensor>\n#include <Eigen/MPRealSupport>\n\n#include \"common.hpp\"\n#include \"kernel.hpp\"\n#include \"piecewise_polynomial.hpp\"\n\n#include \"irlib/detail/basis_impl.ipp\"\n\nnamespace irlib {\n\n/**\n * Class representing kernel Ir basis\n */\n    class basis {\n    public:\n        /**\n         * Constructor\n         * @param s  statistics\n         * @param Lambda Lambda\n         * @param sv singular values\n         * @param u_basis piecewise polynomials representing u_l(x)\n         * @param v_basis piecewise polynomials representing v_l(y)\n         */\n        basis(statistics::statistics_type s,\n            double Lambda,\n            const std::vector<mpfr::mpreal> &sv,\n            const std::vector<piecewise_polynomial<mpfr::mpreal, mpfr::mpreal>> &u_basis,\n            const std::vector<piecewise_polynomial<mpfr::mpreal, mpfr::mpreal>> &v_basis,\n            const std::vector<std::vector<mpfr::mpreal>> &u_basis_coeff_l,\n            const std::vector<std::vector<mpfr::mpreal>> &v_basis_coeff_l\n        ) throw(std::runtime_error) {\n            statistics_ = s;\n            Lambda_ = Lambda;\n            sv_ = sv;\n            u_basis_ = u_basis;\n            v_basis_ = v_basis;\n            u_basis_coeff_l_ = u_basis_coeff_l;\n            v_basis_coeff_l_ = v_basis_coeff_l;\n        }\n\n    private:\n        statistics::statistics_type statistics_;\n        double Lambda_;\n        std::vector<mpfr::mpreal> sv_;\n        std::vector<piecewise_polynomial<mpfr::mpreal, mpfr::mpreal>> u_basis_, v_basis_;\n        std::vector<std::vector<mpfr::mpreal>> u_basis_coeff_l_;\n        std::vector<std::vector<mpfr::mpreal>> v_basis_coeff_l_;\n\n        //mutable mp_prec_t default_prec_bak;\n\n        mp_prec_t save_default_prec() const {\n            mp_prec_t default_prec_bak = mpfr::mpreal::get_default_prec();\n            mpfr::mpreal::set_default_prec(get_prec());\n            return default_prec_bak;\n        }\n\n        void restore_default_prec(mp_prec_t prec) const {\n            mpfr::mpreal::set_default_prec(prec);\n        }\n\n    public:\n        /**\n         * Compute the values of the basis functions for a given x.\n         * @param x    x = 2 * tau/beta - 1  (-1 <= x <= 1)\n         * @param val  results\n         */\n        double sl(int l) const throw(std::runtime_error) {\n            assert(l >= 0 && l < dim());\n            python_runtime_check(l >= 0 && l < dim(), \"Index l is out of range.\");\n            return static_cast<double>(sv_[l]);\n        }\n\n        mpfr::mpreal sl_mp(int l) const throw(std::runtime_error) {\n            assert(l >= 0 && l < dim());\n            python_runtime_check(l >= 0 && l < dim(), \"Index l is out of range.\");\n            return sv_[l];\n        }\n\n        double Lambda() const {\n            return Lambda_;\n        }\n\n        /**\n         * @param l  order of basis function\n         * @param x  x on [-1,1]\n         * @return   The value of u_l(x)\n         */\n        double ulx(int l, double x) const throw(std::runtime_error) {\n            assert(x >= -1 && x <= 1);\n            assert(l >= 0 && l < dim());\n            auto bak = save_default_prec();\n\n            //auto val = ulx_mp(l, mpfr::mpreal(x));\n            //auto r = static_cast<double>(val);\n\n            auto r = static_cast<double>(ulx_mp(l, mpfr::mpreal(x)));\n            restore_default_prec(bak);\n            return r;\n        }\n\n        double ulx_derivative(int l, double x, int order) const throw(std::runtime_error) {\n            assert(x >= -1 && x <= 1);\n            assert(l >= 0 && l < dim());\n            auto bak = save_default_prec();\n            auto r = static_cast<double>(ulx_derivative_mp(l, mpfr::mpreal(x), order));\n            restore_default_prec(bak);\n            return r;\n        }\n\n        /**\n         * @param l  order of basis function\n         * @param y  y on [-1,1]\n         * @return   The value of v_l(y)\n         */\n        double vly(int l, double y) const throw(std::runtime_error) {\n            assert(y >= -1 && y <= 1);\n            assert(l >= 0 && l < dim());\n            auto bak = save_default_prec();\n            auto r = static_cast<double>(vly_mp(l, mpfr::mpreal(y)));\n            restore_default_prec(bak);\n            return r;\n        }\n\n        double vly_derivative(int l, double y, int order) const throw(std::runtime_error) {\n            assert(y >= -1 && y <= 1);\n            assert(l >= 0 && l < dim());\n            auto bak = save_default_prec();\n            auto r = static_cast<double>(vly_derivative_mp(l, mpfr::mpreal(y), order));\n            restore_default_prec(bak);\n            return r;\n        }\n\n\n        /**\n         * Direct access to coefficients of u_l(x)\n         */\n        double coeff_ulx(int l, int section, int p) const {\n            assert(l >= 0 && l < dim());\n            return static_cast<double>(u_basis_[l].coefficient(section, p));\n        }\n\n        std::vector<mpreal> coeff_ulx_leg(int l) const {\n            assert(l >= 0 && l < dim());\n            return u_basis_coeff_l_[l];\n        }\n\n        /**\n         * Direct access to coefficients of v_l(y)\n         */\n        double coeff_vly(int l, int section, int p) const {\n            assert(l >= 0 && l < dim());\n            return static_cast<double>(v_basis_[l].coefficient(section, p));\n        }\n\n        std::vector<mpreal> coeff_vly_leg(int l) const {\n          assert(l >= 0 && l < dim());\n          return v_basis_coeff_l_[l];\n        }\n\n        /**\n         * Access to sections\n         */\n        int num_sections_ulx() const {\n            return u_basis_[0].num_sections();\n        }\n\n        int num_sections_vly() const {\n            return v_basis_[0].num_sections();\n        }\n\n        double section_edge_ulx(int i) const {\n            return static_cast<double>(u_basis_[0].section_edge(i));\n        }\n\n        double section_edge_vly(int i) const {\n            return static_cast<double>(v_basis_[0].section_edge(i));\n        }\n\n        int num_local_poly_ulx() const {\n            return u_basis_[0].order() + 1;\n        }\n\n        int num_local_poly_vly() const {\n            return v_basis_[0].order() + 1;\n        }\n\n        /**\n         * This function should not be called outside this library\n         * @param l  order of basis function\n         * @param x  x on [-1,1]\n         * @return   The value of u_l(x)\n         */\n#ifndef SWIG //DO NOT EXPOSE TO PYTHON\n        mpfr::mpreal ulx_mp(int l, const mpfr::mpreal &x) const throw(std::runtime_error) {\n            assert(x >= -1 && x <= 1);\n            assert(l >= 0 && l < dim());\n            python_runtime_check(l >= 0 && l < dim(), \"Index l is out of range.\");\n            python_runtime_check(x >= -1 && x <= 1, \"x must be in [-1,1].\");\n\n            auto bak = save_default_prec();\n\n            mpfr:mpreal r;\n            if (x >= 0) {\n                r = u_basis_[l].compute_value(x);\n            } else {\n                r = u_basis_[l].compute_value(-x) * (l % 2 == 0 ? 1 : -1);\n            }\n\n            restore_default_prec(bak);\n\n\n            return r;\n        }\n\n        mpfr::mpreal ulx_derivative_mp(int l, const mpfr::mpreal &x, int order) const throw(std::runtime_error) {\n            assert(x >= -1 && x <= 1);\n            assert(l >= 0 && l < dim());\n            python_runtime_check(l >= 0 && l < dim(), \"Index l is out of range.\");\n            python_runtime_check(x >= -1 && x <= 1, \"x must be in [-1,1].\");\n\n            auto bak = save_default_prec();\n\n            mpfr::mpreal r;\n            if (x >= 0) {\n                r = u_basis_[l].derivative(x, order);\n            } else {\n                r = u_basis_[l].derivative(-x, order) * ((l+order) % 2 == 0 ? 1 : -1);\n            }\n\n            restore_default_prec(bak);\n\n            return r;\n        }\n\n        /**\n         * This function should not be called outside this library\n         * @param l  order of basis function\n         * @param y  y on [-1,1]\n         * @return   The value of v_l(y)\n         */\n        mpfr::mpreal vly_mp(int l, const mpfr::mpreal &y) const throw(std::runtime_error) {\n            assert(y >= -1 && y <= 1);\n            assert(l >= 0 && l < dim());\n            python_runtime_check(l >= 0 && l < dim(), \"Index l is out of range.\");\n            python_runtime_check(y >= -1 && y <= 1, \"y must be in [-1,1].\");\n\n            auto bak = save_default_prec();\n\n            mpfr::mpreal r;\n            if (y >= 0) {\n                r = v_basis_[l].compute_value(y);\n            } else {\n                r = v_basis_[l].compute_value(-y) * (l % 2 == 0 ? 1 : -1);\n            }\n\n            restore_default_prec(bak);\n\n            return r;\n        }\n\n        mpfr::mpreal vly_derivative_mp(int l, const mpfr::mpreal &y, int order) const throw(std::runtime_error) {\n            assert(y >= -1 && y <= 1);\n            assert(l >= 0 && l < dim());\n            python_runtime_check(l >= 0 && l < dim(), \"Index l is out of range.\");\n            python_runtime_check(y >= -1 && y <= 1, \"y must be in [-1,1].\");\n\n            auto bak = save_default_prec();\n\n            mpfr::mpreal r;\n            if (y >= 0) {\n                r = v_basis_[l].derivative(y, order);\n            } else {\n                r = v_basis_[l].derivative(-y, order) * ((l+order) % 2 == 0 ? 1 : -1);\n            }\n\n            restore_default_prec(bak);\n\n            return r;\n        }\n#endif\n\n        std::string ulx_str(int l, const std::string& str_x) const throw(std::runtime_error) {\n            auto bak = save_default_prec();\n\n            auto prec = u_basis_[l].section_edge(0).get_prec();\n            mpfr::mpreal x(str_x, prec);\n            auto ulx = ulx_mp(l, x);\n\n            std::ostringstream out;\n            out << std::setprecision(mpfr::bits2digits(ulx.get_prec())) << ulx;\n            //std::cout << \"debug ulx_str \" << std::setprecision(20) << str_x << \" \" << x << \" \" << ulx << \" \" << out.str() << std::endl;\n\n            restore_default_prec(bak);\n\n            return out.str();\n        }\n\n        std::string vly_str(int l, const std::string& str_y) const throw(std::runtime_error) {\n            auto bak = save_default_prec();\n\n            auto prec = v_basis_[l].section_edge(0).get_prec();\n            mpfr::mpreal y(str_y, prec);\n            auto vly = vly_mp(l, y);\n\n            std::ostringstream out;\n            out << std::setprecision(mpfr::bits2digits(vly.get_prec())) << vly;\n\n            restore_default_prec(bak);\n\n            return out.str();\n        }\n\n        /**\n         * Return a reference to the l-th basis function\n         * @param l l-th basis function\n         * @return  reference to the l-th basis function\n         */\n        const piecewise_polynomial<mpfr::mpreal, mpfr::mpreal> &ul(int l) const throw(std::runtime_error) {\n            assert(l >= 0 && l < dim());\n            python_runtime_check(l >= 0 && l < dim(), \"Index l is out of range.\");\n            return u_basis_[l];\n        }\n\n        const piecewise_polynomial<mpfr::mpreal, mpfr::mpreal> &vl(int l) const throw(std::runtime_error) {\n            assert(l >= 0 && l < dim());\n            python_runtime_check(l >= 0 && l < dim(), \"Index l is out of range.\");\n            return v_basis_[l];\n        }\n\n        /**\n         * Return number of basis functions\n         * @return  number of basis functions\n         */\n        int dim() const { return u_basis_.size(); }\n\n\n        mpfr_prec_t get_prec() const {\n            return ul(0).section_edge(0).get_prec();\n        }\n\n        /// Return statistics\n        irlib::statistics::statistics_type get_statistics() const {\n            return statistics_;\n        }\n\n        std::string get_statistics_str() const {\n            return statistics_ == statistics::FERMIONIC ? \"F\" : \"B\" ;\n        }\n\n        int get_prec_int() const {\n            return static_cast<int>(ul(0).section_edge(0).get_prec());\n        }\n\n#ifndef SWIG //DO NOT EXPOSE TO PYTHON\n\n        /**\n         * Compute transformation matrix to Matsubara freq.\n         * The computation may take some time. You may store the result somewhere and do not call this routine frequenctly.\n         * @param n_vec  This vector must contain indices of Matsubara freqencies\n         * @param Tnl    Results\n         */\n        void compute_Tnl(\n                const std::vector<long> &n_vec,\n                Eigen::Tensor<std::complex<double>, 2> &Tnl\n        ) const {\n            auto bak = save_default_prec();\n\n            auto trans_to_non_negative = [&](long n) {\n                if (n >= 0) {\n                    return n;\n                } else {\n                    if (statistics_ == irlib::statistics::FERMIONIC) {\n                        return -n - 1;\n                    } else {\n                        return -n;\n                    }\n                }\n            };\n\n            auto nl = dim();\n\n            std::set<long> none_negative_n;\n            for (const auto &n : n_vec) {\n                none_negative_n.insert(trans_to_non_negative(n));\n            }\n\n            Eigen::Tensor<std::complex<double>, 2> Tnl_tmp;\n            compute_transformation_matrix_to_matsubara<mpreal>(\n                    std::vector<long>(none_negative_n.begin(), none_negative_n.end()),\n                    statistics_, u_basis_, Tnl_tmp\n            );\n\n            Tnl = Eigen::Tensor<std::complex<double>, 2>(n_vec.size(), nl);\n            for (int i = 0; i < n_vec.size(); ++i) {\n                auto index_data = std::distance(\n                        none_negative_n.begin(),\n                        none_negative_n.find(trans_to_non_negative(n_vec[i]))\n                );\n                if (n_vec[i] >= 0) {\n                    for (int l = 0; l < nl; ++l) {\n                        Tnl(i, l) = Tnl_tmp(index_data, l);\n                    }\n                } else {\n                    for (int l = 0; l < nl; ++l) {\n                        Tnl(i, l) = std::conj(Tnl_tmp(index_data, l));\n                    }\n                }\n            }\n\n            restore_default_prec(bak);\n        }\n\n#endif\n\n        /**\n         * Compute transformation matrix to Matsubara freq.\n         * The computation may take some time. You may store the result somewhere and do not call this routine frequenctly.\n         * @param n_vec  This vector must contain indices of Matsubara freqencies\n         * @return Results\n         */\n        Eigen::Tensor<std::complex<double>, 2>\n        compute_Tnl(const std::vector<long> &n_vec) const {\n            std::cout << \"Warning: compute_Tnl() is not well tested!\" << std::endl;\n            Eigen::Tensor<std::complex<double>, 2> Tnl;\n            compute_Tnl(n_vec, Tnl);\n            return Tnl;\n        }\n\n        std::complex<double> compute_Tnl_safe(long n, int l) {\n            auto bak = save_default_prec();\n\n            auto o = (statistics_ == irlib::statistics::FERMIONIC ? 2*n+1 : 2*n);\n            if (o >= 0) {\n                auto r = to_dcomplex(\n                        compute_Tnl_impl(u_basis_[l], l%2==0, statistics_, mpfr::const_pi() * 0.5 * o,\n                                        mpfr::digits2bits(get_prec()),\n                                        mpfr::digits2bits(get_prec()))\n                );\n                restore_default_prec(bak);\n                return r;\n            } else {\n                auto r = to_dcomplex(\n                        compute_Tnl_impl(u_basis_[l], l%2==0, statistics_, -mpfr::const_pi() * 0.5 * o,\n                                        mpfr::digits2bits(get_prec()),\n                                        mpfr::digits2bits(get_prec()))\n                );\n                restore_default_prec(bak);\n                return std::conj(r);\n            }\n        }\n\n    };\n\n    inline basis compute_basis(statistics::statistics_type s,\n                        double Lambda,\n                        int max_dim = 1000,\n                        double cutoff = 1e-8,\n                        const std::string& fp_mode=\"mp\",\n                        double r_tol = 1e-8,\n                        long prec = 64,\n                        int n_local_poly = 10,\n                        int num_nodes_gauss_legendre = 24,\n                        bool verbose = true\n        ) throw(std::runtime_error) {\n        std::vector<mpfr::mpreal> sv;\n        std::vector<piecewise_polynomial<mpfr::mpreal, mpfr::mpreal>> u_basis;\n        std::vector<piecewise_polynomial<mpfr::mpreal, mpfr::mpreal>> v_basis;\n        std::vector<std::vector<mpfr::mpreal>> u_basis_coeff_l;\n        std::vector<std::vector<mpfr::mpreal>> v_basis_coeff_l;\n\n        // Increase default precision if needed\n        auto min_prec = std::max(\n                mpfr::digits2bits(std::log10(1/cutoff)+2*std::log10(1/r_tol)),\n                long(64)//At least 19 digits\n        );\n        //min_prec = std::max(min_prec, mpfr::digits2bits(std::log10(1/r_tol))+10);\n        min_prec = std::max(min_prec, prec);\n        if (min_prec > mpfr::mpreal::get_default_prec()) {\n            mpfr::mpreal::set_default_prec(min_prec);\n        }\n        if (verbose) {\n            std::cout << \"Using default precision = \" << min_prec << \" bits.\" << std::endl;\n        }\n\n        if (fp_mode == \"mp\") {\n            if (s == statistics::FERMIONIC) {\n                std::tie(sv, u_basis, v_basis, u_basis_coeff_l, v_basis_coeff_l) = generate_ir_basis_functions<mpfr::mpreal>(\n                        fermionic_kernel<mpfr::mpreal>(Lambda), max_dim, cutoff, verbose, r_tol, n_local_poly, num_nodes_gauss_legendre);\n            } else if (s == statistics::BOSONIC) {\n                std::tie(sv, u_basis, v_basis, u_basis_coeff_l, v_basis_coeff_l) = generate_ir_basis_functions<mpfr::mpreal>(\n                        bosonic_kernel<mpfr::mpreal>(Lambda), max_dim, cutoff, verbose, r_tol, n_local_poly, num_nodes_gauss_legendre);\n            }\n        } else {\n            throw std::runtime_error(\"Unknown fp_mode \" + fp_mode + \". Only 'mp' is supported.\");\n        }\n\n        return basis(s, Lambda, sv, u_basis, v_basis, u_basis_coeff_l, v_basis_coeff_l);\n    }\n\n    inline void savetxt(const std::string& fname, const basis& b) throw(std::runtime_error) {\n        std::ofstream ofs(fname);\n\n        int version = 2;\n        ofs << version << std::endl;\n        ofs << b.get_statistics() << std::endl;\n        ofs << b.Lambda() << std::endl;\n        ofs << b.dim() << std::endl;\n\n        ofs << b.sl_mp(0).get_prec() << std::endl;\n        for (int l=0; l<b.dim(); ++l) {\n            auto sl = b.sl_mp(l);\n            ofs << std::setprecision(mpfr::bits2digits(sl.get_prec())) << sl << std::endl;\n        }\n        for (int l=0; l<b.dim(); ++l) {\n            ofs << b.ul(l);\n        }\n        for (int l=0; l<b.dim(); ++l) {\n            ofs << b.vl(l);\n        }\n        for (int l=0; l<b.dim(); ++l) {\n            auto coeffs = b.coeff_ulx_leg(l);\n            for (int c=0; c<coeffs.size(); ++c) {\n                ofs << coeffs[c] << std::endl;\n            }\n        }\n        for (int l=0; l<b.dim(); ++l) {\n            auto coeffs = b.coeff_vly_leg(l);\n            for (int c=0; c<coeffs.size(); ++c) {\n                ofs << coeffs[c] << std::endl;\n            }\n        }\n    }\n\n    //inline void dump_coeff(std::ofstream& ofs, const std::vector<mpreal>& coeff) {\n      //auto num_sections = b.ul(l).num_sections();\n      //\n    //}\n\n    inline basis loadtxt(const std::string& fname) throw(std::runtime_error) {\n        std::ifstream ifs(fname);\n\n        if (!ifs.is_open()) {\n            throw std::runtime_error(fname + \" cannot be opened!\");\n        }\n\n        statistics::statistics_type s;\n        double Lambda;\n        int dim;\n\n        int version;\n        ifs >> version;\n\n        if (version == 2) {\n            {\n                int itmp;\n                ifs >> itmp;\n                s = static_cast<statistics::statistics_type>(itmp);\n            }\n            ifs >> Lambda;\n            ifs >> dim;\n\n            mpfr_prec_t prec;\n            ifs >> prec;\n            std::vector<mpfr::mpreal> sv(dim);\n            for (int l=0; l<dim; ++l) {\n                sv[l].set_prec(prec);\n                ifs >> sv[l];\n            }\n\n            std::vector<piecewise_polynomial<mpfr::mpreal, mpfr::mpreal>> u_basis(dim), v_basis(dim);\n\n            for (int l=0; l<dim; ++l) {\n                ifs >> u_basis[l];\n            }\n\n            for (int l=0; l<dim; ++l) {\n                ifs >> v_basis[l];\n            }\n\n            std::vector<std::vector<mpreal>> u_basis_coeffs_leg(dim);\n            for (int l = 0; l < dim; ++l) {\n                u_basis_coeffs_leg[l].resize(u_basis[l].num_sections() * (u_basis[l].order()+1));\n                for (int c = 0; c < u_basis_coeffs_leg[l].size(); ++c) {\n                    ifs >> u_basis_coeffs_leg[l][c];\n                }\n            }\n\n            std::vector<std::vector<mpreal>> v_basis_coeffs_leg(dim);\n            for (int l = 0; l < dim; ++l) {\n                v_basis_coeffs_leg[l].resize(v_basis[l].num_sections() * (v_basis[l].order()+1));\n                for (int c = 0; c < v_basis_coeffs_leg[l].size(); ++c) {\n                    ifs >> v_basis_coeffs_leg[l][c];\n                }\n            }\n\n            return basis(s, Lambda, sv, u_basis, v_basis, u_basis_coeffs_leg, v_basis_coeffs_leg);\n        } else {\n            throw std::runtime_error(\"Version \" + std::to_string(version) + \" is not supported!\");\n        }\n    }\n}\n\n", "meta": {"hexsha": "197fee80475526fbee8fa48a1469fcf2ba277a47", "size": 21470, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/include/irlib/basis.hpp", "max_stars_repo_name": "SpM-lab/irlib", "max_stars_repo_head_hexsha": "60be7c5898bdbba7197fc68874dae76551d88d1c", "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++/include/irlib/basis.hpp", "max_issues_repo_name": "SpM-lab/irlib", "max_issues_repo_head_hexsha": "60be7c5898bdbba7197fc68874dae76551d88d1c", "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++/include/irlib/basis.hpp", "max_forks_repo_name": "shinaoka/irlib", "max_forks_repo_head_hexsha": "60be7c5898bdbba7197fc68874dae76551d88d1c", "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": 34.8538961039, "max_line_length": 137, "alphanum_fraction": 0.5009315324, "num_tokens": 5273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5212340812409822}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include <utils/eigen_ext.hpp>\n\nnamespace ipc::rigid {\n\n/// @brief Compute the total mass, center of mass, and moment of intertia\nvoid compute_mass_properties(\n    const Eigen::MatrixXd& vertices,\n    const Eigen::MatrixXi& facets,\n    double& total_mass,\n    VectorMax3d& center_of_mass,\n    MatrixMax3d& moment_of_inertia);\n\n/// @brief Compute the 2D total mass, center of mass, and moment of intertia\nvoid compute_mass_properties_2D(\n    const Eigen::MatrixXd& vertices,\n    const Eigen::MatrixXi& edges,\n    double& mass,\n    VectorMax3d& center,\n    MatrixMax3d& intertia);\n\n/// @brief Compute the 3D total mass, center of mass, and moment of intertia\nvoid compute_mass_properties_3D(\n    const Eigen::MatrixXd& vertices,\n    const Eigen::MatrixXi& faces,\n    double& mass,\n    VectorMax3d& center,\n    MatrixMax3d& intertia);\n\n/// @brief Construct the sparse mass matrix for the given mesh (V, E).\nvoid construct_mass_matrix(\n    const Eigen::MatrixXd& vertices,\n    const Eigen::MatrixXi& facets,\n    Eigen::SparseMatrix<double>& mass_matrix);\n\n/// @brief Computes the total mass for the given mesh\ndouble compute_total_mass(\n    const Eigen::MatrixXd& vertices, const Eigen::MatrixXi& facets);\n/// @brief Computes the total mass from the mass matrix\ndouble compute_total_mass(const Eigen::SparseMatrix<double>& mass_matrix);\n\nVectorMax3d compute_center_of_mass(\n    const Eigen::MatrixXd& vertices, const Eigen::MatrixXi& facets);\nVectorMax3d compute_center_of_mass(\n    const Eigen::MatrixXd& vertices,\n    const Eigen::SparseMatrix<double>& mass_matrix);\n\n/**\n * @brief Computes the moment of intertia\n *\n * Assumes vertices are given in body space (i.e centered of mass at 0,0).\n */\nMatrixMax3d compute_moment_of_inertia(\n    const Eigen::MatrixXd& vertices, const Eigen::MatrixXi& facets);\nMatrixMax3d compute_moment_of_inertia(\n    const Eigen::MatrixXd& vertices,\n    const Eigen::SparseMatrix<double>& mass_matrix);\n\n} // namespace ipc::rigid\n", "meta": {"hexsha": "55ce839300685bea43a68593d74e7c433c41ea9f", "size": 2019, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/physics/mass.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/physics/mass.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/physics/mass.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": 31.546875, "max_line_length": 76, "alphanum_fraction": 0.7424467558, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5211339735123254}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// ConstStrainDisplacement_cli.cc\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//      Generate a constant strain displacement for demonstration purposes.\n//      Given a strain tensor, create a linear displacement field with that\n//      strain. We choose the displacement field with u = 0 at the bounding box\n//      center and with no infinitesimal rigid rotation component.\n//\n//      The no-rigid-rotation constraint makes integrating the strain simple\n//      because it allows us to treat the strain tensor as a Jacobian:\n//      J = 1/2 (J + J') + 1/2 (J - J') = strain + irot\n//      irot = 0 ==> J = strain\n//      This can also be interpreted componentwise: no rotation means, e.g.,\n//      1/2 (u_x,y - u_y,x) = 0       \\   ==> u_x,y = u_y,x = e_xy = e_yx\n//      1/2 (u_x,y + u_y, x) = e_xy   /\n//\n//      If requested, the fluctuation displacement computed by periodic\n//      homogenization can be added in.\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Company:  New York University\n//  Created:  12/04/2014 01:18:22\n////////////////////////////////////////////////////////////////////////////////\n#include <boost/algorithm/string.hpp>\n#include <string>\n#include <vector>\n#include <MeshFEM/Types.hh>\n#include <MeshFEM/SymmetricMatrix.hh>\n#include <MeshFEM/FEMMesh.hh>\n#include <MeshFEM/MeshIO.hh>\n#include <MeshFEM/LinearElasticity.hh>\n#include <MeshFEM/Materials.hh>\n#include <MeshFEM/PeriodicHomogenization.hh>\n#include <MeshFEM/OrthotropicHomogenization.hh>\n#include <MeshFEM/MSHFieldWriter.hh>\n\n#include <boost/program_options.hpp>\n\nnamespace po = boost::program_options;\nusing namespace std;\nusing namespace PeriodicHomogenization;\n\n[[ noreturn ]] void usage(int exitVal, const po::options_description &visible_opts) {\n    cout << \"Usage: ConstStrainDisplacement_cli [options] in.msh -s 'e_00 e_11 ...' out.msh\" << endl;\n    cout << visible_opts << endl;\n    exit(exitVal);\n}\n\npo::variables_map parseCmdLine(int argc, const char *argv[])\n{\n    po::options_description hidden_opts(\"Hidden Arguments\");\n    hidden_opts.add_options()\n        (\"mesh\", po::value<string>(), \"input mesh\")\n        (\"outMesh\", po::value<string>(), \"output mesh\")\n        ;\n    po::positional_options_description p;\n    p.add(\"mesh\",    1);\n    p.add(\"outMesh\", 1);\n\n    po::options_description visible_opts;\n    visible_opts.add_options()(\"help\", \"Produce this help message\")\n        (\"material,m\", po::value<string>(), \"base material\")\n        (\"strain,s\", po::value<string>(), \"macroscopic strain tensor\")\n        (\"stress,S\", po::value<string>(), \"macroscopic stress tensor\")\n        (\"degree,d\",   po::value<int>()->default_value(2), \"degree of finite elements\")\n        (\"nodalLoad,l\",                     \"compute the effective force on each node.\")\n        (\"addFluctuation,f\",                \"add fluctuation strains to the displacement\")\n        (\"macroOut\", po::value<string>(),   \"also output the unit cell deformation\")\n        (\"manualPeriodicVertices\", po::value<string>(), \"Manually specify identified periodic vertices using a hacky file format (see PeriodicCondition constructor)\")\n        (\"orthotropicCell,O\",               \"Analyze the orthotropic symmetry base cell only\")\n        ;\n\n    po::options_description cli_opts;\n    cli_opts.add(visible_opts).add(hidden_opts);\n\n    po::variables_map vm;\n    try {\n        po::store(po::command_line_parser(argc, argv).\n                  options(cli_opts).positional(p).run(), vm);\n        po::notify(vm);\n    }\n    catch (std::exception &e) {\n        cout << \"Error: \" << e.what() << endl << endl;\n        usage(1, visible_opts);\n    }\n\n    bool fail = false;\n    if (vm.count(\"outMesh\") == 0) {\n        cout << \"Error: must specify input and output mesh\" << endl;\n        fail = true;\n    }\n\n    if (vm.count(\"strain\") + vm.count(\"stress\") != 1) {\n        cout << \"Error: must specify macro strain or stress tensor\" << endl;\n        fail = true;\n    }\n\n    if (fail || vm.count(\"help\"))\n        usage(fail, visible_opts);\n\n    return vm;\n}\n\ntemplate<size_t _N>\nusing HMG = LinearElasticity::HomogenousMaterialGetter<Materials::Constant>::template Getter<_N>;\n\ntemplate<size_t _N, size_t _FEMDegree>\nvoid execute(const po::variables_map &args,\n             const vector<MeshIO::IOVertex> &inVertices,\n             const vector<MeshIO::IOElement> &inElements)\n{\n    auto &mat = HMG<_N>::material;\n    if (args.count(\"material\")) mat.setFromFile(args[\"material\"].as<string>());\n    typedef LinearElasticity::Mesh<_N, _FEMDegree, HMG> Mesh;\n    typedef LinearElasticity::Simulator<Mesh> Simulator;\n    typedef typename Simulator::VField VField;\n    Simulator sim(inElements, inVertices);\n    const auto &mesh = sim.mesh();\n    MSHFieldWriter writer(args[\"outMesh\"].as<string>(), mesh);\n\n\n    // Parse strain/stress tensor.\n    vector<string> probeComponents;\n    string probeString = args.count(\"strain\") ? args[\"strain\"].as<string>() : args[\"stress\"].as<string>();\n    boost::trim(probeString);\n    boost::split(probeComponents, probeString, boost::is_any_of(\"\\t \"),\n                 boost::token_compress_on);\n    if (probeComponents.size() != flatLen(_N))\n        throw runtime_error(\"Invalid strain tensor\");\n\n    SymmetricMatrixValue<Real, _N> strain;\n    // Actually a stress for the macro stress case!\n    for (size_t i = 0; i < probeComponents.size(); ++i)\n        strain[i] = stod(probeComponents[i]);\n\n    // Convert stress probe to corresponding strain probe.\n    std::vector<VField> w_ij;\n\n    std::unique_ptr<PeriodicCondition<_N>> pc;\n    if (args.count(\"manualPeriodicVertices\"))\n        pc = Future::make_unique<PeriodicCondition<_N>>(sim.mesh(), args[\"manualPeriodicVertices\"].as<string>());\n\n    auto doCellProblemSolve = [&]() {\n        if (args.count(\"orthotropicCell\") == 0)   solveCellProblems(w_ij, sim, 1e-7, false, std::move(pc));\n        else PeriodicHomogenization::Orthotropic::solveCellProblems(w_ij, sim, 1e-7);\n    };\n\n    auto getHomogenizedTensor = [&]() {\n        if (args.count(\"orthotropicCell\") == 0)   return homogenizedElasticityTensorDisplacementForm(w_ij, sim);\n        else return PeriodicHomogenization::Orthotropic::homogenizedElasticityTensorDisplacementForm(w_ij, sim);\n    };\n\n    if (args.count(\"stress\")) {\n        doCellProblemSolve();\n        auto Eh = getHomogenizedTensor();\n        auto Sh = Eh.inverse();\n        strain = Sh.doubleContract(strain);\n    }\n\n    auto bbox = mesh.boundingBox();\n    VectorND<_N> center = bbox.center();\n\n    if (args.count(\"macroOut\")) {\n        if (_N != 2) throw std::runtime_error(\"macro displacement output currently only supported in 2D\");\n\n        std::vector<MeshIO::IOVertex> squareVertices;\n        std::vector<MeshIO::IOElement> squareElems;\n\n        VField uMacro(4);\n        SymmetricMatrixField<Real, _N> stressMacro(2);\n\n        if (w_ij.size() == 0) doCellProblemSolve();\n        auto Eh = getHomogenizedTensor();\n        stressMacro(0) = stressMacro(1) = Eh.doubleContract(strain);\n\n        // 2   3\n        // 0   1\n        size_t i = 0;\n        for (Real y : {bbox.minCorner[1], bbox.maxCorner[1]}) {\n            for (Real x : {bbox.minCorner[0], bbox.maxCorner[0]}) {\n                VectorND<_N> p;\n                p.setZero(), p[0] = x, p[1] = y;\n                squareVertices.emplace_back(p);\n                uMacro(i++) = strain.contract(p - center);\n            }\n        }\n\n        squareElems.emplace_back(0, 1, 3);\n        squareElems.emplace_back(0, 3, 2);\n\n        MSHFieldWriter mwriter(args[\"macroOut\"].as<string>(), squareVertices, squareElems);\n        mwriter.addField(\"u_cstrain\", uMacro, DomainType::PER_NODE);\n        mwriter.addField(\"stress\", stressMacro, DomainType::PER_ELEMENT);\n    }\n\n    VField cstrainDisp(mesh.numNodes());\n    for (auto n : mesh.nodes())\n        cstrainDisp(n.index()) = strain.contract(n->p - center);\n\n    if (args.count(\"addFluctuation\")) {\n        if (w_ij.size() == 0) doCellProblemSolve();\n        // Remove rigid translation of fluctuation displacements relative to the\n        // base cell (i.e. try to keep the fluctuation-displaced microstructure\n        // \"within\" the base cell):\n        // The no-rigid-motion constraint on fluctuation displacements\n        // ensures the microstructure's center of mass doesn't move, but\n        // this is not what we need. Instead, we need to ensure vertices on\n        // periodic boundary do not move off the boundary. We enforce this in an\n        // average sense for each cell face by translating so that the\n        // corresponding displacement component's average over all vertices on\n        // the face is zero.\n        for (size_t i = 0; i < w_ij.size(); ++i) {\n            VField &w = w_ij[i];\n            VectorND<_N> translation(VectorND<_N>::Zero());\n            vector<int> numAveraged(_N);\n\n            for (size_t bni = 0; bni < mesh.numBoundaryNodes(); ++bni) {\n                auto n = mesh.boundaryNode(bni).volumeNode();\n                for (size_t d = 0; d < _N; ++d) {\n                    if (std::abs(n->p[d] - bbox.minCorner[d]) < 1e-9) {\n                        translation[d] += w(n.index())[d];\n                        ++numAveraged[d];\n                    }\n                }\n            }\n            for (size_t d = 0; d < _N; ++d)\n                translation[d] /= numAveraged[d];\n            for (size_t n = 0; n < w.domainSize(); ++n)\n                w(n) -= translation;\n        }\n\n        for (size_t i = 0; i < w_ij.size(); ++i) {\n            VField tmp(w_ij[i]);\n            tmp *= (((i < _N) ? 1.0 : 2.0) * strain[i]);\n            cstrainDisp += tmp;\n\n            writer.addField(\"w_ij \" + to_string(i), w_ij[i], DomainType::PER_NODE);\n            // auto strain = sim.averageStrainField(w_ij[i]);\n            // writer.addField(\"strain w_ij \" + to_string(i), strain, DomainType::PER_ELEMENT);\n\n            // ScalarField<Real> comp(strain.domainSize());\n            // for (size_t c = 0; c < flatLen(_N); ++c) {\n            //     for (size_t ei = 0; ei < strain.domainSize(); ++ei)\n            //         comp(ei) = strain(ei)[c];\n            //     writer.addField(\"strain w_ij \" + to_string(i) + \" comp \" + to_string(c), comp, DomainType::PER_ELEMENT);\n            // }\n        }\n    }\n\n    writer.addField(\"u_cstrain\", cstrainDisp, DomainType::PER_NODE);\n    if (args.count(\"nodalLoad\"))\n        writer.addField(\"f_cstrain\", sim.applyStiffnessMatrix(cstrainDisp), DomainType::PER_NODE);\n\n    writer.addField(\"stress\", sim.averageStressField(cstrainDisp), DomainType::PER_ELEMENT);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/*! Program entry point\n//  @param[in]  argc    Number of arguments\n//  @param[in]  argv    Argument strings\n//  @return     status  (0 on success)\n*///////////////////////////////////////////////////////////////////////////////\nint main(int argc, const char *argv[])\n{\n    po::variables_map args = parseCmdLine(argc, argv);\n\n    vector<MeshIO::IOVertex>  inVertices;\n    vector<MeshIO::IOElement> inElements;\n    auto type = load(args[\"mesh\"].as<string>(), inVertices, inElements,\n            MeshIO::FMT_GUESS, MeshIO::MESH_GUESS);\n\n    // Infer dimension from mesh type.\n    size_t dim;\n    if      (type == MeshIO::MESH_TET) dim = 3;\n    else if (type == MeshIO::MESH_TRI) dim = 2;\n    else    throw std::runtime_error(\"Mesh must be triangle or tet.\");\n\n    // Look up and run appropriate instantiation.\n    int deg = args[\"degree\"].as<int>();\n    auto exec = (dim == 3) ? ((deg == 2) ? execute<3, 2> : execute<3, 1>)\n                           : ((deg == 2) ? execute<2, 2> : execute<2, 1>);\n    exec(args, inVertices, inElements);\n    return 0;\n}\n", "meta": {"hexsha": "30d14d378d62804af042cad8841669aa6f5cad10", "size": 11775, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/bin/ConstStrainDisplacement_cli.cc", "max_stars_repo_name": "pbedenbaugh/MeshFEM", "max_stars_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T10:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:41:50.000Z", "max_issues_repo_path": "src/bin/ConstStrainDisplacement_cli.cc", "max_issues_repo_name": "pbedenbaugh/MeshFEM", "max_issues_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-01T15:58:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:31:09.000Z", "max_forks_repo_path": "src/bin/ConstStrainDisplacement_cli.cc", "max_forks_repo_name": "pbedenbaugh/MeshFEM", "max_forks_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T09:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T03:02:39.000Z", "avg_line_length": 41.1713286713, "max_line_length": 166, "alphanum_fraction": 0.5918471338, "num_tokens": 2972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5211339612357087}}
{"text": "// test_negative_binomial.cpp\r\n\r\n// Copyright Paul A. Bristow 2007.\r\n// Copyright John Maddock 2006.\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// Tests for Negative Binomial Distribution.\r\n\r\n// Note that these defines must be placed BEFORE #includes.\r\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\r\n// because several tests overflow & underflow by design.\r\n#define BOOST_MATH_DISCRETE_QUANTILE_POLICY real\r\n\r\n#ifdef _MSC_VER\r\n#  pragma warning(disable: 4127) // conditional expression is constant.\r\n#endif\r\n\r\n#if !defined(TEST_FLOAT) && !defined(TEST_DOUBLE) && !defined(TEST_LDOUBLE) && !defined(TEST_REAL_CONCEPT)\r\n#  define TEST_FLOAT\r\n#  define TEST_DOUBLE\r\n#  define TEST_LDOUBLE\r\n#  define TEST_REAL_CONCEPT\r\n#endif\r\n\r\n#include <boost/math/tools/test.hpp> // for real_concept\r\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\r\nusing ::boost::math::concepts::real_concept;\r\n\r\n#include <boost/math/distributions/negative_binomial.hpp> // for negative_binomial_distribution\r\nusing boost::math::negative_binomial_distribution;\r\n\r\n#include <boost/math/special_functions/gamma.hpp>\r\n  using boost::math::lgamma;  // log gamma\r\n\r\n#define BOOST_TEST_MAIN\r\n#include <boost/test/unit_test.hpp> // for test_main\r\n#include <boost/test/floating_point_comparison.hpp> // for BOOST_CHECK_CLOSE\r\n#include \"table_type.hpp\"\r\n#include \"test_out_of_range.hpp\"\r\n\r\n#include <iostream>\r\nusing std::cout;\r\nusing std::endl;\r\nusing std::setprecision;\r\nusing std::showpoint;\r\n#include <limits>\r\nusing std::numeric_limits;\r\n\r\ntemplate <class RealType>\r\nvoid test_spot( // Test a single spot value against 'known good' values.\r\n               RealType N,    // Number of successes.\r\n               RealType k,    // Number of failures.\r\n               RealType p,    // Probability of success_fraction.\r\n               RealType P,    // CDF probability.\r\n               RealType Q,    // Complement of CDF.\r\n               RealType tol)  // Test tolerance.\r\n{\r\n   boost::math::negative_binomial_distribution<RealType> bn(N, p);\r\n   BOOST_CHECK_EQUAL(N, bn.successes());\r\n   BOOST_CHECK_EQUAL(p, bn.success_fraction());\r\n   BOOST_CHECK_CLOSE(\r\n     cdf(bn, k), P, tol);\r\n\r\n  if((P < 0.99) && (Q < 0.99))\r\n  {\r\n    // We can only check this if P is not too close to 1,\r\n    // so that we can guarantee that Q is free of error:\r\n    //\r\n    BOOST_CHECK_CLOSE(\r\n      cdf(complement(bn, k)), Q, tol);\r\n    if(k != 0)\r\n    {\r\n      BOOST_CHECK_CLOSE(\r\n        quantile(bn, P), k, tol);\r\n    }\r\n    else\r\n    {\r\n      // Just check quantile is very small:\r\n      if((std::numeric_limits<RealType>::max_exponent <= std::numeric_limits<double>::max_exponent)\r\n        && (boost::is_floating_point<RealType>::value))\r\n      {\r\n        // Limit where this is checked: if exponent range is very large we may\r\n        // run out of iterations in our root finding algorithm.\r\n        BOOST_CHECK(quantile(bn, P) < boost::math::tools::epsilon<RealType>() * 10);\r\n      }\r\n    }\r\n    if(k != 0)\r\n    {\r\n      BOOST_CHECK_CLOSE(\r\n        quantile(complement(bn, Q)), k, tol);\r\n    }\r\n    else\r\n    {\r\n      // Just check quantile is very small:\r\n      if((std::numeric_limits<RealType>::max_exponent <= std::numeric_limits<double>::max_exponent)\r\n        && (boost::is_floating_point<RealType>::value))\r\n      {\r\n        // Limit where this is checked: if exponent range is very large we may\r\n        // run out of iterations in our root finding algorithm.\r\n        BOOST_CHECK(quantile(complement(bn, Q)) < boost::math::tools::epsilon<RealType>() * 10);\r\n      }\r\n    }\r\n    // estimate success ratio:\r\n    BOOST_CHECK_CLOSE(\r\n      negative_binomial_distribution<RealType>::find_lower_bound_on_p(\r\n      N+k, N, P),\r\n      p, tol);\r\n    // Note we bump up the sample size here, purely for the sake of the test,\r\n    // internally the function has to adjust the sample size so that we get\r\n    // the right upper bound, our test undoes this, so we can verify the result.\r\n    BOOST_CHECK_CLOSE(\r\n      negative_binomial_distribution<RealType>::find_upper_bound_on_p(\r\n      N+k+1, N, Q),\r\n      p, tol);\r\n\r\n    if(Q < P)\r\n    {\r\n       //\r\n       // We check two things here, that the upper and lower bounds\r\n       // are the right way around, and that they do actually bracket\r\n       // the naive estimate of p = successes / (sample size)\r\n       //\r\n      BOOST_CHECK(\r\n        negative_binomial_distribution<RealType>::find_lower_bound_on_p(\r\n        N+k, N, Q)\r\n        <=\r\n        negative_binomial_distribution<RealType>::find_upper_bound_on_p(\r\n        N+k, N, Q)\r\n        );\r\n      BOOST_CHECK(\r\n        negative_binomial_distribution<RealType>::find_lower_bound_on_p(\r\n        N+k, N, Q)\r\n        <=\r\n        N / (N+k)\r\n        );\r\n      BOOST_CHECK(\r\n        N / (N+k)\r\n        <=\r\n        negative_binomial_distribution<RealType>::find_upper_bound_on_p(\r\n        N+k, N, Q)\r\n        );\r\n    }\r\n    else\r\n    {\r\n       // As above but when P is small.\r\n      BOOST_CHECK(\r\n        negative_binomial_distribution<RealType>::find_lower_bound_on_p(\r\n        N+k, N, P)\r\n        <=\r\n        negative_binomial_distribution<RealType>::find_upper_bound_on_p(\r\n        N+k, N, P)\r\n        );\r\n      BOOST_CHECK(\r\n        negative_binomial_distribution<RealType>::find_lower_bound_on_p(\r\n        N+k, N, P)\r\n        <=\r\n        N / (N+k)\r\n        );\r\n      BOOST_CHECK(\r\n        N / (N+k)\r\n        <=\r\n        negative_binomial_distribution<RealType>::find_upper_bound_on_p(\r\n        N+k, N, P)\r\n        );\r\n    }\r\n\r\n    // Estimate sample size:\r\n    BOOST_CHECK_CLOSE(\r\n      negative_binomial_distribution<RealType>::find_minimum_number_of_trials(\r\n      k, p, P),\r\n      N+k, tol);\r\n    BOOST_CHECK_CLOSE(\r\n      negative_binomial_distribution<RealType>::find_maximum_number_of_trials(\r\n         k, p, Q),\r\n      N+k, tol);\r\n\r\n    // Double check consistency of CDF and PDF by computing the finite sum:\r\n    RealType sum = 0;\r\n    for(unsigned i = 0; i <= k; ++i)\r\n    {\r\n      sum += pdf(bn, RealType(i));\r\n    }\r\n    BOOST_CHECK_CLOSE(sum, P, tol);\r\n\r\n    // Complement is not possible since sum is to infinity.\r\n  } //\r\n} // test_spot\r\n\r\ntemplate <class RealType> // Any floating-point type RealType.\r\nvoid test_spots(RealType)\r\n{\r\n  // Basic sanity checks, test data is to double precision only\r\n  // so set tolerance to 1000 eps expressed as a percent, or\r\n  // 1000 eps of type double expressed as a percent, whichever\r\n  // is the larger.\r\n\r\n  RealType tolerance = (std::max)\r\n    (boost::math::tools::epsilon<RealType>(),\r\n    static_cast<RealType>(std::numeric_limits<double>::epsilon()));\r\n  tolerance *= 100 * 100000.0f;\r\n\r\n  cout << \"Tolerance = \" << tolerance << \"%.\" << endl;\r\n\r\n  RealType tol1eps = boost::math::tools::epsilon<RealType>() * 2; // Very tight, suit exact values.\r\n  //RealType tol2eps = boost::math::tools::epsilon<RealType>() * 2; // Tight, suit exact values.\r\n  RealType tol5eps = boost::math::tools::epsilon<RealType>() * 5; // Wider 5 epsilon.\r\n  cout << \"Tolerance 5 eps = \" << tol5eps << \"%.\" << endl;\r\n\r\n  // Sources of spot test values:\r\n\r\n  // MathCAD defines pbinom(k, r, p) (at about 64-bit double precision, about 16 decimal digits)\r\n  // returns pr(X , k) when random variable X has the binomial distribution with parameters r and p.\r\n  // 0 <= k\r\n  // r > 0\r\n  // 0 <= p <= 1\r\n  // P = pbinom(30, 500, 0.05) = 0.869147702104609\r\n\r\n  // And functions.wolfram.com\r\n\r\n  using boost::math::negative_binomial_distribution;\r\n  using  ::boost::math::negative_binomial;\r\n  using  ::boost::math::cdf;\r\n  using  ::boost::math::pdf;\r\n\r\n  // Test negative binomial using cdf spot values from MathCAD cdf = pnbinom(k, r, p).\r\n  // These test quantiles and complements as well.\r\n\r\n  test_spot(  // pnbinom(1,2,0.5) = 0.5\r\n  static_cast<RealType>(2),   // successes r\r\n  static_cast<RealType>(1),   // Number of failures, k\r\n  static_cast<RealType>(0.5), // Probability of success as fraction, p\r\n  static_cast<RealType>(0.5), // Probability of result (CDF), P\r\n  static_cast<RealType>(0.5),  // complement CCDF Q = 1 - P\r\n  tolerance);\r\n\r\n  test_spot( // pbinom(0, 2, 0.25)\r\n  static_cast<RealType>(2),    // successes r\r\n  static_cast<RealType>(0),    // Number of failures, k\r\n  static_cast<RealType>(0.25),\r\n  static_cast<RealType>(0.0625),                    // Probability of result (CDF), P\r\n  static_cast<RealType>(0.9375),                    // Q = 1 - P\r\n  tolerance);\r\n\r\n  test_spot(  // pbinom(48,8,0.25)\r\n  static_cast<RealType>(8),     // successes r\r\n  static_cast<RealType>(48),    // Number of failures, k\r\n  static_cast<RealType>(0.25),                    // Probability of success, p\r\n  static_cast<RealType>(9.826582228110670E-1),     // Probability of result (CDF), P\r\n  static_cast<RealType>(1 - 9.826582228110670E-1),   // Q = 1 - P\r\n  tolerance);\r\n\r\n  test_spot(  // pbinom(2,5,0.4)\r\n  static_cast<RealType>(5),     // successes r\r\n  static_cast<RealType>(2),     // Number of failures, k\r\n  static_cast<RealType>(0.4),                    // Probability of success, p\r\n  static_cast<RealType>(9.625600000000020E-2),     // Probability of result (CDF), P\r\n  static_cast<RealType>(1 - 9.625600000000020E-2),   // Q = 1 - P\r\n  tolerance);\r\n\r\n  test_spot(  // pbinom(10,100,0.9)\r\n  static_cast<RealType>(100),     // successes r\r\n  static_cast<RealType>(10),     // Number of failures, k\r\n  static_cast<RealType>(0.9),                    // Probability of success, p\r\n  static_cast<RealType>(4.535522887695670E-1),     // Probability of result (CDF), P\r\n  static_cast<RealType>(1 - 4.535522887695670E-1),   // Q = 1 - P\r\n  tolerance);\r\n\r\n  test_spot(  // pbinom(1,100,0.991)\r\n  static_cast<RealType>(100),     // successes r\r\n  static_cast<RealType>(1),     // Number of failures, k\r\n  static_cast<RealType>(0.991),                    // Probability of success, p\r\n  static_cast<RealType>(7.693413044217000E-1),     // Probability of result (CDF), P\r\n  static_cast<RealType>(1 - 7.693413044217000E-1),   // Q = 1 - P\r\n  tolerance);\r\n\r\n  test_spot(  // pbinom(10,100,0.991)\r\n  static_cast<RealType>(100),     // successes r\r\n  static_cast<RealType>(10),     // Number of failures, k\r\n  static_cast<RealType>(0.991),                    // Probability of success, p\r\n  static_cast<RealType>(9.999999940939000E-1),     // Probability of result (CDF), P\r\n  static_cast<RealType>(1 - 9.999999940939000E-1),   // Q = 1 - P\r\n  tolerance);\r\n\r\nif(std::numeric_limits<RealType>::is_specialized)\r\n{ // An extreme value test that takes 3 minutes using the real concept type\r\n  // for which numeric_limits<RealType>::is_specialized == false, deliberately\r\n  // and for which there is no Lanczos approximation defined (also deliberately)\r\n  // giving a very slow computation, but with acceptable accuracy.\r\n  // A possible enhancement might be to use a normal approximation for\r\n  // extreme values, but this is not implemented.\r\n  test_spot(  // pbinom(100000,100,0.001)\r\n  static_cast<RealType>(100),     // successes r\r\n  static_cast<RealType>(100000),     // Number of failures, k\r\n  static_cast<RealType>(0.001),                    // Probability of success, p\r\n  static_cast<RealType>(5.173047534260320E-1),     // Probability of result (CDF), P\r\n  static_cast<RealType>(1 - 5.173047534260320E-1),   // Q = 1 - P\r\n  tolerance*1000); // *1000 is OK 0.51730475350664229  versus\r\n\r\n  // functions.wolfram.com\r\n  //   for I[0.001](100, 100000+1) gives:\r\n  // Wolfram       0.517304753506834882009032744488738352004003696396461766326713\r\n  // JM nonLanczos 0.51730475350664229 differs at the 13th decimal digit.\r\n  // MathCAD       0.51730475342603199 differs at 10th decimal digit.\r\n\r\n  // Error tests:\r\n  check_out_of_range<negative_binomial_distribution<RealType> >(20, 0.5);\r\n  BOOST_MATH_CHECK_THROW(negative_binomial_distribution<RealType>(0, 0.5), std::domain_error);\r\n  BOOST_MATH_CHECK_THROW(negative_binomial_distribution<RealType>(-2, 0.5), std::domain_error);\r\n  BOOST_MATH_CHECK_THROW(negative_binomial_distribution<RealType>(20, -0.5), std::domain_error);\r\n  BOOST_MATH_CHECK_THROW(negative_binomial_distribution<RealType>(20, 1.5), std::domain_error);\r\n}\r\n // End of single spot tests using RealType\r\n\r\n\r\n  // Tests on PDF:\r\n  BOOST_CHECK_CLOSE(\r\n  pdf(negative_binomial_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(0.5)),\r\n  static_cast<RealType>(0) ),  // k = 0.\r\n  static_cast<RealType>(0.25), // 0\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE(\r\n  pdf(negative_binomial_distribution<RealType>(static_cast<RealType>(4), static_cast<RealType>(0.5)),\r\n  static_cast<RealType>(0)),  // k = 0.\r\n  static_cast<RealType>(0.0625), // exact 1/16\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE(\r\n  pdf(negative_binomial_distribution<RealType>(static_cast<RealType>(20), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(0)),  // k = 0\r\n  static_cast<RealType>(9.094947017729270E-13), // pbinom(0,20,0.25) = 9.094947017729270E-13\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE(\r\n  pdf(negative_binomial_distribution<RealType>(static_cast<RealType>(20), static_cast<RealType>(0.2)),\r\n  static_cast<RealType>(0)),  // k = 0\r\n  static_cast<RealType>(1.0485760000000003e-014), // MathCAD 1.048576000000000E-14\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE(\r\n  pdf(negative_binomial_distribution<RealType>(static_cast<RealType>(10), static_cast<RealType>(0.1)),\r\n  static_cast<RealType>(0)),  // k = 0.\r\n  static_cast<RealType>(1e-10), // MathCAD says zero, but suffers cancellation error?\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE(\r\n  pdf(negative_binomial_distribution<RealType>(static_cast<RealType>(20), static_cast<RealType>(0.1)),\r\n  static_cast<RealType>(0)),  // k = 0.\r\n  static_cast<RealType>(1e-20), // MathCAD says zero, but suffers cancellation error?\r\n  tolerance);\r\n\r\n\r\n  BOOST_CHECK_CLOSE( // .\r\n  pdf(negative_binomial_distribution<RealType>(static_cast<RealType>(20), static_cast<RealType>(0.9)),\r\n  static_cast<RealType>(0)),  // k.\r\n  static_cast<RealType>(1.215766545905690E-1), // k=20  p = 0.9\r\n  tolerance);\r\n\r\n  // Tests on cdf:\r\n  // MathCAD pbinom k, r, p) == failures, successes, probability.\r\n\r\n  BOOST_CHECK_CLOSE(cdf(\r\n    negative_binomial_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(0.5)), // successes = 2,prob 0.25\r\n    static_cast<RealType>(0) ), // k = 0\r\n    static_cast<RealType>(0.25), // probability 1/4\r\n    tolerance);\r\n\r\n  BOOST_CHECK_CLOSE(cdf(complement(\r\n    negative_binomial_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(0.5)), // successes = 2,prob 0.25\r\n    static_cast<RealType>(0) )), // k = 0\r\n    static_cast<RealType>(0.75), // probability 3/4\r\n    tolerance);\r\n  BOOST_CHECK_CLOSE( // k = 1.\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(20), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(1)),  // k =1.\r\n  static_cast<RealType>(1.455191522836700E-11),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_SMALL( // Check within an epsilon with CHECK_SMALL\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(20), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(1)) -\r\n  static_cast<RealType>(1.455191522836700E-11),\r\n  tolerance );\r\n\r\n  // Some exact (probably - judging by trailing zeros) values.\r\n  BOOST_CHECK_CLOSE(\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(0)),  // k.\r\n  static_cast<RealType>(1.525878906250000E-5),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE(\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(0)),  // k.\r\n  static_cast<RealType>(1.525878906250000E-5),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_SMALL(\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(0)) -\r\n  static_cast<RealType>(1.525878906250000E-5),\r\n  tolerance );\r\n\r\n  BOOST_CHECK_CLOSE( // k = 1.\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(1)),  // k.\r\n  static_cast<RealType>(1.068115234375010E-4),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE( // k = 2.\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(2)),  // k.\r\n  static_cast<RealType>(4.158020019531300E-4),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE( // k = 3.\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(3)),  // k.bristow\r\n  static_cast<RealType>(1.188278198242200E-3),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE( // k = 4.\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(4)),  // k.\r\n  static_cast<RealType>(2.781510353088410E-3),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE( // k = 5.\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(5)),  // k.\r\n  static_cast<RealType>(5.649328231811500E-3),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE( // k = 6.\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(6)),  // k.\r\n  static_cast<RealType>(1.030953228473680E-2),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE( // k = 7.\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(7)),  // k.\r\n  static_cast<RealType>(1.729983836412430E-2),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE( // k = 8.\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(8)),  // k = n.\r\n  static_cast<RealType>(2.712995628826370E-2),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE( //\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(48)),  // k\r\n  static_cast<RealType>(9.826582228110670E-1),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE( //\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(64)),  // k\r\n  static_cast<RealType>(9.990295004935590E-1),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE( //\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(5), static_cast<RealType>(0.4)),\r\n  static_cast<RealType>(26)),  // k\r\n  static_cast<RealType>(9.989686246611190E-1),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE( //\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(5), static_cast<RealType>(0.4)),\r\n  static_cast<RealType>(2)),  // k failures\r\n  static_cast<RealType>(9.625600000000020E-2),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE( //\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(50), static_cast<RealType>(0.9)),\r\n  static_cast<RealType>(20)),  // k\r\n  static_cast<RealType>(9.999970854144170E-1),\r\n  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE( //\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(500), static_cast<RealType>(0.7)),\r\n  static_cast<RealType>(200)),  // k\r\n  static_cast<RealType>(2.172846379930550E-1),\r\n  tolerance* 2);\r\n\r\n  BOOST_CHECK_CLOSE( //\r\n  cdf(negative_binomial_distribution<RealType>(static_cast<RealType>(50), static_cast<RealType>(0.7)),\r\n  static_cast<RealType>(20)),  // k\r\n  static_cast<RealType>(4.550203671301790E-1),\r\n  tolerance);\r\n\r\n  // Tests of other functions, mean and other moments ...\r\n\r\n  negative_binomial_distribution<RealType> dist(static_cast<RealType>(8), static_cast<RealType>(0.25));\r\n  using namespace std; // ADL of std names.\r\n  // mean:\r\n  BOOST_CHECK_CLOSE(\r\n    mean(dist), static_cast<RealType>(8 * (1 - 0.25) /0.25), tol5eps);\r\n  BOOST_CHECK_CLOSE(\r\n    mode(dist), static_cast<RealType>(21), tol1eps);\r\n  // variance:\r\n  BOOST_CHECK_CLOSE(\r\n    variance(dist), static_cast<RealType>(8 * (1 - 0.25) / (0.25 * 0.25)), tol5eps);\r\n  // std deviation:\r\n  BOOST_CHECK_CLOSE(\r\n    standard_deviation(dist), // 9.79795897113271239270\r\n    static_cast<RealType>(9.797958971132712392789136298823565567864L), // using functions.wolfram.com\r\n    //                              9.79795897113271152534  == sqrt(8 * (1 - 0.25) / (0.25 * 0.25)))\r\n    tol5eps * 100);\r\n  BOOST_CHECK_CLOSE(\r\n    skewness(dist), //\r\n    static_cast<RealType>(0.71443450831176036),\r\n    // using http://mathworld.wolfram.com/skewness.html\r\n    tolerance);\r\n  BOOST_CHECK_CLOSE(\r\n    kurtosis_excess(dist), //\r\n    static_cast<RealType>(0.7604166666666666666666666666666666666666L), // using Wikipedia Kurtosis(excess) formula\r\n    tol5eps * 100);\r\n  BOOST_CHECK_CLOSE(\r\n    kurtosis(dist), // true \r\n    static_cast<RealType>(3.76041666666666666666666666666666666666666L), // \r\n    tol5eps * 100);\r\n  // hazard:\r\n  RealType x = static_cast<RealType>(0.125);\r\n  BOOST_CHECK_CLOSE(\r\n  hazard(dist, x)\r\n  , pdf(dist, x) / cdf(complement(dist, x)), tol5eps);\r\n  // cumulative hazard:\r\n  BOOST_CHECK_CLOSE(\r\n  chf(dist, x), -log(cdf(complement(dist, x))), tol5eps);\r\n  // coefficient_of_variation:\r\n  BOOST_CHECK_CLOSE(\r\n  coefficient_of_variation(dist)\r\n  , standard_deviation(dist) / mean(dist), tol5eps);\r\n\r\n  // Special cases for PDF:\r\n  BOOST_CHECK_EQUAL(\r\n  pdf(\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0)), //\r\n  static_cast<RealType>(0)),\r\n  static_cast<RealType>(0) );\r\n\r\n  BOOST_CHECK_EQUAL(\r\n  pdf(\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0)),\r\n  static_cast<RealType>(0.0001)),\r\n  static_cast<RealType>(0) );\r\n\r\n  BOOST_CHECK_EQUAL(\r\n  pdf(\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(1)),\r\n  static_cast<RealType>(0.001)),\r\n  static_cast<RealType>(0) );\r\n\r\n  BOOST_CHECK_EQUAL(\r\n  pdf(\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(1)),\r\n  static_cast<RealType>(8)),\r\n  static_cast<RealType>(0) );\r\n\r\n  BOOST_CHECK_SMALL(\r\n  pdf(\r\n   negative_binomial_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(0))-\r\n  static_cast<RealType>(0.0625),\r\n  2 * boost::math::tools::epsilon<RealType>() ); // Expect exact, but not quite.\r\n  // numeric_limits<RealType>::epsilon()); // Not suitable for real concept!\r\n\r\n  // Quantile boundary cases checks:\r\n  BOOST_CHECK_EQUAL(\r\n  quantile(  // zero P < cdf(0) so should be exactly zero.\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(0)),\r\n  static_cast<RealType>(0));\r\n\r\n  BOOST_CHECK_EQUAL(\r\n  quantile(  // min P < cdf(0) so should be exactly zero.\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(boost::math::tools::min_value<RealType>())),\r\n  static_cast<RealType>(0));\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(\r\n  quantile(  // Small P < cdf(0) so should be near zero.\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(boost::math::tools::epsilon<RealType>())), // \r\n  static_cast<RealType>(0),\r\n    tol5eps);\r\n\r\n  BOOST_CHECK_CLOSE(\r\n  quantile(  // Small P < cdf(0) so should be exactly zero.\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(0.0001)),\r\n  static_cast<RealType>(0.95854156929288470),\r\n    tolerance);\r\n\r\n  //BOOST_CHECK(  // Fails with overflow for real_concept\r\n  //quantile(  // Small P near 1 so k failures should be big.\r\n  //negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  //static_cast<RealType>(1 - boost::math::tools::epsilon<RealType>())) <=\r\n  //static_cast<RealType>(189.56999032670058)  // 106.462769 for float\r\n  //);\r\n\r\n  if(std::numeric_limits<RealType>::has_infinity)\r\n  { // BOOST_CHECK tests for infinity using std::numeric_limits<>::infinity()\r\n    // Note that infinity is not implemented for real_concept, so these tests\r\n    // are only done for types, like built-in float, double.. that have infinity.\r\n    // Note that these assume that  BOOST_MATH_OVERFLOW_ERROR_POLICY is NOT throw_on_error.\r\n    // #define BOOST_MATH_THROW_ON_OVERFLOW_POLICY ==  throw_on_error would throw here.\r\n    // #define BOOST_MAT_DOMAIN_ERROR_POLICY IS defined throw_on_error,\r\n    //  so the throw path of error handling is tested below with BOOST_MATH_CHECK_THROW tests.\r\n\r\n    BOOST_CHECK(\r\n    quantile(  // At P == 1 so k failures should be infinite.\r\n    negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n    static_cast<RealType>(1)) ==\r\n    //static_cast<RealType>(boost::math::tools::infinity<RealType>())\r\n    static_cast<RealType>(std::numeric_limits<RealType>::infinity()) );\r\n\r\n    BOOST_CHECK_EQUAL(\r\n    quantile(  // At 1 == P  so should be infinite.\r\n    negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n    static_cast<RealType>(1)), //\r\n    std::numeric_limits<RealType>::infinity() );\r\n\r\n    BOOST_CHECK_EQUAL(\r\n    quantile(complement(  // Q zero 1 so P == 1 < cdf(0) so should be exactly infinity.\r\n    negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n    static_cast<RealType>(0))),\r\n    std::numeric_limits<RealType>::infinity() );\r\n   } // test for infinity using std::numeric_limits<>::infinity()\r\n  else\r\n  { // real_concept case, so check it throws rather than returning infinity.\r\n    BOOST_CHECK_EQUAL(\r\n    quantile(  // At P == 1 so k failures should be infinite.\r\n    negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n    static_cast<RealType>(1)),\r\n    boost::math::tools::max_value<RealType>() );\r\n\r\n    BOOST_CHECK_EQUAL(\r\n    quantile(complement(  // Q zero 1 so P == 1 < cdf(0) so should be exactly infinity.\r\n    negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n    static_cast<RealType>(0))),\r\n    boost::math::tools::max_value<RealType>());\r\n  }\r\n  BOOST_CHECK( // Should work for built-in and real_concept.\r\n  quantile(complement(  // Q very near to 1 so P nearly 1  < so should be large > 384.\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(boost::math::tools::min_value<RealType>())))\r\n   >= static_cast<RealType>(384) );\r\n\r\n  BOOST_CHECK_EQUAL(\r\n  quantile(  //  P ==  0 < cdf(0) so should be zero.\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(0)),\r\n  static_cast<RealType>(0));\r\n\r\n  // Quantile Complement boundary cases:\r\n\r\n  BOOST_CHECK_EQUAL(\r\n  quantile(complement(  // Q = 1 so P = 0 < cdf(0) so should be exactly zero.\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(1))),\r\n  static_cast<RealType>(0)\r\n  );\r\n\r\n  BOOST_CHECK_EQUAL(\r\n  quantile(complement(  // Q very near 1 so P == epsilon < cdf(0) so should be exactly zero.\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(1 - boost::math::tools::epsilon<RealType>()))),\r\n  static_cast<RealType>(0)\r\n  );\r\n\r\n  // Check that duff arguments throw domain_error:\r\n  BOOST_MATH_CHECK_THROW(\r\n  pdf( // Negative successes!\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(-1), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(0)), std::domain_error\r\n  );\r\n  BOOST_MATH_CHECK_THROW(\r\n  pdf( // Negative success_fraction!\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(-0.25)),\r\n  static_cast<RealType>(0)), std::domain_error\r\n  );\r\n  BOOST_MATH_CHECK_THROW(\r\n  pdf( // Success_fraction > 1!\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(1.25)),\r\n  static_cast<RealType>(0)),\r\n  std::domain_error\r\n  );\r\n  BOOST_MATH_CHECK_THROW(\r\n  pdf( // Negative k argument !\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(-1)),\r\n  std::domain_error\r\n  );\r\n  //BOOST_MATH_CHECK_THROW(\r\n  //pdf( // Unlike binomial there is NO limit on k (failures)\r\n  //negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  //static_cast<RealType>(9)), std::domain_error\r\n  //);\r\n  BOOST_MATH_CHECK_THROW(\r\n  cdf(  // Negative k argument !\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(0.25)),\r\n  static_cast<RealType>(-1)),\r\n  std::domain_error\r\n  );\r\n  BOOST_MATH_CHECK_THROW(\r\n  cdf( // Negative success_fraction!\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(-0.25)),\r\n  static_cast<RealType>(0)), std::domain_error\r\n  );\r\n  BOOST_MATH_CHECK_THROW(\r\n  cdf( // Success_fraction > 1!\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(1.25)),\r\n  static_cast<RealType>(0)), std::domain_error\r\n  );\r\n  BOOST_MATH_CHECK_THROW(\r\n  quantile(  // Negative success_fraction!\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(-0.25)),\r\n  static_cast<RealType>(0)), std::domain_error\r\n  );\r\n  BOOST_MATH_CHECK_THROW(\r\n  quantile( // Success_fraction > 1!\r\n  negative_binomial_distribution<RealType>(static_cast<RealType>(8), static_cast<RealType>(1.25)),\r\n  static_cast<RealType>(0)), std::domain_error\r\n  );\r\n  // End of check throwing 'duff' out-of-domain values.\r\n\r\n#define T RealType\r\n#include \"negative_binomial_quantile.ipp\"\r\n\r\n  for(unsigned i = 0; i < negative_binomial_quantile_data.size(); ++i)\r\n  {\r\n     using namespace boost::math::policies;\r\n     typedef policy<discrete_quantile<boost::math::policies::real> > P1;\r\n     typedef policy<discrete_quantile<integer_round_down> > P2;\r\n     typedef policy<discrete_quantile<integer_round_up> > P3;\r\n     typedef policy<discrete_quantile<integer_round_outwards> > P4;\r\n     typedef policy<discrete_quantile<integer_round_inwards> > P5;\r\n     typedef policy<discrete_quantile<integer_round_nearest> > P6;\r\n     RealType tol = boost::math::tools::epsilon<RealType>() * 700;\r\n     if(!boost::is_floating_point<RealType>::value)\r\n        tol *= 10;  // no lanczos approximation implies less accuracy\r\n     //\r\n     // Check full real value first:\r\n     //\r\n     negative_binomial_distribution<RealType, P1> p1(negative_binomial_quantile_data[i][0], negative_binomial_quantile_data[i][1]);\r\n     RealType x = quantile(p1, negative_binomial_quantile_data[i][2]);\r\n     BOOST_CHECK_CLOSE_FRACTION(x, negative_binomial_quantile_data[i][3], tol);\r\n     x = quantile(complement(p1, negative_binomial_quantile_data[i][2]));\r\n     BOOST_CHECK_CLOSE_FRACTION(x, negative_binomial_quantile_data[i][4], tol);\r\n     //\r\n     // Now with round down to integer:\r\n     //\r\n     negative_binomial_distribution<RealType, P2> p2(negative_binomial_quantile_data[i][0], negative_binomial_quantile_data[i][1]);\r\n     x = quantile(p2, negative_binomial_quantile_data[i][2]);\r\n     BOOST_CHECK_EQUAL(x, floor(negative_binomial_quantile_data[i][3]));\r\n     x = quantile(complement(p2, negative_binomial_quantile_data[i][2]));\r\n     BOOST_CHECK_EQUAL(x, floor(negative_binomial_quantile_data[i][4]));\r\n     //\r\n     // Now with round up to integer:\r\n     //\r\n     negative_binomial_distribution<RealType, P3> p3(negative_binomial_quantile_data[i][0], negative_binomial_quantile_data[i][1]);\r\n     x = quantile(p3, negative_binomial_quantile_data[i][2]);\r\n     BOOST_CHECK_EQUAL(x, ceil(negative_binomial_quantile_data[i][3]));\r\n     x = quantile(complement(p3, negative_binomial_quantile_data[i][2]));\r\n     BOOST_CHECK_EQUAL(x, ceil(negative_binomial_quantile_data[i][4]));\r\n     //\r\n     // Now with round to integer \"outside\":\r\n     //\r\n     negative_binomial_distribution<RealType, P4> p4(negative_binomial_quantile_data[i][0], negative_binomial_quantile_data[i][1]);\r\n     x = quantile(p4, negative_binomial_quantile_data[i][2]);\r\n     BOOST_CHECK_EQUAL(x, negative_binomial_quantile_data[i][2] < 0.5f ? floor(negative_binomial_quantile_data[i][3]) : ceil(negative_binomial_quantile_data[i][3]));\r\n     x = quantile(complement(p4, negative_binomial_quantile_data[i][2]));\r\n     BOOST_CHECK_EQUAL(x, negative_binomial_quantile_data[i][2] < 0.5f ? ceil(negative_binomial_quantile_data[i][4]) : floor(negative_binomial_quantile_data[i][4]));\r\n     //\r\n     // Now with round to integer \"inside\":\r\n     //\r\n     negative_binomial_distribution<RealType, P5> p5(negative_binomial_quantile_data[i][0], negative_binomial_quantile_data[i][1]);\r\n     x = quantile(p5, negative_binomial_quantile_data[i][2]);\r\n     BOOST_CHECK_EQUAL(x, negative_binomial_quantile_data[i][2] < 0.5f ? ceil(negative_binomial_quantile_data[i][3]) : floor(negative_binomial_quantile_data[i][3]));\r\n     x = quantile(complement(p5, negative_binomial_quantile_data[i][2]));\r\n     BOOST_CHECK_EQUAL(x, negative_binomial_quantile_data[i][2] < 0.5f ? floor(negative_binomial_quantile_data[i][4]) : ceil(negative_binomial_quantile_data[i][4]));\r\n     //\r\n     // Now with round to nearest integer:\r\n     //\r\n     negative_binomial_distribution<RealType, P6> p6(negative_binomial_quantile_data[i][0], negative_binomial_quantile_data[i][1]);\r\n     x = quantile(p6, negative_binomial_quantile_data[i][2]);\r\n     BOOST_CHECK_EQUAL(x, floor(negative_binomial_quantile_data[i][3] + 0.5f));\r\n     x = quantile(complement(p6, negative_binomial_quantile_data[i][2]));\r\n     BOOST_CHECK_EQUAL(x, floor(negative_binomial_quantile_data[i][4] + 0.5f));\r\n  }\r\n\r\n  return;\r\n} // template <class RealType> void test_spots(RealType) // Any floating-point type RealType.\r\n\r\nBOOST_AUTO_TEST_CASE( test_main )\r\n{\r\n  // Check that can generate negative_binomial distribution using the two convenience methods:\r\n  using namespace boost::math;\r\n   negative_binomial mynb1(2., 0.5); // Using typedef - default type is double.\r\n   negative_binomial_distribution<> myf2(2., 0.5); // Using default RealType double.\r\n\r\n  // Basic sanity-check spot values.\r\n\r\n  // Test some simple double only examples.\r\n  negative_binomial_distribution<double> my8dist(8., 0.25);\r\n  // 8 successes (r), 0.25 success fraction = 35% or 1 in 4 successes.\r\n  // Note: double values (matching the distribution definition) avoid the need for any casting.\r\n\r\n  // Check accessor functions return exact values for double at least.\r\n  BOOST_CHECK_EQUAL(my8dist.successes(), static_cast<double>(8));\r\n  BOOST_CHECK_EQUAL(my8dist.success_fraction(), static_cast<double>(1./4.));\r\n\r\n  // (Parameter value, arbitrarily zero, only communicates the floating point type).\r\n#ifdef TEST_FLOAT\r\n  test_spots(0.0F); // Test float.\r\n#endif\r\n#ifdef TEST_DOUBLE\r\n  test_spots(0.0); // Test double.\r\n#endif\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n#ifdef TEST_LDOUBLE\r\n  test_spots(0.0L); // Test long double.\r\n#endif\r\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\r\n#ifdef TEST_REAL_CONCEPT\r\n    test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\r\n#endif\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::endl;\r\n#endif\r\n\r\n  \r\n} // BOOST_AUTO_TEST_CASE( test_main )\r\n\r\n/*\r\n\r\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\test_negative_binomial.exe\"\r\nRunning 1 test case...\r\nTolerance = 0.0119209%.\r\nTolerance 5 eps = 5.96046e-007%.\r\nTolerance = 2.22045e-011%.\r\nTolerance 5 eps = 1.11022e-015%.\r\nTolerance = 2.22045e-011%.\r\nTolerance 5 eps = 1.11022e-015%.\r\nTolerance = 2.22045e-011%.\r\nTolerance 5 eps = 1.11022e-015%.\r\n*** No errors detected\r\n\r\n*/\r\n", "meta": {"hexsha": "d57efb69d0683ae13b8742c8657e2f9bd506575f", "size": 36175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/test/test_negative_binomial.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/test/test_negative_binomial.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/test/test_negative_binomial.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": 41.9663573086, "max_line_length": 166, "alphanum_fraction": 0.688569454, "num_tokens": 9782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.682573734412324, "lm_q1q2_score": 0.5211339563057606}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\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 along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if ! defined(LARGET_SIMON_MOVE_HPP)\n#define LARGET_SIMON_MOVE_HPP\n\n#include <vector>\t\t\t\t\t\t\t// for std::vector\n#include <boost/shared_ptr.hpp>\t\t\t\t// for boost::shared_ptr\n#include <boost/weak_ptr.hpp>\t\t\t\t// for boost::weak_ptr\n#include \"mcmc_updater.hpp\"\t\t// for base class MCMCUpdater\n\nnamespace phycas\n{\n\nclass MCMCChainManager;\ntypedef boost::weak_ptr<MCMCChainManager>\tChainManagerWkPtr;\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tEncapsulates the Larget-Simon local move. The LS move is the default move, but an exception must be made in the case\n|\tof a star tree, which does not have three contiguous edges required for the LS move. For star trees, the proposal\n|\tchanges the length of just one randomly-chosen edge in the tree. An edge chosen at random is set to the value\n|\tY = m*exp(`lambda'*(u - 0.5)), where m is the original length and u is a Uniform(0,1) random deviate. Under this\n|\tproposal scheme, the random variable Y has the following properties:\n|>\n|\tdensity         f(Y) = 1/(lambda*Y)\n|\tcdf             F(Y) = 0.5 + (1/lambda) log(Y/m)\n|\tminimum         m*exp(-lambda/2)\n|\tmaximum         m*exp(lambda/2)\n|\tmean            (m/lambda)[exp(lambda/2) - exp(-lambda/2)]\n|\tvariance        (m/lambda)^2 [(lambda/2)(exp(lambda) - exp(-lambda)) - (exp(lambda/2) - exp(-lambda/2))^2]\n|>\n|\tWith a starting edge length of 1.0, the proposed edge lengths have increasing mean and variance with increasing\n|\tlambda, but values of lambda in the range 0.1 to 2.0 appear to be reasonable.\n|>\n|\tlambda       mean        s.d.\n|\t-----------------------------\n|\t 0.1      1.00042     0.02888\n|\t 0.5      1.01045     0.14554\n|\t 1.0      1.04219     0.29840\n|\t 2.0      1.17520     0.65752\n|\t10.0     14.84064    29.68297\n|>\n*/\nclass LargetSimonMove : public MCMCUpdater\n\t{\n\tpublic:\n\t\t\t\t\t\tLargetSimonMove();\n\t\t\t\t\t\tvirtual ~LargetSimonMove();\n\n\t\tunsigned\t\tgetWhichCase() const;\n\t\tvoid\t\t\tsetTuningParameter(double x);\n\t\tdouble\t\t\tgetTuningParameter() const;\n\t\tbool\t\t\ttopologyChanged() const;\n\t\tvoid\t\t\tdefaultProposeNewState();\n\t\tvoid\t\t\tstarTreeProposeNewState();\n        TreeNode *      randomInternalAboveSubroot();\n        TreeNode *      randomChild(TreeNode * nd);\n        TreeNode *      chooseZ(TreeNode * middle);\n\n\t\tvirtual double  sampleWorkingPrior() const;\n\n\t\tvirtual bool    computesTopologyPrior() const {return true;}\n\t\t// These are virtual functions in the MCMCUpdater base class\n\t\t//\n\t\tdouble\t\t\trecalcWorkingPrior() const;\n\t\tbool \t\t\tisPriorSteward() const;\n\t\tvirtual bool\tupdate();\n\t\tvirtual double\tgetLnHastingsRatio() const;\n\t\tvirtual double\tgetLnJacobian() const;\n\t\tvirtual void\tproposeNewState();\n\t\tvirtual void\trevert();\n\t\tvirtual void\taccept();\n\n\tprivate:\n\n\t\tdouble\t\t\t    lambda;\t\t\t\t\t\t/**< The tuning parameter for this move (the factor used in modifying backbone length) */\n\n\t\tTreeNode *\t\t    ndX;\t\t\t\t\t\t/**< Node at one end of segment involved in move; used by Revert to undo a move */\n\t\tTreeNode *\t\t    ndY;\t\t\t\t\t\t/**< One of two nodes in the middle of segment involved in move; used by Revert to undo a move */\n\t\tTreeNode *\t\t    ndZ;\t\t\t\t\t\t/**< Node at other end (from ndX) of segment involved in move; used by Revert to undo a move */\n\t\tdouble\t\t\t    x;\t\t\t\t\t\t    /**< Original length of ndX's branch; used by Revert to undo a move */\n\t\tdouble\t\t\t    y;\t\t\t\t\t\t    /**< Original length of ndX's branch; used by Revert to undo a move */\n\t\tdouble\t\t\t    z;\t\t\t\t\t\t    /**< Original length of ndX's branch; used by Revert to undo a move */\n\t\tTreeNode *\t\t    swap1;\t\t\t\t\t\t/**< First of the two nodes involved in an NNI swap; NULL if no swap was performed; used by Revert to undo a move */\n\t\tTreeNode *\t\t    swap2;\t\t\t\t\t\t/**< Second of the two nodes involved in an NNI swap; NULL if no swap was performed; used by Revert to undo a move */\n\n\t\tdouble\t\t\t    m;\t\t\t\t\t\t\t/**< Original 3-segment length; needed for computing Hastings ratio */\n\t\tdouble\t\t\t    mstar;\t\t\t\t\t\t/**< Modified 3-segment length; needed for computing Hastings ratio */\n\n        double              expand_contract_factor;     /**< The factor by which the selected 3-edge segment is expanded or contracted */\n\n\t\tbool\t\t\t    topol_changed;\t\t\t\t/**< If true, last proposal changed topology */\n\t\tunsigned\t\t    which_case;\t\t\t\t\t/**< Which of the eight possible cases was tried last */\n\n\t\tstd::vector<double> three_edgelens;\t\t\t/**< workspace declared here to avoid unnecessary allocs/deallocs */\n\n\t\tvoid\t\t\t    reset();\t\t\t\t\t/**< Returns variables involved with reversing a proposed move to the state needed for the start of another proposal */\n\n\t\tbool\t\t\t    star_tree_proposal;\t\t\t/**< True if last proposed move was on a star tree (only one randomly-chosen edge changed); False if last proposed move was not on a star tree */\n\n\t\t// These are needed for the star tree exception\n\t\tdouble\t\t\t\torig_edge_len;\t/**< Length of modified edge saved (in case revert is necessary) */\n\t\tTreeNode *\t\t\torig_node;\t\t/**< Node owning the modified edge (in case revert is necessary) */\n\t\tstd::vector<double>\tone_edgelen;\t/**< workspace declared here to avoid unnecessary allocs/deallocs */\n\t};\n\n} // namespace phycas\n\n#endif\n", "meta": {"hexsha": "b77f51163f0e65c052cbbb3caa13d06b8ad44427", "size": 6587, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/larget_simon_move.hpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/larget_simon_move.hpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_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/larget_simon_move.hpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 52.2777777778, "max_line_length": 180, "alphanum_fraction": 0.6045240625, "num_tokens": 1584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5211339513758126}}
{"text": "//  Copyright (c) 2006 Xiaogang Zhang\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_BESSEL_JY_HPP\n#define BOOST_MATH_BESSEL_JY_HPP\n\n#include <boost/math/tools/config.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n#include <boost/math/special_functions/sin_pi.hpp>\n#include <boost/math/special_functions/cos_pi.hpp>\n#include <boost/math/special_functions/detail/simple_complex.hpp>\n#include <boost/math/special_functions/detail/bessel_jy_asym.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <complex>\n\n// Bessel functions of the first and second kind of fractional order\n\nnamespace boost { namespace math {\n\nnamespace detail {\n\n// Calculate Y(v, x) and Y(v+1, x) by Temme's method, see\n// Temme, Journal of Computational Physics, vol 21, 343 (1976)\ntemplate <typename T, typename Policy>\nint temme_jy(T v, T x, T* Y, T* Y1, const Policy& pol)\n{\n    T g, h, p, q, f, coef, sum, sum1, tolerance;\n    T a, d, e, sigma;\n    unsigned long k;\n\n    BOOST_MATH_STD_USING\n    using namespace boost::math::tools;\n    using namespace boost::math::constants;\n\n    BOOST_ASSERT(fabs(v) <= 0.5f);  // precondition for using this routine\n\n    T gp = boost::math::tgamma1pm1(v, pol);\n    T gm = boost::math::tgamma1pm1(-v, pol);\n    T spv = boost::math::sin_pi(v, pol);\n    T spv2 = boost::math::sin_pi(v/2, pol);\n    T xp = pow(x/2, v);\n\n    a = log(x / 2);\n    sigma = -a * v;\n    d = abs(sigma) < tools::epsilon<T>() ?\n        T(1) : sinh(sigma) / sigma;\n    e = abs(v) < tools::epsilon<T>() ? v*pi<T>()*pi<T>() / 2\n        : 2 * spv2 * spv2 / v;\n\n    T g1 = (v == 0) ? -euler<T>() : (gp - gm) / ((1 + gp) * (1 + gm) * 2 * v);\n    T g2 = (2 + gp + gm) / ((1 + gp) * (1 + gm) * 2);\n    T vspv = (fabs(v) < tools::epsilon<T>()) ? 1/constants::pi<T>() : v / spv;\n    f = (g1 * cosh(sigma) - g2 * a * d) * 2 * vspv;\n\n    p = vspv / (xp * (1 + gm));\n    q = vspv * xp / (1 + gp);\n\n    g = f + e * q;\n    h = p;\n    coef = 1;\n    sum = coef * g;\n    sum1 = coef * h;\n\n    T v2 = v * v;\n    T coef_mult = -x * x / 4;\n\n    // series summation\n    tolerance = tools::epsilon<T>();\n    for (k = 1; k < policies::get_max_series_iterations<Policy>(); k++)\n    {\n        f = (k * f + p + q) / (k*k - v2);\n        p /= k - v;\n        q /= k + v;\n        g = f + e * q;\n        h = p - k * g;\n        coef *= coef_mult / k;\n        sum += coef * g;\n        sum1 += coef * h;\n        if (abs(coef * g) < abs(sum) * tolerance) \n        { \n           break; \n        }\n    }\n    policies::check_series_iterations(\"boost::math::bessel_jy<%1%>(%1%,%1%) in temme_jy\", k, pol);\n    *Y = -sum;\n    *Y1 = -2 * sum1 / x;\n\n    return 0;\n}\n\n// Evaluate continued fraction fv = J_(v+1) / J_v, see\n// Abramowitz and Stegun, Handbook of Mathematical Functions, 1972, 9.1.73\ntemplate <typename T, typename Policy>\nint CF1_jy(T v, T x, T* fv, int* sign, const Policy& pol)\n{\n    T C, D, f, a, b, delta, tiny, tolerance;\n    unsigned long k;\n    int s = 1;\n\n    BOOST_MATH_STD_USING\n\n    // |x| <= |v|, CF1_jy converges rapidly\n    // |x| > |v|, CF1_jy needs O(|x|) iterations to converge\n\n    // modified Lentz's method, see\n    // Lentz, Applied Optics, vol 15, 668 (1976)\n    tolerance = 2 * tools::epsilon<T>();\n    tiny = sqrt(tools::min_value<T>());\n    C = f = tiny;                           // b0 = 0, replace with tiny\n    D = 0.0L;\n    for (k = 1; k < policies::get_max_series_iterations<Policy>() * 100; k++)\n    {\n        a = -1;\n        b = 2 * (v + k) / x;\n        C = b + a / C;\n        D = b + a * D;\n        if (C == 0) { C = tiny; }\n        if (D == 0) { D = tiny; }\n        D = 1 / D;\n        delta = C * D;\n        f *= delta;\n        if (D < 0) { s = -s; }\n        if (abs(delta - 1.0L) < tolerance) \n        { break; }\n    }\n    policies::check_series_iterations(\"boost::math::bessel_jy<%1%>(%1%,%1%) in CF1_jy\", k / 100, pol);\n    *fv = -f;\n    *sign = s;                              // sign of denominator\n\n    return 0;\n}\n\ntemplate <class T>\nstruct complex_trait\n{\n   typedef typename mpl::if_<is_floating_point<T>,\n      std::complex<T>, sc::simple_complex<T> >::type type;\n};\n\n// Evaluate continued fraction p + iq = (J' + iY') / (J + iY), see\n// Press et al, Numerical Recipes in C, 2nd edition, 1992\ntemplate <typename T, typename Policy>\nint CF2_jy(T v, T x, T* p, T* q, const Policy& pol)\n{\n    BOOST_MATH_STD_USING\n\n    typedef typename complex_trait<T>::type complex_type;\n\n    complex_type C, D, f, a, b, delta, one(1);\n    T tiny, zero(0.0L);\n    unsigned long k;\n\n    // |x| >= |v|, CF2_jy converges rapidly\n    // |x| -> 0, CF2_jy fails to converge\n    BOOST_ASSERT(fabs(x) > 1);\n\n    // modified Lentz's method, complex numbers involved, see\n    // Lentz, Applied Optics, vol 15, 668 (1976)\n    T tolerance = 2 * tools::epsilon<T>();\n    tiny = sqrt(tools::min_value<T>());\n    C = f = complex_type(-0.5f/x, 1.0L);\n    D = 0;\n    for (k = 1; k < policies::get_max_series_iterations<Policy>(); k++)\n    {\n        a = (k - 0.5f)*(k - 0.5f) - v*v;\n        if (k == 1)\n        {\n            a *= complex_type(T(0), 1/x);\n        }\n        b = complex_type(2*x, T(2*k));\n        C = b + a / C;\n        D = b + a * D;\n        if (C == zero) { C = tiny; }\n        if (D == zero) { D = tiny; }\n        D = one / D;\n        delta = C * D;\n        f *= delta;\n        if (abs(delta - one) < tolerance) { break; }\n    }\n    policies::check_series_iterations(\"boost::math::bessel_jy<%1%>(%1%,%1%) in CF2_jy\", k, pol);\n    *p = real(f);\n    *q = imag(f);\n\n    return 0;\n}\n\nenum\n{\n   need_j = 1, need_y = 2\n};\n\n// Compute J(v, x) and Y(v, x) simultaneously by Steed's method, see\n// Barnett et al, Computer Physics Communications, vol 8, 377 (1974)\ntemplate <typename T, typename Policy>\nint bessel_jy(T v, T x, T* J, T* Y, int kind, const Policy& pol)\n{\n    BOOST_ASSERT(x >= 0);\n\n    T u, Jv, Ju, Yv, Yv1, Yu, Yu1(0), fv, fu;\n    T W, p, q, gamma, current, prev, next;\n    bool reflect = false;\n    unsigned n, k;\n    int s;\n\n    static const char* function = \"boost::math::bessel_jy<%1%>(%1%,%1%)\";\n\n    BOOST_MATH_STD_USING\n    using namespace boost::math::tools;\n    using namespace boost::math::constants;\n\n    if (v < 0)\n    {\n        reflect = true;\n        v = -v;                             // v is non-negative from here\n        kind = need_j|need_y;               // need both for reflection formula\n    }\n    n = real_cast<unsigned>(v + 0.5L);\n    u = v - n;                              // -1/2 <= u < 1/2\n\n    if (x == 0)\n    {\n       *J = *Y = policies::raise_overflow_error<T>(\n          function, 0, pol);\n       return 1;\n    }\n\n    // x is positive until reflection\n    W = T(2) / (x * pi<T>());               // Wronskian\n    if (x <= 2)                           // x in (0, 2]\n    {\n        if(temme_jy(u, x, &Yu, &Yu1, pol))             // Temme series\n        {\n           // domain error:\n           *J = *Y = Yu;\n           return 1;\n        }\n        prev = Yu;\n        current = Yu1;\n        for (k = 1; k <= n; k++)            // forward recurrence for Y\n        {\n            next = 2 * (u + k) * current / x - prev;\n            prev = current;\n            current = next;\n        }\n        Yv = prev;\n        Yv1 = current;\n        if(kind&need_j)\n        {\n          CF1_jy(v, x, &fv, &s, pol);                 // continued fraction CF1_jy\n          Jv = W / (Yv * fv - Yv1);           // Wronskian relation\n        }\n        else\n           Jv = std::numeric_limits<T>::quiet_NaN(); // any value will do, we're not using it.\n    }\n    else                                    // x in (2, \\infty)\n    {\n        // Get Y(u, x):\n        // define tag type that will dispatch to right limits:\n        typedef typename bessel_asymptotic_tag<T, Policy>::type tag_type;\n\n        T lim;\n        switch(kind)\n        {\n        case need_j:\n           lim = asymptotic_bessel_j_limit<T>(v, tag_type());\n           break;\n        case need_y:\n           lim = asymptotic_bessel_y_limit<T>(tag_type());\n           break;\n        default:\n           lim = (std::max)(\n              asymptotic_bessel_j_limit<T>(v, tag_type()),\n              asymptotic_bessel_y_limit<T>(tag_type()));\n           break;\n        }\n        if(x > lim)\n        {\n           if(kind&need_y)\n           {\n              Yu = asymptotic_bessel_y_large_x_2(u, x);\n              Yu1 = asymptotic_bessel_y_large_x_2(u + 1, x);\n           }\n           else\n              Yu = std::numeric_limits<T>::quiet_NaN(); // any value will do, we're not using it.\n           if(kind&need_j)\n           {\n              Jv = asymptotic_bessel_j_large_x_2(v, x);\n           }\n           else\n              Jv = std::numeric_limits<T>::quiet_NaN(); // any value will do, we're not using it.\n        }\n        else\n        {\n           CF1_jy(v, x, &fv, &s, pol);\n           // tiny initial value to prevent overflow\n           T init = sqrt(tools::min_value<T>());\n           prev = fv * s * init;\n           current = s * init;\n           for (k = n; k > 0; k--)             // backward recurrence for J\n           {\n               next = 2 * (u + k) * current / x - prev;\n               prev = current;\n               current = next;\n           }\n           T ratio = (s * init) / current;     // scaling ratio\n           // can also call CF1_jy() to get fu, not much difference in precision\n           fu = prev / current;\n           CF2_jy(u, x, &p, &q, pol);                  // continued fraction CF2_jy\n           T t = u / x - fu;                   // t = J'/J\n           gamma = (p - t) / q;\n           Ju = sign(current) * sqrt(W / (q + gamma * (p - t)));\n\n           Jv = Ju * ratio;                    // normalization\n\n           Yu = gamma * Ju;\n           Yu1 = Yu * (u/x - p - q/gamma);\n        }\n        if(kind&need_y)\n        {\n           // compute Y:\n           prev = Yu;\n           current = Yu1;\n           for (k = 1; k <= n; k++)            // forward recurrence for Y\n           {\n               next = 2 * (u + k) * current / x - prev;\n               prev = current;\n               current = next;\n           }\n           Yv = prev;\n        }\n        else\n           Yv = std::numeric_limits<T>::quiet_NaN(); // any value will do, we're not using it.\n    }\n\n    if (reflect)\n    {\n        T z = (u + n % 2);\n        *J = boost::math::cos_pi(z, pol) * Jv - boost::math::sin_pi(z, pol) * Yv;     // reflection formula\n        *Y = boost::math::sin_pi(z, pol) * Jv + boost::math::cos_pi(z, pol) * Yv;\n    }\n    else\n    {\n        *J = Jv;\n        *Y = Yv;\n    }\n\n    return 0;\n}\n\n} // namespace detail\n\n}} // namespaces\n\n#endif // BOOST_MATH_BESSEL_JY_HPP\n", "meta": {"hexsha": "9ef303ec6a0ec91f89ec2da1af97f11c70019a36", "size": 10952, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_35/boost/math/special_functions/detail/bessel_jy.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T09:40:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T09:40:26.000Z", "max_issues_repo_path": "vegastrike/boost/1_35/boost/math/special_functions/detail/bessel_jy.hpp", "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vegastrike/boost/1_35/boost/math/special_functions/detail/bessel_jy.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-05-05T22:29:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T14:18:54.000Z", "avg_line_length": 30.2541436464, "max_line_length": 107, "alphanum_fraction": 0.5003652301, "num_tokens": 3363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5210723129159442}}
{"text": "/*\n Copyright (C) 2017 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/*! \\file normalsabrinterpolation.hpp\n    \\brief normal SABR interpolation interpolation between discrete points\n*/\n\n#pragma once\n\n#include <qle/models/normalsabr.hpp>\n\n#include <ql/math/interpolations/xabrinterpolation.hpp>\n#include <ql/termstructures/volatility/sabr.hpp>\n\n#include <boost/assign/list_of.hpp>\n#include <boost/make_shared.hpp>\n\nnamespace QuantExt {\nusing namespace QuantLib;\n\nnamespace detail {\n\nclass NormalSABRWrapper {\npublic:\n    NormalSABRWrapper(const Time t, const Real& forward, const std::vector<Real>& params,\n                      const std::vector<Real>& addParams)\n        : t_(t), forward_(forward), params_(params) {\n        // validateSabrParameters(params[0], 0.0, params[1], params[2]);\n    }\n    const std::vector<Real>& params() const { return params_; }\n    Real volatility(const Real x) { return normalSabrVolatility(x, forward_, t_, params_[0], params_[1], params_[2]); }\n\nprivate:\n    const Real t_, &forward_;\n    const std::vector<Real> params_;\n};\n\nstruct NormalSABRSpecs {\n    Size dimension() { return 3; }\n    void defaultValues(std::vector<Real>& params, std::vector<bool>&, const Real& forward, const Real expiryTime,\n                       const std::vector<Real>& addParams) {\n        if (params[0] == Null<Real>())\n            params[0] = 0.0040;\n        if (params[1] == Null<Real>())\n            params[1] = std::sqrt(0.4);\n        if (params[2] == Null<Real>())\n            params[2] = 0.0;\n    }\n    void guess(Array& values, const std::vector<bool>& paramIsFixed, const Real& forward, const Real expiryTime,\n               const std::vector<Real>& r, const std::vector<Real>& addParams) {\n        Size j = 0;\n        if (!paramIsFixed[0]) {\n            values[0] = (0.01 - 2E-6) * r[j++] + 1E-6; // normal vol guess\n        }\n        if (!paramIsFixed[1])\n            values[1] = 1.5 * r[j++] + 1E-6;\n        if (!paramIsFixed[2])\n            values[2] = (2.0 * r[j++] - 1.0) * (1.0 - 1E-6);\n    }\n    Real eps1() { return .0000001; }\n    Real eps2() { return .9999; }\n    Real dilationFactor() { return 0.001; }\n    Array inverse(const Array& y, const std::vector<bool>&, const std::vector<Real>&, const Real) {\n        Array x(3);\n        x[0] = std::tan(y[0] * M_PI / 0.02 - M_PI_2);\n        x[1] = std::tan(y[1] * M_PI / 5.00 - M_PI_2);\n        x[2] = std::tan((y[2] + 1.0) * M_PI / 2.0 - M_PI_2);\n        return x;\n    }\n    Array direct(const Array& x, const std::vector<bool>&, const std::vector<Real>&, const Real) {\n        Array y(3);\n        y[0] = 0.02 * (std::atan(x[0]) + M_PI_2) / M_PI;\n        y[1] = 5.00 * (std::atan(x[1]) + M_PI_2) / M_PI;\n        y[2] = 2.0 * (std::atan(x[2]) + M_PI_2) / M_PI - 1.0;\n        return y;\n    }\n    Real weight(const Real strike, const Real forward, const Real stdDev, const std::vector<Real>& addParams) {\n        return bachelierBlackFormulaStdDevDerivative(strike, forward, stdDev, 1.0);\n    }\n    typedef NormalSABRWrapper type;\n    boost::shared_ptr<type> instance(const Time t, const Real& forward, const std::vector<Real>& params,\n                                     const std::vector<Real>& addParams) {\n        std::vector<Real> updatedParams(params);\n        if (!addParams.empty()) {\n            updatedParams[0] = normalSabrAlphaFromAtmVol(forward, t, addParams.front(), params[1], params[2]);\n        }\n        return boost::make_shared<type>(t, forward, updatedParams, addParams);\n    }\n};\n} // namespace detail\n\n//! %SABR smile interpolation between discrete volatility points.\n/*! \\ingroup interpolations */\nclass NormalSABRInterpolation : public Interpolation {\npublic:\n    template <class I1, class I2>\n    NormalSABRInterpolation(\n        const I1& xBegin, // x = strikes\n        const I1& xEnd,\n        const I2& yBegin, // y = volatilities\n        Time t,           // option expiry\n        const Real& forward, Real alpha, Real nu, Real rho, bool alphaIsFixed, bool nuIsFixed, bool rhoIsFixed,\n        bool vegaWeighted = true, const Size atmStrikeIndex = Null<Size>(), const bool implyAlphaFromAtmVol = false,\n        const boost::shared_ptr<EndCriteria>& endCriteria = boost::shared_ptr<EndCriteria>(),\n        const boost::shared_ptr<OptimizationMethod>& optMethod = boost::shared_ptr<OptimizationMethod>(),\n        const Real errorAccept = 0.0002, const bool useMaxError = false, const Size maxGuesses = 50) {\n\n        QL_REQUIRE(\n            !implyAlphaFromAtmVol || atmStrikeIndex != Null<Real>(),\n            \"NormalSABRInterpolation: imply alpha from atm vol implies a) that the atm strike index must be given\");\n\n        std::vector<Real> addParams;\n        if (implyAlphaFromAtmVol) {\n            addParams.push_back(*std::next(yBegin, atmStrikeIndex));\n        }\n\n        impl_ = boost::shared_ptr<Interpolation::Impl>(\n            new QuantLib::detail::XABRInterpolationImpl<I1, I2, detail::NormalSABRSpecs>(\n                xBegin, xEnd, yBegin, t, forward, boost::assign::list_of(alpha)(nu)(rho),\n                boost::assign::list_of(alphaIsFixed)(nuIsFixed)(rhoIsFixed), vegaWeighted, endCriteria, optMethod,\n                errorAccept, useMaxError, maxGuesses, addParams));\n        coeffs_ = boost::dynamic_pointer_cast<QuantLib::detail::XABRCoeffHolder<detail::NormalSABRSpecs>>(impl_);\n    }\n    Real expiry() const { return coeffs_->t_; }\n    Real forward() const { return coeffs_->forward_; }\n    Real alpha() const { return coeffs_->modelInstance_->params()[0]; }\n    Real nu() const { return coeffs_->modelInstance_->params()[1]; }\n    Real rho() const { return coeffs_->modelInstance_->params()[2]; }\n    Real rmsError() const { return coeffs_->error_; }\n    Real maxError() const { return coeffs_->maxError_; }\n    const std::vector<Real>& interpolationWeights() const { return coeffs_->weights_; }\n    EndCriteria::Type endCriteria() { return coeffs_->XABREndCriteria_; }\n\nprivate:\n    boost::shared_ptr<QuantLib::detail::XABRCoeffHolder<detail::NormalSABRSpecs>> coeffs_;\n};\n\n//! %SABR interpolation factory and traits\n/*! \\ingroup interpolations */\nclass NormalSABR {\npublic:\n    NormalSABR(Time t, Real forward, Real alpha, Real nu, Real rho, bool alphaIsFixed, bool nuIsFixed, bool rhoIsFixed,\n               bool vegaWeighted = false,\n               const boost::shared_ptr<EndCriteria> endCriteria = boost::shared_ptr<EndCriteria>(),\n               const boost::shared_ptr<OptimizationMethod> optMethod = boost::shared_ptr<OptimizationMethod>(),\n               const Real errorAccept = 0.0002, const bool useMaxError = false, const Size maxGuesses = 50)\n        : t_(t), forward_(forward), alpha_(alpha), nu_(nu), rho_(rho), alphaIsFixed_(alphaIsFixed),\n          nuIsFixed_(nuIsFixed), rhoIsFixed_(rhoIsFixed), vegaWeighted_(vegaWeighted), endCriteria_(endCriteria),\n          optMethod_(optMethod), errorAccept_(errorAccept), useMaxError_(useMaxError), maxGuesses_(maxGuesses) {}\n    template <class I1, class I2> Interpolation interpolate(const I1& xBegin, const I1& xEnd, const I2& yBegin) const {\n        return SABRInterpolation(xBegin, xEnd, yBegin, t_, forward_, alpha_, nu_, rho_, alphaIsFixed_, nuIsFixed_,\n                                 rhoIsFixed_, vegaWeighted_, endCriteria_, optMethod_, errorAccept_, useMaxError_,\n                                 maxGuesses_);\n    }\n    static const bool global = true;\n\nprivate:\n    Time t_;\n    Real forward_;\n    Real alpha_, nu_, rho_;\n    bool alphaIsFixed_, nuIsFixed_, rhoIsFixed_;\n    bool vegaWeighted_;\n    const boost::shared_ptr<EndCriteria> endCriteria_;\n    const boost::shared_ptr<OptimizationMethod> optMethod_;\n    const Real errorAccept_;\n    const bool useMaxError_;\n    const Size maxGuesses_;\n};\n} // namespace QuantExt\n", "meta": {"hexsha": "2ad812871a36251890a1c5fc957ed6b5860106ff", "size": 8407, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/models/normalsabrinterpolation.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/models/normalsabrinterpolation.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/models/normalsabrinterpolation.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": 45.4432432432, "max_line_length": 119, "alphanum_fraction": 0.6557630546, "num_tokens": 2237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5210723021975512}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <fstream>\n#include <numeric>\n\n#include <boost/filesystem.hpp>\n#include <glog/logging.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/eigen.hpp>\n\n#include \"YamlFileIO.h\"\n\nEigen::Matrix4d loadCameraPose(const std::string &file)\n{\n    Eigen::Matrix4d T = Eigen::Matrix4d::Identity();\n    std::ifstream fs(file);\n    if (!fs.is_open())\n    {\n        std::cerr << \"Fail to open camera pose file \" << file << std::endl;\n        return T;\n    }\n\n    std::string line;\n    int i = 0;\n    while (!fs.eof())\n    {\n        line.clear();\n        getline(fs, line);\n        if (line.empty())\n            continue;\n\n        std::stringstream ss(line);\n        std::string dummy_str;\n        if (i < 4)\n        {\n            ss >> T(i, 0) >> dummy_str >> T(i, 1) >> dummy_str >> T(i, 2) >> dummy_str >> T(i, 3);\n            i++;\n        }\n        else\n        {\n            std::cerr << \"Invalid camera pose format!\\n\";\n            break;\n        }\n    }\n    fs.close();\n\n    return T;\n}\n\n\nvoid evaluateBackpackExt(const std::vector<Eigen::Matrix4d> &v_extrinsics, const std::string &eval_pattern){\n    Eigen::Matrix4d T_c0_c1_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd c0_c1_vec = Eigen::AngleAxisd(-90*M_PI/180.0, Eigen::Vector3d(0,-1,0));\n    Eigen::Vector3d t_c0_c1(-0.03543, 0, -0.03543);\n    T_c0_c1_gt.block<3, 3>(0, 0) = c0_c1_vec.matrix();\n    T_c0_c1_gt.block<3, 1>(0, 3) = t_c0_c1;\n    Eigen::Matrix4d T_c0_c2_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd c0_c2_vec = Eigen::AngleAxisd(-180*M_PI/180.0, Eigen::Vector3d(0,-1,0));\n    Eigen::Vector3d t_c0_c2(0, 0, -0.07086);\n    T_c0_c2_gt.block<3, 3>(0, 0) = c0_c2_vec.matrix();\n    T_c0_c2_gt.block<3, 1>(0, 3) = t_c0_c2;\n    Eigen::Matrix4d T_c0_c3_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd c0_c3_vec = Eigen::AngleAxisd(90*M_PI/180.0, Eigen::Vector3d(0,-1,0));\n    Eigen::Vector3d t_c0_c3(0.03543, 0, -0.03543);\n    T_c0_c3_gt.block<3, 3>(0, 0) = c0_c3_vec.matrix();\n    T_c0_c3_gt.block<3, 1>(0, 3) = t_c0_c3;\n\n    Eigen::Matrix4d T_l0_c0_gt = Eigen::Matrix4d::Identity();\n    Eigen::Matrix4d T_l1_c0_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd l1_c0_vec1 = Eigen::AngleAxisd(-15*M_PI/180.0, Eigen::Vector3d(0,1,0));\n    Eigen::AngleAxisd l1_c0_vec2 = Eigen::AngleAxisd(90*M_PI/180.0, Eigen::Vector3d(0,0,1));\n    Eigen::Matrix3d l1_c0_vec =  l1_c0_vec1.matrix()*l1_c0_vec2.matrix();\n    Eigen::Vector3d t_l1_c0(0.58192, 0.0, -0.1954);\n    T_l1_c0_gt.block<3,3>(0, 0) = l1_c0_vec;\n    T_l1_c0_gt.block<3, 1>(0, 3) = l1_c0_vec* t_l1_c0;\n    std::cout << \"T_l1_c0_gt:\\n\" << T_l1_c0_gt << \"\\n\";\n\n    Eigen::Matrix4d T_l0_l1_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd l0_l1_vec1 = Eigen::AngleAxisd(-30*M_PI/180.0, Eigen::Vector3d(0,0,1));\n    Eigen::AngleAxisd l0_l1_vec2 = Eigen::AngleAxisd(-75*M_PI/180.0, Eigen::Vector3d(0,1,0));\n    Eigen::Matrix3d l0_l1_vec =  l0_l1_vec1.matrix()*l0_l1_vec2.matrix();\n    Eigen::Vector3d t_l0_l1(-0.2604, 0, -0.34922);\n    T_l0_l1_gt.block<3,3>(0, 0) = l0_l1_vec;\n    T_l0_l1_gt.block<3, 1>(0, 3) = l0_l1_vec1.matrix() * t_l0_l1;\n\n    Eigen::Matrix4d T_gt = Eigen::Matrix4d::Identity();\n    if (eval_pattern == \"camera0_to_camera1\")\n        T_gt = T_c0_c1_gt;\n    if (eval_pattern == \"camera0_to_camera2\")\n        T_gt = T_c0_c2_gt;\n    if (eval_pattern == \"camera0_to_camera3\")\n        T_gt = T_c0_c3_gt;\n    if (eval_pattern == \"lidar0_to_camera0\")\n        T_gt = T_l0_c0_gt;\n    if (eval_pattern == \"lidar1_to_camera0\")\n        T_gt = T_l1_c0_gt;\n    if (eval_pattern == \"lidar0_to_lidar1\")\n        T_gt = T_l0_l1_gt;\n\n    double avg_roll = 0.0, avg_pitch = 0.0, avg_yaw = 0.0;\n    double avg_tx = 0, avg_ty = 0, avg_tz = 0.0;\n    for(auto &T_ext : v_extrinsics){\n        Eigen::Matrix4d T_error = T_gt.inverse() * T_ext;\n\n        std::cout << \"T_ext:\\n\" << T_ext << \"\\n\";\n        Eigen::Matrix3d R = T_ext.block<3, 3>(0, 0);\n        Eigen::Vector3d v_angles = R.eulerAngles(2,1,0) * 180.0/M_PI;\n        avg_yaw += (std::abs(v_angles[0]) > 90) ? (180 - std::abs(v_angles[0])) : std::abs(v_angles[0]);\n        avg_pitch += (std::abs(v_angles[1]) > 90) ? (180 - std::abs(v_angles[1])) : std::abs(v_angles[1]);\n        avg_roll += (std::abs(v_angles[2]) > 90) ? (180 - std::abs(v_angles[2])) : std::abs(v_angles[2]);\n        LOG(INFO) << eval_pattern << \" euler angles(ZYX): \" << v_angles.transpose() << \"\\n\";\n\n        Eigen::Vector3d t = T_ext.block<3,1>(0, 3);\n        avg_tx += t[0]; avg_ty += t[1]; avg_tz += t[2];\n        LOG(INFO) << eval_pattern << \" trans vector: \" << t.transpose() << \"\\n\";\n\n        Eigen::Matrix3d err_R = T_error.block<3, 3>(0, 0);\n        Eigen::Vector3d err_t = T_error.block<3, 1>(0, 3);\n        Eigen::AngleAxisd delta_R_vec(err_R);\n        LOG(INFO) << \" Rotation difference angle \"\n                    << delta_R_vec.angle() * 180.0 / M_PI << \"\\n\";\n        LOG(INFO) << \" Translation difference norm is \"\n                    << err_t.norm() << \"\\n\";\n    }\n    int size = v_extrinsics.size();\n    LOG(INFO) << \"Evaluate \" << size  << \" extrinsic parameters.\";\n    LOG(INFO) << \"Avg euler angles: (\" << avg_roll/size << \", \" << avg_pitch/size << \", \" << avg_yaw/size << \")\";\n    LOG(INFO) << \"Avg trans: (\" << avg_tx/size << \", \" << avg_ty/size << \", \" << avg_tz/size << \")\";\n}\n\nvoid evaluateAntmanExt(const std::vector<Eigen::Matrix4d> &v_extrinsics, const std::string &eval_pattern){\n    Eigen::Matrix4d T_c0_c1_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd c0_c1_vec = Eigen::AngleAxisd(-90*M_PI/180.0, Eigen::Vector3d(0,-1,0));\n    Eigen::Vector3d t_c0_c1(0.05647, 0, -0.05647);\n    T_c0_c1_gt.block<3, 3>(0, 0) = c0_c1_vec.matrix();\n    T_c0_c1_gt.block<3, 1>(0, 3) = t_c0_c1;\n    Eigen::Matrix4d T_c0_c2_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd c0_c2_vec = Eigen::AngleAxisd(180*M_PI/180.0, Eigen::Vector3d(0,1,0));\n    Eigen::Vector3d t_c0_c2(0, 0, -0.11294);\n    T_c0_c2_gt.block<3, 3>(0, 0) = c0_c2_vec.matrix();\n    T_c0_c2_gt.block<3, 1>(0, 3) = t_c0_c2;\n    Eigen::Matrix4d T_c0_c3_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd c0_c3_vec = Eigen::AngleAxisd(-90*M_PI/180.0, Eigen::Vector3d(0,1,0));\n    Eigen::Vector3d t_c0_c3(-0.05647, 0, -0.05647);\n    T_c0_c3_gt.block<3, 3>(0, 0) = c0_c3_vec.matrix();\n    T_c0_c3_gt.block<3, 1>(0, 3) = t_c0_c3;\n\n    Eigen::Matrix4d T_c3_l0_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd c3_l0_vec1 = Eigen::AngleAxisd(-M_PI/4.0, -Eigen::Vector3d::UnitY());\n    Eigen::AngleAxisd c3_l0_vec2 = Eigen::AngleAxisd(M_PI/2.0, Eigen::Vector3d::UnitX());\n    Eigen::Matrix3d c3_l0_vec = c3_l0_vec2.matrix() * c3_l0_vec1.matrix();\n    Eigen::Vector3d t_c3_l0(-0.03887, -0.03887, 0.0593);\n    T_c3_l0_gt.block<3,3>(0, 0) = c3_l0_vec;\n    T_c3_l0_gt.block<3,1>(0, 3) = t_c3_l0;\n\n    Eigen::Matrix4d T_gt = Eigen::Matrix4d::Identity();\n    if (eval_pattern == \"camera0_to_camera1\")\n        T_gt = T_c0_c1_gt;\n    if (eval_pattern == \"camera0_to_camera2\")\n        T_gt = T_c0_c2_gt;\n    if (eval_pattern == \"camera0_to_camera3\")\n        T_gt = T_c0_c3_gt;\n    // it is lidar0-camera0 actually\n    if (eval_pattern == \"camera0_to_lidar0\")\n        T_gt = T_c3_l0_gt;\n\n    Eigen::Matrix3d R_gt = T_gt.block<3, 3>(0, 0);\n    Eigen::Vector3d v_gt_angles = R_gt.eulerAngles(2,1,0) * 180.0/M_PI;\n    LOG(INFO) << \"GT Euler angles(ZYX): \" << v_gt_angles.transpose() << \"\\n\";\n\n    double avg_roll = 0.0, avg_pitch = 0.0, avg_yaw = 0.0;\n    double avg_tx = 0, avg_ty = 0, avg_tz = 0.0;\n    for(size_t i = 0; i < v_extrinsics.size(); i++){\n        Eigen::Matrix4d T_ext = v_extrinsics[i];\n\n        Eigen::Matrix4d T_error = T_gt.inverse() * T_ext;\n\n        Eigen::Matrix3d R = T_ext.block<3, 3>(0, 0);\n        Eigen::Vector3d v_angles = R.eulerAngles(2,1,0) * 180.0/M_PI;\n        avg_yaw += (std::abs(v_angles[0]) > 90) ? (180 - std::abs(v_angles[0])) : std::abs(v_angles[0]);\n        avg_pitch += (std::abs(v_angles[1]) > 90) ? (180 - std::abs(v_angles[1])) : std::abs(v_angles[1]);\n        avg_roll += (std::abs(v_angles[2]) > 90) ? (180 - std::abs(v_angles[2])) : std::abs(v_angles[2]);\n        LOG(INFO) << eval_pattern << \" euler angles(ZYX): \" << v_angles.transpose() << \"\\n\";\n\n        Eigen::Vector3d t = T_ext.block<3,1>(0, 3);\n        avg_tx += t[0]; avg_ty += t[1]; avg_tz += t[2];\n        LOG(INFO) << eval_pattern << \" trans vector: \" << t.transpose() << \"\\n\";\n\n        Eigen::Matrix3d err_R = T_error.block<3, 3>(0, 0);\n        Eigen::Vector3d err_t = T_error.block<3, 1>(0, 3);\n        Eigen::AngleAxisd delta_R_vec(err_R);\n        LOG(INFO) << \" Rotation difference angle \"\n                    << delta_R_vec.angle() * 180.0 / M_PI << \"\\n\";\n        LOG(INFO) << \" Translation difference norm is \"\n                    << err_t.norm() << \"\\n\";\n    }\n\n    int size = v_extrinsics.size();\n    LOG(INFO) << \"Evaluate \" << size  << \" extrinsic parameters.\";\n    LOG(INFO) << \"Avg euler angles: (\" << avg_roll/size << \", \" << avg_pitch/size << \", \" << avg_yaw/size << \")\";\n    LOG(INFO) << \"Avg trans: (\" << avg_tx/size << \", \" << avg_ty/size << \", \" << avg_tz/size << \")\";\n}\n\nvoid evaluateKaleidoExt(const std::vector<Eigen::Matrix4d> &v_extrinsics, const std::string &eval_pattern){\n    Eigen::Matrix4d T_c0_c1_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd c0_c1_vec = Eigen::AngleAxisd(28*M_PI/180.0, Eigen::Vector3d(1,0,0));\n    Eigen::Vector3d t_c0_c1(0, 0.028, 0);\n    T_c0_c1_gt.block<3, 3>(0, 0) = c0_c1_vec.matrix();\n    T_c0_c1_gt.block<3, 1>(0, 3) = t_c0_c1;\n\n    Eigen::Matrix4d T_c0_l0_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd c0_l0_vec = Eigen::AngleAxisd(-14*M_PI/180.0, Eigen::Vector3d(1,0,0));\n    Eigen::Vector3d t_c0_l0(0, -0.014, 0.020);\n    T_c0_l0_gt.block<3, 3>(0, 0) = c0_l0_vec.matrix();\n    T_c0_l0_gt.block<3, 1>(0, 3) = t_c0_l0;\n\n    Eigen::Matrix4d T_gt = Eigen::Matrix4d::Identity();\n    if (eval_pattern == \"camera0_to_camera1\")\n        T_gt = T_c0_c1_gt;\n    if (eval_pattern == \"camera0_to_lidar0\")\n        T_gt = T_c0_l0_gt;\n\n    double avg_roll = 0.0, avg_pitch = 0.0, avg_yaw = 0.0;\n    double avg_tx = 0, avg_ty = 0, avg_tz = 0.0;\n    for(auto &T_ext : v_extrinsics){\n        Eigen::Matrix4d T_error = T_gt.inverse() * T_ext;\n\n        Eigen::Matrix3d R = T_ext.block<3, 3>(0, 0);\n        Eigen::Vector3d v_angles = R.eulerAngles(2,1,0) * 180.0/M_PI;\n        avg_yaw += (std::abs(v_angles[0]) > 90) ? (180 - std::abs(v_angles[0])) : std::abs(v_angles[0]);\n        avg_pitch += (std::abs(v_angles[1]) > 90) ? (180 - std::abs(v_angles[1])) : std::abs(v_angles[1]);\n        avg_roll += (std::abs(v_angles[2]) > 90) ? (180 - std::abs(v_angles[2])) : std::abs(v_angles[2]);\n        LOG(INFO) << eval_pattern << \" euler angles: \" << v_angles.transpose() << \"\\n\";\n\n        Eigen::Vector3d t = T_ext.block<3,1>(0, 3);\n        avg_tx += t[0]; avg_ty += t[1]; avg_tz += t[2];\n        LOG(INFO) << eval_pattern << \" trans vector: \" << t.transpose() << \"\\n\";\n        Eigen::Matrix3d err_R = T_error.block<3, 3>(0, 0);\n        Eigen::Vector3d err_t = T_error.block<3, 1>(0, 3);\n        Eigen::AngleAxisd delta_R_vec(err_R);\n        LOG(INFO) << \" Rotation difference angle \"\n                    << delta_R_vec.angle() * 180.0 / M_PI << \"\\n\";\n        LOG(INFO) << \" Translation difference norm is \"\n                    << err_t.norm() << \"\\n\";\n    }\n    int size = v_extrinsics.size();\n    LOG(INFO) << \"Evaluate \" << size  << \" extrinsic parameters.\";\n    LOG(INFO) << \"Avg euler angles: (\" << avg_roll/size << \", \" << avg_pitch/size << \", \" << avg_yaw/size << \")\";\n    LOG(INFO) << \"Avg trans: (\" << avg_tx/size << \", \" << avg_ty/size << \", \" << avg_tz/size << \")\";\n}\n\n// compare several camera poses or extrinsic params, to evaluate params consistency\nint main(int argc, char** argv){\n    \n    // This exe is used to analyze the exytrinsic calibration repeatability\n    if(argc < 2){\n        std::cerr <<\"Usage: ./test_eval_extrinsics [input_folder] [file_prefix]\\n\";\n        std::cout << \"[input_folder]: contains many extrinsic calibration result.\\n\";\n        std::cout << \"[file_prefix]: extrinsic file prefix, different sensor configuration results in different extrinsic file.\\n\";\n        return -1;\n    }\n\n    std::string dataset_folder(argv[1]);\n    std::string file_prefix(argv[2]);\n\n    std::vector<Eigen::Matrix4d> v_extrinsics;\n\n    bool b_eval_backpack = false, b_eval_antman = false, b_eval_kaleido = false;\n    if (dataset_folder.find(\"backpack\") != std::string::npos)\n        b_eval_backpack = true;\n    if (dataset_folder.find(\"antman\") != std::string::npos)\n        b_eval_antman = true;\n    if (dataset_folder.find(\"kaleido\") != std::string::npos)\n        b_eval_kaleido = true;\n        \n    for (const auto & entry : boost::filesystem::directory_iterator(dataset_folder)){\n        if(!boost::filesystem::is_directory(entry))\n            continue;\n\n        std::string extrin_filepath = entry.path().string() + \"/\" +file_prefix + \".yml\";\n        Eigen::Matrix4d T_ext = Eigen::Matrix4d::Identity();\n        if (common::loadExtFileOpencv(extrin_filepath, T_ext)){\n            LOG(INFO) << \"Read extrinsic parameters from \" << extrin_filepath;\n        }else{\n            LOG(ERROR) << \"Fail to load \" << extrin_filepath;\n            continue;\n        }\n        v_extrinsics.emplace_back(T_ext);\n    }\n\n    if (b_eval_backpack){\n    evaluateBackpackExt(v_extrinsics, file_prefix);\n    }else{\n        if (b_eval_antman){\n            evaluateAntmanExt(v_extrinsics, file_prefix);\n        }else{\n            evaluateKaleidoExt(v_extrinsics, file_prefix);\n        }\n    }\n    return 0;\n}", "meta": {"hexsha": "88ca2d67663971a5ae476789f2bb1ecaa918fc81", "size": 13647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_eval_extrinsics.cpp", "max_stars_repo_name": "alibaba/multiple-cameras-and-3D-LiDARs-extrinsic-calibration", "max_stars_repo_head_hexsha": "349bc8b954506721583b3571568fb8e23c2f1e83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2021-09-06T02:25:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T12:03:13.000Z", "max_issues_repo_path": "test/test_eval_extrinsics.cpp", "max_issues_repo_name": "alibaba/multiple-cameras-and-3D-LiDARs-extrinsic-calibration", "max_issues_repo_head_hexsha": "349bc8b954506721583b3571568fb8e23c2f1e83", "max_issues_repo_licenses": ["MIT"], "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_eval_extrinsics.cpp", "max_forks_repo_name": "alibaba/multiple-cameras-and-3D-LiDARs-extrinsic-calibration", "max_forks_repo_head_hexsha": "349bc8b954506721583b3571568fb8e23c2f1e83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T22:30:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:43:24.000Z", "avg_line_length": 44.7442622951, "max_line_length": 131, "alphanum_fraction": 0.6023301825, "num_tokens": 4699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5210722904918368}}
{"text": "#include <Eigen/Dense>\n#include <fcl/math/constants.h>\n#include <fcl/narrowphase/collision.h>\n#include <fcl/narrowphase/collision_object.h>\n#include <functional>\n#include <map>\n#include <string>\n#include <utility>\n#include <vector>\n\nusing fcl::AngleAxis;\nusing fcl::Transform3;\nusing fcl::Vector3;\nusing std::map;\nusing std::pair;\nusing std::string;\nusing std::vector;\n\n// Simple specification for defining a box collision object. Specifies the\n// dimensions and pose of the box in some frame F (X_FB). For an explanation\n// of the notation X_FB, see:\n// http://drake.mit.edu/doxygen_cxx/group__multibody__spatial__pose.html\ntemplate <typename S> struct BoxSpecification {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  Vector3<S> size;\n  Transform3<S> X_FB;\n};\n\nint main(int argc, char **argv) {\n  const double pi = fcl::constants<double>::pi();\n  const double size_1 = 1;\n  BoxSpecification<double> box_spec_1{\n      Vector3<double>{size_1, size_1, size_1},\n      Transform3<double>{\n          AngleAxis<double>(pi / 4, fcl::Vector3<double>::UnitY())}};\n\n  const double size_2 = 3;\n  BoxSpecification<double> box_spec_2{\n      fcl::Vector3<double>{size_2, size_2, size_2},\n      fcl::Transform3<double>{\n          fcl::Translation3<double>(fcl::Vector3<double>(0, 0, -size_2 / 2))}};\n\n  fcl::Vector3<double> expected_normal{0, 0, -1};\n  double expected_depth = size_1 * sqrt(2) / 2;\n\n  // Initialize isomorphic rotations of box 2.\n  map<string, fcl::Transform3<double>, std::less<string>,\n      Eigen::aligned_allocator<\n          std::pair<const string, fcl::Transform3<double>>>>\n      iso_poses;\n  iso_poses[\"top\"] = Transform3<double>::Identity();\n  iso_poses[\"bottom\"] =\n      Transform3<double>{AngleAxis<double>(pi, Vector3<double>::UnitX())};\n  iso_poses[\"back\"] =\n      Transform3<double>{AngleAxis<double>(pi / 2, Vector3<double>::UnitX())};\n  iso_poses[\"front\"] = Transform3<double>{\n      AngleAxis<double>(3 * pi / 2, Vector3<double>::UnitX())};\n  iso_poses[\"left\"] =\n      Transform3<double>{AngleAxis<double>(pi / 2, Vector3<double>::UnitY())};\n  iso_poses[\"right\"] = Transform3<double>{\n      AngleAxis<double>(3 * pi / 2, Vector3<double>::UnitY())};\n\n  fcl::Contact<double> expected_contact;\n  expected_contact.penetration_depth = expected_depth;\n\n  for (const auto &reorient_pair : iso_poses) {\n    const std::string &top_face = reorient_pair.first;\n    const fcl::Transform3<double> &pre_pose = reorient_pair.second;\n\n    BoxSpecification<double> box_2_posed{box_spec_2.size,\n                                         box_spec_2.X_FB * pre_pose};\n\n    // Collide (1, 2)\n    expected_contact.normal = expected_normal;\n    {\n      using CollisionGeometryPtr_t =\n          std::shared_ptr<fcl::CollisionGeometry<double>>;\n      CollisionGeometryPtr_t box_geometry_A(\n          new fcl::Box<double>(box_spec_1.size));\n      CollisionGeometryPtr_t box_geometry_B(\n          new fcl::Box<double>(box_spec_2.size));\n\n      fcl::CollisionObject<double> box_A(box_geometry_A, box_spec_1.X_FB);\n      fcl::CollisionObject<double> box_B(box_geometry_B, box_spec_2.X_FB);\n\n      // Compute collision - single contact and enable contact.\n      fcl::CollisionRequest<double> collisionRequest(1, true);\n      collisionRequest.gjk_solver_type = fcl::GST_LIBCCD;\n      fcl::CollisionResult<double> collisionResult;\n      fcl::collide(&box_A, &box_B, collisionRequest, collisionResult);\n      std::vector<fcl::Contact<double>> contacts;\n      collisionResult.getContacts(contacts);\n\n      const fcl::Contact<double> &contact = contacts[0];\n    }\n\n    // Collide (2, 1)\n    expected_contact.normal = -expected_normal;\n    {\n      using CollisionGeometryPtr_t =\n          std::shared_ptr<fcl::CollisionGeometry<double>>;\n      CollisionGeometryPtr_t box_geometry_A(\n          new fcl::Box<double>(box_spec_2.size));\n      CollisionGeometryPtr_t box_geometry_B(\n          new fcl::Box<double>(box_spec_1.size));\n\n      fcl::CollisionObject<double> box_A(box_geometry_A, box_spec_2.X_FB);\n      fcl::CollisionObject<double> box_B(box_geometry_B, box_spec_1.X_FB);\n\n      // Compute collision - single contact and enable contact.\n      fcl::CollisionRequest<double> collisionRequest(1, true);\n      collisionRequest.gjk_solver_type = fcl::GST_LIBCCD;\n      fcl::CollisionResult<double> collisionResult;\n      fcl::collide(&box_A, &box_B, collisionRequest, collisionResult);\n      std::vector<fcl::Contact<double>> contacts;\n      collisionResult.getContacts(contacts);\n\n      const fcl::Contact<double> &contact = contacts[0];\n    }\n    \n  }\n}\n", "meta": {"hexsha": "62360d766c1548e0ee3c1c9b535f1cd91fca0c48", "size": 4530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_package/test_package.cpp", "max_stars_repo_name": "rhololkeolke/conan-fcl", "max_stars_repo_head_hexsha": "f01ef5a960bed890925cc869b3900c8ebe717e1c", "max_stars_repo_licenses": ["MIT"], "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_package/test_package.cpp", "max_issues_repo_name": "rhololkeolke/conan-fcl", "max_issues_repo_head_hexsha": "f01ef5a960bed890925cc869b3900c8ebe717e1c", "max_issues_repo_licenses": ["MIT"], "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_package/test_package.cpp", "max_forks_repo_name": "rhololkeolke/conan-fcl", "max_forks_repo_head_hexsha": "f01ef5a960bed890925cc869b3900c8ebe717e1c", "max_forks_repo_licenses": ["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.8292682927, "max_line_length": 79, "alphanum_fraction": 0.691611479, "num_tokens": 1191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5210722895045152}}
{"text": "// Copyright 2008 Gunter Winkler <guwi17@gmx.de>\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// switch automatic singular check off\n#define BOOST_UBLAS_TYPE_CHECK 0\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/cstdlib.hpp>\n\n#include \"common/testhelper.hpp\"\n\n#include <iostream>\n#include <sstream>\n\nusing namespace boost::numeric::ublas;\nusing std::string;\n\nstatic const string matrix_IN = \"[3,3]((1,2,2),(2,3,3),(3,4,6))\\0\";\nstatic const string matrix_LU = \"[3,3]((3,4,6),(3.33333343e-01,6.66666627e-01,0),(6.66666687e-01,4.99999911e-01,-1))\\0\";\nstatic const string matrix_INV= \"[3,3]((-3,2,-7.94728621e-08),(1.50000012,0,-5.00000060e-01),(4.99999911e-01,-1,5.00000060e-01))\\0\";\nstatic const string matrix_PM = \"[3](2,2,2)\";\n\nint main () {\n\n  typedef float TYPE;\n\n  typedef matrix<TYPE> MATRIX;\n\n  MATRIX A;\n  MATRIX LU;\n  MATRIX INV;\n\n  {\n    std::istringstream is(matrix_IN);\n    is >> A;\n  }\n  {\n    std::istringstream is(matrix_LU);\n    is >> LU;\n  }\n  {\n    std::istringstream is(matrix_INV);\n    is >> INV;\n  }\n  permutation_matrix<>::vector_type temp;\n  {\n    std::istringstream is(matrix_PM);\n    is >> temp;\n  }\n  permutation_matrix<> PM(temp);\n\n  permutation_matrix<> pm(3);\n\n  int result = lu_factorize<MATRIX, permutation_matrix<> >(A, pm);\n\n  assertTrue(\"factorization completed: \", 0 == result);\n  assertTrue(\"LU factors are correct: \", compare(A, LU));\n  assertTrue(\"permutation is correct: \", compare(pm, PM));\n\n  MATRIX B = identity_matrix<TYPE>(A.size2());\n\n  lu_substitute(A, pm, B);\n\n  assertTrue(\"inverse is correct: \", compare(B, INV));\n\n  return (getResults().second > 0) ? boost::exit_failure : boost::exit_success;\n}\n", "meta": {"hexsha": "233e22b167d104af23931e0fd96e2c20a190f9bc", "size": 1803, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/numeric/ublas/test/test_lu.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/numeric/ublas/test/test_lu.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/numeric/ublas/test/test_lu.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": 25.3943661972, "max_line_length": 132, "alphanum_fraction": 0.6772046589, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5210722895045152}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\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#include <iostream>\n\n#include <geometry_test_common.hpp>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/geometry/algorithms/make.hpp>\n#include <boost/geometry/algorithms/append.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/multi_polygon.hpp>\n#include <boost/geometry/geometries/concepts/multi_polygon_concept.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <boost/geometry/io/dsv/write.hpp>\n\n#include <test_common/test_point.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\n#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n#include <initializer_list>\n#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n\ntemplate <typename P>\nbg::model::polygon<P> create_polygon()\n{   \n    bg::model::polygon<P> pl1;\n    P p1;\n    P p2;\n    P p3;\n    bg::assign_values(p1, 1, 2);\n    bg::assign_values(p2, 2, 0);\n    bg::assign_values(p3, 0, 0);\n    \n    bg::append(pl1, p1);\n    bg::append(pl1, p2);\n    bg::append(pl1, p3);\n    bg::append(pl1, p1);\n    return pl1;\n}\n\ntemplate <typename P, typename PL>\nbg::model::multi_polygon<PL> create_multi_polygon()\n{\n    bg::model::multi_polygon<PL> mpl1;\n    PL pl1(create_polygon<P>());\n    mpl1.push_back(pl1);\n    mpl1.push_back(pl1);\n    return mpl1;\n}\n\ntemplate <typename MPL, typename PL>\nvoid check_multi_polygon(MPL& to_check, PL pl1)\n{   \n    MPL cur;\n    cur.push_back(pl1);\n    cur.push_back(pl1);\n\n    std::ostringstream out1, out2;\n    out1 << bg::dsv(to_check);\n    out2 << bg::dsv(cur);\n    BOOST_CHECK_EQUAL(out1.str(), out2.str());\n}\n\ntemplate <typename P, typename PL>\nvoid test_default_constructor()\n{\n    bg::model::multi_polygon<PL> mpl1(create_multi_polygon<P, PL>());\n    check_multi_polygon(mpl1, PL(create_polygon<P>()));\n}\n\ntemplate <typename P, typename PL>\nvoid test_copy_constructor()\n{\n    bg::model::multi_polygon<PL> mpl1 = create_multi_polygon<P, PL>();\n    check_multi_polygon(mpl1, PL(create_polygon<P>()));\n}\n\ntemplate <typename P, typename PL>\nvoid test_copy_assignment()\n{\n    bg::model::multi_polygon<PL> mpl1(create_multi_polygon<P, PL>()), mpl2;\n    mpl2 = mpl1;\n    check_multi_polygon(mpl2, PL(create_polygon<P>()));\n}\n\ntemplate <typename PL>\nvoid test_concept()\n{   \n    typedef bg::model::multi_polygon<PL> MPL;\n\n    BOOST_CONCEPT_ASSERT( (bg::concepts::ConstMultiPolygon<MPL>) );\n    BOOST_CONCEPT_ASSERT( (bg::concepts::MultiPolygon<MPL>) );\n\n    typedef typename bg::coordinate_type<MPL>::type T;\n    typedef typename bg::point_type<MPL>::type PMPL;\n    boost::ignore_unused<T, PMPL>();\n}\n\ntemplate <typename P>\nvoid test_all()\n{   \n    typedef bg::model::polygon<P> PL;\n\n    test_default_constructor<P, PL>();\n    test_copy_constructor<P, PL>();\n    test_copy_assignment<P, PL>();\n    test_concept<PL>();\n}\n\ntemplate <typename P>\nvoid test_custom_multi_polygon(bg::model::polygon<P> IL)\n{   \n    typedef bg::model::polygon<P> PL;\n\n    std::initializer_list<PL> PIL = {IL};\n    bg::model::multi_polygon<PL> mpl1(PIL);\n    std::ostringstream out;\n    out << bg::dsv(mpl1);\n    BOOST_CHECK_EQUAL(out.str(), \"((((3, 3), (3, 0), (0, 0), (0, 3), (3, 3))))\");\n}\n\ntemplate <typename P>\nvoid test_custom()\n{   \n#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n    std::initializer_list<P> IL = {P(3, 3), P(3, 0), P(0, 0), P(0, 3), P(3, 3)};\n    bg::model::ring<P> r1(IL);\n    std::initializer_list<bg::model::ring<P> > RIL = {r1};\n    test_custom_multi_polygon<P>(RIL);\n#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n}\n\ntemplate <typename CS>\nvoid test_cs()\n{\n    test_all<bg::model::point<int, 2, CS> >();\n    test_all<bg::model::point<float, 2, CS> >();\n    test_all<bg::model::point<double, 2, CS> >();\n\n    test_custom<bg::model::point<double, 2, CS> >();\n}\n\n\nint test_main(int, char* [])\n{   \n    test_cs<bg::cs::cartesian>();\n    test_cs<bg::cs::spherical<bg::degree> >();\n    test_cs<bg::cs::spherical_equatorial<bg::degree> >();\n    test_cs<bg::cs::geographic<bg::degree> >();\n\n    test_custom<bg::model::d2::point_xy<double> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "f0c474db587d4b8f74d5b23b179b65f179d0408f", "size": 4512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/geometries/multi_polygon.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": "test/geometries/multi_polygon.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/geometry/test/geometries/multi_polygon.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 27.0179640719, "max_line_length": 81, "alphanum_fraction": 0.6883865248, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.520913255836737}}
{"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//[tiernan_girth_circumference\r\n#include <iostream>\r\n\r\n#include <boost/graph/directed_graph.hpp>\r\n#include <boost/graph/tiernan_all_cycles.hpp>\r\n\r\n#include \"helper.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\n\r\n// Declare the graph type and its vertex and edge types.\r\ntypedef directed_graph<> Graph;\r\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\r\ntypedef graph_traits<Graph>::edge_descriptor Edge;\r\n\r\nint\r\nmain(int argc, char *argv[])\r\n{\r\n    // Create the graph and read it from standard input.\r\n    Graph g;\r\n    read_graph(g, cin);\r\n\r\n    // Compute the girth and circumference simulataneously\r\n    size_t girth, circ;\r\n    boost::tie(girth, circ) = tiernan_girth_and_circumference(g);\r\n\r\n    // Print the result\r\n    cout << \"girth: \" << girth << endl;\r\n    cout << \"circumference: \" << circ << endl;\r\n\r\n    return 0;\r\n}\r\n//]\r\n", "meta": {"hexsha": "df8bf8b53910e49745f4c82605cb0179f11fa3ae", "size": 1076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/tiernan_girth_circumference.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/tiernan_girth_circumference.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/tiernan_girth_circumference.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": 26.243902439, "max_line_length": 66, "alphanum_fraction": 0.6923791822, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.520913242877407}}
{"text": "#include <basix/e-lagrange.h>\n#include <basix/quadrature.h>\n#include <boost/program_options.hpp>\n#include <cmath>\n#include <dolfinx.h>\n#include <dolfinx/io/XDMFFile.h>\n#include <iostream>\n\n#include <cublas_v2.h>\n#include <cuda_profiler_api.h>\n\n// Helper functions\n#include \"precompute.hpp\"\n#include <cuda/allocator.hpp>\n#include <cuda/array.hpp>\n#include <cuda/la.hpp>\n#include <cuda/scatter.hpp>\n#include <cuda/transform.hpp>\n#include <cuda/utils.hpp>\n\nusing namespace dolfinx;\nnamespace po = boost::program_options;\n\nvoid assert_cublas(cudaError_t e) {\n  if (e != cudaSuccess)\n    throw std::runtime_error(\" Unable to allocate memoy - cublas error\");\n}\nint main(int argc, char* argv[]) {\n\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()(\"help,h\", \"print usage message\")(\n      \"size\", po::value<std::size_t>()->default_value(32))(\n      \"degree\", po::value<int>()->default_value(1));\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(desc).allow_unregistered().run(),\n            vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << desc << \"\\n\";\n    return 0;\n  }\n\n  const std::size_t Nx = vm[\"size\"].as<std::size_t>();\n  const int degree = vm[\"degree\"].as<int>();\n\n  common::subsystem::init_logging(argc, argv);\n  common::subsystem::init_mpi(argc, argv);\n  {\n    // MPI\n    MPI_Comm mpi_comm{MPI_COMM_WORLD};\n    int rank = utils::set_device(mpi_comm);\n\n    // Create cublas handle\n    cublasHandle_t handle;\n    cublasCreate(&handle);\n\n    // Read mesh and mesh tags\n    std::array<std::array<double, 3>, 2> p = {{{0.0, 0.0, 0.0}, {1.0, 1.0, 1.0}}};\n    std::array<std::size_t, 3> n = {Nx, Nx, Nx};\n    auto mesh = std::make_shared<mesh::Mesh>(mesh::create_box(\n        mpi_comm, p, n, mesh::CellType::hexahedron, mesh::GhostMode::none));\n\n    // Create a Basix continuous Lagrange element of given degree\n    basix::FiniteElement e = basix::element::create_lagrange(\n        mesh::cell_type_to_basix_type(mesh::CellType::hexahedron), degree,\n        basix::element::lagrange_variant::equispaced, false);\n\n    // Create a scalar function space\n    std::shared_ptr<fem::FunctionSpace> V\n        = std::make_shared<fem::FunctionSpace>(fem::create_functionspace(mesh, e, 1));\n    auto idxmap = V->dofmap()->index_map;\n\n    int ncells = mesh->topology().index_map(3)->size_local();\n    int ndofs = e.dim();\n\n    fem::Function<double> u(V);\n    // Interpolate sin(2 \\pi x[0]) in the scalar Lagrange finite element space\n    constexpr double PI = xt::numeric_constants<double>::PI;\n    u.interpolate([PI](auto&& x) { return xt::sin(2 * PI * xt::row(x, 0)); });\n\n    CUDA::allocator<double> allocator{};\n    la::Vector<double, decltype(allocator)> x(idxmap, 1, allocator);\n    la::Vector<double, decltype(allocator)> y(idxmap, 1, allocator);\n\n    auto uarray = u.x()->array();\n    std::copy(uarray.begin(), uarray.end(), x.mutable_array().begin());\n\n    linalg::prefetch(0, x);\n    linalg::prefetch(0, y);\n\n    // =====================================\n    // Tabulate basis functions at quadrature points\n    // 1 - Tabulate quadrature points and weights\n    int q = 2 * degree; // Quadrature degree\n    auto cell = basix::cell::type::hexahedron;\n    auto quad = basix::quadrature::type::gauss_jacobi;\n    auto [points, weights] = basix::quadrature::make_quadrature(quad, cell, q);\n\n    std::int32_t nquads = weights.size();\n    std::int32_t Ne = ncells * ndofs;\n    std::int32_t Nq = ncells * nquads;\n\n    // 2 - Tabulate basis functions\n    xt::xtensor<double, 4> basis = e.tabulate(0, points);\n    xt::xtensor<double, 2> _phi = xt::view(basis, 0, xt::all(), xt::all(), 0);\n    cuda::array<double> phi(ndofs * nquads);\n    phi.set(_phi);\n    _phi = xt::transpose(_phi);\n    cuda::array<double> phiT(ndofs * nquads);\n    phiT.set(_phi);\n\n    // =====================================\n    // Get dofmap for the gather/scatter\n    // Copy dofmap data to device\n    cuda::array<std::int32_t> dofmap(Ne);\n    const std::vector<std::int32_t>& dof_array = V->dofmap()->list().array();\n    dofmap.set(dof_array);\n\n    // =====================================\n    // Compute determinant of jacobian at quadrature points\n    xt::xtensor<double, 4> J = compute_jacobian(mesh, points);\n    xt::xtensor<double, 2> _detJ = compute_jacobian_determinant(J);\n    for (std::size_t i = 0; i < _detJ.shape(0); i++)\n      for (std::size_t j = 0; j < _detJ.shape(1); j++)\n        _detJ(i, j) = _detJ(i, j) * weights[j];\n    cuda::array<double> detJ(Nq);\n    detJ.set(_detJ);\n\n    // Allocate memory for working arrays on device\n    cuda::array<double> ue(Ne);\n    cuda::array<double> uq(Nq);\n    cuda::array<double> xe(Ne);\n\n    double alpha = 1;\n    double beta = 0;\n\n    double t = MPI_Wtime();\n    // =====================================\n    // Apply gather operator Ue = G u\n    // Ue <- u[dofmap]\n    // From global dof vector to element based dof vector\n    gather(ue.size(), dofmap.data(), x.array().data(), ue.data(), 512);\n\n    // =====================================\n    // Apply operator B^T D B to Ue\n    // Uq^ = B Ue^T\n    cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, nquads, ncells, ndofs, &alpha,\n                phiT.data(), nquads, ue.data(), ndofs, &beta, uq.data(), nquads);\n    // Uq = detJ .* Uq\n    transform1(Ne, uq.data(), detJ.data(), uq.data(), 512);\n    // Xe^T = B^T Uq^T\n    cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, ndofs, ncells, nquads, &alpha,\n                phi.data(), ndofs, uq.data(), nquads, &beta, xe.data(), ndofs);\n    // =====================================\n    // Apply scatter operator\n    // x[dofmap] <- Xe\n    // From element based dof vector to global dof vector\n    scatter(xe.size(), dofmap.data(), xe.data(), y.mutable_array().data(), 512);\n    cudaDeviceSynchronize();\n    t = MPI_Wtime() - t;\n\n    std::cout << y.norm() << std::endl;\n\n    std::cout << \"Number of cells: \" << ncells;\n    std::cout << \"\\nNumber of dofs: \" << ndofs;\n    std::cout << \"\\nNumber of quads: \" << nquads;\n    double ops = 4 * ncells * nquads * ndofs + ncells * nquads;\n    std::cout << \"\\n#Elapsed Time: \" << t << std::endl;\n    std::cout << \"\\nDOF/s: \" << V->dofmap()->index_map->size_local() / t;\n    std::cout << std::endl;\n  }\n\n  common::subsystem::finalize_mpi();\n  return 0;\n}\n", "meta": {"hexsha": "7aacbdaf5a64e36136f57488121871ac0ddeb3f7", "size": 6268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo/gpu_operator/main.cpp", "max_stars_repo_name": "Excalibur-SLE/wave-fenics", "max_stars_repo_head_hexsha": "2d3345c4cffecbe382acd1005a9dcc2bbc62ad1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-27T23:36:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T23:36:14.000Z", "max_issues_repo_path": "demo/gpu_operator/main.cpp", "max_issues_repo_name": "Excalibur-SLE/wave-fenics", "max_issues_repo_head_hexsha": "2d3345c4cffecbe382acd1005a9dcc2bbc62ad1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2022-02-23T13:22:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T12:40:10.000Z", "max_forks_repo_path": "demo/gpu_operator/main.cpp", "max_forks_repo_name": "Excalibur-SLE/wave-fenics", "max_forks_repo_head_hexsha": "2d3345c4cffecbe382acd1005a9dcc2bbc62ad1c", "max_forks_repo_licenses": ["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.2134831461, "max_line_length": 89, "alphanum_fraction": 0.6051372049, "num_tokens": 1871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6187804478040616, "lm_q1q2_score": 0.5209052460682131}}
{"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 *\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 <libint2/initialize.h>\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE aomatrix_test\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// Local VOTCA includes\n#include \"votca/xtp/aomatrix.h\"\n#include \"votca/xtp/orbitals.h\"\n#include <votca/tools/eigenio_matrixmarket.h>\n\nusing namespace votca::xtp;\nusing namespace votca;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(aomatrix_test)\n\nQMMolecule Methane() {\n\n  QMMolecule mol(\" \", 0);\n  mol.LoadFromFile(std::string(XTP_TEST_DATA_FOLDER) +\n                   \"/aomatrix/molecule.xyz\");\n  return mol;\n}\n\nBOOST_AUTO_TEST_CASE(aomatrices_test) {\n  libint2::initialize();\n  QMMolecule mol = Methane();\n  BasisSet basis;\n  basis.Load(std::string(XTP_TEST_DATA_FOLDER) + \"/aomatrix/3-21G.xml\");\n  AOBasis aobasis;\n  aobasis.Fill(basis, mol);\n  AOOverlap overlap;\n  overlap.Fill(aobasis);\n  Eigen::MatrixXd overlap_ref = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/aomatrix/overlap_ref.mm\");\n\n  bool check_overlap = overlap.Matrix().isApprox(overlap_ref, 0.0001);\n  BOOST_CHECK_EQUAL(check_overlap, 1);\n  if (!check_overlap) {\n    cout << \"ref\" << endl;\n    cout << overlap_ref << endl;\n    cout << \"result\" << endl;\n    cout << overlap.Matrix() << endl;\n  }\n\n  AOKinetic kinetic;\n  kinetic.Fill(aobasis);\n  Eigen::MatrixXd kinetic_ref = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/aomatrix/kinetic_ref.mm\");\n\n  bool check_kinetic = kinetic.Matrix().isApprox(kinetic_ref, 0.00001);\n  BOOST_CHECK_EQUAL(check_kinetic, 1);\n  if (!check_kinetic) {\n    cout << \"ref\" << endl;\n    cout << kinetic_ref << endl;\n    cout << \"result\" << endl;\n    cout << kinetic.Matrix() << endl;\n  }\n\n  AOCoulomb coulomb;\n  coulomb.Fill(aobasis);\n  Eigen::MatrixXd coulomb_ref = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/aomatrix/coulomb_ref.mm\");\n  bool check_coulomb = coulomb.Matrix().isApprox(coulomb_ref, 0.00001);\n  BOOST_CHECK_EQUAL(check_coulomb, 1);\n  if (!check_coulomb) {\n    cout << \"ref\" << endl;\n    cout << coulomb_ref << endl;\n    cout << \"result\" << endl;\n    cout << coulomb.Matrix() << endl;\n  }\n\n  Eigen::MatrixXd ps_invSqrt = coulomb.Pseudo_InvSqrt(1e-7);\n  Eigen::MatrixXd coulombinvsqrt_ref =\n      votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n          std::string(XTP_TEST_DATA_FOLDER) +\n          \"/aomatrix/coulombinvsqrt_ref.mm\");\n\n  bool check_coulombinvsqrt = ps_invSqrt.isApprox(coulombinvsqrt_ref, 0.00001);\n  BOOST_CHECK_EQUAL(check_coulombinvsqrt, 1);\n  if (!check_coulombinvsqrt) {\n    cout << \"ref\" << endl;\n    cout << coulombinvsqrt_ref << endl;\n    cout << \"result\" << endl;\n    cout << ps_invSqrt << endl;\n  }\n\n  Eigen::MatrixXd ps_invSqrtgw = coulomb.Pseudo_InvSqrt_GWBSE(overlap, 1e-7);\n  Eigen::MatrixXd coulombinvsqrtgw_ref =\n      votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n          std::string(XTP_TEST_DATA_FOLDER) +\n          \"/aomatrix/coulombinvsqrtgw_ref.mm\");\n\n  bool check_coulombinvsqrtgw =\n      ps_invSqrtgw.isApprox(coulombinvsqrtgw_ref, 0.00001);\n\n  BOOST_CHECK_EQUAL(check_coulombinvsqrtgw, 1);\n  if (!check_coulombinvsqrtgw) {\n    cout << \"ref\" << endl;\n    cout << coulombinvsqrtgw_ref << endl;\n    cout << \"result\" << endl;\n    cout << ps_invSqrtgw << endl;\n  }\n  libint2::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(aomatrices_contracted_test) {\n  libint2::initialize();\n  QMMolecule mol(\"C\", 0);\n  mol.LoadFromFile(std::string(XTP_TEST_DATA_FOLDER) + \"/aomatrix/C.xyz\");\n  BasisSet basis;\n  basis.Load(std::string(XTP_TEST_DATA_FOLDER) + \"/aomatrix/contracted.xml\");\n  AOBasis aobasis;\n  aobasis.Fill(basis, mol);\n  AOOverlap overlap;\n  overlap.Fill(aobasis);\n  Eigen::MatrixXd overlap_ref = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) +\n      \"/aomatrix/overlap_ref_contracted.mm\");\n\n  bool check_overlap = overlap.Matrix().isApprox(overlap_ref, 0.0001);\n  if (!check_overlap) {\n    std::cout << std::endl;\n    std::cout << \"Ref\" << std::endl;\n    std::cout << overlap_ref << std::endl;\n    std::cout << \"Result\" << std::endl;\n    std::cout << overlap.Matrix() << std::endl;\n  }\n  BOOST_CHECK_EQUAL(check_overlap, 1);\n  libint2::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(aocoulomb_inv_test) {\n  libint2::initialize();\n  QMMolecule mol = Methane();\n  BasisSet basis;\n  basis.Load(std::string(XTP_TEST_DATA_FOLDER) + \"/aomatrix/3-21G.xml\");\n  AOBasis aobasis;\n  aobasis.Fill(basis, mol);\n\n  AOCoulomb cou;\n  cou.Fill(aobasis);\n\n  Eigen::MatrixXd PseudoInvSqrt = cou.Pseudo_InvSqrt(1e-7);\n\n  Eigen::MatrixXd Reformed = PseudoInvSqrt * PseudoInvSqrt * cou.Matrix();\n\n  bool check_inv = Reformed.isApprox(Eigen::MatrixXd::Identity(17, 17), 0.0001);\n  if (!check_inv) {\n    std::cout << \"reformed\" << endl;\n    std::cout << Reformed << endl;\n  }\n  BOOST_CHECK_EQUAL(check_inv, 1);\n  libint2::finalize();\n}\n\n/*BOOST_AUTO_TEST_CASE(large_l_test) {\n\n  QMMolecule mol(\"C\", 0);\n  mol.LoadFromFile(std::string(XTP_TEST_DATA_FOLDER) + \"/aomatrix/C2.xyz\");\n\n  BasisSet basisset;\n  basisset.Load(std::string(XTP_TEST_DATA_FOLDER) + \"/aomatrix/G.xml\");\n\n  BasisSet auxbasisset;\n  auxbasisset.Load(std::string(XTP_TEST_DATA_FOLDER) + \"/aomatrix/I.xml\");\n  AOBasis dftbasis;\n  dftbasis.Fill(basisset, mol);\n\n  AOBasis auxbasis;\n  auxbasis.Fill(auxbasisset, mol);\n\n  AOOverlap overlap;\n  overlap.Fill(auxbasis);\n\n  Eigen::MatrixXd overlap_ref = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/aomatrix/overlap_ref_gi.mm\");\n\n  bool check_overlap = overlap.Matrix().isApprox(overlap_ref, 0.00001);\n\n  BOOST_CHECK_EQUAL(check_overlap, 1);\n  if (!check_overlap) {\n    cout << \"ref\" << endl;\n    cout << overlap_ref << endl;\n    cout << \"result\" << endl;\n    cout << overlap.Matrix() << endl;\n  }\n\n  AOCoulomb coulomb;\n  coulomb.Fill(auxbasis);\n  Eigen::MatrixXd coulomb_ref = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/aomatrix/coulomb_ref_gi.mm\");\n\n  bool check_coulomb = coulomb.Matrix().isApprox(coulomb_ref, 0.00001);\n  BOOST_CHECK_EQUAL(check_coulomb, 1);\n  if (!check_coulomb) {\n    cout << \"ref\" << endl;\n    cout << coulomb_ref << endl;\n    cout << \"result\" << endl;\n    cout << coulomb.Matrix() << endl;\n  }\n\n  AOKinetic kinetic;\n  kinetic.Fill(dftbasis);\n\n  Eigen::MatrixXd kinetic_ref = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/aomatrix/kinetic_ref_gi.mm\");\n\n  bool check_kinetic = kinetic.Matrix().isApprox(kinetic_ref, 0.00001);\n\n  BOOST_CHECK_EQUAL(check_kinetic, 1);\n  if (!check_kinetic) {\n    cout << \"ref\" << endl;\n    cout << kinetic_ref << endl;\n    cout << \"result\" << endl;\n    cout << kinetic.Matrix() << endl;\n  }\n} */\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "2df9ae28b1f6e466178eef52e2ae10f23b097755", "size": 7381, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_aomatrix.cc", "max_stars_repo_name": "rubengerritsen/xtp", "max_stars_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "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_aomatrix.cc", "max_issues_repo_name": "rubengerritsen/xtp", "max_issues_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "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_aomatrix.cc", "max_forks_repo_name": "rubengerritsen/xtp", "max_forks_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "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.8828451883, "max_line_length": 80, "alphanum_fraction": 0.696518087, "num_tokens": 2170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5209052440540788}}
{"text": "/*\nIn this tutorial we will learn how to use the pcl::MomentOfInertiaEstimation class \nin order to obtain descriptors based on eccentricity and moment of inertia.\nThis class also allows to extract axis aligned and oriented bounding boxes of the cloud. \nBut keep in mind that extracted OBB is not the minimal possible bounding box.\n*/\n\n#include \"stdafx.h\"\n#include <iostream>\n#include <boost/thread/thread.hpp>\n#include <pcl/point_types.h>\n#include <pcl/features/moment_of_inertia_estimation.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include \"KinnectGrabber.h\"\n\nint main()\n{\n\tpcl::io::OpenNI2Grabber grabber;\n\tKinnectGrabber<pcl::PointXYZRGBA> v(grabber);\n\tv.run();\n\n\tpcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr cloud(new pcl::PointCloud<pcl::PointXYZRGBA>);\n\tcloud = v.getLatestCloud();\n\n\tif (cloud == nullptr)\n\t{\n\t\tstd::cout << \"Get cloud failed!\" << std::endl;\n\t}\n\telse\n\t{\n\t\t// create moment estimator and extratct\n\t\tpcl::MomentOfInertiaEstimation<pcl::PointXYZRGBA> feature_extractor;\n\t\tfeature_extractor.setInputCloud(cloud);\n\t\tfeature_extractor.compute();\n\n\t\t// define moment and eccentricity etc variable\n\t\tstd::vector<float> moment_of_intertia;\n\t\tstd::vector<float> eccentricity;\n\t\tpcl::PointXYZRGBA min_point_AABB;\n\t\tpcl::PointXYZRGBA max_point_AABB;\n\t\tpcl::PointXYZRGBA min_point_OBB;\n\t\tpcl::PointXYZRGBA max_point_OBB;\n\t\tpcl::PointXYZRGBA position_OBB;\n\t\tEigen::Matrix3f  rotational_matrix_OBB;\n\t\tfloat major_value, middle_value, minor_value;\n\t\tEigen::Vector3f major_vector, middle_vector, minor_vector;\n\t\tEigen::Vector3f mass_center;\n\n\t\t// get moment and eccentricity\n\t\tfeature_extractor.getMomentOfInertia(moment_of_intertia);\n\t\tfeature_extractor.getEccentricity(eccentricity);\n\t\tfeature_extractor.getAABB(min_point_AABB, max_point_AABB);\n\t\tfeature_extractor.getOBB(min_point_OBB, max_point_OBB, position_OBB, rotational_matrix_OBB);\n\t\tfeature_extractor.getEigenValues(major_value, middle_value, minor_value);\n\t\tfeature_extractor.getEigenVectors(major_vector, middle_vector, minor_vector);\n\t\tfeature_extractor.getMassCenter(mass_center);\n\n\t\tboost::shared_ptr<pcl::visualization::PCLVisualizer> viewer(new pcl::visualization::PCLVisualizer(\"3D viewer\"));\n\t\tviewer->setBackgroundColor(0, 0, 0);\n\t\tviewer->addCoordinateSystem(1.0);\n\t\tviewer->initCameraParameters();\n\t\tviewer->addPointCloud<pcl::PointXYZRGBA>(cloud, \"sample cloud\");\n\t\tviewer->addCube(min_point_AABB.x, max_point_AABB.x, min_point_AABB.y, max_point_AABB.y, min_point_AABB.z, max_point_AABB.z, 1.0, 1.0, 0.0, \"AABB\");\n\n\t\tEigen::Vector3f position(position_OBB.x, position_OBB.y, position_OBB.z);\n\t\tEigen::Quaternionf quat(rotational_matrix_OBB);\n\t\tviewer->addCube(position, quat, max_point_OBB.x - min_point_OBB.x, max_point_OBB.y - min_point_OBB.y, max_point_OBB.z - min_point_OBB.z, \"OBB\");\n\n\t\tpcl::PointXYZ center(mass_center(0), mass_center(1), mass_center(2));\n\t\tpcl::PointXYZ x_axis(major_vector(0) + mass_center(0), major_vector(1) + mass_center(1), major_vector(2) + mass_center(2));\n\t\tpcl::PointXYZ y_axis(middle_vector(0) + mass_center(0), middle_vector(1) + mass_center(1), middle_vector(2) + mass_center(2));\n\t\tpcl::PointXYZ z_axis(minor_vector(0) + mass_center(0), minor_vector(1) + mass_center(1), minor_vector(2) + mass_center(2));\n\t\tviewer->addLine(center, x_axis, 1.0f, 0.0f, 0.0f, \"major eigen vector\");\n\t\tviewer->addLine(center, y_axis, 0.0f, 1.0f, 0.0f, \"middle eigen vector\");\n\t\tviewer->addLine(center, z_axis, 0.0f, 0.0f, 1.0f, \"minor eigen vector\");\n\n\t\twhile (!viewer->wasStopped())\n\t\t{\n\t\t\tviewer->spinOnce(100);\n\t\t\tboost::this_thread::sleep(boost::posix_time::microseconds(100000));\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "60808ec7164cc2f71b96d3120a22e86a4972d5fd", "size": 3611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Features/MomentOfInertiaEstimation .cpp", "max_stars_repo_name": "QuMIke/PracticePCL", "max_stars_repo_head_hexsha": "efe947607516d28c176721c9930be049b50ad18a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Features/MomentOfInertiaEstimation .cpp", "max_issues_repo_name": "QuMIke/PracticePCL", "max_issues_repo_head_hexsha": "efe947607516d28c176721c9930be049b50ad18a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Features/MomentOfInertiaEstimation .cpp", "max_forks_repo_name": "QuMIke/PracticePCL", "max_forks_repo_head_hexsha": "efe947607516d28c176721c9930be049b50ad18a", "max_forks_repo_licenses": ["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.988372093, "max_line_length": 149, "alphanum_fraction": 0.763777347, "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5209052391430228}}
{"text": "#include \"Utilities/DBC.hh\"\n#include <Eigen/Dense>\n#include <iostream>\n\nnamespace Spheral {\n\n//------------------------------------------------------------------------------\n// Default constructor\n//------------------------------------------------------------------------------\ninline\nBiQuadraticInterpolator::BiQuadraticInterpolator():\n  mnx1(),\n  mny1(),\n  mxmin(),\n  mxmax(),\n  mymin(),\n  mymax(),\n  mxstep(),\n  mystep(),\n  mcoeffs() {\n}\n\n//------------------------------------------------------------------------------\n// Construct with tabulated data\n//------------------------------------------------------------------------------\ntemplate<typename Func>\nBiQuadraticInterpolator::BiQuadraticInterpolator(const double xmin,\n                                                 const double xmax,\n                                                 const double ymin,\n                                                 const double ymax,\n                                                 const size_t nx,\n                                                 const size_t ny,\n                                                 const Func& F):\n  mnx1(),\n  mny1(),\n  mxmin(),\n  mxmax(),\n  mxstep(),\n  mcoeffs() {\n  this->initialize(xmin, xmax, ymin, ymax, nx, ny, F);\n}\n\n//------------------------------------------------------------------------------\n// Destructor\n//------------------------------------------------------------------------------\ninline\nBiQuadraticInterpolator::~BiQuadraticInterpolator() {\n}\n\n//------------------------------------------------------------------------------\n// Initialize the interpolation to fit the given data\n//------------------------------------------------------------------------------\ntemplate<typename Func>\ninline\nvoid\nBiQuadraticInterpolator::initialize(const double xmin,\n                                    const double xmax,\n                                    const double ymin,\n                                    const double ymax,\n                                    const size_t nx,\n                                    const size_t ny,\n                                    const Func& F) {\n\n  // Size stuff up.\n  REQUIRE(nx > 2u);\n  REQUIRE(ny > 2u);\n  mnx1 = nx - 2u;\n  mny1 = ny - 2u;\n  mcoeffs.resize(6*mnx1*mny1);\n\n  // Figure out the sampling steps.\n  mxmin = xmin;\n  mxmax = xmax;\n  mymin = ymin;\n  mymax = ymax;\n  mxstep = (xmax - xmin)/(nx - 1u);\n  mystep = (ymax - ymin)/(ny - 1u);\n\n  // Fit the coefficients\n  Eigen::Vector2d x00, x01, x02, x10, x11, x12, x20, x21, x22;\n  Eigen::MatrixXd A(9, 6);\n  Eigen::VectorXd b(9), c(9);\n  for (auto i = 0u; i < mnx1; ++i) {\n    for (auto j = 0u; j < mny1; ++j) {\n      x00 = {xmin + i      *mxstep, ymin + j      *mystep};\n      x10 = {xmin + (i + 1)*mxstep, ymin + j      *mystep};\n      x20 = {xmin + (i + 2)*mxstep, ymin + j      *mystep};\n      x01 = {xmin + i      *mxstep, ymin + (j + 1)*mystep};\n      x11 = {xmin + (i + 1)*mxstep, ymin + (j + 1)*mystep};\n      x21 = {xmin + (i + 2)*mxstep, ymin + (j + 1)*mystep};\n      x02 = {xmin + i      *mxstep, ymin + (j + 2)*mystep};\n      x12 = {xmin + (i + 1)*mxstep, ymin + (j + 2)*mystep};\n      x22 = {xmin + (i + 2)*mxstep, ymin + (j + 2)*mystep};\n      A << 1.0, x00[0], x00[1], x00[0]*x00[1], x00[0]*x00[0], x00[1]*x00[1],\n           1.0, x01[0], x01[1], x01[0]*x01[1], x01[0]*x01[0], x01[1]*x01[1],\n           1.0, x02[0], x02[1], x02[0]*x02[1], x02[0]*x02[0], x02[1]*x02[1],\n           1.0, x10[0], x10[1], x10[0]*x10[1], x10[0]*x10[0], x10[1]*x10[1],\n           1.0, x11[0], x11[1], x11[0]*x11[1], x11[0]*x11[0], x11[1]*x11[1],\n           1.0, x12[0], x12[1], x12[0]*x12[1], x12[0]*x12[0], x12[1]*x12[1],\n           1.0, x20[0], x20[1], x20[0]*x20[1], x20[0]*x20[0], x20[1]*x20[1],\n           1.0, x21[0], x21[1], x21[0]*x21[1], x21[0]*x21[0], x21[1]*x21[1],\n           1.0, x22[0], x22[1], x22[0]*x22[1], x22[0]*x22[0], x22[1]*x22[1];\n      b << F(x00[0], x00[1]),\n           F(x01[0], x01[1]),\n           F(x02[0], x02[1]),\n           F(x10[0], x10[1]),\n           F(x11[0], x11[1]),\n           F(x12[0], x12[1]),\n           F(x20[0], x20[1]),\n           F(x21[0], x21[1]),\n           F(x22[0], x22[1]);\n      CHECK2(b == b, \"BiQuadraticInterpoolator function return error: \\n\"\n             << x00 << \" : \" << b[0] << \"\\n\"\n             << x01 << \" : \" << b[1] << \"\\n\"\n             << x02 << \" : \" << b[2] << \"\\n\"\n             << x10 << \" : \" << b[3] << \"\\n\"\n             << x11 << \" : \" << b[4] << \"\\n\"\n             << x12 << \" : \" << b[5] << \"\\n\"\n             << x20 << \" : \" << b[6] << \"\\n\"\n             << x21 << \" : \" << b[7] << \"\\n\"\n             << x22 << \" : \" << b[8] << \"\\n\");\n      c = A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n      // std::cerr << \"------------------------------------------------------------------------------\\n\"\n      //           << \"x00: \" << x00 << \"\\n\"\n      //           << \"x10: \" << x10 << \"\\n\"\n      //           << \"x20: \" << x20 << \"\\n\"\n      //           << \"x01: \" << x01 << \"\\n\"\n      //           << \"x11: \" << x11 << \"\\n\"\n      //           << \"x21: \" << x21 << \"\\n\"\n      //           << \"x02: \" << x02 << \"\\n\"\n      //           << \"x12: \" << x12 << \"\\n\"\n      //           << \"x22: \" << x22 << \"\\n\"\n      //           << \"A:\\n\" << A << \"\\n\"\n      //           << \"b:\\n\" << b << \"\\n\"\n      //           << \"c:\\n\" << c << \"\\n\";\n      const auto k = 6*(i + j*mnx1);\n      mcoeffs[k    ] = c(0);\n      mcoeffs[k + 1] = c(1);\n      mcoeffs[k + 2] = c(2);\n      mcoeffs[k + 3] = c(3);\n      mcoeffs[k + 4] = c(4);\n      mcoeffs[k + 5] = c(5);\n    }\n  }\n}\n\n//------------------------------------------------------------------------------\n// Interpolate for the given coordinate.\n//------------------------------------------------------------------------------\ninline\ndouble\nBiQuadraticInterpolator::operator()(const double xi,\n                                    const double yi) const {\n  const auto x = std::max(mxmin, std::min(mxmax, xi));\n  const auto y = std::max(mymin, std::min(mymax, yi));\n  const auto i0 = lowerBound(x, y);\n  // std::cerr << \"================================================================================\\n\"\n  //           << \"mxlog, mylog : \" << mxlog << \" \" << mylog << \"\\n\"\n  //           << \"pos   : \" << pos << \"\\n\"\n  //           << \"(x,y) : \" << x << \" \" << y << \"\\n\"\n  //           << \"i0    : \" << i0 << \"\\n\"\n  //           << \"coeffs: \" << mcoeffs[i0] << \" \" << mcoeffs[i0 + 1] << \" \" << mcoeffs[i0 + 2] << \" \" << mcoeffs[i0 + 3] << \" \" << mcoeffs[i0 + 4] << \" \" << mcoeffs[i0 + 5] << \"\\n\"\n  //           << \"F(x,y): \" << mcoeffs[i0] + mcoeffs[i0 + 1]*x + mcoeffs[i0 + 2]*y + mcoeffs[i0 + 3]*x*y + mcoeffs[i0 + 4]*x*x + mcoeffs[i0 + 5]*y*y << \"\\n\";\n  return mcoeffs[i0] + mcoeffs[i0 + 1]*x + mcoeffs[i0 + 2]*y + mcoeffs[i0 + 3]*x*y + mcoeffs[i0 + 4]*x*x + mcoeffs[i0 + 5]*y*y;\n}\n\n//------------------------------------------------------------------------------\n// Interpolate for the gradient (x)\n//------------------------------------------------------------------------------\ninline\ndouble\nBiQuadraticInterpolator::prime_x(const double xi, const double yi) const {\n  const auto x = std::max(mxmin, std::min(mxmax, xi));\n  const auto y = std::max(mymin, std::min(mymax, yi));\n  const auto i0 = lowerBound(x, y);\n  return mcoeffs[i0 + 1] + mcoeffs[i0 + 3]*y + 2.0*mcoeffs[i0 + 4]*x;\n}\n\n//------------------------------------------------------------------------------\n// Interpolate for the gradient (y)\n//------------------------------------------------------------------------------\ninline\ndouble\nBiQuadraticInterpolator::prime_y(const double xi, const double yi) const {\n  const auto x = std::max(mxmin, std::min(mxmax, xi));\n  const auto y = std::max(mymin, std::min(mymax, yi));\n  const auto i0 = lowerBound(x, y);\n  return mcoeffs[i0 + 2] + mcoeffs[i0 + 3]*x + 2.0*mcoeffs[i0 + 5]*y;\n}\n\n//------------------------------------------------------------------------------\n// Interpolate for the gradient2 (xx)\n//------------------------------------------------------------------------------\ninline\ndouble\nBiQuadraticInterpolator::prime2_xx(const double xi, const double yi) const {\n  const auto x = std::max(mxmin, std::min(mxmax, xi));\n  const auto y = std::max(mymin, std::min(mymax, yi));\n  const auto i0 = lowerBound(x, y);\n  return 2.0*mcoeffs[i0 + 4];\n}\n\n//------------------------------------------------------------------------------\n// Interpolate for the gradient2 (xy)\n//------------------------------------------------------------------------------\ninline\ndouble\nBiQuadraticInterpolator::prime2_xy(const double xi, const double yi) const {\n  const auto x = std::max(mxmin, std::min(mxmax, xi));\n  const auto y = std::max(mymin, std::min(mymax, yi));\n  const auto i0 = lowerBound(x, y);\n  return mcoeffs[i0 + 3];\n}\n\n//------------------------------------------------------------------------------\n// Interpolate for the gradient2 (yx)\n//------------------------------------------------------------------------------\ninline\ndouble\nBiQuadraticInterpolator::prime2_yx(const double xi, const double yi) const {\n  const auto x = std::max(mxmin, std::min(mxmax, xi));\n  const auto y = std::max(mymin, std::min(mymax, yi));\n  const auto i0 = lowerBound(x, y);\n  return mcoeffs[i0 + 3];\n}\n\n//------------------------------------------------------------------------------\n// Interpolate for the gradient2 (yy)\n//------------------------------------------------------------------------------\ninline\ndouble\nBiQuadraticInterpolator::prime2_yy(const double xi, const double yi) const {\n  const auto x = std::max(mxmin, std::min(mxmax, xi));\n  const auto y = std::max(mymin, std::min(mymax, yi));\n  const auto i0 = lowerBound(x, y);\n  return 2.0*mcoeffs[i0 + 5];\n}\n\n//------------------------------------------------------------------------------\n// Return the lower bound entry in the table for the given x coordinate\n//------------------------------------------------------------------------------\ninline\nsize_t\nBiQuadraticInterpolator::lowerBound(const double x, const double y) const {\n  const auto result = 6u*(mnx1*std::min(mny1 - 1u, size_t(std::max(0.0, y - mymin)/mystep)) +\n                               std::min(mnx1 - 1u, size_t(std::max(0.0, x - mxmin)/mxstep)));\n  ENSURE(result <= 6u*mnx1*mny1);\n  return result;\n}\n\n//------------------------------------------------------------------------------\n// Data accessors\n//------------------------------------------------------------------------------\ninline\nsize_t\nBiQuadraticInterpolator::size() const {\n  return mcoeffs.size();\n}\n\ninline\ndouble\nBiQuadraticInterpolator::xmin() const {\n  return mxmin;\n}\n\ninline\ndouble\nBiQuadraticInterpolator::xmax() const {\n  return mxmax;\n}\n\ninline\ndouble\nBiQuadraticInterpolator::ymin() const {\n  return mymin;\n}\n\ninline\ndouble\nBiQuadraticInterpolator::ymax() const {\n  return mymax;\n}\n\ninline\ndouble\nBiQuadraticInterpolator::xstep() const {\n  return mxstep;\n}\n\ninline\ndouble\nBiQuadraticInterpolator::ystep() const {\n  return mystep;\n}\n\ninline\nconst std::vector<double>&\nBiQuadraticInterpolator::coeffs() const {\n  return mcoeffs;\n}\n\n}\n", "meta": {"hexsha": "d58f5b370947c8ea24f9f6c17bec5474c2cda204", "size": 11083, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/Utilities/BiQuadraticInterpolatorInline.hh", "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/BiQuadraticInterpolatorInline.hh", "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/BiQuadraticInterpolatorInline.hh", "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": 36.5775577558, "max_line_length": 181, "alphanum_fraction": 0.400523324, "num_tokens": 3104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5209052342319666}}
{"text": "/* boost test_uniform_int.ipp\n *\n * Copyright Jens Maurer 2000\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$\n */\n\n#include <numeric>\n#include <sstream>\n#include <vector>\n#include <boost/config.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/limits.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/lagged_fibonacci.hpp>\n#include <boost/random/variate_generator.hpp>\n#include \"chi_squared_test.hpp\"\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\ntemplate<class Generator>\nvoid check_uniform_int(Generator & gen, int iter)\n{\n    int range = (gen.max)()-(gen.min)()+1;\n    std::vector<int> bucket(range);\n    for(int j = 0; j < iter; j++) {\n        int result = gen();\n        BOOST_CHECK_GE(result, (gen.min)());\n        BOOST_CHECK_LE(result, (gen.max)());\n        if(result >= (gen.min)() && result <= (gen.max)()) {\n            bucket[result-(gen.min)()]++;\n        }\n    }\n    int sum = std::accumulate(bucket.begin(), bucket.end(), 0);\n    std::vector<double> expected(range, 1.0 / range);\n    BOOST_CHECK_LT(chi_squared_test(bucket, expected, sum), 0.99);\n}\n\nBOOST_AUTO_TEST_CASE(test_uniform_int)\n{\n    boost::random::mt19937 gen;\n    typedef BOOST_RANDOM_UNIFORM_INT<int> int_gen;\n\n    // large range => small range (modulo case)\n    typedef boost::random::variate_generator<boost::random::mt19937&, int_gen> level_one;\n\n    level_one uint12(gen, int_gen(1,2));\n    BOOST_CHECK((uint12.distribution().min)() == 1);\n    BOOST_CHECK((uint12.distribution().max)() == 2);\n    check_uniform_int(uint12, 100000);\n    level_one uint16(gen, int_gen(1,6));\n    check_uniform_int(uint16, 100000);\n\n    // test chaining to get all cases in operator()\n\n    // identity map\n    typedef boost::random::variate_generator<level_one&, int_gen> level_two;\n    level_two uint01(uint12, int_gen(0, 1));\n    check_uniform_int(uint01, 100000);\n\n    // small range => larger range\n    level_two uint05(uint12, int_gen(-3, 2));\n    check_uniform_int(uint05, 100000);\n\n    // small range => larger range\n    level_two uint099(uint12, int_gen(0, 99));\n    check_uniform_int(uint099, 100000);\n\n    // larger => small range, rejection case\n    typedef boost::random::variate_generator<level_two&, int_gen> level_three;\n    level_three uint1_4(uint05, int_gen(1, 4));\n    check_uniform_int(uint1_4, 100000);\n\n    typedef BOOST_RANDOM_UNIFORM_INT<boost::uint8_t> int8_gen;\n    typedef boost::random::variate_generator<boost::random::mt19937&, int8_gen> gen8_t;\n\n    gen8_t gen8_03(gen, int8_gen(0, 3));\n\n    // use the full range of the type, where the destination\n    // range is a power of the source range\n    typedef boost::random::variate_generator<gen8_t, int8_gen> uniform_uint8;\n    uniform_uint8 uint8_0255(gen8_03, int8_gen(0, 255));\n    check_uniform_int(uint8_0255, 100000);\n\n    // use the full range, but a generator whose range is not\n    // a root of the destination range.\n    gen8_t gen8_02(gen, int8_gen(0, 2));\n    uniform_uint8 uint8_0255_2(gen8_02, int8_gen(0, 255));\n    check_uniform_int(uint8_0255_2, 100000);\n\n    // expand the range to a larger type.\n    typedef boost::random::variate_generator<gen8_t, int_gen> uniform_uint_from8;\n    uniform_uint_from8 uint0300(gen8_03, int_gen(0, 300));\n    check_uniform_int(uint0300, 100000);\n}\n\n#if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T)\n\n// testcase by Mario Rutti\nclass ruetti_gen\n{\npublic:\n    ruetti_gen() : state((max)() - 1) {}\n    typedef boost::uint64_t result_type;\n    result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return 0; }\n    result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return std::numeric_limits<result_type>::max BOOST_PREVENT_MACRO_SUBSTITUTION (); }\n    result_type operator()() { return state--; }\nprivate:\n    result_type state;\n};\n\nBOOST_AUTO_TEST_CASE(test_overflow_range)\n{\n    ruetti_gen gen;\n    BOOST_RANDOM_DISTRIBUTION dist(0, 10);\n    for (int i=0;i<10;i++) {\n        dist(gen);\n    }\n}\n\n#endif\n\nBOOST_AUTO_TEST_CASE(test_misc)\n{\n    // bug report from Ken Mahler:  This used to lead to an endless loop.\n    typedef BOOST_RANDOM_UNIFORM_INT<unsigned int> uint_dist;\n    boost::minstd_rand mr;\n    boost::variate_generator<boost::minstd_rand, uint_dist> r2(mr,\n                                                            uint_dist(0, 0xffffffff));\n    r2();\n    r2();\n\n    // bug report from Fernando Cacciola:  This used to lead to an endless loop.\n    // also from Douglas Gregor\n    boost::variate_generator<boost::minstd_rand, BOOST_RANDOM_DISTRIBUTION > x(mr, BOOST_RANDOM_DISTRIBUTION(0, 8361));\n    x();\n\n    // bug report from Alan Stokes and others: this throws an assertion\n    boost::variate_generator<boost::minstd_rand, BOOST_RANDOM_DISTRIBUTION > y(mr, BOOST_RANDOM_DISTRIBUTION(1,1));\n    y();\n    y();\n    y();\n}\n", "meta": {"hexsha": "b1b2659778ac1d380a416569b66e3e71fd173d95", "size": 5002, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/random/test/test_uniform_int.ipp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/random/test/test_uniform_int.ipp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/random/test/test_uniform_int.ipp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": 33.3466666667, "max_line_length": 147, "alphanum_fraction": 0.6931227509, "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5208754929016193}}
{"text": "// ChiSquaredDistribution.hpp\r\n//\r\n// (C) Datasim Education BV  2009\r\n\r\n\r\n#pragma once\r\n\r\n#include <boost/math/distributions.hpp>\r\n\r\nusing namespace System;\r\n\r\nnamespace Wrapper \r\n{\r\n\t// Wrapper for the boost::math::chi_squared_distribution class\r\n\t// We use the .NET naming conventions instead of the original C++ name\r\n\tpublic ref class ChiSquaredDistribution\r\n\t{\r\n\tprivate:\r\n\t\t// The wrapped native class (only pointers to native classes can be a C++/CLI class datamember)\r\n\t\tboost::math::chi_squared_distribution<>* m_distribution;\r\n\r\n\tpublic:\r\n\t\t// Default constructor\r\n\t\tChiSquaredDistribution();\r\n\r\n\t\t// Constructor with value\r\n\t\tChiSquaredDistribution(double value);\r\n\r\n\t\t// Finaliser (called by garbage collector or destructor)\r\n\t\t!ChiSquaredDistribution();\r\n\r\n\t\t// Destructor (Dispose)\r\n\t\t~ChiSquaredDistribution();\r\n\r\n\t\t// Get the native object\r\n\t\tboost::math::chi_squared_distribution<>* GetNative();\r\n\t};\r\n}\r\n", "meta": {"hexsha": "c2120b691c3b62d2d032f8d7475ddceda814bc32", "size": 922, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI Interop Test (Chi-Squared)/Wrapper/ChiSquaredDistribution.hpp", "max_stars_repo_name": "jdm7dv/financial", "max_stars_repo_head_hexsha": "673a552d58751643dbca0ba633aeff119eda107d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T06:54:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T06:54:08.000Z", "max_issues_repo_path": "windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI Interop Test (Chi-Squared)/Wrapper/ChiSquaredDistribution.hpp", "max_issues_repo_name": "jdm7dv/financial", "max_issues_repo_head_hexsha": "673a552d58751643dbca0ba633aeff119eda107d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI Interop Test (Chi-Squared)/Wrapper/ChiSquaredDistribution.hpp", "max_forks_repo_name": "jdm7dv/financial", "max_forks_repo_head_hexsha": "673a552d58751643dbca0ba633aeff119eda107d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-19T19:27:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T06:26:06.000Z", "avg_line_length": 23.641025641, "max_line_length": 98, "alphanum_fraction": 0.7136659436, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5208754929016193}}
{"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\nusing namespace std;  \n\n\ntypedef mtl::dense2D<int> matrix_type;\nusing mtl::irange; using mtl::iall;\n\n\nmatrix_type inline my_row(int i, int, matrix_type& A)\n{\n    return A[irange(i, i+1)][iall];\n}\n\nmatrix_type inline my_col(int, int j, matrix_type& A)\n{\n    return A[iall][irange(j, j+1)];\n}\n\nmatrix_type inline my_block(int i, int j, matrix_type& A)\n{\n    int ib= i/3*3, jb= j/3*3;\n    return A[irange(ib, ib+3)][irange(jb, jb+3)];\n}\n\nint inline nzero(const matrix_type& A)\n{\n    int n= 0;\n    for (unsigned i= 0; i < num_rows(A); i++)\n\tfor (unsigned j= 0; j < num_cols(A); j++)\n\t    if (A[i][j]) n++;\n    return n;\n}\n\n// My relevant sub-matrices\nstruct my_sub_t\n{\n    my_sub_t(int i, int j, matrix_type& A) \n\t: i(i), j(j), mr(my_row(i, j, A)), mc(my_col(i, j, A)), mb(my_block(i, j, A))\n    {}\n\n    int         i, j;\n    matrix_type mr, mc, mb;\n};\n\nbool inline conflict(int v, const matrix_type& A)\n{\n    for (unsigned i= 0; i < num_rows(A); i++)\n\tfor (unsigned j= 0; j < num_cols(A); j++)\n\t    if (A[i][j] == v) return true;\n    return false;\n}\n\nbool inline conflict(int v, const my_sub_t& sub)\n{\n    return conflict(v, sub.mr) || conflict(v, sub.mc) || conflict(v, sub.mb);\n}\n\n\nstruct entry\n{\n    entry(int i, int j, matrix_type& A) \n\t: i(i), j(j), nnz(nzero(my_row(i, j, A)) + nzero(my_col(i, j, A)) + nzero(my_block(i, j, A)))\n    {}\n\n    friend inline std::ostream& operator<< (std::ostream& stream, const entry& e) \n    {\n\treturn stream << \"[\" << e.i << \", \" << e.j << \" = \" << e.nnz << \"]\";\n    }\n\n    bool operator<(const entry& other) const { return nnz > other.nnz; } // to sort \n\n    int         i, j, nnz;\n};\n\ntemplate <typename T>\ninline std::ostream& operator<< (std::ostream& stream, const std::vector<T>& v) \n{\n    stream << \"(\";\n    for (typename std::vector<T>::const_iterator it= v.begin(); it != v.end(); ++it)\n\tstream << *it << \", \";\n    return stream << \")\";\n}\n\n\n// void inline wait() { char c; std::cin >> c; }\n\n\nvoid solve(const char* file_name)\n{\n    mtl::dense2D<int> A;\n    mtl::io::matrix_market_istream(file_name) >> A;\n    cout << \"Read from \" << file_name <<  \" is \\n\"  << A;\n\n    std::vector<entry> to_fill;\n    for (int i= 0; i < 9; i++)\n\tfor (int j= 0; j < 9; j++)\n\t    if (A[i][j] == 0)\n\t\tto_fill.push_back(entry(i, j, A));\n    sort(to_fill.begin(), to_fill.end());\n\n    for (unsigned pos= 0;;) {\n\tint i= to_fill[pos].i, j= to_fill[pos].j;\n\tmy_sub_t my_sub(i, j, A);\n\tint v= A[i][j] + 1;\n\twhile (v < 10 && conflict(v, my_sub))\n\t    v++;\n\n\t// cout << \"Matrix is now: \\n\" << A;\n\tif (v == 10) {// nothing works -> back track\n\t    if (pos-- == 0) \n\t\tthrow \"No solution found\";\n\t    A[i][j]= 0;\n\t} else {\n\t    A[i][j]= v;\n\t    if (++pos == to_fill.size()) {\n\t\tcout << \"Solution is:\\n\" << A;\n\t\treturn;\n\t    }\n\t}\n    }\n\n}\n\n\nint main(int argc, char* argv[])\n{\n    solve(argc > 1 ? argv[1] : \"matrix_market/sudoku_easy.mtx\");\n    return 0;\n}\n", "meta": {"hexsha": "ded4d86f0cfe875ea5d8708150a0bed891e1a5f9", "size": 3429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/solve_sudoku.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/solve_sudoku.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/solve_sudoku.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.1689189189, "max_line_length": 94, "alphanum_fraction": 0.579469233, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5208754852024533}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/big/io/big_read_DLM.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_read_dlm);\n\nBOOST_AUTO_TEST_CASE(my_test_case)\n{\n  typedef ublas::compressed_matrix<double> matrix_type;\n  typedef ublas::vector<double>            vector_type;\n\n  std::string data_path = \"dlm\";\n\n  matrix_type A;\n  vector_type x;\n\n  {\n    std::string filename = \"do_not_exist.wrong_type_extention\";\n    BOOST_CHECK_THROW( OpenTissue::math::big::read_dlm_matrix( filename, A), std::logic_error );\n  }\n  {\n    std::string filename = \"do_not_exist.wrong_type_extention\";\n    BOOST_CHECK_THROW( OpenTissue::math::big::read_dlm_vector( filename, x), std::logic_error );\n  }\n  double tolerance = 0.01;\n  {\n    std::string filename = data_path + \"/4/A.dlm\";\n    bool success = OpenTissue::math::big::read_dlm_matrix( filename, A);\n    BOOST_CHECK( success);\n    BOOST_CHECK( A.size1() == 4 );\n    BOOST_CHECK( A.size2() == 4 );\n    BOOST_CHECK_CLOSE( double( A(0,0) ), 1.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(0,1) ), 2.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(0,2) ), 3.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(0,3) ), 4.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(1,0) ), 5.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(1,1) ), 6.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(1,2) ), 7.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(1,3) ), 8.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(2,0) ), 9.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(2,1) ), 10.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(2,2) ), 11.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(2,3) ), 12.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(3,0) ), 13.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(3,1) ), 14.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(3,2) ), 15.0, tolerance);\n    BOOST_CHECK_CLOSE( double( A(3,3) ), 16.0, tolerance);\n  }\n  {\n    std::string filename = data_path + \"/4/b.dlm\";\n    bool success = OpenTissue::math::big::read_dlm_vector( filename, x);\n    BOOST_CHECK( success);\n\n    BOOST_CHECK( x.size() == 4 );\n    BOOST_CHECK_CLOSE( double( x(0) ), 1.0, tolerance);\n    BOOST_CHECK_CLOSE( double( x(1) ), 2.0, tolerance);\n    BOOST_CHECK_CLOSE( double( x(2) ), 3.0, tolerance);\n    BOOST_CHECK_CLOSE( double( x(3) ), 4.0, tolerance);\n  }\n\n\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "5e8c7e760d60554e7502e34805e6ca87b0d7488e", "size": 2869, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/big/read_dlm/src/unit_read_dlm.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/read_dlm/src/unit_read_dlm.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/read_dlm/src/unit_read_dlm.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": 36.3164556962, "max_line_length": 96, "alphanum_fraction": 0.6922272569, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5208754833591983}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// independence.hpp                                                          //\n//                                                                           //\n//  Copyright 2010 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_NON_PARAMETRIC_CONTINGENCY_TABLE_INCLUDE_PEARSON_CHISQ_INDEPENDENCE_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_INCLUDE_PEARSON_CHISQ_INDEPENDENCE_HPP_ER_2010\n\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/df.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/lost_df.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/statistic.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/tag.hpp>\n\n#endif\n", "meta": {"hexsha": "3268e0a69e582c5069191aa24efaa5b9c810914c", "size": 1214, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/include/pearson_chisq/independence.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": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/include/pearson_chisq/independence.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": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/include/pearson_chisq/independence.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": 71.4117647059, "max_line_length": 111, "alphanum_fraction": 0.6177924217, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5208685852208669}}
{"text": "/* Copyright (C) 2011 Ion Torrent Systems, Inc. All Rights Reserved */\n\n#include <deque>\n#include <vector>\n#include <armadillo>\n#include <Rcpp.h>\n#include \"mixed.h\"\n#include \"bivariate_gaussian.h\"\n\nusing namespace std;\nusing namespace arma;\n\nRcppExport SEXP percentPositive(SEXP RIonoGram, SEXP RCutoff)\n{\n\tvector<double> ionoGram = Rcpp::as<vector<double> >(RIonoGram);\n\tdouble cutoff = Rcpp::as<double>(RCutoff);\n\tdouble ppf    = percent_positive(ionoGram.begin(), ionoGram.end(), cutoff);\n\n\treturn Rcpp::List::create(Rcpp::Named(\"ppf\") = ppf);\n}\n\nRcppExport SEXP sumFractionalPart(SEXP RIonoGram)\n{\n\tvector<double> ionoGram = Rcpp::as<vector<double> >(RIonoGram);\n\tdouble ssq = sum_fractional_part(ionoGram.begin(), ionoGram.end());\n\n\treturn Rcpp::List::create(Rcpp::Named(\"ssq\") = ssq);\n}\n\nRcppExport SEXP fitNormals(SEXP RPPF, SEXP RSSQ)\n{\n\tdeque<float> ppf = Rcpp::as<deque<float> >(RPPF);\n\tdeque<float> ssq = Rcpp::as<deque<float> >(RSSQ);\n\n\t//vec2  mean[2];\n\t//mat22 sigma[2];\n\t//vec2  prior;\n\tvec mean[2];\n\tmat sigma[2];\n\tvec prior;\n    for(int i=0; i<2; ++i){\n        mean[i].set_size(2);\n        sigma[i].set_size(2,2);\n    }\n\n// I assume here (possibly falsely) that the default options are good\n  PolyclonalFilterOpts local_opts;\n\n\tbool converged = fit_normals(mean, sigma, prior, ppf, ssq, local_opts); \n\n\t// (Wrapping the results would be much simpler with RcppArmadillo.)\n\tRcpp::NumericVector RCloneMean  = Rcpp::wrap(mean[0]);\n\tRcpp::NumericVector RMixedMean  = Rcpp::wrap(mean[1]);\n\tRcpp::NumericVector RPrior      = Rcpp::wrap(prior);\n\n\tRcpp::NumericMatrix RCloneSigma(2,2);\n\tRcpp::NumericMatrix RMixedSigma(2,2);\n\tfor(int r=0; r<2; ++r){\n\t\tfor(int c=0; c<2; ++c){\n\t\t\tRCloneSigma(r,c) = sigma[0](r,c);\n\t\t\tRMixedSigma(r,c) = sigma[1](r,c);\n\t\t}\n\t}\n\n\treturn Rcpp::List::create(Rcpp::Named(\"converged\")  = converged,\n                              Rcpp::Named(\"cloneMean\")  = RCloneMean,\n                              Rcpp::Named(\"mixedMean\")  = RMixedMean,\n                              Rcpp::Named(\"cloneSigma\") = RCloneSigma,\n                              Rcpp::Named(\"mixedSigma\") = RMixedSigma,\n                              Rcpp::Named(\"prior\")      = RPrior);\n\n}\n\nRcppExport SEXP distanceFromMean(SEXP RMean, SEXP RSigma, SEXP RX)\n{\n\tRcpp::NumericVector tmpMean(RMean);\n\tRcpp::NumericMatrix tmpSigma(RSigma);\n\tRcpp::NumericVector tmpX(RX);\n\n\t//vec2  mean;\n\t//mat22 sigma;\n\t//vec2  x;\n\tvec mean(2);\n\tmat sigma(2,2);\n\tvec x(2);\n\n\tmean  << tmpMean(0)    << tmpMean(1);\n\tsigma << tmpSigma(0,0) << tmpSigma(0,1) << endr\n\t      << tmpSigma(1,0) << tmpSigma(1,1) << endr;\n\tx     << tmpX(0)       << tmpX(1);\n\n\tbivariate_gaussian g(mean, sigma);\n\t\n\treturn Rcpp::wrap(g.sd(x));\n}\n\n\n", "meta": {"hexsha": "092c70b9d9b170c1389d91c6c680d518f24925a9", "size": 2694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "torrentR/src/mixedReads.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": "torrentR/src/mixedReads.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": "torrentR/src/mixedReads.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": 27.4897959184, "max_line_length": 76, "alphanum_fraction": 0.6332590943, "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5208685852208668}}
{"text": "#include <cstdlib>\n#include <list>\n#include <Eigen/Core>\n#include <moihgp/moihgp_online.h>\n#include <moihgp/matern32ss.h>\n#include <iostream>\n#include <time.h>\n\n\n\nint main()\n{\n\n    double dt = 0.1;\n    size_t num_output = 2;\n    size_t num_latent = 1;\n    size_t windowsize = 1;\n    double gamma = 0.9;\n    bool threading = false;\n    Eigen::MatrixXd H(2, 2);\n    H << 0.7, 0.3, -0.3, 0.7;\n    std::list<Eigen::VectorXd> data;\n    double t = 0.0;\n    while (t < 2 * M_PI)\n    {\n        Eigen::VectorXd x(num_latent);\n        x << sin(t), sin(4*t);\n        data.push_back(H * x + 0.1 * Eigen::VectorXd(num_output).setRandom());\n        t += dt;\n    }\n\n    moihgp::MOIHGPOnlineLearning<moihgp::Matern32StateSpace> gp(dt, num_output, num_latent, gamma, windowsize, threading);\n    std::list<Eigen::VectorXd> yhat;\n    for (std::list<Eigen::VectorXd>::iterator y = data.begin(); y != data.end(); y++)\n    {\n        clock_t tic = clock();\n        yhat.push_back(gp.step(*y));\n        clock_t toc = clock();\n        std::cout << \"Elapsed time per step:\" << double(toc - tic) / 1000.0 << \"ms\" << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "57e63137ea5047bbe76d2f51b391ef344e9e68d6", "size": 1123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moihgp/cpp_examples/example_online_learning.cpp", "max_stars_repo_name": "MLCS-Yonsei/MultiOutputIHGP", "max_stars_repo_head_hexsha": "3767325f57c5cd34655013fd9c7a0d87e97fc74f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "moihgp/cpp_examples/example_online_learning.cpp", "max_issues_repo_name": "MLCS-Yonsei/MultiOutputIHGP", "max_issues_repo_head_hexsha": "3767325f57c5cd34655013fd9c7a0d87e97fc74f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moihgp/cpp_examples/example_online_learning.cpp", "max_forks_repo_name": "MLCS-Yonsei/MultiOutputIHGP", "max_forks_repo_head_hexsha": "3767325f57c5cd34655013fd9c7a0d87e97fc74f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-10T16:44:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T16:44:42.000Z", "avg_line_length": 25.5227272727, "max_line_length": 122, "alphanum_fraction": 0.5814781834, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5208685806245656}}
{"text": "/*\n Copyright (C) 2020 Quaternion Risk Management Ltd\n All rights reserved.\n*/\n\n#include \"utilities.hpp\"\n#include \"toplevelfixture.hpp\"\n#include <boost/test/unit_test.hpp>\n#include <ql/experimental/callablebonds/callablebond.hpp>\n#include <ql/indexes/ibor/euribor.hpp>\n#include <ql/instruments/callabilityschedule.hpp>\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/math/randomnumbers/rngtraits.hpp>\n#include <ql/math/statistics/incrementalstatistics.hpp>\n#include <ql/methods/montecarlo/multipathgenerator.hpp>\n#include <ql/methods/montecarlo/pathgenerator.hpp>\n#include <ql/quantlib.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/credit/flathazardrate.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/time/daycounters/thirty360.hpp>\n\n#include <qle/instruments/cdsoption.hpp>\n#include <qle/instruments/creditdefaultswap.hpp>\n#include <qle/methods/multipathgeneratorbase.hpp>\n#include <qle/models/crossassetmodel.hpp>\n#include <qle/models/cdsoptionhelper.hpp>\n#include <qle/pricingengines/midpointcdsengine.hpp>\n\n#include <qle/models/crcirpp.hpp>\n#include <qle/models/cirppconstantfellerparametrization.hpp>\n#include <qle/models/crossassetmodel.hpp>\n#include <qle/processes/crcirppstateprocess.hpp>\n\n#include <boost/make_shared.hpp>\n\n#include <fstream>\n#include <iostream>\n\n// fix for boost 1.64, see https://lists.boost.org/Archives/boost/2016/11/231756.php\n#if BOOST_VERSION >= 106400\n#include <boost/serialization/array_wrapper.hpp>\n#endif\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/covariance.hpp>\n#include <boost/accumulators/statistics/density.hpp>\n#include <boost/accumulators/statistics/error_of_mean.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/variates/covariate.hpp>\n#include <boost/make_shared.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\n\nusing namespace boost::accumulators;\n\nnamespace {\nstruct CreditModelTestData_flat {\n    CreditModelTestData_flat()\n        : referenceDate(29, July, 2017), dts(boost::make_shared<FlatHazardRate>(referenceDate, 0.04, ActualActual())),\n          yts(boost::make_shared<FlatForward>(referenceDate, 0.02, ActualActual())) {\n\n        Settings::instance().evaluationDate() = referenceDate;\n\n        kappa = 0.206;\n        theta = 0.04;\n        sigma = sqrt(2 * kappa * theta) - 1E-10;\n        y0 = theta;\n        shifted = true;\n\n        recoveryRate = 0.4;\n        // QL_REQUIRE(2 * eurKappa * eurTheta / eurSigma / eurSigma > 1 , \"Feller Condition is not satisfied!\");\n        cirParametrization = boost::make_shared<CrCirppConstantWithFellerParametrization>(\n            EURCurrency(), dts, kappa, theta, sigma, y0, shifted);\n        QL_REQUIRE(cirParametrization != NULL, \"CrCirppConstantWithFellerParametrization has null pointer!\");\n\n        model = boost::make_shared<CrCirpp>(cirParametrization);\n        BOOST_TEST_MESSAGE(\"CIR++ parameters: \");\n        BOOST_TEST_MESSAGE(\"Kappa: \\t\" << model->parametrization()->kappa(0));\n        BOOST_TEST_MESSAGE(\"Theta: \\t\" << model->parametrization()->theta(0));\n        BOOST_TEST_MESSAGE(\"Sigma: \\t\" << model->parametrization()->sigma(0));\n        BOOST_TEST_MESSAGE(\"y0: \\t\" << model->parametrization()->y0(0));\n        BOOST_TEST_MESSAGE(\"Feller condition is (>1 ok) \"\n                           << 2.0 * model->parametrization()->kappa(0) * model->parametrization()->theta(0) /\n                                  model->parametrization()->sigma(0) / model->parametrization()->sigma(0));\n    }\n\n    SavedSettings backup;\n    Date referenceDate;\n    Handle<DefaultProbabilityTermStructure> dts;\n    Handle<YieldTermStructure> yts;\n    Real kappa, theta, sigma, y0;\n    bool shifted;\n    Real recoveryRate;\n    boost::shared_ptr<CrCirppConstantWithFellerParametrization> cirParametrization;\n    boost::shared_ptr<CrCirpp> model;\n}; // IrTSModelTestData\n} // namespace\n\nBOOST_FIXTURE_TEST_SUITE(CrCirppModelTest, CreditModelTestData_flat)\n\nBOOST_AUTO_TEST_CASE(testMartingaleProperty) {\n\n    BOOST_TEST_MESSAGE(\"Testing martingale property in credit-CIR++ model for Brigo-Alfonsi discretizations...\");\n\n    boost::shared_ptr<StochasticProcess> process = model->stateProcess();\n    QL_REQUIRE(process != NULL, \"process has null pointer!\");\n\n    // CIRplusplusStateProcess::Discretization discType = CIRplusplusStateProcess::Discretization::Reflection;\n    // CIRplusplusStateProcess::Discretization discType = CIRplusplusStateProcess::Discretization::PartialTruncation;\n    // CIRplusplusStateProcess::Discretization discType = CIRplusplusStateProcess::Discretization::FullTruncation;\n    // boost::shared_ptr<StochasticProcess> process = boost::make_shared<CIRplusplusStateProcess>(model.get(),\n    // discType);  BOOST_TEST_MESSAGE(\"Simulation type of negative variance process \"<<discType);\n    Size n = 10000; // number of paths\n    Size seed = 42; // rng seed\n    // Time T = 25.0;                          // maturity of payoff\n    // Time T2 = 40.0;                         // zerobond maturity\n    Time T = 10.0;  // maturity of payoff\n    Time T2 = 20.0; // zerobond maturity\n    // QL_REQUIRE(T2 == model->maxSimulationHorizon(), \"Forward measure horizon must be equalt to the maturity of the\n    // zero bond\");\n    Size steps = static_cast<Size>(T * 52); // number of steps taken (euler)\n\n    TimeGrid grid(T, steps);\n    // LowDiscrepancy::rsg_type sg = LowDiscrepancy::make_sequence_generator( 9 * steps, seed);\n    // MultiPathGenerator<LowDiscrepancy::rsg_type> pg(process, grid, sg, false);\n    MultiPathGeneratorMersenneTwister pg(process, grid, seed, true);\n    accumulator_set<double, stats<tag::mean, tag::error_of<tag::mean>>> meanTest_y;\n    accumulator_set<double, stats<tag::variance, tag::error_of<tag::mean>>> varTest_y;\n\n    accumulator_set<double, stats<tag::mean, tag::error_of<tag::mean>>> sp;\n    accumulator_set<double, stats<tag::mean, tag::error_of<tag::mean>>> numeraire;\n\n    accumulator_set<double, stats<tag::density>> histXAcc(tag::density::cache_size = 10000,\n                                                          tag::density::num_bins = 50);\n\n    // typedef boost::iterator_range<std::vector<std::pair<double, double>>::iterator> histogram_type;\n\n    // //create an accumulator\n    // acc histXAcc( tag::density::num_bins = 20, tag::density::cache_size = 10);\n\n    std::ofstream of;\n    // of.open(\"y_paths.txt\");\n    for (Size j = 0; j < n; ++j) {\n        Sample<MultiPath> path = pg.next();\n        Size l = path.value[0].length() - 1;\n        Real y = path.value[0][l];\n        Real num = path.value[1][l];\n        sp(model->survivalProbability(T, T2, y) * num);\n        numeraire(num);\n        meanTest_y(y);\n        varTest_y(y);\n        histXAcc(y);\n    }\n    // histogram_type histX = density(histXAcc);\n    // double total = 0.0;\n    // std::ofstream ofHistX;\n    // ofHistX.open(\"y_hist.txt\");\n\n    // Real binSize = histX[1].first - histX[0].first;\n    // for (Size i = 0; i < histX.size(); i++) {\n    //     ofHistX << histX[i].first << \",\" << histX[i].second / binSize << std::endl;\n    //     total += histX[i].second;\n    // }\n    // BOOST_TEST_MESSAGE(\"Total cdf(x): \" << total); // should be 1 (and it is)\n\n    // total = 0.0;\n    // std::ofstream ofPDFX;\n    // ofPDFX.open(\"y_pdf.txt\");\n    // // for (Real x = - 5.0; x <= 7.0; x += 0.1)\n    // for (Real x = 0.00018; x <= 0.01; x += 0.001) {\n    //     ofPDFX << x << \",\" << model->density(x, T) << std::endl;\n    //     total += model->density(x, T);\n    // }\n    // BOOST_TEST_MESSAGE(\"Total cdf(x): \" << total); // should be 1 (and it is)\n\n    // of.close();\n    // ofPDFX.close();\n    // ofHistX.close();\n\n    // Real kappa = model->parametrization()->kappa(0);\n    // Real theta = model->parametrization()->theta(0);\n    // Real sigma = model->parametrization()->sigma(0);\n    // Real y0 = model->parametrization()->y0(0);\n    // Real sigma2 = sigma * sigma;\n\n    BOOST_TEST_MESSAGE(\"\\nBrigo-Alfonsi:\");\n    // BOOST_TEST_MESSAGE(\"Mean = \" << mean(meanTest_y) << \" +- \" << error_of<tag::mean>(meanTest_y) << \" analytic \"\n    // <<y0 * exp(-kappa*T) + theta * (1- exp(-kappa*T))); BOOST_TEST_MESSAGE(\"Variance = \" << variance(varTest_y) << \"\n    // +- \" << error_of<tag::mean>(varTest_y)<<\" analytic \" <<y0*sigma2/theta*(exp(-kappa*T) - exp(-2*kappa*T)) +\n    // theta*sigma2/2/kappa*(1- exp(-2*kappa *T))*(1- exp(-2*kappa *T)) );\n    BOOST_TEST_MESSAGE(\"SP = \" << mean(sp) << \" +- \" << error_of<tag::mean>(sp) << \" vs analytical \"\n                               << dts->survivalProbability(T2));\n    BOOST_TEST_MESSAGE(\"Num = \" << mean(numeraire) << \" +- \" << error_of<tag::mean>(numeraire) << \" vs analytical \"\n                                << dts->survivalProbability(T));\n\n    Real tol2 = 12.0E-4;\n    Real expectedSP = dts->survivalProbability(T);\n    Real expectedCondSP = dts->survivalProbability(T2);\n    if (std::abs(mean(numeraire) - expectedSP) > tol2)\n        BOOST_FAIL(\"Martingale test failed for SP(t) (Brigo-Alfonsi discr.), excpected \"\n                   << expectedSP << \", got \" << mean(numeraire) << \", tolerance \" << tol2);\n    if (std::abs(mean(sp) - expectedCondSP) > tol2)\n        BOOST_FAIL(\"Martingale test failed for  SP(t,T) (Brigo-Alfonsi discr.), excpected \"\n                   << expectedCondSP << \", got \" << mean(sp) << \", tolerance \" << tol2);\n\n} // testIrTSMartingaleProperty\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7b0f7ac6afb96c194069a558b95044594e1c8f30", "size": 9613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/crcirpp.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/test/crcirpp.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/test/crcirpp.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": 44.711627907, "max_line_length": 119, "alphanum_fraction": 0.6634765422, "num_tokens": 2647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914788, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5208685783264152}}
{"text": "\ufeff//***********************************************************\r\n// 17/10/2020\t1.0.0\tR\u00e9mi Saint-Amant   Creation\r\n//***********************************************************\r\n#include \"LeucopisModel.h\"\r\n#include \"ModelBase/EntryPoint.h\"\r\n#include \"Basic\\DegreeDays.h\"\r\n#include <boost/math/distributions/weibull.hpp>\r\n#include <boost/math/distributions/beta.hpp>\r\n#include <boost/math/distributions/Rayleigh.hpp>\r\n#include <boost/math/distributions/logistic.hpp>\r\n#include <boost/math/distributions/exponential.hpp>\r\n#include <boost/math/distributions/lognormal.hpp>\r\n#include \"ModelBase/SimulatedAnnealingVector.h\"\r\n\r\n//Best parameters (separate)\r\n//\t\t\tTh1\t\tTh2\t\tmu\t\ts\t\tdelta\r\n//La G1\t\t3.2\t\t12.5\t199.5\t31.38\t44\r\n//La G2\t\t3.4\t\t40.5\t861.9\t54.45\t39\r\n//Ln\t\t4.6\t\t12.4\t394.9\t22.87\t44\r\n\r\n//Final parameters\r\n//\r\n//Th1 =  2.9\r\n//Th2 = 19.1\r\n//delta = 45 (February 15)\r\n//\t\t mu\t\t s\t\t\r\n//La G1\t239.6\t41.4\r\n//La G2\t876.0\t55.6\r\n//Ln\t625.2\t38.3\r\n\r\n\r\n\r\nusing namespace WBSF::HOURLY_DATA;\r\nusing namespace std;\r\n\r\n\r\nstatic const bool BEGIN_JULY = true;\r\nstatic const size_t FIRST_Y = BEGIN_JULY ? 1 : 0;\r\n\r\nnamespace WBSF\r\n{\r\n\t//static const CDegreeDays::TDailyMethod DD_METHOD = CDegreeDays::MODIFIED_ALLEN_WAVE;\r\n\tstatic const CDegreeDays::TDailyMethod DD_METHOD = CDegreeDays::ALLEN_WAVE;\r\n\tenum { O_CDD, O_EMERGENCE_LA_G1, O_EMERGENCE_LA_G2, O_EMERGENCE_LP, NB_OUTPUTS };\r\n\r\n\t//this line link this model with the EntryPoint of the DLL\r\n\tstatic const bool bRegistred =\r\n\t\tCModelFactory::RegisterModel(CLeucopisModel::CreateObject);\r\n\r\n\tCLeucopisModel::CLeucopisModel()\r\n\t{\r\n\t\t//NB_INPUT_PARAMETER is used to determine if the dll\r\n\t\t//uses the same number of parameters than the model interface\r\n\t\tNB_INPUT_PARAMETER = -1;\r\n\t\tVERSION = \"1.0.0 (2020)\";\r\n\r\n\t\tm_bCumul = false;\r\n\r\n\t\tm_P[\u03a4\u1d34\u00b9] = 2.9;\r\n\t\tm_P[\u03a4\u1d34\u00b2] = 19.1;\r\n\t\tm_P[delta] = 45;\r\n\t\tm_P[\u03bc1] = 239.6;\r\n\t\tm_P[\u04551] = 41.4;\r\n\t\tm_P[\u03bc2] = 876.0;\r\n\t\tm_P[\u04552] = 55.6;\r\n\t\tm_P[\u03bc3] = 625.2;\r\n\t\tm_P[\u04553] = 38.3;\r\n\t\t\t\r\n\t}\r\n\r\n\tCLeucopisModel::~CLeucopisModel()\r\n\t{\r\n\t}\r\n\r\n\r\n\t//this method is call to load your parameter in your variable\r\n\tERMsg CLeucopisModel::ProcessParameters(const CParameterVector& parameters)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\tsize_t c = 0;\r\n\r\n\t\tm_bCumul = parameters[c++].GetBool();\r\n\r\n\t\tif (parameters.size() == 1 + NB_PARAMS)\r\n\t\t{\r\n\t\t\tfor (size_t p = 0; p < NB_PARAMS; p++)\r\n\t\t\t\tm_P[p] = parameters[c++].GetFloat();\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n\t//This method is called to compute the solution\r\n\tERMsg CLeucopisModel::OnExecuteDaily()\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\t/*\tif (m_weather.GetNbYears() < 2)\r\n\t\t\t{\r\n\t\t\t\tmsg.ajoute(\"Laricobius Osakensis model need at least 2 years of data\");\r\n\t\t\t\treturn msg;\r\n\t\t\t}*/\r\n\r\n\t\t\t//if (!m_weather.IsHourly())\r\n\t\t\t\t//\tm_weather.ComputeHourlyVariables();\r\n\r\n\t\t\t//This is where the model is actually executed\r\n\t\tCTPeriod p = m_weather.GetEntireTPeriod(CTM(CTM::DAILY));\r\n\t\tm_output.Init(p, NB_OUTPUTS, -999);\r\n\r\n\r\n\t\tCModelStatVector CDD;\r\n\t\tGetCDD(m_weather, CDD);\r\n\r\n\t\tboost::math::logistic_distribution<double> emerge_dist1(m_P[\u03bc1], m_P[\u04551]);\r\n\t\tboost::math::logistic_distribution<double> emerge_dist2(m_P[\u03bc2], m_P[\u04552]);\r\n\t\tboost::math::logistic_distribution<double> emerge_dist3(m_P[\u03bc3], m_P[\u04553]);\r\n\t\t//boost::math::logistic_distribution<double> emerge_dist4(m_P[\u03bc4], m_P[\u04554]);\r\n\r\n\t\tfor (CTRef d = p.Begin(); d <= p.End(); d++)\r\n\t\t{\r\n\t\t\tm_output[d][O_CDD] = CDD[d][0];\r\n\t\t\tif (CDD[d][0] > -999)\r\n\t\t\t{\r\n\t\t\t\tm_output[d][O_EMERGENCE_LA_G1] = Round(100 * cdf(emerge_dist1, CDD[d][0]), 1);\r\n\t\t\t\tm_output[d][O_EMERGENCE_LA_G2] = Round(100 * cdf(emerge_dist2, CDD[d][0]), 1);\r\n\t\t\t\tm_output[d][O_EMERGENCE_LP] = Round(100 * cdf(emerge_dist3, CDD[d][0]), 1);\r\n\t\t\t\t//m_output[d][O_EMERGENCE_LN] = Round(100 * cdf(emerge_dist4, CDD[d][0]), 1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\t//void CLeucopisModel::GetCDD(int year, const CWeatherYears& weather, CModelStatVector& CDD)\r\n\t//{\r\n\t//\tCDegreeDays DDmodel(DD_METHOD, m_P[\u03a4\u1d34\u00b9], m_P[\u03a4\u1d34\u00b2]);\r\n\t//\tCModelStatVector DD;\r\n\t//\tDDmodel.Execute(weather[year], DD);\r\n\r\n\r\n\r\n\t//\tCDD.Init(DD.GetTPeriod(), 1, 0.0);\r\n\r\n\t//\t//for (CTRef TRef = DD.GetFirstTRef(); TRef <= DD.GetLastTRef(); TRef++)\r\n\t//\tCDD[0][0] = DD[0][CDegreeDays::S_DD];\r\n\t//\tfor (size_t i = 1; i < DD.size(); i++)\r\n\t//\t\tCDD[i][0] = CDD[i - 1][0] + DD[i][CDegreeDays::S_DD];\r\n\t//}\r\n\r\n\tvoid CLeucopisModel::GetCDD(const CWeatherYears& weather, CModelStatVector& CDD)\r\n\t{\r\n\t\tCDegreeDays DDmodel(DD_METHOD, m_P[\u03a4\u1d34\u00b9], m_P[\u03a4\u1d34\u00b2]);\r\n\t\tCModelStatVector DD;\r\n\t\tDDmodel.Execute(weather, DD);\r\n\r\n\r\n\r\n\t\tCDD.Init(DD.GetTPeriod(), 1, -999);\r\n\r\n\t\tfor (size_t y = 1; y < weather.GetNbYears(); y++)\r\n\t\t{\r\n\t\t\tCTPeriod p = weather[y].GetEntireTPeriod();\r\n\t\t\tp.Begin() = p.Begin() + int(m_P[delta]);\r\n\t\t\tCDD[p.Begin()][0] = DD[p.Begin()][CDegreeDays::S_DD];\r\n\r\n\t\t\tfor (CTRef TRef = p.Begin() + 1; TRef <= p.End(); TRef++)\r\n\t\t\t\tCDD[TRef][0] = CDD[TRef - 1][0] + DD[TRef][CDegreeDays::S_DD];\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tenum TSpecies { S_LA_G1, S_LA_G2, S_LP, S_LN };\r\n\tenum TInput { I_N, I_S/*, I_P, I_CDD*/, NB_INPUTS };\r\n\tvoid CLeucopisModel::AddDailyResult(const StringVector& header, const StringVector& data)\r\n\t{\r\n\t\tASSERT(data.size() == 13);\r\n\t\t//SYC\tsite\tYear\tcollection\tcol_date\temerge_date\tdaily_count\tspecies\tn_days P Time\r\n\r\n\t\tif (data[7] != \"LN\")\r\n\t\t{\r\n\r\n\t\t\tCSAResult obs;\r\n\r\n\t\t\tCStatistic egg_creation_date;\r\n\r\n\t\t\tobs.m_ref.FromFormatedString(data[5]);\r\n\t\t\tobs.m_obs.resize(NB_INPUTS);\r\n\t\t\tobs.m_obs[I_N] = stod(data[6]);\r\n\t\t\t//obs.m_obs[I_S] = ;\r\n\t\t\t//obs.m_obs[I_P] = stod(data[10]);\r\n\t\t\t//obs.m_obs[I_CDD] = stod(data[11]);\r\n\t\t\t//obs.m_obs[I_P] = stod(data[12]);\r\n\r\n\r\n\t\t\tif (data[7] == \"LA\" && data[8] == \"1\")\r\n\t\t\t\tobs.m_obs[I_S] = S_LA_G1;\r\n\t\t\telse if (data[7] == \"LA\" && data[8] == \"2\")\r\n\t\t\t\tobs.m_obs[I_S] = S_LA_G2;\r\n\t\t\telse if (data[7] == \"LP\")\r\n\t\t\t\tobs.m_obs[I_S] = S_LP;\r\n\t\t\telse if (data[7] == \"LN\")\r\n\t\t\t\tobs.m_obs[I_S] = S_LN;\r\n\r\n\t\t\tm_SAResult.push_back(obs);\r\n\t\t}\r\n\t}\r\n\r\n\t//double GetSimX(size_t s, CTRef TRefO, double obs, const CModelStatVector& output)\r\n\t//{\r\n\t//\tdouble x = -999;\r\n\r\n\t//\tif (obs > -999)\r\n\t//\t{\r\n\t//\t\t//if (obs > 0.01 && obs < 99.99)\r\n\t//\t\tif (obs >= 100)\r\n\t//\t\t\tobs = 99.99;//to avoid some problem of truncation\r\n\r\n\t//\t\tlong index = output.GetFirstIndex(s, \">=\", obs, 1, CTPeriod(TRefO.GetYear(), FIRST_MONTH, FIRST_DAY, TRefO.GetYear(), LAST_MONTH, LAST_DAY));\r\n\t//\t\tif (index >= 1)\r\n\t//\t\t{\r\n\t//\t\t\tdouble obsX1 = output.GetFirstTRef().GetJDay() + index;\r\n\t//\t\t\tdouble obsX2 = output.GetFirstTRef().GetJDay() + index + 1;\r\n\r\n\t//\t\t\tdouble obsY1 = output[index][s];\r\n\t//\t\t\tdouble obsY2 = output[index + 1][s];\r\n\t//\t\t\tif (obsY2 != obsY1)\r\n\t//\t\t\t{\r\n\t//\t\t\t\tdouble slope = (obsX2 - obsX1) / (obsY2 - obsY1);\r\n\t//\t\t\t\tdouble obsX = obsX1 + (obs - obsY1)*slope;\r\n\t//\t\t\t\tASSERT(!_isnan(obsX) && _finite(obsX));\r\n\r\n\t//\t\t\t\tx = obsX;\r\n\t//\t\t\t}\r\n\t//\t\t}\r\n\t//\t}\r\n\r\n\t//\treturn x;\r\n\t//}\r\n\r\n\tbool CLeucopisModel::IsParamValid()const\r\n\t{\r\n\t\tbool bValid = true;\r\n\r\n\t\tif (m_P[\u03a4\u1d34\u00b9] >= m_P[\u03a4\u1d34\u00b2])\r\n\t\t\tbValid = false;\r\n\r\n\r\n\t\treturn bValid;\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n\t//static const int ROUND_VAL = 4;\r\n\t//CTRef CLeucopisModel::GetEmergence(const CWeatherYear& weather)\r\n\t//{\r\n\t//\tCTPeriod p = weather.GetEntireTPeriod(CTM(CTM::DAILY));\r\n\r\n\t//\tdouble sumDD = 0;\r\n\t//\tfor (CTRef TRef = p.Begin()+172; TRef <= p.End()&& TRef<= p.Begin() + int(m_ADE[\u028e0]); TRef++)\r\n\t//\t{\r\n\t//\t\t//size_t ii = TRef - p.Begin();\r\n\t//\t\tconst CWeatherDay& wday = m_weather.GetDay(TRef);\r\n\t//\t\tdouble T = wday[H_TNTX][MEAN];\r\n\t//\t\tT = Round(max(m_ADE[\u028ea], T), ROUND_VAL);\r\n\r\n\t//\t\tdouble DD = min(0.0, T - m_ADE[\u028eb]);//DD is negative\r\n\r\n\t//\t\t//if (ii < m_ADE[\u028e0])\r\n\t//\t\t\tsumDD += DD;\r\n\t//\t}\r\n\r\n\r\n\t//\tboost::math::logistic_distribution<double> begin_dist(m_ADE[\u028e2], m_ADE[\u028e3]);\r\n\t//\tint begin = (int)Round(m_ADE[\u028e0] + m_ADE[\u028e1] * cdf(begin_dist, sumDD), 0);\r\n\t//\treturn  p.Begin() + begin;\r\n\t//}\r\n\tenum TPout {P_CDD, P_CE, LA_G1= P_CE, P_LA_G2, P_LP, P_LN, NB_P};//CE = cumulative emergence\r\n\tvoid CLeucopisModel::GetPobs(CModelStatVector& P)\r\n\t{\r\n\t\tstring ID = GetInfo().m_loc.m_ID;\r\n\t\tstring SY = ID.substr(0, ID.length() - 2);\r\n\r\n\t\t//compute CDD for all temperature rprofile\r\n\t\tarray< double, 4> total = { 0 };\r\n\t\tvector<tuple<double, CTRef, double, bool, size_t>> d;\r\n\t\tconst CSimulatedAnnealingVector& SA = GetSimulatedAnnealingVector();\r\n\r\n\t\tfor (size_t i = 0; i < SA.size(); i++)\r\n\t\t{\r\n\t\t\tstring IDi = SA[i]->GetInfo().m_loc.m_ID;\r\n\t\t\tstring SYi = IDi.substr(0, IDi.length() - 2);\r\n\t\t\tif (SYi == SY)\r\n\t\t\t{\r\n\t\t\t\tCModelStatVector CDD;\r\n\t\t\t\tGetCDD(SA[i]->m_weather, CDD);\r\n\t\t\t\tconst CSAResultVector& v = SA[i]->GetSAResult();\r\n\t\t\t\tfor (size_t ii = 0; ii < v.size(); ii++)\r\n\t\t\t\t{\r\n\t\t\t\t\td.push_back(make_tuple(CDD[v[ii].m_ref][0], v[ii].m_ref, v[ii].m_obs[I_N], IDi == ID, v[ii].m_obs[I_S]));\r\n\t\t\t\t\ttotal[v[ii].m_obs[I_S]] += v[ii].m_obs[I_N];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tsort(d.begin(), d.end());\r\n\r\n\t\tP.Init(m_weather.GetEntireTPeriod(CTM::DAILY), NB_P, 0);\r\n\t\tarray< double, 4> sum = { 0 };\r\n\t\tfor (size_t i = 0; i < d.size(); i++)\r\n\t\t{\r\n\t\t\tsize_t s = std::get<4>(d[i]);\r\n\t\t\tsum[s] += std::get<2>(d[i]);\r\n\t\t\tif (std::get<3>(d[i]))\r\n\t\t\t{\r\n\t\t\t\tCTRef Tref = std::get<1>(d[i]);\r\n\t\t\t\t/*double obsP = -999;\r\n\t\t\t\tfor (size_t k = 0; k < m_SAResult.size(); k++)\r\n\t\t\t\t\tif (m_SAResult[k].m_ref == Tref)\r\n\t\t\t\t\t\tobsP = m_SAResult[k].m_obs[I_P];*/\r\n\r\n\r\n\t\t\t\tdouble CDD = std::get<0>(d[i]);\r\n\t\t\t\tdouble p = Round(100 * sum[s] / total[s], 1);\r\n\t\t\t\t\r\n\t\t\t\tP[Tref][P_CDD] = CDD;\r\n\t\t\t\tP[Tref][P_CE + s] = p;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid CLeucopisModel::CalibrateEmergence(CStatisticXY& stat)\r\n\t{\r\n\t\tif (m_SAResult.empty())\r\n\t\t\treturn;\r\n\r\n\t\t//boost::math::lognormal_distribution<double> emerge_dist(m_P[\u03bc], m_P[\u0455]);\r\n\r\n\r\n\r\n\t\t//boost::math::weibull_distribution<double> emerge_dist(m_P[\u03bc], m_P[\u0455]);\r\n\t\t//boost::math::beta_distribution<double> emerge_dist(m_P[\u03bc], m_P[\u0455]);\r\n\t\t//boost::math::exponential_distribution<double> emerge_dist(m_P[\u0455]);\r\n\t\t//boost::math::rayleigh_distribution<double> emerge_dist(m_P[\u0455]);\r\n\r\n\r\n\t\t//CModelStatVector CDD; \r\n\t\t//GetCDD(m_weather, CDD);\r\n\r\n\t\tdouble n = 0;\r\n\r\n\t\tfor (size_t i = 0; i < m_SAResult.size(); i++)\r\n\t\t\tn += m_SAResult[i].m_obs[I_N];\r\n\r\n\r\n\t\tCModelStatVector P;\r\n\t\tGetPobs(P);\r\n\r\n\t\t//array<boost::math::logistic_distribution<double>,4> emerge_dist(mu, S);\r\n\t\t//\t\tarray<boost::math::logistic_distribution<double>, 4> emerge_dist = { {m_P[\u03bc1], m_P[\u04551], m_P[\u03bc1], m_P[\u04551]} };\r\n\r\n\t\tfor (size_t i = 0; i < m_SAResult.size(); i++)\r\n\t\t{\r\n\t\t\tsize_t s = m_SAResult[i].m_obs[I_S];\r\n\t\t\tdouble mu = m_P[\u03bc1 + 2 * s];\r\n\t\t\tdouble S = m_P[\u04551 + 2 * s];\r\n\r\n\t\t\tboost::math::logistic_distribution<double> emerge_dist(mu, S);\r\n\r\n\t\t\tdouble CDD = P[m_SAResult[i].m_ref][P_CDD];\r\n\t\t\tdouble obs = P[m_SAResult[i].m_ref][P_CE+s];\r\n\t\t\tASSERT(obs >= 0 && obs <= 100);\r\n\r\n\t\t\tdouble sim = Round(100 * cdf(emerge_dist, max(0.0, CDD)), 1);\r\n\t\t\tfor (size_t ii = 0; ii < log(n); ii++)\r\n\t\t\t\tstat.Add(obs, sim);\r\n\r\n\t\t}//for all results\r\n\r\n\t\treturn;\r\n\r\n\t}\r\n\r\n\r\n\tvoid CLeucopisModel::GetFValueDaily(CStatisticXY& stat)\r\n\t{\r\n\t\t//bitset<3> test;\r\n\t\t//test.reset();\r\n\r\n\t\t//test.set(I_EGGS);\r\n\t\t//test.set(I_LARVAE);\r\n\t\t//test.set(I_EMERGED_ADULT);\r\n\r\n\t\tif (!IsParamValid())\r\n\t\t\treturn;\r\n\r\n\t\treturn CalibrateEmergence(stat);\r\n\r\n\t\t//return CalibrateOviposition(stat);\r\n\r\n\t\t//if (!m_SAResult.empty())\r\n\t\t//{\r\n\t\t//\tif (!m_bCumul)\r\n\t\t//\t\tm_bCumul = true;//SA always cumulative\r\n\r\n\t\t//\tif (!m_weather.IsHourly())\r\n\t\t//\t\tm_weather.ComputeHourlyVariables();\r\n\r\n\t\t//\t//low and hi relative development rate must be approximatively the same\r\n\t\t//\t//if (!IsParamValid())\r\n\t\t//\t\t//return;\r\n\r\n\r\n\r\n\t\t//\tfor (size_t y = 0; y < m_weather.GetNbYears(); y++)\r\n\t\t//\t{\r\n\t\t//\t\tint year = m_weather[y].GetTRef().GetYear();\r\n\t\t//\t\tif ((test[0] && m_years[I_EGGS].find(year) != m_years[I_EGGS].end()) ||\r\n\t\t//\t\t\t(test[1] && m_years[I_LARVAE].find(year) != m_years[I_LARVAE].end()) ||\r\n\t\t//\t\t\t(test[2] && m_years[I_EMERGED_ADULT].find(year) != m_years[I_EMERGED_ADULT].end()))\r\n\t\t//\t\t{\r\n\r\n\t\t//\t\t\tCModelStatVector output;\r\n\t\t//\t\t\tCTPeriod p = m_weather[y].GetEntireTPeriod(CTM(CTM::DAILY));\r\n\t\t//\t\t\t//not possible to add a second year without having problem in evaluation....\r\n\t\t//\t\t\t//if (m_weather[y].HaveNext())\r\n\t\t//\t\t\t\t//p.End() = m_weather[y + 1].GetEntireTPeriod(CTM(CTM::DAILY)).End();\r\n\r\n\t\t//\t\t\toutput.Init(p, NB_STATS, 0);\r\n\t\t//\t\t\tExecuteDaily(m_weather[y].GetTRef().GetYear(), m_weather, output);\r\n\r\n\t\t//\t\t\tstatic const size_t STAT_STAGE[3] = { S_EGG, S_L1, S_ACTIVE_ADULT };\r\n\r\n\t\t//\t\t\tfor (size_t i = 0; i < m_SAResult.size(); i++)\r\n\t\t//\t\t\t{\r\n\t\t//\t\t\t\tif (output.IsInside(m_SAResult[i].m_ref))\r\n\t\t//\t\t\t\t{\r\n\r\n\t\t//\t\t\t\t\tfor (size_t j = 0; j < NB_INPUTS; j++)\r\n\t\t//\t\t\t\t\t{\r\n\t\t//\t\t\t\t\t\tif (test[j])\r\n\t\t//\t\t\t\t\t\t{\r\n\t\t//\t\t\t\t\t\t\tdouble obs_y = Round(m_SAResult[i].m_obs[j], ROUND_VAL);\r\n\t\t//\t\t\t\t\t\t\tdouble sim_y = Round(output[m_SAResult[i].m_ref][STAT_STAGE[j]], ROUND_VAL);\r\n\r\n\t\t//\t\t\t\t\t\t\tif (obs_y > -999)\r\n\t\t//\t\t\t\t\t\t\t{\r\n\t\t//\t\t\t\t\t\t\t\tstat.Add(obs_y, sim_y);\r\n\r\n\t\t//\t\t\t\t\t\t\t\tdouble obs_x = m_SAResult[i].m_ref.GetJDay();\r\n\t\t//\t\t\t\t\t\t\t\tdouble sim_x = GetSimX(STAT_STAGE[j], m_SAResult[i].m_ref, obs_y, output);\r\n\r\n\t\t//\t\t\t\t\t\t\t\t/*if (sim_x > -999)\r\n\t\t//\t\t\t\t\t\t\t\t{\r\n\t\t//\t\t\t\t\t\t\t\t\tobs_x = Round(100 * (obs_x - m_nb_days[j][LOWEST]) / m_nb_days[j][RANGE],ROUND_VAL);\r\n\t\t//\t\t\t\t\t\t\t\t\tsim_x = Round(100 * (sim_x - m_nb_days[j][LOWEST]) / m_nb_days[j][RANGE],ROUND_VAL);\r\n\t\t//\t\t\t\t\t\t\t\t\tstat.Add(obs_x, sim_x);\r\n\t\t//\t\t\t\t\t\t\t\t}*/\r\n\t\t//\t\t\t\t\t\t\t}\r\n\t\t//\t\t\t\t\t\t}\r\n\t\t//\t\t\t\t\t}\r\n\t\t//\t\t\t\t}\r\n\t\t//\t\t\t}//for all results\r\n\t\t//\t\t}//have data\r\n\t\t//\t}\r\n\t\t//}\r\n\t}\r\n\r\n\r\n\r\n\t//void CLeucopisModel::FinalizeStat(CStatisticXY& stat)\r\n\t//{\r\n\t//\t\r\n\t//}\r\n}\r\n", "meta": {"hexsha": "9df3218abf6dda830a11f87dd0362a486ec72afe", "size": 13373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wbsModels/Leucopis/LeucopisModel.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": "wbsModels/Leucopis/LeucopisModel.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": "wbsModels/Leucopis/LeucopisModel.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": 27.6301652893, "max_line_length": 147, "alphanum_fraction": 0.5876766619, "num_tokens": 4852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.5208550150284255}}
{"text": "#include <chrono>\n#include <Eigen/Dense>\n#include <opencv2/opencv.hpp>\n#include \"relative_pose/relative_pose.hpp\"\n#include \"precomp.hpp\"\n#include \"relative_pose_estimator.hpp\"\n#include \"nullqr.h\"\n\nnamespace pc_2pot\n{\nusing namespace cv;\n\nclass PC2POTNullEEstimatorCallback CV_FINAL : public RelativePoseEstimatorCallback\n{\n    int runKernel( InputArray _m1, InputArray _m2, OutputArray _model ) const CV_OVERRIDE\n    {\n        Mat3d q1 = _m1.getMat(), q2 = _m2.getMat();\n        CV_Assert(q1.cols == 1 && q2.cols == 1);\n\n        double abuf[2][3], t[1][3];\n        Mat1d A(2, 3, &abuf[0][0]);\n        for (int si = 0; si < 2; ++si)\n            A.row(si) = Mat(q2(si, 0)).reshape(1, 1) * skew(q1(si, 0));\n\n        nullQR<2, 3>(abuf, t);\n        Mat1d tvec(1, 3, &t[0][0]);\n        _model.assign(skew(tvec));\n\n        return 1;\n    }\n};\n\n}\n\nnamespace cv\n{\nint RANSACUpdateNumIters_2pot( double p, double ep, int modelPoints, int maxIters )\n{\n    if( modelPoints <= 0 )\n        CV_Error( Error::StsOutOfRange, \"the number of model points should be positive\" );\n\n    p = MAX(p, 0.);\n    p = MIN(p, 1.);\n    ep = MAX(ep, 0.);\n    ep = MIN(ep, 1.);\n\n    // avoid inf's & nan's\n    double num = MAX(1. - p, DBL_MIN);\n    double denom = 1. - std::pow(1. - ep, modelPoints);\n    if( denom < DBL_MIN )\n        return 0;\n\n    num = std::log(num);\n    denom = std::log(denom);\n\n    return denom >= 0 || -num >= maxIters*(-denom) ? maxIters : cvRound(num/denom);\n}\nclass RANSACPointSetRegistrator_2pot : public PointSetRegistrator\n{\npublic:\n    RANSACPointSetRegistrator_2pot(const Ptr<PointSetRegistrator::Callback>& _cb=Ptr<PointSetRegistrator::Callback>(),\n                              int _modelPoints=0, double _threshold=0, double _confidence=0.99, int _maxIters=1000)\n      : cb(_cb), modelPoints(_modelPoints), threshold(_threshold), confidence(_confidence), maxIters(_maxIters) {}\n\n    int findInliers( const Mat& m1, const Mat& m2, const Mat& model, Mat& err, Mat& mask, double thresh ) const\n    {\n        cb->computeError( m1, m2, model, err );\n        mask.create(err.size(), CV_8U);\n\n        CV_Assert( err.isContinuous() && err.type() == CV_32F && mask.isContinuous() && mask.type() == CV_8U);\n        const float* errptr = err.ptr<float>();\n        uchar* maskptr = mask.ptr<uchar>();\n        float t = (float)(thresh*thresh);\n        int i, n = (int)err.total(), nz = 0;\n        for( i = 0; i < n; i++ )\n        {\n            int f = errptr[i] <= t;\n            maskptr[i] = (uchar)f;\n            nz += f;\n        }\n        // {\n        //     Mat E = model;\n        //     Mat R1, R2, t;\n        //     decomposeEssentialMat(E, R1, R2, t);\n        //     t *= (t.at<double>(2) > 0 ? 1 : -1);\n        //     std::cout << \"---------------\" << std::endl;\n        //     std::cout << \"t = \" << t.t() << \" \" << trace(R1)[0] << \" \" << trace(R2)[0] << \" \" << nz << std::endl;\n        // }\n        return nz;\n    }\n\n    bool getSubset( const Mat& m1, const Mat& m2,\n                    Mat& ms1, Mat& ms2, RNG& rng,\n                    int maxAttempts=1000 ) const\n    {\n        cv::AutoBuffer<int> _idx(modelPoints);\n        int* idx = _idx.data();\n        int i = 0, j, k, iters = 0;\n        int d1 = m1.channels() > 1 ? m1.channels() : m1.cols;\n        int d2 = m2.channels() > 1 ? m2.channels() : m2.cols;\n        int esz1 = (int)m1.elemSize1()*d1, esz2 = (int)m2.elemSize1()*d2;\n        int count = m1.checkVector(d1), count2 = m2.checkVector(d2);\n        const int *m1ptr = m1.ptr<int>(), *m2ptr = m2.ptr<int>();\n\n        ms1.create(modelPoints, 1, CV_MAKETYPE(m1.depth(), d1));\n        ms2.create(modelPoints, 1, CV_MAKETYPE(m2.depth(), d2));\n\n        int *ms1ptr = ms1.ptr<int>(), *ms2ptr = ms2.ptr<int>();\n\n        CV_Assert( count >= modelPoints && count == count2 );\n        CV_Assert( (esz1 % sizeof(int)) == 0 && (esz2 % sizeof(int)) == 0 );\n        esz1 /= sizeof(int);\n        esz2 /= sizeof(int);\n\n        for(; iters < maxAttempts; iters++)\n        {\n            for( i = 0; i < modelPoints && iters < maxAttempts; )\n            {\n                int idx_i = 0;\n                for(;;)\n                {\n                    idx_i = idx[i] = rng.uniform(0, count);\n                    for( j = 0; j < i; j++ )\n                        if( idx_i == idx[j] )\n                            break;\n                    if( j == i )\n                        break;\n                }\n                for( k = 0; k < esz1; k++ )\n                    ms1ptr[i*esz1 + k] = m1ptr[idx_i*esz1 + k];\n                for( k = 0; k < esz2; k++ )\n                    ms2ptr[i*esz2 + k] = m2ptr[idx_i*esz2 + k];\n                i++;\n            }\n            if( i == modelPoints && !cb->checkSubset(ms1, ms2, i) )\n                continue;\n            break;\n        }\n\n        return i == modelPoints && iters < maxAttempts;\n    }\n\n    bool run(InputArray _m1, InputArray _m2, OutputArray _model, OutputArray _mask) const CV_OVERRIDE\n    {\n        bool result = false;\n        Mat m1 = _m1.getMat(), m2 = _m2.getMat();\n        Mat err, mask, model, bestModel, ms1, ms2;\n\n        int iter, niters = MAX(maxIters, 1);\n        int d1 = m1.channels() > 1 ? m1.channels() : m1.cols;\n        int d2 = m2.channels() > 1 ? m2.channels() : m2.cols;\n        int count = m1.checkVector(d1), count2 = m2.checkVector(d2), maxGoodCount = 0;\n\n        RNG rng((uint64)-1);\n\n        CV_Assert( cb );\n        CV_Assert( confidence > 0 && confidence < 1 );\n\n        CV_Assert( count >= 0 && count2 == count );\n        if( count < modelPoints )\n            return false;\n\n        Mat bestMask0, bestMask;\n\n        if( _mask.needed() )\n        {\n            _mask.create(count, 1, CV_8U, -1, true);\n            bestMask0 = bestMask = _mask.getMat();\n            CV_Assert( (bestMask.cols == 1 || bestMask.rows == 1) && (int)bestMask.total() == count );\n        }\n        else\n        {\n            bestMask.create(count, 1, CV_8U);\n            bestMask0 = bestMask;\n        }\n\n        if( count == modelPoints )\n        {\n            if( cb->runKernel(m1, m2, bestModel) <= 0 )\n                return false;\n            bestModel.copyTo(_model);\n            bestMask.setTo(Scalar::all(1));\n            return true;\n        }\n\n        for( iter = 0; iter < niters; iter++ )\n        {\n            int i, nmodels;\n            if( count > modelPoints )\n            {\n                bool found = getSubset( m1, m2, ms1, ms2, rng, 10000 );\n                if( !found )\n                {\n                    if( iter == 0 )\n                        return false;\n                    break;\n                }\n            }\n\n            nmodels = cb->runKernel( ms1, ms2, model );\n            if( nmodels <= 0 )\n                continue;\n            CV_Assert( model.rows % nmodels == 0 );\n            Size modelSize(model.cols, model.rows/nmodels);\n\n            for( i = 0; i < nmodels; i++ )\n            {\n                Mat model_i = model.rowRange( i*modelSize.height, (i+1)*modelSize.height );\n                int goodCount = findInliers( m1, m2, model_i, err, mask, threshold );\n\n                if( goodCount > MAX(maxGoodCount, modelPoints-1) )\n                {\n                    // Mat cheir_mask;\n                    // checkPositiveDepth(m1, m2, model_i, mask, cheir_mask);\n                    // if (!cheir_mask.empty()) mask = cheir_mask;\n                    // goodCount = countNonZero(mask);\n                    // if (goodCount > maxGoodCount)\n                    {\n                        std::swap(mask, bestMask);\n                        model_i.copyTo(bestModel);\n                        maxGoodCount = goodCount;\n                        niters = RANSACUpdateNumIters_2pot( confidence, (double)(count - goodCount)/count, modelPoints, niters );\n                    }\n                }\n            }\n        }\n\n        if( maxGoodCount > 0 )\n        {\n            if( bestMask.data != bestMask0.data )\n            {\n                if( bestMask.size() == bestMask0.size() )\n                    bestMask.copyTo(bestMask0);\n                else\n                    transpose(bestMask, bestMask0);\n            }\n            bestModel.copyTo(_model);\n            result = true;\n        }\n        else\n            _model.release();\n\n        return result;\n    }\n\n    void setCallback(const Ptr<PointSetRegistrator::Callback>& _cb) CV_OVERRIDE { cb = _cb; }\n\n    Ptr<PointSetRegistrator::Callback> cb;\n    int modelPoints;\n    double threshold;\n    double confidence;\n    int maxIters;\n};\n\nMat estimateRelativePose_PC2POT(\n        InputArray _rays1, InputArray _rays2,\n        int method, double prob, double threshold, OutputArray _mask)\n{\n    // CV_INSTRUMENT_REGION();\n    Mat rays1, rays2;\n    processInputArray(_rays1, _rays2, rays1, rays2);\n\n    Mat models;\n    if( method == RANSAC )\n    //     createRANSACPointSetRegistrator_2pot(\n    //             makePtr<pc_2pot::PC2POTNullEEstimatorCallback>(), 2, threshold, prob)->run(\n    //             rays1, rays2, models, _mask);\n    {\n        auto reg = RANSACPointSetRegistrator_2pot(\n                makePtr<pc_2pot::PC2POTNullEEstimatorCallback>(), 4, threshold, prob);\n        reg.run(rays1, rays2, models, _mask);\n    }\n    else\n        createLMeDSPointSetRegistrator(\n                makePtr<pc_2pot::PC2POTNullEEstimatorCallback>(), 2, prob)->run(\n                rays1, rays2, models, _mask);\n\n    return models;\n}\n\n}\n", "meta": {"hexsha": "e7d240f42d706cc9535937cce5198ebc9ebca124", "size": 9360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/relative_pose/pc_2pot.cpp", "max_stars_repo_name": "youruncleda/relative_pose", "max_stars_repo_head_hexsha": "cb613f210a812e03754fbfc9c2e93d1f6fe4a265", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2020-07-08T17:58:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:58:37.000Z", "max_issues_repo_path": "src/relative_pose/pc_2pot.cpp", "max_issues_repo_name": "taogashi/relative_pose", "max_issues_repo_head_hexsha": "cb613f210a812e03754fbfc9c2e93d1f6fe4a265", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/relative_pose/pc_2pot.cpp", "max_forks_repo_name": "taogashi/relative_pose", "max_forks_repo_head_hexsha": "cb613f210a812e03754fbfc9c2e93d1f6fe4a265", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-07-24T01:26:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-13T13:32:48.000Z", "avg_line_length": 33.1914893617, "max_line_length": 129, "alphanum_fraction": 0.5025641026, "num_tokens": 2639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.520820135047371}}
{"text": "#ifndef TYPES_HH\n#define TYPES_HH\n\n#include <Eigen/Dense>\n#include <array>\n#include <type_traits>\n#include \"unused.hh\"\ntypedef double Real;\n\n#include <MeshFEM_export.h>\n\ntemplate<size_t N>\nusing VectorND = Eigen::Matrix<Real, N, 1, Eigen::ColMajor, N, 1>;\ntemplate<size_t N>\nusing PointND = VectorND<N>;\ntemplate<size_t N>\nusing IVectorND = std::array<int, N>;\n\ntypedef  PointND<3>  Point3D;\ntypedef VectorND<3> Vector3D;\ntypedef  PointND<2>  Point2D;\ntypedef VectorND<2> Vector2D;\n\nMESHFEM_EXPORT extern Eigen::IOFormat pointFormatter;\n\n// Types templated on floating point representation.\ntemplate<typename Real_> using  Vec3_T = Eigen::Matrix<Real_, 3, 1>;\ntemplate<typename Real_> using   Pt3_T = Vec3_T<Real_>;\ntemplate<typename Real_> using  Vec2_T = Eigen::Matrix<Real_, 2, 1>;\ntemplate<typename Real_> using  VecX_T = Eigen::Matrix<Real_, Eigen::Dynamic, 1>;\ntemplate<typename Real_> using  Mat3_T = Eigen::Matrix<Real_, 3, 3>;\ntemplate<typename Real_> using  Mat2_T = Eigen::Matrix<Real_, 2, 2>;\ntemplate<typename Real_> using MatX3_T = Eigen::Matrix<Real_, Eigen::Dynamic, 3>;\n\nextern Eigen::IOFormat pointFormatter;\n\ntemplate<class EmbeddingSpace, class Enable = void> struct Padder;\ntemplate<class EmbeddingSpace, class Enable = void> struct Truncator;\n\ntemplate<class EigenType, int RowSize, int ColSize, class Enable = void>\nstruct isMatrixOfSize : std::false_type { };\n\ntemplate<class EigenType, int RowSize, int ColSize>\nstruct isMatrixOfSize<EigenType, RowSize, ColSize, typename std::enable_if<(EigenType::RowsAtCompileTime == RowSize) &&\n                                                                           (EigenType::ColsAtCompileTime == ColSize), void>::type> : std::true_type { };\n\ntemplate<class EigenType, class Enable = void>\nstruct isCompileTimeSizedEigen : std::false_type { };\n\ntemplate<class EigenType>\nstruct isCompileTimeSizedEigen<EigenType, typename std::enable_if<(EigenType::RowsAtCompileTime > 0) &&\n                                                                  (EigenType::ColsAtCompileTime > 0), void>::type> : std::true_type { };\n\ntemplate<class EigenType, int RowSize, int ColSize, typename T = void>\nusing EnableIfMatrixOfSize = typename std::enable_if<isMatrixOfSize<EigenType, RowSize, ColSize>::value, T>::type;\n\ntemplate<class EigenType, int VectorSize, typename T = void>\nusing EnableIfVectorOfSize = EnableIfMatrixOfSize<EigenType, VectorSize, 1, T>;\n\ntemplate<class EigenType> using V3MatchingScalarType = Eigen::Matrix<typename EigenType::Scalar, 3, 1>;\ntemplate<class EigenType> using V2MatchingScalarType = Eigen::Matrix<typename EigenType::Scalar, 2, 1>;\ntemplate<class EigenType> using V1MatchingScalarType = Eigen::Matrix<typename EigenType::Scalar, 1, 1>;\n\n// Padding, truncation of 2D, 3D vectors\ntemplate<class EigenType> struct    Padder<EigenType, EnableIfVectorOfSize<EigenType, 1>> { static V3MatchingScalarType<EigenType> run(const EigenType &p) { return V3MatchingScalarType<EigenType>(p[0],  0.0, 0.0); } };\ntemplate<class EigenType> struct    Padder<EigenType, EnableIfVectorOfSize<EigenType, 2>> { static V3MatchingScalarType<EigenType> run(const EigenType &p) { return V3MatchingScalarType<EigenType>(p[0], p[1], 0.0); } };\ntemplate<class EigenType> struct    Padder<EigenType, EnableIfVectorOfSize<EigenType, 3>> { static const EigenType &               run(const EigenType &p) { return p; } }; // pass-through\ntemplate<class EigenType> struct Truncator<EigenType, EnableIfVectorOfSize<EigenType, 1>> { template<typename InEigenType> static       EnableIfVectorOfSize<InEigenType, 3, V1MatchingScalarType<EigenType>>  run(const InEigenType &pt3D) { if ((std::abs(pt3D[1]) > 1e-6) || (std::abs(pt3D[1]) > 1e-6)) throw std::runtime_error(\"Nonzero y or z component in embedded Point1D\"); return V1MatchingScalarType<EigenType>(pt3D[0]); }\n                                                                                            template<typename InEigenType> static       EnableIfVectorOfSize<InEigenType, 2, V1MatchingScalarType<EigenType>>  run(const InEigenType &pt2D) { if ( std::abs(pt2D[1]) > 1e-6                               ) throw std::runtime_error(\"Nonzero y component in embedded Point1D\");      return V1MatchingScalarType<EigenType>(pt2D[0]); }\n                                                                                            template<typename InEigenType> static const EnableIfVectorOfSize<InEigenType, 1,                     InEigenType> &run(const InEigenType &pt1D) { return pt1D; } }; // pass-through\ntemplate<class EigenType> struct Truncator<EigenType, EnableIfVectorOfSize<EigenType, 2>> { template<typename InEigenType> static       EnableIfVectorOfSize<InEigenType, 3, V2MatchingScalarType<EigenType>>  run(const InEigenType &pt3D) { if (std::abs(pt3D[2]) > 1e-6) throw std::runtime_error(\"Nonzero z component in embedded Point2D\"); return V2MatchingScalarType<EigenType>(pt3D[0], pt3D[1]); }\n                                                                                            template<typename InEigenType> static const EnableIfVectorOfSize<InEigenType, 2,                     InEigenType> &run(const InEigenType &pt2D) { return pt2D; } }; // pass-through\ntemplate<class EigenType> struct Truncator<EigenType, EnableIfVectorOfSize<EigenType, 3>> { template<typename InEigenType> static const EnableIfVectorOfSize<InEigenType, 3,                     InEigenType> &run(const InEigenType &pt3D) { return pt3D; } }; // pass-through\n\n// Provide padding/truncation for points of eigen type.\ntemplate<                       class InPointDerived> V3MatchingScalarType<InPointDerived> padTo3D(const Eigen::MatrixBase<InPointDerived> &p) { return    Padder<Eigen::MatrixBase< InPointDerived>>::run(p); }\ntemplate<class OutPointDerived, class InPointDerived> OutPointDerived               truncateFrom3D(const Eigen::MatrixBase<InPointDerived> &p) { return Truncator<Eigen::MatrixBase<OutPointDerived>>::run(p).template cast<typename OutPointDerived::Scalar>(); }\n\n// Also provide padding/truncation for points of eigen type nested inside, e.g., a MeshIO::IOVertex instance.\ntemplate<class InVertex                       , class NestedPointType = decltype(InVertex().point)> V3MatchingScalarType<NestedPointType> padTo3D(const InVertex &v) { return    Padder<NestedPointType                   >::run(v.point); }\ntemplate<class OutPointDerived, class InVertex, class NestedPointType = decltype(InVertex().point)> OutPointDerived                truncateFrom3D(const InVertex &v) { return Truncator<Eigen::MatrixBase<OutPointDerived>>::run(v.point).template cast<typename OutPointDerived::Scalar>(); }\n\n// Compile-time sizes with compile-time checking\ntemplate<class EmbeddingSpace, class InputDerived, typename std::enable_if<isCompileTimeSizedEigen<  InputDerived>::value &&\n                                                                           isCompileTimeSizedEigen<EmbeddingSpace>::value, int>::type = 0>\nEmbeddingSpace truncateFromND(const Eigen::DenseBase<InputDerived> &p) {\n    constexpr int  inRows =   InputDerived::RowsAtCompileTime,\n                   inCols =   InputDerived::ColsAtCompileTime,\n                  outRows = EmbeddingSpace::RowsAtCompileTime,\n                  outCols = EmbeddingSpace::ColsAtCompileTime;\n    static_assert((inRows > 0) && (outRows > 0), \"Vectors must be statically sized, nonempty\");\n    static_assert((inCols == 1) && (outCols == 1), \"We operate only on vectors\");\n    static_assert(inRows >= outRows, \"Truncation cannot upsize\");\n    EmbeddingSpace result = p.template head<outRows>();\n    for (int i = outRows; i < inRows; ++i) {\n        if (std::abs(p[i]) > 1e-6)\n            throw std::runtime_error(\"Nonzero component truncated.\");\n    }\n    return result;\n}\n\n// Dynamic input size, compile-time output size with partial compile-time checking.\ntemplate<class EmbeddingSpace, class InputDerived, typename std::enable_if<!isCompileTimeSizedEigen<  InputDerived>::value &&\n                                                                            isCompileTimeSizedEigen<EmbeddingSpace>::value, int>::type = 0>\nEmbeddingSpace truncateFromND(const Eigen::DenseBase<InputDerived> &p) {\n    constexpr int outRows = EmbeddingSpace::RowsAtCompileTime,\n                  outCols = EmbeddingSpace::ColsAtCompileTime;\n    const     int  inRows = p.rows();\n    static_assert(outRows > 0, \"Output vector must be statically sized, nonempty\");\n    static_assert(outCols == 1, \"Output must be a vector\");\n\n    assert((inRows >= outRows) && \"Truncation cannot upsize\");\n    assert((p.cols() == outCols) && \"Input must be a vector\");\n    EmbeddingSpace result = p.template head<outRows>();\n    for (int i = outRows; i < inRows; ++i) {\n        if (std::abs(p[i]) > 1e-6)\n            throw std::runtime_error(\"Nonzero component truncated.\");\n    }\n    return result;\n}\n\n// Work around alignment issues for C++ versions before C++17:\n// http://eigen.tuxfamily.org/dox-devel/group__TopicStlContainers.html\n#include <Eigen/StdVector>\n#include <vector>\ntemplate<typename T>\nusing aligned_std_vector = std::vector<T, Eigen::aligned_allocator<T>>;\n\n#endif /* end of include guard: TYPES_HH */\n", "meta": {"hexsha": "1354b7db190846e932c8ee0731b40c0e9d89b34c", "size": 9139, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/lib/MeshFEM/Types.hh", "max_stars_repo_name": "pbedenbaugh/MeshFEM", "max_stars_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_stars_repo_licenses": ["MIT"], "max_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/MeshFEM/Types.hh", "max_issues_repo_name": "pbedenbaugh/MeshFEM", "max_issues_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_issues_repo_licenses": ["MIT"], "max_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/MeshFEM/Types.hh", "max_forks_repo_name": "pbedenbaugh/MeshFEM", "max_forks_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.3, "max_line_length": 424, "alphanum_fraction": 0.68738374, "num_tokens": 2299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5208201294134904}}
{"text": "#ifndef __num_t_hpp__\n#define __num_t_hpp__\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing int_t = boost::multiprecision::number\n<\n   boost::multiprecision::cpp_int_backend<>,\n   boost::multiprecision::expression_template_option::et_off\n>;\n\nusing num_t = boost::multiprecision::number\n<\n   boost::multiprecision::cpp_dec_float<1024>,\n   boost::multiprecision::expression_template_option::et_off\n>;\n\n#endif\n", "meta": {"hexsha": "e32949fc823f62dba3a8aed367af9ed8924dbd1a", "size": 461, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "num_t.hpp", "max_stars_repo_name": "kensmith/mancalc", "max_stars_repo_head_hexsha": "db0c2d15811f0da76689ec3c3cc94d9d56d1612d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-24T22:51:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T22:51:38.000Z", "max_issues_repo_path": "num_t.hpp", "max_issues_repo_name": "kensmith/mancalc", "max_issues_repo_head_hexsha": "db0c2d15811f0da76689ec3c3cc94d9d56d1612d", "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": "num_t.hpp", "max_forks_repo_name": "kensmith/mancalc", "max_forks_repo_head_hexsha": "db0c2d15811f0da76689ec3c3cc94d9d56d1612d", "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.05, "max_line_length": 60, "alphanum_fraction": 0.7874186551, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.520820118145729}}
{"text": "#include <iostream>\n\n#include <adept_arrays.h>\n\n#include \"Timer.h\"\n\ntemplate<bool IsActive>\ndouble\ntime_operation(int n, int nrepeat, bool is_col_major)\n{\n  adept::Array<2,double,IsActive> A, B, C;\n  Timer timer;\n  int matmul_timer_id = timer.new_activity(\"matmul\");\n  if (is_col_major) {\n    A.resize_column_major(adept::expression_size(n,n));\n    B.resize_column_major(adept::expression_size(n,n));\n    C.resize_column_major(adept::expression_size(n,n));\n  }\n  else {\n    A.resize(n,n);\n    B.resize(n,n);\n    C.resize(n,n);\n  }\n  for (int irepeat = -nrepeat/10; irepeat < nrepeat; ++irepeat) {\n    A = 1.1;\n    B = 2.2;\n    if (IsActive) {\n      adept::active_stack()->new_recording();\n    }\n    if (irepeat >= 0) {\n      timer.start(matmul_timer_id);\n    }\n    C = A ** B;\n    if (irepeat >= 0) {\n      timer.stop();\n    }\n  }\n  if (IsActive && n < 8) {\n    std::cout << \"C=\" << C;\n    std::cout << *adept::active_stack();\n    adept::active_stack()->print_statements();\n  }\n  return timer.timing(matmul_timer_id) / nrepeat;\n}\n\n\nint\nmain(int argc, char* argv[])\n{\n  int ibegin = 1;\n  int iend = 18;\n  int nrepeat = 10;\n  bool is_col_major = false;\n\n  adept::Stack stack;\n  int n = 2;\n  std::cout << \"Dense N-by-N matrix-matrix multiplication\\n\";\n  std::cout << \" N        inactive time (us)   inactive flops    active time (us)    active flops\\n\";\n  for (int i = ibegin; i <= iend; ++i) {\n    std::cout << n << \"  \";\n\n    double t = time_operation<false>(n, nrepeat, is_col_major);\n    std::cout << t*1.0e6 << \"  \" << (n*n*n) / t << \"  \";\n\n    t = time_operation<true>(n, nrepeat, is_col_major);\n    std::cout << t*1.0e6 << \"  \" << (n*n*n) / t;\n\n    std::cout << \"\\n\";\n\n    n *= 2;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "9e6fd6fcd7b600436dc4a81badd4e6e5e9bae05b", "size": 1703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/matrix_benchmark.cpp", "max_stars_repo_name": "yairchu/Adept-2", "max_stars_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 131.0, "max_stars_repo_stars_event_min_datetime": "2016-07-06T04:06:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T22:34:47.000Z", "max_issues_repo_path": "benchmark/matrix_benchmark.cpp", "max_issues_repo_name": "yairchu/Adept-2", "max_issues_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2016-06-20T20:20:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T14:55:01.000Z", "max_forks_repo_path": "benchmark/matrix_benchmark.cpp", "max_forks_repo_name": "yairchu/Adept-2", "max_forks_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-10-07T00:07:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T17:51:17.000Z", "avg_line_length": 23.0135135135, "max_line_length": 101, "alphanum_fraction": 0.5801526718, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.52082011811652}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Search_traits_3.h>\n#include <CGAL/Search_traits_adapter.h>\n#include <CGAL/point_generators_3.h>\n#include <CGAL/Orthogonal_k_neighbor_search.h>\n#include <CGAL/property_map.h>\n#include <boost/iterator/zip_iterator.hpp>\n#include <utility>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::Point_3                                     Point_3;\ntypedef boost::tuple<Point_3,int>                           Point_and_int;\n\ntypedef CGAL::Random_points_in_cube_3<Point_3>              Random_points_iterator;\ntypedef CGAL::Search_traits_3<Kernel>                       Traits_base;\ntypedef CGAL::Search_traits_adapter<Point_and_int,\n  CGAL::Nth_of_tuple_property_map<0, Point_and_int>,\n  Traits_base>                                              Traits;\n\n\ntypedef CGAL::Orthogonal_k_neighbor_search<Traits>          K_neighbor_search;\ntypedef K_neighbor_search::Tree                             Tree;\ntypedef K_neighbor_search::Distance                         Distance;\n\nint main() {\n  const unsigned int K = 5;\n  // generator for random data points in the cube ( (-1,-1,-1), (1,1,1) )\n  Random_points_iterator rpit( 1.0);\n  std::vector<Point_3> points;\n  std::vector<int>     indices;\n  \n  points.push_back(Point_3(*rpit++));\n  points.push_back(Point_3(*rpit++));\n  points.push_back(Point_3(*rpit++));\n  points.push_back(Point_3(*rpit++));\n  points.push_back(Point_3(*rpit++));\n  points.push_back(Point_3(*rpit++));\n  points.push_back(Point_3(*rpit++));\n\n  indices.push_back(0);\n  indices.push_back(1);\n  indices.push_back(2);\n  indices.push_back(3);\n  indices.push_back(4);\n  indices.push_back(5);\n  indices.push_back(6);\n\n  // Insert number_of_data_points in the tree\n  Tree tree(\n    boost::make_zip_iterator(boost::make_tuple( points.begin(),indices.begin() )),\n    boost::make_zip_iterator(boost::make_tuple( points.end(),indices.end() ) )  \n  );\n  Point_3 query(0.0, 0.0, 0.0);\n  Distance tr_dist;\n\n  // search K nearest neighbours\n  K_neighbor_search search(tree, query, K);\n  for(K_neighbor_search::iterator it = search.begin(); it != search.end(); it++){\n    std::cout << \" d(q, nearest neighbor)=  \"\n\t      << tr_dist.inverse_of_transformed_distance(it->second) << \" \" \n              << boost::get<0>(it->first)<< \" \" << boost::get<1>(it->first) << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "0b55ad64a4dca19564992f08a5569c4e484a4e41", "size": 2394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Spatial_searching/searching_with_point_with_info.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/Spatial_searching/searching_with_point_with_info.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/Spatial_searching/searching_with_point_with_info.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": 36.8307692308, "max_line_length": 89, "alphanum_fraction": 0.6649958229, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.52082011245343}}
{"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_SECPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SECPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing secpi capabilities\n\n    secant of the angle in pi multiples: \\f$1/\\cos(\\pi x)\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = secpi(x);\n    @endcode\n\n    @see secd, sec, cospi, cos\n\n  **/\n  Value secpi(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/secpi.hpp>\n#include <boost/simd/function/simd/secpi.hpp>\n\n#endif\n", "meta": {"hexsha": "ca6ae149fd76c64d59e92ff113c91e4da5974524", "size": 998, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/secpi.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/secpi.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/secpi.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": 22.6818181818, "max_line_length": 100, "alphanum_fraction": 0.5691382766, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5208201068195493}}
{"text": "# ifndef MC_FUNCTIONS_H\n#include \"MC_functions.hpp\"\n# endif\n\n# ifndef COMMON_HEADERS_H\n#include \"common_headers.hpp\"\n# endif\n\n//#include <iomanip>\n\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/format.hpp> // It seems like I might as well just include <boost/kitchen_sink.hpp>\n#include <boost/math/special_functions/ellint_1.hpp>\n#include <boost/math/special_functions/ellint_2.hpp>\n\nusing std::string;\nnamespace br = boost::random;\nnamespace bu = boost::uuids;\n\nParams::Params(size_t len, size_t LL, size_t samples, uint64_t eqSteps,\n        double tmp, string bName, bu::uuid id, br::mt19937_64 engine, \n        br::uniform_real_distribution<double> dist)\n{\n    L = len;\n    N = LL;\n    numSamp = samples;\n    numEqSteps = eqSteps;\n//    beta = bta;\n    temp = tmp;\n    baseName = bName;\n    uid = id;\n    rng = engine;\n    dist01 = dist;\n}\n\ndouble Params::GetRNG01()\n{\n    return dist01(rng);\n}\n\ndouble GetCurrentMagnetization(int64_t *sigma, size_t L)\n{\n    double M = 0;\n    for(size_t i = 0; i < L*L; i++)\n    {\n            M += sigma[i];\n    }\n\n    return M /= (L*L);\n}\n\ndouble GetProperties(int64_t *s, int64_t *plus1, int64_t *minus1, size_t L)\n{\n    double E = 0;\n\n    for(size_t j = 0; j < L; j++)\n    {\n        for(size_t i = 0; i < L; i++)\n        {\n            E -= 0.5 * s[i + L*j] * ( s[plus1[i] + L*j] + s[minus1[i] + L*j] + s[i + L*plus1[j]] + s[i + L*minus1[j]] );\n        }\n    }\n    return E/(L*L);\n}\n\ndouble Update(Params *Pars, int64_t *s, br::uniform_int_distribution<size_t> *dist0L,\n        int64_t *plus1, int64_t *minus1)\n{\n    size_t k = 0;\n    size_t l = 0;\n    size_t L = Pars->L;\n    int64_t deltaE = 0;\n    double M = 0;\n    \n    for(size_t i = 0; i < Pars->N; i++) { M += s[i]; }\n    for(size_t u = 0; u < Pars->N; u++)\n    {\n        k = (*dist0L)(Pars->rng);\n        l = (*dist0L)(Pars->rng);\n        deltaE = 2.0 * s[k + L*l] * ( s[plus1[k] + L*l] + s[minus1[k] + L*l] + s[k + L*plus1[l]] + s[k + L*minus1[l]] );\n        if(deltaE <= 0)\n        {\n            s[k + L*l] *= -1;   // Flip that spin\n            M += 2*s[k + L*l];     // Add to M\n        }\n\n        else if (Pars->GetRNG01() <= (double)exp(-deltaE / Pars->temp))\n        {\n            s[k + L*l] *= -1;   // Flip that spin\n            M += 2*s[k + L*l];     // Add to M\n        }\n    }\n\n    return M/Pars->N;\n}\n\nvoid MonteCarlo(Params Pars)\n{\n    int64_t sigma[Pars.N];\n    for(size_t i = 0; i < Pars.N; i++)\n    {\n        sigma[i] = Pars.GetRNG01() < 0.5 ? -1 : 1;\n    }\n\n    // Expectation value accumulator\n    // Order is: E, M\n    double expecValues[2] = { 0.0, 0.0 };\n    size_t sampleCount = 0;\n\n    // Miscellaneous variables and utilities\n    br::uniform_int_distribution<size_t> dist0L(0, Pars.L-1); \n    string uid_string = bu::to_string(Pars.uid);\n\n    string Lcomp = \"-L_\" + std::to_string(Pars.L);\n    boost::format tempFormatter(\"%06.3f\");\n    string tempComp = \"-T_\" + (tempFormatter % Pars.temp).str();\n    string fileName = \"output\" + Lcomp + tempComp + \"-\" + uid_string + \".dat\";\n\n    FILE *fP;   // File pointer\n    fP = fopen(fileName.c_str(), \"w\");\n    fprintf(fP, \"# PIMCID: %s\\n\", uid_string.c_str());\n    fprintf(fP, \"#\\tE\\t\\tM\\n\");\n    fclose(fP);\n\n    // Create lookup tables for PBCs. Why compute it every time? \n    int64_t plus1[Pars.L];\n    int64_t minus1[Pars.L];\n    for(size_t i = 0; i < Pars.L; i++)\n    {\n        plus1[i] = i+1;\n        minus1[i] = i-1;\n    }\n    plus1[Pars.L-1] = 0;\n    minus1[0] = Pars.L-1;\n    \n// === Begin MC loop here =====================================================\n    // Equilibriate\n    printf(\"Equlibriating...\\n\");\n    expecValues[1] = GetCurrentMagnetization(sigma, Pars.L);\n\n    for(uint64_t step = 0; step < Pars.numEqSteps; step++)\n    {\n        // Perform the updates\n        expecValues[1] = Update(&Pars, sigma, &dist0L, plus1, minus1);\n    }\n    \n    // Collect data\n    printf(\"Collecting data...\\n\");\n    while(sampleCount < Pars.numSamp)\n    {\n        // Perform the updates\n        expecValues[1] = Update(&Pars, sigma, &dist0L, plus1, minus1);\n        expecValues[0] = GetProperties(sigma, plus1, minus1, Pars.L);\n\n        fP = fopen(fileName.c_str(), \"a\");\n        fprintf(fP, \"%f\\t%f\\n\", expecValues[0], expecValues[1]);\n        fclose(fP);\n\n        sampleCount++;\n        if(sampleCount % 1024 == 0)\n        {\n            printf(\"Writing to disk sample %10ld / %10ld\\r\", sampleCount, Pars.numSamp);\n        }\n    }\n    printf(\"Data collection is done.\\n\");\n    printf(\"The UUID is: %s\\n\", uid_string.c_str());\n\n    double q = 2 * sinh(2/Pars.temp) / (cosh(2/Pars.temp) * cosh(2/Pars.temp));\n    double exactEatT = -1/tanh(2/Pars.temp) * ( 1 + 2/M_PI * (2 * tanh(2/Pars.temp) * tanh(2/Pars.temp)- 1) * boost::math::ellint_1(q) );\n    printf(\"Exact E at %f K: %f\\n\\n\", Pars.temp, exactEatT);\n}\n", "meta": {"hexsha": "5ad89c86ec19880f56db7dbf831d85ee7d1d317a", "size": 4802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MC_functions.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": "MC_functions.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": "MC_functions.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": 27.9186046512, "max_line_length": 137, "alphanum_fraction": 0.5489379425, "num_tokens": 1565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5208111089055946}}
{"text": "/*!\n * @file\n * This file defines unit tests for `boost::mpl::reachable_set`.\n */\n\n#include <boost/mpl/reachable_set.hpp>\n#include <boost/mpl/set.hpp>\n#include <boost/mpl/set_equal.hpp>\n#include <boost/mpl/vector.hpp>\n\n\nusing namespace boost::mpl;\n\ntemplate <typename ...AdjacentVertices>\nstruct vertex {\n    using open_neighborhood = vector<AdjacentVertices...>;\n};\n\nstruct dummy_graph;\n\nnamespace test_cyclic_graph {\n    // cycle: u0 -> u2 -> u1 -> u0\n    struct u0 : vertex<struct u2> { };\n    struct u1 : vertex<u0> { };\n    struct u2 : vertex<u1> { };\n\n    static_assert(set_equal<\n        reachable_set<dummy_graph, u0>::type, set<u0, u2, u1>\n    >::value, \"\");\n\n    static_assert(set_equal<\n        reachable_set<dummy_graph, u1>::type, set<u1, u0, u2>\n    >::value, \"\");\n\n    static_assert(set_equal<\n        reachable_set<dummy_graph, u2>::type, set<u2, u1, u0>\n    >::value, \"\");\n}\n\nnamespace test_acyclic_graph {\n    struct v0 : vertex<> { };\n    struct v1 : vertex<v0> { };\n    struct v2 : vertex<v0, v1> { };\n    struct v3 : vertex<v1> { };\n\n    static_assert(set_equal<\n        reachable_set<dummy_graph, v0>::type, set<v0>\n    >::value, \"\");\n\n    static_assert(set_equal<\n        reachable_set<dummy_graph, v1>::type, set<v1, v0>\n    >::value, \"\");\n\n    static_assert(set_equal<\n        reachable_set<dummy_graph, v2>::type, set<v2, v0, v1>\n    >::value, \"\");\n\n    static_assert(set_equal<\n        reachable_set<dummy_graph, v3>::type, set<v3, v1, v0>\n    >::value, \"\");\n}\n\n\nint main() { }\n", "meta": {"hexsha": "0e37f00553a2ab046905aea1ed9b82cfc05f13fc", "size": 1505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/reachable_set.cpp", "max_stars_repo_name": "ldionne/mpl_extensions", "max_stars_repo_head_hexsha": "ca728992567b96dad884be1658b0822a955174cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-25T19:19:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-25T19:19:06.000Z", "max_issues_repo_path": "test/reachable_set.cpp", "max_issues_repo_name": "ldionne/mpl_extensions", "max_issues_repo_head_hexsha": "ca728992567b96dad884be1658b0822a955174cc", "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/reachable_set.cpp", "max_forks_repo_name": "ldionne/mpl_extensions", "max_forks_repo_head_hexsha": "ca728992567b96dad884be1658b0822a955174cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-25T19:19:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-25T19:19:07.000Z", "avg_line_length": 23.1538461538, "max_line_length": 64, "alphanum_fraction": 0.6172757475, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.520811104488582}}
{"text": "// ParticleUtilities.cpp\n// Copyright 2019 Mikko Lauri\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 \"ParticleUtilities.h\"\n#include <boost/random/uniform_real_distribution.hpp>\n#include <eigen3/Eigen/Dense>\n#include \"common.hpp\"\n\nnamespace pgi {\ndouble normalize(std::vector<double>& weights) {\n  if (weights.empty()) {\n    return 0.0;\n  } else {\n    Eigen::Map<Eigen::VectorXd> w(weights.data(), weights.size());\n    const double wsum = w.lpNorm<1>();\n    if (!is_almost_zero(wsum)) w /= wsum;\n    return wsum;\n  }\n}\n\n// Implements systematic resampling\nvoid resample(const std::vector<double>& weights,\n              std::vector<std::size_t>& resample_indices, PRNG& rng) {\n  resample_indices.resize(weights.size());\n  double cdf = 0.0;\n  std::size_t curr_index = 0;\n\n  const double incr = 1.0 / static_cast<double>(weights.size());\n  boost::random::uniform_real_distribution<double> U(0, incr);\n  double u = rng(U);\n  for (auto& resample_index : resample_indices) {\n    while (u > cdf) {\n      cdf += weights[curr_index];\n      ++curr_index;\n    }\n    resample_index = curr_index - 1;\n    u += incr;\n  }\n}\n\ndouble effective_size(const std::vector<double>& weights) {\n  Eigen::Map<const Eigen::VectorXd> w(weights.data(), weights.size());\n  return 1.0 / w.squaredNorm();\n}\n\n}  // namespace pgi\n", "meta": {"hexsha": "52a50ab903a410ded00a74d7b6b6c2327f077eaf", "size": 1818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dec_pomdp_algorithm/src/ParticleUtilities.cpp", "max_stars_repo_name": "TAMS-Group/decpomdp_signal_source_localization", "max_stars_repo_head_hexsha": "3e785c6bb464a1f853b889ce4e3ac343243bc030", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-05-06T09:31:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T03:27:29.000Z", "max_issues_repo_path": "src/dec_pomdp_algorithm/src/ParticleUtilities.cpp", "max_issues_repo_name": "TAMS-Group/decpomdp_signal_source_localization", "max_issues_repo_head_hexsha": "3e785c6bb464a1f853b889ce4e3ac343243bc030", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-02T16:33:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T08:45:24.000Z", "max_forks_repo_path": "src/dec_pomdp_algorithm/src/ParticleUtilities.cpp", "max_forks_repo_name": "TAMS-Group/decpomdp_signal_source_localization", "max_forks_repo_head_hexsha": "3e785c6bb464a1f853b889ce4e3ac343243bc030", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-09T02:09:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-02T15:43:12.000Z", "avg_line_length": 30.813559322, "max_line_length": 75, "alphanum_fraction": 0.6919691969, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5208111004612012}}
{"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// Generate input data for an example C++ code that demonstrates usage of PnP solvers.\n// See pnp_test for more thorough tests of the PnP API.\n\n#include \"engine/core/logger.hpp\"\n#include \"packages/pnp/gems/pnp.hpp\"\n#include \"packages/pnp/gems/tests/simu.hpp\"\n\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <random>\n\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n\n// Print an Eigen matrix such that it can be copy-pasted into a C++ source file.\nvoid PrintMatrixCode(const isaac::MatrixXd& mat) {\n  for (int i = 0; i < mat.rows(); i++) {\n    for (int j = 0; j < mat.cols(); j++) {\n      std::cout << mat(i, j);\n      if (j + 1 < mat.cols()) std::cout << \", \";\n    }\n    if (i + 1 == mat.rows())\n      std::cout << \";\\n\";\n    else\n      std::cout << \",\\n\";\n  }\n}\n\n// Print an isaac pose for example C++ code.\nstd::ostream& operator<<(std::ostream& os, const isaac::Pose3d& pose) {\n  std::cout << \"translation = (\" << pose.translation.transpose() << \"), \";\n  std::cout << \"angle = \" << pose.rotation.angle() << \", \";\n  std::cout << \"axis = (\" << pose.rotation.axis().transpose() << \")\";\n  return os;\n}\n\n// Test equivalence of two poses (a and b) are similar within tolerance parameters.\nvoid TestPoseEquivalence(const isaac::Pose3d& a, const isaac::Pose3d& b, double max_distance = 1e-9,\n                         double max_angle_degrees = 1e-9) {\n  // Calculate difference in orientation.\n  isaac::SO3d delta_rot = a.rotation.inverse() * b.rotation;\n  double angle = std::fmod(isaac::RadToDeg(std::abs(delta_rot.angle())), 360.0);\n  angle = std::min(angle, 360.0 - angle);\n\n  // Calculate difference in position.\n  // Convert world origin in camera frame to camera position in world frame. This can make\n  // a significant difference in case of a moving camera far away from world origin.\n  isaac::Vector3d position1 = -a.rotation.matrix().transpose() * a.translation;\n  isaac::Vector3d position2 = -b.rotation.matrix().transpose() * b.translation;\n\n  ASSERT_LT((position1 - position2).norm(), max_distance);\n  ASSERT_LT(angle, max_angle_degrees);\n}\n\n// Generate an example for PnP and test EPnP on the example data.\nTEST(PnpTest, TestEpnpExample) {\n  // Generate synthetic camera.\n  const int width = 1280;\n  const int height = 720;\n  const double focal = 700.0;\n  isaac::pnp::Camera camera = isaac::pnp::GenerateRandomCamera(width, height, focal);\n\n  // Construct isaac::Pose3d object from the generated camera pose.\n  // This is the known ground-truth pose to compare to the output of pose estimation.\n  isaac::Vector3d gt_angle_axis = isaac::pnp::AngleAxisFromMatrix(camera.rotation_matrix);\n  isaac::Pose3d gt_pose{isaac::SO3d::FromAngleAxis(gt_angle_axis.norm(), gt_angle_axis),\n                        -camera.rotation_matrix * camera.position};\n  std::cout << gt_pose << std::endl;\n\n  // Print camera intrinsics.\n  double focal_u = camera.calib_matrix(0, 0);\n  double focal_v = camera.calib_matrix(1, 1);\n  double principal_u = camera.calib_matrix(0, 2);\n  double principal_v = camera.calib_matrix(1, 2);\n  std::cout << \"--------------- synthetic C++ example below this line\\n\";\n  std::cout << \"focal_u = \" << focal_u << \";\\n\";\n  std::cout << \"focal_v = \" << focal_v << \";\\n\";\n  std::cout << \"principal_u = \" << principal_u << \";\\n\";\n  std::cout << \"principal_v = \" << principal_v << \";\\n\";\n\n  // Generate inlier 2D-3D matches without noise.\n  // 3D points are within camera FoV between near and far planes.\n  const unsigned num_points = 6;\n  const double near = 2.0;\n  const double far = 100.0;\n  isaac::Matrix3Xd points3;\n  isaac::Matrix2Xd points2;\n  isaac::pnp::GenerateFovPoints(num_points, camera, near, far, &points3, &points2);\n\n  // Print generated 2D and 3D points.\n  std::cout << \"isaac::Matrix3Xd points3(3,\" << points3.cols() << \");\\n\";\n  std::cout << \"isaac::Matrix2Xd points2(2,\" << points2.cols() << \");\\n\";\n  std::cout << \"points3 << \\n\";\n  PrintMatrixCode(points3);\n  std::cout << \"points2 << \\n\";\n  PrintMatrixCode(points2);\n  std::cout << \"--------------- end of example\\n\";\n\n  // Test EPnP camera pose estimation.\n  isaac::Pose3d pose;\n  ASSERT_EQ(isaac::pnp::ComputeCameraPoseEpnp(points3, points2, focal_u, focal_v, principal_u,\n                                              principal_v, &pose),\n            isaac::pnp::Status::kSuccess);\n\n  // Test if computed pose matches the ground-truth pose.\n  TestPoseEquivalence(pose, gt_pose);\n\n  // Test reprojection error calculation for the example code.\n  isaac::Matrix3d calib_matrix;\n  calib_matrix << focal_u, 0, principal_u, 0, focal_v, principal_v, 0, 0, 1;\n  for (int i = 0; i < points3.cols(); i++) {\n    isaac::Vector3d proj =\n        calib_matrix * (pose.rotation.matrix() * points3.col(i) + pose.translation);\n    isaac::Vector2d point2(proj(0) / proj(2), proj(1) / proj(2));\n\n    // Reprojection error in pixels should be near zero.\n    ASSERT_LT((points2.col(i) - point2).norm(), 1e-6);\n  }\n}\n\n// Generate synthetic input for the RANSAC-EPnP pose estimation example code.\n// (1) Generate a camera with a random pose.\n// (2) Generate a fixed number of 2D/3D point match inliers and add a fixed percentage of outliers.\n// (3) Run RANSAC-EPnP and test the result.\nTEST(PnpTest, TestEpnpRansacExample) {\n  // Generate synthetic data.\n  const int width = 1280;\n  const int height = 720;\n  const double focal = 700.0;\n  isaac::pnp::Camera camera = isaac::pnp::GenerateRandomCamera(width, height, focal);\n\n  // Construct isaac::Pose3d object from the generated camera pose.\n  // This is the known ground-truth pose to compare to the output of pose estimation.\n  isaac::Vector3d gt_angle_axis = isaac::pnp::AngleAxisFromMatrix(camera.rotation_matrix);\n  isaac::Pose3d gt_pose{isaac::SO3d::FromAngleAxis(gt_angle_axis.norm(), gt_angle_axis),\n                        -camera.rotation_matrix * camera.position};\n  std::cout << gt_pose << std::endl;\n\n  // Print camera intrinsics.\n  double focal_u = camera.calib_matrix(0, 0);\n  double focal_v = camera.calib_matrix(1, 1);\n  double principal_u = camera.calib_matrix(0, 2);\n  double principal_v = camera.calib_matrix(1, 2);\n  std::cout << \"--------------- synthetic C++ example below this line\\n\";\n  std::cout << \"focal_u = \" << focal_u << \";\\n\";\n  std::cout << \"focal_v = \" << focal_v << \";\\n\";\n  std::cout << \"principal_u = \" << principal_u << \";\\n\";\n  std::cout << \"principal_v = \" << principal_v << \";\\n\";\n\n  // Generate inlier 2D-3D matches without noise.\n  // 3D points are within camera FoV between near and far planes.\n  const unsigned num_inliers = 7;\n  const double near = 2.0;\n  const double far = 6.0;\n  isaac::Matrix3Xd points3;\n  isaac::Matrix2Xd points2;\n  isaac::pnp::GenerateFovPoints(num_inliers, camera, near, far, &points3, &points2);\n\n  // Generate outlier 2D-3D matches\n  const unsigned num_outliers = 3;\n  isaac::pnp::InsertOutliers(num_outliers, camera, 30.0, &points3, &points2);\n\n  // Print generated 2D and 3D points.\n  std::cout << \"isaac::Matrix3Xd points3(3,\" << points3.cols() << \");\\n\";\n  std::cout << \"isaac::Matrix2Xd points2(2,\" << points2.cols() << \");\\n\";\n  std::cout << \"points3 << \\n\";\n  PrintMatrixCode(points3);\n  std::cout << \"points2 << \\n\";\n  PrintMatrixCode(points2);\n  std::cout << \"--------------- end of example\\n\";\n\n  // Calculate the number of ransac experiments to run.\n  unsigned ransac_rounds = isaac::pnp::EvaluateRansacFormula(0.99, 0.3, 6);\n\n  // The standard RANSAC formula is very optimistic for small input sizes. An ad-hoc fix.\n  if (points3.cols() < 20) ransac_rounds = std::max(ransac_rounds, 100u);\n\n  // Compute top pose hypotheses.\n  std::random_device rnd;\n  const double ransac_threshold = 1.0;\n  const unsigned max_top_poses = 3;\n  const unsigned rand_seed = 73;\n  std::vector<isaac::pnp::PoseHypothesis> top_hypotheses = isaac::pnp::ComputeCameraPoseEpnpRansac(\n      points3, points2, focal_u, focal_v, principal_u, principal_v, ransac_rounds, ransac_threshold,\n      max_top_poses, rand_seed);\n\n  std::cout << top_hypotheses.size() << \" pose hypotheses:\\n\";\n\n  if (top_hypotheses.size()) {\n    // There is a single valid hypothesis.\n    ASSERT_EQ(top_hypotheses.size(), 1);\n\n    // Print the hypothesis.\n    const auto& hyp = top_hypotheses.front();\n    std::cout << hyp.pose << std::endl;\n    std::cout << \"score=\" << hyp.score;\n    std::cout << \", \" << hyp.inliers.size() << \" inliers\";\n    if (hyp.inliers.size()) {\n      std::cout << \":\";\n      for (auto index : hyp.inliers) std::cout << \" \" << index;\n      std::cout << std::endl;\n    }\n\n    // Calculate and print reprojection errors.\n    std::cout << \"Reprojection error (pixels):\" << std::fixed << std::setprecision(1);\n    isaac::Matrix3d calib_matrix;\n    calib_matrix << focal_u, 0, principal_u, 0, focal_v, principal_v, 0, 0, 1;\n    for (int i = 0; i < points3.cols(); i++) {\n      isaac::Vector3d proj =\n          calib_matrix * (hyp.pose.rotation.matrix() * points3.col(i) + hyp.pose.translation);\n      isaac::Vector2d point2(proj(0) / proj(2), proj(1) / proj(2));\n      double repr_error = (points2.col(i) - point2).norm();\n      std::cout << \"  \" << repr_error;\n    }\n    std::cout << std::endl;\n  }\n}\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "f935c1426b4af3a4a01e54caba4a188dc1d79d6f", "size": 9608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/packages/pnp/gems/tests/gen_examples.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/tests/gen_examples.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/tests/gen_examples.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": 41.0598290598, "max_line_length": 100, "alphanum_fraction": 0.6636136553, "num_tokens": 2755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918019, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.5207918945629448}}
{"text": "#include \"problem.hpp\"\n#include \"statistics.hpp\"\n\n#include <string>\n#include <armadillo>\n#include <yaml-cpp/yaml.h>\n\n\nProblem::Problem(const std::string &file_config)\n{\n  YAML::Node config = YAML::LoadFile(file_config);\n  nchannel_ = config[\"nchannel\"].as<int>();\n  nx_ = config[\"nx\"].as<int>();\n  std::string file_data = config[\"file_data\"].as<std::string>();\n\n  // random x0\n  arma::arma_rng::set_seed_random();\n  x0_ = 2. * (arma::randu<arma::vec>(nx_) - 0.5);\n\n  // (t1, t2, t3) -> idx\n  int idx = 0;\n  for (int k = 0; k < nx_; ++k) {\n    for (int j = 0; j <= k; ++j) {\n      for (int i = 0; i <= j; ++i) {\n        if (i == 0 && k > 0 && k == j) continue;\n        idx++;\n      }\n    }\n  }\n  num_c4_ = idx;\n\n  c4y_.set_size(num_c4_, nchannel_);\n\n  // load traces\n  // arma::mat data(nx_, nchannel_, arma::fill::zeros);\n  arma::mat data;\n  data.load(file_data);\n  std::cout << data.n_rows << \" \" << data.n_cols << std::endl;\n\n  // fourth-order cumulants of records\n  for (int i = 0; i < nchannel_; ++i) {\n    arma::vec trace = data.col(i);\n    trace -= arma::mean(trace);\n    arma::vec cum4(num_c4_, arma::fill::zeros);\n    cumulants_4th(trace, nx_, num_c4_, cum4);\n    c4y_.col(i) = cum4;\n  }\n}\n\narma::vec Problem::x0() const\n{\n  return x0_;\n}\n\n\ndouble Problem::fitness(const arma::vec &x)\n{\n  arma::vec m4h(num_c4_, arma::fill::zeros);\n  moment_function_4th(x, nx_, m4h);\n\n  double misfit = 0;\n  for (int i = 0; i < nchannel_; ++i) {\n    misfit += arma::sum(arma::pow(c4y_.col(i) - m4h, 2));\n  }\n  return misfit;\n}\n\n\narma::vec Problem::gradient(const arma::vec &x)\n{\n  arma::vec m4h(num_c4_, arma::fill::zeros);\n  moment_function_4th(x, nx_, m4h);\n\n  arma::mat jac(nx_, num_c4_, arma::fill::zeros);\n  int idx = 0;\n  for (int k = 0; k < nx_; ++k) {\n    for (int j = 0; j <= k; ++j) {\n      for (int i = 0; i <= j; ++i) {\n        if (i == 0 && k > 0 && k == j) continue;\n\n        arma::vec sums(nx_, arma::fill::zeros);\n        for (int l = 0; l < nx_ - k; ++l)\n          sums(l) += x(l + i) * x(l + j) * x(l + k);\n        for (int l = i; l < nx_ - k + i; ++l)\n          sums(l) += x(l - i) * x(l - i + j) * x(l - i + k);\n        for (int l = j; l < nx_ - k + j; ++l)\n          sums(l) += x(l - j) * x(l - j + i) * x(l - j + k);\n        for (int l = k; l < nx_; ++l)\n          sums(l) += x(l - k) * x(l - k + i) * x(l - k + j);\n\n        jac.col(idx++) = sums;\n      }\n    }\n  }\n\n  arma::vec grad(nx_, arma::fill::zeros);\n  for (int i = 0; i < nchannel_; ++i) {\n    arma::vec error = m4h - c4y_.col(i);\n    grad += 2. * jac * error;\n  }\n\n  return grad;\n\n}\n", "meta": {"hexsha": "08ef939426c7c56f1c3828c67ed1fcc044ef1c49", "size": 2557, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/problem.cc", "max_stars_repo_name": "pan3rock/c4we", "max_stars_repo_head_hexsha": "f4df270eab0554f4c887e0bba7f2689800c0f6e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-02T07:56:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T07:56:12.000Z", "max_issues_repo_path": "src/problem.cc", "max_issues_repo_name": "pan3rock/c4we", "max_issues_repo_head_hexsha": "f4df270eab0554f4c887e0bba7f2689800c0f6e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problem.cc", "max_forks_repo_name": "pan3rock/c4we", "max_forks_repo_head_hexsha": "f4df270eab0554f4c887e0bba7f2689800c0f6e7", "max_forks_repo_licenses": ["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.3523809524, "max_line_length": 64, "alphanum_fraction": 0.5138834572, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.520791882623339}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2016 INRIA.\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// =============================== Double Pendulum Example ===============================\n//\n// Author: Vincent Acary\n//\n// Keywords: LagrangianDS, LagrangianLinear relation, MoreauJeanOSI TimeStepping, LCP.\n//\n// =============================================================================================\n\n#include \"SiconosKernel.hpp\"\n#include <stdlib.h>\nusing namespace std;\n\n#include <boost/progress.hpp>\n\ndouble gravity = 10.0;\ndouble m1 = 1.0;\ndouble m2 = 1.0 ;\ndouble l1 = 1.0 ;\ndouble l2 = 1.0 ;\n\nint main(int argc, char* argv[])\n{\n  try\n  {\n\n    // ================= Creation of the model =======================\n\n    // User-defined main parameters\n    unsigned int nDof = 2;           // degrees of freedom for robot arm\n    double t0 = 0;                   // initial computation time\n    double T = 5.0;                   // final computation time\n    double h = 0.0005;                // time step\n    double criterion = 0.05;\n    unsigned int maxIter = 20000;\n    double e = 1.0;                  // nslaw\n    double e1 = 0.0;\n\n    // -> mind to set the initial conditions below.\n\n    // -------------------------\n    // --- Dynamical systems ---\n    // -------------------------\n\n    // --- DS: Double Pendulum ---\n\n    // Initial position (angles in radian)\n    SP::SiconosVector q0(new SiconosVector(nDof));\n    SP::SiconosVector v0(new SiconosVector(nDof));\n\n    q0->zero();\n    v0->zero();\n\n    // (*q0)(0) = 1.5;\n    // (*q0)(1) = 1.5;\n\n    // for sympy plugins uncomment below (relative parametrization)\n    // Note, we have the relation :\n    // absolute[(*q0)(0)] + relative[(*q0)(1)] = absolute[(*q0)(1)]\n    // (*q0)(0) = 0.1;\n    // (*q0)(1) = 0.1;\n\n    (*q0)(0) = 0.1;\n    (*q0)(1) = 0.2;\n\n    /*REGULAR PLUGINS - uncomment to use*/\n    SP::LagrangianDS doublependulum(new LagrangianDS(q0, v0, \"DoublePendulumPlugin:mass\"));\n    doublependulum->setComputeFGyrFunction(\"DoublePendulumPlugin\", \"FGyr\");\n    doublependulum->setComputeJacobianFGyrqDotFunction(\"DoublePendulumPlugin\", \"jacobianVFGyr\");\n    doublependulum->setComputeJacobianFGyrqFunction(\"DoublePendulumPlugin\", \"jacobianFGyrq\");\n    doublependulum->setComputeFIntFunction(\"DoublePendulumPlugin\", \"FInt\");\n    doublependulum->setComputeJacobianFIntqDotFunction(\"DoublePendulumPlugin\", \"jacobianVFInt\");\n    doublependulum->setComputeJacobianFIntqFunction(\"DoublePendulumPlugin\", \"jacobianFIntq\");\n\n    /*SYMPY PLUGINS - uncomment to use*/\n    // SP::LagrangianDS doublependulum(new LagrangianDS(q0, v0, \"DoublePendulumSymPyPlugin:mass\"));\n    // doublependulum->setComputeFGyrFunction(\"DoublePendulumSymPyPlugin\", \"FGyr\");\n    // doublependulum->setComputeJacobianFGyrqDotFunction(\"DoublePendulumSymPyPlugin\", \"jacobianVFGyr\");\n    // doublependulum->setComputeJacobianFGyrqFunction(\"DoublePendulumSymPyPlugin\", \"jacobianFGyrq\");\n\n    // -------------------\n    // --- Interactions---\n    // -------------------\n\n    // -- relations --\n\n    string G = \"DoublePendulumPlugin:G0\";\n    SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e));\n    SP::Relation relation(new LagrangianScleronomousR(\"DoublePendulumPlugin:h0\", G));\n    SP::Interaction inter(new Interaction(1, nslaw, relation));\n\n    string G1 = \"DoublePendulumPlugin:G1\";\n    SP::NonSmoothLaw nslaw1(new NewtonImpactNSL(e1));\n    SP::Relation relation1(new LagrangianScleronomousR(\"DoublePendulumPlugin:h1\", G1));\n    SP::Interaction inter1(new Interaction(1, nslaw1, relation1));\n\n    // -------------\n    // --- Model ---\n    // -------------\n\n    SP::Model Pendulum(new Model(t0, T));\n    Pendulum->nonSmoothDynamicalSystem()->insertDynamicalSystem(doublependulum);\n    Pendulum->nonSmoothDynamicalSystem()->link(inter,doublependulum);\n    Pendulum->nonSmoothDynamicalSystem()->link(inter1,doublependulum);\n\n    // ----------------\n    // --- Simulation ---\n    // ----------------\n\n    // -- Time discretisation --\n    SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));\n\n    SP::TimeStepping s(new TimeStepping(t));\n    //        s->setUseRelativeConvergenceCriteron(true);\n\n    // -- OneStepIntegrators --\n\n    //double theta=0.500001;\n    double theta = 0.500001;\n\n    SP::MoreauJeanOSI OSI(new MoreauJeanOSI(theta));\n    s->insertIntegrator(OSI);\n\n    // -- OneStepNsProblem --\n    SP::OneStepNSProblem osnspb(new LCP());\n\n    s->insertNonSmoothProblem(osnspb);\n\n    cout << \"=== End of model loading === \" << endl;\n\n    // =========================== End of model definition ===========================  dataPlot(k,7) = (*inter->y(0))(0);\n\n\n    // ================================= Computation =================================\n\n    // --- Simulation initialization ---\n    Pendulum->initialize(s);\n    cout << \"End of simulation initialisation\" << endl;\n\n    int k = 0;\n    int N = ceil((T - t0) / h);\n    cout << \"Number of time step   \" << N << endl;\n    // --- Get the values to be plotted ---\n    // -> saved in a matrix dataPlot\n    unsigned int outputSize = 12;\n    SimpleMatrix dataPlot(N + 1, outputSize);\n    // For the initial time step:\n    // time\n    SP::SiconosVector q = doublependulum->q();\n    SP::SiconosVector v = doublependulum->velocity();\n\n    dataPlot(k, 0) =  t0;\n    dataPlot(k, 1) = (*q)(0);\n    dataPlot(k, 2) = (*v)(0);\n    dataPlot(k, 3) = (*q)(1);\n    dataPlot(k, 4) = (*v)(1);\n    dataPlot(k, 5) =  l1 * sin((*q)(0));\n    dataPlot(k, 6) = -l1 * cos((*q)(0));\n    dataPlot(k, 7) =  l1 * sin((*q)(0)) + l2 * sin((*q)(1));\n    dataPlot(k, 8) = -l1 * cos((*q)(0)) - l2 * cos((*q)(1));\n    dataPlot(k, 9) =  l1 * cos((*q)(0)) * ((*v)(0));\n    dataPlot(k, 10) = l1 * cos((*q)(0)) * ((*v)(0)) + l2 * cos((*q)(1)) * ((*v)(1));\n\n    boost::timer time;\n    time.restart();\n\n    // --- Time loop ---\n    cout << \"Start computation ... \" << endl;\n\n    boost::progress_display show_progress(N);\n\n    while (s->hasNextEvent())\n    {\n      k++;\n      ++show_progress;\n      //  if (!(div(k,1000).rem))  cout <<\"Step number \"<< k << \"\\n\";\n\n      // Solve problem\n      s->newtonSolve(criterion, maxIter);\n      // Data Output\n      dataPlot(k, 0) =  s->nextTime();\n      dataPlot(k, 1) = (*q)(0);\n      dataPlot(k, 2) = (*v)(0);\n      dataPlot(k, 3) = (*q)(1);\n      // sympy plugin with relative parametrization:\n      // dataPlot(k, 3) = (*q)(0) + (*q)(1);\n      dataPlot(k, 4) = (*v)(1);\n      // sympy plugin with relative parametrization:\n      // dataPlot(k, 4) = (*v)(0) + (*v)(1);\n      dataPlot(k, 5) =  l1 * sin((*q)(0));\n      dataPlot(k, 6) = -l1 * cos((*q)(0));\n      dataPlot(k, 7) =  l1 * sin((*q)(0)) + l2 * sin((*q)(1));\n      dataPlot(k, 8) = -l1 * cos((*q)(0)) - l2 * cos((*q)(1));\n      dataPlot(k, 9) =  l1 * cos((*q)(0)) * ((*v)(0));\n      dataPlot(k, 10) = l1 * cos((*q)(0)) * ((*v)(0)) + l2 * cos((*q)(1)) * ((*v)(1));\n      s->nextStep();\n    }\n\n    cout << \"End of computation - Number of iterations done: \" << k << endl;\n    cout << \"Computation Time \" << time.elapsed()  << endl;\n\n    // --- Output files ---\n    ioMatrix::write(\"DoublePendulumResult.dat\", \"ascii\", dataPlot, \"noDim\");\n  }\n\n  catch (SiconosException e)\n  {\n    cout << e.report() << endl;\n  }\n  catch (...)\n  {\n    cout << \"Exception caught in \\'sample/MultiBeadsColumn\\'\" << endl;\n  }\n}\n", "meta": {"hexsha": "ef54286d21aad7ceeada87debb09a82e3dfca5c2", "size": 7851, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/Mechanics/Pendulum/DoublePendulumTS.cpp", "max_stars_repo_name": "siconos/siconos-deb", "max_stars_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "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/Mechanics/Pendulum/DoublePendulumTS.cpp", "max_issues_repo_name": "siconos/siconos-deb", "max_issues_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "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/Mechanics/Pendulum/DoublePendulumTS.cpp", "max_forks_repo_name": "siconos/siconos-deb", "max_forks_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "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.69527897, "max_line_length": 122, "alphanum_fraction": 0.5684626162, "num_tokens": 2310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.520791882623339}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson, John B. Mains\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__FEEDBACK__QP_HPP_\n#define SMOOTH__FEEDBACK__QP_HPP_\n\n/**\n * @file\n * @brief Quadratic Programming.\n */\n\n#include <Eigen/Cholesky>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <optional>\n\nnamespace smooth::feedback {\n\n/**\n * @brief Quadratic program definition.\n *\n * @tparam M number of constraints\n * @tparam N number of variables\n *\n * The quadratic program is on the form\n * \\f[\n * \\begin{cases}\n *  \\min_{x} & \\frac{1}{2} x^T P x + q^T x, \\\\\n *  \\text{s.t.} & l \\leq A x \\leq u,\n * \\end{cases}\n * \\f]\n * where \\f$ P \\in \\mathbb{R}^{n \\times n}, q \\in \\mathbb{R}^n, l, u \\in \\mathbb{R}^m, A \\in\n * \\mathbb{R}^{m \\times n} \\f$.\n */\ntemplate<Eigen::Index M, Eigen::Index N, typename Scalar = double>\nstruct QuadraticProgram\n{\n  /// Positive semi-definite square cost (only upper trianglular part is used)\n  Eigen::Matrix<Scalar, N, N> P;\n  /// Linear cost\n  Eigen::Matrix<Scalar, N, 1> q;\n\n  /// Inequality matrix\n  Eigen::Matrix<Scalar, M, N> A;\n  /// Inequality lower bound\n  Eigen::Matrix<Scalar, M, 1> l;\n  /// Inequality upper bound\n  Eigen::Matrix<Scalar, M, 1> u;\n};\n\n/**\n * @brief Sparse quadratic program definition.\n *\n * The quadratic program is on the form\n * \\f[\n * \\begin{cases}\n *  \\min_{x} & \\frac{1}{2} x^T P x + q^T x, \\\\\n *  \\text{s.t.} & l \\leq A x \\leq u,\n * \\end{cases}\n * \\f]\n * where \\f$ P \\in \\mathbb{R}^{n \\times n}, q \\in \\mathbb{R}^n, l, u \\in \\mathbb{R}^m, A \\in\n * \\mathbb{R}^{m \\times n} \\f$.\n */\ntemplate<typename Scalar = double>\nstruct QuadraticProgramSparse\n{\n  /// Positive semi-definite square cost (only upper trianglular part is used)\n  Eigen::SparseMatrix<Scalar> P;\n  /// Linear cost\n  Eigen::Matrix<Scalar, -1, 1> q;\n\n  /**\n   * @brief Inequality matrix\n   *\n   * @note The constraint matrix is stored in row-major format,\n   * i.e. coefficients for each constraint are contiguous in memory\n   */\n  Eigen::SparseMatrix<Scalar, Eigen::RowMajor> A;\n  /// Inequality lower bound\n  Eigen::Matrix<Scalar, -1, 1> l;\n  /// Inequality upper bound\n  Eigen::Matrix<Scalar, -1, 1> u;\n};\n\n/// Solver exit codes\nenum class QPSolutionStatus : int {\n  Optimal,           /// Solution satisifes optimality condition. Solution is polished if\n                     /// `QPSolverParams::polish = true`.\n  PolishFailed,      /// Solution satisfies optimality condition but is not polished\n  PrimalInfeasible,  /// A certificate of primal infeasibility was found, no solution returned\n  DualInfeasible,    /// A certificate of dual infeasibility was found, no solution returned\n  MaxIterations,     /// Max number of iterations was reached, returned solution is not optimal\n  MaxTime,           /// Max time was reached, returned solution is not optimal\n  Unknown            /// Solution is useless because of other reasons, no solution returned\n};\n\n/// Solver solution\ntemplate<Eigen::Index M, Eigen::Index N, typename Scalar = double>\nstruct QPSolution\n{\n  /// Exit code\n  QPSolutionStatus code = QPSolutionStatus::Unknown;\n  /// Number of iterations\n  uint64_t iter;\n  /// Primal vector\n  Eigen::Matrix<Scalar, N, 1> primal;\n  /// Dual vector\n  Eigen::Matrix<Scalar, M, 1> dual;\n  /// Solution objective value\n  double objective;\n};\n\n/**\n * @brief Options for solve_qp\n */\nstruct QPSolverParams\n{\n  /// print solver info to stdout\n  bool verbose = false;\n\n  /// relaxation parameter\n  float alpha = 1.6;\n  /// first dul step size\n  float rho = 0.1;\n  /// second dual step length\n  float sigma = 1e-6;\n\n  /// scale problem\n  bool scaling = true;\n\n  /// absolute threshold for convergence\n  float eps_abs = 1e-3;\n  /// relative threshold for convergence\n  float eps_rel = 1e-3;\n  /// threshold for primal infeasibility\n  float eps_primal_inf = 1e-4;\n  /// threshold for dual infeasibility\n  float eps_dual_inf = 1e-4;\n\n  /// max number of iterations\n  std::optional<uint32_t> max_iter = {};\n\n  /// max solution time\n  std::optional<std::chrono::nanoseconds> max_time = {};\n\n  /// iterations between checking stopping criterion\n  uint32_t stop_check_iter = 25;\n\n  /// run solution polishing (uses dynamic memory)\n  bool polish = true;\n  /// number of iterations to refine polish\n  uint32_t polish_iter = 5;\n  /// regularization parameter for polishing\n  float delta = 1e-6;\n};\n\nnamespace detail {\n\n// Traits to figure solution type from problem type\n// \\cond\ntemplate<typename T>\nstruct qp_solution;\n\ntemplate<Eigen::Index M, Eigen::Index N, typename Scalar>\nstruct qp_solution<QuadraticProgram<M, N, Scalar>>\n{\n  using type = QPSolution<M, N, Scalar>;\n};\n\ntemplate<typename Scalar>\nstruct qp_solution<QuadraticProgramSparse<Scalar>>\n{\n  using type = QPSolution<-1, -1, Scalar>;\n};\n\ntemplate<typename T>\nusing qp_solution_t = typename qp_solution<T>::type;\n// \\endcond\n\n/**\n * @brief Re-scale a QuadraticProgram\n *\n * @param pbm problem \\f$ (P, q, A, l, u) \\f$ to rescale.\n *\n * @returns tuple `(spbm, s, c)` where `spbm` is a scaled problem \\f$ (\\bar P, \\bar q, \\bar A, \\bar\n * l, \\bar u)\\f$.\n *\n * The scaled problem is defined as\n *\n * * \\f$ \\bar P = c S_x P S_x \\f$,\n * * \\f$ \\bar q = c q S_x \\f$,\n * * \\f$ \\bar A = S_e A S_x \\f$,\n * * \\f$ \\bar l = S_e l \\f$,\n * * \\f$ \\bar u = S_e u \\f$,\n *\n * where \\f$ S_x = diag(s_{0:n}), S_e = diag(s_{n:n+m}) \\f$.\n *\n * The relation between scaled variables and original variables are\n *\n * * Primal: \\f$ \\bar x = S_x^{-1} x \\f$,\n * * Dual: \\f$ \\bar y = c E_x^{-1} x \\f$.\n *\n * The objective of the rescaling is the make the columns of\n * \\f[\n *   \\begin{bmatrix} \\bar P & \\bar A^T \\\\ \\bar A & 0 \\end{bmatrix}\n * \\f]\n * have similar \\f$ l_\\infty \\f$ norm, and similarly for\n * the columns of\n * \\f[\n *  \\begin{bmatrix} \\bar P & \\bar q \\end{bmatrix}.\n * \\f]\n */\ntemplate<typename Pbm>\nauto scale_qp(const Pbm & pbm)\n{\n  using AmatT                  = decltype(Pbm::A);\n  using Scalar                 = typename AmatT::Scalar;\n  static constexpr bool sparse = std::is_base_of_v<Eigen::SparseMatrixBase<AmatT>, AmatT>;\n\n  Pbm ret = pbm;\n\n  static constexpr Eigen::Index M = AmatT::RowsAtCompileTime;\n  static constexpr Eigen::Index N = AmatT::ColsAtCompileTime;\n  static constexpr Eigen::Index K = (N == -1 || M == -1) ? Eigen::Index(-1) : N + M;\n\n  const Eigen::Index n = ret.A.cols(), m = ret.A.rows(), k = n + m;\n  const auto norm = [](auto && t) -> Scalar { return t.template lpNorm<Eigen::Infinity>(); };\n\n  Eigen::Matrix<Scalar, K, 1> scale = Eigen::Matrix<Scalar, K, 1>::Ones(k);  // scaling\n  Eigen::Matrix<Scalar, K, 1> d_scale(k);                                    // incremental scaling\n\n  // find \"norm\" of cost function\n  if constexpr (sparse) {\n    for (auto i = 0u; i != n; ++i) {\n      d_scale(i) = 0;\n      // traverse each col of P\n      for (Eigen::SparseMatrix<double>::InnerIterator it(ret.P, i); it; ++it) {\n        d_scale(i) = std::max(d_scale(i), std::abs(it.value()));\n      }\n    }\n  } else {\n    d_scale.template head<N>(n) = ret.P.colwise().template lpNorm<Eigen::Infinity>();\n  }\n\n  // if there are \"zero cols\"\n  for (auto i = 0u; i != n; ++i) {\n    if (d_scale(i) == 0) { d_scale(i) = 1; }\n  }\n\n  // scale cost function\n  Scalar c = Scalar(1) / std::max({1e-6, d_scale.template head<N>(n).mean(), norm(ret.q)});\n  ret.P *= c;\n  ret.q *= c;\n\n  int iter = 0;\n\n  // calculate norm for every column of [P A' ; A 0]\n  do {\n    if constexpr (sparse) {\n      // P is stored col wise\n      for (auto i = 0u; i != n; ++i) {\n        d_scale(i) = 0;\n        for (Eigen::SparseMatrix<double>::InnerIterator it(ret.P, i); it; ++it) {\n          // upper left block of H\n          d_scale(i) = std::max(d_scale(i), std::abs(it.value()));\n        }\n      }\n      // A is stored row wise\n      for (auto i = 0u; i != m; ++i) {\n        d_scale(n + i) = 0;\n        for (Eigen::SparseMatrix<double, Eigen::RowMajor>::InnerIterator it(ret.A, i); it; ++it) {\n          // bottom left block of H\n          d_scale(it.index()) = std::max(d_scale(it.index()), std::abs(it.value()));\n          // upper right block of H\n          d_scale(n + i) = std::max(d_scale(n + i), std::abs(it.value()));\n        }\n      }\n    } else {\n      d_scale.template head<N>(n) = ret.P.colwise().template lpNorm<Eigen::Infinity>().cwiseMax(\n        ret.A.colwise().template lpNorm<Eigen::Infinity>());\n      d_scale.template segment<M>(n, m) = ret.A.rowwise().template lpNorm<Eigen::Infinity>();\n    }\n\n    // if there are \"zero cols\" we don't scale\n    for (auto i = 0u; i != k; ++i) {\n      if (d_scale(i) == 0) { d_scale(i) = 1; }\n    }\n\n    d_scale = d_scale.cwiseMax(1e-8).cwiseInverse().cwiseSqrt();\n\n    // perform scaling\n    if constexpr (sparse) {\n      ret.P =\n        d_scale.template head<N>(n).asDiagonal() * ret.P * d_scale.template head<N>(n).asDiagonal();\n      ret.A = d_scale.template segment<M>(n, m).asDiagonal() * ret.A\n            * d_scale.template head<N>(n).asDiagonal();\n    } else {\n      ret.P.applyOnTheLeft(d_scale.template head<N>(n).asDiagonal());\n      ret.P.applyOnTheRight(d_scale.template head<N>(n).asDiagonal());\n      ret.A.applyOnTheLeft(d_scale.template segment<M>(n, m).asDiagonal());\n      ret.A.applyOnTheRight(d_scale.template head<N>(n).asDiagonal());\n    }\n    ret.q.applyOnTheLeft(d_scale.template head<N>(n).asDiagonal());\n    ret.l.applyOnTheLeft(d_scale.template segment<M>(n, m).asDiagonal());\n    ret.u.applyOnTheLeft(d_scale.template segment<M>(n, m).asDiagonal());\n\n    scale.applyOnTheLeft(d_scale.asDiagonal());\n  } while (iter++ < 10 && (d_scale.array() - 1).abs().maxCoeff() > 0.1);\n\n  return std::make_tuple(std::move(ret), std::move(scale), c);\n}\n\n/**\n * @brief Polish solution of quadratic program\n *\n * @tparam Pbm problem type\n *\n * @param[in] pbm problem formulation\n * @param[in, out] sol solution to polish\n * @param[in] prm solver options\n *\n * @warning This function allocates heap memory even for static-sized problems.\n */\ntemplate<typename Pbm>\nbool polish_qp(const Pbm & pbm, qp_solution_t<Pbm> & sol, const QPSolverParams & prm)\n{\n  using AmatT                  = decltype(Pbm::A);\n  using Scalar                 = typename AmatT::Scalar;\n  using VecX                   = Eigen::Matrix<Scalar, -1, 1>;\n  static constexpr bool sparse = std::is_base_of_v<Eigen::SparseMatrixBase<AmatT>, AmatT>;\n\n  static constexpr Scalar inf = std::numeric_limits<Scalar>::infinity();\n  static constexpr Scalar eps = std::numeric_limits<Scalar>::epsilon();\n\n  static constexpr Eigen::Index N = AmatT::ColsAtCompileTime;\n  const Eigen::Index n = pbm.A.cols(), m = pbm.A.rows();\n\n  // FIND ACTIVE CONSTRAINT SETS\n\n  Eigen::Index nl = 0, nu = 0;\n  for (Eigen::Index idx = 0; idx < m; ++idx) {\n    if (sol.dual[idx] < -100 * eps && pbm.l[idx] != -inf) { nl++; }\n    if (sol.dual[idx] > 100 * eps && pbm.u[idx] != inf) { nu++; }\n  }\n\n  Eigen::Matrix<Eigen::Index, -1, 1> LU_idx(nl + nu);\n  for (Eigen::Index idx = 0, lcntr = 0, ucntr = 0; idx < m; ++idx) {\n    if (sol.dual[idx] < -100 * eps && pbm.l[idx] != -inf) { LU_idx(lcntr++) = idx; }\n    if (sol.dual[idx] > 100 * eps && pbm.u[idx] != inf) { LU_idx(nl + ucntr++) = idx; }\n  }\n\n  // FORM REDUCED SYSTEMS (27) AND (30)\n\n  // square symmetric system matrix\n  using HT = std::conditional_t<sparse, Eigen::SparseMatrix<Scalar>, Eigen::Matrix<Scalar, -1, -1>>;\n  HT H(n + nl + nu, n + nl + nu), Hp(n + nl + nu, n + nl + nu);\n\n  // fill up H\n  if constexpr (sparse) {\n    // preallocate nonzeros\n    Eigen::Matrix<int, -1, 1> nnz(n + nl + nu);\n    for (auto i = 0u; i != n; ++i) {\n      nnz(i) = pbm.P.outerIndexPtr()[i + 1] - pbm.P.outerIndexPtr()[i];\n    }\n    for (auto i = 0u; i != nl + nu; ++i) {\n      nnz(n + i) = pbm.A.outerIndexPtr()[LU_idx(i) + 1] - pbm.A.outerIndexPtr()[LU_idx(i)];\n    }\n    H.reserve(nnz);\n    Hp.reserve(nnz + Eigen::Matrix<int, -1, 1>::Ones(n + nl + nu));\n\n    using PIter = typename Eigen::SparseMatrix<Scalar, Eigen::ColMajor>::InnerIterator;\n    using AIter = typename Eigen::SparseMatrix<Scalar, Eigen::RowMajor>::InnerIterator;\n\n    // fill P in top left block\n    for (Eigen::Index p_col = 0u; p_col != n; ++p_col) {\n      for (PIter it(pbm.P, p_col); it && it.index() <= p_col; ++it) {\n        H.insert(it.index(), p_col)  = it.value();\n        Hp.insert(it.index(), p_col) = it.value();\n      }\n    }\n\n    // fill selected rows of A in top right block\n    for (auto a_row = 0u; a_row != nl + nu; ++a_row) {\n      for (AIter it(pbm.A, LU_idx(a_row)); it; ++it) {\n        H.insert(it.index(), n + a_row)  = it.value();\n        Hp.insert(it.index(), n + a_row) = it.value();\n      }\n    }\n  } else {\n    H.setZero();\n    H.topLeftCorner(n, n) = pbm.P;\n    for (auto i = 0u; i != nl + nu; ++i) {\n      H.col(n + i).template head<N>(n) = pbm.A.row(LU_idx(i));\n    }\n    Hp = H;\n  }\n\n  // add perturbing diagonal elements to Hp\n  if constexpr (sparse) {\n    for (auto i = 0u; i != n; ++i) { Hp.coeffRef(i, i) += prm.delta; }\n    for (auto i = 0u; i != nl + nu; ++i) { Hp.coeffRef(n + i, n + i) -= prm.delta; }\n    H.makeCompressed();\n    Hp.makeCompressed();\n  } else {\n    Hp.topLeftCorner(n, n) += VecX::Constant(n, prm.delta).asDiagonal();\n    Hp.bottomRightCorner(nl + nu, nl + nu) -= VecX::Constant(nl + nu, prm.delta).asDiagonal();\n  }\n\n  VecX h(n + nl + nu);\n  h.head(n) = -pbm.q;\n  for (auto i = 0u; i != nl; ++i) { h(n + i) = pbm.l(LU_idx(i)); }\n  for (auto i = 0u; i != nu; ++i) { h(n + nl + i) = pbm.u(LU_idx(nl + i)); }\n\n  // ITERATIVE REFINEMENT\n\n  // factorize Hp\n  std::conditional_t<\n    sparse,\n    Eigen::SimplicialLDLT<decltype(H), Eigen::Upper>,\n    Eigen::LDLT<Eigen::Ref<decltype(H)>, Eigen::Upper>>\n    ldlt(Hp);\n\n  if (ldlt.info()) { return false; }\n\n  VecX t_hat = VecX::Zero(n + nl + nu);\n  for (auto i = 0u; i != prm.polish_iter; ++i) {\n    t_hat += ldlt.solve(h - H.template selfadjointView<Eigen::Upper>() * t_hat);\n  }\n\n  // UPDATE SOLUTION\n\n  sol.primal = t_hat.template head<N>(n);\n  for (Eigen::Index i = 0; i < nl; ++i) { sol.dual(LU_idx(i)) = t_hat(n + i); }\n  for (Eigen::Index i = 0; i < nu; ++i) { sol.dual(LU_idx(nl + i)) = t_hat(n + nl + i); }\n  sol.objective = sol.primal.dot(0.5 * pbm.P * sol.primal + pbm.q);\n\n  return true;\n}\n\n/**\n * @brief Check stopping criterion for QP solver.\n */\ntemplate<typename Pbm, typename D1, typename D2, typename D3, typename D4, typename D5>\nstd::optional<QPSolutionStatus> qp_check_stopping(\n  const Pbm & pbm,\n  const Eigen::MatrixBase<D1> & x,\n  const Eigen::MatrixBase<D2> & y,\n  const Eigen::MatrixBase<D3> & z,\n  const Eigen::MatrixBase<D4> & dx,\n  const Eigen::MatrixBase<D5> & dy,\n  const QPSolverParams & prm)\n{\n  using Scalar = typename decltype(Pbm::A)::Scalar;\n\n  const Eigen::Index n = pbm.A.cols(), m = pbm.A.rows();\n  static constexpr Scalar inf = std::numeric_limits<Scalar>::infinity();\n  const auto norm = [](auto && t) -> Scalar { return t.template lpNorm<Eigen::Infinity>(); };\n\n  // working memory\n  Eigen::Matrix<Scalar, decltype(Pbm::A)::ColsAtCompileTime, 1> Px(n), Aty(n);\n  Eigen::Matrix<Scalar, decltype(Pbm::A)::RowsAtCompileTime, 1> Ax(m);\n\n  // OPTIMALITY\n\n  // check primal\n  Ax.noalias() = pbm.A * x;\n  if (norm(Ax - z) <= prm.eps_abs + prm.eps_rel * std::max<Scalar>(norm(Ax), norm(z))) {\n    // primal succeeded, check dual\n    Px.noalias()            = pbm.P * x;\n    Aty.noalias()           = pbm.A.transpose() * y;\n    const Scalar dual_scale = std::max<Scalar>({norm(Px), norm(pbm.q), norm(Aty)});\n    if (norm(Px + pbm.q + Aty) <= prm.eps_abs + prm.eps_rel * dual_scale) {\n      return QPSolutionStatus::Optimal;\n    }\n  }\n\n  // PRIMAL INFEASIBILITY\n\n  Aty.noalias()         = pbm.A.transpose() * dy;  // note new value A' * dy\n  const Scalar Edy_norm = norm(dy);\n\n  Scalar u_dyp_plus_l_dyn = Scalar(0);\n  for (auto i = 0u; i != m; ++i) {\n    if (pbm.u(i) != inf) {\n      u_dyp_plus_l_dyn += pbm.u(i) * std::max<Scalar>(Scalar(0), dy(i));\n    } else if (dy(i) > prm.eps_primal_inf * Edy_norm) {\n      // contributes +inf to sum --> no certificate\n      u_dyp_plus_l_dyn = inf;\n      break;\n    }\n    if (pbm.l(i) != -inf) {\n      u_dyp_plus_l_dyn += pbm.l(i) * std::min<Scalar>(Scalar(0), dy(i));\n    } else if (dy(i) < -prm.eps_primal_inf * Edy_norm) {\n      // contributes +inf to sum --> no certificate\n      u_dyp_plus_l_dyn = inf;\n      break;\n    }\n  }\n\n  if (std::max<Scalar>(norm(Aty), u_dyp_plus_l_dyn) < prm.eps_primal_inf * Edy_norm) {\n    return QPSolutionStatus::PrimalInfeasible;\n  }\n\n  // DUAL INFEASIBILITY\n\n  Ax.noalias()         = pbm.A * dx;  // note new value A * dx\n  const Scalar dx_norm = norm(dx);\n\n  bool dual_infeasible = (norm(pbm.P * dx) <= prm.eps_dual_inf * dx_norm)\n                      && (pbm.q.dot(dx) <= prm.eps_dual_inf * dx_norm);\n  for (auto i = 0u; i != m && dual_infeasible; ++i) {\n    if (pbm.u(i) == inf) {\n      dual_infeasible &= (Ax(i) >= -prm.eps_dual_inf * dx_norm);\n    } else if (pbm.l(i) == -inf) {\n      dual_infeasible &= (Ax(i) <= prm.eps_dual_inf * dx_norm);\n    } else {\n      dual_infeasible &= std::abs(Ax(i)) < prm.eps_dual_inf * dx_norm;\n    }\n  }\n\n  if (dual_infeasible) { return QPSolutionStatus::DualInfeasible; }\n\n  return std::nullopt;\n}\n\n}  // namespace detail\n\n/**\n * @brief Solve a quadratic program using the operator splitting approach.\n *\n * @tparam Pbm problem type (QuadraticProgram or QuadraticProgramSparse)\n *\n * @param pbm problem formulation\n * @param prm solver options\n * @param warmstart provide initial guess for primal and dual variables\n * @return solution as QuasraticProgramSolution<M, N>\n *\n * @note dynamic problem sizes (`M == -1 || N == -1`) are supported\n *\n * This is a third-party implementation of the algorithm described in the following paper:\n * * Stellato, B., Banjac, G., Goulart, P. et al.\n * **OSQP: an operator splitting solver for quadratic programs.**\n * *Math. Prog. Comp.* 12, 637\u2013672 (2020).\n * https://doi.org/10.1007/s12532-020-00179-2\n *\n * For the official C implementation, see https://osqp.org/.\n */\ntemplate<typename Pbm>\ndetail::qp_solution_t<Pbm> solve_qp(\n  const Pbm & pbm,\n  const QPSolverParams & prm,\n  std::optional<std::reference_wrapper<const detail::qp_solution_t<Pbm>>> warmstart = {})\n{\n  using AmatT                  = decltype(Pbm::A);\n  using Scalar                 = typename AmatT::Scalar;\n  static constexpr bool sparse = std::is_base_of_v<Eigen::SparseMatrixBase<AmatT>, AmatT>;\n\n  // static sizes\n  static constexpr Eigen::Index M = AmatT::RowsAtCompileTime;\n  static constexpr Eigen::Index N = AmatT::ColsAtCompileTime;\n  static constexpr Eigen::Index K = (N == -1 || M == -1) ? Eigen::Index(-1) : N + M;\n\n  // typedefs\n  using Rn = Eigen::Matrix<Scalar, N, 1>;\n  using Rm = Eigen::Matrix<Scalar, M, 1>;\n  using Rk = Eigen::Matrix<Scalar, K, 1>;\n\n  // dynamic sizes\n  const Eigen::Index n = pbm.A.cols(), m = pbm.A.rows(), k = n + m;\n\n  static constexpr Scalar inf = std::numeric_limits<Scalar>::infinity();\n\n  // cast parameters to scalar type\n  const Scalar rho_bar    = static_cast<Scalar>(prm.rho);\n  const Scalar alpha      = static_cast<Scalar>(prm.alpha);\n  const Scalar alpha_comp = Scalar(1) - alpha;\n  const Scalar sigma      = static_cast<Scalar>(prm.sigma);\n\n  // return code: when set algorithm is finished\n  std::optional<QPSolutionStatus> ret_code = std::nullopt;\n\n  // allocate working arrays\n  Rn x_us(n), dx_us(n);\n  Rm z_next(m), y_us(m), z_us(m), dy_us(m), rho(m);\n  Rk p(k);\n\n  // scale problem\n  Scalar c                      = 1;\n  Eigen::Matrix<Scalar, K, 1> S = Eigen::Matrix<Scalar, K, 1>::Ones(k);\n  Pbm spbm                      = pbm;\n  if (prm.scaling) { std::tie(spbm, S, c) = detail::scale_qp(pbm); }\n\n  for (auto i = 0u; i != m; ++i) {\n    if (spbm.l(i) == inf || spbm.u(i) == -inf || spbm.u(i) - spbm.l(i) < Scalar(0.)) {\n      ret_code = QPSolutionStatus::PrimalInfeasible;  // feasible set trivially empty\n    }\n\n    // set rho depending on constraint type\n    if (spbm.l(i) == -inf && spbm.u(i) == inf) {\n      rho(i) = Scalar(1e-6);  // unbounded\n    } else if (abs(spbm.l(i) - spbm.u(i)) < 1e-5) {\n      rho(i) = Scalar(1e3) * rho_bar;  // equality\n    } else {\n      rho(i) = rho_bar;  // inequality\n    }\n  }\n\n  const auto t0 = std::chrono::high_resolution_clock::now();\n\n  // fill square symmetric system matrix H\n  std::conditional_t<sparse, Eigen::SparseMatrix<Scalar>, Eigen::Matrix<Scalar, K, K>> H(k, k);\n  if constexpr (sparse) {\n    // preallocate nonzeros in H\n    Eigen::Matrix<int, -1, 1> nnz(k);\n    for (auto i = 0u; i != n; ++i) {\n      nnz(i) = spbm.P.outerIndexPtr()[i + 1] - spbm.P.outerIndexPtr()[i] + 1;\n    }\n    for (auto i = 0u; i != m; ++i) {\n      nnz(n + i) = spbm.A.outerIndexPtr()[i + 1] - spbm.A.outerIndexPtr()[i] + 1;\n    }\n    H.reserve(nnz);\n\n    // fill nonzeros in H\n    using PIter = typename Eigen::SparseMatrix<Scalar, Eigen::ColMajor>::InnerIterator;\n    using AIter = typename Eigen::SparseMatrix<Scalar, Eigen::RowMajor>::InnerIterator;\n    for (Eigen::Index col = 0u; col != n; ++col) {\n      for (PIter it(spbm.P, col); it && it.index() <= col; ++it) {\n        H.insert(it.index(), col) = it.value();\n      }\n      H.coeffRef(col, col) += sigma;\n    }\n    for (auto row = 0u; row != m; ++row) {\n      for (AIter it(spbm.A, row); it; ++it) { H.insert(it.index(), n + row) = it.value(); }\n      H.insert(n + row, n + row) = Scalar(-1) / rho(row);\n    }\n    H.makeCompressed();\n  } else {\n    H.template topLeftCorner<N, N>(n, n) = spbm.P;\n    H.template topLeftCorner<N, N>(n, n) += Rn::Constant(n, sigma).asDiagonal();\n    H.template topRightCorner<N, M>(n, m)    = spbm.A.transpose();\n    H.template bottomRightCorner<M, M>(m, m) = (-rho).cwiseInverse().asDiagonal();\n  }\n\n  const auto t_fill = std::chrono::high_resolution_clock::now();\n\n  if (prm.verbose) {\n    using std::cout, std::left, std::setw, std::right;\n    // clang-format off\n    cout << \"========================= QP Solver =========================\" << '\\n';\n    cout << \"Solving \" << (sparse ? \"sparse\" : \"dense\") << \" QP with n=\" << n << \", m=\" << m << '\\n';\n    cout << setw(8)  << right << \"ITER\"\n         << setw(14) << right << \"OBJ\"\n         << setw(14) << right << \"PRI_RES\"\n         << setw(14) << right << \"DUA_RES\"\n         << setw(10) << right << \"TIME\" << '\\n';\n    // clang-format on\n  }\n\n  // factorize H\n  std::conditional_t<\n    sparse,\n    Eigen::SimplicialLDLT<decltype(H), Eigen::Upper>,\n    Eigen::LDLT<Eigen::Ref<decltype(H)>, Eigen::Upper>>\n    ldlt(H);\n\n  const auto t_factor = std::chrono::high_resolution_clock::now();\n\n  if (ldlt.info()) { ret_code = QPSolutionStatus::Unknown; }\n\n  // initialize solver variables\n  Rn x;\n  Rm z, y;\n  if (warmstart.has_value()) {\n    // warmstart variables must be scaled\n    x = warmstart.value().get().primal;\n    x.applyOnTheLeft(S.template head<N>(n).cwiseInverse().asDiagonal());\n    y = warmstart.value().get().dual;\n    y.applyOnTheLeft(S.template segment<M>(n, m).cwiseInverse().asDiagonal());\n    y *= c;\n    z.noalias() = spbm.A * x;\n  } else {\n    x.setZero(n);\n    y.setZero(m);\n    z.setZero(m);\n  }\n\n  // main optimization loop\n  auto iter = 0u;\n  for (; (!prm.max_iter || iter != prm.max_iter.value()) && !ret_code; ++iter) {\n    p.template head<N>(n)       = sigma * x - spbm.q;\n    p.template segment<M>(n, m) = z - rho.cwiseInverse().cwiseProduct(y);\n    p                           = ldlt.solve(p);\n\n    if (iter % prm.stop_check_iter == 1) {\n      // termination checking requires difference, store old scaled values\n      dx_us = x, dy_us = y;\n    }\n\n    x      = alpha * p.template head<N>(n) + alpha_comp * x;\n    z_next = (alpha * rho.cwiseInverse().cwiseProduct(p.template segment<M>(n, m))\n              + alpha_comp * rho.cwiseInverse().cwiseProduct(y) + z)\n               .cwiseMax(spbm.l)\n               .cwiseMin(spbm.u);\n    y = alpha_comp * y + alpha * p.template segment<M>(n, m) + rho.cwiseProduct(z)\n      - rho.cwiseProduct(z_next);\n    z = z_next;\n\n    if (iter % prm.stop_check_iter == 1) {\n      // check stopping criteria for unscaled problem and unscaled variables\n      x_us     = S.template head<N>(n).cwiseProduct(x);\n      y_us     = S.template segment<M>(n, m).cwiseProduct(y) / c;\n      z_us     = S.template segment<M>(n, m).cwiseInverse().cwiseProduct(z);\n      dx_us    = S.template head<N>(n).cwiseProduct(x - dx_us);\n      dy_us    = S.template segment<M>(n, m).cwiseProduct(y - dy_us) / c;\n      ret_code = detail::qp_check_stopping(pbm, x_us, y_us, z_us, dx_us, dy_us, prm);\n\n      if (prm.verbose) {\n        using std::cout, std::setw, std::right, std::chrono::microseconds;\n        // clang-format off\n        cout << setw(7) << right << iter << \":\"\n          << std::scientific\n          << setw(14) << right << (0.5 * pbm.P * x_us + pbm.q).dot(x_us)\n          << setw(14) << right << (pbm.A * x_us - z_us).template lpNorm<Eigen::Infinity>()\n          << setw(14) << right << (pbm.P * x_us + pbm.q + pbm.A.transpose() * y_us).template lpNorm<Eigen::Infinity>()\n          << setw(10) << right << duration_cast<microseconds>(std::chrono::high_resolution_clock::now() - t0).count()\n          << '\\n';\n        // clang-format on\n      }\n\n      // check for timeout\n      if (!ret_code) {\n        if (prm.max_time && std::chrono::high_resolution_clock::now() > t0 + prm.max_time.value()) {\n          ret_code = QPSolutionStatus::MaxTime;\n        }\n      }\n    }\n  }\n\n  double obj = x.dot(0.5 * pbm.P * x + pbm.q);\n\n  detail::qp_solution_t<Pbm> sol{\n    .code      = ret_code.value_or(QPSolutionStatus::MaxIterations),\n    .iter      = iter - 1,\n    .primal    = std::move(x),\n    .dual      = std::move(y),\n    .objective = obj,\n  };\n\n  const auto t_iter = std::chrono::high_resolution_clock::now();\n\n  // polish solution if optimal\n  if (sol.code == QPSolutionStatus::Optimal && prm.polish) {\n    if (detail::polish_qp(spbm, sol, prm)) {\n      if (prm.verbose) {\n        using std::cout, std::setw, std::right, std::chrono::microseconds;\n        x_us = S.template head<N>(n).cwiseProduct(sol.primal);          // NOTE: x std::moved to sol\n        y_us = S.template segment<M>(n, m).cwiseProduct(sol.dual) / c;  // NOTE: y std::moved to sol\n        z_us = S.template segment<M>(n, m).cwiseInverse().cwiseProduct(z);\n        // clang-format off\n        cout << setw(8) << right << \"polish:\"\n          << std::scientific\n          << setw(14) << right << (0.5 * pbm.P * x_us + pbm.q).dot(x_us)\n          << setw(14) << right << (pbm.A * x_us - z_us).template lpNorm<Eigen::Infinity>()\n          << setw(14) << right << (pbm.P * x_us + pbm.q + pbm.A.transpose() * y_us).template lpNorm<Eigen::Infinity>()\n          << setw(10) << right << duration_cast<microseconds>(std::chrono::high_resolution_clock::now() - t0).count()\n          << '\\n';\n        // clang-format on\n      }\n\n    } else {\n      if (prm.verbose) { std::cout << \"Polish failed\" << '\\n'; }\n      sol.code = QPSolutionStatus::PolishFailed;\n    }\n  }\n\n  const auto t_polish = std::chrono::high_resolution_clock::now();\n\n  // unscale solution\n  sol.primal.applyOnTheLeft(S.template head<N>(n).asDiagonal());\n  sol.dual.applyOnTheLeft(S.template segment<M>(n, m).asDiagonal());\n  sol.dual /= c;\n  sol.objective = sol.primal.dot(0.5 * pbm.P * sol.primal + pbm.q);\n\n  if (prm.verbose) {\n    using std::cout, std::left, std::right, std::setw, std::chrono::microseconds;\n\n    // clang-format off\n    cout << \"QP solver summary:\" << '\\n';\n    cout << \"Result \" << static_cast<int>(sol.code) << '\\n';\n\n    cout << setw(25) << left << \"Iterations\"        << setw(10) << right << iter - 1                                               << '\\n';\n    cout << setw(26) << left << \"Total time (\u00b5s)\"   << setw(10) << right << duration_cast<microseconds>(t_polish - t0).count()     << '\\n';\n    cout << setw(25) << left << \"  Matrix filling\"  << setw(10) << right << duration_cast<microseconds>(t_fill - t0).count()       << '\\n';\n    cout << setw(25) << left << \"  Factorization\"   << setw(10) << right << duration_cast<microseconds>(t_factor - t_fill).count() << '\\n';\n    cout << setw(25) << left << \"  Iteration\"       << setw(10) << right << duration_cast<microseconds>(t_iter - t_factor).count() << '\\n';\n    cout << setw(25) << left << \"  Polish\"          << setw(10) << right << duration_cast<microseconds>(t_polish - t_iter).count() << '\\n';\n    cout << \"=============================================================\" << '\\n';\n    // clang-format on\n  }\n\n  return sol;\n}\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__QP_HPP_\n", "meta": {"hexsha": "ab71cd87f610e852b8fd4204f976e7671cc3a6e0", "size": 29628, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/qp.hpp", "max_stars_repo_name": "pettni/smooth_feedback", "max_stars_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "include/smooth/feedback/qp.hpp", "max_issues_repo_name": "pettni/smooth_feedback", "max_issues_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "include/smooth/feedback/qp.hpp", "max_forks_repo_name": "pettni/smooth_feedback", "max_forks_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T15:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:23:18.000Z", "avg_line_length": 35.4826347305, "max_line_length": 139, "alphanum_fraction": 0.60290941, "num_tokens": 9018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5207918774302408}}
{"text": "// Copyright (c) 2018 by University Paris-Est Marne-la-Vallee\r\n// MetricTools.hpp\r\n// This file is part of the Garamon Generator.\r\n// Authors: Stephane Breuils and Vincent Nozick\r\n// Contact: vincent.nozick@u-pem.fr\r\n//\r\n// Licence MIT\r\n// A a copy of the MIT License is given along with this program\r\n\r\n/// \\file MetricTools.hpp\r\n/// \\author Stephane Breuils, Vincent Nozick\r\n/// \\brief Analyse and transform the metric related to the specified algebra.\r\n\r\n\r\n\r\n#ifndef GARAGEN_METRICTOOLS_HPP\r\n#define GARAGEN_METRICTOOLS_HPP\r\n\r\n#include <Eigen/Core>\r\n#include <vector>\r\n#include <Eigen/Sparse>\r\n#include <Eigen/LU> // for inverting\r\n\r\n#include \"Utilities.hpp\"\r\n\r\nbool isMatrixDiagonal(const Eigen::MatrixXd &metric, const double epsilon);\r\n\r\nbool isMatrixIdentity(const Eigen::MatrixXd &metric, const double epsilon);\r\n\r\nbool isMatrixPermutationOfDiagonal(const Eigen::MatrixXd &metric, const double epsilon);\r\n\r\nunsigned int getRank(const Eigen::MatrixXd &metric);\r\n\r\nvoid eigenDecomposition(const Eigen::MatrixXd &M, Eigen::MatrixXd &P, Eigen::MatrixXd &A);\r\n\r\ndouble minAbsNonZeroValue(Eigen::VectorXd x);\r\n\r\nEigen::MatrixXd eigenRefinement(Eigen::MatrixXd &P, Eigen::MatrixXd &D, Eigen::MatrixXd &Pinv);\r\n\r\nEigen::MatrixXd numericalCleanUp(const Eigen::MatrixXd &M, const double epsilon);\r\n\r\nEigen::VectorXd vectorNumericalCleanUp(const Eigen::VectorXd& original, const double epsilon);\r\n\r\nbool checkNumericalCleanUp(const Eigen::MatrixXd &M, const Eigen::MatrixXd &P, const Eigen::MatrixXd &A, const double epsilon);\r\n\r\nbool checkNumericalCleanUp(const Eigen::MatrixXd &M, const Eigen::MatrixXd &P, const Eigen::MatrixXd &A, const Eigen::MatrixXd &Pinv, const double epsilon);\r\n\r\nEigen::SparseMatrix<double> numericalCleanUpSparse(const Eigen::MatrixXd &M, const double epsilon);\r\n\r\nEigen::SparseMatrix<double, Eigen::ColMajor> computePerGradeTransformationMatrix(const Eigen::MatrixXd &vectorTransformationMatrix,\r\n                                         const unsigned int dimension, const unsigned int grade, const double epsilon);\r\n\r\nEigen::SparseMatrix<double, Eigen::ColMajor>  computeInverseTransformationMatrix(const Eigen::SparseMatrix<double, Eigen::ColMajor>& transformationMatrix, const double epsilon);\r\n\r\nstd::pair<std::vector<double>,std::vector<double>> computeTransformationMatricesToVector(const Eigen::MatrixXd &P, const double epsilon,std::vector<unsigned int>& transformationMatricesSizes,\r\n                                                                                       std::vector<Eigen::SparseMatrix<double, Eigen::ColMajor> >& allTransformationMatrices,\r\n                                                                                       std::vector<Eigen::SparseMatrix<double, Eigen::ColMajor> >& allInverseTransformationMatrices);\r\n\r\nstd::vector<double> transformationMatricesToVectorOfComponents(const Eigen::SparseMatrix<double, Eigen::ColMajor> &transformationMatrix, const int grade, const bool isInverse);\r\n\r\n#endif //GARAGEN_METRICTOOLS_HPP\r\n", "meta": {"hexsha": "1232422e9db7880297f728dace7f02b0961712fc", "size": 2994, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/MetricTools.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/MetricTools.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/MetricTools.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": 48.2903225806, "max_line_length": 192, "alphanum_fraction": 0.7217768871, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.520791870683733}}
{"text": "/*\n dparallel_recursion: distributed parallel_recursion skeleton\n Copyright (C) 2015-2018 Carlos H. Gonzalez, Basilio B. Fraguela. Universidade da Coruna\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#ifdef OPENBLAS\n\n#include \"cblas.h\"\n\nvoid mxm(const MMatrix& a, const MMatrix& b, MMatrix& c)\n{\n  openblas_set_num_threads(1);\n  \n  cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n              a.rows(), c.cols(), a.cols(),\n              1.0, a.raw(), a.row_stride(),\n              b.raw(), b.row_stride(),\n              0.0, c.raw(), c.row_stride());\n}\n\n#else\n\n#ifndef NOBOOST\n\n#define BOOST_UBLAS_SHALLOW_ARRAY_ADAPTOR\n#define BOOST_UBLAS_NDEBUG\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n\nvoid mxm(const MMatrix& a, const MMatrix& b, MMatrix& c)\n{\n  using namespace boost::numeric::ublas;\n\n  typedef matrix<double, row_major, shallow_array_adaptor<double> > MyMatrixType;\n  \n  shallow_array_adaptor<double> am(a.rows() * a.row_stride(), a.raw());\n  shallow_array_adaptor<double> bm(b.rows() * b.row_stride(), b.raw());\n  shallow_array_adaptor<double> cm(c.rows() * c.row_stride(), c.raw());\n  \n  MyMatrixType ax(a.rows(), a.row_stride(), am);\n  MyMatrixType bx(b.rows(), b.row_stride(), bm);\n  MyMatrixType cx(c.rows(), c.row_stride(), cm);\n\n  matrix_range<MyMatrixType> mra (ax, range (0, a.rows()), range (0, a.cols()));\n  matrix_range<MyMatrixType> mrb (bx, range (0, b.rows()), range (0, b.cols()));\n  matrix_range<MyMatrixType> mrc (cx, range (0, c.rows()), range (0, c.cols()));\n  \n  axpy_prod(mra, mrb, mrc, true);\n}\n\n#else\n\nvoid mxm(const MMatrix& a, const MMatrix& b, MMatrix& c)\n{\n  const int common_dim = a.cols();\n  assert(common_dim == b.rows());\n  for (int i = 0; i < c.rows(); i++) {\n    for (int j = 0; j < c.cols(); j++) {\n      double r = 0.0;\n      for (int k = 0; k < common_dim; k++) {\n        r += a(i, k) * b(k, j);\n      }\n      c(i, j) = r;\n    }\n  }\n}\n\n#endif\n\n#endif\n", "meta": {"hexsha": "6bb27a42aac8b4035d79cce39dbb99b9ac2fd740", "size": 2441, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sequential/mxm_product.cpp", "max_stars_repo_name": "fraguela/dparallel_recursion", "max_stars_repo_head_hexsha": "30050242b7d01766fee5a3107c7a79db5c512d9e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-01T07:48:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T14:01:35.000Z", "max_issues_repo_path": "sequential/mxm_product.cpp", "max_issues_repo_name": "fraguela/dparallel_recursion", "max_issues_repo_head_hexsha": "30050242b7d01766fee5a3107c7a79db5c512d9e", "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": "sequential/mxm_product.cpp", "max_forks_repo_name": "fraguela/dparallel_recursion", "max_forks_repo_head_hexsha": "30050242b7d01766fee5a3107c7a79db5c512d9e", "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.0595238095, "max_line_length": 88, "alphanum_fraction": 0.6636624334, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5207918670440441}}
{"text": "/**\n * Copyright (c) 2022 <Daumantas Kavolis>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#pragma once\n\n#include <array>\n#include <vector>\n\n#include \"config.hpp\"\n\nMSVC_WARNING_DISABLE(4619)\n#include <boost/math/quadrature/gauss.hpp>\n#include <boost/math/quadrature/gauss_kronrod.hpp>\nMSVC_WARNING_POP()\n\n#include \"utils.hpp\"\n\nnamespace poly {\n\nnamespace detail {\n/// \\brief function pointer type to get weights/abscissa\ntemplate <class Real>\nusing quadrature_getter = view<Real const> (*)();\n\ntemplate <Reflection Refl, class Container>\n[[nodiscard]] auto full_vector(Container&& points, size_t expected_points [[maybe_unused]])\n    -> decltype(auto) {\n  using Real = std::remove_cvref_t<typename std::remove_cvref_t<Container>::value_type>;\n\n  std::vector<Real> v = to_vector(points);\n  if constexpr (Refl != Reflection::None) {\n    reflect_in_place<Refl>(v, 2 * v.size() > expected_points);\n  }\n\n  return v;\n}\n\ntemplate <class Real, template <class, unsigned> typename Impl, bool Reflect = true>\nstruct BaseQuadrature {\n  template <unsigned Points>\n  static auto weights() -> view<Real const> {\n    static std::vector<Real> items =\n        full_vector<Reflection::Even>(Impl<Real, Points>::weights(), Points);\n    return {items.data(), items.size()};\n  }\n\n  template <unsigned Points>\n  static auto abscissa() -> view<Real const> {\n    static std::vector<Real> items =\n        full_vector<Reflection::Odd>(Impl<Real, Points>::abscissa(), Points);\n    return {items.data(), items.size()};\n  }\n};\n\n/// \\brief Wrapper for boost quadrature to convert compile time points count to runtime\n/// \\tparam Real floating point type\n/// \\tparam Impl Type implementing static functions weights() and abscissa()\n/// \\tparam N Maximum number of points in quadrature\n/// \\tparam Reflect Whether the values from Impl should be reflected first\ntemplate <typename Real, template <class, unsigned> typename Impl, unsigned N = QuadraturePoints,\n          bool Reflect = true>\nstruct Quadrature : BaseQuadrature<Real, Impl, Reflect> {\n  using Base = BaseQuadrature<Real, Impl, Reflect>;\n  template <bool check>\n  static auto weights(unsigned points, bounds_check<check> /* unused */ = no_bounds_check)\n      -> view<Real const> {\n    if constexpr (check)\n      return weights_getters().at(points)();\n    else\n      return weights_getters()[points]();\n  }\n\n  template <bool check = false>\n  static auto abscissa(unsigned points, bounds_check<check> /* unused */ = no_bounds_check)\n      -> view<Real const> {\n    if constexpr (check)\n      return abscissa_getters().at(points)();\n    else\n      return abscissa_getters()[points]();\n  }\n\n private:\n  // using array of function pointers so that the values are only generated on first access\n  using function_container = std::array<detail::quadrature_getter<Real>, N + 1> const;\n\n  template <unsigned... I>\n  static auto make_weights(std::integer_sequence<unsigned, I...> /*unused*/) {\n    return function_container{&Base::template weights<I>...};\n  }\n\n  template <unsigned... I>\n  static auto make_abscissa(std::integer_sequence<unsigned, I...> /*unused*/) {\n    return function_container{&Base::template abscissa<I>...};\n  }\n\n  static auto weights_getters() -> function_container const& {\n    static function_container functions =\n        make_weights(std::make_integer_sequence<unsigned, N + 1>{});\n    return functions;\n  }\n\n  static auto abscissa_getters() -> function_container const& {\n    static function_container functions =\n        make_abscissa(std::make_integer_sequence<unsigned, N + 1>{});\n    return functions;\n  }\n};\n\ntemplate <typename R, unsigned n>\nusing GaussQuadrature = boost::math::quadrature::gauss<R, n>;\n\ntemplate <typename R, unsigned n>\nusing GaussKronrodQuadrature = boost::math::quadrature::gauss_kronrod<R, n>;\n}  // namespace detail\n\ntemplate <typename Real, unsigned N = QuadraturePoints>\nusing GaussQuadrature = detail::Quadrature<Real, detail::GaussQuadrature, N, true>;\n\ntemplate <typename Real, unsigned N = QuadraturePoints>\nusing GaussKronrodQuadrature = detail::Quadrature<Real, detail::GaussKronrodQuadrature, N, true>;\n\n}  // namespace poly\n", "meta": {"hexsha": "d90bc5c37d7bb8a23ca3b16d0e99c1b0d2161ffa", "size": 5146, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/polynomials/include/quadrature.hpp", "max_stars_repo_name": "dkavolis/polynomials", "max_stars_repo_head_hexsha": "10abe0ca8bdd3ae7dafc1ecd04142b42e3213af0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomials/include/quadrature.hpp", "max_issues_repo_name": "dkavolis/polynomials", "max_issues_repo_head_hexsha": "10abe0ca8bdd3ae7dafc1ecd04142b42e3213af0", "max_issues_repo_licenses": ["MIT"], "max_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/include/quadrature.hpp", "max_forks_repo_name": "dkavolis/polynomials", "max_forks_repo_head_hexsha": "10abe0ca8bdd3ae7dafc1ecd04142b42e3213af0", "max_forks_repo_licenses": ["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.2394366197, "max_line_length": 97, "alphanum_fraction": 0.7242518461, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5207918670440441}}
{"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_TANH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_TANH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-hyperbolic\n    Function object implementing tanh capabilities\n\n    Returns the hyperbolic tangent: \\f$\\sinh(x)/\\cosh(x)\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type @c T\n\n    @code\n    T r = tanh(x);\n    @endcode\n\n    @see sinh,  cosh\n  **/\n  Value tanh(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/tanh.hpp>\n#include <boost/simd/function/simd/tanh.hpp>\n\n#endif\n", "meta": {"hexsha": "cdf7fda4c447b8b1a8e9c53c2cdba24caf9ebeaa", "size": 978, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/tanh.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/tanh.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/tanh.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": 22.7441860465, "max_line_length": 100, "alphanum_fraction": 0.563394683, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5207830563751922}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Peter Caspers\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 <ql/quantlib.hpp>\n#include <boost/timer.hpp>\n\nusing namespace QuantLib;\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib {\nInteger sessionId() { return 0; }\n}\n#endif\n\nclass Timer {\n    boost::timer timer_;\n    double elapsed_;\n\n  public:\n    void start() { timer_ = boost::timer(); }\n    void stop() { elapsed_ = timer_.elapsed(); }\n    double elapsed() const { return elapsed_; }\n};\n\n// reusable code snipped to perform one pricing step\n#define PROXY_PRICING \\\n        npvRef = swaptionRef2->NPV(); \\\n        timer.start(); \\\n        npvProxy = swaption2->NPV(); \\\n        /*underlyingProxy = 0.0; swaption2->result<Real>(\"exerciseValue\");*/ \\\n        timer.stop(); \\\n        npvProxyTiming = timer.elapsed(); \\\n        std::clog << \"\\nPricing results on \" \\\n                  << Settings::instance().evaluationDate() \\\n                  << \", reference rate \" << rateLevelRefQuote->value() \\\n                  << \" with maturity \" << maturityRefQuote->value() << \"\\n\"; \\\n        std::clog << \"Integral engine npv = \" << npvRef << \"\\n\"; \\\n        std::clog << \"Proxy    engine npv = \" << npvProxy \\\n                  << \" (timing: \" << npvProxyTiming*1000000.0 \\\n        << \"mus)\" /*<< \", underlying npv = \" << underlyingProxy*/ << \"\\n\";\n// here the main part of the code starts\n\nint main(int argc, char *argv[]) {\n\n    try {\n\n        std::clog << \"Bermudan swaption proxy pricing example\\n\";\n\n        // Timer seutp\n\n        Timer timer;\n\n        // Original evaluation date and rate level\n\n        Real rateLevelOrig = 0.02;\n        Date refDateOrig(12, January, 2015);\n\n        Settings::instance().evaluationDate() = refDateOrig;\n\n        // the yield term structure for the original pricing\n        // this must _not_ be floating, see the warning in\n        // the proxy engine's header.\n\n        Handle<YieldTermStructure> ytsOrig(boost::make_shared<FlatForward>(\n            refDateOrig, rateLevelOrig, Actual365Fixed()));\n\n        // the yield term structure for reference pricings\n        // (integral engine) on future dates, this _floating_\n\n        boost::shared_ptr<SimpleQuote> rateLevelRefQuote =\n            boost::make_shared<SimpleQuote>(0.02);\n        Handle<Quote> rateLevelRef(rateLevelRefQuote);\n        Handle<YieldTermStructure> ytsRef(boost::make_shared<FlatForward>(\n            0, TARGET(), rateLevelRef, Actual365Fixed()));\n\n        // the euribor index for the swaption's underlying.\n        // one should again use the fixed yts ...\n        boost::shared_ptr<IborIndex> euribor6m =\n            boost::make_shared<Euribor>(6 * Months, ytsOrig);\n        // but for the reference pricings in the integral engine\n        // we need a floating version as well.\n        boost::shared_ptr<IborIndex> euribor6mRef =\n            boost::make_shared<Euribor>(6 * Months, ytsRef);\n\n        // the length of the bermudan swaption in years\n\n        Size length = 10;\n\n        // instrument setup\n\n        Real strike = 0.02; // near atm option\n        Date effectiveDate = TARGET().advance(refDateOrig, 2 * Days);\n        Date startDate = TARGET().advance(effectiveDate, 1 * Years);\n        Date maturityDate = TARGET().advance(startDate, length * Years);\n\n        Schedule fixedSchedule(startDate, maturityDate, 1 * Years, TARGET(),\n                               ModifiedFollowing, ModifiedFollowing,\n                               DateGeneration::Forward, false);\n        Schedule floatingSchedule(startDate, maturityDate, 6 * Months, TARGET(),\n                                  ModifiedFollowing, ModifiedFollowing,\n                                  DateGeneration::Forward, false);\n\n        boost::shared_ptr<VanillaSwap> underlying =\n            boost::make_shared<VanillaSwap>(VanillaSwap(\n                VanillaSwap::Payer, 1.0, fixedSchedule, strike, Thirty360(),\n                floatingSchedule, euribor6m, 0.0, Actual360()));\n        boost::shared_ptr<VanillaSwap> underlyingRef =\n            boost::make_shared<VanillaSwap>(VanillaSwap(\n                VanillaSwap::Payer, 1.0, fixedSchedule, strike, Thirty360(),\n                floatingSchedule, euribor6mRef, 0.0, Actual360()));\n\n        std::vector<Date> exerciseDates;\n        for (Size i = 0; i < length; ++i) {\n            exerciseDates.push_back(\n                TARGET().advance(fixedSchedule[i], -2 * Days));\n        }\n\n        boost::shared_ptr<Exercise> exercise =\n            boost::make_shared<BermudanExercise>(exerciseDates, false);\n\n        boost::shared_ptr<Swaption> swaption =\n            boost::make_shared<Swaption>(underlying, exercise);\n        boost::shared_ptr<Swaption> swaptionRef =\n            boost::make_shared<Swaption>(underlyingRef, exercise);\n\n        // our instrument is a swaption, but the engine is for non standard\n        // swaptions\n        // so we just convert it\n\n        boost::shared_ptr<NonstandardSwaption> swaption2 =\n            boost::make_shared<NonstandardSwaption>(*swaption);\n        boost::shared_ptr<NonstandardSwaption> swaptionRef2 =\n            boost::make_shared<NonstandardSwaption>(*swaptionRef);\n\n        // just take any model volatility and reversion, we do not calibrate\n        // them here. Also they are flat, so no steps needed really.\n\n        std::vector<Date> stepDates;\n        std::vector<Real> sigmas(1, 0.0070);\n        Real reversion = 0.0030;\n\n        // the gsr model in T-forward measure, T=50 chosen arbitrary here\n        // the first model uses the fixed yts, used for the mc pricing\n        // generating the proxy\n\n        boost::shared_ptr<Gsr> gsrFixed = boost::make_shared<Gsr>(\n            ytsOrig, stepDates, sigmas, reversion, 50.0);\n\n        // the second model is used for the reference pricing, therefore\n        // using the floating yts\n\n        boost::shared_ptr<Gsr> gsrFloating =\n            boost::make_shared<Gsr>(ytsRef, stepDates, sigmas, reversion, 50.0);\n\n        // the integral engine for reference pricings\n\n        boost::shared_ptr<PricingEngine> integralEngine =\n            boost::make_shared<Gaussian1dNonstandardSwaptionEngine>(\n                gsrFloating, 64, 7.0, true, false, Handle<Quote>(), ytsRef);\n\n        // compute a reference price for the inital pricing\n\n        timer.start();\n        swaption2->setPricingEngine(integralEngine);\n        Real npvOrigIntegral = swaption2->NPV();\n        timer.stop();\n        Real npvOrigIntegralTiming = timer.elapsed();\n\n        // the mc engine, note that we use the fixed model here\n\n        boost::shared_ptr<PricingEngine> mcEngine =\n            MakeMcGaussian1dNonstandardSwaptionEngine<>(gsrFixed)\n                .withSteps(1) // the gsr model allows for large steps\n                .withSamples(10000)\n                .withSeed(42)\n                .withCalibrationSamples(10000)\n                .withProxy(true);\n\n        // compute the mc price\n\n        timer.start();\n        swaption2->setPricingEngine(mcEngine);\n        Real npvOrigMc = swaption2->NPV();\n        Real errorOrigMc = swaption2->errorEstimate();\n        timer.stop();\n        Real npvOrigMcTiming = timer.elapsed();\n\n        // output the results\n\n        std::clog << \"Pricing results on the original reference date (\"\n                  << refDateOrig << \"):\\n\";\n        std::clog << \"Integral engine npv = \" << npvOrigIntegral\n                  << \" (timing: \" << npvOrigIntegralTiming*1000000.0 << \"mus)\\n\";\n        std::clog << \"MC       engine npv = \" << npvOrigMc << \" error estimate \"\n                  << errorOrigMc << \" (timing: \" << npvOrigMcTiming*1000000.0 << \"mus)\\n\";\n\n        // proxy pricing, that is what this example is really about\n\n        // reference maturity for the scenario rate\n\n        boost::shared_ptr<SimpleQuote> maturityRefQuote =\n            boost::make_shared<SimpleQuote>();\n        Handle<Quote> maturityRef(maturityRefQuote);\n\n        boost::shared_ptr<PricingEngine> proxyEngine =\n            boost::make_shared<ProxyNonstandardSwaptionEngine>(\n                swaption2->proxy(), rateLevelRef, maturityRef, 64, 7.0, false);\n\n        Real npvRef, npvProxy, npvProxyTiming;\n\n        swaptionRef2->setPricingEngine(integralEngine);\n        swaption2->setPricingEngine(proxyEngine);\n\n        // move forward by 6 months, to the middle of the first period\n\n        Settings::instance().evaluationDate() = Date(12, June, 2015);\n        rateLevelRefQuote->setValue(0.02); // no change\n        maturityRefQuote->setValue(10.5);  // maturity of the underlying\n        PROXY_PRICING;\n\n        // move somewhere to the middle and check itm, otm, atm \n\n        Settings::instance().evaluationDate() = Date(11, June, 2019);\n        rateLevelRefQuote->setValue(0.025); // in the money\n        maturityRefQuote->setValue(6.5);  \n        PROXY_PRICING;\n        rateLevelRefQuote->setValue(0.02); // at the money\n        PROXY_PRICING;\n        rateLevelRefQuote->setValue(0.015); // out of the money\n        PROXY_PRICING;\n\n        // move to the beginning of a period\n\n        Settings::instance().evaluationDate() = Date(11, January, 2020);\n        rateLevelRefQuote->setValue(0.02); \n        maturityRefQuote->setValue(6.0);\n        PROXY_PRICING;\n\n        // move to the end of a period\n\n        Settings::instance().evaluationDate() = Date(11, January, 2021);\n        rateLevelRefQuote->setValue(0.02); \n        maturityRefQuote->setValue(5.0);\n        PROXY_PRICING;\n\n        // move to the last period\n\n        Settings::instance().evaluationDate() = Date(11, June, 2024);\n        rateLevelRefQuote->setValue(0.02); \n        maturityRefQuote->setValue(1.5);\n        PROXY_PRICING;\n\n        // check exercise\n\n        // Settings::instance().evaluationDate() = Date(10, January, 2020);\n        // rateLevelRefQuote->setValue(0.005);\n        // maturityRefQuote->setValue(6.0);\n        // npvProxy = swaption2->NPV();\n        // underlyingProxy = swaption2->result<Real>(\"exerciseValue\");\n        // std::clog << \"\\nExercise check (\" << Settings::instance().evaluationDate() << \"):\\n\";\n        // std::clog << \"otm option: exercise value=\" << underlyingProxy << \" npv=\" << npvProxy << std::endl;\n\n        // rateLevelRefQuote->setValue(0.04);\n        // npvProxy = swaption2->NPV();\n        // underlyingProxy = swaption2->result<Real>(\"exerciseValue\");\n        // std::clog << \"itm option: exercise value=\" << underlyingProxy << \" npv=\" << npvProxy << std::endl;\n\n        return 0;\n\n    } catch (QuantLib::Error e) {\n        std::clog << \"terminated with a ql exception: \" << e.what()\n                  << std::endl;\n        return 1;\n    } catch (std::exception e) {\n        std::clog << \"terminated with a general exception: \" << e.what()\n                  << std::endl;\n        return 1;\n    }\n}\n", "meta": {"hexsha": "61270448d9833943114661893bcad1b6bf155e31", "size": 11465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/ProxyPricing/ProxyPricing.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/ProxyPricing/ProxyPricing.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/ProxyPricing/ProxyPricing.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": 38.7331081081, "max_line_length": 109, "alphanum_fraction": 0.6154382904, "num_tokens": 2821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5207830284375199}}
{"text": "#include \"main.h\"\n#include \"main_picking.h\"\n\n#include \"geometrycentral/surface/halfedge_mesh.h\"\n#include \"geometrycentral/surface/meshio.h\"\n#include \"geometrycentral/surface/vertex_position_geometry.h\"\n#include \"polyscope/point_cloud.h\"\n\n#include \"../deps/polyscope/deps/args/args/args.hxx\"\n#include \"imgui.h\"\n#include \"surface_derivatives.h\"\n\n#include \"energy/tpe_kernel.h\"\n#include \"energy/all_energies.h\"\n#include \"helpers.h\"\n#include <memory>\n\n#include <Eigen/Sparse>\n#include <omp.h>\n\n#include \"sobolev/all_constraints.h\"\n#include \"sobolev/hs.h\"\n#include \"sobolev/hs_iterative.h\"\n#include \"sobolev/h1.h\"\n#include \"spatial/convolution.h\"\n#include \"spatial/convolution_kernel.h\"\n#include \"surface_derivatives.h\"\n#include \"obj_writer.h\"\n#include \"dropdown_strings.h\"\n#include \"energy/coulomb.h\"\n#include \"energy/willmore_energy.h\"\n\n#include \"bct_constructors.h\"\n\n#include \"remeshing/remeshing.h\"\n\nusing namespace geometrycentral;\nusing namespace geometrycentral::surface;\n\nnamespace rsurfaces\n{\n\n    int MainApp::specifiedNumThreads;\n    int MainApp::defaultNumThreads;\n\n    MainApp *MainApp::instance = 0;\n\n    MainApp::MainApp(MeshPtr mesh_, GeomPtr geom_, SurfaceFlow *flow_, polyscope::SurfaceMesh *psMesh_, std::string meshName_)\n        : mesh(std::move(mesh_)), geom(std::move(geom_)), geomOrig(geom->copy()), remesher(mesh, geom, geomOrig)\n    {\n        flow = flow_;\n        psMesh = psMesh_;\n        meshName = meshName_;\n        vertBVH = 0;\n        vertexPotential = 0;\n        ctrlMouseDown = false;\n        hasPickedVertex = false;\n        numSteps = 0;\n        methodChoice = GradientMethod::HsProjectedIterative;\n        timeSpentSoFar = 0;\n        realTimeLimit = 0;\n        logPerformance = false;\n        referenceEnergy = 0;\n        exitWhenDone = false;\n        totalObstacleVolume = 0;\n    }\n\n    void MainApp::logPerformanceLine()\n    {\n        // Regardless of thread setting, use multithreaded for the all-pairs energy\n        omp_set_num_threads(defaultNumThreads);\n\n        std::cout << \"Evaluating all-pairs energy using \" << defaultNumThreads << \" threads\" << std::endl;\n        referenceEnergy = new TPEnergyAllPairs(kernel->mesh, kernel->geom, kernel->alpha, kernel->beta);\n        referenceEnergy->Update();\n\n        geom->refreshQuantities();\n        std::ofstream outfile;\n        outfile.open(sceneData.performanceLogFile, std::ios_base::app);\n        double currentEnergy = referenceEnergy->Value();\n        std::cout << numSteps << \", \" << timeSpentSoFar << \", \" << currentEnergy << \", \" << mesh->nFaces() << std::endl;\n        outfile << numSteps << \", \" << timeSpentSoFar << \", \" << currentEnergy << \", \" << mesh->nFaces() << std::endl;\n        outfile.close();\n\n        delete referenceEnergy;\n\n        omp_set_num_threads(specifiedNumThreads);\n        std::cout << \"Switched back to \" << specifiedNumThreads << \" threads for flow\" << std::endl;\n\n    }\n\n    void MainApp::TakeOptimizationStep(bool remeshAfter, bool showAreaRatios)\n    {\n        ptic(\"MainApp::TakeOptimizationStep\");\n\n        if (logPerformance && numSteps == 0)\n        {\n            logPerformanceLine();\n        }\n\n        long beforeStep = currentTimeMilliseconds();\n\n        ptic(\"Switch\");\n        switch (methodChoice)\n        {\n        case GradientMethod::HsProjected:\n            flow->StepProjectedGradient();\n            break;\n        case GradientMethod::HsProjectedIterative:\n            flow->StepProjectedGradientIterative();\n            break;\n        case GradientMethod::HsExactProjected:\n            flow->StepProjectedGradientExact();\n            break;\n        case GradientMethod::H1Projected:\n            flow->StepH1ProjGrad();\n            break;\n        case GradientMethod::L2Unconstrained:\n            flow->StepL2Unconstrained();\n            break;\n        case GradientMethod::L2Projected:\n            flow->StepL2Projected();\n            break;\n        case GradientMethod::AQP:\n        {\n            double kappa = 100;\n            flow->StepAQP(1 / kappa);\n        }\n        break;\n        case GradientMethod::H1_LBFGS:\n            flow->StepH1LBFGS();\n            break;\n        case GradientMethod::BQN_LBFGS:\n            flow->StepBQN();\n            break;\n        case GradientMethod::H2Projected:\n        case GradientMethod::Willmore:\n            flow->StepH2Projected();\n            break;\n        default:\n            throw std::runtime_error(\"Unknown gradient method type.\");\n        }\n        ptoc(\"Switch\");\n\n        if (remeshAfter)\n        {\n            bool doCollapse = (numSteps % 1 == 0);\n            std::cout << \"Applying remeshing...\" << std::endl;\n            flow->verticesMutated = remesher.Remesh(5, doCollapse);\n            if (flow->verticesMutated)\n            {\n                std::cout << \"Vertices were mutated this step -- memory vectors are now invalid.\" << std::endl;\n            }\n            else\n            {\n                std::cout << \"Vertices were not mutated this step.\" << std::endl;\n            }\n            ptic(\"mesh->compress()\");\n            mesh->compress();\n            ptoc(\"mesh->compress()\");\n            ptic(\"MainApp::instance->reregisterMesh();\");\n            MainApp::instance->reregisterMesh();\n            ptoc(\"MainApp::instance->reregisterMesh();\");\n        }\n        else\n        {\n            flow->verticesMutated = false;\n            MainApp::instance->updateMeshPositions();\n        }\n        long afterStep = currentTimeMilliseconds();\n        long timeForStep = afterStep - beforeStep;\n        timeSpentSoFar += timeForStep;\n        numSteps++;\n        std::cout << \"  Mesh total volume = \" << totalVolume(geom, mesh) << std::endl;\n        std::cout << \"  Mesh total area = \" << totalArea(geom, mesh) << std::endl;\n\n        if (logPerformance)\n        {\n            logPerformanceLine();\n        }\n\n        if (showAreaRatios)\n        {\n            VertexData<double> areaRatio(*mesh);\n            for (Vertex v : mesh->vertices())\n            {\n                areaRatio[v] = geomOrig->vertexDualArea(v) / geom->vertexDualArea(v);\n            }\n\n            psMesh->addVertexScalarQuantity(\"Area ratios\", areaRatio);\n        }\n        ptoc(\"MainApp::TakeOptimizationStep\");\n    }\n\n    void MainApp::updateMeshPositions()\n    {\n        if (normalizeView)\n        {\n            double scale = 0;\n            for (GCVertex v : mesh->vertices())\n            {\n                scale = fmax(scale, norm(geom->inputVertexPositions[v]));\n            }\n            std::vector<Vector3> scaled(mesh->nVertices());\n            VertexIndices inds = mesh->getVertexIndices();\n            for (GCVertex v : mesh->vertices())\n            {\n                scaled[inds[v]] = geom->inputVertexPositions[v] / scale;\n            }\n            psMesh->updateVertexPositions(scaled);\n        }\n        else\n        {\n            psMesh->updateVertexPositions(geom->inputVertexPositions);\n        }\n        polyscope::requestRedraw();\n    }\n\n    void PlotMatrix(Eigen::MatrixXd &mat, polyscope::SurfaceMesh *psMesh, std::string name)\n    {\n        std::vector<Vector3> vecs;\n        for (int i = 0; i < mat.rows(); i++)\n        {\n            Vector3 row_i = GetRow(mat, i);\n            vecs.push_back(row_i);\n        }\n        psMesh->addVertexVectorQuantity(name, vecs);\n    }\n\n    void PlotVector(Eigen::VectorXd &vec, int nVerts, polyscope::SurfaceMesh *psMesh, std::string name)\n    {\n        Eigen::MatrixXd M;\n        M.setZero(nVerts, 3);\n        MatrixUtils::ColumnIntoMatrix(vec, M);\n        PlotMatrix(M, psMesh, name);\n    }\n\n    void MainApp::PlotGradients()\n    {\n        Eigen::MatrixXd l2Diff, hsGrad, hsGradExact;\n        l2Diff.setZero(mesh->nVertices(), 3);\n        hsGrad.setZero(mesh->nVertices(), 3);\n        hsGradExact.setZero(mesh->nVertices(), 3);\n\n        flow->UpdateEnergies();\n\n        std::cout << \"Assembling L2 differential...\" << std::endl;\n        long diffTimeStart = currentTimeMilliseconds();\n        flow->AssembleGradients(l2Diff);\n        long diffTimeEnd = currentTimeMilliseconds();\n        std::cout << \"Differential took \" << (diffTimeEnd - diffTimeStart) << \" ms\" << std::endl;\n\n        std::unique_ptr<Hs::HsMetric> hs = flow->GetHsMetric();\n\n        std::cout << \"Inverting \\\"sparse\\\" metric...\" << std::endl;\n        long sparseTimeStart = currentTimeMilliseconds();\n        hs->InvertMetricMat(l2Diff, hsGrad);\n        long sparseTimeEnd = currentTimeMilliseconds();\n        std::cout << \"Sparse metric took \" << (sparseTimeEnd - sparseTimeStart) << \" ms\" << std::endl;\n\n        std::cout << \"Inverting dense metric...\" << std::endl;\n        long timeStart = currentTimeMilliseconds();\n        std::vector<ConstraintPack> empty;\n        // hs->ProjectGradientExact(l2Diff, hsGradExact, empty);\n        hsGradExact = hsGrad;\n        long timeEnd = currentTimeMilliseconds();\n        std::cout << \"Dense metric took \" << (timeEnd - timeStart) << \" ms\" << std::endl;\n\n        PlotMatrix(l2Diff, psMesh, \"L2 differential\");\n        PlotMatrix(hsGrad, psMesh, \"Hs sparse gradient\");\n        PlotMatrix(hsGradExact, psMesh, \"Hs dense gradient\");\n    }\n\n    bool MainApp::pickNearbyVertex(GCVertex &out)\n    {\n        using namespace polyscope;\n        Vector2 screenPos = getMouseScreenPos();\n\n        std::pair<Structure *, size_t> pickVal =\n            pick::evaluatePickQuery(screenPos.x, screenPos.y);\n\n        GCVertex pickedVert;\n        GCFace pickedFace;\n        GCEdge pickedEdge;\n        GCHalfedge pickedHalfedge;\n\n        glm::mat4 view = polyscope::view::getCameraViewMatrix();\n        glm::mat4 proj = polyscope::view::getCameraPerspectiveMatrix();\n        glm::mat4 viewProj = proj * view;\n\n        polyscope::SurfaceMesh *asMesh = dynamic_cast<polyscope::SurfaceMesh *>(pickVal.first);\n\n        if (tryGetPickedVertex(asMesh, pickVal.second, mesh, pickedVert))\n        {\n            out = pickedVert;\n            return true;\n        }\n        else if (tryGetPickedFace(asMesh, pickVal.second, mesh, pickedFace))\n        {\n            out = nearestVertexToScreenPos(screenPos, geom, viewProj, pickedFace);\n            return true;\n        }\n        else if (tryGetPickedEdge(asMesh, pickVal.second, mesh, pickedEdge))\n        {\n            out = nearestVertexToScreenPos(screenPos, geom, viewProj, pickedEdge);\n            return true;\n        }\n        else if (tryGetPickedHalfedge(asMesh, pickVal.second, mesh, pickedHalfedge))\n        {\n            out = nearestVertexToScreenPos(screenPos, geom, viewProj, pickedHalfedge);\n            return true;\n        }\n        else\n        {\n            std::cout << \"No valid element was picked (index \" << pickVal.second << \")\" << std::endl;\n            return false;\n        }\n    }\n\n    class PVCompare\n    {\n    public:\n        bool operator()(PriorityVertex v1, PriorityVertex v2)\n        {\n            return (v1.priority > v2.priority);\n        }\n    };\n\n    double gaussian(double radius, double dist)\n    {\n        double radterm = dist / radius;\n        double epow = exp(-0.5 * radterm * radterm);\n        return epow;\n    }\n\n    void MainApp::GetFalloffWindow(GCVertex v, double radius, std::vector<PriorityVertex> &verts)\n    {\n        // Do a simple Dijkstra search on edges\n        VertexData<bool> seen(*mesh, false);\n        std::priority_queue<PriorityVertex, std::vector<PriorityVertex>, PVCompare> queue;\n        queue.push(PriorityVertex{v, 0, geom->inputVertexPositions[v]});\n\n        while (!queue.empty())\n        {\n            PriorityVertex next = queue.top();\n            queue.pop();\n\n            if (next.priority > radius)\n            {\n                break;\n            }\n            else if (seen[next.vertex])\n            {\n                continue;\n            }\n            else\n            {\n                // Mark the next vertex as seen\n                seen[next.vertex] = true;\n                // Compute the weight\n                double weight = gaussian(radius / 3, next.priority);\n                verts.push_back(PriorityVertex{next.vertex, weight, geom->inputVertexPositions[next.vertex]});\n\n                // Enqueue all neighbors\n                for (GCVertex neighbor : next.vertex.adjacentVertices())\n                {\n                    if (seen[neighbor])\n                    {\n                        continue;\n                    }\n                    // Add the next edge distance\n                    Vector3 p1 = geom->inputVertexPositions[next.vertex];\n                    Vector3 p2 = geom->inputVertexPositions[neighbor];\n                    double neighborDist = next.priority + norm(p1 - p2);\n\n                    queue.push(PriorityVertex{neighbor, neighborDist, geom->inputVertexPositions[neighbor]});\n                }\n            }\n        }\n\n        std::cout << \"Got \" << verts.size() << \" vertices\" << std::endl;\n    }\n\n    void MainApp::HandlePicking()\n    {\n        using namespace polyscope;\n\n        auto io = ImGui::GetIO();\n        glm::mat4 view = polyscope::view::getCameraViewMatrix();\n        glm::mat4 proj = polyscope::view::getCameraPerspectiveMatrix();\n        glm::mat4 viewProj = proj * view;\n\n        if (io.KeyCtrl && io.MouseDown[0])\n        {\n            if (!ctrlMouseDown)\n            {\n                if (pickNearbyVertex(pickedVertex))\n                {\n                    hasPickedVertex = true;\n                    GetFalloffWindow(pickedVertex, 0.5, dragVertices);\n\n                    Vector3 screen = projectToScreenCoords3(geom->inputVertexPositions[pickedVertex], viewProj);\n                    pickDepth = screen.z;\n\n                    Vector3 unprojected = unprojectFromScreenCoords3(Vector2{screen.x, screen.y}, pickDepth, viewProj);\n                    initialPickedPosition = geom->inputVertexPositions[pickedVertex];\n                }\n                ctrlMouseDown = true;\n            }\n            else\n            {\n                if (hasPickedVertex)\n                {\n                    Vector2 mousePos = getMouseScreenPos();\n                    Vector3 unprojected = unprojectFromScreenCoords3(mousePos, pickDepth, viewProj);\n                    Vector3 displacement = unprojected - initialPickedPosition;\n\n                    for (PriorityVertex &v : dragVertices)\n                    {\n                        Vector3 newPos = v.position + v.priority * displacement;\n                        geom->inputVertexPositions[v.vertex] = newPos;\n                    }\n\n                    flow->ResetAllConstraints();\n                    flow->ResetAllPotentials();\n\n                    if (vertexPotential)\n                    {\n                        for (PriorityVertex &v : dragVertices)\n                        {\n                            vertexPotential->ChangeVertexTarget(v.vertex, geom->inputVertexPositions[v.vertex]);\n                        }\n                    }\n\n                    updateMeshPositions();\n                }\n            }\n        }\n        else\n        {\n            if (ctrlMouseDown)\n            {\n                ctrlMouseDown = false;\n                hasPickedVertex = false;\n                dragVertices.clear();\n                // geom->inputVertexPositions[pickedVertex] = initialPickedPosition;\n                updateMeshPositions();\n            }\n        }\n    }\n\n    void MainApp::CreateAndDestroyBVH()\n    {\n        OptimizedClusterTree *bvh = CreateOptimizedBVH(mesh, geom);\n        std::cout << \"Created BVH\" << std::endl;\n        delete bvh;\n        std::cout << \"Deleted BVH\" << std::endl;\n    }\n\n    void MainApp::Scale2x()\n    {\n        for (GCVertex v : mesh->vertices())\n        {\n            geom->inputVertexPositions[v] = 2 * geom->inputVertexPositions[v];\n        }\n    }\n\n    Jacobian numericalNormalDeriv(GeomPtr &geom, GCVertex vert, GCVertex wrt)\n    {\n        double h = 1e-4;\n\n        Vector3 origNormal = vertexAreaNormal(geom, vert);\n        Vector3 origPos = geom->inputVertexPositions[wrt];\n        geom->inputVertexPositions[wrt] = origPos + Vector3{h, 0, 0};\n        geom->refreshQuantities();\n        Vector3 n_x = vertexAreaNormal(geom, vert);\n\n        geom->inputVertexPositions[wrt] = origPos + Vector3{0, h, 0};\n        geom->refreshQuantities();\n        Vector3 n_y = vertexAreaNormal(geom, vert);\n\n        geom->inputVertexPositions[wrt] = origPos + Vector3{0, 0, h};\n        geom->refreshQuantities();\n        Vector3 n_z = vertexAreaNormal(geom, vert);\n\n        geom->inputVertexPositions[wrt] = origPos;\n        geom->refreshQuantities();\n\n        Vector3 deriv_y = (n_y - origNormal) / h;\n        Vector3 deriv_z = (n_z - origNormal) / h;\n        Vector3 deriv_x = (n_x - origNormal) / h;\n        Jacobian J_num{deriv_x, deriv_y, deriv_z};\n        return J_num;\n    }\n\n    void MainApp::TestNormalDeriv()\n    {\n        GCVertex vert;\n        for (GCVertex v : mesh->vertices())\n        {\n            if (v.isBoundary())\n            {\n                vert = v;\n                break;\n            }\n        }\n        std::cout << \"Testing vertex \" << vert << std::endl;\n        for (GCVertex neighbor : vert.adjacentVertices())\n        {\n            std::cout << \"Derivative of normal of \" << vert << \" wrt \" << neighbor << std::endl;\n            Jacobian dWrtNeighbor = SurfaceDerivs::vertexNormalWrtVertex(geom, vert, neighbor);\n            dWrtNeighbor.Print();\n            std::cout << \"Numerical:\" << std::endl;\n            numericalNormalDeriv(geom, vert, neighbor).Print();\n        }\n        std::cout << \"Derivative of normal of \" << vert << \" wrt \" << vert << std::endl;\n        Jacobian dWrtSelf = SurfaceDerivs::vertexNormalWrtVertex(geom, vert, vert);\n        dWrtSelf.Print();\n        std::cout << \"Numerical:\" << std::endl;\n        numericalNormalDeriv(geom, vert, vert).Print();\n    }\n\n    void MainApp::TestMultiply()\n    {\n        int threads;\n#pragma omp parallel\n        {\n            threads = omp_get_num_threads();\n        }\n\n        std::cout << std::setprecision(8);\n        std::cout << \"\\n  =====                   =====  \" << std::endl;\n        std::cout << \"=======   TestMultiply   =======\" << std::endl;\n        std::cout << \"  =====                   =====  \" << std::endl;\n        std::cout << \"\\n\"\n                  << std::endl;\n\n        double alpha = 6.;\n        double beta = 12.;\n        double weight = 1.;\n        //        double theta = MainApp::instance->bh_theta;\n        double theta = 0.5;\n        double chi = theta;\n        //        double chi = 0.8 * theta;\n\n        // mesh1 and geom1 represent the movable surface\n        auto mesh = rsurfaces::MainApp::instance->mesh;\n        auto geom = rsurfaces::MainApp::instance->geom;\n\n\n        OptimizedClusterTree *bvh = CreateOptimizedBVH(mesh, geom);\n        BCTPtr bct = CreateOptimizedBCTFromBVH(bvh, alpha, beta, chi);\n\n        mint vertex_count = mesh->nVertices();\n\n        Eigen::MatrixXd V(vertex_count, 3);\n\n        for (mint i = 0; i < vertex_count; ++i)\n        {\n            for (mint j = 0; j < 3; ++j)\n            {\n                V(i, j) = geom->inputVertexPositions[i][j];\n            }\n        }\n\n        Eigen::MatrixXd U(vertex_count, 3);\n        std::ofstream os;\n        mreal *ptr;\n        mint n;\n        std::string name;\n\n        // ####### FractionalOnly\n\n        name = \"FractionalOnly\";\n\n        U.setZero();\n        bct->Multiply(V, U, BCTKernelType::FractionalOnly);\n\n        os.open(\"./Output_\" + name + \".tsv\");\n        for (mint i = 0; i < vertex_count; ++i)\n        {\n            os << U(i, 0) << \"\\t\";\n            os << U(i, 1) << \"\\t\";\n            os << U(i, 2) << \"\\n\";\n        }\n        os.close();\n\n        os.open(\"./P_in_\" + name + \".tsv\");\n        ptr = bct->S->P_in;\n        n = bct->T->cluster_count * bct->T->buffer_dim;\n        for (mint i = 0; i < n - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[n - 1];\n        os.close();\n\n        os.open(\"./C_in_leaves_\" + name + \".tsv\");\n        ptr = bct->T->C_in;\n        n = bct->T->buffer_dim;\n        for (mint i = 0; i < bct->T->leaf_cluster_count; ++i)\n        {\n            for (mint k = 0; k < n; ++k)\n                os << ptr[n * bct->T->leaf_clusters[i] + k] << \"\\t\";\n        }\n        os.close();\n\n        os.open(\"./C_in_\" + name + \".tsv\");\n        ptr = bct->T->C_in;\n        n = bct->T->cluster_count * bct->T->buffer_dim;\n        for (mint i = 0; i < n - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[n - 1];\n        os.close();\n\n        os.open(\"./C_out_\" + name + \".tsv\");\n        ptr = bct->S->C_out;\n        n = bct->S->cluster_count * bct->S->buffer_dim;\n        for (mint i = 0; i < n - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[n - 1];\n        os.close();\n\n        os.open(\"./P_out_\" + name + \".tsv\");\n        ptr = bct->S->P_out;\n        n = bct->S->cluster_count * bct->S->buffer_dim;\n        for (mint i = 0; i < n - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[n - 1];\n        os.close();\n\n        // ####### LowOrder\n\n        name = \"LowOrder\";\n\n        U.setZero();\n        bct->Multiply(V, U, BCTKernelType::LowOrder);\n\n        os.open(\"./Output_\" + name + \".tsv\");\n        for (mint i = 0; i < vertex_count; ++i)\n        {\n            os << U(i, 0) << \"\\t\";\n            os << U(i, 1) << \"\\t\";\n            os << U(i, 2) << \"\\n\";\n        }\n        os.close();\n\n        os.open(\"./P_in_\" + name + \".tsv\");\n        ptr = bct->S->P_in;\n        n = bct->T->cluster_count * bct->T->buffer_dim;\n        for (mint i = 0; i < n - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[n - 1];\n        os.close();\n\n        os.open(\"./C_in_leaves_\" + name + \".tsv\");\n        ptr = bct->T->C_in;\n        n = bct->T->buffer_dim;\n        for (mint i = 0; i < bct->T->leaf_cluster_count; ++i)\n        {\n            for (mint k = 0; k < n; ++k)\n                os << ptr[n * bct->T->leaf_clusters[i] + k] << \"\\t\";\n        }\n        os.close();\n\n        os.open(\"./C_in_\" + name + \".tsv\");\n        ptr = bct->T->C_in;\n        n = bct->T->cluster_count * bct->T->buffer_dim;\n        for (mint i = 0; i < n - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[n - 1];\n        os.close();\n\n        os.open(\"./C_out_\" + name + \".tsv\");\n        ptr = bct->S->C_out;\n        n = bct->S->cluster_count * bct->S->buffer_dim;\n        for (mint i = 0; i < n - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[n - 1];\n        os.close();\n\n        os.open(\"./P_out_\" + name + \".tsv\");\n        ptr = bct->S->P_out;\n        n = bct->S->cluster_count * bct->S->buffer_dim;\n        for (mint i = 0; i < n - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[n - 1];\n        os.close();\n\n        // ####### LowOrder\n\n        name = \"HighOrder\";\n\n        U.setZero();\n        bct->Multiply(V, U, BCTKernelType::HighOrder);\n\n        os.open(\"./Output_\" + name + \".tsv\");\n        for (mint i = 0; i < vertex_count; ++i)\n        {\n            os << U(i, 0) << \"\\t\";\n            os << U(i, 1) << \"\\t\";\n            os << U(i, 2) << \"\\n\";\n        }\n        os.close();\n\n        os.open(\"./P_in_\" + name + \".tsv\");\n        ptr = bct->S->P_in;\n        n = bct->T->cluster_count * bct->T->buffer_dim;\n        for (mint i = 0; i < n - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[n - 1];\n        os.close();\n\n        os.open(\"./C_in_leaves_\" + name + \".tsv\");\n        ptr = bct->T->C_in;\n        n = bct->T->buffer_dim;\n        for (mint i = 0; i < bct->T->leaf_cluster_count; ++i)\n        {\n            for (mint k = 0; k < n; ++k)\n                os << ptr[n * bct->T->leaf_clusters[i] + k] << \"\\t\";\n        }\n        os.close();\n\n        os.open(\"./C_in_\" + name + \".tsv\");\n        ptr = bct->T->C_in;\n        n = bct->T->cluster_count * bct->T->buffer_dim;\n        for (mint i = 0; i < n - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[n - 1];\n        os.close();\n\n        os.open(\"./C_out_\" + name + \".tsv\");\n        ptr = bct->S->C_out;\n        n = bct->S->cluster_count * bct->S->buffer_dim;\n        for (mint i = 0; i < n - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[n - 1];\n        os.close();\n\n        os.open(\"./P_out_\" + name + \".tsv\");\n        ptr = bct->S->P_out;\n        n = bct->S->cluster_count * bct->S->buffer_dim;\n        for (mint i = 0; i < n - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[n - 1];\n        os.close();\n\n        os.open(\"./Far_FractionalOnly.tsv\");\n        ptr = bct->far->fr_values;\n        for (mint i = 0; i < bct->far->nnz - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[bct->far->nnz - 1];\n        os.close();\n        os.open(\"./Far_LowOrder.tsv\");\n        ptr = bct->far->lo_values;\n        for (mint i = 0; i < bct->far->nnz - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[bct->far->nnz - 1];\n        os.close();\n\n        os.open(\"./Far_HighOrder.tsv\");\n        ptr = bct->far->hi_values;\n        for (mint i = 0; i < bct->far->nnz - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[bct->far->nnz - 1];\n        os.close();\n\n        os.open(\"./Near_FractionalOnly.tsv\");\n        ptr = bct->near->fr_values;\n        for (mint i = 0; i < bct->near->nnz - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[bct->near->nnz - 1];\n        os.close();\n        os.open(\"./Near_LowOrder.tsv\");\n        ptr = bct->near->lo_values;\n        for (mint i = 0; i < bct->near->nnz - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[bct->near->nnz - 1];\n        os.close();\n\n        os.open(\"./Near_HighOrder.tsv\");\n        ptr = bct->near->hi_values;\n        for (mint i = 0; i < bct->near->nnz - 1; ++i)\n        {\n            os << ptr[i] << \"\\t\";\n        }\n        os << ptr[bct->near->nnz - 1];\n        os.close();\n\n        delete bvh;\n\n        std::cout << \"TestMultiply finished.\" << std::endl;\n    }\n\n    void MainApp::TestUpdate()\n    {\n        auto tpe = std::make_shared<TPEnergyBarnesHut0>(mesh, geom, 6., 12., 0.5, 1.);\n\n        auto mesh = rsurfaces::MainApp::instance->mesh;\n        auto geom = rsurfaces::MainApp::instance->geom;\n\n        valprint(\"Energy\", tpe->Value());\n\n        UpdateOptimizedBVH(tpe->GetBVH(), mesh, geom);\n\n        valprint(\"Energy\", tpe->Value());\n\n    } // TestUpdate\n\n    void MainApp::TestObstacle0()\n    {\n        int threads;\n#pragma omp parallel\n        {\n            threads = omp_get_num_threads();\n        }\n        ClearProfile(\"./TestObstacle0_\" + std::to_string(threads) + \".tsv\");\n\n        std::cout << std::setprecision(8);\n        std::cout << \"\\n  =====                   =====  \" << std::endl;\n        std::cout << \"=======   TestObstacle0   =======\" << std::endl;\n        std::cout << \"  =====                   =====  \" << std::endl;\n        std::cout << \"\\n\"\n                  << std::endl;\n\n        double alpha = 6.;\n        double beta = 12.;\n        double weight = 1.;\n        //        double theta = MainApp::instance->bh_theta;\n        double theta = 0.25;\n        double chi = theta;\n        //        double chi = 0.8 * theta;\n\n        // mesh1 and geom1 represent the movable surface\n        auto mesh1 = rsurfaces::MainApp::instance->mesh;\n        auto geom1 = rsurfaces::MainApp::instance->geom;\n\n        // Load obstacle\n        //        std::string filename = \"../scenes/Bunny/bunny-10p.obj\";\n        std::string filename = \"../scenes/Bunny/bunny.obj\";\n        MeshUPtr umesh;\n        GeomUPtr ugeom;\n        std::tie(umesh, ugeom) = readMesh(filename);\n        ugeom->requireVertexDualAreas();\n        ugeom->requireVertexNormals();\n        std::string mesh_name = polyscope::guessNiceNameFromPath(filename);\n        polyscope::SurfaceMesh *psMesh = polyscope::registerSurfaceMesh(mesh_name, ugeom->inputVertexPositions, umesh->getFaceVertexList(), polyscopePermutations(*umesh));\n        // mesh2 and geom2 represent the pinned obstacle\n        MeshPtr mesh2 = std::move(umesh);\n        std::shared_ptr<VertexPositionGeometry> geom2 = std::move(ugeom);\n\n        mint primitive_count1 = mesh1->nVertices();\n        mint primitive_count2 = mesh2->nVertices();\n\n        tic(\"Create bvh1\");\n        OptimizedClusterTree *bvh1 = CreateOptimizedBVH(mesh1, geom1);\n        OptimizedClusterTree *bvh1_nl = CreateOptimizedBVH_Normals(mesh1, geom1);\n        OptimizedClusterTree *bvh1_pr = CreateOptimizedBVH_Projectors(mesh1, geom1);\n        toc(\"Create bvh1\");\n        tic(\"Create bvh2\");\n        OptimizedClusterTree *bvh2 = CreateOptimizedBVH(mesh2, geom2);\n        OptimizedClusterTree *bvh2_nl = CreateOptimizedBVH_Normals(mesh2, geom2);\n        OptimizedClusterTree *bvh2_pr = CreateOptimizedBVH_Projectors(mesh2, geom2);\n        toc(\"Create bvh2\");\n\n        tic(\"Create bct11\");\n        auto bct11 = std::make_shared<OptimizedBlockClusterTree>(bvh1, bvh1, alpha, beta, chi);\n        auto bct11_nl = std::make_shared<OptimizedBlockClusterTree>(bvh1_nl, bvh1_nl, alpha, beta, chi);\n        auto bct11_pr = std::make_shared<OptimizedBlockClusterTree>(bvh1_pr, bvh1_pr, alpha, beta, chi);\n        toc(\"Create bct11\");\n        tic(\"Create bct12\");\n        auto bct12 = std::make_shared<OptimizedBlockClusterTree>(bvh1, bvh2, alpha, beta, chi);\n        auto bct12_nl = std::make_shared<OptimizedBlockClusterTree>(bvh1_nl, bvh2_nl, alpha, beta, chi);\n        auto bct12_pr = std::make_shared<OptimizedBlockClusterTree>(bvh1_pr, bvh2_pr, alpha, beta, chi);\n        toc(\"Create bct12\");\n\n        // The transpose of bct12 and thus not needed.\n        //auto bct21 = std::make_shared<OptimizedBlockClusterTree>(bvh2, bvh1, alpha, beta, theta);\n        tic(\"Create bct22\");\n        auto bct22 = std::make_shared<OptimizedBlockClusterTree>(bvh2, bvh2, alpha, beta, chi);\n        auto bct22_nl = std::make_shared<OptimizedBlockClusterTree>(bvh2_nl, bvh2_nl, alpha, beta, chi);\n        auto bct22_pr = std::make_shared<OptimizedBlockClusterTree>(bvh2_pr, bvh2_pr, alpha, beta, chi);\n        toc(\"Create bct22\");\n\n        bct11->PrintStats();\n        bct12->PrintStats();\n        bct22->PrintStats();\n\n        // The joint bct of the union of mesh1 and mesh2 can be written in block matrix for as\n        //  bct = {\n        //            { bct11, bct12 },\n        //            { bct21, bct22 }\n        //        },\n        // where bct11 and bct22 are the instances of OptimizedBlockClusterTree of mesh1 and mesh2, respectively, bct12 is cross interaction OptimizedBlockClusterTree of mesh1 and mesh2, and bct21 is the transpose of bct12.\n        // However, the according matrix (on the space of dofs on the primitives) would be\n        //  A   = {\n        //            { A11 + diag( A12 * one2 ) , A12                      },\n        //            { A21                      , A22 + diag( A21 * one1 ) }\n        //        },\n        // where one1 and one2 are all-1-vectors on the primitives of mesh1 and mesh2, respectively.\n        // OptimizedBlockClusterTree::AddObstacleCorrection is supposed to compute diag( A12 * one2 ) and to add it to the diagonal of A11.\n        // Afterwards, bct1->Multiply will also multiply with the metric contribution of the obstacle.\n        tic(\"Modifying bct11 to include the terms with respect to the obstacle.\");\n        bct11->AddObstacleCorrection(bct12.get());\n        bct11_nl->AddObstacleCorrection(bct12_nl.get());\n        bct11_pr->AddObstacleCorrection(bct12_pr.get());\n        toc(\"Modifying bct11 to include the terms with respect to the obstacle.\");\n\n        mint energy_count = 7;\n\n        // the self-interaction energy of mesh1\n        auto tpe_fm_11 = std::make_shared<TPEnergyMultipole0>(mesh1, geom1, bct11.get(), alpha, beta, weight);\n        auto tpe_fm_nl_11 = std::make_shared<TPEnergyMultipole_Normals0>(mesh1, geom1, bct11_nl.get(), alpha, beta, weight);\n        auto tpe_fm_pr_11 = std::make_shared<TPEnergyMultipole_Projectors0>(mesh1, geom1, bct11_pr.get(), alpha, beta, weight);\n        auto tpe_bh_11 = std::make_shared<TPEnergyBarnesHut0>(mesh1, geom1, alpha, beta, theta, weight);\n        auto tpe_bh_pr_11 = std::make_shared<TPEnergyBarnesHut_Projectors0>(mesh1, geom1, alpha, beta, theta, weight);\n        auto tpe_ex_11 = std::make_shared<TPEnergyAllPairs>(mesh1, geom1, alpha, beta, weight);\n        auto tpe_ex_pr_11 = std::make_shared<TPEnergyAllPairs_Projectors>(mesh1, geom1, alpha, beta, weight);\n\n        // the interaction energy between mesh1 and mesh2\n        auto tpe_fm_12 = std::make_shared<TPObstacleMultipole0>(mesh1, geom1, bct12.get(), alpha, beta, weight);\n        auto tpe_fm_nl_12 = std::make_shared<TPObstacleMultipole_Normals0>(mesh1, geom1, bct12_nl.get(), alpha, beta, weight);\n        auto tpe_fm_pr_12 = std::make_shared<TPObstacleMultipole_Projectors0>(mesh1, geom1, bct12_pr.get(), alpha, beta, weight);\n        auto tpe_bh_12 = std::make_shared<TPObstacleBarnesHut0>(mesh1, geom1, tpe_bh_11.get(), mesh2, geom2, alpha, beta, theta, weight);\n        auto tpe_bh_pr_12 = std::make_shared<TPObstacleBarnesHut_Projectors0>(mesh1, geom1, tpe_bh_pr_11.get(), mesh2, geom2, alpha, beta, theta, weight);\n        auto tpe_ex_12 = std::make_shared<TPObstacleAllPairs>(mesh1, geom1, tpe_bh_11.get(), mesh2, geom2, alpha, beta, weight);\n        auto tpe_ex_pr_12 = std::make_shared<TPObstacleAllPairs_Projectors>(mesh1, geom1, tpe_bh_pr_11.get(), mesh2, geom2, alpha, beta, weight);\n\n        // the self-interaction energy of mesh2; since mesh2 is the obstacle here, this is not needed in practice; I used this here only for test purposes and in order to see how much \"work\" is saved by this approach.\n        auto tpe_fm_22 = std::make_shared<TPEnergyMultipole0>(mesh2, geom2, bct22.get(), alpha, beta, weight);\n        auto tpe_fm_nl_22 = std::make_shared<TPEnergyMultipole_Normals0>(mesh2, geom2, bct22_nl.get(), alpha, beta, weight);\n        auto tpe_fm_pr_22 = std::make_shared<TPEnergyMultipole_Projectors0>(mesh2, geom2, bct22_pr.get(), alpha, beta, weight);\n        auto tpe_bh_22 = std::make_shared<TPEnergyBarnesHut0>(mesh2, geom2, alpha, beta, theta, weight);\n        auto tpe_bh_pr_22 = std::make_shared<TPEnergyBarnesHut_Projectors0>(mesh2, geom2, alpha, beta, theta, weight);\n        auto tpe_ex_22 = std::make_shared<TPEnergyAllPairs>(mesh2, geom2, alpha, beta, weight);\n        auto tpe_ex_pr_22 = std::make_shared<TPEnergyAllPairs_Projectors>(mesh2, geom2, alpha, beta, weight);\n\n        // the energies tpe_**_11, tpe_**_12, tpe_**_22 are gauged such that their sum equals the tangent-point energy of the union of mesh1 and mesh2.\n\n        double E_fm_11, E_fm_12, E_fm_22;\n        double E_fm_nl_11, E_fm_nl_12, E_fm_nl_22;\n        double E_fm_pr_11, E_fm_pr_12, E_fm_pr_22;\n        double E_bh_11, E_bh_12, E_bh_22;\n        double E_bh_pr_11, E_bh_pr_12, E_bh_pr_22;\n        double E_ex_11, E_ex_12, E_ex_22;\n        double E_ex_pr_11, E_ex_pr_12, E_ex_pr_22;\n\n        Eigen::MatrixXd DE_fm_11(primitive_count1, 3);\n        Eigen::MatrixXd DE_fm_12(primitive_count1, 3);\n        Eigen::MatrixXd DE_fm_22(primitive_count2, 3);\n\n        Eigen::MatrixXd DE_fm_nl_11(primitive_count1, 3);\n        Eigen::MatrixXd DE_fm_nl_12(primitive_count1, 3);\n        Eigen::MatrixXd DE_fm_nl_22(primitive_count2, 3);\n\n        Eigen::MatrixXd DE_fm_pr_11(primitive_count1, 3);\n        Eigen::MatrixXd DE_fm_pr_12(primitive_count1, 3);\n        Eigen::MatrixXd DE_fm_pr_22(primitive_count2, 3);\n\n        Eigen::MatrixXd DE_bh_11(primitive_count1, 3);\n        Eigen::MatrixXd DE_bh_12(primitive_count1, 3);\n        Eigen::MatrixXd DE_bh_22(primitive_count2, 3);\n\n        Eigen::MatrixXd DE_bh_pr_11(primitive_count1, 3);\n        Eigen::MatrixXd DE_bh_pr_12(primitive_count1, 3);\n        Eigen::MatrixXd DE_bh_pr_22(primitive_count2, 3);\n\n        Eigen::MatrixXd DE_ex_11(primitive_count1, 3);\n        Eigen::MatrixXd DE_ex_12(primitive_count1, 3);\n        Eigen::MatrixXd DE_ex_22(primitive_count2, 3);\n\n        Eigen::MatrixXd DE_ex_pr_11(primitive_count1, 3);\n        Eigen::MatrixXd DE_ex_pr_12(primitive_count1, 3);\n        Eigen::MatrixXd DE_ex_pr_22(primitive_count2, 3);\n\n        std::cout << \"Using integer exponents.\" << std::endl;\n\n        mint counter = 0;\n        mint count = energy_count * 6;\n        tic();\n        E_ex_11 = tpe_ex_11->Value();\n        mreal t_ex_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        E_ex_12 = tpe_ex_12->Value();\n        mreal t_ex_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        E_ex_22 = tpe_ex_22->Value();\n        mreal t_ex_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_ex_11.setZero();\n        tpe_ex_11->Differential(DE_ex_11);\n        mreal Dt_ex_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_ex_12.setZero();\n        tpe_ex_12->Differential(DE_ex_12);\n        mreal Dt_ex_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_ex_22.setZero();\n        tpe_ex_22->Differential(DE_ex_22);\n        mreal Dt_ex_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        //######################################\n\n        tic();\n        E_ex_pr_11 = tpe_ex_pr_11->Value();\n        mreal t_ex_pr_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        //        tpe_ex_pr_12->Update();\n        E_ex_pr_12 = tpe_ex_pr_12->Value();\n        mreal t_ex_pr_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        E_ex_pr_22 = tpe_ex_pr_22->Value();\n        mreal t_ex_pr_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_ex_pr_11.setZero();\n        tpe_ex_pr_11->Differential(DE_ex_pr_11);\n        mreal Dt_ex_pr_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_ex_pr_12.setZero();\n        tpe_ex_pr_12->Differential(DE_ex_pr_12);\n        mreal Dt_ex_pr_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_ex_pr_22.setZero();\n        tpe_ex_pr_22->Differential(DE_ex_pr_22);\n        mreal Dt_ex_pr_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        //######################################\n\n        tic();\n        E_bh_11 = tpe_bh_11->Value();\n        mreal t_bh_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        //        tpe_bh_12->Update();\n        E_bh_12 = tpe_bh_12->Value();\n        mreal t_bh_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        E_bh_22 = tpe_bh_22->Value();\n        mreal t_bh_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_bh_11.setZero();\n        tpe_bh_11->Differential(DE_bh_11);\n        mreal Dt_bh_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_bh_12.setZero();\n        tpe_bh_12->Differential(DE_bh_12);\n        mreal Dt_bh_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_bh_22.setZero();\n        tpe_bh_22->Differential(DE_bh_22);\n        mreal Dt_bh_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        //######################################\n\n        tic();\n        E_bh_pr_11 = tpe_bh_pr_11->Value();\n        mreal t_bh_pr_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        //        tpe_bh_12->Update();\n        E_bh_pr_12 = tpe_bh_pr_12->Value();\n        mreal t_bh_pr_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        E_bh_pr_22 = tpe_bh_pr_22->Value();\n        mreal t_bh_pr_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_bh_pr_11.setZero();\n        tpe_bh_pr_11->Differential(DE_bh_pr_11);\n        mreal Dt_bh_pr_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_bh_pr_12.setZero();\n        tpe_bh_pr_12->Differential(DE_bh_pr_12);\n        mreal Dt_bh_pr_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_bh_pr_22.setZero();\n        tpe_bh_pr_22->Differential(DE_bh_pr_22);\n        mreal Dt_bh_pr_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        //######################################\n\n        tic();\n        E_fm_nl_11 = tpe_fm_nl_11->Value();\n        mreal t_fm_nl_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        E_fm_nl_12 = tpe_fm_nl_12->Value();\n        mreal t_fm_nl_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        E_fm_nl_22 = tpe_fm_nl_22->Value();\n        mreal t_fm_nl_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_fm_nl_11.setZero();\n        tpe_fm_nl_11->Differential(DE_fm_nl_11);\n        mreal Dt_fm_nl_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_fm_nl_12.setZero();\n        tpe_fm_nl_12->Differential(DE_fm_nl_12);\n        mreal Dt_fm_nl_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_fm_nl_22.setZero();\n        tpe_fm_nl_22->Differential(DE_fm_nl_22);\n        mreal Dt_fm_nl_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        //######################################\n\n        tic();\n        E_fm_11 = tpe_fm_11->Value();\n        mreal t_fm_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        E_fm_12 = tpe_fm_12->Value();\n        mreal t_fm_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        E_fm_22 = tpe_fm_22->Value();\n        mreal t_fm_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_fm_11.setZero();\n        tpe_fm_11->Differential(DE_fm_11);\n        mreal Dt_fm_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_fm_12.setZero();\n        tpe_fm_12->Differential(DE_fm_12);\n        mreal Dt_fm_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_fm_22.setZero();\n        tpe_fm_22->Differential(DE_fm_22);\n        mreal Dt_fm_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        //######################################\n        tic();\n        E_fm_pr_11 = tpe_fm_pr_11->Value();\n        mreal t_fm_pr_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        E_fm_pr_12 = tpe_fm_pr_12->Value();\n        mreal t_fm_pr_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        E_fm_pr_22 = tpe_fm_pr_22->Value();\n        mreal t_fm_pr_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_fm_pr_11.setZero();\n        tpe_fm_pr_11->Differential(DE_fm_pr_11);\n        mreal Dt_fm_pr_11 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_fm_pr_12.setZero();\n        tpe_fm_pr_12->Differential(DE_fm_pr_12);\n        mreal Dt_fm_pr_12 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        tic();\n        DE_fm_pr_22.setZero();\n        tpe_fm_pr_22->Differential(DE_fm_pr_22);\n        mreal Dt_fm_pr_22 = toc();\n        std::cout << \"done \" << ++counter << \" / \" << count << std::endl;\n\n        //######################################\n\n        int w1 = 21;\n        int w = 13;\n        //\n        //        std::string line = \"--------------------------------------------------------------------------------------------------------------------------------------------------------------------\";\n        std::string line = std::string(3 * energy_count + w1 + w * energy_count, '-');\n        std::cout << std::left;\n        std::cout << std::setw(w1) << \"\"\n                  << \" | \" << std::setw(w) << \"exact\"\n                  << \" | \" << std::setw(w) << \"pr\"\n                  << \" | \" << std::setw(w) << \"BH\"\n                  << \" | \" << std::setw(w) << \"BH_pr\"\n                  << \" | \" << std::setw(w) << \"FMM\"\n                  << \" | \" << std::setw(w) << \"FMM_pr\"\n                  << \" | \" << std::setw(w) << \"FMM_nl\"\n                  << std::endl;\n\n        std::cout << line << std::endl;\n\n        std::cout << std::setw(w1) << \"  E_11 \"\n                  << \" | \" << std::setw(w) << E_ex_11\n                  << \" | \" << std::setw(w) << E_ex_pr_11\n                  << \" | \" << std::setw(w) << E_bh_11\n                  << \" | \" << std::setw(w) << E_bh_pr_11\n                  << \" | \" << std::setw(w) << E_fm_11\n                  << \" | \" << std::setw(w) << E_fm_pr_11\n                  << \" | \" << std::setw(w) << E_fm_nl_11\n                  << std::endl;\n\n        std::cout << std::setw(w1) << \"  E_12 \"\n                  << \" | \" << std::setw(w) << E_ex_12\n                  << \" | \" << std::setw(w) << E_ex_pr_12\n                  << \" | \" << std::setw(w) << E_bh_12\n                  << \" | \" << std::setw(w) << E_bh_pr_12\n                  << \" | \" << std::setw(w) << E_fm_12\n                  << \" | \" << std::setw(w) << E_fm_pr_12\n                  << \" | \" << std::setw(w) << E_fm_nl_12\n                  << std::endl;\n\n        std::cout << std::setw(w1) << \"  E_22 \"\n                  << \" | \" << std::setw(w) << E_ex_22\n                  << \" | \" << std::setw(w) << E_ex_pr_22\n                  << \" | \" << std::setw(w) << E_bh_22\n                  << \" | \" << std::setw(w) << E_bh_pr_22\n                  << \" | \" << std::setw(w) << E_fm_22\n                  << \" | \" << std::setw(w) << E_fm_pr_22\n                  << \" | \" << std::setw(w) << E_fm_nl_22\n                  << std::endl;\n\n        std::cout << \"\\n\";\n        std::cout << std::setw(w1) << \"\"\n                  << \" | \" << std::setw(w) << \"exact\"\n                  << \" | \" << std::setw(w) << \"pr\"\n                  << \" | \" << std::setw(w) << \"BH\"\n                  << \" | \" << std::setw(w) << \"BH_pr\"\n                  << \" | \" << std::setw(w) << \"FMM\"\n                  << \" | \" << std::setw(w) << \"FMM_pr\"\n                  << \" | \" << std::setw(w) << \"FMM_nl\"\n                  << std::endl;\n\n        std::cout << line << std::endl;\n\n        std::cout << std::setw(w1) << \"  E_11 error (%) \"\n                  << \" | \" << std::setw(w) << fabs(E_ex_11 / E_ex_11 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_ex_pr_11 / E_ex_11 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_bh_11 / E_ex_11 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_bh_pr_11 / E_ex_11 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_fm_11 / E_ex_11 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_fm_pr_11 / E_ex_11 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_fm_nl_11 / E_ex_11 - 1) * 100\n                  << std::endl;\n\n        std::cout << std::setw(w1) << \"  E_12 error (%) \"\n                  << \" | \" << std::setw(w) << fabs(E_ex_12 / E_ex_12 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_ex_pr_12 / E_ex_12 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_bh_12 / E_ex_12 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_bh_pr_12 / E_ex_12 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_fm_12 / E_ex_12 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_fm_pr_12 / E_ex_12 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_fm_nl_12 / E_ex_12 - 1) * 100\n                  << std::endl;\n\n        std::cout << std::setw(w1) << \"  E_22 error (%) \"\n                  << \" | \" << std::setw(w) << fabs(E_ex_22 / E_ex_22 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_ex_pr_22 / E_ex_22 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_bh_22 / E_ex_22 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_bh_pr_22 / E_ex_22 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_fm_22 / E_ex_22 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_fm_pr_22 / E_ex_22 - 1) * 100\n                  << \" | \" << std::setw(w) << fabs(E_fm_nl_22 / E_ex_22 - 1) * 100\n                  << std::endl;\n\n        std::cout << std::setw(w1) << \" DE_11 error (%) \"\n                  << \" | \" << std::setw(w) << (DE_ex_11 - DE_ex_11).norm() / DE_ex_11.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_ex_pr_11 - DE_ex_11).norm() / DE_ex_11.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_bh_11 - DE_ex_11).norm() / DE_ex_11.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_bh_pr_11 - DE_ex_11).norm() / DE_ex_11.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_fm_11 - DE_ex_11).norm() / DE_ex_11.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_fm_pr_11 - DE_ex_11).norm() / DE_ex_11.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_fm_nl_11 - DE_ex_11).norm() / DE_ex_11.norm() * 100\n                  << std::endl;\n\n        std::cout << std::setw(w1) << \" DE_12 error (%) \"\n                  << \" | \" << std::setw(w) << (DE_ex_12 - DE_ex_12).norm() / DE_ex_12.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_ex_pr_12 - DE_ex_12).norm() / DE_ex_12.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_bh_12 - DE_ex_12).norm() / DE_ex_12.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_bh_pr_12 - DE_ex_12).norm() / DE_ex_12.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_fm_12 - DE_ex_12).norm() / DE_ex_12.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_fm_pr_12 - DE_ex_12).norm() / DE_ex_12.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_fm_nl_12 - DE_ex_12).norm() / DE_ex_12.norm() * 100\n                  << std::endl;\n\n        std::cout << std::setw(w1) << \" DE_22 error (%) \"\n                  << \" | \" << std::setw(w) << (DE_ex_22 - DE_ex_22).norm() / DE_ex_22.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_ex_pr_22 - DE_ex_22).norm() / DE_ex_22.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_bh_22 - DE_ex_22).norm() / DE_ex_22.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_bh_pr_22 - DE_ex_22).norm() / DE_ex_22.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_fm_22 - DE_ex_22).norm() / DE_ex_22.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_fm_pr_22 - DE_ex_22).norm() / DE_ex_22.norm() * 100\n                  << \" | \" << std::setw(w) << (DE_fm_nl_22 - DE_ex_22).norm() / DE_ex_22.norm() * 100\n                  << std::endl;\n\n        std::cout << \"\\n\"\n                  << std::endl;\n        std::cout << std::setw(w1) << \"\"\n                  << \" | \" << std::setw(w) << \"exact\"\n                  << \" | \" << std::setw(w) << \"pr\"\n                  << \" | \" << std::setw(w) << \"BH\"\n                  << \" | \" << std::setw(w) << \"BH_pr\"\n                  << \" | \" << std::setw(w) << \"FMM\"\n                  << \" | \" << std::setw(w) << \"FMM_pr\"\n                  << \" | \" << std::setw(w) << \"FMM_nl\"\n                  << std::endl;\n\n        std::cout << line << std::endl;\n\n        std::cout << std::setw(w1) << \"  E_11 time  (s) \"\n                  << \" | \" << std::setw(w) << t_ex_11\n                  << \" | \" << std::setw(w) << t_ex_pr_11\n                  << \" | \" << std::setw(w) << t_bh_11\n                  << \" | \" << std::setw(w) << t_bh_pr_11\n                  << \" | \" << std::setw(w) << t_fm_11\n                  << \" | \" << std::setw(w) << t_fm_pr_11\n                  << \" | \" << std::setw(w) << t_fm_nl_11\n                  << std::endl;\n\n        std::cout << std::setw(w1) << \"  E_12 time  (s) \"\n                  << \" | \" << std::setw(w) << t_ex_12\n                  << \" | \" << std::setw(w) << t_ex_pr_12\n                  << \" | \" << std::setw(w) << t_bh_12\n                  << \" | \" << std::setw(w) << t_bh_pr_12\n                  << \" | \" << std::setw(w) << t_fm_12\n                  << \" | \" << std::setw(w) << t_fm_pr_12\n                  << \" | \" << std::setw(w) << t_fm_nl_12\n                  << std::endl;\n\n        std::cout << std::setw(w1) << \"  E_22 time  (s) \"\n                  << \" | \" << std::setw(w) << t_ex_22\n                  << \" | \" << std::setw(w) << t_ex_pr_22\n                  << \" | \" << std::setw(w) << t_bh_22\n                  << \" | \" << std::setw(w) << t_bh_pr_22\n                  << \" | \" << std::setw(w) << t_fm_22\n                  << \" | \" << std::setw(w) << t_fm_pr_22\n                  << \" | \" << std::setw(w) << t_fm_nl_22\n                  << std::endl;\n\n        std::cout << std::setw(w1) << \" DE_11 time  (s) \"\n                  << \" | \" << std::setw(w) << Dt_ex_11\n                  << \" | \" << std::setw(w) << Dt_ex_pr_11\n                  << \" | \" << std::setw(w) << Dt_bh_11\n                  << \" | \" << std::setw(w) << Dt_bh_pr_11\n                  << \" | \" << std::setw(w) << Dt_fm_11\n                  << \" | \" << std::setw(w) << Dt_fm_pr_11\n                  << \" | \" << std::setw(w) << Dt_fm_nl_11\n                  << std::endl;\n\n        std::cout << std::setw(w1) << \" DE_12 time  (s) \"\n                  << \" | \" << std::setw(w) << Dt_ex_12\n                  << \" | \" << std::setw(w) << Dt_ex_pr_12\n                  << \" | \" << std::setw(w) << Dt_bh_12\n                  << \" | \" << std::setw(w) << Dt_bh_pr_12\n                  << \" | \" << std::setw(w) << Dt_fm_12\n                  << \" | \" << std::setw(w) << Dt_fm_pr_12\n                  << \" | \" << std::setw(w) << Dt_fm_nl_12\n                  << std::endl;\n\n        std::cout << std::setw(w1) << \" DE_22 time  (s) \"\n                  << \" | \" << std::setw(w) << Dt_ex_22\n                  << \" | \" << std::setw(w) << Dt_ex_pr_22\n                  << \" | \" << std::setw(w) << Dt_bh_22\n                  << \" | \" << std::setw(w) << Dt_bh_pr_22\n                  << \" | \" << std::setw(w) << Dt_fm_22\n                  << \" | \" << std::setw(w) << Dt_fm_pr_22\n                  << \" | \" << std::setw(w) << Dt_fm_nl_22\n                  << std::endl;\n\n        delete bvh1;\n\n        //        std::ofstream file;\n        //        file.open(\"./Profile.tsv\");\n        //        WriteProfile(file);\n        //        file.close();\n\n    } // TestObstacle0\n\n    void MainApp::TestBarnesHut0()\n    {\n        std::cout << std::setprecision(16);\n        std::cout << \"\\n  =====                        =====  \" << std::endl;\n        std::cout << \"=======   TPEnergyBarnesHut0   =======\" << std::endl;\n        std::cout << \"  =====                        =====  \" << std::endl;\n        std::cout << \"\\n\"\n                  << std::endl;\n        auto mesh = rsurfaces::MainApp::instance->mesh;\n        auto geom = rsurfaces::MainApp::instance->geom;\n\n        mreal alpha = 6.;\n        mreal beta = 12.;\n        mreal theta = 0.25;\n\n        //        tic(\"Create BVH\");\n        //        OptimizedClusterTree* bvh = CreateOptimizedBVH( mesh, geom );\n        //        tic(\"Create BVH\");\n\n        double E, Ex;\n        Eigen::MatrixXd DE(mesh->nVertices(), 3);\n        Eigen::MatrixXd DEx(mesh->nVertices(), 3);\n\n        auto tpe = std::make_shared<TPEnergyBarnesHut0>(mesh, geom, alpha, beta, theta);\n        auto tpex = std::make_shared<TPEnergyAllPairs>(mesh, geom, alpha, beta);\n\n        tpe->use_int = false;\n        std::cout << \"Using double exponents.\" << std::endl;\n\n        tic(\"Compute Value\");\n        tpe->Update();\n        E = tpe->Value();\n        toc(\"Compute Value\");\n        std::cout << \"  E = \" << E << std::endl;\n        tic(\"Compute Differential\");\n        DE.setZero();\n        tpe->Differential(DE);\n        toc(\"Compute Differential\");\n\n        std::cout << \"  DE = \" << DE(0, 0) << \" , \" << DE(0, 1) << \" , \" << DE(0, 2) << std::endl;\n        std::cout << \"       \" << DE(1, 0) << \" , \" << DE(1, 1) << \" , \" << DE(1, 2) << std::endl;\n        std::cout << \"       \" << DE(2, 0) << \" , \" << DE(2, 1) << \" , \" << DE(2, 2) << std::endl;\n        std::cout << \"       \" << DE(3, 0) << \" , \" << DE(3, 1) << \" , \" << DE(3, 2) << std::endl;\n        std::cout << \"       \" << DE(4, 0) << \" , \" << DE(4, 1) << \" , \" << DE(4, 2) << std::endl;\n\n        tpe->use_int = true;\n        std::cout << \"Using integer exponents.\" << std::endl;\n\n        tic(\"Compute Value\");\n        tpe->Update();\n        E = tpe->Value();\n        toc(\"Compute Value\");\n        std::cout << \"  E = \" << E << std::endl;\n        tic(\"Compute Differential\");\n        DE.setZero();\n        tpe->Differential(DE);\n        toc(\"Compute Differential\");\n\n        std::cout << \"  DE = \" << DE(0, 0) << \" , \" << DE(0, 1) << \" , \" << DE(0, 2) << std::endl;\n        std::cout << \"       \" << DE(1, 0) << \" , \" << DE(1, 1) << \" , \" << DE(1, 2) << std::endl;\n        std::cout << \"       \" << DE(2, 0) << \" , \" << DE(2, 1) << \" , \" << DE(2, 2) << std::endl;\n        std::cout << \"       \" << DE(3, 0) << \" , \" << DE(3, 1) << \" , \" << DE(3, 2) << std::endl;\n        std::cout << \"       \" << DE(4, 0) << \" , \" << DE(4, 1) << \" , \" << DE(4, 2) << std::endl;\n\n        tic(\"Compute Value (all pairs)\");\n        tpex->Update();\n        Ex = tpex->Value();\n        toc(\"Compute Value (all pairs)\");\n        std::cout << \"  Ex = \" << Ex << std::endl;\n        tic(\"Compute Differential (all pairs)\");\n        DEx.setZero();\n        tpex->Differential(DEx);\n        toc(\"Compute Differential (all pairs)\");\n\n        std::cout << \"Energy value = \" << E << std::endl;\n        std::cout << \"Diff. norm   = \" << DE.norm() << std::endl;\n\n        std::cout << \"Exact energy value = \" << Ex << std::endl;\n        std::cout << \"Exact diff. value  = \" << DEx.norm() << std::endl;\n\n        double energyError = fabs(E - Ex) / Ex * 100;\n        double diffError = (DE - DEx).norm() / DEx.norm() * 100;\n\n        std::cout << \"Energy relative error = \" << energyError << \" percent\" << std::endl;\n        std::cout << \"Diff. relative error  = \" << diffError << \" percent\" << std::endl;\n\n        SurfaceEnergy *oldBH = flow->BaseEnergy();\n        Eigen::MatrixXd oldDiff(mesh->nVertices(), 3);\n\n        oldDiff.setZero();\n        oldBH->Update();\n        double oldE = oldBH->Value();\n        oldBH->Differential(oldDiff);\n\n        std::cout << \"Old BH energy value = \" << oldE << std::endl;\n        std::cout << \"Old BH diff. value  = \" << oldDiff.norm() << std::endl;\n\n        double oldEnergyError = fabs(oldE - Ex) / Ex * 100;\n        double oldDiffError = (oldDiff - DEx).norm() / DEx.norm() * 100;\n\n        std::cout << \"Energy relative error = \" << oldEnergyError << \" percent\" << std::endl;\n        std::cout << \"Diff. relative error  = \" << oldDiffError << \" percent\" << std::endl;\n\n        std::cout << \"\\n --- Derivative test --- \" << std::endl;\n\n        mreal Et;\n        Eigen::MatrixXd x(mesh->nVertices(), 3);\n        Eigen::MatrixXd xnew(mesh->nVertices(), 3);\n\n        VertexIndices inds = mesh->getVertexIndices();\n        for (GCVertex v : mesh->vertices())\n        {\n            size_t i = inds[v];\n            x(i, 0) = geom->inputVertexPositions[v].x;\n            x(i, 1) = geom->inputVertexPositions[v].y;\n            x(i, 2) = geom->inputVertexPositions[v].z;\n        }\n\n        Eigen::MatrixXd u = Eigen::MatrixXd::Random(mesh->nVertices(), 3);\n\n        mreal t = 1.;\n        for (int k = 0; k < 8; ++k)\n        {\n            t *= 0.1;\n            xnew = x + t * u;\n            VertexIndices inds = mesh->getVertexIndices();\n            for (GCVertex v : mesh->vertices())\n            {\n                size_t i = inds[v];\n                Vector3 corr{xnew(i, 0), xnew(i, 1), xnew(i, 2)};\n                geom->inputVertexPositions[v] = corr;\n            }\n\n            geom->refreshQuantities();\n\n            //            UpdateOptimizedBVH(mesh, geom, tpe->GetBVH());\n            tpe->Update();\n            Et = tpe->Value();\n            //            std::cout << \"Et - E             = \" << Et - E << std::endl;\n            //            std::cout << \"        t * DE * u = \" << t * (DE.transpose() * u).trace() << std::endl;\n            std::cout << \"Et - E -t * DE * u = \" << Et - E - t * (DE.transpose() * u).trace() << std::endl;\n        }\n\n    } // TestBarnesHut0\n\n    void MainApp::TestWillmore()\n    {\n\n        std::cout << \"\\n=====   WillmoreEnergy   =====\" << std::endl;\n\n        std::cout << std::setprecision(16);\n\n        auto mesh = rsurfaces::MainApp::instance->mesh;\n        auto geom = rsurfaces::MainApp::instance->geom;\n\n        VertexIndices vInds = mesh->getVertexIndices();\n\n        SurfaceEnergy *willmore = new WillmoreEnergy(mesh, geom);\n\n        tic(\"Value\");\n        double E = willmore->Value();\n        toc(\"Value\");\n\n        std::cout << \"  E = \" << E << std::endl;\n\n        Eigen::MatrixXd DE(mesh->nVertices(), 3);\n\n        tic(\"Differential\");\n        willmore->Differential(DE);\n        toc(\"Differential\");\n\n        std::cout << \"  DE = \" << DE(0, 0) << \" , \" << DE(0, 1) << \" , \" << DE(0, 2) << std::endl;\n        std::cout << \"       \" << DE(1, 0) << \" , \" << DE(1, 1) << \" , \" << DE(1, 2) << std::endl;\n        std::cout << \"       \" << DE(2, 0) << \" , \" << DE(2, 1) << \" , \" << DE(2, 2) << std::endl;\n        std::cout << \"       \" << DE(3, 0) << \" , \" << DE(3, 1) << \" , \" << DE(3, 2) << std::endl;\n        std::cout << \"       \" << DE(4, 0) << \" , \" << DE(4, 1) << \" , \" << DE(4, 2) << std::endl;\n\n        delete willmore;\n    } // TestWillmore\n\n    class VectorInit\n    {\n    public:\n        static void Init(Vector3 &data, BVHNode6D *node)\n        {\n            data = Vector3{1, 2, 3};\n        }\n    };\n\n    void MainApp::AddObstacle(std::string filename, double weight, bool recenter, bool asPointCloud)\n    {\n        std::unique_ptr<surface::SurfaceMesh> obstacleMesh;\n        GeomUPtr obstacleGeometry;\n        // Load mesh\n        std::tie(obstacleMesh, obstacleGeometry) = readNonManifoldMesh(filename);\n\n        obstacleGeometry->requireVertexDualAreas();\n        obstacleGeometry->requireVertexNormals();\n\n        if (recenter)\n        {\n            Vector3 obstacleCenter = meshBarycenter(obstacleGeometry, obstacleMesh);\n            std::cout << \"Recentering obstacle \" << filename << \" (offset \" << obstacleCenter << \")\" << std::endl;\n            for (GCVertex v : obstacleMesh->vertices())\n            {\n                obstacleGeometry->inputVertexPositions[v] = obstacleGeometry->inputVertexPositions[v] - obstacleCenter;\n            }\n        }\n\n        std::string mesh_name = polyscope::guessNiceNameFromPath(filename);\n\n        if (asPointCloud)\n        {\n            polyscope::PointCloud *pointCloud = polyscope::registerPointCloud(mesh_name, obstacleGeometry->inputVertexPositions);\n        }\n\n        else\n        {\n            polyscope::SurfaceMesh *psMesh = polyscope::registerSurfaceMesh(mesh_name, obstacleGeometry->inputVertexPositions,\n                                                                            obstacleMesh->getFaceVertexList(), polyscopePermutations(*obstacleMesh));\n        }\n\n        std::unique_ptr<surface::SurfaceMesh> sharedObsMesh = std::move(obstacleMesh);\n        GeomPtr sharedObsGeom = std::move(obstacleGeometry);\n\n        SurfaceEnergy *obstacleEnergy = 0;\n\n        if (asPointCloud)\n        {\n            size_t nVerts = sharedObsMesh->nVertices();\n\n            Eigen::VectorXd wts;\n            wts.setOnes(nVerts);\n\n            Eigen::MatrixXd pos;\n            pos.setZero(nVerts, 3);\n\n            for (size_t i = 0; i < nVerts; i++)\n            {\n                Vector3 v = sharedObsGeom->inputVertexPositions[i];\n                MatrixUtils::SetRowFromVector3(pos, i, v);\n            }\n\n            obstacleEnergy = new TPPointCloudObstacleBarnesHut0(mesh, geom, flow->BaseEnergy(), wts, pos,\n                                                                kernel->alpha, kernel->beta, bh_theta, weight);\n        }\n\n        else\n        {\n            obstacleEnergy = new TPObstacleBarnesHut0(mesh, geom, flow->BaseEnergy(), sharedObsMesh, sharedObsGeom,\n                                                      kernel->alpha, kernel->beta, bh_theta, weight);\n        }\n\n        flow->AddObstacleEnergy(obstacleEnergy);\n        std::cout << \"Added \" << filename << \" as obstacle with weight \" << weight << std::endl;\n\n        totalObstacleVolume += totalVolume(sharedObsGeom, sharedObsMesh);\n    }\n\n    void MainApp::AddImplicitBarrier(scene::ImplicitBarrierData &barrierData)\n    {\n        ImplicitSurface *implSurface;\n        // Create the requested implicit surface\n        switch (barrierData.type)\n        {\n        case scene::ImplicitType::Plane:\n        {\n            Vector3 point{barrierData.parameters[0], barrierData.parameters[1], barrierData.parameters[2]};\n            Vector3 normal{barrierData.parameters[3], barrierData.parameters[4], barrierData.parameters[5]};\n            std::cout << \"Constructing implicit plane at point \" << point << \" with normal \" << normal << std::endl;\n            implSurface = new FlatPlane(point, normal);\n        }\n        break;\n        case scene::ImplicitType::Torus:\n        {\n            double major = barrierData.parameters[0];\n            double minor = barrierData.parameters[1];\n            Vector3 center{barrierData.parameters[2], barrierData.parameters[3], barrierData.parameters[4]};\n            std::cout << \"Constructing implicit torus with major radius \" << major << \", minor radius \" << minor << \", center \" << center << std::endl;\n            implSurface = new ImplicitTorus(major, minor, center);\n        }\n        break;\n        case scene::ImplicitType::Sphere:\n        {\n            double radius = barrierData.parameters[0];\n            Vector3 center{barrierData.parameters[1], barrierData.parameters[2], barrierData.parameters[3]};\n            std::cout << \"Constructing implicit sphere with radius \" << radius << \", center \" << center << std::endl;\n            implSurface = new ImplicitSphere(radius, center);\n        }\n        break;\n        case scene::ImplicitType::Cylinder:\n        {\n            double radius = barrierData.parameters[0];\n            Vector3 center{barrierData.parameters[1], barrierData.parameters[2], barrierData.parameters[3]};\n            Vector3 axis{barrierData.parameters[4], barrierData.parameters[5], barrierData.parameters[6]};\n            std::cout << \"Constructing implicit cylinder with radius \" << radius << \", center \" << center << \", axis \" << axis << std::endl;\n            implSurface = new ImplicitCylinder(radius, center, axis);\n        }\n        break;\n        default:\n        {\n            throw std::runtime_error(\"Unimplemented implicit surface type.\");\n        }\n        break;\n        }\n\n        // Mesh the 0 isosurface so we can see the implicit surface\n        MainApp::instance->MeshImplicitSurface(implSurface);\n\n        // Use the implicit surface to setup the energy\n        std::unique_ptr<ImplicitSurface> implUnique(implSurface);\n        if (barrierData.repel)\n        {\n            std::cout << \"Using implicit surface as obstacle, with power \" << barrierData.power << \" and weight \" << barrierData.weight << std::endl;\n            ImplicitObstacle *obstacle = new ImplicitObstacle(mesh, geom, std::move(implUnique), barrierData.power, barrierData.weight);\n            flow->AddAdditionalEnergy(obstacle);\n        }\n        else\n        {\n            std::cout << \"Using implicit surface as attractor, with power \" << barrierData.power << \" and weight \" << barrierData.weight << std::endl;\n            ImplicitAttractor *attractor = new ImplicitAttractor(mesh, geom, std::move(implUnique), uvs, barrierData.power, barrierData.weight);\n            flow->AddAdditionalEnergy(attractor);\n        }\n    }\n\n    void MainApp::AddPotential(scene::PotentialType pType, double weight, double targetValue)\n    {\n        switch (pType)\n        {\n        case scene::PotentialType::SquaredError:\n        {\n            SquaredError *errorPotential = new SquaredError(mesh, geom, weight);\n            vertexPotential = errorPotential;\n            flow->AddAdditionalEnergy(errorPotential);\n            remesher.KeepVertexDataUpdated(&errorPotential->originalPositions);\n            break;\n        }\n        case scene::PotentialType::Area:\n        {\n            TotalAreaPotential *areaPotential = new TotalAreaPotential(mesh, geom, weight);\n            flow->AddAdditionalEnergy(areaPotential);\n            break;\n        }\n        case scene::PotentialType::Volume:\n        {\n            TotalVolumePotential *volumePotential = new TotalVolumePotential(mesh, geom, weight);\n            flow->AddAdditionalEnergy(volumePotential);\n            break;\n        }\n        case scene::PotentialType::BoundaryLength:\n        {\n            BoundaryLengthPenalty *errorPotential = new BoundaryLengthPenalty(mesh, geom, weight, targetValue);\n            flow->AddAdditionalEnergy(errorPotential);\n            break;\n        }\n        case scene::PotentialType::BoundaryCurvature:\n        {\n            BoundaryCurvaturePenalty *errorPotential = new BoundaryCurvaturePenalty(mesh, geom, weight);\n            flow->AddAdditionalEnergy(errorPotential);\n            break;\n        }\n        case scene::PotentialType::SoftAreaConstraint:\n        {\n            SoftAreaConstraint *softArea = new SoftAreaConstraint(mesh, geom, weight);\n            flow->AddAdditionalEnergy(softArea);\n            break;\n        }\n        case scene::PotentialType::SoftVolumeConstraint:\n        {\n            SoftVolumeConstraint *softVol = new SoftVolumeConstraint(mesh, geom, weight);\n            flow->AddAdditionalEnergy(softVol);\n            break;\n        }\n        case scene::PotentialType::Willmore:\n        {\n            WillmoreEnergy *willmore = new WillmoreEnergy(mesh, geom, weight);\n            flow->AddAdditionalEnergy(willmore);\n            break;\n        }\n        default:\n        {\n            std::cout << \"Unknown potential type.\" << std::endl;\n            break;\n        }\n        }\n    }\n\n    void MainApp::MeshImplicitSurface(ImplicitSurface *surface)\n    {\n        CIsoSurface<double> *iso = new CIsoSurface<double>();\n\n        std::cout << \"Meshing the supplied implicit surface using marching cubes...\" << std::endl;\n\n        const int numCells = 50;\n        Vector3 center = surface->BoundingCenter();\n        double diameter = surface->BoundingDiameter();\n        double cellSize = diameter / numCells;\n        double radius = diameter / 2;\n\n        Vector3 lowerCorner = center - Vector3{radius, radius, radius};\n\n        int numCorners = numCells + 1;\n\n        double field[numCorners * numCorners * numCorners];\n\n        int nSlice = numCorners * numCorners;\n        int nRow = numCorners;\n\n        for (int x = 0; x < numCorners; x++)\n        {\n            for (int y = 0; y < numCorners; y++)\n            {\n                for (int z = 0; z < numCorners; z++)\n                {\n                    Vector3 samplePt = lowerCorner + Vector3{(double)x, (double)y, (double)z} * cellSize;\n                    double value = surface->SignedDistance(samplePt);\n                    field[nSlice * z + nRow * y + x] = value;\n                }\n            }\n        }\n\n        iso->GenerateSurface(field, 0, numCells, numCells, numCells, cellSize, cellSize, cellSize);\n\n        std::vector<glm::vec3> nodes;\n        std::vector<std::array<size_t, 3>> triangles;\n\n        int nVerts = iso->m_nVertices;\n\n        for (int i = 0; i < nVerts; i++)\n        {\n            double x = iso->m_ppt3dVertices[i][0];\n            double y = iso->m_ppt3dVertices[i][1];\n            double z = iso->m_ppt3dVertices[i][2];\n\n            Vector3 p = lowerCorner + Vector3{x, y, z};\n            nodes.push_back(glm::vec3{p.x, p.y, p.z});\n        }\n\n        int nTris = iso->m_nTriangles;\n\n        for (int i = 0; i < nTris; i++)\n        {\n            int i1 = iso->m_piTriangleIndices[3 * i];\n            int i2 = iso->m_piTriangleIndices[3 * i + 1];\n            int i3 = iso->m_piTriangleIndices[3 * i + 2];\n\n            triangles.push_back({(size_t)i1, (size_t)i2, (size_t)i3});\n        }\n\n        implicitCount++;\n        polyscope::registerSurfaceMesh(\"implicitSurface\" + std::to_string(implicitCount), nodes, triangles);\n        delete iso;\n    }\n} // namespace rsurfaces\n\n// UI parameters\nbool run = false;\nbool takeScreenshots = false;\nbool saveOBJs = false;\nbool skipEveryOther = false;\nuint screenshotNum = 0;\nuint objNum = 0;\nbool uiNormalizeView = false;\nbool remesh = true;\nbool changeTopo = false;\nbool areaRatios = false;\nbool limitStep = false;\nfloat maxStep = -1.;\n\nint partIndex = 4475;\n\nvoid saveScreenshot(uint i)\n{\n    char buffer[5];\n    std::snprintf(buffer, sizeof(buffer), \"%04d\", i);\n    std::string fname = \"frames/frame\" + std::string(buffer) + \".png\";\n    polyscope::screenshot(fname, false);\n    std::cout << \"Saved screenshot to \" << fname << std::endl;\n}\n\nvoid saveOBJ(rsurfaces::MeshPtr mesh, rsurfaces::GeomPtr geom, rsurfaces::GeomPtr geomOrig, uint i)\n{\n\n    char buffer[5];\n    std::snprintf(buffer, sizeof(buffer), \"%04d\", i);\n    std::string fname = \"objs/frame\" + std::string(buffer) + \".obj\";\n    rsurfaces::writeMeshToOBJ(mesh, geom, geomOrig, areaRatios, fname);\n    std::cout << \"Saved OBJ frame to \" << fname << std::endl;\n}\n\ntemplate <typename ItemType>\nvoid selectFromDropdown(std::string label, const ItemType choices[], size_t nChoices, ItemType &store)\n{\n    using namespace rsurfaces;\n\n    // Dropdown menu for list of remeshing mode settings\n    if (ImGui::BeginCombo(label.c_str(), StringOfMode(store).c_str()))\n    {\n        for (size_t i = 0; i < nChoices; i++)\n        {\n            bool is_selected = (store == choices[i]);\n            if (ImGui::Selectable(StringOfMode(choices[i]).c_str(), is_selected))\n                store = choices[i];\n            if (is_selected)\n                ImGui::SetItemDefaultFocus();\n        }\n        ImGui::EndCombo();\n    }\n}\n\n// A user-defined callback, for creating control panels (etc)\n// Use ImGUI commands to build whatever you want here, see\n// https://github.com/ocornut/imgui/blob/master/imgui.h\nvoid customCallback()\n{\n    using namespace rsurfaces;\n\n    const int INDENT = 10;\n    const int ITEM_WIDTH = 160;\n\n    ImGui::Text(\"Flow control\");\n    ImGui::BeginGroup();\n    ImGui::Indent(INDENT);\n    ImGui::PushItemWidth(ITEM_WIDTH);\n    ImGui::Checkbox(\"Run flow\", &run);\n    ImGui::SameLine(ITEM_WIDTH, 2 * INDENT);\n    ImGui::Checkbox(\"Normalize view\", &uiNormalizeView);\n\n    ImGui::Checkbox(\"Take screenshots\", &takeScreenshots);\n    ImGui::SameLine(ITEM_WIDTH, 2 * INDENT);\n    if ((takeScreenshots && screenshotNum == 0) || ImGui::Button(\"Take screenshot\", ImVec2{ITEM_WIDTH, 0}))\n    {\n        saveScreenshot(screenshotNum++);\n    }\n\n    ImGui::Checkbox(\"Write OBJs\", &saveOBJs);\n    ImGui::SameLine(ITEM_WIDTH, 2 * INDENT);\n    if ((saveOBJs && objNum == 0) || ImGui::Button(\"Write OBJ\", ImVec2{ITEM_WIDTH, 0}))\n    {\n        saveOBJ(MainApp::instance->mesh, MainApp::instance->geom, MainApp::instance->geomOrig, objNum++);\n    }\n    ImGui::Checkbox(\"Log performance\", &MainApp::instance->logPerformance);\n    ImGui::Checkbox(\"Skip odd frames\", &skipEveryOther);\n    ImGui::SameLine(ITEM_WIDTH, 2 * INDENT);\n    ImGui::Checkbox(\"Show area ratios\", &areaRatios);\n\n    const GradientMethod methods[] = {GradientMethod::HsProjectedIterative,\n                                      GradientMethod::HsProjected,\n                                      GradientMethod::HsExactProjected,\n                                      GradientMethod::H1Projected,\n                                      GradientMethod::L2Unconstrained,\n                                      GradientMethod::L2Projected,\n                                      GradientMethod::AQP,\n                                      GradientMethod::H1_LBFGS,\n                                      GradientMethod::BQN_LBFGS,\n                                      GradientMethod::H2Projected};\n\n    selectFromDropdown(\"Method\", methods, IM_ARRAYSIZE(methods), MainApp::instance->methodChoice);\n\n    ImGui::Checkbox(\"Dynamic remeshing\", &remesh);\n\n    const remeshing::RemeshingMode rModes[] = {remeshing::RemeshingMode::FlipOnly,\n                                               remeshing::RemeshingMode::SmoothOnly,\n                                               remeshing::RemeshingMode::SmoothAndFlip,\n                                               remeshing::RemeshingMode::SmoothFlipAndCollapse};\n\n    const remeshing::SmoothingMode sModes[] = {remeshing::SmoothingMode::Laplacian,\n                                               remeshing::SmoothingMode::Circumcenter};\n\n    const remeshing::FlippingMode fModes[] = {remeshing::FlippingMode::Delaunay,\n                                              remeshing::FlippingMode::Degree};\n\n    selectFromDropdown(\"Remeshing mode\", rModes, IM_ARRAYSIZE(rModes), MainApp::instance->remesher.remeshingMode);\n    selectFromDropdown(\"Smoothing mode\", sModes, IM_ARRAYSIZE(sModes), MainApp::instance->remesher.smoothingMode);\n    selectFromDropdown(\"Flipping mode\", fModes, IM_ARRAYSIZE(fModes), MainApp::instance->remesher.flippingMode);\n\n    ImGui::Checkbox(\"Curvature adaptive remeshing\", &MainApp::instance->remesher.curvatureAdaptive);\n\n    rsurfaces::MainApp::instance->HandlePicking();\n\n    ImGui::InputInt(\"Iteration limit\", &MainApp::instance->stepLimit);\n    ImGui::InputInt(\"Real time limit (ms)\", &MainApp::instance->realTimeLimit);\n\n    if (uiNormalizeView != MainApp::instance->normalizeView)\n    {\n        rsurfaces::MainApp::instance->normalizeView = uiNormalizeView;\n        rsurfaces::MainApp::instance->updateMeshPositions();\n    }\n    ImGui::PopItemWidth();\n\n    ImGui::Checkbox(\"Limit step size\", &limitStep);\n    ImGui::SliderFloat( \"Max step size\", &maxStep, 0.001, 0.1 );\n    rsurfaces::MainApp::instance->flow->maxStepSize = limitStep ? maxStep : -1.;\n\n    if (ImGui::Button(\"Take 1 step\", ImVec2{ITEM_WIDTH, 0}) || run)\n    {\n        MainApp::instance->TakeOptimizationStep(remesh, areaRatios);\n        if (skipEveryOther)\n        {\n            MainApp::instance->TakeOptimizationStep(remesh, areaRatios);\n        }\n\n        if (takeScreenshots)\n        {\n            saveScreenshot(screenshotNum++);\n        }\n        if (saveOBJs)\n        {\n            saveOBJ(MainApp::instance->mesh, MainApp::instance->geom, MainApp::instance->geomOrig, objNum++);\n        }\n        if ((MainApp::instance->stepLimit > 0 && MainApp::instance->numSteps >= MainApp::instance->stepLimit) ||\n            (MainApp::instance->realTimeLimit > 0 && MainApp::instance->timeSpentSoFar >= MainApp::instance->realTimeLimit))\n        {\n            run = false;\n            if (MainApp::instance->exitWhenDone)\n            {\n                std::exit(0);\n            }\n        }\n    }\n\n    ImGui::EndGroup();\n\n    ImGui::Text(\"Accuracy tests\");\n\n    ImGui::BeginGroup();\n    ImGui::Indent(INDENT);\n\n    if (ImGui::Button(\"Create/destroy BVH\", ImVec2{ITEM_WIDTH, 0}))\n    {\n        MainApp::instance->CreateAndDestroyBVH();\n    }\n\n    ImGui::SameLine(ITEM_WIDTH, 2 * INDENT);\n    if (ImGui::Button(\"TestMultiply\", ImVec2{ITEM_WIDTH, 0}))\n    {\n        MainApp::instance->TestMultiply();\n    }\n\n    if (ImGui::Button(\"Test Update\", ImVec2{ITEM_WIDTH, 0}))\n    {\n        MainApp::instance->TestUpdate();\n    }\n\n    if (ImGui::Button(\"Test Willmore\", ImVec2{ITEM_WIDTH, 0}))\n    {\n        MainApp::instance->TestWillmore();\n    }\n\n    ImGui::SameLine(ITEM_WIDTH, 2 * INDENT);\n    if (ImGui::Button(\"Test TPObstacle0\", ImVec2{ITEM_WIDTH, 0}))\n    {\n        MainApp::instance->TestObstacle0();\n    }\n\n    if (ImGui::Button(\"Test BarnesHut0\", ImVec2{ITEM_WIDTH, 0}))\n    {\n        MainApp::instance->TestBarnesHut0();\n    }\n    ImGui::SameLine(ITEM_WIDTH, 2 * INDENT);\n    if (ImGui::Button(\"Plot gradients\", ImVec2{ITEM_WIDTH, 0}))\n    {\n        MainApp::instance->PlotGradients();\n    }\n    ImGui::EndGroup();\n\n    ImGui::Text(\"Remeshing tests\");\n\n    ImGui::BeginGroup();\n    ImGui::Indent(INDENT);\n\n    if (ImGui::Button(\"Remesh\"))\n    {\n        MainApp::instance->remesher.Remesh(5, true);\n        MainApp::instance->mesh->compress();\n        MainApp::instance->reregisterMesh();\n    }\n    ImGui::EndGroup();\n}\n\nstruct MeshAndEnergy\n{\n    rsurfaces::TPEKernel *kernel;\n    polyscope::SurfaceMesh *psMesh;\n    rsurfaces::MeshPtr mesh;\n    rsurfaces::GeomPtr geom;\n    rsurfaces::UVDataPtr uvs;\n    std::string meshName;\n};\n\nMeshAndEnergy initTPEOnMesh(std::string meshFile, double alpha, double beta)\n{\n    using namespace rsurfaces;\n    std::cout << \"Initializing tangent-point energy with (\" << alpha << \", \" << beta << \")\" << std::endl;\n\n    MeshUPtr u_mesh;\n    std::unique_ptr<VertexPositionGeometry> u_geometry;\n    std::unique_ptr<CornerData<Vector2>> uvs;\n\n    // Load mesh\n    std::tie(u_mesh, u_geometry, uvs) = readParameterizedMesh(meshFile);\n    std::string mesh_name = polyscope::guessNiceNameFromPath(meshFile);\n\n    std::cout << \"Read \" << uvs->size() << \" UV coordinates\" << std::endl;\n    bool hasUVs = false;\n\n    for (GCVertex v : u_mesh->vertices())\n    {\n        for (surface::Corner c : v.adjacentCorners())\n        {\n            Vector2 uv = (*uvs)[c];\n            if (uv.x > 0 || uv.y > 0)\n            {\n                hasUVs = true;\n            }\n        }\n    }\n\n    if (hasUVs)\n    {\n        std::cout << \"Mesh has nonzero UVs; using as flags for attractors\" << std::endl;\n    }\n    else\n    {\n        std::cout << \"Mesh has no UVs or all UVs are 0; not using as flags\" << std::endl;\n    }\n\n    // Register the mesh with polyscope\n    polyscope::SurfaceMesh *psMesh = polyscope::registerSurfaceMesh(mesh_name,\n                                                                    u_geometry->inputVertexPositions, u_mesh->getFaceVertexList(),\n                                                                    polyscopePermutations(*u_mesh));\n\n    psMesh->setSurfaceColor( glm::vec3( 222/255., 192/255., 130/255. ) );\n    psMesh->setEdgeColor( glm::vec3( 156/255., 133/255., 84/255. ) );\n    psMesh->setEdgeWidth( 1.5 );\n    psMesh->setSmoothShade( true );\n    MeshPtr meshShared = std::move(u_mesh);\n    GeomPtr geomShared = std::move(u_geometry);\n    UVDataPtr uvShared = std::move(uvs);\n\n    geomShared->requireFaceNormals();\n    geomShared->requireFaceAreas();\n    geomShared->requireVertexNormals();\n    geomShared->requireVertexDualAreas();\n    geomShared->requireVertexGaussianCurvatures();\n\n    TPEKernel *tpe = new rsurfaces::TPEKernel(meshShared, geomShared, alpha, beta);\n\n    std::cout << \"Initial mesh area = \" << totalArea(geomShared, meshShared) << std::endl;\n    std::cout << \"Initial mesh volume = \" << totalVolume(geomShared, meshShared) << std::endl;\n\n    return MeshAndEnergy{tpe, psMesh, meshShared, geomShared, (hasUVs) ? uvShared : 0, mesh_name};\n}\n\nenum class EnergyOverride\n{\n    TangentPoint,\n    Coulomb,\n    Willmore\n};\n\nrsurfaces::SurfaceFlow *setUpFlow(MeshAndEnergy &m, double theta, rsurfaces::scene::SceneData &scene, EnergyOverride eo)\n{\n    using namespace rsurfaces;\n\n    SurfaceEnergy *energy;\n\n    if (eo == EnergyOverride::Coulomb)\n    {\n        std::cout << \"Using Coulomb energy in place of tangent-point energy\" << std::endl;\n        energy = new CoulombEnergy(m.kernel, theta);\n    }\n    else if (eo == EnergyOverride::Willmore)\n    {\n        std::cout << \"Using Willmore energy in place of tangent-point energy\" << std::endl;\n        energy = new WillmoreEnergy(m.mesh, m.geom);\n    }\n    else\n    {\n        if (theta <= 0)\n        {\n            std::cout << \"Theta was zero (or negative); using exact all-pairs energy.\" << std::endl;\n            energy = new TPEnergyAllPairs(m.kernel->mesh, m.kernel->geom, m.kernel->alpha, m.kernel->beta);\n            ;\n        }\n        else\n        {\n            std::cout << \"Using Barnes-Hut energy with theta = \" << theta << \".\" << std::endl;\n            TPEnergyBarnesHut0 *bh = new TPEnergyBarnesHut0(m.kernel->mesh, m.kernel->geom, m.kernel->alpha, m.kernel->beta, theta);\n            energy = bh;\n        }\n    }\n\n    SurfaceFlow *flow = new SurfaceFlow(energy);\n    bool kernelRemoved = false;\n    flow->allowBarycenterShift = scene.allowBarycenterShift;\n    // Set these up here, so that we can aggregate all vertex pins into the same constraint\n    Constraints::VertexPinConstraint *pinC = 0;\n    Constraints::VertexNormalConstraint *normC = 0;\n\n    std::vector<Vector3> pinLocations;\n\n    for (scene::ConstraintData &data : scene.constraints)\n    {\n        switch (data.type)\n        {\n        case scene::ConstraintType::Barycenter:\n            kernelRemoved = true;\n            flow->addSimpleConstraint<Constraints::BarycenterConstraint3X>(m.mesh, m.geom);\n            break;\n        case scene::ConstraintType::TotalArea:\n            flow->addSchurConstraint<Constraints::TotalAreaConstraint>(m.mesh, m.geom, data.targetMultiplier, data.numIterations, data.targetAddition);\n            break;\n        case scene::ConstraintType::TotalVolume:\n            flow->addSchurConstraint<Constraints::TotalVolumeConstraint>(m.mesh, m.geom, data.targetMultiplier, data.numIterations, data.targetAddition);\n            break;\n\n        case scene::ConstraintType::BoundaryPins:\n        {\n            if (!pinC)\n            {\n                pinC = flow->addSimpleConstraint<Constraints::VertexPinConstraint>(m.mesh, m.geom);\n            }\n            // Manually add all of the boundary vertex indices as pins\n            std::vector<size_t> boundaryInds;\n            VertexIndices inds = m.mesh->getVertexIndices();\n            for (GCVertex v : m.mesh->vertices())\n            {\n                if (v.isBoundary())\n                {\n                    boundaryInds.push_back(inds[v]);\n\n                    Vector3 pos = m.geom->inputVertexPositions[v];\n                    pinLocations.push_back(pos);\n                }\n            }\n            pinC->pinVertices(m.mesh, m.geom, boundaryInds);\n            kernelRemoved = true;\n        }\n        break;\n\n        case scene::ConstraintType::VertexPins:\n        {\n            if (!pinC)\n            {\n                pinC = flow->addSimpleConstraint<Constraints::VertexPinConstraint>(m.mesh, m.geom);\n            }\n            // Add the specified vertices as pins\n            pinC->pinVertices(m.mesh, m.geom, scene.vertexPins);\n            for (VertexPinData &pinData : scene.vertexPins)\n            {\n                Vector3 pos = m.geom->inputVertexPositions[pinData.vertID];\n                pinLocations.push_back(pos);\n            }\n            // Clear the data vector so that we don't add anything twice\n            scene.vertexPins.clear();\n            kernelRemoved = true;\n        }\n        break;\n\n        case scene::ConstraintType::BoundaryNormals:\n        {\n            if (!normC)\n            {\n                normC = flow->addSimpleConstraint<Constraints::VertexNormalConstraint>(m.mesh, m.geom);\n            }\n            // Manually add all of the boundary vertex indices as pins\n            std::vector<size_t> boundaryInds;\n            VertexIndices inds = m.mesh->getVertexIndices();\n            for (GCVertex v : m.mesh->vertices())\n            {\n                if (v.isBoundary())\n                {\n                    boundaryInds.push_back(inds[v]);\n                }\n            }\n            normC->pinVertices(m.mesh, m.geom, boundaryInds);\n        }\n\n        case scene::ConstraintType::VertexNormals:\n        {\n            if (!normC)\n            {\n                normC = flow->addSimpleConstraint<Constraints::VertexNormalConstraint>(m.mesh, m.geom);\n            }\n            // Add the specified vertices as pins\n            normC->pinVertices(m.mesh, m.geom, scene.vertexNormals);\n            // Clear the data vector so that we don't add anything twice\n            scene.vertexNormals.clear();\n        }\n        break;\n\n        default:\n            std::cout << \"  * Skipping unrecognized constraint type\" << std::endl;\n            break;\n        }\n    }\n\n    if (!kernelRemoved)\n    {\n        // std::cout << \"Auto-adding barycenter constraint to eliminate constant kernel of Laplacian\" << std::endl;\n        // flow->addSimpleConstraint<Constraints::BarycenterConstraint3X>(m.mesh, m.geom);\n    }\n\n    if (pinLocations.size() > 0)\n    {\n        polyscope::registerPointCloud(\"pinned vertices\", pinLocations);\n    }\n\n    return flow;\n}\n\nrsurfaces::scene::SceneData defaultScene(std::string meshName)\n{\n    using namespace rsurfaces;\n    using namespace rsurfaces::scene;\n    SceneData data;\n    data.meshName = meshName;\n    data.alpha = 6;\n    data.beta = 12;\n    data.constraints = std::vector<ConstraintData>({ConstraintData{scene::ConstraintType::Barycenter, 1, 0, 0},\n                                                    ConstraintData{scene::ConstraintType::TotalArea, 1, 0, 0},\n                                                    ConstraintData{scene::ConstraintType::TotalVolume, 1, 0, 0}});\n    return data;\n}\n\nint main(int argc, char **argv)\n{\n    using namespace rsurfaces;\n\n    // Configure the argument parser\n    args::ArgumentParser parser(\"geometry-central & Polyscope example project\");\n    args::Positional<std::string> inputFilename(parser, \"mesh\", \"A mesh file.\");\n    args::ValueFlag<double> thetaFlag(parser, \"Theta\", \"Theta value for Barnes-Hut approximation; 0 means exact.\", args::Matcher{'t', \"theta\"});\n    args::ValueFlag<std::string> mult_alg_Flag(parser, \"mult_alg\", \"Algorithm for the near field matrix-vector product. Possible values are \\\"Hybrid\\\" (default) and \\\"MKL_CSR\\\" (maybe more robust).\", {\"mult_alg\"});\n    args::ValueFlagList<std::string> obstacleFiles(parser, \"obstacles\", \"Obstacles to add\", {'o'});\n    args::Flag autologFlag(parser, \"autolog\", \"Automatically start the flow, log performance, and exit when done.\", {\"autolog\"});\n    args::Flag coulombFlag(parser, \"coulomb\", \"Use a coulomb energy instead of the tangent-point energy.\", {\"coulomb\"});\n    args::ValueFlag<int> threadFlag(parser, \"threads\", \"How many threads to use in parallel.\", {\"threads\"});\n\n    polyscope::options::programName = \"Repulsive Surfaces\";\n    polyscope::options::groundPlaneEnabled = false;\n\n    std::cout << \"Using Eigen version \" << EIGEN_WORLD_VERSION << \".\" << EIGEN_MAJOR_VERSION << \".\" << EIGEN_MINOR_VERSION << std::endl;\n\n    MKLVersion Version;\n    mkl_get_version(&Version);\n\n    std::cout << \"Using MKL version \" << Version.MajorVersion << \".\" << Version.MinorVersion << \".\" << Version.UpdateVersion << std::endl;\n\n    // Parse args\n    try\n    {\n        parser.ParseCLI(argc, argv);\n    }\n    catch (args::Help)\n    {\n        std::cout << parser;\n        return 0;\n    }\n    catch (args::ParseError e)\n    {\n        std::cerr << e.what() << std::endl;\n        std::cerr << parser;\n        return 1;\n    }\n    // Make sure a mesh name was given\n    if (!inputFilename)\n    {\n        std::cerr << \"Please specify a mesh file as argument\" << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    MainApp::defaultNumThreads = omp_get_max_threads() / 2 + 2;\n\n    if (threadFlag)\n    {\n        int nThreads = args::get(threadFlag);\n        std::cout << \"Using \" << nThreads << \" threads as specified.\" << std::endl;\n        omp_set_num_threads(nThreads);\n        MainApp::specifiedNumThreads = nThreads;\n    }\n    else\n    {\n        omp_set_num_threads(MainApp::defaultNumThreads);\n        MainApp::specifiedNumThreads = MainApp::defaultNumThreads;\n        std::cout << \"Defaulting to \" << MainApp::defaultNumThreads << \" threads.\" << std::endl;\n    }\n    \n\n    if ( mult_alg_Flag )\n    {\n        std::string s = args::get(mult_alg_Flag);\n        if( s.compare(\"MKL_CSR\") == 0 )\n        {\n            BCTDefaultSettings.mult_alg = NearFieldMultiplicationAlgorithm::MKL_CSR;\n            std::cout << \"Using \\\"MKL_CSR\\\" for near field matrix-vector product.\" << std::endl;\n        }\n        else if( s.compare(\"Hybrid\") == 0 )\n        {\n            BCTDefaultSettings.mult_alg = NearFieldMultiplicationAlgorithm::Hybrid;\n            std::cout << \"Using \\\"Hybrid\\\" for near field matrix-vector product.\" << std::endl;\n        }\n        else\n        {\n            BCTDefaultSettings.mult_alg = NearFieldMultiplicationAlgorithm::Hybrid;\n            std::cout << \"Unknown method \\\"\" + s + \"\\\". Using default value \\\"Hybrid\\\" for near field matrix-vector product.\" << std::endl;\n        }\n    }\n    else\n    {\n        BCTDefaultSettings.mult_alg = NearFieldMultiplicationAlgorithm::Hybrid;\n        std::cout << \"Using default value \\\"Hybrid\\\" for near field matrix-vector product.\" << std::endl;\n    }\n\n    double theta = 0.5;\n    if (!thetaFlag)\n    {\n        std::cout << \"Barnes-Hut theta value not specified; defaulting to theta = \" << theta << std::endl;\n    }\n    else\n    {\n        theta = args::get(thetaFlag);\n    }\n\n    // Initialize polyscope\n    polyscope::init();\n    // Set the callback function\n    polyscope::state::userCallback = customCallback;\n\n    // Parse the input file, either as a scene file or as a mesh\n    std::string inFile = args::get(inputFilename);\n    scene::SceneData data;\n\n    if (endsWith(inFile, \".txt\") || endsWith(inFile, \".scene\"))\n    {\n        std::cout << \"Parsing \" << inFile << \" as scene file.\" << std::endl;\n        data = scene::parseScene(inFile);\n    }\n\n    else if (endsWith(inFile, \".obj\"))\n    {\n        std::cout << \"Parsing \" << inFile << \" as OBJ mesh file.\" << std::endl;\n        data = defaultScene(inFile);\n    }\n\n    else\n    {\n        throw std::runtime_error(\"Unknown file extension for \" + inFile + \".\");\n    }\n\n    bool useCoulomb = false;\n    if (coulombFlag)\n    {\n        useCoulomb = true;\n        std::cout << \"Using Coulomb energy. (Note: Not expected to work well.)\" << std::endl;\n    }\n\n    MeshAndEnergy m = initTPEOnMesh(data.meshName, data.alpha, data.beta);\n\n    EnergyOverride eo = EnergyOverride::TangentPoint;\n    if (useCoulomb)\n    {\n        eo = EnergyOverride::Coulomb;\n    }\n    else if (data.defaultMethod == GradientMethod::Willmore)\n    {\n        eo = EnergyOverride::Willmore;\n    }\n\n    SurfaceFlow *flow = setUpFlow(m, theta, data, eo);\n    flow->disableNearField = data.disableNearField;\n\n    MainApp::instance = new MainApp(m.mesh, m.geom, flow, m.psMesh, m.meshName);\n    MainApp::instance->bh_theta = theta;\n    MainApp::instance->kernel = m.kernel;\n    MainApp::instance->stepLimit = data.iterationLimit;\n    MainApp::instance->realTimeLimit = data.realTimeLimit;\n    MainApp::instance->methodChoice = data.defaultMethod;\n    MainApp::instance->sceneData = data;\n    MainApp::instance->uvs = m.uvs;\n\n    if (autologFlag)\n    {\n        std::cout << \"Autolog flag was used; starting flow automatically.\" << std::endl;\n        MainApp::instance->exitWhenDone = true;\n        MainApp::instance->logPerformance = true;\n        run = true;\n        std::ofstream outfile;\n        outfile.open(data.performanceLogFile, std::ios_base::out);\n        outfile.close();\n    }\n\n    for (scene::PotentialData &p : data.potentials)\n    {\n        MainApp::instance->AddPotential(p.type, p.weight, p.targetValue);\n    }\n    for (scene::ObstacleData &obs : data.obstacles)\n    {\n        MainApp::instance->AddObstacle(obs.obstacleName, obs.weight, obs.recenter, obs.asPointCloud);\n    }\n    for (scene::ImplicitBarrierData &barrierData : data.implicitBarriers)\n    {\n        MainApp::instance->AddImplicitBarrier(barrierData);\n    }\n\n    if (data.autoComputeVolumeTarget)\n    {\n        double targetVol = MainApp::instance->totalObstacleVolume * data.autoVolumeTargetRatio;\n        std::cout << \"Retargeting volume constraint to value \" << targetVol << \" (\" << data.autoVolumeTargetRatio << \"x obstacle volume)\" << std::endl;\n        MainApp::instance->flow->retargetSchurConstraintOfType<Constraints::TotalVolumeConstraint>(targetVol);\n    }\n\n    MainApp::instance->updateMeshPositions();\n\n    // Give control to the polyscope gui\n    polyscope::show();\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "76819975324724b9102629dca90235790720f959", "size": 96732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Conrekatsu/repulsive-surfaces", "max_stars_repo_head_hexsha": "74d6a16e6ca55c8296fa5a49757c2318bea62a84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2021-12-13T09:58:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:03:01.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "Conrekatsu/repulsive-surfaces", "max_issues_repo_head_hexsha": "74d6a16e6ca55c8296fa5a49757c2318bea62a84", "max_issues_repo_licenses": ["MIT"], "max_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": "Conrekatsu/repulsive-surfaces", "max_forks_repo_head_hexsha": "74d6a16e6ca55c8296fa5a49757c2318bea62a84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-02-25T06:46:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T05:46:53.000Z", "avg_line_length": 37.4494773519, "max_line_length": 223, "alphanum_fraction": 0.5281602779, "num_tokens": 25971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.520783028097061}}
{"text": "/*\n * diagonalize.cc\n */\n\n#include \"llvm/Pass.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/IR/Constants.h\"\n#include \"llvm/IR/Instructions.h\"\n#include \"llvm/Analysis/LoopPass.h\"\n#include \"llvm/ADT/ValueMap.h\"\n#include \"llvm/Support/PatternMatch.h\"\n#include \"llvm/Support/InstIterator.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\nusing namespace llvm;\nusing namespace PatternMatch;\nusing namespace Eigen;\n\n#define OP_IN_RANGE(_op, _start, _end) \\\n    (_op >= Instruction:: _start && _op <= Instruction:: _end)\n\nnamespace\n{\n\nclass ADPass : public LoopPass\n{\n    Loop* loop;\n    DominatorTree* DT;\n    ICmpInst* loop_cond; \n    BasicBlock* loop_body;\n    BasicBlock* exit_block;\n    Value* nr_iters;\n    BasicBlock* dgen; \n    ConstantInt* start_iter;\n    PHINode* iter_var;\n    ValueMap<PHINode*, size_t> phis;\n\n    /* Track linear combinations of state variables. */\n    typedef ValueMap<PHINode*, double> Coefficients;\n\npublic:\n    static char ID;\n\n    ADPass() : LoopPass(ID) {}\n\n    virtual void getAnalysisUsage(AnalysisUsage& AU) const {\n        AU.addRequired<DominatorTree>();\n    }\n\n    /*\n     * Drive the optimization pass.\n     * Return true iff the optimization was applied.\n     */\n    virtual bool runOnLoop(Loop* L, LPPassManager&) {\n        loop = L;\n        DT = &getAnalysis<DominatorTree>();\n        phis.clear();\n\n        if (loop->getBlocks().size() != 1\n            || !(loop_body = loop->getBlocks().front())\n            || loop->getSubLoops().size()\n            || !(exit_block = loop->getUniqueExitBlock())\n            || !loopFilter()\n            || !extractIterator())\n        {\n            return false;\n        }\n\n        /* Assign a dimension to each state variable. */\n        size_t phi_index = 0;\n        phis.erase(iter_var);\n        for (auto kv = phis.begin(); kv != phis.end(); ++kv) {\n            phis[kv->first] = phi_index++;\n        }\n\n        /* Find the initial state and all linear dependence relations. */\n        size_t nr_phis = phis.size();\n\n        MatrixXd InitialState(nr_phis, 1);\n        MatrixXd TransformationMatrix(nr_phis, nr_phis);\n        TransformationMatrix << MatrixXd::Zero(nr_phis, nr_phis);\n        for (auto kv = phis.begin(); kv != phis.end(); ++kv) {\n            PHINode* PN = kv->first;\n            size_t phi_label = phis[PN];\n            InitialState(phi_label, 0) = toDouble(getPhiConstVal(PN));\n\n            Coefficients coeffs;\n            if (!trackUpdates(getPhiFeedbackVal(PN), coeffs)) {\n                return false;\n            }\n            for (auto ckv = coeffs.begin(); ckv != coeffs.end(); ++ckv) {\n                size_t target_phi = phis[ckv->first];\n                TransformationMatrix(phi_label, target_phi) = ckv->second;\n            }\n        }\n\n        /* Diagonalize the transformation matrix. */\n        EigenSolver<MatrixXd> EigSolver(TransformationMatrix);\n        MatrixXcd P = EigSolver.eigenvectors();\n        MatrixXcd D = EigSolver.eigenvalues().asDiagonal();\n        MatrixXcd Pinv = P.inverse();\n        if (!checkSystem(TransformationMatrix, P, D, Pinv)) {\n            return false;\n        }\n\n        /* Emit instructions to compute the closed form in a new block. */\n        LLVMContext& ctx = loop_body->getContext();\n        Function* parentFunc = exit_block->getParent();\n\n        Module* mod = parentFunc->getParent();\n        dgen = BasicBlock::Create(ctx, \"dgen\", parentFunc, exit_block);\n        Type* numTy = Type::getDoubleTy(ctx);\n        Function* powf = NULL;\n        if (!(powf = mod->getFunction(\"llvm.pow.f64\"))) {\n            std::vector<Type*> powProto(2, numTy);\n            FunctionType* powType = FunctionType::get(numTy, powProto, false);\n            powf = Function::Create(powType, GlobalValue::ExternalLinkage,\n                \"llvm.pow.f64\", mod);\n            powf->setCallingConv(CallingConv::C);\n        }\n\n        /* P(D^n) = r * \u03bb^n : \u2200(r) \u2208 row(P) */\n        Value** PDn = new Value*[nr_phis * nr_phis];\n        Value* iexpt = BinaryOperator::Create(Instruction::Sub, nr_iters,\n           start_iter, \"iexpt\", dgen);\n        iexpt = BinaryOperator::Create(Instruction::Add, iexpt,\n           ConstantInt::get(Type::getInt32Ty(ctx), 1), \"iexpt_adj\", dgen);\n        Value* exponent = CastInst::Create(Instruction::UIToFP, iexpt, numTy,\n            \"fexpt\", dgen);\n        for (size_t j = 0; j < nr_phis; ++j) {\n            /* \u03bb[j]^n */\n            Value* exptargs[] = {\n                toConstantFP(ctx, std::real(D(j, j))), exponent\n            };\n            Value* eigvexpt = CallInst::Create(powf,\n                ArrayRef<Value*>(exptargs, 2), \"eigvexpt\", dgen);\n\n            /* PDn[i][j] = P[i][j] * \u03bb[j]^n */\n            for (size_t i = 0; i < nr_phis; ++i) {\n                size_t index = i * nr_phis + j;\n                PDn[index] = BinaryOperator::Create(Instruction::FMul,\n                    toConstantFP(ctx, std::real(P(i, j))), eigvexpt, \"pdn\",\n                                 dgen);\n            }\n        }\n\n        /* xf = P(D^n) * Pinv * x0 */\n        Value** soln = new Value*[nr_phis];\n        Value* zero = toConstantFP(ctx, 0.0);\n        for (size_t i = 0; i < nr_phis; ++i) {\n            soln[i] = zero;\n            for (size_t j = 0; j < nr_phis; ++j) {\n                /* dotp = <a, b> : a \u2208 row(P(D^n)), b \u2208 col(Pinv) */\n                Value* dotp = zero;\n                for (size_t k = 0; k < nr_phis; ++k) {\n                    Value* ik_kj = BinaryOperator::Create(Instruction::FMul,\n                        PDn[i * nr_phis + k],\n                        toConstantFP(ctx, std::real(Pinv(k, j))),\n                        \"ik_kj\", dgen);\n                    dotp = BinaryOperator::Create(Instruction::FAdd,\n                        ik_kj, dotp, \"dotp\", dgen);\n                }\n\n                /* xf[i] = \u2211 P(D^n)Pinv[i][j] * x0[j] */\n                Value* xj_prod = BinaryOperator::Create(Instruction::FMul,\n                    dotp, toConstantFP(ctx, InitialState(j)), \"pdpxj\",\n                    dgen);\n                soln[i] = BinaryOperator::Create(Instruction::FAdd, \n                    xj_prod, soln[i], \"xf\", dgen);\n            }\n        }\n\n        delete[] PDn;\n\n        /* Rewire edges headed in and out of the loop. */\n        for (inst_iterator II = inst_begin(parentFunc),\n                           E = inst_end(parentFunc); II != E; ++II)\n        {\n            Instruction* instr = &*II;\n            if (!isa<BranchInst>(instr)) {\n                continue;\n            }\n\n            BranchInst* BI = cast<BranchInst>(instr);\n            for (unsigned k = 0; k < BI->getNumSuccessors(); ++k) {\n                if (BI->getSuccessor(k) == loop_body) {\n                    BI->setSuccessor(k, dgen);\n                }\n            }\n        }\n        BranchInst::Create(exit_block, dgen);\n\n        /* Replace values leading into phi nodes. */\n        for (auto kv = phis.begin(); kv != phis.end(); ++kv) {\n            PHINode* loopPhi = kv->first;\n            Value* incoming = getPhiFeedbackVal(loopPhi);\n            Value* target = soln[kv->second];\n            rewriteLiveValues(incoming, target);\n        }\n        loop_body->replaceSuccessorsPhiUsesWith(dgen);\n\n        /* Delete the old loop. */\n        loop_body->eraseFromParent();\n\n        delete[] soln;\n\n        return true;\n    }\n\nprivate:\n    /*\n     * Check whether the loop is linearizale.\n     */\n    bool loopFilter() {\n        loop_cond = NULL;\n        for (auto II = loop_body->begin(); II != loop_body->end(); ++II) {\n            Instruction* instr = II;\n            if (isa<ICmpInst>(instr)) {\n                if (loop_cond) {\n                    return false;\n                } else {\n                    loop_cond = cast<ICmpInst>(instr);\n                }\n            } else if (isa<PHINode>(instr)) {\n                PHINode* PN = cast<PHINode>(instr);\n                if (PN->getNumIncomingValues() != 2\n                    || !DT->dominates(PN->getIncomingBlock(0), loop_body))\n                {\n                    return false;\n                }\n                Value* inLhs = PN->getIncomingValue(0);\n                Value* inRhs = PN->getIncomingValue(1);\n                if (!isa<ConstantInt>(inLhs) && !isConstant(inRhs)) {\n                    return false;\n                } else {\n                    phis[PN] = 0;\n                }\n            } else if (isa<BinaryOperator>(instr)) {\n                BinaryOperator* binop = cast<BinaryOperator>(instr);\n                if (!(OP_IN_RANGE(binop->getOpcode(), Add, FDiv))) {\n                    return false;\n                }\n            } else if (!isa<BranchInst>(instr)) {\n                return false;\n            }\n        }\n        return loop_cond != NULL;\n    }\n\n    /*\n     * Given a loop in canonical form, extract the loop condition and the\n     * starting iteration. Return true iff basic sanity checks pass.\n     */\n    bool extractIterator() {\n        Value* loop_var = NULL;\n        ICmpInst::Predicate IPred;\n        if (!match(loop_cond, m_ICmp(IPred, m_Value(loop_var),\n                                            m_Value(nr_iters)))\n            || IPred != CmpInst::Predicate::ICMP_EQ\n            || !isa<PHINode>(loop_var))\n        {\n            return false;\n        }\n\n        iter_var = cast<PHINode>(loop_var);\n        if (!match(getPhiConstVal(iter_var), m_ConstantInt(start_iter))) {\n            return false;\n        }\n\n        bool foundIncr = false;\n        for (auto II = loop_body->begin(); II != loop_body->end(); ++II) {\n            Instruction* instr = II;\n            if (!isa<BinaryOperator>(II)) {\n                continue;\n            }\n\n            BinaryOperator* binop = cast<BinaryOperator>(instr);\n            if (foundIncr &&\n                (binop->getOperand(0) == iter_var\n                || binop->getOperand(1) == iter_var))\n            {\n                return false;\n            }\n\n            if (binop->getOpcode() == Instruction::Add\n                && ((binop->getOperand(0) == iter_var\n                      && isa<ConstantInt>(binop->getOperand(1))\n                      && toInt(binop->getOperand(1)) == 1) ||\n                    (binop->getOperand(1) == iter_var\n                      && isa<ConstantInt>(binop->getOperand(0))\n                      && toInt(binop->getOperand(0)) == 1)))\n            {\n                foundIncr = true;\n            }\n        }\n        return foundIncr;\n    }\n\n    Value* getPhiConstVal(PHINode* PN) {\n      if (isConstant(PN->getIncomingValue(0))) {\n        return PN->getIncomingValue(0);\n      }\n      return PN->getIncomingValue(1);\n    }\n\n    Value* getPhiFeedbackVal(PHINode* PN) {\n      if (isConstant(PN->getIncomingValue(0))) {\n        return PN->getIncomingValue(1);\n      }\n      return PN->getIncomingValue(0);\n    }\n\n    /*\n     * Find a linear combination of state variables which generate @parent.\n     * Return true iff a valid list of coefficients is found.\n     */\n    bool trackUpdates(Value* parent, Coefficients& coeffs, bool root = true) {\n        if (isa<Constant>(parent)) {\n            /*\n             * If a state variable is set to a constant during each iteration,\n             * the compiler should lift it out of the loop before we get here.\n             */\n            return !root;\n        } else if (isa<PHINode>(parent)) {\n            PHINode* PN = cast<PHINode>(parent);\n            coeffs[PN] = 1;\n            return phis.count(PN) == 1;\n        } else if (isa<BinaryOperator>(parent)) {\n            BinaryOperator* binop = cast<BinaryOperator>(parent);\n            int opcode = binop->getOpcode();\n            Value *LHS = binop->getOperand(0),\n                  *RHS = binop->getOperand(1);\n\n            Coefficients lhsCoeffs, rhsCoeffs;\n            if (!trackUpdates(LHS, lhsCoeffs, false)\n                || !trackUpdates(RHS, rhsCoeffs, false))\n            {\n                return false;\n            }\n\n            double scalar;\n            if (OP_IN_RANGE(opcode, Add, FSub)) {\n                /* Add instructions shouldn't operate on scalars. */\n                if (isScalar(lhsCoeffs) || isScalar(rhsCoeffs)) {\n                    return false;\n                }\n            } else {\n                /* Mul instructions should only have one scalar operand. */\n                if (!(isScalar(lhsCoeffs) ^ isScalar(rhsCoeffs))) {\n                    return false;\n                }\n\n                /* Div instructions cannot have scalar numerators. */\n                if (OP_IN_RANGE(opcode, UDiv, FDiv) && isScalar(lhsCoeffs)) {\n                    return false;\n                }\n\n                scalar = toDouble(isScalar(lhsCoeffs) ? LHS : RHS);\n            }\n\n            /* Merge the two sets of coefficients. */\n            for (auto kv = phis.begin(); kv != phis.end(); ++kv) {\n                PHINode* PN = kv->first;\n                double lcoeff = lhsCoeffs.lookup(PN);\n                double rcoeff = rhsCoeffs.lookup(PN);\n\n                /* Adding nil entries to 'coeffs' breaks isScalar(). */\n                if (lcoeff == 0.0 && rcoeff == 0.0) {\n                    continue;\n                }\n\n                if (OP_IN_RANGE(opcode, Add, FAdd)) {\n                    coeffs[PN] = lcoeff + rcoeff;\n                } else if (OP_IN_RANGE(opcode, Sub, FSub)) {\n                    coeffs[PN] = lcoeff - rcoeff;\n                } else if (OP_IN_RANGE(opcode, Mul, FMul)) {\n                    coeffs[PN] = scalar * (lcoeff + rcoeff);\n                } else {\n                    coeffs[PN] = (1 / scalar) * (lcoeff + rcoeff);\n                }\n            }\n            return true;\n        }\n        return false;\n    }\n\n    bool isConstant(Value* V) {\n      return isa<ConstantInt>(V) || isa<ConstantFP>(V);\n    }\n\n    int64_t toInt(Value* V) {\n        return cast<ConstantInt>(V)->getValue().getSExtValue();\n    }\n\n    double toDouble(Value* V) {\n        if (isa<ConstantInt>(V)) {\n            return double(toInt(V));\n        } else if (isa<ConstantFP>(V)) {\n            return cast<ConstantFP>(V)->getValueAPF().convertToDouble();\n        }\n        return 0.0;\n    }\n\n    Value* toConstantFP(LLVMContext& ctx, double n) {\n        return ConstantFP::get(ctx, APFloat(n));\n    }\n\n    bool isScalar(Coefficients& coeffs) {\n        return coeffs.size() == 0;\n    }\n\n    /*\n     * Verify that A == PDP^-1 within an acceptable margin of error.\n     */\n    bool checkSystem(MatrixXd& A, MatrixXcd& P,\n                     MatrixXcd& D, MatrixXcd& Pinv)\n    {\n        MatrixXcd PDPi = P*D*Pinv;\n        const double epsilon = 25 * std::numeric_limits<double>::epsilon();\n        for (int i = 0; i < P.rows(); ++i) {\n            for (int j = 0; j < P.cols(); ++j) {\n                if (std::imag(P(i, j)) != 0.0) {\n                    return false;\n                }\n                if (std::abs(A(i, j) - PDPi(i, j)) > epsilon) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n\n    /* \n     * Some instructions may use the results of the loop. Rewire these\n     * instructions so that they use the values from the @dgen basic block.\n     */\n    void rewriteLiveValues(Value* oldval, Value* target) {\n        for (auto UI = oldval->use_begin(); UI != oldval->use_end(); ++UI) {\n            User* user = *UI;\n\n            /* Don't bother updating values in @loop_body. It dies soon. */\n            if (isPartialComputation(user)) {\n                continue;\n            }\n\n            if (isa<PHINode>(user)) {\n                PHINode* userPhi = cast<PHINode>(user);\n                for (unsigned i=0; i < userPhi->getNumIncomingValues(); ++i) {\n                    if (userPhi->getIncomingValue(i) == oldval) {\n                        userPhi->setIncomingValue(i, target);\n                        userPhi->setIncomingBlock(i, dgen);\n                    }\n                }\n                continue;\n            }\n\n            for (auto op = user->op_begin(); op != user->op_end(); ++op) {\n                Use& phiUse = *op;\n                Value* operand = phiUse.get();\n                if (operand == oldval) {\n                    phiUse.set(target);\n                }\n            }\n        }\n    }\n\n    /* \n     * Check if the target value is defined in the loop body.\n     */\n    bool isPartialComputation(Value* target) {\n        for (auto II = loop_body->begin(); II != loop_body->end(); ++II) {\n            Instruction* instr = II;\n            if (instr == target) {\n                return true;\n            }\n        }\n        return false;\n    }\n};\n\nchar ADPass::ID = 0;\n\n}\n\nstatic RegisterPass<ADPass> X(\"auto-diagonalize\",\n    \"Diagonalize linear dynamical systems\", false, false);\n", "meta": {"hexsha": "b4f555e2a8c97f162184bc7fe5cbcccc2974afec", "size": 16653, "ext": "cc", "lang": "C++", "max_stars_repo_path": "diagonalize.cc", "max_stars_repo_name": "vedantk/auto-diagonalize", "max_stars_repo_head_hexsha": "ca8917ac13afc507c86e0ab2f62c2aa35030523c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-05-06T01:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-06T02:56:44.000Z", "max_issues_repo_path": "diagonalize.cc", "max_issues_repo_name": "vedantk/auto-diagonalize", "max_issues_repo_head_hexsha": "ca8917ac13afc507c86e0ab2f62c2aa35030523c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "diagonalize.cc", "max_forks_repo_name": "vedantk/auto-diagonalize", "max_forks_repo_head_hexsha": "ca8917ac13afc507c86e0ab2f62c2aa35030523c", "max_forks_repo_licenses": ["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.9857142857, "max_line_length": 78, "alphanum_fraction": 0.4997297784, "num_tokens": 4108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5207769730027064}}
{"text": "/*\n * ewa_common.hpp\n *\n *  Created on: Feb 28, 2019\n *      Author: Gregory Kramida\n *   Copyright: 2019 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 \"../math/extent.hpp\"\n#include \"common.hpp\"\n\nnamespace eig = Eigen;\n\nnamespace tsdf{\n\ntemplate<typename Scalar>\ninline eig::Matrix<Scalar,3,3,eig::ColMajor>\ncompute_covariance_camera_space(Scalar voxel_size, const eig::Matrix<Scalar,4,4>& camera_pose,\n\t\tScalar gaussian_covariance_scale = 1.0f) {\n\teig::Matrix<Scalar,3,3,eig::ColMajor> camera_rotation_matrix = camera_pose.block(0, 0, 3, 3);\n\teig::Matrix<Scalar,3,3,eig::ColMajor> covariance_voxel_sphere_world_space = eig::Matrix<Scalar,3,3>::Identity() *\n\t\t\t(voxel_size * gaussian_covariance_scale);\n\teig::Matrix<Scalar,3,3,eig::ColMajor> covariance_camera_space =\n\t\t\tcamera_rotation_matrix * covariance_voxel_sphere_world_space * camera_rotation_matrix.transpose();\n\treturn covariance_camera_space;\n}\n\ntemplate<typename Scalar>\ninline bool compute_sampling_bounds(\n\t\tmath::Extent2d& extent,\n\t\tconst eig::Matrix<Scalar,2,1>& bounds_max,\n\t\tconst eig::Matrix<Scalar,2,1>& voxel_image,\n\t\tconst eig::Matrix<unsigned short, eig::Dynamic, eig::Dynamic>& depth_image) {\n\t// compute sampling bounds\n\tint x_sample_start = static_cast<int>(voxel_image(0) - bounds_max(0));\n\tint x_sample_end = static_cast<int>(std::ceil(voxel_image(0) + bounds_max(0) + 1.0f));\n\tint y_sample_start = static_cast<int>(voxel_image(1) - bounds_max(1));\n\tint y_sample_end = static_cast<int>(std::ceil(voxel_image(1) + bounds_max(1) + 1.0f));\n\n\t// check that at least some samples within sampling range fall within the depth image\n\tif (x_sample_start >= depth_image.cols() || x_sample_end <= 0\n\t\t\t|| y_sample_start >= depth_image.rows() || y_sample_end <= 0) {\n\t\treturn false;\n\t}\n\n\t// limit sampling bounds to image bounds\n\textent.x_start = std::max(0, x_sample_start);\n\textent.x_end = std::min(static_cast<int>(depth_image.cols()), x_sample_end);\n\textent.y_start = std::max(0, y_sample_start);\n\textent.y_end = std::min(static_cast<int>(depth_image.rows()), y_sample_end);\n\treturn true;\n}\n\ntemplate<typename Scalar>\ninline bool compute_sampling_bounds_inclusive(\n\t\tmath::Extent2d& extent,\n\t\tconst eig::Matrix<Scalar,2,1>& bounds_max,\n\t\tconst eig::Matrix<Scalar,2,1>& voxel_image,\n\t\tconst eig::Matrix<unsigned short, eig::Dynamic, eig::Dynamic>& depth_image) {\n\t// compute sampling bounds\n\textent.x_start = static_cast<int>(voxel_image(0) - bounds_max(0));\n\textent.x_end = static_cast<int>(std::ceil(voxel_image(0) + bounds_max(0) + 1.0f));\n\textent.y_start = static_cast<int>(voxel_image(1) - bounds_max(1));\n\textent.y_end = static_cast<int>(std::ceil(voxel_image(1) + bounds_max(1) + 1.0f));\n\n\t//TODO: potential speedup -- remove check here and make function void -- we're already checking for \"out-of-bounds\" voxels\n\t// check that at least some samples within sampling range fall within the depth image\n\tif (extent.x_start >= depth_image.cols() || extent.x_end <= 0\n\t\t\t|| extent.y_start >= depth_image.rows() || extent.y_end <= 0) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n\n\n\ntemplate<typename Scalar>\ninline\nScalar compute_voxel_EWA_image_space(\n\t\tconst math::Extent2d& sampling_bounds,\n\t\tconst eig::Matrix<Scalar,2,1>& voxel_image,\n\t\tconst eig::Matrix<Scalar,3,1>& voxel_camera,\n\t\tconst eig::Matrix<Scalar,2,2>& ellipse_matrix,\n\t\tconst Scalar& squared_radius_threshold,\n\t\tconst Scalar& depth_unit_ratio,\n\t\tconst Scalar& narrow_band_half_width,\n\t\tconst eig::Matrix<unsigned short, eig::Dynamic, eig::Dynamic>& depth_image){\n\tScalar weights_sum = static_cast<Scalar>(0.0);\n\tScalar depth_sum = static_cast<Scalar>(0.0);\n\n\t// collect sample readings\n\tfor (int x_sample = sampling_bounds.x_start; x_sample < sampling_bounds.x_end; x_sample++) {\n\t\tfor (int y_sample = sampling_bounds.y_start; y_sample < sampling_bounds.y_end; y_sample++) {\n\t\t\teig::Matrix<Scalar,2,1> sample_centered;\n\t\t\tsample_centered <<\n\t\t\t\t\tstatic_cast<Scalar>(x_sample) - voxel_image(0),\n\t\t\t\t\tstatic_cast<Scalar>(y_sample) - voxel_image(1);\n\t\t\tScalar dist_sq = sample_centered.transpose() * ellipse_matrix * sample_centered;\n\t\t\t//TODO: potential speedup -- remove check\n\t\t\tif (dist_sq > squared_radius_threshold) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tScalar weight = std::exp(static_cast<Scalar>(-0.5) * dist_sq);\n\t\t\tScalar surface_depth = static_cast<Scalar>(depth_image(y_sample, x_sample)) * depth_unit_ratio;\n\t\t\tif (surface_depth <= static_cast<Scalar>(0.0)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tdepth_sum += weight * surface_depth;\n\t\t\tweights_sum += weight;\n\t\t}\n\t}\n\tif (depth_sum <= static_cast<Scalar>(0.0)) {\n\t\treturn static_cast<Scalar>(1.0);\n\t}\n\n\tScalar final_depth = depth_sum / weights_sum;\n\n\t// signed distance from surface to voxel along camera axis\n\t// TODO: try with \"along ray\" and compare. Newcombe et al. in KinectFusion claim there won't be a difference...\n\tScalar signed_distance = final_depth - voxel_camera[2];\n\n\treturn compute_TSDF_value(signed_distance, narrow_band_half_width);\n}\n\ntemplate<typename Scalar>\ninline\nScalar compute_voxel_EWA_voxel_space(\n\t\tconst math::Extent2d& sampling_bounds,\n\t\tconst eig::Matrix<Scalar,2,1>& voxel_image,\n\t\tconst eig::Matrix<Scalar,3,1>& voxel_camera,\n\t\tconst eig::Matrix<Scalar,2,2>& ellipse_matrix,\n\t\tconst Scalar& squared_radius_threshold,\n\t\tconst Scalar& depth_unit_ratio,\n\t\tconst Scalar& narrow_band_half_width,\n\t\tconst eig::Matrix<unsigned short, eig::Dynamic, eig::Dynamic>& depth_image){\n\tScalar weights_sum = static_cast<Scalar>(0.0);\n\tScalar TSDF_sum = static_cast<Scalar>(0.0);\n\n\t// collect sample readings\n\tfor (int x_sample = sampling_bounds.x_start; x_sample < sampling_bounds.x_end; x_sample++) {\n\t\tfor (int y_sample = sampling_bounds.y_start; y_sample < sampling_bounds.y_end; y_sample++) {\n\t\t\teig::Matrix<Scalar,2,1> sample_centered;\n\t\t\tsample_centered <<\n\t\t\t\t\tstatic_cast<Scalar>(x_sample) - voxel_image(0),\n\t\t\t\t\tstatic_cast<Scalar>(y_sample) - voxel_image(1);\n\t\t\tScalar dist_sq = sample_centered.transpose() * ellipse_matrix * sample_centered;\n\t\t\tif (dist_sq > squared_radius_threshold) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tScalar weight = std::exp(static_cast<Scalar>(-0.5) * dist_sq);\n\t\t\tScalar surface_depth = static_cast<Scalar>(depth_image(y_sample, x_sample)) * depth_unit_ratio;\n\t\t\tif (surface_depth <= static_cast<Scalar>(0.0)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tScalar signed_distance = surface_depth - voxel_camera[2];\n\t\t\tTSDF_sum += weight * compute_TSDF_value(signed_distance, narrow_band_half_width);\n\t\t\tweights_sum += weight;\n\t\t}\n\t}\n\n\tif (weights_sum == static_cast<Scalar>(0.0)) {\n\t\treturn static_cast<Scalar>(1.0);\n\t}\n\n\treturn TSDF_sum / weights_sum;\n}\n\ntemplate<typename Scalar>\ninline\nScalar compute_voxel_EWA_voxel_space_inclusive(\n\t\tconst math::Extent2d& sampling_bounds,\n\t\tconst eig::Matrix<Scalar,2,1>& voxel_image,\n\t\tconst eig::Matrix<Scalar,3,1>& voxel_camera,\n\t\tconst eig::Matrix<Scalar,2,2>& ellipse_matrix,\n\t\tconst Scalar& squared_radius_threshold,\n\t\tconst Scalar& depth_unit_ratio,\n\t\tconst Scalar& narrow_band_half_width,\n\t\tconst eig::Matrix<uint16_t, eig::Dynamic, eig::Dynamic>& depth_image){\n\tScalar weights_sum = static_cast<Scalar>(0.0);\n\tScalar TSDF_sum = static_cast<Scalar>(0.0);\n\n\t// collect sample readings\n\tfor (int x_sample = sampling_bounds.x_start; x_sample < sampling_bounds.x_end; x_sample++) {\n\t\tfor (int y_sample = sampling_bounds.y_start; y_sample < sampling_bounds.y_end; y_sample++) {\n\t\t\teig::Matrix<Scalar,2,1> sample_centered;\n\t\t\tsample_centered <<\n\t\t\t\t\tstatic_cast<Scalar>(x_sample) - voxel_image(0),\n\t\t\t\t\tstatic_cast<Scalar>(y_sample) - voxel_image(1);\n\t\t\tScalar dist_sq = sample_centered.transpose() * ellipse_matrix * sample_centered;\n\t\t\t//TODO: potential speedup -- remove range checking\n\t\t\tif (dist_sq > squared_radius_threshold) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tScalar weight = std::exp(static_cast<Scalar>(-0.5) * dist_sq);\n\n\t\t\tif (y_sample < 0 || y_sample >= depth_image.rows() ||\n\t\t\t\t\tx_sample < 0 || x_sample >= depth_image.cols()) {\n\t\t\t\tTSDF_sum += weight;  // (* 1.0)\n\t\t\t} else {\n\t\t\t\tScalar surface_depth = static_cast<Scalar>(depth_image(y_sample, x_sample)) * depth_unit_ratio;\n\t\t\t\tif (surface_depth <= static_cast<Scalar>(0.0)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tScalar signed_distance = surface_depth - voxel_camera[2];\n\t\t\t\tTSDF_sum += weight * compute_TSDF_value(signed_distance, narrow_band_half_width);\n\t\t\t}\n\t\t\tweights_sum += weight;\n\t\t}\n\t}\n\n\t//TODO: potential speedup -- is it even possible for this condition to be true?\n\tif (weights_sum == static_cast<Scalar>(0.0)) {\n\t\treturn static_cast<Scalar>(1.0);\n\t}\n\treturn TSDF_sum / weights_sum;\n}\n\n}//namespace tsdf\n\n\n", "meta": {"hexsha": "0b6b88247b600dbacab752bebb8897d0bcc16c64", "size": 9137, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tsdf/ewa_common.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/tsdf/ewa_common.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/tsdf/ewa_common.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.9128630705, "max_line_length": 123, "alphanum_fraction": 0.7317500274, "num_tokens": 2426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5207769730027064}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// non_parametric::kolmogorov_smirnov::check_convergence.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_STATISTICS_DETAIL_NON_PARAMETRIC_KOLMOGOROV_SMIRNOV_CHECK_CONVERGENCE_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_KOLMOGOROV_SMIRNOV_CHECK_CONVERGENCE_HPP_ER_2009\n\n#include <boost/mpl/copy.hpp>\n#include <boost/mpl/back_inserter.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/numeric/conversion/bounds.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/parameters/accumulator.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/framework/accumulator_set.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n\n#include <boost/statistics/detail/non_parametric/empirical_distribution/ordered_sample.hpp>\n#include <boost/statistics/detail/non_parametric/kolmogorov_smirnov/statistic.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace empirical_distribution{\n\n    // Usage:\n    //     check_convergence<> check;\n    //     check(n_loops,n,n_factor,distribution,random_generator,os);\n    // Generates random samples of size { k = n^p : p=1,...,n_loops} and for\n    // each computes the kolmogorov-smirnov statistic. The results are passed\n    // to os.\n    template<\n    \ttypename T1 = double,\n    \ttypename MoreFeatures = boost::accumulators::stats<>\n    >\n    struct check_convergence\n    {\n    \n    \ttypedef T1 value_type;\n        typedef kolmogorov_smirnov::tag::kolmogorov_smirnov tag_;\n    \ttypedef boost::accumulators::stats<tag_> stats_;\n    \ttypedef boost::mpl::push_back<boost::mpl::_,boost::mpl::_> op_;\n    \n       \ttypedef typename boost::mpl::copy<\n        \tMoreFeatures,boost::mpl::back_inserter< stats_ >\n    \t>::type mpl_features;\n    \n    \tpublic:\n    \n    \tcheck_convergence(){}\n\n        template<typename D,typename G>\n        struct traits{\n            typedef typename D::value_type val_;\n            typedef typename G::distribution_type random_;\n            typedef typename random_::result_type sample_type; \n\n            typedef boost::accumulators::accumulator_set<\n            \tsample_type,\n                typename mpl_features::type\n            > acc_;\n        };\n    \n        template<typename D,typename G>\n        typename traits<D,G>::acc_\n        operator()(\n            long n_loops,\n            long n, \t\t\t// n *= n_factor at each loop\n            long n_factor, \n            const D& dist,\t\n            G& gen,\n            std::ostream& os\n        )const{\n            return (*this)(\n            \tboost::mpl::void_(),\n            \tn_loops, \n                n, \n                n_factor, \n                dist, \n                gen, \n                default_fun<D>(),\n                os\n            );\n        }\n\n        template<\n            typename Args,\n            typename D,\n            typename G,\n            typename F,\n            typename Out\n        >\n        typename traits<D,G>::acc_\n        operator()(\n            const Args& args,\n            long n_loops,\n            long n, // n *= n_factor at each loop\n            long n_factor, \n            const D& dist,\n            G& gen,\n            const F& fun,\n            Out& out\n        )const{\n            typedef traits<D,G> traits_;\n            typedef typename traits_::val_ val_;\n            typedef typename traits_::random_ random_;\n            typedef typename traits_::sample_type sample_type;\n            typedef typename traits_::acc_ acc_;\n            \n            acc_ acc(args);\n        \n            for(long i1 = 0; i1<n_loops; i1++){\n                for(long i2 = 0; i2< n; i2++){\n                    sample_type x = gen();\n                    acc(x);\n                } // grows sample by n\n\t\t\t\t\n                fun(acc,dist,out);                \n                n *= n_factor;\n            }\n            \n            return acc;\n        }\n\n        template<typename D>\n    \tstruct default_fun{\n\n            typedef boost::numeric::bounds<value_type> bounds_;\n\n            default_fun() : ks0( bounds_::highest() ){}\n\t\t\n            template<typename AccSet>\n            void operator()(const AccSet& acc,const D& d,std::ostream& os)const{\n                namespace ns = kolmogorov_smirnov;\n            \tvalue_type ks1 = ns::statistic<value_type>( acc, d );\n                bool ok = ks1 - ks0 < bounds_::smallest(); \n                os \n                    << '('\n                    << boost::accumulators::extract::count(acc) \n                    << ','\n                    << ks1\n                    << ','\n                    << ok\n                    << ')'\n                    << std::endl;\t    \n            }\n\n            private:\n            mutable value_type ks0;\n\n    \t};\n    \n    };\n    \n}// empirical_distribution\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "79fc5197efbaf57607a3fe8ea7b90b650696572e", "size": 5489, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/kolmogorov_smirnov/check_convergence.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": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/kolmogorov_smirnov/check_convergence.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": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/kolmogorov_smirnov/check_convergence.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": 32.8682634731, "max_line_length": 95, "alphanum_fraction": 0.5296046639, "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.5207769507490181}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_FUNCTIONS_SIMD_COMMON_SINC_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_FUNCTIONS_SIMD_COMMON_SINC_HPP_INCLUDED\n\n#include <nt2/trigonometric/functions/sinc.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/divides.hpp>\n#include <nt2/include/functions/simd/sin.hpp>\n#include <nt2/include/functions/simd/is_eqz.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#if !defined(BOOST_SIMD_NO_DENORMALS)\n#include <nt2/include/functions/simd/abs.hpp>\n#include <nt2/include/functions/simd/is_less.hpp>\n#include <nt2/include/constants/eps.hpp>\n#endif\n\n#if !defined(BOOST_SIMD_NO_INFINITIES)\n#include <nt2/include/functions/simd/if_zero_else.hpp>\n#include <nt2/include/functions/simd/is_inf.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( sinc_, boost::simd::tag::simd_\n                            , (A0)(X)\n                            , ((simd_<floating_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      result_type r1 =  nt2::sin(a0)/a0;\n\n      #if !defined(BOOST_SIMD_NO_DENORMALS)\n      r1 = nt2::if_else ( nt2::lt(nt2::abs(a0), nt2::Eps<A0>())\n                        , nt2::One<A0>()\n                        , r1\n                        );\n      #else\n      r1 = nt2::if_else(nt2::is_eqz(a0), nt2::One<result_type>(), r1);\n      #endif\n\n      #if !defined(BOOST_SIMD_NO_INFINITIES)\n      r1 = nt2::if_zero_else(nt2::is_inf(a0), r1);\n      #endif\n\n      return r1;\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "f4cd8ca722f0d8d6700bb42217e82d87f8097594", "size": 2067, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/simd/common/sinc.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/simd/common/sinc.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/trigonometric/include/nt2/trigonometric/functions/simd/common/sinc.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 33.3387096774, "max_line_length": 80, "alphanum_fraction": 0.5858732463, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5207519606511991}}
{"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_ARCH_COMMON_SCALAR_FUNCTION_ATANH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ATANH_HPP_INCLUDED\n#include <boost/simd/function/std.hpp>\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/bitofsign.hpp>\n#include <boost/simd/function/bitwise_xor.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/log1p.hpp>\n#include <boost/simd/function/oneminus.hpp>\n#include <boost/simd/function/raw.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( atanh_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 absa0 = bs::abs(a0);\n      A0 t =  absa0+absa0;\n      A0 z1 = oneminus(absa0);\n      return bitwise_xor(bitofsign(a0),\n                         Half<A0>()*log1p((absa0 < Half<A0>())\n                                          ? fma(t, absa0/z1, t)\n                                          : t/z1)\n                        );\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( atanh_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator() (const std_tag &,  A0  a0) const BOOST_NOEXCEPT\n    {\n      return std::atanh(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( atanh_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::raw_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator() (const raw_tag &,  A0  a0) const BOOST_NOEXCEPT\n    {\n       return  Half<A0>()*log(inc(a0)/oneminus(a0));\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "4869033b67e134e80ba3e693b5c217a431fb2974", "size": 2534, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/atanh.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/arch/common/scalar/function/atanh.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/arch/common/scalar/function/atanh.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.675, "max_line_length": 100, "alphanum_fraction": 0.5027624309, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5207519550740048}}
{"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#include \"math/regression.h\"\n#include \"math/statistics.h\"\n#include \"sensors/sensor_log.h\"\n#include <boost/range/iterator_range.hpp>\n#include <cassert>\n#include <gnuplot-iostream.h>\n#include <iostream>\n\nusing namespace vulcan;\n\nusing LaserIt = sensors::SensorLog::laser_iterator;\n\nvoid estimate_sensor_noise(const std::string& laserName, LaserIt begin, LaserIt end);\n\n\nint main(int argc, char** argv)\n{\n    sensors::SensorLog log(argv[1]);\n\n    if (log.sizeFrontLaser() == 0) {\n        return -1;\n    }\n\n    if (log.sizeBackLaser() == 0) {\n        return -1;\n    }\n\n    estimate_sensor_noise(\"front\", log.beginFrontLaser(), log.endFrontLaser());\n    estimate_sensor_noise(\"back\", log.beginBackLaser(), log.endBackLaser());\n\n    return 0;\n}\n\n\nvoid estimate_sensor_noise(const std::string& laserName, LaserIt begin, LaserIt end)\n{\n    using ValueVec = std::vector<double>;\n    std::vector<ValueVec> values(begin->ranges.size());\n\n    for (auto& scan : boost::make_iterator_range(begin, end)) {\n        assert(values.size() == scan.ranges.size());\n        for (std::size_t n = 0; n < scan.ranges.size(); ++n) {\n            if ((scan.ranges[n] > 0.0f) && (scan.ranges[n] < 40.0f)) {\n                values[n].push_back(scan.ranges[n]);\n            }\n        }\n    }\n\n    std::vector<double> means;\n    std::vector<double> variances;\n\n    for (auto& v : values) {\n        means.push_back(math::mean(v.begin(), v.end()));\n        variances.push_back(std::sqrt(math::variance(v.begin(), v.end())));\n    }\n\n    std::vector<Point<float>> meanVsVar;\n    for (std::size_t n = 0; n < means.size(); ++n) {\n        // Toss out high std dev as they must have hit something dynamic\n        //         if(variances[n] < 0.2)\n        //         {\n        meanVsVar.emplace_back(means[n], variances[n]);\n        //         }\n    }\n\n    auto line = math::total_least_squares(meanVsVar.begin(), meanVsVar.end());\n    std::cout << \"Line fit:\" << line << '\\n';\n\n    Gnuplot plot;\n    plot << \"plot '-' using 1:2 with points title 'Laser: \" << laserName << \"'\\n\";\n    plot.send1d(boost::make_tuple(means, variances));\n}\n", "meta": {"hexsha": "9312cd7c5b1b0b5f3ed2f4df9bb23c36a9e75782", "size": 2460, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/laser/estimate_laser_noise.cpp", "max_stars_repo_name": "anuranbaka/Vulcan", "max_stars_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T23:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T19:06:50.000Z", "max_issues_repo_path": "src/laser/estimate_laser_noise.cpp", "max_issues_repo_name": "anuranbaka/Vulcan", "max_issues_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-07T01:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-07T01:23:47.000Z", "max_forks_repo_path": "src/laser/estimate_laser_noise.cpp", "max_forks_repo_name": "anuranbaka/Vulcan", "max_forks_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-03T07:54:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T07:54:16.000Z", "avg_line_length": 30.0, "max_line_length": 95, "alphanum_fraction": 0.6296747967, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.5207519546114832}}
{"text": "#ifndef EXPSUM_REDUCTION_BALANCED_TRUNCATION_HPP\n#define EXPSUM_REDUCTION_BALANCED_TRUNCATION_HPP\n\n#include <cassert>\n\n#include <armadillo>\n\n#include \"expsum/reduction/cholesky_quasi_cauchy.hpp\"\n#include \"expsum/reduction/coneig_sym_rrd.hpp\"\n\nnamespace expsum\n{\n\ntemplate <typename T>\nclass balanced_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 index_vector_type   = arma::uvec;\n    using real_vector_type    = arma::Col<real_type>;\n    using complex_vector_type = arma::Col<complex_type>;\n\n    using matrix_type         = arma::Mat<value_type>;\n    using real_matrix_type    = arma::Mat<real_type>;\n    using complex_matrix_type = arma::Mat<complex_type>;\n\nprivate:\n    size_type size_;\n    vector_type exponent_;\n    vector_type weight_;\n\n    index_vector_type ipiv_;\n    vector_type work_;\n    real_vector_type rwork_;\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 tol);\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            ipiv_.set_size(n);\n            work_.set_size(std::max(n * (n + 6), n * (3 * n + 1)));\n            rwork_.set_size(arma::is_complex<T>::value ? 3 * n : n);\n        }\n    }\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\nprivate:\n    //\n    // Compute eigenvalue decomposition of (n x n) symmetric matrix A.\n    //\n    // @A On input, matrix A, on exit, A is overwritten.\n    // @d On exit, eigenvalues of matrix A\n    //\n    // --- for real matrix\n    //     workspace size (lwork): n * n\n    static void diagonalize(real_matrix_type& A, real_matrix_type& X,\n                            real_vector_type& d, real_type* work,\n                            size_type lwork, real_type* /*dummy*/)\n    {\n        char jobz = 'V';\n        char uplo = 'U';\n\n        auto n_     = arma::blas_int(A.n_rows);\n        auto lwork_ = static_cast<arma::blas_int>(lwork);\n        auto info_  = arma::blas_int();\n\n        arma::lapack::syev(&jobz, &uplo, &n_, A.memptr(), &n_, d.memptr(), work,\n                           &lwork_, &info_);\n        if (info_)\n        {\n            std::ostringstream msg;\n            msg << \"[s/d]SYEV error: failed with info \" << info_;\n            throw std::logic_error(msg.str());\n        }\n\n        X = A;\n    }\n\n    // --- for complex matrix\n    //     workspace size (lwork): n * n\n    //     real workspace size: 2 * n\n    static void diagonalize(complex_matrix_type& A, complex_matrix_type& X,\n                            complex_vector_type& d, complex_type* work,\n                            size_type lwork, real_type* rwork)\n    {\n        char jobvl = 'N'; // Do not compute left eigenvectors of A\n        char jobvr = 'V'; // Compute right eigenvectors of A\n\n        complex_type vl[2]; // dummy\n\n        auto n_     = arma::blas_int(A.n_rows);\n        auto ldvl_  = arma::blas_int(1);\n        auto lwork_ = static_cast<arma::blas_int>(lwork);\n        auto info_  = arma::blas_int();\n\n        complex_type* work_ = work + A.n_elem;\n\n        arma::lapack::cx_geev(&jobvl, &jobvr, &n_, A.memptr(), &n_, d.memptr(),\n                              &vl[0], &ldvl_, X.memptr(), &n_, work_, &lwork_,\n                              rwork, &info_);\n        if (info_)\n        {\n            std::ostringstream msg;\n            msg << \"[c/z]GEEV error: failed with info \" << info_;\n            throw std::logic_error(msg.str());\n        }\n\n        for (size_type j = 0; j < X.n_cols; ++j)\n        {\n            auto xj          = X.col(j);\n            const auto t     = arma::dot(xj, xj);\n            const auto scale = value_type(1) / std::sqrt(t);\n            xj *= scale;\n        }\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\nbalanced_truncation<T>::run(const VecP& p, const VecW& w, real_type tol)\n{\n    using cholesky_rrd = cholesky_quasi_cauchy<value_type>;\n\n    assert(p.n_elem == w.n_elem);\n\n    const auto n = p.n_elem;\n    resize(n);\n    if (n <= size_type(1))\n    {\n        // Quick return\n        return;\n    }\n\n    value_type* ptr_X = work_.memptr();\n    value_type* ptr_a = ptr_X + n * n;\n    real_type* ptr_d  = reinterpret_cast<real_type*>(exponent_.memptr());\n\n    //\n    // Set the factors that defines the quasi-Cauchy matrix\n    //\n    //   P(i, j) = a[i] * b[j] /(x[i] + y[j]),\n    //   a[i] = sqrt(w[i]),\n    //   b[i] = sqrt(conj(p[i])),\n    //   x[i] = p[i],\n    //   y[i] = conj(p[i]),\n    //\n    // which is the controllability Gramian matrix of the system.\n    //\n    vector_type a(ptr_a + 0 * n, n, false, true);\n    vector_type b(ptr_a + 1 * n, n, false, true);\n    vector_type x(ptr_a + 2 * n, n, false, true);\n    vector_type y(ptr_a + 3 * n, n, false, true);\n    vector_type work1(ptr_a + 4 * n, n, false, true);\n    vector_type work2(ptr_a + 5 * n, n, false, true);\n\n    a = arma::sqrt(w);\n    b = arma::conj(a);\n    x = p;\n    y = arma::conj(x);\n\n    //\n    // Rank-revealing Cholesky factorization of Gramian matrix given as\n    //\n    // P = X * D^2 * X.t()\n    //\n    // Cholesky factorization can be computed accurately using the Gaussian\n    // elimination with complete pivoting (GECP).\n    //\n    index_vector_type ipiv(ipiv_.memptr(), n, false, true);\n    size_ = cholesky_rrd::pivot_order(a, b, x, y, tol, ipiv, work1);\n\n    matrix_type X1(ptr_X, n, size_, false, true);\n    real_vector_type d(ptr_d, size_, false, true);\n\n    cholesky_rrd::factorize(a, b, x, y, X1, d, work1, work2);\n    cholesky_rrd::apply_row_permutation(X1, ipiv, work1);\n\n    //\n    // Compute the state-space transformation matrix.\n    //\n    // First compute eigenvalue decomposition of L * Q * L.t(), where Q is\n    // observability Gramian matrix of the system, which can be obtained as\n    // Q = P.st()\n    //\n    // Let us define\n    //\n    //   G = D * X.st() * X * D,\n    //\n    // then eigenvalue decomposition\n    //\n    //   L * Q * L.t() = G.t() * G = X * S^2 * X.t().\n    //\n    // As described by Haut and Beylkin (2011), the eigenvectors of G.t() * G\n    // become con-eigenvectors of matrix P, i.e.,\n    //\n    //   P = conj(X) * S * X.t().\n    //\n    // where the matrix X is (complex) orthogonal, X.t() * X = I\n    //\n    // The matrix conj(X) is the desired transformation matrix of the system.\n    //\n    // `coneig_sym_rrd` computes only the con-eigenvalues greater than the\n    // target accuracy `tol` and corresponding con-eigenvectors.\n    //\n    // NOTE: Required memory for workspace\n    //\n    // work size : 2 * n * (n + 1)\n    // rwork size:\n    //    if `T` is real type   : n\n    //    if `T` is complex type: 3 * n\n    //\n    const auto k = coneig_sym_rrd<T>::run(X1, d, tol, ptr_a, rwork_.memptr());\n    //\n    // Apply transformation matrix\n    //\n    // A1 = Xk.t() * diagmat(a) * conj(Xk)\n    // b1 = Xk.t() * b\n    // c1 = b.st() * conj(Xk) = b1.st()\n    //\n    // where Xk = X1.head_cols(k) that satisfies X_k.st() * X_k = I_k\n    //\n    auto Xk = X1.head_cols(k);\n    matrix_type A1(ptr_a, k, k, false, true);\n    vector_type p_(exponent_.memptr(), k, false, true);\n    vector_type w_(weight_.memptr(), k, false, true);\n    A1 = Xk.t() * arma::diagmat(p) * arma::conj(Xk);\n    w_ = Xk.t() * arma::sqrt(w);\n\n    //\n    // Compute eigenvalue decomposition of the (k x k) matrix, A1. Since A1 is\n    // real/complex symmetric matrix, the eigen decomposition has the form\n    //\n    //   A1 = X2 * D * X2.st(), (X2.st() * X2 = I).\n    //\n    matrix_type X2(ptr_X, k, k, false, true);\n    diagonalize(A1, X2, p_, ptr_a + n * n, n * n, rwork_.memptr());\n\n    //\n    // Apply the state space transformation by X2,\n    //\n    // A2 = X2.st() * A1 * X2 = D\n    // b2 = X2.st() * b1\n    // c2 = b1 * X2 = b2.st()\n    //\n    // Finally parameters for truncated exponential sum can be obtained as\n    //\n    // p' = A2 = diag(D)\n    // w' = c2 % b2 = square(b2)\n    //\n    size_     = k;\n    A1.col(0) = w_;\n    w_        = X2.st() * A1.col(0);\n    w_        = arma::square(w_);\n\n    return;\n}\n\n} // namespace: expsum\n\n#endif /* EXPSUM_REDUCTION_BALANCED_TRUNCATION_HPP */\n", "meta": {"hexsha": "4bca4fd7b335a7c43554fea9e0bc6a8d6e1b15bc", "size": 8938, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/reduction/balanced_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/reduction/balanced_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/reduction/balanced_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": 30.0942760943, "max_line_length": 80, "alphanum_fraction": 0.5540389349, "num_tokens": 2594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.5207519546114832}}
{"text": "/* Copyright (c) 2018, Skolkovo Institute of Science and Technology (Skoltech)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\n * planeRegistration.hpp\n *\n *  Created on: Jan 28, 2019\n *      Author: Gonzalo Ferrer\n *              g.ferrer@skoltech.ru\n *              Mobile Robotics Lab, Skoltech\n */\n\n#ifndef PLANEREGISTRATION_HPP_\n#define PLANEREGISTRATION_HPP_\n\n#include <vector>\n#include \"mrob/SE3.hpp\"\n#include <Eigen/StdVector>\n#include \"mrob/plane.hpp\"\n#include \"mrob/optimizer.hpp\"\n#include \"mrob/time_profiling.hpp\"\n\n#include <unordered_map>\n#include <memory>\n\n\nnamespace mrob{\n\n/**\n * class PlaneRegistration introduced a class for the alignment of\n * planes.\n */\nclass PlaneRegistration: public OptimizerDense{\n\n  public:\n    // XXX is this mode used anymore? deprecated?\n    enum TrajectoryMode{SEQUENCE=0, INTERPOLATION};\n    // XXX Solve method is almost deprecated\n    //enum SolveModeGrad{GRADIENT_DESCENT_NAIVE=0, GRADIENT_DESCENT_INCR, STEEPEST, HEAVYBALL, MOMENTUM, MOMENTUM_SEQ, BENGIOS_NAG, GRADIENT_DESCENT_BACKTRACKING, BFGS};\n    enum SolveMode{INITIALIZE=0,\n                   GRADIENT,\n                   GRADIENT_BENGIOS_NAG,\n                   GRADIENT_ALL_POSES,\n                   GN_HESSIAN,\n                   GN_CLAMPED_HESSIAN,\n                   LM_SPHER,\n                   LM_ELLIP};\n\n  public:\n    PlaneRegistration();\n    //PlaneRegistration(uint_t numberPlanes , uint_t numberPoses);\n    ~PlaneRegistration();\n\n    // Function from the parent class Optimizer\n    virtual matData_t calculate_error() override;\n    virtual void calculate_gradient_hessian() override;\n    virtual void update_state() override;\n    virtual void bookkeep_state() override;\n    virtual void update_state_from_bookkeep() override;\n\n\n    // Specific methods\n    void set_number_planes_and_poses(uint_t numPlanes, uint_t numPoses);\n    uint_t get_number_planes() const {return numberPlanes_;};\n    uint_t get_number_poses() const {return numberPoses_;};\n\n    /**\n     * solve() calculates the poses on trajectory such that the minimization objective\n     * is met: J = sum (lamda_min_plane)\n     */\n    uint_t solve(SolveMode mode, bool singleIteration = false);\n    /**\n     * solve_interpolate() calculates the poses on trajectory such that the minimization objective\n     * is met: J = sum (lamda_min_plane), and the trajectory is described as an interpolation from I to T_f\n     */\n    uint_t solve_interpolate_gradient(bool singleIteration = false);\n    //Gradient for all poses\n    uint_t solve_gradient_all_poses(bool singleIteration = false);\n    /**\n     * solve_interpolate_hessian() calculates the poses on trajectory such that the minimization objective\n     * is met: J = sum (lamda_min_plane), and the trajectory is described as an interpolation from I to T_f\n     * using second order methods with Hessian. Very similar to solve_interpolate\n     */\n    //uint_t solve_interpolate_hessian(bool singleIteration = false);\n    /**\n     * Initialization_solve give a first guess on all poses by using classical point-point\n     * methods SVD-based to calculate an initial condition closer to the true solution\n     */\n    uint_t solve_initialize();\n    /**\n     * Solve quaternion plane uses a paramteric representation for each plane, a quaternion,\n     * and optimizes both the plane parameters and the trajectory variables\n     */\n    uint_t solve_quaternion_plane();\n    /**\n     * reset_solution, resets the current calculated solution while maintainting all data (planes)\n     * This function is intended for comparing different solvers without replicating data\n     */\n    void reset_solution();\n    double get_current_error() const;\n    /**\n     * Get trajectory returns a SE3 transformations,\n     */\n    SE3 get_trajectory(uint_t time);\n\n    SE3 get_last_pose() {return trajectory_->back();}\n\n    /**\n     * Sets the trajectory (current solution) by addint the last pose\n     */\n    void set_last_pose(SE3 &last);\n\n    /**\n     * add_plane adds a plane structure already initialized and filled with data\n     */\n    void add_plane(uint_t id, std::shared_ptr<Plane> &plane);\n    /**\n     * add new plane is an ALTERNATIVE (for py) to the above function\n     * which creates a new plane inside the class and then points are added one by one\n     *\n     */\n    void add_new_plane(uint_t id);\n    /**\n     * add a point to the new plane. An ALTERNATIVE (for py) to add points into the sover\n     * class (instead of adding the point fully as in add_plane())\n     *\n     */\n    void plane_push_back_point(uint_t id, uint_t t, Mat31 &point);\n\n    uint_t calculate_total_number_points();\n    std::shared_ptr<Plane> & get_plane(uint_t id);\n\n    std::unordered_map<uint_t, std::shared_ptr<Plane>>& get_all_planes() {return planes_;};\n\n    void set_alpha_parameter(double alpha) {alpha_ = alpha;};\n    void set_beta_parameter(double beta) {beta_ = beta;};\n\n    double calculate_poses_rmse(std::vector<SE3> & groundTruth) const;\n\n    void print(bool plotPlanes = true) const;\n\n    /**\n     * print evaluate looks for degenerate cases, such as planes normal vectors,\n     * Hessian rank, det of all normals, etc. Basically this function tries to answer\n     * if the problem is ill-conditioned\n     *\n     * Returns: 0) current error\n     *          1) number of iters,\n     *          2) determinant\n     *          3) number of negative eigenvalues\n     *          4) conditioning number\n     */\n    std::vector<double> print_evaluate();\n\n    /**\n     * add point_cloud requires a complete set of points observed at a given time\n     * stamp (XXX now only an integer) and fills in the registration structure.\n     */\n    void add_point_cloud_planes(uint_t time, std::vector<Mat31>& points, std::vector<uint_t>& point_ids);\n    /**\n     * get_point_cloud gets all raw point, according to the current time index\n     * from trajectory. It does not distinguish between planes.\n     */\n    std::vector<Mat31> get_point_cloud(uint_t time);\n    std::vector<Mat31> get_point_plane_ids(uint_t time);\n\n  protected:\n    // flag for detecting when is has been solved\n    uint_t numberPlanes_, numberPoses_, numberPoints_;\n    uint_t isSolved_;\n    PlaneRegistration::TrajectoryMode trajMode_ {};\n    uint_t time_{};\n    std::unordered_map<uint_t, std::shared_ptr<Plane>> planes_;\n    std::shared_ptr<std::vector<SE3>> trajectory_;\n    SE3 bookept_trajectory_;//last pose is stored/bookept\n    double tau_ {};//variable for weighting the number of poses in traj\n    uint_t solveIters_ {};\n\n    // 1st order parameters methods if used\n    PlaneRegistration::SolveMode solveMode_;\n    std::vector<Mat61> previousState_;\n    double c1_, c2_;    //parameters for the Wolfe conditions DEPRECATED?\n    double alpha_, beta_;\n\n\n    //2nd order data (if used) TODO remove since they are defined in parent class\n    Mat61 gradient__;\n    Mat6 hessian__;\n\n    // time profiling\n    TimeProfiling time_profiles_;\n    double initial_error_ {}; // for benchmark purposes\n\n\n    // alternative structure to keep planes. This is only for the python bindings\n\n};\n\n\n\n}// namespace\n#endif /* PLANEREGISTRATION_HPP_ */\n", "meta": {"hexsha": "73ded3a9e8d7dc404524d32a07f1c297d3ffcc85", "size": 7627, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/PCRegistration/mrob/plane_registration.hpp", "max_stars_repo_name": "miloserdova-l/mrob", "max_stars_repo_head_hexsha": "48bef772ba3158d2122991069196d6efd4a39f8c", "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/mrob/plane_registration.hpp", "max_issues_repo_name": "MobileRoboticsSkoltech/mrob", "max_issues_repo_head_hexsha": "7668a3ee35345c4878aa86fff082cc017992d205", "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/mrob/plane_registration.hpp", "max_forks_repo_name": "MobileRoboticsSkoltech/mrob", "max_forks_repo_head_hexsha": "7668a3ee35345c4878aa86fff082cc017992d205", "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": 35.6401869159, "max_line_length": 169, "alphanum_fraction": 0.697128622, "num_tokens": 1792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5207519490342889}}
{"text": "// This file is part of SWGANH which is released under the MIT license.\n// See file LICENSE or go to http://swganh.com/LICENSE\n\n#include <anh/utility_python.h>\n#include <glm/glm.hpp>\n#include <glm/gtx/quaternion.hpp>\n\n#include <boost/python.hpp>\nusing namespace boost::python;\nnamespace anh\n{\nnamespace utilities\n{\nvoid define_class_glm_vec3()\n{\n\tclass_<glm::vec3>(\"vector3\",\n\t\t\"Stores a direction vector in three-dimensional space\", no_init)\n\t\t.def(init<glm::float_t, glm::float_t, glm::float_t>())\n\t\t.def(init<const glm::vec3&>())\n        .def_readwrite(\"x\", &glm::vec3::x)\n        .def_readwrite(\"y\", &glm::vec3::y)\n        .def_readwrite(\"z\", &glm::vec3::z)\n\t\t.def(\"__len__\", &utility::constant_len_len<glm::vec3, 3>)\n\t\t.def(\"__getitem__\", &utility::constant_len_get_item<glm::vec3, 3, glm::float_t>)\n\t\t.def(\"__setitem__\", &utility::constant_len_set_item<glm::vec3, 3, glm::float_t>)\n\t\t.def(self == self)\n\t\t.def(self != self)\n\t\t.def(self + self)\n\t\t.def(self - self)\n\t\t.def(self * glm::float_t())\n\t\t.def(glm::float_t() * self)\n\t\t.def(self += self)\n\t\t.def(self -= self)\n\t\t.def(self *= glm::float_t())\n\t\t.def(self /= glm::float_t());\n\t\t//.def(self_ns::str(self));\n}\nvoid define_class_glm_quat() \n{\n    class_<glm::quat>(\"quat\",\n\t\t\"Stores a quaternion\", no_init)\n\t\t.def(init<glm::float_t, glm::float_t, glm::float_t, glm::float_t>())\n\t\t.def(init<const glm::quat&>())\n        .def_readwrite(\"x\", &glm::quat::x)\n        .def_readwrite(\"y\", &glm::quat::y)\n        .def_readwrite(\"z\", &glm::quat::z)\n        .def_readwrite(\"w\", &glm::quat::w)\n\t\t.def(\"__len__\", &utility::constant_len_len<glm::quat, 4>)\n\t\t.def(\"__getitem__\", &utility::constant_len_get_item<glm::quat, 4, glm::float_t>)\n\t\t.def(\"__setitem__\", &utility::constant_len_set_item<glm::quat, 4, glm::float_t>)\n\t\t.def(self == self)\n\t\t.def(self != self)\n\t\t/*.def(self + self)\n\t\t.def(self - self)*/\n\t\t.def(self * glm::float_t())\n\t\t.def(glm::float_t() * self)\n\t\t/*.def(self += self)\n\t\t.def(self -= self)*/\n\t\t.def(self *= glm::float_t())\n\t\t.def(self /= glm::float_t());\n\t\t//.def(self_ns::str(self));\n}\n}} // namespace anh::utilities", "meta": {"hexsha": "a93e8a7c3d0d1bda210062e4792e65dbc095bbb3", "size": 2082, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/swganh/utilities/glm_binding.cc", "max_stars_repo_name": "JohnShandy/swganh", "max_stars_repo_head_hexsha": "d20d22a8dca2e9220a35af0f45f7935ca2eda531", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-25T16:02:17.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-25T16:02:17.000Z", "max_issues_repo_path": "src/swganh/utilities/glm_binding.cc", "max_issues_repo_name": "JohnShandy/swganh", "max_issues_repo_head_hexsha": "d20d22a8dca2e9220a35af0f45f7935ca2eda531", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/swganh/utilities/glm_binding.cc", "max_forks_repo_name": "JohnShandy/swganh", "max_forks_repo_head_hexsha": "d20d22a8dca2e9220a35af0f45f7935ca2eda531", "max_forks_repo_licenses": ["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.0476190476, "max_line_length": 82, "alphanum_fraction": 0.6349663785, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5207519436883558}}
{"text": "#pragma once\n#include <Eigen/Eigen>\n#include <nlohmann/json.hpp>\n\nclass TFIsing\n{\nprivate:\n\tint n_;\n\tdouble J_;\n\tdouble h_;\npublic:\n\tTFIsing(int n, double J, double h)\n\t\t: n_(n), J_(J), h_(h)\n\t{\n\t}\n\n\tnlohmann::json params() const\n\t{\n\t\treturn nlohmann::json\n\t\t{\n\t\t\t{\"name\", \"TFIsing\"},\n\t\t\t{\"n\", n_},\n\t\t\t{\"J\", J_},\n\t\t\t{\"h\", h_}\n\t\t};\n\t}\n\t\n\ttemplate<class State>\n\ttypename State::Scalar operator()(const State& smp) const\n\t{\n\t\ttypename State::Scalar s = 0.0;\n\t\t//Nearest-neighbor\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\ts += J_*smp.sigmaAt(i)*smp.sigmaAt((i+1)%n_);\n\t\t\ts += h_*smp.ratio(i);\n\t\t}\n\t\treturn s;\n\t}\n\n\tstd::vector< std::array<int, 1> > offDiagonals(const Eigen::VectorXi& s) const\n\t{\n\t\t(void)s;\n\t\tstd::vector< std::array<int, 1> > res;\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tres.push_back(std::array<int, 1>{i});\n\t\t}\n\t\treturn res;\n\t}\n\n\n\tstd::map<uint32_t, double> operator()(uint32_t col) const\n\t{\n\t\tstd::map<uint32_t, double> res;\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tint s1 = (col >> i) & 1;\n\t\t\tint s2 = (col >> ((i+1) % n_)) & 1;\n\t\t\tlong long int x = (1 << i);\n\t\t\tres[col ^ x] += h_;\n\t\t\tres[col] += J_*(1-2*s1)*(1-2*s2);\n\t\t}\n\t\treturn res;\n\t}\n};\n", "meta": {"hexsha": "4601c17d807607ce42363a4b53452c05ca2198dd", "size": 1149, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Hamiltonians/TFIsing.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/Hamiltonians/TFIsing.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/Hamiltonians/TFIsing.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": 17.1492537313, "max_line_length": 79, "alphanum_fraction": 0.5491731941, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.5207519434570949}}
{"text": "#ifndef _UBLAS_\n#define _UBLAS_\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#endif\n\n#ifndef _KMEANS_\n#define _KMEANS_\n\nusing namespace boost::numeric::ublas;\nusing namespace boost::numeric;\n\ndouble dist_xc /* \u30c7\u30fc\u30bf\u70b9x\u3068\u30af\u30e9\u30b9\u30bf\u4e2d\u5fc3c_j\u3068\u306e\u8ddd\u96e2 */\n(const ublas::matrix_row<const ublas::matrix<double> > x,\n const ublas::matrix<double> c,\n const unsigned int j)\n{\n  double sum = 0;\n  for(unsigned int d = 0; d < x.size(); ++d){\n    sum += (x[d] - c(j,d)) * (x[d] - c(j,d));    \n  }\n  return sqrt(sum);\n}\n\ndouble dist_cc /* \u30af\u30e9\u30b9\u30bf\u4e2d\u5fc3\u9593\u306e\u8ddd\u96e2\u3092\u8a08\u7b97 */\n(const ublas::matrix<double> mat1, const unsigned int r1,\n const ublas::matrix<double> mat2, const unsigned int r2) \n{\n  if(mat1.size2() != mat2.size2()){\n    return -1;\n  }else{\n    double sum = 0;\n    for(unsigned int i = 0; i < mat1.size2(); ++i){\n      sum += (mat1(r1, i) - mat2(r2, i)) * (mat1(r1, i) - mat2(r2, i));\n    }\n    return sqrt(sum);\n  }\n}\n\n#endif\n", "meta": {"hexsha": "777f0c84ed9b688e6f9a2134a0f4c50c334b8220", "size": 1016, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "program/kmeans.hpp", "max_stars_repo_name": "yk-tanigawa/201503_clustering", "max_stars_repo_head_hexsha": "43a11e707c08f1576e5765824c74330b6730e7e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "program/kmeans.hpp", "max_issues_repo_name": "yk-tanigawa/201503_clustering", "max_issues_repo_head_hexsha": "43a11e707c08f1576e5765824c74330b6730e7e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-26T16:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-26T16:53:14.000Z", "max_forks_repo_path": "program/kmeans.hpp", "max_forks_repo_name": "yk-tanigawa/201503_clustering", "max_forks_repo_head_hexsha": "43a11e707c08f1576e5765824c74330b6730e7e9", "max_forks_repo_licenses": ["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.5777777778, "max_line_length": 71, "alphanum_fraction": 0.6446850394, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5207519432258336}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include <CTraitsTest.h>\n#include <gtest/gtest.h>\n#include <mrpt/math/CSparseMatrix.h>\n#include <mrpt/random.h>\n\n#include <Eigen/Dense>\n\nusing namespace mrpt;\nusing namespace mrpt::math;\nusing namespace std;\n\ntemplate class mrpt::CTraitsTest<mrpt::math::CSparseMatrix>;\n\nvoid generateRandomSparseMatrix(\n\tsize_t N, size_t M, size_t nEntries, CSparseMatrix& MAT)\n{\n\tMAT.clear();\n\n\tMAT.setRowCount(N);\n\tMAT.setColCount(M);\n\n\tfor (size_t i = 0; i < nEntries; i++)\n\t{\n\t\tMAT.insert_entry(\n\t\t\tmrpt::random::getRandomGenerator().drawUniform32bit() % N,\n\t\t\tmrpt::random::getRandomGenerator().drawUniform32bit() % M,\n\t\t\tmrpt::random::getRandomGenerator().drawGaussian1D(0, 1));\n\t}\n\n\t// Return already compressed:\n\tMAT.compressFromTriplet();\n}\n\nvoid do_test_init_to_unit(size_t N)\n{\n\tCMatrixDouble dense1;\n\tdense1.setIdentity(N);\n\n\tCSparseMatrix SM(dense1);\n\n\tCMatrixDouble dense_out;\n\tSM.get_dense(dense_out);\n\n\tEXPECT_TRUE(dense_out == dense1) << \"Failed with N=\" << N << \"\\n\";\n}\n\nTEST(SparseMatrix, InitFromDenseUnit)\n{\n\tdo_test_init_to_unit(1);\n\tdo_test_init_to_unit(10);\n\tdo_test_init_to_unit(100);\n}\n\nvoid do_test_init_random(size_t N)\n{\n\tCMatrixDouble dense1(N, N);\n\tmrpt::random::getRandomGenerator().drawGaussian1DMatrix(dense1);\n\tCSparseMatrix SM(dense1);\n\tCMatrixDouble dense_out;\n\tSM.get_dense(dense_out);\n\tEXPECT_TRUE(dense_out == dense1) << \"Failed with N=\" << N << \"\\n\";\n}\n\nTEST(SparseMatrix, InitFromDenseRandom)\n{\n\tdo_test_init_random(1);\n\tdo_test_init_random(10);\n\tdo_test_init_random(100);\n}\n\nTEST(SparseMatrix, InitFromTriplet)\n{\n\tCSparseMatrix SM;\n\tCMatrixDouble D(10, 20);\n\n\tSM.insert_entry(2, 2, 4.0);\n\tD(2, 2) = 4.0;\n\tSM.insert_entry(6, 8, -2.0);\n\tD(6, 8) = -2.0;\n\n\tSM.setRowCount(10);\n\tSM.setColCount(20);\n\n\tCMatrixDouble dense_out1;\n\tSM.get_dense(dense_out1);\n\n\tSM.compressFromTriplet();\n\n\tCMatrixDouble dense_out2;\n\tSM.get_dense(dense_out2);\n\n\tEXPECT_TRUE(dense_out1 == dense_out2);\n}\n\nTEST(SparseMatrix, InitFromSparse)\n{\n\tCMatrixDouble D(4, 5);\n\tmrpt::math::CSparseMatrixTemplate<double> S(4, 5);\n\tD(1, 2) = 2.0;\n\tS(1, 2) = 2.0;\n\n\tD(3, 1) = -7.0;\n\tS(3, 1) = -7.0;\n\n\tCSparseMatrix SM(S);\n\tCMatrixDouble dense_out;\n\tSM.get_dense(dense_out);\n\tEXPECT_TRUE(dense_out == D) << \"Dense: \\n\"\n\t\t\t\t\t\t\t\t<< D << \"Sparse:\\n\"\n\t\t\t\t\t\t\t\t<< dense_out << endl;\n}\n\nTEST(SparseMatrix, InitFromRandom)\n{\n\tCSparseMatrix SM;\n\tgenerateRandomSparseMatrix(100, 100, 25, SM);\n\tgenerateRandomSparseMatrix(20, 10, 15, SM);\n}\n\nusing TMatrixSMOperator = void (*)(\n\tconst CSparseMatrix& M1, const CSparseMatrix& M2, CSparseMatrix& res);\nusing TMatrixDenseOperator = void (*)(\n\tconst CMatrixDouble& M1, const CMatrixDouble& M2, CMatrixDouble& res);\n\nvoid do_matrix_op_test(\n\tsize_t nRows1, size_t nCols1, size_t nNonZeros1, size_t nRows2,\n\tsize_t nCols2, size_t nNonZeros2, TMatrixSMOperator op1,\n\tTMatrixDenseOperator op2)\n{\n\tCSparseMatrix SM1, SM2;\n\tgenerateRandomSparseMatrix(nRows1, nCols1, nNonZeros1, SM1);\n\tgenerateRandomSparseMatrix(nRows2, nCols2, nNonZeros2, SM2);\n\n\tCSparseMatrix SM_res;\n\t(*op1)(SM1, SM2, SM_res);\n\n\t// Check:\n\tCMatrixDouble D1, D2, Dres;\n\tSM1.get_dense(D1);\n\tSM2.get_dense(D2);\n\tSM_res.get_dense(Dres);\n\n\tCMatrixDouble RES;\n\t(*op2)(D1, D2, RES);\n\n\tconst double err = (RES - Dres).array().abs().maxCoeff();\n\n\tEXPECT_TRUE(err < 1e-10) << \"M1:\\n\"\n\t\t\t\t\t\t\t << D1 << \"M2:\\n\"\n\t\t\t\t\t\t\t << D2 << \"Real op result:\\n\"\n\t\t\t\t\t\t\t << RES << \"SM result:\\n\"\n\t\t\t\t\t\t\t << Dres << \"ERR:\\n\"\n\t\t\t\t\t\t\t << (RES - Dres);\n}\n\nvoid op_sparse_add(\n\tconst CSparseMatrix& M1, const CSparseMatrix& M2, CSparseMatrix& res)\n{\n\tres = M1 + M2;\n}\nvoid op_dense_add(\n\tconst CMatrixDouble& M1, const CMatrixDouble& M2, CMatrixDouble& res)\n{\n\tres = M1 + M2;\n}\n\nTEST(SparseMatrix, Op_Add)\n{\n\tdo_matrix_op_test(1, 1, 0, 1, 1, 0, &op_sparse_add, &op_dense_add);\n\tdo_matrix_op_test(1, 1, 1, 1, 1, 1, &op_sparse_add, &op_dense_add);\n\tdo_matrix_op_test(2, 2, 1, 2, 2, 1, &op_sparse_add, &op_dense_add);\n\tdo_matrix_op_test(10, 20, 33, 10, 20, 33, &op_sparse_add, &op_dense_add);\n\tdo_matrix_op_test(11, 21, 34, 11, 21, 34, &op_sparse_add, &op_dense_add);\n}\n\nvoid op_sparse_multiply_AB(\n\tconst CSparseMatrix& M1, const CSparseMatrix& M2, CSparseMatrix& res)\n{\n\tres = M1 * M2;\n}\nvoid op_dense_multiply_AB(\n\tconst CMatrixDouble& M1, const CMatrixDouble& M2, CMatrixDouble& res)\n{\n\tif (M1.isSquare() && M2.isSquare()) res = M1 * M2;\n\telse\n\t\tres = M1.asEigen() * M2.asEigen();\n}\n\nTEST(SparseMatrix, Op_Multiply_AB)\n{\n\tdo_matrix_op_test(\n\t\t1, 1, 0, 1, 1, 0, &op_sparse_multiply_AB, &op_dense_multiply_AB);\n\tdo_matrix_op_test(\n\t\t1, 1, 1, 1, 1, 1, &op_sparse_multiply_AB, &op_dense_multiply_AB);\n\tdo_matrix_op_test(\n\t\t2, 2, 1, 2, 2, 1, &op_sparse_multiply_AB, &op_dense_multiply_AB);\n\tdo_matrix_op_test(\n\t\t10, 20, 33, 20, 15, 33, &op_sparse_multiply_AB, &op_dense_multiply_AB);\n\tdo_matrix_op_test(\n\t\t8, 34, 100, 34, 3, 100, &op_sparse_multiply_AB, &op_dense_multiply_AB);\n}\n\nTEST(SparseMatrix, CholeskyDecomp)\n{\n\tCSparseMatrix SM(10, 10);\n\tconst auto COV1 = mrpt::random::getRandomGenerator()\n\t\t\t\t\t\t  .drawDefinitePositiveMatrix<CMatrixDouble>(6, 0.2);\n\tconst auto COV2 = mrpt::random::getRandomGenerator()\n\t\t\t\t\t\t  .drawDefinitePositiveMatrix<CMatrixDouble>(4, 0.2);\n\n\tSM.insert_submatrix(0, 0, COV1);\n\tSM.insert_submatrix(6, 6, COV2);\n\tSM.compressFromTriplet();\n\n\tCSparseMatrix::CholeskyDecomp Chol(SM);\n\n\tconst CMatrixDouble L = Chol.get_L();  // lower triangle\n\n\t// Compare with the dense matrix implementation:\n\tCMatrixDouble D;\n\tSM.get_dense(D);\n\n\tCMatrixDouble Ud;  // Upper triangle\n\tD.chol(Ud);\n\n\tconst double err = (Ud.transpose() - L.asEigen()).array().abs().mean();\n\tEXPECT_TRUE(err < 1e-8);\n}\n", "meta": {"hexsha": "cde71b96de4b344b9c1f77e19c4981aaf49e5629", "size": 6186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/src/CSparseMatrix_unittest.cpp", "max_stars_repo_name": "wstnturner/mrpt", "max_stars_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T05:24:26.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-17T00:30:02.000Z", "max_issues_repo_path": "libs/math/src/CSparseMatrix_unittest.cpp", "max_issues_repo_name": "wstnturner/mrpt", "max_issues_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T22:43:00.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-17T18:52:59.000Z", "max_forks_repo_path": "libs/math/src/CSparseMatrix_unittest.cpp", "max_forks_repo_name": "wstnturner/mrpt", "max_forks_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T12:32:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-30T15:50:13.000Z", "avg_line_length": 25.9915966387, "max_line_length": 80, "alphanum_fraction": 0.6647268025, "num_tokens": 1985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5206834613685051}}
{"text": "#pragma once\n#include <Eigen/Geometry>\n#include \"mtao/types.hpp\"\n#include \"mtao/colvector_loop.hpp\"\n\n\nnamespace mtao { namespace geometry {\n    template <typename T, int D> using BBox = Eigen::AlignedBox<T,D>;\n    template <typename T, int D>\n        auto bounding_box(const mtao::ColVectors<T,D>& V) {\n            BBox<T,D> bb;\n            if(V.cols() > 0) {\n                bb.extend(V.rowwise().minCoeff());\n                bb.extend(V.rowwise().maxCoeff());\n\n            }\n            return bb;\n        }\n    template <typename T, int D>\n        auto bounding_box_slow(const mtao::ColVectors<T,D>& V) {\n            BBox<T,D> bb;\n            if(V.cols() > 0) {\n                bb.extend(V.rowwise().minCoeff());\n                bb.extend(V.rowwise().maxCoeff());\n                for(auto&& p: colvector_loop(V)) {\n                    bb.extend(p);\n                }\n            }\n\n            return bb;\n        }\n\n    //expand by multiplying by a scale\n    template <typename T, int D>\n        BBox<T,D> expand_bbox(BBox<T,D> bb, T scale) {\n            using Vec = mtao::Vector<T,D>;\n            Vec s = (scale-1) * (T(.5) * bb.sizes());\n            bb.min() -= s;\n            bb.max() += s;\n            return bb;\n        }\n    //expand by adding a factor\n    template <typename T, int D>\n        BBox<T,D> offset_bbox(BBox<T,D> bb, T offset) {\n            bb.min().array() -= offset;\n            bb.max().array() += offset;\n            return bb;\n        }\n}}\n", "meta": {"hexsha": "0dbc4f78142dfbb91a5f5cf8e812389ab269e1e3", "size": 1467, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/geometry/bounding_box.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/geometry/bounding_box.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/geometry/bounding_box.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.34, "max_line_length": 69, "alphanum_fraction": 0.4805725971, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.520683457195186}}
{"text": "\n/*\n * test_image_io.cpp\n *\n *  Created on: Mar 26, 2019\n *      Author: Gregory Kramida\n *   Copyright: 2019 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#define BOOST_TEST_MODULE test_image_io\n\n//libraries\n#include <boost/test/unit_test.hpp>\n\n//test data\n#include \"data/test_data_image_io.hpp\"\n\n//test targets\n#include \"../src/math/typedefs.hpp\"\n#include \"../src/image_io/png_eigen.hpp\"\n#include \"common.hpp\"\n\nBOOST_AUTO_TEST_CASE(test_image_read01) {\n\tmath::MatrixXus depth_image;\n\tbool image_read = read_image_helper(depth_image, \"zigzag_depth_00064.png\");\n\tBOOST_REQUIRE(image_read);\n\tBOOST_REQUIRE_EQUAL(depth_image.rows(), 480);\n\tBOOST_REQUIRE_EQUAL(depth_image.cols(), 640);\n\tBOOST_REQUIRE_EQUAL(depth_image(0, 0), (unsigned short )1997);\n\tBOOST_REQUIRE_EQUAL(depth_image(479, 0), (unsigned short )1997);\n\tBOOST_REQUIRE_EQUAL(depth_image(479, 639), (unsigned short ) 5154);\n\tmath::MatrixXus sample = depth_image.block(40, 60, 1, 20);\n\tBOOST_REQUIRE(sample.isApprox(test_data::depth_00064_sample));\n}\n\n", "meta": {"hexsha": "beb71a8f0c01239e1ce6ce2ccc9971db395246cb", "size": 1556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_image_io.cpp", "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": "tests/test_image_io.cpp", "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": "tests/test_image_io.cpp", "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": 33.1063829787, "max_line_length": 77, "alphanum_fraction": 0.7467866324, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5206834527297272}}
{"text": "/**\n * \\author Norihiro Watanabe\n * \\date   2013-09-06\n *\n * \\copyright\n * Copyright (c) 2013, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/LICENSE.txt\n */\n\n#include <gtest/gtest.h>\n\n#include <limits>\n#include <algorithm>\n#include <vector>\n\n#ifdef OGS_USE_EIGEN\n#include <Eigen/Eigen>\n#endif\n\n#include \"MeshLib/Elements/Quad.h\"\n#include \"NumLib/Fem/ShapeFunction/ShapeQuad4.h\"\n#include \"NumLib/Fem/CoordinatesMapping/ShapeMatrices.h\"\n#include \"NumLib/Fem/CoordinatesMapping/NaturalCoordinatesMapping.h\"\n\n#include \"../TestTools.h\"\n\nusing namespace NumLib;\n\n#ifdef OGS_USE_EIGEN\n\nnamespace\n{\nclass NumLibFemNaturalCoordinatesMappingQuad4Test : public ::testing::Test\n{\n public:\n    // Matrix types\n    static const unsigned dim = 2;\n    static const unsigned e_nnodes = 4;\n    typedef Eigen::Matrix<double, e_nnodes, 1> NodalVector;\n    typedef Eigen::Matrix<double, dim, e_nnodes, Eigen::RowMajor> DimNodalMatrix;\n    typedef Eigen::Matrix<double, dim, dim, Eigen::RowMajor> DimMatrix;\n    // Shape data type\n    typedef ShapeMatrices<NodalVector,DimNodalMatrix,DimMatrix> ShapeMatricesType;\n    // Natural coordinates mapping type\n    typedef NaturalCoordinatesMapping<MeshLib::Quad, ShapeQuad4, ShapeMatricesType> NaturalCoordsMappingType;\n\n public:\n    NumLibFemNaturalCoordinatesMappingQuad4Test()\n    {\n        // create four quad elements used for testing\n        naturalQuad   = createNaturalShapeQuad();\n        irregularQuad = createIrregularShapeQuad();\n        clockwiseQuad = createClockWiseQuad();\n        zeroAreaQuad  = createZeroAreaQuad();\n\n        // for destructor\n        vec_eles.push_back(naturalQuad);\n        vec_eles.push_back(irregularQuad);\n        vec_eles.push_back(clockwiseQuad);\n        vec_eles.push_back(zeroAreaQuad);\n        for (auto e : vec_eles)\n            for (unsigned i=0; i<e->getNNodes(true); i++)\n                vec_nodes.push_back(e->getNode(i));\n    }\n\n    ~NumLibFemNaturalCoordinatesMappingQuad4Test()\n    {\n        for (auto itr = vec_nodes.begin(); itr!=vec_nodes.end(); ++itr )\n            delete *itr;\n        for (auto itr = vec_eles.begin(); itr!=vec_eles.end(); ++itr )\n            delete *itr;\n    }\n\n    // quad having shape identical to that in natural coordinates\n    MeshLib::Quad* createNaturalShapeQuad()\n    {\n        MeshLib::Node** nodes = new MeshLib::Node*[e_nnodes];\n        nodes[0] = new MeshLib::Node( 1.0,  1.0,  0.0);\n        nodes[1] = new MeshLib::Node(-1.0,  1.0,  0.0);\n        nodes[2] = new MeshLib::Node(-1.0, -1.0,  0.0);\n        nodes[3] = new MeshLib::Node( 1.0, -1.0,  0.0);\n        return new MeshLib::Quad(nodes);\n    }\n\n    // quad having irregular or skew shape\n    MeshLib::Quad* createIrregularShapeQuad()\n    {\n        MeshLib::Node** nodes = new MeshLib::Node*[e_nnodes];\n        nodes[0] = new MeshLib::Node(-0.5, -0.5,  0.0);\n        nodes[1] = new MeshLib::Node( 0.6, -0.6,  0.0);\n        nodes[2] = new MeshLib::Node( 0.5,  0.4,  0.0);\n        nodes[3] = new MeshLib::Node(-0.3,  0.1,  0.0);\n        return new MeshLib::Quad(nodes);\n    }\n\n    // invalid case: clock wise node ordering\n    MeshLib::Quad* createClockWiseQuad()\n    {\n        MeshLib::Node** nodes = new MeshLib::Node*[e_nnodes];\n        nodes[0] = new MeshLib::Node( 1.0,  1.0,  0.0);\n        nodes[3] = new MeshLib::Node(-1.0,  1.0,  0.0);\n        nodes[2] = new MeshLib::Node(-1.0, -1.0,  0.0);\n        nodes[1] = new MeshLib::Node( 1.0, -1.0,  0.0);\n        return new MeshLib::Quad(nodes);\n    }\n\n    // invalid case: zero area\n    MeshLib::Quad* createZeroAreaQuad()\n    {\n        MeshLib::Node** nodes = new MeshLib::Node*[e_nnodes];\n        nodes[0] = new MeshLib::Node( 1.0,  1.0,  0.0);\n        nodes[1] = new MeshLib::Node(-1.0,  1.0,  0.0);\n        nodes[2] = new MeshLib::Node(-1.0,  1.0,  0.0);\n        nodes[3] = new MeshLib::Node( 1.0,  1.0,  0.0);\n        return new MeshLib::Quad(nodes);\n    }\n\n    static const double r[dim];\n    static const double exp_N[e_nnodes];\n    static const double exp_dNdr[e_nnodes*dim];\n    static const double eps;\n\n    std::vector<const MeshLib::Node*> vec_nodes;\n    std::vector<const MeshLib::Quad*> vec_eles;\n    MeshLib::Quad* naturalQuad;\n    MeshLib::Quad* irregularQuad;\n    MeshLib::Quad* clockwiseQuad;\n    MeshLib::Quad* zeroAreaQuad;\n\n}; // NumLibFemNaturalCoordinatesMappingQuad4Test\n\nconst double NumLibFemNaturalCoordinatesMappingQuad4Test::r[dim] = {0.5, 0.5};\nconst double NumLibFemNaturalCoordinatesMappingQuad4Test::exp_N[e_nnodes] = {0.5625, 0.1875, 0.0625, 0.1875};\nconst double NumLibFemNaturalCoordinatesMappingQuad4Test::exp_dNdr[e_nnodes*dim] = {0.375, -0.375, -0.125, 0.125, 0.375, 0.125, -0.125, -0.375};\nconst double NumLibFemNaturalCoordinatesMappingQuad4Test::eps = std::numeric_limits<double>::epsilon();\n\n} // namespace\n\nTEST_F(NumLibFemNaturalCoordinatesMappingQuad4Test, CheckFieldSpecification_N)\n{\n    ShapeMatricesType shape(dim, e_nnodes);\n\n    //only N\n    NaturalCoordsMappingType::computeShapeMatrices<ShapeMatrixType::N>(*naturalQuad, r, shape);\n    ASSERT_FALSE(shape.N.isZero());\n    ASSERT_TRUE(shape.dNdr.isZero());\n    ASSERT_TRUE(shape.J.isZero());\n    ASSERT_TRUE(shape.detJ == .0);\n    ASSERT_TRUE(shape.invJ.isZero());\n    ASSERT_TRUE(shape.dNdx.isZero());\n}\n\nTEST_F(NumLibFemNaturalCoordinatesMappingQuad4Test, CheckFieldSpecification_DNDR)\n{\n    ShapeMatricesType shape(dim, e_nnodes);\n\n    // dNdr\n    NaturalCoordsMappingType::computeShapeMatrices<ShapeMatrixType::DNDR>(*naturalQuad, r, shape);\n    ASSERT_TRUE(shape.N.isZero());\n    ASSERT_FALSE(shape.dNdr.isZero());\n    ASSERT_TRUE(shape.J.isZero());\n    ASSERT_TRUE(shape.detJ == .0);\n    ASSERT_TRUE(shape.invJ.isZero());\n    ASSERT_TRUE(shape.dNdx.isZero());\n}\n\nTEST_F(NumLibFemNaturalCoordinatesMappingQuad4Test, CheckFieldSpecification_N_J)\n{\n    ShapeMatricesType shape(dim, e_nnodes);\n\n    // N_J\n    shape.setZero();\n    NaturalCoordsMappingType::computeShapeMatrices<ShapeMatrixType::N_J>(*naturalQuad, r, shape);\n    ASSERT_FALSE(shape.N.isZero());\n    ASSERT_FALSE(shape.dNdr.isZero());\n    ASSERT_FALSE(shape.J.isZero());\n    ASSERT_FALSE(shape.detJ == .0);\n    ASSERT_TRUE(shape.invJ.isZero());\n    ASSERT_TRUE(shape.dNdx.isZero());\n}\n\nTEST_F(NumLibFemNaturalCoordinatesMappingQuad4Test, CheckFieldSpecification_DNDR_J)\n{\n    ShapeMatricesType shape(dim, e_nnodes);\n\n    // dNdr, J\n    NaturalCoordsMappingType::computeShapeMatrices<ShapeMatrixType::DNDR_J>(*naturalQuad, r, shape);\n    ASSERT_TRUE(shape.N.isZero());\n    ASSERT_FALSE(shape.dNdr.isZero());\n    ASSERT_FALSE(shape.J.isZero());\n    ASSERT_FALSE(shape.detJ == .0);\n    ASSERT_TRUE(shape.invJ.isZero());\n    ASSERT_TRUE(shape.dNdx.isZero());\n}\n\nTEST_F(NumLibFemNaturalCoordinatesMappingQuad4Test, CheckFieldSpecification_DNDX)\n{\n    ShapeMatricesType shape(dim, e_nnodes);\n\n    // DNDX\n    shape.setZero();\n    NaturalCoordsMappingType::computeShapeMatrices<ShapeMatrixType::DNDX>(*naturalQuad, r, shape);\n    ASSERT_TRUE(shape.N.isZero());\n    ASSERT_FALSE(shape.dNdr.isZero());\n    ASSERT_FALSE(shape.J.isZero());\n    ASSERT_FALSE(shape.detJ == .0);\n    ASSERT_FALSE(shape.invJ.isZero());\n    ASSERT_FALSE(shape.dNdx.isZero());\n}\n\nTEST_F(NumLibFemNaturalCoordinatesMappingQuad4Test, CheckFieldSpecification_ALL)\n{\n    ShapeMatricesType shape(dim, e_nnodes);\n\n    // ALL\n    shape.setZero();\n    NaturalCoordsMappingType::computeShapeMatrices(*naturalQuad, r, shape);\n    ASSERT_FALSE(shape.N.isZero());\n    ASSERT_FALSE(shape.dNdr.isZero());\n    ASSERT_FALSE(shape.J.isZero());\n    ASSERT_FALSE(shape.detJ == .0);\n    ASSERT_FALSE(shape.invJ.isZero());\n    ASSERT_FALSE(shape.dNdx.isZero());\n}\n\n\nTEST_F(NumLibFemNaturalCoordinatesMappingQuad4Test, CheckNaturalShape)\n{\n    // identical to natural coordinates\n    ShapeMatricesType shape(dim, e_nnodes);\n\n    NaturalCoordsMappingType::computeShapeMatrices(*naturalQuad, r, shape);\n    double exp_J[]= {1.0, 0.0, 0.0, 1.0};\n\n    ASSERT_ARRAY_NEAR(exp_N, shape.N.data(), shape.N.size(), eps);\n    ASSERT_ARRAY_NEAR(exp_dNdr, shape.dNdr.data(), shape.dNdr.size(), eps);\n    ASSERT_ARRAY_NEAR(exp_J, shape.J.data(), shape.J.size(), eps);\n    ASSERT_ARRAY_NEAR(exp_J, shape.invJ.data(), shape.invJ.size(), eps);\n    ASSERT_NEAR(1.0, shape.detJ, eps);\n    ASSERT_ARRAY_NEAR(exp_dNdr, shape.dNdx.data(), shape.dNdx.size(), eps);\n}\n\nTEST_F(NumLibFemNaturalCoordinatesMappingQuad4Test, CheckIrregularShape)\n{\n    // irregular shape\n    ShapeMatricesType shape(dim, e_nnodes);\n\n    NaturalCoordsMappingType::computeShapeMatrices(*irregularQuad, r, shape);\n//        std::cout << shape;\n    double exp_J[]= {-0.5125, 0.0, -0.0625, -0.35};\n    double exp_invJ[]= {-1.9512195121951219, 0.0, 0.3484320557491290, -2.8571428571428572};\n    double exp_dNdx[]= {-0.73170731707317072, 0.73170731707317072, 0.243902439024390, -0.24390243902439029, -0.940766550522648, -0.48780487804878048, 0.313588850174216, 1.1149825783972125};\n\n    ASSERT_ARRAY_NEAR(exp_N, shape.N.data(), shape.N.size(), eps);\n    ASSERT_ARRAY_NEAR(exp_dNdr, shape.dNdr.data(), shape.dNdr.size(), eps);\n    ASSERT_ARRAY_NEAR(exp_J, shape.J.data(), shape.J.size(), eps);\n    ASSERT_ARRAY_NEAR(exp_invJ, shape.invJ.data(), shape.invJ.size(), eps);\n    ASSERT_NEAR(0.179375, shape.detJ, eps);\n    ASSERT_ARRAY_NEAR(exp_dNdx, shape.dNdx.data(), shape.dNdx.size(), eps);\n}\n\nTEST_F(NumLibFemNaturalCoordinatesMappingQuad4Test, CheckClockwise)\n{\n    // clockwise node ordering, which is invalid)\n    ShapeMatricesType shape(dim, e_nnodes);\n\n    NaturalCoordsMappingType::computeShapeMatrices(*clockwiseQuad, r, shape);\n    //std::cout << shape;\n    double exp_J[]= {0.0, 1.0, 1.0, 0.0};\n    // Inverse of the Jacobian matrix doesn't exist\n    double exp_invJ[dim*dim]= {0.0};\n    double exp_dNdx[dim*e_nnodes]= {0.0};\n\n    ASSERT_ARRAY_NEAR(exp_N, shape.N.data(), shape.N.size(), eps);\n    ASSERT_ARRAY_NEAR(exp_dNdr, shape.dNdr.data(), shape.dNdr.size(), eps);\n    ASSERT_ARRAY_NEAR(exp_J, shape.J.data(), shape.J.size(), eps);\n    ASSERT_ARRAY_NEAR(exp_invJ, shape.invJ.data(), shape.invJ.size(), eps);\n    ASSERT_NEAR(-1.0, shape.detJ, eps);\n    ASSERT_ARRAY_NEAR(exp_dNdx, shape.dNdx.data(), shape.dNdx.size(), eps);\n}\n\nTEST_F(NumLibFemNaturalCoordinatesMappingQuad4Test, CheckZeroArea)\n{\n    // zero area\n    ShapeMatricesType shape(dim, e_nnodes);\n\n    NaturalCoordsMappingType::computeShapeMatrices(*zeroAreaQuad, r, shape);\n    //std::cout << shape;\n    double exp_J[]= {1.0, 0.0, 0.0, 0.0};\n    // Inverse of the Jacobian matrix doesn't exist\n    double exp_invJ[dim*dim]= {0.0};\n    double exp_dNdx[dim*e_nnodes]= {0.0};\n\n    ASSERT_ARRAY_NEAR(exp_N, shape.N.data(), shape.N.size(), eps);\n    ASSERT_ARRAY_NEAR(exp_dNdr, shape.dNdr.data(), shape.dNdr.size(), eps);\n    ASSERT_ARRAY_NEAR(exp_J, shape.J.data(), shape.J.size(), eps);\n    ASSERT_ARRAY_NEAR(exp_invJ, shape.invJ.data(), shape.invJ.size(), eps);\n    ASSERT_NEAR(0.0, shape.detJ, eps);\n    ASSERT_ARRAY_NEAR(exp_dNdx, shape.dNdx.data(), shape.dNdx.size(), eps);\n}\n\n#endif //OGS_USE_EIGEN\n\n\n", "meta": {"hexsha": "4d5739b4d7ed7b505d904022b121c1197b97396e", "size": 11107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/NumLib/TestCoordinatesMapping.cpp", "max_stars_repo_name": "WenjieXu/ogs", "max_stars_repo_head_hexsha": "0cd1b72ec824833bf949a8bbce073c82158ee443", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-21T17:29:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T17:29:38.000Z", "max_issues_repo_path": "Tests/NumLib/TestCoordinatesMapping.cpp", "max_issues_repo_name": "WenjieXu/ogs", "max_issues_repo_head_hexsha": "0cd1b72ec824833bf949a8bbce073c82158ee443", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tests/NumLib/TestCoordinatesMapping.cpp", "max_forks_repo_name": "WenjieXu/ogs", "max_forks_repo_head_hexsha": "0cd1b72ec824833bf949a8bbce073c82158ee443", "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.1791530945, "max_line_length": 189, "alphanum_fraction": 0.6847933735, "num_tokens": 3277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5206421063026535}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_MATH_MAX_SERIES_ITERATION_POLICY 10000000\n\n#include <boost/math/special_functions/hypergeometric_1f1.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/lexical_cast.hpp>\n#include <fstream>\n#include <map>\n#include <boost/math/tools/test_data.hpp>\n#include <boost/random.hpp>\n#include \"mp_t.hpp\"\n\nusing namespace boost::math::tools;\nusing namespace boost::math;\nusing namespace std;\n\nstruct hypergeometric_1f1_gen\n{\n   mp_t operator()(mp_t a1, mp_t a2, mp_t z)\n   {\n      std::cout << a1 << \" \" << a2 << \" \" << z << std::endl;\n      mp_t result = boost::math::detail::hypergeometric_1f1_generic_series(a1, a2, z, boost::math::policies::policy<>());\n      std::cout << a1 << \" \" << a2 << \" \" << z << \" \" << result << std::endl;\n      return result;\n   }\n};\n\nstruct hypergeometric_1f1_gen_2\n{\n   mp_t operator()(mp_t a1, mp_t a2, mp_t z)\n   {\n      mp_t result = boost::math::detail::hypergeometric_1f1_generic_series(a1, a2, z, boost::math::policies::policy<>());\n      std::cout << a1 << \" \" << a2 << \" \" << z << \" \" << result << std::endl;\n      if (fabs(result) > (std::numeric_limits<double>::max)())\n      {\n         std::cout << \"Discarding result as too large\\n\";\n         throw std::domain_error(\"\");\n      }\n      if (static_cast<double>(result) == 1)\n      {\n         std::cout << \"Discarding result as unity\\n\";\n         throw std::domain_error(\"\");  // uninteresting result.\n      }\n      return result;\n   }\n};\n\n\nint main(int, char* [])\n{\n   parameter_info<mp_t> arg1, arg2, arg3;\n   test_data<mp_t> data;\n\n   std::cout << \"Welcome.\\n\"\n      \"This program will generate spot tests for 2F0:\\n\";\n\n   std::string line;\n   bool cont;\n\n#if 1\n   std::vector<mp_t> v;\n   random_ns::mt19937 rnd;\n   random_ns::uniform_real_distribution<float> ur_a(0, 1);\n\n   mp_t p = ur_a(rnd);\n   p *= 1e6;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e5;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e4;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e3;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e2;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e-5;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e-12;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e-30;\n   v.push_back(p);\n   v.push_back(-p);\n\n   for (unsigned i = 0; i < v.size(); ++i)\n   {\n      for (unsigned j = 0; j < v.size(); ++j)\n      {\n         for (unsigned k = 0; k < v.size(); ++k)\n         {\n            arg1 = make_single_param(v[i]);\n            arg2 = make_single_param(v[j] * 3 / 2);\n            arg3 = make_single_param(v[k] * 5 / 4);\n            data.insert(hypergeometric_1f1_gen_2(), arg1, arg2, arg3);\n         }\n      }\n   }\n\n\n#else\n\n   do {\n      get_user_parameter_info(arg1, \"a1\");\n      get_user_parameter_info(arg2, \"a2\");\n      get_user_parameter_info(arg3, \"z\");\n      data.insert(hypergeometric_1f1_gen(), arg1, arg2, arg3);\n      std::cout << \"Any more data [y/n]?\";\n      std::getline(std::cin, line);\n      boost::algorithm::trim(line);\n      cont = (line == \"y\");\n   } while (cont);\n\n#endif\n   std::cout << \"Enter name of test data file [default=hypergeometric_1f1.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"hypergeometric_1f1.ipp\";\n   std::ofstream ofs(line.c_str());\n   ofs << std::scientific << std::setprecision(40);\n   write_code(ofs, data, line.c_str());\n   \n   return 0;\n}\n\n\n", "meta": {"hexsha": "0205b42b30878271c96ef93cbd8601a21381e93f", "size": 3724, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/hyp_1f1_data.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-18T13:10:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T13:10:50.000Z", "max_issues_repo_path": "libs/math/tools/hyp_1f1_data.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T12:45:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T20:43:03.000Z", "max_forks_repo_path": "libs/math/tools/hyp_1f1_data.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "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": 25.8611111111, "max_line_length": 121, "alphanum_fraction": 0.5861976369, "num_tokens": 1171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5206421016589464}}
{"text": "/*****************************************************************************\n*\n* Functions for calculating the gap\n*\n* Copyright (C) 2018 by Hidemaro Suwa\n* e-mail:suwamaro@phys.s.u-tokyo.ac.jp\n*\n*****************************************************************************/\n\n#include \"calc_gap.h\"\n#include \"rpa_util.h\"\n#include <armadillo>\n\ncx_double calc_intensity_square(int L, hoppings const& ts, double mu, double U, double delta, double qx, double qy, cx_double omega, bool zz){\n  double k1 = 2. * M_PI / (double)L;\n  \n  cx_double A = 0, B = 0, C = 0, D = 0;\n  /* Summing up at all the wavevectors */\n  for(int x=-L/2; x < L/2; x++){    \n    double kx = k1 * x;\n    for(int y=-L/2; y < L/2; y++){\n      double ky = k1 * y;\n      add_to_sus_mat2( ts, mu, A, B, C, D, qx, qy, 0, kx, ky, 0, delta, omega, zz );\t    }\n  }\n  \n  int n_sites = L * L;\n  A *= 2. / (double)n_sites;\n  B *= 2. / (double)n_sites;\n  C *= 2. / (double)n_sites;  \n  D *= 2. / (double)n_sites;  \n  \n  /* RPA */\n  arma::cx_mat chi0_mat(2,2);\n  chi0_mat(0,0) = A;   // (A, A) correlation\n  chi0_mat(0,1) = B;   // (A, B)\n  chi0_mat(1,0) = C;   // (B, A)\n  chi0_mat(1,1) = D;   // (B, B)\n\n  /* Transverse = < \\sigma^- \\sigma^+ >; Longitudinal (zz) = < \\sigma^z \\sigma^z > */\n  /* Note that 2 < \\sigma^- \\sigma^+ > = < \\sigma^z \\sigma^z > (U -> 0 for the SU(2) case) */  \n  double factor_channel = 1.0;\n  if ( zz ) { factor_channel = 0.5; }\n  \n  arma::cx_mat denom = arma::eye<arma::cx_mat>(2,2) - factor_channel * U * chi0_mat;\n  arma::cx_mat chi_mat = chi0_mat * arma::inv(denom);\n\n  // // for check\n  // chi_mat = chi0_mat;\n\n  // sigma-to-spin factor\n  double factor_operator = 0.5;  \n  cx_double chi = factor_operator * factor_operator * ( chi_mat(0,0) - chi_mat(1,0) - chi_mat(0,1) + chi_mat(1,1) );\n  \n  return chi;  \n}\n\n// cx_double calc_intensity_square2(int L, double t, double mu, double U, double delta, double qx, double qy, cx_double omega, bool zz){  \n//   double k1 = 2. * M_PI / (double)L;\n//   double e_eps = 1e-12;  \n//   cx_double polarization = 0;\n  \n//   /* Summing up over all the wavevectors in the magnetic BZ. */\n//   for(int x=-L/2; x < L/2; x++){    \n//     double kx = k1 * x;\n    \n//     for(int y=-L/2; y < L/2; y++){\n//       double ky = k1 * y;\n      \n//       double e_free = energy_free_electron( t, mu, kx, ky );\n//       if ( e_free < mu + e_eps ) {\n// \tdouble factor = 1.;\n// \tif ( std::abs( e_free - mu ) < e_eps ) {\n// \t  factor = 0.5;\n// \t}\n\t\n// \tdouble kx2 = wave_vector_in_BZ( kx + qx );\n// \tdouble ky2 = wave_vector_in_BZ( ky + qy );\n// \tdouble e_free2 = energy_free_electron( t, mu, kx2, ky2 );\n\n// \tdouble Ek = eigenenergy_HF_plus(e_free, delta);\n// \tdouble Ek2 = eigenenergy_HF_plus(e_free2, delta);\n\t\n// \tdouble element = 0;\n// \tif ( zz ) {\n// \t  element = 1. - (e_free * e_free2 + delta * delta) / (Ek * Ek2);\n// \t} else {\n// \t  element = 1. - (e_free * e_free2 - delta * delta) / (Ek * Ek2);\n// \t}\n\t\n// \tcx_double denom = 1. / (omega - Ek2 - Ek) + 1. / ( - std::conj(omega) - Ek2 - Ek);\n// \tpolarization += - factor * element / denom;\n//       }\n//     } /* end for y */\n//   } /* end for x */\n\n//   int nsites = L * L;\n//   polarization /= (double)(2*nsites);\n//   return polarization / ( 1. - U * polarization );\n// }\n", "meta": {"hexsha": "74c8df99abc7bdcca39fb7956155a8eee6a07a82", "size": 3241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/calc_intensity_square.cpp", "max_stars_repo_name": "suwamaro/rpa", "max_stars_repo_head_hexsha": "fc9d37f03705334ee17b77de6ad2b8feab3cc7b0", "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/calc_intensity_square.cpp", "max_issues_repo_name": "suwamaro/rpa", "max_issues_repo_head_hexsha": "fc9d37f03705334ee17b77de6ad2b8feab3cc7b0", "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/calc_intensity_square.cpp", "max_forks_repo_name": "suwamaro/rpa", "max_forks_repo_head_hexsha": "fc9d37f03705334ee17b77de6ad2b8feab3cc7b0", "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.41, "max_line_length": 142, "alphanum_fraction": 0.5297747609, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5206420962813473}}
{"text": "//\n// Copyright Antoine Leblanc 2010 - 2015\n// Distributed under the MIT license.\n//\n// http://nauths.fr\n// http://github.com/nicuveo\n// mailto://antoine.jp.leblanc@gmail.com\n//\n\n\n\n//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\n// Includes\n\n#include <cstdlib>\n#include <iostream>\n#include <boost/test/unit_test.hpp>\n#include \"nauths/mml/mml.hh\"\n\n\n\n//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\n// Local code\n\nnamespace\n{\n\n  typedef mml::Shape<mml::Num> Shape;\n  typedef mml::Point<mml::Num> Point;\n  typedef mml::Line<mml::Num> Line;\n  typedef mml::Point<mml::Num> Vector;\n  typedef mml::Polygon<mml::Num> Polygon;\n\n  typedef mml::Tessellation<mml::Num> Tessellation;\n\n  typedef std::map<int, Shape> ShapeMap;\n\n\n  Line oriented(const Line& l)\n  {\n    return (l.x0() == l.x1()\n            ? (l.y0() < l.y1()\n               ? l\n               : -l)\n            : (l.x0() < l.x1()\n               ? l\n               : -l));\n  }\n\n  Line\n  common_line(const Polygon& p1, const Polygon& p2)\n  {\n    // ugly\n    for (const Line& l1 : p1.lines())\n      for (const Line& l2 : p2.lines())\n        if (oriented(l1) == oriented(l2))\n          return oriented(l1);\n    BOOST_CHECK(false);\n    return Line();\n  }\n\n  void check_pair(const Polygon& p1, const Polygon& p2)\n  {\n    const Line& common = common_line(p1, p2);\n    Line centers(p1.center(), p2.center());\n    mml::Real n1;\n    mml::Real n2;\n    mml::Real d1;\n    mml::Real d2;\n    mml::il::lines_coeff(common, centers, n1, n2, d1, d2);\n\n    BOOST_CHECK_NE(0, d1);\n    BOOST_CHECK_NE(0, d2);\n    BOOST_CHECK_LE(0, std::abs(n1));\n    BOOST_CHECK_LE(0, std::abs(n2));\n    BOOST_CHECK_LE(std::abs(n1), std::abs(d1));\n    BOOST_CHECK_LE(std::abs(n2), std::abs(d2));\n\n    double real = n2 / d2;\n    double theoretical = mml::tiling::ratio(p1.size(), p2.size());\n    double diff = std::abs(theoretical - real);\n\n    // std::cout << \"real: \" << std::setw(10) << real << \" theo: \" << theoretical << std::endl;\n    BOOST_CHECK_LT(diff / theoretical, 0.05);\n  }\n\n  void check_tiling(mml::TilingType type)\n  {\n    Shape ref(Shape::square(20000));\n    Tessellation tess(type, ref, 5000);\n    Tessellation::iterator it;\n    ShapeMap m;\n\n    for (it = tess.begin(false, true); it != tess.end(); ++it)\n    {\n      m[it.index()] = *it;\n      for (const Tessellation::Link& nid : it.links())\n      {\n        ShapeMap::iterator it2 = m.find(nid.first);\n        if (it2 != m.end())\n          check_pair(m[it.index()].polygon(), it2->second.polygon());\n      }\n    }\n  }\n\n}\n\n\n\n//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\n// Implementation\n\nBOOST_AUTO_TEST_SUITE(tiling_ratios)\n\nBOOST_AUTO_TEST_CASE(TRIANGULAR_TILING)\n{\n  check_tiling(mml::tiling::TRIANGULAR);\n}\n\nBOOST_AUTO_TEST_CASE(SQUARE_TILING)\n{\n  check_tiling(mml::tiling::SQUARE);\n}\n\nBOOST_AUTO_TEST_CASE(HEXAGONAL_TILING)\n{\n  check_tiling(mml::tiling::HEXAGONAL);\n}\n\nBOOST_AUTO_TEST_CASE(SNUB_HEXAGONAL_TILING)\n{\n  check_tiling(mml::tiling::SNUB_HEXAGONAL);\n}\n\nBOOST_AUTO_TEST_CASE(REFLECTED_SNUB_HEXAGONAL_TILING)\n{\n  check_tiling(mml::tiling::REFLECTED_SNUB_HEXAGONAL);\n}\n\nBOOST_AUTO_TEST_CASE(TRI_HEXAGONAL_TILING)\n{\n  check_tiling(mml::tiling::TRI_HEXAGONAL);\n}\n\nBOOST_AUTO_TEST_CASE(ELONGATED_TRIANGULAR_TILING)\n{\n  check_tiling(mml::tiling::ELONGATED_TRIANGULAR);\n}\n\nBOOST_AUTO_TEST_CASE(SNUB_SQUARE_TILING)\n{\n  check_tiling(mml::tiling::SNUB_SQUARE);\n}\n\nBOOST_AUTO_TEST_CASE(RHOMBITRIHEXAGONAL_TILING)\n{\n  check_tiling(mml::tiling::RHOMBITRIHEXAGONAL);\n}\n\nBOOST_AUTO_TEST_CASE(TRUNCATED_SQUARE_TILING)\n{\n  check_tiling(mml::tiling::TRUNCATED_SQUARE);\n}\n\nBOOST_AUTO_TEST_CASE(TRUNCATED_HEXAGONAL_TILING)\n{\n  check_tiling(mml::tiling::TRUNCATED_HEXAGONAL);\n}\n\nBOOST_AUTO_TEST_CASE(TRUNCATED_TRIHEXAGONAL_TILING)\n{\n  check_tiling(mml::tiling::TRUNCATED_TRIHEXAGONAL);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f32aee1859864c8af2c377679603c2e82d01086a", "size": 3861, "ext": "cc", "lang": "C++", "max_stars_repo_path": "check/general/tiling_ratios.cc", "max_stars_repo_name": "nicuveo/MML", "max_stars_repo_head_hexsha": "b877a65abb61ea2fe6d8407b50f44fd170fb748d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "check/general/tiling_ratios.cc", "max_issues_repo_name": "nicuveo/MML", "max_issues_repo_head_hexsha": "b877a65abb61ea2fe6d8407b50f44fd170fb748d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "check/general/tiling_ratios.cc", "max_forks_repo_name": "nicuveo/MML", "max_forks_repo_head_hexsha": "b877a65abb61ea2fe6d8407b50f44fd170fb748d", "max_forks_repo_licenses": ["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.9375, "max_line_length": 95, "alphanum_fraction": 0.6736596737, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5206420955474566}}
{"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_ARCH_COMMON_SIMD_FUNCTION_SIGNIFICANTS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SIGNIFICANTS_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/detail/assert_utils.hpp>\n#include <boost/simd/function/simd/abs.hpp>\n#include <boost/simd/function/simd/divides.hpp>\n#include <boost/simd/function/simd/iceil.hpp>\n#include <boost/simd/function/simd/if_zero_else.hpp>\n#include <boost/simd/function/simd/is_eqz.hpp>\n#include <boost/simd/function/simd/is_gtz.hpp>\n#include <boost/simd/function/simd/log10.hpp>\n#include <boost/simd/function/simd/minus.hpp>\n#include <boost/simd/function/simd/multiplies.hpp>\n#include <boost/simd/function/simd/round.hpp>\n#include <boost/simd/function/simd/tenpower.hpp>\n#include <boost/assert.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/function/simd/if_else.hpp>\n#include <boost/simd/function/simd/is_invalid.hpp>\n#endif\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n\n//   WARNING AN \"IMPLEMENT_IF\" WAS PRESENT IN THE ORIGINAL FILE\n\n   BOOST_DISPATCH_OVERLOAD( significants_\n                          , (typename A0, typename A1, typename X)\n                          , bd::cpu_\n                          , bs::pack_< bd::floating_<A0>, X>\n                          , bs::pack_< bd::integer_<A1>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0, const  A1&  a1) const BOOST_NOEXCEPT\n      {\n        BOOST_ASSERT_MSG( assert_all(is_gtz(a1))\n                        , \"Number of significant digits must be positive\"\n                        );\n        using iA0 =  bd::as_integer_t<A0>;\n        iA0 exp = a1 - iceil(log10(abs(a0)));\n        A0 fac = tenpower(exp);\n        A0 scaled = round(a0*fac);\n  #ifndef BOOST_SIMD_NO_INVALIDS\n        A0 r = if_else(is_invalid(a0), a0, scaled/fac);\n  #else\n        A0 r =  scaled/fac;\n  #endif\n        return if_zero_else(is_eqz(a0), r);\n      }\n   };\n\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "fe2c7c65f08acd2e7778533ab58148bd30ff0027", "size": 2533, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/simd/function/significants.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/arch/common/simd/function/significants.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/arch/common/simd/function/significants.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": 34.2297297297, "max_line_length": 100, "alphanum_fraction": 0.6162652981, "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5206420955474566}}
{"text": "#ifndef TVTML_DATA3D_HPP\n#define TVTML_DATA3D_HPP\n\n// system includes\n#include <cassert>\n#include <limits>\n#include <cmath>\n#include <random>\n\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n\n//Eigen includes\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n\n// OpenCV includes\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#ifdef TV_DATA_DEBUG\n    #include <opencv2/highgui/highgui.hpp>\n#endif\n\n// video++ includes\n#include <vpp/vpp.hh>\n#include <vpp/utils/opencv_bridge.hh>\n\n// own includes \n#include \"data3d_utils.hpp\"\n#include \"manifold.hpp\"\n\nnamespace tvmtl{\n\n// Specialization 3D Data\ntemplate < typename MANIFOLD >\nclass Data<MANIFOLD, 3>{\n    \n    public:\n\tstatic const int img_dim;\n\n\t// Manifold typedefs\n\ttypedef typename MANIFOLD::value_type value_type;\n\ttypedef typename MANIFOLD::scalar_type scalar_type;\n\t\n\t// Storage typedefs\n\ttypedef vpp::image3d<value_type> storage_type;\n\t\n\ttypedef double weights_type;\n\ttypedef vpp::image3d<weights_type> weights_mat;\n\t\n\ttypedef bool inp_type;\n\ttypedef vpp::image3d<inp_type> inp_mat;\n\n\tinline bool doInpaint() const { return inpaint_; }\n\t    \n\t// Data Init functions\n\tinline void initEdgeweights();\n\tinline void initInp();\n\t\n\t// Input functions\n\tvoid rgb_slice_reader(std::string filename, int num_slides);\n\tvoid readMatrixDataFromCSV(std::string filename, const int nz, const int ny, const int nx);\n\tvoid readRawVolumeData(std::string filename, const int nz, const int ny, const int nx);\n\t\n\t// Noise functions\n\tvoid add_gaussian_noise(double stdev);\n\t\n\t// Creation functions\n\tvoid create_noisy_gray(const int nz, const int ny, const int nx, double color=0.5, double stdev=0.1);\n\tvoid create_noisy_rgb(const int nz, const int ny, const int nx, int color=1, double stdev=0.1);\n\n\tvoid setEdgeWeights(const weights_mat&);\n\n\t//Output functions\n\ttemplate <class IMG>\n\tvoid output_matval_img(const IMG& img, std::string filename) const;\n\n//  private:\n\tstorage_type img_;\n\tstorage_type noise_img_;\n\tweights_mat edge_weights_;\n\n\tbool inpaint_;\n\tinp_mat inp_; \n};\n\n\n/*----- Implementation 3D Data ------*/\ntemplate < typename MANIFOLD >\nconst int Data<MANIFOLD, 3>::img_dim = 3;\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 3>::setEdgeWeights(const weights_mat& w){\n    clone3d(w, edge_weights_);\n}\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 3>::initInp(){\n    inp_ = inp_mat(noise_img_.domain());\n    fill3d(inp_, false);\n    inpaint_ = false;\n}\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 3>::initEdgeweights(){\n    edge_weights_ = weights_mat(noise_img_.domain());\n    fill3d(edge_weights_, 1.0);\n}\n\ntemplate <typename MANIFOLD>\nvoid Data<MANIFOLD, 3>::add_gaussian_noise(double stdev){\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::normal_distribution<typename MANIFOLD::scalar_type> rand(0.0, stdev);\n\n    auto generate = [&] (typename MANIFOLD::scalar_type entry){\n\treturn entry + rand(gen);\n    };\n    \n    if(MANIFOLD::non_isometric_embedding)\n\tpixel_wise3d([&] (value_type& i){ MANIFOLD::interpolation_preprocessing(i); }, noise_img_);\n\n    pixel_wise3d([&] (value_type& i) {if(i.norm() > 0.07 ) i = i.unaryExpr(generate); }, noise_img_);\n\n    if(MANIFOLD::non_isometric_embedding)\n\tpixel_wise3d([&] (value_type& i){ MANIFOLD::interpolation_postprocessing(i); }, noise_img_);\n\n    pixel_wise3d([&] (value_type& i) { MANIFOLD::projector(i); }, noise_img_);\n\n    clone3d(noise_img_, img_);\n}\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 3>::create_noisy_gray(const int nz, const int ny, const int nx, double color, double stdev){\n    static_assert(MANIFOLD::value_dim == 1, \"Method is only callable for Manifolds with embedding dimension 1\");\n    noise_img_ = storage_type(nz, ny, nx);\n    img_ = storage_type(noise_img_.domain());\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::normal_distribution<typename MANIFOLD::scalar_type> rand(0.0, stdev);\n    auto insert = [&] (value_type& i) { i.setConstant(color + rand(gen)); MANIFOLD::projector(i); };\n\n    pixel_wise3d(insert, noise_img_);\n    clone3d(noise_img_, img_);\n    initInp();\n    initEdgeweights();\n}\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 3>::create_noisy_rgb(const int nz, const int ny, const int nx, int color, double stdev){\n    static_assert(MANIFOLD::value_dim == 3, \"Method is only callable for Manifolds with embedding dimension 3\");\n    noise_img_ = storage_type(nz, ny, nx);\n    img_ = storage_type(noise_img_.domain());\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::normal_distribution<typename MANIFOLD::scalar_type> rand(0.0, stdev);\n    value_type v(0.7 + rand(gen), 0.3 + rand(gen), 0.3 + rand(gen));\n    auto insert = [&] (value_type& i) { i = v; MANIFOLD::projector(i); };\n\n    pixel_wise3d(insert, noise_img_);\n    clone3d(noise_img_, img_);\n    initInp();\n    initEdgeweights();\n}\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 3>::rgb_slice_reader(std::string filename, int num_slices){\n\tstatic_assert(MANIFOLD::value_dim == 3,\"ERROR: RGB Input requires a Manifold with embedding dimension N=3!\");\n\tstd::string fname(filename);\n\n\tint last_dot_pos = fname.find_last_of(\".\");\n\tstd::string basefilename  = fname.substr(0, last_dot_pos-1);\n\tstd::string ext = fname.substr(last_dot_pos, fname.length());\n\t\n\n\tvpp::image2d<vpp::vuchar3> input_image = vpp::clone(vpp::from_opencv<vpp::vuchar3 >(cv::imread(basefilename + std::to_string(0) + ext)));\n\tvpp::image2d<value_type> input_image_double(input_image.domain());\n\tint nr = input_image.nrows();\n\tint nc = input_image.ncols();\n\tnoise_img_ = storage_type(num_slices, nr, nc);\n\n\t#ifdef TV_DATA_DEBUG\n\t    std::cout << \"\\nReading slice sequence \" << basefilename + std::to_string(0) + ext << \" containing \" << num_slices << \" Slices. \" << std::endl;\n\t    std::cout << \"Dimensions (Slices, Rows, Cols): \" << num_slices << \" X \" << nr << \" X \" << nc << std::endl;\n\t#endif\n\t\t  \n\t// Convert Picture of uchar to double \n\tauto converter =  [] (const auto& i, auto& d) {\n\t    value_type v = value_type::Zero();\n\t    vpp::vuchar3 vu = i;\n\t    // TODO: insert manifold scalar type\n\t    v[0]=static_cast<double>(vu[2]); //opencv saves as BGR\n\t    v[1]=static_cast<double>(vu[1]);\n\t    v[2]=static_cast<double>(vu[0]);\n\t    d = v / static_cast<double>(std::numeric_limits<unsigned char>::max());\n\t};\n\t\n\tfor(int s = 0; s < num_slices; ++s ){\n\t#ifdef TV_DATA_DEBUG\n\t    std::cout << \"Reading slice number \" << s << \" with name \" << basefilename + std::to_string(s) + ext << std::endl;\n\t#endif\n\t    input_image = vpp::clone(vpp::from_opencv<vpp::vuchar3 >(cv::imread(basefilename + std::to_string(s) + ext)));\n\t    vpp::pixel_wise(input_image, input_image_double) | converter; \n\t    \n\t    #pragma omp parallel for\n\t    for(int r = 0; r < nr; ++r){\n\t\tvalue_type* row_pointer3d = &noise_img_(s, r, 0);\n\t\tvalue_type* row_pointer2d = &input_image_double(r,0);\n\t\tfor(int c = 0; c < nc; ++c)\n\t\t    row_pointer3d[c] = row_pointer2d[c];\n\t    }\n\t}\n    img_ = storage_type(noise_img_.domain());\n    clone3d(noise_img_, img_);\n\n    initInp();\n    initEdgeweights();\n}\n\n\ntemplate <typename MANIFOLD>\nvoid Data<MANIFOLD, 3>::readMatrixDataFromCSV(std::string filename, const int nz, const int ny, const int nx){\n    #ifdef TV_DATA_DEBUG\n\tstd::cout << \"ReadMatrixData from CSV File...\" << std::endl;\n    #endif\n    noise_img_ = storage_type(nz, ny, nx);\n    //fill3d(noise_img_, MANIFOLD::value_type::Zero());\n\n    const int N = MANIFOLD::value_type::RowsAtCompileTime; \n    const int N2 = MANIFOLD::value_dim;\n    int cols, rows = 0;\n\n    std::ifstream infile(filename, std::ifstream::in);\n    \n    std::string line = \"\";\n    while (std::getline(infile, line)){\n\tstd::stringstream strstr(line);\n\tstd::string word = \"\";\n\t\n\tif(cols == 0)\n\t    while (std::getline(strstr, word, ','))\n\t\tcols++;\n\t\n\trows++;\n    }\n\n    assert(N2 == cols);\n    assert(nz*nx*ny == rows);\n    \n    infile.clear();\n    infile.seekg(0, std::ios_base::beg);\n    \n    Eigen::Matrix<typename MANIFOLD::scalar_type, N2, 1> vectorizedMat;\n    vectorizedMat.setZero();\n\n    auto it = noise_img_.begin();\n    while (std::getline(infile, line)){\n\tstd::stringstream strstr(line);\n\tstd::string word = \"\";\n\tint j=0;\n\twhile (std::getline(strstr, word,',')){\n\t    typename MANIFOLD::scalar_type entry= static_cast<typename MANIFOLD::scalar_type>(std::stod(word));\n\t    vectorizedMat(j) = entry;\n\t    ++j;\n\t}\n\t*it = Eigen::Map<typename MANIFOLD::value_type>(vectorizedMat.data());\n\tit.next();\n    }\n    img_ = storage_type(noise_img_.domain()); \n    clone3d(noise_img_, img_);\n\n    initInp();\n    initEdgeweights();\n}\n\ntemplate <typename MANIFOLD>\nvoid Data<MANIFOLD, 3>::readRawVolumeData(std::string filename, const int nz, const int ny, const int nx){\n\n    static_assert(MANIFOLD::MyType == EUCLIDIAN, \"readRawVolumeData is only Implemented for Euclidian Manifolds\");\n    static_assert(MANIFOLD::value_dim == 1, \"readMatrixDataFromCSV is only for grayscale volume picture input\");\n\n    int pixel_num = nz * ny * nx;\n    noise_img_ = storage_type(nz, ny, nx);\n\n    std::string fname(filename);\n    std::fstream file;\n    file.open(fname, std::ios::in|std::ios::binary|std::ios::ate);\n\n    std::streampos size;\n    char* buffer;\n    bool read_failure = true;\n\n    std::cout << \"Reading file \" << fname << \" with dimensions(Slices, Rows, Cols) \" << nz << \" X \" << ny << \" X \" << nx << std::endl;\n    std::cout << \"Number of pixels = \" << pixel_num << std::endl;\n\n    if(file.is_open()){\n\tsize = file.tellg();\n\tbuffer = new char[size];\n\tfile.seekg(0, std::ios::beg);\n\tfile.read(buffer, size);\n\tfile.close();\n\tread_failure = false;\n    }\n\n    if(read_failure){\n\tstd::cout << \"File import not successfull!\" << std::endl;\n\treturn;\n\t}\n\n    std::cout << \"File successfully imported! File Size = \" << size << \" Bytes\" <<std::endl;\n    \n    assert(size == pixel_num);\n\n    int k = 0;\n    for(auto& p : noise_img_){\n\tdouble px = static_cast<double>(buffer[k]) / static_cast<double>(std::numeric_limits<unsigned char>::max());\n\tp.setConstant(px);\n\t++k;\n    }\n    \n    img_ = storage_type(noise_img_.domain()); \n    clone3d(noise_img_, img_);\n\n    initInp();\n    initEdgeweights();\n\n}\n\ntemplate < typename MANIFOLD >\ntemplate < class IMG >\nvoid Data<MANIFOLD, 3>::output_matval_img(const IMG& img, std::string filename) const{\n    int ns = img.nslices();\n    int nr = img.nrows();\n    int nc = img.ncols();\n\n    std::fstream f;\n    f.open(filename, std::fstream::out);\n    Eigen::IOFormat CommaInitFmt(Eigen::StreamPrecision, Eigen::DontAlignCols, \", \", \", \", \"\", \"\", \"\", \"\\n\");\n    for (int s=0; s < ns; s++){\n\tfor (int r=0; r < nr; r++){\n\t    const auto* cur = &img(s, r, 0);\n\t    for (int c=0; c < nc; c++)\n\t\tf << cur[c].format(CommaInitFmt);\n\t}\n    }\n/*\nfor (int c=0; c < nc; c++)\nfor (int r=0; r < nr; r++)\nfor (int s=0; s < ns; s++)\n    f << img(s, r, c).format(CommaInitFmt);\n\n    f.close();*/\n}\n\n}// end namespace tvmtl\n\n#endif\n", "meta": {"hexsha": "1aed7f33c4a8b093e57d14fba372a8a35c45a707", "size": 10886, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mtvmtl/core/data3d.hpp", "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": "mtvmtl/core/data3d.hpp", "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": "mtvmtl/core/data3d.hpp", "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": 29.9065934066, "max_line_length": 148, "alphanum_fraction": 0.6691162962, "num_tokens": 3132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706733, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.5206420840583678}}
{"text": "//\n//  geometry.cpp\n//  autd3\n//\n//  Created by Seki Inoue on 6/8/16.\n//\n//\n\n#include <stdio.h>\n#include <map>\n#include <Eigen/Geometry>\n#include \"autd3.hpp\"\n#include \"privdef.hpp\"\n\nclass Device {\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    Device(int device_id, Eigen::Vector3f position, Eigen::Vector3f euler_angles)\n    : device_id(device_id), position(position), euler_angles(euler_angles) {\n        Eigen::Quaternionf quo =\n            Eigen::AngleAxisf(euler_angles.x(), Eigen::Vector3f::UnitZ()) *\n            Eigen::AngleAxisf(euler_angles.y(), Eigen::Vector3f::UnitY()) *\n            Eigen::AngleAxisf(euler_angles.z(), Eigen::Vector3f::UnitZ());\n        \n        transform_matrix = Eigen::Translation3f(position) * quo;\n        z_direction = quo * Eigen::Vector3f(0, 0, 1);\n        \n        int index = 0;\n        for (int y = 0; y < NUM_TRANS_Y; y++)\n            for (int x = 0; x < NUM_TRANS_X; x++)\n                if (!IS_MISSING_TRANSDUCER(x, y))\n                    local_trans_positions.col(index++) = Eigen::Vector3f(x*TRANS_SIZE, y*TRANS_SIZE, 0);\n        \n        global_trans_positions = transform_matrix * local_trans_positions;\n    };\n    int device_id;\n    Eigen::Vector3f position;\n    Eigen::Matrix<float, 3, NUM_TRANS_IN_UNIT> local_trans_positions;\n    Eigen::Matrix<float, 3, NUM_TRANS_IN_UNIT> global_trans_positions;\n    Eigen::Vector3f euler_angles;\n    Eigen::Vector3f z_direction;\n    Eigen::Affine3f transform_matrix;\n};\n\nclass autd::Geometry::impl {\npublic:\n    std::vector<std::shared_ptr<Device> > devices;\n    std::shared_ptr<Device> device(int transducer_id) {\n        int eid = transducer_id/NUM_TRANS_IN_UNIT;\n        return this->devices[eid];\n    }\n};\n\nautd::GeometryPtr autd::Geometry::Create() {\n    return GeometryPtr(new Geometry);\n}\n\nautd::Geometry::Geometry() {\n    this->_pimpl = std::unique_ptr<impl>(new impl());\n}\n\nautd::Geometry::~Geometry() {\n   \n}\n\nint autd::Geometry::AddDevice(Eigen::Vector3f position, Eigen::Vector3f euler_angles) {\n    int device_id = this->_pimpl->devices.size();\n    this->_pimpl->devices.push_back(std::shared_ptr<Device>(new Device(device_id, position, euler_angles)));\n    return device_id;\n}\n\nvoid autd::Geometry::DelDevice(int device_id) {\n    auto itr = this->_pimpl->devices.begin();\n    while (itr != this->_pimpl->devices.end())\n    {\n        if((*itr)->device_id == device_id) itr = this->_pimpl->devices.erase(itr);\n        else itr++;\n    }\n}\n\nconst int autd::Geometry::numDevices() {\n    return this->_pimpl->devices.size();\n}\n\nconst int autd::Geometry::numTransducers() {\n    return this->numDevices()*NUM_TRANS_IN_UNIT;\n}\n\nconst Eigen::Vector3f autd::Geometry::position(int transducer_id) {\n    const int local_trans_id = transducer_id%NUM_TRANS_IN_UNIT;\n    auto device = this->_pimpl->device(transducer_id);\n    return device->global_trans_positions.col(local_trans_id);\n}\n\nconst Eigen::Vector3f &autd::Geometry::direction(int transducer_id) {\n    return this->_pimpl->devices[this->deviceIdForTransIdx(transducer_id)]->z_direction;\n}\n\nconst int autd::Geometry::deviceIdForDeviceIdx(int device_idx) {\n    return this->_pimpl->devices[device_idx]->device_id;\n}\n\nconst int autd::Geometry::deviceIdForTransIdx(int transducer_id) {\n    return this->_pimpl->device(transducer_id)->device_id;\n}\n\n\nfloat  autd::Geometry::frequency() {\n    return FPGA_CLOCK / (640.0 + this->_freq_shift);\n}\n\nvoid   autd::Geometry::SetFrequency(float freq) {\n    this->_freq_shift = std::min(std::max(FPGA_CLOCK / freq - 640, (float)std::numeric_limits<int8_t>::min()), (float)std::numeric_limits<int8_t>::max());\n}", "meta": {"hexsha": "cd7cef8570eb86532dfef5b432d8ee3269edcad8", "size": 3592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "client/lib/geometry.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/geometry.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/geometry.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": 31.5087719298, "max_line_length": 154, "alphanum_fraction": 0.6773385301, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5206011259911848}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n/// \\file\n/// Declares function RootFinder::toms748\n\n#pragma once\n\n#include <boost/math/tools/roots.hpp>\n#include <functional>\n#include <limits>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"ErrorHandling/Exceptions.hpp\"\n\nnamespace RootFinder {\n\n/*!\n * \\ingroup NumericalAlgorithmsGroup\n * \\brief Finds the root of the function `f` with the TOMS_748 method.\n *\n * `f` is a unary invokable that takes a `double` which is the current value at\n * which to evaluate `f`. An example is below.\n *\n * \\snippet Test_TOMS748.cpp double_root_find\n *\n * The TOMS_748 algorithm searches for a root in the interval [`lower_bound`,\n * `upper_bound`], and will throw if this interval does not bracket a root,\n * i.e. if `f(lower_bound) * f(upper_bound) > 0`.\n *\n * The arguments `f_at_lower_bound` and `f_at_upper_bound` are optional, and\n * are the function values at `lower_bound` and `upper_bound`. These function\n * values are often known because the user typically checks if a root is\n * bracketed before calling `toms748`; passing the function values here saves\n * two function evaluations.\n *\n * See the [Boost](http://www.boost.org/) documentation for more details.\n *\n * \\requires Function `f` is invokable with a `double`\n *\n * \\throws `std::domain_error` if the bounds do not bracket a root.\n * \\throws `convergence_error` if the requested tolerance is not met after\n *                            `max_iterations` iterations.\n */\ntemplate <typename Function>\ndouble toms748(const Function& f, const double lower_bound,\n               const double upper_bound, const double f_at_lower_bound,\n               const double f_at_upper_bound, const double absolute_tolerance,\n               const double relative_tolerance,\n               const size_t max_iterations = 100) {\n  ASSERT(relative_tolerance > std::numeric_limits<double>::epsilon(),\n         \"The relative tolerance is too small.\");\n\n  boost::uintmax_t max_iters = max_iterations;\n\n  // This solver requires tol to be passed as a termination condition. This\n  // termination condition is equivalent to the convergence criteria used by the\n  // GSL\n  auto tol = [absolute_tolerance, relative_tolerance](double lhs, double rhs) {\n    return (fabs(lhs - rhs) <=\n            absolute_tolerance +\n                relative_tolerance * fmin(fabs(lhs), fabs(rhs)));\n  };\n  // clang-tidy: internal boost warning, can't fix it.\n  auto result = boost::math::tools::toms748_solve(  // NOLINT\n      f, lower_bound, upper_bound, f_at_lower_bound, f_at_upper_bound, tol,\n      max_iters);\n  if (max_iters >= max_iterations) {\n    throw convergence_error(\n        \"toms748 reached max iterations without converging\");\n  }\n  return result.first + 0.5 * (result.second - result.first);\n}\n\n/*!\n * \\ingroup NumericalAlgorithmsGroup\n * \\brief Finds the root of the function `f` with the TOMS_748 method,\n * where function values are not supplied at the lower and upper\n * bounds.\n */\ntemplate <typename Function>\ndouble toms748(const Function& f, const double lower_bound,\n               const double upper_bound, const double absolute_tolerance,\n               const double relative_tolerance,\n               const size_t max_iterations = 100) {\n  return toms748(f, lower_bound, upper_bound, f(lower_bound), f(upper_bound),\n                 absolute_tolerance, relative_tolerance, max_iterations);\n}\n\nnamespace detail {\ntemplate <typename Function>\nDataVector toms748_impl(const Function& f, const DataVector& lower_bound,\n                        const DataVector& upper_bound,\n                        const DataVector& f_at_lower_bound,\n                        const DataVector& f_at_upper_bound,\n                        const double absolute_tolerance,\n                        const double relative_tolerance,\n                        const size_t max_iterations,\n                        const bool function_values_are_supplied) {\n  ASSERT(relative_tolerance > std::numeric_limits<double>::epsilon(),\n         \"The relative tolerance is too small.\");\n  // This solver requires tol to be passed as a termination condition. This\n  // termination condition is equivalent to the convergence criteria used by the\n  // GSL\n  auto tol = [absolute_tolerance, relative_tolerance](const double lhs,\n                                                      const double rhs) {\n    return (fabs(lhs - rhs) <=\n            absolute_tolerance +\n                relative_tolerance * fmin(fabs(lhs), fabs(rhs)));\n  };\n  DataVector result_vector{lower_bound.size()};\n  for (size_t i = 0; i < result_vector.size(); ++i) {\n    // toms748_solver modifies the max_iters after the root is found to the\n    // number of iterations that it took to find the root, so we reset it to\n    // max_iterations after each root find.\n    boost::uintmax_t max_iters = max_iterations;\n    auto result = function_values_are_supplied\n                      ?\n                      // clang-tidy: internal boost warning, can't fix it.\n                      boost::math::tools::toms748_solve(  // NOLINT\n                          [&f, i](double x) { return f(x, i); }, lower_bound[i],\n                          upper_bound[i], f_at_lower_bound[i],\n                          f_at_upper_bound[i], tol, max_iters)\n                      :\n                      // clang-tidy: internal boost warning, can't fix it.\n                      boost::math::tools::toms748_solve(  // NOLINT\n                          [&f, i](double x) { return f(x, i); }, lower_bound[i],\n                          upper_bound[i], tol, max_iters);\n    if (max_iters >= max_iterations) {\n      throw convergence_error(\n          \"toms748 reached max iterations without converging\");\n    }\n    result_vector[i] = result.first + 0.5 * (result.second - result.first);\n  }\n  return result_vector;\n}\n}  // namespace detail\n\n/*!\n * \\ingroup NumericalAlgorithmsGroup\n * \\brief Finds the root of the function `f` with the TOMS_748 method on each\n * element in a `DataVector`.\n *\n * `f` is a binary invokable that takes a `double` as its first argument and a\n * `size_t` as its second. The `double` is the current value at which to\n * evaluate `f`, and the `size_t` is the current index into the `DataVector`s.\n * Below is an example of how to root find different functions by indexing into\n * a lambda-captured `DataVector` using the `size_t` passed to `f`.\n *\n * \\snippet Test_TOMS748.cpp datavector_root_find\n *\n * For each index `i` into the DataVector, the TOMS_748 algorithm searches for a\n * root in the interval [`lower_bound[i]`, `upper_bound[i]`], and will throw if\n * this interval does not bracket a root,\n * i.e. if `f(lower_bound[i], i) * f(upper_bound[i], i) > 0`.\n *\n * See the [Boost](http://www.boost.org/) documentation for more details.\n *\n * \\requires Function `f` be callable with a `double` and a `size_t`\n *\n * \\throws `std::domain_error` if, for any index, the bounds do not bracket a\n * root.\n * \\throws `convergence_error` if, for any index, the requested tolerance is not\n * met after `max_iterations` iterations.\n */\ntemplate <typename Function>\nDataVector toms748(const Function& f, const DataVector& lower_bound,\n                   const DataVector& upper_bound,\n                   const double absolute_tolerance,\n                   const double relative_tolerance,\n                   const size_t max_iterations = 100) {\n  return detail::toms748_impl(f, lower_bound, upper_bound, DataVector{},\n                              DataVector{}, absolute_tolerance,\n                              relative_tolerance, max_iterations, false);\n}\n\n/*!\n * \\ingroup NumericalAlgorithmsGroup\n * \\brief Finds the root of the function `f` with the TOMS_748 method on each\n * element in a `DataVector`, where function values are supplied at the lower\n * and upper bounds.\n *\n * Supplying function values is an optimization that saves two\n * function calls per point.  The function values are often available\n * because one often checks if the root is bracketed before calling `toms748`.\n */\ntemplate <typename Function>\nDataVector toms748(const Function& f, const DataVector& lower_bound,\n                   const DataVector& upper_bound,\n                   const DataVector& f_at_lower_bound,\n                   const DataVector& f_at_upper_bound,\n                   const double absolute_tolerance,\n                   const double relative_tolerance,\n                   const size_t max_iterations = 100) {\n  return detail::toms748_impl(f, lower_bound, upper_bound, f_at_lower_bound,\n                              f_at_upper_bound, absolute_tolerance,\n                              relative_tolerance, max_iterations, true);\n}\n\n}  // namespace RootFinder\n", "meta": {"hexsha": "ba7b2bd43c210f525c0ed6cfcf21dbd226fbff3b", "size": 8698, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/NumericalAlgorithms/RootFinding/TOMS748.hpp", "max_stars_repo_name": "tomwlodarczyk/spectre", "max_stars_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NumericalAlgorithms/RootFinding/TOMS748.hpp", "max_issues_repo_name": "tomwlodarczyk/spectre", "max_issues_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NumericalAlgorithms/RootFinding/TOMS748.hpp", "max_forks_repo_name": "tomwlodarczyk/spectre", "max_forks_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_forks_repo_licenses": ["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.2736318408, "max_line_length": 80, "alphanum_fraction": 0.6588871005, "num_tokens": 1911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.5205771977384472}}
{"text": "/**\n * Created on Tue Jan 04 2022\n *\n * Shane Flandermeyer, shaneflandermeyer@gmail.com\n *\n * A simple example usage of the CFAR detection object when the input is\n * gaussian noise with a time-varying variance. This example is adapted from\n * https://www.mathworks.com/help/phased/ug/constant-false-alarm-rate-cfar-detection.html\n */\n\n#include \"cfar1d.h\"\n#include \"matrix_utils.h\"\n\n#include <random>\n#include <Eigen/Dense>\n#include <matplot/matplot.h>\n\nusing namespace plasma;\nusing namespace matplot;\nusing namespace Eigen;\nint main() {\n\n  //! CFAR parameters\n  auto method = \"CA\";\n  size_t num_guard_cells = 2;\n  size_t num_train_cells = 200;\n  auto pfa = 1e-3;\n  CFARDetector cfar{num_train_cells, num_guard_cells, pfa};\n\n  //! Generate data\n  // The input data is a square-law input signal with increasing noise power\n  auto noise_power = pow(10, -10 / 10);\n  size_t num_points = 10e3;\n  // std::default_random_engine gen;\n  MatrixXcd rsamp(num_points, 1);\n  MatrixXd x(rsamp.rows(), rsamp.cols());\n  // Start with samples from a complex standard normal distribution\n  std::mt19937 gen{1000};\n  std::normal_distribution<> normal{0, 1};\n  for (size_t i = 0; i < num_points; ++i)\n    rsamp(i) = std::complex<double>(normal(gen), normal(gen));\n  // Create the square-law input signal\n  ArrayXd ramp = ArrayXd::LinSpaced(num_points, 1, 10);\n  x = abs2(sqrt(noise_power * ramp / 2) * rsamp.array()).matrix();\n  // x = hcat(x,x);\n\n  //! Write to a file\n  // std::vector<double> filevec(x.data(), x.data() + x.size());\n  // write_binary<double>(\"/home/shane/bin.dat\",filevec);\n\n  //! Do CFAR\n  DetectionReport det = cfar.detect(x);\n\n  //! Figures\n  // Input data\n  std::vector<double> xvec(x.data(), x.data() + x.size());\n  std::vector<double> threshvec(det.threshold.data(),\n                                det.threshold.data() + det.threshold.size());\n  std::vector<size_t> indices(det.indices.col(0).data(),\n                              det.indices.col(0).data() +\n                                  det.indices.col(0).size());\n  std::vector<double> detvec(det.indices.size());\n  for (size_t i = 0; i < det.indices.size(); ++i)\n    detvec[i] = x(det.indices(i));\n\n  std::cout << \"Number of Detections: \" << det.num_detections << std::endl;\n\n  plot(xvec);\n  hold(true);\n  plot(threshvec);\n  plot(indices, detvec, \"o\");\n  hold(false);\n  show();\n  return 0;\n}", "meta": {"hexsha": "33b83db1c5b954816059fbec5091380896a59dad", "size": 2357, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/cfar1d_example.cpp", "max_stars_repo_name": "ShaneFlandermeyer/plasma-dsp", "max_stars_repo_head_hexsha": "50d969f3873052a582e2b17745c469a8d22f0fe1", "max_stars_repo_licenses": ["MIT"], "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/cfar1d_example.cpp", "max_issues_repo_name": "ShaneFlandermeyer/plasma-dsp", "max_issues_repo_head_hexsha": "50d969f3873052a582e2b17745c469a8d22f0fe1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2022-01-12T19:04:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T15:07:41.000Z", "max_forks_repo_path": "examples/cfar1d_example.cpp", "max_forks_repo_name": "ShaneFlandermeyer/plasma-dsp", "max_forks_repo_head_hexsha": "50d969f3873052a582e2b17745c469a8d22f0fe1", "max_forks_repo_licenses": ["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.4266666667, "max_line_length": 89, "alphanum_fraction": 0.6491302503, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5205771977384472}}
{"text": "#include <iostream>\n\n#include <unistd.h>\n#include <cuda.h>\n#include <cuda_runtime_api.h>\n\n#include <blitz.h>\n\nusing namespace blitz;\n// M K\nShape left_shape(2);\n// K N\nShape right_shape(2);\n// M N\nShape output_shape(2);\n\nvoid compare_cpu_gpu(size_t size, float* output_cpu, float* output_gpu) {\n  for (size_t i = 0; i < size; ++i) {\n    if (output_cpu[i] > output_gpu[i] + 1e-3 ||\n      output_cpu[i] < output_gpu[i] - 1e-3) {\n      std::cout << \"Index: \" << i << \", CPU: \" << output_cpu[i] <<\n        \", GPU: \" << output_gpu[i] << std::endl;\n    }\n  }\n}\n\nvoid multiply(size_t m, size_t n, size_t k, BLITZ_ALGORITHM algorithm, string trans) {\n  bool left_trans, right_trans;\n  // set shapes\n  if (trans == \"nn\") {\n    left_trans = false;\n    right_trans = false;\n    left_shape[0] = m;\n    left_shape[1] = k;\n    right_shape[0] = k;\n    right_shape[1] = n;\n    output_shape[0] = m;\n    output_shape[1] = n;\n  } else if (trans == \"tn\") {\n    left_trans = true;\n    right_trans = false;\n    left_shape[0] = k;\n    left_shape[1] = m;\n    right_shape[0] = k;\n    right_shape[1] = n;\n    output_shape[0] = m;\n    output_shape[1] = n;\n  } else if (trans == \"nt\") {\n    left_trans = false;\n    right_trans = true;\n    left_shape[0] = m;\n    left_shape[1] = k;\n    right_shape[0] = n;\n    right_shape[1] = k;\n    output_shape[0] = m;\n    output_shape[1] = n;\n  } else {\n    std::cerr << \"No such transform method!\" << std::endl;\n    exit(1);\n  }\n  // set up cpu\n  CPUTensor<float> left_cpu(left_shape);\n  CPUTensor<float> right_cpu(right_shape);\n  CPUTensor<float> output_cpu(output_shape);\n  // set up gpu\n  GPUTensor<float> left_gpu(left_shape);\n  GPUTensor<float> right_gpu(right_shape);\n  GPUTensor<float> output_gpu(output_shape);\n  CPUTensor<float> output_copy(output_shape);\n  // init values\n  Backend<CPUTensor, float>::UniformDistributionFunc(&left_cpu, 0.0, 1.0);\n  Backend<CPUTensor, float>::UniformDistributionFunc(&right_cpu, 0.0, 1.0);\n  cudaMemcpy(left_gpu.data(), left_cpu.data(),\n    left_cpu.size() * sizeof(float), cudaMemcpyHostToDevice);\n  cudaMemcpy(right_gpu.data(), right_cpu.data(),\n    right_cpu.size() * sizeof(float), cudaMemcpyHostToDevice);\n  // transpose\n  Backend<CPUTensor, float>::MatrixMultiplyFunc(&left_cpu, &right_cpu, &output_cpu, left_trans, right_trans, 1.0, 0.0, algorithm);\n  Backend<GPUTensor, float>::MatrixMultiplyFunc(&left_gpu, &right_gpu, &output_gpu, left_trans, right_trans, 1.0, 0.0, algorithm);\n  // copy from gpu to cpu\n  cudaMemcpy(output_copy.data(), output_gpu.data(),\n    output_gpu.size() * sizeof(float), cudaMemcpyDeviceToHost);\n  compare_cpu_gpu(output_cpu.size(), output_cpu.data(), output_copy.data());\n}\n\nint main(int argc, char** argv) {\n  const size_t NUM_ARGS = 5;\n  // M N K\n  if (argc != NUM_ARGS + 1) {\n    std::cerr << \"Not matchable args!\" << std::endl;\n    exit(1);\n  }\n  std::string kernel = std::string(argv[1]);\n  std::string trans = std::string(argv[2]);\n  const size_t M = atoi(argv[3]);\n  const size_t N = atoi(argv[4]);\n  const size_t K = atoi(argv[5]);\n  // run\n  multiply(M, N, K, BlitzParseAlgorithm(kernel), trans);\n  return 0;\n}\n", "meta": {"hexsha": "68a622e876b6b40640eb1390ff09b2f5dbf874f1", "size": 3107, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/gpu/matrix/matrix_multiply.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/gpu/matrix/matrix_multiply.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/gpu/matrix/matrix_multiply.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": 30.4607843137, "max_line_length": 130, "alphanum_fraction": 0.6475700032, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5205771922188102}}
{"text": "// -----------------------------------------------------------------------------\n// Filename:    Coord_Process.hpp\n// Revision:    None\n// Date:        2018/09/24 - 10:10\n// Author:      Haixiang HOU\n// Email:       hexid26@outlook.com\n// Website:     [NULL]\n// Notes:       [NULL]\n// -----------------------------------------------------------------------------\n// Copyright:   2018 (c) Haixiang\n// License:     GPL\n// -----------------------------------------------------------------------------\n// Version [1.0]\n// Calculate the coordinates of senders/receivers and sample points.\n\n#include <boost/asio.hpp>\n#include <boost/atomic.hpp>\n#include <boost/thread.hpp>\n#include <chrono>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\n#include \"define.hpp\"\n\nclass Coord_Process {\n  private:\n    boost::atomic_int saved_files;\n    float dis_farest_point;                            // \u6210\u50cf\u70b9\u5230\u5706\u5fc3\u7684\u8ddd\u79bb\n    unsigned long long pre_malloc_points_per_triangle; // \u9884\u5148\u7528\u6765\u4fdd\u5b58\u5355\u4e2a\u4e09\u89d2\u5f62\u70b9\u5750\u6807\u7684\u7a7a\u95f4\u5927\u5c0f\n    uint16_t point_sum_per_line;                       // \u6210\u50cf\u70b9\u6bcf\u884c\u7684\u4e2a\u6570\uff0c\u56fe\u4e3a\u6b63\u65b9\u5f62\n    float coord_step;                                  // \u5f53\u524d\u6210\u50cf\u5206\u8fa8\u7387\u4e0b\u5750\u6807\u6807\u51c6\u65b9\u5411\u4e0a\u7684\u6b65\u8fdb\n    void initialize(uint16_t num);\n    void calc_ele_coords();\n    void calc_all_triangles();\n    inline float change_coord_to_int(float num, float step);\n    void calc_sample_points_coords_by_ele_snd_id(uint16_t triangle_id);\n    void save_sample_points_in_triangle(uint16_t ele_snd_id);\n\n  public:\n    float ele_coord_array_x[ELE_NO], ele_coord_array_y[ELE_NO]; //\u632f\u5143\u5750\u6807\n    float *triangle_vertex_x, *triangle_vertex_y;               // \u6240\u6709\u4e09\u89d2\u5f62\u9876\u70b9\u5750\u6807\n    unsigned long long temp_sample_points_coords_cnt[ELE_NO];        //\u6bcf\u4e2a\u53d1\u5c04\u6e90\u626b\u63cf\u533a\u7684\u70b9\u6570\n    uint16_t **temp_sample_points_coords;              // \u4e8c\u7ef4\u6570\u7ec4[ELE_NO][\u91c7\u6837\u70b9\u6570]\n    void calc_all_sample_points_coords(int thread_sum);         // \u591a\u7ebf\u7a0b\u8ba1\u7b97\u6240\u6709\u626b\u63cf\u533a\u4e2d\uff0c\u70b9\u7684\u5750\u6807\n    void save_all_triangles(int thread_sum);                    // \u591a\u7ebf\u7a0b\u4fdd\u5b58\u6587\u4ef6\n    void print_ele_coords();\n    void print_triangles_vertex();\n    void print_sample_points_info();\n    Coord_Process(uint16_t num);\n    ~Coord_Process();\n};\n\nCoord_Process::Coord_Process(uint16_t num) { initialize(num); }\n\n// num \u662f\u6210\u50cf\u5206\u8fa8\u7387\u5355\u7ef4\u70b9\u6570\nvoid Coord_Process::initialize(uint16_t num) {\n    dis_farest_point = RADIUS - 0.01; // \u8ddd\u79bb\u63a2\u5934 10mm \u7684\u4e0d\u6210\u50cf\n    point_sum_per_line = num;\n    coord_step = IMAGE_WIDTH / (point_sum_per_line - 1);\n    pre_malloc_points_per_triangle =\n        (unsigned long long)(num * num * RADIUS * RADIUS * tan(PI / 18) / IMAGE_WIDTH / IMAGE_WIDTH);\n    printf(\"Points per triangle: %llu\\nPre malloc memory: %.2fGB\\n\", pre_malloc_points_per_triangle,\n           pre_malloc_points_per_triangle * ELE_NO * 2 * 2 / 1024.0 / 1024.0 / 1024.0);\n    calc_ele_coords();\n    triangle_vertex_x = (float *)calloc(3 * sizeof(float), ELE_NO);\n    triangle_vertex_y = (float *)calloc(3 * sizeof(float), ELE_NO);\n    temp_sample_points_coords = new uint16_t *[ELE_NO];\n    for (uint16_t ele_snd_id = 0; ele_snd_id < ELE_NO; ele_snd_id++) {\n        temp_sample_points_coords[ele_snd_id] =\n            (uint16_t *)calloc(2 * sizeof(uint16_t), pre_malloc_points_per_triangle);\n    }\n    calc_all_triangles();\n}\n\nCoord_Process::~Coord_Process() {\n    free(triangle_vertex_x);\n    free(triangle_vertex_y);\n    for (uint16_t index = 0; index < point_sum_per_line; index++) {\n        free(temp_sample_points_coords[index]);\n    }\n}\n\n// \u8ba1\u7b97\u6240\u6709\u53d1\u5c04\u6e90\u7684\u5750\u6807\nvoid Coord_Process::calc_ele_coords() {\n    float raduis = RADIUS;\n    float ele_angle_offset = (2 * PI * 43.4695 / (256 - 1)) / 360; //\u9635\u5143\u95f4\u9694\u89d2\u5ea6\n    float start_ele_angle = 2 * PI * (45 - 43.4695) / 360;         //\u7b2c\u4e00\u4e2a\u9635\u5143\u89d2\u5ea6\n    /* for (int start_ele_id = 0; start_ele_id < 256; start_ele_id++) {\n        ele_coord_array_x[start_ele_id] =\n            raduis * cos(start_ele_angle + start_ele_id * ele_angle_offset);\n        ele_coord_array_y[start_ele_id] =\n            -raduis * sin(start_ele_angle + start_ele_id * ele_angle_offset);\n    } */\n    // \u628a\u4e0a\u9762\u7684 for \u5faa\u73af\u878d\u5165\u5230\u4e0b\u9762\u4f1a\u4ea7\u751f\u8bef\u5dee\uff0c\u4f46\u662f\u4e0a\u9762\u7684\u7ed3\u679c\u4e0d\u7b26\u5408\u53ef90\u5ea6\u65cb\u8f6c\u539f\u7406\n    for (int start_ele_id = 0; start_ele_id < ELE_NO; start_ele_id++) {\n        ele_coord_array_x[start_ele_id] = raduis * cos(start_ele_angle + (start_ele_id % 256) * ele_angle_offset +\n                                                       (int)(start_ele_id / 256) * PI / 4);\n        ele_coord_array_y[start_ele_id] = -raduis * sin(start_ele_angle + (start_ele_id % 256) * ele_angle_offset +\n                                                        (int)(start_ele_id / 256) * PI / 4);\n    }\n}\n\n// \u8ba1\u7b97\u6240\u6709\u53d1\u5c04\u6e90\u626b\u63cf\u533a(\u4e09\u89d2\u5f62)\u7684\u4e09\u70b9\u5750\u6807\nvoid Coord_Process::calc_all_triangles() {\n    float radius = RADIUS;\n    float temp_point[3][2];   // 3\u4e2a\u70b9\uff0c\u6bcf\u4e2a\u70b92\u4e2a\u5750\u6807\u503c\n    uint16_t high_id, low_id; // \u6700\u9ad8\u70b9\u548c\u6700\u4f4e\u70b9\u7684 id\n    for (uint16_t start_ele_id = 0; start_ele_id < ELE_NO; start_ele_id++) {\n        temp_point[0][0] = ele_coord_array_x[start_ele_id];\n        temp_point[0][1] = ele_coord_array_y[start_ele_id];\n        temp_point[1][0] = sin(PI / 18) * radius *\n                           sqrtf(ele_coord_array_y[start_ele_id] * ele_coord_array_y[start_ele_id] / (radius * radius));\n        temp_point[1][1] = -(temp_point[0][0] * temp_point[1][0]) / temp_point[0][1];\n        temp_point[2][0] = -temp_point[1][0];\n        temp_point[2][1] = -temp_point[1][1];\n        // \u6392\u5e8f\n\n        for (uint16_t index = 0; index < 3; index++) {\n            if (temp_point[index][1] == std::max(std::max(temp_point[0][1], temp_point[1][1]), temp_point[2][1])) {\n                high_id = index;\n            }\n        }\n        for (uint16_t index = 0; index < 3; index++) {\n            if (temp_point[index][1] == std::min(std::min(temp_point[0][1], temp_point[1][1]), temp_point[2][1])) {\n                low_id = index;\n            }\n        }\n\n        triangle_vertex_x[3 * start_ele_id] = temp_point[high_id][0];\n        triangle_vertex_y[3 * start_ele_id] = temp_point[high_id][1];\n        triangle_vertex_x[3 * start_ele_id + 1] = temp_point[3 - high_id - low_id][0];\n        triangle_vertex_y[3 * start_ele_id + 1] = temp_point[3 - high_id - low_id][1];\n        triangle_vertex_x[3 * start_ele_id + 2] = temp_point[low_id][0];\n        triangle_vertex_y[3 * start_ele_id + 2] = temp_point[low_id][1];\n    }\n    return;\n}\n\n// \u628a\u4e09\u89d2\u5f62\u4e09\u70b9\u5750\u6807\u8f6c\u79fb\u5230\u6574\u6570\u7a7a\u95f4\ninline float Coord_Process::change_coord_to_int(float num, float step) {\n    return (num + (point_sum_per_line - 1) / 2 * step) / step;\n}\n\n// \u626b\u63cf\u5355\u4e2a\u4e09\u89d2\u5f62\u4e2d\u7684\u70b9\nvoid Coord_Process::calc_sample_points_coords_by_ele_snd_id(uint16_t triangle_id) {\n    float high_point_x = triangle_vertex_x[3 * triangle_id];\n    float mid_point_x = triangle_vertex_x[3 * triangle_id + 1];\n    float low_point_x = triangle_vertex_x[3 * triangle_id + 2];\n    float high_point_y = triangle_vertex_y[3 * triangle_id];\n    float mid_point_y = triangle_vertex_y[3 * triangle_id + 1];\n    float low_point_y = triangle_vertex_y[3 * triangle_id + 2];\n    high_point_x = change_coord_to_int(high_point_x, coord_step);\n    mid_point_x = change_coord_to_int(mid_point_x, coord_step);\n    low_point_x = change_coord_to_int(low_point_x, coord_step);\n    high_point_y = change_coord_to_int(high_point_y, coord_step);\n    mid_point_y = change_coord_to_int(mid_point_y, coord_step);\n    low_point_y = change_coord_to_int(low_point_y, coord_step);\n\n    unsigned long long sample_points_sum = 0;\n\n    float temp1, temp2;\n    int min_horizontal_id, max_horizontal_id;\n    for (int row_id = std::max((int)(low_point_y + 1), 0); row_id <= std::min((int)mid_point_y, point_sum_per_line - 1);\n         row_id++) {\n        temp1 = ((float)row_id - low_point_y) * (mid_point_x - low_point_x) / (mid_point_y - low_point_y) + low_point_x;\n        temp2 =\n            ((float)row_id - low_point_y) * (high_point_x - low_point_x) / (high_point_y - low_point_y) + low_point_x;\n        min_horizontal_id = (int)(std::min(temp1, temp2) + 1);\n        max_horizontal_id = (int)(std::max(temp1, temp2));\n        min_horizontal_id = std::max(min_horizontal_id, 0);\n        min_horizontal_id = std::min(min_horizontal_id, point_sum_per_line - 1);\n        max_horizontal_id = std::min(max_horizontal_id, point_sum_per_line - 1);\n        max_horizontal_id = std::max(max_horizontal_id, 0);\n        for (uint16_t index = min_horizontal_id; index <= max_horizontal_id; index++) {\n            if (sqrtf(((float)index - point_sum_per_line / 2) * ((float)index - point_sum_per_line / 2) +\n                      ((float)row_id - point_sum_per_line / 2) * ((float)row_id - point_sum_per_line / 2)) *\n                    coord_step >\n                dis_farest_point) {\n                continue;\n            }\n            temp_sample_points_coords[triangle_id][2 * sample_points_sum] = (uint16_t)index;\n            temp_sample_points_coords[triangle_id][2 * sample_points_sum + 1] = (uint16_t)row_id;\n            sample_points_sum++;\n        }\n    }\n\n    for (int row_id = std::max((int)(mid_point_y + 1), 0);\n         row_id <= std::min((int)high_point_y, point_sum_per_line - 1); row_id++) {\n        temp1 =\n            ((float)row_id - high_point_y) * (high_point_x - mid_point_x) / (high_point_y - mid_point_y) + high_point_x;\n        temp2 =\n            ((float)row_id - low_point_y) * (high_point_x - low_point_x) / (high_point_y - low_point_y) + low_point_x;\n        min_horizontal_id = (int)(std::min(temp1, temp2) + 1);\n        max_horizontal_id = (int)(std::max(temp1, temp2));\n        min_horizontal_id = std::max(min_horizontal_id, 0);\n        min_horizontal_id = std::min(min_horizontal_id, point_sum_per_line - 1);\n        max_horizontal_id = std::min(max_horizontal_id, point_sum_per_line - 1);\n        max_horizontal_id = std::max(max_horizontal_id, 0);\n        for (uint16_t index = min_horizontal_id; index <= max_horizontal_id; index++) {\n            if (sqrtf(((float)index - point_sum_per_line / 2.0) * ((float)index - point_sum_per_line / 2.0) +\n                      ((float)row_id - point_sum_per_line / 2.0) * ((float)row_id - point_sum_per_line / 2.0)) *\n                    coord_step >\n                dis_farest_point) {\n                continue;\n            }\n            temp_sample_points_coords[triangle_id][2 * sample_points_sum] = (uint16_t)index;\n            temp_sample_points_coords[triangle_id][2 * sample_points_sum + 1] = (uint16_t)row_id;\n            sample_points_sum++;\n        }\n    }\n    temp_sample_points_coords_cnt[triangle_id] = sample_points_sum;\n}\n\n// \u591a\u7ebf\u7a0b\u626b\u63cf\u6240\u6709\u7684(2048)\u4e09\u89d2\u5f62\uff0cthread_sum \u901a\u8fc7\u8fdb\u7a0b\u53c2\u6570\u8bbe\u7f6e\nvoid Coord_Process::calc_all_sample_points_coords(int thread_sum) {\n    boost::asio::thread_pool thread_pool_calc(thread_sum);\n    for (uint16_t ele_snd_id = 0; ele_snd_id < ELE_NO; ele_snd_id++) {\n        boost::asio::post(thread_pool_calc,\n                          boost::bind(&Coord_Process::calc_sample_points_coords_by_ele_snd_id, this, ele_snd_id));\n    }\n    thread_pool_calc.join();\n\n    // for (uint16_t ele_snd_id = 0; ele_snd_id < ELE_NO; ele_snd_id++) {\n    //     calc_sample_points_coords_by_ele_snd_id(ele_snd_id);\n    // }\n}\n\n// \u6253\u5370\u6240\u6709\u63a2\u5934\u7684\u5750\u6807\nvoid Coord_Process::print_ele_coords() {\n    for (uint16_t index = 0; index < ELE_NO; index++) {\n        printf(\"[%04d] = %10.8f, %10.8f; [%04d] = %10.8f, %10.8f; [%04d] = %10.8f, %10.8f; [%04d] = %10.8f, %10.8f;\\n\",\n               index, ele_coord_array_x[index], ele_coord_array_y[index], index + ELE_NO / 4,\n               ele_coord_array_x[index + ELE_NO / 4], ele_coord_array_y[index + ELE_NO / 4], index + ELE_NO * 2 / 4,\n               ele_coord_array_x[index + ELE_NO * 2 / 4], ele_coord_array_y[index + ELE_NO * 2 / 4],\n               index + ELE_NO * 3 / 4, ele_coord_array_x[index + ELE_NO * 3 / 4],\n               ele_coord_array_y[index + ELE_NO * 3 / 4]);\n    }\n    return;\n}\n\nvoid Coord_Process::print_triangles_vertex() {\n    for (uint16_t triangle_id = 0; triangle_id < ELE_NO; triangle_id++) {\n        if (triangle_id % 64 == 0) {\n            printf(\n                \"[[%10.8f, %10.8f, %10.8f, %10.8f],[%10.8f, %10.8f, %10.8f, \"\n                \"%10.8f]]\\n\",\n                triangle_vertex_x[3 * triangle_id], triangle_vertex_x[3 * triangle_id + 1],\n                triangle_vertex_x[3 * triangle_id + 2], triangle_vertex_x[3 * triangle_id],\n                triangle_vertex_y[3 * triangle_id], triangle_vertex_y[3 * triangle_id + 1],\n                triangle_vertex_y[3 * triangle_id + 2], triangle_vertex_y[3 * triangle_id]);\n        }\n    }\n}\n\nvoid Coord_Process::print_sample_points_info() {\n    unsigned long long point_sum = 0;\n    for (uint16_t index = 0; index < ELE_NO; index++) {\n        printf(\"Tri_%04u :: Sample point sum = %llu\\n\", index, temp_sample_points_coords_cnt[index]);\n        point_sum += temp_sample_points_coords_cnt[index];\n    }\n}\n\nvoid Coord_Process::save_sample_points_in_triangle(uint16_t ele_snd_id) {\n    char *file_name = new char[17];\n    sprintf(file_name, \"Tri/Tri_%04d.txt\", ele_snd_id);\n    std::ofstream f_stream(file_name, std::fstream::out);\n    std::string content = \"\";\n    for (unsigned long long index = 0; index < temp_sample_points_coords_cnt[ele_snd_id]; index++) {\n        content += std::to_string(temp_sample_points_coords[ele_snd_id][2 * index]) + \",\" +\n                   std::to_string(temp_sample_points_coords[ele_snd_id][2 * index + 1]) + \"\\n\";\n    }\n    f_stream << content;\n    f_stream.close();\n    saved_files++;\n}\n\nvoid Coord_Process::save_all_triangles(int thread_sum) {\n    boost::asio::thread_pool thread_pool_save(40);\n    saved_files = 0;\n    for (uint16_t ele_snd_id = 0; ele_snd_id < ELE_NO; ele_snd_id++) {\n        boost::asio::post(thread_pool_save,\n                          boost::bind(&Coord_Process::save_sample_points_in_triangle, this, ele_snd_id));\n    }\n    while (saved_files < ELE_NO) {\n        printf(\"\\r%06.3f%%\", (float)saved_files / ELE_NO * 100);\n        fflush(stdout);\n        sleep(1);\n    }\n    printf(\"\\r%06.3f%%\\n\", (float)saved_files / ELE_NO * 100);\n}\n", "meta": {"hexsha": "f8468126632125a192fd177355db4f5f5e4b25f1", "size": 13719, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/header/Coord_Process.hpp", "max_stars_repo_name": "chenxull/UDP_Project", "max_stars_repo_head_hexsha": "2490ee11dea3f0a11ff509f59338e510db25d0d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/header/Coord_Process.hpp", "max_issues_repo_name": "chenxull/UDP_Project", "max_issues_repo_head_hexsha": "2490ee11dea3f0a11ff509f59338e510db25d0d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/header/Coord_Process.hpp", "max_forks_repo_name": "chenxull/UDP_Project", "max_forks_repo_head_hexsha": "2490ee11dea3f0a11ff509f59338e510db25d0d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.9828767123, "max_line_length": 120, "alphanum_fraction": 0.6279612217, "num_tokens": 3966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6442251064863695, "lm_q1q2_score": 0.5205771866991729}}
{"text": "#include <chrono>\n#include <iomanip>\n#include <thread>\n#include <eigen3/Eigen/Dense>\n\n#include \"common/plugin.hpp\"\n#include \"common/switchboard.hpp\"\n#include \"common/data_format.hpp\"\n#include \"common/threadloop.hpp\"\n\n#include <gtsam/base/Matrix.h>\n#include <gtsam/base/Vector.h>\n#include <gtsam/navigation/AHRSFactor.h>\n#include <gtsam/navigation/CombinedImuFactor.h>  // Used if IMU combined is off.\n#include <gtsam/navigation/ImuBias.h>\n#include <gtsam/navigation/ImuFactor.h>\n#include <boost/smart_ptr/shared_ptr.hpp>\n#include <boost/smart_ptr/make_shared.hpp>\n\n// IMU sample time to live in seconds\n#define IMU_TTL 5\n\nusing PimUniquePtr = std::unique_ptr<gtsam::PreintegrationType>;\nusing ImuBias = gtsam::imuBias::ConstantBias;\nusing namespace ILLIXR;\n\ntypedef struct {\n\tdouble timestamp;\n\tEigen::Matrix<double, 3, 1> wm;\n\tEigen::Matrix<double, 3, 1> am;\n} imu_type;\n\nclass imu_integrator : public threadloop {\npublic:\n\timu_integrator(std::string name_, phonebook* pb_)\n\t\t: threadloop{name_, pb_}\n\t\t, sb{pb->lookup_impl<switchboard>()}\n\t\t, _m_imu_cam{sb->subscribe_latest<imu_cam_type>(\"imu_cam\")}\n\t\t, _m_in{sb->subscribe_latest<imu_integrator_seq>(\"imu_integrator_seq\")}\n\t\t, _m_imu_integrator_input{sb->subscribe_latest<imu_integrator_input>(\"imu_integrator_input\")}\n\t\t, _m_imu_raw{sb->publish<imu_raw_type>(\"imu_raw\")}\n\t\t, _seq_expect(1)\n\t{}\n\n\tvirtual skip_option _p_should_skip() override {\n\t\tauto in = _m_in->get_latest_ro();\n\t\tif (!in || in->seq == _seq_expect-1) {\n\t\t\t// No new data, sleep to keep CPU utilization low\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds{1});\n\t\t\treturn skip_option::skip_and_yield;\n\t\t} else {\n\t\t\tif (in->seq != _seq_expect) {\n\t\t\t\t_stat_missed = in->seq - _seq_expect;\n\t\t\t} else {\n\t\t\t\t_stat_missed = 0;\n\t\t\t}\n\t\t\t_stat_processed++;\n\t\t\t_seq_expect = in->seq+1;\n\t\t\treturn skip_option::run;\n\t\t}\n\t}\n\n\tvoid _p_one_iteration() override {\n\t\tconst imu_cam_type *datum = _m_imu_cam->get_latest_ro();\n\t\tdouble timestamp_in_seconds = (double(datum->dataset_time) / NANO_SEC);\n\n\t\timu_type data;\n        data.timestamp = timestamp_in_seconds;\n        data.wm = (datum->angular_v).cast<double>();\n        data.am = (datum->linear_a).cast<double>();\n\t\t_imu_vec.emplace_back(data);\n\n\t\tclean_imu_vec(timestamp_in_seconds);\n        propagate_imu_values(timestamp_in_seconds, datum->time);\n\t}\n\nprivate:\n\tconst std::shared_ptr<switchboard> sb;\n\n\t// IMU Data, Sequence Flag, and State Vars Needed\n\tstd::unique_ptr<reader_latest<imu_cam_type>> _m_imu_cam;\n\tstd::unique_ptr<reader_latest<imu_integrator_seq>> _m_in;\n\tstd::unique_ptr<reader_latest<imu_integrator_input>> _m_imu_integrator_input;\n\n\t// Write IMU Biases for PP\n\tstd::unique_ptr<writer<imu_raw_type>> _m_imu_raw;\n\n\tstd::vector<imu_type> _imu_vec;\n  \tPimUniquePtr pim_ = NULL;\n\n\t[[maybe_unused]] double last_cam_time = 0;\n\tdouble last_imu_offset = 0;\n\tlong long _seq_expect, _stat_processed, _stat_missed;\n\n\t// Remove IMU values older than 'IMU_TTL' from the imu buffer\n\tvoid clean_imu_vec(double timestamp) {\n\t\tauto imu_iterator = _imu_vec.begin();\n\n\t\t// Since the vector is ordered oldest to latest, keep deleting until you\n\t\t// hit a value less than 'IMU_TTL' seconds old\n\t\twhile (imu_iterator != _imu_vec.end()) {\n\t\t\tif (timestamp-(*imu_iterator).timestamp < IMU_TTL) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\timu_iterator = _imu_vec.erase(imu_iterator);\n\t\t}\n\t}\n\n\t// Timestamp we are propagating the biases to (new IMU reading time)\n\tvoid propagate_imu_values(double timestamp, time_type real_time) {\n\t\tconst imu_integrator_input *input_values = _m_imu_integrator_input->get_latest_ro();\n\t\tif (input_values == NULL) {\n\t\t\treturn;\n\t\t}\n\n\t\tImuBias imu_bias = ImuBias(input_values->biasAcc, input_values->biasGyro);\n\t\tif (pim_ == NULL) {\n\t\t\tboost::shared_ptr<gtsam::PreintegratedCombinedMeasurements::Params> params =\n          \t\t\tboost::make_shared<gtsam::PreintegratedCombinedMeasurements::Params>(input_values->params.n_gravity);\n\n\t\t\tparams->setGyroscopeCovariance(std::pow(input_values->params.gyro_noise, 2.0) * Eigen::Matrix3d::Identity());\n  \t\t\tparams->setAccelerometerCovariance(std::pow(input_values->params.acc_noise, 2.0) * Eigen::Matrix3d::Identity());\n  \t\t\tparams->setIntegrationCovariance(std::pow(input_values->params.imu_integration_sigma, 2.0) * Eigen::Matrix3d::Identity());\n\t\t\tparams->biasAccCovariance = std::pow(input_values->params.acc_walk, 2.0) * Eigen::Matrix3d::Identity();\n\t\t\tparams->biasOmegaCovariance = std::pow(input_values->params.gyro_walk, 2.0) * Eigen::Matrix3d::Identity();\n\n\t\t\tpim_ = std::make_unique<gtsam::PreintegratedCombinedMeasurements>(params, imu_bias);\n\t\t\tlast_imu_offset = input_values->t_offset;\n\t\t}\n\n#ifndef NDEBUG\n\t\tif (input_values->last_cam_integration_time > last_cam_time) {\n\t\t\tstd::cout << \"New slow pose has arrived!\\n\";\n\t\t\tlast_cam_time = input_values->last_cam_integration_time;\n\t\t}\n#endif\n\t\tpim_->resetIntegrationAndSetBias(imu_bias);\n\n\t\tdouble time_begin = input_values->last_cam_integration_time + last_imu_offset;\n\t\tdouble time_end = timestamp + input_values->t_offset;\n\n\t\tstd::vector<imu_type> prop_data = select_imu_readings(_imu_vec, time_begin, time_end);\n\t\tif (prop_data.size() < 2) {\n\t\t\treturn;\n\t\t}\n\n   \t\tImuBias prev_bias = pim_->biasHat();\n\t\tImuBias bias = pim_->biasHat();\n\n#ifndef NDEBUG\n\t\tstd::cout << \"Integrating over \" << prop_data.size() << \" IMU samples\\n\";\n#endif\n\n\t\tfor (unsigned i = 0; i < prop_data.size()-1; i++) {\n\t\t\tconst gtsam::Vector3& measured_acc = prop_data.at(i).am;\n\t\t\tconst gtsam::Vector3& measured_omega = prop_data.at(i).wm;\n\n\t\t\t// Delta T should be in seconds\n\t\t\tconst double& delta_t = prop_data.at(i+1).timestamp - prop_data.at(i).timestamp;\n\t\t\tpim_->integrateMeasurement(measured_acc, measured_omega, delta_t);\n\n\t\t\tprev_bias = bias;\n\t\t\tbias = pim_->biasHat();\n\t\t}\n\n\t\tgtsam::NavState navstate_lkf(gtsam::Pose3(gtsam::Rot3(input_values->quat), input_values->position), input_values->velocity);\n\t\tgtsam::NavState navstate_k = pim_->predict(navstate_lkf, imu_bias);\n\t\tgtsam::Pose3 out_pose = navstate_k.pose();\n\n#ifndef NDEBUG\n\t\tstd::cout << \"Base Position (x, y, z) = \"\n\t\t\t\t<< input_values->position(0) << \", \"\n\t\t\t\t<< input_values->position(1) << \", \"\n\t\t\t\t<< input_values->position(2) << std::endl;\n\n\t\tstd::cout << \"New  Position (x, y, z) = \"\n\t\t\t\t<< out_pose.x() << \", \"\n\t\t\t\t<< out_pose.y() << \", \"\n\t\t\t\t<< out_pose.z() << std::endl;\n#endif\n\n\t\t_m_imu_raw->put(new imu_raw_type{\n\t\t\tprev_bias.gyroscope(),\n\t\t\tprev_bias.accelerometer(),\n\t\t\tbias.gyroscope(),\n\t\t\tbias.accelerometer(),\n\t\t\tout_pose.translation(), // Position\n\t\t\tnavstate_k.velocity(), // Velocity\n\t\t\tout_pose.rotation().toQuaternion(), // Eigen Quat\n\t\t\treal_time\n\t\t});\n\t}\n\n\t// Select IMU readings based on timestamp similar to how OpenVINS selects IMU values to propagate\n\tstd::vector<imu_type> select_imu_readings(const std::vector<imu_type>& imu_data, double time_begin, double time_end) {\n\t\tstd::vector<imu_type> prop_data;\n\t\tif (imu_data.size() < 2) {\n\t\t\treturn prop_data;\n\t\t}\n\n\t\tfor (unsigned i = 0; i < imu_data.size()-1; i++) {\n\n\t\t\t// If time_begin comes inbetween two IMUs (A and B), interpolate A forward to time_begin\n\t\t\tif (imu_data.at(i+1).timestamp > time_begin && imu_data.at(i).timestamp < time_begin) {\n\t\t\t\timu_type data = interpolate_imu(imu_data.at(i), imu_data.at(i+1), time_begin);\n\t\t\t\tprop_data.push_back(data);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// IMU is within time_begin and time_end\n\t\t\tif (imu_data.at(i).timestamp >= time_begin && imu_data.at(i+1).timestamp <= time_end) {\n\t\t\t\tprop_data.push_back(imu_data.at(i));\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// IMU is past time_end\n\t\t\tif (imu_data.at(i+1).timestamp > time_end) {\n\t\t\t\timu_type data = interpolate_imu(imu_data.at(i), imu_data.at(i+1), time_end);\n\t\t\t\tprop_data.push_back(data);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Loop through and ensure we do not have an zero dt values\n\t\t// This would cause the noise covariance to be Infinity\n\t\tfor (size_t i = 0; i < prop_data.size()-1; i++) {\n\t\t\tif (std::abs(prop_data.at(i+1).timestamp-prop_data.at(i).timestamp) < 1e-12) {\n\t\t\t\tprop_data.erase(prop_data.begin()+i);\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\n\t\treturn prop_data;\n\t}\n\n\t// For when an integration time ever falls inbetween two imu measurements (modeled after OpenVINS)\n\tstatic imu_type interpolate_imu(const imu_type imu_1, imu_type imu_2, double timestamp) {\n\t\timu_type data;\n\t\tdata.timestamp = timestamp;\n\n\t\tdouble lambda = (timestamp - imu_1.timestamp) / (imu_2.timestamp - imu_1.timestamp);\n\t\tdata.am = (1 - lambda) * imu_1.am + lambda * imu_2.am;\n\t\tdata.wm = (1 - lambda) * imu_1.wm + lambda * imu_2.wm;\n\n\t\treturn data;\n\t}\n};\n\nPLUGIN_MAIN(imu_integrator)\n", "meta": {"hexsha": "3c8029e341c5faac7ba8402c6f7b955245f62fff", "size": 8505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam_integrator/plugin.cpp", "max_stars_repo_name": "jheo4/ILLIXR", "max_stars_repo_head_hexsha": "df8a7bb89874009844607d620e5a5ae75e1a299d", "max_stars_repo_licenses": ["NCSA", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gtsam_integrator/plugin.cpp", "max_issues_repo_name": "jheo4/ILLIXR", "max_issues_repo_head_hexsha": "df8a7bb89874009844607d620e5a5ae75e1a299d", "max_issues_repo_licenses": ["NCSA", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam_integrator/plugin.cpp", "max_forks_repo_name": "jheo4/ILLIXR", "max_forks_repo_head_hexsha": "df8a7bb89874009844607d620e5a5ae75e1a299d", "max_forks_repo_licenses": ["NCSA", "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.8844621514, "max_line_length": 127, "alphanum_fraction": 0.7116990006, "num_tokens": 2477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5205771816153456}}
{"text": "/**\n * @file snapshot_ensembles.cpp\n * @author Marcus Edel\n *\n * Test file for SGDR with snapshot ensembles.\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/optimizers/sgdr/snapshot_ensembles.hpp>\n#include <mlpack/core/optimizers/sgdr/snapshot_sgdr.hpp>\n#include <mlpack/methods/logistic_regression/logistic_regression.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace std;\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::optimization;\n\nusing namespace mlpack::distribution;\nusing namespace mlpack::regression;\n\nBOOST_AUTO_TEST_SUITE(SnapshotEnsemblesTest);\n\n/*\n * Test that the step size resets after a specified number of epochs.\n */\nBOOST_AUTO_TEST_CASE(SnapshotEnsemblesResetTest)\n{\n  const double stepSize = 0.5;\n  arma::mat iterate;\n\n  // Now run cyclical decay policy with a couple of multiplicators and initial\n  // restarts.\n  for (size_t restart = 5; restart < 100; restart += 10)\n  {\n    for (size_t mult = 2; mult < 5; ++mult)\n    {\n      double epochStepSize = stepSize;\n\n      SnapshotEnsembles snapshotEnsembles(restart,\n          double(mult), stepSize, 1000, 2);\n\n      snapshotEnsembles.EpochBatches() = 10 / (double)1000;\n      // Create all restart epochs.\n      arma::Col<size_t> nextRestart(1000 / 10 /  mult);\n      nextRestart(0) = restart;\n      for (size_t j = 1; j < nextRestart.n_elem; ++j)\n        nextRestart(j) = nextRestart(j - 1) * mult;\n\n      for (size_t i = 0; i < 1000; ++i)\n      {\n        snapshotEnsembles.Update(iterate, epochStepSize, iterate);\n        if (i <= restart || arma::accu(arma::find(nextRestart == i)) > 0)\n        {\n          BOOST_CHECK_EQUAL(epochStepSize, stepSize);\n        }\n      }\n\n      BOOST_CHECK_EQUAL(snapshotEnsembles.Snapshots().size(), 2);\n    }\n  }\n}\n\n/**\n * Run SGDR with snapshot ensembles on logistic regression and make sure the\n * results are acceptable.\n */\nBOOST_AUTO_TEST_CASE(LogisticRegressionTest)\n{\n  // Generate a two-Gaussian dataset.\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  // Shuffle the dataset.\n  arma::uvec indices = arma::shuffle(arma::linspace<arma::uvec>(0,\n      data.n_cols - 1, data.n_cols));\n  arma::mat shuffledData(3, 1000);\n  arma::Row<size_t> shuffledResponses(1000);\n  for (size_t i = 0; i < data.n_cols; ++i)\n  {\n    shuffledData.col(i) = data.col(indices[i]);\n    shuffledResponses[i] = responses[indices[i]];\n  }\n\n  // Create a test set.\n  arma::mat testData(3, 1000);\n  arma::Row<size_t> testResponses(1000);\n  for (size_t i = 0; i < 500; ++i)\n  {\n    testData.col(i) = g1.Random();\n    testResponses[i] = 0;\n  }\n  for (size_t i = 500; i < 1000; ++i)\n  {\n    testData.col(i) = g2.Random();\n    testResponses[i] = 1;\n  }\n\n  // Now run SGDR with snapshot ensembles on a couple of batch sizes.\n  for (size_t batchSize = 5; batchSize < 50; batchSize += 5)\n  {\n    SnapshotSGDR<> sgdr(50, 2.0, batchSize, 0.01, 10000, 1e-3);\n    LogisticRegression<> lr(shuffledData, shuffledResponses, sgdr, 0.5);\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, 0.3); // 0.3% error tolerance.\n\n    const double testAcc = lr.ComputeAccuracy(testData, testResponses);\n    BOOST_REQUIRE_CLOSE(testAcc, 100.0, 0.6); // 0.6% error tolerance.\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "790e646b2bdef7ac4846f4c4d83914d45ff56ac0", "size": 3990, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/snapshot_ensembles.cpp", "max_stars_repo_name": "chigur/mlpack", "max_stars_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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-05-02T21:10:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T21:10:55.000Z", "max_issues_repo_path": "src/mlpack/tests/snapshot_ensembles.cpp", "max_issues_repo_name": "chigur/mlpack", "max_issues_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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/snapshot_ensembles.cpp", "max_forks_repo_name": "chigur/mlpack", "max_forks_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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.776119403, "max_line_length": 80, "alphanum_fraction": 0.6649122807, "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.5205771811795354}}
{"text": "/* vim: set sw=4 sts=4 et foldmethod=syntax : */\n\n#include <iostream>\n#include <random>\n\n#include <boost/program_options.hpp>\n\nnamespace po = boost::program_options;\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::exception;\nusing std::mt19937;\nusing std::uniform_real_distribution;\n\nauto main(int argc, char * argv[]) -> int\n{\n    try {\n        po::options_description display_options{ \"Program options\" };\n        display_options.add_options()\n            (\"help\",                                         \"Display help information\");\n\n        po::options_description graph_options{ \"Graph options\" };\n        graph_options.add_options()\n            (\"seed\",      po::value<int>(),              \"Specify a random seed\")\n            (\"directed\",                                 \"Generate a directed graph\")\n            (\"loops\",     po::value<double>(),           \"Generate loops with this probability\")\n            ;\n        display_options.add(graph_options);\n\n        po::options_description all_options{ \"All options\" };\n        all_options.add_options()\n            (\"vertices\",          po::value<int>(),    \"Specify the number of vertices\")\n            (\"edge-probability\",  po::value<double>(), \"Specify the edge probability\")\n            ;\n\n        all_options.add(display_options);\n\n        po::positional_options_description positional_options;\n        positional_options\n            .add(\"vertices\", 1)\n            .add(\"edge-probability\", 1)\n            ;\n\n        po::variables_map options_vars;\n        po::store(po::command_line_parser(argc, argv)\n                .options(all_options)\n                .positional(positional_options)\n                .run(), options_vars);\n        po::notify(options_vars);\n\n        /* --help? Show a message, and exit. */\n        if (options_vars.count(\"help\")) {\n            cout << \"Usage: \" << argv[0] << \" [options] number-of-vertices edge-probability\" << endl;\n            cout << endl;\n            cout << display_options << endl;\n            return EXIT_SUCCESS;\n        }\n\n        if (! options_vars.count(\"vertices\") || ! options_vars.count(\"edge-probability\")) {\n            cout << \"Usage: \" << argv[0] << \" [options] number-of-vertices edge-probability\" << endl;\n            return EXIT_FAILURE;\n        }\n\n        int seed = 0;\n        if (options_vars.count(\"seed\"))\n            seed = options_vars[\"seed\"].as<int>();\n\n        int vertices = options_vars[\"vertices\"].as<int>();\n        double density = options_vars[\"edge-probability\"].as<double>();\n        double loops = options_vars.count(\"loops\") ? options_vars[\"loops\"].as<double>() : 0;\n\n        bool directed = options_vars.count(\"directed\");\n\n        mt19937 rand;\n        rand.seed(seed);\n        uniform_real_distribution<double> dist(0.0, 1.0);\n\n        for (int v = 0 ; v < vertices ; ++v) {\n            cout << \"v\" << v << \",\" << endl;\n            if (loops > dist(rand))\n                cout << \"v\" << v << \",\" << \"v\" << v << endl;\n            for (int w = (directed ? 0 : v + 1) ; w < vertices ; ++w)\n                if (v != w && density > dist(rand))\n                    cout << \"v\" << v << (directed ? \">\" : \",\") << \"v\" << w << endl;\n        }\n\n        return EXIT_SUCCESS;\n    }\n    catch (const po::error & e) {\n        cerr << \"Error: \" << e.what() << endl;\n        cerr << \"Try \" << argv[0] << \" --help\" << endl;\n        return EXIT_FAILURE;\n    }\n    catch (const exception & e) {\n        cerr << \"Error: \" << e.what() << endl;\n        return EXIT_FAILURE;\n    }\n}\n\n", "meta": {"hexsha": "85dc89560ea9080b6cf60859463aee5a7fd94aa1", "size": 3518, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/create_random_graph.cc", "max_stars_repo_name": "jdmoorman/subgraph-matching", "max_stars_repo_head_hexsha": "b473d86ee3b1290b85933d8e18b860957e17ba10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2018-05-06T12:00:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T04:50:26.000Z", "max_issues_repo_path": "src/create_random_graph.cc", "max_issues_repo_name": "jdmoorman/subgraph-matching", "max_issues_repo_head_hexsha": "b473d86ee3b1290b85933d8e18b860957e17ba10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-08-17T04:50:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T13:27:30.000Z", "max_forks_repo_path": "src/create_random_graph.cc", "max_forks_repo_name": "jdmoorman/subgraph-matching", "max_forks_repo_head_hexsha": "b473d86ee3b1290b85933d8e18b860957e17ba10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-06-07T11:48:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T13:55:04.000Z", "avg_line_length": 34.4901960784, "max_line_length": 101, "alphanum_fraction": 0.5258669699, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.5205771803079144}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, 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#include <geometry_test_common.hpp>\n\n#include <boost/geometry/algorithms/area.hpp>\n#include <boost/geometry/algorithms/transform.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/io/wkt/read.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n\n#include <boost/geometry/extensions/gis/latlong/point_ll.hpp>\n#include <boost/geometry/extensions/gis/geographic/strategies/area_huiller_earth.hpp>\n#include <boost/geometry/extensions/gis/projections/epsg.hpp>\n#include <boost/geometry/extensions/gis/projections/parameters.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/sterea.hpp>\n\n//#include <test_common/test_point.hpp>\n\ntemplate <typename PRJ, typename XY, typename LL>\nvoid add_to_ring(PRJ const& prj, LL const& ll,\n                 bg::model::ring<LL>& ring_ll,\n                 bg::model::ring<XY>& ring_xy)\n{\n    ring_ll.push_back(ll);\n\n    XY xy;\n    prj.forward(ll, xy);\n    ring_xy.push_back(xy);\n}\n\ntemplate <typename XY, typename LL>\nvoid test_area_polygon_ll(bool concave, bool hole, double perc)\n{\n    BOOST_ASSERT(! (concave && hole) );\n\n    typedef typename bg::coordinate_type<LL>::type T;\n\n    // Amsterdam, Rotterdam, The Hague, Utrecht,\n    // these cities together are the city group \"Randstad\"\n\n    LL a, r, h, u;\n    // Amsterdam 52 22'23\"N 4 53'32\"E\n    a.lat(bg::dms<bg::north, T>(52, 22, 23));\n    a.lon(bg::dms<bg::east, T>(4, 53, 32));\n\n    // Rotterdam 51 55'51\"N 4 28'45\"E\n    r.lat(bg::dms<bg::north, T>(51, 55, 51));\n    r.lon(bg::dms<bg::east, T>(4, 28, 45));\n\n    // The hague: 52 4' 48\" N, 4 18' 0\" E\n    h.lat(bg::dms<bg::north, T>(52, 4, 48));\n    h.lon(bg::dms<bg::east, T>(4, 18, 0));\n\n    // Utrecht\n    u.lat(bg::dms<bg::north, T>(52, 5, 36));\n    u.lon(bg::dms<bg::east, T>(5, 7, 10));\n\n\n    // For checking calculated area, use the Dutch projection (RD), this is EPSG code 28992\n    bg::projections::sterea_ellipsoid<LL, XY> dutch_prj(bg::projections::init(28992));\n\n    // Add them in clockwise direction\n    bg::model::polygon<LL> randstad;\n    bg::model::polygon<XY> randstad_xy;\n    add_to_ring(dutch_prj, a, randstad.outer(), randstad_xy.outer());\n    add_to_ring(dutch_prj, u, randstad.outer(), randstad_xy.outer());\n\n    // Concave case\n    if (concave)\n    {\n        // Add the city \"Alphen\" to create a concave case\n        // Alphen 52 7' 48\" N, 4 39' 0\" E\n        LL alphen(\n            bg::latitude<T>(bg::dms<bg::north, T>(52, 7, 48)),\n            bg::longitude<T>(bg::dms<bg::east, T>(4, 39)));\n        add_to_ring(dutch_prj, alphen, randstad.outer(), randstad_xy.outer());\n    }\n\n    add_to_ring(dutch_prj, r, randstad.outer(), randstad_xy.outer());\n    add_to_ring(dutch_prj, h, randstad.outer(), randstad_xy.outer());\n    add_to_ring(dutch_prj, a, randstad.outer(), randstad_xy.outer());\n\n    // Hole case\n    if (hole)\n    {\n        // Gouda 52 1' 12\" N, 4 42' 0\" E\n        LL gouda(\n            bg::latitude<T>(bg::dms<bg::north, T>(52, 1, 12)),\n            bg::longitude<T>(bg::dms<bg::east, T>(4, 42)));\n        // Woerden 52 5' 9\" N, 4 53' 0\" E\n        LL woerden(\n            bg::latitude<T>(bg::dms<bg::north, T>(52, 5, 9)),\n            bg::longitude<T>(bg::dms<bg::east, T>(4, 53, 0)));\n        // Uithoorn 52 13' 48\" N, 4 49' 48\" E\n        LL uithoorn(bg::latitude<T>\n            (bg::dms<bg::north, T>(52, 13, 48)),\n            bg::longitude<T>(bg::dms<bg::east, T>(4, 49, 48)));\n        // Alphen 52 7' 48\" N, 4 39' 0\" E\n        LL alphen(bg::latitude<T>(\n            bg::dms<bg::north, T>(52, 7, 48)),\n            bg::longitude<T>(bg::dms<bg::east, T>(4, 39)));\n\n        randstad.inners().resize(1);\n        randstad_xy.inners().resize(1);\n\n        typename bg::model::polygon<LL>::ring_type& ring = randstad.inners()[0];\n        typename bg::model::polygon<XY>::ring_type& ring_xy = randstad_xy.inners()[0];\n\n        // Add them in counter-clockwise direction (see map of the Netherlands)\n        add_to_ring(dutch_prj, gouda, ring, ring_xy);\n        add_to_ring(dutch_prj, woerden, ring, ring_xy);\n        add_to_ring(dutch_prj, uithoorn, ring, ring_xy);\n        add_to_ring(dutch_prj, alphen, ring, ring_xy);\n        add_to_ring(dutch_prj, gouda, ring, ring_xy);\n    }\n\n\n    // Check the area in square KM\n    static const double KM2 = 1.0e6;\n    double d_ll = bg::area(randstad) / KM2;\n    double d_xy = bg::area(randstad_xy) / KM2;\n\n    BOOST_CHECK_CLOSE(d_ll, d_xy, 1.0);\n    if (hole)\n    {\n        BOOST_CHECK_CLOSE(d_ll, 1148.210, perc);\n        BOOST_CHECK_CLOSE(d_xy, 1151.573, perc);\n    }\n    else\n    {\n        BOOST_CHECK_CLOSE(d_ll, concave ? 977.786 : 1356.168, perc);\n        BOOST_CHECK_CLOSE(d_xy, concave ? 980.658 : 1360.140, perc);\n\n        // No hole: area of outer should be equal to area of ring\n        double r_ll = bg::area(randstad.outer()) / KM2;\n        double r_xy = bg::area(randstad_xy.outer()) / KM2;\n\n        BOOST_CHECK_CLOSE(d_ll, r_ll, perc);\n        BOOST_CHECK_CLOSE(d_xy, r_xy, perc);\n    }\n\n    // Calculate are using specified strategy, here with radius in KM\n    // We then don't have to divide by KM*KM to get the same result\n    bg::strategy::area::huiller<LL, long double> strategy(6372.8);\n    d_ll = bg::area(randstad, strategy);\n    BOOST_CHECK_CLOSE(d_ll, d_xy, 1.0);\n}\n\n\n\ntemplate <typename T>\nvoid test_latlong(double perc)\n{\n    test_area_polygon_ll<bg::model::d2::point_xy<T>, bg::model::ll::point<bg::degree, T> >(false, false, perc);\n\n    // with concavities\n    test_area_polygon_ll<bg::model::d2::point_xy<T>, bg::model::ll::point<bg::degree, T> >(true, false, perc);\n\n    // with holes\n    test_area_polygon_ll<bg::model::d2::point_xy<T>, bg::model::ll::point<bg::degree, T> >(false, true, perc);\n\n}\n\nint test_main(int, char* [])\n{\n    test_latlong<double>(0.01);\n    //test_latlong<float>(0.3); // LL area calculations using projections differ\n\n    return 0;\n}\n", "meta": {"hexsha": "b6ff104b98831da621f2df5288742c4ccf9808b4", "size": 6486, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/gis/latlong/area_ll.cpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "extensions/test/gis/latlong/area_ll.cpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "extensions/test/gis/latlong/area_ll.cpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 35.25, "max_line_length": 111, "alphanum_fraction": 0.6342892384, "num_tokens": 2063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6442250928250374, "lm_q1q2_score": 0.5205771756598981}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <tinyply.h>\n#include <vector>\n#include <cstdint>\n\n\nclass TriangleMesh {\npublic:\n\tTriangleMesh(const char* path);\n\n\tvoid print_debug_info() const;\n\n\tvoid write_mesh_ply(const char* fileName, const std::vector<Eigen::Array3<uint8_t>>& colors = {}) const;\n\n\tvoid write_mesh_vertices_sequence_ply(const char* fileName) const;\n\n\tconst std::vector<Eigen::Vector3f>& get_vertices() const {\n\t\treturn m_vertices;\n\t}\n\n\tconst std::vector<Eigen::Array3i>& get_faces() const {\n\t\treturn m_faces;\n\t}\n\n\tvoid rearrange_vertices(const std::vector<uint32_t>& old2new);\n\n\tvoid sort_faces();\n\nprivate:\n\n\tvoid parse_ply(const char* path);\n\n\t// Variables\n\tstd::vector<Eigen::Vector3f> m_vertices;\n\tstd::vector<Eigen::Array3i> m_faces;\n\n\n};\n\n", "meta": {"hexsha": "3b524fea937d6f34f4ff92f86a20af1c954e0c67", "size": 764, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/TriangleMesh.hpp", "max_stars_repo_name": "SirKoto/mesh_layout_optimization", "max_stars_repo_head_hexsha": "54e144ad893192164ee2217a2b05e9fb28957819", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TriangleMesh.hpp", "max_issues_repo_name": "SirKoto/mesh_layout_optimization", "max_issues_repo_head_hexsha": "54e144ad893192164ee2217a2b05e9fb28957819", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TriangleMesh.hpp", "max_forks_repo_name": "SirKoto/mesh_layout_optimization", "max_forks_repo_head_hexsha": "54e144ad893192164ee2217a2b05e9fb28957819", "max_forks_repo_licenses": ["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.1904761905, "max_line_length": 105, "alphanum_fraction": 0.7303664921, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5205048038200681}}
{"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 TestScan\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <numeric>\r\n#include <functional>\r\n#include <vector>\r\n\r\n#include <boost/compute/functional.hpp>\r\n#include <boost/compute/lambda.hpp>\r\n#include <boost/compute/system.hpp>\r\n#include <boost/compute/command_queue.hpp>\r\n#include <boost/compute/algorithm/copy.hpp>\r\n#include <boost/compute/algorithm/exclusive_scan.hpp>\r\n#include <boost/compute/algorithm/inclusive_scan.hpp>\r\n#include <boost/compute/container/vector.hpp>\r\n#include <boost/compute/iterator/counting_iterator.hpp>\r\n#include <boost/compute/iterator/transform_iterator.hpp>\r\n\r\n#include \"check_macros.hpp\"\r\n#include \"context_setup.hpp\"\r\n\r\nnamespace bc = boost::compute;\r\n\r\nBOOST_AUTO_TEST_CASE(inclusive_scan_int)\r\n{\r\n    int data[] = { 1, 2, 1, 2, 3 };\r\n    bc::vector<int> vector(data, data + 5, queue);\r\n    BOOST_CHECK_EQUAL(vector.size(), size_t(5));\r\n\r\n    bc::vector<int> result(5, context);\r\n    BOOST_CHECK_EQUAL(result.size(), size_t(5));\r\n\r\n    // inclusive scan\r\n    bc::inclusive_scan(vector.begin(), vector.end(), result.begin(), queue);\r\n    CHECK_RANGE_EQUAL(int, 5, result, (1, 3, 4, 6, 9));\r\n\r\n    // in-place inclusive scan\r\n    CHECK_RANGE_EQUAL(int, 5, vector, (1, 2, 1, 2, 3));\r\n    bc::inclusive_scan(vector.begin(), vector.end(), vector.begin(), queue);\r\n    CHECK_RANGE_EQUAL(int, 5, vector, (1, 3, 4, 6, 9));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(exclusive_scan_int)\r\n{\r\n    int data[] = { 1, 2, 1, 2, 3 };\r\n    bc::vector<int> vector(data, data + 5, queue);\r\n    BOOST_CHECK_EQUAL(vector.size(), size_t(5));\r\n\r\n    bc::vector<int> result(5, context);\r\n    BOOST_CHECK_EQUAL(vector.size(), size_t(5));\r\n\r\n    // exclusive scan\r\n    bc::exclusive_scan(vector.begin(), vector.end(), result.begin(), queue);\r\n    CHECK_RANGE_EQUAL(int, 5, result, (0, 1, 3, 4, 6));\r\n\r\n    // in-place exclusive scan\r\n    CHECK_RANGE_EQUAL(int, 5, vector, (1, 2, 1, 2, 3));\r\n    bc::exclusive_scan(vector.begin(), vector.end(), vector.begin(), queue);\r\n    CHECK_RANGE_EQUAL(int, 5, vector, (0, 1, 3, 4, 6));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(inclusive_scan_int2)\r\n{\r\n    using boost::compute::int2_;\r\n\r\n    int data[] = { 1, 2,\r\n                   3, 4,\r\n                   5, 6,\r\n                   7, 8,\r\n                   9, 0 };\r\n\r\n    boost::compute::vector<int2_> input(reinterpret_cast<int2_*>(data),\r\n                                        reinterpret_cast<int2_*>(data) + 5,\r\n                                        queue);\r\n    BOOST_CHECK_EQUAL(input.size(), size_t(5));\r\n\r\n    boost::compute::vector<int2_> output(5, context);\r\n    boost::compute::inclusive_scan(input.begin(), input.end(), output.begin(),\r\n                                   queue);\r\n    CHECK_RANGE_EQUAL(\r\n        int2_, 5, output,\r\n        (int2_(1, 2), int2_(4, 6), int2_(9, 12), int2_(16, 20), int2_(25, 20))\r\n    );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(inclusive_scan_counting_iterator)\r\n{\r\n    bc::vector<int> result(10, context);\r\n    bc::inclusive_scan(bc::make_counting_iterator(1),\r\n                       bc::make_counting_iterator(11),\r\n                       result.begin(), queue);\r\n    CHECK_RANGE_EQUAL(int, 10, result, (1, 3, 6, 10, 15, 21, 28, 36, 45, 55));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(exclusive_scan_counting_iterator)\r\n{\r\n    bc::vector<int> result(10, context);\r\n    bc::exclusive_scan(bc::make_counting_iterator(1),\r\n                       bc::make_counting_iterator(11),\r\n                       result.begin(), queue);\r\n    CHECK_RANGE_EQUAL(int, 10, result, (0, 1, 3, 6, 10, 15, 21, 28, 36, 45));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(inclusive_scan_transform_iterator)\r\n{\r\n    float data[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };\r\n    bc::vector<float> input(data, data + 5, queue);\r\n    bc::vector<float> output(5, context);\r\n\r\n    // normal inclusive scan of the input\r\n    bc::inclusive_scan(input.begin(), input.end(), output.begin(), queue);\r\n    bc::system::finish();\r\n    BOOST_CHECK_CLOSE(float(output[0]), 1.0f, 1e-4f);\r\n    BOOST_CHECK_CLOSE(float(output[1]), 3.0f, 1e-4f);\r\n    BOOST_CHECK_CLOSE(float(output[2]), 6.0f, 1e-4f);\r\n    BOOST_CHECK_CLOSE(float(output[3]), 10.0f, 1e-4f);\r\n    BOOST_CHECK_CLOSE(float(output[4]), 15.0f, 1e-4f);\r\n\r\n    // inclusive scan of squares of the input\r\n    using ::boost::compute::_1;\r\n\r\n    bc::inclusive_scan(bc::make_transform_iterator(input.begin(), pown(_1, 2)),\r\n                       bc::make_transform_iterator(input.end(), pown(_1, 2)),\r\n                       output.begin(), queue);\r\n    bc::system::finish();\r\n    BOOST_CHECK_CLOSE(float(output[0]), 1.0f, 1e-4f);\r\n    BOOST_CHECK_CLOSE(float(output[1]), 5.0f, 1e-4f);\r\n    BOOST_CHECK_CLOSE(float(output[2]), 14.0f, 1e-4f);\r\n    BOOST_CHECK_CLOSE(float(output[3]), 30.0f, 1e-4f);\r\n    BOOST_CHECK_CLOSE(float(output[4]), 55.0f, 1e-4f);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(inclusive_scan_doctest)\r\n{\r\n//! [inclusive_scan_int]\r\n// setup input\r\nint data[] = { 1, 2, 3, 4 };\r\nboost::compute::vector<int> input(data, data + 4, queue);\r\n\r\n// setup output\r\nboost::compute::vector<int> output(4, context);\r\n\r\n// scan values\r\nboost::compute::inclusive_scan(\r\n    input.begin(), input.end(), output.begin(), queue\r\n);\r\n\r\n// output = [ 1, 3, 6, 10 ]\r\n//! [inclusive_scan_int]\r\n\r\n    CHECK_RANGE_EQUAL(int, 4, output, (1, 3, 6, 10));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(exclusive_scan_doctest)\r\n{\r\n//! [exclusive_scan_int]\r\n// setup input\r\nint data[] = { 1, 2, 3, 4 };\r\nboost::compute::vector<int> input(data, data + 4, queue);\r\n\r\n// setup output\r\nboost::compute::vector<int> output(4, context);\r\n\r\n// scan values\r\nboost::compute::exclusive_scan(\r\n    input.begin(), input.end(), output.begin(), queue\r\n);\r\n\r\n// output = [ 0, 1, 3, 6 ]\r\n//! [exclusive_scan_int]\r\n\r\n    CHECK_RANGE_EQUAL(int, 4, output, (0, 1, 3, 6));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(inclusive_scan_int_multiplies)\r\n{\r\n//! [inclusive_scan_int_multiplies]\r\n// setup input\r\nint data[] = { 1, 2, 1, 2, 3 };\r\nboost::compute::vector<int> input(data, data + 5, queue);\r\n\r\n// setup output\r\nboost::compute::vector<int> output(5, context);\r\n\r\n// inclusive scan with multiplication\r\nboost::compute::inclusive_scan(\r\n    input.begin(), input.end(), output.begin(),\r\n    boost::compute::multiplies<int>(), queue\r\n);\r\n\r\n// output = [1, 2, 2, 4, 12]\r\n//! [inclusive_scan_int_multiplies]\r\n\r\n    BOOST_CHECK_EQUAL(input.size(), size_t(5));\r\n    BOOST_CHECK_EQUAL(output.size(), size_t(5));\r\n\r\n    CHECK_RANGE_EQUAL(int, 5, output, (1, 2, 2, 4, 12));\r\n\r\n    // in-place inclusive scan\r\n    CHECK_RANGE_EQUAL(int, 5, input, (1, 2, 1, 2, 3));\r\n    boost::compute::inclusive_scan(input.begin(), input.end(), input.begin(),\r\n                                   boost::compute::multiplies<int>(), queue);\r\n    CHECK_RANGE_EQUAL(int, 5, input, (1, 2, 2, 4, 12));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(exclusive_scan_int_multiplies)\r\n{\r\n//! [exclusive_scan_int_multiplies]\r\n// setup input\r\nint data[] = { 1, 2, 1, 2, 3 };\r\nboost::compute::vector<int> input(data, data + 5, queue);\r\n\r\n// setup output\r\nboost::compute::vector<int> output(5, context);\r\n\r\n// exclusive_scan with multiplication\r\n// initial value equals 10\r\nboost::compute::exclusive_scan(\r\n    input.begin(), input.end(), output.begin(),\r\n    int(10), boost::compute::multiplies<int>(), queue\r\n);\r\n\r\n// output = [10, 10, 20, 20, 40]\r\n//! [exclusive_scan_int_multiplies]\r\n\r\n    BOOST_CHECK_EQUAL(input.size(), size_t(5));\r\n    BOOST_CHECK_EQUAL(output.size(), size_t(5));\r\n\r\n    CHECK_RANGE_EQUAL(int, 5, output, (10, 10, 20, 20, 40));\r\n\r\n    // in-place exclusive scan\r\n    CHECK_RANGE_EQUAL(int, 5, input, (1, 2, 1, 2, 3));\r\n    bc::exclusive_scan(input.begin(), input.end(), input.begin(),\r\n                       int(10), bc::multiplies<int>(), queue);\r\n    CHECK_RANGE_EQUAL(int, 5, input, (10, 10, 20, 20, 40));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(inclusive_scan_int_multiplies_long_vector)\r\n{\r\n    size_t size = 1000;\r\n    bc::vector<int> device_vector(size, int(2), queue);\r\n    BOOST_CHECK_EQUAL(device_vector.size(), size);\r\n    bc::inclusive_scan(device_vector.begin(), device_vector.end(),\r\n                       device_vector.begin(), bc::multiplies<int>(), queue);\r\n\r\n    std::vector<int> host_vector(size, 2);\r\n    BOOST_CHECK_EQUAL(host_vector.size(), size);\r\n    bc::copy(device_vector.begin(), device_vector.end(),\r\n             host_vector.begin(), queue);\r\n\r\n    std::vector<int> test(size, 2);\r\n    BOOST_CHECK_EQUAL(test.size(), size);\r\n    std::partial_sum(test.begin(), test.end(),\r\n                     test.begin(), std::multiplies<int>());\r\n\r\n    BOOST_CHECK_EQUAL_COLLECTIONS(host_vector.begin(), host_vector.end(),\r\n                                  test.begin(), test.end());\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(exclusive_scan_int_multiplies_long_vector)\r\n{\r\n    size_t size = 1000;\r\n    bc::vector<int> device_vector(size, int(2), queue);\r\n    BOOST_CHECK_EQUAL(device_vector.size(), size);\r\n    bc::exclusive_scan(device_vector.begin(), device_vector.end(),\r\n                       device_vector.begin(), int(10), bc::multiplies<int>(),\r\n                       queue);\r\n\r\n    std::vector<int> host_vector(size, 2);\r\n    BOOST_CHECK_EQUAL(host_vector.size(), size);\r\n    bc::copy(device_vector.begin(), device_vector.end(),\r\n             host_vector.begin(), queue);\r\n\r\n    std::vector<int> test(size, 2);\r\n    BOOST_CHECK_EQUAL(test.size(), size);\r\n    test[0] = 10;\r\n    std::partial_sum(test.begin(), test.end(),\r\n                     test.begin(), std::multiplies<int>());\r\n\r\n    BOOST_CHECK_EQUAL_COLLECTIONS(host_vector.begin(), host_vector.end(),\r\n                                  test.begin(), test.end());\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(inclusive_scan_int_custom_function)\r\n{\r\n    BOOST_COMPUTE_FUNCTION(int, multi, (int x, int y),\r\n    {\r\n        return x * y * 2;\r\n    });\r\n\r\n    int data[] = { 1, 2, 1, 2, 3 };\r\n    bc::vector<int> vector(data, data + 5, queue);\r\n    BOOST_CHECK_EQUAL(vector.size(), size_t(5));\r\n\r\n    bc::vector<int> result(5, context);\r\n    BOOST_CHECK_EQUAL(result.size(), size_t(5));\r\n\r\n    // inclusive scan\r\n    bc::inclusive_scan(vector.begin(), vector.end(), result.begin(),\r\n                       multi, queue);\r\n    CHECK_RANGE_EQUAL(int, 5, result, (1, 4, 8, 32, 192));\r\n\r\n    // in-place inclusive scan\r\n    CHECK_RANGE_EQUAL(int, 5, vector, (1, 2, 1, 2, 3));\r\n    bc::inclusive_scan(vector.begin(), vector.end(), vector.begin(),\r\n                       multi, queue);\r\n    CHECK_RANGE_EQUAL(int, 5, vector, (1, 4, 8, 32, 192));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(exclusive_scan_int_custom_function)\r\n{\r\n    BOOST_COMPUTE_FUNCTION(int, multi, (int x, int y),\r\n    {\r\n        return x * y * 2;\r\n    });\r\n\r\n    int data[] = { 1, 2, 1, 2, 3 };\r\n    bc::vector<int> vector(data, data + 5, queue);\r\n    BOOST_CHECK_EQUAL(vector.size(), size_t(5));\r\n\r\n    bc::vector<int> result(5, context);\r\n    BOOST_CHECK_EQUAL(result.size(), size_t(5));\r\n\r\n    // exclusive_scan\r\n    bc::exclusive_scan(vector.begin(), vector.end(), result.begin(),\r\n                       int(1), multi, queue);\r\n    CHECK_RANGE_EQUAL(int, 5, result, (1, 2, 8, 16, 64));\r\n\r\n    // in-place exclusive scan\r\n    CHECK_RANGE_EQUAL(int, 5, vector, (1, 2, 1, 2, 3));\r\n    bc::exclusive_scan(vector.begin(), vector.end(), vector.begin(),\r\n                       int(1), multi, queue);\r\n    CHECK_RANGE_EQUAL(int, 5, vector, (1, 2, 8, 16, 64));\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "3a8e403b17ba0b4103912efd2eb304a306532d83", "size": 11712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/compute/test/test_scan.cpp", "max_stars_repo_name": "snichols/boost_1_61_0", "max_stars_repo_head_hexsha": "10142fe2415a0c4ddb72207b5f235cce20f72649", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-06T09:03:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-06T09:03:52.000Z", "max_issues_repo_path": "libs/compute/test/test_scan.cpp", "max_issues_repo_name": "snichols/boost_1_61_0", "max_issues_repo_head_hexsha": "10142fe2415a0c4ddb72207b5f235cce20f72649", "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/compute/test/test_scan.cpp", "max_forks_repo_name": "snichols/boost_1_61_0", "max_forks_repo_head_hexsha": "10142fe2415a0c4ddb72207b5f235cce20f72649", "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.7521613833, "max_line_length": 80, "alphanum_fraction": 0.6023736339, "num_tokens": 3160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.520504795181895}}
{"text": "/**\n * @ file avgvalboundary_main.cc\n * @ brief NPDE homework AvgValBoundary code\n * @ author Simon Meierhans\n * @ date 11.03.2019\n * @ copyright Developed at ETH Zurich\n */\n\n#include <lf/assemble/assemble.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\n#include <Eigen/Core>\n#include <iostream>\n#include <memory>\n\n#include \"avgvalboundary.h\"\n\n/* SAM_LISTING_BEGIN_1 */\nint main() {\n  // read in mesh and set up finite element space\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/square.msh\");\n  auto mesh = reader.mesh();\n  // obtain dofh for lagrangian finite element space\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh);\n  const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n  // Solve test problem\n  Eigen::VectorXd mu = AvgValBoundary::solveTestProblem(dofh);\n  // compute H1 seminorm of the solution\n  double h1s_norm = AvgValBoundary::compH1seminorm(dofh, mu);\n  // compute boundary functional\n  auto w = [](Eigen::Vector2d x) -> double { return 1.0; };\n  double boundary_functional =\n      AvgValBoundary::compBoundaryFunctional(dofh, mu, w);\n\n  std::cout << \"H1s-norm: \" << h1s_norm << \"\\n\";\n  std::cout << \"F: \" << boundary_functional << \"\\n\";\n\n  //====================\n  // Your code goes here\n  //====================\n  return 0;\n}\n/* SAM_LISTING_END_1 */\n", "meta": {"hexsha": "660f46ef2d8fbfc6b62a059a743528bf792c325d", "size": 1541, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/AvgValBoundary/templates/avgvalboundary_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/AvgValBoundary/templates/avgvalboundary_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/AvgValBoundary/templates/avgvalboundary_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": 30.82, "max_line_length": 75, "alphanum_fraction": 0.6638546398, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342972, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.5205047902787627}}
{"text": "#ifndef _MST_HXX_\n#define _MST_HXX_\n\n#include <utility>\n#include <boost/shared_array.hpp>\n\nstruct UnionFind {\n\n    struct Entry {\n        int parent;\n        int depth;\n        int size;\n    };\n\n    int N;\n    boost::shared_array<Entry> partitions;\n\n    UnionFind(int N = 0);\n\n    int Find(int elem) const;\n    int Depth(int elem) const { return partitions[Find(elem)].depth; }\n    int ComponentSize(int elem) const { return partitions[Find(elem)].size; }\n    void Merge(int e1, int e2);\n    int Size() const { return N; }\n};\n\ninline UnionFind::UnionFind(int N)\n    : N(N) \n{\n    partitions = boost::shared_array<Entry>(new Entry[N]);\n    for (int i = 0; i < N; ++i) {\n        partitions[i].parent = i;\n        partitions[i].depth = 1;\n        partitions[i].size = 1;\n    }\n}\n\ninline int UnionFind::Find(int elem) const {\n    int parent = partitions[elem].parent;\n    while (parent != elem) {\n        elem = parent;\n        parent = partitions[elem].parent;\n    }\n    return elem;\n}\n\ninline void UnionFind::Merge(int e1, int e2) {\n    int p1 = Find(e1);\n    int p2 = Find(e2);\n    if (p1 == p2)\n        return;\n    int d1 = partitions[p1].depth;\n    int d2 = partitions[p2].depth;\n    if (d1 < d2) {\n        partitions[p1].parent = p2;\n        partitions[p2].size += partitions[p1].size;\n    } else if (d2 < d1) {\n        partitions[p2].parent = p1;\n        partitions[p1].size += partitions[p2].size;\n    } else {\n        partitions[p2].parent = p1;\n        partitions[p1].size += partitions[p2].size;\n        partitions[p1].depth++;\n    }\n}\n\n#endif\n", "meta": {"hexsha": "7294a60b2407a1f323dd7ff3ff34973366c6424f", "size": 1551, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/union-find.hpp", "max_stars_repo_name": "letterx/deconvolution", "max_stars_repo_head_hexsha": "5d4df9e842c121bd65537b7f8f4fb0a628b31242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-27T05:38:10.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-27T05:38:10.000Z", "max_issues_repo_path": "src/union-find.hpp", "max_issues_repo_name": "letterx/deconvolution", "max_issues_repo_head_hexsha": "5d4df9e842c121bd65537b7f8f4fb0a628b31242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/union-find.hpp", "max_forks_repo_name": "letterx/deconvolution", "max_forks_repo_head_hexsha": "5d4df9e842c121bd65537b7f8f4fb0a628b31242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-30T01:58:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-30T01:58:51.000Z", "avg_line_length": 22.8088235294, "max_line_length": 77, "alphanum_fraction": 0.580270793, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5205047865437218}}
{"text": "//  (C) Copyright Eric Niebler 2005.\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// Test case for weighted_p_square_quantile.hpp\r\n\r\n#include <cmath> // for std::exp()\r\n#include <boost/random.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/accumulators/numeric/functional/vector.hpp>\r\n#include <boost/accumulators/numeric/functional/complex.hpp>\r\n#include <boost/accumulators/numeric/functional/valarray.hpp>\r\n#include <boost/accumulators/accumulators.hpp>\r\n#include <boost/accumulators/statistics/stats.hpp>\r\n#include <boost/accumulators/statistics/weighted_p_square_quantile.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace unit_test;\r\nusing namespace boost::accumulators;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// test_stat\r\n//\r\nvoid test_stat()\r\n{\r\n    typedef accumulator_set<double, stats<tag::weighted_p_square_quantile>, double> accumulator_t;\r\n\r\n    // tolerance in %\r\n    double epsilon = 1;\r\n\r\n    // some random number generators\r\n    double mu4 = -1.0;\r\n    double mu5 = -1.0;\r\n    double mu6 = 1.0;\r\n    double mu7 = 1.0;\r\n    boost::lagged_fibonacci607 rng;\r\n    boost::normal_distribution<> mean_sigma4(mu4, 1);\r\n    boost::normal_distribution<> mean_sigma5(mu5, 1);\r\n    boost::normal_distribution<> mean_sigma6(mu6, 1);\r\n    boost::normal_distribution<> mean_sigma7(mu7, 1);\r\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal4(rng, mean_sigma4);\r\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal5(rng, mean_sigma5);\r\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal6(rng, mean_sigma6);\r\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal7(rng, mean_sigma7);\r\n\r\n    accumulator_t acc0(quantile_probability = 0.001);\r\n    accumulator_t acc1(quantile_probability = 0.025);\r\n    accumulator_t acc2(quantile_probability = 0.975);\r\n    accumulator_t acc3(quantile_probability = 0.999);\r\n\r\n    accumulator_t acc4(quantile_probability = 0.001);\r\n    accumulator_t acc5(quantile_probability = 0.025);\r\n    accumulator_t acc6(quantile_probability = 0.975);\r\n    accumulator_t acc7(quantile_probability = 0.999);\r\n\r\n\r\n    for (std::size_t i=0; i<100000; ++i)\r\n    {\r\n        double sample = rng();\r\n        acc0(sample, weight = 1.);\r\n        acc1(sample, weight = 1.);\r\n        acc2(sample, weight = 1.);\r\n        acc3(sample, weight = 1.);\r\n\r\n        double sample4 = normal4();\r\n        double sample5 = normal5();\r\n        double sample6 = normal6();\r\n        double sample7 = normal7();\r\n        acc4(sample4, weight = std::exp(-mu4 * (sample4 - 0.5 * mu4)));\r\n        acc5(sample5, weight = std::exp(-mu5 * (sample5 - 0.5 * mu5)));\r\n        acc6(sample6, weight = std::exp(-mu6 * (sample6 - 0.5 * mu6)));\r\n        acc7(sample7, weight = std::exp(-mu7 * (sample7 - 0.5 * mu7)));\r\n    }\r\n    // check for uniform distribution with weight = 1\r\n    BOOST_CHECK_CLOSE( weighted_p_square_quantile(acc0), 0.001, 28 );\r\n    BOOST_CHECK_CLOSE( weighted_p_square_quantile(acc1), 0.025, 5 );\r\n    BOOST_CHECK_CLOSE( weighted_p_square_quantile(acc2), 0.975, epsilon );\r\n    BOOST_CHECK_CLOSE( weighted_p_square_quantile(acc3), 0.999, epsilon );\r\n\r\n    // check for shifted standard normal distribution (\"importance sampling\")\r\n    BOOST_CHECK_CLOSE( weighted_p_square_quantile(acc4), -3.090232, epsilon );\r\n    BOOST_CHECK_CLOSE( weighted_p_square_quantile(acc5), -1.959963, epsilon );\r\n    BOOST_CHECK_CLOSE( weighted_p_square_quantile(acc6),  1.959963, epsilon );\r\n    BOOST_CHECK_CLOSE( weighted_p_square_quantile(acc7),  3.090232, epsilon );\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// init_unit_test_suite\r\n//\r\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n    test_suite *test = BOOST_TEST_SUITE(\"weighted_p_square_quantile test\");\r\n\r\n    test->add(BOOST_TEST_CASE(&test_stat));\r\n\r\n    return test;\r\n}\r\n\r\n", "meta": {"hexsha": "5133932809ab3fdc6ec85d31dfd0d170be6c4c33", "size": 4220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/accumulators/test/weighted_p_square_quantile.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/accumulators/test/weighted_p_square_quantile.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/accumulators/test/weighted_p_square_quantile.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.7821782178, "max_line_length": 116, "alphanum_fraction": 0.6708530806, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5205047828086805}}
{"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 * Fitting things to data.\n * ****************************************************************************\n */\n\n#ifndef VISIONCORE_MATH_FITTING_HPP\n#define VISIONCORE_MATH_FITTING_HPP\n\n#include <VisionCore/Platform.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n#include <Eigen/SVD>\n#include <Eigen/LU>\n\n#include <VisionCore/Math/Statistics.hpp>\n#include <VisionCore/Types/Hypersphere.hpp>\n\nnamespace vc\n{\n    \nnamespace math\n{\n\n/**\n * Fitting plane from 3D points.\n */\ntemplate<typename T>\nclass PlaneFitting\n{\npublic:\n    typedef MultivariateStats<Eigen::Matrix<T,3,1>> StatsT;\n    typedef typename StatsT::VectorType VectorT;\n    typedef typename StatsT::CovarianceType CovarianceMatrixT;\n    typedef Eigen::Hyperplane<T,3> PlaneT;\n    \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    PlaneFitting() { reset(); }\n    \n    inline void reset() { stats.reset(); }\n    inline std::size_t count() const { return stats.count(); }\n    \n    inline void operator()(const VectorT& x)\n    {\n        stats(x);\n    }\n\n    bool getPlane(PlaneT& p, T& curvature) const\n    {\n        return getPlane(stats, p, curvature);\n    }\n\nprivate:\n    bool getPlane(const StatsT& ss, PlaneT& p, T& curvature) const\n    {\n        if(ss.count() < 3)\n        {\n            return false;\n        }\n        \n        const VectorT mean_point = ss.mean();\n        const CovarianceMatrixT cm = ss.covariance();\n        \n        getPlane(cm, mean_point, p, curvature);\n        \n        return true;\n    }\n    \n    void getPlane(const CovarianceMatrixT& cm, const VectorT& mean_point, PlaneT& p, T& curvature) const\n    {\n        using Eigen::numext::abs;\n\n        Eigen::SelfAdjointEigenSolver<CovarianceMatrixT> es(cm);\n        \n        const T eigen_value = es.eigenvalues()(0);\n        const VectorT eigen_vector = es.eigenvectors().col(0); \n        \n        p.normal() = eigen_vector;\n        \n        T eig_sum = cm.coeff(0) + cm.coeff(4) + cm.coeff(8);\n        if(eig_sum != T(0.0))\n        {\n            curvature = abs(eigen_value / eig_sum);\n        }\n        else\n        {\n            curvature = T(0.0);\n        }\n        \n        // Hessian form (D = nc . p_plane (centroid here) + p)\n        p.offset() = T(1.0) * eigen_vector.dot(mean_point); \n    }\n    \n    math::MultivariateStats<VectorT> stats;\n};\n\n/**\n * Circle from 3 points.\n */\ntemplate<typename T>\nEIGEN_DEVICE_FUNC static inline types::CircleT<T> circleFrom3Points(const Eigen::Matrix<T,2,1>& p1, const Eigen::Matrix<T,2,1>& p2, const Eigen::Matrix<T,2,1>& p3)\n{\n    T ma = (p2(1) - p1(1))/(p2(0) - p1(0));\n    T mb = (p3(1) - p2(1))/(p3(0) - p2(0));\n    \n    T cx = (ma*mb * (p1(1) - p3(1)) + mb * (p1(0) + p2(0)) - ma * (p2(0) + p3(0)))/(2 * (mb - ma));\n    T cy = (mb*p3(1)+(mb-ma)*p2(1)-ma*p1(1)+p3(0)-p1(0))/(2*(mb-ma));\n    \n    types::CircleT<T> ret;\n    \n    ret.coeff() << cx , cy;\n    ret.radius() = ret(p1);\n    \n    return ret;\n}\n\n// ****************** AFFINE FROM 3D POINT CORRESPONDANCES ***********\n\n/**\n * Establish transform from 3D corresponding points.\n */\ntemplate<typename T>\nclass TransformationFrom3DPointPairs\n{\npublic:\n    typedef Eigen::Matrix<T,3,1> VectorT;\n    typedef Eigen::Matrix<T,3,3> MatrixT;\n    \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    inline void reset() \n    { \n        sample_count = 0;\n        accumulated_weight_ = 0.0;\n        mean1.fill(0);\n        mean2.fill(0);\n        covariance.fill(0);\n    }\n    \n    inline std::size_t count() const { return sample_count; }\n    \n    inline void operator()(const VectorT& p1, const VectorT& p2, T weight = T(1.0))\n    {\n        if(weight == T(0.0))\n            return;\n   \n        ++sample_count;\n        accumulated_weight_ += weight;\n        T alpha = weight/accumulated_weight_;\n        \n        VectorT diff1 = p1 - mean1, diff2 = p2 - mean2;\n        covariance = (T(1.0) - alpha)*(covariance + alpha * (diff2 * diff1.transpose()));\n        \n        mean1 += alpha * (diff1);\n        mean2 += alpha * (diff2);\n    }\n    \n    inline Eigen::Affine3f getTransformation ()\n    {\n        Eigen::JacobiSVD<MatrixT> svd (covariance, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        const MatrixT& u = svd.matrixU(),& v = svd.matrixV();\n        \n        MatrixT s;\n        s.setIdentity();\n        if(u.determinant()*v.determinant() < T(0.0f))\n        {\n            s(2,2) = T(-1.0);\n        }\n        \n        MatrixT r = u * s * v.transpose();\n        VectorT t = mean2 - r*mean1;\n        \n        Eigen::Transform<T,3,Eigen::Affine> ret(Eigen::Matrix<T,4,4>::Zero());\n        ret.block<3,3>(0,0) = r;\n        ret.block<3,1>(0,3) = t;\n        \n        return ret;\n    }\nprivate:\n    std::size_t sample_count;\n    T accumulated_weight_;\n    VectorT mean1, mean2;\n    MatrixT covariance;\n};\n   \n}\n\n}\n\n#endif // VISIONCORE_MATH_FITTING_HPP\n", "meta": {"hexsha": "9820c0112b2f7abde7f9122198b25d5a23b63dcf", "size": 6553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/VisionCore/Math/Fitting.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/Fitting.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/Fitting.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": 29.2544642857, "max_line_length": 163, "alphanum_fraction": 0.5966732794, "num_tokens": 1695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5204990071340272}}
{"text": "/**\n * @file clempiricflux.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 \"clempiricflux.h\"\n\n#include <Eigen/Core>\n#include <cassert>\n\nnamespace CLEmpiricFlux {\n\n/**\n * @brief Bisection algorithm for root finding of an increasing function.\n *\n * @param g continuous changing sign in the interval [v, w]\n * @param v lower bound of the interval containg the root\n * @param w upper bound of the interval containg the root\n * @param tol error tolerance for stopping criterion\n * @return approximate root x in [v, w]\n */\n/* SAM_LISTING_BEGIN_8 */\ntemplate <typename FUNCTOR>\ndouble findRoots(double v, double w, FUNCTOR &&g, double tol = 1.0E-6) {\n  double x = v;  // approximate root\n  const double len = w - v;\n  constexpr static const int maxN = 1000;\n  double gv = g(v), gw = g(w);\n  // Ensure that function changes sign\n  assert(gv * gw <= 0);\n  for (int N = 0; (std::abs(w - v) > tol * len) && N < maxN; N++) {\n    x = (v + w) / 2.0;\n    const double gx = g(x);\n    if (gv * gx < 0.0) {\n      // Sign change in left half of [v,w]\n      w = x;\n      gw = gx;\n    } else {\n      // Sign change in right half of [v,w]\n      v = x;\n      gv = gx;\n    }\n  }\n  return x;\n}\n/* SAM_LISTING_END_8 */\n\nGodunovFlux::GodunovFlux(const UniformCubicSpline &f) : _f(f){};\n\n/* SAM_LISTING_BEGIN_9 */\ndouble GodunovFlux::operator()(double v, double w) const {\n  double result;\n  //====================\n  // Your code goes here\n  //====================\n  return result;\n}\n\n/* SAM_LISTING_END_9 */\n\n}  // namespace CLEmpiricFlux\n", "meta": {"hexsha": "cae832a62d36fa98c1b61ad2de75eaf375618887", "size": 1627, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/CLEmpiricFlux/templates/clempiricflux.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/clempiricflux.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/clempiricflux.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.0307692308, "max_line_length": 73, "alphanum_fraction": 0.6207744315, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.7905303285397348, "lm_q1q2_score": 0.5204990030353384}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Polygon_mesh_processing/compute_normal.h>\n#include <boost/property_map/property_map.hpp>\n\n#include <map>\n// #include <CGAL/Unique_hash_map.h>\n// #include <boost/unordered_map.hpp>\n\n#include <iostream>\n#include <fstream>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_3 Point;\ntypedef K::Vector_3 Vector;\n\ntypedef CGAL::Polyhedron_3<K> Polyhedron;\ntypedef boost::graph_traits<Polyhedron>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<Polyhedron>::face_descriptor   face_descriptor;\n\nint main(int argc, char* argv[])\n{\n  const char* filename = (argc > 1) ? argv[1] : \"data/eight.off\";\n  std::ifstream input(filename);\n\n  Polyhedron mesh;\n  if (!input || !(input >> mesh) || mesh.is_empty()) {\n    std::cerr << \"Not a valid off file.\" << std::endl;\n    return 1;\n  }\n\n  std::map<face_descriptor,Vector> fnormals;\n  std::map<vertex_descriptor,Vector> vnormals;\n  // Instead of std::map you may use std::unordered_map, boost::unordered_map\n  // or CGAL::Unique_hash_map\n  // CGAL::Unique_hash_map<face_descriptor,Vector> fnormals;\n  // boost::unordered_map<vertex_descriptor,Vector> vnormals;\n\n  CGAL::Polygon_mesh_processing::compute_normals(mesh,\n                                                 boost::make_assoc_property_map(vnormals),\n                                                 boost::make_assoc_property_map(fnormals));\n\n  std::cout << \"Face normals :\" << std::endl;\n  for(face_descriptor fd: faces(mesh)){\n    std::cout << fnormals[fd] << std::endl;\n  }\n  std::cout << \"Vertex normals :\" << std::endl;\n  for(vertex_descriptor vd: vertices(mesh)){\n    std::cout << vnormals[vd] << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "0b4032cc7d1d7ab2e16c1b9b841d71813bb10e65", "size": 1781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Polygon_mesh_processing/examples/Polygon_mesh_processing/compute_normals_example_Polyhedron.cpp", "max_stars_repo_name": "gaschler/cgal", "max_stars_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_stars_repo_licenses": ["CC0-1.0"], "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": "Polygon_mesh_processing/examples/Polygon_mesh_processing/compute_normals_example_Polyhedron.cpp", "max_issues_repo_name": "gaschler/cgal", "max_issues_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_issues_repo_licenses": ["CC0-1.0"], "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": "Polygon_mesh_processing/examples/Polygon_mesh_processing/compute_normals_example_Polyhedron.cpp", "max_forks_repo_name": "gaschler/cgal", "max_forks_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_forks_repo_licenses": ["CC0-1.0"], "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": 33.6037735849, "max_line_length": 91, "alphanum_fraction": 0.6895002807, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5204990018353727}}
{"text": "#define BOOST_TEST_MODULE eigen_cuda\n\n#include \"cudamatrix.hpp\"\n#include \"cudapipeline.hpp\"\n#include <boost/test/unit_test.hpp>\n\nusing eigencuda::CudaMatrix;\nusing eigencuda::CudaPipeline;\nusing eigencuda::Index;\n\nBOOST_AUTO_TEST_CASE(create_cudamatrix) {\n  // Call the class to handle GPU resources\n  CudaPipeline cp;\n\n  // Call matrix multiplication GPU\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(2, 2);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Zero(3, 2);\n  Eigen::MatrixXd X = Eigen::MatrixXd::Zero(3, 2);\n\n  // Define matrices\n  A << 1., 2., 3., 4.;\n  B << 5., 6., 7., 8., 9., 10.;\n  X << 23., 34., 31., 46., 39., 58.;\n\n  // Copy matrix back and for to the GPU\n  CudaMatrix cumatrix{B, cp.get_stream()};\n  Eigen::MatrixXd tmp = cumatrix;\n  Eigen::MatrixXd result = tmp * A;\n\n  // Expected results\n  BOOST_TEST(X.isApprox(result));\n}\n\nBOOST_AUTO_TEST_CASE(matrix_multiplication) {\n\n  Index dim = 200;\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(dim, dim);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Random(dim, dim);\n\n  CudaPipeline cuda_pip;\n  CudaMatrix cuma_A{A, cuda_pip.get_stream()};\n  CudaMatrix cuma_B{B, cuda_pip.get_stream()};\n  CudaMatrix cuma_C{dim, dim, cuda_pip.get_stream()};\n\n  cuda_pip.gemm(cuma_A, cuma_B, cuma_C);\n\n  Eigen::MatrixXd C = cuma_C;\n  Eigen::MatrixXd result = A * B;\n\n  BOOST_TEST(C.isApprox(result));\n}\n\nBOOST_AUTO_TEST_CASE(right_matrix_multiplication) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip;\n\n  // Call matrix multiplication GPU\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(2, 2);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Zero(3, 2);\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(3, 2);\n  Eigen::MatrixXd D = Eigen::MatrixXd::Zero(3, 2);\n  Eigen::MatrixXd X = Eigen::MatrixXd::Zero(3, 2);\n  Eigen::MatrixXd Y = Eigen::MatrixXd::Zero(3, 2);\n  Eigen::MatrixXd Z = Eigen::MatrixXd::Zero(3, 2);\n\n  // Define matrices\n  A << 1., 2., 3., 4.;\n  B << 5., 6., 7., 8., 9., 10.;\n  C << 9., 10., 11., 12., 13., 14.;\n  D << 13., 14., 15., 16., 17., 18.;\n  X << 23., 34., 31., 46., 39., 58.;\n  Y << 39., 58., 47., 70., 55., 82.;\n  Z << 55., 82., 63., 94., 71., 106.;\n\n  std::vector<Eigen::MatrixXd> tensor{B, C, D};\n  std::vector<Eigen::MatrixXd> results(3, Eigen::MatrixXd::Zero(3, 2));\n  CudaMatrix cuma_A{A, cuda_pip.get_stream()};\n  CudaMatrix cuma_B{3, 2, cuda_pip.get_stream()};\n  CudaMatrix cuma_C{3, 2, cuda_pip.get_stream()};\n\n  for (Index i = 0; i < 3; i++) {\n    cuma_B.copy_to_gpu(tensor[i]);\n    cuda_pip.gemm(cuma_B, cuma_A, cuma_C);\n    results[i] = cuma_C;\n  }\n  // Expected results\n  BOOST_TEST(X.isApprox(results[0]));\n  BOOST_TEST(Y.isApprox(results[1]));\n  BOOST_TEST(Z.isApprox(results[2]));\n}\n\nBOOST_AUTO_TEST_CASE(wrong_shape_cublas) {\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(2, 2);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Random(5, 5);\n\n  CudaPipeline cuda_pip;\n  CudaMatrix cuma_A{A, cuda_pip.get_stream()};\n  CudaMatrix cuma_B{B, cuda_pip.get_stream()};\n  CudaMatrix cuma_C{2, 5, cuda_pip.get_stream()};\n\n  BOOST_REQUIRE_THROW(cuda_pip.gemm(cuma_A, cuma_B, cuma_C),\n                      std::runtime_error);\n}\n", "meta": {"hexsha": "435f86bfd560e75a19fc9ed475a791f7cb42e37d", "size": 3089, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_dot.cc", "max_stars_repo_name": "cffbots/EigenCuda", "max_stars_repo_head_hexsha": "be5935f9c0010f666d925e426f013480d3c876cc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T13:30:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:00:49.000Z", "max_issues_repo_path": "src/tests/test_dot.cc", "max_issues_repo_name": "cffbots/EigenCuda", "max_issues_repo_head_hexsha": "be5935f9c0010f666d925e426f013480d3c876cc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2019-04-12T07:47:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-17T12:38:56.000Z", "max_forks_repo_path": "src/tests/test_dot.cc", "max_forks_repo_name": "cffbots/EigenCuda", "max_forks_repo_head_hexsha": "be5935f9c0010f666d925e426f013480d3c876cc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-30T22:48:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T13:43:57.000Z", "avg_line_length": 29.7019230769, "max_line_length": 71, "alphanum_fraction": 0.6587892522, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5204990006354066}}
{"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_FACT_10_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_FACT_10_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Fact_10 Fact_10 (function template)\n\n  Generates the @c 10! constant\n\n  @headerref{<boost/simd/constant/fact_10.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Fact_10();\n      @endcode\n\n  2.  @code\n      template<typename T> T Fact_10( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T that evaluates to 10!.\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 @c T(3628800).\n\n  @par Requirements\n  - **T** models Value\n**/\n\n#include <boost/simd/constant/scalar/fact_10.hpp>\n#include <boost/simd/constant/simd/fact_10.hpp>\n\n#endif\n", "meta": {"hexsha": "de290e85897e0ff0004490d91577e50a44a00d61", "size": 1448, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/fact_10.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/fact_10.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/fact_10.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": 28.3921568627, "max_line_length": 100, "alphanum_fraction": 0.5227900552, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.520498996536718}}
{"text": "#ifndef _jsc_bioinfo_sig_hpp_included_\n#define _jsc_bioinfo_sig_hpp_included_\n\n#include <boost/config.hpp>\n\n#include <math.h>\n\n#include <iostream>\n#include <map>\n#include <set>\n#include <sstream>\n#include <vector>\n\n#include <boost/lambda/bind.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include \"jsc/util/interval_list.hpp\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::lambda;\n\nusing namespace jsc::util;\n\nnamespace jsc\n{\n\nnamespace bioinfo\n{\n\n//! Defines the format of a simple sig entry, without strand information.\nclass sig_entry\n{\npublic:\n\tstring chrName;\n\tlong start;\n\tlong end;\n\tdouble sig;\n};\n\n//! A shared_ptr to sig_entry.\n/*!\n * \\sa str2sigp().\n */\ntypedef shared_ptr<sig_entry> sig_ptr;\n//! A vector of jsc::bioinfo::sig_ptr.\n/*!\n * \\sa load_sigps_noheader().\n */\ntypedef vector<sig_ptr> vec_sigp;\n//! A map of (chrName, jsc::util::interval_list).\n/*!\n * \\sa get_map_chr_intervals().\n */\ntypedef map<string, interval_list<long> > map_chr_intervals;\n\ndouble generalized_log2(double x) {\n\tif (x > 0) {\n\t\treturn log2(x + 1);\n\t} else {\n\t\treturn -log2(-x+1);\n\t}\n}\n\n//! Converts a string to jsc::bioinfo::sig_ptr\nsig_ptr str2sigp(string const & line, bool apply_generalized_log2 = false) {\n\tsig_ptr sigp(new sig_entry());\n\tistringstream iss(line);\n\tiss >> sigp->chrName\n\t\t>> sigp->start\n\t\t>> sigp->end\n\t\t>> sigp->sig;\n\tif (apply_generalized_log2) {\n\t\tsigp->sig = generalized_log2(sigp->sig);\n\t}\n\n\treturn sigp;\n}\n\n//! Loads a vector of jsc::bioinfo::sig_ptr from an istream (w/o the header).\nvec_sigp load_sigps_noheader(istream & is)\n{\n\tstring line;\n\n\t/* read content */\n\tvec_sigp sigps;\n\twhile (getline(is, line) && !is.eof())\n\t{\n\t\tsigps.push_back(str2sigp(line));\n\t}\n\n\treturn sigps;\n}\n\n//! Loads a vector of jsc::bioinfo::sig_ptr from an istream (w/o the header) for a specific chrName.\nvoid load_sigps_noheader(istream & is, vec_sigp & sigps)\n{\n\tstring line;\n\n\t/* read content */\n\twhile (getline(is, line) && !is.eof())\n\t{\n\t\tsig_ptr sigp = str2sigp(line);\n\t\tsigps.push_back(str2sigp(line));\n\t}\n}\n\n//! Loads a vector of jsc::bioinfo::sig_ptr from an istream (w/o the header) for a specific chrName.\nvec_sigp load_sigps_noheader(istream & is, string const & chrName)\n{\n\tstring line;\n\n\t/* read content */\n\tvec_sigp sigps;\n\twhile (getline(is, line) && !is.eof())\n\t{\n\t\tsig_ptr sigp = str2sigp(line);\n\t\tif (sigp->chrName == chrName)\n\t\t{\n\t\t\tsigps.push_back(str2sigp(line));\n\t\t}\n\t}\n\n\treturn sigps;\n}\n\n//! Loads a map from chrName to vector of jsc::bioinfo::sig_ptr from an istream (w/o the header)\nvoid load_chr_sigps_map_noheader(istream & is, map<string, vec_sigp> & chr_sigps_map, bool apply_generalized_log2 = false)\n{\n\tstring line;\n\n\t/* read content */\n\twhile (getline(is, line) && !is.eof())\n\t{\n\t\tsig_ptr sigp = str2sigp(line, apply_generalized_log2);\n\t\tchr_sigps_map[sigp->chrName].push_back(sigp);\n\t}\n}\n\nvoid sort_sigps(vec_sigp & sigps) {\n\tsort(sigps.begin(), sigps.end(),\n\t\t\tbind(&sig_entry::start, cref(*_1)) < bind(&sig_entry::start, cref(*_2)));\n}\n\n//! Returns all intervals whose signal values are greater/no greater than the given threshold.\n/*!\n * \\param sigps A vector of jsc::bioinfo::sig_ptr.\n * \\param threshold The threshold.\n * \\param greater_than_threshold A boolean variable specifying whether the criteria is > or <= threshold.\n * \\return map_chr_intervals: a map of (chrName, jsc::util::interval_list).\n */\nmap_chr_intervals get_map_chr_intervals(vec_sigp const & sigps, double threshold, bool greater_than_threshold)\n{\n\tmap_chr_intervals cil_map;\n\tunsigned long i;\n\tfor (i = 0; i < sigps.size(); ++i)\n\t{\n\t\tsig_ptr sigp = sigps[i];\n\t\tif ((greater_than_threshold && sigp->sig > threshold) ||\n\t\t\t\t(!greater_than_threshold && sigp->sig <= threshold))\n\t\t{\n\t\t\tcil_map[sigp->chrName].add_interval(sigp->start, sigp->end);\n\t\t}\n\t}\n\n\treturn cil_map;\n}\n\nvoid get_map_chr_intervals(vec_sigp const & sigps, double threshold, bool greater_than_threshold, map_chr_intervals & cil_map)\n{\n\tunsigned long i;\n\tfor (i = 0; i < sigps.size(); ++i)\n\t{\n\t\tsig_ptr sigp = sigps[i];\n\t\tif ((greater_than_threshold && sigp->sig > threshold) ||\n\t\t\t\t(!greater_than_threshold && sigp->sig <= threshold))\n\t\t{\n\t\t\tcil_map[sigp->chrName].add_interval(sigp->start, sigp->end);\n\t\t}\n\t}\n}\n\n} /* end of bioinfo */\n\n} /* end of jsc */\n\n#endif\n", "meta": {"hexsha": "eac79b73d9935d918e381a50b113cf35b94d349e", "size": 4282, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "jdu_source_collection/jsc/bioinfo/sig.hpp", "max_stars_repo_name": "gersteinlab/LESSeq", "max_stars_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-06-19T21:14:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-15T03:04:41.000Z", "max_issues_repo_path": "jdu_source_collection/jsc/bioinfo/sig.hpp", "max_issues_repo_name": "gersteinlab/LESSeq", "max_issues_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-12T21:17:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-20T13:50:38.000Z", "max_forks_repo_path": "jdu_source_collection/jsc/bioinfo/sig.hpp", "max_forks_repo_name": "gersteinlab/LESSeq", "max_forks_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_forks_repo_licenses": ["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.6560846561, "max_line_length": 126, "alphanum_fraction": 0.6975712284, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.5204989912380632}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"logs.h\"\n#include \"route.h\"\n#include \"track.h\"\n\nusing namespace GPS;\n\n/* \nDocumentation:\nFor my test file I have chosen to do the Minimum Gradient function.\nThis function determines which gradient between each position is the lowest, to check that this function works I have created 10 different tests below checking the functions against certain routes I have created. To work out the gradient between two positions you first need to work out the distance between these two points this can be done using Pythagoras. After the angle is worked out using Trigonometry, the chosen angle will depends on if the route is downhill or uphill. My test will check that the function answers are correct and will try and catch out errors. Throughout the tests majority of them are check_close this is because there could be a rounding difference, I have each case to be 1 +/- of the answer I think this is an appropriate amount.\n\n*/\n\nBOOST_AUTO_TEST_SUITE( Route_minGradient )\n\nconst bool isFileName = true;\n\n//TEST 1: No Elevation change\n// This test checks that the minGradient is correct for ABCD GPX route where there is no change in elevtion therefore no gradient. \nBOOST_AUTO_TEST_CASE( routeABCD )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"ABCD.gpx\", isFileName);\n   BOOST_CHECK_EQUAL( route.minGradient(), 0 );\n}\n\n//TEST 2: Constant Downwards Gradient\n//This route goes downhill at a constant decrease rate\nBOOST_AUTO_TEST_CASE( ConstDownGrad )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"ConstDownGrad.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.minGradient(), -84.87, 1 );\n\n}\n\n//TEST 3: Const Upwards Gradient\n//The route will go upwards by the same elevation each time\nBOOST_AUTO_TEST_CASE( ConstUpGrad )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"ConstUpGrad.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.minGradient(), 84.87, 1 );\n\n}\n\n//TEST 4: DiagalnalIncline\n//This test will go dialgonlly on the grid testing that the function includes the Pythagorus part of the equation\nBOOST_AUTO_TEST_CASE( DiagonalIncline )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"DiagonalIncline.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.minGradient(), 82.75, 1 );\n\n}\n\n//TEST 5: DiagalnalDecline\n//This test is the same as above however it decreases in elevation at each position\nBOOST_AUTO_TEST_CASE( DiagonalDecline )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"DiagonalDecline.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.minGradient(), -82.75, 1 );\n\n}\n\n\n//TEST 6: Only Elevation change = 90/-90\n//This test is where the different positions will stay exactly where they are but go higher/lower in altitude ensuring that the function checks if the distance interms of latitude and longatude is equal to 0 beforehand\nBOOST_AUTO_TEST_CASE( ElevationChangeOnly )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"ElevationChangeOnly.gpx\", isFileName);\n   BOOST_CHECK_EQUAL( route.minGradient(), 90 );\n}\n\n\n//TEST 7: Unconstant Downward Gradient\n//This GPX file has been edited so that the elevation isn't constant. The whole route will be going downwards but at a different rate\nBOOST_AUTO_TEST_CASE( UnconstDownGrad )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"UnconstantDownGrad.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.minGradient(), -77.34, 1 );\n\n}\n\n\n//TEST 8: Unconstant Upward Gradient\n//This route will go upwards but not at a consistant rate, this elevation will differ\nBOOST_AUTO_TEST_CASE( UnconstUpGrad )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"UnconstantUpGrad.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.minGradient(), 79.82, 1 );\n\n}\n\n//The following tests checks that invalid arguments have been put inplace\n//TEST 9: Invalid Input i.e letter\n//This GPX file includes letters instead of numbers, the function should first check the inputted data is the right format\nBOOST_AUTO_TEST_CASE( InvalidInput )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"InvalidInput.gpx\", isFileName);\n   BOOST_CHECK_THROW( route.minGradient(), std::invalid_argument );\n}\n\n\n//TEST 10: Nothing In Vector\n//For this test I have left some places blank this should throw an exception\nBOOST_AUTO_TEST_CASE( NoInput )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"NoInput.gpx\", isFileName);\n   BOOST_CHECK_THROW( route.minGradient(), std::invalid_argument );\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n\n\n\n\n", "meta": {"hexsha": "053851c6b2281275d8c73c36f9a4b35b9efc6ab9", "size": 4398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpx-tests/n0671966_mingrad.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/n0671966_mingrad.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/n0671966_mingrad.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": 36.9579831933, "max_line_length": 760, "alphanum_fraction": 0.7683037744, "num_tokens": 1066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604181, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5204503319234998}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_PREDICATES_FUNCTIONS_SIMD_COMMON_MAJORITY_HPP_INCLUDED\n#define BOOST_SIMD_PREDICATES_FUNCTIONS_SIMD_COMMON_MAJORITY_HPP_INCLUDED\n#include <boost/simd/predicates/functions/majority.hpp>\n#include <boost/simd/sdk/meta/as_logical.hpp>\n#include <boost/simd/include/functions/simd/is_nez.hpp>\n#include <boost/simd/include/functions/simd/logical_and.hpp>\n#include <boost/simd/include/functions/simd/logical_or.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT         (majority_, tag::cpu_,\n                           (A0)(X),\n                           ((simd_<arithmetic_<A0>,X>))\n                           ((simd_<arithmetic_<A0>,X>))\n                           ((simd_<arithmetic_<A0>,X>))\n                          )\n  {\n    typedef typename meta::as_logical<A0>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(3)\n    {\n      result_type aa0 = is_nez(a0);\n      result_type aa1 = is_nez(a1);\n      result_type aa2 = is_nez(a2);\n      result_type r =  logical_or(\n               logical_or(\n                 logical_and(aa0, aa1),\n                 logical_and(aa1, aa2)\n               ),\n               logical_and(aa2, aa0)\n             );\n      return r;\n    }\n  };\n} } }\n#endif\n", "meta": {"hexsha": "d0c7ad8f573907e98096d41fe99183105a7735c8", "size": 1742, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/predicates/functions/simd/common/majority.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/predicates/functions/simd/common/majority.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/boost/simd/base/include/boost/simd/predicates/functions/simd/common/majority.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 39.5909090909, "max_line_length": 80, "alphanum_fraction": 0.5464982778, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5204503174237698}}
{"text": "#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <boost/range/algorithm.hpp>\n#include <boost/integer/common_factor_rt.hpp>\n\nusing namespace std;\n\nint N, T;\n\nint main() {\n\n    while (cin >> N) {\n        int W[N], ret = 100 * 100;\n        for (int i = 0; i < N; i++) {\n            cin >> W[i];\n        }\n        for (int i = 0; i < N; i++) {\n            int left_sum = 0, right_sum = 0;\n            for (int j = 0; j < i; j++) {\n                left_sum += W[j];\n            }\n            for (int j = i; j < N; j++) {\n                right_sum += W[j];\n            }\n            ret = min(ret, abs(left_sum - right_sum));\n        }\n        cout << ret << endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "1e0ef56748da9e0237680c383393b586a78e5ee5", "size": 756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc129_b/Main.cpp", "max_stars_repo_name": "mizo0203/atcoder", "max_stars_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "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": "abc129_b/Main.cpp", "max_issues_repo_name": "mizo0203/atcoder", "max_issues_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "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": "abc129_b/Main.cpp", "max_forks_repo_name": "mizo0203/atcoder", "max_forks_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "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.0, "max_line_length": 54, "alphanum_fraction": 0.4510582011, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5204503147213551}}
{"text": "/***************************************************************************\n* Copyright (c) Johan Mabille, Sylvain Corlay and Wolf Vollprecht          *\n* Copyright (c) QuantStack                                                 *\n*                                                                          *\n* Distributed under the terms of the BSD 3-Clause License.                 *\n*                                                                          *\n* The full license is in the file LICENSE, distributed with this software. *\n****************************************************************************/\n\n#include <benchmark/benchmark.h>\n\n#ifdef HAS_XTENSOR\n#include \"xtensor/xnoalias.hpp\"\n#include \"xtensor/xio.hpp\"\n#include \"xtensor/xrandom.hpp\"\n#include \"xtensor/xtensor.hpp\"\n#include \"xtensor/xarray.hpp\"\n#include \"xtensor/xstrided_view.hpp\"\n#include \"xtensor/xview.hpp\"\n#include \"xtensor/xdynamic_view.hpp\"\n#include \"xtensor/xadapt.hpp\"\n#endif\n\n#ifdef HAS_EIGEN\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#endif\n\n#ifdef HAS_BLITZ\n#include <blitz/array.h>\n#endif\n\n#ifdef HAS_ARMADILLO\n#include <armadillo>\n#endif\n\n#define RANGE 3, 1000\n#define MULTIPLIER 8\n\n\n#ifdef HAS_XTENSOR\nvoid Add2dView_XTensor(benchmark::State& state)\n{\n    using namespace xt;\n\n    xtensor<double,2> vA = random::rand<double>({state.range(0), state.range(0)});\n    xtensor<double,2> vB = random::rand<double>({state.range(0), state.range(0)});\n\n    auto vAView = xt::view(vA, all(), all());\n    auto vBView = xt::view(vB, all(), all());\n\n    for (auto _ : state)\n    {\n        xtensor<double,2> vRes(vAView + vBView);\n        benchmark::DoNotOptimize(vRes.data());\n    }\n}\nBENCHMARK(Add2dView_XTensor)->RangeMultiplier(MULTIPLIER)->Range(RANGE);\n#endif\n\n#ifdef HAS_EIGEN\nvoid Add2dView_Eigen(benchmark::State& state)\n{\n    using namespace Eigen;\n    MatrixXd vA = MatrixXd::Random(state.range(0), state.range(0));\n    MatrixXd vB = MatrixXd::Random(state.range(0), state.range(0));\n\n    auto vAView = vA.topLeftCorner(state.range(0), state.range(0));\n    auto vBView = vB.topLeftCorner(state.range(0), state.range(0));\n\n    for (auto _ : state)\n    {\n        MatrixXd vRes(state.range(0), state.range(0));\n        vRes.noalias() = vAView + vBView;\n        benchmark::DoNotOptimize(vRes.data());\n    }\n}\nBENCHMARK(Add2dView_Eigen)->RangeMultiplier(MULTIPLIER)->Range(RANGE);\n\n//void Add1dMap_Eigen(benchmark::State& state)\n//{\n//    using namespace Eigen;\n//    MatrixXd vA = VectorXd::Random(state.range(0));\n//    MatrixXd vB = VectorXd::Random(state.range(0));\n//\n//    auto vAView = Map<VectorXd, 0, InnerStride<1>>(vA.data(), vA.size());\n//    auto vBView = Map<VectorXd, 0, InnerStride<1>>(vB.data(), vB.size());\n//\n//    for (auto _ : state)\n//    {\n//        VectorXd vRes(vAView + vBView);\n//        benchmark::DoNotOptimize(vRes.data());\n//    }\n//}\n//BENCHMARK(Add1dMap_Eigen)->RangeMultiplier(MULTIPLIER)->Range(RANGE);\n#endif\n\n#ifdef HAS_XTENSOR\nvoid Add2dStridedView_XTensor(benchmark::State& state)\n{\n    using namespace xt;\n\n    xtensor<double, 2> vA = random::rand<double>({state.range(0), state.range(0)});\n    xtensor<double, 2> vB = random::rand<double>({state.range(0), state.range(0)});\n\n    auto vAView = xt::strided_view(vA, {all(), all()});\n    auto vBView = xt::strided_view(vB, {all(), all()});\n\n    for (auto _ : state)\n    {\n        xtensor<double, 2> vRes(vAView + vBView);\n        benchmark::DoNotOptimize(vRes.data());\n    }\n}\nBENCHMARK(Add2dStridedView_XTensor)->RangeMultiplier(MULTIPLIER)->Range(RANGE);\n\nvoid Add2dDynamicView_XTensor(benchmark::State& state)\n{\n    using namespace xt;\n\n    xtensor<double, 2> vA = random::rand<double>({state.range(0), state.range(0)});\n    xtensor<double, 2> vB = random::rand<double>({state.range(0), state.range(0)});\n\n    auto vAView = xt::dynamic_view(vA, {all(), all()});\n    auto vBView = xt::dynamic_view(vB, {all(), all()});\n\n    for (auto _ : state)\n    {\n        xtensor<double, 2> vRes(vAView + vBView);\n        benchmark::DoNotOptimize(vRes.data());\n    }\n}\nBENCHMARK(Add2dDynamicView_XTensor)->RangeMultiplier(MULTIPLIER)->Range(RANGE);\n\nvoid Add2dAdapt_XTensor(benchmark::State& state)\n{\n    using namespace xt;\n\n    xtensor<double, 2> vA = random::rand<double>({state.range(0), state.range(0)});\n    xtensor<double, 2> vB = random::rand<double>({state.range(0), state.range(0)});\n    std::size_t vSize = static_cast<std::size_t>(state.range(0));\n    std::array<std::size_t, 2> vShape = {vSize, vSize};\n    auto vAView = xt::adapt(std::move(vA.data()), vShape);\n    auto vBView = xt::adapt(std::move(vB.data()), vShape);\n\n    for (auto _ : state)\n    {\n        xtensor<double, 2> vRes(vAView + vBView);\n        benchmark::DoNotOptimize(vRes.data());\n    }\n}\nBENCHMARK(Add2dAdapt_XTensor)->RangeMultiplier(MULTIPLIER)->Range(RANGE);\n\nvoid Add2dLoop_XTensor(benchmark::State& state)\n{\n    using namespace xt;\n\n    xtensor<double, 2> vA = random::rand<double>({state.range(0), state.range(0)});\n    xtensor<double, 2> vB = random::rand<double>({state.range(0), state.range(0)});\n    std::array<std::size_t, 2> vShape = {static_cast<std::size_t>(state.range(0)), static_cast<std::size_t>(state.range(0))};\n    for (auto _ : state)\n    {\n        xtensor<double, 2> vRes(vShape);\n        for (std::size_t i = 0; i < vRes.shape()[0]; ++i)\n        {\n            for (std::size_t j = 0; j < vRes.shape()[1]; ++j)\n            {\n                vRes(i, j) = vA(i, j) + vB(i, j);\n            }\n        }\n        benchmark::DoNotOptimize(vRes.data());\n    }\n}\nBENCHMARK(Add2dLoop_XTensor)->RangeMultiplier(MULTIPLIER)->Range(RANGE);\n#endif\n\n\n#undef RANGE\n#undef MULTIPLIER\n\n", "meta": {"hexsha": "a2924bb8d0020597dd9a0effec070260ed444fdc", "size": 5638, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/benchmark_views.hpp", "max_stars_repo_name": "breznak/xtensor-benchmark", "max_stars_repo_head_hexsha": "1a4afb5ca75a4119c09a4063975c5bc5aa1d8e66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-02-26T01:27:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-03T09:16:32.000Z", "max_issues_repo_path": "src/benchmark_views.hpp", "max_issues_repo_name": "breznak/xtensor-benchmark", "max_issues_repo_head_hexsha": "1a4afb5ca75a4119c09a4063975c5bc5aa1d8e66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T07:02:10.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-16T23:06:50.000Z", "max_forks_repo_path": "src/benchmark_views.hpp", "max_forks_repo_name": "breznak/xtensor-benchmark", "max_forks_repo_head_hexsha": "1a4afb5ca75a4119c09a4063975c5bc5aa1d8e66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-12-11T05:51:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-19T19:41:16.000Z", "avg_line_length": 31.1491712707, "max_line_length": 125, "alphanum_fraction": 0.608371763, "num_tokens": 1591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.520450314721355}}
{"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_IS_EVEN_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_IS_EVEN_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-predicates\n    Function object implementing is_even capabilities\n\n    Returns @ref True or @ref False according x is even or not.\n\n    @par Semantic:\n\n    @code\n    auto r = is_even(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    auto r = to_int(x/2)*2 == x;\n    @endcode\n\n    @par Note:\n\n    A floating number is even if it is a  flint\n    and divided by two it is still a flint.\n\n    A flint is a 'floating integer' i.e. a floating number\n    representing an integer value\n\n    Be conscious that all sufficiently great floating points values are even...\n\n    @see is_odd, is_flint\n\n  **/\n  as_logical_t<Value> is_even(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/is_even.hpp>\n#include <boost/simd/function/simd/is_even.hpp>\n\n#endif\n", "meta": {"hexsha": "1062a99ec3003441199532d388770fa3318e3020", "size": 1337, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/is_even.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/is_even.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/is_even.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": 23.0517241379, "max_line_length": 100, "alphanum_fraction": 0.5991024682, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5204503124476301}}
{"text": "#include <vector>\n\n#include <aslam/common/entrypoint.h>\n#include <Eigen/Core>\n\n#include \"aslam/common/descriptor-utils.h\"\n\nnamespace aslam {\nnamespace common {\nnamespace descriptor_utils {\n\nTEST(ViwlsGraph, DescriptorMedianTestSingleDescriptor) {\n  DescriptorsType descriptors(48, 1);\n  descriptors.setRandom();\n  DescriptorType median;\n\n  descriptorMeanRoundedToBinaryValue(descriptors, &median);\n  EXPECT_EQ(descriptors, median);\n}\n\nTEST(ViwlsGraph, DescriptorMedianTestTwoZeroDescriptors) {\n  DescriptorType descriptor0(48, 1);\n  DescriptorType descriptor1(48, 1);\n  descriptor0.setZero();\n  descriptor1.setZero();\n  DescriptorType median;\n\n  DescriptorsType descriptors(48, 2);\n  descriptors.col(0) = descriptor0;\n  descriptors.col(1) = descriptor1;\n\n  descriptorMeanRoundedToBinaryValue(descriptors, &median);\n  EXPECT_EQ(descriptor0, median);\n}\n\nTEST(ViwlsGraph, DescriptorMedianTestThreeDescriptors) {\n  DescriptorsType descriptors(48, 3);\n  descriptors.setZero();\n\n  descriptors(0, 0) = 7;\n  descriptors(0, 1) = 3;\n  descriptors(0, 2) = 1;\n\n  DescriptorType median(48, 1);\n\n  descriptorMeanRoundedToBinaryValue(descriptors, &median);\n  // Median of {1, 1, 1}\n  EXPECT_TRUE(getBit(0, median));\n  // Median of {1, 1, 0}\n  EXPECT_TRUE(getBit(1, median));\n  // Median of {1, 0, 0}\n  EXPECT_FALSE(getBit(2, median));\n  // Median of {0, 0, 0}\n  EXPECT_FALSE(getBit(3, median));\n}\n\nTEST(ViwlsGraph, DescriptorMedianAbsDeviationTest) {\n  DescriptorsType descriptors(48, 3);\n  descriptors.setZero();\n\n  descriptors(0, 0) = 7;\n  descriptors(0, 1) = 3;\n  descriptors(0, 2) = 1;\n\n  EXPECT_EQ(descriptorMeanAbsoluteDeviation(descriptors),\n            2.0 / 3.0);\n}\n\nTEST(ViwlsGraph, DescriptorMeanTestThreeDescriptors) {\n  DescriptorsType descriptors(48, 3);\n  descriptors.setZero();\n\n  descriptors(0, 0) = 7;\n  descriptors(0, 1) = 3;\n  descriptors(0, 2) = 1;\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> mean(48 * kBitsPerByte, 1);\n\n  floatDescriptorMean(descriptors, &mean);\n  // Mean of {1, 1, 1}\n  EXPECT_DOUBLE_EQ(1.0, mean(0));\n  // Mean of {1, 1, 0}\n  EXPECT_DOUBLE_EQ(2.0 / 3.0, mean(1));\n  // Mean of {1, 0, 0}\n  EXPECT_DOUBLE_EQ(1.0 / 3.0, mean(2));\n  // Mean of {0, 0, 0}\n  EXPECT_DOUBLE_EQ(0.0, mean(3));\n}\n\nTEST(ViwlsGraph, DescriptorMeanStdDeviationTest) {\n  DescriptorsType descriptors(48, 3);\n  descriptors.setZero();\n\n  descriptors(0, 0) = 7;\n  descriptors(0, 1) = 3;\n  descriptors(0, 2) = 1;\n\n  EXPECT_DOUBLE_EQ(descriptorMeanStandardDeviation(descriptors),\n                   2.0 / 3.0);\n}\n\nTEST(ViwlsGraph, DescriptorMeanStdDeviationTestZeroDescriptors) {\n  DescriptorsType descriptors(48, 1);\n  EXPECT_DOUBLE_EQ(descriptorMeanStandardDeviation(descriptors),\n                   0.0);\n}\n\nTEST(ViwlsGraph, DescriptorMeanStdDeviationTestOneDescriptor) {\n  DescriptorsType descriptors(48, 1);\n  descriptors.setRandom();\n  EXPECT_DOUBLE_EQ(descriptorMeanStandardDeviation(descriptors),\n                   0.0);\n}\n\nTEST(ViwlsGraph, DescriptorMeanStdDeviationTestSameDescriptors) {\n  DescriptorsType descriptors(48, 3);\n  descriptors.setZero();\n\n  descriptors(0, 0) = 56;\n  descriptors(0, 1) = 56;\n  descriptors(0, 2) = 56;\n\n  EXPECT_DOUBLE_EQ(descriptorMeanStandardDeviation(descriptors),\n                   0.0);\n}\n\nTEST(ViwlsGraph, DescriptorClosestToMedianTestZeroDescriptors) {\n  DescriptorsType descriptors(48, 0);\n  descriptors.setZero();\n\n  size_t closest_to_median_descriptor_index = 0u;\n  EXPECT_DEATH(\n      getIndexOfDescriptorClosestToMedian(\n          descriptors, &closest_to_median_descriptor_index), \"\");\n}\n\nTEST(ViwlsGraph, DescriptorClosestToMedianTestOneDescriptors) {\n  DescriptorsType descriptors(48, 1);\n  descriptors.setZero();\n\n  descriptors(0, 0) = 7;\n\n  size_t closest_to_median_descriptor_index = 0u;\n  getIndexOfDescriptorClosestToMedian(\n      descriptors, &closest_to_median_descriptor_index);\n\n  EXPECT_EQ(0u, closest_to_median_descriptor_index);\n}\n\n\nTEST(ViwlsGraph, DescriptorClosestToMedianTestThreeDescriptors) {\n  DescriptorsType descriptors(48, 3);\n  descriptors.setZero();\n\n  descriptors(0, 0) = 7;\n  descriptors(0, 1) = 3;\n  descriptors(0, 2) = 1;\n\n  size_t closest_to_median_descriptor_index = 0u;\n  getIndexOfDescriptorClosestToMedian(\n      descriptors, &closest_to_median_descriptor_index);\n\n  EXPECT_EQ(1u, closest_to_median_descriptor_index);\n\n  descriptors(0, 1) = 255;\n\n  getIndexOfDescriptorClosestToMedian(\n      descriptors, &closest_to_median_descriptor_index);\n\n  EXPECT_EQ(0u, closest_to_median_descriptor_index);\n\n  descriptors(0, 2) = 127;\n\n  getIndexOfDescriptorClosestToMedian(\n      descriptors, &closest_to_median_descriptor_index);\n\n  EXPECT_EQ(2u, closest_to_median_descriptor_index);\n}\n\n}  // namespace descriptor_utils\n}  // namespace common\n}  // namespace aslam\n\nASLAM_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "e57b47b3417b0a65194fc8d9840f63064e99b4cd", "size": 4762, "ext": "cc", "lang": "C++", "max_stars_repo_path": "aslam_cv_common/test/test-descriptor-utils.cc", "max_stars_repo_name": "shuhannod/aslam_cv2", "max_stars_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 173.0, "max_stars_repo_stars_event_min_datetime": "2017-09-19T18:14:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T09:11:15.000Z", "max_issues_repo_path": "aslam_cv_common/test/test-descriptor-utils.cc", "max_issues_repo_name": "shuhannod/aslam_cv2", "max_issues_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2017-11-16T12:46:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T04:38:41.000Z", "max_forks_repo_path": "aslam_cv_common/test/test-descriptor-utils.cc", "max_forks_repo_name": "shuhannod/aslam_cv2", "max_forks_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 58.0, "max_forks_repo_forks_event_min_datetime": "2017-10-24T17:31:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T03:23:24.000Z", "avg_line_length": 25.7405405405, "max_line_length": 70, "alphanum_fraction": 0.7309953801, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5204503097452151}}
{"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 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}\n  return 0;\n}\n", "meta": {"hexsha": "aef50e9c173175c6f7e687c5c4b979724b6b3db1", "size": 940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_Matrix_resize_int_int.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_Matrix_resize_int_int.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_Matrix_resize_int_int.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": 28.4848484848, "max_line_length": 224, "alphanum_fraction": 0.6659574468, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.5204503097452151}}
{"text": "#include \"scope.h\"\n\n#include \"math_lib/transpose.h\"\n\n#include <boost/qvm/map_mat_mat.hpp>\n#include <boost/qvm/map_mat_vec.hpp>\n#include <boost/qvm/map_vec_mat.hpp>\n#include <boost/qvm/vec_operations.hpp>\n\nnamespace pagoda\n{\nScope::Scope() : m_position{0, 0, 0}, m_size{0, 0, 0}, m_rotation(boost::qvm::diag_mat(Vec3F{1, 1, 1})) {}\n\nScope::Scope(const Vec3F &pos, const Vec3F &size, const Mat3x3F &rot) : m_position(pos), m_size(size), m_rotation(rot)\n{\n}\n\nScope::Scope(const std::array<Vec3F, 8> &boxPoints)\n{\n\tauto origin = boxPoints[static_cast<int>(BoxPoints::LowerBottomLeft)];\n\tauto lbr = boxPoints[static_cast<int>(BoxPoints::LowerBottomRight)];\n\tauto ltl = boxPoints[static_cast<int>(BoxPoints::LowerTopLeft)];\n\tauto hbl = boxPoints[static_cast<int>(BoxPoints::HigherBottomLeft)];\n\tauto xAxis = lbr - origin;\n\tauto yAxis = ltl - origin;\n\tauto zAxis = boost::qvm::cross(xAxis, yAxis);\n\n\tm_position = origin;\n\tm_size = Vec3F{boost::qvm::mag(xAxis), boost::qvm::mag(yAxis), boost::qvm::mag(origin - hbl)};\n\tboost::qvm::col<0>(m_rotation) = boost::qvm::normalized(xAxis);\n\tboost::qvm::col<1>(m_rotation) = boost::qvm::normalized(yAxis);\n\tboost::qvm::col<2>(m_rotation) = boost::qvm::normalized(zAxis);\n}\n\nVec3F Scope::GetPosition() const { return m_position; }\n\nvoid Scope::SetPosition(const Vec3F &pos) { m_position = pos; }\n\nVec3F Scope::GetSize() const { return m_size; }\n\nvoid Scope::SetSize(const Vec3F &size) { m_size = size; }\n\nMat3x3F Scope::GetRotation() const { return m_rotation; }\n\nvoid Scope::SetRotation(const Mat3x3F &rotation) { m_rotation = rotation; }\n\nMat3x3F Scope::GetInverseRotation() const { return boost::qvm::transposed(m_rotation); }\n\nVec3F Scope::GetXAxis() const { return boost::qvm::col<0>(m_rotation); }\nVec3F Scope::GetYAxis() const { return boost::qvm::col<1>(m_rotation); }\nVec3F Scope::GetZAxis() const { return boost::qvm::col<2>(m_rotation); }\n\nVec3F Scope::GetAxis(const std::string &axisName) const\n{\n\tif (axisName == \"x\")\n\t{\n\t\treturn GetXAxis();\n\t}\n\telse if (axisName == \"y\")\n\t{\n\t\treturn GetYAxis();\n\t}\n\tCRITICAL_ASSERT_MSG(axisName == \"z\", \"Axis name must be one of x, y or z.\");\n\treturn GetZAxis();\n}\n\nVec3F Scope::GetAxis(char axisName) const\n{\n\tswitch (axisName)\n\t{\n\t\tcase 'x':\n\t\t\treturn GetXAxis();\n\t\tcase 'y':\n\t\t\treturn GetYAxis();\n\t\tcase 'z':\n\t\t\treturn GetZAxis();\n\t\tdefault:\n\t\t\tCRITICAL_ASSERT_MSG(false, \"Axis must be one of x, y or z.\");\n\t}\n\treturn Vec3F();\n}\n\nPlane<float> Scope::GetXYPlane() const { return Plane<float>::FromPointAndNormal(m_position, GetZAxis()); }\nPlane<float> Scope::GetXZPlane() const { return Plane<float>::FromPointAndNormal(m_position, GetYAxis()); }\nPlane<float> Scope::GetYZPlane() const { return Plane<float>::FromPointAndNormal(m_position, GetXAxis()); }\n\nVec3F Scope::LocalPointInWorld(const Vec3F &localPoint) const\n{\n\treturn m_position + GetXAxis() * X(localPoint) + GetYAxis() * Y(localPoint) + GetZAxis() * Z(localPoint);\n}\n\nVec3F Scope::GetLocalPoint(const BoxPoints &p) const\n{\n\tuint32_t index = static_cast<uint32_t>(p);\n\tVec3F localPoint;\n\tX(localPoint) = ((index & (1 << 0)) != 0 ? X(m_size) : 0);\n\tY(localPoint) = ((index & (1 << 1)) != 0 ? Y(m_size) : 0);\n\tZ(localPoint) = ((index & (1 << 2)) != 0 ? Z(m_size) : 0);\n\treturn localPoint;\n}\n\nVec3F Scope::GetWorldPoint(const BoxPoints &p) const { return LocalPointInWorld(GetLocalPoint(p)); }\n\nstd::array<Vec3F, 8> Scope::GetWorldPoints() const\n{\n\tstd::array<Vec3F, 8> boxPoints;\n\tfor (int i = 0; i < 8; ++i)\n\t{\n\t\tboxPoints[i] = GetWorldPoint(static_cast<BoxPoints>(i));\n\t}\n\treturn boxPoints;\n}\n\nVec3F Scope::GetLocalVector(const Vec3F &worldVector) const\n{\n\treturn Vec3F{boost::qvm::dot(GetXAxis(), worldVector), boost::qvm::dot(GetYAxis(), worldVector),\n\t             boost::qvm::dot(GetZAxis(), worldVector)};\n}\n\nVec3F Scope::GetWorldVector(const Vec3F &localVector) const\n{\n\treturn GetXAxis() * X(localVector) + GetYAxis() * Y(localVector) + GetZAxis() * Z(localVector);\n}\n\nVec3F Scope::GetCenterPointInWorld() const { return LocalPointInWorld(GetCenterPointInLocal()); }\n\nVec3F Scope::GetCenterPointInLocal() const\n{\n\treturn 0.5f * (GetLocalPoint(BoxPoints::LowerBottomLeft) + GetLocalPoint(BoxPoints::HigherTopRight));\n}\n}  // namespace pagoda\n", "meta": {"hexsha": "b4019eade5c7a04b5b9f1c0cc511051b2b092bb4", "size": 4191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/geometry_core/scope.cpp", "max_stars_repo_name": "diegoarjz/selector", "max_stars_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T17:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-12T14:37:27.000Z", "max_issues_repo_path": "source/geometry_core/scope.cpp", "max_issues_repo_name": "diegoarjz/selector", "max_issues_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47.0, "max_issues_repo_issues_event_min_datetime": "2019-05-27T15:24:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T17:54:54.000Z", "max_forks_repo_path": "source/geometry_core/scope.cpp", "max_forks_repo_name": "diegoarjz/selector", "max_forks_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_forks_repo_licenses": ["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.75, "max_line_length": 118, "alphanum_fraction": 0.6993557623, "num_tokens": 1294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5203987685962617}}
{"text": "/******************************************************************************\n * Author:   Laurent Kneip                                                    *\n * Contact:  kneip.laurent@gmail.com                                          *\n * License:  Copyright (c) 2013 Laurent Kneip, ANU. 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 * * 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 ANU nor the names of its contributors may be         *\n *   used to endorse or promote products derived from this software without   *\n *   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 ANU OR THE 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         *\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 OPENGV_RELATIVE_POSE_MODULES_MAIN_HPP_\n#define OPENGV_RELATIVE_POSE_MODULES_MAIN_HPP_\n\n#include <stdlib.h>\n#include <Eigen/Eigen>\n#include <Eigen/src/Core/util/DisableStupidWarnings.h>\n#include <opengv/types.hpp>\n\nnamespace opengv\n{\nnamespace relative_pose\n{\nnamespace modules\n{\nrotation_t sixpt_urban_main_onlyRot(\n\t\tconst bearingVectors_t& f1,\n\t\tconst bearingVectors_t& f2);\ntransformation_t sixpt_urban_main(\n\tconst bearingVectors_t& f1,\n\tconst bearingVectors_t& f2);\nvoid fivept_stewenius_main(\n    const Eigen::Matrix<double,9,4> & EE,\n    complexEssentials_t & complexEssentials );\nvoid fivept_nister_main(\n    const Eigen::Matrix<double,9,4> & EE,\n    essentials_t & essentials );\nvoid fivept_kneip_main(\n    const Eigen::Matrix<double,3,5> & f1,\n    const Eigen::Matrix<double,3,5> & f2,\n    rotations_t & rotations );\nvoid eigensolver_main(\n    const Eigen::Matrix3d & xxF,\n    const Eigen::Matrix3d & yyF,\n    const Eigen::Matrix3d & zzF,\n    const Eigen::Matrix3d & xyF,\n    const Eigen::Matrix3d & yzF,\n    const Eigen::Matrix3d & zxF,\n    eigensolverOutput_t & output );\nvoid sixpt_main(\n    Eigen::Matrix<double,6,6> & L1,\n    Eigen::Matrix<double,6,6> & L2,\n    rotations_t & solutions);\nvoid sixpt_ventura_main(\n\tconst Eigen::Matrix<double, 6, 6> &w1,\n\tconst Eigen::Matrix<double, 6, 6> &w2,\n\tconst Eigen::Matrix<double, 6, 6> &w3,\n\tconst Eigen::Matrix<double, 6, 6> &w4,\n\tconst Eigen::Matrix<double, 6, 6> &w5,\n\tconst Eigen::Matrix<double, 6, 6> &w6,\n\tstd::vector<Eigen::Vector3d> &rsolns);\nvoid ge_main(\n    const Eigen::Matrix3d & xxF,\n    const Eigen::Matrix3d & yyF,\n    const Eigen::Matrix3d & zzF,\n    const Eigen::Matrix3d & xyF,\n    const Eigen::Matrix3d & yzF,\n    const Eigen::Matrix3d & zxF,\n    const Eigen::Matrix<double,3,9> & x1P,\n    const Eigen::Matrix<double,3,9> & y1P,\n    const Eigen::Matrix<double,3,9> & z1P,\n    const Eigen::Matrix<double,3,9> & x2P,\n    const Eigen::Matrix<double,3,9> & y2P,\n    const Eigen::Matrix<double,3,9> & z2P,\n    const Eigen::Matrix<double,9,9> & m11P,\n    const Eigen::Matrix<double,9,9> & m12P,\n    const Eigen::Matrix<double,9,9> & m22P,\n    const cayley_t & startingPoint,\n    geOutput_t & output );\nvoid ge_main2(\n    const Eigen::Matrix3d & xxF,\n    const Eigen::Matrix3d & yyF,\n    const Eigen::Matrix3d & zzF,\n    const Eigen::Matrix3d & xyF,\n    const Eigen::Matrix3d & yzF,\n    const Eigen::Matrix3d & zxF,\n    const Eigen::Matrix<double,3,9> & x1P,\n    const Eigen::Matrix<double,3,9> & y1P,\n    const Eigen::Matrix<double,3,9> & z1P,\n    const Eigen::Matrix<double,3,9> & x2P,\n    const Eigen::Matrix<double,3,9> & y2P,\n    const Eigen::Matrix<double,3,9> & z2P,\n    const Eigen::Matrix<double,9,9> & m11P,\n    const Eigen::Matrix<double,9,9> & m12P,\n    const Eigen::Matrix<double,9,9> & m22P,\n    const cayley_t & startingPoint,\n    geOutput_t & output );\nvoid ge_plot(\n    const Eigen::Matrix3d & xxF,\n    const Eigen::Matrix3d & yyF,\n    const Eigen::Matrix3d & zzF,\n    const Eigen::Matrix3d & xyF,\n    const Eigen::Matrix3d & yzF,\n    const Eigen::Matrix3d & zxF,\n    const Eigen::Matrix<double,3,9> & x1P,\n    const Eigen::Matrix<double,3,9> & y1P,\n    const Eigen::Matrix<double,3,9> & z1P,\n    const Eigen::Matrix<double,3,9> & x2P,\n    const Eigen::Matrix<double,3,9> & y2P,\n    const Eigen::Matrix<double,3,9> & z2P,\n    const Eigen::Matrix<double,9,9> & m11P,\n    const Eigen::Matrix<double,9,9> & m12P,\n    const Eigen::Matrix<double,9,9> & m22P,\n    geOutput_t & output );\n}\n}\n}\n\n#endif /* OPENGV_RELATIVE_POSE_MODULES_MAIN_HPP_ */\n\n\n", "meta": {"hexsha": "471d351dbb6bfb1e5c5c038a66034e3ef76d284a", "size": 5860, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/opengv/relative_pose/modules/main.hpp", "max_stars_repo_name": "Byson-source/opengv", "max_stars_repo_head_hexsha": "a87af73cc5896417fec9e013feef2fa2d9891e8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2016-10-13T15:49:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T05:29:45.000Z", "max_issues_repo_path": "include/opengv/relative_pose/modules/main.hpp", "max_issues_repo_name": "Byson-source/opengv", "max_issues_repo_head_hexsha": "a87af73cc5896417fec9e013feef2fa2d9891e8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-09-01T08:45:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-17T02:05:13.000Z", "max_forks_repo_path": "include/opengv/relative_pose/modules/main.hpp", "max_forks_repo_name": "Byson-source/opengv", "max_forks_repo_head_hexsha": "a87af73cc5896417fec9e013feef2fa2d9891e8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-08-31T23:22:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T05:29:48.000Z", "avg_line_length": 41.2676056338, "max_line_length": 80, "alphanum_fraction": 0.6194539249, "num_tokens": 1543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757312, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5203987659774436}}
{"text": "#include <limits>\n#include <random>\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <rsvd/Constants.hpp>\n#include <rsvd/RandomizedRangeFinder.hpp>\n\nusing Eigen::Index;\nusing Rsvd::LuConditioner;\nusing Rsvd::MgsConditioner;\nusing Rsvd::NoConditioner;\nusing Rsvd::QrConditioner;\nusing Rsvd::Internal::RandomizedSubspaceIterations;\nusing Rsvd::Internal::singleShot;\n\n// Note: Tolerances for the range approximation (tests \"{SingleShot, NoConditioner, LuConditioner,\n// MgsConditioner, QrConditioner}Approximation\") were chosen after several runs with different PRNG\n// seeds (444, 555, 666, 777).\n\ntemplate <typename T> struct RandomizedRangeFinder : public ::testing::Test {\n  using MatrixType = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n  using RealType = typename Eigen::NumTraits<T>::Real;\n\n  const Index numRows = 50;\n  const Index numCols = 25;\n  const Index dim = 15;\n  // The oversampling additional to the rank is important to test for correct deflation, especially\n  // for the MGS conditioner\n  const Index oversampling = 5;\n  const unsigned int numIter = 2;\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(RandomizedRangeFinder, NumericalTypes, );\n\n// \\brief Range approximation must have columns of unit length\nTYPED_TEST(RandomizedRangeFinder, SingleShotNorm) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q = singleShot<MatrixType, std::mt19937_64>(\n      a, TestFixture::dim + TestFixture::oversampling, randomEngine);\n\n  for (Index i = 0; i < TestFixture::dim; ++i) {\n    ASSERT_NEAR(q.col(i).norm(), 1, 2 * TestFixture::macheps);\n  }\n}\n\n// \\brief Range approximation must have orthogonal columns\nTYPED_TEST(RandomizedRangeFinder, SingleShotOrthogonality) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q = singleShot<MatrixType, std::mt19937_64>(\n      a, TestFixture::dim + TestFixture::oversampling, randomEngine);\n\n  for (Index i = 0; i < TestFixture::dim; ++i) {\n    for (Index j = 0; j < i; ++j) {\n      const auto res = std::abs(q.col(i).dot(q.col(j)));\n      ASSERT_NEAR(res, 0, 2 * TestFixture::macheps);\n    }\n  }\n}\n\n// \\brief Range approximation must satisfy the requirement | A - Q Q* A | < eps\nTYPED_TEST(RandomizedRangeFinder, SingleShotApproximation) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q = singleShot<MatrixType, std::mt19937_64>(\n      a, TestFixture::dim + TestFixture::oversampling, randomEngine);\n  const MatrixType res = a - q * (q.adjoint() * a);\n  ASSERT_NEAR(res.norm(), 0, 2e3 * TestFixture::macheps);\n}\n\n// \\brief Range approximation must have columns of unit length\nTYPED_TEST(RandomizedRangeFinder, NoConditionerNorm) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q =\n      RandomizedSubspaceIterations<MatrixType, std::mt19937_64, NoConditioner>::compute(\n          a, TestFixture::dim + TestFixture::oversampling, TestFixture::numIter, randomEngine);\n\n  for (Index i = 0; i < TestFixture::dim; ++i) {\n    ASSERT_NEAR(q.col(i).norm(), 1, 2 * TestFixture::macheps);\n  }\n}\n\n// \\brief Range approximation must have orthogonal columns\nTYPED_TEST(RandomizedRangeFinder, NoConditionerOrthogonality) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q =\n      RandomizedSubspaceIterations<MatrixType, std::mt19937_64, NoConditioner>::compute(\n          a, TestFixture::dim + TestFixture::oversampling, TestFixture::numIter, randomEngine);\n\n  for (Index i = 0; i < TestFixture::dim; ++i) {\n    for (Index j = 0; j < i; ++j) {\n      const auto res = std::abs(q.col(i).dot(q.col(j)));\n      ASSERT_NEAR(res, 0, 2 * TestFixture::macheps);\n    }\n  }\n}\n\n// \\brief Range approximation must satisfy the requirement | A - Q Q* A | < eps\nTYPED_TEST(RandomizedRangeFinder, NoConditionerApproximation) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q =\n      RandomizedSubspaceIterations<MatrixType, std::mt19937_64, NoConditioner>::compute(\n          a, TestFixture::dim + TestFixture::oversampling, TestFixture::numIter, randomEngine);\n  const MatrixType res = a - q * (q.adjoint() * a);\n  ASSERT_NEAR(res.norm(), 0, 1e6 * TestFixture::macheps);\n}\n\n// \\brief Range approximation must have columns of unit length\nTYPED_TEST(RandomizedRangeFinder, LuConditionerNorm) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q =\n      RandomizedSubspaceIterations<MatrixType, std::mt19937_64, LuConditioner>::compute(\n          a, TestFixture::dim + TestFixture::oversampling, TestFixture::numIter, randomEngine);\n\n  for (Index i = 0; i < TestFixture::dim; ++i) {\n    ASSERT_NEAR(q.col(i).norm(), 1, 2 * TestFixture::macheps);\n  }\n}\n\n// \\brief Range approximation must have orthogonal columns\nTYPED_TEST(RandomizedRangeFinder, LuConditionerOrthogonality) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q =\n      RandomizedSubspaceIterations<MatrixType, std::mt19937_64, LuConditioner>::compute(\n          a, TestFixture::dim + TestFixture::oversampling, TestFixture::numIter, randomEngine);\n\n  for (Index i = 0; i < TestFixture::dim; ++i) {\n    for (Index j = 0; j < i; ++j) {\n      const auto res = std::abs(q.col(i).dot(q.col(j)));\n      ASSERT_NEAR(res, 0, 2 * TestFixture::macheps);\n    }\n  }\n}\n\n// \\brief Range approximation must satisfy the requirement | A - Q Q* A | < eps\nTYPED_TEST(RandomizedRangeFinder, LuConditionerApproximation) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q =\n      RandomizedSubspaceIterations<MatrixType, std::mt19937_64, LuConditioner>::compute(\n          a, TestFixture::dim + TestFixture::oversampling, TestFixture::numIter, randomEngine);\n  const MatrixType res = a - q * (q.adjoint() * a);\n  ASSERT_NEAR(res.norm(), 0, 4e2 * TestFixture::macheps);\n}\n\n// \\brief Range approximation must have columns of unit length\nTYPED_TEST(RandomizedRangeFinder, MgsConditionerNorm) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q =\n      RandomizedSubspaceIterations<MatrixType, std::mt19937_64, MgsConditioner>::compute(\n          a, TestFixture::dim + TestFixture::oversampling, TestFixture::numIter, randomEngine);\n\n  for (Index i = 0; i < TestFixture::dim; ++i) {\n    ASSERT_NEAR(q.col(i).norm(), 1, 2 * TestFixture::macheps);\n  }\n}\n\n// \\brief Range approximation must have orthogonal columns\nTYPED_TEST(RandomizedRangeFinder, MgsConditionerOrthogonality) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q =\n      RandomizedSubspaceIterations<MatrixType, std::mt19937_64, MgsConditioner>::compute(\n          a, TestFixture::dim + TestFixture::oversampling, TestFixture::numIter, randomEngine);\n\n  for (Index i = 0; i < TestFixture::dim; ++i) {\n    for (Index j = 0; j < i; ++j) {\n      const auto res = std::abs(q.col(i).dot(q.col(j)));\n      ASSERT_NEAR(res, 0, 2 * TestFixture::macheps);\n    }\n  }\n}\n\n// \\brief Range approximation must satisfy the requirement | A - Q Q* A | < eps\nTYPED_TEST(RandomizedRangeFinder, MgsConditionerApproximation) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q =\n      RandomizedSubspaceIterations<MatrixType, std::mt19937_64, MgsConditioner>::compute(\n          a, TestFixture::dim + TestFixture::oversampling, TestFixture::numIter, randomEngine);\n  const MatrixType res = a - q * (q.adjoint() * a);\n  ASSERT_NEAR(res.norm(), 0, 3e2 * TestFixture::macheps);\n}\n\n// \\brief Range approximation must have columns of unit length\nTYPED_TEST(RandomizedRangeFinder, QrConditionerNorm) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q =\n      RandomizedSubspaceIterations<MatrixType, std::mt19937_64, QrConditioner>::compute(\n          a, TestFixture::dim + TestFixture::oversampling, TestFixture::numIter, randomEngine);\n\n  for (Index i = 0; i < TestFixture::dim; ++i) {\n    ASSERT_NEAR(q.col(i).norm(), 1, 2 * TestFixture::macheps);\n  }\n}\n\n// \\brief Range approximation must have orthogonal columns\nTYPED_TEST(RandomizedRangeFinder, QrConditionerOrthogonality) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q =\n      RandomizedSubspaceIterations<MatrixType, std::mt19937_64, QrConditioner>::compute(\n          a, TestFixture::dim + TestFixture::oversampling, TestFixture::numIter, randomEngine);\n\n  for (Index i = 0; i < TestFixture::dim; ++i) {\n    for (Index j = 0; j < i; ++j) {\n      const auto res = std::abs(q.col(i).dot(q.col(j)));\n      ASSERT_NEAR(res, 0, 2 * TestFixture::macheps);\n    }\n  }\n}\n\n// \\brief Range approximation must satisfy the requirement | A - Q Q* A | < eps\nTYPED_TEST(RandomizedRangeFinder, QrConditionerApproximation) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n\n  // Create a matrix with rank loss\n  const MatrixType a = MatrixType::Random(TestFixture::numRows, TestFixture::dim) *\n                       MatrixType::Random(TestFixture::dim, TestFixture::numCols);\n  // Compute the randomized range approximation\n  const MatrixType q =\n      RandomizedSubspaceIterations<MatrixType, std::mt19937_64, QrConditioner>::compute(\n          a, TestFixture::dim + TestFixture::oversampling, TestFixture::numIter, randomEngine);\n  const MatrixType res = a - q * (q.adjoint() * a);\n  ASSERT_NEAR(res.norm(), 0, 3e2 * TestFixture::macheps);\n}\n", "meta": {"hexsha": "0579da5b84fef6a51a090a6b3733ce36f6067a0b", "size": 14700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/RandomizedRangeFinder.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/RandomizedRangeFinder.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/RandomizedRangeFinder.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": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.061452514, "max_line_length": 99, "alphanum_fraction": 0.7171428571, "num_tokens": 3878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5203671406433673}}
{"text": "// Copyright (C) 2008  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <dlib/optimization/find_optimal_parameters.h>\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.find_optimal_parameters\");\n\n// ----------------------------------------------------------------------------------------\n\n\n    class find_optimal_parameters : public tester\n    {\n    public:\n        find_optimal_parameters (\n        ) :\n            tester (\"test_find_optimal_parameters\",\n                    \"Runs tests on find_optimal_parameters().\")\n        {}\n\n        void perform_test (\n        )\n        {\n            print_spinner();\n            matrix<double,0,1> params = {0.5, 0.5};\n            dlib::find_optimal_parameters(4, 0.001, 100, params, {-0.1, -0.01}, {5, 5}, [](const matrix<double,0,1>& params) {\n                cout << \".\";\n                return sum(squared(params));\n            });\n\n            matrix<double,0,1> true_params = {0,0};\n\n            DLIB_TEST(max(abs(true_params - params)) < 1e-10);\n\n            params = {0.1};\n            dlib::find_optimal_parameters(4, 0.001, 100, params, {-0.01}, {5}, [](const matrix<double,0,1>& params) {\n                cout << \".\";\n                return sum(squared(params));\n            });\n\n            true_params = {0};\n            DLIB_TEST(max(abs(true_params - params)) < 1e-10);\n        }\n    } a;\n\n}\n\n\n\n", "meta": {"hexsha": "9f2f5b348e95e534a31739113a548c364725891e", "size": 1507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/find_optimal_parameters.cpp", "max_stars_repo_name": "yatonon/dlib-face", "max_stars_repo_head_hexsha": "0230c1034ee65d0846d007e6145bfe73ca0d6321", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "dlib/test/find_optimal_parameters.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "dlib/test/find_optimal_parameters.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 25.5423728814, "max_line_length": 126, "alphanum_fraction": 0.502986065, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5203671358250725}}
{"text": "#include <algorithm>\n#include <boost/functional/hash.hpp>\n#include <iostream>\n#include <sstream>\n#include <unordered_map>\n#include <vector>\n\nsize_t checksum(const std::vector<int>& nums) {\n    size_t seed = 0;\n    for (auto n : nums) {\n        boost::hash_combine(seed, n);\n    }\n    return seed;\n}\n\n\nint main() {\n    std::vector<int> nums;\n    {\n        std::string line;\n        std::getline(std::cin, line);\n        std::stringstream ss{line};\n        while (!ss.eof()) {\n            int x;\n            ss >> x;\n            nums.push_back(x);\n        }\n    }\n\n    std::unordered_map<size_t, int> hashes;\n    hashes.insert(std::make_pair(checksum(nums), 0));\n\n    int steps = 0;\n    for(;;) {\n        auto it = std::max_element(std::begin(nums), std::end(nums));\n        if (it == std::end(nums)) {\n            std::cerr << \"NO MAX!\\n\";\n            exit(1);\n        }\n        int val = 0;\n        std::swap(val, *it);\n        for(++it; val > 0; ++it, --val) {\n            if (it == std::end(nums)) {\n                it = std::begin(nums);\n            }\n            (*it)++;\n        }\n        ++steps;\n        auto ii = hashes.insert(std::make_pair(checksum(nums), steps));\n        if (!ii.second) {\n            std::cout << \"last loop: \" << steps-ii.first->second << \"\\n\";\n            break;\n        }\n    }\n}\n", "meta": {"hexsha": "9a8b328ad180de04525446a6742054d1d0fb952c", "size": 1312, "ext": "cc", "lang": "C++", "max_stars_repo_path": "puzzle_06_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_06_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_06_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.4285714286, "max_line_length": 73, "alphanum_fraction": 0.474847561, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5203671358250724}}
{"text": "//\n#include <CGAL/Surface_mesh_segmentation/internal/K_means_clustering.h>\n\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n/**\n * Generates sample points using a few gauissians.\n * Then applies k-means on these generated points.\n * Provides a heuristic score for each k-means clustering result.\n *\n * EXIT_FAILURE does not mean failure but if approximate matching is too low it is best to check\n */\nint main(void)\n{\n    boost::mt19937 engine;\n    engine.seed(1340818006);\n\n    // generate random data using gauissians below\n    std::vector< boost::normal_distribution<double> > distributions;\n    distributions.push_back(boost::normal_distribution<double>(0.1, 0.05));\n    distributions.push_back(boost::normal_distribution<double>(0.4, 0.1));\n    distributions.push_back(boost::normal_distribution<double>(0.55, 0.05));\n    distributions.push_back(boost::normal_distribution<double>(0.7, 0.1));\n    distributions.push_back(boost::normal_distribution<double>(0.9, 0.05));\n    distributions.push_back(boost::normal_distribution<double>(1.0, 0.05));\n\n    std::vector<double> data;\n    for(std::vector< boost::normal_distribution<double> >::iterator it = distributions.begin();\n      it != distributions.end(); ++it)\n    {\n        boost::variate_generator<boost::mt19937&, boost::normal_distribution<double> > var_nor(engine, *it);\n\n        for(std::size_t i = 0; i < 300; ++i) { data.push_back(var_nor()); }\n    }\n\n    // calculate closest center (using above gauissians) for each generated points\n    // we will compare it with k-means results\n    std::vector<std::size_t> data_centers;\n    for(std::vector<double>::iterator it = data.begin(); it != data.end(); ++it)\n    {\n        std::size_t center_id = (std::numeric_limits<std::size_t>::max)(), center_counter = 0;;\n        double min_distance = (std::numeric_limits<double>::max)();\n        for(std::vector< boost::normal_distribution<double> >::iterator dis_it = distributions.begin();\n          dis_it != distributions.end(); ++dis_it, ++center_counter)\n        {\n            double distance = std::abs(*it - dis_it->mean());\n            if(min_distance > distance)\n            {\n                min_distance = distance;\n                center_id = center_counter;\n            }\n        }\n        data_centers.push_back(center_id);\n    }\n\n    // apply k-means clustering\n    typedef CGAL::internal::K_means_clustering K_means;\n    std::vector<K_means> k_means;\n    k_means.push_back(K_means(distributions.size(), data, K_means::PLUS_INITIALIZATION));\n    k_means.push_back(K_means(distributions.size(), data, K_means::RANDOM_INITIALIZATION));\n\n    std::vector< std::vector<std::size_t> > calculated_centers(k_means.size());\n    std::vector< std::vector<std::size_t> >::iterator calc_centers_it = calculated_centers.begin();\n    for(std::vector<K_means>::iterator it = k_means.begin(); it != k_means.end(); ++it, ++calc_centers_it)\n    {\n        it->fill_with_center_ids(*calc_centers_it);\n    }\n\n    std::cout << \"Compare results of k-means with 'expected' (but be aware, it is not optimal result in terms of within-cluster error)\" << std::endl;\n    std::cout << \"Another words a clustering which has smaller within-cluster error can result in worse score in here\" << std::endl;\n    for(std::vector< std::vector<std::size_t> >::iterator calc_centers_it = calculated_centers.begin();\n        calc_centers_it != calculated_centers.end(); ++calc_centers_it)\n    {\n        std::size_t true_count = 0;\n        std::vector<std::size_t>::iterator calculated_it = calc_centers_it->begin();\n        for(std::vector<std::size_t>::iterator it = data_centers.begin(); it != data_centers.end(); ++it, ++calculated_it)\n        {\n            if( (*it) == (*calculated_it) ) { ++true_count; }\n        }\n        double app_fit = static_cast<double>(true_count) / data_centers.size();\n        std::cout << \"[0,1]: \" << app_fit << std::endl;\n        if(app_fit < 0.7) {\n            std::cerr << \"There might be a problem if above printed comparison is too low.\" << std::endl;\n            return EXIT_FAILURE;\n        }\n    }\n}\n", "meta": {"hexsha": "1dd60462646190d679c0842f215699c08b9d4888", "size": 4093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh_segmentation/test/Surface_mesh_segmentation/K_means_clustering_test.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_segmentation/test/Surface_mesh_segmentation/K_means_clustering_test.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_segmentation/test/Surface_mesh_segmentation/K_means_clustering_test.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": 46.5113636364, "max_line_length": 149, "alphanum_fraction": 0.6638162717, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5203289196541286}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#include <Eigen/Dense>\n\n#include <boost/numeric/odeint.hpp>\n#include <cbr_control/mpc/mpc_tracking.hpp>\n#include <matplot/matplot.h>\n\n#include <chrono>\n#include <vector>\n#include <algorithm>\n\n#include \"pendulum_problem.hpp\"\n\nusing namespace std::chrono_literals;\n\n\nint main(int argc, char const * argv[])\n{\n  using state_t = Eigen::Matrix<double, 2, 1>;  // [ theta, theta_dot ]\n  using input_t = Eigen::Matrix<double, 1, 1>;  // [ tau ]\n\n  //  -------------------------------------------------------------------------- /\n  //                              Simulation Params                              /\n  //  -------------------------------------------------------------------------- /\n\n  state_t x0 = (state_t() << cbr::deg2rad(5.), cbr::deg2rad(0.)).finished();\n  const auto dt = 10ms;\n  const auto tf = 5s;\n\n  auto xd = [](nanoseconds) {\n      return state_t(cbr::deg2rad(0.), 0);\n    };\n\n  //  -------------------------------------------------------------------------- /\n  //                                      MPC                                    /\n  //  -------------------------------------------------------------------------- /\n\n  NlOcpPendulum nlOcp{};\n\n  cbr::MPCTrackingParams params;\n  params.T = 5;\n  params.solver_params.osqp_settings.verbose = 0;\n\n  cbr::MPCTracking<NlOcpPendulum, 101> mpc(nlOcp, params);\n  mpc.set_xd(xd);\n\n  //  -------------------------------------------------------------------------- /\n  //                                RUN SIMULATION                               /\n  //  -------------------------------------------------------------------------- /\n\n  nanoseconds t(0);\n  state_t x = x0;\n\n  boost::numeric::odeint::euler<\n    state_t, double, state_t, double,\n    boost::numeric::odeint::vector_space_algebra\n  > stepper;\n\n  std::vector<double> sol_t;\n  std::vector<state_t, Eigen::aligned_allocator<state_t>> sol_x;\n  std::vector<input_t, Eigen::aligned_allocator<input_t>> sol_u;\n\n  while (t < tf) {\n    mpc.update_sync(t, x);\n    const auto u = mpc.get_u(t);\n\n    sol_t.push_back(duration_cast<duration<double>>(t).count());\n    sol_x.push_back(x);\n    sol_u.push_back(u);\n\n    stepper.do_step(\n      [&nlOcp, &u](const state_t & x, state_t & xdot, const double) {\n        xdot = nlOcp.get_f(x, u);\n      },\n      x,\n      duration_cast<duration<double>>(t).count(),\n      duration_cast<duration<double>>(dt).count()\n    );\n\n    t += dt;\n  }\n\n  //  -------------------------------------------------------------------------- /\n  //                                PLOT RESULTS                                 /\n  //  -------------------------------------------------------------------------- /\n\n  // helper function to extract stuff from solutions\n  auto ex_fn = [](const auto & item, auto ex_fn) {\n      std::vector<double> ret;\n      std::transform(item.cbegin(), item.cend(), std::back_inserter(ret), ex_fn);\n      return ret;\n    };\n\n  matplot::figure();\n  matplot::plot(sol_t, ex_fn(sol_x, [](auto s) {return s(0);}))->line_width(2);\n  matplot::title(\"theta\");\n  matplot::figure();\n  matplot::plot(sol_t, ex_fn(sol_x, [](auto s) {return s(1);}))->line_width(2);\n  matplot::title(\"dot theta\");\n  matplot::figure();\n  matplot::plot(sol_t, ex_fn(sol_u, [](auto s) {return s(0);}))->line_width(2);\n  matplot::title(\"input\");\n  matplot::show();\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "24ff8c2c6f3b843145946551e83da6bfd28b12f5", "size": 3426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/pendulum_main.cpp", "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_main.cpp", "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_main.cpp", "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": 31.1454545455, "max_line_length": 82, "alphanum_fraction": 0.4725627554, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5203289100982396}}
{"text": "#include \"storm/constants.hpp\"\n#include \"storm/rambo.hpp\"\n#include \"storm/simple.hpp\"\n#include \"storm/types.hpp\"\n#include <array>\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n#include <cmath>\n#include <cstddef>\n#include <functional>\n#include <locale>\n#include <stdexcept>\n#include <utility>\n\nnamespace storm {\n\n/**\n * Compute the partial width for a RH neutrino decaying into a active neutrino\n * and a Higgs.\n */\nauto SimpleRhNeutrino::width_vl_h() const -> double {\n  return ((-pow(kHIGGS_MASS, 2) + pow(p_mvr, 2)) * pow(p_theta, 2) *\n          std::abs(pow(kHIGGS_MASS, 2) - pow(p_mvr, 2))) /\n         (16. * p_mvr * M_PI * pow(kHIGGS_VEV, 2));\n}\n\n/**\n * Compute the partial width for a RH neutrino decaying into a active neutrino\n * and a Z.\n */\nauto SimpleRhNeutrino::width_vl_z() const -> double {\n\n  return (((pow(p_mvr, 4) + pow(p_mvr, 2) * pow(kZ_BOSON_MASS, 2) -\n            2 * pow(kZ_BOSON_MASS, 4)) *\n           kALPHA_EM * pow(p_theta, 2) *\n           std::abs(pow(p_mvr, 2) - pow(kZ_BOSON_MASS, 2))) /\n          (16.0 * pow(kCOS_THETA_WEAK, 2) * pow(p_mvr, 3) *\n           pow(kZ_BOSON_MASS, 2) * pow(kSIN_THETA_WEAK, 2)));\n}\n\n/**\n * Compute the partial width for a RH neutrino decaying into a charged lepton\n * and a W.\n */\nauto SimpleRhNeutrino::width_l_w() const -> double {\n  return (std::sqrt(\n              (p_ml - p_mvr - kW_BOSON_MASS) * (p_ml + p_mvr - kW_BOSON_MASS) *\n              (p_ml - p_mvr + kW_BOSON_MASS) * (p_ml + p_mvr + kW_BOSON_MASS)) *\n          (pow(pow(p_ml, 2) - pow(p_mvr, 2), 2) +\n           (pow(p_ml, 2) + pow(p_mvr, 2)) * pow(kW_BOSON_MASS, 2) -\n           2 * pow(kW_BOSON_MASS, 4)) *\n          kALPHA_EM * pow(p_theta, 2)) /\n         (16. * pow(p_mvr, 3) * pow(kW_BOSON_MASS, 2) *\n          pow(kSIN_THETA_WEAK, 2));\n}\n\n/**\n * Compute the integration bounds on the Mandelstam variable `s` for three-body\n * phase-space integration.\n * @param m Mass of the decaying particle.\n * @param m1 Mass of final state particle 1.\n * @param m2 Mass of final state particle 2.\n * @param m3 Mass of final state particle 3.\n */\ninline static auto compute_s_bounds(double m, double m1, double m2, double m3)\n    -> std::pair<double, double> {\n  return std::make_pair(pow(m2 + m3, 2), pow(m - m1, 2));\n}\n\n/**\n * @breif Compute the three body decay width given the squared matrix element\n * integrated over the Mandelstam variable `t`.\n * @param msqrd Squared matrix element integrated over t = (p1+p3)^2.\n * @param m Mass of the decaying particle.\n * @param fsp_masses Mass of the three final-state particles.\n * @param error Estimated error in the decay width.\n */\nstatic auto compute_width_3body(const std::function<double(double)> &msqrd,\n                                double m, std::array<double, 3> fsp_masses,\n                                double *error = nullptr) -> double {\n  using boost::math::quadrature::gauss_kronrod;\n\n  auto bounds =\n      compute_s_bounds(m, fsp_masses[0], fsp_masses[1], fsp_masses[2]);\n  auto integral = gauss_kronrod<double, 15>::integrate(\n      msqrd, bounds.first, bounds.second, 5, 1e-9, error);\n\n  const double pf = 1.0 / (256.0 * pow(M_PI * m, 3));\n  *error *= pf;\n  return std::abs(integral) * pf;\n}\n\nstatic auto compute_width_3body(const SquaredMatrixElement &msqrd,\n                                const double m, std::vector<double> fsp_masses,\n                                size_t num_events = 10000,\n                                double *error = nullptr) {\n\n  Rambo rambo{std::move(fsp_masses), m, msqrd};\n  const auto width = rambo.compute_width(num_events);\n  *error = width.second;\n  return width.first;\n}\n\n} // namespace storm", "meta": {"hexsha": "32196e45da24b6f800bdc9045b4c802a3d1e1d59", "size": 3624, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simple/wwidths.cpp", "max_stars_repo_name": "LoganAMorrison/Storm", "max_stars_repo_head_hexsha": "b189f276064a904d1792a10249fa3555237e3062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simple/wwidths.cpp", "max_issues_repo_name": "LoganAMorrison/Storm", "max_issues_repo_head_hexsha": "b189f276064a904d1792a10249fa3555237e3062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simple/wwidths.cpp", "max_forks_repo_name": "LoganAMorrison/Storm", "max_forks_repo_head_hexsha": "b189f276064a904d1792a10249fa3555237e3062", "max_forks_repo_licenses": ["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.1844660194, "max_line_length": 80, "alphanum_fraction": 0.6296909492, "num_tokens": 1106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5203103506466641}}
{"text": "/* Copyright 2020 CNRS-AIST JRL */\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <Eigen/QR>\n\n#include <benchmark/benchmark.h>\n\n#include \"common.h\"\n\nusing namespace Eigen;\n\nstatic void BM_TriangularSolve_NoInversePrecompute(benchmark::State & state)\n{\n  MatrixXd R = MatrixXd::Random(50, 50);\n  MatrixXd A = R.transpose() * R;\n  LLT<MatrixXd> llt(A);\n  VectorXd b = VectorXd::Random(50);\n  for(auto _ : state)\n  {\n    for(int i = 0; i < state.range(0); ++i)\n    {\n      llt.matrixL().solveInPlace(b);\n    }\n  }\n}\n// BENCHMARK(BM_TriangularSolve_NoInversePrecompute)->Apply(testSizes)->Unit(benchmark::kMicrosecond);\n\nstatic void BM_TriangularSolve_InversePrecompute(benchmark::State & state)\n{\n  MatrixXd R = MatrixXd::Random(50, 50);\n  MatrixXd A = R.transpose() * R;\n  LLT<MatrixXd> llt(A);\n  VectorXd b = VectorXd::Random(50);\n  VectorXd x = VectorXd::Random(50);\n  MatrixXd invA(50, 50);\n  for(auto _ : state)\n  {\n    invA.setIdentity();\n    llt.matrixL().solveInPlace(invA);\n    for(int i = 0; i < state.range(0); ++i)\n    {\n      benchmark::DoNotOptimize(x.noalias() = invA.triangularView<Lower>() * b);\n    }\n  }\n}\nBENCHMARK(BM_TriangularSolve_InversePrecompute)->Apply(testSizes)->Unit(benchmark::kMicrosecond);\n\nstatic void BM_TriangularInverse_AtOnce(benchmark::State & state)\n{\n  const int n = state.range(0);\n  MatrixXd A = MatrixXd::Random(n, n);\n  MatrixXd invA(state.range(0), state.range(0));\n  for(auto _ : state)\n  {\n    invA.setIdentity();\n    A.template triangularView<Eigen::Lower>().solveInPlace(invA);\n  }\n}\nBENCHMARK(BM_TriangularInverse_AtOnce)->Apply(testSizes)->Unit(benchmark::kMicrosecond);\n\nstatic void BM_TriangularInverse_Transpose(benchmark::State & state)\n{\n  const int n = state.range(0);\n  MatrixXd A = MatrixXd::Random(n, n);\n  MatrixXd invA(state.range(0), state.range(0));\n  for(auto _ : state)\n  {\n    invA.setIdentity();\n    A.template triangularView<Eigen::Lower>().transpose().solveInPlace(invA);\n  }\n}\nBENCHMARK(BM_TriangularInverse_Transpose)->Apply(testSizes)->Unit(benchmark::kMicrosecond);\n\nstatic void BM_TriangularInverse_ByCol(benchmark::State & state)\n{\n  const int n = state.range(0);\n  MatrixXd A = MatrixXd::Random(n, n);\n  MatrixXd invA(state.range(0), state.range(0));\n  VectorXd e(n);\n  for(auto _ : state)\n  {\n    e.setZero();\n    for(int i = 0; i < n; ++i)\n    {\n      e[i] = 1;\n      invA.col(i) = A.template triangularView<Eigen::Lower>().solve(e);\n      e[i] = 0;\n    }\n  }\n}\nBENCHMARK(BM_TriangularInverse_ByCol)->Apply(testSizes)->Unit(benchmark::kMicrosecond);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "1cace11c55b0f01ad92104d42eee1ae1e31b667d", "size": 2557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/LinearSystemSolving.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": "benchmarks/LinearSystemSolving.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": "benchmarks/LinearSystemSolving.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": 26.9157894737, "max_line_length": 102, "alphanum_fraction": 0.6812671099, "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5202968813974553}}
{"text": "#define BOOST_TEST_MODULE common_unit_tests\n\n#include <boost/test/included/unit_test.hpp>\n#include <armadillo>\n#include \"../src/common.h\"\n#include \"test_utils.cpp\"\n#include \"../src/logging/easylogging++.h\"\n\nINITIALIZE_EASYLOGGINGPP\n\nusing namespace arma;\n\nBOOST_AUTO_TEST_CASE(full_rank_inv_with_random_square_matrix)\n{\n    mat x = randu<mat>(5, 5);\n    mat expected = calculate_pseudoinverse(x);\n    mat actual = calculate_svd_inverse(x);\n    BOOST_CHECK(is_equal(expected, actual));\n}\n\nBOOST_AUTO_TEST_CASE(full_rank_inv_with_rank_argument_with_random_square_matrix)\n{\n    mat x = randu<mat>(5, 5);\n    mat expected = calculate_pseudoinverse(x);\n    mat actual = calculate_svd_inverse(x, 5);\n    BOOST_CHECK(is_equal(expected, actual));\n}\n\nBOOST_AUTO_TEST_CASE(full_rank_inv_with_rank_argument_with_random_non_square_matrix)\n{\n    mat x = randu<mat>(5, 6);\n    mat expected = calculate_pseudoinverse(x);\n    mat actual = calculate_svd_inverse(x, 5);\n    BOOST_CHECK(is_equal(expected, actual));\n}\n\nBOOST_AUTO_TEST_CASE(low_rank_inv_with_random_square_matrix)\n{\n    mat x = randu<mat>(10, 10);\n    mat expected = calculate_pseudoinverse(x);\n    mat actual = calculate_svd_inverse(x, 9);\n    // actual is only approximately equal to expected due to low rank approximation\n    // -> use larger threshold for this test case\n    BOOST_CHECK(is_equal(expected, actual, 0.1));\n}\n\nBOOST_AUTO_TEST_CASE(low_rank_inv_with_non_square_random_matrix)\n{\n    mat x = randu<mat>(10, 12);\n    mat expected = calculate_pseudoinverse(x);\n    mat actual = calculate_svd_inverse(x, 9);\n    // actual is only approximately equal to expected due to low rank approximation\n    // -> use larger threshold for this test case\n    BOOST_CHECK(is_equal(expected, actual, 0.1));\n}\n\nBOOST_AUTO_TEST_CASE(low_rank_approximation_with_non_square_random_matrix)\n{\n    mat x = randu<mat>(10, 12);\n    mat x_low = low_rank_approximation(x, 9);\n    // actual is only approximately equal to expected due to low rank approximation\n    // -> use larger threshold for this test case\n    BOOST_CHECK(is_equal(x, x_low, 0.1));\n}\n\nBOOST_AUTO_TEST_CASE(trimmed_mean_integer_argument)\n{\n    arma::vec x;\n    double result;\n\n    x = {1, 2, 5};\n    result = arma::as_scalar(trimmed_mean(x, 1));\n    BOOST_CHECK_EQUAL(result, 2);\n\n    x = {5, 2, -1, 2};\n    result = arma::as_scalar(trimmed_mean(x, 1));\n    BOOST_CHECK_EQUAL(result, 2);\n\n    x = {0, 10, 2, 12, 1};\n    result = arma::as_scalar(trimmed_mean(x, 2));\n    BOOST_CHECK_EQUAL(result, 2);\n}\n\nBOOST_AUTO_TEST_CASE(trimmed_mean_float_argument)\n{\n    arma::vec x;\n    double result;\n\n    x = {1, 2, 2, 5};\n    result = arma::as_scalar(trimmed_mean(x, 0.2f)); // rejects 1 point from both side\n    BOOST_CHECK_EQUAL(result, 2);\n\n    x = {-1, 3, 5, 2, 7};\n    result = arma::as_scalar(trimmed_mean(x, 0.4f)); // rejects 2 points from both side\n    BOOST_CHECK_EQUAL(result, 3);\n}", "meta": {"hexsha": "2a2b17d94e51b3dae5042de2457bad305c09abe7", "size": 2887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/common_test.cpp", "max_stars_repo_name": "omyllymaki/math", "max_stars_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T03:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T09:12:24.000Z", "max_issues_repo_path": "tests/common_test.cpp", "max_issues_repo_name": "omyllymaki/math", "max_issues_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_issues_repo_licenses": ["MIT"], "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/common_test.cpp", "max_forks_repo_name": "omyllymaki/math", "max_forks_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_forks_repo_licenses": ["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.0729166667, "max_line_length": 87, "alphanum_fraction": 0.7138898511, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5202945710122725}}
{"text": "#include <Eigen/Dense>\n#include <vector>\n#include \"HmcSampler.h\"\n\n#include \"preparation_Eig_Vect.h\"\n\n\n#include <fstream>\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid samples(\n                int n,\n                int dim,\n                int seed,\n                double *initial, \n                int numlin,\n                int numquad,\n                double *lin,\n                double *quad, \n                double *quad_lin,\n                double *offset_lin,\n                double *offset_quad,\n                double *samples_Carray\n\t\t ){\n\n  \n  const Map<VectorXd> initial_value(initial, dim);\n\n\n\n  ofstream logfile;\n  logfile.open (\"logfile.txt\");\n  \n\n  HmcSampler hmc1(dim, seed);\n  if (numlin >0){\t\t\n    const Map<MatrixXd> F(lin, numlin, dim);\n    const Map<VectorXd> g(offset_lin, numlin);\n\n    for(int i=0; i<numlin; i++){\n      hmc1.addLinearConstraint(F.row(i),g(i));\n    }\n  }\n\n  if (numquad >0){\n\n    for(int i=0; i<numquad; i++){\n      double *indice = &quad[i*dim*dim];\n      const Map<MatrixXd> A_Map(indice, dim, dim);\n\n\nfor(int k=0; k<dim; k++){\nfor(int l=0; l<dim; l++){\nlogfile << A_Map(k, l);\n}\nlogfile << endl;\n}\nlogfile << endl;\n\n      MatrixXd A(A_Map);\n      const Map<VectorXd> B_Map(&quad_lin[i*dim], dim);\n      VectorXd B(B_Map);\n      double C = offset_quad[i];  \n      hmc1.addQuadraticConstraint(A,B,C);\n    }\n\n  }\n\n  hmc1.setInitialValue(initial_value);\n  \n  MatrixXd samples(n,dim);\n  \n  for (int i=0; i<n; i++){     \n      samples.row(i) = hmc1.sampleNext();  \n  }\n\n//static double samples_Carray [n][dim];\n\n  double* result = samples.data();\n\n  for(int k=0; k<n; k++){\n    for(int l=0; l<dim;l++){\n      samples_Carray[k*dim + l] = result[k*dim + l];\n    }\n  }\n\n\nfor(int k=0; k< n; k++){\nfor(int l=0; l<dim; l++){\nlogfile << result[k*dim + l];\n}\nlogfile << endl;\n}\n\nlogfile << endl;\n\nfor(int k=0; k< n; k++){\nfor(int l=0; l<dim; l++){\nlogfile << samples_Carray[k*dim + l];\n}\nlogfile << endl;\n}\n\n\n\n  logfile.close();\n\n//return samples_Carray;\n\n}\n", "meta": {"hexsha": "49808fc3ccdb8d20ee58ead7e47662d18490a7cb", "size": 1997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "selectinf/src_C/preparation_Eig_Vect.cpp", "max_stars_repo_name": "TianXie1999/selective-inference", "max_stars_repo_head_hexsha": "ca02bbd84af5f5597944c75bde8337db9c69066a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 51.0, "max_stars_repo_stars_event_min_datetime": "2016-03-31T16:34:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T04:32:58.000Z", "max_issues_repo_path": "selectinf/src_C/preparation_Eig_Vect.cpp", "max_issues_repo_name": "TianXie1999/selective-inference", "max_issues_repo_head_hexsha": "ca02bbd84af5f5597944c75bde8337db9c69066a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-04-07T00:19:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T18:31:14.000Z", "max_forks_repo_path": "selectinf/src_C/preparation_Eig_Vect.cpp", "max_forks_repo_name": "TianXie1999/selective-inference", "max_forks_repo_head_hexsha": "ca02bbd84af5f5597944c75bde8337db9c69066a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-10-28T17:29:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T21:04:30.000Z", "avg_line_length": 17.6725663717, "max_line_length": 55, "alphanum_fraction": 0.5473209815, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5202945710122725}}
{"text": "/** \\file ElInfo2d.h */\n\n#pragma once\n\n#include <boost/numeric/mtl/mtl.hpp>\n\n#include \"ElInfo.hpp\"\n\nnamespace AMDiS\n{\n\n  /** \\ingroup Traverse\n   * \\brief\n   * ElInfo class for 2-dimensional elements (\\ref Triangle).\n   */\n  class ElInfo2d : public ElInfo\n  {\n  public:\n    /// Constructor. Calls ElInfo's protected Constructor.\n    ElInfo2d(Mesh* aMesh);\n\n    ///\n    ~ElInfo2d();\n\n    /// 2-dimensional realisation of ElInfo's fillElInfo method.\n    virtual void fillElInfo(int ichild, const ElInfo* elinfo_old) override;\n\n    /// 2-dimensional realisation of ElInfo's fillMacroInfo method.\n    virtual void fillMacroInfo(const MacroElement*) override;\n\n    /// 2-dimensional realisation of ElInfo's worldToCoord method.\n    virtual int worldToCoord(const WorldVector<double>& w, DimVec<double>& l) const override;\n\n    /// 2-dimensional realisation of ElInfo's calcGrdLambda method.\n    virtual double calcGrdLambda(DimVec<WorldVector<double>>& grd_lam) override;\n\n    /// 2-dimensional realisation of ElInfo's getNormal method.\n    virtual double getNormal(int side, WorldVector<double>& normal) const override;\n\n    /// 2-dimensional realisation of ElInfo's getElementNormal method.\n    virtual double getElementNormal(WorldVector<double>& normal) const override;\n\n    /// implements \\ref Elnfo::getSubElemCoordsMat\n    virtual mtl::dense2D<double>& getSubElemCoordsMat(int degree) const override;\n\n  protected:\n    /// Temp vectors for function \\ref calcGrdLambda.\n    WorldVector<double> e1, e2, normal;\n\n    static double mat_d1_left_val[3][3];\n    static mtl::dense2D<double> mat_d1_left;\n\n    static double mat_d1_right_val[3][3];\n    static mtl::dense2D<double> mat_d1_right;\n\n    static double mat_d2_left_val[6][6];\n    static mtl::dense2D<double> mat_d2_left;\n\n    static double mat_d2_right_val[6][6];\n    static mtl::dense2D<double> mat_d2_right;\n\n    static double mat_d3_left_val[10][10];\n    static mtl::dense2D<double> mat_d3_left;\n\n    static double mat_d3_right_val[10][10];\n    static mtl::dense2D<double> mat_d3_right;\n\n    static double mat_d4_left_val[15][15];\n    static mtl::dense2D<double> mat_d4_left;\n\n    static double mat_d4_right_val[15][15];\n    static mtl::dense2D<double> mat_d4_right;\n  };\n\n} // end namespace AMDiS\n", "meta": {"hexsha": "d59028d5859c6be8bc5f232b997df3f5171fc82d", "size": 2254, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ElInfo2d.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": "src/ElInfo2d.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": "src/ElInfo2d.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": 29.6578947368, "max_line_length": 93, "alphanum_fraction": 0.7200532387, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5202945649083037}}
{"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_SINHCOSH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SINHCOSH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-hyperbolic\n    Function object implementing sinhcosh capabilities\n\n    Computes simultaneously the sinh and cosh of the input\n\n    @par Semantic:\n\n    @code\n    T ch, sh\n    std::tie(sh, ch) = sinhcoshs(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T sh = sinh(x);\n    T ch = cosh(x);\n    @endcode\n\n    but speedier\n\n    @see  sinh, cosh\n\n  **/\n  std::pair<Value, Value> sinhcosh(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sinhcosh.hpp>\n#include <boost/simd/function/simd/sinhcosh.hpp>\n\n#endif\n", "meta": {"hexsha": "adee423fc02f59171d947cc35040f2887c700fe3", "size": 1105, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sinhcosh.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/sinhcosh.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/sinhcosh.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.25, "max_line_length": 100, "alphanum_fraction": 0.5683257919, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5202945600898006}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/pblas_wrapper.hpp>\n#include <frovedis/matrix/scalapack_wrapper.hpp>\n\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    // creating blockcyclic matrix from file\n    auto A = make_blockcyclic_matrix_load<float> (\"./sample_2x2\");\n    auto B = make_blockcyclic_matrix_load<float> (\"./sample_2x1\");\n\n    frovedis::lvec<int> ipiv;  // empty ipiv local-array\n    getrf<float> (A,ipiv);   // A will be factorized and ipiv will contain pivoting info\n    getrs<float> (A,B,ipiv); // solving AX=B, B will be overwritten with result matrix X\n\n    // checking whether the above operations successfully taken place \n    B.save(\"./out_2x1\");\n    BOOST_CHECK (system(\"diff ./out_2x1 ./ref_2x1\") == 0);\n    system(\"rm -f ./out_2x1\");\n}\n\n", "meta": {"hexsha": "2b7df0e629933e9b9fa27e13971450adae52d8ac", "size": 966, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/matrix/test9.2-1/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/test9.2-1/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/test9.2-1/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": 30.1875, "max_line_length": 88, "alphanum_fraction": 0.7070393375, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5202945539858319}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2016-2021 Oracle and/or its affiliates.\n// Contributed and/or modified by Vissarion Fisikopoulos, on behalf of Oracle\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#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_AZIMUTH_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_AZIMUTH_HPP\n\n#include <cmath>\n\n#include <boost/geometry/core/tags.hpp>\n#include <boost/geometry/core/coordinate_promotion.hpp>\n\n#include <boost/geometry/strategies/azimuth.hpp>\n\n#include <boost/geometry/util/select_most_precise.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace azimuth\n{\n\ntemplate <typename CalculationType = void>\nclass cartesian\n{\npublic:\n    template <typename T1, typename T2>\n    struct result_type\n        : geometry::select_most_precise\n              <\n                  // NOTE: this promotes any integer type to double\n                  typename geometry::promote_floating_point<T1, double>::type,\n                  typename geometry::promote_floating_point<T2, double>::type,\n                  CalculationType\n              >\n    {};\n\n    template <typename T1, typename T2, typename Result>\n    static inline void apply(T1 const& x1, T1 const& y1,\n                             T2 const& x2, T2 const& y2,\n                             Result& a1, Result& a2)\n    {\n        compute(x1, y1, x2, y2, a1, a2);\n    }\n    template <typename T1, typename T2, typename Result>\n    static inline void apply(T1 const& x1, T1 const& y1,\n                             T2 const& x2, T2 const& y2,\n                             Result& a1)\n    {\n        compute(x1, y1, x2, y2, a1, a1);\n    }\n    template <typename T1, typename T2, typename Result>\n    static inline void apply_reverse(T1 const& x1, T1 const& y1,\n                                     T2 const& x2, T2 const& y2,\n                                     Result& a2)\n    {\n        compute(x1, y1, x2, y2, a2, a2);\n    }\n\nprivate:\n    template <typename T1, typename T2, typename Result>\n    static inline void compute(T1 const& x1, T1 const& y1,\n                               T2 const& x2, T2 const& y2,\n                               Result& a1, Result& a2)\n    {\n        typedef typename result_type<T1, T2>::type calc_t;\n\n        // NOTE: azimuth 0 is at Y axis, increasing right\n        // as in spherical/geographic where 0 is at North axis\n        a1 = a2 = atan2(calc_t(x2) - calc_t(x1), calc_t(y2) - calc_t(y1));\n    }\n};\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\nnamespace services\n{\n\ntemplate <>\nstruct default_strategy<cartesian_tag>\n{\n    typedef strategy::azimuth::cartesian<> type;\n};\n\n}\n\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n}} // namespace strategy::azimuth\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_AZIMUTH_HPP\n", "meta": {"hexsha": "9035fdddcbe7e1d019916d77b9414a10eb42832f", "size": 3032, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/geometry/strategies/cartesian/azimuth.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/geometry/strategies/cartesian/azimuth.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/geometry/strategies/cartesian/azimuth.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "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.0198019802, "max_line_length": 79, "alphanum_fraction": 0.6339050132, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.5202945430633601}}
{"text": "/* boost histogram.cpp graphical verification of distribution functions\n *\n * Copyright Jens Maurer 2000\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: histogram.cpp,v 1.8 2004/07/27 03:43:34 dgregor Exp $\n *\n * This test program allows to visibly examine the results of the\n * distribution functions.\n */\n\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <string>\n#include <boost/random.hpp>\nusing namespace std;\n#include \"Utilities/OhmmsInfo.h\"\n#include \"Message/Communicate.h\"\n#include \"Message/OpenMP.h\"\n#include \"Utilities/RandomGenerator.h\"\n#include \"OhmmsApp/RandomNumberControl.h\"\nusing namespace qmcplusplus;\n\nvoid plot_histogram(const std::vector<int>& slots, int samples,\n                    double from, double to)\n{\n  int m = *std::max_element(slots.begin(), slots.end());\n  const int nRows = 20;\n  std::cout.setf(std::ios::fixed|std::ios::left);\n  std::cout.precision(5);\n  for(int r = 0; r < nRows; r++)\n  {\n    double y = ((nRows - r) * double(m))/(nRows * samples);\n    std::cout << std::setw(10) << y << \"  \";\n    for(unsigned int col = 0; col < slots.size(); col++)\n    {\n      char out = ' ';\n      if(slots[col]/double(samples) >= y)\n        out = 'x';\n      std::cout << out;\n    }\n    std::cout << std::endl;\n  }\n  std::cout << std::setw(12) << \" \"\n            << std::setw(10) << from;\n  std::cout.setf(std::ios::right, std::ios::adjustfield);\n  std::cout << std::setw(slots.size()-10) << to << std::endl;\n}\n\n// I am not sure whether these two should be in the library as well\n\n// maintain sum of NumberGenerator results\ntemplate<class NumberGenerator,\n         class Sum = typename NumberGenerator::result_type>\nclass sum_result\n{\npublic:\n  typedef NumberGenerator base_type;\n  typedef typename base_type::result_type result_type;\n  explicit sum_result(const base_type & g) : gen(g), _sum(0) { }\n  result_type operator()()\n  {\n    result_type r = gen();\n    _sum += r;\n    return r;\n  }\n  base_type & base()\n  {\n    return gen;\n  }\n  Sum sum() const\n  {\n    return _sum;\n  }\n  void reset()\n  {\n    _sum = 0;\n  }\nprivate:\n  base_type gen;\n  Sum _sum;\n};\n\n\n// maintain square sum of NumberGenerator results\ntemplate<class NumberGenerator,\n         class Sum = typename NumberGenerator::result_type>\nclass squaresum_result\n{\npublic:\n  typedef NumberGenerator base_type;\n  typedef typename base_type::result_type result_type;\n  explicit squaresum_result(const base_type & g) : gen(g), _sum(0) { }\n  result_type operator()()\n  {\n    result_type r = gen();\n    _sum += r*r;\n    return r;\n  }\n  base_type & base()\n  {\n    return gen;\n  }\n  Sum squaresum() const\n  {\n    return _sum;\n  }\n  void reset()\n  {\n    _sum = 0;\n  }\nprivate:\n  base_type gen;\n  Sum _sum;\n};\n\n\ntemplate<class RNG>\nvoid histogram(RNG base, int samples, double from, double to,\n               const std::string & name)\n{\n  typedef squaresum_result<sum_result<RNG, double>, double > SRNG;\n  SRNG gen((sum_result<RNG, double>(base)));\n  const int nSlots = 60;\n  std::vector<int> slots(nSlots,0);\n  for(int i = 0; i < samples; i++)\n  {\n    double val = gen();\n    if(val < from || val >= to)    // early check avoids overflow\n      continue;\n    int slot = int((val-from)/(to-from) * nSlots);\n    if(slot < 0 || slot > (int)slots.size())\n      continue;\n    slots[slot]++;\n  }\n  std::cout << name << std::endl;\n  plot_histogram(slots, samples, from, to);\n  double mean = gen.base().sum() / samples;\n  std::cout << \"mean: \" << mean\n            << \" sigma: \" << std::sqrt(gen.squaresum()/samples-mean*mean)\n            << \"\\n\" << std::endl;\n}\n\ntemplate<class RNG, class SEEDARRAY>\nvoid histogram_OMP(RNG base, int samples, double from, double to,\n                   SEEDARRAY& seeds, const std::string & name)\n{\n  typedef squaresum_result<sum_result<RNG, double>, double > SRNG;\n  const int nSlots = 60;\n  std::vector<int> slots_tot(nSlots,0);\n  double sum1=0.0;\n  double sum2=0.0;\n  #pragma omp parallel\n  {\n    std::vector<int> slots(nSlots,0);\n    RNG base_copy(base);\n    //base_copy.reset();\n    base_copy.seed(seeds[omp_get_thread_num()]);\n    SRNG gen((sum_result<RNG, double>(base_copy)));\n    for(int i = 0; i < samples; i++)\n    {\n      double val = gen();\n      if(val < from || val >= to)    // early check avoids overflow\n        continue;\n      int slot = int((val-from)/(to-from) * nSlots);\n      if(slot < 0 || slot > (int)slots.size())\n        continue;\n      slots[slot]++;\n    }\n    #pragma omp critical\n    {\n      for(int i=0; i<nSlots; i++)\n        slots_tot[i]+=slots[i];\n      sum1 += gen.base().sum();\n      sum2 += gen.squaresum();\n      double mean = gen.base().sum() / samples;\n      std::cout << \"random seed \" << seeds[omp_get_thread_num()]\n                << \" mean: \" << mean\n                << \" sigma: \" << std::sqrt(gen.squaresum()/samples-mean*mean)\n                << std::endl;\n    }\n  }\n  std::cout << name << std::endl;\n  plot_histogram(slots_tot, samples, from, to);\n  int samples_tot=samples*omp_get_max_threads();\n  double mean = sum1/samples_tot;\n  //double mean = gen.base().sum() / samples;\n  std::cout << \"mean: \" << mean\n            << \" sigma: \" << std::sqrt(sum2/samples_tot-mean*mean)\n            << \"\\n\" << std::endl;\n}\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\ntemplate<class PRNG>\nvoid histograms()\n{\n  PRNG rng;\n  using namespace boost;\n  //histogram(make_gen(rng, uniform_smallint<>(0, 5)), 100000, -1, 6,\n  //          \"uniform_smallint(0,5)\");\n  //histogram(make_gen(rng, uniform_int<>(0, 5)), 100000, -1, 6,\n  //          \"uniform_int(0,5)\");\n  histogram(make_gen(rng, uniform_real<>(0,1)), 1000000, -0.5, 1.5,\n            \"uniform_real(0,1)\");\n  //histogram(make_gen(rng, bernoulli_distribution<>(0.2)), 100000, -0.5, 1.5,\n  //          \"bernoulli(0.2)\");\n  //histogram(make_gen(rng, binomial_distribution<>(4, 0.2)), 100000, -1, 5,\n  //          \"binomial(4, 0.2)\");\n  //histogram(make_gen(rng, triangle_distribution<>(1, 2, 8)), 100000, 0, 10,\n  //          \"triangle(1,2,8)\");\n  //histogram(make_gen(rng, geometric_distribution<>(5.0/6.0)), 100000, 0, 10,\n  //          \"geometric(5/6)\");\n  //histogram(make_gen(rng, exponential_distribution<>(0.3)), 100000, 0, 10,\n  //          \"exponential(0.3)\");\n  //histogram(make_gen(rng, cauchy_distribution<>()), 100000, -5, 5,\n  //          \"cauchy\");\n  //histogram(make_gen(rng, lognormal_distribution<>(3, 2)), 100000, 0, 10,\n  //          \"lognormal\");\n  histogram(make_gen(rng, normal_distribution<>()), 1000000, -3, 3,\n            \"normal\");\n  histogram(make_gen(rng, normal_distribution<>(0.5, 0.5)), 1000000, -3, 3,\n            \"normal(0.5, 0.5)\");\n  //histogram(make_gen(rng, poisson_distribution<>(1.5)), 100000, 0, 5,\n  //          \"poisson(1.5)\");\n  //histogram(make_gen(rng, poisson_distribution<>(10)), 100000, 0, 20,\n  //          \"poisson(10)\");\n  //histogram(make_gen(rng, gamma_distribution<>(0.5)), 100000, 0, 0.5,\n  //          \"gamma(0.5)\");\n  //histogram(make_gen(rng, gamma_distribution<>(1)), 100000, 0, 3,\n  //          \"gamma(1)\");\n  //histogram(make_gen(rng, gamma_distribution<>(2)), 100000, 0, 6,\n  //          \"gamma(2)\");\n}\n\nvoid simple_test()\n{\n  typedef qmcplusplus::RandomGenerator_t generator_type;\n  typedef generator_type::uint_type uint_type;\n  generator_type uni;\n  uni.seed(static_cast<uint_type>(std::time(0))%1024);\n  //copy a generator and seed it by random number from the original generator\n  generator_type uni_copy(uni);\n  uni_copy.seed(static_cast<uint_type>(uni()*1000));\n  for(int i=0; i<20; i++)\n    std::cout << uni() << \" \" << uni_copy() << std::endl;\n  //check serial histogram\n  histogram(uni, 1000000, -0.5, 1.5, \"uniform_real(0,1)\");\n  //test PrimeNumberSet class\n  PrimeNumberSet<uint_type> primes;\n  std::vector<uint_type> myprimes;\n  //use a random number as an offset\n  int n=primes.get(static_cast<uint_type>(std::time(0))%1024,omp_get_max_threads(),myprimes);\n  //int n=primes.get(10000,myprimes,5);\n  histogram_OMP(uni, 100000, -0.5, 1.5, myprimes, \"uniform_real(0,1)\");\n  for(int i=0; i<myprimes.size(); i++)\n    std::cout << i << std::setw(12) << myprimes[i] << std::endl;\n}\n\nint main(int argc, char** argv)\n{\n  //histograms<boost::mt19937>();\n  //histograms<boost::lagged_fibonacci607>();\n  OHMMS::Controller->initialize(argc,argv);\n  OhmmsInfo Welcome(argc,argv,OHMMS::Controller->rank());\n  RandomNumberControl rng;\n  rng.put(NULL);\n  //check serial histogram\n  histogram(Random, 10000, -0.5, 1.5, \"uniform_real(0,1)\");\n  std::vector<uint32_t> myprimes;\n  //rng.PrimeNumbers.get(Random.offset()+omp_get_max_threads(),omp_get_max_threads(),myprimes);\n  rng.PrimeNumbers.get(1024,512,myprimes);\n  std::cout <<\"============================  \" << endl;\n  for(int i=0; i<myprimes.size();)\n  {\n    for(int j=0; j<8; j++, i++)\n      std::cout << std::setw(12) << myprimes[i];\n    std::cout << std::endl;\n  }\n  histogram_OMP(Random, 10000, -0.5, 1.5, myprimes, \"uniform_real(0,1)\");\n  std::cout <<\"============================  \" << endl;\n  int imax=8*(rng.PrimeNumbers.size()/8);\n  for(int i=0; i<imax;)\n  {\n    for(int j=0; j<8; j++, i++)\n      std::cout << std::setw(12) << rng.PrimeNumbers[i];\n    std::cout << std::endl;\n  }\n  //std::stringstream a;\n  //Random.write(a);\n  //cout << \"Size of string \" << a.str().size() << endl;\n  //vector<uint32_t> v;\n  //uint32_t vt;\n  //while(!a.eof())\n  //{\n  //  if(a>>vt) v.push_back(vt);\n  //}\n  //for(int i=0; i<v.size(); i++) cout << v[i] << endl;\n  //Random.write(cout);\n  //cout << endl;\n  //cout << \" size of data \" << v.size() << endl;\n  OHMMS::Controller->finalize();\n  return 0;\n}\n\n", "meta": {"hexsha": "6e823f47ed6da4acc0e0e9997c5b2a7b831f1e9e", "size": 9787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/performance-regression/full-apps/qmcpack/src/SandBox/histogram.cpp", "max_stars_repo_name": "JKChenFZ/hclib", "max_stars_repo_head_hexsha": "50970656ac133477c0fbe80bb674fe88a19d7177", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 55.0, "max_stars_repo_stars_event_min_datetime": "2015-07-28T01:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T16:27:46.000Z", "max_issues_repo_path": "test/performance-regression/full-apps/qmcpack/src/SandBox/histogram.cpp", "max_issues_repo_name": "JKChenFZ/hclib", "max_issues_repo_head_hexsha": "50970656ac133477c0fbe80bb674fe88a19d7177", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2015-06-15T20:38:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-26T00:11:43.000Z", "max_forks_repo_path": "test/performance-regression/full-apps/qmcpack/src/SandBox/histogram.cpp", "max_forks_repo_name": "JKChenFZ/hclib", "max_forks_repo_head_hexsha": "50970656ac133477c0fbe80bb674fe88a19d7177", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2015-10-26T22:11:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-02T22:09:15.000Z", "avg_line_length": 31.0698412698, "max_line_length": 95, "alphanum_fraction": 0.6099928477, "num_tokens": 2964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5202752116059527}}
{"text": "#include <big_types.h>\n#include <big_generate_random.h>\n#include <big_diag.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\nBOOST_AUTO_TEST_SUITE(big_diag);\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  \n  for(size_t tst=0u;tst<5u;++tst)\n  {\n    matrix_type D;\n    vector_type v;\n    \n    big::generate_random(10, v);\n    big::diag(v,D);\n    \n    BOOST_CHECK( D.size1() == 10 );\n    BOOST_CHECK( D.size2() == 10 );\n    \n    for(size_t i=0u;i<10u;++i)\n    {\n      for(size_t j=0u;j<10u;++j)\n      {\n        if(i==j)\n          BOOST_CHECK( D(i,i) == v(i) );\n        else\n          BOOST_CHECK( D(i,j) == 0.0 );\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "85f7b7498bb58427782f47b866a65e8d17d8a2d4", "size": 929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/BIG/unit_tests/big_diag/unit_big_diag.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/BIG/unit_tests/big_diag/unit_big_diag.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/BIG/unit_tests/big_diag/unit_big_diag.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": 21.1136363636, "max_line_length": 55, "alphanum_fraction": 0.6297093649, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5202752034550122}}
{"text": "#ifndef SM_POINT_TEST_HARNESS_HPP\n#define SM_POINT_TEST_HARNESS_HPP\n\n#include <sm/eigen/gtest.hpp>\n#include <boost/bind.hpp>\n#include <sm/eigen/NumericalDiff.hpp>\n#include <sm/boost/serialization.hpp>\n\nnamespace sm {\n  \n  template<typename POINT_T>\n  class PointTestHarness\n  {\n  public:\n    typedef POINT_T point_t;\n    double _threshold;\n    PointTestHarness(double nearnessThreshold = 1e-10) : _threshold(nearnessThreshold) {}\n    \n\n    void testAdd(double threshold = -1)\n    {\n\t  SCOPED_TRACE(__FUNCTION__);\n      if(threshold < 0) \n\tthreshold = _threshold;\n\n      Eigen::Vector3d p1;\n      Eigen::Vector3d p2;\n      Eigen::Vector3d answer;\n      for(int i = 0; i < 20; i++)\n\t{\n\t  p1.setRandom();\n\t  p2.setRandom();\n\t  answer = p1+p2;\n\t \n\t  point_t P1(p1);\n\t  point_t P2(p2);\n\t  \n\t  point_t Answer = P1 + P2;\n\t  \n\t  sm::eigen::assertNear(Answer.toEuclidean(), answer, threshold, SM_SOURCE_FILE_POS);\n\t}\n    }\n\n    void testSubtract(double threshold = -1)\n    {\n\t  SCOPED_TRACE(__FUNCTION__);\n      if(threshold < 0) \n\tthreshold = _threshold;\n\n      Eigen::Vector3d p1;\n      Eigen::Vector3d p2;\n      Eigen::Vector3d answer;\n      for(int i = 0; i < 20; i++)\n\t{\n\t  p1.setRandom();\n\t  p2.setRandom();\n\t  answer = p1-p2;\n\t \n\t  point_t P1(p1);\n\t  point_t P2(p2);\n\t  \n\t  point_t Answer = P1 - P2;\n\t  \n\t  sm::eigen::assertNear(Answer.toEuclidean(), answer, threshold, SM_SOURCE_FILE_POS);\n\t}\n    }\n\n    void testAssign3(double threshold = -1)\n    {\n\t  SCOPED_TRACE(__FUNCTION__);\n      if(threshold < 0) \n\tthreshold = _threshold;\n\n      Eigen::Vector3d p1;\n      for(int i = 0; i < 20; i++)\n\t{\n\t  p1.setRandom();\n\t \n\t  point_t P1;\n\n\t  P1 = p1;\n\n\t  sm::eigen::assertNear(P1.toEuclidean(), p1, threshold, SM_SOURCE_FILE_POS);\n\t}\n \n    }\n\n    void testAssign4(double threshold = -1.0)\n    {\n\t  SCOPED_TRACE(__FUNCTION__);\n      if(threshold < 0) \n\tthreshold = _threshold;\n\n      Eigen::Vector4d p1;\n      for(int i = 0; i < 20; i++)\n\t{\n\t  p1.setRandom();\n\t \n\t  point_t P1;\n\n\t  P1 = p1;\n\n\t  Eigen::Vector4d p1a = p1/p1.norm();\n\t  Eigen::Vector4d P1a = P1.toHomogeneous() / P1.toHomogeneous().norm();\n\n\t  sm::eigen::assertNear(p1a, P1a, threshold, SM_SOURCE_FILE_POS);\n\t}\n \n    }\n\n\n    struct EuclideanJacobianFunctor\n    {\n      typedef Eigen::Vector3d value_t;\n      typedef double scalar_t;\n      typedef Eigen::Vector3d input_t;\n      typedef Eigen::Matrix3d jacobian_t;\n\n      point_t p;\n      EuclideanJacobianFunctor(point_t p) : p(p) {}\n\n      Eigen::Vector3d update(Eigen::Vector3d pp, int dimension, double dpd)\n      {\n\tpp[dimension] += dpd;\n\treturn pp;\n      }\n\n      value_t operator()(const Eigen::Vector3d & dp)\n      {\n\tpoint_t j = p;\n\tj.oplus(dp);\n\treturn j.toEuclidean();\n      }\n      \n    };\n    \n    void testToEuclideanJacobian(double threshold = -1)\n    {\n\t  SCOPED_TRACE(__FUNCTION__);\n      if(threshold < 0) \n\tthreshold = _threshold;\n\n      for(int i = 0; i < 10; i++)\n\t{\n\t  point_t P;\n\t  P.setRandom();\n\t  EuclideanJacobianFunctor functor(P);\n\t  sm::eigen::NumericalDiff<EuclideanJacobianFunctor> nd(functor);\n\t  Eigen::Matrix3d Jest = nd.estimateJacobian(Eigen::Vector3d::Zero());\n\t  Eigen::Matrix3d J;\n\t  P.toEuclideanAndJacobian(J);\n\t  \n\t  sm::eigen::assertNear(J,Jest, threshold, SM_SOURCE_FILE_POS);\t  \n\t}\n\n    }\n\n\n    struct HomogeneousJacobianFunctor\n    {\n\t  \n      typedef Eigen::Vector4d value_t;\n      typedef double scalar_t;\n      typedef Eigen::Vector3d input_t;\n      typedef Eigen::Matrix<double,4,3> jacobian_t;\n\n      point_t p;\n      HomogeneousJacobianFunctor(point_t p) : p(p) {}\n\n      Eigen::Vector3d update(Eigen::Vector3d pp, int dimension, double dpd)\n      {\n\tpp[dimension] += dpd;\n\treturn pp;\n      }\n\n      value_t operator()(const Eigen::Vector3d & dp)\n      {\n\tpoint_t j = p;\n\tj.oplus(dp);\n\treturn j.toHomogeneous();\n      }\n      \n    };\n    \n    void testToHomogeneousJacobian(double threshold = -1)\n    {\n\t  SCOPED_TRACE(__FUNCTION__);\n      if(threshold < 0) \n\tthreshold = _threshold;\n\n      for(int i = 0; i < 10; i++)\n\t{\n\t  point_t P;\n\t  P.setRandom();\n\t  HomogeneousJacobianFunctor functor(P);\n\t  sm::eigen::NumericalDiff<HomogeneousJacobianFunctor> nd(functor);\n\t  Eigen::Matrix<double,4,3> Jest = nd.estimateJacobian(Eigen::Vector3d::Zero());\n\t  Eigen::Matrix<double,4,3> J;\n\t  P.toHomogeneousAndJacobian(J);\n\t  \n\t  sm::eigen::assertNear(J,Jest, threshold, SM_SOURCE_FILE_POS);\t  \n\t}\n\n    }\n\n\n\tvoid testSerialization()\n\t{\n\t  SCOPED_TRACE(__FUNCTION__);\n\n\t  point_t p1;\n\t  p1.setRandom();\n\t  \n\t  sm::boost_serialization::save(p1, \"test.ba\");\n\n\t  ASSERT_TRUE(p1.isBinaryEqual(p1));\n\t  \n\t  point_t p2;\n\n\t  ASSERT_FALSE(p1.isBinaryEqual(p2));\n\t  ASSERT_FALSE(p2.isBinaryEqual(p1));\n\n\t  sm::boost_serialization::load(p2, \"test.ba\");\n\n\t  ASSERT_TRUE(p1.isBinaryEqual(p2));\n\t  ASSERT_TRUE(p2.isBinaryEqual(p1));\n\t  \n\t  p1.setRandom();\n\n\t  ASSERT_FALSE(p1.isBinaryEqual(p2));\n\t  ASSERT_FALSE(p2.isBinaryEqual(p1));\n\n\t  sm::boost_serialization::save_xml(p1, \"Point\", \"test.xml\");\n\n\t  sm::boost_serialization::load_xml(p2, \"Point\", \"test.xml\");\n\n\t  // Too strict.\n\t  //ASSERT_TRUE(p1.isBinaryEqual(p2));\n\t  //ASSERT_TRUE(p2.isBinaryEqual(p1));\n\n\t}\n\n    void testAll()\n    {\n      testAdd();\n      testSubtract();\n      testAssign3();\n      testAssign4();\n      testToEuclideanJacobian();\n      testToHomogeneousJacobian();\n\t  testSerialization();\n    }\n    \n  };\n  \n} // namespace sm\n\n\n#endif /* SM_POINT_TEST_HARNESS_HPP */\n", "meta": {"hexsha": "4ddbcc1f866f20158e0ddeaf2fe7e93562dc3644", "size": 5377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_kinematics/test/PointTestHarness.hpp", "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/test/PointTestHarness.hpp", "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/test/PointTestHarness.hpp", "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": 20.6807692308, "max_line_length": 89, "alphanum_fraction": 0.6323228566, "num_tokens": 1596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5202752034550122}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n    This is an example illustrating the use of the krls object \n    from the dlib C++ Library.\n\n    The krls object allows you to perform online regression.  This\n    example will train an instance of it on the sinc function.\n\n*/\n\n#include <iostream>\n#include <vector>\n\n#include <dlib/svm.h>\n\nusing namespace std;\nusing namespace dlib;\n\n// Here is the sinc function we will be trying to learn with the krls\n// object.\ndouble sinc(double x)\n{\n    if (x == 0)\n        return 1;\n    return sin(x)/x;\n}\n\nint main()\n{\n    // Here we declare that our samples will be 1 dimensional column vectors.  In general, \n    // you can use N dimensional vectors as inputs to the krls object.  But here we only \n    // have 1 dimension to make the example simple.  (Note that if you don't know the \n    // dimensionality of your vectors at compile time you can change the first number to \n    // a 0 and then set the size at runtime)\n    typedef matrix<double,1,1> sample_type;\n\n    // Now we are making a typedef for the kind of kernel we want to use.  I picked the\n    // radial basis kernel because it only has one parameter and generally gives good\n    // results without much fiddling.\n    typedef radial_basis_kernel<sample_type> kernel_type;\n\n    // Here we declare an instance of the krls object.  The first argument to the constructor\n    // is the kernel we wish to use.  The second is a parameter that determines the numerical \n    // accuracy with which the object will perform part of the regression algorithm.  Generally\n    // smaller values give better results but cause the algorithm to run slower.  You just have\n    // to play with it to decide what balance of speed and accuracy is right for your problem.\n    // Here we have set it to 0.001.\n    krls<kernel_type> test(kernel_type(0.1),0.001);\n\n    // now we train our object on a few samples of the sinc function.\n    sample_type m;\n    for (double x = -10; x <= 4; x += 1)\n    {\n        m(0) = x;\n        test.train(m, sinc(x));\n    }\n\n    // now we output the value of the sinc function for a few test points as well as the \n    // value predicted by krls object.\n    m(0) = 2.5; cout << sinc(m(0)) << \"   \" << test(m) << endl;\n    m(0) = 0.1; cout << sinc(m(0)) << \"   \" << test(m) << endl;\n    m(0) = -4;  cout << sinc(m(0)) << \"   \" << test(m) << endl;\n    m(0) = 5.0; cout << sinc(m(0)) << \"   \" << test(m) << endl;\n\n    // The output is as follows:\n    // 0.239389   0.239362\n    // 0.998334   0.998333\n    // -0.189201   -0.189201\n    // -0.191785   -0.197267\n\n\n    // The first column is the true value of the sinc function and the second\n    // column is the output from the krls estimate.  \n\n    \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 test object to disk and recall it later like so:\n    ofstream fout(\"saved_krls_object.dat\",ios::binary);\n    serialize(test,fout);\n    fout.close();\n\n    // now lets open that file back up and load the krls object it contains\n    ifstream fin(\"saved_krls_object.dat\",ios::binary);\n    deserialize(test, fin);\n\n    // If you don't want to save the whole krls object (it might be a bit large) \n    // you can save just the decision function it has learned so far.  You can get \n    // the decision function out of it by calling test.get_decision_function() and\n    // then you can serialize that object instead.  E.g.\n    decision_function<kernel_type> funct = test.get_decision_function();\n    fout.open(\"saved_krls_function.dat\",ios::binary);\n    serialize(funct, fout);\n}\n\n\n", "meta": {"hexsha": "ff04066cbd9223254252e62beb6dce14dd6be8bd", "size": 3674, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DynamicGestures/dlib-18.5/examples/krls_ex.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": "DynamicGestures/dlib-18.5/examples/krls_ex.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": "DynamicGestures/dlib-18.5/examples/krls_ex.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": 37.1111111111, "max_line_length": 97, "alphanum_fraction": 0.6663037561, "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5202752024821057}}
{"text": "/*\r\n [auto_generated]\r\n libs/numeric/odeint/examples/heun.cpp\r\n\r\n [begin_description]\r\n Examplary implementation of the method of Heun.\r\n [end_description]\r\n\r\n Copyright 2012 Karsten Ahnert\r\n Copyright 2012 Mario Mulansky\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 <iostream>\r\n\r\n\r\n#include <boost/fusion/container/vector.hpp>\r\n#include <boost/fusion/container/generation/make_vector.hpp>\r\n\r\n#include <boost/array.hpp>\r\n\r\n#include <boost/numeric/odeint.hpp>\r\n\r\n\r\n\r\n\r\n\r\n\r\nnamespace fusion = boost::fusion;\r\n\r\n//[ heun_define_coefficients\r\ntemplate< class Value = double >\r\nstruct heun_a1 : boost::array< Value , 1 > {\r\n    heun_a1( void )\r\n    {\r\n        (*this)[0] = static_cast< Value >( 1 ) / static_cast< Value >( 3 );\r\n    }\r\n};\r\n\r\ntemplate< class Value = double >\r\nstruct heun_a2 : boost::array< Value , 2 >\r\n{\r\n    heun_a2( void )\r\n    {\r\n        (*this)[0] = static_cast< Value >( 0 );\r\n        (*this)[1] = static_cast< Value >( 2 ) / static_cast< Value >( 3 );\r\n    }\r\n};\r\n\r\n\r\ntemplate< class Value = double >\r\nstruct heun_b : boost::array< Value , 3 >\r\n{\r\n    heun_b( void )\r\n    {\r\n        (*this)[0] = static_cast<Value>( 1 ) / static_cast<Value>( 4 );\r\n        (*this)[1] = static_cast<Value>( 0 );\r\n        (*this)[2] = static_cast<Value>( 3 ) / static_cast<Value>( 4 );\r\n    }\r\n};\r\n\r\ntemplate< class Value = double >\r\nstruct heun_c : boost::array< Value , 3 >\r\n{\r\n    heun_c( void )\r\n    {\r\n        (*this)[0] = static_cast< Value >( 0 );\r\n        (*this)[1] = static_cast< Value >( 1 ) / static_cast< Value >( 3 );\r\n        (*this)[2] = static_cast< Value >( 2 ) / static_cast< Value >( 3 );\r\n    }\r\n};\r\n//]\r\n\r\n\r\n//[ heun_stepper_definition\r\ntemplate<\r\n    class State ,\r\n    class Value = double ,\r\n    class Deriv = State ,\r\n    class Time = Value ,\r\n    class Algebra = boost::numeric::odeint::range_algebra ,\r\n    class Operations = boost::numeric::odeint::default_operations ,\r\n    class Resizer = boost::numeric::odeint::initially_resizer\r\n>\r\nclass heun : public\r\nboost::numeric::odeint::explicit_generic_rk< 3 , 3 , State , Value , Deriv , Time ,\r\n                                             Algebra , Operations , Resizer >\r\n{\r\n\r\npublic:\r\n\r\n    typedef boost::numeric::odeint::explicit_generic_rk< 3 , 3 , State , Value , Deriv , Time ,\r\n                                                         Algebra , Operations , Resizer > stepper_base_type;\r\n\r\n    typedef typename stepper_base_type::state_type state_type;\r\n    typedef typename stepper_base_type::wrapped_state_type wrapped_state_type;\r\n    typedef typename stepper_base_type::value_type value_type;\r\n    typedef typename stepper_base_type::deriv_type deriv_type;\r\n    typedef typename stepper_base_type::wrapped_deriv_type wrapped_deriv_type;\r\n    typedef typename stepper_base_type::time_type time_type;\r\n    typedef typename stepper_base_type::algebra_type algebra_type;\r\n    typedef typename stepper_base_type::operations_type operations_type;\r\n    typedef typename stepper_base_type::resizer_type resizer_type;\r\n    typedef typename stepper_base_type::stepper_type stepper_type;\r\n\r\n    heun( const algebra_type &algebra = algebra_type() )\r\n    : stepper_base_type(\r\n            fusion::make_vector(\r\n                heun_a1<Value>() ,\r\n                heun_a2<Value>() ) ,\r\n            heun_b<Value>() , heun_c<Value>() , algebra )\r\n    { }\r\n};\r\n//]\r\n\r\n\r\nconst double sigma = 10.0;\r\nconst double R = 28.0;\r\nconst double b = 8.0 / 3.0;\r\n\r\nstruct lorenz\r\n{\r\n    template< class State , class Deriv >\r\n    void operator()( const State &x_ , Deriv &dxdt_ , double t ) const\r\n    {\r\n        typename boost::range_iterator< const State >::type x = boost::begin( x_ );\r\n        typename boost::range_iterator< Deriv >::type dxdt = boost::begin( dxdt_ );\r\n\r\n        dxdt[0] = sigma * ( x[1] - x[0] );\r\n        dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\r\n        dxdt[2] = -b * x[2] + x[0] * x[1];\r\n    }\r\n};\r\n\r\nstruct streaming_observer\r\n{\r\n    std::ostream &m_out;\r\n    streaming_observer( std::ostream &out ) : m_out( out ) { }\r\n    template< typename State , typename Value >\r\n    void operator()( const State &x , Value t ) const\r\n    {\r\n        m_out << t;\r\n        for( size_t i=0 ; i<x.size() ; ++i ) m_out << \"\\t\" << x[i];\r\n        m_out << \"\\n\";\r\n    }\r\n};\r\n\r\n\r\n\r\nint main( int argc , char **argv )\r\n{\r\n    using namespace std;\r\n    using namespace boost::numeric::odeint;\r\n\r\n\r\n    //[ heun_example\r\n    typedef boost::array< double , 3 > state_type;\r\n    heun< state_type > h;\r\n    state_type x = {{ 10.0 , 10.0 , 10.0 }};\r\n\r\n    integrate_const( h , lorenz() , x , 0.0 , 100.0 , 0.01 ,\r\n                     streaming_observer( std::cout ) );\r\n\r\n    //]\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "31d3f309c00f7fa3f82ffa09889d1caa2c5998d2", "size": 4791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/heun.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/heun.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/heun.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": 28.0175438596, "max_line_length": 109, "alphanum_fraction": 0.5969526195, "num_tokens": 1250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5202751943311654}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2021 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: Wolfgang Bangerth, Colorado State University, 2021. \n * Based on step-15 by Sven Wetterauer, University of Heidelberg, 2012. \n */ \n\n\n// @sect3{Include files}  \n\n// \u8fd9\u4e2a\u7a0b\u5e8f\u5f00\u59cb\u65f6\u548c\u5176\u4ed6\u5927\u591a\u6570\u7a0b\u5e8f\u4e00\u6837\uff0c\u6709\u4f17\u6240\u5468\u77e5\u7684\u5305\u542b\u6587\u4ef6\u3002\u4e0e step-15 \u7a0b\u5e8f\u76f8\u6bd4\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u6240\u505a\u7684\u5927\u90e8\u5206\u5de5\u4f5c\u90fd\u662f\u4ece\u8be5\u7a0b\u5e8f\u4e2d\u590d\u5236\u7684\uff0c\u552f\u4e00\u4e0d\u540c\u7684\u662f\u5305\u62ec\u5934\u6587\u4ef6\uff0c\u6211\u4eec\u4ece\u8be5\u6587\u4ef6\u4e2d\u5bfc\u5165\u4e86SparseDirectUMFPACK\u7c7b\u548cKINSOL\u7684\u5b9e\u9645\u63a5\u53e3\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/base/utilities.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/affine_constraints.h> \n#include <deal.II/lac/sparse_direct.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\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_accessor.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_values.h> \n#include <deal.II/fe/fe_q.h> \n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n#include <deal.II/numerics/solution_transfer.h> \n\n#include <deal.II/sundials/kinsol.h> \n\n#include <fstream> \n#include <iostream> \n\nnamespace Step77 \n{ \n  using namespace dealii; \n// @sect3{The <code>MinimalSurfaceProblem</code> class template}  \n\n// \u540c\u6837\u5730\uff0c\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u57fa\u672c\u4e0a\u662f  step-15  \u4e2d\u7684\u4e00\u4e2a\u526f\u672c\u3002\u7136\u800c\uff0c\u8be5\u7c7b\u786e\u5b9e\u5c06\u96c5\u5404\u5e03\uff08\u7cfb\u7edf\uff09\u77e9\u9635\uff08\u4ee5\u53ca\u4f7f\u7528\u76f4\u63a5\u6c42\u89e3\u5668\u5bf9\u5176\u8fdb\u884c\u56e0\u5f0f\u5206\u89e3\uff09\u548c\u6b8b\u5dee\u7684\u8ba1\u7b97\u5206\u6210\u4e86\u4e0d\u540c\u7684\u51fd\u6570\uff0c\u539f\u56e0\u5df2\u5728\u4ecb\u7ecd\u4e2d\u5217\u51fa\u3002\u51fa\u4e8e\u540c\u6837\u7684\u539f\u56e0\uff0c\u8be5\u7c7b\u4e5f\u6709\u4e00\u4e2a\u6307\u5411\u96c5\u5404\u5e03\u77e9\u9635\u56e0\u5f0f\u5206\u89e3\u7684\u6307\u9488\uff0c\u8be5\u6307\u9488\u5728\u6211\u4eec\u6bcf\u6b21\u66f4\u65b0\u96c5\u5404\u5e03\u77e9\u9635\u65f6\u88ab\u91cd\u7f6e\u3002\n\n// \uff08\u5982\u679c\u4f60\u60f3\u77e5\u9053\u4e3a\u4ec0\u4e48\u7a0b\u5e8f\u5bf9\u96c5\u5404\u5e03\u77e9\u9635\u4f7f\u7528\u76f4\u63a5\u5bf9\u8c61\uff0c\u800c\u5bf9\u56e0\u5f0f\u5206\u89e3\u4f7f\u7528\u6307\u9488\u3002\u6bcf\u6b21KINSOL\u8981\u6c42\u66f4\u65b0\u96c5\u5404\u5e03\u77e9\u9635\u65f6\uff0c\u6211\u4eec\u53ef\u4ee5\u7b80\u5355\u5730\u5199`jacobian_matrix=0;`\u5c06\u5176\u91cd\u7f6e\u4e3a\u4e00\u4e2a\u7a7a\u77e9\u9635\uff0c\u7136\u540e\u6211\u4eec\u53ef\u4ee5\u518d\u6b21\u586b\u5145\u3002\u53e6\u4e00\u65b9\u9762\uff0cSparseDirectUMFPACK\u7c7b\u6ca1\u6709\u529e\u6cd5\u6254\u6389\u5b83\u7684\u5185\u5bb9\u6216\u7528\u65b0\u7684\u56e0\u5f0f\u5206\u89e3\u6765\u66ff\u6362\u5b83\uff0c\u6240\u4ee5\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u6307\u9488\u3002\u6211\u4eec\u53ea\u662f\u6254\u6389\u6574\u4e2a\u5bf9\u8c61\uff0c\u5e76\u5728\u6211\u4eec\u6709\u65b0\u7684\u96c5\u5404\u5e03\u77e9\u9635\u9700\u8981\u5206\u89e3\u65f6\u521b\u5efa\u4e00\u4e2a\u65b0\u7684\u5bf9\u8c61\u3002)\n\n// \u6700\u540e\uff0c\u8be5\u7c7b\u6709\u4e00\u4e2a\u5b9a\u65f6\u5668\u53d8\u91cf\uff0c\u6211\u4eec\u5c06\u7528\u5b83\u6765\u8bc4\u4f30\u7a0b\u5e8f\u7684\u4e0d\u540c\u90e8\u5206\u9700\u8981\u591a\u957f\u65f6\u95f4\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u8bc4\u4f30KINSOL\u7684\u4e0d\u91cd\u5efa\u77e9\u9635\u53ca\u5176\u56e0\u5f0f\u5206\u89e3\u7684\u503e\u5411\u662f\u5426\u5408\u7406\u3002\u6211\u4eec\u5c06\u5728\u4e0b\u9762\u7684 \"\u7ed3\u679c \"\u90e8\u5206\u8ba8\u8bba\u8fd9\u4e2a\u95ee\u9898\u3002\n\n  template <int dim> \n  class MinimalSurfaceProblem \n  { \n  public: \n    MinimalSurfaceProblem(); \n    void run(); \n\n  private: \n    void setup_system(const bool initial_step); \n    void solve(const Vector<double> &rhs, \n               Vector<double> &      solution, \n               const double          tolerance); \n    void refine_mesh(); \n    void output_results(const unsigned int refinement_cycle); \n    void set_boundary_values(); \n    void compute_and_factorize_jacobian(const Vector<double> &evaluation_point); \n    void compute_residual(const Vector<double> &evaluation_point, \n                          Vector<double> &      residual); \n\n    Triangulation<dim> triangulation; \n\n    DoFHandler<dim> dof_handler; \n    FE_Q<dim>       fe; \n\n    AffineConstraints<double> hanging_node_constraints; \n\n    SparsityPattern                      sparsity_pattern; \n    SparseMatrix<double>                 jacobian_matrix; \n    std::unique_ptr<SparseDirectUMFPACK> jacobian_matrix_factorization; \n\n    Vector<double> current_solution; \n\n    TimerOutput computing_timer; \n  }; \n\n//  @sect3{Boundary condition}  \n\n// \u5b9e\u73b0\u8fb9\u754c\u503c\u7684\u7c7b\u662f\u5bf9  step-15  \u7684\u590d\u5236\u3002\n\n  template <int dim> \n  class BoundaryValues : 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  template <int dim> \n  double BoundaryValues<dim>::value(const Point<dim> &p, \n                                    const unsigned int /*component*/) const \n  { \n    return std::sin(2 * numbers::PI * (p[0] + p[1])); \n  } \n// @sect3{The <code>MinimalSurfaceProblem</code> class implementation}  \n// @sect4{Constructor and set up functions}  \n\n// \u4e0b\u9762\u7684\u51e0\u4e2a\u51fd\u6570\u4e5f\u57fa\u672c\u4e0a\u662f\u590d\u5236\u4e86 step-15 \u5df2\u7ecf\u505a\u7684\u4e8b\u60c5\uff0c\u6240\u4ee5\u6ca1\u6709\u4ec0\u4e48\u53ef\u8ba8\u8bba\u7684\u3002\n\n  template <int dim> \n  MinimalSurfaceProblem<dim>::MinimalSurfaceProblem() \n    : dof_handler(triangulation) \n    , fe(1) \n    , computing_timer(std::cout, TimerOutput::never, TimerOutput::wall_times) \n  {} \n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::setup_system(const bool initial_step) \n  { \n    TimerOutput::Scope t(computing_timer, \"set up\"); \n\n    if (initial_step) \n      { \n        dof_handler.distribute_dofs(fe); \n        current_solution.reinit(dof_handler.n_dofs()); \n\n        hanging_node_constraints.clear(); \n        DoFTools::make_hanging_node_constraints(dof_handler, \n                                                hanging_node_constraints); \n        hanging_node_constraints.close(); \n      } \n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp); \n\n    hanging_node_constraints.condense(dsp); \n\n    sparsity_pattern.copy_from(dsp); \n    jacobian_matrix.reinit(sparsity_pattern); \n    jacobian_matrix_factorization.reset(); \n  } \n\n//  @sect4{Assembling and factorizing the Jacobian matrix}  \n\n// \u7136\u540e\uff0c\u4e0b\u9762\u7684\u51fd\u6570\u8d1f\u8d23\u5bf9\u96c5\u5404\u5e03\u77e9\u9635\u8fdb\u884c\u7ec4\u88c5\u548c\u56e0\u5b50\u5316\u3002\u8be5\u51fd\u6570\u7684\u524d\u534a\u90e8\u5206\u5b9e\u8d28\u4e0a\u662f step-15 \u7684`assemble_system()`\u51fd\u6570\uff0c\u53ea\u662f\u5b83\u6ca1\u6709\u5904\u7406\u540c\u65f6\u5f62\u6210\u53f3\u624b\u8fb9\u7684\u5411\u91cf\uff08\u5373\u6b8b\u5dee\uff09\uff0c\u56e0\u4e3a\u6211\u4eec\u5e76\u4e0d\u603b\u662f\u8981\u540c\u65f6\u505a\u8fd9\u4e9b\u64cd\u4f5c\u3002\n\n// \u6211\u4eec\u628a\u6574\u4e2a\u88c5\u914d\u529f\u80fd\u653e\u5728\u4e00\u4e2a\u7531\u5927\u62ec\u53f7\u5305\u56f4\u7684\u4ee3\u7801\u5757\u4e2d\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u7528\u4e00\u4e2a TimerOutput::Scope \u53d8\u91cf\u6765\u8861\u91cf\u5728\u8fd9\u4e2a\u4ee3\u7801\u5757\u4e2d\u82b1\u8d39\u4e86\u591a\u5c11\u65f6\u95f4\uff0c\u4e0d\u5305\u62ec\u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\u53d1\u751f\u5728\u5339\u914d\u7684\u95ed\u5408\u62ec\u53f7`}`\u4e4b\u540e\u7684\u4e00\u5207\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::compute_and_factorize_jacobian( \n    const Vector<double> &evaluation_point) \n  { \n    { \n      TimerOutput::Scope t(computing_timer, \"assembling the Jacobian\"); \n\n      std::cout << \"  Computing Jacobian matrix\" << std::endl; \n\n      const QGauss<dim> quadrature_formula(fe.degree + 1); \n\n      jacobian_matrix = 0; \n\n      FEValues<dim> fe_values(fe, \n                              quadrature_formula, \n                              update_gradients | update_quadrature_points | \n                                update_JxW_values); \n\n      const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n      const unsigned int n_q_points    = quadrature_formula.size(); \n\n      FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n\n      std::vector<Tensor<1, dim>> evaluation_point_gradients(n_q_points); \n\n      std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n      for (const auto &cell : dof_handler.active_cell_iterators()) \n        { \n          cell_matrix = 0; \n\n          fe_values.reinit(cell); \n\n          fe_values.get_function_gradients(evaluation_point, \n                                           evaluation_point_gradients); \n\n          for (unsigned int q = 0; q < n_q_points; ++q) \n            { \n              const double coeff = \n                1.0 / std::sqrt(1 + evaluation_point_gradients[q] * \n                                      evaluation_point_gradients[q]); \n\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)    // ((\\nabla \\phi_i \n                         * coeff                       //   * a_n \n                         * fe_values.shape_grad(j, q)) //   * \\nabla \\phi_j) \n                        -                              //  - \n                        (fe_values.shape_grad(i, q)    //  (\\nabla \\phi_i \n                         * coeff * coeff * coeff       //   * a_n^3 \n                         * \n                         (fe_values.shape_grad(j, q)       //   * (\\nabla \\phi_j \n                          * evaluation_point_gradients[q]) //      * \\nabla u_n) \n                         * evaluation_point_gradients[q])) //   * \\nabla u_n))) \n                       * fe_values.JxW(q));                // * dx \n                } \n            } \n\n          cell->get_dof_indices(local_dof_indices); \n          hanging_node_constraints.distribute_local_to_global(cell_matrix, \n                                                              local_dof_indices, \n                                                              jacobian_matrix); \n        } \n\n      std::map<types::global_dof_index, double> boundary_values; \n      VectorTools::interpolate_boundary_values(dof_handler, \n                                               0, \n                                               Functions::ZeroFunction<dim>(), \n                                               boundary_values); \n      Vector<double> dummy_solution(dof_handler.n_dofs()); \n      Vector<double> dummy_rhs(dof_handler.n_dofs()); \n      MatrixTools::apply_boundary_values(boundary_values, \n                                         jacobian_matrix, \n                                         dummy_solution, \n                                         dummy_rhs); \n    } \n\n// \u8be5\u51fd\u6570\u7684\u540e\u534a\u90e8\u5206\u662f\u5bf9\u8ba1\u7b97\u51fa\u7684\u77e9\u9635\u8fdb\u884c\u56e0\u6570\u5206\u89e3\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u521b\u5efa\u4e00\u4e2a\u65b0\u7684SparseDirectUMFPACK\u5bf9\u8c61\uff0c\u5e76\u5c06\u5176\u5206\u914d\u7ed9\u6210\u5458\u53d8\u91cf`jacobian_matrix_factorization`\uff0c\u540c\u65f6\u9500\u6bc1\u8be5\u6307\u9488\u4e4b\u524d\u6307\u5411\u7684\u4efb\u4f55\u5bf9\u8c61\uff08\u5982\u679c\u6709\uff09\u3002\u7136\u540e\u6211\u4eec\u544a\u8bc9\u8be5\u5bf9\u8c61\u5bf9\u96c5\u5404\u5e03\u7cfb\u6570\u8fdb\u884c\u5206\u89e3\u3002\n\n// \u5982\u4e0a\u6240\u8ff0\uff0c\u6211\u4eec\u628a\u8fd9\u6bb5\u4ee3\u7801\u653e\u5728\u5927\u62ec\u53f7\u91cc\uff0c\u7528\u4e00\u4e2a\u8ba1\u65f6\u5668\u6765\u8bc4\u4f30\u8fd9\u90e8\u5206\u7a0b\u5e8f\u6240\u9700\u7684\u65f6\u95f4\u3002\n\n// (\u4e25\u683c\u6765\u8bf4\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u5b8c\u6210\u540e\u5b9e\u9645\u4e0a\u4e0d\u518d\u9700\u8981\u77e9\u9635\u4e86\uff0c\u6211\u4eec\u53ef\u4ee5\u628a\u77e9\u9635\u5bf9\u8c61\u6254\u6389\u3002\u4e00\u4e2a\u65e8\u5728\u63d0\u9ad8\u5185\u5b58\u6548\u7387\u7684\u4ee3\u7801\u4f1a\u8fd9\u6837\u505a\uff0c\u5e76\u4e14\u53ea\u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\u521b\u5efa\u77e9\u9635\u5bf9\u8c61\uff0c\u800c\u4e0d\u662f\u4f5c\u4e3a\u5468\u56f4\u7c7b\u7684\u6210\u5458\u53d8\u91cf\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u7701\u7565\u4e86\u8fd9\u4e00\u6b65\uff0c\u56e0\u4e3a\u4f7f\u7528\u4e0e\u4ee5\u524d\u7684\u6559\u7a0b\u7a0b\u5e8f\u76f8\u540c\u7684\u7f16\u7801\u98ce\u683c\u53ef\u4ee5\u57f9\u517b\u5bf9\u901a\u7528\u98ce\u683c\u7684\u719f\u6089\uff0c\u5e76\u6709\u52a9\u4e8e\u4f7f\u8fd9\u4e9b\u6559\u7a0b\u7a0b\u5e8f\u66f4\u5bb9\u6613\u9605\u8bfb)\u3002\n\n    { \n      TimerOutput::Scope t(computing_timer, \"factorizing the Jacobian\"); \n\n      std::cout << \"  Factorizing Jacobian matrix\" << std::endl; \n\n      jacobian_matrix_factorization = std::make_unique<SparseDirectUMFPACK>(); \n      jacobian_matrix_factorization->factorize(jacobian_matrix); \n    } \n  } \n\n//  @sect4{Computing the residual vector}  \n\n// `assemble_system()`\u5728 step-15 \u4e2d\u7528\u6765\u505a\u7684\u7b2c\u4e8c\u90e8\u5206\u662f\u8ba1\u7b97\u6b8b\u5dee\u5411\u91cf\uff0c\u4e5f\u5c31\u662f\u725b\u987f\u7ebf\u6027\u7cfb\u7edf\u7684\u53f3\u624b\u5411\u91cf\u3002\u6211\u4eec\u628a\u8fd9\u4e00\u70b9\u4ece\u524d\u9762\u7684\u51fd\u6570\u4e2d\u5206\u89e3\u51fa\u6765\uff0c\u4f46\u5982\u679c\u4f60\u7406\u89e3\u4e86 step-15 \u4e2d`assemble_system()`\u7684\u4f5c\u7528\uff0c\u4e0b\u9762\u7684\u51fd\u6570\u5c31\u4f1a\u5f88\u5bb9\u6613\u7406\u89e3\u3002\u7136\u800c\uff0c\u91cd\u8981\u7684\u662f\uff0c\u6211\u4eec\u9700\u8981\u8ba1\u7b97\u7684\u6b8b\u5dee\u4e0d\u662f\u56f4\u7ed5\u5f53\u524d\u89e3\u5411\u91cf\u7ebf\u6027\u5316\u7684\uff0c\u800c\u662f\u6211\u4eec\u4eceKINSOL\u5f97\u5230\u7684\u4efb\u4f55\u4e1c\u897f\u3002\u8fd9\u5bf9\u4e8e\u8bf8\u5982\u76f4\u7ebf\u641c\u7d22\u8fd9\u6837\u7684\u64cd\u4f5c\u662f\u5fc5\u8981\u7684\uff0c\u6211\u4eec\u60f3\u77e5\u9053\u5728\u4e0d\u540c\u7684 $\\alpha_k$ \u503c\u4e0b\uff0c\u6b8b\u5dee $F(U^k + \\alpha_k \\delta U^K)$ \u662f\u591a\u5c11\uff1b\u5728\u8fd9\u4e9b\u60c5\u51b5\u4e0b\uff0cKINSOL\u53ea\u662f\u7ed9\u6211\u4eec\u51fd\u6570 $F$ \u7684\u53c2\u6570\uff0c\u7136\u540e\u6211\u4eec\u5728\u8fd9\u65f6\u8ba1\u7b97\u6b8b\u5dee $F(\\cdot)$ \u3002\n\n// \u8be5\u51fd\u6570\u5728\u6700\u540e\u6253\u5370\u51fa\u5982\u6b64\u8ba1\u7b97\u7684\u6b8b\u5dee\u7684\u89c4\u8303\uff0c\u4f5c\u4e3a\u6211\u4eec\u8ddf\u8e2a\u7a0b\u5e8f\u8fdb\u5c55\u7684\u4e00\u79cd\u65b9\u5f0f\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::compute_residual( \n    const Vector<double> &evaluation_point, \n    Vector<double> &      residual) \n  { \n    TimerOutput::Scope t(computing_timer, \"assembling the residual\"); \n\n    std::cout << \"  Computing residual vector...\" << std::flush; \n\n    const QGauss<dim> quadrature_formula(fe.degree + 1); \n    FEValues<dim>     fe_values(fe, \n                            quadrature_formula, \n                            update_gradients | update_quadrature_points | \n                              update_JxW_values); \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    Vector<double>              cell_residual(dofs_per_cell); \n    std::vector<Tensor<1, dim>> evaluation_point_gradients(n_q_points); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        cell_residual = 0; \n        fe_values.reinit(cell); \n\n        fe_values.get_function_gradients(evaluation_point, \n                                         evaluation_point_gradients); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            const double coeff = \n              1.0 / std::sqrt(1 + evaluation_point_gradients[q] * \n                                    evaluation_point_gradients[q]); \n\n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              cell_residual(i) = (fe_values.shape_grad(i, q) // \\nabla \\phi_i \n                                  * coeff                    // * a_n \n                                  * evaluation_point_gradients[q] // * u_n \n                                  * fe_values.JxW(q));            // * dx \n          } \n\n        cell->get_dof_indices(local_dof_indices); \n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          residual(local_dof_indices[i]) += cell_residual(i); \n      } \n\n    hanging_node_constraints.condense(residual); \n\n    for (const types::global_dof_index i : \n         DoFTools::extract_boundary_dofs(dof_handler)) \n      residual(i) = 0; \n\n    for (const types::global_dof_index i : \n         DoFTools::extract_hanging_node_dofs(dof_handler)) \n      residual(i) = 0; \n\n    std::cout << \" norm=\" << residual.l2_norm() << std::endl; \n  } \n\n//  @sect4{Solving linear systems with the Jacobian matrix}  \n\n// \u63a5\u4e0b\u6765\u662f\u5b9e\u73b0\u7528\u96c5\u5404\u5e03\u77e9\u9635\u89e3\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\u3002\u7531\u4e8e\u6211\u4eec\u5728\u5efa\u7acb\u77e9\u9635\u65f6\u5df2\u7ecf\u5bf9\u77e9\u9635\u8fdb\u884c\u4e86\u56e0\u5f0f\u5206\u89e3\uff0c\u6240\u4ee5\u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u7684\u65b9\u6cd5\u5c31\u662f\u5c06\u9006\u77e9\u9635\u5e94\u7528\u4e8e\u7ed9\u5b9a\u7684\u53f3\u4fa7\u5411\u91cf\u3002\u8fd9\u5c31\u662f\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u7684 SparseDirectUMFPACK::vmult() \u51fd\u6570\u7684\u4f5c\u7528\u3002\u5728\u8fd9\u4e4b\u540e\uff0c\u6211\u4eec\u5fc5\u987b\u786e\u4fdd\u6211\u4eec\u4e5f\u80fd\u89e3\u51b3\u89e3\u5411\u91cf\u4e2d\u7684\u60ac\u7a7a\u8282\u70b9\u7684\u503c\uff0c\u800c\u8fd9\u662f\u7528 AffineConstraints::distribute(). \u6765\u5b8c\u6210\u7684\u3002\n\n// \u8be5\u51fd\u6570\u9700\u8981\u4e00\u4e2a\u989d\u5916\u7684\uff0c\u4f46\u672a\u4f7f\u7528\u7684\u53c2\u6570`tolerance`\uff0c\u5b83\u8868\u793a\u6211\u4eec\u5fc5\u987b\u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u7684\u7cbe\u786e\u7a0b\u5ea6\u3002\u8fd9\u4e2a\u53c2\u6570\u7684\u542b\u4e49\u5728\u4ecb\u7ecd\u4e2d\u7ed3\u5408 \"Eisenstat Walker\u6280\u5de7 \"\u8fdb\u884c\u4e86\u8ba8\u8bba\uff0c\u4f46\u7531\u4e8e\u6211\u4eec\u4f7f\u7528\u7684\u662f\u76f4\u63a5\u6c42\u89e3\u5668\u800c\u4e0d\u662f\u8fed\u4ee3\u6c42\u89e3\u5668\uff0c\u6240\u4ee5\u6211\u4eec\u5e76\u6ca1\u6709\u5229\u7528\u8fd9\u4e2a\u673a\u4f1a\u53ea\u6c42\u89e3\u7ebf\u6027\u7cfb\u7edf\u7684\u4e0d\u7cbe\u786e\u6027\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::solve(const Vector<double> &rhs, \n                                         Vector<double> &      solution, \n                                         const double /*tolerance*/) \n  { \n    TimerOutput::Scope t(computing_timer, \"linear system solve\"); \n\n    std::cout << \"  Solving linear system\" << std::endl; \n\n    jacobian_matrix_factorization->vmult(solution, rhs); \n\n    hanging_node_constraints.distribute(solution); \n  } \n\n//  @sect4{Refining the mesh, setting boundary values, and generating graphical output}  \n\n// \u4ee5\u4e0b\u4e09\u4e2a\u51fd\u6570\u53c8\u662f\u5bf9  step-15  \u4e2d\u7684\u51fd\u6570\u7684\u7b80\u5355\u590d\u5236\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::refine_mesh() \n  { \n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n\n    KellyErrorEstimator<dim>::estimate( \n      dof_handler, \n      QGauss<dim - 1>(fe.degree + 1), \n      std::map<types::boundary_id, const Function<dim> *>(), \n      current_solution, \n      estimated_error_per_cell); \n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    estimated_error_per_cell, \n                                                    0.3, \n                                                    0.03); \n\n    triangulation.prepare_coarsening_and_refinement(); \n\n    SolutionTransfer<dim> solution_transfer(dof_handler); \n    solution_transfer.prepare_for_coarsening_and_refinement(current_solution); \n\n    triangulation.execute_coarsening_and_refinement(); \n\n    dof_handler.distribute_dofs(fe); \n\n    Vector<double> tmp(dof_handler.n_dofs()); \n    solution_transfer.interpolate(current_solution, tmp); \n    current_solution = std::move(tmp); \n\n    hanging_node_constraints.clear(); \n\n    DoFTools::make_hanging_node_constraints(dof_handler, \n                                            hanging_node_constraints); \n    hanging_node_constraints.close(); \n\n    hanging_node_constraints.distribute(current_solution); \n\n    set_boundary_values(); \n\n    setup_system(/*initial_step=*/false); \n  } \n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::set_boundary_values() \n  { \n    std::map<types::global_dof_index, double> boundary_values; \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             0, \n                                             BoundaryValues<dim>(), \n                                             boundary_values); \n    for (const auto &boundary_value : boundary_values) \n      current_solution(boundary_value.first) = boundary_value.second; \n\n    hanging_node_constraints.distribute(current_solution); \n  } \n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::output_results( \n    const unsigned int refinement_cycle) \n  { \n    TimerOutput::Scope t(computing_timer, \"graphical output\"); \n\n    DataOut<dim> data_out; \n\n \n    data_out.add_data_vector(current_solution, \"solution\"); \n    data_out.build_patches(); \n\n    const std::string filename = \n      \"solution-\" + Utilities::int_to_string(refinement_cycle, 2) + \".vtu\"; \n    std::ofstream output(filename); \n    data_out.write_vtu(output); \n  } \n\n//  @sect4{The run() function and the overall logic of the program}  \n\n// \u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u552f\u4e00**\u6709\u8da3\u7684\u51fd\u6570\u662f\u9a71\u52a8\u6574\u4e2a\u7b97\u6cd5\u7684\u51fd\u6570\uff0c\u5373\u4ece\u4e00\u4e2a\u7c97\u5927\u7684\u7f51\u683c\u5f00\u59cb\uff0c\u505a\u4e00\u4e9b\u7f51\u683c\u7ec6\u5316\u5faa\u73af\uff0c\u5e76\u5728\u6bcf\u4e2a\u7f51\u683c\u4e0a\u4f7f\u7528KINSOL\u6765\u5bfb\u627e\u6211\u4eec\u4ece\u8fd9\u4e2a\u7f51\u683c\u4e0a\u79bb\u6563\u5316\u5f97\u5230\u7684\u975e\u7ebf\u6027\u4ee3\u6570\u65b9\u7a0b\u7684\u89e3\u3002\u4e0a\u9762\u7684`refine_mesh()`\u51fd\u6570\u53ef\u4ee5\u786e\u4fdd\u4e00\u4e2a\u7f51\u683c\u4e0a\u7684\u89e3\u88ab\u7528\u4f5c\u4e0b\u4e00\u4e2a\u7f51\u683c\u7684\u8d77\u59cb\u731c\u6d4b\u3002\u6211\u4eec\u8fd8\u4f7f\u7528\u4e00\u4e2aTimerOutput\u5bf9\u8c61\u6765\u6d4b\u91cf\u6bcf\u4e2a\u7f51\u683c\u4e0a\u7684\u6bcf\u4e00\u6b21\u64cd\u4f5c\u6240\u82b1\u8d39\u7684\u65f6\u95f4\uff0c\u5e76\u5728\u6bcf\u4e2a\u5468\u671f\u5f00\u59cb\u65f6\u91cd\u7f6e\u8be5\u8ba1\u65f6\u5668\u3002\n\n// \u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u6ca1\u6709\u5fc5\u8981\u7279\u522b\u7cbe\u786e\u5730\u89e3\u51b3\u7c97\u7565\u7f51\u683c\u4e0a\u7684\u95ee\u9898\uff0c\u56e0\u4e3a\u8fd9\u4e9b\u95ee\u9898\u53ea\u80fd\u4f5c\u4e3a\u4e0b\u4e00\u4e2a\u7f51\u683c\u7684\u8d77\u59cb\u731c\u6d4b\u6765\u89e3\u51b3\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5c06\u5728 $k$ \u4e2a\u7f51\u683c\u7ec6\u5316\u5468\u671f\u4e2d\u4f7f\u7528 $\\tau=10^{-3} \\frac{1}{10^k}$ \u7684\u76ee\u6807\u516c\u5dee\u3002\n\n// \u6240\u6709\u8fd9\u4e9b\u90fd\u5728\u8fd9\u4e2a\u51fd\u6570\u7684\u7b2c\u4e00\u90e8\u5206\u8fdb\u884c\u4e86\u7f16\u7801\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::run() \n  { \n    GridGenerator::hyper_ball(triangulation); \n    triangulation.refine_global(2); \n\n    setup_system(/*initial_step=*/true); \n    set_boundary_values(); \n\n    for (unsigned int refinement_cycle = 0; refinement_cycle < 6; \n         ++refinement_cycle) \n      { \n        computing_timer.reset(); \n        std::cout << \"Mesh refinement step \" << refinement_cycle << std::endl; \n\n        if (refinement_cycle != 0) \n          refine_mesh(); \n\n        const double target_tolerance = 1e-3 * std::pow(0.1, refinement_cycle); \n        std::cout << \"  Target_tolerance: \" << target_tolerance << std::endl \n                  << std::endl; \n\n// \u8fd9\u5c31\u662f\u6709\u8da3\u7684\u5f00\u59cb\u3002\u5728\u9876\u90e8\uff0c\u6211\u4eec\u521b\u5efa\u4e86KINSOL\u6c42\u89e3\u5668\u5bf9\u8c61\uff0c\u5e76\u7ed9\u5b83\u63d0\u4f9b\u4e86\u4e00\u4e2a\u5bf9\u8c61\uff0c\u8be5\u5bf9\u8c61\u7f16\u7801\u4e86\u4e00\u4e9b\u989d\u5916\u7684\u5177\u4f53\u60c5\u51b5\uff08\u5176\u4e2d\u6211\u4eec\u53ea\u6539\u53d8\u4e86\u6211\u4eec\u60f3\u8981\u8fbe\u5230\u7684\u975e\u7ebf\u6027\u5bb9\u5fcd\u5ea6\uff1b\u4f46\u4f60\u53ef\u80fd\u60f3\u770b\u770b SUNDIALS::KINSOL::AdditionalData \u7c7b\u6709\u54ea\u4e9b\u5176\u4ed6\u6210\u5458\uff0c\u5e76\u4e0e\u5b83\u4eec\u4e00\u8d77\u73a9\uff09\u3002\n\n        { \n          typename SUNDIALS::KINSOL<Vector<double>>::AdditionalData \n            additional_data; \n          additional_data.function_tolerance = target_tolerance; \n\n          SUNDIALS::KINSOL<Vector<double>> nonlinear_solver(additional_data); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u5fc5\u987b\u63cf\u8ff0\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u63d0\u5230\u7684\u64cd\u4f5c\u3002\u4ece\u672c\u8d28\u4e0a\u8bb2\uff0c\u6211\u4eec\u5fc5\u987b\u6559KINSOL\u5982\u4f55(i)\u5c06\u4e00\u4e2a\u5411\u91cf\u8c03\u6574\u5230\u6b63\u786e\u7684\u5927\u5c0f\uff0c(ii)\u8ba1\u7b97\u6b8b\u5dee\u5411\u91cf\uff0c(iii)\u8ba1\u7b97\u96c5\u5404\u5e03\u77e9\u9635\uff08\u5728\u8fd9\u671f\u95f4\u6211\u4eec\u4e5f\u8ba1\u7b97\u5176\u56e0\u5f0f\u5206\u89e3\uff09\uff0c\u4ee5\u53ca(iv)\u7528\u96c5\u5404\u5e03\u77e9\u9635\u89e3\u4e00\u4e2a\u7ebf\u6027\u7cfb\u7edf\u3002\n\n// \u6240\u6709\u8fd9\u56db\u79cd\u64cd\u4f5c\u90fd\u7531 SUNDIALS::KINSOL \u7c7b\u7684\u6210\u5458\u53d8\u91cf\u8868\u793a\uff0c\u8fd9\u4e9b\u6210\u5458\u53d8\u91cf\u7684\u7c7b\u578b\u662f `std::function`, \uff0c\u5373\u5b83\u4eec\u662f\u6211\u4eec\u53ef\u4ee5\u5206\u914d\u7ed9\u4e00\u4e2a\u51fd\u6570\u7684\u6307\u9488\u7684\u5bf9\u8c61\uff0c\u6216\u8005\u50cf\u6211\u4eec\u5728\u8fd9\u91cc\u505a\u7684\u90a3\u6837\uff0c\u4e00\u4e2a \"lambda\u51fd\u6570\"\uff0c\u5b83\u63a5\u53d7\u76f8\u5e94\u7684\u53c2\u6570\u5e76\u8fd4\u56de\u76f8\u5e94\u7684\u4fe1\u606f\u3002\u6309\u7167\u60ef\u4f8b\uff0cKINSOL\u5e0c\u671b\u505a\u4e00\u4e9b\u4e0d\u91cd\u8981\u7684\u4e8b\u60c5\u7684\u51fd\u6570\u8fd4\u56de\u4e00\u4e2a\u6574\u6570\uff0c\u5176\u4e2d0\u8868\u793a\u6210\u529f\u3002\u4e8b\u5b9e\u8bc1\u660e\uff0c\u6211\u4eec\u53ea\u9700\u752825\u884c\u4ee3\u7801\u5c31\u53ef\u4ee5\u5b8c\u6210\u6240\u6709\u8fd9\u4e9b\u5de5\u4f5c\u3002\n\n// \u5982\u679c\u4f60\u4e0d\u77e5\u9053\u4ec0\u4e48\u662f \"lambda\u51fd\u6570\"\uff0c\u53ef\u4ee5\u770b\u770b step-12 \u6216[wikipedia\u9875\u9762](https:en.wikipedia.org/wiki/Anonymous_function)\u5173\u4e8e\u8fd9\u4e2a\u95ee\u9898\u3002lambda\u51fd\u6570\u7684\u60f3\u6cd5\u662f\uff0c\u4eba\u4eec\u60f3\u7528\u4e00\u7ec4\u53c2\u6570\u6765\u5b9a\u4e49\u4e00\u4e2a\u51fd\u6570\uff0c\u4f46(i)\u4e0d\u4f7f\u5b83\u6210\u4e3a\u4e00\u4e2a\u547d\u540d\u7684\u51fd\u6570\uff0c\u56e0\u4e3a\u901a\u5e38\u60c5\u51b5\u4e0b\uff0c\u8be5\u51fd\u6570\u53ea\u5728\u4e00\u4e2a\u5730\u65b9\u4f7f\u7528\uff0c\u4f3c\u4e4e\u6ca1\u6709\u5fc5\u8981\u7ed9\u5b83\u4e00\u4e2a\u5168\u5c40\u540d\u79f0\uff1b(ii)\u8be5\u51fd\u6570\u53ef\u4ee5\u8bbf\u95ee\u5b58\u5728\u4e8e\u5b9a\u4e49\u5b83\u7684\u5730\u65b9\u7684\u4e00\u4e9b\u53d8\u91cf\uff0c\u5305\u62ec\u6210\u5458\u53d8\u91cf\u3002lambda\u51fd\u6570\u7684\u8bed\u6cd5\u5f88\u7b28\u62d9\uff0c\u4f46\u6700\u7ec8\u8fd8\u662f\u5f88\u6709\u7528\u7684\uff09\u3002)\n\n// \u5728\u4ee3\u7801\u5757\u7684\u6700\u540e\uff0c\u6211\u4eec\u544a\u8bc9KINSOL\u53bb\u5de5\u4f5c\uff0c\u89e3\u51b3\u6211\u4eec\u7684\u95ee\u9898\u3002\u4ece'residual'\u3001'setup_jacobian'\u548c'solve_jacobian_system'\u51fd\u6570\u4e2d\u8c03\u7528\u7684\u6210\u5458\u51fd\u6570\u5c06\u5411\u5c4f\u5e55\u6253\u5370\u8f93\u51fa\uff0c\u4f7f\u6211\u4eec\u80fd\u591f\u8ddf\u8e2a\u7a0b\u5e8f\u7684\u8fdb\u5c55\u60c5\u51b5\u3002\n\n          nonlinear_solver.reinit_vector = [&](Vector<double> &x) { \n            x.reinit(dof_handler.n_dofs()); \n          }; \n\n          nonlinear_solver.residual = \n            [&](const Vector<double> &evaluation_point, \n                Vector<double> &      residual) { \n              compute_residual(evaluation_point, residual); \n\n              return 0; \n            }; \n\n          nonlinear_solver.setup_jacobian = \n            [&](const Vector<double> &current_u, \n                const Vector<double> & /*current_f*/) { \n              compute_and_factorize_jacobian(current_u); \n\n              return 0; \n            }; \n\n          nonlinear_solver.solve_with_jacobian = [&](const Vector<double> &rhs, \n                                                     Vector<double> &      dst, \n                                                     const double tolerance) { \n            this->solve(rhs, dst, tolerance); \n\n            return 0; \n          }; \n\n          nonlinear_solver.solve(current_solution); \n        } \n\n// \u5269\u4e0b\u7684\u5c31\u53ea\u662f\u5185\u52a1\u6574\u7406\u4e86\u3002\u5c06\u6570\u636e\u5199\u5165\u6587\u4ef6\uff0c\u4ee5\u4fbf\u8fdb\u884c\u53ef\u89c6\u5316\uff0c\u5e76\u663e\u793a\u6536\u96c6\u5230\u7684\u65f6\u95f4\u6458\u8981\uff0c\u4ee5\u4fbf\u6211\u4eec\u53ef\u4ee5\u89e3\u91ca\u6bcf\u4e2a\u64cd\u4f5c\u82b1\u4e86\u591a\u957f\u65f6\u95f4\uff0c\u6267\u884c\u7684\u9891\u7387\u5982\u4f55\uff0c\u7b49\u7b49\u3002\n\n        output_results(refinement_cycle); \n\n        computing_timer.print_summary(); \n\n        std::cout << std::endl; \n      } \n  } \n} // namespace Step77 \n\nint main() \n{ \n  try \n    { \n      using namespace Step77; \n\n      MinimalSurfaceProblem<2> laplace_problem_2d; \n      laplace_problem_2d.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\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\n", "meta": {"hexsha": "87d2efb3b84a55d9bf32ac89ddde96baf8768289", "size": 20524, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-77/step-77.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-77/step-77.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-77/step-77.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.7813620072, "max_line_length": 319, "alphanum_fraction": 0.6087020074, "num_tokens": 6559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5202751943311653}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\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#include <boost/config.hpp>\n#include <iostream>\n#include <algorithm>\n#include <boost/graph/adjacency_list.hpp>\n\nusing namespace std;\nusing namespace boost;\n\n/*\n  Vertex Basics\n\n  This example demonstrates the GGCL Vertex interface.\n\n  Sample output:\n\n  vertices(g) = 0 1 2 3 4\n  vertex id: 0\n  out-edges: (0,1) (0,2) (0,3) (0,4)\n  in-edges: (2,0) (3,0) (4,0)\n  adjacent vertices: 1 2 3 4\n\n  vertex id: 1\n  out-edges:\n  in-edges: (0,1) (3,1) (4,1)\n  adjacent vertices:\n\n  vertex id: 2\n  out-edges: (2,0) (2,4)\n  in-edges: (0,2)\n  adjacent vertices: 0 4\n\n  vertex id: 3\n  out-edges: (3,0) (3,1) (3,4)\n  in-edges: (0,3)\n  adjacent vertices: 0 1 4\n\n  vertex id: 4\n  out-edges: (4,0) (4,1)\n  in-edges: (0,4) (2,4) (3,4)\n  adjacent vertices: 0 1\n\n\n */\n\n/* some helper functors for output */\n\ntemplate < class Graph > struct print_edge\n{\n    print_edge(Graph& g) : G(g) {}\n\n    typedef typename boost::graph_traits< Graph >::edge_descriptor Edge;\n    typedef typename boost::graph_traits< Graph >::vertex_descriptor Vertex;\n    void operator()(Edge e) const\n    {\n        typename boost::property_map< Graph, vertex_index_t >::type id\n            = get(vertex_index, G);\n\n        Vertex src = source(e, G);\n        Vertex targ = target(e, G);\n\n        cout << \"(\" << id[src] << \",\" << id[targ] << \") \";\n    }\n\n    Graph& G;\n};\n\ntemplate < class Graph > struct print_index\n{\n    print_index(Graph& g) : G(g) {}\n\n    typedef typename boost::graph_traits< Graph >::vertex_descriptor Vertex;\n    void operator()(Vertex c) const\n    {\n        typename boost::property_map< Graph, vertex_index_t >::type id\n            = get(vertex_index, G);\n        cout << id[c] << \" \";\n    }\n\n    Graph& G;\n};\n\ntemplate < class Graph > struct exercise_vertex\n{\n    typedef typename boost::graph_traits< Graph >::vertex_descriptor Vertex;\n\n    exercise_vertex(Graph& _g) : g(_g) {}\n\n    void operator()(Vertex v) const\n    {\n        typename boost::property_map< Graph, vertex_index_t >::type id\n            = get(vertex_index, g);\n\n        cout << \"vertex id: \" << id[v] << endl;\n\n        cout << \"out-edges: \";\n        for_each(out_edges(v, g).first, out_edges(v, g).second,\n            print_edge< Graph >(g));\n\n        cout << endl;\n\n        cout << \"in-edges: \";\n        for_each(in_edges(v, g).first, in_edges(v, g).second,\n            print_edge< Graph >(g));\n\n        cout << endl;\n\n        cout << \"adjacent vertices: \";\n        for_each(adjacent_vertices(v, g).first, adjacent_vertices(v, g).second,\n            print_index< Graph >(g));\n        cout << endl << endl;\n    }\n\n    Graph& g;\n};\n\nint main()\n{\n    typedef adjacency_list< vecS, vecS, bidirectionalS > MyGraphType;\n\n    typedef pair< int, int > Pair;\n    Pair edge_array[11] = { Pair(0, 1), Pair(0, 2), Pair(0, 3), Pair(0, 4),\n        Pair(2, 0), Pair(3, 0), Pair(2, 4), Pair(3, 1), Pair(3, 4), Pair(4, 0),\n        Pair(4, 1) };\n\n    /* Construct a graph using the edge_array*/\n    MyGraphType g(5);\n    for (int i = 0; i < 11; ++i)\n        add_edge(edge_array[i].first, edge_array[i].second, g);\n\n    boost::property_map< MyGraphType, vertex_index_t >::type id\n        = get(vertex_index, g);\n\n    cout << \"vertices(g) = \";\n    boost::graph_traits< MyGraphType >::vertex_iterator vi;\n    for (vi = vertices(g).first; vi != vertices(g).second; ++vi)\n        std::cout << id[*vi] << \" \";\n    std::cout << std::endl;\n\n    /* Use the STL for_each algorithm to \"exercise\" all\n       of the vertices in the graph */\n    for_each(vertices(g).first, vertices(g).second,\n        exercise_vertex< MyGraphType >(g));\n\n    return 0;\n}\n", "meta": {"hexsha": "107fd5ebc86171ea1506a27ede0d825fdb80e424", "size": 3997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/vertex_basics.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.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": "3rdparty/boost_1_73_0/libs/graph/example/vertex_basics.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": "3rdparty/boost_1_73_0/libs/graph/example/vertex_basics.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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.7870967742, "max_line_length": 79, "alphanum_fraction": 0.5756817613, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.5202751902556951}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/min.hpp\n *\n * \\brief The \\c min operation.\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_MIN_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_MIN_HPP\n\n\n#include <boost/numeric/ublas/detail/config.hpp>\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublasx/detail/debug.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/ublas/traits.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <complex>\n#include <cstddef>\n#include <limits>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\n//@{ Declarations\n\n/**\n * \\brief Find the minimum element of the given vector expression.\n * \\tparam VectorExprT The type of the vector expression.\n * \\param ve The vector expression over which to iterate for finding the minimum\n *  element.\n * \\return The minimum element in the vector expression.\n *\n * \\author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt;\n */\ntemplate <typename VectorExprT>\ntypename vector_traits<VectorExprT>::value_type min(vector_expression<VectorExprT> const& ve);\n\n/**\n * \\brief Find the minimum element of the given matrix expression.\n * \\tparam MatrixExprT The type of the matrix expression.\n * \\param me The matrix expression over which to iterate for finding the minimum\n *  element.\n * \\return The minimum element in the matrix expression.\n *\n * \\author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt;\n */\ntemplate <typename MatrixExprT>\ntypename matrix_traits<MatrixExprT>::value_type min(matrix_expression<MatrixExprT> const& me);\n\n/**\n * \\brief Find the minimum element of each row in the given matrix expression.\n * \\tparam MatrixExprT The type of the matrix expression.\n * \\param me The matrix expression over which to iterate for finding the minimum\n *  element of each row.\n * \\return A vector containing the minimum element for each row in the given\n *  matrix expression.\n *\n * \\author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt;\n */\ntemplate <typename MatrixExprT>\nvector<typename matrix_traits<MatrixExprT>::value_type> min_rows(matrix_expression<MatrixExprT> const& me);\n\n/**\n * \\brief Find the minimum element of each column in the given matrix\n *  expression.\n * \\tparam MatrixExprT The type of the matrix expression.\n * \\param me The matrix expression over which to iterate for finding the minimum\n *  element of each column.\n * \\return A vector containing the minimum element for each column in the given\n *  matrix expression.\n *\n * \\author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt;\n */\ntemplate <typename MatrixExprT>\nvector<typename matrix_traits<MatrixExprT>::value_type> min_columns(matrix_expression<MatrixExprT> const& me);\n\n/**\n * \\brief Find the minimum element of the given vector expression.\n * \\tparam Dim The dimension number (for vector, only dimension 1 is valid).\n * \\tparam MatrixExprT The type of the vectovector expression.\n * \\param ve The vector expression over which to iterate for finding the minimum\n *  element over the given dimension.\n * \\return A vector of size 1 containing the minimum element of the given vector\n *  expression.\n *\n * This function is provided for the sake of usability, in order to make to make\n * the call to \\c size<1>(vec) a valid call.\n * For the same reason, the return type is a vector instead of a simple scalar.\n *\n * \\author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt;\n */\ntemplate <size_t Dim, typename VectorExprT>\nvector<typename vector_traits<VectorExprT>::value_type> min(vector_expression<VectorExprT> const& ve);\n\n/**\n * \\brief Find the minimum elements over the given dimension of the given matrix\n *  expression.\n * \\tparam Dim The dimension number (starting from 1).\n * \\tparam MatrixExprT The type of the matrix expression.\n * \\param me The matrix expression over which to iterate for finding the minimum\n *  element over the given dimension.\n * \\return A vector containing the minimum elements over the given dimension in\n *  the given matrix expression.\n *\n * \\author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt;\n */\ntemplate <size_t Dim, typename MatrixExprT>\nvector<typename matrix_traits<MatrixExprT>::value_type> min(matrix_expression<MatrixExprT> const& me);\n\n/**\n * \\brief Find the minimum elements over the given dimension tag of the given\n *  matrix expression.\n * \\tparam TagT The dimension tag type (e.g., tag::major).\n * \\tparam MatrixExprT The type of the matrix expression.\n * \\param me The matrix expression over which to iterate for finding the minimum\n *  element over the given dimension.\n * \\return A vector containing the minimum elements over the given dimension in\n *  the given matrix expression.\n *\n * \\author Marco Guazzone, &lt;marco.guazzone@gmail.com&gt;\n */\ntemplate <typename TagT, typename MatrixExprT>\nvector<typename matrix_traits<MatrixExprT>::value_type> min_by_tag(matrix_expression<MatrixExprT> const& me);\n\n//@} Declarations\n\n\nnamespace detail { namespace /*<unnamed>*/ {\n\n//@{ Declarations\n\n/// Helper function for implementing the 'less-than' relational operator over\n/// generic types.\ntemplate <typename T>\nbool less_than_impl(T a, T b);\n\n/// Helper function for implementing the 'less-than' relational operator over\n/// complex types.\ntemplate <typename T>\nbool less_than_impl(::std::complex<T> const& a, ::std::complex<T> const& b);\n\n/**\n * \\brief Helper class for real/complex infinity\n *\n * See Wolfram MathWorld (http://mathworld.wolfram.com/ComplexInfinity.html)\n * for a definition of complex infinity.\n */\ntemplate <typename T>\nstruct infinity;\n\n/**\n * \\brief Auxiliary class for computing the minimum elements over the given\n *  dimension for a container of the given category.\n * \\tparam Dim The dimension number (starting from 1).\n * \\tparam CategoryT The category type (e.g., vector_tag).\n */\ntemplate <std::size_t Dim, typename CategoryT>\nstruct min_by_dim_impl;\n\n/**\n * \\brief Auxiliary class for computing the minimum elements over the given\n *  dimension tag for a container of the given category.\n * \\tparam TagT The dimension tag type (e.g., tag::major).\n * \\tparam CategoryT The category type (e.g., vector_tag).\n * \\tparam OrientationT The orientation category type (e.g., row_major_tag).\n */\ntemplate <typename TagT, typename CategoryT, typename OrientationT>\nstruct min_by_tag_impl;\n\n//@} Declarations\n\n\n//@{ Definitions\n\ntemplate <typename T>\nBOOST_UBLAS_INLINE\nbool less_than_impl(T a, T b)\n{\n\treturn a < b;\n}\n\n\ntemplate <typename T>\nBOOST_UBLAS_INLINE\nbool less_than_impl(::std::complex<T> const& a, ::std::complex<T> const& b)\n{\n\t// For complex numbers compare modulus and phase angle\n\t// Use the same logic used by MATLAB for the 'min' function:\n\t// \"For complex input A, min returns the complex number with the smallest\n\t//  complex modulus (magnitude), computed with min(abs(A)). Then\n\t//  computes the smallest phase angle with min(angle(x)), if necessary\"\n\n\tconst T ax(::std::abs(a));\n\tconst T bx(::std::abs(b));\n\treturn ax < bx\n\t\t   || (ax == bx && ::std::arg(a) < ::std::arg(b));\n}\n\n\ntemplate <typename T>\nstruct infinity\n{\n\tstatic const T value;\n};\ntemplate <typename T>\nconst T infinity<T>::value = ::std::numeric_limits<T>::has_infinity ? ::std::numeric_limits<T>::infinity() : ::std::numeric_limits<T>::max();\n\n\ntemplate <typename T>\nstruct infinity< ::std::complex<T> >\n{\n\tstatic const ::std::complex<T> value;\n};\ntemplate <typename T>\nconst ::std::complex<T> infinity< ::std::complex<T> >::value = ::std::complex<T>(infinity<T>::value,::std::numeric_limits<T>::quiet_NaN());\n\n\ntemplate <>\nstruct min_by_dim_impl<1, vector_tag>\n{\n\ttemplate <typename VectorExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename vector_traits<VectorExprT>::value_type> apply(vector_expression<VectorExprT> const& ve)\n\t{\n\t\ttypedef typename vector_traits<VectorExprT>::value_type value_type;\n\n\t\tvector<value_type> res(1);\n\n\t\tres(0) = min(ve);\n\n\t\treturn res;\n\t}\n};\n\n\ntemplate <>\nstruct min_by_dim_impl<1, matrix_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn min_rows(me);\n\t}\n};\n\n\ntemplate <>\nstruct min_by_dim_impl<2, matrix_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn min_columns(me);\n\t}\n};\n\n\ntemplate <>\nstruct min_by_tag_impl<tag::major, matrix_tag, row_major_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn min_rows(me);\n\t}\n};\n\n\ntemplate <>\nstruct min_by_tag_impl<tag::minor, matrix_tag, row_major_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn min_columns(me);\n\t}\n};\n\n\ntemplate <>\nstruct min_by_tag_impl<tag::leading, matrix_tag, row_major_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn min_columns(me);\n\t}\n};\n\n\ntemplate <>\nstruct min_by_tag_impl<tag::major, matrix_tag, column_major_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn min_columns(me);\n\t}\n};\n\n\ntemplate <>\nstruct min_by_tag_impl<tag::minor, matrix_tag, column_major_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn min_rows(me);\n\t}\n};\n\n\ntemplate <>\nstruct min_by_tag_impl<tag::leading, matrix_tag, column_major_tag>\n{\n\ttemplate <typename MatrixExprT>\n\tBOOST_UBLAS_INLINE\n\tstatic vector<typename matrix_traits<MatrixExprT>::value_type> apply(matrix_expression<MatrixExprT> const& me)\n\t{\n\t\treturn min_rows(me);\n\t}\n};\n\n\ntemplate <typename TagT>\nstruct min_by_tag_impl<TagT, matrix_tag, unknown_orientation_tag>: min_by_tag_impl<TagT, matrix_tag, row_major_tag>\n{\n\t// Empty\n};\n\n//@} Definitions\n\n}} // Namespace detail::<unnamed>\n\n\n//@{ Definitions\n\ntemplate <typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename vector_traits<VectorExprT>::value_type min(vector_expression<VectorExprT> const& ve)\n{\n\ttypedef typename vector_traits<VectorExprT>::size_type size_type;\n\ttypedef typename vector_traits<VectorExprT>::value_type value_type;\n\n\tsize_type n = size(ve);\n/*\n\tvalue_type m = ::std::numeric_limits<value_type>::has_infinity\n\t\t\t\t   ? ::std::numeric_limits<value_type>::infinity()\n\t\t\t\t   : ::std::numeric_limits<value_type>::max();\n*/\n\tvalue_type m = detail::infinity<value_type>::value;\n\n\tfor (size_type i = 0; i < n; ++i)\n\t{\n//\t\tif (ve()(i) < m)\n\t\tif (detail::less_than_impl(ve()(i), m))\n\t\t{\n\t\t\tm = ve()(i);\n\t\t}\n\t}\n\n\treturn m;\n}\n\n\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<MatrixExprT>::value_type min(matrix_expression<MatrixExprT> const& me)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::size_type size_type;\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\n\tsize_type nr = num_rows(me);\n\tsize_type nc = num_columns(me);\n//\tvalue_type m = ::std::numeric_limits<value_type>::has_infinity\n//\t\t\t\t   ? ::std::numeric_limits<value_type>::infinity()\n//\t\t\t\t   : ::std::numeric_limits<value_type>::max();\n\tvalue_type m = detail::infinity<value_type>::value;\n\n\tfor (size_type r = 0; r < nr; ++r)\n\t{\n\t\tfor (size_type c = 0; c < nc; ++c)\n\t\t{\n//\t\t\tif (me()(r,c) < m)\n\t\t\tif (detail::less_than_impl(me()(r,c), m))\n\t\t\t{\n\t\t\t\tm = me()(r,c);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn m;\n}\n\n\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\nvector<typename matrix_traits<MatrixExprT>::value_type> min_rows(matrix_expression<MatrixExprT> const& me)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::size_type size_type;\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\n\tsize_type nr = num_rows(me);\n\tsize_type nc = num_columns(me);\n\n\tvector<value_type> res(nr);\n\tsize_type j = 0;\n\tfor (size_type r = 0; r < nr; ++r)\n\t{\n//\t\tvalue_type m = ::std::numeric_limits<value_type>::has_infinity\n//\t\t\t\t\t   ? ::std::numeric_limits<value_type>::infinity()\n//\t\t\t\t\t   : ::std::numeric_limits<value_type>::max();\n\t\tvalue_type m = detail::infinity<value_type>::value;\n\n\t\tfor (size_type c = 0; c < nc; ++c)\n\t\t{\n//\t\t\tif (me()(r,c) < m)\n\t\t\tif (detail::less_than_impl(me()(r,c), m))\n\t\t\t{\n\t\t\t\tm = me()(r,c);\n\t\t\t}\n\t\t}\n\n\t\tres(j++) = m;\n\t}\n\n\treturn res;\n}\n\n\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\nvector<typename matrix_traits<MatrixExprT>::value_type> min_columns(matrix_expression<MatrixExprT> const& me)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::size_type size_type;\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\n\tsize_type nr = num_rows(me);\n\tsize_type nc = num_columns(me);\n\n\tvector<value_type> res(nc);\n\tsize_type j = 0;\n\tfor (size_type c = 0; c < nc; ++c)\n\t{\n//\t\tvalue_type m = ::std::numeric_limits<value_type>::has_infinity\n//\t\t\t\t\t   ? ::std::numeric_limits<value_type>::infinity()\n//\t\t\t\t\t   : ::std::numeric_limits<value_type>::max();\n\t\tvalue_type m = detail::infinity<value_type>::value;\n\n\t\tfor (size_type r = 0; r < nr; ++r)\n\t\t{\n//\t\t\tif (me()(r,c) < m)\n\t\t\tif (detail::less_than_impl(me()(r,c), m))\n\t\t\t{\n\t\t\t\tm = me()(r,c);\n\t\t\t}\n\t\t}\n\n\t\tres(j++) = m;\n\t}\n\n\treturn res;\n}\n\n\ntemplate <size_t Dim, typename VectorExprT>\nBOOST_UBLAS_INLINE\nvector<typename vector_traits<VectorExprT>::value_type> min(vector_expression<VectorExprT> const& ve)\n{\n\treturn detail::min_by_dim_impl<Dim, vector_tag>::template apply(ve);\n}\n\n\ntemplate <size_t Dim, typename MatrixExprT>\nBOOST_UBLAS_INLINE\nvector<typename matrix_traits<MatrixExprT>::value_type> min(matrix_expression<MatrixExprT> const& me)\n{\n\treturn detail::min_by_dim_impl<Dim, matrix_tag>::template apply(me);\n}\n\n\ntemplate <typename TagT, typename MatrixExprT>\n//template <typename MatrixExprT, typename TagT>\nBOOST_UBLAS_INLINE\nvector<typename matrix_traits<MatrixExprT>::value_type> min_by_tag(matrix_expression<MatrixExprT> const& me)\n{\n\treturn detail::min_by_tag_impl<TagT, matrix_tag, typename matrix_traits<MatrixExprT>::orientation_category>::template apply(me);\n}\n\n//@} Definitions\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_MIN_HPP\n", "meta": {"hexsha": "8db4917ed6d49eebc5c5d7deb6ae513bd5820801", "size": 14824, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/min.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/min.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/min.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": 28.6177606178, "max_line_length": 141, "alphanum_fraction": 0.7385995683, "num_tokens": 3749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5202751897692418}}
{"text": "#include \"plugin_graph_algorithm.h\"\n\n#include \"core/log.h\"\n\n#include \"netlist/gate.h\"\n#include \"netlist/net.h\"\n#include \"netlist/netlist.h\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/graph_traits.hpp>\n\nstd::map<std::shared_ptr<gate>, std::tuple<std::vector<std::shared_ptr<gate>>, int>> plugin_graph_algorithm::get_dijkstra_shortest_paths(const std::shared_ptr<gate> g)\n{\n    if (g == nullptr)\n    {\n        log_error(this->get_name(), \"parameter 'g' is nullptr\");\n        return {};\n    }\n\n    /*\n     * boost graph definition for a directed graph\n     *\n     * boost::adjacency_list - adjacency list\n     * boost::listS - stores edge set of each vertex in a list\n     * boost::vecS - stores the vertex set in a vector\n     * boost::directedS - graph is directed\n     * boost::no_property - no information stored to vertex\n     * boost::property<boost::edge_weight_t, int> - weight information stored to edge\n     */\n    typedef boost::adjacency_list<boost::listS, boost::vecS, boost::directedS, boost::no_property, boost::property<boost::edge_weight_t, int>> boost_graph_t;\n\n    /*\n     * boost vertex definition for the boost_graph_t \n     */\n    typedef boost::graph_traits<boost_graph_t>::vertex_descriptor vertex_t;\n\n    boost_graph_t boost_graph;\n\n    // add gates ordered by id (for determinisitc behavior) to boost graph\n    // vertices in boost graph are ordered from 0, 1, ...\n    auto nl = g->get_netlist();\n    std::set<u32> gate_ids;\n    for (const auto& gate : nl->get_gates())\n        gate_ids.insert(gate->get_id());\n\n    std::map<u32, vertex_t> gate_id_to_vertex;\n    std::map<vertex_t, u32> vertex_id_to_gate_id;\n\n    u32 vertex_id_cnt = 0;\n    for (const auto& gate_id : gate_ids)\n    {\n        auto vd                               = boost::add_vertex(boost_graph);\n        gate_id_to_vertex[gate_id]            = vd;\n        vertex_id_to_gate_id[vertex_id_cnt++] = gate_id;\n    }\n\n    // add ordered weigthened edges (weight = 1) to directed boost graph\n    std::map<u32, std::shared_ptr<net>> ordered_nets;\n    for (const auto& net : nl->get_nets())\n        ordered_nets[net->get_id()] = net;\n\n    for (const auto& it : ordered_nets)\n    {\n        if (it.second->get_src().gate == nullptr)\n            continue;\n\n        std::set<u32> dst_ids;\n        for (auto dst : it.second->get_dsts())\n            dst_ids.insert(dst.gate->get_id());\n\n        for (const auto& dst_id : dst_ids)\n            boost::add_edge(gate_id_to_vertex[it.second->get_src().gate->get_id()], gate_id_to_vertex[dst_id], 1, boost_graph);\n    }\n\n    // initialize parameters for dijkstra_shortest_paths()\n    std::vector<vertex_t> predecessors(nl->get_gates().size());\n    std::vector<int> distance(nl->get_gates().size());\n\n    dijkstra_shortest_paths(boost_graph,\n                            gate_id_to_vertex[g->get_id()],\n                            predecessor_map(boost::make_iterator_property_map(predecessors.begin(), get(boost::vertex_index, boost_graph)))\n                                .distance_map(boost::make_iterator_property_map(distance.begin(), get(boost::vertex_index, boost_graph))));\n\n    // postprocess boost result\n    std::map<std::shared_ptr<gate>, std::tuple<std::vector<std::shared_ptr<gate>>, int>> result;\n    boost::graph_traits<boost_graph_t>::vertex_iterator vi, vend;\n    for (boost::tie(vi, vend) = boost::vertices(boost_graph); vi != vend; ++vi)\n    {\n        if (distance[*vi] == ((i64)1 << 31) - 1)\n        {\n            // no path from g to gate\n            result[nl->get_gate_by_id(vertex_id_to_gate_id[*vi])] = std::make_tuple(std::vector<std::shared_ptr<gate>>(), -1);\n        }\n        else\n        {\n            // path from src to gate, so assemble path\n            std::vector<std::shared_ptr<gate>> path;\n            auto tmp = *vi;\n            while (vertex_id_to_gate_id[tmp] != g->get_id())\n            {\n                path.push_back(nl->get_gate_by_id(vertex_id_to_gate_id[tmp]));\n                tmp = predecessors[tmp];\n            }\n            path.push_back(g);\n            std::reverse(path.begin(), path.end());\n            result[nl->get_gate_by_id(vertex_id_to_gate_id[*vi])] = std::make_tuple(path, distance[*vi]);\n        }\n    }\n    return result;\n}\n", "meta": {"hexsha": "1b9966ecce56bd807c7bff88a1bcefcb8497fa28", "size": 4284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plugins/graph_algorithm/src/dijkstra_shortest_paths.cpp", "max_stars_repo_name": "swallat/hal", "max_stars_repo_head_hexsha": "98b08ac69448c2d7067f1bdd53ba428548c87cc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-13T17:14:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-13T17:14:35.000Z", "max_issues_repo_path": "plugins/graph_algorithm/src/dijkstra_shortest_paths.cpp", "max_issues_repo_name": "swallat/hal", "max_issues_repo_head_hexsha": "98b08ac69448c2d7067f1bdd53ba428548c87cc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plugins/graph_algorithm/src/dijkstra_shortest_paths.cpp", "max_forks_repo_name": "swallat/hal", "max_forks_repo_head_hexsha": "98b08ac69448c2d7067f1bdd53ba428548c87cc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T23:38:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-09T23:38:55.000Z", "avg_line_length": 38.25, "max_line_length": 167, "alphanum_fraction": 0.6251167134, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439707, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5200692231054429}}
{"text": "#include <ceres/ceres.h>\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n#include <math.h>\n#include <pybind11/numpy.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <iostream>\n#include <thread>\nusing ceres::AutoDiffCostFunction;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solve;\nusing ceres::Solver;\nconst int kNumObservations = 8;\n\n#define STRINGIFY(x) #x\n#define MACRO_STRINGIFY(x) STRINGIFY(x)\nnamespace py = pybind11;\n\n// -------------\n// pure C++ code\n// -------------\nstruct Cost_FixedM_1mag {\n  Cost_FixedM_1mag(double x, double y, double z, double x2, double y2,\n                   double z2, double m)\n      : Bx(x),\n        By(y),\n        Bz(z),\n        Xs(x2),\n        Ys(y2),\n        Zs(z2),\n        M{m} {}  // init the sensor position and the magnitude reading.\n  template <typename T>\n  bool operator()(const T *const x, const T *const y, const T *const z,\n                  const T *const theta, const T *const phy, const T *const Gx,\n                  const T *const Gy, const T *const Gz, T *residual)\n      const {  // x y z is the coordinates of magnate j, m is the attributes of\n               // magate j, theta phy is the orientation of the magnate\n    Eigen::Matrix<T, 3, 1> VecM =\n        Eigen::Matrix<T, 3, 1>(sin(theta[0]) * cos(phy[0]),\n                               sin(theta[0]) * sin(phy[0]), cos(theta[0])) *\n        1e-7 * exp(M);\n    Eigen::Matrix<T, 3, 1> VecR =\n        Eigen::Matrix<T, 3, 1>(Xs - x[0], Ys - y[0], Zs - z[0]);\n    T NormR = VecR.norm();\n    Eigen::Matrix<T, 3, 1> B =\n        (3.0 * VecR * (VecM.transpose() * VecR) / pow(NormR, 5) -\n         VecM /\n             pow(NormR, 3));  // convert it's unit to correspond with the input\n    // std::cout << \"B= \" << (B(0, 0) + Gx[0]) * 1e6 << \"\\t\" << (B(1, 0) +\n    // Gy[0]) * 1e6 << \"\\t\" << (B(2, 0) + Gz[0]) * 1e6 << \"\\n\"; std::cout <<\n    // B(0) << '\\n'\n    //           << B(1) << '\\n'\n    //           << B(2) << std::endl;\n    residual[0] = (B(0, 0) + Gx[0]) * 1e6 - Bx;\n    residual[1] = (B(1, 0) + Gy[0]) * 1e6 - By;\n    residual[2] = (B(2, 0) + Gz[0]) * 1e6 - Bz;\n    // std::cout << residual[0] << '\\t' << residual[1] << '\\t' << residual[2] <<\n    // std::endl;\n    return true;\n  }\n\n private:\n  const double Bx;\n  const double By;\n  const double Bz;\n  const double Xs;\n  const double Ys;\n  const double Zs;\n  const double M;\n};\n\nstruct Cost_FixedM_2mag {\n  Cost_FixedM_2mag(double Bx_, double By_, double Bz_, double Xs_, double Ys_,\n                   double Zs_, double m)\n      : Bx(Bx_),\n        By(By_),\n        Bz(Bz_),\n        Xs(Xs_),\n        Ys(Ys_),\n        Zs(Zs_),\n        M{m} {}  // init the sensor position and the magnitude reading.\n  template <typename T>\n  bool operator()(const T *const Gx, const T *const Gy, const T *const Gz,\n                  const T *const x0, const T *const y0, const T *const z0,\n                  const T *const theta0, const T *const phy0, const T *const x1,\n                  const T *const y1, const T *const z1, const T *const theta1,\n                  const T *const phy1, T *residual)\n      const {  // x y z is the coordinates of magnate j, m is the attributes of\n               // magate j, theta phy is the orientation of the magnate\n    // mag one\n    Eigen::Matrix<T, 3, 1> VecM0 =\n        Eigen::Matrix<T, 3, 1>(sin(theta0[0]) * cos(phy0[0]),\n                               sin(theta0[0]) * sin(phy0[0]), cos(theta0[0])) *\n        1e-7 * exp(M);\n    Eigen::Matrix<T, 3, 1> VecR0 =\n        Eigen::Matrix<T, 3, 1>(Xs - x0[0], Ys - y0[0], Zs - z0[0]);\n    T NormR0 = VecR0.norm();\n    Eigen::Matrix<T, 3, 1> B0 =\n        (3.0 * VecR0 * (VecM0.transpose() * VecR0) / pow(NormR0, 5) -\n         VecM0 /\n             pow(NormR0, 3));  // convert it's unit to correspond with the input\n    // mag two\n    Eigen::Matrix<T, 3, 1> VecM1 =\n        Eigen::Matrix<T, 3, 1>(sin(theta1[0]) * cos(phy1[0]),\n                               sin(theta1[0]) * sin(phy1[0]), cos(theta1[0])) *\n        1e-7 * exp(M);\n    Eigen::Matrix<T, 3, 1> VecR1 =\n        Eigen::Matrix<T, 3, 1>(Xs - x1[0], Ys - y1[0], Zs - z1[0]);\n    T NormR1 = VecR1.norm();\n    Eigen::Matrix<T, 3, 1> B1 =\n        (3.0 * VecR1 * (VecM1.transpose() * VecR1) / pow(NormR1, 5) -\n         VecM1 /\n             pow(NormR1, 3));  // convert it's unit to correspond with the input\n\n    residual[0] = (B0(0, 0) + B1(0, 0) + Gx[0]) * 1e6 - Bx;\n    residual[1] = (B0(1, 0) + B1(1, 0) + Gy[0]) * 1e6 - By;\n    residual[2] = (B0(2, 0) + B1(2, 0) + Gz[0]) * 1e6 - Bz;\n    // std::cout << residual[0] << '\\t' << residual[1] << '\\t' << residual[2] <<\n    // std::endl;\n    return true;\n  }\n\n private:\n  const double Bx;\n  const double By;\n  const double Bz;\n  const double Xs;\n  const double Ys;\n  const double Zs;\n  const double M;\n};\n\nstd::vector<double> cal_Bi(double xs, double ys, double zs,\n                           std::vector<double> param) {\n  double x = param[4];\n  double y = param[5];\n  double z = param[6];\n  double theta = param[7];\n  double phy = param[8];\n  double Gx = param[0];\n  double Gy = param[1];\n  double Gz = param[2];\n  double M = param[3];\n\n  Eigen::Matrix<double, 3, 1> VecM =\n      Eigen::Matrix<double, 3, 1>(sin(theta) * cos(phy), sin(theta) * sin(phy),\n                                  cos(theta)) *\n      1e-7 * M;\n  Eigen::Matrix<double, 3, 1> VecR =\n      Eigen::Matrix<double, 3, 1>(xs - x, ys - y, zs - z);\n  double NormR = VecR.norm();\n  Eigen::Matrix<double, 3, 1> B =\n      (3.0 * VecR * (VecM.transpose() * VecR) / pow(NormR, 5) -\n       VecM / pow(NormR, 3));  // convert it's unit to correspond with the input\n\n  std::vector<double> reading = {(B(0, 0) + Gx) * 1e6, (B(1, 0) + Gy) * 1e6,\n                                 (B(2, 0) + Gz) * 1e6};\n  return reading;\n}\n\nclass MagCost : public ceres::SizedCostFunction<3, 1, 1, 1, 1, 1, 1, 1, 1> {\n public:\n  MagCost(const double Bx, const double By, const double Bz, const double Xs,\n          const double Ys, const double Zs, const double M)\n      : Bx_(Bx), By_(By), Bz_(Bz), Xs_(Xs), Ys_(Ys), Zs_(Zs), M_(M) {}\n  virtual ~MagCost() {}\n  virtual bool Evaluate(double const *const *parameters, double *residuals,\n                        double **jacobians) const {\n    double x = parameters[0][0];\n    double y = parameters[1][0];\n    double z = parameters[2][0];\n    double theta = parameters[3][0];\n    double phy = parameters[4][0];\n    double Gx = parameters[5][0];\n    double Gy = parameters[6][0];\n    double Gz = parameters[7][0];\n\n    Eigen::Matrix<double, 3, 1> VecM =\n        Eigen::Matrix<double, 3, 1>(sin(theta) * cos(phy),\n                                    sin(theta) * sin(phy), cos(theta)) *\n        1e-7 * exp(M_);\n    Eigen::Matrix<double, 3, 1> VecR =\n        Eigen::Matrix<double, 3, 1>(Xs_ - x, Ys_ - y, Zs_ - z);\n    double NormR = VecR.norm();\n    Eigen::Matrix<double, 3, 1> B =\n        (3.0 * VecR * (VecM.transpose() * VecR) / pow(NormR, 5) -\n         VecM /\n             pow(NormR, 3));  // convert it's unit to correspond with the input\n\n    residuals[0] = (B(0, 0) + Gx) * 1e6 - Bx_;\n    residuals[1] = (B(1, 0) + Gy) * 1e6 - By_;\n    residuals[2] = (B(2, 0) + Gz) * 1e6 - Bz_;\n\n    if (!jacobians) return true;\n\n    // calculate dx\n    double t1 = VecM.transpose() * VecR;\n    jacobians[0][0] =\n        1e6 * (5 * 3 * VecR(0, 0) * VecR(0, 0) * t1 / pow(NormR, 7) -\n               (2 * 3 * VecR(0, 0) * VecM(0, 0) + 3 * t1) / pow(NormR, 5));\n    jacobians[0][1] =\n        1e6 * (5 * 3 * VecR(0, 0) * VecR(1, 0) * t1 / pow(NormR, 7) -\n               (3 * VecR(0, 0) * VecM(1, 0) + 3 * VecR(1, 0) * VecM(0, 0)) /\n                   pow(NormR, 5));\n    jacobians[0][2] =\n        1e6 * (5 * 3 * VecR(0, 0) * VecR(2, 0) * t1 / pow(NormR, 7) -\n               (3 * VecR(0, 0) * VecM(2, 0) + 3 * VecR(2, 0) * VecM(0, 0)) /\n                   pow(NormR, 5));\n\n    // calculate dy\n    jacobians[1][0] =\n        1e6 * (5 * 3 * VecR(0, 0) * VecR(1, 0) * t1 / pow(NormR, 7) -\n               (3 * VecR(0, 0) * VecM(1, 0) + 3 * VecR(1, 0) * VecM(0, 0)) /\n                   pow(NormR, 5));\n    jacobians[1][1] =\n        1e6 * (5 * 3 * VecR(1, 0) * VecR(1, 0) * t1 / pow(NormR, 7) -\n               (2 * 3 * VecR(1, 0) * VecM(1, 0) + 3 * t1) / pow(NormR, 5));\n    jacobians[1][2] =\n        1e6 * (5 * 3 * VecR(1, 0) * VecR(2, 0) * t1 / pow(NormR, 7) -\n               (3 * VecR(1, 0) * VecM(2, 0) + 3 * VecR(2, 0) * VecM(1, 0)) /\n                   pow(NormR, 5));\n\n    // calculate dz\n    jacobians[2][0] =\n        1e6 * (5 * 3 * VecR(0, 0) * VecR(2, 0) * t1 / pow(NormR, 7) -\n               (3 * VecR(0, 0) * VecM(2, 0) + 3 * VecR(2, 0) * VecM(0, 0)) /\n                   pow(NormR, 5));\n    jacobians[2][1] =\n        1e6 * (5 * 3 * VecR(1, 0) * VecR(2, 0) * t1 / pow(NormR, 7) -\n               (3 * VecR(1, 0) * VecM(2, 0) + 3 * VecR(2, 0) * VecM(1, 0)) /\n                   pow(NormR, 5));\n    jacobians[2][2] =\n        1e6 * (5 * 3 * VecR(2, 0) * VecR(2, 0) * t1 / pow(NormR, 7) -\n               (2 * 3 * VecR(2, 0) * VecM(2, 0) + 3 * t1) / pow(NormR, 5));\n\n    // calculate d(theta)\n    double t2 = 1e-7 * exp(M_) *\n                (VecR(0, 0) * cos(phy) * cos(theta) +\n                 VecR(1, 0) * sin(phy) * cos(theta) - VecR(2, 0) * sin(theta));\n    jacobians[3][0] =\n        1e6 * (3 * VecR(0, 0) * t2 / pow(NormR, 5) -\n               1e-7 * exp(M_) * cos(phy) * cos(theta) / pow(NormR, 3));\n    jacobians[3][1] =\n        1e6 * (3 * VecR(1, 0) * t2 / pow(NormR, 5) -\n               1e-7 * exp(M_) * sin(phy) * cos(theta) / pow(NormR, 3));\n    jacobians[3][2] = 1e6 * (3 * VecR(2, 0) * t2 / pow(NormR, 5) +\n                             1e-7 * exp(M_) * sin(theta) / pow(NormR, 3));\n\n    // calculate d(phi)\n    double t3 = 1e-7 * exp(M_) *\n                (-VecR(0, 0) * sin(phy) * sin(theta) +\n                 VecR(1, 0) * sin(theta) * cos(phy));\n    jacobians[4][0] =\n        1e6 * (3 * VecR(0, 0) * t3 / pow(NormR, 5) +\n               1e-7 * exp(M_) * sin(phy) * sin(theta) / pow(NormR, 3));\n    jacobians[4][1] =\n        1e6 * (3 * VecR(1, 0) * t3 / pow(NormR, 5) -\n               1e-7 * exp(M_) * cos(phy) * sin(theta) / pow(NormR, 3));\n    jacobians[4][2] = 1e6 * (3 * VecR(2, 0) * t3 / pow(NormR, 5));\n\n    // calculate dG\n    jacobians[5][0] = 1e6;\n    jacobians[5][1] = 0;\n    jacobians[5][2] = 0;\n    jacobians[6][0] = 0;\n    jacobians[6][1] = 1e6;\n    jacobians[6][2] = 0;\n    jacobians[7][0] = 0;\n    jacobians[7][1] = 0;\n    jacobians[7][2] = 1e6;\n\n    return true;\n  }\n\n private:\n  const double Bx_;\n  const double By_;\n  const double Bz_;\n  const double Xs_;\n  const double Ys_;\n  const double Zs_;\n  const double M_;\n};\n\nstd::vector<double> solve_1mag(std::vector<double> readings,\n                               std::vector<double> pSensor,\n                               std::vector<double> init_param) {\n  // std::vector<float> test_vector = { 2,1,3 };\n  // Eigen::MatrixXf readings_vec = Eigen::Map<Eigen::Matrix<double, 8, 3>\n  // >(readings.data()); Eigen::MatrixXf pSensor_vec =\n  // Eigen::Map<Eigen::Matrix<double, 8, 3> >(pSensor.data());\n  Eigen::VectorXd readings_vec = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(\n      readings.data(), readings.size());\n  Eigen::VectorXd pSensor_vec = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(\n      pSensor.data(), pSensor.size());\n  // Eigen::MatrixXd readings_vec_1(&readings[0], 8, 3);\n  // Eigen::MatrixXd pSensor_vec_1(&pSensor[0], 8, 3);\n  // Eigen::Map<Eigen::MatrixXd> readings_vec(readings_vec_1.data(), 3, 8);\n  // Eigen::Map<Eigen::MatrixXd> pSensor_vec(pSensor_vec_1.data(), 3, 8);\n  // readings_vec = readings_vec.transpose();\n  // pSensor_vec = pSensor_vec.transpose();\n  // std::cout\n  //     << \"readings_vec: \" << readings_vec << \"\\n\";\n  // std::cout << \"pSensor_vec: \" << pSensor_vec << \"\\n\";\n\n  double Gx = init_param[0];\n  double Gy = init_param[1];\n  double Gz = init_param[2];\n  double m = init_param[3];\n  double x = init_param[4];\n  double y = init_param[5];\n  double z = init_param[6];\n  double theta = init_param[7];\n  double phy = init_param[8];\n  // std::cout << \"Initial x: \" << x << \" y: \" << y << \" z: \" << z << \" m: \" <<\n  // m << \" theta: \" << theta << \" phy: \" << phy << \" Gx: \" << Gx << \" Gy: \" <<\n  // Gy << \" Gz: \" << Gz << \"\\n\";\n  Problem problem;\n  for (int i = 0; i < int(pSensor_vec.size() / 3); ++i) {\n    // problem.AddResidualBlock(\n    //     new AutoDiffCostFunction<Cost, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1>(\n    //         new Cost(testdata(i, 0), testdata(i, 1), testdata(i, 2),\n    //         sPosition(i, 0), sPosition(i, 1), sPosition(i, 2))),\n    //     NULL, &x, &y, &z, &m, &theta, &phy, &Gx, &Gy, &Gz);\n\n    problem.AddResidualBlock(\n        new AutoDiffCostFunction<Cost_FixedM_1mag, 3, 1, 1, 1, 1, 1, 1, 1, 1>(\n            new Cost_FixedM_1mag(readings_vec[i * 3], readings_vec[i * 3 + 1],\n                                 readings_vec[i * 3 + 2], pSensor_vec[i * 3],\n                                 pSensor_vec[i * 3 + 1], pSensor_vec[i * 3 + 2],\n                                 m)),\n        NULL, &x, &y, &z, &theta, &phy, &Gx, &Gy, &Gz);\n  }\n  Solver::Options options;\n  // options.max_num_iterations = 1e6;\n  options.minimizer_type = ceres::TRUST_REGION;\n  options.trust_region_strategy_type = ceres::LEVENBERG_MARQUARDT;\n  options.minimizer_progress_to_stdout = false;\n  options.num_threads = std::thread::hardware_concurrency();\n  // options.sparse_linear_algebra_library_type = ceres::EIGEN_SPARSE;\n  options.max_num_iterations = 1e5;\n  // options.min_relative_decrease = 1e-16;\n  // options.max_num_consecutive_invalid_steps = 1e6;\n  // options.function_tolerance = 1e-32;\n  Solver::Summary summary;\n  Solve(options, &problem, &summary);\n  // std::cout << summary.FullReport() << \"\\n\";\n  // std::cout << \"Initial x: \" << 0.0 << \" y: \" << 0.0 << \" z: \" << 0.0 << \" m:\n  // \" << 0.0 << \" theta: \" << 0.0 << \" phy: \" << 0.0 << \"\\n\"; std::cout <<\n  // \"Final x: \" << x << \" y: \" << y << \" z: \" << z << \" m: \" << m << \" theta: \"\n  // << theta << \" phy: \" << phy << \" Gx: \" << Gx << \" Gy: \" << Gy << \" Gz: \" <<\n  // Gz << \"\\n\";\n\n  // set params\n  std::vector<double> result_vec = {Gx, Gy, Gz, m, x, y, z, theta, phy};\n  return result_vec;\n}\n\nstd::vector<double> solve_2mag(std::vector<double> readings,\n                               std::vector<double> pSensor,\n                               std::vector<double> init_param) {\n  // std::vector<float> test_vector = { 2,1,3 };\n  // Eigen::MatrixXf readings_vec = Eigen::Map<Eigen::Matrix<double, 8, 3>\n  // >(readings.data()); Eigen::MatrixXf pSensor_vec =\n  // Eigen::Map<Eigen::Matrix<double, 8, 3> >(pSensor.data());\n  Eigen::VectorXd readings_vec = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(\n      readings.data(), readings.size());\n  Eigen::VectorXd pSensor_vec = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(\n      pSensor.data(), pSensor.size());\n  // Eigen::MatrixXd readings_vec_1(&readings[0], 8, 3);\n  // Eigen::MatrixXd pSensor_vec_1(&pSensor[0], 8, 3);\n  // Eigen::Map<Eigen::MatrixXd> readings_vec(readings_vec_1.data(), 3, 8);\n  // Eigen::Map<Eigen::MatrixXd> pSensor_vec(pSensor_vec_1.data(), 3, 8);\n  // readings_vec = readings_vec.transpose();\n  // pSensor_vec = pSensor_vec.transpose();\n  // std::cout\n  //     << \"readings_vec: \" << readings_vec << \"\\n\";\n  // std::cout << \"pSensor_vec: \" << pSensor_vec << \"\\n\";\n\n  double Gx = init_param[0];\n  double Gy = init_param[1];\n  double Gz = init_param[2];\n  double m = init_param[3];\n  double x0 = init_param[4];\n  double y0 = init_param[5];\n  double z0 = init_param[6];\n  double theta0 = init_param[7];\n  double phy0 = init_param[8];\n  double x1 = init_param[9];\n  double y1 = init_param[10];\n  double z1 = init_param[11];\n  double theta1 = init_param[12];\n  double phy1 = init_param[13];\n\n  // std::cout << \"Initial x: \" << x << \" y: \" << y << \" z: \" << z << \" m: \" <<\n  // m << \" theta: \" << theta << \" phy: \" << phy << \" Gx: \" << Gx << \" Gy: \" <<\n  // Gy << \" Gz: \" << Gz << \"\\n\";\n  Problem problem;\n  for (int i = 0; i < int(pSensor_vec.size() / 3); ++i) {\n    // problem.AddResidualBlock(\n    //     new AutoDiffCostFunction<Cost, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1>(\n    //         new Cost(testdata(i, 0), testdata(i, 1), testdata(i, 2),\n    //         sPosition(i, 0), sPosition(i, 1), sPosition(i, 2))),\n    //     NULL, &x, &y, &z, &m, &theta, &phy, &Gx, &Gy, &Gz);\n\n    problem.AddResidualBlock(\n        new AutoDiffCostFunction<Cost_FixedM_2mag, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n                                 1, 1, 1, 1>(new Cost_FixedM_2mag(\n            readings_vec[i * 3], readings_vec[i * 3 + 1],\n            readings_vec[i * 3 + 2], pSensor_vec[i * 3], pSensor_vec[i * 3 + 1],\n            pSensor_vec[i * 3 + 2], m)),\n        NULL, &Gx, &Gy, &Gz, &x0, &y0, &z0, &theta0, &phy0, &x1, &y1, &z1,\n        &theta1, &phy1);\n  }\n  Solver::Options options;\n  // options.max_num_iterations = 1e6;\n  options.minimizer_type = ceres::TRUST_REGION;\n  options.trust_region_strategy_type = ceres::LEVENBERG_MARQUARDT;\n  options.minimizer_progress_to_stdout = false;\n  options.num_threads = std::thread::hardware_concurrency();\n  // options.sparse_linear_algebra_library_type = ceres::EIGEN_SPARSE;\n  options.max_num_iterations = 1e5;\n  // options.min_relative_decrease = 1e-16;\n  // options.max_num_consecutive_invalid_steps = 1e6;\n  // options.function_tolerance = 1e-32;\n  Solver::Summary summary;\n  Solve(options, &problem, &summary);\n  // std::cout << summary.FullReport() << \"\\n\";\n  // std::cout << \"Initial x: \" << 0.0 << \" y: \" << 0.0 << \" z: \" << 0.0 << \" m:\n  // \" << 0.0 << \" theta: \" << 0.0 << \" phy: \" << 0.0 << \"\\n\"; std::cout <<\n  // \"Final x: \" << x << \" y: \" << y << \" z: \" << z << \" m: \" << m << \" theta: \"\n  // << theta << \" phy: \" << phy << \" Gx: \" << Gx << \" Gy: \" << Gy << \" Gz: \" <<\n  // Gz << \"\\n\";\n\n  // set params\n  std::vector<double> result_vec = {Gx,     Gy,   Gz, m,  x0, y0,     z0,\n                                    theta0, phy0, x1, y1, z1, theta1, phy1};\n  return result_vec;\n}\n\nstd::vector<double> calB(std::vector<double> pSensor,\n                         std::vector<double> init_param) {\n  Eigen::VectorXd pSensor_vec = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(\n      pSensor.data(), pSensor.size());\n\n  double Gx = init_param[0];\n  double Gy = init_param[1];\n  double Gz = init_param[2];\n  double m = init_param[3];\n  double x = init_param[4];\n  double y = init_param[5];\n  double z = init_param[6];\n  double theta = init_param[7];\n  double phy = init_param[8];\n\n  std::vector<double> result, Bi;\n\n  for (int i = 0; i < int(pSensor_vec.size() / 3); ++i) {\n    Bi = cal_Bi(pSensor_vec[i * 3], pSensor_vec[i * 3 + 1],\n                pSensor_vec[i * 3 + 2], init_param);\n    result.insert(result.end(), Bi.begin(), Bi.end());\n  }\n\n  // set params\n  return result;\n}\n\n// wrap C++ function with NumPy array IO\npy::array_t<double> py_solve_1mag(\n    py::array_t<double, py::array::c_style | py::array::forcecast> readings,\n    py::array_t<double, py::array::c_style | py::array::forcecast> pSensor,\n    py::array_t<double, py::array::c_style | py::array::forcecast> init_param) {\n  // allocate std::vector (to pass to the C++ function)\n  std::vector<double> readings_vec(readings.size());\n  std::vector<double> pSensor_vec(pSensor.size());\n  std::vector<double> init_param_vec(init_param.size());\n\n  std::vector<double> result_vec(init_param.size());\n  // copy py::array -> std::vector\n  std::memcpy(readings_vec.data(), readings.data(),\n              readings.size() * sizeof(double));\n  std::memcpy(pSensor_vec.data(), pSensor.data(),\n              pSensor.size() * sizeof(double));\n  std::memcpy(init_param_vec.data(), init_param.data(),\n              init_param.size() * sizeof(double));\n\n  // call pure C++ function\n  result_vec = solve_1mag(readings_vec, pSensor_vec, init_param_vec);\n  // std::vector<double> result_vec = multiply(array_vec);\n  // multiply2(array_vec, result_vec);\n\n  // allocate py::array (to pass the result of the C++ function to Python)\n  auto result = py::array_t<double>(init_param.size());\n  auto result_buffer = result.request();\n  double *result_ptr = (double *)result_buffer.ptr;\n\n  // copy std::vector -> py::array\n  std::memcpy(result_ptr, result_vec.data(),\n              result_vec.size() * sizeof(double));\n\n  return result;\n}\n\npy::array_t<double> py_solve_2mag(\n    py::array_t<double, py::array::c_style | py::array::forcecast> readings,\n    py::array_t<double, py::array::c_style | py::array::forcecast> pSensor,\n    py::array_t<double, py::array::c_style | py::array::forcecast> init_param) {\n  // allocate std::vector (to pass to the C++ function)\n  std::vector<double> readings_vec(readings.size());\n  std::vector<double> pSensor_vec(pSensor.size());\n  std::vector<double> init_param_vec(init_param.size());\n\n  std::vector<double> result_vec(init_param.size());\n  // copy py::array -> std::vector\n  std::memcpy(readings_vec.data(), readings.data(),\n              readings.size() * sizeof(double));\n  std::memcpy(pSensor_vec.data(), pSensor.data(),\n              pSensor.size() * sizeof(double));\n  std::memcpy(init_param_vec.data(), init_param.data(),\n              init_param.size() * sizeof(double));\n\n  // call pure C++ function\n  result_vec = solve_2mag(readings_vec, pSensor_vec, init_param_vec);\n  // std::vector<double> result_vec = multiply(array_vec);\n  // multiply2(array_vec, result_vec);\n\n  // allocate py::array (to pass the result of the C++ function to Python)\n  auto result = py::array_t<double>(init_param.size());\n  auto result_buffer = result.request();\n  double *result_ptr = (double *)result_buffer.ptr;\n\n  // copy std::vector -> py::array\n  std::memcpy(result_ptr, result_vec.data(),\n              result_vec.size() * sizeof(double));\n\n  return result;\n}\n\npy::array_t<double> py_calB(\n    py::array_t<double, py::array::c_style | py::array::forcecast> pSensor,\n    py::array_t<double, py::array::c_style | py::array::forcecast> init_param) {\n  // allocate std::vector (to pass to the C++ function)\n  std::vector<double> pSensor_vec(pSensor.size());\n  std::vector<double> init_param_vec(init_param.size());\n\n  std::vector<double> result_vec;\n  // copy py::array -> std::vector\n  std::memcpy(pSensor_vec.data(), pSensor.data(),\n              pSensor.size() * sizeof(double));\n  std::memcpy(init_param_vec.data(), init_param.data(),\n              init_param.size() * sizeof(double));\n  // call pure C++ function\n\n  // std::vector<double> result_vec = multiply(array_vec);\n  result_vec = calB(pSensor_vec, init_param_vec);\n\n  // allocate py::array (to pass the result of the C++ function to Python)\n  int result_size;\n  if (init_param.size() == 9)\n    result_size = pSensor_vec.size();\n  else\n    result_size = (pSensor_vec.size() / 3 + 1) * 3;\n  // std::cout << result_size;\n  auto result = py::array_t<double>(result_size);\n  auto result_buffer = result.request();\n  double *result_ptr = (double *)result_buffer.ptr;\n\n  // copy std::vector -> py::array\n  std::memcpy(result_ptr, result_vec.data(),\n              result_vec.size() * sizeof(double));\n\n  return result;\n}\n\nPYBIND11_MODULE(cppsolver, m) {\n  m.doc() = R\"pbdoc(\n        Pybind11 example plugin\n        -----------------------\n\n        .. currentmodule:: cppsolver\n\n        .. autosummary::\n           :toctree: _generate\n\n           add\n           subtract\n    )pbdoc\";\n\n  m.def(\n      \"solve_1mag\", &py_solve_1mag,\n      \"solve using the given parameters, sensor readings and sensor positions\");\n\n  m.def(\n      \"solve_2mag\", &py_solve_2mag,\n      \"solve using the given parameters, sensor readings and sensor positions\");\n\n  m.def(\"calB\", &py_calB, \"Cal B given psensor and params\");\n\n#ifdef VERSION_INFO\n  m.attr(\"__version__\") = MACRO_STRINGIFY(VERSION_INFO);\n#else\n  m.attr(\"__version__\") = \"dev\";\n#endif\n}\n", "meta": {"hexsha": "c5786256643eb808468396fec75bb85075d8da10", "size": 23733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Codes/cpp_solver/src/cpp_solver_analytical.cpp", "max_stars_repo_name": "dychen24/magx", "max_stars_repo_head_hexsha": "3d72cfa447bcab050e97ee517b1688ef99dd480d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-11-16T06:01:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:09:14.000Z", "max_issues_repo_path": "Codes/cpp_solver/src/cpp_solver_analytical.cpp", "max_issues_repo_name": "dychen24/magx", "max_issues_repo_head_hexsha": "3d72cfa447bcab050e97ee517b1688ef99dd480d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Codes/cpp_solver/src/cpp_solver_analytical.cpp", "max_forks_repo_name": "dychen24/magx", "max_forks_repo_head_hexsha": "3d72cfa447bcab050e97ee517b1688ef99dd480d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-18T09:21:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T03:43:33.000Z", "avg_line_length": 38.906557377, "max_line_length": 80, "alphanum_fraction": 0.5535751907, "num_tokens": 8162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5200692208712409}}
{"text": "#ifndef TEST_HELPER_HH\n#define TEST_HELPER_HH\n\n#include <hpp/bezier-com-traj/solve.hh>\n#include <hpp/bezier-com-traj/common_solve_methods.hh>\n#include <hpp/centroidal-dynamics/centroidal_dynamics.hh>\n#include <boost/test/included/unit_test.hpp>\n\nusing bezier_com_traj::MatrixXX;\nusing bezier_com_traj::MatrixX3;\nusing bezier_com_traj::Matrix3;\nusing bezier_com_traj::VectorX;\nusing bezier_com_traj::Vector3;\n\n#define MASS 50.\n#define MU 0.5\n#define LX 0.2172        // contact surface size in x direction\n#define LY 0.138         // contact surface size in y direction\n#define KIN_X_MIN -0.7\n#define KIN_X_MAX  0.7\n#define KIN_Y_MIN -0.4\n#define KIN_Y_MAX  0.4\n#define KIN_Z_MIN  0\n#define KIN_Z_MAX  0.9\n#define EPSILON  1e-6\n\ntypedef std::pair<MatrixX3,VectorX> ConstraintsPair;\n\nstd::pair<MatrixX3, MatrixX3> generateKinematicsConstraints(){\n    // generate a simple polytgone  : faces aligned along x,y,z axis\n    // size : x [-0.5,0.5] ; y = [-0.3,1] ; z [0,0.8]\n    MatrixX3 N(6,3);\n    MatrixX3 V(6,3);\n\n    N.block<1,3>(0,0) = Vector3(-1,0,0);\n    V.block<1,3>(0,0) = Vector3(KIN_X_MIN,KIN_Y_MAX,0);\n    N.block<1,3>(1,0) = Vector3(0,1,0);\n    V.block<1,3>(1,0) = Vector3(KIN_X_MIN,KIN_Y_MAX,0);\n    N.block<1,3>(2,0) = Vector3(1,0,0);\n    V.block<1,3>(2,0) = Vector3(KIN_X_MAX,KIN_Y_MIN,0);\n    N.block<1,3>(3,0) = Vector3(0,-1,0);\n    V.block<1,3>(3,0) = Vector3(KIN_X_MAX,KIN_Y_MIN,0);\n    N.block<1,3>(4,0) = Vector3(0,0,-1);\n    V.block<1,3>(4,0) = Vector3(0,0,KIN_Z_MIN);\n    N.block<1,3>(5,0) = Vector3(0,0,1);\n    V.block<1,3>(5,0) = Vector3(0,0,KIN_Z_MAX);\n\n    return std::make_pair(N,V);\n}\n\n\nstd::pair<MatrixXX, VectorX> generateKinematicsConstraints(Matrix3 endEffRotation, Vector3 endEffTranslation){\n\n    std::pair<MatrixX3, MatrixX3> NV = generateKinematicsConstraints();\n    MatrixX3 N = NV.first;\n    MatrixX3 V = NV.second;\n    size_t numFaces = N.rows();\n    MatrixX3 A(numFaces,3);\n    VectorX b(numFaces);\n    VectorX n,v;\n\n    for(size_t i = 0 ; i < numFaces ; ++i){\n        n = endEffRotation * (N.block<1,3>(i,0).transpose());\n        v = endEffRotation * (V.block<1,3>(i,0).transpose()) + endEffTranslation;\n        A.block<1,3>(i,0) = n;\n        b[i] = v.dot(n);\n    }\n\n    return std::make_pair(A,b);\n}\n\nstd::pair<MatrixX3, MatrixX3> computeRectangularContacts(MatrixX3 normals, MatrixX3 positions, double size_X,double size_Y){\n    // TODO : consider normal != z (see code in rbprm :: stability.cc (or add it as dependency ?)\n\n    BOOST_CHECK(normals.rows() == positions.rows());\n    MatrixX3 rec_normals(normals.rows()*4,3);\n    MatrixX3 rec_positions(normals.rows()*4,3);\n\n    double lx = size_X/2.;\n    double ly = size_Y/2.;\n    MatrixX3 p(4,3);\n    p << lx,  ly, 0,\n         lx, -ly, 0,\n        -lx, -ly, 0,\n        -lx,  ly, 0;\n\n\n    for (long int ic = 0 ; ic < normals.rows() ; ++ic){\n        for (long int i = 0 ; i < 4 ; ++i){\n            rec_normals.block<1,3>(ic*4+i,0) = normals.block<1,3>(ic,0);\n            rec_positions.block<1,3>(ic*4+i,0) = positions.block<1,3>(ic,0) + p.block<1,3>(i,0);\n        }\n    }\n    return std::make_pair(rec_normals,rec_positions);\n}\n\ncentroidal_dynamics::Equilibrium ComputeContactCone(MatrixX3 normals, MatrixX3 positions, const centroidal_dynamics::EquilibriumAlgorithm algo = centroidal_dynamics::EQUILIBRIUM_ALGORITHM_PP){\n    centroidal_dynamics::Equilibrium contactCone(\"test-quasiStatic\", MASS,4,centroidal_dynamics::SOLVER_LP_QPOASES,true,10,false);\n    //centroidal_dynamics::EquilibriumAlgorithm alg = centroidal_dynamics::EQUILIBRIUM_ALGORITHM_PP;\n    contactCone.setNewContacts(positions,normals,MU,algo);\n    return contactCone;\n}\n\nstd::pair<MatrixXX, VectorX> generateStabilityConstraints(centroidal_dynamics::Equilibrium contactPhase,Vector3 acc = Vector3::Zero()){\n    const Vector3& g = contactPhase.m_gravity;\n    const Matrix3 gSkew = bezier_com_traj::skew(g);\n    const Matrix3 accSkew = bezier_com_traj::skew(acc);\n    // compute GIWC\n    centroidal_dynamics::MatrixXX Hrow;\n    VectorX h;\n    contactPhase.getPolytopeInequalities(Hrow,h);\n    MatrixXX H = -Hrow;\n    H.rowwise().normalize();\n    int dimH = (int)(H.rows());\n    MatrixXX mH = contactPhase.m_mass * H;\n    // constraints : mH[:,3:6] g^  x <= h + mH[:,0:3]g\n    // A = mH g^\n    // b = h + mHg\n    MatrixX3 A = mH.block(0,3,dimH,3) * (gSkew - accSkew);\n    VectorX b = h+mH.block(0,0,dimH,3)*(g - acc);\n    return std::make_pair(A,b);\n}\n\nstd::pair<MatrixXX, VectorX> generateStabilityConstraints(MatrixX3 normals, MatrixX3 positions,Vector3 acc = Vector3::Zero(), const centroidal_dynamics::EquilibriumAlgorithm algo = centroidal_dynamics::EQUILIBRIUM_ALGORITHM_PP){\n    std::pair<MatrixX3, MatrixX3> contacts = computeRectangularContacts(normals,positions,LX,LY);\n    centroidal_dynamics::Equilibrium contactPhase = ComputeContactCone(contacts.first,contacts.second, algo);\n    return generateStabilityConstraints(contactPhase,acc);\n}\n\nstd::pair<Matrix3, Vector3> computeCost(){\n    Matrix3 H = Matrix3::Identity();\n    Vector3 g = Vector3::Zero();\n    return std::make_pair(H,g);\n}\n\nstd::pair<MatrixX3,VectorX> generateConstraints(MatrixX3 normals, MatrixX3 positions,Matrix3 endEffRotation, Vector3 endEffTranslation){\n    std::pair<MatrixX3,VectorX> Ab = generateKinematicsConstraints(endEffRotation,endEffTranslation);\n    std::pair<MatrixX3,VectorX> Cd = generateStabilityConstraints(normals,positions);\n    size_t numIneq = Ab.first.rows() + Cd.first.rows();\n    MatrixXX M(numIneq,3);\n    VectorX  n(numIneq);\n    M.block(0,0,Ab.first.rows(),3) = Ab.first;\n    M.block(Ab.first.rows(),0,Cd.first.rows(),3) = Cd.first;\n    n.segment(0,Ab.first.rows()) = Ab.second;\n    n.segment(Ab.first.rows(),Cd.first.rows()) = Cd.second;\n    return std::make_pair(M,n);\n}\n\n\ndouble fRandom(double fMin, double fMax)\n{\n    double f = (double)std::rand() / RAND_MAX;\n    return fMin + f * (fMax - fMin);\n}\n\n\n\nConstraintsPair stackConstraints(const ConstraintsPair& Ab,const ConstraintsPair& Cd){\n    size_t numIneq = Ab.first.rows() + Cd.first.rows();\n    MatrixX3 M(numIneq,3);\n    VectorX  n(numIneq);\n    M.block(0,0,Ab.first.rows(),3) = Ab.first;\n    M.block(Ab.first.rows(),0,Cd.first.rows(),3) = Cd.first;\n    n.segment(0,Ab.first.rows()) = Ab.second;\n    n.segment(Ab.first.rows(),Cd.first.rows()) = Cd.second;\n    return std::make_pair(M,n);\n}\n\n\nbool verifyKinematicConstraints(const ConstraintsPair& Ab, const Vector3 &point){\n    for(long int i = 0 ; i < Ab.second.size() ; ++i){\n        if(Ab.first.block<1,3>(i,0).dot(point) > Ab.second[i] ){\n            return false;\n        }\n    }\n    return true;\n}\n\nbool verifyStabilityConstraintsDLP(centroidal_dynamics::Equilibrium contactPhase,Vector3 c,Vector3 /*dc*/, Vector3 ddc){\n    bool success(false);\n    double res;\n    centroidal_dynamics::Equilibrium contactPhaseDLP(contactPhase);\n    contactPhaseDLP.setAlgorithm(centroidal_dynamics::EQUILIBRIUM_ALGORITHM_DLP);\n    centroidal_dynamics::LP_status status = contactPhaseDLP.computeEquilibriumRobustness(c,ddc,res);\n    success = (status == centroidal_dynamics::LP_STATUS_OPTIMAL || status == centroidal_dynamics::LP_STATUS_UNBOUNDED);\n    if(success)\n        success = res>=-EPSILON;\n    if(!success)\n        std::cout << \"fail level \" << res << std::endl;\n    return success;\n}\n\nbool verifyStabilityConstraintsPP(centroidal_dynamics::Equilibrium contactPhase,Vector3 c,Vector3 /*dc*/, Vector3 acc){\n    // compute inequalities :\n    const Vector3& g = contactPhase.m_gravity;\n    const Matrix3 gSkew = bezier_com_traj::skew(g);\n    const Matrix3 accSkew = bezier_com_traj::skew(acc);\n    // compute GIWC\n    centroidal_dynamics::MatrixXX Hrow;\n    VectorX h;\n    contactPhase.getPolytopeInequalities(Hrow,h);\n    MatrixXX H = -Hrow;\n    H.rowwise().normalize();\n    int dimH = (int)(H.rows());\n    MatrixXX mH = contactPhase.m_mass * H;\n    // constraints : mH[:,3:6] g^  x <= h + mH[:,0:3]g\n    // A = mH g^\n    // b = h + mHg\n    MatrixX3 A = mH.block(0,3,dimH,3) * (gSkew - accSkew);\n    VectorX b = h+mH.block(0,0,dimH,3)*(g - acc);\n\n    // verify inequalities with c :\n    for(long int i = 0 ; i < b.size() ; ++i){\n        if(A.block<1,3>(i,0).dot(c) -EPSILON > b[i] ){\n            return false;\n        }\n    }\n    return true;\n}\n\n\n#endif // TEST_HELPER_HH\n", "meta": {"hexsha": "a99820f280b3023f640b015a15efc896b24c49c4", "size": 8237, "ext": "hh", "lang": "C++", "max_stars_repo_path": "tests/test_helper.hh", "max_stars_repo_name": "jmirabel/hpp-bezier-com-traj", "max_stars_repo_head_hexsha": "b6484f4538ee774c815133fae919784e5df08674", "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": "tests/test_helper.hh", "max_issues_repo_name": "jmirabel/hpp-bezier-com-traj", "max_issues_repo_head_hexsha": "b6484f4538ee774c815133fae919784e5df08674", "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/test_helper.hh", "max_forks_repo_name": "jmirabel/hpp-bezier-com-traj", "max_forks_repo_head_hexsha": "b6484f4538ee774c815133fae919784e5df08674", "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.9372197309, "max_line_length": 228, "alphanum_fraction": 0.6716037392, "num_tokens": 2598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6224593452091673, "lm_q1q2_score": 0.5200545456376966}}
{"text": "/*\n    Lightmetrica - A modern, research-oriented renderer\n\n    Copyright (c) 2015 Hisanari Otsu\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\n    THE SOFTWARE.\n*/\n\n#include \"manifoldutils.h\"\n#include \"debugio.h\"\n#include <cereal/archives/json.hpp>\n#include <cereal/types/vector.hpp>\n\n#if LM_COMPILER_MSVC\n#pragma warning(disable:4714)\n#pragma warning(disable:4701)\n#pragma warning(disable:4456)\n#include <Eigen/Dense>\n#else\n#include <eigen3/Eigen/Dense>\n#endif\n\n#define INVERSEMAP_MANIFOLDWALK_USE_EIGEN_SOLVER 1\n#define INVERSEMAP_MANIFOLDWALK_BETA_EXT 0\n\nLM_NAMESPACE_BEGIN\n\nusing Matrix = Eigen::Matrix<Float, Eigen::Dynamic, Eigen::Dynamic>;\nusing Vector = Eigen::Matrix<Float, Eigen::Dynamic, 1>;\n\ntemplate <class Archive>\nauto serialize(Archive& archive, Vec3& v) -> void\n{\n    archive(cereal::make_nvp(\"x\", v.x), cereal::make_nvp(\"y\", v.y), cereal::make_nvp(\"z\", v.z));\n}\n\n\nnamespace\n{\n\nauto SolveBlockLinearEq(const ConstraintJacobian& nablaC, const std::vector<Vec2>& V, std::vector<Vec2>& W) -> void\n{\n\tconst int n = (int)(nablaC.size());\n\tassert(V.size() == nablaC.size());\n\t\t\n\t// --------------------------------------------------------------------------------\n\n\t#pragma region LU decomposition\n\n\t// A'_{0,n-1} = B_{0,n-1}\n\t// B'_{0,n-2} = C_{0,n-2}\n\t// C'_{0,n-2} = A_{1,n-1}\n\tstd::vector<Mat2> L(n);\n\tstd::vector<Mat2> U(n);\n\t{\n\t\t// U_1 = A'_1\n\t\tU[0] = nablaC[0].B;\n\t\tfor (int i = 1; i < n; i++)\n\t\t{\n\t\t\tL[i] = nablaC[i].A * Math::Inverse(U[i-1]);\t\t// L_i = C'_i U_{i-1}^-1\n\t\t\tU[i] = nablaC[i].B - L[i] * nablaC[i-1].C;\t\t// U_i = A'_i - L_i * B'_{i-1}\n\t\t}\n\t}\n\n\t#pragma endregion\n\n\t// --------------------------------------------------------------------------------\n\n\t#pragma region Forward substitution\n \n\t// Solve L V' = V\n\tstd::vector<Vec2> Vp(n);\n\tVp[0] = V[0];\n\tfor (int i = 1; i < n; i++)\n\t{\n\t\t// V'_i = V_i - L_i V'_{i-1}\n\t\tVp[i] = V[i] - L[i] * Vp[i - 1];\n\t}\n\n\t#pragma endregion\n\n\t// --------------------------------------------------------------------------------\n\n\t#pragma region Backward substitution\n\n\tW.assign(n, Vec2());\n\n\t// Solve U_n W_n = V'_n\n\tW[n - 1] = Math::Inverse(U[n - 1]) * Vp[n - 1];\n\n\tfor (int i = n - 2; i >= 0; i--)\n\t{\n\t\t// Solve U_i W_i = V'_i - V_i W_{i+1}\n\t\tW[i] = Math::Inverse(U[i]) * (Vp[i] - V[i] * W[i + 1]);\n\t}\n\n\t#pragma endregion\n}\n\n}\n\n#if 1\nauto ManifoldUtils::ComputeConstraintJacobian(const Subpath& path, ConstraintJacobian& nablaC) -> void\n{\n\tconst int n = (int)(path.vertices.size());\n\tfor (int i = 1; i < n - 1; i++)\n\t{\n\t\t#pragma region Some precomputation\n\n        const auto vi  = path.vertices[i];\n        const auto vip = path.vertices[i - 1];\n        const auto vin = path.vertices[i + 1];\n\n\t\tconst auto& x  = vi.geom;\n\t\tconst auto& xp = vip.geom;\n\t\tconst auto& xn = vin.geom;\n\t\t\t\n\t\tconst auto wi  = Math::Normalize(xp.p - x.p);\n\t\tconst auto wo  = Math::Normalize(xn.p - x.p);\n        const auto eta = 1_f / vi.primitive->bsdf->Eta(x, wi);\n\t\tconst auto H   = Math::Normalize(wi + eta * wo);\n\n\t\tconst auto inv_wiL = 1_f / Math::Length(xp.p - x.p);     // ili\n\t\tconst auto inv_woL = 1_f / Math::Length(xn.p - x.p);     // ilo\n\t\tconst auto inv_HL  = 1_f / Math::Length(wi + eta * wo);  // ilh\n\t\t\t\n\t\tconst auto dot_H_n    = Math::Dot(x.sn, H);\n\t\tconst auto dot_H_dndu = Math::Dot(x.dndu, H);\n\t\tconst auto dot_H_dndv = Math::Dot(x.dndv, H);\n\t\tconst auto dot_u_n    = Math::Dot(x.dpdu, x.sn);\n\t\tconst auto dot_v_n    = Math::Dot(x.dpdv, x.sn);\n\n\t\tconst auto s = x.dpdu - dot_u_n * x.sn;\n\t\tconst auto t = x.dpdv - dot_v_n * x.sn;\n\n\t\tconst auto div_inv_wiL_HL = inv_wiL * inv_HL;         // ili := ili * ilh\n\t\tconst auto div_inv_woL_HL = inv_woL * inv_HL * eta;   // ilo := ilo * eta * ilh\n\n\t\t#pragma endregion\n\n\t\t// --------------------------------------------------------------------------------\n\n\t\t#pragma region Compute A_i (derivative w.r.t. x_{i-1})\n\t\t\t\n\t\t{\n\t\t\tconst auto tu = (xp.dpdu - wi * Math::Dot(wi, xp.dpdu)) * div_inv_wiL_HL;\n\t\t\tconst auto tv = (xp.dpdv - wi * Math::Dot(wi, xp.dpdv)) * div_inv_wiL_HL;\n\t\t\tconst auto dHdu = tu - H * Math::Dot(tu, H);\n\t\t\tconst auto dHdv = tv - H * Math::Dot(tv, H);\n\t\t\tnablaC[i-1].A = Mat2(\n\t\t\t\tMath::Dot(dHdu, s), Math::Dot(dHdu, t),\n\t\t\t\tMath::Dot(dHdv, s), Math::Dot(dHdv, t));\n\t\t}\n\n\t\t#pragma endregion\n\t\t\t\n\t\t// --------------------------------------------------------------------------------\n\n\t\t#pragma region Compute B_i (derivative w.r.t. x_i)\n\n\t\t{\n\t\t\tconst auto tu = -x.dpdu * (div_inv_wiL_HL + div_inv_woL_HL) + wi * (Math::Dot(wi, x.dpdu) * div_inv_wiL_HL) + wo * (Math::Dot(wo, x.dpdu) * div_inv_woL_HL);\n\t\t\tconst auto tv = -x.dpdv * (div_inv_wiL_HL + div_inv_woL_HL) + wi * (Math::Dot(wi, x.dpdv) * div_inv_wiL_HL) + wo * (Math::Dot(wo, x.dpdv) * div_inv_woL_HL);\n\t\t\tconst auto dHdu = tu - H * Math::Dot(tu, H);\n\t\t\tconst auto dHdv = tv - H * Math::Dot(tv, H);\n\t\t\tnablaC[i-1].B = Mat2(\n\t\t\t\tMath::Dot(dHdu, s) - Math::Dot(x.dpdu, x.dndu) * dot_H_n - dot_u_n * dot_H_dndu,\n\t\t\t\tMath::Dot(dHdu, t) - Math::Dot(x.dpdv, x.dndu) * dot_H_n - dot_v_n * dot_H_dndu,\n\t\t\t\tMath::Dot(dHdv, s) - Math::Dot(x.dpdu, x.dndv) * dot_H_n - dot_u_n * dot_H_dndv,\n\t\t\t\tMath::Dot(dHdv, t) - Math::Dot(x.dpdv, x.dndv) * dot_H_n - dot_v_n * dot_H_dndv);\n\t\t}\n\n\t\t#pragma endregion\n\t\t\t\n\t\t// --------------------------------------------------------------------------------\n\n\t\t#pragma region Compute C_i (derivative w.r.t. x_{i+1})\n\n\t\t{\n\t\t\tconst auto tu = (xn.dpdu - wo * Math::Dot(wo, xn.dpdu)) * div_inv_woL_HL;\n\t\t\tconst auto tv = (xn.dpdv - wo * Math::Dot(wo, xn.dpdv)) * div_inv_woL_HL;\n\t\t\tconst auto dHdu = tu - H * Math::Dot(tu, H);\n\t\t\tconst auto dHdv = tv - H * Math::Dot(tv, H);\n\t\t\tnablaC[i - 1].C = Mat2(\n\t\t\t\tMath::Dot(dHdu, s), Math::Dot(dHdu, t),\n\t\t\t\tMath::Dot(dHdv, s), Math::Dot(dHdv, t));\n\t\t}\n\n\t\t#pragma endregion\n\t}\n}\n#else\nauto ManifoldUtils::ComputeConstraintJacobian(const Subpath& path, ConstraintJacobian& nablaC) -> void\n{\n\tconst int n = (int)(path.vertices.size());\n\tfor (int i = 1; i < n - 1; i++)\n\t{\n\t\t#pragma region Some precomputation\n\n        const auto vi  = path.vertices[i];\n        const auto vip = path.vertices[i - 1];\n        const auto vin = path.vertices[i + 1];\n\n\t\tconst auto& x  = vi.geom;\n\t\tconst auto& xp = vip.geom;\n\t\tconst auto& xn = vin.geom;\n\t\t\t\n\t\tconst auto wi  = Math::Normalize(xp.p - x.p);\n\t\tconst auto wo  = Math::Normalize(xn.p - x.p);\n        const auto eta = 1_f / vi.primitive->bsdf->Eta(x, wi);\n        // No need to normalize H for index-matched materials or reflections\n        const bool normalizeH = eta != 1_f;\n\t\tconst auto H   = normalizeH ? Math::Normalize(wi + eta * wo) : wi + wo;\n\n\t\tconst auto inv_wiL = 1_f / Math::Length(xp.p - x.p);                        // ili\n\t\tconst auto inv_woL = 1_f / Math::Length(xn.p - x.p);                        // ilo\n        const auto inv_HL = normalizeH ? 1_f / Math::Length(wi + eta * wo) : 1_f;  // ilh\n\t\t\t\n\t\tconst auto dot_H_n    = Math::Dot(x.sn, H);\n\t\tconst auto dot_H_dndu = Math::Dot(x.dndu, H);\n\t\tconst auto dot_H_dndv = Math::Dot(x.dndv, H);\n\t\tconst auto dot_u_n    = Math::Dot(x.dpdu, x.sn);\n\t\tconst auto dot_v_n    = Math::Dot(x.dpdv, x.sn);\n\n\t\tconst auto s = x.dpdu - dot_u_n * x.sn;\n\t\tconst auto t = x.dpdv - dot_v_n * x.sn;\n\n\t\tconst auto div_inv_wiL_HL = inv_wiL * inv_HL;         // ili := ili * ilh\n\t\tconst auto div_inv_woL_HL = inv_woL * inv_HL * eta;   // ilo := ilo * eta * ilh\n\n\t\t#pragma endregion\n\n\t\t// --------------------------------------------------------------------------------\n\n\t\t#pragma region Compute A_i (derivative w.r.t. x_{i-1})\n\t\t\t\n\t\t{\n\t\t\tconst auto tu = (xp.dpdu - wi * Math::Dot(wi, xp.dpdu)) * div_inv_wiL_HL;\n\t\t\tconst auto tv = (xp.dpdv - wi * Math::Dot(wi, xp.dpdv)) * div_inv_wiL_HL;\n\t\t\tconst auto dHdu = normalizeH ? tu - H * Math::Dot(tu, H) : tu;\n\t\t\tconst auto dHdv = normalizeH ? tv - H * Math::Dot(tv, H) : tv;\n\t\t\tnablaC[i-1].A = Mat2(\n\t\t\t\tMath::Dot(dHdu, s), Math::Dot(dHdu, t),\n\t\t\t\tMath::Dot(dHdv, s), Math::Dot(dHdv, t));\n\t\t}\n\n\t\t#pragma endregion\n\t\t\t\n\t\t// --------------------------------------------------------------------------------\n\n\t\t#pragma region Compute B_i (derivative w.r.t. x_i)\n\n\t\t{\n\t\t\tconst auto tu = -x.dpdu * (div_inv_wiL_HL + div_inv_woL_HL) + wi * (Math::Dot(wi, x.dpdu) * div_inv_wiL_HL) + wo * (Math::Dot(wo, x.dpdu) * div_inv_woL_HL);\n\t\t\tconst auto tv = -x.dpdv * (div_inv_wiL_HL + div_inv_woL_HL) + wi * (Math::Dot(wi, x.dpdv) * div_inv_wiL_HL) + wo * (Math::Dot(wo, x.dpdv) * div_inv_woL_HL);\n\t\t\tconst auto dHdu = normalizeH ? tu - H * Math::Dot(tu, H) : tu;\n\t\t\tconst auto dHdv = normalizeH ? tv - H * Math::Dot(tv, H) : tv;\n\t\t\tnablaC[i-1].B = Mat2(\n\t\t\t\tMath::Dot(dHdu, s) - Math::Dot(x.dpdu, x.dndu) * dot_H_n - dot_u_n * dot_H_dndu,\n\t\t\t\tMath::Dot(dHdu, t) - Math::Dot(x.dpdv, x.dndu) * dot_H_n - dot_v_n * dot_H_dndu,\n\t\t\t\tMath::Dot(dHdv, s) - Math::Dot(x.dpdu, x.dndv) * dot_H_n - dot_u_n * dot_H_dndv,\n\t\t\t\tMath::Dot(dHdv, t) - Math::Dot(x.dpdv, x.dndv) * dot_H_n - dot_v_n * dot_H_dndv);\n\t\t}\n\n\t\t#pragma endregion\n\t\t\t\n\t\t// --------------------------------------------------------------------------------\n\n\t\t#pragma region Compute C_i (derivative w.r.t. x_{i+1})\n\n\t\t{\n\t\t\tconst auto tu = (xn.dpdu - wo * Math::Dot(wo, xn.dpdu)) * div_inv_woL_HL;\n\t\t\tconst auto tv = (xn.dpdv - wo * Math::Dot(wo, xn.dpdv)) * div_inv_woL_HL;\n\t\t\tconst auto dHdu = normalizeH ? tu - H * Math::Dot(tu, H) : tu;\n\t\t\tconst auto dHdv = normalizeH ? tv - H * Math::Dot(tv, H) : tv;\n\t\t\tnablaC[i - 1].C = Mat2(\n\t\t\t\tMath::Dot(dHdu, s), Math::Dot(dHdu, t),\n\t\t\t\tMath::Dot(dHdv, s), Math::Dot(dHdv, t));\n\t\t}\n\n\t\t#pragma endregion\n\t}\n}\n#endif\n\n// --------------------------------------------------------------------------------\n\nnamespace\n{\n    template <typename t_matrix>\n    t_matrix PseudoInverse(const t_matrix& m, const double &tolerance = 1.e-6)\n    {\n        using namespace Eigen;\n        typedef JacobiSVD<t_matrix> TSVD;\n        unsigned int svd_opt(ComputeThinU | ComputeThinV);\n        if (m.RowsAtCompileTime != Dynamic || m.ColsAtCompileTime != Dynamic)\n            svd_opt = ComputeFullU | ComputeFullV;\n        TSVD svd(m, svd_opt);\n        const typename TSVD::SingularValuesType &sigma(svd.singularValues());\n        typename TSVD::SingularValuesType sigma_inv(sigma.size());\n        for (long i = 0; i<sigma.size(); ++i)\n        {\n            if (sigma(i) > tolerance)\n                sigma_inv(i) = 1.0 / sigma(i);\n            else\n                sigma_inv(i) = 0.0;\n        }\n        return svd.matrixV()*sigma_inv.asDiagonal()*svd.matrixU().transpose();\n    }\n}\n\nauto ManifoldUtils::ComputeConstraintJacobianDeterminant(const Subpath& subpath) -> Float\n{\n    const int n = (int)(subpath.vertices.size());\n\n    // --------------------------------------------------------------------------------\n\n    ConstraintJacobian nablaC;\n    nablaC.assign(n - 2, VertexConstraintJacobian());\n    ComputeConstraintJacobian(subpath, nablaC);\n\n    // --------------------------------------------------------------------------------\n\n    // A\n    Matrix A;\n    A.setZero(2 * (n - 2), 2 * (n - 2));\n    for (int i = 0; i < n - 2; i++)\n    {\n        if (i > 0)\n        {\n            const auto& A_ = nablaC[i].A;\n            Eigen::Array22d m;\n            m << A_[0][0], A_[1][0],\n                 A_[0][1], A_[1][1];\n            A.block<2, 2>(i * 2, (i - 1) * 2) = m;\n        }\n        {\n            const auto& B_ = nablaC[i].B;\n            Eigen::Array22d m;\n            m << B_[0][0], B_[1][0],\n                 B_[0][1], B_[1][1];\n            A.block<2, 2>(i * 2, i * 2) = m;\n        }\n        if (i < n - 2 - 1)\n        {\n            const auto& C_ = nablaC[i].C;\n            Eigen::Array22d m;\n            m << C_[0][0], C_[1][0],\n                 C_[0][1], C_[1][1];\n            A.block<2, 2>(i * 2, (i + 1) * 2) = m;\n        }\n    }\n\n    // A^-1\n    const decltype(A) invA = A.inverse();\n    //const decltype(A) invA = PseudoInverse(A);\n\n    // P_2 A^-1 B_n\n    const auto Bn_np   = nablaC[n - 3].C;\n    const auto invA_0n = Mat2(invA(0, 2*(n-3)), invA(1, 2*(n-3)), invA(0, 2*(n-3)+1), invA(1, 2*(n-3)+1));\n    const auto invA_Bn = invA_0n * Bn_np;\n    const auto det     = invA_Bn[0][0] * invA_Bn[1][1] - invA_Bn[1][0] * invA_Bn[0][1];\n\n    // --------------------------------------------------------------------------------\n    return Math::Abs(det);\n}\n\nauto ManifoldUtils::WalkManifold(const Scene3* scene, const Subpath& seedPath, const Vec3& target) -> boost::optional<Subpath>\n{\n    Subpath subpath;\n    if (!WalkManifold(scene, seedPath, target, subpath))\n    {\n        return boost::none;\n    }\n    return subpath;\n}\n\n// Returns the converged path. Returns none if not converged.\nauto ManifoldUtils::WalkManifold(const Scene3* scene, const Subpath& seedPath, const Vec3& target, Subpath& connPath) -> bool\n{\n\t#pragma region Preprocess\n\n\t// Number of path vertices\n\tconst int n = (int)(seedPath.vertices.size());\n\n\t// Initial path\n    Subpath currP;\n    currP = seedPath;\n\n\t#pragma endregion\n\n    // --------------------------------------------------------------------------------\n\n    #if INVERSEMAP_MANIFOLDWALK_DEBUG_IO\n    LM_LOG_DEBUG(\"seed_path\");\n    {\n        DebugIO::Wait();\n        std::vector<double> vs;\n        for (const auto& v : currP.vertices)\n        {\n            for (int i = 0; i < 3; i++) vs.push_back(v.geom.p[i]);\n        }\n        std::stringstream ss;\n        {\n            cereal::JSONOutputArchive oa(ss);\n            oa(vs);\n        }\n        DebugIO::Output(\"seed_path\", ss.str());\n    }       \n    #endif\n\n\t// --------------------------------------------------------------------------------\n\n    #if INVERSEMAP_MANIFOLDWALK_DEBUG_IO\n    LM_LOG_DEBUG(\"target\");\n    {\n        DebugIO::Wait();\n        std::vector<double> vs;\n        for (int i = 0; i < 3; i++) vs.push_back(target[i]);\n        std::stringstream ss;\n        {\n            cereal::JSONOutputArchive oa(ss);\n            oa(vs);\n        }\n        DebugIO::Output(\"target\", ss.str());\n    }\n    #endif\n\n    // --------------------------------------------------------------------------------\n\n    #if 0\n    #if INVERSEMAP_MANIFOLDWALK_DEBUG_IO\n    LM_LOG_DEBUG(\"tanget_frame_v1\");\n    {\n        DebugIO::Wait();\n        std::stringstream ss;\n        {\n            cereal::JSONOutputArchive oa(ss);\n            const auto& v = currP.vertices[1];\n            oa(v.geom.p, v.geom.sn, v.geom.dpdu, v.geom.dpdv);\n        }\n        DebugIO::Output(\"tanget_frame_v1\", ss.str());\n    }\n    #endif\n    #endif\n\n    // --------------------------------------------------------------------------------\n\n\t#pragma region Optimization loop\n\n\tconst Float MaxBeta = 100.0;\n    #if INVERSEMAP_MANIFOLDWALK_BETA_EXT\n    Vec2 beta(MaxBeta, MaxBeta);\n    #else\n\tFloat beta = MaxBeta;\n    #endif\n\tconst Float Eps = 1e-4;\n\tconst int MaxIter = 50;\n\n\tfor (int iteration = 0; iteration < MaxIter; iteration++)\n\t{\n        #if INVERSEMAP_MANIFOLDWALK_OUTPUT_FAILED_TRIAL_PATHS\n        {\n            static long long count = 0;\n            if (count == 0)\n            {\n                boost::filesystem::remove(\"dirs.out\");\n            }\n            {\n                count++;\n                std::ofstream out(\"dirs.out\", std::ios::out | std::ios::app);\n                for (const auto& v : currP.vertices)\n                {\n                    out << boost::str(boost::format(\"%.10f %.10f %.10f \") % v.geom.p.x % v.geom.p.y % v.geom.p.z);\n                }\n                out << std::endl;\n            }\n        }\n        #endif\n\n        // --------------------------------------------------------------------------------\n\n        #if INVERSEMAP_MANIFOLDWALK_DEBUG_IO\n        LM_LOG_DEBUG(\"current_path\");\n        {\n            DebugIO::Wait();\n            std::vector<double> vs;\n            for (const auto& v : currP.vertices)\n            {\n                for (int i = 0; i < 3; i++) vs.push_back(v.geom.p[i]);\n            }\n            std::stringstream ss;\n            {\n                cereal::JSONOutputArchive oa(ss);\n                oa(vs);\n            }\n            DebugIO::Output(\"current_path\", ss.str());\n        }       \n        #endif\n\n        // --------------------------------------------------------------------------------\n\n        #if 0\n        #if INVERSEMAP_MANIFOLDWALK_DEBUG_IO\n        LM_LOG_DEBUG(\"current_tanget_frame_v1\");\n        {\n            DebugIO::Wait();\n            std::stringstream ss;\n            {\n                cereal::JSONOutputArchive oa(ss);\n                const auto& v = currP.vertices[1];\n                oa(v.geom.p, v.geom.sn, v.geom.dpdu, v.geom.dpdv);\n            }\n            DebugIO::Output(\"current_tanget_frame_v1\", ss.str());\n        }\n        #endif\n        #endif\n\n        // --------------------------------------------------------------------------------\n\n        #if 0\n        {\n            const auto d = Math::Length(currP.vertices.back().geom.p - target);\n            LM_LOG_DEBUG(boost::str(boost::format(\"#%02d: Dist to target %.15f\") % iteration % d));\n        }\n        #endif\n\n        // --------------------------------------------------------------------------------\n\n        // Compute \\nabla C\n        ConstraintJacobian nablaC;\n        nablaC.assign(n - 2, VertexConstraintJacobian());\n        ComputeConstraintJacobian(currP, nablaC);\n\n        // Compute L\n        Float L = 0;\n        for (const auto& x : currP.vertices) { L = Math::Max(L, Math::Length(x.geom.p)); }\n\n        // --------------------------------------------------------------------------------\n\n\t\t#pragma region Stop condition\n\t\tif (Math::Length(currP.vertices[n - 1].geom.p - target) < Eps * L)\n\t\t{\n            //LM_LOG_INFO(\"Converged\");\n            connPath = currP;\n            return true;\n\t\t}\n\t\t#pragma endregion\n\n\t\t// --------------------------------------------------------------------------------\n\n\t\t#pragma region Compute movement in tangement plane\n\t\t// New position of initial specular vertex\n\t\tconst auto p = [&]() -> Vec3\n\t\t{\n\t\t\t// x_n, x'_n\n\t\t\tconst auto& xn = currP.vertices[n - 1].geom.p;\n\t\t\tconst auto& xnp = target;\n\n\t\t\t// T(x_n)^T\n            const auto Txn = Mat3x2(currP.vertices[n - 1].geom.dpdu, currP.vertices[n - 1].geom.dpdv);\n\t\t\tconst auto TxnT = Math::Transpose(Txn);\n\n\t\t\t// V \\equiv B_n T(x_n)^T (x'_n - x)\n\t\t\tconst auto Bn_n2p = nablaC[n - 3].C;\n\t\t\tconst auto V_n2p = Bn_n2p * TxnT * (xnp - xn);\n\n\t\t\t// Solve AW = V\n            std::vector<Vec2> V;\n            V.assign(n - 2, Vec2());\n            std::vector<Vec2> W;\n            W.assign(n - 2, Vec2());\n\t\t\tfor (int i = 0; i < n - 2; i++) { V[i] = i == n - 3 ? V_n2p : Vec2(); }\n            #if !INVERSEMAP_MANIFOLDWALK_USE_EIGEN_SOLVER\n\t\t\tSolveBlockLinearEq(nablaC, V, W);\n            #else\n            Matrix nablaC_;\n            nablaC_.setZero(2 * (n - 2), 2 * (n - 2));\n            for (int i = 0; i < n - 2; i++)\n            {\n                if (i > 0)\n                {\n                    const auto& A = nablaC[i].A;\n                    Eigen::Array22d m;\n                    m << A[0][0], A[1][0],\n                         A[0][1], A[1][1];\n                    nablaC_.block<2, 2>(i * 2, (i - 1) * 2) = m;\n                }\n                {\n                    const auto& B = nablaC[i].B;\n                    Eigen::Array22d m;\n                    m << B[0][0], B[1][0],\n                         B[0][1], B[1][1];\n                    nablaC_.block<2, 2>(i * 2, i * 2) = m;\n                }\n                if (i < n - 2 - 1)\n                {\n                    const auto& C = nablaC[i].C;\n                    Eigen::Array22d m;\n                    m << C[0][0], C[1][0],\n                         C[0][1], C[1][1];\n                    nablaC_.block<2, 2>(i * 2, (i + 1) * 2) = m;\n\n                }\n            }\n            Vector V_;\n            V_.setZero(2 * (n - 2));\n            for (int i = 0; i < n - 2; i++) { V_(2*i) = V[i].x; V_(2*i+1) = V[i].y; }\n            Vector W_;\n            W_ = nablaC_.colPivHouseholderQr().solve(V_);\n            for (int i = 0; i < n - 2; i++) { W[i].x = W_(2 * i); W[i].y = W_(2 * i + 1); }\n            #endif\n\n\t\t\t// x_2, T(x_2)\n\t\t\tconst auto& x2 = currP.vertices[1].geom.p;\n\t\t\tconst Mat3x2 Tx2(currP.vertices[1].geom.dpdu, currP.vertices[1].geom.dpdv);\n\n            #if INVERSEMAP_MANIFOLDWALK_DEBUG_IO\n            LM_LOG_DEBUG(\"points_on_tangent_s\");\n            {\n                DebugIO::Wait();\n                std::vector<Vec3> vs;\n                for (int i = 0; i < n - 2; i++)\n                {\n                    const Mat3x2 Tx(currP.vertices[i + 1].geom.dpdu, currP.vertices[i + 1].geom.dpdv);\n                    vs.push_back(currP.vertices[i + 1].geom.p +  Tx * W[i]);\n                }\n                std::stringstream ss;\n                {\n                    cereal::JSONOutputArchive oa(ss);\n                    oa(vs);\n                }\n                DebugIO::Output(\"points_on_tangent_s\", ss.str());\n            }\n            #endif\n\n\t\t\t// W_{n-2} = P_2 W\n\t\t\t//const auto Wn2p = W[n - 3];\n            const auto Wn2p = W[0];\n\n\t\t\t// p = x_2 - \\beta T(x_2) P_2 W_{n-2}\n            #if INVERSEMAP_MANIFOLDWALK_BETA_EXT\n            const auto t1 = Vec2(Wn2p.x * beta.x, Wn2p.y * beta.y);\n            const auto t2 = Tx2 * t1;\n            #else\n            const auto t1 = Tx2 * Wn2p;\n            const auto t2 = t1 * beta;\n            #endif\n\t\t\treturn x2 - t2;\n        }();\n\t\t#pragma endregion\n\n        // --------------------------------------------------------------------------------\n\n        #if INVERSEMAP_MANIFOLDWALK_DEBUG_IO\n        LM_LOG_DEBUG(\"point_on_tangent\");\n        {\n            DebugIO::Wait();\n            std::vector<double> vs;\n            for (int i = 0; i < 3; i++) vs.push_back(p[i]);\n            std::stringstream ss;\n            {\n                cereal::JSONOutputArchive oa(ss);\n                oa(vs);\n            }\n            DebugIO::Output(\"point_on_tangent\", ss.str());\n        }\n        #endif\n\n\t\t// --------------------------------------------------------------------------------\n\n\t\t#pragma region Propagate light path to p - x1\n        const auto nextP = [&]() -> boost::optional<Subpath>\n        {\n            Subpath nextP;\n            nextP.vertices.clear();\n            nextP.vertices.push_back(currP.vertices[0]);\n            for (int i = 1; i < n; i++)\n            {\n                // Current vertex & previous vertex\n                const auto* vp = &nextP.vertices[i - 1];\n                const auto* vpp = i - 2 >= 0 ? &nextP.vertices[i - 2] : nullptr;\n\n                // Next ray direction\n                const auto wo = [&]()\n                {\n                    if (i == 1) { return Math::Normalize(p - vp->geom.p); }\n                    else\n                    {\n                        assert(vp->type == SurfaceInteractionType::S);\n                        const auto uC = [&]() -> Float\n                        {\n                            // Fix sampled component for Flesnel material (TODO. refactor it)\n                            // Vertices in current path\n                            const auto& curr_v  = currP.vertices[i - 1];\n                            const auto& curr_vp = currP.vertices[i - 2];\n                            const auto& curr_vn = currP.vertices[i];\n                            const auto wo = Math::Normalize(curr_vn.geom.p - curr_v.geom.p);\n                            const auto wi = Math::Normalize(curr_vp.geom.p - curr_v.geom.p);\n                            const auto localWo = curr_v.geom.ToLocal * wo;\n                            const auto localWi = curr_v.geom.ToLocal * wi;\n                            return Math::LocalCos(localWi) * Math::LocalCos(localWo) >= 0_f ? 0_f : 1_f;\n                        }();\n                        Vec3 wo;\n                        vp->primitive->SampleDirection(Vec2(), uC, vp->type, vp->geom, Math::Normalize(vpp->geom.p - vp->geom.p), wo);\n                        return wo;\n                    }\n                }();\n\n                // Intersection query\n                Ray ray = { vp->geom.p, wo };\n                Intersection isect;\n                if (!scene->Intersect(ray, isect))\n                {\n                    return boost::none;\n                }\n\n                // Fails if not intersected with specular vertex, except for the last vertex.\n                if (i <= n - 2 && (isect.primitive->Type() & SurfaceInteractionType::S) == 0)\n                {\n                    return boost::none;\n                }\n                    \n                // Fails if the last vertex is S\n                if (i == n - 1 && (isect.primitive->Type() & SurfaceInteractionType::S) != 0)\n                {\n                    return boost::none;\n                }\n\n                // Add vertex\n                SubpathSampler::PathVertex v;\n                v.geom = isect.geom;\n                v.primitive = isect.primitive;\n                v.type = isect.primitive->Type() & ~SurfaceInteractionType::Emitter;\n                nextP.vertices.push_back(v);\n            }\n            return nextP;\n        }();\n\t\t#pragma endregion\n\n        // --------------------------------------------------------------------------------\n            \n        #if INVERSEMAP_MANIFOLDWALK_DEBUG_IO\n        if (nextP)\n        {\n            LM_LOG_DEBUG(\"next_path\");\n            DebugIO::Wait();\n            std::vector<double> vs;\n            for (const auto& v : nextP->vertices)\n            {\n                for (int i = 0; i < 3; i++) vs.push_back(v.geom.p[i]);\n            }\n            std::stringstream ss;\n            {\n                cereal::JSONOutputArchive oa(ss);\n                oa(vs);\n            }\n            DebugIO::Output(\"next_path\", ss.str());\n        }\n        #endif\n\n        // --------------------------------------------------------------------------------\n\n        #if INVERSEMAP_MANIFOLDWALK_OUTPUT_FAILED_TRIAL_PATHS\n        if (nextP)\n        {\n            static long long count = 0;\n            if (count == 0)\n            {\n                boost::filesystem::remove(\"dirs_next.out\");\n            }\n            {\n                count++;\n                std::ofstream out(\"dirs_next.out\", std::ios::out | std::ios::app);\n                for (const auto& v : nextP->vertices)\n                {\n                    out << boost::str(boost::format(\"%.10f %.10f %.10f \") % v.geom.p.x % v.geom.p.y % v.geom.p.z);\n                }\n                out << std::endl;\n            }\n        }\n        #endif\n\n        // --------------------------------------------------------------------------------\n\n\t\t#pragma region Update beta\n        const auto update = [&]() -> bool\n        {\n            if (!nextP)\n            {\n                return true;\n            }\n            // Update beta if nextP shows larger difference to target\n            const auto d  = Math::Length2(currP.vertices.back().geom.p - target);\n            const auto dn = Math::Length2(nextP->vertices.back().geom.p - target);\n            //LM_LOG_INFO(boost::str(boost::format(\"d, dn: %.15f %.15f\") % d % dn));\n            if (dn >= d)\n            {\n                return true;\n            }\n            return false;\n        }();\n        if (update)\n        {\n            #if INVERSEMAP_MANIFOLDWALK_BETA_EXT\n            if (Math::Abs(beta.x) > Math::Abs(beta.y)) { beta.x *= -0.5_f; }\n            else { beta.y *= -0.5_f; }\n            #else\n            beta *= -0.5_f;\n            #endif\n            //LM_LOG_INFO(boost::str(boost::format(\"- beta: %.15f\") % beta));\n        }\n        else\n        {\n            #if INVERSEMAP_MANIFOLDWALK_BETA_EXT\n            beta.x = Math::Clamp(beta.x * 2_f, -MaxBeta, MaxBeta);\n            beta.y = Math::Clamp(beta.y * 2_f, -MaxBeta, MaxBeta);\n            //if (Math::Abs(beta.x) > Math::Abs(beta.y)) { beta.y = Math::Clamp(beta.y * 2_f, -MaxBeta, MaxBeta); }\n            //else { beta.x = Math::Clamp(beta.x * 2_f, -MaxBeta, MaxBeta); }\n            #else\n            beta = Math::Clamp(beta * 2_f, -MaxBeta, MaxBeta);\n            #endif\n            //LM_LOG_INFO(boost::str(boost::format(\"+ beta: %.15f\") % beta));\n            currP = *nextP;\n        }\n\t\t#pragma endregion\n\t}\n\n\t#pragma endregion\n\n\t// --------------------------------------------------------------------------------\n\treturn false;\n}\n\nLM_NAMESPACE_END\n", "meta": {"hexsha": "ac83dc084137a0f757acb42b5db8abf93ac8d73c", "size": 29118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plugin/renderer_inversemap/manifoldutils.cpp", "max_stars_repo_name": "jammm/lightmetrica-v2", "max_stars_repo_head_hexsha": "6864942ec48d37f2c35dc30a38a26d7cc4bb527e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 150.0, "max_stars_repo_stars_event_min_datetime": "2015-12-28T10:26:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T14:36:16.000Z", "max_issues_repo_path": "plugin/renderer_inversemap/manifoldutils.cpp", "max_issues_repo_name": "jammm/lightmetrica-v2", "max_issues_repo_head_hexsha": "6864942ec48d37f2c35dc30a38a26d7cc4bb527e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plugin/renderer_inversemap/manifoldutils.cpp", "max_forks_repo_name": "jammm/lightmetrica-v2", "max_forks_repo_head_hexsha": "6864942ec48d37f2c35dc30a38a26d7cc4bb527e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2016-02-08T10:57:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-04T03:57:33.000Z", "avg_line_length": 34.176056338, "max_line_length": 159, "alphanum_fraction": 0.4740366783, "num_tokens": 8220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5200545405380705}}
{"text": "/*\n * adjointness.cpp\n *\n *  Created on: 22.07.2017\n *      Author: thies\n */\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/numbers.h>\n#include <deal.II/base/point.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria.h>\n\n#include <base/AdaptiveMesh.h>\n#include <base/ConstantMesh.h>\n#include <base/DiscretizedFunction.h>\n#include <base/MacroFunctionParser.h>\n#include <base/SpaceTimeMesh.h>\n#include <base/Transformation.h>\n#include <base/Tuple.h>\n#include <base/Util.h>\n#include <forward/L2RightHandSide.h>\n#include <forward/WaveEquation.h>\n#include <forward/WaveEquationAdjoint.h>\n#include <forward/WaveEquationBase.h>\n#include <measurements/ConvolutionMeasure.h>\n#include <measurements/DeltaMeasure.h>\n#include <measurements/GridDistribution.h>\n#include <measurements/Measure.h>\n#include <measurements/SensorDistribution.h>\n#include <norms/L2L2.h>\n#include <problems/QProblem.h>\n#include <problems/WaveProblem.h>\n\n#include <gtest/gtest.h>\n\n#include <stddef.h>\n#include <cmath>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace {\n\nusing namespace dealii;\nusing namespace wavepi::base;\nusing namespace wavepi;\nusing namespace wavepi::measurements;\n\nenum class MeasureType { convolution = 1, delta };\n\ntemplate <int dim>\nvoid run_sensor_measure_adjoint_test(MeasureType measure_type, int fe_order, int quad_order, int refines, int n_steps) {\n  auto triangulation = std::make_shared<Triangulation<dim>>();\n  GridGenerator::hyper_cube(*triangulation, -1, 1);\n  Util::set_all_boundary_ids(*triangulation, 0);\n  triangulation->refine_global(refines);\n\n  double t_start = 0.0, t_end = 1.0, dt = t_end / n_steps;\n  std::vector<double> times;\n\n  for (size_t i = 0; t_start + i * dt <= t_end; i++)\n    times.push_back(t_start + i * dt);\n\n  FE_Q<dim> fe(fe_order);\n  Quadrature<dim> quad = QGauss<dim>(quad_order);  // exact in poly degree 2n-1 (needed: fe_dim^3)\n\n  std::shared_ptr<SpaceTimeMesh<dim>> mesh = std::make_shared<ConstantMesh<dim>>(times, fe, quad, triangulation);\n\n  deallog << std::endl << \"----------  n_dofs / timestep: \" << mesh->get_dof_handler(0)->n_dofs();\n  deallog << \", n_steps: \" << times.size() << \"  ----------\" << std::endl;\n\n  const size_t PPD = 2;\n\n  std::vector<double> mtimes(PPD, 0.0);\n  for (size_t i = 0; i < mtimes.size(); i++)\n    mtimes[i] = (i + 1.0) / (mtimes.size() + 1.0);\n\n  std::vector<std::vector<double>> spatial_points;\n  for (size_t d = 0; d < dim; d++) {\n    std::vector<double> tmp(PPD, 0.0);\n\n    for (size_t i = 0; i < tmp.size(); i++)\n      tmp[i] = ((i + 1.0) / (tmp.size() + 1.0)) * 2.0 - 1.0;\n\n    spatial_points.push_back(tmp);\n  }\n\n  auto grid = std::make_shared<GridDistribution<dim>>(mtimes, spatial_points);\n  std::shared_ptr<Measure<DiscretizedFunction<dim>, SensorValues<dim>>> measure;\n\n  if (measure_type == MeasureType::convolution)\n    measure = std::make_shared<ConvolutionMeasure<dim>>(mesh, grid, std::make_shared<norms::L2L2<dim>>(),\n                                                        std::make_shared<typename ConvolutionMeasure<dim>::HatShape>(),\n                                                        0.1, 0.2);\n  else if (measure_type == MeasureType::delta)\n    measure = std::make_shared<DeltaMeasure<dim>>(mesh, grid, std::make_shared<norms::L2L2<dim>>());\n\n  double tol = 1e-06;\n\n  for (int i = 0; i < 10; i++) {\n    DiscretizedFunction<dim> f = DiscretizedFunction<dim>::noise(mesh);\n    f.set_norm(std::make_shared<norms::L2L2<dim>>());\n\n    SensorValues<dim> g = SensorValues<dim>::noise(grid);\n\n    Timer eval_timer;\n    eval_timer.start();\n    auto Psif = measure->evaluate(f);\n    eval_timer.stop();\n\n    Timer adj_timer;\n    adj_timer.start();\n    auto PsiAdjg = measure->adjoint(g);\n    AssertThrow(*PsiAdjg.get_norm() == norms::L2L2<dim>(), ExcInternalError());\n    adj_timer.stop();\n\n    double dot_Psif_g    = Psif * g;\n    double dot_f_Psiadjg = f * PsiAdjg;\n    double mfg_err       = std::abs(dot_Psif_g - dot_f_Psiadjg) / (std::abs(dot_Psif_g) + 1e-300);\n\n    deallog << \"wall time evaluate: \" << std::fixed << eval_timer.wall_time() << \" s\" << std::endl;\n    deallog << \"wall time adjoint: \" << std::fixed << adj_timer.wall_time() << \" s\" << std::endl;\n\n    deallog << std::scientific << \"(\u03a8f, g) = \" << dot_Psif_g << \", (f, \u03a8*g) = \" << dot_f_Psiadjg\n            << \", rel. error = \" << mfg_err << std::endl;\n\n    EXPECT_LT(mfg_err, tol);\n  }\n\n  deallog << std::endl;\n}\n\n// tests whether the specialized implementation of delta_measure for constant meshes yields the same result as for\n// general meshes\ntemplate <int dim>\nvoid run_delta_measure_implementation_test(int fe_order, int quad_order, int refines, int n_steps) {\n  auto triangulation = std::make_shared<Triangulation<dim>>();\n  GridGenerator::hyper_cube(*triangulation, -1, 1);\n  Util::set_all_boundary_ids(*triangulation, 0);\n  triangulation->refine_global(refines);\n\n  double t_start = 0.0, t_end = 1.0, dt = t_end / n_steps;\n  std::vector<double> times;\n\n  for (size_t i = 0; t_start + i * dt <= t_end; i++)\n    times.push_back(t_start + i * dt);\n\n  FE_Q<dim> fe(fe_order);\n  Quadrature<dim> quad = QGauss<dim>(quad_order);  // exact in poly degree 2n-1 (needed: fe_dim^3)\n\n  std::shared_ptr<SpaceTimeMesh<dim>> mesh  = std::make_shared<ConstantMesh<dim>>(times, fe, quad, triangulation);\n  std::shared_ptr<SpaceTimeMesh<dim>> amesh = std::make_shared<AdaptiveMesh<dim>>(times, fe, quad, triangulation);\n\n  deallog << std::endl << \"----------  n_dofs / timestep: \" << mesh->get_dof_handler(0)->n_dofs();\n  deallog << \", n_steps: \" << times.size() << \"  ----------\" << std::endl;\n\n  const size_t PPD = 10;\n\n  std::vector<double> mtimes(PPD, 0.0);\n  for (size_t i = 0; i < mtimes.size(); i++)\n    mtimes[i] = (i + 1.0) / (mtimes.size() + 1.0);\n\n  std::vector<std::vector<double>> spatial_points;\n  for (size_t d = 0; d < dim; d++) {\n    std::vector<double> tmp(PPD, 0.0);\n\n    for (size_t i = 0; i < tmp.size(); i++)\n      tmp[i] = ((i + 1.0) / (tmp.size() + 1.0)) * 2.0 - 1.0;\n\n    spatial_points.push_back(tmp);\n  }\n\n  auto grid     = std::make_shared<GridDistribution<dim>>(mtimes, spatial_points);\n  auto measure  = std::make_shared<DeltaMeasure<dim>>(mesh, grid, std::make_shared<norms::L2L2<dim>>());\n  auto ameasure = std::make_shared<DeltaMeasure<dim>>(amesh, grid, std::make_shared<norms::L2L2<dim>>());\n\n  double tol = 1e-06;\n\n  for (int i = 0; i < 10; i++) {\n    DiscretizedFunction<dim> f = DiscretizedFunction<dim>::noise(mesh);\n    f.set_norm(std::make_shared<norms::L2L2<dim>>());\n\n    DiscretizedFunction<dim> af = DiscretizedFunction<dim>(amesh);\n    for (size_t ti = 0; ti < mesh->length(); ti++)\n      af[ti] = f[ti];\n\n    SensorValues<dim> g = SensorValues<dim>::noise(grid);\n\n    Timer timer;\n    timer.restart();\n    auto Psif = measure->evaluate(f);\n    timer.stop();\n    deallog << \"wall time evaluate (ConstantMesh): \" << std::fixed << timer.wall_time() << \" s\" << std::endl;\n\n    timer.restart();\n    auto aPsif = ameasure->evaluate(af);\n    timer.stop();\n    deallog << \"wall time evaluate (AdaptiveMesh): \" << std::fixed << timer.wall_time() << \" s\" << std::endl;\n\n    timer.restart();\n    auto PsiAdjg = measure->adjoint(g);\n    AssertThrow(*PsiAdjg.get_norm() == norms::L2L2<dim>(), ExcInternalError());\n    timer.stop();\n    deallog << \"wall time adjoint (ConstantMesh): \" << std::fixed << timer.wall_time() << \" s\" << std::endl;\n\n    timer.restart();\n    auto aPsiAdjg = ameasure->adjoint(g);\n    AssertThrow(*aPsiAdjg.get_norm() == norms::L2L2<dim>(), ExcInternalError());\n    timer.stop();\n    deallog << \"wall time adjoint (AdaptiveMesh): \" << std::fixed << timer.wall_time() << \" s\" << std::endl;\n\n    DiscretizedFunction<dim> PsiAdjg_copy = DiscretizedFunction<dim>(amesh, PsiAdjg.get_norm());\n    for (size_t ti = 0; ti < mesh->length(); ti++)\n      PsiAdjg_copy[ti] = PsiAdjg[ti];\n\n    double psi_err = aPsif.relative_error(Psif);\n    deallog << std::scientific << \"error [ \u03a8f (ConstantMesh - \u03a8f (AdaptiveMesh) ] = \" << psi_err << std::endl;\n\n    EXPECT_LT(psi_err, tol);\n\n    double psiadj_err = aPsiAdjg.relative_error(PsiAdjg_copy);\n    deallog << std::scientific << \"error [ \u03a8*f (ConstantMesh - \u03a8*f (AdaptiveMesh) ] = \" << psiadj_err << std::endl;\n\n    EXPECT_LT(psiadj_err, tol);\n  }\n\n  deallog << std::endl;\n}\n\n}  // namespace\n\nTEST(Measurements, ConvolutionMeasureAdjointness1DFE1) {\n  run_sensor_measure_adjoint_test<1>(MeasureType::convolution, 1, 4, 9, 256);\n}\n\nTEST(Measurements, ConvolutionMeasureAdjointness1DFE2) {\n  run_sensor_measure_adjoint_test<1>(MeasureType::convolution, 2, 4, 7, 128);\n}\n\nTEST(Measurements, ConvolutionMeasureAdjointness2DFE1) {\n  run_sensor_measure_adjoint_test<2>(MeasureType::convolution, 1, 4, 5, 256);\n}\n\nTEST(Measurements, ConvolutionMeasureAdjointness2DFE2) {\n  run_sensor_measure_adjoint_test<2>(MeasureType::convolution, 2, 4, 5, 128);\n}\n\nTEST(Measurements, ConvolutionMeasureAdjointness3DFE1) {\n  run_sensor_measure_adjoint_test<3>(MeasureType::convolution, 1, 4, 4, 128);\n}\n\nTEST(Measurements, DeltaMeasureAdjointness1DFE1) {\n  run_sensor_measure_adjoint_test<1>(MeasureType::delta, 1, 4, 9, 256);\n}\n\nTEST(Measurements, DeltaMeasureAdjointness1DFE2) {\n  run_sensor_measure_adjoint_test<1>(MeasureType::delta, 2, 4, 7, 128);\n}\n\nTEST(Measurements, DeltaMeasureAdjointness2DFE1) {\n  run_sensor_measure_adjoint_test<2>(MeasureType::delta, 1, 4, 5, 256);\n}\n\nTEST(Measurements, DeltaMeasureAdjointness2DFE2) {\n  run_sensor_measure_adjoint_test<2>(MeasureType::delta, 2, 4, 5, 128);\n}\n\nTEST(Measurements, DeltaMeasureAdjointness3DFE1) {\n  run_sensor_measure_adjoint_test<3>(MeasureType::delta, 1, 4, 4, 128);\n}\n\nTEST(Measurements, DeltaMeasureImplementation1DFE1) { run_delta_measure_implementation_test<1>(1, 4, 9, 256); }\n\nTEST(Measurements, DeltaMeasureImplementation1DFE2) { run_delta_measure_implementation_test<1>(2, 4, 7, 128); }\n\nTEST(Measurements, DeltaMeasureImplementation2DFE1) { run_delta_measure_implementation_test<2>(1, 4, 5, 256); }\n\nTEST(Measurements, DeltaMeasureImplementation2DFE2) { run_delta_measure_implementation_test<2>(2, 4, 5, 128); }\n\nTEST(Measurements, DeltaMeasureImplementation3DFE1) { run_delta_measure_implementation_test<3>(1, 4, 3, 128); }\n", "meta": {"hexsha": "6d0b27075c502e14d3c9033305d5ed9eb129afed", "size": 10336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/measurements.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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/measurements.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/measurements.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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.8888888889, "max_line_length": 120, "alphanum_fraction": 0.6753095975, "num_tokens": 3165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5200545379882574}}
{"text": "#include <boost/math/distributions/chi_squared.hpp>\n", "meta": {"hexsha": "1a8972981e2118b0fa060c198aa81d48f8369c34", "size": 52, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_chi_squared.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_chi_squared.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_chi_squared.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.0, "max_line_length": 51, "alphanum_fraction": 0.8269230769, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.5200545244873783}}
{"text": "#pragma once\n\n#include \"quadrature/qhermitew.hpp\"\n#include <Eigen/Dense>\n\n\nnamespace boltzmann {\n\ntemplate <typename DERIVED, typename FUNC>\nvoid\nto_nodal(Eigen::DenseBase<DERIVED>& dst, const FUNC f)\n{\n  assert(dst.rows() == dst.cols());\n\n  int K = dst.rows();\n  QHermiteW quad(1.0, K);\n\n  auto& x = quad.pts();\n  auto& w = quad.wts();\n\n  for (int i = 0; i < K; ++i) {\n    for (int j = 0; j < K; ++j) {\n      // convection: x -> rows, y -> cols (for example, see Polar2Nodal)\n      dst(i, j) = f(x[j], x[i]) * std::sqrt(w[i] * w[j]);\n    }\n  }\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "55fd29add89f9a393a0179f3301370b2e8049407", "size": 578, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/nodal.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/nodal.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/nodal.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": 19.2666666667, "max_line_length": 72, "alphanum_fraction": 0.5778546713, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5200545186359388}}
{"text": "#pragma once\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <cudd/cplusplus/cuddObj.hh>\n#include <vector>\n\n#include \"number_representation.hpp\"\n\nnamespace abo::error_metrics {\n\n/**\n * @brief Computes the average value of the function f over all possible inputs\n * @param f The function to compute the average of\n * Is interpreted to be unsigned\n * @return the average value of f as a high precision float\n */\nboost::multiprecision::cpp_dec_float_100 average_value(const std::vector<BDD>& f);\n\n/**\n * @brief Computes the average squared value of the function f over all possible inputs\n * @param f The function to compute the average squared value of\n * Is interpreted to be unsigned\n * @return the mean squared value of f as a high precision float\n */\nboost::multiprecision::cpp_dec_float_100 mean_squared_value(const std::vector<BDD>& f);\n\n/**\n * @brief Computes the average absolute difference between the functions f and f_hat\n * The computation is performed symbolically with BDD forests and may take exponential time\n * @param mgr Cudd manager object\n * @param f The original function\n * @param f_hat The approximated function\n * @param num_rep The number representation for f and f_hat\n * @return The average absolute difference between f and f_hat\n */\nboost::multiprecision::cpp_dec_float_100\naverage_case_error(const Cudd& mgr, const std::vector<BDD>& f, const std::vector<BDD>& f_hat,\n                   const abo::util::NumberRepresentation num_rep = abo::util::NumberRepresentation::BaseTwo);\n\n/**\n * @brief Computes the average squared absolute difference between the functions f and f_hat\n * The computation is performed symbolically with BDD forests and may take exponential time\n * @param mgr Cudd manager object\n * @param f The original function\n * @param f_hat The approximated function\n * @param num_rep The number representation for f and f_hat\n * @return The average squared absolute difference between f and f_hat\n */\nboost::multiprecision::cpp_dec_float_100\nmean_squared_error(const Cudd& mgr, const std::vector<BDD>& f,\n                   const std::vector<BDD>& f_hat,\n                   const abo::util::NumberRepresentation num_rep\n                        = abo::util::NumberRepresentation::BaseTwo);\n\n/**\n * @brief Computes the average absolute difference between the functions f and f_hat\n * The computation is performed symbolically with ADDs and may take exponential time\n * This function is generally slower than the equivalent average_case_error() function\n * and should only be used as a reference\n * @param mgr Cudd manager object\n * @param f The original function\n * @param f_hat The approximated function\n * @param num_rep The number representation for f and f_hat\n * @return The average absolute difference between f and f_hat\n */\nboost::multiprecision::cpp_dec_float_100\naverage_case_error_add(const Cudd& mgr, const std::vector<BDD>& f,\n                       const std::vector<BDD>& f_hat,\n                       const abo::util::NumberRepresentation num_rep\n                            = abo::util::NumberRepresentation::BaseTwo);\n\n/**\n * @brief Computes the average squared absolute difference between the functions f and f_hat\n * The computation is performed symbolically with ADDs and may take exponential time\n * This function is generally slower than the equivalent mean_squared_error() function\n * and should only be used as a reference\n * @param mgr Cudd manager object\n * @param f The original function\n * @param f_hat The approximated function\n * @param num_rep The number representation for f and f_hat\n * @return The average squared absolute difference between f and f_hat\n */\nboost::multiprecision::cpp_dec_float_100\nmean_squared_error_add(const Cudd& mgr, const std::vector<BDD>& f,\n                       const std::vector<BDD>& f_hat,\n                       const abo::util::NumberRepresentation num_rep\n                            = abo::util::NumberRepresentation::BaseTwo);\n\n} // namespace abo::error_metrics\n", "meta": {"hexsha": "957fce64eb648cd88d6fc7e2b43c993bd52c556e", "size": 3981, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/error_metrics/average_case_error.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/error_metrics/average_case_error.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/error_metrics/average_case_error.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": 44.2333333333, "max_line_length": 109, "alphanum_fraction": 0.7347400151, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.5200545171323118}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Perlin\n\n#include <boost/test/unit_test.hpp>\n#include <geomc/function/PerlinNoise.h>\n#include <geomc/random/MTRand.h>\n#include <geomc/random/RandomTools.h>\n\nusing namespace geom;\nusing namespace std;\n\n\n// todo: should figure out a way to get a copy of a PerlinNoise in Dual form, \n//       and verify the gradient that way.\n\n\n// return rms(error), max(error)\ntemplate <typename T, index_t N>\nstd::pair<T,T> perlin_gradient(Random* rng, index_t n_trials) {\n    PerlinNoise<T,N> pn(rng);\n    Sampler<T> smp(rng);\n    const T eps = 0.00001;\n    \n    T err_sq  = (T)0;\n    T err_max = (T)0;\n    \n    for (index_t i = 0; i < n_trials; ++i) {\n        Vec<T,N>  x = 512 * smp.template solidball<N>(); // :G\n        auto   x_dx = pn.gradient(x);\n        Vec<T,N> g;\n        \n        // finite difference the gradient\n        for (index_t axis = 0; axis < N; axis++) {\n            Vec<T,N> dx;\n            dx[axis] = eps;\n            g[axis]  = (pn.eval(x + dx) - pn.eval(x - dx)) / (2 * eps);\n        }\n        \n        // gradient()'s opinion on f(x) should be the same as eval()'s.\n        BOOST_CHECK_CLOSE(x_dx.first, pn.eval(x), eps);\n        \n        g      -= x_dx.second;\n        T e     = g.dot(g);\n        err_sq += e;\n        err_max = std::max(e, err_max);\n    }\n    \n    return std::pair<T,T>(\n        std::sqrt(err_sq) / n_trials,\n        std::sqrt(err_max));\n}\n\n\nBOOST_AUTO_TEST_SUITE(perlin_noise)\n\n\nBOOST_AUTO_TEST_CASE(test_perlin_gradient) {\n    MTRand rng = MTRand(1017381749271967481LL);\n    std::pair<double, double> k;\n    k = perlin_gradient<double,2>(&rng, 10000);\n    BOOST_CHECK_SMALL(k.first,  5e-11);\n    BOOST_CHECK_SMALL(k.second, 1e-8);\n    k = perlin_gradient<double,3>(&rng, 10000);\n    BOOST_CHECK_SMALL(k.first,  5e-11);\n    BOOST_CHECK_SMALL(k.second, 1e-8);\n    k = perlin_gradient<double,4>(&rng, 10000);\n    BOOST_CHECK_SMALL(k.first,  5e-11);\n    BOOST_CHECK_SMALL(k.second, 1e-8);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "1386a2dbdfca3fca78b0ba325a2ba64326968392", "size": 2000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "regression/perlin.cpp", "max_stars_repo_name": "trbabb/geomc", "max_stars_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-07-22T20:33:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T00:16:16.000Z", "max_issues_repo_path": "regression/perlin.cpp", "max_issues_repo_name": "trbabb/geomc", "max_issues_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-08-13T14:28:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-29T00:04:47.000Z", "max_forks_repo_path": "regression/perlin.cpp", "max_forks_repo_name": "trbabb/geomc", "max_forks_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-10-03T10:30:55.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-06T18:14:18.000Z", "avg_line_length": 27.397260274, "max_line_length": 78, "alphanum_fraction": 0.602, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.5200545069330597}}
{"text": "\n#include <cmath>\n\n#include <functional>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Astrodynamics/Propulsion/costateBasedThrustGuidance.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/modifiedEquinoctialElementConversions.h\"\n\nnamespace tudat\n{\n\nnamespace propulsion\n{\n\n//! Constructor\nMeeCostateBasedThrustGuidance::MeeCostateBasedThrustGuidance(\n        const std::function< Eigen::Vector6d( ) > thrustingBodyStateFunction,\n        const std::function< Eigen::Vector6d( ) > centralBodyStateFunction,\n        const std::function< double( ) > centralBodyGravitationalParameterFunction,\n        std::function< Eigen::VectorXd( const double ) > costateFunction,\n        const std::function< Eigen::Vector3d( ) > bodyFixedForceDirection )\n    : BodyFixedForceDirectionGuidance( bodyFixedForceDirection ),\n      thrustingBodyStateFunction_( thrustingBodyStateFunction ),\n      centralBodyStateFunction_( centralBodyStateFunction ),\n      centralBodyGravitationalParameterFunction_( centralBodyGravitationalParameterFunction ),\n      costateFunction_( costateFunction ){ }\n\n//! Function to update the force direction to the current time.\nvoid MeeCostateBasedThrustGuidance::updateForceDirection( const double time )\n{\n    if( !( time == currentTime_ ) )\n    {\n        Eigen::VectorXd costates_ = costateFunction_( time );\n\n        // Get the current state in cartesian coordinates and keplerian elements, and some convenient parameters\n        Eigen::Vector6d currentState = thrustingBodyStateFunction_( ) - centralBodyStateFunction_( );\n        double centralBodyGravitationalParameter = centralBodyGravitationalParameterFunction_( );\n\n        // Obtain ModifiedEquinoctial elements, flag of 0 indicates that singularity occurs at 180 deg inclination.\n        Eigen::Vector6d modifiedEquinoctialElements =\n                orbital_element_conversions::convertCartesianToModifiedEquinoctialElements(\n                    currentState, centralBodyGravitationalParameter, 0 );\n\n        // Optimal control laws local variables declared for clarity\n        double auxiliaryParameterW = ( 1.0 + modifiedEquinoctialElements( 1 ) * cos( modifiedEquinoctialElements( 5 ) )\n                     + modifiedEquinoctialElements( 2 ) * sin( modifiedEquinoctialElements( 5 ) ) );\n        double auxiliaryParameterSSquared = 1.0 + modifiedEquinoctialElements( 3 ) * modifiedEquinoctialElements( 3 )\n                + modifiedEquinoctialElements( 4 ) * modifiedEquinoctialElements( 4 );\n\n        // Local variables for al constant terms for the calculation of pitch angle\n        double Lap = costates_( 0 ) * 2.0 * modifiedEquinoctialElements( 0 ) / auxiliaryParameterW;\n        double Laf1 = costates_( 1 )  * sin( modifiedEquinoctialElements( 5 ) ) ;\n        double Laf2 = costates_( 1 ) / auxiliaryParameterW *\n                ( ( auxiliaryParameterW + 1.0 ) * cos( modifiedEquinoctialElements( 5 ) )\n                                             + modifiedEquinoctialElements( 1 ) ) ;\n        double Lag1 = costates_( 2 ) * cos( modifiedEquinoctialElements( 5 ) );\n        double Lag2 = costates_( 2 ) / auxiliaryParameterW *\n                ( ( auxiliaryParameterW + 1.0 ) * sin( modifiedEquinoctialElements( 5 ) )\n                                             + modifiedEquinoctialElements( 2 ) );\n\n        // Calculate pitch angle, NOTE: denomitator ommitted since it is not relevant for the atan2 function,\n        // since both denominators are the same.\n        double thrustAngleAlpha = std::atan2( -Laf1+Lag1, -Lap-Laf2-Lag2);\n\n        // Local variables for al constant terms for the calculation of yaw angle\n        double Lbp = costates_( 0 ) * 2.0 * modifiedEquinoctialElements( 0 ) * cos( thrustAngleAlpha) / auxiliaryParameterW;\n        double Lbf1 = costates_( 1 )  * sin( modifiedEquinoctialElements( 5 ) ) * sin( thrustAngleAlpha );\n        double Lbf2 = costates_( 1 ) / auxiliaryParameterW *\n                ( ( auxiliaryParameterW + 1.0 ) * cos( modifiedEquinoctialElements( 5 ) )\n                                             + modifiedEquinoctialElements( 1 ) ) * cos( thrustAngleAlpha );\n        double Lbf3 = costates_( 1 ) / auxiliaryParameterW * ( modifiedEquinoctialElements( 2 ) *(\n                                                 modifiedEquinoctialElements( 3 ) * sin( modifiedEquinoctialElements( 5 ) )\n                                                 - modifiedEquinoctialElements( 4 ) * cos( modifiedEquinoctialElements( 5 ) ) ) );\n\n        double Lbg1 = costates_( 2 ) * cos( modifiedEquinoctialElements( 5 ) ) * sin( thrustAngleAlpha);\n        double Lbg2 = costates_( 2 ) / auxiliaryParameterW *\n                ( ( auxiliaryParameterW + 1.0 ) * sin( modifiedEquinoctialElements( 5 ) )\n                                             + modifiedEquinoctialElements( 2 ) ) * cos( thrustAngleAlpha);\n        double Lbg3 = costates_( 2 ) / auxiliaryParameterW * ( modifiedEquinoctialElements( 1 ) *(\n                                                 modifiedEquinoctialElements( 3 ) * sin( modifiedEquinoctialElements( 5 ) )\n                                                 - modifiedEquinoctialElements( 4 ) * cos( modifiedEquinoctialElements( 5 ) ) ) );\n        double Lbh = costates_( 3 ) * auxiliaryParameterSSquared *\n                cos( modifiedEquinoctialElements( 5 ) ) / ( 2.0 * auxiliaryParameterW );\n        double Lbk = costates_( 4 ) * auxiliaryParameterSSquared *\n                sin( modifiedEquinoctialElements( 5 ) ) / ( 2.0 * auxiliaryParameterW );\n\n        // Calculate yaw angle, NOTE: denomitator ommitted since it is not relevant for the atan2 function,\n        // since both denominators are the same.\n        double thrustAngleBeta = std::atan2( Lbf3 - Lbg3 - Lbh - Lbk, - Lbp - Lbf1 - Lbf2 + Lbg1 - Lbg2 );\n\n        // Calculate thrust direction\n        currentForceDirection_ = reference_frames::getVelocityBasedLvlhToInertialRotation(\n                    currentState, Eigen::Vector6d::Zero( ), false ) *\n                ( ( Eigen::Vector3d( ) <<\n                    cos( thrustAngleAlpha ) * cos( thrustAngleBeta ), sin( thrustAngleAlpha ) * cos( thrustAngleBeta ) ,\n                    sin( thrustAngleBeta )  ).finished( ).normalized( ) );\n        currentTime_ = time;\n\n\n//        // Switching function for the thrust magnitude.\n//        double thrustMagnitudeSwitchingCondition = /*( 1.0 / thrustingBodyMassFunction_( ) ) **/\n//                ( Lbp * cos( thrustAngleBeta ) + Lbh * sin( thrustAngleBeta ) + Lbk * sin( thrustAngleBeta )\n//                + Lbf1 * cos( thrustAngleBeta ) + Lbf2 * cos( thrustAngleBeta ) - Lbf3 * sin( thrustAngleBeta )\n//                - Lbg1 * cos( thrustAngleBeta ) + Lbg2 * cos( thrustAngleBeta ) + Lbg3 * sin( thrustAngleBeta ) );\n//        if ( thrustMagnitudeSwitchingCondition <= 0.0 )\n//        {\n//            std::cout << \"INSIDE THRUST DIRECTION FUNCTION, THRUST ON. \" << \"\\n\\n\";\n//        }\n//        else\n//        {\n//            std::cout << \"INSIDE THRUST DIRECTION FUNCTION, THRUST OFF. \" << \"\\n\\n\";\n//        }\n    }\n\n}\n\n} // namespace propulsion\n\n} // namespace tudat\n", "meta": {"hexsha": "e6e838b579e9ae961b2bb2971e888e693384282e", "size": 7060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Propulsion/costateBasedThrustGuidance.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/Propulsion/costateBasedThrustGuidance.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/Propulsion/costateBasedThrustGuidance.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": 57.868852459, "max_line_length": 130, "alphanum_fraction": 0.6389518414, "num_tokens": 1756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787536, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.5200517746115253}}
{"text": "#include \"../../include/IntrinsicFormula/KnoppelStripePattern.h\"\n#include \"../../include/IntrinsicFormula/AmpSolver.h\"\n#include \"../../include/Optimization/NewtonDescent.h\"\n#include <igl/cotmatrix.h>\n#include <SymGEigsShiftSolver.h>\n#include <MatOp/SparseCholesky.h>\n#include <Eigen/CholmodSupport>\n#include <MatOp/SparseSymShiftSolve.h>\n#include <iostream>\n\nusing namespace IntrinsicFormula;\n\nvoid IntrinsicFormula::computeMatrixA(const MeshConnectivity &mesh, const Eigen::MatrixXd &halfEdgeW,\n\t\t\t\t\t\t\t\t\t const Eigen::VectorXd &faceArea, const Eigen::MatrixXd &cotEntries,\n\t\t\t\t\t\t\t\t\t const int nverts, Eigen::SparseMatrix<double> &A)\n{\n\tstd::vector<Eigen::Triplet<double>> AT;\n\tint nfaces = mesh.nFaces();\n\tint nedges = mesh.nEdges();\n\n\tEigen::VectorXd halfEdgeWeight(nedges);\n\thalfEdgeWeight.setConstant(1.0);\n\n//    for (int i = 0; i < nfaces; i++)  // form mass matrix\n//    {\n//        for (int j = 0; j < 3; j++)\n//        {\n//            int eid = mesh.faceEdge(i, j);\n//            halfEdgeWeight(eid) += cotEntries(i, j);\n//        }\n//    }\n\tfor(int i = 0; i < nedges; i++)\n\t{\n\t\tint vid0 = mesh.edgeVertex(i, 0);\n\t\tint vid1 = mesh.edgeVertex(i, 1);\n\n\t\tAT.push_back({2 * vid0, 2 * vid0, 2 * halfEdgeWeight(i)});\n\t\tAT.push_back({2 * vid0 + 1, 2 * vid0 + 1, 2 * halfEdgeWeight(i)});\n\n\t\tAT.push_back({2 * vid1, 2 * vid1, 2 * halfEdgeWeight(i)});\n\t\tAT.push_back({2 * vid1 + 1, 2 * vid1 + 1, 2 * halfEdgeWeight(i)});\n\n\t\tstd::complex<double> expw0 = std::complex<double>(std::cos(halfEdgeW(i, 0)), std::sin(halfEdgeW(i, 0)));\n\t\tstd::complex<double> expw1 = std::complex<double>(std::cos(halfEdgeW(i, 1)), std::sin(halfEdgeW(i, 1)));\n\n\t\tAT.push_back({2 * vid0, 2 * vid1, -halfEdgeWeight(i) * (expw0.real() + expw1.real())});\n\t\tAT.push_back({2 * vid0 + 1, 2 * vid1, -halfEdgeWeight(i) * (-expw0.imag() + expw1.imag())});\n\t\tAT.push_back({2 * vid0, 2 * vid1 + 1, -halfEdgeWeight(i) * (expw0.imag() - expw1.imag())});\n\t\tAT.push_back({2 * vid0 + 1, 2 * vid1 + 1, -halfEdgeWeight(i) * (expw0.real() + expw1.real())});\n\n\t\tAT.push_back({ 2 * vid1, 2 * vid0, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) });\n\t\tAT.push_back({ 2 * vid1, 2 * vid0 + 1, -halfEdgeWeight(i) * (-expw0.imag() + expw1.imag()) });\n\t\tAT.push_back({ 2 * vid1 + 1, 2 * vid0, -halfEdgeWeight(i) * (expw0.imag() - expw1.imag()) });\n\t\tAT.push_back({ 2 * vid1 + 1, 2 * vid0 + 1, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) });\n\n\t}\n\tA.resize(2 * nverts, 2 * nverts);\n\tA.setFromTriplets(AT.begin(), AT.end());\n}\n\nvoid IntrinsicFormula::computeMatrixAGivenMag(const MeshConnectivity &mesh, const Eigen::MatrixXd &halfEdgeW, const Eigen::VectorXd& vertAmp, const Eigen::VectorXd& faceArea, const Eigen::MatrixXd& cotEntries, const int nverts, Eigen::SparseMatrix<double>& A) {\n\tstd::vector<Eigen::Triplet<double>> AT;\n\tint nfaces = mesh.nFaces();\n\tint nedges = mesh.nEdges();\n\n\tEigen::VectorXd halfEdgeWeight(nedges);\n\thalfEdgeWeight.setConstant(1.0);\n\n//    for (int i = 0; i < nfaces; i++)  // form mass matrix\n//    {\n//        for (int j = 0; j < 3; j++)\n//        {\n//            int eid = mesh.faceEdge(i, j);\n//            halfEdgeWeight(eid) += cotEntries(i, j);\n//        }\n//    }\n\n\tfor (int i = 0; i < nedges; i++) {\n\t\tint vid0 = mesh.edgeVertex(i, 0);\n\t\tint vid1 = mesh.edgeVertex(i, 1);\n\n\t\tdouble r0 = vertAmp(vid0);\n\t\tdouble r1 = vertAmp(vid1);\n\n\t\tstd::complex<double> expw0 = std::complex<double>(std::cos(halfEdgeW(i, 0)), std::sin(halfEdgeW(i, 0)));\n\t\tstd::complex<double> expw1 = std::complex<double>(std::cos(halfEdgeW(i, 1)), std::sin(halfEdgeW(i, 1)));\n\n\n\t\tAT.push_back({2 * vid0, 2 * vid0, 2 * r1 * r1 * halfEdgeWeight(i)});\n\t\tAT.push_back({2 * vid0 + 1, 2 * vid0 + 1, 2 * r1 * r1 * halfEdgeWeight(i)});\n\n\t\tAT.push_back({2 * vid1, 2 * vid1, 2 * r0 * r0 * halfEdgeWeight(i)});\n\t\tAT.push_back({2 * vid1 + 1, 2 * vid1 + 1, 2 * r0 * r0 * halfEdgeWeight(i)});\n\n\n\t\tAT.push_back({2 * vid0, 2 * vid1, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) * r0 * r1});\n\t\tAT.push_back({2 * vid0 + 1, 2 * vid1, -halfEdgeWeight(i) * (-expw0.imag() + expw1.imag()) * r0 * r1});\n\t\tAT.push_back({2 * vid0, 2 * vid1 + 1, -halfEdgeWeight(i) * (expw0.imag() - expw1.imag()) * r0 * r1});\n\t\tAT.push_back({2 * vid0 + 1, 2 * vid1 + 1, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) * r0 * r1});\n\n\t\tAT.push_back({2 * vid1, 2 * vid0, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) * r0 * r1});\n\t\tAT.push_back({2 * vid1, 2 * vid0 + 1, -halfEdgeWeight(i) * (-expw0.imag() + expw1.imag()) * r0 * r1});\n\t\tAT.push_back({2 * vid1 + 1, 2 * vid0, -halfEdgeWeight(i) * (expw0.imag() - expw1.imag()) * r0 * r1});\n\t\tAT.push_back({2 * vid1 + 1, 2 * vid0 + 1, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) * r0 * r1});\n\t}\n\tA.resize(2 * nverts, 2 * nverts);\n\tA.setFromTriplets(AT.begin(), AT.end());\n}\n\ndouble IntrinsicFormula::KnoppelEnergy(const MeshConnectivity& mesh, const Eigen::MatrixXd& halfEdgeW, const Eigen::VectorXd& faceArea, const Eigen::MatrixXd& cotEntries, const std::vector<std::complex<double>>& zvals, Eigen::VectorXd* deriv, std::vector<Eigen::Triplet<double>>* hess)\n{\n\tstd::vector<Eigen::Triplet<double>> AT;\n\tint nfaces = mesh.nFaces();\n\tint nedges = mesh.nEdges();\n\tint nverts = zvals.size();\n\n\tEigen::VectorXd halfEdgeWeight(nedges);\n\thalfEdgeWeight.setConstant(1.0);\n\n//    for (int i = 0; i < nfaces; i++)  // form mass matrix\n//    {\n//        for (int j = 0; j < 3; j++)\n//        {\n//            int eid = mesh.faceEdge(i, j);\n//            halfEdgeWeight(eid) += cotEntries(i, j);\n//        }\n//    }\n\tdouble energy = 0;\n\t\n\tfor (int i = 0; i < nedges; i++)\n\t{\n\t\tint vid0 = mesh.edgeVertex(i, 0);\n\t\tint vid1 = mesh.edgeVertex(i, 1);\n\n\t\tstd::complex<double> expw0 = std::complex<double>(std::cos(halfEdgeW(i, 0)), std::sin(halfEdgeW(i, 0)));\n\t\tstd::complex<double> expw1 = std::complex<double>(std::cos(halfEdgeW(i, 1)), std::sin(halfEdgeW(i, 1)));\n\n\t\tstd::complex<double> z0 = zvals[vid0];\n\t\tstd::complex<double> z1 = zvals[vid1];\n\n\t\tenergy += 0.5 * (norm((z0 * expw0 - z1)) + norm((z1 * expw1 - z0))) * halfEdgeWeight(i);\n\n\t\tif (deriv || hess)\n\t\t{\n\t\t\tAT.push_back({ 2 * vid0, 2 * vid0, 2 * halfEdgeWeight(i) });\n\t\t\tAT.push_back({ 2 * vid0 + 1, 2 * vid0 + 1, 2 * halfEdgeWeight(i) });\n\n\t\t\tAT.push_back({ 2 * vid1, 2 * vid1, 2 * halfEdgeWeight(i) });\n\t\t\tAT.push_back({ 2 * vid1 + 1, 2 * vid1 + 1, 2 * halfEdgeWeight(i) });\n\n\n\t\t\tAT.push_back({ 2 * vid0, 2 * vid1, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) });\n\t\t\tAT.push_back({ 2 * vid0 + 1, 2 * vid1, -halfEdgeWeight(i) * (-expw0.imag() + expw1.imag()) });\n\t\t\tAT.push_back({ 2 * vid0, 2 * vid1 + 1, -halfEdgeWeight(i) * (expw0.imag() - expw1.imag()) });\n\t\t\tAT.push_back({ 2 * vid0 + 1, 2 * vid1 + 1, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) });\n\n\t\t\tAT.push_back({ 2 * vid1, 2 * vid0, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) });\n\t\t\tAT.push_back({ 2 * vid1, 2 * vid0 + 1, -halfEdgeWeight(i) * (-expw0.imag() + expw1.imag()) });\n\t\t\tAT.push_back({ 2 * vid1 + 1, 2 * vid0, -halfEdgeWeight(i) * (expw0.imag() - expw1.imag()) });\n\t\t\tAT.push_back({ 2 * vid1 + 1, 2 * vid0 + 1, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) });\n\t\t}\n\t}\n\n\tif (deriv || hess)\n\t{\n\t\tEigen::SparseMatrix<double> A;\n\n\t\tA.resize(2 * nverts, 2 * nverts);\n\t\tA.setFromTriplets(AT.begin(), AT.end());\n\n\t\tif (deriv)\n\t\t{\n\t\t\tEigen::VectorXd fvals(2 * nverts);\n\t\t\tfor (int i = 0; i < nverts; i++)\n\t\t\t{\n\t\t\t\tfvals(2 * i) = zvals[i].real();\n\t\t\t\tfvals(2 * i + 1) = zvals[i].imag();\n\t\t\t}\n\t\t\t(*deriv) = A * fvals;\n\t\t}\n\t\t   \n\t\tif (hess)\n\t\t\t(*hess) = AT;\n\t}\n\n\treturn energy;\n}\n\ndouble IntrinsicFormula::KnoppelEnergyGivenMag(const MeshConnectivity& mesh, const Eigen::MatrixXd& halfEdgeW, const Eigen::VectorXd& vertAmp, const Eigen::VectorXd& faceArea, const Eigen::MatrixXd& cotEntries, const std::vector<std::complex<double>>& zvals, Eigen::VectorXd* deriv, std::vector<Eigen::Triplet<double>>* hess)\n{\n\tstd::vector<Eigen::Triplet<double>> AT;\n\tint nfaces = mesh.nFaces();\n\tint nedges = mesh.nEdges();\n\tint nverts = vertAmp.size();\n\n\tEigen::VectorXd halfEdgeWeight(nedges);\n\thalfEdgeWeight.setConstant(1.0);\n\n//    for (int i = 0; i < nfaces; i++)  // form mass matrix\n//    {\n//        for (int j = 0; j < 3; j++)\n//        {\n//            int eid = mesh.faceEdge(i, j);\n//            halfEdgeWeight(eid) += cotEntries(i, j);\n//        }\n//    }\n\tdouble energy = 0;\n\n\tfor (int i = 0; i < nedges; i++)\n\t{\n\t\tint vid0 = mesh.edgeVertex(i, 0);\n\t\tint vid1 = mesh.edgeVertex(i, 1);\n\n\t\tdouble r0 = vertAmp(vid0);\n\t\tdouble r1 = vertAmp(vid1);\n\n\t\tstd::complex<double> expw0 = std::complex<double>(std::cos(halfEdgeW(i, 0)), std::sin(halfEdgeW(i, 0)));\n\t\tstd::complex<double> expw1 = std::complex<double>(std::cos(halfEdgeW(i, 1)), std::sin(halfEdgeW(i, 1)));\n\n\t\tstd::complex<double> z0 = zvals[vid0];\n\t\tstd::complex<double> z1 = zvals[vid1];\n\n\n\t\tenergy += 0.5 * (norm((r1 * z0 * expw0 - r0 * z1)) + norm((r0 * z1 * expw1 - r1 * z0))) * halfEdgeWeight(i);\n\n\t\tif (deriv || hess)\n\t\t{\n\t\t\tAT.push_back({ 2 * vid0, 2 * vid0, 2 * r1 * r1 * halfEdgeWeight(i) });\n\t\t\tAT.push_back({ 2 * vid0 + 1, 2 * vid0 + 1, 2 * r1 * r1 * halfEdgeWeight(i) });\n\n\t\t\tAT.push_back({ 2 * vid1, 2 * vid1, 2 * r0 * r0 * halfEdgeWeight(i) });\n\t\t\tAT.push_back({ 2 * vid1 + 1, 2 * vid1 + 1, 2 * r0 * r0 * halfEdgeWeight(i) });\n\n\n\t\t\tAT.push_back({ 2 * vid0, 2 * vid1, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) * r0 * r1 });\n\t\t\tAT.push_back({ 2 * vid0 + 1, 2 * vid1, -halfEdgeWeight(i) * (-expw0.imag() + expw1.imag()) * r0 * r1 });\n\t\t\tAT.push_back({ 2 * vid0, 2 * vid1 + 1, -halfEdgeWeight(i) * (expw0.imag() - expw1.imag()) * r0 * r1 });\n\t\t\tAT.push_back({ 2 * vid0 + 1, 2 * vid1 + 1, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) * r0 * r1 });\n\n\t\t\tAT.push_back({ 2 * vid1, 2 * vid0, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) * r0 * r1 });\n\t\t\tAT.push_back({ 2 * vid1, 2 * vid0 + 1, -halfEdgeWeight(i) * (-expw0.imag() + expw1.imag()) * r0 * r1 });\n\t\t\tAT.push_back({ 2 * vid1 + 1, 2 * vid0, -halfEdgeWeight(i) * (expw0.imag() - expw1.imag()) * r0 * r1 });\n\t\t\tAT.push_back({ 2 * vid1 + 1, 2 * vid0 + 1, -halfEdgeWeight(i) * (expw0.real() + expw1.real()) * r0 * r1 });\n\t\t}\n\t}\n\n\tif (deriv || hess)\n\t{\n\t\tEigen::SparseMatrix<double> A;\n\n\t\tA.resize(2 * nverts, 2 * nverts);\n\t\tA.setFromTriplets(AT.begin(), AT.end());\n\n\t\t// check whether A is PD\n\n\n\t\tif (deriv)\n\t\t{\n\t\t\tEigen::VectorXd fvals(2 * nverts);\n\t\t\tfor (int i = 0; i < nverts; i++)\n\t\t\t{\n\t\t\t\tfvals(2 * i) = zvals[i].real();\n\t\t\t\tfvals(2 * i + 1) = zvals[i].imag();\n\t\t\t}\n\t\t\t(*deriv) = A * fvals;\n\t\t}\n\n\t\tif (hess)\n\t\t\t(*hess) = AT;\n\t}\n\n\treturn energy;\n}\n\ndouble IntrinsicFormula::KnoppelEnergyFor2DVertexOmegaPerEdge(const Eigen::MatrixXd& pos, const MeshConnectivity& mesh, const Eigen::VectorXd& faceArea, const Eigen::MatrixXd& cotEntries, const std::vector<std::complex<double>>& zvals, const Eigen::MatrixXd& vertexOmega, const double edgeWeight, int eid, Eigen::Matrix<double, 8, 1>* deriv, Eigen::Matrix<double, 8, 8>* hess, bool isProj)\n{\n\tint vid0 = mesh.edgeVertex(eid, 0);\n\tint vid1 = mesh.edgeVertex(eid, 1);\n\n\tEigen::Vector2d e = (pos.row(vid1) - pos.row(vid0)).segment<2>(0);\n\n\tdouble w01 = vertexOmega.row(vid0).dot(e);\n\tdouble w10 = -vertexOmega.row(vid1).dot(e);\n\n\tdouble sin0 = std::sin(w01), cos0 = std::cos(w01);\n\tdouble sin1 = std::sin(w10), cos1 = std::cos(w10);\n\n\n\tEigen::Vector2d z0(zvals[vid0].real(), zvals[vid0].imag());\n\tEigen::Vector2d z1(zvals[vid1].real(), zvals[vid1].imag());\n\n\tEigen::Matrix2d mat0, mat1;\n\tmat0 << cos0, -sin0, sin0, cos0;\n\tmat1 << cos1, -sin1, sin1, cos1;\n\n\tEigen::Vector2d f0, f1;\n\tf0 = mat0 * z0 - z1;\n\tf1 = mat1 * z1 - z0;\n\n\tdouble energy = 0.5 * (f0.dot(f0) + f1.dot(f1)) * edgeWeight;\n\n\tif (deriv)\n\t\tderiv->setZero();\n\n\tif (deriv || hess)\n\t{\n\t\tEigen::Vector2d e0, e1;\n\t\te0 << 1, 0;\n\t\te1 << 0, 1;\n\n\t\tEigen::Matrix2d dmat0, dmat1;\n\t\tdmat0 << -sin0, -cos0, cos0, -sin0;\n\t\tdmat1 << -sin1, -cos1, cos1, -sin1;\n\n\t\tEigen::Matrix<double, 2, 8> gradF0, gradF1;\n\t\tgradF0.setZero();\n\t\tgradF1.setZero();\n\n\t\tgradF0.col(0) = mat0 * e0;\n\t\tgradF0.col(1) = mat0 * e1;\n\t\tgradF0.col(2) = -e0;\n\t\tgradF0.col(3) = -e1;\n\n\t\tgradF0.col(4) = dmat0 * z0 * e(0);\n\t\tgradF0.col(5) = dmat0 * z0 * e(1);\n\n\t\tgradF1.col(0) = -e0;\n\t\tgradF1.col(1) = -e1;\n\t\tgradF1.col(2) = mat1 * e0;\n\t\tgradF1.col(3) = mat1 * e1;\n\n\t\tgradF1.col(6) = -dmat1 * z1 * e(0);\n\t\tgradF1.col(7) = -dmat1 * z1 * e(1);\n\n\t\tif (deriv)\n\t\t\t*deriv = (f0.transpose() * gradF0 + f1.transpose() * gradF1) * edgeWeight;\n\n\t\tif (hess)\n\t\t{\n\t\t\t*hess = (gradF0.transpose() * gradF0 + gradF1.transpose() * gradF1) * edgeWeight;\n\n\t\t\t\n\t\t\t(*hess)(0, 4) += edgeWeight * (f0(0) * -sin0 * e(0) + f0(1) * cos0 * e(0));\n\t\t\t(*hess)(0, 5) += edgeWeight * (f0(0) * -sin0 * e(1) + f0(1) * cos0 * e(1));\n\n\t\t\t(*hess)(1, 4) += edgeWeight * (f0(0) * -cos0 * e(0) + f0(1) * -sin0 * e(0));\n\t\t\t(*hess)(1, 5) += edgeWeight * (f0(0) * -cos0 * e(1) + f0(1) * -sin0 * e(1));\n\n\t\t\t(*hess)(2, 6) += edgeWeight * (f1(0) * sin1 * e(0) - f1(1) * cos1 * e(0));\n\t\t\t(*hess)(2, 7) += edgeWeight * (f1(0) * sin1 * e(1) - f1(1) * cos1 * e(1));\n\n\t\t\t(*hess)(3, 6) += edgeWeight * (f1(0) * cos1 * e(0) + f1(1) * sin1 * e(0));\n\t\t\t(*hess)(3, 7) += edgeWeight * (f1(0) * cos1 * e(1) + f1(1) * sin1 * e(1));\n\n\t\t\t(*hess)(4, 0) = (*hess)(0, 4);\n\t\t\t(*hess)(4, 1) = (*hess)(1, 4);\n\t\t\t(*hess)(4, 4) += edgeWeight * (f0(0) * (-z0(0) * cos0 + z0(1) * sin0) + f0(1) * (-z0(0) * sin0 - z0(1) * cos0)) * e(0) * e(0);\n\t\t\t(*hess)(4, 5) += edgeWeight * (f0(0) * (-z0(0) * cos0 + z0(1) * sin0) + f0(1) * (-z0(0) * sin0 - z0(1) * cos0)) * e(0) * e(1);\n\n\n\t\t\t(*hess)(5, 0) = (*hess)(0, 5);\n\t\t\t(*hess)(5, 1) = (*hess)(1, 5);\n\t\t\t(*hess)(5, 4) += edgeWeight * (f0(0) * (-z0(0) * cos0 + z0(1) * sin0) + f0(1) * (-z0(0) * sin0 - z0(1) * cos0)) * e(1) * e(0);\n\t\t\t(*hess)(5, 5) += edgeWeight * (f0(0) * (-z0(0) * cos0 + z0(1) * sin0) + f0(1) * (-z0(0) * sin0 - z0(1) * cos0)) * e(1) * e(1);\n\n\n\t\t\t(*hess)(6, 2) = (*hess)(2, 6);\n\t\t\t(*hess)(6, 3) = (*hess)(3, 6);\n\t\t\t(*hess)(6, 6) += edgeWeight * (f1(0) * (-z1(0) * cos1 + z1(1) * sin1) + f1(1) * (-z1(0) * sin1 - z1(1) * cos1)) * e(0) * e(0);\n\t\t\t(*hess)(6, 7) += edgeWeight * (f1(0) * (-z1(0) * cos1 + z1(1) * sin1) + f1(1) * (-z1(0) * sin1 - z1(1) * cos1)) * e(0) * e(1);\n\n\n\t\t\t(*hess)(7, 2) = (*hess)(2, 7);\n\t\t\t(*hess)(7, 3) = (*hess)(3, 7);\n\t\t\t(*hess)(7, 6) += edgeWeight * (f1(0) * (-z1(0) * cos1 + z1(1) * sin1) + f1(1) * (-z1(0) * sin1 - z1(1) * cos1)) * e(1) * e(0);\n\t\t\t(*hess)(7, 7) += edgeWeight * (f1(0) * (-z1(0) * cos1 + z1(1) * sin1) + f1(1) * (-z1(0) * sin1 - z1(1) * cos1)) * e(1) * e(1);\n\t\t\t\n\n\t\t\tif (isProj)\n\t\t\t\t(*hess) = SPDProjection(*hess);\n\n\t\t}\n\n\t}\n\n\treturn energy;\n}\n\ndouble IntrinsicFormula::KnoppelEnergyFor2DVertexOmega(const Eigen::MatrixXd& pos, const MeshConnectivity& mesh, const Eigen::VectorXd& faceArea, const Eigen::MatrixXd& cotEntries, const std::vector<std::complex<double>>& zvals, const Eigen::MatrixXd& vertexOmega, Eigen::VectorXd* deriv, std::vector<Eigen::Triplet<double>>* hess, bool isProj)\n{\n\tstd::vector<Eigen::Triplet<double>> AT;\n\tint nfaces = mesh.nFaces();\n\tint nedges = mesh.nEdges();\n\tint nverts = zvals.size();\n\n\tEigen::VectorXd edgeWeight(nedges);\n\tedgeWeight.setZero();\n\n\tfor (int i = 0; i < nfaces; i++)  // form mass matrix\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint eid = mesh.faceEdge(i, j);\n\t\t\tedgeWeight(eid) += cotEntries(i, j);\n\t\t}\n\t}\n\tdouble energy = 0;\n\tedgeWeight.setConstant(1.0);\n\n\tif (deriv)\n\t{\n\t\tderiv->setZero(4 * nverts);\n\t}\n\t\n\tfor (int i = 0; i < nedges; i++)\n\t{\n\t\tEigen::Matrix<double, 8, 1> edgeDeriv;\n\t\tEigen::Matrix<double, 8, 8> edgeHess;\n\n\t\tenergy += KnoppelEnergyFor2DVertexOmegaPerEdge(pos, mesh, faceArea, cotEntries, zvals, vertexOmega, edgeWeight(i), i, deriv ? &edgeDeriv : NULL, hess ? &edgeHess : NULL, isProj);\n\n\n\t\tint vid0 = mesh.edgeVertex(i, 0);\n\t\tint vid1 = mesh.edgeVertex(i, 1);\n\n\t\tif (deriv)\n\t\t{\n\t\t\tderiv->segment<2>(2 * vid0) += edgeDeriv.segment<2>(0);\n\t\t\tderiv->segment<2>(2 * vid1) += edgeDeriv.segment<2>(2);\n\n\t\t\tderiv->segment<2>(2 * vid0 + 2 * nverts) += edgeDeriv.segment<2>(4);\n\t\t\tderiv->segment<2>(2 * vid1 + 2 * nverts) += edgeDeriv.segment<2>(6);\n\n\t\t}\n\n\t\tif (hess)\n\t\t{\n\t\t\tfor(int m = 0; m < 2; m++)\n\t\t\t\tfor (int n = 0; n < 2; n++)\n\t\t\t\t{\n\t\t\t\t\thess->push_back({ 2 * vid0 + m , 2 * vid0 + n, edgeHess(m, n) });\n\t\t\t\t\thess->push_back({ 2 * vid0 + m , 2 * vid1 + n, edgeHess(m, 2 + n) });\n\t\t\t\t\thess->push_back({ 2 * vid0 + m , 2 * vid0 + 2 * nverts + n, edgeHess(m, 4 + n) });\n\t\t\t\t\thess->push_back({ 2 * vid0 + m , 2 * vid1 + 2 * nverts + n, edgeHess(m, 6 + n) });\n\n\n\t\t\t\t\thess->push_back({ 2 * vid1 + m , 2 * vid0 + n, edgeHess(2 + m, n) });\n\t\t\t\t\thess->push_back({ 2 * vid1 + m , 2 * vid1 + n, edgeHess(2 + m, 2 + n) });\n\t\t\t\t\thess->push_back({ 2 * vid1 + m , 2 * vid0 + 2 * nverts + n, edgeHess(2 + m, 4 + n) });\n\t\t\t\t\thess->push_back({ 2 * vid1 + m , 2 * vid1 + 2 * nverts + n, edgeHess(2 + m, 6 + n) });\n\n\t\t\t\t\thess->push_back({ 2 * vid0 + 2 * nverts + m , 2 * vid0 + n, edgeHess(4 + m, n) });\n\t\t\t\t\thess->push_back({ 2 * vid0 + 2 * nverts + m , 2 * vid1 + n, edgeHess(4 + m, 2 + n) });\n\t\t\t\t\thess->push_back({ 2 * vid0 + 2 * nverts + m , 2 * vid0 + 2 * nverts + n, edgeHess(4 + m, 4 + n) });\n\t\t\t\t\thess->push_back({ 2 * vid0 + 2 * nverts + m , 2 * vid1 + 2 * nverts + n, edgeHess(4 + m, 6 + n) });\n\n\t\t\t\t\thess->push_back({ 2 * vid1 + 2 * nverts + m , 2 * vid0 + n, edgeHess(6 + m, n) });\n\t\t\t\t\thess->push_back({ 2 * vid1 + 2 * nverts + m , 2 * vid1 + n, edgeHess(6 + m, 2 + n) });\n\t\t\t\t\thess->push_back({ 2 * vid1 + 2 * nverts + m , 2 * vid0 + 2 * nverts + n, edgeHess(6 + m, 4 + n) });\n\t\t\t\t\thess->push_back({ 2 * vid1 + 2 * nverts + m , 2 * vid1 + 2 * nverts + n, edgeHess(6 + m, 6 + n) });\n\n\t\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\treturn energy;\n}\n\nvoid IntrinsicFormula::roundVertexZvalsFromHalfEdgeOmega(const MeshConnectivity &mesh, const Eigen::MatrixXd &halfEdgeW,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t const Eigen::VectorXd &faceArea,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t const Eigen::MatrixXd &cotEntries, const int nverts,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t std::vector<std::complex<double>> &zvals)\n{\n\tstd::vector<Eigen::Triplet<double>> BT;\n\tint nfaces = mesh.nFaces();\n\tint nedges = mesh.nEdges();\n\t\n\tfor(int i = 0; i < nfaces; i++)  // form mass matrix\n\t{\n\t\tfor(int j =0; j < 3; j++)\n\t\t{\n\t\t\tint vid = mesh.faceVertex(i, j);\n\t\t\tBT.push_back({2 * vid, 2 * vid, faceArea(i) / 3.0});\n\t\t\tBT.push_back({2 * vid + 1, 2 * vid + 1, faceArea(i) / 3.0});\n\t\t}\n\t}\n\tEigen::SparseMatrix<double> A;\n\tcomputeMatrixA(mesh, halfEdgeW, faceArea, cotEntries, nverts, A);\n\n\tEigen::SparseMatrix<double> B(2 * nverts, 2 * nverts);\n\tB.setFromTriplets(BT.begin(), BT.end());\n   /* std::cout << A.toDense() << std::endl;\n\tstd::cout << B.toDense() << std::endl;*/\n\n\tSpectra::SymShiftInvert<double> op(A, B);\n\tSpectra::SparseSymMatProd<double> Bop(B);\n\tSpectra::SymGEigsShiftSolver<Spectra::SymShiftInvert<double>, Spectra::SparseSymMatProd<double>, Spectra::GEigsMode::ShiftInvert> geigs(op, Bop, 1, 6, -1e-6);\n\tgeigs.init();\n\tint nconv = geigs.compute(Spectra::SortRule::LargestMagn, 1e6);\n\n\tEigen::VectorXd evalues;\n\tEigen::MatrixXd evecs;\n\n\tevalues = geigs.eigenvalues();\n\tevecs = geigs.eigenvectors();\n\tif (nconv != 1 || geigs.info() != Spectra::CompInfo::Successful)\n\t{\n\t\tstd::cout << \"Eigensolver failed to converge!!\" << std::endl;\n\t}\n\n\tstd::cout << \"Eigenvalue is \" << evalues[0] << std::endl;\n\n\tzvals.clear();\n\tfor(int i = 0; i < nverts; i++)\n\t{\n\t\tzvals.push_back(std::complex<double>(evecs(2 * i, 0), evecs(2 * i + 1, 0)));\n\t}\n}\n\nvoid IntrinsicFormula::roundVertexZvalsFromHalfEdgeOmegaVertexMag(const MeshConnectivity &mesh, const Eigen::MatrixXd& halfEdgeW, const Eigen::VectorXd& vertAmp, const Eigen::VectorXd& faceArea, const Eigen::MatrixXd& cotEntries, const int nverts, std::vector<std::complex<double>>& zvals)\n{\n\tstd::vector<Eigen::Triplet<double>> BT;\n\tint nfaces = mesh.nFaces();\n\tint nedges = mesh.nEdges();\n\n\tfor(int i = 0; i < nfaces; i++)  // form mass matrix\n\t{\n\t\tfor(int j =0; j < 3; j++)\n\t\t{\n\t\t\tint vid = mesh.faceVertex(i, j);\n\t\t\tBT.push_back({2 * vid, 2 * vid, faceArea(i) / 3.0});\n\t\t\tBT.push_back({2 * vid + 1, 2 * vid + 1, faceArea(i) / 3.0});\n\t\t}\n\t}\n\tEigen::SparseMatrix<double> A;\n\tcomputeMatrixAGivenMag(mesh, halfEdgeW, vertAmp, faceArea, cotEntries, nverts, A);\n\n\tEigen::CholmodSupernodalLLT<Eigen::SparseMatrix<double>> solver;\n\tEigen::SparseMatrix<double> I = A;\n\tI.setIdentity();\n\tdouble eps = 1e-16;\n    Eigen::SparseMatrix<double> tmpA = A + eps * I;\n\tsolver.compute(tmpA);\n\twhile(solver.info() != Eigen::Success)\n\t{\n\t\tstd::cout << \"matrix is not PD after adding \"<< eps << \" * I\" << std::endl;\n\t\tsolver.compute(tmpA);\n\t\teps *= 2;\n        tmpA = A + eps * I;\n\t}\n\n\tEigen::SparseMatrix<double> B(2 * nverts, 2 * nverts);\n\tB.setFromTriplets(BT.begin(), BT.end());\n\t/* std::cout << A.toDense() << std::endl;\n\t std::cout << B.toDense() << std::endl;*/\n\n\tSpectra::SymShiftInvert<double> op(A, B);\n\tSpectra::SparseSymMatProd<double> Bop(B);\n\tSpectra::SymGEigsShiftSolver<Spectra::SymShiftInvert<double>, Spectra::SparseSymMatProd<double>, Spectra::GEigsMode::ShiftInvert> geigs(op, Bop, 1, 6, -2 * eps);\n\tgeigs.init();\n\tint nconv = geigs.compute(Spectra::SortRule::LargestMagn, 1e6);\n\n\tEigen::VectorXd evalues;\n\tEigen::MatrixXd evecs;\n\n\tevalues = geigs.eigenvalues();\n\tevecs = geigs.eigenvectors();\n\tif (nconv != 1 || geigs.info() != Spectra::CompInfo::Successful)\n\t{\n\t\tstd::cout << \"Eigensolver failed to converge!!\" << std::endl;\n\t\texit(1);\n\t}\n\n\tstd::cout << \"Eigenvalue is \" << evalues[0] << std::endl;\n\n\tzvals.clear();\n\tfor(int i = 0; i < nverts; i++)\n\t{\n\t\tstd::complex<double> z = std::complex<double>(evecs(2 * i, 0), evecs(2 * i + 1, 0));\n\t\tz *= vertAmp(i) / std::abs(z);\n\t\tzvals.push_back(z);\n\t}\n}\n\nvoid IntrinsicFormula::roundZvalsForSpecificDomainWithGivenMag(const MeshConnectivity& mesh, const Eigen::MatrixXd& halfEdgeW, const Eigen::VectorXd& vertAmp, const Eigen::VectorXi& vertFlags, const Eigen::VectorXd& faceArea, const Eigen::MatrixXd& cotEntries, const int nverts, std::vector<std::complex<double>>& zvals)\n{\n\tstd::vector<Eigen::Triplet<double>> BT;\n\tint nfaces = mesh.nFaces();\n\tint nedges = mesh.nEdges();\n\n\tfor (int i = 0; i < nfaces; i++)  // form mass matrix\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint vid = mesh.faceVertex(i, j);\n\t\t\tBT.push_back({ 2 * vid, 2 * vid, faceArea(i) / 3.0 });\n\t\t\tBT.push_back({ 2 * vid + 1, 2 * vid + 1, faceArea(i) / 3.0 });\n\t\t}\n\t}\n\tEigen::SparseMatrix<double> A;\n\tcomputeMatrixAGivenMag(mesh, halfEdgeW, vertAmp, faceArea, cotEntries, nverts, A);\n//    computeMatrixA(mesh, halfEdgeW, faceArea, cotEntries, nverts, A);\n\n\tEigen::SparseMatrix<double> B(2 * nverts, 2 * nverts);\n\tB.setFromTriplets(BT.begin(), BT.end());\n\n    Eigen::CholmodSupernodalLLT<Eigen::SparseMatrix<double>> solver;\n    Eigen::SparseMatrix<double> I = A;\n    I.setIdentity();\n    double eps = 1e-16;\n    Eigen::SparseMatrix<double> tmpA = A + eps * I;\n    solver.compute(tmpA);\n    while(solver.info() != Eigen::Success)\n    {\n        std::cout << \"matrix is not PD after adding \"<< eps << \" * I\" << std::endl;\n        solver.compute(tmpA);\n        eps *= 2;\n        tmpA = A + eps * I;\n    }\n\n\tSpectra::SymShiftInvert<double> op(A, B);\n\tSpectra::SparseSymMatProd<double> Bop(B);\n\tSpectra::SymGEigsShiftSolver<Spectra::SymShiftInvert<double>, Spectra::SparseSymMatProd<double>, Spectra::GEigsMode::ShiftInvert> geigs(op, Bop, 1, 6, -2 * eps);\n\tgeigs.init();\n\tint nconv = geigs.compute(Spectra::SortRule::LargestMagn, 1e6);\n\n\tEigen::VectorXd evalues;\n\tEigen::MatrixXd evecs;\n\n\tevalues = geigs.eigenvalues();\n\tevecs = geigs.eigenvectors();\n\tif (nconv != 1 || geigs.info() != Spectra::CompInfo::Successful)\n\t{\n\t\tstd::cout << \"Eigensolver failed to converge!!\" << std::endl;\n\t}\n\n\tstd::cout << \"Eigenvalue is \" << evalues[0] << std::endl;\n\n\tzvals.clear();\n    Eigen::VectorXd fullVar = evecs;\n//\tEigen::VectorXd fullVar = projM.transpose() * evecs;\n\tfor (int i = 0; i < nverts; i++)\n\t{\n\t\tstd::complex<double> z = std::complex<double>(fullVar(2 * i, 0), fullVar(2 * i + 1, 0));\n\n        if (vertFlags(i) == 1)\n        {\n            z *= vertAmp(i) / std::abs(z);\n        }\n\n\t\tzvals.push_back(z);\n\t}\n}\n\nvoid IntrinsicFormula::roundZvalsForSpecificDomainWithBndValues(const Eigen::MatrixXd& pos, const MeshConnectivity& mesh, const Eigen::MatrixXd& halfEdgeW, const Eigen::VectorXi& vertFlags, const Eigen::VectorXd& faceArea, const Eigen::MatrixXd& cotEntries, const int nverts, std::vector<std::complex<double>>& vertZvals, double smoothnessCoeff)\n{\n\tEigen::VectorXd clampedVals(2 * nverts);\n\tclampedVals.setZero();\n\n\tstd::vector<Eigen::Triplet<double>> PT;\n\tint nDOFs = 0;\n\tfor (int i = 0; i < nverts; i++)\n\t{\n\t\tif (vertFlags(i) == 0)\t// free variables\n\t\t{\n\t\t\tPT.push_back({ 2 * nDOFs, 2 * i, 1.0 });\n\t\t\tPT.push_back({ 2 * nDOFs + 1, 2 * i + 1, 1.0 });\n\t\t\tnDOFs += 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tclampedVals(2 * i) = vertZvals[i].real();\n\t\t\tclampedVals(2 * i + 1) = vertZvals[i].imag();\n\t\t}\n\t}\n\tif (nDOFs == 0)\n\t\treturn;\n\tEigen::SparseMatrix<double> projM, unProjM;\n\tprojM.resize(2 * nDOFs, 2 * nverts);\n\tprojM.setFromTriplets(PT.begin(), PT.end());\n\n\tunProjM = projM.transpose();\n\n\tauto zList2CoordVec = [&](const std::vector<std::complex<double>>& zvals, Eigen::VectorXd& xvec, Eigen::VectorXd& yvec)\n\t{\n\t\txvec.setZero(zvals.size());\n\t\tyvec.setZero(zvals.size());\n\n\t\tfor (int i = 0; i < zvals.size(); i++)\n\t\t{\n\t\t\txvec(i) = zvals[i].real();\n\t\t\tyvec(i) = zvals[i].imag();\n\t\t}\n\t};\n\n\tauto zList2Vec = [&](const std::vector<std::complex<double>>& zvals)\n\t{\n\t\tEigen::VectorXd zvec(2 * zvals.size());\n\t\tfor (int i = 0; i < zvals.size(); i++)\n\t\t{\n\t\t\tzvec(2 * i) = zvals[i].real();\n\t\t\tzvec(2 * i + 1) = zvals[i].imag();\n\t\t}\n\t\treturn zvec;\n\t};\n\n\tauto vec2zList = [&](const Eigen::VectorXd& zvec)\n\t{\n\t\tstd::vector<std::complex<double>> zList;\n\t\tfor (int i = 0; i < zvec.size() / 2; i++)\n\t\t{\n\t\t\tzList.push_back(std::complex<double>(zvec(2 * i), zvec(2 * i + 1)));\n\t\t}\n\t\treturn zList;\n\t};\n\n\tauto projVar = [&](const std::vector<std::complex<double>>& zvals)\n\t{\n\t\tEigen::VectorXd zvec = zList2Vec(zvals);\n\t\treturn projM * zvec;\n\t};\n\n\tauto unprojVar = [&](const Eigen::VectorXd& zvec, const Eigen::VectorXd& clampedZvecs)\n\t{\n\t\tEigen::VectorXd fullZvec = unProjM * zvec + clampedVals;\n\t\treturn vec2zList(fullZvec);\n\t};\n\n\tEigen::SparseMatrix<double> L, lapL;\n\tigl::cotmatrix(pos, mesh.faces(), L);\n\n\tstd::vector<Eigen::Triplet<double>> lapT;\n\n\tfor (int k = 0; k < L.outerSize(); ++k)\n\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(L, k); it; ++it)\n\t\t{\n\t\t\tlapT.push_back(Eigen::Triplet<double>(2 * it.row(), 2 * it.col(), -it.value()));\n\t\t\tlapT.push_back(Eigen::Triplet<double>(2 * it.row() + 1, 2 * it.col() + 1, -it.value()));\n\t\t}\n\n\tlapL.resize(2 * nverts, 2 * nverts);\n\tlapL.setFromTriplets(lapT.begin(), lapT.end());\n\n\tauto funVal = [&](const Eigen::VectorXd& x, Eigen::VectorXd* grad, Eigen::SparseMatrix<double>* hess, bool isProj) \n\t{\n\t\tstd::vector<std::complex<double>> zList = unprojVar(x, clampedVals);\n\t\tEigen::VectorXd deriv;\n\t\tstd::vector<Eigen::Triplet<double>> T;\n\t\tEigen::SparseMatrix<double> H;\n\t\tdouble E = KnoppelEnergy(mesh, halfEdgeW, faceArea, cotEntries, zList, grad ? &deriv : NULL, hess ? &T : NULL);\n\n\t\tEigen::VectorXd fullx = zList2Vec(zList);\n\t\t\n\t\tif (smoothnessCoeff > 0)\n\t\t\tE += smoothnessCoeff * fullx.dot(lapL * fullx) / 2;\n\t\t\n\n\t\tif (grad)\n\t\t{\n\t\t\tif (smoothnessCoeff > 0)\n\t\t\t\tderiv += smoothnessCoeff * lapL * fullx;\n\t\t\t(*grad) = projM * deriv;\n\t\t}\n\t\tif (hess)\n\t\t{\n\t\t\tH.resize(2 * nverts, 2 * nverts);\n\t\t\tH.setFromTriplets(T.begin(), T.end());\n\n\t\t\tif (smoothnessCoeff > 0)\n\t\t\t\tH += smoothnessCoeff * lapL;\n\t\t\t(*hess) = projM * H * unProjM;\n\t\t}\n\n\t\treturn E;\n\t};\n\n\tauto maxStep = [&](const Eigen::VectorXd& x, const Eigen::VectorXd& dir) {\n\t\treturn 1.0;\n\t};\n\n\tEigen::VectorXd x0 = projVar(vertZvals);\n\tOptSolver::newtonSolver(funVal, maxStep, x0, 1000, 1e-6, 1e-10, 1e-15, true);\n\n\tEigen::VectorXd deriv;\n\tdouble E = funVal(x0, &deriv, NULL, false);\n\tstd::cout << \"terminated with energy : \" << E << \", gradient norm : \" << deriv.norm() << std::endl << std::endl;\n\tvertZvals = unprojVar(x0, clampedVals);\n}\n\n\ndouble IntrinsicFormula::lArg(const long &n, const Eigen::Vector3d &bary)\n{\n\tdouble larg = 0;\n\tdouble ti = bary(0), tj = bary(1), tk = bary(2);\n\tif(tk <= ti && tk <= tj)\n\t\tlarg = M_PI / 3 * n * (1 + (tj - ti) / (1 - 3 * tk));\n\telse if (ti <= tj && ti <= tk)\n\t\tlarg = M_PI / 3 * n * (3 + (tk - tj) / (1 - 3 * ti));\n\telse\n\t\tlarg = M_PI / 3 * n * (5 + (ti - tk) / (1 - 3 * tj));\n\treturn larg;\n}\n\nvoid IntrinsicFormula::getUpsamplingTheta(const MeshConnectivity &mesh, const Eigen::MatrixXd &halfEdgeW,\n\t\t\t\t\t\t\t\t\t\t  const std::vector<std::complex<double>> &zvals,\n\t\t\t\t\t\t\t\t\t\t  const std::vector<std::pair<int, Eigen::Vector3d>> &bary, Eigen::VectorXd& upTheta)\n{\n\tEigen::VectorXd edgeW = (halfEdgeW.col(0) - halfEdgeW.col(1)) / 2;\n\tint upsize = bary.size();\n\tupTheta.setZero(upsize);\n\n\tfor(int i = 0; i < bary.size(); i++)\n\t{\n\t\tint fid = bary[i].first;\n\t\tdouble omegaIJ = edgeW(mesh.faceEdge(fid, 2));\n\t\tdouble omegaJK = edgeW(mesh.faceEdge(fid, 0));\n\t\tdouble omegaKI = edgeW(mesh.faceEdge(fid, 1));\n\n\t\tdouble cIJ = mesh.faceVertex(fid, 0) == mesh.edgeVertex(mesh.faceEdge(fid, 2), 0) ? 1 : -1;\n\t\tdouble cJK = mesh.faceVertex(fid, 1) == mesh.edgeVertex(mesh.faceEdge(fid, 0), 0) ? 1 : -1;\n\t\tdouble cKI = mesh.faceVertex(fid, 2) == mesh.edgeVertex(mesh.faceEdge(fid, 1), 0) ? 1 : -1;\n\n\t\tomegaIJ *= cIJ;\n\t\tomegaJK *= cJK;\n\t\tomegaKI *= cKI;\n\n\t\tstd::complex<double> rij( std::cos(omegaIJ), std::sin(omegaIJ) );\n\t\tstd::complex<double> rjk( std::cos(omegaJK), std::sin(omegaJK) );\n\t\tstd::complex<double> rki( std::cos(omegaKI), std::sin(omegaKI) );\n\n\t\tstd::complex<double> psiI = zvals[mesh.faceVertex(fid, 0)];\n\t\tstd::complex<double> psiJ = zvals[mesh.faceVertex(fid, 1)];\n\t\tstd::complex<double> psiK = zvals[mesh.faceVertex(fid, 2)];\n\n\n\t\tdouble alphaI = std::arg(psiI);\n\t\tdouble alphaJ = alphaI + omegaIJ - std::arg(rij*psiI/psiJ); //fmodPI((varphiI + omegaIJ) - varphiJ); // could do this in terms of angles instead of complex numbers...\n\t\tdouble alphaK = alphaJ + omegaJK - std::arg(rjk*psiJ/psiK); //fmodPI((varphiJ + omegaJK) - varphiK); // mostly a matter of taste---possibly a matter of performance?\n\t\tdouble alphaL = alphaK + omegaKI - std::arg(rki*psiK/psiI); //fmodPI((varphiK + omegaKI) - varphiI);\n\n\t\t// adjust triangles containing zeros\n\t\tlong n = std::lround((alphaL-alphaI)/(2.*M_PI));\n\t\talphaJ -= 2.*M_PI*n/3.;\n\t\talphaK -= 4.*M_PI*n/3.;\n\n\t\tdouble theta = lArg(n, bary[i].second);\n\t\tupTheta(i) = theta + bary[i].second(0) * alphaI + bary[i].second(1) * alphaJ + bary[i].second(2) * alphaK;\n\t}\n}\n\nvoid IntrinsicFormula::testRoundingEnergy(const MeshConnectivity &mesh, const Eigen::MatrixXd &halfEdgeW,\n\t\t\t\t\t\t\t\t\t\t  const Eigen::VectorXd &faceArea, const Eigen::MatrixXd &cotEntries,\n\t\t\t\t\t\t\t\t\t\t  const int nverts, std::vector<std::complex<double>> zvals)\n{\n\tEigen::SparseMatrix<double> A;\n\tcomputeMatrixA(mesh, halfEdgeW, faceArea, cotEntries, nverts, A);\n\tint nfaces = mesh.nFaces();\n\tint nedges = mesh.nEdges();\n\n\tEigen::VectorXd halfEdgeWeight(nedges);\n\thalfEdgeWeight.setZero();\n\n\tfor(int i = 0; i < nfaces; i++)  // form mass matrix\n\t{\n\t\tfor(int j =0; j < 3; j++)\n\t\t{\n\t\t\tint eid = mesh.faceEdge(i, j);\n\t\t\thalfEdgeWeight(eid) += cotEntries(i, j);\n\t\t}\n\t}\n\tdouble energy = 0;\n\tfor(int i = 0; i < nedges; i++)\n\t{\n\t\tint vid0 = mesh.edgeVertex(i, 0);\n\t\tint vid1 = mesh.edgeVertex(i, 1);\n\n\t\tstd::complex<double> expw0 = std::complex<double>(std::cos(halfEdgeW(i, 0)), std::sin(halfEdgeW(i, 0)));\n\t\tstd::complex<double> expw1 = std::complex<double>(std::cos(halfEdgeW(i, 1)), std::sin(halfEdgeW(i, 1)));\n\n\t\tEigen::Matrix2d tmpMat;\n\n\t\ttmpMat(0, 0) = expw0.real();\n\t\ttmpMat(0, 1) = expw0.imag();\n\t\ttmpMat(1, 0) = -expw0.imag();\n\t\ttmpMat(1, 1) = expw0.real();\n\t\tEigen::Vector2d aibi(zvals[vid0].real(), zvals[vid0].imag());\n\t\tEigen::Vector2d ajbj(zvals[vid1].real(), zvals[vid1].imag());\n\n\t\tdouble part1 = 2 * aibi.dot(tmpMat * ajbj) + aibi.squaredNorm() + ajbj.squaredNorm();\n\t\tdouble part2 = ((zvals[vid0] * expw0 - zvals[vid1])).real() * ((zvals[vid0] * expw0 - zvals[vid1])).real() + ((zvals[vid0] * expw0 - zvals[vid1])).imag() * ((zvals[vid0] * expw0 - zvals[vid1])).imag();\n\n\t\tenergy += 0.5 * (norm((zvals[vid0] * expw0 - zvals[vid1])) + norm((zvals[vid1] * expw1 - zvals[vid0]))) * halfEdgeWeight(i);\n\n\t}\n\n\tEigen::VectorXd x(2 * nverts);\n\tfor(int i = 0; i < nverts; i++)\n\t{\n\t\tx(2 * i) = zvals[i].real();\n\t\tx(2 * i + 1) = zvals[i].imag();\n\t}\n}\n\nvoid IntrinsicFormula::testKnoppelEnergyFor2DVertexOmegaPerEdge(const Eigen::MatrixXd& pos, const MeshConnectivity& mesh, const Eigen::VectorXd& faceArea, const Eigen::MatrixXd& cotEntries, const std::vector<std::complex<double>>& zvals, const Eigen::MatrixXd& vertexOmega, const double edgeWeight, int eid)\n{\n\tint nverts = pos.rows();\n\tauto zbackup = zvals;\n\tauto wbackup = vertexOmega;\n\n\tEigen::Matrix<double, 8, 1> deriv;\n\tEigen::Matrix<double, 8, 8> hess;\n   \n\tdouble e = KnoppelEnergyFor2DVertexOmegaPerEdge(pos, mesh, faceArea, cotEntries, zvals, vertexOmega, edgeWeight, eid, &deriv, &hess, false);\n\tstd::cout << \"energy: \" << e << std::endl;\n\n\tint vid0 = mesh.edgeVertex(eid, 0);\n\tint vid1 = mesh.edgeVertex(eid, 1);\n\n\tEigen::Vector2d edge = (pos.row(vid1) - pos.row(vid0)).segment<2>(0);\n\tEigen::Vector2d z0(zvals[vid0].real(), zvals[vid0].imag());\n\tEigen::Vector2d z1(zvals[vid1].real(), zvals[vid1].imag());\n\n\tstd::cout << \"(a0, b0): \" << z0.transpose() << std::endl;\n\tstd::cout << \"(a1, b1): \" << z1.transpose() << std::endl;\n\tstd::cout << \"e: \" << edge.transpose() << std::endl;\n\tstd::cout << \"w0: \" << vertexOmega.row(vid0) << std::endl;\n\tstd::cout << \"w1: \" << vertexOmega.row(vid1) << std::endl;\n\n\tstd::cout << \"hess: \\n\" << hess << std::endl;\n   \n\n\tEigen::Matrix<double, 8, 1> dir = deriv;\n\tdir.setRandom();\n\n   \n\n\tfor (int i = 3; i < 9; i++)\n\t{\n\t\tdouble eps = std::pow(0.1, i);\n\n\t\tfor (int j = 0; j < 2; j++)\n\t\t{\n\t\t\tint v = mesh.edgeVertex(eid, j);\n\t\t\tzbackup[v] = std::complex<double>(zvals[v].real() + dir(2 * j) * eps, zvals[v].imag() + dir(1 + 2 * j) * eps);\n\t\t\twbackup(v, 0) = vertexOmega(v, 0) + eps * dir(4 + 2 * j);\n\t\t\twbackup(v, 1) = vertexOmega(v, 1) + eps * dir(5 + 2 * j);\n\t\t}\n\n\t\tEigen::Matrix<double, 8, 1> deriv1;\n\t\tdouble e1 = KnoppelEnergyFor2DVertexOmegaPerEdge(pos, mesh, faceArea, cotEntries, zbackup, wbackup, edgeWeight, eid, &deriv1, NULL, false);\n\n\t\tstd::cout << \"eps: \" << eps << std::endl;\n\t\tstd::cout << \"value-gradient check: \" << (e1 - e) / eps - dir.dot(deriv) << std::endl;\n\t\tstd::cout << \"gradient-hessian check: \" << ((deriv1 - deriv) / eps - hess * dir).norm() << std::endl;\n\t}\n}\n\n\nvoid IntrinsicFormula::testKnoppelEnergyFor2DVertexOmega(const Eigen::MatrixXd& pos, const MeshConnectivity& mesh, const Eigen::VectorXd& faceArea, const Eigen::MatrixXd& cotEntries, const std::vector<std::complex<double>>& zvals, const Eigen::MatrixXd& vertexOmega)\n{\n\tEigen::VectorXd deriv;\n\tEigen::SparseMatrix<double> hess;\n\tstd::vector<Eigen::Triplet<double>> hessT;\n\n\tdouble e = KnoppelEnergyFor2DVertexOmega(pos, mesh, faceArea, cotEntries, zvals, vertexOmega, &deriv, &hessT, false);\n\tstd::cout << \"energy: \" << e << std::endl;\n\thess.resize(deriv.rows(), deriv.rows());\n\thess.setFromTriplets(hessT.begin(), hessT.end());\n\n\tEigen::VectorXd dir = deriv;\n\tdir.setRandom();\n\t\n\tint nverts = pos.rows();\n\tauto zbackup = zvals;\n\tauto wbackup = vertexOmega;\n\n\tfor (int i = 3; i < 9; i++)\n\t{\n\t\tdouble eps = std::pow(0.1, i);\n\n\t\tfor (int v = 0; v < nverts; v++)\n\t\t{\n\t\t\tzbackup[v] = std::complex<double>(zvals[v].real() + dir(2 * v) * eps, zvals[v].imag() + dir(2 * v + 1) * eps);\n\t\t\twbackup(v, 0) = vertexOmega(v, 0) + eps * dir(2 * v + 2 * nverts);\n\t\t\twbackup(v, 1) = vertexOmega(v, 1) + eps * dir(2 * v + 2 * nverts + 1);\n\t\t}\n\n\t\tEigen::VectorXd deriv1;\n\t\tdouble e1 = KnoppelEnergyFor2DVertexOmega(pos, mesh, faceArea, cotEntries, zbackup, wbackup, &deriv1, NULL, false);\n\n\t\tstd::cout << \"eps: \" << eps << std::endl;\n\t\tstd::cout << \"value-gradient check: \" << (e1 - e) / eps - dir.dot(deriv) << std::endl;\n\t\tstd::cout << \"gradient-hessian check: \" << ((deriv1 - deriv) / eps - hess * dir).norm() << std::endl;\n\t}\n}", "meta": {"hexsha": "218ac2d3d50095e8349beab248f6e539bd04136a", "size": 35781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/IntrinsicFormula/KnoppelStripePattern.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/IntrinsicFormula/KnoppelStripePattern.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/IntrinsicFormula/KnoppelStripePattern.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.9608040201, "max_line_length": 389, "alphanum_fraction": 0.6033649143, "num_tokens": 13305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5200511841754825}}
{"text": "/*******************************************************\n * Copyright (C) 2020, RAM-LAB, Hong Kong University of Science and Technology\n *\n * This file is part of M-LOAM (https://ram-lab.com/file/jjiao/m-loam).\n * If you use this code, please cite the respective publications as\n * listed on the above websites.\n *\n * Licensed under the GNU General Public License v3.0;\n * you may not use this file except in compliance with the License.\n *\n * Author: Jianhao JIAO (jiaojh1994@gmail.com)\n *******************************************************/\n\n#pragma once\n\n#include <cmath>\n#include <cassert>\n#include <cstring>\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n\n#include <Eigen/Eigen>\n#include <Eigen/Dense>\n\ntemplate <typename Derived>\nstatic Eigen::Quaternion<typename Derived::Scalar> deltaQ(const Eigen::MatrixBase<Derived> &theta)\n{\n    typedef typename Derived::Scalar Scalar_t;\n    Eigen::Quaternion<Scalar_t> dq;\n    Eigen::Matrix<Scalar_t, 3, 1> half_theta = theta;\n    half_theta /= static_cast<Scalar_t>(2.0);\n    dq.w() = static_cast<Scalar_t>(1.0);\n    dq.x() = half_theta.x();\n    dq.y() = half_theta.y();\n    dq.z() = half_theta.z();\n    return dq;\n}\ntemplate <typename Derived>\nstatic Eigen::Matrix<typename Derived::Scalar, 3, 3> skewSymmetric(const Eigen::MatrixBase<Derived> &q)\n{\n    Eigen::Matrix<typename Derived::Scalar, 3, 3> ans;\n    ans << typename Derived::Scalar(0), -q(2), q(1),\n        q(2), typename Derived::Scalar(0), -q(0),\n        -q(1), q(0), typename Derived::Scalar(0);\n    return ans;\n}\n\n\n// pure odom planar factor\nclass LidarPureOdomPlaneNormFactor : public ceres::SizedCostFunction<1, 7, 7, 7>\n{\n\npublic:\n\tLidarPureOdomPlaneNormFactor(const Eigen::Vector3d &point,\n\t\t\t\t\t\t\t\t const Eigen::Vector4d &coeff,\n\t\t\t\t\t\t\t\t const double &sqrt_info = 1.0)\n\t\t: point_(point),\n\t\t  coeff_(coeff),\n\t\t  sqrt_info_(sqrt_info) {}\n\n\t// residual = sum(w^(T) * (R * p + t) + d)\n\tbool Evaluate(double const *const *param, double *residuals, double **jacobians) const\n    {\n\t\tEigen::Quaterniond Q_pivot(param[0][6], param[0][3], param[0][4], param[0][5]);\n\t\tEigen::Vector3d t_pivot(param[0][0], param[0][1], param[0][2]);\n\t\tEigen::Quaterniond Q_i(param[1][6], param[1][3], param[1][4], param[1][5]);\n\t\tEigen::Vector3d t_i(param[1][0], param[1][1], param[1][2]);\n\t\tEigen::Quaterniond Q_ext(param[2][6], param[2][3], param[2][4], param[2][5]);\n\t\tEigen::Vector3d t_ext(param[2][0], param[2][1], param[2][2]);\n\n\t\tEigen::Quaterniond Q_pi = Q_pivot.conjugate() * Q_i;\n\t\tEigen::Vector3d t_pi = Q_pivot.conjugate() * (t_i - t_pivot);\n\t\tEigen::Quaterniond Q_ext_pi = Q_pi * Q_ext;\n\t\tEigen::Vector3d t_ext_pi = Q_pi * t_ext + t_pi;\n\n\t\tEigen::Vector3d w(coeff_(0), coeff_(1), coeff_(2));\n\t\tconst double d = coeff_(3);\n\t\tconst double r = w.dot(Q_ext_pi * point_ + t_ext_pi) + d;\n\t\tresiduals[0] = sqrt_info_ * r;\n\n\t\t// jacobians: 3x7\n        if (jacobians)\n        {\n            Eigen::Matrix3d Rp = Q_pivot.toRotationMatrix();\n\t\t\tEigen::Matrix3d Ri = Q_i.toRotationMatrix();\n            Eigen::Matrix3d Rext = Q_ext.toRotationMatrix();\n            if (jacobians[0])\n            {\n                Eigen::Map<Eigen::Matrix<double, 1, 7, Eigen::RowMajor> > jacobian_pose_pivot(jacobians[0]);\n\n                Eigen::Matrix<double, 1, 6> jaco_pivot;\n\t\t\t\tjaco_pivot.leftCols<3>() = -w.transpose() * Rp.transpose();\n\t\t\t\tjaco_pivot.rightCols<3>() = w.transpose() * (Rp.transpose() *\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t skewSymmetric(Ri * Rext * point_ + Ri * t_ext + t_i - t_pivot));\n\n                jacobian_pose_pivot.leftCols<6>() = sqrt_info_ * jaco_pivot;\n                jacobian_pose_pivot.rightCols<1>().setZero();\n            }\n\n            if (jacobians[1])\n            {\n                Eigen::Map<Eigen::Matrix<double, 1, 7, Eigen::RowMajor> > jacobian_pose_i(jacobians[1]);\n\n                Eigen::Matrix<double, 1, 6> jaco_i;\n\t\t\t\tjaco_i.leftCols<3>() = w.transpose() * Rp.transpose();\n\t\t\t\tjaco_i.rightCols<3>() = -w.transpose() * Rp.transpose() *\n\t\t\t\t\t\t\t\t\t\tRi * skewSymmetric(Rext * point_ + t_ext);\n\n                jacobian_pose_i.leftCols<6>() = sqrt_info_ * jaco_i;\n                jacobian_pose_i.rightCols<1>().setZero();\n            }\n\n            if (jacobians[2])\n            {\n                Eigen::Map<Eigen::Matrix<double, 1, 7, Eigen::RowMajor> > jacobian_pose_ex(jacobians[2]);\n\n\t\t\t\tEigen::Matrix<double, 1, 6> jaco_ex;\n\t\t\t\tjaco_ex.leftCols<3>() = w.transpose() * Rp.transpose() * Ri;\n\t\t\t\tjaco_ex.rightCols<3>() = -w.transpose() * Rp.transpose() * Ri * skewSymmetric(Rext * point_);\n\n                jacobian_pose_ex.leftCols<6>() = sqrt_info_ * jaco_ex;\n                jacobian_pose_ex.rightCols<1>().setZero();\n            }\n        }\n        return true;\n    }\n\n\t// TODO: check if derived jacobian == perturbation on the raw function\n    void check(double **param)\n    {\n        double *res = new double[1];\n        double **jaco = new double *[3];\n        jaco[0] = new double[1 * 7];\n        jaco[1] = new double[1 * 7];\n        jaco[2] = new double[1 * 7];\n        Evaluate(param, res, jaco);\n\t\tstd::cout << \"[LidarPureOdomPlaneNormFactor] check begins\" << std::endl;\n        std::cout << \"analytical:\" << std::endl;\n\n        std::cout << res[0] << std::endl;\n        std::cout << Eigen::Map<Eigen::Matrix<double, 1, 7, Eigen::RowMajor> >(jaco[0]) << std::endl;\n        std::cout << Eigen::Map<Eigen::Matrix<double, 1, 7, Eigen::RowMajor> >(jaco[1]) << std::endl;\n        std::cout << Eigen::Map<Eigen::Matrix<double, 1, 7, Eigen::RowMajor> >(jaco[2]) << std::endl;\n\n\t\tdelete[] jaco[0];\n\t\tdelete[] jaco[1];\n\t\tdelete[] jaco[2];\n\t\tdelete[] jaco;\n\t\tdelete[] res;\n\n\t\tEigen::Quaterniond Q_pivot(param[0][6], param[0][3], param[0][4], param[0][5]);\n\t\tEigen::Vector3d t_pivot(param[0][0], param[0][1], param[0][2]);\n\t\tEigen::Quaterniond Q_i(param[1][6], param[1][3], param[1][4], param[1][5]);\n\t\tEigen::Vector3d t_i(param[1][0], param[1][1], param[1][2]);\n\t\tEigen::Quaterniond Q_ext(param[2][6], param[2][3], param[2][4], param[2][5]);\n\t\tEigen::Vector3d t_ext(param[2][0], param[2][1], param[2][2]);\n\n\t\tEigen::Quaterniond Q_pi = Q_pivot.conjugate() * Q_i;\n\t\tEigen::Vector3d t_pi = Q_pivot.conjugate() * (t_i - t_pivot);\n\t\tEigen::Quaterniond Q_ext_pi = Q_pi * Q_ext;\n\t\tEigen::Vector3d t_ext_pi = Q_pi * t_ext + t_pi;\n\n\t\tEigen::Vector3d w(coeff_(0), coeff_(1), coeff_(2));\n        double d = coeff_(3);\n\t\tdouble r = w.dot(Q_ext_pi * point_ + t_ext_pi) + d;\n        r *= sqrt_info_;\n\n        std::cout << \"perturbation:\" << std::endl;\n        std::cout << r << std::endl;\n\n        const double eps = 1e-6;\n        Eigen::Matrix<double, 1, 18> num_jacobian;\n\n\t\t// add random perturbation\n\t\tfor (int k = 0; k < 18; k++)\n\t\t{\n\t\t\tEigen::Quaterniond Q_pivot(param[0][6], param[0][3], param[0][4], param[0][5]);\n\t\t\tEigen::Vector3d t_pivot(param[0][0], param[0][1], param[0][2]);\n\t\t\tEigen::Quaterniond Q_i(param[1][6], param[1][3], param[1][4], param[1][5]);\n\t\t\tEigen::Vector3d t_i(param[1][0], param[1][1], param[1][2]);\n\t\t\tEigen::Quaterniond Q_ext(param[2][6], param[2][3], param[2][4], param[2][5]);\n\t\t\tEigen::Vector3d t_ext(param[2][0], param[2][1], param[2][2]);\n\t\t\tint a = k / 3, b = k % 3;\n\t\t\tEigen::Vector3d delta = Eigen::Vector3d(b == 0, b == 1, b == 2) * eps;\n\n\t\t\tif (a == 0)\n\t\t\t\tt_pivot += delta;\n\t\t\telse if (a == 1)\n\t\t\t\tQ_pivot = Q_pivot * deltaQ(delta);\n\t\t\telse if (a == 2)\n\t\t\t\tt_i += delta;\n\t\t\telse if (a == 3)\n\t\t\t\tQ_i = Q_i * deltaQ(delta);\n\t\t\telse if (a == 4)\n\t\t\t\tt_ext += delta;\n\t\t\telse if (a == 5)\n\t\t\t\tQ_ext = Q_ext * deltaQ(delta);\n\n\t\t\tEigen::Quaterniond Q_pi = Q_pivot.conjugate() * Q_i;\n\t\t\tEigen::Vector3d t_pi = Q_pivot.conjugate() * (t_i - t_pivot);\n\t\t\tEigen::Quaterniond Q_ext_pi = Q_pi * Q_ext;\n\t\t\tEigen::Vector3d t_ext_pi = Q_pi * t_ext + t_pi;\n\n\t\t\tEigen::Vector3d w(coeff_(0), coeff_(1), coeff_(2));\n\t        double d = coeff_(3);\n\t\t\tdouble tmp_r = w.dot(Q_ext_pi * point_ + t_ext_pi) + d;\n\t        tmp_r *= sqrt_info_;\n            num_jacobian(k) = (tmp_r - r) / eps;\n        }\n        std::cout << num_jacobian.block<1, 6>(0, 0) << std::endl;\n        std::cout << num_jacobian.block<1, 6>(0, 6) << std::endl;\n        std::cout << num_jacobian.block<1, 6>(0, 12) << std::endl;\n    }\n\nprivate:\n\tconst Eigen::Vector3d point_;\n\tconst Eigen::Vector4d coeff_;\n\tconst double sqrt_info_;\n};\n\n// pure odom planar factor\nclass LidarPureOdomEdgeFactor : public ceres::SizedCostFunction<1, 7, 7, 7>\n{\npublic:\n\tLidarPureOdomEdgeFactor(const Eigen::Vector3d &point,\n\t\t\t\t\t\t\tconst Eigen::VectorXd &coeff,\n\t\t\t\t\t\t\tconst double &sqrt_info = 1.0)\n\t\t: point_(point),\n\t\t  coeff_(coeff),\n\t\t  sqrt_info_(sqrt_info) {}\n\n\t// residual = sum(w^(T) * (R * p + t) + d)\n\tbool Evaluate(double const *const *param, double *residuals, double **jacobians) const\n    {\n\t\tEigen::Quaterniond Q_pivot(param[0][6], param[0][3], param[0][4], param[0][5]);\n\t\tEigen::Vector3d t_pivot(param[0][0], param[0][1], param[0][2]);\n\t\tEigen::Quaterniond Q_i(param[1][6], param[1][3], param[1][4], param[1][5]);\n\t\tEigen::Vector3d t_i(param[1][0], param[1][1], param[1][2]);\n\t\tEigen::Quaterniond Q_ext(param[2][6], param[2][3], param[2][4], param[2][5]);\n\t\tEigen::Vector3d t_ext(param[2][0], param[2][1], param[2][2]);\n\n\t\tEigen::Quaterniond Q_pi = Q_pivot.conjugate() * Q_i;\n\t\tEigen::Vector3d t_pi = Q_pivot.conjugate() * (t_i - t_pivot);\n\t\tEigen::Quaterniond Q_ext_pi = Q_pi * Q_ext;\n\t\tEigen::Vector3d t_ext_pi = Q_pi * t_ext + t_pi;\n\n\t\tEigen::Vector3d lpa(coeff_(0), coeff_(1), coeff_(2));\n\t\tEigen::Vector3d lpb(coeff_(3), coeff_(4), coeff_(5));\n\t\tEigen::Vector3d lp = Q_ext_pi * point_ + t_ext_pi;\n\n        Eigen::Vector3d nu = (lp - lpa).cross(lp - lpb);\n        Eigen::Vector3d de = lpa - lpb;\n        residuals[0] = sqrt_info_ * nu.norm() / de.norm();\t\t\n\n\t\t// jacobians: 1x21\n        if (jacobians)\n        {\n            Eigen::Matrix3d Rp = Q_pivot.toRotationMatrix();\n\t\t\tEigen::Matrix3d Ri = Q_i.toRotationMatrix();\n            Eigen::Matrix3d Rext = Q_ext.toRotationMatrix();\n\n\t\t\tEigen::Matrix<double, 1, 3> eta = 1.0 / de.norm() * nu.normalized().transpose();\n\t\t\tEigen::Vector3d ba = lp - lpa;\n\t\t\tEigen::Vector3d bb = lp - lpb;\n\n            if (jacobians[0])\n            {\n                Eigen::Map<Eigen::Matrix<double, 1, 7, Eigen::RowMajor> > jacobian_pose_pivot(jacobians[0]);\n\n                Eigen::Matrix<double, 1, 6> jaco_pivot;\n\t\t\t\tjaco_pivot.leftCols<3>() = - eta * skewSymmetric(ba - bb) * Rp.transpose();\n\t\t\t\tjaco_pivot.rightCols<3>() = eta * skewSymmetric(ba - bb) * \n\t\t\t\t\tskewSymmetric(Rp.transpose() * (Ri * Rext * point_ + Ri * t_ext + t_i - t_pivot));\n\n\t\t\t\tjacobian_pose_pivot.setZero();\n                jacobian_pose_pivot.leftCols<6>() = sqrt_info_ * jaco_pivot;\n            }\n\n            if (jacobians[1])\n            {\n                Eigen::Map<Eigen::Matrix<double, 1, 7, Eigen::RowMajor> > jacobian_pose_i(jacobians[1]);\n\n                Eigen::Matrix<double, 1, 6> jaco_i;\n\t\t\t\tjaco_i.leftCols<3>() = eta * skewSymmetric(ba - bb) * Rp.transpose();\n\t\t\t\tjaco_i.rightCols<3>() = - eta * skewSymmetric(ba - bb) * Rp.transpose() * Ri * \n\t\t\t\t\tskewSymmetric(Rext * point_ + t_ext);\n\n\t\t\t\tjacobian_pose_i.setZero();\n                jacobian_pose_i.leftCols<6>() = sqrt_info_ * jaco_i;\n            }\n\n            if (jacobians[2])\n            {\n                Eigen::Map<Eigen::Matrix<double, 1, 7, Eigen::RowMajor> > jacobian_pose_ex(jacobians[2]);\n\n\t\t\t\tEigen::Matrix<double, 1, 6> jaco_ex;\n\t\t\t\tjaco_ex.leftCols<3>() = eta * skewSymmetric(ba - bb) * Rp.transpose() * Ri;\n\t\t\t\tjaco_ex.rightCols<3>() = - eta * skewSymmetric(ba - bb) * Rp.transpose() * Ri * \n\t\t\t\t\t(Rext * skewSymmetric(point_) + skewSymmetric(t_ext));\n\n\t\t\t\tjacobian_pose_ex.setZero();\n                jacobian_pose_ex.leftCols<6>() = sqrt_info_ * jaco_ex;\n            }\n        }\n        return true;\n    }\n\n\t// TODO: check if derived jacobian == perturbation on the raw function\n    void check(double **param)\n    {\n        double *res = new double[1];\n        double **jaco = new double *[3];\n        jaco[0] = new double[1 * 7];\n        jaco[1] = new double[1 * 7];\n        jaco[2] = new double[1 * 7];\n        Evaluate(param, res, jaco);\n\t\tstd::cout << \"[LidarPureOdomEdgeFactor] check begins\" << std::endl;\n        std::cout << \"analytical:\" << std::endl;\n\n        std::cout << res[0] << std::endl;\n        std::cout << Eigen::Map<Eigen::Matrix<double, 1, 7, Eigen::RowMajor> >(jaco[0]) << std::endl;\n        std::cout << Eigen::Map<Eigen::Matrix<double, 1, 7, Eigen::RowMajor> >(jaco[1]) << std::endl;\n        std::cout << Eigen::Map<Eigen::Matrix<double, 1, 7, Eigen::RowMajor> >(jaco[2]) << std::endl;\n\n\t\tdelete[] jaco[0];\n\t\tdelete[] jaco[1];\n\t\tdelete[] jaco[2];\n\t\tdelete[] jaco;\n\t\tdelete[] res;\n\n\t\tEigen::Quaterniond Q_pivot(param[0][6], param[0][3], param[0][4], param[0][5]);\n\t\tEigen::Vector3d t_pivot(param[0][0], param[0][1], param[0][2]);\n\t\tEigen::Quaterniond Q_i(param[1][6], param[1][3], param[1][4], param[1][5]);\n\t\tEigen::Vector3d t_i(param[1][0], param[1][1], param[1][2]);\n\t\tEigen::Quaterniond Q_ext(param[2][6], param[2][3], param[2][4], param[2][5]);\n\t\tEigen::Vector3d t_ext(param[2][0], param[2][1], param[2][2]);\n\n\t\tEigen::Quaterniond Q_pi = Q_pivot.conjugate() * Q_i;\n\t\tEigen::Vector3d t_pi = Q_pivot.conjugate() * (t_i - t_pivot);\n\t\tEigen::Quaterniond Q_ext_pi = Q_pi * Q_ext;\n\t\tEigen::Vector3d t_ext_pi = Q_pi * t_ext + t_pi;\n\n\t\tEigen::Vector3d lpa(coeff_(0), coeff_(1), coeff_(2));\n\t\tEigen::Vector3d lpb(coeff_(3), coeff_(4), coeff_(5));\n\t\tEigen::Vector3d lp = Q_ext_pi * point_ + t_ext_pi;\n\n        Eigen::Vector3d nu = (lp - lpa).cross(lp - lpb);\n        Eigen::Vector3d de = lpa - lpb;\n        double r = sqrt_info_ * nu.norm() / de.norm();\t\t\n\n        std::cout << \"perturbation:\" << std::endl;\n        std::cout << r << std::endl;\n\n        const double eps = 1e-6;\n        Eigen::Matrix<double, 1, 18> num_jacobian;\n\n\t\t// add random perturbation\n\t\tfor (int k = 0; k < 18; k++)\n\t\t{\n\t\t\tEigen::Quaterniond Q_pivot(param[0][6], param[0][3], param[0][4], param[0][5]);\n\t\t\tEigen::Vector3d t_pivot(param[0][0], param[0][1], param[0][2]);\n\t\t\tEigen::Quaterniond Q_i(param[1][6], param[1][3], param[1][4], param[1][5]);\n\t\t\tEigen::Vector3d t_i(param[1][0], param[1][1], param[1][2]);\n\t\t\tEigen::Quaterniond Q_ext(param[2][6], param[2][3], param[2][4], param[2][5]);\n\t\t\tEigen::Vector3d t_ext(param[2][0], param[2][1], param[2][2]);\n\t\t\tint a = k / 3, b = k % 3;\n\t\t\tEigen::Vector3d delta = Eigen::Vector3d(b == 0, b == 1, b == 2) * eps;\n\n\t\t\tif (a == 0)\n\t\t\t\tt_pivot += delta;\n\t\t\telse if (a == 1)\n\t\t\t\tQ_pivot = Q_pivot * deltaQ(delta);\n\t\t\telse if (a == 2)\n\t\t\t\tt_i += delta;\n\t\t\telse if (a == 3)\n\t\t\t\tQ_i = Q_i * deltaQ(delta);\n\t\t\telse if (a == 4)\n\t\t\t\tt_ext += delta;\n\t\t\telse if (a == 5)\n\t\t\t\tQ_ext = Q_ext * deltaQ(delta);\n\n\t\t\tEigen::Quaterniond Q_pi = Q_pivot.conjugate() * Q_i;\n\t\t\tEigen::Vector3d t_pi = Q_pivot.conjugate() * (t_i - t_pivot);\n\t\t\tEigen::Quaterniond Q_ext_pi = Q_pi * Q_ext;\n\t\t\tEigen::Vector3d t_ext_pi = Q_pi * t_ext + t_pi;\n\n\t\t\tEigen::Vector3d lpa(coeff_(0), coeff_(1), coeff_(2));\n\t\t\tEigen::Vector3d lpb(coeff_(3), coeff_(4), coeff_(5));\n\t\t\tEigen::Vector3d lp = Q_ext_pi * point_ + t_ext_pi;\n\n\t\t\tEigen::Vector3d nu = (lp - lpa).cross(lp - lpb);\n\t\t\tEigen::Vector3d de = lpa - lpb;\n\t\t\tdouble tmp_r = sqrt_info_ * nu.norm() / de.norm();\n            num_jacobian(k) = (tmp_r - r) / eps;\n        }\n        std::cout << num_jacobian.block<1, 6>(0, 0) << std::endl;\n        std::cout << num_jacobian.block<1, 6>(0, 6) << std::endl;\n        std::cout << num_jacobian.block<1, 6>(0, 12) << std::endl;\n    }\n\nprivate:\n\tconst Eigen::Vector3d point_;\n\tconst Eigen::VectorXd coeff_;\n\tconst double sqrt_info_;\n};\n\n\n// pure odom edge factor using auto diff\nclass LidarPureOdomEdgeFactorAuto\n{\npublic:\n\tLidarPureOdomEdgeFactorAuto(const Eigen::Vector3d &point,\n\t\t\t\t\t\t\t    const Eigen::VectorXd &coeff,\n\t\t\t\t\t\t\t    const double &sqrt_info = 1.0)\n\t\t: point_(point),\n\t\t  coeff_(coeff),\n\t\t  sqrt_info_(sqrt_info) {}\n\n\ttemplate <typename T>\n\tbool operator()(const T *param1, const T *param2, const T *param3, T *residuals) const\n\t{\n\t\tEigen::Quaternion<T> Q_pivot(param1[6], param1[3], param1[4], param1[5]);\n\t\tEigen::Matrix<T, 3, 1> t_pivot(param1[0], param1[1], param1[2]);\n\t\tEigen::Quaternion<T> Q_i(param2[6], param2[3], param2[4], param2[5]);\n\t\tEigen::Matrix<T, 3, 1> t_i(param2[0], param2[1], param2[2]);\n\t\tEigen::Quaternion<T> Q_ext(param3[6], param3[3], param3[4], param3[5]);\n\t\tEigen::Matrix<T, 3, 1> t_ext(param3[0], param3[1], param3[2]);\n\n\t\tEigen::Quaternion<T> Q_pi = Q_pivot.conjugate() * Q_i;\n\t\tEigen::Matrix<T, 3, 1> t_pi = Q_pivot.conjugate() * (t_i - t_pivot);\n\t\tEigen::Quaternion<T> Q_ext_pi = Q_pi * Q_ext;\n\t\tEigen::Matrix<T, 3, 1> t_ext_pi = Q_pi * t_ext + t_pi;\n\n\t\tEigen::Matrix<T, 3, 1> cp(T(point_.x()), T(point_.y()), T(point_.z()));\n\t\tEigen::Matrix<T, 3, 1> lpa(T(coeff_(0)), T(coeff_(1)), T(coeff_(2)));\n\t\tEigen::Matrix<T, 3, 1> lpb(T(coeff_(3)), T(coeff_(4)), T(coeff_(5)));\n\t\tEigen::Matrix<T, 3, 1> lp = Q_ext_pi * cp + t_ext_pi;\n\n\t\tEigen::Matrix<T, 3, 1> nu = (lp - lpa).cross(lp - lpb);\n\t\tEigen::Matrix<T, 3, 1> de = lpa - lpb;\n\t\t// residuals[0] = T(sqrt_info_) * nu.x() / de.norm();\n\t\t// residuals[1] = T(sqrt_info_) * nu.y() / de.norm();\n\t\t// residuals[2] = T(sqrt_info_) * nu.z() / de.norm();\n\t\tresiduals[0] = T(sqrt_info_) * nu.norm() / de.norm();\n\n\t\treturn true;\n\t}\n\n\tstatic ceres::CostFunction *Create(const Eigen::Vector3d &point,\n\t\t\t\t\t\t\t\t\t   const Eigen::VectorXd &coeff,\n\t\t\t\t\t\t\t\t\t   const double sqrt_info)\n\t{\n\t\treturn (new ceres::AutoDiffCostFunction<\n\t\t\t\tLidarPureOdomEdgeFactorAuto, 1, 7, 7, 7>(\n\t\t\tnew LidarPureOdomEdgeFactorAuto(point, coeff, sqrt_info)));\n\t}\n\nprivate: \n\tconst Eigen::Vector3d point_;\n\tconst Eigen::VectorXd coeff_;\n\tconst double sqrt_info_;\n};\n\n//\n", "meta": {"hexsha": "a10899e85b97a18b870db6917f2ebfa7095f3f43", "size": 17595, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lidar_pure_odom_factor.hpp", "max_stars_repo_name": "CL-Chiang/EECS568_final_project", "max_stars_repo_head_hexsha": "0e69e91f66591d1691a46fc17ce627172a8d64e3", "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/lidar_pure_odom_factor.hpp", "max_issues_repo_name": "CL-Chiang/EECS568_final_project", "max_issues_repo_head_hexsha": "0e69e91f66591d1691a46fc17ce627172a8d64e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/lidar_pure_odom_factor.hpp", "max_forks_repo_name": "CL-Chiang/EECS568_final_project", "max_forks_repo_head_hexsha": "0e69e91f66591d1691a46fc17ce627172a8d64e3", "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.8387096774, "max_line_length": 108, "alphanum_fraction": 0.5964762717, "num_tokens": 5949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5200511803775733}}
{"text": "\n#include <cmath>\n\n#include <functional>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Astrodynamics/Propulsion/costateBasedThrustGuidance.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/modifiedEquinoctialElementConversions.h\"\n\nnamespace tudat\n{\n\nnamespace propulsion\n{\n\n//! Constructor\nMeeCostateBasedThrustGuidance::MeeCostateBasedThrustGuidance(\n        const std::function< Eigen::Vector6d( ) > thrustingBodyStateFunction,\n        const std::function< Eigen::Vector6d( ) > centralBodyStateFunction,\n        const std::function< double( ) > centralBodyGravitationalParameterFunction,\n        std::function< Eigen::VectorXd( const double ) > costateFunction,\n        const std::function< Eigen::Vector3d( ) > bodyFixedForceDirection )\n    : BodyFixedForceDirectionGuidance( bodyFixedForceDirection ),\n      thrustingBodyStateFunction_( thrustingBodyStateFunction ),\n      centralBodyStateFunction_( centralBodyStateFunction ),\n      centralBodyGravitationalParameterFunction_( centralBodyGravitationalParameterFunction ),\n      costateFunction_( costateFunction ){ }\n\n//! Function to update the force direction to the current time.\nvoid MeeCostateBasedThrustGuidance::updateForceDirection( const double time )\n{\n    if( !( time == currentTime_ ) )\n    {\n        Eigen::VectorXd costates_ = costateFunction_( time );\n\n        // Get the current state in cartesian coordinates and keplerian elements, and some convenient parameters\n        Eigen::Vector6d currentState = thrustingBodyStateFunction_( ) - centralBodyStateFunction_( );\n        double centralBodyGravitationalParameter = centralBodyGravitationalParameterFunction_( );\n\n        // Obtain ModifiedEquinoctial elements, flag of 0 indicates that singularity occurs at 180 deg inclination.\n        Eigen::Vector6d modifiedEquinoctialElements =\n                orbital_element_conversions::convertCartesianToModifiedEquinoctialElements(\n                    currentState, centralBodyGravitationalParameter, 0 );\n\n        // Optimal control laws local variables declared for clarity\n        double auxiliaryParameterW = ( 1.0 + modifiedEquinoctialElements( 1 ) * cos( modifiedEquinoctialElements( 5 ) )\n                     + modifiedEquinoctialElements( 2 ) * sin( modifiedEquinoctialElements( 5 ) ) );\n        double auxiliaryParameterSSquared = 1.0 + modifiedEquinoctialElements( 3 ) * modifiedEquinoctialElements( 3 )\n                + modifiedEquinoctialElements( 4 ) * modifiedEquinoctialElements( 4 );\n\n        // Local variables for al constant terms for the calculation of pitch angle\n        double Lap = costates_( 0 ) * 2.0 * modifiedEquinoctialElements( 0 ) / auxiliaryParameterW;\n        double Laf1 = costates_( 1 )  * sin( modifiedEquinoctialElements( 5 ) ) ;\n        double Laf2 = costates_( 1 ) / auxiliaryParameterW *\n                ( ( auxiliaryParameterW + 1.0 ) * cos( modifiedEquinoctialElements( 5 ) )\n                                             + modifiedEquinoctialElements( 1 ) ) ;\n        double Lag1 = costates_( 2 ) * cos( modifiedEquinoctialElements( 5 ) );\n        double Lag2 = costates_( 2 ) / auxiliaryParameterW *\n                ( ( auxiliaryParameterW + 1.0 ) * sin( modifiedEquinoctialElements( 5 ) )\n                                             + modifiedEquinoctialElements( 2 ) );\n\n        // Calculate pitch angle, NOTE: denomitator ommitted since it is not relevant for the atan2 function,\n        // since both denominators are the same.\n        double thrustAngleAlpha = std::atan2( -Laf1+Lag1, -Lap-Laf2-Lag2);\n\n        // Local variables for al constant terms for the calculation of yaw angle\n        double Lbp = costates_( 0 ) * 2.0 * modifiedEquinoctialElements( 0 ) * cos( thrustAngleAlpha) / auxiliaryParameterW;\n        double Lbf1 = costates_( 1 )  * sin( modifiedEquinoctialElements( 5 ) ) * sin( thrustAngleAlpha );\n        double Lbf2 = costates_( 1 ) / auxiliaryParameterW *\n                ( ( auxiliaryParameterW + 1.0 ) * cos( modifiedEquinoctialElements( 5 ) )\n                                             + modifiedEquinoctialElements( 1 ) ) * cos( thrustAngleAlpha );\n        double Lbf3 = costates_( 1 ) / auxiliaryParameterW * ( modifiedEquinoctialElements( 2 ) *(\n                                                 modifiedEquinoctialElements( 3 ) * sin( modifiedEquinoctialElements( 5 ) )\n                                                 - modifiedEquinoctialElements( 4 ) * cos( modifiedEquinoctialElements( 5 ) ) ) );\n\n        double Lbg1 = costates_( 2 ) * cos( modifiedEquinoctialElements( 5 ) ) * sin( thrustAngleAlpha);\n        double Lbg2 = costates_( 2 ) / auxiliaryParameterW *\n                ( ( auxiliaryParameterW + 1.0 ) * sin( modifiedEquinoctialElements( 5 ) )\n                                             + modifiedEquinoctialElements( 2 ) ) * cos( thrustAngleAlpha);\n        double Lbg3 = costates_( 2 ) / auxiliaryParameterW * ( modifiedEquinoctialElements( 1 ) *(\n                                                 modifiedEquinoctialElements( 3 ) * sin( modifiedEquinoctialElements( 5 ) )\n                                                 - modifiedEquinoctialElements( 4 ) * cos( modifiedEquinoctialElements( 5 ) ) ) );\n        double Lbh = costates_( 3 ) * auxiliaryParameterSSquared *\n                cos( modifiedEquinoctialElements( 5 ) ) / ( 2.0 * auxiliaryParameterW );\n        double Lbk = costates_( 4 ) * auxiliaryParameterSSquared *\n                sin( modifiedEquinoctialElements( 5 ) ) / ( 2.0 * auxiliaryParameterW );\n\n        // Calculate yaw angle, NOTE: denomitator ommitted since it is not relevant for the atan2 function,\n        // since both denominators are the same.\n        double thrustAngleBeta = std::atan2( Lbf3 - Lbg3 - Lbh - Lbk, - Lbp - Lbf1 - Lbf2 + Lbg1 - Lbg2 );\n\n        // Calculate thrust direction\n        currentForceDirection_ = reference_frames::getVelocityBasedLvlhToInertialRotation(\n                    currentState, Eigen::Vector6d::Zero( ), false ) *\n                ( ( Eigen::Vector3d( ) <<\n                    cos( thrustAngleAlpha ) * cos( thrustAngleBeta ), sin( thrustAngleAlpha ) * cos( thrustAngleBeta ) ,\n                    sin( thrustAngleBeta )  ).finished( ).normalized( ) );\n        currentTime_ = time;\n    }\n\n}\n\n} // namespace propulsion\n\n} // namespace tudat\n", "meta": {"hexsha": "5aa11592e9062fab98815769f60d2d47842d7b1d", "size": 6265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Propulsion/costateBasedThrustGuidance.cpp", "max_stars_repo_name": "J-Westin/tudat", "max_stars_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "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/Propulsion/costateBasedThrustGuidance.cpp", "max_issues_repo_name": "J-Westin/tudat", "max_issues_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Propulsion/costateBasedThrustGuidance.cpp", "max_forks_repo_name": "J-Westin/tudat", "max_forks_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "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": 58.5514018692, "max_line_length": 130, "alphanum_fraction": 0.6507581804, "num_tokens": 1536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460027, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.520013794156734}}
{"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 seat_id(string line) {\n    boost::trim(line);\n\n    int row_min = 0;\n    int row_max = 127;\n    int col_min = 0;\n    int col_max = 7;\n    for (char c : line) {\n        if (c == 'F') {\n            row_max = row_min + (row_max - row_min) / 2;\n        } else if (c == 'B') {\n            row_min = row_min + (row_max - row_min) / 2 + 1;\n        } else if (c == 'L') {\n            col_max = col_min + (col_max - col_min) / 2;\n        } else if (c == 'R') {\n            col_min = col_min + (col_max - col_min) / 2 + 1;\n        }\n    }\n\n    return row_min * 8 + col_min;\n}\n\nint main() {\n    ifstream file (\"2020/5.txt\");\n    if (!file.is_open()) {\n        cout << \"Failed to open file: \" << strerror(errno) << endl;\n        return -1;\n    }\n\n    map<int, bool> found;\n    int max_id = 0;\n\n    string line; \n    while (getline(file, line, '\\n')) {\n        int id = seat_id(line);\n\n        if (id > max_id) {\n            max_id = id;\n        }\n        found[id] = true;\n\n        //cout << line << \" \" << id << endl;\n    }\n\n    cout << \"Answer 5.1: \" << max_id << endl;\n\n    for (int i = 0; i < max_id; i++) {\n        if (!found[i] && found[i - 1] && found[i + 1]) {\n            cout << \"Answer 5.2: \" << i << endl;\n            break;\n        }\n    }\n\n    file.close();\n}", "meta": {"hexsha": "9cbd86ca1350fcdae37dca76ca8cbd77763f16aa", "size": 1433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/5.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": "2020/5.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": "2020/5.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": 22.0461538462, "max_line_length": 67, "alphanum_fraction": 0.4696441033, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.5199947543186054}}
{"text": "// Copyright (C) 2008  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include \"optimization_test_functions.h\"\n#include <dlib/optimization.h>\n#include <dlib/statistics.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\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n    logger dlog(\"test.optimization\");\n\n// ----------------------------------------------------------------------------------------\n\n    bool approx_equal (\n        double a,\n        double b\n    )\n    {\n        return std::abs(a - b) < 100*std::numeric_limits<double>::epsilon();\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    long total_count = 0;\n\n\n    template <typename T>\n    double apq ( const T& x)\n    {\n        DLIB_ASSERT(x.nr() > 1 && x.nc() == 1,\"\");\n        COMPILE_TIME_ASSERT(is_matrix<T>::value);\n        double temp = 0;\n        for (long r = 0; r < x.nr(); ++r)\n        {\n            temp += (r+1)*x(r)*x(r);\n        }\n\n        ++total_count;\n\n        return temp + 1/100.0*(x(0) + x(x.nr()-1))*(x(0) + x(x.nr()-1));\n    }\n\n    template <typename T>\n    T der_apq ( const T& x)\n    {\n        DLIB_ASSERT(x.nr() > 1 && x.nc() == 1,\"\");\n        COMPILE_TIME_ASSERT(is_matrix<T>::value);\n        T temp(x.nr());\n        for (long r = 0; r < x.nr(); ++r)\n        {\n            temp(r) = 2*(r+1)*x(r) ;\n        }\n\n        temp(0) += 1/50.0*(x(0) + x(x.nr()-1));\n        temp(x.nr()-1) += 1/50.0*(x(0) + x(x.nr()-1));\n\n        ++total_count;\n\n        return temp;\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    // Rosenbrock's function.  minimum at (1,1)\n    double rosen ( const matrix<double,2,1>& x)\n    {\n        ++total_count;\n        return 100*pow(x(1) - x(0)*x(0),2) + pow(1 - x(0),2);\n    }\n\n    matrix<double,2,1> der_rosen ( const matrix<double,2,1>& x)\n    {\n        ++total_count;\n        matrix<double,2,1> res;\n        res(0) = -400*x(0)*(x(1)-x(0)*x(0)) - 2*(1-x(0));\n        res(1) = 200*(x(1)-x(0)*x(0));\n        return res;\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    // negative of Rosenbrock's function.  minimum at (1,1)\n    double neg_rosen ( const matrix<double,2,1>& x)\n    {\n        ++total_count;\n        return -(100*pow(x(1) - x(0)*x(0),2) + pow(1 - x(0),2));\n    }\n\n    matrix<double,2,1> der_neg_rosen ( const matrix<double,2,1>& x)\n    {\n        ++total_count;\n        matrix<double,2,1> res;\n        res(0) = -400*x(0)*(x(1)-x(0)*x(0)) - 2*(1-x(0));\n        res(1) = 200*(x(1)-x(0)*x(0));\n        return -res;\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    double simple ( const matrix<double,2,1>& x)\n    {\n        ++total_count;\n        return 10*x(0)*x(0) + x(1)*x(1);\n    }\n\n    matrix<double,2,1> der_simple ( const matrix<double,2,1>& x)\n    {\n        ++total_count;\n        matrix<double,2,1> res;\n        res(0) = 20*x(0);\n        res(1) = 2*x(1);\n        return res;\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    double powell ( const matrix<double,4,1>& x)\n    {\n        ++total_count;\n        return pow(x(0) + 10*x(1),2) +\n            pow(std::sqrt(5.0)*(x(2) - x(3)),2) + \n            pow((x(1) - 2*x(2))*(x(1) - 2*x(2)),2) +\n            pow(std::sqrt(10.0)*(x(0) - x(3))*(x(0) - x(3)),2);\n    }\n\n// ----------------------------------------------------------------------------------------\n\n// a simple function with a minimum at zero\n    double single_variable_function ( double x)\n    {\n        ++total_count;\n        return 3*x*x + 5;\n    }\n\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n\n    void test_apq (\n        const matrix<double,0,1> p\n    )\n    {\n        typedef matrix<double,0,1> T;\n        const double eps = 1e-12;\n        const double minf = -10;\n        matrix<double,0,1> x(p.nr()), opt(p.nr());\n        set_all_elements(opt, 0);\n        double val = 0;\n\n        if (p.size() < 20)\n            dlog << LINFO << \"testing with apq and the start point: \" << trans(p);\n        else\n            dlog << LINFO << \"testing with apq and a big vector with \" << p.size() << \" components.\";\n\n        // don't use bfgs on really large vectors\n        if (p.size() < 20)\n        {\n            total_count = 0;\n            x = p;\n            val = find_min(bfgs_search_strategy(), \n                     objective_delta_stop_strategy(eps),\n                     wrap_function(apq<T>), wrap_function(der_apq<T>), x, minf);\n            DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n            DLIB_TEST(approx_equal(val , apq(x)));\n            dlog << LINFO << \"find_min() bgfs: got apq in \" << total_count;\n\n            total_count = 0;\n            x = p;\n            find_min(bfgs_search_strategy(), \n                     gradient_norm_stop_strategy(),\n                     wrap_function(apq<T>), wrap_function(der_apq<T>), x, minf);\n            DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n            dlog << LINFO << \"find_min() bgfs(gn): got apq in \" << total_count;\n        }\n\n\n        if (p.size() < 100)\n        {\n            total_count = 0;\n            x = p;\n            val=find_min_bobyqa(wrap_function(apq<T>), x, 2*x.size()+1,\n                            uniform_matrix<double>(x.size(),1,-1e100),\n                            uniform_matrix<double>(x.size(),1,1e100),\n                            (max(abs(x))+1)/10,\n                            1e-6,\n                            10000);\n            DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n            DLIB_TEST(approx_equal(val , apq(x)));\n            dlog << LINFO << \"find_min_bobyqa(): got apq in \" << total_count;\n        }\n\n        total_count = 0;\n        x = p;\n        val=find_min(lbfgs_search_strategy(10), \n                 objective_delta_stop_strategy(eps),\n                 wrap_function(apq<T>), wrap_function(der_apq<T>), x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , apq(x)));\n        dlog << LINFO << \"find_min() lbgfs-10: got apq in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(lbfgs_search_strategy(1), \n                 objective_delta_stop_strategy(eps),\n                 wrap_function(apq<T>), wrap_function(der_apq<T>), x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , apq(x)));\n        dlog << LINFO << \"find_min() lbgfs-1: got apq in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(cg_search_strategy(),\n                 objective_delta_stop_strategy(eps),\n                 wrap_function(apq<T>), wrap_function(der_apq<T>), x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , apq(x)));\n        dlog << LINFO << \"find_min() cg: got apq in \" << total_count;\n\n\n        // don't do approximate derivative tests if the input point is really long\n        if (p.size() < 20)\n        {\n            total_count = 0;\n            x = p;\n            val=find_min(bfgs_search_strategy(),\n                     objective_delta_stop_strategy(eps),\n                     wrap_function(apq<T>), derivative(wrap_function(apq<T>)), x, minf);\n            DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n            DLIB_TEST(approx_equal(val , apq(x)));\n            dlog << LINFO << \"find_min() bfgs: got apq/noder in \" << total_count;\n\n\n            total_count = 0;\n            x = p;\n            val=find_min(cg_search_strategy(),\n                     objective_delta_stop_strategy(eps),\n                     wrap_function(apq<T>), derivative(wrap_function(apq<T>)), x, minf);\n            DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n            DLIB_TEST(approx_equal(val , apq(x)));\n            dlog << LINFO << \"find_min() cg: got apq/noder in \" << total_count;\n\n\n            total_count = 0;\n            x = p;\n            val=find_min_using_approximate_derivatives(bfgs_search_strategy(),\n                                                   objective_delta_stop_strategy(eps), \n                                                   wrap_function(apq<T>), x, minf);\n            DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n            DLIB_TEST(approx_equal(val , apq(x)));\n            dlog << LINFO << \"find_min() bfgs: got apq/noder2 in \" << total_count;\n\n\n            total_count = 0;\n            x = p;\n            val=find_min_using_approximate_derivatives(lbfgs_search_strategy(10),\n                                                   objective_delta_stop_strategy(eps), \n                                                   wrap_function(apq<T>), x, minf);\n            DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n            dlog << LINFO << \"find_min() lbfgs-10: got apq/noder2 in \" << total_count;\n\n\n            total_count = 0;\n            x = p;\n            val=find_min_using_approximate_derivatives(cg_search_strategy(),\n                                                   objective_delta_stop_strategy(eps),\n                                                   wrap_function(apq<T>), x, minf);\n            DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n            DLIB_TEST(approx_equal(val , apq(x)));\n            dlog << LINFO << \"find_min() cg: got apq/noder2 in \" << total_count;\n        }\n    }\n\n    void test_powell (\n        const matrix<double,4,1> p\n    )\n    {\n        const double eps = 1e-15;\n        const double minf = -1;\n        matrix<double,4,1> x, opt;\n        opt(0) = 0;\n        opt(1) = 0;\n        opt(2) = 0;\n        opt(3) = 0;\n\n        double val = 0;\n\n        dlog << LINFO << \"testing with powell and the start point: \" << trans(p);\n\n        /*\n        total_count = 0;\n        x = p;\n        val=find_min(bfgs_search_strategy(),\n                 objective_delta_stop_strategy(eps),\n                 powell, derivative(powell,1e-8), x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-2),opt-x);\n        DLIB_TEST(approx_equal(val , powell(x)));\n        dlog << LINFO << \"find_min() bfgs: got powell/noder in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(cg_search_strategy(),\n                 objective_delta_stop_strategy(eps),\n                 powell, derivative(powell,1e-9), x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-2),opt-x);\n        DLIB_TEST(approx_equal(val , powell(x)));\n        dlog << LINFO << \"find_min() cg: got powell/noder in \" << total_count;\n        */\n\n        total_count = 0;\n        x = p;\n        val=find_min_using_approximate_derivatives(bfgs_search_strategy(),\n                                               objective_delta_stop_strategy(eps),\n                                               powell, x, minf, 1e-10);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-1),opt-x);\n        DLIB_TEST(approx_equal(val , powell(x)));\n        dlog << LINFO << \"find_min() bfgs: got powell/noder2 in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min_using_approximate_derivatives(lbfgs_search_strategy(4),\n                                               objective_delta_stop_strategy(eps),\n                                               powell, x, minf, 1e-10);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-1),opt-x);\n        DLIB_TEST(approx_equal(val , powell(x)));\n        dlog << LINFO << \"find_min() lbfgs-4: got powell/noder2 in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min_using_approximate_derivatives(lbfgs_search_strategy(4),\n                                               gradient_norm_stop_strategy(),\n                                               powell, x, minf, 1e-10);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-1),opt-x);\n        DLIB_TEST(approx_equal(val , powell(x)));\n        dlog << LINFO << \"find_min() lbfgs-4(gn): got powell/noder2 in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min_using_approximate_derivatives(cg_search_strategy(),\n                                               objective_delta_stop_strategy(eps),\n                                               powell, x, minf, 1e-10);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-1),opt-x);\n        DLIB_TEST(approx_equal(val , powell(x)));\n        dlog << LINFO << \"find_min() cg: got powell/noder2 in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min_bobyqa(powell, x, 2*x.size()+1,\n                        uniform_matrix<double>(x.size(),1,-1e100),\n                        uniform_matrix<double>(x.size(),1,1e100),\n                        (max(abs(x))+1)/10,\n                        1e-8,\n                        10000);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-3),opt-x);\n        DLIB_TEST(approx_equal(val , powell(x)));\n        dlog << LINFO << \"find_min_bobyqa(): got powell in \" << total_count;\n\n    }\n\n\n\n    void test_simple (\n        const matrix<double,2,1> p\n    )\n    {\n        const double eps = 1e-12;\n        const double minf = -10000;\n        matrix<double,2,1> x, opt;\n        opt(0) = 0;\n        opt(1) = 0;\n        double val = 0;\n\n        dlog << LINFO << \"testing with simple and the start point: \" << trans(p);\n\n        total_count = 0;\n        x = p;\n        val=find_min(bfgs_search_strategy(),\n                 objective_delta_stop_strategy(eps),\n                 simple, der_simple, x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , simple(x)));\n        dlog << LINFO << \"find_min() bfgs: got simple in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(bfgs_search_strategy(),\n                 gradient_norm_stop_strategy(),\n                 simple, der_simple, x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , simple(x)));\n        dlog << LINFO << \"find_min() bfgs(gn): got simple in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(lbfgs_search_strategy(3),\n                 objective_delta_stop_strategy(eps),\n                 simple, der_simple, x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , simple(x)));\n        dlog << LINFO << \"find_min() lbfgs-3: got simple in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(cg_search_strategy(),\n                 objective_delta_stop_strategy(eps),\n                 simple, der_simple, x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , simple(x)));\n        dlog << LINFO << \"find_min() cg: got simple in \" << total_count;\n\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(bfgs_search_strategy(),\n                 objective_delta_stop_strategy(eps),\n                 simple, derivative(simple), x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , simple(x)));\n        dlog << LINFO << \"find_min() bfgs: got simple/noder in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(lbfgs_search_strategy(8),\n                 objective_delta_stop_strategy(eps),\n                 simple, derivative(simple), x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , simple(x)));\n        dlog << LINFO << \"find_min() lbfgs-8: got simple/noder in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(cg_search_strategy(),\n                 objective_delta_stop_strategy(eps),\n                 simple, derivative(simple), x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , simple(x)));\n        dlog << LINFO << \"find_min() cg: got simple/noder in \" << total_count;\n\n\n\n        total_count = 0;\n        x = p;\n        val=find_min_using_approximate_derivatives(bfgs_search_strategy(),\n                                               objective_delta_stop_strategy(eps),\n                                               simple, x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , simple(x)));\n        dlog << LINFO << \"find_min() bfgs: got simple/noder2 in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min_using_approximate_derivatives(lbfgs_search_strategy(6),\n                                               objective_delta_stop_strategy(eps),\n                                               simple, x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , simple(x)));\n        dlog << LINFO << \"find_min() lbfgs-6: got simple/noder2 in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min_using_approximate_derivatives(cg_search_strategy(),\n                                               objective_delta_stop_strategy(eps),\n                                               simple, x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , simple(x)));\n        dlog << LINFO << \"find_min() cg: got simple/noder2 in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min_bobyqa(simple, x, 2*x.size()+1,\n                        uniform_matrix<double>(x.size(),1,-1e100),\n                        uniform_matrix<double>(x.size(),1,1e100),\n                        (max(abs(x))+1)/10,\n                        1e-6,\n                        10000);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , simple(x)));\n        dlog << LINFO << \"find_min_bobyqa(): got simple in \" << total_count;\n\n    }\n\n\n    void test_rosen (\n        const matrix<double,2,1> p\n    )\n    {\n        const double eps = 1e-15;\n        const double minf = -10;\n        matrix<double,2,1> x, opt;\n        opt(0) = 1;\n        opt(1) = 1;\n\n        double val = 0;\n\n        dlog << LINFO << \"testing with rosen and the start point: \" << trans(p);\n\n        total_count = 0;\n        x = p;\n        val=find_min(bfgs_search_strategy(),\n                 objective_delta_stop_strategy(eps),\n                 rosen, der_rosen, x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-7),opt-x);\n        DLIB_TEST(approx_equal(val , rosen(x)));\n        dlog << LINFO << \"find_min() bfgs: got rosen in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(bfgs_search_strategy(),\n                 gradient_norm_stop_strategy(),\n                 rosen, der_rosen, x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-7),opt-x);\n        DLIB_TEST(approx_equal(val , rosen(x)));\n        dlog << LINFO << \"find_min() bfgs(gn): got rosen in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(lbfgs_search_strategy(20),\n                 objective_delta_stop_strategy(eps),\n                 rosen, der_rosen, x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-7),opt-x);\n        DLIB_TEST(approx_equal(val , rosen(x)));\n        dlog << LINFO << \"find_min() lbfgs-20: got rosen in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(cg_search_strategy(),\n                 objective_delta_stop_strategy(eps),\n                 rosen, der_rosen, x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-7),opt-x);\n        DLIB_TEST(approx_equal(val , rosen(x)));\n        dlog << LINFO << \"find_min() cg: got rosen in \" << total_count;\n\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(bfgs_search_strategy(),\n                 objective_delta_stop_strategy(eps),\n                 rosen, derivative(rosen,1e-5), x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-4),opt-x);\n        DLIB_TEST(approx_equal(val , rosen(x)));\n        dlog << LINFO << \"find_min() bfgs: got rosen/noder in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(lbfgs_search_strategy(5),\n                 objective_delta_stop_strategy(eps),\n                 rosen, derivative(rosen,1e-5), x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-4),opt-x);\n        DLIB_TEST(approx_equal(val , rosen(x)));\n        dlog << LINFO << \"find_min() lbfgs-5: got rosen/noder in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min(cg_search_strategy(),\n                 objective_delta_stop_strategy(eps),\n                 rosen, derivative(rosen,1e-5), x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-4),opt-x);\n        DLIB_TEST(approx_equal(val , rosen(x)));\n        dlog << LINFO << \"find_min() cg: got rosen/noder in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_min_using_approximate_derivatives(cg_search_strategy(),\n                                               objective_delta_stop_strategy(eps),\n                                               rosen, x, minf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-4),opt-x);\n        DLIB_TEST(approx_equal(val , rosen(x)));\n        dlog << LINFO << \"find_min() cg: got rosen/noder2 in \" << total_count;\n\n\n        if (max(abs(p)) < 1000)\n        {\n            total_count = 0;\n            x = p;\n            val=find_min_bobyqa(rosen, x, 2*x.size()+1,\n                            uniform_matrix<double>(x.size(),1,-1e100),\n                            uniform_matrix<double>(x.size(),1,1e100),\n                            (max(abs(x))+1)/10,\n                            1e-6,\n                            10000);\n            DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n            DLIB_TEST(approx_equal(val , rosen(x)));\n            dlog << LINFO << \"find_min_bobyqa(): got rosen in \" << total_count;\n        }\n    }\n\n\n    void test_neg_rosen (\n        const matrix<double,2,1> p\n    )\n    {\n        const double eps = 1e-15;\n        const double maxf = 10;\n        matrix<double,2,1> x, opt;\n        opt(0) = 1;\n        opt(1) = 1;\n\n        double val = 0;\n\n        dlog << LINFO << \"testing with neg_rosen and the start point: \" << trans(p);\n\n        total_count = 0;\n        x = p;\n        val=find_max(\n            bfgs_search_strategy(), \n            objective_delta_stop_strategy(eps), neg_rosen, der_neg_rosen, x, maxf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-7),opt-x);\n        DLIB_TEST(approx_equal(val , neg_rosen(x)));\n        dlog << LINFO << \"find_max() bfgs: got neg_rosen in \" << total_count;\n\n        total_count = 0;\n        x = p;\n        val=find_max(\n            lbfgs_search_strategy(5), \n            objective_delta_stop_strategy(eps), neg_rosen, der_neg_rosen, x, maxf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-7),opt-x);\n        DLIB_TEST(approx_equal(val , neg_rosen(x)));\n        dlog << LINFO << \"find_max() lbfgs-5: got neg_rosen in \" << total_count;\n\n        total_count = 0;\n        x = p;\n        val=find_max(\n            lbfgs_search_strategy(5), \n            objective_delta_stop_strategy(eps), neg_rosen, derivative(neg_rosen), x, maxf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-7),opt-x);\n        DLIB_TEST(approx_equal(val , neg_rosen(x)));\n        dlog << LINFO << \"find_max() lbfgs-5: got neg_rosen/noder in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_max_using_approximate_derivatives(\n            cg_search_strategy(), \n            objective_delta_stop_strategy(eps), neg_rosen, x, maxf);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-7),opt-x);\n        DLIB_TEST(approx_equal(val , neg_rosen(x)));\n        dlog << LINFO << \"find_max() cg: got neg_rosen/noder2 in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        val=find_max_bobyqa(neg_rosen, x, 2*x.size()+1,\n                        uniform_matrix<double>(x.size(),1,-1e100),\n                        uniform_matrix<double>(x.size(),1,1e100),\n                        (max(abs(x))+1)/10,\n                        1e-6,\n                        10000);\n        DLIB_TEST_MSG(dlib::equal(x,opt, 1e-5),opt-x);\n        DLIB_TEST(approx_equal(val , neg_rosen(x)));\n        dlog << LINFO << \"find_max_bobyqa(): got neg_rosen in \" << total_count;\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_single_variable_function (\n        const double p\n    )\n    {\n        const double eps = 1e-7;\n\n\n        dlog << LINFO << \"testing with single_variable_function and the start point: \" << p;\n        double out, x;\n\n        total_count = 0;\n        x = p;\n        out = find_min_single_variable(single_variable_function, x, -1e100, 1e100, eps, 1000);\n        DLIB_TEST_MSG(std::abs(out-5) < 1e-6, out-5);\n        DLIB_TEST_MSG(std::abs(x) < 1e-6, x);\n        dlog << LINFO << \"find_min_single_variable(): got single_variable_function in \" << total_count;\n\n\n        total_count = 0;\n        x = p;\n        out = -find_max_single_variable(negate_function(single_variable_function), x, -1e100, 1e100, eps, 1000);\n        DLIB_TEST_MSG(std::abs(out-5) < 1e-6, out-5);\n        DLIB_TEST_MSG(std::abs(x) < 1e-6, x);\n        dlog << LINFO << \"find_max_single_variable(): got single_variable_function in \" << total_count;\n\n\n        if (p > 0)\n        {\n            total_count = 0;\n            x = p;\n            out = find_min_single_variable(single_variable_function, x, -1e-4, 1e100, eps, 1000);\n            DLIB_TEST_MSG(std::abs(out-5) < 1e-6, out-5);\n            DLIB_TEST_MSG(std::abs(x) < 1e-6, x);\n            dlog << LINFO << \"find_min_single_variable(): got single_variable_function in \" << total_count;\n\n\n            if (p > 3)\n            {\n                total_count = 0;\n                x = p;\n                out = -find_max_single_variable(negate_function(single_variable_function), x, 3, 1e100, eps, 1000);\n                DLIB_TEST_MSG(std::abs(out - (3*3*3+5)) < 1e-6, out-(3*3*3+5));\n                DLIB_TEST_MSG(std::abs(x-3) < 1e-6, x);\n                dlog << LINFO << \"find_max_single_variable(): got single_variable_function in \" << total_count;\n            }\n        }\n\n        if (p < 0)\n        {\n            total_count = 0;\n            x = p;\n            out = find_min_single_variable(single_variable_function, x, -1e100, 1e-4, eps, 1000);\n            DLIB_TEST_MSG(std::abs(out-5) < 1e-6, out-5);\n            DLIB_TEST_MSG(std::abs(x) < 1e-6, x);\n            dlog << LINFO << \"find_min_single_variable(): got single_variable_function in \" << total_count;\n\n            if (p < -3)\n            {\n                total_count = 0;\n                x = p;\n                out = find_min_single_variable(single_variable_function, x, -1e100, -3, eps, 1000);\n                DLIB_TEST_MSG(std::abs(out - (3*3*3+5)) < 1e-6, out-(3*3*3+5));\n                DLIB_TEST_MSG(std::abs(x+3) < 1e-6, x);\n                dlog << LINFO << \"find_min_single_variable(): got single_variable_function in \" << total_count;\n            }\n        }\n\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void optimization_test (\n    )\n    /*!\n        ensures\n            - runs tests on the optimization stuff compliance with the specs\n    !*/\n    {        \n        matrix<double,0,1> p;\n\n        print_spinner();\n\n        p.set_size(2);\n\n        // test with single_variable_function\n        test_single_variable_function(0);\n        test_single_variable_function(1);\n        test_single_variable_function(-10);\n        test_single_variable_function(-100);\n        test_single_variable_function(900.53);\n\n        // test with the rosen function\n        p(0) = 9;\n        p(1) = -4.9;\n        test_rosen(p);\n        test_neg_rosen(p);\n\n        p(0) = 0;\n        p(1) = 0;\n        test_rosen(p);\n\n        p(0) = 5323;\n        p(1) = 98248;\n        test_rosen(p);\n\n        // test with the simple function\n        p(0) = 1;\n        p(1) = 1;\n        test_simple(p);\n\n        p(0) = 0.5;\n        p(1) = -9;\n        test_simple(p);\n\n        p(0) = 645;\n        p(1) = 839485;\n        test_simple(p);\n\n        print_spinner();\n\n        // test with the apq function\n        p.set_size(5);\n\n        p(0) = 1;\n        p(1) = 1;\n        p(2) = 1;\n        p(3) = 1;\n        p(4) = 1;\n        test_apq(p);\n\n        p(0) = 1;\n        p(1) = 2;\n        p(2) = 3;\n        p(3) = 4;\n        p(4) = 5;\n        test_apq(p);\n\n        p(0) = 1;\n        p(1) = 2;\n        p(2) = -3;\n        p(3) = 4;\n        p(4) = 5;\n        test_apq(p);\n\n        print_spinner();\n\n        p(0) = 1;\n        p(1) = 2324;\n        p(2) = -3;\n        p(3) = 4;\n        p(4) = 534534;\n        test_apq(p);\n\n        p.set_size(10);\n        p(0) = 1;\n        p(1) = 2;\n        p(2) = -3;\n        p(3) = 4;\n        p(4) = 5;\n        p(5) = 1;\n        p(6) = 2;\n        p(7) = -3;\n        p(8) = 4;\n        p(9) = 5;\n        test_apq(p);\n\n        // test apq with a big vector\n        p.set_size(500);\n        dlib::rand rnd;\n        for (long i = 0; i < p.size(); ++i)\n        {\n            p(i) = rnd.get_random_double()*20 - 10; \n        }\n        test_apq(p);\n\n        print_spinner();\n\n        // test with the powell function\n        p.set_size(4);\n\n        p(0) = 3;\n        p(1) = -1;\n        p(2) = 0;\n        p(3) = 1;\n        test_powell(p);\n\n        {\n            matrix<double,2,1> m;\n            m(0) = -0.43;\n            m(1) = 0.919;\n            DLIB_TEST(dlib::equal(der_rosen(m) , derivative(rosen)(m),1e-5));\n\n            DLIB_TEST_MSG(std::abs(derivative(make_line_search_function(rosen,m,m))(0) - \n                                  make_line_search_function(derivative(rosen),m,m)(0)) < 1e-5,\"\");\n            DLIB_TEST_MSG(std::abs(derivative(make_line_search_function(rosen,m,m))(1) - \n                                  make_line_search_function(derivative(rosen),m,m)(1)) < 1e-5,\"\");\n\n            DLIB_TEST_MSG(std::abs(derivative(make_line_search_function(rosen,m,m))(0) - \n                                  make_line_search_function(der_rosen,m,m)(0)) < 1e-5,\"\");\n            DLIB_TEST_MSG(std::abs(derivative(make_line_search_function(rosen,m,m))(1) - \n                                  make_line_search_function(der_rosen,m,m)(1)) < 1e-5,\"\");\n        }\n        {\n            matrix<double,2,1> m;\n            m(0) = 1;\n            m(1) = 2;\n            DLIB_TEST(dlib::equal(der_rosen(m) , derivative(rosen)(m),1e-5));\n\n            DLIB_TEST_MSG(std::abs(derivative(make_line_search_function(rosen,m,m))(0) - \n                                  make_line_search_function(derivative(rosen),m,m)(0)) < 1e-5,\"\");\n            DLIB_TEST_MSG(std::abs(derivative(make_line_search_function(rosen,m,m))(1) - \n                                  make_line_search_function(derivative(rosen),m,m)(1)) < 1e-5,\"\");\n\n            DLIB_TEST_MSG(std::abs(derivative(make_line_search_function(rosen,m,m))(0) - \n                                  make_line_search_function(der_rosen,m,m)(0)) < 1e-5,\"\");\n            DLIB_TEST_MSG(std::abs(derivative(make_line_search_function(rosen,m,m))(1) - \n                                  make_line_search_function(der_rosen,m,m)(1)) < 1e-5,\"\");\n        }\n\n        {\n            matrix<double,2,1> m;\n            m = 1,2;\n            DLIB_TEST(std::abs(neg_rosen(m) - negate_function(rosen)(m) ) < 1e-16);\n        }\n\n    }\n\n    template <typename der_funct, typename T>\n    double unconstrained_gradient_magnitude (\n        const der_funct& grad,\n        const T& x,\n        const T& lower,\n        const T& upper\n    )\n    {\n        T g = grad(x);\n\n        double unorm = 0;\n\n        for (long i = 0; i < g.size(); ++i)\n        {\n            if (lower(i) < x(i) && x(i) < upper(i))\n                unorm += g(i)*g(i);\n            else if (x(i) == lower(i) && g(i) < 0)\n                unorm += g(i)*g(i);\n            else if (x(i) == upper(i) && g(i) > 0)\n                unorm += g(i)*g(i);\n        }\n\n        return unorm;\n    }\n\n    template <typename der_funct, typename T>\n    double unconstrained_gradient_magnitude_neg_funct (\n        const der_funct& grad,\n        const T& x,\n        const T& lower,\n        const T& upper\n    )\n    {\n        T g = grad(x);\n\n        double unorm = 0;\n\n        for (long i = 0; i < g.size(); ++i)\n        {\n            if (lower(i) < x(i) && x(i) < upper(i))\n                unorm += g(i)*g(i);\n            else if (x(i) == lower(i) && g(i) > 0)\n                unorm += g(i)*g(i);\n            else if (x(i) == upper(i) && g(i) < 0)\n                unorm += g(i)*g(i);\n        }\n\n        return unorm;\n    }\n\n    template <typename search_strategy_type>\n    double test_bound_solver_neg_rosen (dlib::rand& rnd, search_strategy_type search_strategy)\n    {\n        using namespace dlib::test_functions;\n        print_spinner();\n        matrix<double,2,1> starting_point, lower, upper, x;\n\n\n        // pick random bounds\n        lower = rnd.get_random_gaussian()+1, rnd.get_random_gaussian()+1;\n        upper = rnd.get_random_gaussian()+1, rnd.get_random_gaussian()+1;\n        while (upper(0) < lower(0)) upper(0) = rnd.get_random_gaussian()+1;\n        while (upper(1) < lower(1)) upper(1) = rnd.get_random_gaussian()+1;\n\n        starting_point = rnd.get_random_double()*(upper(0)-lower(0))+lower(0), \n                       rnd.get_random_double()*(upper(1)-lower(1))+lower(1);\n\n        dlog << LINFO << \"lower: \"<< trans(lower);\n        dlog << LINFO << \"upper: \"<< trans(upper);\n        dlog << LINFO << \"starting: \"<< trans(starting_point);\n\n        x = starting_point;\n        double val = find_max_box_constrained( \n            search_strategy,\n            objective_delta_stop_strategy(1e-16, 500), \n            neg_rosen, der_neg_rosen, x,\n            lower,  \n            upper   \n        );\n\n        DLIB_TEST_MSG(std::abs(val - neg_rosen(x)) < 1e-11, std::abs(val - neg_rosen(x)));\n        dlog << LINFO << \"neg_rosen solution:\\n\" << x;\n\n        dlog << LINFO << \"neg_rosen gradient: \"<< trans(der_neg_rosen(x));\n        const double gradient_residual = unconstrained_gradient_magnitude_neg_funct(der_neg_rosen, x, lower, upper);\n        dlog << LINFO << \"gradient_residual: \"<< gradient_residual;\n\n        return gradient_residual;\n    }\n\n    template <typename search_strategy_type>\n    double test_bound_solver_rosen (dlib::rand& rnd, search_strategy_type search_strategy)\n    {\n        using namespace dlib::test_functions;\n        print_spinner();\n        matrix<double,2,1> starting_point, lower, upper, x;\n\n\n        // pick random bounds and sometimes put the upper bound at zero so we can have\n        // a test where the optimal value has a bound active at 0 so make sure this case\n        // works properly.\n        if (rnd.get_random_double() > 0.2)\n        {\n            lower = rnd.get_random_gaussian()+1, rnd.get_random_gaussian()+1;\n            upper = rnd.get_random_gaussian()+1, rnd.get_random_gaussian()+1;\n            while (upper(0) < lower(0)) upper(0) = rnd.get_random_gaussian()+1;\n            while (upper(1) < lower(1)) upper(1) = rnd.get_random_gaussian()+1;\n        }\n        else\n        {\n            upper = 0,0;\n            if (rnd.get_random_double() > 0.5)\n                upper(0) = -rnd.get_random_double();\n            if (rnd.get_random_double() > 0.5)\n                upper(1) = -rnd.get_random_double();\n\n            lower = rnd.get_random_double()+1, rnd.get_random_double()+1;\n            lower = upper - lower;\n        }\n        const bool pick_uniform_bounds = rnd.get_random_double() > 0.9;\n        if (pick_uniform_bounds)\n        {\n            double x = rnd.get_random_gaussian()*2;\n            double y = rnd.get_random_gaussian()*2;\n            lower = min(x,y);\n            upper = max(x,y);\n        }\n\n        starting_point = rnd.get_random_double()*(upper(0)-lower(0))+lower(0), \n                       rnd.get_random_double()*(upper(1)-lower(1))+lower(1);\n\n        dlog << LINFO << \"lower: \"<< trans(lower);\n        dlog << LINFO << \"upper: \"<< trans(upper);\n        dlog << LINFO << \"starting: \"<< trans(starting_point);\n\n        x = starting_point;\n        double val;\n        if (!pick_uniform_bounds)\n        {\n            val = find_min_box_constrained( \n                search_strategy,\n                objective_delta_stop_strategy(1e-16, 500), \n                rosen, der_rosen, x,\n                lower,  \n                upper   \n            );\n        }\n        else\n        {\n            val = find_min_box_constrained( \n                search_strategy,\n                objective_delta_stop_strategy(1e-16, 500), \n                rosen, der_rosen, x,\n                lower(0),  \n                upper(0)   \n            );\n        }\n\n\n        DLIB_TEST_MSG(std::abs(val - rosen(x)) < 1e-11, std::abs(val - rosen(x)));\n        dlog << LINFO << \"rosen solution:\\n\" << x;\n\n        dlog << LINFO << \"rosen gradient: \"<< trans(der_rosen(x));\n        const double gradient_residual = unconstrained_gradient_magnitude(der_rosen, x, lower, upper);\n        dlog << LINFO << \"gradient_residual: \"<< gradient_residual;\n\n        return gradient_residual;\n    }\n\n    template <typename search_strategy_type>\n    double test_bound_solver_brown (dlib::rand& rnd, search_strategy_type search_strategy)\n    {\n        using namespace dlib::test_functions;\n        print_spinner();\n        matrix<double,4,1> starting_point(4), lower(4), upper(4), x;\n\n        const matrix<double,0,1> solution = brown_solution();\n\n        // pick random bounds\n        lower = rnd.get_random_gaussian(), rnd.get_random_gaussian(), rnd.get_random_gaussian(), rnd.get_random_gaussian();\n        lower = lower*10 + solution;\n        upper = rnd.get_random_gaussian(), rnd.get_random_gaussian(), rnd.get_random_gaussian(), rnd.get_random_gaussian();\n        upper = upper*10 + solution;\n        for (int i = 0; i < lower.size(); ++i)\n        {\n            if (upper(i) < lower(i)) \n                swap(upper(i),lower(i));\n        }\n\n        starting_point = rnd.get_random_double()*(upper(0)-lower(0))+lower(0), \n                       rnd.get_random_double()*(upper(1)-lower(1))+lower(1),\n                       rnd.get_random_double()*(upper(2)-lower(2))+lower(2),\n                       rnd.get_random_double()*(upper(3)-lower(3))+lower(3);\n\n        dlog << LINFO << \"lower: \"<< trans(lower);\n        dlog << LINFO << \"upper: \"<< trans(upper);\n        dlog << LINFO << \"starting: \"<< trans(starting_point);\n\n        x = starting_point;\n        double val = find_min_box_constrained( \n            search_strategy,\n            objective_delta_stop_strategy(1e-16, 500), \n            brown, brown_derivative, x,\n            lower,  \n            upper   \n        );\n\n        DLIB_TEST(std::abs(val - brown(x)) < 1e-14);\n        dlog << LINFO << \"brown solution:\\n\" << x;\n        return unconstrained_gradient_magnitude(brown_derivative, x, lower, upper);\n    }\n\n    template <typename search_strategy_type>\n    void test_box_constrained_optimizers(search_strategy_type search_strategy)\n    {\n        dlib::rand rnd;\n        running_stats<double> rs;\n\n        dlog << LINFO << \"test find_min_box_constrained() on rosen\";\n        for (int i = 0; i < 10000; ++i)\n            rs.add(test_bound_solver_rosen(rnd, search_strategy));\n        dlog << LINFO << \"mean rosen gradient: \" << rs.mean();\n        dlog << LINFO << \"max rosen gradient:  \" << rs.max();\n        DLIB_TEST(rs.mean() < 1e-12);\n        DLIB_TEST(rs.max() < 1e-9);\n\n        dlog << LINFO << \"test find_min_box_constrained() on brown\";\n        rs.clear();\n        for (int i = 0; i < 1000; ++i)\n            rs.add(test_bound_solver_brown(rnd, search_strategy));\n        dlog << LINFO << \"mean brown gradient: \" << rs.mean();\n        dlog << LINFO << \"max brown gradient:  \" << rs.max();\n        dlog << LINFO << \"min brown gradient:  \" << rs.min();\n        DLIB_TEST(rs.mean() < 4e-5);\n        DLIB_TEST_MSG(rs.max() < 3e-2, rs.max());\n        DLIB_TEST(rs.min() < 1e-10);\n\n        dlog << LINFO << \"test find_max_box_constrained() on neg_rosen\";\n        rs.clear();\n        for (int i = 0; i < 1000; ++i)\n            rs.add(test_bound_solver_neg_rosen(rnd, search_strategy));\n        dlog << LINFO << \"mean neg_rosen gradient: \" << rs.mean();\n        dlog << LINFO << \"max neg_rosen gradient:  \" << rs.max();\n        DLIB_TEST(rs.mean() < 1e-12);\n        DLIB_TEST(rs.max() < 1e-9);\n\n    }\n\n    void test_poly_min_extract_2nd()\n    {\n        double off;\n\n        off = 0.0; DLIB_TEST(std::abs( poly_min_extrap(off*off, -2*off, (1-off)*(1-off)) - off) < 1e-13); \n        off = 0.1; DLIB_TEST(std::abs( poly_min_extrap(off*off, -2*off, (1-off)*(1-off)) - off) < 1e-13); \n        off = 0.2; DLIB_TEST(std::abs( poly_min_extrap(off*off, -2*off, (1-off)*(1-off)) - off) < 1e-13); \n        off = 0.3; DLIB_TEST(std::abs( poly_min_extrap(off*off, -2*off, (1-off)*(1-off)) - off) < 1e-13); \n        off = 0.4; DLIB_TEST(std::abs( poly_min_extrap(off*off, -2*off, (1-off)*(1-off)) - off) < 1e-13); \n        off = 0.5; DLIB_TEST(std::abs( poly_min_extrap(off*off, -2*off, (1-off)*(1-off)) - off) < 1e-13); \n        off = 0.6; DLIB_TEST(std::abs( poly_min_extrap(off*off, -2*off, (1-off)*(1-off)) - off) < 1e-13); \n        off = 0.8; DLIB_TEST(std::abs( poly_min_extrap(off*off, -2*off, (1-off)*(1-off)) - off) < 1e-13); \n        off = 0.9; DLIB_TEST(std::abs( poly_min_extrap(off*off, -2*off, (1-off)*(1-off)) - off) < 1e-13); \n        off = 1.0; DLIB_TEST(std::abs( poly_min_extrap(off*off, -2*off, (1-off)*(1-off)) - off) < 1e-13); \n    }\n\n    void test_solve_trust_region_subproblem_bounded()\n    {\n        print_spinner();\n        matrix<double> H(2,2);\n        H = 1, 0,\n        0, 1;\n        matrix<double,0,1> g, lower, upper, p, true_p;\n        g = {0, 0};\n\n        double radius = 0.5;\n        lower = {0.5, 0};\n        upper = {10, 10};\n\n\n        solve_trust_region_subproblem_bounded(H,g, radius, p,  0.001, 500, lower, upper);\n        true_p = { 0.5, 0};\n        DLIB_TEST_MSG(length(p-true_p) < 1e-12, p);\n\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    class optimization_tester : public tester\n    {\n    public:\n        optimization_tester (\n        ) :\n            tester (\"test_optimization\",\n                    \"Runs tests on the optimization component.\")\n        {}\n\n        void perform_test (\n        )\n        {\n            dlog << LINFO << \"test_box_constrained_optimizers(bfgs_search_strategy())\";\n            test_box_constrained_optimizers(bfgs_search_strategy());\n            dlog << LINFO << \"test_box_constrained_optimizers(lbfgs_search_strategy(5))\";\n            test_box_constrained_optimizers(lbfgs_search_strategy(5));\n            test_poly_min_extract_2nd();\n            optimization_test();\n            test_solve_trust_region_subproblem_bounded();\n        }\n    } a;\n\n}\n\n\n", "meta": {"hexsha": "b47449abeef45cd9015d55586d310606c4a9261a", "size": 43056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/dlib/test/optimization.cpp", "max_stars_repo_name": "mohitjain4395/mosip", "max_stars_repo_head_hexsha": "20ee978dc539be42c8b79cd4b604fdf681e7b672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 139.0, "max_stars_repo_stars_event_min_datetime": "2018-02-23T14:03:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T12:10:52.000Z", "max_issues_repo_path": "dlib/dlib/test/optimization.cpp", "max_issues_repo_name": "mohitjain4395/mosip", "max_issues_repo_head_hexsha": "20ee978dc539be42c8b79cd4b604fdf681e7b672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2018-03-10T06:11:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-12T07:27:42.000Z", "max_forks_repo_path": "dlib/dlib/test/optimization.cpp", "max_forks_repo_name": "mohitjain4395/mosip", "max_forks_repo_head_hexsha": "20ee978dc539be42c8b79cd4b604fdf681e7b672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 52.0, "max_forks_repo_forks_event_min_datetime": "2018-03-06T11:20:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T12:46:09.000Z", "avg_line_length": 34.9480519481, "max_line_length": 123, "alphanum_fraction": 0.505574136, "num_tokens": 11725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5199947422390119}}
{"text": "/* Copyright (c) 2019 Kjetil Olsen Lye, ETH Zurich\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\n#include <boost/test/unit_test.hpp>\n#include <fbm/fbm.hpp>\n#include <fbm/generate_normal_random.hpp>\n\nBOOST_AUTO_TEST_SUITE(FBB2DTests)\n\n\nBOOST_AUTO_TEST_CASE(BridgeZero2D) {\n    const int N = 64;\n    auto X = fbm::generate_normal_random((N - 1) * (N - 1));\n\n    auto fBm = fbm::fractional_brownian_bridge_2d(0.5, N, X);\n\n    BOOST_TEST((N + 1) * (N + 1) == fBm.size());\n\n    for (size_t i = 0; i < N + 1; ++i) {\n        BOOST_TEST(0.0 == fBm[i]);\n        BOOST_TEST(0.0 == fBm[i + N * (N + 1)]);\n        BOOST_TEST(0.0 == fBm[(N + 1) * i]);\n        BOOST_TEST(0.0 == fBm[(N + 1) * i + N]);\n\n    }\n}\n\nBOOST_AUTO_TEST_CASE(BridgeZero2DNotSidesToZero) {\n    const int N = 64;\n    auto X = fbm::generate_normal_random((N) * (N));\n\n    auto fBm = fbm::fractional_brownian_bridge_2d(0.5, N, X, false);\n\n    BOOST_TEST((N + 1) * (N + 1) == fBm.size());\n\n    BOOST_TEST(fBm[0] == 0);\n    BOOST_TEST(fBm[N] == 0);\n    BOOST_TEST(fBm[N * (N + 1)] == 0);\n    BOOST_TEST(fBm[N * (N + 1) + N] == 0);\n\n    for (size_t i = 1; i < N; ++i) {\n        BOOST_TEST(0.0 != fBm[i]);\n        BOOST_TEST(0.0 != fBm[(N + 1) * i]);\n    }\n}\n\n\n\nBOOST_AUTO_TEST_CASE(SmallSizeTwo) {\n    // Check that we can create small sizes\n    int N = 2;\n    auto X = fbm::generate_normal_random((N - 1) * (N - 1));\n\n    auto fBm = fbm::fractional_brownian_bridge_2d(0.5, N, X);\n\n    BOOST_TEST(fBm.size() == 9);\n\n\n}\n\nBOOST_AUTO_TEST_CASE(SmallSizeOne) {\n    // Check that we can create small sizes\n    int N = 1;\n    auto X = fbm::generate_normal_random((N - 1) * (N - 1));\n\n    auto fBm = fbm::fractional_brownian_bridge_2d(0.5, N, X);\n\n    BOOST_TEST(fBm.size() == 4);\n\n    for (auto d : fBm) {\n        BOOST_TEST(d == 0);\n    }\n\n\n}\n\nBOOST_AUTO_TEST_CASE(Nested) {\n\n    //return;\n    std::vector<int> resolutions = {8, 16, 32, 64, 128};\n\n\n    const int N = 2 * resolutions.back();\n    auto X = fbm::generate_normal_random((N - 1) * (N - 1));\n\n    for (auto resolution : resolutions) {\n\n        auto fBm = fbm::fractional_brownian_bridge_2d(0.5, resolution, X);\n        auto fBm_fine = fbm::fractional_brownian_bridge_2d(0.5, 2 * resolution, X);\n\n        for (int i = 0; i < resolution; ++i) {\n            for (int j = 0; j < resolution; ++j) {\n\n                BOOST_TEST(fBm[i * (resolution + 1) + j] == fBm_fine[2 * i *\n                        (2 * resolution + 1) + 2 * j]);\n            }\n        }\n    }\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE(NestedNotSetSidesToZero) {\n\n    //return;\n    std::vector<int> resolutions = {8, 16, 32, 64, 128};\n\n\n    const int N = 2 * resolutions.back();\n    auto X = fbm::generate_normal_random((N) * (N));\n\n    for (auto resolution : resolutions) {\n\n        auto fBm = fbm::fractional_brownian_bridge_2d(0.5, resolution, X, false);\n        auto fBm_fine = fbm::fractional_brownian_bridge_2d(0.5, 2 * resolution, X,\n                false);\n\n        for (int i = 0; i < resolution; ++i) {\n            for (int j = 0; j < resolution; ++j) {\n\n                BOOST_TEST(fBm[i * (resolution + 1) + j] == fBm_fine[2 * i *\n                        (2 * resolution + 1) + 2 * j]);\n            }\n        }\n    }\n\n}\n\n\nBOOST_AUTO_TEST_CASE(ThrowsOnNonePowerOfTwo) {\n    std::vector<int> non_powers = {3, 5, 6, 12};\n\n    for (auto non_power : non_powers) {\n        auto X = fbm::generate_normal_random((non_power - 1));\n        //Boost check throw wouldn't work\n\n        try {\n            auto fBm = fbm::fractional_brownian_bridge_2d(0.5, non_power, X);\n        } catch (std::runtime_error& e) {\n            continue;\n        }\n\n        BOOST_TEST(false);\n    }\n}\n\n\n\n\nBOOST_AUTO_TEST_CASE(ThrowsOnNonPositive) {\n    std::vector<int> non_positives = {-10, -4, 0};\n    auto X = fbm::generate_normal_random((10 - 1));\n\n    for (auto non_positive : non_positives) {\n\n        //Boost check throw wouldn't work\n\n        try {\n            auto fBm = fbm::fractional_brownian_bridge_2d(0.5, non_positive, X);\n        } catch (std::runtime_error& e) {\n            continue;\n        }\n\n        BOOST_TEST(false);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(NonZeroInterior) {\n    // We generate a fake random vector with constnat value 1.0\n    // This should guarantee that we never get any zero values in the interior.\n    const int N = 64;\n\n    std::vector<double> X(N * N, 1);\n\n    auto fBm = fbm::fractional_brownian_bridge_2d(0.5, N, X);\n\n    BOOST_TEST((N + 1) * (N + 1) == fBm.size());\n\n    for (size_t i = 0; i < N + 1; ++i) {\n        BOOST_TEST(0.0 == fBm[i]);\n        BOOST_TEST(0.0 == fBm[i + N * (N + 1)]);\n        BOOST_TEST(0.0 == fBm[(N + 1) * i]);\n        BOOST_TEST(0.0 == fBm[(N + 1) * i + N]);\n\n    }\n\n    for (size_t i = 1; i < N; ++i) {\n        for (size_t j = 1; j < N; ++j) {\n            BOOST_TEST(0.0 != fBm[i + j * (N + 1)]);\n        }\n    }\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "aa379bdc6dc92610258b0f269bb41c9cb4929409", "size": 5898, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fbmtest/src/test_fbb_2d.cpp", "max_stars_repo_name": "kjetil-lye/fractional_brownian_motion", "max_stars_repo_head_hexsha": "0dfd8ddd8568e72f8d1eaf1ad37280cc6733be8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T12:37:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T12:37:03.000Z", "max_issues_repo_path": "fbmtest/src/test_fbb_2d.cpp", "max_issues_repo_name": "kjetil-lye/fractional_brownian_motion", "max_issues_repo_head_hexsha": "0dfd8ddd8568e72f8d1eaf1ad37280cc6733be8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fbmtest/src/test_fbb_2d.cpp", "max_forks_repo_name": "kjetil-lye/fractional_brownian_motion", "max_forks_repo_head_hexsha": "0dfd8ddd8568e72f8d1eaf1ad37280cc6733be8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T15:48:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-14T15:48:05.000Z", "avg_line_length": 27.0550458716, "max_line_length": 83, "alphanum_fraction": 0.5886741268, "num_tokens": 1861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5199947370457296}}
{"text": "#include <geometry.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\ntypedef tiny::MathTypes<float> MT;\ntypedef MT::vector3_type       V;\ntypedef MT::real_type          T;\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(inside_triangle_test)\n{\n  V const p0 = V::make(0.0, 0.0, 0.0);\n  V const p1 = V::make(1.0, 0.0, 0.0);\n  V const p2 = V::make(0.0, 1.0, 0.0);\n\n  geometry::Triangle<V> const A = geometry::make_triangle(p0,p1,p2);\n\n  BOOST_CHECK( geometry::is_valid(A) == true );\n\n  // Close to corners are allways inside\n  {\n    V const k0 = V::make(0.0001, 0.0001, 0.0);\n    V const k1 = V::make(0.9999, 0.0, 0.0);\n    V const k2 = V::make(0.0, 0.9999, 0.0);\n\n    bool test0 = geometry::inside_triangle( k0, A, true );\n    bool test1 = geometry::inside_triangle( k1, A, true );\n    bool test2 = geometry::inside_triangle( k2, A, true );\n\n    BOOST_CHECK( test0 );\n    BOOST_CHECK( test1 );\n    BOOST_CHECK( test2 );\n\n    test0 = geometry::inside_triangle( k0, A, false );\n    test1 = geometry::inside_triangle( k1, A, false );\n    test2 = geometry::inside_triangle( k2, A, false );\n\n    BOOST_CHECK( test0 );\n    BOOST_CHECK( test1 );\n    BOOST_CHECK( test2 );\n\n  }\n  // Midpoint is allways inside\n  {\n    bool const test0 = geometry::inside_triangle( (p0+p1+p2)/3.0 , A, true );\n    bool const test1 = geometry::inside_triangle( (p0+p1+p2)/3.0 , A, false );\n\n    BOOST_CHECK( test0 );\n    BOOST_CHECK( test1 );\n  }\n  // Some arbitary points\n  {\n    V const k0 = V::make( 0.2,  0.2,  0.0);  // inside and on plane\n    V const k1 = V::make( 0.2,  0.2,  0.2);  // inside and above plane\n    V const k2 = V::make( 0.2,  0.2, -0.2); // inside and below plane\n    V const k3 = V::make(-1.0, -1.0,  0.0);   // outside and on plane\n    V const k4 = V::make(-1.0, -1.0,  0.2);  // outside and above plane\n    V const k5 = V::make(-1.0, -1.0, -0.2); // outside and below plane\n\n    bool test0 = geometry::inside_triangle( k0, A, true );\n    bool test1 = geometry::inside_triangle( k1, A, true );\n    bool test2 = geometry::inside_triangle( k2, A, true );\n    bool test3 = geometry::inside_triangle( k3, A, true );\n    bool test4 = geometry::inside_triangle( k4, A, true );\n    bool test5 = geometry::inside_triangle( k5, A, true );\n\n    BOOST_CHECK( test0 );\n    BOOST_CHECK( !test1 );\n    BOOST_CHECK( !test2 );\n    BOOST_CHECK( !test3 );\n    BOOST_CHECK( !test4 );\n    BOOST_CHECK( !test5 );\n\n    test0 = geometry::inside_triangle( k0, A, false );\n    test1 = geometry::inside_triangle( k1, A, false );\n    test2 = geometry::inside_triangle( k2, A, false );\n    test3 = geometry::inside_triangle( k3, A, false );\n    test4 = geometry::inside_triangle( k4, A, false );\n    test5 = geometry::inside_triangle( k5, A, false );\n\n    BOOST_CHECK( test0 );\n    BOOST_CHECK( test1 );\n    BOOST_CHECK( test2 );\n    BOOST_CHECK( !test3 );\n    BOOST_CHECK( !test4 );\n    BOOST_CHECK( !test5 );\n  }\n  // Different outside tests -- trying to generate all different cases....\n  {\n    V const k0 = V::make( 0.5, -0.1, 0.0);\n    V const k1 = V::make( 1.0,  1.0, 0.0);\n    V const k2 = V::make(-0.1,  0.5, 0.0);\n    V const k3 = V::make(-1.0, -1.0, 0.0);\n    V const k4 = V::make( 0.1,  1.0, 0.0);\n    V const k5 = V::make( 1.0,  0.1, 0.0);\n\n    bool const test0 = geometry::inside_triangle( k0, A, false );\n    bool const test1 = geometry::inside_triangle( k1, A, false );\n    bool const test2 = geometry::inside_triangle( k2, A, false );\n    bool const test3 = geometry::inside_triangle( k3, A, false );\n    bool const test4 = geometry::inside_triangle( k4, A, false );\n    bool const test5 = geometry::inside_triangle( k5, A, false );\n\n    BOOST_CHECK( !test0 );\n    BOOST_CHECK( !test1 );\n    BOOST_CHECK( !test2 );\n    BOOST_CHECK( !test3 );\n    BOOST_CHECK( !test4 );\n    BOOST_CHECK( !test5 );\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "2bf1960b0588d0e336c6d1919f28a615389ea6be", "size": 3998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_inside_triangle/geometry_inside_triangle.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_inside_triangle/geometry_inside_triangle.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_inside_triangle/geometry_inside_triangle.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.041322314, "max_line_length": 78, "alphanum_fraction": 0.6228114057, "num_tokens": 1338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.519920545560929}}
{"text": "/**\n * @author      Mahdi Maghrebi <mahdi.maghrebi@nih.gov>\n * This code is an implementation of UMAP algorithm for dimension reduction. \n * The reference paper is \u201cUMAP: Uniform Manifold Approximation and Projection for Dimension Reduction\u201c, by McInnes et al., 2018 (https://arxiv.org/abs/1802.03426)\n * Jan 2020\n */\n\n#include <vector>\n#include <iostream>\n#include <stdio.h>      \n#include <stdlib.h>     \n#include <time.h>      \n#include <list>\n#include <string>\n#include <math.h>\n#include <fstream>\n#include <float.h>\n#include <boost/filesystem.hpp>\n#include \"KNN_OpenMP_Code.h\"\n#include \"highDComputes.h\"\n#include \"Initialization.h\"\n#include \"LMOptimization.h\"\n#include \"SGD.h\"\n#include <exception>\n#include <sstream>\n#include <omp.h>\n#include <Eigen/Sparse>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char ** argv) {\n\t/**\n\t * The errors and informational messages are outputted to the log file \n\t */\n\tofstream logFile;\n\tstring logFileName=\"Setting.txt\";\n\tlogFile.open(logFileName);\n\t/**\n\t * The input parameters are read from command line which are as follow.\n\t * filePath: The full path to the input file containig the dataset.\n\t * outputPath: The full path to the output csv file containing the coordinates of data in the embedding space.\n\t * K: K in K-NN that means the desired number of Nearest Neighbours to be computed.\n\t * sampleRate: The rate at which we do sampling. This parameter plays a key role in the performance.\n\t * This parameter is a trades-off between the performance and the accuracy of the results.\n\t * Values closer to 1 provides more accurate results but the execution takes longer.\n\t * DimLowSpace: Dimension of Low-D or embedding space (usually 1,2,or 3).\n\t * randomInitializing: Defining the Method for Initialization of data in low-D space\n\t * nepochs: is the number of training epochs to be used in optimizing. Larger values result in more accurate embeddings\n\t * mindist defines how tight the points are from each other in Low-D space\n\t * distanceMetric is the metric to compute the distance between the points in high-D space, by deafult should be euclidean\n\t * distanceV1 is the first optional variable needed for computing distance in some metrics\n\t * distanceV2 is the second optional variable needed for computing distance in some metrics\n\t * inputPathOptionalArray is the full path to the directory that contains a csv file of the optional array needed for computing distance in some metrics. \n\t */\n\tstring filePath, filePathOptionalArray=\"\", outputPath, LogoutputPath, inputPath;\n\tint K,DimLowSpace,nepochs;\n\tfloat sampleRate,mindist,distanceV1=0,distanceV2=0;\n\tbool randomInitializing;\n\tstring distanceMetric=\"euclidean\";\n\n\tfor (int i=1; i<argc;++i){\n\t\tif (string(argv[i])==\"--inputPath\") {\n\t\t\tinputPath=argv[i+1];\n\n\t\t\tif(!boost::filesystem::exists(inputPath) || !boost::filesystem::is_directory(inputPath))\n\t\t\t{\n\t\t\t\tlogFile << \"Incorrect input path\";\n\t\t\t\tcout << \"Incorrect input path\";\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tconst std::string ext = \".csv\";\n\t\t\tboost::filesystem::recursive_directory_iterator it(inputPath);\n\t\t\tboost::filesystem::recursive_directory_iterator endit;\n\n\t\t\tbool fileFound = false;\n\t\t\twhile(it != endit) {\n\t\t\t\tif(boost::filesystem::is_regular_file(*it) && it->path().extension() == ext){\n\t\t\t\t\tfileFound = true;\n\t\t\t\t\tfilePath = it->path().string();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t++it;\n\t\t\t}\n\t\t\tif (!fileFound){\n\t\t\t\tlogFile << \"CSV file is not found in the input path\";\n\t\t\t\tcout << \"CSV file is not found in the input path\";\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\telse if (string(argv[i])==\"--K\") K=atoi(argv[i+1]);\n\t\telse if (string(argv[i])==\"--sampleRate\") sampleRate=stof(argv[i+1]);\n\t\telse if (string(argv[i])==\"--mindist\") mindist=stof(argv[i+1]);\n\t\telse if (string(argv[i])==\"--DimLowSpace\") DimLowSpace=atoi(argv[i+1]);\n\t\telse if (string(argv[i])==\"--randomInitializing\") {\n\t\t\tstd::stringstream ss(argv[i+1]);\n\t\t\tss >> std::boolalpha >> randomInitializing;\n\t\t}\n\t\telse if (string(argv[i])==\"--outputPath\"){\n\t\t\tboost::filesystem::path p(argv[i+1]);\n\n\t\t\tif(!boost::filesystem::exists(p) || !boost::filesystem::is_directory(p))\n\t\t\t{\n\t\t\t\tlogFile << \"Incorrect output path\";\n\t\t\t\tcout << \"Incorrect output path\";\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tLogoutputPath=argv[i+1];\n\t\t\tboost::filesystem::path joinedPath = p / boost::filesystem::path(\"ProjectedData_EmbeddedSpace.csv\");\n\t\t\toutputPath = joinedPath.string();\n\n\t\t}\n\t\telse if (string(argv[i])==\"--nepochs\") nepochs=atoi(argv[i+1]);\n\t\telse if (string(argv[i])==\"--distanceMetric\") distanceMetric=argv[i+1];\n\t\telse if (string(argv[i])==\"--distanceV1\") distanceV1=stof(argv[i+1]);\n\t\telse if (string(argv[i])==\"--distanceV2\") distanceV2=stof(argv[i+1]);\n\t\telse if (string(argv[i])==\"--inputPathOptionalArray\") {\n\t\t\tstring inputPathOptionalArray=argv[i+1];\n\n\t\t\tif(!boost::filesystem::exists(inputPathOptionalArray) || !boost::filesystem::is_directory(inputPathOptionalArray))\n\t\t\t{\n\t\t\t\tlogFile << \"Incorrect input path\";\n\t\t\t\tcout << \"Incorrect input path\";\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tconst std::string ext = \".csv\";\n\t\t\tboost::filesystem::recursive_directory_iterator it(inputPathOptionalArray);\n\t\t\tboost::filesystem::recursive_directory_iterator endit;\n\n\t\t\tbool fileFound = false;\n\t\t\twhile(it != endit) {\n\t\t\t\tif(boost::filesystem::is_regular_file(*it) && it->path().extension() == ext){\n\t\t\t\t\tfileFound = true;\n\t\t\t\t\tfilePathOptionalArray = it->path().string();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t++it;\n\t\t\t}\n\t\t\tif (!fileFound){\n\t\t\t\tlogFile << \"CSV file is not found in the input path\";\n\t\t\t\tcout << \"CSV file is not found in the input path\";\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\n\t}\n\tlogFile<<\"------------The following Input Arguments were read------------\"<<endl;\n\tlogFile<<\"The full path to the input file: \"<< filePath<<endl;\n\tlogFile<<\"The full path to the output file: \"<< outputPath<<endl;\n\tlogFile<<\"The desired number of NN to be computed: \"<< K <<endl;\n\tlogFile<<\"The sampleRate(The rate at which we do sampling): \"<< sampleRate <<endl;  \n\tlogFile<<\"The Dimension of Low-D Space: \"<< DimLowSpace <<endl; \n\tlogFile << std::boolalpha;\n\tlogFile<<\"Random Initialization of Points in Low-D Space: \"<< randomInitializing <<endl; \n\tlogFile<<\"The number of training epochs: \"<< nepochs <<endl; \n\tlogFile<<\"The chosen mindist parameter: \"<< mindist <<endl; \t\n\tlogFile<<\"The metric to compute the distance between the points in high-D space: \"<< distanceMetric <<endl; \n\tlogFile<<\"The optional variable 1 for the distance: \"<< distanceV1 <<endl; \n\tlogFile<<\"The optional variable 2 for the distance: \"<< distanceV2 <<endl;\n\tlogFile<<\"The full path to optional array for the distance metric computation: \"<< filePathOptionalArray <<endl;\t\n\n\tcout<<\"------------The following Input Arguments were read------------\"<<endl;\n\tcout<<\"The full path to the input file: \"<< filePath<<endl;\n\tcout<<\"The full path to the output file: \"<< outputPath<<endl;\n\tcout<<\"The desired number of NN to be computed: \"<< K <<endl;\n\tcout<<\"The sampleRate(The rate at which we do sampling): \"<< sampleRate <<endl;   \n\tcout<<\"The Dimension of Low-D Space: \"<< DimLowSpace <<endl; \n\tcout << std::boolalpha;\n\tcout<<\"Random Initialization of Points in Low-D Space: \"<< randomInitializing <<endl; \n\tcout<<\"The number of training epochs: \"<< nepochs <<endl; \n\tcout<<\"The chosen mindist parameter: \"<< mindist <<endl; \t\n\tcout<<\"The metric to compute the distance between the points in high-D space: \"<< distanceMetric <<endl; \n\tcout<<\"The optional variable 1 for the distance: \"<< distanceV1 <<endl; \n\tcout<<\"The optional variable 2 for the distance: \"<< distanceV2 <<endl;\n\tcout<<\"The full path to optional array for the distance metric computation: \"<< filePathOptionalArray <<endl;\n\t/**\n\t * Size of Dataset without the header (i.e.(#Rows in dataset)-1).\n\t */\n\tstring cmd=\"wc -l \"+filePath;\n\tstring outputCmd = exec(cmd.c_str());\n\tconst int N=stoi(outputCmd.substr(0, outputCmd.find(\" \")))-1;\n\tlogFile<<\"The Dimension of Dataset Records (Number of Rows in inputfile w/o header ): \"<< N <<endl;\n\tcout<<\"The Dimension of Dataset Records (Number of Rows in inputfile w/o header ): \"<< N <<endl;\n\t/**\n\t * Dimension of Dataset (#Columns)\n\t */\n\tint Dim;\n\tstring cmd2=\"head -n 1 \"+ filePath + \" |tr '\\\\,' '\\\\n' |wc -l \";\n\tDim = stoi(exec(cmd2.c_str())); \n\tlogFile<<\"The Dimension of Dataset Features(Number of Columns in inputfile): \"<< Dim <<endl;\n\tcout<<\"The Dimension of Dataset Features(Number of Columns in inputfile): \"<< Dim <<endl;\n\n\tif (K > N) {\n\t\tlogFile<<\" The desired number of NN has exceeded the size of dataset \"<<endl;\n\t\tcout<<\" The desired number of NN has exceeded the size of dataset \"<<endl;   \n\t\treturn 1;\n\t}\n\n\tlogFile<<\"------------END of INPUT READING------------\"<< endl;\t\n\tcout<<\"------------END of INPUT READING------------\"<< endl;\n\t\n\t/**\n\t * Query about the number of available CPU processors and set it as OpenMP threads\n\t */\t\n\tint nProcessors = omp_get_num_procs();\n    omp_set_num_threads(nProcessors-1);\n\tcout <<\"Total Number of Processes in the OpenMP Parallel Region = \"<< nProcessors-1 <<endl;\t\n\t\n\tsrand(17);\t\n\n\t/**\n\t * convThreshold: Convergance Threshold of K-NN. A fixed integer is used here instead of delta*N*K. \n\t */\t\t \n\tconst int convThreshold=5;\n\t/**\n\t * indices of K-NN for each data point\n\t */\n\tint** B_Index = new int*[N];\n\tfor (int i = 0; i < N; ++i) { B_Index[i] = new int[K]; }\t\n\t/**\n\t * corresponding distance for K-NN indices stored in B_Index\n\t */\n\tdouble** B_Dist = new double*[N];\n\tfor (int i = 0; i < N; ++i) { B_Dist[i] = new double[K]; }\n\t/**\n\t * Compute K-NN following the algorithm for shared-memory K-NN\n\t * @param filePath The full path to the input file containig the dataset.\n\t * @param N Size of Dataset without the header (i.e.(#Rows in dataset)-1).\t \n\t * @param Dim Dimension of Dataset (#Columns) \n\t * @param K the desired number of Nearest Neighbours to be computed\n\t * @param sampleRate The rate at which we do sampling\n\t * @param convThreshold Convergance Threshold\n\t * @param logFile The errors and informational messages are outputted to the log file\n\t * @param distanceMetric is the metric to compute the distance between the points in high-D space, by deafult should be euclidean\n\t * @param distanceV1 is the first optional variable needed for computing distance in some metrics\n\t * @param distanceV2 is the second optional variable needed for computing distance in some metrics\t\n\t * @param filePathOptionalArray The full path to optional array for the distance metric computation\n\t * @return B_Index indices of K-NN for each data point \t \n\t * @return B_Dist corresponding distance for K-NN indices stored in B_Index\t \n\t */\n\tcomputeKNNs(filePath, N, Dim, K, sampleRate, convThreshold,B_Index,B_Dist, logFile, distanceMetric, distanceV1, distanceV2,filePathOptionalArray);\n    \n\tbool flag=false;\n\tfor (int i = 0; i < N; ++i) {\n\t\tfor (int j = 0; j < K; ++j) {\n\t\t\tif (B_Dist[i][j] < 0) {         \n\t\t\t\tlogFile<<\"ALERT: A distance in high-D space was computed as negative, use this program with caution\"<<endl;\n\t\t\t\tcout<<\"ALERT: A distance in high-D space was computed as negative, use this program with caution\"<<endl; \n\t\t\t\tflag=true;\n\t\t\t\tbreak; \n\t\t\t}     \n\t\t}\n\t\tif (flag) break;\n\t}\n\n\tint* B_Index_Min = new int[N];\n\tdouble* B_Dist_Min = new double[N];\n\t/**\n\t * Compute B_Index and B_Dist for the closest points (K-NNs) \n\t * @param B_Index indices of K-NN for each data point \t\n\t * @param B_Dist corresponding distance for K-NN indices stored in B_Index\n\t * @param N Size of Dataset without the header (i.e.(#Rows in dataset)-1). \n\t * @param K the desired number of Nearest Neighbours to be computed\t \t \t \t \n\t * @return B_Index_Min B_Index for the closest point \n\t * @return B_Dist_Min B_Dist for the corresponding B_Index_Min\n\t */\n\tfindMin(B_Index,B_Dist, N,K,B_Index_Min,B_Dist_Min);\n\n\tdouble* SigmaValues = new double[N];\n\t/**\n\t * Compute SigmaValues for each data point (Smooth approximator to K-NN distance) iteratively\n\t * @param B_Dist corresponding distance for K-NN indices stored in B_Index\n\t * @param B_Dist_Min B_Dist for the corresponding B_Index_Min\n\t * @param N Size of Dataset without the header (i.e.(#Rows in dataset)-1). \n\t * @param K the desired number of Nearest Neighbours to be computed\t\n\t * @return SigmaValues An array of Sigma Values for data \t \t \t \n\t */\n\tfindSigma(B_Dist, B_Dist_Min,SigmaValues, N, K);\n\n\t/**\n\t * To save memory space, \"Sparse Matrix\" data structure is used here\n\t * SparseMatrix by default is oriented column-major\n\t */\n\tSparseMatrix<float> adjacencyMatrixA(N,N), adjacencyMatrixAT(N,N), graphSM(N,N);\t \n\ttypedef Eigen::Triplet<float> T;\n\tstd::vector<T> tripletList;\n\ttripletList.reserve(N*K);\n\n\tfor (int i=0; i<N; ++i){\n\t\tfor (int j=0; j<K; ++j){\n\t\t\tint point2=B_Index[i][j]; \n\t\t\tfloat tmp=exp((B_Dist_Min[i]-B_Dist[i][j])/SigmaValues[i]);\n\t\t\ttripletList.push_back(T(i,point2,tmp));\n\t\t}\n\t}\n\n\tadjacencyMatrixA.setFromTriplets(tripletList.begin(), tripletList.end());\t\t\n\tadjacencyMatrixAT=adjacencyMatrixA.transpose();\n\tgraphSM=adjacencyMatrixA+adjacencyMatrixAT;\n\tgraphSM -=adjacencyMatrixA.cwiseProduct(adjacencyMatrixAT);\n\n\tfloat MaxWeight=0;\n\tfor (int k=0; k<graphSM.outerSize(); ++k){\n\t\tfloat sum=0;\n\t\tfor (SparseMatrix<float>::InnerIterator it(graphSM,k); it; ++it) {\n\t\t\tsum += it.value(); \n\t\t\tif (it.value() > MaxWeight) MaxWeight=it.value();  \n\t\t}\n\t} \n\n\tlogFile<<\"------------Setting Low-D Space Design------------\"<<endl;\n\tcout<<\"------------Setting Low-D Space Design------------\"<<endl;\n\n\t/**\n\t * embedding is the coordinates of the points in the low-D space  \n\t */\n\tdouble** embedding = new double*[N];\n\tfor (int i = 0; i < N; ++i) { embedding[i] = new double[DimLowSpace]; }    \n\n\tlogFile<<\"------------Starting Initialization in the Low-D Space------------\"<<endl;\n\tcout<<\"------------Starting Initialization in the Low-D Space------------\"<<endl;\n\t/**\n\t * Initializes the data points in low-D space\n\t * @param randomInitializing the methodology for Initialization of data in low-D space\n\t * @param logFile contains the errors and informational messages \n\t * @param N Size of Dataset without the header (i.e.(#Rows in dataset)-1). \n\t * @param graph contains undirected weights (similarities) in the form of a matrix of size NxN\n\t * @param DimLowSpace Dimension of Low-D space \t \t \n\t * @return embedding is the coordinates of the points in the low-D space\t \t \t \n\t */\n\tInitialization (randomInitializing, embedding, logFile, N, graphSM, MaxWeight, DimLowSpace, nepochs);\n\n\tlogFile<<\"------------Starting Estimating Hyper-Parameters a and b ------------\"<<endl;\n\tcout<<\"------------Starting Estimating Hyper-Parameters a and b ------------\"<<endl;\n\t/**\n\t * Hyper-Parameters a and b which needs to be estimated by data fitting. \n\t */\n\tfloat aValue, bValue;\n\tfloat spread=1.0;\n\t/**\n\t *  Estimation of Hyper-Parameters a and b by curve fitting and using Levenberg-Marquardt solution\n\t */\t\t\n\testimateParameters(aValue, bValue, mindist, spread, logFile);\n\n\tlogFile<<\"The Estimated Values for a is \"<< aValue << \" and for b is \"<< bValue <<endl;\n\tcout<<\"The Estimated Values for a is \"<< aValue << \" and for b is \"<< bValue <<endl;\n\n\tlogFile<<\"------------Starting Solution for Stochastic Gradient Descent (SGD)------------\"<<endl;\t\n\tcout<<\"------------Starting Solution for Stochastic Gradient Descent (SGD)------------\"<<endl;\n\t/**\n\t *  alpha is the initial learning rate for the SGD. alpha starts from 1 and decreases in each epoch iteration\n\t */\t\n\tfloat alpha=1.0;  \n\t/**\n\t * epochs_per_sample is a vector of edges with the values proportional to the values in graph \n\t * epochs_per_sample represents the epoch weight for edges where the edge with the highest similarity will get the value of 1 \n\t * and all other edges will get a proportional epoch weight scaled from it. epochs_per_sample is used as a measure to include an edge in \n\t * SGD computations. The edge with the highest similarity will be used at every epoch iteration. \n\t * head is a vector containing the head index of the edge\n\t * tail is a vector containing the tail index of the edge\n\t */\n\tvector<int> head, tail;\n\tvector<float> epochs_per_sample;\n\n\tfor (int k=0; k<graphSM.outerSize(); ++k){\n\t\tfor (SparseMatrix<float>::InnerIterator it(graphSM,k); it; ++it) {\n\t\t    if (it.value() <  MaxWeight/nepochs) continue;  \n\t\t\tepochs_per_sample.push_back(MaxWeight/it.value());\n\t\t\thead.push_back(it.col());\n\t\t\ttail.push_back(it.row()); \n\t\t}\n\t}\n\n\t/**\n\t * This section was adopted from SGD implementation at https://github.com/lmcinnes/umap/blob/8f2ef23ec835cc5071fe6351a0da8313d8e75706/umap/layouts.py#L136\n\t * edgeCounts is total number of edges in the high-D space graph\n\t * epoch_of_next_sample is an index of the epoch state of the edges. If it is less than epoch index, we will use the edge in the computation\n\t * epoch_of_next_negative_sample is an index of the epoch state of the edges for sampling from non-connected surrounding points. \n\t * negative_sample_rate is the rate at which we sample from the non-connected surrounding points as compared to the connected edges. \n\t * Increasing this value will result in greater repulsive force being applied, greater optimization cost, but slightly more accuracy.\n\t */\t \n\tint edgeCounts=epochs_per_sample.size();\n\tconst int negative_sample_rate=5;\n\tint n_neg_samples;\n//Substituting with Vectors due to Stacksize run-time error\n//\tfloat epoch_of_next_sample[edgeCounts];    \n//\tfloat epochs_per_negative_sample[edgeCounts]; \n//\tfloat epoch_of_next_negative_sample[edgeCounts];  \n    vector<float> epoch_of_next_sample,epochs_per_negative_sample,epoch_of_next_negative_sample;\n\n\tfor (int i = 0; i < edgeCounts; ++i) {\n//\t\tepoch_of_next_sample[i]=epochs_per_sample[i];\n//\t\tepochs_per_negative_sample[i]=epochs_per_sample[i]/negative_sample_rate;\n//\t\tepoch_of_next_negative_sample[i]=epochs_per_negative_sample[i];\n        epoch_of_next_sample.push_back(epochs_per_sample[i]);\n        epochs_per_negative_sample.push_back(epochs_per_sample[i]/negative_sample_rate);\n        epoch_of_next_negative_sample.push_back(epochs_per_negative_sample[i]);\n\t}  \n\t/**\n\t *  move_other is equal to 1 if not embedding new previously unseen points to low-D space\n\t */\n\tconst int move_other=1; \n\t/**\n\t *  dEpsilon is zero approximation in double precision\n\t */\t\n\tconst double dEpsilon=1e-14;\n\tdouble dist_squared;\n\t// The main training loop     \n\tfor (int n = 1; n < nepochs; ++n) {\n\n\t\t//Loop over all edges of the graph \n\t\tif (n%100 == 0){\n\t\t\tlogFile << \"SGD iteration = \"<<n<<\" from \"<< nepochs <<endl;\n\t\t\tcout << \"SGD iteration = \"<<n<<\" from \"<< nepochs <<endl;\n\t\t}\n\n\t\tfor (int i = 0; i < edgeCounts; ++i) {  \t\n\t\t\tif (epoch_of_next_sample[i] <= n){ \t\n\n\t\t\t\tint headIndex = head[i];   \n\t\t\t\tint tailIndex = tail[i];  \n\n\t\t\t\tdist_squared = rdist(embedding, DimLowSpace, headIndex, tailIndex);\n\n\t\t\t\tdouble grad_coeff;\n\t\t\t\tif (dist_squared<dEpsilon) grad_coeff=0;  \n\t\t\t\telse {grad_coeff= -2.0*aValue*bValue*pow(dist_squared,bValue-1)/(1.0+aValue*pow(dist_squared,bValue)); }\n                \n                double grad_d;\n\t\t\t\tfor (int jj = 0; jj < DimLowSpace; ++jj) { \t\t\t\t\n\t\t\t\t\tgrad_d = alpha*clip(grad_coeff*(embedding[headIndex][jj]-embedding[tailIndex][jj]));\n                    embedding[headIndex][jj] += grad_d; \n\t\t\t\t\t//if (move_other==1) \t{\t\t\t\t\t\n\t\t\t\t\t\tembedding[tailIndex][jj] -= grad_d;\t\t\t\t\t\t\t\n\t\t\t\t\t//}\n\t\t\t\t}\n\n\t\t\t\tepoch_of_next_sample[i] += epochs_per_sample[i];\n\t\t\t\tn_neg_samples = int((float(n) - epoch_of_next_negative_sample[i])/ epochs_per_negative_sample[i]);     \t      \n\n\t\t\t\tfor (int ll = 0; ll < n_neg_samples; ++ll) {\t    \t\n\t\t\t\t\tint randomIndex = rand() % N;\n\t\t\t\t\tif (randomIndex==headIndex) continue;\n\n\t\t\t\t\tdist_squared= rdist(embedding, DimLowSpace, headIndex, randomIndex);\n\n\t\t\t\t\tif (dist_squared < dEpsilon) grad_coeff=0; \n\t\t\t\t\telse{ grad_coeff = 2.0*bValue/((0.001+dist_squared)*(1.0+aValue*pow(dist_squared,bValue))); }\n\n\t\t\t\t\tfor (int jj = 0; jj < DimLowSpace; ++jj) {  \n\t\t\t\t\t\tif  (grad_coeff > 0) {\n\t\t\t\t\t\t\tembedding[headIndex][jj] += alpha*clip(grad_coeff*(embedding[headIndex][jj]-embedding[randomIndex][jj]));\n\t\t\t\t\t\t} else  {\t\t\t\t\t\t\n\t\t\t\t\t\t\tembedding[headIndex][jj] += alpha*4.0; \n\t\t\t\t\t\t}\n\t\t\t\t\t}    \t        \n\t\t\t\t}       \t    \n\t\t\t\tepoch_of_next_negative_sample[i] += (n_neg_samples * epochs_per_negative_sample[i]);  \n\t\t\t}   \t\n\t\t}    \t\n\t\talpha=1.0-((float)n)/nepochs;    \t\n\t}\n\n\tlogFile<<\"------------Starting Outputing the Results------------\"<<endl;\n\tcout<<\"------------Starting Outputing the Results------------\"<<endl;\n\t/**\n\t * Output the coordinates of the projected data in the low-D space\n\t */ \n\tofstream embeddedSpacefile;\n\tembeddedSpacefile.open(outputPath);\n\n\tfor (int j = 0; j < DimLowSpace; ++j) {\n\t\tif (j != DimLowSpace-1) embeddedSpacefile<<\"Dimension\"<<j+1<<\",\";\n\t\telse embeddedSpacefile<<\"Dimension\"<<j+1<<endl;\n\t}\n\n\tfor (int i = 0; i < N; ++i) {\n\t\tfor (int j = 0; j < DimLowSpace; ++j) {\t\t\n\t\t\tif (j==DimLowSpace-1) {\n\t\t\t\tembeddedSpacefile<< embedding[i][j]<<endl;}\n\t\t\telse {embeddedSpacefile<< embedding[i][j]<<\",\";}\n\t\t}\n\t}\n\n\tembeddedSpacefile.close();\n\tlogFile.close();\n\t/**\n\t * copy Logfile to the file system which could be accessed outside the docker container\n\t */ \n\tstring cmd3=\"cp \"+ logFileName+\"  \"+LogoutputPath;\n\t// To remove the returning messages, we can switch to the following command \n\t//\tstring cmd3=\"cp \"+ logFileName+\"  \"+LogoutputPath+ \" 2>&1 /dev/null\";\n\tstring outputCmd3 = exec(cmd3.c_str());\n\n\treturn 0;\n}\n\n\n\n", "meta": {"hexsha": "678f6e37337af1763220f796adf1b54b89e50ffa", "size": 21205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dimension_reduction/UMAP/Shared-Memory-OpenMP/main.cpp", "max_stars_repo_name": "mmvih/polus-plugins", "max_stars_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dimension_reduction/UMAP/Shared-Memory-OpenMP/main.cpp", "max_issues_repo_name": "mmvih/polus-plugins", "max_issues_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dimension_reduction/UMAP/Shared-Memory-OpenMP/main.cpp", "max_forks_repo_name": "mmvih/polus-plugins", "max_forks_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-26T19:23:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T19:23:57.000Z", "avg_line_length": 42.1570576541, "max_line_length": 163, "alphanum_fraction": 0.6834237208, "num_tokens": 5543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5199205386595234}}
{"text": "/*===================================================================\n\nMSI applications for interactive analysis in MITK (M2aia)\n\nCopyright (c) Jonas Cordes\n\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt for details.\n\n===================================================================*/\n\n#include \"mitkIOUtil.h\"\n#include <m2MedianAbsoluteDeviation.h>\n#include <mitkTestFixture.h>\n#include <mitkTestingMacros.h>\n#include <random>\n\n//#include <boost/algorithm/string.hpp>\n\nclass m2MedianAbsoluteDeviationTestSuite : public mitk::TestFixture\n{\n  CPPUNIT_TEST_SUITE(m2MedianAbsoluteDeviationTestSuite);\n  MITK_TEST(ApplyMAD_SeededGaussianNoise_shouldReturnTrue);\n\n  CPPUNIT_TEST_SUITE_END();\n\nprivate:\npublic:\n  void ApplyMAD_SeededGaussianNoise_shouldReturnTrue()\n  {\n\n    std::vector<double> signal = {5, 5, 9, 5, 5, 5, 5, 0, 4, 4, 4, 6, 6, 6};\n    double noiseLevel = m2::Signal::mad(signal);\n    CPPUNIT_ASSERT_DOUBLES_EQUAL(double(1.4825999999999999), noiseLevel, mitk::eps);\n  }\n};\n\nMITK_TEST_SUITE_REGISTRATION(m2MedianAbsoluteDeviation)\n", "meta": {"hexsha": "40c3798ebf58856f5b7bd53c1a69f97b8641b2db", "size": 1176, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/M2aiaSignalProcessing/Testing/m2MedianAbsoluteDeviationTest.cpp", "max_stars_repo_name": "ivowolf/M2aia", "max_stars_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-07-22T06:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T12:53:31.000Z", "max_issues_repo_path": "Modules/M2aiaSignalProcessing/Testing/m2MedianAbsoluteDeviationTest.cpp", "max_issues_repo_name": "ivowolf/M2aia", "max_issues_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-07-25T22:29:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T13:21:30.000Z", "max_forks_repo_path": "Modules/M2aiaSignalProcessing/Testing/m2MedianAbsoluteDeviationTest.cpp", "max_forks_repo_name": "ivowolf/M2aia", "max_forks_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-23T11:53:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T06:14:24.000Z", "avg_line_length": 26.7272727273, "max_line_length": 84, "alphanum_fraction": 0.6879251701, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5199205386595234}}
{"text": "/*\r\n \r\n [begin_description]\r\n Test case for issue 149: \r\n Error C2582 with msvc-10 when using iterator-based integration\r\n [end_description]\r\n\r\n Copyright 2011-2015 Karsten Ahnert\r\n Copyright 2011-2015 Mario Mulansky\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\r\n// disable checked iterator warning for msvc\r\n\r\n#include <boost/config.hpp>\r\n#ifdef BOOST_MSVC\r\n    #pragma warning(disable:4996)\r\n#endif\r\n\r\n#define BOOST_TEST_MODULE odeint_regression_147\r\n\r\n#include <utility>\r\n#include <iostream>\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <boost/mpl/vector.hpp>\r\n#include <boost/range/algorithm/find_if.hpp>\r\n\r\n#include <boost/numeric/odeint.hpp>\r\n\r\nusing namespace boost::unit_test;\r\nusing namespace boost::numeric::odeint;\r\nnamespace mpl = boost::mpl;\r\n\r\ntypedef std::vector<double> state_type;\r\n\r\nvoid rhs( const state_type &x , state_type &dxdt , const double t )\r\n{\r\n}\r\n\r\n\r\ntemplate<class Stepper>\r\nstruct perform_test\r\n{\r\n    void operator()( void )\r\n    {\r\n        bulirsch_stoer< state_type > stepper( 1e-9, 0.0, 0.0, 0.0 );\r\n        state_type x( 3, 10.0 );\r\n\r\n        auto iter = boost::find_if(\r\n            make_adaptive_time_range( stepper, rhs, x, 0.0, 1.0, 0.01 ),\r\n            []( const std::pair< const state_type &, double > &x )\r\n        { return ( x.first[0] < 0.0 ); } );\r\n\r\n        std::cout << iter->second << \"\\t\" << iter->first[0] << \"\\t\"\r\n                  << iter->first[1] << \"\\t\" << iter->first[2] << \"\\n\";\r\n    }\r\n};\r\n\r\ntypedef mpl::vector<\r\n    euler< state_type > ,\r\n    runge_kutta4< state_type > ,\r\n    runge_kutta_cash_karp54< state_type > ,\r\n    runge_kutta_dopri5< state_type > ,\r\n    runge_kutta_fehlberg78< state_type > ,\r\n    bulirsch_stoer< state_type >\r\n    > steppers;\r\n\r\n\r\nBOOST_AUTO_TEST_SUITE( regression_147_test )\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( regression_147_test , Stepper, \r\n                               steppers )\r\n{\r\n    perform_test< Stepper > tester;\r\n    tester();\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "8189ebc06a5c14b96fd6f1149f903a370b2d9441", "size": 2087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/test/regression/regression_149.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/numeric/odeint/test/regression/regression_149.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/numeric/odeint/test/regression/regression_149.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": 24.5529411765, "max_line_length": 73, "alphanum_fraction": 0.6425491136, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5199205335288762}}
{"text": "#ifndef CANNON_CONTROL_PID_H\n#define CANNON_CONTROL_PID_H \n\n/*!\n * \\file cannon/control/pid.hpp\n * \\brief File containing PidController class definition.\n */\n\n#include <Eigen/Dense>\n\n#include <cannon/utils/class_forward.hpp>\n\nusing namespace Eigen;\n\nnamespace cannon {\n\n  namespace geom {\n    CANNON_CLASS_FORWARD(Trajectory);\n    CANNON_CLASS_FORWARD(ControlledTrajectory);  \n  }\n\n  using namespace cannon::geom;\n\n  namespace control {\n\n    /*!\n     * \\brief Class representing a PID controller around a reference.\n     */\n    class PidController {\n      public:\n\n        /*!\n         * \\brief Constructor taking the state and control dimensionality of\n         * the system to be controlled, as well as sampling time for\n         * digital control.\n         */\n        PidController(unsigned int state_dim = 1, unsigned int control_dim = 1,\n                      double timestep = 0.01);\n\n        /*!\n         * \\brief Get PID control for the input state. Also affects integral\n         * and derivative estimation.\n         *\n         * \\param state The state to compute PID control for. Note that this is\n         * in the global frame, not the error frame.\n         *\n         * \\returns The computed PID control.\n         */\n        VectorXd get_control(const Ref<const VectorXd>& state);\n\n        /*!\n         * \\brief Reset the internal derivative and integral estimation of this\n         * PID controller.\n         */\n        void reset();\n\n        /*!\n         * \\brief Get a modifiable reference to the reference set for this PID\n         * controller. The dimension of this vector should not be changed.\n         *\n         * \\returns Reference to the reference vector.\n         */\n        Ref<VectorXd> ref() {\n          return ref_;\n        }\n\n        /*!\n         * \\brief Get a modifiable reference to the proportional gain matrix\n         * for this PID controller. Matrix dimensions shouldn't be changed.\n         *\n         * \\returns Modifiable reference to proportional gain matrix.\n         */\n        Ref<MatrixXd> proportional_gain() {\n          return Kp_;\n        }\n\n        /*!\n         * \\brief Get a modifiable reference to the integral gain matrix\n         * for this PID controller. Matrix dimensions shouldn't be changed.\n         *\n         * \\returns Modifiable reference to integral gain matrix.\n         */\n        Ref<MatrixXd> integral_gain() {\n          return Ki_;\n        }\n\n        /*!\n         * \\brief Get a modifiable reference to the derivative gain matrix\n         * for this PID controller. Matrix dimensions shouldn't be changed.\n         *\n         * \\returns Modifiable reference to derivative gain matrix.\n         */\n        Ref<MatrixXd> derivative_gain() {\n          return Kd_;\n        }\n\n      private:\n        unsigned int state_dim_; //!< State dimension of system to be controlled\n        unsigned int control_dim_; //!< Control dimension of system to be controlled\n        double time_step_; //!< Control sampling timestep\n\n        VectorXd ref_; //!< Current reference\n        VectorXd penultimate_error_state_; //!< Second-to-last observed error state\n        VectorXd last_error_state_; //!< Last observed error state, used for discrete derivative\n        VectorXd last_control_; //!< Previous computed control\n\n        MatrixXd Kp_; //!< Proportional term gain matrix\n        MatrixXd Ki_; //!< Integral term gain matrix\n        MatrixXd Kd_; //!< Derivative term gain matrix\n\n    };\n\n    /*!\n     * \\brief Construct a controlled trajectory tracking the input geometric\n     * path using the input PID controller and the input model.\n     *\n     * \\param system Dynamic system simulator to compute controlled trajectory in. Note that there are no checks on the dimensions of the arguments to this system, so watch for dimension errors.\n     * \\param traj Geometric trajectory to track.\n     * \\param controller PID controller to track trajectory with.\n     * \\param controlled_dims Number of state dimensions to feed to PID controller.\n     * \\param total_dims Total number of state dimensions\n     * \\param timestep Integration timestep of the input system.\n     *\n     * \\returns The generated controlled trajectory in the input simulator.\n     */\n    ControlledTrajectory get_pid_controlled_trajectory(\n        std::function<VectorXd(const Ref<const VectorXd> &,\n                               const Ref<const VectorXd> &)>\n            system,\n        const Trajectory &traj, PidController &controller,\n        unsigned int controlled_dims, unsigned int total_dims,\n        double timestep = 0.01);\n  }\n}\n\n#endif /* ifndef CANNON_CONTROL_PID_H */\n", "meta": {"hexsha": "d7e9c308d2176965b7ebd30fb7dab195fd183d55", "size": 4615, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/control/pid.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/control/pid.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/control/pid.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.6861313869, "max_line_length": 194, "alphanum_fraction": 0.6348862405, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5199205335288761}}
{"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_ROUND_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ROUND_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing round capabilities\n\n    round(x,n) rounds aways from 0 to n digits:\n\n    @par semantic:\n    For any given value @c x of type @c T and integer n :\n\n    @code\n    T r = round(x, n);\n    @endcode\n\n    is equivalent to\n\n    @code\n    T r = round(x*exp10(n)*exp10(-n));\n    @endcode\n\n    @par Note:\n\n    - n > 0: round to n digits to the right of the decimal point.\n\n    - n = 0: round to the nearest integer.\n\n    - n < 0: round to n digits to the left of the decimal point.\n\n    aways from 0 means that half integer values are rounded to the nearest\n    integer of greatest absolute value\n\n  **/\n  const boost::dispatch::functor<tag::round_> round = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/round.hpp>\n#include <boost/simd/function/simd/round.hpp>\n\n#endif\n", "meta": {"hexsha": "6800f9bc69b36b84033ef5ee83afcaba92882d97", "size": 1415, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/round.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/round.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/round.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": 23.9830508475, "max_line_length": 100, "alphanum_fraction": 0.5908127208, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5199028468467388}}
{"text": "//\n// Created by Zhongshi Jiang on 5/8/17.\n//\n\n#include <igl/copyleft/tetgen/tetrahedralize.h>\n#include <Eigen/Core>\n#include <igl/opengl/glfw/Viewer.h>\n#include <igl/triangle/triangulate.h>\n#include <igl/cat.h>\n#include <igl/writeOBJ.h>\n#include <igl/readOBJ.h>\n#include <igl/writeMESH.h>\n#include <igl/readMESH.h>\n#include <igl/barycenter.h>\n#include <igl/read_triangle_mesh.h>\n#include <iostream>\n#include <igl/Timer.h>\n#include <fstream>\n#include <igl/boundary_loop.h>\n#include <igl/harmonic.h>\n#include <igl/map_vertices_to_circle.h>\n#include <igl/doublearea.h>\n#include <igl/PI.h>\n#include <igl/flipped_triangles.h>\n#include <igl/file_dialog_open.h>\n\nvoid parameterization_init(std::string filename, Eigen::MatrixXd& V_ref,\n                           Eigen::MatrixXi &F_ref,\n                           Eigen::MatrixXd& V_all, Eigen::MatrixXi &F_scaf,\n  Eigen::VectorXi &frame_id, Eigen::MatrixXi& display_F) {\n  using namespace std;\n  using namespace Eigen;\n  while (!igl::read_triangle_mesh(filename, V_ref,\n                                  F_ref)) {\n    std::cerr << \"Cannot Open Mesh!\" << std::endl;\n    filename = igl::file_dialog_open();\n  }\n\n  Eigen::MatrixXd uv_init;\n  Eigen::VectorXi bnd;\n  Eigen::MatrixXd bnd_uv;\n  igl::Timer timer;\n  timer.start();\n  igl::boundary_loop(F_ref, bnd);\n  cout << \"bndloop = \" << timer.getElapsedTime() << endl;\n  timer.start();\n\n\n  timer.start();\n  VectorXd M;\n  igl::doublearea(V_ref, F_ref, M);\n std::cout<<\"sqrtM/2pi\"<< sqrt(M.sum()/(2*igl::PI))<<std::endl;\n//  M /= M.sum()/igl::PI;\n\n  igl::map_vertices_to_circle(V_ref, bnd, bnd_uv);\n  V_ref *= 2;\n  bnd_uv *= sqrt(M.sum()/(2*igl::PI));\n  cout << \"v2circle = \" << timer.getElapsedTime() << endl;\n  igl::harmonic(V_ref, F_ref, bnd, bnd_uv, 1, uv_init);\n  if (igl::flipped_triangles(uv_init, F_ref).size() != 0) {\n    igl::harmonic(F_ref, bnd, bnd_uv, 1, uv_init); // use uniform laplacian\n  }\n  cout << \"Harmonic = \" << timer.getElapsedTime() << endl;\n\n//  scaffold_generator(uv_init, F_ref, scaf_data.density, Vall, Fscaf);\n\n  MatrixXd V_bnd;\n  V_bnd.resize(bnd.size(), uv_init.cols());\n  for (int i = 0; i < bnd.size(); i++) // redoing step 1.\n  {\n    V_bnd.row(i) = uv_init.row(bnd(i));\n  }\n  Matrix2d ob;// = rect_corners;\n  {\n    VectorXd uv_max = uv_init.colwise().maxCoeff();\n    VectorXd uv_min = uv_init.colwise().minCoeff();\n    VectorXd uv_mid = (uv_max + uv_min) / 2.;\n\n    double scaf_range = 8;\n    ob.row(0) = uv_mid + scaf_range * (uv_min - uv_mid);\n    ob.row(1) = uv_mid + scaf_range * (uv_max - uv_mid);\n  }\n  Vector2d rect_len;\n  rect_len << ob(1, 0) - ob(0, 0), ob(1, 1) - ob(0, 1);\n\n  int frame_points = 5;\n  MatrixXd V_rect;\n  V_rect.resize(4 * frame_points, 2);\n  for (int i = 0; i < frame_points; i++) {\n    // 0,0;0,1\n    V_rect.row(i) << ob(0, 0), ob(0, 1) + i * rect_len(1) / frame_points;\n    // 0,0;1,1\n    V_rect.row(i + frame_points)\n        << ob(0, 0) + i * rect_len(0) / frame_points, ob(1, 1);\n    // 1,0;1,1\n    V_rect.row(i + 2 * frame_points) << ob(1, 0), ob(1, 1) - i * rect_len(1) /\n        frame_points;\n    // 1,0;0,1\n    V_rect.row(i + 3 * frame_points)\n        << ob(1, 0) - i * rect_len(0) / frame_points, ob(0, 1);\n    // 0,0;0,1\n  }\n\n  // Concatenate Vert and Edge\n  MatrixXd V;\n  MatrixXi E;\n  igl::cat(1, V_bnd, V_rect, V);\n  E.resize(V.rows(), 2);\n  for (int i = 0; i < E.rows(); i++)\n    E.row(i) << i, i + 1;\n  E(bnd.size() - 1, 1) = 0;\n  E(V.rows() - 1, 1) = static_cast<int>(bnd.size());\n\n  MatrixXd H = MatrixXd::Zero(10, 2);\n  for (int f = 0; f < H.rows(); f++)\n    for (int i = 0; i < 3; i++)\n      H.row(f) += uv_init.row(F_ref(f, i)); // redoing step 2\n  H /= 3.;\n  timer.start();\n  MatrixXd uv2;\n  igl::triangle::triangulate(V, E, H, \"qYYQ\", uv2, F_scaf);\n\n  auto bnd_n = bnd.size();\n  V_all.resize(uv_init.rows() - bnd_n + uv2.rows(), 2);\n  V_all.topRows(uv_init.rows()) = uv_init;\n  V_all.bottomRows(uv2.rows() - bnd_n) = uv2.bottomRows(-bnd_n + uv2.rows());\n\n  for (auto i = 0; i < F_scaf.rows(); i++)\n    for (auto j = 0; j < F_scaf.cols(); j++) {\n      auto &x = F_scaf(i, j);\n      if (x < bnd_n) x = bnd(x);\n      else x += uv_init.rows() - bnd_n;\n    }\n\n  cout << \"New Cat = \" << timer.getElapsedTime() << endl;\n\n  frame_id = Eigen::VectorXi::LinSpaced(\n      V_rect.rows(), V_ref.rows(), V_ref.rows() + V_rect.rows() - 1);\n  igl::cat(1, F_ref, F_scaf, display_F);\n}\n", "meta": {"hexsha": "aa75d47a55dcae2f3111f7c2958b5c05f17003fb", "size": 4339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/demo/parameterization_init.cpp", "max_stars_repo_name": "squarefk/Scaffold-Map", "max_stars_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2018-04-04T19:50:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T00:56:10.000Z", "max_issues_repo_path": "src/demo/parameterization_init.cpp", "max_issues_repo_name": "squarefk/Scaffold-Map", "max_issues_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-04-27T05:01:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-21T19:07:28.000Z", "max_forks_repo_path": "src/demo/parameterization_init.cpp", "max_forks_repo_name": "squarefk/Scaffold-Map", "max_forks_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-04-05T10:50:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T14:26:09.000Z", "avg_line_length": 30.7730496454, "max_line_length": 78, "alphanum_fraction": 0.6001382807, "num_tokens": 1533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5199028468467387}}
{"text": "/*\n * Waypoint controller\n * Given a list of 3D points, the controller generate altitude commands\n * and send it over to crazyflie using crazyflie_ros package. \n *\n * Topics:\n *   Sub:\n *     /vrpn_client_node/body1/Pose\t\tgeometry_msgs::PoseStamped  Current position\n *     \"~/target_position\t\t\t\tgeometry_msgs::Pose         Target position\n *     \"~/state\t\t\t\t\t\t\tstd_msgs::UInt8             See controller.hpp\n * \n *   Pub:\n *     /crazyflie/cmd_vel\t\t\t\tgeometry_msgs::Twist        Altitude commands\n *\n *   By Jason Chan\n *   Aug 18, 2017\n *\n */\n \n#include <ros/ros.h>\n#include <ros/console.h>\n\n#include \"std_msgs/UInt8.h\"\n#include \"std_msgs/MultiArrayLayout.h\"\n#include \"std_msgs/Float64MultiArray.h\"\n#include \"geometry_msgs/Twist.h\"\n#include \"geometry_msgs/Pose.h\"\n#include \"geometry_msgs/PoseStamped.h\"\n\n#include <cmath>\n#include <Eigen/Dense>\n#include \"Controller.hpp\"\n#include \"AdaptiveController.hpp\"\n\nusing namespace Eigen;\n\n// command parameters\n#define POSITION_LOOP_RATE\t200.0\n#define POSITION_LOOP_DT\t(double)(1.0/POSITION_LOOP_RATE)\n\n////////////////////////////////////////////////////////\n// * Adaptive controller related settings\n////////////////////////////////////////////////////////\n#define USE_ADAPTIVE_CONTROLLER \n#define USE_RBF\n////////////////////////////////////////////////////////\n\n\n////////////////////////////////////////////////////////\n// * Phi function, used in AdaptiveController Class\n////////////////////////////////////////////////////////\n#ifndef USE_RBF\n    void phi_functions(VectorXd &phi, const VectorXd states)\n    {\n        double z = states(0);\n        phi = VectorXd::Zero(2);\n        phi(0) = z;\n        phi(1) = 1;\n    }\n#else\n    const double rbf_center[] = {-0.0, -0.2, -0.4, -0.6, -0.8, -1.0};\n    //const double rbf_center[] = {-0.0, -0.4, -0.8};\n    const double rbf_width = 0.6;\n\tconst int nrbf = sizeof(rbf_center)/sizeof(double) + 1;\n\n    inline double rbf(double x, double center, double base_width)\n    {\n      \treturn exp(-pow((x-center)/(base_width/4), 2));\n    }\n\n    void phi_functions(VectorXd &phi, const VectorXd states)\n    {\n        double z = states(0);\n        \n        phi = VectorXd::Zero(nrbf);\n        for (int i=0; i<(nrbf-1); i++)\n        {\n            phi(i) = rbf(z, rbf_center[i], rbf_width);\n        \t//ROS_INFO(\"%d, %.4f, %.4f, %.4f, %.4f\", i, phi(i), z, rbf_center[i], rbf_width);\n        }\n        phi(nrbf-1) = 1;\n\n    }\n#endif\n\n////////////////////////////////////////////////////////\n\n\n\n////////////////////////////////////////////////////////\n// * Global Variabls\n////////////////////////////////////////////////////////\nstatic ros::Publisher pub_command;\n#ifdef USE_ADAPTIVE_CONTROLLER\n\tstatic AdaptiveController hover_controller(phi_functions);\n\tstatic ros::Publisher pub_ref_states;\n\tstatic ros::Publisher pub_adp_gains;\n#else\n\tstatic Controller hover_controller;\n#endif\nstatic uint8_t last_state = 0;\n////////////////////////////////////////////////////////\n\n\n\n////////////////////////////////////////////////////////\n// * Callback functions\n////////////////////////////////////////////////////////\nvoid sub_flight_state_callback(const std_msgs::UInt8::ConstPtr& _state) {\n\tuint8_t new_state = _state->data;\n\tif(last_state != new_state)\n\t{\n\t\tswitch (new_state) {\n\t\t\tcase 0:\n\t\t\t\thover_controller.switch_to_standby();\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\thover_controller.switch_to_tracking();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\thover_controller.switch_to_emergency();\n\t\t}\n\t\tlast_state = _state->data;\n\t}\n}\n\n#ifdef USE_ADAPTIVE_CONTROLLER\nvoid pub_ref_states_callback(const ros::TimerEvent& e) {\n\tgeometry_msgs::PoseStamped pose;\n\n\tVectorXd states;\n\thover_controller.get_reference_states(states);\n\n\tpose.header.stamp = ros::Time::now();\n\tpose.pose.position.x = 0.0;\n\tpose.pose.position.y = 0.0;\n\tpose.pose.position.z = states(0);\n\tpose.pose.orientation.x = 0.0;\n\tpose.pose.orientation.y = 0.0;\n\tpose.pose.orientation.z = 0.0;\n\tpose.pose.orientation.w = 0.0;\n\n\tpub_ref_states.publish(pose);\n}\n\n\nvoid pub_adp_gains_callback(const ros::TimerEvent& e) {\n\tstd_msgs::Float64MultiArray msg_gains;\n\n\tMatrixXd m_gains;\n\thover_controller.get_adaptive_gains(m_gains);\n\n\tconst int m = m_gains.rows();\n\tconst int n = m_gains.cols();\n\tfor (int i=0;i<m;i++)\n\t{\n\t\tfor (int j=0;j<n;j++)\n\t\t{\n\t\t\tmsg_gains.data.push_back(m_gains(i, j));\n\t\t}\n\t}\n\n\tpub_adp_gains.publish(msg_gains);\n}\n#endif\n\nvoid pub_cmd_callback(const ros::TimerEvent& e) {\n\tgeometry_msgs::Twist cmd_vel;\n\n\thover_controller.compute_outputs(&cmd_vel);\n\tpub_command.publish(cmd_vel);\n}\n////////////////////////////////////////////////////////\n\n\n\n////////////////////////////////////////////////////////\n// * Main\n////////////////////////////////////////////////////////\nint main(int argc, char **argv) {\n\tros::init(argc, argv, \"hover_controller\");\n\tros::NodeHandle n(\"~\");\n\n\tPID_Config_t config_x;\n\tPID_Config_t config_y;\n\tPID_Config_t config_z;\n\n\tReferenceModel_Config_t config_model_z;\n\tAdaptiveLaw_Config_t config_law_z;\n\n\t// MatLab + tuned\n\t//n.param(\"Kpx\", config_x.Kp,  -0.259246154*1.5);\n\t//n.param(\"Kix\", config_x.Ki,  -0.049913621*1.5);\n\t//n.param(\"Kdx\", config_x.Kd,  -0.336624385*1.5);\n\t//n.param(\"Kpy\", config_y.Kp,  -0.259246154*1.5);\n\t//n.param(\"Kiy\", config_y.Ki,  -0.049913621*1.5);\n\t//n.param(\"Kdy\", config_y.Kd,  -0.336624385*1.5);\n\t//n.param(\"Kpz\", config_z.Kp,  42692.24448);\n\t//n.param(\"Kiz\", config_z.Ki,  8219.695803);\n\t//n.param(\"Kdz\", config_z.Kd,  55434.76858);\n\n\t// MatLab\n\tn.param(\"Kpx\", config_x.Kp,  -0.259246154*1.5);\n\tn.param(\"Kix\", config_x.Ki,  -0.049913621*1.5);\n\tn.param(\"Kdx\", config_x.Kd,  -0.336624385*1.5);\n\tn.param(\"Kpy\", config_y.Kp,  -0.259246154*1.5);\n\tn.param(\"Kiy\", config_y.Ki,  -0.049913621*1.5);\n\tn.param(\"Kdy\", config_y.Kd,  -0.336624385*1.5);\n\tn.param(\"Kpz\", config_z.Kp,  42692.24448);\n\tn.param(\"Kiz\", config_z.Ki,  8219.695803);\n\tn.param(\"Kdz\", config_z.Kd,  55434.76858);\n\n\tconfig_x.dt \t\t= POSITION_LOOP_DT;\n\tconfig_x.threshold\t= 1.0e-4;\n\tconfig_x.max_output\t= 4.0e4;\n\tconfig_y.dt \t\t= POSITION_LOOP_DT;\n\tconfig_y.threshold\t= 1.0e-4;\n\tconfig_y.max_output\t= 4.0e4;\n\tconfig_z.dt \t\t= POSITION_LOOP_DT;\n\tconfig_z.threshold\t= 1.0e-4;\n\tconfig_z.max_output\t= 4.0e4;\n    \n    // Reference model\n\tconfig_model_z.A\t\t= MatrixXd::Zero(2,2);\n    config_model_z.B\t\t= MatrixXd::Zero(2,1);\n\tconfig_model_z.states0\t= VectorXd::Zero(2);\n\tconfig_model_z.dt\t\t= POSITION_LOOP_DT;\n    config_model_z.A(0,0)\t=  0.0;\n    config_model_z.A(0,1)\t=  1.0;\n    config_model_z.A(1,0)\t= -5.416;\n    config_model_z.A(1,1)\t= -7.027;\n    config_model_z.B(0,0)\t= -0.1145;\n    config_model_z.B(1,0)\t=  6.273;\n\tconfig_model_z.states0(0) = -0.03; // ground is not at zero\n    \n    // Adaptive Law\n#ifndef USE_RBF\n\tconfig_law_z.Gamma\t= 6.0e-4*MatrixXd::Identity(2,2);\n#else\n\tconfig_law_z.Gamma\t= 6.0e-4*MatrixXd::Identity(nrbf,nrbf);\n#endif\n\tconfig_law_z.P\t\t= MatrixXd::Zero(2,2);\n\tconfig_law_z.B\t\t= MatrixXd::Zero(2,1);\n\tconfig_law_z.dt\t\t= POSITION_LOOP_DT;\n    config_law_z.P(0,0) = 72.373382399897039;\n    config_law_z.P(0,1) =  9.231905465288030;\n    config_law_z.P(1,0) =  9.231905465288030;\n    config_law_z.P(1,1) =  1.384930335176893;\n    config_law_z.B(0,0) =  0.0;\n    config_law_z.B(1,0) = 26.232948583420782;\n\t\n#ifdef USE_ADAPTIVE_CONTROLLER\n    hover_controller.initialize(config_x, config_y, config_z,\n\t\t\t\t\t\t\t\tconfig_model_z, config_law_z, \n\t\t\t\t\t\t\t\tPOSITION_LOOP_DT);\n#else\n\thover_controller.initialize(config_x, config_y, config_z);\n#endif\n    \n    ros::Subscriber sub_position = n.subscribe<geometry_msgs::PoseStamped>(\n        \"current_pose\", 1, &Controller::update_position, (Controller*) &hover_controller);\n    ros::Subscriber sub_target = n.subscribe<geometry_msgs::Pose>(\n        \"target_pose\", 1, &Controller::update_target, (Controller*) &hover_controller);\n\tros::Subscriber sub_flight_state = n.subscribe<std_msgs::UInt8>(\n        \"state\", 1, sub_flight_state_callback);\n\n\tpub_command = n.advertise<geometry_msgs::Twist>(\"/crazyflie/cmd_vel\", 1);\n\tros::Timer timer_pub_cmd = n.createTimer(\n        ros::Duration(POSITION_LOOP_DT), pub_cmd_callback);\n#ifdef USE_ADAPTIVE_CONTROLLER\n\tpub_ref_states = n.advertise<geometry_msgs::PoseStamped>(\"reference_states\", 1);\n\tros::Timer timer_pub_ref_states = n.createTimer(\n        ros::Duration(POSITION_LOOP_DT), pub_ref_states_callback);\n\n\tpub_adp_gains = n.advertise<std_msgs::Float64MultiArray>(\"adaptive_gains\", 1);\n\tros::Timer timer_pub_adp_gains = n.createTimer(\n        ros::Duration(POSITION_LOOP_DT), pub_adp_gains_callback);\n#endif\n\t\n\tros::spin();\n\n\treturn 0;\n}\n////////////////////////////////////////////////////////\n", "meta": {"hexsha": "2420d683566ab01e2b73ddf6048d2f1a083ed66e", "size": 8520, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "crazyflie_mrac_hover_controller/src/main.cpp", "max_stars_repo_name": "fjctp/crazyflie_mrac_ros", "max_stars_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-09T03:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T06:00:12.000Z", "max_issues_repo_path": "crazyflie_mrac_hover_controller/src/main.cpp", "max_issues_repo_name": "fjctp/crazyflie_mrac_ros", "max_issues_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crazyflie_mrac_hover_controller/src/main.cpp", "max_forks_repo_name": "fjctp/crazyflie_mrac_ros", "max_forks_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-24T22:48:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-24T22:48:29.000Z", "avg_line_length": 29.8947368421, "max_line_length": 90, "alphanum_fraction": 0.617370892, "num_tokens": 2476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5199028459948414}}
{"text": "/* ===-- fixdfti.c - Implement __fixdfti -----------------------------------===\n *\n *                     The LLVM Compiler Infrastructure\n *\n * This file is dual licensed under the MIT and the University of Illinois Open\n * Source Licenses. See LICENSE.TXT for details.\n *\n * ===----------------------------------------------------------------------===\n */\n\n#include \"fp64.h\"\n\n#ifdef _MSC_VER\n#include <boost/multiprecision/cpp_int.hpp>\ntypedef boost::multiprecision::int128_t fixint_t;\ntypedef boost::multiprecision::uint128_t fixuint_t;\n#else\ntypedef __int128 fixint_t;\ntypedef unsigned __int128 fixuint_t;\n#endif\n\nfixint_t ___fixdfti(uint64_t a) {\n    const fixint_t fixint_max = (fixint_t)((~(fixuint_t)0) / 2);\n    const fixint_t fixint_min = -fixint_max - 1;\n    // Break a into sign, exponent, significand\n    const rep_t aRep = a;\n    const rep_t aAbs = aRep & absMask;\n    const fixint_t sign = aRep & signBit ? -1 : 1;\n    const int exponent = (aAbs >> significandBits) - exponentBias;\n    const rep_t significand = (aAbs & significandMask) | implicitBit;\n\n    // If exponent is negative, the result is zero.\n    if (exponent < 0)\n        return 0;\n\n    // If the value is too large for the integer type, saturate.\n    if ((unsigned)exponent >= sizeof(fixint_t) * CHAR_BIT)\n        return sign == 1 ? fixint_max : fixint_min;\n\n    // If 0 <= exponent < significandBits, right shift to get the result.\n    // Otherwise, shift left.\n    if (exponent < significandBits)\n        return sign * (significand >> (significandBits - exponent));\n    else\n        return sign * ((fixint_t)significand << (exponent - significandBits));\n\n}\n", "meta": {"hexsha": "84780b30fde9115f0694483e77d6356df00a9687", "size": 1638, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libraries/builtins/fixdfti.cc", "max_stars_repo_name": "jxlczjp77/eos", "max_stars_repo_head_hexsha": "75437df5e4b584fc52d8160efe29aff30b656ff6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/builtins/fixdfti.cc", "max_issues_repo_name": "jxlczjp77/eos", "max_issues_repo_head_hexsha": "75437df5e4b584fc52d8160efe29aff30b656ff6", "max_issues_repo_licenses": ["MIT"], "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/builtins/fixdfti.cc", "max_forks_repo_name": "jxlczjp77/eos", "max_forks_repo_head_hexsha": "75437df5e4b584fc52d8160efe29aff30b656ff6", "max_forks_repo_licenses": ["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.125, "max_line_length": 79, "alphanum_fraction": 0.63003663, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5199028405928249}}
{"text": "\n#include \"proseco_planning/action/noiseGenerator.h\"\n\n#include <boost/math/policies/policy.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <memory>\n\n#include \"proseco_planning/action/action.h\"\n#include \"proseco_planning/config/computeOptions.h\"\n#include \"proseco_planning/config/configuration.h\"\n#include \"proseco_planning/math/mathlib.h\"\n\nnamespace proseco_planning {\n\n/**\n * @brief Constructs a new Noise Generator object\n *\n */\nNoiseGenerator::NoiseGenerator() {\n  m_distributionY =\n      std::normal_distribution<float>(cOpt().action_noise.meanY, cOpt().action_noise.sigmaY);\n  m_distributionVx =\n      std::normal_distribution<float>(cOpt().action_noise.meanVx, cOpt().action_noise.sigmaVx);\n  m_normalDensityY  = boost::math::normal_distribution<float>(cOpt().action_noise.meanY,\n                                                             cOpt().action_noise.sigmaY);\n  m_normalDensityVx = boost::math::normal_distribution<float>(cOpt().action_noise.meanVx,\n                                                              cOpt().action_noise.sigmaVx);\n}\n\n/**\n * @brief Creates a noisy action using the noise parameters for the Gaussian distribution from the\n * configuration.\n *\n * @param action The action which is to become noisy.\n * @return ActionPtr The action with noise.\n */\nActionPtr NoiseGenerator::createNoisyAction(const ActionPtr& action) {\n  float epsilonY{m_distributionY(math::Random::engine())};\n  float epsilonVx{m_distributionVx(math::Random::engine())};\n  float likelihoodY{boost::math::pdf(m_normalDensityY, epsilonY)};\n  float likelihoodVx{boost::math::pdf(m_normalDensityVx, epsilonVx)};\n\n  auto noisyAction = std::make_shared<Action>(action->m_velocityChange + epsilonVx,\n                                              action->m_lateralChange + epsilonY);\n\n  noisyAction->noise.m_likelihoodY   = likelihoodY;\n  noisyAction->noise.m_likelihoodVx  = likelihoodVx;\n  noisyAction->noise.m_muY           = action->m_lateralChange;\n  noisyAction->noise.m_muVx          = action->m_velocityChange;\n  noisyAction->noise.m_sigmaY        = cOpt().action_noise.sigmaY;\n  noisyAction->noise.m_sigmaVx       = cOpt().action_noise.sigmaVx;\n  noisyAction->m_selectionLikelihood = action->m_selectionLikelihood;\n  return noisyAction;\n}\n\n/**\n * @brief Create noisy versions of all actions of the action set using the noise generator.\n *\n * @param actionSet The action set which is to become noisy.\n * @return ActionSet The action set with noise.\n */\nActionSet NoiseGenerator::createNoisyActions(const ActionSet& actionSet) {\n  ActionSet noisyActionSet;\n  for (const auto& action : actionSet) {\n    noisyActionSet.push_back(createNoisyAction(action));\n  }\n  return noisyActionSet;\n}\n}  // namespace proseco_planning", "meta": {"hexsha": "354d11a48820c14ad24896f46cf290eafd77991b", "size": 2745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/proseco_planning/action/noiseGenerator.cpp", "max_stars_repo_name": "ProSeCo-Planning/proseco_planning", "max_stars_repo_head_hexsha": "c9a8d65c5f24e59e170e8de271e769ca65b9b10d", "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/proseco_planning/action/noiseGenerator.cpp", "max_issues_repo_name": "ProSeCo-Planning/proseco_planning", "max_issues_repo_head_hexsha": "c9a8d65c5f24e59e170e8de271e769ca65b9b10d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/proseco_planning/action/noiseGenerator.cpp", "max_forks_repo_name": "ProSeCo-Planning/proseco_planning", "max_forks_repo_head_hexsha": "c9a8d65c5f24e59e170e8de271e769ca65b9b10d", "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.7826086957, "max_line_length": 98, "alphanum_fraction": 0.7143897996, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5199028343389107}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2020 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 \"delaunay_complex\"\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <CGAL/Epick_d.h>\n#include <CGAL/Epeck_d.h>\n\n#include <vector>\n#include <limits>  // NaN\n#include <cmath>\n\n#include <gudhi/Alpha_complex.h>\n// to construct a simplex_tree from Delaunay_triangulation\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Unitary_tests_utils.h>\n#include <gudhi/random_point_generators.h>\n\n// Use dynamic_dimension_tag for the user to be able to set dimension\ntypedef CGAL::Epeck_d< CGAL::Dynamic_dimension_tag > Exact_kernel_d;\n// Use static dimension_tag for the user not to be able to set dimension\ntypedef CGAL::Epeck_d< CGAL::Dimension_tag<5> > Exact_kernel_s;\n// Use dynamic_dimension_tag for the user to be able to set dimension\ntypedef CGAL::Epick_d< CGAL::Dynamic_dimension_tag > Inexact_kernel_d;\n// Use static dimension_tag for the user not to be able to set dimension\ntypedef CGAL::Epick_d< CGAL::Dimension_tag<5> > Inexact_kernel_s;\n// The triangulation uses the default instantiation of the TriangulationDataStructure template parameter\n\ntypedef boost::mpl::list<Exact_kernel_d, Exact_kernel_s, Inexact_kernel_d, Inexact_kernel_s> list_of_kernel_variants;\n\nusing Simplex_tree = Gudhi::Simplex_tree<>;\nusing Simplex_handle = Simplex_tree::Simplex_handle;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_from_OFF_file, TestedKernel, list_of_kernel_variants) {\n  std::cout << \"*****************************************************************************************************\";\n  using Point = typename TestedKernel::Point_d;\n  std::vector<Point> points;\n  // 50 points on a 4-sphere\n  points = Gudhi::generate_points_on_sphere_d<TestedKernel>(10, 5, 1.);\n\n  Gudhi::alpha_complex::Alpha_complex<TestedKernel> alpha_complex(points);\n\n  // Alpha complex\n  Simplex_tree stree_from_alpha_complex;\n  BOOST_CHECK(alpha_complex.create_complex(stree_from_alpha_complex));\n\n  // Delaunay complex\n  Simplex_tree stree_from_delaunay_complex;\n  BOOST_CHECK(alpha_complex.create_complex(stree_from_delaunay_complex, 0., false, true));\n\n  // Check all the simplices from alpha complex are in the Delaunay complex\n  for (auto f_simplex : stree_from_alpha_complex.complex_simplex_range()) {\n    Simplex_handle sh = stree_from_delaunay_complex.find(stree_from_alpha_complex.simplex_vertex_range(f_simplex));\n    BOOST_CHECK(std::isnan(stree_from_delaunay_complex.filtration(sh)));\n    BOOST_CHECK(sh != stree_from_delaunay_complex.null_simplex());\n  }\n}\n", "meta": {"hexsha": "c1cc1fabc9eef07ebd0cfe1ebfaf13866e91a74e", "size": 2921, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Alpha_complex/test/Delaunay_complex_unit_test.cpp", "max_stars_repo_name": "m0baxter/gudhi-devel", "max_stars_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "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/Alpha_complex/test/Delaunay_complex_unit_test.cpp", "max_issues_repo_name": "m0baxter/gudhi-devel", "max_issues_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "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/Alpha_complex/test/Delaunay_complex_unit_test.cpp", "max_forks_repo_name": "m0baxter/gudhi-devel", "max_forks_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "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.3333333333, "max_line_length": 119, "alphanum_fraction": 0.7548784663, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5199028343389106}}
{"text": "/*\nCopyright (c) 2014, Aaron S Wishnick\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, 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 Aaron S Wishnick, iZotope, Inc., 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\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (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#include <iostream>\n#include <cmath>\n#include <array>\n#include <vector>\n#include <iomanip>\n#include <string>\n#include <complex>\n#include <functional>\n#include <map>\n#include <random>\n#include <Eigen/Dense>\n#include <memory>\n#include \"sndfile.h\"\nusing namespace std;\nusing namespace Eigen;\n\nstatic array<double, 5> lowpass_coefficients(double w0, double q) {\n  array<double, 5> coeffs;\n\n  const double cosw0 = cos(w0);\n  const double alpha = sin(w0) / (2 * q);\n\n  const double a0 = 1 + alpha;\n\n  coeffs[0] = 0.5 * (1 - cosw0);\n  coeffs[1] = 1 - cosw0;\n  coeffs[2] = 0.5 * (1 - cosw0);\n  coeffs[3] = -2 * cosw0;\n  coeffs[4] = 1 - alpha;\n\n  for (auto& x : coeffs) {\n    x /= a0;\n  }\n\n  return coeffs;\n}\n\nstatic array<double, 5> peaking_coefficients(double w0, double q, double gain) {\n  array<double, 5> coeffs;\n\n  const double A = pow(10.0, gain / 40);\n  const double alpha = sin(w0) / (2 * q);\n\n  coeffs[0] = 1 + alpha * A;\n  coeffs[1] = -2 * cos(w0);\n  coeffs[2] = 1 - alpha * A;\n  double a0 = 1 + alpha / A;\n  coeffs[3] = -2 * cos(w0);\n  coeffs[4] = 1 - alpha / A;\n\n  for (auto& x : coeffs) {\n    x /= a0;\n  }\n\n  return coeffs;\n}\n\nstatic vector<double> generate_sine_wave(int length, double cycles_per_sample) {\n  vector<double> signal(length);\n\n  if (cycles_per_sample == 0) {\n    signal.assign(length, 1.0);\n    return signal;\n  }\n\n  for (int i = 0; i < length; ++i) {\n    signal[i] = sin(2 * M_PI * i * cycles_per_sample);\n  }\n  return signal;\n}\n\n// Smooth a signal with a linear-phase Hann filter.\nstatic vector<double> smooth_hann(const vector<double>& x, int radius) {\n  int n = x.size();\n  int m = 2 * radius + 1;\n\n  vector<double> y(n + m - 1);\n\n  vector<double> h(m);\n  double norm = 0;\n  for (int i = 0; i < m; ++i) {\n    h[i] = 0.5 - 0.5 * cos((i + 0.5) * 2.0 * M_PI / m);\n    norm += h[i];\n  }\n  for (int i = 0; i < m; ++i) {\n    h[i] /= norm;\n  }\n\n  for (int i = 0; i < n + m - 1; ++i) {\n    double sum = 0;\n    for (int j = 0; j < m; ++j) {\n      int idx = radius + i - j;\n      if (idx < 0) {\n        break;\n      }\n      sum += h[j] * x[idx];\n    }\n    y[i] = sum;\n  }\n\n  return y;\n}\n\n// Generate a Hann window.\nstatic vector<double> generate_hann_window(int n) {\n  vector<double> w(n);\n  for (int i = 0; i < n; ++i) {\n    w[i] = 0.5 - 0.5 * cos(2.0 * M_PI * i / (n - 1));\n  }\n  return w;\n}\n\n// Compute the gain of a biquad at frequency w0.\nstatic double biquad_gain(array<double, 5> coeffs, double w0) {\n  const double b0 = coeffs[0], b1 = coeffs[1], b2 = coeffs[2];\n  const double a1 = coeffs[3], a2 = coeffs[4];\n\n  auto z = polar(1.0, w0);\n  auto z2 = z * z;\n\n  auto h = (b0 + b1 / z + b2 / z2) / (1.0 + a1 / z + a2 / z2);\n  return abs(h);\n}\n\n// High-quality reference signal. Assumes that the filter input is a sinusoid.\n// Smooths the gain of the filter coefficients, and applies it to the signal.\nstatic vector<double> reference(vector<double> x,\n                                const vector<array<double, 5>>& coeffs,\n                                double w0, int radius) {\n  const int n = x.size();\n\n  vector<double> gains(n);\n  transform(begin(coeffs), end(coeffs), begin(gains),\n            [w0](array<double, 5> coeffs) { return biquad_gain(coeffs, w0); });\n\n  gains = smooth_hann(gains, radius);\n\n  transform(begin(x), end(x), begin(gains), begin(x),\n            [](double sig, double gain) { return sig * gain; });\n\n  return x;\n}\n\n// Low-quality anchor. Applies the gain to the signal, with no smoothing, and\n// inserts an impulse whenever coefficients change.\nstatic vector<double>\nanchor(vector<double> x, const vector<array<double, 5>>& coeffs, double w0) {\n  const int n = x.size();\n\n  vector<double> gains(n);\n  transform(begin(coeffs), end(coeffs), begin(gains),\n            [w0](array<double, 5> coeffs) { return biquad_gain(coeffs, w0); });\n\n  double max_gain = accumulate(begin(gains), end(gains), 0.0,\n                               [](double a, double b) { return max(a, b); });\n  double transient_gain = 3 * max_gain;\n\n  for (int i = 0; i < n; ++i) {\n    if (i != 0 && gains[i] != gains[i - 1]) {\n      // If there was a change in gain, insert a click.\n      x[i] += transient_gain;\n    } else {\n      x[i] *= gains[i];\n    }\n  }\n\n  return x;\n}\n\n// Vanilla Direct Form II implementation.\nstatic vector<double> time_varying_df2(vector<double> x,\n                                       const vector<array<double, 5>>& coeffs) {\n  double w1 = 0, w2 = 0;\n  const int n = x.size();\n  for (int i = 0; i < n; ++i) {\n    auto cur_coeffs = coeffs[i];\n\n    double w = x[i] - cur_coeffs[3] * w1 - cur_coeffs[4] * w2;\n    double y = cur_coeffs[0] * w + cur_coeffs[1] * w1 + cur_coeffs[2] * w2;\n    x[i] = y;\n\n    w2 = w1;\n    w1 = w;\n  }\n\n  return x;\n}\n\n// Vanilla SVF implementation.\nstatic vector<double> time_varying_svf(vector<double> x,\n                                       const vector<array<double, 5>>& coeffs) {\n  double s1 = 0, s2 = 0;\n  const int n = x.size();\n\n  for (int i = 0; i < n; ++i) {\n    const double b0 = coeffs[i][0], b1 = coeffs[i][1], b2 = coeffs[i][2];\n    const double a1 = coeffs[i][3], a2 = coeffs[i][4];\n\n    const complex<double> neg_sqrt = sqrt(complex<double>(-1 - a1 - a2));\n    const complex<double> pos_sqrt = sqrt(complex<double>(-1 + a1 - a2));\n\n    const double g = (neg_sqrt / pos_sqrt).real();\n    const double R = (a2 - 1) / (neg_sqrt * pos_sqrt).real();\n    const double TwoR = 2 * R;\n    const double g2 = g * g;\n    const double chp = (b0 - b1 + b2) / (1 - a1 + a2);\n    const double cbp = -2 * (b0 - b2) / (neg_sqrt * pos_sqrt).real();\n    const double clp = (b0 + b1 + b2) / (1 + a1 + a2);\n\n    double u1 = (x[i] - (g + TwoR) * s1 - s2) / (1 + g2 + TwoR * g);\n    double u2 = g * u1 + s1;\n    double u3 = g * u2 + s2;\n\n    s1 += 2.0 * g * u1;\n    s2 += 2.0 * g * u2;\n\n    x[i] = chp * u1 + cbp * u2 + clp * u3;\n  }\n\n  return x;\n}\n\n// SVF, with the stabilization method from \"Stability of Recursive Time-Varying\n// Digital Filters by State Vector Transformation.\"\nstatic vector<double>\nsvf_rabenstein_czarnach(vector<double> x,\n                        const vector<array<double, 5>>& coeffs) {\n  Matrix<double, 2, 1> s = Matrix<double, 2, 1>::Zero();\n  const int n = x.size();\n\n  double R_prev;\n\n  for (int i = 0; i < n; ++i) {\n    const double b0 = coeffs[i][0], b1 = coeffs[i][1], b2 = coeffs[i][2];\n    const double a1 = coeffs[i][3], a2 = coeffs[i][4];\n\n    const complex<double> neg_sqrt = sqrt(complex<double>(-1 - a1 - a2));\n    const complex<double> pos_sqrt = sqrt(complex<double>(-1 + a1 - a2));\n\n    const double g = (neg_sqrt / pos_sqrt).real();\n    const double R = (a2 - 1) / (neg_sqrt * pos_sqrt).real();\n    const double g2 = g * g;\n\n    const double chp = (b0 - b1 + b2) / (1 - a1 + a2);\n    const double cbp = -2 * (b0 - b2) / (neg_sqrt * pos_sqrt).real();\n    const double clp = (b0 + b1 + b2) / (1 + a1 + a2);\n\n    Matrix<double, 2, 2> A;\n    A(0, 0) = -2 * R;\n    A(0, 1) = -1;\n    A(1, 0) = 1;\n    A(1, 1) = 0;\n\n    Matrix<double, 2, 1> B;\n    B(0, 0) = 1;\n    B(1, 0) = 0;\n\n    Matrix<double, 2, 2> H =\n        (Matrix<double, 2, 2>::Identity() - g * A).inverse();\n\n    Matrix<double, 2, 2> Pa = Matrix<double, 2, 2>::Identity() + 2 * g * A * H;\n    Matrix<double, 2, 1> Pb = 2 * g2 * A * H * B + 2 * g * B;\n    Matrix<double, 2, 1> Pc;\n    Pc(0, 0) = cbp - 2 * R * chp;\n    Pc(1, 0) = clp - chp;\n    double Pd = chp;\n\n    Matrix<double, 2, 2> TT;\n    double Rn = i != 0 ? R_prev : R;\n    TT(0, 0) = (sqrt(complex<double>(Rn * Rn - 1)) /\n                sqrt(complex<double>(R * R - 1))).real();\n    TT(0, 1) = -(complex<double>(0, 1) * (R - Rn) /\n                 sqrt(complex<double>(R * R - 1))).real();\n    TT(1, 0) = 0;\n    TT(1, 1) = 1;\n\n    s = TT * s;\n\n    // Compute output.\n    double y = Pc.transpose() * s + Pd * x[i];\n\n    // State update\n    s = Pa * s + Pb * x[i];\n\n    R_prev = R;\n\n    x[i] = y;\n  }\n\n  return x;\n}\n\ntemplate <int N>\nstatic Matrix<double, N, N>\nComputeRabensteinK(Matrix<double, N, N> A1, Matrix<double, N, 1> b1,\n                   Matrix<double, N, N> A2, Matrix<double, N, 1> b2) {\n  Matrix<double, N, N> K = b1 * b2.transpose();\n\n  auto Ae1 = A1;\n  auto Ae2 = A2;\n  int i = 0;\n  while (i++ < 1000000 && (Ae1.template lpNorm<Infinity>() > 1e-12 ||\n                           Ae2.template lpNorm<Infinity>() > 1e-12)) {\n    Matrix<double, N, 1> f1 = Ae1 * b1;\n    Matrix<double, N, 1> f2 = Ae2 * b2;\n\n    K += f1 * f2.transpose();\n\n    Ae1 *= A1;\n    Ae2 *= A2;\n  }\n\n  return K;\n}\n\n// Direct Form 2 Transposed\nstatic vector<double> tdf2(vector<double> x,\n                           const vector<array<double, 5>>& coeffs) {\n  const int n = x.size();\n  Matrix<double, 2, 1> s = Matrix<double, 2, 1>::Zero();\n\n  for (int i = 0; i < n; ++i) {\n    const double b0 = coeffs[i][0], b1 = coeffs[i][1], b2 = coeffs[i][2];\n    const double a1 = coeffs[i][3], a2 = coeffs[i][4];\n\n    Matrix<double, 2, 2> A;\n    A << -a1, 1.0, -a2, 0.0;\n\n    Matrix<double, 2, 1> b;\n    b << b1 - b0* a1, b2 - b0* a2;\n\n    Matrix<double, 2, 1> c;\n    c << 1.0, 0.0;\n\n    double d = b2;\n\n    double y = c.transpose() * s + d * x[i];\n    s = A * s + b * x[i];\n\n    x[i] = y;\n  }\n\n  return x;\n}\n\nstatic vector<double>\ntdf2_rabenstein_czarnach(vector<double> x,\n                         const vector<array<double, 5>>& coeffs) {\n  const int n = x.size();\n  Matrix<double, 2, 1> s = Matrix<double, 2, 1>::Zero();\n\n  for (int i = 0; i < n; ++i) {\n    const double b0 = coeffs[i][0], b1 = coeffs[i][1], b2 = coeffs[i][2];\n    const double a1 = coeffs[i][3], a2 = coeffs[i][4];\n\n    Matrix<double, 2, 2> A;\n    A << -a1, 1.0, -a2, 0.0;\n\n    Matrix<double, 2, 1> b;\n    b << b1 - b0* a1, b2 - b0* a2;\n\n    Matrix<double, 2, 1> c;\n    c << 1.0, 0.0;\n\n    double d = b2;\n\n    double r = sqrt(a2);\n    double t = acos(a1 / (-2 * r));\n\n    auto prev_coeffs = i != 0 ? coeffs[i - 1] : coeffs[i];\n    double rp = sqrt(prev_coeffs[4]);\n    double tp = acos(prev_coeffs[3] / (-2 * rp));\n\n    Matrix<double, 2, 2> TT;\n    TT << 1, 0, r* sin(t - tp) / sin(tp), r * sin(t) / (rp * sin(tp));\n    s = TT * s;\n\n    double y = c.transpose() * s + d * x[i];\n    s = A * s + b * x[i];\n\n    x[i] = y;\n  }\n\n  return x;\n}\n\n// SVF, with transient minimization as \"Minimization of Transient Signals in\n// Recursive Time-Varying Digital Filters\".\nstatic vector<double> svf_rabenstein(vector<double> x,\n                                     const vector<array<double, 5>>& coeffs) {\n  Matrix<double, 2, 1> s = Matrix<double, 2, 1>::Zero();\n  const int n = x.size();\n\n  Matrix<double, 2, 2> Pa_prev;\n  Matrix<double, 2, 1> Pb_prev;\n\n  for (int i = 0; i < n; ++i) {\n    const double b0 = coeffs[i][0], b1 = coeffs[i][1], b2 = coeffs[i][2];\n    const double a1 = coeffs[i][3], a2 = coeffs[i][4];\n\n    const complex<double> neg_sqrt = sqrt(complex<double>(-1 - a1 - a2));\n    const complex<double> pos_sqrt = sqrt(complex<double>(-1 + a1 - a2));\n\n    const double g = (neg_sqrt / pos_sqrt).real();\n    const double R = (a2 - 1) / (neg_sqrt * pos_sqrt).real();\n    const double g2 = g * g;\n\n    const double chp = (b0 - b1 + b2) / (1 - a1 + a2);\n    const double cbp = -2 * (b0 - b2) / (neg_sqrt * pos_sqrt).real();\n    const double clp = (b0 + b1 + b2) / (1 + a1 + a2);\n\n    Matrix<double, 2, 2> A;\n    A(0, 0) = -2 * R;\n    A(0, 1) = -1;\n    A(1, 0) = 1;\n    A(1, 1) = 0;\n\n    Matrix<double, 2, 1> B;\n    B(0, 0) = 1;\n    B(1, 0) = 0;\n\n    Matrix<double, 2, 2> H =\n        (Matrix<double, 2, 2>::Identity() - g * A).inverse();\n\n    Matrix<double, 2, 2> Pa = Matrix<double, 2, 2>::Identity() + 2 * g * A * H;\n    Matrix<double, 2, 1> Pb = 2 * g2 * A * H * B + 2 * g * B;\n    Matrix<double, 2, 1> Pc;\n    Pc(0, 0) = cbp - 2 * R * chp;\n    Pc(1, 0) = clp - chp;\n    double Pd = chp;\n\n    if (i != 0 && coeffs[i] != coeffs[i - 1]) {\n      auto Knn = ComputeRabensteinK(Pa_prev, Pb_prev, Pa_prev, Pb_prev);\n      auto Knp = ComputeRabensteinK(Pa_prev, Pb_prev, Pa, Pb);\n\n      Pa_prev = Pa;\n      Pb_prev = Pb;\n\n      Matrix<double, 2, 2> T = Knp.transpose() * Knn.inverse();\n      Pa = Pa * T;\n      Pc = (Pc.transpose() * T).transpose();\n    } else {\n      Pa_prev = Pa;\n      Pb_prev = Pb;\n    }\n\n    // Compute output.\n    double y = Pc.transpose() * s + Pd * x[i];\n\n    // State update\n    s = Pa * s + Pb * x[i];\n\n    x[i] = y;\n  }\n\n  return x;\n}\n\n// Truncated output switching, as in \"Suppression of Transients in Time-Varying\n// Recursive Filters for Audio Signals\".\nstatic vector<double> truncated_output_switching_filter(\n    vector<double> x, const vector<array<double, 5>> coeffs, int Na) {\n  const int n = x.size();\n  vector<double> ys(n);\n  for (int i = 0; i < n; ++i) {\n    auto cur_coeffs = coeffs[i];\n    double w1 = 0, w2 = 0;\n    double y = 0;\n\n    int start = max(i - Na + 1, 0);\n    for (int j = start; j <= i; ++j) {\n      double w = x[j] - cur_coeffs[3] * w1 - cur_coeffs[4] * w2;\n      y = cur_coeffs[0] * w + cur_coeffs[1] * w1 + cur_coeffs[2] * w2;\n\n      w2 = w1;\n      w1 = w;\n    }\n\n    ys[i] = y;\n  }\n\n  return ys;\n}\n\n// Output switching, equivalent to Zetterberg-Zhang.\nstatic vector<double>\noutput_switching_filter(vector<double> x,\n                        const vector<array<double, 5>> coeffs) {\n  return truncated_output_switching_filter(x, coeffs, x.size() + 1);\n  const int n = x.size();\n  vector<double> ys(n);\n  for (int i = 0; i < n; ++i) {\n    auto cur_coeffs = coeffs[i];\n    double w1 = 0, w2 = 0;\n    double y = 0;\n\n    for (int j = 0; j <= i; ++j) {\n      double w = x[j] - cur_coeffs[3] * w1 - cur_coeffs[4] * w2;\n      y = cur_coeffs[0] * w + cur_coeffs[1] * w1 + cur_coeffs[2] * w2;\n\n      w2 = w1;\n      w1 = w;\n    }\n\n    ys[i] = y;\n  }\n\n  return ys;\n}\n\n// Gold/Rader or coupled/normal form.\nstatic vector<double> gold_rader(vector<double> x,\n                                 const vector<array<double, 5>> coeffs) {\n  const int n = x.size();\n  double u1 = 0, u2 = 0;\n\n  for (int i = 0; i < n; ++i) {\n    const double a1 = coeffs[i][3], a2 = coeffs[i][4];\n    double alpha = -a1 / 2;\n    double beta = -0.5 * sqrt(4 * a2 - a1 * a1);\n\n    const double b0 = coeffs[i][0], b1 = coeffs[i][1], b2 = coeffs[i][2];\n    double alpha2 = alpha * alpha, beta2 = beta * beta;\n    double k1 = b0 - b2 / (alpha2 + beta2);\n    double k2 = (b2 * alpha + (b1 + b0 * alpha) * (alpha2 + beta2)) /\n                (beta * (alpha2 + beta2));\n    double k3 = b2 / (alpha2 + beta2);\n\n    double y = k1 * u1 + k2 * u2 + k3 * x[i];\n\n    double u1_new = alpha * u1 - beta * u2 + x[i];\n    double u2_new = beta * u1 + alpha * u2;\n    u1 = u1_new;\n    u2 = u2_new;\n    x[i] = y;\n  }\n\n  return x;\n}\n\nstatic void write_wav(const char* path, double sampling_rate, int channel_count,\n                      const vector<double>& samples) {\n  SF_INFO sfinfo;\n  sfinfo.samplerate = static_cast<int>(sampling_rate + 0.5);\n  sfinfo.channels = channel_count;\n  sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_FLOAT;\n  unique_ptr<SNDFILE, int (*)(SNDFILE*)> file(sf_open(path, SFM_WRITE, &sfinfo),\n                                              &sf_close);\n\n  if (!file) {\n    cerr << \"Error opening \\\"\" << path << \"\\\" for writing. \"\n         << sf_strerror(nullptr) << endl;\n    return;\n  }\n\n  // Make the data multichannel.\n  vector<float> multichannel_samples;\n  multichannel_samples.reserve(channel_count * samples.size());\n  for (auto x : samples) {\n    for (int i = 0; i < channel_count; ++i) {\n      multichannel_samples.push_back(x);\n    }\n  }\n\n  sf_write_float(file.get(), multichannel_samples.data(),\n                 multichannel_samples.size());\n}\n\nint main(int argc, char* argv[]) {\n  if (argc != 4) {\n    cerr << \"Usage: \" << argv[0]\n         << \" [filter type] [sine_hz|dc] [output_dir]\\n\";\n    return -1;\n  }\n\n  double cycles_per_second;\n  bool dc_input;\n  try {\n    if (strcmp(argv[2], \"dc\") == 0) {\n      dc_input = true;\n      cycles_per_second = 100;\n    } else {\n      dc_input = false;\n      cycles_per_second = stod(argv[2]);\n    }\n  }\n  catch (...) {\n    cerr << \"Invalid stimulus \\\"\" << argv[2] << \"\\\".\\n\";\n    return -2;\n  }\n\n  string output_dir(argv[3]);\n\n  const double sampling_rate = 48000;\n  const double cycles_per_sample = cycles_per_second / sampling_rate;\n  const double q = 6.0;\n  const double cutoff_scale = 0.2;\n  const double start_cutoff =\n      max(cycles_per_second, 100.0) * (1 - cutoff_scale);\n  const double end_cutoff = max(cycles_per_second, 100.0) * (1 + cutoff_scale);\n  const int constant_length = 48000;\n  const int end_constant_length = sampling_rate;\n  const int start_vary_pos = constant_length;\n  const int max_ramp_length = 200;\n  const int length = constant_length + max_ramp_length + end_constant_length;\n\n  auto ramp_fn = [=](int i, int ramp_length, double start_val, double end_val) {\n    if (i < start_vary_pos) {\n      return start_val;\n    }\n    if (i < start_vary_pos + ramp_length) {\n      return start_val + static_cast<double>(i - start_vary_pos) / ramp_length *\n                             (end_val - start_val);\n    }\n    return end_val;\n  };\n\n  const double start_w0 = start_cutoff * 2 * M_PI / sampling_rate;\n  const double end_w0 = end_cutoff * 2 * M_PI / sampling_rate;\n  auto vary_freq_fn = [=](int i, int ramp_length = 0) {\n    return ramp_fn(i, ramp_length, start_w0, end_w0);\n  };\n\n  const double start_gain = -4, end_gain = 4;\n  const double w0 = cycles_per_second * 2 * M_PI / sampling_rate;\n  auto vary_gain_fn = [=](int i, int ramp_length = 0) {\n    return ramp_fn(i, ramp_length, start_gain, end_gain);\n  };\n\n  const double start_q = 0.6, end_q = 4;\n  auto vary_q_fn = [=](int i, int ramp_length = 0) {\n    return ramp_fn(i, ramp_length, start_q, end_q);\n  };\n\n  auto input_signal =\n      generate_sine_wave(length, dc_input ? 0 : cycles_per_sample);\n\n  map<string, function<array<double, 5>(int i)>> filter_types = {\n      {\"lowpass_freq\",\n       [=](int i) { return lowpass_coefficients(vary_freq_fn(i), q); }},\n      {\"lowpass_q\",\n       [=](int i) { return lowpass_coefficients(w0, vary_q_fn(i)); }},\n      {\"peaking_freq\", [=](int i) {\n        return peaking_coefficients(vary_freq_fn(i), q, end_gain);\n      }},\n      {\"peaking_gain\",\n       [=](int i) { return peaking_coefficients(w0, q, vary_gain_fn(i)); }},\n      {\"peaking_q\", [=](int i) {\n        return peaking_coefficients(end_w0, vary_q_fn(i), end_gain);\n      }},\n  };\n\n  auto filter_iter = filter_types.find(argv[1]);\n  if (filter_iter == end(filter_types)) {\n    cerr << \"Invalid filter type \\\"\" << argv[1] << \"\\\". Types:\\n\";\n    for (const auto& p : filter_types) {\n      cerr << \"\\t\" << p.first << endl;\n    }\n    return -1;\n  }\n  auto coeffs_fn = filter_iter->second;\n\n  vector<array<double, 5>> coeffs(length);\n  for (int i = 0; i < length; ++i) {\n    coeffs[i] = coeffs_fn(i);\n  }\n\n  typedef function<vector<double>(vector<double>,\n                                  const vector<array<double, 5>>&)> filter_fn;\n  map<string, filter_fn> methods = {\n      {\"df2\", &time_varying_df2},\n      {\"gr\", &gold_rader},\n      {\"svf\", &time_varying_svf},\n      {\"svf_r\", &svf_rabenstein},\n      {\"svf_rc\", &svf_rabenstein_czarnach},\n      {\"tdf2\", &tdf2},\n      {\"tdf2_rc\", &tdf2_rabenstein_czarnach},\n      {\"zz\", &output_switching_filter},\n      {\"reference\",\n       [=](vector<double> x, const vector<array<double, 5>>& coeffs) {\n        return reference(std::move(x), coeffs, w0,\n                         static_cast<int>(sampling_rate * 0.01));\n      }},\n      {\n       \"anchor\", [=](vector<double> x, const vector<array<double, 5>>& coeffs) {\n                   return anchor(std::move(x), coeffs, w0);\n                 },\n      }};\n\n  // Reference and anchor aren't needed for testing DC input.\n  if (dc_input) {\n    methods.erase(\"reference\");\n    methods.erase(\"anchor\");\n  }\n\n  // Process with each filter structure.\n  map<string, vector<double>> outputs;\n  transform(begin(methods), end(methods), inserter(outputs, outputs.end()),\n            [&](pair<string, filter_fn> cur_method) {\n    return make_pair(cur_method.first, cur_method.second(input_signal, coeffs));\n  });\n\n  // Normalize peak levels.\n  double max_level =\n      accumulate(begin(outputs), end(outputs), 0.0,\n                 [](double cur, const pair<string, vector<double>>& p) {\n        double new_max_level =\n            accumulate(begin(p.second), end(p.second), 0.0,\n                       [](double cur, double x) { return max(cur, abs(x)); });\n        return max(cur, new_max_level);\n      });\n  for (auto& p : outputs) {\n    transform(begin(p.second), end(p.second), begin(p.second),\n              [max_level](double x) { return x / max_level; });\n  }\n\n  // Apply fade-in and fade-out, so the signal starting and ending doesn't\n  // distract from the filter transition.\n  // This only gets done for sinusoidal input, since it's used for the\n  // subjective tests. For the objective tests, the transition doesn't matter\n  // because there's no listening component.\n  if (!dc_input) {\n    auto fade_samples = static_cast<int>(sampling_rate * 0.05 + 0.5);\n    auto hann_window = generate_hann_window(2 * fade_samples);\n    hann_window.resize(fade_samples);\n    for (auto& p : outputs) {\n      auto& xs = p.second;\n      transform(begin(xs), begin(xs) + fade_samples, begin(hann_window),\n                begin(xs), std::multiplies<double>());\n      transform(end(xs) - fade_samples, end(xs), begin(hann_window),\n                end(xs) - fade_samples,\n                [](double x, double w) { return x * (1.0 - w); });\n    }\n  }\n\n  // Write the output.\n  const int channel_count = 2;\n  for (auto& output : outputs) {\n    auto output_path = output_dir + \"/\" + output.first + \".wav\";\n    write_wav(output_path.c_str(), sampling_rate, channel_count, output.second);\n  }\n}\n", "meta": {"hexsha": "1dbc572b7eb629144b475cbae665b575b117153c", "size": 23079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/src/filter.cpp", "max_stars_repo_name": "iZotope/time_varying_filters_paper", "max_stars_repo_head_hexsha": "59e67ab46b8b3204ffa4322f9485c1cca19c37b6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2015-03-26T00:28:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T04:20:36.000Z", "max_issues_repo_path": "code/src/filter.cpp", "max_issues_repo_name": "dafx/time_varying_filters_paper", "max_issues_repo_head_hexsha": "59e67ab46b8b3204ffa4322f9485c1cca19c37b6", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/filter.cpp", "max_forks_repo_name": "dafx/time_varying_filters_paper", "max_forks_repo_head_hexsha": "59e67ab46b8b3204ffa4322f9485c1cca19c37b6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-01-19T19:17:19.000Z", "max_forks_repo_forks_event_max_datetime": "2015-01-19T19:17:19.000Z", "avg_line_length": 29.9727272727, "max_line_length": 80, "alphanum_fraction": 0.5766281035, "num_tokens": 7318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5198137209427537}}
{"text": "#include <CGAL/Simple_cartesian.h>\n\n#include <CGAL/Surface_mesh.h>\n\n#include <CGAL/Surface_mesh_parameterization/IO/File_off.h>\n#include <CGAL/Surface_mesh_parameterization/Circular_border_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/Discrete_authalic_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/Error_code.h>\n#include <CGAL/Surface_mesh_parameterization/parameterize.h>\n\n#include <CGAL/Polygon_mesh_processing/measure.h>\n\n#include <boost/foreach.hpp>\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n\ntypedef CGAL::Simple_cartesian<double>       Kernel;\ntypedef Kernel::Point_2                      Point_2;\ntypedef Kernel::Point_3                      Point_3;\ntypedef CGAL::Surface_mesh<Kernel::Point_3>  SurfaceMesh;\n\ntypedef boost::graph_traits<SurfaceMesh>::halfedge_descriptor  halfedge_descriptor;\ntypedef boost::graph_traits<SurfaceMesh>::vertex_descriptor    vertex_descriptor;\ntypedef boost::graph_traits<SurfaceMesh>::face_descriptor      face_descriptor;\n\nnamespace SMP = CGAL::Surface_mesh_parameterization;\n\nint main(int argc, char * argv[])\n{\n  std::ifstream in((argc>1) ? argv[1] : \"data/three_peaks.off\");\n  if(!in) {\n    std::cerr << \"Problem loading the input data\" << std::endl;\n    return 1;\n  }\n\n  SurfaceMesh sm;\n  in >> sm;\n\n  // A halfedge on the border\n  halfedge_descriptor bhd = CGAL::Polygon_mesh_processing::longest_border(sm).first;\n\n  // The 2D points of the uv parametrisation will be written into this map\n  typedef SurfaceMesh::Property_map<vertex_descriptor, Point_2>  UV_pmap;\n  UV_pmap uv_map = sm.add_property_map<vertex_descriptor, Point_2>(\"v:uv\").first;\n\n  typedef SMP::Circular_border_arc_length_parameterizer_3<SurfaceMesh>  Border_parameterizer;\n  typedef SMP::Discrete_authalic_parameterizer_3<SurfaceMesh, Border_parameterizer> Parameterizer;\n\n  SMP::Error_code err = SMP::parameterize(sm, Parameterizer(), bhd, uv_map);\n\n  if(err != SMP::OK) {\n    std::cerr << \"Error: \" << SMP::get_error_message(err) << std::endl;\n    return 1;\n  }\n\n  std::ofstream out(\"result.off\");\n  SMP::IO::output_uvmap_to_off(sm, bhd, uv_map, out);\n\n  return 0;\n}\n", "meta": {"hexsha": "ed4eb5ef07f0e7946dfc3f28c02e7791d367c8d6", "size": 2137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Surface_mesh_parameterization/discrete_authalic.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/Surface_mesh_parameterization/discrete_authalic.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/Surface_mesh_parameterization/discrete_authalic.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": 33.9206349206, "max_line_length": 98, "alphanum_fraction": 0.7515208236, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.519813719528277}}
{"text": "//==================================================================================================\n/*\n  Copyright 2017 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//! [roundings]\n#include <boost/simd/arithmetic.hpp>\n#include <boost/simd/pack.hpp>\n#include <iostream>\n\nnamespace bs =  boost::simd;\nusing pack_ft =  bs::pack <float, 8>;\n\nint main()\n{\n  pack_ft p = {-1.1f, -1.5f, -1.6f, -2.1f, -2.5f, -2.6f,  1.1f, 1.5f };\n  std::cout << \" p =  \" << p << std::endl\n            <<  \" -> bs::ceil(p) =       \" << bs::ceil(p)      << std::endl\n            <<  \" -> bs::floor(p) =      \" << bs::floor(p)     << std::endl\n            <<  \" -> bs::fix(p) =        \" << bs::fix(p)       << std::endl\n            <<  \" -> bs::round(p) =      \" << bs::round(p)     << std::endl\n            <<  \" -> bs::nearbyint(p) =  \" << bs::nearbyint(p) << std::endl;\n  return 0;\n}\n//! [roundings]\n", "meta": {"hexsha": "1bab0b4216b69336485900cc8ca10b470c4e1bee", "size": 1092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/arithmetic/roundings.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/doc/arithmetic/roundings.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/doc/arithmetic/roundings.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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": 37.6551724138, "max_line_length": 100, "alphanum_fraction": 0.4047619048, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5198137090535281}}
{"text": "// Copyright (c) 2009 INRIA Sophia-Antipolis (France).\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org).\n// You can redistribute it and/or modify it under the terms of the GNU\n// General Public License as published by the Free Software Foundation,\n// either version 3 of the License, or (at your option) any later version.\n//\n// Licensees holding a valid commercial license may use this file in\n// accordance with the commercial license agreement provided with the software.\n//\n// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n//\n// $URL$\n// $Id$\n//\n//\n// Author(s)     : St\u00e9phane Tayeb\n//\n//******************************************************************************\n// File Description :\n// Outputs to out.mesh a mesh of implicit domains. These domains are defined\n// by a vector of functions. Each n-uplet of sign of function values defines a\n// subdomain.\n//******************************************************************************\n\n\n#include \"debug.h\"\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Mesh_triangulation_3.h>\n#include <CGAL/Mesh_complex_3_in_triangulation_3.h>\n#include <CGAL/Mesh_criteria_3.h>\n\n#include <CGAL/Implicit_to_labeling_function_wrapper.h>\n#include <CGAL/Labeled_mesh_domain_3.h>\n#include <CGAL/make_mesh_3.h>\n#include \"../examples/Mesh_3/implicit_functions.h\"\n\n#include <CGAL/Mesh_3/Mesh_global_optimizer.h>\n\n// IO\n#include <CGAL/IO/File_medit.h>\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\nusing namespace CGAL::parameters;\n\n// Domain\nstruct K: public CGAL::Exact_predicates_inexact_constructions_kernel {};\ntypedef FT_to_point_function_wrapper<K::FT, K::Point_3> Function;\ntypedef CGAL::Implicit_multi_domain_to_labeling_function_wrapper<Function>\n                                                        Function_wrapper;\ntypedef Function_wrapper::Function_vector Function_vector;\ntypedef CGAL::Labeled_mesh_domain_3<Function_wrapper, K> Mesh_domain;\n\n// Triangulation\ntypedef CGAL::Mesh_triangulation_3<Mesh_domain>::type Tr;\ntypedef CGAL::Mesh_complex_3_in_triangulation_3<Tr> C3t3;\n\n\n// Mesh Criteria\ntypedef CGAL::Mesh_criteria_3<Tr> Mesh_criteria;\ntypedef Mesh_criteria::Facet_criteria    Facet_criteria;\ntypedef Mesh_criteria::Cell_criteria     Cell_criteria;\n\n\ntemplate <typename T>\ndouble set_arg(const std::string& param_name,\n               const std::string& param_string,\n               const po::variables_map& vm)\n{\n  T param_value(0);\n  \n  if ( vm.count(param_name) )\n  {\n    param_value = vm[param_name].as<T>();\n    std::cout << param_string << \": \" << param_value << \"\\n\";\n  }\n  else\n  {\n    std::cout << param_string << \" ignored.\\n\";\n  }\n  \n  return param_value;\n}\n\n\nvoid set_function(Function_vector& v,\n                  Function& f,\n                  const std::string& function_name,\n                  const po::variables_map& vm)\n{\n  if ( vm.count(function_name) )\n  {\n    v.push_back(f);\n    std::cout << function_name << \" \";\n  }\n}\n\n\nint main(int argc, char* argv[])\n{\n  po::options_description generic(\"Generic options\");\n  generic.add_options() (\"help\", \"Produce help message\");\n  \n  po::options_description mesh(\"Mesh generation parameters\");\n  mesh.add_options()(\"facet_angle\", po::value<double>(), \"Set facet angle bound\")\n  (\"facet_size\", po::value<double>(), \"Set facet size bound\")\n  (\"facet_error\", po::value<double>(), \"Set facet approximation error bound\")\n  (\"tet_shape\", po::value<double>(), \"Set tet radius-edge bound\")\n  (\"tet_size\", po::value<double>(), \"Set tet size bound\");\n  \n  po::options_description functions(\"Implicit functions\");\n  functions.add_options()(\"torus\", \"Mesh torus function\")\n  (\"sphere\", \"Mesh sphere function\")\n  (\"chair\", \"Mesh chair function\")\n  (\"tanglecube\", \"Mesh tanglecube function\")\n  (\"cube\", \"Mesh cube function\")\n  (\"ellipsoid\", \"Mesh ellipsoid function\")\n  (\"heart\", \"Mesh heart function\")\n  (\"octic\", \"Mesh octic function\");\n  \n  po::options_description desc(\"Options\");\n  desc.add_options()\n  (\"exude\", po::value<double>(), \"Exude mesh after refinement. arg is time_limit.\")\n  (\"perturb\", po::value<double>(), \"Perturb (sliver removal) mesh after refinement. arg is time_limit.\")\n  (\"lloyd\", po::value<int>(), \"Lloyd-smoothing after refinement. arg is max_iteration_nb\")\n  (\"odt\", po::value<int>(), \"ODT-smoothing after refinement. arg is max_iteration_nb\")\n  (\"convergence\", po::value<double>()->default_value(0.02), \"Convergence ratio for smoothing functions\")\n  (\"min_displacement\", po::value<double>()->default_value(0.01), \"Minimal displacement ratio for smoothing functions (moves that are below that ratio will not be done)\")\n  (\"time_limit\", po::value<double>()->default_value(0), \"Max time for smoothing functions\")    \n  (\"no_label_rebind\", \"Don't rebind cell labels in medit output\")\n  (\"show_patches\", \"Show surface patches in medit output\");\n\n  \n  po::options_description cmdline_options(\"Usage\",1);\n  cmdline_options.add(generic).add(mesh).add(functions).add(desc);\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, cmdline_options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\") || argc < 2)\n  {\n    std::cout << cmdline_options << std::endl;\n    return 1;\n  }\n\n  std::cout << \"=========== Params ===========\"<< std::endl;\n  \n  double facet_angle = set_arg<double>(\"facet_angle\",\"Facet angle\",vm);\n  double facet_size = set_arg<double>(\"facet_size\",\"Facet size\",vm);\n  double facet_error = set_arg<double>(\"facet_error\",\"Facet approximation error\",vm);\n\n  double tet_shape = set_arg<double>(\"tet_shape\",\"Tet shape (radius-edge)\",vm);\n  double tet_size = set_arg<double>(\"tet_size\",\"Tet size\",vm);\n  \n\n  \n  // Define functions\n  Function f1(&torus_function);\n  Function f2(&sphere_function<3>);\n  Function f3(&chair_function);\n  Function f4(&tanglecube_function);\n  Function f5(&cube_function);\n  Function f6(&ellipsoid_function);\n  Function f7(&heart_function);\n  Function f8(&octic_function);\n\n  Function_vector v;\n  \n  std::cout << \"\\nFunction(s): \";\n  \n  set_function(v,f1,\"torus\",vm);\n  set_function(v,f2,\"sphere\",vm);\n  set_function(v,f3,\"chair\",vm);\n  set_function(v,f4,\"tanglecube\",vm);\n  set_function(v,f5,\"cube\",vm);\n  set_function(v,f6,\"ellipsoid\",vm);\n  set_function(v,f7,\"heart\",vm);\n  set_function(v,f8,\"octic\",vm);\n    \n  std::cout << \"\\n==============================\"<< std::endl;\n  std::cout << std::endl;\n  \n  if ( v.empty() )\n  {\n    std::cout << \"No function set. Exit.\\n\";\n    return 0;\n  }\n  \n  // Domain (Warning: Sphere_3 constructor uses square radius !)\n  Mesh_domain domain(v, K::Sphere_3(CGAL::ORIGIN, 7.*7.), 1e-8);\n\n  // Set mesh criteria\n  Facet_criteria facet_criteria(facet_angle, facet_size, facet_error); // angle, size, approximation\n  Cell_criteria cell_criteria(tet_shape, tet_size); // radius-edge ratio, size\n  Mesh_criteria criteria(facet_criteria, cell_criteria);\n\n  // Mesh generation\n  C3t3 c3t3 = CGAL::make_mesh_3<C3t3>(domain, criteria, no_exude(), no_perturb());\n\n  // Odt\n  if (  vm.count(\"odt\") )\n  {\n    CGAL::odt_optimize_mesh_3(c3t3, domain,\n                              max_iteration_number=vm[\"odt\"].as<int>(),\n                              convergence=vm[\"convergence\"].as<double>(),\n                              sliver_bound=vm[\"min_displacement\"].as<double>(),\n                              time_limit=vm[\"time_limit\"].as<double>());\n  }\n  \n  // Lloyd\n  if ( vm.count(\"lloyd\") )\n  {\n    CGAL::lloyd_optimize_mesh_3(c3t3, domain,\n                                max_iteration_number=vm[\"lloyd\"].as<int>(),\n                                convergence=vm[\"convergence\"].as<double>(),\n                                sliver_bound=vm[\"min_displacement\"].as<double>(),\n                                time_limit=vm[\"time_limit\"].as<double>());\n  }\n  \n  // Perturbation\n  if ( vm.count(\"perturb\") )\n  {\n    CGAL::perturb_mesh_3(c3t3, domain, time_limit = vm[\"perturb\"].as<double>() );\n  }\n  \n  // Exudation\n  if ( vm.count(\"exude\") )\n  { \n    CGAL::exude_mesh_3(c3t3, time_limit = vm[\"exude\"].as<double>());\n  }\n  \n  double min_angle = 181.;\n  for ( C3t3::Cell_iterator cit = c3t3.cells_begin() ;\n       cit != c3t3.cells_end() ;\n       ++cit )\n  {\n    min_angle = (std::min)(min_angle,\n                           CGAL::to_double(CGAL::Mesh_3::minimum_dihedral_angle(c3t3.triangulation().tetrahedron(cit))));\n  }\n  \n  std::cerr << \"Min angle: \" << min_angle << std::endl;\n\n  // Output\n  std::ofstream medit_file(\"out.mesh\");\n  CGAL::output_to_medit(medit_file, c3t3, !vm.count(\"no_label_rebind\"), vm.count(\"show_patches\"));\n\n  return 0;\n}\n", "meta": {"hexsha": "0926a94ecea500b01a51bf084ef592cf293926c6", "size": 8644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Mesh_3/applications/mesh_implicit_domains.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/Mesh_3/applications/mesh_implicit_domains.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/Mesh_3/applications/mesh_implicit_domains.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": 33.8980392157, "max_line_length": 169, "alphanum_fraction": 0.6516658954, "num_tokens": 2206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5198137076390513}}
{"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    testScenario.cpp\n * @brief   Unit test Scenario class\n * @author  Frank Dellaert\n */\n\n#include <gtsam/base/numericalDerivative.h>\n#include <gtsam/navigation/Scenario.h>\n\n#include <CppUnitLite/TestHarness.h>\n#include <boost/bind.hpp>\n#include <cmath>\n\nusing namespace std;\nusing namespace gtsam;\n\nstatic const double kDegree = M_PI / 180.0;\n\n/* ************************************************************************* */\nTEST(Scenario, Spin) {\n  //  angular velocity 6 kDegree/sec\n  const double w = 6 * kDegree;\n  const Vector3 W(0, 0, w), V(0, 0, 0);\n  const ConstantTwistScenario scenario(W, V);\n\n  const double T = 10;\n  EXPECT(assert_equal(W, scenario.omega_b(T), 1e-9));\n  EXPECT(assert_equal(V, scenario.velocity_b(T), 1e-9));\n  EXPECT(assert_equal(W.cross(V), scenario.acceleration_b(T), 1e-9));\n\n  const Pose3 T10 = scenario.pose(T);\n  EXPECT(assert_equal(Vector3(0, 0, 60 * kDegree), T10.rotation().xyz(), 1e-9));\n  EXPECT(assert_equal(Point3(0, 0, 0), T10.translation(), 1e-9));\n}\n\n/* ************************************************************************* */\nTEST(Scenario, Forward) {\n  const double v = 2;  // m/s\n  const Vector3 W(0, 0, 0), V(v, 0, 0);\n  const ConstantTwistScenario scenario(W, V);\n\n  const double T = 15;\n  EXPECT(assert_equal(W, scenario.omega_b(T), 1e-9));\n  EXPECT(assert_equal(V, scenario.velocity_b(T), 1e-9));\n  EXPECT(assert_equal(W.cross(V), scenario.acceleration_b(T), 1e-9));\n\n  const Pose3 T15 = scenario.pose(T);\n  EXPECT(assert_equal(Vector3(0, 0, 0), T15.rotation().xyz(), 1e-9));\n  EXPECT(assert_equal(Point3(30, 0, 0), T15.translation(), 1e-9));\n}\n\n/* ************************************************************************* */\nTEST(Scenario, Circle) {\n  // Forward velocity 2m/s, angular velocity 6 kDegree/sec around Z\n  const double v = 2, w = 6 * kDegree;\n  const Vector3 W(0, 0, w), V(v, 0, 0);\n  const ConstantTwistScenario scenario(W, V);\n\n  const double T = 15;\n  EXPECT(assert_equal(W, scenario.omega_b(T), 1e-9));\n  EXPECT(assert_equal(V, scenario.velocity_b(T), 1e-9));\n  EXPECT(assert_equal(W.cross(V), scenario.acceleration_b(T), 1e-9));\n\n  // R = v/w, so test if circle is of right size\n  const double R = v / w;\n  const Pose3 T15 = scenario.pose(T);\n  EXPECT(assert_equal(Vector3(0, 0, 90 * kDegree), T15.rotation().xyz(), 1e-9));\n  EXPECT(assert_equal(Point3(R, R, 0), T15.translation(), 1e-9));\n}\n\n/* ************************************************************************* */\nTEST(Scenario, Loop) {\n  // Forward velocity 2m/s\n  // Pitch up with angular velocity 6 kDegree/sec (negative in FLU)\n  const double v = 2, w = 6 * kDegree;\n  const Vector3 W(0, -w, 0), V(v, 0, 0);\n  const ConstantTwistScenario scenario(W, V);\n\n  const double T = 30;\n  EXPECT(assert_equal(W, scenario.omega_b(T), 1e-9));\n  EXPECT(assert_equal(V, scenario.velocity_b(T), 1e-9));\n  EXPECT(assert_equal(W.cross(V), scenario.acceleration_b(T), 1e-9));\n\n  // R = v/w, so test if loop crests at 2*R\n  const double R = v / w;\n  const Pose3 T30 = scenario.pose(30);\n  EXPECT(assert_equal(Rot3::Rodrigues(0, M_PI, 0), T30.rotation(), 1e-9));\n#ifdef GTSAM_USE_QUATERNIONS\n  EXPECT(assert_equal(Vector3(-M_PI, 0, -M_PI), T30.rotation().xyz()));\n#else\n  EXPECT(assert_equal(Vector3(M_PI, 0, M_PI), T30.rotation().xyz()));\n#endif\n  EXPECT(assert_equal(Point3(0, 0, 2 * R), T30.translation(), 1e-9));\n}\n\n/* ************************************************************************* */\nTEST(Scenario, LoopWithInitialPose) {\n  // Forward velocity 2m/s\n  // Pitch up with angular velocity 6 kDegree/sec (negative in FLU)\n  const double v = 2, w = 6 * kDegree;\n  const Vector3 W(0, -w, 0), V(v, 0, 0);\n  const Rot3 nRb0 = Rot3::Yaw(M_PI);\n  const Pose3 nTb0(nRb0, Point3(1, 2, 3));\n  const ConstantTwistScenario scenario(W, V, nTb0);\n\n  const double T = 30;\n  EXPECT(assert_equal(W, scenario.omega_b(T), 1e-9));\n  EXPECT(assert_equal(V, scenario.velocity_b(T), 1e-9));\n  EXPECT(assert_equal(W.cross(V), scenario.acceleration_b(T), 1e-9));\n\n  // R = v/w, so test if loop crests at 2*R\n  const double R = v / w;\n  const Pose3 T30 = scenario.pose(30);\n  EXPECT(\n      assert_equal(nRb0 * Rot3::Rodrigues(0, M_PI, 0), T30.rotation(), 1e-9));\n  EXPECT(assert_equal(Point3(1, 2, 3 + 2 * R), T30.translation(), 1e-9));\n}\n\n/* ************************************************************************* */\nTEST(Scenario, Accelerating) {\n  // Set up body pointing towards y axis, and start at 10,20,0 with velocity\n  // going in X. The body itself has Z axis pointing down\n  const Rot3 nRb(Point3(0, 1, 0), Point3(1, 0, 0), Point3(0, 0, -1));\n  const Point3 P0(10, 20, 0);\n  const Vector3 V0(50, 0, 0);\n\n  const double a = 0.2;  // m/s^2\n  const Vector3 A(0, a, 0), W(0.1, 0.2, 0.3);\n  const AcceleratingScenario scenario(nRb, P0, V0, A, W);\n\n  const double T = 3;\n  EXPECT(assert_equal(W, scenario.omega_b(T), 1e-9));\n  EXPECT(assert_equal(Vector3(V0 + T * A), scenario.velocity_n(T), 1e-9));\n  EXPECT(assert_equal(A, scenario.acceleration_n(T), 1e-9));\n\n  {\n    // Check acceleration in nav\n    Matrix expected = numericalDerivative11<Vector3, double>(\n        boost::bind(&Scenario::velocity_n, scenario, _1), T);\n    EXPECT(assert_equal(Vector3(expected), scenario.acceleration_n(T), 1e-9));\n  }\n\n  const Pose3 T3 = scenario.pose(3);\n  EXPECT(assert_equal(nRb.expmap(T * W), T3.rotation(), 1e-9));\n  EXPECT(assert_equal(Point3(10 + T * 50, 20 + a * T * T / 2, 0),\n                      T3.translation(), 1e-9));\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "9c080929dd385bacc51970e1a375df12b9a9f3a8", "size": 6078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/navigation/tests/testScenario.cpp", "max_stars_repo_name": "kvmanohar22/gtsam", "max_stars_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-12-11T18:33:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:52:45.000Z", "max_issues_repo_path": "gtsam/navigation/tests/testScenario.cpp", "max_issues_repo_name": "kvmanohar22/gtsam", "max_issues_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-10-30T21:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T18:47:40.000Z", "max_forks_repo_path": "gtsam/navigation/tests/testScenario.cpp", "max_forks_repo_name": "kvmanohar22/gtsam", "max_forks_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T16:24:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T11:10:49.000Z", "avg_line_length": 36.6144578313, "max_line_length": 80, "alphanum_fraction": 0.5809476802, "num_tokens": 1803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5198137038161535}}
{"text": "/* Copyright (c) 2021, the adamantine authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#define BOOST_TEST_MODULE DataAssimilator\n\n#include <DataAssimilator.hh>\n#include <Geometry.hh>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/lac/la_parallel_vector.h>\n\n#include \"main.cc\"\n\nnamespace adamantine\n{\nclass DataAssimilatorTester\n{\npublic:\n  void test_constructor()\n  {\n    boost::property_tree::ptree database;\n\n    // First checking the dealii default values\n    DataAssimilator da0(database);\n\n    double tol = 1.0e-12;\n    BOOST_CHECK_SMALL(da0._solver_control.tolerance() - 1.0e-10, tol);\n    BOOST_CHECK(da0._solver_control.max_steps() == 100);\n    BOOST_CHECK(da0._additional_data.max_n_tmp_vectors == 30);\n\n    // Now explicitly setting them\n    database.put(\"solver.convergence_tolerance\", 1.0e-6);\n    database.put(\"solver.max_iterations\", 25);\n    database.put(\"solver.max_number_of_temp_vectors\", 4);\n    DataAssimilator da1(database);\n    BOOST_CHECK_SMALL(da1._solver_control.tolerance() - 1.0e-6, tol);\n    BOOST_CHECK(da1._solver_control.max_steps() == 25);\n    BOOST_CHECK(da1._additional_data.max_n_tmp_vectors == 4);\n  };\n\n  void test_calc_kalman_gain()\n  {\n    // Create the DoF mapping\n    MPI_Comm communicator = MPI_COMM_WORLD;\n\n    boost::property_tree::ptree database;\n    database.put(\"import_mesh\", false);\n    database.put(\"length\", 1);\n    database.put(\"length_divisions\", 2);\n    database.put(\"height\", 1);\n    database.put(\"height_divisions\", 2);\n    adamantine::Geometry<2> geometry(communicator, database);\n    dealii::parallel::distributed::Triangulation<2> const &tria =\n        geometry.get_triangulation();\n\n    dealii::FE_Q<2> fe(1);\n    dealii::DoFHandler<2> dof_handler(tria);\n    dof_handler.distribute_dofs(fe);\n\n    unsigned int sim_size = 5;\n    unsigned int expt_size = 2;\n\n    dealii::Vector<double> expt_vec(2);\n    expt_vec(0) = 2.5;\n    expt_vec(1) = 9.5;\n\n    std::pair<std::vector<int>, std::vector<int>> indices_and_offsets;\n    indices_and_offsets.first.resize(2);\n    indices_and_offsets.second.resize(3); // Offset vector is one longer\n    indices_and_offsets.first[0] = 1;\n    indices_and_offsets.first[1] = 3;\n    indices_and_offsets.second[0] = 0;\n    indices_and_offsets.second[1] = 1;\n    indices_and_offsets.second[2] = 2;\n\n    boost::property_tree::ptree solver_settings_database;\n    DataAssimilator da(solver_settings_database);\n    da._sim_size = sim_size;\n    da._expt_size = expt_size;\n    da._num_ensemble_members = 3;\n    da.update_dof_mapping<2>(dof_handler, indices_and_offsets);\n\n    // Create the simulation data\n    std::vector<dealii::LA::distributed::Vector<double>> data(3);\n    data[0].reinit(5);\n    data[0](0) = 1.0;\n    data[0](1) = 3.0;\n    data[0](2) = 6.0;\n    data[0](3) = 9.0;\n    data[0](4) = 11.0;\n    data[1].reinit(5);\n    data[1](0) = 1.5;\n    data[1](1) = 3.2;\n    data[1](2) = 6.3;\n    data[1](3) = 9.7;\n    data[1](4) = 11.9;\n    data[2].reinit(5);\n    data[2](0) = 1.1;\n    data[2](1) = 3.1;\n    data[2](2) = 6.1;\n    data[2](3) = 9.1;\n    data[2](4) = 11.1;\n\n    // Build the sparse experimental covariance matrix\n    dealii::SparsityPattern pattern(expt_size, expt_size, 1);\n    pattern.add(0, 0);\n    pattern.add(1, 1);\n    pattern.compress();\n\n    dealii::SparseMatrix<double> R(pattern);\n    R.add(0, 0, 0.002);\n    R.add(1, 1, 0.001);\n\n    // Create the (perturbed) innovation\n    std::vector<dealii::Vector<double>> perturbed_innovation(3);\n    for (unsigned int sample = 0; sample < perturbed_innovation.size();\n         ++sample)\n    {\n      perturbed_innovation[sample].reinit(expt_size);\n      dealii::Vector<double> temp = da.calc_Hx(data[sample]);\n      for (unsigned int i = 0; i < expt_size; ++i)\n      {\n        perturbed_innovation[sample][i] = expt_vec[i] - temp[i];\n      }\n    }\n\n    perturbed_innovation[0][0] = perturbed_innovation[0][0] + 0.0008;\n    perturbed_innovation[0][1] = perturbed_innovation[0][1] - 0.0005;\n    perturbed_innovation[1][0] = perturbed_innovation[1][0] - 0.001;\n    perturbed_innovation[1][1] = perturbed_innovation[1][1] + 0.0002;\n    perturbed_innovation[2][0] = perturbed_innovation[2][0] + 0.0002;\n    perturbed_innovation[2][1] = perturbed_innovation[2][1] - 0.0009;\n\n    // Apply the Kalman gain\n    std::vector<dealii::LA::distributed::Vector<double>> forecast_shift =\n        da.apply_kalman_gain(data, R, perturbed_innovation);\n\n    double tol = 1.0e-4;\n\n    // Reference solution calculated using Python\n    BOOST_CHECK_CLOSE(forecast_shift[0][0], 0.21352564, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[0][1], -0.14600986, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[0][2], -0.02616469, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[0][3], 0.45321598, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[0][4], 0.69290631, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[1][0], -0.27786325, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[1][1], -0.32946285, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[1][2], -0.31226298, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[1][3], -0.24346351, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[1][4], -0.20906377, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[2][0], 0.12767094, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[2][1], -0.20319395, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[2][2], -0.09290565, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[2][3], 0.34824753, tol);\n    BOOST_CHECK_CLOSE(forecast_shift[2][4], 0.56882413, tol);\n  };\n\n  void test_update_dof_mapping()\n  {\n    MPI_Comm communicator = MPI_COMM_WORLD;\n\n    boost::property_tree::ptree database;\n    database.put(\"import_mesh\", false);\n    database.put(\"length\", 1);\n    database.put(\"length_divisions\", 2);\n    database.put(\"height\", 1);\n    database.put(\"height_divisions\", 2);\n    adamantine::Geometry<2> geometry(communicator, database);\n    dealii::parallel::distributed::Triangulation<2> const &tria =\n        geometry.get_triangulation();\n\n    dealii::FE_Q<2> fe(1);\n    dealii::DoFHandler<2> dof_handler(tria);\n    dof_handler.distribute_dofs(fe);\n\n    unsigned int sim_size = 4;\n    unsigned int expt_size = 3;\n\n    std::pair<std::vector<int>, std::vector<int>> indices_and_offsets;\n    indices_and_offsets.first.resize(3);\n    indices_and_offsets.second.resize(4); // offset vector is one longer\n    indices_and_offsets.first[0] = 0;\n    indices_and_offsets.first[1] = 1;\n    indices_and_offsets.first[2] = 3;\n    indices_and_offsets.second[0] = 0;\n    indices_and_offsets.second[1] = 1;\n    indices_and_offsets.second[2] = 2;\n    indices_and_offsets.second[3] = 3;\n\n    boost::property_tree::ptree solver_settings_database;\n    DataAssimilator da(solver_settings_database);\n    da._sim_size = sim_size;\n    da._expt_size = expt_size;\n    da.update_dof_mapping<2>(dof_handler, indices_and_offsets);\n\n    BOOST_CHECK(da._expt_to_dof_mapping.first[0] == 0);\n    BOOST_CHECK(da._expt_to_dof_mapping.first[1] == 1);\n    BOOST_CHECK(da._expt_to_dof_mapping.first[2] == 2);\n    BOOST_CHECK(da._expt_to_dof_mapping.second[0] == 0);\n    BOOST_CHECK(da._expt_to_dof_mapping.second[1] == 1);\n    BOOST_CHECK(da._expt_to_dof_mapping.second[2] == 3);\n  };\n\n  void test_calc_H()\n  {\n    MPI_Comm communicator = MPI_COMM_WORLD;\n\n    boost::property_tree::ptree database;\n    database.put(\"import_mesh\", false);\n    database.put(\"length\", 1);\n    database.put(\"length_divisions\", 2);\n    database.put(\"height\", 1);\n    database.put(\"height_divisions\", 2);\n    adamantine::Geometry<2> geometry(communicator, database);\n    dealii::parallel::distributed::Triangulation<2> const &tria =\n        geometry.get_triangulation();\n\n    dealii::FE_Q<2> fe(1);\n    dealii::DoFHandler<2> dof_handler(tria);\n    dof_handler.distribute_dofs(fe);\n\n    unsigned int sim_size = 4;\n    unsigned int expt_size = 3;\n\n    std::pair<std::vector<int>, std::vector<int>> indices_and_offsets;\n    indices_and_offsets.first.resize(3);\n    indices_and_offsets.second.resize(4); // offset vector is one longer\n    indices_and_offsets.first[0] = 0;\n    indices_and_offsets.first[1] = 1;\n    indices_and_offsets.first[2] = 3;\n    indices_and_offsets.second[0] = 0;\n    indices_and_offsets.second[1] = 1;\n    indices_and_offsets.second[2] = 2;\n    indices_and_offsets.second[3] = 3;\n\n    boost::property_tree::ptree solver_settings_database;\n    DataAssimilator da(solver_settings_database);\n    da._sim_size = sim_size;\n    da._expt_size = expt_size;\n    da.update_dof_mapping<2>(dof_handler, indices_and_offsets);\n\n    dealii::SparsityPattern pattern(expt_size, sim_size, expt_size);\n\n    dealii::SparseMatrix<double> H = da.calc_H(pattern);\n\n    double tol = 1e-12;\n    for (unsigned int i = 0; i < expt_size; ++i)\n    {\n      for (unsigned int j = 0; j < sim_size; ++j)\n      {\n        if (i == 0 && j == 0)\n          BOOST_CHECK_CLOSE(H(i, j), 1.0, tol);\n        else if (i == 1 && j == 1)\n          BOOST_CHECK_CLOSE(H(i, j), 1.0, tol);\n        else if (i == 2 && j == 3)\n          BOOST_CHECK_CLOSE(H(i, j), 1.0, tol);\n        else\n          BOOST_CHECK_CLOSE(H.el(i, j), 0.0, tol);\n      }\n    }\n  };\n  void test_calc_Hx()\n  {\n    MPI_Comm communicator = MPI_COMM_WORLD;\n\n    boost::property_tree::ptree database;\n    database.put(\"import_mesh\", false);\n    database.put(\"length\", 1);\n    database.put(\"length_divisions\", 2);\n    database.put(\"height\", 1);\n    database.put(\"height_divisions\", 2);\n    adamantine::Geometry<2> geometry(communicator, database);\n    dealii::parallel::distributed::Triangulation<2> const &tria =\n        geometry.get_triangulation();\n\n    dealii::FE_Q<2> fe(1);\n    dealii::DoFHandler<2> dof_handler(tria);\n    dof_handler.distribute_dofs(fe);\n\n    int sim_size = 4;\n    int expt_size = 3;\n\n    dealii::LA::distributed::Vector<double> sim_vec(dof_handler.n_dofs());\n    sim_vec(0) = 2.0;\n    sim_vec(1) = 4.0;\n    sim_vec(2) = 5.0;\n    sim_vec(3) = 7.0;\n\n    dealii::Vector<double> expt_vec(3);\n    expt_vec(0) = 2.5;\n    expt_vec(1) = 4.5;\n    expt_vec(2) = 8.5;\n\n    std::pair<std::vector<int>, std::vector<int>> indices_and_offsets;\n    indices_and_offsets.first.resize(3);\n    indices_and_offsets.second.resize(4); // Offset vector is one longer\n    indices_and_offsets.first[0] = 0;\n    indices_and_offsets.first[1] = 1;\n    indices_and_offsets.first[2] = 3;\n    indices_and_offsets.second[0] = 0;\n    indices_and_offsets.second[1] = 1;\n    indices_and_offsets.second[2] = 2;\n    indices_and_offsets.second[3] = 3;\n\n    boost::property_tree::ptree solver_settings_database;\n    DataAssimilator da(solver_settings_database);\n    da._sim_size = sim_size;\n    da._expt_size = expt_size;\n    da.update_dof_mapping<2>(dof_handler, indices_and_offsets);\n    dealii::Vector<double> Hx = da.calc_Hx(sim_vec);\n\n    double tol = 1e-10;\n    BOOST_CHECK_CLOSE(Hx(0), 2.0, tol);\n    BOOST_CHECK_CLOSE(Hx(1), 4.0, tol);\n    BOOST_CHECK_CLOSE(Hx(2), 7.0, tol);\n  };\n\n  void test_calc_sample_covariance_dense()\n  {\n    double tol = 1e-10;\n\n    // Trivial case of identical vectors, covariance should be the zero matrix\n    std::vector<dealii::LA::distributed::Vector<double>> data1(3);\n    data1[0].reinit(4);\n    data1[0](0) = 1.0;\n    data1[0](1) = 3.0;\n    data1[0](2) = 6.0;\n    data1[0](3) = 9.0;\n    data1[1].reinit(4);\n    data1[1](0) = 1.0;\n    data1[1](1) = 3.0;\n    data1[1](2) = 6.0;\n    data1[1](3) = 9.0;\n    data1[2].reinit(4);\n    data1[2](0) = 1.0;\n    data1[2](1) = 3.0;\n    data1[2](2) = 6.0;\n    data1[2](3) = 9.0;\n\n    boost::property_tree::ptree solver_settings_database;\n    DataAssimilator da(solver_settings_database);\n    dealii::FullMatrix<double> cov = da.calc_sample_covariance_dense(data1);\n\n    // Check results\n    for (unsigned int i = 0; i < 4; ++i)\n    {\n      for (unsigned int j = 0; j < 4; ++j)\n      {\n        BOOST_CHECK_SMALL(std::abs(cov(i, j)), tol);\n      }\n    }\n\n    // Non-trivial case, using NumPy solution as the reference\n    std::vector<dealii::LA::distributed::Vector<double>> data2(3);\n    data2[0].reinit(5);\n    data2[0](0) = 1.0;\n    data2[0](1) = 3.0;\n    data2[0](2) = 6.0;\n    data2[0](3) = 9.0;\n    data2[0](4) = 11.0;\n    data2[1].reinit(5);\n    data2[1](0) = 1.5;\n    data2[1](1) = 3.2;\n    data2[1](2) = 6.3;\n    data2[1](3) = 9.7;\n    data2[1](4) = 11.9;\n    data2[2].reinit(5);\n    data2[2](0) = 1.1;\n    data2[2](1) = 3.1;\n    data2[2](2) = 6.1;\n    data2[2](3) = 9.1;\n    data2[2](4) = 11.1;\n\n    da._sim_size = 5;\n    dealii::FullMatrix<double> cov2 = da.calc_sample_covariance_dense(data2);\n\n    BOOST_CHECK_CLOSE(cov2(0, 0), 0.07, tol);\n    BOOST_CHECK_CLOSE(cov2(1, 0), 0.025, tol);\n    BOOST_CHECK_CLOSE(cov2(2, 0), 0.04, tol);\n    BOOST_CHECK_CLOSE(cov2(3, 0), 0.1, tol);\n    BOOST_CHECK_CLOSE(cov2(4, 0), 0.13, tol);\n    BOOST_CHECK_CLOSE(cov2(0, 1), 0.025, tol);\n    BOOST_CHECK_CLOSE(cov2(1, 1), 0.01, tol);\n    BOOST_CHECK_CLOSE(cov2(2, 1), 0.015, tol);\n    BOOST_CHECK_CLOSE(cov2(3, 1), 0.035, tol);\n    BOOST_CHECK_CLOSE(cov2(4, 1), 0.045, tol);\n    BOOST_CHECK_CLOSE(cov2(0, 2), 0.04, tol);\n    BOOST_CHECK_CLOSE(cov2(1, 2), 0.015, tol);\n    BOOST_CHECK_CLOSE(cov2(2, 2), 0.02333333333333, tol);\n    BOOST_CHECK_CLOSE(cov2(3, 2), 0.05666666666667, tol);\n    BOOST_CHECK_CLOSE(cov2(4, 2), 0.07333333333333, tol);\n    BOOST_CHECK_CLOSE(cov2(0, 3), 0.1, tol);\n    BOOST_CHECK_CLOSE(cov2(1, 3), 0.035, tol);\n    BOOST_CHECK_CLOSE(cov2(2, 3), 0.05666666666667, tol);\n    BOOST_CHECK_CLOSE(cov2(3, 3), 0.14333333333333, tol);\n    BOOST_CHECK_CLOSE(cov2(4, 3), 0.18666666666667, tol);\n    BOOST_CHECK_CLOSE(cov2(0, 4), 0.13, tol);\n    BOOST_CHECK_CLOSE(cov2(1, 4), 0.045, tol);\n    BOOST_CHECK_CLOSE(cov2(2, 4), 0.07333333333333, tol);\n    BOOST_CHECK_CLOSE(cov2(3, 4), 0.18666666666667, tol);\n    BOOST_CHECK_CLOSE(cov2(4, 4), 0.24333333333333, tol);\n  };\n\n  void test_fill_noise_vector()\n  {\n    boost::property_tree::ptree solver_settings_database;\n    DataAssimilator da(solver_settings_database);\n\n    dealii::SparsityPattern pattern(3, 3, 3);\n    pattern.add(0, 0);\n    pattern.add(1, 0);\n    pattern.add(1, 1);\n    pattern.add(0, 1);\n    pattern.add(2, 2);\n    pattern.compress();\n\n    dealii::SparseMatrix<double> R(pattern);\n\n    R.add(0, 0, 0.1);\n    R.add(1, 0, 0.3);\n    R.add(1, 1, 1.0);\n    R.add(0, 1, 0.3);\n    R.add(2, 2, 0.2);\n\n    std::vector<dealii::Vector<double>> data;\n    dealii::Vector<double> ensemble_member(3);\n    for (unsigned int i = 0; i < 1000; ++i)\n    {\n      da.fill_noise_vector(ensemble_member, R);\n      data.push_back(ensemble_member);\n    }\n\n    dealii::FullMatrix<double> Rtest = da.calc_sample_covariance_dense(data);\n\n    double tol = 20.; // Loose 20% tolerance because this is a statistical check\n    BOOST_CHECK_CLOSE(R(0, 0), Rtest(0, 0), tol);\n    BOOST_CHECK_CLOSE(R(1, 0), Rtest(1, 0), tol);\n    BOOST_CHECK_CLOSE(R(1, 1), Rtest(1, 1), tol);\n    BOOST_CHECK_CLOSE(R(0, 1), Rtest(0, 1), tol);\n    BOOST_CHECK_CLOSE(R(2, 2), Rtest(2, 2), tol);\n  };\n\n  void test_update_ensemble()\n  {\n    // Create the DoF mapping\n    MPI_Comm communicator = MPI_COMM_WORLD;\n\n    boost::property_tree::ptree database;\n    database.put(\"import_mesh\", false);\n    database.put(\"length\", 1);\n    database.put(\"length_divisions\", 2);\n    database.put(\"height\", 1);\n    database.put(\"height_divisions\", 2);\n    adamantine::Geometry<2> geometry(communicator, database);\n    dealii::parallel::distributed::Triangulation<2> const &tria =\n        geometry.get_triangulation();\n\n    dealii::FE_Q<2> fe(1);\n    dealii::DoFHandler<2> dof_handler(tria);\n    dof_handler.distribute_dofs(fe);\n\n    int sim_size = 5;\n    int expt_size = 2;\n\n    std::vector<double> expt_vec(2);\n    expt_vec[0] = 2.5;\n    expt_vec[1] = 9.5;\n\n    std::pair<std::vector<int>, std::vector<int>> indices_and_offsets;\n    indices_and_offsets.first.resize(2);\n    indices_and_offsets.second.resize(3); // Offset vector is one longer\n    indices_and_offsets.first[0] = 1;\n    indices_and_offsets.first[1] = 3;\n    indices_and_offsets.second[0] = 0;\n    indices_and_offsets.second[1] = 1;\n    indices_and_offsets.second[2] = 2;\n\n    boost::property_tree::ptree solver_settings_database;\n    DataAssimilator da(solver_settings_database);\n    da._sim_size = sim_size;\n    da._expt_size = expt_size;\n    da._num_ensemble_members = 3;\n\n    da.update_dof_mapping<2>(dof_handler, indices_and_offsets);\n\n    // Create the simulation data\n    std::vector<dealii::LA::distributed::Vector<double>> data(3);\n    data[0].reinit(5);\n    data[0](0) = 1.0;\n    data[0](1) = 3.0;\n    data[0](2) = 6.0;\n    data[0](3) = 9.0;\n    data[0](4) = 11.0;\n    data[1].reinit(5);\n    data[1](0) = 1.5;\n    data[1](1) = 3.2;\n    data[1](2) = 6.3;\n    data[1](3) = 9.7;\n    data[1](4) = 11.9;\n    data[2].reinit(5);\n    data[2](0) = 1.1;\n    data[2](1) = 3.1;\n    data[2](2) = 6.1;\n    data[2](3) = 9.1;\n    data[2](4) = 11.1;\n\n    // Build the sparse experimental covariance matrix\n    dealii::SparsityPattern pattern(expt_size, expt_size, 1);\n    pattern.add(0, 0);\n    pattern.add(1, 1);\n    pattern.compress();\n\n    dealii::SparseMatrix<double> R(pattern);\n    R.add(0, 0, 0.002);\n    R.add(1, 1, 0.001);\n\n    // Save the data at the observation points before assimilation\n    std::vector<double> sim_at_expt_pt_1_before(3);\n    sim_at_expt_pt_1_before.push_back(data[0][1]);\n    sim_at_expt_pt_1_before.push_back(data[1][1]);\n    sim_at_expt_pt_1_before.push_back(data[2][1]);\n\n    std::vector<double> sim_at_expt_pt_2_before(3);\n    sim_at_expt_pt_2_before.push_back(data[0][3]);\n    sim_at_expt_pt_2_before.push_back(data[1][3]);\n    sim_at_expt_pt_2_before.push_back(data[2][3]);\n\n    // Update the simulation data\n    da.update_ensemble(data, expt_vec, R);\n\n    // Save the data at the observation points after assimilation\n    std::vector<double> sim_at_expt_pt_1_after(3);\n    sim_at_expt_pt_1_after.push_back(data[0][1]);\n    sim_at_expt_pt_1_after.push_back(data[1][1]);\n    sim_at_expt_pt_1_after.push_back(data[2][1]);\n\n    std::vector<double> sim_at_expt_pt_2_after(3);\n    sim_at_expt_pt_2_after.push_back(data[0][3]);\n    sim_at_expt_pt_2_after.push_back(data[1][3]);\n    sim_at_expt_pt_2_after.push_back(data[2][3]);\n\n    // Check the solution\n    // The observed points should get closer to the experimental values\n    // Large entries in R could make these fail spuriously\n    for (int member = 0; member < 3; ++member)\n    {\n      BOOST_CHECK(std::abs(expt_vec[0] - sim_at_expt_pt_1_after[member]) <=\n                  std::abs(expt_vec[0] - sim_at_expt_pt_1_before[member]));\n      BOOST_CHECK(std::abs(expt_vec[1] - sim_at_expt_pt_2_after[member]) <=\n                  std::abs(expt_vec[1] - sim_at_expt_pt_2_before[member]));\n    }\n  };\n};\n\nBOOST_AUTO_TEST_CASE(data_assimilator)\n{\n  DataAssimilatorTester dat;\n\n  dat.test_constructor();\n  dat.test_update_dof_mapping();\n  dat.test_calc_sample_covariance_dense();\n  dat.test_fill_noise_vector();\n  dat.test_calc_H();\n  dat.test_calc_Hx();\n  dat.test_calc_kalman_gain();\n  dat.test_update_ensemble();\n}\n} // namespace adamantine\n", "meta": {"hexsha": "9e68687847ee7bab0d68841e312fadb6259e7944", "size": 19040, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/test_data_assimilator.cc", "max_stars_repo_name": "Rombur/adamantine", "max_stars_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-09-03T02:08:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T01:26:41.000Z", "max_issues_repo_path": "tests/test_data_assimilator.cc", "max_issues_repo_name": "Rombur/adamantine", "max_issues_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 74.0, "max_issues_repo_issues_event_min_datetime": "2016-08-31T18:10:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T01:51:44.000Z", "max_forks_repo_path": "tests/test_data_assimilator.cc", "max_forks_repo_name": "Rombur/adamantine", "max_forks_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-12T15:43:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-19T02:58:56.000Z", "avg_line_length": 33.2286212914, "max_line_length": 80, "alphanum_fraction": 0.6592436975, "num_tokens": 6254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.5198137038161534}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2014 Benoit Dequidt <benoit.dequidt@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://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#include <iostream>\n#include <cstdlib>\n\n#include <boost/compute/core.hpp>\n#include <boost/compute/algorithm/copy.hpp>\n#include <boost/compute/algorithm/inclusive_scan.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/type_traits/type_name.hpp>\n#include <boost/compute/utility/source.hpp>\n\nnamespace compute = boost::compute;\n\n/// warning precision is not precise due\n/// to the float error accumulation when size is large enough\n/// for more precision use double\n/// or a kahan sum else results can diverge\n/// from the CPU implementation\ncompute::program make_sma_program(const compute::context &context)\n{\n    const char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(\n        __kernel void SMA(__global const float *scannedValues, int size, __global float *output, int wSize) {\n            const int gid = get_global_id(0);\n\n            float cumValues = 0.f;\n            int endIdx = gid + wSize / 2;\n            int startIdx = gid - 1 - wSize / 2;\n\n            if (endIdx > size - 1)\n                endIdx = size - 1;\n\n            cumValues += scannedValues[endIdx];\n            if (startIdx < 0)\n                startIdx = -1;\n            else\n                cumValues -= scannedValues[startIdx];\n\n            output[gid] = (float)(cumValues / (float)(endIdx - startIdx));\n        });\n\n    // create sma program\n    return compute::program::build_with_source(source, context);\n}\n\nbool check_results(const std::vector<float, mi_stl_allocator<float>> &values, const std::vector<float, mi_stl_allocator<float>> &smoothValues, unsigned int wSize)\n{\n    int size = values.size();\n    if (size != (int)smoothValues.size())\n        return false;\n\n    int semiWidth = wSize / 2;\n\n    bool ret = true;\n    for (int idx = 0; idx < size; ++idx)\n    {\n        int start = (std::max)(idx - semiWidth, 0);\n        int end = (std::min)(idx + semiWidth, size - 1);\n        float res = 0;\n        for (int j = start; j <= end; ++j)\n        {\n            res += values[j];\n        }\n\n        res /= float(end - start + 1);\n\n        if (std::abs(res - smoothValues[idx]) > 1e-3)\n        {\n            std::cout << \"idx = \" << idx << \" -- expected = \" << res << \" -- result = \" << smoothValues[idx] << std::endl;\n            ret = false;\n        }\n    }\n\n    return ret;\n}\n\n// generate a uniform law over [0,10]\nfloat myRand()\n{\n    static const double divisor = double(RAND_MAX) + 1.;\n    return double(rand()) / divisor * 10.;\n}\n\nint main()\n{\n    unsigned int size = 1024;\n    // wSize must be odd\n    unsigned int wSize = 21;\n    // get the default device\n    compute::device device = compute::system::default_device();\n    // create a context for the device\n    compute::context context(device);\n    // get the program\n    compute::program program = make_sma_program(context);\n\n    // create vector of random numbers on the host\n    std::vector<float, mi_stl_allocator<float>> host_vector(size);\n    std::vector<float, mi_stl_allocator<float>> host_result(size);\n    std::generate(host_vector.begin(), host_vector.end(), myRand);\n\n    compute::vector<float> a(size, context);\n    compute::vector<float> b(size, context);\n    compute::vector<float> c(size, context);\n    compute::command_queue queue(context, device);\n\n    compute::copy(host_vector.begin(), host_vector.end(), a.begin(), queue);\n\n    // scan values\n    compute::inclusive_scan(a.begin(), a.end(), b.begin(), queue);\n    // sma kernel\n    compute::kernel kernel(program, \"SMA\");\n    kernel.set_arg(0, b.get_buffer());\n    kernel.set_arg(1, (int)b.size());\n    kernel.set_arg(2, c.get_buffer());\n    kernel.set_arg(3, (int)wSize);\n\n    using compute::uint_;\n    uint_ tpb = 128;\n    uint_ workSize = size;\n    queue.enqueue_1d_range_kernel(kernel, 0, workSize, tpb);\n\n    compute::copy(c.begin(), c.end(), host_result.begin(), queue);\n\n    bool res = check_results(host_vector, host_result, wSize);\n    std::string status = res ? \"results are equivalent\" : \"GPU results differs from CPU one's\";\n    std::cout << status << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "38acf0ee10ea8b4d4e4cefcc8cf8b7600f707e52", "size": 4474, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "compute/example/simple_moving_average.cpp", "max_stars_repo_name": "atksh/mimalloc-lgb", "max_stars_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "compute/example/simple_moving_average.cpp", "max_issues_repo_name": "atksh/mimalloc-lgb", "max_issues_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compute/example/simple_moving_average.cpp", "max_forks_repo_name": "atksh/mimalloc-lgb", "max_forks_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_forks_repo_licenses": ["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": 162, "alphanum_fraction": 0.608180599, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5198086483534902}}
{"text": "//  Copyright (c) 2015 Boost.Test team\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 tolerance_06\n#include <boost/test/included/unit_test.hpp>\nnamespace utf = boost::unit_test;\nnamespace tt = boost::test_tools;\n\nBOOST_AUTO_TEST_CASE(test1, * utf::tolerance(0.1415 / 3)) // == 0.047166667\n{\n  double x = 3.141592404915836;\n  // x is 'double' which is tolerance based, 3 is 'int' which is arithmetic:\n  // tolerance based comparison will be used.\n  // Type of tolerance for this comparison will be boost::common_type<double, int>::type == double\n  // Value for this tolerance type is set by the decorator.\n  BOOST_TEST(x == 3);\n}\n//]\n", "meta": {"hexsha": "04389d4fd4f25d152b96bcf6a80b941896b3cb9f", "size": 855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/boost_1_71_0/libs/test/doc/examples/tolerance_06.run-fail.cpp", "max_stars_repo_name": "anonymouscode1/djxperf", "max_stars_repo_head_hexsha": "b6073a761753aa7a6247f2618977ca3a2633e78a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T11:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T03:08:16.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/test/doc/examples/tolerance_06.run-fail.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 266.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T02:03:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:22:12.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/test/doc/examples/tolerance_06.run-fail.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 185.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T18:09:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T18:07:05.000Z", "avg_line_length": 35.625, "max_line_length": 98, "alphanum_fraction": 0.7239766082, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5198086408492311}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 1999 - 2015 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 at\n * the top level of the deal.II distribution.\n *\n * ---------------------------------------------------------------------\n *\n * based on deal.II step-2\n */\n\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_renumbering.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_q.h>\n\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/manifold_lib.h>\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#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/sparse_matrix.h>\n\n#include <fstream>\n\nusing namespace dealii;\n\n\nvoid\nmake_grid(Triangulation<2> &triangulation)\n{\n  const Point<2> center(1, 0);\n  const double   inner_radius = 0.5, outer_radius = 1.0;\n  GridGenerator::hyper_shell(\n    triangulation, center, inner_radius, outer_radius, 5);\n\n  static const SphericalManifold<2> manifold_description(center);\n  triangulation.set_all_manifold_ids(0);\n  triangulation.set_manifold(0, manifold_description);\n\n  for (unsigned int step = 0; step < 3; ++step)\n    {\n      Triangulation<2>::active_cell_iterator cell =\n                                               triangulation.begin_active(),\n                                             endc = triangulation.end();\n\n      for (; cell != endc; ++cell)\n        for (unsigned int v = 0; v < GeometryInfo<2>::vertices_per_cell; ++v)\n          {\n            const double distance_from_center =\n              center.distance(cell->vertex(v));\n\n            if (std::fabs(distance_from_center - inner_radius) < 1e-10)\n              {\n                cell->set_refine_flag();\n                break;\n              }\n          }\n\n      triangulation.execute_coarsening_and_refinement();\n    }\n}\n\nvoid\nmake_square_grid(Triangulation<2> &triangulation)\n{\n  GridGenerator::hyper_cube(triangulation);\n  triangulation.refine_global(3);\n}\n\n\n\nSparsityPattern\ndistribute_dofs(DoFHandler<2> &dof_handler)\n{\n  static const FE_Q<2> finite_element(1);\n  dof_handler.distribute_dofs(finite_element);\n\n  DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs(),\n                                                  dof_handler.n_dofs());\n\n  DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern);\n\n  SparsityPattern sparsity_pattern;\n  sparsity_pattern.copy_from(dynamic_sparsity_pattern);\n\n  std::ofstream out(\"sparsity_pattern1.svg\");\n  sparsity_pattern.print_svg(out);\n\n  return sparsity_pattern;\n}\n\n\n\nSparsityPattern\nrenumber_dofs(DoFHandler<2> &dof_handler)\n{\n  DoFRenumbering::Cuthill_McKee(dof_handler);\n\n  DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs(),\n                                                  dof_handler.n_dofs());\n  DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern);\n\n  SparsityPattern sparsity_pattern;\n  sparsity_pattern.copy_from(dynamic_sparsity_pattern);\n\n  std::ofstream out(\"sparsity_pattern2.svg\");\n  sparsity_pattern.print_svg(out);\n\n  return sparsity_pattern;\n}\n\nvoid\nrow_lenths(const SparsityPattern &sparsity_pattern)\n{\n  for (unsigned int i = 0; i < sparsity_pattern.n_rows(); i++)\n    {\n      std::cout << \"Row\" << i << \"- - row length \"\n                << sparsity_pattern.row_length(i) << std::endl;\n    }\n}\n\nstd::tuple<int, int, double, double>\ncompute_pattern_statistics(const SparsityPattern &sparsity_pattern)\n{\n  double avarage_per_row = 0.;\n  for (unsigned int i = 0; i < sparsity_pattern.n_rows(); i++)\n    {\n      avarage_per_row += sparsity_pattern.row_length(i);\n    }\n\n  double fill_ratio = avarage_per_row / (double)(sparsity_pattern.n_rows() *\n                                                 sparsity_pattern.n_cols());\n  avarage_per_row /= (double)sparsity_pattern.n_rows();\n  return std::make_tuple(sparsity_pattern.n_rows(),\n                         sparsity_pattern.bandwidth(),\n                         avarage_per_row,\n                         fill_ratio);\n}\n\n\nint\nmain()\n{\n  Triangulation<2> triangulation;\n  // make_grid(triangulation);\n  make_square_grid(triangulation);\n\n  DoFHandler<2> dof_handler(triangulation);\n\n  auto sparcity_pattern  = distribute_dofs(dof_handler);\n  auto sparcity_pattern2 = renumber_dofs(dof_handler);\n\n  row_lenths(sparcity_pattern2);\n\n  std::cout << sparcity_pattern.row_length(41) << std::endl;\n\n  auto patern_statistics = compute_pattern_statistics(sparcity_pattern2);\n  std::cout << std::get<0>(patern_statistics) << \" \"\n            << std::get<1>(patern_statistics) << \"  \"\n            << std::get<2>(patern_statistics) << \"  \"\n            << std::get<3>(patern_statistics) << std::endl;\n}\n", "meta": {"hexsha": "06bcd86323a5c557ca30ccb5b9b7c7ee87a92c16", "size": 5115, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/step-2.cc", "max_stars_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-iprusak", "max_stars_repo_head_hexsha": "34b732221edd3bd5b040670167dafa7e923a409a", "max_stars_repo_licenses": ["MIT"], "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/step-2.cc", "max_issues_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-iprusak", "max_issues_repo_head_hexsha": "34b732221edd3bd5b040670167dafa7e923a409a", "max_issues_repo_licenses": ["MIT"], "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/step-2.cc", "max_forks_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-iprusak", "max_forks_repo_head_hexsha": "34b732221edd3bd5b040670167dafa7e923a409a", "max_forks_repo_licenses": ["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.2285714286, "max_line_length": 77, "alphanum_fraction": 0.6506353861, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5198086337581436}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2014 Roshan <thisisroshansmail@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://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestDiscreteDistribution\n#include <boost/test/unit_test.hpp>\n\n#include <vector>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/algorithm/count_if.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/random/default_random_engine.hpp>\n#include <boost/compute/random/discrete_distribution.hpp>\n#include <boost/compute/lambda.hpp>\n\n#include \"context_setup.hpp\"\n\nBOOST_AUTO_TEST_CASE(discrete_distribution_doctest)\n{\n    using boost::compute::uint_;\n    using boost::compute::lambda::_1;\n\n    boost::compute::vector<uint_> vec(100, context);\n\n    //! [generate]\n    // initialize the default random engine\n    boost::compute::default_random_engine engine(queue);\n\n    // initialize weights\n    int weights[] = {2, 2};\n\n    // setup the discrete distribution to produce integers 0 and 1\n    // with equal weights\n    boost::compute::discrete_distribution<uint_> distribution(weights, weights + 2);\n\n    // generate the random values and store them to 'vec'\n    distribution.generate(vec.begin(), vec.end(), engine, queue);\n    // ! [generate]\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::count_if(\n            vec.begin(), vec.end(), _1 > 1, queue),\n        size_t(0));\n}\n\nBOOST_AUTO_TEST_CASE(discrete_distribution)\n{\n    using boost::compute::uint_;\n    using boost::compute::lambda::_1;\n\n    size_t size = 100;\n    boost::compute::vector<uint_> vec(size, context);\n\n    // initialize the default random engine\n    boost::compute::default_random_engine engine(queue);\n\n    // initialize weights\n    int weights[] = {10, 40, 40, 10};\n\n    // setup the discrete distribution\n    boost::compute::discrete_distribution<uint_> distribution(\n        weights, weights + 4);\n\n    std::vector<double, mi_stl_allocator<double>> p = distribution.probabilities();\n    BOOST_CHECK_CLOSE(p[0], double(0.1), 0.001);\n    BOOST_CHECK_CLOSE(p[1], double(0.4), 0.001);\n    BOOST_CHECK_CLOSE(p[2], double(0.4), 0.001);\n    BOOST_CHECK_CLOSE(p[3], double(0.1), 0.001);\n\n    BOOST_CHECK_EQUAL((distribution.min)(), uint_(0));\n    BOOST_CHECK_EQUAL((distribution.max)(), uint_(3));\n\n    // generate the random values and store them to 'vec'\n    distribution.generate(vec.begin(), vec.end(), engine, queue);\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::count_if(\n            vec.begin(), vec.end(), _1 < 4, queue),\n        size);\n}\n\nBOOST_AUTO_TEST_CASE(discrete_distribution_default_ctor)\n{\n    using boost::compute::uint_;\n    using boost::compute::lambda::_1;\n\n    size_t size = 100;\n    boost::compute::vector<uint_> vec(size, context);\n\n    // initialize the default random engine\n    boost::compute::default_random_engine engine(queue);\n\n    // call default constructor\n    boost::compute::discrete_distribution<uint_> distribution;\n\n    std::vector<double, mi_stl_allocator<double>> p = distribution.probabilities();\n    BOOST_CHECK_CLOSE(p[0], double(1), 0.001);\n\n    // generate the random values and store them to 'vec'\n    distribution.generate(vec.begin(), vec.end(), engine, queue);\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::count_if(\n            vec.begin(), vec.end(), _1 == 0, queue),\n        size);\n}\n\nBOOST_AUTO_TEST_CASE(discrete_distribution_one_weight)\n{\n    using boost::compute::uint_;\n    using boost::compute::lambda::_1;\n\n    size_t size = 100;\n    boost::compute::vector<uint_> vec(size, context);\n\n    // initialize the default random engine\n    boost::compute::default_random_engine engine(queue);\n\n    std::vector<int, mi_stl_allocator<int>> weights(1, 1);\n    // call default constructor\n    boost::compute::discrete_distribution<uint_> distribution(\n        weights.begin(), weights.end());\n\n    std::vector<double, mi_stl_allocator<double>> p = distribution.probabilities();\n    BOOST_CHECK_CLOSE(p[0], double(1), 0.001);\n\n    BOOST_CHECK_EQUAL((distribution.min)(), uint_(0));\n    BOOST_CHECK_EQUAL((distribution.max)(), uint_(0));\n\n    // generate the random values and store them to 'vec'\n    distribution.generate(vec.begin(), vec.end(), engine, queue);\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::count_if(\n            vec.begin(), vec.end(), _1 == 0, queue),\n        size);\n}\n\nBOOST_AUTO_TEST_CASE(discrete_distribution_empty_weights)\n{\n    using boost::compute::uint_;\n    using boost::compute::lambda::_1;\n\n    size_t size = 100;\n    boost::compute::vector<uint_> vec(size, context);\n\n    // initialize the default random engine\n    boost::compute::default_random_engine engine(queue);\n\n    std::vector<int, mi_stl_allocator<int>> weights;\n    // weights.begin() == weights.end()\n    boost::compute::discrete_distribution<uint_> distribution(\n        weights.begin(), weights.end());\n\n    std::vector<double, mi_stl_allocator<double>> p = distribution.probabilities();\n    BOOST_CHECK_CLOSE(p[0], double(1), 0.001);\n\n    BOOST_CHECK_EQUAL((distribution.min)(), uint_(0));\n    BOOST_CHECK_EQUAL((distribution.max)(), uint_(0));\n\n    // generate the random values and store them to 'vec'\n    distribution.generate(vec.begin(), vec.end(), engine, queue);\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::count_if(\n            vec.begin(), vec.end(), _1 == 0, queue),\n        size);\n}\n\nBOOST_AUTO_TEST_CASE(discrete_distribution_uchar)\n{\n    using boost::compute::uchar_;\n    using boost::compute::uint_;\n    using boost::compute::lambda::_1;\n\n    size_t size = 100;\n    boost::compute::vector<uchar_> uchar_vec(size, context);\n    boost::compute::vector<uint_> uint_vec(size, context);\n\n    // initialize the default random engine\n    boost::compute::default_random_engine engine(queue);\n\n    // initialize weights\n    std::vector<int, mi_stl_allocator<int>> weights(258, 0);\n    weights[257] = 1;\n\n    // setup the discrete distribution\n    boost::compute::discrete_distribution<uchar_> distribution(\n        weights.begin(), weights.end());\n\n    BOOST_CHECK_EQUAL((distribution.min)(), uchar_(0));\n    BOOST_CHECK_EQUAL((distribution.max)(), uchar_(255));\n\n    // generate the random uchar_ values to the uchar_ vector\n    distribution.generate(uchar_vec.begin(), uchar_vec.end(), engine, queue);\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::count_if(\n            uchar_vec.begin(), uchar_vec.end(), _1 == uchar_(1), queue),\n        size);\n\n    // generate the random uchar_ values to the uint_ vector\n    distribution.generate(uint_vec.begin(), uint_vec.end(), engine, queue);\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::count_if(\n            uint_vec.begin(), uint_vec.end(), _1 == uint_(1), queue),\n        size);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c0b2d2c487589f85b4e29bb845d1ec08b0a30903", "size": 7030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "compute/test/test_discrete_distribution.cpp", "max_stars_repo_name": "atksh/mimalloc-lgb", "max_stars_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "compute/test/test_discrete_distribution.cpp", "max_issues_repo_name": "atksh/mimalloc-lgb", "max_issues_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compute/test/test_discrete_distribution.cpp", "max_forks_repo_name": "atksh/mimalloc-lgb", "max_forks_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_forks_repo_licenses": ["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.9545454545, "max_line_length": 84, "alphanum_fraction": 0.6684210526, "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5198086311190002}}
{"text": "#pragma once\n\n#include <cstdint>\n#include <functional>\n#include <limits>\n#include <stdexcept>\n#include <vector>\n\n#include <Eigen/Geometry>\n\nnamespace common_robotics_utilities\n{\nnamespace simple_dtw\n{\ntemplate<typename FirstDatatype, typename SecondDatatype,\n         typename FirstContainer=std::vector<FirstDatatype>,\n         typename SecondContainer=std::vector<SecondDatatype>>\nclass SimpleDTW\n{\nprotected:\n  void InitializeMatrix(const ssize_t first_sequence_size,\n                        const ssize_t second_sequence_size)\n  {\n    const ssize_t rows = first_sequence_size + 1;\n    const ssize_t cols = second_sequence_size + 1;\n    if (dtw_matrix_.rows() < rows || dtw_matrix_.cols() < cols)\n    {\n      dtw_matrix_ = Eigen::MatrixXd::Zero(rows, cols);\n      if (rows > 1 && cols > 1)\n      {\n        for (ssize_t row = 1; row < rows; row++)\n        {\n          dtw_matrix_(row, 0) = std::numeric_limits<double>::infinity();\n        }\n        for (ssize_t col = 1; col < cols; col++)\n        {\n          dtw_matrix_(0, col) = std::numeric_limits<double>::infinity();\n        }\n      }\n    }\n  }\n\n  Eigen::MatrixXd dtw_matrix_;\n\npublic:\n  SimpleDTW()\n  {\n    InitializeMatrix(0, 0);\n  }\n\n  SimpleDTW(const ssize_t first_sequence_size,\n            const ssize_t second_sequence_size)\n  {\n    InitializeMatrix(first_sequence_size, second_sequence_size);\n  }\n\n  double EvaluateWarpingCost(\n      const FirstContainer& first_sequence,\n      const SecondContainer& second_sequence,\n      const std::function<double(const FirstDatatype&,\n                                 const SecondDatatype&)>& distance_fn)\n  {\n    if (first_sequence.empty())\n    {\n      throw std::invalid_argument(\"first_sequence is empty\");\n    }\n    if (second_sequence.empty())\n    {\n      throw std::invalid_argument(\"second_sequence is empty\");\n    }\n    const ssize_t first_sequence_size\n        = static_cast<ssize_t>(first_sequence.size());\n    const ssize_t second_sequence_size\n        = static_cast<ssize_t>(second_sequence.size());\n    InitializeMatrix(first_sequence_size, second_sequence_size);\n    //Compute DTW cost for the two sequences\n    for (ssize_t i = 1; i <= first_sequence_size; i++)\n    {\n      const FirstDatatype& first_item\n          = first_sequence[static_cast<size_t>(i) - 1];\n      for (ssize_t j = 1; j <= second_sequence_size; j++)\n      {\n        const SecondDatatype& second_item\n            = second_sequence[static_cast<size_t>(j) - 1];\n        const double index_cost = distance_fn(first_item, second_item);\n        double prev_cost = 0.0;\n        // Get the next neighboring values from the matrix to use for the update\n        double im1j = dtw_matrix_(i - 1, j);\n        double im1jm1 = dtw_matrix_(i - 1, j - 1);\n        double ijm1 = dtw_matrix_(i, j - 1);\n        // Start the update step\n        if (im1j < im1jm1 && im1j < ijm1)\n        {\n          prev_cost = im1j;\n        }\n        else if (ijm1 < im1j && ijm1 < im1jm1)\n        {\n          prev_cost = ijm1;\n        }\n        else\n        {\n          prev_cost = im1jm1;\n        }\n        // Update the value in the matrix\n        const double new_cost = index_cost + prev_cost;\n        dtw_matrix_(i, j) = new_cost;\n      }\n    }\n    //Return total path cost\n    const double warping_cost\n        = dtw_matrix_(first_sequence_size, second_sequence_size);\n    return warping_cost;\n  }\n};\n\ntemplate<typename FirstDatatype, typename SecondDatatype,\n         typename FirstContainer=std::vector<FirstDatatype>,\n         typename SecondContainer=std::vector<SecondDatatype>>\ninline double EvaluateWarpingCost(\n    const FirstContainer& first_sequence,\n    const SecondContainer& second_sequence,\n    const std::function<double(const FirstDatatype&,\n                               const SecondDatatype&)>& distance_fn)\n{\n  SimpleDTW<FirstDatatype, SecondDatatype,\n            FirstContainer, SecondContainer> dtw_evaluator;\n  return dtw_evaluator.EvaluateWarpingCost(\n      first_sequence, second_sequence, distance_fn);\n}\n}  // namespace simple_dtw\n}  // namespace common_robotics_utilities\n", "meta": {"hexsha": "246d1122b2586189924fae88f550ba68460df271", "size": 4061, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common_robotics_utilities/simple_dtw.hpp", "max_stars_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_stars_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/common_robotics_utilities/simple_dtw.hpp", "max_issues_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_issues_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/common_robotics_utilities/simple_dtw.hpp", "max_forks_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_forks_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7651515152, "max_line_length": 80, "alphanum_fraction": 0.6456537799, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5198086262538846}}
{"text": "#include \"neuralnet/magnitude.h\"\n#include \"streams.h\"\n\n#include <iostream>\n#include <boost/test/unit_test.hpp>\n\n// -----------------------------------------------------------------------------\n// Magnitude\n// -----------------------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE(Magnitude)\n\nBOOST_AUTO_TEST_CASE(it_initializes_to_zero_magnitude)\n{\n    const NN::Magnitude mag = NN::Magnitude::Zero();\n\n    BOOST_CHECK_EQUAL(mag.Scaled(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(it_initializes_to_zero_when_rounding_invalid_magnitudes)\n{\n    // Negative\n    const NN::Magnitude negative = NN::Magnitude::RoundFrom(-1.234);\n    BOOST_CHECK_EQUAL(negative.Scaled(), 0);\n\n    // Rounds-down to zero\n    const NN::Magnitude effectivly_zero = NN::Magnitude::RoundFrom(0.005);\n    BOOST_CHECK_EQUAL(effectivly_zero.Scaled(), 0);\n\n    // Exceeded maximum\n    const NN::Magnitude overflow = NN::Magnitude::RoundFrom(32767.123);\n    BOOST_CHECK_EQUAL(overflow.Scaled(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(it_rounds_a_small_magnitude_to_two_places)\n{\n    const NN::Magnitude min = NN::Magnitude::RoundFrom(0.0051);\n    BOOST_CHECK_EQUAL(min.Scaled(), 1);\n\n    const NN::Magnitude max = NN::Magnitude::RoundFrom(0.994);\n    BOOST_CHECK_EQUAL(max.Scaled(), 99);\n}\n\nBOOST_AUTO_TEST_CASE(it_rounds_a_medium_magnitude_to_one_place)\n{\n    const NN::Magnitude min = NN::Magnitude::RoundFrom(0.995);\n    BOOST_CHECK_EQUAL(min.Scaled(), 100);\n\n    const NN::Magnitude max = NN::Magnitude::RoundFrom(9.94);\n    BOOST_CHECK_EQUAL(max.Scaled(), 990);\n}\n\nBOOST_AUTO_TEST_CASE(it_rounds_a_large_magnitude_to_a_whole)\n{\n    const NN::Magnitude min = NN::Magnitude::RoundFrom(9.95);\n    BOOST_CHECK_EQUAL(min.Scaled(), 1000);\n\n    const NN::Magnitude max = NN::Magnitude::RoundFrom(32767.0);\n    BOOST_CHECK_EQUAL(max.Scaled(), 3276700);\n}\n\nBOOST_AUTO_TEST_CASE(it_compares_another_magnitude_for_equality)\n{\n    const NN::Magnitude magnitude1 = NN::Magnitude::RoundFrom(1.23);\n    const NN::Magnitude magnitude2 = NN::Magnitude::RoundFrom(1.23);\n\n    BOOST_CHECK(magnitude1 == magnitude2);\n    BOOST_CHECK(magnitude1 != NN::Magnitude::Zero());\n}\n\nBOOST_AUTO_TEST_CASE(it_compares_an_integer_for_equality)\n{\n    const NN::Magnitude magnitude = NN::Magnitude::RoundFrom(123);\n\n    BOOST_CHECK(magnitude == 123);\n    BOOST_CHECK(magnitude != 999);\n}\n\nBOOST_AUTO_TEST_CASE(it_compares_a_floating_point_number_for_equality)\n{\n    const NN::Magnitude magnitude = NN::Magnitude::RoundFrom(1.23);\n\n    // Floating-point comparisons round the other value according to the size\n    // for the precision tiers before checking equality:\n    BOOST_CHECK(magnitude == 1.23);\n    BOOST_CHECK(magnitude == 1.2);\n    BOOST_CHECK(magnitude == 1.25);\n    BOOST_CHECK(magnitude != 1.26);\n}\n\nBOOST_AUTO_TEST_CASE(it_reports_its_size_category)\n{\n    using Kind = NN::Magnitude::Kind;\n\n    const NN::Magnitude zero = NN::Magnitude::Zero();\n    BOOST_CHECK(zero.Which() == Kind::ZERO);\n\n    const NN::Magnitude effectively_zero = NN::Magnitude::RoundFrom(0.005);\n    BOOST_CHECK(effectively_zero.Which() == Kind::ZERO);\n\n    const NN::Magnitude min_small = NN::Magnitude::RoundFrom(0.0051);\n    BOOST_CHECK(min_small.Which() == Kind::SMALL);\n\n    const NN::Magnitude max_small = NN::Magnitude::RoundFrom(0.994);\n    BOOST_CHECK(max_small.Which() == Kind::SMALL);\n\n    const NN::Magnitude min_medium = NN::Magnitude::RoundFrom(0.995);\n    BOOST_CHECK(min_medium.Which() == Kind::MEDIUM);\n\n    const NN::Magnitude max_medium = NN::Magnitude::RoundFrom(9.94);\n    BOOST_CHECK(max_medium.Which() == Kind::MEDIUM);\n\n    const NN::Magnitude min_large = NN::Magnitude::RoundFrom(9.95);\n    BOOST_CHECK(min_large.Which() == Kind::LARGE);\n\n    const NN::Magnitude max_large = NN::Magnitude::RoundFrom(32767.0);\n    BOOST_CHECK(max_large.Which() == Kind::LARGE);\n}\n\nBOOST_AUTO_TEST_CASE(it_presents_the_scaled_magnitude_representation)\n{\n    const NN::Magnitude small = NN::Magnitude::RoundFrom(0.11);\n    BOOST_CHECK_EQUAL(small.Scaled(), 11);\n\n    const NN::Magnitude medium = NN::Magnitude::RoundFrom(1.1);\n    BOOST_CHECK_EQUAL(medium.Scaled(), 110);\n\n    const NN::Magnitude large = NN::Magnitude::RoundFrom(11.0);\n    BOOST_CHECK_EQUAL(large.Scaled(), 1100);\n}\n\nBOOST_AUTO_TEST_CASE(it_presents_the_compact_magnitude_representation)\n{\n    const NN::Magnitude small = NN::Magnitude::RoundFrom(0.11);\n    BOOST_CHECK_EQUAL(small.Compact(), 11);\n\n    const NN::Magnitude medium = NN::Magnitude::RoundFrom(1.1);\n    BOOST_CHECK_EQUAL(medium.Compact(), 11);\n\n    const NN::Magnitude large = NN::Magnitude::RoundFrom(11.0);\n    BOOST_CHECK_EQUAL(large.Compact(), 11);\n}\n\nBOOST_AUTO_TEST_CASE(it_presents_the_floatng_point_magnitude_representation)\n{\n    const NN::Magnitude small = NN::Magnitude::RoundFrom(0.11);\n    BOOST_CHECK_EQUAL(small.Floating(), 0.11);\n\n    const NN::Magnitude medium = NN::Magnitude::RoundFrom(1.1);\n    BOOST_CHECK_EQUAL(medium.Floating(), 1.1);\n\n    const NN::Magnitude large = NN::Magnitude::RoundFrom(11.0);\n    BOOST_CHECK_EQUAL(large.Floating(), 11.0);\n}\n\nBOOST_AUTO_TEST_CASE(it_represents_itself_as_a_string)\n{\n    const NN::Magnitude zero = NN::Magnitude::Zero();\n    BOOST_CHECK_EQUAL(zero.ToString(), \"0\");\n\n    const NN::Magnitude small = NN::Magnitude::RoundFrom(0.11);\n    BOOST_CHECK_EQUAL(small.ToString(), \"0.11\");\n\n    const NN::Magnitude medium = NN::Magnitude::RoundFrom(1.1);\n    BOOST_CHECK_EQUAL(medium.ToString(), \"1.1\");\n\n    const NN::Magnitude large = NN::Magnitude::RoundFrom(11.0);\n    BOOST_CHECK_EQUAL(large.ToString(), \"11\");\n\n    const NN::Magnitude max = NN::Magnitude::RoundFrom(32767.0);\n    BOOST_CHECK_EQUAL(max.ToString(), \"32767\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "1dfe51d94341e51739f9a8f0dc17f9e3fc63ca91", "size": 5680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/neuralnet/magnitude_tests.cpp", "max_stars_repo_name": "Ponce/Gridcoin-Research", "max_stars_repo_head_hexsha": "74d98ae376972d6e756f252b18dae4ac1c11adc2", "max_stars_repo_licenses": ["MIT"], "max_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/neuralnet/magnitude_tests.cpp", "max_issues_repo_name": "Ponce/Gridcoin-Research", "max_issues_repo_head_hexsha": "74d98ae376972d6e756f252b18dae4ac1c11adc2", "max_issues_repo_licenses": ["MIT"], "max_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/neuralnet/magnitude_tests.cpp", "max_forks_repo_name": "Ponce/Gridcoin-Research", "max_forks_repo_head_hexsha": "74d98ae376972d6e756f252b18dae4ac1c11adc2", "max_forks_repo_licenses": ["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.4571428571, "max_line_length": 80, "alphanum_fraction": 0.7017605634, "num_tokens": 1448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5198086187496254}}
{"text": "//=======================================================================\n// Copyright (c) 2018 Yi Ji\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\n#include <boost/graph/max_cardinality_matching.hpp>\n#include <boost/graph/maximum_weighted_matching.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/adjacency_matrix.hpp>\n#include <boost/core/lightweight_test.hpp>\n\nusing namespace boost;\n\ntypedef property< edge_weight_t, float, property< edge_index_t, int > >\n    EdgeProperty;\n\ntypedef adjacency_list< vecS, vecS, undirectedS,\n    property< vertex_index_t, int >, EdgeProperty >\n    undirected_graph;\ntypedef adjacency_list< listS, listS, undirectedS,\n    property< vertex_index_t, int >, EdgeProperty >\n    undirected_list_graph;\ntypedef adjacency_matrix< undirectedS, property< vertex_index_t, int >,\n    EdgeProperty >\n    undirected_adjacency_matrix_graph;\n\ntemplate < typename Graph > struct vertex_index_installer\n{\n    static void install(Graph&) {}\n};\n\ntemplate <> struct vertex_index_installer< undirected_list_graph >\n{\n    static void install(undirected_list_graph& g)\n    {\n        typedef graph_traits< undirected_list_graph >::vertex_iterator\n            vertex_iterator_t;\n        typedef graph_traits< undirected_list_graph >::vertices_size_type\n            v_size_t;\n\n        vertex_iterator_t vi, vi_end;\n        v_size_t i = 0;\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi, ++i)\n            put(vertex_index, g, *vi, i);\n    }\n};\n\ntemplate < typename Graph > void print_graph(const Graph& g)\n{\n    typedef typename graph_traits< Graph >::edge_iterator edge_iterator_t;\n    edge_iterator_t ei, ei_end;\n    std::cout << std::endl << \"The graph is: \" << std::endl;\n    for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n        std::cout << \"add_edge(\" << source(*ei, g) << \", \" << target(*ei, g)\n                  << \", EdgeProperty(\" << get(edge_weight, g, *ei) << \"), );\"\n                  << std::endl;\n}\n\ntemplate < typename Graph >\nvoid weighted_matching_test(const Graph& g,\n    typename property_traits< typename property_map< Graph,\n        edge_weight_t >::type >::value_type answer)\n{\n    typedef\n        typename property_map< Graph, vertex_index_t >::type vertex_index_map_t;\n    typedef vector_property_map<\n        typename graph_traits< Graph >::vertex_descriptor, vertex_index_map_t >\n        mate_t;\n    mate_t mate(num_vertices(g));\n    maximum_weighted_matching(g, mate);\n    bool same_result = (matching_weight_sum(g, mate) == answer);\n    BOOST_TEST(same_result);\n    if (!same_result)\n    {\n        mate_t max_mate(num_vertices(g));\n        brute_force_maximum_weighted_matching(g, max_mate);\n\n        std::cout << std::endl\n                  << \"Found a weighted matching of weight sum \"\n                  << matching_weight_sum(g, mate) << std::endl\n                  << \"While brute-force search found a weighted matching of \"\n                     \"weight sum \"\n                  << matching_weight_sum(g, max_mate) << std::endl;\n\n        typedef\n            typename graph_traits< Graph >::vertex_iterator vertex_iterator_t;\n        vertex_iterator_t vi, vi_end;\n\n        print_graph(g);\n\n        std::cout << std::endl << \"The algorithmic matching is:\" << std::endl;\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n            if (mate[*vi] != graph_traits< Graph >::null_vertex()\n                && *vi < mate[*vi])\n                std::cout << \"{\" << *vi << \", \" << mate[*vi] << \"}\"\n                          << std::endl;\n\n        std::cout << std::endl << \"The brute-force matching is:\" << std::endl;\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n            if (max_mate[*vi] != graph_traits< Graph >::null_vertex()\n                && *vi < max_mate[*vi])\n                std::cout << \"{\" << *vi << \", \" << max_mate[*vi] << \"}\"\n                          << std::endl;\n\n        std::cout << std::endl;\n    }\n}\n\ntemplate < typename Graph >\nGraph make_graph(typename graph_traits< Graph >::vertices_size_type num_v,\n    typename graph_traits< Graph >::edges_size_type num_e,\n    std::deque< std::size_t > input_edges)\n{\n    Graph g(num_v);\n    vertex_index_installer< Graph >::install(g);\n    for (std::size_t i = 0; i < num_e; ++i)\n    {\n        std::size_t src_v, tgt_v, edge_weight;\n        src_v = input_edges.front();\n        input_edges.pop_front();\n        tgt_v = input_edges.front();\n        input_edges.pop_front();\n        edge_weight = input_edges.front();\n        input_edges.pop_front();\n        add_edge(\n            vertex(src_v, g), vertex(tgt_v, g), EdgeProperty(edge_weight), g);\n    }\n    return g;\n}\n\nint main(int, char*[])\n{\n    std::ifstream in_file(\"weighted_matching.dat\");\n    std::string line;\n    while (std::getline(in_file, line))\n    {\n        std::istringstream in_graph(line);\n        std::size_t answer, num_v, num_e;\n        in_graph >> answer >> num_v >> num_e;\n\n        std::deque< std::size_t > input_edges;\n        std::size_t i;\n        while (in_graph >> i)\n            input_edges.push_back(i);\n\n        weighted_matching_test(\n            make_graph< undirected_graph >(num_v, num_e, input_edges), answer);\n        weighted_matching_test(\n            make_graph< undirected_list_graph >(num_v, num_e, input_edges),\n            answer);\n        weighted_matching_test(make_graph< undirected_adjacency_matrix_graph >(\n                                   num_v, num_e, input_edges),\n            answer);\n    }\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "2baa0adcf1cb551f61c4df241567aebbb7f46f35", "size": 5784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/test/weighted_matching_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": 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": "3rdparty/boost_1_73_0/libs/graph/test/weighted_matching_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": "3rdparty/boost_1_73_0/libs/graph/test/weighted_matching_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": 35.0545454545, "max_line_length": 80, "alphanum_fraction": 0.6004495159, "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5197171995557351}}
{"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_compute_index_reordering.h>\n#include <OpenTissue/core/math/optimization/optimization_partition_vector.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_partition_vector);\n\nBOOST_AUTO_TEST_CASE(test_case)\n{\n  typedef ublas::vector<size_t>   idx_vector_type;\n\n  idx_vector_type bitmask;\n\n  bitmask.resize(10,false);\n\n  bitmask(2) = OpenTissue::math::optimization::IN_ACTIVE;\n  bitmask(4) = OpenTissue::math::optimization::IN_ACTIVE;\n  bitmask(6) = OpenTissue::math::optimization::IN_ACTIVE;\n  bitmask(9) = OpenTissue::math::optimization::IN_ACTIVE;\n  bitmask(1) = OpenTissue::math::optimization::IN_LOWER;\n  bitmask(3) = OpenTissue::math::optimization::IN_LOWER;\n  bitmask(8) = OpenTissue::math::optimization::IN_LOWER;\n  bitmask(0) = OpenTissue::math::optimization::IN_UPPER;\n  bitmask(5) = OpenTissue::math::optimization::IN_UPPER;\n  bitmask(7) = OpenTissue::math::optimization::IN_UPPER;\n\n  idx_vector_type old2new;\n  idx_vector_type new2old;\n\n  OpenTissue::math::optimization::compute_index_reordering( bitmask, old2new, new2old );\n\n  ublas::vector<double> rhs;\n  rhs.resize(10,false);\n\n  rhs(0) = 1.0;\n  rhs(1) = 2.0;\n  rhs(2) = 3.0;\n  rhs(3) = 4.0;\n  rhs(4) = 5.0;\n  rhs(5) = 6.0;\n  rhs(6) = 7.0;\n  rhs(7) = 8.0;\n  rhs(8) = 9.0;\n  rhs(9) = 10.0;\n\n  ublas::vector<double> rhs_a;\n  ublas::vector<double> rhs_b;\n  OpenTissue::math::optimization::partition_vector( rhs, bitmask, old2new, 4, 6, rhs_a, rhs_b );\n\n  BOOST_CHECK( rhs_a.size() == 4);\n  BOOST_CHECK( rhs_b.size() == 6);\n\n  double tol =0.01;\n  BOOST_CHECK_CLOSE( double( rhs_a( 0 ) ), double( rhs( new2old(0) ) ), tol );\n  BOOST_CHECK_CLOSE( double( rhs_a( 1 ) ), double( rhs( new2old(1) ) ), tol );\n  BOOST_CHECK_CLOSE( double( rhs_a( 2 ) ), double( rhs( new2old(2) ) ), tol );\n  BOOST_CHECK_CLOSE( double( rhs_a( 3 ) ), double( rhs( new2old(3) ) ), tol );\n  BOOST_CHECK_CLOSE( double( rhs_b( 0 ) ), double( rhs( new2old(0+4) ) ), tol );\n  BOOST_CHECK_CLOSE( double( rhs_b( 1 ) ), double( rhs( new2old(1+4) ) ), tol );\n  BOOST_CHECK_CLOSE( double( rhs_b( 2 ) ), double( rhs( new2old(2+4) ) ), tol );\n  BOOST_CHECK_CLOSE( double( rhs_b( 3 ) ), double( rhs( new2old(3+4) ) ), tol );\n  BOOST_CHECK_CLOSE( double( rhs_b( 4 ) ), double( rhs( new2old(4+4) ) ), tol );\n  BOOST_CHECK_CLOSE( double( rhs_b( 5 ) ), double( rhs( new2old(5+4) ) ), tol );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "62de48922af994af3166f63d29332d9215c315b8", "size": 2949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/partition_vector/src/unit_partition_vector.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/partition_vector/src/unit_partition_vector.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/partition_vector/src/unit_partition_vector.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": 36.4074074074, "max_line_length": 96, "alphanum_fraction": 0.7080366226, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5197171995557351}}
{"text": "#include \"points_untangler/points_untangler.h\"\n\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <Eigen/Dense>\n#include <igl/list_to_matrix.h>\n#include <igl/write_triangle_mesh.h>\n\nbool load(const std::string & path, Eigen::MatrixXd &res)\n{\n\tstd::fstream file;\n\tfile.open(path.c_str());\n\n\tif (!file.good())\n\t{\n\t\tstd::cerr << \"Failed to open file : \" << path << std::endl;\n\t\tfile.close();\n\t\treturn false;\n\t}\n\n\n\tstd::string s;\n\tstd::vector<std::vector<double>> matrix;\n\n\twhile (getline(file, s))\n\t{\n\t\tstd::stringstream input(s);\n\t\tdouble temp;\n\t\tmatrix.emplace_back();\n\n\t\tstd::vector<double> &currentLine = matrix.back();\n\n\t\twhile (input >> temp)\n\t\t\tcurrentLine.push_back(temp);\n\t}\n\n\tif (!igl::list_to_matrix(matrix, res))\n\t{\n\t\tstd::cerr << \"list to matrix error\" << std::endl;\n\t\tfile.close();\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n\nint main(int argc, char** argv) {\n\tEigen::MatrixXd pts;\n\tEigen::MatrixXi F;\n\tEigen::MatrixXd newPts;\n\n\tconst std::string root = DATA_DIR;\n\n\tload(\"/Users/teseo/GDrive/Cellogram/Images/img12/vDetected.xyz\", pts);\n\tif(pts.cols() == 2){\n\t\tpts.conservativeResize(pts.rows(), 3);\n\t\tpts.col(2).setZero();\n\t}\n\n\tstd::vector<int> dropped;\n\n\tcellogram::PointsUntangler::pointsUntangler(pts, F, dropped, newPts);\n\n\tEigen::MatrixXd total(pts.rows()+newPts.rows(), pts.cols());\n\t// total.setZero();\n\n\ttotal.block(0, 0, pts.rows(), pts.cols()) = pts;\n\ttotal.block(pts.rows(), 0, newPts.rows(), newPts.cols()) = newPts;\n\n\tigl::write_triangle_mesh(\"test.obj\", total, F);\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "b06bbc459fefcd20f646f0bf593fff5edfda693d", "size": 1533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/pts_untangler.cpp", "max_stars_repo_name": "cellogram/cellogram", "max_stars_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-09-25T15:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T08:17:44.000Z", "max_issues_repo_path": "misc/pts_untangler.cpp", "max_issues_repo_name": "cellogram/cellogram", "max_issues_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_issues_repo_licenses": ["MIT"], "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/pts_untangler.cpp", "max_forks_repo_name": "cellogram/cellogram", "max_forks_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-14T01:36:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-11T20:27:57.000Z", "avg_line_length": 19.9090909091, "max_line_length": 71, "alphanum_fraction": 0.6666666667, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5197171966650442}}
{"text": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <iostream>\n#include <fstream>\n#include <random>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n#include <Eigen/LU>\n#include <time.h>\n\n// this is an example in how to use a class in one executable using full namespaces\n\n// file that defines the class you want to use\n#include \"calibration/Calibration.h\"\n\nint main(int argc, char **argv) \n{\n\nstd::ofstream myfile;\nmyfile.open (\"example.txt\");\nmyfile << \"iPos\\ti_den\\ti_times\\t\\terrorR\\t\\t\\terrorT \\n\";\n\nstd::vector<double> comp_time_vec, vect1, vect2;\n//int i_time = 0;\n\nfor (int i_5times = 1; i_5times <= 5; i_5times++) {\n\nint i_pos = 1280;\n\n\tstd::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<> dis(-1, 1);\n\n\t// AX = ZB\n\tEigen::Matrix4f Z = Eigen::Matrix4f::Identity();\n\tEigen::Vector4f qz_use = Eigen::Vector4f(dis(gen), dis(gen), dis(gen), dis(gen) );\n\tEigen::Quaternionf qz( qz_use[0], qz_use[1], qz_use[2], qz_use[3] );\n\tqz.normalize();\n\tEigen::Vector3f tz = Eigen::Vector3f( dis(gen), dis(gen), dis(gen) );\n\tZ.block<3,3>(0,0) = qz.toRotationMatrix();\n\tZ.block<3,1>(0,3) = tz;\n\t//std::cout << \"Z: \" << std::endl << Z << std::endl;\n\n \tEigen::Matrix4f X = Eigen::Matrix4f::Identity();;\n\tEigen::Vector4f qx_use = Eigen::Vector4f(dis(gen), dis(gen), dis(gen), dis(gen) );\n\tEigen::Quaternionf qx( qx_use[0], qx_use[1], qx_use[2], qx_use[3] );\n\tqx.normalize();\n\tEigen::Vector3f tx = Eigen::Vector3f(dis(gen),dis(gen), dis(gen));\n\tX.block<3,3>(0,0) = qx.toRotationMatrix();\n\tX.block<3,1>(0,3) = tx;\n\t//std::cout << \"X: \" << std::endl << X << std::endl;\n\n \tint NPoses = i_pos;\n\n\tstd::vector<Matrix4f> B, A;\n\n\tEigen::Matrix4f a = Eigen::Matrix4f::Identity();\n\n\n\tEigen::Vector4f q_use = Eigen::Vector4f::Random();\n\tEigen::Quaternionf q( q_use[0], q_use[1], q_use[2], q_use[3]);\n\tq.normalize();\n\n\tEigen::Vector3f t = Eigen::Vector3f( dis(gen), dis(gen), dis(gen) );\n\n\ta.block<3,3>(0,0) = q.toRotationMatrix();\n\ta.block<3,1>(0,3) = t;\n\n\tint den_test = 1024; // grid resolution\n\n\tfor (int i = 0; i < NPoses; i++)\n\t{\n\n\t\t// test data\n\t\tEigen::Matrix4f b = Eigen::Matrix4f::Identity();\n\t\tb = Z.inverse()*a*X;\n\n\t\tEigen::Matrix4f d = Eigen::Matrix4f::Identity();\n        \n\t\tEigen::Vector3f t = 0.1*(1/den_test)*Eigen::Vector3f( dis(gen),dis(gen), dis(gen) );\n\n\t\tfloat roll = dis(gen)*M_PI/den_test;\n\t\tfloat pitch = dis(gen)*M_PI/den_test;\n\t\tfloat yaw = dis(gen)*M_PI/den_test;\n\t\tEigen::Matrix3f R;\n\t\tR = AngleAxisf(roll, Vector3f::UnitX())\n\t\t\t*AngleAxisf(pitch, Vector3f::UnitY())\n  \t\t\t*AngleAxisf(yaw, Vector3f::UnitZ());\n\t\td.block<3,3>(0,0) = R;\n\t\td.block<3,1>(0,3) = t;\n\n\t\ta = d*a;\n\n\t\tA.push_back(a);\n\t\tB.push_back(b);\n\n\t}\n\n\t//i_den it's the sampling fraction: pick one champion every i_den\n\tfor (int i_den = 1; i_den <= 32; i_den *= 2) {\n\n\tstd::cout << std::endl << \"i_pos: \" << i_pos << \", \" << \"i_den: \" << i_den << \", \" << std::endl << \"i_5times: \" << i_5times << std::endl;\n\n\tstd::vector<Matrix4f> Asampled, Bsampled; //A, B sampled\n\tAsampled.clear();\n\tBsampled.clear();\n\n\t//fulfilling matrices A,B with choosen champions, limit per matrix sampled is NPoses (total available) over the sampling fraction i_den\n\n\tfor (int i_sam = 0; i_sam < NPoses/i_den; i_sam +=i_den){\n\t\tAsampled.push_back(A[i_sam]);\n\t\tBsampled.push_back(B[i_sam]);\n\t}\n\n\t// first, create an object of your class \n\tcalibration::Calibration mycalib;\n\n\tmycalib.setInput(Asampled, Bsampled);\n\t\n\tclock_t t1,t2;\n    t1=clock();\n    vect1.push_back((float(t1)*1000)/CLOCKS_PER_SEC);\n\n\tmycalib.computeClosedForm();\n\t\n\tt2=clock();\n\tvect2.push_back((float(t2)*1000)/CLOCKS_PER_SEC);\n    float diff ((float)t2-(float)t1);\n    comp_time_vec.push_back( (diff*10000) / CLOCKS_PER_SEC );\n    //i_time++;\n\t//sleep(2);\n\n\tmycalib.computeNonLinOpt();\n\n\tEigen::Matrix4f Tx, Tz;\n\tfloat Er, Et;\n\tTx = Eigen::Matrix4f::Identity();\n\tTz = Eigen::Matrix4f::Identity();\n\tmycalib.getFullOutput(Tz, Tx, Er, Et);\n\n\tmyfile << i_pos << \"\\t\\t\" << i_den << \"\\t\\t\" << i_5times << \"\\t\\t\" << Er << \"\\t\\t\" <<  Et << \"\\t\\t\" << \"\\n\";\n\n\t// print out the result\n\n\tstd::cout << \"combo: \" << i_pos << \" / \" << i_den << \" / \" << i_5times << std::endl;\n\t\n\tstd::cout << \"Input Z: \" << std::endl << Z << std::endl;\n\tstd::cout << \"Estimated Z:\" << std::endl << Tz << std::endl;\n\tstd::cout << \"Error over Z estimation: \" << std::endl << Z-Tz << std::endl << std::endl;\n\t\n\tstd::cout << \"Input X: \" << std::endl << X << std::endl;\n\tstd::cout << \"Estimated X:\" << std::endl << Tx << std::endl;\n\tstd::cout << \"Error over X estimation: \" << std::endl << X-Tx << std::endl;\n\n// compute Rotation and translation errors over Non Linear results\n\n\t/*Eigen::Matrix3f RxOK_NL, RzOK_NL;\n\tEigen::Vector3f txOK_NL, tzOK_NL;\n\n\tRxOK_NL = Tx.block<3,3>(0,0);\n\tRzOK_NL = Tz.block<3,3>(0,0);\n\ttxOK_NL = Tx.block<3,1>(0,3);\n\ttzOK_NL = Tz.block<3,1>(0,3);\n\n\tfloat Er_NL = 0;\n\n\tfloat EtNum_NL = 0, EtDen_NL = 1;\n\n\tfor (int i = 0; i < NPoses; i++)\n\t{\n\t\t\n\n\t\tEr_NL += Matrix3f( A[i].block<3,3>(0,0)*RxOK_NL - RzOK_NL*B[i].block<3,3>(0,0) ).squaredNorm();\n\n\t\tEtDen_NL += Vector3f( A[i].block<3,3>(0,0)*txOK_NL - A[i].block<3,1>(0,3) ).squaredNorm();\n\t\t\t\t  \n\t\tEtNum_NL += Vector3f( A[i].block<3,3>(0,0)*txOK_NL + A[i].block<3,1>(0,3) - RzOK_NL*B[i].block<3,1>(0,3) - tzOK_NL ).squaredNorm();\n\n\t}\n\n\tfloat Et_NL = sqrt(EtNum_NL/EtDen_NL);\n\n\tstd::cout << \"Rotation error on Non Linear form is \" << Er_NL << std::endl;\n\tstd::cout << \"Translation error on Non Linear form is \" << Et_NL << std::endl;\n\tstd::cout << \"combo \" << NPoses << \"/ \" << den_test << \"/ \" << i_5times << std::endl;*/\n\n\n\n\n}\n}\n// chiusura dei tre for\nstd::cout << \"closed form time computation in microseconds :\"<< std::endl;\n  for (unsigned i=0; i<comp_time_vec.size(); i++)\n    std::cout << \"i \" << i<< \" diff \" << comp_time_vec[i] << \" t1 \" << vect1[i] <<\" t2 \" << vect2[i] << std::endl;\n  std::cout << '\\n';\n//std::cout<< \"closed form time computation in milliseconds \" << std::endl << comp_time_vec << std::endl;\n\nmyfile.close();\n\nreturn 0;\n\n}", "meta": {"hexsha": "fe25f3c801679a9d2e3227e447adbb30f3df6d7c", "size": 5996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/calibration_test_noise.cpp", "max_stars_repo_name": "gialen/calibration", "max_stars_repo_head_hexsha": "e9247df76d36ddc5f7bf928aa2433214032449c7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-14T22:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-14T22:44:21.000Z", "max_issues_repo_path": "test/calibration_test_noise.cpp", "max_issues_repo_name": "gialen/calibration", "max_issues_repo_head_hexsha": "e9247df76d36ddc5f7bf928aa2433214032449c7", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/calibration_test_noise.cpp", "max_forks_repo_name": "gialen/calibration", "max_forks_repo_head_hexsha": "e9247df76d36ddc5f7bf928aa2433214032449c7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-02-18T16:41:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-23T15:31:27.000Z", "avg_line_length": 29.1067961165, "max_line_length": 138, "alphanum_fraction": 0.6212474983, "num_tokens": 2123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5197171945337246}}
{"text": "/* Boost libs/numeric/odeint/performance/openmp/osc_chain_1d.cpp\n\n Copyright 2013 Karsten Ahnert\n Copyright 2013 Mario Mulansky\n Copyright 2013 Pascal Germroth\n\n stronlgy nonlinear hamiltonian lattice in 2d\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 <iostream>\n#include <vector>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/external/mpi/mpi.hpp>\n\n#include <boost/program_options.hpp>\n#include <boost/random.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/foreach.hpp>\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/median.hpp>\n#include \"osc_chain_1d_system.hpp\"\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\nusing namespace boost::accumulators;\nusing namespace boost::program_options;\n\nusing boost::timer::cpu_timer;\n\nconst double p_kappa = 3.3;\nconst double p_lambda = 4.7;\n\nint main( int argc , char* argv[] )\n{\n    boost::mpi::environment env(argc, argv);\n    boost::mpi::communicator world;\n\n    size_t N, steps, repeat;\n    bool dump;\n    options_description desc(\"Options\");\n    desc.add_options()\n        (\"help,h\", \"show this help\")\n        (\"length\", value(&N)->default_value(1024), \"length of chain\")\n        (\"steps\", value(&steps)->default_value(100), \"simulation steps\")\n        (\"repeat\", value(&repeat)->default_value(25), \"repeat runs\")\n        (\"dump\", bool_switch(&dump), \"dump final state to stderr (on node 0)\")\n        ;\n    variables_map vm;\n    store(command_line_parser(argc, argv).options(desc).run(), vm);\n    notify(vm);\n    if(vm.count(\"help\"))\n    {\n        if(world.rank() == 0)\n            cerr << desc << endl;\n        return EXIT_FAILURE;\n    }\n    cout << \"length\\tsteps\\tthreads\\ttime\" << endl;\n\n    accumulator_set< double, stats<tag::mean, tag::median> > acc_time;\n\n    vector<double> p( N ), q( N, 0 );\n    if(world.rank() == 0) {\n        boost::random::uniform_real_distribution<double> distribution;\n        boost::random::mt19937 engine( 0 );\n        generate( p.begin() , p.end() , boost::bind( distribution , engine ) );\n    }\n\n    typedef vector<double> inner_state_type;\n    typedef mpi_state< inner_state_type > state_type;\n    typedef symplectic_rkn_sb3a_mclachlan<\n              state_type , state_type , double\n            > stepper_type;\n    state_type p_split( world ), q_split( world );\n    split(p, p_split);\n    split(q, q_split);\n\n    for(size_t n_run = 0 ; n_run != repeat ; n_run++) {\n        cpu_timer timer;\n        world.barrier();\n        integrate_n_steps( stepper_type() , osc_chain( p_kappa , p_lambda ) ,\n                           make_pair( boost::ref(q_split) , boost::ref(p_split) ) ,\n                           0.0 , 0.01 , steps );\n        world.barrier();\n        if(world.rank() == 0) {\n            double run_time = static_cast<double>(timer.elapsed().wall) * 1.0e-9;\n            acc_time(run_time);\n            cout << N << '\\t' << steps << '\\t' << world.size() << '\\t' << run_time << endl;\n        }\n    }\n\n    if(dump) {\n        unsplit(p_split, p);\n        if(world.rank() == 0) {\n            copy(p.begin(), p.end(), ostream_iterator<double>(cerr, \"\\t\"));\n            cerr << endl;\n        }\n    }\n\n    if(world.rank() == 0)\n        cout << \"# mean=\" << mean(acc_time)\n             << \" median=\" << median(acc_time) << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "ef2ce7dbdb22b688d02152da9ec74db80986d915", "size": 3529, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/performance/mpi/osc_chain_1d.cpp", "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.cpp", "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.cpp", "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": 31.2300884956, "max_line_length": 91, "alphanum_fraction": 0.6245395296, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5196635156117109}}
{"text": "\n\n#include <iostream>\n#include <autodiff/forward/real.hpp>\n#include <autodiff/forward/real/eigen.hpp>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\n#include \"rotation.hpp\"\n\n// using namespace autodiff;\nusing namespace Eigen;\n\nclass Object {\n    public:\n        Object();\n        virtual autodiff::real U(const autodiff::ArrayXreal& pos);\n        VectorXd DLT1(const autodiff::ArrayXreal& q1, const autodiff::ArrayXreal& q2, double h);\n    private:\n\n    protected:\n        double m = 1;  // mass (kg)\n        double g = 1;  // gravity accel (m/s^2)\n        MatrixXd J;  // (3x3) Inertia Tensor (kg*m^2)\n\n};\n", "meta": {"hexsha": "e796b0390eee58d6c4eb9c4b6343d1740e85f708", "size": 606, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/dynamics/object.hpp", "max_stars_repo_name": "brysonjones/dynamics_sim", "max_stars_repo_head_hexsha": "201bdf0a93d00addc585ffa47f280cffacebb9b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dynamics/object.hpp", "max_issues_repo_name": "brysonjones/dynamics_sim", "max_issues_repo_head_hexsha": "201bdf0a93d00addc585ffa47f280cffacebb9b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dynamics/object.hpp", "max_forks_repo_name": "brysonjones/dynamics_sim", "max_forks_repo_head_hexsha": "201bdf0a93d00addc585ffa47f280cffacebb9b3", "max_forks_repo_licenses": ["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.4444444444, "max_line_length": 96, "alphanum_fraction": 0.6435643564, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5196570639106552}}
{"text": "#pragma once\r\n\r\n#include <skynet/config.hpp>\r\n#include <skynet/ublas.hpp>\r\n#include <skynet/utility/tag.hpp>\r\n\r\n\r\n#include <Eigen/Core>\r\n\r\nnamespace skynet{namespace statistics{\r\n\r\n\r\n\r\n\ttemplate <typename M>\r\n\tclass metric;\r\n\r\n\ttemplate <>\r\n\tclass metric<Mahalanobis> : public unary_function<ublas::vector<double>, double>{\r\n\tpublic:\r\n\t\ttypedef ublas::matrix<double>\t\t\t\t\tmatrix_type;\r\n\t\ttypedef ublas::vector<double>\t\t\t\t\tvector_type;\r\n\t\t\r\n\t\tmetric(){}\r\n\r\n\t\tmetric(const metric &rhs) \r\n\t\t\t: _mean(rhs._mean), _covariance(rhs._covariance), _inv_cov(rhs._inv_cov){}\r\n\r\n\t\tvoid attach(matrix_type  feature_matrix){\r\n\t\t\t_mean = ublas::zero_vector<double>(feature_matrix.size1());\r\n\t\t\tfor (int i = 0; i < feature_matrix.size2(); ++i){\r\n\t\t\t\t_mean += ublas::column(feature_matrix, i);\r\n\t\t\t}\r\n\r\n\t\t\t_mean /= feature_matrix.size2();\r\n\r\n\t\t\tfor (int i = 0; i < feature_matrix.size2(); ++i){\r\n\t\t\t\tublas::column(feature_matrix, i) -= _mean;\r\n\t\t\t}\r\n\t\t\r\n\t\t\t_covariance = ublas::prod(feature_matrix, ublas::trans(feature_matrix));\r\n\t\t\t_covariance /= feature_matrix.size2();\r\n\t\t\t_inv_cov = \r\n\t\t}\r\n\r\n\t\tresult_type\t operator()(const argument_type &x) const{\r\n\t\t\tauto x_sub_mean = x - _mean;\r\n\t\t\tauto dis = ublas::trans(x_sub_mean) * _inv_cov * x_sub_mean;\r\n\t\t\treturn dis;\r\n\t\t}\r\n\r\n\t\tvoid mean(const vector_type &mean)\t\t{ _mean = mean; }\r\n\t\tvector_type mean() const\t\t\t\t{ return _mean; }\r\n\r\n\t\ttemplate <typename Archive>\r\n\t\tvoid serialize(Archive &ar, const unsigned int &){\r\n\t\t\tar & boost::serialization::make_nvp(\"mean_feature\", _mean);\r\n\t\t\tar & boost::serialization::make_nvp(\"covariance\", _covariance);\r\n\t\t\tar & boost::serialization::make_nvp(\"inv_covariance\", _inv_cov);\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tvector_type\t\t\t\t\t\t_mean;\r\n\t\tmatrix_type\t\t\t\t\t\t_covariance;\t\r\n\t\tmatrix_type\t\t\t\t\t\t_inv_cov;\r\n\t};\r\n\r\n\r\n}}\r\n", "meta": {"hexsha": "a03777e3478f839c413e4ae34d1925e6af25a663", "size": 1774, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "skynet/statistics/metric.hpp", "max_stars_repo_name": "zhangzhimin/skynet", "max_stars_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-08-02T03:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-16T01:07:55.000Z", "max_issues_repo_path": "skynet/statistics/metric.hpp", "max_issues_repo_name": "zhangzhimin/skynet", "max_issues_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skynet/statistics/metric.hpp", "max_forks_repo_name": "zhangzhimin/skynet", "max_forks_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_forks_repo_licenses": ["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.7101449275, "max_line_length": 83, "alphanum_fraction": 0.6561443067, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5196570499696886}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2012 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 <Core/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/Algorithms/Math/SolveLinearSystemWithEigen.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/DenseColumnMatrix.h>\n#include <Core/Datatypes/SparseRowMatrix.h>\n#include <Core/Datatypes/MatrixTypeConversions.h>\n#include <Eigen/Sparse>\n\nusing namespace SCIRun::Core::Algorithms::Math;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core;\n\nnamespace\n{\n  class SolveLinearSystemAlgorithmEigenCGImpl\n  {\n  public:\n    SolveLinearSystemAlgorithmEigenCGImpl(const DenseColumnMatrix& rhs, double tolerance, int maxIterations) : \n        rhs_(rhs), tolerance_(tolerance), maxIterations_(maxIterations) {}\n\n    template <class MatrixType>\n    DenseColumnMatrix::EigenBase solveWithEigen(const MatrixType& lhs)\n    {\n      Eigen::ConjugateGradient<typename MatrixType::EigenBase> cg;\n      cg.compute(lhs);\n\n      if (cg.info() != Eigen::Success)\n        BOOST_THROW_EXCEPTION(AlgorithmInputException() \n          << LinearAlgebraErrorMessage(\"Conjugate gradient initialization was unsuccessful\")\n          << EigenComputationInfo(cg.info()));\n\n      cg.setTolerance(tolerance_);\n      cg.setMaxIterations(maxIterations_);\n      auto solution = cg.solve(rhs_).eval();\n      tolerance_ = cg.error();\n      maxIterations_ = cg.iterations();\n      return solution;\n    }\n\n    double tolerance_;\n    int maxIterations_;\n  private:\n    const DenseColumnMatrix& rhs_;\n  };\n}\n\nSolveLinearSystemAlgorithm::Outputs SolveLinearSystemAlgorithm::run(const Inputs& input, const Parameters& params) const\n{\n  auto A = input.get<0>();\n  ENSURE_ALGORITHM_INPUT_NOT_NULL(A, \"Null input matrix\");\n\n  auto b = input.get<1>();\n  ENSURE_ALGORITHM_INPUT_NOT_NULL(b, \"Null rhs vector\");\n  \n  double tolerance = params.get<0>();\n  ENSURE_POSITIVE_DOUBLE(tolerance, \"Tolerance out of range!\");\n\n  int maxIterations = params.get<1>();\n  ENSURE_POSITIVE_INT(maxIterations, \"Max iterations out of range!\");\n\n  SolveLinearSystemAlgorithmEigenCGImpl impl(*b, tolerance, maxIterations);\n  DenseColumnMatrix x;\n  if (matrix_is::dense(A))\n  {\n    x = impl.solveWithEigen(*matrix_cast::as_dense(A));\n  }\n  else if (matrix_is::sparse(A))\n  {\n    x = impl.solveWithEigen(*matrix_cast::as_sparse(A));\n  }\n  else\n    BOOST_THROW_EXCEPTION(AlgorithmProcessingException() << ErrorMessage(\"solveWithEigen can only handle dense and sparse matrices.\"));\n  \n  if (x.size() != 0)\n  {\n    /// @todo: move ctor\n    DenseColumnMatrixHandle solution(boost::make_shared<DenseColumnMatrix>(x));\n    return SolveLinearSystemAlgorithm::Outputs(solution, impl.tolerance_, impl.maxIterations_);\n  }\n  else\n    BOOST_THROW_EXCEPTION(AlgorithmProcessingException() << ErrorMessage(\"solveWithEigen produced an empty solution.\"));\n}\n\nAlgorithmOutput SolveLinearSystemAlgorithm::run_generic(const AlgorithmInput& input) const\n{\n  throw 2;\n}", "meta": {"hexsha": "784496c1fd09abd8333b9ca63bd076a6e1b4442e", "size": 4245, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Math/SolveLinearSystemWithEigen.cc", "max_stars_repo_name": "benjaminlarson/SCIRunGUIPrototype", "max_stars_repo_head_hexsha": "ed34ee11cda114e3761bd222a71a9f397517914d", "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/Core/Algorithms/Math/SolveLinearSystemWithEigen.cc", "max_issues_repo_name": "benjaminlarson/SCIRunGUIPrototype", "max_issues_repo_head_hexsha": "ed34ee11cda114e3761bd222a71a9f397517914d", "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/Core/Algorithms/Math/SolveLinearSystemWithEigen.cc", "max_forks_repo_name": "benjaminlarson/SCIRunGUIPrototype", "max_forks_repo_head_hexsha": "ed34ee11cda114e3761bd222a71a9f397517914d", "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.5948275862, "max_line_length": 135, "alphanum_fraction": 0.7479387515, "num_tokens": 961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5196109487456725}}
{"text": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace std; \nusing namespace boost::numeric::ublas;\n\nint main () {\n    matrix<complex<double>> m(3, 3);\n    for (unsigned i = 0; i < m.size1(); ++ i)\n        for (unsigned j = 0; j < m.size2(); ++ j)\n            m(i, j) = complex<double> (3 * i + j, 3 * i + j);\n\n    cout << - m << endl;\n    cout << conj (m) << endl;\n    cout << real (m) << endl;\n    cout << imag (m) << endl;\n    cout << trans (m) << endl;\n    cout << herm (m) << endl;\n}\n", "meta": {"hexsha": "da6a935ce1974b5e7378fb87265e2c3daa8e077b", "size": 531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "practice/matrix1.cpp", "max_stars_repo_name": "ShiZhan/graph-study", "max_stars_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-14T07:27:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-15T03:11:31.000Z", "max_issues_repo_path": "practice/matrix1.cpp", "max_issues_repo_name": "Zhan2012/graph-study", "max_issues_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practice/matrix1.cpp", "max_forks_repo_name": "Zhan2012/graph-study", "max_forks_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "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.55, "max_line_length": 61, "alphanum_fraction": 0.5235404896, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5196109487456724}}
{"text": "/* -------------------------------------------------------------------------\n *  A repertory of multi primitive-to-primitive (MP2) ICP algorithms in C++\n * Copyright (C) 2018-2019 Jose Luis Blanco, University of Almeria\n * See LICENSE for license information.\n * ------------------------------------------------------------------------- */\n/**\n * @file   optimal_tf_gauss_newton.cpp\n * @brief  Simple non-linear optimizer to find the SE(3) optimal transformation\n * @author Jose Luis Blanco Claraco\n * @date   Jun 16, 2019\n */\n\n#include <mp2p_icp/optimal_tf_gauss_newton.h>\n#include <mrpt/poses/Lie/SE.h>\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace mp2p_icp;\n\nvoid mp2p_icp::optimal_tf_gauss_newton(\n    const Pairings_GaussNewton& in, OptimalTF_Result& result)\n{\n    using std::size_t;\n\n    MRPT_START\n\n    // Run Gauss-Newton steps, using SE(3) relinearization at the current\n    // solution:\n    result.optimal_pose = in.initial_guess;\n\n    const auto nPt2Pt = in.paired_points.size();\n    const auto nPt2Pl = in.paired_pt2pl.size();\n    const auto nPl2Pl = in.paired_planes.size();\n\n    const auto nErrorTerms = (nPt2Pt + nPl2Pl) * 3 + nPt2Pl;\n\n    Eigen::VectorXd                          err(nErrorTerms);\n    Eigen::Matrix<double, Eigen::Dynamic, 6> J(nErrorTerms, 6);\n\n    double       w_pt = in.weight_point2point;\n    const double w_pl = in.weight_point2plane, w_pl2pl = in.weight_plane2plane;\n\n    const bool  has_per_pt_weight       = !in.point_weights.empty();\n    auto        cur_point_block_weights = in.point_weights.begin();\n    std::size_t cur_point_block_start   = 0;\n\n    MRPT_TODO(\"Implement robust Kernel in this solver\");\n\n    for (size_t iter = 0; iter < in.max_iterations; iter++)\n    {\n        // (12x6 Jacobian)\n        const auto dDexpe_de =\n            mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(result.optimal_pose);\n\n        // Point-to-point:\n        for (size_t idx_pt = 0; idx_pt < nPt2Pt; idx_pt++)\n        {\n            // Error:\n            const auto&  p  = in.paired_points[idx_pt];\n            const double lx = p.other_x, ly = p.other_y, lz = p.other_z;\n            double       gx, gy, gz;\n            result.optimal_pose.composePoint(lx, ly, lz, gx, gy, gz);\n            err[idx_pt * 3 + 0] = gx - p.this_x;\n            err[idx_pt * 3 + 1] = gy - p.this_y;\n            err[idx_pt * 3 + 2] = gz - p.this_z;\n\n            // Eval Jacobian:\n            // clang-format off\n            const Eigen::Matrix<double, 3, 12> J1 =\n                (Eigen::Matrix<double, 3, 12>() <<\n                   lx,  0,  0,  ly,  0,  0, lz,  0,  0,  1,  0,  0,\n                    0, lx,  0,  0,  ly,  0,  0, lz,  0,  0,  1,  0,\n                    0,  0, lx,  0,  0,  ly,  0,  0, lz,  0,  0,  1\n                 ).finished();\n            // clang-format on\n\n            // Get weight:\n            if (has_per_pt_weight)\n            {\n                if (idx_pt >=\n                    cur_point_block_start + cur_point_block_weights->first)\n                {\n                    ASSERT_(cur_point_block_weights != in.point_weights.end());\n                    ++cur_point_block_weights;  // move to next block\n                    cur_point_block_start = idx_pt;\n                }\n                w_pt = cur_point_block_weights->second;\n            }\n\n            // Build Jacobian:\n            J.block<3, 6>(idx_pt * 3, 0) = w_pt * J1 * dDexpe_de.asEigen();\n        }\n\n        // Point-to-plane:\n        auto base_idx = nPt2Pt * 3;\n        for (size_t idx_pl = 0; idx_pl < nPt2Pl; idx_pl++)\n        {\n            // Error:\n            const auto& p = in.paired_pt2pl[idx_pl];\n\n            const double lx = p.pt_other.x, ly = p.pt_other.y,\n                         lz = p.pt_other.z;\n            mrpt::math::TPoint3D g;\n            result.optimal_pose.composePoint(lx, ly, lz, g.x, g.y, g.z);\n\n            err(idx_pl + base_idx) = p.pl_this.plane.evaluatePoint(g);\n\n            // Eval Jacobian:\n            // clang-format off\n            const Eigen::Matrix<double, 3, 12> J1 =\n                (Eigen::Matrix<double, 3, 12>() <<\n                   lx,  0,  0,  ly,  0,  0, lz,  0,  0,  1,  0,  0,\n                    0, lx,  0,  0,  ly,  0,  0, lz,  0,  0,  1,  0,\n                    0,  0, lx,  0,  0,  ly,  0,  0, lz,  0,  0,  1\n                 ).finished();\n            // clang-format on\n\n            const Eigen::Matrix<double, 1, 3> Jpl =\n                (Eigen::Matrix<double, 1, 3>() << p.pl_this.plane.coefs[0],\n                 p.pl_this.plane.coefs[1], p.pl_this.plane.coefs[2])\n                    .finished();\n\n            const Eigen::Matrix<double, 1, 6> Jb =\n                Jpl * J1 * dDexpe_de.asEigen();\n\n            J.block<1, 6>(idx_pl + base_idx, 0) = w_pl * Jb;\n        }\n\n        // Plane-to-plane (only direction of normal vectors):\n        base_idx += nPt2Pl * 1;\n        for (size_t idx_pl = 0; idx_pl < nPl2Pl; idx_pl++)\n        {\n            // Error term:\n            const auto& p = in.paired_planes[idx_pl];\n\n            const auto nl = p.p_other.plane.getNormalVector();\n            const auto ng = p.p_this.plane.getNormalVector();\n\n            const auto p_oplus_nl = result.optimal_pose.rotateVector(nl);\n\n            for (int i = 0; i < 3; i++)\n                err(i + idx_pl * 3 + base_idx) = ng[i] - p_oplus_nl[i];\n\n            // Eval Jacobian:\n\n            // df_oplus(A,p)/d_A. Section 7.3.2 tech. report:\n            // \"A tutorial on SE(3) transformation parameterizations and\n            // on-manifold optimization\"\n            // Modified, to discard the last I_3 block, since this particular\n            // cost function is insensible to translations.\n\n            // clang-format off\n            const Eigen::Matrix<double, 3, 12> J1 =\n                (Eigen::Matrix<double, 3, 12>() <<\n                   nl.x,  0,  0,  nl.y,  0,  0, nl.z,  0,  0,  0,  0,  0,\n                    0, nl.x,  0,  0,  nl.y,  0,  0, nl.z,  0,  0,  0,  0,\n                    0,  0, nl.x,  0,  0,  nl.y,  0,  0, nl.z,  0,  0,  0\n                 ).finished();\n            // clang-format on\n\n            J.block<3, 6>(3 * idx_pl + base_idx, 0) =\n                w_pl2pl * J1 * dDexpe_de.asEigen();\n        }\n\n        // 3) Solve Gauss-Newton:\n        const Eigen::VectorXd             g = J.transpose() * err;\n        const Eigen::Matrix<double, 6, 6> H = J.transpose() * J;\n        const Eigen::Matrix<double, 6, 1> delta =\n            -H.colPivHouseholderQr().solve(g);\n\n        // 4) add SE(3) increment:\n        const auto dE = mrpt::poses::Lie::SE<3>::exp(\n            mrpt::math::CVectorFixed<double, 6>(delta));\n\n        result.optimal_pose = result.optimal_pose + dE;\n\n        if (in.verbose)\n        {\n            std::cout << \"[P2P GN] iter:\" << iter << \" err:\" << err.norm()\n                      << \" delta:\" << delta.transpose() << \"\\n\";\n        }\n\n        // Simple convergence test:\n        if (delta.norm() < in.min_delta) break;\n\n    }  // for each iteration\n    MRPT_END\n}\n", "meta": {"hexsha": "cd8202594e1d5d80bea7ff790b0edfa8b2b1e60e", "size": 6958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimal_tf_gauss_newton.cpp", "max_stars_repo_name": "jtpils/mp2p_icp", "max_stars_repo_head_hexsha": "40066f00457ac4d7ca6bee3d5882192af666514a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-26T03:27:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T03:27:33.000Z", "max_issues_repo_path": "src/optimal_tf_gauss_newton.cpp", "max_issues_repo_name": "jtpils/mp2p_icp", "max_issues_repo_head_hexsha": "40066f00457ac4d7ca6bee3d5882192af666514a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimal_tf_gauss_newton.cpp", "max_forks_repo_name": "jtpils/mp2p_icp", "max_forks_repo_head_hexsha": "40066f00457ac4d7ca6bee3d5882192af666514a", "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.8148148148, "max_line_length": 79, "alphanum_fraction": 0.5007185973, "num_tokens": 2063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733955639775, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5196109413002189}}
{"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  std::string sep = \"\\n----------------------------------------\\n\";\nMatrix3d m1;\nm1 << 1.111111, 2, 3.33333, 4, 5, 6, 7, 8.888888, 9;\n\nIOFormat CommaInitFmt(StreamPrecision, DontAlignCols, \", \", \", \", \"\", \"\", \" << \", \";\");\nIOFormat CleanFmt(4, 0, \", \", \"\\n\", \"[\", \"]\");\nIOFormat OctaveFmt(StreamPrecision, 0, \", \", \";\\n\", \"\", \"\", \"[\", \"]\");\nIOFormat HeavyFmt(FullPrecision, 0, \", \", \";\\n\", \"[\", \"]\", \"[\", \"]\");\n\nstd::cout << m1 << sep;\nstd::cout << m1.format(CommaInitFmt) << sep;\nstd::cout << m1.format(CleanFmt) << sep;\nstd::cout << m1.format(OctaveFmt) << sep;\nstd::cout << m1.format(HeavyFmt) << sep;\n\n  return 0;\n}\n", "meta": {"hexsha": "ee2d080b3fc233d0232d9188ca2697735f3fed12", "size": 1087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_IOFormat.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_IOFormat.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_IOFormat.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": 31.0571428571, "max_line_length": 224, "alphanum_fraction": 0.5869365225, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132314, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.5194009208890166}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2008-2010 Gael Guennebaud <g.gael@free.fr>\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/SparseExtra>\n#include \"unsupported/Eigen/src/SparseExtra/BlockSparseQR.h\"\n\ntemplate<typename Scalar, typename BlockSolverLeft, typename BlockSolverRight>\nvoid block_sparse_qr(int nRows, int nCols, int blockCols) \n{\n    std::cout << \"block_sparse_qr< \" << eigen_test_nice_typename<BlockSolverLeft>() << \", \" << eigen_test_nice_typename<BlockSolverRight>() << \">[\" << nRows << \"x\" << blockCols << \" | \" << nRows << \"x\" << (nCols - blockCols) << \"]\\n\";\n    typedef Eigen::Matrix<Scalar, Dynamic, Dynamic> DenseMatrix;\n\n    // Generate random sparse matrix\n    SparseMatrix<Scalar> mat;\n    mat.resize(nRows, nCols);\n    std::vector< Eigen::Triplet<Scalar> > triplets;\n    const double occupancy = 0.5;\n    for(int i=0; i<nRows; i++) {\n        for(int j=0; j<nCols; j++) {\n            if( Eigen::internal::random<double>(0., 1.) > occupancy )\n                triplets.push_back( Eigen::Triplet<Scalar>(i, j, Eigen::internal::random<Scalar>() ) );\n        }\n    }\n    mat.setFromTriplets(triplets.begin(), triplets.end());\n    mat.makeCompressed();\n\n    // solve using BlockSparseQR, using provided Left and Right solvers\n    BlockSparseQR<SparseMatrix<Scalar>, BlockSolverLeft, BlockSolverRight> solver;\n    solver.setBlockParams(blockCols);\n    solver.compute(mat);\n\n    // check result\n    auto Q = solver.matrixQ();\n    auto R = solver.matrixR();\n\n    DenseMatrix I = DenseMatrix::Identity(nRows, nRows);\n\n    DenseMatrix sQ = Q * I;\n\n    // check A*P = Q*R\n    DenseMatrix  Q_dot_R = Q*R;\n    DenseMatrix AP = mat.toDense();\n    solver.colsPermutation().applyThisOnTheRight(AP);\n    VERIFY_IS_APPROX( Q_dot_R, AP );\n\n    // check Qt*Q = I\n    DenseMatrix  QtQ = Q.transpose()*sQ;\n    VERIFY_IS_APPROX( QtQ, I );\n\n    // check R = upper triangular\n    for(int i=0; i<R.rows(); i++) \n        for(int j=0; j<R.cols() && j<i; j++) \n            eigen_assert( fabs(R.coeff(i,j)) < 0.00001  );\n\n}\n\n\n\nvoid test_block_sparse_qr()\n{\n  for(int i = 0; i < g_repeat; i++) {\n\n    typedef double Scalar;\n    typedef SparseQR<SparseMatrix<Scalar>, COLAMDOrdering<int> > BlockSparseSolver;\n    typedef ColPivHouseholderQR<Matrix<Scalar,Dynamic,Dynamic> > BlockDenseSolver;\n\n    CALL_SUBTEST((block_sparse_qr<Scalar, BlockSparseSolver, BlockDenseSolver>(20, 31, 13)));\n    CALL_SUBTEST((block_sparse_qr<Scalar, BlockSparseSolver, BlockSparseSolver>(20, 31, 13)));\n    CALL_SUBTEST((block_sparse_qr<Scalar, BlockSparseSolver, BlockDenseSolver>(10, 6, 2)));\n    CALL_SUBTEST((block_sparse_qr<Scalar, BlockSparseSolver, BlockDenseSolver>(6, 10, 2)));\n    CALL_SUBTEST(( block_sparse_qr<Scalar, BlockSparseSolver, BlockDenseSolver>( 100, 50, 20 ) ));\n    CALL_SUBTEST(( block_sparse_qr<Scalar, BlockSparseSolver, BlockDenseSolver>( 9, 8, 2 ) ));\n\n  }\n}\n", "meta": {"hexsha": "c738984dc57faa2d4b4e5e8bca3d2da076d77e8b", "size": 3122, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_pr/unsupported/test/block_sparse_qr.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/block_sparse_qr.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/block_sparse_qr.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": 37.6144578313, "max_line_length": 234, "alphanum_fraction": 0.6739269699, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5194009187495963}}
{"text": "#ifndef OPENGV2_BSPLINEREAL_HPP\n#define OPENGV2_BSPLINEREAL_HPP\n\n#include <Eigen/Eigen>\n#include <Eigen/StdVector>\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n#include <iostream>\n\nnamespace opengv2 {\n    template<int dim>\n    class BsplineReal {\n    public:\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        explicit BsplineReal(int p = dim,\n                             const std::vector<Eigen::Matrix<double, dim, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, dim, 1>>> &Q = std::vector<Eigen::Matrix<double, dim, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, dim, 1>>>(),\n                             int controlPointsNum = -1,\n                             const std::vector<double> &u = std::vector<double>(),\n                             const std::vector<Eigen::Matrix<double, dim, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, dim, 1>>> &dQ = std::vector<Eigen::Matrix<double, dim, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, dim, 1>>>(),\n                         bool derWithMagnitude = false, double lambda = 1) : degree(p), lambda(lambda) {\n            // if dataPoints given, then do approximation\n            if (!Q.empty()) {\n                dataPoints = Q;\n\n                // Data registration\n                if (!u.empty()) {\n                    correspondingUs = u;\n                } else {\n                    // Data registration using chord length\n                    // Range: [0,1]\n                    correspondingUs.resize(dataPoints.size());\n\n                    double d = 0;\n                    for (int i = 1; i < dataPoints.size(); ++i) {\n                        d += (dataPoints[i] - dataPoints[i - 1]).norm();\n                    }\n\n                    correspondingUs.front() = 0;\n                    correspondingUs.back() = 1;\n                    for (int i = 1; i < dataPoints.size() - 1; ++i) {\n                        correspondingUs[i] =\n                                correspondingUs[i - 1] + (dataPoints[i] - dataPoints[i - 1]).norm() / d;\n                    }\n                }\n\n                // derivative\n                if (!dQ.empty()) {\n                    derivatives = dQ;\n\n                    if (!derWithMagnitude) {\n                        // derivatives is unit direction, magnitude estimation by speed estimation\n                        for (int i = 1; i <= dataPoints.size() - 2; ++i) {\n                            double speed = (dataPoints[i] - dataPoints[i - 1]).norm() /\n                                           (correspondingUs[i] - correspondingUs[i - 1]) +\n                                           (dataPoints[i + 1] - dataPoints[i]).norm() /\n                                           (correspondingUs[i + 1] - correspondingUs[i]);\n                            derivatives[i] *= speed / 2;\n                        }\n                        derivatives.front() *=\n                                (dataPoints[1] - dataPoints[0]).norm() / (correspondingUs[1] - correspondingUs[0]);\n                        derivatives.back() *=\n                                (dataPoints[dataPoints.size() - 1] - dataPoints[dataPoints.size() - 2]).norm() /\n                                (correspondingUs[dataPoints.size() - 1] - correspondingUs[dataPoints.size() - 2]);\n                    }\n                }\n\n                // approximation\n                if (controlPointsNum < 0)\n                    controlPointsNum = std::max(int(Q.size() / 3), degree + 1);\n                if (controlPointsNum <= degree) {\n                    std::cerr << \"Constructor: control points number should greater than degree!\" << std::endl;\n                    return;\n                }\n                approximation(controlPointsNum);\n            }\n        };\n\n\n        /*\n         * Approximation\n         * return: status: failed(-1), success(0)\n         */\n        int approximation(int controlPointsNum) {\n            /*** knot initialization (9.68) in NURBS book ***/\n            knotVector.resize(controlPointsNum + degree + 1);\n            std::fill_n(knotVector.begin(), degree + 1, correspondingUs.front());\n            std::fill_n(knotVector.rbegin(), degree + 1, correspondingUs.back());\n            double d = dataPoints.size() / double(controlPointsNum - degree);\n            for (int j = 1; j <= controlPointsNum - 1 - degree; j++) {\n                int i = floor(j * d);\n                double alpha = j * d - i;\n                knotVector[degree + j] = (1 - alpha) * correspondingUs[i - 1] + alpha * correspondingUs[i];\n            }\n\n            return optimization();\n        };\n\n        /*\n         * Compute nonzero basis functions and their derivatives up to derivativeLimit.\n         * N_{i-p,p}(u),...,N_{i,p}(u)\n         * Output: two-dimensional array, ders. ders[k][j] is the kth derivative of the function N_{i-p+j,p}, where 0<=k<=n and 0<=j<=p.\n         */\n        int dersBasisFuns(double u, size_t spanIdx, int derivativeLimit, std::vector<std::vector<double>> &ders) const {\n            // check\n            if (knotVector.empty()) {\n                std::cerr << \"Function dersBasisFuns: knotVector is empty!\" << std::endl;\n                return -1;\n            }\n\n            ders.resize(derivativeLimit + 1);\n            for (auto &it:ders) {\n                it.assign(degree + 1, 0);\n            }\n\n            double ndu[degree + 1][degree + 1]; // store the basis functions and knot differences\n\n            // store (in an alternating fashion) the two most recently computed rows a_{k,j} and a_{k-1,j}\n            double a[2][degree + 1];\n\n            std::vector<double> left, right;\n            left.resize(degree + 1);\n            right.resize(degree + 1);\n\n            ndu[0][0] = 1;\n            for (int j = 1; j <= degree; j++) {\n                left[j] = u - knotVector[spanIdx + 1 - j];\n                right[j] = knotVector[spanIdx + j] - u;\n                double saved = 0.0;\n                for (int r = 0; r < j; ++r) {\n                    ndu[j][r] = right[r + 1] + left[j - r];\n                    double temp = ndu[r][j - 1] / ndu[j][r];\n\n                    ndu[r][j] = saved + right[r + 1] * temp;\n                    saved = left[j - r] * temp;\n                }\n                ndu[j][j] = saved;\n            }\n\n            /* Load the basis functions */\n            for (int j = 0; j <= degree; j++)\n                ders[0][j] = ndu[j][degree];\n\n            if (derivativeLimit > 0) {\n                /*** This section computes the derivatives (Eq.[2.9]) ***/\n                /* Load over function index */\n                for (int r = 0; r <= degree; r++) {\n                    int s1 = 0, s2 = 1; // Alternate rows in array a\n                    a[0][0] = 1;\n\n                    // loop to compute kth derivative\n                    for (int k = 1; k <= derivativeLimit; k++) {\n                        double d = 0;\n                        int rk = r - k, pk = degree - k;\n                        if (r >= k) {\n                            a[s2][0] = a[s1][0] / ndu[pk + 1][rk];\n                            d = a[s2][0] * ndu[rk][pk];\n                        }\n\n                        int j1, j2;\n                        if (rk >= -1)\n                            j1 = 1;\n                        else\n                            j1 = -rk;\n\n                        if (r - 1 <= pk)\n                            j2 = k - 1;\n                        else\n                            j2 = degree - r;\n\n                        for (int j = j1; j <= j2; j++) {\n                            a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][rk + j];\n                            d += a[s2][j] * ndu[rk + j][pk];\n                        }\n\n                        if (r <= pk) {\n                            a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r];\n                            d += a[s2][k] * ndu[r][pk];\n                        }\n\n                        ders[k][r] = d;\n\n                        // switch rows\n                        std::swap(s1, s2);\n                    }\n                }\n\n                /* Multiply through by correct factors (Eq. [2.9]) */\n                int r = degree;\n                for (int k = 1; k <= derivativeLimit; ++k) {\n                    for (int j = 0; j <= degree; j++)\n                        ders[k][j] *= r;\n\n                    r *= (degree - k);\n                }\n            }\n\n            return 0;\n        }\n\n        /*\n         * Determine the knot span index i \\in [p,n], whole is [0,n+p+1]\n         * u \\in [u_{i}, u_{i+1}) , special at u==u_{n+1}\n         */\n        size_t findSpan(double u) const {\n            // assume it's totally p-smooth, which means there is only one knot for each boundary\n            // Notes: the size of knot vector is n+p+2\n            size_t n = knotVector.size() - 2 - degree;\n\n            // special case\n            if (u == knotVector[n + 1])\n                return n;\n\n            // binary search\n            size_t low = degree;\n            size_t high = n + 1;\n            size_t mid = (low + high) / 2;\n            while (u < knotVector[mid] || u >= knotVector[mid + 1]) {\n                if (u < knotVector[mid])\n                    high = mid;\n                else\n                    low = mid;\n\n                mid = (low + high) / 2;\n            }\n\n            return mid;\n        };\n\n        // shape won't change\n        int insertKnot(double u) {\n            if (knotVector.empty()) {\n                std::cerr << \"Function insertKnot: knotVector is empty!\" << std::endl;\n                return -1;\n            }\n            if (controlPoints.empty()) {\n                std::cerr << \"Function insertKnot: controlPoints is empty!\" << std::endl;\n                return -1;\n            }\n\n            size_t spanIdx = findSpan(u);\n            std::vector<Eigen::Matrix<double, dim, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, dim,\n                    1 >>> Q(controlPoints.size() + 1);\n\n            std::copy(controlPoints.begin(), controlPoints.begin() + spanIdx - degree + 1, Q.begin());\n            std::copy(controlPoints.begin() + spanIdx, controlPoints.end(), Q.begin() + spanIdx + 1);\n            for (size_t i = spanIdx - degree + 1; i <= spanIdx; i++) {\n                double alpha = (u - knotVector[i]) / (knotVector[i + degree] - knotVector[i]);\n                Q[i] = alpha * controlPoints[i] + (1 - alpha) * controlPoints[i - 1];\n            }\n\n            //update knotVector\n            knotVector.insert(knotVector.begin() + spanIdx + 1, u);\n            //update controlPoints\n            controlPoints = std::move(Q);\n\n            return 0;\n        };\n\n        // assume X: ascending sorted\n        int refineKnotVect(std::vector<double> &X) {\n            if (knotVector.empty()) {\n                std::cerr << \"Function refineKnotVect: knotVector is empty!\" << std::endl;\n                return -1;\n            }\n            if (controlPoints.empty()) {\n                std::cerr << \"Function refineKnotVect: controlPoints is empty!\" << std::endl;\n                return -1;\n            }\n\n            std::sort(X.begin(), X.end());\n\n            std::vector<Eigen::Matrix<double, dim, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, dim, 1>>> Q(\n                    controlPoints.size() + X.size());\n            std::vector<double> Ubar(knotVector.size() + X.size());\n\n            size_t n = knotVector.size() - 2 - degree;\n            size_t r = X.size() - 1;\n            size_t m = knotVector.size() - 1;\n            size_t a = findSpan(X.front());\n            size_t b = findSpan(X.back());\n            b++;\n\n            for (size_t j = 0; j <= a - degree; j++)\n                Q[j] = controlPoints[j];\n            for (size_t j = b - 1; j <= n; j++)\n                Q[j + X.size()] = controlPoints[j];\n            for (size_t j = 0; j <= a; j++)\n                Ubar[j] = knotVector[j];\n            for (size_t j = b + degree; j <= m; j++)\n                Ubar[j + X.size()] = knotVector[j];\n\n            int i = b + degree - 1;\n            int k = b + degree + r;\n            for (int j = r; j >= 0; j--) {\n                while (X[j] <= knotVector[i] && i > a) {\n                    Q[k - degree - 1] = controlPoints[i - degree - 1];\n                    Ubar[k] = knotVector[i];\n                    k--;\n                    i--;\n                }\n\n                Q[k - degree - 1] = Q[k - degree];\n                for (int l = 1; l <= degree; l++) {\n                    int idx = k - degree + l;\n                    double alpha = Ubar[k + l] - X[j];\n                    if (std::abs(alpha) == 0.0)\n                        Q[idx - 1] = Q[idx];\n                    else {\n                        alpha /= (Ubar[k + l] - knotVector[i - degree + l]);\n                        Q[idx - 1] = alpha * Q[idx - 1] + (1 - alpha) * Q[idx];\n                    }\n                }\n                Ubar[k] = X[j];\n                k--;\n            }\n\n            //update knotVector\n            knotVector = std::move(Ubar);\n            //update controlPoints\n            controlPoints = std::move(Q);\n            return 0;\n        };\n\n        // optimize control points w.r.t distance error after knot vector change\n        int optimization() {\n            /*** check ***/\n            if (dataPoints.empty()) {\n                std::cerr << \"Function optimize: dataPoints is empty!\" << std::endl;\n                return -1;\n            }\n            if (dataPoints.size() != derivatives.size() && derivatives.size() != 0) {\n                std::cerr\n                        << \"Function optimization: dataPoints ans derivatives should be same size (NAN for unknow) OR derivatives should be empty!\"\n                        << std::endl;\n                return -1;\n            }\n            if (knotVector.empty()) {\n                std::cerr << \"Function optimization: knotVector is empty!\" << std::endl;\n                return -1;\n            }\n\n            int controlPointsNum = knotVector.size() - degree - 1;\n\n            // initialize controlPoints\n            controlPoints.resize(controlPointsNum);\n            controlPoints.front() = dataPoints.front();\n            controlPoints.back() = dataPoints.back();\n\n            // support for derivative lacking\n            int derivativesCounter = 0;\n            std::vector<int> map(derivatives.size(), -1);\n            for (size_t k = 0; k < derivatives.size(); k++) {\n                if (!std::isnan(derivatives[k][0])) {\n                    map[k] = derivativesCounter++;\n                }\n            }\n\n            /*** Problem ***/\n            Eigen::SparseMatrix<double> N(dataPoints.size(), controlPointsNum);\n            Eigen::SparseMatrix<double> M(dataPoints.size(), controlPointsNum);\n            std::vector<std::vector<double>> ders;\n            for (int k = 0; k < dataPoints.size(); ++k) {\n                size_t spanIdx = findSpan(correspondingUs[k]);\n                dersBasisFuns(correspondingUs[k], spanIdx, derivativesCounter > 0 ? 1 : 0, ders);\n\n                for (int j = 0; j <= degree; ++j) {\n                    if (ders[0][j] != 0)\n                        N.insert(k, spanIdx - degree + j) = ders[0][j]; // N_{i-p+j,p}^{0}(\\bar{u}_k)\n\n                    if (derivativesCounter > 0) {\n                        if (ders[1][j] != 0)\n                            M.insert(k, spanIdx - degree + j) = ders[1][j]; // N_{i-p+j,p}^{1}(\\bar{u}_k)\n                    }\n                }\n            }\n\n            // formulating B\n            std::vector<Eigen::Matrix<double, dim, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, dim, 1>>> B;\n            B.assign(controlPointsNum - 2, Eigen::Matrix<double, dim, 1>::Zero());\n            for (int l = 1; l <= controlPointsNum - 2; ++l) {\n                // for l-th col of N\n                for (Eigen::SparseMatrix<double>::InnerIterator it(N, l); it; ++it) {\n                    // N_{l,p}(\\bar{u}_k), valid for column-major\n                    int k = it.row();\n                    if (k != 0 && k != dataPoints.size() - 1) {\n                        B[l - 1] += it.value() * (dataPoints[k] - N.coeff(k, 0) * dataPoints.front() -\n                                                  N.coeff(k, controlPointsNum - 1) * dataPoints.back());\n                    }\n                }\n\n                if (derivativesCounter > 0) {\n                    // for l-th col of M\n                    for (Eigen::SparseMatrix<double>::InnerIterator it(M, l); it; ++it) {\n                        // N_{l,p}^{1}(\\bar{u}_k), valid for column-major\n                        int k = it.row();\n                        if (map[k] > -1) {\n                            B[l - 1] += lambda * it.value() * (derivatives[k] - M.coeff(k, 0) * dataPoints.front() -\n                                                               M.coeff(k, controlPointsNum - 1) *\n                                                               dataPoints.back());\n                        }\n                    }\n                }\n            }\n\n            // formulating M,N\n            Eigen::SparseMatrix<double> Nc = N.block(1, 1, dataPoints.size() - 2, controlPointsNum - 2);\n            Eigen::SparseMatrix<double> A = Nc.transpose() * Nc;\n\n            if (derivativesCounter > 0) {\n                Eigen::SparseMatrix<double> Mc(derivativesCounter, controlPointsNum - 2);\n                for (int i = 1; i <= controlPointsNum - 2; ++i) {\n                    for (Eigen::SparseMatrix<double>::InnerIterator it(M, i); it; ++it) {// i-th col\n                        if (map[it.row()] > -1) {\n                            Mc.insert(map[it.row()], it.col() - 1) = it.value();\n                        }\n                    }\n                }\n                A += lambda * Mc.transpose() * Mc;\n            }\n\n            // solving\n            A.makeCompressed();\n            Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;\n            solver.compute(A);\n            if (solver.info() != Eigen::Success) {\n                std::cerr << \"Function optimization: decomposition failed!\" << std::endl;\n                return -1;\n            }\n            Eigen::VectorXd b(controlPointsNum - 2);\n            for (int i = 0; i < dim; i++) {\n                for (int j = 0; j < B.size(); ++j) {\n                    b[j] = B[j][i];\n                }\n                Eigen::VectorXd x = solver.solve(b);\n                if (solver.info() != Eigen::Success) {\n                    std::cerr << \"Function optimization: solving failed!\" << std::endl;\n                    return -1;\n                }\n                for (int j = 1; j <= controlPointsNum - 2; ++j) {\n                    controlPoints[j][i] = x[j - 1];\n                }\n            }\n\n            return 0;\n        };\n\n        /*\n         * Evaluate up to k-th derivative at u\n         */\n        int evaluate(double u, int derivativeLimit,\n                     std::vector<Eigen::Matrix<double, dim, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, dim, 1>>> &Ders) const {\n            if (controlPoints.empty()) {\n                std::cerr << \"Function evaluate: controlPoints is empty!\" << std::endl;\n                return -1;\n            }\n\n            Ders.assign(derivativeLimit + 1, Eigen::Matrix<double, dim, 1>::Zero());\n            std::vector<std::vector<double>> ders;\n            size_t spanIdx = findSpan(u);\n\n            dersBasisFuns(u, spanIdx, derivativeLimit, ders);\n\n            for (size_t i = 0; i < ders.size(); i++) {\n                for (size_t j = 0; j < ders[i].size(); ++j) {\n                    Ders[i] += ders[i][j] * controlPoints[spanIdx - degree + j];\n                }\n            }\n\n            return 0;\n        }\n\n        inline std::vector<Eigen::Matrix<double, dim, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, dim, 1>>> &\n        getCP() {\n            return controlPoints;\n        };\n\n        inline const std::vector<double> &getCorrespondingUs() {\n            return correspondingUs;\n        }\n\n        inline const std::vector<double> &getKnotVector() {\n            return knotVector;\n        }\n\n    protected:\n        int degree;\n\n        std::vector<double> knotVector;\n        std::vector<Eigen::Matrix<double, dim, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, dim, 1>>> controlPoints;\n\n        // optional\n        std::vector<Eigen::Matrix<double, dim, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, dim, 1>>> dataPoints;\n        std::vector<double> correspondingUs; //corresponding u for each data point\n        std::vector<Eigen::Matrix<double, dim, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, dim, 1>>> derivatives; //corresponding derivatives for each data point\n        double lambda;\n    };\n}\n\n#endif //OPENGV2_BSPLINEREAL_HPP\n", "meta": {"hexsha": "eae40b30f8d92585355a279cda7c763a2582f60d", "size": 20746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/spline/include/opengv2/spline/BsplineReal.hpp", "max_stars_repo_name": "MobilePerceptionLab/EventCameraCalibration", "max_stars_repo_head_hexsha": "debd774ac989674b500caf27641b7ad4e94681e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T03:21:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T03:40:54.000Z", "max_issues_repo_path": "modules/core/spline/include/opengv2/spline/BsplineReal.hpp", "max_issues_repo_name": "MobilePerceptionLab/MultiCamCalib", "max_issues_repo_head_hexsha": "2f0e94228c2c4aea7f20c26e3e8daa6321ce8022", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-25T02:55:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T15:18:45.000Z", "max_forks_repo_path": "modules/core/spline/include/opengv2/spline/BsplineReal.hpp", "max_forks_repo_name": "MobilePerceptionLab/MultiCamCalib", "max_forks_repo_head_hexsha": "2f0e94228c2c4aea7f20c26e3e8daa6321ce8022", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-11T12:29:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T03:41:01.000Z", "avg_line_length": 41.1626984127, "max_line_length": 243, "alphanum_fraction": 0.4363250747, "num_tokens": 4914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5194009016604113}}
{"text": "#ifndef PROCON_28_GEO_HPP\n#define PROCON_28_GEO_HPP\n\n#include <iostream>\n#include <vector>\n\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/segment.hpp>\n#include <boost/geometry/geometry.hpp>\n\nnamespace bg = boost::geometry;\nnamespace trans = bg::strategy::transform;\n\nnamespace procon28 {\nusing Point_Type = long double;                     // x, y\u5ea7\u6a19\u306b\u4f7f\u7528\u3059\u308b\u578b\nusing Point = bg::model::d2::point_xy<Point_Type>;  // \u5ea7\u6a19\nusing Polygon = bg::model::polygon<Point>;          // \u56f3\u5f62\nusing Segment = bg::model::segment<Point>;          // \u7dda\u5206\nusing Ring = typename Polygon::ring_type;\nusing InnerContainer = typename Polygon::inner_container_type;\nconst long double EPS = 1e-10;\nconst long double PI = std::acos(-1);\n\nstd::istream& operator>>(std::istream&, Polygon&);\nstd::ostream& operator<<(std::ostream&, Polygon&);\n\nconst Point operator+(const Point&, const Point&);\nconst Point operator-(const Point&, const Point&);\n\nPoint get_point(const Ring&, int);\nPoint get_point(const Polygon&, int);\nPoint get_point(const Segment&, int);\nSegment inv_segment(const Segment&);\nSegment get_segment(const Ring&, int, int);\nSegment get_segment(const Polygon&, int, int);\nSegment get_segment(const Ring&, int);\nSegment get_segment(const Polygon&, int);\nlong double get_angle(const Segment&);\nlong double get_angle(const Segment&, const Segment&);\nlong double get_corner(const Ring&, int);\nlong double get_corner(const Polygon&, int);\nPoint to_vec(const Segment&);\nPolygon to_frame(const std::vector<Polygon>&);\nstd::vector<Polygon> to_piece(const Polygon&);\nPolygon translate(const Polygon&, Point_Type, Point_Type);\nPolygon translate(const Polygon&, Point);\nPolygon rotate(const Polygon&, long double);\nPolygon rotate(const Polygon&, long double, Point);\nPolygon inverse(const Polygon&);\nPolygon scale(const Polygon&, double);\nvoid printFrame(const Polygon&, std::ostream&);\n\n}  // namespace procon28\n\n#endif\n", "meta": {"hexsha": "6db5e673dd31c4ed068195d563a1646adf339803", "size": 1977, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Geo.hpp", "max_stars_repo_name": "kurokoji/procon28-kurosolver", "max_stars_repo_head_hexsha": "2e50b35a85dc33a95ca1f40f6c6487874f389460", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-10T10:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-10T10:58:26.000Z", "max_issues_repo_path": "src/Geo.hpp", "max_issues_repo_name": "kurokoji/procon28-kurosolver", "max_issues_repo_head_hexsha": "2e50b35a85dc33a95ca1f40f6c6487874f389460", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Geo.hpp", "max_forks_repo_name": "kurokoji/procon28-kurosolver", "max_forks_repo_head_hexsha": "2e50b35a85dc33a95ca1f40f6c6487874f389460", "max_forks_repo_licenses": ["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.6842105263, "max_line_length": 67, "alphanum_fraction": 0.7445624684, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.519328876586458}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu> Licensed\n * under the MIT license. See the license file LICENSE.\n */\n#pragma once\n\n#include <stdint.h>\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <unsupported/Eigen/MatrixFunctions>\n\n// CUDA runtime\n#include <cuda_runtime.h>\n// Utilities and system includes\n//#include <helper_functions.h>\n#include <nvidia/helper_cuda.h>\n\n//#include <mmf/defines.h>\n#include <mmf/sphereSimple.hpp>\n#include <mmf/optimizationSO3.hpp>\n#include <manifold/SO3.h>\n#include <jsCore/vmf.h>\n\nusing namespace Eigen;\n\nextern void MMFvMFCostFctAssignmentGPU(float *h_cost, float *d_cost,\n  uint32_t *h_W, uint32_t *d_W, float *d_x, float* d_weights, \n  uint32_t *d_z, float *d_mu, float*d_pi, int N, int K);\n\nnamespace mmf{\n\n// closed form solution for the vMF cost function.\nclass OptSO3MMFvMF : public OptSO3\n{\n  public:\n  OptSO3MMFvMF(uint32_t K, float *d_weights =NULL):\n    OptSO3(1.,1.,0.1,d_weights), \n    Rs_(K, Eigen::Matrix3f::Identity()),\n    pi_(K*6), taus_(Eigen::VectorXf::Ones(K*6)),\n    estimateTau_(false)\n  { \n    // overwrite cld\n    cld_ = jsc::ClDataGpu<float>(3,6*K);\n    if(d_cost) checkCudaErrors(cudaFree(d_cost));\n    if(d_mu_)  checkCudaErrors(cudaFree(d_mu_));\n    if(d_N_) checkCudaErrors(cudaFree(d_N_));\n    for (uint32_t k=0; k<K; ++k)\n      Rs_[k] = SO3f::Random().matrix();\n    init();\n  };\n\n  virtual ~OptSO3MMFvMF() { };\n  uint32_t K() {return Rs_.size();};\n  virtual std::vector<Eigen::Matrix3f> GetRs() { return Rs_; };\n\nprotected:\n  std::vector<Eigen::Matrix3f> Rs_;\n  jsc::GpuMatrix<float> pi_;\n  Eigen::VectorXf taus_;\n  bool estimateTau_;\n\n  virtual float computeAssignment(uint32_t& N);\n\n  virtual float conjugateGradientCUDA_impl(Matrix3f& R, float res0,\n    uint32_t N, uint32_t maxIter);\n  virtual void conjugateGradientPostparation_impl(Matrix3f& R);\n  virtual float conjugateGradientPreparation_impl(Matrix3f& R, uint32_t& N);\n  /* evaluate cost function for a given assignment of npormals to axes */\n  virtual float evalCostFunction(Matrix3f& R);\n  /* compute Jacobian */\n  virtual void computeJacobian(Matrix3f&J, Matrix3f& R, float N);\n  virtual void init();\n\n  /* copy rotation to device */\n  void Rot2Device();\n};\n\n}\n", "meta": {"hexsha": "83e4244bd2532c431d80f06ce7ef96f463258b39", "size": 2256, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mmf/optimizationSO3_mmfvmf.hpp", "max_stars_repo_name": "jstraub/mmf", "max_stars_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-06-02T04:17:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T05:44:53.000Z", "max_issues_repo_path": "include/mmf/optimizationSO3_mmfvmf.hpp", "max_issues_repo_name": "jstraub/mmf", "max_issues_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "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/mmf/optimizationSO3_mmfvmf.hpp", "max_forks_repo_name": "jstraub/mmf", "max_forks_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-06T04:34:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-28T06:35:00.000Z", "avg_line_length": 28.2, "max_line_length": 76, "alphanum_fraction": 0.7087765957, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.5193288654362666}}
{"text": "#include <vector>\n\n#include <boost/shared_ptr.hpp>\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n\n#include <cmath>\n\n#include \"caffe/blob.hpp\"\n#include \"caffe/common.hpp\"\n#include \"caffe/layers/st_layer.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n\nnamespace caffe {\n\ntemplate <typename Dtype>\nvoid SpatialTransformerLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top) {\n\n\tstring prefix = \"\\t\\tSpatial Transformer Layer:: LayerSetUp: \\t\";\n\n\tif(this->layer_param_.st_param().transform_type() == \"affine\") {\n\t\ttransform_type_ = \"affine\";\n\t} else {\n\t\tCHECK(false) << prefix << \"Transformation type only supports affine now!\" << std::endl;\n\t}\n\n\tif(this->layer_param_.st_param().sampler_type() == \"bilinear\") {\n\t\tsampler_type_ = \"bilinear\";\n\t} else {\n\t\tCHECK(false) << prefix << \"Sampler type only supports bilinear now!\" << std::endl;\n\t}\n\n\tif(this->layer_param_.st_param().to_compute_du()) {\n\t\tto_compute_dU_ = true;\n\t}\n\n\tstd::cout<<prefix<<\"Getting output_H_ and output_W_\"<<std::endl;\n\n\toutput_H_ = bottom[0]->shape(2);\n\tif(this->layer_param_.st_param().has_output_h()) {\n\t\toutput_H_ = this->layer_param_.st_param().output_h();\n\t}\n\toutput_W_ = bottom[0]->shape(3);\n\tif(this->layer_param_.st_param().has_output_w()) {\n\t\toutput_W_ = this->layer_param_.st_param().output_w();\n\t}\n\n\tstd::cout<<prefix<<\"output_H_ = \"<<output_H_<<\", output_W_ = \"<<output_W_<<std::endl;\n\n\tstd::cout<<prefix<<\"Getting pre-defined parameters\"<<std::endl;\n\n\tis_pre_defined_theta[0] = false;\n\tif(this->layer_param_.st_param().has_theta_1_1()) {\n\t\tis_pre_defined_theta[0] = true;\n\t\t++ pre_defined_count;\n\t\tpre_defined_theta[0] = this->layer_param_.st_param().theta_1_1();\n\t\tstd::cout<<prefix<<\"Getting pre-defined theta[1][1] = \"<<pre_defined_theta[0]<<std::endl;\n\t}\n\n\tis_pre_defined_theta[1] = false;\n\tif(this->layer_param_.st_param().has_theta_1_2()) {\n\t\tis_pre_defined_theta[1] = true;\n\t\t++ pre_defined_count;\n\t\tpre_defined_theta[1] = this->layer_param_.st_param().theta_1_2();\n\t\tstd::cout<<prefix<<\"Getting pre-defined theta[1][2] = \"<<pre_defined_theta[1]<<std::endl;\n\t}\n\n\tis_pre_defined_theta[2] = false;\n\tif(this->layer_param_.st_param().has_theta_1_3()) {\n\t\tis_pre_defined_theta[2] = true;\n\t\t++ pre_defined_count;\n\t\tpre_defined_theta[2] = this->layer_param_.st_param().theta_1_3();\n\t\tstd::cout<<prefix<<\"Getting pre-defined theta[1][3] = \"<<pre_defined_theta[2]<<std::endl;\n\t}\n\n\tis_pre_defined_theta[3] = false;\n\tif(this->layer_param_.st_param().has_theta_2_1()) {\n\t\tis_pre_defined_theta[3] = true;\n\t\t++ pre_defined_count;\n\t\tpre_defined_theta[3] = this->layer_param_.st_param().theta_2_1();\n\t\tstd::cout<<prefix<<\"Getting pre-defined theta[2][1] = \"<<pre_defined_theta[3]<<std::endl;\n\t}\n\n\tis_pre_defined_theta[4] = false;\n\tif(this->layer_param_.st_param().has_theta_2_2()) {\n\t\tis_pre_defined_theta[4] = true;\n\t\t++ pre_defined_count;\n\t\tpre_defined_theta[4] = this->layer_param_.st_param().theta_2_2();\n\t\tstd::cout<<prefix<<\"Getting pre-defined theta[2][2] = \"<<pre_defined_theta[4]<<std::endl;\n\t}\n\n\tis_pre_defined_theta[5] = false;\n\tif(this->layer_param_.st_param().has_theta_2_3()) {\n\t\tis_pre_defined_theta[5] = true;\n\t\t++ pre_defined_count;\n\t\tpre_defined_theta[5] = this->layer_param_.st_param().theta_2_3();\n\t\tstd::cout<<prefix<<\"Getting pre-defined theta[2][3] = \"<<pre_defined_theta[5]<<std::endl;\n\t}\n\n\t// check the validation for the parameter theta\n\tCHECK(bottom[1]->count(1) + pre_defined_count == 6) << \"The dimension of theta is not six!\"\n\t\t\t<< \" Only \" << bottom[1]->count(1) << \" + \" << pre_defined_count << std::endl;\n\tCHECK(bottom[1]->shape(0) == bottom[0]->shape(0)) << \"The first dimension of theta and \" <<\n\t\t\t\"U should be the same\" << std::endl;\n\n\t// initialize the matrix for output grid\n\tstd::cout<<prefix<<\"Initializing the matrix for output grid\"<<std::endl;\n\n\tvector<int> shape_output(2);\n\tshape_output[0] = output_H_ * output_W_; shape_output[1] = 3;\n\toutput_grid.Reshape(shape_output);\n\n\tDtype* data = output_grid.mutable_cpu_data();\n\tfor(int i=0; i<output_H_ * output_W_; ++i) {\n\t\tdata[3 * i] = (i / output_W_) * 1.0 / output_H_ * 2 - 1;\n\t\tdata[3 * i + 1] = (i % output_W_) * 1.0 / output_W_ * 2 - 1;\n\t\tdata[3 * i + 2] = 1;\n\t}\n\n\t// initialize the matrix for input grid\n\tstd::cout<<prefix<<\"Initializing the matrix for input grid\"<<std::endl;\n\n\tvector<int> shape_input(3);\n\tshape_input[0] = bottom[1]->shape(0); shape_input[1] = output_H_ * output_W_; shape_input[2] = 2;\n\tinput_grid.Reshape(shape_input);\n\n\tstd::cout<<prefix<<\"Initialization finished.\"<<std::endl;\n}\n\ntemplate <typename Dtype>\nvoid SpatialTransformerLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top) {\n\n\tstring prefix = \"\\t\\tSpatial Transformer Layer:: Reshape: \\t\";\n\n\tif(global_debug) std::cout<<prefix<<\"Starting!\"<<std::endl;\n\n\tN = bottom[0]->shape(0);\n\tC = bottom[0]->shape(1);\n\tH = bottom[0]->shape(2);\n\tW = bottom[0]->shape(3);\n\n\t// reshape V\n\tvector<int> shape(4);\n\n\tshape[0] = N;\n\tshape[1] = C;\n\tshape[2] = output_H_;\n\tshape[3] = output_W_;\n\n\ttop[0]->Reshape(shape);\n\n\t// reshape dTheta_tmp\n\tvector<int> dTheta_tmp_shape(4);\n\n\tdTheta_tmp_shape[0] = N;\n\tdTheta_tmp_shape[1] = 2;\n\tdTheta_tmp_shape[2] = 3;\n\tdTheta_tmp_shape[3] = output_H_ * output_W_ * C;\n\n\tdTheta_tmp.Reshape(dTheta_tmp_shape);\n\n\t// init all_ones_2\n\tvector<int> all_ones_2_shape(1);\n\tall_ones_2_shape[0] = output_H_ * output_W_ * C;\n\tall_ones_2.Reshape(all_ones_2_shape);\n\n\t// reshape full_theta\n\tvector<int> full_theta_shape(2);\n\tfull_theta_shape[0] = N;\n\tfull_theta_shape[1] = 6;\n\tfull_theta.Reshape(full_theta_shape);\n\n\tif(global_debug) std::cout<<prefix<<\"Finished.\"<<std::endl;\n}\n\ntemplate <typename Dtype>\nDtype SpatialTransformerLayer<Dtype>::transform_forward_cpu(const Dtype* pic, Dtype px, Dtype py) {\n\n\tbool debug = false;\n\n\tstring prefix = \"\\t\\tSpatial Transformer Layer:: transform_forward_cpu: \\t\";\n\n\tif(debug) std::cout<<prefix<<\"Starting!\\t\"<<std::endl;\n\tif(debug) std::cout<<prefix<<\"(px, py) = (\"<<px<<\", \"<<py<<\")\"<<std::endl;\n\n\tDtype res = (Dtype)0.;\n\n\tDtype x = (px + 1) / 2 * H; Dtype y = (py + 1) / 2 * W;\n\n\tif(debug) std::cout<<prefix<<\"(x, y) = (\"<<x<<\", \"<<y<<\")\"<<std::endl;\n\n\tint m, n; Dtype w;\n\n\tm = floor(x); n = floor(y); w = 0;\n\tif(debug) std::cout<<prefix<<\"1: (m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\t\tres += w * pic[m * W + n];\n\t\tif(debug) std::cout<<prefix<<\"w = \"<<w<<\", pic[m, n] = \"<<pic[m * W + n]<<std::endl;\n\t}\n\n\tm = floor(x) + 1; n = floor(y); w = 0;\n\tif(debug) std::cout<<prefix<<\"2: (m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\t\tres += w * pic[m * W + n];\n\t\tif(debug) std::cout<<prefix<<\"w = \"<<w<<\", pic[m, n] = \"<<pic[m * W + n]<<std::endl;\n\t}\n\n\tm = floor(x); n = floor(y) + 1; w = 0;\n\tif(debug) std::cout<<prefix<<\"3: (m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\t\tres += w * pic[m * W + n];\n\t\tif(debug) std::cout<<prefix<<\"w = \"<<w<<\", pic[m, n] = \"<<pic[m * W + n]<<std::endl;\n\t}\n\n\tm = floor(x) + 1; n = floor(y) + 1; w = 0;\n\tif(debug) std::cout<<prefix<<\"4: (m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\t\tres += w * pic[m * W + n];\n\t\tif(debug) std::cout<<prefix<<\"w = \"<<w<<\", pic[m, n] = \"<<pic[m * W + n]<<std::endl;\n\t}\n\n\tif(debug) std::cout<<prefix<<\"Finished. \\tres = \"<<res<<std::endl;\n\n\treturn res;\n}\n\ntemplate <typename Dtype>\nvoid SpatialTransformerLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n    const vector<Blob<Dtype>*>& top) {\n\n\tstring prefix = \"\\t\\tSpatial Transformer Layer:: Forward_cpu: \\t\";\n\n\t// CHECK(false) << \"Don't use the CPU implementation! If you really want to, delete the\" <<\n\t//\t\t\" CHECK in st_layer.cpp file. Line number: 240-241.\" << std::endl;\n\n\tif(global_debug) std::cout<<prefix<<\"Starting!\"<<std::endl;\n\n\tconst Dtype* U = bottom[0]->cpu_data();\n\tconst Dtype* theta = bottom[1]->cpu_data();\n\tconst Dtype* output_grid_data = output_grid.cpu_data();\n\n\tDtype* input_grid_data = input_grid.mutable_cpu_data();\n\tDtype* V = top[0]->mutable_cpu_data();\n\n\tcaffe_set(input_grid.count(), (Dtype)0, input_grid_data);\n\tcaffe_set(top[0]->count(), (Dtype)0, V);\n\n\t// for each input\n\tfor(int i = 0; i < N; ++i) {\n\n\t\tDtype* coordinates = input_grid_data + (output_H_ * output_W_ * 2) * i;\n\n\t\tcaffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, output_H_ * output_W_, 2, 3, (Dtype)1.,\n\t\t      output_grid_data, theta + 6 * i, (Dtype)0., coordinates);\n\n\t\tint row_idx; Dtype px, py;\n\n\t\tfor(int j = 0; j < C; ++j)\n\t\t\tfor(int s = 0; s < output_H_; ++s)\n\t\t\t\tfor(int t = 0; t < output_W_; ++t) {\n\n\t\t\t\t\trow_idx = output_W_ * s + t;\n\n\t\t\t\t\tpx = coordinates[row_idx * 2];\n\t\t\t\t\tpy = coordinates[row_idx * 2 + 1];\n\n\t\t\t\t\tV[top[0]->offset(i, j, s, t)] = transform_forward_cpu(\n\t\t\t\t\t\t\tU + bottom[0]->offset(i, j, 0, 0), px, py);\n\t\t\t\t}\n\t}\n\n\tif(global_debug) std::cout<<prefix<<\"Finished.\"<<std::endl;\n}\n\ntemplate <typename Dtype>\nvoid SpatialTransformerLayer<Dtype>::transform_backward_cpu(Dtype dV, const Dtype* U, const Dtype px,\n\t\tconst Dtype py, Dtype* dU, Dtype& dpx, Dtype& dpy) {\n\n\tbool debug = false;\n\n\tstring prefix = \"\\t\\tSpatial Transformer Layer:: transform_backward_cpu: \\t\";\n\n\tif(debug) std::cout<<prefix<<\"Starting!\"<<std::endl;\n\n\tDtype x = (px + 1) / 2 * H; Dtype y = (py + 1) / 2 * W;\n\tif(debug) std::cout<<prefix<<\"(x, y) = (\"<<x<<\", \"<<y<<\")\"<<std::endl;\n\n\tint m, n; Dtype w;\n\n\tm = floor(x); n = floor(y); w = 0;\n\tif(debug) std::cout<<prefix<<\"(m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\n\t\tdU[m * W + n] += w * dV;\n\n\t\tif(abs(x - m) < 1) {\n\t\t\tif(m >= x) {\n\t\t\t\tdpx += max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx += \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpx -= max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx -= \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t}\n\t\t}\n\n\t\tif(abs(y - n) < 1) {\n\t\t\tif(n >= y) {\n\t\t\t\tdpy += max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy += \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpy -= max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy -= \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\tm = floor(x) + 1; n = floor(y); w = 0;\n\tif(debug) std::cout<<prefix<<\"(m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\n\t\tdU[m * W + n] += w * dV;\n\n\t\tif(abs(x - m) < 1) {\n\t\t\tif(m >= x) {\n\t\t\t\tdpx += max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx += \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpx -= max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx -= \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t}\n\t\t}\n\n\t\tif(abs(y - n) < 1) {\n\t\t\tif(n >= y) {\n\t\t\t\tdpy += max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy += \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpy -= max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy -= \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\tm = floor(x); n = floor(y) + 1; w = 0;\n\tif(debug) std::cout<<prefix<<\"(m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\n\t\tdU[m * W + n] += w * dV;\n\n\t\tif(abs(x - m) < 1) {\n\t\t\tif(m >= x) {\n\t\t\t\tdpx += max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx += \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpx -= max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx -= \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t}\n\t\t}\n\n\t\tif(abs(y - n) < 1) {\n\t\t\tif(n >= y) {\n\t\t\t\tdpy += max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy += \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpy -= max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy -= \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\tm = floor(x) + 1; n = floor(y) + 1; w = 0;\n\tif(debug) std::cout<<prefix<<\"(m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\n\t\tdU[m * W + n] += w * dV;\n\n\t\tif(abs(x - m) < 1) {\n\t\t\tif(m >= x) {\n\t\t\t\tdpx += max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx += \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpx -= max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx -= \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t}\n\t\t}\n\n\t\tif(abs(y - n) < 1) {\n\t\t\tif(n >= y) {\n\t\t\t\tdpy += max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy += \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpy -= max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy -= \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(debug) std::cout<<prefix<<\"Finished.\"<<std::endl;\n}\n\ntemplate <typename Dtype>\nvoid SpatialTransformerLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,\n    const vector<bool>& propagate_down,\n    const vector<Blob<Dtype>*>& bottom) {\n\n\t\tstring prefix = \"\\t\\tSpatial Transformer Layer:: Backward_cpu: \\t\";\n\n\t\t// CHECK(false) << \"Don't use the CPU implementation! If you really want to, delete the\" <<\n\t\t//\t\t\" CHECK in st_layer.cpp file. Line number: 420-421.\" << std::endl;\n\n\t\tif(global_debug) std::cout<<prefix<<\"Starting!\"<<std::endl;\n\n\t\tconst Dtype* dV = top[0]->cpu_diff();\n\t\tconst Dtype* input_grid_data = input_grid.cpu_data();\n\t\tconst Dtype* U = bottom[0]->cpu_data();\n\n\t\tDtype* dU = bottom[0]->mutable_cpu_diff();\n\t\tDtype* dTheta = bottom[1]->mutable_cpu_diff();\n\t\tDtype* input_grid_diff = input_grid.mutable_cpu_diff();\n\n\t\tcaffe_set(bottom[0]->count(), (Dtype)0, dU);\n\t\tcaffe_set(bottom[1]->count(), (Dtype)0, dTheta);\n\t\tcaffe_set(input_grid.count(), (Dtype)0, input_grid_diff);\n\n\t\tfor(int i = 0; i < N; ++i) {\n\n\t\t\tconst Dtype* coordinates = input_grid_data + (output_H_ * output_W_ * 2) * i;\n\t\t\tDtype* coordinates_diff = input_grid_diff + (output_H_ * output_W_ * 2) * i;\n\n\t\t\tint row_idx; Dtype px, py, dpx, dpy, delta_dpx, delta_dpy;\n\n\t\t\tfor(int s = 0; s < output_H_; ++s)\n\t\t\t\tfor(int t = 0; t < output_W_; ++t) {\n\n\t\t\t\t\trow_idx = output_W_ * s + t;\n\n\t\t\t\t\tpx = coordinates[row_idx * 2];\n\t\t\t\t\tpy = coordinates[row_idx * 2 + 1];\n\n\t\t\t\t\tfor(int j = 0; j < C; ++j) {\n\n\t\t\t\t\t\tdelta_dpx = delta_dpy = (Dtype)0.;\n\n\t\t\t\t\t\ttransform_backward_cpu(dV[top[0]->offset(i, j, s, t)], U + bottom[0]->offset(i, j, 0, 0),\n\t\t\t\t\t\t\t\tpx, py, dU + bottom[0]->offset(i, j, 0, 0), delta_dpx, delta_dpy);\n\n\t\t\t\t\t\tcoordinates_diff[row_idx * 2] += delta_dpx;\n\t\t\t\t\t\tcoordinates_diff[row_idx * 2 + 1] += delta_dpy;\n\t\t\t\t\t}\n\n\t\t\t\t\tdpx = coordinates_diff[row_idx * 2];\n\t\t\t\t\tdpy = coordinates_diff[row_idx * 2 + 1];\n\n\t\t\t\t\tdTheta[6 * i] += dpx * (s * 1.0 / output_H_ * 2 - 1);\n\t\t\t\t\tdTheta[6 * i + 1] += dpx * (t * 1.0 / output_W_ * 2 - 1);\n\t\t\t\t\tdTheta[6 * i + 2] += dpx;\n\t\t\t\t\tdTheta[6 * i + 3] += dpy * (s * 1.0 / output_H_ * 2 - 1);\n\t\t\t\t\tdTheta[6 * i + 4] += dpy * (t * 1.0 / output_W_ * 2 - 1);\n\t\t\t\t\tdTheta[6 * i + 5] += dpy;\n\t\t\t\t}\n\t\t}\n\n\t\tif(global_debug) std::cout<<prefix<<\"Finished.\"<<std::endl;\n}\n\n#ifdef CPU_ONLY\nSTUB_GPU(SpatialTransformerLayer);\n#endif\n\nINSTANTIATE_CLASS(SpatialTransformerLayer);\nREGISTER_LAYER_CLASS(SpatialTransformer);\n\n}  // namespace caffe\n", "meta": {"hexsha": "60506262aecf28ab43cff853f17617eeede9e54d", "size": 16507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/layers/st_layer.cpp", "max_stars_repo_name": "dangweili/caffe", "max_stars_repo_head_hexsha": "9b46693346314dd00b4f3ddae55c2ce875c6ec62", "max_stars_repo_licenses": ["Intel", "BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-08T09:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T06:11:19.000Z", "max_issues_repo_path": "src/caffe/layers/st_layer.cpp", "max_issues_repo_name": "dangweili/caffe", "max_issues_repo_head_hexsha": "9b46693346314dd00b4f3ddae55c2ce875c6ec62", "max_issues_repo_licenses": ["Intel", "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/caffe/layers/st_layer.cpp", "max_forks_repo_name": "dangweili/caffe", "max_forks_repo_head_hexsha": "9b46693346314dd00b4f3ddae55c2ce875c6ec62", "max_forks_repo_licenses": ["Intel", "BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-02-04T09:00:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-16T07:12:19.000Z", "avg_line_length": 33.5508130081, "max_line_length": 124, "alphanum_fraction": 0.5555218998, "num_tokens": 6012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6334102567576902, "lm_q1q2_score": 0.5193288595651032}}
{"text": "#include \"cuNDFFT.h\"\n#include \"cuNDArray_math.h\"\n#include \"complext.h\"\n#include <gtest/gtest.h>\n#include <boost/random.hpp>\n\nusing namespace Gadgetron;\nusing testing::Types;\n\ntemplate<typename REAL> class cuNDFFT_test : public ::testing::Test {\nprotected:\n\tvirtual void SetUp(){\n\t\tboost::random::mt19937 rng;\n\t\tboost::random::uniform_real_distribution<REAL> uni(0,1);\n\t\tstd::vector<size_t > dimensions(3,128);\n\n\t\thoNDArray<complext<REAL> > tmp(dimensions);\n\t\tcomplext<REAL>* data = tmp.get_data_ptr();\n\n\t\tfor (size_t i = 0; i < tmp.get_number_of_elements(); i++)\n\t\t\tdata[i] = complext<REAL>(uni(rng),uni(rng));\n\n\t\tArray = cuNDArray<complext<REAL> >(tmp);\n\t\tArray2 = Array;\n\t}\n\n\tcuNDArray<complext<REAL> > Array;\n\n\tcuNDArray<complext<REAL> > Array2;\n\n};\ntypedef Types<float, double> realImplementations;\nTYPED_TEST_SUITE(cuNDFFT_test, realImplementations);\n\nTYPED_TEST(cuNDFFT_test,fftNrm2Test){\n\tcuNDFFT<TypeParam>::instance()->fft(&this->Array);\n\n\tEXPECT_NEAR(nrm2(&this->Array2),nrm2(&this->Array),nrm2(&this->Array)*1e-3);\n\n}\n\nTYPED_TEST(cuNDFFT_test,ifftNrm2Test){\n\tcuNDFFT<TypeParam>::instance()->ifft(&this->Array);\n\n\tEXPECT_NEAR(nrm2(&this->Array2),nrm2(&this->Array),nrm2(&this->Array)*1e-3);\n\n}\n", "meta": {"hexsha": "f32aa1af3d9b1fc4ad85f23f7d7b0dbce2774f12", "size": 1204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cuNDFFT_test.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "test/cuNDFFT_test.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "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/cuNDFFT_test.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["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.0833333333, "max_line_length": 77, "alphanum_fraction": 0.7209302326, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5193288540886969}}
{"text": "#ifndef PCP_ALGORITHM_BILATERAL_FILTER_HPP\n#define PCP_ALGORITHM_BILATERAL_FILTER_HPP\n\n/**\n * @file\n * @ingroup algorithm\n */\n\n#include \"pcp/common/norm.hpp\"\n#include \"pcp/common/vector3d.hpp\"\n#include \"pcp/kdtree/linked_kdtree.hpp\"\n#include \"pcp/traits/output_iterator_traits.hpp\"\n#include \"pcp/traits/point_map.hpp\"\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <array>\n#include <execution>\n#include <vector>\n\nnamespace pcp {\nnamespace algorithm {\nnamespace bilateral {\n\n/**\n * @brief\n * Parameters for the bilateral filtering algorithm\n */\nstruct params_t\n{\n    double sigmaf = 1.;  ///< Standard deviation for the support region of spatial weight function f\n    double sigmag = 0.1; ///< Standard deviation for the influence weight function g\n    std::size_t K = 1u;  ///< Number of iterations of bilateral filtering\n};\n\nnamespace detail {\n\ntemplate <\n    class KdTree,\n    class CoordinateMap,\n    class PointMap,\n    class NormalMap,\n    class SpatialWeightFunction,\n    class InfluenceWeightFunction,\n    class ProjectionFunction,\n    class ScalarType>\nstd::invoke_result_t<PointMap, std::size_t> compute_pi(\n    std::size_t const i,\n    ScalarType const sigmaf,\n    ScalarType const sigmag,\n    KdTree const& kdtree,\n    CoordinateMap const& coordinate_map,\n    PointMap const& point_map,\n    NormalMap const& normal_map,\n    SpatialWeightFunction const& f,\n    InfluenceWeightFunction const& g,\n    ProjectionFunction const& projection)\n{\n    using scalar_type = ScalarType;\n    using point_type  = std::invoke_result_t<PointMap, std::size_t>;\n    using normal_type = std::invoke_result_t<NormalMap, std::size_t>;\n\n    scalar_type constexpr two  = scalar_type{2.};\n    scalar_type constexpr zero = scalar_type{0.};\n\n    auto const s  = point_map(i);\n    auto const ci = coordinate_map(i);\n\n    sphere_a<scalar_type> support_region{};\n    support_region.position = ci;\n    support_region.radius   = two * sigmaf;\n\n    auto const neighbors = kdtree.range_search(support_region);\n\n    scalar_type k = zero;\n    point_type sprime{zero, zero, zero};\n    for (auto it = neighbors.begin(); it != neighbors.end(); ++it)\n    {\n        point_type const p           = point_map(*it);\n        normal_type const np         = normal_map(*it);\n        point_type const s_projected = projection(p, np, s);\n\n        scalar_type const rf = common::norm(s - p);\n        scalar_type const rg = common::norm(s_projected - s);\n\n        scalar_type const wf = f(sigmaf, rf);\n        scalar_type const wg = g(sigmag, rg);\n\n        scalar_type const w = wf * wg;\n        k += w;\n        common::basic_vector3d_t<scalar_type> translation{\n            w * s_projected.x(),\n            w * s_projected.y(),\n            w * s_projected.z()};\n        sprime = sprime + translation;\n    }\n    sprime = sprime / k;\n\n    return sprime;\n}\n\ntemplate <\n    class KdTree,\n    class CoordinateMap,\n    class PointMap,\n    class NormalMap,\n    class SpatialWeightFunction,\n    class SpatialWeightFunctionDerivative,\n    class InfluenceWeightFunction,\n    class InfluenceWeightFunctionDerivative,\n    class ProjectionFunction,\n    class ScalarType>\nstd::invoke_result_t<NormalMap, std::size_t> compute_ni(\n    std::size_t const i,\n    ScalarType const sigmaf,\n    ScalarType const sigmag,\n    KdTree const& kdtree,\n    CoordinateMap const& coordinate_map,\n    PointMap const& point_map,\n    NormalMap const& normal_map,\n    SpatialWeightFunction const& f,\n    SpatialWeightFunctionDerivative const& df,\n    InfluenceWeightFunction const& g,\n    InfluenceWeightFunctionDerivative const& dg,\n    ProjectionFunction const& projection)\n{\n    using scalar_type           = ScalarType;\n    using point_type            = std::invoke_result_t<PointMap, std::size_t>;\n    using normal_type           = std::invoke_result_t<NormalMap, std::size_t>;\n    using matrix_3d_type        = Eigen::Matrix<scalar_type, 3, 3>;\n    using column_vector_3d_type = Eigen::Matrix<scalar_type, 3, 1>;\n    using row_vector_3d_type    = Eigen::Matrix<scalar_type, 1, 3>;\n\n    scalar_type constexpr two  = scalar_type{2.};\n    scalar_type constexpr zero = scalar_type{0.};\n\n    point_type const pcp_s = point_map(i);\n    column_vector_3d_type const s{pcp_s.x(), pcp_s.y(), pcp_s.z()};\n    auto const ci = coordinate_map(i);\n\n    sphere_a<scalar_type> support_region{};\n    support_region.position = ci;\n    support_region.radius   = two * sigmaf;\n\n    auto const neighbors = kdtree.range_search(support_region);\n\n    /**\n     * Jacobian of sum of:\n     *\n     * projection(s) * f(||s - p||) * g(||projection(s) - s||)\n     */\n    matrix_3d_type J_pi_f_g;\n    J_pi_f_g.setZero();\n    /**\n     * sum of:\n     *\n     * projection(s) * f(||s - p||) * g(||projection(s) - s||)\n     */\n    column_vector_3d_type pi_f_g;\n    pi_f_g.setZero();\n    /**\n     * Gradient of k(s)\n     */\n    row_vector_3d_type grad_k;\n    grad_k.setZero();\n    /**\n     * k(s)\n     */\n    scalar_type k = zero;\n\n    for (auto it = neighbors.begin(); it != neighbors.end(); ++it)\n    {\n        point_type const pcp_p           = point_map(*it);\n        normal_type const pcp_np         = normal_map(*it);\n        point_type const pcp_s_projected = projection(pcp_p, pcp_np, pcp_s);\n\n        column_vector_3d_type const p{pcp_p.x(), pcp_p.y(), pcp_p.z()};\n        column_vector_3d_type const np{pcp_np.nx(), pcp_np.ny(), pcp_np.nz()};\n        column_vector_3d_type const s_projected{\n            pcp_s_projected.x(),\n            pcp_s_projected.y(),\n            pcp_s_projected.z()};\n\n        column_vector_3d_type const sp  = s - p;\n        column_vector_3d_type const sps = s_projected - s;\n        scalar_type const rf            = sp.norm();\n        scalar_type const rg            = sps.norm();\n\n        // f(||s - p||)\n        scalar_type const wf = f(sigmaf, rf);\n        // g(||projection(s) - s||)\n        scalar_type const wg = g(sigmag, rg);\n\n        scalar_type const w = wf * wg;\n\n        // k(s) = sum f(||s - p||) * g(||projection(s) - s||)\n        k += w;\n\n        // projection(s) * f(||s - p||) * g(||projection(s) - s||)\n        column_vector_3d_type translation{\n            w * pcp_s_projected.x(),\n            w * pcp_s_projected.y(),\n            w * pcp_s_projected.z()};\n        pi_f_g += translation;\n\n        // derivative df/dr | r=||s-p||\n        scalar_type const wdf            = df(sigmaf, rf);\n        row_vector_3d_type const sp_unit = sp.normalized().transpose();\n        // grad(f) = (s - p) / ||s - p|| * (df/dr | r=||s-p||)\n        row_vector_3d_type const grad_f = sp_unit * wdf;\n\n        // Jacobian of projection(s)\n        matrix_3d_type Jpi;\n        Jpi(0, 0) = 1 - (np.x() * np.x());\n        Jpi(1, 1) = 1 - (np.y() * np.y());\n        Jpi(2, 2) = 1 - (np.z() * np.z());\n        Jpi(0, 1) = np.x() * np.y();\n        Jpi(0, 2) = np.x() * np.z();\n        Jpi(1, 2) = np.y() * np.z();\n        Jpi(1, 0) = Jpi(0, 1);\n        Jpi(2, 0) = Jpi(0, 2);\n        Jpi(2, 1) = Jpi(1, 2);\n\n        // derivative dg/dr | r = ||projection(s) - s||\n        scalar_type const wdg             = dg(sigmag, rg);\n        row_vector_3d_type const sps_unit = sps.normalized().transpose();\n        /**\n         * Let sps_unit = (projection(s) - s) / ||projection(s) - s||\n         *\n         * grad(g) =\n         * (sps_unit * Jacobian(projection(s)) - sps_unit) *\n         * (dg/dr | r = ||projection(s) - s||)\n         */\n        row_vector_3d_type const grad_g = (sps_unit * Jpi - sps_unit) * wdg;\n\n        /**\n         * Product rule grad(f(||s - p||) * g(||projection(s) - s||))\n         */\n        grad_k += (grad_f * wg) + (wf * grad_g);\n        /**\n         * Product rule grad(projection(s) * f(||s - p||) * g(||projection(s) - s||))\n         */\n        J_pi_f_g += (Jpi * wf * wg) + (sps * grad_f * wg) + (sps * wf * grad_g);\n    }\n\n    /**\n     * Quotient rule grad(u/v) = (1/v^2) * (grad(u)*v - u*grad(v))\n     */\n    scalar_type const ks2_inv = scalar_type{1.} / (k * k);\n    matrix_3d_type const J    = ks2_inv * (J_pi_f_g * k - pi_f_g * grad_k);\n\n    normal_type const pcp_ns = normal_map(i);\n    column_vector_3d_type const ns{pcp_ns.nx(), pcp_ns.ny(), pcp_ns.nz()};\n\n    /**\n     * In the original normal improvement paper, they use the inverse transpose\n     * of the jacobian. In our case, we directly use the jacobian\n     * of the filter F(s), because it is in line with the intuition\n     * of using the local spatial deformation of the field F(s) to\n     * adjust normals.\n     */\n    // ns' = J^(-T) * ns\n    // matrix_3d_type const adj       = J.adjoint();\n    column_vector_3d_type ns_prime = J * ns;\n    ns_prime.normalize();\n    return normal_type{ns_prime.x(), ns_prime.y(), ns_prime.z()};\n}\n\n} // namespace detail\n} // namespace bilateral\n\n/**\n * @ingroup smoothing-algorithm\n * @brief\n * Uses a bilateral filter to smooth an input point cloud.\n *\n * The bilateral filter is defined in the same way as in\n * 'Jones, Thouis R., Fredo Durand, and Matthias Zwicker. \"Normal improvement for point rendering.\"\n * IEEE Computer Graphics and Applications 24.4 (2004): 53-56.'\n *\n * Internally, the filtering needs a temporary copy of the points p(k)\n * to compute p(k+1), the points at the next iteration. At each iteration,\n * a kd-tree must be built over the points p(k) to support optimized\n * range search queries.\n *\n * The transformation F (the bilateral filter) over our points P is done in parallel at each\n * iteration k.\n *\n * @tparam RandomAccessIter Iterator type satisfying Random Access requirements\n * @tparam OutputIter Iterator type dereferenceable to a type satisfying Point concept\n * @tparam PointMap Type satisfying PointMap concept\n * @tparam NormalMap Type satisfying NormalMap concept\n * @param begin Start iterator of input point cloud\n * @param end End iterator of input point cloud\n * @param out_begin Start iterator of output points\n * @param point_map The point map property map\n * @param normal_map The normal map property map\n * @param params The bilateral filter algorithm's parameters\n * @return End iterator of output sequence\n */\ntemplate <class RandomAccessIter, class OutputIter, class PointMap, class NormalMap>\nOutputIter bilateral_filter_points(\n    RandomAccessIter begin,\n    RandomAccessIter end,\n    OutputIter out_begin,\n    PointMap const& point_map,\n    NormalMap const& normal_map,\n    bilateral::params_t const& params)\n{\n    using input_element_type = typename std::iterator_traits<RandomAccessIter>::value_type;\n    using input_point_type   = std::invoke_result_t<PointMap, input_element_type>;\n    using input_normal_type  = std::invoke_result_t<NormalMap, input_element_type>;\n    using scalar_type        = typename input_point_type::coordinate_type;\n    using output_point_type  = typename xstd::output_iterator_traits<OutputIter>::value_type;\n    // using difference_type    = typename std::iterator_traits<RandomAccessIter>::difference_type;\n\n    static_assert(\n        traits::is_point_map_v<PointMap, input_element_type>,\n        \"point_map must satisfy PointMap concept\");\n\n    static_assert(\n        traits::is_point_v<output_point_type>,\n        \"OutputIter must be dereferenceable to a type satisfying Point concept\");\n\n    std::size_t const N        = static_cast<std::size_t>(std::distance(begin, end));\n    scalar_type const sigmaf   = static_cast<scalar_type>(params.sigmaf);\n    scalar_type const sigmag   = static_cast<scalar_type>(params.sigmag);\n    std::size_t const K        = params.K;\n    scalar_type constexpr pi   = static_cast<scalar_type>(3.14159265358979323846);\n    scalar_type constexpr zero = scalar_type{0.};\n\n    assert(K > 0u);\n    assert(N > 0u);\n    assert(sigmaf > zero);\n    assert(sigmag > zero);\n\n    std::vector<std::size_t> indices(N);\n    std::iota(indices.begin(), indices.end(), 0u);\n\n    std::vector<input_point_type> points(N);\n    std::transform(begin, end, points.begin(), [&](input_element_type const& e) {\n        return point_map(e);\n    });\n\n    std::vector<input_point_type> temporary_points(N);\n\n    std::vector<input_normal_type> normals(N);\n    std::transform(begin, end, normals.begin(), [&](input_element_type const& e) {\n        return normal_map(e);\n    });\n\n    auto const internal_point_map = [&](std::size_t const i) {\n        return points[i];\n    };\n    auto const internal_normal_map = [&](std::size_t const i) {\n        return normals[i];\n    };\n\n    auto const gaussian = [=](scalar_type const sigma, scalar_type const r) -> scalar_type {\n        scalar_type const s2      = sigma * sigma;\n        scalar_type const r2      = r * r;\n        scalar_type const power   = -r2 / (2 * s2);\n        scalar_type constexpr one = scalar_type{1.};\n        scalar_type constexpr two = scalar_type{2.};\n        scalar_type const coeff   = one / (sigma * std::sqrt(two * pi));\n        return coeff * std::exp(power);\n    };\n\n    auto const projection = [&](input_point_type const& p,\n                                input_normal_type const& np,\n                                input_point_type const& s) -> input_point_type {\n        auto const sp = p - s;\n        common::basic_vector3d_t<scalar_type> const n{np.nx(), np.ny(), np.nz()};\n        auto const d = common::inner_product(sp, n);\n        return s + d * n;\n    };\n\n    using coordinates_type = std::array<scalar_type, 3u>;\n\n    auto const coordinate_map = [&](std::size_t const pe) {\n        auto const p = internal_point_map(pe);\n        return coordinates_type{p.x(), p.y(), p.z()};\n    };\n\n    kdtree::construction_params_t kdtree_params;\n    kdtree_params.compute_max_depth     = true;\n    kdtree_params.construction          = kdtree::construction_t::nth_element;\n    kdtree_params.max_elements_per_leaf = 64u;\n\n    for (std::size_t k = 0u; k < K; ++k)\n    {\n        basic_linked_kdtree_t<input_element_type, 3u, decltype(coordinate_map)> kdtree{\n            indices.begin(),\n            indices.end(),\n            coordinate_map,\n            kdtree_params};\n\n        std::transform(\n            std::execution::par,\n            indices.begin(),\n            indices.end(),\n            temporary_points.begin(),\n            [&](std::size_t const i) {\n                return bilateral::detail::compute_pi(\n                    i,\n                    sigmaf,\n                    sigmag,\n                    kdtree,\n                    coordinate_map,\n                    internal_point_map,\n                    internal_normal_map,\n                    gaussian,\n                    gaussian,\n                    projection);\n            });\n\n        std::copy(temporary_points.begin(), temporary_points.end(), points.begin());\n    }\n\n    return std::copy(points.begin(), points.end(), out_begin);\n}\n\n/**\n * @ingroup smoothing-algorithm\n * @brief\n * Deforms the normal field of an input point cloud using the local deformation field of the\n * 3d bilateral filter (in other words, its Jacobian at a point p).\n *\n * The bilateral filter is defined in the same way as in\n * 'Jones, Thouis R., Fredo Durand, and Matthias Zwicker. \"Normal improvement for point rendering.\"\n * IEEE Computer Graphics and Applications 24.4 (2004): 53-56.'\n *\n * This method should be used only for point rendering. It does not smooth input normals as one\n * would expect for surface reconstruction. For normal smoothing, one should rather look at\n * techniques such as EAR (edge aware resampling):\n *\n * 'Huang, Hui, et al. \"Edge-aware point set resampling.\" ACM transactions on graphics (TOG) 32.1\n * (2013): 1-12.'\n *\n * @tparam RandomAccessIter Iterator type satisfying Random Access requirements\n * @tparam OutputIter Iterator type dereferenceable to a type satisfying Normal concept\n * @tparam PointMap Type satisfying PointMap concept\n * @tparam NormalMap Type satisfying NormalMap concept\n * @param begin Start iterator of input point cloud\n * @param end End iterator of input point cloud\n * @param out_begin Start iterator of output points\n * @param point_map The point map property map\n * @param normal_map The normal map property map\n * @param params The bilateral filter algorithm's parameters\n * @return End iterator of output sequence\n */\ntemplate <class RandomAccessIter, class OutputIter, class PointMap, class NormalMap>\nOutputIter bilateral_filter_normals(\n    RandomAccessIter begin,\n    RandomAccessIter end,\n    OutputIter out_begin,\n    PointMap const& point_map,\n    NormalMap const& normal_map,\n    bilateral::params_t const& params)\n{\n    using input_element_type = typename std::iterator_traits<RandomAccessIter>::value_type;\n    using input_point_type   = std::invoke_result_t<PointMap, input_element_type>;\n    using input_normal_type  = std::invoke_result_t<NormalMap, input_element_type>;\n    using scalar_type        = typename input_point_type::coordinate_type;\n    using output_normal_type = typename xstd::output_iterator_traits<OutputIter>::value_type;\n    using difference_type    = typename std::iterator_traits<RandomAccessIter>::difference_type;\n\n    static_assert(\n        traits::is_point_map_v<PointMap, input_element_type>,\n        \"point_map must satisfy PointMap concept\");\n\n    std::size_t const N        = static_cast<std::size_t>(std::distance(begin, end));\n    scalar_type const sigmaf   = static_cast<scalar_type>(params.sigmaf);\n    scalar_type const sigmag   = static_cast<scalar_type>(params.sigmag);\n    std::size_t const K        = params.K;\n    scalar_type constexpr pi   = static_cast<scalar_type>(3.14159265358979323846);\n    scalar_type constexpr zero = scalar_type{0.};\n\n    assert(K > 0u);\n    assert(N > 0u);\n    assert(sigmaf > zero);\n    assert(sigmag > zero);\n\n    std::vector<std::size_t> indices(N);\n    std::iota(indices.begin(), indices.end(), 0u);\n\n    std::vector<input_normal_type> normals(N);\n    std::transform(begin, end, normals.begin(), [&](input_element_type const& e) {\n        return normal_map(e);\n    });\n\n    std::vector<input_normal_type> temporary_normals(N);\n\n    auto const internal_point_map = [&](std::size_t const i) -> input_point_type {\n        return point_map(*std::next(begin, static_cast<difference_type>(i)));\n    };\n    auto const internal_normal_map = [&](std::size_t const i) -> input_normal_type {\n        return normals[i];\n    };\n\n    auto const gaussian = [=](scalar_type const sigma, scalar_type const r) {\n        scalar_type const s2      = sigma * sigma;\n        scalar_type const r2      = r * r;\n        scalar_type const power   = -r2 / (2 * s2);\n        scalar_type constexpr one = scalar_type{1.};\n        scalar_type constexpr two = scalar_type{2.};\n        scalar_type const coeff   = one / (sigma * std::sqrt(two * pi));\n        return coeff * std::exp(power);\n    };\n\n    auto const dgaussian = [=](scalar_type const sigma, scalar_type const r) {\n        scalar_type const s2      = sigma * sigma;\n        scalar_type const s3      = sigma * s2;\n        scalar_type const r2      = r * r;\n        scalar_type const power   = -r2 / (2 * s2);\n        scalar_type constexpr two = scalar_type{2.};\n        scalar_type const coeff   = -r / (s3 * std::sqrt(two * pi));\n        return coeff * std::exp(power);\n    };\n\n    auto const projection = [&](input_point_type const& p,\n                                input_normal_type const& np,\n                                input_point_type const& s) -> input_point_type {\n        auto const sp = p - s;\n        common::basic_vector3d_t<scalar_type> const n{np.nx(), np.ny(), np.nz()};\n        auto const d = common::inner_product(sp, n);\n        return s + d * n;\n    };\n\n    using coordinates_type = std::array<scalar_type, 3u>;\n\n    auto const coordinate_map = [&](std::size_t const i) {\n        auto const p = internal_point_map(i);\n        return coordinates_type{p.x(), p.y(), p.z()};\n    };\n\n    kdtree::construction_params_t kdtree_params;\n    kdtree_params.compute_max_depth     = true;\n    kdtree_params.construction          = kdtree::construction_t::nth_element;\n    kdtree_params.max_elements_per_leaf = 64u;\n\n    basic_linked_kdtree_t<input_element_type, 3u, decltype(coordinate_map)> kdtree{\n        indices.begin(),\n        indices.end(),\n        coordinate_map,\n        kdtree_params};\n\n    for (std::size_t k = 0u; k < K; ++k)\n    {\n        std::transform(\n            std::execution::par,\n            indices.begin(),\n            indices.end(),\n            temporary_normals.begin(),\n            [&](std::size_t const i) {\n                return bilateral::detail::compute_ni(\n                    i,\n                    sigmaf,\n                    sigmag,\n                    kdtree,\n                    coordinate_map,\n                    internal_point_map,\n                    internal_normal_map,\n                    gaussian,\n                    dgaussian,\n                    gaussian,\n                    dgaussian,\n                    projection);\n            });\n\n        std::copy(temporary_normals.begin(), temporary_normals.end(), normals.begin());\n    }\n\n    return std::copy(normals.begin(), normals.end(), out_begin);\n}\n\n} // namespace algorithm\n} // namespace pcp\n\n#endif // PCP_ALGORITHM_BILATERAL_FILTER_HPP\n", "meta": {"hexsha": "b714f7840c251239fe0060767befdcf79153ffcd", "size": 21003, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pcp/algorithm/bilateral_filter.hpp", "max_stars_repo_name": "Q-Minh/octree", "max_stars_repo_head_hexsha": "0c3fd5a791d660b37461daf968a68ffb1c80b965", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-10T09:57:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T21:19:57.000Z", "max_issues_repo_path": "include/pcp/algorithm/bilateral_filter.hpp", "max_issues_repo_name": "Q-Minh/octree", "max_issues_repo_head_hexsha": "0c3fd5a791d660b37461daf968a68ffb1c80b965", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2020-12-07T20:09:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-12T20:42:59.000Z", "max_forks_repo_path": "include/pcp/algorithm/bilateral_filter.hpp", "max_forks_repo_name": "Q-Minh/octree", "max_forks_repo_head_hexsha": "0c3fd5a791d660b37461daf968a68ffb1c80b965", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1497418244, "max_line_length": 100, "alphanum_fraction": 0.6299100129, "num_tokens": 5226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.519328848513601}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include \"ukf.h\"\n\nusing Eigen::MatrixXd;\n\nint main() {\n\n  // Create a UKF instance\n  UKF ukf;\n\n  /**\n   * Programming assignment calls\n   */\n  MatrixXd Xsig = MatrixXd(5, 11);\n  ukf.GenerateSigmaPoints(&Xsig);\n\n  // print result\n  std::cout << \"Xsig = \" << std::endl << Xsig << std::endl;\n\n  return 0;\n}", "meta": {"hexsha": "81b9539cbcc7afe3e2ab383e8d10c8cea25a4786", "size": 346, "ext": "cc", "lang": "C++", "max_stars_repo_path": "SFND_Kalman_Filter/UKF_Prep/generating_sigma_points/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/UKF_Prep/generating_sigma_points/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/UKF_Prep/generating_sigma_points/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": 15.7272727273, "max_line_length": 59, "alphanum_fraction": 0.6184971098, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.519328848513601}}
{"text": "#include <iostream>\n#include <boost/filesystem.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include \"tiny_cnn/tiny_cnn.h\"\n\nusing namespace tiny_cnn;\nusing namespace tiny_cnn::activation;\nnamespace fs = boost::filesystem;\n\nstd::string label_strs[14] = {\n    \"3\", \"C\", \"D\", \"E\", \"F\", \"H\", \"J\", \"K\", \"L\", \"M\", \"N\", \"W\", \"X\", \"Y\"\n};\n\nvoid construct_net(network<sequential>& nn) {\n    // connection table [Y.Lecun, 1998 Table.1]\n#define O true\n#define X false\n    static const bool tbl[] = {\n        O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O,\n        O, O, X, X, X, O, O, O, X, X, O, O, O, O, X, O,\n        O, O, O, X, X, X, O, O, O, X, X, O, X, O, O, O,\n        X, O, O, O, X, X, O, O, O, O, X, X, O, X, O, O,\n        X, X, O, O, O, X, X, O, O, O, O, X, O, O, X, O,\n        X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O\n    };\n#undef O\n#undef X\n\n    // construct nets\n    nn << convolutional_layer<tan_h>(32, 32, 5, 1, 6)  // C1, 1@32x32-in, 6@28x28-out\n       << average_pooling_layer<tan_h>(28, 28, 6, 2)   // S2, 6@28x28-in, 6@14x14-out\n       << convolutional_layer<tan_h>(14, 14, 5, 6, 16,\n            connection_table(tbl, 6, 16))              // C3, 6@14x14-in, 16@10x10-in\n       << average_pooling_layer<tan_h>(10, 10, 16, 2)  // S4, 16@10x10-in, 16@5x5-out\n       << convolutional_layer<tan_h>(5, 5, 5, 16, 120) // C5, 16@5x5-in, 120@1x1-out\n       << fully_connected_layer<tan_h>(120, 14);       // F6, 120-in, 14-out\n}\n\n// convert image to vec_t\nvoid convert_image(const std::string& imagefilename,\n    double minv,\n    double maxv,\n    int w,\n    int h,\n    vec_t& data) {\n    auto img = cv::imread(imagefilename, cv::IMREAD_GRAYSCALE);\n    if (img.data == nullptr) return; // cannot open, or it's not an image\n\n    cv::Mat_<uint8_t> resized;\n    cv::resize(img, resized, cv::Size(w, h));\n\n    // mnist dataset is \"white on black\", so negate required\n    std::transform(resized.begin(), resized.end(), std::back_inserter(data),\n        [=](uint8_t c) { return (255 - c) * (maxv - minv) / 255.0 + minv; });\n}\n\n\nvoid load_dataset(std::vector<label_t> &train_labels,\n                  std::vector<vec_t> &train_images,\n                  std::vector<label_t> &test_labels,\n                  std::vector<vec_t> &test_images)\n{\n    for (int i = 0; i < 14; ++i){\n        std::vector<std::string> images;\n\n        fs::directory_iterator end_iter;\n        fs::path path(\"./training_set/\"+label_strs[i]);\n        for (fs::directory_iterator iter(path); iter != end_iter; ++iter){\n            if (fs::extension(*iter)==\".png\"){\n                images.push_back(iter->path().string());\n            }\n        }\n\n        //train_set.size() : test_set.size() = 4:1\n        int flag = 0;\n        std::vector<std::string>::iterator itr = images.begin();\n        for (;itr != images.end(); ++itr){\n            vec_t data;\n            convert_image(*itr, -1.0, 1.0, 32, 32, data);\n            if (flag <= 4){\n                train_labels.push_back(i);\n                train_images.push_back(data);\n            }else{\n                test_labels.push_back(i);\n                test_images.push_back(data);\n                flag = 0;\n            }\n            flag++; \n        }\n    }\n}\n\nint main(int argc, char **argv) {\n    // specify loss-function and learning strategy\n    network<sequential> nn;\n    adagrad optimizer;\n\n    construct_net(nn);\n\n    std::cout << \"load models...\" << std::endl;\n\n    // load training set and test set.\n    std::vector<label_t> train_labels;\n    std::vector<label_t> test_labels;\n    std::vector<vec_t> train_images;\n    std::vector<vec_t> test_images;\n\n    load_dataset(train_labels, train_images, test_labels, test_images);\n\n    std::cout << \"start training: \"<<train_images.size()<<\" examples...\"<< std::endl;\n\n    progress_display disp(train_images.size());\n    timer t;\n    int minibatch_size = 100;\n    int num_epochs = 50;\n\n    // optimizer.alpha *= std::sqrt(minibatch_size);\n\n    // create callback\n    auto on_enumerate_epoch = [&](){\n        std::cout << t.elapsed() << \"s elapsed.\" << std::endl;\n        tiny_cnn::result res = nn.test(test_images, test_labels);\n        std::cout << res.num_success << \"/\" << res.num_total << std::endl;\n        disp.restart(train_images.size());\n        t.restart();\n    };\n\n    auto on_enumerate_minibatch = [&](){\n        disp += minibatch_size;\n    };\n\n    // training\n    nn.train<mse>(optimizer, train_images, train_labels, minibatch_size, num_epochs,\n             on_enumerate_minibatch, on_enumerate_epoch);\n\n    std::cout << \"end training.\" << std::endl;\n\n    // save networks\n    std::ofstream ofs(\"weibo.cn-nn-weights\");\n    ofs << nn;\n}\n", "meta": {"hexsha": "0ab51a6b4693793d4fa5fe212e4bb58f2f055baa", "size": 4692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "weibo.cn/cpp/trainer/main.cpp", "max_stars_repo_name": "LeWeis/captcha-break", "max_stars_repo_head_hexsha": "6427b8d42b7916a896fd684756830457f0683ee2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 772.0, "max_stars_repo_stars_event_min_datetime": "2016-06-20T13:32:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T21:05:51.000Z", "max_issues_repo_path": "weibo.cn/cpp/trainer/main.cpp", "max_issues_repo_name": "LeWeis/captcha-break", "max_issues_repo_head_hexsha": "6427b8d42b7916a896fd684756830457f0683ee2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2016-11-05T05:16:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-23T01:45:23.000Z", "max_forks_repo_path": "weibo.cn/cpp/trainer/main.cpp", "max_forks_repo_name": "LeWeis/captcha-break", "max_forks_repo_head_hexsha": "6427b8d42b7916a896fd684756830457f0683ee2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 256.0, "max_forks_repo_forks_event_min_datetime": "2016-09-04T13:46:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T18:49:37.000Z", "avg_line_length": 32.5833333333, "max_line_length": 85, "alphanum_fraction": 0.5637254902, "num_tokens": 1448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5193288427411271}}
{"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_ASECH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASECH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-hyperbolic\n    This function returns the hyperbolic secant argument \\f$\\mathop{\\textrm{acosh}}(1/x)\\f$\n\n    @par Header <boost/simd/function/asech.hpp>\n\n    @see cosh, acosh, sinh, asinh, atanh, atanh, acoth, acsch\n\n    @par Example:\n\n      @snippet asech.cpp asech\n\n    @par Possible output:\n\n      @snippet asech.txt asech\n\n  **/\n  IEEEValue asech(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/asech.hpp>\n#include <boost/simd/function/simd/asech.hpp>\n\n#endif\n", "meta": {"hexsha": "9970c0853d911f875f6a402f1938a361d696d18e", "size": 1063, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/asech.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/function/asech.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/function/asech.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": 24.1590909091, "max_line_length": 100, "alphanum_fraction": 0.5813734713, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083132, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5193282230523338}}
{"text": "#ifndef ENKF_HPP\n#define ENKF_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n#include <vector>\n#include <functional>\n#include <utility>\n#include <cassert>\n#include <random>\n#include <cmath>\n#include <iostream>\n\nnamespace fastmath\n{\n  using Vec = Eigen::VectorXd;\n  using Mat = Eigen::MatrixXd;\n\n  template<class State_t, class Obs_t, class ObsOp_t, class... ForecastArgs>\n  class EnKF\n  {\n  public:\n    \n    constexpr EnKF() {};\n\n    //filter with one observation\n    /* virtual void filter(const Obs_t& y);*/\n\n    virtual Obs_t observe(const State_t& x);\n\n    virtual State_t forecast(State_t& x, ForecastArgs&... args);\n\n    virtual ~EnKF() {};\n  };\n\n  //scalar EnKF with linear observations\n  template<class... ForecastArgs>\n  class VectorEnKF : public EnKF<Vec, Vec, Mat, ForecastArgs...>\n  {\n\n private:\n\n    Mat  m_H;\n\n    Vec m_state;\n\n    Vec m_obs = m_H * m_state;\n\n    std::function<Vec(Vec&, ForecastArgs&...)> m_forecast;\n\n    Vec m_ensemble_mean;\n\n    Mat m_ensemble_covariance;\n\n    Mat m_obs_covariance;\n\n    int m_ensemble_size;\n\n    int m_dimension;\n\n    Mat m_ensemble = Mat::Zero(m_dimension, m_ensemble_size);\n\n    bool m_initialized_ensemble = false;\n\n    Mat m_background_covariance = Mat::Identity(m_dimension, m_dimension);\n\n    Mat m_ensemble_transform = gen_covariance_transform(m_ensemble_covariance);\n  public:\n\n    VectorEnKF(const std::function<Vec(Vec&, ForecastArgs&...)>& n_forecast,\n\t\t\t const Mat& n_H,\n\t\t\t const Vec& n_initial_state,\n\t\t\t const Mat& n_observe_err_covariance,\n\t\t\t const Vec& n_initial_ensemble_mean,\n\t\t\t const Mat&   n_initial_ensemble_covariance,\n\t\t\t const int    n_ensemble_size\n\t\t\t ) : EnKF<Vec, Vec, Mat, ForecastArgs...>(),\n\t\t\t     m_H(n_H),\n\t\t\t     m_state(n_initial_state),\n\t\t\t     m_forecast(n_forecast),\n\t\t\t     m_ensemble_mean(n_initial_ensemble_mean),\n\t\t\t     m_ensemble_covariance(n_initial_ensemble_covariance),\n\t\t\t     m_obs_covariance(n_observe_err_covariance),\n\t\t\t     m_ensemble_size(n_ensemble_size),\n\t\t\t     m_dimension(static_cast<int>(n_initial_state.size()))\n\t\t\t     \n    {};\n\n\n    void set_state(const Vec& n_state) noexcept\n    {\n      m_state = n_state;\n    }\n\n    void set_ensemble_size(const int n_ensemble_size) noexcept\n    {\n      assert(n_ensemble_size > 0);\n      m_ensemble_size = n_ensemble_size;\n    }\n     \n\n    Vec state()\n    {\n      return m_state;\n    }\n\n    int ensemble_size()\n    {\n      return m_ensemble_size;\n    }\n\n    Vec ensemble_mean()\n    {\n      return m_ensemble_mean;\n    }\n\n    Mat ensemble_covariance()\n    {\n      return m_ensemble_covariance;\n    }\n    \n    Vec observe(const Vec& x){\n      return m_H * x;\n    }\n\n    Vec forecast(Vec& x, ForecastArgs&... args){\n      return m_forecast(x, args...);\n    }\n\n\n  private:\n\n    Mat gen_covariance_transform(const Mat& target_covariance) const\n    {\n      return target_covariance.ldlt().matrixL();\n    }\n\n    Mat gen_obs_perturbations()\n    {\n      auto rcovtransform = gen_covariance_transform(m_obs_covariance);\n\n      std::random_device rd{};\n      std::mt19937 gen{rd()};\n      std::normal_distribution<> dis{0.0, 1.0};\n\n      Mat A(m_H.rows(), m_ensemble_size);\n      Vec epsilon(m_H.rows());\n\n      for(auto i = 0; i < m_ensemble_size; ++i){\n\tfor(auto e = 0; e < m_H.rows(); ++e){\n\t  epsilon[e] = dis(gen);\n\t}\n\tA.col(i) = epsilon;\n      }\n\n      return rcovtransform * A;\n    }\n      \n\n    Mat gen_ensemble_perturbations(bool gen_cov_transform=true)\n    {\n      std::random_device rd{};\n      std::mt19937 gen{rd()};\n      std::normal_distribution<> dis{0.0, 1.0};\n\n      Mat A(m_dimension,m_ensemble_size);\n      Vec epsilon(m_dimension);\n\n      if(gen_cov_transform){\n\tm_ensemble_transform = gen_covariance_transform(m_ensemble_covariance);\n      }\n\n\n      for(auto i = 0; i < m_ensemble_size; ++i){\n\tfor(auto e = 0; e < m_dimension; ++e){\n\t  epsilon[e] = dis(gen);\n\t}\n\tA.col(i) = epsilon + m_ensemble_mean;\n      }\n      \n      return  m_ensemble_transform * A;// * A;\n    }\n\n  /*std::pair<Vec,Mat> sample_mean_covariance(const std::vector<Vec>& sample)\n    {\n      Vec mu(sample[0].size());\n\n      for(auto i = 0; i < m_ensemble_size; ++i){\n\tfor(auto i = 0; i < sample[0].size(); ++i){\n\t  mu[i] += s[i];\n\t}\n      }\n\n      mu /= sample.size();\n     \n      Mat cov = Mat::Zero(sample.size(), sample.size());\n\n      for(const auto& s : sample){\n\tauto delta = s - mu;\n\tcov.noalias() += delta * delta.transpose();\n      }\n\n      cov /= (sample.size() - 1);\n\n      return std::make_pair(mu, cov);\n      }*/\n      \n    //A is the result of a call to form_A\n    Mat kalman_gain_A(const Mat& A)\n    {\n      auto V = m_H * A;\n\n      auto vvr = V * V.transpose();// + m_obs_covariance;\n      return A * V.transpose() * vvr.inverse();\n    }   \n\n    //copy ensemble here \n    Mat form_A(Mat ensemble)\n    {\n      for(auto i = 0; i < m_ensemble_size; ++i){\n\tensemble.col(i) -= m_ensemble_mean;\n      }\n\n      return ensemble / std::sqrt(m_ensemble_size - 1);\n    }\n\n    Mat kalman_gain_ensemble(const Mat& ensemble)\n    {\n      auto A = form_A(ensemble);\n      return kalman_gain_A(A);\n    }\n\n    //B matrix given an ensemble\n    Mat ensemble_prior_covariance(const Mat& A)\n    {\n      return A * A.transpose();\n    }\n      \n\n    Vec ensemble_member_update(const Mat& K, const Vec& perturbed_y, const Vec& xi)\n    {\n      auto err = perturbed_y - m_H * xi;\n\n      return xi + K * err;\n    }\n\n    Mat ensemble_update(const Mat& K, const Mat& perturbed_yvals, const Mat& ensemble_xvals)\n    {\n      Mat updated_xvals(ensemble_xvals.rows(), ensemble_xvals.cols());\n      for(auto i = 0; i < m_ensemble_size; ++i){\n\tupdated_xvals.col(i) = ensemble_member_update(K, perturbed_yvals.col(i), ensemble_xvals.col(i));\n      }\n      return updated_xvals;\n    }\n\n    Mat ETKF_ensemble_update_mat(Mat& A)\n    {\n      auto V = m_H * A;\n      auto Id = Mat::Identity(m_ensemble_size);\n      auto emat = Id + V.transpose() * m_obs_covariance.inverse() * V;\n\n      Eigen::SelfAdjointEigenSolver<Mat> esolver(emat);\n\n      assert(esolver.info() == Eigen::Success);//, \"ETKF eigendecomposition failed.\");\n\n      Mat Gamma = esolver.eigenvalues().asDiagonal();/* I + Gamma in the notes*/\n      auto Q = esolver.eigenvectors();\n\n      for(auto i = 0; i < Gamma.cols(); ++i){\n\tGamma(i,i) = std::sqrt(Gamma(i,i));\n      }\n\n      return Q * Gamma * Q.transpose();\n    }\n\n    Mat ETKF_posterior_ensemble(Mat& A)\n    {\n      // A is prior ensemble\n      auto X = ETKF_ensemble_update_mat(A);\n      auto one = Vec::Ones(m_ensemble_size);\n      auto aplus = A * one / m_ensemble_size;\n      return A - aplus * one.transpose();\n    }\n      \n\n    Mat ensemble_posterior_covariance(const Mat& B, const Mat& K)\n    {\n      return B - K * m_H * B;\n    }\n\n    \n\n  public:\n\n    void ETKF_filter(Vec& obs, ForecastArgs&... args)\n    {\n      for(auto i = 0; i < m_ensemble_size; ++i){\n\t  m_ensemble.col(i) = m_state;\n\t}\n\n      m_ensemble += gen_ensemble_perturbations();\n\n      m_ensemble = ETKF_posterior_ensemble(m_ensemble);\n\n      m_state = m_ensemble.rowwise().mean();\n\n      m_ensemble_mean = m_state;\n\n      m_ensemble_covariance = m_ensemble * m_ensemble.transpose();\n    }\n      \n\n    void filter(Vec& obs, ForecastArgs&... args)\n    {\n      // generate ensemble\n      if(!m_initialized_ensemble){\n\tfor(auto i = 0; i < m_ensemble_size; ++i){\n\t  m_ensemble.col(i) = m_state;\n\t}\n\t//m_initialized_ensemble = true;\n      }\n      m_ensemble += gen_ensemble_perturbations();\n      /* forecast ensemble */\n      for(auto i = 0; i < m_ensemble_size; ++i){\n\tVec xstate = m_ensemble.col(i);\n\tm_ensemble.col(i) = m_forecast(xstate, args...);\n      }\n\n      m_ensemble_mean = m_ensemble.rowwise().mean();\n      \n      auto A = form_A(m_ensemble);\n      m_background_covariance = A * A.transpose();\n \n      Mat obs_perturbed = gen_obs_perturbations();\n\n      for(auto i = 0; i < m_ensemble_size; ++i){\n\tobs_perturbed.col(i) += obs;\n      }\n      auto K = kalman_gain_A(A);\n      A = ensemble_update(K, obs_perturbed / std::sqrt(m_ensemble_size-1), A);\n\n      m_ensemble_covariance = A * A.transpose();\n\n      /* get ensemble back */\n      A *= std::sqrt(m_ensemble_size - 1);\n      //add prior mean back and re-scale\n      m_ensemble_mean = std::sqrt(m_ensemble_size - 1) * (A.rowwise().mean() + m_ensemble_mean);\n      m_state = m_ensemble_mean;\n    }\n      \n      \n\n    \n  };\n  \n\n}//namespace fastmath\n#endif\n", "meta": {"hexsha": "161f3d6487728e59232c2ba0d37b1c701af3e477", "size": 8349, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "enkf/include/enkf.hpp", "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/enkf.hpp", "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/enkf.hpp", "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": 23.1916666667, "max_line_length": 97, "alphanum_fraction": 0.6166007905, "num_tokens": 2261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5193282003781251}}
{"text": "#include <pybindings.h>\n#include <container_pybindings.h>\n#include <maps/pointing.h>\n#include <G3Map.h>\n#include <G3Units.h>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <vector>\n#include <math.h>\n#include <iostream>\n#include <iomanip>\n\n#include <stdlib.h>\n#include <time.h>\n\nusing namespace boost::math;\n\nconst double PI = constants::pi<double>();\n\n#define ASIN asin\n#define ATAN2 atan2\n\n//#define CHECK_QUAT_INVERSE\n\n\n/*\n * Quaternions cannot represent parity flips.  Since celestial coordinates \n * and az-el coordinates by construction have a different parity, we can't use\n * the general alpha delta angle to x-y-z mapping for one of the coordiate\n * systems.\n *\n * For the Euclidean quaternion representation at the pole,\n * the z coordinate = -sin(elevation) = sin(declination)\n */\n\nstatic quat\nproject_on_plane(quat plane_normal, quat point)\n{\n\t// Projects the quaternion onto a plane with unit normal plane_normal\n\t//   The plane is defined as going through the origin \n\t//   with normal = plane_normal\n\n\tquat out_q(point);\n\t//ensure unit vec\n\tplane_normal /= sqrt(dot3(plane_normal,plane_normal));\n\tout_q -= plane_normal * dot3(plane_normal, point);\n\treturn out_q;\n}\n\nstatic bool\nsloppy_eq(quat a, quat b, double slop = 1e-6)\n{\n\t// Fuzzy quaternion equality comparison\n\treturn ((fabs(a.R_component_1() - (b.R_component_1())) < slop ) &&\n\t\t(fabs(a.R_component_2() - (b.R_component_2())) < slop ) &&\n\t\t(fabs(a.R_component_3() - (b.R_component_3())) < slop ) &&\n\t\t(fabs(a.R_component_4() - (b.R_component_4())) < slop ));\n}\n\nquat\nang_to_quat(double alpha, double delta)\n{\n\tdouble c_delta = cos(delta / G3Units::rad);\n\treturn quat(0, \n\t\t    c_delta * cos(alpha/G3Units::rad),\n\t\t    c_delta * sin(alpha/G3Units::rad),\n\t\t    sin(delta / G3Units::rad));\n}\n\nvoid\nquat_to_ang(quat q, double &alpha, double &delta)\n{\n\tdouble d = dot3(q,q);\n\tif (fabs(d - 1.0) > 1e-6){\n\t\tq /= sqrt(d);\n\t}\n\tdelta = ASIN(q.R_component_4()) * G3Units::rad;\n\talpha = ATAN2(q.R_component_3(), q.R_component_2())*G3Units::rad;\n}\n\nstatic boost::python::tuple\npy_quat_to_ang(quat q)\n{\n\tdouble a,d;\n\tquat_to_ang(q, a, d);\n\n\treturn boost::python::make_tuple(a, d);\n}\n\nquat\ncoord_quat_to_delta_hat(quat q)\n{\n\t// computes the delta hat vector for a given point on the unit sphere\n\t// specified by q\n\t// \n\t// (The delta hat is equal to -alpha hat)\n\n\tq /= sqrt(dot3(q,q));\n\tdouble st = sqrt(1 - (q.R_component_4()*q.R_component_4()));\n\tquat u= quat(0, \n\t\t     -1 * (q.R_component_2() * q.R_component_4())/st,\n\t\t     -1 * (q.R_component_3() * q.R_component_4())/st,\n\t\t     st);\n\tu /= sqrt(dot3(u,u));\n\treturn u;\n}\n\ndouble\nget_rot_ang(quat start_q, quat end_q, quat trans)\n{\n\t// delta is the physicist spherical coordinates delta\n\t// Computes delta hat for the start q applies trans to it\n\t// and then computes the angle between that and end_q's delta hat.\n\n\tquat t = trans * coord_quat_to_delta_hat(start_q) / trans;\n\tquat t_p = coord_quat_to_delta_hat(end_q);\n\t\n\tt /= sqrt(dot3(t,t));\n\tt_p /= sqrt(dot3(t_p,t_p));\n\tdouble d  = dot3(t,t_p);\n\tdouble sf = (dot3(end_q, cross3(t, t_p)) < 0) ? -1 : 1;\n\tif (d > 1) {\n\t\tg3_assert(d < 1.01);\n\t\treturn 0;\n\t} else if (d < -1) {\n\t\tg3_assert(d > -1.01);\n\t\treturn PI * G3Units::rad;\n\t} else {\n\t\treturn sf * acos(d) * G3Units::rad;\n\t}\n}\n\n\nquat\nget_transform_quat(double as_0, double ds_0, double ae_0, double de_0,\n    double as_1, double ds_1, double ae_1, double de_1)\n{\n\t/*\n\t * as = alpha start\n\t * ds = delta start\n\t * ae = alpha end\n\t * de = delta end\n\t *\n\t * The numeral postscripts are for which set of points.\n\t *\n\t * Computes a rotation that will take: (as_0,ds_0) to (ae_0, de_0) and\n\t * (as_1, ds_1) to (ae_1, de_1)\n\t *\n\t */\n\n\tquat asds_0 = ang_to_quat(as_0, ds_0);\n\tquat asds_1 = ang_to_quat(as_1, ds_1);\n\tquat aede_0 = ang_to_quat(ae_0, de_0);\n\tquat aede_1 = ang_to_quat(ae_1, de_1);\n\n\tquat tquat = cross3(asds_0, aede_0);\n\tdouble mag = sqrt(dot3(tquat, tquat));\n\tdouble ang = acos(dot3(asds_0, aede_0)); \n\ttquat *= sin(ang/2.0) / mag;\n\ttquat += quat(cos(ang/2.0),0,0,0);\n\n\t// trans_asds_1 and aede_1 should now be the same up to a rotation\n\t// around aede_0\n\tquat trans_asds_1 = tquat * asds_1 / tquat;\n\n\t// Project them on to a plane and find the angle between the two vectors\n\t// using (ae_0, de_0) as the normal since we are rotating around that\n\t// vector.\n\tquat p_asds1 = project_on_plane(aede_0, trans_asds_1);\t\n\tquat p_aede1 = project_on_plane(aede_0, aede_1);\n\tp_asds1 /= sqrt(dot3(p_asds1,p_asds1));\n\tp_aede1 /= sqrt(dot3(p_aede1,p_aede1));\n\n\tdouble rot_ang = acos(dot3(p_asds1, p_aede1));\n\tdouble sf = (dot3(aede_0, cross3(p_asds1, p_aede1)) < 0) ? -1 : 1;\n\trot_ang *= sf;\n\t\n\tdouble sin_rot_ang_ov_2 = sin(rot_ang/2.0);\n\tquat rot_quat = quat(cos(rot_ang/2.0),\n\t\t\t     sin_rot_ang_ov_2 * aede_0.R_component_2(), \n\t\t\t     sin_rot_ang_ov_2 * aede_0.R_component_3(), \n\t\t\t     sin_rot_ang_ov_2 * aede_0.R_component_4());\n\tquat final_trans = rot_quat * tquat;\n\n\treturn final_trans;\n}\n\nstatic std::vector<double>\ntest_trans(double az_0, double el_0, double ra_0, double dec_0,\n    double az_1, double el_1, double ra_1, double dec_1,\n    double az_t, double el_t)\n{\n\t// computes the transform from the first 4 variables\n\t// returns that transform to the last 2 variables\n\t\n\tdouble ra_t, dec_t;\n\tquat q = get_transform_quat(az_0, -el_0,\n\t\t\t\t    ra_0, dec_0,\n\t\t\t\t    az_1, -el_1,\n\t\t\t\t    ra_1, dec_1);\n\tquat azel = ang_to_quat(az_t, -el_t);\n\tquat rad = q * azel / q;\n\tquat_to_ang(rad, ra_t, dec_t);\n\tstd::vector<double> r(2,0);\n\tr[0] = ra_t;\n\tr[1] = dec_t;\n\treturn r;\n}\n\nstatic std::vector<double>\ntest_gal_trans(double az_0, double el_0, double ra_0, double dec_0,\n    double az_1, double el_1, double ra_1, double dec_1,\n    double az_t, double el_t)\n{\n\tdouble l_t, b_t;\n\tquat q = get_fk5_j2000_to_gal_quat() *get_transform_quat(az_0, -el_0,\n\t\t\t\t\t\t\t\t ra_0, dec_0,\n\t\t\t\t\t\t\t\t az_1, -el_1,\n\t\t\t\t\t\t\t\t ra_1, dec_1);\n\tquat azel = ang_to_quat(az_t, -el_t);\n\tquat rad = q * azel / q;\n\tquat_to_ang(rad, l_t, b_t);\n\tstd::vector<double> r(2,0);\n\tr[0] = l_t;\n\tr[1] = b_t;\n\treturn r;\n}\n\nstatic double\ntest_gal_trans_rot(double ra, double dec)\n{\n\tquat start = ang_to_quat(ra,dec);\n\tquat trans = get_fk5_j2000_to_gal_quat();\n\n\treturn get_rot_ang(start, trans*start/trans, trans);\n}\n\n\nquat\noffsets_to_quat(double x_offset, double y_offset)\n{\n\t// Rotates the point (1,0,0) by the rotation matrix for the y_offset\n\t// and then the rotation matrix for the x_offset\n\t// quat t = (quat(cos(x_offset/(2.0*G3Units::rad)),0,0,sin(x_offset/(2.0*G3Units::rad))) *\n\t// \t  quat(cos(y_offset/(2.0*G3Units::rad)),0,sin(y_offset/(2.0*G3Units::rad)),0));\n\t// return t*quat(0,1.0,0,0)/t;\n\t// The above is exactly equal to:\n\treturn ang_to_quat(x_offset, -y_offset);\n}\n\nquat\nget_origin_rotator(double alpha, double delta)\n{\n\t// Rotates the point (1,0,0) to the point specified by alpha and\n\t// delta via a rotation about the y axis and then the z axis\n        return (quat(cos(alpha/2.0), 0, 0, sin(alpha/2.0)) *\n                quat(cos(delta/2.0), 0, -sin(delta/2.0), 0));\n}\n\nstatic void\nprint_fk5_j2000_to_gal_quat()\n{\n\t// uhh, so, this code was a super lazy way to get the quaternion\n\t// that takes fk5 j2000 to galactic j2000\n\tstd::cout << std::setprecision(10) << std::endl;\n\tstd::cout << get_transform_quat(\n\t\t0,0, 1.6814025470759737, -1.050488399695429,\n\t\t0,-0.7853981633974483, 5.750520098164818, -1.2109809382060603)\n\t          << std::endl;\n}\n\nquat\nget_fk5_j2000_to_gal_quat()\n{\n\t// returns the quaternion that rotates fk5j2000 to galactic J2000\n\t// coordinates\n\treturn quat(0.4889475076,-0.483210684,0.1962537583,0.699229742);\n}\n\nstatic void\ncreate_det_az_el_trans(const G3Timestream &az, const G3Timestream &el,\n    G3VectorQuat &trans_quats) // XXX: switch to G3TimestreamQuat?\n{\n\t// Creates the transform that takes (1,0,0) to az, -el \n\t// for why it's -el see the comment at the top of this document\n\n\tg3_assert(az.size() == el.size());\n\ttrans_quats = G3VectorQuat(az.size(), quat(1,0,0,0));\n\tfor (size_t i = 0; i < az.size(); i++)\n\t\ttrans_quats[i] = get_origin_rotator(az[i], -el[i]);\n}\n\nstatic void\ncreate_lazy_det_ra_dec_trans(const G3Timestream &ra, const G3Timestream &dec, \n    G3VectorQuat &trans_quats)\n{\n\t// Creates the transform that takes (1,0,0) to ra,dec\n\tg3_assert(ra.size() == dec.size());\n\ttrans_quats = G3VectorQuat(ra.size(), quat(1,0,0,0));\n\tfor (size_t i = 0; i < ra.size(); i++)\n\t\ttrans_quats[i] = get_origin_rotator(ra[i], dec[i]);\n}\n\nstatic void\ncreate_det_ra_dec_trans(const G3Timestream &az_0, const G3Timestream &el_0, \n     const G3Timestream &ra_0, const G3Timestream &dec_0, \n     const G3Timestream &az_1, const G3Timestream &el_1, \n     const G3Timestream &ra_1, const G3Timestream &dec_1, \n     G3VectorQuat & trans_quats)\n{\n\t// Computes the transform that takes (1,0,0) to the point (ra_0, dec_0)\n\t// and properly handles rotation about the (ra_0, dec_0) point with the\n\t// inclusion of the second set of points.\n\t//\n\t// Stores the output in trans_quats.\n\n\tg3_assert(az_0.size() == el_0.size());\n\tg3_assert(az_0.size() == el_1.size());\n\tg3_assert(az_0.size() == az_1.size());\n\tg3_assert(az_0.size() == dec_0.size());\n\tg3_assert(az_0.size() == dec_1.size());\n\tg3_assert(az_0.size() == ra_0.size());\n\tg3_assert(az_0.size() == ra_1.size());\n\ttrans_quats = G3VectorQuat(ra_0.size(), quat(1,0,0,0));\t\n\n\tfor (size_t i = 0; i < ra_0.size(); i++) {\n\t\ttrans_quats[i] = get_transform_quat(\n\t\t    az_0[i], -el_0[i],\n\t\t    ra_0[i], dec_0[i],\n\t\t    az_1[i], -el_1[i],\n\t\t    ra_1[i], dec_1[i]\n\t\t    )*get_origin_rotator(az_0[i], -el_0[i]);\n\t}\n}\n\nstatic void\nconvert_ra_dec_trans_to_gal(const G3VectorQuat &radec_trans,\n    G3VectorQuat &gal_trans)\n{\n\t// Converts a rotation from (1,0,0) to fk5 j2000 into a rotation that\n\t// takes (1,0,0) to our galactic (l,b)\n\n\tgal_trans = G3VectorQuat(radec_trans.size(), quat(1,0,0,0));\n\tquat gt = get_fk5_j2000_to_gal_quat();\n\tfor (size_t i = 0; i < radec_trans.size(); i++)\n\t\tgal_trans[i] = gt*radec_trans[i];\n}\n\nvoid\nget_detector_pointing(double x_offset, double y_offset,\n    const G3VectorQuat &trans_quat, MapCoordReference coord_sys,\n    std::vector<double> &alpha, std::vector<double> &delta)\n{\n\t// For a detector x/y offset and a boresight position specified by\n\t// trans_quat with a given coordinate system coord_sys,\n\t// computes the individual detector pointing coordinates.\n\n\tquat det_pos = offsets_to_quat(x_offset, y_offset);\n\tdelta.resize(trans_quat.size());\n\talpha.resize(trans_quat.size());\n\n\tif ((!std::isfinite(x_offset)) || (!std::isfinite(y_offset))){\n\t\tlog_debug(\"Found non-finite (inf or nan) offsets\");\n\t\tfor (size_t i=0; i<alpha.size(); i++){\n\t\t\talpha[i] = nan(\"\");\n\t\t\tdelta[i] = nan(\"\");\n\t\t}\n\t\treturn;\n\t}\n\n\tfor (size_t i = 0; i < alpha.size(); i++) {\n\t\t//using boost inverse\n\t\t//quat q=trans_quat[i]*det_pos/trans_quat[i];\n\t\t\n\t\t//uses an inverse that assumes we are on the unit sphere\n\t\tconst quat & t = trans_quat[i];\n\t\tquat q=trans_quat[i]*det_pos * quat( t.R_component_1(),\n\t\t    -t.R_component_2(), -t.R_component_3(), -t.R_component_4());\n\n\t\tquat_to_ang(q, alpha[i], delta[i]);\n\n\t\t#ifdef CHECK_QUAT_INVERSE\n\t\tdouble a,d;\n\t\tquat u = trans_quat[i]*det_pos/trans_quat[i];\t\t\n\t\tquat_to_ang(u, a, d);\n\t\tif( fabs(a - alpha[i]) > 1e-5 || fabs(d - delta[i]) > 1e-5){\n\t\t\tlog_fatal(\"Failed trans %lf %lf %lf %lf\\n\", a, alpha[i], d, delta[i]);\n\t\t}\n\t\t#endif\n\t}\n\tif (coord_sys == Local) {\n\t\tfor (size_t i = 0; i < delta.size(); i++)\n\t\t\tdelta[i] *= -1;\n\t}\n\n}\n\nvoid\nget_detector_rotation(double x_offset, double y_offset,\n    const G3VectorQuat &trans_quat, std::vector<double> &rot)\n{\n\t// Computes the polarization angle rotation that occurs under the \n\t// transform trans_quat and stores it in rot.\t   \n\t\n\trot = std::vector<double>(trans_quat.size(), 0);\n\tquat det_pos = offsets_to_quat(x_offset, y_offset);\n\tfor (size_t i = 0; i < rot.size(); i++) {\n\t\tquat q = trans_quat[i]*det_pos/trans_quat[i];\n\t\trot[i] = get_rot_ang(det_pos, q, trans_quat[i]);\n\t}\n}\n\nstatic std::vector<double>\nconvert_celestial_offsets_to_local_offsets(G3VectorQuat trans_vec,\n    double x_offset_celest, double y_offset_celest)\n{\n\tdouble alpha, delta;\n \tdouble x_offset_local, y_offset_local;\n\n\t// written at a time when we only have python bindings for the vector quat\n\tg3_assert( trans_vec.size() == 1); \n\tquat trans = trans_vec[0];\n\n\t// First we compute the celestial position of boresight.\n\tquat bs_cel = trans * quat(0,1,0,0) / trans;\n\tquat_to_ang(bs_cel, alpha, delta); //alpha, delta are celestial boresight\n\t\n\t// Next, with our celestial position offsets we compute the position\n\t// of our detector in celestial coordinates with the celestial offsets.\n\t// because the offset is in celestial coordinates we do that with the transform\n\t// that takes (1,0,0) in celestial coordinates to the boresight  while ignoring\n\t//boresight rotation\n\n\tquat celestial_trans = get_origin_rotator(alpha, delta);\n\n\tquat det_cel = celestial_trans * offsets_to_quat(x_offset_celest, y_offset_celest) / \n\t    celestial_trans;\n\n\t// We then transform those positions to local coordinates using the full transform\n\tquat inv_trans = boost::math::conj(trans);\n\tquat det_local = inv_trans * det_cel / inv_trans;\n\n\t#ifdef CHECK_QUAT_INVERSE\n\t//just to check I'm not insane can be dropped in the future\n\tg3_assert(sloppy_eq(inv_trans * bs_cel / inv_trans, quat(0,1,0,0)));\n\t#endif\n\t\n\t// we read off the position of the detector.\n\tquat_to_ang(det_local, x_offset_local, y_offset_local);\n\n\t// C++11 is magic.\n\treturn {x_offset_local, -y_offset_local};\n}\n\nstatic double\nangle_d2(double ra_0, double dec_0, double ra_1, double dec_1)\n{\n\tdouble delta_ra_abs = fabs(ra_0 - ra_1);\n\tdouble delta_dec = dec_0 - dec_1;\n\tif (delta_ra_abs > PI){\n\t\tdelta_ra_abs = 2 * PI - delta_ra_abs;\n\t}\n\tdelta_ra_abs /= cos(dec_0);\n\treturn delta_ra_abs*delta_ra_abs + delta_dec*delta_dec;\n\n}\n\nstatic G3VectorQuat\nget_closest_transform(double ra, double dec,\n    const G3VectorDouble &ras, const G3VectorDouble &decs,\n    const G3VectorQuat &trans)\n{\n\t// Returns quaternion transformation nearest the requested ra/dec\n\n\tdouble dist = angle_d2(ras[0]/G3Units::rad, decs[0]/G3Units::rad,\n\t\t\t       ra/G3Units::rad, dec/G3Units::rad);\n\tsize_t ind = 0;\n\tfor (size_t i = 0; i < ras.size(); i++) {\n\t\tdouble td = angle_d2(ras[i]/G3Units::rad, decs[i]/G3Units::rad,\n\t\t\t\t     ra/G3Units::rad, dec/G3Units::rad);\n\t\tif (td < dist) {\n\t\t\tdist = td;\n\t\t\tind = i;\n\t\t}\n\t}\n\tG3VectorQuat v;\n\tv.push_back(trans[ind]);\n\treturn v;\n}\n\n\nPYBINDINGS(\"maps\")\n{\n\tusing namespace boost::python;\n\n\tdef(\"test_trans_\", test_trans);\n\tdef(\"test_gal_trans_\", test_gal_trans);\n\tdef(\"test_gal_trans_rot_\", test_gal_trans_rot);\n\tdef(\"print_fk5_j2000_to_gal_quat_\", print_fk5_j2000_to_gal_quat);\n\tdef(\"c_quat_to_ang_\", py_quat_to_ang);\n\tdef(\"c_ang_to_quat_\", ang_to_quat);\n\n        def(\"get_origin_rotator\", get_origin_rotator, (arg(\"alpha\"), arg(\"delta\")),\n            \"Compute the transformation quaternion that would rotate the \"\n            \"vector (1, 0, 0) to point in the given direction.\");\n        def(\"offsets_to_quat\", offsets_to_quat, (arg(\"x\"), arg(\"y\")),\n            \"Returns the vector quaternion (0,1,0,0) rotated by the given \"\n            \"x and y offsets.  Equivalent to ``t * quat(0,1,0,0) / t``, where \"\n            \"``t = get_origin_rotator(x, -y)``\");\n\tdef(\"create_det_az_el_trans\", create_det_az_el_trans,\n\t    \"Construct a quaternion vector from timestreams of detector \"\n\t    \"azimuth and elevation. Equivalent to ``R_z(az) * R_y(-el)``.\");\n\tdef(\"create_lazy_det_ra_dec_trans\", create_lazy_det_ra_dec_trans,\n\t    \"Construct a quaternion vector from timestreams of detector \"\n\t    \"RA and declination.  Equivalent to ``R_z(ra) * R_y(dec)``\");\n\tdef(\"create_det_ra_dec_trans\", create_det_ra_dec_trans,\n\t    \"Construct a quaternion vector from timestreams of detector \"\n\t    \"coordinates.  Computes the transformation from local \"\n\t    \"(az_0, el_0) coordinates to celestial (ra_0, dec_0), \"\n\t    \"accounting for rotation about the boresight by including \"\n\t    \"the second set of points.\");\n\tdef(\"convert_ra_dec_trans_to_gal\", convert_ra_dec_trans_to_gal,\n\t    \"Rotate a vector of quaternions from Equatorial to Galactic \"\n\t    \"coordinates\");\n}\n", "meta": {"hexsha": "78b1b68361e6b8cd89f3406727e9d558f660c89b", "size": 16042, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "maps/src/pointing.cxx", "max_stars_repo_name": "tskisner/spt3g_software", "max_stars_repo_head_hexsha": "bf4ba191506842477490c6d2300caeafee5fe93d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-05-03T15:37:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-29T17:14:48.000Z", "max_issues_repo_path": "maps/src/pointing.cxx", "max_issues_repo_name": "tskisner/spt3g_software", "max_issues_repo_head_hexsha": "bf4ba191506842477490c6d2300caeafee5fe93d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 36.0, "max_issues_repo_issues_event_min_datetime": "2017-09-25T20:05:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T18:57:57.000Z", "max_forks_repo_path": "maps/src/pointing.cxx", "max_forks_repo_name": "tskisner/spt3g_software", "max_forks_repo_head_hexsha": "bf4ba191506842477490c6d2300caeafee5fe93d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-09-25T18:54:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-17T19:55:57.000Z", "avg_line_length": 30.440227704, "max_line_length": 91, "alphanum_fraction": 0.6874454557, "num_tokens": 5164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.519328200378125}}
{"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/// This file contains some auxiliary code used for computing 1D\n/// Green's functions and related quantities using piecewise cubic\n/// interpolation.\n\n#include <cmath>\n#include <boost/math/special_functions/pow.hpp>\n\nnamespace alma {\nnamespace aux_cubic {\n/// Auxiliary function used when computing rational integrals.\ninline double I1(double x0) {\n    return std::log(std::abs((1. - x0) / x0));\n}\n\n/// Auxiliary function used when computing rational integrals.\ninline double I2(double dd, double ee) {\n    double den{std::sqrt(4. * ee - boost::math::pow<2>(dd))};\n\n    return -2. * (std::atan(dd / den) - std::atan((dd + 2. * ee) / den)) / den;\n}\n\n/// Auxiliary function used when computing rational integrals.\ninline double I3(double dd, double ee) {\n    double den = std::sqrt(4. * ee - boost::math::pow<2>(dd));\n\n    return (2. * dd * (std::atan(dd / den) - std::atan((dd + 2. * ee) / den)) +\n            den * std::log1p(dd + ee)) /\n           (2 * ee * den);\n}\n\n/// Objects of this class perform rational integrals of the kind\n/// found when approximating bands by piecewise cubic polynomials\n/// to obtain Green's functions in 1D.\nclass Cubic_segment {\nprivate:\n    /// Coefficients of the cubic polynomial in the denominator.\n    const std::array<double, 4> coeff;\n\npublic:\n    /// Constructor.\n    ///\n    /// @param[in] a - value of the energy at the left\n    /// @param[in] b - value of the energy at the right\n    /// @param[in] ap - derivative of the energy at the left\n    /// @param[in] bp - derivative of the energy at the right\n    Cubic_segment(double a, double b, double ap, double bp)\n        : coeff({{-(2. * a + ap - 2. * b + bp),\n                  -(-3. * a - 2. * ap + 3. * b - bp),\n                  -ap,\n                  -a}}) {\n    }\n    /// Obtain the values of the four integrals needed for the\n    /// calculation of the Green's function at a particular\n    /// energy.\n    ///\n    /// @param[in] energ - value of the energy\n    /// @return a vector with the four integrals in this order:\n    /// ReG, ReGx, ImG, ImGx\n    std::array<double, 4> calc_integrals(double ener) const {\n        // Coefficients of the full polynomial in the\n        // denominator.\n        std::array<double, 4> p(this->coeff);\n        p[3] += ener;\n        // Get the number of roots based on the value of the\n        // discriminant for the third-order equation.\n        double a{p[1] / p[0]};\n        double b{p[2] / p[0]};\n        double c{p[3] / p[0]};\n        double a2{boost::math::pow<2>(a)};\n        double q{(a2 - 3. * b) / 9.};\n        double r{(a * (2. * a2 - 9. * b) + 27. * c) / 54.};\n        double r2{boost::math::pow<2>(r)};\n        double q3{boost::math::pow<3>(q)};\n        std::array<double, 4> nruter({{0., 0., 0., 0.}});\n\n        // And use the formulae specific to each case.\n        if (r2 < q3) {\n            // Three real roots.\n            double th{std::acos(r / std::sqrt(q3))};\n            double q12{std::sqrt(q)};\n            double x0{-2. * q12 * std::cos(th / 3.) - a / 3.};\n            double x1{-2. * q12 * std::cos((th + 2. * constants::pi) / 3.) -\n                      a / 3.};\n            double x2{-2. * q12 * std::cos((th - 2. * constants::pi) / 3.) -\n                      a / 3.};\n            double pref{-x0 * x1 * x2 / p[3]};\n            double aa{pref / ((x0 - x1) * (x0 - x2))};\n            double bb{pref / ((x1 - x0) * (x1 - x2))};\n            double cc{pref / ((x2 - x0) * (x2 - x1))};\n            nruter[0] = aa * I1(x0) + bb * I1(x1) + cc * I1(x2);\n            double aax{x0 * aa};\n            double bbx{x1 * bb};\n            double ccx{x2 * cc};\n            nruter[1] = aax * I1(x0) + bbx * I1(x1) + ccx * I1(x2);\n\n            if ((0. < x0) && (x0 < 1.)) {\n                nruter[2] += std::abs(aa);\n                nruter[3] += std::abs(aax);\n            }\n\n            if ((0. < x1) && (x1 < 1.)) {\n                nruter[2] += std::abs(bb);\n                nruter[3] += std::abs(bbx);\n            }\n\n            if ((0. < x2) && (x2 < 1.)) {\n                nruter[2] += std::abs(cc);\n                nruter[3] += std::abs(ccx);\n            }\n            nruter[2] *= constants::pi;\n            nruter[3] *= constants::pi;\n        }\n        else {\n            // Only one real root.\n            double A{-signum(r) * std::cbrt(std::abs(r) + std::sqrt(r2 - q3))};\n            double B{(A == 0. ? 0. : q / A)};\n            double x0{A + B - a / 3.};\n            double dd{A + B + 2. * a / 3.};\n            double ee{boost::math::pow<2>(dd / 2.) +\n                      .75 * boost::math::pow<2>(A - B)};\n            double pref{-x0 * ee / p[3]};\n            double aa{pref / (x0 * (x0 + dd) + ee)};\n            double bb{-(x0 + dd) * aa};\n            double cc{-aa};\n            double aax{x0 * aa};\n            double bbx{ee * aa};\n            double ccx{-aax};\n            nruter[0] = aa * I1(x0) + (bb / ee) * I2(dd / ee, 1. / ee) +\n                        (cc / ee) * I3(dd / ee, 1. / ee);\n            nruter[1] = aax * I1(x0) + (bbx / ee) * I2(dd / ee, 1. / ee) +\n                        (ccx / ee) * I3(dd / ee, 1. / ee);\n\n            if ((0. < x0) && (x0 < 1.)) {\n                nruter[2] = constants::pi * std::abs(aa);\n                nruter[3] = constants::pi * std::abs(aax);\n            }\n        }\n        return nruter;\n    }\n};\n} // namespace aux_cubic\n} // namespace alma\n", "meta": {"hexsha": "d3ef20b9adca79e7ee4533af58691b76036e81c8", "size": 5985, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/aux_cubic.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/aux_cubic.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/aux_cubic.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": 37.40625, "max_line_length": 79, "alphanum_fraction": 0.5037593985, "num_tokens": 1814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629215, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5193281919007018}}
{"text": "/**\n * @file SparseCholesky.hpp\n * @license License BSD-3-Clause\n * @date 2019-10-06\n * @author Timothy A. Davis\n * @copyright LDL Copyright (c) 2005-2012 by Timothy A. Davis. http://www.suitesparse.com\n *\n * LDL License:\n *\n *    Your use or distribution of LDL or any modified version of\n *    LDL implies that you agree to this License.\n *\n *    This library is free software; you can redistribute it and/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License as published by the Free Software Foundation; either\n *    version 2.1 of the License, or (at your option) any later version.\n *\n *    This library 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 GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301\n *    USA\n *\n *    Permission is hereby granted to use or copy this program under the\n *    terms of the GNU LGPL, provided that the Copyright, this License,\n *    and the Availability of the original version is retained on all copies.\n *    User documentation of any code that uses this code or any modified\n *    version of this code must cite the Copyright, this License, the\n *    Availability note, and \"Used by permission.\" Permission to modify\n *    the code and to distribute modified code is granted, provided the\n *    Copyright, this License, and the Availability note are retained,\n *    and a notice that the code was modified is included.\n *\n * Availability:\n *\n *    http://www.suitesparse.com\n *\n * Stripped down by Alexander Domahidi, 2012.\n * Modified to c++ code by New York University and Max Planck Gesellschaft, 2017 \n * \n */\n\n#pragma once\n\n#include <memory>\n#include <Eigen/Sparse>\n#include <solver/interface/SolverSetting.hpp>\n\nnamespace linalg {\n\n  /**\n   * Class to perform an LDL factorization of a matrix\n   */\n  class SparseCholesky\n  {\n    public:\n\t  SparseCholesky(){}\n\t  ~SparseCholesky(){}\n\n\t  void analyzePattern(const Eigen::SparseMatrix<double>& mat, const solver::SolverSetting& stgs);\n\t  int  factorize(const Eigen::SparseMatrix<double>& mat, const Eigen::Ref<const Eigen::VectorXd>& sign);\n\t  void solve(const Eigen::Ref<const Eigen::VectorXd>& b, double* x);\n\t  Eigen::VectorXd& solve(const Eigen::VectorXd& b);\n\n    private:\n      inline const solver::SolverSetting& getSetting() const { return *setting_; }\n\n\t  int n_;\n\t  double eps_, delta_;\n\t  Eigen::VectorXd D_, Y_, X_;\n\t  Eigen::SparseMatrix<double> L_;\n\t  Eigen::VectorXi Parent_, Pattern_, Flag_, Lnnz_;\n\t  std::shared_ptr<const solver::SolverSetting> setting_;\n\n  };\n\n}\n", "meta": {"hexsha": "0bd143c31ee10aab7c4ffcfdef4ab54e5e6f6540", "size": 2878, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "solver/include/solver/optimizer/SparseCholesky.hpp", "max_stars_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_stars_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "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/include/solver/optimizer/SparseCholesky.hpp", "max_issues_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_issues_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "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/include/solver/optimizer/SparseCholesky.hpp", "max_forks_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_forks_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "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": 35.0975609756, "max_line_length": 105, "alphanum_fraction": 0.7084781098, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5193281833216579}}
{"text": "/*************************************************************************\n\t> File Name: lqr_steer_control.cpp\n\t> Author: TAI Lei\n\t> Mail: ltai@ust.hk\n\t> Created Time: Wed Apr 17 11:48:46 2019\n ************************************************************************/\n\n#include <iostream>\n#include <limits>\n#include <vector>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <sys/time.h>\n#include <Eigen/Eigen>\n#include \"cubic_spline.h\"\n#include \"motion_model.h\"\n#include \"cpprobotics_types.h\"\n\n#define DT 0.1\n#define L 0.5\n#define KP 1.0\n#define MAX_STEER 45.0/180*M_PI\n\nusing namespace cpprobotics;\nusing Matrix5f = Eigen::Matrix<float, 5, 5>;\nusing Matrix52f = Eigen::Matrix<float, 5, 2>;\nusing Matrix25f = Eigen::Matrix<float, 2, 5>;\nusing RowVector5f = Eigen::Matrix<float, 1, 5>;\nusing Vector5f = Eigen::Matrix<float, 5, 1>;\n\ncv::Point2i cv_offset(\n    float x, float y, int image_width=2000, int image_height=2000){\n  cv::Point2i output;\n  output.x = int(x * 100) + 300;\n  output.y = image_height - int(y * 100) - image_height/2;\n  return output;\n};\n\nVec_f calc_speed_profile(Vec_f rx, Vec_f ry, Vec_f ryaw, float target_speed){\n    Vec_f speed_profile(ryaw.size(), target_speed);\n\n  float direction = 1.0;\n  for(unsigned int i=0; i < ryaw.size()-1; i++){\n    float dyaw = std::abs(ryaw[i+1] - ryaw[i]);\n    float switch_point = (M_PI/4.0< dyaw) && (dyaw<M_PI/2.0);\n\n    if (switch_point) direction = direction * -1;\n    if (direction != 1.0) speed_profile[i]= target_speed * -1;\n    else speed_profile[i]= target_speed;\n\n    if (switch_point) speed_profile[i] = 0.0;\n  }\n\n  for(int k=0; k< 40; k++){\n    *(speed_profile.end()-k) = target_speed / (50 - k);\n    if (*(speed_profile.end()-k) <= 1.0 / 3.6){\n      *(speed_profile.end()-k) = 1.0 / 3.6;\n    }\n  }\n  return speed_profile;\n};\n\n\nfloat calc_nearest_index(State state, Vec_f cx, Vec_f cy, Vec_f cyaw, int &ind){\n  float mind = std::numeric_limits<float>::max();\n  for(unsigned int i=0; i<cx.size(); i++){\n    float idx = cx[i] - state.x;\n    float idy = cy[i] - state.y;\n    float d_e = idx*idx + idy*idy;\n\n    if (d_e<mind){\n      mind = d_e;\n      ind = i;\n    }\n  }\n  float dxl = cx[ind] - state.x;\n  float dyl = cy[ind] - state.y;\n  float angle = YAW_P2P(cyaw[ind] - std::atan2(dyl, dxl));\n  if (angle < 0) mind = mind * -1;\n\n  return mind;\n};\n\nMatrix5f solve_DARE(Matrix5f A, Matrix52f B, Matrix5f Q, Eigen::Matrix2f R){\n  Matrix5f X = Q;\n  int maxiter = 150;\n  float eps = 0.01;\n\n  for(int i=0; i<maxiter; i++){\n    Matrix5f Xn = A.transpose()*X*A-A.transpose()*X*B*(R+B.transpose()*X*B).inverse() * B.transpose()*X*A+Q;\n    Matrix5f error = Xn - X;\n    if (error.cwiseAbs().maxCoeff()<eps){\n      return Xn;\n    }\n    X = Xn;\n  }\n\n  return X;\n};\n\nMatrix25f dlqr(Matrix5f A, Matrix52f B, Matrix5f Q, Eigen::Matrix2f R){\n  Matrix5f X = solve_DARE(A, B ,Q, R);\n  Matrix25f K = (B.transpose()*X*B + R).inverse() * (B.transpose()*X*A);\n  return K;\n};\n\nVec_f lqr_steering_control(State state, Vec_f cx, Vec_f cy, Vec_f cyaw, Vec_f ck, Vec_f sp, float& pe, float& pth_e){\n  int ind = 0;\n  float e = calc_nearest_index(state, cx, cy, cyaw, ind);\n\n  float k = ck[ind];\n  float th_e = YAW_P2P(state.yaw - cyaw[ind]);\n  float tv = sp[ind];\n\n  Matrix5f A = Matrix5f::Zero();\n  A(0, 0) = 1.0;\n  A(0 ,1) = DT;\n  A(1 ,2) = state.v;\n  A(2 ,2) = 1.0;\n  A(2 ,3) = DT;\n  A(4 ,4) = 1.0;\n\n  Matrix52f B = Matrix52f::Zero();\n  B(3, 0) = state.v/L;\n  B(4, 1) = DT;\n\n  Matrix5f Q = Matrix5f::Identity();\n  Eigen::Matrix2f R = Eigen::Matrix2f::Identity();\n\n  // gain of lqr\n  Matrix25f K = dlqr(A, B, Q, R);\n\n  Vector5f x = Vector5f::Zero();\n  x(0) = e;\n  x(1) = (e-pe)/DT;\n  x(2) = th_e;\n  x(3) = (th_e-pth_e)/DT;\n  x(4) = state.v - tv;\n\n  Eigen::Vector2f ustar = -K * x;\n\n  float ff = std::atan2((L*k), (double)1.0);\n  float fb = YAW_P2P(ustar(0));\n  float delta = ff+fb;\n  float ai = ustar(1);\n\n  pe = e;\n  pth_e = th_e;\n  return {ai, delta};\n};\n\n\nvoid update (State& state, float a, float delta){\n\n  if (delta >= MAX_STEER) delta = MAX_STEER;\n  if (delta <= - MAX_STEER) delta = - MAX_STEER;\n\n  state.x = state.x + state.v * std::cos(state.yaw) * DT;\n  state.y = state.y + state.v * std::sin(state.yaw) * DT;\n  state.yaw = state.yaw + state.v / L * std::tan(delta) * DT;\n  state.v = state.v + a * DT;\n\n};\n\nvoid closed_loop_prediction(Vec_f cx, Vec_f cy, Vec_f cyaw, Vec_f ck, Vec_f speed_profile, Poi_f goal){\n  float T = 500.0;\n  float goal_dis = 0.3;\n  float stop_speed = 0.05;\n\n  State state(-0.0, -0.0, 0.0, 0.0);\n\n  float time_ = 0.0;\n  Vec_f x;\n  x.push_back(state.x);\n  Vec_f y;\n  y.push_back(state.y);\n  Vec_f yaw;\n  yaw.push_back(state.yaw);\n  Vec_f v;\n  v.push_back(state.v);\n  Vec_f t;\n  t.push_back(0.0);\n\n  float e = 0;\n  float e_th = 0;\n\n  cv::namedWindow(\"lqr_full\", cv::WINDOW_NORMAL);\n  int count = 0;\n  Vec_f x_h;\n  Vec_f y_h;\n\n\n  while (T >= time_){\n    Vec_f control = lqr_steering_control(state, cx, cy, cyaw, ck, speed_profile, e, e_th);\n    // float ai = KP * (speed_profile[ind]-state.v);\n    update(state, control[0], control[1]);\n    // if (std::abs(state.v) <= stop_speed) ind += 1;\n\n    float dx = state.x - goal[0];\n    float dy = state.y - goal[1];\n    if (std::sqrt(dx*dx + dy*dy) <= goal_dis) {\n      std::cout<<(\"Goal\")<<std::endl;\n      break;\n    }\n\n    x_h.push_back(state.x);\n    y_h.push_back(state.y);\n\n    // visualization\n    cv::Mat bg(2000, 3000, CV_8UC3, cv::Scalar(255, 255, 255));\n    for(unsigned int i=1; i<cx.size(); i++){\n      cv::line(\n        bg,\n        cv_offset(cx[i-1], cy[i-1], bg.cols, bg.rows),\n        cv_offset(cx[i], cy[i], bg.cols, bg.rows),\n        cv::Scalar(0, 0, 0),\n        10);\n    }\n\n    for(unsigned int j=0; j< x_h.size(); j++){\n      cv::circle(\n        bg,\n        cv_offset(x_h[j], y_h[j], bg.cols, bg.rows),\n        10, cv::Scalar(0, 0, 255), -1);\n    }\n\n    cv::putText(\n      bg,\n      \"Speed: \" + std::to_string(state.v*3.6).substr(0, 4) + \"km/h\",\n      cv::Point2i((int)bg.cols*0.5, (int)bg.rows*0.1),\n      cv::FONT_HERSHEY_SIMPLEX,\n      3,\n      cv::Scalar(0, 0, 0),\n      10);\n\n    // save image in build/bin/pngs\n    struct timeval tp;\n    gettimeofday(&tp, NULL);\n    long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;\n    std::string int_count = std::to_string(ms);\n    cv::imwrite(\"./pngs/\"+int_count+\".png\", bg);\n    // cv::imshow(\"lqr_full\", bg);\n    // cv::waitKey(5);\n  }\n};\n\nint main(){\n  Vec_f wx({0.0, 6.0,  12.5, 10.0, 17.5, 20.0, 25.0});\n  Vec_f wy({0.0, -3.0, -5.0,  6.5, 3.0, 0.0, 0.0});\n\n  Spline2D csp_obj(wx, wy);\n  Vec_f r_x;\n  Vec_f r_y;\n  Vec_f ryaw;\n  Vec_f rcurvature;\n  Vec_f rs;\n  for(float i=0; i<csp_obj.s.back(); i+=0.1){\n    std::array<float, 2> point_ = csp_obj.calc_postion(i);\n    r_x.push_back(point_[0]);\n    r_y.push_back(point_[1]);\n    ryaw.push_back(csp_obj.calc_yaw(i));\n    rcurvature.push_back(csp_obj.calc_curvature(i));\n    rs.push_back(i);\n  }\n  float target_speed = 10.0 / 3.6;\n  Vec_f speed_profile = calc_speed_profile(r_x, r_y, ryaw, target_speed);\n  closed_loop_prediction(r_x, r_y, ryaw, rcurvature, speed_profile, {{wx.back(), wy.back()}});\n}\n", "meta": {"hexsha": "70ec1211043a776f70b86992ad78b94b87d3ce37", "size": 7091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lqr_speed_steer_control.cpp", "max_stars_repo_name": "surfertas/CppRobotics", "max_stars_repo_head_hexsha": "e2cf767fe728458b2bc8938a73cfae5d6cad643d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-04T06:24:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-04T06:24:21.000Z", "max_issues_repo_path": "src/lqr_speed_steer_control.cpp", "max_issues_repo_name": "OctoberWu/CppRobotics", "max_issues_repo_head_hexsha": "e2cf767fe728458b2bc8938a73cfae5d6cad643d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lqr_speed_steer_control.cpp", "max_forks_repo_name": "OctoberWu/CppRobotics", "max_forks_repo_head_hexsha": "e2cf767fe728458b2bc8938a73cfae5d6cad643d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-01T09:32:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-07T02:33:47.000Z", "avg_line_length": 26.262962963, "max_line_length": 117, "alphanum_fraction": 0.5872232407, "num_tokens": 2524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.51929742460016}}
{"text": "#ifndef EULER1D_HPP_INCLUDED\n#define EULER1D_HPP_INCLUDED\n\n// C includes\n#include <cmath>\n#include <cstdio>\n\n// C++ includes\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <algorithm>\n#include <iterator>\n#include <string>\n#include <chrono>\n\n// Boost includes\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n\n// Local includes\n#include \"vector_utilities.hpp\"\n\n// OUT and IN can be redefined as a filestream\n// to enable direct file input/output\n// In MinGW already defined in windef.h, so need to undef them first\n#ifdef OUT\n#undef OUT\n#endif // OUT\n#define OUT std::cout\n#ifdef IN\n#undef IN\n#endif\n#define IN  std::cin\n#define ERROUT std::cerr\n#define LF  std::endl\n#define ABS std::abs\n\n// Problem size and number of velocity dimensions to keep track of,\n// to avoid magic numbers in loops\n#define PRB_DIM 3\n#define VEL_DIM 1\n\n// Array sizes\n//  - data is in [2..n+1] with [0], [1], [n+2] and [n+3] as buffers\n#define NX      (params.nx+4)\n#define NXFIRST (2)\n#define NXLAST  (params.nx+2)\n\n// Output modes\n#define OUT_MODE_STEP 1\n#define OUT_MODE_TIME 2\n\n// Time stepping modes\n#define TIME_MODE_CONSTANT 1\n#define TIME_MODE_VARIABLE 2\n\n// Time stepping methods\n#define STEP_EULER   1\n#define STEP_RK3TVD  2\n#define STEP_RIEMANN 3\n\n// Spatial integration methods\n#define METHOD_CENTRAL_FD 1\n#define METHOD_ENO        2\n\n// Boundary conditions\n#define BOUNDARY_OPEN        1\n#define BOUNDARY_PERIODIC    2\n\n// Special problem types\n#define PROBLEM_NORMAL  1\n#define PROBLEM_PISTON  2\n#define PROBLEM_RIEMANN 3\n\n// Function return values\n#define RET_OK              0\n#define RET_NO_CHANGE       1\n#define RET_UPDATED         2\n#define RET_ERR_TIME_UNDERFLOW         -1\n#define RET_RIEMANN_FAILED_TO_CONVERGE -2\n\n#define EPS            (1e-20)\n#define EPS_EQUAL(a,b) (std::abs((a)-(b))<EPS)\n#define EPS_ZERO(x)    (std::abs(x)<EPS)\n#define MAX(a,b)       ((a)>(b) ? (a) : (b))\n\ntypedef struct {\n   // Output categories\n   bool natural;\n   bool conservation;\n\n   // Skipping parameters\n   int    skip_mode;\n   int    skip_steps;\n   double skip_t;\n\n   // File\n   std::string filename;\n   FILE *file;\n} t_output;\n\ntypedef struct {\n   // Grid parameters\n   int    nx;\n   double dx;\n   double start_x;\n\n   // Time parameters\n   int    time_mode;\n   int    steps;\n   double cfl_number;\n   double dt_min;\n   double dt_max;\n   double t_max;\n\n   // Simulation parameters\n   int boundary;\n   int time_stepping;\n   int scheme;\n\n   // Physical parameters\n   double gamma;\n\n   // Problem-specific parameters\n   int problem_type;\n   int param_dbl_n;\n   int param_int_n;\n   t_vector param_dbl;\n   int     *param_int;\n} t_params;\n\ntypedef struct {\n   // Conserved variables; density, momentum, magnetic field, energy\n   t_vectors U;\n   // Primitive variables; velocity and pressure\n   t_vectors u;\n   t_vector  p;\n   double dt;\n   double t_current;\n} t_data;\n\n// File access - open & close\nvoid openFile(  t_output &output );\nvoid closeFile( t_output  output );\n\n// File access - input from ini\nvoid inputData( const std::string filename,\n                t_output &output_grid, t_output &output_non_grid, t_params &params, t_data &data );\n\n// File access - output grid data file\nvoid outputGridData( const t_output &output, const t_params &params, const t_data &data, int step, int index );\n\n// File access - output non-grid data to file\nvoid outputNonGridData( const t_output &output, const t_params &params, const t_data &data, int step, int index );\n\n// Conversion - conservation to natural variables\nvoid toNatural( const t_params &params,\n                t_data &data );\n\n// Conversion - natural to conservation variables\nvoid toConservation( const t_params &params,\n                     t_data &data );\n\n// Time stepper - Third order optimal TVD Runge-Kutta time stepping method\nint rk3tvd( t_vectors U, double &dt, const t_params &params );\n\n// Time stepper - Euler time stepping method\nint euler_step( t_vectors U, double &dt, const t_params &params );\n\n// Solver - Riemann solver\nint riemann_solver( t_data &data, const t_params &params );\n\n// Scheme - central FD\nvoid central_fd( t_vectors U, t_vectors UL, double &dt_step,\n                 const t_params &params );\n\n// Scheme - ENO-Roe with characteristics decomposition\nvoid eno_system_roe( t_vectors U, t_vectors UL, double &dt_step,\n                     const t_params &params );\n\n#endif // EULER1D_HPP_INCLUDED\n", "meta": {"hexsha": "2a940b9fb98937c9ec55ab196049e558e407dd0c", "size": 4419, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "euler-1d-solver/euler1d.hpp", "max_stars_repo_name": "piccolo255/mhd2d-solver", "max_stars_repo_head_hexsha": "be635bb6f5f8d3d06a9fa02a15801eedd1f50306", "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": "euler-1d-solver/euler1d.hpp", "max_issues_repo_name": "piccolo255/mhd2d-solver", "max_issues_repo_head_hexsha": "be635bb6f5f8d3d06a9fa02a15801eedd1f50306", "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": "euler-1d-solver/euler1d.hpp", "max_forks_repo_name": "piccolo255/mhd2d-solver", "max_forks_repo_head_hexsha": "be635bb6f5f8d3d06a9fa02a15801eedd1f50306", "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.1475409836, "max_line_length": 114, "alphanum_fraction": 0.6990269292, "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5192816532424042}}
{"text": "\n#include <Eigen/Dense>\n\n#include \"TestsCatchRequire.h\"\n#include \"../core/MatrixUtils.h\"\n\n// Dummy function for testing applyFunction\ndouble addOne(double x) {\n    return x+1;\n}\n\nTEST_CASE(\"MatrixUtils initializeRandomWeights\", \"[MatrixUtils]\") {\n    Eigen::MatrixXd m = Eigen::Matrix2d::Zero();\n\n    SECTION(\"Test method initialise randomly\") {\n        MatrixUtils::initializeRandomWeights(m);\n        REQUIRE(m.isZero(0) == false);\n    }\n\n    SECTION(\"Test method initialise no seed\") {\n        Eigen::MatrixXd m2 = Eigen::Matrix2d::Zero();\n\n        MatrixUtils::initializeRandomWeights(m, false);\n        MatrixUtils::initializeRandomWeights(m2, false);\n\n        REQUIRE(m.isZero(0) == false);\n        REQUIRE(m2.isZero(0) == false);\n\n        REQUIRE(m == m2);\n    }\n}\n", "meta": {"hexsha": "c88f226135684458e3df8a201a3a010d410edcf4", "size": 772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/MatrixUtilsTest.cpp", "max_stars_repo_name": "samueljackson92/cynapse", "max_stars_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/MatrixUtilsTest.cpp", "max_issues_repo_name": "samueljackson92/cynapse", "max_issues_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-10-09T16:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-30T07:06:21.000Z", "max_forks_repo_path": "src/test/MatrixUtilsTest.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": 24.125, "max_line_length": 67, "alphanum_fraction": 0.6476683938, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208002, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5192816516892321}}
{"text": "#ifndef MATHTOOLBOX_BFGS_HPP\n#define MATHTOOLBOX_BFGS_HPP\n\n#include <Eigen/Core>\n#include <functional>\n\nnamespace mathtoolbox\n{\n    namespace optimization\n    {\n        void RunBfgs(const Eigen::VectorXd&                                        x_init,\n                     const std::function<double(const Eigen::VectorXd&)>&          f,\n                     const std::function<Eigen::VectorXd(const Eigen::VectorXd&)>& g,\n                     const double                                                  epsilon,\n                     const unsigned int                                            max_num_iterations,\n                     Eigen::VectorXd&                                              x_star,\n                     unsigned int&                                                 num_iterations);\n    }\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_BFGS_HPP\n", "meta": {"hexsha": "70a3f86f51be013006f73dc2aca0d1790864926e", "size": 875, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/bfgs.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/bfgs.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/bfgs.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": 39.7727272727, "max_line_length": 102, "alphanum_fraction": 0.4468571429, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583250334527, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.5192816438318285}}
{"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#ifdef _MSC_VER\n#  pragma warning (disable : 4189) //  'd' : local variable is initialized but not referenced\n#endif\n\n#include <iostream>\nusing std::cout; using std::endl;\n\n#include <stdexcept>\nusing std::domain_error;\n\n//[policy_ref_snip13\n\n#include <boost/math/distributions/cauchy.hpp>\n\nnamespace myspace\n{ // using namespace boost::math::policies; // May be convenient in myspace.\n\n  // Define a policy called my_policy to use.\n  using boost::math::policies::policy;\n\n// In this case we want all the distribution accessor functions to compile,\n// even if they are mathematically undefined, so\n// make the policy assert_undefined.\n  using boost::math::policies::assert_undefined;\n\ntypedef policy<assert_undefined<false> > my_policy;\n\n// Finally apply this policy to type double.\nBOOST_MATH_DECLARE_DISTRIBUTIONS(double, my_policy)\n} // namespace myspace\n\n// Now we can use myspace::cauchy etc, which will use policy\n// myspace::mypolicy:\n//\n// This compiles but throws a domain error exception at runtime.\n// Caution! If you omit the try'n'catch blocks,\n// it will just silently terminate, giving no clues as to why!\n// So try'n'catch blocks are very strongly recommended.\n\nvoid test_cauchy()\n{\n   try\n   {\n      double d = mean(myspace::cauchy());  // Cauchy does not have a mean!\n   }\n   catch(const std::domain_error& e)\n   {\n      cout << e.what() << endl;\n   }\n}\n\n//] //[/policy_ref_snip13]\n\nint main()\n{\n   test_cauchy();\n}\n\n/*\n\nOutput:\n\npolicy_snip_13.vcxproj -> J:\\Cpp\\MathToolkit\\test\\Math_test\\Release\\policy_snip_13.exe\n  Error in function boost::math::mean(cauchy<double>&): The Cauchy distribution does not have a mean: the only possible return value is 1.#QNAN.\n\n  */\n", "meta": {"hexsha": "9c0324ca421f9664f9584c66e2e16a466e0ff144", "size": 2079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/policy_ref_snip13.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_snip13.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_snip13.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": 27.3552631579, "max_line_length": 144, "alphanum_fraction": 0.7253487253, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5192816438318285}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <vector>\n#include \"algorithms/math/primes.hpp\"\n\nBOOST_AUTO_TEST_SUITE(TestPrimesGeneration)\n\nBOOST_AUTO_TEST_CASE(naive_invalid)\n{\n    BOOST_CHECK(std::vector<int>() == Algo::Math::GetPrimesNaive<int>(-10));\n    BOOST_CHECK(std::vector<int>() == Algo::Math::GetPrimesNaive<int>(0));\n    BOOST_CHECK(std::vector<int>() == Algo::Math::GetPrimesNaive<int>(1));\n}\n\nBOOST_AUTO_TEST_CASE(naive_min)\n{\n    std::vector<int> expected = {2};\n    BOOST_CHECK(expected == Algo::Math::GetPrimesNaive<int>(2));\n}\n\nBOOST_AUTO_TEST_CASE(naive)\n{\n    std::vector<int> expected = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,\n            41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};\n\n    BOOST_CHECK(expected == Algo::Math::GetPrimesNaive<int>(100));\n}\n\nBOOST_AUTO_TEST_CASE(improved_invalid)\n{\n    BOOST_CHECK(std::vector<int>() == Algo::Math::GetPrimesImproved<int>(-10));\n    BOOST_CHECK(std::vector<int>() == Algo::Math::GetPrimesImproved<int>(0));\n    BOOST_CHECK(std::vector<int>() == Algo::Math::GetPrimesImproved<int>(1));\n}\n\nBOOST_AUTO_TEST_CASE(improved_min)\n{\n    std::vector<int> expected = {2};\n    BOOST_CHECK(expected == Algo::Math::GetPrimesImproved<int>(2));\n}\n\nBOOST_AUTO_TEST_CASE(improved)\n{\n    std::vector<int> expected = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,\n            41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};\n\n    BOOST_CHECK(expected == Algo::Math::GetPrimesImproved<int>(100));\n}\n\nBOOST_AUTO_TEST_CASE(seive_invalid)\n{\n    BOOST_CHECK(std::vector<int>() == Algo::Math::GetPrimesSeive<int>(-10));\n    BOOST_CHECK(std::vector<int>() == Algo::Math::GetPrimesSeive<int>(0));\n    BOOST_CHECK(std::vector<int>() == Algo::Math::GetPrimesSeive<int>(1));\n}\n\nBOOST_AUTO_TEST_CASE(seive_min)\n{\n    std::vector<int> expected = {2};\n    BOOST_CHECK(expected == Algo::Math::GetPrimesSeive<int>(2));\n}\n\nBOOST_AUTO_TEST_CASE(seive)\n{\n    std::vector<int> expected = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,\n            41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};\n\n    BOOST_CHECK(expected == Algo::Math::GetPrimesSeive<int>(100));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "51912f758c901f534c59aa5e99736c8f1bddf683", "size": 2160, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/math/test_primes.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_primes.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_primes.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": 30.0, "max_line_length": 79, "alphanum_fraction": 0.6564814815, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6959583250334527, "lm_q1q2_score": 0.5192816438318285}}
{"text": "#include \"randomGraphDrawing.h\"\n#include <random>\n#include <boost/graph/topological_sort.hpp>\n#include <boost/range/adaptor/reversed.hpp>\n\n\nnamespace WikiMainPath {\n\tnamespace GraphDrawing {\n\t\tstd::vector<double> averaged_precessor_graph_drawing(const EventNetwork& event_network)\n\t\t{\n\t\t\tstd::size_t n_wo_incoming = 0;\n\t\t\tfor(std::size_t i = 0; i < boost::num_vertices(event_network); i++)\n\t\t\t\tif(boost::in_degree(i, event_network) == 0)\n\t\t\t\t\tn_wo_incoming++;\n\n\t\t\tdouble cur_pos = 0;\n\t\t\tstd::vector<double> positions(boost::num_vertices(event_network), 0.0);\n\t\t\tfor(std::size_t i = 0; i < boost::num_vertices(event_network); i++)\n\t\t\t\tif(boost::in_degree(i, event_network) == 0)\n\t\t\t\t{\n\t\t\t\t\tcur_pos += 1.0 / (n_wo_incoming+1);\n\t\t\t\t\tpositions[i] = cur_pos;\n\t\t\t\t}\n\n\t\t\t// std::vector<EventNetwork::vertex_descriptor> topological_order;\n\t\t\t// boost::topological_sort(event_network, std::back_inserter(topological_order));\n\n\t\t\t// for(std::size_t v = 0; v < boost::num_vertices(event_network); v++)\n\t\t\tfor(auto v : boost::make_iterator_range(boost::vertices(event_network))) // output from boost::topological_sort is in reverse top. order => reverse again\n\t\t\t// for(auto v : boost::adaptors::reverse(topological_order)) // output from boost::topological_sort is in reverse top. order => reverse again\n\t\t\t\tif(boost::in_degree(v, event_network) == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\telse {\n\t\t\t\t\t// compute average of incoming neighbours\n\t\t\t\t\tdouble avg = 0.0;\n\t\t\t\t\tfor (auto e : boost::make_iterator_range(boost::in_edges(v,event_network)))\n\t\t\t\t\t\tavg += positions[boost::source(e,event_network)];\n\t\t\t\t\tavg = avg / boost::in_degree(v,event_network);\n\n\t\t\t\t\tpositions[v] = avg;\n\t\t\t\t}\n\n\t\t\treturn positions;\n\t\t}\n\n\t} \n}\n", "meta": {"hexsha": "e43495bcb9e803869c1a4866ce589dd45b4f2517", "size": 1691, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backend/graphDrawing/averagedPrecessorGraphDrawing.cpp", "max_stars_repo_name": "bencabrera/wikiMainPath", "max_stars_repo_head_hexsha": "a42e81a8fbe119e858548045653b2a22068a34f8", "max_stars_repo_licenses": ["MIT"], "max_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/graphDrawing/averagedPrecessorGraphDrawing.cpp", "max_issues_repo_name": "bencabrera/wikiMainPath", "max_issues_repo_head_hexsha": "a42e81a8fbe119e858548045653b2a22068a34f8", "max_issues_repo_licenses": ["MIT"], "max_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/graphDrawing/averagedPrecessorGraphDrawing.cpp", "max_forks_repo_name": "bencabrera/wikiMainPath", "max_forks_repo_head_hexsha": "a42e81a8fbe119e858548045653b2a22068a34f8", "max_forks_repo_licenses": ["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.2291666667, "max_line_length": 156, "alphanum_fraction": 0.691898285, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5192816391265406}}
{"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: Luigi Palmieri */\n#define BOOST_TEST_MODULE \"HaltonDeterministicSampling\"\n#include <boost/test/unit_test.hpp>\n#include <boost/filesystem.hpp>\n\n#include <ompl/config.h>\n#include <ompl/base/samplers/deterministic/HaltonSequence.h>\n#include \"../resources/haltonXD.h\"\n\n#include <iostream>\n\nnamespace ob = ompl::base;\n\nBOOST_AUTO_TEST_CASE(Halton_1D)\n{\n    boost::filesystem::path path(TEST_RESOURCES_DIR);\n    // Reading sequence from file\n    HaltonXD hd1 = HaltonXD(1);\n    hd1.loadSequence((path / \"halton/halton_1d.txt\").string().c_str());\n    std::vector<std::vector<double>> seq = hd1.getSequence();\n    // Defining Halton sequence from ompl::base\n    ob::HaltonSequence hs1d(1);\n    // checking if we have read all rows\n    BOOST_CHECK_EQUAL(seq.size(), 5);\n    // checking the samples of the rows\n    for (unsigned int i = 0; i < 5; ++i)\n    {\n        std::vector<double> sample = hs1d.sample();\n        std::vector<double> read_sample = seq[i];\n        BOOST_CHECK_EQUAL(sample.size(), read_sample.size());\n\n        for (unsigned int j = 0; j < sample.size(); j++)\n        {\n            BOOST_CHECK_CLOSE(sample[j], read_sample[j], 0.001);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Halton_2D)\n{\n    boost::filesystem::path path(TEST_RESOURCES_DIR);\n    // Reading sequence from file\n    HaltonXD hd2 = HaltonXD(2);\n    hd2.loadSequence((path / \"halton/halton_2d.txt\").string().c_str());\n    std::vector<std::vector<double>> seq = hd2.getSequence();\n    // Defining Halton sequence from ompl::base\n    ob::HaltonSequence hs2d(2);\n    // checking if we have read all rows\n    BOOST_CHECK_EQUAL(seq.size(), 5);\n    // checking the samples of the rows\n    for (unsigned int i = 0; i < 5; ++i)\n    {\n        std::vector<double> sample = hs2d.sample();\n        std::vector<double> read_sample = seq[i];\n        BOOST_CHECK_EQUAL(sample.size(), read_sample.size());\n\n        for (unsigned int j = 0; j < sample.size(); j++)\n        {\n            BOOST_CHECK_CLOSE(sample[j], read_sample[j], 0.001);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Halton_5D)\n{\n    boost::filesystem::path path(TEST_RESOURCES_DIR);\n    // Reading sequence from file\n    HaltonXD hd5 = HaltonXD(5);\n    hd5.loadSequence((path / \"halton/halton_5d.txt\").string().c_str());\n    std::vector<std::vector<double>> seq = hd5.getSequence();\n    // Defining Halton sequence from ompl::base\n    ob::HaltonSequence hs5d(5);\n    // checking if we have read all rows\n    BOOST_CHECK_EQUAL(seq.size(), 5);\n    // checking the samples of the rows\n    for (unsigned int i = 0; i < 5; ++i)\n    {\n        std::vector<double> sample = hs5d.sample();\n        std::vector<double> read_sample = seq[i];\n        BOOST_CHECK_EQUAL(sample.size(), read_sample.size());\n\n        for (unsigned int j = 0; j < sample.size(); j++)\n        {\n            BOOST_CHECK_CLOSE(sample[j], read_sample[j], 0.001);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Halton_10D)\n{\n    boost::filesystem::path path(TEST_RESOURCES_DIR);\n    // Reading sequence from file\n    HaltonXD hd10 = HaltonXD(10);\n    hd10.loadSequence((path / \"halton/halton_10d.txt\").string().c_str());\n    std::vector<std::vector<double>> seq = hd10.getSequence();\n    // Defining Halton sequence from ompl::base\n    ob::HaltonSequence hs10d(10);\n    // checking if we have read all rows\n    BOOST_CHECK_EQUAL(seq.size(), 5);\n    // checking the samples of the rows\n    for (unsigned int i = 0; i < 5; ++i)\n    {\n        std::vector<double> sample = hs10d.sample();\n        std::vector<double> read_sample = seq[i];\n        BOOST_CHECK_EQUAL(sample.size(), read_sample.size());\n\n        for (unsigned int j = 0; j < sample.size(); j++)\n        {\n            BOOST_CHECK_CLOSE(sample[j], read_sample[j], 0.001);\n        }\n    }\n}\n", "meta": {"hexsha": "7f0306211930fcefedfc5c1de35106ec9b4071d4", "size": 5506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/base/halton_deterministic_sampling.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": "tests/base/halton_deterministic_sampling.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": "tests/base/halton_deterministic_sampling.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": 37.4557823129, "max_line_length": 73, "alphanum_fraction": 0.6554667635, "num_tokens": 1363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5192816312691367}}
{"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#ifndef STAPL_CONTAINERS_MULTIARRAY_BLOCK_PARTITION_HPP\n#define STAPL_CONTAINERS_MULTIARRAY_BLOCK_PARTITION_HPP\n\n#include <boost/mpl/int.hpp>\n#include <stapl/containers/partitions/ndim_partition.hpp>\n#include <stapl/containers/partitions/balanced.hpp>\n#include <stapl/domains/indexed.hpp>\n#include <stapl/utility/tuple.hpp>\n#include <cmath>\n#include <algorithm>\n#include <array>\n#include <numeric>\n#include <iterator>\n\n#include \"partitions_generator.hpp\"\n\n#include <stapl/containers/type_traits/is_invertible_partition.hpp>\n\nnamespace stapl {\n\nnamespace multiarray_impl {\n\n////////////////////////////////////////////////////////////////////////\n/// @brief Determines if a number is not prime.\n////////////////////////////////////////////////////////////////////////\nstruct not_prime\n{\n  bool operator()(size_t x) const\n  {\n    for (size_t i = floor(sqrt(x)); i >= 2; --i)\n    {\n      if (x % i == 0 && i != x)\n        return true;\n    }\n\n    return false;\n  }\n};\n\n\n////////////////////////////////////////////////////////////////////////\n/// @brief Function object that initializes a tuple of n elements that is\n/// used to create an n-dimensional multiarray partition.\n////////////////////////////////////////////////////////////////////////\ntemplate<size_t N, typename = make_index_sequence<N>>\nstruct make_multiarray_size;\n\n\ntemplate <size_t N, std::size_t... Indices>\nstruct make_multiarray_size<N, index_sequence<Indices...>>\n{\n  using result_type = typename homogeneous_tuple_type<N, size_t>::type;\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Partitions the elements of the multiarray appropriately in\n  /// each dimension.\n  /// @param p The number of processors.\n  //////////////////////////////////////////////////////////////////////\n  result_type operator()(size_t p) const\n  {\n    std::array<size_t, N> v;\n\n    v[0] = p;\n\n    std::fill(v.begin() + 1, v.end(), 1);\n\n    auto equal_one = [](size_t const& val) { return val == 1; };\n    auto prime     = [](size_t const& val) { return !not_prime()(val); };\n\n    while (std::count_if(v.begin(), v.end(), equal_one) > 0\n        && std::count_if(v.begin(), v.end(), not_prime()) > 0)\n    {\n      auto filtered = std::partition(v.begin(), v.end(), prime);\n      auto val1     = std::max_element(filtered, v.end());\n      auto val2     = std::find_if(v.begin(), v.end(), equal_one);\n\n      for (size_t i = floor(sqrt(*val1)); i >= 2; i--)\n      {\n        if (*val1 % i == 0) {\n          *val2 = *val1/i;\n          *val1 = i;\n          break;\n        }\n      }\n    }\n\n    return result_type(get<N-Indices-1>(v)...);\n  }\n}; // struct make_multiarray_size\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief n-dimensional partition consisting of balanced_partitions of\n/// indexed_domain. This class will partition a multidimensional domain\n/// into multidimensional blocks with a certain number of blocks in each\n/// dimension. This is the default partition for the @ref multiarray\n/// container.\n///\n/// @tparam Traversal Multidimensional traversal type\n/// @see multiarray\n//////////////////////////////////////////////////////////////////////\ntemplate <typename Traversal>\nclass block_partition\n  : public nd_partition<\n      typename homogeneous_tuple_type<\n        tuple_size<Traversal>::value,\n        balanced_partition<indexed_domain<size_t>>>::type,\n      Traversal>\n{\nprivate:\n  /// The number of dimensions for this partition\n  using dimension_type = boost::mpl::int_<tuple_size<Traversal>::value>;\n  using base_type      = nd_partition<\n                           typename homogeneous_tuple_type<\n                             tuple_size<Traversal>::value,\n                             balanced_partition<indexed_domain<size_t>>>::type,\n                           Traversal>;\n\npublic:\n  using partitions_type = typename base_type::partitions_type;\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Create a multidimensional partition based on a given n-dimensional\n  /// domain that is balanced based on the number of locations in each\n  /// dimension.\n  /// @param dom The original domain to partition.\n  //////////////////////////////////////////////////////////////////////\n  template<typename Dom>\n  explicit\n  block_partition(const Dom& dom)\n    : base_type(partitions_impl::partitions_generator<\n                  tuple_size<Traversal>::value, Dom, partitions_type\n                >(dom)(partitions_type()))\n  { }\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Create a multidimensional partition based on a given n-dimensional\n  /// domain and a tuple of the number of partitions in each dimension.\n  /// @param dom The original domain to partition.\n  /// @param nparts Tuple of the number of partitions in each dimension\n  //////////////////////////////////////////////////////////////////////\n  template<typename Dom, typename NParts>\n  block_partition(Dom const& dom, NParts const& nparts)\n    : base_type(partitions_impl::partitions_generator<\n                  tuple_size<Traversal>::value, Dom, partitions_type\n                >(dom)(partitions_type(), nparts))\n  { }\n}; // class block_partition\n\n} // namespace multiarray_impl\n\n\ntemplate<typename Traversal>\nstruct is_invertible_partition<multiarray_impl::block_partition<Traversal>>\n  : public std::integral_constant<bool, true>\n{ };\n\n} // namespace stapl\n\n#endif // STAPL_CONTAINERS_MULTIARRAY_BLOCK_PARTITION_HPP\n", "meta": {"hexsha": "95d28dddc80fbebca2846a33f959296eb10cd01c", "size": 5864, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stapl_release/stapl/containers/partitions/block_partition.hpp", "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/stapl/containers/partitions/block_partition.hpp", "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/stapl/containers/partitions/block_partition.hpp", "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": 34.0930232558, "max_line_length": 79, "alphanum_fraction": 0.5806616644, "num_tokens": 1191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5192530719311881}}
{"text": "#include \"InstructionFactory.h\"\n#include \"InstructionOptions.h\"\n#include \"../animations/Animation.h\"\n\n#include \"../objects/Line.h\"\n#include \"../objects/Circle.h\"\n#include \"../objects/Rectangle.h\"\n#include \"../objects/Spiral.h\"\n#include \"../objects/CompositeObject.h\"\n\n#include <chrono>\n#include <cmath>\n#include <cassert>\n\n#include <boost/date_time/time.hpp>\n\n#include <json/value.h>\n\nnamespace laser { namespace holodeck {\n\nconst Color MetaDataColor(Color::LIGHTBLUE);\n\nstatic void ShiftPoints(std::vector<Point> & points, Point base)\n{\n\tfor (Point & p: points)\n\t\tp += base;\n}\n\n/*!\n * \\brief determine characteristic values for a rectangle\n * \\image html calculateRectangleCharacteristics.svg\n * \\param[in] p1 midpoint of one short side of the rectangle\n * \\param[in] p2 midpoint of the other short side\n * \\param[out] angle angle between x-axis and line between \\a p1 and \\a p2\n * \\param[out] length \\f$ \\mbox{length} = \\sqrt{(\\mbox{p1}_x - \\mbox{p2}_x)^2 + (\\mbox{p1}_y - \\mbox{p2}_y)^2} \\f$\n * \\param[out] start start point of axis aligned bounding box\n * \\param[out] mid mid point of axis aligned bounding box\n * \\param[out] end end point of axis aligned bounding box\n */\nstatic void calculateRectangleCharacteristics(Point p1, Point p2, float &angle, float &length, Point &start, Point &mid, Point &end)\n{\n\t// calculate rotation\n\tint dx = p2.x() - p1.x();\n\tint dy = p2.y() - p1.y();\n\tangle = atan2(dy, dx);\n\n\t// length of wall\n\tlength = sqrt(sqr(dx) + sqr(dy));\n\n\tmid = (p1 + p2) / 2;\n\tstart = mid - Point(0, length / 2);\n\tend   = mid + Point(0, length / 2);\n}\n\nstatic ObjectPtr getDigit(const Json::Value &root, unsigned int i, Point p = Point(0, 0), double rotation = 0.0)\n{\n\tint id = root.get(\"turkers\",\n\t\t\t\t\t\t\t\tJson::Value())\n\t\t\t\t\t\t  .get(i,\n\t\t\t\t\t\t\t\tJson::Value(-1))\n\t\t\t\t\t\t  .asInt();\n\tCompositeObjectPtr digit = opts::Digit::get(id);\n\tif (digit) {\n\t\tdigit->rotate(rotation, Point(250, 500));\n\t\tdigit->move(p);\n\t\tdigit->setColor(MetaDataColor);\n\t}\n\treturn digit;\n}\n\nstatic ObjectPtr MovingIndicator(const Point & p1, double angle)\n{\n\tconst double right = p1.x() + opts::IndicatorWidth * 0.5;\n\tconst double left = p1.x() - opts::IndicatorWidth * 0.5;\n\tconst double top = p1.y() - opts::IndicatorHeight * 0.5;\n\tconst double bottom = p1.y() + opts::IndicatorHeight * 0.5;\n\n\tCompositeObjectPtr group = CompositeObject::construct();\n\tLine *lA0 = new Line(Point(left, top), p1),\n\t\t *lA1 = new Line(p1, Point(right, top)),\n\t\t *lB0 = new Line(right, p1.y(), p1.x(), bottom),\n\t\t *lB1 = new Line(p1.x(), bottom, left, p1.y());\n\n\tgroup->add(lA0);\n\tgroup->add(lA1);\n\tgroup->add(lB0);\n\tgroup->add(lB1);\n\n\tgroup->setColor(MetaDataColor);\n\tgroup->rotate(angle, p1);\n\n\tstd::shared_ptr<int> storedStep(new int);\n\t*storedStep = 3;\n\tgroup->addAnimation([=](Object *){\n\t\t// What about static's semantic?\n\t\tint step = *storedStep;\n\t\tlA0->setVisible((bool)(step & 1) != (bool)(step & 2));\n\t\tlA1->setVisible((bool)(step & 1) != (bool)(step & 2));\n\n\t\tlB0->setVisible(step & 2);\n\t\tlB1->setVisible(step & 2);\n\t\t*storedStep = (step + 1) & 3;\n\t}, Animation::msecs(200));\n\n\treturn group;\n}\n\n////////////////////////////////////////////////////////////\n\nObjectPtr InstructionFactory::Wall(const Json::Value &root, Point p1, Point p2, Point p3, Point p4)\n{\n\treturn Table(root, p1, p2, p3, p4);\n}\n\n// Hannes asked to define walls by four points. I keep that one for MovingWalls, Door, etc.\nstatic ObjectPtr TwoPointWall(const Json::Value & root, Point p1, Point p2)\n{\n\tCompositeObjectPtr group = CompositeObject::construct();\n\tgroup->add(new Line(p1, p2, true));\n\n\tfloat alpha;\n\tfloat length;\n\tPoint midPoint;\n\tPoint start;\n\tPoint end;\n\n\tcalculateRectangleCharacteristics(p1, p2, alpha, length, start, midPoint, end);\n\n\tPoint p1p2 = p2 - p1;\n\tObjectPtr turkerId = getDigit(root, 0);\n\tif(turkerId){\n\t\tturkerId->rotate(alpha);\n\t\tturkerId->move(midPoint - p1p2 / 2);\n\t\tturkerId->move(Point(-p1p2.y(), p1p2.x()).norm() * 100);\n\n\t\tgroup->add(turkerId);\n\t}\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::MovingWall(const Json::Value &root, Point p1, Point p2)\n{\n\tCompositeObjectPtr group = std::dynamic_pointer_cast<CompositeObject>(TwoPointWall(root, p1, p2));\n\n\tPoint direction = p2 - p1;\n\tPoint mid = p1 + direction * 0.5;\n\tPoint spacer = direction.perpendicular().norm() * opts::IndicatorDistance;\n\n\tgroup->add(MovingIndicator(mid + spacer, direction.angle()));\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::Door(const Json::Value &root, Point p1, Point p2)\n{\n\tCompositeObjectPtr door = std::dynamic_pointer_cast<CompositeObject>(TwoPointWall(root, p1, p2));\n\tdoor->add(new Circle(p2, 750));\n\n\treturn door;\n}\n\nObjectPtr InstructionFactory::Table(const Json::Value &root, Point p1, Point p2, Point p3, Point p4)\n{\n\tCompositeObjectPtr group = CompositeObject::construct();\n\tconst Point center = (p1 + p2 + p3 + p4) * 0.25;\n\tgroup->add(new Rectangle(p1, p2, p3, p4, false));\n\tgroup->add(getDigit(root, 0, center));\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::Player(const Json::Value &root, Point p)\n{\n\t// No turkerId needed here\n\t(void)root;\n\tObjectPtr c(new Circle(p, 1000));\n\tc->setPermanent(true);\n\treturn c;\n}\n\nObjectPtr InstructionFactory::Switch(const Json::Value &root, Point p1, Point p2)\n{\n\tCompositeObjectPtr group = CompositeObject::construct();\n\n\tgroup->add(new Circle(p2, opts::SwitchHandleSize));\n\n\tPoint stickDirection(p2 - p1);\n\tPoint attachmentPoint = p2 - stickDirection.norm() * opts::SwitchHandleSize;\n\tgroup->add(new Line(p1, attachmentPoint));\n\tgroup->add(getDigit(root, 0, p1 + stickDirection / 2, stickDirection.angle()));\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::Beam(const Json::Value &root, Point p1, Point p2)\n{\n\tCompositeObjectPtr group = CompositeObject::construct();\n\n\tfloat alpha;\n\tfloat length;\n\tPoint midPoint;\n\tPoint start;\n\tPoint end;\n\tPoint dir(p2 - p1);\n\n\tcalculateRectangleCharacteristics(p1, p2, alpha, length, start, midPoint, end);\n\n\tRectangle *bigRect = new Rectangle(midPoint.x() - 1000,\n\t\t\t\t\t\t\t\t\t   midPoint.y() - length/2,\n\t\t\t\t\t\t\t\t\t   2000, // beam is 1000 thick\n\t\t\t\t\t\t\t\t\t   length, // and as long as requested\n\t\t\t\t\t\t\t\t\t   false);\n\tbigRect->rotate(alpha-M_PI_2, midPoint);\n\tgroup->add(bigRect);\n\tgroup->add(getDigit(root, 0, midPoint + dir.norm().perpendicular() * 1000, dir.angle()));\n\n\treturn group;\n}\n\nstatic ObjectPtr Portal(const Json::Value &root, Point p1, Point p2, bool active)\n{\n\t(void)root;\n\tCompositeObjectPtr group = CompositeObject::construct();\n\n\tfloat alpha;\n\tfloat length;\n\tPoint mid;\n\tPoint start;\n\tPoint end;\n\n\tcalculateRectangleCharacteristics(p1, p2, alpha, length, start, mid, end);\n\n\tif (active)\n\t{\n\t\tgroup->add(new Line(start, start + Point(length / 3, 0)));\n\t\tgroup->add(new Spiral(mid.x(), mid.y() + length/8, 200, length/4, 3, active));\n\t\tgroup->add(new Line(end - Point(length/3, 0), end));\n\t}\n\telse\n\t{\n\t\tgroup->add(new Line(start, end));\n\t\tgroup->add(new Spiral(mid.x(), mid.y() + length/8, 200, length/4, 3, active));\n\t}\n\n\tgroup->rotate(alpha, mid);\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::PortalInactive(const Json::Value &root, Point p1, Point p2)\n{ return Portal(root, p1, p2, false); }\n\nObjectPtr InstructionFactory::PortalActive(const Json::Value &root, Point p1, Point p2)\n{ return Portal(root, p1, p2, true); }\n\nObjectPtr InstructionFactory::Zipline(const Json::Value &root, Point p1, Point p2)\n{\n\tCompositeObjectPtr group = CompositeObject::construct();\n\tconst Point midaxis(p2 - p1);\n\tconst Point direction = midaxis.norm();\n\tconst Point perpendic = direction.perpendicular();\n\n\t// Need 5 turkers\n\tauto addTurkerDigit = [&](const int index, const Point & pos) {\n\t\tgroup->add(getDigit(root, index, pos, direction.angle()));\n\t};\n\n\taddTurkerDigit(0, p1 - direction.norm() * (opts::ZipLineOuterCircle + opts::Number0Right) - perpendic * opts::Number0Bottom);\n\taddTurkerDigit(1, p1 - direction.norm() * (opts::ZipLineOuterCircle + opts::Number0Right));\n\n\tgroup->add(new Circle(p1, opts::ZipLineOuterCircle));\n\tgroup->add(new Circle(p1, opts::ZipLineInnerCircle));\n\n\tgroup->add(new Line(p1, p2));\n\n\tgroup->add(new Circle(p2, opts::ZipLineInnerCircle));\n\tgroup->add(new Circle(p2, opts::ZipLineOuterCircle));\n\n\taddTurkerDigit(2, p2 + direction.norm() * opts::ZipLineOuterCircle - perpendic * opts::Number0Bottom);\n\taddTurkerDigit(3, p2 + direction.norm() * opts::ZipLineOuterCircle);\n\n\taddTurkerDigit(4, p1 + midaxis * 0.5);\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::ZiplineWithStep(const Json::Value &root, Point p1, Point p2, Point p3, Point p4)\n{\n\tCompositeObjectPtr group = std::dynamic_pointer_cast<CompositeObject>(Zipline(root, p1, p2));\n\n\tconst Point direction(p2 - p1);\n\n\tauto fromMidLineTo = [&](const Point & target){\n\t\t// Project p1-target-vector on p1-p2-vector\n\t\tPoint b_proj = direction * (direction.dot(target - p1) / sqr(direction.abs()));\n\t\t// find foot point and measure distance\n\t\treturn target - (p1 + b_proj);\n\t};\n\n\tconst Point toP3 = fromMidLineTo(p3);\n\tconst Point toP4 = fromMidLineTo(p4);\n\tconst Point leftStart = p1 + (direction.norm() * opts::ZipLineOuterCircle);\n\tconst Point rightEnd = p2 - (direction.norm() * opts::ZipLineOuterCircle);\n\tObjectPtr step(new Rectangle(leftStart + toP4, rightEnd + toP4, rightEnd + toP3, leftStart + toP3));\n\tgroup->add(step);\n\n\tconst Point indicatorLine = p1 + toP3 + toP3.norm() * opts::IndicatorDistance;\n\tgroup->add(MovingIndicator(indicatorLine + direction * 0.25, direction.angle()));\n\tgroup->add(MovingIndicator(indicatorLine + direction * 0.75, direction.angle()));\n\n\t// No digit here. Let the guy with the horizontal stick think he is in charge\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::Stool(const Json::Value &root, Point p1, Point p2, Point p3, Point p4)\n{\n\t//return std::make_shared<Rectangle>(p1, p2, p3, p4, false);\n\n\t// They just look the same\n\treturn Table(root, p1, p2, p3, p4);\n}\n\nObjectPtr InstructionFactory::Corpse(const Json::Value &root, Point head, Point chest)\n{\n\tCompositeObjectPtr corpse = CompositeObject::construct();\n\n\tconst double bodyAspectRatio = 0.702;\n\tconst double spine = (head - chest).abs(); // bodyHeight\n\tconst double bodyWidth = bodyAspectRatio * spine * 2;\n\tconst double armWidth = 0.10 * spine;\n\n\tPoint armStart(bodyWidth * (3.0 / 8), -spine * 1.0/3);\n\tPoint ellbow(bodyWidth * 0.5, -spine);\n\tPoint upperArm(ellbow - armStart);\n\tPoint armShift(armWidth, 0);\n\n\n\tObjectPtr turkerId = getDigit(root, 0, Point(0, -spine * 0.3));\n\tif(turkerId) corpse->add(turkerId);\n\n\tObjectPtr body(new Circle(0, 0, spine, M_PI));\n\tbody->scale(bodyAspectRatio, 1.0);\n\tcorpse->add(body);\n\n\tcorpse->add(new Circle(Point(0, -spine), 0.4 * spine, radians(158), radians(382)));\n\tcorpse->add(new Line(armStart, ellbow));\n\tcorpse->add(new Line(ellbow, ellbow + upperArm.scaled(-1, 1)));\n\tcorpse->add(new Line(ellbow + upperArm.scaled(-1, 1) + armShift, ellbow + armShift));\n\tcorpse->add(new Line(ellbow + armShift, armStart + armShift));\n\n\tcorpse->rotate(M_PI_2 + (head - chest).angle());\n\tcorpse->move(chest);\n\n\treturn CompositeObject::construct(corpse);  // Safely store transform on corpse\n}\n\nObjectPtr InstructionFactory::Water(const Json::Value &root, Point p)\n{\n\t(void)root;\n\tCompositeObjectPtr group = CompositeObject::construct();\n\n\tgroup->add(new Circle(p, 2000, 3.8*M_PI_4, 9*M_PI_4));\n\tgroup->add(new Line(p.x() - 1750, p.y()+500, p.x(), p.y() + 4000));\n\tgroup->add(new Line(p.x() + 1750, p.y()+500, p.x(), p.y() + 4000));\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::Poke(const Json::Value &root, Point p1, Point p2)\n{\n\t(void)root;\n\tCompositeObjectPtr group = CompositeObject::construct();\n\n\tfloat alpha;\n\tfloat length;\n\tPoint mid;\n\tPoint start;\n\tPoint end;\n\n\tcalculateRectangleCharacteristics(p1, p2, alpha, length, start, mid, end);\n\n\tgroup->add(new Rectangle(start.x(), start.y()-500, length, 1000, false));\n\tgroup->add(new Rectangle(start.x()+3000, start.y()-3000, length-3000, 2500, false));\n\tgroup->add(new Rectangle(mid.x()+2000, start.y(), length/2-2000, 2500, false));\n\tgroup->add(new Line(start.x()+3000, start.y() -2000, mid.x()+2000, start.y() -2000));\n\tgroup->add(new Line(start.x()+3000, start.y() -1000, mid.x()+2000, start.y() -1000));\n\tgroup->rotate(alpha, mid);\n\n\n\tgroup->addAnimation([](Object *o) {\n\t\t\t\t\t\t\to->setVisible(!o->visible());\n\t\t\t\t\t\t}, std::chrono::milliseconds(50));\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::Footwear(const Json::Value &root, Point p)\n{\n\t(void)root;\n\tCompositeObjectPtr group = CompositeObject::construct();\n\tCompositeObjectPtr groupA = CompositeObject::construct();\n\tCompositeObjectPtr groupB = CompositeObject::construct();\n\n\tgroupA->add(new Circle(p, 1000));\n\tgroupA->add(new Circle(p + Point(1000, 1000), 300));\n\n\n\tstd::vector<Point> points;\n\tpoints.emplace_back(+ 300,  700);\n\tpoints.emplace_back(+ 200, 1400);\n\tpoints.emplace_back(    0,  700);\n\tpoints.emplace_back(- 200, 1400);\n\tpoints.emplace_back(- 300,  700);\n\tpoints.emplace_back(- 500, 1400);\n\tpoints.emplace_back(- 700,  700);\n\t//points.emplace_back(+ 500,  700);\n\tShiftPoints(points, p);\n\n\tgroupA->add(new Polygon(points, false));\n\n\tgroupA->move(-p);\n\tgroupA->scale(1, 2);\n\tgroupA->move(p);\n\n\tgroupA->move(-1500, 0);\n\n\n\tgroupB->add(new Circle(p, 1000));\n\tgroupB->add(new Circle(p + Point(1000, 1000), 300));\n\n\n\tpoints.clear();\n\tpoints.emplace_back(+ 300,  700);\n\tpoints.emplace_back(+ 200, 1400);\n\tpoints.emplace_back(    0,  700);\n\tpoints.emplace_back(- 200, 1400);\n\tpoints.emplace_back(- 300,  700);\n\tpoints.emplace_back(- 500, 1400);\n\tpoints.emplace_back(- 700,  700);\n\t//points.emplace_back(+ 500, 700);\n\tShiftPoints(points, p);\n\n\tgroupB->add(new Polygon(points, false));\n\n\tgroupB->move(-p);\n\tgroupB->scale(-1, 2);\n\tgroupB->move(p);\n\n\tgroupB->move(1500, 0);\n\n\tgroup->add(groupA);\n\tgroup->add(groupB);\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::Heat(const Json::Value &root, Point p)\n{\n\t(void)root;\n\tCompositeObjectPtr group = CompositeObject::construct();\n\n\tgroup->add(new Circle(p, 2000, 3.8*M_PI_4, 9*M_PI_4));\n\n\n\tstd::vector<Point> points;\n\n\tpoints.emplace_back(-1750,  500);\n\tpoints.emplace_back(-1500, 1000);\n\tpoints.emplace_back(-1000,  750);\n\tpoints.emplace_back(    0, 2000);\n\tpoints.emplace_back(  500, 1000);\n\tpoints.emplace_back( 1250, 4000);\n\tpoints.emplace_back( 1750,  500);\n\tShiftPoints(points, p);\n\n\tgroup->add(new Polygon(points, false, false, false));\n\n    return group;\n}\n\nObjectPtr InstructionFactory::Elevator(const Json::Value &root, Point p1, Point p2, Point p3)\n{\n\t(void)root;\n\tCompositeObjectPtr group = CompositeObject::construct();\n\n\tPoint s12 = p2 - p1;\n\tPoint s13 = p3 - p1;\n\tPoint s23 = p3 - p2;\n\tPoint arrowOneBottom = p1 + s12 / 5   + s23 / 5;\n\tPoint arrowOneTop    = p1 + s12 / 5   + s23 * 0.8;\n\tPoint arrowTwoBottom = p1 + s12 * 0.8 + s23 / 5;\n\tPoint arrowTwoTop    = p1 + s12 * 0.8 + s23 * 0.8;\n\n\tPoint arrowOneTopTipRight = arrowOneTop - s13 * 0.1;\n\tPoint arrowOneTopTipLeft  = arrowOneTop + s13.scaled(0.1, -0.1);\n\tPoint arrowTwoBottomTipRight = arrowTwoBottom + s13 * 0.1;\n\tPoint arrowTwoBottomTipLeft = arrowTwoBottom + s13.scaled(-0.1, 0.1);\n\n\tgroup->add(new Rectangle(p1, p2, p3, p3 - s12, false));\n\tgroup->add(new Line(arrowOneBottom, arrowOneTop));\n\tgroup->add(new Line(arrowOneTop, arrowOneTopTipRight));\n\tgroup->add(new Line(arrowOneTop, arrowOneTopTipLeft));\n\tgroup->add(new Line(arrowTwoBottom, arrowTwoTop));\n\tgroup->add(new Line(arrowTwoBottom, arrowTwoBottomTipRight));\n\tgroup->add(new Line(arrowTwoBottom, arrowTwoBottomTipLeft));\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::Guardrail(const Json::Value &root, Point p1, Point p2, Point p3, Point p4)\n{\n\t(void)root;\n\tCompositeObjectPtr group = CompositeObject::construct();\n\n\tfloat alpha;\n\tfloat length;\n\tPoint midPoint;\n\tPoint start;\n\tPoint end;\n\n\tcalculateRectangleCharacteristics(p1, p2, alpha, length, start, midPoint, end);\n\n\tPoint p1p2 = p2 - p1;\n\tObjectPtr turkerId = getDigit(root, 0);\n\tif(turkerId){\n\t\tturkerId->rotate(alpha);\n\t\tturkerId->move(midPoint - p1p2 / 2);\n\t\tturkerId->move(Point(-p1p2.y(), p1p2.x()).norm() * 100);\n\t\tgroup->add(turkerId);\n\t}\n\tgroup->add(new Rectangle(p1, p2, p3, p4, false));\n\treturn group;\n}\n\nObjectPtr InstructionFactory::BlueprintWall(const Json::Value &root, Point p1, Point p2)\n{\n\t// No turker for this one\n\t(void)root;\n\n\tPoint start = p1 + (p2 - p1) / 10;\n\tPoint end   = p2 + (p1 - p2) / 10;\n\n\tCompositeObjectPtr group = CompositeObject::construct();\n\n\tgroup->add(new Line(p1, start));\n\tgroup->add(new Line(end, p2));\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::MovingWallWarning(const Json::Value &root, Point p1, Point p2)\n{\n\tint normalX = root.get(\"direction\", Json::Value()).get(\"x\", Json::Value()).asInt();\n\tint normalY = root.get(\"direction\", Json::Value()).get(\"y\", Json::Value()).asInt();\n//\tint countdown = root.get(\"countdown\", Json::Value(5000)).asInt();\n\tPoint arrowTop = (p1 + p2) / 2 + Point(normalX, normalY).norm() * 1000;\n\tPoint arrowEnd = arrowTop\n\t\t\t\t\t - Point(normalX, normalY).norm() * 500\n\t\t\t\t\t + (p2 - p1).norm() * 250;\n\n\tCompositeObjectPtr group = CompositeObject::construct();\n\n\tgroup->add(new Line(p1, p2));\n\n\tstd::vector<Point> arrowPoints {(p1 + p2) / 2, arrowTop, arrowEnd};\n\n\tObjectPtr arrow = std::make_shared<Polygon>(arrowPoints, false, false, false);\n\tarrow->addAnimation([] (Object *me) {\n\t\t\t\t\t\t\t\t\t\tstatic bool visible = true;\n\t\t\t\t\t\t\t\t\t\tvisible = !visible;\n\t\t\t\t\t\t\t\t\t\tme->setVisible(visible);\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\tstd::chrono::milliseconds(500)\n\t);\n\tgroup->add(arrow);\n\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::MoveTurker(const Json::Value &root, BlinkFrequency freq, Point p1, Point p2)\n{\n\t(void)root;\n\tCompositeObjectPtr group = CompositeObject::construct();\n\tgroup->add(new /*long*/ Line(p1, p2));\n\tPoint end = p2 + (p1 - p2)/3;\n\tLine* shortLine = new Line(p2, end);\n\tshortLine->rotate(30.0f/180.0f*M_PI, p2);\n\tgroup->add(shortLine);\n\tstd::chrono::milliseconds blinkfrequency;\n\tswitch (freq) {\n\tcase LOW:\n\t\tblinkfrequency = std::chrono::milliseconds(1000);\n\t\tbreak;\n\tcase MEDIUM:\n\t\tblinkfrequency = std::chrono::milliseconds(500);\n\t\tbreak;\n\tcase HIGH:\n\t\tblinkfrequency = std::chrono::milliseconds(100);\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tif (freq != NO)\n\t{\n\t\t\tgroup->addAnimation([] (Object* me)\n\t\t\t{\n\t\t\t\tstatic bool visible = false;\n\t\t\t\tvisible = !visible;\n\t\t\t\tme->setVisible(visible);\n\t\t\t}, blinkfrequency);\n\t}\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::MoveTurkerLowFreq(const Json::Value &root, Point p1, Point p2)\n{\n\treturn MoveTurker(root, LOW, p1, p2);\n}\n\nObjectPtr InstructionFactory::MoveTurkerMidFreq(const Json::Value &root, Point p1, Point p2)\n{\n\treturn MoveTurker(root, MEDIUM, p1, p2);\n}\n\nObjectPtr InstructionFactory::MoveTurkerHighFreq(const Json::Value &root, Point p1, Point p2)\n{\n\treturn MoveTurker(root, HIGH, p1, p2);\n}\n\nObjectPtr InstructionFactory::MoveTurkerNoFreq(const Json::Value &root, Point p1, Point p2)\n{\n\treturn MoveTurker(root, NO, p1, p2);\n}\n\nObjectPtr InstructionFactory::MoveDoorClockwise(const Json::Value &root, BlinkFrequency freq, Point p1, Point p2)\n{\n\t(void)root;\n\tPoint p1p2 = p2 - p1;\n\tdouble distance = p1p2.abs();\n\tdouble radius = distance / M_SQRT2;\n\t//std::cout << radius << std::endl;\n\tPoint halfway = (p1 + p2) / 2.0f;\n\t//ststd::cout << halfway << std::endl;\n\tPoint center = halfway + p1p2.perpendicular().norm() * sqrt(sqr(radius) - sqr(distance/2));\n\t//ststd::cout << center << std::endl;\n\tdouble startAngle = (p1 - center).angle();\n\t//ststd::cout << startAngle << std::endl;\n\tdouble endAngle = (p2 - center).angle();\n\tif (endAngle < startAngle)\n\t{\n\t\tendAngle += 2*M_PI;\n\t}\n\t//ststd::cout << endAngle << std::endl;\n\tPoint arrowEnd = p2 + (p2 - center) / 3.0f;\n\n\tCompositeObjectPtr group = CompositeObject::construct();\n\tgroup->add(new Circle(center, radius, startAngle, endAngle));\n\tLine* shortLine = new Line(p2, arrowEnd);\n\tshortLine->rotate(-60.0f/180.0f*M_PI, p2);\n\tgroup->add(shortLine);\n\tstd::chrono::milliseconds blinkfrequency;\n\tswitch (freq) {\n\tcase LOW:\n\t\tblinkfrequency = std::chrono::milliseconds(1000);\n\t\tbreak;\n\tcase MEDIUM:\n\t\tblinkfrequency = std::chrono::milliseconds(500);\n\t\tbreak;\n\tcase HIGH:\n\t\tblinkfrequency = std::chrono::milliseconds(100);\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tif (freq != NO)\n\t{\n\t\t\tgroup->addAnimation([] (Object* me)\n\t\t\t{\n\t\t\t\tstatic bool visible = false;\n\t\t\t\tvisible = !visible;\n\t\t\t\tme->setVisible(visible);\n\t\t\t}, blinkfrequency);\n\t}\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::MoveDoorCounterClockwise(const Json::Value &root, BlinkFrequency freq, Point p1, Point p2)\n{\n\t(void)root;\n\tPoint p1p2 = p2 - p1;\n\tdouble distance = p1p2.abs();\n\tdouble radius = distance / M_SQRT2;\n\t//std::cout << radius << std::endl;\n\tPoint halfway = (p1 + p2) / 2.0f;\n\t//std:std::cout << halfway << std::endl;\n\tPoint center = halfway - p1p2.perpendicular().norm() * sqrt(sqr(radius) - sqr(distance/2));\n\t//std:std::cout << center << std::endl;\n\tdouble startAngle = (p1 - center).angle();\n\t//std:std::cout << startAngle << std::endl;\n\tdouble endAngle = (p2 - center).angle();\n\tif (endAngle < startAngle)\n\t{\n\t\tendAngle += 2*M_PI;\n\t}\n\t//std:std::cout << endAngle << std::endl;\n\tPoint arrowEnd = p2 + (p2 - center) / 3.0f;\n\n\tCompositeObjectPtr group = CompositeObject::construct();\n\tgroup->add(new Circle(center, radius, endAngle, startAngle));\n\tLine* shortLine = new Line(p2, arrowEnd);\n\tshortLine->rotate(60.0f/180.0f*M_PI, p2);\n\tgroup->add(shortLine);\n\tstd::chrono::milliseconds blinkfrequency;\n\tswitch (freq) {\n\tcase LOW:\n\t\tblinkfrequency = std::chrono::milliseconds(1000);\n\t\tbreak;\n\tcase MEDIUM:\n\t\tblinkfrequency = std::chrono::milliseconds(500);\n\t\tbreak;\n\tcase HIGH:\n\t\tblinkfrequency = std::chrono::milliseconds(100);\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tif (freq != NO)\n\t{\n\t\t\tgroup->addAnimation([] (Object* me)\n\t\t\t{\n\t\t\t\tstatic bool visible = false;\n\t\t\t\tvisible = !visible;\n\t\t\t\tme->setVisible(visible);\n\t\t\t}, blinkfrequency);\n\t}\n\n\treturn group;\n}\n\nObjectPtr InstructionFactory::MoveDoorClockwiseNoFreq(const Json::Value &root, Point p1, Point p2)\n{\n\treturn MoveDoorClockwise(root, NO, p1, p2);\n}\n\nObjectPtr InstructionFactory::MoveDoorClockwiseLowFreq(const Json::Value &root, Point p1, Point p2)\n{\n\treturn MoveDoorClockwise(root, LOW, p1, p2);\n}\n\nObjectPtr InstructionFactory::MoveDoorClockwiseMidFreq(const Json::Value &root, Point p1, Point p2)\n{\n\treturn MoveDoorClockwise(root, MEDIUM, p1, p2);\n}\n\nObjectPtr InstructionFactory::MoveDoorClockwiseHighFreq(const Json::Value &root, Point p1, Point p2)\n{\n\treturn MoveDoorClockwise(root, HIGH, p1, p2);\n}\n\nObjectPtr InstructionFactory::MoveDoorCounterClockwiseNoFreq(const Json::Value &root, Point p1, Point p2)\n{\n\treturn MoveDoorCounterClockwise(root, NO, p1, p2);\n\n}\n\nObjectPtr InstructionFactory::MoveDoorCounterClockwiseLowFreq(const Json::Value &root, Point p1, Point p2)\n{\n\treturn MoveDoorCounterClockwise(root, LOW, p1, p2);\n\n}\n\nObjectPtr InstructionFactory::MoveDoorCounterClockwiseMidFreq(const Json::Value &root, Point p1, Point p2)\n{\n\treturn MoveDoorCounterClockwise(root, MEDIUM, p1, p2);\n\n}\n\nObjectPtr InstructionFactory::MoveDoorCounterClockwiseHighFreq(const Json::Value &root, Point p1, Point p2)\n{\n\treturn MoveDoorCounterClockwise(root, HIGH, p1, p2);\n}\n\nObjectPtr InstructionFactory::TurkerLabel(const Json::Value &root, Point p1, Point p2)\n{\n\tObjectPtr digit = getDigit(root, 0, p1);\n\tif (digit)\n\t\tdigit->rotate((p2 - p1).angle(), p1);\n\treturn digit;\n}\n\n}} // namespace laser::holodeck\n", "meta": {"hexsha": "e54c8d8da5c807c4b534d3b33e01e3d2189b045a", "size": 23141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/holodeck/InstructionFactory.cpp", "max_stars_repo_name": "Chaostreff-Potsdam/laser_control", "max_stars_repo_head_hexsha": "8f4f2adea7fe36fec85c64811a81e37057519a06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/holodeck/InstructionFactory.cpp", "max_issues_repo_name": "Chaostreff-Potsdam/laser_control", "max_issues_repo_head_hexsha": "8f4f2adea7fe36fec85c64811a81e37057519a06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-19T12:16:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-24T15:25:55.000Z", "max_forks_repo_path": "src/holodeck/InstructionFactory.cpp", "max_forks_repo_name": "Chaostreff-Potsdam/laser_control", "max_forks_repo_head_hexsha": "8f4f2adea7fe36fec85c64811a81e37057519a06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-24T12:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-24T12:50:47.000Z", "avg_line_length": 28.92625, "max_line_length": 132, "alphanum_fraction": 0.6903763882, "num_tokens": 6835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5192530719311881}}
{"text": "#ifndef IMAGE_REPROJECTION_PLUGINS_SPHERE_SURFACE_MODEL_HPP\n#define IMAGE_REPROJECTION_PLUGINS_SPHERE_SURFACE_MODEL_HPP\n\n#include <cmath>\n#include <string>\n\n#include <image_reprojection/surface_model.hpp>\n#include <image_reprojection_plugins/SphereStamped.h>\n#include <topic_tools/shape_shifter.h>\n\n#include <boost/thread/locks.hpp>\n#include <boost/thread/shared_mutex.hpp>\n\n#include <opencv2/core/core.hpp>\n\nnamespace image_reprojection_plugins {\n\nclass SphereSurfaceModel : public image_reprojection::SurfaceModel {\npublic:\n  SphereSurfaceModel() {}\n\n  virtual ~SphereSurfaceModel() {}\n\n  virtual void update(const topic_tools::ShapeShifter &surface) override {\n    const SphereStampedConstPtr sphere = surface.instantiate<SphereStamped>();\n    CV_Assert(sphere);\n    update(*sphere);\n  }\n\n  void update(const SphereStamped &sphere) {\n    CV_Assert(sphere.radius > 0.);\n\n    boost::unique_lock<boost::shared_mutex> write_lock(mutex_);\n\n    frame_id_ = sphere.header.frame_id;\n    center_ = cv::Vec3f(sphere.center.x, sphere.center.y, sphere.center.z);\n    radius_ = sphere.radius;\n  }\n\n  virtual std::string getFrameId() const override {\n    boost::shared_lock<boost::shared_mutex> read_lock(mutex_);\n    return frame_id_;\n  }\n\nprivate:\n  virtual void onInit() override {}\n\n  virtual void onIntersection(const cv::Vec3f &src_origin, const cv::Mat &src_direction,\n                              cv::Mat &dst, cv::Mat &mask) const override {\n    boost::shared_lock<boost::shared_mutex> read_lock(mutex_);\n    multiraySphereIntersection(src_origin, src_direction, dst, mask);\n  }\n\n  void multiraySphereIntersection(const cv::Vec3f &src_origin, const cv::Mat &src_direction,\n                                  cv::Mat &dst, cv::Mat &mask) const {\n    dst.create(src_direction.size(), CV_32FC3);\n    mask.forEach<uchar>([this, &src_origin, &src_direction, &dst](uchar &m, const int *const pos) {\n      if (m != 0) {\n        const cv::Vec3f &sd = *src_direction.ptr<cv::Vec3f>(pos[0], pos[1]);\n        cv::Vec3f &d = *dst.ptr<cv::Vec3f>(pos[0], pos[1]);\n        m = raySphereIntersection(src_origin, sd, d) ? 1 : 0;\n      }\n    });\n  }\n\n  bool raySphereIntersection(const cv::Vec3f &src_origin, const cv::Vec3f &src_direction,\n                             cv::Vec3f &dst) const {\n    // intersection point (x) can be described as\n    //   x = p + t * d  (t >= 0)\n    //   |x - c| = r\n    // where p: ray origin, d: ray direction, c: center of sphere, r: radius of sphere\n    //   |d|^2 * t^2 + 2 * dot(d, p - c) * t + |p - c|^2 - r^2 = 0\n\n    // position of ray origin with respect to center of sphere\n    const cv::Vec3f o = src_origin - center_;\n\n    // coefficients\n    const double a = src_direction.dot(src_direction);\n    const double b = src_direction.dot(o);\n    const double c = o.dot(o) - radius_ * radius_;\n    const double D = b * b - a * c; // discriminant\n    if (/* no intersection */ D < 0.) {\n      return false;\n    }\n\n    // intersection point\n    const double sD = std::sqrt(D);\n    const double t0 = (-b + sD) / a, t1 = (-b - sD) / a;\n    if (t0 >= 0. && t1 >= 0.) {\n      dst = src_origin + std::min(t0, t1) * src_direction;\n      return true;\n    } else if (t0 >= 0. && t1 < 0.) {\n      dst = src_origin + t0 * src_direction;\n      return true;\n    } else if (t0 < 0. && t1 >= 0.) {\n      dst = src_origin + t1 * src_direction;\n      return true;\n    }\n\n    return false;\n  }\n\nprivate:\n  mutable boost::shared_mutex mutex_;\n  std::string frame_id_;\n  cv::Vec3f center_;\n  double radius_;\n};\n\n} // namespace image_reprojection_plugins\n\n#endif", "meta": {"hexsha": "4b38b9f6ef8a0830f3dc87dd465049475d545f16", "size": 3558, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "image_reprojection_plugins/include/image_reprojection_plugins/sphere_surface_model.hpp", "max_stars_repo_name": "yoshito-n-students/image_reprojection", "max_stars_repo_head_hexsha": "7398c49619f7132ab95d8b9accce90a241d6507a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-09-14T05:26:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T04:28:03.000Z", "max_issues_repo_path": "image_reprojection_plugins/include/image_reprojection_plugins/sphere_surface_model.hpp", "max_issues_repo_name": "yoshito-n-students/image_reprojection", "max_issues_repo_head_hexsha": "7398c49619f7132ab95d8b9accce90a241d6507a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "image_reprojection_plugins/include/image_reprojection_plugins/sphere_surface_model.hpp", "max_forks_repo_name": "yoshito-n-students/image_reprojection", "max_forks_repo_head_hexsha": "7398c49619f7132ab95d8b9accce90a241d6507a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-14T04:03:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-14T04:03:35.000Z", "avg_line_length": 31.7678571429, "max_line_length": 99, "alphanum_fraction": 0.6447442383, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5192530639211863}}
{"text": "\n#include <stdlib.h>\n#include <math.h>\n#include <string>\n#include <GL/glut.h>\n#include <GL/freeglut_ext.h>\n\n#include <libpng/png.h>\n#include <live2d/Live2D.h>\n#include <live2d/util/UtSystem.h>\n#include <live2d/Live2DModelOpenGL.h>\n#include <live2d/util/Json.h>\n\n#include <opencv2/opencv.hpp> \n\n#include <dlib/opencv.h>\n#include <dlib/image_processing/frontal_face_detector.h>  \n#include <dlib/image_processing/render_face_detections.h>  \n#include <dlib/image_processing.h>  \n#include <dlib/gui_widgets.h>\n\nusing namespace std;\n\nlive2d::Live2DModelOpenGL* live2DModel;\ncv::VideoCapture* camera;\ndlib::frontal_face_detector detector;\ndlib::shape_predictor pose_model;\n\n// live2d parameters\nfloat x_rotate = 0.0f;\nfloat y_rotate = 0.0f;\nfloat z_rotate = 0.0f;\n\nfloat left_eye = 1.0f;\nfloat right_eye = 1.0f;\n\nfloat eyebrow_left = 0.0f;\nfloat eyebrow_right = 0.0f;\n\nfloat mouth_open = 0.0f;\n\ndouble meter(double A, double B, double C, double x, double y)\n{\n\tdouble diversion = A * x + B * y + C;\n\treturn diversion / sqrt(pow(A, 2) + pow(B, 2));\n}\n\ndouble eyebrow_move(dlib::point &p1, dlib::point &p2, double slope, double last, double rate)\n{\n\tdouble bias = p1.y() - slope * p1.x();\n\tdouble distance = sqrt(pow(p1.x() - p2.x(), 2) + pow(p1.y() - p2.y(), 2));\n\tdouble diversion = meter(slope, -1, bias, p2.x(), p2.y());\n\tdouble result = (diversion / distance - 0.45) * 6;\n\tresult = last * (1 - rate) + result * rate;\n\treturn result;\n}\n\ndouble eye_open(dlib::point &p1, dlib::point &p2, dlib::point &v11, dlib::point &v12, dlib::point &v21, dlib::point &v22, double last, double rate)\n{\n\tdouble distance = sqrt(pow(p1.x() - p2.x(), 2) + pow(p1.y() - p2.y(), 2));\n\tdouble slope = (double)(p2.y() - p1.y()) / (double)(p2.x() - p1.x());\n\tdouble bias = p2.y() - slope * p2.x();\n\tdouble d1 = abs(meter(slope, -1, bias, v11.x(), v11.y()));\n\tdouble d2 = abs(meter(slope, -1, bias, v12.x(), v12.y()));\n\tdouble diversion = d1 > d2 ? d1 : d2;\n\td1 = abs(meter(slope, -1, bias, v21.x(), v21.y()));\n\td2 = abs(meter(slope, -1, bias, v22.x(), v22.y()));\n\tdiversion += d1 > d2 ? d1 : d2;\n\tdouble ratio = (diversion / distance - 0.18) * 8;\n\tratio = ((int)(ratio * 10.0)) / 10.0;\n\tratio = last * (1 - rate) + ratio * rate;\n\treturn ratio;\n}\n\nvoid display(void)\n{\n\tcv::Mat buff, temp;\n\t*camera >> temp;\n\tcv::GaussianBlur(temp, buff, cv::Size(5, 5), 5, 5);\n\tcv::flip(buff, temp, 1);\n\n\tdlib::cv_image<dlib::bgr_pixel> cimg(temp);\n\tvector<dlib::rectangle> faces = detector(cimg);\n\tvector<dlib::full_object_detection> shapes;\n\n\tfor (unsigned long i = 0; i < faces.size(); ++i)\n\t\tshapes.push_back(pose_model(cimg, faces[i]));\n\n\tif (!shapes.empty()) {\n\t\tfor (int i = 0; i < 68; i++) {\n\t\t\tcv::circle(temp, cvPoint(shapes[0].part(i).x(), shapes[0].part(i).y()), 2, cv::Scalar(0, 0, 255), -1);\n\t\t}\n\n\t\tint div_x = shapes[0].part(16).x() - shapes[0].part(0).x();\n\t\tint div_y = shapes[0].part(16).y() - shapes[0].part(0).y();\n\t\tdouble center_x = shapes[0].part(0).x() + div_x / 2.0;\n\t\tdouble center_y = shapes[0].part(0).y() + div_y / 2.0;\n\t\tdouble slope = (double)(div_y) / (double)(div_x);\n\t\tdouble bias = center_y - slope * center_x;\n\t\tdouble x_proj = (slope * (shapes[0].part(30).y() - bias) + shapes[0].part(30).x()) / (1 + pow(slope, 2));\n\t\tdouble y_proj = slope * x_proj + bias;\n\t\tdouble diversion = sqrt(pow(x_proj - shapes[0].part(0).x(), 2) + pow(y_proj - shapes[0].part(0).y(), 2));\n\t\tdouble distance = sqrt(pow(shapes[0].part(16).x() - shapes[0].part(0).x(), 2) + pow(shapes[0].part(16).y() - shapes[0].part(0).y(), 2));\n\n\t\tdouble rate = 0.5;\n\t\t// Ax+By+C/sqrt(A^2+B^2)\n\t\tx_rotate = x_rotate * (1 - rate) + asin(diversion / distance - 0.5) * 3.14 * 40.0 * rate;\n\n\t\t// nose to eye around 1/6 head\n\t\tdiversion = meter(slope, -1, bias, shapes[0].part(30).x(), shapes[0].part(30).y());\n\t\tdiversion = diversion + 1.0 / 6 * distance;\n\t\ty_rotate = y_rotate * (1 - rate) + asin(diversion / distance) * 3.14 * 40.0 * rate;\n\n\t\tz_rotate = z_rotate * (1 - rate) + atan(slope) * 3.14 * 40 * rate;\n\n\t\t// eye\n\t\tleft_eye = eye_open(shapes[0].part(36), shapes[0].part(39), shapes[0].part(37), shapes[0].part(38), shapes[0].part(40), shapes[0].part(41), left_eye, rate);\n\t\tright_eye = eye_open(shapes[0].part(42), shapes[0].part(45), shapes[0].part(43), shapes[0].part(44), shapes[0].part(46), shapes[0].part(47), right_eye, rate);\n\n\t\t// eyebrow\n\t\teyebrow_left = eyebrow_move(shapes[0].part(17), shapes[0].part(19), slope, eyebrow_left, rate);\n\t\teyebrow_right = eyebrow_move(shapes[0].part(26), shapes[0].part(24), slope, eyebrow_right, rate);\n\n\t\t// mouth\n\t\tdiversion = sqrt(pow(shapes[0].part(62).x() - shapes[0].part(66).x(), 2) + pow(shapes[0].part(62).y() - shapes[0].part(66).y(), 2));\n\t\tdistance = sqrt(pow(shapes[0].part(60).x() - shapes[0].part(64).x(), 2) + pow(shapes[0].part(60).y() - shapes[0].part(64).y(), 2));\n\t\tmouth_open = (diversion / distance - 0.15) * 2;\n\t}\n\telse\n\t{\n\t\tx_rotate = 0.0f;\n\t\ty_rotate = 0.0f;\n\t\tz_rotate = 0.0f;\n\t\tleft_eye = 1.0f;\n\t\tright_eye = 1.0f;\n\t\teyebrow_left = 0.0f;\n\t\teyebrow_right = 0.0f;\n\t\tmouth_open = 0.0f;\n\t}\n\n\tglClear(GL_COLOR_BUFFER_BIT);\n\t//double t = (live2d::UtSystem::getUserTimeMSec() / 1000.0) * 2 * 3.14;\n\t//live2DModel->setParamFloat(\"PARAM_ANGLE_Z\", (float)(30 * sin(t / 3.0)));\n\tlive2DModel->setParamFloat(\"PARAM_ANGLE_X\", x_rotate);\n\tlive2DModel->setParamFloat(\"PARAM_ANGLE_Y\", y_rotate);\n\tlive2DModel->setParamFloat(\"PARAM_ANGLE_Z\", z_rotate);\n\n\tlive2DModel->setParamFloat(\"PARAM_EYE_L_OPEN\", left_eye);\n\tlive2DModel->setParamFloat(\"PARAM_EYE_R_OPEN\", right_eye);\n\n\tlive2DModel->setParamFloat(\"PARAM_BROW_L_Y\", eyebrow_left);\n\tlive2DModel->setParamFloat(\"PARAM_BROW_R_Y\", eyebrow_right);\n\n\tlive2DModel->setParamFloat(\"PARAM_MOUTH_OPEN_Y\", mouth_open);\n\n\tlive2DModel->update();\n\tlive2DModel->draw();\n\n\t//Display it all on the screen  \n\tcv::imshow(\"Feature points\", temp);\n\tglFlush();\n}\n\nvoid timer(int value) {\n\n\n\tglutPostRedisplay();\n\tglutTimerFunc(30, timer, 0);\n}\n\nint loadGLTexture(const char* path)\n{\n\tunsigned int id;\n\n\tFILE            *fp;\n\tpng_structp     png_ptr;\n\tpng_infop       info_ptr;\n\tunsigned int   width, height;\n\tint             bit_depth, color_type, interlace_type;\n\tunsigned char   *image;\n\n\terrno_t error;\n\n\tif ((error = fopen_s(&fp, path, \"rb\")) != 0) {\n\t\tprintf(\"file not exists!\");\n\t\treturn -1;\n\t}\n\n\tpng_ptr = png_create_read_struct(\n\t\tPNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n\tinfo_ptr = png_create_info_struct(png_ptr);\n\n\tpng_init_io(png_ptr, fp);\n\tpng_read_info(png_ptr, info_ptr);\n\tpng_get_IHDR(png_ptr, info_ptr, &width, &height,\n\t\t&bit_depth, &color_type, &interlace_type,\n\t\tNULL, NULL);\n\tint rb = png_get_rowbytes(png_ptr, info_ptr);\n\timage = new unsigned char[height * rb];\n\tunsigned char **recv = new unsigned char*[height];\n\tfor (int i = 0; i < height; i++)\n\t\trecv[i] = &image[i * rb];\n\tpng_read_image(png_ptr, recv);\n\tpng_read_end(png_ptr, info_ptr);\n\n\t//premultiplied alpha\n\n\n\tpng_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n\tfclose(fp);\n\tdelete[] recv;\n\n\n\tglEnable(GL_TEXTURE_2D);\n\tglGenTextures(1, &id);\n\n\tglBindTexture(GL_TEXTURE_2D, id);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n\n\t/*glTexImage2D(\n\tGL_TEXTURE_2D , 0 , GL_RGBA , width , height ,\n\t0 , GL_RGBA , GL_UNSIGNED_BYTE , image\n\t);*/\n\tgluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, width, height, GL_RGBA, GL_UNSIGNED_BYTE, image);\n\treturn id;\n}\n\nvoid Live2DInit(void)\n{\n\tglClearColor(0.0, 0.0, 1.0, 1.0);\n\n\tstd::string path = \"res/Epsilon/\";\n\tlive2DModel = live2d::Live2DModelOpenGL::loadModel((char*)((path + \"Epsilon.moc\").c_str()));\n\n\tconst char* TEXTURES[] = {\n\t\t(char*)((path + \"Epsilon.2048/texture_00.png\").c_str()),\n\t\tNULL ,\n\t};\n\n\tfor (int i = 0; i < 1000; i++) {\n\t\tif (!TEXTURES[i]) break;\n\n\t\tint tex = loadGLTexture(TEXTURES[i]);\n\n\t\tif (tex < 0) printf(\"failed\");\n\t\tlive2DModel->setTexture(i, tex);\n\t}\n\tlive2DModel->setPremultipliedAlpha(false);\n}\n\nvoid OpenCVInit(void)\n{\n\tcamera = new cv::VideoCapture(0);\n\tif (!camera->isOpened())\n\t{\n\t\tcerr << \"Unable to connect to camera\" << endl;\n\t}\n\n\tdetector = dlib::get_frontal_face_detector();\n\tdlib::deserialize(\"shape_predictor_68_face_landmarks.dat\") >> pose_model;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\n\tglLoadIdentity();\n\n\tfloat aspect = (float)w / h;\n\tfloat sx = 2.0 / live2DModel->getCanvasWidth();\n\tfloat sy = -2.0 / live2DModel->getCanvasWidth() * aspect;\n\tfloat x = -1;\n\tfloat y = 1;\n\tfloat matrix[] = {\n\t\tsx , 0 , 0 , 0 ,\n\t\t0 , sy ,0 , 0 ,\n\t\t0 , 0 , 1 , 0 ,\n\t\tx , y , 0 , 1\n\t};\n\n\n\tlive2DModel->setMatrix(matrix);\n}\n\n\nint main(int argc, char *argv[])\n{\n\tlive2d::Live2D::init();\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA);\n\tglutInitWindowSize(600, 600);\n\tglutCreateWindow(\"Model\");\n\tLive2DInit();\n\tOpenCVInit();\n\tglutDisplayFunc(display);\n\tglutReshapeFunc(resize);\n\tglutTimerFunc(100, timer, 0);\n\tglutMainLoop();\n\treturn 0;\n}\n\n", "meta": {"hexsha": "de573cc920efbe2195c4af80f4342128c77e31ba", "size": 8843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SimpleFacerig/main.cpp", "max_stars_repo_name": "HTTdesu/SimpleFacerig", "max_stars_repo_head_hexsha": "769f71f98440b3c946508fcc097ad9af4b26eb28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2018-05-01T08:57:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:53:11.000Z", "max_issues_repo_path": "SimpleFacerig/main.cpp", "max_issues_repo_name": "HTTdesu/SimpleFacerig", "max_issues_repo_head_hexsha": "769f71f98440b3c946508fcc097ad9af4b26eb28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-10-07T12:02:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-05T10:28:05.000Z", "max_forks_repo_path": "SimpleFacerig/main.cpp", "max_forks_repo_name": "HTTdesu/SimpleFacerig", "max_forks_repo_head_hexsha": "769f71f98440b3c946508fcc097ad9af4b26eb28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2019-07-12T17:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T04:28:14.000Z", "avg_line_length": 29.1848184818, "max_line_length": 160, "alphanum_fraction": 0.6566775981, "num_tokens": 3054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.5192381709161193}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2014 Alec Jacobson <alecjacobson@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 \"volume.h\"\n#include \"cross.h\"\n#include <Eigen/Geometry>\ntemplate <\n  typename DerivedV, \n  typename DerivedT, \n  typename Derivedvol>\nIGL_INLINE void igl::volume(\n  const Eigen::PlainObjectBase<DerivedV>& V,\n  const Eigen::PlainObjectBase<DerivedT>& T,\n  Eigen::PlainObjectBase<Derivedvol>& vol)\n{\n  using namespace Eigen;\n  const int m = T.rows();\n  vol.resize(m,1);\n  for(int t = 0;t<m;t++)\n  {\n    const RowVector3d & a = V.row(T(t,0));\n    const RowVector3d & b = V.row(T(t,1));\n    const RowVector3d & c = V.row(T(t,2));\n    const RowVector3d & d = V.row(T(t,3));\n    vol(t) = -(a-d).dot((b-d).cross(c-d))/6.;\n  }\n}\n\ntemplate <\n  typename DerivedA,\n  typename DerivedB,\n  typename DerivedC,\n  typename DerivedD,\n  typename Derivedvol>\nIGL_INLINE void igl::volume(\n  const Eigen::PlainObjectBase<DerivedA> & A,\n  const Eigen::PlainObjectBase<DerivedB> & B,\n  const Eigen::PlainObjectBase<DerivedC> & C,\n  const Eigen::PlainObjectBase<DerivedD> & D,\n  Eigen::PlainObjectBase<Derivedvol> & vol)\n{\n  const auto & AmD = A-D;\n  const auto & BmD = B-D;\n  const auto & CmD = C-D;\n  Eigen::PlainObjectBase<DerivedA> BmDxCmD;\n  cross(BmD.eval(),CmD.eval(),BmDxCmD);\n  const auto & AmDdx = (AmD.array() * BmDxCmD.array()).rowwise().sum();\n  vol = -AmDdx/6.;\n}\n\ntemplate <\n  typename VecA,\n  typename VecB,\n  typename VecC,\n  typename VecD>\nIGL_INLINE typename VecA::Scalar igl::volume_single(\n  const VecA & a,\n  const VecB & b,\n  const VecC & c,\n  const VecD & d)\n{\n  return -(a-d).dot((b-d).cross(c-d))/6.;\n}\n\n\ntemplate <\n  typename DerivedL, \n  typename Derivedvol>\nIGL_INLINE void igl::volume(\n  const Eigen::PlainObjectBase<DerivedL>& L,\n  Eigen::PlainObjectBase<Derivedvol>& vol)\n{\n  using namespace Eigen;\n  const int m = L.rows();\n  typedef typename Derivedvol::Scalar ScalarS;\n  vol.resize(m,1);\n  for(int t = 0;t<m;t++)\n  {\n    const ScalarS u = L(t,0);\n    const ScalarS v = L(t,1);\n    const ScalarS w = L(t,2);\n    const ScalarS U = L(t,3);\n    const ScalarS V = L(t,4);\n    const ScalarS W = L(t,5);\n    const ScalarS X = (w - U + v)*(U + v + w);\n    const ScalarS x = (U - v + w)*(v - w + U);\n    const ScalarS Y = (u - V + w)*(V + w + u);\n    const ScalarS y = (V - w + u)*(w - u + V);\n    const ScalarS Z = (v - W + u)*(W + u + v);\n    const ScalarS z = (W - u + v)*(u - v + W);\n    const ScalarS a = sqrt(x*Y*Z); \n    const ScalarS b = sqrt(y*Z*X); \n    const ScalarS c = sqrt(z*X*Y); \n    const ScalarS d = sqrt(x*y*z); \n    vol(t) = sqrt(\n       (-a + b + c + d)*\n       ( a - b + c + d)*\n       ( a + b - c + d)*\n       ( a + b + c - d))/\n       (192.*u*v*w);\n  }\n}\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\n// generated by autoexplicit.sh\ntemplate void igl::volume<Eigen::Matrix<double, -1, 6, 0, -1, 6>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 6, 0, -1, 6> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);\ntemplate Eigen::Matrix<double, 1, 3, 1, 1, 3>::Scalar igl::volume_single<Eigen::Matrix<double, 1, 3, 1, 1, 3>, Eigen::Matrix<double, 1, 3, 1, 1, 3>, Eigen::Matrix<double, 1, 3, 1, 1, 3>, Eigen::Matrix<double, 1, 3, 1, 1, 3> >(Eigen::Matrix<double, 1, 3, 1, 1, 3> const&, Eigen::Matrix<double, 1, 3, 1, 1, 3> const&, Eigen::Matrix<double, 1, 3, 1, 1, 3> const&, Eigen::Matrix<double, 1, 3, 1, 1, 3> const&);\ntemplate Eigen::Matrix<double, 3, 1, 0, 3, 1>::Scalar igl::volume_single<Eigen::Matrix<double, 3, 1, 0, 3, 1>, Eigen::Matrix<double, 3, 1, 0, 3, 1>, Eigen::Matrix<double, 3, 1, 0, 3, 1>, Eigen::Matrix<double, 3, 1, 0, 3, 1> >(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&);\ntemplate void igl::volume<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);\ntemplate void igl::volume<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);\n#endif\n", "meta": {"hexsha": "133303bb4cc46af44b54c21c10c034be93e2dfae", "size": 5055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/include/igl/volume.cpp", "max_stars_repo_name": "FabianRepository/SinusProject", "max_stars_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "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/include/igl/volume.cpp", "max_issues_repo_name": "FabianRepository/SinusProject", "max_issues_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/include/igl/volume.cpp", "max_forks_repo_name": "FabianRepository/SinusProject", "max_forks_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "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": 43.5775862069, "max_line_length": 597, "alphanum_fraction": 0.6132542038, "num_tokens": 1903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619393159452, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5192251941525807}}
{"text": "/**\n * \\file HadamardMixture.hxx\n */\n\n#include <ATK/Delay/FeedbackDelayNetworkFilter.hxx>\n#include <ATK/Delay/HadamardMixture.h>\n\n#include <Eigen/Dense>\n\n#include <ATK/Core/TypeTraits.h>\n#include <ATK/Utility/fmath.h>\n\nnamespace ATK\n{\n  template<typename DataType_, unsigned int order>\n  class HadamardMixture<DataType_, order>::MixtureImpl\n  {\n  public:\n    using Vector = Eigen::Matrix<DataType, nb_channels, 1>;\n    using Matrix = Eigen::Matrix<DataType, nb_channels, nb_channels>;\n\n    Vector mix(const Vector& x) const\n    {\n      return transition * x;\n    }\n\n  protected:\n    const Matrix transition = create();\n    \n    static Matrix create()\n    {\n      return (DataType_(1 / fmath::pow(2, order / 2.)) * recursive_create<order>()).template cast<DataType_>();\n    }\n    \n    template<unsigned int recursive_order>\n    static Eigen::Matrix<typename TypeTraits<DataType_>::Scalar, (1U<<recursive_order), (1U<<recursive_order)> recursive_create()\n    {\n      if constexpr(recursive_order == 0)\n      {\n        return Eigen::Matrix<typename TypeTraits<DataType_>::Scalar, 1U, 1U>::Constant(1);\n      }\n      else\n      {\n        constexpr auto big_size = (1U << recursive_order);\n        constexpr auto small_size = (1U << (recursive_order - 1));\n        Eigen::Matrix<typename TypeTraits<DataType_>::Scalar, big_size, big_size> cur_transition;\n        \n        auto M_1 = recursive_create<recursive_order - 1>();\n        cur_transition.block(0, 0, small_size, small_size) = M_1;\n        cur_transition.block(0, small_size, small_size, small_size) = M_1;\n        cur_transition.block(small_size, 0, small_size, small_size) = -M_1;\n        cur_transition.block(small_size, small_size, small_size, small_size) = M_1;\n        return cur_transition;\n      }\n    }\n  };\n}\n", "meta": {"hexsha": "fed673d9b8239f9f9e25aa9d410a3c01c9f19457", "size": 1772, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "ATK/Delay/HadamardMixture.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/Delay/HadamardMixture.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/Delay/HadamardMixture.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.5517241379, "max_line_length": 129, "alphanum_fraction": 0.6670428894, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5192251914362842}}
{"text": "#include \"Core.h\"\r\n#include \"random.h\"\r\n#include <boost/random.hpp>\r\n#include <ctime>\r\n\r\nfloat angle_clamp(const float rads) {\r\n\tconst float P = float(2.0*M_PI);\r\n\tfloat clamped = rads;\r\n\t\r\n\twhile (clamped < 0.0f) {\r\n\t\tclamped += P;\r\n\t}\r\n\t\r\n\twhile (clamped > 2*P) {\r\n\t\tclamped -= P;\r\n\t}\r\n\t\r\n\treturn clamped;\r\n}\r\n\r\nfloat getAngle( const vec2 &a, const vec2 &b ) {\r\n\tfloat dx = a.x - b.x;\r\n\tfloat dy = a.y - b.y;\r\n\tfloat rads = atan2f(dy, dx);\r\n\tfloat clamped = angle_clamp(rads);\r\n\treturn clamped;\r\n}\r\n\r\nvec3 GetRandomVector(float length) {\r\n\treturn vec3(FRAND_RANGE(-1.0f,+1.0f),\r\n\t            FRAND_RANGE(-1.0f,+1.0f),\r\n\t            FRAND_RANGE(-1.0f,+1.0f)).getNormal() * length;\r\n}\r\n\r\nstring toString(const any &value) {\r\n\tstring typeName = value.type().name();\r\n\t\r\n\tif (typeName == typeid(vec2).name()) {\r\n\t\treturn vec2::toString(any_cast<vec2>(value));\r\n\t} else if (typeName == typeid(vec3).name()) {\r\n\t\treturn vec3::toString(any_cast<vec3>(value));\r\n\t} else if (typeName == typeid(vec4).name()) {\r\n\t\treturn vec4::toString(any_cast<vec4>(value));\r\n\t} else if (typeName == typeid(mat4).name()) {\r\n\t\treturn mat4::toString(any_cast<mat4>(value));\r\n\t} else if (typeName == typeid(mat3).name()) {\r\n\t\treturn mat3::toString(any_cast<mat3>(value));\r\n\t} else if (typeName == typeid(float).name()) {\r\n\t\treturn ftos(any_cast<float>(value));\r\n\t} else if (typeName == typeid(int).name()) {\r\n\t\treturn itos(any_cast<int>(value));\r\n\t} else if (typeName == typeid(size_t).name()) {\r\n\t\treturn sizet_to_string(any_cast<size_t>(value));\r\n\t} else if (typeName == typeid(bool).name()) {\r\n\t\treturn any_cast<bool>(value) ? \"true\" : \"false\";\r\n\t} else {\r\n\t\treturn \"???\";\r\n\t}\r\n}\r\n\r\nvec3 calcTriNorm(const vec3 &a, const vec3 &b, const vec3 &c) {\r\n\tvec3 v1 = a - b;\r\n\tvec3 v2 = b - c;\r\n\tvec3 n = v1.cross(v2);\r\n\treturn n.getNormal();\r\n}\r\n\r\nvec3 calcTriNorm(const Triangle &tri) {\r\n\treturn calcTriNorm(tri.a, tri.b, tri.c);\r\n}\r\n\r\nfloat SampleLogNormal(float mean, float sigma) {\r\n\t// Create a Mersenne twister random number generator\r\n\t// that is seeded once with #seconds since 1970\r\n\tstatic mt19937 rng(static_cast<unsigned> (std::time(0)));\r\n\t\r\n\t// select gamma probability distribution\r\n\tlognormal_distribution<float> dist(mean, sigma);\r\n\t\r\n\t// bind random number generator to distribution, forming a function\r\n\tvariate_generator<mt19937&, lognormal_distribution<float> >  sampler(rng, dist);\r\n\t\r\n\t// sample from the distribution\r\n\treturn sampler();\r\n}\r\n\r\nfloat SampleNormal(float mean, float sigma) {\r\n\t// Create a Mersenne twister random number generator\r\n\t// that is seeded once with #seconds since 1970\r\n\tstatic mt19937 rng(static_cast<unsigned> (std::time(0)));\r\n\t\r\n\t// select Gaussian probability distribution\r\n\tnormal_distribution<float> norm_dist(mean, sigma);\r\n\t\r\n\t// bind random number generator to distribution, forming a function\r\n\tvariate_generator<mt19937&, normal_distribution<float> >  normal_sampler(rng, norm_dist);\r\n\t\r\n\t// sample from the distribution\r\n\treturn normal_sampler();\r\n}\r\n", "meta": {"hexsha": "c04c6784b37680d9c109fcbba607312222c65898", "size": 2982, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Core.cpp", "max_stars_repo_name": "foxostro/CheeseTesseract", "max_stars_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-05-17T03:36:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-17T03:36:52.000Z", "max_issues_repo_path": "src/Core.cpp", "max_issues_repo_name": "foxostro/CheeseTesseract", "max_issues_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_issues_repo_licenses": ["MIT"], "max_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.cpp", "max_forks_repo_name": "foxostro/CheeseTesseract", "max_forks_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_forks_repo_licenses": ["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.5247524752, "max_line_length": 91, "alphanum_fraction": 0.6623071764, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5192251805710979}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\n\ntemplate <typename Matrix>\nvoid test(Matrix& A, const char* name)\n{\n    A.change_dim(5, 5); A= 0.0;\n    {\n\tmtl::mat::inserter<Matrix>   ins(A);\n\tins[0][0] << 7; ins[1][1] << 8; ins[1][3] << 2; ins[1][4] << 3;\n\tins[2][2] << 2; ins[3][3] << 4; ins[4][4] << 9;\n    }\n    \n    double xa[] = {1, 2, 3, 4, 5};\n    mtl::dense_vector<double> x(xa), b;\n    \n    b= A * x;\n    x= 0.0;\n    \n    // Check whether entries on the lower triangle are ignored for solving\n    Matrix U(A); // Copy of the upper triangular\n    {\n\tmtl::mat::inserter<Matrix>   ins(A);\n\tins[4][1] << 7; ins[3][2] << 6;\n    }\n\n    cout << name << \"\\nA = \\n\" << A << \"b = \" << b << \"\\n\";\n\n    invert_diagonal(A);\n    \n    x= upper_trisolve(A, b, mtl::tag::inverse_diagonal());\n    cout << \"x = upper_trisolve(A, b) ==\" << x << \"\\n\\n\";\n    MTL_THROW_IF(std::abs(x[2] - 3.0) > 0.0001, mtl::runtime_error(\"Wrong result in upper_trisolve!\"));\n\n    Matrix B(trans(A)); // Diagonal already inverted\n\n    x= xa;\n    \n    b= trans(U) * x;    // Take transposed of original matrix\n    x= 0.0;\n    \n    cout << \"B = \\n\" << B << \"b = \" << b << \"\\n\";\n\t\n    // invert_diagonal(B);\n\n    x= lower_trisolve(B, b, mtl::tag::inverse_diagonal());\n    cout << \"x = lower_trisolve(B, b) ==\" << x << \"\\n\\n\";\n    MTL_THROW_IF(std::abs(x[2] - 3.0) > 0.0001, mtl::runtime_error(\"Wrong result in lower_trisolve!\"));\n\n\n}\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    dense2D<double>                                      dr;\n    dense2D<double, mat::parameters<col_major> >      dc;\n    morton_dense<double, recursion::morton_z_mask>       mzd;\n    morton_dense<double, recursion::doppled_2_row_mask>  d2r;\n    compressed2D<double>                                 cr;\n    compressed2D<double, mat::parameters<col_major> > cc;\n\n    test(dr, \"Dense row major\");\n    test(dc, \"Dense column major\");\n    test(mzd, \"Morton Z-order\");\n    test(d2r, \"Hybrid 2 row-major\");\n    test(cr, \"Compressed row major\");\n    test(cc, \"Compressed column major\");\n\n    return 0;\n}\n", "meta": {"hexsha": "84a80eeee9880d5bd1f507156381da1870492eb2", "size": 2529, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/inverse_trisolve_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_trisolve_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_trisolve_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": 28.4157303371, "max_line_length": 103, "alphanum_fraction": 0.5741399763, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5192218543510247}}
{"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 * UdU' Factorisation of Covariance Filter.\n *\n * For efficiency UD_scheme requires to know the maximum q_size of the predict_model\n * ISSUES:\n *  observe functions: returned rcond is the minimum of each sequential update, an overall conditioning would be better\n */\n#include \"UDFlt.hpp\"\n#include \"matSup.hpp\"\n#include <boost/limits.hpp>\n\n/* Filter namespace */\nnamespace Bayesian_filter\n{\n\tusing namespace Bayesian_filter_matrix;\n\n\nUD_scheme::\nUD_scheme (std::size_t x_size, std::size_t q_maxsize, std::size_t z_initialsize) :\n\t\tKalman_state_filter(x_size),\n\t\tq_max(q_maxsize),\n\t\tUD(x_size,x_size+q_max),\n\t\ts(Empty), Sd(Empty),\n\t\td(x_size+q_max), dv(x_size+q_max), v(x_size+q_max),\n\t\ta(x_size), b(x_size),\n\t\th1(x_size), w(x_size),\n\t\tznorm(Empty),\n\t\tzpdecol(Empty),\n\t\tGz(Empty),\n\t\tGIHx(Empty)\n/* Initialise filter and set the size of things we know about\n */\n{\n\tlast_z_size = 0;\t// Matrices conform to z_initialsize, they are left Empty if z_initialsize==0\n\tobserve_size (z_initialsize);\n}\n\nUD_scheme&\n UD_scheme::operator= (const UD_scheme& a)\n/* Optimise copy assignment to only copy filter state\n * Precond: matrix size conformance\n */\n{\n\tKalman_state_filter::operator=(a);\n\tq_max = a.q_max;\n\tUD = a.UD;\n\treturn *this;\n}\n\n\nvoid\n UD_scheme::init ()\n/* Initialise from a state and state coveriance\n * Computes UD factor from initial covaiance\n * Predcond:\n *  X\n * Postcond:\n *  X\n *  UD=X, d is PSD\n */\n{\n\t\t\t\t\t// Factorise X into left partition of UD\n\tstd::size_t x_size = UD.size1();\n\tUD.sub_matrix(0,x_size, 0,x_size) .assign (X);\n\tFloat rcond = UdUfactor (UD, x_size);\n\trclimit.check_PSD(rcond, \"Initial X not PSD\");\n}\n\n\nvoid\n UD_scheme::update ()\n/* Defactor UD back into X\n * Precond:\n *  UD\n * Postcond:\n *  X=UD  PSD iff UD is PSD\n */\n{\n\tUdUrecompose (X, UD);\n}\n\n\nUD_scheme::Float\n UD_scheme::predict (Linrz_predict_model& f)\n/* Prediction using a diagonalised noise q, and its coupling G\n *  q can have order less then x and a matching G so GqG' has order of x\n * Precond:\n *\tUD\n * Postcond:\n *  UD is PSD\n */\n{\n\tx = f.f(x);\t\t\t// Extended Kalman state predict is f(x) directly\n\n\t\t\t\t\t\t// Predict UD from model\n\tFloat rcond = predictGq (f.Fx, f.G, f.q);\n\trclimit.check_PSD(rcond, \"X not PSD in predict\");\n\treturn rcond;\n}\n\n\nUD_scheme::Float\n UD_scheme::predictGq (const Matrix& Fx, const Matrix& G, const FM::Vec& q)\n/* MWG-S prediction from Bierman  p.132\n *  q can have order less then x and a matching G so GqG' has order of x\n * Precond:\n *  UD\n * Postcond:\n *  UD\n *\n * Return:\n *\t\treciprocal condition number, -1 if negative, 0 if semi-definite (including zero)\n */\n{\n\tstd::size_t i,j,k;\n\tconst std::size_t n = x.size();\n\tconst std::size_t Nq = q.size();\n\tconst std::size_t N = n+Nq;\n\tFloat e;\n\t\t\t\t\t// Check preallocated space for q size\n\tif (Nq > q_max)\n\t\terror (Logic_exception(\"Predict model q larger than preallocated space\"));\n\n\tif (n > 0)\t\t// Simplify reverse loop termination\n\t{\n\t\t\t\t\t\t// Augment d with q, UD with G\n\t\tfor (i = 0; i < Nq; ++i)\t\t// 0..Nq-1\n\t\t{\n\t\t\td[i+n] = q[i];\n\t\t}\n\t\tfor (j = 0; j < n; ++j)\t\t// 0..n-1\n\t\t{\n\t\t\tMatrix::Row UDj(UD,j);\n\t\t\tMatrix::const_Row  Gj(G,j);\n\t\t\tfor (i = 0; i < Nq; ++i)\t\t// 0..Nq-1\n\t\t\t\tUDj[i+n] = Gj[i];\n\t\t}\n\n\t\t\t\t\t\t// U=Fx*U and diagonals retrieved\n\t\tfor (j = n-1; j > 0; --j)\t\t// n-1..1\n\t\t{\n\t\t\t\t\t\t// Prepare d(0)..d(j) as temporary\n\t\t\tfor (i = 0; i <= j; ++i)\t// 0..j\n\t\t\t\td[i] = Float(UD(i,j));\t// ISSUE mixed type proxy assignment\n\n\t\t\t\t\t\t// Lower triangle of UD is implicitly empty\n\t\t\tfor (i = 0; i < n; ++i) \t// 0..n-1\n\t\t\t{\n\t\t\t\tMatrix::Row UDi(UD,i);\n\t\t\t\tMatrix::const_Row Fxi(Fx,i);\n\t\t\t\tUDi[j] = Fxi[j];\n\t\t\t\tfor (k = 0; k < j; ++k)\t// 0..j-1\n\t\t\t\t\tUDi[j] += Fxi[k] * d[k];\n\t\t\t}\n\t\t}\n\t\td[0] = Float(UD(0,0));\t// ISSUE mixed type proxy assignment\n\n\t\t\t\t\t\t//  Complete U = Fx*U\n\t\tfor (j = 0; j < n; ++j)\t\t\t// 0..n-1\n\t\t{\n\t\t\tUD(j,0) = Fx(j,0);\n\t\t}\n\n\t\t\t\t\t\t// The MWG-S algorithm on UD transpose\n\t\tj = n-1;\n\t\tdo {\t\t\t\t\t\t\t// n-1..0\n\t\t\tMatrix::Row UDj(UD,j);\n\t\t\te = 0;\n\t\t\tfor (k = 0; k < N; ++k)\t\t// 0..N-1\n\t\t\t{\n\t\t\t\tv[k] = Float(UDj[k]);\t// ISSUE mixed type proxy assignment\n\t\t\t\tdv[k] = d[k] * v[k];\n\t\t\t\te += v[k] * dv[k];\n\t\t\t}\n\t\t\t// Check diagonal element\n\t\t\tif (e > 0)\n\t\t\t{\n\t\t\t\t// Positive definite\n\t\t\t\tUDj[j] = e;\n\n\t\t\t\tFloat diaginv = 1 / e;\n\t\t\t\tfor (k = 0; k < j; ++k)\t// 0..j-1\n\t\t\t\t{\n\t\t\t\t\tMatrix::Row UDk(UD,k);\n\t\t\t\t\te = 0;\n\t\t\t\t\tfor (i = 0; i < N; ++i)\t// 0..N-1\n\t\t\t\t\t\te += UDk[i] * dv[i];\n\t\t\t\t\te *= diaginv;\n\t\t\t\t\tUDj[k] = e;\n\n\t\t\t\t\tfor (i = 0; i < N; ++i)\t// 0..N-1\n\t\t\t\t\t\tUDk[i] -= e * v[i];\n\t\t\t\t}\n\t\t\t}//PD\n\t\t\telse if (e == 0)\n\t\t\t{\n\t\t\t\t// Possibly semi-definite, check not negative\n\t\t\t\tUDj[j] = e;\n\n\t\t\t\t// 1 / e is infinite\n\t\t\t\tfor (k = 0; k < j; ++k)\t// 0..j-1\n\t\t\t\t{\n\t\t\t\t\tMatrix::Row UDk(UD,k);\n\t\t\t\t\tfor (i = 0; i < N; ++i)\t// 0..N-1\n\t\t\t\t\t{\n\t\t\t\t\t\te = UDk[i] * dv[i];\n\t\t\t\t\t\tif (e != 0)\n\t\t\t\t\t\t\tgoto Negative;\n\t\t\t\t\t}\n\t\t\t\t\t// UD(j,k) unaffected\n\t\t\t\t}\n\t\t\t}//PD\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Negative\n\t\t\t\tgoto Negative;\n\t\t\t}\n\t\t} while (j-- > 0); //MWG-S loop\n\n\t\t\t\t\t\t// Transpose and Zero lower triangle\n\t\tfor (j = 1; j < n; ++j)\t\t\t// 0..n-1\n\t\t{\n\t\t\tMatrix::Row UDj(UD,j);\n\t\t\tfor (i = 0; i < j; ++i)\n\t\t\t{\n\t\t\t\tUD(i,j) = UDj[i];\n\t\t\t\tUDj[i] = 0;\t\t\t// Zeroing unnecessary as lower only used as a scratch\n\t\t\t}\n\t\t}\n\n\t}\n\n\t// Estimate the reciprocal condition number from upper triangular part\n\treturn UdUrcond(UD,n);\n\nNegative:\n\treturn -1;\n}\n\n\nvoid\n UD_scheme::observe_size (std::size_t z_size)\n/* Optimised dynamic observation sizing\n */\n{\n\tif (z_size != last_z_size) {\n\t\tlast_z_size = z_size;\n\n\t\ts.resize(z_size, false);\n\t\tSd.resize(z_size, false);\n\t\tznorm.resize(z_size, false);\n\t}\n}\n\nBayes_base::Float\n UD_scheme::observe (Linrz_uncorrelated_observe_model& h, const Vec& z)\n/* Standard linrz observe\n *  Uncorrelated observations are applied sequentially in the order they appear in z\n *  The sequential observation updates state x\n *  Therefore the model of each observation needs to be computed sequentially. Generally this\n *  is inefficient and observe (UD_sequential_observe_model&) should be used instead\n * Precond:\n *\t UD\n *\t Zv is PSD\n * Postcond:\n *  UD is PSD\n * Return: Minimum rcond of all sequential observe\n */\n{\n\tconst std::size_t z_size = z.size();\n\tFloat s, S;\t\t\t// Innovation and covariance\n\n\t\t\t\t\t\t\t\t// Dynamic sizing\n\tobserve_size (z_size);\n\t\t\t\t\t\t\t\t// Apply observations sequentially as they are decorrelated\n\tFloat rcondmin = std::numeric_limits<Float>::max();\n\tfor (std::size_t o = 0; o < z_size; ++o)\n\t{\n\t\t\t\t\t\t\t\t// Observation model, extracted for a single z element\n\t\tconst Vec& zp = h.h(x);\n\t\th.normalise(znorm = z, zp);\n\t\tnoalias(h1) = row(h.Hx, o);\n\t\t\t\t\t\t\t\t// Check Z precondition\n\t\tif (h.Zv[o] < 0)\n\t\t\terror (Numeric_exception(\"Zv not PSD in observe\"));\n\t\t\t\t\t\t\t\t// Update UD and extract gain\n\t\tFloat rcond = observeUD (w, S, h1, h.Zv[o]);\n\t\trclimit.check_PSD(rcond, \"S not PD in observe\");\t// -1 implies S singular\n\t\tif (rcond < rcondmin) rcondmin = rcond;\n\t\t\t\t\t\t\t\t// State update using normalised non-linear innovation\n\t\ts = znorm[o] - zp[o];\n\t\tnoalias(x) += w * s;\n\t\t\t\t\t\t\t\t// Copy s and Sd\n\t\tUD_scheme::s[o] = s;\n\t\tUD_scheme::Sd[o] = S;\n\t}\n\treturn rcondmin;\n}\n\nBayes_base::Float\n UD_scheme::observe (Linrz_correlated_observe_model& /*h*/, const Vec& /*z*/)\n/* No solution for Correlated noise and Linearised model\n */\n{\n\terror (Logic_exception(\"observe no Linrz_correlated_observe_model solution\"));\n\treturn 0;\t// never reached\n}\n\nBayes_base::Float\n UD_scheme::observe (Linear_correlated_observe_model& h, const Vec& z)\n/* Special Linear Hx observe for correlated Z\n *  Z must be PD and will be decorrelated\n * Applies observations sequentially in the order they appear in z\n * Creates temporary Vec and Matrix to decorrelate z,Z\n * Precondition:\n *  UD\n *  Z is PSD\n * Postcondition:\n *  UD is PSD\n * Return: Minimum rcond of all sequential observe\n */\n{\n\tstd::size_t i, j, k;\n\tconst std::size_t x_size = x.size();\n\tconst std::size_t z_size = z.size();\n\tFloat s, S;\t\t\t// Innovation and covariance\n\n\t\t\t\t\t// Dynamic sizing\n\tobserve_size (z_size);\n\tif (z_size != zpdecol.size()) {\n\t\tzpdecol.resize(z_size, false);\n\t\tGz.resize(z_size,z_size, false);\n\t\tGIHx.resize(z_size, x_size, false);\n\t}\n\n\t\t\t\t\t// Factorise process noise as GzG'\n\t{\tFloat rcond = FM::UdUfactor (Gz, h.Z);\n\t\trclimit.check_PSD(rcond, \"Z not PSD in observe\");\n\t}\n\n\t\t\t\t\t\t\t\t// Observation prediction and normalised observation\n\tconst Vec& zp = h.h(x);\n\th.normalise(znorm = z, zp);\n\t\n\tif (z_size > 0)\n\t{\t\t\t\t\t\t\t// Solve G* GIHx = Hx for GIHx in-place\n\t\tGIHx = h.Hx;\n\t\tfor (j = 0; j < x_size; ++j)\n\t\t{\n\t\t\ti = z_size-1;\n\t\t\tdo {\n\t\t\t\tfor (k = i+1; k < z_size; ++k)\n\t\t\t\t{\n\t\t\t\t\tGIHx(i,j) -= Gz(i,k) * GIHx(k,j);\n\t\t\t\t}\n\t\t\t} while (i-- > 0);\n\t\t}\n\t\t\t\t\t\n\t\tzpdecol = zp;\t\t\t// Solve G zp~ = z, G z~ = z  for zp~,z~ in-place\n\t\ti = z_size-1;\n\t\tdo {\n\t\t\tfor (k = i+1; k < z_size; ++k)\n\t\t\t{\n\t\t\t\tznorm[i] -= Gz(i,k) * znorm[k];\n\t\t\t\tzpdecol[i] -= Gz(i,k) * zpdecol[k];\n\t\t\t}\n\t\t} while (i-- > 0);\n\t}//if (z_size>0)\n\n\t\t\t\t\t\t\t\t// Apply observations sequential as they are decorrelated\n\tFloat rcondmin = std::numeric_limits<Float>::max();\n\tfor (std::size_t o = 0; o < z_size; ++o)\n\t{\n\t\th1 = row(GIHx,o);\n\t\t\t\t\t\t\t\t// Update UD and extract gain\n\t\tFloat rcond = observeUD (w, S, h1, Gz(o,o));\n\t\trclimit.check_PSD(rcond, \"S not PD in observe\");\t// -1 implies S singular\n\t\tif (rcond < rcondmin) rcondmin = rcond;\n\t\t\t\t\t\t\t\t// State update using linear innovation\n\t\ts = znorm[o]-zpdecol[o];\n\t\tnoalias(x) += w * s;\n\t\t\t\t\t\t\t\t// Copy s and Sd\n\t\tUD_scheme::s[o] = s;\n\t\tUD_scheme::Sd[o] = S;\n\t}\n\treturn rcondmin;\n}\n\nBayes_base::Float\n UD_scheme::observe (UD_sequential_observe_model& h, const Vec& z)\n/* Special observe using observe_model_sequential for fast uncorrelated linrz operation\n * Uncorrelated observations are applied sequentially in the order they appear in z\n * The sequential observation updates state x. Therefore the model of\n * each observation needs to be computed sequentially\n * Precondition:\n *  UD\n *  Z is PSD\n * Postcondition:\n *  UD is PSD\n * Return: Minimum rcond of all sequential observe\n */\n{\n\tstd::size_t o;\n\tconst std::size_t z_size = z.size();\n\tFloat s, S;\t\t\t// Innovation and covariance\n\n\t\t\t\t\t\t\t\t// Dynamic sizing\n\tobserve_size (z_size);\n\t\t\t\t\t\t\t\t// Apply observations sequentially as they are decorrelated\n\tFloat rcondmin = std::numeric_limits<Float>::max();\n\tfor (o = 0; o < z_size; ++o)\n\t{\n\t\t\t\t\t\t\t\t// Observation prediction and model\n\t\tconst Vec& zp = h.ho(x, o);\n\t\th.normalise(znorm = z, zp);\n\t\t\t\t\t\t\t\t// Check Z precondition\n\t\tif (h.Zv[o] < 0)\n\t\t\terror (Numeric_exception(\"Zv not PSD in observe\"));\n\t\t\t\t\t\t\t\t// Update UD and extract gain\n\t\tFloat rcond = observeUD (w, S, h.Hx_o, h.Zv[o]);\n\t\trclimit.check_PSD(rcond, \"S not PD in observe\");\t// -1 implies S singular\n\t\tif (rcond < rcondmin) rcondmin = rcond;\n\t\t\t\t\t\t\t\t// State update using non-linear innovation\n\t\ts = znorm[o]-zp[o];\n\t\tnoalias(x) += w * s;\n\t\t\t\t\t\t\t\t// Copy s and Sd\n\t\tUD_scheme::s[o] = s;\n\t\tUD_scheme::Sd[o] = S;\n\t}\n\treturn rcondmin;\n}\n\n\nUD_scheme::Float\n UD_scheme::observeUD (FM::Vec& gain, Float & alpha, const Vec& h, const Float r)\n/** Linear UD factorisation update\n *  Bierman UdU' factorisation update. Bierman p.100\n * Input\n *  h observation coefficients\n *  r observation variance\n * Output\n *  gain  observation Kalman gain\n *  alpha observation innovation variance\n * Variables with physical significance\n *  gamma becomes covariance of innovation\n * Precondition:\n *  UD\n *  r is PSD (not checked)\n * Postcondition:\n *  UD (see return value)\n * Return:\n *  reciprocal condition number of UD, -1 if alpha singular (negative or zero)\n */\n{\n\tstd::size_t i,j,k;\n\tconst std::size_t n = UD.size1();\n\tFloat gamma, alpha_jm1, lamda;\n\t// a(n) is U'a\n\t// b(n) is Unweighted Kalman gain\n\n\t\t\t\t\t// Compute b = DU'h, a = U'h\n\ta = h;\n\tfor (j = n-1; j >= 1; --j)\t// n-1..1\n\t{\n\t\tfor (k = 0; k < j; ++k)\t// 0..j-1\n\t\t{\n\t\t\ta[j] += UD(k,j) * a[k];\n\t\t}\n\t\tb[j] = UD(j,j) * a[j];\n\t}\n\tb[0] = UD(0,0) * a[0];\n\n\t\t\t\t\t// Update UD(0,0), d(0) modification\n\talpha = r + b[0] * a[0];\n\tif (alpha <= 0) goto alphaNotPD;\n\tgamma = 1 / alpha;\n\tUD(0,0) *= r * gamma;\n\t\t\t\t\t// Update rest of UD and gain b\n\tfor (j = 1; j < n; ++j)\t\t// 1..n-1\n\t{\n\t\t\t\t\t// d modification\n\t\talpha_jm1 = alpha;\t// alpha at j-1\n\t\talpha += b[j] * a[j];\n\t\tlamda = -a[j] * gamma;\n\t\tif (alpha <= 0) goto alphaNotPD;\n\t\tgamma = 1 / alpha;\n\t\tUD(j,j) *= alpha_jm1 * gamma;\n\t\t\t\t\t// U modification\n\t\tfor (i = 0; i < j; ++i)\t\t// 0..j-1\n\t\t{\n\t\t\tFloat UD_jm1 = UD(i,j);\n\t\t\tUD(i,j) = UD_jm1 + lamda * b[i];\n\t\t\tb[i] += b[j] * UD_jm1;\n\t\t}\n\t}\n\t\t\t\t\t// Update gain from b\n\tnoalias(gain) = b * gamma;\n \t// Estimate the reciprocal condition number from upper triangular part\n\treturn UdUrcond(UD,n);\n\nalphaNotPD:\n\treturn -1;\n}\n\n}//namespace\n", "meta": {"hexsha": "6bab00890a6316728de97c07051d3c7beca4feb4", "size": 12718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BayesFilter/UDFlt.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": "BayesFilter/UDFlt.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": "BayesFilter/UDFlt.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": 24.7431906615, "max_line_length": 119, "alphanum_fraction": 0.6100802013, "num_tokens": 4360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5192218487902177}}
{"text": "// Copyright \u00a9 2016-2021 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#include <boost/math/special_functions/fpclassify.hpp> // isnan\n#include <boost/math/special_functions/log1p.hpp>\n#include <cmath>\n#include <vinecopulib/misc/tools_eigen.hpp>\n\nnamespace vinecopulib {\ninline GumbelBicop::GumbelBicop()\n{\n  family_ = BicopFamily::gumbel;\n  parameters_ = Eigen::VectorXd(1);\n  parameters_lower_bounds_ = Eigen::VectorXd(1);\n  parameters_upper_bounds_ = Eigen::VectorXd(1);\n  parameters_ << 1;\n  parameters_lower_bounds_ << 1;\n  parameters_upper_bounds_ << 50;\n}\n\ninline double\nGumbelBicop::generator(const double& u)\n{\n  return std::pow(std::log(1 / u), this->parameters_(0));\n}\n\ninline double\nGumbelBicop::generator_inv(const double& u)\n{\n  return std::exp(-std::pow(u, 1 / this->parameters_(0)));\n}\n\ninline double\nGumbelBicop::generator_derivative(const double& u)\n{\n  double theta = double(this->parameters_(0));\n  return std::pow(std::log(1 / u), theta - 1) * (-theta / u);\n}\n\n// inline double GumbelBicop::generator_derivative2(const double &u)\n//{\n//    double theta = double(this->parameters_(0));\n//    return (theta - 1 - std::log(u)) * std::pow(std::log(1 / u), theta - 2) *\n//           (theta / std::pow(u, 2));\n//}\n\ninline Eigen::VectorXd\nGumbelBicop::pdf_raw(const Eigen::MatrixXd& u)\n{\n  double theta = static_cast<double>(parameters_(0));\n  double thetha1 = 1.0 / theta;\n  auto f = [theta, thetha1](const double& u1, const double& u2) {\n    double t1 = std::pow(-std::log(u1), theta) + std::pow(-std::log(u2), theta);\n    double temp = -std::pow(t1, thetha1) + (2 * thetha1 - 2.0) * std::log(t1) +\n                  (theta - 1.0) * std::log(std::log(u1) * std::log(u2)) -\n                  std::log(u1 * u2) +\n                  boost::math::log1p((theta - 1.0) * std::pow(t1, -thetha1));\n    return std::exp(temp);\n  };\n  return tools_eigen::binaryExpr_or_nan(u, f);\n}\n\ninline Eigen::VectorXd\nGumbelBicop::hinv1_raw(const Eigen::MatrixXd& u)\n{\n  double theta = double(this->parameters_(0));\n  double u1, u2;\n  Eigen::VectorXd hinv = Eigen::VectorXd::Zero(u.rows());\n  for (int j = 0; j < u.rows(); ++j) {\n    u1 = u(j, 1);\n    u2 = u(j, 0);\n    if ((boost::math::isnan)(u1) | (boost::math::isnan)(u2)) {\n      hinv(j) = std::numeric_limits<double>::quiet_NaN();\n    } else {\n      hinv(j) = qcondgum(&u1, &u2, &theta);\n    }\n  }\n\n  return hinv;\n}\n\ninline Eigen::MatrixXd\nGumbelBicop::tau_to_parameters(const double& tau)\n{\n  auto par = Eigen::VectorXd::Constant(1, 1.0 / (1 - std::fabs(tau)));\n  return par.cwiseMax(parameters_lower_bounds_)\n    .cwiseMin(parameters_upper_bounds_);\n}\n\ninline double\nGumbelBicop::parameters_to_tau(const Eigen::MatrixXd& parameters)\n{\n  return (parameters(0) - 1) / parameters(0);\n}\n\ninline Eigen::VectorXd\nGumbelBicop::get_start_parameters(const double tau)\n{\n  Eigen::VectorXd par = tau_to_parameters(tau);\n  par = par.cwiseMax(parameters_lower_bounds_);\n  par = par.cwiseMin(parameters_upper_bounds_);\n  return par;\n}\n}\n\n// This is copy&paste from the VineCopula package\ninline double\nqcondgum(double* q, double* u, double* de)\n{\n  double a, p, z1, z2, con, de1, dif;\n  double mxdif;\n  int iter;\n\n  p = 1 - *q;\n  z1 = -log(*u);\n  con = log(1. - p) - z1 + (1. - *de) * log(z1);\n  de1 = *de - 1.;\n  a = pow(2. * pow(z1, *de), 1. / (*de));\n  mxdif = 1;\n  iter = 0;\n  dif = .1; // needed in case first step leads to NaN\n  while ((mxdif > 1.e-6) && (iter < 20)) {\n    double g = a + de1 * log(a) + con;\n    double gp = 1. + de1 / a;\n    if ((boost::math::isnan)(g) || (boost::math::isnan)(gp) ||\n        (boost::math::isnan)(g / gp)) {\n      // added for de>50\n      dif /= -2.;\n    } else {\n      dif = g / gp;\n    }\n    a -= dif;\n    iter++;\n    int it = 0;\n    while ((a <= z1) && (it < 20)) {\n      dif /= 2.;\n      a += dif;\n      ++it;\n    }\n    mxdif = fabs(dif);\n  }\n  z2 = pow(pow(a, *de) - pow(z1, *de), 1. / (*de));\n  return (exp(-z2));\n}\n", "meta": {"hexsha": "a0eaf9716027da02a5084056b91821c98a7e0ad8", "size": 4110, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "include/vinecopulib/bicop/implementation/gumbel.ipp", "max_stars_repo_name": "tvatter/vinecoplib", "max_stars_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-05-05T13:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T23:40:01.000Z", "max_issues_repo_path": "include/vinecopulib/bicop/implementation/gumbel.ipp", "max_issues_repo_name": "vinecopulib/vinecopulib", "max_issues_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 264.0, "max_issues_repo_issues_event_min_datetime": "2017-03-28T10:07:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T10:04:39.000Z", "max_forks_repo_path": "include/vinecopulib/bicop/implementation/gumbel.ipp", "max_forks_repo_name": "tvatter/vinecoplib", "max_forks_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-04-24T13:54:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T16:56:17.000Z", "avg_line_length": 27.7702702703, "max_line_length": 80, "alphanum_fraction": 0.6182481752, "num_tokens": 1361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6406358548398982, "lm_q1q2_score": 0.5192218484857197}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2020 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#ifndef GEOMETRY_TEST_EXPECTATION_LIMITS_HPP\n#define GEOMETRY_TEST_EXPECTATION_LIMITS_HPP\n\n#include <boost/geometry/util/math.hpp>\n\n#include <ostream>\n\n// Structure to manage expectations: there might be small variations in area, for different\n// types or options, which are all acceptable. With tolerance this is inconvenient.\n// The values are stored as doubles, but the member functions accept any type,\n// also for example Boost.MultiPrecision types\nstruct expectation_limits\n{\n    expectation_limits(double expectation)\n        : m_lower_limit(expectation)\n        , m_upper_limit(expectation)\n    {\n    }\n\n    expectation_limits(double lower_limit, double upper_limit)\n        : m_lower_limit(lower_limit)\n        , m_upper_limit(upper_limit)\n    {\n    }\n\n    double get() const { return m_lower_limit; }\n\n    bool is_zero() const { return m_lower_limit < 1.0e-8; }\n\n    bool has_two_limits() const { return m_lower_limit < m_upper_limit; }\n\n    template<typename T>\n    bool contains_logarithmic(const T& value, double tolerance) const\n    {\n      return abs(log(value) - std::log(m_lower_limit)) < tolerance;\n    }\n\n    template<typename T>\n    bool contains(const T& value, double percentage, bool logarithmic = false) const\n    {\n        if (m_upper_limit < 1.0e-8)\n        {\n            return value < 1.0e-8;\n        }\n        if (logarithmic)\n        {\n            return contains_logarithmic(value, percentage);\n        }\n\n        // Note the > and <= and percentages, this is to make it exactly equivalent to\n        // BOOST_CHECK_CLOSE(m_lower_limit, value, percentage) (if lower == upper)\n        // But for two limits and optional slivers, >= is needed (for 0.00)\n        double const fraction = percentage / 100.0;\n        double const lower_limit = m_lower_limit * (1.0 - fraction);\n        double const upper_limit = m_upper_limit * (1.0 + fraction);\n        return has_two_limits()\n                ? value >= lower_limit && value <= upper_limit\n                : value > lower_limit && value <= upper_limit;\n    }\n\n    expectation_limits operator+(const expectation_limits& a) const\n    {\n        return this->has_two_limits() || a.has_two_limits()\n                ? expectation_limits(this->m_lower_limit + a.m_lower_limit,\n                                     this->m_upper_limit + a.m_upper_limit)\n                : expectation_limits(this->m_lower_limit + a.m_lower_limit);\n    }\n\n    friend std::ostream &operator<<(std::ostream &os, const expectation_limits& lim)\n    {\n        if (lim.has_two_limits())\n        {\n            os << \"[\" << lim.m_lower_limit << \" .. \" << lim.m_upper_limit << \"]\";\n        }\n        else\n        {\n            os << lim.m_lower_limit;\n        }\n        return os;\n    }\n\nprivate :\n    double const m_lower_limit;\n    double const m_upper_limit;\n};\n\ninline expectation_limits optional_sliver(double upper_limit = 1.0e-4)\n{\n    return expectation_limits(0, upper_limit);\n}\n\n#endif // GEOMETRY_TEST_EXPECTATION_LIMITS_HPP\n", "meta": {"hexsha": "eda85d706bd944b2423ddb1234e84c3368a9b3cd", "size": 3289, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/expectation_limits.hpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-05-15T20:46:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T11:02:21.000Z", "max_issues_repo_path": "test/expectation_limits.hpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "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": "test/expectation_limits.hpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "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": 32.5643564356, "max_line_length": 91, "alphanum_fraction": 0.653694132, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5192218484857196}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// kernel::example::scalar_nw.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/typeof/typeof.hpp>\n\n#include <boost/fusion/sequence/intrinsic/at_key.hpp>\n#include <boost/fusion/include/at_key.hpp>\n#include <boost/fusion/container/map.hpp>\n#include <boost/fusion/include/map.hpp>\n#include <boost/fusion/include/map_fwd.hpp>\n\n#include <boost/statistics/detail/fusion/functor/at_key.hpp>\n\n#include <boost/statistics/detail/kernel/kernels/scalar/gaussian.hpp>\n#include <boost/statistics/detail/kernel/estimation/meta_nw_visitor_unary.hpp>\n#include <boost/statistics/detail/kernel/estimation/estimator.hpp>\n#include <libs/statistics/detail/kernel/example/scalar_nw.h>\n\nvoid example_scalar_nw(std::ostream& out){\n\n    out << \"-> example_scalar_nw : \";\n    using namespace boost;\n\n    namespace kernel = boost::statistics::detail::kernel;\n\n    // This example shows how to compute a Nadaraya-Watson estimate of E[y|x]. \n    // The type used for each data-unit, here, is a fusion map whose x and y\n    // components are accessed using keys\n    \n    // Types\n    typedef double                                          val_;\n    typedef std::vector<val_>                               vals_;\n    typedef mpl::int_<0>                                    key_x_;\n    typedef mpl::int_<1>                                    key_y_;\n    typedef fusion::pair<key_x_,val_>                       x_;\n    typedef fusion::pair<key_y_,val_>                       y_;\n    typedef statistics::detail::fusion::functor::at_key<key_x_> at_key_x_;\n    typedef statistics::detail::fusion::functor::at_key<key_y_> at_key_y_;\n    typedef fusion::map<x_,y_>                              data_unit_;\n    typedef std::vector<data_unit_>                          dataset_;\n    // The rationale for data_range_ is it's cheap to copy\n    typedef sub_range<dataset_>                             data_range_;\n        \n    typedef mt19937                                         urng_;\n    typedef normal_distribution<val_>                       norm_;\n    typedef variate_generator<urng_&,norm_>                 gen_;\n    typedef kernel::scalar::gaussian_kernel<val_>                  gauss_k_;\n    typedef kernel::meta_nw_visitor_unary<\n        at_key_x_,\n        at_key_y_\n    > meta_nw_visitor_u_;\n    typedef meta_nw_visitor_u_::apply<\n        gauss_k_,\n        val_\n    >::type  nw_visitor_u_;\n    typedef nw_visitor_u_::nw_visitor_type              nw_visitor_;\n    typedef nw_visitor_u_::rp_visitor_type              rp_visitor_;\n    \n    // Constants\n    const val_ bandwidth = 0.5;\n    const val_ eps = math::tools::epsilon<val_>();\n    const unsigned n = 10;\n    \n    // Initialization\n    vals_ vec_rp; vec_rp.reserve(n);\n    vals_ vec_nw; vec_nw.reserve(n);\n    dataset_ dataset;\n    dataset.reserve(n);\n    {\n        urng_ urng;\n        norm_ norm;\n        gen_ gen(urng,norm);\n        val_ one = static_cast<val_>(1);\n        for(unsigned i = 0; i<n; i++){\n            dataset.push_back(\n                data_unit_(\n                    fusion::make_pair<key_x_>(gen()),\n                    fusion::make_pair<key_y_>(one)\n                )\n            );\n        }\n    }\n\n    // Computes nw = E[y|x] for each x in the dataset. The density (rp) is \n    // obtained as a by-product. Here, y = 1, so we should have \n    // rp = nw (un-normalized).\n    BOOST_FOREACH(data_unit_& u,dataset){\n        nw_visitor_ nw_visitor = std::for_each(\n            boost::begin(dataset),\n            boost::end(dataset),\n            nw_visitor_u_(\n                bandwidth,\n                fusion::at_key<key_x_>(u)\n            )\n        );\n        val_ u_nw = nw_visitor.unnormalized_estimate();\n        vec_nw.push_back(u_nw);\n        rp_visitor_ rp_visitor = nw_visitor.rp_visitor();\n        val_ rp = rp_visitor.estimate();\n        BOOST_ASSERT(fabs(rp-u_nw)<eps);\n    }\n    \n    // Same as above using estimator\n    \n    typedef kernel::estimator<\n        data_range_,\n        meta_nw_visitor_u_::apply,\n        gauss_k_\n    > estimator_;\n    estimator_ estimator(bandwidth);\n    estimator.train(\n        data_range_(dataset)\n    ); // * step 1 *\n\n    \n    BOOST_FOREACH(data_unit_& u,dataset){\n        // -> these steps are independent of step2, they're just a test\n        val_ x = fusion::at_key<key_x_>(u);\n        BOOST_AUTO( nw_v , estimator.visit(x) );\n        val_ u_nw = nw_v.unnormalized_estimate();\n        BOOST_AUTO( rp_v , nw_v.rp_visitor() );\n        val_ rp = rp_v.estimate();\n        BOOST_ASSERT(fabs(rp-u_nw)<eps);\n        // <-\n        \n        estimator.predict(x); // * step 2 *\n    \n    } \n    \n    out << \"<-\" << std::endl;\n}\n", "meta": {"hexsha": "8540444b89d44754db166fb666f073e3a33b0309", "size": 5472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/libs/statistics/detail/kernel/example/scalar_nw.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_nw.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_nw.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": 37.4794520548, "max_line_length": 80, "alphanum_fraction": 0.5643274854, "num_tokens": 1224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5192218429249128}}
{"text": "#define ARMA_DONT_USE_WRAPPER\n\n#include <armadillo>\n\n#include \"../include/calc_asymptotic_variance.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\n//' Calculate the asymptotic variance for the predicted y values\n//' \n//' @param Sigma_ll Sigma_ll matrix for the whole genome\n//' @param Sigma_ls Sigma_ls matrix for the whole genome\n//' @param Sigma_ss Sigma_ss matrix for the whole genome\n//' @param Sigma_ss_blockwise a one-dimensional field containing blockwise Sigma_ss matrices\n//' @param sigma2_s estimated value of sigma^2_s\n//' @param n sample size for observed data (not the reference panel)\n//' @param Xl_test genotypes matrix for large effect SNPs for test subjects\n//' @param Xs_test genotypes matrix for small effect SNPs for test subjects\n//' @return variance of predicted y values\n\narma::mat calc_asymptotic_variance(const arma::mat& Sigma_ll, \n                                   const arma::mat& Sigma_ls, \n                                   const arma::mat& Sigma_ss,\n                                   const arma::field <arma::mat >& Sigma_ss_blockwise,\n                                   double sigma2_s, \n                                   unsigned int n,\n                                   const arma::mat& Xl_test, \n                                   const arma::mat& Xs_test){\n  arma::mat Ainv = calc_A_inverse(Sigma_ss_blockwise, sigma2_s, n);\n  arma::mat var_bl = calc_var_betal(Sigma_ll, \n                                    Sigma_ls, \n                                    Sigma_ss, \n                                    Ainv, \n                                    n);\n  arma::mat var_bs = calc_var_betas(Sigma_ss, \n                                    Sigma_ls,\n                                    Ainv,\n                                    sigma2_s,\n                                    n,\n                                    var_bl);\n  arma::mat result = Xl_test * var_bl * arma::trans(Xl_test) + Xs_test * var_bs * arma::trans(Xs_test);\n  return(result);\n}\n\n//' Calculate A inverse matrix\n//' \n//' @details (sigma^{-2}n^{-1} I_ms + Sigma_ss) = A. Here, we use the block diagonal structure\n//' @param field a one-dimensional armadillo field for the entire genome. Each entry corresponds to a single LD block\n//' @param sigma2_s estimate of sigma^2_s\n//' @param n sample size\n//' @return A inverse matrix\n\narma::mat calc_A_inverse(const arma::field <arma::mat >& field, \n                         double sigma2_s, \n                         unsigned int n)  {\n  unsigned int n_blocks = field.n_elem;\n  arma::field <arma::mat> inv_field(n_blocks);\n  for( unsigned int i = 0; i < n_blocks; i++) {\n    //make the diagonal matrix \n    unsigned int m_s = field(i).n_rows;\n    inv_field(i) = arma::inv_sympd(arma::eye(m_s, m_s) / (n * sigma2_s) + field(i));\n  }\n  arma::mat result = BlockDiag(inv_field);\n  return result;\n}\n\n\n\n\n\n//' Calculate variance of coefficient estimator for large effects\n//' \n//' @param Sigma_ll Sigma_ll constructed for one LD block\n//' @param Sigma_ls Sigma_ls constructed for one LD block\n//' @param Sigma_ss Sigma_ss constructed for one LD block\n//' @param A_inverse inverse of (sigma^{-2}n^{-1} I_ms + Sigma_ss)\n//' @param n sample size\n//' @return covariance matrix\n\narma::mat calc_var_betal(const arma::mat& Sigma_ll, \n                         const arma::mat& Sigma_ls, \n                         const arma::mat& Sigma_ss,\n                         const arma::mat& A_inverse,\n                         unsigned int n){\n  //calculate second matrix\n  arma::mat big = Sigma_ll - Sigma_ls * A_inverse * arma::trans(Sigma_ls);\n  //invert and divide by n\n  arma::mat result = arma::inv_sympd(big) / n;\n  return (result);\n}\n\n//' Calculate variance of coefficient estimator for small effects\n//' \n//' @param Sigma_ss Sigma_ss matrix \n//' @param Sigma_ls Sigma_ls matrix \n//' @param A_inverse A inverse matrix \n//' @param sigma2_s estimated value of sigma^2_s\n//' @param n sample size\n//' @param var_bl variance of beta hat l\n//' @return covariance matrix\n  \n  arma::mat calc_var_betas(const arma::mat& Sigma_ss, \n                           const arma::mat& Sigma_ls,\n                           const arma::mat& A_inverse,\n                           double sigma2_s,\n                           unsigned int n,\n                           const arma::mat& var_bl){\n  arma::mat small = arma::trans(Sigma_ls) - Sigma_ss * A_inverse * arma::trans(Sigma_ls);\n  arma::mat term2 = small * var_bl * arma::trans(small);\n  arma::mat term1 = Sigma_ss - Sigma_ss * A_inverse * Sigma_ss;\n  arma::mat result = sigma2_s * sigma2_s * n * (term1 + term2);\n  return (result);\n}\n\n\n//' Construct a block diagonal matrix from a collection of matrices\n//' \n//' @param x a field of matrices, possibly of different sizes. Some matrices may have no rows and no columns\n//' @return a block diagonal matrix\n//' @reference https://stackoverflow.com/questions/29198893/block-diagonal-matrix-armadillo\n\narma::mat BlockDiag( const arma::field<arma::mat>& x ) {\n  \n  unsigned int len = x.n_elem;\n  int drow = 0;\n  int dcol = 0;\n  arma::ivec rvec(len);\n  arma::ivec cvec(len);\n  //get dimensions of each matrix in the field\n  for(unsigned int i = 0; i < len; i++) {\n    rvec(i) = x(i).n_rows ; \n    cvec(i) = x(i).n_cols ; \n    drow += rvec(i);\n    dcol += cvec(i);\n  }\n  //initialize matrix to be returned\n  arma::mat X(drow, dcol, fill::zeros);\n  int idx_row = 0;\n  int idx_col = 0;\n  // place matrices at correct places\n  for(unsigned int i=0; i < len; i++) {\n    if (rvec(i) > 0 && cvec(i) > 0){\n      X.submat(idx_row, \n               idx_col, \n               idx_row + rvec(i) - 1, \n               idx_col + cvec(i) - 1) = x(i) ;\n      idx_row = idx_row + rvec(i) ;\n      idx_col = idx_col + cvec(i);\n    }\n  }\n  return(X);\n}\n\n\n//' Construct a n by p matrix from field containing matrices with n rows, but possibly fewer columns.\n//' \n//' @param x a field of matrices, possibly of different sizes, but all with the same number of rows. \n//' @return a matrix\n\narma::mat ConcatenateColumns( const arma::field<arma::mat>& x ) {\n  \n  unsigned int len = x.n_elem;\n  //unsigned int nrow = x(1).n_rows;//problem!\n  int dcol = 0;\n  \n  arma::ivec cvec(len);\n  arma::ivec rvec(len);\n  //get number of columns of each matrix in the field\n  for(unsigned int i = 0; i < len; i++) {\n    cvec(i) = x(i).n_cols ; \n    rvec(i) = x(i).n_rows;\n    dcol += cvec(i);\n  }\n  unsigned int nrow = max(rvec);\n  //initialize matrix to be returned\n  arma::mat X(nrow, dcol, fill::zeros);\n  cout << \"number of rows: \" << nrow << endl; \n  cout << \"number of columns: \" << dcol << endl; \n  \n  int idx_col = 0;\n  // place matrices at correct places\n  for(unsigned int i=0; i < len; i++) {\n    if (cvec(i) > 0){\n      X.submat(0, \n               idx_col, \n               nrow - 1, \n               idx_col + cvec(i) - 1) = x(i) ;\n      idx_col = idx_col + cvec(i);\n    }\n  }\n  return(X);\n}\n\n\n//' Assemble one set of five matrices for one chromosome\n//' \n//' @details Input is a two-dimensional arma::field, say from one chromosome, where each cell contains an arma::mat\n//'     Specifically, it is a k by 5 arma::field, where k is the number of blocks on the chromosome of interest.\n//' @param field a two-dimensional arma::field. See details.\n//' @return a one-dimensional field containing exactly five arma::mat matrices: Sigma_ss, Sigma_sl, Sigma_ll, geno_s, geno_l    \n\narma::field <arma::mat> assembleMatrices(const arma::field < arma::mat>& field){\n  arma::field <arma::mat> result(5);\n  cout << \"field has this number of rows: \" << field.n_rows << endl; \n  result(0) = BlockDiag(field.col(0));\n  cout << \"result(0) has this dimension: \" << result(0).n_rows << \" rows & \" << result(0).n_cols << \" columns\" << endl; \n  result(1) = BlockDiag(field.col(1));\n  cout << \"result(1) has this dimension: \" << result(1).n_rows << \" rows & \" << result(1).n_cols << \" columns\" << endl; \n  result(2) = BlockDiag(field.col(2));\n  cout << \"result(2) has this dimension: \" << result(2).n_rows << \" rows & \" << result(2).n_cols << \" columns\" << endl; \n  result(3) = ConcatenateColumns(field.col(3));\n  cout << \"result(3) has this dimension: \" << result(3).n_rows << \" rows & \" << result(3).n_cols << \" columns\" << endl; \n  result(4) = ConcatenateColumns(field.col(4));\n  return result;\n} \n", "meta": {"hexsha": "27d21b9ebab2e4200f8add416ff40cecc0caa934", "size": 8253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/calc_asymptotic_variance.cpp", "max_stars_repo_name": "fboehm/DBSLMMread", "max_stars_repo_head_hexsha": "23626971f492228ba11e08d3b6b848ffbf942dc3", "max_stars_repo_licenses": ["MIT"], "max_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_asymptotic_variance.cpp", "max_issues_repo_name": "fboehm/DBSLMMread", "max_issues_repo_head_hexsha": "23626971f492228ba11e08d3b6b848ffbf942dc3", "max_issues_repo_licenses": ["MIT"], "max_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_asymptotic_variance.cpp", "max_forks_repo_name": "fboehm/DBSLMMread", "max_forks_repo_head_hexsha": "23626971f492228ba11e08d3b6b848ffbf942dc3", "max_forks_repo_licenses": ["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.0322580645, "max_line_length": 128, "alphanum_fraction": 0.5973585363, "num_tokens": 2162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5192218373641058}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n\n#include <scitbx/math/basic_statistics.h>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n\nnamespace scitbx { namespace math { namespace {\n\n  struct basic_statistics_wrappers\n  {\n    typedef basic_statistics<> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"basic_statistics\", no_init)\n        .def(init<af::const_ref<double> const&>((arg(\"values\"))))\n        .def_readonly(\"n\", &w_t::n)\n        .def_readonly(\"min\", &w_t::min)\n        .def_readonly(\"max\", &w_t::max)\n        .def_readonly(\"max_absolute\", &w_t::max_absolute)\n        .def_readonly(\"sum\", &w_t::sum)\n        .def_readonly(\"mean\", &w_t::mean)\n        .def_readonly(\"mean_absolute_deviation_from_mean\",\n          &w_t::mean_absolute_deviation_from_mean)\n        .def_readonly(\"biased_variance\", &w_t::biased_variance)\n        .def_readonly(\"biased_standard_deviation\",\n          &w_t::biased_standard_deviation)\n        .def_readonly(\"bias_corrected_variance\", &w_t::bias_corrected_variance)\n        .def_readonly(\"bias_corrected_standard_deviation\",\n          &w_t::bias_corrected_standard_deviation)\n        .def_readonly(\"skew\", &w_t::skew)\n        .def_readonly(\"kurtosis\", &w_t::kurtosis)\n        .def_readonly(\"kurtosis_excess\", &w_t::kurtosis_excess)\n      ;\n    }\n  };\n\n} // namespace <anonymous>\n\nnamespace boost_python {\n\n  void wrap_basic_statistics()\n  {\n    basic_statistics_wrappers::wrap();\n  }\n\n}}} // namespace scitbx::math::boost_python\n", "meta": {"hexsha": "c699d1573d4a9c4657dfafa5ccda4e63b3640fae", "size": 1541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/math/boost_python/basic_statistics.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/math/boost_python/basic_statistics.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/math/boost_python/basic_statistics.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 30.82, "max_line_length": 79, "alphanum_fraction": 0.6696950032, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5192218314988006}}
{"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//[expand\n//` Shows the usage of expand\n\n#include <iostream>\n#include <list>\n\n#include <boost/geometry.hpp>\n\nint main()\n{\n    typedef boost::geometry::model::d2::point_xy<short int> point_type;\n    typedef boost::geometry::model::box<point_type> box_type;\n\n    using boost::geometry::expand;\n\n    box_type box = boost::geometry::make_inverse<box_type>(); /*< expand is usually preceded by a call to assign_inverse or make_inverse  >*/\n\n    expand(box, point_type(0, 0));\n    expand(box, point_type(1, 2));\n    expand(box, point_type(5, 4));\n    expand(box, boost::geometry::make<box_type>(3, 3, 5, 5));\n\n    std::cout << boost::geometry::dsv(box) << std::endl;\n\n    return 0;\n}\n\n//]\n\n//[expand_output\n/*`\nOutput:\n[pre\n((0, 0), (5, 5))\n]\n*/\n//]\n", "meta": {"hexsha": "d2cb3fc4db645c3655a9c28bfbb0661907783127", "size": 1075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/expand.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/expand.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/expand.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": 22.8723404255, "max_line_length": 141, "alphanum_fraction": 0.6762790698, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5192001688998448}}
{"text": "\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.gray\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Copyright Christopher Kormanyos 2015 - 2016.\r\n// Copyright Paul A. Bristow 2015.\r\n\r\n// This file is written to be included from a Quickbook .qbk document.\r\n// It can be compiled by the C++ compiler, and run. Any output can\r\n// also be added here as comment or included or pasted in elsewhere.\r\n// Caution: this file contains Quickbook markup as well as code\r\n// and comments: don't change any of the special comment markups!\r\n\r\n// This file also includes Doxygen-style documentation about the function of the code.\r\n// See http://www.doxygen.org for details.\r\n\r\n//! \\file\r\n\r\n//! \\brief Example program showing fixed-point text-based Mandelbrot calculation with high resolution.\r\n\r\n// Below are snippets of code that are included into Quickbook file fixed_point.qbk.\r\n\r\n#include <algorithm>\r\n#include <ctime>\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <iterator>\r\n#include <numeric>\r\n#include <vector>\r\n\r\n#include <boost/cstdint.hpp>\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/gil/extension/io/jpeg_io.hpp>\r\n#include <boost/gil/image.hpp>\r\n#include <boost/gil/typedefs.hpp>\r\n\r\n#define MANDELBROT_01_AQUA_FULL\r\n//#define MANDELBROT_02_YELLOW_TOP\r\n//#define MANDELBROT_03_FUSCHIA_SWIRL\r\n//#define MANDELBROT_04_BLACK_WHITE_SEAHORSES\r\n\r\n// Declare a base class for the Mandelbrot configuration.\r\nclass mandelbrot_configuration_base\r\n{\r\npublic:\r\n  virtual ~mandelbrot_configuration_base() { }\r\n\r\n  long double x_lo() const { return my_x_lo; }\r\n  long double x_hi() const { return my_x_hi; }\r\n  long double y_lo() const { return my_y_lo; }\r\n  long double y_hi() const { return my_y_hi; }\r\n\r\n  virtual boost::uint_fast16_t max_iterations() const = 0;\r\n\r\n  virtual int mandelbrot_fractional_resolution() const = 0;\r\n\r\n  virtual long double step() const = 0;\r\n\r\n  virtual boost::uint_fast32_t width () const = 0;\r\n  virtual boost::uint_fast32_t height() const = 0;\r\n\r\n  virtual boost::uint_fast32_t red_hue  () const = 0;\r\n  virtual boost::uint_fast32_t green_hue() const = 0;\r\n  virtual boost::uint_fast32_t blue_hue () const = 0;\r\n\r\nprotected:\r\n  const long double my_x_lo;\r\n  const long double my_x_hi;\r\n  const long double my_y_lo;\r\n  const long double my_y_hi;\r\n\r\n  mandelbrot_configuration_base(const long double xl, const long double xh,\r\n                                const long double yl, const long double yh) : my_x_lo(xl), my_x_hi(xh),\r\n                                                                              my_y_lo(yl), my_y_hi(yh) { }\r\nprivate:\r\n  mandelbrot_configuration_base() : my_x_lo(0.0L), my_x_hi(0.0L),\r\n                                    my_y_lo(0.0L), my_y_hi(0.0L) { }\r\n};\r\n\r\n// Make a template class that represents the Mandelbrot configuration.\r\n// This class automatically creates sensible parameters based on\r\n// the resolution of the fixed-point type supplied in the template\r\n// parameter. If a custom pixel count is required, the step()\r\n// method can be modified accordingly.\r\ntemplate<const int TotalDigits,\r\n         const boost::uint_fast16_t MaxIterations,\r\n         const int MandelbrotFractionalResolution,\r\n         const boost::uint_fast32_t RedHue,\r\n         const boost::uint_fast32_t GreenHue,\r\n         const boost::uint_fast32_t BlueHue>\r\nclass mandelbrot_configuration : public mandelbrot_configuration_base\r\n{\r\npublic:\r\n  static_assert(    (RedHue   < UINT32_C(256))\r\n                 && (GreenHue < UINT32_C(256))\r\n                 && (BlueHue  < UINT32_C(256)), \"The color hue parameters must be 255 or smaller.\");\r\n\r\n  typedef boost::fixed_point::negatable<16, 16 + 1 - TotalDigits> fixed_point_type;\r\n\r\n  mandelbrot_configuration(const long double xl, const long double xh,\r\n                           const long double yl, const long double yh)\r\n    : mandelbrot_configuration_base(xl, xh, yl, yh) { }\r\n\r\n  virtual ~mandelbrot_configuration() { }\r\n\r\nprivate:\r\n  virtual boost::uint_fast16_t max_iterations() const { return MaxIterations; }\r\n\r\n  virtual int mandelbrot_fractional_resolution() const { return MandelbrotFractionalResolution; }\r\n\r\n  virtual long double step() const { return 1.0L / (UINT64_C(1) << -mandelbrot_fractional_resolution()); }\r\n\r\n  virtual boost::uint_fast32_t width () const { return static_cast<boost::uint_fast32_t>((x_hi() - x_lo()) / step()); }\r\n  virtual boost::uint_fast32_t height() const { return static_cast<boost::uint_fast32_t>((y_hi() - y_lo()) / step()); }\r\n\r\n  virtual boost::uint_fast32_t red_hue  () const { return RedHue; }\r\n  virtual boost::uint_fast32_t green_hue() const { return GreenHue; }\r\n  virtual boost::uint_fast32_t blue_hue () const { return BlueHue; }\r\n};\r\n\r\n// This class generated the rows of the mandelbrot iteration.\r\n// The coordinates are set up according to the Mandelbrot configuration.\r\ntemplate<typename NumericType>\r\nclass mandelbrot_generator\r\n{\r\npublic:\r\n  mandelbrot_generator(const mandelbrot_configuration_base& config)\r\n    : mandelbrot_configuration_object(config),\r\n      mandelbrot_image               (config.width(), config.height()),\r\n      mandelbrot_view                (boost::gil::rgb8_view_t()),\r\n      mandelbrot_iteration_matrix    (mandelbrot_configuration_object.width(),\r\n                                      std::vector<boost::uint_fast16_t>(mandelbrot_configuration_object.height())),\r\n      mandelbrot_color_histogram     (static_cast<std::size_t>(config.max_iterations() + 1U), UINT32_C(0))\r\n  {\r\n    mandelbrot_view = boost::gil::view(mandelbrot_image);\r\n  }\r\n\r\n  ~mandelbrot_generator() { }\r\n\r\n  void generate_mandelbrot_image()\r\n  {\r\n    // Setup the x-axis coordinates.\r\n    std::vector<NumericType> x_values(mandelbrot_configuration_object.width());\r\n\r\n    // Initialize the x-axis coordinates (one time only).\r\n    {\r\n      NumericType x_step(mandelbrot_configuration_object.x_lo());\r\n\r\n      for(NumericType& x : x_values)\r\n      {\r\n        x = x_step;\r\n\r\n        x_step += mandelbrot_configuration_object.step();\r\n      }\r\n    }\r\n\r\n    // Initialize the y-axis coordinate.\r\n    NumericType y(mandelbrot_configuration_object.y_hi());\r\n\r\n    // TBD: The iteration through rows can be distributed in multithreading.\r\n\r\n    // Loop through all the rows of pixels on the vertical\r\n    // y-axis in the direction of decreasing y-value.\r\n    for(boost::uint_fast32_t row = UINT32_C(0); row < mandelbrot_configuration_object.height(); ++row, y -= mandelbrot_configuration_object.step())\r\n    {\r\n      // Loop through this column of pixels on the horizontal\r\n      // x-axis in the direction of increasing x-value.\r\n      boost::uint_fast32_t col = UINT32_C(0);\r\n\r\n      std::for_each(x_values.cbegin(),\r\n                    x_values.cend(),\r\n      [&y, &col, &row, this](const NumericType& x)\r\n      {\r\n        const NumericType cr(x);\r\n        const NumericType ci(y);\r\n\r\n        NumericType zr(0);\r\n        NumericType zi(0);\r\n\r\n        NumericType zr_sqr(0);\r\n        NumericType zi_sqr(0);\r\n\r\n        // Use an optimized complex-numbered multiplication scheme.\r\n        // Thereby reduce the main work of the Mandelbrot iteration to\r\n        // three real-valued multiplications and several real-valued\r\n        // addition/subtraction operations.\r\n\r\n        boost::uint_fast16_t i = UINT16_C(0);\r\n\r\n        // Perform the iteration sequence for generating the Mandelbrot set.\r\n        // Herein lies the work of the program.\r\n        // TBD: This can easily be distributed to parallel processes.\r\n\r\n        while(   (i < mandelbrot_configuration_object.max_iterations())\r\n              && ((zr_sqr + zi_sqr) < 4))\r\n        {\r\n          zi *= zr;\r\n          zi  = (zi + zi) + ci;\r\n\r\n          zr = (zr_sqr - zi_sqr) + cr;\r\n\r\n          zr_sqr = zr * zr;\r\n          zi_sqr = zi * zi;\r\n\r\n          ++i;\r\n        }\r\n\r\n        mandelbrot_iteration_matrix[col][row] = i;\r\n\r\n        ++mandelbrot_color_histogram[i];\r\n\r\n        ++col;\r\n      });\r\n\r\n      std::cout << \"Calculating Mandelbrot image at row \"\r\n                << std::setw(6)\r\n                << (row + 1U)\r\n                << \" of \"\r\n                << std::setw(6)\r\n                << mandelbrot_configuration_object.height()\r\n                << \" total. Have patience.\"\r\n                << \"\\r\";\r\n    }\r\n\r\n    const boost::uint_fast32_t total = boost::uint_fast32_t(mandelbrot_configuration_object.width()) * mandelbrot_configuration_object.height();\r\n\r\n    // Perform color-stretching using the histogram approach.\r\n    // Convert the histogram entries such that a given entry contains\r\n    // the sum of its own entries plus all previous entries. This provides\r\n    // a set of scale factors for the color. The histogram approach\r\n    // automatically scales to the distribution of pixels in the image.\r\n\r\n    std::accumulate(mandelbrot_color_histogram.begin(),\r\n                    mandelbrot_color_histogram.end(),\r\n                    boost::uint_fast32_t(0U),\r\n    [&total](boost::uint_fast32_t& sum, boost::uint_fast32_t& histogram_entry) -> boost::uint_fast32_t\r\n    {\r\n      sum += histogram_entry;\r\n\r\n      histogram_entry = UINT32_C(0xFF) - static_cast<boost::uint_fast32_t>((boost::uint64_t(sum) * 0xFFU) / total);\r\n\r\n      return sum;\r\n    });\r\n\r\n    for(boost::uint_fast32_t row = UINT32_C(0); row < mandelbrot_configuration_object.height(); ++row)\r\n    {\r\n      for(boost::uint_fast32_t col = UINT32_C(0); col < mandelbrot_configuration_object.width(); ++col)\r\n      {\r\n        const boost::uint_fast32_t color = mandelbrot_color_histogram[mandelbrot_iteration_matrix[col][row]];\r\n\r\n        // Mix the color supplied in the template hue parameters.\r\n        const boost::uint8_t rh = static_cast<boost::uint8_t>((mandelbrot_configuration_object.red_hue  () * color) / UINT32_C(255));\r\n        const boost::uint8_t gh = static_cast<boost::uint8_t>((mandelbrot_configuration_object.green_hue() * color) / UINT32_C(255));\r\n        const boost::uint8_t bh = static_cast<boost::uint8_t>((mandelbrot_configuration_object.blue_hue () * color) / UINT32_C(255));\r\n\r\n        const boost::gil::rgb8_pixel_t the_color  = boost::gil::rgb8_pixel_t(rh, gh, bh);\r\n\r\n        mandelbrot_view(col, row) = boost::gil::rgb8_pixel_t(the_color);\r\n      }\r\n    }\r\n\r\n    boost::gil::jpeg_write_view(\"mandelbrot.jpg\", mandelbrot_view);\r\n\r\n    std::cout << std::endl\r\n              << \"The ouptput file mandelbrot.jpg has been written\"\r\n              << std::endl;\r\n  }\r\n\r\nprivate:\r\n  const mandelbrot_configuration_base&           mandelbrot_configuration_object;\r\n  boost::gil::rgb8_image_t                       mandelbrot_image;\r\n  boost::gil::rgb8_view_t                        mandelbrot_view;\r\n  std::vector<std::vector<boost::uint_fast16_t>> mandelbrot_iteration_matrix;\r\n  std::vector<boost::uint_fast32_t>              mandelbrot_color_histogram;\r\n};\r\n\r\nint main()\r\n{\r\n  #if defined MANDELBROT_01_AQUA_FULL\r\n\r\n    // This is the classic full immage rendered in aqua tones (and black).\r\n    typedef mandelbrot_configuration<128, UINT16_C(2000), -11,\r\n                                     UINT32_C(80),\r\n                                     UINT32_C(255),\r\n                                     UINT32_C(255)> mandelbrot_configuration_type;\r\n\r\n    const mandelbrot_configuration_type mandelbrot_configuration_object(-2.000L, +0.500L,\r\n                                                                        -1.000L, +1.000L);\r\n\r\n  #elif defined MANDELBROT_02_YELLOW_TOP\r\n\r\n    // This is an upper part of the image rendered in yellow and black tones.\r\n    typedef mandelbrot_configuration<128, UINT16_C(2000), -13,\r\n                                     UINT32_C(255),\r\n                                     UINT32_C(255),\r\n                                     UINT32_C(0)> mandelbrot_configuration_type;\r\n\r\n    const mandelbrot_configuration_type mandelbrot_configuration_object(-0.1208L - 0.1616L, -0.1208L + 0.1616L,\r\n                                                                        +0.7607L - 0.1616L, +0.7607L + 0.1616L);\r\n\r\n  #elif defined MANDELBROT_03_FUSCHIA_SWIRL\r\n\r\n    // This is a fanning image rendered in fuschia tones (and black).\r\n    typedef mandelbrot_configuration<128, UINT16_C(10000), -22,\r\n                                     UINT32_C(255),\r\n                                     UINT32_C(0),\r\n                                     UINT32_C(210)> mandelbrot_configuration_type;\r\n\r\n    const mandelbrot_configuration_type mandelbrot_configuration_object(-0.749730L - 0.0002315L, -0.749730L + 0.0002315L,\r\n                                                                        -0.046608L - 0.0002315L, -0.046608L + 0.0002315L);\r\n\r\n  #elif defined MANDELBROT_04_BLACK_WHITE_SEAHORSES\r\n\r\n    // This is a swirly seahorse image rendered in black-and-white tones.\r\n    typedef mandelbrot_configuration<128, UINT16_C(10000), -46,\r\n                                     UINT32_C(255),\r\n                                     UINT32_C(255),\r\n                                     UINT32_C(255)> mandelbrot_configuration_type;\r\n    const mandelbrot_configuration_type mandelbrot_configuration_object(-0.745398360667L - 1.25E-11L, -0.745398360667L + 1.25E-11L,\r\n                                                                      +0.112504634996L - 1.25E-11L, +0.112504634996L + 1.25E-11L);\r\n\r\n  #else\r\n\r\n    #error: Mandelbrot imag type is not defined!\r\n\r\n  #endif\r\n\r\n  typedef mandelbrot_configuration_type::fixed_point_type mandelbrot_numeric_type;\r\n\r\n  typedef mandelbrot_generator<mandelbrot_numeric_type> mandelbrot_generator_type;\r\n\r\n  const std::clock_t start = std::clock();\r\n\r\n  mandelbrot_generator_type* the_mandelbrot_generator = new mandelbrot_generator_type(mandelbrot_configuration_object);\r\n\r\n  the_mandelbrot_generator->generate_mandelbrot_image();\r\n\r\n  const float elapsed = (float(std::clock()) - float(start)) / CLOCKS_PER_SEC;\r\n\r\n  std::cout << \"Time for calculation: \"\r\n            << elapsed\r\n            << \"s\"\r\n            << std::endl;\r\n\r\n  delete the_mandelbrot_generator;\r\n}\r\n", "meta": {"hexsha": "34fa742f37ee03951b810987f35cc22ba5a12c7f", "size": 14060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_mandelbrot.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_mandelbrot.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_mandelbrot.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": 40.2865329513, "max_line_length": 148, "alphanum_fraction": 0.6371266003, "num_tokens": 3449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5192001590765363}}
{"text": "#define BOOST_TEST_MODULE SparseLatticeMultTestsSpecial\n\n\n\n\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//!Relies on normal SparseLattice*SparseLattice operator functioning correctly, i.e., that the SparseLatticeMultTests passed\ntemplate<typename data_type>\nvoid multwork(size_t m1, size_t n1, size_t n2, size_t p,double hypersparsity){\n\r\n\r\n\r\n\r\n    typedef LibMIA::SparseLattice<data_type> sparseType;\r\n    sparseType A,B;\r\n    A=sparseType(m1,n1,p);\r\n    A.resize(std::ceil(p*m1*hypersparsity));\r\n    A.randu(1,10);\r\n    A.rand_indices();\r\n    A.collect_duplicates();\r\n\r\n    B=sparseType(n1,n2,p);\r\n    B.resize(std::ceil(p*n2*hypersparsity));\r\n    B.randu(1,10);\r\n    B.rand_indices();\r\n    B.collect_duplicates();\r\n\r\n    sparseType C,C_test;\r\n\r\n    C=A*B;\r\n\r\n    C_test=A.template csc_times<false>(B);\r\n    BOOST_CHECK_MESSAGE(C.fuzzy_equals(C_test,test_precision<data_type>()),std::string(\"CSC Mult Test Accum for \")+typeid(data_type).name());\r\n\t\r\n\r\n    C_test=A.template csc_no_accum<false>(B);\r\n    BOOST_CHECK_MESSAGE(C.fuzzy_equals(C_test,test_precision<data_type>()),std::string(\"CSC Mult Test No Accum for \")+typeid(data_type).name());\r\n\t\r\n    C_test=A.template csc_times<true>(B);\r\n    BOOST_CHECK_MESSAGE(C.fuzzy_equals(C_test,test_precision<data_type>()),std::string(\"DCSC Mult Test Accum for \")+typeid(data_type).name());\r\n\r\n    C_test=A.template csc_no_accum<true>(B);\r\n    BOOST_CHECK_MESSAGE(C.fuzzy_equals(C_test,test_precision<data_type>()),std::string(\"DCSC Mult Test No Accum for \")+typeid(data_type).name());\r\n\r\n    C_test=A.outer_times(B);\r\n    BOOST_CHECK_MESSAGE(C.fuzzy_equals(C_test,test_precision<data_type>()),std::string(\"Outer Mult Test for \")+typeid(data_type).name());\r\n\r\n\r\n\n\n}\n\nBOOST_AUTO_TEST_CASE( SparseLatticeMultTestsSpecial )\n{\n\n\n    //multwork<double>(5,5,5,5,1);\r\n    multwork<double>(20,20,20,20,1);\n    multwork<float>(20,20,20,20,1);\r\n    multwork<int>(20,20,20,20,1);\r\n    multwork<long>(20,20,20,20,1);\r\n\r\n    multwork<double>(20,20,20,20,.5);\n    multwork<float>(20,20,20,20,.5);\r\n    multwork<int>(20,20,20,20,.5);\r\n    multwork<long>(20,20,20,20,.5);\r\n\r\n    multwork<double>(40,20,20,20,1);\n    multwork<float>(40,20,20,20,1);\r\n    multwork<int>(40,20,20,20,1);\r\n    multwork<long>(40,20,20,20,1);\r\n\r\n    multwork<double>(20,20,40,20,.5);\n    multwork<float>(20,20,40,20,.5);\r\n    multwork<int>(20,20,20,40,.5);\r\n    multwork<long>(20,20,20,40,.5);\n\n\n\n}\r\n", "meta": {"hexsha": "a7f2ef93614cd3c7f093439b2b6bd2e9ce7e0d16", "size": 2545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/SparseLattice/sparse_lattice_mult_test_specialized.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_specialized.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_specialized.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.595505618, "max_line_length": 146, "alphanum_fraction": 0.6813359528, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5192001516694542}}
{"text": "#include <deal.II/base/function_parser.h>\n#include <deal.II/base/point.h>\n#include <iostream>\n#include <map>\n#include <unordered_map>\n#include <boost/functional/hash.hpp>\n\nusing namespace dealii;\n\n\nnamespace std {\ntemplate<>\nclass hash<dealii::Point<2>>\n{\n public:\n  std::size_t operator()(const dealii::Point<2>& x) const\n  {\n    std::size_t current = std::hash<double>()(x[0]);\n    boost::hash_combine(current, std::hash<double>()(x[1]));\n\n    return current;\n  }\n\n};\n}  // std\n\n\nint main(int argc, char *argv[])\n{\n  // set up problem:\n  std::string variables = \"x,y\";\n  std::string expression = \"cos(pi*x)+sqrt(y)\";\n  std::map<std::string,double> constants;\n  constants[\"pi\"] = 3.14159265358979323846264338328;\n  // FunctionParser with 2 variables and 1 component:\n  FunctionParser<2> fp(1);\n  fp.initialize(variables,\n                expression,\n                constants);\n  // Point at which we want to evaluate the function\n  Point<2> point(1.0, 4.0);\n  // evaluate the expression at 'point':\n  double result = fp.value(point);\n  std::cout << \"result \" << result << \"\\n\";\n  std::unordered_map<Point<2>, double> huch;\n\n  return 0;\n}\n", "meta": {"hexsha": "730f1929898321969a48372bc85d7405c2daad72", "size": 1139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function_parser/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/function_parser/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/function_parser/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": 23.2448979592, "max_line_length": 60, "alphanum_fraction": 0.6514486392, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5191783095759556}}
{"text": "#ifndef TRIUMF_BNMR_SLR_CBRT_EXP_HPP\n#define TRIUMF_BNMR_SLR_CBRT_EXP_HPP\n\n#include <boost/math/quadrature/tanh_sinh.hpp>\n#include <cmath>\n#include <triumf/bnmr/slr/common.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// \u03b2-detected nuclear magnetic resonance (\u03b2-NMR)\nnamespace bnmr {\n\n// spin-lattice relaxation (SLR)\nnamespace slr {\n\n/// pulsed cube root exponential integral (from 0 to time_p <= time)\ntemplate <typename T = double>\nT pulsed_cbrt_exp_integral(T time, T time_p, T nuclear_lifetime, T slr_rate) {\n  // make sure that\n  assert(time >= time_p);\n  // integrand for the numeric integral\n  auto integrand = [=](T t_p) {\n    return std::exp(-(time - t_p) / nuclear_lifetime) *\n           std::exp(-std::cbrt(slr_rate * (time - t_p)));\n  };\n  // create the integrator for tanh-sinh quadrature\n  static boost::math::quadrature::tanh_sinh<T> integrator;\n  // evaluate the integral from 0 to time_p\n  T Q = integrator.integrate(integrand, 0.0, time_p);\n  return Q;\n}\n\n/// pulsed cube root exponential\ntemplate <typename T = double>\nT pulsed_cbrt_exp(T time, T nuclear_lifetime, T pulse_length, T asymmetry,\n                  T slr_rate) {\n  if (time == 0.0) {\n    return asymmetry;\n  } else if (time > 0.0 and time <= pulse_length) {\n    return asymmetry *\n           pulsed_cbrt_exp_integral(time, time, nuclear_lifetime, slr_rate) /\n           normalization(time, nuclear_lifetime);\n  } else if (time > pulse_length) {\n    return (asymmetry *\n            pulsed_cbrt_exp_integral(time, pulse_length, nuclear_lifetime,\n                                     slr_rate) /\n            normalization(pulse_length, nuclear_lifetime)) /\n           std::exp(-(time - pulse_length) / nuclear_lifetime);\n  } else {\n    return 0.0;\n  }\n}\n\n/// pulsed cube root exponential (ROOT)\ntemplate <typename T = double> T pulsed_cbrt_exp(const T *x, const T *par) {\n  return pulsed_cbrt_exp<T>(*x, par[0], par[1], par[2], par[3]);\n}\n\n} // namespace slr\n\n} // namespace bnmr\n\n} // namespace triumf\n\n#endif // TRIUMF_BNMR_SLR_CBRT_EXP_HPP\n", "meta": {"hexsha": "7be86ba6cc0c2a437ccefd6605a6a1bd4e1786f7", "size": 2051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/bnmr/slr/cbrt_exp.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/bnmr/slr/cbrt_exp.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/bnmr/slr/cbrt_exp.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": 30.6119402985, "max_line_length": 78, "alphanum_fraction": 0.6757679181, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5191783095759555}}
{"text": "#pragma once\n\n#include <cmath>\n#include <ros/ros.h>\n#include <ct/optcon/optcon.h>\n#include <lqr_controller/declarations_quaternion.hpp>\n#include <nav_msgs/Odometry.h>\n#include <Eigen/Geometry>\n#include <mavros/frame_tf.h>\n#include <mav_msgs/eigen_mav_msgs.h>\n#include <mav_trajectory_generation/polynomial_optimization_linear.h>\n//#include <mav_trajectory_generation/polynomial_optimization_nonlinear.h>\n#include <mav_trajectory_generation/trajectory.h>\n#include <mav_trajectory_generation/trajectory_sampling.h>\n#include <mav_trajectory_generation_ros/ros_visualization.h>\n#include <visualization_msgs/MarkerArray.h>\n#include <ros/package.h>\n\nnamespace LQR {\nclass LQR_Quaternion {\n  public:\n    /*!\n     * Constructor.\n     * @param nodeHandle the ROS node handle.\n     */\n    LQR_Quaternion(ros::NodeHandle& nodeHandle);\n\n    /*!\n     * Destructor.\n     */\n    virtual ~LQR_Quaternion();\n\n    control_vector_t getTrajectoryControl();\n    state_vector_t getError();\n    ct::core::FeedbackMatrix<nStates, nControls> getGain();\n    void setOutput(double output, int j);\n    void setOutput(control_vector_t output);\n    control_vector_t getOutput();\n    state_vector_t getRefStates();\n\n   private:\n\n    /*!\n     * ROS topic callback method.\n     * @param message the received message.\n     */\n\n    void topicCallback(const nav_msgs::Odometry::ConstPtr& msg);\n    void setStates(const nav_msgs::Odometry::ConstPtr& msg, state_vector_t& x);\n    void setError(const state_vector_t& xref, const state_vector_t& x, state_vector_t& xerror);\n    bool setTrajectoryReference(state_vector_t& xref,control_vector_t& uref);\n    bool setStaticReference(state_vector_t& xref,control_vector_t& uref, Eigen::Vector4d& flat_states);\n    Eigen::Vector3d quaternion_to_rpy_wrap(const Eigen::Quaterniond &q);\n    void generateTrajectory(mav_msgs::EigenTrajectoryPoint::Vector& states);\n\n    //! ROS node handle.\n    ros::NodeHandle& nodeHandle_;\n\n    //! ROS topic subscriber.\n    ros::Subscriber odom_sub_;\n\n    //Marker publisher\n    ros::Publisher marker_pub_;\n\n    //! State and control matrix dimensions\n    const size_t state_dim = nStates;\n    const size_t control_dim = nControls;\n\n    //Trajectory\n    double sampling_interval = 0.1;\n    const double v_max = 2.0;\n    const double a_max = 5.0;\n    const int dimension = 3;\n    int traj_index;\n    bool initiated;\n    mav_msgs::EigenTrajectoryPoint::Vector states_;\n    visualization_msgs::MarkerArray markers_;\n\n    ros::Time init_time_;\n    Eigen::Vector3d position_enu_;\n    Eigen::Vector3d velocity_enu_;\n    Eigen::Quaterniond q_enu_;\n    state_matrix_t A_;\n    control_gain_matrix_t B_;\n    ct::core::FeedbackMatrix<nStates, nControls> Kold_;\n    ct::core::FeedbackMatrix<nStates, nControls> Knew_;\n    ros::Time callBack_;\n    state_vector_t x_;\n    control_vector_t u_;\n    state_vector_t xref_;\n    control_vector_t uref_;\n    state_vector_t xerror_;\n    control_vector_t output_;\n\n    ct::optcon::TermQuadratic<nStates, nControls> quadraticCost_;\n    ct::optcon::TermQuadratic<nStates, nControls>::state_matrix_t Q_;\n    ct::optcon::TermQuadratic<nStates, nControls>::control_matrix_t R_;\n    ct::optcon::LQR<nStates, nControls> lqrSolver_;\n    //states\n    state_matrix_t A_quadrotor(const state_vector_t& x, const control_vector_t& u);\n    control_gain_matrix_t B_quadrotor(const state_vector_t& x, const control_vector_t& u);\n  };\n\n} /* namespace */\n", "meta": {"hexsha": "613090d9ee86fd6c10d049381e1455df66b6fd62", "size": 3401, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lqr_controller/lqr_quaternion.hpp", "max_stars_repo_name": "llanesc/lqr-tracking", "max_stars_repo_head_hexsha": "270f2f5164a668bfb77e19f5191595f1d3913a16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-17T10:00:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T22:17:36.000Z", "max_issues_repo_path": "include/lqr_controller/lqr_quaternion.hpp", "max_issues_repo_name": "llanesc/lqr-tracking", "max_issues_repo_head_hexsha": "270f2f5164a668bfb77e19f5191595f1d3913a16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-30T18:12:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-28T05:08:35.000Z", "max_forks_repo_path": "include/lqr_controller/lqr_quaternion.hpp", "max_forks_repo_name": "llanesc/lqr-tracking", "max_forks_repo_head_hexsha": "270f2f5164a668bfb77e19f5191595f1d3913a16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-04-22T09:00:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:33:58.000Z", "avg_line_length": 32.3904761905, "max_line_length": 103, "alphanum_fraction": 0.7356659806, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5190696337405079}}
{"text": "/**\n * @file convolutional_network_test.cpp\n * @author Marcus Edel\n * @author Abhinav Moudgil\n *\n * Tests the convolutional neural network.\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\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/init_rules/gaussian_init.hpp>\n\n#include <ensmallen.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(ConvolutionalNetworkTest);\n\n/**\n * Train the vanilla network on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(VanillaNetworkTest)\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>(1, nPoints);\n  for (size_t i = 0; i < nPoints; i++)\n  {\n    if (i < nPoints / 2)\n    {\n      // Assign label \"1\" to all samples with digit = 4\n      Y(i) = 1;\n    }\n    else\n    {\n      // Assign label \"2\" to all samples with digit = 9\n      Y(i) = 2;\n    }\n  }\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  // It isn't guaranteed that the network will converge in the specified number\n  // of iterations using random weights. If this works 1 of 5 times, I'm fine\n  // with that. All I want to know is that the network is able to escape from\n  // local minima and to solve the task.\n  bool success = false;\n  for (size_t trial = 0; trial < 5; ++trial)\n  {\n    FFN<NegativeLogLikelihood<>, RandomInitialization> model;\n\n    model.Add<Convolution<> >(1, 8, 5, 5, 1, 1, 0, 0, 28, 28);\n    model.Add<ReLULayer<> >();\n    model.Add<MaxPooling<> >(8, 8, 2, 2);\n    model.Add<Convolution<> >(8, 12, 2, 2);\n    model.Add<ReLULayer<> >();\n    model.Add<MaxPooling<> >(2, 2, 2, 2);\n    model.Add<Linear<> >(192, 20);\n    model.Add<ReLULayer<> >();\n    model.Add<Linear<> >(20, 10);\n    model.Add<ReLULayer<> >();\n    model.Add<Linear<> >(10, 2);\n    model.Add<LogSoftMax<> >();\n\n    // Train for only 8 epochs.\n    ens::RMSProp opt(0.001, 1, 0.88, 1e-8, 8 * nPoints, -1);\n\n    double objVal = model.Train(X, Y, opt);\n\n    // Test that objective value returned by FFN::Train() is finite.\n    BOOST_REQUIRE_EQUAL(std::isfinite(objVal), true);\n\n    arma::mat predictionTemp;\n    model.Predict(X, predictionTemp);\n    arma::mat prediction = arma::zeros<arma::mat>(1, predictionTemp.n_cols);\n\n    for (size_t i = 0; i < predictionTemp.n_cols; ++i)\n    {\n      prediction(i) = arma::as_scalar(arma::find(\n            arma::max(predictionTemp.col(i)) == predictionTemp.col(i), 1)) + 1;\n    }\n\n    size_t correct = arma::accu(prediction == Y);\n    double classificationError = 1 - double(correct) / X.n_cols;\n    if (classificationError <= 0.25)\n    {\n      success = true;\n      break;\n    }\n  }\n\n  BOOST_REQUIRE_EQUAL(success, true);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "a7c3e4144235944135875e17fb5d1aaf8257c6b8", "size": 4133, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/convolutional_network_test.cpp", "max_stars_repo_name": "abinezer/mlpack", "max_stars_repo_head_hexsha": "8002e49150742acea4e76deef8161653b8350936", "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": "2019-11-07T14:34:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-07T14:34:37.000Z", "max_issues_repo_path": "src/mlpack/tests/convolutional_network_test.cpp", "max_issues_repo_name": "876arham/mlpack", "max_issues_repo_head_hexsha": "1379831e578037c9d0ed3a1683ce76e3d1c8247e", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-10T17:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-11T14:56:25.000Z", "max_forks_repo_path": "src/mlpack/tests/convolutional_network_test.cpp", "max_forks_repo_name": "876arham/mlpack", "max_forks_repo_head_hexsha": "1379831e578037c9d0ed3a1683ce76e3d1c8247e", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7923076923, "max_line_length": 79, "alphanum_fraction": 0.5717396564, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5190696240810612}}
{"text": "#ifndef CT_ICP_TYPES_HPP\n#define CT_ICP_TYPES_HPP\n\n#include <map>\n#include <unordered_map>\n#include <list>\n\n#include <tsl/robin_map.h>\n\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n#include <glog/logging.h>\n\n#include \"utils.hpp\"\n\n#define _USE_MATH_DEFINES\n\n#include <math.h>\n\nnamespace ct_icp {\n\n    // A Point3D\n    struct Point3D {\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        Eigen::Vector3d raw_pt; // Raw point read from the sensor\n        Eigen::Vector3d pt; // Corrected point taking into account the motion of the sensor during frame acquisition\n        double alpha_timestamp = 0.0; // Relative timestamp in the frame in [0.0, 1.0]\n        double timestamp = 0.0; // The absolute timestamp (if applicable)\n        int index_frame = -1; // The frame index\n\n        Point3D() = default;\n    };\n\n    inline double AngularDistance(const Eigen::Matrix3d &rota,\n                                  const Eigen::Matrix3d &rotb) {\n        double norm = ((rota * rotb.transpose()).trace() - 1) / 2;\n        norm = std::acos(norm) * 180 / M_PI;\n        return norm;\n    }\n\n    // A Trajectory Frame\n    struct TrajectoryFrame {\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        bool success = true;\n        double begin_timestamp = 0.0;\n        double end_timestamp = 1.0;\n        Eigen::Matrix3d begin_R;\n        Eigen::Vector3d begin_t;\n        Eigen::Matrix3d end_R;\n        Eigen::Vector3d end_t;\n\n        inline double EgoAngularDistance() const {\n            return AngularDistance(begin_R, end_R);\n        }\n\n        double TranslationDistance(const TrajectoryFrame &other) {\n            return (begin_t - other.begin_t).norm() + (end_t - other.end_t).norm();\n        }\n\n        double RotationDistance(const TrajectoryFrame &other) {\n            return (begin_R * other.begin_R.inverse() - Eigen::Matrix3d::Identity()).norm() +\n                   (end_R * other.end_R.inverse() - Eigen::Matrix3d::Identity()).norm();\n        }\n\n        TrajectoryFrame() = default;\n\n        [[nodiscard]] inline Eigen::Matrix4d MidPose() const {\n            Eigen::Matrix4d mid_pose = Eigen::Matrix4d::Identity();\n            auto q_begin = Eigen::Quaterniond(begin_R);\n            auto q_end = Eigen::Quaterniond(end_R);\n            Eigen::Vector3d t_begin = begin_t;\n            Eigen::Vector3d t_end = end_t;\n            Eigen::Quaterniond q = q_begin.slerp(0.5, q_end);\n            q.normalize();\n            mid_pose.block<3, 3>(0, 0) = q.toRotationMatrix();\n            mid_pose.block<3, 1>(0, 3) = 0.5 * t_begin + 0.5 * t_end;\n            return mid_pose;\n        }\n    };\n\n\n    // Voxel\n    // Note: Coordinates range is in [-32 768, 32 767]\n    struct Voxel {\n\n        Voxel() = default;\n\n        Voxel(short x, short y, short z) : x(x), y(y), z(z) {}\n\n        bool operator==(const Voxel &vox) const { return x == vox.x && y == vox.y && z == vox.z; }\n\n        inline bool operator<(const Voxel &vox) const {\n            return x < vox.x || (x == vox.x && y < vox.y) || (x == vox.x && y == vox.y && z < vox.z);\n        }\n\n        inline static Voxel Coordinates(const Eigen::Vector3d &point, double voxel_size) {\n            return {short(point.x() / voxel_size),\n                    short(point.y() / voxel_size),\n                    short(point.z() / voxel_size)};\n        }\n\n        short x;\n        short y;\n        short z;\n    };\n\n    typedef std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> ArrayVector3d;\n    typedef std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>> ArrayMatrix4d;\n    typedef ArrayMatrix4d ArrayPoses;\n\n    struct VoxelBlock {\n\n        explicit VoxelBlock(int num_points = 20) : num_points_(num_points) { points.reserve(num_points); }\n\n        ArrayVector3d points;\n\n        bool IsFull() const { return num_points_ == points.size(); }\n\n        void AddPoint(const Eigen::Vector3d &point) {\n            CHECK(num_points_ >= points.size()) << \"Voxel Is Full\";\n            points.push_back(point);\n        }\n\n        inline int NumPoints() const { return points.size(); }\n\n        inline int Capacity() { return num_points_; }\n\n    private:\n        int num_points_;\n    };\n\n\n    typedef tsl::robin_map<Voxel, VoxelBlock> VoxelHashMap;\n\n\n} // namespace Elastic_ICP\n\n\n// Specialization of std::hash for our custom type Voxel\nnamespace std {\n\n\n    template<>\n    struct hash<ct_icp::Voxel> {\n        std::size_t operator()(const ct_icp::Voxel &vox) const {\n#ifdef CT_ICP_IS_WINDOWS\n            const std::hash<int32_t> hasher;\n            return ((hasher(vox.x) ^ (hasher(vox.y) << 1)) >> 1) ^ (hasher(vox.z) << 1) >> 1;\n#else\n            const size_t kP1 = 73856093;\n            const size_t kP2 = 19349669;\n            const size_t kP3 = 83492791;\n            return vox.x * kP1 + vox.y * kP2 + vox.z * kP3;\n#endif\n        }\n    };\n}\n\n#endif //CT_ICP_TYPES_HPP\n", "meta": {"hexsha": "2af161509c6f505b1e585af8c0172b52ad9b614c", "size": 4834, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ct_icp/types.hpp", "max_stars_repo_name": "xiang-1208/ct_icp", "max_stars_repo_head_hexsha": "42928e584c24595c49e147e2ea120f8cc31ec716", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2021-10-08T01:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:55:15.000Z", "max_issues_repo_path": "src/ct_icp/types.hpp", "max_issues_repo_name": "ZuoJiaxing/ct_icp", "max_issues_repo_head_hexsha": "1c371331aad833faec157c015fb8f72143019caa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-10-19T07:25:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T03:20:19.000Z", "max_forks_repo_path": "src/ct_icp/types.hpp", "max_forks_repo_name": "ZuoJiaxing/ct_icp", "max_forks_repo_head_hexsha": "1c371331aad833faec157c015fb8f72143019caa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2021-10-08T01:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T15:35:07.000Z", "avg_line_length": 29.8395061728, "max_line_length": 116, "alphanum_fraction": 0.590401324, "num_tokens": 1265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503682, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5190696192513377}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n#include <valarray>\n#include <sstream>\n#include <filesystem>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"miMaS/field.h\"\n#include \"miMaS/weno.h\"\n#include \"miMaS/fft.h\"\n#include \"miMaS/array_view.h\"\n#include \"miMaS/poisson.h\"\n#include \"miMaS/rk.h\"\n#include \"miMaS/config.h\"\n#include \"miMaS/signal_handler.h\"\n\nnamespace o2 {\n  template < typename _T , std::size_t NumDimsV >\n  auto\n  trp_v ( field<_T,NumDimsV> const & u , ublas::vector<_T> const& E )\n  {\n    field<_T,NumDimsV> trp(tools::array_view<const std::size_t>(u.shape(),NumDimsV+1));\n\n    { auto k=0, km1=trp.size(0)-1;\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[k+1][i]-u[km1][i])/(2.*u.step.dv) );\n      }\n    }\n    for ( auto k=1 ; k<trp.size(0)-1 ; ++k ) {\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[k+1][i]-u[k-1][i])/(2.*u.step.dv) );\n      }\n    }\n    { auto k=trp.size(0)-1, kp1=0;\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[kp1][i]-u[k-1][i])/(2.*u.step.dv) );\n      }\n    }\n\n    return trp;\n  }\n}\n\n\nnamespace math = boost::math::constants;\nconst std::complex<double> & I = std::complex<double>(0.,1.);\n\n#define SQ(X) ((X)*(X))\n#define Xi(i) (i*f.step.dx+f.range.x_min)\n#define Vk(k) (k*f.step.dv+f.range.v_min)\n\n\nauto\nmaxwellian ( double rho , double u , double T ) {\n  return [=](double x,double v){ return rho/(std::sqrt(2.*math::pi<double>()*T))*std::exp( -0.5*SQ(v-u)/T ); };\n}\n\nint\nmain(int argc, char const *argv[])\n{\n  std::filesystem::path p(\"config.init\");\n  if ( argc > 1 ) {\n    p = argv[1];\n  }\n  auto c = config(p);\n  std::cout << \" \" << c.output_dir << std::endl;\n  c.name = \"\";\n\n  c.create_output_directory();\n  std::ofstream ofconfig( c.output_dir / \"config.init\" );\n  ofconfig << c << \"\\n\";\n  ofconfig.close();\n\n/* --------------------------------------------------------------- */\n  field<double,1> f(boost::extents[c.Nv][c.Nx]);\n  double Kx = 0.5;\n\n  f.range.v_min = -8.; f.range.v_max = 8.;\n  //f.range.x_min =  0.; f.range.x_max = 2./Kx*math::pi<double>();\n  f.range.x_min = 0.; f.range.x_max = 20.*math::pi<double>();\n  f.compute_steps();\n\n  ublas::vector<double> v (c.Nv,0.);\n  for ( std::size_t k=0 ; k<c.Nv ; ++k ) { v[k] = Vk(k); }\n\n  ublas::vector<double> kx(c.Nx);\n  {\n    double l = f.range.len_x();\n    for ( auto i=0 ; i<c.Nx/2 ; ++i ) { kx[i]      = 2.*math::pi<double>()*i/l; }\n    for ( int i=-c.Nx/2 ; i<0 ; ++i ) { kx[c.Nx+i] = 2.*math::pi<double>()*i/l; }\n  }\n\n  //double alpha = 0.2 , ui = 2.0;\n  auto landau_M = maxwellian( 1.        ,  0.   , 1.   );\n  auto db_M1    = maxwellian( 0.5       , -c.ui , 1.   ) , db_M2  = maxwellian( 0.5       ,  c.ui , 1.  );\n  //auto bot_M1   = maxwellian( 1.-alpha  ,  0. , 1.   ) , bot_M2 = maxwellian( alpha     ,  ui , 0.25);\n  auto bot_M1   = maxwellian(0.9,0.,1.) , bot_M2 = maxwellian(0.2,4.5,0.25);\n  auto tb_MC    = maxwellian( 1.-c.alpha  ,  0. , c.Tc ) ,\n       tb_M1    = maxwellian( 0.5*c.alpha ,  c.ui , 1.   ) , tb_M2  = maxwellian( 0.5*c.alpha , -c.ui , 1.  );\n  auto v10_MC   = maxwellian( 1.-c.alpha  ,  0. , c.Tc ) , v10_Mh = maxwellian( c.alpha     ,  0. , 1.  );\n\n  for (field<double,2>::size_type k=0 ; k<f.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<f.size(1) ; ++i ) {\n      //f[k][i] = ((1.-alpha)*M0c(Xi(i),Vk(k)) + 0.5*alpha*( Mpu(Xi(i),Vk(k)) + Mmu(Xi(i),Vk(k)) ))*(1.+0.01*std::cos(0.5*Xi(i)));\n\n      //// landau damping : Kx=0.5\n      //f[k][i] = landau_M(Xi(i),Vk(k))*(1.+0.001*std::cos(Kx*Xi(i)));\n      //// strong landau damping : Kx=0.5\n      //f[k][i] = landau_M(Xi(i),Vk(k))*(1.+0.6*std::cos(Kx*Xi(i)));\n      //// double beam Kx=0.2, ui=2.4 ou Kx=0.2, ui=4.5\n      //f[k][i] = (db_M1(Xi(i),Vk(k))+db_M2(Xi(i),Vk(k)))*(1.+0.001*std::cos(Kx*Xi(i)));\n      //// bot Kx=0.5 , alpha=0.2 , ui=4.5\n      //f[k][i] = (bot_M1(Xi(i),Vk(k)) + bot_M2(Xi(i),Vk(k)))*(1.+0.04*std::cos(0.3*Xi(i)));\n      //// tb Kx=0.5 , ui=4. , alpha=0.2 , Tc=0.01\n      f[k][i] = tb_MC(Xi(i),Vk(k)) + (tb_M1(Xi(i),Vk(k)) + tb_M2(Xi(i),Vk(k)) )*(1. + 0.01*std::cos(Kx*Xi(i)));\n      //// v10 Kx=0.5 , alpha=0.2\n      //f[k][i] = v10_MC(Xi(i),Vk(k)) + ( std::pow(Vk(k),10)*v10_Mh(Xi(i),Vk(k))/945. )*(1. + 0.01*std::cos(Kx*Xi(i)));\n    }\n  }\n  f.write( c.output_dir / \"init.dat\" );\n\n  unsigned int i_t = 0;\n  double current_time = 0.;\n  double dt =  0.1*f.step.dv/0.6;\n  //double dt = 1.433*f.step.dv;\n\n  std::vector<double> ee;   ee.reserve(int(std::ceil(c.Tf/dt))+1);\n  std::vector<double> Emax; Emax.reserve(int(std::ceil(c.Tf/dt))+1);\n  std::vector<double> H;    H.reserve(int(std::ceil(c.Tf/dt))+1);\n  std::vector<double> Ec;   Ec.reserve(int(std::ceil(c.Tf/dt))+1);\n\n  std::vector<double> times; times.reserve(int(std::ceil(c.Tf/dt))+1);\n\n  // lambda to save data, any time you want, where you want\n  auto save_data = [&] ( std::string && suffix ) -> void {\n    suffix = c.name + suffix;\n\n    // save temporel data\n    auto dt_y = [&,count=0] (auto const& y) mutable {\n      std::stringstream ss; ss<<times[count++]<<\" \"<<y;\n      return ss.str();\n    };\n    c << monitoring::data( \"ee_\"+suffix+\".dat\"   , ee   , dt_y );\n    c << monitoring::data( \"Emax_\"+suffix+\".dat\" , Emax , dt_y );\n    c << monitoring::data( \"H_\"+suffix+\".dat\"    , H    , dt_y );\n\n    // save distribution function\n    f.write( c.output_dir / (\"vp_\"+suffix+\".dat\") );\n  };\n\n  // to stop simulation at any time (and save data)\n  signal_handler::signal_handler<SIGINT,SIGILL>::handler( [&]( int signal ) -> void {\n    std::cerr << \"\\n\\033[41;97m ** End of execution after signal \" << signal << \" ** \\033[0m\\n\";\n    std::cerr << \"\\033[38;5;202msave data...\\033[0m\\n\";\n    save_data(\"_SIGINT\");\n  });\n\n  // space scheme\n  auto wenol = [&](field<double,1>const& f , ublas::vector<double> const& E )->field<double,1> { return wenolin::trp_v(f,E); };\n  auto weno  = [&](field<double,1>const& f , ublas::vector<double> const& E )->field<double,1> { return weno::trp_v(f,E); };\n  auto cd2   = [&](field<double,1>const& f , ublas::vector<double> const& E )->field<double,1> { return o2::trp_v(f,E); };\n\n  // time scheme init\n  //expRK::HochbruckOstermann<poisson<double>> rk(c.Nx,c.Nv,f.range.len_x(),f.shape(),v,kx,cd2);\n  //expRK::Krogstad<poisson<double>> rk(c.Nx,c.Nv,f.range.len_x(),f.shape(),v,kx,cd2);\n  //lawson::RK33<poisson<double>> rk(c.Nx,c.Nv,f.range.len_x(),f.shape(),v,kx,weno);\n  lawson::RK44<poisson<double>> rk(c.Nx,c.Nv,f.range.len_x(),f.shape(),v,kx,weno);\n\n  rk.E = rk.poisson_solver(f.density());\n  {\n    Emax.push_back( std::abs(*std::max_element( rk.E.begin() , rk.E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} )) );\n    double electric_energy = 0.;\n    for ( const auto & ei : rk.E ) { electric_energy += ei*ei*f.step.dx; }\n    ee.push_back( std::sqrt(electric_energy) );\n    H.push_back( energy(f,rk.E) );\n    Ec.push_back( kinetic_energy(f) );\n    times.push_back( 0. );\n  }\n\n\n  while (  current_time < c.Tf ) {\n    std::cout<<\" [\"<<std::setw(5)<<i_t<<\"] \"<< current_time <<\"\\r\"<<std::flush;\n    \n    f = rk(f,dt);\n\n    // end of time loop\n\n    // MONITORING\n    rk.E = rk.poisson_solver(f.density());\n    Emax.push_back( std::abs(*std::max_element( rk.E.begin() , rk.E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} )) );\n    double electric_energy = 0.;\n    for ( const auto & ei : rk.E ) { electric_energy += ei*ei*f.step.dx; }\n    ee.push_back( std::sqrt(electric_energy) );\n    H.push_back( energy(f,rk.E) );\n    Ec.push_back( kinetic_energy(f) );\n\n    //dt = std::min( 0.1 , SIGMA*f.step.dv/Emax[i_t] );\n\n    // increment time\n    ++i_t;\n    current_time += dt;\n    times.push_back( current_time );\n  } // while (  i_t*dt < Tf )\n  std::cout<<\" [\"<<std::setw(5)<<i_t<<\"] \"<<i_t*dt <<std::endl;\n\n  //f.write( c.output_dir / \"vp.dat\" );\n\n  save_data(\"\");\n/*\n  of.open( c.output_dir / \"ee.dat\" );\n  std::transform( ee.begin() , ee.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dt_y );\n  of.close();\n  \n  of.open( c.output_dir / \"Emax.dat\" );\n  std::transform( Emax.begin() , Emax.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dt_y );\n  of.close();\n  \n  of.open( c.output_dir / \"H.dat\" );\n  std::transform( H.begin() , H.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dt_y );\n  of.close();\n  \n  of.open( c.output_dir / \"Ec.dat\" );\n  std::transform( Ec.begin() , Ec.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dt_y );\n  of.close();\n*/\n  std::ofstream of;\n  auto dx_y = [&,count=0](auto const& y) mutable { std::stringstream ss; ss<< f.step.dx*(count++) <<\" \"<<y; return ss.str(); };\n\n  of.open( c.output_dir / \"E.dat\" );\n  std::transform( rk.E.begin() , rk.E.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dx_y );\n  of.close();\n\n  auto rho = f.density();\n  of.open( c.output_dir / \"rho.dat\" );\n  std::transform( rho.begin() , rho.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dx_y );\n  of.close();\n\n  auto J = f.courant();\n  of.open( c.output_dir / \"J.dat\" );\n  std::transform( J.begin() , J.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dx_y );\n  of.close();\n\n  of.open( c.output_dir / \"energy.dat\" );\n  for ( auto i=0 ; i<times.size() ; ++i ) {\n    of << times[i] << \" \" << ee[i] << \" \" << Ec[i] << \" \" << H[i] << \" \" << ee[i] + Ec[i] << \"\\n\";\n  }\n  of.close();\n\n  for (field<double,2>::size_type k=0 ; k<f.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<f.size(1) ; ++i ) {\n      f[k][i] -= tb_MC(Xi(i),Vk(k)) + (tb_M1(Xi(i),Vk(k)) + tb_M2(Xi(i),Vk(k)) )*(1. + 0.01*std::cos(Kx*Xi(i)));\n    }\n  }\n  f.write( c.output_dir / \"diff.dat\" );\n\n  return 0;\n}\n", "meta": {"hexsha": "0d6f9695565d0387b76d787734a82a8174233fce", "size": 9723, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/cmp_tb.cc", "max_stars_repo_name": "Kivvix/miMaS", "max_stars_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-03T22:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-29T06:12:07.000Z", "max_issues_repo_path": "code/cmp_tb.cc", "max_issues_repo_name": "Kivvix/miMaS", "max_issues_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_issues_repo_licenses": ["MIT"], "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/cmp_tb.cc", "max_forks_repo_name": "Kivvix/miMaS", "max_forks_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-29T06:17:16.000Z", "avg_line_length": 36.8295454545, "max_line_length": 140, "alphanum_fraction": 0.5509616374, "num_tokens": 3553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5190696192513375}}
{"text": "#include \"Math/gfp.h\"\n#include \"Math/gf2n.h\"\n#include \"Networking/sockets.h\"\n#include \"Tools/int.h\"\n#include \"Math/Setup.h\"\n#include \"Auth/fake-stuff.h\"\n#include \"Eigen/Dense\"\n#include \"json/json.hpp\"\n#include<gmp.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZ_pXFactoring.h>\n\n#include <sodium.h>\n#include <iostream>\n#include <cstdio>\n#include <sstream>\n#include <fstream>\n#include <cstdlib>\n\nusing namespace NTL;\n\n// Add the private input value to triple[0] and send to each spdz engine.\nvoid send_private_inputs(vector<gfp>& values, vector<int>& sockets, int nparties)\n{\n    int num_inputs = values.size();\n    octetStream os;\n    vector< vector<gfp> > triples(num_inputs, vector<gfp>(3));\n    vector<gfp> triple_shares(3);\n\n    // Receive num_inputs triples from SPDZ\n    for (int j = 0; j < nparties; j++)\n    {\n        os.reset_write_head();\n        os.Receive(sockets[j]);\n\n        for (int j = 0; j < num_inputs; j++)\n        {\n            for (int k = 0; k < 3; k++)\n            {\n                triple_shares[k].unpack(os);\n                triples[j][k] += triple_shares[k];\n            }\n        }\n    }\n\n    // Check triple relations (is a party cheating?)\n    for (int i = 0; i < num_inputs; i++)\n    {\n        if (triples[i][0] * triples[i][1] != triples[i][2])\n        {\n            cout << triples[i][0] << \" , \" << triples[i][1] << \" , \" << triples[i][2] << endl;\n            cerr << \"Incorrect triple at \" << i << \", aborting\\n\";\n            exit(1);\n        }\n    }\n\n    os.reset_write_head();\n    // Send inputs + triple[0], so SPDZ can compute shares of each value\n    for (int i = 0; i < num_inputs; i++)\n    {\n        gfp y = values[i] + triples[i][0];\n        y.pack(os);\n        cout << y << \" , \";\n    }\n    for (int j = 0; j < nparties; j++)\n        os.Send(sockets[j]);\n}\n\n// Assumes that Scripts/setup-online.sh has been run to compute prime\nvoid initialise_fields(const string& dir_prefix)\n{\n  int lg2;\n  bigint p;\n\n  string filename = dir_prefix + \"Params-Data\";\n  cout << \"loading params from: \" << filename << endl;\n\n  ifstream inpf(filename.c_str());\n  if (inpf.fail()) { throw file_error(filename.c_str()); }\n  inpf >> p;\n  inpf >> lg2;\n  inpf.close();\n\n  gfp::init_field(p);\n  gf2n::init_field(lg2);\n}\n\n// Based off of \nvector<gfp> keygen(int primeLength) {\n    ZZ p, q;\n    GenPrimePair(p, q, primeLength);\n    ZZ n = p * q;\n    ZZ g = n + 1;\n    ZZ phi = (p - 1) * (q - 1);\n    // LCM(p, q) = p * q / GCD(p, q);\n   \t// ZZ lambda = phi / GCD(p - 1, q - 1);\n   \tZZ lambda = phi;\n    ZZ mu = InvMod(lambda, modulus);\n\n    vector<gfp> keys(4);\n    keys[0] = n;\n    keys[1] = g;\n    keys[2] = lambda;\n    keys[3] = mu;\n    return keys;\n}\n\n\n/*\ngfp receive_one_result(vector<int>& sockets, int nparties)\n{\n    vector<gfp> output_values(3);\n    octetStream os;\n    for (int i = 0; i < nparties; i++)\n    {\n        os.reset_write_head();\n        os.Receive(sockets[i]);\n        for (unsigned int j = 0; j < 3; j++)\n        {\n            gfp value;\n            value.unpack(os);\n            output_values[j] += value;            \n        }\n    }\n\n    if (output_values[0] * output_values[1] != output_values[2])\n    {\n        cerr << \"Unable to authenticate output value as correct, aborting.\" << endl;\n        exit(1);\n    }\n    return output_values[0];\n}\n\n\n\nvector<double> receive_result(vector<int>& sockets, int nparties, int NUM_COLUMNS)\n{\n    cout << \"Receiving matrix\" << endl;\n    vector<double> output_values(NUM_COLUMNS);    \n    octetStream os;\n    for (int i = 0; i < NUM_COLUMNS; i++)\n    {\n        //gfp gfp_val;\n        gfp gfp_val = receive_one_result(sockets, nparties);\n\n\n        const gfp gfp_regular = gfp_val;\n        bigint val;\n        to_bigint(val, gfp_regular);\n\n        bigint val_negate;\n        gfp_val.negate();\n        to_bigint(val_negate, gfp_val);\n\n\n        double converted_double = mpz_get_d(val.get_mpz_t()) / pow(2, 20);\n        double converted_double_negate = -1 * mpz_get_d(val_negate.get_mpz_t()) / pow(2, 20);\n        cout << \"Converted double \" << converted_double << endl;\n        cout << \"Converted double negative \" << converted_double_negate << endl;\n        if (abs(converted_double) < 10) {\n            output_values[i] = converted_double;\n        } else {\n            output_values[i] = converted_double_negate;\n        }\n        //cout << \"received \" << output_values[i] << endl;\n    }\n\n    return output_values;\n}\n*/\n\n\n\n\n\n\nvoid func(int argc, char** argv) {\n    cout << argc;\n    cout << argv;\n    return;\n}\n\nint main(int argc, char** argv) {\n    \n    //srand(time(NULL));\n    clock_t start;\n    double duration;\n    int port_base = 14000;\n    //int nparties = 2;\n\n    //Shift all numbers over by 20 bits\n    int numShift = 20;\n\n    //string host_names[] = {\"ec2-52-39-162-238.us-west-2.compute.amazonaws.com\", \"ec2-34-223-215-198.us-west-2.compute.amazonaws.com\", \"ec2-23-20-124-131.compute-1.amazonaws.com\", \"ec2-52-73-142-253.compute-1.amazonaws.com\"};\n\n\tstring host_names[] = {\"localhost\", \"localhost\", \"localhost\", \"localhost\"};\n    if (argc < 1) {\n        cout << \"Please provide client id\" << endl;\n        exit(0);\n    }\n\n\n    int nparties = atoi(argv[2]);\n    // Default prime length to 128 bits\n    int prime_length = 128;\n    // Init\n    string prep_data_prefix = get_prep_dir(nparties, 128, 128);\n    initialise_fields(prep_data_prefix);\n\n\n\n\n    vector<int> sockets(nparties);\n    \n    for (int i = 0; i < nparties; i++)\n    {\n        set_up_client_socket(sockets[i], host_names[i].c_str(), port_base + i);\n    }\n    cout << \"Finish setup socket connections to SPDZ engines.\" << endl;\n    \n    start = clock();\n\n    vector<gfp> keys = keygen(prime_length);\n    send_private_inputs(values, sockets, nparties);\n    cout << \"Sent private inputs to each SPDZ engine, waiting for result...\" << endl;\n\n    // Get the result back (client_id of winning client)\n    //vector<double> result = receive_result(sockets, nparties, cols);\n\n\n    duration = (clock() - start ) / (double) CLOCKS_PER_SEC;\n    printf(\" Took %f seconds for Paillier Keygen\", duration);\n    \n    for (int i = 0; i < nparties; i++) {\n        close_client_socket(sockets[i]);\n    }\n    \n    func(argc, argv);\n}\n", "meta": {"hexsha": "c3f5fd6cedc8a5094f80fa05394b9952a99e1f4b", "size": 6157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ExternalIO/paillier-client.cpp", "max_stars_repo_name": "ryandeng1/SPZD", "max_stars_repo_head_hexsha": "8a0289afd03acd726099eab2711bac0bf91954bb", "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": "ExternalIO/paillier-client.cpp", "max_issues_repo_name": "ryandeng1/SPZD", "max_issues_repo_head_hexsha": "8a0289afd03acd726099eab2711bac0bf91954bb", "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": "ExternalIO/paillier-client.cpp", "max_forks_repo_name": "ryandeng1/SPZD", "max_forks_repo_head_hexsha": "8a0289afd03acd726099eab2711bac0bf91954bb", "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": 25.6541666667, "max_line_length": 226, "alphanum_fraction": 0.5796654215, "num_tokens": 1737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5190186408990495}}
{"text": "/*!\n* \\file GrapheneFloquet.cpp\n*\n*\n* \\author Author: D. Gagnon <denisg6@hotmail.com>\n*/\n\n// Include some headers\n#include <iostream>\n#include <fstream>\n#include <armadillo>\n#include <cmath>\n#include <complex>\n\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n\n#include \"GrapheneFloquet.hpp\"\n#include \"Utils.hpp\"\n\n/// Main function\nint main(int argc, char *argv[])\n{\n\n    // Parse parameter file\n    boost::property_tree::ptree pt;\n    boost::property_tree::ini_parser::read_ini(\"GrapheneFloquet.ini\", pt);\n\n    // Problem parameters\n    double freq  =          std::stof(pt.get<std::string>(\"Parameters.frequency\"));  // Angular frequency in Hz\n    double E0 =             std::stof(pt.get<std::string>(\"Parameters.E0\"));         // Peak electric field in V/m\n    size_t nblocks =  std::stoi(pt.get<std::string>(\"Parameters.nblocks\"));    // Envelope frequency, in units of freq\n\n    // Parameter sweep\n    double xmin =   std::stof(pt.get<std::string>(\"Sweep.xmin\")); // Minimum frequency in sweep\n    double xmax =   std::stof(pt.get<std::string>(\"Sweep.xmax\")); // Minimum frequency in sweep\n    size_t x_elem =    std::stoi(pt.get<std::string>(\"Sweep.xnum\"));\n\n    // Parameter sweep\n    double ymin =   std::stof(pt.get<std::string>(\"Sweep.ymin\")); // Minimum frequency in sweep\n    double ymax =   std::stof(pt.get<std::string>(\"Sweep.ymax\")); // Minimum frequency in sweep\n    size_t y_elem =    std::stoi(pt.get<std::string>(\"Sweep.ynum\"));\n\n    // Process input variables (angular frequency units)\n    double omega = 2.0*M_PI*freq;     // Angular frequency\n\n    // Meshgrid (vectors of parameters)\n    auto xvec = arma::linspace(xmin, xmax, x_elem);\n    auto yvec = arma::linspace(ymin, ymax, y_elem);\n\n    // Prepare output file\n    // std::ofstream outfile;\n    // outfile.open(\"quasienergies.dat\");\n\n    // Prepare output file for transition probabilities\n    std::ofstream outfile2;\n    // outfile2.open(\"kmap.dat\");\n\n    // Variables to store probability values\n    auto probvec = arma::mat(y_elem,x_elem);\n    auto probvec_sigma = arma::mat(y_elem,x_elem);\n\n    // Variables to store quasienergy values\n    auto quasi0 = arma::mat(y_elem,x_elem);\n    auto quasi1 = arma::mat(y_elem,x_elem);\n    auto quasi2 = arma::mat(y_elem,x_elem);\n\n    // Variables for loops\n    size_t id, id2;\n    double prob = 0.0;\n    double prob_sigma = 0.0; // Trans. prob. between sigma_z eigenstates\n\n    // Loop for each K value and compute probability\n    # pragma omp parallel for default(shared) private (id, id2, prob, prob_sigma)\n    for (id=0; id < y_elem; id++)\n    {\n        // Initialize probabilities (will be passed by reference)\n        for (id2=0; id2 < x_elem; id2++)\n        {\n            // Compute energies and transition probability\n            auto Energies = QuasiEnergies(xvec[id2],yvec[id],omega,E0,nblocks, prob, prob_sigma);\n\n            // Store in arrays\n            probvec(id,id2) = prob;\n            probvec_sigma(id,id2) = prob_sigma;\n\n            quasi0(id,id2) = Energies[Energies.n_elem/2 - 1]; // Quasi-energ.\n            quasi1(id,id2) = Energies[Energies.n_elem/2];\n            quasi2(id,id2) = Energies[Energies.n_elem/2 + 1];\n        }\n\n    }\n\n    // Save Floquet Data\n    probvec.save(\"probability.dat\", arma::raw_ascii);\n\n    // Save parameters vector\n    xvec.save(\"xvec.dat\", arma::raw_ascii);\n    yvec.save(\"yvec.dat\", arma::raw_ascii);\n\n\n    quasi0.save(\"quasi0.dat\", arma::raw_ascii);\n    quasi1.save(\"quasi1.dat\", arma::raw_ascii);\n    quasi2.save(\"quasi2.dat\", arma::raw_ascii);\n\n    // Save parameters vector\n    xvec.save(\"xvec.dat\", arma::raw_ascii);\n    yvec.save(\"yvec.dat\", arma::raw_ascii);\n\n    return 0;\n\n    /*\n    auto Gamma = GammaValues(2.30,0.0,316227766016837.94,1e10,1);\n\n    for(auto it = Gamma.begin(); it != Gamma.end(); it++)\n    {\n        std::cout << *it << std::endl;\n    }\n\n    double prob = 0.0;\n    double prob_sigma = 0.0;\n    auto Quasi = QuasiEnergies(2.30,0.0,316227766016837.94,1e10,1, prob, prob_sigma);\n    */\n}\n", "meta": {"hexsha": "4878cd5ddce1fede0a3904120838613f505997b0", "size": 4026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulations/GrapheneFloquet.cpp", "max_stars_repo_name": "DenGagn/phdm", "max_stars_repo_head_hexsha": "1412cd8730806f08d80e5faa00d854b95559207d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-24T02:07:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-24T02:07:41.000Z", "max_issues_repo_path": "simulations/GrapheneFloquet.cpp", "max_issues_repo_name": "DenGagn/phdm", "max_issues_repo_head_hexsha": "1412cd8730806f08d80e5faa00d854b95559207d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulations/GrapheneFloquet.cpp", "max_forks_repo_name": "DenGagn/phdm", "max_forks_repo_head_hexsha": "1412cd8730806f08d80e5faa00d854b95559207d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.208, "max_line_length": 118, "alphanum_fraction": 0.6363636364, "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5190186399167273}}
{"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_ATANH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ATANH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-hyperbolic\n    This function object returns the hyperbolic tangent argument \\f$\\frac12\\log\\frac{1+x}{1-x}\\f$\n\n    @par Header <boost/simd/function/atanh.hpp>\n\n    @see cosh, sinh, acosh, asinh, atanh, asech, acoth, acsch\n\n    @par Example:\n\n      @snippet atanh.cpp atanh\n\n    @par Possible output:\n\n      @snippet atanh.txt atanh\n\n\n  **/\n  IEEEValue atanh(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/atanh.hpp>\n#include <boost/simd/function/simd/atanh.hpp>\n\n#endif\n", "meta": {"hexsha": "77da213f606ecd68001be5cc408781fb2e1a2b94", "size": 1069, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/atanh.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/function/atanh.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/function/atanh.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": 23.7555555556, "max_line_length": 100, "alphanum_fraction": 0.582787652, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.519018634624792}}
{"text": "// Copyright (c) 2015-2018, CNRS\n// Authors: Justin Carpentier <jcarpent@laas.fr>\n\n#ifndef __multicontact_api_math_nrand_hpp__\n#define __multicontact_api_math_nrand_hpp__\n\n#include <cmath>\n#include <cstdlib>\n#include <boost/math/constants/constants.hpp>\n\nnamespace multicontact_api\n{\n  namespace math\n  {\n\n    template<typename Scalar>\n    inline Scalar nrand()\n    {\n      const Scalar two_pi = 2 * boost::math::constants::pi<Scalar>();\n      const Scalar eps = std::numeric_limits<Scalar>::min();\n      using std::rand;\n      using std::cos;\n      using std::sqrt;\n      using std::log;\n\n      Scalar u1, u2;\n      const Scalar RAND_MAX_INV = (1.0 / RAND_MAX);\n      do\n      {\n        u1 = (Scalar)rand() * RAND_MAX_INV;\n        u2 = (Scalar)rand() * RAND_MAX_INV;\n      }\n      while(u1 <= eps);\n\n      Scalar z0 = sqrt(-2.0 * log(u1)) * cos(two_pi * u2);\n\n      return z0;\n\n    }\n  }\n}\n\n#endif // ifndef __multicontact_api_math_nrand_hpp__\n", "meta": {"hexsha": "9575f0fcfdced14d2e22da3ffdeaa573700cc53c", "size": 945, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/multicontact-api/math/nrand.hpp", "max_stars_repo_name": "pFernbach/multicontact-api", "max_stars_repo_head_hexsha": "efe4cf25d37aba9184875df6036a864d7aa34b88", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-17T09:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T09:19:05.000Z", "max_issues_repo_path": "include/multicontact-api/math/nrand.hpp", "max_issues_repo_name": "pFernbach/multicontact-api", "max_issues_repo_head_hexsha": "efe4cf25d37aba9184875df6036a864d7aa34b88", "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/multicontact-api/math/nrand.hpp", "max_forks_repo_name": "pFernbach/multicontact-api", "max_forks_repo_head_hexsha": "efe4cf25d37aba9184875df6036a864d7aa34b88", "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": 21.4772727273, "max_line_length": 69, "alphanum_fraction": 0.6328042328, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6261241842048093, "lm_q1q2_score": 0.5190186298240175}}
{"text": "//\n// Created by dominik on 25.06.21.\n//\n\n#ifndef SQSGENERATOR_STRUCTURE_UTILS_HPP\n#define SQSGENERATOR_STRUCTURE_UTILS_HPP\n\n\n#include \"types.hpp\"\n#include \"utils.hpp\"\n#include <vector>\n#include <limits>\n#include <algorithm>\n#include <boost/multi_array.hpp>\n#include <boost/log/trivial.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/storage.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\nusing namespace boost;\nusing namespace boost::numeric::ublas;\n\n\nnamespace sqsgenerator::utils {\n\n        template<typename T>\n        multi_array<T, 3> pbc_shortest_vectors(const matrix<T> &lattice, const matrix<T> &coords, bool frac_coords = false){\n            const matrix<T> cart_coords(frac_coords ? prod(coords, lattice): coords);\n            auto num_atoms {static_cast<index_t>(coords.size1())};\n            auto a {row(lattice, 0)};\n            auto b {row(lattice, 1)};\n            auto c {row(lattice, 2)};\n\n            std::vector<int> axis {-1, 0, 1};\n            multi_array<T, 3> vecs(boost::extents[num_atoms][num_atoms][3]);\n            // pi1 = position_index_1\n            // pi2 = position_index_2\n            for (index_t pi1 = 0; pi1 < num_atoms; pi1++) {\n                auto p1 {row(cart_coords, pi1)};\n                for (index_t pi2 = pi1+1; pi2 < num_atoms; pi2++) {\n                    auto p2 {row(cart_coords, pi2)};\n                    T norm {std::numeric_limits<T>::max()};\n                    for (auto &i : axis) {\n                        for (auto &j: axis) {\n                            for (auto &k: axis) {\n                                auto t = i * a + j * b + k * c;\n                                auto diff = p1 - (t + p2);\n                                T image_norm {norm_2(diff)};\n                                if (image_norm < norm) {\n                                    norm = image_norm;\n                                    for (index_t dim = 0; dim < 3; dim++) {\n                                        vecs[pi1][pi2][dim] = diff(dim);\n                                        vecs[pi2][pi1][dim] = -diff(dim);\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n\n            return vecs;\n        }\n\n        template<typename T>\n        multi_array<T, 3> pbc_shortest_vectors(const std::vector<T> &lattice, const std::vector<T> &coords,  bool frac_coords = false){\n            assert(lattice.size() == 9);\n            assert(coords.size() % 3 == 0);\n            return pbc_shortest_vectors(matrix_from_vector(3, 3, lattice),\n                                        matrix_from_vector(coords.size() / 3, 3, coords), frac_coords);\n        }\n\n        template<typename MultiArray>\n        multi_array<typename MultiArray::element, 2> distance_matrix(const MultiArray &vecs){\n            typedef typename MultiArray::index index_t;\n            typedef typename MultiArray::element T;\n            auto shape(shape_from_multi_array(vecs));\n            auto num_atoms {static_cast<index_t>(shape[0])};\n            multi_array<T, 2> d2(boost::extents[num_atoms][num_atoms]);\n            for (index_t i = 0; i < num_atoms; i++) {\n                for (index_t j = i; j < num_atoms; j++) {\n                    T norm = std::sqrt(\n                            vecs[i][j][0]*vecs[i][j][0] +\n                            vecs[i][j][1]*vecs[i][j][1] +\n                            vecs[i][j][2]*vecs[i][j][2]);\n                    d2[i][j] = norm;\n                    d2[j][i] = norm;\n                }\n            }\n            return d2;\n        }\n\n\n        template<typename MultiArray>\n        pair_shell_matrix_t shell_matrix(const MultiArray &distance_matrix, const std::vector<typename MultiArray::element> &distances, typename MultiArray::element atol = 1.0e-5, typename MultiArray::element rtol=1.0e-8) {\n\n            typedef typename MultiArray::index index_t;\n            typedef typename MultiArray::element T;\n            auto shape(shape_from_multi_array(distance_matrix));\n            auto num_atoms {static_cast<index_t>(shape[0])};\n            pair_shell_matrix_t shells(boost::extents[num_atoms][num_atoms]);\n            auto is_close_tol = [&atol, &rtol] (T a, T b) {\n                return is_close(a, b, atol, rtol);\n            };\n\n            auto find_shell = [&distances, &is_close_tol] (T distance) {\n                if (distance < 0 ) return -1;\n                if (is_close_tol(distance, 0.0)) return 0;\n                else {\n                    for (size_t i = 0; i < distances.size() - 1; i++) {\n                        T lower_bound {distances[i]}, upper_bound {distances[i+1]};\n                        if ((is_close_tol(distance, lower_bound) or distance > lower_bound) and (is_close_tol(distance, upper_bound) or upper_bound > distance)) {\n                            return static_cast<int>(i+1);\n                        }\n                    }\n                }\n                return static_cast<int>(distances.size());\n            };\n\n            for (index_t i = 0; i < num_atoms; i++) {\n                for (index_t j = i + 1; j < num_atoms; j++) {\n                    int shell {find_shell(distance_matrix[i][j])};\n                    if (shell < 0) throw std::runtime_error(\"A shell was detected which I am not aware of\");\n                    else if (shell == 0 and i != j) {\n                        BOOST_LOG_TRIVIAL(warning) << \"Atoms \" + std::to_string(i) + \" and \" + std::to_string(j) + \" are overlapping! (distance = \" + std::to_string(distance_matrix[i][j])<< \", shell = \" << shell <<\")!\";\n                    }\n                    shells[i][j] = shell;\n                    shells[j][i] = shell;\n                }\n            }\n            return shells;\n        }\n\n    template<typename MultiArray>\n    std::vector<typename MultiArray::element> default_shell_distances(const MultiArray &distance_matrix, typename MultiArray::element atol = 1.0e-5, typename MultiArray::element rtol=1.0e-8) {\n        typedef typename MultiArray::index index_t;\n        typedef typename MultiArray::element T;\n        auto shape(shape_from_multi_array(distance_matrix));\n        auto num_atoms {static_cast<index_t>(shape[0])};\n        std::vector<T> all_distances(distance_matrix.data(), distance_matrix.data() + distance_matrix.num_elements());\n        std::sort(all_distances.begin(), all_distances.end());\n        std::vector<T> shell_dists;\n\n\n        auto is_close_tol = [=] (T a, T b) {\n            return is_close(a, b, atol, rtol);\n        };\n\n        std::function<int(T)> get_shell_index  = [&](T distance){\n            for (auto i = 0; i < shell_dists.size(); i++)  if (is_close_tol(distance, shell_dists[i])) return i;\n            return -1;\n        };\n\n        for (const auto& distance : all_distances) {\n            auto shell_dist_index {get_shell_index(distance)};\n            // We average the distances\n            if (shell_dist_index >= 0) shell_dists[shell_dist_index] = 0.5 * (shell_dists[shell_dist_index] + distance);\n            else shell_dists.push_back(distance);\n            std::sort(shell_dists.begin(), shell_dists.end());\n        }\n\n        // make a sanity check -> we check here that each of the computed coordination shell occurs at least once\n        pair_shell_matrix_t current_shell_matrix(shell_matrix(distance_matrix, shell_dists, atol, rtol));\n        std::set<shell_t> unique_shells(current_shell_matrix.data(), current_shell_matrix.data() + current_shell_matrix.num_elements());\n        if (unique_shells.size() < shell_dists.size()) {\n            auto message = \"The number of of computed (default) shells does not match the occuring shells in the shell matrix (computed: \" + std::to_string(shell_dists.size()) + \" !=\" + \" shell_matrix: \" + std::to_string(unique_shells.size()) + \")\";\n            BOOST_LOG_TRIVIAL(warning) << message;\n            throw std::runtime_error(message);\n        }\n        return shell_dists;\n    }\n\n    std::map<shell_t, index_t> shell_index_map(const pair_shell_weights_t &weights);\n    std::vector<AtomPair> create_pair_list(const pair_shell_matrix_t &shell_matrix, const std::map<shell_t, double> &weights);\n    std::tuple<std::vector<shell_t>, std::vector<double>> compute_shell_indices_and_weights(const pair_shell_weights_t &shell_weights);\n    array_3d_t compute_prefactors(const_pair_shell_matrix_ref_t shell_matrix, const pair_shell_weights_t &shell_weights, const configuration_t &configuration);\n}\n\n#endif //SQSGENERATOR_STRUCTURE_UTILS_HPP\n", "meta": {"hexsha": "af44148e3e885d0c7faa9572d6450394a2864203", "size": 8551, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sqsgenerator/core/include/structure_utils.hpp", "max_stars_repo_name": "dgehringer/sqsgenerator", "max_stars_repo_head_hexsha": "562697166a53f806629e8e1086b381871d9a675e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-16T10:34:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:32:42.000Z", "max_issues_repo_path": "sqsgenerator/core/include/structure_utils.hpp", "max_issues_repo_name": "dgehringer/sqsgenerator", "max_issues_repo_head_hexsha": "562697166a53f806629e8e1086b381871d9a675e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-11-21T05:54:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:56:34.000Z", "max_forks_repo_path": "sqsgenerator/core/include/structure_utils.hpp", "max_forks_repo_name": "dgehringer/sqsgenerator", "max_forks_repo_head_hexsha": "562697166a53f806629e8e1086b381871d9a675e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T14:28:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T14:11:44.000Z", "avg_line_length": 47.5055555556, "max_line_length": 249, "alphanum_fraction": 0.554321132, "num_tokens": 1977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5190186293328567}}
{"text": "#include <iostream>\r\n#include <cinttypes>\r\n#include <vector>\r\n#include <numeric>\r\n#include <iomanip>\r\n\r\nusing namespace std;\r\n\r\n#include <boost/math/distributions/normal.hpp>\r\n\r\ndouble epsilon = 1e-7;\r\ndouble epsilon2 = 1e-24;\r\n\r\ndouble solve(double a, int64_t till) {\r\n    double answer(0.5);\r\n    vector<pair<double, double>> vals{make_pair(0.0, 0.5)};\r\n    double remaining((M_PI * M_PI) / 6 - 1);\r\n#if 0\r\n    double prev_answer = 0;\r\n#endif\r\n    for (int64_t i = 2; i <= till; ++i) {\r\n        double component = ((double)1.0) / ((double)i) / i;\r\n        vector<pair<double, double>> new_vals;\r\n        for (auto v: vals) {\r\n            if (v.first + remaining < a) {\r\n                continue;\r\n            }\r\n\r\n            if (v.first + component > a) {\r\n                answer += v.second / 2.0;\r\n                new_vals.push_back(make_pair(v.first, v.second / 2.0));\r\n            } else {\r\n                new_vals.push_back(make_pair(v.first, v.second / 2.0));\r\n                new_vals.push_back(make_pair(v.first + component, v.second / 2.0));\r\n            }\r\n        }\r\n        remaining -= component;\r\n\r\n        sort(new_vals.begin(), new_vals.end(), greater<pair<double, double>>());\r\n        vals.clear();\r\n        for (auto v: new_vals) {\r\n            if (v.second < epsilon2) {\r\n                continue;\r\n            }\r\n            if (vals.empty() || (vals.back().first - v.first) > epsilon) {\r\n                vals.push_back(v);\r\n            } else {\r\n                vals.back().first = vals.back().first * vals.back().second + v.first * v.second;\r\n                vals.back().second += v.second;\r\n                vals.back().first /= vals.back().second;\r\n            }\r\n        }\r\n\r\n        if (vals.empty()) {\r\n            break;\r\n        }\r\n#if 0\r\n        if (answer - prev_answer > 1e-8) {\r\n            cout << i << \": \" << answer << \", \" << answer - prev_answer << \" (\" << vals.size() << \")\" << endl;\r\n            prev_answer = answer;\r\n        }\r\n#endif\r\n    }\r\n\r\n    // Approximate by normal distribution.\r\n    boost::math::normal_distribution<double> nd(remaining / 2.0, remaining / boost::math::constants::pi<double>() / 2);\r\n    if (!vals.empty()) {\r\n        for (auto v: vals) {\r\n            answer += v.second * (1.0 - boost::math::cdf(nd, a - v.first));\r\n        }\r\n    }\r\n\r\n    return answer;\r\n}\r\n\r\nint main() {\r\n    cout << setprecision(15);\r\n\r\n    //double answer = solve(0.5, 10000000);\r\n    double answer = solve(0.5, 3000);\r\n    cout << setprecision(8);\r\n    cout << answer << endl;\r\n}\r\n", "meta": {"hexsha": "df145bcc1286431394391199d5bfb4c5fc99bba6", "size": 2527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "600-700/689.cpp", "max_stars_repo_name": "Thomaw/Project-Euler", "max_stars_repo_head_hexsha": "bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "600-700/689.cpp", "max_issues_repo_name": "Thomaw/Project-Euler", "max_issues_repo_head_hexsha": "bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "600-700/689.cpp", "max_forks_repo_name": "Thomaw/Project-Euler", "max_forks_repo_head_hexsha": "bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d", "max_forks_repo_licenses": ["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.0833333333, "max_line_length": 120, "alphanum_fraction": 0.4942619707, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5190186293328566}}
{"text": "#include <simulation.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\n#include \"eigenIntegration.hpp\"\n\nnamespace scpp\n{\n\nclass ODE\n{\npublic:\n    ODE(Model::ptr_t model, double dt, const Model::input_vector_t &u0, const Model::input_vector_t &u1);\n    void operator()(const Model::state_vector_t &f, Model::state_vector_t &dfdt, const double t);\n\nprivate:\n    Model::ptr_t model;\n    Model::input_vector_t u0, u1;\n    double dt;\n};\n\nODE::ODE(Model::ptr_t model, double dt, const Model::input_vector_t &u0, const Model::input_vector_t &u1)\n    : model(model), u0(u0), u1(u1), dt(dt) {}\n\nvoid ODE::operator()(const Model::state_vector_t &f, Model::state_vector_t &dfdt, const double t)\n{\n    Model::input_vector_t u = u0 + t / dt * (u1 - u0);\n    model->computef(f, u, dfdt);\n}\n\nvoid simulate(Model::ptr_t model, double dt,\n              const Model::input_vector_t &u0,\n              const Model::input_vector_t &u1,\n              Model::state_vector_t &x)\n{\n    using namespace boost::numeric::odeint;\n    runge_kutta_fehlberg78<Model::state_vector_t, double, Model::state_vector_t, double, vector_space_algebra> stepper;\n\n    ODE ode(model, dt, u0, u1);\n\n    integrate_adaptive(stepper, ode, x, 0., dt, dt / 20.);\n}\n\n} // namespace scpp", "meta": {"hexsha": "079150bd7abd0d352998acd2175a5da8778ba360", "size": 1230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scpp_core/src/simulation.cpp", "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_core/src/simulation.cpp", "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_core/src/simulation.cpp", "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": 27.9545454545, "max_line_length": 119, "alphanum_fraction": 0.6780487805, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938799869521, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.519018624040921}}
{"text": "/******************************************************************************\n * Copyright (C) 2013 by Jerome Maye                                          *\n * jerome.maye@gmail.com                                                      *\n ******************************************************************************/\n\n/** \\file simulate-online.cpp\n    \\brief This file runs a simulation of the calibration problem in iterative\n           mode.\n  */\n\n#include <vector>\n\n#include <boost/make_shared.hpp>\n\n#include <Eigen/Core>\n\n#include <sm/kinematics/rotations.hpp>\n#include <sm/kinematics/three_point_methods.hpp>\n\n#include <aslam/backend/OptimizationProblem.hpp>\n#include <aslam/backend/Optimizer2Options.hpp>\n#include <aslam/backend/SparseQrLinearSystemSolver.hpp>\n#include <aslam/backend/SparseQRLinearSolverOptions.h>\n#include <aslam/backend/GaussNewtonTrustRegionPolicy.hpp>\n#include <aslam/backend/Optimizer2.hpp>\n\n#include <aslam/calibration/statistics/UniformDistribution.h>\n#include <aslam/calibration/statistics/NormalDistribution.h>\n#include <aslam/calibration/data-structures/VectorDesignVariable.h>\n#include <aslam/calibration/geometry/Transformation.h>\n#include <aslam/calibration/base/Timestamp.h>\n#include <truncated-svd-solver/marginalization.h>\n\n#include \"aslam/calibration/2dlrf/utils.h\"\n#include \"aslam/calibration/2dlrf/ErrorTermMotion.h\"\n#include \"aslam/calibration/2dlrf/ErrorTermObservation.h\"\n\nusing namespace aslam::calibration;\nusing namespace aslam::backend;\nusing namespace sm::kinematics;\n\nint main(int argc, char** argv) {\n  // steps to simulate\n  const size_t steps = 5000;\n\n  // timestep size\n  const double T = 0.1;\n\n  // true state\n  std::vector<Eigen::Matrix<double, 3, 1> > x_true;\n  x_true.reserve(steps);\n\n  // integrated odometry\n  std::vector<Eigen::Matrix<double, 3, 1> > x_odom;\n  x_odom.reserve(steps);\n\n  // true control input\n  std::vector<Eigen::Matrix<double, 3, 1> > u_true;\n  const double sineWaveAmplitude = 1.0;\n  const double sineWaveFrequency = 0.01;\n  genSineWavePath(u_true, steps, sineWaveAmplitude, sineWaveFrequency, T);\n\n  // measured control input\n  std::vector<Eigen::Matrix<double, 3, 1> > u_noise;\n  u_noise.reserve(steps);\n\n  // number of landmarks\n  const size_t nl = 17;\n\n  // playground size\n  Eigen::Matrix<double, 2, 1> min(0, 0);\n  Eigen::Matrix<double, 2, 1> max(30, 30);\n\n  // bearing measurements\n  std::vector<std::vector<double> > b;\n  b.reserve(steps);\n  b.push_back(std::vector<double>(nl, 0));\n\n  // range measurements\n  std::vector<std::vector<double> > r;\n  r.reserve(steps);\n  r.push_back(std::vector<double>(nl, 0));\n\n  // covariance matrix for motion model\n  Eigen::Matrix<double, 3, 3> Q = Eigen::Matrix<double, 3, 3>::Zero();\n  Q(0, 0) = 0.00044;\n  Q(1, 1) = 1e-6;\n  Q(2, 2) = 0.00082;\n\n  // covariance matrix for observation model\n  Eigen::Matrix<double, 2, 2> R = Eigen::Matrix<double, 2, 2>::Zero();\n  R(0, 0) = 0.00090;\n  R(1, 1) = 0.00067;\n\n  // landmark positions\n  std::vector<Eigen::Matrix<double, 2, 1> > x_l;\n  UniformDistribution<double, 2>(min, max).getSamples(x_l, nl);\n\n  // true calibration parameters\n  Eigen::Matrix<double, 3, 1> Theta(0.219, 0.1, 0.78);\n\n  // guessed calibration parameters\n//  Eigen::Matrix<double, 3, 1> Theta_hat = Theta +\n//    aslam::calibration::NormalDistribution<3>(\n//    Eigen::Matrix<double, 3, 1>::Zero(),\n//    Eigen::Matrix<double, 3, 3>::Identity() * 1e-2).getSample();\n  Eigen::Matrix<double, 3, 1> Theta_hat(0.23, 0.11, 0.8);\n\n  // initial state\n  Eigen::Matrix<double, 3, 1> x_0(1.0, 1.0, M_PI / 4);\n  x_true.push_back(x_0);\n  x_odom.push_back(x_0);\n  u_noise.push_back(Eigen::Matrix<double, 3, 1>::Zero());\n\n  // simulate\n  for (size_t i = 1; i < steps; ++i) {\n    Eigen::Matrix<double, 3, 3> B = Eigen::Matrix<double, 3, 3>::Identity();\n    B(0, 0) = cos(x_true[i - 1](2));\n    B(0, 1) = -sin(x_true[i - 1](2));\n    B(1, 0) = sin(x_true[i - 1](2));\n    B(1, 1) = cos(x_true[i - 1](2));\n    Eigen::Matrix<double, 3, 1> xk = x_true[i - 1] + T * B * u_true[i];\n    xk(2) = angleMod(xk(2));\n    x_true.push_back(xk);\n    u_noise.push_back(u_true[i] + NormalDistribution<3>(\n      Eigen::Matrix<double, 3, 1>::Zero(), Q).getSample());\n    B(0, 0) = cos(x_odom[i - 1](2));\n    B(0, 1) = -sin(x_odom[i - 1](2));\n    B(1, 0) = sin(x_odom[i - 1](2));\n    B(1, 1) = cos(x_odom[i - 1](2));\n    xk = x_odom[i - 1] + T * B * u_noise[i];\n    xk(2) = angleMod(xk(2));\n    x_odom.push_back(xk);\n    const double ct = cos(x_true[i](2));\n    const double st = sin(x_true[i](2));\n    std::vector<double> rk(nl, 0);\n    std::vector<double> bk(nl, 0);\n    for (size_t j = 0; j < nl; ++j) {\n      const double aa = x_l[j](0) - x_true[i](0) - Theta(0) * ct +\n        Theta(1) * st;\n      const double bb = x_l[j](1) - x_true[i](1) - Theta(0) * st -\n        Theta(1) * ct;\n      const double range = sqrt(aa * aa + bb * bb) + NormalDistribution<1>(\n        0, R(0, 0)).getSample();\n      rk[j] = range;\n      bk[j] = angleMod(atan2(bb, aa) - x_true[i](2) - Theta(2) +\n        NormalDistribution<1>(0, R(1, 1)).getSample());\n    }\n    r.push_back(rk);\n    b.push_back(bk);\n  }\n\n  // landmark guess\n  std::vector<Eigen::Matrix<double, 2, 1> > x_l_hat;\n  initLandmarks(x_l_hat, x_odom, Theta_hat, r, b);\n\n  // create state design variables\n  std::vector<boost::shared_ptr<VectorDesignVariable<3> > > dv_x;\n  dv_x.reserve(steps);\n  for (size_t i = 0; i < steps; ++i) {\n    dv_x.push_back(\n      boost::make_shared<VectorDesignVariable<3> >(x_odom[i]));\n    dv_x[i]->setActive(true);\n  }\n\n  // create landmarks design variables\n  std::vector<boost::shared_ptr<VectorDesignVariable<2> > > dv_x_l;\n  dv_x_l.reserve(nl);\n  for (size_t i = 0; i < nl; ++i) {\n    dv_x_l.push_back(\n      boost::make_shared<VectorDesignVariable<2> >(x_l_hat[i]));\n    dv_x_l[i]->setActive(true);\n  }\n\n  // create calibration parameters design variable\n  auto dv_Theta = boost::make_shared<VectorDesignVariable<3> >(Theta_hat);\n  dv_Theta->setActive(true);\n\n  // batch size\n  const size_t batchSize = 200;\n\n  // mutual information threshold\n  const double miTol = 0.5;\n\n  // batch idx used for optimization\n  std::vector<size_t> batchIdx;\n  batchIdx.reserve(steps / batchSize);\n\n  // calibration parameters record\n  Eigen::Matrix <double, 3, 1> calibParams = dv_Theta->getValue();\n\n  // Sigma record\n  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> SigmaRecord;\n\n  // Sigma determinant record\n  double SigmaDetRecord = 0;\n\n  // iterative optimization\n  for (size_t i = 0; i < steps; i += batchSize) {\n    const double timeStart = Timestamp::now();\n\n    // insert current batch\n    batchIdx.push_back(i);\n\n    // create optimization problem\n    auto problem = boost::make_shared<OptimizationProblem>();\n\n    // add design variables to the problem\n    for (size_t j = 0; j < batchIdx.size(); ++j)\n      for (size_t k = batchIdx[j]; k < batchIdx[j] + batchSize; ++k)\n        problem->addDesignVariable(dv_x[k]);\n    for (size_t j = 0; j < nl; ++j)\n      problem->addDesignVariable(dv_x_l[j]);\n    problem->addDesignVariable(dv_Theta);\n\n    // add error terms to the problem\n    for (size_t j = 0; j < batchIdx.size(); ++j) {\n      for (size_t k = batchIdx[j] + 1; k < batchIdx[j] + batchSize; ++k) {\n        auto e_mot = boost::make_shared<ErrorTermMotion>(dv_x[k - 1].get(),\n          dv_x[k].get(), T, u_noise[k], Q);\n        problem->addErrorTerm(e_mot);\n        for (size_t l = 0; l < nl; ++l) {\n          auto e_obs = boost::make_shared<ErrorTermObservation>(dv_x[k].get(),\n            dv_x_l[l].get(), dv_Theta.get(), r[k][l], b[k][l], R);\n          problem->addErrorTerm(e_obs);\n        }\n      }\n    }\n\n    std::cout << \"Calibration before: \" << calibParams.transpose() << std::endl;\n\n    // optimization round\n    Optimizer2Options options;\n    options.verbose = true;\n    options.linearSystemSolver =\n      boost::make_shared<SparseQrLinearSystemSolver>();\n    options.trustRegionPolicy =\n      boost::make_shared<GaussNewtonTrustRegionPolicy>();\n    SparseQRLinearSolverOptions linearSolverOptions;\n    linearSolverOptions.colNorm = true;\n    linearSolverOptions.qrTol = 0.02;\n    Optimizer2 optimizer(options);\n    optimizer.getSolver<SparseQrLinearSystemSolver>()->setOptions(\n      linearSolverOptions);\n    optimizer.setProblem(problem);\n    optimizer.optimize();\n\n    // Sigma computation\n    aslam::backend::CompressedColumnMatrix<std::ptrdiff_t> Jt =\n        optimizer.getSolver<SparseQrLinearSystemSolver>()->\n        getJacobianTranspose();\n\n    const size_t dim = 3;\n    const size_t numCols = Jt.rows();\n\n    Eigen::MatrixXd NS, CS, Sigma, SigmaP, Omega;\n    cholmod_sparse Jt_cholmod;\n    Jt.getView(&Jt_cholmod);\n    truncated_svd_solver::marginalize(&Jt_cholmod, numCols - dim, NS, CS,\n                                      Sigma, SigmaP, Omega);\n    const double SigmaDet = Sigma.determinant();\n\n    std::cout << \"Calibration after: \" << *dv_Theta << std::endl;\n    std::cout << \"Sigma: \" << std::endl << Sigma << std::endl;\n\n    // decision round\n    if (batchIdx.size() == 1) { // keep if only one batch\n      calibParams = dv_Theta->getValue();\n      SigmaRecord = Sigma;\n      SigmaDetRecord = SigmaDet;\n    }\n    else {\n      // compute mutual information\n      const double mi = 0.5 * log2(SigmaDetRecord / SigmaDet);\n\n      // keep batch if needed\n      if (mi > miTol) {\n        calibParams = dv_Theta->getValue();\n        SigmaRecord = Sigma;\n        SigmaDetRecord = SigmaDet;\n      }\n      else\n        batchIdx.pop_back();\n    }\n\n    const double timeStop = Timestamp::now();\n    std::cout << \"Batch processing time [s]: \" << timeStop - timeStart\n      << std::endl;\n  }\n\n  std::cout << \"Final calibration: \" << calibParams.transpose() << std::endl;\n  std::cout << \"Sigma: \" << std::endl << SigmaRecord << std::endl;\n  std::cout << \"Data used: \" << (batchIdx.size() * batchSize) / (double)steps\n    * 100 << \" %\" << std::endl;\n\n  // output results to file\n  std::ofstream x_true_log(\"x_true.txt\");\n  for (size_t i = 0; i < steps; ++i)\n    x_true_log << x_true[i].transpose() << std::endl;\n  std::ofstream x_odom_log(\"x_odom.txt\");\n  for (size_t i = 0; i < steps; ++i)\n    x_odom_log << x_odom[i].transpose() << std::endl;\n  std::ofstream x_est_log(\"x_est.txt\");\n  for (size_t i = 0; i < batchIdx.size(); ++i)\n    for (size_t j = batchIdx[i]; j < batchIdx[i] + batchSize; ++j)\n      x_est_log << *(dv_x[j]) << std::endl;\n  std::ofstream l_log(\"l.txt\");\n  for (size_t i = 0; i < nl; ++i)\n    l_log << x_l[i].transpose() << std::endl;\n  std::ofstream l_est_log(\"l_est.txt\");\n  for (size_t i = 0; i < nl; ++i)\n    l_est_log << *(dv_x_l[i]) << std::endl;\n\n  // align landmarks\n  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> l =\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Zero(3, nl);\n  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> l_est =\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Zero(3, nl);\n  for (size_t i = 0; i < nl; ++i) {\n    l(0, i) = x_l[i](0);\n    l(1, i) = x_l[i](1);\n    l_est(0, i) = dv_x_l[i]->getValue()(0);\n    l_est(1, i) = dv_x_l[i]->getValue()(1);\n  }\n  Transformation<double, 3> trans(threePointSvd(l, l_est));\n  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> l_est_trans =\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Zero(3, nl);\n  for (size_t i = 0; i < nl; ++i)\n    l_est_trans.col(i) = trans(l_est.col(i));\n  std::ofstream l_est_trans_log(\"l_est_trans.txt\");\n  for (size_t i = 0; i < nl; ++i)\n    l_est_trans_log << l_est_trans.col(i).head<2>().transpose() << std::endl;\n\n  // align poses\n  std::vector<Eigen::Matrix<double, 3, 1> > x_est_trans;\n  x_est_trans.reserve(steps);\n  std::ofstream x_est_trans_log(\"x_est_trans.txt\");\n  for (size_t i = 0; i < batchIdx.size(); ++i)\n    for (size_t j = batchIdx[i]; j < batchIdx[i] + batchSize; ++j) {\n      Eigen::Matrix<double, 3, 1> pose((Eigen::Matrix<double, 3, 1>()\n        << dv_x[j]->getValue().head<2>(), 0).finished());\n      trans.transform(pose, pose);\n      pose(2) = dv_x[j]->getValue()(2);\n      x_est_trans.push_back(pose);\n      x_est_trans_log << pose.transpose() << std::endl;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "9943f8473319a6392763613383c0165c800017a4", "size": 12086, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "incremental_calibration_examples/incremental_calibration_examples_2dlrf/src/2dlrf/simulate-online.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_2dlrf/src/2dlrf/simulate-online.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_2dlrf/src/2dlrf/simulate-online.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.5314285714, "max_line_length": 80, "alphanum_fraction": 0.6202217442, "num_tokens": 3689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.519018624040921}}
{"text": "#include \"point_transform_function.hpp\"\n#include \"cgal_typedefs.hpp\"\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Regular_triangulation_3.h>\n//#include <CGAL/Regular_triangulation_euclidean_traits_3.h>\n#include <CGAL/Fixed_alpha_shape_3.h>\n#include <CGAL/Triangulation_vertex_base_with_info_3.h>\n#include <CGAL/Fixed_alpha_shape_vertex_base_3.h>\n#include <CGAL/Fixed_alpha_shape_cell_base_3.h>\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <utility>\n#include <iterator>\n#include <stdexcept>\n\nnamespace busv{\n\ntemplate <typename T>\nT* init_mem(size_t size, const T& init_val){\n\tT* mem = (T*)malloc(sizeof(T)*size);\n\tif(!mem){\n\t\tthrow std::runtime_error(\"Insufficient memory\");\n\t}\n\tfor(size_t i = 0; i < size; ++i){\n\t\tmem[i] = init_val;\n\t}\n\treturn mem;\n}\n\ntemplate <typename it_t, typename AS, typename T>\nsize_t countNotType(it_t it, it_t end, const AS& as, T type){\n\tsize_t num = 0;\n\tfor(;it!=end;++it){\n\t\tif(as.classify(*it) != type){\n\t\t\t++num;\n\t\t}\n\t}\n\treturn num;\n}\n\ntemplate <typename it_t, typename AS, typename T>\nsize_t countNotType2(it_t it, it_t end, const AS& as, T type){\n\tsize_t num = 0;\n\tfor(;it!=end;++it){\n\t\tif(as.classify(it) != type){\n\t\t\t++num;\n\t\t}\n\t}\n\treturn num;\n}\n\ntemplate <typename T, typename U>\nvoid alpha_shapes(\n\tU num_points, T alpha, \n\tconst T* points, const T* weights, \n\tU* num_edges, U** edges, \n\tU* num_triangles, U** triangles, \n\tU* num_tetrahedra, U** tetrahedra\n){\n\t//typedef cgal_typedefs<T, U> cgt;\n\t//typedef typename cgt::Fixed_alpha_shape_3 Fixed_alpha_shape_3;\n\t//typedef typename cgt::Triangulation_3 Triangulation_3;\n\ttypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n\n\t//fixed weighted example from docs\n\t/*typedef CGAL::Regular_triangulation_vertex_base_3<K>      Vbb;\n\ttypedef CGAL::Fixed_alpha_shape_vertex_base_3<K,Vbb>      Vb;\n\ttypedef CGAL::Regular_triangulation_cell_base_3<K>        Rcb;\n\ttypedef CGAL::Fixed_alpha_shape_cell_base_3<K,Rcb>        Cb;\n\ttypedef CGAL::Triangulation_data_structure_3<Vb,Cb>       Tds;\n\ttypedef CGAL::Regular_triangulation_3<K,Tds>              Triangulation_3;\n\ttypedef CGAL::Fixed_alpha_shape_3<Triangulation_3>        Fixed_alpha_shape_3;*/\n\n\ttypedef CGAL::Regular_triangulation_vertex_base_3<K> Vbb;\n\ttypedef CGAL::Triangulation_vertex_base_with_info_3<U, K, Vbb> Tb;\n\ttypedef CGAL::Fixed_alpha_shape_vertex_base_3<K, Tb> Vb;\n\n\ttypedef CGAL::Regular_triangulation_cell_base_3<K> Rcb;\n\ttypedef CGAL::Fixed_alpha_shape_cell_base_3<K, Rcb> Fb;\n\n\ttypedef CGAL::Triangulation_data_structure_3<Vb,Fb> Tds;\n\ttypedef CGAL::Regular_triangulation_3<K,Tds> Triangulation_3;\n\ttypedef CGAL::Fixed_alpha_shape_3<Triangulation_3> Fixed_alpha_shape_3;\n\t//typedef typename Fixed_alpha_shape_3::Cell_handle Cell_handle;\n\t//typedef typename Fixed_alpha_shape_3::Vertex_handle Vertex_handle;\n\ttypedef typename Fixed_alpha_shape_3::Cell Cell;\n\ttypedef typename Fixed_alpha_shape_3::Facet Facet;\n\ttypedef typename Fixed_alpha_shape_3::Edge Edge;\n\t//typedef typename Triangulation_3::Weighted_point Weighted_point;\n\t//typedef typename Triangulation_3::Bare_point Bare_point;\n\n\tbusv::PointTransformFunction<Triangulation_3, U, T> tfunc(points, weights);\n\t//unsigned int i;\n\n\t//build one alpha_shape with alpha=0\n\tFixed_alpha_shape_3 as(\n\t\tboost::make_transform_iterator(boost::counting_iterator<U>(0), tfunc), \n\t\tboost::make_transform_iterator(boost::counting_iterator<U>(num_points), tfunc), \n\t\talpha\n\t);\n\n\n\t*num_edges = countNotType(as.finite_edges_begin(), as.finite_edges_end(), as, Fixed_alpha_shape_3::EXTERIOR);\n\tU* t = *edges = init_mem<U>((*num_edges)*2, 0);\n\ttypedef typename Fixed_alpha_shape_3::Finite_edges_iterator edge_it_t;\n\tfor(edge_it_t it = as.finite_edges_begin(), eit = as.finite_edges_end(); it!= eit; ++it){\n\t\tconst Edge& e = *it;\n\t\tif(as.classify(e) != Fixed_alpha_shape_3::EXTERIOR){\n\t\t\tt[0] = e.first->vertex(e.second)->info();\n\t\t\tt[1] = e.first->vertex(e.third)->info();\n\t\t\tt += 2;\n\t\t}\n\t}\n\n\t*num_triangles = countNotType(as.finite_facets_begin(), as.finite_facets_end(), as, Fixed_alpha_shape_3::EXTERIOR);\n\tt = *triangles = init_mem<U>((*num_triangles)*3, 0);\n\ttypedef typename Fixed_alpha_shape_3::Finite_facets_iterator facet_it_t;\n\tfor(facet_it_t it = as.finite_facets_begin(), eit = as.finite_facets_end(); it!= eit; ++it){\n\t\tconst Facet& f = *it;\n\t\t//if(as.classify(f) == Fixed_alpha_shape_3::SINGULAR){\n\t\tif(as.classify(f) != Fixed_alpha_shape_3::EXTERIOR){\n\t\t\tt[0] = f.first->vertex((f.second+1)%4)->info();\n\t\t\tt[1] = f.first->vertex((f.second+2)%4)->info();\n\t\t\tt[2] = f.first->vertex((f.second+3)%4)->info();\n\t\t\tt += 3;\n\t\t}\n\t}\n\n\t*num_tetrahedra = countNotType2(as.finite_cells_begin(), as.finite_cells_end(), as, Fixed_alpha_shape_3::EXTERIOR);\n\tt = *tetrahedra = init_mem<U>((*num_tetrahedra)*4, 0);\n\ttypedef typename Fixed_alpha_shape_3::Finite_cells_iterator cell_it_t;\n\tfor(cell_it_t it = as.finite_cells_begin(), eit = as.finite_cells_end(); it!= eit; ++it){\n\t\tconst Cell& c = *it;\n//\t\tif(as.classify(it) == Fixed_alpha_shape_3::INTERIOR){\n\t\tif(as.classify(it) != Fixed_alpha_shape_3::EXTERIOR){\n\t\t\tt[0] = c.vertex(0)->info();\n\t\t\tt[1] = c.vertex(1)->info();\n\t\t\tt[2] = c.vertex(2)->info();\n\t\t\tt[3] = c.vertex(3)->info();\n\t\t\tt += 4;\n\t\t}\n\t}\n}\t\n\n} //namespace busv\n\n\n", "meta": {"hexsha": "9c5407e0d5855a8b8de67c114e664a4d87bc24fc", "size": 5272, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/alpha_shapes/alpha_shapes.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/alpha_shapes.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/alpha_shapes.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": 35.6216216216, "max_line_length": 116, "alphanum_fraction": 0.7325493171, "num_tokens": 1611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.5190186182578246}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_FUNCTIONS_COMPLEX_GENERIC_SINCOS_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_FUNCTIONS_COMPLEX_GENERIC_SINCOS_HPP_INCLUDED\n#include <nt2/trigonometric/functions/sincos.hpp>\n#include <nt2/include/functions/sincos.hpp>\n#include <nt2/include/functions/sinhcosh.hpp>\n#include <nt2/include/functions/real.hpp>\n#include <nt2/include/functions/imag.hpp>\n#include <nt2/sdk/complex/meta/as_complex.hpp>\n#include <nt2/sdk/complex/meta/as_real.hpp>\n#include <nt2/include/functions/logical_or.hpp>\n#include <nt2/include/functions/if_zero_else.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::sincos_, tag::cpu_,\n                             (A0),\n                             (generic_ < complex_<floating_ < A0> > > )\n                             (generic_ < complex_<floating_ < A0> > > )\n                             (generic_ < complex_<floating_ < A0> > > )\n                            )\n  {\n    typedef void result_type;\n    inline void operator()(A0 const& a0,A0 & a1,A0 & a2) const\n    {\n      typedef typename meta::as_real<A0>::type rtype;\n      rtype c, s, ch, sh;\n      sincos(nt2::real(a0), s, c);\n      sinhcosh(nt2::imag(a0), sh, ch);\n      rtype r1 = if_zero_else(is_imag(a0), s*ch);\n      rtype i1 = if_zero_else(is_real(a0), c*sh);\n      rtype r2 = c*ch;\n      rtype i2 = if_zero_else(logical_or(is_imag(a0), is_real(a0)), -s*sh);\n      a1 =  A0(r1, i1);\n      a2 =  A0(r2, i2);\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::sincos_, tag::cpu_,\n                             (A0)(A1),\n                             (generic_ < imaginary_<floating_ < A0> > > )\n                             (generic_ < dry_<floating_ < A1> > > )\n                             (generic_ < imaginary_<floating_ < A0> > > )\n                            )\n  {\n    typedef void result_type;\n    inline void operator()(A0 const& a0,A1 & a1,A0 & a2) const\n    {\n      typedef typename meta::as_real<A0>::type rtype;\n      rtype ch, sh;\n      sinhcosh(nt2::imag(a0), sh, ch);\n      a1 =  bitwise_cast<A1>(ch);\n      a2 =  bitwise_cast<A0>(-sh);\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::sincos_, tag::cpu_,\n                             (A0),\n                             (generic_ < dry_<floating_ < A0> > > )\n                             (generic_ < dry_<floating_ < A0> > > )\n                             (generic_ < dry_<floating_ < A0> > > )\n                            )\n  {\n    typedef void result_type;\n    inline void operator()(A0 const& a0,A0 & a1,A0 & a2) const\n    {\n      typedef typename meta::as_real<A0>::type rtype;\n      rtype c, s;\n      sincos(nt2::real(a0), s, c);\n      a1 =  bitwise_cast<A0>(c);\n      a2 =  bitwise_cast<A0>(s);\n    }\n  };\n\n\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::sincos_, tag::cpu_,\n                             (A0),\n                             (generic_ < complex_<floating_ < A0> > > )\n                             (generic_ < complex_<floating_ < A0> > > )\n                            )\n  {\n    typedef A0 result_type;\n    inline A0 operator()(A0 const& a0,A0 & a2) const\n    {\n      result_type a1;\n      sincos(a0, a1, a2);\n      return a1;\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::sincos_, tag::cpu_,\n                             (A0),\n                             (generic_ < complex_<floating_<A0> > > )\n                            )\n  {\n    typedef std::pair<A0, A0>           result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      result_type res;\n      sincos(a0, res.first, res.second);\n      return res;\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "d92eed79d7e9f9e78808bd851494ebc1ace5b979", "size": 4076, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/trigonometric/include/nt2/trigonometric/functions/complex/generic/sincos.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/type/complex/trigonometric/include/nt2/trigonometric/functions/complex/generic/sincos.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/type/complex/trigonometric/include/nt2/trigonometric/functions/complex/generic/sincos.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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.1379310345, "max_line_length": 80, "alphanum_fraction": 0.5110402355, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5190186177666636}}
{"text": "#include <octomap/GaussionOcTree.h>\n#include <octomap/octomap.h>\n#include <pcl/common/centroid.h>\n#include <pcl/common/transforms.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n\n#include <Eigen/Dense>\n#include <unordered_map>\n#include <unordered_set>\n\n#define maxdepth 16   // unit: layer\n#define resolution 2  // unit: m\n\nint main(int argc, char** argv) {\n  std::string octomap_name = \"simple_tree_gussion.ot\";\n\n  // Part1: Read origin point cloud\n  Eigen::Vector4f centroid;\n  Eigen::Matrix3f covariance_matrix;\n  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_in(\n      new pcl::PointCloud<pcl::PointXYZ>);\n\n  std::cout << \" --------------- \"\n            << \" initial         \"\n            << \" --------------- \" << std::endl;\n\n  if (argc == 2) {\n    std::cout << \"use input data\" << std::endl;\n\n    if (pcl::io::loadPCDFile(argv[1], *cloud_in)) {\n      std::cerr << \"failed to open \" << argv[1] << std::endl;\n      return 1;\n    }\n\n    pcl::computeMeanAndCovarianceMatrix(*cloud_in, covariance_matrix, centroid);\n\n    Eigen::Matrix4f transform = Eigen::Matrix4f::Identity();\n    transform(0, 3) = -centroid(0);\n    transform(1, 3) = -centroid(1);\n    transform(2, 3) = -centroid(2);\n\n    pcl::transformPointCloud(*cloud_in, *cloud_in, transform);\n  } else {\n    std::cout << \"use builtin data\" << std::endl;\n    cloud_in->push_back(pcl::PointXYZ(1, 1.5, 0));\n    cloud_in->push_back(pcl::PointXYZ(1, 0.5, 0));\n    cloud_in->push_back(pcl::PointXYZ(0.5, 1, 0));\n    cloud_in->push_back(pcl::PointXYZ(1.5, 1, 0));\n\n    cloud_in->push_back(pcl::PointXYZ(3, 1.5, 0));\n    cloud_in->push_back(pcl::PointXYZ(3, 0.5, 0));\n    cloud_in->push_back(pcl::PointXYZ(2.5, 1, 0));\n    cloud_in->push_back(pcl::PointXYZ(3.5, 1, 0));\n\n    cloud_in->push_back(pcl::PointXYZ(1, 2.5, 0));\n    cloud_in->push_back(pcl::PointXYZ(1, 3.5, 0));\n    cloud_in->push_back(pcl::PointXYZ(0.5, 3, 0));\n    cloud_in->push_back(pcl::PointXYZ(1.5, 3, 0));\n\n    cloud_in->push_back(pcl::PointXYZ(1, 2.5, 2));\n    cloud_in->push_back(pcl::PointXYZ(1, 3.5, 2));\n    cloud_in->push_back(pcl::PointXYZ(0.5, 3, 2));\n    cloud_in->push_back(pcl::PointXYZ(1.5, 3, 2));\n\n    cloud_in->push_back(pcl::PointXYZ(3, 2.5, 0));\n    cloud_in->push_back(pcl::PointXYZ(3, 3.5, 0));\n    cloud_in->push_back(pcl::PointXYZ(2.5, 3, 0));\n    cloud_in->push_back(pcl::PointXYZ(3.5, 3, 0));\n\n    cloud_in->push_back(pcl::PointXYZ(1, -2, 0));\n    cloud_in->push_back(pcl::PointXYZ(2, -1, 0));\n    cloud_in->push_back(pcl::PointXYZ(2, -2, 0));\n    cloud_in->push_back(pcl::PointXYZ(2, -3, 0));\n    cloud_in->push_back(pcl::PointXYZ(3, -2, 0));\n  }\n\n  std::cout << \"Input \" << cloud_in->size() << \" pts. \" << std::endl;\n\n  // Part2: Construct Gaussion Octomap\n  std::cout << \" --------------- \"\n            << \" compute tree    \"\n            << \" --------------- \" << std::endl;\n\n  octomap::GaussionOcTree save_tree(resolution);\n  std::unordered_multimap<octomap::OcTreeKey, pcl::PointXYZ,\n                          octomap::OcTreeKey::KeyHash>\n      unorderedMultiMap;\n  std::unordered_set<octomap::OcTreeKey, octomap::OcTreeKey::KeyHash> set;\n\n  for (auto p : (*cloud_in).points) {\n    auto key = save_tree.coordToKey(p.x, p.y, p.z, 16);\n    unorderedMultiMap.emplace(key, p);\n    set.emplace(key);\n  }\n\n  for (auto iter = set.begin(); iter != set.end(); ++iter) {\n    auto key = *iter;\n    auto range = unorderedMultiMap.equal_range(key);\n    int i = 0;\n\n    pcl::PointCloud<pcl::PointXYZ> cloud;\n    for (auto it = range.first; it != range.second; ++it) {\n      cloud.push_back(it->second);\n      i++;\n    }\n\n    if (cloud.size() < 20) continue;\n    pcl::computeMeanAndCovarianceMatrix(cloud, covariance_matrix, centroid);\n    covariance_matrix = covariance_matrix * i / (i - 1);\n    auto n = save_tree.updateNode(key, true);\n    n->setGaussionDistribution(i, centroid.head<3>(), covariance_matrix);\n    // std::cout << \"This part has: \" << cloud.size() << \" pts. \" << std::endl\n    //           << \"centroid: \" << centroid << std::endl;\n  }\n\n  save_tree.updateInnerOccupancy();\n\n  std::cout << \" --------------- \"\n            << \" itr test before \"\n            << \" --------------- \" << std::endl;\n\n  std::cout << \"tree size: \" << save_tree.size() << std::endl;\n\n  int write_count_leaf_[maxdepth] = {0};\n\n  for (int ite = 0; ite < maxdepth; ite++) {\n    bool firstin_ = true;\n    for (auto it = save_tree.begin_leafs(ite), end = save_tree.end_leafs();\n         it != end; ++it) {\n      if (firstin_) {\n        std::cout << \" ------- \" << it.getDepth() << \"/\"\n                  << save_tree.getTreeDepth() << \" layer ------- \" << std::endl;\n        std::cout << \" coordinate: \" << it.getCoordinate()\n                  << \"  size: \" << it.getSize() << std::endl;\n        firstin_ = false;\n      }\n\n      if (ite == 0) {  // \u6253\u5370\u6700\u4f4e\u5c42\u7684\u6240\u6709\u5206\u5e03\n        std::cout << \"\u7b2c\" << write_count_leaf_[ite] << \"\u4e2a\u5206\u5e03\uff0c \"\n                  << \" \" << it->getGaussionDistribution() << std::endl;\n      }\n\n      if (ite == maxdepth - 1) {  // \u6253\u5370\u6b21\u4f4e\u5c42\u7684\u6240\u6709\u5206\u5e03\n        std::cout << \"\u7b2c\" << write_count_leaf_[ite] << \"\u4e2a\u5206\u5e03\uff0c \"\n                  << \" \" << it->getGaussionDistribution() << std::endl;\n      }\n\n      if (ite == maxdepth - 2) {  // \u6253\u5370\u6b21\u4f4e\u5c42\u7684\u6240\u6709\u5206\u5e03\n        std::cout << \"\u7b2c\" << write_count_leaf_[ite] << \"\u4e2a\u5206\u5e03\uff0c \"\n                  << \" \" << it->getGaussionDistribution() << std::endl;\n\n        std::cout << \"search [3.5,3,0]\" << std::endl;\n        int x_ = 2;\n        int y_ = 2;\n        int z_ = 0;\n        auto key = save_tree.coordToKey(x_, y_, z_, maxdepth - 2);\n        octomap::GaussionOcTreeNode* node = save_tree.search(key, maxdepth - 2);\n        std::cout << node->getGaussionDistribution() << std::endl;\n      }\n\n      if (ite == maxdepth - 3) {  // \u6253\u5370\u6b21\u4f4e\u5c42\u7684\u6240\u6709\u5206\u5e03\n        std::cout << \"\u7b2c\" << write_count_leaf_[ite] << \"\u4e2a\u5206\u5e03\uff0c \"\n                  << \" \" << it->getGaussionDistribution() << std::endl;\n\n        std::cout << \"search [3.5,3,0]\" << std::endl;\n        int x_ = 2;\n        int y_ = 2;\n        int z_ = 0;\n        auto key = save_tree.coordToKey(x_, y_, z_, maxdepth - 2);\n\n        octomap::GaussionOcTreeNode* node = save_tree.search(key, maxdepth - 2);\n        std::cout << node->getGaussionDistribution();\n      }\n      // if (ite == 1) { // \u6253\u5370\u6700\u9ad8\u5206\u5e03\n      //   std::cout << \"\u7b2c\" << write_count_leaf_[ite] << \"\u4e2a\u5206\u5e03\uff0c \"\n      //             << \" \" << it->getGaussionDistribution() << std::endl;\n      // }\n      write_count_leaf_[ite]++;\n    }\n\n    std::cout << \" num of leafs :: \" << write_count_leaf_[ite] << std::endl\n              << std::endl;\n  }\n\n  // Part3: Save Gaussion Octomap\n  save_tree.write(octomap_name);\n\n  // Part4: Read Gaussion Octomap\n  cloud_in->clear();\n\n  octomap::AbstractOcTree* read_tree =\n      octomap::AbstractOcTree::read(octomap_name);\n  octomap::GaussionOcTree* readtree =\n      dynamic_cast<octomap::GaussionOcTree*>(read_tree);\n\n  std::cout << \" --------------- \"\n            << \" itr test  after \"\n            << \" --------------- \" << std::endl;\n\n  std::cout << \"tree size: \" << readtree->size() << std::endl;\n\n  int read_count_leaf_[maxdepth] = {0};\n  for (int ite = 0; ite < maxdepth; ite++) {\n    bool firstin_ = true;\n    for (auto it = readtree->begin_leafs(ite), end = readtree->end_leafs();\n         it != end; ++it) {\n      if (firstin_) {\n        std::cout << \" ------- \" << it.getDepth() << \"/\"\n                  << readtree->getTreeDepth() << \" layer ------- \" << std::endl;\n        std::cout << \" coordinate: \" << it.getCoordinate()\n                  << \"  size: \" << it.getSize() << std::endl;\n        firstin_ = false;\n      }\n\n      // if (ite == 0) {  // \u6253\u5370\u6700\u4f4e\u5c42\u7684\u6240\u6709\u5206\u5e03\n      //   std::cout << \"\u7b2c\" << read_count_leaf_[ite] << \"\u4e2a\u5206\u5e03\uff0c \"\n      //             << \" \" << it->getGaussionDistribution() << std::endl;\n      // }\n\n      // if (ite == maxdepth - 1) {  // \u6253\u5370\u6b21\u4f4e\u5c42\u7684\u6240\u6709\u5206\u5e03\n      //   std::cout << \"\u7b2c\" << read_count_leaf_[ite] << \"\u4e2a\u5206\u5e03\uff0c \"\n      //             << \" \" << it->getGaussionDistribution() << std::endl;\n      // }\n\n      // if (ite == 1) {\n      //   std::cout << \"\u7b2c\" << read_count_leaf_[ite] << \"\u4e2a\u5206\u5e03\uff0c \"\n      //             << \" \" << it->getGaussionDistribution() << std::endl;\n      // }\n      read_count_leaf_[ite]++;\n    }\n\n    std::cout << \" num of leafs :: \" << read_count_leaf_[ite] << std::endl\n              << std::endl;\n  }\n\n  std::cout << \"read file \" << octomap_name << \" done\" << std::endl\n            << std::endl;\n}\n", "meta": {"hexsha": "4a6c9ce4105d42d4b0f54db1091d6317513cd1ef", "size": 8319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "octomap/src/testing/test_gaussion_tree.cpp", "max_stars_repo_name": "Peiwvy/octomap_gaussion", "max_stars_repo_head_hexsha": "74d46af2046c8f0e95419e17a584501240e24f3c", "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": "octomap/src/testing/test_gaussion_tree.cpp", "max_issues_repo_name": "Peiwvy/octomap_gaussion", "max_issues_repo_head_hexsha": "74d46af2046c8f0e95419e17a584501240e24f3c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "octomap/src/testing/test_gaussion_tree.cpp", "max_forks_repo_name": "Peiwvy/octomap_gaussion", "max_forks_repo_head_hexsha": "74d46af2046c8f0e95419e17a584501240e24f3c", "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.6625, "max_line_length": 80, "alphanum_fraction": 0.5402091598, "num_tokens": 2642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5190155099459368}}
{"text": "#include <CGAL/Simple_cartesian.h>\n\n#include <CGAL/boost/graph/graph_traits_Linear_cell_complex_for_combinatorial_map.h>\n#include <CGAL/boost/graph/IO/polygon_mesh_io.h>\n\n#include <boost/graph/breadth_first_search.hpp>\n\n#include <fstream>\n\ntypedef CGAL::Simple_cartesian<double>              Kernel;\ntypedef Kernel::Point_3                             Point;\ntypedef CGAL::Linear_cell_complex_traits<3, Kernel> LCC_traits;\n\ntypedef CGAL::Linear_cell_complex_for_bgl_combinatorial_map_helper\n         <2, 3, LCC_traits>::type LCC;\n\ntypedef boost::graph_traits<LCC>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<LCC>::vertex_iterator   vertex_iterator;\n\nint main(int argc, char** argv)\n{\n  LCC lcc;\n  CGAL::IO::read_polygon_mesh((argc>1)?argv[1]:\"cube.off\", lcc);\n\n  // This is the vector where the distance gets written to\n  std::vector<int> distance(lcc.vertex_attributes().size());\n\n  // Here we start at an arbitrary vertex\n  // Any other vertex could be the starting point\n  vertex_iterator vb, ve;\n  boost::tie(vb,ve)=vertices(lcc);\n  vertex_descriptor  vd = *vb;\n\n  std::cout << \"We compute distances to \" << vd->point() << std::endl;\n\n  // bfs = breadth first search explores the graph\n  // Just as the distance_recorder there is a way to record the predecessor of a vertex\n  boost::breadth_first_search(lcc,\n                              vd,\n                              visitor(boost::make_bfs_visitor\n                                      (boost::record_distances\n                                       (make_iterator_property_map\n                                        (distance.begin(),\n                                         get(boost::vertex_index, lcc)),\n                                        boost::on_tree_edge()))));\n\n  // Traverse all vertices and show at what distance they are\n  for(boost::tie(vb,ve)=vertices(lcc); vb!=ve; ++vb)\n  {\n    vd = *vb;\n    std::cout<<vd->point()<<\"  is \"<<distance[vd->id()]<<\" hops away.\"<<std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "73dd211644c2d3a013ce4315f4ca0bd3a887af04", "size": 1996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGL/examples/BGL_LCC/distance_lcc.cpp", "max_stars_repo_name": "antoniospg/cgal", "max_stars_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-20T17:02:24.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-20T17:02:24.000Z", "max_issues_repo_path": "BGL/examples/BGL_LCC/distance_lcc.cpp", "max_issues_repo_name": "antoniospg/cgal", "max_issues_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-10T13:32:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T12:23:20.000Z", "max_forks_repo_path": "BGL/examples/BGL_LCC/distance_lcc.cpp", "max_forks_repo_name": "antoniospg/cgal", "max_forks_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T15:26:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-21T15:26:25.000Z", "avg_line_length": 35.6428571429, "max_line_length": 87, "alphanum_fraction": 0.621743487, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5190155099459368}}
{"text": "/*\n * Copyright (C) 2019  Rhys Mainwaring\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 \"wave_gazebo_plugins/Wavefield.hh\"\n#include \"wave_gazebo_plugins/Geometry.hh\"\n#include \"wave_gazebo_plugins/Physics.hh\"\n#include \"wave_gazebo_plugins/Utilities.hh\"\n\n#include <Eigen/Dense>\n\n#include <gazebo/gazebo.hh>\n#include <gazebo/common/common.hh>\n#include <gazebo/msgs/msgs.hh>\n\n#include <ignition/math/Pose3.hh>\n#include <ignition/math/Vector2.hh>\n#include <ignition/math/Vector3.hh>\n\n#include <array>\n#include <iostream>\n#include <cmath>\n#include <string>\n\nnamespace asv \n{\n///////////////////////////////////////////////////////////////////////////////\n// Utilities\n\n  std::ostream& operator<<(std::ostream& os, const std::vector<double>& _vec)\n  { \n    for (auto&& v : _vec )\n      os << v << \", \";\n    return os;\n  }\n\n///////////////////////////////////////////////////////////////////////////////\n// WaveParametersPrivate\n\n  /// \\internal\n  /// \\brief Private data for the WavefieldParameters.\n  class WaveParametersPrivate\n  {\n    /// \\brief Constructor.\n    public: WaveParametersPrivate():\n      number(1), \n      scale(2.0),\n      angle(2.0*M_PI/10.0),\n      steepness(1.0),\n      amplitude(0.0), \n      period(1.0), \n      phase(0.0), \n      direction(1, 0),\n      angularFrequency(2.0*M_PI),\n      wavelength(2*M_PI/Physics::DeepWaterDispersionToWavenumber(2.0*M_PI)), \n      wavenumber(Physics::DeepWaterDispersionToWavenumber(2.0*M_PI))\n    {\n    }\n\n    /// \\brief The number of component waves.\n    public: size_t number;\n\n    /// \\brief Set the scale of the largest and smallest waves. \n    public: double scale;\n\n    /// \\brief Set the angle between component waves and the mean direction.\n    public: double angle;\n\n    /// \\brief Control the wave steepness. 0 is sine waves, 1 is Gerstner waves.\n    public: double steepness;\n\n    /// \\brief The mean wave amplitude [m].\n    public: double amplitude;\n\n    /// \\brief The mean wave period [s]\n    public: double period;\n\n    /// \\brief The mean wve phase (not currently enabled).\n    public: double phase;\n\n    /// \\brief The mean wave direction.\n    public: ignition::math::Vector2d direction;\n\n    /// \\brief The mean wave angular frequency (derived).    \n    public: double angularFrequency;\n\n    /// \\brief The mean wavelength (derived).\n    public: double wavelength;\n\n    /// \\brief The mean wavenumber (derived).\n    public: double wavenumber;\n  \n    /// \\brief The component wave angular frequencies (derived).\n    public: std::vector<double> angularFrequencies;\n\n    /// \\brief The component wave amplitudes (derived).\n    public: std::vector<double> amplitudes;\n\n    /// \\brief The component wave phases (derived).\n    public: std::vector<double> phases;\n\n    /// \\brief The component wave steepness factors (derived).\n    public: std::vector<double> steepnesses;\n\n    /// \\brief The component wavenumbers (derived).\n    public: std::vector<double> wavenumbers;\n\n    /// \\brief The component wave dirctions (derived).\n    public: std::vector<ignition::math::Vector2d> directions;\n\n    /// \\brief Recalculate all derived quantities from inputs.\n    public: void Recalculate()\n    {\n      // Normalize direction\n      this->direction = Geometry::Normalize(this->direction);\n\n      // Derived mean values\n      this->angularFrequency = 2.0 * M_PI / this->period;\n      this->wavenumber = Physics::DeepWaterDispersionToWavenumber(this->angularFrequency);\n      this->wavelength = 2.0 * M_PI / this->wavenumber;\n\n      // Update components\n      this->angularFrequencies.clear();\n      this->amplitudes.clear();\n      this->phases.clear();\n      this->wavenumbers.clear();\n      this->steepnesses.clear();\n      this->directions.clear();\n\n      for (size_t i=0; i<this->number; ++i)\n      {\n        const int n = i - this->number/2;\n        const double scaleFactor = std::pow(this->scale, n);\n        const double a = scaleFactor * this->amplitude;\n        const double k = this->wavenumber / scaleFactor;\n        const double omega = Physics::DeepWaterDispersionToOmega(k);\n        const double phi = this->phase;\n        double q = 0.0;\n        if (a != 0)\n        {\n          q = std::min(1.0, this->steepness / (a * k * this->number));\n        }\n\n        this->amplitudes.push_back(a);        \n        this->angularFrequencies.push_back(omega);\n        this->phases.push_back(phi);\n        this->steepnesses.push_back(q);\n        this->wavenumbers.push_back(k);\n      \n        // Direction\n        const double c = std::cos(n * this->angle);\n        const double s = std::sin(n * this->angle);\n        // const TransformMatrix T(\n        //   c, -s,\n        //   s,  c\n        // );\n        // const ignition::math::Vector2d d = T(this->direction);\n        const ignition::math::Vector2d d(\n          c * this->direction.X() - s * this->direction.Y(),\n          s * this->direction.X() + c * this->direction.Y()\n        );\n        directions.push_back(d);\n      }\n    }\n  };\n\n///////////////////////////////////////////////////////////////////////////////\n// WaveParameters\n\n  WaveParameters::~WaveParameters()\n  {\n  }\n\n  WaveParameters::WaveParameters()\n    : data(new WaveParametersPrivate())\n  {\n    this->data->Recalculate();\n  }\n\n  void WaveParameters::FillMsg(gazebo::msgs::Param_V& _msg) const\n  {\n    // Clear \n    _msg.mutable_param()->Clear();\n\n    // \"number\"\n    {\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"number\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::INT32);\n      nextParam->mutable_value()->set_int_value(this->data->number);\n    }\n    // \"scale\"\n    {\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"scale\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::DOUBLE);\n      nextParam->mutable_value()->set_double_value(this->data->scale);\n    }\n    // \"angle\"\n    {\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"angle\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::DOUBLE);\n      nextParam->mutable_value()->set_double_value(this->data->angle);\n    }\n    // \"steepness\"\n    {\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"steepness\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::DOUBLE);\n      nextParam->mutable_value()->set_double_value(this->data->steepness);\n    }\n    // \"amplitude\"\n    {\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"amplitude\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::DOUBLE);\n      nextParam->mutable_value()->set_double_value(this->data->amplitude);\n    }\n    // \"period\"\n    {\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"period\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::DOUBLE);\n      nextParam->mutable_value()->set_double_value(this->data->period);\n    }\n    // \"direction\"\n    {\n      const auto& direction = this->data->direction;\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"direction\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::VECTOR3D);\n      nextParam->mutable_value()->mutable_vector3d_value()->set_x(direction.X());\n      nextParam->mutable_value()->mutable_vector3d_value()->set_y(direction.Y());\n      nextParam->mutable_value()->mutable_vector3d_value()->set_z(0);\n    }\n  }\n\n  void WaveParameters::SetFromMsg(const gazebo::msgs::Param_V& _msg)\n  {\n    this->data->number    = Utilities::MsgParamSizeT(_msg,    \"number\",     this->data->number);\n    this->data->amplitude = Utilities::MsgParamDouble(_msg,   \"amplitude\",  this->data->amplitude);\n    this->data->period    = Utilities::MsgParamDouble(_msg,   \"period\",     this->data->period);\n    this->data->phase     = Utilities::MsgParamDouble(_msg,   \"phase\",      this->data->phase);\n    this->data->direction = Utilities::MsgParamVector2(_msg,  \"direction\",  this->data->direction);\n    this->data->scale     = Utilities::MsgParamDouble(_msg,   \"scale\",      this->data->scale);\n    this->data->angle     = Utilities::MsgParamDouble(_msg,   \"angle\",      this->data->angle);\n    this->data->steepness = Utilities::MsgParamDouble(_msg,   \"steepness\",  this->data->steepness);\n\n    this->data->Recalculate();\n  }\n\n  void WaveParameters::SetFromSDF(sdf::Element& _sdf)\n  {\n    this->data->number    = Utilities::SdfParamSizeT(_sdf,    \"number\",     this->data->number);\n    this->data->amplitude = Utilities::SdfParamDouble(_sdf,   \"amplitude\",  this->data->amplitude);\n    this->data->period    = Utilities::SdfParamDouble(_sdf,   \"period\",     this->data->period);\n    this->data->phase     = Utilities::SdfParamDouble(_sdf,   \"phase\",      this->data->phase);\n    this->data->direction = Utilities::SdfParamVector2(_sdf,  \"direction\",  this->data->direction);\n    this->data->scale     = Utilities::SdfParamDouble(_sdf,   \"scale\",      this->data->scale);\n    this->data->angle     = Utilities::SdfParamDouble(_sdf,   \"angle\",      this->data->angle);\n    this->data->steepness = Utilities::SdfParamDouble(_sdf,   \"steepness\",  this->data->steepness);\n\n    this->data->Recalculate();\n  }\n\n  size_t WaveParameters::Number() const\n  {\n    return this->data->number;\n  }\n\n  double WaveParameters::Angle() const\n  {\n    return this->data->angle;\n  }\n\n  double WaveParameters::Scale() const\n  {\n    return this->data->scale;\n  }\n\n  double WaveParameters::Steepness() const\n  {\n    return this->data->steepness;\n  }\n\n  double WaveParameters::AngularFrequency() const\n  {\n    return this->data->angularFrequency;\n  }\n\n  double WaveParameters::Amplitude() const\n  {\n    return this->data->amplitude;\n  }\n  \n  double WaveParameters::Period() const\n  {\n    return this->data->period;\n  }\n  \n  double WaveParameters::Phase() const\n  {\n    return this->data->phase;\n  }\n\n  double WaveParameters::Wavelength() const\n  {\n    return this->data->wavelength;\n  }\n\n  double WaveParameters::Wavenumber() const\n  {\n    return this->data->wavenumber;\n  }    \n\n  ignition::math::Vector2d WaveParameters::Direction() const\n  {\n    return this->data->direction;\n  }\n  \n  void WaveParameters::SetNumber(size_t _number)\n  {\n    this->data->number = _number;\n    this->data->Recalculate();\n  }\n\n  void WaveParameters::SetAngle(double _angle)\n  {\n    this->data->angle = _angle;\n    this->data->Recalculate();\n  }\n\n  void WaveParameters::SetScale(double _scale)\n  {\n    this->data->scale = _scale;\n    this->data->Recalculate();\n  }\n\n  void WaveParameters::SetSteepness(double _steepness)\n  {\n    this->data->steepness = _steepness;\n    this->data->Recalculate();\n  }\n\n  void WaveParameters::SetAmplitude(double _amplitude)\n  {\n    this->data->amplitude = _amplitude;\n    this->data->Recalculate();\n  }\n  \n  void WaveParameters::SetPeriod(double _period)\n  {\n    this->data->period = _period;\n    this->data->Recalculate();\n  }\n    \n  void WaveParameters::SetPhase(double _phase)\n  {\n    this->data->phase = _phase;\n    this->data->Recalculate();\n  }\n  \n  void WaveParameters::SetDirection(const ignition::math::Vector2d& _direction)\n  {\n    this->data->direction = _direction;\n    this->data->Recalculate();\n  }\n\n  const std::vector<double>& WaveParameters::AngularFrequency_V() const\n  {\n    return this->data->angularFrequencies;\n  }\n\n  const std::vector<double>& WaveParameters::Amplitude_V() const\n  {\n    return this->data->amplitudes;\n  }\n  \n  const std::vector<double>& WaveParameters::Phase_V() const\n  {\n    return this->data->phases;\n  }\n  \n  const std::vector<double>& WaveParameters::Steepness_V() const\n  {\n    return this->data->steepnesses;\n  }\n\n  const std::vector<double>& WaveParameters::Wavenumber_V() const\n  {\n    return this->data->wavenumbers;\n  }\n\n  const std::vector<ignition::math::Vector2d>& WaveParameters::Direction_V() const\n  {\n    return this->data->directions;\n  }\n \n  void WaveParameters::DebugPrint() const\n  {\n    gzmsg << \"number:     \" << this->data->number << std::endl;\n    gzmsg << \"scale:      \" << this->data->scale << std::endl;\n    gzmsg << \"angle:      \" << this->data->angle << std::endl;\n    gzmsg << \"period:     \" << this->data->period << std::endl;\n    gzmsg << \"amplitude:  \" << this->data->amplitudes << std::endl;\n    gzmsg << \"wavenumber: \" << this->data->wavenumbers << std::endl;\n    gzmsg << \"omega:      \" << this->data->angularFrequencies << std::endl;\n    gzmsg << \"phase:      \" << this->data->phases << std::endl;\n    gzmsg << \"steepness:  \" << this->data->steepnesses << std::endl;\n    for (auto&& d : this->data->directions)\n    {\n      gzmsg << \"direction:  \" << d << std::endl;\n    }\n  }\n\n///////////////////////////////////////////////////////////////////////////////    \n// WavefieldSampler\n\n  double WavefieldSampler::ComputeDepthDirectly(  \n    const WaveParameters& _waveParams,\n    const ignition::math::Vector3d& _point,\n    double time\n  )\n  {\n    // Struture for passing wave parameters to lambdas\n    struct WaveParams\n    {\n      WaveParams(\n        const std::vector<double>& _a,\n        const std::vector<double>& _k,\n        const std::vector<double>& _omega,\n        const std::vector<double>& _phi,\n        const std::vector<double>& _q,\n        const std::vector<ignition::math::Vector2d>& _dir) :\n        a(_a), k(_k), omega(_omega), phi(_phi), q(_q), dir(_dir) {}\n\n      const std::vector<double>& a;\n      const std::vector<double>& k;\n      const std::vector<double>& omega;\n      const std::vector<double>& phi;\n      const std::vector<double>& q;\n      const std::vector<ignition::math::Vector2d>& dir;\n    };\n\n    // Compute the target function and Jacobian. Also calculate pz,\n    // the z-componen of the Gerstner wave, which we essentially get for free.\n    auto wave_fdf = [=](auto x, auto p, auto t, auto& wp, auto& F, auto& J)\n    {\n      double pz = 0;\n      F(0) = p.x() - x.x();\n      F(1) = p.y() - x.y();\n      J(0, 0) = -1;\n      J(0, 1) =  0;\n      J(1, 0) =  0;\n      J(1, 1) = -1;\n      const size_t n = wp.a.size();\n      for (auto&& i=0; i<n; ++i)\n      {\n        const double dx = wp.dir[i].X();\n        const double dy = wp.dir[i].Y();\n        const double q = wp.q[i];\n        const double a = wp.a[i];\n        const double k = wp.k[i];\n        const double dot = x.x() * dx + x.y() * dy;\n        const double theta = k * dot - wp.omega[i] * t;\n        const double s = std::sin(theta);\n        const double c = std::cos(theta);\n        const double qakc = q * a * k * c;\n        const double df1x = qakc * dx * dx;\n        const double df1y = qakc * dx * dy;\n        const double df2x = df1y;\n        const double df2y = qakc * dy * dy;\n        pz += a * c;\n        F(0) += a * dx * s;\n        F(1) += a * dy * s;\n        J(0, 0) += df1x;\n        J(0, 1) += df1y;\n        J(1, 0) += df2x;\n        J(1, 1) += df2y;\n      }\n      return pz;\n    };\n\n    // Simple multi-variate Newton solver - this version returns the z-component of the\n    // wave field at the desired point p.\n    auto solver = [=](auto& fdfunc, auto x0, auto p, auto t, auto& wp, auto tol, auto nmax)\n    {\n      int n = 0;\n      double err = 1;\n      double pz = 0;\n      auto xn = x0;\n      Eigen::Vector2d F;\n      Eigen::Matrix2d J;\n      while (std::abs(err) > tol && n < nmax)\n      {\n        pz = fdfunc(x0, p, t, wp, F, J);\n        xn = x0 - J.inverse() * F;\n        x0 = xn;\n        err = F.norm();\n        n++;\n      }\n      return pz;\n    };\n\n    // Set up parameter references\n    WaveParams wp(\n      _waveParams.Amplitude_V(),\n      _waveParams.Wavenumber_V(),\n      _waveParams.AngularFrequency_V(),\n      _waveParams.Phase_V(),\n      _waveParams.Steepness_V(),\n      _waveParams.Direction_V()\n    );\n\n    // Tolerances etc.\n    const double tol = 1.0E-10;\n    const double nmax = 30;\n\n    // Use the target point as the initial guess (this is within sum{amplitudes} of the solution)\n    Eigen::Vector2d p2(_point.X(), _point.Y());\n    const double pz = solver(wave_fdf, p2, p2, time, wp, tol, nmax);\n    const double h = pz - _point.Z();\n    return h;\n  }\n\n///////////////////////////////////////////////////////////////////////////////\n\n} // namespace asv\n", "meta": {"hexsha": "0574523140ec816fc1c81b5d11a59b2065d987b1", "size": 16539, "ext": "cc", "lang": "C++", "max_stars_repo_path": "wave_gazebo_plugins/src/Wavefield.cc", "max_stars_repo_name": "srmainwaring/wave_sim_vrx", "max_stars_repo_head_hexsha": "a7022086783b92160a653558c65cfb4c5ebc3171", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wave_gazebo_plugins/src/Wavefield.cc", "max_issues_repo_name": "srmainwaring/wave_sim_vrx", "max_issues_repo_head_hexsha": "a7022086783b92160a653558c65cfb4c5ebc3171", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wave_gazebo_plugins/src/Wavefield.cc", "max_forks_repo_name": "srmainwaring/wave_sim_vrx", "max_forks_repo_head_hexsha": "a7022086783b92160a653558c65cfb4c5ebc3171", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4585635359, "max_line_length": 99, "alphanum_fraction": 0.601729246, "num_tokens": 4475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.5190155012258627}}
{"text": "#define BOOST_TEST_MODULE\n#include <boost/test/unit_test.hpp>\n#include <util/test_macros.hpp>\n#include <stdlib.h>\n#include <vector>\n#include <string>\n#include <functional>\n#include <random>\n\n#include <unity/lib/gl_sframe.hpp>\n#include <unity/lib/unity_sframe.hpp>\n#include <unity/lib/variant_deep_serialize.hpp>\n#include <unity/toolkits/pattern_mining/rule_mining.hpp>\n#include <unity/toolkits/pattern_mining/fp_growth.hpp>\n\n#include <cfenv>\n\nusing namespace turi;\nusing namespace turi::pattern_mining;\n\n/*\n * Note the conviction score tests are commented out. Those cannot be right.\n * Some of the \"true values\" are NaNs or Infs\n */\n\n/**\n *  Run tests.\n*/\nstruct fp_rule_mining_test  {\n\n    rule_list setupRuleList(void) {\n      rule_list my_rules;\n\n      rule rule1;\n      rule1.LHS = {1};\n      rule1.RHS = {9};\n      rule1.LHS_support = 10;\n      rule1.RHS_support = 7;\n      rule1.total_support = 5;\n\n      rule rule2;\n      rule2.LHS = {2};\n      rule2.RHS = {9};\n      rule2.LHS_support = 10;\n      rule2.RHS_support = 5;\n      rule2.total_support = 5;\n\n      rule rule3;\n      rule3.LHS = {3};\n      rule3.RHS = {9};\n      rule3.LHS_support = 5;\n      rule3.RHS_support = 7;\n      rule3.total_support = 5;\n\n      rule rule4;\n      rule4.LHS = {4};\n      rule4.RHS = {9};\n      rule4.LHS_support = 5;\n      rule4.RHS_support = 4;\n      rule4.total_support = 1;\n\n      my_rules.add_rule(rule1);\n      my_rules.add_rule(rule2);\n      my_rules.add_rule(rule3);\n      my_rules.add_rule(rule4);\n      my_rules.num_transactions = 20;\n      return my_rules;\n    }\n\n  public:\n\n    void testConfidenceScore(void){\n      TS_ASSERT_DELTA(confidence_score(10, 7, 5), 5.0 / 10.0, 1e-7);\n      TS_ASSERT_DELTA(confidence_score(10, 5, 5), 5.0 / 10.0, 1e-7);\n      TS_ASSERT_DELTA(confidence_score(5, 7, 5), 5.0 / 5.0, 1e-7);\n      TS_ASSERT_DELTA(confidence_score(5, 4, 1), 1.0 / 5.0, 1e-7);\n    }\n    void testLiftScore(void){\n      TS_ASSERT_DELTA(lift_score(10, 7, 5), 5.0 / 70.0, 1e-7);\n      TS_ASSERT_DELTA(lift_score(10, 5, 5), 5.0 / 50.0, 1e-7);\n      TS_ASSERT_DELTA(lift_score(5, 7, 5), 5.0 / 35.0, 1e-7);\n      TS_ASSERT_DELTA(lift_score(5, 4, 1), 1.0 / 20.0, 1e-7);\n    }\n//     void testConvictionScore(void){\n//       TS_ASSERT_DELTA(conviction_score(10, 7/20.0, 5), (1 - 7.0/20.0) / (1 - 5.0/10.0), 1e-7);\n//       TS_ASSERT_DELTA(conviction_score(10, 5/20.0, 5), (1 - 5.0/20.0) / (1 - 5.0/10.0), 1e-7);\n//       TS_ASSERT_DELTA(conviction_score(5, 7/20.0, 5), (1 - 7.0/20.0) / (1 - 5.0/5.0), 1e-7);\n//       TS_ASSERT_DELTA(conviction_score(5, 4/20.0, 1), (1 - 4.0/20.0) / (1 - 1.0/5.0), 1e-7);\n//     }\n    void testAllConfidenceScore(void){\n      TS_ASSERT_DELTA(all_confidence_score(10, 7, 5), 5.0 / 10.0, 1e-7);\n      TS_ASSERT_DELTA(all_confidence_score(10, 5, 5), 5.0 / 10.0, 1e-7);\n      TS_ASSERT_DELTA(all_confidence_score(5, 7, 5), 5.0 / 7.0, 1e-7);\n      TS_ASSERT_DELTA(all_confidence_score(5, 4, 1), 1.0 / 5.0, 1e-7);\n    }\n    void testMaxConfidenceScore(void){\n      TS_ASSERT_DELTA(max_confidence_score(10, 7, 5), 5.0 / 7.0, 1e-7);\n      TS_ASSERT_DELTA(max_confidence_score(10, 5, 5), 5.0 / 5.0, 1e-7);\n      TS_ASSERT_DELTA(max_confidence_score(5, 7, 5), 5.0 / 5.0, 1e-7);\n      TS_ASSERT_DELTA(max_confidence_score(5, 4, 1), 1.0 / 4.0, 1e-7);\n    }\n    void testKulcScore(void){\n      TS_ASSERT_DELTA(kulc_score(10, 7, 5), 0.5 * ((5.0 / 10.0) + (5.0/7.0)), 1e-7);\n      TS_ASSERT_DELTA(kulc_score(10, 5, 5), 0.5 * ((5.0 / 10.0) + (5.0/5.0)), 1e-7);\n      TS_ASSERT_DELTA(kulc_score(5, 7, 5), 0.5 * ((5.0 / 5.0) + (5.0/7.0)), 1e-7);\n      TS_ASSERT_DELTA(kulc_score(5, 4, 1), 0.5* ((1.0 / 5.0)+ (1.0/4.0)), 1e-7);\n    }\n    void testCosineScore(void){\n      TS_ASSERT_DELTA(cosine_score(10, 7, 5), 5.0 / std::sqrt(70.0), 1e-7);\n      TS_ASSERT_DELTA(cosine_score(10, 5, 5), 5.0 / std::sqrt(50.0), 1e-7);\n      TS_ASSERT_DELTA(cosine_score(5, 7, 5), 5.0 / std::sqrt(35.0), 1e-7);\n      TS_ASSERT_DELTA(cosine_score(5, 4, 1), 1.0 / std::sqrt(20.0), 1e-7);\n    }\n\n    void testConfScoreRules(void){\n      rule_list my_rules = setupRuleList();\n\n      std::vector<double> conf_scores = my_rules.score_rules(CONF_SCORE);\n      std::vector<double> expected_scores = { 5.0 / 10.0,\n                                              5.0 / 10.0,\n                                              5.0 / 5.0,\n                                              1.0 / 5.0 };\n      for (size_t i = 0;i < expected_scores.size(); ++i) {\n        TS_ASSERT_DELTA(conf_scores[i], expected_scores[i], 1e-7);\n      }\n    }\n    void testLiftScoreRules(void){\n      rule_list my_rules = setupRuleList();\n\n      std::vector<double> lift_scores = my_rules.score_rules(LIFT_SCORE);\n      std::vector<double> expected_scores = { 5.0 / 70.0 * 20.0,\n                                              5.0 / 50.0 * 20.0,\n                                              5.0 / 35.0 * 20.0,\n                                              1.0 / 20.0 * 20.0};\n      for (size_t i = 0;i < expected_scores.size(); ++i) {\n        TS_ASSERT_DELTA(lift_scores[i], expected_scores[i], 1e-7);\n      }\n    }\n//     void testConvictionScoreRules(void){\n//       rule_list my_rules = setupRuleList();\n// \n//       std::vector<double> conviction_scores = my_rules.score_rules(CONVICTION_SCORE);\n//       std::vector<double> expected_scores = { (1 - 7.0/20.0) / (1 - 5.0/10.0),\n//                                               (1 - 5.0/20.0) / (1 - 5.0/10.0),\n//                                               (1 - 7.0/20.0) / (1 - 5.0/5.0),\n//                                               (1 - 4.0/20.0) / (1 - 1.0/5.0)};\n//       for (size_t i = 0;i < expected_scores.size(); ++i) {\n//         TS_ASSERT_DELTA(conviction_scores[i], expected_scores[i], 1e-7);\n//       }\n//     }\n    void testAllConfScoreRules(void){\n      rule_list my_rules = setupRuleList();\n\n      std::vector<double> all_conf_scores = my_rules.score_rules(ALL_CONF_SCORE);\n      std::vector<double> expected_scores = { 5.0 / 10.0,\n                                              5.0 / 10.0,\n                                              5.0 / 7.0,\n                                              1.0 / 5.0};\n      for (size_t i = 0;i < expected_scores.size(); ++i) {\n        TS_ASSERT_DELTA(all_conf_scores[i], expected_scores[i], 1e-7);\n      }\n    }\n    void testMaxConfScoreRules(void){\n      rule_list my_rules = setupRuleList();\n\n      std::vector<double> max_conf_scores = my_rules.score_rules(MAX_CONF_SCORE);\n      std::vector<double> expected_scores = { 5.0 / 7.0,\n                                              5.0 / 5.0,\n                                              5.0 / 5.0,\n                                              1.0 / 4.0};\n      for (size_t i = 0;i < expected_scores.size(); ++i) {\n        TS_ASSERT_DELTA(max_conf_scores[i], expected_scores[i], 1e-7);\n      }\n    }\n    void testKulcScoreRules(void){\n      rule_list my_rules = setupRuleList();\n\n      std::vector<double> kulc_scores = my_rules.score_rules(KULC_SCORE);\n      std::vector<double> expected_scores = { 0.5 * ((5.0 / 10.0) + (5.0/7.0)),\n                                              0.5 * ((5.0 / 10.0) + (5.0/5.0)),\n                                              0.5 * ((5.0 / 5.0) + (5.0/7.0)),\n                                              0.5* ((1.0 / 5.0)+ (1.0/4.0))};\n      for (size_t i = 0;i < expected_scores.size(); ++i) {\n        TS_ASSERT_DELTA(kulc_scores[i], expected_scores[i], 1e-7);\n      }\n    }\n    void testCosineScoreRules(void){\n      rule_list my_rules = setupRuleList();\n\n      std::vector<double> cosine_scores = my_rules.score_rules(COSINE_SCORE);\n      std::vector<double> expected_scores = { 5.0 / std::sqrt(70.0),\n                                              5.0 / std::sqrt(50.0),\n                                              5.0 / std::sqrt(35.0),\n                                              1.0 / std::sqrt(20.0)};\n      for (size_t i = 0;i < expected_scores.size(); ++i) {\n        TS_ASSERT_DELTA(cosine_scores[i], expected_scores[i], 1e-7);\n      }\n    }\n\n    // Test extract_relevant_rules\n    void testExtractRelevantRules(void) {\n      std::vector<size_t> id_order = {2, 3, 1, 4, 0};\n      gl_sframe closed_itemsets{{\"itemsets\", {flex_list{2, 1, 4},\n                                              flex_list{2, 3},\n                                              flex_list{2, 3, 1, 4},\n                                              flex_list{3, 1},\n                                              flex_list{2},\n                                              flex_list{3},\n                                              flex_list{1},\n                                              flex_list{1, 0},\n                                              flex_list{}}},\n                              {\"support\", {20, 24, 12, 20, 30, 27, 23, 13, 40}}};\n      fp_results_tree my_results = fp_results_tree(id_order);\n      my_results.build_tree(closed_itemsets);\n\n      std::vector<size_t> my_itemset = {1};\n      auto my_rules = extract_relevant_rules(my_itemset, my_results);\n      // std::cout << my_rules << std::endl;\n      TS_ASSERT_EQUALS(my_rules.rules.size(), 7);\n      TS_ASSERT_EQUALS(my_rules.get_LHS_supports(), \\\n          std::vector<size_t>({40, 23, 40, 23, 40, 23, 23}));\n      TS_ASSERT_EQUALS(my_rules.get_RHS_supports(), \\\n          std::vector<size_t>({30, 20, 24, 12, 27, 27, 13}));\n      TS_ASSERT_EQUALS(my_rules.get_total_supports(), \\\n          std::vector<size_t>({30, 20, 24, 12, 27, 20, 13}));\n      TS_ASSERT_EQUALS(my_rules.num_transactions, 40); // Support of emptyset\n\n      my_itemset = {4};\n      my_rules = extract_relevant_rules(my_itemset, my_results);\n      // std::cout << my_rules << std::endl;\n      TS_ASSERT_EQUALS(my_rules.rules.size(), 8);\n      TS_ASSERT_EQUALS(my_rules.get_LHS_supports(), \\\n          std::vector<size_t>({40, 20, 40, 20, 40, 40, 40, 40}));\n      TS_ASSERT_EQUALS(my_rules.get_RHS_supports(), \\\n          std::vector<size_t>({30, 20, 24, 12, 27, 20, 23, 13}));\n      TS_ASSERT_EQUALS(my_rules.get_total_supports(), \\\n          std::vector<size_t>({30, 20, 24, 12, 27, 20, 23, 13}));\n\n\n\n      my_itemset = {5, 3, 4};\n      my_rules = extract_relevant_rules(my_itemset, my_results);\n      // std::cout << my_rules << std::endl;\n      TS_ASSERT_EQUALS(my_rules.rules.size(), 7);\n      TS_ASSERT_EQUALS(my_rules.get_LHS_supports(), \\\n          std::vector<size_t>({40, 20, 27, 12, 27, 40, 40}));\n      TS_ASSERT_EQUALS(my_rules.get_RHS_supports(), \\\n          std::vector<size_t>({30, 20, 30, 20, 23, 23, 13}));\n      TS_ASSERT_EQUALS(my_rules.get_total_supports(), \\\n          std::vector<size_t>({30, 20, 24, 12, 20, 23, 13}));\n\n    }\n\n    // test rule_list::get_top_k_rules()\n    void testGetTopKRules(void) {\n      std::vector<size_t> id_order = {2, 3, 1, 4, 0};\n      gl_sframe closed_itemsets{{\"itemsets\", {flex_list{2, 1, 4},\n                                              flex_list{2, 3},\n                                              flex_list{2, 3, 1, 4},\n                                              flex_list{3, 1},\n                                              flex_list{2},\n                                              flex_list{3},\n                                              flex_list{1},\n                                              flex_list{1, 0},\n                                              flex_list{}}},\n                              {\"support\", {20, 24, 12, 20, 30, 27, 23, 13, 40}}};\n      fp_results_tree my_results = fp_results_tree(id_order);\n      my_results.build_tree(closed_itemsets);\n\n      std::vector<size_t> my_itemset = {2, 0};\n      auto my_rules = extract_relevant_rules(my_itemset, my_results);\n      // std::cout << my_rules;\n\n      flex_list _conf_rules = my_rules.get_top_k_rules(5, CONF_SCORE);\n      std::vector<flex_list> conf_rules;\n      for (const auto& cr: _conf_rules) {\n        conf_rules.push_back(cr);\n      }\n\n      // std::cout << conf_rules;\n      TS_ASSERT_EQUALS(conf_rules.size(), 5);\n      // First rule is 0 -> 1\n      TS_ASSERT_EQUALS(conf_rules[0][3], 13); // Support of 0\n      TS_ASSERT_EQUALS(conf_rules[0][4], 23); // Support of 1\n      TS_ASSERT_EQUALS(conf_rules[0][5], 13); // Support of 0,1\n      TS_ASSERT_DELTA(conf_rules[0][2], 1.0, 1e-6);\n\n      // Second rule is 2 -> 3\n      TS_ASSERT_EQUALS(conf_rules[1][3], 30);\n      TS_ASSERT_EQUALS(conf_rules[1][4], 27);\n      TS_ASSERT_EQUALS(conf_rules[1][5], 24);\n      TS_ASSERT_DELTA(conf_rules[1][2], 0.8, 1e-6);\n\n      // Third rule is [] -> 3\n      TS_ASSERT_EQUALS(conf_rules[2][3], 40);\n      TS_ASSERT_EQUALS(conf_rules[2][4], 27);\n      TS_ASSERT_EQUALS(conf_rules[2][5], 27);\n      TS_ASSERT_DELTA(conf_rules[2][2], 0.675, 1e-6);\n\n      flex_list _cosine_rules = my_rules.get_top_k_rules(500, COSINE_SCORE);\n      std::vector<flex_list> cosine_rules;\n      for (const auto& cr: _cosine_rules) {\n        cosine_rules.push_back(cr);\n      }\n\n      // std::cout << cosine_rules;\n      TS_ASSERT_EQUALS(cosine_rules.size(), 7);\n      TS_ASSERT_EQUALS(cosine_rules[0][0], flex_list{2});\n      TS_ASSERT_EQUALS(cosine_rules[0][1], flex_list{3});\n      TS_ASSERT_DELTA(cosine_rules[0][2], 24.0 / std::sqrt(30*27), 1e-3);\n      TS_ASSERT_EQUALS(cosine_rules[1][0], flex_list{});\n      TS_ASSERT_EQUALS(cosine_rules[1][1], flex_list{3});\n      TS_ASSERT_DELTA(cosine_rules[1][2], 27.0 / std::sqrt(27*40), 1e-3);\n\n    }\n    // Test extract_top_k_rules()\n    void testExtractTopKRules(void) {\n      std::vector<size_t> id_order = {2, 3, 1, 4, 0};\n      gl_sframe closed_itemsets{{\"itemsets\", {flex_list{2, 1, 4},\n                                              flex_list{2, 3},\n                                              flex_list{2, 3, 1, 4},\n                                              flex_list{3, 1},\n                                              flex_list{2},\n                                              flex_list{3},\n                                              flex_list{1},\n                                              flex_list{1, 0},\n                                              flex_list{}}},\n                              {\"support\", {20, 24, 12, 20, 30, 27, 23, 13, 40}}};\n      fp_results_tree my_results = fp_results_tree(id_order);\n      my_results.build_tree(closed_itemsets);\n\n      std::vector<size_t> my_itemset = {2, 0};\n\n      flex_list _conf_rules = extract_top_k_rules(my_itemset, my_results, 5, CONF_SCORE);\n      std::vector<flex_list> conf_rules;\n      for (const auto& cr: _conf_rules) {\n        conf_rules.push_back(cr);\n      }\n\n      // std::cout << conf_rules;\n      TS_ASSERT_EQUALS(conf_rules.size(), 5);\n      TS_ASSERT_DELTA(conf_rules[0][2], 1.0, 1e-6);\n      TS_ASSERT_DELTA(conf_rules[1][2], 0.8, 1e-6);\n      TS_ASSERT_DELTA(conf_rules[2][2], 0.675, 1e-6);\n\n      flex_list _cosine_rules = extract_top_k_rules(my_itemset, my_results, 500, COSINE_SCORE);\n      std::vector<flex_list> cosine_rules;\n      for (const auto& cr: _cosine_rules) {\n        cosine_rules.push_back(cr);\n      }\n\n      // std::cout << cosine_rules;\n      TS_ASSERT_EQUALS(cosine_rules.size(), 7);\n      TS_ASSERT_EQUALS(cosine_rules[0][0], flex_list{2});\n      TS_ASSERT_EQUALS(cosine_rules[0][1], flex_list{3});\n      TS_ASSERT_DELTA(cosine_rules[0][2], 24.0 / std::sqrt(30*27), 1e-3);\n      TS_ASSERT_EQUALS(cosine_rules[1][0], flex_list{});\n      TS_ASSERT_EQUALS(cosine_rules[1][1], flex_list{3});\n      TS_ASSERT_DELTA(cosine_rules[1][2], 27.0 / std::sqrt(27*40), 1e-3);\n    }\n\n\n};\n\n\nBOOST_FIXTURE_TEST_SUITE(_fp_rule_mining_test, fp_rule_mining_test)\nBOOST_AUTO_TEST_CASE(testConfidenceScore) {\n  fp_rule_mining_test::testConfidenceScore();\n}\nBOOST_AUTO_TEST_CASE(testLiftScore) {\n  fp_rule_mining_test::testLiftScore();\n}\nBOOST_AUTO_TEST_CASE(testAllConfidenceScore) {\n  fp_rule_mining_test::testAllConfidenceScore();\n}\nBOOST_AUTO_TEST_CASE(testMaxConfidenceScore) {\n  fp_rule_mining_test::testMaxConfidenceScore();\n}\nBOOST_AUTO_TEST_CASE(testKulcScore) {\n  fp_rule_mining_test::testKulcScore();\n}\nBOOST_AUTO_TEST_CASE(testCosineScore) {\n  fp_rule_mining_test::testCosineScore();\n}\nBOOST_AUTO_TEST_CASE(testConfScoreRules) {\n  fp_rule_mining_test::testConfScoreRules();\n}\nBOOST_AUTO_TEST_CASE(testLiftScoreRules) {\n  fp_rule_mining_test::testLiftScoreRules();\n}\nBOOST_AUTO_TEST_CASE(testAllConfScoreRules) {\n  fp_rule_mining_test::testAllConfScoreRules();\n}\nBOOST_AUTO_TEST_CASE(testMaxConfScoreRules) {\n  fp_rule_mining_test::testMaxConfScoreRules();\n}\nBOOST_AUTO_TEST_CASE(testKulcScoreRules) {\n  fp_rule_mining_test::testKulcScoreRules();\n}\nBOOST_AUTO_TEST_CASE(testCosineScoreRules) {\n  fp_rule_mining_test::testCosineScoreRules();\n}\nBOOST_AUTO_TEST_CASE(testExtractRelevantRules) {\n  fp_rule_mining_test::testExtractRelevantRules();\n}\nBOOST_AUTO_TEST_CASE(testGetTopKRules) {\n  fp_rule_mining_test::testGetTopKRules();\n}\nBOOST_AUTO_TEST_CASE(testExtractTopKRules) {\n  fp_rule_mining_test::testExtractTopKRules();\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "db2e02fd91d2389b2fe1bfd8790ee1f01f4276f9", "size": 16891, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/unity/toolkits/pattern_mining/rule_mining.cxx", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-26T12:36:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-26T12:36:11.000Z", "max_issues_repo_path": "test/unity/toolkits/pattern_mining/rule_mining.cxx", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:18:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:39:44.000Z", "max_forks_repo_path": "test/unity/toolkits/pattern_mining/rule_mining.cxx", "max_forks_repo_name": "ZeroInfinite/turicreate", "max_forks_repo_head_hexsha": "dd210c2563930881abd51fd69cb73007955b33fd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-21T17:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T17:46:28.000Z", "avg_line_length": 40.8983050847, "max_line_length": 97, "alphanum_fraction": 0.5584630869, "num_tokens": 5101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5190084937413051}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2006-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NASA Vision Workbench is licensed under the Apache License,\n//  Version 2.0 (the \"License\"); you may not use this file except in\n//  compliance with the License. You may obtain a copy of the License at\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// __END_LICENSE__\n\n\n#include <gtest/gtest_VW.h>\n#include <boost/random.hpp>\n#include <vw/config.h>\n#include <vw/Math/Functors.h>\n\nusing namespace vw;\nusing namespace vw::math;\n\nstatic const double DELTA = 1e-5;\n\ntemplate <class T1, class T2>\nstatic bool is_of_type( T2 ) {\n  return boost::is_same<T1,T2>::value;\n}\n\nTEST(Functors, Real) {\n  ArgRealFunctor f;\n  EXPECT_EQ( f(2.0), 2.0 );\n  EXPECT_EQ( f(std::complex<double>(2.0,3.0)), 2.0 );\n  EXPECT_TRUE( is_of_type<float>( f(float()) ) );\n  EXPECT_TRUE( is_of_type<double>( f(double()) ) );\n  EXPECT_TRUE( is_of_type<long double>( f((long double)(0)) ) );\n  EXPECT_TRUE( is_of_type<int>( f(int()) ) );\n  EXPECT_TRUE( is_of_type<float>( f(std::complex<float> ()) ) );\n  EXPECT_TRUE( is_of_type<double>( f(std::complex<double> ()) ) );\n  EXPECT_TRUE( is_of_type<long double>( f(std::complex<long double> ()) ) );\n  EXPECT_TRUE( is_of_type<int>( f(std::complex<int> ()) ) );\n}\n\nTEST(Functors, Imag) {\n  ArgImagFunctor f;\n  EXPECT_EQ( f(2.0), 0.0 );\n  EXPECT_EQ( f(std::complex<double>(2.0,3.0)), 3.0 );\n  EXPECT_TRUE( is_of_type<float>( f(float()) ) );\n  EXPECT_TRUE( is_of_type<double>( f(double()) ) );\n  EXPECT_TRUE( is_of_type<long double>( f((long double)(0)) ) );\n  EXPECT_TRUE( is_of_type<int>( f(int()) ) );\n  EXPECT_TRUE( is_of_type<float>( f(std::complex<float>()) ) );\n  EXPECT_TRUE( is_of_type<double>( f(std::complex<double>()) ) );\n  EXPECT_TRUE( is_of_type<long double>( f(std::complex<long double>()) ) );\n  EXPECT_TRUE( is_of_type<int>( f(std::complex<int>()) ) );\n}\n\nTEST(Functors, Abs) {\n  ArgAbsFunctor f;\n  EXPECT_EQ( f(2.0), 2.0 );\n  EXPECT_EQ( f(-2.0), 2.0 );\n  EXPECT_DOUBLE_EQ( f(std::complex<double>(3.0,4.0)), 5.0 );\n  EXPECT_TRUE( is_of_type<float>( f(float()) ) );\n  EXPECT_TRUE( is_of_type<double>( f(double()) ) );\n  EXPECT_TRUE( is_of_type<long double>( f((long double)(0)) ) );\n  EXPECT_TRUE( is_of_type<int>( f(int()) ) );\n  EXPECT_TRUE( is_of_type<float>( f(std::complex<float>()) ) );\n  EXPECT_TRUE( is_of_type<double>( f(std::complex<double>()) ) );\n  EXPECT_TRUE( is_of_type<long double>( f(std::complex<long double>()) ) );\n}\n\nTEST(Functors, Conj) {\n  ArgConjFunctor f;\n  EXPECT_EQ( f(2.0), 2.0 );\n  EXPECT_EQ( f(std::complex<double>(1.0,2.0)), std::complex<double>(1.0,-2.0) );\n  EXPECT_TRUE( is_of_type<float>( f(float()) ) );\n  EXPECT_TRUE( is_of_type<double>( f(double()) ) );\n  EXPECT_TRUE( is_of_type<long double>( f((long double)(0)) ) );\n  EXPECT_TRUE( is_of_type<int>( f(int()) ) );\n  EXPECT_TRUE( is_of_type<std::complex<float> >( f(std::complex<float>()) ) );\n  EXPECT_TRUE( is_of_type<std::complex<double> >( f(std::complex<double>()) ) );\n  EXPECT_TRUE( is_of_type<std::complex<long double> >( f(std::complex<long double>()) ) );\n  EXPECT_TRUE( is_of_type<std::complex<int> >( f(std::complex<int>()) ) );\n}\n\nTEST(Functors, Median){\n  MedianAccumulator<double> V;\n  V(8);\n  V(9);\n  V(3);\n  V(5);\n\n  // The median better be 6.5\n  EXPECT_TRUE( V.value() == 6.5 );\n}\n\nTEST(Functors, StdDev){\n  StdDevAccumulator<double> V;\n  V(8);\n  V(9);\n  V(3);\n  V(5);\n\n  EXPECT_TRUE( V.value() == 2.3848480035423640366 );\n}\n\nTEST(Functors, DestructiveMedian){\n\n  std::vector<double> V;\n  V.push_back(8);\n  V.push_back(9);\n  V.push_back(3);\n  V.push_back(5);\n\n  // The median better be 6.5\n  EXPECT_TRUE( destructive_median(V) == 6.5 );\n}\n\nTEST(Functors, DestructiveNmad){\n\n  std::vector<double> V;\n  V.push_back(8);\n  V.push_back(9);\n  V.push_back(3);\n  V.push_back(5);\n\n  EXPECT_TRUE( destructive_nmad(V) == 2.9652 );\n}\n\nTEST(Functors, DestructivePercentile){\n\n  std::vector<double> V, W;\n  V.push_back(8);\n  V.push_back(9);\n  V.push_back(3);\n  V.push_back(5);\n\n  // Start with new W each time, as it will be messed up\n\n  W = V; EXPECT_TRUE( destructive_percentile(V,   0) == 3 );\n  W = V; EXPECT_TRUE( destructive_percentile(V,  20) == 3 );\n  W = V; EXPECT_TRUE( destructive_percentile(V,  25) == 3 );\n  W = V; EXPECT_TRUE( destructive_percentile(V,  26) == 5 );\n  W = V; EXPECT_TRUE( destructive_percentile(V,  45) == 5 );\n  W = V; EXPECT_TRUE( destructive_percentile(V,  50) == 5 );\n  W = V; EXPECT_TRUE( destructive_percentile(V,  51) == 8 );\n  W = V; EXPECT_TRUE( destructive_percentile(V,  70) == 8 );\n  W = V; EXPECT_TRUE( destructive_percentile(V,  75) == 8 );\n  W = V; EXPECT_TRUE( destructive_percentile(V,  76) == 9 );\n  W = V; EXPECT_TRUE( destructive_percentile(V, 100) == 9 );\n  \n}\n\n#define TEST_UNARY_MATH_FUNCTOR(func,arg,result)                        \\\n  do {                                                                                                    \\\n    Arg##func##Functor f;                                                                                 \\\n    EXPECT_NEAR( (result), f((float)(arg)),       DELTA );                                                        \\\n    EXPECT_NEAR( (result), f((double)(arg)),      DELTA );                                                       \\\n    EXPECT_NEAR( (result), f((long double)(arg)), DELTA );                                                  \\\n    EXPECT_TRUE( is_of_type<float>(f((float)(arg))) );                                                      \\\n    EXPECT_TRUE( is_of_type<double>(f((double)(arg))) );                                                    \\\n    EXPECT_TRUE( is_of_type<long double>(f((long double)(arg))) );                                          \\\n    EXPECT_TRUE( is_of_type<double>(f((int)(arg))) );                                                       \\\n  } while(false)\n\n#define TEST_BINARY_MATH_FUNCTOR(func,arg1,arg2,result)                                                   \\\n  do {                                                                                                    \\\n    ArgArg##func##Functor f;                                                                              \\\n    EXPECT_NEAR( (result), f((float)(arg1),(float)(arg2)),             DELTA );                                         \\\n    EXPECT_NEAR( (result), f((double)(arg1),(double)(arg2)),           DELTA );                                       \\\n    EXPECT_NEAR( (result), f((long double)(arg1),(long double)(arg2)), DELTA );                             \\\n    EXPECT_TRUE( is_of_type<float>(f((float)(arg1),(float)(arg2))) );                                       \\\n    EXPECT_TRUE( is_of_type<double>(f((double)(arg1),(double)(arg2))) );                                    \\\n    EXPECT_TRUE( is_of_type<long double>(f((long double)(arg1),(long double)(arg2))) );                     \\\n    EXPECT_TRUE( is_of_type<double>( f((float)(arg1),(double)(arg2))) );                                    \\\n    EXPECT_TRUE( is_of_type<long double>( f((float)(arg1),(long double)(arg2))) );                          \\\n    EXPECT_TRUE( is_of_type<double>( f((int)(arg1),(int)(arg2))) );                                         \\\n    EXPECT_TRUE( is_of_type<float>( f((int)(arg1),(float)(arg2))) );                                        \\\n    EXPECT_NEAR( (result), ArgVal##func##Functor<float>(arg2)((float)(arg1)),             DELTA );                      \\\n    EXPECT_NEAR( (result), ArgVal##func##Functor<double>(arg2)((double)(arg1)),           DELTA );                    \\\n    EXPECT_NEAR( (result), ArgVal##func##Functor<long double>(arg2)((long double)(arg1)), DELTA );          \\\n    EXPECT_TRUE( is_of_type<float>(ArgVal##func##Functor<float>(arg2)((float)(arg1))) );                    \\\n    EXPECT_TRUE( is_of_type<double>(ArgVal##func##Functor<double>(arg2)((double)(arg1))) );                 \\\n    EXPECT_TRUE( is_of_type<long double>(ArgVal##func##Functor<long double>(arg2)((long double)(arg1))) );  \\\n    EXPECT_TRUE( is_of_type<double>( ArgVal##func##Functor<double>(arg2)((float)(arg1))) );                 \\\n    EXPECT_TRUE( is_of_type<long double>( ArgVal##func##Functor<long double>(arg2)((float)(arg1))) );       \\\n    EXPECT_TRUE( is_of_type<double>( ArgVal##func##Functor<int>((int)(arg2))((int)(arg1))) );               \\\n    EXPECT_TRUE( is_of_type<float>( ArgVal##func##Functor<float>(arg2)((int)(arg1))) );                     \\\n    EXPECT_NEAR( (result), ValArg##func##Functor<float>(arg1)((float)(arg2)),             DELTA );                      \\\n    EXPECT_NEAR( (result), ValArg##func##Functor<double>(arg1)((double)(arg2)),           DELTA );                    \\\n    EXPECT_NEAR( (result), ValArg##func##Functor<long double>(arg1)((long double)(arg2)), DELTA );          \\\n    EXPECT_TRUE( is_of_type<float>(ValArg##func##Functor<float>(arg1)((float)(arg2))) );                    \\\n    EXPECT_TRUE( is_of_type<double>(ValArg##func##Functor<double>(arg1)((double)(arg2))) );                 \\\n    EXPECT_TRUE( is_of_type<long double>(ValArg##func##Functor<long double>(arg1)((long double)(arg2))) );  \\\n    EXPECT_TRUE( is_of_type<double>( ValArg##func##Functor<float>(arg1)((double)(arg2))) );                 \\\n    EXPECT_TRUE( is_of_type<long double>( ValArg##func##Functor<float>(arg1)((long double)(arg2))) );       \\\n    EXPECT_TRUE( is_of_type<double>( ValArg##func##Functor<int>((int)(arg1))((int)(arg2))) );               \\\n    EXPECT_TRUE( is_of_type<float>( ValArg##func##Functor<int>((int)arg1)((float)(arg2))) );                \\\n  } while(false)\n\nTEST(Functors, Acos)  { TEST_UNARY_MATH_FUNCTOR(Acos,  0.5, 1.04719755);   }\nTEST(Functors, Asin)  { TEST_UNARY_MATH_FUNCTOR(Asin,  0.5, 0.523598776); }\nTEST(Functors, Atan)  { TEST_UNARY_MATH_FUNCTOR(Atan,  1.0, 0.785398163); }\nTEST(Functors, Cos)   { TEST_UNARY_MATH_FUNCTOR(Cos,   1.0, 0.540302306);  }\nTEST(Functors, Sin)   { TEST_UNARY_MATH_FUNCTOR(Sin,   1.0, 0.841471);  }\nTEST(Functors, Tan)   { TEST_UNARY_MATH_FUNCTOR(Tan,   1.0, 1.55741);   }\nTEST(Functors, Cosh)  { TEST_UNARY_MATH_FUNCTOR(Cosh,  1.0, 1.54308);  }\nTEST(Functors, Sinh)  { TEST_UNARY_MATH_FUNCTOR(Sinh,  1.0, 1.1752);   }\nTEST(Functors, Tanh)  { TEST_UNARY_MATH_FUNCTOR(Tanh,  1.0, 0.761594); }\nTEST(Functors, Exp)   { TEST_UNARY_MATH_FUNCTOR(Exp,   1.0, 2.718281);  }\nTEST(Functors, Log)   { TEST_UNARY_MATH_FUNCTOR(Log,   2.0, 0.693147);  }\nTEST(Functors, Log10) { TEST_UNARY_MATH_FUNCTOR(Log10, 2.0, 0.30103); }\nTEST(Functors, Sqrt)  { TEST_UNARY_MATH_FUNCTOR(Sqrt,  2.0, 1.41421);  }\nTEST(Functors, Ceil)  { TEST_UNARY_MATH_FUNCTOR(Ceil,  1.5, 2.0);\n                        TEST_UNARY_MATH_FUNCTOR(Ceil, -1.5, -1.0);    }\nTEST(Functors, Floor) { TEST_UNARY_MATH_FUNCTOR(Floor, 1.5, 1.0);\n                        TEST_UNARY_MATH_FUNCTOR(Floor,-1.5, -2.0);   }\n\nTEST(Functors, Atan2) { TEST_BINARY_MATH_FUNCTOR(Atan2,2.0,1.0,1.10715); }\nTEST(Functors, Pow)   { TEST_BINARY_MATH_FUNCTOR(Pow,3.0,2.0,9.0);  }\n\n#ifndef WIN32\nTEST(Functors, Acosh) { TEST_UNARY_MATH_FUNCTOR(Acosh,1.5,0.962424); }\nTEST(Functors, Asinh) { TEST_UNARY_MATH_FUNCTOR(Asinh,1.0,0.881374); }\nTEST(Functors, Atanh) { TEST_UNARY_MATH_FUNCTOR(Atanh,0.5,0.549306); }\n\n#ifdef VW_HAVE_EXP2\nTEST(Functors, Exp2)  { TEST_UNARY_MATH_FUNCTOR(Exp2,1.0,2.0); }\n#else\nTEST(Functors, DISABLED_Exp2)  { }\n#endif\n\n#ifdef VW_HAVE_LOG2\nTEST(Functors, Log2) { TEST_UNARY_MATH_FUNCTOR(Log2,2.0,1.0); }\n#else\nTEST(Functors, DISABLED_Log2) { }\n#endif\n\n#ifdef VW_HAVE_TGAMMA\nTEST(Functors, Tgamma) { TEST_UNARY_MATH_FUNCTOR(Tgamma,1.5,0.886227); }\n#else\nTEST(Functors, DISABLED_Tgamma) { }\n#endif\n\nTEST(Functors, Expm1)    { TEST_UNARY_MATH_FUNCTOR(Expm1,1.0,1.718281);  }\nTEST(Functors, Log1p)    { TEST_UNARY_MATH_FUNCTOR(Log1p,1.0,0.693147);  }\nTEST(Functors, Cbrt)     { TEST_UNARY_MATH_FUNCTOR(Cbrt,2.0,1.25992);    }\nTEST(Functors, Erf)      { TEST_UNARY_MATH_FUNCTOR(Erf,1.0,0.842701);    }\nTEST(Functors, Erfc)     { TEST_UNARY_MATH_FUNCTOR(Erfc,1.0,0.157299);   }\nTEST(Functors, Lgamma)   { TEST_UNARY_MATH_FUNCTOR(Lgamma,2.5,0.284683); }\nTEST(Functors, Round)    { TEST_UNARY_MATH_FUNCTOR(Round,1.4,1.0);\n                           TEST_UNARY_MATH_FUNCTOR(Round,1.5,2.0);       }\nTEST(Functors, Trunc)    { TEST_UNARY_MATH_FUNCTOR(Trunc,1.5,1.0);\n                           TEST_UNARY_MATH_FUNCTOR(Trunc,-1.5,-1.0);     }\n\nTEST(Functors, Hypot)    { TEST_BINARY_MATH_FUNCTOR(Hypot,2.0,1.0,2.23607); }\nTEST(Functors, Copysign) { TEST_BINARY_MATH_FUNCTOR(Copysign,3.0,-2.0,-3.0);\n                           TEST_BINARY_MATH_FUNCTOR(Copysign,3.0,2.0,3.0); }\nTEST(Functors, Fdim)     { TEST_BINARY_MATH_FUNCTOR(Fdim,3.0,2.0,1.0);\n                           TEST_BINARY_MATH_FUNCTOR(Fdim,2.0,3.0,0.0); }\n\n#endif\n\n\nTEST(Functiors, Median) {\n  MedianAccumulator<double> median;\n\n  boost::mt19937 random_gen(42);\n  boost::cauchy_distribution<double> cauchy(35,80);\n  boost::variate_generator<boost::mt19937&,\n    boost::cauchy_distribution<double> > generator(random_gen, cauchy);\n\n  for ( uint16 i = 0; i < 50000; i++ )\n    median( generator() );\n\n  EXPECT_NEAR( median.value(), 35.0, 1.5 );\n}\n\n", "meta": {"hexsha": "ab2acc94f81ab861650294e25628fd07b04f8a5c", "size": 13489, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/vw/Math/tests/TestFunctors.cxx", "max_stars_repo_name": "maxerbubba/visionworkbench", "max_stars_repo_head_hexsha": "b06ba0597cd3864bb44ca52671966ca580c02af1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 318.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T16:37:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T07:12:20.000Z", "max_issues_repo_path": "src/vw/Math/tests/TestFunctors.cxx", "max_issues_repo_name": "maxerbubba/visionworkbench", "max_issues_repo_head_hexsha": "b06ba0597cd3864bb44ca52671966ca580c02af1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2015-07-30T22:22:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-23T16:11:55.000Z", "max_forks_repo_path": "src/vw/Math/tests/TestFunctors.cxx", "max_forks_repo_name": "maxerbubba/visionworkbench", "max_forks_repo_head_hexsha": "b06ba0597cd3864bb44ca52671966ca580c02af1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 135.0, "max_forks_repo_forks_event_min_datetime": "2015-01-19T00:57:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T13:51:40.000Z", "avg_line_length": 47.6643109541, "max_line_length": 121, "alphanum_fraction": 0.5902587293, "num_tokens": 4028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5190084827352963}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Peter Caspers\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 sviinterpolation.hpp\n    \\brief Svi interpolation interpolation between discrete points\n*/\n\n#ifndef quantlib_svi_interpolation_hpp\n#define quantlib_svi_interpolation_hpp\n\n#include <ql/experimental/volatility/svismilesection.hpp>\n#include <ql/math/interpolations/xabrinterpolation.hpp>\n#include <boost/assign/list_of.hpp>\n#include <utility>\n\nnamespace QuantLib {\n\nnamespace detail {\n\ninline void checkSviParameters(const Real a, const Real b, const Real sigma,\n                               const Real rho, const Real m) {\n    QL_REQUIRE(b >= 0.0, \"b (\" << b << \") must be non negative\");\n    QL_REQUIRE(std::fabs(rho) < 1.0, \"rho (\" << rho << \") must be in (-1,1)\");\n    QL_REQUIRE(sigma > 0.0, \"sigma (\" << sigma << \") must be positive\");\n    QL_REQUIRE(a + b * sigma * std::sqrt(1.0 - rho * rho) >= 0.0,\n               \"a + b sigma sqrt(1-rho^2) (a=\" << a << \", b=\" << b << \", sigma=\"\n                                               << sigma << \", rho=\" << rho\n                                               << \") must be non negative\");\n    QL_REQUIRE(b * (1.0 + std::fabs(rho)) < 4.0,\n               \"b(1+|rho|) must be less than 4\");\n}\n\ninline Real sviTotalVariance(const Real a, const Real b, const Real sigma,\n                             const Real rho, const Real m, const Real k) {\n    return a +\n           b * (rho * (k - m) + std::sqrt((k - m) * (k - m) + sigma * sigma));\n}\n\ntypedef SviSmileSection SviWrapper;\n\nstruct SviSpecs {\n    Size dimension() { return 5; }\n    void defaultValues(std::vector<Real> &params,\n                       std::vector<bool> &paramIsFixed, const Real &forward,\n                       const Real expiryTime,\n                       const std::vector<Real> &addParams) {\n        if (params[2] == Null<Real>())\n            params[2] = 0.1;\n        if (params[3] == Null<Real>())\n            params[3] = -0.4;\n        if (params[4] == Null<Real>())\n            params[4] = 0.0;\n        if (params[1] == Null<Real>())\n            params[1] = 2.0 / (1.0 + std::fabs(params[3]));\n        if (params[0] == Null<Real>()) {\n            params[0] = std::max(\n                0.20 * 0.20 * expiryTime -\n                    params[1] * (params[3] * (-params[4]) +\n                                 std::sqrt((-params[4]) * (-params[4]) +\n                                           params[2] * params[2])),\n                -params[1] * params[2] *\n                std::sqrt(1.0 - params[3] * params[3]) + eps1());\n        }\n    }\n    void guess(Array &values, const std::vector<bool> &paramIsFixed,\n               const Real &forward, const Real expiryTime,\n               const std::vector<Real> &r, const std::vector<Real> &addParams) {\n        Size j = 0;\n        if (!paramIsFixed[2])\n            values[2] = r[j++] + eps1();\n        if (!paramIsFixed[3])\n            values[3] = (2.0 * r[j++] - 1.0) * eps2();\n        if (!paramIsFixed[4])\n            values[4] = (2.0 * r[j++] - 1.0);\n        if (!paramIsFixed[1])\n            values[1] = r[j++] * 4.0 / (1.0 + std::fabs(values[3])) * eps2();\n        if (!paramIsFixed[0])\n            values[0] = r[j++] * expiryTime -\n                        eps2() * (values[1] * values[2] *\n                                  std::sqrt(1.0 - values[3] * values[3]));\n    }\n    Array inverse(const Array &y, const std::vector<bool> &,\n                  const std::vector<Real> &, const Real) {\n        Array x(5);\n        x[2] = std::sqrt(y[2] - eps1());\n        x[3] = std::asin(y[3] / eps2());\n        x[4] = y[4];\n        x[1] = std::tan(y[1] / 4.0 * (1.0 + std::fabs(y[3])) / eps2() * M_PI -\n                        M_PI / 2.0);\n        x[0] = std::sqrt(y[0] - eps1() +\n                         y[1] * y[2] * std::sqrt(1.0 - y[3] * y[3]));\n        return x;\n    }\n    Real eps1() { return 0.000001; }\n    Real eps2() { return 0.999999; }\n    Array direct(const Array &x, const std::vector<bool> &paramIsFixed,\n                 const std::vector<Real> &params, const Real forward) {\n        Array y(5);\n        y[2] = x[2] * x[2] + eps1();\n        y[3] = std::sin(x[3]) * eps2();\n        y[4] = x[4];\n        if (paramIsFixed[1])\n            y[1] = params[1];\n        else\n            y[1] = (std::atan(x[1]) + M_PI / 2.0) / M_PI * eps2() * 4.0 /\n                   (1.0 + std::fabs(y[3]));\n        if (paramIsFixed[0])\n            y[0] = params[0];\n        else\n            y[0] = eps1() + x[0] * x[0] -\n                   y[1] * y[2] * std::sqrt(1.0 - y[3] * y[3]);\n        return y;\n    }\n    Real weight(const Real strike, const Real forward, const Real stdDev,\n                const std::vector<Real> &addParams) {\n        return blackFormulaStdDevDerivative(strike, forward, stdDev, 1.0);\n    }\n    typedef SviWrapper type;\n    ext::shared_ptr<type> instance(const Time t, const Real &forward,\n                                     const std::vector<Real> &params,\n                                     const std::vector<Real> &addParams) {\n        return ext::make_shared<type>(t, forward, params);\n    }\n};\n}\n\n//! %Svi smile interpolation between discrete volatility points.\nclass SviInterpolation : public Interpolation {\n  public:\n    template <class I1, class I2>\n    SviInterpolation(const I1 &xBegin, // x = strikes\n                     const I1 &xEnd,\n                     const I2 &yBegin, // y = volatilities\n                     Time t,           // option expiry\n                     const Real &forward, Real a, Real b, Real sigma, Real rho,\n                     Real m, bool aIsFixed, bool bIsFixed, bool sigmaIsFixed,\n                     bool rhoIsFixed, bool mIsFixed, bool vegaWeighted = true,\n                     const ext::shared_ptr<EndCriteria> &endCriteria =\n                         ext::shared_ptr<EndCriteria>(),\n                     const ext::shared_ptr<OptimizationMethod> &optMethod =\n                         ext::shared_ptr<OptimizationMethod>(),\n                     const Real errorAccept = 0.0020,\n                     const bool useMaxError = false,\n                     const Size maxGuesses = 50) {\n\n        impl_ = ext::shared_ptr<Interpolation::Impl>(\n            new detail::XABRInterpolationImpl<I1, I2, detail::SviSpecs>(\n                xBegin, xEnd, yBegin, t, forward,\n                boost::assign::list_of(a)(b)(sigma)(rho)(m),\n                boost::assign::list_of(aIsFixed)(bIsFixed)(sigmaIsFixed)(\n                    rhoIsFixed)(mIsFixed),\n                vegaWeighted, endCriteria, optMethod, errorAccept, useMaxError,\n                maxGuesses));\n        coeffs_ = ext::dynamic_pointer_cast<\n            detail::XABRCoeffHolder<detail::SviSpecs> >(impl_);\n    }\n    Real expiry() const { return coeffs_->t_; }\n    Real forward() const { return coeffs_->forward_; }\n    Real a() const { return coeffs_->params_[0]; }\n    Real b() const { return coeffs_->params_[1]; }\n    Real sigma() const { return coeffs_->params_[2]; }\n    Real rho() const { return coeffs_->params_[3]; }\n    Real m() const { return coeffs_->params_[4]; }\n    Real rmsError() const { return coeffs_->error_; }\n    Real maxError() const { return coeffs_->maxError_; }\n    const std::vector<Real> &interpolationWeights() const {\n        return coeffs_->weights_;\n    }\n    EndCriteria::Type endCriteria() { return coeffs_->XABREndCriteria_; }\n\n  private:\n    ext::shared_ptr<detail::XABRCoeffHolder<detail::SviSpecs> > coeffs_;\n};\n\n//! %Svi interpolation factory and traits\nclass Svi {\n  public:\n    Svi(Time t,\n        Real forward,\n        Real a,\n        Real b,\n        Real sigma,\n        Real rho,\n        Real m,\n        bool aIsFixed,\n        bool bIsFixed,\n        bool sigmaIsFixed,\n        bool rhoIsFixed,\n        bool mIsFixed,\n        bool vegaWeighted = false,\n        ext::shared_ptr<EndCriteria> endCriteria = ext::shared_ptr<EndCriteria>(),\n        ext::shared_ptr<OptimizationMethod> optMethod = ext::shared_ptr<OptimizationMethod>(),\n        const Real errorAccept = 0.0020,\n        const bool useMaxError = false,\n        const Size maxGuesses = 50)\n    : t_(t), forward_(forward), a_(a), b_(b), sigma_(sigma), rho_(rho), m_(m), aIsFixed_(aIsFixed),\n      bIsFixed_(bIsFixed), sigmaIsFixed_(sigmaIsFixed), rhoIsFixed_(rhoIsFixed),\n      mIsFixed_(mIsFixed), vegaWeighted_(vegaWeighted), endCriteria_(std::move(endCriteria)),\n      optMethod_(std::move(optMethod)), errorAccept_(errorAccept), useMaxError_(useMaxError),\n      maxGuesses_(maxGuesses) {}\n    template <class I1, class I2>\n    Interpolation interpolate(const I1 &xBegin, const I1 &xEnd,\n                              const I2 &yBegin) const {\n        return SviInterpolation(xBegin, xEnd, yBegin, t_, forward_, a_, b_,\n                                 sigma_, rho_, m_, aIsFixed_, bIsFixed_,\n                                 sigmaIsFixed_, rhoIsFixed_, mIsFixed_,\n                                 vegaWeighted_, endCriteria_, optMethod_,\n                                 errorAccept_, useMaxError_, maxGuesses_);\n    }\n    static const bool global = true;\n\n  private:\n    Time t_;\n    Real forward_;\n    Real a_, b_, sigma_, rho_, m_;\n    bool aIsFixed_, bIsFixed_, sigmaIsFixed_, rhoIsFixed_, mIsFixed_;\n    bool vegaWeighted_;\n    const ext::shared_ptr<EndCriteria> endCriteria_;\n    const ext::shared_ptr<OptimizationMethod> optMethod_;\n    const Real errorAccept_;\n    const bool useMaxError_;\n    const Size maxGuesses_;\n};\n}\n\n#endif\n", "meta": {"hexsha": "370c18414a610160494ed3a017e5119b96056223", "size": 10134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/volatility/sviinterpolation.hpp", "max_stars_repo_name": "thejourneyofman/QuantLib", "max_stars_repo_head_hexsha": "98467eaf6d1a20885f05ea1aa602bb8380c39390", "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": "ql/experimental/volatility/sviinterpolation.hpp", "max_issues_repo_name": "thejourneyofman/QuantLib", "max_issues_repo_head_hexsha": "98467eaf6d1a20885f05ea1aa602bb8380c39390", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/volatility/sviinterpolation.hpp", "max_forks_repo_name": "thejourneyofman/QuantLib", "max_forks_repo_head_hexsha": "98467eaf6d1a20885f05ea1aa602bb8380c39390", "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.7037037037, "max_line_length": 99, "alphanum_fraction": 0.5496348924, "num_tokens": 2716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.5190084772322918}}
{"text": "/* CHOMP class implementation\n *\n * Copyright (C) 2016 Rafael Valencia. All rights reserved.\n * License (3-Cluase BSD): https://github.com/rafaelvalencia\n * \n * This code uses and is based on code from:\n *   Project: trychomp https://github.com/poftwaresatent/trychomp\n *   Copyright (C) 2014 Roland Philippsen. All rights reserved.\n *   License (3-Clause BSD) : https://github.com/poftwaresatent/trychomp\n * **\n * \\file chomp.cpp\n *\n * CHOMP for point vehicles (x,y) moving holonomously in the plane. It will\n * plan a trajectory (xi) connecting start point (qs) to end point (qe) while\n * avoiding obstacles (obs)\n */\n#include \"path_adaptor.hpp\"\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <stdlib.h>\n#include <sys/time.h>\n#include <err.h>\n#include <algorithm>\n\ntypedef Eigen::VectorXd Vector;\ntypedef Eigen::MatrixXd Matrix;\ntypedef Eigen::Isometry3d Transform;\nstatic size_t const obs_dim(3); \t// obstacle dimensions (x,y,Radius)\n\nusing namespace std;\n\n#define INF 1E20\n#define epsilon 2.0\n\nstatic double *dt(double *f, int n) {\n  double *d = new double[n];\n  int *v = new int[n];\n  double *z = new double[n+1];\n  int k = 0;\n  v[0] = 0;\n  z[0] = -INF;\n  z[1] = +INF;\n  for (int q = 1; q <= n-1; q++) {        // Compute lower envelope\n    double s  = ((f[q]+pow(q,2.0))-(f[v[k]]+pow(v[k],2.0)))/(2*q-2*v[k]);\n    while (s <= z[k]) {\n      k--;\n      s  = ((f[q]+pow(q,2.0))-(f[v[k]]+pow(v[k],2.0)))/(2*q-2*v[k]);\n    }\n    k++;\n    v[k] = q;\n    z[k] = s;\n    z[k+1] = +INF;\n  }\n\n  k = 0;\n  for (int q = 0; q <= n-1; q++) {\n    while (z[k+1] < q)\n      k++;\n    d[q] = pow(q-v[k],2.0) + f[v[k]];\n  }\n\n  delete [] v;\n  delete [] z;\n  return d;\n}\n\n\n\nMatrix ComputeDistanceTranform(Matrix cost_init){\n\n\tint width = cost_init.rows();\n\tint height = cost_init.cols();\n\tdouble *f = new double[max(width, height)];\n\n\t// transfrom over rows\n\tfor (int x=0; x < width; x++){\n\t\tfor (int y=0; y<height; y++){\n\t\t\tf[y] = cost_init(x,y);\n\t\t}\n\t\tdouble *d = dt(f,height);\n\t\tfor (int y=0; y< height; y++){\n\t\t\tcost_init(x,y) = d[y];\n\t\t}\n\t\tdelete [] d;\n\t}\n\n\t//cout << cost_init << endl;\n\n\t// transfrom over columns\n\tfor (int y=0; y < height; y++){\n\t\tfor (int x=0; x < width; x++ ){\n\t\t\tf[x] = cost_init(x,y);\n\t\t}\n\t\tdouble *d = dt(f, width);\n\t\tfor (int x=0; x < width; x++){\n\t\t\tcost_init(x,y) = d[x];\n\t\t}\n\t\tdelete [] d;\n\t}\n\n\tdelete f;\n\n\t//cout << cost_init << endl;\n\treturn cost_init;\n\n}\n\n\nCHOMP::CHOMP(double dt_input, double eta_input, double lambda_input, size_t nq_input, size_t cdim_input, size_t numIt_input, double gain, double gamma_input) \n{\n\t//Sets basic parameters.\t\n\tnq_ = nq_input;\t\t\t// number of poses q in xi\n\tcdim_ = cdim_input;\t\t// dimension of config space\n\txidim_ = nq_ * cdim_; \t// dimension of trajectory, xidim = nq * cdim\n\tdt_ =  dt_input;\t    // time step\n\teta_ = eta_input; \t\t// >= 1, regularization factor for gradient descent\n\tlambda_ = lambda_input; // weight of smoothness objective\t\n\tnumIt_  = numIt_input; \t// Number of iterations\n\tcostGain_ = gain;\t\t// Gain inside cost function (usually 10) \n\tgamma_ = gamma_input;\n\t\n\tres_ = 0.0001;\t\t\t// Residual from optimization\n\tcter_ = 0;\t\t\t\t// Zero iterations so far\n\t\n\tPATH_INIT_ = false;     // path is not initialized yet\n\t\n\tOBS_ = Matrix::Zero (obs_dim, 1); //initialize obstacle matrix\n\t\n\tcout << \"-----------------------------------------------------:\"<< endl;  \t\t  \t\n\tcout << \"CHOMP has the following parameters:\"<< endl;  \n\tcout << \"-----------------------------------------------------:\"<< endl;  \t  \t\n\tcout << \"Time step: \" << dt_ << endl;   \n\tcout << \"Eta: \" << eta_ << endl;  \n\tcout << \"Lambda: \" << lambda_ << endl;  \t\n\tcout << \"Number of poses in xi: \" << nq_ << endl;\n\tcout << \"Dimensions of config. space: \" << cdim_ << endl;\t\n\tcout << \"Number of iterations: \" << numIt_ << endl;\n\tcout << \"Cost function gain: \" << costGain_ << endl;\n\tcout << \"-----------------------------------------------------:\"<< endl;  \n\t\t  \t\n}\n\nvoid CHOMP::makeGrid(double xmin, double ymin, double xmax, double ymax)\n{\n\tint xdim = (int) xmax - xmin;\n\tint ydim = (int) ymax - ymin;\n\tgrid_ = Matrix::Zero (xdim, ydim);\n}\n\ndouble CHOMP::chompIteration(Vector  &xi, Vector &ti)\n{  \n\t\n\t// Before performing the iteration check if a path has been given\n\t\n\tif (PATH_INIT_==false)\n\t{\n\t\tcout << \"A path was not initialized. Leaving CHOMP iteration! \" << endl;\n\t\treturn NAN;\t\n\t}\n\t\n\t//////////////////////////////////////////////////\n\t// beginning of \"the\" CHOMP iteration\n\t\n\tVector nabla_smooth (AA_ * xi_ + bb_);\n\tVector nabla_smooth_time(gamma_* (BB_ * ti_ + tt_));\n\n\tVector const & xidd (- nabla_smooth); // indeed, it is the same in this formulation...\n\tVector const & tidd ( - nabla_smooth_time/gamma_);  // t''\n\n\tVector nabla_obs (Vector::Zero (xidim_));  // xidim_ : dimension of trajectory\n\tVector nabla_obs_time (Vector::Zero (nq_));\n\n\tfor (size_t iq (0); iq < nq_; ++iq) \n\t{\n\t\tVector const qq (xi_.block (iq * cdim_, 0, cdim_, 1));\n\t\tdouble currentTime = ti_(iq);\n\n\t\tVector qd;\n\t\tdouble tprime;\n\n\t\tif (0 == iq) {\n\t\t\t//cout << \"block:  \" << xi_.block ((iq+1) * cdim_, 0, cdim_, 1) << endl;\n\t\t  qd = 0.5 * (xi_.block ((iq+1) * cdim_, 0, cdim_, 1) - qs_);\n\t\t  tprime =  1/(2*dt_) * (ti_(iq+1) - ts_); \n\t\t}\n\t\telse if (iq == nq_ - 1) {\n\t\t  qd = 0.5 * (qe_ - xi_.block ((iq-1) * cdim_, 0, cdim_, 1));\n\t\t  tprime = 1/(2*dt_) * (te_ - ti_(iq-1));\n\t\t}\n\t\telse {\n\t\t  qd = 0.5 * (xi_.block ((iq+1) * cdim_, 0, cdim_, 1) - xi_.block ((iq-1) * cdim_, 0, cdim_, 1));\n\t\t  tprime = 1/(2*dt_) * (ti_(iq+1) - ti_(iq-1));\n\t\t}\n\n\t\t//cout << \"qs_  \" << qs_ << endl;\n\t\t//cout << \"qe_  \" << qe_ << endl;\n\t\t//cout << \"xi_  \"  << xi_ << endl;\n\t\t//cout << \"qd_  \" << qd << endl;\n\t\t//cout << \"xidd_  \" << xidd << endl;\n\t\t// In this case, C and W are the same, Jacobian is identity.  We\n\t\t// still write more or less the full-fledged CHOMP expressions\n\t\t// (but we only use one body point) to make subsequent extension\n\t\t// easier.\n\t\t//\n\t\tVector const & xx (qq);          // currentTime equivalent to this\n\t\tVector const & xd (qd);\n\t\tMatrix const JJ (Matrix::Identity (2, 2)); // a little silly here, as noted above.\n\t\tdouble const vel (xd.norm());         // tprime equivalent to this\n\t\tif (vel < 1.0e-3 || tprime < 1.0e-3) \n\t\t{\n\t\t\t// avoid div by zero further down\n\t\t\tcontinue;\n\t\t}\n\t\tVector const xdn (xd / vel);\n\t\tVector const xdd (JJ * xidd.block (iq * cdim_, 0, cdim_ , 1));\n\t\tMatrix const prj (Matrix::Identity (2, 2) - xdn * xdn.transpose()); // hardcoded planar case\n\t\tVector const kappa (prj * xdd / pow (vel, 2.0));\n\t\tMatrix delta = Matrix::Zero(2,1);\n\t\tdouble cost;\n\n\t\t//Add obstacles\t\t \n\t\tfor (int ii = 0; ii < OBS_.cols(); ii++) \n\t\t{\n\t\t\t\n\t\t\t/*\n\t\t\tVector delta(xx - OBS_.block(0, ii, 2, 1));\n\t\t\tdouble const dist(delta.norm());\n\t\t\tif ((dist >= OBS_(2, ii)) || (dist < 1e-9))   // Maxdist = radius*2\n\t\t\t\tcontinue;\n\t\t\t//double const cost(costGain_ * OBS_(2, ii) * pow(1.0 - dist / OBS_(2, ii), 3.0) / 3.0); \n\t\t\tdouble const cost(OBS_(2, ii) * pow(1.0 - dist / OBS_(2, ii), 3.0) / 3.0);   \n\t\t\tdelta *= - costGain_ *pow(1.0 - dist / OBS_(2, ii), 2.0) / dist;\n\t\t\t*/\n\t\t\t\n\t\t\t//cout << \"xx: \" << xx(0) << \" \" << xx(1) << endl;\n\n\t\t\tint a = (int)xx(0);\n\t\t\tint b = (int)xx(1);\n\n\t\t\t// cout << \"a \" << a <<  \"  \"  << \"b \" << b << endl;\n\n\t\t\tdouble distanceField = Dx_(a, b);\n\n\t\t\tdelta(0,0) =  Dx_(a+1,b) - Dx_(a-1,b);\n\t\t\tdelta(1,0) =  Dx_(a,b+1) - Dx_(a,b-1) ;  \n\n\t\t\t//cout << distanceField << endl;\n\t\t\t\n\t\t\tif (distanceField > epsilon)\n\t\t\t\tcontinue;\n\n\t\t\t\n\t\t\tif (distanceField < 0)\n\t\t\t{\n\t\t\t\t cost = -costGain_*distanceField + 0.5*epsilon;\n\t\t\t\t delta = delta*-1;\n\t\t\t}\n\n\t\t\telse if (distanceField <= epsilon)\n\t\t\t{\n\t\t\t\tcost = 0.5*epsilon*pow(distanceField - epsilon,2);\n\t\t\t\tdelta = delta*(Dx_(a,b) - epsilon)/epsilon;\n\t\t\t}  \n\t\t\t   \n\n\t\t\t\n\n\t\t\t//cout << \"JJ transpose  \" << JJ.transpose() << endl;\n\t\t\t//cout << \"velocity \" << vel << endl;\n\t\t\t//cout << \"projection matrix \" << prj << endl;\n\t\t\t//cout << \"cost \" << cost << endl;\n\t\t\t//cout << \"kappa \" << kappa << endl;\n\t\t\t//cout << \"delta  \" << delta << endl;\n\n\n\t\t\tnabla_obs.block(iq * cdim_, 0, cdim_, 1) += JJ.transpose() * vel * (prj * delta - cost * kappa);\n\t\t} \n\t\t\n\t}\n\n\tVector dxi (Ainv_ * (nabla_obs + lambda_ * nabla_smooth));\n\n \t//cout << \"change \" << dxi / eta_ << endl;\n\n\txi_ -= dxi / eta_;\n\t\n\txi = xi_; //updated path\n\t\n\tres_ = dxi.norm() / eta_;\n\t\n\treturn res_;\n\t// end of \"the\" CHOMP iteration\n\t//////////////////////////////////////////////////\n}\n\n\ndouble CHOMP::chompUpdate(Vector  &xi, double &U_cost, double &curv)\n{  \n\t\n\t// Before performing the iteration check if a path has been given\n\t\n\tif (PATH_INIT_==false)\n\t{\n\t\tcout << \"A path was not initialized. Leaving CHOMP iteration! \" << endl;\n\t\treturn NAN;\t\n\t}\n\t\n\t//////////////////////////////////////////////////\n\t// beginning of \"the\" CHOMP iteration\n\t\n\tdouble U(NAN); //cost functional value\n\tdouble F_obs(0);//obstacle functional value\n\tdouble F_smooth(0);//obstacle functional value\n\tdouble curvature(0); //curvature\t\n\n\tVector nabla_smooth (AA_ * xi_ + bb_);\n\tVector const & xidd (nabla_smooth); // indeed, it is the same in this formulation...\n\n\tVector nabla_obs (Vector::Zero (xidim_));\n\tfor (size_t iq (0); iq < nq_; ++iq) \n\t{\n\t\tVector const qq (xi_.block (iq * cdim_, 0, cdim_, 1));\n\t\tVector qd;\n\t\tif (0 == iq) {\n\t\t  qd = 0.5 * (xi_.block ((iq+1) * cdim_, 0, cdim_, 1) - qs_);\n\t\t}\n\t\telse if (iq == nq_ - 1) {\n\t\t  qd = 0.5 * (qe_ - xi_.block ((iq-1) * cdim_, 0, cdim_, 1));\n\t\t}\n\t\telse {\n\t\t  qd = 0.5 * (xi_.block ((iq+1) * cdim_, 0, cdim_, 1) - xi_.block ((iq-1) * cdim_, 0, cdim_, 1));;\n\t\t}\n\n\t\t// In this case, C and W are the same, Jacobian is identity.  We\n\t\t// still write more or less the full-fledged CHOMP expressions\n\t\t// (but we only use one body point) to make subsequent extension\n\t\t// easier.\n\t\t//\n\t\tVector const & xx (qq);\n\t\tVector const & xd (qd);\n\t\tMatrix const JJ (Matrix::Identity (2, 2)); // a little silly here, as noted above.\n\t\tdouble const vel (xd.norm());\n\t\tif (vel < 1.0e-3) \n\t\t{\n\t\t\t// avoid div by zero further down\n\t\t\tcontinue;\n\t\t}\n\t\tVector const xdn (xd / vel);\n\t\tVector const xdd (JJ * xidd.block (iq * cdim_, 0, cdim_ , 1));\n\t\tMatrix const prj (Matrix::Identity (2, 2) - xdn * xdn.transpose()); // hardcoded planar case\n\t\tVector const kappa (prj * xdd / pow (vel, 2.0));\n\t\t\n\t\t//curvature\n\t\tcurvature += kappa.norm();\n\t\t\n\t\tdouble acc_cost(0); //sum of cost function values from all obstacles at a given robot pose\n\t\t\t\t\n\t\t//Add obstacles\t\t \n\t\tfor (int ii = 0; ii < OBS_.cols(); ii++) \n\t\t{\n\t\t\tVector delta(xx - OBS_.block(0, ii, 2, 1));\n\t\t\tdouble const dist(delta.norm());\n\t\t\tif ((dist >= OBS_(2, ii)) || (dist < 1e-9))\n\t\t\t\tcontinue;\n\t\t\tdouble const cost(costGain_ * OBS_(2, ii) * pow(1.0 - dist / OBS_(2, ii), 3.0) / 3.0);  \n\t\t\tdelta *= - costGain_ *pow(1.0 - dist / OBS_(2, ii), 2.0) / dist;                        \n\t\t\tnabla_obs.block(iq * cdim_, 0, cdim_, 1) += JJ.transpose() * vel * (prj * delta - cost * kappa);\n\t\t\tacc_cost += cost;\n\t\t} \n\t\t\n\t\t//smoothness and obstacle costs\n\t\tF_smooth +=    pow(vel / dt_, 2.0); \n\t\tF_obs +=    acc_cost * (vel / dt_); \t\t\n\t}\n\t\n\t//compute cost functional (from smoothness and obstacle costs)\n\tU =  (F_obs + 0.5 * lambda_ * F_smooth ) / (nq_ + 1);\n    U_cost = U;\n\n    //normalize curvature to size\n    curv =   curvature / (nq_ + 1);\n    \n\tVector dxi (Ainv_ * (nabla_obs + lambda_ * nabla_smooth));\n\txi_ -= dxi / eta_;\n\t\n\txi = xi_; //updated path\n\t\n\tres_ = dxi.norm() / eta_;\n\t\n\treturn res_;\n\t// end of \"the\" CHOMP iteration\n\t//////////////////////////////////////////////////\n}\n\n\ndouble CHOMP::chompUpdateWithSearchRegion(Vector  &xi, double theta, double &U_cost, double &curv)\n{  \n\t\n\t// Before performing the iteration check if a path has been given\n\t\n\tif (PATH_INIT_==false)\n\t{\n\t\tcout << \"A path was not initialized. Leaving CHOMP iteration! \" << endl;\n\t\treturn NAN;\t\n\t}\n\t\n\t//////////////////////////////////////////////////\n\t//Compute transformation between global and starting vehicle's reference frames (qs_). \n\tEigen::Matrix4d T_global2local, T_local2global;\n\tT_local2global   <<   cos(theta), -sin(theta), \t0, \tqs_(0),\n\t\t\t\t\t\t  sin(theta),  cos(theta), \t0, \tqs_(1),\n\t\t\t\t\t\t  0, \t\t\t\t\t0, \t1, \t0,\n\t\t\t\t\t\t  0,\t\t\t\t\t0,\t0,\t1;\n\tT_global2local = \tT_local2global.inverse();\t\t\t  \n\t\n\t//Slope for lines defining search region\t\n\tdouble m  = 1.; // lines at qs_ with 45 deg of slope \n\t\t\n\t//////////////////////////////////////////////////\n\t// beginning of \"the\" CHOMP iteration\n\t\n\tdouble U(NAN); //cost functional value\n\tdouble F_obs(0);//obstacle functional value\n\tdouble F_smooth(0);//obstacle functional value\n\tdouble curvature(0); //curvature\n\n\tVector nabla_smooth (AA_ * xi_ + bb_);\n\tVector const & xidd (nabla_smooth); // indeed, it is the same in this formulation...\n\n\tVector nabla_obs (Vector::Zero (xidim_));\n\tfor (size_t iq (0); iq < nq_; ++iq) \n\t{\n\t\tVector const qq (xi_.block (iq * cdim_, 0, cdim_, 1));\n\t\tVector qd;\n\t\tif (0 == iq) {\n\t\t  qd = 0.5 * (xi_.block ((iq+1) * cdim_, 0, cdim_, 1) - qs_);\n\t\t}\n\t\telse if (iq == nq_ - 1) {\n\t\t  qd = 0.5 * (qe_ - xi_.block ((iq-1) * cdim_, 0, cdim_, 1));\n\t\t}\n\t\telse {\n\t\t  qd = 0.5 * (xi_.block ((iq+1) * cdim_, 0, cdim_, 1) - xi_.block ((iq-1) * cdim_, 0, cdim_, 1));;\n\t\t}\n\n\t\t// In this case, C and W are the same, Jacobian is identity.  We\n\t\t// still write more or less the full-fledged CHOMP expressions\n\t\t// (but we only use one body point) to make subsequent extension\n\t\t// easier.\n\t\t//\n\t\tVector const & xx (qq);\n\t\tVector const & xd (qd);\n\t\tMatrix const JJ (Matrix::Identity (2, 2)); // a little silly here, as noted above.\n\t\tdouble const vel (xd.norm());\n\t\tif (vel < 1.0e-3) \n\t\t{\n\t\t\t// avoid div by zero further down\n\t\t\tcontinue;\n\t\t}\n\t\tVector const xdn (xd / vel);\n\t\tVector const xdd (JJ * xidd.block (iq * cdim_, 0, cdim_ , 1));\n\t\tMatrix const prj (Matrix::Identity (2, 2) - xdn * xdn.transpose()); // hardcoded planar case\n\t\tVector const kappa (prj * xdd / pow (vel, 2.0));\n\t\tdouble gain;\n\t\n\t\t//curvature\n\t\tcurvature += kappa.norm();\n\t\t\n\t\tdouble acc_cost(0); //sum of cost function values from all obstacles at a given robot pose\n\t\t//Consider obstacles\t\t \n\t\tfor (int ii = 0; ii < OBS_.cols(); ii++) \n\t\t{\n\t\t\t//Check search region, if it is outside the search region set a high obs. function gain\n\t\t\tEigen::Vector4d xx_l, xx_g;\n\t\t\txx_g << xx(0), xx(1), 0, 1;\n\t\t\t\n\t\t\txx_l =  T_global2local *  xx_g;\n\t\t\t\n\t\t\t//allow only poses infront of initial position (avoids reverse motion paths)  \n\t\t\t//if( ( xx_l(0) > 0 ) ) \n\t\t\t//no reverse motion paths & inside a region defined by 2 lines centered at qs_\n\t\t\tif( ( xx_l(0) > 0 ) && ( xx_l(1) < m * xx_l(0) ) && (  xx_l(1) > - m * xx_l(0) ) )\n\t\t\t{\n\t\t\t\t//Inside desired search region\n\t\t\t\tgain = costGain_;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//Outside desired search region\n\t\t\t\tgain = 1000 * costGain_;\t\n\t\t\t\tcout << \" Outside desired search region!!! \" << endl;\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tVector delta(xx - OBS_.block(0, ii, cdim_, 1));\n\t\t\tdouble const dist(delta.norm());\n\t\t\tif ((dist >= OBS_(2, ii)) || (dist < 1e-9))\n\t\t\t\tcontinue;\n\t\t\tdouble const cost(gain * OBS_(2, ii) * pow(1.0 - dist / OBS_(2, ii), 3.0) / 3.0);  \n\t\t\tdelta *= - gain *pow(1.0 - dist / OBS_(2, ii), 2.0) / dist;                        \n\t\t\tnabla_obs.block(iq * cdim_, 0, cdim_, 1) += JJ.transpose() * vel * (prj * delta - cost * kappa);\n\t\t\tacc_cost += cost;\n\t\t} \n\t\t\n\t\t//smoothness and obstacle costs\n\t\tF_smooth +=    pow(vel / dt_, 2.0); \n\t\tF_obs +=    acc_cost * (vel / dt_); \n\t\t\n\n\t}\n\n\t//compute cost functional (from smoothness and obstacle costs)\n\tU =  (F_obs + 0.5 * lambda_ * F_smooth ) / (nq_ + 1);\n    U_cost = U;\n    \n    //normalize curvature to size\n    curv =   curvature / (nq_ + 1);\n\t\n\tVector dxi (Ainv_ * (nabla_obs + lambda_ * nabla_smooth));\n\txi_ -= dxi / eta_;\n\t\n\txi = xi_; //updated path\n\t\n\t++cter_; // increase iteration counter\t\n\t\n\tres_ = dxi.norm() / eta_;\n\tcout << \"It No. \" << cter_ << \" Res.: \" << dxi.norm() / eta_<< \" Cost: \" << U << \" Curvature:\" << curv << endl;\n\t\n\t//Detect local minimum\t\n\tif(cter_ > 1000 && res_ > 0.1)\n\t{\n\t\tcout << \"LOCAL MINIMUM DETECTED! \" << endl;\n\t\tfor (size_t ii (0); ii < xidim_; ++ii) \n\t\t{\n\t\t\t double noise = 0.1 * (- 50 + rand() % 100); //random noise between -5 to 5\n\t\t\t xi_[ii] = xi_[ii] + noise;\n\t\t\t cter_ = 0;\n\t\t\t \n\t\t}\t\n\t}\n\telse if (cter_ > 1000 && res_ < 0.01)\n\t{\n\t\tcout << \"CONVERGENCE, RESETING COUNTER! \" << endl;\n\t\tcter_ = 0;\n\t}\n\t\t\n\t\n\treturn res_;\n\t\n\t// end of \"the\" CHOMP iteration\n\t//////////////////////////////////////////////////\n}\n\nvoid CHOMP::generatePath(Vector  &xi, Vector &ti)\n{\n\tdouble err;\n\tfor (size_t ii(0); ii < numIt_; ++ii)  \n\t{\n\t\terr = CHOMP::chompIteration(xi, ti);\n\t\tcout << \"err \" << err  << \"ii \" << ii << endl;\n\t\tif (err < 0.01)\n\t\t{\n\t\t\t//it converged\n\t\t\tcter_ = 0;\n\t\t\tbreak;\n\t\t}\n\t}\t\n\t\n}\n\n//optimize path using with numIt_ iterations with serch region.\t\nvoid CHOMP::generatePathWithSearchReg(Vector  &xi, double orientation, double &U_cost, double &curv)\t\n{\n\tdouble err;\n\tfor (size_t ii(0); ii < numIt_; ++ii)  \n\t{\n\t\terr = CHOMP::chompUpdateWithSearchRegion(xi, orientation,U_cost,curv);\n\t\tif (err < 0.01)\n\t\t{\n\t\t\t//it converged\n\t\t\tcter_ = 0;\n\t\t\tbreak;\n\t\t}\n\t}\t\n\t\n}\n\nvoid CHOMP::addObstacle(double px, double py, double radius)\n{\n\tOBS_.conservativeResize(obs_dim, OBS_.cols() + 1);\n\tOBS_.block(0, OBS_.cols() - 1, obs_dim, 1) << px, py, radius;\n}\n\nvoid CHOMP::setObstacles(Matrix obs)\n{\n\tOBS_.resize (obs_dim, obs.cols()); \n\tOBS_ = obs; \n\n\tfor (size_t ii(0); ii < OBS_.cols(); ++ii)\n\t{\n\t\tint ox = (int) OBS_(0,ii);\n\t\tint oy = (int) OBS_(1,ii);\n\t\tint ro = (int) OBS_(2,ii);\n\n\t\t//cout << \"ox: \" << ox << \" \" << \"oy: \" << oy << \" \" << \"ro: \" << ro << endl; \n\n\t\tfor (int row = (ox - ro); row <= ox + ro; row++)\n\t\t{\n\t\t\tfor (int col = (oy - ro); col <= oy + ro; col++)\n\t\t\t{\n\t\t\t\tgrid_(row, col) = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t//cout << \"grid_  \" << grid_ << endl;\n\n\tMatrix cost_init = Matrix::Zero(grid_.rows(), grid_.cols());\n\tfor (int i=0; i< grid_.rows(); i++)\n\t{\n\t\tfor (int j=0; j < grid_.cols(); j++)\n\t\t{\n\t\t\tif (!grid_(i,j))\n\t\t\t\tcost_init(i,j) = +INF;\n\t\t}\n\t}\n\n\t//cout << \"cost_init  \" << cost_init << endl;\n\tcost_init = ComputeDistanceTranform(cost_init);\n\n\t\t\t// Taking square root\n\tfor (int x=0; x < grid_.rows(); x++)\n\t{\n\t\tfor (int y=0; y < grid_.cols(); y++)\n\t\t{\n\t\t\t\tcost_init(x,y) = pow(cost_init(x,y), 0.5);\n\t\t}\n\t}\n\n\tMatrix posd_x = cost_init;\n\t//cout << posd_x << endl;\n\n\t// EDT of obstacle field Complement \n\tfor (int i=0; i< grid_.rows(); i++)\n\t{\n\t\tfor (int j=0; j < grid_.cols(); j++)\n\t\t{\n\t\t\tif (grid_(i,j))\n\t\t\t\tcost_init(i,j) = +INF;\n\t\t\telse\n\t\t\t\tcost_init(i,j) = 0;\n\t\t}\n\t}\n\n\tcost_init = ComputeDistanceTranform(cost_init);\n\n\t\tfor (int x=0; x < grid_.rows(); x++)\n\t{\n\t\tfor (int y=0; y < grid_.cols(); y++)\n\t\t{\n\t\t\t\tcost_init(x,y) = pow(cost_init(x,y), 0.5);\n\t\t}\n\t}\n\n\tMatrix negd_x = cost_init;\n\t//cout << negd_x << endl;\n\n\tDx_ = posd_x - negd_x; // Discretized Signed Distance Field of obstacle\n\t//cout << Dx_ << endl;  \n\n\t//cout << \"Final Euclidean Distance Cost \" << cost_init << endl;\n\t//cout << \"Current Obstacles: \\n\" << OBS_ << endl;\n}\n\n// Sets an aribitrary value for xi_, qs_, qe_\t\t\nvoid CHOMP::setPath(Vector  &qs, Vector &qe, double ts, double te, Vector &xi)\n{\n\txi_ = xi;\n\tqs_ = qs;\n\tqe_ = qe;\n\n\tts_ = ts;\n\tte_ = te;\n\t\n\t//Sets gradient descent vectors and matrices with the initialized path\n\tCHOMP::initCHOMP();\t\t\n}\n\n//Sets qs_ and qe_ and initializes all points xi_ to qs_ (stacked to qs_)\nvoid CHOMP::initStackedPath(Vector  &qs, Vector &qe, double ts, double te)\n{\n\tqs_ = qs;\n\tqe_ = qe;\n\n\tts_ = ts;\n\tte_ = te;\n\n\txi_ = Vector::Zero (xidim_);\n\tti_ = Vector::Zero (nq_);\n\tfor (size_t ii (0); ii < nq_; ++ii) \n\t{\n\t\txi_.block (cdim_ * ii, 0, cdim_, 1) = qs_ + (ii+1)*(qe_ - qs_)/(nq_ + 1);\n\t\tti_(ii) = ts_ + (ii+1)*(te_ - ts_)/(nq_ + 1);\n\t}\n\n\t//Sets gradient descent vectors and matrices with the initialized path\n\tCHOMP::initCHOMP();\t\t\n\n}\n\n//Initializes path xi as a straight line conecting the starting point qs_ and the ending point qe_\nvoid CHOMP::initStraightLinePath(Vector  &qs, Vector &qe)\n{\n\t//initalize a new trajectory based on a direct line connecting qs to qe\n\tqs_ = qs;\n\tqe_ = qe;\n\t\n\txi_ = Vector::Zero(xidim_);\n\tVector dxi(cdim_);\n\tdxi << (qe_(0) - qs_(0)) / (nq_ - 1), (qe_(0) - qs_(0)) / (nq_ - 1);\n\tfor (size_t ii(0); ii < nq_; ++ii)\n\t{\n\t\txi_.block(cdim_ * ii, 0, cdim_, 1) = qs_ + ii * dxi;\n\t}\n\t\n\t//Sets gradient descent vectors and matrices with the initialized path\n\tCHOMP::initCHOMP();\t\t\t\n}\n\n// Gets xi_ \nvoid CHOMP::getPath(Vector &xi, Vector &ti)\n{\n\txi = xi_;\n\tti = ti_;\n}\n\n\nvoid CHOMP::initCHOMP(void)\n{\n\n\t// Initializes gradient descent vectors and matrices\n\tAA_ = Matrix::Zero (xidim_, xidim_);\n\n\t// For timing of trajectory\n\tBB_ = Matrix::Zero(nq_, nq_);\n\n\tfor (size_t ii(0); ii < nq_; ++ii) \n\t{\n\t\tAA_.block (cdim_ * ii, cdim_ * ii, cdim_ , cdim_) = 2.0 * Matrix::Identity (cdim_, cdim_);\n\t\tBB_(ii,ii) = 2.0;\n\t\tif (ii > 0) \n\t\t{\n\t\t\tAA_.block (cdim_ * (ii-1), cdim_ * ii, cdim_ , cdim_) = -1.0 * Matrix::Identity (cdim_, cdim_);\n\t\t\tAA_.block (cdim_ * ii, cdim_ * (ii-1), cdim_ , cdim_) = -1.0 * Matrix::Identity (cdim_, cdim_);\n\t\t\tBB_(ii-1, ii) = -1.0;\n\t\t\tBB_(ii, ii-1) = -1.0;\n\t\t}\n\t}\n\n\tAA_ /= dt_ * dt_ * (nq_ + 1);\n\tBB_ /= dt_ * dt_ * (nq_ + 1);\n\n\tbb_ = Vector::Zero (xidim_);\n\tbb_.block (0,            0, cdim_, 1) = qs_;\n\tbb_.block (xidim_ - cdim_, 0, cdim_, 1) = qe_;\n\tbb_ /= - dt_ * dt_ * (nq_ + 1);\n\n\tAinv_ = AA_.inverse();\n\n\n\ttt_ = Vector::Zero (nq_);\n\ttt_(0) = ts_;  \n\ttt_(nq_-1) = te_;\n\ttt_ /= -dt_ * dt_ * (nq_ + 1);\n\n\tBinv_ = BB_.inverse();\n\t\n\tPATH_INIT_= true;\n}\n", "meta": {"hexsha": "d6d8a7c61d3adb67f44cafc5dc461211bf42616f", "size": 21236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "path_adaptor.cpp", "max_stars_repo_name": "aashi7/chomp_edt", "max_stars_repo_head_hexsha": "90015b2c1255a6d204b8e2eaf99418dc29e57596", "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": "path_adaptor.cpp", "max_issues_repo_name": "aashi7/chomp_edt", "max_issues_repo_head_hexsha": "90015b2c1255a6d204b8e2eaf99418dc29e57596", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "path_adaptor.cpp", "max_forks_repo_name": "aashi7/chomp_edt", "max_forks_repo_head_hexsha": "90015b2c1255a6d204b8e2eaf99418dc29e57596", "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.2605905006, "max_line_length": 158, "alphanum_fraction": 0.5704935016, "num_tokens": 7420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5190084717292873}}
{"text": "#pragma once\n#include <utility>\n#include <armadillo>\n#include <kahansum.hpp>\n#include <utility.hpp>\n\nnamespace arm_simu{\n\t\n\ttemplate<typename RPType>\n\tstruct IntegralPointerBuilder{\n\t\ttypedef void (*Fptr)(RPType y,double t,RPType& dydt);\n\t\ttypedef Fptr Pointer;\n\t};\n\t\n\t\n\t\n\t//These returns matrix and time vector\n\tstatic std::pair<arma::vec,arma::vec> EulerIntegrate(\n\t\ttypename IntegralPointerBuilder<double>::Pointer equation,double x0,arma::vec t_frame\n\t){\n\t\tdouble dt=t_frame[1]-t_frame[0];\n\t\tstd::pair<arma::vec,arma::vec> result;\n\t\tresult.second=t_frame;\n\t\n\t\tarma::vec _result(t_frame.size());\n\t\tKahanSumParam<double> param;\n\t\t_result[0]=x0;\n\t\tfor (int i=1;i<t_frame.size();i++){\n\t\t\tdouble slope;\n\t\t\tequation(_result[i-1],t_frame[i-1],slope);\n\t\t\t\n\t\t\tparam.sum=_result[i-1];\n\t\t\t_result[i]=KahanSum::StepSummation<double>(dt*slope,param);\n\t\t\t\n\t\t\t//KahanSum::ResetStepSummation(param);\n\t\t}\n\t\tresult.first=_result;\n\t\t\n\t\treturn result;\n\t}\n\t\n\t\n\tstatic std::pair<arma::mat,arma::vec> EulerIntegrate(\n\t\ttypename IntegralPointerBuilder<arma::rowvec>::Pointer equation,arma::rowvec x0,arma::vec t_frame\n\t){\n\t\tstd::pair<arma::mat,arma::vec> result;\n\t\t\n\t\tresult.second=t_frame;\n\t\tdouble dt=t_frame[1]-t_frame[0];\n\t\t\n\t\tarma::mat _result(t_frame.size(),x0.size());\n\t\t\n\t\tarm_simu::KahanSumParam<arma::rowvec> param{\n\t\t\tx0,\n\t\t\tarma::rowvec(x0.size()),\n\t\t\tarma::rowvec(x0.size()),\n\t\t\tarma::rowvec(x0.size())\n\t\t};\n\t\tparam.y.fill(0);\n\t\tparam.t.fill(0);\n\t\tparam.c.fill(0);\n\t\t_result.row(0)=x0;\n\t\tarma::rowvec slope(x0.size());\n\t\tfor (int i=1;i<t_frame.size();i++){\n\t\t\t\n\t\t\tequation(_result.row(i-1),t_frame[i-1],slope);\n\t\t\t\n\t\t\t_result.row(i)=_result.row(i-1)+dt*slope;\n\t\t\tparam.sum=_result.row(i-1);\n\t\t}\n\t\t\n\t\t\n\t\tresult.first=_result;\n\t\t\n\t\treturn result;\n\t}\n\t\n}", "meta": {"hexsha": "5e09ac5974313ba8113193cb1bb23b0af99b918b", "size": 1744, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/integrators.hpp", "max_stars_repo_name": "cosmo-organization/armsimu", "max_stars_repo_head_hexsha": "1ab92f05465c8206848057a6bd774232180bbb99", "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/integrators.hpp", "max_issues_repo_name": "cosmo-organization/armsimu", "max_issues_repo_head_hexsha": "1ab92f05465c8206848057a6bd774232180bbb99", "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/integrators.hpp", "max_forks_repo_name": "cosmo-organization/armsimu", "max_forks_repo_head_hexsha": "1ab92f05465c8206848057a6bd774232180bbb99", "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": 22.358974359, "max_line_length": 99, "alphanum_fraction": 0.6720183486, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5190084717292873}}
{"text": "#include <gtest/gtest.h>\n#include <iostream>\n#include <assert.h>\n#include <algorithm>\n#include <random>\n#include \"spaND.h\"\n#include \"mmio.hpp\"\n#include \"cxxopts.hpp\"\n#include <Eigen/SparseCholesky>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace spaND;\n\nbool VERB = false;\nint  N_THREADS = 4;\nint  RUN_MANY = 4;\n\nSymmKind symm2syk(int symm) {\n    switch(symm) {\n        case 0: return SymmKind::SPD;\n        case 1: return SymmKind::SYM;\n        case 2: return SymmKind::GEN;\n        default: assert(false);\n    };\n    return SymmKind::SPD;\n}\n\nPartKind pki2pk(int pki) {\n    switch(pki) {\n        case 0: return PartKind::MND;\n        case 1: return PartKind::RB;\n        default: assert(false);\n    };\n    return PartKind::MND;\n}\n\nScalingKind ski2sk(int ski) {\n    switch(ski) {\n        case 0: return ScalingKind::LLT;\n        case 1: return ScalingKind::EVD;\n        case 2: return ScalingKind::SVD;\n        case 3: return ScalingKind::PLU;\n        case 4: return ScalingKind::PLUQ;\n        case 5: return ScalingKind::LDLT;\n        default: assert(false);\n    };\n    return ScalingKind::LLT;\n}\n\nbool is_valid(SymmKind syk, ScalingKind sk, bool preserve) {    \n    if(syk == SymmKind::SPD) {\n        if (sk != ScalingKind::LLT) return false;\n    }\n    if(syk == SymmKind::SYM) {\n        if (sk != ScalingKind::LDLT) return false;\n    }\n    if(syk == SymmKind::GEN) {\n        if (sk != ScalingKind::PLU && sk != ScalingKind::PLUQ) return false;\n    }\n    if(preserve) return false;\n    return true;\n}\n\nstruct params {\n    SymmKind syk;\n    PartKind pk;\n    ScalingKind sk;\n    bool preserve;\n};\n\nvector<params> get_params() {\n    vector<params> configs;\n    for(int symm = 0; symm < 3; symm++) {\n        for(int pki = 0; pki < 2; pki++) {\n            for(int ski = 0; ski < 6; ski++) {\n                for(int pres = 0; pres < 2; pres++) {\n                    PartKind pk = pki2pk(pki);\n                    ScalingKind sk = ski2sk(ski); \n                    SymmKind syk = symm2syk(symm);\n                    if(! is_valid(syk, sk, pres)) continue;\n                    configs.push_back({syk, pk, sk, pres == 1});\n                }\n            }\n        }\n    }\n    return configs;\n};\n\nSpMat neglapl(int n, int d) {\n    stringstream s;\n    s << \"../mats/neglapl_\" << d << \"_\" << n << \".mm\";\n    string file = s.str();\n    SpMat A = mmio::sp_mmread<double,int>(file);\n    return A;\n}\n\nSpMat neglapl_unsym(int n, int d, int seed) {\n    SpMat A = neglapl(n, d);\n    default_random_engine gen;\n    gen.seed(seed);\n    uniform_real_distribution<double> rand(-0.1, 0.1);\n    for(int k = 0; k < A.outerSize(); ++k) {\n        for(SpMat::InnerIterator it(A, k); it; ++it) {\n            A.coeffRef(it.row(), it.col()) += rand(gen);\n        }\n    }\n    return A;\n}\n\nSpMat make_indef(SpMat& A, int seed) {\n    Eigen::SimplicialLLT<SpMat, Eigen::Lower> sllt(A);\n    VectorXd random_diagonal = random(A.rows(), seed);        \n    for(int i = 0; i < A.rows(); i++) {\n        if(random_diagonal[i] <= 0.9) {\n            random_diagonal[i] = -1;\n        } else {\n            random_diagonal[i] = 1;\n        }\n    }\n    SpMat L = sllt.matrixL();\n    return L * (random_diagonal.asDiagonal() * L.transpose());\n}\n\nSpMat random_SpMat(int n, double p, int seed) {\n    default_random_engine gen;\n    gen.seed(seed);\n    uniform_real_distribution<double> dist(0.0,1.0);\n    vector<Triplet<double>> triplets;\n    for(int i = 0; i < n; ++i) {\n        for(int j = 0; j < n; ++j) {\n            auto v_ij = dist(gen);\n            if(v_ij < p) {\n                triplets.push_back(Triplet<double>(i,j,v_ij));\n            }\n        }\n    }\n    SpMat A(n,n);\n    A.setFromTriplets(triplets.begin(), triplets.end()); \n    return A;\n}\n\nSpMat identity_SpMat(int n) {\n    vector<Triplet<double>> triplets;\n    for(int i = 0; i < n; ++i) {\n        triplets.push_back(Triplet<double>(i,i,1.0));\n    }\n    SpMat A(n,n);\n    A.setFromTriplets(triplets.begin(), triplets.end()); \n    return A;\n}\n\nTEST(MatrixMarket, Sparse) {\n    // 1\n    SpMat A = mmio::sp_mmread<double,int>(\"../mats/test1.mm\");\n    SpMat Aref(2, 3);\n    Aref.insert(0, 0) = 1;\n    Aref.insert(0, 1) = -2e2;\n    Aref.insert(1, 1) = 3e3;\n    Aref.insert(1, 2) = -4.4e4;\n    EXPECT_EQ(A.nonZeros(), 4);\n    EXPECT_EQ((Aref - A).norm(), 0.0);\n    // 2\n    A = mmio::sp_mmread<double,int>(\"../mats/test2.mm\");\n    Aref = SpMat(3, 3);\n    Aref.insert(0, 0) = 1.1;\n    Aref.insert(1, 1) = 2e2;\n    Aref.insert(2, 0) = -3.3;\n    Aref.insert(0, 2) = -3.3;\n    EXPECT_EQ(A.nonZeros(), 4);\n    EXPECT_EQ((Aref - A).norm(), 0.0);\n    // 3\n    A = mmio::sp_mmread<double,int>(\"../mats/test3.mm\");\n    Aref = SpMat(4, 1);\n    Aref.insert(3, 0) = -1;\n    EXPECT_EQ(A.nonZeros(), 1);\n    EXPECT_EQ((Aref - A).norm(), 0.0);\n    // 4\n    A = mmio::sp_mmread<double,int>(\"../mats/test4.mm\");\n    Aref = SpMat(2, 2);\n    Aref.insert(1, 0) = -3.3;\n    Aref.insert(0, 1) = -3.3;\n    EXPECT_EQ(A.nonZeros(), 2);\n    EXPECT_EQ((Aref - A).norm(), 0.0);\n}\n\nTEST(MatrixMarket, Array) {\n    // 5\n    MatrixXd A = mmio::dense_mmread<double>(\"../mats/test5.mm\");\n    EXPECT_EQ(A.rows(), 2);\n    EXPECT_EQ(A.cols(), 3);\n    MatrixXd Aref(2, 3);\n    Aref << 1, 3, -5, 2, 4, 1e6; // row-wise filling in eigen\n    EXPECT_EQ((Aref - A).norm(), 0.0);\n    // 6\n    A = mmio::dense_mmread<double>(\"../mats/test6.mm\");\n    Aref = MatrixXd(2, 2);\n    EXPECT_EQ(A.rows(), 2);\n    EXPECT_EQ(A.cols(), 2);\n    Aref << 1, -2, -2, 3; // row-wise filling in eigen\n    EXPECT_EQ((Aref - A).norm(), 0.0);\n}\n\n/** Util.cpp tests **/\n\nTEST(Util, AreConnected) {\n    // 3x3 laplacian\n    SpMat A = mmio::sp_mmread<double,int>(\"../mats/neglapl_2_3.mm\");\n    VectorXi a(2);\n    VectorXi b(3);\n    a << 0, 1;\n    b << 6, 7, 8;\n    EXPECT_FALSE(are_connected(a, b, A));\n    a = VectorXi(2);\n    b = VectorXi(3);\n    a << 0, 1;\n    b << 2, 5, 8;\n    EXPECT_TRUE(are_connected(a, b, A));\n    a = VectorXi(2);\n    b = VectorXi(1);\n    a << 3, 4;\n    b << 5;\n    EXPECT_TRUE(are_connected(a, b, A));\n    a = VectorXi(1);\n    b = VectorXi(1);\n    a << 6;\n    b << 6;\n    EXPECT_TRUE(are_connected(a, b, A));\n}\n\nTEST(Util, ShouldBeDisconnected) {\n    EXPECT_TRUE(should_be_disconnected(0, 0, 0, 2));\n    EXPECT_TRUE(should_be_disconnected(0, 0, 1, 2));\n    EXPECT_TRUE(should_be_disconnected(0, 0, 4, 2));\n    EXPECT_TRUE(should_be_disconnected(0, 0, 5, 2));\n    EXPECT_TRUE(should_be_disconnected(0, 0, 1000, 2));\n\n    EXPECT_TRUE(should_be_disconnected(1, 2, 2, 0));\n    EXPECT_TRUE(should_be_disconnected(0, 1, 1, 1));\n    EXPECT_TRUE(should_be_disconnected(0, 2, 1, 1));\n    EXPECT_TRUE(should_be_disconnected(2, 0, 0, 5));\n    EXPECT_TRUE(should_be_disconnected(2, 2, 0, 1));\n\n    EXPECT_FALSE(should_be_disconnected(0, 1, 0, 0));\n    EXPECT_FALSE(should_be_disconnected(0, 2, 0, 0));\n    EXPECT_FALSE(should_be_disconnected(0, 10, 0, 0));\n\n    EXPECT_FALSE(should_be_disconnected(2, 0, 1, 5));\n    EXPECT_FALSE(should_be_disconnected(2, 0, 1, 6));\n    EXPECT_FALSE(should_be_disconnected(2, 1, 1, 2));\n    EXPECT_FALSE(should_be_disconnected(2, 1, 1, 3));\n}\n\nTEST(Util, ChooseRank) {\n    VectorXd errs = VectorXd(5);\n    errs << 1.0, -0.1, 0.01, -0.001, 1e-4;\n    EXPECT_EQ(choose_rank(errs, 1e-1), 2);\n    EXPECT_EQ(choose_rank(errs, 1e-2), 3);\n    EXPECT_EQ(choose_rank(errs, 1.0), 0);\n    EXPECT_EQ(choose_rank(errs, 0), 5);\n    EXPECT_EQ(choose_rank(errs, 1e-16), 5);\n}\n\nTEST(Util, Block2Dense) {\n    // Usual case\n    {\n        SpMat A(5, 5);\n        A.insert(0, 0) = 1.0;\n        A.insert(2, 2) = -2.0;\n        A.insert(1, 3) = 3.0;\n        A.makeCompressed();\n        VectorXi rowval = Map<VectorXi>(A.innerIndexPtr(), A.nonZeros());\n        VectorXi colptr = Map<VectorXi>(A.outerIndexPtr(), 6);\n        VectorXd nnzval = Map<VectorXd>(A.valuePtr(), A.nonZeros());\n        MatrixXd Ad = MatrixXd::Zero(3, 3);\n        block2dense(rowval, colptr, nnzval, 1, 1, 3, 3, &Ad, false);\n        MatrixXd Adref = MatrixXd::Zero(3, 3);\n        Adref << 0, 0, 3, 0, -2, 0, 0, 0, 0;\n        EXPECT_EQ((Adref - Ad).norm(), 0);\n    }\n    // Transpose\n    {\n        SpMat A(3, 4);\n        A.insert(0, 1) = 1.0;\n        A.insert(1, 0) = 2.0;\n        A.insert(1, 2) = 3.0;\n        A.insert(2, 1) = 4.0;\n        A.insert(0, 3) = 5.0;\n        A.makeCompressed();\n        VectorXi rowval = Map<VectorXi>(A.innerIndexPtr(), A.nonZeros());\n        VectorXi colptr = Map<VectorXi>(A.outerIndexPtr(), 5);\n        VectorXd nnzval = Map<VectorXd>(A.valuePtr(), A.nonZeros());\n        MatrixXd Ad = MatrixXd::Zero(3, 2);\n        block2dense(rowval, colptr, nnzval, 0, 0, 2, 3, &Ad, true);\n        MatrixXd Adref = MatrixXd::Zero(3, 2);\n        Adref << 0, 2, 1, 0, 0, 3;\n        EXPECT_EQ((Adref - Ad).norm(), 0);\n    }\n}\n\nTEST(Util, LinspaceNd) {\n    MatrixXd X2 = linspace_nd(3, 2);\n    MatrixXd X2ref(2, 9);\n    X2ref << 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2;\n    EXPECT_EQ((X2ref - X2).norm(), 0);\n    MatrixXd X3 = linspace_nd(2, 3);\n    MatrixXd X3ref(3, 8);\n    X3ref << 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1;\n    EXPECT_EQ((X3ref - X3).norm(), 0);\n}\n\nTEST(Util, SymmPerm) {\n    vector<int> dims  = {2, 2,  2,  3, 3,  3,  3 };\n    vector<int> sizes = {5, 10, 20, 5, 15, 25, 30};\n    for(int test = 0; test < dims.size(); test++) {\n        int s = sizes[test];\n        int d = dims[test];\n        stringstream ss;\n        ss << \"../mats/neglapl_\" << d << \"_\" << s << \".mm\";\n        SpMat A = mmio::sp_mmread<double,int>(ss.str());\n        // Create random perm\n        int N = A.rows();\n        VectorXi p = VectorXi::LinSpaced(N, 0, N-1);\n        random_device rd;\n        mt19937 g(rd());\n        shuffle(p.data(), p.data() + N, g);\n        // Compare\n        SpMat pAp = symm_perm(A, p);\n        SpMat pApref = p.asPermutation().inverse() * A * p.asPermutation();\n        EXPECT_EQ((pAp - pApref).norm(), 0.0);\n    }\n}\n\nTEST(Util, isperm) {\n    VectorXi perm1(10);\n    VectorXi perm2(10);\n    VectorXi noperm1(10);\n    VectorXi noperm2(5);\n    perm1 << 0, 9, 8, 1, 4, 2, 3, 7, 5, 6;\n    perm2 << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9;\n    noperm1 << 0, 9, 8, 1, 4, 2, 3, 5, 5, 6;\n    noperm2 << 0, 9, 8, 1, 4;\n    EXPECT_TRUE(isperm(&perm1));\n    EXPECT_TRUE(isperm(&perm2));\n    EXPECT_FALSE(isperm(&noperm1));\n    EXPECT_FALSE(isperm(&noperm2));\n}\n\nTEST(Util, swap2perm) {\n    VectorXi swap(6);\n    VectorXi perm(6);\n    VectorXi permRef(6);\n    swap << 3, 3, 2, 5, 4, 5;\n    permRef << 3, 0, 2, 5, 4, 1;\n    swap2perm(&swap, &perm); // perm.asPermutation().transpose() * x <=> x[perm]\n    EXPECT_EQ((perm - permRef).norm(), 0.0);\n}\n\nSpMat symmetric_graph_ref(SpMat A) {\n    SpMat ATabs = A.cwiseAbs().transpose();\n    return A.cwiseAbs() + ATabs + identity_SpMat(A.rows());\n}\n\nTEST(Util, symmetric_graph) {\n    for(int i = 1; i < 100; i++) {\n        SpMat A = random_SpMat(i, 0.2, i);\n        SpMat AAT = symmetric_graph(A);\n        EXPECT_LT( (AAT - symmetric_graph_ref(A)).norm(), 1e-12);\n    }\n}\n\n\n/** Partitioning tests **/\n\n/**\n * Check the partitioning of a square laplacian 5x5\n */\nTEST(PartitionTest, Square) {\n    SpMat A = mmio::sp_mmread<double,int>(\"../mats/neglapl_2_5.mm\");\n    MatrixXd X = linspace_nd(5, 2);\n    Tree t(3);\n    t.set_verb(VERB);\n    t.set_use_geo(true);\n    t.set_Xcoo(&X);\n    auto part = t.partition(A);\n    vector<SepID> sepidref { \n        SepID(0,0), SepID(0,0), SepID(1,0), SepID(0,1), SepID(0,1),\n        SepID(0,0), SepID(0,0), SepID(1,0), SepID(0,1), SepID(0,1),\n        SepID(2,0), SepID(2,0), SepID(2,0), SepID(2,0), SepID(2,0),\n        SepID(0,2), SepID(0,2), SepID(1,1), SepID(0,3), SepID(0,3),\n        SepID(0,2), SepID(0,2), SepID(1,1), SepID(0,3), SepID(0,3), \n    } ;\n    vector<SepID> leftref { \n        SepID(0,0), SepID(0,0), SepID(0,0), SepID(0,1), SepID(0,1),\n        SepID(0,0), SepID(0,0), SepID(0,0), SepID(0,1), SepID(0,1),\n        SepID(0,0), SepID(0,0), SepID(1,0), SepID(0,1), SepID(0,1),\n        SepID(0,2), SepID(0,2), SepID(0,2), SepID(0,3), SepID(0,3),\n        SepID(0,2), SepID(0,2), SepID(0,2), SepID(0,3), SepID(0,3), \n    } ;\n    vector<SepID> rightref { \n        SepID(0,0), SepID(0,0), SepID(0,1), SepID(0,1), SepID(0,1),\n        SepID(0,0), SepID(0,0), SepID(0,1), SepID(0,1), SepID(0,1),\n        SepID(0,2), SepID(0,2), SepID(1,1), SepID(0,3), SepID(0,3),\n        SepID(0,2), SepID(0,2), SepID(0,3), SepID(0,3), SepID(0,3),\n        SepID(0,2), SepID(0,2), SepID(0,3), SepID(0,3), SepID(0,3), \n    } ;\n    for(int i = 0; i < part.size(); i++) {\n        ASSERT_TRUE(part[i].self  == sepidref[i]);\n        ASSERT_TRUE(part[i].l     == leftref[i]);\n        ASSERT_TRUE(part[i].r     == rightref[i]);\n    }\n}\n\n/**\n * Check consistency of the partitioning\n */\nTEST(PartitionTest, Consistency) {\n    vector<int> dims  = {2, 2,  2,   3, 3,  3 };\n    vector<int> sizes = {5, 20, 100, 5, 15, 25};\n    for(int test = 0; test < dims.size(); test++) {\n        int s = sizes[test];\n        int d = dims[test];\n        stringstream ss;\n        ss << \"../mats/neglapl_\" << d << \"_\" << s << \".mm\";\n        int n = pow(s, d);\n        string file = ss.str();\n        for(int nlevels = 1; nlevels < 8; nlevels++) {\n            for(int geoi = 0; geoi < 2; geoi++) {\n                for(int pki = 0; pki < 2; pki++) {\n                    bool geo = (geoi == 0);\n                    PartKind pk = pki == 0 ? PartKind::MND : PartKind::RB;\n                    // Partition tree\n                    MatrixXd X = linspace_nd(s, d);\n                    Tree t(nlevels);\n                    t.set_verb(VERB);\n                    SpMat A = mmio::sp_mmread<double,int>(file);\n                    t.set_use_geo(geo);\n                    t.set_Xcoo(&X);\n                    t.set_part_kind(pk);\n                    auto part = t.partition(A);                    \n                    // (1) Lengths\n                    ASSERT_EQ(part.size(), n);\n                    // (2) Check ordering integrity\n                    for(int i = 0; i < n; i++) {\n                        auto pi = part[i].self;\n                        for (SpMat::InnerIterator it(A,i); it; ++it) {\n                            int j = it.row();\n                            auto pj = part[j].self;  \n                            ASSERT_FALSE(should_be_disconnected(pi.lvl, pj.lvl, pi.sep, pj.sep));\n                        }\n                    }\n                    // (3) Check left/right integrity          \n                    for(int i = 0; i < n; i++) {\n                        auto pi = part[i].self;\n                        auto li = part[i].l;\n                        auto ri = part[i].r;\n                        if(pi.lvl == 0) {\n                            ASSERT_TRUE(pi == li);\n                            ASSERT_TRUE(pi == ri);\n                        } else {\n                            ASSERT_TRUE(pi.lvl > li.lvl);\n                            ASSERT_TRUE(pi.lvl > ri.lvl);\n                            while(li.lvl < pi.lvl - 1) {\n                                li.lvl += 1;\n                                li.sep /= 2;\n                            }\n                            while(ri.lvl < pi.lvl - 1) {\n                                ri.lvl += 1;\n                                ri.sep /= 2;\n                            }\n                            ASSERT_TRUE(li.lvl == pi.lvl - 1);\n                            ASSERT_TRUE(ri.lvl == pi.lvl - 1);\n                            ASSERT_TRUE(li.sep == 2 * pi.sep);\n                            ASSERT_TRUE(ri.sep == 2 * pi.sep + 1);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\n/** Assembly tests **/\n\n/** \n * Check assembly\n */\nTEST(Assembly, Consistency) {\n    vector<int> dims  = {2, 2,  2,  3, 3,  3};\n    vector<int> sizes = {5, 10, 20, 5, 10, 15};\n    for(int spandlorasp = 0; spandlorasp < 2; spandlorasp++) {\n        for(int test = 0; test < dims.size(); test++) { \n            for(int pki = 0; pki < 2; pki++) {\n                PartKind pk = pki == 0 ? PartKind::MND : PartKind::RB;       \n                int s = sizes[test];\n                int d = dims[test];\n                SpMat Aref = neglapl(s, d);\n                SpMat Arefunsym = neglapl_unsym(s, d, test);\n                for(int nlevels = 2; nlevels < 5 ; nlevels++) {\n                    /**\n                     * Symmetric case\n                     */\n                    {\n                        // Partition and assemble\n                        Tree t(nlevels);\n                        t.set_verb(VERB);\n                        t.set_use_geo(false);\n                        t.set_part_kind(pk);\n                        if(spandlorasp == 0) t.partition(Aref);\n                        else                 t.partition_lorasp(Aref);\n                        t.assemble(Aref);\n                        // Get permutation\n                        VectorXi p = t.get_assembly_perm();\n                        // Check it's indeed a permutation\n                        ASSERT_TRUE(isperm(&p));\n                        auto P = p.asPermutation();\n                        // Check get_mat()\n                        SpMat A2 = t.get_trailing_mat();\n                        EXPECT_EQ((P.inverse() * Aref * P - A2).norm(), 0.0);\n                    }\n                    /**\n                     * Unsymmetric case\n                     */\n                    {\n                        // Partition and assemble\n                        Tree t(nlevels);\n                        t.set_verb(VERB);\n                        t.set_symm_kind(SymmKind::GEN);\n                        t.set_use_geo(false);\n                        t.set_part_kind(pk);                        \n                        if(spandlorasp == 0) t.partition(Arefunsym);\n                        else                 t.partition_lorasp(Arefunsym);\n                        t.assemble(Arefunsym);                \n                        // Get permutation\n                        VectorXi p = t.get_assembly_perm();\n                        // Check it's indeed a permutation\n                        ASSERT_TRUE(isperm(&p));\n                        auto P = p.asPermutation();\n                        // Check get_mat()\n                        SpMat A2 = t.get_trailing_mat();\n                        EXPECT_EQ((P.inverse() * Arefunsym * P - A2).norm(), 0.0);\n                    }\n                }\n            }\n        }\n    }\n}\n\n/** Factorization tests **/\n\nTEST(ApproxTest, PrintConfigs) {\n    vector<params> configs = get_params();\n    cout << \"Preserve ? PartKind ? ScalingKind ? SymmKind ?\" << endl;\n    for(auto c: configs) {\n        cout << c.preserve << \" \" << part2str(c.pk) << \" \" << scaling2str(c.sk) << \" \" << symm2str(c.syk) << endl;\n    }\n}\n\n/**\n * Test that with eps=0, we get exact solutions\n */\nTEST(ApproxTest, Exact) {\n    vector<int> dims  = {2, 2,  2,  3, 3};\n    vector<int> sizes = {5, 10, 20, 5, 15};\n    vector<double> tols = {1e-14, 1e-14, 0.0};\n    vector<int> skips   = {0,     4,     1000};\n    vector<params> configs = get_params();\n    for(int test = 0; test < dims.size(); test++) {\n        cout << \"Test \" << test << \"... \";\n        int count = 0;\n        int s = sizes[test];\n        int d = dims[test];\n        int n = pow(s, d);\n        int nlevelsmin = n < 1000 ? 1 : 8;\n        SpMat Aref = neglapl(s, d);\n        SpMat Arefunsym = neglapl_unsym(s, d, test);\n        SpMat Arefsym = make_indef(Aref, 2019+test);\n        for(int nlevels = nlevelsmin; nlevels < nlevelsmin+5 ; nlevels++) {\n            for(auto c: configs) {\n                SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? Arefsym : Arefunsym));\n                assert(! c.preserve);\n                MatrixXd phi = random(Aref.rows(), 3, test+nlevels+2019);\n                for(int it = 0; it < tols.size(); it++) {\n                    double tol = tols[it];\n                    double skip = skips[it];\n                    Tree t(nlevels);\n                    t.set_verb(VERB);\n                    t.set_part_kind(c.pk);\n                    t.set_scaling_kind(c.sk);\n                    t.set_symm_kind(c.syk);                                \n                    t.partition(A);\n                    t.assemble(A);\n                    t.set_tol(tol);\n                    t.set_skip(skip);\n                    t.set_preserve(c.preserve);\n                    if(c.preserve) t.set_phi(&phi);\n                    t.factorize();\n                    VectorXd b = random(n, test+nlevels+2019+1);\n                    auto x = b;\n                    t.solve(x);\n                    double err = (A*x-b).norm() / b.norm();\n                    EXPECT_LE(err, 1e-10) << err;\n                    count++;\n                }\n            }\n        }\n        cout << count << \" tested.\\n\";\n    }\n}\n\n/**\n * Test SPD on A (laplacian) and SYM+LDLT on -A (- laplacian) give the same, with or without compression\n */\nTEST(ApproxTest, SPD_vs_LDLT) {\n    vector<int> dims  = {2,  3, 3};\n    vector<int> sizes = {128, 5, 15};\n    vector<double> tols = {0,   1e-4, 1e-14};\n    vector<int> skips   = {100, 1,    0};\n    vector<params> configs = get_params();\n    for(int test = 0; test < dims.size(); test++) {\n        cout << \"Test \" << test << \"... \";\n        int count = 0;\n        int s = sizes[test];\n        int d = dims[test];\n        int n = pow(s, d);\n        int nlevelsmin = n < 1000 ? 1 : 8;\n        SpMat A = neglapl(s, d);\n        SpMat Aneg = -A;\n        for(int nlevels = nlevelsmin; nlevels < nlevelsmin+5 ; nlevels++) {\n            for(auto c: configs) {\n                if(c.sk != ScalingKind::LLT && !c.preserve) continue;\n                for(int it = 0; it < tols.size(); it++) {\n                    double tol = tols[it];\n                    double skip = skips[it];\n                    VectorXd b = random(n, test+nlevels+2019+1);\n                    // Use LLT on A\n                    Tree t_llt(nlevels);\n                    t_llt.set_verb(VERB);\n                    t_llt.set_part_kind(c.pk);\n                    t_llt.set_scaling_kind(ScalingKind::LLT);\n                    t_llt.set_symm_kind(SymmKind::SPD);                                \n                    t_llt.partition(A);\n                    t_llt.assemble(A);\n                    t_llt.set_tol(tol);\n                    t_llt.set_skip(skip);\n                    t_llt.set_preserve(false);\n                    t_llt.factorize();                    \n                    VectorXd x_llt = b;\n                    t_llt.solve(x_llt);\n                    // Use LDLT on -A\n                    Tree t_ldlt(nlevels);\n                    t_ldlt.set_verb(VERB);\n                    t_ldlt.set_part_kind(c.pk);\n                    t_ldlt.set_scaling_kind(ScalingKind::LDLT);\n                    t_ldlt.set_symm_kind(SymmKind::SYM);                                \n                    t_ldlt.partition(Aneg);\n                    t_ldlt.assemble(Aneg);\n                    t_ldlt.set_tol(tol);\n                    t_ldlt.set_skip(skip);\n                    t_ldlt.set_preserve(false);\n                    t_ldlt.factorize();                    \n                    VectorXd x_ldlt = - b;\n                    t_ldlt.solve(x_ldlt);\n                    // Compare                    \n                    double err_llt = (A*x_llt-b).norm() / b.norm();\n                    double err_ldlt = (A*x_ldlt-b).norm() / b.norm();\n                    double diff = (x_llt - x_ldlt).norm() / x_llt.norm();\n                    if (tol == 0.0) {\n                        EXPECT_LE(err_llt, 1e-12);\n                        EXPECT_LE(err_ldlt, 1e-12);  \n                        EXPECT_LE(diff, 1e-12);                      \n                    } else {\n                        EXPECT_LE(err_llt, tol * 1e2);\n                        EXPECT_LE(err_ldlt, tol * 1e2);\n                        EXPECT_LE(diff, tol * 1e2);\n                    }                    \n                    count++;\n                }\n            }\n        }\n        cout << count << \" tested.\\n\";\n    }\n}\n\n/** \n * Test conservation is correct\n */\nTEST(ApproxTest, Preservation) {\n    vector<int> dims  = {2, 2,  2,  3, 3,  3};\n    vector<int> sizes = {5, 10, 20, 5, 10, 25};\n    for(int test = 0; test < dims.size(); test++) {\n        cout << \"Test \" << test;\n        int s = sizes[test];\n        int d = dims[test];\n        stringstream ss;\n        ss << \"../mats/neglapl_\" << d << \"_\" << s << \".mm\";\n        int n = pow(s, d);\n        string file = ss.str();\n        SpMat A_spd = mmio::sp_mmread<double,int>(file);        \n        SpMat A_sym = - A_spd;\n        int nlevelsmin = n < 1000 ? 1 : 8;\n        vector<double> tols = {10, 1e-2, 1e-3, 1e-4, 1e-6, 0.0};\n        for(int nlevels = nlevelsmin; nlevels < nlevelsmin + 5; nlevels++) {\n            for(int it = 0; it < tols.size(); it++) {\n                for(int skip = 0; skip < 3; skip++) {\n                    for(int symm = 0; symm < 2; symm++) {\n                        printf(\".\"); fflush(stdout);\n                        SpMat A;\n                        if(symm == 0) A = A_spd;\n                        else          A = A_sym;\n                        // Check a 1 is preserved\n                        {\n                            Tree t(nlevels);\n                            if(symm == 0) {\n                                t.set_scaling_kind(ScalingKind::LLT);\n                                t.set_symm_kind(SymmKind::SPD);\n                            } else {\n                                t.set_scaling_kind(ScalingKind::LDLT);\n                                t.set_symm_kind(SymmKind::SYM);\n                            }\n                            t.set_verb(VERB);\n                            t.partition(A);\n                            t.assemble(A);\n                            MatrixXd phi = MatrixXd::Ones(n, 1);\n                            t.set_tol(tols[it]);\n                            t.set_skip(skip);\n                            t.set_preserve(true);\n                            t.set_phi(&phi);                            \n                            t.factorize();\n                            for(int c = 0; c < phi.cols(); c++) {\n                                VectorXd b = A * phi.col(c);\n                                VectorXd x = b;\n                                t.solve(x);\n                                double err1 = (A*x-b).norm() / b.norm();\n                                double err2 = (x-phi.col(c)).norm() / phi.col(c).norm();\n                                EXPECT_TRUE(err1 < 1e-12) << \"err1 = \" << err1 << \" | \" << skip << \" \" << it << \" \" << nlevels << \" \" << test << endl;\n                                EXPECT_TRUE(err2 < 1e-12) << \"err2 = \" << err2 << \" | \" << skip << \" \" << it << \" \" << nlevels << \" \" << test << endl;\n                            }\n                            VectorXd b = random(n, nlevels+it+skip+2019);\n                            auto x = b;\n                            t.solve(x);\n                            double err = (A*x-b).norm() / b.norm();\n                            if (tols[it] == 0.0) {\n                                EXPECT_TRUE(err < 1e-12);\n                            } else {\n                                EXPECT_TRUE(err < tols[it] * 1e2);\n                            }\n                        }\n                        // Check that a multiple random b are preserved\n                        {\n                            Tree t(nlevels);\n                            if(symm == 0) {\n                                t.set_scaling_kind(ScalingKind::LLT);\n                                t.set_symm_kind(SymmKind::SPD);\n                            } else {\n                                t.set_scaling_kind(ScalingKind::LDLT);\n                                t.set_symm_kind(SymmKind::SYM);\n                            }\n                            t.set_verb(VERB);\n                            t.partition(A);\n                            t.assemble(A);\n                            MatrixXd phi = random(n, 5, nlevels+it+skip+2019);\n                            t.set_tol(tols[it]);\n                            t.set_skip(skip);\n                            t.set_preserve(true);\n                            t.set_phi(&phi);                            \n                            t.factorize();\n                            for(int c = 0; c < phi.cols(); c++) {\n                                VectorXd b = A * phi.col(c);\n                                VectorXd x = b;\n                                t.solve(x);\n                                double err1 = (A*x-b).norm() / b.norm();\n                                double err2 = (x-phi.col(c)).norm() / phi.col(c).norm();\n                                EXPECT_TRUE(err1 < 1e-12) << \"err1 = \" << err1 << \" | \" << skip << \" \" << it << \" \" << nlevels << \" \" << test << endl;\n                                EXPECT_TRUE(err2 < 1e-12) << \"err2 = \" << err2 << \" | \" << skip << \" \" << it << \" \" << nlevels << \" \" << test << endl;\n                            }\n                            VectorXd b = random(n, nlevels+it+skip+2019);\n                            auto x = b;\n                            t.solve(x);\n                            double err = (A*x-b).norm() / b.norm();\n                            if (tols[it] == 0.0) {\n                                EXPECT_TRUE(err < 1e-12);\n                            } else {\n                                EXPECT_TRUE(err < tols[it] * 1e2);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        printf(\"\\n\");\n    }\n}\n\n/**\n * Test that the approximations are reasonnable accurate \n * with and without preservation\n */\nTEST(ApproxTest, Approx) {\n    vector<int> dims  = {2, 2,  2,  2,   3, 3};\n    vector<int> sizes = {5, 10, 20, 128, 5, 15};\n    vector<double> tols = {0.0, 1e-10, 1e-6, 1e-2, 10};\n    matrix_hash<VectorXd> hash;\n    vector<params> configs = get_params();\n    for(int test = 0; test < dims.size(); test++) {\n        vector<size_t> allhashes;\n        int count = 0;\n        cout << \"Test \" << test << \"... \";\n        int s = sizes[test];\n        int d = dims[test];\n        SpMat Aref = neglapl(s, d);\n        SpMat Arefunsym = neglapl_unsym(s, d, test+2019);\n        SpMat Arefsym = - Aref;\n        int n = pow(s, d);\n        int nlevelsmin = n < 1000 ? 1 : 8;\n        for(int nlevels = nlevelsmin; nlevels < nlevelsmin + 5; nlevels++) {\n            for(int it = 0; it < tols.size(); it++) {\n                for(int skip = 0; skip < 3; skip++) {\n                    for(auto c: configs) {\n                        SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? Arefsym : Arefunsym));\n                        assert(! c.preserve);\n                        Tree t(nlevels);\n                        t.set_verb(VERB);\n                        t.set_symm_kind(c.syk);\n                        t.set_part_kind(c.pk);\n                        t.set_scaling_kind(c.sk);\n                        t.partition(A);\n                        t.assemble(A);\n                        MatrixXd phi = random(A.rows(), 2, nlevels+it+skip+2019);\n                        t.set_tol(tols[it]);\n                        t.set_skip(skip);\n                        t.set_preserve(c.preserve);\n                        if(c.preserve) t.set_phi(&phi);\n                        t.factorize();\n                        VectorXd b = random(n, nlevels+it+skip+2019);\n                        auto x = b;\n                        t.solve(x);\n                        double err = (A*x-b).norm() / b.norm();\n                        auto hb = hash(b);\n                        auto hx = hash(x);\n                        allhashes.push_back(hb);\n                        allhashes.push_back(hx);\n                        if (tols[it] == 0.0) {\n                            EXPECT_LE(err, 5e-12);\n                        } else {\n                            EXPECT_LE(err, tols[it] * 2e2);\n                        }\n                        count++;\n                    }\n                }\n            }\n        }\n        size_t h = hashv(allhashes);\n        cout << count << \" tested. Overall hash(x,b) = \" << h << endl;\n    }\n}\n\nTEST(ApproxTest, ApproxLoRaSp) {\n    vector<int> dims  = {2, 2,  2,  2,   3, 3};\n    vector<int> sizes = {5, 10, 20, 64,  5, 15};\n    vector<double> tols = {0.0, 1e-10, 1e-6, 1e-4};\n    matrix_hash<VectorXd> hash;\n    vector<params> configs = get_params();\n    for(int test = 0; test < dims.size(); test++) {\n        vector<size_t> allhashes;\n        int count = 0;\n        cout << \"Test \" << test << \"... \";\n        int s = sizes[test];\n        int d = dims[test];\n        SpMat Aref = neglapl(s, d);\n        SpMat Arefunsym = neglapl_unsym(s, d, test+2019);\n        int n = pow(s, d);\n        int nlevelsmin = n < 1000 ? 1 : 8;\n        for(int nlevels = nlevelsmin; nlevels < nlevelsmin + 5; nlevels++) {\n            for(int it = 0; it < tols.size(); it++) {\n                for(auto c: configs) {\n                    SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? (-Aref) : Arefunsym));\n                    Tree t(nlevels);\n                    t.set_verb(VERB);\n                    t.set_symm_kind(c.syk);                    \n                    t.set_scaling_kind(c.sk);                                                                    \n                    t.partition_lorasp(A);\n                    t.assemble(A);                        \n                    MatrixXd phi = random(A.rows(), 2, nlevels+it+2019);\n                    t.set_tol(tols[it]);\n                    try {\n                        t.factorize_lorasp();\n                        VectorXd b = random(n, nlevels+it+2019);\n                        auto x = b;\n                        t.solve(x);\n                        double err = (A*x-b).norm() / b.norm();\n                        auto hb = hash(b);\n                        auto hx = hash(x);\n                        allhashes.push_back(hb);\n                        allhashes.push_back(hx);\n                        if (tols[it] == 0.0) {\n                            EXPECT_LE(err, 5e-12);\n                        } else {\n                            EXPECT_LE(err, tols[it] * 2e2);\n                        } \n                    } catch (exception& ex) {\n                        cout << ex.what();\n                        EXPECT_TRUE(false);\n                    }                    \n                    count++;\n                }\n            }\n        }\n        size_t h = hashv(allhashes);\n        cout << count << \" tested. Overall hash(x,b) = \" << h << endl;\n    }\n}\n\n/** \n * Test that the code produce reproducable results\n */\nTEST(ApproxTest, Repro) {\n    int    dims[3]      = {2, 2, 2};\n    int    sizes[3]     = {20, 64, 16};\n    double tols[4]      = {1e-5, 10, 1e-8, 0.1};\n    double skips[4]     = {1, 2, 0, 1};\n    int    repeat       = 10;\n    vector<params> configs = get_params();\n    for(int test = 0; test < 3; test++) {\n        printf(\"Tests \"); fflush(stdout);\n        int count = 0;\n        int s = sizes[test];\n        int d = dims[test];\n        int n = pow(s, d);\n        SpMat Aref = neglapl(s, d);\n        SpMat Arefunsym = neglapl_unsym(s, d, test);        \n        for(int nlevels = 5; nlevels < 7; nlevels++) {\n            for(int pr = 0; pr < 6; pr++) {\n                for(auto c: configs) {\n                    for(int lrsp = 0; lrsp < 2; lrsp++) {\n                        printf(\".\"); fflush(stdout);\n                        SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? (-Aref) : Arefunsym));\n                        MatrixXd phi = random(A.rows(), 3, test+nlevels+pr+2019);\n                        Tree t(nlevels);\n                        t.set_verb(VERB);\n                        t.set_symm_kind(c.syk);\n                        t.set_part_kind(c.pk);\n                        t.set_scaling_kind(c.sk);\n                        if(lrsp == 0) {\n                            t.partition(A);\n                        } else {\n                            t.partition_lorasp(A);\n                        }\n                        t.assemble(A);\n                        t.set_tol(tols[pr]);\n                        t.set_skip(skips[pr]);\n                        t.set_preserve(c.preserve);\n                        if(c.preserve) t.set_phi(&phi);\n                        if(lrsp == 0) {\n                            t.factorize();\n                        } else {\n                            t.factorize_lorasp();\n                        }\n                        VectorXd b = random(n, nlevels+test);\n                        auto xref = b;\n                        t.solve(xref);\n                        count++;\n                        for(int i = 0; i < repeat; i++) {\n                            Tree t2(nlevels);\n                            t2.set_verb(VERB);                        \n                            t2.set_symm_kind(c.syk);\n                            t2.set_part_kind(c.pk);\n                            t2.set_scaling_kind(c.sk);\n                            if(lrsp == 0) {\n                                t2.partition(A);\n                            } else {\n                                t2.partition_lorasp(A);\n                            }\n                            t2.assemble(A);\n                            t2.set_tol(tols[pr]);\n                            t2.set_skip(skips[pr]);\n                            t2.set_preserve(c.preserve);\n                            t2.set_phi(&phi);\n                            if(lrsp == 0) {\n                                t2.factorize();\n                            } else {\n                                t2.factorize_lorasp();\n                            }\n                            auto x = b;\n                            t2.solve(x);\n                            EXPECT_EQ((xref - x).norm(), 0.0);\n                        }\n                    }\n                }\n            }\n        }\n        printf(\": %d tested.\\n\", count); fflush(stdout);\n    }\n}\n\nTEST(Run, Many) {\n    vector<int>    dims  = {2,  2,  2,   3, 3,  3 };\n    vector<int>    sizes = {5,  16, 64,  5, 10, 15};\n    vector<double> tols  = {0.0, 1e-2, 1.0, 10.0};\n    RUN_MANY = RUN_MANY > dims.size() ? dims.size() : RUN_MANY;\n    matrix_hash<VectorXd> hash;\n    vector<size_t> allhashes;\n    vector<params> configs = get_params();\n    for(int test = 0; test < RUN_MANY; test++) {\n        cout << \"Run \" << test << \"... \\n\";\n        int count = 0;\n        int n = sizes[test];\n        int d = dims[test];\n        SpMat Aref = neglapl(n, d);\n        SpMat Arefunsym = neglapl_unsym(n, d, test);        \n        int N = Aref.rows();\n        int nlevelsmin = N < 1000 ? 1 : 8;\n        for(int nlevels = nlevelsmin; nlevels < nlevelsmin+3; nlevels++) {\n            for(double tol : tols) {\n                for(int skip = 0; skip < 3; skip++) {\n                    for(int geo = 0; geo < 2; geo++) {\n                        for(auto c: configs) {\n                            SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? (-Aref) : Arefunsym));\n                            MatrixXd phi = random(A.rows(), 3, test+nlevels+2019);\n                            MatrixXd X = linspace_nd(n, d);\n                            Tree t(nlevels);\n                            t.set_verb(VERB);                        \n                            t.set_symm_kind(c.syk);\n                            t.set_part_kind(c.pk);\n                            t.set_scaling_kind(c.sk);\n                            t.set_use_geo(geo);\n                            t.set_Xcoo(&X);\n                            t.set_tol(tol);\n                            t.set_skip(skip);\n                            t.set_preserve(c.preserve);\n                            if(c.preserve) t.set_phi(&phi);\n                            t.partition(A);\n                            t.assemble(A);\n                            t.factorize();\n                            VectorXd b = random(N, nlevels+test);\n                            auto x = b;\n                            t.solve(x);                            \n                            double res = (A*x-b).norm() / b.norm();\n                            auto h = hash(x);\n                            allhashes.push_back(h);\n                            printf(\"%6d %4d %d] %3d %3.2e %d %d %d %d %d %d %d %d | %3.2e | %lu\\n\", \n                                     N, n, d,   nlevels, \n                                                     tol, skip, \n                                                              geo,\n                                                                c.preserve, \n                                                                   int(c.syk), int(c.pk), int(c.sk), 1, 1,\n                                                                   res, h);\n                            count++;\n                        }\n                    }\n                }\n            }\n        }\n        cout << \"Ran \" << count << \" tests\\n\";\n        size_t h = hashv(allhashes);\n        cout << \"Overall hash so far: \" << h << endl;\n    }\n    size_t h = hashv(allhashes);\n    cout << \"Overall hash: \" << h << endl;\n}\n\nint main(int argc, char **argv) {\n    ::testing::InitGoogleTest(&argc, argv);\n\n    cxxopts::Options options(\"spaND tests\", \"Test suite for the spaND algorithms.\");\n    options.add_options()\n        (\"help\", \"Print help\")\n        (\"v,verb\", \"Verbose (default: false)\", cxxopts::value<bool>()->default_value(\"false\"))\n        (\"n_threads\", \"Number of threads\", cxxopts::value<int>()->default_value(\"4\"))\n        (\"run\", \"How many Run.Many to run\", cxxopts::value<int>()->default_value(\"4\"))\n        ;\n    auto result = options.parse(argc, argv);\n\n    if (result.count(\"help\"))\n    {\n        cout << options.help({\"\", \"Group\"}) << endl;\n        exit(0);\n    }\n\n    VERB = result[\"verb\"].as<bool>();\n    N_THREADS = result[\"n_threads\"].as<int>();\n    RUN_MANY = result[\"run\"].as<int>();\n    cout << \"n_threads: \" << N_THREADS << endl;\n    cout << \"verb: \" << VERB << endl;\n    cout << \"run: \" << RUN_MANY << endl;\n\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "da816a5740ebbd66adff15d7f6c185d906b311e1", "size": 41955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/tests.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/tests.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/tests.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": 38.5261707989, "max_line_length": 150, "alphanum_fraction": 0.4203074723, "num_tokens": 11547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.518934862527263}}
{"text": "/* \n * benchmark_hogwild_regression.cpp\n * author: Abhijit Chowdhary (achowdh2@ncsu.edu)\n *\n * Benchmark HOGWILD! as applied to regression on to a simple random normal 50\n * x 50 matrix A and random normal vector b:\n *\n *  minimize ||Ax-b||_2^2\n *\n * Outputs to results.txt and stdout time taken to reach desired tolerance for\n * each core count possible in system.\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 */\n#include <omp.h>\n#include <stdio.h>\n\n#include <algorithm>\n#include <array>\n#include <atomic>\n#include <iostream>\n#include <random>\n\n#include <Eigen/Dense>\n\n#include \"readCSV.h\"\n\n#define ETA 0.001\n#define NUM_EPOCHS 50\n#define TRIALS_PER_CORE 5\n\nint \nmain(int argc, char **argv)\n{\n  // Initialize random state, and parallel parameters.\n  unsigned P = omp_get_max_threads();\n  Eigen::initParallel();\n  omp_set_dynamic(0);\n  std::mt19937 gen(0);\n\n  // Read MSD dataset into memory and format matrices.\n  unsigned const num_data = 160000; unsigned const num_features = 400;\n  Eigen::MatrixXd Data;\n  readCSV<double>(\"../simplemat.csv\", Data);\n  Eigen::MatrixXd A = Data.topRightCorner(num_data, num_features);\n  Eigen::VectorXd b = Data.col(0);\n\n  // Construct sampling w/ replacement vector.\n  std::uniform_int_distribution<std::mt19937::result_type> distN(0,num_data-1);\n  //std::array<unsigned, num_data*NUM_EPOCHS> rand_selection;\n  unsigned *rand_selection = new unsigned[num_data*NUM_EPOCHS];\n  for (unsigned k = 0; k < num_data*NUM_EPOCHS; k++)\n  {\n    rand_selection[k] = distN(gen);\n  }\n\n  std::array<std::atomic<double>, num_features> x;\n  for (unsigned p = 0; p < P; ++p)\n  { // Begin trials for processor count p+1\n    omp_set_num_threads(p+1);\n    double t = 0.0;\n    for (unsigned trial = 0; trial < TRIALS_PER_CORE; ++trial)\n    { // Begin SGD trial\n      for (unsigned k = 0; k < num_features; k++) { x[k] = 1; }\n\n      double t_start, t_end;\n      t_start = omp_get_wtime();\n\n      #pragma omp parallel for\n      for (unsigned k = 0; k < num_data*NUM_EPOCHS; k++)\n      { // Begin parallel SGD iterations\n        unsigned id = rand_selection[k];\n        double dg = 0;\n        for (unsigned i = 0; i < num_features; i++) { dg += A(id, i)*x[i].load(); }\n        dg -= b(id);\n        for (unsigned i = 0; i < num_features; i++)\n        {\n          double dgi = x[i].load() - ETA*( A(id,i)*dg );\n          x[i].exchange( dgi );\n        }\n      } // End parallel SGD iterations\n\n      t_end = omp_get_wtime(); t += t_end-t_start;\n    } // End SGD trial\n    t /= TRIALS_PER_CORE;\n\n    Eigen::MatrixXd xx(num_features,1);\n    for (int k = 0; k < num_features; k++) { xx(k) = x[k].load(); }\n    double E = 0.5*(A*xx-b).squaredNorm();\n    printf(\"T(p=%d) = %.5f, E(p=%d) = %.5f\\n\", p+1, t, p+1, E);\n  } // End trials for processor count p+1\n\n  delete []rand_selection;\n  return 0;\n}\n", "meta": {"hexsha": "cd3529b492c511cd7ff415e843684243e06a9066", "size": 3041, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Tests/large_regression/dense/replacement/benchmark_hogwild_regression.cc", "max_stars_repo_name": "abhijit-c/HOGWILD", "max_stars_repo_head_hexsha": "1ae85888fb5c33f0cf01043064d30106e7a3de39", "max_stars_repo_licenses": ["MIT"], "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/large_regression/dense/replacement/benchmark_hogwild_regression.cc", "max_issues_repo_name": "abhijit-c/HOGWILD", "max_issues_repo_head_hexsha": "1ae85888fb5c33f0cf01043064d30106e7a3de39", "max_issues_repo_licenses": ["MIT"], "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/large_regression/dense/replacement/benchmark_hogwild_regression.cc", "max_forks_repo_name": "abhijit-c/HOGWILD", "max_forks_repo_head_hexsha": "1ae85888fb5c33f0cf01043064d30106e7a3de39", "max_forks_repo_licenses": ["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.0306122449, "max_line_length": 83, "alphanum_fraction": 0.6241367971, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5189348484130786}}
{"text": "#ifndef EZSOLVER_H_\n#define EZSOLVER_H_\n\n#include <Eigen/Dense>\n\nclass EzSolver {\npublic:\n  EzSolver(const Eigen::Ref<const Eigen::MatrixXd> &matA,\n           const Eigen::Ref<const Eigen::MatrixXd> &matB);\n  Eigen::VectorXcd compute(double sigma, int nev);\n  Eigen::VectorXcd compute_sym(double sigma, int nev);\n\nprivate:\n  int ndim_;\n  Eigen::MatrixXd matA_, matB_;\n};\n\n#endif", "meta": {"hexsha": "bd344b0f9d595febb5faa9e83de6a0fc41543779", "size": 378, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ezsolver.hpp", "max_stars_repo_name": "pan3rock/shift-invert", "max_stars_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_stars_repo_licenses": ["MIT"], "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/ezsolver.hpp", "max_issues_repo_name": "pan3rock/shift-invert", "max_issues_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_issues_repo_licenses": ["MIT"], "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/ezsolver.hpp", "max_forks_repo_name": "pan3rock/shift-invert", "max_forks_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_forks_repo_licenses": ["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": 58, "alphanum_fraction": 0.7169312169, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434768461855, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.518934841355986}}
{"text": "// Copyright (c) 2018 by University Paris-Est Marne-la-Vallee\n// OuterExplicit.hpp\n// This file is part of the Garamon for e3ga.\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 OuterExplicit.hpp\n/// \\author Stephane Breuils, Vincent Nozick\n/// \\brief Explicit precomputed per grades outer product.\n\n\n#ifndef E3GA_OUTER_PRODUCT_EXPLICIT_HPP__\n#define E3GA_OUTER_PRODUCT_EXPLICIT_HPP__\n#pragma once\n\n#include <Eigen/Core>\n\n#include \"e3ga/Mvec.hpp\"\n#include \"e3ga/Outer.hpp\"\n\n\n/*!\n * @namespace e3ga\n */\nnamespace e3ga {\n    template<typename T> class Mvec;\n\n    /// \\brief Compute the outer product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1^mv2, which is also a homogeneous multivector of grade 0\n\ttemplate<typename T>\n\tvoid outer_0_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the outer product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 1). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1^mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid outer_0_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1.coeff(0)*mv2;\n\t}\n\n\n\t/// \\brief Compute the outer product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 2). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1^mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid outer_0_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1.coeff(0)*mv2;\n\t}\n\n\n\t/// \\brief Compute the outer product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 3). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1^mv2, which is also a homogeneous multivector of grade 3\n\ttemplate<typename T>\n\tvoid outer_0_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1.coeff(0)*mv2;\n\t}\n\n\n\t/// \\brief Compute the outer product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1^mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid outer_1_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the outer product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 1). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1^mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid outer_1_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(1) - mv1.coeff(1)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(0)*mv2.coeff(2) - mv1.coeff(2)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(1)*mv2.coeff(2) - mv1.coeff(2)*mv2.coeff(1);\n\t}\n\n\n\t/// \\brief Compute the outer product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 2). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1^mv2, which is also a homogeneous multivector of grade 3\n\ttemplate<typename T>\n\tvoid outer_1_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(2) - mv1.coeff(1)*mv2.coeff(1) + mv1.coeff(2)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the outer product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1^mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid outer_2_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the outer product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 1). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1^mv2, which is also a homogeneous multivector of grade 3\n\ttemplate<typename T>\n\tvoid outer_2_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(2) - mv1.coeff(1)*mv2.coeff(1) + mv1.coeff(2)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the outer product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1^mv2, which is also a homogeneous multivector of grade 3\n\ttemplate<typename T>\n\tvoid outer_3_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1*mv2.coeff(0);\n\t}\n\n\n\t\n\n    template<typename T>\n\tstd::array<std::array<std::function<void(const Eigen::Matrix<T, Eigen::Dynamic, 1> & , const Eigen::Matrix<T, Eigen::Dynamic, 1> & , Eigen::Matrix<T, Eigen::Dynamic, 1>&)>, 4>, 4> outerFunctionsContainer = {{\n\t\t{{outer_0_0<T>,outer_0_1<T>,outer_0_2<T>,outer_0_3<T>}},\n\t\t{{outer_1_0<T>,outer_1_1<T>,outer_1_2<T>,{}}},\n\t\t{{outer_2_0<T>,outer_2_1<T>,{},{}}},\n\t\t{{outer_3_0<T>,{},{},{}}}\n\t}};\n\n}/// End of Namespace\n\n#endif // E3GA_OUTER_PRODUCT_EXPLICIT_HPP__", "meta": {"hexsha": "e59e2c10042701a3e9fe99b76a0a3865a2a35028", "size": 8475, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gaLib/e3ga/OuterExplicit.hpp", "max_stars_repo_name": "sbreuils/GADigitizedTransformations", "max_stars_repo_head_hexsha": "553a357fe12cd5ee0fa21ffc93d835555ea192f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T23:29:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T11:20:41.000Z", "max_issues_repo_path": "gaLib/e3ga/OuterExplicit.hpp", "max_issues_repo_name": "sbreuils/GADigitizedTransformations", "max_issues_repo_head_hexsha": "553a357fe12cd5ee0fa21ffc93d835555ea192f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-12-23T02:07:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-12T08:47:54.000Z", "max_forks_repo_path": "gaLib/e3ga/OuterExplicit.hpp", "max_forks_repo_name": "sbreuils/GADigitizedTransformations", "max_forks_repo_head_hexsha": "553a357fe12cd5ee0fa21ffc93d835555ea192f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.6774193548, "max_line_length": 209, "alphanum_fraction": 0.7169321534, "num_tokens": 2527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5189348402675441}}
{"text": "// Copyright  (C)  2018  Craig Carignan <craigc at ssl dot umd dot edu>\n\n// Version: 1.0\n// Author: Craig Carignan <craigc at ssl dot umd dot edu>\n// Maintainer: Ruben Smits <ruben dot smits at intermodalics dot eu>\n// URL: http://www.orocos.org/kdl\n\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 2.1 of the License, or (at your option) any later version.\n\n// This library 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 GNU\n// Lesser General Public License for more details.\n\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n\n// Inverse of a positive definite symmetric matrix times a vector\n// based on LDL^T Decomposition\n#ifndef LDL_SOLVER_EIGEN_HPP\n#define LDL_SOLVER_EIGEN_HPP\n\n\n#include <Eigen/Core>\n#include \"../solveri.hpp\"\n\nnamespace KDL\n{\n    /**\n     * \\brief Solves the system of equations Aq = v for q via LDL decomposition,\n     *        where A is a square positive definite matrix\n     *\n     * The algorithm factor A into the product of three matrices LDL^T, where L\n     * is a lower triangular matrix and D is a diagonal matrix.  This allows q\n     * to be computed without explicity inverting A.  Note that the LDL decomposition\n     * is a variant of the classical Cholesky Decomposition that does not require\n     * the computation of square roots.\n     * Input parameters:\n     * @param A matrix<double>(nxn)\n     * @param v vector<double> n\n     * @param vtmp vector<double> n [temp variable]\n     * Output parameters:\n     * @param L matrix<double>(nxn)\n     * @param D vector<double> n\n     * @param q vector<double> n\n     * @return 0 if successful, E_SIZE_MISMATCH if dimensions do not match\n     * References:\n     * https://en.wikipedia.org/wiki/Cholesky_decomposition\n     */\n    int ldl_solver_eigen(const Eigen::MatrixXd& A, const Eigen::VectorXd& v, Eigen::MatrixXd& L, Eigen::VectorXd& D, Eigen::VectorXd& vtmp, Eigen::VectorXd& q);\n}\n#endif\n", "meta": {"hexsha": "f54aa947288213ea93deafe6c06b094e4a0978ae", "size": 2337, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdparty/kdl/src/utilities/ldl_solver_eigen.hpp", "max_stars_repo_name": "rocos-sia/rocos-app", "max_stars_repo_head_hexsha": "83aa8aa31dd303d77693cfc5ad48055d051fa4bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-06T15:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:21:40.000Z", "max_issues_repo_path": "3rdparty/kdl/src/utilities/ldl_solver_eigen.hpp", "max_issues_repo_name": "thinkexist1989/rocos-app", "max_issues_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_issues_repo_licenses": ["MIT"], "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/kdl/src/utilities/ldl_solver_eigen.hpp", "max_forks_repo_name": "thinkexist1989/rocos-app", "max_forks_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_forks_repo_licenses": ["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.2931034483, "max_line_length": 160, "alphanum_fraction": 0.7133076594, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.518934840267544}}
{"text": "#include <random>\n\n#include <ros/ros.h>\n#include <geometry_msgs/PoseArray.h>\n#include <tf/tf.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/transform_listener.h>\n\n#include <Eigen/Dense>\n\nint NUM_OBSTACLE;\ndouble NEIGHBER_RANGE = 5.0;\ndouble LAMBDA = 2.0;\ndouble GAMMA = 0.35;\ndouble N_PRIME = 3.0;\ndouble N = 2.0;\ndouble MAX_VELOCITY = 1.5;\ndouble RELAXATION_TIME = 0.5;\ndouble DESIRED_FORCE_FACTOR;\ndouble SOCIAL_FORCE_FACTOR;\ndouble HZ;\ndouble INITIAL_KEEP_OUT_POSITION_X;\ndouble INITIAL_KEEP_OUT_POSITION_Y;\ndouble INITIAL_KEEP_OUT_RANGE;\n\n\nstd::string ROBOT_FRAME;\nstd::string WORLD_FRAME;\nstd::string OBS_FRAME;\ndouble SIMULATION_SQUARE_LENGTH;\n\nclass SFMObstacle\n{\npublic:\n    SFMObstacle(void);\n\n    unsigned int id;\n    Eigen::Vector3d pose;\n    Eigen::Vector3d velocity;\n    Eigen::Vector3d current_goal;\n    double preferred_speed;\n    bool dodging_right;\n    Eigen::Vector3d last_desired_force;\n    Eigen::Vector3d last_social_force;\nprivate:\n};\n\nSFMObstacle::SFMObstacle(void)\n{\n    id = 0;\n    pose = Eigen::Vector3d::Zero();\n    velocity = Eigen::Vector3d::Zero();\n    current_goal = Eigen::Vector3d::Zero();\n    preferred_speed = 1.0;\n    dodging_right = true;\n    last_desired_force = Eigen::Vector3d::Zero();\n    last_social_force = Eigen::Vector3d::Zero();\n}\n\nstd::ostream& operator<<(std::ostream& out, const SFMObstacle& sfmo)\n{\n    out << \"id: \" << sfmo.id << \"\\n\"\n        << \"pose: \" << sfmo.pose.transpose() << \"\\n\"\n        << \"velocity: \" << sfmo.velocity.transpose() << \"\\n\"\n        << \"current speed: \" << sfmo.velocity.norm() << \"\\n\"\n        << \"current goal: \" << sfmo.current_goal.transpose() << \"\\n\"\n        << \"last desired force: \" << sfmo.last_desired_force.transpose() << \"\\n\"\n        << \"last social force: \" << sfmo.last_social_force.transpose();\n    return out;\n}\n\nEigen::Vector3d get_next_goal(const SFMObstacle& agent)\n{\n    Eigen::Vector3d new_goal = Eigen::Vector3d::Zero();\n    while(1){\n        new_goal = Eigen::Vector3d::Random() * SIMULATION_SQUARE_LENGTH * 0.5;\n        double distance_from_agent = (new_goal - agent.pose).norm();\n        if(distance_from_agent > SIMULATION_SQUARE_LENGTH * 0.5){\n            return new_goal;\n        }\n    }\n}\n\nEigen::Vector3d get_social_force(const SFMObstacle& agent, const std::vector<SFMObstacle>& obstacles)\n{\n    Eigen::Vector3d force = Eigen::Vector3d::Zero();\n\n    for(auto obstacle : obstacles){\n        if(agent.id == obstacle.id){\n            continue;\n        }\n\n        Eigen::Vector3d diff_vector = obstacle.pose - agent.pose;\n        double distance = diff_vector.norm();\n        if (distance > NEIGHBER_RANGE){\n            continue;\n        }\n        // e_{ij}\n        Eigen::Vector3d diff_direction = diff_vector.normalized();\n\n        double other_angle = atan2(diff_direction(1), diff_direction(0));\n        double agent_angle = atan2(agent.velocity(1), agent.velocity(0));\n        double angle_fov = other_angle - agent_angle;\n        angle_fov = atan2(sin(angle_fov), cos(angle_fov));\n        if(fabs(angle_fov) > M_PI * 5.0 / 6.0){\n            continue;\n        }\n\n        Eigen::Vector3d velocity_diff = agent.velocity - obstacle.velocity;\n\n        // D_{ij}\n        Eigen::Vector3d interaction_vector = LAMBDA * velocity_diff + diff_direction;\n        // t_{ij}\n        Eigen::Vector3d interaction_direction = interaction_vector.normalized();\n\n        double interaction_angle = atan2(interaction_direction(1), interaction_direction(0));\n        double theta_angle = other_angle - interaction_angle;\n        theta_angle = atan2(sin(theta_angle), cos(theta_angle));\n\n        double sign_of_theta = (fabs(theta_angle) == 0.00) ? 0.0 : theta_angle / fabs(theta_angle);\n\n        double b = GAMMA * interaction_vector.norm();\n\n        double force_velocity_amount = -std::exp(-diff_vector.norm() / b - (N_PRIME * b * theta_angle) * (N_PRIME * b * theta_angle));\n        double force_angle_amount = -sign_of_theta * std::exp(-diff_vector.norm() / b - (N * b * theta_angle) * (N * b * theta_angle));\n\n        Eigen::Vector3d force_velocity = force_velocity_amount * interaction_direction;\n\n        Eigen::Vector3d interaction_direction_normal;\n        if(agent.dodging_right){\n            interaction_direction_normal << -interaction_direction(1), interaction_direction(0), interaction_direction(2);\n        }else{\n            interaction_direction_normal << interaction_direction(1), -interaction_direction(0), interaction_direction(2);\n        }\n\n        Eigen::Vector3d force_angle = force_angle_amount * interaction_direction_normal;\n\n        force += force_velocity + force_angle;\n    }\n    return force;\n}\n\nEigen::Vector3d get_desired_force(const SFMObstacle& agent)\n{\n    Eigen::Vector3d force = Eigen::Vector3d::Zero();\n    // force = (agent.current_goal - agent.pose).normalized();\n    Eigen::Vector3d desired_vector = (agent.current_goal - agent.pose).normalized();\n    force = (agent.preferred_speed * desired_vector - agent.velocity) / RELAXATION_TIME;\n    return force;\n}\n\nvoid set_obs_list(const std::vector<SFMObstacle>& obstacles, std::vector<geometry_msgs::TransformStamped>& obs_list)\n{\n    obs_list.clear();\n    for(auto& obs : obstacles){\n        geometry_msgs::TransformStamped tfs;\n        tfs.header.stamp = ros::Time::now();\n        tfs.header.frame_id = WORLD_FRAME;\n        tfs.child_frame_id = OBS_FRAME + std::to_string(obs.id);\n        tfs.transform.translation.x = obs.pose(0);\n        tfs.transform.translation.y = obs.pose(1);\n        tfs.transform.rotation = tf::createQuaternionMsgFromYaw(atan2(obs.velocity(1), obs.velocity(0)));\n        obs_list.push_back(tfs);\n    }\n}\n\nvoid simulate_one_step(std::vector<SFMObstacle>& obstacles, double dt)\n{\n    if(dt < 0.0){\n        return;\n    }\n    // std::cout << \"simulate one step\" << std::endl;\n    for(auto& obs : obstacles){\n        // std::cout << obs << std::endl;\n        Eigen::Vector3d relative_goal = obs.current_goal - obs.pose;\n        if(relative_goal.norm() < 0.5){\n            obs.current_goal = Eigen::Vector3d::Random() * SIMULATION_SQUARE_LENGTH * 0.5;\n            obs.current_goal = get_next_goal(obs);\n            obs.current_goal(2) = 0;\n        }\n        Eigen::Vector3d desired_force = get_desired_force(obs);\n        obs.last_desired_force = desired_force;\n        // std::cout << obs.last_desired_force.transpose() << std::endl;\n        Eigen::Vector3d social_force = get_social_force(obs, obstacles);\n        obs.last_social_force = social_force;\n        // std::cout << obs.last_social_force.transpose() << std::endl;\n        Eigen::Vector3d force = DESIRED_FORCE_FACTOR * desired_force + SOCIAL_FORCE_FACTOR * social_force;\n        obs.velocity += obs.velocity + force * dt;\n        // std::cout << obs.velocity.transpose() << std::endl;\n        double speed = obs.velocity.norm();\n        if(speed > obs.preferred_speed){\n            obs.velocity = obs.velocity.normalized() * obs.preferred_speed;\n        }\n        obs.pose += obs.velocity * dt;\n        // std::cout << obs.pose.transpose() << std::endl;\n    }\n}\n\nint main(int argc, char** argv)\n{\n    ros::init(argc, argv, \"sfm_obstacle_simulator\");\n    std::cout << \"=== sfm_obstacle_simulator ===\" << std::endl;\n    ros::NodeHandle nh;\n\n    ros::NodeHandle local_nh(\"~\");\n\n    local_nh.param<std::string>(\"/dynamic_avoidance/ROBOT_FRAME\", ROBOT_FRAME, {\"base_link\"});\n    local_nh.param<std::string>(\"/dynamic_avoidance/WORLD_FRAME\", WORLD_FRAME, {\"map\"});\n    local_nh.param<std::string>(\"/dynamic_avoidance/OBSTACLES_FRAME\", OBS_FRAME, {\"obs\"});\n    local_nh.param<double>(\"HZ\", HZ, {20.0});\n    local_nh.param<int>(\"NUM_OBSTACLE\", NUM_OBSTACLE, {20});\n    local_nh.param<double>(\"DESIRED_FORCE_FACTOR\", DESIRED_FORCE_FACTOR, {20.0});\n    local_nh.param<double>(\"SOCIAL_FORCE_FACTOR\", SOCIAL_FORCE_FACTOR, {100.0});\n    local_nh.param<double>(\"SIMULATION_SQUARE_LENGTH\", SIMULATION_SQUARE_LENGTH, {20.0});\n    local_nh.param<double>(\"INITIAL_KEEP_OUT_POSITION_X\", INITIAL_KEEP_OUT_POSITION_X, {-10.0});\n    local_nh.param<double>(\"INITIAL_KEEP_OUT_POSITION_Y\", INITIAL_KEEP_OUT_POSITION_Y, {0.0});\n    local_nh.param<double>(\"INITIAL_KEEP_OUT_RANGE\", INITIAL_KEEP_OUT_RANGE, {3.0});\n    int SEED;\n    local_nh.param<int>(\"SEED\", SEED, {-1});\n\n    std::cout << \"HZ: \" << HZ << std::endl;\n    std::cout << \"NUM_OBSTACLE: \" << NUM_OBSTACLE << std::endl;\n    std::cout << \"DESIRED_FORCE_FACTOR: \" << DESIRED_FORCE_FACTOR << std::endl;\n    std::cout << \"SOCIAL_FORCE_FACTOR: \" << SOCIAL_FORCE_FACTOR << std::endl;\n    std::cout << \"SIMULATION_SQUARE_LENGTH: \" << SIMULATION_SQUARE_LENGTH << std::endl;\n    std::cout << \"INITIAL_KEEP_OUT_POSITION_X: \" << INITIAL_KEEP_OUT_POSITION_X << std::endl;\n    std::cout << \"INITIAL_KEEP_OUT_POSITION_Y: \" << INITIAL_KEEP_OUT_POSITION_Y << std::endl;\n    std::cout << \"INITIAL_KEEP_OUT_RANGE: \" << INITIAL_KEEP_OUT_RANGE << std::endl;\n    std::cout << \"SEED: \" << SEED << std::endl;\n\n    ros::Rate loop_rate(HZ);\n\n    tf::TransformBroadcaster obs_broadcaster;\n\n    // srand((unsigned int)time(0));// for Eigen\n    // srand((unsigned int)SEED);// for Eigen\n    srand(SEED < 0 ? (unsigned int)time(0) : (unsigned int)SEED);// for Eigen\n    std::random_device rnd;\n    std::mt19937 mt(SEED < 0 ? rnd() : SEED);\n    std::uniform_real_distribution<> dist(1.0, MAX_VELOCITY);\n    std::uniform_int_distribution<> dist_bool(0, 1);\n\n    std::vector<SFMObstacle> obstacles;\n    obstacles.clear();\n    // initialize\n    Eigen::Vector3d init_pos(INITIAL_KEEP_OUT_POSITION_X, INITIAL_KEEP_OUT_POSITION_Y, 0.0);\n    for(int i=0;i<NUM_OBSTACLE;i++){\n        SFMObstacle o;\n        o.id = i;\n        while(1){\n            o.pose = Eigen::Vector3d::Random() * SIMULATION_SQUARE_LENGTH * 0.5;\n            o.pose(2) = 0;\n            if((o.pose - init_pos).norm() > INITIAL_KEEP_OUT_RANGE){\n                break;\n            }\n        }\n        o.velocity = Eigen::Vector3d::Random();\n        o.velocity(2) = 0;\n        o.current_goal = Eigen::Vector3d::Random() * SIMULATION_SQUARE_LENGTH * 0.5;\n        o.current_goal(2) = 0;\n        o.preferred_speed = dist(mt);\n        o.dodging_right = dist(mt);\n        obstacles.push_back(o);\n        std::cout << o << std::endl;\n    }\n\n    tf::TransformListener listener;\n\n    while(ros::ok()){\n        bool robot_added_flag = false;\n        try{\n            static bool first_tf_flag = true;\n            static double last_tf_time = 0;\n            static Eigen::Vector3d last_robot_pose = Eigen::Vector3d::Zero();\n            Eigen::Vector3d robot_velocity = Eigen::Vector3d::Zero();\n            Eigen::Vector3d robot_pose = Eigen::Vector3d::Zero();\n\n            geometry_msgs::PoseStamped robot_p;\n            robot_p.header.frame_id = ROBOT_FRAME;\n            robot_p.header.stamp = ros::Time(0);\n            robot_p.pose.orientation = tf::createQuaternionMsgFromYaw(0);\n            listener.transformPose(WORLD_FRAME, robot_p, robot_p);\n            robot_pose(0) = robot_p.pose.position.x;\n            robot_pose(1) = robot_p.pose.position.y;\n            if(!first_tf_flag){\n                double dt = robot_p.header.stamp.toSec() - last_tf_time;\n                if(dt > 1e-4){\n                    robot_velocity = (robot_pose - last_robot_pose) / dt;\n                }else{\n                    robot_velocity = Eigen::Vector3d::Zero();\n                }\n            }else{\n                first_tf_flag = false;\n            }\n            SFMObstacle robot_o;\n            robot_o.id = obstacles.size();\n            robot_o.pose = robot_pose;\n            robot_o.velocity = robot_velocity;\n            robot_o.current_goal = robot_o.pose + robot_o.velocity * 5.0;// 5[s] after\n            obstacles.push_back(robot_o);\n            // std::cout << \"robot is added\" << std::endl;\n            // std::cout << robot_o << std::endl;\n            // std::cout << robot_p.header.stamp.toSec() - last_tf_time << std::endl;\n            // std::cout << last_robot_pose.transpose() << std::endl;\n\n            robot_added_flag = true;\n            last_robot_pose = robot_pose;\n            last_tf_time = robot_p.header.stamp.toSec();\n        }catch(tf::TransformException& ex){\n            std::cout << ex.what() << std::endl;\n        }\n\n        simulate_one_step(obstacles, 1 / HZ);\n\n        if(robot_added_flag){\n            obstacles.pop_back();\n        }\n\n        std::vector<geometry_msgs::TransformStamped> obs_list;\n        obs_list.clear();\n        set_obs_list(obstacles, obs_list);\n\n        std::cout << \"===\" << std::endl;\n        for(const auto obs : obstacles){\n            std::cout << obs << std::endl;\n        }\n\n        obs_broadcaster.sendTransform(obs_list);\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n    return 0;\n};\n", "meta": {"hexsha": "7dd01faf5b11d3d38eebd16d66ce5a91b750a3c7", "size": 12668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sfm_obstacle_simulator.cpp", "max_stars_repo_name": "amslabtech/dynamic_obstacle_avoidance_planner", "max_stars_repo_head_hexsha": "e8d3a883f917cb247529204ab8ebb591247bae69", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2019-08-23T12:38:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T09:06:11.000Z", "max_issues_repo_path": "src/sfm_obstacle_simulator.cpp", "max_issues_repo_name": "amslabtech/dynamic_obstacle_avoidance_planner", "max_issues_repo_head_hexsha": "e8d3a883f917cb247529204ab8ebb591247bae69", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-08-16T03:16:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-23T14:29:52.000Z", "max_forks_repo_path": "src/sfm_obstacle_simulator.cpp", "max_forks_repo_name": "amslabtech/dynamic_obstacle_avoidance_planner", "max_forks_repo_head_hexsha": "e8d3a883f917cb247529204ab8ebb591247bae69", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2019-08-06T11:34:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T09:10:49.000Z", "avg_line_length": 37.9281437126, "max_line_length": 135, "alphanum_fraction": 0.6325386801, "num_tokens": 3198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5188913347375985}}
{"text": "\n// Copyright 2014, D. E. Shaw Research.\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// A few (2) rounds of a PRNG has some appeal as a 'randomizing'\n// alternative to the existing boost::hash_value.\n//\n// This is just a sketch... \n//\n// A fully general version would require quite a bit more template\n// armor to handle all the integer-promotion corner cases and aliases\n// and the fact that philox and threefry have only uint32 and uint64\n// variants.\n//\n// How many rounds is enough?  Hash_value's main use is to index into\n// hash tables, so it may not have to be a certifiably \"good\" random\n// number generator which would require 7 rounds for philox and 13 for\n// threefry.  Two rounds of philox or four rounds of threefry \"looks\"\n// random, which may be sufficient.  That may be \"random\" enough to\n// satisfy people who are unhappy with the complete lack of \n// randomness in the current (1.55) implementation of hash_value(v).\n\n#include <boost/random/philox.hpp>\n#include <boost/cstdint.hpp>\n\nsize_t hash_value(uint32_t x){\n    typedef uint32_t Uint;\n    boost::array<Uint, 2> c = {x, 0};\n    return size_t(boost::random::philox<2, Uint, 2>()(c)[0]);\n}\n\nsize_t hash_value(uint64_t x){\n    typedef uint64_t Uint;\n    boost::array<Uint, 2> c = {x, 0};\n    return size_t(boost::random::philox<2, Uint, 2>()(c)[0]);\n}\n\nint main(int argc, char **argv){\n    for(unsigned i=0; i<10; ++i){\n        size_t hv = hash_value(i);\n        std::cout << \"hv(\" << i << \") = \" << hv << std::hex << \" = \" << hv << std::dec << \"\\n\";\n    }\n    return 0;\n}\n", "meta": {"hexsha": "8bb7caa5ee7437c70b62b08b9b767046edf192b0", "size": 1657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/examples/philox_hash_value.cpp", "max_stars_repo_name": "DEShawResearch/Random123-Boost", "max_stars_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-04-08T18:40:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T00:08:25.000Z", "max_issues_repo_path": "libs/random/examples/philox_hash_value.cpp", "max_issues_repo_name": "DEShawResearch/Random123-Boost", "max_issues_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/random/examples/philox_hash_value.cpp", "max_forks_repo_name": "DEShawResearch/Random123-Boost", "max_forks_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "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.2553191489, "max_line_length": 95, "alphanum_fraction": 0.6722993361, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5188913257011284}}
{"text": "// Copyright 2021 Apex.AI, Inc.\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//  \u00a0 \u00a0http://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// Co-developed by Tier IV, Inc. and Apex.AI, Inc.\n\n#ifndef STATE_ESTIMATION__KALMAN_FILTER__KALMAN_FILTER_HPP_\n#define STATE_ESTIMATION__KALMAN_FILTER__KALMAN_FILTER_HPP_\n\n#include <helper_functions/float_comparisons.hpp>\n#include <motion_model/motion_model_interface.hpp>\n#include <motion_model/stationary_motion_model.hpp>\n#include <state_estimation/noise_model/noise_interface.hpp>\n#include <state_estimation/state_estimation_interface.hpp>\n#include <state_estimation/visibility_control.hpp>\n\n#include <Eigen/LU>\n\n#include <limits>\n#include <vector>\n\nnamespace autoware\n{\nnamespace common\n{\nnamespace state_estimation\n{\n///\n/// @brief      A Kalman filter implementation.\n///\n/// @tparam     MotionModelT  Type of the motion model.\n/// @tparam     NoiseModelT   Type of the noise model.\n///\ntemplate<typename MotionModelT, typename NoiseModelT>\nclass STATE_ESTIMATION_PUBLIC KalmanFilter\n  : public StateEstimationInterface<KalmanFilter<MotionModelT, NoiseModelT>>\n{\n  static_assert(\n    std::is_base_of<common::motion_model::MotionModelInterface<MotionModelT>, MotionModelT>::value,\n    \"\\n\\nMotion model must inherit from MotionModelInterface\\n\\n\");\n  static_assert(\n    std::is_base_of<NoiseInterface<NoiseModelT>, NoiseModelT>::value,\n    \"\\n\\nNoise model must inherit from NoiseInterface\\n\\n\");\n  static_assert(\n    std::is_same<typename MotionModelT::State, typename NoiseModelT::State>::value,\n    \"\\n\\nMotion model and noise model must have the same underlying state\\n\\n\");\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  using State = typename MotionModelT::State;\n  using StateMatrix = typename State::Matrix;\n  using MotionModel = MotionModelT;\n  using NoiseModel = NoiseModelT;\n\n  ///\n  /// @brief      Constructs a new instance of a Kalman filter.\n  ///\n  /// @param[in]  motion_model        The motion model to be used to predict the movement.\n  /// @param[in]  noise_model         The noise model that models the motion noise.\n  /// @param[in]  initial_state       The initial state of the filter.\n  /// @param[in]  initial_covariance  The initial state covariance.\n  ///\n  explicit KalmanFilter(\n    MotionModelT motion_model,\n    NoiseModelT noise_model,\n    const State & initial_state,\n    const StateMatrix & initial_covariance)\n  : m_motion_model{motion_model},\n    m_noise_model{noise_model},\n    m_state{initial_state},\n    m_covariance{initial_covariance} {}\n\n  ///\n  /// @brief      Predict next state.\n  ///\n  /// @param[in]  dt    Time difference to the time at which prediction is needed.\n  ///\n  /// @return     Predicted state.\n  ///\n  State crtp_predict(const std::chrono::nanoseconds & dt)\n  {\n    m_state = m_motion_model.predict(m_state, dt);\n    const auto & motion_jacobian = m_motion_model.jacobian(m_state, dt);\n    m_covariance =\n      motion_jacobian * m_covariance * motion_jacobian.transpose() + m_noise_model.covariance(dt);\n    return m_state;\n  }\n\n  ///\n  /// @brief      Correct the predicted state given a measurement\n  ///\n  /// @note       It is expected that a prediction step was done right before the correction.\n  ///\n  /// @param[in]  measurement   Current measurement.\n  ///\n  /// @tparam     MeasurementT  Measurement type.\n  ///\n  /// @return     State corrected with the measurement.\n  ///\n  template<typename MeasurementT>\n  State crtp_correct(const MeasurementT & measurement)\n  {\n    const auto expected_measurement = measurement.create_new_instance_from(m_state);\n    const auto innovation = wrap_all_angles(measurement.state() - expected_measurement);\n    const auto mapping_matrix = measurement.mapping_matrix_from(m_state);\n    const auto innovation_covariance =\n      mapping_matrix * m_covariance * mapping_matrix.transpose() + measurement.covariance();\n    const auto kalman_gain =\n      m_covariance * mapping_matrix.transpose() * innovation_covariance.inverse();\n    m_state += kalman_gain * innovation.vector();\n    m_state.wrap_all_angles();\n    m_covariance = (State::Matrix::Identity() - kalman_gain * mapping_matrix) * m_covariance;\n    return m_state;\n  }\n\n  ///\n  /// @brief      Reset the state of the filter to a given state and covariance.\n  ///\n  /// @param[in]  state       The new state that overwrites one stored in the filter.\n  /// @param[in]  covariance  The new covariance that overwrites one stored in the filter.\n  ///\n  void crtp_reset(const State & state, const StateMatrix & covariance)\n  {\n    m_state = state;\n    m_covariance = covariance;\n  }\n\n  /// @brief      Get current state.\n  auto & crtp_state() {return m_state;}\n  /// @brief      Get current state.\n  const auto & crtp_state() const {return m_state;}\n\n  /// @brief      Get current covariance.\n  auto & crtp_covariance() {return m_covariance;}\n  /// @brief      Get current covariance.\n  const auto & crtp_covariance() const {return m_covariance;}\n\nprivate:\n  /// Motion model used to predict the state forward.\n  MotionModelT m_motion_model{};\n  /// Noise model of the movement.\n  NoiseModelT m_noise_model{};\n  /// State of the tracked object.\n  State m_state{};\n  /// Covariance of the state of the tracked object.\n  StateMatrix m_covariance{StateMatrix::Zero()};\n};\n\n///\n/// @brief      A utility function that creates a Kalman filter.\n///\n/// @details    Mostly this is needed to avoid passing the template parameters explicitly and let\n///             the compiler infer them from the objects passed into this function.\n///\n/// @param[in]  motion_model        A motion model.\n/// @param[in]  noise_model         A noise model.\n/// @param[in]  initial_state       The initial state\n/// @param[in]  initial_covariance  The initial covariance\n///\n/// @tparam     MotionModelT        Type of the motion model.\n/// @tparam     NoiseModelT         Type of the noise model.\n///\n/// @return     Returns a valid KalmanFilter instance.\n///\ntemplate<typename MotionModelT, typename NoiseModelT>\nauto make_kalman_filter(\n  const MotionModelT & motion_model,\n  const NoiseModelT & noise_model,\n  const typename MotionModelT::State & initial_state,\n  const typename MotionModelT::State::Matrix & initial_covariance)\n{\n  return KalmanFilter<MotionModelT, NoiseModelT>{\n    motion_model, noise_model, initial_state, initial_covariance};\n}\n\n///\n/// @brief      A utility function that creates a Kalman filter that is to be used for correction\n///             only, i.e., this Kalman filter cannot predict the state forward in time.\n///\n/// @details    Mostly this is needed to avoid passing the template parameters explicitly and let\n///             the compiler infer them from the objects passed into this function.\n///\n/// @param[in]  initial_state       The initial state\n/// @param[in]  initial_covariance  The initial covariance\n///\n/// @tparam     StateT              { description }\n/// @tparam     MotionModelT  Type of the motion model.\n/// @tparam     NoiseModelT   Type of the noise model.\n///\n/// @return     Returns a valid KalmanFilter instance.\n///\ntemplate<typename StateT>\nauto make_correction_only_kalman_filter(\n  const StateT & initial_state,\n  const typename StateT::Matrix & initial_covariance)\n{\n  struct DummyNoise : public NoiseInterface<DummyNoise>\n  {\n    using State = StateT;\n    typename State::Matrix crtp_covariance(const std::chrono::nanoseconds &) const\n    {\n      throw std::runtime_error(\n              \"Trying to use a correction-only Kalman filter to predict the state.\");\n    }\n  };\n\n  using MotionModel = common::motion_model::StationaryMotionModel<StateT>;\n\n  return make_kalman_filter(\n    MotionModel{}, DummyNoise{}, initial_state, initial_covariance);\n}\n\n///\n/// @brief      A utility function that creates a Kalman filter from a vector of variances.\n///\n///             Mostly this is needed to avoid passing the template parameters explicitly and let\n///             the compiler infer them from the objects passed into this function.\n///\n/// @param[in]  motion_model       A motion model.\n/// @param[in]  noise_model        A noise model.\n/// @param[in]  initial_state      Initial state.\n/// @param[in]  initial_variances  Initial variances as a vector.\n///\n/// @tparam     MotionModelT       Type of the motion model.\n/// @tparam     NoiseModelT        Type of the noise model.\n///\n/// @return     Returns a valid KalmanFilter instance.\n///\ntemplate<typename MotionModelT, typename NoiseModelT>\nauto make_kalman_filter(\n  const MotionModelT & motion_model,\n  const NoiseModelT & noise_model,\n  const typename MotionModelT::State & initial_state,\n  const std::vector<typename MotionModelT::State::Scalar> & initial_variances)\n{\n  using State = typename MotionModelT::State;\n  if (initial_variances.size() != static_cast<std::size_t>(State::size())) {\n    std::runtime_error(\n      \"Cannot create Kalman filter - dimensions mismatch. Provided \" +\n      std::to_string(initial_variances.size()) + \" variances, but \" +\n      std::to_string(State::size()) + \" required.\");\n  }\n  typename State::Vector variances{State::Vector::Zero()};\n  // A small enough epsilon to compare a floating point variance with zero.\n  const auto epsilon = 5.0F * std::numeric_limits<common::types::float32_t>::epsilon();\n  for (std::uint32_t i = 0; i < initial_variances.size(); ++i) {\n    if (common::helper_functions::comparisons::abs_lte(initial_variances[i], 0.0F, epsilon)) {\n      throw std::domain_error(\"Variances must be positive\");\n    }\n    variances[static_cast<std::int32_t>(i)] = initial_variances[i] * initial_variances[i];\n  }\n  return KalmanFilter<MotionModelT, NoiseModelT>{\n    motion_model, noise_model, initial_state, variances.asDiagonal()};\n}\n\n}  // namespace state_estimation\n}  // namespace common\n}  // namespace autoware\n\n#endif  // STATE_ESTIMATION__KALMAN_FILTER__KALMAN_FILTER_HPP_\n", "meta": {"hexsha": "7364fc0f55dab18733db0a6b68cc6492109cce12", "size": 10277, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/state_estimation/include/state_estimation/kalman_filter/kalman_filter.hpp", "max_stars_repo_name": "QS-L-1992/AutowareAuto", "max_stars_repo_head_hexsha": "f35a22677cbd2309ecae36d52f83f035cd96b8cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T06:14:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T10:03:08.000Z", "max_issues_repo_path": "src/common/state_estimation/include/state_estimation/kalman_filter/kalman_filter.hpp", "max_issues_repo_name": "QS-L-1992/AutowareAuto", "max_issues_repo_head_hexsha": "f35a22677cbd2309ecae36d52f83f035cd96b8cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2021-10-29T22:00:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T20:56:34.000Z", "max_forks_repo_path": "src/common/state_estimation/include/state_estimation/kalman_filter/kalman_filter.hpp", "max_forks_repo_name": "QS-L-1992/AutowareAuto", "max_forks_repo_head_hexsha": "f35a22677cbd2309ecae36d52f83f035cd96b8cb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2021-05-29T14:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:03:09.000Z", "avg_line_length": 37.9225092251, "max_line_length": 99, "alphanum_fraction": 0.7117835944, "num_tokens": 2396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5188913211828929}}
{"text": "/*\n\nPICCANTE\nThe hottest HDR imaging library!\nhttp://vcg.isti.cnr.it/piccante\n\nCopyright (C) 2014\nVisual Computing Laboratory - ISTI CNR\nhttp://vcg.isti.cnr.it\nFirst author: Francesco Banterle\n\nThis Source Code Form is subject to the terms of the Mozilla Public\nLicense, v. 2.0. If a copy of the MPL was not distributed with this\nfile, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n*/\n\n#ifndef PIC_COMPUTER_VISION_HOMOGRAPHY_HPP\n#define PIC_COMPUTER_VISION_HOMOGRAPHY_HPP\n\n#include <vector>\n#include <random>\n#include <stdlib.h>\n\n#include \"../base.hpp\"\n\n#include \"../util/math.hpp\"\n#include \"../util/eigen_util.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n\n#ifndef PIC_EIGEN_NOT_BUNDLED\n    #include \"../externals/Eigen/Dense\"\n    #include \"../externals/Eigen/SVD\"\n    #include \"../externals/Eigen/Geometry\"\n#else\n    #include <Eigen/Dense>\n    #include <Eigen/SVD>\n    #include <Eigen/Geometry>\n#endif\n\n#endif\n\n#include \"../computer_vision/nelder_mead_opt_homography.hpp\"\n\nnamespace pic {\n\n#ifndef PIC_DISABLE_EIGEN\n\n/**\n * @brief estimateHomography estimates an homography matrix H between image 1 to image 2\n * @param points0 is an array of points computed from image 1.\n * @param points1 is an array of points computed from image 2.\n * @return It returns the homography matrix H.\n */\nPIC_INLINE Eigen::Matrix3d estimateHomography(std::vector< Eigen::Vector2f > &points0,\n                                   std::vector< Eigen::Vector2f > &points1)\n{\n    Eigen::Matrix3d  H;\n\n    if((points0.size() != points1.size()) || (points0.size() < 4)) {\n        H.setZero();\n        return H;\n    }\n\n    Eigen::Vector3f transform_0 = ComputeNormalizationTransform(points0);\n    Eigen::Vector3f transform_1 = ComputeNormalizationTransform(points1);\n\n    Eigen::Matrix3d mat_0 = getShiftScaleMatrix(transform_0);\n    Eigen::Matrix3d mat_1 = getShiftScaleMatrix(transform_1);\n\n    int n = int(points0.size());\n    Eigen::MatrixXd A(n * 2, 9);\n\n    //set up the linear system\n    for(int i = 0; i < n; i++) {\n        //transform coordinates for increasing stability of the system\n        Eigen::Vector2f p0 = points0[i];\n        Eigen::Vector2f p1 = points1[i];\n\n        p0[0] = (p0[0] - transform_0[0]) / transform_0[2];\n        p0[1] = (p0[1] - transform_0[1]) / transform_0[2];\n\n        p1[0] = (p1[0] - transform_1[0]) / transform_1[2];\n        p1[1] = (p1[1] - transform_1[1]) / transform_1[2];\n\n        int j = i * 2;\n        A(j, 0) = 0.0;\n        A(j, 1) = 0.0;\n        A(j, 2) = 0.0;\n        A(j, 3) = p0[0];\n        A(j, 4) = p0[1];\n        A(j, 5) = 1.0;\n        A(j, 6) = -p1[1] * p0[0];\n        A(j, 7) = -p1[1] * p0[1];\n        A(j, 8) = -p1[1];\n\n        j++;\n\n        A(j, 0) = p0[0];\n        A(j, 1) = p0[1];\n        A(j, 2) = 1.0;\n        A(j, 3) = 0.0;\n        A(j, 4) = 0.0;\n        A(j, 5) = 0.0;\n        A(j, 6) = -p1[0] * p0[0];\n        A(j, 7) = -p1[0] * p0[1];\n        A(j, 8) = -p1[0];\n    }\n\n    //solve the linear system\n    Eigen::JacobiSVD< Eigen::MatrixXd > svd(A, Eigen::ComputeFullV);\n    Eigen::MatrixXd V = svd.matrixV();\n\n    n = int(V.cols()) - 1;\n\n    //assign and transpose\n    H(0, 0) = V(0, n);\n    H(0, 1) = V(1, n);\n    H(0, 2) = V(2, n);\n\n    H(1, 0) = V(3, n);\n    H(1, 1) = V(4, n);\n    H(1, 2) = V(5, n);\n\n    H(2, 0) = V(6, n);\n    H(2, 1) = V(7, n);\n    H(2, 2) = V(8, n);\n\n    H = mat_1.inverse() * H * mat_0;\n    return H / H(2, 2);\n}\n\n/**\n * @brief estimateHomographyRansac computes the homography such that: points1 = H * points0\n * @param points0\n * @param points1\n * @param inliers\n * @param maxIterations\n * @return\n */\nPIC_INLINE Eigen::Matrix3d estimateHomographyRansac(std::vector< Eigen::Vector2f > &points0,\n                                         std::vector< Eigen::Vector2f > &points1,\n                                         std::vector< unsigned int > &inliers,\n                                         unsigned int maxIterations = 100,\n                                         double threshold = 4.0,\n                                         unsigned int seed = 1)\n{\n    if(points0.size() < 5) {\n        return estimateHomography(points0, points1);\n    }\n\n    Eigen::Matrix3d H;\n    int nSubSet = 4;\n\n    std::mt19937 m(seed);\n\n    unsigned int n = int(points0.size());\n\n    unsigned int *subSet = new unsigned int [nSubSet];\n\n    inliers.clear();\n\n    for(unsigned int i = 0; i < maxIterations; i++) {       \n\n        getRandomPermutation(m, subSet, nSubSet, n);\n\n        std::vector< Eigen::Vector2f > sub_points0;\n        std::vector< Eigen::Vector2f > sub_points1;\n\n        for(int j = 0; j < nSubSet; j++) {\n            sub_points0.push_back(points0[subSet[j]]);\n            sub_points1.push_back(points1[subSet[j]]);\n        }\n\n        Eigen::Matrix3d tmpH = estimateHomography(sub_points0, sub_points1);\n\n        //is it a good one?\n        std::vector< unsigned int > tmp_inliers;\n\n        for(unsigned int j = 0; j < n; j++) {\n            Eigen::Vector3d point_hom = Eigen::Vector3d(points0[j][0], points0[j][1], 1.0);\n            Eigen::Vector3d pp = tmpH * point_hom;\n            pp /= pp[2];\n\n            double dx = points1[j][0] - pp[0];\n            double dy = points1[j][1] - pp[1];\n            double squared_diff = (dx * dx) + (dy * dy);\n\n            if(squared_diff < threshold) {\n                tmp_inliers.push_back(j);\n            }\n        }\n\n        //get the inliers\n        if(tmp_inliers.size() > inliers.size()) {\n            H = tmpH;\n            inliers.clear();\n            inliers.assign(tmp_inliers.begin(), tmp_inliers.end());\n        }\n    }\n\n    //improve estimate with inliers only\n    if(inliers.size() > 3) {\n        #ifdef PIC_DEBUG\n            printf(\"Better estimate using inliers only.\\n\");\n        #endif\n\n        std::vector< Eigen::Vector2f > sub_points0;\n        std::vector< Eigen::Vector2f > sub_points1;\n\n        for(unsigned int i = 0; i < inliers.size(); i++) {\n            sub_points0.push_back(points0[inliers[i]]);\n            sub_points1.push_back(points1[inliers[i]]);\n        }\n\n        H = estimateHomography(sub_points0, sub_points1);\n    }\n\n    return H;\n}\n    \n/**\n* @brief estimateHomographyRansac computes the homography such that: points1 = H * points0\n* @param points0\n* @param points1\n* @param inliers\n* @param maxIterations\n* @return\n*/\nPIC_INLINE Eigen::Matrix3d estimateHomographyWithNonLinearRefinement(\n                                         std::vector< Eigen::Vector2f > &points0,\n                                         std::vector< Eigen::Vector2f > &points1,\n                                         std::vector< unsigned int > &inliers,\n                                         unsigned int maxIterationsRansac = 10000,\n                                         double thresholdRansac = 2.5,\n                                         unsigned int seedRansac = 1,\n                                         unsigned int maxIterationsNonLinear = 10000,\n                                         float thresholdNonLinear = 1e-5f\n                                                          ) {\n    \n    Eigen::Matrix3d H = estimateHomographyRansac(points0, points1, inliers,\n                                                 maxIterationsRansac, thresholdRansac,\n                                                 seedRansac);\n\n    NelderMeadOptHomography nmoh(points0, points1, inliers);\n    float *H_array = getLinearArrayFromMatrix(H);\n    nmoh.run(H_array, 8, thresholdNonLinear, maxIterationsNonLinear, H_array);\n    H = getMatrix3dFromLinearArray(H_array);\n    return H;\n}\n\n#endif // PIC_DISABLE_EIGEN\n\n} // end namespace pic\n\n#endif // PIC_COMPUTER_VISION_HOMOGRAPHY_HPP\n", "meta": {"hexsha": "2ec98c43c54c5e2c2bf42bcce6718649586dfafd", "size": 7596, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/computer_vision/homography_matrix.hpp", "max_stars_repo_name": "ecarpita93/HPC_projet_1", "max_stars_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "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": "include/computer_vision/homography_matrix.hpp", "max_issues_repo_name": "ecarpita93/HPC_projet_1", "max_issues_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "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": "include/computer_vision/homography_matrix.hpp", "max_forks_repo_name": "ecarpita93/HPC_projet_1", "max_forks_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "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": 29.4418604651, "max_line_length": 92, "alphanum_fraction": 0.5494997367, "num_tokens": 2180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5188492700976429}}
{"text": "/*\n    utils.hpp\n    Desc: Utility functions for mvee library\n    @author Chris Larson, Cornell University\n    @date (2017)\n    @version 1.0\n*/\n\n#include <iostream>\n#include <fstream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <vector>\n#include <string>\n#include <thread>\n#include <future>\n#include <exception>\n#include <Eigen/Dense>\n#include <boost/algorithm/string.hpp>\n\n\n\nint findIdx(Eigen::VectorXd& vec, double val)\n{\n    for (int i=0; i<vec.rows(); i++)\n    {\n        if (vec(i) == val) \n        { \n\t\t\treturn i;\n        }\n    }\n    return -1;\n}\n\n\nstd::vector<double> toStdVec(Eigen::VectorXd& fromX, double (*f)(double))\n{\n\tstd::vector<double> toX(fromX.size(), 0.);\n\tfor (int i=0; i<fromX.size(); i++)\n\t{\n\t\ttoX[i] = (*f)(fromX(i));\n\t}\n\treturn toX;\n}\n\n\nstd::vector<std::vector<double>> toStdMat(Eigen::MatrixXd& fromX, double (*f)(double))\n{\n\tstd::vector<std::vector<double>> \n\ttoX(fromX.rows(), std::vector<double>(fromX.cols(), 0.));\n\tfor (int i=0; i<fromX.rows(); i++)\n\t{\n\t\tfor (int j=0; j<fromX.cols(); j++)\n\t\t{\n\t\t\ttoX[i][j] = (*f)(fromX(i, j));\n\t\t}\n\t}\n\treturn toX;\n}\n\n\nEigen::MatrixXd readCSV(std::string file, char delim) \n{\n\t// Get dimensions for Eigen::MatrixXd constructor\n\tint rows = 0;\n\tint cols = 0;\n\tstd::ifstream in;\n\tin.open(file);\n\tif (in.is_open())\n\t{\n\t\tstd::string s;\n\t\twhile(!in.eof()) \n\t\t{\n\t\t\tgetline(in, s);\n\t\t\tif (s != \"\")\n\t\t\t{\n\t\t\t\trows++;\n\t\t\t\tif (!cols)\n\t\t\t\t{\n\t\t\t\t\tcols = count(s.begin(), s.end(), delim) + 1;\n\t\t\t\t} \n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tthrow std::runtime_error(\"Error: Cannot open \" + file + \".\");\n\t}\n\tin.close();\n\t\n\n\t// Stream file into Eigen::MatrixXd container\n\tstd::string line;\n\tEigen::MatrixXd X = Eigen::MatrixXd(rows, cols);\n\tint row = 0;\n\tint col = 0;\n\tin.open(file);\n\twhile (getline(in, line)) \n\t{\n\t\tchar* ptr = (char*) line.c_str();\n\t\tint len = line.length();\n\t\tcol = 0;\n\t\tchar* start = ptr;\n\t\tfor (int i=0; i<len; i++) \n\t\t{\n\t\t\tif (ptr[i] == delim) \n\t\t\t{\n\t\t\t\tX(row, col++) = atof(start);\n\t\t\t\tstart = ptr + i + 1;\n\t\t\t}\n\t\t}\n\t\tX(row, col) = atof(start);\n\t\trow++;\n\t}\n\tin.close();\n\t\n\treturn X;\n}\n", "meta": {"hexsha": "78f9623bcb961eaa348785264b78c090e93adbb1", "size": 2040, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/utils.hpp", "max_stars_repo_name": "chrislarson1/MVEE", "max_stars_repo_head_hexsha": "4a6aa32f05527dcb01c89a72803f0dcfd078d082", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-09T02:16:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T12:15:23.000Z", "max_issues_repo_path": "include/utils.hpp", "max_issues_repo_name": "chrislarson1/MVEE", "max_issues_repo_head_hexsha": "4a6aa32f05527dcb01c89a72803f0dcfd078d082", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/utils.hpp", "max_forks_repo_name": "chrislarson1/MVEE", "max_forks_repo_head_hexsha": "4a6aa32f05527dcb01c89a72803f0dcfd078d082", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1428571429, "max_line_length": 86, "alphanum_fraction": 0.5666666667, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5188492394475146}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <array>\n#include <string>\n\nconst unsigned NUMS = 256;\n\nint main() {\n    std::vector<int> lengths;\n\n    std::string line;\n    std::getline(std::cin, line);\n\n    std::vector<std::string> words;\n    boost::algorithm::split(\n            words, line, boost::is_any_of(\", \"), boost::algorithm::token_compress_on);\n    for (const auto& w : words) {\n        lengths.push_back(std::stoi(&w[0]));\n    }\n\n    std::array<int, NUMS> nums;\n    for (unsigned i = 0; i < NUMS; ++i) {\n        nums[i] = i;\n    }\n\n    int skip = 0;\n    int pos = 0;\n\n    for (auto w : lengths) {\n        int from = pos, to = (pos + w - 1) % NUMS;\n        for(unsigned i = w/2; i > 0; --i) {\n            std::swap(nums[from], nums[to]);\n            from = ++from % NUMS;\n            if (to == 0) {\n                to = NUMS;\n            }\n            to = --to;\n        }\n        pos = (pos + w + skip++) % NUMS;\n    }\n\n    std::cout << \"0: \" << nums[0] << \"\\n\"\n    << \"1: \" << nums[1] << \"\\n\"\n    << \"multiple: \" << nums[0]*nums[1] << \"\\n\";\n}\n", "meta": {"hexsha": "b6ee2c9e4177c2cbae8a7d10a8ae462282370751", "size": 1174, "ext": "cc", "lang": "C++", "max_stars_repo_path": "puzzle_10_1.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_10_1.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_10_1.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.9591836735, "max_line_length": 86, "alphanum_fraction": 0.4957410562, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5187877002886314}}
{"text": "//\n//  cal_M_global_vec.hpp\n//  hybrid_fem_bie\n//\n//  Created by Max on 2/10/18.\n//\n//\n\n#ifndef cal_M_global_vec_hpp\n#define cal_M_global_vec_hpp\n\n#include <stdio.h>\n#include <Eigen/Eigen>\n#include \"cal_M.hpp\"\n#include \"mapglobal.hpp\"\n\nusing namespace Eigen;\nvoid cal_M_global_vec(MatrixXd &Node, MatrixXd &Element, double density, MatrixXd &index_store, int Ndofn, VectorXd &M_global_vec);\n\n\n#endif /* cal_M_global_vec_hpp */\n", "meta": {"hexsha": "03e74d9c6577a5602f09cb5d8432fbd1eb2e6ef2", "size": 427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/fem/cal_M_global_vec.hpp", "max_stars_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_stars_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T19:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:12:57.000Z", "max_issues_repo_path": "src/fem/cal_M_global_vec.hpp", "max_issues_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_issues_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fem/cal_M_global_vec.hpp", "max_forks_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_forks_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-07T07:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T07:23:58.000Z", "avg_line_length": 19.4090909091, "max_line_length": 131, "alphanum_fraction": 0.7470725995, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5187876990122404}}
{"text": "#include <stan/math/prim/mat.hpp>\n#include <test/unit/math/prim/mat/util.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <gtest/gtest.h>\n#include <stdexcept>\n\nTEST(ProbDistributionsInvWishartRng, rng) {\n  using Eigen::MatrixXd;\n  using stan::math::inv_wishart_rng;\n  boost::random::mt19937 rng;\n\n  MatrixXd omega(3,4);\n  EXPECT_THROW(inv_wishart_rng(3.0, omega, rng), std::invalid_argument);\n\n  MatrixXd sigma(3,3);\n  sigma << 9.0, -3.0, 0.0,\n    -3.0,  4.0, 0.0,\n    2.0, 1.0, 3.0;\n  EXPECT_NO_THROW(inv_wishart_rng(3.0, sigma, rng));\n  EXPECT_THROW(inv_wishart_rng(2, sigma, rng), std::domain_error);\n  EXPECT_THROW(inv_wishart_rng(-1, sigma, rng), std::domain_error);\n}\nTEST(probdistributionsInvWishartRng, symmetry) {\n  using Eigen::MatrixXd;\n  using stan::math::inv_wishart_rng;\n  using stan::test::unit::expect_symmetric;\n  using stan::test::unit::spd_rng;\n\n  boost::random::mt19937 rng;\n  for (int k = 1; k < 20; ++k)\n    for (double nu = k - 0.5; nu < k + 20; ++nu)\n      for (int n = 0; n < 10; ++n)\n        expect_symmetric(inv_wishart_rng(nu, spd_rng(k, rng), rng));\n}\n\nTEST(ProbDistributionsInvWishart, chiSquareGoodnessFitTest) {\n  using stan::math::determinant;\n  using stan::math::inv_wishart_rng;\n  using boost::math::digamma;\n  using boost::math::chi_squared;\n  using Eigen::MatrixXd;\n  using std::log;\n\n  boost::random::mt19937 rng;\n  MatrixXd sigma(3,3);\n  sigma << 9.0, -3.0, 0.0,\n    -3.0,  4.0, 1.0,\n    0.0, 1.0, 3.0;\n  int N = 10000;\n\n  MatrixXd siginv(3,3);\n  siginv = sigma.inverse();\n  int count = 0;\n  double avg = 0;\n  double expect = sigma.rows() * log(2.0) + log(determinant(siginv))\n    + digamma(5.0 / 2.0) + digamma(4.0 / 2.0) + digamma(3.0 / 2.0);\n\n  MatrixXd a(sigma.rows(),sigma.rows());\n  while (count < N) {\n    a = inv_wishart_rng(5.0, sigma, rng);\n    avg += log(determinant(a)) / N;\n    count++;\n   }\n  double chi = (expect - avg) * (expect - avg) / expect;\n  chi_squared mydist(1);\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsInvWishart, SpecialRNGTest) {\n  //When the scale matrix is an identity matrix and df = k + 2\n  //The avg of the samples should also be an identity matrix\n\n  using Eigen::MatrixXd;\n  using stan::math::inv_wishart_rng;\n  \n  boost::random::mt19937 rng(1234U);\n  int N = 1e5;\n  double tol = 0.1;\n  for (int k = 1; k < 5; k++) {\n    MatrixXd sigma = MatrixXd::Identity(k, k);\n    MatrixXd Z = MatrixXd::Zero(k, k);\n    for (int i = 0; i < N; i++)\n      Z += inv_wishart_rng(k + 2, sigma, rng);\n    Z /= N;\n    for (int j = 0; j < k; j++) {\n      for (int i = 0; i < k; i++) {\n        if (j == i)\n          EXPECT_NEAR(Z(i, j), 1.0, tol);\n        else\n          EXPECT_NEAR(Z(i, j), 0.0, tol);\n      }\n    }\n  }\n}\n\n\n", "meta": {"hexsha": "d78d7e89138764d1f59ea23215128ea267386d4e", "size": 2728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/prob/inv_wishart_rng_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/mat/prob/inv_wishart_rng_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/mat/prob/inv_wishart_rng_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1237113402, "max_line_length": 72, "alphanum_fraction": 0.6231671554, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.5187876884497731}}
{"text": "#ifndef PYTHONIC_INCLUDE_NUMPY_FIX_HPP\n#define PYTHONIC_INCLUDE_NUMPY_FIX_HPP\n\n#include \"pythonic/include/utils/functor.hpp\"\n#include \"pythonic/include/types/ndarray.hpp\"\n#include \"pythonic/include/utils/numpy_traits.hpp\"\n#include <boost/simd/function/trunc.hpp>\n\nnamespace pythonic\n{\n\n  namespace numpy\n  {\n    namespace wrapper\n    {\n      template <class T>\n      double fix(T const &v)\n      {\n        return boost::simd::trunc(v);\n      }\n    }\n#define NUMPY_NARY_FUNC_NAME fix\n#define NUMPY_NARY_FUNC_SYM wrapper::fix\n#include \"pythonic/include/types/numpy_nary_expr.hpp\"\n  }\n}\n\n#endif\n", "meta": {"hexsha": "bffd7ba327c1c80b41a213845ea9185059eb5acd", "size": 592, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pythran/pythonic/include/numpy/fix.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": "pythran/pythonic/include/numpy/fix.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": "pythran/pythonic/include/numpy/fix.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": 20.4137931034, "max_line_length": 53, "alphanum_fraction": 0.7297297297, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.5187876871733821}}
{"text": "// This is the main file that generates the animation based on the input motion plan and mesh\n// The executable created is called bbw, which can be run after compiling the project.\n\n#include <igl/boundary_conditions.h>\n#include <igl/readMESH.h>\n#include <igl/opengl/glfw/Viewer.h>\n#include <igl/bbw.h>\n#include <igl/normalize_row_sums.h>\n#include <igl/forward_kinematics.h>\n#include <igl/directed_edge_parents.h>\n\n#include <igl/lbs_matrix.h>\n#include <igl/deform_skeleton.h>\n\n#include <fk.hpp>\n\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n#include <vector>\n#include <algorithm>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nconst Eigen::RowVector3d sea_green(70./255.,252./255.,167./255.);\n\nEigen::MatrixXd V,W,U,C,M, CT, T_mat;\nEigen::MatrixXi T,F,BE;\nEigen::VectorXi P;\n\nstd::vector<std::vector<double>> motion;\n// handles to create skeleton constraints\nstd::vector<int> CE_ind = {633, 39664, 32904, 28716, 5931, 3569, 3632, \n                            32099, 31372, 27125, 7050, 3014, 2040};\n\n// joint mapping to handles (used in FK file)\nstd::vector<std::string> joint_names = {\"FL_HAA\", \"FL_KFE\", \"FL_FOOT\", \"FR_HAA\" ,\"FR_KFE\", \"FR_FOOT\",\n                                        \"HL_HAA\", \"HL_KFE\", \"HL_FOOT\", \"HR_HAA\", \"HR_KFE\", \"HR_FOOT\"};\nint k;\nint selected = 0;\n\nEigen::VectorXd q;\nstd::string rpath = \"../data/solo12.urdf\";\n// change file name to create different animations\nstd::string motion_file = \"../motions/trotting.txt\";\n\nstd::vector<std::vector<double>> read_motion(std::string file_name){\n    fstream newfile;\n    newfile.open(file_name,ios::in); //open a file to perform read operation using file object\n\n    std::vector<std::vector<double>> q_vec;\n\n    if (newfile.is_open()){   //checking whether the file is open\n        string tp;\n        while(getline(newfile, tp)){ //read data from file object and put it into string.\n            vector <double> OutputVertices;\n            istringstream ss(tp);\n            copy(\n            istream_iterator <double> ( ss ),\n            istream_iterator <double> (),\n            back_inserter( OutputVertices )\n            );\n            q_vec.push_back(OutputVertices);\n        }\n        newfile.close(); //close the file object.\n    };\n\n    return q_vec;\n}\n\n\nbool pre_draw(igl::opengl::glfw::Viewer & viewer){\n\n    for (unsigned i = 0; i < motion[k].size(); ++i){\n        if (i < 3 || i > 6){\n            q(i) = motion[k][i];\n        }\n        // hack because of difference in co ordinate frames \n        // of mesh and urdf\n        q(0) = motion[k][1]; q(1) = -motion[k][0];\n    }\n    std::string rpath = \"../data/solo12.urdf\";\n    fk::ForwardKinematics fk(rpath, joint_names, V, CE_ind, BE);\n    MatrixXd CT(CE_ind.size(), V.cols());\n    MatrixXd T_mat(BE.rows()*(V.cols()+1),V.cols());\n\n    fk.compute(q, CT, T_mat);\n    U = M*T_mat;\n    viewer.data().set_vertices(U);\n    // viewer.data().set_edges(CT,BE,sea_green);\n    k = (k < motion.size() - 1 ? k + 1 : 0);\n}\n\nint main(int argc, char *argv[]){\n    \n    k = 0;\n    motion = read_motion(motion_file);\n    std::cout << \"finished reading motion ..\" << std::endl;\n\n    q.resize(19);\n    q <<  0.2, 0.4, 0.24, 0.0, 0.0, -0.707107, 0.707107, \n          0.8, 0.8, -1.6, 0.0, 1.5, -1.6, \n          0.0, -0.8, 1.6, 0.0, -0.8, 1.6;\n\n    BE.resize(12,2);\n    BE << 0,1,\n          1,2, \n          2,3,\n          0,4,\n          4,5,\n          5,6,\n          0,7,\n          7,8,\n          8,9,\n          0,10,\n          10,11,\n          11,12;\n\n    igl::readOFF(\"../data/Dog_v1.off\",V,F);\n    U = V;\n    std::cout << \"finished reading ...\" << std::endl;\n\n    fk::ForwardKinematics fk(rpath, joint_names, V, CE_ind, BE);\n    fk.get_C(C);\n\n    // BBW\n    VectorXi b;\n    MatrixXd bc;\n    igl::boundary_conditions(V,F,C,VectorXi(),BE,MatrixXi(),b,bc);\n    igl::BBWData bbw_data;\n    bbw_data.active_set_params.max_iter = 8;\n    bbw_data.verbosity = 2;\n    if(!igl::bbw(V,F,b,bc,bbw_data,W))\n    {\n        return EXIT_FAILURE;\n    }\n\n    igl::normalize_row_sums(W,W);\n    igl::lbs_matrix(V,W,M);\n\n    igl::opengl::glfw::Viewer viewer;\n    viewer.data().set_mesh(U, F);\n    // comment to create final version of the animation\n    viewer.data().set_data(W.col(selected));\n    viewer.data().set_edges(C,BE,sea_green);\n    viewer.callback_pre_draw = &pre_draw;\n    viewer.data().show_lines = false;\n    viewer.data().show_overlay_depth = false;\n    viewer.data().line_width = 1;\n    viewer.core().animation_max_fps = 60.;\n    viewer.core().is_animating = true;\n    viewer.launch();\n\n    return 0;\n}\n", "meta": {"hexsha": "97cd662db33027ab7467497637ce3e5b3e877da4", "size": 4530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project/demos/bbw.cpp", "max_stars_repo_name": "avadesh02/geometric_modeling", "max_stars_repo_head_hexsha": "dc5d884d1295b0393ea3fae4acff9d973acb3cac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project/demos/bbw.cpp", "max_issues_repo_name": "avadesh02/geometric_modeling", "max_issues_repo_head_hexsha": "dc5d884d1295b0393ea3fae4acff9d973acb3cac", "max_issues_repo_licenses": ["MIT"], "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/demos/bbw.cpp", "max_forks_repo_name": "avadesh02/geometric_modeling", "max_forks_repo_head_hexsha": "dc5d884d1295b0393ea3fae4acff9d973acb3cac", "max_forks_repo_licenses": ["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.8535031847, "max_line_length": 102, "alphanum_fraction": 0.5984547461, "num_tokens": 1370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.518787687173382}}
{"text": "#include \"optimizer.h\"\n\n#include <random>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nusing namespace LiteMath;\n\nstruct OptComplex : public IOptimizer\n{\n  OptComplex(){}\n\n  void         Init(const TriangleMesh& a_mesh, const Img& a_image) override;\n  TriangleMesh Run (size_t a_numIters = 100) override;\n\n  TriangleMesh g_mesh; ///<! global mesh optimized mesh\n  Img          g_targetImage;\n  size_t       g_iter = 0;\n};\n\nIOptimizer* CreateComplexOptimizer() { return new OptComplex; };\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <Eigen/Dense>              // optimization methods\n#define OPTIM_ENABLE_EIGEN_WRAPPERS // optimization methods\n#include \"optim.hpp\"                // optimization methods\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1> EVector;\n\nEVector VectorFromMesh(const TriangleMesh& a_mesh)\n{\n  EVector result( a_mesh.vertices.size()*2 + a_mesh.colors.size()*3 );\n  size_t currPos = 0;\n  for(size_t vertId=0; vertId< a_mesh.vertices.size(); vertId++, currPos+=2)\n  {\n    result[currPos+0] = a_mesh.vertices[vertId].x;\n    result[currPos+1] = a_mesh.vertices[vertId].y;\n  }\n  for(size_t faceId=0; faceId < a_mesh.colors.size(); faceId++, currPos+=3)\n  {\n   result[currPos+0] = a_mesh.colors[faceId].x;\n   result[currPos+1] = a_mesh.colors[faceId].y;\n   result[currPos+2] = a_mesh.colors[faceId].z;\n  }\n  return result;\n}\n\nconstexpr float alphaPos   = 0.1f;\nconstexpr float alphaColor = 0.00001f;\n\nEVector VectorFromDMesh(const DTriangleMesh& a_mesh)\n{\n  EVector result(a_mesh.totalParams());\n  size_t currPos = 0;\n  for(int vertId=0; vertId< a_mesh.numVertices(); vertId++, currPos+=2)\n  {\n    result[currPos+0] = a_mesh.vertices()[vertId].x*alphaPos;\n    result[currPos+1] = a_mesh.vertices()[vertId].y*alphaPos;\n  }\n  for(int faceId=0; faceId < a_mesh.numFaces(); faceId++, currPos+=3)\n  {\n    result[currPos+0] = a_mesh.faceColors()[faceId].x*alphaColor;\n    result[currPos+1] = a_mesh.faceColors()[faceId].y*alphaColor;\n    result[currPos+2] = a_mesh.faceColors()[faceId].z*alphaColor;\n  }\n  return result;\n}\n\nTriangleMesh MeshFromVector(const EVector& a_vec, const TriangleMesh& a_mesh)\n{\n  TriangleMesh result = a_mesh;\n  size_t currPos = 0;\n  for(size_t vertId=0; vertId< result.vertices.size(); vertId++, currPos+=2)\n  {\n    result.vertices[vertId].x = a_vec[currPos+0];\n    result.vertices[vertId].y = a_vec[currPos+1];\n  }\n  for(size_t faceId=0; faceId < result.colors.size(); faceId++, currPos+=3)\n  {\n    result.colors[faceId].x = a_vec[currPos+0];\n    result.colors[faceId].y = a_vec[currPos+1];\n    result.colors[faceId].z = a_vec[currPos+2];\n  }\n  return result;\n}\n\nfloat EvalFunction(const EVector& vals_inp, EVector* grad_out, void* opt_data)\n{\n  OptComplex* pObj = (OptComplex*)opt_data;\n\n  TriangleMesh mesh = MeshFromVector(vals_inp, pObj->g_mesh);\n  \n  constexpr int samples_per_pixel = 4;\n\n  Img img(256, 256);\n  std::mt19937 rng(1234);\n  render(mesh, samples_per_pixel, rng, img);\n  \n  std::stringstream strOut;\n  strOut  << \"rendered_opt/render_\" << std::setfill('0') << std::setw(4) << pObj->g_iter << \".bmp\";\n  save_img(img, strOut.str());\n\n  Img adjoint(img.width, img.height, float3{1, 1, 1});\n  float mse = MSEAndDiff(img, pObj->g_targetImage, adjoint);\n  Img dx(img.width, img.height), dy(img.width, img.height); // actually not needed here\n  \n  DTriangleMesh d_mesh(mesh.vertices.size(), mesh.colors.size());\n  d_render(mesh, adjoint, samples_per_pixel, img.width * img.height , rng, dx, dy, d_mesh);\n  \n  std::cout << \"iter \" << pObj->g_iter << \", error = \" << mse << std::endl;\n  (*grad_out) = VectorFromDMesh(d_mesh); // apply 2.0f*summ(I[x,y] - I_target[x,y]) to get correct gradient for target image\n  pObj->g_iter++;\n  return mse;\n}\n\nvoid OptComplex::Init(const TriangleMesh& a_mesh, const Img& a_image) \n{ \n  g_mesh        = a_mesh; \n  g_targetImage = a_image; \n  g_iter        = 0; \n}\n\nTriangleMesh OptComplex::Run(size_t a_numIters) \n{ \n  optim::algo_settings_t settings;\n  settings.iter_max = a_numIters;\n  settings.gd_settings.method = 0; // 0 for simple gradient descend, 6 ADAM\n  settings.gd_settings.par_step_size      = 1.0; // initialization for ADAM\n  settings.gd_settings.step_decay         = true;\n  settings.gd_settings.step_decay_periods = a_numIters/10;\n  settings.gd_settings.step_decay_val     = 0.75f;\n  settings.opt_error_value                = 20.0f;\n\n  EVector x = VectorFromMesh(g_mesh);\n  bool success = optim::gd(x, &EvalFunction, this, settings);\n  std::cout << \"OptComplex, optimization is FINISHED!\" << std::endl;\n\n  return MeshFromVector(x, g_mesh);\n}", "meta": {"hexsha": "7a909be208f1cd7168077da1025545f0690478d4", "size": 4944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "optimizer_complex.cpp", "max_stars_repo_name": "FROL256/diffrender_tutorials", "max_stars_repo_head_hexsha": "1b5e90f6697b09a1ac0ee750b88e383cb3355012", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optimizer_complex.cpp", "max_issues_repo_name": "FROL256/diffrender_tutorials", "max_issues_repo_head_hexsha": "1b5e90f6697b09a1ac0ee750b88e383cb3355012", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimizer_complex.cpp", "max_forks_repo_name": "FROL256/diffrender_tutorials", "max_forks_repo_head_hexsha": "1b5e90f6697b09a1ac0ee750b88e383cb3355012", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 134, "alphanum_fraction": 0.6314724919, "num_tokens": 1340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5187876831685395}}
{"text": "/*\nCopyright (c) 2015, Sigurd Storve\nAll rights reserved.\n\nLicensed under the BSD license.\n\nRedistribution and use in source and binary forms, with or without\nmodification, 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 <organization> 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\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON 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\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#pragma once\n#include <cmath>\n#include <boost/numeric/ublas/matrix.hpp>\n\n// Create matrix for rotating around the x-axis.\ntemplate <typename T>\nboost::numeric::ublas::matrix<T> rotation_matrix_x(T angle) {\n    boost::numeric::ublas::matrix<T> m(3, 3);\n    m(0,0) = static_cast<T>(1.0); m(0,1) = static_cast<T>(0.0);             m(0,2) = static_cast<T>(0.0);\n    m(1,0) = static_cast<T>(0.0); m(1,1) = static_cast<T>(std::cos(angle)); m(1,2) = static_cast<T>(-std::sin(angle));\n    m(2,0) = static_cast<T>(0.0); m(2,1) = static_cast<T>(std::sin(angle)); m(2,2) = static_cast<T>(std::cos(angle));\n    return m;\n}\n\n// Create matrix for rotating around the y-axis\ntemplate <typename T>\nboost::numeric::ublas::matrix<T> rotation_matrix_y(T angle) {\n    boost::numeric::ublas::matrix<T> m(3, 3);\n    m(0,0) = static_cast<T>(std::cos(angle));  m(0,1) = static_cast<T>(0.0); m(0,2) = static_cast<T>(std::sin(angle));\n    m(1,0) = static_cast<T>(0.0);              m(1,1) = static_cast<T>(1.0); m(1,2) = static_cast<T>(0.0);\n    m(2,0) = static_cast<T>(-std::sin(angle)); m(2,1) = static_cast<T>(0.0); m(2,2) = static_cast<T>(std::cos(angle));\n    return m;\n}\n\n// Create matrix for rotating around the z-axis\ntemplate <typename T>\nboost::numeric::ublas::matrix<T> rotation_matrix_z(T angle) {\n    boost::numeric::ublas::matrix<T> m(3, 3);\n    m(0,0) = static_cast<T>(std::cos(angle));  m(0,1) = static_cast<T>(-std::sin(angle)); m(0,2) = static_cast<T>(0.0);\n    m(1,0) = static_cast<T>(std::sin(angle));  m(1,1) = static_cast<T>(std::cos(angle));  m(1,2) = static_cast<T>(0.0);\n    m(2,0) = static_cast<T>(0.0);              m(2,1) = static_cast<T>(0.0);              m(2,2) = static_cast<T>(1.0);\n    return m;\n}\n\n// Create matrix for rotation along x, y, z, in that order\ntemplate <typename T>\nboost::numeric::ublas::matrix<T> rotation_matrix_xyz(T x_angle, T y_angle, T z_angle) {\n    using namespace boost::numeric::ublas;\n    const auto rot_x = rotation_matrix_x<double>(x_angle);\n    const auto rot_y = rotation_matrix_y<double>(y_angle);\n    const auto rot_z = rotation_matrix_z<double>(z_angle);\n    boost::numeric::ublas::matrix<T> temp = prod(rot_z, rot_y);\n    return prod(temp, rot_x);\n}\n\n// Return unit vector along the x-axis\ntemplate <typename T>\nboost::numeric::ublas::vector<T> unit_x() {\n    boost::numeric::ublas::vector<T> u(3);\n    u(0) = static_cast<T>(1.0); u(1) = static_cast<T>(0.0); u(2) = static_cast<T>(0.0);\n    return u;\n}\n\n// Return unit vector along the y-axis\ntemplate <typename T>\nboost::numeric::ublas::vector<T> unit_y() {\n    boost::numeric::ublas::vector<T> u(3);\n    u(0) = static_cast<T>(0.0); u(1) = static_cast<T>(1.0); u(2) = static_cast<T>(0.0);\n    return u;\n}\n\n// Return unit vector along the z-axis\ntemplate <typename T>\nboost::numeric::ublas::vector<T> unit_z() {\n    boost::numeric::ublas::vector<T> u(3);\n    u(0) = static_cast<T>(0.0); u(1) = static_cast<T>(0.0); u(2) = static_cast<T>(1.0);\n    return u;\n}", "meta": {"hexsha": "06bb1cee69fc88fffac16c349c64d16df78d31e7", "size": 4490, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/rotation3d.hpp", "max_stars_repo_name": "sigurdstorve/OpenBCSim", "max_stars_repo_head_hexsha": "500025c1b63bc6ff083cbd649771d1b98e3f7314", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2016-05-27T13:09:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T07:08:47.000Z", "max_issues_repo_path": "src/utils/rotation3d.hpp", "max_issues_repo_name": "rojsc/OpenBCSim", "max_issues_repo_head_hexsha": "53773172974ad42fc3faceb7b36611573abf1c4c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 63.0, "max_issues_repo_issues_event_min_datetime": "2015-09-10T11:22:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-21T14:52:39.000Z", "max_forks_repo_path": "src/utils/rotation3d.hpp", "max_forks_repo_name": "rojsc/OpenBCSim", "max_forks_repo_head_hexsha": "53773172974ad42fc3faceb7b36611573abf1c4c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T14:52:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T15:52:28.000Z", "avg_line_length": 46.2886597938, "max_line_length": 119, "alphanum_fraction": 0.6824053452, "num_tokens": 1318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5187876818921484}}
{"text": "/*******************************************************************************\n * Copyright 2013-2014 Sebastian Niemann <niemann@sra.uni-hannover.de>.\n * \n * Licensed under the MIT License (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://opensource.org/licenses/MIT\n * \n * Developers:\n *   Sebastian Niemann - Lead developer\n *   Daniel Kiechle - Unit testing\n ******************************************************************************/\n#include <Expected.hpp>\nusing armadilloJava::Expected;\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <utility>\nusing std::pair;\n\n#include <armadillo>\nusing arma::Col;\nusing arma::Mat;\nusing arma::uword;\nusing arma::cross;\nusing arma::join_rows;\nusing arma::join_horiz;\nusing arma::join_cols;\nusing arma::join_vert;\nusing arma::kron;\n\n#include <InputClass.hpp>\nusing armadilloJava::InputClass;\n\n#include <Input.hpp>\nusing armadilloJava::Input;\n\nnamespace armadilloJava {\n  class ExpectedGenColVecGenMat : public Expected {\n    public:\n      ExpectedGenColVecGenMat() {\n        cout << \"Compute ExpectedGenColVecGenMat(): \" << endl;\n\n        vector<vector<pair<string, void*>>> inputs = Input::getTestParameters({\n          InputClass::GenColVec,\n          InputClass::GenMat\n        });\n\n        for (vector<pair<string, void*>> input : inputs) {\n          _fileSuffix = \"\";\n\n          int n = 0;\n          for (pair<string, void*> value : input) {\n            switch (n) {\n              case 0:\n                _fileSuffix += value.first;\n                _genColVec = *static_cast<Col<double>*>(value.second);\n                break;\n              case 1:\n                _fileSuffix += \",\" + value.first;\n                _genMat = *static_cast<Mat<double>*>(value.second);\n                break;\n            }\n            ++n;\n          }\n\n          cout << \"Using input: \" << _fileSuffix << endl;\n\n          expectedArmaCross();\n          expectedArmaJoin_rows();\n          expectedArmaJoin_horiz();\n          expectedArmaJoin_cols();\n          expectedArmaJoin_vert();\n          expectedArmaKron();\n          expectedColPlus();\n          expectedColMinus();\n          expectedColTimes();\n          expectedColElemTimes();\n          expectedColElemDivide();\n          expectedColEquals();\n          expectedColNonEquals();\n          expectedColGreaterThan();\n          expectedColLessThan();\n          expectedColStrictGreaterThan();\n          expectedColStrictLessThan();\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n    protected:\n      Col<double> _genColVec;\n      Mat<double> _genMat;\n\n      void expectedArmaCross() {\n        cout << \"- Compute expectedArmaCross() ... \";\n\n        Col<double> tempGenColVec = Col<double>(_genColVec);\n        tempGenColVec.resize(3);\n        Mat<double> tempGenMat = Mat<double>(_genMat);\n        tempGenMat.resize(3, 1);\n\n        save<double>(\"Arma.cross\", cross(tempGenColVec, tempGenMat));\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaJoin_rows() {\n        if(_genColVec.n_rows != _genMat.n_rows) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaJoin_rows() ... \";\n        save<double>(\"Arma.join_rows\", join_rows(_genColVec, _genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaJoin_horiz() {\n        if(_genColVec.n_rows != _genMat.n_rows) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaJoin_horiz() ... \";\n        save<double>(\"Arma.join_horiz\", join_horiz(_genColVec, _genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaJoin_cols() {\n        if(_genColVec.n_cols != _genMat.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaJoin_cols() ... \";\n        save<double>(\"Arma.join_cols\", join_cols(_genColVec, _genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaJoin_vert() {\n        if(_genColVec.n_cols != _genMat.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaJoin_vert() ... \";\n        save<double>(\"Arma.join_vert\", join_cols(_genColVec, _genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaKron() {\n        cout << \"- Compute expectedArmaKron() ... \";\n        save<double>(\"Arma.kron\", kron(_genColVec, _genMat));\n        cout << \"done.\" << endl;\n      }\n\t  \n      void expectedColPlus() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedColPlus() ... \";\n        save<double>(\"Col.plus\", _genColVec + _genMat);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColMinus() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedColMinus() ... \";\n        save<double>(\"Col.minus\", _genColVec - _genMat);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColTimes() {\n        if(_genMat.n_rows != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedColTimes() ... \";\n        save<double>(\"Col.times\", _genColVec * _genMat);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColElemTimes() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedColElemTimes() ... \";\n        save<double>(\"Col.elemTimes\", _genColVec % _genMat);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColElemDivide() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedColElemDivide() ... \";\n        save<double>(\"Col.elemDivide\", _genColVec / _genMat);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColEquals() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedColEquals() ... \";\n\n        Col<uword> expected = _genColVec == _genMat;\n        save<uword>(\"Col.equals\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColNonEquals() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedColVecNonEquals() ... \";\n\n        Col<uword> expected = _genColVec != _genMat;\n        save<uword>(\"Col.nonEquals\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColGreaterThan() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedColGreaterThan() ... \";\n\n        Col<uword> expected = _genColVec >= _genMat;\n        save<uword>(\"Col.greaterThan\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColLessThan() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedColLessThan() ... \";\n\n        Col<uword> expected = _genColVec <= _genMat;\n        save<uword>(\"Col.lessThan\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColStrictGreaterThan() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedColStrictGreaterThan() ... \";\n\n        Col<uword> expected = _genColVec > _genMat;\n        save<uword>(\"Col.strictGreaterThan\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColStrictLessThan() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedColElemDivide() ... \";\n\n        Col<uword> expected = _genColVec < _genMat;\n        save<uword>(\"Col.strictLessThan\", expected);\n\n        cout << \"done.\" << endl;\n      }\n  };\n}\n", "meta": {"hexsha": "ba7be8483fa6c63d29c2704adf7b555cba783ae6", "size": 8454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/cpp/src/ExpectedGenColVecGenMat.cpp", "max_stars_repo_name": "SebastianNiemann/ArmadilloJava", "max_stars_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T02:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-15T07:43:53.000Z", "max_issues_repo_path": "src/test/cpp/src/ExpectedGenColVecGenMat.cpp", "max_issues_repo_name": "sebiniemann/ArmadilloJava", "max_issues_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2019-10-20T21:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T21:53:47.000Z", "max_forks_repo_path": "src/test/cpp/src/ExpectedGenColVecGenMat.cpp", "max_forks_repo_name": "sebiniemann/ArmadilloJava", "max_forks_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T17:01:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T18:45:14.000Z", "avg_line_length": 25.9325153374, "max_line_length": 80, "alphanum_fraction": 0.5327655548, "num_tokens": 2053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5187876818921484}}
{"text": "#define DEBUG 1\n/**\n * File    : F.cpp\n * Author  : Kazune Takahashi\n * Created : 2020/7/1 1:44:15\n * Powered by Visual Studio Code\n */\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n// ----- boost -----\n#include <boost/integer/common_factor_rt.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/rational.hpp>\n// ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::integer::gcd; // for C++14 or for cpp_int\nusing boost::integer::lcm; // for C++14 or for cpp_int\nusing boost::multiprecision::cpp_int;\nusing ll = unsigned long long;\nusing ld = long double;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n// ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n// constexpr ll MOD{998'244'353LL}; // be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nbool ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\ntemplate <typename T>\nbool ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\n// ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(Mint const &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(Mint const &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(Mint const &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator/=(Mint const &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }\n  bool operator<(Mint const &a) const { return x < a.x; }\n  bool operator<=(Mint const &a) const { return x <= a.x; }\n  bool operator>(Mint const &a) const { return x > a.x; }\n  bool operator>=(Mint const &a) const { return x >= a.x; }\n  bool operator==(Mint const &a) const { return x == a.x; }\n  bool operator!=(Mint const &a) const { return !(*this == a); }\n  Mint power(ll N) const\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N / 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }\ntemplate <ll MOD>\nMint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }\n// ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i{2LL}; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i{1LL}; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\n// ----- for C++17 -----\ntemplate <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>\nsize_t popcount(T x) { return bitset<64>(x).count(); }\nsize_t popcount(string const &S) { return bitset<200010>{S}.count(); }\n// ----- Infty -----\ntemplate <typename T>\nconstexpr T Infty() { return numeric_limits<T>::max(); }\ntemplate <typename T>\nconstexpr T mInfty() { return numeric_limits<T>::min(); }\n// ----- frequently used constexpr -----\n// constexpr double epsilon{1e-10};\n// constexpr ll infty{1'000'000'000'000'010LL}; // or\n// constexpr int infty{1'000'000'010};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"-1\" << endl;\n  exit(0);\n}\n\n// ----- Solve -----\n\ntemplate <typename T>\nostream &operator<<(ostream &os, vector<vector<T>> const &v)\n{\n  int n = v.size();\n  for (auto i{0}; i < n; ++i)\n  {\n    for (auto j{0}; j < n; ++j)\n    {\n      os << v[i][j];\n      if (j < n - 1)\n      {\n        os << \" \";\n      }\n      else\n      {\n        os << endl;\n      }\n    }\n  }\n  return os;\n}\n\nclass Solve\n{\n  int n;\n  vector<bool> s, t, u, v;\n  vector<vector<int>> res;\n\npublic:\n  Solve(int n, vector<bool> s, vector<bool> t, vector<bool> u, vector<bool> v) : n{n}, s{s}, t{t}, u{u}, v{v}, res(n, vector<int>(n, -1))\n  {\n#if DEBUG == 1\n    cerr << \"problem: \" << endl;\n    for (auto i{0}; i < n; ++i)\n    {\n      cerr << \"s[\" << i << \"] = \" << s[i] << endl;\n    }\n    for (auto i{0}; i < n; ++i)\n    {\n      cerr << \"t[\" << i << \"] = \" << t[i] << endl;\n    }\n    for (auto i{0}; i < n; ++i)\n    {\n      cerr << \"u[\" << i << \"] = \" << u[i] << endl;\n    }\n    for (auto i{0}; i < n; ++i)\n    {\n      cerr << \"v[\" << i << \"] = \" << v[i] << endl;\n    }\n#endif\n  }\n\n  vector<vector<int>> answer()\n  {\n    prepare();\n    fill_zero();\n#if DEBUG == 1\n    cerr << res;\n#endif\n    fixed_up();\n#if DEBUG == 1\n    cerr << res;\n#endif\n    final_check();\n    return res;\n  }\n\nprivate:\n  void ch(int i, int j, int v)\n  {\n    if (res[i][j] == -1)\n    {\n      res[i][j] = v;\n    }\n    else if (res[i][j] != v)\n    {\n      No();\n    }\n  }\n\n  void final_check()\n  {\n    for (auto i{0}; i < n; ++i)\n    {\n      int tmp{res[i][0]};\n      if (!s[i])\n      {\n        for (auto j{0}; j < n; ++j)\n        {\n          tmp &= res[i][j];\n        }\n      }\n      else\n      {\n        for (auto j{0}; j < n; ++j)\n        {\n          tmp |= res[i][j];\n        }\n      }\n      if (tmp != u[i])\n      {\n        No();\n      }\n    }\n    for (auto j{0}; j < n; ++j)\n    {\n      int tmp{res[0][j]};\n      if (!t[j])\n      {\n        for (auto i{0}; i < n; ++i)\n        {\n          tmp &= res[i][j];\n        }\n      }\n      else\n      {\n        for (auto i{0}; i < n; ++i)\n        {\n          tmp |= res[i][j];\n        }\n      }\n      if (tmp != v[j])\n      {\n        No();\n      }\n    }\n  }\n\n  void fixed_up()\n  {\n    for (auto i{0}; i < n; ++i)\n    {\n      if (!(s[i] && (u[i] & 1)))\n      {\n        continue;\n      }\n      bool ok{false};\n      for (auto j{0}; j < n; ++j)\n      {\n        if (res[i][j] == 1)\n        {\n          ok = true;\n          break;\n        }\n      }\n      if (ok)\n      {\n        continue;\n      }\n      for (auto j{0}; j < n; ++j)\n      {\n        if (!(!t[j] && !(v[j] & 1)))\n        {\n          continue;\n        }\n        int cnt{0};\n        for (auto k{0}; k < n; ++k)\n        {\n          if (res[k][j] == 0)\n          {\n            ++cnt;\n          }\n        }\n        if (cnt <= 1)\n        {\n          continue;\n        }\n        res[i][j] = 1;\n        ok = true;\n        break;\n      }\n      if (!ok)\n      {\n        No();\n      }\n    }\n    for (auto j{0}; j < n; ++j)\n    {\n      if (!(t[j] && (v[j] & 1)))\n      {\n        continue;\n      }\n#if DEBUG == 1\n      cerr << \"j = \" << j << endl;\n#endif\n      bool ok{false};\n      for (auto i{0}; i < n; ++i)\n      {\n        if (res[i][j] == 1)\n        {\n          ok = true;\n          break;\n        }\n      }\n      if (ok)\n      {\n        continue;\n      }\n#if DEBUG == 1\n      cerr << \"j = \" << j << endl;\n#endif\n      for (auto i{0}; i < n; ++i)\n      {\n        if (!(!s[i] && !(u[i] & 1)))\n        {\n          continue;\n        }\n#if DEBUG == 1\n        cerr << \"i = \" << i << endl;\n#endif\n        int cnt{0};\n        for (auto k{0}; k < n; ++k)\n        {\n          if (res[i][k] == 0)\n          {\n            ++cnt;\n          }\n        }\n        if (cnt <= 1)\n        {\n          continue;\n        }\n        res[i][j] = 1;\n        ok = true;\n        break;\n      }\n      if (!ok)\n      {\n        No();\n      }\n    }\n  }\n\n  void fill_zero()\n  {\n    for (auto i{0}; i < n; ++i)\n    {\n      for (auto j{0}; j < n; ++j)\n      {\n        if (res[i][j] == -1)\n        {\n          res[i][j] = 0;\n        }\n      }\n    }\n  }\n\n  void prepare()\n  {\n    for (auto i{0}; i < n; ++i)\n    {\n      if (!s[i] && u[i])\n      {\n        for (auto j{0}; j < n; ++j)\n        {\n          ch(i, j, 1);\n        }\n      }\n      else if (s[i] && !u[i])\n      {\n        for (auto j{0}; j < n; ++j)\n        {\n          ch(i, j, 0);\n        }\n      }\n    }\n    for (auto i{0}; i < n; ++i)\n    {\n      if (!t[i] && v[i])\n      {\n        for (auto j{0}; j < n; ++j)\n        {\n          ch(j, i, 1);\n        }\n      }\n      else if (t[i] && !v[i])\n      {\n        for (auto j{0}; j < n; ++j)\n        {\n          ch(j, i, 0);\n        }\n      }\n    }\n    for (auto i{0}; i < n; ++i)\n    {\n      for (auto j{0}; j < n; ++j)\n      {\n        if (res[i][j] == -1)\n        {\n          if (u[i] && v[j])\n          {\n            res[i][j] = 1;\n          }\n          else if (!u[i] && !v[j])\n          {\n            res[i][j] = 0;\n          }\n        }\n      }\n    }\n  }\n};\n\n// ----- main() -----\n\nconstexpr int C{64};\n\nint main()\n{\n  int n;\n  cin >> n;\n  vector<bool> s(n), t(n);\n  vector<ll> us(n), vs(n);\n  for (auto i{0}; i < n; ++i)\n  {\n    int x;\n    cin >> x;\n    s[i] = x;\n  }\n  for (auto i{0}; i < n; ++i)\n  {\n    int x;\n    cin >> x;\n    t[i] = x;\n  }\n  for (auto i{0}; i < n; ++i)\n  {\n    cin >> us[i];\n  }\n  for (auto i{0}; i < n; ++i)\n  {\n    cin >> vs[i];\n  }\n  vector<vector<ll>> ans(n, vector<ll>(n, 0));\n  for (auto k{0}; k < C; ++k)\n  {\n    vector<bool> u(n), v(n);\n    for (auto i{0}; i < n; ++i)\n    {\n      u[i] = (us[i] >> k & 1);\n    }\n    for (auto i{0}; i < n; ++i)\n    {\n      v[i] = (vs[i] >> k & 1);\n    }\n    Solve solve(n, s, t, u, v);\n    auto res{solve.answer()};\n    for (auto i{0}; i < n; ++i)\n    {\n      for (auto j{0}; j < n; ++j)\n      {\n        ans[i][j] |= static_cast<ll>(res[i][j]) << k;\n      }\n    }\n#if DEBUG == 1\n    cerr << ans;\n#endif\n    for (auto i{0}; i < n; ++i)\n    {\n      auto tmp{ans[i][0]};\n      if (!s[i])\n      {\n        for (auto j{0}; j < n; ++j)\n        {\n          tmp &= ans[i][j];\n        }\n      }\n      else\n      {\n        for (auto j{0}; j < n; ++j)\n        {\n          tmp |= ans[i][j];\n        }\n      }\n      auto cut{us[i]};\n      if (k < C - 1)\n      {\n        cut &= (1ULL << (k + 1)) - 1;\n      }\n      if (tmp != cut)\n      {\n#if DEBUG == 1\n        cerr << \"failed: k = \" << k << \", i = \" << i << endl;\n#endif\n        No();\n      }\n    }\n    for (auto j{0}; j < n; ++j)\n    {\n      auto tmp{ans[0][j]};\n      if (!t[j])\n      {\n        for (auto i{0}; i < n; ++i)\n        {\n          tmp &= ans[i][j];\n        }\n      }\n      else\n      {\n        for (auto i{0}; i < n; ++i)\n        {\n          tmp |= ans[i][j];\n        }\n      }\n      auto cut{vs[j]};\n      if (k < C - 1)\n      {\n        cut &= (1ULL << (k + 1)) - 1;\n      }\n      if (tmp != cut)\n      {\n#if DEBUG == 1\n        cerr << \"failed: k = \" << k << \", j = \" << j << endl;\n#endif\n        No();\n      }\n    }\n  }\n  for (auto i{0}; i < n; ++i)\n  {\n    for (auto j{0}; j < n; ++j)\n    {\n      cout << ans[i][j];\n      if (j < n - 1)\n      {\n        cout << \" \";\n      }\n      else\n      {\n        cout << endl;\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "6d26fe3d47e0b722e884d10d9d0f5c7026cd518b", "size": 12721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/0701_ABC164/F.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2020/0701_ABC164/F.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/0701_ABC164/F.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 19.4213740458, "max_line_length": 137, "alphanum_fraction": 0.422372455, "num_tokens": 4215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6224593452091673, "lm_q1q2_score": 0.5187106767914185}}
{"text": "/*\n main.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/format.hpp>\n#include <boost/numeric/ublas/io.hpp>\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/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/range/algorithm.hpp>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\n#include \"correlation.hxx\"\n#include \"neighbour.hxx\"\n#include \"supercell.hxx\"\n#include \"utils.hxx\"\n\nnamespace ublas = boost::numeric::ublas;\n\nint main(void) {\n\n  unsigned long nbas = 2;\n  ublas::matrix<double> plat(3,3);\n  ublas::matrix<double> basis(nbas,3);\n  double rmax = 2.0;\n\n  /* Set Basis Vectors */\n  double isqrt2 = 1/std::sqrt(2);\n  double isqrt3 = 1/std::sqrt(3);\n  double isqrt6 = 1/std::sqrt(6);\n\n  basis(0,0) =      0.0; basis(0,1) =          0.0; basis(0,2) =            0.0;\n  basis(1,0) =   isqrt6; basis(1,1) =       isqrt2; basis(1,2) =         isqrt3;\n\n  plat(0,0)  = 2*isqrt6; plat(0,1)  =          0.0; plat(0,2)  = std::sqrt(3)/6;\n  plat(1,0)  =      0.0; plat(1,1)  = std::sqrt(2); plat(1,2)  =            0.0;\n  plat(2,0)  =      0.0; plat(2,1)  =          0.0; plat(2,2)  = std::sqrt(3)/2;\n\n  /* Primitive I/O */\n  std::cout << boost::format(\"Primitive Number of Atoms : %8d\\n\") % nbas;\n  std::cout << boost::format(\"Pair Cut Off Radius       : %16.7f\\n\") % rmax;\n  std::cout << boost::format(\"Primitive Lattice Vectors : %16.7f %16.7f %16.7f\\n\")\n    % plat(0,0) % plat(0,1) % plat(0,2);\n  std::cout << boost::format(\"                            %16.7f %16.7f %16.7f\\n\")\n    % plat(1,0) % plat(1,1) % plat(1,2);\n  std::cout << boost::format(\"                            %16.7f %16.7f %16.7f\\n\")\n    % plat(2,0) % plat(2,1) % plat(2,2);\n\n  for (auto i = 0; i < nbas; i++) {\n    ublas::matrix_row<ublas::matrix<double>> b(basis,i);\n    if (i == 0) {\n      std::cout << boost::format(\"Primitive Basis Vectors   : %16.7f %16.7f %16.7f\\n\")\n\t% b(0) % b(1) % b(2);\n    } else {\n      std::cout << boost::format(\"                          : %16.7f %16.7f %16.7f\\n\")\n        % b(0) % b(1) % b(2);\n    }\n  }\n  \n  /* Supercell Creation */\n  ublas::vector<long> sext(3);\n  sext(0) = 100; sext(1) = 60; sext(2) = 3;\n\n  double concentration = 0.05;\n  \n  Supercell supercell = Supercell(sext,nbas,plat,basis,concentration);\n\n  /* Supercell Inverse */\n  ublas::matrix<double> isplat = inv3(supercell.lattice_vectors);\n  ublas::matrix<double> xsbasis(supercell.number_of_atoms,3);\n  for (auto i = 0; i < supercell.number_of_atoms; i++) {\n    ublas::matrix_row<ublas::matrix<double>> b(supercell.basis_vectors,i);\n    auto xb = prod(b,isplat);\n    for (auto a = 0; a < 3; a++) {\n      xsbasis(i,a) = xb(a);\n    }\n  }\n  \n  /* Supercell I/O */\n  std::cout << boost::format(\"Supercell Number of Atoms : %8d\\n\")\n    % supercell.number_of_atoms;\n    \n  std::cout << boost::format(\"Supercell Lattice Vectors : %16.7f %16.7f %16.7f\\n\")\n    % supercell.lattice_vectors(0,0)\n    % supercell.lattice_vectors(0,1)\n    % supercell.lattice_vectors(0,2);\n  std::cout << boost::format(\"                            %16.7f %16.7f %16.7f\\n\")\n    % supercell.lattice_vectors(1,0)\n    % supercell.lattice_vectors(1,1)\n    % supercell.lattice_vectors(1,2);\n  std::cout << boost::format(\"                            %16.7f %16.7f %16.7f\\n\")\n    % supercell.lattice_vectors(2,0)\n    % supercell.lattice_vectors(2,1)\n    % supercell.lattice_vectors(2,2);\n  \n  /* Random Number Generator */\n  boost::mt19937 mt(time(0));\n  boost::uniform_int<> uni_dist;\n  boost::variate_generator<boost::mt19937&,boost::uniform_int<>>\n    generator(mt,uni_dist);\n\n  long nitf = 100000;\n  double term = 0.0001;\n\n  std::cout << boost::format(\"Number of Iterations      : %8d\\n\") % nitf;\n  std::cout << boost::format(\"Concentration             : %16.7f\\n\") % concentration;\n  std::cout << boost::format(\"Perfect Correlation       : %16.7f\\n\")\n    % ((2*concentration-1)*(2*concentration-1)); \n  std::cout << boost::format(\"SQS Accept Tolerance      : %16.7f\\n\\n\") % term;\n\n  Neighbour neighbour = Neighbour(supercell.number_of_atoms,\n\t\t\t\t  supercell.lattice_vectors,\n\t\t\t\t  supercell.basis_vectors);\n  \n  neighbour.SetInverseLattice(isplat,xsbasis);\n  neighbour.GetNhbrList(rmax);\n\n  double best = 1.0;\n  long snum = 0;\n  long bnum = 0;\n  \n  for (long n = 0; n < nitf; n++) { \n    \n    boost::range::random_shuffle(supercell.pointers,generator);\n        \n    /* Correlation Function Calculation */\n    Correlation correlation = Correlation();\n    correlation.Calculate(neighbour,supercell);\n    double result = correlation.ErrorFunction(concentration);\n\n    bool bestq = (result < best);\n    bool writeq = (result < term);\n    if (bestq) {\n      best = result;\n      bnum = snum;\n    }\n    \n    std::cout << boost::format(\"Iteration                 : %8d\\n\") % (n+1);\n    std::cout << boost::format(\"Mean Error                : %16.7f\\n\")\n      % result;\n    std::cout << boost::format(\"Least Error      %8d : %16.7f\\n\") % bnum % best;\n    if (writeq) {\n      snum++;\n      std::cout << \"Accept\\n\";\n    } else {\n      std::cout << \"Reject\\n\";\n    }\n    \n    for (auto i = 0; i < correlation.number; i++) {\n      std::cout << boost::format(\"  %16.7f  %5d  %16.7f  %16.7f\\n\")\n\t% correlation.pair_clusters[i]\n\t% (correlation.pair_count[i]/supercell.number_of_atoms)\n\t% correlation.pair_correlations[i]\n\t% correlation.errors[i];\n    }\n    std::cout << std::endl;\n\n    /* File Writing */\n    if (writeq) {\n      std::ofstream outfile;\n      boost::format fmt = boost::format(\"sqs.%d.out\") % snum;\n      outfile.open(fmt.str());\n      outfile << boost::format(\"# special quasirandom structure\\n\");\n      for (auto i = 0; i < supercell.number_of_atoms; i++) {\n\tlong ptr = 1;\n\tif (supercell.pointers(i) == -1) ptr = 2;\n\toutfile << boost::format(\"%8d %22.15f %22.15f %22.15f\\n\")\n\t  % ptr\n\t  % supercell.basis_vectors(i,0)\n\t  % supercell.basis_vectors(i,1)\n\t  % supercell.basis_vectors(i,2);\n      }\n      outfile.close();\n    }\n    \n  }\n  \n  return 0;\n\n}\n", "meta": {"hexsha": "8f07e41ac5e4740a1da66f958718015600d1184c", "size": 6270, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/main.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/main.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/main.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": 32.65625, "max_line_length": 86, "alphanum_fraction": 0.5918660287, "num_tokens": 2065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5187106702719783}}
{"text": "#include <algorithm>\n#include <vector>\n#include <fstream>\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Surface_mesh.h>\n\n#include <CGAL/box_intersection_d.h>\n#include <CGAL/Timer.h>\n\n#include <boost/bind.hpp>\n#include <boost/functional/value_factory.hpp>\n#include <boost/range/algorithm/transform.hpp>\n\n#include <algorithm>\n#include <vector>\n#include <fstream>\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel K;\n\ntypedef K::Triangle_3 Triangle_3;\ntypedef K::Point_3 Point_3;\ntypedef CGAL::Surface_mesh<K::Point_3> Mesh;\ntypedef CGAL::Bbox_3 Bbox_3;\ntypedef CGAL::Timer Timer;\n\ntypedef Mesh::Face_index Face_descriptor;\ntypedef Mesh::Halfedge_index Halfedge_descriptor;\n\n/// small helper to extract a triangle from a face\nTriangle_3 triangle(const Mesh& sm, Face_descriptor f)\n{\n  Halfedge_descriptor hf = sm.halfedge(f);\n  Point_3 a = sm.point(sm.target(hf));\n  hf = sm.next(hf);\n  Point_3 b = sm.point(sm.target(hf));\n  hf = sm.next(hf);\n  Point_3 c = sm.point(sm.target(hf));\n  hf = sm.next(hf);\n  return Triangle_3(a, b, c);\n}\n\nclass Box\n  : public CGAL::Box_intersection_d::Box_d<double, 3,  CGAL::Box_intersection_d::ID_NONE> {\nprivate:\n  typedef CGAL::Box_intersection_d::Box_d<\n    double, 3,  CGAL::Box_intersection_d::ID_NONE> Base;\n  Face_descriptor fd;\npublic:\n  typedef double                                   NT;\n  typedef std::size_t                              ID;\n\n  Box(Face_descriptor f, const Mesh& sm) : Base(triangle(sm, f).bbox()), fd(f) {}\n  Box(const Bbox_3& b, Face_descriptor fd) : Base(b), fd(fd) {}\n  Face_descriptor f() const { return fd; }\n  ID  id() const { return static_cast<ID>(fd); }\n};\n\nstruct Callback {\n  Callback(const Mesh& P, const Mesh& Q, unsigned int& i)\n    : P(P), Q(Q), count(i)\n  {}\n\n  void operator()(const Box* bp, const Box* bq) {\n    Face_descriptor fp = bp->f();\n    Triangle_3 tp = triangle(P, fp);\n\n    Face_descriptor fq = bq->f();\n    Triangle_3 tq = triangle(Q, fq);\n\n    if(do_intersect( tp, tq)) {\n      ++(count);\n    }\n  }\n\n  const Mesh& P;\n  const Mesh& Q;\n  unsigned int& count;\n};\n\nconst Box*\naddress_of_box(const Box& b)\n{\n  return &b;\n}\n\nunsigned int intersect(const Mesh& P, const Mesh& Q) {\n  std::vector<Box> P_boxes, Q_boxes;\n  std::vector<const Box*> P_box_ptr, Q_box_ptr;\n  P_boxes.reserve(P.number_of_faces());\n  P_box_ptr.reserve(P.number_of_faces());\n  Q_boxes.reserve(Q.number_of_faces());\n  Q_box_ptr.reserve(Q.number_of_faces());\n\n  // build boxes and pointers to boxes\n  for(auto f : P.faces())\n    P_boxes.push_back( Box(f, P) );\n  std::transform(P_boxes.begin(), P_boxes.end(), std::back_inserter(P_box_ptr),\n                 &address_of_box);\n  for(auto f : Q.faces())\n    Q_boxes.push_back( Box(f, Q) );\n  std::transform(Q_boxes.begin(), Q_boxes.end(), std::back_inserter(Q_box_ptr),\n                 &address_of_box);\n\n  unsigned int i = 0;\n  Callback c(P,Q, i);\n  CGAL::box_intersection_d(P_box_ptr.begin(), P_box_ptr.end(),\n                           Q_box_ptr.begin(), Q_box_ptr.end(),\n                           c);\n  return i;\n}\n\nint main(int argc, char* argv[])\n{\n  if(argc < 3)\n  {\n    std::cerr << \"Usage: do_intersect <mesh_1.off> <mesh_2.off>\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  std::cout.precision(17);\n\n  Mesh P, Q;\n  if(!CGAL::read_polygon_mesh(argv[1], P) || !CGAL::read_polygon_mesh(argv[2], Q))\n  {\n    std::cerr << \"Invalid input files.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  Timer timer;\n  timer.start();\n  unsigned int num_intersections = intersect(P,Q);\n  timer.stop();\n  std::cout << \"Counted \" << num_intersections << \" in \"\n            << timer.time() << \" seconds.\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "33ac1ef7dadc17f10eeb70d296ea29acfbdcf563", "size": 3668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh/examples/Surface_mesh/sm_do_intersect.cpp", "max_stars_repo_name": "yemaedahrav/cgal", "max_stars_repo_head_hexsha": "ef771049b173007f2c566375bbd85a691adcee17", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-22T16:58:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T16:58:57.000Z", "max_issues_repo_path": "Surface_mesh/examples/Surface_mesh/sm_do_intersect.cpp", "max_issues_repo_name": "yemaedahrav/cgal", "max_issues_repo_head_hexsha": "ef771049b173007f2c566375bbd85a691adcee17", "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": "Surface_mesh/examples/Surface_mesh/sm_do_intersect.cpp", "max_forks_repo_name": "yemaedahrav/cgal", "max_forks_repo_head_hexsha": "ef771049b173007f2c566375bbd85a691adcee17", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-05T04:18:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:18:59.000Z", "avg_line_length": 26.3884892086, "max_line_length": 91, "alphanum_fraction": 0.6507633588, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5187106702719781}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu> Licensed\n * under the MIT license. See the license file LICENSE.\n */\n#pragma once\n\n#include <stdint.h>\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <unsupported/Eigen/MatrixFunctions>\n\n// CUDA runtime\n#include <cuda_runtime.h>\n// Utilities and system includes\n//#include <helper_functions.h>\n#include <nvidia/helper_cuda.h>\n\n//#include <mmf/defines.h>\n#include <mmf/sphereSimple.hpp>\n#include <mmf/optimizationSO3.hpp>\n//#include <mmf/timer.hpp>\n\nusing namespace Eigen;\n\nextern void vMFCostFctAssignmentGPU(float *h_cost, float *d_cost,\n  uint32_t *h_W, uint32_t *d_W, float *d_x, float* d_weights, \n  uint32_t *d_z, float *d_mu, float* d_pi, int N);\n\nnamespace mmf{\n\n// closed form solution for the vMF cost function.\nclass OptSO3vMFCF : public OptSO3\n{\n  public:\n  OptSO3vMFCF(float *d_weights =NULL):\n    OptSO3(1.,1.,0.1,d_weights), pi_(6), tauR_(1000) { \n    Eigen::VectorXf pi = Eigen::VectorXf::Ones(6)/6.;\n    pi_.set(pi);\n  };\n\n  virtual ~OptSO3vMFCF() { };\n\nprotected:\n  jsc::GpuMatrix<float> pi_;\n  float tauR_; // concentration of vMF on rotation from previous to current frame\n\n  virtual float computeAssignment(Matrix3f& R, uint32_t& N);\n  virtual float conjugateGradientCUDA_impl(Matrix3f& R, float res0,\n    uint32_t N, uint32_t maxIter);\n  virtual void conjugateGradientPostparation_impl(Matrix3f& R);\n  virtual float conjugateGradientPreparation_impl(Matrix3f& R, uint32_t& N);\n  /* evaluate cost function for a given assignment of npormals to axes */\n  virtual float evalCostFunction(Matrix3f& R);\n  /* compute Jacobian */\n  virtual void computeJacobian(Matrix3f&J, Matrix3f& R, float N);\n  virtual void init() {};\n};\n\n}\n", "meta": {"hexsha": "6160bfcfabdd6933d6bea125a02f040243cf07fc", "size": 1751, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mmf/optimizationSO3_vmfCF.hpp", "max_stars_repo_name": "jstraub/mmf", "max_stars_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-06-02T04:17:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T05:44:53.000Z", "max_issues_repo_path": "include/mmf/optimizationSO3_vmfCF.hpp", "max_issues_repo_name": "jstraub/mmf", "max_issues_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "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/mmf/optimizationSO3_vmfCF.hpp", "max_forks_repo_name": "jstraub/mmf", "max_forks_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-06T04:34:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-28T06:35:00.000Z", "avg_line_length": 28.7049180328, "max_line_length": 81, "alphanum_fraction": 0.7310108509, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5187106702719781}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\n/**\n * This is a highly distilled version of fcl::detail::boxBox2 from \n * https://github.com/flexible-collision-library/fcl/blob/master/include/fcl/narrowphase/detail/primitive_shape_algorithm/box_box-inl.h\n * I have been unable to reduce it further and still reproduce the issue.\n */\ndouble reproFunction(const Eigen::Matrix3d& R_in)\n{\n  const Eigen::Matrix3d R = R_in;\n\n  Eigen::Matrix3d Q = R.cwiseAbs();\n\n  if(R(1,2) < 2) {\n    Eigen::Vector3d n{0, 1, R(1, 2)};\n    double s2 = R(1,2);\n    s2 /= n.norm();\n  }\n  return R(1, 2);\n}\n\nint main() {\n  Eigen::Matrix3d R;\n  R = Eigen::Matrix3d::Zero(3,3); \n\n  // This fails - reproFunction(R) returns 0\n  R(1, 2) = 0.7;\n  double R12 = reproFunction(R);\n  bool are_they_equal = (R12 == R(1,2));\n  std::cout << \"R12 == R(1,2): \" << are_they_equal << std::endl;\n  std::cout << \"R12: \" << R12 << std::endl;\n  std::cout << \"R(1, 2): \" << R(1, 2) << std::endl;\n}\n\n", "meta": {"hexsha": "437a19cd3ac8281b0c232b5a7a12f1a4e900398e", "size": 950, "ext": "cc", "lang": "C++", "max_stars_repo_path": "failure_case.cc", "max_stars_repo_name": "avalenzu/eigen-clang-weirdness", "max_stars_repo_head_hexsha": "7c4541122574b2400263b024359ef76052beabe6", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "failure_case.cc", "max_issues_repo_name": "avalenzu/eigen-clang-weirdness", "max_issues_repo_head_hexsha": "7c4541122574b2400263b024359ef76052beabe6", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "failure_case.cc", "max_forks_repo_name": "avalenzu/eigen-clang-weirdness", "max_forks_repo_head_hexsha": "7c4541122574b2400263b024359ef76052beabe6", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3888888889, "max_line_length": 135, "alphanum_fraction": 0.6221052632, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5187106651187804}}
{"text": "/// @brief Constraint functions for use with constraint based collisions.\n\n#pragma once\n\n#include <Eigen/Core>\n\nnamespace Eigen {\ntypedef Matrix<double, 12, 1> Vector12d;\n}\n\nnamespace IPC {\n\n/// @brief Methods for computing the constraints of the optimization problem.\nenum CollisionConstraintType {\n    VOLUME, ///< @brief Volume of a tetrahedron formed by the vertices.\n    GRAPHICS, ///< @brief Distance constraint from Harmon et al. [2008].\n    NONSMOOTH_NEWMARK, ///< @brief Variation of volume constraints proposed by Kane et al. [1999].\n    GAP_FUNCTION, ///< @brief Common method from computational mechanics [Wriggers 1995]\n    CMR, ///< @brief Constraint manifold refinement from Otaduy et al. [2009].\n    VERSCHOOR, ///< @brief Variant of standard graphics approach by Verschoor and Jalba [2019].\n    STIV ///< @brief Space-Time Interference Volume of Harmon et al. [2011] and Lu et al. [2018].\n};\n\n/**\n * @brief Compute the collision constraint value.\n *\n * Triangle vertices expected in clockwise order.\n *\n * @param[in]  v0_t0           First vertex at the start of time-step\n * @param[in]  v1_t0           Second vertex at the start of time-step\n * @param[in]  v2_t0           Third vertex at the start of time-step\n * @param[in]  v3_t0           Fourth vertex at the start of time-step\n * @param[in]  v0_t1           First vertex at the end of time-step\n * @param[in]  v1_t1           Second vertex at the end of time-step\n * @param[in]  v2_t1           Third vertex at the end of time-step\n * @param[in]  v3_t1           Fourth vertex at the end of time-step\n * @param[in]  constraintType  Type of collision constraint to compute.\n * @param[in]  is_edge_edge    Are the vertices of two edge:\n *                             (v0, v1) and (v2, v3)?\n * @param[in]  toi             Normalized time of impact between the two\n *                             primitives.\n * @param[out] c               Computed constraint value.\n */\nvoid compute_collision_constraint(\n    const Eigen::Vector3d& v0_t0, const Eigen::Vector3d& v1_t0,\n    const Eigen::Vector3d& v2_t0, const Eigen::Vector3d& v3_t0,\n    const Eigen::Vector3d& v0_t1, const Eigen::Vector3d& v1_t1,\n    const Eigen::Vector3d& v2_t1, const Eigen::Vector3d& v3_t1,\n    const CollisionConstraintType constraintType, bool is_edge_edge,\n    double toi, double& c);\n\n/**\n * @brief Compute the collision constraint gradient.\n *\n * Triangle vertices expected in clockwise order.\n *\n * @param[in]  v0_t0           First vertex at the start of time-step\n * @param[in]  v1_t0           Second vertex at the start of time-step\n * @param[in]  v2_t0           Third vertex at the start of time-step\n * @param[in]  v3_t0           Fourth vertex at the start of time-step\n * @param[in]  v0_t1           First vertex at the end of time-step\n * @param[in]  v1_t1           Second vertex at the end of time-step\n * @param[in]  v2_t1           Third vertex at the end of time-step\n * @param[in]  v3_t1           Fourth vertex at the end of time-step\n * @param[in]  constraintType  Type of collision constraint to compute.\n * @param[in]  is_edge_edge    Are the vertices of two edge:\n *                             (v0, v1) and (v2, v3)?\n * @param[in]  toi             Normalized time of impact between the two\n *                             primitives.\n * @param[out] grad_c          Computed gradient of constraint value.\n */\nvoid compute_collision_constraint_gradient(\n    const Eigen::Vector3d& v0_t0, // First vertex at the start of time-step\n    const Eigen::Vector3d& v1_t0, // Second vertex at the start of time-step\n    const Eigen::Vector3d& v2_t0, // Third vertex at the start of time-step\n    const Eigen::Vector3d& v3_t0, // Fourth vertex at the start of time-step\n    const Eigen::Vector3d& v0_t1, // First vertex at the end of time-step\n    const Eigen::Vector3d& v1_t1, // Second vertex at the end of time-step\n    const Eigen::Vector3d& v2_t1, // Third vertex at the end of time-step\n    const Eigen::Vector3d& v3_t1, // Fourth vertex at the end of time-step\n    const CollisionConstraintType constraintType, bool is_edge_edge,\n    const double toi, Eigen::Vector12d& grad_c);\n\n///////////////////////////////////////////////////////////////////////////////\n// Volume Constraint\n\n/**\n * @brief Compute the collision constraint volume.\n *\n * Triangle vertices expected in clockwise order.\n */\nvoid compute_collision_volume_constraint(\n    const Eigen::Vector3d& v0,\n    const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, const Eigen::Vector3d& v3,\n    double& c);\n\n/**\n * @brief Compute the collision constraint volume gradient.\n *\n * Triangle vertices expected in clockwise order.\n */\nvoid compute_collision_volume_constraint_gradient(\n    const Eigen::Vector3d& v0,\n    const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, const Eigen::Vector3d& v3,\n    Eigen::Vector12d& grad_c);\n\n///////////////////////////////////////////////////////////////////////////////\n// Graphics (Distance) Constraint\n\n/**\n* @brief Compute the barycentric coordinates of a point in triangle (a, b, c).\n*\n* Computes the barycentric coordinates of any point in the plane containing\n* the triangle (a, b, c).\n*\n* @param[in]  p       Compute the barycentric coordinates of this point.\n* @param[in]  a       First vertex in the triangle.\n* @param[in]  b       Second vertex in the triangle.\n* @param[in]  b       Third vertex in the triangle.\n* @param[out] coords  Computed barycentric coordinates.\n*/\nvoid barycentric_coordinates(\n    const Eigen::Vector3d& p,\n    const Eigen::Vector3d& a,\n    const Eigen::Vector3d& b,\n    const Eigen::Vector3d& c,\n    Eigen::Vector3d& coords);\n\n/**\n * @brief Compute the standard graphics point-triangle constraint value.\n *\n * Triangle vertices expected in counter-clockwise order.\n */\nvoid compute_graphics_point_triangle_constraint(\n    const Eigen::Vector3d& v0, // point\n    const Eigen::Vector3d& v1, // triangle point 0\n    const Eigen::Vector3d& v2, // triangle point 2\n    const Eigen::Vector3d& v3, // triangle point 1\n    double& c);\n\n/**\n * @brief Compute the standard graphics edge-edge collision constraint value.\n */\nvoid compute_graphics_edge_edge_constraint(\n    const Eigen::Vector3d& v0, // first edge's first vertex\n    const Eigen::Vector3d& v1, // first edge's second vertex\n    const Eigen::Vector3d& v2, // second edge's first vertex\n    const Eigen::Vector3d& v3, // second edge's second vertex\n    double& c);\n\n/**\n * @brief Compute the standard graphics point-triangle constraint gradient.\n *\n * Triangle vertices expected in counter-clockwise order.\n */\nvoid compute_graphics_point_triangle_constraint_gradient(\n    const Eigen::Vector3d& v0, // point\n    const Eigen::Vector3d& v1, // triangle point 0\n    const Eigen::Vector3d& v2, // triangle point 2\n    const Eigen::Vector3d& v3, // triangle point 1\n    Eigen::Vector12d& grad_c);\n\n/**\n * @brief Compute the standard graphics edge-edge collision constraint gradient.\n */\nvoid compute_graphics_edge_edge_constraint_gradient(\n    const Eigen::Vector3d& v0, // first edge's first vertex\n    const Eigen::Vector3d& v1, // first edge's second vertex\n    const Eigen::Vector3d& v2, // second edge's first vertex\n    const Eigen::Vector3d& v3, // second edge's second vertex\n    Eigen::Vector12d& grad_c);\n\n///////////////////////////////////////////////////////////////////////////////\n// Efficient and Accurate Collision Response for Elastically Deformable Models\n// [Verschoor et al. 2019]\n\nvoid compute_Verschoor_point_triangle_constraint(\n    const Eigen::Vector3d& v0_t0, // point at start of the timestep\n    const Eigen::Vector3d& v1_t0, // triangle point 0 at start of the timestep\n    const Eigen::Vector3d& v2_t0, // triangle point 1 at start of the timestep\n    const Eigen::Vector3d& v3_t0, // triangle point 2 at start of the timestep\n    const Eigen::Vector3d& v0_t1, // point at end of the timestep\n    const Eigen::Vector3d& v1_t1, // triangle point 0 at end of the timestep\n    const Eigen::Vector3d& v2_t1, // triangle point 1 at end of the timestep\n    const Eigen::Vector3d& v3_t1, // triangle point 2 at end of the timestep\n    double toi, double& c);\n\nvoid compute_Verschoor_edge_edge_constraint(\n    const Eigen::Vector3d& v0_t0, // first edge's first vertex at t = 0\n    const Eigen::Vector3d& v1_t0, // first edge's second vertex at t = 0\n    const Eigen::Vector3d& v2_t0, // second edge's first vertex at t = 0\n    const Eigen::Vector3d& v3_t0, // second edge's second vertex at t = 0\n    const Eigen::Vector3d& v0_t1, // first edge's first vertex at t = 1\n    const Eigen::Vector3d& v1_t1, // first edge's second vertex at t = 1\n    const Eigen::Vector3d& v2_t1, // second edge's first vertex at t = 1\n    const Eigen::Vector3d& v3_t1, // second edge's second vertex at t = 1\n    double toi, double& c);\n\nvoid compute_Verschoor_point_triangle_constraint_gradient(\n    const Eigen::Vector3d& v0_t0, // point at start of the timestep\n    const Eigen::Vector3d& v1_t0, // triangle point 0 at start of the timestep\n    const Eigen::Vector3d& v2_t0, // triangle point 1 at start of the timestep\n    const Eigen::Vector3d& v3_t0, // triangle point 2 at start of the timestep\n    const Eigen::Vector3d& v0_t1, // point at end of the timestep\n    const Eigen::Vector3d& v1_t1, // triangle point 0 at end of the timestep\n    const Eigen::Vector3d& v2_t1, // triangle point 1 at end of the timestep\n    const Eigen::Vector3d& v3_t1, // triangle point 2 at end of the timestep\n    double toi, Eigen::Vector12d& grad_c);\n\nvoid compute_Verschoor_edge_edge_constraint_gradient(\n    const Eigen::Vector3d& v0_t0, // first edge's first vertex at t = 0\n    const Eigen::Vector3d& v1_t0, // first edge's second vertex at t = 0\n    const Eigen::Vector3d& v2_t0, // second edge's first vertex at t = 0\n    const Eigen::Vector3d& v3_t0, // second edge's second vertex at t = 0\n    const Eigen::Vector3d& v0_t1, // first edge's first vertex at t = 1\n    const Eigen::Vector3d& v1_t1, // first edge's second vertex at t = 1\n    const Eigen::Vector3d& v2_t1, // second edge's first vertex at t = 1\n    const Eigen::Vector3d& v3_t1, // second edge's second vertex at t = 1\n    double toi, Eigen::Vector12d& grad_c);\n\n///////////////////////////////////////////////////////////////////////////////\n// Parallel contact-aware simulations of deformable particles in 3D Stokes flow\n// [Lu et al. 2018]\n\nvoid compute_STIV_point_triangle_constraint(\n    const Eigen::Vector3d& v0_t0, // point at start of the timestep\n    const Eigen::Vector3d& v1_t0, // triangle point 0 at start of the timestep\n    const Eigen::Vector3d& v2_t0, // triangle point 1 at start of the timestep\n    const Eigen::Vector3d& v3_t0, // triangle point 2 at start of the timestep\n    const Eigen::Vector3d& v0_t1, // point at end of the timestep\n    const Eigen::Vector3d& v1_t1, // triangle point 0 at end of the timestep\n    const Eigen::Vector3d& v2_t1, // triangle point 1 at end of the timestep\n    const Eigen::Vector3d& v3_t1, // triangle point 2 at end of the timestep\n    double toi, double& c);\n\nvoid compute_STIV_edge_edge_constraint(\n    const Eigen::Vector3d& v0_t0, // first edge's first vertex at t = 0\n    const Eigen::Vector3d& v1_t0, // first edge's second vertex at t = 0\n    const Eigen::Vector3d& v2_t0, // second edge's first vertex at t = 0\n    const Eigen::Vector3d& v3_t0, // second edge's second vertex at t = 0\n    const Eigen::Vector3d& v0_t1, // first edge's first vertex at t = 1\n    const Eigen::Vector3d& v1_t1, // first edge's second vertex at t = 1\n    const Eigen::Vector3d& v2_t1, // second edge's first vertex at t = 1\n    const Eigen::Vector3d& v3_t1, // second edge's second vertex at t = 1\n    double toi, double& c);\n\nvoid compute_STIV_point_triangle_constraint_gradient(\n    const Eigen::Vector3d& v0_t0, // point at start of the timestep\n    const Eigen::Vector3d& v1_t0, // triangle point 0 at start of the timestep\n    const Eigen::Vector3d& v2_t0, // triangle point 1 at start of the timestep\n    const Eigen::Vector3d& v3_t0, // triangle point 2 at start of the timestep\n    const Eigen::Vector3d& v0_t1, // point at end of the timestep\n    const Eigen::Vector3d& v1_t1, // triangle point 0 at end of the timestep\n    const Eigen::Vector3d& v2_t1, // triangle point 1 at end of the timestep\n    const Eigen::Vector3d& v3_t1, // triangle point 2 at end of the timestep\n    double toi, Eigen::Vector12d& grad_c);\n\nvoid compute_STIV_edge_edge_constraint_gradient(\n    const Eigen::Vector3d& v0_t0, // first edge's first vertex at t = 0\n    const Eigen::Vector3d& v1_t0, // first edge's second vertex at t = 0\n    const Eigen::Vector3d& v2_t0, // second edge's first vertex at t = 0\n    const Eigen::Vector3d& v3_t0, // second edge's second vertex at t = 0\n    const Eigen::Vector3d& v0_t1, // first edge's first vertex at t = 1\n    const Eigen::Vector3d& v1_t1, // first edge's second vertex at t = 1\n    const Eigen::Vector3d& v2_t1, // second edge's first vertex at t = 1\n    const Eigen::Vector3d& v3_t1, // second edge's second vertex at t = 1\n    double toi, Eigen::Vector12d& grad_c);\n\n} // namespace IPC\n", "meta": {"hexsha": "8ffc261c397435228f5ca3d8e352c9cc78560f8b", "size": 13083, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/CollisionObject/CollisionConstraints.hpp", "max_stars_repo_name": "vincentkslim/IPC", "max_stars_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2020-07-03T14:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:01:11.000Z", "max_issues_repo_path": "src/CollisionObject/CollisionConstraints.hpp", "max_issues_repo_name": "vincentkslim/IPC", "max_issues_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T15:56:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:56:39.000Z", "max_forks_repo_path": "src/CollisionObject/CollisionConstraints.hpp", "max_forks_repo_name": "vincentkslim/IPC", "max_forks_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T05:04:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:09:23.000Z", "avg_line_length": 48.4555555556, "max_line_length": 98, "alphanum_fraction": 0.6787434075, "num_tokens": 3622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.5187106637525373}}
{"text": "#include <boost/numeric/ublas/vector.hpp>\n#include <kv/interval.hpp>\n\nnamespace ub = boost::numeric::ublas;\n\nstruct Matsu1 {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = (x(0)-1.) * (x(0)-1.) + x(1) * x(1) - 1.;\n\t\ty(1) = x(0) - x(1);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(2);\n\t\tfor (i=0; i<2; i++) {\n\t\t\tx(i) = kv::interval<T>(-8., 8.);\n\t\t}\n\t}\n};\n\nstruct Matsu2 {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(0) * x(0) + x(1) * x(1) - 1.;\n\t\ty(1) = x(0) - x(1) + 1.;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(2);\n\t\tfor (i=0; i<2; i++) {\n\t\t\tx(i) = kv::interval<T>(-8., 8.);\n\t\t}\n\t}\n};\n\nstruct NoSol {\n\n\tdouble param;\n\n\tNoSol(double param = 1e-5) : param(param) {\n\t}\n\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(0) * x(0) - x(1);\n\t\ty(1) = x(0) * x(0) - x(1) + param;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(2);\n\t\tfor (i=0; i<2; i++) {\n\t\t\tx(i) = kv::interval<T>(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct BadCond {\n\n\tdouble param;\n\n\tBadCond (double param = 1e-7) : param(param) {\n\t}\n\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(0) * x(0) - x(1);\n\t\ty(1) = (1. - param) * x(0) * x(0) - x(1) + param;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(2);\n\t\tfor (i=0; i<2; i++) {\n\t\t\tx(i) = kv::interval<T>(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct Hansen1 {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(1);\n\n\t\ty(0) = x(0)*x(0)*x(0)*x(0) - 12.*x(0)*x(0)*x(0) + 47.*x(0)*x(0) - 60.*x(0);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(1);\n\t\tfor (i=0; i<1; i++) {\n\t\t\tx(i) = kv::interval<T>(-1e20, 1e20);\n\t\t}\n\t}\n};\n\nstruct Burden {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(0) * (4. - 0.0003 * x(0) - 0.0004 * x(1));\n\t\ty(1) = x(1) * (2. - 0.0002 * x(0) - 0.0001 * x(1));\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(2);\n\t\tfor (i=0; i<2; i++) {\n\t\t\tx(i) = kv::interval<T>(0., 1e10);\n\t\t}\n\t}\n};\n\nstruct GE1 {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = -1. / (1. + x(0)) + x(1) / (1. + x(1));\n\t\ty(1) = 1. / (1. + x(0)) - x(1) / (x(0) + x(1));\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(2);\n\t\tfor (i=0; i<2; i++) {\n\t\t\tx(i) = kv::interval<T>(0.01, 100.);\n\t\t}\n\t}\n};\n\n// Yoshitane Shinohara: Suuchikaiseki no Kiso, q. 3.8.2\nstruct Shinohara1 {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(2);\n\t\tT p, q;\n\n\t\tp = x(0);\n\t\tq = x(1);\n\n\t\ty(0) = p*p*p*p*p - 10.*p*p*p*q*q + 5.*p*q*q*q*q\n\t\t       - 2.*p*p*p*p + 12.*p*p*q*q - 2.*q*q*q*q\n\t\t       + 10.*p*p*p - 30.*p*q*q - 9.*p + 3.;\n\t\ty(1) = q*q*q*q*q - 10.*p*p*q*q*q + 5.*p*p*p*p*q\n\t\t       - 8.*p*p*p*q + 8.*p*q*q*q + 30.*p*p*q\n\t\t       -10.*q*q*q - 9.*q;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(2);\n\t\tfor (i=0; i<2; i++) {\n\t\t\tx(i) = kv::interval<T>(-5., 5.);\n\t\t}\n\t}\n};\n\n// Yoshitane Shinohara: Suuchikaiseki no Kiso, q. 3.8.3\nstruct Shinohara2 {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(2);\n\t\tT p, q;\n\n\t\tp = x(0);\n\t\tq = x(1);\n\n\t\ty(0) = p*p*p*p*p - 10.*p*p*p*q*q + 5.*p*q*q*q*q\n\t\t       - 3.*p*p*p*p + 18.*p*p*q*q - 3.*q*q*q*q\n\t\t       - 2.*p*p*p + 6.*p*q*q + 3.*p*p*q - q*q*q\n\t\t       + 12.*p*p - 12.*q*q - 10.*p*q - 8.*p + 8.*q;\n\t\ty(1) = 5.*p*p*p*p*q - 10.*p*p*q*q*q + q*q*q*q*q\n\t\t       - 12.*p*p*p*q + 12.*p*q*q*q - p*p*p + 3.*p*q*q\n\t\t       - 6.*p*p*q + 2.*q*q*q + 5.*p*p - 5.*q*q\n\t\t       + 24.*p*q - 8.*p - 8.*q + 4.;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(2);\n\t\tfor (i=0; i<2; i++) {\n\t\t\tx(i) = kv::interval<T>(-3., 3.);\n\t\t}\n\t}\n};\n\n\n// Yoshitane Shinohara: Suuchikaiseki no Kiso, ex. 3.8\nstruct Shinohara3 {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(5);\n\t\tT p, q, r, s, t;\n\n\t\tp = x(0);\n\t\tq = x(1);\n\t\tr = x(2);\n\t\ts = x(3);\n\t\tt = x(4);\n\n\t\ty(0) = p*p*p - 2.*p*q + r + 0.75*p + 1.;\n\t\ty(1) = p*p*q - q*q - p*r +s + 0.75*q + 0.25;\n\t\ty(2) = p*p*r - p*s - q*r + t + 0.75*r + 0.75;\n\t\ty(3) = p*p*s - p*t - q*s + 0.75*s;\n\t\ty(4) = p*p*t - q*t + 0.75*t - 0.25;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(5);\n\t\tx(0) = kv::interval<T>(-1.5, 2.);\n\t\tx(1) = kv::interval<T>(-0.6, 3.);\n\t\tx(2) = kv::interval<T>(-1.5, 2.5);\n\t\tx(3) = kv::interval<T>(-0.5, 1.9);\n\t\tx(4) = kv::interval<T>(-1, 1.);\n\t}\n};\n\n\n/*\n  Problem taken from\n  http://nlab.ee.tokushima-u.ac.jp/nishio/Pub-Data/WORK/W153.pdf, \n  http://200.13.98.241/~martin/syop/tareas3/kuno_seader_homotopy.pdf\n  Computing All Real Solutions to Systems of Nonlinear Equations\n  with a Global Fixed-Point Homotopy\n  This equation has 7 solutions and difficult to find all solution\n  by homotopy method.\n */\n\nstruct ModifiedHimmelblau {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = 2.*x(0)*x(0)*x(0) + 2.*x(0)*x(1) - 22.*x(0) + x(1)*x(1) + 13.;\n\t\ty(1) = x(0)*x(0) + 2.*x(0)*x(1) + 2.*x(1)*x(1)*x(1) - 14.*x(1) + 9.;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(2);\n\t\tfor (i=0; i<2; i++) {\n\t\t\tx(i) = kv::interval<T>(-1e8, 1e8);\n\t\t}\n\t}\n};\n\n//\n// made by Heihachiro Yoshii on 2013/07/25\n//\n\nstruct Heihachiro {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = 2. * x(0) * x(0) * x(1) - 1.;\n\t\ty(1) = x(0) + 0.5 * x(1) * x(1) - 2.;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(2);\n\t\tfor (i=0; i<2; i++) {\n\t\t\tx(i) = kv::interval<T>(-1000., 1000.);\n\t\t}\n\t}\n};\n\n\nstruct Yamamura2 {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tint n = x.size();\n\t\tub::vector<T> y(n);\n\t\tT s;\n\t\tint i;\n\n\t\ts = 0.;\n\t\tfor (i=0; i<n; i++) {\n\t\t\ts += pow(x(i), 3);\n\t\t}\n\n\t\tfor (i=0; i<n; i++) {\n\t\t\ty(i) = x(i) - (s + (i + 1.)) / (2. * n);\n\t\t}\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(int n, ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(n);\n\t\tfor (i=0; i<n; i++) {\n\t\t\tx(i) = kv::interval<T>(-2.5, 2.5);\n\t\t}\n\t}\n};\n\n\n//\n// K. Meintjes and A. P. Morgan:\n// Chemical Equilibrium Systems as Numerical Test Problmes,\n// ACM Transactions on Mathematical Software, 16(2):143, 1990.\n//\n\nstruct HydroCarbon {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(5);\n\t\t// phisical constants\n\t\tstatic T K5 = kv::constants<T>::str(\"1.930e-1\");\n\t\tstatic T K6 = kv::constants<T>::str(\"2.597e-3\");\n\t\tstatic T K7 = kv::constants<T>::str(\"3.448e-3\");\n\t\tstatic T K8 = kv::constants<T>::str(\"1.799e-5\");\n\t\tstatic T K9 = kv::constants<T>::str(\"2.155e-4\");\n\t\tstatic T K10 = kv::constants<T>::str(\"3.846e-5\");\n\t\t// parameters\n\t\tstatic T R = T(10);\n\t\tstatic T p = T(40);\n\t\t// constants\n\t\tstatic T R5 = K5;\n\t\tstatic T R6 = K6 * pow(p, -0.5);\n\t\tstatic T R7 = K7 * pow(p, -0.5);\n\t\tstatic T R8 = K8 * pow(p, -1);\n\t\tstatic T R9 = K9 * pow(p, -0.5);\n\t\tstatic T R10 = K10 * pow(p, -1);\n\n\t\ty(0) = x(0) * x(1) + x(0) - 3 * x(4);\n\t\ty(1) = 2 * x(0) * x(1) + x(0) + 2 * R10 * pow(x(1), 2) + x(1) * pow(x(2), 2) + R7 * x(1) * x(2) + R9 * x(1) * x(3) + R8 * x(1) - R * x(4);\n\t\ty(2) = 2 * x(1) * pow(x(2), 2) + R7 * x(1) * x(2) + 2 * R5 * pow(x(2), 2) + R6 * x(2) - 8 * x(4);\n\t\ty(3) = R9 * x(1) * x(3) + 2 * pow(x(3), 2) - 4 * R * x(4);\n\t\ty(4) = x(0) * x(1) + x(0) + R10 * pow(x(1), 2) + x(1) * pow(x(2), 2) + R7 * x(1) * x(2) + R9 * x(1) * x(3) + R8 * x(1) + R5 * pow(x(2), 2) + R6 * x(2) + pow(x(3), 2) - 1;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid range(ub::vector< kv::interval<T> >& x) {\n\t\tx.resize(5);\n\t\tint i;\n\t\tfor (i=0; i<5; i++) {\n\t\t\tx(i) = kv::interval<T>(-100, 100);\n\t\t}\n\t}\n};\n", "meta": {"hexsha": "f7d144366d86a014ea91e17b9aa5f8b149d56cc2", "size": 8331, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "example/allsolexample.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/allsolexample.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/allsolexample.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": 21.0911392405, "max_line_length": 172, "alphanum_fraction": 0.4944184372, "num_tokens": 3745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5186868629749881}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <vector>\n#include \"EM.hpp\"\n\ntemplate<class Mixture>\nclass Generator {\npublic:\n    typedef typename Mixture::float_type float_type;\n    typedef typename Mixture::sample_type sample_type;\n    typedef typename Mixture::variable_type variable_type;\nprivate:\n    std::vector<float_type> prior;\n    std::vector<Generator<variable_type> > variableGenerator;\npublic:\n    Generator(const Mixture& mixture) :\n        prior{mixture.prior}\n    {\n        for(size_t k=0; k<mixture.size(); k++){\n            variableGenerator.emplace_back( Generator<variable_type>(mixture[k]) );\n        }\n    }\n    sample_type operator()(){\n        float_type p = (float_type) rand()/RAND_MAX;\n        float_type sum = 0.0;\n        for(size_t k=0; k<prior.size(); k++){\n            sum += prior[k];\n            if( sum>=p ){\n                return variableGenerator[k]();\n            }\n        }\n        return variableGenerator.back()();\n    }\n};\n\n", "meta": {"hexsha": "b8e231762a624599bf8c181e0838b71eeb789100", "size": 966, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Generator.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/Generator.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/Generator.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": 26.1081081081, "max_line_length": 83, "alphanum_fraction": 0.6149068323, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5186868582481016}}
{"text": "#include \"datatypes.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Eigen>\n#include \"parameters.hpp\"\n\n#include <nlopt.h>\n\nnamespace gd {\n\nusing namespace Eigen;\nusing namespace std;\n\ntemplate<class F>\ndouble nlopt_wrapper(unsigned n, const double *x, double *grad, void *data);\ntemplate<typename F=std::function<double(unsigned n, const double *x, double *grad)>, typename T=double>\nclass MinimizerNLoptTest {\n\ttypedef MinimizerNLoptTest<F, T> type;\npublic:\n\tF f;\n\tint N;\n\tMinimizerNLoptTest(F f, int N) : f(f), N(N) {\n\t}\n\t//template<int N, class... Ts>\n\tvoid optimize(int n_eval, double* x) {\n\t//const int N = sizeof...(Ts);\n\t\tnlopt_opt opt;\n\t\topt = nlopt_create(NLOPT_LD_MMA, N);\n\t\topt = nlopt_create(NLOPT_LD_LBFGS, N);\n\t\t//opt = nlopt_create(NLOPT_AUGLAG, N);\n\t//opt = nlopt_create(NLOPT_LD_VAR1, N);\n\t//opt = nlopt_create(NLOPT_LN_COBYLA, N);\n\t\t\n\t//nlopt_set_lower_bounds(opt, lb);\n\t\tnlopt_set_min_objective(opt, nlopt_wrapper<type>, this);\n\t\t//double lower_bounds[N] = { 0 };\n\t\tdouble* lower_bounds = new double[N];\n\t\tdouble* upper_bounds = new double[N];\n//lower_bounds[0] = 0.1;\n\t\t//lower_bounds[1] = 1;\n\t\tfor(int i = 0; i < N; i++) {\n\t\t\tlower_bounds[i] = -HUGE_VAL;\n\t\t\tupper_bounds[i] =  HUGE_VAL;\n\t\t}\n\t\t\n\t\t//double upper_bounds[N];\n\t\t//upper_bounds[0] = 10;\n\t\t//upper_bounds[1] = 40;\n\t\t//for(int i = 2; i < N; i++) {\n\t\t//\tlower_bounds[i] = -1;\n\t\t//\tupper_bounds[i] = 1;\n\t\t//}\n\t\t//nlopt_set_lower_bounds(opt, lower_bounds);\n\t\t//nlopt_set_upper_bounds(opt, upper_bounds);\n\t\t//for(int i = 0; i < N; i++)\n\t\t//\tprintf(\"lower_bounds[%d] = %f\\n\", i, lower_bounds[i]);\n\t\t//for(int i = 0; i < N; i++)\n\t\t//\tprintf(\"upper [%d] = %f\\n\", i, upper_bounds[i]);\n\t//double steps[N] = {1e-8, 1e-10};\n\t//nlopt_set_initial_step1(opt, 1e-5);\n\t\t\n\t\tnlopt_set_xtol_rel(opt, 1e-8);\n\t\t//nlopt_set_ftol_abs(opt, 1e-9);\n\t\tnlopt_set_maxeval(opt, n_eval);\n\t\t//double x[N] = { initial_values... };\n\t\tdouble minf;\n\t\tint ret = nlopt_optimize(opt, x, &minf);\n\t\tif (ret < 0) {\n\t\t\tprintf(\"nlopt failed!: %d\\n\", ret);\n\t\t}\n\t\telse {\n\t\t\tprintf(\"found minimum at f(...\");\n\t\t\t//for(int i = 0; i < N; i++)\n\t\t\t//\tprintf(\"%g, \", x[i]);\n\t\t\tprintf(\") = %0.10g\\n\", minf);\n\t\t}\n\t\tnlopt_destroy(opt);\n\t}\n};\n\ntemplate<class F>\nMinimizerNLoptTest<F> nnlopt_optimize(F f, int N)\n{\n\tMinimizerNLoptTest<F> opt(f, N);\n\treturn opt;\n}\n\nnamespace schw {\n\n};\n\n\n\nclass OptimizationMatrixChiSquare {\npublic:\n\tOptimizationMatrixChiSquare(double_matrix model_matrix, double_vector observed) {\n\t\tthis->model_matrix = MatrixXd::Map(model_matrix.data().begin(), model_matrix.size2(), model_matrix.size1());\n\t\tthis->observed = VectorXd::Map(observed.data().begin(), observed.size());\n\t}\n\tdouble _logp(double_vector _x) {\n\t\tMap<VectorXd> x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\treturn logp(x);\n\t}\n\ttemplate<class T>\n\tdouble logp(T& x) {\n\t\t//double total = x.sum();\n\t\t//VectorXd xn = x/total;\n\t\t//double norm = totalmass.dot(x);\n\t\t//int N = pmatrix.rows();\n\t\t//printf(\"[N=%d f=%f %f]\\n\", N, norm, log(norm));\n\t\t//double value = ((pmatrix * x).cwise().log()).sum() - N*log(norm);// - pmatrix.rows() * log(x.sum());\n\t\tdouble chisq = (model_matrix * x - observed).cwise().square().sum();\n\t\treturn -0.5 * chisq;\n\t\t//return value;\n\t}\n\tvoid _dlogpdx(double_vector _x, double_vector _gradient) {\n\t\tVectorXd x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\tMap<VectorXd> gradient = VectorXd::Map(_gradient.data().begin(), _gradient.size());\n\t\tdlogpdx(x, gradient);\n\t}\n\t\n\ttemplate<class T1, class T2>\n\tvoid dlogpdx(T1& x, T2& gradient) {\n\t\t//double total = x.sum();\n\t\t//VectorXd xn = x/total;\n\t\tVectorXd model_values = model_matrix * x;\n\t\t//int N = model_matrix.rows();\n\t\t//VectorXd Pi_inv = Pi.cwise().inverse();\n\t\t//VectorXd t1 = -pmatrix.transpose() * Pi_inv;\n\t\t//VectorXd g = t1.cwise() + x.size()/(x.sum());\n\t\t//gradient.setZero();\n\t\tint Nx = x.size();\n\t\t//printf(\"matrix: %d %d observed: %d\\n\", model_matrix.cols(), model_matrix.rows(), observed.size());\n\t\t//double norm = totalmass.dot(x);\n\t\t//int N = pmatrix.rows();\n\t\tint Nj = model_matrix.rows();\n\t\tfor(int k = 0; k < Nx; k++) {\n\t\t\tfor(int j = 0; j < Nj; j++) {\n\t\t\t\tgradient(k) += -(model_values(j) - observed(j))*model_matrix(j,k);\n\t\t\t}\n\t\t\t//gradient(k) += -N/norm*totalmass(k);\n\t\t}\n\t\t//gradient += g;//.cwise();//*x;\n\t\t\n\t}\n\tMatrixXd model_matrix;\n\tVectorXd observed;\n};\n\n\n\nclass OptimizationMatrix {\npublic:\n\tOptimizationMatrix(double_matrix pmatrix, double_vector totalmass) {\n\t\tthis->pmatrix = MatrixXd::Map(pmatrix.data().begin(), pmatrix.size2(), pmatrix.size1());\n\t\tthis->totalmass = VectorXd::Map(totalmass.data().begin(), totalmass.size());\n\t}\n\tdouble _logp(double_vector _x) {\n\t\tMap<VectorXd> x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\treturn logp(x);\n\t}\n\ttemplate<class T>\n\tdouble logp(T& x) {\n\t\t//double total = x.sum();\n\t\t//VectorXd xn = x/total;\n\t\tdouble norm = totalmass.dot(x);\n\t\tint N = pmatrix.rows();\n\t\t//printf(\"[N=%d f=%f %f]\\n\", N, norm, log(norm));\n\t\tdouble value = ((pmatrix * x).cwise().log()).sum() - N*log(norm);// - pmatrix.rows() * log(x.sum());\n\t\treturn value;\n\t}\n\tvoid _dlogpdx(double_vector _x, double_vector _gradient) {\n\t\tVectorXd x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\tMap<VectorXd> gradient = VectorXd::Map(_gradient.data().begin(), _gradient.size());\n\t\tdlogpdx(x, gradient);\n\t}\n\t\n\ttemplate<class T1, class T2>\n\tvoid dlogpdx(T1& x, T2& gradient) {\n\t\t//double total = x.sum();\n\t\t//VectorXd xn = x/total;\n\t\tVectorXd Pi = (pmatrix * x);\n\t\tint N = pmatrix.rows();\n\t\t//VectorXd Pi_inv = Pi.cwise().inverse();\n\t\t//VectorXd t1 = -pmatrix.transpose() * Pi_inv;\n\t\t//VectorXd g = t1.cwise() + x.size()/(x.sum());\n\t\t//gradient.setZero();\n\t\tint Nx = x.size();\n\t\t//printf(\"matrix: %d %d Pi: %d\\n\", pmatrix.cols(), pmatrix.rows(), Pi.size());\n\t\tdouble norm = totalmass.dot(x);\n\t\t//int N = pmatrix.rows();\n\t\tint Nj = pmatrix.rows();\n\t\tfor(int k = 0; k < Nx; k++) {\n\t\t\tfor(int j = 0; j < Nj; j++) {\n\t\t\t\tgradient(k) += pmatrix(j,k)/Pi(j);\n\t\t\t}\n\t\t\tgradient(k) += -N/norm*totalmass(k);\n\t\t}\n\t\t//gradient += g;//.cwise();//*x;\n\t\t\n\t}\n\tMatrixXd pmatrix;\n\tVectorXd totalmass;\n};\n\nclass OptimizationMatrixForegroundConditional {\npublic:\n\tOptimizationMatrixForegroundConditional(double_matrix pmatrix, double_matrix pcmatrix, double_vector ratios, double_vector p_v_non_member) {\n\t\tthis->pmatrix = MatrixXd::Map(pmatrix.data().begin(), pmatrix.size2(), pmatrix.size1());\n\t\tthis->pcmatrix = MatrixXd::Map(pcmatrix.data().begin(), pcmatrix.size2(), pcmatrix.size1());\n\t\t//this->totalmass = VectorXd::Map(totalmass.data().begin(), totalmass.size());\n\t\tthis->ratios = VectorXd::Map(ratios.data().begin(), ratios.size());\n\t\tthis->p_v_non_member = VectorXd::Map(p_v_non_member.data().begin(), p_v_non_member.size());\n\t\tp_member = this->ratios.cwise() / (1 + this->ratios.cwise());\n\t}\n\t\n\tdouble _logp(double_vector _x) {\n\t\tMap<VectorXd> x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\treturn logp(x);\n\t}\n\ttemplate<class T>\n\tdouble logp(T& x) {\n\t\t//double total = x.sum();\n\t\t//VectorXd xn = x/total;\n\t\t//double norm = totalmass.dot(x);\n\t\t//int N = pmatrix.rows();\n\t\t//printf(\"[N=%d f=%f %f]\\n\", N, norm, log(norm));\n\t\t// sum( p(v|R) = sum( p(v,R)/p(R) )\n\t\tVectorXd p_v_member = (pmatrix * x).cwise() / (pcmatrix * x);\n\t\tdouble value = (p_v_member.cwise()*p_member +p_v_non_member.cwise() * ((p_member*-1).cwise() + 1)).cwise().log().sum(); // - N*log(norm);// - pmatrix.rows() * log(x.sum());\n\t\treturn value;\n\t}\n\tvoid _dlogpdx(double_vector _x, double_vector _gradient) {\n\t\tVectorXd x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\tMap<VectorXd> gradient = VectorXd::Map(_gradient.data().begin(), _gradient.size());\n\t\tdlogpdx(x, gradient);\n\t}\n\t\n\ttemplate<class T1, class T2>\n\tvoid dlogpdx(T1& x, T2& gradient) {\n\t\t//double total = x.sum();\n\t\t//VectorXd xn = x/total;\n\t\tVectorXd Pi = (pmatrix * x);\n\t\tVectorXd PCi = (pcmatrix * x);\n\t\t//VectorXd p = Pi.cwise() / PCi;\n\t\t\n\t\tVectorXd p_v_member = (pmatrix * x).cwise() / (pcmatrix * x);\n\t\tVectorXd p = (p_v_member.cwise()*p_member +p_v_non_member.cwise() * ((p_member*-1).cwise() + 1));\n\t\t\n\t\t//int N = pmatrix.rows();\n\t\t//VectorXd Pi_inv = Pi.cwise().inverse();\n\t\t//VectorXd t1 = -pmatrix.transpose() * Pi_inv;\n\t\t//VectorXd g = t1.cwise() + x.size()/(x.sum());\n\t\t//gradient.setZero();\n\t\tint Nx = x.size();\n\t\t//printf(\"matrix: %d %d Pi: %d\\n\", pmatrix.cols(), pmatrix.rows(), Pi.size());\n\t\t//double norm = totalmass.dot(x);\n\t\t//int N = pmatrix.rows();\n\t\tint Nj = pmatrix.rows();\n\t\t//printf(\" %d %d %d %d %d %d \\n\", Nj, Nx, Pi.size(), PCi.size(), p.size(), pcmatrix.cols());\n\t\tfor(int k = 0; k < Nx; k++) {\n\t\t\tfor(int j = 0; j < Nj; j++) {\n\t\t\t\t//gradient(k) += pmatrix(j,k)/Pi(j);\n\t\t\t\t//gradient(k) += 1./p(j) * (pmatrix(j,k) / PCi(j)  - Pi(j)/pow(PCi(j), 2) * pcmatrix(j,k) );\n\t\t\t\tgradient(k) += 1./p(j) * (pmatrix(j,k) * p_member(j) / PCi(j)  - Pi(j) * p_member(j) /pow(PCi(j), 2) * pcmatrix(j,k) );\n\t\t\t}\n\t\t\t//gradient(k) += -N/norm*totalmass(k);\n\t\t}\n\t\t//exit(0);\n\t\t//gradient += g;//.cwise();//*x;\n\t\t\n\t}\n\tMatrixXd pmatrix, pcmatrix;\n\tVectorXd totalmass;\n\tVectorXd ratios;\n\tVectorXd p_member;\n\tVectorXd p_v_non_member;\n\t\n};\n\n\n\nclass OptimizationQP {\npublic:\n\tMatrixXd P;\n\tVectorXd q;\n\tOptimizationQP(double_matrix P, double_vector q) {\n\t\tthis->P = MatrixXd::Map(P.data().begin(), P.size2(), P.size1());\n\t\tthis->q = VectorXd::Map(q.data().begin(), q.size());\n\t}\n\tdouble _logp(double_vector _x) {\n\t\tMap<VectorXd> x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\treturn logp(x);\n\t}\n\ttemplate<class T>\n\tdouble logp(T& x) {\n\t\t//double total = x.sum();\n\t\tVectorXd Px = P * x;\n\t\tdouble value = x.dot(Px)/2 + q.dot(x);\n\t\t//double norm = totalmass.dot(x);\n\t\t//double value = ((pmatrix * x).cwise().log().cwise() * counts).sum() - this->N*log(norm);// - pmatrix.rows() * log(x.sum());\n\t\treturn value;\n\t}\n\tvoid _dlogpdx(double_vector _x, double_vector _gradient) {\n\t\tVectorXd x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\tMap<VectorXd> gradient = VectorXd::Map(_gradient.data().begin(), _gradient.size());\n\t\tdlogpdx(x, gradient);\n\t}\n\t\n\ttemplate<class T1, class T2>\n\tvoid dlogpdx(T1& x, T2& gradient) {\n\t\tgradient = gradient + P * x + q;\n\t}\n};\n\n\nclass OptimizationMatrixN {\npublic:\n\tOptimizationMatrixN(double_matrix pmatrix, double_vector counts, double_vector totalmass) {\n\t\tthis->pmatrix = MatrixXd::Map(pmatrix.data().begin(), pmatrix.size2(), pmatrix.size1());\n\t\tthis->counts = VectorXd::Map(counts.data().begin(), counts.size());\n\t\tthis->totalmass = VectorXd::Map(totalmass.data().begin(), totalmass.size());\n\t\tthis->N = this->counts.sum();\n\t}\n\tdouble _logp(double_vector _x) {\n\t\tMap<VectorXd> x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\treturn logp(x);\n\t}\n\ttemplate<class T>\n\tdouble logp(T& x) {\n\t\t//double total = x.sum();\n\t\t//VectorXd xn = x/total;\n\t\tdouble norm = totalmass.dot(x);\n\t\tdouble value = ((pmatrix * x).cwise().log().cwise() * counts).sum() - this->N*log(norm);// - pmatrix.rows() * log(x.sum());\n\t\treturn value;\n\t}\n\tvoid _dlogpdx(double_vector _x, double_vector _gradient) {\n\t\tVectorXd x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\tMap<VectorXd> gradient = VectorXd::Map(_gradient.data().begin(), _gradient.size());\n\t\tdlogpdx(x, gradient);\n\t}\n\t\n\ttemplate<class T1, class T2>\n\tvoid dlogpdx(T1& x, T2& gradient) {\n\t\t/*double total = x.sum();\n\t\tVectorXd xn = x/total;\n\t\tVectorXd pi = (pmatrix * xn);\n\t\tVectorXd t = pi.cwise().inverse();\n\t\tMatrixXd m = pmatrix;\n\t\tfor(int i = 0; i < pmatrix.cols(); i++) {\n\t\t\tm.col(i) = m.col(i).cwise() * counts;\n\t\t}\n\t\t//cout << counts;\n\t\t//printf(\"matrix: %d %d vector: %d\\n\", pmatrix.cols(), pmatrix.rows(), counts.size());\n\t\t//MatrixXd m = pmatrix.transpose().cwise() * counts;\n\t\t//VectorXd g1 = -(pmatrix.transpose().colwise() * counts) * t;\n\t\t//g1 = g1.cwise() + pmatrix.rows() * 1/(x.sum());\n\t\t//g1 = (g1.cwise() * counts)  + (counts*(1/(x.sum())));\n\t\t//g1 = (g1.cwise() * counts)  + (counts*(1/(x.sum())));\n\t\t//g1 = (g1) ;//  + (counts*(1/(x.sum())));\n\t\t//gradient.setZero();\n\t\tVectorXd ex = counts*(1./x.sum());\n\t\tdouble bla = counts.sum()/(x.sum());\n\t\tgradient += (-(m.transpose() * t)).cwise() + bla;\n\t\t//gradient = g1;//.cwise();//*x;*/\n\t\t//double total = x.sum();\n\t\t//VectorXd xn = x/total;\n\t\tVectorXd Pi = (pmatrix * x);\n\t\t//VectorXd Pi_inv = Pi.cwise().inverse();\n\t\t//VectorXd t1 = -pmatrix.transpose() * Pi_inv;\n\t\t//VectorXd g = t1.cwise() + x.size()/(x.sum());\n\t\t//gradient.setZero();\n\t\tint Nx = x.size();\n\t\tdouble norm = totalmass.dot(x);\n\t\t//printf(\"matrixN: %d %d Pi: %d\\n\", pmatrix.cols(), pmatrix.rows(), Pi.size());\n\t\tint Nj = pmatrix.rows();\n\t\tfor(int k = 0; k < Nx; k++) {\n\t\t\tfor(int j = 0; j < Nj; j++) {\n\t\t\t\tgradient(k) += counts(j) * pmatrix(j,k)/Pi(j) - counts(j)/norm*totalmass(k);\n\t\t\t}\n\t\t}\n\t\t//gradient += g;//.cwise();//*x;\n\t\t\n\t}\n\tMatrixXd pmatrix;\n\tVectorXd counts;\n\tVectorXd totalmass;\n\tdouble N;\n};\n\n\n\n\nclass OptimizationNormalize {\npublic:\n\tdouble value, error;\n\tOptimizationNormalize(double value, double error) : value(value), error(error) {\n\t}\n\tdouble _logp(double_vector _x) {\n\t\tMap<VectorXd> x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\treturn logp(x);\n\t}\n\ttemplate<class T>\n\tdouble logp(T& x) {\n\t\tdouble value = -pow((this->value-x.sum())/error, 2);\n\t\treturn value;\n\t}\n\tvoid _dlogpdx(double_vector _x, double_vector _gradient) {\n\t\tVectorXd x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\tMap<VectorXd> gradient = VectorXd::Map(_gradient.data().begin(), _gradient.size());\n\t\tdlogpdx(x, gradient);\n\t}\n\t\n\ttemplate<class T1, class T2>\n\tvoid dlogpdx(T1& x, T2& gradient) {\n\t\tgradient = gradient.cwise() + 2*(value-x.sum())/pow(error,2);\n\t}\t\n};\n\nclass OptimizationNormalizeMass {\npublic:\n\tVectorXd mass_vector;\n\tdouble totalmass, error;\n\tOptimizationNormalizeMass(double_vector mass_vector, double totalmass, double error) : totalmass(totalmass), error(error) {\n\t\tthis->mass_vector = VectorXd::Map(mass_vector.data().begin(), mass_vector.size());\n\t}\n\tdouble _logp(double_vector _x) {\n\t\tMap<VectorXd> x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\treturn logp(x);\n\t}\n\ttemplate<class T>\n\tdouble logp(T& x) {\n\t\tdouble mass = mass_vector.dot(x);\n\t\tdouble value = -pow((this->totalmass-mass)/error, 2);\n\t\treturn value;\n\t}\n\tvoid _dlogpdx(double_vector _x, double_vector _gradient) {\n\t\tVectorXd x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\tMap<VectorXd> gradient = VectorXd::Map(_gradient.data().begin(), _gradient.size());\n\t\tdlogpdx(x, gradient);\n\t}\n\t\n\ttemplate<class T1, class T2>\n\tvoid dlogpdx(T1& x, T2& gradient) {\n\t\t//gradient = gradient.cwise() + 2*(((mass_vector.cwise() - this->totalmass).cwise()) /pow(error,2)).cwise();\n\t\tint Nx = x.size();\n\t\t//double norm = totalmass.dot(x);\n\t\t//printf(\"matrixN: %d %d Pi: %d\\n\", pmatrix.cols(), pmatrix.rows(), Pi.size());\n\t\t//int Nj = pmatrix.rows();\n\t\tdouble mass = mass_vector.dot(x);\n\t\tdouble value = (this->totalmass-mass);\n\t\tdouble err = pow(error, 2);\n\t\tfor(int k = 0; k < Nx; k++) {\n\t\t\t//for(int j = 0; j < Nj; j++) {\n\t\t\tgradient(k) += 2 * value/err * mass_vector(k);\n\t\t\t//}\n\t\t}\n\t}\t\n};\n\nclass OptimizationEntropy {\npublic:\n\tdouble scale;\n\tOptimizationEntropy(double scale) : scale(scale)  {\n\t}\n\tdouble _logp(double_vector _x) {\n\t\tMap<VectorXd> x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\treturn logp(x);\n\t}\n\ttemplate<class T>\n\tdouble logp(T& x) {\n\t\tdouble value = -scale * (x.cwise() * x.cwise().log()).sum();\n\t\treturn value;\n\t}\n\tvoid _dlogpdx(double_vector _x, double_vector _gradient) {\n\t\tVectorXd x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\tMap<VectorXd> gradient = VectorXd::Map(_gradient.data().begin(), _gradient.size());\n\t\tdlogpdx(x, gradient);\n\t}\n\t\n\ttemplate<class T1, class T2>\n\tvoid dlogpdx(T1& x, T2& gradient) {\n\t\t//gradient = gradient.cwise() + 2*(value-x.sum())/pow(error,2);\n\t\tgradient += -scale * ((x.cwise().log().cwise()+1));\n\t}\t\n};\n\n\n\n/*\nclass OptimizationMatrixN {\npublic:\n\tOptimizationMatrixN(double_matrix pmatrix, double_vector counts) : pmatrix(pmatrix), counts(counts) {\n\t\tthis->pmatrix = MatrixXd::Map(pmatrix.data().begin(), pmatrix.size2(), pmatrix.size1());\n\t\tthis->counts = VectorXd::Map(counts.data().begin(), counts.size());\n\t}\n\tdouble _logp(double_vector _x) {\n\t\tMap<VectorXd> x = VectorXd::Map(_x.data().begin(), _x.size());\n\t\treturn logp(x);\n\t}\n\ttemplate<class T>\n\tdouble logp(T& x) {\n\t\tVectorXd x = u.cwise().exp();\n\t\tdouble total = x.sum();\n\t\tVectorXd xn = x/total;\n\t\t//VectorXd rho2d = rho2dmatrix * x;\n\t\t//cout << \"cols \" << pmatrix.cols() << endl;\n\t\t//double logLkinematics = (pmatrix * x).cwise().log().sum() - pmatrix.rows() * log(x.sum());\n\t\tdouble value = ((pmatrix * xn).cwise().log().cwise() * count.cwise()).sum();// - pmatrix.rows() * log(x.sum());\n\t\treturn value;\n\t}\n\tMatrixXd pmatrix;\n\tVectorXd counts;\n};*/\n\nclass OptimizationProblemSchw {\npublic:\n\tOptimizationProblemSchw(double_matrix _pmatrix, double_matrix _rho2dmatrix, double_vector _orbitweights, double_vector _rho2d_target, double_vector _rho2d_error, double error_x, double entropy_scale, bool kin, bool light, bool norm) : error_x(error_x), entropy_scale(entropy_scale), kin(kin), light(light), norm(norm) {\n\t\tpmatrix = MatrixXd::Map(_pmatrix.data().begin(), _pmatrix.size2(), _pmatrix.size1());\n\t\trho2dmatrix = MatrixXd::Map(_rho2dmatrix.data().begin(), _rho2dmatrix.size2(), _rho2dmatrix.size1());\n\t\torbitweights = VectorXd::Map(_orbitweights.data().begin(), _orbitweights.size());\n\t\trho2d_target = VectorXd::Map(_rho2d_target.data().begin(), _rho2d_target.size());\n\t\trho2d_error = VectorXd::Map(_rho2d_error.data().begin(), _rho2d_error.size());\n\t}\n\t\n\tvoid optimize(int n_eval, int steps, double_vector _u) {\n\t\tint iteration = 0;\n\t\t//int steps = 1;\n\t\tauto g = [&](int n, const double *x, double *grad) -> double {\n\t\t\t//toy.scale = x[0];\n\t\t\t//toy.M = exp(x[1]);\n\t\t\tMap<VectorXd> u(x, n);\n\t\t\tdouble minlogL = -this->likelihood(u);\n\t\t\tif(grad) {\n\t\t\t\tMap<VectorXd> gradvector(grad, n);\n\t\t\t\tthis->dfdx(u, gradvector);\n\t\t\t}\n\t\t\tif((iteration % steps) == 0) { \n\t\t\t\tprintf(\"current point(...\");\n\t\t\t\t//for(int i = 0; i < n; i++)\n\t\t\t\t//\tprintf(\"%g, \", x[i]);\n\t\t\t\tprintf(\") = %20f\\n\", minlogL);\n\t\t\t}\n\t\t\t/*\n\t\t\tdouble chisq = fit.optimize_function(grad);\n\t\t\tif((iteration % steps) == 0) { \n\t\t\t\tif(grad) {\n\t\t\t\t\tprintf(\" gradient(\");\n\t\t\t\t\tfor(int i = 0; i < n; i++)\n\t\t\t\t\t\tprintf(\"%g, \", grad[i]);\n\t\t\t\t}\n\t\t\t\tprintf(\")\");\n\t\t\t\tprintf(\" chisq = %f iteration = %d\\n\", chisq, iteration);\n\t\t\t}\n\t\t//grad[0] = fit.denergyChisqdb(J1, J2);\n\t\t//return fit.energyChisq(J1, J2);*/\n\t\t\titeration++;\n\t\t\treturn minlogL;\n\t\t};\n\t\tauto o = nnlopt_optimize(g, orbitweights.rows());\n\t\t//int n = atoi(argv[1]);\n\t\to.optimize(n_eval, _u.data().begin());\n\t\tcout << \"interations: \" << iteration << endl;\n\t}\n\t\n\tvoid _hessian(double_matrix _h, double_vector _u, bool du=true) {\n\t\tMap<MatrixXd> h = MatrixXd::Map(_h.data().begin(), _h.size2(), _h.size1());\n\t\tVectorXd u = VectorXd::Map(_u.data().begin(), _u.size());\n\t\thessian(h, u, du);\n\t}\n\t\n\ttemplate<class T1, class T2>\n\tdouble hessian(T1& h, T2& u, bool du=true) {\n\t\tVectorXd x = u.cwise().exp();\n\t\t\n\t\tassert(h.rows() == h.cols());\n\t\tint N = h.rows();\n\t\tVectorXd gradient = VectorXd::Zero(N);\n\t\tthis->dfdx(u, gradient);\n\t\th.setZero();\n\t\t//cout << \"g \" << gradient(0) << endl;\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tcout << \"rows = \" << pmatrix.rows() << endl;\n\t\tcout << \"cols = \" << pmatrix.cols() << endl;\n\t\tif(kin) {\n\t\t\tVectorXd w = (pmatrix * x).cwise().inverse().cwise().square();\n\t\t\tcout << \"els = \" << w.rows() << endl;\n\t\t\tfor(int k = 0; k < N; k++) {\n\t\t\t\tfor(int l = 0; l < N; l++) {\n\t\t\t\t\tfor(int i = 0; i < pmatrix.rows(); i++) {\n\t\t\t\t\t\tif(du) \n\t\t\t\t\t\t\th(l,k) += w(i) * pmatrix(i,l) * pmatrix(i,k) * x(k) * x(l);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\th(l,k) += w(i) * pmatrix(i,l) * pmatrix(i,k);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\tfor(int k = 0; k < N; k++) {\n\t\t\tfor(int l = 0; l < N; l++) {\n\t\t\t\tif((k == l) and du)\n\t\t\t\t\th(k,l) += gradient(k);\n\t\t\t\tif(light) {\n\t\t\t\t\tfor(int i = 0; i < rho2dmatrix.rows(); i++) {\n\t\t\t\t\t\tif(du)\n\t\t\t\t\t\t\th(k,l) += 2 * rho2dmatrix(i,l) * rho2dmatrix(i,k) / pow(rho2d_error(i), 2) * x(k) * x(l);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\th(k,l) += 2 * rho2dmatrix(i,l) * rho2dmatrix(i,k) / pow(rho2d_error(i), 2);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(norm) {\n\t\t\t\t\tif(du)\n\t\t\t\t\t\th(k, l) += 2/pow(error_x, 2) * x(k) * x(l);\n\t\t\t\t\telse\n\t\t\t\t\t\th(k, l) += 2/pow(error_x, 2);\n\t\t\t\t}\n\t\t\t\t//cout << \"h \" << h(k,l) << endl;\n\t\t\t} \n\t\t} \n\t\t//MatrixXd::Map(_h.data().begin(), _h.size2(), _h.size1()) = h;\n\t}\n\n\tdouble  _likelihood(double_vector _u) {\n\t\tMap<VectorXd> u = VectorXd::Map(_u.data().begin(), _u.size());\n\t\treturn likelihood(u);\n\t}\n\t// return f(x) to optimize\n\ttemplate<class T>\n\tdouble likelihood(T& u) {\n\t\t//VectorXd u = VectorXd::Map(_u.data().begin(), _u.size());\n\t\tVectorXd x = u.cwise().exp();\n\t\tdouble total = x.sum();\n\t\tVectorXd xn = x/total;\n\t\tVectorXd rho2d = rho2dmatrix * x;\n\t\t//cout << \"cols \" << pmatrix.cols() << endl;\n\t\t//double logLkinematics = (pmatrix * x).cwise().log().sum() - pmatrix.rows() * log(x.sum());\n\t\tdouble logLkinematics = (pmatrix * xn).cwise().log().sum();// - pmatrix.rows() * log(x.sum());\n\t\t// + 52082.8 + 1500;\n\t\tdouble logLnorm = -pow((1.000001-x.sum())/error_x, 2);\n\t\tdouble logLdensity = -((rho2d_target-rho2d).cwise()/rho2d_error).cwise().pow(2).sum();\n\t\t//cout << \"u = \" << u << endl;\n\t\t//cout << \"x = \" << x << endl;\n\t\t//cout << \">\" << logLkinematics << \" \" << logLnorm << \" \" << logLdensity << endl;\n\t\t//assert(0);\n\t\t//double entropy = -k * (x.cwise() * x.cwise().log()).sum();\n\t\t//return logLkinematics + logLnorm + logLdensity;\n\t\tdouble logL = 0;\n\t\tlogL += -entropy_scale * (x.cwise() * x.cwise().log()).sum();\n\t\tif(kin)\n\t\t\tlogL += logLkinematics;\n\t\tif(light)\n\t\t\tlogL += logLdensity;\n\t\tif(norm)\n\t\t\tlogL += logLnorm ;\n\t\treturn logL;\n\t\t\n\t\t//return logLdensity;// - entropy; // logL \\propto -entropy.. ?\n\t\t//return 1; //logLnorm;// - entropy; // logL \\propto -entropy.. ?\n\t\t//return logLdensity;\n\t\t//return 0;\n\t\t//return logLkinematics;\n\t\t//-sum((rho2d_true-rho2d)**2/rho2d_error**2)*fudgefactor\n\t}\n\t\n\t// gradient\n\tvoid _dfdx(double_vector _u, double_vector _gradient) {\n\t\tVectorXd u = VectorXd::Map(_u.data().begin(), _u.size());\n\t\tMap<VectorXd> gradient = VectorXd::Map(_gradient.data().begin(), _gradient.size());\n\t\tdfdx(u, gradient);\n\t}\n\t\n\ttemplate<class T1, class T2>\n\tvoid dfdx(T1& u, T2& gradient) {\n\t\tVectorXd x = u.cwise().exp();\n\t\tVectorXd rho2d = rho2dmatrix * x;\n\t\t/*g1 =  -sum(dpidxk / pi, axis=1)\n\t\tgu = -(2*(1.001-sum(u))/error_x**2)\n\t\tg2 = -sum(2*(rho2d_true-rho2d)/rho2d_error**2 *rho2ds, axis=1) * fudgefactor\n\t\tg = g1*u+gu*u# -g2 #-(-g1+g2)\n\t\tg += g2*u*/\n\t\tVectorXd pi = (pmatrix * x);\n\t\t//pmatrix.cwise() / pi;\n\t\tVectorXd t = pi.cwise().inverse();\n\t\tVectorXd g1 = -pmatrix.transpose() * t;\n\t\tg1 = g1.cwise() + pmatrix.rows() * 1/(x.sum()); // * x;\n\t\tVectorXd gu = -2*(1.000001-x.sum())/pow(error_x,2) * x;\n\t\tt = (rho2d_target-rho2d).cwise()/rho2d_error.cwise().pow(2) * -2;\n\t\tVectorXd g2 = rho2dmatrix.transpose() * t;\n\t\t//VectorXd g(g2.size());\n\t\tgradient.setZero();\n\t\tgradient = entropy_scale * ((x.cwise().log().cwise()+1).cwise() * x);\n\t\tif(kin)\n\t\t\tgradient += g1.cwise()*x;\n\t\tif(light)\n\t\t\tgradient += g2.cwise()*x;\n\t\tif(norm)\n\t\t\tgradient += gu;\n\n\t\t//VectorXd::Map(_gradient.data().begin(), _gradient.size()) = g;\n\t\t//VectorXd::Map(_gradient.data().begin(), _gradient.size()) = g2.cwise()*x;\n\t\t\n\t\t/*VectorXd::Map(_g1.data().begin(), _g1.size()) = g1.cwise()*x;\n\t\tVectorXd::Map(_gu.data().begin(), _gu.size()) = gu;\n\t\tVectorXd::Map(_g2.data().begin(), _g2.size()) = g2.cwise()*x;*/\n\t}\n\t\n\tdouble f_and_gradient(double_vector x, double &fx, double_vector &gradientvector) {\n\t\treturn 0.;\n\t}\n\tMatrixXd pmatrix;\n\tMatrixXd rho2dmatrix;\n\tVectorXd orbitweights;\n\tVectorXd rho2d_target;\n\tVectorXd rho2d_error;\n\tdouble error_x;\n\tdouble entropy_scale;\n\tdouble k;\n\tbool kin, light, norm;\n};\ntemplate<class F>\ndouble nlopt_wrapper(unsigned n, const double *x, double *grad, void *data) {\n\tF *opt = (F*)data;\n\treturn opt->f(n, x, grad);\n}\n\n\n};", "meta": {"hexsha": "5d63d661c7f35325f3e26aa6c8315b48ce26d180", "size": 23595, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/optimization_schw.hpp", "max_stars_repo_name": "maartenbreddels/mab", "max_stars_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T04:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T04:10:34.000Z", "max_issues_repo_path": "gdfast/src/optimization_schw.hpp", "max_issues_repo_name": "maartenbreddels/mab", "max_issues_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gdfast/src/optimization_schw.hpp", "max_forks_repo_name": "maartenbreddels/mab", "max_forks_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3219178082, "max_line_length": 320, "alphanum_fraction": 0.6158508159, "num_tokens": 7852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5186868575306274}}
{"text": "/*\n * chaotic_system.cpp\n *\n * This example demonstrates how one can use odeint to determine the Lyapunov\n * exponents of a chaotic system namely the well known Lorenz system. Furthermore,\n * it shows how odeint interacts with boost.range.\n *\n * Copyright 2011-2012 Karsten Ahnert\n * Copyright 2011-2013 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#include <boost/array.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\n#include \"gram_schmidt.hpp\"\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n\nconst double sigma = 10.0;\nconst double R = 28.0;\nconst double b = 8.0 / 3.0;\n\n//[ system_function_without_perturbations\nstruct lorenz\n{\n    template< class State , class Deriv >\n    void operator()( const State &x_ , Deriv &dxdt_ , double t ) const\n    {\n        typename boost::range_iterator< const State >::type x = boost::begin( x_ );\n        typename boost::range_iterator< Deriv >::type dxdt = boost::begin( dxdt_ );\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//]\n\n\n\n//[ system_function_with_perturbations\nconst size_t n = 3;\nconst size_t num_of_lyap = 3;\nconst size_t N = n + n*num_of_lyap;\n\ntypedef boost::array< double , N > state_type;\ntypedef boost::array< double , num_of_lyap > lyap_type;\n\nvoid lorenz_with_lyap( const state_type &x , state_type &dxdt , double t )\n{\n    lorenz()( x , dxdt , t );\n\n    for( size_t l=0 ; l<num_of_lyap ; ++l )\n    {\n        const double *pert = x.begin() + 3 + l * 3;\n        double *dpert = dxdt.begin() + 3 + l * 3;\n        dpert[0] = - sigma * pert[0] + 10.0 * pert[1];\n        dpert[1] = ( R - x[2] ) * pert[0] - pert[1] - x[0] * pert[2];\n        dpert[2] = x[1] * pert[0] + x[0] * pert[1] - b * pert[2];\n    }\n}\n//]\n\n\n\n\n\nint main( int argc , char **argv )\n{\n    state_type x;\n    lyap_type lyap;\n\n    fill( x.begin() , x.end() , 0.0 );\n    x[0] = 10.0 ; x[1] = 10.0 ; x[2] = 5.0;\n\n    const double dt = 0.01;\n\n    //[ integrate_transients_with_range\n    // explicitly choose range_algebra to override default choice of array_algebra\n    runge_kutta4< state_type , double , state_type , double , range_algebra > rk4;\n\n    // perform 10000 transient steps\n    integrate_n_steps( rk4 , lorenz() , std::make_pair( x.begin() , x.begin() + n ) , 0.0 , dt , 10000 );\n    //]\n\n    //[ lyapunov_full_code\n    fill( x.begin()+n , x.end() , 0.0 );\n    for( size_t i=0 ; i<num_of_lyap ; ++i ) x[n+n*i+i] = 1.0;\n    fill( lyap.begin() , lyap.end() , 0.0 );\n\n    double t = 0.0;\n    size_t count = 0;\n    while( true )\n    {\n\n        t = integrate_n_steps( rk4 , lorenz_with_lyap , x , t , dt , 100 );\n        gram_schmidt< num_of_lyap >( x , lyap , n );\n        ++count;\n\n        if( !(count % 100000) )\n        {\n            cout << t;\n            for( size_t i=0 ; i<num_of_lyap ; ++i ) cout << \"\\t\" << lyap[i] / t ;\n            cout << endl;\n        }\n    }\n    //]\n\n    return 0;\n}\n", "meta": {"hexsha": "607846898a3e62fe60452b2a4a055e12e88de32e", "size": 3087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/chaotic_system.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/chaotic_system.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/chaotic_system.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 25.725, "max_line_length": 105, "alphanum_fraction": 0.5853579527, "num_tokens": 1019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5186868568131529}}
{"text": "#include <VolViz/VolViz.h>\n\n#include <Eigen/Core>\n#include <igl/readOBJ.h>\n#include <igl/readOFF.h>\n#include <igl/readPLY.h>\n#include <igl/readSTL.h>\n\n#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <thread>\n\nauto generateVolume();\n\nauto generateVolume() {\n  using namespace VolViz;\n  using namespace VolViz::literals;\n  Size3 const size(256, 256, 128);\n  auto const nVoxels = size(0) * size(1) * size(2);\n\n  std::vector<Color> data;\n  data.reserve(3 * nVoxels);\n  Color c = Colors::Black();\n  for (unsigned int z = 0; z < size(2); ++z) {\n    c(2) = (static_cast<float>(z) / static_cast<float>(size(2) - 1));\n    for (unsigned int y = 0; y < size(1); ++y) {\n      c(1) = (static_cast<float>(y) / static_cast<float>(size(1) - 1));\n      for (unsigned int x = 0; x < size(0); ++x) {\n        c(0) = (static_cast<float>(x) / static_cast<float>(size(0) - 1));\n        data.push_back(c);\n      }\n    }\n  }\n\n  VolumeDescriptor v;\n  v.size = size;\n  v.voxelSize = {{100_um, 100_um, 200_um}};\n  v.type = VolumeType::ColorRGB;\n\n  return std::make_pair(v, data);\n}\n\nint main(int argc, char **argv) {\n  using namespace VolViz;\n  using namespace VolViz::literals;\n  using Eigen::Vector3d;\n  using Vertices = Eigen::MatrixXd;\n  using Triangles = Eigen::MatrixXi;\n\n  if (argc != 2) {\n    std::cerr << \"Usage: \" << argv[0] << \" meshFile\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  auto f = std::ifstream(argv[1]);\n  auto const filename = std::string(argv[1]);\n  auto const ext = filename.substr(filename.size() - 3, 3);\n  std::cout << \"Loading mesh \" << argv[1] << \"... \" << std::flush;\n  Vertices V;\n  Triangles T;\n  if (ext == \"off\")\n    igl::readOFF(filename, V, T);\n  else if (ext == \"ply\")\n    igl::readPLY(filename, V, T);\n  else if (ext == \"stl\") {\n    Vertices N;\n    igl::readSTL(filename, V, T, N);\n  } else if (ext == \"obj\")\n    igl::readOBJ(filename, V, T);\n  else {\n    std::cerr << std::endl << \"Unrecognized mesh format: \" << ext << std::endl;\n    return EXIT_FAILURE;\n  }\n  std::cout << \"done.\" << std::endl;\n  std::cout << V.rows() << \" vertices, \" << T.rows() << \" triangles.\"\n            << std::endl;\n\n  Eigen::Vector3d const min = V.colwise().minCoeff();\n  Eigen::Vector3d const max = V.colwise().maxCoeff();\n\n  Length meshScale = 5_cm;\n\n  std::cout << \"bbox: \" << min.transpose() << \" - \" << max.transpose()\n            << std::endl;\n  std::cout << \"bbox size: \"\n            << ((max - min).transpose() * static_cast<double>(meshScale / 1_mm))\n            << \" mm\" << std::endl;\n\n  //  Eigen::MatrixXd V(3, 3);\n  //  V << 0, 1, 0, -1, -1, 0, 1, -1, 0;\n  //  Eigen::MatrixXi T(1, 3);\n  //  T << 0, 1, 2;\n\n  auto viewer = Visualizer{};\n\n  // Add mesh\n  MeshDescriptor mesh;\n  mesh.vertices = V.cast<float>();\n  mesh.indices = T.cast<std::uint32_t>();\n  mesh.movable = true;\n  mesh.scale = 50_mm;\n  mesh.color = Colors::White();\n  viewer.addGeometry(\"Mesh\", mesh);\n\n  viewer.showGrid = true;\n  viewer.backgroundColor = (Colors::Magenta() + Colors::Cyan()) / 2.0;\n\n  Light light;\n  light.ambientFactor = 1.0f;\n  light.color = Colors::White();\n  light.position = PositionH(1, 1, 1, 0);\n\n  viewer.addLight(0, light);\n\n  light.position = PositionH(2, 1, 1, 0);\n  viewer.addLight(1, light);\n\n  light.position = PositionH(1, 2, 1, 0);\n  viewer.addLight(2, light);\n\n  viewer.scale = 1_mm;\n\n  AxisAlignedPlaneDescriptor plane;\n  plane.axis = Axis::X;\n  // plane.color = Colors::Green();\n  plane.color = Colors::White();\n  plane.intercept = 0_mm;\n\n  viewer.addGeometry(\"X-Plane\", plane);\n\n  plane.axis = Axis::Y;\n  // plane.color = Colors::Blue();\n  plane.color = Colors::White();\n  plane.intercept = 0_mm;\n  viewer.addGeometry(\"Y-Plane\", plane);\n\n  plane.axis = Axis::Z;\n  // plane.color = Colors::Red();\n  plane.color = Colors::White();\n  plane.intercept = 0_mm;\n  viewer.addGeometry(\"Z-Plane\", plane);\n\n  // cube\n  CubeDescriptor cube;\n  cube.color = Colors::Magenta();\n  cube.position = {11.5f, 11.5f, 11.5f};\n  viewer.addGeometry(\"Cube\", cube);\n\n  std::cout << \"Generating volume... \" << std::flush;\n  auto const vol = generateVolume();\n  std::cout << \"done.\" << std::endl;\n\n  viewer.setVolume(vol.first, as_span(vol.second));\n\n  viewer.enableMultithreading();\n  viewer.start();\n\n  std::thread workerThread([&viewer, &mesh, &cube]() {\n    using Clock = std::chrono::steady_clock;\n    using namespace std::chrono_literals;\n    auto constexpr updateIntervall = 1s / 30.f;\n    int count{0};\n    while (viewer) {\n      auto const t0 = Clock::now();\n      mesh.vertices *= count < 10 ? 1.01f : 0.99f;\n      cube.position[0] = static_cast<float>(count - 10) * 12.8f / 10.f;\n      viewer.updateGeometry(\"Cube\", cube);\n      viewer.updateGeometry(\"Mesh\", mesh);\n      if (++count > 20) count = 0;\n      auto const timeLeft = -(Clock::now() - t0) + updateIntervall;\n      if (timeLeft > 0s) std::this_thread::sleep_for(timeLeft);\n    }\n  });\n\n  viewer.renderAtFPS(60);\n\n  workerThread.join();\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "b744e3b6e71c7a3416be2b3440019fa9b37eda97", "size": 4930, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/VolVisualizer.cpp", "max_stars_repo_name": "ithron/VolViz", "max_stars_repo_head_hexsha": "e79f36563d908d9ba1bd71c3e760792521dd5e7a", "max_stars_repo_licenses": ["MIT"], "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/VolVisualizer.cpp", "max_issues_repo_name": "ithron/VolViz", "max_issues_repo_head_hexsha": "e79f36563d908d9ba1bd71c3e760792521dd5e7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2016-06-09T07:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-28T12:23:59.000Z", "max_forks_repo_path": "Examples/VolVisualizer.cpp", "max_forks_repo_name": "ithron/VolViz", "max_forks_repo_head_hexsha": "e79f36563d908d9ba1bd71c3e760792521dd5e7a", "max_forks_repo_licenses": ["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.0879120879, "max_line_length": 80, "alphanum_fraction": 0.6036511156, "num_tokens": 1547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5186868459244315}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    int n, m; cin >> n >> m;\n    vector<pair<long long int, long long int>> v(n);\n    for (int i = 0; i < n; i++) cin >> v[i].first >> v[i].second;\n    sort(v.begin(), v.end());\n    cpp_int sum = 0;\n    long long int cnt = 0;\n    for (int i = 0; i < n; i++) {\n        if (cnt + v[i].second > m) {\n            sum += (m - cnt) * v[i].first;\n            break;\n        }\n        else sum += v[i].second * v[i].first, cnt += v[i].second;\n    }\n    cout << sum << endl;\n\n}\n", "meta": {"hexsha": "2228f7f888197763f2a7f5aa798ce96d03975d2f", "size": 662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc121/c/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/abc121/c/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/abc121/c/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": 26.48, "max_line_length": 65, "alphanum_fraction": 0.5287009063, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919830720203, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5186868452069566}}
{"text": "#pragma once\n\n#include <boost/operators.hpp>\n#include <cassert>\n#include <tuple>   // import std::tie()\n#include <utility> // import std::move\n\nnamespace recti\n{\n\n\n/**\n * @brief vector2\n *\n */\ntemplate <typename T = int>\nclass vector2\n    : boost::totally_ordered<vector2<T>,\n          boost::additive<vector2<T>, boost::multiplicative<vector2<T>, T>>>\n// note: private inheritance is OK here!\n{\n  private:\n    T _x;\n    T _y;\n\n  public:\n    /**\n     * @brief\n     *\n     */\n    constexpr vector2(T&& x, T&& y) noexcept\n        : _x {std::move(x)}\n        , _y {std::move(y)}\n    {\n    }\n\n    /**\n     * @brief\n     *\n     */\n    constexpr vector2(const T& x, const T& y)\n        : _x {x}\n        , _y {y}\n    {\n    }\n\n    /**\n     * @brief\n     *\n     * @return constexpr const T&\n     */\n    [[nodiscard]] constexpr auto x() const noexcept -> const T&\n    {\n        return this->_x;\n    }\n\n    /**\n     * @brief\n     *\n     * @return constexpr const T&\n     */\n    [[nodiscard]] constexpr auto y() const noexcept -> const T&\n    {\n        return this->_y;\n    }\n\n    /**\n     * @brief\n     *\n     * @param rhs\n     * @return constexpr vector2&\n     */\n    [[nodiscard]] constexpr auto cross(const vector2& rhs) const -> T\n    {\n        return this->_x * rhs._y - rhs._x * this->_y;\n    }\n\n    /**\n     * @brief\n     *\n     * @param rhs\n     * @return constexpr vector2&\n     */\n    constexpr auto operator+=(const vector2& rhs) -> vector2&\n    {\n        this->_x += rhs.x();\n        this->_y += rhs.y();\n        return *this;\n    }\n\n    /**\n     * @brief\n     *\n     * @param rhs\n     * @return constexpr vector2&\n     */\n    constexpr auto operator-=(const vector2& rhs) -> vector2&\n    {\n        this->_x -= rhs.x();\n        this->_y -= rhs.y();\n        return *this;\n    }\n\n    /**\n     * @brief\n     *\n     * @param alpha\n     * @return constexpr vector2&\n     */\n    constexpr auto operator*=(const T& alpha) -> vector2&\n    {\n        this->_x *= alpha;\n        this->_y *= alpha;\n        return *this;\n    }\n\n    /**\n     * @brief\n     *\n     * @param alpha\n     * @return constexpr vector2&\n     */\n    constexpr auto operator/=(const T& alpha) -> vector2&\n    {\n        this->_x /= alpha;\n        this->_y /= alpha;\n        return *this;\n    }\n\n    /**\n     * @brief\n     *\n     * @param rhs\n     * @return true\n     * @return false\n     */\n    constexpr auto operator==(const vector2<T>& rhs) const -> bool\n    {\n        return std::tie(this->x(), this->y()) == std::tie(rhs.x(), rhs.y());\n    }\n\n    /**\n     * @brief\n     *\n     * @param rhs\n     * @return true\n     * @return false\n     */\n    constexpr auto operator<(const vector2<T>& rhs) const -> bool\n    {\n        return std::tie(this->x(), this->y()) < std::tie(rhs.x(), rhs.y());\n    }\n};\n\n\n/**\n * @brief 2D point\n *\n * @tparam T1\n * @tparam T2\n */\n#pragma pack(push, 1)\ntemplate <typename T1, typename T2 = T1>\nclass point : boost::totally_ordered<point<T1, T2>,\n                  boost::additive2<point<T1, T2>, vector2<T1>>>\n{\n  protected:\n    T1 _x; //!< x coordinate\n    T2 _y; //!< y coordinate\n\n  public:\n    /**\n     * @brief Construct a new point object\n     *\n     * @param x\n     * @param y\n     */\n    constexpr point(T1&& x, T2&& y) noexcept\n        : _x {std::move(x)}\n        , _y {std::move(y)}\n    {\n    }\n\n    /**\n     * @brief Construct a new point object\n     *\n     * @param x\n     * @param y\n     */\n    constexpr point(const T1& x, const T2& y)\n        : _x {x}\n        , _y {y}\n    {\n    }\n\n\n    /**\n     * @brief\n     *\n     * @return const T1&\n     */\n    [[nodiscard]] constexpr auto x() const noexcept -> const T1&\n    {\n        return this->_x;\n    }\n\n    /**\n     * @brief\n     *\n     * @return const T2&\n     */\n    [[nodiscard]] constexpr auto y() const noexcept -> const T2&\n    {\n        return this->_y;\n    }\n\n    /**\n     * @brief\n     *\n     * @param rhs\n     * @return constexpr point&\n     */\n    constexpr auto operator+=(const vector2<T1>& rhs) -> point&\n    {\n        this->_x += rhs.x();\n        this->_y += rhs.y();\n        return *this;\n    }\n\n    /**\n     * @brief\n     *\n     * @param rhs\n     * @return constexpr point&\n     */\n    constexpr auto operator-=(const vector2<T1>& rhs) -> point&\n    {\n        this->_x -= rhs.x();\n        this->_y -= rhs.y();\n        return *this;\n    }\n\n    /**\n     * @brief\n     *\n     * @param rhs\n     * @return vector2<T1>\n     */\n    constexpr auto operator-(const point& rhs) const -> vector2<T1>\n    {\n        return {this->x() - rhs.x(), this->y() - rhs.y()};\n    }\n\n    /**\n     * @brief\n     *\n     * @tparam U1\n     * @tparam U2\n     * @param rhs\n     * @return true\n     * @return false\n     */\n    template <typename U1, typename U2>\n    constexpr auto operator<(const point<U1, U2>& rhs) const -> bool\n    {\n        return std::tie(this->x(), this->y()) < std::tie(rhs.x(), rhs.y());\n    }\n\n\n    /**\n     * @brief\n     *\n     * @tparam U1\n     * @tparam U2\n     * @param rhs\n     * @return true\n     * @return false\n     */\n    template <typename U1, typename U2>\n    constexpr auto operator==(const point<U1, U2>& rhs) const -> bool\n    {\n        return std::tie(this->x(), this->y()) == std::tie(rhs.x(), rhs.y());\n    }\n\n    /**\n     * @brief\n     *\n     * @return point<T2, T1>\n     */\n    [[nodiscard]] constexpr auto flip() const -> point<T2, T1>\n    {\n        return {this->y(), this->x()};\n    }\n\n    /**\n     * @brief\n     *\n     * @tparam Stream\n     * @tparam T1\n     * @tparam T2\n     * @param out\n     * @param p\n     * @return Stream&\n     */\n    template <class Stream>\n    friend auto operator<<(Stream& out, const point& p) -> Stream&\n    {\n        out << '(' << p.x() << \", \" << p.y() << ')';\n        return out;\n    }\n};\n#pragma pack(pop)\n\n/**\n * @brief 2D point\n *\n * @tparam T1\n * @tparam T2\n */\n#pragma pack(push, 1)\ntemplate <typename T1, typename T2 = T1>\nclass dualpoint : public point<T1, T2>\n{\n  public:\n    /**\n     * @brief\n     *\n     * @return const T1&\n     */\n    constexpr auto y() const -> const T1& // override intentionally\n    {\n        return this->_x;\n    }\n\n    /**\n     * @brief\n     *\n     * @return const T2&\n     */\n    constexpr auto x() const -> const T2& // override intentionally\n    {\n        return this->_y;\n    }\n};\n#pragma pack(pop)\n\n\n/**\n * @brief adapter for containers of point\n *\n * @tparam iter\n */\ntemplate <typename iterator>\nclass dual_iterator : public iterator\n{\n    using value_type = typename iterator::value_type;\n    using T1 = decltype(std::declval(iterator::value_type).x());\n    using T2 = decltype(std::declval(iterator::value_type).y());\n\n    constexpr dual_iterator(iterator&& a)\n        : iterator {std::forward<iterator>(a)}\n    {\n    }\n\n    constexpr auto operator*() const noexcept -> const dualpoint<T2, T1>&\n    {\n        return dualpoint<T2, T1> {};\n        // return std::reinterpret_cast<const dualpoint<T2,\n        // T1>&>(*iterator::operator*());\n    }\n\n    constexpr auto operator*() noexcept -> dualpoint<T2, T1>&\n    {\n        return dualpoint<T2, T1> {};\n        // return std::reinterpret_cast<dualpoint<T2,\n        // T1>&>(*iterator::operator*());\n    }\n};\n\n\n/**\n * @brief Interval\n *\n * @tparam T\n */\n#pragma pack(push, 1)\ntemplate <typename T = int>\nclass interval : boost::totally_ordered<interval<T>>\n{\n  private:\n    T _lower; //> lower bound\n    T _upper; //> upper bound\n\n  public:\n    /**\n     * @brief Construct a new interval object\n     *\n     * @param lower\n     * @param upper\n     */\n    constexpr interval(T&& lower, T&& upper) noexcept\n        : _lower {std::move(lower)}\n        , _upper {std::move(upper)}\n    {\n        assert(!(_upper < _lower));\n    }\n\n    /**\n     * @brief Construct a new interval object\n     *\n     * @param lower\n     * @param upper\n     */\n    constexpr interval(const T& lower, const T& upper)\n        : _lower {lower}\n        , _upper {upper}\n    {\n        assert(!(_upper < _lower));\n    }\n\n    /**\n     * @brief\n     *\n     * @return const T&\n     */\n    [[nodiscard]] constexpr auto lower() const -> const T&\n    {\n        return this->_lower;\n    }\n\n    /**\n     * @brief\n     *\n     * @return const T&\n     */\n    [[nodiscard]] constexpr auto upper() const -> const T&\n    {\n        return this->_upper;\n    }\n\n    /**\n     * @brief\n     *\n     * @return constexpr T\n     */\n    [[nodiscard]] constexpr auto len() const -> T\n    {\n        return this->upper() - this->lower();\n    }\n\n    /**\n     * @brief\n     *\n     * @param rhs\n     * @return true\n     * @return false\n     */\n    constexpr auto operator==(const interval& rhs) const -> bool\n    {\n        return this->lower() == rhs.lower() && this->upper() == rhs.upper();\n    }\n\n    /**\n     * @brief\n     *\n     * @param rhs\n     * @return true\n     * @return false\n     */\n    constexpr auto operator<(const interval& rhs) const -> bool\n    {\n        return this->upper() < rhs.lower();\n    }\n\n    /**\n     * @brief\n     *\n     * @tparam U\n     * @param a\n     * @return true\n     * @return false\n     */\n    template <typename U>\n    [[nodiscard]] constexpr auto contains(const interval<U>& a) const -> bool\n    {\n        return !(a.lower() < this->lower() || this->upper() < a.upper());\n    }\n\n    /**\n     * @brief\n     *\n     * @param x\n     * @return true\n     * @return false\n     */\n    [[nodiscard]] constexpr auto contains(const T& a) const -> bool\n    {\n        return !(a < this->lower() || this->upper() < a);\n    }\n};\n#pragma pack(pop)\n\n\n/**\n * @brief Rectangle (Rectilinear)\n *\n * @tparam T\n * @todo use \"__attribute__((aligned(0)))\" to align struct 'rectangle<int>' to 0\n * bytes\n */\n#pragma pack(push, 1)\ntemplate <typename T>\nstruct rectangle : point<interval<T>>\n{\n    /**\n     * @brief Construct a new rectangle object\n     *\n     * @param x\n     * @param y\n     */\n    constexpr rectangle(interval<T>&& x, interval<T>&& y) noexcept\n        : point<interval<T>> {std::move(x), std::move(y)}\n    {\n    }\n\n    /**\n     * @brief Construct a new rectangle object\n     *\n     * @param x\n     * @param y\n     */\n    constexpr rectangle(const interval<T>& x, const interval<T>& y)\n        : point<interval<T>> {x, y}\n    {\n    }\n\n    /**\n     * @brief\n     *\n     * @param rhs\n     * @return true\n     * @return false\n     */\n    template <typename U1, typename U2>\n    [[nodiscard]] constexpr auto contains(const point<U1, U2>& rhs) const\n        -> bool\n    {\n        return this->x().contains(rhs.x()) && this->y().contains(rhs.y());\n    }\n\n    /**\n     * @brief\n     *\n     * @return point<T>\n     */\n    [[nodiscard]] constexpr auto lower() const -> point<T>\n    {\n        return {this->x().lower(), this->y().lower()};\n    }\n\n    /**\n     * @brief\n     *\n     * @return point<T>\n     */\n    [[nodiscard]] constexpr auto upper() const -> point<T>\n    {\n        return {this->x().upper(), this->y().upper()};\n    }\n\n    /**\n     * @brief\n     *\n     * @return constexpr T\n     */\n    [[nodiscard]] constexpr auto area() const -> T\n    {\n        return this->x().len() * this->y().len();\n    }\n\n    /**\n     * @brief\n     *\n     * @tparam Stream\n     * @tparam T\n     * @param out\n     * @param r\n     * @return Stream&\n     */\n    template <class Stream>\n    friend auto operator<<(Stream& out, const rectangle& r) -> Stream&\n    {\n        out << r.lower() << \" rectangle \" << r.upper();\n        return out;\n    }\n};\n#pragma pack(pop)\n\n\n/**\n * @brief Horizontal Line Segment\n *\n * @tparam T\n * @todo pack\n */\n#pragma pack(push, 1)\ntemplate <typename T>\nstruct hsegment : point<interval<T>, T>\n{\n    /**\n     * @brief Construct a new hsegment object\n     *\n     * @param x\n     * @param y\n     */\n    constexpr hsegment(interval<T>&& x, T&& y) noexcept\n        : point<interval<T>, T> {std::move(x), std::move(y)}\n    {\n    }\n\n    /**\n     * @brief Construct a new hsegment object\n     *\n     * @param x\n     * @param y\n     */\n    constexpr hsegment(const interval<T>& x, const T& y)\n        : point<interval<T>, T> {x, y}\n    {\n    }\n\n    /**\n     * @brief\n     *\n     * @tparam U\n     * @param rhs\n     * @return true\n     * @return false\n     */\n    template <typename U>\n    constexpr auto contains(const point<U>& rhs) const -> bool\n    {\n        return this->y() == rhs.y() && this->x().contains(rhs.x());\n    }\n};\n#pragma pack(pop)\n\n\n/**\n * @brief vsegment Line Segment\n *\n * @tparam T\n * @todo pack\n */\n#pragma pack(push, 1)\ntemplate <typename T>\nstruct vsegment : point<T, interval<T>>\n{\n    /**\n     * @brief Construct a new vsegment object\n     *\n     * @param x\n     * @param y\n     */\n    constexpr vsegment(T&& x, interval<T>&& y) noexcept\n        : point<T, interval<T>> {std::move(x), std::move(y)}\n    {\n    }\n\n    /**\n     * @brief Construct a new vsegment object\n     *\n     * @param x\n     * @param y\n     */\n    constexpr vsegment(const T& x, const interval<T>& y)\n        : point<T, interval<T>> {x, y}\n    {\n    }\n\n    /**\n     * @brief\n     *\n     * @tparam U\n     * @param rhs\n     * @return true\n     * @return false\n     */\n    template <typename U>\n    constexpr auto contains(const point<U>& rhs) const -> bool\n    {\n        return this->x() == rhs.x() && this->y().contains(rhs.y());\n    }\n};\n#pragma pack(pop)\n\n} // namespace recti\n", "meta": {"hexsha": "1f7118bebb1b9b8d5d691c7e24b1c672a8cff407", "size": 13146, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/recti/recti.hpp", "max_stars_repo_name": "luk036/physdes", "max_stars_repo_head_hexsha": "1a6a6c06a92798cc36d5efd70a968f545d406568", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-30T04:51:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-30T04:51:25.000Z", "max_issues_repo_path": "lib/include/recti/recti.hpp", "max_issues_repo_name": "luk036/physdes", "max_issues_repo_head_hexsha": "1a6a6c06a92798cc36d5efd70a968f545d406568", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-19T10:28:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-11T04:11:51.000Z", "max_forks_repo_path": "lib/include/recti/recti.hpp", "max_forks_repo_name": "luk036/physdes", "max_forks_repo_head_hexsha": "1a6a6c06a92798cc36d5efd70a968f545d406568", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-11T05:12:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-11T05:12:37.000Z", "avg_line_length": 18.8338108883, "max_line_length": 80, "alphanum_fraction": 0.4926973984, "num_tokens": 3648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5186406296207656}}
{"text": "\n#include <CGAL/trace.h>\n#include <CGAL/Timer.h>\n#include <iostream>\n#include <string>\n#include <fstream>\n\n\n#include <Eigen/Eigen>\n#include <Eigen/SVD>\n\nint main() {\n\n  std::ifstream file;\n  file.open(\"SVD_benchmark\");\n  if (!file)\n  {\n    CGAL_TRACE_STREAM << \"Error loading file!\\n\";\n    return 0;\n  }\n\n  int ite = 200000;\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd;\n  Eigen::Matrix3d u, v, cov, r;\n  Eigen::Vector3d w;\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 >> cov(j, k);\n      }\n    }\n  }\n\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\n    svd.compute( cov, Eigen::ComputeFullU | Eigen::ComputeFullV );\n    u = svd.matrixU(); v = svd.matrixV(); w = svd.singularValues();\n    r = v*u.transpose();\n  }\n  task_timer.stop();\n  file.close();\n\n  CGAL_TRACE_STREAM << \"done: \" << task_timer.time() << \"s\\n\";\n\n  return 0;\n}", "meta": {"hexsha": "ba6e332f2bfb46fa189230ae4ea0c1bd87fc6041", "size": 1039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh_deformation/benchmark/Surface_mesh_deformation/optimal_rotation/optimal_rotation_svd_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_svd_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_svd_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": 18.2280701754, "max_line_length": 67, "alphanum_fraction": 0.572666025, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.5186220152102383}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/include/functions/tan.hpp>\n\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <complex>\n#include <nt2/sdk/complex/complex.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/basic.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/i.hpp>\n\n#include <nt2/include/functions/mul_i.hpp>\n#include <nt2/include/functions/mul_minus_i.hpp>\n\nNT2_TEST_CASE_TPL ( tan,  NT2_REAL_TYPES)\n{\n  using nt2::tan;\n  using nt2::tag::tan_;\n  typedef std::complex<T> cT;\n  typedef typename nt2::meta::call<tan_(cT)>::type r_t;\n  typedef typename nt2:: meta::as_complex<T>::type wished_r_t;\n\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(nt2::tan(cT(nt2::Inf<T>())), cT(nt2::Nan<T>()), 10);\n  NT2_TEST_ULP_EQUAL(nt2::tan(cT(nt2::Minf<T>())), cT(nt2::Nan<T>()), 10);\n  NT2_TEST_ULP_EQUAL(nt2::tan(cT(1, 1)),std::tan(cT(1.0, 1.0)), 10);\n  NT2_TEST_ULP_EQUAL(nt2::tan(cT(1, 0.5)),std::tan(cT(1.0, 0.5)), 10);\n  NT2_TEST_ULP_EQUAL(nt2::tan(cT(0.5, 1)),std::tan(cT(0.5, 1.0)), 10);\n  NT2_TEST_ULP_EQUAL(nt2::tan(cT(0.5, 0.5)),std::tan(cT(0.5, 0.5)), 10);\n  NT2_TEST_ULP_EQUAL(nt2::tan(cT(0, 1)),std::tan(cT(0.0, 1.0)), 10);\n  NT2_TEST_ULP_EQUAL(nt2::tan(cT(0, 0.5)),std::tan(cT(0.0, 0.5)), 10);\n  NT2_TEST_ULP_EQUAL(nt2::tan(cT(0.5, 0)),std::tan(cT(0.5, 0.0)), 10);\n\n  const int N = 20;\n  cT inputs[N] =\n    { cT(nt2::Zero<T>(),nt2::Zero<T>()),cT(nt2::Inf<T>(),nt2::Zero<T>()),cT(nt2::Minf<T>(),nt2::Zero<T>()),cT(nt2::Nan<T>(),nt2::Zero<T>()),\n      cT(nt2::Zero<T>(),nt2::Inf<T>()), cT(nt2::Inf<T>(),nt2::Inf<T>()), cT(nt2::Minf<T>(),nt2::Inf<T>()), cT(nt2::Nan<T>(),nt2::Inf<T>()),\n      cT(nt2::Zero<T>(),nt2::Minf<T>()),cT(nt2::Inf<T>(),nt2::Minf<T>()),cT(nt2::Minf<T>(),nt2::Minf<T>()),cT(nt2::Nan<T>(),nt2::Minf<T>()),\n      cT(nt2::Zero<T>(),nt2::Nan<T>()), cT(nt2::Inf<T>(),nt2::Nan<T>()), cT(nt2::Minf<T>(),nt2::Nan<T>()), cT(nt2::Nan<T>(),nt2::Nan<T>()),\n      cT(nt2::Zero<T>(),nt2::Pi <T>()), cT(nt2::Inf<T>(),nt2::Pi <T>()), cT(nt2::Minf<T>(),nt2::Pi <T>()), cT(nt2::Nan<T>(),nt2::Pi<T>()),\n    };\n\n  for(int i=0; i < N; i++)\n   {\n     std::cout << \"-------------------\" << std::endl;\n     std::cout << \"inputs  \"<< inputs[i] << std::endl;\n     NT2_TEST_ULP_EQUAL(nt2::tan(-inputs[i]), -nt2::tan(inputs[i]), 3);\n     NT2_TEST_ULP_EQUAL(nt2::tan(inputs[i]), nt2::mul_minus_i(nt2::tanh(nt2::mul_i(inputs[i]))), 3);\n     std::cout << \"=================== \" << std::endl;\n   }\n\n\n } // end of test for floating_\n\n", "meta": {"hexsha": "0a8105c6ddbf27570d128f7b0911c744932c1da2", "size": 3415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/trigonometric/unit/scalar/tan.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/type/complex/trigonometric/unit/scalar/tan.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/type/complex/trigonometric/unit/scalar/tan.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 44.9342105263, "max_line_length": 140, "alphanum_fraction": 0.5806734993, "num_tokens": 1217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5185895848629279}}
{"text": "//Author: Dr. Shantanu Shahane\n#ifndef general_functions_H_ /* Include guard */\n#define general_functions_H_\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <float.h>\n#include <string.h>\n#include <iostream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n#include <fstream>\n#include <random>\n#include \"metis.h\"\n#include \"mpi.h\"\n#include <Eigen/Dense>\n#include <unsupported/Eigen/SparseExtra>\n#include <Eigen/SparseLU>\n#include <Eigen/OrderingMethods>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Spectra/GenEigsSolver.h>\n#include <Spectra/MatOp/SparseGenMatProd.h>\n#include <Spectra/GenEigsRealShiftSolver.h>\n#include <Spectra/MatOp/SparseGenRealShiftSolve.h>\nusing namespace std;\n\nEigen::VectorXcd calc_largest_magnitude_eigenvalue(Eigen::SparseMatrix<double, Eigen::RowMajor> &matrix);\n\nvoid does_file_exist(const char *, const char *);\n\nvoid check_mpi();\n\nvoid print_to_terminal(vector<bool> &a, const char *text);\n\nvoid print_to_terminal(vector<double> &a, int n_row, int n_col, const char *text);\n\nvoid print_to_terminal(vector<double> &a, const char *text);\n\nvoid print_to_terminal(vector<int> &a, const char *text);\n\nvoid print_to_terminal(Eigen::VectorXd &a, const char *text);\n\nvoid print_to_terminal(vector<vector<int>> &a, const char *text);\n\nvoid print_to_terminal(vector<pair<int, int>> &a, const char *text);\n\nvoid print_to_terminal(vector<int> &a, int n_row, int n_col, const char *text);\n\nvoid print_to_terminal(idx_t *elem_vert_row, idx_t *elem_vert_col, int n_row, const char *text);\n\nvoid print_to_terminal(vector<bool> &a, int n_row, int n_col, const char *text);\n\nvoid print_to_terminal(vector<int> &sp_row, vector<int> &sp_col, const char *text);\n\nvoid print_to_terminal(Eigen::MatrixXd &A, const char *text);\n\nvoid print_to_terminal(Eigen::MatrixXcd &A, const char *text);\n\nvoid print_to_terminal(Eigen::MatrixXi &A, const char *text);\n\nvoid print_to_terminal(Eigen::SparseMatrix<double, Eigen::RowMajor> &A, const char *text);\n\nvoid print_to_terminal(Eigen::SparseMatrix<int> &A, const char *text);\n\nvoid write_csv(vector<double> &vect, int nr, int nc, const char *file_name);\n\nvoid write_csv(vector<bool> &vect, int nr, int nc, const char *file_name);\n\nvoid write_csv(double *vect, int nr, int nc, const char *file_name);\n\nvoid write_csv(Eigen::MatrixXd &A, const char *file_name);\n\nvoid write_csv(Eigen::MatrixXcd &A, const char *file_name);\n\nvoid write_csv(Eigen::VectorXd &A, const char *file_name);\n\nvoid write_csv_benchmark(vector<double> &xyz_interp, Eigen::VectorXd &reference, Eigen::VectorXd &simulation, const char *file_name, int dimension);\n\nvoid write_csv_benchmark(vector<double> &xyz_interp, Eigen::VectorXd &simulation, const char *file_name, int dimension);\n\nvoid write_csv(vector<double> &xyz, vector<bool> &boundary_flag, int dim, const char *file_name);\n\nvoid write_csv(vector<double> &xyz, vector<bool> &boundary_flag, vector<bool> &periodic_bc_flag, int dim, const char *file_name);\n\nvoid write_csv(vector<double> &xyz, vector<bool> &boundary_flag, vector<bool> &periodic_bc_flag, vector<int> &periodic_bc_section, int dim, const char *file_name);\n\nvoid write_csv(vector<double> &xyz, vector<bool> &boundary_flag, Eigen::VectorXd &A_ana, Eigen::VectorXd &A_num, int dim, const char *file_name);\n\nvoid write_csv(Eigen::SparseMatrix<double, Eigen::RowMajor> &A, const char *file_name);\n\nvoid write_csv(Eigen::SparseMatrix<int> &A, const char *file_name);\n\nvoid write_csv(vector<int> &sp_row, vector<int> &sp_col, const char *file_name);\n\nvoid write_csv(vector<int> &sp_row, vector<double> &sp_val, const char *file_name);\n\nvoid write_csv(vector<vector<int>> &a, const char *file_name);\n\nvoid write_csv(vector<vector<double>> &a, const char *file_name);\n\nvoid write_csv(vector<tuple<int, int, double>> &a, const char *file_name);\n\nvoid write_csv(vector<int> &vect, int nr, int nc, const char *file_name);\n\nvoid k_smallest_elements(vector<double> &k_min_a, vector<int> &k_min_a_indices, vector<double> &a, int k);\n\nvector<int> argsort(const vector<double> &v);\n\nvector<double> calc_crowd_distance(vector<double> &x, vector<double> &y, vector<double> &z, int dim);\n\ndouble max_abs(Eigen::VectorXd &a);\n\nvoid cuthill_mckee_ordering(vector<vector<int>> &adjacency, vector<int> &order);\n\nvoid reverse_cuthill_mckee_ordering(vector<vector<int>> &adjacency, vector<int> &order);\n\ndouble vector_norm(vector<double> &a, int norm_type);\n\ndouble vector_norm(double *a, int size, int norm_type);\n\nvoid cross_product(double *result, double *u, double *v);\n\nvoid calc_max_l1_error(vector<double> &a1, vector<double> &a2, double &max_err, double &l1_err);\n\nvoid calc_max_l1_error(Eigen::VectorXd &a1, Eigen::VectorXd &a2, double &max_err, double &l1_err);\n\nvoid calc_max_l1_error(Eigen::VectorXd &a1, Eigen::VectorXd &a2, double &max_err_boundary, double &l1_err_boundary, double &max_err_internal, double &l1_err_internal, vector<bool> &boundary_flag);\n\nvoid calc_max_l1_relative_error(vector<double> &ana_val, vector<double> &num_val, double &max_err, double &l1_err);\n\nvoid calc_max_l1_relative_error(Eigen::VectorXd &ana_val, Eigen::VectorXd &num_val, double &max_err, double &l1_err);\n\nvoid calc_max_l1_relative_error(Eigen::VectorXd &ana_val, Eigen::VectorXd &num_val, double &max_err_boundary, double &l1_err_boundary, double &max_err_internal, double &l1_err_internal, vector<bool> &boundary_flag);\n\nvoid gauss_siedel_eigen(Eigen::SparseMatrix<double, Eigen::RowMajor> &matrix, Eigen::VectorXd &source, Eigen::VectorXd &field_old, int num_iter, double omega);\n\nEigen::SparseMatrix<double, Eigen::RowMajor> convert_csc_to_csr_eigen(Eigen::SparseMatrix<double, Eigen::ColMajor> &matrix);\n\nEigen::SparseMatrix<double, Eigen::ColMajor> convert_csr_to_csc_eigen(Eigen::SparseMatrix<double, Eigen::RowMajor> &matrix);\n\n#endif\n", "meta": {"hexsha": "335fe02e3043245292a9ee99160296caf1f68bfc", "size": 5847, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "header_files/general_functions.hpp", "max_stars_repo_name": "shahaneshantanu/memphys", "max_stars_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "header_files/general_functions.hpp", "max_issues_repo_name": "shahaneshantanu/memphys", "max_issues_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "header_files/general_functions.hpp", "max_forks_repo_name": "shahaneshantanu/memphys", "max_forks_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-07T00:32:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:32:37.000Z", "avg_line_length": 40.0479452055, "max_line_length": 215, "alphanum_fraction": 0.7689413374, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5185895806107502}}
{"text": "#pragma once\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\nusing namespace boost::numeric::ublas;\n\ntemplate <typename T>\nvoid fp2double(T x_fp, double &x, size_t &p) {\n    x = double((int32_t) x_fp) / (1ll << p);\n    //cout << \"fp2double(\" << x_fp << \",\" << p << \") = \" << x << endl;\n}\n\ntemplate <typename T>\nvoid double2fp(double x, T &x_fp, size_t &p) {\n    x_fp = (x * (1ll << p));\n    /*cout << \"double2fp(\" << x << \",\" << p << \") = \" << x_fp << endl;\n    // test:\n    double x_test = 99.99;\n    fp2double(x_fp, x_test, p);*/\n}\n\n\n// This assumes memory for M_fp has been allocated\ntemplate <typename T>\nvoid double_matrix2fp(matrix<double> &M, matrix<T> &M_fp, size_t precision) {\n    for (size_t i = 0; i < M.size1(); i++) {\n        for (size_t j = 0; j < M.size2(); j++) {\n        double2fp(M(i, j), M_fp(i, j), precision);\n        }\n    }\n}\n\n// This assumes memory for M_fp has been allocated\ntemplate <typename T>\nvoid fp_matrix2double(matrix<T> &M_fp, matrix<double> &M, size_t precision) {\n    for (size_t i = 0; i < M.size1(); i++) {\n        for (size_t j = 0; j < M.size2(); j++) {\n        fp2double(M_fp(i, j), M(i, j), precision);\n        }\n    }\n}\n", "meta": {"hexsha": "3f3de081b7d29d105b4c4df7fdc813635f710dbe", "size": 1246, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/src/fp.hpp", "max_stars_repo_name": "nikikilbertus/blind-justice", "max_stars_repo_head_hexsha": "2344609e55a2af20396ec042627ffed368e01e56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-06-11T21:12:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T18:49:16.000Z", "max_issues_repo_path": "c++/src/fp.hpp", "max_issues_repo_name": "nikikilbertus/blind-justice", "max_issues_repo_head_hexsha": "2344609e55a2af20396ec042627ffed368e01e56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-17T14:28:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T14:28:11.000Z", "max_forks_repo_path": "c++/src/fp.hpp", "max_forks_repo_name": "nikikilbertus/blind-justice", "max_forks_repo_head_hexsha": "2344609e55a2af20396ec042627ffed368e01e56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-06T08:46:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T15:39:26.000Z", "avg_line_length": 28.976744186, "max_line_length": 77, "alphanum_fraction": 0.577046549, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5185419093723376}}
{"text": "// Boost.Geometry\r\n// Unit Test\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// Licensed under the Boost Software License version 1.0.\r\n// http://www.boost.org/users/license.html\r\n\r\n\r\n#include <geometry_test_common.hpp>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/geometries.hpp>\r\n\r\n\r\nint test_main(int, char* [])\r\n{\r\n    typedef bg::model::point<double, 2, bg::cs::cartesian> point;\r\n    typedef bg::model::box<point> box;\r\n    typedef bg::model::linestring<point> linestring;\r\n    typedef bg::model::multi_linestring<linestring> mlinestring;\r\n    typedef bg::model::polygon<point> polygon;    \r\n    typedef bg::model::multi_polygon<polygon> mpolygon;\r\n\r\n    point p;\r\n    linestring ls;\r\n    mlinestring mls;\r\n    polygon po;\r\n    mpolygon mpo;\r\n\r\n    bg::read_wkt(\"POINT(0 0)\", p);\r\n    bg::read_wkt(\"LINESTRING(0 0,7 7,7 9)\", ls);\r\n    bg::read_wkt(\"MULTILINESTRING((0 0,7 7,7 9),(7 9, 9 9))\", mls);\r\n    bg::read_wkt(\"POLYGON((0 0,0 5,5 5,5 0,0 0),(1 1,4 1,4 4,1 4,1 1))\", po);\r\n    bg::read_wkt(\"MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0),(1 1,4 1,4 4,1 4,1 1)),((2 2,2 3,3 3,3 2,2 2)))\", mpo);\r\n\r\n    BOOST_CHECK_CLOSE(bg::perimeter(po), 32.0, 0.0001);\r\n    BOOST_CHECK_CLOSE(bg::area(mpo), 17.0, 0.0001);\r\n    BOOST_CHECK_CLOSE(bg::length(mls), 13.899494936611665, 0.0001);\r\n\r\n    BOOST_CHECK(bg::covered_by(p, po));\r\n    BOOST_CHECK(!bg::crosses(ls, mls));\r\n    BOOST_CHECK(!bg::equals(ls, mls));\r\n    BOOST_CHECK(bg::intersects(ls, po));\r\n    BOOST_CHECK(bg::relate(p, ls, bg::de9im::mask(\"F0F******\")));\r\n    BOOST_CHECK(bg::relation(mls, mpo).str() == \"101F00212\");\r\n    BOOST_CHECK(bg::within(po, mpo));\r\n    BOOST_CHECK(!bg::touches(mls, po));\r\n    \r\n    mpolygon res;\r\n    bg::intersection(po, mpo, res);\r\n    BOOST_CHECK_CLOSE(bg::area(res), 16.0, 0.0001);\r\n    bg::clear(res);\r\n    bg::union_(po, mpo, res);\r\n    BOOST_CHECK_CLOSE(bg::area(res), 17.0, 0.0001);\r\n    bg::clear(res);\r\n    bg::difference(mpo, po, res);\r\n    BOOST_CHECK_CLOSE(bg::area(res), 1.0, 0.0001);\r\n    bg::clear(res);\r\n    bg::sym_difference(mpo, po, res);\r\n    BOOST_CHECK_CLOSE(bg::area(res), 1.0, 0.0001);\r\n\r\n    BOOST_CHECK(bg::is_simple(ls));\r\n    BOOST_CHECK(bg::is_valid(mpo));\r\n\r\n    point c;\r\n    bg::centroid(mpo, c);\r\n    BOOST_CHECK_CLOSE(bg::distance(p, c), 3.5355339059327378, 0.0001);\r\n    BOOST_CHECK_CLOSE(bg::distance(mls, mpo), 0.0, 0.0001);\r\n    BOOST_CHECK_CLOSE(bg::distance(po, mpo), 0.0, 0.0001);\r\n\r\n    box b;\r\n    bg::envelope(mls, b);\r\n    BOOST_CHECK_CLOSE(bg::area(b), 81.0, 0.0001);\r\n\r\n    polygon h;\r\n    bg::convex_hull(mls, h);\r\n    BOOST_CHECK_CLOSE(bg::area(h), 9.0, 0.0001);\r\n\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "3a2e26737a90bb089eb9d79d32f086dd05ee33cc", "size": 2728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/minimal.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/minimal.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/geometry/test/minimal.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": 32.4761904762, "max_line_length": 110, "alphanum_fraction": 0.6180351906, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5185419070201035}}
{"text": "// Copyright (C) 2012  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n#include <dlib/svm.h>\n#include <dlib/rand.h>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n\n#include \"tester.h\"\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n\n    logger dlog(\"test.ranking\");\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename T>\n    void brute_force_count_ranking_inversions (\n        const std::vector<T>& x,\n        const std::vector<T>& y,\n        std::vector<unsigned long>& x_count,\n        std::vector<unsigned long>& y_count\n    )\n    {\n        x_count.assign(x.size(),0);\n        y_count.assign(y.size(),0);\n\n        for (unsigned long i = 0; i < x.size(); ++i)\n        {\n            for (unsigned long j = 0; j < y.size(); ++j)\n            {\n                if (x[i] <= y[j])\n                {\n                    x_count[i]++;\n                    y_count[j]++;\n                }\n            }\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_count_ranking_inversions()\n    {\n        print_spinner();\n        dlog << LINFO << \"in test_count_ranking_inversions()\";\n\n        dlib::rand rnd;\n        std::vector<int> x, y;\n        std::vector<unsigned long> x_count, y_count;\n        std::vector<unsigned long> x_count2, y_count2;\n        for (int iter = 0; iter < 5000; ++iter)\n        {\n            x.resize(rnd.get_random_32bit_number()%10);\n            y.resize(rnd.get_random_32bit_number()%10);\n            for (unsigned long i = 0; i < x.size(); ++i)\n                x[i] = ((int)rnd.get_random_32bit_number()%10) - 5;\n            for (unsigned long i = 0; i < y.size(); ++i)\n                y[i] = ((int)rnd.get_random_32bit_number()%10) - 5;\n\n            count_ranking_inversions(x, y, x_count, y_count);\n            brute_force_count_ranking_inversions(x, y, x_count2, y_count2);\n\n            DLIB_TEST(mat(x_count) == mat(x_count2));\n            DLIB_TEST(mat(y_count) == mat(y_count2));\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void dotest1()\n    {\n        print_spinner();\n        dlog << LINFO << \"in dotest1()\";\n\n        typedef matrix<double,4,1> sample_type;\n\n        typedef linear_kernel<sample_type> kernel_type;\n\n        svm_rank_trainer<kernel_type> trainer;\n\n\n        std::vector<ranking_pair<sample_type> > samples;\n\n        ranking_pair<sample_type> p;\n        sample_type samp;\n\n        samp = 0, 0, 0, 1; p.relevant.push_back(samp);\n        samp = 1, 0, 0, 0; p.nonrelevant.push_back(samp);\n        samples.push_back(p);\n\n        samp = 0, 0, 1, 0; p.relevant.push_back(samp);\n        samp = 1, 0, 0, 0; p.nonrelevant.push_back(samp);\n        samp = 0, 1, 0, 0; p.nonrelevant.push_back(samp);\n        samp = 0, 1, 0, 0; p.nonrelevant.push_back(samp);\n        samples.push_back(p);\n\n\n        trainer.set_c(10);\n\n        decision_function<kernel_type> df = trainer.train(samples);\n\n        dlog << LINFO << \"accuracy: \"<< test_ranking_function(df, samples);\n        matrix<double,1,2> res;\n        res = 1,1;\n        DLIB_TEST(equal(test_ranking_function(df, samples), res));\n\n        DLIB_TEST(equal(test_ranking_function(trainer.train(samples[1]), samples), res));\n\n        trainer.set_epsilon(1e-13);\n        df = trainer.train(samples);\n\n        dlog << LINFO << df.basis_vectors(0);\n        sample_type truew;\n        truew = -0.5, -0.5, 0.5, 0.5;\n        DLIB_TEST(length(truew - df.basis_vectors(0)) < 1e-10);\n\n        dlog << LINFO << \"accuracy: \"<< test_ranking_function(df, samples);\n        DLIB_TEST(equal(test_ranking_function(df, samples), res));\n\n        dlog << LINFO << \"cv-accuracy: \"<< cross_validate_ranking_trainer(trainer, samples,2);\n        DLIB_TEST(std::abs(cross_validate_ranking_trainer(trainer, samples,2)(0) - 0.7777777778) < 0.0001);\n\n        trainer.set_learns_nonnegative_weights(true);\n        df = trainer.train(samples);\n        truew = 0, 0, 1.0, 1.0;\n        dlog << LINFO << df.basis_vectors(0);\n        DLIB_TEST(length(truew - df.basis_vectors(0)) < 1e-10);\n        dlog << LINFO << \"accuracy: \"<< test_ranking_function(df, samples);\n        DLIB_TEST(equal(test_ranking_function(df, samples), res));\n\n\n        samples.clear();\n        samples.push_back(p);\n        samples.push_back(p);\n        samples.push_back(p);\n        samples.push_back(p);\n        dlog << LINFO << \"cv-accuracy: \"<< cross_validate_ranking_trainer(trainer, samples,4);\n        DLIB_TEST(equal(cross_validate_ranking_trainer(trainer, samples,4) , res));\n\n        df.basis_vectors(0) = 0;\n        dlog << LINFO << \"BAD RANKING:\" << test_ranking_function(df, samples);\n        DLIB_TEST(test_ranking_function(df, samples)(1) < 0.5);\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void dotest_sparse_vectors()\n    {\n        print_spinner();\n        dlog << LINFO << \"in dotest_sparse_vectors()\";\n\n        typedef std::map<unsigned long,double> sample_type;\n\n        typedef sparse_linear_kernel<sample_type> kernel_type;\n\n        svm_rank_trainer<kernel_type> trainer;\n\n\n        std::vector<ranking_pair<sample_type> > samples;\n\n        ranking_pair<sample_type> p;\n        sample_type samp;\n\n        samp[3] = 1; p.relevant.push_back(samp); samp.clear();\n        samp[0] = 1; p.nonrelevant.push_back(samp); samp.clear();\n        samples.push_back(p);\n\n        samp[2] = 1; p.relevant.push_back(samp); samp.clear();\n        samp[0] = 1; p.nonrelevant.push_back(samp); samp.clear();\n        samp[1] = 1; p.nonrelevant.push_back(samp); samp.clear();\n        samp[1] = 1; p.nonrelevant.push_back(samp); samp.clear();\n        samples.push_back(p);\n\n\n        trainer.set_c(10);\n\n        decision_function<kernel_type> df = trainer.train(samples);\n\n        matrix<double,1,2> res;\n        res = 1,1;\n\n        dlog << LINFO << \"accuracy: \"<< test_ranking_function(df, samples);\n        DLIB_TEST(equal(test_ranking_function(df, samples), res));\n\n        DLIB_TEST(equal(test_ranking_function(trainer.train(samples[1]), samples), res));\n\n        trainer.set_epsilon(1e-13);\n        df = trainer.train(samples);\n\n        dlog << LINFO << sparse_to_dense(df.basis_vectors(0));\n        sample_type truew;\n        truew[0] = -0.5;\n        truew[1] = -0.5;\n        truew[2] =  0.5;\n        truew[3] =  0.5;\n        DLIB_TEST(length(subtract(truew , df.basis_vectors(0))) < 1e-10);\n\n        dlog << LINFO << \"accuracy: \"<< test_ranking_function(df, samples);\n        DLIB_TEST(equal(test_ranking_function(df, samples), res));\n\n        dlog << LINFO << \"cv-accuracy: \"<< cross_validate_ranking_trainer(trainer, samples,2);\n        DLIB_TEST(std::abs(cross_validate_ranking_trainer(trainer, samples,2)(0) - 0.7777777778) < 0.0001);\n\n        trainer.set_learns_nonnegative_weights(true);\n        df = trainer.train(samples);\n        truew[0] =  0.0;\n        truew[1] =  0.0;\n        truew[2] =  1.0;\n        truew[3] =  1.0;\n        dlog << LINFO << sparse_to_dense(df.basis_vectors(0));\n        DLIB_TEST(length(subtract(truew , df.basis_vectors(0))) < 1e-10);\n        dlog << LINFO << \"accuracy: \"<< test_ranking_function(df, samples);\n        DLIB_TEST(equal(test_ranking_function(df, samples), res));\n\n\n        samples.clear();\n        samples.push_back(p);\n        samples.push_back(p);\n        samples.push_back(p);\n        samples.push_back(p);\n        dlog << LINFO << \"cv-accuracy: \"<< cross_validate_ranking_trainer(trainer, samples,4);\n        DLIB_TEST(equal(cross_validate_ranking_trainer(trainer, samples,4) , res) );\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename K, bool use_dcd_trainer>\n    class simple_rank_trainer\n    {\n    public:\n        template <typename T>\n        decision_function<K> train (\n            const ranking_pair<T>& pair\n        ) const\n        {\n            typedef matrix<double,10,1> sample_type;\n\n            std::vector<sample_type> relevant = pair.relevant;\n            std::vector<sample_type> nonrelevant = pair.nonrelevant;\n\n            std::vector<sample_type> samples;\n            std::vector<double> labels;\n            for (unsigned long i = 0; i < relevant.size(); ++i)\n            {\n                for (unsigned long j = 0; j < nonrelevant.size(); ++j)\n                {\n                    samples.push_back(relevant[i] - nonrelevant[j]);\n                    labels.push_back(+1);\n                    samples.push_back(nonrelevant[i] - relevant[j]);\n                    labels.push_back(-1);\n                }\n            }\n\n            if (use_dcd_trainer)\n            {\n                svm_c_linear_dcd_trainer<K> trainer;\n                trainer.set_c(1.0/samples.size());\n                trainer.set_epsilon(1e-10);\n                trainer.force_last_weight_to_1(true);\n                //trainer.be_verbose();\n                return trainer.train(samples, labels);\n            }\n            else\n            {\n                svm_c_linear_trainer<K> trainer;\n                trainer.set_c(1.0);\n                trainer.set_epsilon(1e-13);\n                trainer.force_last_weight_to_1(true);\n                //trainer.be_verbose();\n                decision_function<K> df = trainer.train(samples, labels);\n                DLIB_TEST_MSG(df.b == 0, df.b);\n                return df;\n            }\n        }\n    };\n\n    template <bool use_dcd_trainer>\n    void test_svmrank_weight_force_dense()\n    {\n        print_spinner();\n        dlog << LINFO << \"use_dcd_trainer: \"<< use_dcd_trainer;\n\n        typedef matrix<double,10,1> sample_type;\n        typedef linear_kernel<sample_type> kernel_type;\n\n        ranking_pair<sample_type> pair;\n\n        for (int i = 0; i < 20; ++i)\n        {\n            pair.relevant.push_back(abs(gaussian_randm(10,1,i)));\n        }\n\n        for (int i = 0; i < 20; ++i)\n        {\n            pair.nonrelevant.push_back(-abs(gaussian_randm(10,1,i+10000)));\n            pair.nonrelevant.back()(9) += 1;\n        }\n\n\n        svm_rank_trainer<kernel_type> trainer;\n        trainer.force_last_weight_to_1(true);\n        trainer.set_epsilon(1e-13);\n        //trainer.be_verbose();\n        decision_function<kernel_type> df;\n        df = trainer.train(pair);\n\n        matrix<double,1,2> res;\n        res = 1,1;\n        dlog << LINFO << \"weights: \"<< trans(df.basis_vectors(0));\n        const matrix<double,1,2> acc1 = test_ranking_function(df, pair);\n        dlog << LINFO << \"ranking accuracy: \" << acc1;\n        DLIB_TEST(equal(acc1,res));\n\n        simple_rank_trainer<kernel_type,use_dcd_trainer> strainer;\n        decision_function<kernel_type> df2;\n        df2 = strainer.train(pair);\n        dlog << LINFO << \"weights: \"<< trans(df2.basis_vectors(0));\n        const matrix<double,1,2> acc2 = test_ranking_function(df2, pair);\n        dlog << LINFO << \"ranking accuracy: \" << acc2;\n        DLIB_TEST(equal(acc2,res));\n\n        dlog << LINFO << \"w error: \" << max(abs(df.basis_vectors(0) - df2.basis_vectors(0)));\n        dlog << LINFO << \"b error: \" << abs(df.b - df2.b);\n        DLIB_TEST(std::abs(max(abs(df.basis_vectors(0) - df2.basis_vectors(0)))) < 1e-8);\n        DLIB_TEST(std::abs(abs(df.b - df2.b)) < 1e-8);\n    }\n\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n\n    class test_ranking_tools : public tester\n    {\n    public:\n        test_ranking_tools (\n        ) :\n            tester (\"test_ranking\",\n                    \"Runs tests on the ranking tools.\")\n        {}\n\n\n        void perform_test (\n        )\n        {\n            test_count_ranking_inversions();\n            dotest1();\n            dotest_sparse_vectors();\n            test_svmrank_weight_force_dense<true>();\n            test_svmrank_weight_force_dense<false>();\n\n        }\n    } a;\n\n\n}\n\n\n\n\n", "meta": {"hexsha": "4355dd1d2f7b401bdea1d45f96792f1cb80c96b7", "size": 12174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/dlib/test/ranking.cpp", "max_stars_repo_name": "markovchainz/cppagent", "max_stars_repo_head_hexsha": "97314ec43786a90697ca7fda15db13f2973aee3e", "max_stars_repo_licenses": ["Apache-2.0"], "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": "lib/dlib/test/ranking.cpp", "max_issues_repo_name": "markovchainz/cppagent", "max_issues_repo_head_hexsha": "97314ec43786a90697ca7fda15db13f2973aee3e", "max_issues_repo_licenses": ["Apache-2.0"], "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": "lib/dlib/test/ranking.cpp", "max_forks_repo_name": "markovchainz/cppagent", "max_forks_repo_head_hexsha": "97314ec43786a90697ca7fda15db13f2973aee3e", "max_forks_repo_licenses": ["Apache-2.0"], "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": 33.0815217391, "max_line_length": 107, "alphanum_fraction": 0.5362247413, "num_tokens": 3015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5185419044144444}}
{"text": "//=======================================================================\n// Copyright (c)\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 ir_steiner_tree_test.cpp\n * @brief\n * @author Maciej Andrejczuk, Piotr Godlewski, Piotr Wygocki\n * @version 1.0\n * @date 2013-02-04\n */\n#include \"test_utils/sample_graph.hpp\"\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/test_result_check.hpp\"\n\n#include \"paal/iterative_rounding/steiner_tree/steiner_tree.hpp\"\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\n#include <cmath>\n\nusing Vertex = int;\nusing Terminals = std::vector<int>;\n\nBOOST_AUTO_TEST_SUITE(ir_steiner_tree)\n\nstatic const double APPROXIMATION_RATIO = 1.39;\n\nBOOST_AUTO_TEST_CASE(test_all_generator) {\n    paal::ir::steiner_tree_all_generator strategy_all(5);\n\n    Terminals terminals, steiner_vertices;\n    std::vector<Vertex> result;\n    // small graph\n    auto metrics = sample_graphs_metrics::get_graph_metric_steiner();\n    boost::tie(terminals, steiner_vertices) =\n        sample_graphs_metrics::get_graph_steiner_vertices();\n\n    auto status = paal::ir::steiner_tree_iterative_rounding(metrics, terminals,\n            steiner_vertices, std::back_inserter(result), strategy_all);\n    BOOST_CHECK_EQUAL(status, paal::lp::OPTIMAL);\n    int cost = paal::ir::steiner_utils::count_cost(result, terminals, metrics);\n    BOOST_CHECK(cost == 4);\n\n    // check if algorithm doesn't modify supplied data\n    BOOST_CHECK(boost::equal(terminals,\n        sample_graphs_metrics::get_graph_steiner_vertices().first));\n    BOOST_CHECK(boost::equal(steiner_vertices,\n        sample_graphs_metrics::get_graph_steiner_vertices().second));\n    auto m2 = sample_graphs_metrics::get_graph_metric_steiner();\n    // TODO function comparing 2 metrics\n    int n = m2.size();\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            BOOST_CHECK(metrics(i, j) == m2(i, j));\n        }\n    }\n\n    // bigger graph\n    result.clear();\n    metrics = sample_graphs_metrics::get_graph_metric_steiner_bigger();\n    boost::tie(terminals, steiner_vertices) =\n        sample_graphs_metrics::get_graph_steiner_bigger_vertices();\n\n    status = paal::ir::steiner_tree_iterative_rounding(metrics, terminals,\n            steiner_vertices, std::back_inserter(result), strategy_all);\n    BOOST_CHECK_EQUAL(status, paal::lp::OPTIMAL);\n    cost = paal::ir::steiner_utils::count_cost(result, terminals, metrics);\n    BOOST_CHECK(cost == 15);\n}\n\ntemplate <typename Strategy>\nvoid run_multiple_seed_tests(Strategy& strategy) {\n    Terminals terminals, steiner_vertices;\n    std::vector<Vertex> result;\n\n    // small graph\n    auto metrics = sample_graphs_metrics::get_graph_metric_steiner();\n    boost::tie(terminals, steiner_vertices) =\n        sample_graphs_metrics::get_graph_steiner_vertices();\n\n    int best_cost = std::numeric_limits<int>::max();\n    for (unsigned long i : paal::irange(5)) {\n        std::default_random_engine rng{i};\n        LOGLN(\"small graph, seed \" << i);\n        result.clear();\n        paal::ir::steiner_tree_ir_components<> comps{};\n        comps.set<paal::ir::RoundCondition>(paal::ir::steiner_tree_round_condition{rng});\n        auto status = paal::ir::steiner_tree_iterative_rounding(metrics, terminals,\n                steiner_vertices, std::back_inserter(result), strategy, comps);\n        BOOST_CHECK_EQUAL(status, paal::lp::OPTIMAL);\n        int cost = paal::ir::steiner_utils::count_cost(result, terminals, metrics);\n        paal::assign_min(best_cost, cost);\n        BOOST_CHECK(cost >= 4);\n    }\n    // warning: randomized algorithm, approximation ratio could be violated\n    check_result(best_cost, 4, APPROXIMATION_RATIO);\n\n    // bigger graph\n    metrics = sample_graphs_metrics::get_graph_metric_steiner_bigger();\n    boost::tie(terminals, steiner_vertices) =\n        sample_graphs_metrics::get_graph_steiner_bigger_vertices();\n\n    best_cost = std::numeric_limits<int>::max();\n    for (int i : paal::irange(5)) {\n        LOGLN(\"big graph, seed \" << i);\n        srand(i);\n        result.clear();\n        auto status = paal::ir::steiner_tree_iterative_rounding(metrics, terminals,\n                steiner_vertices, std::back_inserter(result), strategy);\n        BOOST_CHECK_EQUAL(status, paal::lp::OPTIMAL);\n        int cost = paal::ir::steiner_utils::count_cost(result, terminals, metrics);\n        best_cost = std::min(best_cost, cost);\n        BOOST_CHECK(cost >= 15);\n    }\n    // warning: randomized algorithm, approximation ratio could be violated\n    check_result(best_cost, 15, APPROXIMATION_RATIO);\n}\n\nBOOST_AUTO_TEST_CASE(test_all_generator_seeds) {\n    LOGLN(\"strategy_all\");\n    paal::ir::steiner_tree_all_generator strategy_all(5);\n    run_multiple_seed_tests(strategy_all);\n}\n\nBOOST_AUTO_TEST_CASE(test_rand_generator) {\n    LOGLN(\"strategy_rand\");\n    paal::ir::steiner_tree_random_generator strategy_rand(10, 5);\n    run_multiple_seed_tests(strategy_rand);\n}\n\nBOOST_AUTO_TEST_CASE(test_smart_generator) {\n    LOGLN(\"strategy_smart\");\n    paal::ir::steiner_tree_smart_generator strategy_smart(10, 5);\n    run_multiple_seed_tests(strategy_smart);\n}\n\nBOOST_AUTO_TEST_CASE(test_graph_all_generator) {\n    LOGLN(\"strategy_graph_all\");\n    srand(0);\n\n    Terminals terminals, steiner_vertices;\n    std::vector<Vertex> result;\n\n    // small graph\n    auto small_graph = sample_graphs_metrics::get_graph_steiner();\n    auto metrics = sample_graphs_metrics::get_graph_metric_steiner();\n    boost::tie(terminals, steiner_vertices) =\n        sample_graphs_metrics::get_graph_steiner_vertices();\n\n    int best_cost = std::numeric_limits<int>::max();\n    for (int i : paal::irange(5)) {\n        auto strategy = paal::ir::make_steiner_tree_graph_all_generator<Vertex>(\n            small_graph, terminals, 5);\n        srand(i);\n        LOGLN(\"small graph, seed \" << i);\n        result.clear();\n        auto status = paal::ir::steiner_tree_iterative_rounding(metrics, terminals,\n                steiner_vertices, std::back_inserter(result), strategy);\n        BOOST_CHECK_EQUAL(status, paal::lp::OPTIMAL);\n        int cost = paal::ir::steiner_utils::count_cost(result, terminals, metrics);\n        best_cost = std::min(best_cost, cost);\n        BOOST_CHECK(cost >= 4);\n    }\n    // warning: randomized algorithm, approximation ratio could be violated\n    check_result(best_cost, 4, APPROXIMATION_RATIO);\n\n    // bigger graph\n    auto bigger_graph = sample_graphs_metrics::get_graph_steiner_bigger();\n    metrics = sample_graphs_metrics::get_graph_metric_steiner_bigger();\n    boost::tie(terminals, steiner_vertices) =\n        sample_graphs_metrics::get_graph_steiner_bigger_vertices();\n\n    best_cost = std::numeric_limits<int>::max();\n    for (int i : paal::irange(5)) {\n        auto strategy = paal::ir::make_steiner_tree_graph_all_generator<Vertex>(\n            bigger_graph, terminals, 5);\n        LOGLN(\"big graph, seed \" << i);\n        srand(i);\n        result.clear();\n        auto status = paal::ir::steiner_tree_iterative_rounding(metrics, terminals,\n                steiner_vertices, std::back_inserter(result), strategy);\n        BOOST_CHECK_EQUAL(status, paal::lp::OPTIMAL);\n        int cost = paal::ir::steiner_utils::count_cost(result, terminals, metrics);\n        best_cost = std::min(best_cost, cost);\n        BOOST_CHECK(cost >= 15);\n    }\n    // warning: randomized algorithm, approximation ratio could be violated\n    check_result(best_cost, 15, APPROXIMATION_RATIO);\n}\n\nBOOST_AUTO_TEST_CASE(euclidean_metric_test) {\n    using Points = std::vector<std::pair<int, int>>;\n\n    srand(0);\n    paal::ir::steiner_tree_random_generator strategy_rand(10, 5);\n    paal::data_structures::euclidean_metric<int> em;\n    Points terminals, steiner_vertices, result;\n\n    std::tie(em, terminals, steiner_vertices) =\n        sample_graphs_metrics::get_euclidean_steiner_sample();\n\n    auto status = paal::ir::steiner_tree_iterative_rounding(em, terminals, steiner_vertices,\n                std::back_inserter(result), strategy_rand);\n    BOOST_CHECK_EQUAL(status, paal::lp::OPTIMAL);\n    auto cost = paal::ir::steiner_utils::count_cost(result, terminals, em);\n\n    BOOST_CHECK_EQUAL(result.size(), std::size_t(1));\n    BOOST_CHECK(result.front() == std::make_pair(1, 1));\n    BOOST_CHECK_CLOSE(cost, 4 * std::sqrt(2), 1e-6);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c22ef5450fcb50ae6604b437713d3158275e0db8", "size": 8516, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/iterative_rounding/steiner_tree/ir_steiner_tree_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/iterative_rounding/steiner_tree/ir_steiner_tree_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/iterative_rounding/steiner_tree/ir_steiner_tree_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": 39.0642201835, "max_line_length": 92, "alphanum_fraction": 0.6888210427, "num_tokens": 2070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5185418994565512}}
{"text": "// Copyright Paul A. Bristow 2012.\n// Copyright John Maddock 2012.\n// Copyright Benjamin Sobotta 2012\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifdef _MSC_VER\n#  pragma warning (disable : 4127) // conditional expression is constant.\n#  pragma warning (disable : 4305) // 'initializing' : truncation from 'double' to 'const float'.\n#  pragma warning (disable : 4310) // cast truncates constant value.\n#  pragma warning (disable : 4512) // assignment operator could not be generated.\n#endif\n\n//#include <pch.hpp> // include directory libs/math/src/tr1/ is needed.\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/floating_point_comparison.hpp>\n\n#include <boost/math/distributions/skew_normal.hpp>\nusing boost::math::skew_normal_distribution;\nusing boost::math::skew_normal;\n#include <boost/math/tools/test.hpp>\n\n#include <iostream>\n#include <iomanip>\nusing std::cout;\nusing std::endl;\nusing std::setprecision;\n#include <limits>\nusing std::numeric_limits;\n#include \"test_out_of_range.hpp\"\n\ntemplate <class RealType>\nvoid check_skew_normal(RealType mean, RealType scale, RealType shape, RealType x, RealType p, RealType q, RealType tol)\n{\n using boost::math::skew_normal_distribution;\n\n  BOOST_CHECK_CLOSE_FRACTION(\n    ::boost::math::cdf(   // Check cdf\n    skew_normal_distribution<RealType>(mean, scale, shape),      // distribution.\n    x),    // random variable.\n    p,     // probability.\n    tol);   // tolerance.\n  BOOST_CHECK_CLOSE_FRACTION(\n    ::boost::math::cdf( // Check cdf complement\n    complement(\n    skew_normal_distribution<RealType>(mean, scale, shape),   // distribution.\n    x)),   // random variable.\n    q,      // probability complement.\n    tol);    // %tolerance.\n  BOOST_CHECK_CLOSE_FRACTION(\n    ::boost::math::quantile( // Check quantile\n    skew_normal_distribution<RealType>(mean, scale, shape),    // distribution.\n    p),   // probability.\n    x,   // random variable.\n    tol);   // tolerance.\n  BOOST_CHECK_CLOSE_FRACTION(\n    ::boost::math::quantile( // Check quantile complement\n    complement(\n    skew_normal_distribution<RealType>(mean, scale, shape),   // distribution.\n    q)),   // probability complement.\n    x,     // random variable.\n    tol);  // tolerance.\n\n   skew_normal_distribution<RealType> dist (mean, scale, shape);\n\n   if((p < 0.999) && (q < 0.999))\n   {  // We can only check this if P is not too close to 1,\n      // so that we can guarantee Q is accurate:\n      BOOST_CHECK_CLOSE_FRACTION(\n        cdf(complement(dist, x)), q, tol); // 1 - cdf\n      BOOST_CHECK_CLOSE_FRACTION(\n        quantile(dist, p), x, tol); // quantile(cdf) = x\n      BOOST_CHECK_CLOSE_FRACTION(\n        quantile(complement(dist, q)), x, tol); // quantile(complement(1 - cdf)) = x\n   }\n} // template <class RealType>void check_skew_normal()\n\n\ntemplate <class RealType>\nvoid test_spots(RealType)\n{\n   // Basic sanity checks\n   RealType tolerance = 1e-4f; // 1e-4 (as %)\n\n  // Check some bad parameters to the distribution,\n#ifndef BOOST_NO_EXCEPTIONS\n   BOOST_MATH_CHECK_THROW(boost::math::skew_normal_distribution<RealType> nbad1(0, 0), std::domain_error); // zero sd\n   BOOST_MATH_CHECK_THROW(boost::math::skew_normal_distribution<RealType> nbad1(0, -1), std::domain_error); // negative sd\n#else\n   BOOST_MATH_CHECK_THROW(boost::math::skew_normal_distribution<RealType>(0, 0), std::domain_error); // zero sd\n   BOOST_MATH_CHECK_THROW(boost::math::skew_normal_distribution<RealType>(0, -1), std::domain_error); // negative sd\n#endif\n  // Tests on extreme values of random variate x, if has numeric_limit infinity etc.\n    skew_normal_distribution<RealType> N01;\n  if(std::numeric_limits<RealType>::has_infinity)\n  {\n    BOOST_CHECK_EQUAL(pdf(N01, +std::numeric_limits<RealType>::infinity()), 0); // x = + infinity, pdf = 0\n    BOOST_CHECK_EQUAL(pdf(N01, -std::numeric_limits<RealType>::infinity()), 0); // x = - infinity, pdf = 0\n    BOOST_CHECK_EQUAL(cdf(N01, +std::numeric_limits<RealType>::infinity()), 1); // x = + infinity, cdf = 1\n    BOOST_CHECK_EQUAL(cdf(N01, -std::numeric_limits<RealType>::infinity()), 0); // x = - infinity, cdf = 0\n    BOOST_CHECK_EQUAL(cdf(complement(N01, +std::numeric_limits<RealType>::infinity())), 0); // x = + infinity, c cdf = 0\n    BOOST_CHECK_EQUAL(cdf(complement(N01, -std::numeric_limits<RealType>::infinity())), 1); // x = - infinity, c cdf = 1\n#ifndef BOOST_NO_EXCEPTIONS\n    BOOST_MATH_CHECK_THROW(boost::math::skew_normal_distribution<RealType> nbad1(std::numeric_limits<RealType>::infinity(), static_cast<RealType>(1)), std::domain_error); // +infinite mean\n    BOOST_MATH_CHECK_THROW(boost::math::skew_normal_distribution<RealType> nbad1(-std::numeric_limits<RealType>::infinity(),  static_cast<RealType>(1)), std::domain_error); // -infinite mean\n    BOOST_MATH_CHECK_THROW(boost::math::skew_normal_distribution<RealType> nbad1(static_cast<RealType>(0), std::numeric_limits<RealType>::infinity()), std::domain_error); // infinite sd\n#else\n    BOOST_MATH_CHECK_THROW(boost::math::skew_normal_distribution<RealType>(std::numeric_limits<RealType>::infinity(), static_cast<RealType>(1)), std::domain_error); // +infinite mean\n    BOOST_MATH_CHECK_THROW(boost::math::skew_normal_distribution<RealType>(-std::numeric_limits<RealType>::infinity(),  static_cast<RealType>(1)), std::domain_error); // -infinite mean\n    BOOST_MATH_CHECK_THROW(boost::math::skew_normal_distribution<RealType>(static_cast<RealType>(0), std::numeric_limits<RealType>::infinity()), std::domain_error); // infinite sd\n#endif\n  }\n\n  if (std::numeric_limits<RealType>::has_quiet_NaN)\n  {\n    // No longer allow x to be NaN, then these tests should throw.\n    BOOST_MATH_CHECK_THROW(pdf(N01, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // x = NaN\n    BOOST_MATH_CHECK_THROW(cdf(N01, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // x = NaN\n    BOOST_MATH_CHECK_THROW(cdf(complement(N01, +std::numeric_limits<RealType>::quiet_NaN())), std::domain_error); // x = + infinity\n    BOOST_MATH_CHECK_THROW(quantile(N01, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // p = + infinity\n    BOOST_MATH_CHECK_THROW(quantile(complement(N01, +std::numeric_limits<RealType>::quiet_NaN())), std::domain_error); // p = + infinity\n  }\n\n   cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \" << tolerance << \" %\" << endl;\n\n   // Tests where shape = 0, so same as normal tests.\n   // (These might be removed later).\n   check_skew_normal(\n      static_cast<RealType>(5),\n      static_cast<RealType>(2),\n      static_cast<RealType>(0),\n      static_cast<RealType>(4.8),\n      static_cast<RealType>(0.46017),\n      static_cast<RealType>(1 - 0.46017),\n      tolerance);\n\n   check_skew_normal(\n      static_cast<RealType>(5),\n      static_cast<RealType>(2),\n      static_cast<RealType>(0),\n      static_cast<RealType>(5.2),\n      static_cast<RealType>(1 - 0.46017),\n      static_cast<RealType>(0.46017),\n      tolerance);\n\n   check_skew_normal(\n      static_cast<RealType>(5),\n      static_cast<RealType>(2),\n      static_cast<RealType>(0),\n      static_cast<RealType>(2.2),\n      static_cast<RealType>(0.08076),\n      static_cast<RealType>(1 - 0.08076),\n      tolerance);\n\n   check_skew_normal(\n      static_cast<RealType>(5),\n      static_cast<RealType>(2),\n      static_cast<RealType>(0),\n      static_cast<RealType>(7.8),\n      static_cast<RealType>(1 - 0.08076),\n      static_cast<RealType>(0.08076),\n      tolerance);\n\n   check_skew_normal(\n      static_cast<RealType>(-3),\n      static_cast<RealType>(5),\n      static_cast<RealType>(0),\n      static_cast<RealType>(-4.5),\n      static_cast<RealType>(0.38209),\n      static_cast<RealType>(1 - 0.38209),\n      tolerance);\n\n   check_skew_normal(\n      static_cast<RealType>(-3),\n      static_cast<RealType>(5),\n      static_cast<RealType>(0),\n      static_cast<RealType>(-1.5),\n      static_cast<RealType>(1 - 0.38209),\n      static_cast<RealType>(0.38209),\n      tolerance);\n\n   check_skew_normal(\n      static_cast<RealType>(-3),\n      static_cast<RealType>(5),\n      static_cast<RealType>(0),\n      static_cast<RealType>(-8.5),\n      static_cast<RealType>(0.13567),\n      static_cast<RealType>(1 - 0.13567),\n      tolerance);\n\n   check_skew_normal(\n      static_cast<RealType>(-3),\n      static_cast<RealType>(5),\n      static_cast<RealType>(0),\n      static_cast<RealType>(2.5),\n      static_cast<RealType>(1 - 0.13567),\n      static_cast<RealType>(0.13567),\n      tolerance);\n\n   // Tests where shape != 0, specific to skew_normal distribution.\n   //void check_skew_normal(RealType mean, RealType scale, RealType shape, RealType x, RealType p, RealType q, RealType tol)\n      check_skew_normal( // 1st R example.\n      static_cast<RealType>(1.1),\n      static_cast<RealType>(2.2),\n      static_cast<RealType>(-3.3),\n      static_cast<RealType>(0.4), // x\n      static_cast<RealType>(0.733918618927874), // p == psn\n      static_cast<RealType>(1 - 0.733918618927874), // q\n      tolerance);\n\n   // Not sure about these yet.\n      //check_skew_normal( // 2nd R example.\n      //static_cast<RealType>(1.1),\n      //static_cast<RealType>(0.02),\n      //static_cast<RealType>(0.03),\n      //static_cast<RealType>(1.3), // x\n      //static_cast<RealType>(0.01), // p\n      //static_cast<RealType>(0.09), // q\n      //tolerance);\n      //check_skew_normal( // 3nd R example.\n      //static_cast<RealType>(10.1),\n      //static_cast<RealType>(5.),\n      //static_cast<RealType>(-0.03),\n      //static_cast<RealType>(-1.3), // x\n      //static_cast<RealType>(0.01201290665838824), // p\n      //static_cast<RealType>(1. - 0.01201290665838824), // q 0.987987101\n      //tolerance);\n\n    // Tests for PDF: we know that the normal peak value is at 1/sqrt(2*pi)\n   //\n   tolerance = boost::math::tools::epsilon<RealType>() * 5; // 5 eps as a fraction\n   BOOST_CHECK_CLOSE_FRACTION(\n      pdf(skew_normal_distribution<RealType>(), static_cast<RealType>(0)),\n      static_cast<RealType>(0.3989422804014326779399460599343818684759L), // 1/sqrt(2*pi)\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      pdf(skew_normal_distribution<RealType>(3), static_cast<RealType>(3)),\n      static_cast<RealType>(0.3989422804014326779399460599343818684759L),\n      tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(\n      pdf(skew_normal_distribution<RealType>(3, 5), static_cast<RealType>(3)),\n      static_cast<RealType>(0.3989422804014326779399460599343818684759L / 5),\n      tolerance);\n\n   // Shape != 0.\n   BOOST_CHECK_CLOSE_FRACTION(\n      pdf(skew_normal_distribution<RealType>(3,5,1e-6), static_cast<RealType>(3)),\n      static_cast<RealType>(0.3989422804014326779399460599343818684759L / 5),\n      tolerance);\n\n\n   // Checks on mean, variance cumulants etc.\n   // Checks on shape ==0\n\n    RealType tol5 = boost::math::tools::epsilon<RealType>() * 5;\n    skew_normal_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>(8), tol5);\n    // variance:\n    BOOST_CHECK_CLOSE(\n       variance(dist)\n       , static_cast<RealType>(9), tol5);\n    // std deviation:\n    BOOST_CHECK_CLOSE(\n       standard_deviation(dist)\n       , static_cast<RealType>(3), tol5);\n    // hazard:\n    BOOST_CHECK_CLOSE(\n       hazard(dist, x)\n       , pdf(dist, x) / cdf(complement(dist, x)), tol5);\n    // cumulative hazard:\n    BOOST_CHECK_CLOSE(\n       chf(dist, x)\n       , -log(cdf(complement(dist, x))), tol5);\n    // coefficient_of_variation:\n    BOOST_CHECK_CLOSE(\n       coefficient_of_variation(dist)\n       , standard_deviation(dist) / mean(dist), tol5);\n    // mode:\n    BOOST_CHECK_CLOSE_FRACTION(mode(dist), static_cast<RealType>(8), 0.001f);\n\n    BOOST_CHECK_CLOSE(\n       median(dist)\n       , static_cast<RealType>(8), tol5);\n\n    // skewness:\n    BOOST_CHECK_CLOSE(\n       skewness(dist)\n       , static_cast<RealType>(0), tol5);\n    // kurtosis:\n    BOOST_CHECK_CLOSE(\n       kurtosis(dist)\n       , static_cast<RealType>(3), tol5);\n    // kurtosis excess:\n    BOOST_CHECK_CLOSE(\n       kurtosis_excess(dist)\n       , static_cast<RealType>(0), tol5);\n\n    skew_normal_distribution<RealType> norm01(0, 1); // Test default (0, 1)\n    BOOST_CHECK_CLOSE(\n       mean(norm01),\n       static_cast<RealType>(0), 0); // Mean == zero\n\n    skew_normal_distribution<RealType> defsd_norm01(0); // Test default (0, sd = 1)\n    BOOST_CHECK_CLOSE(\n       mean(defsd_norm01),\n       static_cast<RealType>(0), 0); // Mean == zero\n\n    skew_normal_distribution<RealType> def_norm01; // Test default (0, sd = 1)\n    BOOST_CHECK_CLOSE(\n       mean(def_norm01),\n       static_cast<RealType>(0), 0); // Mean == zero\n\n    BOOST_CHECK_CLOSE(\n       standard_deviation(def_norm01),\n       static_cast<RealType>(1), 0);  //\n\n    BOOST_CHECK_CLOSE(\n       mode(def_norm01),\n       static_cast<RealType>(0), 0); // Mode == zero\n\n\n    // Skew_normal tests with shape != 0.\n    {\n      // Note these tolerances are expressed as percentages, hence the extra * 100 on the end:\n      RealType tol10 = boost::math::tools::epsilon<RealType>() * 10 * 100;\n      RealType tol100 = boost::math::tools::epsilon<RealType>() * 100 * 100;\n\n      //skew_normal_distribution<RealType> dist(1.1, 0.02, 0.03);\n\n      BOOST_MATH_STD_USING // ADL of std math lib names.\n\n      // Test values from R = see skew_normal_drv.cpp which included the R code used.\n      {\n        dist = skew_normal_distribution<RealType>(static_cast<RealType>(1.1l), static_cast<RealType>(2.2l), static_cast<RealType>(-3.3l));\n\n        BOOST_CHECK_CLOSE(      // mean:\n           mean(dist)\n           , static_cast<RealType>(-0.579908992539856825862549L), tol10 * 2);\n\n        std::cout << std::setprecision(17) << \"Variance = \" << variance(dist) << std::endl;\n         BOOST_CHECK_CLOSE(      // variance: N[variance[skewnormaldistribution[1.1, 2.2, -3.3]], 50]\n          variance(dist)\n          , static_cast<RealType>(2.0179057767837232633904061072049998357047989154484L), tol10);\n\n        BOOST_CHECK_CLOSE(      // skewness:\n           skewness(dist)\n           , static_cast<RealType>(-0.709854548171537509192897824663L), tol100);\n        BOOST_CHECK_CLOSE(      // kurtosis:\n           kurtosis(dist)\n           , static_cast<RealType>(3.5538752625241790601377L), tol100);\n        BOOST_CHECK_CLOSE(      // kurtosis excess:\n           kurtosis_excess(dist)\n           , static_cast<RealType>(0.5538752625241790601377L), tol100);\n\n        BOOST_CHECK_CLOSE(\n          pdf(dist, static_cast<RealType>(0.4L)),\n          static_cast<RealType>(0.294140110156599539564571L),\n          tol10);\n\n        BOOST_CHECK_CLOSE(\n          cdf(dist, static_cast<RealType>(0.4L)),\n          static_cast<RealType>(0.7339186189278737976326676452L),\n          tol100);\n\n        BOOST_CHECK_CLOSE(\n          quantile(dist, static_cast<RealType>(0.3L)),\n          static_cast<RealType>(-1.180104068086875314419247L),\n          tol100);\n\n\n      { // mode tests\n\n           dist = skew_normal_distribution<RealType>(static_cast<RealType>(0.l), static_cast<RealType>(1.l), static_cast<RealType>(4.l));\n\n       // cout << \"pdf(dist, 0) = \" << pdf(dist, 0) <<  \", pdf(dist, 0.45) = \" << pdf(dist, 0.45) << endl;\n       // BOOST_CHECK_CLOSE(mode(dist), boost::math::constants::root_two<RealType>() / 2, tol5);\n        BOOST_CHECK_CLOSE(mode(dist), static_cast<RealType>(0.41697299497388863932L), tol100);\n      }\n\n\n      }\n      {\n        dist = skew_normal_distribution<RealType>(static_cast<RealType>(1.1l), static_cast<RealType>(0.02l), static_cast<RealType>(0.03l));\n\n        BOOST_CHECK_CLOSE(      // mean:\n           mean(dist)\n           , static_cast<RealType>(1.1004785154529557886162L), tol10);\n        BOOST_CHECK_CLOSE(      // variance:\n          variance(dist)\n           , static_cast<RealType>(0.00039977102296128251645L), tol10);\n\n        BOOST_CHECK_CLOSE(      // skewness:\n           skewness(dist)\n           , static_cast<RealType>(5.8834811259890359782e-006L), tol100);\n        BOOST_CHECK_CLOSE(      // kurtosis:\n           kurtosis(dist)\n           , static_cast<RealType>(3.L + 9.2903475812137800239002e-008L), tol100);\n        BOOST_CHECK_CLOSE(      // kurtosis excess:\n           kurtosis_excess(dist)\n           , static_cast<RealType>(9.2903475812137800239002e-008L), tol100);\n      }\n      {\n        dist = skew_normal_distribution<RealType>(static_cast<RealType>(10.1l), static_cast<RealType>(5.l), static_cast<RealType>(-0.03l));\n        BOOST_CHECK_CLOSE(      // mean:\n           mean(dist)\n           , static_cast<RealType>(9.9803711367610528459485937L), tol10);\n        BOOST_CHECK_CLOSE(      // variance:\n          variance(dist)\n           , static_cast<RealType>(24.98568893508015727823L), tol10);\n\n        BOOST_CHECK_CLOSE(      // skewness:\n           skewness(dist)\n           , static_cast<RealType>(-5.8834811259890359782085e-006L), tol100);\n        BOOST_CHECK_CLOSE(      // kurtosis:\n           kurtosis(dist)\n           , static_cast<RealType>(3.L + 9.2903475812137800239002e-008L), tol100);\n        BOOST_CHECK_CLOSE(      // kurtosis excess:\n           kurtosis_excess(dist)\n           , static_cast<RealType>(9.2903475812137800239002e-008L), tol100);\n      }\n      {\n        dist = skew_normal_distribution<RealType>(static_cast<RealType>(-10.1l), static_cast<RealType>(5.l), static_cast<RealType>(30.l));\n        BOOST_CHECK_CLOSE(      // mean:\n           mean(dist)\n           , static_cast<RealType>(-6.11279169674138408531365L), 2 * tol10);\n        BOOST_CHECK_CLOSE(      // variance:\n          variance(dist)\n          , static_cast<RealType>(9.10216994642554914628242L), tol10 * 2);\n\n        BOOST_CHECK_CLOSE(      // skewness:\n           skewness(dist)\n           , static_cast<RealType>(0.99072425443686904424L), tol100);\n        BOOST_CHECK_CLOSE(      // kurtosis:\n           kurtosis(dist)\n           , static_cast<RealType>(3.L + 0.8638862008406084244563L), tol100);\n        BOOST_CHECK_CLOSE(      // kurtosis excess:\n           kurtosis_excess(dist)\n           , static_cast<RealType>(0.8638862008406084244563L), tol100);\n      }\n\n      BOOST_MATH_CHECK_THROW(cdf(skew_normal_distribution<RealType>(0, 0, 0), 0), std::domain_error);\n      BOOST_MATH_CHECK_THROW(cdf(skew_normal_distribution<RealType>(0, -1, 0), 0), std::domain_error);\n      BOOST_MATH_CHECK_THROW(quantile(skew_normal_distribution<RealType>(0, 1, 0), -1), std::domain_error);\n      BOOST_MATH_CHECK_THROW(quantile(skew_normal_distribution<RealType>(0, 1, 0), 2), std::domain_error);\n      check_out_of_range<skew_normal_distribution<RealType> >(1, 1, 1);\n    }\n\n\n} // template <class RealType>void test_spots(RealType)\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n\n\n  using boost::math::skew_normal;\n  using boost::math::skew_normal_distribution;\n\n  //int precision = 17; // std::numeric_limits<double::max_digits10;\n  double tolfeweps = numeric_limits<double>::epsilon() * 5;\n  //double tol6decdigits = numeric_limits<float>::epsilon() * 2;\n  // Check that can generate skew_normal distribution using the two convenience methods:\n  boost::math::skew_normal w12(1., 2); // Using typedef.\n  boost::math::skew_normal_distribution<> w01; // Use default unity values for mean and scale.\n  // Note NOT myn01() as the compiler will interpret as a function!\n\n  // Checks on constructors.\n  // Default parameters.\n  BOOST_CHECK_EQUAL(w01.location(), 0);\n  BOOST_CHECK_EQUAL(w01.scale(), 1);\n  BOOST_CHECK_EQUAL(w01.shape(), 0);\n\n  skew_normal_distribution<> w23(2., 3); // Using default RealType double.\n  BOOST_CHECK_EQUAL(w23.scale(), 3);\n  BOOST_CHECK_EQUAL(w23.shape(), 0);\n\n  skew_normal_distribution<> w123(1., 2., 3.); // Using default RealType double.\n  BOOST_CHECK_EQUAL(w123.location(), 1.);\n  BOOST_CHECK_EQUAL(w123.scale(), 2.);\n  BOOST_CHECK_EQUAL(w123.shape(), 3.);\n\n  BOOST_CHECK_CLOSE_FRACTION(mean(w01), static_cast<double>(0), tolfeweps); // Default mean == zero\n  BOOST_CHECK_CLOSE_FRACTION(scale(w01), static_cast<double>(1), tolfeweps); // Default scale == unity\n\n  // Basic sanity-check spot values for all floating-point types..\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#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\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/*\n\nOutput:\n\n\n*/\n", "meta": {"hexsha": "dcc62ba0bf9ad964cbaadeb48b0f1870a3a48526", "size": 21160, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/math/test/test_skew_normal.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/math/test/test_skew_normal.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/math/test/test_skew_normal.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": 40.5363984674, "max_line_length": 190, "alphanum_fraction": 0.6686672968, "num_tokens": 5763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5185418971043173}}
{"text": "/**\n * @file electrostaticforce.cc\n * @brief ElectrostaticForce\n * @author Erick Schulz\n * @date 27.11.2019\n * @copyright Developed at ETH Zurich\n */\n\n// HACK:\n#undef SOLUTION\n#define SOLUTION 1\n\n#include \"../electrostaticforce.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\nnamespace ElectrostaticForce::test {\n\nTEST(ElectrostaticForce, computeExactForce) {\n  Eigen::Vector2d exactForce = ElectrostaticForce::computeExactForce();\n  double tol = 1.0e-3;\n  ASSERT_NEAR(13.0776, exactForce(0), tol);\n  ASSERT_NEAR(0.0, exactForce(1), tol);\n}\n\nTEST(ElectrostaticForce, computeForceDomainFunctional) {\n  std::string mesh_file =\n      CURRENT_SOURCE_DIR \"/../../meshes/emforce\" + std::to_string(4) + \".msh\";\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  const lf::io::GmshReader reader(std::move(mesh_factory), mesh_file);\n  auto mesh_p = reader.mesh();\n  auto fe_space_p =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  Eigen::VectorXd approx_sol = ElectrostaticForce::solvePoissonBVP(fe_space_p);\n\n  Eigen::Vector2d approx_force_domain_functional =\n      ElectrostaticForce::computeForceDomainFunctional(fe_space_p, approx_sol);\n\n  double tol = 1.0e-4;\n  ASSERT_NEAR(13.0711, approx_force_domain_functional(0), tol);\n  ASSERT_NEAR(0.01106, approx_force_domain_functional(1), tol);\n}\n\nTEST(ElectrostaticForce, computeForceBoundaryFunctional) {\n  std::string mesh_file =\n      CURRENT_SOURCE_DIR \"/../../meshes/emforce\" + std::to_string(4) + \".msh\";\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  const lf::io::GmshReader reader(std::move(mesh_factory), mesh_file);\n  auto mesh_p = reader.mesh();\n  auto fe_space_p =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  Eigen::VectorXd approx_sol = ElectrostaticForce::solvePoissonBVP(fe_space_p);\n\n  Eigen::Vector2d approx_force_boundary_functional =\n      ElectrostaticForce::computeForceBoundaryFunctional(fe_space_p,\n                                                         approx_sol);\n\n  double tol = 1.0e-3;\n  ASSERT_NEAR(12.5894, approx_force_boundary_functional(0), tol);\n  ASSERT_NEAR(-0.0602, approx_force_boundary_functional(1), tol);\n}\n\nTEST(ElectrostaticForce, solvePoissonBVPBoundaryConditions) {\n  double tol = 1.0e-14;\n  std::string mesh_file =\n      CURRENT_SOURCE_DIR \"/../../meshes/emforce\" + std::to_string(1) + \".msh\";\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  const lf::io::GmshReader reader(std::move(mesh_factory), mesh_file);\n  auto mesh_p = reader.mesh();\n  auto fe_space_p =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  const lf::assemble::DofHandler &dofh{fe_space_p->LocGlobMap()};\n\n  Eigen::VectorXd approx_sol = ElectrostaticForce::solvePoissonBVP(fe_space_p);\n\n  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 2)};\n  for (const lf::mesh::Entity *node : mesh_p->Entities(2)) {\n    if (bd_flags(*node)) {\n      auto dof_idx = dofh.GlobalDofIndices(*node);\n      auto endpoints = lf::geometry::Corners(*(node->Geometry()));\n      if (endpoints.norm() < 0.27) {\n        ASSERT_NEAR(1.0, approx_sol(dof_idx[0]), tol);\n      } else {\n        ASSERT_NEAR(0.0, approx_sol(dof_idx[0]), tol);\n      }\n    }\n  }\n}\n\n}  // namespace ElectrostaticForce::test\n", "meta": {"hexsha": "1fdfa5acdd23e929deb6f82af2566b98e4fdf558", "size": 3322, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElectrostaticForce/templates/test/electrostaticforce_test.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ElectrostaticForce/templates/test/electrostaticforce_test.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ElectrostaticForce/templates/test/electrostaticforce_test.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 34.9684210526, "max_line_length": 79, "alphanum_fraction": 0.7080072246, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5184875484932587}}
{"text": "#include <cassert>\n#include <iostream>\n#include <sstream>\n#include <boost/program_options/variables_map.hpp>\n#include \"optimize.h\"\n#include \"online_optimizer.h\"\n#include \"sparse_vector.h\"\n#include \"fdict.h\"\n\nusing namespace std;\n\ndouble TestOptimizer(BatchOptimizer* opt) {\n  cerr << \"TESTING NON-PERSISTENT OPTIMIZER\\n\";\n\n  // f(x,y) = 4x1^2 + x1*x2 + x2^2 + x3^2 + 6x3 + 5\n  // df/dx1 = 8*x1 + x2\n  // df/dx2 = 2*x2 + x1\n  // df/dx3 = 2*x3 + 6\n  vector<double> x(3);\n  vector<double> g(3);\n  x[0] = 8;\n  x[1] = 8;\n  x[2] = 8;\n  double obj = 0;\n  do {\n    g[0] = 8 * x[0] + x[1];\n    g[1] = 2 * x[1] + x[0];\n    g[2] = 2 * x[2] + 6;\n    obj = 4 * x[0]*x[0] + x[0] * x[1] + x[1]*x[1] + x[2]*x[2] + 6 * x[2] + 5;\n    opt->Optimize(obj, g, &x);\n\n    cerr << x[0] << \" \" << x[1] << \" \" << x[2] << endl;\n    cerr << \"   obj=\" << obj << \"\\td/dx1=\" << g[0] << \" d/dx2=\" << g[1] << \" d/dx3=\" << g[2] << endl;\n  } while (!opt->HasConverged());\n  return obj;\n}\n\ndouble TestPersistentOptimizer(BatchOptimizer* opt) {\n  cerr << \"\\nTESTING PERSISTENT OPTIMIZER\\n\";\n  // f(x,y) = 4x1^2 + x1*x2 + x2^2 + x3^2 + 6x3 + 5\n  // df/dx1 = 8*x1 + x2\n  // df/dx2 = 2*x2 + x1\n  // df/dx3 = 2*x3 + 6\n  vector<double> x(3);\n  vector<double> g(3);\n  x[0] = 8;\n  x[1] = 8;\n  x[2] = 8;\n  double obj = 0;\n  string state;\n  bool converged = false;\n  while (!converged) {\n    g[0] = 8 * x[0] + x[1];\n    g[1] = 2 * x[1] + x[0];\n    g[2] = 2 * x[2] + 6;\n    obj = 4 * x[0]*x[0] + x[0] * x[1] + x[1]*x[1] + x[2]*x[2] + 6 * x[2] + 5;\n\n    {\n      if (state.size() > 0) {\n        istringstream is(state, ios::binary);\n        opt->Load(&is);\n      }\n      opt->Optimize(obj, g, &x);\n      ostringstream os(ios::binary); opt->Save(&os); state = os.str();\n\n    }\n\n    cerr << x[0] << \" \" << x[1] << \" \" << x[2] << endl;\n    cerr << \"   obj=\" << obj << \"\\td/dx1=\" << g[0] << \" d/dx2=\" << g[1] << \" d/dx3=\" << g[2] << endl;\n    converged = opt->HasConverged();\n    if (!converged) {\n      // now screw up the state (should be undone by Load)\n      obj += 2.0;\n      g[1] = -g[2];\n      vector<double> x2 = x;\n      try {\n        opt->Optimize(obj, g, &x2);\n      } catch (...) { }\n    }\n  }\n  return obj;\n}\n\ntemplate <class O>\nvoid TestOptimizerVariants(int num_vars) {\n  O oa(num_vars);\n  cerr << \"-------------------------------------------------------------------------\\n\";\n  cerr << \"TESTING: \" << oa.Name() << endl;\n  double o1 = TestOptimizer(&oa);\n  O ob(num_vars);\n  double o2 = TestPersistentOptimizer(&ob);\n  if (o1 != o2) {\n    cerr << oa.Name() << \" VARIANTS PERFORMED DIFFERENTLY!\\n\" << o1 << \" vs. \" << o2 << endl;\n    exit(1);\n  }\n  cerr << oa.Name() << \" SUCCESS\\n\";\n}\n\nusing namespace std::tr1;\n\nvoid TestOnline() {\n  size_t N = 20;\n  double C = 1.0;\n  double eta0 = 0.2;\n  shared_ptr<LearningRateSchedule> r(new ExponentialDecayLearningRate(N, eta0, 0.85));\n  //shared_ptr<LearningRateSchedule> r(new StandardLearningRate(N, eta0));\n  CumulativeL1OnlineOptimizer opt(r, N, C, std::vector<int>());\n  assert(r->eta(10) < r->eta(1));\n}\n\nint main() {\n  int n = 3;\n  TestOptimizerVariants<LBFGSOptimizer>(n);\n  TestOptimizerVariants<RPropOptimizer>(n);\n  TestOnline();\n  return 0;\n}\n\n", "meta": {"hexsha": "fe7ca70f2fd5ab5d62c30e4c13330bc6373f2b0f", "size": 3158, "ext": "cc", "lang": "C++", "max_stars_repo_path": "training/optimize_test.cc", "max_stars_repo_name": "agesmundo/FasterCubePruning", "max_stars_repo_head_hexsha": "f80150140b5273fd1eb0dfb34bdd789c4cbd35e6", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-03T00:44:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-03T00:44:01.000Z", "max_issues_repo_path": "training/optimize_test.cc", "max_issues_repo_name": "jhclark/cdec", "max_issues_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "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": "training/optimize_test.cc", "max_forks_repo_name": "jhclark/cdec", "max_forks_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-19T12:44:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T12:44:54.000Z", "avg_line_length": 26.5378151261, "max_line_length": 101, "alphanum_fraction": 0.5126662445, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5184875396000056}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2012 - 2021 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: Sven Wetterauer, University of Heidelberg, 2012 \n */ \n\n\n// @sect3{Include files}  \n\n// \u524d\u9762\u51e0\u4e2a\u6587\u4ef6\u5df2\u7ecf\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u8bb2\u8fc7\u4e86\uff0c\u56e0\u6b64\u4e0d\u518d\u505a\u8fdb\u4e00\u6b65\u7684\u8bc4\u8bba\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/utilities.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\n#include <deal.II/dofs/dof_handler.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 <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n\n#include <fstream> \n#include <iostream> \n\n// \u6211\u4eec\u5c06\u5728\u725b\u987f\u8fed\u4ee3\u4e4b\u95f4\u4f7f\u7528\u81ea\u9002\u5e94\u7f51\u683c\u7ec6\u5316\u6280\u672f\u3002\u8981\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u9700\u8981\u80fd\u591f\u5728\u65b0\u7684\u7f51\u683c\u4e0a\u4f7f\u7528\u89e3\u51b3\u65b9\u6848\uff0c\u5c3d\u7ba1\u5b83\u662f\u5728\u65e7\u7684\u7f51\u683c\u4e0a\u8ba1\u7b97\u51fa\u6765\u7684\u3002SolutionTransfer\u7c7b\u5c06\u89e3\u51b3\u65b9\u6848\u4ece\u65e7\u7f51\u683c\u8f6c\u79fb\u5230\u65b0\u7f51\u683c\u3002\n\n#include <deal.II/numerics/solution_transfer.h> \n\n// \u7136\u540e\uff0c\u6211\u4eec\u4e3a\u8fd9\u4e2a\u7a0b\u5e8f\u6253\u5f00\u4e00\u4e2a\u547d\u540d\u7a7a\u95f4\uff0c\u50cf\u4ee5\u524d\u7684\u7a0b\u5e8f\u4e00\u6837\uff0c\u5c06dealii\u547d\u540d\u7a7a\u95f4\u4e2d\u7684\u6240\u6709\u4e1c\u897f\u5bfc\u5165\u5176\u4e2d\u3002\n\nnamespace Step15 \n{ \n  using namespace dealii; \n// @sect3{The <code>MinimalSurfaceProblem</code> class template}  \n\n// \u7c7b\u6a21\u677f\u4e0e  step-6  \u4e2d\u7684\u57fa\u672c\u76f8\u540c\u3002 \u589e\u52a0\u4e86\u4e09\u4e2a\u5185\u5bb9\u3002\n\n// - \u6709\u4e24\u4e2a\u89e3\u51b3\u65b9\u6848\u5411\u91cf\uff0c\u4e00\u4e2a\u7528\u4e8e\u725b\u987f\u66f4\u65b0  $\\delta u^n$  \uff0c\u53e6\u4e00\u4e2a\u7528\u4e8e\u5f53\u524d\u8fed\u4ee3  $u^n$  \u3002\n\n// -  <code>setup_system</code> \u51fd\u6570\u9700\u8981\u4e00\u4e2a\u53c2\u6570\uff0c\u8868\u793a\u8fd9\u662f\u5426\u662f\u7b2c\u4e00\u6b21\u88ab\u8c03\u7528\u3002\u4e0d\u540c\u7684\u662f\uff0c\u7b2c\u4e00\u6b21\u6211\u4eec\u9700\u8981\u5206\u914d\u81ea\u7531\u5ea6\uff0c\u5e76\u5c06 $u^n$ \u7684\u89e3\u5411\u91cf\u8bbe\u7f6e\u4e3a\u6b63\u786e\u7684\u5927\u5c0f\u3002\u63a5\u4e0b\u6765\u7684\u51e0\u6b21\uff0c\u8be5\u51fd\u6570\u662f\u5728\u6211\u4eec\u5df2\u7ecf\u5b8c\u6210\u4e86\u8fd9\u4e9b\u6b65\u9aa4\uff0c\u4f5c\u4e3a\u7ec6\u5316 <code>refine_mesh</code> \u4e2d\u7f51\u683c\u7684\u4e00\u90e8\u5206\u4e4b\u540e\u88ab\u8c03\u7528\u7684\u3002\n\n// - \u7136\u540e\u6211\u4eec\u8fd8\u9700\u8981\u65b0\u7684\u51fd\u6570\u3002  <code>set_boundary_values()</code> \u8d1f\u8d23\u6b63\u786e\u8bbe\u7f6e\u89e3\u5411\u91cf\u7684\u8fb9\u754c\u503c\uff0c\u8fd9\u5728\u4ecb\u7ecd\u7684\u6700\u540e\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u4e86\u3002  <code>compute_residual()</code> \u662f\u4e00\u4e2a\u8ba1\u7b97\u975e\u7ebf\u6027\uff08\u79bb\u6563\uff09\u6b8b\u5dee\u89c4\u8303\u7684\u51fd\u6570\u3002\u6211\u4eec\u7528\u8fd9\u4e2a\u51fd\u6570\u6765\u76d1\u6d4b\u725b\u987f\u8fed\u4ee3\u7684\u6536\u655b\u6027\u3002\u8be5\u51fd\u6570\u4ee5\u6b65\u957f $\\alpha^n$ \u4e3a\u53c2\u6570\u6765\u8ba1\u7b97 $u^n + \\alpha^n \\; \\delta u^n$ \u7684\u6b8b\u5dee\u3002\u8fd9\u662f\u4eba\u4eec\u901a\u5e38\u9700\u8981\u7684\u6b65\u957f\u63a7\u5236\uff0c\u5c3d\u7ba1\u6211\u4eec\u5728\u8fd9\u91cc\u4e0d\u4f1a\u4f7f\u7528\u8fd9\u4e2a\u529f\u80fd\u3002\u6700\u540e\uff0c <code>determine_step_length()</code> \u8ba1\u7b97\u6bcf\u4e2a\u725b\u987f\u8fed\u4ee3\u4e2d\u7684\u6b65\u957f $\\alpha^n$ \u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u4e00\u4e2a\u56fa\u5b9a\u7684\u6b65\u957f\uff0c\u5e76\u628a\u5b9e\u73b0\u4e00\u4e2a\u66f4\u597d\u7684\u7b56\u7565\u4f5c\u4e3a\u4e00\u4e2a\u7ec3\u4e60\u3002(  step-77 \u7684\u505a\u6cd5\u4e0d\u540c\u3002\u5b83\u53ea\u662f\u5728\u6574\u4e2a\u6c42\u89e3\u8fc7\u7a0b\u4e2d\u4f7f\u7528\u4e86\u4e00\u4e2a\u5916\u90e8\u5305\uff0c\u800c\u4e00\u4e2a\u597d\u7684\u76f4\u7ebf\u641c\u7d22\u7b56\u7565\u662f\u8be5\u5305\u6240\u63d0\u4f9b\u7684\u4e00\u90e8\u5206\uff09\u3002)\n\n  template <int dim> \n  class MinimalSurfaceProblem \n  { \n  public: \n    MinimalSurfaceProblem(); \n    void run(); \n\n  private: \n    void   setup_system(const bool initial_step); \n    void   assemble_system(); \n    void   solve(); \n    void   refine_mesh(); \n    void   set_boundary_values(); \n    double compute_residual(const double alpha) const; \n    double determine_step_length() const; \n    void   output_results(const unsigned int refinement_cycle) const; \n\n    Triangulation<dim> triangulation; \n\n    DoFHandler<dim> dof_handler; \n    FE_Q<dim>       fe; \n\n    AffineConstraints<double> hanging_node_constraints; \n\n    SparsityPattern      sparsity_pattern; \n    SparseMatrix<double> system_matrix; \n\n    Vector<double> current_solution; \n    Vector<double> newton_update; \n    Vector<double> system_rhs; \n  }; \n// @sect3{Boundary condition}  \n\n// \u8fb9\u754c\u6761\u4ef6\u7684\u5b9e\u73b0\u5c31\u50cf\u5728  step-4  \u4e2d\u4e00\u6837\u3002 \u5b83\u88ab\u9009\u4e3a  $g(x,y)=\\sin(2 \\pi (x+y))$  \u3002\n\n  template <int dim> \n  class BoundaryValues : 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  template <int dim> \n  double BoundaryValues<dim>::value(const Point<dim> &p, \n                                    const unsigned int /*component*/) const \n  { \n    return std::sin(2 * numbers::PI * (p[0] + p[1])); \n  } \n// @sect3{The <code>MinimalSurfaceProblem</code> class implementation}  \n// @sect4{MinimalSurfaceProblem::MinimalSurfaceProblem}  \n\n// \u8be5\u7c7b\u7684\u6784\u9020\u51fd\u6570\u548c\u6790\u6784\u51fd\u6570\u4e0e\u524d\u51e0\u7bc7\u6559\u7a0b\u4e2d\u7684\u76f8\u540c\u3002\n\n  template <int dim> \n  MinimalSurfaceProblem<dim>::MinimalSurfaceProblem() \n    : dof_handler(triangulation) \n    , fe(2) \n  {} \n// @sect4{MinimalSurfaceProblem::setup_system}  \n\n// \u5728setup-system\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u603b\u662f\u8bbe\u7f6e\u6709\u9650\u5143\u65b9\u6cd5\u7684\u53d8\u91cf\u3002\u4e0e step-6 \u6709\u76f8\u540c\u7684\u533a\u522b\uff0c\u56e0\u4e3a\u5728\u90a3\u91cc\u6211\u4eec\u5728\u6bcf\u4e2a\u7ec6\u5316\u5468\u671f\u4e2d\u90fd\u8981\u4ece\u5934\u5f00\u59cb\u6c42\u89e3PDE\uff0c\u800c\u5728\u8fd9\u91cc\u6211\u4eec\u9700\u8981\u628a\u4ee5\u524d\u7684\u7f51\u683c\u7684\u89e3\u653e\u5230\u5f53\u524d\u7684\u7f51\u683c\u4e0a\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u4e0d\u80fd\u53ea\u662f\u91cd\u7f6e\u89e3\u5411\u91cf\u3002\u56e0\u6b64\uff0c\u4f20\u9012\u7ed9\u8fd9\u4e2a\u51fd\u6570\u7684\u53c2\u6570\u8868\u660e\u6211\u4eec\u662f\u5426\u53ef\u4ee5\u5206\u5e03\u81ea\u7531\u5ea6\uff08\u52a0\u4e0a\u8ba1\u7b97\u7ea6\u675f\uff09\u5e76\u5c06\u89e3\u5411\u91cf\u8bbe\u7f6e\u4e3a\u96f6\uff0c\u6216\u8005\u8fd9\u5728\u5176\u4ed6\u5730\u65b9\u5df2\u7ecf\u53d1\u751f\u8fc7\u4e86\uff08\u7279\u522b\u662f\u5728 <code>refine_mesh()</code> \uff09\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::setup_system(const bool initial_step) \n  { \n    if (initial_step) \n      { \n        dof_handler.distribute_dofs(fe); \n        current_solution.reinit(dof_handler.n_dofs()); \n\n        hanging_node_constraints.clear(); \n        DoFTools::make_hanging_node_constraints(dof_handler, \n                                                hanging_node_constraints); \n        hanging_node_constraints.close(); \n      } \n\n// \u8be5\u51fd\u6570\u7684\u5176\u4f59\u90e8\u5206\u4e0e  step-6  \u4e2d\u7684\u76f8\u540c\u3002\n\n    newton_update.reinit(dof_handler.n_dofs()); \n    system_rhs.reinit(dof_handler.n_dofs()); \n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp); \n\n    hanging_node_constraints.condense(dsp); \n\n    sparsity_pattern.copy_from(dsp); \n    system_matrix.reinit(sparsity_pattern); \n  } \n// @sect4{MinimalSurfaceProblem::assemble_system}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u7684\u4f5c\u7528\u4e0e\u524d\u9762\u7684\u6559\u7a0b\u76f8\u540c\uff0c\u5f53\u7136\uff0c\u73b0\u5728\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u51fd\u6570\u53d6\u51b3\u4e8e\u4e0a\u4e00\u6b21\u8fed\u4ee3\u7684\u89e3\u3002\u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u6211\u4eec\u9700\u8981\u4f7f\u7528\u725b\u987f\u66f4\u65b0\u7684\u96f6\u8fb9\u754c\u503c\uff1b\u6211\u4eec\u5728\u8fd9\u4e2a\u51fd\u6570\u7684\u6700\u540e\u8ba1\u7b97\u5b83\u4eec\u3002\n\n// \u8be5\u51fd\u6570\u7684\u9876\u90e8\u5305\u542b\u4e86\u901a\u5e38\u7684\u6a21\u677f\u4ee3\u7801\uff0c\u8bbe\u7f6e\u4e86\u5141\u8bb8\u6211\u4eec\u5728\u6b63\u4ea4\u70b9\u8bc4\u4f30\u5f62\u72b6\u51fd\u6570\u7684\u5bf9\u8c61\uff0c\u4ee5\u53ca\u672c\u5730\u77e9\u9635\u548c\u5411\u91cf\u7684\u4e34\u65f6\u5b58\u50a8\u4f4d\u7f6e\uff0c\u4ee5\u53ca\u6b63\u4ea4\u70b9\u4e0a\u5148\u524d\u89e3\u7684\u68af\u5ea6\u3002\u7136\u540e\u6211\u4eec\u5f00\u59cb\u5728\u6240\u6709\u5355\u5143\u683c\u4e0a\u8fdb\u884c\u5faa\u73af\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::assemble_system() \n  { \n    const QGauss<dim> quadrature_formula(fe.degree + 1); \n\n    system_matrix = 0; \n    system_rhs    = 0; \n\n    FEValues<dim> fe_values(fe, \n                            quadrature_formula, \n                            update_gradients | update_quadrature_points | \n                              update_JxW_values); \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<double>     cell_rhs(dofs_per_cell); \n\n    std::vector<Tensor<1, dim>> old_solution_gradients(n_q_points); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \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// \u4e3a\u4e86\u7ec4\u88c5\u7ebf\u6027\u7cfb\u7edf\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u6b63\u4ea4\u70b9\u4e0a\u83b7\u5f97\u524d\u4e00\u4e2a\u89e3\u7684\u68af\u5ea6\u503c\u3002\u6709\u4e00\u4e2a\u6807\u51c6\u7684\u65b9\u6cd5\uff1a FEValues::get_function_gradients \u51fd\u6570\u63a5\u6536\u4e00\u4e2a\u4ee3\u8868\u5b9a\u4e49\u5728DoFHandler\u4e0a\u7684\u6709\u9650\u5143\u573a\u7684\u5411\u91cf\uff0c\u5e76\u8bc4\u4f30\u8fd9\u4e2a\u573a\u5728FEValues\u5bf9\u8c61\u6700\u540e\u88ab\u91cd\u65b0\u521d\u59cb\u5316\u7684\u5355\u5143\u7684\u6b63\u4ea4\u70b9\u7684\u68af\u5ea6\u3002\u7136\u540e\u5c06\u6240\u6709\u6b63\u4ea4\u70b9\u7684\u68af\u5ea6\u503c\u5199\u5165\u7b2c\u4e8c\u4e2a\u53c2\u6570\u4e2d\u3002\n\n        fe_values.get_function_gradients(current_solution, \n                                         old_solution_gradients); \n\n// \u6709\u4e86\u8fd9\u4e2a\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5bf9\u6240\u6709\u7684\u6b63\u4ea4\u70b9\u548c\u5f62\u72b6\u51fd\u6570\u8fdb\u884c\u79ef\u5206\u5faa\u73af\u3002 \u5728\u521a\u521a\u8ba1\u7b97\u4e86\u6b63\u4ea4\u70b9\u4e2d\u65e7\u89e3\u7684\u68af\u5ea6\u540e\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u8ba1\u7b97\u8fd9\u4e9b\u70b9\u4e2d\u7684\u7cfb\u6570 $a_{n}$ \u3002 \u7136\u540e\uff0c\u7cfb\u7edf\u672c\u8eab\u7684\u7ec4\u88c5\u770b\u8d77\u6765\u4e0e\u6211\u4eec\u4e00\u8d2f\u7684\u505a\u6cd5\u76f8\u4f3c\uff0c\u9664\u4e86\u975e\u7ebf\u6027\u9879\u4e4b\u5916\uff0c\u5c06\u7ed3\u679c\u4ece\u5c40\u90e8\u5bf9\u8c61\u590d\u5236\u5230\u5168\u5c40\u5bf9\u8c61\u4e2d\u4e5f\u662f\u5982\u6b64\u3002\n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            const double coeff = \n              1.0 / std::sqrt(1 + old_solution_gradients[q] * \n                                    old_solution_gradients[q]); \n\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)      // ((\\nabla \\phi_i \n                       * coeff                         //   * a_n \n                       * fe_values.shape_grad(j, q))   //   * \\nabla \\phi_j) \n                      -                                //  - \n                      (fe_values.shape_grad(i, q)      //  (\\nabla \\phi_i \n                       * coeff * coeff * coeff         //   * a_n^3 \n                       * (fe_values.shape_grad(j, q)   //   * (\\nabla \\phi_j \n                          * old_solution_gradients[q]) //      * \\nabla u_n) \n                       * old_solution_gradients[q]))   //   * \\nabla u_n))) \n                     * fe_values.JxW(q));              // * dx \n\n                cell_rhs(i) -= (fe_values.shape_grad(i, q)  // \\nabla \\phi_i \n                                * coeff                     // * a_n \n                                * old_solution_gradients[q] // * u_n \n                                * fe_values.JxW(q));        // * dx \n              } \n          } \n\n        cell->get_dof_indices(local_dof_indices); \n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          { \n            for (unsigned int j = 0; j < dofs_per_cell; ++j) \n              system_matrix.add(local_dof_indices[i], \n                                local_dof_indices[j], \n                                cell_matrix(i, j)); \n\n            system_rhs(local_dof_indices[i]) += cell_rhs(i); \n          } \n      } \n\n// \u6700\u540e\uff0c\u6211\u4eec\u4ece\u7cfb\u7edf\u4e2d\u79fb\u9664\u60ac\u6302\u7684\u8282\u70b9\uff0c\u5e76\u5c06\u96f6\u8fb9\u754c\u503c\u5e94\u7528\u5230\u5b9a\u4e49\u725b\u987f\u66f4\u65b0\u7684\u7ebf\u6027\u7cfb\u7edf\u4e2d  $\\delta u^n$  \u3002\n\n    hanging_node_constraints.condense(system_matrix); \n    hanging_node_constraints.condense(system_rhs); \n\n    std::map<types::global_dof_index, double> boundary_values; \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             0, \n                                             Functions::ZeroFunction<dim>(), \n                                             boundary_values); \n    MatrixTools::apply_boundary_values(boundary_values, \n                                       system_matrix, \n                                       newton_update, \n                                       system_rhs); \n  } \n\n//  @sect4{MinimalSurfaceProblem::solve}  \n\n// \u89e3\u7b97\u51fd\u6570\u548c\u4ee5\u5f80\u4e00\u6837\u3002\u5728\u6c42\u89e3\u8fc7\u7a0b\u7684\u6700\u540e\uff0c\u6211\u4eec\u901a\u8fc7\u8bbe\u7f6e $u^{n+1}=u^n+\\alpha^n\\;\\delta u^n$ \u6765\u66f4\u65b0\u5f53\u524d\u7684\u89e3\u51b3\u65b9\u6848\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::solve() \n  { \n    SolverControl            solver_control(system_rhs.size(), \n                                 system_rhs.l2_norm() * 1e-6); \n    SolverCG<Vector<double>> solver(solver_control); \n\n    PreconditionSSOR<SparseMatrix<double>> preconditioner; \n    preconditioner.initialize(system_matrix, 1.2); \n\n    solver.solve(system_matrix, newton_update, system_rhs, preconditioner); \n\n    hanging_node_constraints.distribute(newton_update); \n\n    const double alpha = determine_step_length(); \n    current_solution.add(alpha, newton_update); \n  } \n// @sect4{MinimalSurfaceProblem::refine_mesh}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u7684\u7b2c\u4e00\u90e8\u5206\u4e0e step-6 \u4e2d\u7684\u5185\u5bb9\u76f8\u540c ... \u7136\u800c\uff0c\u5728\u7ec6\u5316\u7f51\u683c\u540e\uff0c\u6211\u4eec\u5fc5\u987b\u5c06\u65e7\u7684\u89e3\u51b3\u65b9\u6848\u8f6c\u79fb\u5230\u65b0\u7684\u89e3\u51b3\u65b9\u6848\u4e2d\uff0c\u6211\u4eec\u5728SolutionTransfer\u7c7b\u7684\u5e2e\u52a9\u4e0b\u5b8c\u6210\u3002\u8fd9\u4e2a\u8fc7\u7a0b\u7a0d\u5fae\u6709\u70b9\u590d\u6742\uff0c\u6240\u4ee5\u8ba9\u6211\u4eec\u8be6\u7ec6\u63cf\u8ff0\u4e00\u4e0b\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::refine_mesh() \n  { \n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n\n    KellyErrorEstimator<dim>::estimate( \n      dof_handler, \n      QGauss<dim - 1>(fe.degree + 1), \n      std::map<types::boundary_id, const Function<dim> *>(), \n      current_solution, \n      estimated_error_per_cell); \n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    estimated_error_per_cell, \n                                                    0.3, \n                                                    0.03); \n\n// \u7136\u540e\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u989d\u5916\u7684\u6b65\u9aa4\uff1a\u4f8b\u5982\uff0c\u5982\u679c\u4f60\u6807\u8bb0\u4e86\u4e00\u4e2a\u6bd4\u5b83\u7684\u90bb\u5c45\u66f4\u7cbe\u70bc\u4e00\u6b21\u7684\u5355\u5143\uff0c\u800c\u8fd9\u4e2a\u90bb\u5c45\u6ca1\u6709\u88ab\u6807\u8bb0\u4e3a\u7cbe\u70bc\uff0c\u6211\u4eec\u6700\u7ec8\u4f1a\u5728\u4e00\u4e2a\u5355\u5143\u754c\u9762\u4e0a\u8df3\u8fc7\u4e24\u4e2a\u7cbe\u70bc\u7ea7\u522b\u3002 \u4e3a\u4e86\u907f\u514d\u8fd9\u4e9b\u60c5\u51b5\uff0c\u5e93\u5c06\u9ed8\u9ed8\u5730\u4e5f\u8981\u5bf9\u90bb\u5c45\u5355\u5143\u8fdb\u884c\u4e00\u6b21\u7ec6\u5316\u3002\u5b83\u901a\u8fc7\u5728\u5b9e\u9645\u8fdb\u884c\u7ec6\u5316\u548c\u7c97\u5316\u4e4b\u524d\u8c03\u7528 Triangulation::prepare_coarsening_and_refinement \u51fd\u6570\u6765\u5b9e\u73b0\u3002 \u8fd9\u4e2a\u51fd\u6570\u6807\u5fd7\u7740\u4e00\u7ec4\u989d\u5916\u7684\u5355\u5143\u683c\u8fdb\u884c\u7ec6\u5316\u6216\u7c97\u5316\uff0c\u4ee5\u6267\u884c\u50cf\u5355\u60ac\u8282\u70b9\u89c4\u5219\u8fd9\u6837\u7684\u89c4\u5219\u3002 \u8c03\u7528\u6b64\u51fd\u6570\u540e\uff0c\u88ab\u6807\u8bb0\u4e3a\u7ec6\u5316\u548c\u7c97\u5316\u7684\u5355\u5143\u683c\u6b63\u662f\u90a3\u4e9b\u5c06\u88ab\u5b9e\u9645\u7ec6\u5316\u6216\u7c97\u5316\u7684\u5355\u5143\u683c\u3002\u901a\u5e38\u60c5\u51b5\u4e0b\uff0c\u4f60\u4e0d\u9700\u8981\u624b\u5de5\u64cd\u4f5c (Triangulation::execute_coarsening_and_refinement \u4e3a\u4f60\u505a\u8fd9\u4e2a\uff09\u3002) \u7136\u800c\uff0c\u6211\u4eec\u9700\u8981\u521d\u59cb\u5316SolutionTransfer\u7c7b\uff0c\u5b83\u9700\u8981\u77e5\u9053\u6700\u7ec8\u5c06\u88ab\u7c97\u5316\u6216\u7ec6\u5316\u7684\u5355\u5143\u96c6\uff0c\u4ee5\u4fbf\u5b58\u50a8\u65e7\u7f51\u683c\u7684\u6570\u636e\u5e76\u8f6c\u79fb\u5230\u65b0\u7f51\u683c\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u624b\u52a8\u8c03\u7528\u8fd9\u4e2a\u51fd\u6570\u3002\n\n    triangulation.prepare_coarsening_and_refinement(); \n\n// \u6709\u4e86\u8fd9\u4e2a\u65b9\u6cd5\uff0c\u6211\u4eec\u7528\u73b0\u5728\u7684DoFHandler\u521d\u59cb\u5316\u4e00\u4e2aSolutionTransfer\u5bf9\u8c61\uff0c\u5e76\u5c06\u89e3\u51b3\u65b9\u6848\u5411\u91cf\u9644\u52a0\u5230\u5b83\u4e0a\u9762\uff0c\u7136\u540e\u5728\u65b0\u7f51\u683c\u4e0a\u8fdb\u884c\u5b9e\u9645\u7684\u7ec6\u5316\u548c\u81ea\u7531\u5ea6\u5206\u914d\n\n    SolutionTransfer<dim> solution_transfer(dof_handler); \n    solution_transfer.prepare_for_coarsening_and_refinement(current_solution); \n\n    triangulation.execute_coarsening_and_refinement(); \n\n    dof_handler.distribute_dofs(fe); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u627e\u56de\u63d2\u503c\u5230\u65b0\u7f51\u683c\u7684\u65e7\u89e3\u3002\u7531\u4e8eSolutionTransfer\u51fd\u6570\u5b9e\u9645\u4e0a\u5e76\u4e0d\u5b58\u50a8\u65e7\u7684\u89e3\u51b3\u65b9\u6848\u7684\u503c\uff0c\u800c\u662f\u7d22\u5f15\uff0c\u6211\u4eec\u9700\u8981\u4fdd\u7559\u65e7\u7684\u89e3\u51b3\u65b9\u6848\u5411\u91cf\uff0c\u76f4\u5230\u6211\u4eec\u5f97\u5230\u65b0\u7684\u5185\u63d2\u503c\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5c06\u65b0\u7684\u6570\u503c\u5199\u5165\u4e00\u4e2a\u4e34\u65f6\u7684\u5411\u91cf\u4e2d\uff0c\u4e4b\u540e\u624d\u5c06\u5176\u5199\u5165\u89e3\u51b3\u65b9\u6848\u5411\u91cf\u5bf9\u8c61\u4e2d\u3002\n\n    Vector<double> tmp(dof_handler.n_dofs()); \n    solution_transfer.interpolate(current_solution, tmp); \n    current_solution = tmp; \n\n// \u5728\u65b0\u7684\u7f51\u683c\u4e0a\uff0c\u6709\u4e0d\u540c\u7684\u60ac\u6302\u8282\u70b9\uff0c\u5bf9\u4e8e\u8fd9\u4e9b\u8282\u70b9\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u6254\u6389\u4e4b\u524d\u7684\u5bf9\u8c61\u5185\u5bb9\u540e\uff0c\u91cd\u65b0\u8ba1\u7b97\u7ea6\u675f\u3002\u4e3a\u4e86\u5b89\u5168\u8d77\u89c1\uff0c\u6211\u4eec\u8fd8\u5e94\u8be5\u786e\u4fdd\u5f53\u524d\u89e3\u51b3\u65b9\u6848\u7684\u5411\u91cf\u6761\u76ee\u6ee1\u8db3\u60ac\u7a7a\u8282\u70b9\u7684\u7ea6\u675f\u6761\u4ef6\uff08\u53c2\u89c1SolutionTransfer\u7c7b\u6587\u6863\u4e2d\u7684\u8ba8\u8bba\uff0c\u4e86\u89e3\u4e3a\u4ec0\u4e48\u5fc5\u987b\u8fd9\u6837\u505a\uff09\u3002\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u660e\u786e\u8c03\u7528`hanging_node_constraints.distribution(current_solution)`\u6765\u505a\u5230\u8fd9\u4e00\u70b9\uff1b\u6211\u4eec\u7701\u7565\u8fd9\u4e00\u6b65\uff0c\u56e0\u4e3a\u8fd9\u5c06\u5728\u4e0b\u9762\u8c03\u7528`set_boundary_values()`\u7684\u6700\u540e\u53d1\u751f\uff0c\u800c\u4e14\u6ca1\u6709\u5fc5\u8981\u505a\u4e24\u6b21\u3002\n\n    hanging_node_constraints.clear(); \n\n    DoFTools::make_hanging_node_constraints(dof_handler, \n                                            hanging_node_constraints); \n    hanging_node_constraints.close(); \n\n// \u4e00\u65e6\u6211\u4eec\u6709\u4e86\u5185\u63d2\u7684\u89e3\u51b3\u65b9\u6848\u548c\u6240\u6709\u5173\u4e8e\u60ac\u6302\u8282\u70b9\u7684\u4fe1\u606f\uff0c\u6211\u4eec\u5fc5\u987b\u786e\u4fdd\u6211\u4eec\u73b0\u5728\u7684 $u^n$ \u5b9e\u9645\u4e0a\u6709\u6b63\u786e\u7684\u8fb9\u754c\u503c\u3002\u6b63\u5982\u5728\u4ecb\u7ecd\u7684\u6700\u540e\u6240\u89e3\u91ca\u7684\uff0c\u5373\u4f7f\u7ec6\u5316\u524d\u7684\u89e3\u51b3\u65b9\u6848\u6709\u6b63\u786e\u7684\u8fb9\u754c\u503c\uff0c\u4e5f\u4e0d\u4f1a\u81ea\u52a8\u51fa\u73b0\u8fd9\u79cd\u60c5\u51b5\uff0c\u56e0\u6b64\u6211\u4eec\u5fc5\u987b\u660e\u786e\u5730\u786e\u4fdd\u5b83\u73b0\u5728\u6709\u3002\n\n    set_boundary_values(); \n\n// \u6211\u4eec\u901a\u8fc7\u66f4\u65b0\u6240\u6709\u5269\u4f59\u7684\u6570\u636e\u7ed3\u6784\u6765\u7ed3\u675f\u8fd9\u4e2a\u51fd\u6570\uff0c\u5411 <code>setup_dofs()</code> \u8868\u660e\u8fd9\u4e0d\u662f\u7b2c\u4e00\u6b21\u4e86\uff0c\u5b83\u9700\u8981\u4fdd\u7559\u89e3\u5411\u91cf\u7684\u5185\u5bb9\u3002\n\n    setup_system(false); \n  } \n\n//  @sect4{MinimalSurfaceProblem::set_boundary_values}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u786e\u4fdd\u89e3\u5411\u91cf\u7684\u6761\u76ee\u5c0a\u91cd\u6211\u4eec\u95ee\u9898\u7684\u8fb9\u754c\u503c\u3002 \u5728\u7ec6\u5316\u4e86\u7f51\u683c\u4e4b\u540e\uff08\u6216\u8005\u521a\u521a\u5f00\u59cb\u8ba1\u7b97\uff09\uff0c\u8fb9\u754c\u4e0a\u53ef\u80fd\u4f1a\u51fa\u73b0\u65b0\u7684\u8282\u70b9\u3002\u8fd9\u4e9b\u8282\u70b9\u7684\u6570\u503c\u662f\u5728`refine_mesh()`\u4e2d\u4ece\u4e4b\u524d\u7684\u7f51\u683c\u4e2d\u7b80\u5355\u63d2\u503c\u51fa\u6765\u7684\uff0c\u800c\u4e0d\u662f\u6b63\u786e\u7684\u8fb9\u754c\u503c\u3002\u8fd9\u4e2a\u95ee\u9898\u53ef\u4ee5\u901a\u8fc7\u5c06\u5f53\u524d\u89e3\u51b3\u65b9\u6848\u5411\u91cf\u7684\u6240\u6709\u8fb9\u754c\u8282\u70b9\u660e\u786e\u8bbe\u7f6e\u4e3a\u6b63\u786e\u7684\u503c\u6765\u89e3\u51b3\u3002\n\n// \u4f46\u662f\u6709\u4e00\u4e2a\u95ee\u9898\u6211\u4eec\u5fc5\u987b\u6ce8\u610f\uff1a\u5982\u679c\u6211\u4eec\u6709\u4e00\u4e2a\u6302\u8d77\u7684\u8282\u70b9\u7d27\u6328\u7740\u4e00\u4e2a\u65b0\u7684\u8fb9\u754c\u8282\u70b9\uff0c\u90a3\u4e48\u5b83\u7684\u503c\u4e5f\u5fc5\u987b\u88ab\u8c03\u6574\u4ee5\u786e\u4fdd\u6709\u9650\u5143\u573a\u4fdd\u6301\u8fde\u7eed\u3002\u8fd9\u5c31\u662f\u8fd9\u4e2a\u51fd\u6570\u6700\u540e\u4e00\u884c\u7684\u8c03\u7528\u6240\u505a\u7684\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::set_boundary_values() \n  { \n    std::map<types::global_dof_index, double> boundary_values; \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             0, \n                                             BoundaryValues<dim>(), \n                                             boundary_values); \n    for (auto &boundary_value : boundary_values) \n      current_solution(boundary_value.first) = boundary_value.second; \n\n    hanging_node_constraints.distribute(current_solution); \n  } \n// @sect4{MinimalSurfaceProblem::compute_residual}  \n\n// \u4e3a\u4e86\u76d1\u6d4b\u6536\u655b\u6027\uff0c\u6211\u4eec\u9700\u8981\u4e00\u79cd\u65b9\u6cd5\u6765\u8ba1\u7b97\uff08\u79bb\u6563\uff09\u6b8b\u5dee\u7684\u89c4\u8303\uff0c\u5373\u5728\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u5411\u91cf $\\left<F(u^n),\\varphi_i\\right>$ \u4e0e $F(u)=-\\nabla \\cdot \\left(\\frac{1}{\\sqrt{1+|\\nabla u|^{2}}}\\nabla u \\right)$ \u7684\u89c4\u8303\u3002\u4e8b\u5b9e\u8bc1\u660e\uff0c\uff08\u5c3d\u7ba1\u6211\u4eec\u5728\u5f53\u524d\u7248\u672c\u7684\u7a0b\u5e8f\u4e2d\u6ca1\u6709\u4f7f\u7528\u8fd9\u4e2a\u529f\u80fd\uff09\u5728\u786e\u5b9a\u6700\u4f73\u6b65\u957f\u65f6\u9700\u8981\u8ba1\u7b97\u6b8b\u5dee $\\left<F(u^n+\\alpha^n\\;\\delta u^n),\\varphi_i\\right>$ \uff0c\u56e0\u6b64\u8fd9\u5c31\u662f\u6211\u4eec\u5728\u8fd9\u91cc\u5b9e\u73b0\u7684\uff1a\u8be5\u51fd\u6570\u5c06\u6b65\u957f $\\alpha^n$ \u4f5c\u4e3a\u53c2\u6570\u3002\u539f\u6709\u7684\u529f\u80fd\u5f53\u7136\u662f\u901a\u8fc7\u4f20\u9012\u4e00\u4e2a\u96f6\u4f5c\u4e3a\u53c2\u6570\u5f97\u5230\u7684\u3002\n\n// \u5728\u4e0b\u9762\u7684\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u9996\u5148\u4e3a\u6b8b\u5dee\u8bbe\u7f6e\u4e00\u4e2a\u5411\u91cf\uff0c\u7136\u540e\u4e3a\u8bc4\u4f30\u70b9\u8bbe\u7f6e\u4e00\u4e2a\u5411\u91cf  $u^n+\\alpha^n\\;\\delta u^n$  \u3002\u63a5\u4e0b\u6765\u662f\u6211\u4eec\u5728\u6240\u6709\u7684\u79ef\u5206\u64cd\u4f5c\u4e2d\u4f7f\u7528\u7684\u76f8\u540c\u7684\u6a21\u677f\u4ee3\u7801\u3002\n\n  template <int dim> \n  double MinimalSurfaceProblem<dim>::compute_residual(const double alpha) const \n  { \n    Vector<double> residual(dof_handler.n_dofs()); \n\n    Vector<double> evaluation_point(dof_handler.n_dofs()); \n    evaluation_point = current_solution; \n    evaluation_point.add(alpha, newton_update); \n\n    const QGauss<dim> quadrature_formula(fe.degree + 1); \n    FEValues<dim>     fe_values(fe, \n                            quadrature_formula, \n                            update_gradients | update_quadrature_points | \n                              update_JxW_values); \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    Vector<double>              cell_residual(dofs_per_cell); \n    std::vector<Tensor<1, dim>> gradients(n_q_points); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        cell_residual = 0; \n        fe_values.reinit(cell); \n\n// \u5b9e\u9645\u7684\u8ba1\u7b97\u4e0e  <code>assemble_system()</code>  \u4e2d\u7684\u8ba1\u7b97\u5dee\u4e0d\u591a\u3002\u6211\u4eec\u9996\u5148\u8bc4\u4f30 $u^n+\\alpha^n\\,\\delta u^n$ \u5728\u6b63\u4ea4\u70b9\u7684\u68af\u5ea6\uff0c\u7136\u540e\u8ba1\u7b97\u7cfb\u6570 $a_n$ \uff0c\u7136\u540e\u5c06\u5176\u5168\u90e8\u63d2\u5165\u6b8b\u5dee\u516c\u5f0f\u4e2d\u3002\n\n        fe_values.get_function_gradients(evaluation_point, gradients); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            const double coeff = \n              1. / std::sqrt(1 + gradients[q] * gradients[q]); \n\n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              cell_residual(i) -= (fe_values.shape_grad(i, q) // \\nabla \\phi_i \n                                   * coeff                    // * a_n \n                                   * gradients[q]             // * u_n \n                                   * fe_values.JxW(q));       // * dx \n          } \n\n        cell->get_dof_indices(local_dof_indices); \n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          residual(local_dof_indices[i]) += cell_residual(i); \n      } \n\n// \u5728\u8fd9\u4e2a\u51fd\u6570\u7684\u6700\u540e\uff0c\u6211\u4eec\u8fd8\u5fc5\u987b\u5904\u7406\u60ac\u6302\u8282\u70b9\u7684\u7ea6\u675f\u548c\u8fb9\u754c\u503c\u7684\u95ee\u9898\u3002\u5173\u4e8e\u540e\u8005\uff0c\u6211\u4eec\u5fc5\u987b\u5c06\u6240\u6709\u5bf9\u5e94\u4e8e\u4f4d\u4e8e\u8fb9\u754c\u7684\u81ea\u7531\u5ea6\u7684\u6761\u76ee\u7684\u6b8b\u5dee\u5411\u91cf\u5143\u7d20\u8bbe\u7f6e\u4e3a\u96f6\u3002\u539f\u56e0\u662f\uff0c\u7531\u4e8e\u90a3\u91cc\u7684\u89e3\u7684\u503c\u662f\u56fa\u5b9a\u7684\uff0c\u5b83\u4eec\u5f53\u7136\u4e0d\u662f \"\u771f\u6b63\u7684 \"\u81ea\u7531\u5ea6\uff0c\u56e0\u6b64\uff0c\u4e25\u683c\u6765\u8bf4\uff0c\u6211\u4eec\u4e0d\u5e94\u8be5\u5728\u6b8b\u5dee\u5411\u91cf\u4e2d\u4e3a\u5b83\u4eec\u96c6\u5408\u6761\u76ee\u3002\u7136\u800c\uff0c\u6b63\u5982\u6211\u4eec\u4e00\u76f4\u6240\u505a\u7684\u90a3\u6837\uff0c\u6211\u4eec\u60f3\u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\u505a\u5b8c\u5168\u76f8\u540c\u7684\u4e8b\u60c5\uff0c\u56e0\u6b64\u6211\u4eec\u5e76\u4e0d\u60f3\u5728\u4e0a\u9762\u7684\u79ef\u5206\u4e2d\u5904\u7406\u67d0\u4e2a\u81ea\u7531\u5ea6\u662f\u5426\u4f4d\u4e8e\u8fb9\u754c\u7684\u95ee\u9898\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u5c06\u7b80\u5355\u5730\u5728\u4e8b\u540e\u5c06\u8fd9\u4e9b\u6761\u76ee\u8bbe\u7f6e\u4e3a\u96f6\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9700\u8981\u786e\u5b9a\u54ea\u4e9b\u81ea\u7531\u5ea6\u5b9e\u9645\u4e0a\u5c5e\u4e8e\u8fb9\u754c\uff0c\u7136\u540e\u5728\u6240\u6709\u8fd9\u4e9b\u81ea\u7531\u5ea6\u4e0a\u8fdb\u884c\u5faa\u73af\uff0c\u5e76\u5c06\u5269\u4f59\u6761\u76ee\u8bbe\u7f6e\u4e3a\u96f6\u3002\u8fd9\u53d1\u751f\u5728\u4ee5\u4e0b\u51e0\u884c\u4e2d\uff0c\u6211\u4eec\u5df2\u7ecf\u5728 step-11 \u4e2d\u770b\u5230\u4e86\u4f7f\u7528DoFTools\u547d\u540d\u7a7a\u95f4\u7684\u9002\u5f53\u51fd\u6570\u3002\n\n    hanging_node_constraints.condense(residual); \n\n    for (types::global_dof_index i : \n         DoFTools::extract_boundary_dofs(dof_handler)) \n      residual(i) = 0; \n\n// \u5728\u51fd\u6570\u7684\u6700\u540e\uff0c\u6211\u4eec\u8fd4\u56de\u6b8b\u5dee\u7684\u5e38\u6570\u3002\n\n    return residual.l2_norm(); \n  } \n\n//  @sect4{MinimalSurfaceProblem::determine_step_length}  \n\n// \u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u5982\u679c\u6211\u4eec\u603b\u662f\u91c7\u53d6\u5168\u6b65\uff0c\u5373\u8ba1\u7b97 $u^{n+1}=u^n+\\delta u^n$ \uff0c\u725b\u987f\u65b9\u6cd5\u7ecf\u5e38\u4e0d\u6536\u655b\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u963b\u5c3c\u53c2\u6570\uff08\u6b65\u957f\uff09  $\\alpha^n$  \u5e76\u8bbe\u7f6e  $u^{n+1}=u^n+\\alpha^n\\delta u^n$  \u3002\u8fd9\u4e2a\u51fd\u6570\u662f\u7528\u6765\u8ba1\u7b97 $\\alpha^n$  \u7684\u3002\n\n// \u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u7b80\u5355\u5730\u603b\u662f\u8fd4\u56de0.1\u3002\u8fd9\u5f53\u7136\u662f\u4e00\u4e2a\u6b21\u4f18\u7684\u9009\u62e9\uff1a\u7406\u60f3\u60c5\u51b5\u4e0b\uff0c\u4eba\u4eec\u5e0c\u671b\u7684\u662f\uff0c\u5f53\u6211\u4eec\u8d8a\u6765\u8d8a\u63a5\u8fd1\u89e3\u7684\u65f6\u5019\uff0c\u6b65\u957f\u53d8\u62101\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u4eab\u53d7\u725b\u987f\u65b9\u6cd5\u7684\u5feb\u901f\u4e8c\u6b21\u6536\u655b\u3002\u6211\u4eec\u5c06\u5728\u4e0b\u9762\u7684\u7ed3\u679c\u90e8\u5206\u8ba8\u8bba\u66f4\u597d\u7684\u7b56\u7565\uff0c step-77 \u4e5f\u6d89\u53ca\u8fd9\u65b9\u9762\u7684\u5185\u5bb9\u3002\n\n  template <int dim> \n  double MinimalSurfaceProblem<dim>::determine_step_length() const \n  { \n    return 0.1; \n  } \n\n//  @sect4{MinimalSurfaceProblem::output_results}  \n\n// \u4ece`run()`\u8c03\u7528\u7684\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u4ee5\u56fe\u5f62\u5f62\u5f0f\u8f93\u51fa\u5f53\u524d\u7684\u89e3\u51b3\u65b9\u6848\uff08\u548c\u725b\u987f\u66f4\u65b0\uff09\uff0c\u4f5c\u4e3aVTU\u6587\u4ef6\u3002\u5b83\u4e0e\u4e4b\u524d\u6559\u7a0b\u4e2d\u4f7f\u7528\u7684\u5b8c\u5168\u76f8\u540c\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::output_results( \n    const unsigned int refinement_cycle) const \n  { \n    DataOut<dim> data_out; \n\n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(current_solution, \"solution\"); \n    data_out.add_data_vector(newton_update, \"update\"); \n    data_out.build_patches(); \n\n    const std::string filename = \n      \"solution-\" + Utilities::int_to_string(refinement_cycle, 2) + \".vtu\"; \n    std::ofstream output(filename); \n    data_out.write_vtu(output); \n  } \n// @sect4{MinimalSurfaceProblem::run}  \n\n// \u5728\u8fd0\u884c\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u5efa\u7acb\u7b2c\u4e00\u4e2a\u7f51\u683c\uff0c\u7136\u540e\u6709\u725b\u987f\u8fed\u4ee3\u7684\u9876\u5c42\u903b\u8f91\u3002\n\n// \u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u63cf\u8ff0\u7684\uff0c\u9886\u57df\u662f\u56f4\u7ed5\u539f\u70b9\u7684\u5355\u4f4d\u5706\u76d8\uff0c\u521b\u5efa\u65b9\u5f0f\u4e0e step-6 \u4e2d\u6240\u793a\u76f8\u540c\u3002\u7f51\u683c\u7ecf\u8fc7\u4e24\u6b21\u5168\u5c40\u7ec6\u5316\uff0c\u7136\u540e\u518d\u8fdb\u884c\u82e5\u5e72\u6b21\u9002\u5e94\u6027\u5faa\u73af\u3002\n\n// \u5728\u5f00\u59cb\u725b\u987f\u5faa\u73af\u4e4b\u524d\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u505a\u4e00\u4e9b\u8bbe\u7f6e\u5de5\u4f5c\u3002\u6211\u4eec\u9700\u8981\u521b\u5efa\u57fa\u672c\u7684\u6570\u636e\u7ed3\u6784\uff0c\u5e76\u786e\u4fdd\u7b2c\u4e00\u4e2a\u725b\u987f\u8fed\u4ee3\u5df2\u7ecf\u6709\u4e86\u6b63\u786e\u7684\u8fb9\u754c\u503c\uff0c\u8fd9\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u4e86\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::run() \n  { \n    GridGenerator::hyper_ball(triangulation); \n    triangulation.refine_global(2); \n\n    setup_system(/*first time=*/true); \n    set_boundary_values(); \n\n// \u63a5\u4e0b\u6765\u5f00\u59cb\u725b\u987f\u8fed\u4ee3\u3002\u6211\u4eec\u4e00\u76f4\u8fed\u4ee3\u5230\u4e0a\u4e00\u6b21\u8fed\u4ee3\u7ed3\u675f\u65f6\u8ba1\u7b97\u7684\u6b8b\u5dee\uff08\u89c4\u8303\uff09\u5c0f\u4e8e $10^{-3}$ \uff0c\u6b63\u5982\u5728 \"do{ ... } while \"\u5faa\u73af\u7ed3\u675f\u65f6\u7684\u68c0\u67e5\u3002\u56e0\u4e3a\u6211\u4eec\u6ca1\u6709\u4e00\u4e2a\u5408\u7406\u7684\u503c\u6765\u521d\u59cb\u5316\u8fd9\u4e2a\u53d8\u91cf\uff0c\u6240\u4ee5\u6211\u4eec\u53ea\u662f\u4f7f\u7528\u53ef\u4ee5\u8868\u793a\u4e3a`\u53cc\u6570'\u7684\u6700\u5927\u503c\u3002\n\n    double       last_residual_norm = std::numeric_limits<double>::max(); \n    unsigned int refinement_cycle   = 0; \n    do \n      { \n        std::cout << \"Mesh refinement step \" << refinement_cycle << std::endl; \n\n        if (refinement_cycle != 0) \n          refine_mesh(); \n\n// \u5728\u6bcf\u4e2a\u7f51\u683c\u4e0a\uff0c\u6211\u4eec\u6b63\u597d\u505a\u4e94\u4e2a\u725b\u987f\u6b65\u9aa4\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u6253\u5370\u521d\u59cb\u6b8b\u5dee\uff0c\u7136\u540e\u5728\u8fd9\u4e2a\u7f51\u683c\u4e0a\u5f00\u59cb\u8fed\u4ee3\u3002\n\n// \u5728\u6bcf\u4e00\u4e2a\u725b\u987f\u6b65\u9aa4\u4e2d\uff0c\u9996\u5148\u8981\u8ba1\u7b97\u7cfb\u7edf\u77e9\u9635\u548c\u53f3\u624b\u8fb9\uff0c\u7136\u540e\u6211\u4eec\u5b58\u50a8\u53f3\u624b\u8fb9\u7684\u89c4\u8303\u4f5c\u4e3a\u6b8b\u5dee\uff0c\u4ee5\u4fbf\u5728\u51b3\u5b9a\u662f\u5426\u505c\u6b62\u8fed\u4ee3\u65f6\u8fdb\u884c\u68c0\u67e5\u3002\u7136\u540e\u6211\u4eec\u6c42\u89e3\u7ebf\u6027\u7cfb\u7edf\uff08\u8be5\u51fd\u6570\u4e5f\u4f1a\u66f4\u65b0 $u^{n+1}=u^n+\\alpha^n\\;\\delta u^n$ \uff09\uff0c\u5e76\u5728\u8fd9\u4e2a\u725b\u987f\u6b65\u9aa4\u7ed3\u675f\u65f6\u8f93\u51fa\u6b8b\u5dee\u7684\u51c6\u5219\u3002\n\n// \u5728\u8fd9\u4e2a\u5faa\u73af\u7ed3\u675f\u540e\uff0c\u6211\u4eec\u8fd8\u5c06\u4ee5\u56fe\u5f62\u5f62\u5f0f\u8f93\u51fa\u5f53\u524d\u7f51\u683c\u4e0a\u7684\u89e3\uff0c\u5e76\u589e\u52a0\u7f51\u683c\u7ec6\u5316\u5faa\u73af\u7684\u8ba1\u6570\u5668\u3002\n\n        std::cout << \"  Initial residual: \" << compute_residual(0) << std::endl; \n\n        for (unsigned int inner_iteration = 0; inner_iteration < 5; \n             ++inner_iteration) \n          { \n            assemble_system(); \n            last_residual_norm = system_rhs.l2_norm(); \n\n            solve(); \n\n            std::cout << \"  Residual: \" << compute_residual(0) << std::endl; \n          } \n\n        output_results(refinement_cycle); \n\n        ++refinement_cycle; \n        std::cout << std::endl; \n      } \n    while (last_residual_norm > 1e-3); \n  } \n} // namespace Step15 \n// @sect4{The main function}  \n\n// \u6700\u540e\u662f\u4e3b\u51fd\u6570\u3002\u8fd9\u9075\u5faa\u4e86\u6240\u6709\u5176\u4ed6\u4e3b\u51fd\u6570\u7684\u65b9\u6848\u3002\n\nint main() \n{ \n  try \n    { \n      using namespace Step15; \n\n      MinimalSurfaceProblem<2> laplace_problem_2d; \n      laplace_problem_2d.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\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\n\n\n", "meta": {"hexsha": "5524f73f2bcf13a05db99be95d752e030cd9585d", "size": 20718, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-15/step-15.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-15/step-15.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-15/step-15.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.9964285714, "max_line_length": 415, "alphanum_fraction": 0.6283907713, "num_tokens": 7813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.518487535639913}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// example::iterator::flatten_iterator2.cpp                                  //\n//                                                                           //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n/////////////////////////////////////////////////////////////////////////////// \n#include <iostream>\n#include <boost/array.hpp>\n#include <boost/multi_array.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/assign/list_of.hpp>\n#include <boost/range.hpp>\n#include <vector>\n#include <boost/iterator/flatten_iterator.hpp>\n#include <boost/range/flatten_range.hpp>\n#include <libs/iterator/example/flatten_iterator2.h>\n\nvoid example_flatten_iterator2(std::ostream& out){\n    out << \"->example_flatten_iterator2 : \";\n\n    using namespace boost;\n    typedef int val_;\n    typedef std::vector<val_>\t\t\t\t\t\t\tvals_;\n\ttypedef boost::multi_array<val_, 2> \t\t\t\tma_;\n\ttypedef boost::multi_array_types::index_range \t\tidx_range_;\n\ttypedef boost::multi_array_types::index \t\t\tidx_;\n    typedef boost::range_iterator<const ma_>::type\t\tit_ma_;\n    typedef flatten_iterator<it_ma_>\t\t\t\t\tflat_it_;\n    \n    typedef boost::array_view_gen<ma_,2>::type \t\t\tview2_;\n    typedef boost::range_iterator<view2_>::type \t\tnit2_;\n    typedef flatten_iterator<nit2_>\t\t\t\t\t\tflat_it2_;\n\n    typedef boost::array_view_gen<ma_,1>::type \t\t\tview1_;\n    \n    //  \tarray_type::index_gen indices;\n    //  \tarray_type::array_view<2>::type myview =\n    //    myarray[ indices[range(0,2)][1][range(0,4,2)] ];\n\n    ma_ ma(boost::extents[2][5]);\n    {\n        vals_ vals1;\n    \tusing namespace boost::assign;\n        vals1 += 1,2,3,4,5;\n        vals1 += 6,7,8,9,10;\n        vals1 += 11,12,13,14,15;\n        ma.assign(boost::begin(vals1),boost::end(vals1));\n\t}        \n\n//    view1_ view1 = ma[ boost::indices[1][idx_range_(0,4)] ]; // idx_range_(0,2)\n//    typedef boost::range_iterator<const view_>::type nit_;\n\n    view2_ view2 = ma[ boost::indices[idx_range_()][idx_range_(0,4)] ]; // idx_range_(0,2)\n//    typedef boost::range_iterator<view2_>::type nit2_;\n//    nit2_ nit2 = boost::begin(view2);\n\n\tflat_it2_ it2_b(boost::begin(view2),boost::end(view2));\n\tflat_it2_ it2_e(boost::end(view2),boost::end(view2));\n    std::copy(it2_b,it2_e,std::ostream_iterator<val_>(std::cout,\" \"));\n\n//\tit_ma_ it_ma = boost::begin(ma);\n//    flat_it_ b(ma.begin(),ma.end());\n\n    //\tma[boost::indices[1][idx_range_(0,4)]] = vals1; //assign(boost::begin(vals1),boost::end(vals1));\n    //\tma(boost::indices[1]); \n\n    out << \"<-\" << std::endl;\n}", "meta": {"hexsha": "49dde837d8596caa04b156c65a336a3b8c470acb", "size": 2603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "iterator/libs/iterator/example/flatten_iterator2.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": "iterator/libs/iterator/example/flatten_iterator2.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": "iterator/libs/iterator/example/flatten_iterator2.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": 38.8507462687, "max_line_length": 103, "alphanum_fraction": 0.5897041875, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.518487535639913}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-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#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SIDE_BY_CROSS_TRACK_HPP\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SIDE_BY_CROSS_TRACK_HPP\n\n#include <boost/mpl/if.hpp>\n#include <boost/type_traits.hpp>\n#include <boost/core/ignore_unused.hpp>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n\n#include <boost/geometry/util/select_coordinate_type.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/strategies/side.hpp>\n//#include <boost/geometry/strategies/concepts/side_concept.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n\nnamespace strategy { namespace side\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\n/// Calculate course (bearing) between two points. Might be moved to a \"course formula\" ...\ntemplate <typename Point>\nstatic inline double course(Point const& p1, Point const& p2)\n{\n    // http://williams.best.vwh.net/avform.htm#Crs\n    double dlon = get_as_radian<0>(p2) - get_as_radian<0>(p1);\n    double cos_p2lat = cos(get_as_radian<1>(p2));\n\n    // \"An alternative formula, not requiring the pre-computation of d\"\n    return atan2(sin(dlon) * cos_p2lat,\n        cos(get_as_radian<1>(p1)) * sin(get_as_radian<1>(p2))\n        - sin(get_as_radian<1>(p1)) * cos_p2lat * cos(dlon));\n}\n\n}\n#endif // DOXYGEN_NO_DETAIL\n\n\n\n/*!\n\\brief Check at which side of a Great Circle segment a point lies\n         left of segment (> 0), right of segment (< 0), on segment (0)\n\\ingroup strategies\n\\tparam CalculationType \\tparam_calculation\n */\ntemplate <typename CalculationType = void>\nclass side_by_cross_track\n{\n\npublic :\n    template <typename P1, typename P2, typename P>\n    static inline int apply(P1 const& p1, P2 const& p2, P const& p)\n    {\n        typedef typename boost::mpl::if_c\n            <\n                boost::is_void<CalculationType>::type::value,\n                typename select_most_precise\n                    <\n                        typename select_most_precise\n                            <\n                                typename coordinate_type<P1>::type,\n                                typename coordinate_type<P2>::type\n                            >::type,\n                        typename coordinate_type<P>::type\n                    >::type,\n                CalculationType\n            >::type coordinate_type;\n\n        boost::ignore_unused<coordinate_type>();\n\n        double d1 = 0.001; // m_strategy.apply(sp1, p);\n        double crs_AD = detail::course(p1, p);\n        double crs_AB = detail::course(p1, p2);\n        double XTD = asin(sin(d1) * sin(crs_AD - crs_AB));\n\n        return math::equals(XTD, 0) ? 0 : XTD < 0 ? 1 : -1;\n    }\n};\n\n}} // namespace strategy::side\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SIDE_BY_CROSS_TRACK_HPP\n", "meta": {"hexsha": "818bd4c346539c00e37b6b0c07d4ada93a698b15", "size": 3122, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/boost/geometry/strategies/spherical/side_by_cross_track.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": 133.0, "max_stars_repo_stars_event_min_datetime": "2018-04-20T14:09:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T11:51:25.000Z", "max_issues_repo_path": "boost/boost_1_56_0/boost/geometry/strategies/spherical/side_by_cross_track.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/boost/geometry/strategies/spherical/side_by_cross_track.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": 83.0, "max_forks_repo_forks_event_min_datetime": "2018-04-27T03:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:23:40.000Z", "avg_line_length": 30.0192307692, "max_line_length": 91, "alphanum_fraction": 0.6601537476, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.518432201406853}}
{"text": "#ifndef QST_OBSERVERWAVEFUNCTION_HPP\n#define QST_OBSERVERWAVEFUNCTION_HPP\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <iomanip>\n#include <fstream>\n\nnamespace qst{\n\ntemplate<class Wavefunction> class ObserverPSI{\n\n    Wavefunction &PSI_;\n\n    int N_;\n    int npar_;\n    Eigen::VectorXcd target_psi_;\n    std::vector<Eigen::VectorXcd> rotated_wf_;\n    Eigen::MatrixXd basis_states_;      // Hilbert space basis\n    std::map<std::string,Eigen::MatrixXcd> U_;\n    std::vector<std::vector<std::string> > basisSet_;\n    std::string basis_;\npublic:\n\n    double KL_;\n    double overlap_;\n    double Z_;\n    double NLL_;\n\n    ObserverPSI(Wavefunction &PSI,std::string &basis):PSI_(PSI){ \n        \n        std::cout<<\"- Initializing observer module\"<<std::endl;\n        N_ = PSI_.N();\n        npar_ = PSI_.Npar();\n        basis_ = basis;\n        basis_states_.resize(1<<N_,N_);\n        std::bitset<10> bit;\n        // Create the basis of the Hilbert space\n        for(int i=0;i<1<<N_;i++){\n            bit = i;\n            for(int j=0;j<N_;j++){\n                basis_states_(i,j) = bit[N_-j-1];\n            }\n        }\n    }\n \n    //Compute different estimators for the training performance\n    void Scan(int i){//,Eigen::MatrixXd &nll_test,std::ofstream &obs_out){\n        ExactPartitionFunction();\n        ExactKL(); \n        Overlap();\n        PrintStats(i);\n    }\n\n    //Compute the partition function by exact enumeration \n    void ExactPartitionFunction() {\n        Z_ = 0.0;\n        for(int i=0;i<basis_states_.rows();i++){\n            Z_ += norm(PSI_.psi(basis_states_.row(i)));\n        }\n    }\n\n    // Compute the overlap with the target wavefunction\n    void Overlap(){\n        overlap_ = 0.0;\n        std::complex<double> tmp;\n        for(int i=0;i<basis_states_.rows();i++){\n            tmp += conj(target_psi_(i))*PSI_.psi(basis_states_.row(i))/std::sqrt(Z_);\n        }\n        overlap_ = abs(tmp);\n    }\n    // Compute the fidelity with the target wavefunction \n    void Fidelity(){\n        Overlap();\n        return overlap_*overlap_;\n    }\n    \n    void NLL(Eigen::MatrixXd &data){\n        //TODO NOTE THIS IS ONLY FOR REFERENCE BASIS\n        NLL_ = 0.0;\n        for (int i=0;i<data.rows();i++){\n            NLL_ -= log(norm(PSI_.psi(data.row(i))));\n            NLL_ += log(Z_);\n        }\n        NLL_ /= float(data.rows());\n    }\n\n    //Compute KL divergence exactly\n    void ExactKL(){\n        Eigen::VectorXcd rotated_psi(1<<N_);\n        //KL in the standard basis\n        KL_ = 0.0;\n        for(int i=0;i<1<<N_;i++){\n            if (norm(target_psi_(i))>0.0){\n                KL_ += norm(target_psi_(i))*log(norm(target_psi_(i)));\n            }\n            KL_ -= norm(target_psi_(i))*log(norm(PSI_.psi(basis_states_.row(i))));\n            KL_ += norm(target_psi_(i))*log(Z_);\n        }\n        if (basis_.compare(\"std\")!=0){\n            //KL in the rotated bases\n            for (int b=1;b<basisSet_.size();b++){\n                rotateRbmWF(basisSet_[b],rotated_psi);\n                for(int i=0;i<1<<N_;i++){\n                    if (norm(rotated_wf_[b-1](i))>0.0){\n                        KL_ += norm(rotated_wf_[b-1](i))*log(norm(rotated_wf_[b-1](i)));\n                    }\n                    KL_ -= norm(rotated_wf_[b-1](i))*log(norm(rotated_psi(i)));\n                    KL_ += norm(rotated_wf_[b-1](i))*log(Z_);\n                }\n            }\n        }\n    }\n    \n    //Print observer\n    void PrintStats(int i){\n        std::cout << \"Epoch: \" << i << \"\\t\";     \n        std::cout << \"KL = \" << std::setprecision(10) << KL_ << \"\\t\";\n        std::cout << \"Overlap = \" << std::setprecision(10) << overlap_<< \"\\t\";//<< Fcheck_;\n        std::cout << std::endl;\n    } \n\n    //Set the value of the target wavefunction\n    void setWavefunction(Eigen::VectorXcd & psi){\n        target_psi_.resize(1<<N_);\n        for(int i=0;i<1<<N_;i++){\n            target_psi_(i) = psi(i);\n        }\n    }\n\n    void setRotatedWavefunctions(std::vector<Eigen::VectorXcd> & psi){\n        for(int b=0;b<psi.size();b++){\n            rotated_wf_.push_back(psi[b]);\n        }\n    }\n    //Set the value of the target wavefunction\n    void setBasisRotations(std::map<std::string,Eigen::MatrixXcd> & U){\n        U_ = U;\n    }\n    void setBasis(std::vector<std::vector<std::string> > basis) {\n        basisSet_ = basis;\n    }\n\n    void rotateRbmWF(const std::vector<std::string> & basis, Eigen::VectorXcd &psiR){//VectorRbmT & psiR){\n        int t,counter;\n        std::complex<double> U,Upsi;\n        std::bitset<16> bit;\n        std::bitset<16> st;\n        std::bitset<16> tmp;\n        std::vector<int> basisIndex;\n        Eigen::VectorXd state(N_);\n        Eigen::VectorXd v(N_);\n    \n        for(int x=0;x<1<<N_;x++){\n            U = 1.0;\n            Upsi=0.0;\n            basisIndex.clear();\n            t = 0;\n            st = x;\n            for (int j=0;j<N_;j++){\n                state(j) = st[N_-1-j];\n            }\n            for(int j=0;j<N_;j++){\n                if (basis[j]!=\"Z\"){\n                    t++;\n                    basisIndex.push_back(j);\n                }\n            }\n            for(int i=0;i<1<<t;i++){\n                counter  =0;\n                bit = i;\n                v=state;\n                for(int j=0;j<N_;j++){\n                    if (basis[j] != \"Z\"){\n                        v(j) = bit[counter];\n                        counter++;\n                    }\n                }\n                U=1.0;\n                for(int ii=0;ii<t;ii++){\n                    U = U * U_[basis[basisIndex[ii]]](int(state(basisIndex[ii])),int(v(basisIndex[ii])));\n                }\n                for(int j=0;j<N_;j++){\n                    tmp[j]=v(N_-1-j);\n                }\n                Upsi += U*PSI_.psi(v);\n            }\n            psiR(x) = Upsi;\n        }\n    }\n};\n}\n\n#endif\n", "meta": {"hexsha": "85e68ffa32a69c1a55f39d506a18dacb8b10eaff", "size": 5805, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "qucumber/cpp/observer_wavefunction.hpp", "max_stars_repo_name": "PatrickHuembeli/QuCumber", "max_stars_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-02T10:03:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-02T10:03:45.000Z", "max_issues_repo_path": "qucumber/cpp/observer_wavefunction.hpp", "max_issues_repo_name": "PatrickHuembeli/QuCumber", "max_issues_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "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": "qucumber/cpp/observer_wavefunction.hpp", "max_forks_repo_name": "PatrickHuembeli/QuCumber", "max_forks_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "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.7692307692, "max_line_length": 106, "alphanum_fraction": 0.4868217054, "num_tokens": 1564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5184321967089096}}
{"text": "#include <gnuplot-iostream/gnuplot-iostream.h>\n#include <boost/tuple/tuple.hpp>\n#include <iostream>\n#include <functional>\n#include <iomanip>\n#include <string>\n#include <cmath>\n#include \"Tools.hpp\"\nusing namespace std;\n\n\n/*****************************************************************************\n\nThis program uses the classes and a few functions from Tools.hpp to model a\nblock-spring system in simple harmonic motion (SHM). The program implements\ntwo methods: Euler's method and the Euler-Cromer method. The variables of the\ndifferential equation are stored in a classes named accordingly, along with\naccessor methods and a mutator to apply the defined euler step. Since \nEulerCromer1D is a subclass of Euler1D, they can be used polymorphically by\nallocating memory for them and referencing them by a pointer to Euler1D.\n\nIn the applyMethod function, the line with obj->update(dt) applies the update\nfunction of whichever class is supplied, not the one for Euler1D. It returns a \nstruct of type Path1D (from Tools.hpp) to avoid nasty data types like 2D \nvectors or having to return multiple values.\n\nThe plotpath function simply takes the Path1D, along with some information\nabout what's being plotted and how big it is, and sends it to gnuplot.\n\nFinally, the main method creates the objects, applies the method, and plots\nthem both. The getMaxValue function returns the amplitude of the Euler Method\npath (which should be larger) and plots them both methods at the same scale.\nThen, the created objects are deleted and the program ends.\n\n*****************************************************************************/\n\n\nconst double x_0 = inputDouble(0, \"Initial Position\");\t\t// Initial position\nconst double v_0 = inputDouble(10, \"Initial Velocity\");\t\t// Initial velocity\nconst double dt = inputDouble(0.005, \"Time Step\");\t\t\t// Time step\nconst double k = inputDouble(25, \"Spring Constant\");\t\t// Spring Constant\nconst double m = inputDouble(1, \"Mass\");\t\t\t\t\t// Mass\nconst double om = sqrt(k/m);\t\t\t\t\t\t\t\t// Omega\nconst double SIM_TIME = inputDouble(50, \"Simulation Time\");\t// Time to simulate\n\n\nfunction<double(double,double)> springStep = [](double x, double v){ return -om*om*x; };\t// The lambda function used as the differential equation\n\n\nPath1D applyMethod(Euler1D* obj){\t// Function to apply euler method to a pointer of Euler1D, allowing for polymorphism\n\tPath1D out;\t\t\t\t\t\t// Define an empty path to put the results in and output\n\n\tfor(double t = 0; t < SIM_TIME; t += dt){\t// Iterate from 0 to SIM_TIME with the defined time step\n\t\tout.x.push_back(obj->getX());\t// Add the current position to the path\n\t\tout.v.push_back(obj->getV());\t// Add the current velocity to the path (for phase space)\n\t\tout.t.push_back(t);\t\t\t\t// Add the current time to the path\n\t\tobj->update(dt);\t\t\t\t// Apply the update method of obj (either Euler's or Euler-Cromer)\n\t}\n\n\treturn out;\t// Return the path variable\n}\n\n\nvoid plotPath(Path1D p, double amp, string title, string fname){\t// Used to plot a path, specialized for this program...\n\t// Accepts input for the path, maximum amplitude (so graphs have the same scale and aren't terrible), the title of the method, and the file name to output\n\tGnuplot gp;\t// Instance of gnuplot terminal stream\n\n\tgp << setprecision(3);\n\tgp << \"set xrange [0:\" << SIM_TIME << \"]\\n\";\n\tgp << \"set yrange [\" << -amp*1.1 << \":\" << amp*1.1 << \"]\\n\";\n\tgp << \"set format y \\\"%.1f\\\"\\n\";\n\tgp << \"set term png size 720,480 font \\\"FreeSerif,12\\\"\\n\";\n\tgp << \"set xlabel \\\"t (s)\\\"\\n\";\n\tgp << \"set ylabel \\\"x (m)\\\"\\n\";\n\tgp << \"set title \\\"Position Vs. Time in Simple Harmonic Motion\\\\nUsing \" << title << \"\\\"\\n\"; \n\tgp << \"set output \\\"\" << fname << \"\\\"\\n\";\n\tgp << \"plot '-' with dots lc rgb \\\"black\\\" notitle\\n\";\n\tgp.send1d(boost::make_tuple(p.t,p.x));\t// Separate the path into components and plot it!\n}\n\n\nvoid plotPhaseSpace(Path1D p, string title, string fname){\t\n\tGnuplot gp;\t// Instance of gnuplot terminal stream\n\tvector<double> v = getMomentum(p.v, m);\n\n\tgp << setprecision(3);\n\tgp << \"set xrange [\" << -1.1*getMaxVal(p.x) << \":\" << 1.1*getMaxVal(p.x) << \"]\\n\";\n\tgp << \"set yrange [\" << -1.1*getMaxVal(v) << \":\" << 1.1*getMaxVal(v) << \"]\\n\";\n\tgp << \"set format y \\\"%.1f\\\"\\n\";\n\tgp << \"set term png size 720,480 font \\\"FreeSerif,12\\\"\\n\";\n\tgp << \"set xlabel \\\"x (m)\\\"\\n\";\n\tgp << \"set ylabel \\\"v (m/s)\\\"\\n\";\n\tgp << \"set title \\\"Phase Space Diagram of SHM using \" << title << \"\\\"\\n\"; \n\tgp << \"set output \\\"\" << fname << \"\\\"\\n\";\n\tgp << \"plot '-' with dots lc rgb \\\"black\\\" notitle\\n\";\n\tgp.send1d(boost::make_tuple(p.x,v));\t// Separate the path into components and plot it!\n}\n\n\nint main(){\n\tEuler1D* badSpring = new Euler1D(x_0, v_0, springStep);\t\t\t// Make a pointer to a Euler1D object\n\tEuler1D* goodSpring = new EulerCromer1D(x_0, v_0, springStep);\t// And one to a EulerCromer1D object\n\n\tPath1D badPath = applyMethod(badSpring);\t// Apply the method for both objects\n\tPath1D goodPath = applyMethod(goodSpring);\n\n\tdouble bigAmp = getMaxVal(badPath.x);\t// Amplitude of the oscillation (max value of pos)\n\tplotPath(badPath, bigAmp, \"Euler's Method\", \"BadMethod.png\");\t\t\t// Plot them accordingly!\n\tplotPath(goodPath, bigAmp, \"The Euler-Cromer Method\", \"GoodMethod.png\");\n\n\tplotPhaseSpace(badPath, \"Euler's Method\", \"BadPSD.png\");\n\tplotPhaseSpace(goodPath, \"the Euler-Cromer Method\", \"GoodPSD.png\");\n\n\tdelete badSpring;\t// Garbage collection to free up allocated memory\n\tdelete goodSpring;\n\treturn 0;\t\t\t// All done!\n}", "meta": {"hexsha": "dde3fa394278b537186864a637d8594ffdff8fe6", "size": 5417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SHM/SHMMethods.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": "SHM/SHMMethods.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": "SHM/SHMMethods.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": 46.2991452991, "max_line_length": 155, "alphanum_fraction": 0.6778659775, "num_tokens": 1507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5183665034477578}}
{"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 <cmath>\n#include <iostream>\n#include <vector>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace std;\n\ntemplate <typename Vector>\nvoid test(const char* name)\n{\n    cout << \"Testing multi_vector with \" << name << endl;\n    mtl::multi_vector<Vector> A(4, 6), B(4, 6);\n    A= 3.0;\n    cout << \"A is\\n\" << A << endl;\n\n    B= A;\n    cout << \"B= A yields\\n\" << B << endl;\n    cout << \"A is\\n\" << B << endl;\n\n    B= A + A;\n    cout << \"A + A is\\n\" << B << endl;\n    MTL_THROW_IF(B[1][1] != 6.0, mtl::runtime_error(\"Wrong value on diagonal\\n\"));\n    MTL_THROW_IF(B[1][0] != 0.0, mtl::runtime_error(\"Wrong value off diagonal\\n\"));\n\n    B= 2 * A;\n    cout << \"2 * A is\\n\" << B << endl;\n    MTL_THROW_IF(B[1][1] != 6.0, mtl::runtime_error(\"Wrong value on diagonal\\n\"));\n    MTL_THROW_IF(B[1][0] != 0.0, mtl::runtime_error(\"Wrong value off diagonal\\n\"));\n\n    B= 2 * A + A;\n    cout << \"2 * A is\\n\" << B << endl;\n    MTL_THROW_IF(B[1][1] != 9.0, mtl::runtime_error(\"Wrong value on diagonal\\n\"));\n    MTL_THROW_IF(B[1][0] != 0.0, mtl::runtime_error(\"Wrong value off diagonal\\n\"));\n\n    B= 2.0 * A + 3 * A;\n    cout << \"2 * A + 3 * A is\\n\" << B << endl;\n    MTL_THROW_IF(B[1][1] != 15.0, mtl::runtime_error(\"Wrong value on diagonal\\n\"));\n    MTL_THROW_IF(B[1][0] != 0.0, mtl::runtime_error(\"Wrong value off diagonal\\n\"));\n\n    B= 2.0 * A + 3 * A - 2.6 * A;\n    cout << \"2 * A + 3 * A - 2.6 * A is\\n\" << B << endl;\n    MTL_THROW_IF(std::abs(B[1][1] - 7.2) > 0.001, mtl::runtime_error(\"Wrong value on diagonal\\n\"));\n    MTL_THROW_IF(B[1][0] != 0.0, mtl::runtime_error(\"Wrong value off diagonal\\n\"));\n\n    mtl::multi_vector<Vector> C;\n    C.change_dim(3, 10);\n    C= 7;\n    cout << \"C is\\n\" << C;\n}\n\nint main(int, char**)\n{\n    test<mtl::dense_vector<double> >(\"dense_vector<double>\");\n\n    return 0;\n}\n", "meta": {"hexsha": "7647e94e08c1d92d1f34ce2fc929a74ebb8bb7a7", "size": 2244, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/multi_vector_expr_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/multi_vector_expr_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/multi_vector_expr_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": 32.5217391304, "max_line_length": 99, "alphanum_fraction": 0.5882352941, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5183664957856778}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2003 - 2021 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 * Authors: Guido Kanschat, University of Heidelberg, 2003 \n *          Baerbel Janssen, University of Heidelberg, 2010 \n *          Wolfgang Bangerth, Texas A&M University, 2010 \n */ \n\n\n// @sect3{Include files}  \n\n// \u540c\u6837\uff0c\u524d\u51e0\u4e2ainclude\u6587\u4ef6\u5df2\u7ecf\u77e5\u9053\u4e86\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u4f1a\u5bf9\u5b83\u4eec\u8fdb\u884c\u8bc4\u8bba\u3002\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\n#include <deal.II/lac/affine_constraints.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/solver_cg.h> \n#include <deal.II/lac/precondition.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\n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_values.h> \n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n\n// \u8fd9\u4e9b\uff0c\u73b0\u5728\uff0c\u662f\u591a\u7ea7\u65b9\u6cd5\u6240\u5fc5\u9700\u7684\u5305\u62ec\u3002\u7b2c\u4e00\u4e2a\u58f0\u660e\u4e86\u5982\u4f55\u5904\u7406\u591a\u7f51\u683c\u65b9\u6cd5\u6bcf\u4e2a\u5c42\u6b21\u4e0a\u7684Dirichlet\u8fb9\u754c\u6761\u4ef6\u3002\u5bf9\u4e8e\u81ea\u7531\u5ea6\u7684\u5b9e\u9645\u63cf\u8ff0\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u4efb\u4f55\u65b0\u7684\u5305\u542b\u6587\u4ef6\uff0c\u56e0\u4e3aDoFHandler\u5df2\u7ecf\u5b9e\u73b0\u4e86\u6240\u6709\u5fc5\u8981\u7684\u65b9\u6cd5\u3002\u6211\u4eec\u53ea\u9700\u8981\u5c06\u81ea\u7531\u5ea6\u5206\u914d\u7ed9\u66f4\u591a\u7684\u5c42\u6b21\u3002\n\n// \u5176\u4f59\u7684\u5305\u542b\u6587\u4ef6\u6d89\u53ca\u5230\u4f5c\u4e3a\u7ebf\u6027\u7b97\u5b50\uff08\u6c42\u89e3\u5668\u6216\u9884\u5904\u7406\u5668\uff09\u7684\u591a\u91cd\u7f51\u683c\u7684\u529b\u5b66\u95ee\u9898\u3002\n\n#include <deal.II/multigrid/mg_constrained_dofs.h> \n#include <deal.II/multigrid/multigrid.h> \n#include <deal.II/multigrid/mg_transfer.h> \n#include <deal.II/multigrid/mg_tools.h> \n#include <deal.II/multigrid/mg_coarse.h> \n#include <deal.II/multigrid/mg_smoother.h> \n#include <deal.II/multigrid/mg_matrix.h> \n\n// \u6700\u540e\u6211\u4eec\u5305\u62ecMeshWorker\u6846\u67b6\u3002\u8fd9\u4e2a\u6846\u67b6\u901a\u8fc7\u5176\u51fd\u6570loop()\u548cintegration_loop()\uff0c\u81ea\u52a8\u5728\u5355\u5143\u683c\u4e0a\u8fdb\u884c\u5faa\u73af\uff0c\u5e76\u5c06\u6570\u636e\u7ec4\u88c5\u6210\u5411\u91cf\u3001\u77e9\u9635\u7b49\u3002\u5b83\u81ea\u52a8\u670d\u4ece\u7ea6\u675f\u3002\u7531\u4e8e\u6211\u4eec\u5fc5\u987b\u5efa\u7acb\u51e0\u4e2a\u77e9\u9635\uff0c\u5e76\u4e14\u5fc5\u987b\u6ce8\u610f\u51e0\u7ec4\u7ea6\u675f\uff0c\u8fd9\u5c06\u4f7f\u6211\u4eec\u7701\u53bb\u5f88\u591a\u9ebb\u70e6\u3002\n\n#include <deal.II/meshworker/dof_info.h> \n#include <deal.II/meshworker/integration_info.h> \n#include <deal.II/meshworker/simple.h> \n#include <deal.II/meshworker/output.h> \n#include <deal.II/meshworker/loop.h> \n\n// \u4e3a\u4e86\u8282\u7701\u7cbe\u529b\uff0c\u6211\u4eec\u4f7f\u7528\u4e86\u5728\u4ee5\u4e0b\u6587\u4ef6\u4e2d\u627e\u5230\u7684\u9884\u5148\u5b9e\u73b0\u7684\u62c9\u666e\u62c9\u65af\u3002\n\n#include <deal.II/integrators/laplace.h> \n#include <deal.II/integrators/l2.h> \n\n// \u8fd9\u5c31\u662fC++\u3002\n\n#include <iostream> \n#include <fstream> \n\nusing namespace dealii; \n\nnamespace Step16 \n{ \n// @sect3{The integrator on each cell}  \n\n//  MeshWorker::integration_loop() \u5e0c\u671b\u6709\u4e00\u4e2a\u7c7b\u80fd\u591f\u63d0\u4f9b\u5728\u5355\u5143\u683c\u548c\u8fb9\u754c\u53ca\u5185\u90e8\u9762\u7684\u79ef\u5206\u529f\u80fd\u3002\u8fd9\u662f\u7531\u4e0b\u9762\u7684\u7c7b\u6765\u5b8c\u6210\u7684\u3002\u5728\u6784\u9020\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u544a\u8bc9\u5faa\u73af\u5e94\u8be5\u8ba1\u7b97\u5355\u5143\u683c\u79ef\u5206\uff08\"\u771f\"\uff09\uff0c\u4f46\u4e0d\u5e94\u8be5\u8ba1\u7b97\u8fb9\u754c\u548c\u5185\u90e8\u9762\u7684\u79ef\u5206\uff08\u4e24\u4e2a \"\u5047\"\uff09\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u53ea\u9700\u8981\u4e00\u4e2a\u5355\u5143\u683c\u51fd\u6570\uff0c\u800c\u4e0d\u9700\u8981\u9762\u7684\u51fd\u6570\u3002\n\n  template <int dim> \n  class LaplaceIntegrator : public MeshWorker::LocalIntegrator<dim> \n  { \n  public: \n    LaplaceIntegrator(); \n    virtual void cell(MeshWorker::DoFInfo<dim> &        dinfo, \n                      MeshWorker::IntegrationInfo<dim> &info) const override; \n  }; \n\n  template <int dim> \n  LaplaceIntegrator<dim>::LaplaceIntegrator() \n    : MeshWorker::LocalIntegrator<dim>(true, false, false) \n  {} \n\n// \u63a5\u4e0b\u6765\u662f\u6bcf\u4e2a\u5355\u5143\u4e0a\u7684\u5b9e\u9645\u79ef\u5206\u5668\u3002\u6211\u4eec\u89e3\u51b3\u4e00\u4e2a\u6cca\u677e\u95ee\u9898\uff0c\u5728\u53f3\u534a\u5e73\u9762\u4e0a\u7684\u7cfb\u6570\u4e3a1\uff0c\u5728\u5de6\u534a\u5e73\u9762\u4e0a\u7684\u7cfb\u6570\u4e3a\u5341\u5206\u4e4b\u4e00\u3002\n\n//  MeshWorker::LocalResults \u7684\u57fa\u7c7b MeshWorker::DoFInfo \u5305\u542b\u53ef\u4ee5\u5728\u8fd9\u4e2a\u5c40\u90e8\u79ef\u5206\u5668\u4e2d\u586b\u5145\u7684\u5bf9\u8c61\u3002\u5728MeshWorker\u6846\u67b6\u5185\uff0c\u6709\u591a\u5c11\u5bf9\u8c61\u88ab\u521b\u5efa\u662f\u7531\u88c5\u914d\u5668\u7c7b\u51b3\u5b9a\u7684\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u4e3e\u4f8b\u6d4b\u8bd5\u4e00\u4e0b\uff0c\u9700\u8981\u4e00\u4e2a\u77e9\u9635 (MeshWorker::LocalResults::n_matrices()).  \u77e9\u9635\u662f\u901a\u8fc7 MeshWorker::LocalResults::matrix(), \u6765\u8bbf\u95ee\u7684\uff0c\u5b83\u7684\u7b2c\u4e00\u4e2a\u53c2\u6570\u662f\u77e9\u9635\u7684\u7f16\u53f7\u3002\u7b2c\u4e8c\u4e2a\u53c2\u6570\u53ea\u7528\u4e8e\u9762\u7684\u79ef\u5206\uff0c\u5f53\u6bcf\u4e2a\u6d4b\u8bd5\u51fd\u6570\u4f7f\u7528\u4e24\u4e2a\u77e9\u9635\u65f6\u3002\u90a3\u4e48\uff0c\u7b2c\u4e8c\u4e2a\u6307\u6807\u4e3a \"true \"\u7684\u77e9\u9635\u5c06\u4ee5\u76f8\u540c\u7684\u7d22\u5f15\u5b58\u5728\u3002\n\n//  MeshWorker::IntegrationInfo \u63d0\u4f9b\u4e86\u4e00\u4e2a\u6216\u51e0\u4e2aFEValues\u5bf9\u8c61\uff0c\u4e0b\u9762\u8fd9\u4e9b\u5bf9\u8c61\u88ab LocalIntegrators::Laplace::cell_matrix() \u6216 LocalIntegrators::L2::L2(). \u4f7f\u7528\uff0c\u56e0\u4e3a\u6211\u4eec\u53ea\u7ec4\u88c5\u4e00\u4e2aPDE\uff0c\u6240\u4ee5\u4e5f\u53ea\u6709\u4e00\u4e2a\u7d22\u5f15\u4e3a0\u7684\u5bf9\u8c61\u3002\n\n// \u6b64\u5916\uff0c\u6211\u4eec\u6ce8\u610f\u5230\u8fd9\u4e2a\u79ef\u5206\u5668\u7684\u4f5c\u7528\u662f\u8ba1\u7b97\u591a\u7ea7\u9884\u5904\u7406\u7684\u77e9\u9635\uff0c\u4ee5\u53ca\u5168\u5c40\u7cfb\u7edf\u7684\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u3002\u7531\u4e8e\u7cfb\u7edf\u7684\u6c47\u7f16\u5668\u9700\u8981\u4e00\u4e2a\u989d\u5916\u7684\u5411\u91cf\uff0c MeshWorker::LocalResults::n_vectors() \u8981\u8fd4\u56de\u4e00\u4e2a\u975e\u96f6\u503c\u3002\u76f8\u5e94\u5730\uff0c\u6211\u4eec\u5728\u8fd9\u4e2a\u51fd\u6570\u7684\u672b\u5c3e\u586b\u5145\u4e86\u4e00\u4e2a\u53f3\u8fb9\u7684\u5411\u91cf\u3002\u7531\u4e8eLocalResults\u53ef\u4ee5\u5904\u7406\u591a\u4e2aBlockVector\u5bf9\u8c61\uff0c\u4f46\u6211\u4eec\u8fd9\u91cc\u53c8\u662f\u6700\u7b80\u5355\u7684\u60c5\u51b5\uff0c\u6240\u4ee5\u6211\u4eec\u5c06\u4fe1\u606f\u8f93\u5165\u5230\u96f6\u53f7\u5411\u91cf\u7684\u96f6\u53f7\u5757\u4e2d\u3002\n\n  template <int dim> \n  void \n  LaplaceIntegrator<dim>::cell(MeshWorker::DoFInfo<dim> &        dinfo, \n                               MeshWorker::IntegrationInfo<dim> &info) const \n  { \n    AssertDimension(dinfo.n_matrices(), 1); \n    const double coefficient = (dinfo.cell->center()(0) > 0.) ? .1 : 1.; \n\n    LocalIntegrators::Laplace::cell_matrix(dinfo.matrix(0, false).matrix, \n                                           info.fe_values(0), \n                                           coefficient); \n\n    if (dinfo.n_vectors() > 0) \n      { \n        std::vector<double> rhs(info.fe_values(0).n_quadrature_points, 1.); \n        LocalIntegrators::L2::L2(dinfo.vector(0).block(0), \n                                 info.fe_values(0), \n                                 rhs); \n      } \n  } \n// @sect3{The <code>LaplaceProblem</code> class template}  \n\n// \u8fd9\u4e2a\u4e3b\u7c7b\u4e0e  step-6  \u4e2d\u7684\u7c7b\u57fa\u672c\u76f8\u540c\u3002\u5c31\u6210\u5458\u51fd\u6570\u800c\u8a00\uff0c\u552f\u4e00\u589e\u52a0\u7684\u662f <code>assemble_multigrid</code> \u51fd\u6570\uff0c\u5b83\u7ec4\u88c5\u4e86\u5bf9\u5e94\u4e8e\u4e2d\u95f4\u5c42\u79bb\u6563\u8fd0\u7b97\u7b26\u7684\u77e9\u9635\u3002\n\n  template <int dim> \n  class LaplaceProblem \n  { \n  public: \n    LaplaceProblem(const unsigned int degree); \n    void run(); \n\n  private: \n    void setup_system(); \n    void assemble_system(); \n    void assemble_multigrid(); \n    void solve(); \n    void refine_grid(); \n    void output_results(const unsigned int cycle) const; \n\n    Triangulation<dim> triangulation; \n    FE_Q<dim>          fe; \n    DoFHandler<dim>    dof_handler; \n\n    SparsityPattern      sparsity_pattern; \n    SparseMatrix<double> system_matrix; \n\n    AffineConstraints<double> constraints; \n\n    Vector<double> solution; \n    Vector<double> system_rhs; \n\n    const unsigned int degree; \n\n// \u4ee5\u4e0b\u6210\u5458\u662f\u591a\u7f51\u683c\u65b9\u6cd5\u7684\u57fa\u672c\u6570\u636e\u7ed3\u6784\u3002\u524d\u4e24\u4e2a\u8868\u793a\u7a00\u758f\u6a21\u5f0f\u548c\u591a\u7ea7\u5c42\u6b21\u7ed3\u6784\u4e2d\u5404\u4e2a\u5c42\u6b21\u7684\u77e9\u9635\uff0c\u975e\u5e38\u7c7b\u4f3c\u4e8e\u4e0a\u9762\u7684\u5168\u5c40\u7f51\u683c\u7684\u5bf9\u8c61\u3002\n\n// \u7136\u540e\uff0c\u6211\u4eec\u6709\u4e24\u4e2a\u65b0\u7684\u77e9\u9635\uff0c\u53ea\u9700\u8981\u5728\u81ea\u9002\u5e94\u7f51\u683c\u4e0a\u8fdb\u884c\u5c40\u90e8\u5e73\u6ed1\u7684\u591a\u7f51\u683c\u65b9\u6cd5\u3002\u5b83\u4eec\u5728\u7ec6\u5316\u533a\u57df\u7684\u5185\u90e8\u548c\u7ec6\u5316\u8fb9\u7f18\u4e4b\u95f4\u4f20\u9012\u6570\u636e\uff0c\u5728 @ref mg_paper \"\u591a\u7f51\u683c\u8bba\u6587 \"\u4e2d\u8be6\u7ec6\u4ecb\u7ecd\u8fc7\u3002\n\n// \u6700\u540e\u4e00\u4e2a\u5bf9\u8c61\u5b58\u50a8\u4e86\u6bcf\u4e2a\u5c42\u6b21\u4e0a\u7684\u8fb9\u754c\u6307\u6570\u4fe1\u606f\u548c\u4f4d\u4e8e\u4e24\u4e2a\u4e0d\u540c\u7ec6\u5316\u5c42\u6b21\u4e4b\u95f4\u7684\u7ec6\u5316\u8fb9\u7f18\u4e0a\u7684\u6307\u6570\u4fe1\u606f\u3002\u56e0\u6b64\uff0c\u5b83\u7684\u4f5c\u7528\u4e0eAffineConstraints\u7c7b\u4f3c\uff0c\u4f46\u5728\u6bcf\u4e2a\u5c42\u6b21\u4e0a\u3002\n\n    MGLevelObject<SparsityPattern>      mg_sparsity_patterns; \n    MGLevelObject<SparseMatrix<double>> mg_matrices; \n    MGLevelObject<SparseMatrix<double>> mg_interface_in; \n    MGLevelObject<SparseMatrix<double>> mg_interface_out; \n    MGConstrainedDoFs                   mg_constrained_dofs; \n  }; \n// @sect3{The <code>LaplaceProblem</code> class implementation}  \n\n// \u5173\u4e8e\u4e09\u89d2\u5f62\u7684\u6784\u9020\u51fd\u6570\u53ea\u6709\u4e00\u4e2a\u7b80\u77ed\u7684\u8bc4\u8bba\uff1a\u6309\u7167\u60ef\u4f8b\uff0cdeal.II\u4e2d\u6240\u6709\u81ea\u9002\u5e94\u7cbe\u5316\u7684\u4e09\u89d2\u5f62\u5728\u5355\u5143\u683c\u4e4b\u95f4\u7684\u9762\u7684\u53d8\u5316\u4e0d\u4f1a\u8d85\u8fc7\u4e00\u4e2a\u7ea7\u522b\u3002\u7136\u800c\uff0c\u5bf9\u4e8e\u6211\u4eec\u7684\u591a\u7f51\u683c\u7b97\u6cd5\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u66f4\u4e25\u683c\u7684\u4fdd\u8bc1\uff0c\u5373\u7f51\u683c\u5728\u8fde\u63a5\u4e24\u4e2a\u5355\u5143\u7684\u9876\u70b9\u4e0a\u7684\u53d8\u5316\u4e5f\u4e0d\u8d85\u8fc7\u7ec6\u5316\u7ea7\u522b\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u6211\u4eec\u5fc5\u987b\u9632\u6b62\u51fa\u73b0\u4ee5\u4e0b\u60c5\u51b5\u3002\n\n//  @image html limit_level_difference_at_vertices.png \"\"  \n\n// \u8fd9\u53ef\u4ee5\u901a\u8fc7\u5411\u4e09\u89d2\u5316\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4f20\u9012 Triangulation::limit_level_difference_at_vertices \u6807\u5fd7\u6765\u5b9e\u73b0\u3002\n\n  template <int dim> \n  LaplaceProblem<dim>::LaplaceProblem(const unsigned int degree) \n    : triangulation(Triangulation<dim>::limit_level_difference_at_vertices) \n    , fe(degree) \n    , dof_handler(triangulation) \n    , degree(degree) \n  {} \n\n//  @sect4{LaplaceProblem::setup_system}  \n\n// \u9664\u4e86\u53ea\u662f\u5728DoFHandler\u4e2d\u5206\u914d\u81ea\u7531\u5ea6\u4e4b\u5916\uff0c\u6211\u4eec\u5728\u6bcf\u4e00\u5c42\u90fd\u505a\u540c\u6837\u7684\u4e8b\u60c5\u3002\u7136\u540e\uff0c\u6211\u4eec\u6309\u7167\u4e4b\u524d\u7684\u7a0b\u5e8f\uff0c\u5728\u53f6\u5b50\u7f51\u683c\u4e0a\u8bbe\u7f6e\u7cfb\u7edf\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::setup_system() \n  { \n    dof_handler.distribute_dofs(fe); \n    dof_handler.distribute_mg_dofs(); \n\n    deallog << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n            << \" (by level: \"; \n    for (unsigned int level = 0; level < triangulation.n_levels(); ++level) \n      deallog << dof_handler.n_dofs(level) \n              << (level == triangulation.n_levels() - 1 ? \")\" : \", \"); \n    deallog << std::endl; \n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp); \n\n    solution.reinit(dof_handler.n_dofs()); \n    system_rhs.reinit(dof_handler.n_dofs()); \n\n    constraints.clear(); \n    DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n\n    std::set<types::boundary_id> dirichlet_boundary_ids = {0}; \n    Functions::ZeroFunction<dim> homogeneous_dirichlet_bc; \n    const std::map<types::boundary_id, const Function<dim> *> \n      dirichlet_boundary_functions = { \n        {types::boundary_id(0), &homogeneous_dirichlet_bc}}; \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             dirichlet_boundary_functions, \n                                             constraints); \n    constraints.close(); \n    constraints.condense(dsp); \n    sparsity_pattern.copy_from(dsp); \n    system_matrix.reinit(sparsity_pattern); \n\n// \u591a\u7f51\u683c\u7ea6\u675f\u5fc5\u987b\u88ab\u521d\u59cb\u5316\u3002\u4ed6\u4eec\u4e5f\u9700\u8981\u77e5\u9053\u8fb9\u754c\u503c\uff0c\u6240\u4ee5\u6211\u4eec\u4e5f\u5728\u8fd9\u91cc\u4f20\u9012 <code>dirichlet_boundary</code> \u3002\n\n    mg_constrained_dofs.clear(); \n    mg_constrained_dofs.initialize(dof_handler); \n    mg_constrained_dofs.make_zero_boundary_constraints(dof_handler, \n                                                       dirichlet_boundary_ids); \n\n// \u73b0\u5728\u662f\u5173\u4e8e\u591a\u7f51\u683c\u6570\u636e\u7ed3\u6784\u7684\u4e8b\u60c5\u3002\u9996\u5148\uff0c\u6211\u4eec\u8c03\u6574\u591a\u7ea7\u5bf9\u8c61\u7684\u5927\u5c0f\uff0c\u4ee5\u5bb9\u7eb3\u6bcf\u4e00\u7ea7\u7684\u77e9\u9635\u548c\u7a00\u758f\u6a21\u5f0f\u3002\u7c97\u7565\u7684\u7ea7\u522b\u662f\u96f6\uff08\u73b0\u5728\u662f\u5f3a\u5236\u6027\u7684\uff0c\u4f46\u5728\u672a\u6765\u7684\u4fee\u8ba2\u4e2d\u53ef\u80fd\u4f1a\u6539\u53d8\uff09\u3002\u6ce8\u610f\uff0c\u8fd9\u4e9b\u51fd\u6570\u5728\u8fd9\u91cc\u91c7\u53d6\u7684\u662f\u4e00\u4e2a\u5b8c\u6574\u7684\u3001\u5305\u5bb9\u7684\u8303\u56f4\uff08\u800c\u4e0d\u662f\u4e00\u4e2a\u8d77\u59cb\u7d22\u5f15\u548c\u5927\u5c0f\uff09\uff0c\u6240\u4ee5\u6700\u7ec6\u7684\u7ea7\u522b\u662f <code>n_levels-1</code>  \u3002\u6211\u4eec\u9996\u5148\u8981\u8c03\u6574\u5bb9\u7eb3SparseMatrix\u7c7b\u7684\u5bb9\u5668\u7684\u5927\u5c0f\uff0c\u56e0\u4e3a\u5b83\u4eec\u5fc5\u987b\u5728\u8c03\u6574\u5927\u5c0f\u65f6\u91ca\u653e\u5b83\u4eec\u7684SparsityPattern\u624d\u80fd\u88ab\u9500\u6bc1\u3002\n\n    const unsigned int n_levels = triangulation.n_levels(); \n\n    mg_interface_in.resize(0, n_levels - 1); \n    mg_interface_in.clear_elements(); \n    mg_interface_out.resize(0, n_levels - 1); \n    mg_interface_out.clear_elements(); \n    mg_matrices.resize(0, n_levels - 1); \n    mg_matrices.clear_elements(); \n    mg_sparsity_patterns.resize(0, n_levels - 1); \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u6bcf\u4e2a\u5c42\u9762\u4e0a\u63d0\u4f9b\u4e00\u4e2a\u77e9\u9635\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u4f7f\u7528 MGTools::make_sparsity_pattern \u51fd\u6570\u5728\u6bcf\u4e2a\u5c42\u6b21\u4e0a\u751f\u6210\u4e00\u4e2a\u521d\u6b65\u7684\u538b\u7f29\u7a00\u758f\u6a21\u5f0f\uff08\u5173\u4e8e\u8fd9\u4e2a\u4e3b\u9898\u7684\u66f4\u591a\u4fe1\u606f\uff0c\u8bf7\u53c2\u89c1 @ref Sparsity \u6a21\u5757\uff09\uff0c\u7136\u540e\u628a\u5b83\u590d\u5236\u5230\u6211\u4eec\u771f\u6b63\u60f3\u8981\u7684\u90a3\u4e2a\u5c42\u6b21\u4e0a\u3002\u4e0b\u4e00\u6b65\u662f\u7528\u8fd9\u4e9b\u7a00\u758f\u6a21\u5f0f\u521d\u59cb\u5316\u4e24\u79cd\u5c42\u6b21\u77e9\u9635\u3002\n\n// \u503c\u5f97\u6307\u51fa\u7684\u662f\uff0c\u754c\u9762\u77e9\u9635\u53ea\u6709\u4f4d\u4e8e\u8f83\u7c97\u7684\u7f51\u683c\u548c\u8f83\u7ec6\u7684\u7f51\u683c\u4e4b\u95f4\u7684\u754c\u9762\u4e0a\u7684\u81ea\u7531\u5ea6\u6761\u76ee\u3002\u56e0\u6b64\uff0c\u5b83\u4eec\u751a\u81f3\u6bd4\u6211\u4eec\u591a\u7f51\u683c\u5c42\u6b21\u7ed3\u6784\u4e2d\u7684\u5404\u4e2a\u5c42\u6b21\u7684\u77e9\u9635\u8fd8\u8981\u7a00\u5c11\u3002\u5982\u679c\u6211\u4eec\u66f4\u5173\u5fc3\u5185\u5b58\u7684\u4f7f\u7528\uff08\u53ef\u80fd\u8fd8\u6709\u6211\u4eec\u4f7f\u7528\u8fd9\u4e9b\u77e9\u9635\u7684\u901f\u5ea6\uff09\uff0c\u6211\u4eec\u5e94\u8be5\u5bf9\u8fd9\u4e24\u79cd\u77e9\u9635\u4f7f\u7528\u4e0d\u540c\u7684\u7a00\u758f\u6027\u6a21\u5f0f\u3002\n\n    for (unsigned int level = 0; level < n_levels; ++level) \n      { \n        DynamicSparsityPattern dsp(dof_handler.n_dofs(level), \n                                   dof_handler.n_dofs(level)); \n        MGTools::make_sparsity_pattern(dof_handler, dsp, level); \n\n        mg_sparsity_patterns[level].copy_from(dsp); \n\n        mg_matrices[level].reinit(mg_sparsity_patterns[level]); \n        mg_interface_in[level].reinit(mg_sparsity_patterns[level]); \n        mg_interface_out[level].reinit(mg_sparsity_patterns[level]); \n      } \n  } \n// @sect4{LaplaceProblem::assemble_system}  \n\n// \u4e0b\u9762\u7684\u51fd\u6570\u5c06\u7ebf\u6027\u7cfb\u7edf\u88c5\u914d\u5728\u7f51\u683c\u7684\u6700\u7ec6\u5c42\u4e0a\u3002\u7531\u4e8e\u6211\u4eec\u60f3\u5728\u4e0b\u9762\u7684\u5c42\u6b21\u88c5\u914d\u4e2d\u91cd\u7528\u8fd9\u91cc\u7684\u4ee3\u7801\uff0c\u6211\u4eec\u4f7f\u7528\u672c\u5730\u79ef\u5206\u5668\u7c7bLaplaceIntegrator\uff0c\u800c\u5c06\u5faa\u73af\u7559\u7ed9MeshWorker\u6846\u67b6\u3002\u56e0\u6b64\uff0c\u8fd9\u4e2a\u51fd\u6570\u9996\u5148\u8bbe\u7f6e\u4e86\u8fd9\u4e2a\u6846\u67b6\u6240\u9700\u7684\u5bf9\u8c61\uff0c\u5373  \n\n// - \u4e00\u4e2a MeshWorker::IntegrationInfoBox \u5bf9\u8c61\uff0c\u5b83\u5c06\u63d0\u4f9b\u5355\u5143\u683c\u4e0a\u6b63\u4ea4\u70b9\u7684\u6240\u6709\u9700\u8981\u7684\u6570\u636e\u3002\u8fd9\u4e2a\u5bf9\u8c61\u53ef\u4ee5\u770b\u4f5c\u662fFEValues\u7684\u6269\u5c55\uff0c\u63d0\u4f9b\u66f4\u591a\u7684\u6709\u7528\u4fe1\u606f\u3002 \n\n// - \u4e00\u4e2a MeshWorker::DoFInfo \u5bf9\u8c61\uff0c\u5b83\u4e00\u65b9\u9762\u6269\u5c55\u4e86\u5355\u5143\u683c\u8fed\u4ee3\u5668\u7684\u529f\u80fd\uff0c\u53e6\u4e00\u65b9\u9762\u4e5f\u4e3a\u5176\u57fa\u7c7bLocalResults\u7684\u8fd4\u56de\u503c\u63d0\u4f9b\u4e86\u7a7a\u95f4\u3002 \n\n// - \u4e00\u4e2a\u6c47\u7f16\u5668\uff0c\u5728\u8fd9\u91cc\u662f\u6307\u6574\u4e2a\u7cfb\u7edf\u3002\u8fd9\u91cc\u7684 \"\u7b80\u5355 \"\u6307\u7684\u662f\u5168\u5c40\u7cfb\u7edf\u6ca1\u6709\u4e00\u4e2a\u5757\u72b6\u7ed3\u6784\u3002 \n\n// - \u672c\u5730\u96c6\u6210\u5668\uff0c\u5b83\u5b9e\u73b0\u4e86\u5b9e\u9645\u7684\u5f62\u5f0f\u3002\n\n// \u5728\u5faa\u73af\u5c06\u6240\u6709\u8fd9\u4e9b\u7ec4\u5408\u6210\u4e00\u4e2a\u77e9\u9635\u548c\u4e00\u4e2a\u53f3\u624b\u8fb9\u4e4b\u540e\uff0c\u8fd8\u6709\u4e00\u4ef6\u4e8b\u8981\u505a\uff1a\u96c6\u5408\u5668\u5bf9\u53d7\u9650\u81ea\u7531\u5ea6\u7684\u77e9\u9635\u884c\u548c\u5217\u4e0d\u505a\u4efb\u4f55\u5904\u7406\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5728\u5bf9\u89d2\u7ebf\u4e0a\u653e\u4e00\u4e2a\u4e00\uff0c\u4f7f\u6574\u4e2a\u7cfb\u7edf\u6446\u597d\u3002\u4e00\u7684\u503c\u6216\u4efb\u4f55\u56fa\u5b9a\u7684\u503c\u90fd\u6709\u4e00\u4e2a\u597d\u5904\uff0c\u5373\u5b83\u5bf9\u77e9\u9635\u7684\u9891\u8c31\u7684\u5f71\u54cd\u5f88\u5bb9\u6613\u7406\u89e3\u3002\u7531\u4e8e\u76f8\u5e94\u7684\u7279\u5f81\u5411\u91cf\u5f62\u6210\u4e86\u4e00\u4e2a\u4e0d\u53d8\u7684\u5b50\u7a7a\u95f4\uff0c\u6240\u9009\u62e9\u7684\u503c\u4e0d\u4f1a\u5f71\u54cdKrylov\u7a7a\u95f4\u6c42\u89e3\u5668\u7684\u6536\u655b\u6027\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::assemble_system() \n  { \n    MappingQ1<dim>                      mapping; \n    MeshWorker::IntegrationInfoBox<dim> info_box; \n    UpdateFlags                         update_flags = \n      update_values | update_gradients | update_hessians; \n    info_box.add_update_flags_all(update_flags); \n    info_box.initialize(fe, mapping); \n\n    MeshWorker::DoFInfo<dim> dof_info(dof_handler); \n\n    MeshWorker::Assembler::SystemSimple<SparseMatrix<double>, Vector<double>> \n      assembler; \n    assembler.initialize(constraints); \n    assembler.initialize(system_matrix, system_rhs); \n\n    LaplaceIntegrator<dim> matrix_integrator; \n    MeshWorker::integration_loop<dim, dim>(dof_handler.begin_active(), \n                                           dof_handler.end(), \n                                           dof_info, \n                                           info_box, \n                                           matrix_integrator, \n                                           assembler); \n\n    for (unsigned int i = 0; i < dof_handler.n_dofs(); ++i) \n      if (constraints.is_constrained(i)) \n        system_matrix.set(i, i, 1.); \n  } \n// @sect4{LaplaceProblem::assemble_multigrid}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u5efa\u7acb\u7ebf\u6027\u7b97\u5b50\uff08\u77e9\u9635\uff09\uff0c\u5b9a\u4e49\u6bcf\u4e00\u7ea7\u7f51\u683c\u4e0a\u7684\u591a\u6805\u65b9\u6cd5\u3002\u79ef\u5206\u7684\u6838\u5fc3\u548c\u4e0a\u9762\u7684\u4e00\u6837\uff0c\u4f46\u662f\u4e0b\u9762\u7684\u5faa\u73af\u4f1a\u904d\u5386\u6240\u6709\u5df2\u6709\u7684\u5355\u5143\uff0c\u800c\u4e0d\u4ec5\u4ec5\u662f\u6d3b\u52a8\u7684\u5355\u5143\uff0c\u800c\u4e14\u7ed3\u679c\u5fc5\u987b\u8f93\u5165\u6b63\u786e\u7684\u5c42\u6b21\u77e9\u9635\u3002\u5e78\u8fd0\u7684\u662f\uff0cMeshWorker\u5bf9\u6211\u4eec\u9690\u85cf\u4e86\u5927\u90e8\u5206\u7684\u5185\u5bb9\uff0c\u56e0\u6b64\u8fd9\u4e2a\u51fd\u6570\u548c\u4e4b\u524d\u7684\u51fd\u6570\u7684\u533a\u522b\u53ea\u5728\u4e8e\u6c47\u7f16\u5668\u7684\u8bbe\u7f6e\u548c\u5faa\u73af\u4e2d\u4e0d\u540c\u7684\u8fed\u4ee3\u5668\u3002\u53e6\u5916\uff0c\u6700\u540e\u4fee\u590d\u77e9\u9635\u7684\u8fc7\u7a0b\u4e5f\u6bd4\u8f83\u590d\u6742\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::assemble_multigrid() \n  { \n    MappingQ1<dim>                      mapping; \n    MeshWorker::IntegrationInfoBox<dim> info_box; \n    UpdateFlags                         update_flags = \n      update_values | update_gradients | update_hessians; \n    info_box.add_update_flags_all(update_flags); \n    info_box.initialize(fe, mapping); \n\n    MeshWorker::DoFInfo<dim> dof_info(dof_handler); \n\n    MeshWorker::Assembler::MGMatrixSimple<SparseMatrix<double>> assembler; \n    assembler.initialize(mg_constrained_dofs); \n    assembler.initialize(mg_matrices); \n    assembler.initialize_interfaces(mg_interface_in, mg_interface_out); \n\n    LaplaceIntegrator<dim> matrix_integrator; \n    MeshWorker::integration_loop<dim, dim>(dof_handler.begin_mg(), \n                                           dof_handler.end_mg(), \n                                           dof_info, \n                                           info_box, \n                                           matrix_integrator, \n                                           assembler); \n\n    const unsigned int nlevels = triangulation.n_levels(); \n    for (unsigned int level = 0; level < nlevels; ++level) \n      { \n        for (unsigned int i = 0; i < dof_handler.n_dofs(level); ++i) \n          if (mg_constrained_dofs.is_boundary_index(level, i) || \n              mg_constrained_dofs.at_refinement_edge(level, i)) \n            mg_matrices[level].set(i, i, 1.); \n      } \n  } \n\n//  @sect4{LaplaceProblem::solve}  \n\n// \u8fd9\u662f\u53e6\u5916\u4e00\u4e2a\u5728\u652f\u6301\u591a\u6805\u6c42\u89e3\u5668\uff08\u6216\u8005\u8bf4\uff0c\u4e8b\u5b9e\u4e0a\uff0c\u6211\u4eec\u4f7f\u7528\u591a\u6805\u65b9\u6cd5\u7684\u524d\u63d0\u6761\u4ef6\uff09\u65b9\u9762\u6709\u660e\u663e\u4e0d\u540c\u7684\u51fd\u6570\u3002\n\n// \u8ba9\u6211\u4eec\u4ece\u5efa\u7acb\u591a\u5c42\u6b21\u65b9\u6cd5\u7684\u4e24\u4e2a\u7ec4\u6210\u90e8\u5206\u5f00\u59cb\uff1a\u5c42\u6b21\u95f4\u7684\u8f6c\u79fb\u8fd0\u7b97\u5668\u548c\u6700\u7c97\u5c42\u6b21\u4e0a\u7684\u6c42\u89e3\u5668\u3002\u5728\u6709\u9650\u5143\u65b9\u6cd5\u4e2d\uff0c\u8f6c\u79fb\u7b97\u5b50\u6765\u81ea\u6240\u6d89\u53ca\u7684\u6709\u9650\u5143\u51fd\u6570\u7a7a\u95f4\uff0c\u901a\u5e38\u53ef\u4ee5\u7528\u72ec\u7acb\u4e8e\u6240\u8003\u8651\u95ee\u9898\u7684\u901a\u7528\u65b9\u5f0f\u8ba1\u7b97\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528MGTransferPrebuilt\u7c7b\uff0c\u7ed9\u5b9a\u6700\u7ec8\u7ebf\u6027\u7cfb\u7edf\u7684\u7ea6\u675f\u548cMGConstrainedDoFs\u5bf9\u8c61\uff0c\u8be5\u5bf9\u8c61\u77e5\u9053\u6bcf\u4e2a\u5c42\u6b21\u7684\u8fb9\u754c\u6761\u4ef6\u548c\u4e0d\u540c\u7ec6\u5316\u5c42\u6b21\u4e4b\u95f4\u63a5\u53e3\u7684\u81ea\u7531\u5ea6\uff0c\u53ef\u4ee5\u4ece\u5177\u6709\u5c42\u6b21\u81ea\u7531\u5ea6\u7684DoFHandler\u5bf9\u8c61\u4e2d\u5efa\u7acb\u8fd9\u4e9b\u8f6c\u79fb\u64cd\u4f5c\u7684\u77e9\u9635\u3002\n\n// \u4e0b\u9762\u51e0\u884c\u7684\u7b2c\u4e8c\u90e8\u5206\u662f\u5173\u4e8e\u7c97\u7565\u7f51\u683c\u6c42\u89e3\u5668\u7684\u3002\u7531\u4e8e\u6211\u4eec\u7684\u7c97\u7f51\u683c\u786e\u5b9e\u975e\u5e38\u7c97\uff0c\u6211\u4eec\u51b3\u5b9a\u91c7\u7528\u76f4\u63a5\u6c42\u89e3\u5668\uff08\u6700\u7c97\u5c42\u6b21\u77e9\u9635\u7684Householder\u5206\u89e3\uff09\uff0c\u5373\u4f7f\u5176\u5b9e\u73b0\u4e0d\u662f\u7279\u522b\u590d\u6742\u3002\u5982\u679c\u6211\u4eec\u7684\u7c97\u7f51\u683c\u6bd4\u8fd9\u91cc\u76845\u4e2a\u5355\u5143\u591a\u5f97\u591a\uff0c\u90a3\u4e48\u8fd9\u91cc\u663e\u7136\u9700\u8981\u66f4\u5408\u9002\u7684\u4e1c\u897f\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::solve() \n  { \n    MGTransferPrebuilt<Vector<double>> mg_transfer(mg_constrained_dofs); \n    mg_transfer.build(dof_handler); \n\n    FullMatrix<double> coarse_matrix; \n    coarse_matrix.copy_from(mg_matrices[0]); \n    MGCoarseGridHouseholder<double, Vector<double>> coarse_grid_solver; \n    coarse_grid_solver.initialize(coarse_matrix); \n\n// \u591a\u7ea7\u6c42\u89e3\u5668\u6216\u9884\u5904\u7406\u5668\u7684\u4e0b\u4e00\u4e2a\u7ec4\u6210\u90e8\u5206\u662f\uff0c\u6211\u4eec\u9700\u8981\u5728\u6bcf\u4e00\u7ea7\u4e0a\u6709\u4e00\u4e2a\u5e73\u6ed1\u5668\u3002\u8fd9\u65b9\u9762\u5e38\u89c1\u7684\u9009\u62e9\u662f\u4f7f\u7528\u677e\u5f1b\u65b9\u6cd5\u7684\u5e94\u7528\uff08\u5982SOR\u3001Jacobi\u6216Richardson\u65b9\u6cd5\uff09\u6216\u6c42\u89e3\u5668\u65b9\u6cd5\u7684\u5c11\u91cf\u8fed\u4ee3\uff08\u5982CG\u6216GMRES\uff09\u3002 mg::SmootherRelaxation \u548cMGSmootherPrecondition\u7c7b\u4e3a\u8fd9\u4e24\u79cd\u5e73\u6ed1\u5668\u63d0\u4f9b\u652f\u6301\u3002\u8fd9\u91cc\uff0c\u6211\u4eec\u9009\u62e9\u5e94\u7528\u5355\u4e00\u7684SOR\u8fed\u4ee3\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u5b9a\u4e49\u4e00\u4e2a\u9002\u5f53\u7684\u522b\u540d\uff0c\u7136\u540e\u8bbe\u7f6e\u4e00\u4e2a\u5e73\u6ed1\u5668\u5bf9\u8c61\u3002\n\n// \u6700\u540e\u4e00\u6b65\u662f\u7528\u6211\u4eec\u7684\u6c34\u5e73\u77e9\u9635\u521d\u59cb\u5316\u5e73\u6ed1\u5668\u5bf9\u8c61\uff0c\u5e76\u8bbe\u7f6e\u4e00\u4e9b\u5e73\u6ed1\u53c2\u6570\u3002 <code>initialize()</code> \u51fd\u6570\u53ef\u4ee5\u6709\u9009\u62e9\u5730\u63a5\u53d7\u989d\u5916\u7684\u53c2\u6570\uff0c\u8fd9\u4e9b\u53c2\u6570\u5c06\u88ab\u4f20\u9012\u7ed9\u6bcf\u4e00\u7ea7\u7684\u5e73\u6ed1\u5668\u5bf9\u8c61\u3002\u5728\u5f53\u524dSOR\u5e73\u6ed1\u5668\u7684\u60c5\u51b5\u4e0b\uff0c\u8fd9\u53ef\u80fd\u5305\u62ec\u4e00\u4e2a\u677e\u5f1b\u53c2\u6570\u3002\u7136\u800c\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u5c06\u8fd9\u4e9b\u53c2\u6570\u4fdd\u7559\u4e3a\u9ed8\u8ba4\u503c\u3002\u5bf9 <code>set_steps()</code> \u7684\u8c03\u7528\u8868\u660e\u6211\u4eec\u5c06\u5728\u6bcf\u4e2a\u7ea7\u522b\u4e0a\u4f7f\u7528\u4e24\u4e2a\u524d\u5e73\u6ed1\u6b65\u9aa4\u548c\u4e24\u4e2a\u540e\u5e73\u6ed1\u6b65\u9aa4\uff1b\u4e3a\u4e86\u5728\u4e0d\u540c\u7ea7\u522b\u4e0a\u4f7f\u7528\u53ef\u53d8\u6570\u91cf\u7684\u5e73\u6ed1\u5668\u6b65\u9aa4\uff0c\u53ef\u4ee5\u5728\u5bf9 <code>mg_smoother</code> \u5bf9\u8c61\u7684\u6784\u9020\u51fd\u6570\u8c03\u7528\u4e2d\u8bbe\u7f6e\u66f4\u591a\u9009\u9879\u3002\n\n// \u6700\u540e\u4e00\u6b65\u7684\u7ed3\u679c\u662f\u6211\u4eec\u4f7f\u7528SOR\u65b9\u6cd5\u4f5c\u4e3a\u5e73\u6ed1\u5668\u7684\u4e8b\u5b9e\n\n// --\u8fd9\u4e0d\u662f\u5bf9\u79f0\u7684\n\n// \u4f46\u6211\u4eec\u5728\u4e0b\u9762\u4f7f\u7528\u5171\u8f6d\u68af\u5ea6\u8fed\u4ee3\uff08\u9700\u8981\u5bf9\u79f0\u7684\u9884\u5904\u7406\uff09\uff0c\u6211\u4eec\u9700\u8981\u8ba9\u591a\u7ea7\u9884\u5904\u7406\u786e\u4fdd\u6211\u4eec\u5f97\u5230\u4e00\u4e2a\u5bf9\u79f0\u7684\u7b97\u5b50\uff0c\u5373\u4f7f\u662f\u975e\u5bf9\u79f0\u7684\u5e73\u6ed1\u5668\u3002\n\n    using Smoother = PreconditionSOR<SparseMatrix<double>>; \n    mg::SmootherRelaxation<Smoother, Vector<double>> mg_smoother; \n    mg_smoother.initialize(mg_matrices); \n    mg_smoother.set_steps(2); \n    mg_smoother.set_symmetric(true); \n\n// \u4e0b\u4e00\u4e2a\u51c6\u5907\u6b65\u9aa4\u662f\uff0c\u6211\u4eec\u5fc5\u987b\u5c06\u6211\u4eec\u7684\u6c34\u5e73\u77e9\u9635\u548c\u63a5\u53e3\u77e9\u9635\u5305\u88f9\u5728\u4e00\u4e2a\u5177\u6709\u6240\u9700\u4e58\u6cd5\u51fd\u6570\u7684\u5bf9\u8c61\u4e2d\u3002\u6211\u4eec\u5c06\u4e3a\u4ece\u7c97\u5230\u7ec6\u7684\u63a5\u53e3\u5bf9\u8c61\u521b\u5efa\u4e24\u4e2a\u5bf9\u8c61\uff0c\u53cd\u4e4b\u4ea6\u7136\uff1b\u591a\u7f51\u683c\u7b97\u6cd5\u5c06\u5728\u4ee5\u540e\u7684\u64cd\u4f5c\u4e2d\u4f7f\u7528\u8f6c\u7f6e\u8fd0\u7b97\u5668\uff0c\u5141\u8bb8\u6211\u4eec\u7528\u5df2\u7ecf\u5efa\u7acb\u7684\u77e9\u9635\u521d\u59cb\u5316\u8be5\u8fd0\u7b97\u5668\u7684\u4e0a\u4e0b\u7248\u672c\u3002\n\n    mg::Matrix<Vector<double>> mg_matrix(mg_matrices); \n    mg::Matrix<Vector<double>> mg_interface_up(mg_interface_in); \n    mg::Matrix<Vector<double>> mg_interface_down(mg_interface_out); \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u51c6\u5907\u8bbe\u7f6eV\u578b\u5faa\u73af\u7b97\u5b50\u548c\u591a\u7ea7\u9884\u5904\u7406\u7a0b\u5e8f\u3002\n\n    Multigrid<Vector<double>> mg( \n      mg_matrix, coarse_grid_solver, mg_transfer, mg_smoother, mg_smoother); \n    mg.set_edge_matrices(mg_interface_down, mg_interface_up); \n\n    PreconditionMG<dim, Vector<double>, MGTransferPrebuilt<Vector<double>>> \n      preconditioner(dof_handler, mg, mg_transfer); \n\n// \u6709\u4e86\u8fd9\u4e00\u5207\uff0c\u6211\u4eec\u7ec8\u4e8e\u53ef\u4ee5\u7528\u901a\u5e38\u7684\u65b9\u6cd5\u6765\u89e3\u51b3\u8fd9\u4e2a\u7ebf\u6027\u7cfb\u7edf\u4e86\u3002\n\n    SolverControl            solver_control(1000, 1e-12); \n    SolverCG<Vector<double>> solver(solver_control); \n\n    solution = 0; \n\n    solver.solve(system_matrix, solution, system_rhs, preconditioner); \n    constraints.distribute(solution); \n  } \n\n//  @sect4{Postprocessing}  \n\n// \u4e0b\u9762\u4e24\u4e2a\u51fd\u6570\u5728\u8ba1\u7b97\u51fa\u89e3\u51b3\u65b9\u6848\u540e\u5bf9\u5176\u8fdb\u884c\u540e\u5904\u7406\u3002\u7279\u522b\u662f\uff0c\u7b2c\u4e00\u4e2a\u51fd\u6570\u5728\u6bcf\u4e2a\u5468\u671f\u5f00\u59cb\u65f6\u7ec6\u5316\u7f51\u683c\uff0c\u7b2c\u4e8c\u4e2a\u51fd\u6570\u5728\u6bcf\u4e2a\u5468\u671f\u7ed3\u675f\u65f6\u8f93\u51fa\u7ed3\u679c\u3002\u8fd9\u4e9b\u51fd\u6570\u4e0e step-6 \u4e2d\u7684\u51fd\u6570\u51e0\u4e4e\u6ca1\u6709\u53d8\u5316\uff0c\u53ea\u6709\u4e00\u4e2a\u5c0f\u7684\u533a\u522b\uff1a\u6211\u4eec\u4ee5VTK\u683c\u5f0f\u751f\u6210\u8f93\u51fa\uff0c\u4ee5\u4f7f\u7528\u5f53\u4eca\u66f4\u73b0\u4ee3\u7684\u53ef\u89c6\u5316\u7a0b\u5e8f\uff0c\u800c\u4e0d\u662f step-6 \u7f16\u5199\u65f6\u7684\u90a3\u4e9b\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::refine_grid() \n  { \n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n\n    KellyErrorEstimator<dim>::estimate( \n      dof_handler, \n      QGauss<dim - 1>(fe.degree + 1), \n      std::map<types::boundary_id, const Function<dim> *>(), \n      solution, \n      estimated_error_per_cell); \n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    estimated_error_per_cell, \n                                                    0.3, \n                                                    0.03); \n    triangulation.execute_coarsening_and_refinement(); \n  } \n\n  template <int dim> \n  void LaplaceProblem<dim>::output_results(const unsigned int cycle) const \n  { \n    DataOut<dim> data_out; \n\n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \"solution\"); \n    data_out.build_patches(); \n\n    std::ofstream output(\"solution-\" + std::to_string(cycle) + \".vtk\"); \n    data_out.write_vtk(output); \n  } \n// @sect4{LaplaceProblem::run}  \n\n// \u548c\u4e0a\u9762\u7684\u51e0\u4e2a\u51fd\u6570\u4e00\u6837\uff0c\u8fd9\u51e0\u4e4e\u662f\u5bf9  step-6  \u4e2d\u76f8\u5e94\u51fd\u6570\u7684\u590d\u5236\u3002\u552f\u4e00\u7684\u533a\u522b\u662f\u5bf9 <code>assemble_multigrid</code> \u7684\u8c03\u7528\uff0c\u5b83\u8d1f\u8d23\u5f62\u6210\u6211\u4eec\u5728\u591a\u7f51\u683c\u65b9\u6cd5\u4e2d\u9700\u8981\u7684\u6bcf\u4e00\u5c42\u7684\u77e9\u9635\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::run() \n  { \n    for (unsigned int cycle = 0; cycle < 8; ++cycle) \n      { \n        deallog << \"Cycle \" << cycle << std::endl; \n\n        if (cycle == 0) \n          { \n            GridGenerator::hyper_ball(triangulation); \n            triangulation.refine_global(1); \n          } \n        else \n          refine_grid(); \n\n        deallog << \"   Number of active cells:       \" \n                << triangulation.n_active_cells() << std::endl; \n\n        setup_system(); \n\n        assemble_system(); \n        assemble_multigrid(); \n\n        solve(); \n        output_results(cycle); \n      } \n  } \n} // namespace Step16 \n// @sect3{The main() function}  \n\n// \u8fd9\u53c8\u662f\u4e0e step-6 \u4e2d\u76f8\u540c\u7684\u51fd\u6570\u3002\n\nint main() \n{ \n  try \n    { \n      using namespace Step16; \n\n      deallog.depth_console(2); \n\n      LaplaceProblem<2> laplace_problem(1); \n      laplace_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\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\n", "meta": {"hexsha": "17659cf7cb431758d85dba74e63c48aae85e0cea", "size": 19275, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-16b/step-16b.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-16b/step-16b.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-16b/step-16b.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.8546845124, "max_line_length": 287, "alphanum_fraction": 0.6640726329, "num_tokens": 7396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5183664938482175}}
{"text": "/**\n * @file mmchecker.hpp:  Cube_Product_Checker template class\n * and its implementation.\n *\n * Class is for finding Strassen-like algorithms for cube product.\n *\n * @author Eugene Petkevich\n * @version pre-alpha\n */\n\n#ifndef MMCHECKER_HPP_INCLUDED\n#define MMCHECKER_HPP_INCLUDED\n\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <set>\n#include <vector>\n#include <map>\n#include <string>\n#include <numeric>\n#include <omp.h>\n\n#include <boost/dynamic_bitset.hpp>\n#include <boost/algorithm/string/join.hpp>\n\n#include \"slae.hpp\"\n#include \"utils.hpp\"\n\nusing namespace std;\n\n//=============================================================================\n\nclass Solution_Properties;\n\n//=============================================================================\n//=============================================================================\n\n/**\n * Main class, calculates all nesessary information\n * for given template parameters:\n *\n * @param N: size of the cube;\n * @param D: dimension of the cube;\n * @param NM: number of bits in multiplication vectors ((N^D)^D);\n * @param NMH: number of elements in the array (N^D).\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nclass Cube_Product_Checker {\npublic:\n    typedef mm_bitset<NM> Multiplication_Vector;\n    typedef mm_bitset<NMH> Multiplication_Part_Vector;\n    typedef set<int> Candidate;\n    int length; /// size of cube (N)\n    int dimension; /// dimension of cube (D)\n    int element_count; /// number of elements in cube (N^D)\n    mm_vector_with_properties_options vector_options; /// options for vector properties\n    mm_vector_with_properties<NM>* r_vectors; /// result vectors\n    mm_vector_with_properties<NM>* m_vectors; /// multiplication vectors\n    bool owns_arrays; /// If arrays are created by the object.\n    int m_count; /// number of non-zero multiplication vectors = (2^(N^D)-1)^D\n    int m_length; /// number non-zero element sums = 2^(N^D)-1\n    int f_count; /// number of vectors to choose for a basis (for minimal improvement it is N^(D+1)-1)\n    set<int> good_vectors_indexes; /// set of indexes for vectors that are in the current span\n    set<int> n_vectors_indexes; /// set of indexes of current chosen vectors\n    set<Candidate> neighbours; /// set of neighbours;\n    set<set<int>> solutions; /// set of found unique solutions\n    map<set<int>, int> solution_distribution; /// set of all found solutions\n    int iteration_count; /// number of finished iterations\n    int local_max_iterations; /// number of iterations in probable local maximum\n    int restarts; /// number of restarts\n    int local_iterations; /// number of iterations\n    int checked_sets_count; /// number of sets checked\n    int raw_solution_count; /// number of found solutions, including duplicates\n    int best_result; /// maximum number of vectors in the span found\n    int lin_dependent_sets;\n    Timewatch tw; /// timer that is used for getting calculation time\n    Random rnd; /// random number generator\n    int thread_number; /// thread number\n    map<Candidate, int> candidate_cache; /// cache of already checked candidates\n    int cache_limit; /// limit of the cache size\n    int cache_hits; /// cache hits\n    bool* stop_signal; /// if execution should be stopped\n    int bit_check_hits; /// number of bit check hits\n    int gaussian_eliminations; /// number of gaussian eliminations\n    set<set<int>> top_best_solutions; /// best solutions found so far\n    int top_best_result; /// best result so far\n    set<set<int>> candidate_space; /// candidate space\n\n    //=============--- constructors and destructors\n    Cube_Product_Checker();\n    ~Cube_Product_Checker();\n\n    //=============--- index operations\n    /// return linear index in a bit vector by its indexes in matrices\n    int get_vector_index(int ai, int aj, int bi, int bj) const; /// for 2-dimensional case\n    int get_vector_index(int ai, int aj, int ak, int bi, int bj, int bk, int ci, int cj, int ck) const; /// for 3-d case\n    /// return linear index in a bit vector by combined indexes in matrices\n    int get_vector_index(int a, int b) const; /// for 2-d case\n    int get_vector_index(int a, int b, int c) const; /// for 3-d case\n    /// return indices from bit index\n    void decode_indices_from_index(int index, int& ai, int& aj, int& bi, int& bj) const; /// for 2-d case\n    void decode_indices_from_index(int index, int& ai, int& aj, int& ak, int& bi, int& bj, int& bk, int& ci, int& cj, int& ck) const; /// for 3-d case\n    /// return linear index of an element in a matrix\n    int get_element_index(int i, int j) const; /// for 2-d case\n    int get_element_index(int i, int j, int k) const; /// for 3-d case\n    /// return index of multiplication vector in the set\n    int get_m_index(int i, int j) const; /// for 2-d case\n    int get_m_index(int i, int j, int k) const; /// for 3-d case\n    vector<int> decode_m_index(int index) const; /// return the coefficients from m-vector index\n\n    //=============--- Initial calculations\n    void init(int mult_count, const string& filename, const string& space_filename); /// calculate all properties\n    void init(const Cube_Product_Checker& cpc); /// Link to all properties in other object.\n    void calculate_r_vectors(); /// write result vectors to array\n    void calculate_m_vectors(); /// write multiplication vectors to array\n\n    //=============--- checking routines\n    void clear_sets(); /// clear current sets of vectors\n    void add_vector_to_set(int index); /// add vector to current sets\n    bool check_vectors_for_goodness(); /// check current set of vectors\n    void clear_statistics(); /// clear statistics of solutions\n    void make_random_candidate(); /// make random candidate solution\n    void make_candidate_from_space(); /// make random candidate from restricted space\n    bool check_cache(); /// check if candidate result is in cache\n    void update_cache(); /// update the cache with new result\n\n    //=============--- searching for solution\n    bool check_for_good_vectors(); /// check all solution space\n    bool check_for_good_vectors_randomized(); /// do random search\n    bool solve_hill_climbing(int local_max_limit, bool use_space); /// do local search\n    void start_neighbourhood(); /// make list of neighbours\n\n    //=============--- utilities\n    void output_vector(Multiplication_Vector v) const; /// output vector to screen\n    void output_vector_text(Multiplication_Vector v) const; /// output vector to screen in letters\n    void save_random_samples(int size, const char* filename) const; /// save random sets to a file (for testing later)\n    void read_samples_and_check(const char* filename, const char* filenameout) const; /// check sets from a file\n    void output_current_state() const; // output current state of the checker\n    void read_m_vectors(const string& filename); /// read m_vectors from file\n    void read_candidate_space(const string& filename); /// read candidate space from file\n    void write_m_vectors(const string& filename); /// write m_vectors into file\n\n    //=============--- Statistics and results\n    void save_results(const char* filename); /// save results to a file\n    bool check_solution(set<int> s, Solution_Properties& sp); /// check if a solution is valid\n    void save_solution_properties(const Solution_Properties& sp, const char* filename); /// output solution properties to a file\n    vector<int> sum_operations_cube(int index); /// number of summation operations inside cubes\n};\n\n//=============================================================================\n\nclass Solution_Properties {\npublic:\n    set<int> multiplication_vectors; /// multiplication vector indices\n    vector<boost::dynamic_bitset<>> coefficients; /// result vector coefficients\n    int operation_count; /// number of addition operations used for calculating result matrix overall\n};\n\n//=============================================================================\n//=============================================================================\n\n/**\n * Class constructor.\n *\n * Create an object for work with D-dimensional cubes of size N.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nCube_Product_Checker<N, D, NM, NMH>::\nCube_Product_Checker() :\n    owns_arrays(false)\n{\n    length = N;\n    dimension = D;\n    element_count = power(length, dimension);\n    f_count = power(length,dimension+1)-1;\n    m_length = power(2,element_count)-1;\n    m_count = power(m_length,dimension);\n    cache_limit = 3000000;\n    cache_hits = 0;\n    bit_check_hits = 0;\n    gaussian_eliminations = 0;\n    rnd.init(0, m_count-1);\n#ifdef VERBOSE_OUTPUT\n    cout << \"Cube Product Checker has been created.\" << endl;\n#endif // VERBOSE_OUTPUT\n}\n\n//=============================================================================\n\n/**\n * Destructor.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nCube_Product_Checker<N, D, NM, NMH>::\n~Cube_Product_Checker()\n{\n    if (owns_arrays) {\n        delete [] r_vectors;\n        delete [] m_vectors;\n        delete stop_signal;\n    }\n}\n\n//=============================================================================\n\n/**\n * Initialize the object with all necessary properties.\n *\n * @param mult_count:  number of multiplications in resulting algorithm.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\ninit(int mult_count, const string& filename, const string& space_filename)\n{\n    f_count = mult_count;\n    stop_signal = new bool(false);\n    r_vectors = new mm_vector_with_properties<NM>[element_count];\n    m_vectors = new mm_vector_with_properties<NM>[m_count];\n    mm_vector_with_properties<NM>::make_options(vector_options);\n    owns_arrays = true;\n#ifdef VERBOSE_OUTPUT\n    tw.watch();\n#endif // VERBOSE_OUTPUT\n    calculate_r_vectors();\n    for (int i = 0; i < element_count; ++i) {\n        r_vectors[i].calculate_properties(vector_options);\n    }\n#ifdef VERBOSE_OUTPUT\n    cout << \"[\" << tw.watch() << \" s] Result vectors calculated.\" << endl;\n#endif // VERBOSE_OUTPUT\n    if (filename.length() > 0) {\n        read_m_vectors(filename);\n    } else {\n        calculate_m_vectors();\n        for (int i = 0; i < m_count; ++i) {\n            m_vectors[i].calculate_properties(vector_options);\n        }\n    }\n    if (space_filename.length() > 0) {\n        read_candidate_space(space_filename);\n    }\n#ifdef VERBOSE_OUTPUT\n    cout << \"[\" << tw.watch() << \" s] Multiplication vectors calculated.\" << endl;\n#endif // VERBOSE_OUTPUT\n}\n\n/**\n * Initialize the object with all necessary properties from other object.\n *\n * Link to all big data fields in the other object.\n *\n * @param cpc: the object to get main arrays from.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\ninit(const Cube_Product_Checker& cpc)\n{\n    f_count = cpc.f_count;\n    r_vectors = cpc.r_vectors;\n    m_vectors = cpc.m_vectors;\n    vector_options = cpc.vector_options;\n    stop_signal = cpc.stop_signal;\n    candidate_space = cpc.candidate_space;\n}\n\n//=============================================================================\n\n/**\n * Get bit index in a multiplication vector (2-dimensional case).\n *\n * @param ai: element's first index in the first matrix;\n * @param aj: element's second index in the first matrix;\n * @param bi: element's first index in the second matrix;\n * @param bj: element's second index in the second matrix;\n *\n * @return bit index.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\ninline int\nCube_Product_Checker<N, D, NM, NMH>::\nget_vector_index(int ai, int aj,\n                 int bi, int bj) const\n{\n    int result = ai;\n    result *= length;\n    result += aj;\n    result *= length;\n\n    result += bi;\n    result *= length;\n    result += bj;\n    return result;\n}\n\n/**\n * Get bit index in a multiplication vector (3-dimensional case).\n *\n * @param ai: element's first index in the first cube;\n * @param aj: element's second index in the first cube;\n * @param ak: element's third index in the first cube;\n * @param bi: element's first index in the second cube;\n * @param bj: element's second index in the second cube;\n * @param bk: element's third index in the second cube;\n * @param ci: element's first index in the third cube;\n * @param cj: element's second index in the third cube;\n * @param ck: element's third index in the third cube.\n *\n * @return bit index.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\ninline int\nCube_Product_Checker<N, D, NM, NMH>::\nget_vector_index(int ai, int aj, int ak,\n                 int bi, int bj, int bk,\n                 int ci, int cj, int ck) const\n{\n    int result = ai;\n    result *= length;\n    result += aj;\n    result *= length;\n    result += ak;\n    result *= length;\n\n    result += bi;\n    result *= length;\n    result += bj;\n    result *= length;\n    result += bk;\n    result *= length;\n\n    result += ci;\n    result *= length;\n    result += cj;\n    result *= length;\n    result += ck;\n    return result;\n}\n\n//=============================================================================\n\n/**\n * Get bit index in a multiplication vector (2-dimensional case).\n *\n * @param a: element'S index in the first matrix;\n * @param b: element'S index in the second matrix.\n *\n * @return bit index.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\ninline int\nCube_Product_Checker<N, D, NM, NMH>::\nget_vector_index(int a, int b) const\n{\n    int result = a;\n    result *= element_count;\n    result += b;\n    return result;\n}\n\n/**\n * Get bit index in a multiplication vector (3-dimensional case).\n *\n * @param a: element's index in the first cube;\n * @param b: element's index in the second cube;\n * @param c: element's index in the third cube.\n *\n * @return bit index.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\ninline int\nCube_Product_Checker<N, D, NM, NMH>::\nget_vector_index(int a, int b, int c) const\n{\n    int result = a;\n    result *= element_count;\n    result += b;\n    result *= element_count;\n    result += c;\n    return result;\n}\n\n//=============================================================================\n\n/**\n * Get element indices in matrices from bit index in the multiplication vector\n * (2-dimensional case).\n *\n * @param index: bit index in a multiplication vector;\n *\n * @param ai: element's first index in the first matrix;\n * @param aj: element's second index in the first matrix;\n * @param bi: element's first index in the second matrix;\n * @param bj: element's second index in the second matrix.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\ninline void\nCube_Product_Checker<N, D, NM, NMH>::\ndecode_indices_from_index(int index,\n                          int& ai, int& aj,\n                          int& bi, int& bj) const\n{\n    bj = index % length;\n    index /= length;\n    bi = index % length;;\n    index /= length;\n    aj = index % length;\n    index /= length;\n    ai = index;\n    return;\n}\n\n/**\n * Get element indices in cubes from bit index in a multiplication vector\n * (2-dimensional case).\n *\n * @param index: bit index in the multiplication vector;\n *\n * @param ai: element's first index in the first cube;\n * @param aj: element's second index in the first cube;\n * @param ak: element's third index in the first cube;\n * @param bi: element's first index in the second cube;\n * @param bj: element's second index in the second cube;\n * @param bk: element's third index in the second cube;\n * @param ci: element's first index in the third cube;\n * @param cj: element's second index in the third cube;\n * @param ck: element's third index in the third cube.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\ninline void\nCube_Product_Checker<N, D, NM, NMH>::\ndecode_indices_from_index(int index,\n                          int& ai, int& aj, int& ak,\n                          int& bi, int& bj, int& bk,\n                          int& ci, int& cj, int& ck) const\n{\n    ck = index % length;\n    index /= length;\n    cj = index % length;\n    index /= length;\n    ci = index % length;\n    index /= length;\n\n    bk = index % length;\n    index /= length;\n    bj = index % length;\n    index /= length;\n    bi = index % length;\n    index /= length;\n\n    ak = index % length;\n    index /= length;\n    aj = index % length;\n    index /= length;\n    ai = index;\n    return;\n}\n\n//=============================================================================\n\n/**\n * Get element's index in a matrix (2-dimensional case).\n *\n * @param i: element's first index in the cube;\n * @param j: element's second index in the cube;\n *\n * @return element's index in the cube.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\ninline int\nCube_Product_Checker<N, D, NM, NMH>::\nget_element_index(int i, int j) const\n{\n    return ((i*length) + j);\n}\n\n/**\n * Get element's index in a cube (3-dimensional case).\n *\n * @param i: element's first index in the cube;\n * @param j: element's second index in the cube;\n * @param k: element's third index in the cube;\n *\n * @return element's index in the cube.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\ninline int\nCube_Product_Checker<N, D, NM, NMH>::\nget_element_index(int i, int j, int k) const\n{\n    return (((i*length) + j)*length + k);\n}\n\n//=============================================================================\n\n/**\n * Get index of a multiplication vector by its sum indices.\n *\n * This index is a unique number of the vector\n * in the set of all non-zero multiplication vectors.\n *\n * @param i: vector's first index;\n * @param j: vector's second index;\n *\n * @return multiplication vector index.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\ninline int\nCube_Product_Checker<N, D, NM, NMH>::\nget_m_index(int i, int j) const\n{\n    return ((i*m_length) + j);\n}\n\n/**\n * Get index of a multiplication vector by its sum indices.\n *\n * This index is a unique number of the vector\n * in the set of all non-zero multiplication vectors.\n *\n * @param i: vector's first index;\n * @param j: vector's second index;\n * @param k: vector's third index;\n *\n * @return multiplication vector index.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\ninline int\nCube_Product_Checker<N, D, NM, NMH>::\nget_m_index(int i, int j, int k) const\n{\n    return (((i*m_length) + j)*m_length + k);\n}\n\n//=============================================================================\n\n/**\n * Get coefficients of cube elements by number of multiplication vector.\n *\n * @param multiplication vector index.\n *\n * @return\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\ninline vector<int>\nCube_Product_Checker<N, D, NM, NMH>::\ndecode_m_index(int index) const\n{\n    int last, previous;\n    last = index % m_length;\n    index /= m_length;\n    previous = index % m_length;\n    vector<int> result;\n    if (dimension == 3) {\n        int first = index / m_length;\n        result.push_back(first);\n    }\n    result.push_back(previous);\n    result.push_back(last);\n    return result;\n}\n\n//=============================================================================\n\n/**\n * Calculate product result vectors (2x2 case).\n */\ntemplate <>\nvoid\nCube_Product_Checker<2, 2, 16, 4>::\ncalculate_r_vectors()\n{\n    for (int i = 0; i < length; ++i) {\n        for (int j = 0; j < length; ++j) {\n            int index = get_element_index(i, j);\n            r_vectors[index].v.reset();\n            for (int l = 0; l < length; ++l) {\n                r_vectors[index].v[get_vector_index(i, l, l, j)] = 1;\n            }\n        }\n    }\n}\n\n/**\n * Calculate product result vectors (3x3 case).\n */\ntemplate <>\nvoid\nCube_Product_Checker<3, 2, 81, 9>::\ncalculate_r_vectors()\n{\n    for (int i = 0; i < length; ++i) {\n        for (int j = 0; j < length; ++j) {\n            int index = get_element_index(i, j);\n            r_vectors[index].v.reset();\n            for (int l = 0; l < length; ++l) {\n                r_vectors[index].v[get_vector_index(i, l, l, j)] = 1;\n            }\n        }\n    }\n}\n\n/**\n * Calculate product result vectors (2x2x2 case).\n */\ntemplate <>\nvoid\nCube_Product_Checker<2, 3, 512, 8>::\ncalculate_r_vectors()\n{\n    for (int i = 0; i < length; ++i) {\n        for (int j = 0; j < length; ++j) {\n            for (int k = 0; k < length; ++k) {\n                int index = get_element_index(i, j, k);\n                r_vectors[index].v.reset();\n                for (int l = 0; l < length; ++l) {\n                    r_vectors[index].v[get_vector_index(i, j, l, i, l, k, l, j, k)] = 1;\n                }\n            }\n        }\n    }\n}\n\n//=============================================================================\n\n/**\n * Calculate non-zero multiplication vectors (2x2 case).\n */\ntemplate <>\nvoid\nCube_Product_Checker<2, 2, 16, 4>::\ncalculate_m_vectors()\n{\n    for (int i = 1; i < power(2,element_count); ++i) {\n        for (int j = 1; j < power(2,element_count); ++j) {\n            Multiplication_Part_Vector av(i);\n            Multiplication_Part_Vector bv(j);\n            int index = get_m_index(i-1, j-1);\n            m_vectors[index].v.reset();\n            for (int k = 0; k < element_count; ++k) {\n                for (int l = 0; l < element_count; ++l) {\n                    if (av[k] && bv[l]) {\n                        m_vectors[index].v.set(get_vector_index(k, l));\n                    }\n                }\n            }\n        }\n    }\n}\n\n/**\n * Calculate non-zero multiplication vectors (3x3 case).\n */\ntemplate <>\nvoid\nCube_Product_Checker<3, 2, 81, 9>::\ncalculate_m_vectors()\n{\n    for (int i = 1; i < power(2,element_count); ++i) {\n        for (int j = 1; j < power(2,element_count); ++j) {\n            Multiplication_Part_Vector av(i);\n            Multiplication_Part_Vector bv(j);\n            int index = get_m_index(i-1, j-1);\n            m_vectors[index].v.reset();\n            for (int k = 0; k < element_count; ++k) {\n                for (int l = 0; l < element_count; ++l) {\n                    if (av[k] && bv[l]) {\n                        m_vectors[index].v.set(get_vector_index(k, l));\n                    }\n                }\n            }\n        }\n    }\n}\n\n/**\n * Calculate non-zero multiplication vectors (3-d case).\n */\ntemplate <>\nvoid\nCube_Product_Checker<2, 3, 512, 8>::\ncalculate_m_vectors()\n{\n    for (int i = 1; i < power(2,element_count); ++i) {\n        for (int j = 1; j < power(2,element_count); ++j) {\n            for (int k = 1; k < power(2,element_count); ++k) {\n                Multiplication_Part_Vector av(i);\n                Multiplication_Part_Vector bv(j);\n                Multiplication_Part_Vector cv(k);\n                int index = get_m_index(i-1, j-1, k-1);\n                m_vectors[index].v.reset();\n                for (int l = 0; l < element_count; ++l) {\n                    for (int o = 0; o < element_count; ++o) {\n                        for (int p = 0; p < element_count; ++p) {\n                            if (av[l] & bv[o] & cv[p]) {\n                                m_vectors[index].v.set(get_vector_index(l, o, p));\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\n//=============================================================================\n\n/**\n * Clear the current sets.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\nclear_sets()\n{\n    n_vectors_indexes.clear();\n    good_vectors_indexes.clear();\n}\n\n//=============================================================================\n\n/**\n * Add a multiplication vector to the current set.\n *\n * @param index: index of the multiplication vector.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\nadd_vector_to_set(int index)\n{\n    n_vectors_indexes.insert(index);\n}\n\n//=============================================================================\n\n/**\n * Clear statistics.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\nclear_statistics()\n{\n    checked_sets_count = 0;\n    iteration_count = 0;\n    best_result = 0;\n    lin_dependent_sets = 0;\n#ifdef OUTPUT_STATISTICS\n    raw_solution_count = 0;\n    solutions.clear();\n    solution_distribution.clear();\n#endif // OUTPUT_STATISTICS\n}\n\n//=============================================================================\n\n/**\n * Make a random candidate.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\nmake_random_candidate()\n{\n    clear_sets();\n    for (int i = 0; i < (f_count-element_count); ++i) {\n        int cc = rnd.next();\n        while (n_vectors_indexes.count(cc) > 0) {\n            cc = rnd.next();\n        }\n        add_vector_to_set(cc);\n    }\n}\n\n//=============================================================================\n\n/**\n * Make a random candidate.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\nmake_candidate_from_space()\n{\n    clear_sets();\n    n_vectors_indexes = (*candidate_space.begin());\n}\n\n//=============================================================================\n\n/**\n * If current candidate is in cache, than get info from cache.\n *\n * @return true if the current candidate is in cache.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nbool\nCube_Product_Checker<N, D, NM, NMH>::\ncheck_cache()\n{\n    map<Candidate, int>::const_iterator it;\n    if ((it = candidate_cache.find(n_vectors_indexes)) != candidate_cache.end()) {\n        best_result = it->second;\n        ++cache_hits;\n        return true;\n    } else {\n        return false;\n    }\n}\n\n//=============================================================================\n\n/**\n * Update the cache with new result.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\nupdate_cache()\n{\n    if (candidate_cache.size() >= cache_limit) {\n        candidate_cache.clear();\n        //cout << \"------------->> Cache cleared\" << endl;\n    }\n    candidate_cache[n_vectors_indexes] = best_result;\n}\n\n//=============================================================================\n\n/**\n * Check the current set for being a solution.\n *\n * @return true if the current set is a solution.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nbool\nCube_Product_Checker<N, D, NM, NMH>::\ncheck_vectors_for_goodness()\n{\n#ifdef VERY_DETAILED_OUTPUT\n    cout << \"<\" << thread_number << \"> \";\n    cout << \"Checking of vectors { \";\n    for (int i: n_vectors_indexes) {\n        cout << i << \" \";\n    }\n    cout << \"} has started...\" << endl;\n    tw.watch();\n#endif // VERY_DETAILED_OUTPUT\n    ++checked_sets_count;\n#ifdef USE_CACHE\n    if (check_cache()) {\n        if (best_result == f_count) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n#endif // USE_CACHE\n    vector<mm_vector_with_properties<NM>> nvwp; /// set of span vectors for SLAE\n    vector<mm_vector_with_properties<NM>> gvwp; /// set of good vectors for SLAE\n    Vectors_Presolve_Data<NM> v; /// vector presolve data for span vectors\n    Gauss_WP_Presolve_Data<NM> pwp(0); /// presolve data for SLAE for span vectors\n    Gauss_WP_Presolve_Data<NM> pwpg(0); /// presolve data for SLAE for good vectors\n\n    for (set<int>::iterator i = n_vectors_indexes.begin(); i != n_vectors_indexes.end(); ++i) {\n        nvwp.push_back(m_vectors[*i]);\n        v.add_vector(m_vectors[*i].v);\n    }\n    for (int i = 0; i < element_count; ++i) {\n        nvwp.push_back(r_vectors[i]);\n        v.add_vector(r_vectors[i].v);\n    }\n    if (!gauss_wp_presolve(nvwp, pwp)) { // vectors are linearly dependent\n        ++lin_dependent_sets;\n#ifdef USE_CACHE\n        update_cache();\n#endif // USE_CACHE\n        return false;\n    }\n    gauss_wp_presolve(gvwp, pwpg);\n    v.presolve();\n    for (int i = 0; i < m_count; ++i) {\n        //if (!v.check(m_vectors[i].v)) { // discard vector by checking bits\n        //    ++bit_check_hits;\n        //    continue;\n        //}\n#ifdef OUTPUT_STATISTICS\n        ++gaussian_eliminations;\n#endif // OUTPUT_STATISTICS\n        if (gauss_wp_solve(pwp, m_vectors[i])) { // if vector is in the current span\n#ifdef OUTPUT_STATISTICS\n            ++gaussian_eliminations;\n#endif // OUTPUT_STATISTICS\n            if (!gauss_wp_solve(pwpg, m_vectors[i])) { // if not linearly dependent\n                good_vectors_indexes.insert(i);\n                gvwp.push_back(m_vectors[i]);\n                gauss_wp_presolve(gvwp, pwpg);\n            }\n            if (good_vectors_indexes.size() >= f_count) // we have found solution\n                break;\n        }\n    }\n#ifdef VERY_DETAILED_OUTPUT\n    cout << \"  [\" << tw.watch() << \" s] Done.\" << endl;\n#endif // VERY_DETAILED_OUTPUT\n    best_result = good_vectors_indexes.size();\n    if (best_result > (f_count-element_count)) {\n        if (best_result >= top_best_result) {\n            if (best_result > top_best_result) {\n                top_best_result = best_result;\n                top_best_solutions.clear();\n#ifdef SAVE_BEST_RESULTS_TO_FILE\n                ofstream fout(to_string(thread_number)+string(\"bestsofar.txt\"), ios_base::app);\n                fout << top_best_result << \" vectors\" << endl;\n                fout.close();\n#endif // SAVE_BEST_RESULTS_TO_FILE\n            }\n            top_best_solutions.insert(n_vectors_indexes);\n#ifdef SAVE_BEST_RESULTS_TO_FILE\n            ofstream fout(to_string(thread_number)+string(\"bestsofar.txt\"), ios_base::app);\n            for (set<int>::iterator cc = n_vectors_indexes.begin(); cc != n_vectors_indexes.end(); ++cc) {\n                fout << *cc << \" \";\n            }\n            fout << endl;\n            fout.close();\n#endif // SAVE_BEST_RESULTS_TO_FILE\n        }\n    }\n#ifdef USE_CACHE\n        update_cache();\n#endif // USE_CACHE\n    if (good_vectors_indexes.size() >= f_count) { // there is a solution\n#ifdef VERBOSE_OUTPUT\n        cout << \"  Good vectors have been found: { \";\n        for (set<int>::iterator cc = good_vectors_indexes.begin(); cc != good_vectors_indexes.end(); ++cc) {\n            cout << *cc << \" \";\n        }\n        cout << \"}\" << endl;\n#endif // VERBOSE_OUTPUT\n#ifdef OUTPUT_SOLUTIONS_TO_FILE\n        ofstream mvfile(\"good.txt\");\n        mvfile << \"Found good vectors!!!\\n\";\n        for (set<int>::iterator cc = good_vectors_indexes.begin(); cc != good_vectors_indexes.end(); ++cc) {\n            mvfile << *cc << \" \";\n        }\n        mvfile << \"\\n\";\n#endif // OUTPUT_SOLUTIONS_TO_FILE\n        return true;\n    }\n    return false;\n}\n\n//=============================================================================\n\n/**\n * Check all solution space for solutions (2x2 case).\n *\n * @return true if at least one solution was found.\n */\ntemplate <>\nbool\nCube_Product_Checker<2, 2, 16, 4>::\ncheck_for_good_vectors()\n{\n    clear_statistics();\n    for (int c1 = 0; c1 < m_count-2; ++c1) {\n        //cout << c1 << endl;\n        for (int c2 = c1+1; c2 < m_count-1; ++c2) {\n            for (int c3 = c2+1; c3 < m_count; ++c3) {\n                if (*stop_signal)\n                    return false;\n                clear_sets();\n                add_vector_to_set(c1);\n                add_vector_to_set(c2);\n                add_vector_to_set(c3);\n                if (check_vectors_for_goodness()) {\n#ifdef OUTPUT_STATISTICS\n                    solutions.insert(good_vectors_indexes);\n                    ++solution_distribution[good_vectors_indexes];\n                    ++raw_solution_count;\n#endif // OUTPUT_STATISTICS\n                }\n            }\n        }\n    }\n    return true;\n}\n\n/**\n * Check all solution space for solutions (2x2x2 case).\n *\n * @return true if a solution was found.\n */\ntemplate <>\nbool\nCube_Product_Checker<2, 3, 512, 8>::\ncheck_for_good_vectors()\n{\n    clear_statistics();\n    for (int c1 = 0; c1 < m_count-6; ++c1)\n        for (int c2 = c1+1; c2 < m_count-5; ++c2)\n            for (int c3 = c2+1; c3 < m_count-4; ++c3)\n                for (int c4 = c3+1; c4 < m_count-3; ++c4)\n                    for (int c5 = c4+1; c5 < m_count-2; ++c5)\n                        for (int c6 = c5+1; c6 < m_count-1; ++c6)\n                            for (int c7 = c6+1; c7 < m_count; ++c7) {\n                                if (*stop_signal)\n                                    return false;\n                                clear_sets();\n                                add_vector_to_set(c1);\n                                add_vector_to_set(c2);\n                                add_vector_to_set(c3);\n                                add_vector_to_set(c4);\n                                add_vector_to_set(c5);\n                                add_vector_to_set(c6);\n                                add_vector_to_set(c7);\n                                if (check_vectors_for_goodness())\n                                    return true;\n                            }\n    return false;\n}\n\n//=============================================================================\n\n/**\n * Check solutions by randomly picking vector sets.\n *\n * @return true if a solution was found.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nbool\nCube_Product_Checker<N, D, NM, NMH>::\ncheck_for_good_vectors_randomized()\n{\n    clear_statistics();\n    while (true) {\n        if (*stop_signal)\n            return false;\n        make_random_candidate();\n        if (check_vectors_for_goodness())\n            return true;\n    }\n    return false;\n}\n\n//=============================================================================\n\n/**\n * Make neighbourhood of the current candidate.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\nstart_neighbourhood()\n{\n    //cout << \"Start making neighbours\" << endl;\n    neighbours.clear();\n    // all possible one-coefficient changes in one of the vectors\n    for (int i: n_vectors_indexes) {\n        //cout << \"  start with vector \" << i << endl;\n        Candidate c_set = Candidate(n_vectors_indexes);\n        c_set.erase(i);\n        vector<int> coef = decode_m_index(i);\n        vector<Multiplication_Part_Vector> cur_coef;\n        for (int j = 0; j < dimension; ++j) {\n            cur_coef.push_back(Multiplication_Part_Vector(coef[j]+1));\n        }\n#ifdef OUTPUT_STATISTICS\n        int value = cur_coef[0].to_ulong()-1;\n        for (int o = 1; o < dimension; ++o) {\n            value = value*m_length + cur_coef[o].to_ulong()-1;\n        }\n        if (value != i) {\n            cout << \"Hardcore error here! \" << value << endl;\n        }\n#endif // OUTPUT_STATISTICS\n        for (int j = 0; j < dimension; ++j) {\n            //cout << \"    start with cube \" << j << \" with total bits \" << cur_coef[j] << endl;\n            for (int k = 0; k < cur_coef[j].size(); ++k) {\n                //cout << \"      start with bit \" << k << endl;\n                cur_coef[j].flip(k);\n                if (cur_coef[j].count() == 0) {\n                    cur_coef[j].flip(k);\n                    continue;\n                }\n                Candidate new_set = Candidate(c_set);\n                int value = cur_coef[0].to_ulong()-1;\n                for (int o = 1; o < dimension; ++o) {\n                    value = value*m_length + cur_coef[o].to_ulong()-1;\n                }\n#ifdef OUTPUT_STATISTICS\n                if ((value < 0) || (value >= m_count)) {\n                    cout << \"--->  got value \" << value << endl\n                              << \"--->  after \" << i << endl\n                              << \"--->  on j = \" << j << \" and k = \" << k << endl\n                              << \"--->  with cur_coef[j] = \" << cur_coef[j] << \" and it's long as \" << cur_coef[j].to_ulong() << endl;\n                }\n#endif // OUTPUT_STATISTICS\n                new_set.insert(value);\n                if (new_set.size() == n_vectors_indexes.size()) {\n                    neighbours.insert(new_set);\n                }\n                cur_coef[j].flip(k);\n            }\n        }\n    }\n    //cout << \"Made \" << neighbours.size() << \" neigbours.\" << endl;\n}\n\n//=============================================================================\n\n/**\n * Check solutions by doing local search.\n *\n * @return true if a solution was found.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nbool\nCube_Product_Checker<N, D, NM, NMH>::\nsolve_hill_climbing(int local_max_limit, bool use_space)\n{\n    Random r;\n    clear_statistics();\n    clear_sets();\n    if (use_space) {\n        make_candidate_from_space();\n    } else {\n        make_random_candidate();\n    }\n    check_vectors_for_goodness();\n    local_max_iterations = 0;\n    local_iterations = 0;\n    restarts = 0;\n    while (true) {\n        if (local_max_iterations > local_max_limit) {\n#ifdef VERBOSE_OUTPUT\n            cout << omp_get_thread_num() << \"] Doing restart! local iterations = \" << local_iterations << \" / \" << iteration_count << endl;\n#endif // VERBOSE_OUTPUT\n            clear_sets();\n            if (use_space) {\n                make_candidate_from_space();\n            } else {\n                make_random_candidate();\n            }\n            check_vectors_for_goodness();\n            local_max_iterations = 0;\n            local_iterations = 0;\n            ++restarts;\n        }\n#ifdef VERBOSE_OUTPUT\n        cout << omp_get_thread_num() << \"] Iteration \" << local_iterations << \": best is \" << best_result << endl;\n#endif // VERBOSE_OUTPUT\n        if (best_result >= f_count)\n            break;\n        int next_best_result = 0;\n        int old_best_result = best_result;\n        vector<Candidate> best_candidates;\n        start_neighbourhood();\n        for (const Candidate& c: neighbours) {\n            if (*stop_signal)\n                return false;\n            n_vectors_indexes = c;\n            good_vectors_indexes.clear();\n            check_vectors_for_goodness();\n            if (best_result > next_best_result) {\n                next_best_result = best_result;\n                best_candidates.clear();\n                best_candidates.push_back(n_vectors_indexes);\n            } else if (best_result == next_best_result) {\n                best_candidates.push_back(n_vectors_indexes);\n            }\n        }\n        r.init(0, best_candidates.size()-1);\n        n_vectors_indexes = best_candidates[r.next()];\n        best_result = next_best_result;\n        if (next_best_result > old_best_result) {\n            local_max_iterations = 0;\n        } else {\n            ++local_max_iterations;\n        }\n        ++iteration_count;\n        ++local_iterations;\n#ifdef VERBOSE_OUTPUT\n        output_current_state();\n#endif // VERBOSE_OUTPUT\n        //cout << \"Iteration \" << iteration_count << \": best is \" << best_result << endl;\n    }\n    good_vectors_indexes.clear();\n    check_vectors_for_goodness();\n    if (best_result >= f_count)\n        return true;\n    else {\n        cout << \"Error!\" << endl;\n        return false;\n    }\n}\n\n//=============================================================================\n\n/**\n * Output current state variables of the checker.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\noutput_current_state() const\n{\n    cout << endl;\n    cout << \"===================================================\" << endl;\n    cout << \"Current state of thread <\" << thread_number << \"> is:\" << endl;\n    cout << checked_sets_count << \" checked sets\" << endl;\n    cout << restarts << \" restarts\" << endl;\n    cout << iteration_count << \" iterations\" << endl;\n    cout << lin_dependent_sets << \" linearly dependent sets hits\" << endl;\n    cout << bit_check_hits << \" bit check hits\" << endl;\n    cout << gaussian_eliminations << \" gaussian eliminations\" << endl;\n    cout << cache_hits << \" cache hits\" << endl;\n    cout << \"===================================================\" << endl;\n}\n\n//=============================================================================\n\n/**\n * Write m_vectors into file.\n *\n * @param filename: filename.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\nwrite_m_vectors(const string& filename)\n{\n    ofstream fout(filename);\n    for (int i = 0; i < m_count; ++i) {\n        fout << m_vectors[i].v.to_string() << m_vectors[i].r.to_string();\n    }\n    fout.close();\n}\n\n//=============================================================================\n\n/**\n * Read m_vectors from file.\n *\n * @param filename: filename.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\nread_m_vectors(const string& filename)\n{\n    ifstream fin(filename);\n    for (int i = 0; i < m_count; ++i) {\n        fin >> m_vectors[i].v >> m_vectors[i].r;\n    }\n    fin.close();\n}\n\n//=============================================================================\n\n/**\n * Read candidate space from file.\n *\n * @param filename: filename.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\nread_candidate_space(const string& filename)\n{\n    ifstream fin(filename);\n    set<int> candidate;\n    for (int i = 0; i < f_count-element_count; ++i) {\n        int v;\n        fin >> v;\n        candidate.insert(v);\n    }\n    candidate_space.insert(candidate);\n    fin.close();\n}\n\n//=============================================================================\n\n/**\n * Print binary value of a vector.\n *\n * @param v: the vector.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\noutput_vector(Multiplication_Vector v) const\n{\n    cout << v;\n}\n\n//=============================================================================\n\n/**\n * Print value of a vector in letters (2-d case).\n *\n * @param v: the vector.\n */\ntemplate <>\nvoid\nCube_Product_Checker<2, 2, 16, 4>::\noutput_vector_text(Multiplication_Vector v) const\n{\n    for (size_t i = 0; i < v.size(); ++i) {\n        if (v[i]) {\n            int ai, aj, bi, bj;\n            decode_indices_from_index(i, ai, aj, bi, bj);\n            cout << \"A\" << ai+1 << aj+1 << \"B\" << bi+1 << bj+1 << \" \";\n        }\n    }\n}\n\n//=============================================================================\n\n/**\n * Generate and save to a file a sequence of random sets.\n *\n * @param size: number of sets;\n * @param filename: filename.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\nsave_random_samples(int size, const char* filename) const\n{\n    ofstream fout(filename);\n    Random rnd(0, m_count-1);\n    fout << size << \"\\n\";\n    for (int i = 0; i < size; ++i) {\n        clear_sets();\n        for (int i = 0; i < (f_count-element_count); ++i) {\n            int cc = rnd.next();\n            while (n_vectors_indexes.count(cc) > 0) {\n                cc = rnd.next();\n            }\n            add_vector_to_set(cc);\n            fout << cc << \" \";\n        }\n        fout << \"\\n\";\n    }\n    fout.close();\n}\n\n//=============================================================================\n\n/**\n * Reda a set sequence from the file and check it.\n *\n * @param filenamein: filename to read from;\n * @param filenameout: filename for output.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid Cube_Product_Checker<N, D, NM, NMH>::\nread_samples_and_check(const char* filenamein, const char* filenameout) const\n{\n    ifstream fin(filenamein);\n    ofstream fout(filenameout, ios_base::app);\n    fout << \"\\n ################################### \\n\";\n    int size;\n    fin >> size;\n    Timewatch timer;\n    double time = 0.0;\n    int gv = 0;\n    for (int i = 0; i < size; ++i) {\n        if (N*D > 5) {\n            cout << \"working on case \" << i << \"\\n\";\n        }\n        clear_sets();\n        for (int i = 0; i < (f_count-element_count); ++i) {\n            int cc;\n            fin >> cc;\n            add_vector_to_set(cc);\n        }\n        timer.watch();\n        if (check_vectors_for_goodness()) {\n            ++gv;\n        }\n        double curtime = timer.watch();\n        time += curtime;\n        if (N*D > 5) {\n            fout << \"\\t\" << i << \": \" << curtime << \" s\\n\";\n        }\n    }\n    cout << \"Found \" << gv << \" solutions\\n\";\n    fout << \"Total time: \" << time << \" s (\" << (time/size) << \" s avg) (found \" << gv << \" good vectors)\\n\";\n    fout.close();\n}\n\n//=============================================================================\n\n/**\n * Calculate statistics and save to a file.\n *\n * @param filename: filename to save statistics.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\nsave_results(const char* filename) {\n    ofstream fout(filename);\n    fout << \"Results: \" << solutions.size() << \" different solutions were found.\" << endl;\n    fout << raw_solution_count << \" vector sets were successful.\" << endl;\n    map<int, int> vector_distribution = map<int, int>();\n    vector<map<int, int>> bit_distributions;\n    for (set<set<int>>::iterator i = solutions.begin(); i != solutions.end(); ++i) {\n        fout << \"[ \";\n        map<int, int> bd;\n        for (set<int>::iterator j = (*i).begin(); j != (*i).end(); ++j) {\n            fout << (*j) << \" \";\n            ++vector_distribution[*j];\n            for (size_t k = 0; k < m_vectors[*j].v.size(); ++k) {\n                if (m_vectors[*j].v.test(k)) {\n                    ++bd[k];\n                }\n            }\n        }\n        bit_distributions.push_back(bd);\n        fout << \"] : \" << solution_distribution[(*i)] << endl;\n    }\n    fout << endl << \"Used vectors are:\" << endl;\n    for (const auto& e: vector_distribution) {\n        fout << e.first << \"\\t\" << m_vectors[e.first].v << \" : \" << e.second << endl;\n    }\n    fout << endl << \"Bit distributions per solution are:\" << endl;\n    for (auto& e: bit_distributions) {\n        for (int i = 0; i < NM; ++i) {\n            fout << e[i];\n        }\n        fout << endl;\n    }\n    fout.close();\n}\n\n//=============================================================================\n\n/**\n * Check if a given set of vectors is a valid solution.\n *\n * @param s:  set of result vectors;\n *\n * @param sp: solution properties;\n *\n * @return if it is a solution.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nbool\nCube_Product_Checker<N, D, NM, NMH>::\ncheck_solution(set<int> s, Solution_Properties& sp) {\n    sp.coefficients.clear();\n    sp.multiplication_vectors.clear();\n    sp.multiplication_vectors = s;\n    sp.operation_count = 0;\n    vector<mm_bitset<NM>> vectors;\n    for (auto i: s) {\n        vectors.push_back(m_vectors[i].v);\n        vector<int> ops = sum_operations_cube(i);\n        sp.operation_count += accumulate(ops.begin(), ops.end(), -ops.size());\n    }\n    for (int i = 0; i < element_count; ++i) {\n        if (!gauss_solve(vectors, r_vectors[i].v)) {\n            return false;\n        }\n        boost::dynamic_bitset<> x = binary_solve_result(vectors, r_vectors[i].v);\n        sp.coefficients.push_back(x);\n        sp.operation_count += x.count() - 1;\n    }\n    return true;\n}\n\n//=============================================================================\n\n/**\n * Return number of summation operations inside cubes for a given index of multiplication vector.\n *\n * @param index: multiplication vector index;\n *\n * @return list of operation count for each cube.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvector<int>\nCube_Product_Checker<N, D, NM, NMH>::\nsum_operations_cube(int index)\n{\n    vector<int> result;\n    if (dimension == 2) {\n        int i, j;\n        j = index % m_length + 1;\n        i = index / m_length + 1;\n        result.push_back(popcount(i));\n        result.push_back(popcount(j));\n    } else if (dimension == 3) {\n        int i, j, k;\n        k = index % m_length + 1;\n        index /= m_length;\n        j = index % m_length + 1;\n        i = index / m_length + 1;\n        result.push_back(popcount(i));\n        result.push_back(popcount(j));\n        result.push_back(popcount(k));\n    }\n    return result;\n}\n\n//=============================================================================\n\n/**\n * Output solution properties to a file in readable text form.\n *\n * @param sp: solution properties object;\n * @param filename: filename.\n */\ntemplate <int N, int D, size_t NM, size_t NMH>\nvoid\nCube_Product_Checker<N, D, NM, NMH>::\nsave_solution_properties(const Solution_Properties& sp, const char* filename)\n{\n    ofstream out(filename);\n    //----- header\n    out << \"Strassen solution for \";\n    for (int i = 0; i < dimension-1; ++i) {\n        out << length << \"\u00d7\";\n    }\n    out << length << \" cube product with \" << f_count << \" multiplications.\" << endl << endl;\n    //----- multiplication vectors numbers\n    out << \"Multiplication numbers: [ \";\n    for (auto i: sp.multiplication_vectors) {\n        out << i << \" \";\n    }\n    out << \"]\" << endl;\n    //----- multiplications\n    int c = 1;\n    int m_summations = 0;\n    for (auto i = sp.multiplication_vectors.begin(); i != sp.multiplication_vectors.end(); ++i, ++c) {\n        out << \"M\" << c << \" = \";\n        vector<int> ops = sum_operations_cube(*i);\n        m_summations += accumulate(ops.begin(), ops.end(), -ops.size());\n        vector<string> sm, smc;\n        set<string> sa, sb, sc;\n        Multiplication_Vector& mv = m_vectors[*i].v;\n        if (dimension == 2) {\n            for (size_t j = 0; j < mv.size(); ++j) {\n                if (mv[j]) {\n                    int ai, aj, bi, bj;\n                    decode_indices_from_index(j, ai, aj, bi, bj);\n                    sm.push_back(\"A\" + to_string(ai+1) + to_string(aj+1) +\n                                 \"B\" + to_string(bi+1) + to_string(bj+1));\n                    sa.insert(\"A\" + to_string(ai+1) + to_string(aj+1));\n                    sb.insert(\"B\" + to_string(bi+1) + to_string(bj+1));\n                }\n            }\n            out << \"(\" << boost::algorithm::join(sa, \" + \") + \")\u00d7\";\n            out << \"(\" << boost::algorithm::join(sb, \" + \") + \")\";\n        } else if (dimension == 3) {\n            // TODO\n        }\n        out << \" = \";\n        out << boost::algorithm::join(sm, \" + \") << endl;\n    }\n    //----- result elements\n    int r_summations = 0;\n    for (int i = 0; i < element_count; ++i) {\n        vector<string> sr;\n        boost::dynamic_bitset<> x = sp.coefficients[i];\n        r_summations += x.count() - 1;\n        if (dimension == 2) {\n            out << \"C\" << i/length+1 << i%length+1 << \" = \";\n        } else if (dimension == 3) {\n            // TODO\n        }\n        for (boost::dynamic_bitset<>::size_type j = 0; j < x.size(); ++j) {\n            if (x.test(j)) {\n                sr.push_back(\"M\" + to_string(j+1));\n            }\n        }\n        out << boost::algorithm::join(sr, \" + \") << endl;\n    }\n    //----- summation count\n    out << \"Summation count for multiplications = \" << m_summations << endl;\n    out << \"Summation count for result elements = \" << r_summations << endl;\n    out << \"Total number of summations used = \" << sp.operation_count << endl;\n    //----- end\n    out.close();\n}\n\n//=============================================================================\n\n#endif // MMCHECKER_HPP_INCLUDED\n", "meta": {"hexsha": "22662c57ebb23b9c1468cbede9265e1ebb206c9b", "size": 50739, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpchecker.hpp", "max_stars_repo_name": "nasedil/checkspanfast", "max_stars_repo_head_hexsha": "f274660211d9b24e64d7632552cad81795c20cd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpchecker.hpp", "max_issues_repo_name": "nasedil/checkspanfast", "max_issues_repo_head_hexsha": "f274660211d9b24e64d7632552cad81795c20cd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpchecker.hpp", "max_forks_repo_name": "nasedil/checkspanfast", "max_forks_repo_head_hexsha": "f274660211d9b24e64d7632552cad81795c20cd1", "max_forks_repo_licenses": ["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.7913533835, "max_line_length": 150, "alphanum_fraction": 0.5495181222, "num_tokens": 12186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5183664909859077}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   tstExponentialDistribution.cpp\n//! \\author Alex Robinson\n//! \\brief  Histogram distribution unit tests.\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <iostream>\n#include <limits>\n\n// Boost Includes\n#include <boost/units/systems/si.hpp>\n#include <boost/units/systems/cgs.hpp>\n#include <boost/units/io.hpp>\n\n// Trilinos Includes\n#include <Teuchos_UnitTestHarness.hpp>\n#include <Teuchos_RCP.hpp>\n#include <Teuchos_ParameterList.hpp>\n#include <Teuchos_XMLParameterListCoreHelpers.hpp>\n#include <Teuchos_VerboseObject.hpp>\n\n// FRENSIE Includes\n#include \"Utility_UnitTestHarnessExtensions.hpp\"\n#include \"Utility_OneDDistribution.hpp\"\n#include \"Utility_ExponentialDistribution.hpp\"\n#include \"Utility_RandomNumberGenerator.hpp\"\n#include \"Utility_PhysicalConstants.hpp\"\n#include \"Utility_UnitTraits.hpp\"\n#include \"Utility_QuantityTraits.hpp\"\n#include \"Utility_ElectronVoltUnit.hpp\"\n\nusing boost::units::quantity;\nusing namespace Utility::Units;\nnamespace si = boost::units::si;\nnamespace cgs = boost::units::cgs;\n\n//---------------------------------------------------------------------------//\n// Testing Variables\n//---------------------------------------------------------------------------//\n\nTeuchos::RCP<Teuchos::ParameterList> test_dists_list;\n\nTeuchos::RCP<Utility::OneDDistribution> distribution( \n\t\t\t     new Utility::ExponentialDistribution( 2.0, 3.0 ) );\nTeuchos::RCP<Utility::UnitAwareOneDDistribution<cgs::length,si::amount> > unit_aware_distribution( new Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>( 2.0*si::mole, 300.0/si::meter, 0.0*si::meter ) );\n\n//---------------------------------------------------------------------------//\n// Tests.\n//---------------------------------------------------------------------------//\n// Check that the distribution can be evaluated\nTEUCHOS_UNIT_TEST( ExponentialDistribution, evaluate )\n{\n  TEST_EQUALITY_CONST( distribution->evaluate( -1.0 ), 0.0 );\n  TEST_EQUALITY_CONST( distribution->evaluate( 0.0 ), 2.0 );\n  TEST_FLOATING_EQUALITY(distribution->evaluate( 1.0 ), 2.0*exp(-3.0), 1e-12);\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be evaluated\nTEUCHOS_UNIT_TEST( UnitAwareExponentialDistribution, evaluate )\n{\n  TEST_EQUALITY_CONST( unit_aware_distribution->evaluate(-1.0*cgs::centimeter),\n\t\t       0.0*si::mole );\n  TEST_EQUALITY_CONST( unit_aware_distribution->evaluate( 0.0*cgs::centimeter),\n\t\t       2.0*si::mole );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t       unit_aware_distribution->evaluate( 1.0*cgs::centimeter),\n\t\t       2.0*exp(-3.0)*si::mole,\n\t\t       1e-12 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the PDF can be evaluated\nTEUCHOS_UNIT_TEST( ExponentialDistribution, evaluatePDF )\n{\n  TEST_EQUALITY_CONST( distribution->evaluatePDF( -1.0 ), 0.0 );\n  TEST_EQUALITY_CONST( distribution->evaluatePDF( 0.0 ), 3.0 );\n  TEST_FLOATING_EQUALITY(distribution->evaluatePDF(1.0), 3.0*exp(-3.0), 1e-12);\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware PDF can be evaluated\nTEUCHOS_UNIT_TEST( UnitAwareExponentialDistribution, evaluatePDF )\n{\n  TEST_EQUALITY_CONST( \n\t\t  unit_aware_distribution->evaluatePDF( -1.0*cgs::centimeter ),\n\t\t  0.0/cgs::centimeter );\n  TEST_EQUALITY_CONST( \n\t\t   unit_aware_distribution->evaluatePDF( 0.0*cgs::centimeter ),\n\t\t   3.0/cgs::centimeter );\n  UTILITY_TEST_FLOATING_EQUALITY(\n\t\t   unit_aware_distribution->evaluatePDF( 1.0*cgs::centimeter ),\n\t\t   3.0*exp(-3.0)/cgs::centimeter,\n\t\t   1e-12 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled\nTEUCHOS_UNIT_TEST( ExponentialDistribution, sample_basic_static )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n  \n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  double sample = Utility::ExponentialDistribution::sample( 3.0 );\n  TEST_EQUALITY_CONST( sample, 0.0 );\n\n  sample = Utility::ExponentialDistribution::sample( 3.0 );\n  TEST_FLOATING_EQUALITY( sample, 11.5131919974469596, 1e-15 );\n  \n  sample = Utility::ExponentialDistribution::sample( 3.0 );\n  TEST_FLOATING_EQUALITY( sample, -log(0.5)/3.0, 1e-12 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled\nTEUCHOS_UNIT_TEST( UnitAwareExponentialDistribution, sample_basic_static )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n  \n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  quantity<cgs::length> sample = \n    Utility::UnitAwareExponentialDistribution<cgs::length>::sample( 3.0/cgs::centimeter );\n  TEST_EQUALITY_CONST( sample, 0.0*cgs::centimeter );\n\n  sample = Utility::UnitAwareExponentialDistribution<cgs::length>::sample( 3.0/cgs::centimeter );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  11.5131919974469596*cgs::centimeter, \n\t\t\t\t  1e-15 );\n  \n  sample = Utility::UnitAwareExponentialDistribution<cgs::length>::sample( 3.0/cgs::centimeter );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  -log(0.5)/3.0*cgs::centimeter, \n\t\t\t\t  1e-12 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled\nTEUCHOS_UNIT_TEST( ExponentialDistribution, sample_static )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n  \n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  double inf = std::numeric_limits<double>::infinity();\n\n  double sample = Utility::ExponentialDistribution::sample( 3.0, 0.0, inf );\n  TEST_EQUALITY_CONST( sample, 0.0 );\n\n  sample = Utility::ExponentialDistribution::sample( 3.0, 0.0, inf );\n  TEST_FLOATING_EQUALITY( sample, 11.5131919974469596, 1e-15 );\n  \n  sample = Utility::ExponentialDistribution::sample( 3.0, 0.0, inf );\n  TEST_FLOATING_EQUALITY( sample, -log(0.5)/3.0, 1e-12 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled\nTEUCHOS_UNIT_TEST( UnitAwareExponentialDistribution, sample_static )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n  \n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  quantity<cgs::length> inf = \n    Utility::QuantityTraits<quantity<cgs::length> >::inf();\n\n  quantity<cgs::length> sample = \n    Utility::UnitAwareExponentialDistribution<cgs::length>::sample( \n\t\t\t       3.0/cgs::centimeter, 0.0*cgs::centimeter, inf );\n  TEST_EQUALITY_CONST( sample, 0.0*cgs::centimeter );\n\n  sample = Utility::UnitAwareExponentialDistribution<cgs::length>::sample( \n\t\t\t       3.0/cgs::centimeter, 0.0*cgs::centimeter, inf );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  11.5131919974469596*cgs::centimeter,\n\t\t\t\t  1e-15 );\n  \n  sample = Utility::UnitAwareExponentialDistribution<cgs::length>::sample( \n\t\t\t       3.0/cgs::centimeter, 0.0*cgs::centimeter, inf );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  -log(0.5)/3.0*cgs::centimeter, \n\t\t\t\t  1e-12 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();  \n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled\nTEUCHOS_UNIT_TEST( ExponentialDistribution, sample )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n  \n  double sample = distribution->sample();\n  TEST_EQUALITY_CONST( sample, 0.0 );\n  \n  sample = distribution->sample(); \n  TEST_FLOATING_EQUALITY( sample, 11.5131919974469596, 1e-15 );\n\n  sample = distribution->sample(); \n  TEST_FLOATING_EQUALITY( sample, -log(0.5)/3.0, 1e-12 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled\nTEUCHOS_UNIT_TEST( UnitAwareExponentialDistribution, sample )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n  \n  quantity<cgs::length> sample = unit_aware_distribution->sample();\n  TEST_EQUALITY_CONST( sample, 0.0*cgs::centimeter );\n  \n  sample = unit_aware_distribution->sample(); \n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  11.5131919974469596*cgs::centimeter, \n\t\t\t\t  1e-15 );\n\n  sample = unit_aware_distribution->sample(); \n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  -log(0.5)/3.0*cgs::centimeter, \n\t\t\t\t  1e-12 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled\nTEUCHOS_UNIT_TEST( ExponentialDistribution, sampleAndRecordTrials )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n  \n  unsigned trials = 0;\n  \n  double sample = distribution->sampleAndRecordTrials( trials );\n  TEST_EQUALITY_CONST( sample, 0.0 );\n  TEST_EQUALITY_CONST( trials, 1 );\n\n  sample = distribution->sampleAndRecordTrials( trials ); \n  UTILITY_TEST_FLOATING_EQUALITY( sample, 11.5131919974469596, 1e-15 );\n  TEST_EQUALITY_CONST( trials, 2 );\n\n  sample = distribution->sampleAndRecordTrials( trials ); \n  TEST_FLOATING_EQUALITY( sample, -log(0.5)/3.0, 1e-12 );\n  TEST_EQUALITY_CONST( trials, 3 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled\nTEUCHOS_UNIT_TEST( UnitAwareExponentialDistribution, sampleAndRecordTrials )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n  \n  unsigned trials = 0;\n  \n  quantity<cgs::length> sample = \n    unit_aware_distribution->sampleAndRecordTrials( trials );\n  TEST_EQUALITY_CONST( sample, 0.0*cgs::centimeter );\n  TEST_EQUALITY_CONST( trials, 1 );\n\n  sample = unit_aware_distribution->sampleAndRecordTrials( trials ); \n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  11.5131919974469596*cgs::centimeter, \n\t\t\t\t  1e-15 );\n  TEST_EQUALITY_CONST( trials, 2 );\n\n  sample = unit_aware_distribution->sampleAndRecordTrials( trials ); \n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  -log(0.5)/3.0*cgs::centimeter, \n\t\t\t\t  1e-12 );\n  TEST_EQUALITY_CONST( trials, 3 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the distribution independent variable can be\n// returned\nTEUCHOS_UNIT_TEST( ExponentialDistribution, getUpperBoundOfIndepVar )\n{\n  TEST_EQUALITY_CONST( distribution->getUpperBoundOfIndepVar(),\n\t\t       std::numeric_limits<double>::infinity() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the unit-aware distribution independent \n// variable can be returned\nTEUCHOS_UNIT_TEST( UnitAwareExponentialDistribution, getUpperBoundOfIndepVar )\n{\n  TEST_EQUALITY_CONST( unit_aware_distribution->getUpperBoundOfIndepVar(),\n\t\t       Utility::QuantityTraits<quantity<cgs::length> >::inf());\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the distribution independent variable can be\n// returned\nTEUCHOS_UNIT_TEST( ExponentialDistribution, getLowerBoundOfIndepVar )\n{\n  TEST_EQUALITY_CONST( distribution->getLowerBoundOfIndepVar(), 0.0 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the unit-aware distribution independent \n// variable can be returned\nTEUCHOS_UNIT_TEST( UnitAwareExponentialDistribution, getLowerBoundOfIndepVar )\n{\n  TEST_EQUALITY_CONST( unit_aware_distribution->getLowerBoundOfIndepVar(), \n\t\t       Utility::QuantityTraits<quantity<cgs::length> >::zero());\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution type can be returned\nTEUCHOS_UNIT_TEST( ExponentialDistribution, getDistributionType )\n{\n  TEST_EQUALITY_CONST( distribution->getDistributionType(),\n\t\t       Utility::EXPONENTIAL_DISTRIBUTION );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution type can be returned\nTEUCHOS_UNIT_TEST( UnitAwareExponentialDistribution, getDistributionType )\n{\n  TEST_EQUALITY_CONST( unit_aware_distribution->getDistributionType(),\n\t\t       Utility::EXPONENTIAL_DISTRIBUTION );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the distribution is tabular\nTEUCHOS_UNIT_TEST( ExponentialDistribution, isTabular )\n{\n  TEST_ASSERT( !distribution->isTabular() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the unit-aware distribution is tabular\nTEUCHOS_UNIT_TEST( UnitAwareExponentialDistribution, isTabular )\n{\n  TEST_ASSERT( !unit_aware_distribution->isTabular() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the distribution is continuous\nTEUCHOS_UNIT_TEST( ExponentialDistribution, isContinuous )\n{\n  TEST_ASSERT( distribution->isContinuous() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the unit-aware distribution is continuous\nTEUCHOS_UNIT_TEST( UnitAwareExponentialDistribution, isContinuous )\n{\n  TEST_ASSERT( unit_aware_distribution->isContinuous() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be written to an xml file\nTEUCHOS_UNIT_TEST( ExponentialDistribution, toParameterList )\n{\n  Teuchos::RCP<Utility::ExponentialDistribution> true_distribution =\n   Teuchos::rcp_dynamic_cast<Utility::ExponentialDistribution>( distribution );\n  \n  Teuchos::ParameterList parameter_list;\n  \n  parameter_list.set<Utility::ExponentialDistribution>( \"test distribution\", \n\t\t\t\t\t\t     *true_distribution );\n\n  Teuchos::writeParameterListToXmlFile( parameter_list,\n\t\t\t\t\t\"exponential_dist_test_list.xml\" );\n  \n  Teuchos::RCP<Teuchos::ParameterList> read_parameter_list = \n    Teuchos::getParametersFromXmlFile( \"exponential_dist_test_list.xml\" );\n  \n  TEST_EQUALITY( parameter_list, *read_parameter_list );\n\n  Teuchos::RCP<Utility::ExponentialDistribution> \n    copy_distribution( new Utility::ExponentialDistribution );\n\n  *copy_distribution = \n    read_parameter_list->get<Utility::ExponentialDistribution>(\n\t\t\t\t\t\t\t  \"test distribution\");\n\n  TEST_EQUALITY( *copy_distribution, *true_distribution );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be written to an xml file\nTEUCHOS_UNIT_TEST( UnitAwareExponentialDistribution, toParameterList )\n{\n  typedef Utility::UnitAwareExponentialDistribution<cgs::length,si::amount> \n    UnitAwareExponentialDistribution;\n  \n  Teuchos::RCP<UnitAwareExponentialDistribution> true_distribution =\n   Teuchos::rcp_dynamic_cast<UnitAwareExponentialDistribution>( \n\t\t\t\t\t\t     unit_aware_distribution );\n  \n  Teuchos::ParameterList parameter_list;\n  \n  parameter_list.set<UnitAwareExponentialDistribution>( \"test distribution\", \n\t\t\t\t\t\t\t*true_distribution );\n\n  Teuchos::writeParameterListToXmlFile( parameter_list,\n\t\t\t\t\t\"unit_aware_exponential_dist_test_list.xml\" );\n  \n  Teuchos::RCP<Teuchos::ParameterList> read_parameter_list = \n    Teuchos::getParametersFromXmlFile( \"unit_aware_exponential_dist_test_list.xml\" );\n  \n  TEST_EQUALITY( parameter_list, *read_parameter_list );\n\n  Teuchos::RCP<UnitAwareExponentialDistribution> \n    copy_distribution( new UnitAwareExponentialDistribution );\n\n  *copy_distribution = \n    read_parameter_list->get<UnitAwareExponentialDistribution>(\n\t\t\t\t\t\t\t  \"test distribution\");\n\n  TEST_EQUALITY( *copy_distribution, *true_distribution );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be read from an xml file\nTEUCHOS_UNIT_TEST( ExponentialDistribution, fromParameterList )\n{\n  Utility::ExponentialDistribution read_distribution = \n    test_dists_list->get<Utility::ExponentialDistribution>( \"Exponential Distribution A\" );\n\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0 ), 1.0 );\n  TEST_FLOATING_EQUALITY( read_distribution.evaluate( 1.0 ), \n\t\t\t  exp( -3.0 ), \n\t\t\t  1e-15 );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n\t\t       std::numeric_limits<double>::infinity() );\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(), 0.0 );\n  \n  read_distribution = \n    test_dists_list->get<Utility::ExponentialDistribution>( \"Exponential Distribution B\" );\n\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0 ),\n\t\t       Utility::PhysicalConstants::pi );\n  TEST_FLOATING_EQUALITY( read_distribution.evaluate( 1.0 ),\n\t\t\t  Utility::PhysicalConstants::pi*exp( -3.0 ),\n\t\t\t  1e-15 );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n\t\t       std::numeric_limits<double>::infinity() );\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(), 0.0 );\n  \n  read_distribution = \n    test_dists_list->get<Utility::ExponentialDistribution>( \"Exponential Distribution C\" );\n\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0 ), 0.0 );\n  TEST_FLOATING_EQUALITY( read_distribution.evaluate( 1.0 ),\n\t\t\t  Utility::PhysicalConstants::pi*exp( -3.0 ),\n\t\t\t  1e-15 );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n\t\t       std::numeric_limits<double>::infinity() );\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(), 1.0 );\n\n  read_distribution = \n    test_dists_list->get<Utility::ExponentialDistribution>( \"Exponential Distribution D\" );\n\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0 ), 0.0 );\n  TEST_FLOATING_EQUALITY( read_distribution.evaluate( 1.0 ),\n\t\t\t  Utility::PhysicalConstants::pi*exp( -3.0 ),\n\t\t\t  1e-15 );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(), 2.0 );\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(), 1.0 );\n\n  read_distribution = \n    test_dists_list->get<Utility::ExponentialDistribution>( \"Exponential Distribution E\" );\n\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0 ), 0.0 );\n  TEST_FLOATING_EQUALITY( read_distribution.evaluate( 1.0 ),\n\t\t\t  Utility::PhysicalConstants::pi*exp( -3.0 ),\n\t\t\t  1e-15 );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n\t\t       std::numeric_limits<double>::infinity() );\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(), 1.0 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be read from an xml file\nTEUCHOS_UNIT_TEST( UnitAwareExponentialDistribution, fromParameterList )\n{\n  typedef Utility::UnitAwareExponentialDistribution<cgs::length,si::amount> \n    UnitAwareExponentialDistribution;\n  \n  UnitAwareExponentialDistribution read_distribution = \n    test_dists_list->get<UnitAwareExponentialDistribution>( \"Unit-Aware Exponential Distribution A\" );\n\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0*cgs::centimeter ), \n  \t\t       1.0*si::mole );\n  UTILITY_TEST_FLOATING_EQUALITY( \n  \t\t\t     read_distribution.evaluate( 1.0*cgs::centimeter ),\n  \t\t\t     exp( -3.0 )*si::mole, \n  \t\t\t     1e-15 );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n  \t\t       Utility::QuantityTraits<quantity<cgs::length> >::inf());\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(), \n  \t\t       0.0*cgs::centimeter );\n  \n  read_distribution = \n    test_dists_list->get<UnitAwareExponentialDistribution>( \n\t\t\t\t     \"Unit-Aware Exponential Distribution B\" );\n\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0*cgs::centimeter ),\n  \t\t       Utility::PhysicalConstants::pi*si::mole );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t  read_distribution.evaluate( 1.0*cgs::centimeter ),\n  \t\t\t  Utility::PhysicalConstants::pi*exp( -3.0 )*si::mole,\n  \t\t\t  1e-15 );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n  \t\t       Utility::QuantityTraits<quantity<cgs::length> >::inf());\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(), \n\t\t       0.0*cgs::centimeter );\n  \n  read_distribution = \n    test_dists_list->get<UnitAwareExponentialDistribution>( \n\t\t\t\t     \"Unit-Aware Exponential Distribution C\" );\n\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0*cgs::centimeter ), \n\t\t       0.0*si::mole );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   read_distribution.evaluate( 1.0*cgs::centimeter ),\n\t\t\t   Utility::PhysicalConstants::pi*exp( -3.0 )*si::mole,\n\t\t\t   1e-15 );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n  \t\t       Utility::QuantityTraits<quantity<cgs::length> >::inf());\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(), \n\t\t       1.0*cgs::centimeter );\n\n  read_distribution = \n    test_dists_list->get<UnitAwareExponentialDistribution>( \n\t\t\t\t     \"Unit-Aware Exponential Distribution D\" );\n\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0*cgs::centimeter ), \n\t\t       0.0*si::mole );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   read_distribution.evaluate( 1.0*cgs::centimeter ),\n\t\t\t   Utility::PhysicalConstants::pi*exp( -3.0 )*si::mole,\n\t\t\t   1e-15 );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(), \n\t\t       2.0*cgs::centimeter );\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(), \n\t\t       1.0*cgs::centimeter );\n\n  read_distribution = \n    test_dists_list->get<UnitAwareExponentialDistribution>( \n\t\t\t\t     \"Unit-Aware Exponential Distribution E\" );\n\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0*cgs::centimeter ), \n\t\t       0.0*si::mole );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   read_distribution.evaluate( 1.0*cgs::centimeter ),\n\t\t\t   Utility::PhysicalConstants::pi*exp( -3.0 )*si::mole,\n\t\t\t   1e-15 );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n  \t\t       Utility::QuantityTraits<quantity<cgs::length> >::inf());\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(), \n\t\t       1.0*cgs::centimeter );\n}\n\n//---------------------------------------------------------------------------//\n// Check that distributions can be scaled\nTEUCHOS_UNIT_TEST_TEMPLATE_4_DECL( UnitAwareExponentialDistribution,\n\t\t\t\t   explicit_conversion,\n\t\t\t\t   IndepUnitA,\n\t\t\t\t   DepUnitA,\n\t\t\t\t   IndepUnitB,\n\t\t\t\t   DepUnitB )\n{\n  typedef typename Utility::UnitTraits<IndepUnitA>::template GetQuantityType<double>::type IndepQuantityA;\n  typedef typename Utility::UnitTraits<typename Utility::UnitTraits<IndepUnitA>::InverseUnit>::template GetQuantityType<double>::type InverseIndepQuantityA;\n  \n  typedef typename Utility::UnitTraits<IndepUnitB>::template GetQuantityType<double>::type IndepQuantityB;\n  typedef typename Utility::UnitTraits<typename Utility::UnitTraits<IndepUnitB>::InverseUnit>::template GetQuantityType<double>::type InverseIndepQuantityB;\n  \n  typedef typename Utility::UnitTraits<DepUnitA>::template GetQuantityType<double>::type DepQuantityA;\n  typedef typename Utility::UnitTraits<DepUnitB>::template GetQuantityType<double>::type DepQuantityB;\n\n  // Copy from unitless distribution to distribution type A (static method)\n  Utility::UnitAwareExponentialDistribution<IndepUnitA,DepUnitA>\n    unit_aware_dist_a_copy = Utility::UnitAwareExponentialDistribution<IndepUnitA,DepUnitA>::fromUnitlessDistribution( *Teuchos::rcp_dynamic_cast<Utility::ExponentialDistribution>( distribution ) );\n\n  // Copy from distribution type A to distribution type B (explicit cast)\n  Utility::UnitAwareExponentialDistribution<IndepUnitB,DepUnitB>\n    unit_aware_dist_b_copy( unit_aware_dist_a_copy );\n\n  IndepQuantityA indep_quantity_a = \n    Utility::QuantityTraits<IndepQuantityA>::initializeQuantity( 0.0 );\n  InverseIndepQuantityA inv_indep_quantity_a = \n    Utility::QuantityTraits<InverseIndepQuantityA>::initializeQuantity( 3.0 );\n  DepQuantityA dep_quantity_a = \n    Utility::QuantityTraits<DepQuantityA>::initializeQuantity( 2.0 );\n\n  IndepQuantityB indep_quantity_b( indep_quantity_a );\n  InverseIndepQuantityB inv_indep_quantity_b( inv_indep_quantity_a );\n  DepQuantityB dep_quantity_b( dep_quantity_a );\n\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   unit_aware_dist_a_copy.evaluate( indep_quantity_a ),\n\t\t\t   dep_quantity_a,\n\t\t\t   1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\tunit_aware_dist_a_copy.evaluatePDF( indep_quantity_a ),\n\t\t\tinv_indep_quantity_a,\n\t\t\t1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   unit_aware_dist_b_copy.evaluate( indep_quantity_b ),\n\t\t\t   dep_quantity_b,\n\t\t\t   1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\tunit_aware_dist_b_copy.evaluatePDF( indep_quantity_b ),\n\t\t\tinv_indep_quantity_b,\n\t\t\t1e-15 );\n\n  Utility::setQuantity( indep_quantity_a, 1.0 );\n  Utility::setQuantity( inv_indep_quantity_a, 3.0*exp(-3.0) );\n  Utility::setQuantity( dep_quantity_a, 2.0*exp(-3.0) );\n\n  indep_quantity_b = IndepQuantityB( indep_quantity_a );\n  inv_indep_quantity_b = InverseIndepQuantityB( inv_indep_quantity_a );\n  dep_quantity_b = DepQuantityB( dep_quantity_a );\n\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   unit_aware_dist_a_copy.evaluate( indep_quantity_a ),\n\t\t\t   dep_quantity_a,\n\t\t\t   1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\tunit_aware_dist_a_copy.evaluatePDF( indep_quantity_a ),\n\t\t\tinv_indep_quantity_a,\n\t\t\t1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   unit_aware_dist_b_copy.evaluate( indep_quantity_b ),\n\t\t\t   dep_quantity_b,\n\t\t\t   1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\tunit_aware_dist_b_copy.evaluatePDF( indep_quantity_b ),\n\t\t\tinv_indep_quantity_b,\n\t\t\t1e-15 );\n}\n\ntypedef si::energy si_energy;\ntypedef cgs::energy cgs_energy;\ntypedef si::amount si_amount;\ntypedef si::length si_length;\ntypedef cgs::length cgs_length;\ntypedef si::mass si_mass;\ntypedef cgs::mass cgs_mass;\ntypedef si::dimensionless si_dimensionless;\ntypedef cgs::dimensionless cgs_dimensionless;\n\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_length,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_length );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_length,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_length );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_mass,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_mass );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_mass,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_mass );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_dimensionless,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_dimensionless );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_dimensionless,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_dimensionless );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      void,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      void );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      void,\n\t\t\t\t      si_energy,\n\t\t\t\t      void );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareExponentialDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      void,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      void,\n\t\t\t\t      KiloElectronVolt );\n\n//---------------------------------------------------------------------------//\n// Custom main function\n//---------------------------------------------------------------------------//\nint main( int argc, char** argv )\n{\n  std::string test_dists_xml_file;\n  \n  Teuchos::CommandLineProcessor& clp = Teuchos::UnitTestRepository::getCLP();\n  \n  clp.setOption( \"test_dists_xml_file\",\n\t\t &test_dists_xml_file,\n\t\t \"Test distributions xml file name\" );\n\n  const Teuchos::RCP<Teuchos::FancyOStream> out = \n    Teuchos::VerboseObjectBase::getDefaultOStream();\n\n  Teuchos::CommandLineProcessor::EParseCommandLineReturn parse_return = \n    clp.parse(argc,argv);\n\n  if ( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL ) {\n    *out << \"\\nEnd Result: TEST FAILED\" << std::endl;\n    return parse_return;\n  }\n\n  TEUCHOS_ADD_TYPE_CONVERTER( Utility::ExponentialDistribution );\n  typedef Utility::UnitAwareExponentialDistribution<cgs::length,si::amount> UnitAwareExponentialDistribution;\n  TEUCHOS_ADD_TYPE_CONVERTER( UnitAwareExponentialDistribution );\n  \n  test_dists_list = Teuchos::getParametersFromXmlFile( test_dists_xml_file );\n  \n  // Initialize the random number generator\n  Utility::RandomNumberGenerator::createStreams();\n  \n  // Run the unit tests\n  Teuchos::GlobalMPISession mpiSession( &argc, &argv );\n\n  const bool success = Teuchos::UnitTestRepository::runUnitTests(*out);\n\n  if (success)\n    *out << \"\\nEnd Result: TEST PASSED\" << std::endl;\n  else\n    *out << \"\\nEnd Result: TEST FAILED\" << std::endl;\n\n  clp.printFinalTimerSummary(out.ptr());\n\n  return (success ? 0 : 1);\n}\n\n//---------------------------------------------------------------------------//\n// end tstExponentialDistribution.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "6b4fa3d936143ea9a9eb23daff644a7b13f4a0d5", "size": 33119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/distribution/test/tstExponentialDistribution.cpp", "max_stars_repo_name": "lkersting/SCR-2123", "max_stars_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "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": "packages/utility/distribution/test/tstExponentialDistribution.cpp", "max_issues_repo_name": "lkersting/SCR-2123", "max_issues_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/utility/distribution/test/tstExponentialDistribution.cpp", "max_forks_repo_name": "lkersting/SCR-2123", "max_forks_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "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.3803611738, "max_line_length": 219, "alphanum_fraction": 0.6702798998, "num_tokens": 7959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5183664890484473}}
{"text": "#include \"catch.hpp\"\n\n#include <blitzml/base/common.h>\n#include <blitzml/base/vector_util.h>\n#include <vector>\n#include <algorithm>\n\nusing std::vector;\n\nusing namespace BlitzML;\n\nTEST_CASE( \"test_crude_shuffle\", \"[vector_util]\" ) {\n  vector<int> v(100, 0);\n  for (size_t i = 0; i < v.size(); ++i) {\n    v[i] = i;\n  }\n  crude_shuffle(v, 0, v.size());\n  bool is_sorted = true;\n  for (size_t i = 1; i < v.size(); ++i) {\n    if (v[i] < v[i -1]) {\n      is_sorted = false;\n      break;\n    }\n  }\n  REQUIRE( is_sorted == false );\n}\n\nTEST_CASE( \"indirect_sort_indices\", \"[vector_util]\" ) {\n  vector<index_t> indices;\n  indices.push_back(1);\n  indices.push_back(0);\n  indices.push_back(3);\n  indices.push_back(2);\n  vector<value_t> values;\n  values.push_back(5.0);\n  values.push_back(1.1);\n  values.push_back(1.3);\n  values.push_back(1.4);\n  indirect_sort_indices(indices, values);\n  REQUIRE( indices[0] == 1 );\n  REQUIRE( indices[1] == 2 );\n  REQUIRE( indices[2] == 3 );\n  REQUIRE( indices[3] == 0 );\n}\n\nTEST_CASE( \"scale_vector\", \"[vector_util]\" ) {\n  vector<double> v;\n  v.push_back(2.0);\n  v.push_back(-1.0);\n  scale_vector(v, -2.0);\n  REQUIRE( v[0] == Approx(-4.0) );\n  REQUIRE( v[1] == Approx(2.0) );\n  v.push_back(3.5);\n  scale_vector(v, 0.5);\n  REQUIRE( v[0] == Approx(-2.0) );\n  REQUIRE( v[1] == Approx(1.0) );\n  REQUIRE( v[2] == Approx(1.75) );\n\n  add_scalar_to_vector(v, -0.5);\n  REQUIRE( v[0] == Approx(-2.5) );\n  REQUIRE( v[1] == Approx(0.5) );\n  REQUIRE( v[2] == Approx(1.25) );\n}\n\nTEST_CASE( \"is_vector_const\", \"[vector_util]\" ) {\n  vector<double> v(100, -25.0);\n  REQUIRE( is_vector_const(v) == true );\n  v[0] = 25.;\n  REQUIRE( is_vector_const(v) == false );\n  v[0] = -25.;\n  REQUIRE( is_vector_const(v) == true );\n  v[99] = 25.;\n  REQUIRE( is_vector_const(v) == false );\n}\n\n", "meta": {"hexsha": "fc1f4904561aad462d6e915affe11f6751bed907", "size": 1783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cpp/test_vector_util.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": "test/cpp/test_vector_util.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": "test/cpp/test_vector_util.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.4605263158, "max_line_length": 55, "alphanum_fraction": 0.6012338755, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.5183664833238275}}
{"text": "// Copyright (C) 2018  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n\r\n#include <dlib/optimization.h>\r\n#include <dlib/global_optimization.h>\r\n#include <sstream>\r\n#include <string>\r\n#include <cstdlib>\r\n#include <ctime>\r\n#include <vector>\r\n\r\n#include \"tester.h\"\r\n\r\n\r\nnamespace  \r\n{\r\n\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n\r\n    logger dlog(\"test.isotonic_regression\");\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    class optimization_tester : public tester\r\n    {\r\n    public:\r\n        optimization_tester (\r\n        ) :\r\n            tester (\"test_isotonic_regression\",\r\n                    \"Runs tests on the isotonic_regression object.\")\r\n        {}\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            dlib::rand rnd;\r\n\r\n            for (int round = 0; round < 100; ++round)\r\n            {\r\n                print_spinner();\r\n                std::vector<double> vect;\r\n                for (int i = 0; i < 5; ++i)\r\n                    vect.push_back(put_in_range(-1,1,rnd.get_random_gaussian()));\r\n\r\n\r\n                auto f = [&](const matrix<double,0,1>& x)\r\n                {\r\n                    double dist = 0;\r\n                    double sum = 0;\r\n                    for (long i = 0; i < x.size(); ++i)\r\n                    {\r\n                        sum += x(i);\r\n                        dist += (sum-vect[i])*(sum-vect[i]);\r\n                    }\r\n                    return dist;\r\n                };\r\n\r\n                auto objval = [vect](const matrix<double,0,1>& x)\r\n                {\r\n                    return sum(squared(mat(vect)-x));\r\n                };\r\n\r\n                auto is_monotonic = [](const matrix<double,0,1>& x)\r\n                {\r\n                    for (long i = 1; i < x.size(); ++i)\r\n                    {\r\n                        if (x(i-1) > x(i))\r\n                            return false;\r\n                    }\r\n                    return true;\r\n                };\r\n\r\n                matrix<double,0,1> lower(5), upper(5);\r\n                lower = 0;\r\n                lower(0) = -4;\r\n                upper = 4;\r\n                // find the solution with find_min_global() and then check that it matches\r\n                auto result = find_min_global(f, lower, upper, max_function_calls(40));\r\n\r\n                for (long i = 1; i < result.x.size(); ++i)\r\n                    result.x(i) += result.x(i-1);\r\n\r\n                isotonic_regression mr;\r\n                mr(vect);\r\n\r\n                dlog << LINFO << \"err: \"<<  objval(mat(vect)) - objval(result.x);\r\n\r\n                DLIB_CASSERT(is_monotonic(mat(vect)));\r\n                DLIB_CASSERT(is_monotonic(result.x));\r\n                // isotonic_regression should be at least as good as find_min_global().\r\n                DLIB_CASSERT(objval(mat(vect)) - objval(result.x) < 1e-13);\r\n            }\r\n\r\n        }\r\n    } a;\r\n\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "24dd6e98aef50ec7889ce61227a29782423c955a", "size": 3007, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/isotonic_regression.cpp", "max_stars_repo_name": "oms1226/dlib-19.13", "max_stars_repo_head_hexsha": "0bb55d112324edb700a42a3e6baca09c03967754", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dlib/test/isotonic_regression.cpp", "max_issues_repo_name": "oms1226/dlib-19.13", "max_issues_repo_head_hexsha": "0bb55d112324edb700a42a3e6baca09c03967754", "max_issues_repo_licenses": ["MIT"], "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/isotonic_regression.cpp", "max_forks_repo_name": "oms1226/dlib-19.13", "max_forks_repo_head_hexsha": "0bb55d112324edb700a42a3e6baca09c03967754", "max_forks_repo_licenses": ["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.9134615385, "max_line_length": 92, "alphanum_fraction": 0.4183571666, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5183664737242876}}
{"text": "/**\n * \\file path/to/include/file.hpp\n *\n * \\brief Rotate matrix 90 degrees.\n *\n * Inspired by the \\c rot90 MATLAB function.\n * See http://www.mathworks.com/help/techdoc/ref/rot90.html.\n *\n * Copyright (c) 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_ROT90_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_ROT90_HPP\n\n\n//#include <boost/numeric/ublasx/detail/temporary.hpp>\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublas/vector.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 <cstddef>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\nnamespace detail {\n\ntemplate <typename MatrixT>\nstruct rot90_matrix_traits\n{\n//Not all matrix types have this type (e.g., scalar_matrix<>)\n//\ttypedef typename detail::matrix_temporary_traits<MatrixT>::type result_type;\n\ttypedef matrix<typename matrix_traits<MatrixT>::value_type> result_type;\n};\n\ntemplate <typename VectorT>\nstruct rot90_vector_traits\n{\n//Not all vector types have this type (e.g., scalar_vector<>)\n//\ttypedef typename detail::vector_temporary_traits<VectorT>::type result_type;\n\ttypedef vector<typename vector_traits<VectorT>::value_type> result_type;\n};\n\n} // Namespace detail\n\n\n/// Rotate the given vector counterclockwise by (a multiple of) 90 degrees.\ntemplate <typename VectorT>\ntypename detail::rot90_vector_traits<VectorT>::result_type rot90(vector_expression<VectorT> const& v, int k=1)\n{\n\ttypedef typename detail::rot90_vector_traits<VectorT>::result_type result_type;\n\ttypedef typename vector_traits<VectorT>::size_type size_type;\n\n\tsize_type n(ublasx::size(v));\n\n\tresult_type x;\n\n\t// Make sure k \\in {0, 1, 2, 3}\n\tk %= 4;\n\tif (k < 0)\n\t{\n\t\tk += 4;\n\t}\n\n\t// NOTE: uBLAS makes no distinction between row and column vector.\n\t//       So rotations for k=0 and k=1 are considered identical.\n\t//       The same applies for rotations for k=2 and k=3.\n\n\tif (k == 2 || k == 3)\n\t{\n\t\tx.resize(n, false);\n\n\t\tfor (size_type i = 0; i < n; ++i)\n\t\t{\n\t\t\tx(n-i-1) = v()(i);\n\t\t}\n\t}\n\telse\n\t{\n\t\tx = v;\n\t}\n\n\treturn x;\n}\n\n\n/// Rotate the given vector counterclockwise by (a multiple of) 90 degrees.\ntemplate <typename VectorT>\nBOOST_UBLAS_INLINE\nvoid rot90_inplace(vector_container<VectorT>& v, int k=1)\n{\n\tv() = rot90(v, k);\n}\n\n\n/// Rotate the given matrix counterclockwise by (a multiple of) 90 degrees\ntemplate <typename MatrixT>\ntypename detail::rot90_matrix_traits<MatrixT>::result_type rot90(matrix_expression<MatrixT> const& A, int k=1)\n{\n\ttypedef typename detail::rot90_matrix_traits<MatrixT>::result_type result_type;\n\ttypedef typename matrix_traits<MatrixT>::size_type size_type;\n\n\tsize_type nr(ublasx::num_rows(A));\n\tsize_type nc(ublasx::num_columns(A));\n\n\tresult_type X;\n\n\t// Make sure k \\in {0, 1, 2, 3}\n\tk %= 4;\n\tif (k < 0)\n\t{\n\t\tk += 4;\n\t}\n\n\tif (k == 1)\n\t{\n\t\tX.resize(nc, nr, false);\n\n\t\tfor (size_type c = 0; c < nc; ++c)\n\t\t{\n\t\t\trow(X, nc-c-1) = column(A(), c);\n\t\t}\n\t}\n\telse if (k == 2)\n\t{\n\t\tX.resize(nr, nc, false);\n\n\t\tfor (size_type r = 0; r < nr; ++r)\n\t\t{\n\t\t\tfor (size_type c = 0; c < nc; ++c)\n\t\t\t{\n\t\t\t\tX(nr-r-1,nc-c-1) = A()(r,c);\n\t\t\t}\n\t\t}\n\t}\n\telse if (k == 3)\n\t{\n\t\tX.resize(nc, nr, false);\n\n\t\tfor (size_type r = 0; r < nr; ++r)\n\t\t{\n\t\t\tcolumn(X, nr-r-1) = row(A(), r);\n\t\t}\n\t}\n\telse\n\t{\n\t\tX = A;\n\t}\n\n\treturn X;\n}\n\n/// Rotate the given matrix counterclockwise by (a multiple of) 90 degrees\ntemplate <typename MatrixT>\nBOOST_UBLAS_INLINE\nvoid rot90_inplace(matrix_container<MatrixT>& A, int k=1)\n{\n\tA() = rot90(A, k);\n}\n\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_ROT90_HPP\n", "meta": {"hexsha": "47c865eed9c9b0ef6bb16335e8a1f6dcf31cb345", "size": 4047, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/rot90.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/rot90.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/rot90.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": 22.6089385475, "max_line_length": 110, "alphanum_fraction": 0.6963182604, "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5183345246613555}}
{"text": "#define BOOST_TEST_MODULE example\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\n//____________________________________________________________________________//\n\nBOOST_AUTO_TEST_CASE( test )\n{\n    double v1 = 1.111e-10;\n    double v2 = 1.112e-10;\n\n    BOOST_CHECK_CLOSE_FRACTION( v1, v2, 0.0008999 );\n}\n\n//____________________________________________________________________________//\n", "meta": {"hexsha": "f20ef93bfce70908240d7f654c030caa92cc3d30", "size": 437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/test/doc/src/examples/example44.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/test/doc/src/examples/example44.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/test/doc/src/examples/example44.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": 27.3125, "max_line_length": 80, "alphanum_fraction": 0.8100686499, "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5183345111765113}}
{"text": "#ifndef _COMPLEMENTARY_FILTER_HPP_\n#define _COMPLEMENTARY_FILTER_HPP_\n\n#include <cmath>\n#include <stdio.h>\n#include <vector>\n#include <algorithm>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <boost/math/special_functions.hpp>\n\n\n// #define LOCAL_MAG_X 225.1 //miligauss\n// #define LOCAL_MAG_Y 5.75\n// #define LOCAL_MAG_Z 415.2\n\nconstexpr double gravity = 9.80665;\nconstexpr double local_mx = 208.762; //in miligauss\nconstexpr double local_my = 3.448;\nconstexpr double local_mz = 434.129;\n\nusing namespace std;\n\n\n    class ComplementaryFilter{\n\n        // constructor\n        public:\n\n        ComplementaryFilter()\n            {\n                is_init = false;\n                data_fused = false;\n                filter_updated = false;\n                magFieldEarth = Eigen::Vector3d(local_mx,local_my,local_mz);\n                mag = Eigen::Vector3d(0,0,0);\n                accel = Eigen::Vector3d(0,0,0);\n                gyro = Eigen::Vector3d(0,0,0);\n            }\n\n        struct parameters\n        {\n            double k1;\n            double k2;\n            double k3;\n            double k4;\n            double kb;\n            double sat;\n        };\n        \n        // Maths Functions\n        Eigen::Matrix3d quatToRotationMatrix(Eigen::Vector4d quat);  // transforme quaternion to rotation matrix\n\n        // Filter Methods\n        void initFilter();\n        void updateSensorData(Eigen::Vector3d gyro, Eigen::Vector3d accel, Eigen::Vector3d mag);\n        void fuseInertialData();\n        void updateFilter();\n\n        private:\n\n        // filter variables;\n        double dt; \n        Eigen::Vector3d magFieldEarth;\n        Eigen::Matrix3d rotationMatrix;\n        Eigen::Vector3d mag;\n        Eigen::Vector3d accel;\n        Eigen::Vector3d gyro;\n        Eigen::Vector3d bias;\n        Eigen::Vector3d sigR;\n        Eigen::Vector3d sigB;\n        Eigen::Vector3d gyro_estimate;\n        Eigen::Quaterniond quaternion;\n        Eigen::Matrix3d rotation_matrix;\n\n        // filter flags\n        bool is_init;\n        bool data_fused;\n        bool filter_updated;\n\n        // filter parameters\n        parameters params;\n\n    };\n\n\n#endif", "meta": {"hexsha": "25e690082c7bc851b3e08112dfbf8180d48196f5", "size": 2172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ComplementaryFilter.hpp", "max_stars_repo_name": "MehdiN/MahonyCF", "max_stars_repo_head_hexsha": "cb0ea5af529ca9a58347c95c011f02013baa7dfe", "max_stars_repo_licenses": ["MIT"], "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/ComplementaryFilter.hpp", "max_issues_repo_name": "MehdiN/MahonyCF", "max_issues_repo_head_hexsha": "cb0ea5af529ca9a58347c95c011f02013baa7dfe", "max_issues_repo_licenses": ["MIT"], "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/ComplementaryFilter.hpp", "max_forks_repo_name": "MehdiN/MahonyCF", "max_forks_repo_head_hexsha": "cb0ea5af529ca9a58347c95c011f02013baa7dfe", "max_forks_repo_licenses": ["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.6818181818, "max_line_length": 112, "alphanum_fraction": 0.5939226519, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5183028492403285}}
{"text": "#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n#include \"geometry_msgs/Twist.h\"\n#include \"geometry_msgs/PoseStamped.h\"\n#include \"videoray/Throttle.h\"\n#include \"nav_msgs/Odometry.h\"\n#include \"std_msgs/Float32.h\"\n\n#include <iostream>\n#include <sstream>\n\n#include <boost/numeric/odeint.hpp>\n\nusing std::cout;\nusing std::endl;\n\nusing namespace boost::numeric::odeint;\n\ntypedef boost::array< double , 12 > state_type;\n\n#define PI (3.14159265359)\n\nnav_msgs::Odometry odom_;\nvoid odomCallback(const nav_msgs::Odometry::ConstPtr& msg)\n{\n     odom_ = *msg;\n}\n\nstate_type x_ = {0,0,0,0,0,0,0,0,0,0,0,0};\n\n// Linear and angular velocity states\ndouble u;\ndouble v;\ndouble w;\ndouble p;\ndouble q;\ndouble r;\n          \n// Added Mass Terms\ndouble X_udot = 1.94; // inertia matrix M (m11)\ndouble Y_vdot = 6.05; // inertia matrix M (m22)\ndouble Z_wdot = 3.95; // m33\ndouble N_rdot = 0.1;\n//double N_rdot = 1.18e-2; // vehicle's motion of inertia about z-axis\n// (6,6) entry of the vehicle inertia Matrix M\n\n// Linear Drag Coefficients\ndouble Xu = -0.95;\ndouble Yv = -5.87;\ndouble Nr = -0.023;\ndouble Zw = -3.70;\n\n// Quadratic Drag Coefficients\ndouble Xuu = -6.04;\ndouble Yvv = -30.73;\ndouble Nrr = -0.45;\ndouble Zww = -26.36;\n\ndouble Ct_forw = 0.026667;\ndouble Ct_back = 0.026667;\ndouble Ct_vert_forw = 0.026667;\ndouble Ct_vert_back = 0.026667;\n\ndouble u_sat_low = -150;\ndouble u_sat_high = 150;\n     \n// Control inputs\ndouble X = 0;\ndouble N = 0;\ndouble Z = 0;\n\ndouble u_port = 0;\ndouble u_star = 0;\ndouble u_vert = 0;\n\ndouble xpos  = 0;\ndouble ypos  = 0;\ndouble zpos  = 0;\ndouble phi   = 0;\ndouble theta = 0;\ndouble psi   = 0;\n\ndouble c1 = 0;\ndouble c2 = 0;\ndouble c3 = 0;\ndouble s1 = 0;\ndouble s2 = 0;\ndouble s3 = 0;\ndouble t2 = 0;\n\nvideoray::Throttle throttle_;\n\nvoid videoray_model( const state_type &x , state_type &dxdt , double t )\n{\n/// States: \n/// 0:  u     : surge velocity\n/// 1:  v     : sway velocity\n/// 2:  w     : heave velocity\n/// 3:  p     : roll rate\n/// 4:  q     : pitch rate\n/// 5:  r     : yaw rate\n/// 6:  xpos  : earth x-pos\n/// 7:  ypos  : earth y-pos\n/// 8:  zpos  : earth z-pos\n/// 9:  phi   : roll angle\n/// 10: theta : pitch angle\n/// 11: psi   : yaw angle\n     u = x[0];\n     v = x[1];\n     w = x[2];\n     p = x[3];\n     q = x[4];\n     r = x[5];\n     xpos  = x[6];\n     ypos  = x[7];\n     zpos  = x[8];\n     phi   = x[9];\n     theta = x[10];\n     psi   = x[11];\n          \n     // Calculate fixed frame velocity rates\n     dxdt[0] = (-Y_vdot*v*r + Xu*u + Xuu*u*abs(u) + X) / X_udot;\n     dxdt[1] = (X_udot*u*r + Yv*v + Yvv*v*abs(v)) / Y_vdot;\n     dxdt[2] = (Zw*w + Zww*w*abs(w) + Z) / Z_wdot;\n\n     // Calculate fixed frame orientation rates\n     dxdt[3] = 0;\n     dxdt[4] = 0;\n     dxdt[5] = (Nr*r + Nrr*r*abs(r) + N) / N_rdot;     \n\n     c1 = cos(phi);\n     c2 = cos(theta); \n     c3 = cos(psi); \n     s1 = sin(phi); \n     s2 = sin(theta); \n     s3 = sin(psi); \n     t2 = tan(theta);\n\n     // Calculate inertial frame position\n     dxdt[6] = c3*c2*u + (c3*s2*s1-s3*c1)*v + (s3*s1+c3*c1*s2)*w;\n     dxdt[7] = s3*c2*u + (c1*c3+s1*s2*s3)*v + (c1*s2*s3-c3*s1)*w;\n     dxdt[8] = -s2*u + c2*s1*v + c1*c2*w;\n\n     // Calculate inertial frame orientations\n     dxdt[9] = p + (q*s1 + r*c1)*t2;\n     dxdt[10] = q*c1 - r*s1;\n     dxdt[11] = (q*s1 + r*c1)* (1 / cos(theta));\n}\n\n//\n// Converts input throttle commands to simulated linear and angular velocities.\n//\ngeometry_msgs::Twist velocity_cmd_;\ngeometry_msgs::Vector3 velocity_linear_;\ngeometry_msgs::Vector3 velocity_angular_;\n\ndouble saturate(double input, const double &min, const double &max)\n{\n     if (min > max) {\n          ROS_INFO(\"saturate(): Invalid Min / Max Combo\");\n          return 0;\n     } else if (input < min) {\n          input = min;\n     } else if(input > max) {\n          input = max;\n     }\n     return input;\n}\n\n// Assumes that input has already been saturated within the in_min and in_max\n// boundaries. Use the saturate() function on input before calling normalize\ndouble normalize(double input, const double &in_min, const double &in_max,\n                 const double &out_min, const double &out_max)\n{\n     if (in_min >= in_max || out_min >= out_max) {\n          ROS_INFO(\"normalize(): Invalid Min / Max Combo\");\n          return 0;\n     }\n\n     double ratio = input / (in_max - in_min);\n     return ratio * (out_max - out_min);\n\n     return input;\n}\n\ndouble thrust_port = 0, thrust_star = 0;\nvoid processThrottleCmds()\n{\n     u_port = saturate(throttle_.PortInput, u_sat_low, u_sat_high);\n     u_star = saturate(throttle_.StarInput, u_sat_low, u_sat_high);\n     u_vert = saturate(throttle_.VertInput, u_sat_low, u_sat_high);\n\n     // Ct is different for reverse and forward\n     if ( u_port >= 0 ) {\n          thrust_port = u_port * Ct_forw;\n     } else {\n          thrust_port = u_port * Ct_back;\n     }\n\n     if ( u_star >= 0 ) {\n          thrust_star = u_star * Ct_forw;\n     } else {\n          thrust_star = u_star * Ct_back;\n     }\n\n     X = thrust_port + thrust_star;\n     N = thrust_star - thrust_port;\n\n     // Ct is different for reverse and forward\n     if ( u_vert >= 0 ) {\n          Z = u_vert * Ct_vert_forw;\n     } else {\n          Z = u_vert * Ct_vert_back;\n     }\n\n}\n\ndouble normDegrees(double input)\n{\n     if (input < 0) {\n          input += 360;\n     } else if(input >= 360) {\n          input -= 360;\n     }\n     return input;\n}\n\nvoid quaternionToEuler(const double &q0, const double &q1, \n                       const double &q2, const double &q3,\n                       double &roll, double &pitch, double &yaw)\n{\n     roll = atan2(2*(q0*q1 + q2*q3), 1 - 2*(q1*q1 + q2*q2) );\n     pitch = asin(2*(q0*q2-q3*q1));\n     yaw = atan2(2*(q0*q3 + q1*q2), 1 - 2*(q2*q2 + q3*q3) );\n}\n\nvoid eulerToQuaternion(const double &roll, const double &pitch, \n                       const double &yaw,\n                       double &q0, double &q1, \n                       double &q2, double &q3)\n{\n     q0 = cos(roll/2)*cos(pitch/2)*cos(yaw/2) + sin(roll/2)*sin(pitch/2)*sin(yaw/2);\n     q1 = sin(roll/2)*cos(pitch/2)*cos(yaw/2) - cos(roll/2)*sin(pitch/2)*sin(yaw/2);\n     q2 = cos(roll/2)*sin(pitch/2)*cos(yaw/2) + sin(roll/2)*cos(pitch/2)*sin(yaw/2);\n     q3 = cos(roll/2)*cos(pitch/2)*sin(yaw/2) - sin(roll/2)*sin(pitch/2)*cos(yaw/2);\n}\n\ndouble depth_ref = 0;\ndouble speed_ref = 0;\ndouble heading_ref = 0;\n\nvoid desiredVelocityCallback(const std_msgs::Float32::ConstPtr& msg)\n{\n     speed_ref = msg->data;\n}\n\nvoid desiredHeadingCallback(const std_msgs::Float32::ConstPtr& msg)\n{\n     heading_ref = normDegrees(msg->data - 90);\n     //heading_ref = msg->data;\n}\n\nvoid desiredDepthCallback(const std_msgs::Float32::ConstPtr& msg)\n{\n     depth_ref = msg->data;\n}\n\n//geometry_msgs::Quaternion quat_;\ndouble depth_err = 0;\ndouble speed_err = 0;\ndouble heading_err = 0;\ndouble heading = 0;\ndouble heading_port, heading_star, speed_port, speed_star;\ndouble heading_weight = 0.5;\ndouble speed_weight = 0.5;\n//double K_heading = 0.25;\ndouble K_heading = 0.01;\ndouble K_speed = 10;\ndouble K_depth = 50;\ndouble roll_ = 0;\ndouble pitch_ = 0;\ndouble yaw_ = 0;\n\nvoid execControlLaw()\n{     \n     //quat_ = odom_.pose.pose.orientation;\n     //quaternionToEuler(quat_.w, quat_.x, quat_.y, quat_.z,\n     //                  roll_, pitch_, yaw_);\n          \n     //depth_err = depth_ref - odom_.pose.pose.position.z;\n     //speed_err = speed_ref - odom_.twist.twist.linear.x;\n     \n     roll_ = x_[9];\n     pitch_ = x_[10];\n     yaw_ = x_[11];\n     \n     depth_err = depth_ref - x_[8];\n     speed_err = speed_ref - x_[0];\n     \n     heading = normDegrees(yaw_*180/PI);\n     heading_err = heading_ref - heading;\n          \n     if (abs(heading_err) < 180) {\n          heading_port = -K_heading*heading_err;\n          heading_star = K_heading*heading_err;\n     } else  {\n          heading_port = K_heading*heading_err;\n          heading_star = -K_heading*heading_err;\n     }\n          \n     speed_port = K_speed*speed_err;\n     speed_star = K_speed*speed_err;\n     \n     throttle_.PortInput = heading_weight*heading_port + speed_weight*speed_port;\n     throttle_.StarInput = heading_weight*heading_star + speed_weight*speed_star;\n     throttle_.VertInput = K_depth*depth_err;\n\n     //throttle_.PortInput = 100;\n     //throttle_.StarInput = 95;\n     //throttle_.VertInput = 0;\n}\n\nint main(int argc, char **argv)\n{\n     ros::init(argc, argv, \"videoray_sim_and_control\");     \n     ros::NodeHandle n;\n\n     //ros::Publisher twist_pub = n.advertise<geometry_msgs::Twist>(\"motion\", 1);     \n     //ros::Subscriber odom_sub = n.subscribe(\"odometry\", 1, \n     //                                       odomCallback);\n\n     ros::Publisher pose_pub = n.advertise<geometry_msgs::Pose>(\"motion\",1);\n     geometry_msgs::Pose pose_;\n\n     ros::Publisher pub_nav_x = n.advertise<std_msgs::Float32>(\"NAV_X\",1);\n     ros::Publisher pub_nav_y = n.advertise<std_msgs::Float32>(\"NAV_Y\",1);\n     ros::Publisher pub_nav_depth = n.advertise<std_msgs::Float32>(\"NAV_DEPTH\",1);\n     ros::Publisher pub_nav_heading = n.advertise<std_msgs::Float32>(\"NAV_HEADING\",1);\n     ros::Publisher pub_nav_speed = n.advertise<std_msgs::Float32>(\"NAV_SPEED\",1);\n\n     std_msgs::Float32 nav_x, nav_y, nav_depth, nav_heading, nav_speed;\n\n     ros::Subscriber desired_vel_sub = n.subscribe(\"desired_velocity\", \n                                                   1, \n                                                   desiredVelocityCallback);\n\n     ros::Subscriber desired_head_sub = n.subscribe(\"desired_heading\", \n                                                    1, \n                                                    desiredHeadingCallback);\n\n     ros::Subscriber desired_depth_sub = n.subscribe(\"desired_depth\", \n                                                     1, \n                                                     desiredDepthCallback);\n     \n     //double rate = 30;\n     double rate = 10;\n     ros::Rate loop_rate(rate);\n\n     ros::Time begin = ros::Time::now();\n     ros::Time curr_time = begin;\n     ros::Time prev_time = begin;\n     ros::Duration dt = curr_time - prev_time;\n     \n     geometry_msgs::Quaternion quat;\n\n     runge_kutta4< state_type > stepper;\n     //runge_kutta_dopri5< state_type > stepper;\n     //adams_bashforth_moulton< 2 , state_type > stepper;\n\n     while (ros::ok())\n     {\n          //cout << \"*\" << std::flush;\n          \n          curr_time = ros::Time::now();\n          dt = curr_time - prev_time;\n          prev_time = curr_time;\n\n          ROS_INFO(\"dt: %f\\n\", dt.toSec());\n\n          //cout << dt.toSec() << endl << std::flush;\n\n          // Update state vector with odometry data from morse...\n          //state_type x = {0,0,0,0,0,0,0,0,0,0,0,0};\n          //x[0] = odom_.twist.twist.linear.x;\n          //x[1] = odom_.twist.twist.linear.y;\n          //x[2] = odom_.twist.twist.linear.z;\n          //x[3] = odom_.twist.twist.angular.x;\n          //x[4] = odom_.twist.twist.angular.y;\n          //x[5] = odom_.twist.twist.angular.z;\n          \n          execControlLaw();\n\n          processThrottleCmds();\n\n          //geometry_msgs::Quaternion quat = odom_.pose.pose.orientation;\n          //quaternionToEuler(quat.x, quat.y, quat.z, quat.w,\n          //                  roll_, pitch_, yaw_);\n          \n          //boost::numeric::odeint::integrate(videoray_model, \n          //                                  x_, \n          //                                  curr_time.toSec() , \n          //                                  (curr_time + dt).toSec(), \n          //                                  dt.toSec());\n          //boost::numeric::odeint::integrate(videoray_model, \n          //                                  x_, \n          //                                  curr_time.toSec() , \n          //                                  curr_time.toSec() + 1.0/rate, \n          //                                  1.0/rate);\n\n          stepper.do_step(videoray_model, x_ , curr_time.toSec() , dt.toSec() );\n\n          ROS_INFO(\"========================\");\n          ROS_INFO(\"Current: %f, \\tdt: %f\", curr_time.toSec(), dt.toSec());\n          ROS_INFO(\"Surge: %f\", x_[0]);\n          ROS_INFO(\"Sway: %f\", x_[1]);\n          ROS_INFO(\"Heave: %f\", x_[2]);\n          \n          ROS_INFO(\"3: %f\", x_[3]);\n          ROS_INFO(\"4: %f\", x_[4]);\n          ROS_INFO(\"5: %f\", x_[5]);\n          ROS_INFO(\"6: %f\", x_[6]);\n          ROS_INFO(\"7: %f\", x_[7]);\n          ROS_INFO(\"8: %f\", x_[8]);\n          ROS_INFO(\"9: %f\", x_[9]);\n          ROS_INFO(\"10: %f\", x_[10]);\n          ROS_INFO(\"11: %f\", x_[11]);\n          \n          //velocity_linear_.x = x[0];\n          //velocity_linear_.y = x[1];\n          //velocity_linear_.z = x[2];\n          //velocity_angular_.z = x[5];\n          //\n          //velocity_cmd_.linear = velocity_linear_;\n          //velocity_cmd_.angular = velocity_angular_;\n          //twist_pub.publish(velocity_cmd_);\n          \n          \n\n          //quaternionToEuler(quat.w, quat.x, quat.y, quat.z,\n          //                  roll_, pitch_, yaw_);               \n          //\n          //eulerToQuaternion(x_[9], \n          //                  x_[10], \n          //                  x_[11],\n          //                  quat.w, quat.x, quat.y, quat.x);          \n\n          //quat.w = 0.1; quat.x = 0.2; quat.y = 0.3 ; quat.z = 0.4;\n          \n          //quaternionToEuler(quat.w, quat.x, quat.y, quat.z,\n          //                  roll_, pitch_, yaw_);               \n          \n          roll_  = x_[9];\n          pitch_ = x_[10];\n          yaw_   = x_[11];\n                    \n          eulerToQuaternion(roll_, \n                            pitch_, \n                            yaw_,\n                            quat.w, quat.x, quat.y, quat.z);          \n          \n          pose_.position.x = x_[6];\n          pose_.position.y = x_[7];\n          pose_.position.z = x_[8];\n          pose_.orientation.x = quat.x;\n          pose_.orientation.y = quat.y;\n          pose_.orientation.z = quat.z;\n          pose_.orientation.w = quat.w;\n\n          pose_pub.publish(pose_);\n\n          nav_x.data = x_[6];\n          nav_y.data = x_[7];\n          nav_depth.data = x_[8];\n          nav_speed.data = x_[0];\n          nav_heading.data = normDegrees(x_[11]*180.0/PI + 90);\n\n          pub_nav_x.publish(nav_x);\n          pub_nav_y.publish(nav_y);\n          pub_nav_depth.publish(nav_depth);\n          pub_nav_heading.publish(nav_heading);\n          pub_nav_speed.publish(nav_speed);\n\n          ros::spinOnce();\n\n          loop_rate.sleep();\n     }\n     return 0;\n}\n", "meta": {"hexsha": "17a8c73e7ed6b48d79d459b6348755bac02f9769", "size": 14479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/videoray/catkin_ws/src/videoray/src/sim/videoray_sim_and_control.cpp", "max_stars_repo_name": "toremobjo/VideoRayROS", "max_stars_repo_head_hexsha": "aa13a6d4f924fbcd7c2b0b2016a7b409b9272d63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-06-17T18:23:27.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-14T05:33:24.000Z", "max_issues_repo_path": "src/videoray/catkin_ws/src/videoray/src/sim/videoray_sim_and_control.cpp", "max_issues_repo_name": "toremobjo/VideoRayROS", "max_issues_repo_head_hexsha": "aa13a6d4f924fbcd7c2b0b2016a7b409b9272d63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-07-01T09:01:17.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-02T15:24:15.000Z", "max_forks_repo_path": "src/videoray/catkin_ws/src/videoray/src/sim/videoray_sim_and_control.cpp", "max_forks_repo_name": "toremobjo/VideoRayROS", "max_forks_repo_head_hexsha": "aa13a6d4f924fbcd7c2b0b2016a7b409b9272d63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:57:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-20T12:42:54.000Z", "avg_line_length": 29.609406953, "max_line_length": 86, "alphanum_fraction": 0.5398853512, "num_tokens": 4162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5183028442238804}}
{"text": "#include \"NearestNeighbourSearch.hpp\"\n\n\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Search_traits_3.h>\n#include <CGAL/Search_traits_adapter.h>\n//#include <CGAL/point_generators_3.h>\n#include <CGAL/Orthogonal_k_neighbor_search.h>\n#include <CGAL/property_map.h>\n#include <boost/iterator/zip_iterator.hpp>\n#include <utility>\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::Point_3                                     Point_3;\ntypedef boost::tuple<Point_3,int>                           Point_and_int;\n//typedef CGAL::Random_points_in_cube_3<Point_3>              Random_points_iterator;\ntypedef CGAL::Search_traits_3<Kernel>                       Traits_base;\ntypedef CGAL::Search_traits_adapter<Point_and_int,\n  CGAL::Nth_of_tuple_property_map<0, Point_and_int>,\n  Traits_base>                                              Traits;\ntypedef CGAL::Orthogonal_k_neighbor_search<Traits>          K_neighbor_search;\ntypedef K_neighbor_search::Tree                             Tree;\ntypedef K_neighbor_search::Distance                         Distance;\n\n\n  \n  NearestNeighbourSearch::NearestNeighbourSearch(const std::vector<nniSample>& spoints)\n    : m_sps(spoints),\n      m_tree()\n  {\n    \n\n    std::vector<Point_3>  points;\n    std::vector<size_t>   indices;\n    size_t idx = 0;\n    for(const auto& sp : m_sps){\n      points.push_back(Point_3(sp.s_pos.x, sp.s_pos.y, sp.s_pos.z));\n      indices.push_back(idx);\n      ++idx;\n    }\n    \n\n    m_tree = new Tree(\n\t\t      boost::make_zip_iterator(boost::make_tuple( points.begin(),indices.begin() )),\n\t\t      boost::make_zip_iterator(boost::make_tuple( points.end(),indices.end() ) )  \n\t\t      );\n\n    \n  }\n  \n  NearestNeighbourSearch::~NearestNeighbourSearch()\n  {}\n  \n\n  std::vector<nniSample>\n  NearestNeighbourSearch::search(const nniSample& ipolant,unsigned num_neighbours) const{\n    std::vector<nniSample> result;\n\n    Point_3 query(ipolant.s_pos.x, ipolant.s_pos.y, ipolant.s_pos.z);\n    K_neighbor_search search(*(reinterpret_cast<Tree*>(m_tree)), query, num_neighbours);\n\n    for(K_neighbor_search::iterator it = search.begin(); it != search.end(); it++){\n      result.push_back(m_sps[boost::get<1>(it->first)]);\n    }\n\n\n    return result;\n#if 0    \n    const unsigned int K = 5;\n    Point_3 query(0.0, 0.0, 0.0);\n    Distance tr_dist;\n    // search K nearest neighbours\n    K_neighbor_search search(*(reinterpret_cast<Tree*>(m_tree)), query, K);\n    for(K_neighbor_search::iterator it = search.begin(); it != search.end(); it++){\n      std::cout << \" d(q, nearest neighbor) =  \"\n\t\t<< tr_dist.inverse_of_transformed_distance(it->second) << \" point: \" \n\t\t<< boost::get<0>(it->first)<< \" index \" << boost::get<1>(it->first) << std::endl;\n    }\n#endif\n    }\n\n\n", "meta": {"hexsha": "38cac09799081e987ecd214cf96edc6387ae3a5b", "size": 2778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "framework/NearestNeighbourSearch.cpp", "max_stars_repo_name": "aosterthun/rgbdri", "max_stars_repo_head_hexsha": "8e513172f512c902f7d6d8631c7580b5b62277c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "framework/NearestNeighbourSearch.cpp", "max_issues_repo_name": "aosterthun/rgbdri", "max_issues_repo_head_hexsha": "8e513172f512c902f7d6d8631c7580b5b62277c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "framework/NearestNeighbourSearch.cpp", "max_forks_repo_name": "aosterthun/rgbdri", "max_forks_repo_head_hexsha": "8e513172f512c902f7d6d8631c7580b5b62277c4", "max_forks_repo_licenses": ["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.4698795181, "max_line_length": 89, "alphanum_fraction": 0.6558675306, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5183028442238804}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 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_ARCH_COMMON_SCALAR_FUNCTION_SQRT1PM1_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_SQRT1PM1_HPP_INCLUDED\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/sqrt.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( sqrt1pm1_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 tmp =  bs::sqrt(inc(a0));\n      return  ((bs::abs(a0) < bs::Half<A0>())? a0/bs::inc(tmp) : bs::dec(tmp));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "d363797645b579df29ce53c0ad5c206d77f8d689", "size": 1484, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/sqrt1pm1.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/arch/common/scalar/function/sqrt1pm1.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/arch/common/scalar/function/sqrt1pm1.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": 32.9777777778, "max_line_length": 100, "alphanum_fraction": 0.5774932615, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.5183028392074323}}
{"text": "#include <boost/graph/fruchterman_reingold.hpp>\n#include <vector>\n\n#include \"graph_animator.hpp\"\n\nvoid GraphAnimator::add_vertices_edges(Graph &graph, GraphEventQueue &graph_event_queue, boost::gregorian::date date, boost::circle_topology<> topology)\n{\n    std::vector<Vertex> vertices = graph_event_queue.pop_vertices(date);\n    std::vector<Edge> edges = graph_event_queue.pop_edges(date);\n\n    // Add vertices.\n    for (\n        std::vector<Vertex>::iterator vertex_iterator = vertices.begin();\n        vertex_iterator != vertices.end();\n        ++vertex_iterator)\n    {\n        Vertex vertex = *vertex_iterator;\n        vertex.position = topology.center();\n        vertex.target_position = topology.center();\n\n        boost::add_vertex(vertex.id, vertex, graph);\n    }\n\n    // Add edges.\n    for (\n        std::vector<Edge>::iterator edge_iterator = edges.begin();\n        edge_iterator != edges.end();\n        ++edge_iterator)\n    {\n        Edge edge = *edge_iterator;\n\n        boost::add_edge_by_label(edge.source, edge.target, edge, graph);\n    }\n}\n\nvoid GraphAnimator::evaluate_target_layout(Graph &graph, boost::circle_topology<> topology)\n{\n    boost::fruchterman_reingold_force_directed_layout(\n        graph,\n        boost::get(&Vertex::target_position, graph),\n        topology,\n        boost::force_pairs(boost::all_force_pairs()));\n}\n\nvoid GraphAnimator::update_layout(Graph &graph, boost::circle_topology<> topology, double step)\n{\n    VertexIterator vertex_iterator, vertex_iterator_end;\n    for (\n        boost::tie(vertex_iterator, vertex_iterator_end) = boost::vertices(graph);\n        vertex_iterator != vertex_iterator_end;\n        ++vertex_iterator)\n    {\n        Vertex *vertex = &graph.graph()[*vertex_iterator];\n        vertex->position = topology.move_position_toward(vertex->position, step, vertex->target_position);\n    }\n}\n", "meta": {"hexsha": "286030f150009bb0ceb936ceba2d9bcd3173831d", "size": 1852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/graph_animator.cpp", "max_stars_repo_name": "stephaneseng/dynamic-network-visualization-boost-graph-library", "max_stars_repo_head_hexsha": "095b64677a088dfffe8c0968fc0bb2bc0d0360a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T05:23:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T12:13:27.000Z", "max_issues_repo_path": "src/graph_animator.cpp", "max_issues_repo_name": "stephaneseng/dynamic-network-visualization-boost-graph-library", "max_issues_repo_head_hexsha": "095b64677a088dfffe8c0968fc0bb2bc0d0360a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graph_animator.cpp", "max_forks_repo_name": "stephaneseng/dynamic-network-visualization-boost-graph-library", "max_forks_repo_head_hexsha": "095b64677a088dfffe8c0968fc0bb2bc0d0360a9", "max_forks_repo_licenses": ["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.4912280702, "max_line_length": 152, "alphanum_fraction": 0.681425486, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.518255784856891}}
{"text": "/* test_uniform_int_distribution.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$\n *\n */\n\n#include <boost/random/uniform_int_distribution.hpp>\n#include <limits>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::uniform_int_distribution<>\n#define BOOST_RANDOM_ARG1 a\n#define BOOST_RANDOM_ARG2 b\n#define BOOST_RANDOM_ARG1_DEFAULT 0\n#define BOOST_RANDOM_ARG2_DEFAULT 0x7fffffff\n#define BOOST_RANDOM_ARG1_VALUE 100\n#define BOOST_RANDOM_ARG2_VALUE 250\n\n#define BOOST_RANDOM_DIST0_MIN 0\n#define BOOST_RANDOM_DIST0_MAX 0x7fffffff\n#define BOOST_RANDOM_DIST1_MIN 100\n#define BOOST_RANDOM_DIST1_MAX 0x7fffffff\n#define BOOST_RANDOM_DIST2_MIN 100\n#define BOOST_RANDOM_DIST2_MAX 250\n\n#define BOOST_RANDOM_TEST1_PARAMS (0, 9)\n#define BOOST_RANDOM_TEST1_MIN 0\n#define BOOST_RANDOM_TEST1_MAX 9\n\n#define BOOST_RANDOM_TEST2_PARAMS (10, 19)\n#define BOOST_RANDOM_TEST2_MIN 10\n#define BOOST_RANDOM_TEST2_MAX 19\n\n#include \"test_distribution.ipp\"\n\n#define BOOST_RANDOM_UNIFORM_INT boost::random::uniform_int_distribution\n\n#include \"test_uniform_int.ipp\"\n", "meta": {"hexsha": "5863163b04963f3ef9af1105e3200ecefd9cc9e6", "size": 1190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_uniform_int_distribution.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/random/test/test_uniform_int_distribution.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/random/test/test_uniform_int_distribution.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.6744186047, "max_line_length": 75, "alphanum_fraction": 0.8319327731, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.518255784856891}}
{"text": "// -------------------------------------------------------------------\n//\n// basho_metrics: fast performance metrics for Erlang.\n// \n// inspired and partially derived from Coda Hale's 'metrics' \n// Copyright (c) 2010-2001 Coda Hale\n// https://github.com/codahale/metrics/blob/development/LICENSE.md\n//\n// Copyright (c) 2011 Basho Technologies, Inc. All Rights Reserved.\n//\n// This file is provided to you under the Apache License,\n// Version 2.0 (the \"License\"); you may not use this file\n// except in compliance with the License.  You may obtain\n// 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,\n// software distributed under the License is distributed on an\n// \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n// KIND, either express or implied.  See the License for the\n// specific language governing permissions and limitations\n// under the License.\n//\n// -------------------------------------------------------------------\n#ifndef SAMPLE_HPP_\n#define SAMPLE_HPP_\n\n#include <map>\n#include <vector>\n#include <cmath>\n#include <ctime>\n#include <cstdlib>\n#include <stdint.h>\n#include <sys/time.h>\n#include <boost/circular_buffer.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n\n/**\n * An exponentially-decaying random sample of {@code long}s. Uses Cormode et\n * al's forward-decaying priority reservoir sampling method to produce a\n * statistically representative sample, exponentially biased towards newer\n * entries.\n *\n * @see <a href=\"http://www.research.att.com/people/Cormode_Graham/library/publications/CormodeShkapenyukSrivastavaXu09.pdf\">\n * Cormode et al. Forward Decay: A Practical Time Decay Model for Streaming\n * Systems. ICDE '09: Proceedings of the 2009 IEEE International Conference on\n * Data Engineering (2009)</a>\n */\ntemplate <typename IntType=unsigned long>\nstruct exponentially_decaying_sample\n{\n    exponentially_decaying_sample(std::size_t size, double alpha=0.015)\n        : size_(size),\n          alpha_(alpha),\n          count_(0),\n          start_time_(tick()),\n          next_scale_time_(start_time_ + RESCALE_THRESHOLD)\n    {\n    }\n        \n    /**\n     * Clears all recorded values.\n     */\n    void clear()\n    {\n        values_.clear();\n        count_ = 0;\n        start_time_ = tick();\n        next_scale_time_ = start_time_ + RESCALE_THRESHOLD;\n    }\n\n   /**\n     * Returns the number of values recorded.\n     */\n    std::size_t size() const\n    {\n        return std::min(size_, count_);\n    }\n\n    double weight(long t) const\n    {\n        return std::exp(alpha_ * t);\n    }\n\n    /**\n     * Adds a new recorded value to the sample.\n     */    \n    void update(IntType value) \n    {\n        update(value, tick());\n    }\n\n    void update(IntType value, long timestamp)\n    {\n        double priority = weight(timestamp - start_time_) / next_random();\n        if (++count_ <= size_)\n            values_[priority] = value;\n        else\n        {\n            double first = values_.begin()->first;\n            if (first < priority)\n            {\n                if (values_.find(priority) == values_.end() )\n                    values_[priority] = value;\n                values_.erase(values_.begin());\n            }\n        }\n        long now = tick();\n        if (now > next_scale_time_)\n            rescale(now, next_scale_time_);\n    }\n\n    /* \"A common feature of the above techniques\u2014indeed, the key technique \n     * that allows us to track the decayed weights efficiently\u2014is that they \n     * maintain counts and other quantities based on g(ti \u2212 L), and only scale \n     * by g(t \u2212 L) at query time. But while g(ti \u2212L)/g(t\u2212L) is guaranteed to \n     * lie between zero and one, the intermediate values of g(ti \u2212 L) could \n     * become very large. For polynomial functions, these values should not \n     * grow too large, and should be effectively represented in practice by \n     * floating point values without loss of precision. For exponential \n     * functions, these values could grow quite large as new values of (ti \u2212 L)\n     * become large, and potentially exceed the capacity of common floating \n     * point types. However, since the values stored by the algorithms are \n     * linear combinations of g values (scaled sums), they can be rescaled \n     * relative to a new landmark. That is, by the analysis of exponential \n     * decay in Section III-A, the choice of L does not affect the final \n     * result. We can therefore multiply each value based on L by a factor of \n     * exp(\u2212\u03b1(L\u2032 \u2212 L)), and obtain the correct value as if we had instead \n     * computed relative to a new landmark L\u2032 (and then use this new L\u2032 at \n     * query time). This can be done with a linear pass over whatever data \n     * structure is being used.\"\n     */\n    void rescale(long now, long next) \n    {\n        next_scale_time_ = now + RESCALE_THRESHOLD;\n        long old_start_time = start_time_;\n        start_time_ = tick();\n        std::map<double, IntType> new_values;\n        for (typename std::map<double, IntType>::const_iterator \n             it=values_.begin();\n             it != values_.end();\n             ++it)\n        {\n            IntType value = it->second;\n            new_values[it->first * std::exp(-alpha_ * (start_time_-old_start_time))] = value;\n        }\n        values_.swap(new_values);\n    }\n\n    /**\n     * Returns a copy of the sample's values.\n     */\n    std::vector<IntType> values() const\n    {\n        std::vector<IntType> v;\n        for (typename std::map<double, IntType>::const_iterator \n                 it=values_.begin();\n             it != values_.end();\n             ++it)\n        {\n            v.push_back(it->second);\n        }\n        return v;\n    }\n\nprivate:\n    long tick() const \n    {\n        return time(NULL);\n    }\n\n   double next_random()\n   {\n       return dist_(gen_) / static_cast<double>(std::numeric_limits<IntType>::max());\n   }\nprivate:\n    std::size_t size_;\n    double alpha_;\n    std::size_t count_;\n    long start_time_;\n    long next_scale_time_;\n    std::map<double, IntType> values_;\n    boost::random::uniform_int_distribution<IntType> dist_;\n    boost::random::mt19937 gen_;\n    const static long RESCALE_THRESHOLD = 60;\n};\n\n\n/**\n * Sliding sample of a stream of {@code long}s. Operates on fixed-time window,\n * expired points are simply dropped.\n */\ntemplate <typename IntType=unsigned long>\nstruct sliding_sample\n{\n    sliding_sample(std::size_t size, std::size_t width_in_ms)\n        : size_(size),\n          width_(width_in_ms * 1000),\n          ticks_(size),\n          values_(size)\n    {\n    }\n\n    typedef uint64_t tick_t;\n\npublic:\n    void clear()\n    {\n        ticks_.clear();\n        values_.clear();\n    }\n\n    std::size_t size() const\n    {\n        return values_.size();\n    }\n\n    void update(IntType value)\n    {\n        tick_t ts = tick();\n        cut(ts);\n        values_.push_back(value);\n        ticks_.push_back(ts);\n    }\n\n    std::vector<IntType> values() const\n    {\n        std::size_t expired = std::min(expired_before(tick()), size() - 1);\n        return std::vector<IntType>(values_.begin() + expired, values_.end());\n    }\n\nprivate:\n    tick_t tick() const\n    {\n        timeval tv;\n        if (0 == gettimeofday(&tv, 0)) {\n            return uint64_t(tv.tv_sec) * 1000000 + tv.tv_usec;\n        }\n        return 0;\n    }\n\n    void cut(tick_t ts)\n    {\n        std::size_t cut = expired_before(ts);\n        if (cut) {\n            values_.erase(values_.begin(), values_.begin() + cut);\n            ticks_.erase(ticks_.begin(), ticks_.begin() + cut);\n        }\n    }\n\n    std::size_t expired_before(tick_t ts) const {\n        tick_t cutoff = ts - width_;\n        tick_buffer::const_iterator it = ticks_.begin(), end = ticks_.end();\n        while (it != end && *it < cutoff) {\n            ++it;\n        }\n        return it - ticks_.begin();\n    }\n\nprivate:\n    std::size_t size_;\n    tick_t width_;\n    typedef boost::circular_buffer<tick_t> tick_buffer;\n    tick_buffer ticks_;\n    boost::circular_buffer<IntType> values_;\n\n};\n\n\n/**\n * A random sample of a stream of {@code long}s. Uses Vitter's Algorithm R to\n * produce a statistically representative sample.\n *\n * @see <a href=\"http://www.cs.umd.edu/~samir/498/vitter.pdf\">Random Sampling\n *      with a Reservoir</a>\n */\ntemplate <typename IntType=unsigned long>\nstruct uniform_sample \n{\n    uniform_sample(std::size_t reservoir_size)\n        : size_(reservoir_size),\n          count_(0),\n          values_(reservoir_size, 0)\n    {\n    }\npublic:\n    void clear() \n    {\n        std::fill_n(values_.begin(), size_, 0);\n    }\n\n    std::size_t size() const\n    {\n        return std::min(count_, size_);\n    }\n\n    void update(IntType value)\n    {\n        std::size_t c = ++count_;\n        if (c <= size_) { values_[c-1] = value; }\n        else\n        {\n            std::size_t r = next_random() % c;\n            if (r < size_) { values_[r] = value; }\n        }\n    }\n\n    std::vector<IntType> values() const\n    {\n        return std::vector<IntType>(values_.begin(), values_.begin()+size());\n    }\n\nprivate:\n    IntType next_random() \n    {\n        return dist_(gen_);\n    }\n\nprivate:\n    std::size_t size_;\n    std::size_t count_;\n    std::vector<IntType> values_;\n    boost::random::uniform_int_distribution<IntType> dist_;\n    boost::random::mt19937 gen_;\n};\n\n#endif // include guard\n", "meta": {"hexsha": "cdb66564041a174fae59c6a8c5b244dc34cd0936", "size": 9425, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c_src/sample.hpp", "max_stars_repo_name": "russelldb/basho_metrics", "max_stars_repo_head_hexsha": "0b7474694c1bab3debc6742f0e64d12970d5fccf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-04-21T03:15:34.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-13T15:06:18.000Z", "max_issues_repo_path": "c_src/sample.hpp", "max_issues_repo_name": "russelldb/basho_metrics", "max_issues_repo_head_hexsha": "0b7474694c1bab3debc6742f0e64d12970d5fccf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-10-05T17:14:06.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-05T17:14:06.000Z", "max_forks_repo_path": "c_src/sample.hpp", "max_forks_repo_name": "russelldb/basho_metrics", "max_forks_repo_head_hexsha": "0b7474694c1bab3debc6742f0e64d12970d5fccf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-09-06T08:07:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-12T11:42:26.000Z", "avg_line_length": 28.4743202417, "max_line_length": 125, "alphanum_fraction": 0.6040318302, "num_tokens": 2246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5182557785446774}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/boost/graph/Dual.h>\n#include <CGAL/boost/graph/helpers.h>\n\n#include <iostream>\n#include <fstream>\n\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/connected_components.hpp>\n\ntypedef CGAL::Simple_cartesian<double>             Kernel;\ntypedef Kernel::Point_3                            Point;\ntypedef CGAL::Surface_mesh<Point>                  Mesh;\ntypedef CGAL::Dual<Mesh>                           Dual;\ntypedef boost::graph_traits<Dual>::edge_descriptor edge_descriptor;\n\ntemplate <typename G>\nstruct noborder {\n  noborder() : g(nullptr) {} // default-constructor required by filtered_graph\n  noborder(G& g) : g(&g) {}\n\n  bool operator()(const edge_descriptor& e) const\n  { return !is_border(e,*g); }\n\n  G* g;\n};\n\n\n// A dual border edge has a null_face as the source or target \"vertex\"\n// BGL algorithms won't like that, so we remove border edges through a\n// boost::filtered_graph.\ntypedef boost::filtered_graph<Dual, noborder<Mesh> >   FiniteDual;\ntypedef boost::graph_traits<Mesh>::vertex_descriptor   vertex_descriptor;\ntypedef boost::graph_traits<Mesh>::face_descriptor     face_descriptor;\ntypedef boost::graph_traits<Mesh>::edge_descriptor     edge_descriptor;\n\nint main(int argc, char* argv[])\n{\n  const char* filename = (argc > 1) ? argv[1] : \"data/prim.off\";\n\n  Mesh primal;\n  if(!CGAL::IO::read_polygon_mesh(filename, primal))\n  {\n    std::cerr << \"Invalid input.\" << std::endl;\n    return 1;\n  }\n\n  Dual dual(primal);\n  FiniteDual finite_dual(dual,noborder<Mesh>(primal));\n\n  std::cout << \"dual has \" << num_vertices(dual) << \" vertices\" << std::endl;\n\n  std::cout << \"The vertices of dual are faces in primal\"<< std::endl;\n  for(boost::graph_traits<Dual>::vertex_descriptor dvd : vertices(dual)) {\n    std::cout << dvd << std::endl;\n  }\n\n  std::cout << \"The edges in primal and dual with source and target\" << std::endl;\n  for(edge_descriptor e : edges(dual)) {\n   std::cout << e << \" in primal:  \" << source(e,primal)      << \" -- \" << target(e,primal)       << \"   \"\n             <<      \" in dual  :  \" << source(e,finite_dual) << \" -- \" << target(e,finite_dual)  << std::endl;\n  }\n\n\n std::cout << \"edges of the finite dual graph\" << std::endl;\n for(boost::graph_traits<FiniteDual>::edge_descriptor e : CGAL::make_range(edges(finite_dual))) {\n   std::cout << e << \"  \" << source(e,primal) << \" \" << source(e,finite_dual)  << std::endl;\n }\n\n // the storage of a property map is in primal\n Mesh::Property_map<face_descriptor,int> fccmap;\n fccmap = primal.add_property_map<face_descriptor,int>(\"f:CC\").first;\n int num = connected_components(finite_dual, fccmap);\n\n std::cout << \"The graph has \" << num << \" connected components (face connectivity)\" << std::endl;\n for(face_descriptor f : faces(primal)) {\n   std::cout << f << \" in connected component \" << fccmap[f] << std::endl;\n }\n\n Mesh::Property_map<vertex_descriptor,int> vccmap;\n vccmap = primal.add_property_map<vertex_descriptor,int>(\"v:CC\").first;\n num = connected_components(primal, vccmap);\n\n std::cout << \"The graph has \" << num << \" connected components (edge connectvity)\" << std::endl;\n for(vertex_descriptor v : vertices(primal)) {\n   std::cout << v << \" in connected component \" << vccmap[v] << std::endl;\n }\n  return 0;\n}\n", "meta": {"hexsha": "d278a383cabf6fc8aaeea105c60de0ed8eafcd47", "size": 3302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGL/examples/BGL_surface_mesh/surface_mesh_dual.cpp", "max_stars_repo_name": "antoniospg/cgal", "max_stars_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-20T17:02:24.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-20T17:02:24.000Z", "max_issues_repo_path": "BGL/examples/BGL_surface_mesh/surface_mesh_dual.cpp", "max_issues_repo_name": "antoniospg/cgal", "max_issues_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-10T13:32:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T12:23:20.000Z", "max_forks_repo_path": "BGL/examples/BGL_surface_mesh/surface_mesh_dual.cpp", "max_forks_repo_name": "antoniospg/cgal", "max_forks_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T15:26:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-21T15:26:25.000Z", "avg_line_length": 36.2857142857, "max_line_length": 111, "alphanum_fraction": 0.6620230164, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.518255767774872}}
{"text": "#pragma once\n#include <vector>\n#include <Eigen/Dense>\n\ntemplate <typename T>\nstruct PoseBase {\n    using Vector2 = Eigen::Matrix<T, 2, 1>;\n    using Vector3 = Eigen::Matrix<T, 3, 1>;\n    using Matrix2 = Eigen::Matrix<T, 2, 2>;\n    using Matrix3 = Eigen::Matrix<T, 3, 3>;\n    T x;\n    T y;\n    T theta;\n    PoseBase() : x(0), y(0), theta(0) {}\n    // loop: using while loop for normalizing angle to (-pi, pi] \n    PoseBase(T x, T y, T theta, bool loop = false): x(x), y(y) {\n        if (loop == false)\n            this->theta = goodAngle(theta);\n        else\n            this->theta = loopNormalize(theta);\n    }\n    PoseBase(const PoseBase& p): x(p.x), y(p.y), theta(p.theta) {}\n    PoseBase(Vector3 p, bool loop = false) : x(p(0)), y(p(1)) {\n        if (loop == false)\n            this->theta = goodAngle(p(2));\n        else\n            this->theta = loopNormalize(p(2));\n    }\n    PoseBase(Vector2 p, T theta):\n        x(p(0)), y(p(1)), theta(theta) {}\n    PoseBase(const Matrix2& R, const Vector2& t):\n        x(t.x()), y(t.y()), theta(atan2(R(1, 0), R(0, 0))) {}\n    PoseBase(const Matrix3& M): \n        x(M(0, 2)), y(M(1, 2)), \n        theta(atan2(M(1, 0), M(0, 0))) {}\n    Vector3 eigen() const {\n        return Vector3(x, y, theta);\n    }\n    Vector3 weighted_eigen(T theta_weight) const {\n        return Vector3(x, y, theta * theta_weight);\n    }\n    T norm2d() const {\n        return std::sqrt(x * x + y * y);\n    }\n    void operator+=(Vector3 p) {\n        x += p(0);\n        y += p(1);\n        theta = goodAngle(theta + p(2));\n    }\n    void operator-=(Vector3 p) {\n        x -= p(0);\n        y -= p(1);\n        theta = goodAngle(theta - p(2));\n    }\n    PoseBase operator-(const PoseBase& p) const {\n        return PoseBase(x - p.x, y - p.y, goodAngle(theta - p.theta));\n    }\n    PoseBase operator*(const PoseBase& p) const {\n        return PoseBase(rotation() * p.translation() + translation(), goodAngle(theta + p.theta));\n    }\n    Vector2 translation() const {\n        return Vector2(x, y);\n    }\n    Matrix2 rotation() const {\n        Matrix2 rotate_mat;\n        const T cosa = cos(theta), sina = sin(theta);\n        rotate_mat << cosa, -sina, sina, cosa;\n        return rotate_mat;\n    }\n    PoseBase inverse() const {\n        T cos_theta = cos(theta);\n        T sin_theta = sin(theta);\n        T trans_x = x * cos_theta + y * sin_theta;\n        T trans_y = x * sin_theta - y * cos_theta;\n        return PoseBase(-trans_x, trans_y, -theta);\n    }\n    Matrix3 transform() const {\n        const T cosa = cos(theta), sina = sin(theta);\n        const Matrix3 res = {cosa, -sina, x, sina, cosa, y, 0, 0, 1};\n        return res;\n    }\n    bool isnan() const {\n        return (std::isnan(x) || std::isnan(y) || std::isnan(theta));\n    }\n    static PoseBase Identity() {\n        return PoseBase(0, 0, 0);\n    }\n    static T goodAngle(T angle) {\n        if (angle > M_PI) \n            angle -= 2 * M_PI;\n        if (angle < -M_PI)\n            angle += 2 * M_PI;\n        return angle;\n    }\n    static T loopNormalize(T angle) {\n        while (angle > M_PI) \n            angle -= 2 * M_PI;\n        while (angle < -M_PI)\n            angle += 2 * M_PI;\n        return angle;\n    }\n};\n\ntypedef PoseBase<double> Pose;", "meta": {"hexsha": "b375df5afc24613aed32d80f4ef3a692cb7a74aa", "size": 3221, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bosch_locator_bridge/include/bosch_locator_bridge/transform.hpp", "max_stars_repo_name": "Enigmatisms/locator_ros_bridge", "max_stars_repo_head_hexsha": "bcf88f588def7388f4cfe04c3839b801cf3dafad", "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": "bosch_locator_bridge/include/bosch_locator_bridge/transform.hpp", "max_issues_repo_name": "Enigmatisms/locator_ros_bridge", "max_issues_repo_head_hexsha": "bcf88f588def7388f4cfe04c3839b801cf3dafad", "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": "bosch_locator_bridge/include/bosch_locator_bridge/transform.hpp", "max_forks_repo_name": "Enigmatisms/locator_ros_bridge", "max_forks_repo_head_hexsha": "bcf88f588def7388f4cfe04c3839b801cf3dafad", "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.9711538462, "max_line_length": 98, "alphanum_fraction": 0.5237503881, "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.518255767774872}}
{"text": "#ifndef RESOURCE_HPP\n#define RESOURCE_HPP\n\n#include \"generated_config.hpp\"\n\n#include <boost/container/small_vector.hpp>\n#include <type_traits>\n#include <utility> // for pair\n#include <vector>  // for allocator, vector\n\n// one term: coefficient, exponent\ntypedef std::pair<double, double> poly_term;\n\n// list of terms\n// TODO make number of optimized poly-terms a compile-time variable?\ntypedef std::vector<poly_term> polynomial;\n\ndouble apply_polynomial(const polynomial & poly, double x);\n// TODO add moving variant for efficiency\npolynomial add_poly(const polynomial & lhs, const polynomial & rhs);\n\n// Forwards\nclass Instance;\n\nclass Availability {\npublic:\n\tAvailability(double start_amount);\n\tAvailability(const Availability & other) = default; // copy constructor\n\n\tvoid set(std::vector<std::pair<unsigned int, double>> && new_points);\n\tdouble get_at(unsigned int point) const noexcept;\n\t\n\tdouble get_flat_available() const;\n\n\tstd::vector<std::pair<unsigned int, double>>::const_iterator begin() const;\n\tstd::vector<std::pair<unsigned int, double>>::const_iterator end() const;\n\nprivate:\n\t/* Each pair in the points vector is one step of a stepwise function\n\t * indicating the availability of a resource. The first member of every point\n\t * indicates from which time step on the amount is available, the second\n\t * member indicates the amount. The first point (i.e., the first member of the\n\t * first point) must be 0. The points must be sorted by ascending time steps.\n\t */\n\tstd::vector<std::pair<unsigned int, double>> points;\n};\n\nclass FlexCost {\npublic:\n\tFlexCost(polynomial base);\n\n\tvoid\n\tset_flexible(std::vector<std::pair<unsigned int, polynomial>> && new_points);\n\n\tconst polynomial & get_at(unsigned int point) const noexcept;\n\tconst polynomial & get_base() const noexcept;\n\t\n\tbool is_flat() const;\n\n\tstd::vector<std::pair<unsigned int, polynomial>>::const_iterator\n\tbegin() const;\n\tstd::vector<std::pair<unsigned int, polynomial>>::const_iterator end() const;\n\nprivate:\n\tpolynomial base;\n\t// Same idea as for Availability\n\tstd::vector<std::pair<unsigned int, polynomial>> points;\n};\n\nclass Resource {\npublic:\n\texplicit Resource(unsigned int id);\n\n\tvoid set_availability(Availability && availability);\n\tvoid set_overshoot_costs(FlexCost && cost);\n\tvoid set_investment_costs(polynomial costs);\n\n\tconst Availability & get_availability() const;\n\n\tconst FlexCost & get_flex_overshoot() const;\n\tconst polynomial & get_overshoot_costs(unsigned int pos) const;\n\n\t// This only works if the instance has flat costs!\n\tconst polynomial & get_overshoot_costs() const;\n\tbool is_overshoot_flat() const;\n\n\tconst polynomial & get_investment_costs() const;\n\n\tunsigned int get_rid();\n\tvoid set_id(unsigned int id);\n\n\tbool\n\toperator==(const Resource & other) const\n\t{\n\t\treturn other.rid == this->rid;\n\t\t// TODO in debug mode, compare everything!\n\t}\n\n\t// deepcopy\n\tResource clone() const;\n\nprivate:\n\tunsigned int rid;\n\tAvailability availability;\n\tpolynomial investment_costs;\n\tFlexCost overshoot_costs;\n};\n\nclass ResVec\n    : public boost::container::small_vector<double, OPTIMAL_RESOURCE_COUNT> {\npublic:\n\tusing boost::container::small_vector<double,\n\t                                     OPTIMAL_RESOURCE_COUNT>::small_vector;\n};\n\nclass Resources {\npublic:\n\tResources();\n\tResources(double usage);\n\tResources(const Instance * instance, const ResVec & usage);\n\tResources(const Instance * instance, const std::vector<double> & usage);\n\tResources(const Instance * instance, ResVec && usage);\n\tResources(const Instance * instance);\n\n\tconst ResVec & getUsage() const;\n\tResVec & getUsage();\n\n\tResources operator+(const Resources & other) const;\n\tResources operator-(const Resources & other) const;\n\tResources operator*(const Resources & other) const;\n\tResources operator/(const Resources & other) const;\n\tvoid operator+=(const Resources & other);\n\tvoid operator-=(const Resources & other);\n\tvoid operator*=(const Resources & other);\n\tvoid operator/=(const Resources & other);\n\n\tbool operator<(const Resources & other) const;\n\tbool operator>(const Resources & other) const;\n\tbool operator<=(const Resources & other) const;\n\tbool operator>=(const Resources & other) const;\n\tbool operator!=(const Resources & other) const;\n\tbool operator==(const Resources & other) const;\n\n\ttemplate <typename T>\n\tinline friend std::enable_if_t<std::is_integral_v<T>, Resources>\n\toperator*(const T & scalar, const Resources & resource);\n\nprivate:\n\tconst Instance * instance;\n\tmutable bool cached;\n\tmutable double cache;\n\n\tResVec usage;\n\n\tdouble getCosts() const;\n};\n\ntemplate <typename T>\ninline std::enable_if_t<std::is_integral_v<T>, Resources>\noperator*(const T & scalar, const Resources & resource)\n{\n\tResources res(resource.instance, resource.usage);\n\tfor (size_t i = 0; i < resource.usage.size(); i++) {\n\t\tres.usage[i] *= scalar;\n\t}\n\treturn res;\n}\n\ntemplate <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>\nResources\noperator*(const Resources & resource, const T & scalar)\n{\n\treturn scalar * resource;\n}\n\n#endif\n", "meta": {"hexsha": "59a410936145f18fc3025ae1bbcb48b4e6ee3b6e", "size": 5003, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/instance/resource.hpp", "max_stars_repo_name": "kit-algo/TCPSPSuite", "max_stars_repo_head_hexsha": "01499b4fb0f28bda72115a699cd762c70d7fff63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-05-02T11:45:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-14T08:35:43.000Z", "max_issues_repo_path": "src/instance/resource.hpp", "max_issues_repo_name": "kit-algo/TCPSPSuite", "max_issues_repo_head_hexsha": "01499b4fb0f28bda72115a699cd762c70d7fff63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/instance/resource.hpp", "max_forks_repo_name": "kit-algo/TCPSPSuite", "max_forks_repo_head_hexsha": "01499b4fb0f28bda72115a699cd762c70d7fff63", "max_forks_repo_licenses": ["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.2655367232, "max_line_length": 79, "alphanum_fraction": 0.7409554267, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.51825576331728}}
{"text": "#include <vector>\n\n#include <glm/glm.hpp>\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n\n#include \"Types.h\"\n#include \"Dynamic.h\"\n\nnamespace BalloonFEM\n{\n    void Engine::computeAirForces(ObjState &state, Vvec3 &f_sum)\n    {\n        /* add air pressure force */\n        for (size_t i = 0; i < m_tetra->holes.size(); i++)\n        {\n            double p = m_air_model->pressure(state.hole_volume[i]);\n            Hole &h = m_tetra->holes[i];\n            std::vector<size_t>::iterator j;\n\n            for (j = h.vertices.begin(); j != h.vertices.end(); j++)\n            {\n                f_sum[*j] += p * state.volume_gradient[*j];\n            }\n        }\n    }\n        \n    SpMat Engine::computeAirDiffMat(ObjState &state)\n    {\n\t    printf(\"building air pressure differential matrix \\n\");\n\t\t/* project from constrained freedom state to world space */\n\t\tVvec3 &pos = state.world_space_pos;\n\n\t\t/* compute air pressure force differential matrix */\n\t\tSpMat E = state.volumeGradientDiffMat();\n\n\t\tstd::vector<T> pressure;\n\t\tpressure.reserve(pos.size());\n\t\tfor (size_t i = 0; i < m_tetra->holes.size(); i++)\n\t\t{\n\t\t\tdouble p = m_air_model->pressure(state.hole_volume[i]);\n\t\t\tHole &h = m_tetra->holes[i];\n\t\t\tstd::vector<size_t>::iterator j;\n            \n\t\t\t//double dV = 0;\n\t\t\tfor (j = h.vertices.begin(); j != h.vertices.end(); j++)\n\t\t\t{\n\t\t\t\t/* p(V) * dG */\n\t\t\t\tpressure.push_back( T(3 * *j    , 3 * *j    , p) );\n\t\t\t\tpressure.push_back( T(3 * *j + 1, 3 * *j + 1, p) );\n\t\t\t\tpressure.push_back( T(3 * *j + 2, 3 * *j + 2, p) );\n\t\t\t}\n\t\t}\n\t\tSpMat P(3 * pos.size(), 3 * pos.size());\n\t\tP.setFromTriplets(pressure.begin(), pressure.end());\n\t\tE = E * P;\n\n        return E;\n    }\n}\n", "meta": {"hexsha": "2f5de82c6f7b65bc48a60dd1fbf0d2ec156cb9b2", "size": 1668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Dynamic_Air.cpp", "max_stars_repo_name": "milkpku/FEM_practice", "max_stars_repo_head_hexsha": "5498de6c8d99c5336f7aaf0044335d61ffc0a02c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Dynamic_Air.cpp", "max_issues_repo_name": "milkpku/FEM_practice", "max_issues_repo_head_hexsha": "5498de6c8d99c5336f7aaf0044335d61ffc0a02c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Dynamic_Air.cpp", "max_forks_repo_name": "milkpku/FEM_practice", "max_forks_repo_head_hexsha": "5498de6c8d99c5336f7aaf0044335d61ffc0a02c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-10T08:20:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-10T08:20:06.000Z", "avg_line_length": 26.9032258065, "max_line_length": 68, "alphanum_fraction": 0.5587529976, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5182557623899693}}
{"text": "// Testing Jabc for random states\n#include \"../include/Jabc.hpp\"\n#include <armadillo>\n#include <iostream>\n#include <stdlib.h>\n#include <math.h>\n\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char *argv[])\n{\n  int a = atoi(argv[1]);\n  int b = atoi(argv[2]);\n  int c = atoi(argv[3]);\n  int n_q = atoi(argv[4]);\n\n  cx_mat psi_r, psi_i, psi;\n  psi_r.randn(1<<n_q, 1);\n  psi_i.randn(1<<n_q, 1);\n  psi = psi_r + cx_double(0.0, 1.0) * psi_i;\n  \n  \n  psi /= norm(psi);\n\n  cout << Jabc(a,b,c,psi)<< endl;\n}\n", "meta": {"hexsha": "6f4c2e4dd0eb70c7faa2ea4bed833b66bac82c83", "size": 515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_rand.cpp", "max_stars_repo_name": "ikim-quantum/Jabc", "max_stars_repo_head_hexsha": "e98278ecb5daa7f239daadf573a2de36997aa644", "max_stars_repo_licenses": ["MIT"], "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_rand.cpp", "max_issues_repo_name": "ikim-quantum/Jabc", "max_issues_repo_head_hexsha": "e98278ecb5daa7f239daadf573a2de36997aa644", "max_issues_repo_licenses": ["MIT"], "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_rand.cpp", "max_forks_repo_name": "ikim-quantum/Jabc", "max_forks_repo_head_hexsha": "e98278ecb5daa7f239daadf573a2de36997aa644", "max_forks_repo_licenses": ["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.3928571429, "max_line_length": 44, "alphanum_fraction": 0.6174757282, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5181970917622332}}
{"text": "#include \"IKinematics.hpp\"\n\n#include <cmath>\n\n#include <Eigen/Eigen>\n\nusing namespace Eigen;\n\nstatic float crop(float angle)\n{\n   while (angle <= -M_PI) angle += 2*M_PI;\n   while (angle >   M_PI) angle -= 2*M_PI;\n\n   return angle;\n}\n\nnamespace IKinematics\n{\n\n/**\n * (Very) luckily for us, the nao's leg joint chain can be separated out\n * into reasonably simple independent chains. For simplicity, we assume that\n * the chain link from the ankle to the ground in negligible.\n *\n * Define the following:\n *   x:      axis extending forwards from the robot's torso (sagittal plane)\n *   y:      axis extending rightwards of the robot's torso (coronal plane )\n *   z:      axis extending upwards of the robot's torso\n *   rot:    rotation of the foot relative to the x axis, 0 is forward\n *\n * When rot is 0, the x and y chains are easily separable as only the\n * thigh roll can affects the y axis. Therefore\n *\n *    thighRoll = atan2(z, y)\n *\n * Two joints affect the x axis, namely thighPitch and kneePitch. Note\n * however that the chain has been rotated however, and the new target z'\n * is now the hypotenuse of the triangle created by target z y.\n *\n *    z' = cos(thighPitch + kneePitch)thighL + cos(kneePitch)shinL\n *    x  = sin(thighPitch + kneePitch)thighL + sin(kneePitch)shinL\n *\n * It's pretty obvious that there is a periodic solution to the above\n * equations. However, it is a hell of a lot easier just to use the\n * law of cosines to get the angles.\n *\n *  |\\        -     |  We know `thigh', `shin' and the third length of\n *  |A\\ thigh |     |  the triangle is simply hypot(z', x). Villa, solve\n *   | \\      | z'  |  for B and you're done.\n *   | B\\     |     |\n *    |C/     |     |  Note that thigh pitch is not the same as A. In\n *    |/ shin -     |  actual fact, it is a lot easier to calculate\n *                  |  thigh pitch by simply substituting the value of\n *  |-|             |  knee pitch into the above equations.\n *    x             |\n *\n * Relating the above logic back to the original equation, we note that\n * kneePos = pi + B. A rather nice result is that B is always positive\n * assuming we take the positive arc-cosine. We do not want to consider\n * the negative case because this would imply the knee is bending backwards.\n *\n * For rotation, note that the only way to rotate the foot in the lateral\n * plane is to alter the hip pitch (the joint is diagonal). Rotating the\n * chain causes the x and y chains to now depend on each other, as the pitch\n * and roll of each joint now affect both x and y. Easy solution, transform\n * the target using the rotation matrix of the hip. Now the x and y axes are\n * independent again.\n *\n * Now to deal with the negligible foot joint, it turns out its actually pretty\n * easy to add to the chain.\n *\n *    let a = thighPitch\n *        b = kneePitch\n *        c = anklePitch\n *\n *    0  = a + b + c\n *    z' = cos(a + b + c)footL + cos(a + b)shinL + cos(a)thighL\n *    x  = sin(a + b + c)footL + sin(a + b)shinL + sin(a)thighL\n *\n * cos(a + b + c) is a constant, so we can simply remove it both sides of\n * the equation and solve using the same triangle as above. Too easy. In\n * the same manner, we can add the ankle roll to the chain to reach our\n * y-target.\n */\n\nNaoLegChain NaoSolve(const NaoFootTarget &target, float left)\n{\n   const float thighL = 0.10000;\n   const float shinL  = 0.10290;\n   const float footL  = 0.04519;\n\n   NaoLegChain r;\n   float x, y, z;\n\n   /* For now assume hip yaw is exactly equal to foot yaw.\n    * Fuck my life http://en.wikipedia.org/wiki/Universal_joint\n    * Well, its actually reasonably linear:\n    * http://www.wolframalpha.com/input/?i=plot+atan(tan(x)/cos(pi/4)))\n    *\n    * This is an expensive operation so dont do it unless we actually need to.\n    */\n   r.hip = target.yaw;\n   if (target.yaw == 0) {\n      x = target.x;\n      y = target.y;\n      z = target.z;\n   } else {\n      Vector3f v(target.x, target.y, target.z);\n      AngleAxis<float> aa(-target.yaw, Vector3f(0, sqrtf(2)/2, sqrtf(2)/2));\n      v = aa * v;\n      x = v.x(); y = v.y(); z = v.z();\n   }\n\n   /* Subtract foot length from target. This can be seen as the vector\n    *    target' = target - Rot_roll * Rot_pitch * foot\n    *\n    * The fact that pitch is applied before roll is due to the robot's\n    * physical design.\n    */ \n\n   x -= footL * sinf(target.pitch);\n   y -= footL * cosf(target.pitch) * sinf(target.roll);\n   z += footL * cosf(target.pitch) * cosf(target.roll);\n\n   r.thighRoll = atan2f(y, -z);\n\n   /* Solve for target.x and target.z */\n   const float z_prime = z / cosf(r.thighRoll);\n   const float h = hypotf(z_prime, x);\n\n   /* A B and C are as above comment */\n   const float A = acosf((shinL*shinL - h*h - thighL*thighL) / (-2*thighL*h));\n   const float B = acosf((h*h - thighL*thighL - shinL*shinL) / (-2*thighL*shinL));\n   r.thighPitch = A + asin(x/h) + 3*M_PI_2;\n   r.kneePitch  = B + M_PI;\n\n   /* Calculate the ankle pitch and roll */\n   r.anklePitch = target.pitch - r.kneePitch - r.thighPitch;\n   r.ankleRoll  = target.roll - r.thighRoll;\n\n   /* Currently all angles are wound counter clockwise from the normal.\n    * Joints on the actual robot each have their own normals. Basically,\n    * when all joint values are set to zero the robot is standing upright.\n    */\n   r.thighPitch = 3*M_PI_2 - r.thighPitch;\n   r.kneePitch  =          - r.kneePitch;\n   r.anklePitch = 1*M_PI_2 - r.anklePitch;\n\n   /* Finally make sure all angles are bound by (-pi, pi] */\n   r.hip        = crop(r.hip       );\n   r.thighRoll  = crop(r.thighRoll );\n   r.thighPitch = crop(r.thighPitch);\n   r.kneePitch  = crop(r.kneePitch );\n   r.ankleRoll  = crop(r.ankleRoll );\n   r.anklePitch = crop(r.anklePitch);\n\n   return r;\n}\n\nstd::ostream &operator <<(std::ostream &out, const NaoLegChain &chain)\n{\n   out << \"chain.hip        = \" << chain.hip        << std::endl;\n   out << \"chain.thighRoll  = \" << chain.thighRoll  << std::endl;\n   out << \"chain.thighPitch = \" << chain.thighPitch << std::endl;\n   out << \"chain.kneePitch  = \" << chain.kneePitch  << std::endl;\n   out << \"chain.ankleRoll  = \" << chain.ankleRoll  << std::endl;\n   out << \"chain.anklePitch = \" << chain.anklePitch << std::endl;\n\n   return out;\n}\n\n\nstd::ostream &operator <<(std::ostream &out, const NaoFootTarget &target)\n{\n   out << \"x     =\" << target.x     << std::endl;\n   out << \"y     =\" << target.y     << std::endl;\n   out << \"z     =\" << target.z     << std::endl;\n   out << \"pitch =\" << target.pitch << std::endl;\n   out << \"roll  =\" << target.roll  << std::endl;\n   out << \"yaw   =\" << target.yaw   << std::endl;\n\n   return out;\n}\n\n} /* namespace IKinematics */\n\n", "meta": {"hexsha": "9ea69708cd9dc1b80b86d21b60f1a96243171b74", "size": 6641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Core/External/unsw/unsw/motion/IKinematics.cpp", "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/motion/IKinematics.cpp", "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/motion/IKinematics.cpp", "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": 35.513368984, "max_line_length": 82, "alphanum_fraction": 0.6258093661, "num_tokens": 1961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.518197087710692}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 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_ARCH_COMMON_FUNCTION_SCALAR_ACOSH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_ACOSH_HPP_INCLUDED\n\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/constant/oneotwoeps.hpp>\n#include <boost/simd/function/scalar/log.hpp>\n#include <boost/simd/function/scalar/log1p.hpp>\n#include <boost/simd/function/scalar/minusone.hpp>\n#include <boost/simd/function/scalar/sqr.hpp>\n#include <boost/simd/function/scalar/sqrt.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( acosh_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 t = minusone(a0);\n      if(BOOST_LIKELY(t <= Oneotwoeps<A0>()))\n        return log1p(t+bs::sqrt(t+t+sqr(t)));\n      else\n        return log(t)+Log_2<A0>();\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "9ad2a8234ccbb96dcf09066d37c52833aa2b30c1", "size": 1543, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/acosh.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/arch/common/scalar/function/acosh.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/arch/common/scalar/function/acosh.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": 32.1458333333, "max_line_length": 100, "alphanum_fraction": 0.5793907971, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5181970836591506}}
{"text": "#include <Eigen/Geometry>\n#include <iostream>\n\n#include \"align/rigid_pipe.h\"\n#include \"face/model.h\"\n#include \"util/eigen_pcl.h\"\n\nusing namespace std;\nusing namespace telef::feature;\nusing namespace telef::types;\nusing namespace telef::face;\n\nnamespace telef::align {\n\nPCARigidFittingPipe::PCARigidFittingPipe() :\n    m_prev_scale(0.0f)\n{}\n\nboost::shared_ptr<PCANonRigidAlignmentSuite> PCARigidFittingPipe::_processData(\n    boost::shared_ptr<PCANonRigidAlignmentSuite> in) {\n  std::vector<int> pca_lmks = in->pca_model->getLandmarks();\n  auto in_lmks = in->fittingSuite->landmark3d;\n\n  Eigen::VectorXf ref =\n    in->pca_model->genPosition(in->shapeCoeff, in->expressionCoeff);\n  Eigen::Matrix3Xf mesh_pts_t =\n      Eigen::Map<Eigen::Matrix3Xf>(ref.data(), 3, ref.size() / 3);\n  std::vector<int> selection = {\n                                0, 1, 2, 3,\n                                13, 14, 15, 16,\n                                27, 28, 29, 30,\n                                33, 36, 39, 42, 45};\n  Eigen::MatrixXf mesh_lmk_pts(selection.size(), 3);\n\n  for (int i = 0; i < selection.size(); i++) {\n    mesh_lmk_pts.row(i) = mesh_pts_t.col(pca_lmks[selection[i]]);\n  }\n\n  Eigen::MatrixXf lmk_pts(selection.size(), 3);\n  for (int i = 0; i < selection.size(); i++) {\n    lmk_pts(i, 0) = in_lmks->points[selection[i]].x;\n    lmk_pts(i, 1) = in_lmks->points[selection[i]].y;\n    lmk_pts(i, 2) = in_lmks->points[selection[i]].z;\n  }\n\n  Eigen::MatrixXf transformation;\n  if(m_prev_scale == 0.0f)\n    {\n      transformation = Eigen::umeyama(mesh_lmk_pts.transpose(), lmk_pts.transpose());\n      m_prev_scale = transformation.block(0,0,3,0).norm();\n    }\n  else\n    {\n      transformation = Eigen::umeyama(\n          m_prev_scale*mesh_lmk_pts.transpose(), lmk_pts.transpose(), false);\n      transformation.block(0,0,3,3) *= m_prev_scale;\n    }\n\n  in->transformation = transformation;\n  return in;\n}\n} // namespace telef::align\n", "meta": {"hexsha": "2802c01e70f58f16c7794b6addd64f570899559a", "size": 1924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/align/rigid_pipe.cpp", "max_stars_repo_name": "ycjungSubhuman/Kinect-Face", "max_stars_repo_head_hexsha": "b582bd8572e998617b5a0d197b4ac9bd4a9b42be", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-12T22:05:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T08:39:32.000Z", "max_issues_repo_path": "src/align/rigid_pipe.cpp", "max_issues_repo_name": "ycjungSubhuman/Kinect-Face", "max_issues_repo_head_hexsha": "b582bd8572e998617b5a0d197b4ac9bd4a9b42be", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/align/rigid_pipe.cpp", "max_forks_repo_name": "ycjungSubhuman/Kinect-Face", "max_forks_repo_head_hexsha": "b582bd8572e998617b5a0d197b4ac9bd4a9b42be", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-14T08:29:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-01T07:11:17.000Z", "avg_line_length": 30.5396825397, "max_line_length": 85, "alphanum_fraction": 0.632016632, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436727, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.5181839904649178}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2007-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\r\n#include <geometry_test_common.hpp>\r\n\r\n\r\n#include <boost/geometry/algorithms/assign.hpp>\r\n\r\n\r\n#include <boost/geometry/strategies/spherical/side_by_cross_track.hpp>\r\n//#include <boost/geometry/strategies/spherical/side_via_plane.hpp>\r\n#include <boost/geometry/strategies/spherical/ssf.hpp>\r\n#include <boost/geometry/strategies/cartesian/side_by_triangle.hpp>\r\n\r\n#include <boost/geometry/core/cs.hpp>\r\n\r\n#include <boost/geometry/geometries/point.hpp>\r\n#include <boost/geometry/geometries/segment.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry {\r\n\r\ntemplate <typename Vector, typename Point1, typename Point2>\r\nstatic inline Vector create_vector(Point1 const& p1, Point2 const& p2)\r\n{\r\n    Vector v;\r\n    convert(p1, v);\r\n    subtract_point(v, p2);\r\n    return v;\r\n}\r\n\r\n}}\r\n\r\ninline char side_char(int side)\r\n{\r\n    return side == 1 ? 'L'\r\n        : side == -1 ? 'R'\r\n        : '-'\r\n        ;\r\n}\r\n\r\ntemplate <typename Point>\r\nvoid test_side1(std::string const& case_id, Point const& p1, Point const& p2, Point const& p3,\r\n                   int expected, int expected_cartesian)\r\n{\r\n    // std::cout << case_id << \": \";\r\n    //int s = bg::strategy::side::side_via_plane<>::apply(p1, p2, p3);\r\n    int side_ssf = bg::strategy::side::spherical_side_formula<>::apply(p1, p2, p3);\r\n    //int side2 = bg::strategy::side::side_via_plane<>::apply(p1, p2, p3);\r\n    int side_ct = bg::strategy::side::side_by_cross_track<>::apply(p1, p2, p3);\r\n\r\n    typedef bg::strategy::side::services::default_strategy<bg::cartesian_tag>::type cartesian_strategy;\r\n    int side_cart = cartesian_strategy::apply(p1, p2, p3);\r\n\r\n\r\n    BOOST_CHECK_EQUAL(side_ssf, expected);\r\n    BOOST_CHECK_EQUAL(side_ct, expected);\r\n    BOOST_CHECK_EQUAL(side_cart, expected_cartesian);\r\n    /*\r\n    std::cout \r\n        << \"exp: \" << side_char(expected)\r\n        << \" ssf: \" << side_char(side1)\r\n        << \" pln: \" << side_char(side2)\r\n        << \" ct: \" << side_char(side3)\r\n        //<< \" def: \" << side_char(side4)\r\n        << \" cart: \" << side_char(side5)\r\n        << std::endl;\r\n    */\r\n}\r\n\r\ntemplate <typename Point>\r\nvoid test_side(std::string const& case_id, Point const& p1, Point const& p2, Point const& p3,\r\n                   int expected, int expected_cartesian = -999)\r\n{\r\n    if (expected_cartesian == -999)\r\n    {\r\n        expected_cartesian = expected;\r\n    }\r\n    test_side1(case_id, p1, p2, p3, expected, expected_cartesian);\r\n    test_side1(case_id, p2, p1, p3, -expected, -expected_cartesian);\r\n}\r\n\r\n\r\ntemplate <typename Point>\r\nvoid test_all()\r\n{\r\n    typedef std::pair<double, double> pair;\r\n\r\n    Point amsterdam(5.9, 52.4);\r\n    Point barcelona(2.0, 41.0);\r\n    Point paris(2.0, 48.0);\r\n    Point milan(7.0, 45.0);\r\n\r\n    //goto wrong;\r\n\r\n    test_side<Point>(\"bp-m\", barcelona, paris, milan, -1);\r\n    test_side<Point>(\"bm-p\", barcelona, milan, paris, 1);\r\n    test_side<Point>(\"mp-b\", milan, paris, barcelona, 1);\r\n\r\n    test_side<Point>(\"am-p\", amsterdam, milan, paris, -1);\r\n    test_side<Point>(\"pm-a\", paris, milan, amsterdam, 1);\r\n\r\n    // http://www.gcmap.com/mapui?P=30N+10E-50N+50E,39N+30E\r\n    Point gcmap_p1(10.0, 30.0);\r\n    Point gcmap_p2(50.0, 50.0);\r\n    test_side<Point>(\"blog1\", gcmap_p1, gcmap_p2, Point(30.0, 41.0), -1, 1);\r\n    test_side<Point>(\"blog1\", gcmap_p1, gcmap_p2, Point(30.0, 42.0), -1, 1);\r\n    test_side<Point>(\"blog1\", gcmap_p1, gcmap_p2, Point(30.0, 43.0), -1, 1);\r\n    test_side<Point>(\"blog1\", gcmap_p1, gcmap_p2, Point(30.0, 44.0), 1);\r\n\r\n    // http://www.gcmap.com/mapui?P=50N+80E-60N+50W,65N+30E\r\n    Point gcmap_np1(80.0, 50.0);\r\n    Point gcmap_np2(-50.0, 60.0);\r\n    // http://www.gcmap.com/mapui?P=50N+140E-60N+10E,65N+30E\r\n    //Point gcmap_np1(140.0, 50.0);\r\n    //Point gcmap_np2(10.0, 60.0);\r\n    //test_side<Point>(gcmap_np1, gcmap_np2, gcmap_np, 1);\r\n    test_side<Point>(\"40\", gcmap_np1, gcmap_np2, Point(30.0, 60.0), 1, -1);\r\n    test_side<Point>(\"45\", gcmap_np1, gcmap_np2, Point(30.0, 65.0), 1, -1);\r\n    test_side<Point>(\"70\", gcmap_np1, gcmap_np2, Point(30.0, 70.0), 1, -1);\r\n    test_side<Point>(\"75\", gcmap_np1, gcmap_np2, Point(30.0, 75.0), -1);\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n    test_all<bg::model::point<int, 2, bg::cs::spherical<bg::degree> > >();\r\n    test_all<bg::model::point<double, 2, bg::cs::spherical_equatorial<bg::degree> > >();\r\n\r\n#if defined(HAVE_TTMATH)\r\n    typedef ttmath::Big<1,4> tt;\r\n    test_all<bg::model::point<tt, 2, bg::cs::spherical_equatorial<bg::degree> > >();\r\n#endif\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "40d803a1e45cd782fa7bcff36651eb00b7b5910d", "size": 4810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/strategies/spherical_side.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/test/strategies/spherical_side.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/test/strategies/spherical_side.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": 33.6363636364, "max_line_length": 104, "alphanum_fraction": 0.632016632, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5181305752720581}}
{"text": "// test file for special functions.\r\n\r\n//  (C) Copyright Hubert Holin 2003. Permission to copy, use, modify, sell and\r\n//  distribute this software is granted provided this copyright notice appears\r\n//  in all copies. This software is provided \"as is\" without express or implied\r\n//  warranty, and with no claim as to its suitability for any purpose.\r\n\r\n\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <functional>\r\n\r\n\r\n#include <boost/bind.hpp>\r\n#include <boost/function.hpp>\r\n\r\n\r\n#include <boost/test/unit_test_suite_ex.hpp>\r\n\r\n\r\n#include \"sinc_test.hpp\"\r\n#include \"sinhc_test.hpp\"\r\n#include \"atanh_test.hpp\"\r\n#include \"asinh_test.hpp\"\r\n#include \"acosh_test.hpp\"\r\n\r\n\r\n\r\nboost::unit_test_framework::test_suite *    init_unit_test_suite(int, char *[])\r\n{\r\n    //::boost::unit_test_framework::unit_test_log::instance().\r\n    //    set_log_threshold_level_by_name(\"messages\");\r\n    \r\n    boost::unit_test_framework::test_suite *    test =\r\n        BOOST_TEST_SUITE(\"special_functions_test\");\r\n    \r\n#define    BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(fct,type)    \\\r\n    test->add(BOOST_TEST_CASE(::boost::bind(static_cast          \\\r\n        < void (*) (const char *) >(&fct##_test<type>), #type)));\r\n    \r\n    \r\n#define    BOOST_SPECIAL_FUNCTIONS_COMMON_TEST(type)        \\\r\n    BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(atanh,type)    \\\r\n    BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(asinh,type)    \\\r\n    BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(acosh,type)    \\\r\n    BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(sinc_pi,type)  \\\r\n    BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(sinhc_pi,type)\r\n    \r\n    \r\n#define    BOOST_SPECIAL_FUNCTIONS_TEMPLATE_TEMPLATE_TEST(type)      \\\r\n    BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(sinc_pi_complex,type)   \\\r\n    BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(sinhc_pi_complex,type)\r\n    \r\n    \r\n#ifdef    BOOST_NO_TEMPLATE_TEMPLATES\r\n\r\n#define    BOOST_SPECIAL_FUNCTIONS_TEST(type)                                 \\\r\n    BOOST_SPECIAL_FUNCTIONS_COMMON_TEST(type)                                 \\\r\n    BOOST_MESSAGE(\"Warning: no template templates; curtailed functionality.\");\r\n    \r\n#else    /* BOOST_NO_TEMPLATE_TEMPLATES */\r\n\r\n#define    BOOST_SPECIAL_FUNCTIONS_TEST(type)            \\\r\n    BOOST_SPECIAL_FUNCTIONS_COMMON_TEST(type)            \\\r\n    BOOST_SPECIAL_FUNCTIONS_TEMPLATE_TEMPLATE_TEST(type)\r\n    \r\n#endif    /* BOOST_NO_TEMPLATE_TEMPLATES */\r\n    \r\n    \r\n    BOOST_SPECIAL_FUNCTIONS_TEST(float)\r\n    BOOST_SPECIAL_FUNCTIONS_TEST(double)\r\n    BOOST_SPECIAL_FUNCTIONS_TEST(long double)\r\n    \r\n    \r\n#undef    BOOST_SPECIAL_FUNCTIONS_TEST\r\n\r\n#undef    BOOST_SPECIAL_FUNCTIONS_TEMPLATE_TEMPLATE_TEST\r\n    \r\n#undef    BOOST_SPECIAL_FUNCTIONS_COMMON_TEST\r\n\r\n#undef    BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR\r\n    \r\n    \r\n#ifdef    BOOST_SPECIAL_FUNCTIONS_TEST_VERBOSE\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    BOOST_MESSAGE(\"epsilon\");\r\n    \r\n    BOOST_MESSAGE( ::std::setw(15) << numeric_limits<float>::epsilon()\r\n                << ::std::setw(15) << numeric_limits<double>::epsilon()\r\n                << ::std::setw(15) << numeric_limits<long double>::epsilon());\r\n    \r\n    BOOST_MESSAGE(\" \");\r\n    \r\n    atanh_manual_check();\r\n    asinh_manual_check();\r\n    acosh_manual_check();\r\n    sinc_pi_manual_check();\r\n    sinhc_pi_manual_check();\r\n    \r\n#endif    /* BOOST_SPECIAL_FUNCTIONS_TEST_VERBOSE */\r\n    \r\n    return(test);\r\n}\r\n\r\n", "meta": {"hexsha": "62f04da917bc10b6a500528a33345940bf7c2787", "size": 3396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/special_functions_test.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/special_functions_test.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/libs/math/special_functions/special_functions_test.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.738317757, "max_line_length": 80, "alphanum_fraction": 0.6775618375, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5181305748345311}}
{"text": "/*\n * Taken from http://www.andrew.cmu.edu/user/vanhoeve/mdd/ with the notice:\n * \"The software can be freely used but comes with no warranty\"\n * -----------------------------------------------------------\n * Data structure to store positive sets of integers.\n\n * Should be used in the cases where one needs to do\n * fast intersections and unions, and does not iterate\n * on all elements too many times.\n * -----------------------------------------------------------\n */\n\n#ifndef INTSET_HPP_\n#define INTSET_HPP_\n\n#define NOT_COMPUTED -1     /**< indicates if the size was not computed */\n\n#include <boost/dynamic_bitset.hpp>\n#include <cassert>\n#include <iostream>\n#include <fstream>\n#include \"util.hpp\"\n\n\n/**\n * Integer Set structure\n */\nstruct IntSet {\n\n    /** Constructor */\n    IntSet(int _min, int _max, bool _filled);\n\n    /** Empty constructor */\n    IntSet();\n\n    /** Check if set contains element */\n    bool contains(int elem);\n\n    /** Add an element to the set */\n    void add(int elem);\n\n    /** Add all possible elements to the set */\n    void add_all_elements();\n\n    /** Remove element, if it is contained */\n    void remove(int elem);\n\n    /** Get number of elements in the set */\n    int get_size();\n\n    /** Get the first element of the set */\n    int get_first();\n\n    /** Get next element higher than the one passed as parameter */\n    int get_next(int elem);\n\n    /** Get end of the set (beyond last element) */\n    const int get_end();\n\n    /** Clear set */\n    void clear();\n\n    /** Resize */\n    void resize(int _min, int _max, bool _filled);\n\n    /** Take the union with another intset */\n    void union_with(IntSet& intset);\n\n    /** Take the intersection with another intset */\n    void intersect_with(IntSet& intset);\n    \n    /** Checks if one intersects with the other intset */\n    void does_intersect(IntSet& intset);\n    \n    /** Assignment operator */\n    IntSet& operator=(const IntSet& rhs);\n    \n    /** Returns if set is a subset of another */\n    bool is_subset(const IntSet& other);\n\n    /** Returns if one set equals another */\n    bool equals_to(const IntSet& other);\n\n\n    // parameters\n\n    boost::dynamic_bitset<>     set;            /**< bitvector representing the set */\n    const int                   end;            /**< position beyond end of the set */\n    int                         size;           /**< number of elements in the set */\n    int                         min;            /**< minimum possible element of the set */\n    int                         max;            /**< maximum possible element of the set */\n    //int                         shift;          /**< shift of element to be added in the set */\n};\n\n\n/**\n * Lexicographic comparator function for IntSet class.\n */\nstruct IntSetLexLessThan {\n    bool operator()(const IntSet* setA, const IntSet* setB) const {\n        return setA->set < setB->set;\n    }\n};\n\n\n\n/**\n * -----------------------------------------------\n * Inline implementations\n * -----------------------------------------------\n */\n\n/**\n * Constructor\n */\ninline IntSet::IntSet(int _min, int _max, bool _filled) : end((int)set.npos) {\n    resize(_min, _max, _filled);\n    size = NOT_COMPUTED;\n}\n\n/**\n * Empty constructor\n */\ninline IntSet::IntSet() : end((int)set.npos) {\n}\n\n\n/**\n * Add an element to the set\n */\ninline bool IntSet::contains(int elem) {\n    assert( elem >= min && elem <= max );\n    return( set.test(elem) );\n}\n\n\n/**\n * Add an element to the set\n */\ninline void IntSet::add(int elem) {\n    assert( elem >= min && elem <= max );\n    set.set(elem, true);\n    size = NOT_COMPUTED;\n}\n\n/** Remove element, if it is contained */\ninline void IntSet::remove(int elem) {\n    assert( elem >= min && elem <= max );\n    set.set(elem, false);\n    size = NOT_COMPUTED;\n}\n\n/**\n * Get the first element of the set\n */\ninline int IntSet::get_first() {\n    return (set.find_first());\n}\n\n/**\n * Get next element higher than the one passed as parameter\n */\ninline int IntSet::get_next(int elem) {\n    assert( elem >= min && elem <= max );\n    return (set.find_next(elem));\n}\n\n/**\n * Get end of the set (beyond last element)\n */\ninline const int IntSet::get_end() {\n    return end;\n}\n\n/**\n * Clear set\n */\ninline void IntSet::clear() {\n    set.reset();\n    size = 0;\n}\n\n\n/**\n * Assignment operator\n */\ninline IntSet& IntSet::operator=(const IntSet& rhs) {\n    assert(rhs.max == max && rhs.min == min);\n    if (this != &rhs) {\n        set = rhs.set;\n        size = NOT_COMPUTED;\n    }\n    return *this;\n}\n\n\n/**\n * Resize\n */\ninline void IntSet::resize(int _min, int _max, bool _filled) {\n\n\tif( _min != 0 ) {\n\t\texit(1);\n\t}\n\n    min = _min;\n    max = _max;\n\n    set.resize(max - min + 1);\n\n    if( _filled )\n        set.set();\n    else\n        set.reset();\n\n    size = NOT_COMPUTED;\n}\n\n/**\n * Take the union with another intset\n */\ninline void IntSet::union_with(IntSet& intset) {\n    set |= intset.set;\n    size = NOT_COMPUTED;\n}\n\n/**\n * Take the intersection with another intset\n */\ninline void IntSet::intersect_with(IntSet& intset) {\n    set &= intset.set;\n    size = NOT_COMPUTED;\n}\n\n/** Get number of elements in the set */\ninline int IntSet::get_size() {\n    if( size == NOT_COMPUTED ) {\n        size = set.count();\n    }\n    return size;\n}\n\n/**\n * Add all possible elements to the set\n */\ninline void IntSet::add_all_elements() {\n    set.set();\n    size = set.size();\n}\n\n\n/**\n * Stream output function\n */\ninline std::ostream& operator<<(std::ostream &os, IntSet &intset) {\n    os << \"[ \";\n    int val = intset.get_first();\n    while( val != intset.get_end() ) {\n        os << val << \" \";\n        val = intset.get_next(val);\n    }\n    os << \"]\";\n    return os;\n}\n\n\n/** \n * Returns if set is a subset of another \n */\ninline bool IntSet::is_subset(const IntSet& other) {\n    return set.is_subset_of(other.set);\n}\n\n/**\n * Returns if one is equal to the other\n */\ninline bool IntSet::equals_to(const IntSet& other) {\n\treturn (set == other.set);\n}\n\n\n\n#endif /* INTSET_HPP_ */\n\n", "meta": {"hexsha": "046b5710f3b69230bb90e65042ac71177f721d66", "size": 5966, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "models/misp-random/code/include/dd/intset.hpp", "max_stars_repo_name": "qcappart/learning-DD", "max_stars_repo_head_hexsha": "93094c450f8f0929168b303b4d0680889deeb9b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T20:04:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T19:31:36.000Z", "max_issues_repo_path": "models/misp-random/code/include/dd/intset.hpp", "max_issues_repo_name": "qcappart/learning-DD", "max_issues_repo_head_hexsha": "93094c450f8f0929168b303b4d0680889deeb9b0", "max_issues_repo_licenses": ["MIT"], "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/misp-random/code/include/dd/intset.hpp", "max_forks_repo_name": "qcappart/learning-DD", "max_forks_repo_head_hexsha": "93094c450f8f0929168b303b4d0680889deeb9b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-07-26T01:22:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T13:48:18.000Z", "avg_line_length": 20.9333333333, "max_line_length": 97, "alphanum_fraction": 0.5709017767, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5181305666233474}}
{"text": "\n#include <NTL/mat_ZZ.h>\n\n\nNTL_START_IMPL\n\n\nvoid add(mat_ZZ& X, const mat_ZZ& A, const mat_ZZ& B)  \n{  \n   long n = A.NumRows();  \n   long m = A.NumCols();  \n  \n   if (B.NumRows() != n || B.NumCols() != m)   \n      LogicError(\"matrix add: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n  \n   long i, j;  \n   for (i = 1; i <= n; i++)   \n      for (j = 1; j <= m; j++)  \n         add(X(i,j), A(i,j), B(i,j));  \n}  \n  \nvoid sub(mat_ZZ& X, const mat_ZZ& A, const mat_ZZ& B)  \n{  \n   long n = A.NumRows();  \n   long m = A.NumCols();  \n  \n   if (B.NumRows() != n || B.NumCols() != m)  \n      LogicError(\"matrix sub: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n  \n   long i, j;  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= m; j++)  \n         sub(X(i,j), A(i,j), B(i,j));  \n}  \n  \nvoid mul_aux(mat_ZZ& X, const mat_ZZ& A, const mat_ZZ& B)  \n{  \n   long n = A.NumRows();  \n   long l = A.NumCols();  \n   long m = B.NumCols();  \n  \n   if (l != B.NumRows())  \n      LogicError(\"matrix mul: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n  \n   long i, j, k;  \n   ZZ acc, tmp;  \n  \n   for (i = 1; i <= n; i++) {  \n      for (j = 1; j <= m; j++) {  \n         clear(acc);  \n         for(k = 1; k <= l; k++) {  \n            mul(tmp, A(i,k), B(k,j));  \n            add(acc, acc, tmp);  \n         }  \n         X(i,j) = acc;  \n      }  \n   }  \n}  \n  \n  \nvoid mul(mat_ZZ& X, const mat_ZZ& A, const mat_ZZ& B)  \n{  \n   if (&X == &A || &X == &B) {  \n      mat_ZZ tmp;  \n      mul_aux(tmp, A, B);  \n      X = tmp;  \n   }  \n   else  \n      mul_aux(X, A, B);  \n}  \n  \n  \nstatic\nvoid mul_aux(vec_ZZ& x, const mat_ZZ& A, const vec_ZZ& b)  \n{  \n   long n = A.NumRows();  \n   long l = A.NumCols();  \n  \n   if (l != b.length())  \n      LogicError(\"matrix mul: dimension mismatch\");  \n  \n   x.SetLength(n);  \n  \n   long i, k;  \n   ZZ acc, tmp;  \n  \n   for (i = 1; i <= n; i++) {  \n      clear(acc);  \n      for (k = 1; k <= l; k++) {  \n         mul(tmp, A(i,k), b(k));  \n         add(acc, acc, tmp);  \n      }  \n      x(i) = acc;  \n   }  \n}  \n  \n  \nvoid mul(vec_ZZ& x, const mat_ZZ& A, const vec_ZZ& b)  \n{  \n   if (&b == &x || A.alias(x)) {\n      vec_ZZ tmp;\n      mul_aux(tmp, A, b);\n      x = tmp;\n   }\n   else\n      mul_aux(x, A, b);\n}  \n\nstatic\nvoid mul_aux(vec_ZZ& x, const vec_ZZ& a, const mat_ZZ& B)  \n{  \n   long n = B.NumRows();  \n   long l = B.NumCols();  \n  \n   if (n != a.length())  \n      LogicError(\"matrix mul: dimension mismatch\");  \n  \n   x.SetLength(l);  \n  \n   long i, k;  \n   ZZ acc, tmp;  \n  \n   for (i = 1; i <= l; i++) {  \n      clear(acc);  \n      for (k = 1; k <= n; k++) {  \n         mul(tmp, a(k), B(k,i));\n         add(acc, acc, tmp);  \n      }  \n      x(i) = acc;  \n   }  \n}  \n\nvoid mul(vec_ZZ& x, const vec_ZZ& a, const mat_ZZ& B)\n{\n   if (&a == &x) { \n      vec_ZZ tmp;\n      mul_aux(tmp, a, B);\n      x = tmp;\n   }\n   else\n      mul_aux(x, a, B);\n}\n\n     \n  \nvoid ident(mat_ZZ& X, long n)  \n{  \n   X.SetDims(n, n);  \n   long i, j;  \n  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= n; j++)  \n         if (i == j)  \n            set(X(i, j));  \n         else  \n            clear(X(i, j));  \n} \n\nstatic\nlong DetBound(const mat_ZZ& a)\n{\n   long n = a.NumRows();\n   long i;\n   ZZ res, t1;\n\n   set(res);\n\n   for (i = 0; i < n; i++) {\n      InnerProduct(t1, a[i], a[i]);\n      if (t1 > 1) {\n         SqrRoot(t1, t1);\n         add(t1, t1, 1);\n      }\n      mul(res, res, t1);\n   }\n\n   return NumBits(res);\n}\n\n\n\n   \n\nvoid determinant(ZZ& rres, const mat_ZZ& a, long deterministic)\n{\n   long n = a.NumRows();\n   if (a.NumCols() != n)\n      LogicError(\"determinant: nonsquare matrix\");\n\n   if (n == 0) {\n      set(rres);\n      return;\n   }\n\n   zz_pBak zbak;\n   zbak.save();\n\n   ZZ_pBak Zbak;\n   Zbak.save();\n\n   long instable = 1;\n\n   long gp_cnt = 0;\n\n   long bound = 2+DetBound(a);\n\n   ZZ res, prod;\n\n   clear(res);\n   set(prod);\n\n\n   long i;\n   for (i = 0; ; i++) {\n      if (NumBits(prod) > bound)\n         break;\n\n      if (!deterministic &&\n          !instable && bound > 1000 && NumBits(prod) < 0.25*bound) {\n         ZZ P;\n\n\n         long plen = 90 + NumBits(max(bound, NumBits(res)));\n         GenPrime(P, plen, 90 + 2*NumBits(gp_cnt++));\n\n         ZZ_p::init(P);\n\n         mat_ZZ_p A;\n         conv(A, a);\n\n         ZZ_p t;\n         determinant(t, A);\n\n         if (CRT(res, prod, rep(t), P))\n            instable = 1;\n         else\n            break;\n      }\n\n\n      zz_p::FFTInit(i);\n      long p = zz_p::modulus();\n\n      mat_zz_p A;\n      conv(A, a);\n\n      zz_p t;\n      determinant(t, A);\n\n      instable = CRT(res, prod, rep(t), p);\n   }\n\n   rres = res;\n\n   zbak.restore();\n   Zbak.restore();\n}\n\n\n\n\nvoid conv(mat_zz_p& x, const mat_ZZ& a)\n{\n   long n = a.NumRows();\n   long m = a.NumCols();\n   long i;\n\n   x.SetDims(n, m);\n   for (i = 0; i < n; i++)\n      conv(x[i], a[i]);\n}\n\nvoid conv(mat_ZZ_p& x, const mat_ZZ& a)\n{\n   long n = a.NumRows();\n   long m = a.NumCols();\n   long i;\n\n   x.SetDims(n, m);\n   for (i = 0; i < n; i++)\n      conv(x[i], a[i]);\n}\n\nlong IsIdent(const mat_ZZ& A, long n)\n{\n   if (A.NumRows() != n || A.NumCols() != n)\n      return 0;\n\n   long i, j;\n\n   for (i = 1; i <= n; i++)\n      for (j = 1; j <= n; j++)\n         if (i != j) {\n            if (!IsZero(A(i, j))) return 0;\n         }\n         else {\n            if (!IsOne(A(i, j))) return 0;\n         }\n\n   return 1;\n}\n\n\nvoid transpose(mat_ZZ& X, const mat_ZZ& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   long i, j;\n\n   if (&X == & A) {\n      if (n == m)\n         for (i = 1; i <= n; i++)\n            for (j = i+1; j <= n; j++)\n               swap(X(i, j), X(j, i));\n      else {\n         mat_ZZ tmp;\n         tmp.SetDims(m, n);\n         for (i = 1; i <= n; i++)\n            for (j = 1; j <= m; j++)\n               tmp(j, i) = A(i, j);\n         X.kill();\n         X = tmp;\n      }\n   }\n   else {\n      X.SetDims(m, n);\n      for (i = 1; i <= n; i++)\n         for (j = 1; j <= m; j++)\n            X(j, i) = A(i, j);\n   }\n}\n\nlong CRT(mat_ZZ& gg, ZZ& a, const mat_zz_p& G)\n{\n   long n = gg.NumRows();\n   long m = gg.NumCols();\n\n   if (G.NumRows() != n || G.NumCols() != m)\n      LogicError(\"CRT: dimension mismatch\");\n\n   long p = zz_p::modulus();\n\n   ZZ new_a;\n   mul(new_a, a, p);\n\n   long a_inv;\n   a_inv = rem(a, p);\n   a_inv = InvMod(a_inv, p);\n\n   long p1;\n   p1 = p >> 1;\n\n   ZZ a1;\n   RightShift(a1, a, 1);\n\n   long p_odd = (p & 1);\n\n   long modified = 0;\n\n   long h;\n\n   ZZ g;\n   long i, j;\n\n   for (i = 0; i < n; i++) {\n      for (j = 0; j < m; j++) {\n         if (!CRTInRange(gg[i][j], a)) {\n            modified = 1;\n            rem(g, gg[i][j], a);\n            if (g > a1) sub(g, g, a);\n         }\n         else\n            g = gg[i][j];\n      \n         h = rem(g, p);\n         h = SubMod(rep(G[i][j]), h, p);\n         h = MulMod(h, a_inv, p);\n         if (h > p1)\n            h = h - p;\n      \n         if (h != 0) {\n            modified = 1;\n\n            if (!p_odd && g > 0 && (h == p1))\n               MulSubFrom(g, a, h);\n            else\n               MulAddTo(g, a, h);\n\n         }\n   \n         gg[i][j] = g;\n      }\n   }\n\n   a = new_a;\n\n   return modified;\n\n}\n\n\nvoid mul(mat_ZZ& X, const mat_ZZ& A, const ZZ& b_in)\n{\n   ZZ b = b_in;\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(n, m);\n\n   long i, j;\n   for (i = 0; i < n; i++)\n      for (j = 0; j < m; j++)\n         mul(X[i][j], A[i][j], b);\n}\n\nvoid mul(mat_ZZ& X, const mat_ZZ& A, long b)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(n, m);\n\n   long i, j;\n   for (i = 0; i < n; i++)\n      for (j = 0; j < m; j++)\n         mul(X[i][j], A[i][j], b);\n}\n\n\nstatic\nvoid ExactDiv(vec_ZZ& x, const ZZ& d)\n{\n   long n = x.length();\n   long i;\n\n   for (i = 0; i < n; i++)\n      if (!divide(x[i], x[i], d))\n         ArithmeticError(\"inexact division\");\n}\n\nstatic\nvoid ExactDiv(mat_ZZ& x, const ZZ& d)\n{\n   long n = x.NumRows();\n   long m = x.NumCols();\n   \n   long i, j;\n\n   for (i = 0; i < n; i++)\n      for (j = 0; j < m; j++)\n         if (!divide(x[i][j], x[i][j], d))\n            ArithmeticError(\"inexact division\");\n}\n\nvoid diag(mat_ZZ& X, long n, const ZZ& d_in)  \n{  \n   ZZ d = d_in;\n   X.SetDims(n, n);  \n   long i, j;  \n  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= n; j++)  \n         if (i == j)  \n            X(i, j) = d;  \n         else  \n            clear(X(i, j));  \n} \n\nlong IsDiag(const mat_ZZ& A, long n, const ZZ& d)\n{\n   if (A.NumRows() != n || A.NumCols() != n)\n      return 0;\n\n   long i, j;\n\n   for (i = 1; i <= n; i++)\n      for (j = 1; j <= n; j++)\n         if (i != j) {\n            if (!IsZero(A(i, j))) return 0;\n         }\n         else {\n            if (A(i, j) != d) return 0;\n         }\n\n   return 1;\n}\n\n\n\n\nvoid solve(ZZ& d_out, vec_ZZ& x_out,\n           const mat_ZZ& A, const vec_ZZ& b,\n           long deterministic)\n{\n   long n = A.NumRows();\n   \n   if (A.NumCols() != n)\n      LogicError(\"solve: nonsquare matrix\");\n\n   if (b.length() != n)\n      LogicError(\"solve: dimension mismatch\");\n\n   if (n == 0) {\n      set(d_out);\n      x_out.SetLength(0);\n      return;\n   }\n\n   zz_pBak zbak;\n   zbak.save();\n\n   ZZ_pBak Zbak;\n   Zbak.save();\n\n   vec_ZZ x(INIT_SIZE, n);\n   ZZ d, d1;\n\n   ZZ d_prod, x_prod;\n   set(d_prod);\n   set(x_prod);\n\n   long d_instable = 1;\n   long x_instable = 1;\n\n   long check = 0;\n\n   long gp_cnt = 0;\n\n   vec_ZZ y, b1;\n\n   long i;\n   long bound = 2+DetBound(A);\n\n   for (i = 0; ; i++) {\n      if ((check || IsZero(d)) && !d_instable) {\n         if (NumBits(d_prod) > bound) {\n            break;\n         }\n         else if (!deterministic &&\n                  bound > 1000 && NumBits(d_prod) < 0.25*bound) {\n\n            ZZ P;\n   \n            long plen = 90 + NumBits(max(bound, NumBits(d)));\n            GenPrime(P, plen, 90 + 2*NumBits(gp_cnt++));\n   \n            ZZ_p::init(P);\n   \n            mat_ZZ_p AA;\n            conv(AA, A);\n   \n            ZZ_p dd;\n            determinant(dd, AA);\n   \n            if (CRT(d, d_prod, rep(dd), P))\n               d_instable = 1;\n            else \n               break;\n         }\n      }\n\n\n      zz_p::FFTInit(i);\n      long p = zz_p::modulus();\n\n      mat_zz_p AA;\n      conv(AA, A);\n\n      if (!check) {\n         vec_zz_p bb, xx;\n         conv(bb, b);\n\n         zz_p dd; \n\n         solve(dd, xx, AA, bb);\n\n         d_instable = CRT(d, d_prod, rep(dd), p);\n         if (!IsZero(dd)) {\n            mul(xx, xx, dd);\n            x_instable = CRT(x, x_prod, xx);\n         }\n         else\n            x_instable = 1;\n\n         if (!d_instable && !x_instable) {\n            mul(y, x, A);\n            mul(b1, b, d);\n            if (y == b1) {\n               d1 = d;\n               check = 1;\n            }\n         }\n      }\n      else {\n         zz_p dd;\n         determinant(dd, AA);\n         d_instable = CRT(d, d_prod, rep(dd), p);\n      }\n   }\n\n   if (check && d1 != d) {\n      mul(x, x, d);\n      ExactDiv(x, d1);\n   }\n\n   d_out = d;\n   if (check) x_out = x;\n\n   zbak.restore();\n   Zbak.restore();\n}\n\nvoid inv(ZZ& d_out, mat_ZZ& x_out, const mat_ZZ& A, long deterministic)\n{\n   long n = A.NumRows();\n   \n   if (A.NumCols() != n)\n      LogicError(\"solve: nonsquare matrix\");\n\n   if (n == 0) {\n      set(d_out);\n      x_out.SetDims(0, 0);\n      return;\n   }\n\n   zz_pBak zbak;\n   zbak.save();\n\n   ZZ_pBak Zbak;\n   Zbak.save();\n\n   mat_ZZ x(INIT_SIZE, n, n);\n   ZZ d, d1;\n\n   ZZ d_prod, x_prod;\n   set(d_prod);\n   set(x_prod);\n\n   long d_instable = 1;\n   long x_instable = 1;\n\n   long gp_cnt = 0;\n\n   long check = 0;\n\n\n   mat_ZZ y;\n\n   long i;\n   long bound = 2+DetBound(A);\n\n   for (i = 0; ; i++) {\n      if ((check || IsZero(d)) && !d_instable) {\n         if (NumBits(d_prod) > bound) {\n            break;\n         }\n         else if (!deterministic &&\n                  bound > 1000 && NumBits(d_prod) < 0.25*bound) {\n\n            ZZ P;\n   \n            long plen = 90 + NumBits(max(bound, NumBits(d)));\n            GenPrime(P, plen, 90 + 2*NumBits(gp_cnt++));\n   \n            ZZ_p::init(P);\n   \n            mat_ZZ_p AA;\n            conv(AA, A);\n   \n            ZZ_p dd;\n            determinant(dd, AA);\n   \n            if (CRT(d, d_prod, rep(dd), P))\n               d_instable = 1;\n            else \n               break;\n         }\n      }\n\n\n      zz_p::FFTInit(i);\n      long p = zz_p::modulus();\n\n      mat_zz_p AA;\n      conv(AA, A);\n\n      if (!check) {\n         mat_zz_p xx;\n\n         zz_p dd; \n\n         inv(dd, xx, AA);\n\n         d_instable = CRT(d, d_prod, rep(dd), p);\n         if (!IsZero(dd)) {\n            mul(xx, xx, dd);\n            x_instable = CRT(x, x_prod, xx);\n         }\n         else\n            x_instable = 1;\n\n         if (!d_instable && !x_instable) {\n            mul(y, x, A);\n            if (IsDiag(y, n, d)) {\n               d1 = d;\n               check = 1;\n            }\n         }\n      }\n      else {\n         zz_p dd;\n         determinant(dd, AA);\n         d_instable = CRT(d, d_prod, rep(dd), p);\n      }\n   }\n\n   if (check && d1 != d) {\n      mul(x, x, d);\n      ExactDiv(x, d1);\n   }\n\n   d_out = d;\n   if (check) x_out = x;\n\n   zbak.restore();\n   Zbak.restore();\n}\n\nvoid negate(mat_ZZ& X, const mat_ZZ& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n\n   X.SetDims(n, m);\n\n   long i, j;\n   for (i = 1; i <= n; i++)\n      for (j = 1; j <= m; j++)\n         negate(X(i,j), A(i,j));\n}\n\n\n\nlong IsZero(const mat_ZZ& a)\n{\n   long n = a.NumRows();\n   long i;\n\n   for (i = 0; i < n; i++)\n      if (!IsZero(a[i]))\n         return 0;\n\n   return 1;\n}\n\nvoid clear(mat_ZZ& x)\n{\n   long n = x.NumRows();\n   long i;\n   for (i = 0; i < n; i++)\n      clear(x[i]);\n}\n\n\nmat_ZZ operator+(const mat_ZZ& a, const mat_ZZ& b)\n{\n   mat_ZZ res;\n   add(res, a, b);\n   NTL_OPT_RETURN(mat_ZZ, res);\n}\n\nmat_ZZ operator*(const mat_ZZ& a, const mat_ZZ& b)\n{\n   mat_ZZ res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(mat_ZZ, res);\n}\n\nmat_ZZ operator-(const mat_ZZ& a, const mat_ZZ& b)\n{\n   mat_ZZ res;\n   sub(res, a, b);\n   NTL_OPT_RETURN(mat_ZZ, res);\n}\n\n\nmat_ZZ operator-(const mat_ZZ& a)\n{\n   mat_ZZ res;\n   negate(res, a);\n   NTL_OPT_RETURN(mat_ZZ, res);\n}\n\nvec_ZZ operator*(const mat_ZZ& a, const vec_ZZ& b)\n{\n   vec_ZZ res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_ZZ, res);\n}\n\nvec_ZZ operator*(const vec_ZZ& a, const mat_ZZ& b)\n{\n   vec_ZZ res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_ZZ, res);\n}\n\n\n\n\nvoid inv(mat_ZZ& X, const mat_ZZ& A)\n{\n   ZZ d;\n   inv(d, X, A);\n   if (d == -1)\n      negate(X, X);\n   else if (d != 1)\n      ArithmeticError(\"inv: non-invertible matrix\");\n}\n\nvoid power(mat_ZZ& X, const mat_ZZ& A, const ZZ& e)\n{\n   if (A.NumRows() != A.NumCols()) LogicError(\"power: non-square matrix\");\n\n   if (e == 0) {\n      ident(X, A.NumRows());\n      return;\n   }\n\n   mat_ZZ T1, T2;\n   long i, k;\n\n   k = NumBits(e);\n   T1 = A;\n\n   for (i = k-2; i >= 0; i--) {\n      sqr(T2, T1);\n      if (bit(e, i))\n         mul(T1, T2, A);\n      else\n         T1 = T2;\n   }\n\n   if (e < 0)\n      inv(X, T1);\n   else\n      X = T1;\n}\n\n\n\n/***********************************************************\n\n   routines for solving a linear system via Hensel lifting\n\n************************************************************/\n\n\nstatic\nlong MaxBits(const mat_ZZ& A)\n{\n   long m = 0;\n   long i, j;\n   for (i = 0; i < A.NumRows(); i++)\n      for (j = 0; j < A.NumCols(); j++)\n         m = max(m, NumBits(A[i][j]));\n\n   return m;\n}\n\n\n\n\n// Computes an upper bound on the numerators and denominators\n// to the solution x*A = b using Hadamard's bound and Cramer's rule. \n// If A contains a zero row, then sets both bounds to zero.\n\nstatic\nvoid hadamard(ZZ& num_bound, ZZ& den_bound, \n              const mat_ZZ& A, const vec_ZZ& b)\n{\n   long n = A.NumRows();\n\n   if (n == 0) LogicError(\"internal error: hadamard with n = 0\");\n\n   ZZ b_len, min_A_len, prod, t1;\n\n   InnerProduct(min_A_len, A[0], A[0]);\n\n   prod = min_A_len;\n\n   long i;\n   for (i = 1; i < n; i++) {\n      InnerProduct(t1, A[i], A[i]);\n      if (t1 < min_A_len)\n         min_A_len = t1;\n      mul(prod, prod, t1);\n   }\n\n   if (min_A_len == 0) {\n      num_bound = 0;\n      den_bound = 0;\n      return;\n   }\n\n   InnerProduct(b_len, b, b);\n\n   div(t1, prod, min_A_len);\n   mul(t1, t1, b_len);\n\n   SqrRoot(num_bound, t1);\n   SqrRoot(den_bound, prod);\n}\n\n\nstatic\nvoid MixedMul(vec_ZZ& x, const vec_zz_p& a, const mat_ZZ& B)\n{\n   long n = B.NumRows();\n   long l = B.NumCols();\n\n   if (n != a.length())\n      LogicError(\"matrix mul: dimension mismatch\");\n\n   x.SetLength(l);\n\n   long i, k;\n   ZZ acc, tmp;\n\n   for (i = 1; i <= l; i++) {\n      clear(acc);\n      for (k = 1; k <= n; k++) {\n         mul(tmp, B(k, i), rep(a(k)));\n         add(acc, acc, tmp);\n      }\n      x(i) = acc;\n    }\n} \n\nstatic\nvoid SubDiv(vec_ZZ& e, const vec_ZZ& t, long p)\n{\n   long n = e.length();\n   if (t.length() != n) LogicError(\"SubDiv: dimension mismatch\");\n\n   ZZ s;\n   long i;\n\n   for (i = 0; i < n; i++) {\n      sub(s, e[i], t[i]);\n      div(e[i], s, p);\n   }\n}\n\nstatic\nvoid MulAdd(vec_ZZ& x, const ZZ& prod, const vec_zz_p& h)\n{\n   long n = x.length();\n   if (h.length() != n) LogicError(\"MulAdd: dimension mismatch\");\n\n   ZZ t;\n   long i;\n\n   for (i = 0; i < n; i++) {\n      mul(t, prod, rep(h[i]));\n      add(x[i], x[i], t);\n   }\n}\n\n\nstatic\nvoid double_MixedMul1(vec_ZZ& x, double *a, double **B, long n)\n{\n   long i, k;\n   double acc;\n\n   for (i = 0; i < n; i++) {\n      double *bp = B[i];\n      acc = 0;\n      for (k = 0; k < n; k++) {\n         acc += bp[k] * a[k];\n      }\n      conv(x[i], acc);\n    }\n} \n\n\nstatic\nvoid double_MixedMul2(vec_ZZ& x, double *a, double **B, long n, long limit)\n{\n   long i, k;\n   double acc;\n   ZZ acc1, t;\n   long j;\n\n   for (i = 0; i < n; i++) {\n      double *bp = B[i];\n\n      clear(acc1);\n      acc = 0;\n      j = 0;\n\n      for (k = 0; k < n; k++) {\n         acc += bp[k] * a[k];\n         j++;\n         if (j == limit) {\n            conv(t, acc);\n            add(acc1, acc1, t);\n            acc = 0;\n            j = 0;\n         }\n      }\n\n      if (j > 0) {\n         conv(t, acc);\n         add(acc1, acc1, t);\n      }\n\n      x[i] = acc1;\n    }\n} \n\n\nstatic\nvoid long_MixedMul1(vec_ZZ& x, long *a, long **B, long n)\n{\n   long i, k;\n   long acc;\n\n   for (i = 0; i < n; i++) {\n      long *bp = B[i];\n      acc = 0;\n      for (k = 0; k < n; k++) {\n         acc += bp[k] * a[k];\n      }\n      conv(x[i], acc);\n    }\n} \n\n\nstatic\nvoid long_MixedMul2(vec_ZZ& x, long *a, long **B, long n, long limit)\n{\n   long i, k;\n   long acc;\n   ZZ acc1, t;\n   long j;\n\n   for (i = 0; i < n; i++) {\n      long *bp = B[i];\n\n      clear(acc1);\n      acc = 0;\n      j = 0;\n\n      for (k = 0; k < n; k++) {\n         acc += bp[k] * a[k];\n         j++;\n         if (j == limit) {\n            conv(t, acc);\n            add(acc1, acc1, t);\n            acc = 0;\n            j = 0;\n         }\n      }\n\n      if (j > 0) {\n         conv(t, acc);\n         add(acc1, acc1, t);\n      }\n\n      x[i] = acc1;\n    }\n} \n\n\nvoid solve1(ZZ& d_out, vec_ZZ& x_out, const mat_ZZ& A, const vec_ZZ& b)\n{\n   long n = A.NumRows();\n\n   if (A.NumCols() != n)\n      LogicError(\"solve1: nonsquare matrix\");\n\n   if (b.length() != n)\n      LogicError(\"solve1: dimension mismatch\");\n\n   if (n == 0) {\n      set(d_out);\n      x_out.SetLength(0);\n      return;\n   }\n\n   ZZ num_bound, den_bound;\n\n   hadamard(num_bound, den_bound, A, b);\n\n   if (den_bound == 0) {\n      clear(d_out);\n      return;\n   }\n\n   zz_pBak zbak;\n   zbak.save();\n\n   long i;\n   long j;\n\n   ZZ prod;\n   prod = 1;\n\n   mat_zz_p B;\n\n\n   for (i = 0; ; i++) {\n      zz_p::FFTInit(i);\n\n      mat_zz_p AA, BB;\n      zz_p dd;\n\n      conv(AA, A);\n      inv(dd, BB, AA);\n\n      if (dd != 0) {\n         transpose(B, BB);\n         break;\n      }\n\n      mul(prod, prod, zz_p::modulus());\n      \n      if (prod > den_bound) {\n         d_out = 0;\n         return;\n      }\n   }\n\n   long max_A_len = MaxBits(A);\n\n   long use_double_mul1 = 0;\n   long use_double_mul2 = 0;\n   long double_limit = 0;\n\n   if (max_A_len + NTL_SP_NBITS + NumBits(n) <= NTL_DOUBLE_PRECISION-1)\n      use_double_mul1 = 1;\n\n   if (!use_double_mul1 && max_A_len+NTL_SP_NBITS+2 <= NTL_DOUBLE_PRECISION-1) {\n      use_double_mul2 = 1;\n      double_limit = (1L << (NTL_DOUBLE_PRECISION-1-max_A_len-NTL_SP_NBITS));\n   }\n\n   long use_long_mul1 = 0;\n   long use_long_mul2 = 0;\n   long long_limit = 0;\n\n   if (max_A_len + NTL_SP_NBITS + NumBits(n) <= NTL_BITS_PER_LONG-1)\n      use_long_mul1 = 1;\n\n   if (!use_long_mul1 && max_A_len+NTL_SP_NBITS+2 <= NTL_BITS_PER_LONG-1) {\n      use_long_mul2 = 1;\n      long_limit = (1L << (NTL_BITS_PER_LONG-1-max_A_len-NTL_SP_NBITS));\n   }\n\n\n\n   if (use_double_mul1 && use_long_mul1)\n      use_long_mul1 = 0;\n   else if (use_double_mul1 && use_long_mul2)\n      use_long_mul2 = 0;\n   else if (use_double_mul2 && use_long_mul1)\n      use_double_mul2 = 0;\n   else if (use_double_mul2 && use_long_mul2) {\n      if (long_limit > double_limit)\n         use_double_mul2 = 0;\n      else\n         use_long_mul2 = 0;\n   }\n\n\n   double **double_A=0;\n   double *double_h=0;\n\n   Unique2DArray<double> double_A_store;\n   UniqueArray<double> double_h_store;\n\n\n   if (use_double_mul1 || use_double_mul2) {\n      double_h_store.SetLength(n);\n      double_h = double_h_store.get();\n\n      double_A_store.SetDims(n, n);\n      double_A = double_A_store.get();\n\n      for (i = 0; i < n; i++)\n         for (j = 0; j < n; j++)\n            double_A[j][i] = to_double(A[i][j]);\n   }\n\n   long **long_A=0;\n   long *long_h=0;\n\n   Unique2DArray<long> long_A_store;\n   UniqueArray<long> long_h_store;\n\n\n   if (use_long_mul1 || use_long_mul2) {\n      long_h_store.SetLength(n);\n      long_h = long_h_store.get();\n\n      long_A_store.SetDims(n, n);\n      long_A = long_A_store.get();\n\n      for (i = 0; i < n; i++)\n         for (j = 0; j < n; j++)\n            long_A[j][i] = to_long(A[i][j]);\n   }\n\n\n   vec_ZZ x;\n   x.SetLength(n);\n\n   vec_zz_p h;\n   h.SetLength(n);\n\n   vec_ZZ e;\n   e = b;\n\n   vec_zz_p ee;\n\n   vec_ZZ t;\n   t.SetLength(n);\n\n   prod = 1;\n\n   ZZ bound1;\n   mul(bound1, num_bound, den_bound);\n   mul(bound1, bound1, 2);\n\n   while (prod <= bound1) {\n      conv(ee, e);\n\n      mul(h, B, ee);\n\n      if (use_double_mul1) {\n         for (i = 0; i < n; i++)\n            double_h[i] = to_double(rep(h[i]));\n\n         double_MixedMul1(t, double_h, double_A, n);\n      }\n      else if (use_double_mul2) {\n         for (i = 0; i < n; i++)\n            double_h[i] = to_double(rep(h[i]));\n\n         double_MixedMul2(t, double_h, double_A, n, double_limit);\n      }\n      else if (use_long_mul1) {\n         for (i = 0; i < n; i++)\n            long_h[i] = to_long(rep(h[i]));\n\n         long_MixedMul1(t, long_h, long_A, n);\n      }\n      else if (use_long_mul2) {\n         for (i = 0; i < n; i++)\n            long_h[i] = to_long(rep(h[i]));\n\n         long_MixedMul2(t, long_h, long_A, n, long_limit);\n      }\n      else\n         MixedMul(t, h, A); // t = h*A\n\n      SubDiv(e, t, zz_p::modulus()); // e = (e-t)/p\n      MulAdd(x, prod, h);  // x = x + prod*h\n\n      mul(prod, prod, zz_p::modulus());\n   }\n\n   vec_ZZ num, denom;\n   ZZ d, d_mod_prod, tmp1;\n\n   num.SetLength(n);\n   denom.SetLength(n);\n \n   d = 1;\n   d_mod_prod = 1;\n\n   for (i = 0; i < n; i++) {\n      rem(x[i], x[i], prod);\n      MulMod(x[i], x[i], d_mod_prod, prod);\n\n      if (!ReconstructRational(num[i], denom[i], x[i], prod, \n           num_bound, den_bound))\n          LogicError(\"solve1 internal error: rat recon failed!\");\n\n      mul(d, d, denom[i]);\n\n      if (i != n-1) {\n         if (denom[i] != 1) {\n            div(den_bound, den_bound, denom[i]); \n            mul(bound1, num_bound, den_bound);\n            mul(bound1, bound1, 2);\n\n            div(tmp1, prod, zz_p::modulus());\n            while (tmp1 > bound1) {\n               prod = tmp1;\n               div(tmp1, prod, zz_p::modulus());\n            }\n\n            rem(tmp1, denom[i], prod);\n            rem(d_mod_prod, d_mod_prod, prod);\n            MulMod(d_mod_prod, d_mod_prod, tmp1, prod);\n         }\n      }\n   }\n\n   tmp1 = 1;\n   for (i = n-1; i >= 0; i--) {\n      mul(num[i], num[i], tmp1);\n      mul(tmp1, tmp1, denom[i]);\n   }\n   \n   x_out.SetLength(n);\n\n   for (i = 0; i < n; i++) {\n      x_out[i] = num[i];\n   }\n\n   d_out = d;\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "f52646c4662a4295925dc8c623ecb90ab2925a38", "size": 24070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/mat_ZZ.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "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": "homomorphic_evaluation/ntl-11.3.2/src/mat_ZZ.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "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": "LibSource/ExtendedNTL/src/mat_ZZ.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "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": 18.0029917726, "max_line_length": 80, "alphanum_fraction": 0.4552139593, "num_tokens": 8117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5181305616427014}}
{"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// #define CRS_CVEC_MULT_NO_ACCEL\n\n// #define CRS_CVEC_MULT_NO_ACCEL // for benchmarking\n// #define MTL_LAZY_LOOP_WO_UNROLL // for benchmarking\n\n#include <iostream>\n#include <typeinfo>\n#include <boost/timer.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\n\nint main()\n{\n    mtl::vampir_trace<9999> tracer;\n  // For a more realistic example set size to 1000 or larger\n  const int size = 1000, N = size * size; \n  using namespace mtl;\n\n  typedef unsigned size_type;\n  // typedef std::size_t size_type;\n  std::cout << \"sizeof in size_type is \" << sizeof(size_type) << '\\n';\n  typedef mat::parameters<row_major, mtl::index::c_index, non_fixed::dimensions, false, size_type> para;\n  typedef compressed2D<double, para>  matrix_type;\n  matrix_type          A(N, N);\n  laplacian_setup(A, size, size);\n\n  itl::pc::ilu_0<matrix_type, float>     P(A);\n  itl::pc::identity<matrix_type>  P2(A);\n\n  mtl::dense_vector<double> x(N, 1.0), b(N);\n\n  b = A * x;\n\n  for (int l= 2; l <= 10; l++) {\n      x= 0;\n      itl::cyclic_iteration<double> iter(b, 100, 1.e-6, 0.0, 100);\n      boost::timer t;\n      bicgstab_ell(A, x, b, P, P2, iter, l);\n      std::cout << \"BiCGStab(\" << l << \") took \" << t.elapsed() << \"s.\\n\";\n  }\n \n  return 0;\n}\n", "meta": {"hexsha": "f588726acb68fa253eecc72021af63a2903f2a20", "size": 1691, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/timing/ilu_0_bicgstab_ell_timing.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/timing/ilu_0_bicgstab_ell_timing.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/timing/ilu_0_bicgstab_ell_timing.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.1964285714, "max_line_length": 104, "alphanum_fraction": 0.6581904199, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5181035459047243}}
{"text": "#include <mex.h>\n#include <Eigen/Eigen>\n#include \"localize.h\"\n\n// Takes an mxArray and returns its contents as an eigen matrix by reference\nvoid input_matrix(const mxArray* p, Eigen::MatrixXd& mat) {\n    int m = mxGetM(p);\n    int n = mxGetN(p);\n\n    mat.resize(m,n);\n\n    double *data = mxGetPr(p);\n\n    for(int j = 0; j < n; j++) {\n        for(int i = 0; i < m; i++) {\n            mat(i,j) = data[m*j + i];\n        }\n    }\n}\n\n// Should be called as:\n// [P, inliers] = CameraPoseRANSAC_Mex(X,x,tol,nIters), where X is a 3xN matrix containing the 3D points, and\n// x is a 3xN matrix containing the image points as unit vectors and tol is the largest allowed\n// angular deviation (in radians) for a correspondence to be considered an inlier, and nIters is the max number of iterations.\n// The output P is the calculated camera matrix as well as an integer designating the number of inliers.\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n    // Validate the input\n    if(nrhs != 4)\n        mexErrMsgTxt(\"Invalid input! The function takes three inputs: \\n\\t3d structure X as a 3xN matrix, \\n\\ta 3xN matrix representing image points as unit vectors, \\n\\tthe maximum allowed angle deviation for a correspondence to be considered an inlier,\\n\\tnumber of RANSAC iterations.\");\n    if(nlhs != 2)\n        mexErrMsgTxt(\"Invalid output! The function returns two outputs: P representing the triangulated camera matrix and an integer designating the number of inliers for P. \");\n\n    Eigen::MatrixXd x;\n    Eigen::MatrixXd X;\n    double tol = mxGetScalar(prhs[2]);\n    int nIter = int(mxGetScalar(prhs[3]));\n\n    input_matrix(prhs[0],X);\n    input_matrix(prhs[1],x);\n\n    if(x.rows() != 3 || X.rows() != 3 || x.cols() != X.cols())\n        mexErrMsgTxt(\"Input matrices must both have three rows and the same number of columns!\");\n\n    // Inputs and outputs are ok! Calculate camera pose!\n    int numInliers = 0;\n    Eigen::Matrix<double,3,4> P = Eigen::MatrixXd::Zero(3,4);\n    bool success = cameraPoseRANSAC(x,X,nIter,tol,P,numInliers);\n    if (!success)\n    {\n        numInliers = 0;\n    }\n\n    // Create output\n    plhs[0] = mxCreateDoubleMatrix(P.rows(),4,mxREAL);\n    double* outputMatrix = mxGetPr(plhs[0]);\n    int index = 0;\n    for (int j = 0; j < P.cols(); j++) {\n        for (int i = 0; i < P.rows(); i++) {\n            outputMatrix[index] = P(i,j);\n            index++;\n        }\n    }\n\n    plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);\n    double* output = mxGetPr(plhs[1]);\n    output[0] = static_cast<double>(numInliers);\n}\n", "meta": {"hexsha": "b7d75ab9a04f6c8e09a8ec9859992d70d0bd58d3", "size": 2557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/CameraPoseRANSAC_Mex.cpp", "max_stars_repo_name": "erikstenborg/RansacLib", "max_stars_repo_head_hexsha": "9c2d140dd11b3b62661083266d20a2f90db70eaa", "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/CameraPoseRANSAC_Mex.cpp", "max_issues_repo_name": "erikstenborg/RansacLib", "max_issues_repo_head_hexsha": "9c2d140dd11b3b62661083266d20a2f90db70eaa", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/CameraPoseRANSAC_Mex.cpp", "max_forks_repo_name": "erikstenborg/RansacLib", "max_forks_repo_head_hexsha": "9c2d140dd11b3b62661083266d20a2f90db70eaa", "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.0579710145, "max_line_length": 289, "alphanum_fraction": 0.6429409464, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5181035356792909}}
{"text": "// Copyright 2018 Hans Dembinski\r\n//\r\n// Distributed under the 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#ifndef BOOST_HISTOGRAM_ACCUMULATORS_WEIGHTED_MEAN_HPP\r\n#define BOOST_HISTOGRAM_ACCUMULATORS_WEIGHTED_MEAN_HPP\r\n\r\n#include <boost/histogram/fwd.hpp>\r\n#include <type_traits>\r\n\r\nnamespace boost {\r\nnamespace histogram {\r\nnamespace accumulators {\r\n\r\n/**\r\n  Calculates mean and variance of weighted sample.\r\n\r\n  Uses West's incremental algorithm to improve numerical stability\r\n  of mean and variance computation.\r\n*/\r\ntemplate <typename RealType>\r\nclass weighted_mean {\r\npublic:\r\n  weighted_mean() = default;\r\n  weighted_mean(const RealType& wsum, const RealType& wsum2, const RealType& mean,\r\n                const RealType& variance)\r\n      : sum_of_weights_(wsum)\r\n      , sum_of_weights_squared_(wsum2)\r\n      , weighted_mean_(mean)\r\n      , sum_of_weighted_deltas_squared_(\r\n            variance * (sum_of_weights_ - sum_of_weights_squared_ / sum_of_weights_)) {}\r\n\r\n  void operator()(const RealType& x) { operator()(1, x); }\r\n\r\n  void operator()(const RealType& w, const RealType& x) {\r\n    sum_of_weights_ += w;\r\n    sum_of_weights_squared_ += w * w;\r\n    const auto delta = x - weighted_mean_;\r\n    weighted_mean_ += w * delta / sum_of_weights_;\r\n    sum_of_weighted_deltas_squared_ += w * delta * (x - weighted_mean_);\r\n  }\r\n\r\n  template <typename T>\r\n  weighted_mean& operator+=(const weighted_mean<T>& rhs) {\r\n    const auto tmp = weighted_mean_ * sum_of_weights_ +\r\n                     static_cast<RealType>(rhs.weighted_mean_ * rhs.sum_of_weights_);\r\n    sum_of_weights_ += static_cast<RealType>(rhs.sum_of_weights_);\r\n    sum_of_weights_squared_ += static_cast<RealType>(rhs.sum_of_weights_squared_);\r\n    weighted_mean_ = tmp / sum_of_weights_;\r\n    sum_of_weighted_deltas_squared_ +=\r\n        static_cast<RealType>(rhs.sum_of_weighted_deltas_squared_);\r\n    return *this;\r\n  }\r\n\r\n  weighted_mean& operator*=(const RealType& s) {\r\n    weighted_mean_ *= s;\r\n    sum_of_weighted_deltas_squared_ *= s * s;\r\n    return *this;\r\n  }\r\n\r\n  template <typename T>\r\n  bool operator==(const weighted_mean<T>& rhs) const noexcept {\r\n    return sum_of_weights_ == rhs.sum_of_weights_ &&\r\n           sum_of_weights_squared_ == rhs.sum_of_weights_squared_ &&\r\n           weighted_mean_ == rhs.weighted_mean_ &&\r\n           sum_of_weighted_deltas_squared_ == rhs.sum_of_weighted_deltas_squared_;\r\n  }\r\n\r\n  template <typename T>\r\n  bool operator!=(const T& rhs) const noexcept {\r\n    return !operator==(rhs);\r\n  }\r\n\r\n  const RealType& sum_of_weights() const noexcept { return sum_of_weights_; }\r\n  const RealType& value() const noexcept { return weighted_mean_; }\r\n  RealType variance() const {\r\n    return sum_of_weighted_deltas_squared_ /\r\n           (sum_of_weights_ - sum_of_weights_squared_ / sum_of_weights_);\r\n  }\r\n\r\n  template <class Archive>\r\n  void serialize(Archive&, unsigned /* version */);\r\n\r\nprivate:\r\n  RealType sum_of_weights_ = RealType(), sum_of_weights_squared_ = RealType(),\r\n           weighted_mean_ = RealType(), sum_of_weighted_deltas_squared_ = RealType();\r\n};\r\n\r\n} // namespace accumulators\r\n} // namespace histogram\r\n} // namespace boost\r\n\r\n#ifndef BOOST_HISTOGRAM_DOXYGEN_INVOKED\r\nnamespace std {\r\ntemplate <class T, class U>\r\n/// Specialization for boost::histogram::accumulators::weighted_mean.\r\nstruct common_type<boost::histogram::accumulators::weighted_mean<T>,\r\n                   boost::histogram::accumulators::weighted_mean<U>> {\r\n  using type = boost::histogram::accumulators::weighted_mean<common_type_t<T, U>>;\r\n};\r\n} // namespace std\r\n#endif\r\n\r\n#endif\r\n", "meta": {"hexsha": "fd8e6013ee086dcf970a8509712565f9789409bd", "size": 3688, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dep/win/include/boost/histogram/accumulators/weighted_mean.hpp", "max_stars_repo_name": "Netis/packet-agent", "max_stars_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 995.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z", "max_issues_repo_path": "dep/win/include/boost/histogram/accumulators/weighted_mean.hpp", "max_issues_repo_name": "Netis/packet-agent", "max_issues_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z", "max_forks_repo_path": "dep/win/include/boost/histogram/accumulators/weighted_mean.hpp", "max_forks_repo_name": "Netis/packet-agent", "max_forks_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z", "avg_line_length": 34.4672897196, "max_line_length": 89, "alphanum_fraction": 0.7030911063, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5181035338308319}}
{"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\nBOOST_AUTO_TEST_CASE( Fletcher_Powell_Helix )\n{\n    /*\n        Performs a single fit using the FLETCHER_POWELL_HELIX model.\n        - zero data is passed in.\n        - Checks final chi_square to be near by zero.\n        - Checks fitted parameters equalling the true parameters.\n    */\n\n    std::size_t const n_fits{ 1 } ;\n    std::size_t const n_points{ 3 } ;\n    std::size_t const n_parameters{ 3 } ;\n\n    std::array< REAL, n_parameters > const true_parameters{ { 1., 0., 0. } };\n\n    std::array< REAL, n_points > data{ { 0., 0., 0. } } ;\n\n    std::array< REAL, n_parameters > initial_parameters{ { -1., 0., 0. } } ;\n\n    REAL tolerance{ 1e-8f } ;\n    \n    int max_n_iterations{ 50 } ;\n    \n    std::array< int, n_parameters > parameters_to_fit{ { 1, 1, 1 } } ;\n    \n    std::array< REAL, n_parameters > output_parameters ;\n    int output_state ;\n    REAL output_chi_square ;\n    int output_n_iterations ;\n\n    // test initial_parameters * 1.\n    int status = gpufit\n        (\n            n_fits,\n            n_points,\n            data.data(),\n            0,\n            FLETCHER_POWELL_HELIX,\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_state,\n            & output_chi_square,\n            & output_n_iterations\n        ) ;\n\n    BOOST_CHECK( status == 0 ) ;\n    BOOST_CHECK( output_state == 0 );\n    BOOST_CHECK( output_n_iterations <= 9 );\n    BOOST_CHECK( output_chi_square < 1e-26f );\n\n    BOOST_CHECK(std::abs(output_parameters[0] - true_parameters[0]) < 1e-13);\n    BOOST_CHECK(std::abs(output_parameters[1] - true_parameters[1]) < 1e-13);\n    BOOST_CHECK(std::abs(output_parameters[2] - true_parameters[2]) < 1e-13);\n\n    // test initial_parameters * 10.\n    for (int i = 0; i < n_parameters; i++)\n        initial_parameters[i] *= 10.;\n\n    status = gpufit\n    (\n        n_fits,\n        n_points,\n        data.data(),\n        0,\n        FLETCHER_POWELL_HELIX,\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_state,\n        &output_chi_square,\n        &output_n_iterations\n    );\n\n    BOOST_CHECK(status == 0);\n    BOOST_CHECK(output_state == 0);\n    BOOST_CHECK(output_n_iterations <= 21);\n    BOOST_CHECK(output_chi_square < 1e-26);\n\n    BOOST_CHECK(std::abs(output_parameters[0] - true_parameters[0]) < 1e-13);\n    BOOST_CHECK(std::abs(output_parameters[1] - true_parameters[1]) < 1e-13);\n    BOOST_CHECK(std::abs(output_parameters[2] - true_parameters[2]) < 1e-13);\n\n    // test initial_parameters * 100.\n    for (int i = 0; i < n_parameters; i++)\n        initial_parameters[i] *= 10.;\n\n    status = gpufit\n    (\n        n_fits,\n        n_points,\n        data.data(),\n        0,\n        FLETCHER_POWELL_HELIX,\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_state,\n        &output_chi_square,\n        &output_n_iterations\n    );\n\n    BOOST_CHECK(status == 0);\n    BOOST_CHECK(output_state == 0);\n    BOOST_CHECK(output_n_iterations <= 29);\n    BOOST_CHECK(output_chi_square < 1e-20);\n\n    BOOST_CHECK(std::abs(output_parameters[0] - true_parameters[0]) < 1e-10);\n    BOOST_CHECK(std::abs(output_parameters[1] - true_parameters[1]) < 1e-10);\n    BOOST_CHECK(std::abs(output_parameters[2] - true_parameters[2]) < 1e-10);\n}\n", "meta": {"hexsha": "28b64b985c0aa40ecc4d104d9418fec78bb4d1b5", "size": 3751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gpufit/tests/Fletcher_Powell_Helix_Fit.cpp", "max_stars_repo_name": "sriharijayaram5/Gpufit", "max_stars_repo_head_hexsha": "468ffbce6e6ff98632951af5e027c88c332bc1e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 228.0, "max_stars_repo_stars_event_min_datetime": "2017-08-10T17:46:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:06:06.000Z", "max_issues_repo_path": "Gpufit/tests/Fletcher_Powell_Helix_Fit.cpp", "max_issues_repo_name": "sriharijayaram5/Gpufit", "max_issues_repo_head_hexsha": "468ffbce6e6ff98632951af5e027c88c332bc1e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2017-08-14T11:41:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:22:59.000Z", "max_forks_repo_path": "Gpufit/tests/Fletcher_Powell_Helix_Fit.cpp", "max_forks_repo_name": "sriharijayaram5/Gpufit", "max_forks_repo_head_hexsha": "468ffbce6e6ff98632951af5e027c88c332bc1e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 76.0, "max_forks_repo_forks_event_min_datetime": "2017-08-16T15:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T06:28:38.000Z", "avg_line_length": 27.7851851852, "max_line_length": 77, "alphanum_fraction": 0.5942415356, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5181035324150324}}
{"text": "/*\n * Copyright 2019 \u00a9 Centre Interdisciplinaire de d\u00e9veloppement en Cartographie des Oc\u00e9ans (CIDCO), Tous droits r\u00e9serv\u00e9s\n */\n\n/* \n * File:   SideScanGeoreferencingTest.hpp\n * Author: Jordan McManus <jordan.mcmanus@cidco.ca>\n *\n * Created on March 11, 2020, 1:18 PM\n */\n\n#ifndef SIDESCANGEOREFERENCINGTEST_HPP\n#define SIDESCANGEOREFERENCINGTEST_HPP\n\n#include \"catch.hpp\"\n#include <Eigen/Dense>\n#include \"../src/Position.hpp\"\n#include \"../src/sidescan/SideScanGeoreferencing.hpp\"\n#include \"../src/math/CoordinateTransform.hpp\"\n#include \"../src/utils/Constants.hpp\"\n\nTEST_CASE(\"Georeferencing Side Scan No LeverArm No Layback test\") {\n\n    double earthRadius = 6.3781e6; // in meters\n    double objectLatRadians = 0.0;\n    double objectLonRadians = 0.0 + 10 / (earthRadius); // 10 meters east of Greenwich\n    double objectHeight = 0.0;\n\n    double shipLat = 0.0;\n    double shipLon = 0.0;\n    double shipHeight = 0.0;\n    Position shipPositionAtEquatorGreenwichMeridian(0, shipLat, shipLon, shipHeight);\n\n    Eigen::Vector3d shipPositionEcef;\n    CoordinateTransform::getPositionECEF(shipPositionEcef, shipPositionAtEquatorGreenwichMeridian);\n\n    Eigen::Vector3d sideDistanceEcef(0, 10, 0);\n\n    Eigen::Vector3d antenna2TowPointLeverArmEcef(0, 0, 0);\n    Eigen::Vector3d laybackEcef(0, 0, 0);\n\n    Position objectPosition(0, 0.0, 0.0, 0.0);\n    SideScanGeoreferencing::georeferenceSideScanEcef(\n            shipPositionEcef,\n            antenna2TowPointLeverArmEcef,\n            laybackEcef,\n            sideDistanceEcef,\n            objectPosition);\n\n    double latLonTreshold = 1e-9; // about 5.7e-8 degrees\n    double heightTrashold = 1e-5; // 10 micrometers\n    REQUIRE(std::abs(objectPosition.getLatitude() * D2R - objectLatRadians) < latLonTreshold);\n    REQUIRE(std::abs(objectPosition.getLongitude() * D2R - objectLonRadians) < latLonTreshold);\n    REQUIRE(std::abs(objectPosition.getEllipsoidalHeight() - objectHeight) < heightTrashold);\n}\n\n#endif /* SIDESCANGEOREFERENCINGTEST_HPP */\n\n", "meta": {"hexsha": "c9454a6f635297aa26cf33512302c61ddc084eb9", "size": 1996, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/SideScanGeoreferencingTest.hpp", "max_stars_repo_name": "JordanMcManus/MBES-lib", "max_stars_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T14:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T06:44:37.000Z", "max_issues_repo_path": "test/SideScanGeoreferencingTest.hpp", "max_issues_repo_name": "JordanMcManus/MBES-lib", "max_issues_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2019-04-16T13:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T19:44:23.000Z", "max_forks_repo_path": "test/SideScanGeoreferencingTest.hpp", "max_forks_repo_name": "JordanMcManus/MBES-lib", "max_forks_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-04-10T19:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T21:42:22.000Z", "avg_line_length": 33.8305084746, "max_line_length": 119, "alphanum_fraction": 0.7224448898, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5181035287181152}}
{"text": "// Copyright (c) 2013-2016. This code was produced by the\n// Australian Centre for Field Robotics, The University of Sydney under\n// the Future Flight Planning project, University Reference 13996, contract\n// NSW-CPS-2011-015264, Work Orders 5, 7 and 8. The intellectual property\n// ownership is as set out in these contracts, as registered with\n// Commercial Development and Industry Partnerships.\n\n#include <iostream>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <comma/application/command_line_options.h>\n#include <comma/csv/stream.h>\n#include <comma/visiting/traits.h>\n#include \"../../../math/range_bearing_elevation.h\"\n#include \"../coordinates.h\"\n#include \"../sample.h\"\n#include \"../traits.h\"\n\nstatic const std::string app_name = \"sphere-calc\";\n\nstatic void usage( bool verbose )\n{\n    std::cerr << std::endl;\n    std::cerr << \"generates a sample ever the whole sphere\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"usage: sphere-calc <options> > sample.csv\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"options\" << std::endl;\n    std::cerr << \"    -h|--help                       Show this help (-v|--verbose to show csv options)\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"sample type options\" << std::endl;\n    std::cerr << \"    --random                        Random uniform sample\" << std::endl;\n    std::cerr << \"    --regular                       Regular grid sample\" << std::endl;\n    std::cerr << \"    --regular-uniform,--uniform     Regular, but pretty uniform\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"random seed options\" << std::endl;\n    std::cerr << \"    -s|--seed=<random-seed>         seed for the random sample\" << std::endl;\n    std::cerr << \"    -t|--seed-time                  use current time as random number seed\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"sample options\" << std::endl;\n    std::cerr << \"    --begin,--from=<latitude,longitude>; default: -90, -180\" << std::endl;\n    std::cerr << \"    --end,--to=<latitude,longitude>; end not included, default: 90.00000001, 180\" << std::endl;\n    std::cerr << \"    --resolution,-r=<value>         Sample resolution in degrees\" << std::endl;\n    if( verbose ) { std::cerr << std::endl << \"csv options\" << std::endl << comma::csv::options::usage() << std::endl; }\n    std::cerr << std::endl;\n    exit( 0 );\n}\n\ntemplate< typename T > T get_option( comma::command_line_options &options, const std::string option_name, const T &default_val )\n{\n    if( !options.exists( option_name ) ) { return default_val; }\n    T result = default_val;\n    result = comma::csv::ascii< T >().get( options.value< std::string >( option_name ) );\n    return result;\n}\n\nusing namespace snark;\n\nint main( int ac, char** av )\n{\n    try\n    {\n        using snark::spherical::coordinates;\n        \n        comma::command_line_options options( ac, av, usage );\n        if( options.exists( \"--verbose,-v\" ) ) { std::cerr << \"sphere-calc: called as: \" << options.string() << std::endl; }\n        double resolution = options.value< double >( \"--resolution,-r\" ) * M_PI / 180;\n        comma::csv::output_stream< coordinates > ostream( std::cout, comma::csv::options( options ) );\n        options.assert_mutually_exclusive( \"--random,--regular\" );\n        bool regular = options.exists( \"--regular\" );\n        bool random = options.exists( \"--random\" );\n        bool regular_uniform = options.exists( \"--regular-uniform,--uniform\" );\n        if( !regular && !random && !regular_uniform ) { std::cerr << \"sphere-calc: expected sample type (--random, --regular, or --uniform)\" << std::endl; return 1; }\n        coordinates begin = get_option< coordinates >( options, \"--begin\", coordinates( -M_PI / 2, -M_PI ) );\n        static const double epsilon = 0.00000001;\n        coordinates end = get_option< coordinates >( options, \"--end\", coordinates( M_PI / 2 + epsilon, M_PI - epsilon ) );\n        if( begin.latitude < -M_PI / 2 ) { begin.latitude = -M_PI / 2; }\n        if( begin.longitude < -M_PI ) { begin.longitude = -M_PI; }\n        if( end.latitude > M_PI / 2 ) { end.latitude = M_PI / 2; }\n        if( end.longitude > M_PI ) { end.longitude = M_PI; }\n        if( regular )\n        {\n            for( coordinates c = begin; comma::math::less( c.latitude, end.latitude ); c.latitude += resolution )\n            {\n                for( c.longitude = begin.longitude; comma::math::less( c.longitude, end.longitude ); c.longitude += resolution )\n                {\n                    ostream.write( c );\n                }\n            }\n        }\n        else if( random || regular_uniform )\n        {\n            options.assert_mutually_exclusive( \"--seed,-s,--seed-time,-t\" );\n            boost::optional< unsigned long > seed = options.optional< unsigned long >( \"--seed,-s\" );\n            if( options.exists( \"--seed-time,-t\" ) ) { seed = static_cast< unsigned long >( std::time( 0 ) ); }\n            boost::mt19937 generator;\n            if( seed ) { generator.seed( *seed ); }\n            boost::uniform_real< double > distribution( 0, 1 );\n            boost::variate_generator< boost::mt19937&, boost::uniform_real< double > > r( generator, distribution );\n            for( coordinates c = begin; comma::math::less( c.latitude, end.latitude ); c.latitude += resolution )\n            {\n                double radius = std::abs( std::cos( c.latitude ) );\n                if( radius == 0 ) { continue; }\n                double step = resolution / radius;\n                double offset = random ? ( r() * 2 - 1 ) * step : 0.0;\n                for( c.longitude = begin.longitude + offset; comma::math::less( c.longitude, end.longitude + offset ); c.longitude += step )\n                {\n                    ostream.write( regular_uniform ? c : pretty_uniform_sample( c, resolution / 2 ) );\n                }\n            }\n        }\n        return 0;\n    }\n    catch( std::exception& ex ) { std::cerr << \"sphere-calc: \" << ex.what() << std::endl; }\n    catch( ... ) { std::cerr << \"sphere-calc: unknown exception\" << std::endl; }\n    return 1;\n}\n", "meta": {"hexsha": "b6f1216347077e05ab7acd323548e24a6a6234da", "size": 6165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/spherical_geometry/applications/sphere-sample.cpp", "max_stars_repo_name": "mission-systems-pty-ltd/snark", "max_stars_repo_head_hexsha": "2bc8a20292ee3684d3a9897ba6fee43fed8d89ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2015-01-14T14:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T09:56:03.000Z", "max_issues_repo_path": "math/spherical_geometry/applications/sphere-sample.cpp", "max_issues_repo_name": "NEU-LC/snark", "max_issues_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2015-01-21T00:57:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T04:22:35.000Z", "max_forks_repo_path": "math/spherical_geometry/applications/sphere-sample.cpp", "max_forks_repo_name": "NEU-LC/snark", "max_forks_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:17:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T17:13:35.000Z", "avg_line_length": 51.8067226891, "max_line_length": 166, "alphanum_fraction": 0.5829683698, "num_tokens": 1554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5181035254538572}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu)  2011.\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/metaparse/foldl1.hpp>\n#include <boost/metaparse/build_parser.hpp>\n#include <boost/metaparse/transform.hpp>\n#include <boost/metaparse/one_of_c.hpp>\n#include <boost/metaparse/entire_input.hpp>\n#include <boost/metaparse/string.hpp>\n\n#include <boost/metaparse/util/digit_to_int.hpp>\n\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/times.hpp>\n\n#include <iostream>\n\nusing boost::metaparse::foldl1;\nusing boost::metaparse::build_parser;\nusing boost::metaparse::transform;\nusing boost::metaparse::one_of_c;\nusing boost::metaparse::entire_input;\n\nusing boost::metaparse::util::digit_to_int;\n\nusing boost::mpl::int_;\nusing boost::mpl::plus;\nusing boost::mpl::times;\n\n/*\n * The grammar\n *\n * expression ::= ('1' | '0')*\n */\n\nstruct next_element\n{\n  template <class Acc, class B>\n  struct apply : plus<times<Acc, int_<2> >, B> {};\n};\n\ntypedef\n  foldl1<transform<one_of_c<'0', '1'>, digit_to_int<> >, int_<0>, next_element>\n  S;\n\ntypedef build_parser<entire_input<S> > binary_parser;\n\ntemplate <class S>\nstruct binary : binary_parser::apply<S>::type {};\n\n#ifdef _STR\n#  error _STR already defined\n#endif\n#define _STR BOOST_METAPARSE_STRING\n\n#if BOOST_METAPARSE_STD < 2011\n\nint main()\n{\n  using std::cout;\n  using std::endl;\n  using boost::metaparse::string;\n\n  cout\n    << binary<string<'1','0','0'> >::value << endl\n    << binary<string<'1','0','1','1'> >::value << endl\n    << binary<string<'1'> >::value << endl;\n}\n#else\nint main()\n{\n  using std::cout;\n  using std::endl;\n\n  cout\n    << binary<_STR(\"100\")>::value << endl\n    << binary<_STR(\"1011\")>::value << endl\n    << binary<_STR(\"1\")>::value << endl;\n}\n#endif\n", "meta": {"hexsha": "432b1d6fb6d391015775b36485b2a0f49ad88a8e", "size": 1877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/metaparse/example/binary_number/main.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/metaparse/example/binary_number/main.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/metaparse/example/binary_number/main.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": 22.3452380952, "max_line_length": 79, "alphanum_fraction": 0.6856686201, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5181035236053984}}
{"text": "#ifndef INTEGRATION_HPP\n#define INTEGRATION_HPP\n\n#include <Eigen/Dense>\nusing namespace Eigen;\n\nclass PhysicalSystem {\n    // parent class for physical systems that support implicit integration\npublic:\n    // return number of *positional* degrees of freedom (not velocity)\n    virtual int getDOFs() = 0;\n    // write position and velocity into vectors\n    virtual void getState(VectorXd &x, VectorXd &v) = 0;\n    // read position and velocity from vectors\n    virtual void setState(const VectorXd &x, const VectorXd &v) = 0;\n    // write mass matrix\n    virtual void getInertia(MatrixXd &M) = 0;\n    // write forces\n    virtual void getForces(VectorXd &f) = 0;\n    // write Jacobians\n    virtual void getJacobians(MatrixXd &Jx, MatrixXd &Jv) = 0;\n};\n\n// perform a forward Euler step of length dt\nvoid forwardEulerStep(PhysicalSystem *system, double dt);\n\n// perform a backward Euler step of length dt\nvoid backwardEulerStep(PhysicalSystem *system, double dt);\n\n#endif\n", "meta": {"hexsha": "43661bed4d4c180a12eacc253bd5ae1b8643b4f2", "size": 968, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "C++/1_MassSpring_Explicit/integration.hpp", "max_stars_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_stars_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-08-02T08:15:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T09:29:04.000Z", "max_issues_repo_path": "C++/2_MassSpring_Implicit/integration.hpp", "max_issues_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_issues_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "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++/2_MassSpring_Implicit/integration.hpp", "max_forks_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_forks_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "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.2258064516, "max_line_length": 74, "alphanum_fraction": 0.7252066116, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5180622108192874}}
{"text": "/*\nCopyright (c) 2015 Jeff Epler\n\nThis software is provided 'as-is', without any express or implied\nwarranty. In no event will the authors be held liable for any damages\narising from the use of this software.\n\nPermission is granted to anyone to use this software for any purpose,\nincluding commercial applications, and to alter it and redistribute it\nfreely, subject to the following restrictions:\n\n1. The origin of this software must not be misrepresented; you must not\n   claim that you wrote the original software. If you use this software\n   in a product, an acknowledgement in the product documentation would be\n   appreciated but is not required.\n2. Altered source versions must be plainly marked as such, and must not be\n   misrepresented as being the original software.\n3. This notice may not be removed or altered from any source distribution.\n*/\n\n#ifndef DASHING_H\n#define DASHING_H\n\n#include <cmath>\n#include <cassert>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <stdexcept>\n#include <boost/algorithm/string/replace.hpp>\n#include <boost/algorithm/string/trim.hpp>\n\nnamespace dashing\n{\n\nstruct PSMatrix {\n    double a, b, c, d, e, f;\n\n    PSMatrix inverse() const;\n    double determinant() const { return a * d - b * c; }\n};\n\nPSMatrix Translation(double x, double y);\nPSMatrix Rotation(double theta);\nPSMatrix XSkew(double xk);\nPSMatrix YScale(double ys);\n\nstruct Point { double x, y; };\ninline Point operator*(const Point &p, const PSMatrix &m) {\n    return Point{ p.x*m.a + p.y*m.c + m.e,\n                  p.x*m.b + p.y*m.d + m.f };\n}\ninline Point operator*(const Point &p, double d)\n{\n    return Point{ p.x * d, p.y * d };\n}\ninline Point operator*(double d, const Point &p)\n{\n    return Point{ p.x * d, p.y * d };\n}\ninline Point operator+(const Point &p, const Point &q)\n{\n    return Point{ p.x + q.x, p.y * q.y };\n}\n\nPSMatrix operator*(const PSMatrix &m1, const PSMatrix m2);\n\nstruct Dash {\n    PSMatrix tr, tf;\n    std::vector<double> dash, sum;\n\n    Dash(double th, double x0, double y0, double dx, double dy,\n            const std::vector<double>::const_iterator dbegin,\n            const std::vector<double>::const_iterator dend);\n\n    static Dash FromString(const std::string &line, double scale);\n};\n\nstruct Segment { Point p, q; bool swapped; };\nstruct Intersection { double u; bool positive; };\ninline bool operator<(const Intersection &a, const Intersection &b)\n{\n    return a.u < b.u;\n}\n\n// \"sort\" a segment so that its first component has the lower y-value\ninline void ysort(Segment &s) {\n    if(s.p.y < s.q.y) return;\n    s.swapped = ! s.swapped;\n    std::swap(s.p, s.q);\n}\n\ninline double intceil(double x) { return int(ceil(x)); }\ninline double intfloor(double x) { return int(floor(x)); }\n\ninline double pythonmod(double a, double b) {\n    auto r = a - floor(a / b) * b;\n    if(r == b) return 0;\n    return r;\n}\n\ninline size_t utoidx(const Dash &d, double u, double &o) {\n    u = pythonmod(u, d.sum.back());\n    for(size_t i = 1; i != d.sum.size(); i++) {\n        if(u < d.sum[i]) { o = u - d.sum[i-1]; return i-1; }\n    }\n    abort(); // should be unreachable\n}\n\ntemplate<class Cb>\nvoid uvdraw(const Dash &pattern, double v, double u1, double u2, Cb cb) {\n    if(pattern.dash.empty()) { cb(v, u1, u2); return;  }\n    double o;\n    auto i = utoidx(pattern, u1, o);\n    const auto &pi = pattern.dash[i];\n    if(pi >= 0) { cb(v, u1, std::min(u2, u1+pi-o)); u1 += pi-o; }\n    else { u1 -= pi+o; }\n    i = i + 1;\n    if(i == pattern.dash.size()) i = 0;\n    for(auto u = u1; u < u2;) {\n        const auto &pi = pattern.dash[i];\n        if(pi >= 0) { cb(v, u, std::min(u2, u+pi)); u += pi; }\n        else { u -= pi; }\n        i = i + 1;\n        if(i == pattern.dash.size()) i = 0;\n    }\n}\n\ntemplate<class Cb, class Wr>\nvoid uvspans(const Dash &pattern, std::vector<Segment> && segments, Cb cb, std::vector<Intersection> &uu, Wr wr) {\n    if(segments.empty()) return; // no segments\n\n    for(auto &s : segments) ysort(s);\n    std::sort(segments.begin(), segments.end(),\n        [](const Segment &a, const Segment &b) {\n            return a.p.y < b.p.y; // sort in increasing p.y\n        });\n\n    // we want to maintain the heap condition in such a way that we can always\n    // quickly pop items that our span has moved past.\n    // C++ heaps are max-heaps, so we need a decreasing sort.\n    auto heapcmp = [](const Segment &a, const Segment &b) {\n            return b.q.y < a.q.y; // sort in decreasing q.y;\n        };\n\n    auto segments_begin = segments.begin();\n    auto heap_begin = segments.begin(), heap_end = segments.begin();\n\n    auto vstart = intfloor(segments.front().p.y);\n    auto vend = intceil(std::max_element(segments.begin(), segments.end(), \n                [](const Segment &a, const Segment &b) {\n                        return a.q.y < b.q.y; // sort in increasing q.y;\n                })->q.y);\n\n    // sweep-line algorithm to intersects spans with segments\n    // \"active\" holds segments that may intersect with this span;\n    // when v moves below an active segment, drop it from the active heap.\n    // when v moves into a remaining segment, move it from segments to active.\n    for(auto v = vstart; v != vend; v++) {\n        uu.clear();\n\n        while(heap_begin != heap_end && heap_begin->q.y < v)\n        {\n            std::pop_heap(heap_begin, heap_end, heapcmp);\n            heap_end --;\n        }\n        while(segments_begin != segments.end() && segments_begin->p.y < v) {\n            const auto &s = *segments_begin;\n            if(s.q.y >= v) {\n                *heap_end++ = s;\n                std::push_heap(heap_begin, heap_end, heapcmp);\n            }\n            segments_begin ++;\n        }\n\n        for(const auto &s : boost::make_iterator_range(heap_begin, heap_end)) {\n            auto du = s.q.x - s.p.x;\n            auto dv = s.q.y - s.p.y;\n            assert(dv);\n            if(dv) uu.push_back(\n                    Intersection{s.p.x + du * (v - s.p.y) / dv,s.swapped});\n        }\n        std::sort(uu.begin(), uu.end());\n        int winding = 0;\n        double old_u = -std::numeric_limits<double>::infinity();\n        for(const auto &isect : uu) {\n            if(wr(winding)) uvdraw(pattern, v, old_u, isect.u, cb);\n            winding += 2*isect.positive - 1;\n            old_u = isect.u;\n        }\n    }\n}\n\nstruct HatchPattern {\n    std::vector<Dash> d;\n    static HatchPattern FromFile(std::istream &fi, double scale) {\n        HatchPattern result;\n\n        std::string line;\n        while(getline(fi, line)) {\n            auto i = line.find(\";\");\n            if(i != line.npos) line.erase(i, line.npos);\n            boost::algorithm::trim(line);\n            if(line.empty()) continue;\n            if(line[0] == '*') continue;\n            result.d.push_back(Dash::FromString(line, scale));\n        }\n        return result;\n    }\n\n    static HatchPattern FromFile(const char *filename, double scale) {\n        std::ifstream fi(filename);\n        return FromFile(fi, scale);\n    }\n};\n\ntemplate<class It, class Cb, class Wr>\nvoid xyhatch(const Dash &pattern, It start, It end, Cb cb, std::vector<Segment> &uvsegments, std::vector<Intersection> &uu, Wr wr) {\n    uvsegments.clear();\n    bool swapped = pattern.tf.determinant() < 0;\n    std::transform(start, end, std::back_inserter(uvsegments),\n        [&](const Segment &s)\n        { return Segment{s.p * pattern.tf, s.q * pattern.tf, swapped != s.swapped };\n    });\n    uvspans(pattern, std::move(uvsegments), [&](double v, double u1, double u2) {\n        Point p{u1, v}, q{u2, v};\n        Segment xy{ p * pattern.tr, q * pattern.tr, false };\n        cb(xy);\n    }, uu, wr);\n}\n\ntemplate<class It, class Cb, class Wr>\nvoid xyhatch(const HatchPattern &pattern, It start, It end, Cb cb, Wr wr) {\n    std::vector<Segment> uvsegments;\n    uvsegments.reserve(end-start);\n    std::vector<Intersection> uu;\n    uu.reserve(8);\n    for(const auto &i : pattern.d) xyhatch(i, start, end, cb, uvsegments, uu, wr);\n}\n\ntemplate<class C, class Cb, class Wr>\nvoid xyhatch(const HatchPattern &pattern, const C &c, Cb cb, Wr wr) {\n    xyhatch(pattern, c.begin(), c.end(), cb, wr);\n}\n\n}\n#endif\n", "meta": {"hexsha": "57794f3720a2ac7002ec8bd1d26956270d4210aa", "size": 8116, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dashing.hh", "max_stars_repo_name": "jepler/dashing", "max_stars_repo_head_hexsha": "2bb91cceebd6cabdcfcdc50a56fb9d3f32d32087", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-08-20T14:18:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-04T07:51:09.000Z", "max_issues_repo_path": "dashing.hh", "max_issues_repo_name": "jepler/dashing", "max_issues_repo_head_hexsha": "2bb91cceebd6cabdcfcdc50a56fb9d3f32d32087", "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": "dashing.hh", "max_forks_repo_name": "jepler/dashing", "max_forks_repo_head_hexsha": "2bb91cceebd6cabdcfcdc50a56fb9d3f32d32087", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-10-27T19:28:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-25T15:47:43.000Z", "avg_line_length": 32.7258064516, "max_line_length": 132, "alphanum_fraction": 0.6054706752, "num_tokens": 2175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5180622093278681}}
{"text": "#include <dai/alldai.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include \"dai/emrun.h\"\n#include <dai/util.h>\n#include <string>\n#include <sys/stat.h>\n#include <time.h>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/generator_iterator.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <iomanip>      // std::setprecision\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <boost/lexical_cast.hpp>\n#include <boost/tokenizer.hpp>\n#include <algorithm>\n#include<math.h>\nusing namespace std;\nusing namespace dai;\nusing namespace boost;\nvoid seed()\n{\n\t/*Declare variable to hold seconds on clock.*/\n    //\ttime_t seconds;\n\t/*Get value from system clock and place in seconds variable.*/\n    //\ttime(&seconds);\n\t/*Convert seconds to a unsigned integer.*/\n    struct timeval time;\n    gettimeofday(&time,NULL);\n    \n    // microsecond has 1 000 000\n    srand((time.tv_sec * 1000) + (time.tv_usec));\n    //  rnd_seed((time.tv_sec * 1000) + (time.tv_usec / 10) );\n}\ndouble unifRand()\n{\n    return rand()/double(RAND_MAX);\n}\n\n\n// Define a random number generator and initialize it with a reproducible\n// seed.\nmt19937 generator(42);\n\n// Define a uniform random number distribution which produces \"double\"\n// values between 0 and 1 (0 inclusive, 1 exclusive).\nboost::uniform_real<> uni_dist(0,1);\nboost::variate_generator<mt19937&, boost::uniform_real<> > uni(generator, uni_dist);\n\nboost::normal_distribution<> nd(0.0, 1.0);\nboost::variate_generator<mt19937&, boost::normal_distribution<> > normal(generator, nd);\nint main()\n{\n    generator.seed(static_cast<unsigned int>(std::time(0)));\n    seed();\n    \n    for (int i=0; i<10; i++)\n    {\n        \n    cout<<normal()<<\" \"<<uni()<<\" \"<<rnd_stdnormal()<<\" \"<<rnd_uniform()<<\" \"<<unifRand()<<endl;\n    }\n    return 0;\n}\n//\n//int main()\n//{\n//\n//std::vector<double> vec;\n//seed();\n//  for (int i=0; i<10; i++) {\n//\tvec.push_back(unifRand());\n//\t//cout<<vec[i]<<endl;\n//\t//++p[int(number)];\n//  }\n//\n//const double total = std::accumulate(vec.begin(), vec.end(), 0.0);\n//for (double& value: vec) \n//\t{\n// \tvalue /= total;\n//\tcout<<value <<endl;\n//\t}\n//\n//  return 0;\n//}\n", "meta": {"hexsha": "1ca3df7c6608a2efb3dbdbc7dc668b22e2b8f591", "size": 2387, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/normal_distribution.cpp", "max_stars_repo_name": "Priyaaks/libDAI_P", "max_stars_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "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/normal_distribution.cpp", "max_issues_repo_name": "Priyaaks/libDAI_P", "max_issues_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "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/normal_distribution.cpp", "max_forks_repo_name": "Priyaaks/libDAI_P", "max_forks_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6666666667, "max_line_length": 96, "alphanum_fraction": 0.6711353163, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5180621973969943}}
{"text": "\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// Copyright Paul A. Bristow 2015 - 2016.\n// Copyright Christopher Kormanyos 2015 - 2016.\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n// This file also includes Doxygen-style documentation about the function of the code.\n// See http://www.doxygen.org for details.\n\n//! \\file\n\n// Below are snippets of code that can be included into a Quickbook file.\n\n#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <typeinfo>\n\n//[fixed_point_include_1\n#include <boost/fixed_point/fixed_point.hpp>\n//] [/fixed_point_include_1]\n\n//[fixed_point_typedef_1\ntypedef boost::fixed_point::negatable<15, -16> fixed_point_type;\n//] [/fixed_point_typedef_1]\n\nint main()\n{\n  try\n  {\n    std::cout.precision(std::numeric_limits<fixed_point_type>::digits10 + 1);\n\n//[show_numeric_limits_1\n\n    std::cout << \"Numeric_limits for type\"                                                 << std::endl\n              << typeid(fixed_point_type).name()                                           << std::endl\n              << \"digits10     = \" <<  std::numeric_limits<fixed_point_type>::digits10     << std::endl\n              << \"max_digits10 = \" <<  std::numeric_limits<fixed_point_type>::max_digits10 << std::endl\n              << \"radix        = \" <<  std::numeric_limits<fixed_point_type>::radix        << std::endl\n              << \"epsilon      = \" <<  std::numeric_limits<fixed_point_type>::epsilon()    << std::endl\n              << \"max          = \" << (std::numeric_limits<fixed_point_type>::max)()       << std::endl\n              << \"min          = \" << (std::numeric_limits<fixed_point_type>::min)()       << std::endl\n              << \"lowest       = \" <<  std::numeric_limits<fixed_point_type>::lowest()     << std::endl\n              ;\n\n    if(std::numeric_limits<fixed_point_type>::has_infinity)\n    {\n      std::cout << \"infinity = \" << std::numeric_limits<fixed_point_type>::infinity() << std::endl;\n    }\n    else\n    {\n      std::cout << \"Type does not have an infinity\" << std::endl;\n    }\n\n    if (std::numeric_limits<fixed_point_type>::has_quiet_NaN)\n    {\n      std::cout << \"NaN = \" << std::numeric_limits<fixed_point_type>::quiet_NaN() << std::endl;\n    }\n    else\n    {\n      std::cout << \"Type does not have a NaN\" << std::endl;\n    }\n//] [/show_numeric_limits_1]\n\n    std::cout.setf(std::ios::boolalpha | std::ios::showpoint); // Show any trailing zeros.\n    std::cout << std::endl;\n\n//[fixed_example_1\n\n    fixed_point_type x = fixed_point_type(123) /   100;\n    fixed_point_type y = fixed_point_type(456) / 10000;\n\n    // Show all the significant digits for this particular floating-point type.\n    std::cout.precision(std::numeric_limits<fixed_point_type>::digits10);\n\n    std::cout << \"x = fixed_point_type(123) /   100 = \"\n              << x // 1.22999573 is the nearest representation of decimal digit string 1.23.\n              << std::endl;\n\n    std::cout << \"y = fixed_point_type(456) / 10000 = \"\n              << y // 0.0455932617 is the nearest representation of decimal digit string 0.0456\n              << std::endl;\n\n    x = -x / 2; // Do some trivial arithmetic.\n\n    std::cout <<\"x = -x / 2 = \"\n              << x // -0.614990234  is the nearest representation of decimal digit string -0.615\n              << std::endl;\n\n//] [/fixed_example_1]\n\n//[fixed_example_functions\n\n    int exponential;\n\n    x = frexp(x, &exponential);\n\n    std::cout << \"x = frexp(x, &exponential) = \"\n              << x // 0.614990234\n              << \" exponential = \"\n              << exponential\n              << std::endl; // 0\n\n    exponential++; // double the value.\n\n    std::cout << \"double the value\" << std::endl;\n\n    x = ldexp(x, exponential);\n\n    // Show the fraction and exponent parts after changing the exponent.\n    std::cout << \"x = frexp(x, &exponential) = \"\n              << frexp(x, &exponential) // -0.614990234\n              << \" exponential = \"\n              << exponential\n              << std::endl; // 1\n\n    // Other C numeric math functions (cmath) are available, of course, for example:\n    std::cout << \"ldexp(x, exponential); = \"\n              << x\n              << std::endl; // -1.22998047\n\n    std::cout << \"abs  (x)       = \"\n              <<  abs(x)\n              << std::endl; // 1.22998047\n\n    std::cout << \"fabs (x)       = \" << fabs(x) << std::endl; // 1.22998047\n\n    std::cout << \"sqrt (fabs(x)) = \"\n              <<  sqrt(fabs(x))\n              << std::endl; //  = 0.\n\n    std::cout << \"sqrt (y)       = \"\n              <<  sqrt(y)\n              << std::endl; //  = 0.213516235\n\n//] [/fixed_example_functions]\n  }\n  catch(const std::exception& ex)\n  {\n    std::cout << ex.what() << std::endl;\n  }\n}\n\n\n/*\n//[numeric_limits_output_1\nNumeric_limits for type\nclass boost::fixed_point::negatable<15,-16,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined>\ndigits10     = 9\nmax_digits10 = 11\nradix        = 2\nepsilon      = 3.051757813e-005\nmax          = 32767.99998\nmin          = 1.525878906e-005\nlowest       = -32768\nType does not have an infinity\nType does not have a NaN\n\nx = fixed_point_type(123) /   100 = 1.22999573\ny = fixed_point_type(456) / 10000 = 0.0455932617\nx = -x / 2 = -0.614990234\n//] [/numeric_limits_output_1]\n\n//[fixed_example_functions_output\nx = frexp(x, &exponential) = -0.614990234 exponential = 0\ndouble the value\nx = frexp(x, &exponential) = -0.614990234 exponential = 1\nldexp(x, exponential); = -1.22998047\nabs  (x)       = 1.22998047\nfabs (x)       = 1.22998047\nsqrt (fabs(x)) = 1.10902405\nsqrt (y)       = 0.213516235\n//] [/fixed_example_functions_output]\n\n*/\n", "meta": {"hexsha": "a9874bbd3c5b88a388eb4d78d86292454388f04a", "size": 6077, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_demo_basic.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_demo_basic.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_demo_basic.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": 32.6720430108, "max_line_length": 132, "alphanum_fraction": 0.5887773572, "num_tokens": 1686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.7826624840223699, "lm_q1q2_score": 0.5180621918045328}}
{"text": "#include \"consts.hpp\"\n#include \"gamma.hpp\"\n\n#include <math.h>\n#include <limits>\n#include <boost/numeric/conversion/cast.hpp>\n\nnamespace cephes {\n\nconstexpr double ASYMP_FACTOR = 1e6;\n\ndouble lbeta_asymp(double a, double b, int *sgn);\ndouble lbeta_negint(int a, double b);\ndouble beta_negint(int a, double b);\n\ndouble beta(double a, double b)\n{\n    double y;\n    int sign = 1;\n\n    if (a <= 0.0) {\n        if (a == std::floor(a)) {\n            if (a == boost::numeric_cast<int>(a)) {\n                return beta_negint(boost::numeric_cast<int>(a), b);\n            }\n            else {\n                goto overflow;\n            }\n        }\n    }\n\n    if (b <= 0.0) {\n        if (b == std::floor(b)) {\n            if (b == boost::numeric_cast<int>(b)) {\n                return beta_negint(boost::numeric_cast<int>(b), a);\n            }\n            else {\n                goto overflow;\n            }\n        }\n    }\n\n    if (std::fabs(a) < std::fabs(b)) {\n        y = a; a = b; b = y;\n    }\n\n    if (std::fabs(a) > ASYMP_FACTOR * std::fabs(b) && a > ASYMP_FACTOR) {\n        /* Avoid loss of precision in lgam(a + b) - lgam(a) */\n        y = lbeta_asymp(a, b, &sign);\n        return sign * std::exp(y);\n    }\n\n    y = a + b;\n    if (std::fabs(y) > MAXGAM || std::fabs(a) > MAXGAM || std::fabs(b) > MAXGAM) {\n\tint sgngam;\n\ty = lgam_sgn(y, &sgngam);\n\tsign *= sgngam;\t\t/* keep track of the sign */\n\ty = lgam_sgn(b, &sgngam) - y;\n\tsign *= sgngam;\n\ty = lgam_sgn(a, &sgngam) + y;\n\tsign *= sgngam;\n\tif (y > MAXLOG) {\n\t    goto overflow;\n\t}\n\treturn (sign * std::exp(y));\n    }\n\n    y = Gamma(y);\n    a = Gamma(a);\n    b = Gamma(b);\n    if (y == 0.0)\n        goto overflow;\n\n    if (std::fabs(std::fabs(a) - std::fabs(y)) > std::fabs(std::fabs(b) - std::fabs(y))) {\n        y = b / y;\n        y *= a;\n    }\n    else {\n        y = a / y;\n        y *= b;\n    }\n\n    return (y);\n\noverflow:\n    return (sign * std::numeric_limits<double>::infinity());\n}\n\n\n/* Natural log of |beta|. */\n\ndouble lbeta(double a, double b)\n{\n    double y;\n    int sign;\n\n    sign = 1;\n\n    if (a <= 0.0) {\n        if (a == std::floor(a)) {\n            if (a == boost::numeric_cast<int>(a)) {\n                return lbeta_negint(boost::numeric_cast<int>(a), b);\n            }\n            else {\n                goto over;\n            }\n        }\n    }\n\n    if (b <= 0.0) {\n        if (b == std::floor(b)) {\n            if (b == boost::numeric_cast<int>(b)) {\n                return lbeta_negint(boost::numeric_cast<int>(b), a);\n            }\n            else {\n                goto over;\n            }\n        }\n    }\n\n    if (std::fabs(a) < std::fabs(b)) {\n        y = a; a = b; b = y;\n    }\n\n    if (std::fabs(a) > ASYMP_FACTOR * std::fabs(b) && a > ASYMP_FACTOR) {\n        /* Avoid loss of precision in lgam(a + b) - lgam(a) */\n        y = lbeta_asymp(a, b, &sign);\n        return y;\n    }\n\n    y = a + b;\n    if (std::fabs(y) > MAXGAM || std::fabs(a) > MAXGAM || std::fabs(b) > MAXGAM) {\n\tint sgngam;\n\ty = lgam_sgn(y, &sgngam);\n\tsign *= sgngam;\t\t/* keep track of the sign */\n\ty = lgam_sgn(b, &sgngam) - y;\n\tsign *= sgngam;\n\ty = lgam_sgn(a, &sgngam) + y;\n\tsign *= sgngam;\n\treturn (y);\n    }\n\n    y = Gamma(y);\n    a = Gamma(a);\n    b = Gamma(b);\n    if (y == 0.0) {\n      over:\n        return (sign * std::numeric_limits<double>::infinity());\n    }\n\n    if (std::fabs(std::fabs(a) - std::fabs(y)) > std::fabs(std::fabs(b) - std::fabs(y))) {\n        y = b / y;\n        y *= a;\n    }\n    else {\n        y = a / y;\n        y *= b;\n    }\n\n    if (y < 0) {\n\ty = -y;\n    }\n\n    return std::log(y);\n}\n\n/*\n * Asymptotic expansion for  ln(|B(a, b)|) for a > ASYMP_FACTOR*max(|b|, 1).\n */\ndouble lbeta_asymp(double a, double b, int *sgn)\n{\n    double r = lgam_sgn(b, sgn);\n    r -= b * std::log(a);\n\n    r += b*(1-b)/(2*a);\n    r += b*(1-b)*(1-2*b)/(12*a*a);\n    r += - b*b*(1-b)*(1-b)/(12*a*a*a);\n\n    return r;\n}\n\n\n/*\n * Special case for a negative integer argument\n */\n\ndouble beta_negint(int a, double b)\n{\n    int sgn;\n    if (b == boost::numeric_cast<int>(b) && 1 - a - b > 0) {\n        sgn = (boost::numeric_cast<int>(b) % 2 == 0) ? 1 : -1;\n        return sgn * beta(1 - a - b, b);\n    }\n    else {\n        return std::numeric_limits<double>::infinity();\n    }\n}\n\ndouble lbeta_negint(int a, double b)\n{\n    double r;\n    if (b == boost::numeric_cast<int>(b) && 1 - a - b > 0) {\n        r = lbeta(1 - a - b, b);\n        return r;\n    }\n    else {\n        return std::numeric_limits<double>::infinity();\n    }\n}\n\n}\n", "meta": {"hexsha": "ac5784b172248e0c799908b976854f344ce22f23", "size": 4475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/cephes/beta.cpp", "max_stars_repo_name": "ufora/ufora", "max_stars_repo_head_hexsha": "04db96ab049b8499d6d6526445f4f9857f1b6c7e", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_stars_count": 571.0, "max_stars_repo_stars_event_min_datetime": "2015-11-05T20:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T22:31:09.000Z", "max_issues_repo_path": "third_party/cephes/beta.cpp", "max_issues_repo_name": "timgates42/ufora", "max_issues_repo_head_hexsha": "04db96ab049b8499d6d6526445f4f9857f1b6c7e", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_issues_count": 218.0, "max_issues_repo_issues_event_min_datetime": "2015-11-05T20:37:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-30T03:53:50.000Z", "max_forks_repo_path": "third_party/cephes/beta.cpp", "max_forks_repo_name": "timgates42/ufora", "max_forks_repo_head_hexsha": "04db96ab049b8499d6d6526445f4f9857f1b6c7e", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-11-07T21:42:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T03:48:19.000Z", "avg_line_length": 21.108490566, "max_line_length": 90, "alphanum_fraction": 0.4661452514, "num_tokens": 1438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5180363830624161}}
{"text": "#ifndef OCV_ARMA_DIST_METRIC_HPP\n#define OCV_ARMA_DIST_METRIC_HPP\n\n#include \"../arma/type_traits.hpp\"\n\n#include <armadillo>\n\n/*!\n *  \\addtogroup ocv\n *  @{\n */\nnamespace ocv{\n\n/*!\n *  \\addtogroup armd\n *  @{\n */\nnamespace armd{\n\nnamespace details{\n\ntemplate<typename T,\n         typename Hist1,\n         typename Hist2,\n         typename Index>\nstruct type_constraint\n{\n    static_assert(std::is_floating_point<T>::value,\n                  \"T should be floating point\");\n    static_assert(std::is_same<typename Hist1::elem_type,\n                  typename Hist2::elem_type>::value,\n                  \"elem type of Hist1 and Hist2 \"\n                  \"should be the same one\");\n    static_assert(std::is_floating_point<typename Hist1::elem_type>::value,\n                  \"elem type of Hist1 and Hist2 should \"\n                  \"be floating point\");\n    static_assert(std::is_integral<Index>::value,\n                  \"Index should be integral\");\n    static_assert(is_two_dim<Hist2>::value,\n                  \"Hist2 should be arma::Mat or \"\n                  \"arma::SpMat\");\n};\n\ntemplate<typename T, typename U>\ninline\ntypename std::enable_if<\narma::is_arma_sparse_type<U>::value ||\n(arma::is_arma_type<U>::value &&\n !std::is_same<T, typename U::elem_type>::value),\narma::Col<T>>::type\nto_colvec(U const &input)\n{    \n    return arma::Col<T>(input);\n}\n\ntemplate<typename T, typename U>\ninline\ntypename std::enable_if<\narma::is_arma_type<U>::value &&\nstd::is_same<T, typename U::elem_type>::value,\nU>::type const&\nto_colvec(U const &input)\n{    \n    return input;\n}\n\n}\n\n/**\n * measure chi square distance\n * @tparam T return type of compare\n */\ntemplate<typename T = float>\nstruct cosine_similarity\n{\n    using result_type = T;\n\n    template<typename Hist1,\n             typename Hist2,\n             typename Index>\n    T compare(Hist1 const &query_hist,\n              Hist2 const &datahist,\n              Index const &index) const\n    {\n        using namespace details;\n        details::type_constraint<T,Hist1,Hist2,Index>();\n\n        return similarity_compute(to_colvec<T>(query_hist),\n                                  to_colvec<T>(datahist.col(index)));\n    }\n\nprivate:    \n    template<typename U, typename V>\n    T similarity_compute(U const &lhs,\n                         V const &rhs) const\n    {       \n        auto const denom =\n                std::sqrt(arma::sum(lhs.col(0) % lhs.col(0))) *\n                std::sqrt(arma::sum(rhs % rhs)) +\n                T(1e-10);\n\n        return arma::sum((lhs % rhs)) / (denom);\n    }\n};\n\n/**\n * measure chi square distance\n * @tparam T return type of compare\n */\ntemplate<typename T = float>\nstruct chi_square{\n\n    using result_type = T;\n\n    template<typename Hist1,\n             typename Hist2,\n             typename Index>\n    T compare(Hist1 const &query_hist,\n              Hist2 const &datahist,\n              Index const &index) const\n    {\n        using namespace details;\n        type_constraint<T,Hist1,Hist2,Index>();\n\n        return chi_square_compute(to_colvec<T>(query_hist),\n                                  to_colvec<T>(datahist.col(index)));\n    }\n\nprivate:    \n    template<typename U, typename V>\n    T chi_square_compute(U const &lhs,\n                         V const &rhs) const\n    {\n        return arma::sum(arma::square(lhs - rhs) /\n                         (lhs + rhs + T(1e-10)));\n    }\n\n};\n\n} /*! @} End of Doxygen Groups*/\n\n} /*! @} End of Doxygen Groups*/\n\n#endif // DIST_METRIC_HPP\n", "meta": {"hexsha": "82c36bd15dce611c2c41c1b8f931e8e2c4856fdd", "size": 3465, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "arma/dist_metric.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": "arma/dist_metric.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": "arma/dist_metric.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": 23.8965517241, "max_line_length": 75, "alphanum_fraction": 0.5812409812, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5180334601665908}}
{"text": "#include \"joint_tracker/RevoluteJointFilter.h\"\n\n#include \"omip_common/OMIPUtils.h\"\n\n#include <Eigen/Geometry>\n\n#include <boost/math/distributions/chi_squared.hpp>\n\n#include \"geometry_msgs/PoseWithCovarianceStamped.h\"\n\n#include \"std_msgs/Float64MultiArray.h\"\n\nusing namespace omip;\nusing namespace MatrixWrapper;\nusing namespace BFL;\n\n// Dimensions of the system state of the filter that tracks a revolute joint: orientation (2 values), position (3 values), joint variable, and joint velocity\n#define REV_STATE_DIM 7\n#define MEAS_DIM 6\n\n/**\n * EKF internal state:\n *\n * x(1) =  RevJointOrientation_phi\n * x(2) =  RevJointOrientation_theta\n * RevJointOrientation is represented in spherical coords\n * x(3) = RevJointPosition_x\n * x(4) = RevJointPosition_y\n * x(5) = RevJointPosition_z\n * x(6) = RevJointVariable\n * x(7) = RevJointVariable_d\n *\n * EKF measurement:\n *\n * m(1) = TwistLinearPart_x\n * m(2) = TwistLinearPart_y\n * m(3) = TwistLinearPart_z\n * m(4) = TwistAngularPart_x\n * m(5) = TwistAngularPart_y\n * m(6) = TwistAngularPart_z\n */\n\nusing namespace omip;\n\nRevoluteJointFilter::RevoluteJointFilter() :\n    JointFilter(),\n    _sys_PDF(NULL),\n    _sys_MODEL(NULL),\n    _meas_PDF(NULL),\n    _meas_MODEL(NULL),\n    _ekf(NULL),\n    _sigma_delta_meas_uncertainty_angular(-1),\n    _accumulated_rotation(0.0)\n{\n}\n\nvoid RevoluteJointFilter::setCovarianceDeltaMeasurementAngular(double sigma_delta_meas_uncertainty_angular)\n{\n    this->_sigma_delta_meas_uncertainty_angular = sigma_delta_meas_uncertainty_angular;\n}\n\nvoid RevoluteJointFilter::initialize()\n{\n    JointFilter::initialize();\n    this->_joint_orientation = Eigen::Vector3d( this->_current_delta_pose_in_rrbf.rx(),\n                                                    this->_current_delta_pose_in_rrbf.ry(),\n                                                    this->_current_delta_pose_in_rrbf.rz());\n    this->_joint_state = this->_joint_orientation.norm();\n    //this->_joint_velocity = this->_joint_state/(this->_loop_period_ns/1e9);\n    // Setting it to 0 is better.\n    // The best approximation would be to (this->_joint_state/num_steps_to_joint_state)/(this->_loop_period_ns/1e9)\n    // but we don't know how many steps passed since we estimated the first time the joint variable\n    this->_joint_velocity = 0.0;\n\n    this->_joint_states_all.push_back(this->_joint_state);\n\n    Eigen::Vector3d linear_part = Eigen::Vector3d( this->_current_delta_pose_in_rrbf.vx(),\n                                                   this->_current_delta_pose_in_rrbf.vy(),\n                                                   this->_current_delta_pose_in_rrbf.vz());\n// Alternative\n//    Eigen::Matrix4d ht;\n//    Twist2TransformMatrix(_current_delta_pose_in_rrbf, ht);\n\n//    this->_joint_position = ht.block<3,1>(0,3)\n//            - ht.block<3,3>(0,0)*ht.block<3,1>(0,3);\n\n    this->_joint_position = (1.0 / (pow(this->_joint_state, 2))) * this->_joint_orientation.cross(linear_part);\n    this->_joint_orientation.normalize();\n\n    this->_initializeSystemModel();\n    this->_initializeMeasurementModel();\n    this->_initializeEKF();\n}\n\nvoid RevoluteJointFilter::setMinRotationRevolute(const double& value)\n{\n    _rev_min_rot_for_ee = value;\n}\n\nvoid RevoluteJointFilter::setMaxRadiusDistanceRevolute(const double& value)\n{\n    _rev_max_joint_distance_for_ee = value;\n}\n\nvoid RevoluteJointFilter::_initializeSystemModel()\n{\n    // create SYSTEM MODEL\n    Matrix A(REV_STATE_DIM, REV_STATE_DIM);\n    A = 0.;\n    for (unsigned int i = 1; i <= REV_STATE_DIM; i++)\n    {\n        A(i, i) = 1.0;\n    }\n    A(6, 7) = this->_loop_period_ns/1e9; //Adding the velocity to the position of the joint variable\n\n    ColumnVector sys_noise_MU(REV_STATE_DIM);\n    sys_noise_MU = 0;\n\n    SymmetricMatrix sys_noise_COV(REV_STATE_DIM);\n    sys_noise_COV = 0.0;\n    sys_noise_COV(1, 1) = this->_sigma_sys_noise_phi* (std::pow((this->_loop_period_ns/1e9),3) / 3.0); // PHI\n    sys_noise_COV(2, 2) = this->_sigma_sys_noise_theta* (std::pow((this->_loop_period_ns/1e9),3) / 3.0); // THETA\n    sys_noise_COV(3, 3) = this->_sigma_sys_noise_px* (std::pow((this->_loop_period_ns/1e9),3) / 3.0); // Px\n    sys_noise_COV(4, 4) = this->_sigma_sys_noise_py* (std::pow((this->_loop_period_ns/1e9),3) / 3.0); // Py\n    sys_noise_COV(5, 5) = this->_sigma_sys_noise_pz* (std::pow((this->_loop_period_ns/1e9),3) / 3.0); // Pz\n    sys_noise_COV(6, 6) = this->_sigma_sys_noise_jv* (std::pow((this->_loop_period_ns/1e9),3) / 3.0); // pv\n    sys_noise_COV(7, 7) = this->_sigma_sys_noise_jvd*(this->_loop_period_ns/1e9); // d(pv)/dt\n\n    // Initialize System Model\n    Gaussian system_uncertainty_PDF(sys_noise_MU, sys_noise_COV);\n    this->_sys_PDF = new LinearAnalyticConditionalGaussian( A, system_uncertainty_PDF);\n    this->_sys_MODEL = new LinearAnalyticSystemModelGaussianUncertainty( this->_sys_PDF);\n}\n\nvoid RevoluteJointFilter::_initializeMeasurementModel()\n{\n    // create MEASUREMENT MODEL\n    ColumnVector meas_noise_MU(MEAS_DIM);\n    meas_noise_MU = 0.0;\n    SymmetricMatrix meas_noise_COV(MEAS_DIM);\n    meas_noise_COV = 0.0;\n    for (unsigned int i = 1; i <= MEAS_DIM; i++)\n        meas_noise_COV(i, i) = this->_sigma_meas_noise;\n\n    Gaussian meas_uncertainty_PDF(meas_noise_MU, meas_noise_COV);\n\n    this->_meas_PDF = new NonLinearRevoluteMeasurementPdf(meas_uncertainty_PDF);\n    this->_meas_MODEL = new AnalyticMeasurementModelGaussianUncertainty(this->_meas_PDF);\n}\n\nvoid RevoluteJointFilter::_initializeEKF()\n{\n    ColumnVector prior_MU(REV_STATE_DIM);\n    prior_MU = 0.0;\n\n    SymmetricMatrix prior_COV(REV_STATE_DIM);\n    prior_COV = 0.0;\n\n    // This is weird but happens when working with synthetic data\n    // We don't want to divide by 0!\n    if(this->_joint_orientation.x() == 0.0)\n    {\n        this->_joint_orientation.x() = 1e-6;\n    }\n\n    prior_MU(1) = atan2( this->_joint_orientation.y() , this->_joint_orientation.x());\n    prior_MU(2) = acos(this->_joint_orientation.z());\n    prior_MU(3) = this->_joint_position.x();\n    prior_MU(4) = this->_joint_position.y();\n    prior_MU(5) = this->_joint_position.z();\n    prior_MU(6) = this->_joint_state;\n    prior_MU(7) = this->_joint_velocity;\n\n\n    for (int i = 1; i <= REV_STATE_DIM; i++)\n    {\n        prior_COV(i, i) = _prior_cov_vel;\n    }\n\n    Gaussian prior_PDF(prior_MU, prior_COV);\n\n    this->_ekf = new ExtendedKalmanFilter(&prior_PDF);\n}\n\nRevoluteJointFilter::~RevoluteJointFilter()\n{\n    if (this->_sys_PDF)\n    {\n        delete this->_sys_PDF;\n        this->_sys_PDF = NULL;\n    }\n    if (this->_sys_MODEL)\n    {\n        delete this->_sys_MODEL;\n        this->_sys_MODEL = NULL;\n    }\n    if (this->_meas_PDF)\n    {\n        delete this->_meas_PDF;\n        this->_meas_PDF = NULL;\n    }\n    if (this->_meas_MODEL)\n    {\n        delete this->_meas_MODEL;\n        this->_meas_MODEL = NULL;\n    }\n    if (this->_ekf)\n    {\n        delete this->_ekf;\n        this->_ekf = NULL;\n    }\n}\n\nRevoluteJointFilter::RevoluteJointFilter(const RevoluteJointFilter &rev_joint) :\n    JointFilter(rev_joint)\n{\n    this->_sigma_delta_meas_uncertainty_angular = rev_joint._sigma_delta_meas_uncertainty_angular;\n    this->_sys_PDF = new LinearAnalyticConditionalGaussian(*(rev_joint._sys_PDF));\n    this->_sys_MODEL = new LinearAnalyticSystemModelGaussianUncertainty( *(rev_joint._sys_MODEL));\n    this->_meas_PDF = new NonLinearRevoluteMeasurementPdf(*(rev_joint._meas_PDF));\n    this->_meas_MODEL = new AnalyticMeasurementModelGaussianUncertainty( *(rev_joint._meas_MODEL));\n    this->_ekf = new ExtendedKalmanFilter(*(rev_joint._ekf));\n}\n\nvoid RevoluteJointFilter::predictState(double time_interval_ns)\n{\n    // Estimate the new cov matrix depending on the time elapsed between the previous and the current measurement\n    SymmetricMatrix sys_noise_COV(REV_STATE_DIM);\n    sys_noise_COV = 0.0;\n    sys_noise_COV(1, 1) = this->_sigma_sys_noise_phi* (std::pow((time_interval_ns/1e9),3) / 3.0); // PHI\n    sys_noise_COV(2, 2) = this->_sigma_sys_noise_theta* (std::pow((time_interval_ns/1e9),3) / 3.0); // THETA\n    sys_noise_COV(3, 3) = this->_sigma_sys_noise_px* (std::pow((time_interval_ns/1e9),3) / 3.0); // Px\n    sys_noise_COV(4, 4) = this->_sigma_sys_noise_py* (std::pow((time_interval_ns/1e9),3) / 3.0); // Py\n    sys_noise_COV(5, 5) = this->_sigma_sys_noise_pz* (std::pow((time_interval_ns/1e9),3) / 3.0); // Pz\n    sys_noise_COV(6, 6) = this->_sigma_sys_noise_jv* (std::pow((time_interval_ns/1e9),3) / 3.0); // pv\n    sys_noise_COV(7, 7) = this->_sigma_sys_noise_jvd*(time_interval_ns/1e9); // d(pv)/dt\n\n    // Estimate the new updating matrix which also depends on the time elapsed between the previous and the current measurement\n    // x(t+1) = x(t) + v(t) * delta_t\n    Matrix A(REV_STATE_DIM, REV_STATE_DIM);\n    A = 0.;\n    for (unsigned int i = 1; i <= REV_STATE_DIM; i++)\n    {\n        A(i, i) = 1.0;\n    }\n    A(6, 7) = time_interval_ns/1e9;; //Adding the velocity (times the time) to the position of the joint variable\n\n    this->_sys_PDF->MatrixSet(0, A);\n    this->_sys_PDF->AdditiveNoiseSigmaSet(sys_noise_COV);\n    //The system update\n    this->_ekf->Update(this->_sys_MODEL);\n}\n\nvoid RevoluteJointFilter::predictMeasurement()\n{\n    ColumnVector empty;\n    ColumnVector state_updated_state = this->_ekf->PostGet()->ExpectedValueGet();\n\n    ColumnVector predicted_delta_pose_in_rrbf = this->_meas_MODEL->PredictionGet(empty, state_updated_state);\n\n    this->_predicted_delta_pose_in_rrbf = Eigen::Twistd( predicted_delta_pose_in_rrbf(4), predicted_delta_pose_in_rrbf(5),\n                                                         predicted_delta_pose_in_rrbf(6), predicted_delta_pose_in_rrbf(1),\n                                                         predicted_delta_pose_in_rrbf(2), predicted_delta_pose_in_rrbf(3));\n\n    Eigen::Displacementd predicted_delta = this->_predicted_delta_pose_in_rrbf.exp(1e-20);\n    Eigen::Displacementd T_rrbf_srbf_t0 = this->_srb_initial_pose_in_rrbf.exp(1.0e-20);\n    Eigen::Displacementd T_rrbf_srbf_t_next = predicted_delta * T_rrbf_srbf_t0;\n\n    this->_srb_predicted_pose_in_rrbf = T_rrbf_srbf_t_next.log(1.0e-20);\n\n    bool change = false;\n    this->_srb_predicted_pose_in_rrbf = unwrapTwist(this->_srb_predicted_pose_in_rrbf, T_rrbf_srbf_t_next, this->_srb_previous_predicted_pose_in_rrbf, change);\n\n    this->_srb_previous_predicted_pose_in_rrbf = this->_srb_predicted_pose_in_rrbf;\n}\n\nvoid RevoluteJointFilter::correctState()\n{\n    ColumnVector updated_state = this->_ekf->PostGet()->ExpectedValueGet();\n    ColumnVector rb2_measured_delta_relative_pose_cv(MEAS_DIM);\n    rb2_measured_delta_relative_pose_cv = 0.;\n    rb2_measured_delta_relative_pose_cv(1) = this->_current_delta_pose_in_rrbf.vx();\n    rb2_measured_delta_relative_pose_cv(2) = this->_current_delta_pose_in_rrbf.vy();\n    rb2_measured_delta_relative_pose_cv(3) = this->_current_delta_pose_in_rrbf.vz();\n    rb2_measured_delta_relative_pose_cv(4) = this->_current_delta_pose_in_rrbf.rx();\n    rb2_measured_delta_relative_pose_cv(5) = this->_current_delta_pose_in_rrbf.ry();\n    rb2_measured_delta_relative_pose_cv(6) = this->_current_delta_pose_in_rrbf.rz();\n\n    // Update the uncertainty on the measurement\n    // The uncertainty on the measurement (the delta motion of the second rigid body wrt the reference rigid body) will be large if the measurement\n    // is small and small if the measurement is large\n    // Also at 2PI the uncertainty should be high (rotational periodicity of the exponential map)\n    Eigen::Vector3d angular_component(this->_current_delta_pose_in_rrbf.rx(), this->_current_delta_pose_in_rrbf.ry(), this->_current_delta_pose_in_rrbf.rz());\n    double meas_uncertainty_factor = 1 / (1.0 - exp(-sin(angular_component.norm()/2.0)/this->_sigma_delta_meas_uncertainty_angular));\n\n    // Truncate the factor\n    meas_uncertainty_factor = std::min(meas_uncertainty_factor, 1e6);\n\n    SymmetricMatrix current_delta_pose_cov_in_rrbf(6);\n    for (unsigned int i = 0; i < 6; i++)\n    {\n        for (unsigned int j = 0; j < 6; j++)\n        {\n            current_delta_pose_cov_in_rrbf(i + 1, j + 1) = _current_delta_pose_cov_in_rrbf(i, j);\n        }\n    }\n\n    this->_meas_PDF->AdditiveNoiseSigmaSet(current_delta_pose_cov_in_rrbf * meas_uncertainty_factor );\n\n    this->_ekf->Update(this->_meas_MODEL, rb2_measured_delta_relative_pose_cv);\n\n    updated_state = this->_ekf->PostGet()->ExpectedValueGet();\n\n    this->_joint_orientation(0) = sin(updated_state(2)) * cos(updated_state(1));\n    this->_joint_orientation(1) = sin(updated_state(2)) * sin(updated_state(1));\n    this->_joint_orientation(2) = cos(updated_state(2));\n\n    SymmetricMatrix updated_uncertainty = this->_ekf->PostGet()->CovarianceGet();\n\n    for(int i=0; i<3; i++)\n    {\n        this->_joint_position(i) = updated_state(i+3);\n        for(int j=0; j<3; j++)\n        {\n            this->_uncertainty_joint_position(i,j) = updated_uncertainty(i+3, j+3);\n        }\n    }\n\n    double joint_state_before = _joint_state;\n\n    // This jump should happen if we are close to 2PI or -2PI rotation\n    if(_from_inverted_to_non_inverted)\n    {\n        _accumulated_rotation = std::round(joint_state_before/(2*M_PI))*2*M_PI;\n    }\n\n    // This jump should happen if we are close to PI or -PI rotation\n    if(_from_non_inverted_to_inverted)\n    {\n        _accumulated_rotation = std::round(joint_state_before/(M_PI))*2*M_PI;\n    }\n\n    this->_joint_state = updated_state(6);\n\n    // If we are inverting the twist is because we are in the interval (PI, 2PI) or (-PI, -2PI)\n    if(_inverted_delta_srb_pose_in_rrbf)\n    {\n        _joint_state = _accumulated_rotation - _joint_state;\n    }else{\n        _joint_state = _accumulated_rotation + _joint_state;\n    }\n\n\n    this->_uncertainty_joint_state = updated_uncertainty(6,6);\n    this->_joint_velocity = updated_state(7);\n    this->_uncertainty_joint_velocity = updated_uncertainty(7,7);\n\n    this->_joint_orientation_phi = updated_state(1);\n    this->_joint_orientation_theta = updated_state(2);\n    this->_uncertainty_joint_orientation_phitheta(0,0) = updated_uncertainty(1, 1);\n    this->_uncertainty_joint_orientation_phitheta(0,1) = updated_uncertainty(1, 2);\n    this->_uncertainty_joint_orientation_phitheta(1,0) = updated_uncertainty(1, 2);\n    this->_uncertainty_joint_orientation_phitheta(1,1) = updated_uncertainty(2, 2);\n}\n\nvoid RevoluteJointFilter::estimateMeasurementHistoryLikelihood()\n{\n    double accumulated_error = 0.;\n\n    double p_one_meas_given_model_params = 0;\n    double p_all_meas_given_model_params = 0;\n\n    double sigma_translation = 0.05;\n    double sigma_rotation = 0.2;\n\n    ColumnVector updated_state = this->_ekf->PostGet()->ExpectedValueGet();\n    double phi = updated_state(1);\n    double theta = updated_state(2);\n    double sp = sin(phi);\n    double cp = cos(phi);\n    double st = sin(theta);\n    double ct = cos(theta);\n\n    double px = updated_state(3);\n    double py = updated_state(4);\n    double pz = updated_state(5);\n\n    this->_joint_states_all.push_back(updated_state(6));\n\n    Eigen::Vector3d rev_joint_rotation_unitary = Eigen::Vector3d(cp * st, sp * st, ct);\n    rev_joint_rotation_unitary.normalize();\n\n    // Convert the screw attributes (line description) to a twist\n    Eigen::Vector3d rev_joint_position = Eigen::Vector3d(px, py, pz);\n    Eigen::Vector3d rev_joint_translation_unitary = (-rev_joint_rotation_unitary).cross(rev_joint_position);\n\n    double counter = 0.;\n    size_t trajectory_length = this->_delta_poses_in_rrbf.size();\n    size_t amount_samples = std::min(trajectory_length, (size_t)this->_likelihood_sample_num);\n    double delta_idx_samples = (double)std::max(1., (double)trajectory_length/(double)this->_likelihood_sample_num);\n    size_t current_idx = 0;\n\n    double max_norm_of_deltas = 0;\n\n    // Estimation of the quality of the parameters of the revolute joint\n    // If the joint is revolute and the parameters are accurate, the joint axis orientation and position should not change over time\n    // That means that the current orientation/position, multiplied by the amount of revolute displacement at each time step, should provide the delta in the relative\n    // pose between ref and second rb at each time step\n    // We test amount_samples of the relative trajectory\n    // I check if the joint is too young or if there is too few rotation and the axis is very far away (a prismatic joint can be seen as a revolute joint where the\n    // joint is far away)\n    // We need to have memory here: if the rotation was once larger than the this->_rev_min_rot_for_ee could be that we returned to the starting relative pose\n\n    for (size_t sample_idx = 0; sample_idx < amount_samples; sample_idx++)\n    {\n        current_idx = boost::math::round(sample_idx*delta_idx_samples);\n        Eigen::Displacementd rb2_last_delta_relative_displ = this->_delta_poses_in_rrbf.at(current_idx).exp(1e-12);\n\n        max_norm_of_deltas = std::max(this->_delta_poses_in_rrbf.at(current_idx).norm(), max_norm_of_deltas);\n\n        Eigen::Vector3d rb2_last_delta_relative_translation = rb2_last_delta_relative_displ.getTranslation();\n        Eigen::Quaterniond rb2_last_delta_relative_rotation = Eigen::Quaterniond(rb2_last_delta_relative_displ.qw(),\n                                                                                 rb2_last_delta_relative_displ.qx(),\n                                                                                 rb2_last_delta_relative_displ.qy(),\n                                                                                 rb2_last_delta_relative_displ.qz());\n\n        Eigen::Vector3d rev_joint_translation = this->_joint_states_all.at(current_idx) * rev_joint_translation_unitary;\n        Eigen::Vector3d rev_joint_rotation = this->_joint_states_all.at(current_idx) * rev_joint_rotation_unitary;\n        Eigen::Displacementd rb2_last_delta_relative_displ_rev_hyp = Eigen::Twistd( rev_joint_rotation.x(),\n                                                                                    rev_joint_rotation.y(),\n                                                                                    rev_joint_rotation.z(),\n                                                                                    rev_joint_translation.x(),\n                                                                                    rev_joint_translation.y(),\n                                                                                    rev_joint_translation.z()).exp(1e-12);\n        Eigen::Vector3d rb2_last_delta_relative_translation_rev_hyp = rb2_last_delta_relative_displ_rev_hyp.getTranslation();\n        Eigen::Quaterniond rb2_last_delta_relative_rotation_rev_hyp = Eigen::Quaterniond(rb2_last_delta_relative_displ_rev_hyp.qw(),\n                                                                                         rb2_last_delta_relative_displ_rev_hyp.qx(),\n                                                                                         rb2_last_delta_relative_displ_rev_hyp.qy(),\n                                                                                         rb2_last_delta_relative_displ_rev_hyp.qz());\n\n        // Distance proposed by park and okamura in \"Kinematic calibration using the product of exponentials formula\"\n        double translation_error = (rb2_last_delta_relative_translation - rb2_last_delta_relative_translation_rev_hyp).norm();\n        Eigen::Quaterniond rotation_error = rb2_last_delta_relative_rotation.inverse() * rb2_last_delta_relative_rotation_rev_hyp;\n        double rotation_error_angle = Eigen::Displacementd(0., 0., 0., rotation_error.w(), rotation_error.x(), rotation_error.y(), rotation_error.z()).log(1e-12).norm();\n\n        accumulated_error += translation_error + fabs(rotation_error_angle);\n\n        p_one_meas_given_model_params = (1.0/(sigma_translation*sqrt(2.0*M_PI)))*exp((-1.0/2.0)*pow(translation_error/sigma_translation, 2)) *\n                (1.0/(sigma_rotation*sqrt(2.0*M_PI)))*exp((-1.0/2.0)*pow(rotation_error_angle/sigma_rotation, 2));\n\n        p_all_meas_given_model_params += (p_one_meas_given_model_params/(double)amount_samples);\n\n        counter++;\n    }\n\n    if(counter != 0)\n    {\n        this->_measurements_likelihood = p_all_meas_given_model_params;\n    }else{\n        this->_measurements_likelihood = 1e-5;\n    }\n}\n\nvoid RevoluteJointFilter::estimateUnnormalizedModelProbability()\n{\n    Eigen::Vector3d point1_in_rrbf = this->_joint_position + 100*this->_joint_orientation;\n    Eigen::Vector3d point2_in_rrbf = this->_joint_position - 100*this->_joint_orientation;\n\n    // The joint position and orientation are in rrb frame.\n\n    double p_params_given_model = 1;\n\n    // We only measure the distance to the reference rb if it is not the static environment!\n    double distance_to_rrb = 0;\n    if(_rrb_id != 0)\n    {\n        distance_to_rrb = (point2_in_rrbf- point1_in_rrbf).cross(point1_in_rrbf).norm()/((point2_in_rrbf - point1_in_rrbf).norm());\n        p_params_given_model *= (1.0/(_rev_max_joint_distance_for_ee*sqrt(2.0*M_PI)))*exp((-1.0/2.0)*pow(distance_to_rrb/_rev_max_joint_distance_for_ee, 2));\n    }\n\n    Eigen::Vector4d point1_in_rrbf_homo(point1_in_rrbf.x(), point1_in_rrbf.y(), point1_in_rrbf.z(), 1.0);\n    Eigen::Vector4d point1_in_sf_homo = _rrb_current_pose_in_sf.exp(1e-12).toHomogeneousMatrix()*point1_in_rrbf_homo;\n    Eigen::Vector3d point1_in_sf(point1_in_sf_homo[0],point1_in_sf_homo[1],point1_in_sf_homo[2]);\n\n    Eigen::Vector4d point2_in_rrbf_homo(point2_in_rrbf.x(), point2_in_rrbf.y(), point2_in_rrbf.z(), 1.0);\n    Eigen::Vector4d point2_in_sf_homo = _rrb_current_pose_in_sf.exp(1e-12).toHomogeneousMatrix()*point2_in_rrbf_homo;\n    Eigen::Vector3d point2_in_sf(point2_in_sf_homo[0],point2_in_sf_homo[1],point2_in_sf_homo[2]);\n\n    double distance_to_srb = ((point2_in_sf - point1_in_sf).cross(point1_in_sf - _srb_centroid_in_sf)).norm()/((point2_in_sf - point1_in_sf).norm());\n\n    p_params_given_model *= (1.0/(_rev_max_joint_distance_for_ee*sqrt(2.0*M_PI)))*exp((-1.0/2.0)*pow(distance_to_srb/_rev_max_joint_distance_for_ee, 2));\n\n    this->_unnormalized_model_probability = _model_prior_probability*_measurements_likelihood*p_params_given_model;\n}\n\ngeometry_msgs::TwistWithCovariance RevoluteJointFilter::getPredictedSRBDeltaPoseWithCovInSensorFrame()\n{\n    Eigen::Matrix<double, 6, 6> adjoint;\n    computeAdjoint(this->_rrb_current_pose_in_sf, adjoint);\n    Eigen::Twistd predicted_delta_pose_in_sf = adjoint*this->_predicted_delta_pose_in_rrbf;\n\n    geometry_msgs::TwistWithCovariance hypothesis;\n\n    hypothesis.twist.linear.x = predicted_delta_pose_in_sf.vx();\n    hypothesis.twist.linear.y = predicted_delta_pose_in_sf.vy();\n    hypothesis.twist.linear.z = predicted_delta_pose_in_sf.vz();\n    hypothesis.twist.angular.x = predicted_delta_pose_in_sf.rx();\n    hypothesis.twist.angular.y = predicted_delta_pose_in_sf.ry();\n    hypothesis.twist.angular.z = predicted_delta_pose_in_sf.rz();\n\n    // This call gives me the covariance of the predicted measurement: the relative pose between RBs\n    ColumnVector empty;\n    ColumnVector state_updated_state = this->_ekf->PostGet()->ExpectedValueGet();\n    SymmetricMatrix measurement_cov = this->_meas_MODEL->CovarianceGet(empty, state_updated_state);\n    for(int i=0; i<6; i++)\n    {\n        for(int j=0; j<6; j++)\n        {\n             hypothesis.covariance[6 * i + j] = measurement_cov(i+1,j+1);\n        }\n    }\n\n    return hypothesis;\n}\n\ngeometry_msgs::TwistWithCovariance RevoluteJointFilter::getPredictedSRBVelocityWithCovInSensorFrame()\n{\n    Eigen::Matrix<double, 6, 6> adjoint;\n    computeAdjoint(this->_rrb_current_pose_in_sf, adjoint);\n    Eigen::Twistd predicted_delta_pose_in_sf = adjoint*(this->_predicted_delta_pose_in_rrbf/(_loop_period_ns/1e9));\n\n    geometry_msgs::TwistWithCovariance hypothesis;\n\n    hypothesis.twist.linear.x = predicted_delta_pose_in_sf.vx();\n    hypothesis.twist.linear.y = predicted_delta_pose_in_sf.vy();\n    hypothesis.twist.linear.z = predicted_delta_pose_in_sf.vz();\n    hypothesis.twist.angular.x = predicted_delta_pose_in_sf.rx();\n    hypothesis.twist.angular.y = predicted_delta_pose_in_sf.ry();\n    hypothesis.twist.angular.z = predicted_delta_pose_in_sf.rz();\n\n    // This call gives me the covariance of the predicted measurement: the relative pose between RBs\n    ColumnVector empty;\n    ColumnVector state_updated_state = this->_ekf->PostGet()->ExpectedValueGet();\n    SymmetricMatrix measurement_cov = this->_meas_MODEL->CovarianceGet(empty, state_updated_state);\n    for(int i=0; i<6; i++)\n    {\n        for(int j=0; j<6; j++)\n        {\n             hypothesis.covariance[6 * i + j] = measurement_cov(i+1,j+1);\n        }\n    }\n\n    return hypothesis;\n}\n\ngeometry_msgs::TwistWithCovariance RevoluteJointFilter::getPredictedSRBPoseWithCovInSensorFrame()\n{\n    Eigen::Twistd delta_rrb_in_sf = this->_rrb_current_vel_in_sf*(this->_loop_period_ns/1e9);\n    Eigen::Twistd rrb_next_pose_in_sf = (delta_rrb_in_sf.exp(1e-12)*this->_rrb_current_pose_in_sf.exp(1e-12)).log(1e-12);\n\n    Eigen::Displacementd T_sf_rrbf_next = rrb_next_pose_in_sf.exp(1e-12);\n    Eigen::Displacementd T_rrbf_srbf_next = this->_srb_predicted_pose_in_rrbf.exp(1e-12);\n\n    Eigen::Displacementd T_sf_srbf_next = T_rrbf_srbf_next*T_sf_rrbf_next;\n\n    Eigen::Twistd srb_next_pose_in_sf = T_sf_srbf_next.log(1e-12);\n\n    geometry_msgs::TwistWithCovariance hypothesis;\n\n    hypothesis.twist.linear.x = srb_next_pose_in_sf.vx();\n    hypothesis.twist.linear.y = srb_next_pose_in_sf.vy();\n    hypothesis.twist.linear.z = srb_next_pose_in_sf.vz();\n    hypothesis.twist.angular.x = srb_next_pose_in_sf.rx();\n    hypothesis.twist.angular.y = srb_next_pose_in_sf.ry();\n    hypothesis.twist.angular.z = srb_next_pose_in_sf.rz();\n\n    // This call gives me the covariance of the predicted measurement: the relative pose between RBs\n    ColumnVector empty;\n    ColumnVector state_updated_state = this->_ekf->PostGet()->ExpectedValueGet();\n    SymmetricMatrix measurement_cov = this->_meas_MODEL->CovarianceGet(empty, state_updated_state);\n    Eigen::Matrix<double,6,6> measurement_cov_eigen;\n    for(int i=0; i<6; i++)\n    {\n        for(int j=0; j<6; j++)\n        {\n            measurement_cov_eigen(i,j) = measurement_cov(i+1,j+1);\n        }\n    }\n    // I need the covariance of the absolute pose of the second RB, so I add the cov of the relative pose to the\n    // cov of the reference pose. I need to \"move\" the second covariance to align it to the reference frame (see Barfoot)\n    Eigen::Matrix<double,6,6> tranformed_cov;\n    adjointXcovXadjointT(_rrb_current_pose_in_sf, measurement_cov_eigen, tranformed_cov);\n    Eigen::Matrix<double,6,6> new_pose_covariance = this->_rrb_pose_cov_in_sf + tranformed_cov;\n    for (unsigned int i = 0; i < 6; i++)\n    {\n        for (unsigned int j = 0; j < 6; j++)\n        {\n            hypothesis.covariance[6 * i + j] = new_pose_covariance(i, j);\n        }\n    }\n\n\n#ifdef PUBLISH_PREDICTED_POSE_AS_PWC\n    // This is used to visualize the predictions based on the joint hypothesis\n    geometry_msgs::PoseWithCovarianceStamped pose_with_cov_stamped;\n    pose_with_cov_stamped.header.stamp = ros::Time::now();\n    pose_with_cov_stamped.header.frame_id = \"camera_rgb_optical_frame\";\n\n    Eigen::Displacementd displ_from_twist = srb_next_pose_in_sf.exp(1e-12);\n    pose_with_cov_stamped.pose.pose.position.x = displ_from_twist.x();\n    pose_with_cov_stamped.pose.pose.position.y = displ_from_twist.y();\n    pose_with_cov_stamped.pose.pose.position.z = displ_from_twist.z();\n    pose_with_cov_stamped.pose.pose.orientation.x = displ_from_twist.qx();\n    pose_with_cov_stamped.pose.pose.orientation.y = displ_from_twist.qy();\n    pose_with_cov_stamped.pose.pose.orientation.z = displ_from_twist.qz();\n    pose_with_cov_stamped.pose.pose.orientation.w = displ_from_twist.qw();\n\n    for (unsigned int i = 0; i < 6; i++)\n        for (unsigned int j = 0; j < 6; j++)\n            pose_with_cov_stamped.pose.covariance[6 * i + j] = new_pose_covariance(i, j);\n\n    _predicted_next_pose_publisher.publish(pose_with_cov_stamped);\n#endif\n\n    return hypothesis;\n}\n\nstd::vector<visualization_msgs::Marker> RevoluteJointFilter::getJointMarkersInRRBFrame() const\n{\n    // The class variable _joint_orientation and _rev_joint_posi (also _uncertainty_o_phi and _uncertainty_o_theta) are defined in the frame of the\n    // ref RB with the initial relative transformation to the second RB\n    // We want the variables to be in the ref RB frame, without the initial relative transformation to the second RB\n    Eigen::Vector3d rev_joint_ori_in_ref_rb = this->_joint_orientation;\n    Eigen::Vector3d rev_joint_posi_in_ref_rb = this->_joint_position;\n\n\n    std::vector<visualization_msgs::Marker> revolute_markers;\n    // AXIS MARKER 1 -> The axis ///////////////////////////////////////////////////////////////////////////////////////////////////////////\n    visualization_msgs::Marker axis_orientation_marker;\n    axis_orientation_marker.ns = \"kinematic_structure\";\n    axis_orientation_marker.action = visualization_msgs::Marker::ADD;\n    axis_orientation_marker.type = visualization_msgs::Marker::ARROW;\n\n    // Define the joint parameters relative to the REFERENCE RIGID BODY and the marker will be also\n    // defined wrt to the frame of the REFERENCE RIGID BODY!\n    // The frame name will be assigned in the MultiJointTrackerNode because we don't know the rb ids here\n    //axis_orientation_marker.header.frame_id = \"camera_rgb_optical_frame\";\n    axis_orientation_marker.id = 3 * this->_joint_id;\n    axis_orientation_marker.scale.x = JOINT_AXIS_AND_VARIABLE_MARKER_RADIUS;\n    axis_orientation_marker.scale.y = 0.f;\n    axis_orientation_marker.scale.z = 0.f;\n    axis_orientation_marker.color.r = 1.f;\n    axis_orientation_marker.color.g = 0.f;\n    axis_orientation_marker.color.b = 0.f;\n    axis_orientation_marker.color.a = 1.f;\n    Eigen::Vector3d point_on_rot_axis_1 = rev_joint_posi_in_ref_rb - this->_joint_state * rev_joint_ori_in_ref_rb;\n    geometry_msgs::Point pt1;\n    pt1.x = point_on_rot_axis_1.x();\n    pt1.y = point_on_rot_axis_1.y();\n    pt1.z = point_on_rot_axis_1.z();\n    axis_orientation_marker.points.push_back(pt1);\n    Eigen::Vector3d point_on_rot_axis_2 = rev_joint_posi_in_ref_rb + this->_joint_state * rev_joint_ori_in_ref_rb;\n    geometry_msgs::Point pt2;\n    pt2.x = point_on_rot_axis_2.x();\n    pt2.y = point_on_rot_axis_2.y();\n    pt2.z = point_on_rot_axis_2.z();\n    axis_orientation_marker.points.push_back(pt2);\n    revolute_markers.push_back(axis_orientation_marker);\n\n    // AXIS MARKER 2 -> Proportional to the joint state///////////////////////////////////////////////////////////////////////////////////////////////////////////\n    visualization_msgs::Marker axis_orientation_markerb;\n    axis_orientation_markerb.ns = \"kinematic_structure\";\n    axis_orientation_markerb.action = visualization_msgs::Marker::ADD;\n    axis_orientation_markerb.type = visualization_msgs::Marker::ARROW;\n    // Define the joint parameters relative to the REFERENCE RIGID BODY and the marker will be also\n    // defined wrt to the frame of the REFERENCE RIGID BODY!\n    // The frame name will be assigned in the MultiJointTrackerNode because we don't know the rb ids here\n    //axis_orientation_markerb.header.frame_id = \"camera_rgb_optical_frame\";\n    axis_orientation_markerb.id = 3 * this->_joint_id + 1;\n    axis_orientation_markerb.scale.x = JOINT_AXIS_MARKER_RADIUS;\n    axis_orientation_markerb.scale.y = 0.f;\n    axis_orientation_markerb.scale.z = 0.f;\n    axis_orientation_markerb.color.r = 1.f;\n    axis_orientation_markerb.color.g = 0.f;\n    axis_orientation_markerb.color.b = 0.f;\n    axis_orientation_markerb.color.a = 1.f;\n    Eigen::Vector3d point_on_rot_axis_1b = rev_joint_posi_in_ref_rb - 100 * rev_joint_ori_in_ref_rb;\n    geometry_msgs::Point pt1b;\n    pt1b.x = point_on_rot_axis_1b.x();\n    pt1b.y = point_on_rot_axis_1b.y();\n    pt1b.z = point_on_rot_axis_1b.z();\n    axis_orientation_markerb.points.push_back(pt1b);\n    Eigen::Vector3d point_on_rot_axis_2b = rev_joint_posi_in_ref_rb  + 100 * rev_joint_ori_in_ref_rb;\n    geometry_msgs::Point pt2b;\n    pt2b.x = point_on_rot_axis_2b.x();\n    pt2b.y = point_on_rot_axis_2b.y();\n    pt2b.z = point_on_rot_axis_2b.z();\n    axis_orientation_markerb.points.push_back(pt2b);\n\n    revolute_markers.push_back(axis_orientation_markerb);\n\n    // AXIS MARKER 3 -> Text with the joint state ///////////////////////////////////////////////////////////////////////////////////////////////////////////\n    axis_orientation_markerb.points.clear();\n    axis_orientation_markerb.id = 3 * this->_joint_id + 2;\n    axis_orientation_markerb.type = visualization_msgs::Marker::TEXT_VIEW_FACING;\n    axis_orientation_markerb.scale.z = JOINT_VALUE_TEXT_SIZE;\n    std::ostringstream oss_joint_value;\n    oss_joint_value << std::fixed<< std::setprecision(0) << (180/M_PI)*this->_joint_state;\n    axis_orientation_markerb.text = oss_joint_value.str() + std::string(\" deg\");\n    axis_orientation_markerb.pose.position.x = rev_joint_posi_in_ref_rb.x();\n    axis_orientation_markerb.pose.position.y = rev_joint_posi_in_ref_rb.y();\n    axis_orientation_markerb.pose.position.z = rev_joint_posi_in_ref_rb.z();\n    axis_orientation_markerb.pose.orientation.x = 0;\n    axis_orientation_markerb.pose.orientation.y = 0;\n    axis_orientation_markerb.pose.orientation.z = 0;\n    axis_orientation_markerb.pose.orientation.w = 1;\n\n    revolute_markers.push_back(axis_orientation_markerb);\n\n    // UNCERTAINTY MARKERS ///////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    visualization_msgs::Marker axis_position_uncertainty_marker;\n    axis_position_uncertainty_marker.pose.position.x = rev_joint_posi_in_ref_rb.x();\n    axis_position_uncertainty_marker.pose.position.y = rev_joint_posi_in_ref_rb.y();\n    axis_position_uncertainty_marker.pose.position.z = rev_joint_posi_in_ref_rb.z();\n    // Define the joint parameters relative to the REFERENCE RIGID BODY and the marker will be also\n    // defined wrt to the frame of the REFERENCE RIGID BODY!\n    // The frame name will be assigned in the MultiJointTrackerNode because we don't know the rb ids here\n    //axis_position_uncertainty_marker.header.frame_id = \"camera_rgb_optical_frame\";\n    axis_position_uncertainty_marker.ns = \"kinematic_structure_uncertainty\";\n    axis_position_uncertainty_marker.type = visualization_msgs::Marker::SPHERE;\n    axis_position_uncertainty_marker.action = visualization_msgs::Marker::ADD;\n    axis_position_uncertainty_marker.id = 3 * this->_joint_id ;\n    // Reliability = 1 --> position_sphere_uncertainty = 0\n    // Reliability = 0 --> position_sphere_uncertainty = 1m\n    axis_position_uncertainty_marker.scale.x = this->_uncertainty_joint_position(0,0); //Using start and end points, scale.x is the radius of the array body\n    axis_position_uncertainty_marker.scale.y = this->_uncertainty_joint_position(1,1); //Using start and end points, scale.y is the radius of the array head\n    axis_position_uncertainty_marker.scale.z = this->_uncertainty_joint_position(2,2); //Using start and end points, scale.y is the radius of the array head\n    axis_position_uncertainty_marker.color.a = 0.3;\n    axis_position_uncertainty_marker.color.r = 1.0;\n    axis_position_uncertainty_marker.color.g = 0.0;\n    axis_position_uncertainty_marker.color.b = 0.0;\n    revolute_markers.push_back(axis_position_uncertainty_marker);\n\n    visualization_msgs::Marker rev_axis_unc_cone1;\n    rev_axis_unc_cone1.type = visualization_msgs::Marker::MESH_RESOURCE;\n    rev_axis_unc_cone1.action = visualization_msgs::Marker::ADD;\n    rev_axis_unc_cone1.mesh_resource = \"package://joint_tracker/meshes/cone.stl\";\n    rev_axis_unc_cone1.pose.position.x = rev_joint_posi_in_ref_rb.x();\n    rev_axis_unc_cone1.pose.position.y = rev_joint_posi_in_ref_rb.y();\n    rev_axis_unc_cone1.pose.position.z = rev_joint_posi_in_ref_rb.z();\n\n\n    // NOTE:\n    // Estimation of the uncertainty cones -----------------------------------------------\n    // We estimate the orientation of the revolute axis in spherical coordinates (r=1 always)\n    // We estimate phi: angle from the x axis to the projection of the revolute joint axis to the xy plane\n    // We estimate theta: angle from the z axis to the revolute joint axis\n    // [TODO: phi and theta are in the reference rigid body. Do we need to transform it (adding uncertainty) to the reference frame?]\n    // The covariance of phi and theta (a 2x2 matrix) gives us the uncertainty of the orientation of the joint\n    // If we look from the joint axis, we would see an ellipse given by this covariance matrix [http://www.visiondummy.com/2014/04/draw-error-ellipse-representing-covariance-matrix/]\n    // But in RVIZ we can only set the scale of our cone mesh in x and y, not in a different axis\n    // The first thing is then to estimate the direction of the major and minor axis of the ellipse and their size\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> eigensolver(this->_uncertainty_joint_orientation_phitheta);\n\n    // The sizes of the major and minor axes of the ellipse are given by the eigenvalues and the chi square distribution P(x<critical_value) = confidence_value\n    // For 50% of confidence on the cones shown\n    double confidence_value = 0.5;\n    boost::math::chi_squared chi_sq_dist(2);\n    double critical_value = boost::math::quantile(chi_sq_dist, confidence_value);\n    double major_axis_length = 2*eigensolver.eigenvalues()[1]*std::sqrt(critical_value);\n    double minor_axis_length = 2*eigensolver.eigenvalues()[0]*std::sqrt(critical_value);\n\n    // If z is pointing in the direction of the joint, the angle between the x axis and the largest axis of the ellipse is arctg(v1_y/v1_x) where v1 is the eigenvector of\n    // largest eigenvalue (the last column in the matrix returned by eigenvectors() in eigen library):\n    double alpha = atan2(eigensolver.eigenvectors().col(1)[1],eigensolver.eigenvectors().col(1)[0]);\n    // We create a rotation around the z axis to align the ellipse to have the major axis aligned to the x-axis (we UNDO the rotation of the ellipse):\n    Eigen::AngleAxisd init_rot(-alpha, Eigen::Vector3d::UnitZ());\n\n    // Now I need to rotate the mesh so that:\n    // 1) The z axis of the mesh points in the direction of the joint\n    // 2) The x axis of the mesh is contained in the x-y plane of the reference frame\n\n    // To get the z axis of the mesh to point in the direction of the joint\n    Eigen::Quaterniond ori_quat;\n    ori_quat.setFromTwoVectors(Eigen::Vector3d::UnitZ(), rev_joint_ori_in_ref_rb);\n\n    // To get the x axis of the mesh to be contained in the x-y plane of the reference frame\n    // First, find a vector that is orthogonal to the joint orientation and also to the z_axis (this latter implies to be contained in the xy plane)\n    Eigen::Vector3d coplanar_xy_orthogonal_to_joint_ori = rev_joint_ori_in_ref_rb.cross(Eigen::Vector3d::UnitZ());\n    // Normalize it -> Gives me the desired x axis after the rotation\n    coplanar_xy_orthogonal_to_joint_ori.normalize();\n\n    // Then find the corresponding y axis after the rotation as the cross product of the z axis after rotation (orientation of the joint)\n    // and the x axis after rotation\n    Eigen::Vector3d y_pos = rev_joint_ori_in_ref_rb.cross(coplanar_xy_orthogonal_to_joint_ori);\n\n    // Create a matrix with the values of the vectors after rotation\n    Eigen::Matrix3d rotation_pos;\n    rotation_pos << coplanar_xy_orthogonal_to_joint_ori.x(),y_pos.x(),rev_joint_ori_in_ref_rb.x(),\n            coplanar_xy_orthogonal_to_joint_ori.y(),y_pos.y(),rev_joint_ori_in_ref_rb.y(),\n            coplanar_xy_orthogonal_to_joint_ori.z(),y_pos.z(),rev_joint_ori_in_ref_rb.z();\n\n    // Create a quaternion with the matrix\n    Eigen::Quaterniond ori_quat_final(rotation_pos);\n\n    Eigen::Quaterniond ori_quat_final_ellipse(ori_quat_final.toRotationMatrix()*init_rot.toRotationMatrix());\n\n    rev_axis_unc_cone1.pose.orientation.x = ori_quat_final_ellipse.x();\n    rev_axis_unc_cone1.pose.orientation.y = ori_quat_final_ellipse.y();\n    rev_axis_unc_cone1.pose.orientation.z = ori_quat_final_ellipse.z();\n    rev_axis_unc_cone1.pose.orientation.w = ori_quat_final_ellipse.w();\n    // Define the joint parameters relative to the REFERENCE RIGID BODY and the marker will be also\n    // defined wrt to the frame of the REFERENCE RIGID BODY!\n    // The frame name will be assigned in the MultiJointTrackerNode because we don't know the rb ids here\n    //rev_axis_unc_cone1.header.frame_id = \"camera_rgb_optical_frame\";\n    rev_axis_unc_cone1.ns = \"kinematic_structure_uncertainty\";\n    rev_axis_unc_cone1.id = 3 * this->_joint_id + 1;\n    rev_axis_unc_cone1.color.a = 0.4;\n    rev_axis_unc_cone1.color.r = 1.0;\n    rev_axis_unc_cone1.color.g = 0.0;\n    rev_axis_unc_cone1.color.b = 0.0;\n\n    // If the uncertainty is pi/6 (30 degrees) the scale in this direction should be 1\n    // If the uncertainty is pi/12 (15 degrees) the scale in this direction should be 0.5\n    // If the uncertainty is close to 0 the scale in this direction should be 0\n    // If the uncertainty is close to pi the scale in this direction should be inf\n\n    rev_axis_unc_cone1.scale.x = major_axis_length / (M_PI / 6.0);\n    rev_axis_unc_cone1.scale.y = minor_axis_length / (M_PI / 6.0);\n    rev_axis_unc_cone1.scale.z = 1.;\n    revolute_markers.push_back(rev_axis_unc_cone1);\n\n    // We repeat the process for the cone in the other direction\n    // To get the z axis of the mesh to point in the direction of the joint (negative)\n    Eigen::Vector3d rev_joint_ori_in_ref_rb_neg = -rev_joint_ori_in_ref_rb;\n    Eigen::Quaterniond ori_quat_neg;\n    ori_quat_neg.setFromTwoVectors(Eigen::Vector3d::UnitZ(), rev_joint_ori_in_ref_rb_neg);\n\n    // To get the x axis of the mesh to be contained in the x-y plane of the reference frame\n    // First, find a vector that is orthogonal to the joint orientation and also to the z_axis (this latter implies to be contained in the xy plane)\n    Eigen::Vector3d coplanar_xy_orthogonal_to_joint_ori_neg = rev_joint_ori_in_ref_rb_neg.cross(Eigen::Vector3d::UnitZ());\n    // Normalize it -> Gives me the desired x axis after the rotation\n    coplanar_xy_orthogonal_to_joint_ori_neg.normalize();\n\n    // Then find the corresponding y axis after the rotation as the cross product of the z axis after rotation (orientation of the joint)\n    // and the x axis after rotation\n    Eigen::Vector3d y_neg = rev_joint_ori_in_ref_rb_neg.cross(coplanar_xy_orthogonal_to_joint_ori_neg);\n\n    // Create a matrix with the values of the vectors after rotation\n    Eigen::Matrix3d rotation_neg;\n    rotation_neg << coplanar_xy_orthogonal_to_joint_ori_neg.x(),y_neg.x(),rev_joint_ori_in_ref_rb_neg.x(),\n            coplanar_xy_orthogonal_to_joint_ori_neg.y(),y_neg.y(),rev_joint_ori_in_ref_rb_neg.y(),\n            coplanar_xy_orthogonal_to_joint_ori_neg.z(),y_neg.z(),rev_joint_ori_in_ref_rb_neg.z();\n\n    // Create a quaternion with the matrix\n    Eigen::Quaterniond ori_quat_neg_final(rotation_neg);\n\n    // We undo the rotation of the ellipse (but negative!):\n    Eigen::AngleAxisd init_rot_neg(alpha, Eigen::Vector3d::UnitZ());\n    Eigen::Quaterniond ori_quat_neg_final_ellipse(ori_quat_neg_final.toRotationMatrix()*init_rot_neg.toRotationMatrix());\n\n    rev_axis_unc_cone1.pose.orientation.x = ori_quat_neg_final_ellipse.x();\n    rev_axis_unc_cone1.pose.orientation.y = ori_quat_neg_final_ellipse.y();\n    rev_axis_unc_cone1.pose.orientation.z = ori_quat_neg_final_ellipse.z();\n    rev_axis_unc_cone1.pose.orientation.w = ori_quat_neg_final_ellipse.w();\n    rev_axis_unc_cone1.scale.x = major_axis_length / (M_PI / 6.0);\n    rev_axis_unc_cone1.scale.y = minor_axis_length / (M_PI / 6.0);\n    rev_axis_unc_cone1.scale.z = 1.;\n    rev_axis_unc_cone1.id = 3 * this->_joint_id + 2;\n    revolute_markers.push_back(rev_axis_unc_cone1);\n\n    return revolute_markers;\n}\n\nJointFilterType RevoluteJointFilter::getJointFilterType() const\n{\n    return REVOLUTE_JOINT;\n}\n\nstd::string RevoluteJointFilter::getJointFilterTypeStr() const\n{\n    return std::string(\"RevoluteJointFilter\");\n}\n", "meta": {"hexsha": "f33fca63a4f1a3ff1b0e9d96122cfe6b1cff4d72", "size": 44021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "joint_tracker/src/RevoluteJointFilter.cpp", "max_stars_repo_name": "tu-rbo/omip", "max_stars_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2016-11-10T16:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T20:11:39.000Z", "max_issues_repo_path": "joint_tracker/src/RevoluteJointFilter.cpp", "max_issues_repo_name": "tu-rbo/omip", "max_issues_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-28T13:22:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-22T22:01:58.000Z", "max_forks_repo_path": "joint_tracker/src/RevoluteJointFilter.cpp", "max_forks_repo_name": "tu-rbo/omip", "max_forks_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-11-25T18:24:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T03:20:33.000Z", "avg_line_length": 49.7412429379, "max_line_length": 182, "alphanum_fraction": 0.7132732105, "num_tokens": 11379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5180334601665908}}
{"text": "#include <boost/math/distributions/gamma.hpp>\n", "meta": {"hexsha": "55762deaca50367bf93f60c10f6b745f4f8059be", "size": 46, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_gamma.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_gamma.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_gamma.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.0, "max_line_length": 45, "alphanum_fraction": 0.8043478261, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5180334557748677}}
{"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_fill_profile\n\n#include <boost/format.hpp>\n#include <boost/histogram.hpp>\n#include <cassert>\n#include <iostream>\n#include <sstream>\n#include <utility>\n\nint main() {\n  using namespace boost::histogram;\n\n  // make a profile, it computes the mean of the samples in each histogram cell\n  auto h = make_profile(axis::regular<>(3, 0.0, 1.0));\n\n  // mean is computed from the values marked with the sample() helper function\n  h(0.10, sample(2.5)); // 2.5 goes to bin 0\n  h(0.25, sample(3.5)); // 3.5 goes to bin 0\n  h(0.45, sample(1.2)); // 1.2 goes to bin 1\n  h(sample(3.4), 0.51); // 3.4 goes to bin 1, sample be at the front\n\n  // fills from tuples are also supported, 1.3 and 1.9 go to bin 2\n  auto xs1 = std::make_tuple(0.81, sample(1.3));\n  auto xs2 = std::make_tuple(0.86, sample(1.9));\n  h(xs1);\n  h(xs2);\n\n  // builtin accumulators have methods to access their state\n  std::ostringstream os;\n  for (auto x : indexed(h)) {\n    // use `.` to access methods of accessor, like `index()`\n    // use `->` to access methods of accumulator\n    const auto i = x.index();\n    const auto n = x->count();     // how many samples are in this bin\n    const auto vl = x->value();    // mean value\n    const auto vr = x->variance(); // estimated variance of the mean value\n    os << boost::format(\"bin %i count %i value %.1f variance %.1f\\n\") % i % n % vl % vr;\n  }\n\n  std::cout << os.str() << std::flush;\n\n  assert(os.str() == \"bin 0 count 2 value 3.0 variance 0.5\\n\"\n                     \"bin 1 count 2 value 2.3 variance 2.4\\n\"\n                     \"bin 2 count 2 value 1.6 variance 0.2\\n\");\n}\n\n//]\n", "meta": {"hexsha": "cda9d11aff6aac083a5b8b0cba787e07f639a9d5", "size": 1790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/guide_fill_profile.cpp", "max_stars_repo_name": "henryiii/histogram", "max_stars_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2020-12-21T05:14:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T11:27:32.000Z", "max_issues_repo_path": "examples/guide_fill_profile.cpp", "max_issues_repo_name": "henryiii/histogram", "max_issues_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T11:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T13:40:06.000Z", "max_forks_repo_path": "examples/guide_fill_profile.cpp", "max_forks_repo_name": "henryiii/histogram", "max_forks_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2020-12-22T09:40:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T18:16:00.000Z", "avg_line_length": 33.1481481481, "max_line_length": 88, "alphanum_fraction": 0.630726257, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.517875779005344}}
{"text": "//\n// Created by tyoun on 11/7/2021.\n//\n#include <catch2/catch.hpp>\n#include <set>\n#include <boost/graph/adjacency_list.hpp>\n\n\n/* Boost graph library (BGL) is a set of collections and algorithims for storing\n * and manipulatign graphs. BGL offers three containers that represent graphs\n *\n * boost::adjacency_list\n * boost::adjacency_matrix\n * boost::edge\n */\n\n\nTEST_CASE(\"boost::adjacency_list stores graph data\")\n{\n    boost::adjacency_list<> graph{};\n    // add vertex returns a vertext and takes and adjacency list\n\n    auto vertex_1 = boost::add_vertex(graph);\n    auto vertex_2 = boost::add_vertex(graph);\n    auto vertex_3 = boost::add_vertex(graph);\n    auto vertex_4 = boost::add_vertex(graph);\n\n    auto edge_12 = boost::add_edge(vertex_1, vertex_2, graph);\n    auto edge_13 = boost::add_edge(vertex_1, vertex_3, graph);\n    auto edge_21 = boost::add_edge(vertex_2, vertex_1, graph);\n    auto edge_24 = boost::add_edge(vertex_2, vertex_4, graph);\n    auto edge_43 = boost::add_edge(vertex_4, vertex_3, graph);\n\n    REQUIRE(boost::num_vertices(graph) == 4);\n    REQUIRE(boost::num_edges(graph) == 5);\n\n    auto [begin, end] = boost::adjacent_vertices(vertex_1, graph);\n    std::set<decltype(vertex_1)> neighboors_1 { begin, end};\n    REQUIRE(neighboors_1.count(vertex_2) == 1);\n    REQUIRE(neighboors_1.count(vertex_3) == 1);\n    REQUIRE(neighboors_1.count(vertex_4) == 0);\n\n}\n", "meta": {"hexsha": "fbe40d12379f91433b747e1937371d5aafd4fc78", "size": 1386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/boost_graph_tests.cpp", "max_stars_repo_name": "tyoungjr/Catch2Practice", "max_stars_repo_head_hexsha": "6c602b0b57edaf2299043b4ef3c11d9507ce167b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/boost_graph_tests.cpp", "max_issues_repo_name": "tyoungjr/Catch2Practice", "max_issues_repo_head_hexsha": "6c602b0b57edaf2299043b4ef3c11d9507ce167b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/boost_graph_tests.cpp", "max_forks_repo_name": "tyoungjr/Catch2Practice", "max_forks_repo_head_hexsha": "6c602b0b57edaf2299043b4ef3c11d9507ce167b", "max_forks_repo_licenses": ["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": 80, "alphanum_fraction": 0.7049062049, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.517875766300873}}
{"text": "/* -*- c++ -*- */\n/*\n * Copyright 2010,2012 Free Software Foundation, Inc.\n *\n * GNU Radio 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, or (at your option)\n * any later version.\n *\n * GNU Radio 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 GNU Radio; see the file COPYING.  If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street,\n * Boston, MA 02110-1301, USA.\n */\n\n// Calculate the taps for the CPM phase responses\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <cmath>\n#include <cfloat>\n#include <gnuradio/analog/cpm.h>\n\n//gives us erf on compilers without it\n#include <boost/math/special_functions/erf.hpp>\nnamespace bm = boost::math;\n\nnamespace gr {\n  namespace analog {\n\n#ifndef M_TWOPI\n#  define M_TWOPI (2*M_PI)\n#endif\n\n    //! Normalised sinc function, sinc(x)=sin(pi*x)/pi*x\n    inline double\n    sinc(double x)\n    {\n      if(x == 0) {\n\treturn 1.0;\n      }\n      return sin(M_PI * x) / (M_PI * x);\n    }\n\n\n    //! Taps for L-RC CPM (Raised cosine of length L symbols)\n    std::vector<float>\n    generate_cpm_lrc_taps(unsigned samples_per_sym, unsigned L)\n    {\n      std::vector<float> taps(samples_per_sym * L, 1.0/L/samples_per_sym);\n      for(unsigned i = 0; i < samples_per_sym * L; i++) {\n\ttaps[i] *= 1 - cos(M_TWOPI * i / L / samples_per_sym);\n      }\n\n      return taps;\n    }\n\n\n    /*! Taps for L-SRC CPM (Spectral raised cosine of length L symbols).\n     *\n     * L-SRC has a time-continuous phase response function of\n     *\n     * g(t) = 1/LT * sinc(2t/LT) * cos(beta * 2pi t / LT) / (1 - (4beta / LT * t)^2)\n     *\n     * which is the Fourier transform of a cos-rolloff function with rolloff\n     * beta, and looks like a sinc-function, multiplied with a rolloff term.\n     * We return the main lobe of the sinc, i.e., everything between the\n     * zero crossings.\n     * The time-discrete IR is thus\n     *\n     * g(k) = 1/Ls * sinc(2k/Ls) * cos(beta * pi k / Ls) / (1 - (4beta / Ls * k)^2)\n     * where k = 0...Ls-1\n     * and s = samples per symbol.\n     */\n    std::vector<float>\n    generate_cpm_lsrc_taps(unsigned samples_per_sym, unsigned L, double beta)\n    {\n      double Ls = (double) L * samples_per_sym;\n      std::vector<double> taps_d(L * samples_per_sym, 0.0);\n      std::vector<float> taps(L * samples_per_sym, 0.0);\n\n      double sum = 0;\n      for(unsigned i = 0; i < samples_per_sym * L; i++) {\n\tdouble k =  i - Ls/2; // Causal to acausal\n\n\ttaps_d[i] = 1.0 / Ls * sinc(2.0 * k / Ls);\n\n\t// For k = +/-Ls/4*beta, the rolloff term's cos-function becomes zero\n\t// and the whole thing converges to PI/4 (to prove this, use de\n\t// l'hopital's rule).\n\tif(fabs(fabs(k) - Ls/4/beta) < 2*DBL_EPSILON) {\n\t  taps_d[i] *= M_PI_4;\n\t}\n\telse {\n\t  double tmp = 4.0 * beta * k / Ls;\n\t  taps_d[i] *= cos(beta * M_TWOPI * k / Ls) / (1 - tmp * tmp);\n\t}\n\tsum += taps_d[i];\n      }\n\n      for(unsigned i = 0; i < samples_per_sym * L; i++) {\n\ttaps[i] = (float) taps_d[i] / sum;\n      }\n\n      return taps;\n    }\n\n    //! Taps for L-REC CPM (Rectangular pulse shape of length L symbols)\n    std::vector<float>\n    generate_cpm_lrec_taps(unsigned samples_per_sym, unsigned L)\n    {\n      return std::vector<float>(samples_per_sym * L, 1.0/L/samples_per_sym);\n    }\n\n    //! Helper function for TFM\n    double tfm_g0(double k, double sps)\n    {\n      if(fabs(k) < 2 * DBL_EPSILON) {\n\treturn 1.145393004159143; // 1 + pi^2/48 / sqrt(2)\n      }\n\n      const double pi2_24 = 0.411233516712057; // pi^2/24\n      double f = M_PI * k / sps;\n      return sinc(k/sps) - pi2_24 * (2 * sin(f) - 2*f*cos(f) - f*f*sin(f)) / (f*f*f);\n    }\n\n    //! Taps for TFM CPM (Tamed frequency modulation)\n    //\n    // See [2, Chapter 2.7.2].\n    //\n    // [2]: Anderson, Aulin and Sundberg; Digital Phase Modulation\n    std::vector<float>\n    generate_cpm_tfm_taps(unsigned sps, unsigned L)\n    {\n      unsigned causal_shift = sps * L / 2;\n      std::vector<double> taps_d(sps * L, 0.0);\n      std::vector<float> taps(sps * L, 0.0);\n\n      double sum = 0;\n      for(unsigned i = 0; i < sps * L; i++) {\n\tdouble k = (double)(((int)i) - ((int)causal_shift)); // Causal to acausal\n\n\ttaps_d[i] = tfm_g0(k - sps, sps) +\n\t  2 * tfm_g0(k,       sps) +\n\t  tfm_g0(k + sps, sps);\n\tsum += taps_d[i];\n      }\n\n      for(unsigned i = 0; i < sps * L; i++) {\n\ttaps[i] = (float) taps_d[i] / sum;\n      }\n\n      return taps;\n    }\n\n    //! Taps for Gaussian CPM. Phase response is truncated after \\p L symbols.\n    //  \\p bt sets the 3dB-time-bandwidth product.\n    //\n    // Note: for h = 0.5, this is the phase response for GMSK.\n    //\n    // This C99-compatible formula for the taps is taken straight\n    // from [1, Chapter 9.2.3].\n    // A version in Q-notation can be found in [2, Chapter 2.7.2].\n    //\n    // [1]: Karl-Dirk Kammeyer; Nachrichten\u00fcbertragung, 4th Edition.\n    // [2]: Anderson, Aulin and Sundberg; Digital Phase Modulation\n    //\n    std::vector<float>\n    generate_cpm_gaussian_taps(unsigned samples_per_sym, unsigned L, double bt)\n    {\n      double Ls = (double) L * samples_per_sym;\n      std::vector<double> taps_d(L * samples_per_sym, 0.0);\n      std::vector<float> taps(L * samples_per_sym, 0.0);\n\n      // alpha = sqrt(2/ln(2)) * pi * BT\n      double alpha = 5.336446256636997 * bt;\n      for(unsigned i = 0; i < samples_per_sym * L; i++) {\n\tdouble k =  i - Ls/2; // Causal to acausal\n\ttaps_d[i] = (bm::erf(alpha * (k / samples_per_sym + 0.5)) -\n\t\t     bm::erf(alpha * (k / samples_per_sym - 0.5)))\n\t  * 0.5 / samples_per_sym;\n\ttaps[i] = (float) taps_d[i];\n      }\n\n      return taps;\n    }\n\n    std::vector<float>\n    cpm::phase_response(cpm_type type, unsigned samples_per_sym, unsigned L, double beta)\n    {\n      switch(type) {\n      case LRC:\n\treturn generate_cpm_lrc_taps(samples_per_sym, L);\n\n      case LSRC:\n\treturn generate_cpm_lsrc_taps(samples_per_sym, L, beta);\n\n      case LREC:\n\treturn generate_cpm_lrec_taps(samples_per_sym, L);\n\n      case TFM:\n\treturn generate_cpm_tfm_taps(samples_per_sym, L);\n\n      case GAUSSIAN:\n\treturn generate_cpm_gaussian_taps(samples_per_sym, L, beta);\n\n      default:\n\treturn generate_cpm_lrec_taps(samples_per_sym, 1);\n      }\n    }\n\n  } // namespace analog\n} // namespace gr\n\n", "meta": {"hexsha": "b61ee28816437a4860a4a3901f733320fc87ae57", "size": 6565, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-analog/lib/cpm.cc", "max_stars_repo_name": "v1259397/cosmic-gnuradio", "max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z", "max_issues_repo_path": "gnuradio-3.7.13.4/gr-analog/lib/cpm.cc", "max_issues_repo_name": "v1259397/cosmic-gnuradio", "max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gnuradio-3.7.13.4/gr-analog/lib/cpm.cc", "max_forks_repo_name": "v1259397/cosmic-gnuradio", "max_forks_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "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.5720720721, "max_line_length": 89, "alphanum_fraction": 0.6176694593, "num_tokens": 2038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5178757571186299}}
{"text": "#include <armadillo>\n#include <complex>\n\n#include \"Quaca.h\"\n#include \"catch.hpp\"\n\nTEST_CASE(\"Integrated PolarizabilityNoBath fulfills the omega_cut much smaller \"\n          \"than omega_a asymptote\",\n          \"[PolarizabilityNoBath]\") {\n\n  // define greens tensor\n  auto v = GENERATE(1e-4, 1e-8);\n  auto beta = GENERATE(1e-3, 1., 1e2);\n  double relerr_k = 1E-9;\n  auto greens = std::make_shared<GreensTensorVacuum>(v, beta, relerr_k);\n\n  // define polarizability\n  auto omega_a = GENERATE(0.21, 1.7);\n  auto alpha_zero = GENERATE(1e-8, 1e-9);\n\n  Polarizability pol(omega_a, alpha_zero, greens);\n\n  double omega_min = 0.0;\n  double omega_max = 1e-3 * omega_a; // omega_max much smaller than omega_a\n  double relerr = 1e-13;\n  double abserr = 0.;\n\n  cx_mat::fixed<3, 3> result(fill::zeros);\n  cx_mat::fixed<3, 3> asymp(fill::zeros);\n  asymp(0, 0) = alpha_zero * alpha_zero * pow(omega_max, 4) / 2.0 * 1.0 /\n                (3 * (1.0 - v * v) * (1.0 - v * v));\n  asymp(1, 1) = alpha_zero * alpha_zero * pow(omega_max, 4) / 2.0 *\n                (1.0 + v * v) / (3 * pow((1.0 - v * v), 3));\n  asymp(2, 2) = asymp(1, 1);\n\n  // loop over indices\n  for (size_t i = 0; i < 3; i++) {\n    for (size_t j = 0; j < 3; j++) {\n      result(i, j) = pol.integrate_omega({i, j}, IM, omega_min,\n                                         omega_max, relerr, abserr);\n    }\n  }\n\n  // Ensure non-trivial result\n  REQUIRE(!result.is_zero());\n  REQUIRE(!asymp.is_zero());\n\n  REQUIRE(approx_equal(result, asymp, \"reldiff\", 1e-4));\n  // Ensure that the total error is above the error due to the series expansio\n  REQUIRE(approx_equal(result, asymp, \"absdiff\", pow(omega_max, 2)));\n}\n\nTEST_CASE(\"Integrated PolarizabilityNoBath fulfills the omega_cut much larger \"\n          \"than omega_a asymptote\",\n          \"[PolarizabilityNoBath]\") {\n  // define greens tensor\n  auto v = GENERATE(1e-4, 1e-8);\n  double beta = 1e5;\n  double relerr_k = 1E-9;\n  auto greens = std::make_shared<GreensTensorVacuum>(v, beta, relerr_k);\n\n  // define polarizability\n  auto omega_a = GENERATE(0.21, 1.5);\n  double alpha_zero = 1e-10;\n  Polarizability pol(omega_a, alpha_zero, greens);\n\n  double omega_min = 0.0;\n  double omega_max = omega_a * 1e5;\n  double relerr = 1e-13;\n  double abserr = 0.;\n\n  double asymp = alpha_zero * omega_a * M_PI / 2.0;\n  cx_mat::fixed<3, 3> result(fill::zeros);\n  // create unitary matrix\n  cx_mat::fixed<3, 3> asymp_mat(fill::eye);\n  asymp_mat *= asymp;\n\n  // loop over indices\n  for (size_t i = 0; i < 3; i++) {\n    for (size_t j = 0; j < 3; j++) {\n      result(i, j) = pol.integrate_omega({i, j}, IM, omega_min,\n                                         omega_a - 1e-3, relerr, abserr);\n      result(i, j) +=\n          pol.integrate_omega({i, j}, IM, omega_a - 1e-3,\n                              omega_a + 1e-3, relerr, abserr);\n      result(i, j) +=\n          pol.integrate_omega({i, j}, IM, omega_a + 1e-3,\n                              omega_max, relerr, abserr);\n    }\n  }\n\n  // Ensure non-trivial results\n  REQUIRE(!result.is_zero());\n  REQUIRE(!asymp_mat.is_zero());\n\n  REQUIRE(approx_equal(result, asymp_mat, \"reldiff\", 1e-4));\n  // Ensure that the error is above the error due to the series expansin\n  REQUIRE(approx_equal(result, asymp_mat, \"absdiff\", sqrt(alpha_zero)));\n}\n", "meta": {"hexsha": "82418c8f19473566bd5fe8efe9d67cf2b580dcd1", "size": 3265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/IntegratedTests/Polarizability/test_PolarizabilityNoBath_integrated.cpp", "max_stars_repo_name": "QuaCaTeam/quaca", "max_stars_repo_head_hexsha": "ab2d213f3e0e357bd72930ae1e4e703184130270", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T09:01:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T07:57:54.000Z", "max_issues_repo_path": "test/IntegratedTests/Polarizability/test_PolarizabilityNoBath_integrated.cpp", "max_issues_repo_name": "myoelmy/quaca", "max_issues_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T08:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-28T07:33:35.000Z", "max_forks_repo_path": "test/IntegratedTests/Polarizability/test_PolarizabilityNoBath_integrated.cpp", "max_forks_repo_name": "myoelmy/quaca", "max_forks_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_forks_repo_licenses": ["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.65, "max_line_length": 80, "alphanum_fraction": 0.6070444104, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5178600814616336}}
{"text": "// SPDX-FileCopyrightText: 2015 - 2021 Marcin \u0141o\u015b <marcin.los.91@gmail.com>\n// SPDX-License-Identifier: MIT\n\n#ifndef ADS_SIMULATION_SIMULATION_3D_HPP\n#define ADS_SIMULATION_SIMULATION_3D_HPP\n\n#include <array>\n#include <cstddef>\n\n#include <boost/range/counting_range.hpp>\n\n#include \"ads/lin/tensor.hpp\"\n#include \"ads/projection.hpp\"\n#include \"ads/simulation/dimension.hpp\"\n#include \"ads/simulation/simulation_base.hpp\"\n#include \"ads/solver.hpp\"\n#include \"ads/util/function_value.hpp\"\n#include \"ads/util/iter/product.hpp\"\n#include \"basic_simulation_3d.hpp\"\n\nnamespace ads {\n\nclass simulation_3d : public basic_simulation_3d, public simulation_base {\npublic:\n    using basic_simulation_3d::dof_global_to_local;\n    using basic_simulation_3d::dofs;\n    using basic_simulation_3d::dofs_on_element;\n    using basic_simulation_3d::elements;\n    using basic_simulation_3d::elements_supporting_dof;\n    using basic_simulation_3d::eval;\n    using basic_simulation_3d::eval_basis;\n    using basic_simulation_3d::jacobian;\n    using basic_simulation_3d::point;\n    using basic_simulation_3d::quad_points;\n    using basic_simulation_3d::update_global_rhs;\n    using basic_simulation_3d::weight;\n\n    dimension x, y, z;\n    vector_type buffer;\n\n    void solve(vector_type& rhs) { ads_solve(rhs, buffer, x.data(), y.data(), z.data()); }\n\n    template <typename Function>\n    void projection(vector_type& v, Function f) {\n        compute_projection(v, x.basis, y.basis, z.basis, f);\n    }\n\n    double grad_dot(value_type a, value_type b) const {\n        return a.dx * b.dx + a.dy * b.dy + a.dz * b.dz;\n    }\n\n    std::array<int, 3> shape() const { return {x.dofs(), y.dofs(), z.dofs()}; }\n\n    std::array<int, 3> local_shape() const {\n        return {x.basis.dofs_per_element(), y.basis.dofs_per_element(), z.basis.dofs_per_element()};\n    }\n\n    void prepare_matrices() {\n        x.factorize_matrix();\n        y.factorize_matrix();\n        z.factorize_matrix();\n    }\n\n    index_range elements() const {\n        return util::product_range<index_type>(x.element_indices(), y.element_indices(),\n                                               z.element_indices());\n    }\n\n    index_range quad_points() const {\n        auto rx = boost::counting_range(0, x.basis.quad_order);\n        auto ry = boost::counting_range(0, y.basis.quad_order);\n        auto rz = boost::counting_range(0, z.basis.quad_order);\n        return util::product_range<index_type>(rx, ry, rz);\n    }\n\n    index_range dofs_on_element(index_type e) const {\n        auto rx = x.basis.dof_range(e[0]);\n        auto ry = y.basis.dof_range(e[1]);\n        auto rz = z.basis.dof_range(e[2]);\n        return util::product_range<index_type>(rx, ry, rz);\n    }\n\n    double jacobian(index_type e) const {\n        return x.basis.J[e[0]] * y.basis.J[e[1]] * z.basis.J[e[2]];\n    }\n\n    double weight(index_type q) const {\n        return x.basis.w[q[0]] * y.basis.w[q[1]] * z.basis.w[q[2]];\n    }\n\n    point_type point(index_type e, index_type q) const {\n        double px = x.basis.x[e[0]][q[0]];\n        double py = y.basis.x[e[1]][q[1]];\n        double pz = z.basis.x[e[2]][q[2]];\n        return {px, py, pz};\n    }\n\n    value_type eval_basis(index_type e, index_type q, index_type a) const {\n        auto loc = dof_global_to_local(e, a);\n\n        const auto& bx = x.basis;\n        const auto& by = y.basis;\n        const auto& bz = z.basis;\n\n        double B1 = bx.b[e[0]][q[0]][0][loc[0]];\n        double B2 = by.b[e[1]][q[1]][0][loc[1]];\n        double B3 = bz.b[e[2]][q[2]][0][loc[2]];\n        double dB1 = bx.b[e[0]][q[0]][1][loc[0]];\n        double dB2 = by.b[e[1]][q[1]][1][loc[1]];\n        double dB3 = bz.b[e[2]][q[2]][1][loc[2]];\n\n        double v = B1 * B2 * B3;\n        double dxv = dB1 * B2 * B3;\n        double dyv = B1 * dB2 * B3;\n        double dzv = B1 * B2 * dB3;\n\n        return {v, dxv, dyv, dzv};\n    }\n\n    value_type eval_fun(const vector_type& v, index_type e, index_type q) const {\n        value_type u{};\n        for (auto b : dofs_on_element(e)) {\n            double c = v(b[0], b[1], b[2]);\n            value_type B = eval_basis(e, q, b);\n            u += c * B;\n        }\n        return u;\n    }\n\n    index_type dof_global_to_local(index_type e, index_type a) const {\n        const auto& bx = x.basis;\n        const auto& by = y.basis;\n        const auto& bz = z.basis;\n\n        return {{a[0] - bx.first_dof(e[0]), a[1] - by.first_dof(e[1]), a[2] - bz.first_dof(e[2])}};\n    }\n\n    vector_type element_rhs() const { return vector_type{local_shape()}; }\n\n    void update_global_rhs(vector_type& global, const vector_type& local, index_type e) const {\n        for (auto a : dofs_on_element(e)) {\n            auto loc = dof_global_to_local(e, a);\n            global(a[0], a[1], a[2]) += local(loc[0], loc[1], loc[2]);\n        }\n    }\n\n    explicit simulation_3d(const config_3d& config);\n\n    simulation_3d(const dimension& x, const dimension& y, const dimension& z,\n                  const timesteps_config& steps);\n};\n\n}  // namespace ads\n\n#endif  // ADS_SIMULATION_SIMULATION_3D_HPP\n", "meta": {"hexsha": "ff35e1bf8377e9c6bddb425e78e311407edf41e6", "size": 5050, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ads/simulation/simulation_3d.hpp", "max_stars_repo_name": "Pan-Maciek/iga-ads", "max_stars_repo_head_hexsha": "4744829c98cba4e9505c5c996070119e73ba18fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-01-19T00:19:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T00:53:00.000Z", "max_issues_repo_path": "include/ads/simulation/simulation_3d.hpp", "max_issues_repo_name": "Pan-Maciek/iga-ads", "max_issues_repo_head_hexsha": "4744829c98cba4e9505c5c996070119e73ba18fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T22:44:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T15:18:00.000Z", "max_forks_repo_path": "include/ads/simulation/simulation_3d.hpp", "max_forks_repo_name": "Pan-Maciek/iga-ads", "max_forks_repo_head_hexsha": "4744829c98cba4e9505c5c996070119e73ba18fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-04-13T19:42:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T18:46:24.000Z", "avg_line_length": 32.3717948718, "max_line_length": 100, "alphanum_fraction": 0.6152475248, "num_tokens": 1450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744806385542, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5178600786730158}}
{"text": "#ifndef qlex_doubleexponentialcalibration_hpp\n#define qlex_doubleexponentialcalibration_hpp\n\n#include <ql/math/optimization/endcriteria.hpp>\n#include <ql/math/optimization/projectedcostfunction.hpp>\n#include <ql/math/array.hpp>\n#include <ql/quote.hpp>\n#include <boost/shared_ptr.hpp>\n#include <vector>\n\nusing namespace QuantLib;\n\nnamespace QLExtension {\n    \n    class QuantLib::Quote;\n    class QuantLib::OptimizationMethod;\n    class QuantLib::ParametersTransformation;\n\n\t// Time homogeneous vol term structure\n\t// pp. 104 Valuation and Risk Management in Energy Market\n\t// sigma^2(T-t) = simga^2[exp(-2b_1(T-1)+lambda*exp(-2b_2(T-t)]\n    class DoubleExponentialCalibration {\n    \n    private:\n\n\t\tclass DoubleExponentialError : public CostFunction {\n          public:\n            DoubleExponentialError(DoubleExponentialCalibration* dblexp) : dblexp_(dblexp) {}\n\n            Real value(const Array& x) const {\n\t\t\t\tdblexp_->sigma_ = x[0];\n\t\t\t\tdblexp_->b1_ = x[1];\n\t\t\t\tdblexp_->b2_ = x[2];\n\t\t\t\tdblexp_->lambda_ = x[3];\n\t\t\t\treturn dblexp_->error();\n            }\n            Disposable<Array> values(const Array& x) const {\n\t\t\t\tdblexp_->sigma_ = x[0];\n\t\t\t\tdblexp_->b1_ = x[1];\n\t\t\t\tdblexp_->b2_ = x[2];\n\t\t\t\tdblexp_->lambda_ = x[3];\n\t\t\t\treturn dblexp_->errors();\n            }\n          private:\n            DoubleExponentialCalibration* dblexp_;\n        };\n\n      public:\n        DoubleExponentialCalibration() {};\n\t\tDoubleExponentialCalibration(\n             const std::vector<Real>& t,\n             const std::vector<Real>& blackVols,\n             Real sigmaGuess = 0.10,\n             Real b1Guess =  0.25,\n             Real b2Guess =  0.60,\n             Real lambdaGuess =  0.5,\n             bool sigmaIsFixed = false,\n             bool b1IsFixed = false,\n             bool b2IsFixed = false,\n             bool lambdaIsFixed = false,\n             bool vegaWeighted = false,\n             const boost::shared_ptr<EndCriteria>& endCriteria\n                      = boost::shared_ptr<EndCriteria>(),\n             const boost::shared_ptr<OptimizationMethod>& method\n                      = boost::shared_ptr<OptimizationMethod>());\n\n        //! adjustment factors needed to match Black vols\n\t\tstd::vector<Real> k() const;\t\t// big T approach\n        std::vector<Real> k(const std::vector<Real>& t,\n                            const std::vector<Real>& blackVols) const;\n        void compute();\n        //calibration results\n\t\t// obsolute\n        Real value(Real x, Real T) const;\n\t\tReal value(Real t1, Real t2, Real T) const;\n\t\t\n\t\t// max abs(modelvol - marketvol)\n        Real maxError() const;\n\t\t// vector (modelvol-marketvol)*sqrt(weight)\n        Disposable<Array> errors() const;\n\t\t// square sum of errors()\n\t\tReal error() const;\n\n        EndCriteria::Type endCriteria() const;\n\n        Real sigma() const;\n        Real b1() const;\n        Real b2() const;\n        Real lambda() const;\n\n        bool sigmaIsFixed_, b1IsFixed_, b2IsFixed_, lambdaIsFixed_;\n        Real sigma_, b1_, b2_, lambda_;\n\n      private:\n\n        // optimization method used for fitting\n        mutable EndCriteria::Type dblexpEndCriteria_;\n        boost::shared_ptr<EndCriteria> endCriteria_;\n        boost::shared_ptr<OptimizationMethod> optMethod_;\n        mutable std::vector<Real> weights_;\n        bool vegaWeighted_;\n        //! Parameters\n        std::vector<Real> times_, blackVols_;\n\n\t\tinline void validateDoubleExponentialParameters(Real sigma,\n\t\t\tReal b1, // no condition on b\n\t\t\tReal b2,\n\t\t\tReal lambda) {\n\t\t\tQL_REQUIRE(sigma > 0,\n\t\t\t\t\"sigma (\" << sigma << \") must be positive\");\n\t\t\tQL_REQUIRE(b1 > 0,\n\t\t\t\t\"b1 (\" << b1 << \") must be positive\");\n\t\t\tQL_REQUIRE(b2 > 0,\n\t\t\t\t\"b2 (\" << b2 << \") must be positive\");\n\t\t\tQL_REQUIRE(lambda > 0,\n\t\t\t\t\"lambda (\" << lambda << \") must be positive\");\n\t\t}\n    };\n}\n\n#endif\n", "meta": {"hexsha": "4aefd662efb776ef9f393cbaf9d42cd97419a911", "size": 3790, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CppCoreLibrary/QLExtension/termstructures/volatility/doubleexponentialcalibration.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/termstructures/volatility/doubleexponentialcalibration.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/termstructures/volatility/doubleexponentialcalibration.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": 31.0655737705, "max_line_length": 93, "alphanum_fraction": 0.610817942, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5178600589111837}}
{"text": "#include <armadillo>\n#include <cmath>\n#include <json.hpp>\n#include <iostream>\n#include <Multivariate_Gaussian_emission.hpp>\n\nusing namespace arma;\nusing namespace robotics;\nusing namespace std;\nusing json = nlohmann::json;   \n \nnamespace hsmm {\n\n    /**\n     * MultivariateGaussianEmission implementation.\n     */\n    MultivariateGaussianEmission::MultivariateGaussianEmission(\n            vector<random::NormalDist> states) : states_(states),\n            AbstractEmissionObsCondIIDgivenState(states.size(),\n            states.at(0).mean().n_elem) {\n        for(auto& dist: states_)\n            assert(dist.mean().n_elem == getDimension());\n    }\n\n    MultivariateGaussianEmission* MultivariateGaussianEmission::clone() const {\n        return new MultivariateGaussianEmission(*this);\n    }\n\n    double MultivariateGaussianEmission::loglikelihood(int state,\n            const vec &single_obs) const {\n        return random::log_normal_density(states_.at(state), single_obs);\n    }\n\n    void MultivariateGaussianEmission::fitFromLabels(\n            const field<mat> &observations_seq, const field<ivec> &labels_seq) {\n        assert(observations_seq.n_elem == labels_seq.n_elem);\n        vector<vec> obs_for_each_state[states_.size()];\n        for(int j = 0; j < labels_seq.n_elem; j++) {\n            const mat& observations = observations_seq(j);\n            const ivec& labels = labels_seq(j);\n            assert(observations.n_cols == labels.n_elem);\n            for(int i = 0; i < labels.n_elem; i++)\n                obs_for_each_state[labels(i)].push_back(observations.col(i));\n        }\n        for(int i = 0; i < states_.size(); i++)\n            states_.at(i) = random::mle_multivariate_normal(\n                    obs_for_each_state[i]);\n    }\n\n    field<mat> MultivariateGaussianEmission::sampleFromState(int state,\n            int size, mt19937 &rng) const {\n        vector<vec> s = sample_multivariate_normal(rng, states_.at(state),\n                size);\n        field<mat> ret(size);\n        for(int i = 0; i < size; i++)\n            ret(i) = s.at(i);\n        return ret;\n    }\n};\n\n", "meta": {"hexsha": "72c3f1117186b4aaab256d4bd698f286f1c2537e", "size": 2093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Multivariate_Gaussian_emission.cpp", "max_stars_repo_name": "DiegoAE/BOSD", "max_stars_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-05-03T05:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:14:31.000Z", "max_issues_repo_path": "src/Multivariate_Gaussian_emission.cpp", "max_issues_repo_name": "DiegoAE/BOSD", "max_issues_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T15:29:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T10:14:54.000Z", "max_forks_repo_path": "src/Multivariate_Gaussian_emission.cpp", "max_forks_repo_name": "DiegoAE/BOSD", "max_forks_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T07:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T07:44:09.000Z", "avg_line_length": 34.3114754098, "max_line_length": 80, "alphanum_fraction": 0.6311514572, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.63341026367784, "lm_q1q2_score": 0.5178600589111836}}
{"text": "// Author: Daisuke Kanaizumi\n// Affiliation: Department of Applied Mathematics, Waseda University\n\n// verification program for the q-Hypergeometric function\n\n#ifndef QHYPERGEOMETRIC_HPP\n#define QHYPERGEOMETRIC_HPP\n\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/complex.hpp>\n#include <kv/qAiry.hpp>\n#include <kv/Heine.hpp>\n#include <kv/Pochhammer.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\nnamespace ub = boost::numeric::ublas;\nnamespace kv{\ntemplate <class T> interval<T> qPochhammer(const ub::vector<interval<T> >& a,const interval<T>& q,int n){\ninterval<T> res,pro;\nint r;\nr=a.size();\npro=1.;\nfor(int i=0;i<=r-1;i++){\npro=pro*qPochhammer(interval<T>(a(i)),interval<T>(q),int (n));\n}\nres=pro;\nreturn res;\n}\ntemplate <class T> complex<interval<T> >qPochhammer(const ub::vector<complex<interval<T> > >& a,const interval<T>& q,int n){\ncomplex<interval<T> >res,pro;\nint r;\nr=a.size();\npro=1.;\nfor(int i=0;i<=r-1;i++){\n  pro=pro*qPochhammer(complex<interval<T> >(a(i)),interval<T>(q),int (n));\n}\nres=pro;\nreturn res;\n}\n\ntemplate <class T> interval<T> QHypergeom(const ub::vector<interval<T> >& a,const ub::vector<interval<T> >& b,const interval<T>& q,const interval<T>& z){\n  interval<T>res,mid,first,ratio,pro1,pro2;\n  T rad;\n  int r,s;\n  r=a.size();\n  s=b.size();\n  mid=1.;\n  pro1=1.;\n  pro2=1.;\n  int N;\n  N=1000;\n  for(int i=0;i<=s-1;i++){\n    while(abs(b(i))>pow(1/q,N)){\n      N=N+500;\n    }\n  }\n  if (q>=1){\n    throw std::domain_error(\"value of q must be under 1\");\n  }\n  if (q<=0){\n    throw std::domain_error(\"q must be positive\");\n  }\n  if (r>s+1){\n    throw std::domain_error(\"r>s+1 is not implemented\");\n  }\n  if(r==s+1){\n    if (abs(z)>=1){\n      throw std::domain_error(\"absolute value of z must be under 1\");\n    }\n    if(r==2&&s==1){\n      // Heine hypergeometric function\n      res=Heine(interval<T>(a(0)),interval<T>(a(1)),interval<T>(b(0)),interval<T>(q),interval<T>(z));\n    }\n    else{\n      for(int n=1;n<=N-1;n++){\n\tmid=mid+qPochhammer(ub::vector<interval<T> >(a),interval<T>(q),int (n))*pow(z,n)\n\t  /qPochhammer(ub::vector<interval<T> >(b),interval<T>(q),int (n))/qPochhammer(interval<T>(q),interval<T>(q),int (n));\n      }\n      first=abs(qPochhammer(ub::vector<interval<T> >(a),interval<T>(q),int (N))*pow(z,N)\n\t\t/qPochhammer(ub::vector<interval<T> >(b),interval<T>(q),int (N))/qPochhammer(interval<T>(q),interval<T>(q),int (N)));\n      for(int j=0;j<=s-1;j++){\n\tpro1=pro1*(1+abs(b(j)-a(j))*pow(q,N)/abs(1-b(j)*pow(q,N)));\n      }\n      ratio=abs(z)*pro1*(1+pow(q,N)*abs(q-a(r-1))/abs(1-pow(q,N+1)));\n      if(ratio<1){\n\trad=(first/(1-ratio)).upper();\n\tres=mid+rad*interval<T>(-1.,1.);\n      }\n      else{\n\tthrow std::domain_error(\"ratio is more than 1\");\n      }\n      \n    }\n  }\n  if(r<=s){\n    if(r==0&&s==1){\n      res=_0phi_1(interval<T>(b(0)),interval<T>(q),interval<T>(z));\n    }\n    if(r==1&&s==1){\n      res=_1phi_1(interval<T>(a(0)),interval<T>(b(0)),interval<T>(q),interval<T>(z));\n    }\n    \n    else{\n      for(int n=1;n<=N-1;n++){\n\tmid=mid+qPochhammer(ub::vector<interval<T> >(a),interval<T>(q),int (n))*std::pow(-1,1+s-r)*pow(q,n*(n-1)*0.5*(1+s-r))*pow(z,n)\n\t  /qPochhammer(ub::vector<interval<T> >(b),interval<T>(q),int (n))/qPochhammer(interval<T>(q),interval<T>(q),int (n));\n      }\n      first=abs(qPochhammer(ub::vector<interval<T> >(a),interval<T>(q),int (N))*std::pow(-1,1+s-r)*pow(q,N*(N-1)*0.5*(1+s-r))*pow(z,N)\n\t\t/qPochhammer(ub::vector<interval<T> >(b),interval<T>(q),int (N))/qPochhammer(interval<T>(q),interval<T>(q),int (N)));\n      for(int k=0;k<=r-1;k++){\n\tpro1=pro1*(1+abs(b(k)-a(k))*pow(q,N)/abs(1-b(k)*pow(q,N)));\n      }\n      for(int h=r;h<=s-1;h++){\n\tpro2=pro2*pow(q,N*(1+s-r))/abs(1-b(h)*pow(q,N));\n      }\n      ratio=abs(z)*pro1*pro2/abs(1-pow(q,N));\n      if(ratio<1){\n\trad=(first/(1-ratio)).upper();\n\tres=mid+rad*interval<T>(-1.,1.);\n      }\n      else{\n\tthrow std::domain_error(\"ratio is more than 1\");\n      }\n    }\n  }\nreturn res;\n}\n  \n  template <class T> complex<interval<T> >QHypergeom(const ub::vector<complex<interval<T> > >& a,const ub::vector<complex<interval<T> > >& b,const interval<T>& q,const complex<interval<T> >& z){\n    complex<interval<T> >res,mid;\n    interval<T>first,ratio,pro1,pro2;\n    T rad;\n    int r,s;\n    r=a.size();\n    s=b.size();\n    mid=1.;\n    pro1=1.;\n    pro2=1.;\n    int N;\n    N=1000;\n    for(int i=0;i<=s-1;i++){\n      while(abs(b(i))>pow(1/q,N)){\n\tN=N+500;\n      }\n    }\n    if (q>=1){\n      throw std::domain_error(\"value of q must be under 1\");\n    }\n    if (q<=0){\n      throw std::domain_error(\"q must be positive\");\n    }\n    if (r>s+1){\n      throw std::domain_error(\"r>s+1 is not implemented\");\n    }\n    if(r==s+1){\n      if (abs(z)>=1){\n\tthrow std::domain_error(\"absolute value of z must be under 1\");\n      }\n      if(r==2&&s==1){\n\t// Heine hypergeometric function\n\tres=Heine(complex<interval<T> >(a(0)),complex<interval<T> >(a(1)),complex<interval<T> >(b(0)),interval<T>(q),complex<interval<T> >(z));\n}\n      else{\n\tfor(int n=1;n<=N-1;n++){\n\t  mid=mid+qPochhammer(ub::vector<complex<interval<T> > >(a),interval<T>(q),int (n))*pow(z,n)\n\t    /qPochhammer(ub::vector<complex<interval<T> > >(b),interval<T>(q),int (n))/qPochhammer(interval<T>(q),interval<T>(q),int (n));\n\t}\n\tfirst=abs(qPochhammer(ub::vector<complex<interval<T> > >(a),interval<T>(q),int (N))*pow(z,N)\n\t\t  /qPochhammer(ub::vector<complex<interval<T> > >(b),interval<T>(q),int (N))/qPochhammer(interval<T>(q),interval<T>(q),int (N)));\n\tfor(int j=0;j<=s-1;j++){\n\t  pro1=pro1*(1+abs(b(j)-a(j))*pow(q,N)/abs(1-b(j)*pow(q,N)));\n\t}\n\tratio=abs(z)*pro1*(1+pow(q,N)*abs(q-a(r-1))/abs(1-pow(q,N+1)));\n\tif(ratio<1){\n\t  rad=(first/(1-ratio)).upper();\n\t  res=complex_nbd(mid,rad);\n\t}\n\telse{\n\t  throw std::domain_error(\"ratio is more than 1\");\n\t}\n\t\n      }\n    }\n    if(r<=s){\n      if(r==0&&s==1){\n\tres=_0phi_1(complex<interval<T> >(b(0)),interval<T>(q),complex<interval<T> >(z));\n      }\n      if(r==1&&s==1){\n\tres=_1phi_1(complex<interval<T> >(a(0)),complex<interval<T> >(b(0)),interval<T>(q),complex<interval<T> >(z));\n      }\n      \n      else{\n\tfor(int n=1;n<=N-1;n++){\n\t  mid=mid+qPochhammer(ub::vector<complex<interval<T> > >(a),interval<T>(q),int (n))*std::pow(-1,1+s-r)*pow(q,n*(n-1)*0.5*(1+s-r))*pow(z,n)\n\t    /qPochhammer(ub::vector<complex<interval<T> > >(b),interval<T>(q),int (n))/qPochhammer(interval<T>(q),interval<T>(q),int (n));\n\t}\n\tfirst=abs(qPochhammer(ub::vector<complex<interval<T> > >(a),interval<T>(q),int (N))*std::pow(-1,1+s-r)*pow(q,N*(N-1)*0.5*(1+s-r))*pow(z,N)\n\t\t  /qPochhammer(ub::vector<complex<interval<T> > >(b),interval<T>(q),int (N))/qPochhammer(interval<T>(q),interval<T>(q),int (N)));\n\tfor(int k=0;k<=r-1;k++){\n\t  pro1=pro1*(1+abs(b(k)-a(k))*pow(q,N)/abs(1-b(k)*pow(q,N)));\n\t}\n\tfor(int h=r;h<=s-1;h++){\n\t  pro2=pro2*pow(q,N*(1+s-r))/abs(1-b(h)*pow(q,N));\n\t}\n\tratio=abs(z)*pro1*pro2/abs(1-pow(q,N));\n\tif(ratio<1){\n\t  rad=(first/(1-ratio)).upper();\n\t  res=complex_nbd(mid,rad);\n\t}\n\telse{\n\t  throw std::domain_error(\"ratio is more than 1\");\n\t}\n      }\n    }\n    return res;\n  }\n  template <class T> complex<interval<T> >qAppell1(const complex<interval<T> >& a,const complex<interval<T> >& b,const complex<interval<T> >& bp,const complex<interval<T> >& c ,\n\t\t\t\t\t\t     const interval<T>& q,const complex<interval<T> >& x,const complex<interval<T> >& y){\n    // verification program for the first q-Appell function\n    // reference:DLMF http://dlmf.nist.gov/17.11 formula 17.11.1\n    complex<interval<T> >res;\n    ub::vector<complex<interval<T> > >v1(3),v2(2);\n    v1(0)=c/a;v1(1)=x;v1(2)=y;\n    v2(0)=b*x;v2(1)=bp*y;\n    if (q>=1){\n      throw std::domain_error(\"value of q must be under 1\");\n    }\n    if (q<=0){\n      throw std::domain_error(\"q must be positive\");\n    }\n    if (abs(x).upper()>=1){\n      throw std::domain_error(\"absolute value of x must be under 1\");\n    }\n    if (abs(y).upper()>=1){\n      throw std::domain_error(\"absolute value of y must be under 1\");\n    }\n\n    res=infinite_qPochhammer(complex<interval<T> >(a),interval<T>(q))\n      *infinite_qPochhammer(complex<interval<T> >(b*x),interval<T>(q))\n      *infinite_qPochhammer(complex<interval<T> >(bp*y),interval<T>(q))\n      /infinite_qPochhammer(complex<interval<T> >(c),interval<T>(q))\n      /infinite_qPochhammer(complex<interval<T> >(x),interval<T>(q))\n      /infinite_qPochhammer(complex<interval<T> >(y),interval<T>(q))\n      *QHypergeom(ub::vector<complex<interval<T> > >(v1),ub::vector<complex<interval<T> > >(v2),interval<T>(q),complex<interval<T> >(a));\n    return res;\n  }\n\n  template <class T> interval<T> infinite_qPochhammer(const ub::vector<interval<T> >& a,const interval<T>& q){\n    interval<T> res,pro;\n    int r;\n    r=a.size();\n    pro=1.;\n    for(int i=0;i<=r-1;i++){\n      pro=pro*infinite_qPochhammer(interval<T>(a(i)),interval<T>(q));\n    }\n    res=pro;\n    return res;\n  }\n  template <class T> complex<interval<T> >infinite_qPochhammer(const ub::vector<complex<interval<T> > >& a,const interval<T>& q){\n    complex<interval<T> >res,pro;\n    int r;\n    r=a.size();\n    pro=1.;\n    for(int i=0;i<=r-1;i++){\n      pro=pro*infinite_qPochhammer(complex<interval<T> >(a(i)),interval<T>(q));\n    }\n    res=pro;\n    return res;\n  }\n  template <class T> complex<interval<T> >qLauricellaD(const complex<interval<T> >& a,const ub::vector<complex<interval<T> > >& b,const complex<interval<T> >& c ,\n\t\t\t\t\t\t     const interval<T>& q,const ub::vector<complex<interval<T> > >& x){\n    // verification program for the q-Lauricella function type D\n    // reference: Andrews (1972), Gasper-Rahman (2004) (Page 300, Exercise 10.17)\n    if (q>=1){\n      throw std::domain_error(\"value of q must be under 1\");\n    }\n    if (q<=0){\n      throw std::domain_error(\"q must be positive\");\n    }\n    if(b.size()!=x.size()){\n      throw std::domain_error(\"size of b and x must be same\");\n    }\n    int r;\n    r=b.size();\n    for(int k=0;k<=r-1;k++){\n      if(abs(x(k)).upper()>=1){\n      throw std::domain_error(\"value of x must be under 1\");\n      }\n    }\n    complex<interval<T> >res;\n    ub::vector<complex<interval<T> > >v1(r),v2(r);\n    for(int i=0;i<=r-1;i++){\n      v1(i)=b(i)*x(i);\n    }\n    v2(0)=c/a;\n    for(int j=1;j<=r-1;j++){\n      v2(j)=x(j);\n    }\n    res=infinite_qPochhammer(complex<interval<T> >(a),interval<T>(q))/infinite_qPochhammer(complex<interval<T> >(c),interval<T>(q))\n      *infinite_qPochhammer(ub::vector<complex<interval<T> > >(v1),interval<T>(q))/infinite_qPochhammer(ub::vector<complex<interval<T> > >(x),interval<T>(q))\n      *QHypergeom(ub::vector<complex<interval<T> > >(v2),ub::vector<complex<interval<T> > >(v1),interval<T>(q),complex<interval<T> >(a));\n    return res;\n  }\n  template <class T> complex<interval<T> >VWP(const complex<interval<T> >& a,const ub::vector<complex<interval<T> > >& b,const interval<T>& q,const complex<interval<T> >& x){\n    // verification program for the very-well-poised q-hypergeometric function\n    if (q>=1){\n      throw std::domain_error(\"value of q must be under 1\");\n    }\n    if (q<=0){\n      throw std::domain_error(\"q must be positive\");\n    }\n    if (abs(x)>=1){\n      throw std::domain_error(\"absolute value of x must be under 1\");\n    }\n    int r;\n    r=b.size()+3;\n    complex<interval<T> >res;\n    ub::vector<complex<interval<T> > >v1(r+1),v2(r);\n    v1(0)=a;v1(1)=q*sqrt(a);v1(2)=-q*sqrt(a);\n    for(int i=3;i<=r;i++){\n      v1(i)=b(i-3);\n    }\n    v2(0)=sqrt(a);v2(1)=-sqrt(a);\n    for(int j=2;j<=r-1;j++){\n      v2(j)=a*q/b(j-2);\n    }\n\n    res=QHypergeom(ub::vector<complex<interval<T> > >(v1),ub::vector<complex<interval<T> > >(v2),interval<T>(q),complex<interval<T> >(x));\n    return res;\n  }\n  template <class T> interval<T> Euler_qlog(const interval<T>& q,const interval<T> & x){\n    // verification program for Euler's q-logarithm\n    // reference: Koelink-Van Assche\n    interval<T> res;\n    ub::vector<interval<T> >v1(3),v2(2);\n    v1(0)=q;v1(1)=q;v1(2)=q*x;\n    v2(0)=q*q;v2(1)=0;\n    res=-q*(1-x)*QHypergeom(ub::vector<interval<T>  >(v1),ub::vector<interval<T>  >(v2),interval<T>(q),interval<T> (q))/(1-q);\n    return res;\n    \n  }\n}\n#endif\n", "meta": {"hexsha": "e71725cf6337ee7935028d90b79364f9d96bb0e9", "size": 12068, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QHypergeometric.hpp", "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": "QHypergeometric.hpp", "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": "QHypergeometric.hpp", "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": 34.9797101449, "max_line_length": 194, "alphanum_fraction": 0.5921445144, "num_tokens": 4216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744806385543, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.5178600560420638}}
{"text": "#include \"unmixing.h\"\n#include <cmath>\n#include <cfloat>\n#include <iostream>\n#include <ctime>\n#include <thread>\n#include <Eigen/LU>\n#include \"nloptutility.h\"\n#include \"image_processing.h\"\n\nusing Eigen::Vector3d;\nusing Eigen::Vector4d;\nusing Eigen::VectorXd;\nusing Eigen::Vector3i;\nusing Eigen::Matrix3d;\nusing ImageProcessing::Image;\nusing ImageProcessing::ColorImage;\n\n//#define SPARCITY\n#define PARALLEL\n\nnamespace\n{\n\n#ifdef PARALLEL\n// Perform the function in parallel for { 0, 1, ..., n - 1 }\ntemplate<typename Callable>\nvoid perform_in_parallel(Callable function, int width, int height)\n{\n    const int hint      = std::thread::hardware_concurrency();\n    const int n_threads = std::min(width * height, (hint == 0) ? 4 : hint);\n\n    auto inner_loop = [width, height, n_threads, function](const int j)\n    {\n        const int n = width * height;\n\n        const int start_index = j * (n / n_threads);\n        const int end_index   = (j + 1 == n_threads) ? n : (j + 1) * (n / n_threads);\n\n        for (int k = start_index; k < end_index; ++ k) function(k % width, k / width);\n    };\n    std::vector<std::thread> threads;\n    for (int j = 0; j < n_threads; ++ j) threads.push_back(std::thread(inner_loop, j));\n    for (auto& t : threads) t.join();\n}\n#endif\n\nstruct ColorKernel\n{\n    ColorKernel(const Vector3d& mu, const Matrix3d& sigma_inv, int seed_x = - 1, int seed_y = - 1) :\n        mu(mu),\n        sigma_inv(sigma_inv),\n        seed_x(seed_x),\n        seed_y(seed_y)\n    {\n    }\n\n    Vector3d mu;\n    Matrix3d sigma_inv;\n    int seed_x;\n    int seed_y;\n\n    double calculate_squared_Mahalanobis_distance(const Vector3d& color) const\n    {\n        return (color - mu).transpose() * sigma_inv * (color - mu);\n    }\n};\n\nstruct OptimizationParameterSet\n{\n    Vector3d target_color;\n    Vector4d lambda;\n    double   lo;\n    double   sigma;\n    std::vector<ColorKernel> kernels;\n    bool     use_sparcity;\n    bool     use_target_alphas; // If true, the alternative constraint (Eq. 6) will be used instead of the unity constraint (Eq. 2).\n    VectorXd target_alphas;     // This will be used when \"use_target_alphas\" is true.\n};\n\nVector3d composite_color(const VectorXd& alphas, const VectorXd& colors)\n{\n    const int number_of_layers = alphas.rows();\n    Vector3d sum_color = Vector3d::Zero();\n    for (int index = 0; index < number_of_layers; ++ index)\n    {\n        sum_color += alphas[index] * colors.segment<3>(index * 3);\n    }\n    return sum_color;\n}\n\nVectorXd gradient_of_equality_constraint_terms(const VectorXd& alphas,\n                                               const VectorXd& colors,\n                                               const Vector3d& target_color,\n                                               const Vector4d& constraint_vector,\n                                               const Vector4d& lambda,\n                                               double lo,\n                                               bool use_target_alphas,\n                                               const VectorXd& target_alphas = VectorXd())\n{\n    const int number_of_layers = alphas.rows();\n\n    VectorXd grad_lagrange_term = VectorXd(number_of_layers * 4);\n    VectorXd grad_penalty_term  = VectorXd(number_of_layers * 4);\n\n    const double   sum_alpha = alphas.sum();\n    const Vector3d sum_color = composite_color(alphas, colors);\n\n    for (int index = 0; index < number_of_layers; ++ index)\n    {\n        const Vector3d& u = colors.segment<3>(index * 3);\n        const double    a = alphas(index);\n\n        const Vector3d partial_g_u_per_partial_a = 2.0 * u.cwiseProduct(sum_color - target_color);\n        const double   partial_g_a_per_partial_a = use_target_alphas ? 2.0 * (a - target_alphas(index)) : 2.0 * (sum_alpha - 1.0);\n\n        const double partial_lambda_transpose_g_per_partial_alpha = lambda.segment<3>(0).transpose() * partial_g_u_per_partial_a + lambda(3) * partial_g_a_per_partial_a;\n\n        const double partial_g_u_r_per_partial_u_r = 2.0 * a * (sum_color(0) - target_color(0));\n        const double partial_g_u_g_per_partial_u_g = 2.0 * a * (sum_color(1) - target_color(1));\n        const double partial_g_u_b_per_partial_u_b = 2.0 * a * (sum_color(2) - target_color(2));\n\n        const double partial_lambda_transpose_g_per_partial_u_r = lambda(0) * partial_g_u_r_per_partial_u_r;\n        const double partial_lambda_transpose_g_per_partial_u_g = lambda(1) * partial_g_u_g_per_partial_u_g;\n        const double partial_lambda_transpose_g_per_partial_u_b = lambda(2) * partial_g_u_b_per_partial_u_b;\n\n        const Vector4d partial_g_per_partial_a = Vector4d(partial_g_u_per_partial_a(0), partial_g_u_per_partial_a(1), partial_g_u_per_partial_a(2), partial_g_a_per_partial_a);\n\n        grad_lagrange_term(index)                            = partial_lambda_transpose_g_per_partial_alpha;\n        grad_lagrange_term(number_of_layers + index * 3 + 0) = partial_lambda_transpose_g_per_partial_u_r;\n        grad_lagrange_term(number_of_layers + index * 3 + 1) = partial_lambda_transpose_g_per_partial_u_g;\n        grad_lagrange_term(number_of_layers + index * 3 + 2) = partial_lambda_transpose_g_per_partial_u_b;\n\n        grad_penalty_term(index)                            = 0.5 * lo * 2.0 * constraint_vector.transpose() * partial_g_per_partial_a;\n        grad_penalty_term(number_of_layers + index * 3 + 0) = 0.5 * lo * 2.0 * constraint_vector(0) * partial_g_u_r_per_partial_u_r;\n        grad_penalty_term(number_of_layers + index * 3 + 1) = 0.5 * lo * 2.0 * constraint_vector(1) * partial_g_u_g_per_partial_u_g;\n        grad_penalty_term(number_of_layers + index * 3 + 2) = 0.5 * lo * 2.0 * constraint_vector(2) * partial_g_u_b_per_partial_u_b;\n    }\n\n    return grad_lagrange_term + grad_penalty_term;\n}\n\ndouble calculate_equality_constraint_terms(const Vector4d& constraint_vector, const Vector4d& lambda, double lo)\n{\n    return lambda.transpose() * constraint_vector + 0.5 * lo * constraint_vector.squaredNorm();\n}\n\nVector4d calculate_equality_constraint_vector(const VectorXd& alphas,\n                                              const VectorXd& colors,\n                                              const Vector3d& target_color,\n                                              bool use_target_alphas,\n                                              const VectorXd& target_alphas = VectorXd())\n{\n    const Vector3d sum_color = composite_color(alphas, colors);\n    const Vector3d g_color   = (sum_color - target_color).cwiseProduct(sum_color - target_color);\n    const double   sum_alpha = alphas.sum();\n    const double   g_alpha   = use_target_alphas ? (alphas - target_alphas).squaredNorm() : (sum_alpha - 1.0) * (sum_alpha - 1.0);\n\n    return Vector4d(g_color(0), g_color(1), g_color(2), g_alpha);\n}\n\nVector4d calculate_equality_constraint_vector(const VectorXd& x,\n                                              const Vector3d& target_color,\n                                              bool use_target_alphas,\n                                              const VectorXd& target_alphas = VectorXd())\n{\n    const int number_of_layers = x.rows() / 4;\n    return calculate_equality_constraint_vector(x.segment(0, number_of_layers), x.segment(number_of_layers, number_of_layers * 3), target_color, use_target_alphas, target_alphas);\n}\n\n// Calculate the gradient of the main objective function (Eq. 4)\nVectorXd gradient_of_energy_function(const VectorXd& alphas,\n                                     const VectorXd& colors,\n                                     const std::vector<ColorKernel>& kernels,\n                                     double sigma,\n                                     bool use_sparcity)\n{\n    const int number_of_layers = alphas.rows();\n\n    VectorXd grad = VectorXd(number_of_layers * 4);\n\n    // Main term\n    for (int index = 0; index < number_of_layers; ++ index)\n    {\n        const ColorKernel& k = kernels[index];\n        const Vector3d&    u = colors.segment<3>(index * 3);\n        grad(index) = k.calculate_squared_Mahalanobis_distance(u);\n        grad.segment<3>(number_of_layers + index * 3) = 2.0 * alphas(index) * k.sigma_inv * (u - k.mu);\n    }\n\n    // Sparcity term\n    if (use_sparcity)\n    {\n        double alpha_sum         = alphas.sum();\n        double alpha_squared_sum = alphas.squaredNorm();\n        for (int index = 0; index < number_of_layers; ++ index)\n        {\n            grad(index) += sigma * (alpha_squared_sum - 2.0 * alphas(index) * alpha_sum) / (alpha_squared_sum * alpha_squared_sum);\n        }\n    }\n\n    return grad;\n}\n\n// Calculate the main objective function (Eq. 4)\ndouble energy_function(const VectorXd& alphas,\n                       const VectorXd& colors,\n                       const std::vector<ColorKernel>& kernels,\n                       double sigma,\n                       bool use_sparcity)\n{\n    const int number_of_layers = alphas.rows();\n\n    // Main term\n    double energy = 0.0;\n    for (int index = 0; index < number_of_layers; ++ index)\n    {\n        energy += alphas[index] * kernels[index].calculate_squared_Mahalanobis_distance(colors.segment<3>(index * 3));\n    }\n\n    // Sparcity term\n    if (use_sparcity) energy += sigma * ((alphas.sum() / alphas.squaredNorm()) - 1.0);\n\n    return energy;\n}\n\ndouble objective_function(const std::vector<double> &x, std::vector<double>& grad, void* data)\n{\n    const int number_of_layers = x.size() / 4;\n\n    const OptimizationParameterSet& set = *static_cast<const OptimizationParameterSet*>(data);\n\n    const VectorXd alphas = Eigen::Map<const VectorXd>(&x[0], number_of_layers);\n    const VectorXd colors = Eigen::Map<const VectorXd>(&x[number_of_layers], number_of_layers * 3);\n\n    const Vector4d constraint_vector = calculate_equality_constraint_vector(alphas, colors, set.target_color, set.use_target_alphas, set.target_alphas);\n\n    if (!grad.empty())\n    {\n        const VectorXd gradient_energy     = gradient_of_energy_function(alphas, colors, set.kernels, set.sigma, set.use_sparcity);\n        const VectorXd gradient_constraint = gradient_of_equality_constraint_terms(alphas, colors, set.target_color, constraint_vector, set.lambda, set.lo, set.use_target_alphas, set.target_alphas);\n        Eigen::Map<VectorXd>(&grad[0], grad.size()) = gradient_energy + gradient_constraint;\n    }\n\n    return energy_function(alphas, colors, set.kernels, set.sigma, set.use_sparcity) + calculate_equality_constraint_terms(constraint_vector, set.lambda, set.lo);\n}\n\nVectorXd solve_per_pixel_optimization(const Vector3d& target_color,\n                                      const std::vector<ColorKernel>& kernels,\n                                      bool for_refinement = false,\n                                      const VectorXd& initial_colors = VectorXd(),\n                                      const VectorXd& target_alphas = VectorXd())\n{\n    const int number_of_layers = kernels.size();\n\n    const VectorXd upper = VectorXd::Constant(number_of_layers * 4, 1.0);\n    const VectorXd lower = VectorXd::Constant(number_of_layers * 4, 0.0);\n\n    constexpr double gamma   = 0.25;\n    constexpr double epsilon = 1e-08;\n    constexpr double beta    = 10.0;\n\n    OptimizationParameterSet set;\n    set.kernels           = kernels;\n    set.lambda            = Vector4d::Constant(0.1);\n    set.lo                = 0.1;\n    set.target_color      = target_color;\n    set.sigma             = 10.0;\n    set.target_alphas     = target_alphas;\n    if (!for_refinement)\n    {\n#ifdef SPARCITY\n        set.use_sparcity      = true;\n#else\n        set.use_sparcity      = false;\n#endif\n        set.use_target_alphas = false;\n    }\n    else\n    {\n        set.use_sparcity      = false;\n        set.use_target_alphas = true;\n    }\n\n    // Find an initial solution\n    VectorXd x_initial = VectorXd::Zero(number_of_layers * 4);\n    if (!for_refinement)\n    {\n        double min_distance  = DBL_MAX;\n        int    closest_index = - 1;\n        for (int index = 0; index < number_of_layers; ++ index)\n        {\n            double distance = kernels[index].calculate_squared_Mahalanobis_distance(set.target_color);\n            if (min_distance > distance)\n            {\n                min_distance  = distance;\n                closest_index = index;\n            }\n        }\n        x_initial(closest_index) = 1.0;\n        for (int index = 0; index < number_of_layers; ++ index)\n        {\n            x_initial.segment<3>(number_of_layers + index * 3) = (index == closest_index) ? set.target_color : kernels[index].mu;\n            for (int i : { 0, 1, 2}) x_initial(number_of_layers + index * 3 + i) = std::max(std::min(x_initial(number_of_layers + index * 3 + i), 1.0), 0.0);\n        }\n    }\n    else\n    {\n        x_initial.segment(0, number_of_layers) = target_alphas;\n        x_initial.segment(number_of_layers, number_of_layers * 3) = initial_colors;\n    }\n\n    VectorXd x = x_initial;\n\n    int count = 0;\n    constexpr int max_count = 100;\n    while (true)\n    {\n        const VectorXd x_new = nloptUtility::compute(x, upper, lower, objective_function, &set, nlopt::LD_MMA, 100, epsilon);\n        const Vector4d g     = calculate_equality_constraint_vector(x    , set.target_color, for_refinement, target_alphas);\n        const Vector4d g_new = calculate_equality_constraint_vector(x_new, set.target_color, for_refinement, target_alphas);\n\n        set.lambda += set.lo * g_new;\n        if (g_new.norm() > gamma * g.norm()) set.lo *= beta;\n  \n        const bool is_unchanged = (x_new - x).squaredNorm() < epsilon;\n        const bool is_satisfied = g_new.norm() < epsilon;\n        \n        x = x_new;\n        \n        if ((is_unchanged && is_satisfied) || count > max_count) break;\n\n        ++ count;\n    }\n    return x;\n}\n\nvoid print_kernel(const ColorKernel& kernel)\n{\n    std::cout << \"mu: \" << std::endl;\n    std::cout << kernel.mu.transpose() << std::endl;\n    std::cout << \"sigma: \" << std::endl;\n    std::cout << kernel.sigma_inv.inverse() << std::endl;\n    std::cout << \"seed: \" << std::endl;\n    std::cout << \"(\" << kernel.seed_x << \", \" << kernel.seed_y << \")\" << std::endl;\n}\n\nvoid print_kernels(const std::vector<ColorKernel>& kernels)\n{\n    for (const ColorKernel& kernel : kernels)\n    {\n        std::cout << \"---------------------\" << std::endl;\n        print_kernel(kernel);\n    }\n    std::cout << \"---------------------\" << std::endl;\n}\n\nvoid compute_normal_distribution(const ColorImage& original_image, const Image& weight_map, Vector3d& mu, Matrix3d& sigma)\n{\n    const int width  = original_image.width();\n    const int height = original_image.height();\n\n    mu = Vector3d::Zero();\n    for (int x = 0; x < width; ++ x) for (int y = 0; y < height; ++ y)\n    {\n        const Vector3d I = original_image.get_rgb(x, y);\n        mu += weight_map.get_pixel(x, y) * I;\n    }\n    sigma = Matrix3d::Zero();\n    for (int x = 0; x < width; ++ x) for (int y = 0; y < height; ++ y)\n    {\n        const Vector3d I = original_image.get_rgb(x, y);\n        sigma += weight_map.get_pixel(x, y) * (I - mu) * (I - mu).transpose();\n    }\n\n    // For avoiding singularity (note: this process is not used in the original paper)\n    constexpr double epsilon = 1e-03; // This value is empirically set\n    sigma += epsilon * Matrix3d::Identity();\n}\n\nstd::vector<ColorImage> perform_matte_refinement(const ColorImage& original_image, const std::vector<ColorImage>& layers, const std::vector<ColorKernel>& kernels)\n{\n    assert(layers.size() == kernels.size());\n\n    const int number = layers.size();\n    const int width  = original_image.width();\n    const int height = original_image.height();\n    const int radius = 60 * std::min(width, height) / 1000;\n    constexpr double epsilon = 1e-04;\n\n    // Apply guided filter\n    std::vector<Image> refined_alphas;\n    for (const ColorImage& layer : layers)\n    {\n        const Image alpha = layer.get_a();\n        const Image refined_alpha = ImageProcessing::apply_guided_filter(alpha, original_image, radius, epsilon);\n\n        refined_alphas.push_back(refined_alpha);\n    }\n\n    // Regularize alphas such that the sum equals to one for each pixel\n    for (int x = 0; x < width; ++ x) for (int y = 0; y < height; ++ y)\n    {\n        double sum = 0.0;\n        for (int i = 0; i < number; ++ i)\n        {\n            refined_alphas[i].set_pixel(x, y, std::max(std::min(refined_alphas[i].get_pixel(x, y), 1.0), 0.0));\n            sum += refined_alphas[i].get_pixel(x, y);\n        }\n        assert(sum > 0.0);\n        for (int i = 0; i < number; ++ i)\n        {\n            refined_alphas[i].set_pixel(x, y, refined_alphas[i].get_pixel(x, y) / sum);\n        }\n    }\n\n    // Perform optimization\n    std::vector<ColorImage> refined_layers(number, ColorImage(width, height));\n    auto per_pixel_process = [&](int x, int y)\n    {\n        VectorXd initial_colors(number * 3);\n        VectorXd target_alphas(number);\n        for (int i = 0; i < number; ++ i)\n        {\n            initial_colors.segment<3>(i * 3) = layers[i].get_rgb(x, y);\n            target_alphas(i) = refined_alphas[i].get_pixel(x, y);\n        }\n\n        const Vector3d pixel_color = original_image.get_rgb(x, y);\n        const VectorXd solution = solve_per_pixel_optimization(pixel_color, kernels, true, initial_colors, target_alphas);\n\n        const VectorXd alphas = Eigen::Map<const VectorXd>(&solution[0], number);\n        const VectorXd colors = Eigen::Map<const VectorXd>(&solution[number], number * 3);\n\n        for (int index = 0; index < number; ++ index)\n        {\n            refined_layers[index].set_rgba(x, y, colors.segment<3>(index * 3), alphas(index));\n        }\n    };\n#ifdef PARALLEL\n    perform_in_parallel(per_pixel_process, width, height);\n#else\n    for (int x = 0; x < width; ++ x) for (int y = 0; y < height; ++ y) per_pixel_process(x, y);\n#endif\n\n    return refined_layers;\n}\n\nstd::vector<ColorImage> convert_alpha_add_to_overlay(const std::vector<ColorImage>& layers)\n{\n    const int number = layers.size();\n    const int width  = layers.front().width();\n    const int height = layers.front().height();\n\n    std::vector<ColorImage> overlay_layers(number, ColorImage(width, height));\n\n    for (int x = 0; x < width; ++ x) for (int y = 0; y < height; ++ y)\n    {\n        for (int index = 0; index < number; ++ index)\n        {\n            VectorXd overlay_alphas = VectorXd(number);\n            double sum_current_alpha = 0.0;\n            for (int i = 0; i <= index; ++ i)\n            {\n                sum_current_alpha += layers[i].get_a().get_pixel(x, y);\n            }\n            constexpr double epsilon = 1e-16;\n            overlay_alphas(index) = (sum_current_alpha < epsilon) ? 1.0 : layers[index].get_a().get_pixel(x, y) / sum_current_alpha;\n            overlay_layers[index].set_rgba(x, y, layers[index].get_rgb(x, y), overlay_alphas(index));\n        }\n    }\n    return overlay_layers;\n}\n\n}\n\nvoid ColorUnmixing::compute_color_unmixing(const std::string &image_file_path, const std::string &output_directory_path)\n{\n    clock_t start_time = clock();\n\n    // Import the target image\n    const ColorImage original_image(image_file_path);\n    const int width  = original_image.width();\n    const int height = original_image.height();\n\n    // Calculate intermediate images\n    const Image gray_image         = original_image.get_luminance();\n    const Image gradient_magnitude = ImageProcessing::calculate_gradient_magnitude(gray_image);\n\n    // Compute color models\n    std::vector<ColorKernel> kernels;\n    std::vector<std::vector<bool>> well_represented(width, std::vector<bool>(height, false));\n\n    constexpr double tau                 = 5.0; // The value used in the original paper is 5.\n    constexpr int    neighborhood_radius = 10;  // In the paper, this value is fixed to 10 (i.e., 20 x 20 neighborhood) for any input image. This may need to be modified so that it adapts to the image size.\n    constexpr int    number_of_bins      = 10;\n    \n    while (true)\n    {\n        // Initialize bins\n        double bins[number_of_bins][number_of_bins][number_of_bins];\n        std::fill(bins[0][0], bins[number_of_bins][0], 0.0);\n\n        auto get_bin = [number_of_bins, &original_image](int x, int y)\n        {\n            const Vector3d pixel_color = original_image.get_rgb(x, y);\n            const int bin_r = std::min(static_cast<int>(std::floor(pixel_color(0) * number_of_bins)), number_of_bins - 1);\n            const int bin_g = std::min(static_cast<int>(std::floor(pixel_color(1) * number_of_bins)), number_of_bins - 1);\n            const int bin_b = std::min(static_cast<int>(std::floor(pixel_color(2) * number_of_bins)), number_of_bins - 1);\n            return Vector3i(bin_r, bin_g, bin_b);\n        };\n\n        // Poll bins\n        auto per_pixel_polling_process = [&](int x, int y)\n        {\n            // Skip if the pixel is already well represented\n            if (well_represented[x][y]) return;\n\n            // Calculate bin\n            const Vector3i bin = get_bin(x, y);\n\n            // Calculate per-pixel representation score\n            double representation_score = DBL_MAX;\n            if (!kernels.empty())\n            {\n                const Vector3d pixel_color = original_image.get_rgb(x, y);\n                const VectorXd solution = solve_per_pixel_optimization(pixel_color, kernels);\n                const VectorXd alphas = Eigen::Map<const VectorXd>(&solution[0], kernels.size());\n                const VectorXd colors = Eigen::Map<const VectorXd>(&solution[kernels.size()], kernels.size() * 3);\n\n                representation_score = energy_function(alphas, colors, kernels, 0.0, false);\n            }\n\n            // Reject if it is already well represented\n            if (representation_score < tau * tau)\n            {\n                well_represented[x][y] = true;\n                return;\n            }\n\n            // Calculate vote values\n            const double vote_weight = std::exp(- gradient_magnitude.get_pixel(x, y)) * (1.0 - std::exp(- representation_score));\n\n            // Vote to bin\n            bins[bin(0)][bin(1)][bin(2)] += vote_weight;\n        };\n#ifdef PARALLEL\n        perform_in_parallel(per_pixel_polling_process, width, height);\n#else\n        for (int x = 0; x < width; ++ x) for (int y = 0; y < height; ++ y) per_pixel_polling_process(x, y);\n#endif\n        \n        // Export the current mask\n        Image well_represented_map(width, height, 0.0);\n        for (int x = 0; x < width; ++ x) for (int y = 0; y < height; ++ y)\n        {\n            well_represented_map.set_pixel(x, y, (well_represented[x][y] ? 1.0 : 0.0));\n        }\n        well_represented_map.save(output_directory_path + \"/rep\" + std::to_string(kernels.size()) + \".png\");\n\n        // Break the loop if *almost* all the pixels are already well represented\n        int count = 0;\n        for (int x = 0; x < width; ++ x) for (int y = 0; y < height; ++ y)\n        {\n            if (well_represented[x][y]) ++ count;\n        }\n        std::cout << count << \" / \" << width * height << std::endl;\n        constexpr double almost_threshold = 0.995;\n        const bool done = (almost_threshold < static_cast<double>(count) / static_cast<double>(width * height));\n        if (done) break;\n\n        // Select the most popular bin\n        Vector3i max_bin = Vector3i::Constant(- 1);\n        double max_bin_vote = 0.0;\n        for (int r = 0; r < number_of_bins; ++ r)\n        {\n            for (int g = 0; g < number_of_bins; ++ g)\n            {\n                for (int b = 0; b < number_of_bins; ++ b)\n                {\n                    if (max_bin_vote <= bins[r][g][b])\n                    {\n                        max_bin = Vector3i(r, g, b);\n                        max_bin_vote = bins[r][g][b];\n                    }\n                }\n            }\n        }\n\n        // Select seed pixel\n        int seed_x = - 1;\n        int seed_y = - 1;\n        double max_score = 0.0;\n        for (int x = 0; x < width; ++ x) for (int y = 0; y < height; ++ y)\n        {\n            // Ignore if it is well represented already\n            if (well_represented[x][y]) continue;\n\n            // Calculate bin\n            const Vector3i bin = get_bin(x, y);\n\n            // Ignore if the pixel does not belong to the selected bin\n            if (bin != max_bin) continue;\n\n            // Calculate score\n            int neighborhood_count = 0;\n            for (int offset_x = - neighborhood_radius; offset_x <= neighborhood_radius; ++ offset_x)\n            {\n                for (int offset_y = - neighborhood_radius; offset_y <= neighborhood_radius; ++ offset_y)\n                {\n                    if (x + offset_x < 0 || x + offset_x >= width)  continue;\n                    if (y + offset_y < 0 || y + offset_y >= height) continue;\n                    if (well_represented[x + offset_x][y + offset_y]) continue;\n\n                    const Vector3i neighbor_bin = get_bin(x + offset_x, y + offset_y);\n\n                    if (neighbor_bin == max_bin) ++ neighborhood_count;\n                }\n            }\n            assert(neighborhood_count > 0);\n            const double score = static_cast<double>(neighborhood_count) * std::exp(- gradient_magnitude.get_pixel(x, y));\n\n            // Update the seed pixel candidate\n            if (max_score < score)\n            {\n                max_score = score;\n                seed_x = x;\n                seed_y = y;\n            }\n        }\n        assert(seed_x >= 0 && seed_y >= 0);\n\n        // Compute guided filter weights\n        // Note: preventing the values from being negative is necessary to ensure the validity of the obtained normal distribution\n        const Image weight_map = ImageProcessing::calculate_guided_filter_kernel(gray_image, seed_x, seed_y, neighborhood_radius);\n\n        // Export the weight map\n        Image temporary_weight_map = weight_map;\n        temporary_weight_map.scale_to_unit();\n        temporary_weight_map.save(output_directory_path + \"/weight\" + std::to_string(kernels.size()) + \".png\");\n\n        // Calculate the color distribution\n        Vector3d mu;\n        Matrix3d sigma;\n        compute_normal_distribution(original_image, weight_map, mu, sigma);\n\n        // Add a new color kernel\n        const ColorKernel kernel = ColorKernel(mu, sigma.inverse(), seed_x, seed_y);\n        print_kernel(kernel);\n        kernels.push_back(kernel);\n    }\n\n    const int number_of_layers = kernels.size();\n\n    std::vector<ColorImage> layers(number_of_layers, ColorImage(width, height));\n\n    auto per_pixel_process = [&](int x, int y)\n    {\n        const Vector3d pixel_color = original_image.get_rgb(x, y);\n        const VectorXd solution = solve_per_pixel_optimization(pixel_color, kernels);\n\n        const VectorXd alphas = Eigen::Map<const VectorXd>(&solution[0], number_of_layers);\n        const VectorXd colors = Eigen::Map<const VectorXd>(&solution[number_of_layers], number_of_layers * 3);\n\n        for (int index = 0; index < number_of_layers; ++ index)\n        {\n            layers[index].set_rgba(x, y, colors.segment<3>(index * 3), alphas(index));\n        }\n    };\n\n#ifdef PARALLEL\n    perform_in_parallel(per_pixel_process, width, height);\n#else\n    for (int x = 0; x < width; ++ x) for (int y = 0; y < height; ++ y) per_pixel_process(x, y);\n#endif\n\n    const std::vector<ColorImage> overlay_layers = convert_alpha_add_to_overlay(layers);\n    const std::vector<ColorImage> refined_layers = perform_matte_refinement(original_image, layers, kernels);\n    const std::vector<ColorImage> refined_overlay_layers = convert_alpha_add_to_overlay(refined_layers);\n\n    // Export layers\n    for (int index = 0; index < number_of_layers; ++ index)\n    {\n        layers[index].save(output_directory_path + \"/layer\" + std::to_string(index) + \".png\");\n        layers[index].get_a().save(output_directory_path + \"/layer_alpha\" + std::to_string(index) + \".png\");\n        overlay_layers[index].save(output_directory_path + \"/overlay_layer\" + std::to_string(index) + \".png\");\n        refined_layers[index].save(output_directory_path + \"/refined_layer\" + std::to_string(index) + \".png\");\n        refined_layers[index].get_a().save(output_directory_path + \"/refined_layer_alpha\" + std::to_string(index) + \".png\");\n        refined_overlay_layers[index].save(output_directory_path + \"/refined_overlay_layer\" + std::to_string(index) + \".png\");\n    }\n\n    // Export the original image\n    original_image.save(output_directory_path + \"/original.png\");\n\n    // Print kernel info\n    print_kernels(kernels);\n\n    clock_t finish_time = clock();\n    double duration = (double)(finish_time - start_time) / CLOCKS_PER_SEC;\n    std::cout << \"\\nTotal Time: \" << duration << \"s\" << std::endl;\n}\n", "meta": {"hexsha": "66d1ff99d00aca05d1e5092752f216f0febe92ac", "size": 28551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unmixing/unmixing.cpp", "max_stars_repo_name": "lyfxyz/color-unmixing", "max_stars_repo_head_hexsha": "f87c2cf0007d14714f16f42c727b4015d34d12b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unmixing/unmixing.cpp", "max_issues_repo_name": "lyfxyz/color-unmixing", "max_issues_repo_head_hexsha": "f87c2cf0007d14714f16f42c727b4015d34d12b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unmixing/unmixing.cpp", "max_forks_repo_name": "lyfxyz/color-unmixing", "max_forks_repo_head_hexsha": "f87c2cf0007d14714f16f42c727b4015d34d12b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-16T00:40:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T00:40:54.000Z", "avg_line_length": 40.6709401709, "max_line_length": 206, "alphanum_fraction": 0.6124829253, "num_tokens": 7012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5178600532534458}}
{"text": "// math_fwd.hpp\n\n// TODO revise completely for new distribution classes.\n\n// Copyright Paul A. Bristow 2006.\n// Copyright John Maddock 2006.\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// Omnibus list of forward declarations of math special functions.\n\n// IT = Integer type.\n// RT = Real type (built-in floating-point types, float, double, long double) &\n// User Defined Types AT = Integer or Real type\n\n#ifndef BOOST_MATH_SPECIAL_MATH_FWD_HPP\n#define BOOST_MATH_SPECIAL_MATH_FWD_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/config/no_tr1/complex.hpp>\n#include <boost/math/policies/policy.hpp>\n#include <boost/math/special_functions/detail/round_fwd.hpp>\n#include <boost/math/tools/promotion.hpp> // for argument promotion.\n#include <boost/mpl/comparison.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <vector>\n\n#define BOOST_NO_MACRO_EXPAND /**/\n\nnamespace boost\n{\nnamespace math\n{ // Math functions (in roughly alphabetic order).\n\n// Beta functions.\ntemplate <class RT1, class RT2>\ntypename tools::promote_args<RT1, RT2>::type\n    beta(RT1 a, RT2 b); // Beta function (2 arguments).\n\ntemplate <class RT1, class RT2, class A>\ntypename tools::promote_args<RT1, RT2, A>::type\n    beta(RT1 a, RT2 b, A x); // Beta function (3 arguments).\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    beta(RT1 a, RT2 b, RT3 x,\n         const Policy& pol); // Beta function (3 arguments).\n\ntemplate <class RT1, class RT2, class RT3>\ntypename tools::promote_args<RT1, RT2, RT3>::type betac(RT1 a, RT2 b, RT3 x);\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type betac(RT1 a, RT2 b, RT3 x,\n                                                        const Policy& pol);\n\ntemplate <class RT1, class RT2, class RT3>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibeta(RT1 a, RT2 b, RT3 x); // Incomplete beta function.\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibeta(RT1 a, RT2 b, RT3 x, const Policy& pol); // Incomplete beta function.\n\ntemplate <class RT1, class RT2, class RT3>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibetac(RT1 a, RT2 b, RT3 x); // Incomplete beta complement function.\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibetac(RT1 a, RT2 b, RT3 x,\n           const Policy& pol); // Incomplete beta complement function.\n\ntemplate <class T1, class T2, class T3, class T4>\ntypename tools::promote_args<T1, T2, T3, T4>::type ibeta_inv(T1 a, T2 b, T3 p,\n                                                             T4* py);\n\ntemplate <class T1, class T2, class T3, class T4, class Policy>\ntypename tools::promote_args<T1, T2, T3, T4>::type\n    ibeta_inv(T1 a, T2 b, T3 p, T4* py, const Policy& pol);\n\ntemplate <class RT1, class RT2, class RT3>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibeta_inv(RT1 a, RT2 b, RT3 p); // Incomplete beta inverse function.\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibeta_inv(RT1 a, RT2 b, RT3 p,\n              const Policy&); // Incomplete beta inverse function.\n\ntemplate <class RT1, class RT2, class RT3>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibeta_inva(RT1 a, RT2 b, RT3 p); // Incomplete beta inverse function.\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibeta_inva(RT1 a, RT2 b, RT3 p,\n               const Policy&); // Incomplete beta inverse function.\n\ntemplate <class RT1, class RT2, class RT3>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibeta_invb(RT1 a, RT2 b, RT3 p); // Incomplete beta inverse function.\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibeta_invb(RT1 a, RT2 b, RT3 p,\n               const Policy&); // Incomplete beta inverse function.\n\ntemplate <class T1, class T2, class T3, class T4>\ntypename tools::promote_args<T1, T2, T3, T4>::type ibetac_inv(T1 a, T2 b, T3 q,\n                                                              T4* py);\n\ntemplate <class T1, class T2, class T3, class T4, class Policy>\ntypename tools::promote_args<T1, T2, T3, T4>::type\n    ibetac_inv(T1 a, T2 b, T3 q, T4* py, const Policy& pol);\n\ntemplate <class RT1, class RT2, class RT3>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibetac_inv(RT1 a, RT2 b,\n               RT3 q); // Incomplete beta complement inverse function.\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibetac_inv(RT1 a, RT2 b, RT3 q,\n               const Policy&); // Incomplete beta complement inverse function.\n\ntemplate <class RT1, class RT2, class RT3>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibetac_inva(RT1 a, RT2 b,\n                RT3 q); // Incomplete beta complement inverse function.\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibetac_inva(RT1 a, RT2 b, RT3 q,\n                const Policy&); // Incomplete beta complement inverse function.\n\ntemplate <class RT1, class RT2, class RT3>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibetac_invb(RT1 a, RT2 b,\n                RT3 q); // Incomplete beta complement inverse function.\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibetac_invb(RT1 a, RT2 b, RT3 q,\n                const Policy&); // Incomplete beta complement inverse function.\n\ntemplate <class RT1, class RT2, class RT3>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibeta_derivative(RT1 a, RT2 b, RT3 x); // derivative of incomplete beta\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type\n    ibeta_derivative(RT1 a, RT2 b, RT3 x,\n                     const Policy& pol); // derivative of incomplete beta\n\n// Binomial:\ntemplate <class T, class Policy>\nT binomial_coefficient(unsigned n, unsigned k, const Policy& pol);\ntemplate <class T>\nT binomial_coefficient(unsigned n, unsigned k);\n\n// erf & erfc error functions.\ntemplate <class RT> // Error function.\ntypename tools::promote_args<RT>::type erf(RT z);\ntemplate <class RT, class Policy> // Error function.\ntypename tools::promote_args<RT>::type erf(RT z, const Policy&);\n\ntemplate <class RT> // Error function complement.\ntypename tools::promote_args<RT>::type erfc(RT z);\ntemplate <class RT, class Policy> // Error function complement.\ntypename tools::promote_args<RT>::type erfc(RT z, const Policy&);\n\ntemplate <class RT> // Error function inverse.\ntypename tools::promote_args<RT>::type erf_inv(RT z);\ntemplate <class RT, class Policy> // Error function inverse.\ntypename tools::promote_args<RT>::type erf_inv(RT z, const Policy& pol);\n\ntemplate <class RT> // Error function complement inverse.\ntypename tools::promote_args<RT>::type erfc_inv(RT z);\ntemplate <class RT, class Policy> // Error function complement inverse.\ntypename tools::promote_args<RT>::type erfc_inv(RT z, const Policy& pol);\n\n// Polynomials:\ntemplate <class T1, class T2, class T3>\ntypename tools::promote_args<T1, T2, T3>::type legendre_next(unsigned l, T1 x,\n                                                             T2 Pl, T3 Plm1);\n\ntemplate <class T>\ntypename tools::promote_args<T>::type legendre_p(int l, T x);\ntemplate <class T>\ntypename tools::promote_args<T>::type legendre_p_prime(int l, T x);\n\ntemplate <class T, class Policy>\ninline std::vector<T> legendre_p_zeros(int l, const Policy& pol);\n\ntemplate <class T>\ninline std::vector<T> legendre_p_zeros(int l);\n\n#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1310)\ntemplate <class T, class Policy>\ntypename boost::enable_if_c<policies::is_policy<Policy>::value,\n                            typename tools::promote_args<T>::type>::type\n    legendre_p(int l, T x, const Policy& pol);\ntemplate <class T, class Policy>\ninline typename boost::enable_if_c<policies::is_policy<Policy>::value,\n                                   typename tools::promote_args<T>::type>::type\n    legendre_p_prime(int l, T x, const Policy& pol);\n#endif\ntemplate <class T>\ntypename tools::promote_args<T>::type legendre_q(unsigned l, T x);\n#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1310)\ntemplate <class T, class Policy>\ntypename boost::enable_if_c<policies::is_policy<Policy>::value,\n                            typename tools::promote_args<T>::type>::type\n    legendre_q(unsigned l, T x, const Policy& pol);\n#endif\ntemplate <class T1, class T2, class T3>\ntypename tools::promote_args<T1, T2, T3>::type\n    legendre_next(unsigned l, unsigned m, T1 x, T2 Pl, T3 Plm1);\n\ntemplate <class T>\ntypename tools::promote_args<T>::type legendre_p(int l, int m, T x);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type legendre_p(int l, int m, T x,\n                                                 const Policy& pol);\n\ntemplate <class T1, class T2, class T3>\ntypename tools::promote_args<T1, T2, T3>::type laguerre_next(unsigned n, T1 x,\n                                                             T2 Ln, T3 Lnm1);\n\ntemplate <class T1, class T2, class T3>\ntypename tools::promote_args<T1, T2, T3>::type\n    laguerre_next(unsigned n, unsigned l, T1 x, T2 Pl, T3 Plm1);\n\ntemplate <class T>\ntypename tools::promote_args<T>::type laguerre(unsigned n, T x);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type laguerre(unsigned n, unsigned m, T x,\n                                               const Policy& pol);\n\ntemplate <class T1, class T2>\nstruct laguerre_result\n{\n    typedef\n        typename mpl::if_<policies::is_policy<T2>,\n                          typename tools::promote_args<T1>::type,\n                          typename tools::promote_args<T2>::type>::type type;\n};\n\ntemplate <class T1, class T2>\ntypename laguerre_result<T1, T2>::type laguerre(unsigned n, T1 m, T2 x);\n\ntemplate <class T>\ntypename tools::promote_args<T>::type hermite(unsigned n, T x);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type hermite(unsigned n, T x,\n                                              const Policy& pol);\n\ntemplate <class T1, class T2, class T3>\ntypename tools::promote_args<T1, T2, T3>::type hermite_next(unsigned n, T1 x,\n                                                            T2 Hn, T3 Hnm1);\n\ntemplate <class T1, class T2, class T3>\ntypename tools::promote_args<T1, T2, T3>::type\n    chebyshev_next(T1 const& x, T2 const& Tn, T3 const& Tn_1);\n\ntemplate <class Real, class Policy>\ntypename tools::promote_args<Real>::type chebyshev_t(unsigned n, Real const& x,\n                                                     const Policy&);\ntemplate <class Real>\ntypename tools::promote_args<Real>::type chebyshev_t(unsigned n, Real const& x);\n\ntemplate <class Real, class Policy>\ntypename tools::promote_args<Real>::type chebyshev_u(unsigned n, Real const& x,\n                                                     const Policy&);\ntemplate <class Real>\ntypename tools::promote_args<Real>::type chebyshev_u(unsigned n, Real const& x);\n\ntemplate <class Real, class Policy>\ntypename tools::promote_args<Real>::type\n    chebyshev_t_prime(unsigned n, Real const& x, const Policy&);\ntemplate <class Real>\ntypename tools::promote_args<Real>::type chebyshev_t_prime(unsigned n,\n                                                           Real const& x);\n\ntemplate <class Real, class T2>\nReal chebyshev_clenshaw_recurrence(const Real* const c, size_t length,\n                                   const T2& x);\n\ntemplate <class T1, class T2>\nstd::complex<typename tools::promote_args<T1, T2>::type>\n    spherical_harmonic(unsigned n, int m, T1 theta, T2 phi);\n\ntemplate <class T1, class T2, class Policy>\nstd::complex<typename tools::promote_args<T1, T2>::type>\n    spherical_harmonic(unsigned n, int m, T1 theta, T2 phi, const Policy& pol);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type\n    spherical_harmonic_r(unsigned n, int m, T1 theta, T2 phi);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type\n    spherical_harmonic_r(unsigned n, int m, T1 theta, T2 phi,\n                         const Policy& pol);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type\n    spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type\n    spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi,\n                         const Policy& pol);\n\n// Elliptic integrals:\ntemplate <class T1, class T2, class T3>\ntypename tools::promote_args<T1, T2, T3>::type ellint_rf(T1 x, T2 y, T3 z);\n\ntemplate <class T1, class T2, class T3, class Policy>\ntypename tools::promote_args<T1, T2, T3>::type ellint_rf(T1 x, T2 y, T3 z,\n                                                         const Policy& pol);\n\ntemplate <class T1, class T2, class T3>\ntypename tools::promote_args<T1, T2, T3>::type ellint_rd(T1 x, T2 y, T3 z);\n\ntemplate <class T1, class T2, class T3, class Policy>\ntypename tools::promote_args<T1, T2, T3>::type ellint_rd(T1 x, T2 y, T3 z,\n                                                         const Policy& pol);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type ellint_rc(T1 x, T2 y);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type ellint_rc(T1 x, T2 y,\n                                                     const Policy& pol);\n\ntemplate <class T1, class T2, class T3, class T4>\ntypename tools::promote_args<T1, T2, T3, T4>::type ellint_rj(T1 x, T2 y, T3 z,\n                                                             T4 p);\n\ntemplate <class T1, class T2, class T3, class T4, class Policy>\ntypename tools::promote_args<T1, T2, T3, T4>::type\n    ellint_rj(T1 x, T2 y, T3 z, T4 p, const Policy& pol);\n\ntemplate <class T1, class T2, class T3>\ntypename tools::promote_args<T1, T2, T3>::type ellint_rg(T1 x, T2 y, T3 z);\n\ntemplate <class T1, class T2, class T3, class Policy>\ntypename tools::promote_args<T1, T2, T3>::type ellint_rg(T1 x, T2 y, T3 z,\n                                                         const Policy& pol);\n\ntemplate <typename T>\ntypename tools::promote_args<T>::type ellint_2(T k);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type ellint_2(T1 k, T2 phi);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type ellint_2(T1 k, T2 phi,\n                                                    const Policy& pol);\n\ntemplate <typename T>\ntypename tools::promote_args<T>::type ellint_1(T k);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type ellint_1(T1 k, T2 phi);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type ellint_1(T1 k, T2 phi,\n                                                    const Policy& pol);\n\ntemplate <typename T>\ntypename tools::promote_args<T>::type ellint_d(T k);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type ellint_d(T1 k, T2 phi);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type ellint_d(T1 k, T2 phi,\n                                                    const Policy& pol);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type jacobi_zeta(T1 k, T2 phi);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type jacobi_zeta(T1 k, T2 phi,\n                                                       const Policy& pol);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type heuman_lambda(T1 k, T2 phi);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type heuman_lambda(T1 k, T2 phi,\n                                                         const Policy& pol);\n\nnamespace detail\n{\n\ntemplate <class T, class U, class V>\nstruct ellint_3_result\n{\n    typedef typename mpl::if_<\n        policies::is_policy<V>, typename tools::promote_args<T, U>::type,\n        typename tools::promote_args<T, U, V>::type>::type type;\n};\n\n} // namespace detail\n\ntemplate <class T1, class T2, class T3>\ntypename detail::ellint_3_result<T1, T2, T3>::type ellint_3(T1 k, T2 v, T3 phi);\n\ntemplate <class T1, class T2, class T3, class Policy>\ntypename tools::promote_args<T1, T2, T3>::type ellint_3(T1 k, T2 v, T3 phi,\n                                                        const Policy& pol);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type ellint_3(T1 k, T2 v);\n\n// Factorial functions.\n// Note: not for integral types, at present.\ntemplate <class RT>\nstruct max_factorial;\ntemplate <class RT>\nRT factorial(unsigned int);\ntemplate <class RT, class Policy>\nRT factorial(unsigned int, const Policy& pol);\ntemplate <class RT>\nRT unchecked_factorial(\n    unsigned int BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(RT));\ntemplate <class RT>\nRT double_factorial(unsigned i);\ntemplate <class RT, class Policy>\nRT double_factorial(unsigned i, const Policy& pol);\n\ntemplate <class RT>\ntypename tools::promote_args<RT>::type falling_factorial(RT x, unsigned n);\n\ntemplate <class RT, class Policy>\ntypename tools::promote_args<RT>::type falling_factorial(RT x, unsigned n,\n                                                         const Policy& pol);\n\ntemplate <class RT>\ntypename tools::promote_args<RT>::type rising_factorial(RT x, int n);\n\ntemplate <class RT, class Policy>\ntypename tools::promote_args<RT>::type rising_factorial(RT x, int n,\n                                                        const Policy& pol);\n\n// Gamma functions.\ntemplate <class RT>\ntypename tools::promote_args<RT>::type tgamma(RT z);\n\ntemplate <class RT>\ntypename tools::promote_args<RT>::type tgamma1pm1(RT z);\n\ntemplate <class RT, class Policy>\ntypename tools::promote_args<RT>::type tgamma1pm1(RT z, const Policy& pol);\n\ntemplate <class RT1, class RT2>\ntypename tools::promote_args<RT1, RT2>::type tgamma(RT1 a, RT2 z);\n\ntemplate <class RT1, class RT2, class Policy>\ntypename tools::promote_args<RT1, RT2>::type tgamma(RT1 a, RT2 z,\n                                                    const Policy& pol);\n\ntemplate <class RT>\ntypename tools::promote_args<RT>::type lgamma(RT z, int* sign);\n\ntemplate <class RT, class Policy>\ntypename tools::promote_args<RT>::type lgamma(RT z, int* sign,\n                                              const Policy& pol);\n\ntemplate <class RT>\ntypename tools::promote_args<RT>::type lgamma(RT x);\n\ntemplate <class RT, class Policy>\ntypename tools::promote_args<RT>::type lgamma(RT x, const Policy& pol);\n\ntemplate <class RT1, class RT2>\ntypename tools::promote_args<RT1, RT2>::type tgamma_lower(RT1 a, RT2 z);\n\ntemplate <class RT1, class RT2, class Policy>\ntypename tools::promote_args<RT1, RT2>::type tgamma_lower(RT1 a, RT2 z,\n                                                          const Policy&);\n\ntemplate <class RT1, class RT2>\ntypename tools::promote_args<RT1, RT2>::type gamma_q(RT1 a, RT2 z);\n\ntemplate <class RT1, class RT2, class Policy>\ntypename tools::promote_args<RT1, RT2>::type gamma_q(RT1 a, RT2 z,\n                                                     const Policy&);\n\ntemplate <class RT1, class RT2>\ntypename tools::promote_args<RT1, RT2>::type gamma_p(RT1 a, RT2 z);\n\ntemplate <class RT1, class RT2, class Policy>\ntypename tools::promote_args<RT1, RT2>::type gamma_p(RT1 a, RT2 z,\n                                                     const Policy&);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type tgamma_delta_ratio(T1 z, T2 delta);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type tgamma_delta_ratio(T1 z, T2 delta,\n                                                              const Policy&);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type tgamma_ratio(T1 a, T2 b);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type tgamma_ratio(T1 a, T2 b,\n                                                        const Policy&);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type gamma_p_derivative(T1 a, T2 x);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type gamma_p_derivative(T1 a, T2 x,\n                                                              const Policy&);\n\n// gamma inverse.\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type gamma_p_inv(T1 a, T2 p);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type gamma_p_inva(T1 a, T2 p,\n                                                        const Policy&);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type gamma_p_inva(T1 a, T2 p);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type gamma_p_inv(T1 a, T2 p,\n                                                       const Policy&);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type gamma_q_inv(T1 a, T2 q);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type gamma_q_inv(T1 a, T2 q,\n                                                       const Policy&);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type gamma_q_inva(T1 a, T2 q);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type gamma_q_inva(T1 a, T2 q,\n                                                        const Policy&);\n\n// digamma:\ntemplate <class T>\ntypename tools::promote_args<T>::type digamma(T x);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type digamma(T x, const Policy&);\n\n// trigamma:\ntemplate <class T>\ntypename tools::promote_args<T>::type trigamma(T x);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type trigamma(T x, const Policy&);\n\n// polygamma:\ntemplate <class T>\ntypename tools::promote_args<T>::type polygamma(int n, T x);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type polygamma(int n, T x, const Policy&);\n\n// Hypotenuse function sqrt(x ^ 2 + y ^ 2).\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type hypot(T1 x, T2 y);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type hypot(T1 x, T2 y, const Policy&);\n\n// cbrt - cube root.\ntemplate <class RT>\ntypename tools::promote_args<RT>::type cbrt(RT z);\n\ntemplate <class RT, class Policy>\ntypename tools::promote_args<RT>::type cbrt(RT z, const Policy&);\n\n// log1p is log(x + 1)\ntemplate <class T>\ntypename tools::promote_args<T>::type log1p(T);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type log1p(T, const Policy&);\n\n// log1pmx is log(x + 1) - x\ntemplate <class T>\ntypename tools::promote_args<T>::type log1pmx(T);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type log1pmx(T, const Policy&);\n\n// Exp (x) minus 1 functions.\ntemplate <class T>\ntypename tools::promote_args<T>::type expm1(T);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type expm1(T, const Policy&);\n\n// Power - 1\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type powm1(const T1 a, const T2 z);\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type powm1(const T1 a, const T2 z,\n                                                 const Policy&);\n\n// sqrt(1+x) - 1\ntemplate <class T>\ntypename tools::promote_args<T>::type sqrt1pm1(const T& val);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type sqrt1pm1(const T& val, const Policy&);\n\n// sinus cardinals:\ntemplate <class T>\ntypename tools::promote_args<T>::type sinc_pi(T x);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type sinc_pi(T x, const Policy&);\n\ntemplate <class T>\ntypename tools::promote_args<T>::type sinhc_pi(T x);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type sinhc_pi(T x, const Policy&);\n\n// inverse hyperbolics:\ntemplate <typename T>\ntypename tools::promote_args<T>::type asinh(T x);\n\ntemplate <typename T, class Policy>\ntypename tools::promote_args<T>::type asinh(T x, const Policy&);\n\ntemplate <typename T>\ntypename tools::promote_args<T>::type acosh(T x);\n\ntemplate <typename T, class Policy>\ntypename tools::promote_args<T>::type acosh(T x, const Policy&);\n\ntemplate <typename T>\ntypename tools::promote_args<T>::type atanh(T x);\n\ntemplate <typename T, class Policy>\ntypename tools::promote_args<T>::type atanh(T x, const Policy&);\n\nnamespace detail\n{\n\ntypedef mpl::int_<0> bessel_no_int_tag;    // No integer optimisation possible.\ntypedef mpl::int_<1> bessel_maybe_int_tag; // Maybe integer optimisation.\ntypedef mpl::int_<2> bessel_int_tag;       // Definite integer optimistaion.\n\ntemplate <class T1, class T2, class Policy>\nstruct bessel_traits\n{\n    typedef typename mpl::if_<\n        is_integral<T1>, typename tools::promote_args<T2>::type,\n        typename tools::promote_args<T1, T2>::type>::type result_type;\n\n    typedef\n        typename policies::precision<result_type, Policy>::type precision_type;\n\n    typedef typename mpl::if_<\n        mpl::or_<mpl::less_equal<precision_type, mpl::int_<0>>,\n                 mpl::greater<precision_type, mpl::int_<64>>>,\n        bessel_no_int_tag,\n        typename mpl::if_<is_integral<T1>, bessel_int_tag,\n                          bessel_maybe_int_tag>::type>::type optimisation_tag;\n    typedef typename mpl::if_<\n        mpl::or_<mpl::less_equal<precision_type, mpl::int_<0>>,\n                 mpl::greater<precision_type, mpl::int_<113>>>,\n        bessel_no_int_tag,\n        typename mpl::if_<is_integral<T1>, bessel_int_tag,\n                          bessel_maybe_int_tag>::type>::type\n        optimisation_tag128;\n};\n} // namespace detail\n\n// Bessel functions:\ntemplate <class T1, class T2, class Policy>\ntypename detail::bessel_traits<T1, T2, Policy>::result_type\n    cyl_bessel_j(T1 v, T2 x, const Policy& pol);\ntemplate <class T1, class T2, class Policy>\ntypename detail::bessel_traits<T1, T2, Policy>::result_type\n    cyl_bessel_j_prime(T1 v, T2 x, const Policy& pol);\n\ntemplate <class T1, class T2>\ntypename detail::bessel_traits<T1, T2, policies::policy<>>::result_type\n    cyl_bessel_j(T1 v, T2 x);\ntemplate <class T1, class T2>\ntypename detail::bessel_traits<T1, T2, policies::policy<>>::result_type\n    cyl_bessel_j_prime(T1 v, T2 x);\n\ntemplate <class T, class Policy>\ntypename detail::bessel_traits<T, T, Policy>::result_type\n    sph_bessel(unsigned v, T x, const Policy& pol);\ntemplate <class T, class Policy>\ntypename detail::bessel_traits<T, T, Policy>::result_type\n    sph_bessel_prime(unsigned v, T x, const Policy& pol);\n\ntemplate <class T>\ntypename detail::bessel_traits<T, T, policies::policy<>>::result_type\n    sph_bessel(unsigned v, T x);\ntemplate <class T>\ntypename detail::bessel_traits<T, T, policies::policy<>>::result_type\n    sph_bessel_prime(unsigned v, T x);\n\ntemplate <class T1, class T2, class Policy>\ntypename detail::bessel_traits<T1, T2, Policy>::result_type\n    cyl_bessel_i(T1 v, T2 x, const Policy& pol);\ntemplate <class T1, class T2, class Policy>\ntypename detail::bessel_traits<T1, T2, Policy>::result_type\n    cyl_bessel_i_prime(T1 v, T2 x, const Policy& pol);\n\ntemplate <class T1, class T2>\ntypename detail::bessel_traits<T1, T2, policies::policy<>>::result_type\n    cyl_bessel_i(T1 v, T2 x);\ntemplate <class T1, class T2>\ntypename detail::bessel_traits<T1, T2, policies::policy<>>::result_type\n    cyl_bessel_i_prime(T1 v, T2 x);\n\ntemplate <class T1, class T2, class Policy>\ntypename detail::bessel_traits<T1, T2, Policy>::result_type\n    cyl_bessel_k(T1 v, T2 x, const Policy& pol);\ntemplate <class T1, class T2, class Policy>\ntypename detail::bessel_traits<T1, T2, Policy>::result_type\n    cyl_bessel_k_prime(T1 v, T2 x, const Policy& pol);\n\ntemplate <class T1, class T2>\ntypename detail::bessel_traits<T1, T2, policies::policy<>>::result_type\n    cyl_bessel_k(T1 v, T2 x);\ntemplate <class T1, class T2>\ntypename detail::bessel_traits<T1, T2, policies::policy<>>::result_type\n    cyl_bessel_k_prime(T1 v, T2 x);\n\ntemplate <class T1, class T2, class Policy>\ntypename detail::bessel_traits<T1, T2, Policy>::result_type\n    cyl_neumann(T1 v, T2 x, const Policy& pol);\ntemplate <class T1, class T2, class Policy>\ntypename detail::bessel_traits<T1, T2, Policy>::result_type\n    cyl_neumann_prime(T1 v, T2 x, const Policy& pol);\n\ntemplate <class T1, class T2>\ntypename detail::bessel_traits<T1, T2, policies::policy<>>::result_type\n    cyl_neumann(T1 v, T2 x);\ntemplate <class T1, class T2>\ntypename detail::bessel_traits<T1, T2, policies::policy<>>::result_type\n    cyl_neumann_prime(T1 v, T2 x);\n\ntemplate <class T, class Policy>\ntypename detail::bessel_traits<T, T, Policy>::result_type\n    sph_neumann(unsigned v, T x, const Policy& pol);\ntemplate <class T, class Policy>\ntypename detail::bessel_traits<T, T, Policy>::result_type\n    sph_neumann_prime(unsigned v, T x, const Policy& pol);\n\ntemplate <class T>\ntypename detail::bessel_traits<T, T, policies::policy<>>::result_type\n    sph_neumann(unsigned v, T x);\ntemplate <class T>\ntypename detail::bessel_traits<T, T, policies::policy<>>::result_type\n    sph_neumann_prime(unsigned v, T x);\n\ntemplate <class T, class Policy>\ntypename detail::bessel_traits<T, T, Policy>::result_type\n    cyl_bessel_j_zero(T v, int m, const Policy& pol);\n\ntemplate <class T>\ntypename detail::bessel_traits<T, T, policies::policy<>>::result_type\n    cyl_bessel_j_zero(T v, int m);\n\ntemplate <class T, class OutputIterator>\nOutputIterator cyl_bessel_j_zero(T v, int start_index, unsigned number_of_zeros,\n                                 OutputIterator out_it);\n\ntemplate <class T, class OutputIterator, class Policy>\nOutputIterator cyl_bessel_j_zero(T v, int start_index, unsigned number_of_zeros,\n                                 OutputIterator out_it, const Policy&);\n\ntemplate <class T, class Policy>\ntypename detail::bessel_traits<T, T, Policy>::result_type\n    cyl_neumann_zero(T v, int m, const Policy& pol);\n\ntemplate <class T>\ntypename detail::bessel_traits<T, T, policies::policy<>>::result_type\n    cyl_neumann_zero(T v, int m);\n\ntemplate <class T, class OutputIterator>\nOutputIterator cyl_neumann_zero(T v, int start_index, unsigned number_of_zeros,\n                                OutputIterator out_it);\n\ntemplate <class T, class OutputIterator, class Policy>\nOutputIterator cyl_neumann_zero(T v, int start_index, unsigned number_of_zeros,\n                                OutputIterator out_it, const Policy&);\n\ntemplate <class T1, class T2>\nstd::complex<\n    typename detail::bessel_traits<T1, T2, policies::policy<>>::result_type>\n    cyl_hankel_1(T1 v, T2 x);\n\ntemplate <class T1, class T2, class Policy>\nstd::complex<typename detail::bessel_traits<T1, T2, Policy>::result_type>\n    cyl_hankel_1(T1 v, T2 x, const Policy& pol);\n\ntemplate <class T1, class T2, class Policy>\nstd::complex<typename detail::bessel_traits<T1, T2, Policy>::result_type>\n    cyl_hankel_2(T1 v, T2 x, const Policy& pol);\n\ntemplate <class T1, class T2>\nstd::complex<\n    typename detail::bessel_traits<T1, T2, policies::policy<>>::result_type>\n    cyl_hankel_2(T1 v, T2 x);\n\ntemplate <class T1, class T2, class Policy>\nstd::complex<typename detail::bessel_traits<T1, T2, Policy>::result_type>\n    sph_hankel_1(T1 v, T2 x, const Policy& pol);\n\ntemplate <class T1, class T2>\nstd::complex<\n    typename detail::bessel_traits<T1, T2, policies::policy<>>::result_type>\n    sph_hankel_1(T1 v, T2 x);\n\ntemplate <class T1, class T2, class Policy>\nstd::complex<typename detail::bessel_traits<T1, T2, Policy>::result_type>\n    sph_hankel_2(T1 v, T2 x, const Policy& pol);\n\ntemplate <class T1, class T2>\nstd::complex<\n    typename detail::bessel_traits<T1, T2, policies::policy<>>::result_type>\n    sph_hankel_2(T1 v, T2 x);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type airy_ai(T x, const Policy&);\n\ntemplate <class T>\ntypename tools::promote_args<T>::type airy_ai(T x);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type airy_bi(T x, const Policy&);\n\ntemplate <class T>\ntypename tools::promote_args<T>::type airy_bi(T x);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type airy_ai_prime(T x, const Policy&);\n\ntemplate <class T>\ntypename tools::promote_args<T>::type airy_ai_prime(T x);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type airy_bi_prime(T x, const Policy&);\n\ntemplate <class T>\ntypename tools::promote_args<T>::type airy_bi_prime(T x);\n\ntemplate <class T>\nT airy_ai_zero(int m);\ntemplate <class T, class Policy>\nT airy_ai_zero(int m, const Policy&);\n\ntemplate <class OutputIterator>\nOutputIterator airy_ai_zero(int start_index, unsigned number_of_zeros,\n                            OutputIterator out_it);\ntemplate <class OutputIterator, class Policy>\nOutputIterator airy_ai_zero(int start_index, unsigned number_of_zeros,\n                            OutputIterator out_it, const Policy&);\n\ntemplate <class T>\nT airy_bi_zero(int m);\ntemplate <class T, class Policy>\nT airy_bi_zero(int m, const Policy&);\n\ntemplate <class OutputIterator>\nOutputIterator airy_bi_zero(int start_index, unsigned number_of_zeros,\n                            OutputIterator out_it);\ntemplate <class OutputIterator, class Policy>\nOutputIterator airy_bi_zero(int start_index, unsigned number_of_zeros,\n                            OutputIterator out_it, const Policy&);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type sin_pi(T x, const Policy&);\n\ntemplate <class T>\ntypename tools::promote_args<T>::type sin_pi(T x);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type cos_pi(T x, const Policy&);\n\ntemplate <class T>\ntypename tools::promote_args<T>::type cos_pi(T x);\n\ntemplate <class T>\nint fpclassify BOOST_NO_MACRO_EXPAND(T t);\n\ntemplate <class T>\nbool isfinite BOOST_NO_MACRO_EXPAND(T z);\n\ntemplate <class T>\nbool isinf BOOST_NO_MACRO_EXPAND(T t);\n\ntemplate <class T>\nbool isnan BOOST_NO_MACRO_EXPAND(T t);\n\ntemplate <class T>\nbool isnormal BOOST_NO_MACRO_EXPAND(T t);\n\ntemplate <class T>\nint signbit BOOST_NO_MACRO_EXPAND(T x);\n\ntemplate <class T>\nint sign BOOST_NO_MACRO_EXPAND(const T& z);\n\ntemplate <class T, class U>\ntypename tools::promote_args_permissive<T, U>::type copysign\n    BOOST_NO_MACRO_EXPAND(const T& x, const U& y);\n\ntemplate <class T>\ntypename tools::promote_args_permissive<T>::type changesign\n    BOOST_NO_MACRO_EXPAND(const T& z);\n\n// Exponential integrals:\nnamespace detail\n{\n\ntemplate <class T, class U>\nstruct expint_result\n{\n    typedef typename mpl::if_<policies::is_policy<U>,\n                              typename tools::promote_args<T>::type,\n                              typename tools::promote_args<U>::type>::type type;\n};\n\n} // namespace detail\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type expint(unsigned n, T z, const Policy&);\n\ntemplate <class T, class U>\ntypename detail::expint_result<T, U>::type expint(T const z, U const u);\n\ntemplate <class T>\ntypename tools::promote_args<T>::type expint(T z);\n\n// Zeta:\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type zeta(T s, const Policy&);\n\n// Owen's T function:\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type owens_t(T1 h, T2 a,\n                                                   const Policy& pol);\n\ntemplate <class T1, class T2>\ntypename tools::promote_args<T1, T2>::type owens_t(T1 h, T2 a);\n\n// Jacobi Functions:\ntemplate <class T, class U, class V, class Policy>\ntypename tools::promote_args<T, U, V>::type\n    jacobi_elliptic(T k, U theta, V* pcn, V* pdn, const Policy&);\n\ntemplate <class T, class U, class V>\ntypename tools::promote_args<T, U, V>::type\n    jacobi_elliptic(T k, U theta, V* pcn = 0, V* pdn = 0);\n\ntemplate <class U, class T, class Policy>\ntypename tools::promote_args<T, U>::type jacobi_sn(U k, T theta,\n                                                   const Policy& pol);\n\ntemplate <class U, class T>\ntypename tools::promote_args<T, U>::type jacobi_sn(U k, T theta);\n\ntemplate <class T, class U, class Policy>\ntypename tools::promote_args<T, U>::type jacobi_cn(T k, U theta,\n                                                   const Policy& pol);\n\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type jacobi_cn(T k, U theta);\n\ntemplate <class T, class U, class Policy>\ntypename tools::promote_args<T, U>::type jacobi_dn(T k, U theta,\n                                                   const Policy& pol);\n\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type jacobi_dn(T k, U theta);\n\ntemplate <class T, class U, class Policy>\ntypename tools::promote_args<T, U>::type jacobi_cd(T k, U theta,\n                                                   const Policy& pol);\n\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type jacobi_cd(T k, U theta);\n\ntemplate <class T, class U, class Policy>\ntypename tools::promote_args<T, U>::type jacobi_dc(T k, U theta,\n                                                   const Policy& pol);\n\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type jacobi_dc(T k, U theta);\n\ntemplate <class T, class U, class Policy>\ntypename tools::promote_args<T, U>::type jacobi_ns(T k, U theta,\n                                                   const Policy& pol);\n\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type jacobi_ns(T k, U theta);\n\ntemplate <class T, class U, class Policy>\ntypename tools::promote_args<T, U>::type jacobi_sd(T k, U theta,\n                                                   const Policy& pol);\n\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type jacobi_sd(T k, U theta);\n\ntemplate <class T, class U, class Policy>\ntypename tools::promote_args<T, U>::type jacobi_ds(T k, U theta,\n                                                   const Policy& pol);\n\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type jacobi_ds(T k, U theta);\n\ntemplate <class T, class U, class Policy>\ntypename tools::promote_args<T, U>::type jacobi_nc(T k, U theta,\n                                                   const Policy& pol);\n\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type jacobi_nc(T k, U theta);\n\ntemplate <class T, class U, class Policy>\ntypename tools::promote_args<T, U>::type jacobi_nd(T k, U theta,\n                                                   const Policy& pol);\n\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type jacobi_nd(T k, U theta);\n\ntemplate <class T, class U, class Policy>\ntypename tools::promote_args<T, U>::type jacobi_sc(T k, U theta,\n                                                   const Policy& pol);\n\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type jacobi_sc(T k, U theta);\n\ntemplate <class T, class U, class Policy>\ntypename tools::promote_args<T, U>::type jacobi_cs(T k, U theta,\n                                                   const Policy& pol);\n\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type jacobi_cs(T k, U theta);\n\ntemplate <class T>\ntypename tools::promote_args<T>::type zeta(T s);\n\n// pow:\ntemplate <int N, typename T, class Policy>\ntypename tools::promote_args<T>::type pow(T base, const Policy& policy);\n\ntemplate <int N, typename T>\ntypename tools::promote_args<T>::type pow(T base);\n\n// next:\ntemplate <class T, class U, class Policy>\ntypename tools::promote_args<T, U>::type nextafter(const T&, const U&,\n                                                   const Policy&);\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type nextafter(const T&, const U&);\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type float_next(const T&, const Policy&);\ntemplate <class T>\ntypename tools::promote_args<T>::type float_next(const T&);\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type float_prior(const T&, const Policy&);\ntemplate <class T>\ntypename tools::promote_args<T>::type float_prior(const T&);\ntemplate <class T, class U, class Policy>\ntypename tools::promote_args<T, U>::type float_distance(const T&, const U&,\n                                                        const Policy&);\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type float_distance(const T&, const U&);\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type float_advance(T val, int distance,\n                                                    const Policy& pol);\ntemplate <class T>\ntypename tools::promote_args<T>::type float_advance(const T& val, int distance);\n\ntemplate <class T, class Policy>\ntypename tools::promote_args<T>::type ulp(const T& val, const Policy& pol);\ntemplate <class T>\ntypename tools::promote_args<T>::type ulp(const T& val);\n\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type relative_difference(const T&,\n                                                             const U&);\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type epsilon_difference(const T&, const U&);\n\ntemplate <class T>\nBOOST_MATH_CONSTEXPR_TABLE_FUNCTION T\n    unchecked_bernoulli_b2n(const std::size_t n);\ntemplate <class T, class Policy>\nT bernoulli_b2n(const int i, const Policy& pol);\ntemplate <class T>\nT bernoulli_b2n(const int i);\ntemplate <class T, class OutputIterator, class Policy>\nOutputIterator bernoulli_b2n(const int start_index,\n                             const unsigned number_of_bernoullis_b2n,\n                             OutputIterator out_it, const Policy& pol);\ntemplate <class T, class OutputIterator>\nOutputIterator bernoulli_b2n(const int start_index,\n                             const unsigned number_of_bernoullis_b2n,\n                             OutputIterator out_it);\ntemplate <class T, class Policy>\nT tangent_t2n(const int i, const Policy& pol);\ntemplate <class T>\nT tangent_t2n(const int i);\ntemplate <class T, class OutputIterator, class Policy>\nOutputIterator tangent_t2n(const int start_index,\n                           const unsigned number_of_bernoullis_b2n,\n                           OutputIterator out_it, const Policy& pol);\ntemplate <class T, class OutputIterator>\nOutputIterator tangent_t2n(const int start_index,\n                           const unsigned number_of_bernoullis_b2n,\n                           OutputIterator out_it);\n\n// Lambert W:\ntemplate <class T, class Policy>\ntypename boost::math::tools::promote_args<T>::type\n    lambert_w0(T z, const Policy& pol);\ntemplate <class T>\ntypename boost::math::tools::promote_args<T>::type lambert_w0(T z);\ntemplate <class T, class Policy>\ntypename boost::math::tools::promote_args<T>::type\n    lambert_wm1(T z, const Policy& pol);\ntemplate <class T>\ntypename boost::math::tools::promote_args<T>::type lambert_wm1(T z);\ntemplate <class T, class Policy>\ntypename boost::math::tools::promote_args<T>::type\n    lambert_w0_prime(T z, const Policy& pol);\ntemplate <class T>\ntypename boost::math::tools::promote_args<T>::type lambert_w0_prime(T z);\ntemplate <class T, class Policy>\ntypename boost::math::tools::promote_args<T>::type\n    lambert_wm1_prime(T z, const Policy& pol);\ntemplate <class T>\ntypename boost::math::tools::promote_args<T>::type lambert_wm1_prime(T z);\n\n} // namespace math\n} // namespace boost\n\n#ifdef BOOST_HAS_LONG_LONG\n#define BOOST_MATH_DETAIL_LL_FUNC(Policy)                                      \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline T modf(const T& v, boost::long_long_type* ipart)                    \\\n    {                                                                          \\\n        using boost::math::modf;                                               \\\n        return modf(v, ipart, Policy());                                       \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline boost::long_long_type lltrunc(const T& v)                           \\\n    {                                                                          \\\n        using boost::math::lltrunc;                                            \\\n        return lltrunc(v, Policy());                                           \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline boost::long_long_type llround(const T& v)                           \\\n    {                                                                          \\\n        using boost::math::llround;                                            \\\n        return llround(v, Policy());                                           \\\n    }\n\n#else\n#define BOOST_MATH_DETAIL_LL_FUNC(Policy)\n#endif\n\n#define BOOST_MATH_DECLARE_SPECIAL_FUNCTIONS(Policy)                           \\\n                                                                               \\\n    BOOST_MATH_DETAIL_LL_FUNC(Policy)                                          \\\n                                                                               \\\n    template <class RT1, class RT2>                                            \\\n    inline typename boost::math::tools::promote_args<RT1, RT2>::type beta(     \\\n        RT1 a, RT2 b)                                                          \\\n    {                                                                          \\\n        return ::boost::math::beta(a, b, Policy());                            \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2, class A>                                   \\\n    inline typename boost::math::tools::promote_args<RT1, RT2, A>::type beta(  \\\n        RT1 a, RT2 b, A x)                                                     \\\n    {                                                                          \\\n        return ::boost::math::beta(a, b, x, Policy());                         \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2, class RT3>                                 \\\n    inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type      \\\n        betac(RT1 a, RT2 b, RT3 x)                                             \\\n    {                                                                          \\\n        return ::boost::math::betac(a, b, x, Policy());                        \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2, class RT3>                                 \\\n    inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type      \\\n        ibeta(RT1 a, RT2 b, RT3 x)                                             \\\n    {                                                                          \\\n        return ::boost::math::ibeta(a, b, x, Policy());                        \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2, class RT3>                                 \\\n    inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type      \\\n        ibetac(RT1 a, RT2 b, RT3 x)                                            \\\n    {                                                                          \\\n        return ::boost::math::ibetac(a, b, x, Policy());                       \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2, class T3, class T4>                          \\\n    inline typename boost::math::tools::promote_args<T1, T2, T3, T4>::type     \\\n        ibeta_inv(T1 a, T2 b, T3 p, T4* py)                                    \\\n    {                                                                          \\\n        return ::boost::math::ibeta_inv(a, b, p, py, Policy());                \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2, class RT3>                                 \\\n    inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type      \\\n        ibeta_inv(RT1 a, RT2 b, RT3 p)                                         \\\n    {                                                                          \\\n        return ::boost::math::ibeta_inv(a, b, p, Policy());                    \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2, class T3, class T4>                          \\\n    inline typename boost::math::tools::promote_args<T1, T2, T3, T4>::type     \\\n        ibetac_inv(T1 a, T2 b, T3 q, T4* py)                                   \\\n    {                                                                          \\\n        return ::boost::math::ibetac_inv(a, b, q, py, Policy());               \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2, class RT3>                                 \\\n    inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type      \\\n        ibeta_inva(RT1 a, RT2 b, RT3 p)                                        \\\n    {                                                                          \\\n        return ::boost::math::ibeta_inva(a, b, p, Policy());                   \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2, class T3>                                    \\\n    inline typename boost::math::tools::promote_args<T1, T2, T3>::type         \\\n        ibetac_inva(T1 a, T2 b, T3 q)                                          \\\n    {                                                                          \\\n        return ::boost::math::ibetac_inva(a, b, q, Policy());                  \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2, class RT3>                                 \\\n    inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type      \\\n        ibeta_invb(RT1 a, RT2 b, RT3 p)                                        \\\n    {                                                                          \\\n        return ::boost::math::ibeta_invb(a, b, p, Policy());                   \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2, class T3>                                    \\\n    inline typename boost::math::tools::promote_args<T1, T2, T3>::type         \\\n        ibetac_invb(T1 a, T2 b, T3 q)                                          \\\n    {                                                                          \\\n        return ::boost::math::ibetac_invb(a, b, q, Policy());                  \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2, class RT3>                                 \\\n    inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type      \\\n        ibetac_inv(RT1 a, RT2 b, RT3 q)                                        \\\n    {                                                                          \\\n        return ::boost::math::ibetac_inv(a, b, q, Policy());                   \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2, class RT3>                                 \\\n    inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type      \\\n        ibeta_derivative(RT1 a, RT2 b, RT3 x)                                  \\\n    {                                                                          \\\n        return ::boost::math::ibeta_derivative(a, b, x, Policy());             \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    T binomial_coefficient(unsigned n, unsigned k)                             \\\n    {                                                                          \\\n        return ::boost::math::binomial_coefficient<T, Policy>(n, k, Policy()); \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT>                                                        \\\n    inline typename boost::math::tools::promote_args<RT>::type erf(RT z)       \\\n    {                                                                          \\\n        return ::boost::math::erf(z, Policy());                                \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT>                                                        \\\n    inline typename boost::math::tools::promote_args<RT>::type erfc(RT z)      \\\n    {                                                                          \\\n        return ::boost::math::erfc(z, Policy());                               \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT>                                                        \\\n    inline typename boost::math::tools::promote_args<RT>::type erf_inv(RT z)   \\\n    {                                                                          \\\n        return ::boost::math::erf_inv(z, Policy());                            \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT>                                                        \\\n    inline typename boost::math::tools::promote_args<RT>::type erfc_inv(RT z)  \\\n    {                                                                          \\\n        return ::boost::math::erfc_inv(z, Policy());                           \\\n    }                                                                          \\\n                                                                               \\\n    using boost::math::legendre_next;                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type legendre_p(      \\\n        int l, T x)                                                            \\\n    {                                                                          \\\n        return ::boost::math::legendre_p(l, x, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type                  \\\n        legendre_p_prime(int l, T x)                                           \\\n    {                                                                          \\\n        return ::boost::math::legendre_p(l, x, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type legendre_q(      \\\n        unsigned l, T x)                                                       \\\n    {                                                                          \\\n        return ::boost::math::legendre_q(l, x, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    using ::boost::math::legendre_next;                                        \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type legendre_p(      \\\n        int l, int m, T x)                                                     \\\n    {                                                                          \\\n        return ::boost::math::legendre_p(l, m, x, Policy());                   \\\n    }                                                                          \\\n                                                                               \\\n    using ::boost::math::laguerre_next;                                        \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type laguerre(        \\\n        unsigned n, T x)                                                       \\\n    {                                                                          \\\n        return ::boost::math::laguerre(n, x, Policy());                        \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::laguerre_result<T1, T2>::type laguerre(       \\\n        unsigned n, T1 m, T2 x)                                                \\\n    {                                                                          \\\n        return ::boost::math::laguerre(n, m, x, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type hermite(         \\\n        unsigned n, T x)                                                       \\\n    {                                                                          \\\n        return ::boost::math::hermite(n, x, Policy());                         \\\n    }                                                                          \\\n                                                                               \\\n    using boost::math::hermite_next;                                           \\\n                                                                               \\\n    using boost::math::chebyshev_next;                                         \\\n                                                                               \\\n    template <class Real>                                                      \\\n    Real chebyshev_t(unsigned n, Real const& x)                                \\\n    {                                                                          \\\n        return ::boost::math::chebyshev_t(n, x, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class Real>                                                      \\\n    Real chebyshev_u(unsigned n, Real const& x)                                \\\n    {                                                                          \\\n        return ::boost::math::chebyshev_u(n, x, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class Real>                                                      \\\n    Real chebyshev_t_prime(unsigned n, Real const& x)                          \\\n    {                                                                          \\\n        return ::boost::math::chebyshev_t_prime(n, x, Policy());               \\\n    }                                                                          \\\n                                                                               \\\n    using ::boost::math::chebyshev_clenshaw_recurrence;                        \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline std::complex<                                                       \\\n        typename boost::math::tools::promote_args<T1, T2>::type>               \\\n        spherical_harmonic(unsigned n, int m, T1 theta, T2 phi)                \\\n    {                                                                          \\\n        return boost::math::spherical_harmonic(n, m, theta, phi, Policy());    \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type             \\\n        spherical_harmonic_r(unsigned n, int m, T1 theta, T2 phi)              \\\n    {                                                                          \\\n        return ::boost::math::spherical_harmonic_r(n, m, theta, phi,           \\\n                                                   Policy());                  \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type             \\\n        spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi)              \\\n    {                                                                          \\\n        return boost::math::spherical_harmonic_i(n, m, theta, phi, Policy());  \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2, class Policy>                                \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type             \\\n        spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi,              \\\n                             const Policy& pol);                               \\\n                                                                               \\\n    template <class T1, class T2, class T3>                                    \\\n    inline typename boost::math::tools::promote_args<T1, T2, T3>::type         \\\n        ellint_rf(T1 x, T2 y, T3 z)                                            \\\n    {                                                                          \\\n        return ::boost::math::ellint_rf(x, y, z, Policy());                    \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2, class T3>                                    \\\n    inline typename boost::math::tools::promote_args<T1, T2, T3>::type         \\\n        ellint_rd(T1 x, T2 y, T3 z)                                            \\\n    {                                                                          \\\n        return ::boost::math::ellint_rd(x, y, z, Policy());                    \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type ellint_rc(  \\\n        T1 x, T2 y)                                                            \\\n    {                                                                          \\\n        return ::boost::math::ellint_rc(x, y, Policy());                       \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2, class T3, class T4>                          \\\n    inline typename boost::math::tools::promote_args<T1, T2, T3, T4>::type     \\\n        ellint_rj(T1 x, T2 y, T3 z, T4 p)                                      \\\n    {                                                                          \\\n        return boost::math::ellint_rj(x, y, z, p, Policy());                   \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2, class T3>                                    \\\n    inline typename boost::math::tools::promote_args<T1, T2, T3>::type         \\\n        ellint_rg(T1 x, T2 y, T3 z)                                            \\\n    {                                                                          \\\n        return ::boost::math::ellint_rg(x, y, z, Policy());                    \\\n    }                                                                          \\\n                                                                               \\\n    template <typename T>                                                      \\\n    inline typename boost::math::tools::promote_args<T>::type ellint_2(T k)    \\\n    {                                                                          \\\n        return boost::math::ellint_2(k, Policy());                             \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type ellint_2(   \\\n        T1 k, T2 phi)                                                          \\\n    {                                                                          \\\n        return boost::math::ellint_2(k, phi, Policy());                        \\\n    }                                                                          \\\n                                                                               \\\n    template <typename T>                                                      \\\n    inline typename boost::math::tools::promote_args<T>::type ellint_d(T k)    \\\n    {                                                                          \\\n        return boost::math::ellint_d(k, Policy());                             \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type ellint_d(   \\\n        T1 k, T2 phi)                                                          \\\n    {                                                                          \\\n        return boost::math::ellint_d(k, phi, Policy());                        \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type             \\\n        jacobi_zeta(T1 k, T2 phi)                                              \\\n    {                                                                          \\\n        return boost::math::jacobi_zeta(k, phi, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type             \\\n        heuman_lambda(T1 k, T2 phi)                                            \\\n    {                                                                          \\\n        return boost::math::heuman_lambda(k, phi, Policy());                   \\\n    }                                                                          \\\n                                                                               \\\n    template <typename T>                                                      \\\n    inline typename boost::math::tools::promote_args<T>::type ellint_1(T k)    \\\n    {                                                                          \\\n        return boost::math::ellint_1(k, Policy());                             \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type ellint_1(   \\\n        T1 k, T2 phi)                                                          \\\n    {                                                                          \\\n        return boost::math::ellint_1(k, phi, Policy());                        \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2, class T3>                                    \\\n    inline typename boost::math::tools::promote_args<T1, T2, T3>::type         \\\n        ellint_3(T1 k, T2 v, T3 phi)                                           \\\n    {                                                                          \\\n        return boost::math::ellint_3(k, v, phi, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type ellint_3(   \\\n        T1 k, T2 v)                                                            \\\n    {                                                                          \\\n        return boost::math::ellint_3(k, v, Policy());                          \\\n    }                                                                          \\\n                                                                               \\\n    using boost::math::max_factorial;                                          \\\n    template <class RT>                                                        \\\n    inline RT factorial(unsigned int i)                                        \\\n    {                                                                          \\\n        return boost::math::factorial<RT>(i, Policy());                        \\\n    }                                                                          \\\n    using boost::math::unchecked_factorial;                                    \\\n    template <class RT>                                                        \\\n    inline RT double_factorial(unsigned i)                                     \\\n    {                                                                          \\\n        return boost::math::double_factorial<RT>(i, Policy());                 \\\n    }                                                                          \\\n    template <class RT>                                                        \\\n    inline typename boost::math::tools::promote_args<RT>::type                 \\\n        falling_factorial(RT x, unsigned n)                                    \\\n    {                                                                          \\\n        return boost::math::falling_factorial(x, n, Policy());                 \\\n    }                                                                          \\\n    template <class RT>                                                        \\\n    inline typename boost::math::tools::promote_args<RT>::type                 \\\n        rising_factorial(RT x, unsigned n)                                     \\\n    {                                                                          \\\n        return boost::math::rising_factorial(x, n, Policy());                  \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT>                                                        \\\n    inline typename boost::math::tools::promote_args<RT>::type tgamma(RT z)    \\\n    {                                                                          \\\n        return boost::math::tgamma(z, Policy());                               \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT>                                                        \\\n    inline typename boost::math::tools::promote_args<RT>::type tgamma1pm1(     \\\n        RT z)                                                                  \\\n    {                                                                          \\\n        return boost::math::tgamma1pm1(z, Policy());                           \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2>                                            \\\n    inline typename boost::math::tools::promote_args<RT1, RT2>::type tgamma(   \\\n        RT1 a, RT2 z)                                                          \\\n    {                                                                          \\\n        return boost::math::tgamma(a, z, Policy());                            \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT>                                                        \\\n    inline typename boost::math::tools::promote_args<RT>::type lgamma(         \\\n        RT z, int* sign)                                                       \\\n    {                                                                          \\\n        return boost::math::lgamma(z, sign, Policy());                         \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT>                                                        \\\n    inline typename boost::math::tools::promote_args<RT>::type lgamma(RT x)    \\\n    {                                                                          \\\n        return boost::math::lgamma(x, Policy());                               \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2>                                            \\\n    inline typename boost::math::tools::promote_args<RT1, RT2>::type           \\\n        tgamma_lower(RT1 a, RT2 z)                                             \\\n    {                                                                          \\\n        return boost::math::tgamma_lower(a, z, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2>                                            \\\n    inline typename boost::math::tools::promote_args<RT1, RT2>::type gamma_q(  \\\n        RT1 a, RT2 z)                                                          \\\n    {                                                                          \\\n        return boost::math::gamma_q(a, z, Policy());                           \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2>                                            \\\n    inline typename boost::math::tools::promote_args<RT1, RT2>::type gamma_p(  \\\n        RT1 a, RT2 z)                                                          \\\n    {                                                                          \\\n        return boost::math::gamma_p(a, z, Policy());                           \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type             \\\n        tgamma_delta_ratio(T1 z, T2 delta)                                     \\\n    {                                                                          \\\n        return boost::math::tgamma_delta_ratio(z, delta, Policy());            \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type             \\\n        tgamma_ratio(T1 a, T2 b)                                               \\\n    {                                                                          \\\n        return boost::math::tgamma_ratio(a, b, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type             \\\n        gamma_p_derivative(T1 a, T2 x)                                         \\\n    {                                                                          \\\n        return boost::math::gamma_p_derivative(a, x, Policy());                \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type             \\\n        gamma_p_inv(T1 a, T2 p)                                                \\\n    {                                                                          \\\n        return boost::math::gamma_p_inv(a, p, Policy());                       \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type             \\\n        gamma_p_inva(T1 a, T2 p)                                               \\\n    {                                                                          \\\n        return boost::math::gamma_p_inva(a, p, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type             \\\n        gamma_q_inv(T1 a, T2 q)                                                \\\n    {                                                                          \\\n        return boost::math::gamma_q_inv(a, q, Policy());                       \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type             \\\n        gamma_q_inva(T1 a, T2 q)                                               \\\n    {                                                                          \\\n        return boost::math::gamma_q_inva(a, q, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type digamma(T x)     \\\n    {                                                                          \\\n        return boost::math::digamma(x, Policy());                              \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type trigamma(T x)    \\\n    {                                                                          \\\n        return boost::math::trigamma(x, Policy());                             \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type polygamma(int n, \\\n                                                                        T x)   \\\n    {                                                                          \\\n        return boost::math::polygamma(n, x, Policy());                         \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type hypot(T1 x, \\\n                                                                         T2 y) \\\n    {                                                                          \\\n        return boost::math::hypot(x, y, Policy());                             \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT>                                                        \\\n    inline typename boost::math::tools::promote_args<RT>::type cbrt(RT z)      \\\n    {                                                                          \\\n        return boost::math::cbrt(z, Policy());                                 \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type log1p(T x)       \\\n    {                                                                          \\\n        return boost::math::log1p(x, Policy());                                \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type log1pmx(T x)     \\\n    {                                                                          \\\n        return boost::math::log1pmx(x, Policy());                              \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type expm1(T x)       \\\n    {                                                                          \\\n        return boost::math::expm1(x, Policy());                                \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::tools::promote_args<T1, T2>::type powm1(      \\\n        const T1 a, const T2 z)                                                \\\n    {                                                                          \\\n        return boost::math::powm1(a, z, Policy());                             \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type sqrt1pm1(        \\\n        const T& val)                                                          \\\n    {                                                                          \\\n        return boost::math::sqrt1pm1(val, Policy());                           \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type sinc_pi(T x)     \\\n    {                                                                          \\\n        return boost::math::sinc_pi(x, Policy());                              \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type sinhc_pi(T x)    \\\n    {                                                                          \\\n        return boost::math::sinhc_pi(x, Policy());                             \\\n    }                                                                          \\\n                                                                               \\\n    template <typename T>                                                      \\\n    inline typename boost::math::tools::promote_args<T>::type asinh(const T x) \\\n    {                                                                          \\\n        return boost::math::asinh(x, Policy());                                \\\n    }                                                                          \\\n                                                                               \\\n    template <typename T>                                                      \\\n    inline typename boost::math::tools::promote_args<T>::type acosh(const T x) \\\n    {                                                                          \\\n        return boost::math::acosh(x, Policy());                                \\\n    }                                                                          \\\n                                                                               \\\n    template <typename T>                                                      \\\n    inline typename boost::math::tools::promote_args<T>::type atanh(const T x) \\\n    {                                                                          \\\n        return boost::math::atanh(x, Policy());                                \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::detail::bessel_traits<T1, T2,                 \\\n                                                       Policy>::result_type    \\\n        cyl_bessel_j(T1 v, T2 x)                                               \\\n    {                                                                          \\\n        return boost::math::cyl_bessel_j(v, x, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::detail::bessel_traits<T1, T2,                 \\\n                                                       Policy>::result_type    \\\n        cyl_bessel_j_prime(T1 v, T2 x)                                         \\\n    {                                                                          \\\n        return boost::math::cyl_bessel_j_prime(v, x, Policy());                \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline                                                                     \\\n        typename boost::math::detail::bessel_traits<T, T, Policy>::result_type \\\n        sph_bessel(unsigned v, T x)                                            \\\n    {                                                                          \\\n        return boost::math::sph_bessel(v, x, Policy());                        \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline                                                                     \\\n        typename boost::math::detail::bessel_traits<T, T, Policy>::result_type \\\n        sph_bessel_prime(unsigned v, T x)                                      \\\n    {                                                                          \\\n        return boost::math::sph_bessel_prime(v, x, Policy());                  \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::detail::bessel_traits<T1, T2,                 \\\n                                                       Policy>::result_type    \\\n        cyl_bessel_i(T1 v, T2 x)                                               \\\n    {                                                                          \\\n        return boost::math::cyl_bessel_i(v, x, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::detail::bessel_traits<T1, T2,                 \\\n                                                       Policy>::result_type    \\\n        cyl_bessel_i_prime(T1 v, T2 x)                                         \\\n    {                                                                          \\\n        return boost::math::cyl_bessel_i_prime(v, x, Policy());                \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::detail::bessel_traits<T1, T2,                 \\\n                                                       Policy>::result_type    \\\n        cyl_bessel_k(T1 v, T2 x)                                               \\\n    {                                                                          \\\n        return boost::math::cyl_bessel_k(v, x, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::detail::bessel_traits<T1, T2,                 \\\n                                                       Policy>::result_type    \\\n        cyl_bessel_k_prime(T1 v, T2 x)                                         \\\n    {                                                                          \\\n        return boost::math::cyl_bessel_k_prime(v, x, Policy());                \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::detail::bessel_traits<T1, T2,                 \\\n                                                       Policy>::result_type    \\\n        cyl_neumann(T1 v, T2 x)                                                \\\n    {                                                                          \\\n        return boost::math::cyl_neumann(v, x, Policy());                       \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline typename boost::math::detail::bessel_traits<T1, T2,                 \\\n                                                       Policy>::result_type    \\\n        cyl_neumann_prime(T1 v, T2 x)                                          \\\n    {                                                                          \\\n        return boost::math::cyl_neumann_prime(v, x, Policy());                 \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline                                                                     \\\n        typename boost::math::detail::bessel_traits<T, T, Policy>::result_type \\\n        sph_neumann(unsigned v, T x)                                           \\\n    {                                                                          \\\n        return boost::math::sph_neumann(v, x, Policy());                       \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline                                                                     \\\n        typename boost::math::detail::bessel_traits<T, T, Policy>::result_type \\\n        sph_neumann_prime(unsigned v, T x)                                     \\\n    {                                                                          \\\n        return boost::math::sph_neumann_prime(v, x, Policy());                 \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline                                                                     \\\n        typename boost::math::detail::bessel_traits<T, T, Policy>::result_type \\\n        cyl_bessel_j_zero(T v, int m)                                          \\\n    {                                                                          \\\n        return boost::math::cyl_bessel_j_zero(v, m, Policy());                 \\\n    }                                                                          \\\n                                                                               \\\n    template <class OutputIterator, class T>                                   \\\n    inline void cyl_bessel_j_zero(                                             \\\n        T v, int start_index, unsigned number_of_zeros, OutputIterator out_it) \\\n    {                                                                          \\\n        boost::math::cyl_bessel_j_zero(v, start_index, number_of_zeros,        \\\n                                       out_it, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline                                                                     \\\n        typename boost::math::detail::bessel_traits<T, T, Policy>::result_type \\\n        cyl_neumann_zero(T v, int m)                                           \\\n    {                                                                          \\\n        return boost::math::cyl_neumann_zero(v, m, Policy());                  \\\n    }                                                                          \\\n                                                                               \\\n    template <class OutputIterator, class T>                                   \\\n    inline void cyl_neumann_zero(                                              \\\n        T v, int start_index, unsigned number_of_zeros, OutputIterator out_it) \\\n    {                                                                          \\\n        boost::math::cyl_neumann_zero(v, start_index, number_of_zeros, out_it, \\\n                                      Policy());                               \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type sin_pi(T x)      \\\n    {                                                                          \\\n        return boost::math::sin_pi(x);                                         \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type cos_pi(T x)      \\\n    {                                                                          \\\n        return boost::math::cos_pi(x);                                         \\\n    }                                                                          \\\n                                                                               \\\n    using boost::math::fpclassify;                                             \\\n    using boost::math::isfinite;                                               \\\n    using boost::math::isinf;                                                  \\\n    using boost::math::isnan;                                                  \\\n    using boost::math::isnormal;                                               \\\n    using boost::math::signbit;                                                \\\n    using boost::math::sign;                                                   \\\n    using boost::math::copysign;                                               \\\n    using boost::math::changesign;                                             \\\n                                                                               \\\n    template <class T, class U>                                                \\\n    inline typename boost::math::tools::promote_args<T, U>::type expint(       \\\n        T const& z, U const& u)                                                \\\n    {                                                                          \\\n        return boost::math::expint(z, u, Policy());                            \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type expint(T z)      \\\n    {                                                                          \\\n        return boost::math::expint(z, Policy());                               \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type zeta(T s)        \\\n    {                                                                          \\\n        return boost::math::zeta(s, Policy());                                 \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline T round(const T& v)                                                 \\\n    {                                                                          \\\n        using boost::math::round;                                              \\\n        return round(v, Policy());                                             \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline int iround(const T& v)                                              \\\n    {                                                                          \\\n        using boost::math::iround;                                             \\\n        return iround(v, Policy());                                            \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline long lround(const T& v)                                             \\\n    {                                                                          \\\n        using boost::math::lround;                                             \\\n        return lround(v, Policy());                                            \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline T trunc(const T& v)                                                 \\\n    {                                                                          \\\n        using boost::math::trunc;                                              \\\n        return trunc(v, Policy());                                             \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline int itrunc(const T& v)                                              \\\n    {                                                                          \\\n        using boost::math::itrunc;                                             \\\n        return itrunc(v, Policy());                                            \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline long ltrunc(const T& v)                                             \\\n    {                                                                          \\\n        using boost::math::ltrunc;                                             \\\n        return ltrunc(v, Policy());                                            \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline T modf(const T& v, T* ipart)                                        \\\n    {                                                                          \\\n        using boost::math::modf;                                               \\\n        return modf(v, ipart, Policy());                                       \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline T modf(const T& v, int* ipart)                                      \\\n    {                                                                          \\\n        using boost::math::modf;                                               \\\n        return modf(v, ipart, Policy());                                       \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline T modf(const T& v, long* ipart)                                     \\\n    {                                                                          \\\n        using boost::math::modf;                                               \\\n        return modf(v, ipart, Policy());                                       \\\n    }                                                                          \\\n                                                                               \\\n    template <int N, class T>                                                  \\\n    inline typename boost::math::tools::promote_args<T>::type pow(T v)         \\\n    {                                                                          \\\n        return boost::math::pow<N>(v, Policy());                               \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    T nextafter(const T& a, const T& b)                                        \\\n    {                                                                          \\\n        return boost::math::nextafter(a, b, Policy());                         \\\n    }                                                                          \\\n    template <class T>                                                         \\\n    T float_next(const T& a)                                                   \\\n    {                                                                          \\\n        return boost::math::float_next(a, Policy());                           \\\n    }                                                                          \\\n    template <class T>                                                         \\\n    T float_prior(const T& a)                                                  \\\n    {                                                                          \\\n        return boost::math::float_prior(a, Policy());                          \\\n    }                                                                          \\\n    template <class T>                                                         \\\n    T float_distance(const T& a, const T& b)                                   \\\n    {                                                                          \\\n        return boost::math::float_distance(a, b, Policy());                    \\\n    }                                                                          \\\n    template <class T>                                                         \\\n    T ulp(const T& a)                                                          \\\n    {                                                                          \\\n        return boost::math::ulp(a, Policy());                                  \\\n    }                                                                          \\\n                                                                               \\\n    template <class RT1, class RT2>                                            \\\n    inline typename boost::math::tools::promote_args<RT1, RT2>::type owens_t(  \\\n        RT1 a, RT2 z)                                                          \\\n    {                                                                          \\\n        return boost::math::owens_t(a, z, Policy());                           \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline std::complex<typename boost::math::detail::bessel_traits<           \\\n        T1, T2, Policy>::result_type>                                          \\\n        cyl_hankel_1(T1 v, T2 x)                                               \\\n    {                                                                          \\\n        return boost::math::cyl_hankel_1(v, x, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline std::complex<typename boost::math::detail::bessel_traits<           \\\n        T1, T2, Policy>::result_type>                                          \\\n        cyl_hankel_2(T1 v, T2 x)                                               \\\n    {                                                                          \\\n        return boost::math::cyl_hankel_2(v, x, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline std::complex<typename boost::math::detail::bessel_traits<           \\\n        T1, T2, Policy>::result_type>                                          \\\n        sph_hankel_1(T1 v, T2 x)                                               \\\n    {                                                                          \\\n        return boost::math::sph_hankel_1(v, x, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class T1, class T2>                                              \\\n    inline std::complex<typename boost::math::detail::bessel_traits<           \\\n        T1, T2, Policy>::result_type>                                          \\\n        sph_hankel_2(T1 v, T2 x)                                               \\\n    {                                                                          \\\n        return boost::math::sph_hankel_2(v, x, Policy());                      \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type jacobi_elliptic( \\\n        T k, T theta, T* pcn, T* pdn)                                          \\\n    {                                                                          \\\n        return boost::math::jacobi_elliptic(k, theta, pcn, pdn, Policy());     \\\n    }                                                                          \\\n                                                                               \\\n    template <class U, class T>                                                \\\n    inline typename boost::math::tools::promote_args<T, U>::type jacobi_sn(    \\\n        U k, T theta)                                                          \\\n    {                                                                          \\\n        return boost::math::jacobi_sn(k, theta, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T, class U>                                                \\\n    inline typename boost::math::tools::promote_args<T, U>::type jacobi_cn(    \\\n        T k, U theta)                                                          \\\n    {                                                                          \\\n        return boost::math::jacobi_cn(k, theta, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T, class U>                                                \\\n    inline typename boost::math::tools::promote_args<T, U>::type jacobi_dn(    \\\n        T k, U theta)                                                          \\\n    {                                                                          \\\n        return boost::math::jacobi_dn(k, theta, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T, class U>                                                \\\n    inline typename boost::math::tools::promote_args<T, U>::type jacobi_cd(    \\\n        T k, U theta)                                                          \\\n    {                                                                          \\\n        return boost::math::jacobi_cd(k, theta, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T, class U>                                                \\\n    inline typename boost::math::tools::promote_args<T, U>::type jacobi_dc(    \\\n        T k, U theta)                                                          \\\n    {                                                                          \\\n        return boost::math::jacobi_dc(k, theta, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T, class U>                                                \\\n    inline typename boost::math::tools::promote_args<T, U>::type jacobi_ns(    \\\n        T k, U theta)                                                          \\\n    {                                                                          \\\n        return boost::math::jacobi_ns(k, theta, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T, class U>                                                \\\n    inline typename boost::math::tools::promote_args<T, U>::type jacobi_sd(    \\\n        T k, U theta)                                                          \\\n    {                                                                          \\\n        return boost::math::jacobi_sd(k, theta, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T, class U>                                                \\\n    inline typename boost::math::tools::promote_args<T, U>::type jacobi_ds(    \\\n        T k, U theta)                                                          \\\n    {                                                                          \\\n        return boost::math::jacobi_ds(k, theta, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T, class U>                                                \\\n    inline typename boost::math::tools::promote_args<T, U>::type jacobi_nc(    \\\n        T k, U theta)                                                          \\\n    {                                                                          \\\n        return boost::math::jacobi_nc(k, theta, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T, class U>                                                \\\n    inline typename boost::math::tools::promote_args<T, U>::type jacobi_nd(    \\\n        T k, U theta)                                                          \\\n    {                                                                          \\\n        return boost::math::jacobi_nd(k, theta, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T, class U>                                                \\\n    inline typename boost::math::tools::promote_args<T, U>::type jacobi_sc(    \\\n        T k, U theta)                                                          \\\n    {                                                                          \\\n        return boost::math::jacobi_sc(k, theta, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T, class U>                                                \\\n    inline typename boost::math::tools::promote_args<T, U>::type jacobi_cs(    \\\n        T k, U theta)                                                          \\\n    {                                                                          \\\n        return boost::math::jacobi_cs(k, theta, Policy());                     \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type airy_ai(T x)     \\\n    {                                                                          \\\n        return boost::math::airy_ai(x, Policy());                              \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type airy_bi(T x)     \\\n    {                                                                          \\\n        return boost::math::airy_bi(x, Policy());                              \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type airy_ai_prime(   \\\n        T x)                                                                   \\\n    {                                                                          \\\n        return boost::math::airy_ai_prime(x, Policy());                        \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type airy_bi_prime(   \\\n        T x)                                                                   \\\n    {                                                                          \\\n        return boost::math::airy_bi_prime(x, Policy());                        \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline T airy_ai_zero(int m)                                               \\\n    {                                                                          \\\n        return boost::math::airy_ai_zero<T>(m, Policy());                      \\\n    }                                                                          \\\n    template <class T, class OutputIterator>                                   \\\n    OutputIterator airy_ai_zero(int start_index, unsigned number_of_zeros,     \\\n                                OutputIterator out_it)                         \\\n    {                                                                          \\\n        return boost::math::airy_ai_zero<T>(start_index, number_of_zeros,      \\\n                                            out_it, Policy());                 \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline T airy_bi_zero(int m)                                               \\\n    {                                                                          \\\n        return boost::math::airy_bi_zero<T>(m, Policy());                      \\\n    }                                                                          \\\n    template <class T, class OutputIterator>                                   \\\n    OutputIterator airy_bi_zero(int start_index, unsigned number_of_zeros,     \\\n                                OutputIterator out_it)                         \\\n    {                                                                          \\\n        return boost::math::airy_bi_zero<T>(start_index, number_of_zeros,      \\\n                                            out_it, Policy());                 \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    T bernoulli_b2n(const int i)                                               \\\n    {                                                                          \\\n        return boost::math::bernoulli_b2n<T>(i, Policy());                     \\\n    }                                                                          \\\n    template <class T, class OutputIterator>                                   \\\n    OutputIterator bernoulli_b2n(int start_index,                              \\\n                                 unsigned number_of_bernoullis_b2n,            \\\n                                 OutputIterator out_it)                        \\\n    {                                                                          \\\n        return boost::math::bernoulli_b2n<T>(                                  \\\n            start_index, number_of_bernoullis_b2n, out_it, Policy());          \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    T tangent_t2n(const int i)                                                 \\\n    {                                                                          \\\n        return boost::math::tangent_t2n<T>(i, Policy());                       \\\n    }                                                                          \\\n    template <class T, class OutputIterator>                                   \\\n    OutputIterator tangent_t2n(int start_index,                                \\\n                               unsigned number_of_bernoullis_b2n,              \\\n                               OutputIterator out_it)                          \\\n    {                                                                          \\\n        return boost::math::tangent_t2n<T>(                                    \\\n            start_index, number_of_bernoullis_b2n, out_it, Policy());          \\\n    }                                                                          \\\n                                                                               \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type lambert_w0(T z)  \\\n    {                                                                          \\\n        return boost::math::lambert_w0(z, Policy());                           \\\n    }                                                                          \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type lambert_wm1(T z) \\\n    {                                                                          \\\n        return boost::math::lambert_w0(z, Policy());                           \\\n    }                                                                          \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type                  \\\n        lambert_w0_prime(T z)                                                  \\\n    {                                                                          \\\n        return boost::math::lambert_w0(z, Policy());                           \\\n    }                                                                          \\\n    template <class T>                                                         \\\n    inline typename boost::math::tools::promote_args<T>::type                  \\\n        lambert_wm1_prime(T z)                                                 \\\n    {                                                                          \\\n        return boost::math::lambert_w0(z, Policy());                           \\\n    }\n\n#endif // BOOST_MATH_SPECIAL_MATH_FWD_HPP\n", "meta": {"hexsha": "76254ebc79f5f5f8a5586d6ec6ca375b39f4cf48", "size": 131115, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/math/special_functions/math_fwd.hpp", "max_stars_repo_name": "sotaoverride/backup", "max_stars_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/math/special_functions/math_fwd.hpp", "max_issues_repo_name": "sotaoverride/backup", "max_issues_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/math/special_functions/math_fwd.hpp", "max_forks_repo_name": "sotaoverride/backup", "max_forks_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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": 58.1957390146, "max_line_length": 80, "alphanum_fraction": 0.364763757, "num_tokens": 22740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.517834125196837}}
{"text": "//\n// Copyright 2021 Prathamesh Tagore <prathameshtagore@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#ifndef BOOST_GIL_IMAGE_PROCESSING_MORPHOLOGY_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_MORPHOLOGY_HPP\n#include <boost/gil/extension/numeric/kernel.hpp>\n#include <boost/gil/gray.hpp>\n#include <boost/gil/image_processing/threshold.hpp>\n\nnamespace boost\n{\nnamespace gil\n{\nnamespace detail\n{\nenum class morphological_operation\n{\n    dilation,\n    erosion,\n};\n/// \\addtogroup ImageProcessing\n/// @{\n\n/// \\brief Implements morphological operations at pixel level.This function\n/// compares neighbouring pixel values according to the kernel and choose\n/// minimum/mamximum neighbouring pixel value and assigns it to the pixel under\n/// consideration.\n/// \\param src_view - Source/Input image view.\n/// \\param dst_view - View which stores the final result of operations performed by this function.\n/// \\param kernel - Kernel matrix/structuring element containing 0's and 1's\n/// which will be used for applying the required morphological operation.\n/// \\param identifier - Indicates the type of morphological operation to be applied.\n/// \\tparam SrcView type of source image.\n/// \\tparam DstView type of output image.\n/// \\tparam Kernel type of structuring element.\ntemplate <typename SrcView, typename DstView, typename Kernel>\nvoid morph_impl(SrcView const& src_view, DstView const& dst_view, Kernel const& kernel,\n                morphological_operation identifier)\n{\n    std::ptrdiff_t flip_ker_row, flip_ker_col, row_boundary, col_boundary;\n    typename channel_type<typename SrcView::value_type>::type target_element;\n    for (std::ptrdiff_t view_row = 0; view_row < src_view.height(); ++view_row)\n    {\n        for (std::ptrdiff_t view_col = 0; view_col < src_view.width(); ++view_col)\n        {\n            target_element = src_view(view_col, view_row);\n            for (std::size_t kernel_row = 0; kernel_row < kernel.size(); ++kernel_row)\n            {\n                flip_ker_row = kernel.size() - 1 - kernel_row; // row index of flipped kernel\n\n                for (std::size_t kernel_col = 0; kernel_col < kernel.size(); ++kernel_col)\n                {\n                    flip_ker_col = kernel.size() - 1 - kernel_col; // column index of flipped kernel\n\n                    // We ensure that we consider only those pixels which are overlapped\n                    // on a non-zero kernel_element as\n                    if (kernel.at(flip_ker_row, flip_ker_col) == 0)\n                    {\n                        continue;\n                    }\n                    // index of input signal, used for checking boundary\n                    row_boundary = view_row + (kernel.center_y() - flip_ker_row);\n                    col_boundary = view_col + (kernel.center_x() - flip_ker_col);\n\n                    // ignore input samples which are out of bound\n                    if (row_boundary >= 0 && row_boundary < src_view.height() &&\n                        col_boundary >= 0 && col_boundary < src_view.width())\n                    {\n\n                        if (identifier == morphological_operation::dilation)\n                        {\n                            target_element =\n                                (std::max)(src_view(col_boundary, row_boundary)[0], target_element);\n                        }\n                        else if (identifier == morphological_operation::erosion)\n                        {\n                            target_element =\n                                (std::min)(src_view(col_boundary, row_boundary)[0], target_element);\n                        }\n                    }\n                }\n            }\n            dst_view(view_col, view_row) = target_element;\n        }\n    }\n}\n\n/// \\brief Checks feasibility of the desired operation and passes parameter\n/// values to the function morph_impl alongwith individual channel views of the\n/// input image.\n/// \\param src_view - Source/Input image view.\n/// \\param dst_view - View which stores the final result of operations performed by this function.\n/// \\param kernel - Kernel matrix/structuring element containing 0's and 1's\n/// which will be used for applying the required morphological operation.\n/// \\param identifier - Indicates the type of morphological operation to be applied.\n/// \\tparam SrcView type of source image.\n/// \\tparam DstView type of output image.\n/// \\tparam Kernel type of structuring element.\ntemplate <typename SrcView, typename DstView, typename Kernel>\nvoid morph(SrcView const& src_view, DstView const& dst_view, Kernel const& ker_mat,\n           morphological_operation identifier)\n{\n    BOOST_ASSERT(ker_mat.size() != 0 && src_view.dimensions() == dst_view.dimensions());\n    gil_function_requires<ImageViewConcept<SrcView>>();\n    gil_function_requires<MutableImageViewConcept<DstView>>();\n\n    gil_function_requires<ColorSpacesCompatibleConcept<typename color_space_type<SrcView>::type,\n                                                       typename color_space_type<DstView>::type>>();\n\n    gil::image<typename DstView::value_type> intermediate_img(src_view.dimensions());\n\n    for (std::size_t i = 0; i < src_view.num_channels(); i++)\n    {\n        morph_impl(nth_channel_view(src_view, i), nth_channel_view(view(intermediate_img), i),\n                   ker_mat, identifier);\n    }\n    copy_pixels(view(intermediate_img), dst_view);\n}\n\n/// \\brief Calculates the difference between pixel values of first image_view\n/// and second image_view.\n/// \\param src_view1 - First parameter for subtraction of views.\n/// \\param src_view2 - Second parameter for subtraction of views.\n/// \\param diff_view - View containing result of the subtraction of second view from\n/// the first view.\n/// \\tparam SrcView type of source/Input images used for subtraction.\n/// \\tparam DiffView type of image view containing the result of subtraction.\ntemplate <typename SrcView, typename DiffView>\nvoid difference_impl(SrcView const& src_view1, SrcView const& src_view2, DiffView const& diff_view)\n{\n    for (std::ptrdiff_t view_row = 0; view_row < src_view1.height(); ++view_row)\n        for (std::ptrdiff_t view_col = 0; view_col < src_view1.width(); ++view_col)\n            diff_view(view_col, view_row) =\n                src_view1(view_col, view_row) - src_view2(view_col, view_row);\n}\n\n/// \\brief Passes parameter values to the function 'difference_impl' alongwith\n/// individual channel views of input images.\n/// \\param src_view1 - First parameter for subtraction of views.\n/// \\param src_view2 - Second parameter for subtraction of views.\n/// \\param diff_view - View containing result of the subtraction of second view from the first view.\n/// \\tparam SrcView type of source/Input images used for subtraction.\n/// \\tparam DiffView type of image view containing the result of subtraction.\ntemplate <typename SrcView, typename DiffView>\nvoid difference(SrcView const& src_view1, SrcView const& src_view2, DiffView const& diff_view)\n{\n    gil_function_requires<ImageViewConcept<SrcView>>();\n    gil_function_requires<MutableImageViewConcept<DiffView>>();\n\n    gil_function_requires<ColorSpacesCompatibleConcept<\n        typename color_space_type<SrcView>::type, typename color_space_type<DiffView>::type>>();\n\n    for (std::size_t i = 0; i < src_view1.num_channels(); i++)\n    {\n        difference_impl(nth_channel_view(src_view1, i), nth_channel_view(src_view2, i),\n                        nth_channel_view(diff_view, i));\n    }\n}\n} // namespace detail\n\n/// \\brief Applies morphological dilation on the input image view using given\n/// structuring element. It gives the maximum overlapped value to the pixel\n/// overlapping with the center element of structuring element. \\param src_view\n/// - Source/input image view.\n/// \\param int_op_view - view for writing output and performing intermediate operations.\n/// \\param ker_mat - Kernel matrix/structuring element containing 0's and 1's which will be used for\n/// applying dilation.\n/// \\param iterations - Specifies the number of times dilation is to be applied on the input image\n/// view.\n/// \\tparam SrcView type of source image, models gil::ImageViewConcept.\n/// \\tparam IntOpView type of output image, models gil::MutableImageViewConcept.\n/// \\tparam Kernel type of structuring element.\ntemplate <typename SrcView, typename IntOpView, typename Kernel>\nvoid dilate(SrcView const& src_view, IntOpView const& int_op_view, Kernel const& ker_mat,\n            int iterations)\n{\n    copy_pixels(src_view, int_op_view);\n    for (int i = 0; i < iterations; ++i)\n        morph(int_op_view, int_op_view, ker_mat, detail::morphological_operation::dilation);\n}\n\n/// \\brief Applies morphological erosion on the input image view using given\n/// structuring element. It gives the minimum overlapped value to the pixel\n/// overlapping with the center element of structuring element.\n/// \\param src_view - Source/input image view.\n/// \\param int_op_view - view for writing output and performing intermediate operations.\n/// \\param ker_mat - Kernel matrix/structuring element containing 0's and 1's which will be used for\n/// applying erosion.\n/// \\param iterations - Specifies the number of times erosion is to be applied on the input\n/// image view.\n/// \\tparam SrcView type of source image, models gil::ImageViewConcept.\n/// \\tparam IntOpView type of output image, models gil::MutableImageViewConcept.\n/// \\tparam Kernel type of structuring element.\ntemplate <typename SrcView, typename IntOpView, typename Kernel>\nvoid erode(SrcView const& src_view, IntOpView const& int_op_view, Kernel const& ker_mat,\n           int iterations)\n{\n    copy_pixels(src_view, int_op_view);\n    for (int i = 0; i < iterations; ++i)\n        morph(int_op_view, int_op_view, ker_mat, detail::morphological_operation::erosion);\n}\n\n/// \\brief Performs erosion and then dilation on the input image view . This\n/// operation is utilized for removing noise from images.\n/// \\param src_view - Source/input image view.\n/// \\param int_op_view - view for writing output and performing intermediate operations.\n/// \\param ker_mat - Kernel matrix/structuring element containing 0's and 1's which will be used for\n/// applying the opening operation.\n/// \\tparam SrcView type of source image, models gil::ImageViewConcept.\n/// \\tparam IntOpView type of output image, models gil::MutableImageViewConcept.\n/// \\tparam Kernel type of structuring element.\ntemplate <typename SrcView, typename IntOpView, typename Kernel>\nvoid opening(SrcView const& src_view, IntOpView const& int_op_view, Kernel const& ker_mat)\n{\n    erode(src_view, int_op_view, ker_mat, 1);\n    dilate(int_op_view, int_op_view, ker_mat, 1);\n}\n\n/// \\brief Performs dilation and then erosion on the input image view which is\n/// exactly opposite to the opening operation . Closing operation can be\n/// utilized for closing small holes inside foreground objects.\n/// \\param src_view - Source/input image view.\n/// \\param int_op_view - view for writing output and performing intermediate operations.\n/// \\param ker_mat - Kernel matrix/structuring element containing 0's and 1's which will be used for\n/// applying the closing operation.\n/// \\tparam SrcView type of source image, models gil::ImageViewConcept.\n/// \\tparam IntOpView type of output image, models gil::MutableImageViewConcept.\n/// \\tparam Kernel type of structuring element.\ntemplate <typename SrcView, typename IntOpView, typename Kernel>\nvoid closing(SrcView const& src_view, IntOpView const& int_op_view, Kernel const& ker_mat)\n{\n    dilate(src_view, int_op_view, ker_mat, 1);\n    erode(int_op_view, int_op_view, ker_mat, 1);\n}\n\n/// \\brief Calculates the difference between image views generated after\n/// applying dilation dilation and erosion on an image . The resultant image\n/// will look like the outline of the object(s) present in the image.\n/// \\param src_view - Source/input image view.\n/// \\param dst_view - Destination view which will store the final result of morphological\n/// gradient operation.\n/// \\param ker_mat - Kernel matrix/structuring element containing 0's and 1's which\n/// will be used for applying the morphological gradient operation.\n/// \\tparam SrcView type of source image, models gil::ImageViewConcept.\n/// \\tparam DstView type of output image, models gil::MutableImageViewConcept.\n/// \\tparam Kernel type of structuring element.\ntemplate <typename SrcView, typename DstView, typename Kernel>\nvoid morphological_gradient(SrcView const& src_view, DstView const& dst_view, Kernel const& ker_mat)\n{\n    using namespace boost::gil;\n    gil::image<typename DstView::value_type> int_dilate(src_view.dimensions()),\n        int_erode(src_view.dimensions());\n    dilate(src_view, view(int_dilate), ker_mat, 1);\n    erode(src_view, view(int_erode), ker_mat, 1);\n    difference(view(int_dilate), view(int_erode), dst_view);\n}\n\n/// \\brief Calculates the difference between input image view and the view\n/// generated by opening operation on the input image view.\n/// \\param src_view - Source/input image view.\n/// \\param dst_view - Destination view which will store the final result of top hat operation.\n/// \\param ker_mat - Kernel matrix/structuring element containing 0's and 1's which will be used for\n/// applying the top hat operation.\n/// \\tparam SrcView type of source image, models gil::ImageViewConcept.\n/// \\tparam DstView type of output image, models gil::MutableImageViewConcept.\n/// \\tparam Kernel type of structuring element.\ntemplate <typename SrcView, typename DstView, typename Kernel>\nvoid top_hat(SrcView const& src_view, DstView const& dst_view, Kernel const& ker_mat)\n{\n    using namespace boost::gil;\n    gil::image<typename DstView::value_type> int_opening(src_view.dimensions());\n    opening(src_view, view(int_opening), ker_mat);\n    difference(src_view, view(int_opening), dst_view);\n}\n\n/// \\brief Calculates the difference between closing of the input image and\n/// input image.\n/// \\param src_view - Source/input image view.\n/// \\param dst_view - Destination view which will store the final result of black hat operation.\n/// \\param ker_mat - Kernel matrix/structuring element containing 0's and 1's\n/// which will be used for applying the black hat operation.\n/// \\tparam SrcView type of source image, models gil::ImageViewConcept.\n/// \\tparam DstView type of output image, models gil::MutableImageViewConcept.\n/// \\tparam Kernel type of structuring element.\ntemplate <typename SrcView, typename DstView, typename Kernel>\nvoid black_hat(SrcView const& src_view, DstView const& dst_view, Kernel const& ker_mat)\n{\n    using namespace boost::gil;\n    gil::image<typename DstView::value_type> int_closing(src_view.dimensions());\n    closing(src_view, view(int_closing), ker_mat);\n    difference(view(int_closing), src_view, dst_view);\n}\n/// @}\n}}     // namespace boost::gil\n#endif // BOOST_GIL_IMAGE_PROCESSING_MORPHOLOGY_HPP\n", "meta": {"hexsha": "1149b2c165835a99b7d9493018a3a638d1f8ee13", "size": 14975, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/morphology.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/morphology.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/morphology.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": 49.7508305648, "max_line_length": 100, "alphanum_fraction": 0.7131218698, "num_tokens": 3328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5178341201930226}}
{"text": "#ifndef _MODEL_HPP_\n#define _MODEL_HPP_\n\n#include \"Trajectory.h\"\n#include <vector>\n#include \"Policy.h\"\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\n/*\nThis class builds a model of an MDPs with tabular states and actions, and a finite  horizon, L.\n*/\n\nclass Model {\npublic:\n\t// Adding a defauly constructor so that I can extend it\n\tModel();\n\n\t/*\n\tTake historical data in trajs and build a model. numState and numActions are the total numbers of possible states and actions\n\t*/\n\tModel(const vector<Trajectory*> & trajs, int numStates, int numActions, int L, bool JiangStyle);\n\n\t/*\n\tUse the model to directly estimate the value of a policy. This uses value iteration.\n\t*/\n\t//double getPolicyValue(const Policy & pi) const;\n\n\t// V and Q predictions - can be loaded for a specific evaluation policy\n\tvoid loadEvalPolicy(const Policy & pi, const int & L); // int L = Gridworld::getMaxTrajLen();\n\tvector<VectorXd> actionProbabilities; // [s][a]\n\tvector<VectorXd> V; // [t](s) - t in [0,L].\n\tvector<MatrixXd> Q; // [t](s,a)\n\t//vector<MatrixXd> Rsa; // [t](s,a) - Prediction of R_t given that S_0 =s and A_0=a\n\t//vector<vector<MatrixXd>> Rsas; // [t][s](a,sPrime) - Prediction of R_t given that S_0 =s and A_0=a, and S_1 = sPrime\n\t//MatrixXd Rs; // (s,t)\n\tdouble evalPolicyValue;\n\n\t// Generate trajectories from the provided policy\n\tvector<Trajectory> generateTrajectories(const Policy & pi, int N, mt19937_64 & generator) const;\n\n\t// Estimate value of policy under model using Monte Carlo returns\n  double evalMonteCarlo(const Policy & pi, int N, mt19937_64 & generator) const;\n\n\t// We exposed these variables in order to do DRv2 (version 2 implementations) without having to compute Rsa and Rsas tables above (compute intensive)\n\tvector<vector<vector<double>>> R;\t\t\t\t// R[s][a][s']. Size = [numStates][numActions][numStates+1]\n\tvector<vector<vector<double>>> P;\t\t\t\t// P[s][a][s']. Size = [numStates][numActions][numStates+1]\n\n//private:\n\tint N;\n\tint L;\n\tint numStates;\n\tint numActions;\n\tvector<double> d0;\t\t\t\t\t\t\t\t// d0[s] = Pr(S_0=s). Size = [numStates]\n\n\t// How many times was each (s), (s,a), and (s,a,s') tuple seen?\n\tvector<vector<int>> stateActionCounts;\n\tvector<vector<int>> stateActionCounts_includingHorizon;\t\t\t\t // Includes transitions to terminal absorbing state due to time horizon\n\tvector<vector<vector<int>>> stateActionStateCounts;\n\tvector<vector<vector<int>>> stateActionStateCounts_includingHorizon; // Includes transitions to terminal absorbing state due to time horizon\n};\n\n#endif\n", "meta": {"hexsha": "e48d8058dcd79f15676f90151c1bd426f59acef1", "size": 2516, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gridworld/headers/Model.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/Model.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/Model.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": 38.1212121212, "max_line_length": 150, "alphanum_fraction": 0.7209856916, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.517834117983416}}
{"text": "#ifdef STAN_OPENCL\n\n#include <stan/math/opencl/kernel_generator.hpp>\n#include <stan/math/opencl/matrix_cl.hpp>\n#include <stan/math/opencl/copy.hpp>\n#include <stan/math/opencl/multiply.hpp>\n#include <test/unit/math/opencl/kernel_generator/reference_kernel.hpp>\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n#include <algorithm>\n#include <string>\n\nusing Eigen::Matrix;\nusing Eigen::MatrixXd;\nusing Eigen::MatrixXi;\nusing stan::math::matrix_cl;\n\n#define EXPECT_MATRIX_NEAR(A, B, DELTA) \\\n  for (int i = 0; i < A.size(); i++)    \\\n    EXPECT_NEAR(A(i), B(i), DELTA);\n\nTEST(KernelGenerator, addition_test) {\n  std::string kernel_filename = \"binary_operation_addition.cl\";\n  MatrixXd m1(3, 3);\n  m1 << 1, 2.5, 3, 4, 5, 6.3, 7, -8, -9.5;\n  MatrixXd m2(3, 3);\n  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;\n\n  matrix_cl<double> m1_cl(m1);\n  matrix_cl<double> m2_cl(m2);\n\n  auto tmp = m1_cl + m2_cl;\n\n  matrix_cl<double> res_cl;\n  std::string kernel_src = tmp.get_kernel_source_for_evaluating_into(res_cl);\n  stan::test::store_reference_kernel_if_needed(kernel_filename, kernel_src);\n  std::string expected_kernel_src\n      = stan::test::load_reference_kernel(kernel_filename);\n  EXPECT_EQ(expected_kernel_src, kernel_src);\n\n  res_cl = tmp;\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  MatrixXd correct = m1 + m2.cast<double>();\n  EXPECT_MATRIX_NEAR(res, correct, 1e-9);\n}\n\n#define BINARY_OPERATION_TEST(test_name, operation, res_type)          \\\n  TEST(KernelGenerator, test_name) {                                   \\\n    MatrixXd m1(3, 3);                                                 \\\n    m1 << 1, 2.5, 3, 4, 5, 6.3, 7, -8, -9.5;                           \\\n    MatrixXi m2(3, 3);                                                 \\\n    m2 << 1, 100, 1000, 0, -10, -12, 2, -8, 8;                         \\\n                                                                       \\\n    matrix_cl<double> m1_cl(m1);                                       \\\n    matrix_cl<int> m2_cl(m2);                                          \\\n                                                                       \\\n    auto tmp = m1_cl operation m2_cl;                                  \\\n    matrix_cl<res_type> res_cl = tmp;                                  \\\n    Matrix<res_type, -1, -1> res = stan::math::from_matrix_cl(res_cl); \\\n                                                                       \\\n    Matrix<res_type, -1, -1> correct                                   \\\n        = m1.array() operation m2.cast<double>().array();              \\\n    EXPECT_MATRIX_NEAR(res, correct, 1e-9);                            \\\n  }\n\nBINARY_OPERATION_TEST(subtraction_test, -, double);\n\nTEST(KernelGenerator, elt_multiply_test) {\n  MatrixXd m1(3, 3);\n  m1 << 1, 2.5, 3, 4, 5, 6.3, 7, -8, -9.5;\n  MatrixXi m2(3, 3);\n  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;\n\n  matrix_cl<double> m1_cl(m1);\n  matrix_cl<int> m2_cl(m2);\n\n  auto tmp = elt_multiply(m1_cl, m2_cl);\n  matrix_cl<double> res_cl = tmp;\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  MatrixXd correct = m1.array() * m2.cast<double>().array();\n  EXPECT_MATRIX_NEAR(res, correct, 1e-9);\n}\n\nTEST(KernelGenerator, elt_divide_test) {\n  MatrixXd m1(3, 3);\n  m1 << 1, 2.5, 3, 4, 5, 6.3, 7, -8, -9.5;\n  MatrixXi m2(3, 3);\n  m2 << 10, 100, 1000, 1, -10, -12, 2, 4, 8;\n\n  matrix_cl<double> m1_cl(m1);\n  matrix_cl<int> m2_cl(m2);\n  auto tmp = elt_divide(m1_cl, m2_cl);\n  matrix_cl<double> res_cl = tmp;\n\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  MatrixXd correct = m1.array() / m2.cast<double>().array();\n  EXPECT_MATRIX_NEAR(res, correct, 1e-9);\n}\n\nBINARY_OPERATION_TEST(less_than_test, <, bool);\nBINARY_OPERATION_TEST(less_than_or_equal_test, <=, bool);\nBINARY_OPERATION_TEST(greater_than_test, >, bool);\nBINARY_OPERATION_TEST(greater_than_or_equal_test, >=, bool);\nBINARY_OPERATION_TEST(equals_test, ==, bool);\nBINARY_OPERATION_TEST(not_equals_test, !=, bool);\n\nTEST(KernelGenerator, logical_or_test) {\n  Matrix<bool, -1, -1> m1(3, 3);\n  m1 << true, true, true, false, false, true, true, false, false;\n  Matrix<bool, -1, -1> m2(3, 3);\n  m2 << true, false, false, true, false, true, false, true, false;\n\n  matrix_cl<bool> m1_cl(m1);\n  matrix_cl<bool> m2_cl(m2);\n\n  auto tmp = m1_cl || m2_cl;\n  matrix_cl<bool> res_cl = tmp;\n  Matrix<bool, -1, -1> res = stan::math::from_matrix_cl(res_cl);\n\n  Matrix<bool, -1, -1> correct = m1 || m2;\n  EXPECT_MATRIX_NEAR(res, correct, 1e-9);\n}\n\nTEST(KernelGenerator, logical_and_test) {\n  Matrix<bool, -1, -1> m1(3, 3);\n  m1 << true, true, true, false, false, true, true, false, false;\n  Matrix<bool, -1, -1> m2(3, 3);\n  m2 << true, false, false, true, false, true, false, true, false;\n\n  matrix_cl<bool> m1_cl(m1);\n  matrix_cl<bool> m2_cl(m2);\n\n  auto tmp = m1_cl && m2_cl;\n  matrix_cl<bool> res_cl = tmp;\n  Matrix<bool, -1, -1> res = stan::math::from_matrix_cl(res_cl);\n\n  Matrix<bool, -1, -1> correct = m1 && m2;\n  EXPECT_MATRIX_NEAR(res, correct, 1e-9);\n}\n\nTEST(KernelGenerator, binary_operation_multiple_operations) {\n  MatrixXd m1(3, 3);\n  m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n  MatrixXi m2(3, 3);\n  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;\n  MatrixXi m3(3, 3);\n  m3 << 1, 10, 1100, -40, -14, -1, 2, 4, 8;\n\n  matrix_cl<double> m1_cl(m1);\n  matrix_cl<int> m2_cl(m2);\n  matrix_cl<int> m3_cl(m3);\n  auto tmp = m1_cl * 2. - (m2_cl + m3_cl) * 4;\n  matrix_cl<double> res_cl = tmp;\n\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  MatrixXd correct = m1 * 2. - ((m2 + m3) * 4).cast<double>();\n  EXPECT_MATRIX_NEAR(res, correct, 1e-9);\n}\n\nTEST(KernelGenerator, binary_operation_multiple_operations_accepts_lvalue) {\n  MatrixXd m1(3, 3);\n  m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n  MatrixXi m2(3, 3);\n  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;\n  MatrixXi m3(3, 3);\n  m3 << 1, 10, 1100, -40, -14, -1, 2, 4, 8;\n\n  matrix_cl<double> m1_cl(m1);\n  matrix_cl<int> m2_cl(m2);\n  matrix_cl<int> m3_cl(m3);\n  auto tmp = (m2_cl + m3_cl) * 4;\n  auto tmp2 = m1_cl * 2. - tmp;\n  matrix_cl<double> res_cl = tmp2;\n\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  MatrixXd correct = m1 * 2. - ((m2 + m3) * 4).cast<double>();\n  EXPECT_MATRIX_NEAR(res, correct, 1e-9);\n}\n\nTEST(KernelGenerator, multiplication_with_scalar_test) {\n  MatrixXd m1(3, 3);\n  m1 << 1, 2.5, 3, 4, 5, 6.3, 7, -8, -9.5;\n  MatrixXd m2(3, 3);\n  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;\n\n  matrix_cl<double> m1_cl(m1);\n  matrix_cl<double> m2_cl(m2);\n\n  auto tmp = m1_cl * 2;\n  matrix_cl<double> res_cl = tmp;\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  EXPECT_MATRIX_NEAR(res, (m1.array() * 2).matrix().eval(), 1e-9);\n\n  auto tmp2 = 2 * m1_cl;\n  matrix_cl<double> res2_cl = tmp2;\n  MatrixXd res2 = stan::math::from_matrix_cl(res2_cl);\n\n  MatrixXd correct = m1.array() * 2;\n  EXPECT_MATRIX_NEAR(res2, correct, 1e-9);\n}\n\nTEST(KernelGenerator, matrix_multiplication_in_expression_test) {\n  MatrixXd m1(3, 3);\n  m1 << 1, 2.5, 3, 4, 5, 6.3, 7, -8, -9.5;\n  MatrixXd m2(3, 3);\n  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;\n\n  matrix_cl<double> m1_cl(m1);\n  matrix_cl<double> m2_cl(m2);\n\n  auto tmp = ((m1_cl - 2) * (m2_cl + 3)) - 1;\n  matrix_cl<double> res_cl = tmp;\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  MatrixXd correct\n      = ((m1.array() - 2.).matrix() * (m2.array() + 3.).matrix()).array() - 1.;\n  EXPECT_MATRIX_NEAR(res, correct, 1e-9);\n}\n\nTEST(KernelGenerator, reuse_expression_simple) {\n  MatrixXd m1(3, 3);\n  m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n  MatrixXd m2(3, 3);\n  m2 << 10, 100, 1000, 0.1, -10, -12, 2, 4, 8;\n\n  matrix_cl<double> m1_cl(m1);\n  matrix_cl<double> m2_cl(m2);\n  auto tmp = stan::math::elt_divide(m1_cl, m2_cl);\n  auto tmp2 = stan::math::elt_multiply(tmp, tmp);\n  matrix_cl<double> res_cl;\n  std::string kernel_src = tmp2.get_kernel_source_for_evaluating_into(res_cl);\n  // if the expression is correctly reused, division will only occur once in the\n  // kernel\n  EXPECT_EQ(1, std::count(kernel_src.begin(), kernel_src.end(), '/'));\n  res_cl = tmp2;\n\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  auto tmp_eig = m1.array() / m2.array();\n  MatrixXd res_eig = tmp_eig * tmp_eig;\n\n  EXPECT_MATRIX_NEAR(res_eig, res, 1e-9);\n}\n\n// Shows subexpressions tmp and tmp2 are reused in the kernel\nTEST(KernelGenerator, reuse_expression_complicated) {\n  std::string kernel_filename = \"binary_operation_reuse_expression.cl\";\n  MatrixXd m1(3, 3);\n  m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n  MatrixXd m2(3, 3);\n  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;\n\n  matrix_cl<double> m1_cl(m1);\n  matrix_cl<double> m2_cl(m2);\n  auto tmp = m1_cl + m2_cl;\n  auto tmp2 = stan::math::elt_divide(stan::math::elt_multiply(tmp, tmp), m1_cl);\n  auto tmp3 = stan::math::elt_multiply(stan::math::elt_divide(tmp, tmp2), tmp2);\n  matrix_cl<double> res_cl;\n  std::string kernel_src = tmp3.get_kernel_source_for_evaluating_into(res_cl);\n  stan::test::store_reference_kernel_if_needed(kernel_filename, kernel_src);\n  std::string expected_kernel_src\n      = stan::test::load_reference_kernel(kernel_filename);\n  EXPECT_EQ(expected_kernel_src, kernel_src);\n\n  res_cl = tmp3;\n\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  auto tmp_eig = m1.array() + m2.array();\n  MatrixXd tmp2_eig = (tmp_eig * tmp_eig).array() / m1.array();\n  MatrixXd tmp3_eig\n      = (tmp_eig.array() / tmp2_eig.array()).array() * tmp2_eig.array();\n\n  EXPECT_MATRIX_NEAR(tmp3_eig, res, 1e-9);\n}\n\n#endif\n", "meta": {"hexsha": "087c843139a160f5d55ee423c2a961750567c938", "size": 9342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/opencl/kernel_generator/binary_operation_test.cpp", "max_stars_repo_name": "tiagocabaco/math", "max_stars_repo_head_hexsha": "1b300c592b680fbfde289f08dc75d1da9c61901d", "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/opencl/kernel_generator/binary_operation_test.cpp", "max_issues_repo_name": "tiagocabaco/math", "max_issues_repo_head_hexsha": "1b300c592b680fbfde289f08dc75d1da9c61901d", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/opencl/kernel_generator/binary_operation_test.cpp", "max_forks_repo_name": "tiagocabaco/math", "max_forks_repo_head_hexsha": "1b300c592b680fbfde289f08dc75d1da9c61901d", "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.8943661972, "max_line_length": 80, "alphanum_fraction": 0.6149646757, "num_tokens": 3243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5178341179834159}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2011 Gael Guennebaud <g.gael@free.fr>\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#define EIGEN_NO_DEBUG_SMALL_PRODUCT_BLOCKS\n#include \"sparse_solver.h\"\n\n#include <Eigen/CholmodSupport>\n\ntemplate<typename T> void test_cholmod_T()\n{\n  CholmodDecomposition<SparseMatrix<T>, Lower> g_chol_colmajor_lower; g_chol_colmajor_lower.setMode(CholmodSupernodalLLt);\n  CholmodDecomposition<SparseMatrix<T>, Upper> g_chol_colmajor_upper; g_chol_colmajor_upper.setMode(CholmodSupernodalLLt);\n  CholmodDecomposition<SparseMatrix<T>, Lower> g_llt_colmajor_lower;  g_llt_colmajor_lower.setMode(CholmodSimplicialLLt);\n  CholmodDecomposition<SparseMatrix<T>, Upper> g_llt_colmajor_upper;  g_llt_colmajor_upper.setMode(CholmodSimplicialLLt);\n  CholmodDecomposition<SparseMatrix<T>, Lower> g_ldlt_colmajor_lower; g_ldlt_colmajor_lower.setMode(CholmodLDLt);\n  CholmodDecomposition<SparseMatrix<T>, Upper> g_ldlt_colmajor_upper; g_ldlt_colmajor_upper.setMode(CholmodLDLt);\n  \n  CholmodSupernodalLLT<SparseMatrix<T>, Lower> chol_colmajor_lower;\n  CholmodSupernodalLLT<SparseMatrix<T>, Upper> chol_colmajor_upper;\n  CholmodSimplicialLLT<SparseMatrix<T>, Lower> llt_colmajor_lower;\n  CholmodSimplicialLLT<SparseMatrix<T>, Upper> llt_colmajor_upper;\n  CholmodSimplicialLDLT<SparseMatrix<T>, Lower> ldlt_colmajor_lower;\n  CholmodSimplicialLDLT<SparseMatrix<T>, Upper> ldlt_colmajor_upper;\n\n  check_sparse_spd_solving(g_chol_colmajor_lower);\n  check_sparse_spd_solving(g_chol_colmajor_upper);\n  check_sparse_spd_solving(g_llt_colmajor_lower);\n  check_sparse_spd_solving(g_llt_colmajor_upper);\n  check_sparse_spd_solving(g_ldlt_colmajor_lower);\n  check_sparse_spd_solving(g_ldlt_colmajor_upper);\n  \n  check_sparse_spd_solving(chol_colmajor_lower);\n  check_sparse_spd_solving(chol_colmajor_upper);\n  check_sparse_spd_solving(llt_colmajor_lower);\n  check_sparse_spd_solving(llt_colmajor_upper);\n  check_sparse_spd_solving(ldlt_colmajor_lower);\n  check_sparse_spd_solving(ldlt_colmajor_upper);\n\n  check_sparse_spd_determinant(chol_colmajor_lower);\n  check_sparse_spd_determinant(chol_colmajor_upper);\n  check_sparse_spd_determinant(llt_colmajor_lower);\n  check_sparse_spd_determinant(llt_colmajor_upper);\n  check_sparse_spd_determinant(ldlt_colmajor_lower);\n  check_sparse_spd_determinant(ldlt_colmajor_upper);\n}\n\nvoid test_cholmod_support()\n{\n  CALL_SUBTEST_1(test_cholmod_T<double>());\n  CALL_SUBTEST_2(test_cholmod_T<std::complex<double> >());\n}\n", "meta": {"hexsha": "a7eda28f79e1bc161f4b482cdd8faeb8299dfae9", "size": 2686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/test/cholmod_support.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/test/cholmod_support.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/test/cholmod_support.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 46.3103448276, "max_line_length": 122, "alphanum_fraction": 0.8339538347, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859596, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5178341179834159}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2021 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_MATH_EXPRESSION_MATH_HPP\n#define CRYPTO3_MATH_EXPRESSION_MATH_HPP\n\n#ifndef CRYPTO3_MATH_EXPRESSION_HPP\n#error \"math.hpp must not be included directly!\"\n#endif\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace math {\n            namespace expressions {\n                namespace detail {\n                    namespace math {\n\n                        /// @brief Sign function\n                        template <typename T>\n                        T sgn(T x) {\n                            return (T{0} < x) - (x < T{0});\n                        }\n\n                        /// @brief isnan function with adjusted return type\n                        template <typename T>\n                        T isnan(T x) {\n                            return std::isnan(x);\n                        }\n\n                        /// @brief isinf function with adjusted return type\n                        template <typename T>\n                        T isinf(T x) {\n                            return std::isinf(x);\n                        }\n\n                        /// @brief Convert radians to degrees\n                        template <typename T>\n                        T deg(T x) {\n                            return x * boost::math::constants::radian<T>();\n                        }\n\n                        /// @brief Convert degrees to radians\n                        template <typename T>\n                        T rad(T x) {\n                            return x * boost::math::constants::degree<T>();\n                        }\n\n                        /// @brief unary plus\n                        template <typename T>\n                        T plus(T x) {\n                            return x;\n                        }\n\n                        /// @brief binary plus\n                        template <typename T>\n                        T plus(T x, T y) {\n                            return x + y;\n                        }\n\n                        /// @brief unary minus\n                        template <typename T>\n                        T minus(T x) {\n                            return -x;\n                        }\n\n                        /// @brief binary minus\n                        template <typename T>\n                        T minus(T x, T y) {\n                            return x - y;\n                        }\n\n                        /// @brief multiply\n                        template <typename T>\n                        T multiplies(T x, T y) {\n                            return x * y;\n                        }\n\n                        /// @brief divide\n                        template <typename T>\n                        T divides(T x, T y) {\n                            return x / y;\n                        }\n\n                        /// @brief unary not\n                        template <typename T>\n                        T unary_not(T x) {\n                            return !x;\n                        }\n\n                        /// @brief logical and\n                        template <typename T>\n                        T logical_and(T x, T y) {\n                            return x && y;\n                        }\n\n                        /// @brief logical or\n                        template <typename T>\n                        T logical_or(T x, T y) {\n                            return x || y;\n                        }\n\n                        /// @brief less\n                        template <typename T>\n                        T less(T x, T y) {\n                            return x < y;\n                        }\n\n                        /// @brief less equals\n                        template <typename T>\n                        T less_equals(T x, T y) {\n                            return x <= y;\n                        }\n\n                        /// @brief greater\n                        template <typename T>\n                        T greater(T x, T y) {\n                            return x > y;\n                        }\n\n                        /// @brief greater equals\n                        template <typename T>\n                        T greater_equals(T x, T y) {\n                            return x >= y;\n                        }\n\n                        /// @brief equals\n                        template <typename T>\n                        T equals(T x, T y) {\n                            return x == y;\n                        }\n\n                        /// @brief not equals\n                        template <typename T>\n                        T not_equals(T x, T y) {\n                            return x != y;\n                        }\n\n                    } // namespace math\n                }    // namespace detail    \n            }    // namespace expressions\n        }    // namespace math\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_MATH_EXPRESSION_MATH_HPP", "meta": {"hexsha": "8fbfcf62c6c5f50caaeba5e0ff91fe070e4503c5", "size": 6329, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/math/expressions/math.hpp", "max_stars_repo_name": "NilFoundation/fft", "max_stars_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nil/crypto3/math/expressions/math.hpp", "max_issues_repo_name": "NilFoundation/fft", "max_issues_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-12-19T23:19:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T20:10:27.000Z", "max_forks_repo_path": "include/nil/crypto3/math/expressions/math.hpp", "max_forks_repo_name": "NilFoundation/crypto3-math", "max_forks_repo_head_hexsha": "9351ff8c0f1a75022457e82475b0eba2447ceecc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0116959064, "max_line_length": 81, "alphanum_fraction": 0.3923210618, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5178341179834159}}
{"text": "#pragma once\n\n#include <iostream>\n\n#include <Eigen/Dense>\n\n//The geometry of the grid\nenum Geometry\n{\n    Triangular = 0,\n    Orthogonal = 1,\n    Hexagonal = 2\n};\n\nstd::ostream& operator<<(std::ostream& os, const Geometry& g);\n\n//The orientation of the grid\nenum Orientation\n{\n    Horizontal = 0,\n    Vertical = 1\n};\n\nstd::ostream& operator<<(std::ostream& os, const Orientation& o);\n\n//this is a flat mesh\n//i will principaly use it to set lens array and checkerboard (if needed ;) )\ntemplate<int Dimension>\nstruct PolygonMesh\n{\n    Geometry geometry;\n    Orientation orientation;\n    std::array<int,2> dimensions;\n    double edge_length;  //the mean distance between two vertices\n\n    PolygonMesh(const Geometry g = Triangular\n              , const Orientation o = Horizontal\n              , const std::array<int,2>& d = std::array<int,2>{0,0}\n              , const double e = 0.0\n        )\n    : geometry(g), dimensions(d), edge_length(e)\n    {}\n\n    ~PolygonMesh(){};\n\n    Eigen::Matrix<double,Dimension,1> vertex(const int col, const int row) const;\n    // Eigen::Matrix<double,Dimension,1> vertex(const int i) const;\n\n    // return edge parameters linking two nodes (note by indices)\n    // edge(const int i1, const int i2) const;\n};\n\nusing PolygonMesh2D = PolygonMesh<2>;\nusing PolygonMesh3D = PolygonMesh<3>;\n\ntemplate<int Dimension>\nEigen::Matrix<double,Dimension,1> PolygonMesh<Dimension>::vertex(const int col, const int row) const\n{\n    // if ( col < 0 or col >= width )\n    //     throw(std::out_of_range( boost::str(boost::format(\"PolygonMesh<Dimension>::vertex: wrong col index (%1%)\")%col)) );\n    // if ( row < 0 or row >= height )\n    //     throw(std::out_of_range( boost::str(boost::format(\"PolygonMesh<Dimension>::vertex: wrong row index (%1%)\")%row)) );\n\n    Eigen::Matrix<double,Dimension,1> p = Eigen::Matrix<double,Dimension,1>::Zero();\n\n    if (geometry == Triangular)\n    {\n        std::cerr << \"Error: PolygonMesh::vertex: Not implemented.\" << std::endl;\n        if (orientation == Horizontal)\n        {\n            return p;\n        }\n        else if (orientation == Vertical)\n        {\n            return p;\n        }\n        else\n            std::cerr << \"Error: PolygonMesh::vertex: wrong orientation value (\" << orientation << \").\"<< std::endl;\n\n    }\n    else if (geometry == Orthogonal)\n    {\n        p.x() = edge_length * (double(col) + double(row));\n        p.y() = edge_length * (double(row) + double(col));\n    }\n    else if (geometry == Hexagonal)\n    {\n        double val = 0.0;\n        if (orientation == Horizontal)\n        {\n            if (row%2 == 0)\n                val = 0.5;\n\n            p.x() =  (double(col) + val) * edge_length;\n            p.y() =  double(row) * edge_length * std::sin(M_PI / 3.0);\n\n            return p;\n\n        }\n        if (orientation == Vertical)\n        {\n            if (col%2 == 0)\n                val = 0.5;\n\n            p.x() = double(col) * edge_length * std::sin(M_PI / 3.0);\n            p.y() = (double(row) + val) * edge_length;\n\n            return p;\n        }\n        else\n            std::cerr << \"Error: PolygonMesh::vertex: wrong orientation value (\" << orientation << \").\"<< std::endl;\n    }    \n    else\n        std::cerr << \"Error: PolygonMesh::vertex: wrong geometry value (\" << geometry << \").\"<< std::endl;\n\n    return {};\n}\n\ntemplate<int Dimension>\nstd::ostream& operator<<(std::ostream& os, const PolygonMesh<Dimension>& m)\n{\n    os << \"geometry: \" << m.geometry << \"\\n\";\n    os << \"orientation: \" << m.orientation << \"\\n\";\n    os << \"dimensions: [\" << m.dimensions[0] << \", \" << m.dimensions[1] << \"]\\n\"; \n    os << \"edges length: \" << m.edge_length;\n\n    return os;\n}\n", "meta": {"hexsha": "06eb1a045588966d8d54465ecc43e6b532da83a1", "size": 3668, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geometry/mesh.hpp", "max_stars_repo_name": "charlybigoud/kidocam", "max_stars_repo_head_hexsha": "5cf2d59194a48897b35f0e3c8e3cea39b748c3d0", "max_stars_repo_licenses": ["MIT"], "max_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/mesh.hpp", "max_issues_repo_name": "charlybigoud/kidocam", "max_issues_repo_head_hexsha": "5cf2d59194a48897b35f0e3c8e3cea39b748c3d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geometry/mesh.hpp", "max_forks_repo_name": "charlybigoud/kidocam", "max_forks_repo_head_hexsha": "5cf2d59194a48897b35f0e3c8e3cea39b748c3d0", "max_forks_repo_licenses": ["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.4341085271, "max_line_length": 126, "alphanum_fraction": 0.5684296619, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.517834107975787}}
{"text": "/* \n * A header-only version of RedSVD\n * \n * Copyright (c) 2014 Nicolas Tessore\n * \n * based on RedSVD\n * \n * Copyright (c) 2010 Daisuke Okanohara\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 authors nor the names of its contributors\n *    may be uses to endorse or promote products derived from this\n *    software without specific prior written permission.\n *\n *    Minor modifications by Luca Formaggia.\n */\n\n#ifndef REDSVD_MODULE_H\n#define REDSVD_MODULE_H\n\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\n#include <cstdlib>\n#include <cmath>\n#include <random>\n\nnamespace RedSVD\n{\n  //! It generates a (pseudo) x and y extracted from a (pseudo) random Gaussian distribution\n  /*!\n   * It uses the Box-Muller transform, see \n   * [this Wikipedia page](https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform),\n   * to generate a couple of variables from a normally distribution\n   * with zero mean and unitary variance.  \n   *\n   * This version uses rand() to generate the uniform distribution from\n   * which the Gaussian one is derived.  It may be changed to implement\n   * the new random distribution.\n   *\n   * \\note Compared with the original version, it is no more used to generate\n   * random Gaussian matrices, since we use the random number generator\n   * of the standard library.\n   */\n  template<typename Scalar>\n  inline void sample_gaussian(Scalar& x, Scalar& y)\n  {\n    using std::sqrt;\n    using std::log;\n    using std::cos;\n    using std::sin;\n\t\t\n    constexpr Scalar PI(3.1415926535897932384626433832795028841971693993751);\n\t\t\n    Scalar v1 = (Scalar)(std::rand() + Scalar(1)) / ((Scalar)RAND_MAX+Scalar(2));\n    Scalar v2 = (Scalar)(std::rand() + Scalar(1)) / ((Scalar)RAND_MAX+Scalar(2));\n    Scalar len = sqrt(Scalar(-2) * log(v1));\n    x = len * cos(Scalar(2) * PI * v2);\n    y = len * sin(Scalar(2) * PI * v2);\n  }\n\n  //! Generates a random Gaussian matrix\n  /*! A matrix whose elements are drawn from Normal distribution with\n   * zero mean and unitary variance.\n   *\n   * \\note Modified from the original code by Luca Formaggia: using standard library random number distribution.\n  */\n  template<typename MatrixType>\n  inline void sample_gaussian(MatrixType& mat)\n  {\n    // generate random seed\n    std::random_device rd{};\n    std::mt19937 gen{rd()};\n    // define the distribution\n    typedef typename MatrixType::Scalar Scalar;\n    std::normal_distribution<Scalar> d;\n\n    typedef typename MatrixType::Index Index;\n          \n    for(Index i = 0; i < mat.rows(); ++i)\n      for(Index j = 0; j < mat.cols(); ++j)\n        mat(i, j)=d(gen);\n  }\n  //! Performs Gram Schmidt on the matrix columns\n  /*!\n   * \\tparam MatrixType An Eigen Dense Matrix\n   * \\param mat The matrix on which to operate. The orthonormalisation is performed in-place\n   * \\param EPS tolerance to discard small columns. Defaulted to 1e-6\n   */\n  template<typename MatrixType>\n  inline void gram_schmidt(MatrixType& mat,\n                           typename MatrixType::Scalar const EPS=1.E-6)\n  {\n    typedef typename MatrixType::Scalar Scalar;\n    typedef typename MatrixType::Index Index;\n\t\t\n    for(Index i = 0; i < mat.cols(); ++i)\n      {\n        // c_i = c_i - sum_{j<i} (c_i * c_j)c_j\n        for(Index j = 0; j < i; ++j)\n          {\n            Scalar r = mat.col(i).dot(mat.col(j));\n            mat.col(i) -= r * mat.col(j);\n          }\n\t\t\t\n        Scalar norm = mat.col(i).norm();\n        // If the norm is too small it means that rank A = i-1\n        // so we can put=0 all columns k with k>= i.\n        if(norm < EPS)\n          {\n            for(Index k = i; k < mat.cols(); ++k)\n              mat.col(k).setZero();\n            return;\n          }\n        // Orhonormalization\n        mat.col(i) /= norm;\n      }\n  }\n\n  //! Performs reduced Singular Value Decomposition\n  /*!\n   * Given a nxm matrix \\f$A\\f$ it computes matrices \\f$U\\f$ (nxk, orthogonal), \\f$\\Sigma\\f$ (kxk, diagonal) and\n   * \\f$V\\f$ (mxk, orthogonal), so that \\f$A^*=U\\Sigma V^T\\f$ is a rank-k matrix approximation of \\f$A\\f$.\n   * Matrix \\f$\\Sigma\\f$ is returned as vector of size k containing the diagonal elements, which are an approximation\n   * of the first singular values of \\f$A\\f$.\n   *\n   * This algorithm uses is a probabilistic algorithm. More details on this type of algorithms may be found in\n   * <em>Finding structures with randomness:..., Halko, N. and Martinsson, P. G. and Tropp, J. A. (2009)</em>\n   */\n  template<typename My_MatrixType>\n  class RedSVD\n  {\n  public:\n    typedef My_MatrixType MatrixType;\n    typedef typename MatrixType::Scalar Scalar;\n    typedef typename MatrixType::Index Index;\n    typedef typename Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> DenseMatrix;\n    typedef typename Eigen::Matrix<Scalar, Eigen::Dynamic, 1> ScalarVector;\n    //! Default constructor\n    RedSVD()=default;\n\n    //! A may be a dense or sparse Eigen matrix.\n    /*!\n      Here rank is taken as min between n. rows and n. columns\n      No great memory savings.\n    */\n    RedSVD(const MatrixType& A)\n    {\n      int r = (A.rows() < A.cols()) ? A.rows() : A.cols();\n      compute(A, r);\n    }\n    //! Specifying the rank\n    /*!\n      \\param A a sparse or dense Eigen matrix\n      \\param rank the desired rank for the reduced decomposition\n    */\n    RedSVD(const MatrixType& A, const Index rank)\n    {\n      compute(A, rank);\n    }\n    /*!\n      \\brief Computes the actual reduced SVD\n      It is automatically called by constructors that take a matrix in input.\n    */\n    void compute(const MatrixType& A, const Index rank)\n    {\n      if(A.cols() == 0 || A.rows() == 0)\n        return;\n\t\t\t\n      Index r = (rank < A.cols()) ? rank : A.cols();\n\t\t\t\n      r = (r < A.rows()) ? r : A.rows();\n\t\t\t\n      // Gaussian Random Matrix for A^T\n      DenseMatrix O(A.rows(), r);\n      sample_gaussian(O);\n\t\t\t\n      // Compute Sample Matrix of A^T\n      DenseMatrix Y = A.transpose() * O;\n\t\t\t\n      // Orthonormalize Y\n      gram_schmidt(Y);\n\t\t\t\n      // Range(B) = Range(A^T)\n      DenseMatrix B = A * Y;\n\t\t\t\n      // Gaussian Random Matrix\n      DenseMatrix P(B.cols(), r);\n      sample_gaussian(P);\n\t\t\t\n      // Compute Sample Matrix of B\n      DenseMatrix Z = B * P;\n\t\t\t\n      // Orthonormalize Z\n      gram_schmidt(Z);\n\t\t\t\n      // Range(C) = Range(B)\n      DenseMatrix C = Z.transpose() * B; \n      // Thin SVD. \t\t\t\n      Eigen::JacobiSVD<DenseMatrix> svdOfC(C, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\t\t\t\n      // C = USV^T\n      // A^* = (Z * U) * S * (Y * V)^T (low rank approx of A).\n      m_matrixU = Z * svdOfC.matrixU();\n      m_vectorS = svdOfC.singularValues();\n      m_matrixV = Y * svdOfC.matrixV();\n    }\n\n    //! Returns matrix U\n    DenseMatrix matrixU() const\n    {\n      return m_matrixU;\n    }\n    //! Returns vector with first k singular values    \n    ScalarVector singularValues() const\n    {\n      return m_vectorS;\n    }\n    //! Returns matrix V\n    DenseMatrix matrixV() const\n    {\n      return m_matrixV;\n    }\n\t\t\n  private:\n    DenseMatrix m_matrixU;\n    ScalarVector m_vectorS;\n    DenseMatrix m_matrixV;\n  };\n\n  //! Like RedSVD but for symmetric matrices\n  /*!\n   * In this case, \\f$U=V\\f$ is the matrix with the first (approximate) eigenvectors of \\f$A\\f$ and \\f$\\Sigma\\f$ contains\n   * the (approximate) first k eigenvalues.\n   */\n  template<typename _MatrixType>\n  class RedSymEigen\n  {\n  public:\n    typedef _MatrixType MatrixType;\n    typedef typename MatrixType::Scalar Scalar;\n    typedef typename MatrixType::Index Index;\n    typedef typename Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> DenseMatrix;\n    typedef typename Eigen::Matrix<Scalar, Eigen::Dynamic, 1> ScalarVector;\n\t\t\n    RedSymEigen()=default;\n\t\t\n    RedSymEigen(const MatrixType& A)\n    {\n      int r = (A.rows() < A.cols()) ? A.rows() : A.cols();\n      compute(A, r);\n    }\n\t\t\n    RedSymEigen(const MatrixType& A, const Index rank)\n    {\n      compute(A, rank);\n    }  \n\t\t\n    void compute(const MatrixType& A, const Index rank)\n    {\n      if(A.cols() == 0 || A.rows() == 0)\n        return;\n\t\t\t\n      Index r = (rank < A.cols()) ? rank : A.cols();\n\t\t\t\n      r = (r < A.rows()) ? r : A.rows();\n\t\t\t\n      // Gaussian Random Matrix\n      DenseMatrix O(A.rows(), r);\n      sample_gaussian(O);\n\t\t\t\n      // Compute Sample Matrix of A\n      DenseMatrix Y = A.transpose() * O;\n\t\t\t\n      // Orthonormalize Y\n      gram_schmidt(Y);\n\t\t\t\n      DenseMatrix B = Y.transpose() * A * Y;\n      Eigen::SelfAdjointEigenSolver<DenseMatrix> eigenOfB(B);\n\t\t\t\n      m_eigenvalues = eigenOfB.eigenvalues();\n      m_eigenvectors = Y * eigenOfB.eigenvectors();\n    }\n    //! Returns a vector with the first k approximate eigenvalues\n    /*!\n      They are the diagonal elements of \\f$\\Sigma\\f$.\n     */\n    ScalarVector eigenvalues() const\n    {\n      return m_eigenvalues;\n    }\n    //! Returns a nxk orthogonal matrix whose columns are the first k approximate eigenvectors\n    DenseMatrix eigenvectors() const\n    {\n      return m_eigenvectors;\n    }\n\t\t\n  private:\n    ScalarVector m_eigenvalues;\n    DenseMatrix m_eigenvectors;\n  };\n\n  //! Performs the principal component analysis\n  /*!\n   * It works by contructing a RedSVD object to perform an low-rank SVD decomposition and then\n   * it returns the nxk matrix \\f$V\\f$ that represent the components of the PCA and the nxk matrix\n   * \\f$U\\Sigma\\f$, which are the scores.\n   */\n  template<typename _MatrixType>\n  class RedPCA\n  {\n  public:\n    typedef _MatrixType MatrixType;\n    typedef typename MatrixType::Scalar Scalar;\n    typedef typename MatrixType::Index Index;\n    typedef typename Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> DenseMatrix;\n    typedef typename Eigen::Matrix<Scalar, Eigen::Dynamic, 1> ScalarVector;\n\t\t\n    RedPCA() {}\n\t\t\n    RedPCA(const MatrixType& A)\n    {\n      int r = (A.rows() < A.cols()) ? A.rows() : A.cols();\n      compute(A, r);\n    }\n\t\t\n    RedPCA(const MatrixType& A, const Index rank)\n    {\n      compute(A, rank);\n    }  \n\t\t\n    void compute(const DenseMatrix& A, const Index rank)\n    {\n      RedSVD<MatrixType> redsvd(A, rank);\n\t\t\t\n      ScalarVector S = redsvd.singularValues();\n\t\t\t\n      m_components = redsvd.matrixV();\n      m_scores = redsvd.matrixU() * S.asDiagonal();\n    }\n    //! Returns the components\n    DenseMatrix components() const\n    {\n      return m_components;\n    }\n    //! Returns the scores\t\t\n    DenseMatrix scores() const\n    {\n      return m_scores;\n    }\n\t\t\n  private:\n    DenseMatrix m_components;\n    DenseMatrix m_scores;\n  };\n}\n\n#endif\n", "meta": {"hexsha": "847fd8f3838444ac3f5f621beb81170ddc66c9e4", "size": 11004, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/RedSVD/RedSVD.hpp", "max_stars_repo_name": "lformaggia/redsvd-h", "max_stars_repo_head_hexsha": "fe10907511bdd6e3c589ad499b2e40461e62c94f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-16T23:04:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T23:04:23.000Z", "max_issues_repo_path": "include/RedSVD/RedSVD.hpp", "max_issues_repo_name": "lformaggia/redsvd-h", "max_issues_repo_head_hexsha": "fe10907511bdd6e3c589ad499b2e40461e62c94f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/RedSVD/RedSVD.hpp", "max_forks_repo_name": "lformaggia/redsvd-h", "max_forks_repo_head_hexsha": "fe10907511bdd6e3c589ad499b2e40461e62c94f", "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.7405405405, "max_line_length": 121, "alphanum_fraction": 0.6272264631, "num_tokens": 2900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.517833528665996}}
{"text": "\n#include \"datatypes/heap.h\"\n#include \"segmentation/isf.h\"\n\n#include <Eigen/Dense>\n\n#include <queue>\n\nusing namespace segm;\n\n\nISF &ISF::operator=(const ISF &isf)\n{\n    ForestingTransform::operator=(isf);\n    alpha = isf.getAlpha();\n    beta = isf.getBeta();\n    return (*this);\n}\n\n\nvoid ISF::run(int n_superpixels, int iterations)\n{\n    Image<int> markers(w, h);\n    for (int ite = 0; ite < iterations; ite++)\n    {\n        if (ite == 0)\n            markers = sample(n_superpixels);\n        else\n            markers = computeCentroids();\n\n        ForestingTransform::run(markers);\n    }\n}\n\n\nvoid ISF::conquer(int x, int y, int adj_x, int adj_y)\n{\n    if (valid(adj_x, adj_y) && !heap.is(adj_x, adj_y, heap.black))\n    {\n        int p = index(x, y);\n        int q = index(adj_x, adj_y);\n        float arc_weight = cost(p) + powf(alpha * l2norm(root(p), q), beta) + 1.0f;\n        if (arc_weight < cost(q))\n        {\n            cost(q)  = arc_weight;\n            root(q)  = root(p);\n            pred(q)  = p;\n            label(q) = label(p);\n\n            if (heap.is(q, heap.gray))\n                heap.goUp(adj_x, adj_y);\n            else\n                heap.insert(q);\n        }\n    }\n}\n\n\nImage<int> ISF::sample(int sample_size)\n{\n    auto step_x = static_cast<int>(w / round(sqrt(sample_size)));\n    auto step_y = static_cast<int>(h / round(sqrt(sample_size)));\n\n    if (step_x < 1.0f || step_y < 1.0f)\n        std::runtime_error(\"Sample size is too big., ISF::gridSample\");\n\n    Image<int> samples(w, h);\n    samples.fill(-1);\n\n    int label = 0;\n    for (int x = step_x / 2; x < w; x += step_x) {\n        for (int y = step_y / 2; y < h; y += step_y) {\n            samples(x, y) = label;\n            label++;\n        }\n    }\n\n    return samples;\n}\n\n\nImage<int> ISF::computeCentroids()\n{\n    int n_sup = label.max() + 1;\n\n    /* 0 = x-axis, 1 = y-axis, 2 = count */\n    Eigen::MatrixXi centroids = Eigen::MatrixXi::Constant(n_sup, 3, 0);\n\n    for (int y = 0; y < h; y++) {\n        for (int x = 0; x < w; x++) {\n            int lb = label(x, y);\n            centroids(lb, 0) += x;\n            centroids(lb, 1) += y;\n            centroids(lb, 2) += 1;\n        }\n    }\n\n    Image<int> samples(w, h);\n    samples.fill(-1);\n    for (int lb = 0; lb < centroids.rows(); lb++)\n    {\n        int x = centroids(lb, 0) /= centroids(lb, 2);\n        int y = centroids(lb, 1) /= centroids(lb, 2);\n        if (label(x, y) == lb)\n            samples(x, y) = lb;\n        else {\n            Pixel p = findNearest(x, y, lb);\n            samples(p.x, p.y) = lb;\n        }\n    }\n\n    return samples;\n}\n\n\nISF::Pixel ISF::findNearest(int x, int y, int _label)\n{\n    Pixel p(x, y);\n    std::queue<Pixel> Q;\n    while (label(p.x, p.y) != _label)\n    {\n        if (valid(p.x + 1, p.y))\n            Q.push(Pixel(p.x + 1, p.y));\n\n        if (valid(p.x, p.y + 1))\n            Q.push(Pixel(p.x, p.y + 1 ));\n\n        if (valid(p.x - 1, p.y))\n            Q.push(Pixel(p.x - 1, p.y));\n\n        if (valid(p.x, p.y - 1))\n            Q.push(Pixel(p.x, p.y - 1));\n\n        p = Q.front();\n        Q.pop();\n    }\n\n    return p;\n}", "meta": {"hexsha": "c5ad4ea7865087181f404d9cafe32407ebaea026", "size": 3092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/segmentation/isf.cpp", "max_stars_repo_name": "JoOkuma/segm", "max_stars_repo_head_hexsha": "6d3ea82c4ee6dcc94c26db8e9d03392397646449", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-27T13:00:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-27T13:00:31.000Z", "max_issues_repo_path": "src/segmentation/isf.cpp", "max_issues_repo_name": "JoOkuma/segm", "max_issues_repo_head_hexsha": "6d3ea82c4ee6dcc94c26db8e9d03392397646449", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/segmentation/isf.cpp", "max_forks_repo_name": "JoOkuma/segm", "max_forks_repo_head_hexsha": "6d3ea82c4ee6dcc94c26db8e9d03392397646449", "max_forks_repo_licenses": ["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.2446043165, "max_line_length": 83, "alphanum_fraction": 0.4857697283, "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5178215302678643}}
{"text": "#pragma once\n\n#include <cmath>\n#include <vector>\n#include <Eigen/Dense>\n\n/* NOTE: The following field layout:\n   +-------+ (fW/2,fH/2) <- Enemy goal keeper\n   |       |\n   | (0,0) |\n   +---+---+ (fw/2,0)\n   |       |\n   |       |\n   +-------+ (fw/2,-fH/2) <- Our goal keeper */\n\n    static const int NUM_OF_IMU_DATA = 6;\n    static const double FIRST_TIME = 0.01;\n    static const double DT = 0.01;\n    static const double GRAV_ACC = 9.80665;\n    static const double TO_DEG = 57.2958;\n    static const double IMU_LPF = 0.07;\n    static const std::vector<double> coordinateModifyFactor{ 1.0, -1.0, 1.0, -1.0, 1.0, -1.0 };\n    static const std::vector<double> BIAS{ 0, 0, 0, 0, 0, 0 };\n\n    static const std::vector<double> INIT_P{ 0.0001, 0.0001, 0.0001, 0.0001 };\n    static const std::vector<double> INIT_Q{ 0.01, 0.01, 0.01, 0.01 };\n    static const std::vector<double> INIT_R{ 1.0, 1.0, 10.0 };\n    static const std::vector<double> INIT_X{ 0.0, 0.0, 0.0, 1.0 };\n    static const int SIZE_VECTOR_X = 4;\n    static const int SIZE_VECTOR_Y = 3;\n\n/**\n * localization.hh\n *\n * Allow the player to update and track localization related information.\n **/\nclass Localization{\n  private:\n    Eigen::Matrix<double, SIZE_VECTOR_X, 1> xHat;\n    Eigen::Matrix<double, SIZE_VECTOR_X, 1> xHatMinus;\n    Eigen::Matrix<double, SIZE_VECTOR_Y, 1> y;\n    Eigen::Matrix<double, SIZE_VECTOR_X, 1> f;\n    Eigen::Matrix<double, SIZE_VECTOR_Y, 1> h;\n    Eigen::Matrix<double, SIZE_VECTOR_X, SIZE_VECTOR_X> A;\n    Eigen::Matrix<double, SIZE_VECTOR_X, SIZE_VECTOR_X> AT;\n    Eigen::Matrix<double, SIZE_VECTOR_X, SIZE_VECTOR_Y> C;\n    Eigen::Matrix<double, SIZE_VECTOR_Y, SIZE_VECTOR_X> CT;\n    Eigen::Matrix<double, SIZE_VECTOR_X, SIZE_VECTOR_Y> g;\n    Eigen::Matrix<double, SIZE_VECTOR_X, SIZE_VECTOR_X> P;\n    Eigen::Matrix<double, SIZE_VECTOR_X, SIZE_VECTOR_X> PMinus;\n    Eigen::Matrix<double, SIZE_VECTOR_X, SIZE_VECTOR_X> Q;\n    Eigen::Matrix<double, SIZE_VECTOR_Y, SIZE_VECTOR_Y> R;\n    Eigen::Matrix<double, SIZE_VECTOR_X, SIZE_VECTOR_X> I;\n    std::vector<double> lpf;\n\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    /**\n     * Localization()\n     *\n     * Initialize the localization system.\n     **/\n    Localization();\n\n    /**\n     * ~Localization()\n     *\n     * De-initialize the localization system and free up resources.\n     **/\n    ~Localization();\n\n    void update();\n\n  private:\n    void prediction(std::vector<double>& imu);\n\n    void filter(std::vector<double>& imu);\n\n    void normXHat();\n\n    static Eigen::Matrix<double, 3, 3> getDCM(Eigen::Matrix<double, SIZE_VECTOR_X, 1>& x);\n\n    static Eigen::Matrix<double, 3, 1> getEuler(Eigen::Matrix<double, 3, 3>& dcm);\n\n    static Eigen::Matrix<double, 3, 1> getEulerFromAccData(std::vector<double>& imu);\n};\n", "meta": {"hexsha": "27925351299a3f23c5f386e03ed7ea045d79e690", "size": 2759, "ext": "hh", "lang": "C++", "max_stars_repo_path": "source/src/localization/localization.hh", "max_stars_repo_name": "Dr-MunirShah/black-sheep", "max_stars_repo_head_hexsha": "e908203d9516e01f90f4ed4c796cf4143d0df0c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-07-25T10:06:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T06:00:51.000Z", "max_issues_repo_path": "source/src/localization/localization.hh", "max_issues_repo_name": "Dr-MunirShah/black-sheep", "max_issues_repo_head_hexsha": "e908203d9516e01f90f4ed4c796cf4143d0df0c0", "max_issues_repo_licenses": ["MIT"], "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/src/localization/localization.hh", "max_forks_repo_name": "Dr-MunirShah/black-sheep", "max_forks_repo_head_hexsha": "e908203d9516e01f90f4ed4c796cf4143d0df0c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-31T23:32:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-31T23:32:02.000Z", "avg_line_length": 31.3522727273, "max_line_length": 95, "alphanum_fraction": 0.6491482421, "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5178215248407456}}
{"text": "#ifndef LIBRARY_INCLUDE_H\n#define LIBRARY_INCLUDE_H\n/// \\file\n/// \\brief Include libraries that are commonly used in the package\n\n// ROS\n#include \"ros/ros.h\"\n\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n\n// Sophus\n#include \"sophus/se3.hpp\"\n#include \"sophus/so3.hpp\"\n\ntypedef Sophus::SE3d SE3;\ntypedef Sophus::SO3d SO3;\n\n// OpenCV\n#include <opencv2/core/core.hpp>\n#include <opencv2/opencv.hpp>\n\n#endif", "meta": {"hexsha": "55bb7e224704b79df1f6d8f81af581feeb3a837e", "size": 436, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/stereo_visual_slam_main/library_include.hpp", "max_stars_repo_name": "shangzhouye/stereo-visual-slam", "max_stars_repo_head_hexsha": "23abdb95b08a69e0ae630d4f4e6c3a64248b1284", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2020-03-25T02:36:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:20:51.000Z", "max_issues_repo_path": "include/stereo_visual_slam_main/library_include.hpp", "max_issues_repo_name": "ujasmandavia/STEREO-VISUAL-SLAM", "max_issues_repo_head_hexsha": "cb34d91319f4f03c3b047d12016f40dd9bae6ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-07T20:21:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T17:55:02.000Z", "max_forks_repo_path": "include/stereo_visual_slam_main/library_include.hpp", "max_forks_repo_name": "ujasmandavia/STEREO-VISUAL-SLAM", "max_forks_repo_head_hexsha": "cb34d91319f4f03c3b047d12016f40dd9bae6ec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-10-23T22:58:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T04:13:34.000Z", "avg_line_length": 17.44, "max_line_length": 66, "alphanum_fraction": 0.7339449541, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5178215190649768}}
{"text": "/* =========================================================================\n   Copyright (c) 2012-2014, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n                             -----------------\n               ViennaFEM - The Vienna Finite Element Method Library\n                             -----------------\n\n   Author:     Karl Rupp                          rupp@iue.tuwien.ac.at\n\n   License:    MIT (X11), see file LICENSE in the ViennaFEM base directory\n============================================================================ */\n\n\n// include necessary system headers\n#include <iostream>\n\n// ViennaFEM includes:\n#include \"viennafem/fem.hpp\"\n#include \"viennafem/io/vtk_writer.hpp\"\n\n// ViennaGrid includes:\n#include \"viennagrid/forwards.hpp\"\n#include \"viennagrid/config/default_configs.hpp\"\n#include \"viennagrid/io/netgen_reader.hpp\"\n\n// ViennaData includes:\n#include \"viennadata/api.hpp\"\n\n// ViennaMath includes:\n#include \"viennamath/expression.hpp\"\n\n// Boost.uBLAS includes:\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n\n\n//ViennaCL includes:\n#ifndef VIENNACL_HAVE_UBLAS\n #define VIENNACL_HAVE_UBLAS\n#endif\n\n#include \"viennacl/linalg/cg.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n\n\n/** @brief A tag class used for storing the permittivity (i.e. a cell quantity) with ViennaData */\nstruct permittivity_key\n{\n  // Operator< is required for compatibility with std::map\n  bool operator<(permittivity_key const & /*other*/) const { return false; }\n};\n\nint main()\n{\n  typedef viennagrid::triangular_2d_mesh                                                  DomainType;\n  typedef viennagrid::result_of::segmentation<DomainType>::type                           SegmentationType;\n  typedef SegmentationType::iterator                                                      SegmentationIteratorType;\n  typedef viennagrid::result_of::segment_handle<SegmentationType>::type                   SegmentType;\n  typedef viennagrid::result_of::cell_tag<DomainType>::type                               CellTagType;\n  typedef viennagrid::result_of::element<DomainType, viennagrid::vertex_tag>::type        VertexType;\n  typedef viennagrid::result_of::element<DomainType, CellTagType>::type                   CellType;\n\n  typedef viennagrid::result_of::element_range<DomainType, viennagrid::vertex_tag>::type  VertexContainerType;\n  typedef viennagrid::result_of::iterator<VertexContainerType>::type                      VertexIteratorType;\n  typedef viennagrid::result_of::element_range<SegmentType, CellTagType>::type            CellOnSegmentContainerType;\n  typedef viennagrid::result_of::iterator<CellOnSegmentContainerType>::type               CellOnSegmentIteratorType;\n\n  typedef boost::numeric::ublas::compressed_matrix<viennafem::numeric_type>  MatrixType;\n  typedef boost::numeric::ublas::vector<viennafem::numeric_type>             VectorType;\n\n  typedef viennamath::function_symbol   FunctionSymbol;\n  typedef viennamath::equation          Equation;\n\n  //\n  // Create a domain from file\n  //\n  DomainType my_domain;\n  SegmentationType segments(my_domain);\n\n  //\n  // Create a storage object\n  //\n  typedef viennadata::storage<> StorageType;\n  StorageType   storage;\n\n  try\n  {\n    viennagrid::io::netgen_reader my_netgen_reader;\n    my_netgen_reader(my_domain, segments, \"../examples/data/square224.mesh\");\n  }\n  catch (...)\n  {\n    std::cerr << \"File-Reader failed. Aborting program...\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n\n  //\n  // Specify Poisson equation with inhomogeneous permittivity:\n  //\n  FunctionSymbol u(0, viennamath::unknown_tag<>());   //an unknown function used for PDE specification\n  FunctionSymbol v(0, viennamath::test_tag<>());   //an unknown function used for PDE specification\n  viennafem::cell_quan<CellType, viennamath::expr::interface_type>  permittivity; permittivity.wrap_constant( storage, permittivity_key() );\n\n  //the strong form (not yet functional because of ViennaMath limitations)\n  //Equation poisson_equ = viennamath::make_equation( viennamath::div(permittivity * viennamath::grad(u)), 0);\n\n  //the weak form:\n  Equation poisson_equ = viennamath::make_equation(\n                          viennamath::integral(viennamath::symbolic_interval(),\n                                               permittivity * (viennamath::grad(u) * viennamath::grad(v)) ),\n                          0);\n\n  MatrixType system_matrix;\n  VectorType load_vector;\n\n  //\n  // Setting boundary information on domain (this should come from device specification)\n  //\n  //setting some boundary flags:\n  VertexContainerType vertices = viennagrid::elements<VertexType>(my_domain);\n  for (VertexIteratorType vit = vertices.begin();\n      vit != vertices.end();\n      ++vit)\n  {\n    // Boundary condition: 0 at left boundary, 1 at right boundary\n    if ( viennagrid::point(my_domain, *vit)[0] == 0.0)\n      viennafem::set_dirichlet_boundary(storage, *vit, 0.0);\n    else if ( viennagrid::point(my_domain, *vit)[0] == 1.0)\n      viennafem::set_dirichlet_boundary(storage, *vit, 1.0);\n\n  }\n\n\n  //\n  // Create PDE solver functors: (discussion about proper interface required)\n  //\n  viennafem::pde_assembler<StorageType> fem_assembler(storage);\n\n\n  //\n  // Solve system and write solution vector to pde_result:\n  // (discussion about proper interface required. Introduce a pde_result class?)\n  //\n  std::size_t si = 0;\n  for(SegmentationIteratorType sit = segments.begin(); sit != segments.end(); sit++)\n  {\n    //set permittivity:\n    CellOnSegmentContainerType cells = viennagrid::elements<CellType>(*sit);\n    for (CellOnSegmentIteratorType cit  = cells.begin();\n                                   cit != cells.end();\n                                 ++cit)\n    {\n      if (si == 0) //Si\n        viennadata::access<permittivity_key, double>(storage, permittivity_key(), *cit) = 3.9;\n      else //SiO2\n        viennadata::access<permittivity_key, double>(storage, permittivity_key(), *cit) = 11.9;\n    }\n\n\n    fem_assembler(viennafem::make_linear_pde_system(poisson_equ,\n                                                    u,\n                                                    viennafem::make_linear_pde_options(0,\n                                                                                       viennafem::lagrange_tag<1>(),\n                                                                                       viennafem::lagrange_tag<1>())\n                                                  ),\n                  *sit,\n                  system_matrix,\n                  load_vector\n                );\n  }\n\n  VectorType pde_result = viennacl::linalg::solve(system_matrix, load_vector, viennacl::linalg::cg_tag());\n  std::cout << \"* solve(): Residual: \" << norm_2(prod(system_matrix, pde_result) - load_vector) << std::endl;\n\n  //\n  // Writing solution back to domain (discussion about proper way of returning a solution required...)\n  //\n  viennafem::io::write_solution_to_VTK_file(pde_result, \"poisson_cellquan_2d\", my_domain, segments, storage, 0);\n\n  std::cout << \"*****************************************\" << std::endl;\n  std::cout << \"* Poisson solver finished successfully! *\" << std::endl;\n  std::cout << \"*****************************************\" << std::endl;\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "a8a9b410b637349101ae206d7e53ddbcea8fbc39", "size": 7491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorials/poisson_cellquan_2d.cpp", "max_stars_repo_name": "viennafem/viennafem-dev", "max_stars_repo_head_hexsha": "1f2d772cef5fb1c148e22e5bbbb6302b301e896b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-23T17:35:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-19T14:39:03.000Z", "max_issues_repo_path": "examples/tutorials/poisson_cellquan_2d.cpp", "max_issues_repo_name": "viennafem/viennafem-dev", "max_issues_repo_head_hexsha": "1f2d772cef5fb1c148e22e5bbbb6302b301e896b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-11-17T03:28:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-04T03:40:11.000Z", "max_forks_repo_path": "examples/tutorials/poisson_cellquan_2d.cpp", "max_forks_repo_name": "viennafem/viennafem-dev", "max_forks_repo_head_hexsha": "1f2d772cef5fb1c148e22e5bbbb6302b301e896b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-23T20:24:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T20:24:15.000Z", "avg_line_length": 39.4263157895, "max_line_length": 140, "alphanum_fraction": 0.61340275, "num_tokens": 1727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5178215132892074}}
{"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#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"manifold_tracing\"\n#include <boost/test/unit_test.hpp>\n#include <gudhi/Unitary_tests_utils.h>\n\n#include <iostream>\n\n#include <gudhi/Coxeter_triangulation.h>\n#include <gudhi/Functions/Function_Sm_in_Rd.h>\n#include <gudhi/Implicit_manifold_intersection_oracle.h>\n#include <gudhi/Manifold_tracing.h>\n\nusing namespace Gudhi::coxeter_triangulation;\n\nBOOST_AUTO_TEST_CASE(manifold_tracing) {\n  // manifold without boundary\n  Function_Sm_in_Rd fun_sph(5.1111, 2);\n  auto oracle = make_oracle(fun_sph);\n  Coxeter_triangulation<> cox_tr(oracle.amb_d());\n  // cox_tr.change_offset(Eigen::VectorXd::Random(oracle.amb_d()));\n\n  using MT = Manifold_tracing<Coxeter_triangulation<> >;\n  Eigen::VectorXd seed = fun_sph.seed();\n  std::vector<Eigen::VectorXd> seed_points(1, seed);\n  typename MT::Out_simplex_map out_simplex_map;\n  manifold_tracing_algorithm(seed_points, cox_tr, oracle, out_simplex_map);\n\n  for (auto si_pair : out_simplex_map) {\n    BOOST_CHECK(si_pair.first.dimension() == oracle.function().cod_d());\n    BOOST_CHECK(si_pair.second.size() == (long int)oracle.function().amb_d());\n  }\n  std::clog << \"out_simplex_map.size() = \" << out_simplex_map.size() << \"\\n\";\n  BOOST_CHECK(out_simplex_map.size() == 1118);\n\n  // manifold with boundary\n  Function_Sm_in_Rd fun_boundary(3.0, 2, fun_sph.seed());\n  auto oracle_with_boundary = make_oracle(fun_sph, fun_boundary);\n  typename MT::Out_simplex_map interior_simplex_map, boundary_simplex_map;\n  manifold_tracing_algorithm(seed_points, cox_tr, oracle_with_boundary, interior_simplex_map, boundary_simplex_map);\n  for (auto si_pair : interior_simplex_map) {\n    BOOST_CHECK(si_pair.first.dimension() == oracle.function().cod_d());\n    BOOST_CHECK(si_pair.second.size() == (long int)oracle.function().amb_d());\n  }\n  std::clog << \"interior_simplex_map.size() = \" << interior_simplex_map.size() << \"\\n\";\n  BOOST_CHECK(interior_simplex_map.size() == 96);\n  for (auto si_pair : boundary_simplex_map) {\n    BOOST_CHECK(si_pair.first.dimension() == oracle.function().cod_d() + 1);\n    BOOST_CHECK(si_pair.second.size() == (long int)oracle.function().amb_d());\n  }\n  std::clog << \"boundary_simplex_map.size() = \" << boundary_simplex_map.size() << \"\\n\";\n  BOOST_CHECK(boundary_simplex_map.size() == 54);\n}\n", "meta": {"hexsha": "63497f5a8f91b5577479511f4bf44f9308af7603", "size": 2657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Coxeter_triangulation/test/manifold_tracing_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/manifold_tracing_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/manifold_tracing_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": 42.1746031746, "max_line_length": 116, "alphanum_fraction": 0.7331576967, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5178215075134383}}
{"text": "#include <celero/Celero.h>\n\n#include <Eigen/Core>\n#include <cpzlib.hh>\n#include <random>\n\nCELERO_MAIN\n\n// TODO: Add test setup for matrices that definitely need regularization\nclass BasicFixture : public celero::TestFixture {\n public:\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> generators;\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> center;\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> exponents;\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> constraints;\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> constraint_generators;\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> constraint_exponents;\n  void setUp(const celero::TestFixture::ExperimentValue&) override {\n    std::mt19937 gen(0);\n    std::uniform_int_distribution<> dist(1, 50);\n    const int dim             = dist(gen);\n    const int num_gens        = dist(gen);\n    const int num_coeffs      = dist(gen);\n    const int num_constrs     = dist(gen);\n    const int num_constr_gens = dist(gen);\n\n    center     = Eigen::Matrix<float, Eigen::Dynamic, 1>::Random(dim);\n    generators = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>::Random(dim, num_gens);\n    exponents = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>::Random(num_coeffs, num_gens);\n    constraints = Eigen::Matrix<float, Eigen::Dynamic, 1>::Random(num_constrs);\n    constraint_generators =\n    Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>::Random(num_constrs, num_constr_gens);\n    constraint_exponents =\n    Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>::Random(num_coeffs, num_constr_gens);\n  }\n};\n\nBASELINE_F(Regularization, Baseline, BasicFixture, 1000, 0) {\n  cpz::ConstrainedPolynomialZonotope<> z(\n  center, generators, exponents, constraints, constraint_generators, constraint_exponents);\n}\n", "meta": {"hexsha": "9a02973bad0cde8299749ad7e3f77277898114ca", "size": 1810, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/cpzlib_benchmarks.cc", "max_stars_repo_name": "wbthomason/cpzlib", "max_stars_repo_head_hexsha": "d0361c91d634480e60988a396c02334b5fccb44e", "max_stars_repo_licenses": ["MIT"], "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/cpzlib_benchmarks.cc", "max_issues_repo_name": "wbthomason/cpzlib", "max_issues_repo_head_hexsha": "d0361c91d634480e60988a396c02334b5fccb44e", "max_issues_repo_licenses": ["MIT"], "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/cpzlib_benchmarks.cc", "max_forks_repo_name": "wbthomason/cpzlib", "max_forks_repo_head_hexsha": "d0361c91d634480e60988a396c02334b5fccb44e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-16T19:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T19:25:24.000Z", "avg_line_length": 43.0952380952, "max_line_length": 99, "alphanum_fraction": 0.7209944751, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5177967418498901}}
{"text": "#include <functional>\n#include <Eigen/SparseCholesky>\n#include <Eigen/SparseLU>\n#include <iostream>\n#include <fstream>\n#include <assert.h>\n#include <stdio.h>\n\n#include \"tree.h\"\n#include \"util.h\"\n#include \"mmio.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int argc, char* argv[]) {\n  vector<int> dims  = {2,  2,  2,   3, 3,  3 };\n  vector<int> sizes = {5,  16, 64,  5, 10, 15};\n  int ntests = dims.size();\n  if (argc > 1) {\n      ntests = atoi(argv[1]);\n      printf(\"Running max %d different tests problems\\n\", ntests);\n  }\n  matrix_hash<VectorXd> hash;\n  vector<size_t> allhashes;\n  for(int test = 0; test < ntests; test++) {\n    int s = sizes[test];\n    int d = dims[test];\n    stringstream ss;\n    ss << \"../mats/neglapl_\" << d << \"_\" << s << \".mm\";\n    string file = ss.str();\n    cout << file << endl;\n    SpMat Asymm = mmio::sp_mmread<double,int>(file);\n    default_random_engine gen;\n    uniform_real_distribution<double> dist(0.5,1.0);\n    double a = dist(gen);\n    SpMat Aunsymm = a * Asymm.triangularView<Lower>() + (1 - a) * Asymm.triangularView<Upper>(); \n    SpMat* A = nullptr;\n    int N = Asymm.rows();\n    int nlevelsmin = N < 1000 ? 1 : 8;\n    for(int nlevels = nlevelsmin; nlevels < nlevelsmin+3; nlevels++) {\n      vector<double> tols = {0.0, 1e-2, 1.0, 10.0};\n      for(double tol : tols) {\n        for(int skip = 0; skip < 3; skip++) {\n          for(int pres = 0; pres < 2; pres++) {\n            for(int symm = 0; symm < 2; symm++) {\n              for(int geo = 0; geo < 2; geo++) {\n                for(int scale = 0; scale < 2; scale++) {\n                  for(int ortho = 0; ortho < 2; ortho++) {\n                    // Only valid combinations\n                    if(ortho && (!scale))   continue;\n                    if(pres  && ((!ortho) || (!symm)) ) continue;\n                    Tree t = Tree(nlevels);\n                    t.set_verb(false);\n                    t.set_tol(tol);\n                    t.set_skip(skip);\n                    t.set_scale(scale);\n                    t.set_ortho(ortho);\n                    t.set_preserve(pres);\n                    t.set_use_geo(geo);\n                    t.set_symmetry(symm);\n                    MatrixXd phi = MatrixXd::Ones(N,1);\n                    MatrixXd X = linspace_nd(s, d);\n                    t.set_phi(&phi);                                        \n                    t.set_Xcoo(&X);  \n                    if(symm) {\n                        A = &Asymm;                                            \n                    } else {\n                        A = &Aunsymm;                                            \n                    }\n                    t.partition(*A);\n                    t.assemble(*A);\n                    int errors = t.factorize();                        \n                    assert(errors == 0);\n                    VectorXd b = VectorXd::Random(N);\n                    auto x = b;\n                    t.solve(x);\n                    double res = ((*A)*x-b).norm() / b.norm();\n                    SparseLU<SpMat> lu((*A));\n                    VectorXd xref;\n                    xref = lu.solve(b);\n                    double err = (xref - x).norm() / xref.norm();\n                    auto h = hash(x);\n                    allhashes.push_back(h);\n                    printf(\"%6d %4d %d] %3d %3.2e %2d %d %d %d %d %d %3.2e %3.2e | %lu\\n\", N, s, d, nlevels, tol, skip, pres, symm, geo, scale, ortho, res, err, hash(x));\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n  size_t h = hashv(allhashes);\n  cout << \"Overall hash: \" << h << endl;\n  ofstream f;\n  f.open(\"allhashes.log\");\n  for(auto v : allhashes) {\n    f << v << \"\\n\";\n  }\n  f.close();\n  return 1;\n}\n\n", "meta": {"hexsha": "aa8da274751fe126efb231dfd09ae835517cb9fa", "size": 3738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/run.cpp", "max_stars_repo_name": "wuyou33/spaND_public", "max_stars_repo_head_hexsha": "5383ec0af835634bef7b2ff24c979794a2ef253b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-23T12:04:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-23T12:04:30.000Z", "max_issues_repo_path": "tests/run.cpp", "max_issues_repo_name": "wuyou33/spaND_public", "max_issues_repo_head_hexsha": "5383ec0af835634bef7b2ff24c979794a2ef253b", "max_issues_repo_licenses": ["MIT"], "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/run.cpp", "max_forks_repo_name": "wuyou33/spaND_public", "max_forks_repo_head_hexsha": "5383ec0af835634bef7b2ff24c979794a2ef253b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2641509434, "max_line_length": 170, "alphanum_fraction": 0.430176565, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825655188238, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.517796736968141}}
{"text": "/**\n * Copyright (c) 2015 Carnegie Mellon University, Daniel Maturana <dimatura@cmu.edu>\n *\n * For License information please see the LICENSE file in the root directory.\n *\n */\n\n#ifndef SCROLLGRID2_HPP_YPBBYE5Q\n#define SCROLLGRID2_HPP_YPBBYE5Q\n\n#include <math.h>\n#include <stdint.h>\n\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <ros/ros.h>\n#include <ros/console.h>\n\n#include <pcl_util/point_types.hpp>\n#include <geom_cast/geom_cast.hpp>\n\n#include \"scrollgrid/mod_wrap.hpp\"\n#include \"scrollgrid/grid_types.hpp\"\n#include \"scrollgrid/box.hpp\"\n\nnamespace ca\n{\n\ntemplate<class Scalar>\nclass ScrollGrid2 {\npublic:\n  typedef Eigen::Matrix<Scalar, 2, 1> Vec2;\n\n  typedef boost::shared_ptr<ScrollGrid2> Ptr;\n  typedef boost::shared_ptr<const ScrollGrid2> ConstPtr;\n\npublic:\n  ScrollGrid2() :\n      box_(),\n      origin_(0, 0),\n      min_world_corner_ij_(0, 0),\n      dimension_(0, 0),\n      num_cells_(0),\n      strides_(0, 0),\n      scroll_offset_(0, 0),\n      last_ij_(0, 0),\n      wrap_ij_min_(0, 0),\n      wrap_ij_max_(0, 0),\n      resolution_(0)\n  { }\n\n  ScrollGrid2(const Vec2& center,\n              const Vec2Ix& dimension,\n              Scalar resolution,\n              bool x_fastest=false) :\n      box_(center-(dimension.cast<Scalar>()*resolution)/2,\n           center+(dimension.cast<Scalar>()*resolution)/2),\n      origin_(center-box_.radius()),\n      dimension_(dimension),\n      num_cells_(dimension.prod()),\n      strides_(dimension[1], 1),\n      scroll_offset_(0, 0, 0),\n      last_ij_(scroll_offset_ + dimension_),\n      resolution_(resolution)\n  {\n\n    Vec2 m;\n    m[0] = -static_cast<Scalar>(std::numeric_limits<uint16_t>::max()/2)*resolution_;\n    m[1] = -static_cast<Scalar>(std::numeric_limits<uint16_t>::max()/2)*resolution_;\n    min_world_corner_ij_ = this->world_to_grid(m);\n\n    if (x_fastest) {\n      strides_ = Vec2Ix(1, dimension[0]);\n    }\n\n    this->update_wrap_ij();\n  }\n\n  virtual ~ScrollGrid2() { }\n\n  ScrollGrid2(const ScrollGrid2& other) :\n      box_(other.box_),\n      origin_(other.origin_),\n      min_world_corner_ij_(other.min_world_corner_ij_),\n      dimension_(other.dimension_),\n      num_cells_(other.num_cells_),\n      strides_(other.strides_),\n      scroll_offset_(other.scroll_offset_),\n      last_ij_(other.last_ij_),\n      wrap_ij_min_(other.wrap_ij_min_),\n      wrap_ij_max_(other.wrap_ij_max_),\n      resolution_(other.resolution_)\n  {\n  }\n\n  ScrollGrid2& operator=(const ScrollGrid2& other) {\n    if (*this==other) { return *this; }\n    box_ = other.box_;\n    origin_ = other.origin_;\n    min_world_corner_ij_ = other.min_world_corner_ij_;\n    dimension_ = other.dimension_;\n    num_cells_ = other.num_cells_;\n    strides_ = other.strides_;\n    scroll_offset_ = other.scroll_offset_;\n    last_ij_ = other.last_ij_;\n    wrap_ij_min_ = other.wrap_ij_min_;\n    wrap_ij_max_ = other.wrap_ij_max_;\n    resolution_ = other.resolution_;\n    return *this;\n  }\n\npublic:\n\n  void reset(const Vec2& center,\n             const Vec2Ix& dimension,\n             Scalar resolution,\n             bool x_fastest=false) {\n    box_.set_center(center);\n    box_.set_radius((dimension.cast<Scalar>()*resolution)/2);\n    origin_ = center - box_.radius();\n\n    dimension_ = dimension;\n    num_cells_ = dimension.prod();\n    if (x_fastest) {\n      strides_ = Vec2Ix(1, dimension[0]);\n    } else {\n      strides_ = Vec2Ix(dimension[1], 1);\n    }\n    scroll_offset_.setZero();\n    last_ij_ = scroll_offset_ + dimension_;\n\n    this->update_wrap_ij();\n\n    resolution_ = resolution;\n\n    Vec2 m;\n    m[0] = -static_cast<Scalar>(std::numeric_limits<uint16_t>::max()/2)*resolution_;\n    m[1] = -static_cast<Scalar>(std::numeric_limits<uint16_t>::max()/2)*resolution_;\n    min_world_corner_ij_ = this->world_to_grid(m);\n\n  }\n\n  /**\n   * Is inside 3D box containing grid?\n   * @param pt point in same frame as center (probably world_view)\n   */\n  bool is_inside_box(const Vec2& pt) const {\n    return box_.contains(pt);\n  }\n\n  template<class PointT>\n  bool is_inside_box(const PointT& pt) const {\n    return box_.contains(ca::point_cast<Vec2>(pt));\n  }\n\n  /**\n   * is i, j, k inside the grid limits?\n   */\n  bool is_inside_grid(const Vec2Ix& grid_ix) const {\n    return ((grid_ix.array() >= scroll_offset_.array()).all() &&\n            (grid_ix.array() < (scroll_offset_+dimension_).array()).all());\n  }\n\n  bool is_inside_grid(grid_ix_t i, grid_ix_t j) const {\n    return this->is_inside_grid(Vec2Ix(i, j));\n  }\n\n  /**\n   * scroll grid.\n   * updates bounding box and offset_cells.\n   * @param offset_cells. how much to scroll. offset_cells is a signed integral.\n   *\n   */\n  void scroll(const Vec2Ix& offset_cells) {\n    Vec2Ix new_offset = scroll_offset_ + offset_cells;\n    box_.translate((offset_cells.cast<Scalar>()*resolution_));\n    scroll_offset_ = new_offset;\n    last_ij_ = scroll_offset_ + dimension_;\n\n    this->update_wrap_ij();\n  }\n\n  /**\n   * get boxes to clear if scrolling by offset_cells.\n   * call this *before* scroll().\n   * @param clear_i_min min corner of obsolete region in grid\n   * @param clear_i_max max corner of obsolete region in grid\n   * same for j and k\n   * Note that boxes may overlap.\n   */\n  void get_clear_boxes(const Vec2Ix& offset_cells,\n                       Vec2Ix& clear_i_min, Vec2Ix& clear_i_max,\n                       Vec2Ix& clear_j_min, Vec2Ix& clear_j_max) {\n\n    Vec2Ix new_offset = scroll_offset_ + offset_cells;\n\n    clear_i_min.setZero();\n    clear_j_min.setZero();\n    clear_i_max.setZero();\n    clear_j_max.setZero();\n\n    // X axis\n    if (offset_cells[0] > 0) {\n      clear_i_min = scroll_offset_;\n      clear_i_max = Vec2Ix(new_offset[0],\n                           scroll_offset_[1]+dimension_[1]);\n    } else if (offset_cells[0] < 0) {\n      clear_i_min = Vec2Ix(scroll_offset_[0]+dimension_[0]+offset_cells[0],\n                           scroll_offset_[1]);\n      clear_i_max = scroll_offset_ + dimension_;\n    }\n\n    // Y axis\n    if (offset_cells[1] > 0) {\n      clear_j_min = scroll_offset_;\n      clear_j_max = Vec2Ix(scroll_offset_[0]+dimension_[0],\n                           new_offset[1]);\n    } else if (offset_cells[1] < 0) {\n      clear_j_min = Vec2Ix(scroll_offset_[0],\n                           scroll_offset_[1]+dimension_[1]+offset_cells[1]);\n      clear_j_max = scroll_offset_ + dimension_;\n    }\n\n  }\n\n  /**\n   * Given position in world coordinates, return grid coordinates.\n   * (grid coordinates are not wrapped to be inside grid!)\n   * Note: does not check if point is inside grid.\n   */\n  Vec2Ix world_to_grid(const Vec2& xy) const {\n    Vec2 tmp = ((xy - origin_).array() - 0.5*resolution_)/resolution_;\n    //ROS_INFO_STREAM(\"tmp = \" << tmp);\n    //return tmp.cast<grid_ix_t>();\n    return Vec2Ix(round(tmp.x()), round(tmp.y()));\n  }\n\n  Vec2Ix world_to_grid(Scalar x, Scalar y) const {\n    return this->world_to_grid(Vec2(x, y));\n  }\n\n  Vec2 grid_to_world(const Vec2Ix& grid_ix) const {\n    Vec2 w((grid_ix.cast<Scalar>()*resolution_ + origin_).array() + 0.5*resolution_);\n    return w;\n  }\n\n  Vec2 grid_to_world(grid_ix_t i, grid_ix_t j) const {\n    return this->grid_to_world(Vec2Ix(i, j));\n  }\n\n  /**\n   * Translate grid indices to an address in linear memory.\n   * Does not check if grid_ix is inside current grid box.\n   * Assumes C-order, x the slowest and z the fastest.\n   */\n  mem_ix_t grid_to_mem(const Vec2Ix& grid_ix) const {\n    Vec2Ix grid_ix2(ca::mod_wrap(grid_ix[0], dimension_[0]),\n                    ca::mod_wrap(grid_ix[1], dimension_[1]));\n    return strides_.dot(grid_ix2);\n  }\n\n  /**\n   * This is faster than grid_to_mem, as it avoids modulo.\n   * But it only works if the grid_ix are inside the bounding box.\n   * Hopefully branch prediction kicks in\n   */\n  mem_ix_t grid_to_mem2(const Vec2Ix& grid_ix) const {\n    Vec2Ix grid_ix2(grid_ix);\n    if (grid_ix2[0] >= wrap_ij_max_[0]) { grid_ix2[0] -= wrap_ij_max_[0]; } else { grid_ix2[0] -= wrap_ij_min_[0]; }\n    if (grid_ix2[1] >= wrap_ij_max_[1]) { grid_ix2[1] -= wrap_ij_max_[1]; } else { grid_ix2[1] -= wrap_ij_min_[1]; }\n    mem_ix_t mem_ix2 = strides_.dot(grid_ix2);\n    return mem_ix2;\n  }\n\n  mem_ix_t grid_to_mem(grid_ix_t i, grid_ix_t j) const {\n    return this->grid_to_mem(Vec2Ix(i, j));\n  }\n\n  mem_ix_t grid_to_mem2(grid_ix_t i, grid_ix_t j) const {\n    return grid_to_mem2(Vec2Ix(i, j));\n  }\n\n  uint64_t grid_to_hash(const Vec2Ix& grid_ix) const {\n    // grid2 should be all positive\n    Vec2Ix grid2(grid_ix - min_world_corner_ij_);\n    uint64_t hi = static_cast<uint64_t>(grid2[0]);\n    uint64_t hj = static_cast<uint64_t>(grid2[1]);\n    uint64_t h = (hi << 48) | (hj << 32);\n    return h;\n  }\n\n  Vec2Ix hash_to_grid(uint64_t hix) const {\n    uint64_t hi = (hix & 0xffff000000000000) >> 48;\n    uint64_t hj = (hix & 0x0000ffff00000000) >> 32;\n    Vec2Ix grid_ix(hi, hj);\n    grid_ix += min_world_corner_ij_;\n    return grid_ix;\n  }\n\n  /**\n   * Note that no bound check is performed!\n   */\n  mem_ix_t world_to_mem(const Vec2& xy) const {\n    Vec2 tmp(((xy - origin_).array() - 0.5*resolution_)/resolution_);\n    Vec2Ix gix(round(tmp.x()), round(tmp.y()), round(tmp.z()));\n    ca::inplace_mod_wrap(gix[0], dimension_[0]);\n    ca::inplace_mod_wrap(gix[1], dimension_[1]);\n    return strides_.dot(gix);\n  }\n\n  mem_ix_t world_to_mem2(const Vec2& xy) const {\n    Vec2Ix gix(this->world_to_grid(xy));\n    return this->world_to_mem2(gix);\n  }\n\n  Vec2Ix mem_to_grid(grid_ix_t mem_ix) const {\n    // TODO does this work for x-fastest strides?\n    grid_ix_t i = mem_ix/strides_[0];\n    mem_ix -= i*strides_[0];\n    grid_ix_t j = mem_ix/strides_[1];\n    mem_ix -= j*strides_[1];\n\n    // undo wrapping\n    grid_ix_t ax = floor(static_cast<Scalar>(scroll_offset_[0])/dimension_[0])*dimension_[0];\n    grid_ix_t ay = floor(static_cast<Scalar>(scroll_offset_[1])/dimension_[1])*dimension_[1];\n\n    Vec2Ix fixed_ij;\n    fixed_ij[0] = i + ax + (i<(scroll_offset_[0]-ax))*dimension_[0];\n    fixed_ij[1] = j + ay + (j<(scroll_offset_[1]-ay))*dimension_[1];\n\n    return fixed_ij;\n  }\n\n public:\n\n  grid_ix_t dim_i() const { return dimension_[0]; }\n  grid_ix_t dim_j() const { return dimension_[1]; }\n  grid_ix_t first_i() const { return scroll_offset_[0]; }\n  grid_ix_t first_j() const { return scroll_offset_[1]; }\n  grid_ix_t last_i() const { return last_ij_[0]; }\n  grid_ix_t last_j() const { return last_ij_[1]; }\n  const Vec2Ix& dimension() const { return dimension_; }\n  const Vec2& radius() const { return box_.radius(); }\n  const Vec2& origin() const { return origin_; }\n  Vec2 min_pt() const { return box_.min_pt(); }\n  Vec2 max_pt() const { return box_.max_pt(); }\n  const Vec2& center() const { return box_.center(); }\n  Scalar resolution() const { return resolution_; }\n  const ca::scrollgrid::Box<Scalar, 2>& box() const { return box_; }\n  grid_ix_t num_cells() const { return num_cells_; }\n  Vec2Ix scroll_offset() const { return scroll_offset_; }\n\n private:\n\n  void update_wrap_ij() {\n    wrap_ij_min_[0] = floor(static_cast<float>(scroll_offset_[0])/dimension_[0])*dimension_[0];\n    wrap_ij_min_[1] = floor(static_cast<float>(scroll_offset_[1])/dimension_[1])*dimension_[1];\n\n    wrap_ij_max_[0] = floor(static_cast<float>(scroll_offset_[0]+dimension_[0])/dimension_[0])*dimension_[0];\n    wrap_ij_max_[1] = floor(static_cast<float>(scroll_offset_[1]+dimension_[1])/dimension_[1])*dimension_[1];\n  }\n\n private:\n  // 2d box enclosing grid. In whatever coordinates were given (probably\n  // world_view)\n  ca::scrollgrid::Box<Scalar, 2> box_;\n\n  // static origin of the grid coordinate system. does not move when scrolling\n  // it's center - box.radius\n  Vec2 origin_;\n\n  // minimum world corner in ij. used for hash\n  Vec2Ix min_world_corner_ij_;\n\n  // number of grid cells along each axis\n  Vec2Ix dimension_;\n\n  // number of cells\n  grid_ix_t num_cells_;\n\n  // grid strides to translate from linear to 3D layout.\n  // C-ordering, ie x slowest, z fastest.\n  Vec2Ix strides_;\n\n  // to keep track of scrolling along z.\n  Vec2Ix scroll_offset_;\n\n  // redundant but actually seems to have a performance benefit\n  // should always be dimension + offset\n  Vec2Ix last_ij_;\n\n  // for grid_to_mem2. the points where the grid crosses modulo boundaries.\n  Vec2Ix wrap_ij_min_;\n  Vec2Ix wrap_ij_max_;\n\n  // size of grid cells\n  Scalar resolution_;\n\n};\n\ntypedef ScrollGrid2<float> ScrollGrid2f;\ntypedef ScrollGrid2<double> ScrollGrid2d;\n\n} /* ca */\n\n#endif /* end of include guard: SCROLLGRID2_HPP_YPBBYE5Q */\n", "meta": {"hexsha": "d0cf57e8f7a16229a3cd5592a4f6af0830658218", "size": 12406, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/scrollgrid/scrollgrid2.hpp", "max_stars_repo_name": "castacks/scrollgrid", "max_stars_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-07-20T23:04:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T08:03:10.000Z", "max_issues_repo_path": "include/scrollgrid/scrollgrid2.hpp", "max_issues_repo_name": "castacks/scrollgrid", "max_issues_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/scrollgrid/scrollgrid2.hpp", "max_forks_repo_name": "castacks/scrollgrid", "max_forks_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-06T16:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T01:39:22.000Z", "avg_line_length": 30.2585365854, "max_line_length": 116, "alphanum_fraction": 0.6647589876, "num_tokens": 3453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5177967320863919}}
{"text": "#pragma once\n#include <csapex/model/node.h>\n\n#include <csapex_opencv/roi.h>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <opencv2/opencv.hpp>\n#include <sstream>\n\nnamespace csapex\n{\nnamespace vision\n{\nclass ROISizeStatistics : public csapex::Node\n{\n    template <typename T>\n    using Accumulator = boost::accumulators::accumulator_set<\n        T, boost::accumulators::stats<boost::accumulators::tag::min, boost::accumulators::tag::max, boost::accumulators::tag::mean, boost::accumulators::tag::variance>>;\n\n    template <typename T>\n    static std::string formatAccumulator(const Accumulator<T>& accu)\n    {\n        std::ostringstream os;\n        os << boost::accumulators::mean(accu);\n        os << \" (std.dev.: \" << std::sqrt(boost::accumulators::variance(accu)) << \")\";\n        os << \" (min: \" << boost::accumulators::min(accu);\n        os << \", max: \" << boost::accumulators::max(accu) << \")\";\n        return os.str();\n    }\n\n    struct Statistics\n    {\n        void reset();\n        void update(const Roi& roi);\n        std::string format() const;\n\n        std::size_t count;\n        Accumulator<int> height;\n        Accumulator<int> width;\n        Accumulator<int> area;\n        Accumulator<float> ratio;\n    };\n\n    enum class BinType\n    {\n        HEIGHT,\n        WIDTH,\n        AREA\n    };\n\npublic:\n    ROISizeStatistics();\n    void setupParameters(csapex::Parameterizable& parameters) override;\n    void setup(csapex::NodeModifier& node_modifier) override;\n    void process() override;\n\nprivate:\n    void resetStats();\n    void saveStats();\n    void updateStats(const Roi& roi);\n    std::string formatStats() const;\n\nprivate:\n    Input* in_rois_;\n    Output* out_info_;\n    Output* out_histogram_;\n\n    int max_width_;\n    int max_height_;\n    int histogram_bin_size_;\n    std::string output_path_;\n    int bin_count_;\n    BinType bin_type_;\n\n    Statistics global_stats_;\n    cv::Mat global_histogram_;\n    std::vector<Statistics> bin_stats_;\n};\n\n}  // namespace vision\n}  // namespace csapex\n", "meta": {"hexsha": "827c28789f279f64645557ef95be9ebd3176b501", "size": 2269, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "csapex_vision/src/roi/roi_size_statistics.hpp", "max_stars_repo_name": "AdrianZw/csapex_core_plugins", "max_stars_repo_head_hexsha": "1b23c90af7e552c3fc37c7dda589d751d2aae97f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-02T15:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T22:09:33.000Z", "max_issues_repo_path": "csapex_vision/src/roi/roi_size_statistics.hpp", "max_issues_repo_name": "AdrianZw/csapex_core_plugins", "max_issues_repo_head_hexsha": "1b23c90af7e552c3fc37c7dda589d751d2aae97f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-14T19:53:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-14T19:53:30.000Z", "max_forks_repo_path": "csapex_vision/src/roi/roi_size_statistics.hpp", "max_forks_repo_name": "AdrianZw/csapex_core_plugins", "max_forks_repo_head_hexsha": "1b23c90af7e552c3fc37c7dda589d751d2aae97f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-10-12T00:55:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T17:49:25.000Z", "avg_line_length": 26.0804597701, "max_line_length": 169, "alphanum_fraction": 0.6624063464, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5177967320863918}}
{"text": "//  Copyright John Maddock 2006.\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#ifndef BOOST_MATH_SF_BINOMIAL_HPP\r\n#define BOOST_MATH_SF_BINOMIAL_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/math/special_functions/math_fwd.hpp>\r\n#include <boost/math/special_functions/factorials.hpp>\r\n#include <boost/math/special_functions/beta.hpp>\r\n#include <boost/math/policies/error_handling.hpp>\r\n\r\nnamespace boost{ namespace math{\r\n\r\ntemplate <class T, class Policy>\r\nT binomial_coefficient(unsigned n, unsigned k, const Policy& pol)\r\n{\r\n   BOOST_STATIC_ASSERT(!boost::is_integral<T>::value);\r\n   BOOST_MATH_STD_USING\r\n   static const char* function = \"boost::math::binomial_coefficient<%1%>(unsigned, unsigned)\";\r\n   if(k > n)\r\n      return policies::raise_domain_error<T>(\r\n         function, \r\n         \"The binomial coefficient is undefined for k > n, but got k = %1%.\",\r\n         static_cast<T>(k), pol);\r\n   T result;\r\n   if((k == 0) || (k == n))\r\n      return static_cast<T>(1);\r\n   if((k == 1) || (k == n-1))\r\n      return static_cast<T>(n);\r\n\r\n   if(n <= max_factorial<T>::value)\r\n   {\r\n      // Use fast table lookup:\r\n      result = unchecked_factorial<T>(n);\r\n      result /= unchecked_factorial<T>(n-k);\r\n      result /= unchecked_factorial<T>(k);\r\n   }\r\n   else\r\n   {\r\n      // Use the beta function:\r\n      if(k < n - k)\r\n         result = k * beta(static_cast<T>(k), static_cast<T>(n-k+1), pol);\r\n      else\r\n         result = (n - k) * beta(static_cast<T>(k+1), static_cast<T>(n-k), pol);\r\n      if(result == 0)\r\n         return policies::raise_overflow_error<T>(function, 0, pol);\r\n      result = 1 / result;\r\n   }\r\n   // convert to nearest integer:\r\n   return ceil(result - 0.5f);\r\n}\r\n//\r\n// Type float can only store the first 35 factorials, in order to\r\n// increase the chance that we can use a table driven implementation\r\n// we'll promote to double:\r\n//\r\ntemplate <>\r\ninline float binomial_coefficient<float, policies::policy<> >(unsigned n, unsigned k, const policies::policy<>& pol)\r\n{\r\n   return policies::checked_narrowing_cast<float, policies::policy<> >(binomial_coefficient<double>(n, k, pol), \"boost::math::binomial_coefficient<%1%>(unsigned,unsigned)\");\r\n}\r\n\r\ntemplate <class T>\r\ninline T binomial_coefficient(unsigned n, unsigned k)\r\n{\r\n   return binomial_coefficient<T>(n, k, policies::policy<>());\r\n}\r\n\r\n} // namespace math\r\n} // namespace boost\r\n\r\n\r\n#endif // BOOST_MATH_SF_BINOMIAL_HPP\r\n\r\n\r\n\r\n", "meta": {"hexsha": "c8a0a80f2b256e5745f7865068c2a56820391c21", "size": 2590, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/math/special_functions/binomial.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/math/special_functions/binomial.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/math/special_functions/binomial.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": 31.2048192771, "max_line_length": 174, "alphanum_fraction": 0.6540540541, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5177967320863918}}
{"text": "#include \"storm/utility/numerical.h\"\n\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n\n#include \"storm/utility/macros.h\"\n#include \"storm/utility/constants.h\"\n#include \"storm/exceptions/InvalidArgumentException.h\"\n#include \"storm/exceptions/PrecisionExceededException.h\"\n\nnamespace storm {\n    namespace utility {\n        namespace numerical {\n\n            template<typename ValueType>\n            FoxGlynnResult<ValueType>::FoxGlynnResult() : left(0), right(0), totalWeight(storm::utility::zero<ValueType>()) {\n                // Intentionally left empty.\n            }\n            \n            /*!\n             * The following implementation of Fox and Glynn's algorithm is taken from David Jansen's patched version\n             * in MRMC, which is based on his paper:\n             *\n             * https://pms.cs.ru.nl/iris-diglib/src/getContent.php?id=2011-Jansen-UnderstandingFoxGlynn\n             *\n             * We have only adapted the code to match more of C++'s and our coding guidelines.\n             */\n            \n            template<typename ValueType>\n            FoxGlynnResult<ValueType> foxGlynnFinder(ValueType lambda, ValueType epsilon) {\n                ValueType tau = std::numeric_limits<ValueType>::min();\n                ValueType omega = std::numeric_limits<ValueType>::max();\n                ValueType const sqrt_2_pi = boost::math::constants::root_two_pi<ValueType>();\n                ValueType const log10_e = std::log10(boost::math::constants::e<ValueType>());\n                \n                uint64_t m = static_cast<uint64_t>(lambda);\n                \n                int64_t left = 0;\n                int64_t right = 0;\n                \n                // tau is only used in underflow checks, which we are going to do in the logarithm domain.\n                tau = log(tau);\n                \n                // In error bound comparisons, we always compare with epsilon*sqrt_2_pi.\n                epsilon *= sqrt_2_pi;\n                \n                // Compute left truncation point.\n                if (m < 25) {\n                    // For lambda below 25 the exponential can be smaller than tau. If that is the case we expect\n                    // underflows and warn the user.\n                    if (-lambda <= tau) {\n                        STORM_LOG_WARN(\"Fox-Glynn: 0 < lambda < 25, underflow near Poi(\" << lambda << \", 0) = \" << std::exp(-lambda) << \". The results are unreliable.\");\n                    }\n                    \n                    // Zero is used as left truncation point for lambda <= 25.\n                    left = 0;\n                } else {\n                    // Compute the left truncation point for lambda >= 25 (for lambda < 25 we use zero as left truncation point).\n\n                    ValueType const bl = (1 + 1 / lambda) * std::exp((1/lambda) * 0.125);\n                    ValueType const sqrt_lambda = std::sqrt(lambda);\n                    int64_t k;\n                    \n                    // Start looking for the left truncation point:\n                    // * start search at k=4 (taken from original Fox-Glynn paper)\n                    // * increase the left truncation point until we fulfil the error condition\n                    \n                    for (k = 4;; ++k) {\n                        ValueType max_err;\n                        \n                        left = m - static_cast<int64_t>(std::ceil(k*sqrt_lambda + 0.5));\n                        \n                        // For small lambda the above calculation can yield negative truncation points, crop them here.\n                        if (left <= 0) {\n                            left = 0;\n                            break;\n                        }\n                        \n                        // Note that Propositions 2-4 in Fox--Glynn mix up notation: they write Phi where they mean\n                        // 1 - Phi. (In Corollaries 1 and 2, phi is used correctly again.)\n                        max_err = bl * exp(-0.5 * (k*k)) / k;\n                        if (max_err * 2 <= epsilon) {\n                            // If the error on the left hand side is smaller, we can be more lenient on the right hand\n                            // side. To this end, we now set epsilon to the part of the error that has not yet been eaten\n                            // up by the left-hand truncation.\n                            epsilon -= max_err;\n                            break;\n                        }\n                    }\n                    \n                    // Finally the left truncation point is found.\n                }\n                \n                // Compute right truncation point.\n                {\n                    ValueType lambda_max;\n                    int64_t m_max, k;\n                    \n                    // According to Fox-Glynn, if lambda < 400 we should take lambda = 400, otherwise use the original\n                    // value. This is for computing the right truncation point.\n                    if (m < 400) {\n                        lambda_max = 400;\n                        m_max = 400;\n                        epsilon *= 0.662608824988162441697980;\n                        /* i.e. al = (1+1/400) * exp(1/16) * sqrt_2; epsilon /= al; */\n                    } else {\n                        lambda_max = lambda;\n                        m_max = m;\n                        epsilon *= (1 - 1 / (lambda + 1)) * 0.664265347050632847802225;\n                        /* i.e. al = (1+1/lambda) * exp(1/16) * sqrt_2; epsilon /= al; */\n                    }\n                    \n                    // Find right truncation point.\n                    \n                    // This loop is a modification to the original Fox-Glynn paper.\n                    // The search for the right truncation point is only terminated by  the error condition and not by\n                    // the stop index from the FG paper. This can yield more accurate results if necessary.\n                    for (k = 4;; ++k) {\n                        // dkl_inv is between 1 - 1e-33 and 1 if lambda_max >= 400 and k >= 4; this will always be\n                        // rounded to 1.0. We therefore leave the factor out.\n                        // double dkl_inv=1 - exp(-266/401.0 * (k*sqrt(2*lambda_max) + 1.5));\n                        \n                        // actually: \"k * (dkl_inv*epsilon/al) >= exp(-0.5 * k^2)\", but epsilon has been changed appropriately.\n                        if (k * epsilon >= exp(-0.5*(k*k))) {\n                            break;\n                        }\n                    }\n                    right = m_max + static_cast<int64_t>(std::ceil(k * std::sqrt(2 * lambda_max) + 0.5));\n                    if (right > m_max + static_cast<int64_t>(std::ceil((lambda_max + 1) * 0.5))) {\n                        STORM_LOG_WARN(\"Fox-Glynn: right = \" << right << \" >> lambda = \" << lambda_max << \", cannot bound the right tail. The results are unreliable.\");\n                    }\n                }\n                \n                // Time to set the initial value for weights.\n                FoxGlynnResult<ValueType> fgresult;\n                fgresult.left = static_cast<uint64_t>(left);\n                fgresult.right = static_cast<uint64_t>(right);\n                fgresult.weights.resize(fgresult.right - fgresult.left + 1);\n\n                fgresult.weights[m - left] = omega / (1.0e+10 * (right - left));\n                \n                if (m >= 25) {\n                    // Perform underflow check.\n                    ValueType result, log_c_m_inf;\n                    int64_t i;\n                    \n                    // we are going to compare with tau - log(w[m]).\n                    tau -= std::log(fgresult.weights[m - left]);\n                    \n                    // We take the c_m_inf = 0.14627 / sqrt( m ), as for lambda >= 25\n                    // c_m = 1 / ( sqrt( 2.0 * pi * m ) ) * exp( m - lambda - 1 / ( 12.0 * m ) ) => c_m_inf.\n                    // Note that m-lambda is in the interval (-1,0], and -1/(12*m) is in [-1/(12*25),0).\n                    // So, exp(m-lambda - 1/(12*m)) is in (exp(-1-1/(12*25)),exp(0)).\n                    // Therefore, we can improve the lower bound on c_m to exp(-1-1/(12*25)) / sqrt(2*pi) = ~0.14627.\n                    // Its logarithm is -1 - 1/(12*25) - log(2*pi) * 0.5 = ~ -1.922272 (rounded towards -infinity).\n                    log_c_m_inf = -1.922272 - log((double) m) * 0.5;\n                    \n                    // We use FG's Proposition 6 directly (and not Corollary 4 i and ii), as k_prime may be too large\n                    // if pFG->left == 0.\n                    i = m - left;\n                    \n                    // Equivalent to 2*i <= m, equivalent to i <= lambda/2.\n                    if (i <= left) {\n                        // Use Proposition 6 (i). Note that Fox--Glynn are off by one in the proof of this proposition;\n                        // they sum up to i-1, but should have summed up to i. */\n                        result = log_c_m_inf\n                        - i * (i+1) * (0.5 + (2*i+1)/(6*lambda)) / lambda;\n                    } else {\n                        // Use Corollary 4 (iii). Note that k_prime <= sqrt(m+1)/m is a misprint for k_prime <= m/sqrt(m+1),\n                        // which is equivalent to left >= 0, which holds trivially.\n                        result = -lambda;\n                        if (left != 0) {\n                            // Also use Proposition 6 (ii).\n                            double result_1 = log_c_m_inf + i * log(1 - i/(double) (m+1));\n                            \n                            // Take the maximum.\n                            if (result_1 > result) {\n                                result = result_1;\n                            }\n                        }\n                    }\n                    if (result <= tau) {\n                        int64_t const log10_result = static_cast<int64_t>(std::floor(result * log10_e));\n                        STORM_LOG_WARN(\"Fox-Glynn: lambda >= 25, underflow near Poi(\" << lambda << \",\" << left << \") <= \" << std::exp(result - log10_result/log10_e) << log10_result << \". The results are unreliable.\");\n                    }\n                    \n                    // We still have to perform an underflow check for the right truncation point when lambda >= 400.\n                    if (m >= 400) {\n                        // Use Proposition 5 of Fox--Glynn.\n                        i = right - m;\n                        result = log_c_m_inf - i * (i + 1) / (2 * lambda);\n                        if (result <= tau) {\n                            int64_t const log10_result = static_cast<int64_t>(std::floor(result * log10_e));\n                            STORM_LOG_WARN(\"Fox-Glynn: lambda >= 25, underflow near Poi(\" << lambda << \",\" << right << \") <= \" << std::exp(result - log10_result/log10_e) << log10_result << \". The results are unreliable.\");\n                        }\n                    }\n                }\n                \n                return fgresult;\n            }\n            \n            template<typename ValueType>\n            FoxGlynnResult<ValueType> foxGlynnWeighter(ValueType lambda, ValueType epsilon) {\n                ValueType tau = std::numeric_limits<ValueType>::min();\n\n                // The magic m point.\n                uint64_t m = static_cast<uint64_t>(lambda);\n                int64_t j, t;\n\n                FoxGlynnResult<ValueType> result = foxGlynnFinder(lambda, epsilon);\n                \n                // Fill the left side of the array.\n                for (j = m - result.left; j > 0; --j) {\n                    result.weights[j - 1] = (j + result.left) / lambda * result.weights[j];\n                }\n                \n                t = result.right - result.left;\n                \n                // Fill the right side of the array, have two cases lambda < 400 & lambda >= 400.\n                if (m < 400) {\n                    // Perform the underflow check, according to Fox-Glynn.\n                    STORM_LOG_ERROR_COND(result.right <= 600, \"Fox-Glynn: \" << result.right << \" > 600, underflow is possible.\");\n\n                    // Compute weights.\n                    for (j = m - result.left; j < t; ++j) {\n                        ValueType q = lambda / (j + 1 + result.left);\n                        if (result.weights[j] > tau / q) {\n                            result.weights[j + 1] = q * result.weights[j];\n                        } else {\n                            t = j;\n                            result.right = j + result.left;\n                            result.weights.resize(result.right - result.left + 1);\n                            \n                            // It's time to compute W.\n                            break;\n                        }\n                    }\n                } else {\n                    // Compute weights.\n                    for (j = m - result.left; j < t; ++j) {\n                        result.weights[j + 1] = lambda / (j + 1 + result.left) * result.weights[j];\n                    }\n                }\n                \n                // It is time to compute the normalization weight W.\n                result.totalWeight = storm::utility::zero<ValueType>();\n                j = 0;\n                \n                // t was set above.\n                while(j < t) {\n                    if (result.weights[j] <= result.weights[t]) {\n                        result.totalWeight += result.weights[j];\n                        j++;\n                    } else {\n                        result.totalWeight += result.weights[t];\n                        t--;\n                    }\n                }\n                result.totalWeight += result.weights[j];\n                \n                STORM_LOG_TRACE(\"Fox-Glynn: ltp = \" << result.left << \", rtp = \" << result.right << \", w = \" << result.totalWeight << \", \" << result.weights.size() << \" weights.\");\n                \n                return result;\n            }\n            \n            template<typename ValueType>\n            FoxGlynnResult<ValueType> foxGlynn(ValueType lambda, ValueType epsilon) {\n                STORM_LOG_THROW(lambda > 0, storm::exceptions::InvalidArgumentException, \"Fox-Glynn requires positive lambda.\");\n                return foxGlynnWeighter(lambda, epsilon);\n            }\n\n            template FoxGlynnResult<double> foxGlynn(double lambda, double epsilon);\n            \n        }\n    }\n}\n", "meta": {"hexsha": "2c40d7680e82cbd802c40f4ec920cf92d17427c3", "size": 14506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "artifact/storm/src/storm/utility/numerical.cpp", "max_stars_repo_name": "glatteis/tacas21-artifact", "max_stars_repo_head_hexsha": "30b4f522bd3bdb4bebccbfae93f19851084a3db5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "artifact/storm/src/storm/utility/numerical.cpp", "max_issues_repo_name": "glatteis/tacas21-artifact", "max_issues_repo_head_hexsha": "30b4f522bd3bdb4bebccbfae93f19851084a3db5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "artifact/storm/src/storm/utility/numerical.cpp", "max_forks_repo_name": "glatteis/tacas21-artifact", "max_forks_repo_head_hexsha": "30b4f522bd3bdb4bebccbfae93f19851084a3db5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-05T12:39:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T12:39:53.000Z", "avg_line_length": 52.3682310469, "max_line_length": 222, "alphanum_fraction": 0.4442299738, "num_tokens": 3055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5177967272046424}}
{"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 <cmath>\n#include <cfloat>\n#include <cstdint>\n#include <limits>\n#include <stdexcept>\n#include <iostream>\n#include <type_traits>\n#include <boost/math/ccmath/round.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\ntemplate <typename T>\nconstexpr void test()\n{\n    if constexpr (std::numeric_limits<T>::has_quiet_NaN)\n    {\n        static_assert(boost::math::ccmath::isnan(boost::math::ccmath::round(std::numeric_limits<T>::quiet_NaN())), \"If x is NaN, NaN is returned\");\n        static_assert(boost::math::ccmath::lround(std::numeric_limits<T>::quiet_NaN()) == T(0), \"If x is NaN, 0 is returned\");\n        static_assert(boost::math::ccmath::llround(std::numeric_limits<T>::quiet_NaN()) == T(0), \"If x is NaN, 0 is returned\");\n    }\n\n    static_assert(boost::math::ccmath::round(T(0)) == T(0));\n    static_assert(boost::math::ccmath::lround(T(0)) == 0l);\n    static_assert(boost::math::ccmath::llround(T(0)) == 0ll);\n\n    static_assert(boost::math::ccmath::round(T(-0)) == T(-0));\n    static_assert(boost::math::ccmath::lround(T(-0)) == -0l);\n    static_assert(boost::math::ccmath::llround(T(-0)) == -0ll);\n\n    static_assert(boost::math::ccmath::isinf(boost::math::ccmath::round(std::numeric_limits<T>::infinity())));\n    static_assert(boost::math::ccmath::lround(std::numeric_limits<T>::infinity()) == 0l);\n    static_assert(boost::math::ccmath::llround(std::numeric_limits<T>::infinity()) == 0ll);\n\n    static_assert(boost::math::ccmath::round(T(2.3)) == T(2));\n    static_assert(boost::math::ccmath::round(T(2.5)) == T(3));\n    static_assert(boost::math::ccmath::round(T(2.7)) == T(3));\n    static_assert(boost::math::ccmath::round(T(-2.3)) == T(-2));\n    static_assert(boost::math::ccmath::round(T(-2.5)) == T(-3));\n    static_assert(boost::math::ccmath::round(T(-2.7)) == T(-3));\n\n    static_assert(boost::math::ccmath::lround(T(2.3)) == 2l);\n    static_assert(boost::math::ccmath::lround(T(2.5)) == 3l);\n    static_assert(boost::math::ccmath::lround(T(2.7)) == 3l);\n    static_assert(boost::math::ccmath::lround(T(-2.3)) == -2l);\n    static_assert(boost::math::ccmath::lround(T(-2.5)) == -3l);\n    static_assert(boost::math::ccmath::lround(T(-2.7)) == -3l);\n\n    static_assert(boost::math::ccmath::llround(T(2.3)) == 2ll);\n    static_assert(boost::math::ccmath::llround(T(2.5)) == 3ll);\n    static_assert(boost::math::ccmath::llround(T(2.7)) == 3ll);\n    static_assert(boost::math::ccmath::llround(T(-2.3)) == -2ll);\n    static_assert(boost::math::ccmath::llround(T(-2.5)) == -3ll);\n    static_assert(boost::math::ccmath::llround(T(-2.7)) == -3ll);\n}\n\n#if !defined(BOOST_MATH_NO_CONSTEXPR_DETECTION) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\nint main()\n{\n    test<float>();\n    test<double>();\n\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test<long double>();\n    #endif\n    \n    #ifdef BOOST_HAS_FLOAT128\n    test<boost::multiprecision::float128>();\n    #endif\n\n    return 0;\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "5ac4d35371c87ce5746e3dd9b417b3643b628d19", "size": 3295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ccmath_round_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/ccmath_round_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/ccmath_round_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": 37.8735632184, "max_line_length": 147, "alphanum_fraction": 0.6597875569, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5177938478621614}}
{"text": "//\n// Copyright 2005-2007 Adobe Systems Incorporated\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#include <boost/gil/extension/io/jpeg.hpp>\n#include <boost/gil/image.hpp>\n#include <boost/gil/typedefs.hpp>\n\n// Example for convolve_rows() and convolve_cols() in the numeric extension\n\nusing namespace boost::gil;\n\n// Models a Unary Function\ntemplate <typename P> // Models PixelValueConcept\nstruct mandelbrot_fn {\n  using point_t = boost::gil::point_t;\n  using const_t = mandelbrot_fn;\n  using value_type = P;\n  using reference = value_type;\n  using const_reference = value_type;\n  using argument_type = point_t;\n  using result_type = reference;\n  static constexpr bool is_mutable = false;\n\n  value_type _in_color, _out_color;\n  point_t _img_size;\n  static const int MAX_ITER = 100; // max number of iterations\n\n  mandelbrot_fn() {}\n  mandelbrot_fn(const point_t &sz, const value_type &in_color,\n                const value_type &out_color)\n      : _in_color(in_color), _out_color(out_color), _img_size(sz) {}\n\n  result_type operator()(const point_t &p) const {\n    // normalize the coords to (-2..1, -1.5..1.5)\n    // (actually make y -1.0..2 so it is asymmetric, so we can verify some view\n    // factory methods)\n    double t = get_num_iter(\n        point<double>(p.x / (double)_img_size.x * 3 - 2,\n                      p.y / (double)_img_size.y * 3 - 1.0f)); // 1.5f));\n    t = pow(t, 0.2);\n\n    value_type ret;\n    for (int k = 0; k < num_channels<P>::value; ++k)\n      ret[k] = (typename channel_type<P>::type)(_in_color[k] * t +\n                                                _out_color[k] * (1 - t));\n    return ret;\n  }\n\nprivate:\n  double get_num_iter(const point<double> &p) const {\n    point<double> Z(0, 0);\n    for (int i = 0; i < MAX_ITER; ++i) {\n      Z = point<double>(Z.x * Z.x - Z.y * Z.y + p.x, 2 * Z.x * Z.y + p.y);\n      if (Z.x * Z.x + Z.y * Z.y > 4)\n        return i / (double)MAX_ITER;\n    }\n    return 0;\n  }\n};\n\nint main() {\n  using deref_t = mandelbrot_fn<rgb8_pixel_t>;\n  using point_t = deref_t::point_t;\n  using locator_t = virtual_2d_locator<deref_t, false>;\n  using my_virt_view_t = image_view<locator_t>;\n\n  boost::function_requires<PixelLocatorConcept<locator_t>>();\n  gil_function_requires<StepIteratorConcept<locator_t::x_iterator>>();\n\n  point_t dims(200, 200);\n  my_virt_view_t mandel(dims, locator_t(point_t(0, 0), point_t(1, 1),\n                                        deref_t(dims, rgb8_pixel_t(255, 0, 255),\n                                                rgb8_pixel_t(0, 255, 0))));\n  write_view(\"out-mandelbrot.jpg\", mandel, jpeg_tag{});\n\n  return 0;\n}\n", "meta": {"hexsha": "b54073f518c9fe4fd29edb5b80a6a4390285dba5", "size": 2712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/mandelbrot.cpp", "max_stars_repo_name": "sdebionne/gil-reformated", "max_stars_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "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/mandelbrot.cpp", "max_issues_repo_name": "sdebionne/gil-reformated", "max_issues_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "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/mandelbrot.cpp", "max_forks_repo_name": "sdebionne/gil-reformated", "max_forks_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "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.0731707317, "max_line_length": 80, "alphanum_fraction": 0.633480826, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5177938425997552}}
{"text": "//\n// Created by jhwangbo on 17.04.17.\n//\n\n#ifndef RAI_DLCTRL_SIMPLEMLP_HPP\n#define RAI_DLCTRL_SIMPLEMLP_HPP\n\n#include <string>\n#include <vector>\n#include <Eigen/Dense>\n#include <cstdlib>\n#include \"iostream\"\n#include <fstream>\n#include <cmath>\n\nnamespace RAI {\n\ntemplate<int StateDim, int ActionDim>\nclass MLP_fullyconnected {\n\n public:\n  MLP_fullyconnected(const std::vector<int>& hiddensizes) \n  // :    act_(activation) \n  {\n    const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, \", \", \"\\n\");\n\n    layersizes.push_back(StateDim);\n    layersizes.reserve(layersizes.size() + hiddensizes.size());\n    layersizes.insert(layersizes.end(), hiddensizes.begin(), hiddensizes.end());\n    layersizes.push_back(ActionDim);\n    ///[input hidden output]\n\n    params.resize(2 * (layersizes.size() - 1));\n    Ws.resize(layersizes.size() - 1);\n    bs.resize(layersizes.size() - 1);\n    lo.resize(layersizes.size());\n  }\n\n  bool readPolicyFromFile(const std::string& fileName) {\n    std::stringstream parameterFileName;\n    std::ifstream indata;\n    indata.open(fileName);\n    std::string line;\n    getline(indata, line);\n    std::stringstream lineStream(line);\n    std::string cell;\n\n    ///assign parameters\n    for (int i = 0; i < params.size(); i++) {\n      int paramSize = 0;\n\n      if (i % 2 == 0) ///W resize\n      {\n        Ws[i / 2].resize(layersizes[i / 2 + 1], layersizes[i / 2]);\n        params[i].resize(layersizes[i / 2] * layersizes[i / 2 + 1]);\n      }\n      if (i % 2 == 1) ///b resize\n      {\n        bs[(i - 1) / 2].resize(layersizes[(i + 1) / 2]);\n        params[i].resize(layersizes[(i + 1) / 2]);\n      }\n\n      while (std::getline(lineStream, cell, ',')) { ///Read param\n        params[i](paramSize++) = std::stof(cell);\n        if (paramSize == params[i].size()) break;\n      }\n      if (i % 2 == 0) ///W copy\n        memcpy(Ws[i / 2].data(), params[i].data(), sizeof(double) * Ws[i / 2].size());\n      if (i % 2 == 1) ///b copy\n        memcpy(bs[(i - 1) / 2].data(), params[i].data(), sizeof(double) * bs[(i - 1) / 2].size());\n    }\n\n    return true;\n  }\n\n\n  Eigen::VectorXd forward(Eigen::VectorXd state) {\n    lo[0] = state;\n    for (int cnt = 0; cnt < Ws.size() - 1; cnt++) {\n      lo[cnt + 1] = Ws[cnt] * lo[cnt] + bs[cnt];\n\n      for (int i = 0; i < lo[cnt + 1].size(); i++) {\n        // if (act_.compare(\"tanh\") == 0) {\n          lo[cnt + 1][i] = std::tanh(lo[cnt + 1][i]);\n        // }\n        // else if (act_.compare(\"relu\") == 0) {\n          // if (lo[cnt + 1][i] < 0) lo[cnt + 1][i] = 0;\n        // }\n        // else if (act_.compare(\"softsign\") == 0) {\n          // lo[cnt + 1][i] =  lo[cnt + 1][i] / (std::abs( lo[cnt + 1][i]) + 1.0);\n        // }\n      }\n    }\n\n    lo[lo.size() - 1] = Ws[Ws.size() - 1] * lo[lo.size() - 2] + bs[bs.size() - 1]; /// output layer\n\n    return lo[lo.size() - 1];\n  }\n private:\n\n//Eigen::MatrixXd output_;\n  std::vector<Eigen::VectorXd> params;\n  std::vector<Eigen::MatrixXd> Ws;\n  std::vector<Eigen::VectorXd> bs;\n  std::vector<Eigen::VectorXd> lo;\n\n  std::vector<int> layersizes;\n};\n\n}\n\n\n#endif //RAI_SIMPLEMLP_HPP \n", "meta": {"hexsha": "d15b73f1b3cf5703d82ac0a48ef1a4179836c8d4", "size": 3106, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cerberus_anymal_control/include/cerberus_anymal_control/controllers/SimpleMLPLayer.hpp", "max_stars_repo_name": "heuristicus/cerberus_anymal_locomotion", "max_stars_repo_head_hexsha": "75f53e9a0ea267f62657bd90b9db95a884cd5ccb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-04-21T11:37:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T15:30:20.000Z", "max_issues_repo_path": "cerberus_anymal_control/include/cerberus_anymal_control/controllers/SimpleMLPLayer.hpp", "max_issues_repo_name": "heuristicus/cerberus_anymal_locomotion", "max_issues_repo_head_hexsha": "75f53e9a0ea267f62657bd90b9db95a884cd5ccb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-04-22T13:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-12T17:20:18.000Z", "max_forks_repo_path": "cerberus_anymal_control/include/cerberus_anymal_control/controllers/SimpleMLPLayer.hpp", "max_forks_repo_name": "heuristicus/cerberus_anymal_locomotion", "max_forks_repo_head_hexsha": "75f53e9a0ea267f62657bd90b9db95a884cd5ccb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-03T07:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T12:02:11.000Z", "avg_line_length": 27.2456140351, "max_line_length": 101, "alphanum_fraction": 0.5569864778, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.5177938423743995}}
{"text": "#include <iostream>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"utils.hpp\"\n\nnamespace ublas  = boost::numeric::ublas;\n\nstatic const double TOL(1.0e-5); ///< Used for comparing two real numbers.\nstatic const int n(10);           ///< defines the test matrix size\n\ntemplate<class mat, class vec>\ndouble diff(const mat& A, const vec& x, const vec& b) {\n  return ublas::norm_2(prod(A, x) - b);\n}\n\n// efficiently fill matrix depending on majority\ntemplate<class mat>\nvoid fill_matrix(mat& A, ublas::column_major_tag) {\n  for (int i=0; i<n; ++i) {\n    if (i-1>=0) {\n      A(i-1, i) = -1;\n    }\n    A(i, i) = 1;\n    if (i+1<n) {\n      A(i+1, i) = -2;\n    }\n  }\n}\ntemplate<class mat>\nvoid fill_matrix(mat& A, ublas::row_major_tag) {\n  for (int i=0; i<n; ++i) {\n    if (i-1>=0) {\n      A(i, i-1) = -1;\n    }\n    A(i, i) = 1;\n    if (i+1<n) {\n      A(i, i+1) = -2;\n    }\n  }\n}\n\ntemplate<class mat>\nBOOST_UBLAS_TEST_DEF ( test_inplace_solve )\n{\n  mat A(n, n);\n  A.clear();\n  fill_matrix(A, typename mat::orientation_category());\n\n  ublas::vector<double>  b(n, 1.0);\n\n  // The test matrix is not triangular, but is interpreted that way by\n  // inplace_solve using the lower_tag/upper_tags. For checking, the\n  // triangular_adaptor makes A triangular for comparison.\n  {\n    ublas::vector<double>  x(b);\n    ublas::inplace_solve(A, x, ublas::lower_tag());\n    BOOST_UBLAS_TEST_CHECK(diff(ublas::triangular_adaptor<mat, ublas::lower>(A), x, b) < TOL);\n  }\n  {\n    ublas::vector<double>  x(b);\n    ublas::inplace_solve(A, x, ublas::upper_tag());\n    BOOST_UBLAS_TEST_CHECK(diff (ublas::triangular_adaptor<mat, ublas::upper>(A), x, b) < TOL);\n  }\n  {\n    ublas::vector<double>  x(b);\n    ublas::inplace_solve(x, A, ublas::lower_tag());\n    BOOST_UBLAS_TEST_CHECK(diff (trans(ublas::triangular_adaptor<mat, ublas::lower>(A)), x, b) < TOL);\n  }\n  {\n    ublas::vector<double>  x(b);\n    ublas::inplace_solve(x, A, ublas::upper_tag());\n    BOOST_UBLAS_TEST_CHECK(diff (trans(ublas::triangular_adaptor<mat, ublas::upper>(A)), x , b) < TOL);\n  }\n}\n\nint main() {\n\n  // typedefs are needed as macros do not work with \",\" in template arguments\n  typedef ublas::compressed_matrix<double, ublas::row_major>     commat_doub_rowmaj;\n  typedef ublas::compressed_matrix<double, ublas::column_major>  commat_doub_colmaj;\n  typedef ublas::matrix<double, ublas::row_major>                mat_doub_rowmaj;\n  typedef ublas::matrix<double, ublas::column_major>             mat_doub_colmaj;\n  typedef ublas::mapped_matrix<double, ublas::row_major>         mapmat_doub_rowmaj;\n  typedef ublas::mapped_matrix<double, ublas::column_major>      mapmat_doub_colmaj;\n  typedef ublas::coordinate_matrix<double, ublas::row_major>     cormat_doub_rowmaj;\n  typedef ublas::coordinate_matrix<double, ublas::column_major>  cormat_doub_colmaj;\n  typedef ublas::mapped_vector_of_mapped_vector<double, ublas::row_major> mvmv_doub_rowmaj;\n  typedef ublas::mapped_vector_of_mapped_vector<double, ublas::column_major> mvmv_doub_colmaj;\n\n  BOOST_UBLAS_TEST_BEGIN();\n\n#ifdef USE_MATRIX\n  BOOST_UBLAS_TEST_DO( test_inplace_solve<mat_doub_rowmaj> );\n  BOOST_UBLAS_TEST_DO( test_inplace_solve<mat_doub_colmaj> );\n#endif\n\n#ifdef USE_COMPRESSED_MATRIX\n  BOOST_UBLAS_TEST_DO( test_inplace_solve<commat_doub_rowmaj> );\n  BOOST_UBLAS_TEST_DO( test_inplace_solve<commat_doub_colmaj> );\n#endif\n\n#ifdef USE_MAPPED_MATRIX\n  BOOST_UBLAS_TEST_DO( test_inplace_solve<mapmat_doub_rowmaj> );\n  BOOST_UBLAS_TEST_DO( test_inplace_solve<mapmat_doub_colmaj> );\n#endif\n\n#ifdef USE_COORDINATE_MATRIX\n  BOOST_UBLAS_TEST_DO( test_inplace_solve<cormat_doub_rowmaj> );\n  BOOST_UBLAS_TEST_DO( test_inplace_solve<cormat_doub_colmaj> );\n#endif\n\n#ifdef USE_MAPPED_VECTOR_OF_MAPPED_VECTOR\n  BOOST_UBLAS_TEST_DO( test_inplace_solve<mvmv_doub_rowmaj> );\n  BOOST_UBLAS_TEST_DO( test_inplace_solve<mvmv_doub_colmaj> );\n#endif\n\n  BOOST_UBLAS_TEST_END();\n}\n", "meta": {"hexsha": "0ff8bf9d97b4fd5adff156f0836ab92c4195fa3b", "size": 4047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/numeric/ublas/test/test_inplace_solve.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/numeric/ublas/test/test_inplace_solve.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/numeric/ublas/test/test_inplace_solve.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": 32.6370967742, "max_line_length": 103, "alphanum_fraction": 0.7116382506, "num_tokens": 1246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5177938311735193}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2008 Andreas Gaida\n Copyright (C) 2008 Ralph Schreyer\n Copyright (C) 2008, 2019 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#include <ql/math/functional.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/distributions/chisquaredistribution.hpp>\n#include <ql/math/interpolations/linearinterpolation.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/termstructures/volatility/equityfx/localvoltermstructure.hpp>\n#include <ql/methods/finitedifferences/meshers/fdmhestonvariancemesher.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <set>\n#include <algorithm>\n\nnamespace QuantLib {\n\n    namespace {\n        struct interpolated_volatility {\n            interpolated_volatility(const std::vector<Real>& pGrid,\n                                    const std::vector<Real>& vGrid)\n            : variance(pGrid.begin(), pGrid.end(), vGrid.begin()) {}\n            Real operator()(Real x) const {\n                return std::sqrt(variance(x, true));\n            }\n            LinearInterpolation variance;\n        };\n    }\n\n    FdmHestonVarianceMesher::FdmHestonVarianceMesher(\n        Size size,\n        const ext::shared_ptr<HestonProcess> & process,\n        Time maturity, Size tAvgSteps, Real epsilon,\n        Real mixingFactor)\n        : Fdm1dMesher(size) {\n\n        std::vector<Real> vGrid(size, 0.0), pGrid(size, 0.0);\n        const Real mixedSigma = process->sigma()*mixingFactor;\n        const Real df  = 4*process->theta()*process->kappa()/squared(mixedSigma);\n        try {\n            std::multiset<std::pair<Real, Real> > grid;\n            \n            for (Size l=1; l<=tAvgSteps; ++l) {\n                const Real t = (maturity*l)/tAvgSteps;\n                const Real ncp = 4*process->kappa()*std::exp(-process->kappa()*t)/(squared(mixedSigma)\n                    *(1-std::exp(-process->kappa()*t)))*process->v0();\n                const Real k = squared(mixedSigma)\n                    *(1-std::exp(-process->kappa()*t))/(4*process->kappa());\n\n                const Real qMin = 0.0; // v_min = 0.0;\n                const Real qMax = std::max(process->v0(),\n                    k*InverseNonCentralCumulativeChiSquareDistribution(\n                                            df, ncp, 100, 1e-8)(1-epsilon));\n\n                const Real minVStep=(qMax-qMin)/(50*size);\n                Real ps,p = 0.0;\n\n                Real vTmp = qMin;\n                grid.insert(std::pair<Real, Real>(qMin, epsilon));\n                \n                for (Size i=1; i < size; ++i) {\n                    ps = (1 - epsilon - p)/(size-i);\n                    p += ps;\n                    const Real tmp = k*InverseNonCentralCumulativeChiSquareDistribution(\n                        df, ncp, 100, 1e-8)(p);\n\n                    const Real vx = std::max(vTmp+minVStep, tmp);\n                    p = NonCentralCumulativeChiSquareDistribution(df, ncp)(vx/k);\n                    vTmp=vx;\n                    grid.insert(std::pair<Real, Real>(vx, p));\n                }\n            }\n            QL_REQUIRE(grid.size() == size*tAvgSteps, \n                       \"something wrong with the grid size\");\n            \n            const std::vector<std::pair<Real, Real> > tp(grid.begin(), grid.end());\n\n            for (Size i=0; i < size; ++i) {\n                const Size b = (i*tp.size())/size;\n                const Size e = ((i+1)*tp.size())/size;\n                for (Size j=b; j < e; ++j) {\n                    vGrid[i]+=tp[j].first/(e-b);\n                    pGrid[i]+=tp[j].second/(e-b);\n                }\n            }\n        } \n        catch (const Error&) {\n            // use default mesh\n            const Real vol = mixedSigma*\n                std::sqrt(process->theta()/(2*process->kappa()));\n\n            const Real mean = process->theta();\n            const Real upperBound = std::max(process->v0()+4*vol, mean+4*vol);\n            const Real lowerBound\n                = std::max(0.0, std::min(process->v0()-4*vol, mean-4*vol));\n\n            for (Size i=0; i < size; ++i) {\n                pGrid[i] = i/(size-1.0);\n                vGrid[i] = lowerBound + i*(upperBound-lowerBound)/(size-1.0);\n            }\n        }\n\n        Real skewHint = ((process->kappa() != 0.0) \n                ? std::max(1.0, mixedSigma/process->kappa()) : 1.0);\n\n        std::sort(pGrid.begin(), pGrid.end());\n        volaEstimate_ = GaussLobattoIntegral(100000, 1e-4)(\n            interpolated_volatility(pGrid, vGrid),\n                pGrid.front(), pGrid.back())*std::pow(skewHint, 1.5);\n\n        const Real v0 = process->v0();\n        for (Size i=1; i<vGrid.size(); ++i) {\n            if (vGrid[i-1] <= v0 && vGrid[i] >= v0) {\n                if (std::fabs(vGrid[i-1] - v0) < std::fabs(vGrid[i] - v0))\n                    vGrid[i-1] = v0;\n                else\n                    vGrid[i] = v0;\n            }\n        }\n\n        std::copy(vGrid.begin(), vGrid.end(), locations_.begin());\n\n        for (Size i=0; i < size-1; ++i) {\n            dminus_[i+1] = dplus_[i] = vGrid[i+1] - vGrid[i];\n        }\n        dplus_.back() = dminus_.front() = Null<Real>();\n    }\n\n\n    FdmHestonLocalVolatilityVarianceMesher::FdmHestonLocalVolatilityVarianceMesher(\n        Size size,\n        const ext::shared_ptr<HestonProcess>& process,\n        const ext::shared_ptr<LocalVolTermStructure>& leverageFct,\n        Time maturity, Size tAvgSteps, Real epsilon,\n        Real mixingFactor)\n     : Fdm1dMesher(size) {\n\n        const FdmHestonVarianceMesher mesher(\n            size, process, maturity, tAvgSteps, epsilon, mixingFactor);\n\n        for (Size i=0; i < size; ++i) {\n            dplus_[i] = mesher.dplus(i);\n            dminus_[i] = mesher.dminus(i);\n            locations_[i] = mesher.location(i);\n        }\n\n        volaEstimate_ = mesher.volaEstimate();\n\n        if (leverageFct != nullptr) {\n            typedef boost::accumulators::accumulator_set<\n                Real, boost::accumulators::stats<\n                    boost::accumulators::tag::mean> >\n                accumulator_set;\n\n            accumulator_set acc;\n\n            const Real s0 = process->s0()->value();\n\n            acc(leverageFct->localVol(0, s0, true));\n\n            const Handle<YieldTermStructure> rTS = process->riskFreeRate();\n            const Handle<YieldTermStructure> qTS = process->dividendYield();\n\n            for (Size l=1; l <= tAvgSteps; ++l) {\n                const Real t = (maturity*l)/tAvgSteps;\n                const Real vol = volaEstimate_ * boost::accumulators::mean(acc);\n\n                const Real fwd = s0*qTS->discount(t)/rTS->discount(t);\n\n                const Size sAvgSteps = 50;\n\n                std::vector<Real> u(sAvgSteps), sig(sAvgSteps);\n\n                for (Size i=0; i < sAvgSteps; ++i) {\n                    u[i] = epsilon + ((1-2*epsilon)/(sAvgSteps-1))*i;\n                    const Real x = InverseCumulativeNormal()(u[i]);\n\n                    const Real gf = x*vol*std::sqrt(t);\n                    const Real f = fwd*std::exp(gf);\n\n                    sig[i] = squared(leverageFct->localVol(t, f, true));\n                }\n\n                const Real leverageAvg =\n                    GaussLobattoIntegral(10000, 1e-4)(\n                        interpolated_volatility(u, sig), u.front(), u.back())\n                    / (1-2*epsilon);\n\n                acc(leverageAvg);\n            }\n            volaEstimate_ *= boost::accumulators::mean(acc);\n        }\n    }\n}\n", "meta": {"hexsha": "ca805cc2b954fb6882bdf625969a196af304318a", "size": 8270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/methods/finitedifferences/meshers/fdmhestonvariancemesher.cpp", "max_stars_repo_name": "mshojatalab/QuantLib", "max_stars_repo_head_hexsha": "7801a0fb3226bc1b001e310bacdd35ddb2e51661", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T12:21:33.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-21T12:21:33.000Z", "max_issues_repo_path": "ql/methods/finitedifferences/meshers/fdmhestonvariancemesher.cpp", "max_issues_repo_name": "mshojatalab/QuantLib", "max_issues_repo_head_hexsha": "7801a0fb3226bc1b001e310bacdd35ddb2e51661", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-03-09T16:19:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:33:42.000Z", "max_forks_repo_path": "ql/methods/finitedifferences/meshers/fdmhestonvariancemesher.cpp", "max_forks_repo_name": "sweemer/QuantLib", "max_forks_repo_head_hexsha": "1341223e3d839dd77bb7231d0913809f01437740", "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.6448598131, "max_line_length": 102, "alphanum_fraction": 0.5420798065, "num_tokens": 2107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.5888891307678321, "lm_q1q2_score": 0.5177199794653873}}
{"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/FluidDataSet.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/FluidTensor.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <queue>\n#include <string>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass KMeans\n{\n\npublic:\n  void clear()\n  {\n    mMeans.setZero();\n    mAssignments.setZero();\n    mTrained = false;\n  }\n\n  bool initialized() const { return mTrained; }\n\n  void train(const FluidDataSet<std::string, double, 1>& dataset, index k,\n             index maxIter)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    assert(!mTrained || (dataset.pointSize() == mDims && mK == k));\n    auto dataPoints = asEigen<Array>(dataset.getData());\n    if (mTrained) { mAssignments = assignClusters(dataPoints); }\n    else\n    {\n      mK = k;\n      mDims = dataset.pointSize();\n      mMeans = ArrayXXd::Zero(mK, mDims);\n      mEmpty = std::vector<bool>(asUnsigned(mK), false);\n      mAssignments =\n          ((0.5 + (0.5 * ArrayXf::Random(dataPoints.rows()))) * (mK - 1))\n              .round()\n              .cast<int>();\n    }\n\n    while (maxIter-- > 0)\n    {\n      computeMeans(dataPoints);\n      auto assignments = assignClusters(dataPoints);\n      if (!changed(assignments)) { break; }\n      else\n      {\n        mAssignments = assignments;\n      }\n    }\n    mTrained = true;\n  }\n\n  index getClusterSize(index cluster) const\n  {\n    index count = 0;\n    for (index i = 0; i < mAssignments.size(); i++)\n    {\n      if (mAssignments(i) == cluster) count++;\n    }\n    return count;\n  }\n\n  index vq(RealVectorView point) const\n  {\n    assert(point.size() == mDims);\n    return assignPoint(_impl::asEigen<Eigen::Array>(point));\n  }\n\n  void getMeans(RealMatrixView out) const\n  {\n    if (mTrained) out <<= _impl::asFluid(mMeans);\n  }\n\n  void setMeans(RealMatrixView means)\n  {\n    mMeans = _impl::asEigen<Eigen::Array>(means);\n    mDims = mMeans.cols();\n    mK = mMeans.rows();\n    mEmpty = std::vector<bool>(asUnsigned(mK), false);\n    mTrained = true;\n  }\n\n  index dims() const { return mMeans.cols(); }\n  index size() const { return mMeans.rows(); }\n  index getK() const { return mMeans.rows(); }\n  index nAssigned() const { return mAssignments.size(); }\n\n  void getAssignments(FluidTensorView<index, 1> out) const\n  {\n    out <<= _impl::asFluid(mAssignments);\n  }\n\n  void transform(RealMatrixView data, RealMatrixView out) const\n  {\n    Eigen::ArrayXXd points = _impl::asEigen<Eigen::Array>(data);\n    Eigen::ArrayXXd D = fluid::algorithm::DistanceMatrix(points, 2);\n    Eigen::MatrixXd means = mMeans.matrix();\n    D = fluid::algorithm::DistanceMatrix<Eigen::ArrayXXd>(points, mMeans, 2);\n    out <<= _impl::asFluid(D);\n  }\n\nprotected:\n  double distance(const Eigen::ArrayXd&  v1, const Eigen::ArrayXd& v2) const\n  {\n    return (v1 - v2).matrix().norm();\n  }\n\n  index assignPoint(Eigen::ArrayXd point) const\n  {\n    double minDistance = std::numeric_limits<double>::infinity();\n    index  minK;\n    for (index k = 0; k < mK; k++)\n    {\n      double dist = distance(point, mMeans.row(k));\n      if (dist < minDistance)\n      {\n        minK = k;\n        minDistance = dist;\n      }\n    }\n    return minK;\n  }\n\n  Eigen::VectorXi assignClusters(Eigen::ArrayXXd dataPoints) const\n  {\n    Eigen::VectorXi assignments = Eigen::VectorXi::Zero(dataPoints.rows());\n    for (index i = 0; i < dataPoints.rows(); i++)\n    { assignments(i) = static_cast<int>(assignPoint(dataPoints.row(i))); }\n    return assignments;\n  }\n\n  void computeMeans(Eigen::ArrayXXd dataPoints)\n  {\n    using namespace Eigen;\n    for (index k = 0; k < mK; k++)\n    {\n      if (mEmpty[asUnsigned(k)]) continue;\n      std::vector<index> kAssignment;\n      for (index i = 0; i < mAssignments.size(); i++)\n      {\n        if (mAssignments(i) == k) kAssignment.push_back(i);\n      }\n      if (kAssignment.size() == 0)\n      {\n        std::cout << \"Warning: empty cluster\" << std::endl;\n        mEmpty[asUnsigned(k)] = true;\n        return;\n      }\n      ArrayXXd clusterPoints =\n          ArrayXXd::Zero(asSigned(kAssignment.size()), mDims);\n      for (index i = 0; asUnsigned(i) < kAssignment.size(); i++)\n      { clusterPoints.row(i) = dataPoints.row(kAssignment[asUnsigned(i)]); }\n      ArrayXd mean = clusterPoints.colwise().mean();\n      mMeans.row(k) = mean;\n    }\n  }\n\n  bool changed(Eigen::VectorXi newAssignments) const\n  {\n    auto dif = (newAssignments - mAssignments).cwiseAbs().sum();\n    return dif > 0;\n  }\n\n  index             mK{0};\n  index             mDims{0};\n  Eigen::ArrayXXd   mMeans;\n  std::vector<bool> mEmpty;\n  Eigen::VectorXi   mAssignments;\n  bool              mTrained{false};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "6029e140239da2b3d96cc7c98b8374c66afc549d", "size": 5176, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/KMeans.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/KMeans.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/KMeans.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": 26.9583333333, "max_line_length": 77, "alphanum_fraction": 0.6234544049, "num_tokens": 1404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5177199794653873}}
{"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 \"Sampling.h\"\n#include \"params.h\"\n#include \"FFT.h\"\n#include \"Random.h\"\n#include \"Algebra.h\"\n\nusing namespace std;\nusing namespace NTL;\n\nconst ZZX phi = Cyclo();\n\n\n//==============================================================================\n//Generates from parameters N and q :\n// - a public key : polynomial h\n// - a private key : polynomials f,g,F,G\n//==============================================================================\nvoid Keygen(ZZ_pX& PublicKey, ZZX* PrivateKey)\n{\n    ZZ SqNorm;\n    ZZX f,g,F,G;\n\n    SqNorm = conv<ZZ>(1.36*q0/2);\n\n    GenerateBasis(f, g, F, G, SqNorm);\n    PrivateKey[0] = f;\n    PrivateKey[1] = g;\n    PrivateKey[2] = F;\n    PrivateKey[3] = G;\n\n    for(unsigned int i=0; i<4; i++)\n    {\n            PrivateKey[i].SetLength(N0);\n    }\n\n    PublicKey = Quotient(f, g);\n}\n\n//==============================================================================\n//Computes the private basis B from private key PrivateKey and parameter N\n//==============================================================================\nvoid CompletePrivateKey(mat_ZZ& B, const ZZX * const PrivateKey)\n{\n    ZZX f,g,F,G;\n    f = PrivateKey[0];\n    g = PrivateKey[1];\n    F = PrivateKey[2];\n    G = PrivateKey[3];\n\n    f = -f;\n    F = -F;\n\n    B = BasisFromPolynomials(g, f, G, F);\n}\n\n\n\n\n\nvoid GPV(RR_t * v, const RR_t * const c, const RR_t s, const MSK_Data * const MSKD)\n{\n\n    int i;\n    unsigned j;\n    RR_t ci[2*N0], zi, cip, sip, aux;\n\n    for(j=0; j<2*N0;j++)\n    {\n        ci[j] = c[j];\n    }\n\n//    for(j=0; j<2*N0; j++)\n//    {\n//\n//    }    \n\n    for(i=2*N0-1; i>=0; i--)\n    {\n        aux = (MSKD->GS_Norms)[i];\n        cip = DotProduct(ci, MSKD->Bstar[i])/(aux*aux);\n        sip = s/aux;\n        zi = Sample4(cip, sip*PiPrime);\n\n        for(j=0; j<2*N0; j++)\n        {\n            ci[j] -= zi*(MSKD->B)[i][j];\n        }\n    }\n\n    for(j=0; j<2*N0; j++)\n    {\n        v[j] = c[j] - ci[j];\n    }\n\n}\n\n\n\n//==============================================================================\n//==============================================================================\n//                            MAIN PROGRAMS\n//==============================================================================\n//==============================================================================\n\n\nvoid CompleteMSK(MSK_Data * MSKD, ZZX * MSK)\n{\n    unsigned int i, j;\n    mat_ZZ B0;\n\n    for(i=0; i<4; i++)\n    {\n        MSKD->PrK[i] = MSK[i];\n        ZZXToFFT(MSKD->PrK_fft[i], MSK[i]);\n    }\n\n    CompletePrivateKey(B0, MSK);\n\n    for(i=0; i<2*N0; i++)\n    {\n        for(j=0; j<2*N0; j++)\n        {\n            MSKD->B[i][j] = ( (RR_t) conv<double>(B0[i][j]) );\n        }\n    }\n\n    for(i=0; i<1; i++)\n    {\n        FastMGS(MSKD->Bstar, MSKD->B);\n    }\n\n    for(i=0; i<2*N0; i++)\n    {\n        MSKD->GS_Norms[i] = sqrt( DotProduct(MSKD->Bstar[i], MSKD->Bstar[i]) );\n    }\n\n    MSKD->sigma = 2*MSKD->GS_Norms[0];\n\n}\n\n\n\nvoid CompleteMPK(MPK_Data * MPKD, ZZ_pX MPK)\n{\n    MPKD->h = MPK;\n    ZZXToFFT(MPKD->h_FFT, conv<ZZX>(MPK));\n}\n\n\n\nvoid PEKS_Trapdoor(ZZX SK_tr[2], vec_ZZ kw, const MSK_Data * const MSKD)\n{\n    unsigned int i;\n    RR_t c[2*N0], sk[2*N0], sigma;\n    ZZX f,g,aux;\n\n    f = MSKD -> PrK[0];\n    g = MSKD -> PrK[1];\n    sigma = MSKD->sigma;\n    SK_tr[0].SetLength(N0);\n    SK_tr[1].SetLength(N0);\n\n    for(i=0;i<N0;i++)\n    {\n        c[i] = ((RR_t) conv<double>(kw[i])) ;\n        c[i+N0] = 0;\n    }\n\n    GPV(sk, c, sigma, MSKD);\n\n    for(i=0; i<N0; i++)\n    {\n        sk[i] = c[i] - sk[i];\n        sk[i+N0] = - sk[i+N0];\n    }\n\n    for(i=0; i<N0; i++)\n    {\n        SK_tr[0][i] = sk[i];\n        SK_tr[1][i] = sk[i+N0];\n    }\n    \n}\n\n\nunsigned long PEKS_Verify_Trapdoor(const ZZX SK_tr[2], const vec_ZZ kw, const MSK_Data * const MSKD)\n{\n    unsigned int i;\n    ZZX f,g,t,aux;\n\n    f = MSKD -> PrK[0];\n    g = MSKD -> PrK[1];\n    \n    t = conv<ZZX>(kw);\n    aux = ((SK_tr[0] - t)*f + g*SK_tr[1])%phi;\n\n    for(i=0; i<N0; i++)\n    {\n        aux[i] %= q1;\n    }\n\n    if( IsZero(aux) != 0)\n    {\n        cout << \"The signature (s1,s2) doesn't verify the required equality [ (s1 - t)*f + g*s2 = 0 ] !\\nActually, (s1 - t)*f + g*s2 = \" << aux << endl << endl;\n    }\n    return IsZero(aux);\n}\n\n\nvoid PEKS_Enc(long C[3][N0],  const long id0[N0],  const MPK_Data * const MPKD)\n{\n\n    unsigned long i;\n    long r[N0], e1[N0], e2[N0];\n    CC_t r_FFT[N0], t_FFT[N0], aux1_FFT[N0], aux2_FFT[N0];\n\n\n    for(i=0; i<N0; i++)\n    {\n        e1[i] = (rand()%3) - 1;\n        e2[i] = (rand()%3) - 1;\n        r[i] = (rand()%3) - 1;\n        C[2][i] = (rand()%2);\n    }\n\n\n    MyIntFFT(r_FFT, r);\n    MyIntFFT(t_FFT, id0);\n\n    for(i=0; i<N0; i++)\n    {\n        aux1_FFT[i] = r_FFT[i]*((MPKD->h_FFT)[i]);\n        aux2_FFT[i] = r_FFT[i]*t_FFT[i];\n    } \n\n    MyIntReverseFFT(C[0], aux1_FFT);\n    MyIntReverseFFT(C[1], aux2_FFT);\n\n    for(i=0; i<N0; i++)\n    { \n        C[0][i] = (C[0][i] + e1[i]               + q0/2)%q0 - (q0/2);\n        C[1][i] = (C[1][i] + e2[i] + (q0/2)*C[2][i] + q0/2)%q0 - (q0/2);\n    } \n\n}\n\n\nbool PEKS_Test( const long C[3][N0], const CC_t * const SKtd_FFT)\n{\n    unsigned int i;\n    CC_t c0_FFT[N0], aux_FFT[N0];\n    bool fout = false ;\n    long k[N0];\n    MyIntFFT(c0_FFT, C[0]);\n\n    for(i=0; i<N0; i++)\n    {\n        aux_FFT[i] = c0_FFT[i]*SKtd_FFT[i];\n    }\n\n    MyIntReverseFFT(k, aux_FFT);\n\n    for(i=0; i<N0; i++)\n    {\n        k[i] = C[1][i] - k[i];\n        k[i] = ((unsigned long)(k[i] ))%q0;\n        k[i] = (k[i] + (q0>>2) )/(q0>>1);\n        k[i] %= 2;\n        if (C[2][i]== k[i])\n            fout = true;\n            \n        else\n            fout = false;\n     }\n   /* if (fout)\n        cout << endl<< endl<<endl <<\"  TEST algorithm has been succesful\"<< endl; */\n    return fout;\n\n}\n\n\n\n//==============================================================================\n//==============================================================================\n//                             BENCHES AND TESTS\n//                   FOR EXTRACTION AND ENCRYPTION/DECRYPTION\n//==============================================================================\n//==============================================================================\n\n\nvoid Trapdoor_Bench(const unsigned int nb_extr, MSK_Data * MSKD)\n{\n    clock_t t1, t2;\n    float diff;\n    unsigned int i;\n    vec_ZZ kw;\n    ZZX SK_tr[2];\n\n    t1 = clock();\n\n    cout << \"0%\" << flush;\n    for(i=0; i<nb_extr; i++)\n    {\n        kw = RandomVector();\n\n        PEKS_Trapdoor(SK_tr, kw, MSKD);\n        if((i+1)%(nb_extr/10)==0)\n        {\n            cout << \"...\" << (i+1)/(nb_extr/10) << \"0%\" << flush;\n        }\n    }\n\n    t2 = clock();\n    diff = ((float)t2 - (float)t1)/1000000.0F;\n    cout << \"\\n\\nIt took \" << diff << \" seconds to create  \" << nb_extr << \" trapdoors.\" << endl;\n    cout << \"That's \" << (diff/nb_extr)*1000 << \" milliseconds per trapdoor.\" << endl << endl;\n}\n\n\nvoid Encrypt_Bench(const unsigned int nb_cryp, MPK_Data * MPKD, MSK_Data * MSKD)\n{\n    clock_t te1, te2, td1, td2;\n    float diffe, diffd;\n    unsigned int i,j;\n    vec_ZZ kw;\n    ZZX SK_tr[2], w;\n    CC_t SKid_FFT[N0];\n   // long int message[N0], decrypted[N0];\n    long int keyword[N0], Ciphertext[3][N0];\n\t//bool flag = true; \n\n    kw = RandomVector();\n    PEKS_Trapdoor(SK_tr, kw, MSKD);\n    PEKS_Verify_Trapdoor(SK_tr, kw, MSKD);\n    ZZXToFFT(SKid_FFT, SK_tr[1]);\n\n    for(i=0; i<N0; i++)\n    {\n        keyword[i] = conv<long int>(kw[i]);\n    }\n\n    \n\n\n    cout << \"0%\" << flush ;\n    for(i=0; i<nb_cryp; i++)\n    {\n\n   /*     for(j=0; j<N0; j++)\n        {\n            message[j] = (rand()%2);\n        }*/\n/*\t\tfor(j=0; j<N0; j++)\n        {\n             cout << \" \"<< j<<\"th \"<< message[j] << \"\\t\"; ;\n        }*/\n\tte1 = clock();\t\n\t\tPEKS_Enc(Ciphertext, keyword, MPKD);\n\tte2 = clock();\n\n\t\n\n\ttd1 = clock();\n\t\tif (!PEKS_Test(Ciphertext, SKid_FFT)){\n\t\t\t cout << \"TEST FAILED --- Exiting...\"<<endl;\n\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\ttd2 = clock();\n\t\n        if((i+1)%(nb_cryp/10)==0)\n        {\n            cout << \"...\" << (i+1)/(nb_cryp/10) << \"0%\" << flush;\n        }\n\n\tdiffe += ((float)te2 - (float)te1)/1000000.0l;\n\tdiffd += ((float)td2 - (float)td1)/1000000.0l;\n\n    }\n\n    cout << \"\\n\\nIt took \" << diffe << \" seconds to do \" << nb_cryp << \" encryptions.\" << endl;\n    cout << \"That's \" << (diffe/nb_cryp)*1000 << \" milliseconds per PEKS generation.\" << endl;\n    cout << \"That's \" << (diffe/nb_cryp)*1000*1024/N0 << \" milliseconds per PEKS per Kilobit.\" << endl << endl;\n\n    cout << \"\\n\\nIt took \" << diffd << \" seconds to do \" << nb_cryp << \" Tests.\" << endl;\n    cout << \"That's \" << (diffd/nb_cryp)*1000 << \" milliseconds per Tests.\" << endl;\n    cout << \"That's \" << (diffd/nb_cryp)*1000*1024/N0 << \" milliseconds per Tests per Kilobit.\" << endl << endl;\n\n}\n\n\nvoid Trapdoor_Test(const unsigned int nb_extr, MSK_Data * MSKD)\n{\n    unsigned int i, rep;\n    vec_ZZ kw;\n    ZZX SK_kw[2];\n\n    rep = 0;\n\n    cout << \"0%\" << flush;\n    for(i=0; i<nb_extr; i++)\n    {\n        kw = RandomVector();\n\n        PEKS_Trapdoor(SK_kw, kw, MSKD);\n        rep += PEKS_Verify_Trapdoor(SK_kw, kw, MSKD);\n        if((i+1)%(nb_extr/10)==0)\n        {\n            cout << \"...\" << (i+1)/(nb_extr/10) << \"0%\" << flush;\n        }\n    }\n\n    cout << endl;\n    if(rep == 0)\n    {    cout << endl << nb_extr << \" Trapdoor successfully performed!\" << endl << endl;    }\n    else\n    {    cout << endl << rep << \" out of \" << nb_extr << \" extractions failed miserabily!\" << endl << endl;    }\n}\n\n\nvoid Encrypt_Test(const unsigned int nb_cryp, MPK_Data * MPKD, MSK_Data * MSKD)\n{\n    unsigned int i, j, rep;\n    vec_ZZ kw;\n    ZZX SK_td[2], m;\n    CC_t SKtd_FFT[N0];\n    long int kw0[N0], Ciphertext[2][N0];\n   // long int message[N0], decrypted[N0];\n\n\n    kw = RandomVector();\n    PEKS_Trapdoor(SK_td, kw, MSKD);\n    PEKS_Verify_Trapdoor(SK_td, kw, MSKD);\n    ZZXToFFT(SKtd_FFT, SK_td[1]);\n\n    rep = 0;\n\n    for(i=0; i<N0; i++)\n    {\n        kw0[i] = conv<long int>(kw[i]);\n\t\n\n    }\n\n    cout << \"0%\" << flush;\n    for(i=0; i<nb_cryp; i++)\n    {\n\n       /* for(j=0; j<N0; j++)\n        {\n            message[j] = (rand()%2);\n        }*/\n\n\t\tPEKS_Enc(Ciphertext, kw0, MPKD);\n        PEKS_Test(Ciphertext, SKtd_FFT);\n        \n/*        for(j=0; j<N0; j++)\n        {\n            if(message[j] != decrypted[j])\n            {\n                cout << \"ERROR : Dec(Enc(m)) != m \" << endl;\n                rep++;\n                break;\n            }\n        }*/\n\n        if((i+1)%(nb_cryp/10)==0)\n        {\n            cout << \"...\" << (i+1)/(nb_cryp/10) << \"0%\" << flush;\n        }\n    }\n\n    cout << endl;\n    if(rep == 0)\n    {    cout << endl << nb_cryp << \" PEKS+TEST successfully performed!\" << endl << endl;    }\n    else\n    {    cout << endl << rep << \" out of \" << nb_cryp << \" PEKS+TEST failed miserabily!\" << endl << endl;    }\n}\n", "meta": {"hexsha": "4d874aac25efee2a9a4a6b726c0736d10f82edae", "size": 10928, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Scheme.cc", "max_stars_repo_name": "Rbehnia/NTRUPEKS", "max_stars_repo_head_hexsha": "780d5ef54baaa6c09386185e4d4fce1dc2e394f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-09-15T01:54:10.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-25T06:55:49.000Z", "max_issues_repo_path": "Scheme.cc", "max_issues_repo_name": "Rbehnia/NTRUPEKS", "max_issues_repo_head_hexsha": "780d5ef54baaa6c09386185e4d4fce1dc2e394f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scheme.cc", "max_forks_repo_name": "Rbehnia/NTRUPEKS", "max_forks_repo_head_hexsha": "780d5ef54baaa6c09386185e4d4fce1dc2e394f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-22T21:39:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-22T21:39:45.000Z", "avg_line_length": 22.3476482618, "max_line_length": 160, "alphanum_fraction": 0.4414348463, "num_tokens": 3591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.517719975736036}}
{"text": "#include <Eigen/Dense>\n#include \"Common/Common.h\"\n#include <assert.h>\n\nnamespace Eigen\n{\n// https://stackoverflow.com/questions/25389480/how-to-write-read-an-eigen-matrix-from-binary-file\ntemplate <class Matrix>\nvoid write_binary(const std::string filename, const Matrix &matrix)\n{\n    std::ofstream out(filename, std::ios::out | std::ios::binary | std::ios::trunc);\n    typename Matrix::Index rows = matrix.rows(), cols = matrix.cols();\n    out.write((char *)(&rows), sizeof(typename Matrix::Index));\n    out.write((char *)(&cols), sizeof(typename Matrix::Index));\n    out.write((char *)matrix.data(), rows * cols * sizeof(typename Matrix::Scalar));\n    out.close();\n}\ntemplate <class Matrix>\nvoid read_binary(const std::string filename, Matrix &matrix)\n{\n    std::ifstream in(filename, std::ios::in | std::ios::binary);\n    typename Matrix::Index rows = 0, cols = 0;\n    in.read((char *)(&rows), sizeof(typename Matrix::Index));\n    in.read((char *)(&cols), sizeof(typename Matrix::Index));\n    matrix.resize(rows, cols);\n    in.read((char *)matrix.data(), rows * cols * sizeof(typename Matrix::Scalar));\n    in.close();\n}\n} // namespace Eigen\n\nclass TrajectoryData\n{\npublic:\n    TrajectoryData(std::vector<Eigen::Isometry3d> _transformations, Eigen::VectorXd _dt_inv)\n    {\n        transformations = _transformations;\n        dt_inv = _dt_inv;\n    }\n\n    TrajectoryData(std::string path_prefix)\n    {\n        // Read trajectory from directory\n        const int num_rows = 30;\n\n        transformations.resize(num_rows);\n        for (int i = 0; i < num_rows; i++)\n        {\n            // std::cout << i << std::endl;\n            Eigen::read_binary(path_prefix + std::to_string(i) + \".dat\", transformations[i].matrix());\n            // std::cout<<transformations[i].translation()<<std::endl;\n        }\n\n        Eigen::read_binary(path_prefix + \"dt.dat\", dt_inv);\n        // std::cout << dt_inv << std::endl;\n        assert(dt_inv.cols() == transformations.size());\n    }\n\n    void step(Real currentTime)\n    {\n        idx++;\n        Real dt = (idx >= dt_inv.size()) ? 1e8 : 1 / dt_inv[idx];\n        nextUpdateTime += dt;\n\n        std::cout << \"STEP:\" << idx << \"/\" << dt_inv.size() << std::endl;\n        std::cout << \"CUR:\" << currentTime << \" NEXT:\" << nextUpdateTime << std::endl;\n        std::cout << transformations[idx].translation() << std::endl\n                  << std::endl;\n    }\n\n    bool needUpdate(Real currentTime)\n    {\n        return currentTime >= nextUpdateTime;\n    }\n\n    void transform(Vector3r &pos)\n    {\n        assert(idx < dt_inv.size());\n        pos = transformations[idx] * pos;\n    }\n\n    void reset()\n    {\n        idx = 0;\n        nextUpdateTime = 0;\n    }\n\n    std::vector<Eigen::Isometry3d> transformations;\n    Eigen::VectorXd dt_inv;\n\nprivate:\n    int idx = 0;\n    Real nextUpdateTime = 0;\n};", "meta": {"hexsha": "0327c57efad6740d62c5372712e91a0e4163111d", "size": 2828, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Demos/BarDemo/helpers.hpp", "max_stars_repo_name": "taohnouaccountb/PositionBasedDynamics", "max_stars_repo_head_hexsha": "605f3de24f883315e48932a77f3fdfbd1c293ccc", "max_stars_repo_licenses": ["MIT"], "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/BarDemo/helpers.hpp", "max_issues_repo_name": "taohnouaccountb/PositionBasedDynamics", "max_issues_repo_head_hexsha": "605f3de24f883315e48932a77f3fdfbd1c293ccc", "max_issues_repo_licenses": ["MIT"], "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/BarDemo/helpers.hpp", "max_forks_repo_name": "taohnouaccountb/PositionBasedDynamics", "max_forks_repo_head_hexsha": "605f3de24f883315e48932a77f3fdfbd1c293ccc", "max_forks_repo_licenses": ["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.4086021505, "max_line_length": 102, "alphanum_fraction": 0.6032531825, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5177141494940796}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/log.hpp\n *\n * \\brief Compute the natural logarithm to each element of a vector or matrix\n *  expression.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n *\n * <hr/>\n *\n * Copyright (c) 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\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_LOG_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_LOG_HPP\n\n\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/expression/matrix_unary_functor.hpp>\n#include <boost/numeric/ublasx/expression/vector_unary_functor.hpp>\n#include <cmath>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\nnamespace detail {\n\ntemplate <typename VectorExprT>\nstruct vector_log_functor_traits\n{\n    typedef VectorExprT input_expression_type;\n    typedef typename vector_traits<input_expression_type>::value_type signature_argument_type;\n    typedef signature_argument_type signature_result_type;\n    typedef vector_unary_functor_traits<\n                input_expression_type,\n                signature_result_type (signature_argument_type)\n            > unary_functor_expression_type;\n    typedef typename unary_functor_expression_type::result_type result_type;\n    typedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\ntemplate <typename MatrixExprT>\nstruct matrix_log_functor_traits\n{\n    typedef MatrixExprT input_expression_type;\n    typedef typename matrix_traits<input_expression_type>::value_type signature_argument_type;\n    typedef signature_argument_type signature_result_type;\n    typedef matrix_unary_functor_traits<\n                input_expression_type,\n                signature_result_type (signature_argument_type)\n            > unary_functor_expression_type;\n    typedef typename unary_functor_expression_type::result_type result_type;\n    typedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\n/// Auxiliary function used to replace ::std::log2 when that is not available.\ntemplate <typename T>\nBOOST_UBLAS_INLINE\nT log(T x)\n{\n    return ::std::log(x);\n}\n\n} // Namespace detail\n\n\n/**\n * \\brief Applies the \\c std::log function to each element of a given vector\n *  expression.\n *\n * \\tparam VectorExprT The type of the input vector expression.\n *\n * \\param ve The input vector expression.\n * \\return A vector expression representing the application of \\c std::log to\n *  each element of \\a ve.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename detail::vector_log_functor_traits<VectorExprT>::result_type log(vector_expression<VectorExprT> const& ve)\n{\n    typedef typename detail::vector_log_functor_traits<VectorExprT>::expression_type expression_type;\n    typedef typename detail::vector_log_functor_traits<VectorExprT>::signature_result_type signature_result_type;\n\n    return expression_type(ve(), detail::log<signature_result_type>);\n}\n\n\n/**\n * \\brief Applies the \\c std::log function to each element of a given matrix\n *  expression.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param me The input matrix expression.\n * \\return A matrix expression representing the application of \\c std::log to\n *  each element of \\a me.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename detail::matrix_log_functor_traits<MatrixExprT>::result_type log(matrix_expression<MatrixExprT> const& me)\n{\n    typedef typename detail::matrix_log_functor_traits<MatrixExprT>::expression_type expression_type;\n    typedef typename detail::matrix_log_functor_traits<MatrixExprT>::signature_result_type signature_result_type;\n\n    return expression_type(me(), detail::log<signature_result_type>);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_LOG_HPP\n", "meta": {"hexsha": "b91e29a4b4958fcad50fbe8a49520eba18a6e409", "size": 4087, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/log.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/log.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/log.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": 32.4365079365, "max_line_length": 114, "alphanum_fraction": 0.7753853682, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5177141388447634}}
{"text": "#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/box.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/algorithms/envelope.hpp>\r\n#include <boost/geometry/io/wkt/wkt.hpp>\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n    typedef boost::geometry::model::d2::point_xy<double> point;\r\n\r\n    boost::geometry::model::polygon<point> polygon;\r\n\r\n    boost::geometry::read_wkt(\r\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)\"\r\n        \"(4.0 2.0, 4.2 1.4, 4.8 1.9, 4.4 2.2, 4.0 2.0))\", polygon);\r\n\r\n    boost::geometry::model::box<point> box;\r\n    boost::geometry::envelope(polygon, box);\r\n\r\n    std::cout << \"envelope:\" << boost::geometry::dsv(box) << std::endl;\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "2c17070a1c0d8300ad65b22a769116cfb0ae1ad7", "size": 850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sample/boost/main.cpp", "max_stars_repo_name": "bkotkowski/vcpkg", "max_stars_repo_head_hexsha": "83aa31f06389e0417e214ac3154b177c85fdbd37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sample/boost/main.cpp", "max_issues_repo_name": "bkotkowski/vcpkg", "max_issues_repo_head_hexsha": "83aa31f06389e0417e214ac3154b177c85fdbd37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sample/boost/main.cpp", "max_forks_repo_name": "bkotkowski/vcpkg", "max_forks_repo_head_hexsha": "83aa31f06389e0417e214ac3154b177c85fdbd37", "max_forks_repo_licenses": ["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.4814814815, "max_line_length": 108, "alphanum_fraction": 0.6341176471, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5177003356237339}}
{"text": "//////////////////////////////////////////////////////////////////////////////////\n// random::poisson_ex::poisson_devroye::detail::q_function::using_factorial.hpp //\n//                                                                              //\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#ifndef BOOST_RANDOM_POISSON_EXT_DEVROYE_DETAIL_Q_FUNCTION_USING_FACTORIAL_ER_2010\n#define BOOST_RANDOM_POISSON_EXT_DEVROYE_DETAIL_Q_FUNCTION_USING_FACTORIAL_ER_2010\n#include <cmath>\n#include <boost/mpl/bool.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace poisson{\nnamespace devroye{            \nnamespace q{\n\nnamespace factorial_method{\n    template<typename T,typename Int,typename P,typename IntT>\n    T fun(const Int& i_mean,const Int& i_y,const P& p,const IntT& converter);\n}\n\n    struct using_factorial{ using_factorial(){} };\n\n    template<typename T,typename Int,typename P,typename IntT>\n    T fun(const Int& i_mean,const Int& i_y,const P& p,\n        const IntT& converter,using_factorial/*method*/)\n    {\n        return factorial_method::fun<T>(i_mean,i_y,p,converter);\n    }\n\nnamespace factorial_method{\n\n    template<typename T,typename Int,typename P,typename IntT>\n    T fun(const Int& i_mean,const Int& i_y,const P& p,const IntT& converter)\n    {\n        T r = IntT::convert( 0 );\n        if(i_y!=0){\n            T m = IntT::convert( i_mean );\n            T y = IntT::convert( i_y );\n            T mp1 = IntT::convert( i_mean + 1 );\n            r += first_half(m,y,p);\n            if(i_y<0) r += second_half(m,i_y,p,boost::mpl::bool_<false>());\n            if(i_y>0) r += second_half(mp1,i_y,p,boost::mpl::bool_<true>());\n        }\n        return r;\n    }  \n\n    template<typename T,typename P>\n    T first_half(const T& m,const T& y,const P& p){ return y * log( m ); }\n\n    template<typename T,typename Int,typename P>\n    T second_half(const T& mp1,const Int& i_y,const P& p,\n        boost::mpl::bool_<true>/*y>0*/)\n    {\n        BOOST_ASSERT(i_y>0);\n        using namespace boost::math;\n        return -log( rising_factorial<T>(mp1,i_y,p) );\n    }\n    template<typename T,typename Int,typename P>\n    T second_half(const T& m,const Int& i_y,const P& p,\n         boost::mpl::bool_<false>/*y>0*/)\n    {\n        BOOST_ASSERT(i_y<0);\n        using namespace boost::math;\n        return log( falling_factorial<T>(m,-i_y,p) );\n    }\n\n}// factorial_method\n}// q\n}// devroye\n}// poisson\n}// random\n}// boost\n\n#endif\n\n", "meta": {"hexsha": "3b7d30de9cb882ee5f4908d3e0724dd9b6498115", "size": 2932, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/poisson_ext/devroye/q_function/using_factorial.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": "random/boost/random/poisson_ext/devroye/q_function/using_factorial.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": "random/boost/random/poisson_ext/devroye/q_function/using_factorial.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.756097561, "max_line_length": 82, "alphanum_fraction": 0.5579809004, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5176768419670029}}
{"text": "//\n// Sprout C++ Library\n//\n// Copyright (c) 2013\n// bolero-MURAKAMI : http://d.hatena.ne.jp/boleros/\n// osyo-manga : http://d.hatena.ne.jp/osyo-manga/\n// \n// Readme:\n// https://github.com/bolero-MURAKAMI/Sprout/blob/master/README\n//\n// License:\n// Boost Software License - Version 1.0\n// <http://www.boost.org/LICENSE_1_0.txt>\n//\n#include <sprout/random.hpp>\n#include <iostream>\n// #include <boost/mpl/print.hpp>\n\nint\nmain(){\n\tstatic constexpr sprout::uniform_int_distribution<int> dist(100, 999);\n\n\t{\n\t\tstatic constexpr auto seed = 2013;\n\t\tstatic constexpr sprout::default_random_engine engine(seed);\n\n\t\tstatic_assert(engine() == 33832491, \"\");\n\t\tstatic_assert(dist(engine) == 114, \"\");\n\t}\n\n\t{\n\t\tstatic constexpr auto seed = 8379842;\n\t\tstatic constexpr sprout::default_random_engine engine(seed);\n\n\t\tstatic_assert(engine() == 1253567439, \"\");\n\t\tstatic_assert(dist(engine) == 625, \"\");\n\t}\n\n\t//\n\t// Compile time unique seed\n\t//\n\t{\n\t\tstatic constexpr auto seed = SPROUT_UNIQUE_SEED;\n\t\tstd::cout << seed << std::endl;\n\n\t\tstatic constexpr sprout::default_random_engine engine(seed);\n\t\tstd::cout << engine() << std::endl;\n\t\tstd::cout << dist(engine) << std::endl;\n\n\t\t// compile time output\n// \t\ttypedef boost::mpl::print<boost::mpl::int_<seed>>::type unique_seed_type;\n// \t\ttypedef boost::mpl::print<boost::mpl::int_<engine()>>::type engine_type;\n// \t\ttypedef boost::mpl::print<boost::mpl::int_<dist(engine)>>::type dist_type;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "41535b7a8422107fea85481c1ec0aae54832c790", "size": 1440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/example/seed.cpp", "max_stars_repo_name": "thinkoid/Sprout", "max_stars_repo_head_hexsha": "a5a5944bb1779d3bb685087c58c20a4e18df2f39", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T22:17:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T11:53:44.000Z", "max_issues_repo_path": "dsp/lib/sprout/libs/random/example/seed.cpp", "max_issues_repo_name": "TheSlowGrowth/TapeLooper", "max_issues_repo_head_hexsha": "ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2021-10-31T21:41:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T10:51:34.000Z", "max_forks_repo_path": "libs/random/example/seed.cpp", "max_forks_repo_name": "thinkoid/Sprout", "max_forks_repo_head_hexsha": "a5a5944bb1779d3bb685087c58c20a4e18df2f39", "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.8275862069, "max_line_length": 79, "alphanum_fraction": 0.6777777778, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.517676836044736}}
{"text": "#include <mass.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\nBOOST_AUTO_TEST_SUITE(mass);\n\nBOOST_AUTO_TEST_CASE(tetrahedron)\n{\n  double const rho  =  1.0;\n  \n  double const X1   = -1.0;\n  double const Y1   =  0.0;\n  double const Z1   = -1.0;\n  double const X2   =  1.0;\n  double const Y2   =  0.0;\n  double const Z2   = -1.0;\n  double const X3   =  0.0;\n  double const Y3   = -1.0;\n  double const Z3   =  1.0;\n  double const X4   =  0.0;\n  double const Y4   =  1.0;\n  double const Z4   =  1.0;\n  \n    \n  mass::Properties<double> P = mass::compute_tetrahedron(\n                            rho\n                            ,X1,Y1,Z1\n                            ,X2,Y2,Z2\n                            ,X3,Y3,Z3\n                            ,X4,Y4,Z4\n                            );\n  \n  BOOST_CHECK_CLOSE(P.m_x, 0.0, 0.01 );\n  BOOST_CHECK_CLOSE(P.m_y, 0.0, 0.01 );\n  BOOST_CHECK_CLOSE(P.m_z, 0.0, 0.01 );\n  BOOST_CHECK(P.m_m  > 0.0);\n  BOOST_CHECK(P.m_Ixx > 0.0);\n  BOOST_CHECK(P.m_Iyy > 0.0);\n  BOOST_CHECK(P.m_Izz > 0.0);\n  BOOST_CHECK_CLOSE(P.m_Ixy, 0.0, 0.01 );\n  BOOST_CHECK_CLOSE(P.m_Ixz, 0.0, 0.01 );\n  BOOST_CHECK_CLOSE(P.m_Iyz, 0.0, 0.01 );\n  BOOST_CHECK_CLOSE(P.m_Ixx, P.m_Iyy, 0.01 );\n  BOOST_CHECK(P.m_Izz < P.m_Ixx);\n  \n  BOOST_CHECK(   P.is_body_space() );  \n  BOOST_CHECK(  !P.is_model_space() );  \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "ba76a69ad604bb9f68ecc90a5be638efd7710264", "size": 1499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/SIMULATION/MASS/unit_tests/mass_tetrahedron/mass_tetrahedron.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/SIMULATION/MASS/unit_tests/mass_tetrahedron/mass_tetrahedron.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/SIMULATION/MASS/unit_tests/mass_tetrahedron/mass_tetrahedron.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2545454545, "max_line_length": 57, "alphanum_fraction": 0.5790527018, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067222797121, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5176768360447359}}
{"text": "/*\n\tFile: StateSpace.hpp\n\tDescription: A Class for creating state space calculations \n\t\n\tTODO: Finish full state\n\t\t  Write autonomous\n\n*/\n#ifndef STATE_SPACE_CONTROL_H\n#define STATE_SPACE_CONTROL_H\n\n#include <Eigen>\n#include <iostream>\n\n\nclass StateSpace{\nprivate:\n\tint states;\n\tint inputs;\n\tint outputs;\n\tint type;\n\n    \n    Eigen::MatrixXf systemMatrix;\n    Eigen::MatrixXf inputMatrix;\n    Eigen::MatrixXf outputMatrix;\n    Eigen::MatrixXf transmissionMatrix;\n    Eigen::MatrixXf controlInputs;\n    Eigen::MatrixXf referenceInputs;\n    Eigen::MatrixXf controlGain;\n    Eigen::MatrixXf integralGain;\n    Eigen::MatrixXf precompensator;\n    Eigen::MatrixXf compensator;\n\tEigen::MatrixXf estimatorOutput;\n\n\t//Set Actual State & Output\n\tEigen::MatrixXf actual;\n\tEigen::MatrixXf\trealOutput;\n\npublic:\n\tStateSpace(int state, int input, int output, int type);\n\tvoid Initialise(Eigen::MatrixXf A, Eigen::MatrixXf B, Eigen::MatrixXf C, Eigen::MatrixXf K);  // Sets Values of matrices to values defined in the main\n\tEigen::MatrixXf Calculate();\t//Determines the output of the system and updates new values\n\t\n\t\n\t\n\n\t//Get Functions\n\tEigen::MatrixXf getControlInputs();\n\tEigen::MatrixXf getReferenceInputs();\n\tEigen::MatrixXf getSystemMatrix();\n\tEigen::MatrixXf getInputMatrix();\n\tEigen::MatrixXf getOutputMatrix();\n\tEigen::MatrixXf getTransmissionMatrix();\n\tEigen::MatrixXf getControlGain();\n\tEigen::MatrixXf getIntegralGain();\n\tEigen::MatrixXf getPrecompensator();\n\tEigen::MatrixXf getEstimatorOutput();\n\tEigen::MatrixXf getActual();\n\tEigen::MatrixXf getRealOutput();\n\n\t//Set Functions\n\tvoid setControlInputs(Eigen::MatrixXf X);\n\tvoid setReferenceInputs(Eigen::MatrixXf X);\n\tvoid setSystemMatrix(Eigen::MatrixXf X);\n\tvoid setInputMatrix(Eigen::MatrixXf X);\n\tvoid setOutputMatrix(Eigen::MatrixXf X);\n\tvoid setTransmissionMatrix(Eigen::MatrixXf X);\n\tvoid setControlGain(Eigen::MatrixXf X);\n\tvoid setIntegralGain(Eigen::MatrixXf X);\n\tvoid setPrecompensator(Eigen::MatrixXf X);\n\tvoid setEstimatorOutput(Eigen::MatrixXf X);\n\tvoid setActual(Eigen::MatrixXf X);\n\tvoid setRealOutput(Eigen::MatrixXf X);\n\n};\n#endif // STATE_SPACE_CONTROL_H\n\n\n\n", "meta": {"hexsha": "8f1df03915dcbf93976cbd56727dbcf7e5f60da1", "size": 2125, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "StateSpace.hpp", "max_stars_repo_name": "rusmanr/StateSpaceControlGUI", "max_stars_repo_head_hexsha": "0ff848dc3903dc2d7dddad0e43b5690a3caec4c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "StateSpace.hpp", "max_issues_repo_name": "rusmanr/StateSpaceControlGUI", "max_issues_repo_head_hexsha": "0ff848dc3903dc2d7dddad0e43b5690a3caec4c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StateSpace.hpp", "max_forks_repo_name": "rusmanr/StateSpaceControlGUI", "max_forks_repo_head_hexsha": "0ff848dc3903dc2d7dddad0e43b5690a3caec4c9", "max_forks_repo_licenses": ["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.2345679012, "max_line_length": 151, "alphanum_fraction": 0.7590588235, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6406358548398982, "lm_q1q2_score": 0.5176768242002017}}
{"text": "//\n// Copyright 2005-2007 Adobe Systems Incorporated\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#ifndef BOOST_GIL_EXTENSION_NUMERIC_AFFINE_HPP\n#define BOOST_GIL_EXTENSION_NUMERIC_AFFINE_HPP\n\n#include <boost/gil/point.hpp>\n\nnamespace boost {\nnamespace gil {\n\n////////////////////////////////////////////////////////////////////////////////////////\n///\n/// Simple matrix to do 2D affine transformations. It is actually 3x3 but the\n/// last column is [0 0 1]\n///\n////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename T> class matrix3x2 {\npublic:\n  matrix3x2() : a(1), b(0), c(0), d(1), e(0), f(0) {}\n  matrix3x2(T A, T B, T C, T D, T E, T F)\n      : a(A), b(B), c(C), d(D), e(E), f(F) {}\n  matrix3x2(const matrix3x2 &mat)\n      : a(mat.a), b(mat.b), c(mat.c), d(mat.d), e(mat.e), f(mat.f) {}\n  matrix3x2 &operator=(const matrix3x2 &m) {\n    a = m.a;\n    b = m.b;\n    c = m.c;\n    d = m.d;\n    e = m.e;\n    f = m.f;\n    return *this;\n  }\n\n  matrix3x2 &operator*=(const matrix3x2 &m) {\n    (*this) = (*this) * m;\n    return *this;\n  }\n\n  static matrix3x2 get_rotate(T rads) {\n    T c = std::cos(rads);\n    T s = std::sin(rads);\n    return matrix3x2(c, s, -s, c, 0, 0);\n  }\n  static matrix3x2 get_translate(point<T> const &t) {\n    return matrix3x2(1, 0, 0, 1, t.x, t.y);\n  }\n  static matrix3x2 get_translate(T x, T y) {\n    return matrix3x2(1, 0, 0, 1, x, y);\n  }\n  static matrix3x2 get_scale(point<T> const &s) {\n    return matrix3x2(s.x, 0, 0, s.y, 0, 0);\n  }\n  static matrix3x2 get_scale(T x, T y) { return matrix3x2(x, 0, 0, y, 0, 0); }\n  static matrix3x2 get_scale(T s) { return matrix3x2(s, 0, 0, s, 0, 0); }\n\n  T a, b, c, d, e, f;\n};\n\ntemplate <typename T>\nBOOST_FORCEINLINE matrix3x2<T> operator*(const matrix3x2<T> &m1,\n                                         const matrix3x2<T> &m2) {\n  return matrix3x2<T>(m1.a * m2.a + m1.b * m2.c, m1.a * m2.b + m1.b * m2.d,\n                      m1.c * m2.a + m1.d * m2.c, m1.c * m2.b + m1.d * m2.d,\n                      m1.e * m2.a + m1.f * m2.c + m2.e,\n                      m1.e * m2.b + m1.f * m2.d + m2.f);\n}\n\ntemplate <typename T, typename F>\nBOOST_FORCEINLINE point<F> operator*(point<T> const &p, matrix3x2<F> const &m) {\n  return {m.a * p.x + m.c * p.y + m.e, m.b * p.x + m.d * p.y + m.f};\n}\n\n////////////////////////////////////////////////////////////////////////////////////////\n/// Define affine mapping that transforms the source coordinates by the affine\n/// transformation\n////////////////////////////////////////////////////////////////////////////////////////\n/*\ntemplate <typename MapFn>\nconcept MappingFunctionConcept {\n    typename mapping_traits<MapFn>::result_type;   where\nPointNDConcept<result_type>;\n\n    template <typename Domain> { where PointNDConcept<Domain> }\n    result_type transform(MapFn&, const Domain& src);\n};\n*/\n\ntemplate <typename T> struct mapping_traits;\n\ntemplate <typename F> struct mapping_traits<matrix3x2<F>> {\n  using result_type = point<F>;\n};\n\ntemplate <typename F, typename F2>\nBOOST_FORCEINLINE point<F> transform(matrix3x2<F> const &mat,\n                                     point<F2> const &src) {\n  return src * mat;\n}\n\n} // namespace gil\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "0deada7f0d14528597d163d732e661bedc8adff6", "size": 3337, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/extension/numeric/affine.hpp", "max_stars_repo_name": "sdebionne/gil-reformated", "max_stars_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/gil/extension/numeric/affine.hpp", "max_issues_repo_name": "sdebionne/gil-reformated", "max_issues_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/gil/extension/numeric/affine.hpp", "max_forks_repo_name": "sdebionne/gil-reformated", "max_forks_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "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.6146788991, "max_line_length": 88, "alphanum_fraction": 0.5382079712, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5176768242002016}}
{"text": "#pragma once\n#include <cstdint>\n#include <cassert>\n#include <algorithm>\n#include <map>\n#include <boost/dynamic_bitset.hpp>\n//#include \"BitOperations.h\"\n#include \"../Basis/AbstractBasis1D.hpp\"\n\ntemplate<typename UINT>\nclass TIXXXJ1J2\n{\nprivate:\n\tconst edlib::AbstractBasis<UINT>& basis_;\n\tdouble J1_;\n\tdouble J2_;\n\n\tint sign_ = 1;\n\npublic:\n\tTIXXXJ1J2(const edlib::AbstractBasis<UINT>& basis, double J1, double J2, \n\t\t\tbool signRule = false)\n\t\t: basis_(basis), J1_(J1), J2_(J2)\n\t{\n\t\tif(signRule)\n\t\t\tsign_ = -1;\n\t}\n\n\tstd::map<int,double> getCol(UINT n) const\n\t{\n\t\tint N = basis_.getN();\n\n\t\tUINT a = basis_.getNthRep(n);\n\t\tconst boost::dynamic_bitset<> bs(N, a);\n\n\t\tstd::map<int, double> m;\n\t\tfor(unsigned int i = 0; i < N; i++)\n\t\t{\n\t\t\t//Nearest neighbors\n\t\t\t{\n\t\t\t\tunsigned int j = (i+1)%N;\n\t\t\t\tint sgn = (1-2*bs[i])*(1-2*bs[j]);\n\n\t\t\t\tm[n] += J1_*sgn;\n\t\t\t\t\n\t\t\t\tUINT s = a;\n\t\t\t\ts ^= basis_.mask({i,j});\n\n\t\t\t\tint bidx;\n\t\t\t\tdouble coeff;\n\n\t\t\t\tstd::tie(bidx, coeff) = basis_.hamiltonianCoeff(s, n);\n\t\t\t\t\n\t\t\t\tif(bidx >= 0)\n\t\t\t\t\tm[bidx] += J1_*(1-sgn)*sign_*coeff;\n\t\t\t}\n\t\t\t//Next-nearest neighbors\n\t\t\t{\n\t\t\t\tunsigned int j = (i+2)%N;\n\t\t\t\tint sgn = (1-2*bs[i])*(1-2*bs[j]);\n\n\t\t\t\tm[n] += J2_*sgn;\n\t\t\t\t\n\t\t\t\tUINT s = a;\n\t\t\t\ts ^= basis_.mask({i,j});\n\t\t\n\t\t\t\tint bidx;\n\t\t\t\tdouble coeff;\n\n\t\t\t\tstd::tie(bidx, coeff) = basis_.hamiltonianCoeff(s, n);\n\n\t\t\t\tif(bidx >= 0)\n\t\t\t\t\tm[bidx] += J2_*(1-sgn)*coeff;\n\t\t\t}\n\t\t}\n\t\treturn m;\n\t}\n};\n", "meta": {"hexsha": "234b43ae7f37e26830fe14d4c00a121b63a3568f", "size": 1410, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/edlib/Hamiltonians/TIXXXJ1J2.hpp", "max_stars_repo_name": "chaeyeunpark/ExactDiagonalization", "max_stars_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T08:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:47:05.000Z", "max_issues_repo_path": "include/edlib/Hamiltonians/TIXXXJ1J2.hpp", "max_issues_repo_name": "chaeyeunpark/ExactDiagonalization", "max_issues_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T19:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T19:02:14.000Z", "max_forks_repo_path": "include/edlib/Hamiltonians/TIXXXJ1J2.hpp", "max_forks_repo_name": "chaeyeunpark/ExactDiagonalization", "max_forks_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-22T18:59:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T18:59:11.000Z", "avg_line_length": 17.8481012658, "max_line_length": 74, "alphanum_fraction": 0.5794326241, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5176242525602904}}
{"text": "#ifndef Jabc_HPP_\n#define Jabc_HPP_\n\n#include <armadillo>\nusing namespace arma;\n\nvoid transform_xlogx_mat(cx_mat &X);\nvoid transform_xlogx_vec(vec &s);\nint log2_int(int n);\nvoid apply_modular_op(int k, int n, cx_mat &psi);\nvoid transform_ab(int a, int b, int c, cx_mat &psi);\nvoid transform_bc(int a, int b, int c, cx_mat &psi);\ndouble Jabc(int a, int b, int c, cx_mat &psi);\n\n#endif // Jabc_HPP_\n", "meta": {"hexsha": "76b925a36f289eca77febf47c2dca18209e8c25b", "size": 397, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Jabc.hpp", "max_stars_repo_name": "ikim-quantum/Jabc", "max_stars_repo_head_hexsha": "e98278ecb5daa7f239daadf573a2de36997aa644", "max_stars_repo_licenses": ["MIT"], "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/Jabc.hpp", "max_issues_repo_name": "ikim-quantum/Jabc", "max_issues_repo_head_hexsha": "e98278ecb5daa7f239daadf573a2de36997aa644", "max_issues_repo_licenses": ["MIT"], "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/Jabc.hpp", "max_forks_repo_name": "ikim-quantum/Jabc", "max_forks_repo_head_hexsha": "e98278ecb5daa7f239daadf573a2de36997aa644", "max_forks_repo_licenses": ["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.8125, "max_line_length": 52, "alphanum_fraction": 0.7355163728, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.6261241772283033, "lm_q1q2_score": 0.5176242525602903}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_ARITHMETIC_FUNCTIONS_COMPLEX_GENERIC_FMA_HPP_INCLUDED\n#define NT2_ARITHMETIC_FUNCTIONS_COMPLEX_GENERIC_FMA_HPP_INCLUDED\n\n#include <nt2/arithmetic/functions/fma.hpp>\n#include <nt2/include/functions/real.hpp>\n#include <nt2/include/functions/imag.hpp>\n#include <nt2/include/functions/simd/logical_and.hpp>\n#include <nt2/include/functions/if_else.hpp>\n#include <nt2/include/functions/if_zero_else.hpp>\n#include <nt2/include/functions/if_allbits_else.hpp>\n#include <nt2/include/functions/is_invalid.hpp>\n#include <nt2/include/functions/is_real.hpp>\n#include <nt2/include/functions/is_imag.hpp>\n#include <nt2/include/functions/is_nez.hpp>\n#include <nt2/include/functions/multiplies.hpp>\n#include <nt2/include/functions/plus.hpp>\n#include <nt2/include/functions/simd/any.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/functions/simd/seladd.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/sdk/complex/meta/as_complex.hpp>\n#include <nt2/sdk/complex/meta/as_real.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n// for optimize\n#include <nt2/include/functions/fnma.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n\n\n  //0 ccc\n  BOOST_DISPATCH_IMPLEMENT  ( fma_, tag::cpu_, (A0)(A1)(A2)\n                              , (generic_<complex_<arithmetic_<A0> > > )\n                              (generic_<complex_<arithmetic_<A1> > > )\n                              (generic_<complex_<arithmetic_<A2> > > )\n    )\n  {\n    typedef A0 result_type;\n    typedef typename nt2::meta::as_real<A0>::type r_type;\n    NT2_FUNCTOR_CALL(3)\n    {\n      r_type r = fma(-nt2::imag(a1), nt2::imag(a0), fma(nt2::real(a0), nt2::real(a1), nt2::real(a2)));\n      r_type i = fma(nt2::real(a1), nt2::imag(a0), fma(nt2::real(a0), nt2::imag(a1), nt2::imag(a2)));\n      return checkr(a0, a1, a2, result_type(r, i));\n    }\n\n    static inline result_type checkr(const A0& a0,  const A1& a1,  const A2& a2, const result_type& res)\n    {\n#ifdef BOOST_SIMD_NO_INVALIDS\n      return res;\n#else\n      if(nt2::any(is_invalid(res)))\n      {\n        result_type z = nt2::multiplies(a0, a1);\n        z+=a2;\n        return if_else(is_invalid(res), z, res);\n      }\n      return res;\n#endif\n\n    }\n  };\n\n\n  //8 acc\n  BOOST_DISPATCH_IMPLEMENT  ( fma_, tag::cpu_, (A0)(A1)(A2)\n                              , (generic_<arithmetic_<A0> > )\n                              (generic_<complex_<arithmetic_<A1> > > )\n                              (generic_<complex_<arithmetic_<A2> > > )\n    )\n  {\n    typedef A1 result_type;\n    typedef typename nt2::meta::as_real<A0>::type r_type;\n    NT2_FUNCTOR_CALL(3)\n    {\n      r_type r = fma(a0, nt2::real(a1), nt2::real(a2));\n      r_type i = fma(a0, nt2::imag(a1), nt2::imag(a2));\n      return checkr(a0, a1, a2, r, i);\n    }\n    static inline result_type checkr(const A0& a0, const A1& a1, const A2& a2, r_type& r, r_type& i)\n    {\n#ifdef BOOST_SIMD_NO_INVALIDS\n      return result_type(r, i);\n#else\n      r =  if_else(is_invalid(a0),\n                   if_else(is_real(a1),\n                           r,\n                           if_else(nt2::is_imag(a1), nt2::real(a2),r)),\n                   r\n        );\n      i =  if_else(is_invalid(a0),\n                   if_else(is_real(a1), nt2::imag(a2), i),\n                   i);\n      return result_type(r, i);\n#endif\n    }\n  };\n\n  //9 cac\n  BOOST_DISPATCH_IMPLEMENT  ( fma_, tag::cpu_, (A0)(A1)(A2)\n                              , (generic_<complex_<arithmetic_<A0> > > )\n                              (generic_<arithmetic_<A1> > )\n                              (generic_<complex_<arithmetic_<A2> > > )\n    )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(3)\n    {\n      return fma(a1, a0, a2);\n    }\n  };\n\n  //10 cca\n  BOOST_DISPATCH_IMPLEMENT  ( fma_, tag::cpu_, (A0)(A1)(A2)\n                              , (generic_<complex_<arithmetic_<A0> > > )\n                              (generic_<complex_<arithmetic_<A1> > > )\n                              (generic_<arithmetic_<A2> > )\n    )\n  {\n    typedef A0 result_type;\n    typedef typename nt2::meta::as_real<A0>::type r_type;\n    NT2_FUNCTOR_CALL(3)\n    {\n      r_type r =fma(-nt2::imag(a1), nt2::imag(a0), fma(nt2::real(a1), nt2::real(a0), a2));\n      r_type i = fma(nt2::real(a1), nt2::imag(a0), nt2::real(a0)*nt2::imag(a1));\n      return checkr(a0, a1, a2, r, i);\n\n    }\n    static inline result_type checkr(const A0& a0, const A1& a1, const A2& a2, const r_type& r, const r_type& i)\n    {\n#ifdef BOOST_SIMD_NO_INVALIDS\n      return result_type(r, i);\n#else\n      BOOST_AUTO_TPL(test, nt2::logical_and(nt2::logical_and(nt2::is_real(a1), nt2::is_real(a0)), nt2::is_nez(i)));\n      BOOST_AUTO_TPL(testr, nt2::logical_and(logical_or(nt2::is_eqz(a1), is_eqz(a0)),\n                                             logical_and(logical_and(is_imag(a0),\n                                                                     is_imag(a1)),\n                                                         nt2::is_invalid(r))));\n      return result_type(if_else(testr, a2, r), nt2::if_zero_else(test, i));\n#endif\n\n    }\n  };\n\n  //11 caa\n  BOOST_DISPATCH_IMPLEMENT  ( fma_, tag::cpu_, (A0)(A1)(A2)\n                              , (generic_<complex_<arithmetic_<A0> > > )\n                              (generic_< arithmetic_<A1>  > )\n                              (generic_< arithmetic_<A2>  > )\n    )\n  {\n    typedef A0 result_type;\n    typedef typename nt2::meta::as_real<A0>::type r_type;\n    NT2_FUNCTOR_CALL(3)\n    {\n      r_type r = fma(nt2::real(a0), a1, a2);\n      r_type i = nt2::imag(a0)*a1;\n      return checkr(a0, r, i);\n    }\n    static inline result_type checkr(const A0& a0, const r_type& r, const r_type& i)\n    {\n#ifdef BOOST_SIMD_NO_INVALIDS\n      return result_type(r, i);\n#else\n      BOOST_AUTO_TPL(test, nt2::logical_and(nt2::is_real(a0), nt2::is_nez(i)));\n      return result_type(r, nt2::if_zero_else(test, i));\n#endif\n    }\n  };\n\n  //12 aca\n  BOOST_DISPATCH_IMPLEMENT  ( fma_, tag::cpu_, (A0)(A1)(A2)\n                              , (generic_< arithmetic_<A0>  > )\n                              (generic_<complex_<arithmetic_<A1> > > )\n                              (generic_< arithmetic_<A2>  > )\n    )\n  {\n    typedef A1 result_type;\n    NT2_FUNCTOR_CALL(3)\n    {\n      return fma(a1, a0, a2);\n    }\n  };\n\n  //13 aac\n  BOOST_DISPATCH_IMPLEMENT  ( fma_, tag::cpu_, (A0)(A1)(A2)\n                              , (generic_<arithmetic_<A0>  > )\n                              (generic_<arithmetic_<A1>  > )\n                              (generic_<complex_<arithmetic_<A2> > > )\n    )\n  {\n    typedef A2 result_type;\n    NT2_FUNCTOR_CALL(3)\n    {\n      return result_type( fma(a0, a1, nt2::real(a2))\n                          , nt2::imag(a2)\n        );\n    }\n  };\n\n } } }\n\n#endif\n", "meta": {"hexsha": "b8a927908d9e088549b0ecf3f42e04bb47a3d1e3", "size": 7222, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/base/include/nt2/arithmetic/functions/complex/generic/fma.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/type/complex/base/include/nt2/arithmetic/functions/complex/generic/fma.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/type/complex/base/include/nt2/arithmetic/functions/complex/generic/fma.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 33.9061032864, "max_line_length": 115, "alphanum_fraction": 0.5487399612, "num_tokens": 2030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5176242472138628}}
{"text": "//  (C) Copyright John Maddock 2005.\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_COMPLEX_ATANH_INCLUDED\n#define BOOST_MATH_COMPLEX_ATANH_INCLUDED\n\n#ifndef BOOST_MATH_COMPLEX_DETAILS_INCLUDED\n#  include <boost/math/complex/details.hpp>\n#endif\n#ifndef BOOST_MATH_LOG1P_INCLUDED\n#  include <boost/math/special_functions/log1p.hpp>\n#endif\n#include <boost/assert.hpp>\n\n#ifdef BOOST_NO_STDC_NAMESPACE\nnamespace std{ using ::sqrt; using ::fabs; using ::acos; using ::asin; using ::atan; using ::atan2; }\n#endif\n\nnamespace boost{ namespace math{\n\ntemplate<class T> \nstd::complex<T> atanh(const std::complex<T>& z)\n{\n   //\n   // References:\n   //\n   // Eric W. Weisstein. \"Inverse Hyperbolic Tangent.\" \n   // From MathWorld--A Wolfram Web Resource. \n   // http://mathworld.wolfram.com/InverseHyperbolicTangent.html\n   //\n   // Also: The Wolfram Functions Site,\n   // http://functions.wolfram.com/ElementaryFunctions/ArcTanh/\n   //\n   // Also \"Abramowitz and Stegun. Handbook of Mathematical Functions.\"\n   // at : http://jove.prohosting.com/~skripty/toc.htm\n   //\n   // See also: https://svn.boost.org/trac/boost/ticket/7291\n   //\n   \n   static const T pi = boost::math::constants::pi<T>();\n   static const T half_pi = pi / 2;\n   static const T one = static_cast<T>(1.0L);\n   static const T two = static_cast<T>(2.0L);\n   static const T four = static_cast<T>(4.0L);\n   static const T zero = static_cast<T>(0);\n   static const T log_two = boost::math::constants::ln_two<T>();\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4127)\n#endif\n\n   T x = std::fabs(z.real());\n   T y = std::fabs(z.imag());\n\n   T real, imag;  // our results\n\n   T safe_upper = detail::safe_max(two);\n   T safe_lower = detail::safe_min(static_cast<T>(2));\n\n   //\n   // Begin by handling the special cases specified in C99:\n   //\n   if((boost::math::isnan)(x))\n   {\n      if((boost::math::isnan)(y))\n         return std::complex<T>(x, x);\n      else if((boost::math::isinf)(y))\n         return std::complex<T>(0, ((boost::math::signbit)(z.imag()) ? -half_pi : half_pi));\n      else\n         return std::complex<T>(x, x);\n   }\n   else if((boost::math::isnan)(y))\n   {\n      if(x == 0)\n         return std::complex<T>(x, y);\n      if((boost::math::isinf)(x))\n         return std::complex<T>(0, y);\n      else\n         return std::complex<T>(y, y);\n   }\n   else if((x > safe_lower) && (x < safe_upper) && (y > safe_lower) && (y < safe_upper))\n   {\n\n      T yy = y*y;\n      T mxm1 = one - x;\n      ///\n      // The real part is given by:\n      // \n      // real(atanh(z)) == log1p(4*x / ((x-1)*(x-1) + y^2))\n      // \n      real = boost::math::log1p(four * x / (mxm1*mxm1 + yy));\n      real /= four;\n      if((boost::math::signbit)(z.real()))\n         real = (boost::math::changesign)(real);\n\n      imag = std::atan2((y * two), (mxm1*(one+x) - yy));\n      imag /= two;\n      if(z.imag() < 0)\n         imag = (boost::math::changesign)(imag);\n   }\n   else\n   {\n      //\n      // This section handles exception cases that would normally cause\n      // underflow or overflow in the main formulas.\n      //\n      // Begin by working out the real part, we need to approximate\n      //    real = boost::math::log1p(4x / ((x-1)^2 + y^2))\n      // without either overflow or underflow in the squared terms.\n      //\n      T mxm1 = one - x;\n      if(x >= safe_upper)\n      {\n         // x-1 = x to machine precision:\n         if((boost::math::isinf)(x) || (boost::math::isinf)(y))\n         {\n            real = 0;\n         }\n         else if(y >= safe_upper)\n         {\n            // Big x and y: divide through by x*y:\n            real = boost::math::log1p((four/y) / (x/y + y/x));\n         }\n         else if(y > one)\n         {\n            // Big x: divide through by x:\n            real = boost::math::log1p(four / (x + y*y/x));\n         }\n         else\n         {\n            // Big x small y, as above but neglect y^2/x:\n            real = boost::math::log1p(four/x);\n         }\n      }\n      else if(y >= safe_upper)\n      {\n         if(x > one)\n         {\n            // Big y, medium x, divide through by y:\n            real = boost::math::log1p((four*x/y) / (y + mxm1*mxm1/y));\n         }\n         else\n         {\n            // Small or medium x, large y:\n            real = four*x/y/y;\n         }\n      }\n      else if (x != one)\n      {\n         // y is small, calculate divisor carefully:\n         T div = mxm1*mxm1;\n         if(y > safe_lower)\n            div += y*y;\n         real = boost::math::log1p(four*x/div);\n      }\n      else\n         real = boost::math::changesign(two * (std::log(y) - log_two));\n\n      real /= four;\n      if((boost::math::signbit)(z.real()))\n         real = (boost::math::changesign)(real);\n\n      //\n      // Now handle imaginary part, this is much easier,\n      // if x or y are large, then the formula:\n      //    atan2(2y, (1-x)*(1+x) - y^2)\n      // evaluates to +-(PI - theta) where theta is negligible compared to PI.\n      //\n      if((x >= safe_upper) || (y >= safe_upper))\n      {\n         imag = pi;\n      }\n      else if(x <= safe_lower)\n      {\n         //\n         // If both x and y are small then atan(2y),\n         // otherwise just x^2 is negligible in the divisor:\n         //\n         if(y <= safe_lower)\n            imag = std::atan2(two*y, one);\n         else\n         {\n            if((y == zero) && (x == zero))\n               imag = 0;\n            else\n               imag = std::atan2(two*y, one - y*y);\n         }\n      }\n      else\n      {\n         //\n         // y^2 is negligible:\n         //\n         if((y == zero) && (x == one))\n            imag = 0;\n         else\n            imag = std::atan2(two*y, mxm1*(one+x));\n      }\n      imag /= two;\n      if((boost::math::signbit)(z.imag()))\n         imag = (boost::math::changesign)(imag);\n   }\n   return std::complex<T>(real, imag);\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n}\n\n} } // namespaces\n\n#endif // BOOST_MATH_COMPLEX_ATANH_INCLUDED\n", "meta": {"hexsha": "66f4599e528e489299401080da0f53f55eba5b85", "size": 6103, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/math/complex/atanh.hpp", "max_stars_repo_name": "189569400/ClickHouse", "max_stars_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/math/complex/atanh.hpp", "max_issues_repo_name": "189569400/ClickHouse", "max_issues_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/math/complex/atanh.hpp", "max_forks_repo_name": "189569400/ClickHouse", "max_forks_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": 28.3860465116, "max_line_length": 101, "alphanum_fraction": 0.5315418647, "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6261241772283033, "lm_q1q2_score": 0.5176242472138627}}
{"text": "//\n// Created by a.kiryanenko on 3/26/20.\n//\n\n#include \"../SpuUltraGraphAdapter.h\"\n#include \"../SpuUltraGraphProperty.h\"\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n#include \"GraphPerformanceTest.h\"\n\n\nusing namespace SPU_GRAPH;\nusing namespace boost;\n\n\ntypedef boost::adjacency_list <\n        boost::vecS, // \u043a\u0430\u043a \u0445\u0440\u0430\u043d\u0438\u0442\u044c \u0432\u0435\u0440\u0448\u0438\u043d\u044b - \u0432 \u0432\u0435\u043a\u0442\u043e\u0440\u0435\n        boost::vecS, // \u043a\u0430\u043a \u0445\u0440\u0430\u043d\u0438\u0442\u044c \u0440\u0435\u0431\u0440\u0430 \u0438\u0437 \u043a\u0430\u0436\u0434\u043e\u0439 \u0432\u0435\u0440\u0448\u0438\u043d\u044b - \u0432 \u0432\u0435\u043a\u0442\u043e\u0440\u0435\n        boost::directedS,\n        no_property,\n        property < edge_weight_t, int >\n> AdjacencyListGraph;\n\n\n\ntemplate <class G>\npair<typename graph_traits<G>::edge_descriptor, bool>\nadd_weight_edge(typename graph_traits<G>::vertex_descriptor u, typename graph_traits<G>::vertex_descriptor v, G& g) {\n    auto weight = rand() % 16;\n    return add_edge(u, v, weight, g);\n}\n\ntemplate <>\npair<typename graph_traits<SpuUltraGraph>::edge_descriptor, bool>\nadd_weight_edge(typename graph_traits<SpuUltraGraph>::vertex_descriptor u, typename graph_traits<SpuUltraGraph>::vertex_descriptor v, SpuUltraGraph& g) {\n    auto weight = rand() % 16;\n    return {g.add_edge(g.get_free_edge_descriptor(weight), u, v), true};\n}\n\n\ntemplate <class G>\nvoid dijkstra_test(G &g) {\n    typedef typename graph_traits<G>::vertex_descriptor vertex_t;\n\n    // \u0421\u043e\u0437\u0434\u0430\u044e \u0441\u0432\u043e\u0439\u0441\u0442\u0432\u043e \u043f\u0440\u0435\u0434\u0448\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u0438\u043a \u0434\u043b\u044f \u0432\u0435\u0440\u0448\u0438\u043d\n    map<vertex_t, vertex_t> vertex_to_predecessor;\n    associative_property_map<map<vertex_t, vertex_t>> predecessor_property_map(vertex_to_predecessor);\n    // \u0421\u043e\u0437\u0434\u0430\u044e \u0441\u0432\u043e\u0439\u0441\u0442\u0432\u043e \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0435 \u0434\u043b\u044f \u0432\u0435\u0440\u0448\u0438\u043d\n    map<vertex_t, size_t> vertex_to_distance;\n    associative_property_map<map<vertex_t, size_t>> distance_property_map(vertex_to_distance);\n\n    // \u0412\u044b\u043f\u043e\u043b\u043d\u044f\u044e \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u0434\u0435\u0439\u043a\u0441\u0442\u0440\u0430 \u0434\u043b\u044f \u043f\u043e\u0434\u0441\u0447\u0435\u0442\u0430 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0439 \u043e\u0442 \u0432\u0435\u0440\u0448\u0438\u043d\u044b #1 \u0434\u043e \u043e\u0441\u0442\u0430\u043b\u044c\u043d\u044b\u0445\n    dijkstra_shortest_paths_no_color_map(g, 1, predecessor_map(predecessor_property_map).distance_map(distance_property_map));\n}\n\n\nint main()\n{\n    cout << \"SpuUltraGraph performance test\" << endl;\n    cout << \"==========================================\" << endl;\n    GraphPerformanceTest<SpuUltraGraph> spu_graph_test(dijkstra_test, \"dijkstra_test_SpuUltraGraph.csv\");\n    spu_graph_test.is_mutable_test = false;\n    spu_graph_test.add_edge_func = add_weight_edge;\n    spu_graph_test.start();\n\n    cout << \"adjacency_list performance test\" << endl;\n    cout << \"==========================================\" << endl;\n    GraphPerformanceTest<AdjacencyListGraph> adjacency_list_test(dijkstra_test, \"dijkstra_test_adjacency_list.csv\");\n    adjacency_list_test.is_mutable_test = false;\n    adjacency_list_test.add_edge_func = add_weight_edge;\n    adjacency_list_test.start();\n\n    cout << \"adjacency_matrix performance test\" << endl;\n    cout << \"==========================================\" << endl;\n    GraphPerformanceTest<AdjacencyMatrixGraph> adjacency_matrix_test(dijkstra_test, \"dijkstra_test_adjacency_matrix.csv\");\n    adjacency_matrix_test.is_mutable_test = false;\n    adjacency_matrix_test.add_edge_func = add_weight_edge;\n    adjacency_matrix_test.end_vertices_cnt = 25000;\n    adjacency_matrix_test.start();\n    return 0;\n}", "meta": {"hexsha": "472d506ef9139369a7ad05b2695ccca64c107524", "size": 3109, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "performance_tests/dijkstra.cpp", "max_stars_repo_name": "kiryanenko/graph-api", "max_stars_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T19:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-29T19:42:34.000Z", "max_issues_repo_path": "performance_tests/dijkstra.cpp", "max_issues_repo_name": "kiryanenko/graph-api", "max_issues_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "performance_tests/dijkstra.cpp", "max_forks_repo_name": "kiryanenko/graph-api", "max_forks_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_forks_repo_licenses": ["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.3827160494, "max_line_length": 153, "alphanum_fraction": 0.726600193, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.5176242467927307}}
{"text": "/*\n [auto_generated]\n libs/numeric/odeint/examples/molecular_dynamics.cpp\n\n [begin_description]\n Molecular dynamics example.\n [end_description]\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#include <boost/numeric/odeint.hpp>\n\n#include <vector>\n#include <iostream>\n#include <random>\n\nusing namespace boost::numeric::odeint;\n\n\n\nusing namespace std;\n#define tab \"\\t\"\n\nconst size_t n1 = 16;\nconst size_t n2 = 16;\n\nstruct md_system\n{\n    static const size_t n = n1 * n2;\n    typedef std::vector< double > vector_type;\n\n    md_system( double a = 0.0 ,            // strength of harmonic oscillator\n               double gamma = 0.0   ,       // friction\n               double eps = 0.1 ,          // interaction strenght\n               double sigma = 1.0 ,            // interaction radius\n               double xmax = 150.0 , double ymax = 150.0 )\n    : m_a( a ) , m_gamma( gamma ) \n    , m_eps( eps ) , m_sigma( sigma ) \n    , m_xmax( xmax ) , m_ymax( ymax )\n    { }\n    \n    static void init_vector_type( vector_type &x ) { x.resize( 2 * n ); }\n    \n    void operator()( vector_type const& x , vector_type const& v , vector_type &a , double t ) const\n    {\n        for( size_t i=0 ; i<n ; ++i )\n        {\n            double diffx = x[i] - 0.5 * m_xmax , diffy = x[i+n] - 0.5 * m_ymax;\n            double r2 = diffx * diffx + diffy * diffy ;\n            double r = std::sqrt( r2 );\n            a[     i ] = - m_a * r * diffx - m_gamma * v[     i ] ;\n            a[ n + i ] = - m_a * r * diffy - m_gamma * v[ n + i ] ;\n        }\n        \n        for( size_t i=0 ; i<n ; ++i )\n        {\n            double xi = x[i] , yi = x[n+i];\n            xi = periodic_bc( xi , m_xmax );\n            yi = periodic_bc( yi , m_ymax );\n            for( size_t j=0 ; j<i ; ++j )\n            {\n                double xj = x[j] , yj = x[n+j];\n                xj = periodic_bc( xj , m_xmax );\n                yj = periodic_bc( yj , m_ymax );\n                \n                double diffx = ( xj - xi ) , diffy = ( yj - yi );\n                double r = sqrt( diffx * diffx + diffy * diffy );\n                double f = lennard_jones( r );\n                a[     i ] += diffx / r * f;\n                a[ n + i ] += diffy / r * f;\n                a[     j ] -= diffx / r * f;\n                a[ n + j ] -= diffy / r * f;\n            }\n        }\n    }\n    \n    void bc( vector_type &x )\n    {\n        for( size_t i=0 ; i<n ; ++i )\n        {\n            x[ i     ] = periodic_bc( x[ i     ] , m_xmax );\n            x[ i + n ] = periodic_bc( x[ i + n ] , m_ymax );\n        }\n    }\n    \n    inline double lennard_jones( double r ) const\n    {\n        double c = m_sigma / r;\n        double c3 = c * c * c;\n        double c6 = c3 * c3;\n        return 4.0 * m_eps * ( -12.0 * c6 * c6 / r + 6.0 * c6 / r );\n    }\n    \n    static inline double periodic_bc( double x , double xmax )\n    {\n        return ( x < 0.0 ) ? x + xmax : ( x > xmax ) ? x - xmax : x ;\n    }\n    \n    double m_a;\n    double m_gamma;\n    double m_eps ;\n    double m_sigma ;\n    double m_xmax , m_ymax;\n};\n\n\n\n\n\nint main( int argc , char *argv[] )\n{\n    const size_t n = md_system::n;\n    typedef md_system::vector_type vector_type;\n    \n    \n    std::mt19937 rng;\n    std::normal_distribution<> dist( 0.0 , 1.0 );\n    \n    vector_type x , v;\n    md_system::init_vector_type( x );\n    md_system::init_vector_type( v );\n    \n    for( size_t i=0 ; i<n1 ; ++i )\n    {\n        for( size_t j=0 ; j<n2 ; ++j )\n        {\n            x[i*n2+j  ] = 5.0 + i * 4.0 ;\n            x[i*n2+j+n] = 5.0 + j * 4.0 ;\n            v[i]   = dist( rng ) ;\n            v[i+n] = dist( rng ) ;\n        }\n    }\n    \n    velocity_verlet< vector_type > stepper;\n    const double dt = 0.025;\n    double t = 0.0;\n    md_system sys;\n    for( size_t oi=0 ; oi<100000 ; ++oi )\n    {\n        for( size_t ii=0 ; ii<100 ; ++ii,t+=dt )\n            stepper.do_step( sys , std::make_pair( std::ref( x ) , std::ref( v ) ) , t , dt );\n        sys.bc( x );\n        \n        std::cout << \"set size square\" << \"\\n\";\n        std::cout << \"unset key\" << \"\\n\";\n        std::cout << \"p [0:\" << sys.m_xmax << \"][0:\" << sys.m_ymax << \"] '-' pt 7 ps 0.5\" << \"\\n\";\n        for( size_t i=0 ; i<n ; ++i )\n            std::cout << x[i] << \" \" << x[i+n] << \" \" << v[i] << \" \" << v[i+n] << \"\\n\";\n        std::cout << \"e\" << std::endl;\n    }\n    \n    \n    return 0;\n}\n", "meta": {"hexsha": "e1a82e036f0797f5daf2a9c0f7400b063dcd9565", "size": 4526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/molecular_dynamics.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/molecular_dynamics.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/molecular_dynamics.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": 28.1118012422, "max_line_length": 100, "alphanum_fraction": 0.4659743703, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118068790618, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.5176242441195169}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <rrt/StateSpace.hpp>\n\nnamespace RRT {\n\n/**\n * @brief A 2d plane with continuous states and no obstacles.\n */\ntemplate <class POINT_CLASS = Eigen::Vector2d>\nclass PlaneStateSpace : public StateSpace<POINT_CLASS> {\npublic:\n    PlaneStateSpace(double width, double height)\n        : _width(width), _height(height) {}\n\n    POINT_CLASS randomState() const {\n        return POINT_CLASS(drand48() * width(), drand48() * height());\n    }\n\n    POINT_CLASS intermediateState(const POINT_CLASS& source,\n                                  const POINT_CLASS& target,\n                                  double stepSize) const {\n        POINT_CLASS delta = target - source;\n        delta = delta / delta.norm();  //  unit vector\n\n        POINT_CLASS val = source + delta * stepSize;\n        return val;\n    }\n\n    double distance(const POINT_CLASS& from, const POINT_CLASS& to) const {\n        POINT_CLASS delta = from - to;\n        return sqrtf(powf(delta.x(), 2) + powf(delta.y(), 2));\n    }\n\n    /**\n     * Returns a boolean indicating whether the given point is within bounds.\n     */\n    bool stateValid(const POINT_CLASS& pt) const {\n        return pt.x() >= 0 && pt.y() >= 0 && pt.x() < width() &&\n               pt.y() < height();\n    }\n\n    double width() const { return _width; }\n    double height() const { return _height; }\n\nprivate:\n    double _width, _height;\n};\n\n}  // namespace RRT\n", "meta": {"hexsha": "e9950abd462c3a8250cde2925e15f104813a1b55", "size": 1427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rrt/2dplane/PlaneStateSpace.hpp", "max_stars_repo_name": "huangwen0907/rrt", "max_stars_repo_head_hexsha": "4e89cbf9dbe850f7362955f4c8eae735cad0b71b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 243.0, "max_stars_repo_stars_event_min_datetime": "2015-03-03T01:21:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T09:41:29.000Z", "max_issues_repo_path": "src/rrt/2dplane/PlaneStateSpace.hpp", "max_issues_repo_name": "huangwen0907/rrt", "max_issues_repo_head_hexsha": "4e89cbf9dbe850f7362955f4c8eae735cad0b71b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2015-01-11T02:26:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-15T03:31:26.000Z", "max_forks_repo_path": "src/rrt/2dplane/PlaneStateSpace.hpp", "max_forks_repo_name": "huangwen0907/rrt", "max_forks_repo_head_hexsha": "4e89cbf9dbe850f7362955f4c8eae735cad0b71b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 94.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T00:06:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T01:54:33.000Z", "avg_line_length": 27.4423076923, "max_line_length": 77, "alphanum_fraction": 0.599159075, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5176242356787432}}
{"text": "#ifndef CDTree_H\n#define CDTree_H\n\n#include <iostream>\n#include <fstream>  //\u8bfb\u53d6\u6587\u4ef6\u5185\u5bb9\n#include <map>\n#include <vector>\n#include <string>\n#include <Eigen/Dense>\n#include <cmath>\n\nusing std::cout; using std::cin; using std::cerr; using std::endl;\nusing std::string; using std::ifstream; using std::istringstream;\nusing std::vector; using std::map; using std::ios;\n\nusing Eigen::MatrixXf;   //Eigen Matrix float \u5b58\u50a8\u6570\u636e  \u8bad\u7ec3\u6570\u636e\nusing Eigen::MatrixXi;  //Eigen Matrix int \u5b58\u50a8\u6570\u636e  \u8bad\u7ec3\u6570\u636e\u548c\u6807\u7b7e\nusing Eigen::VectorXi;\nusing Eigen::VectorXf;\n\n\nclass CDTree\n{\t\t\npublic:\n    struct TreeNode\n    {   //\u8282\u70b9\u4fe1\u606f\n        TreeNode* parents;  //\u5f53\u524d\u8282\u70b9\u7684\u53cc\u4eb2\u8282\u70b9\n        int AttributeIndex;   //\u6b64\u8282\u70b9\u5bf9\u5e94\u7684\u5c5e\u6027\u7d22\u5f15\n        bool LeafNode; //\u5224\u65ad\u662f\u5426\u4e3a\u53f6\u5b50\u8282\u70b9\n        vector<TreeNode*> children; //\u5b69\u5b50\u8282\u70b9\u7684\u5730\u5740\u3002\n        int label;  //if it is a leaf node then this prameter is useful\n\n    };\n\n    struct IntervalTree\n    {\n        IntervalTree *leftTree;\n        IntervalTree *rightTree;\n        bool LeafNode;\n        float cutValue;\n        IntervalTree *parients;\n    };\n\n    vector<int> ColsIndex;  //\u6240\u6709\u6570\u636e\u7684\u5217\n    TreeNode* root;\n    int deepestTree; // deepest depth of the tree\n    int max_bin;   // max number of interval on every  continous parameter's cut\n    float thresholdInfoGain; //\u5728\u8ba1\u7b97\n    int trainX_Dimension;\n\n\n\tCDTree(int deepestTree, int max_bin, float thresholdInfoGain);\n    CDTree();\n    int buildTree(const MatrixXf &trainX, const MatrixXi &trainY, const MatrixXf &validateX, const MatrixXi &validateY, string Algorithm);\n    int buildTree(const MatrixXf &trainX, const MatrixXi &trainY, string Algorithm);\n    MatrixXi predict(const MatrixXf &testX);\n    ~CDTree();\n\nprivate:\n    vector<vector<std::pair<float, float>>> intervals;  // \u6bcf\u4e2a\u5c5e\u6027\u7684\u533a\u95f4\u5206\u5272\n    vector<vector<std::pair<float, float>>> continous2discrete(const MatrixXf &trainX, const MatrixXi &trainY);\n    IntervalTree* MultiwayPartitionGain(IntervalTree *parientsNode, const vector<float> &continuousVec, const MatrixXf &trainX, const MatrixXi &trainY, int index, float thresholdInfoGain);\n    int getIntervalsFromTreeStruct(IntervalTree *Intervalroot, vector<float> &intervals);\n    int sortVectorXf(const VectorXf &vec, VectorXf &sorted_vec, VectorXi &ind);\n    int cutBranches(const MatrixXf &validateX, const MatrixXi &validateY);\n    int cutBranches(int deepthTree);\n    TreeNode* AlgorithmID3(TreeNode *parients, const MatrixXf &trainX, const MatrixXi &trainY, vector<int> attrrbuteIndexOfCurrentData);\n\tTreeNode* AlgorithmC4_5(const MatrixXf &trainX, const MatrixXi &trainY);\n\tTreeNode* AlgorithmCART(const MatrixXf &trainX, const MatrixXi &trainY);\n    std::pair<MatrixXf, MatrixXi> splitData(const MatrixXf &trainX, const MatrixXi &trainY, std::pair<float, float> smallInterval, int maxIndex, string flag); \n    int FindMaxInformationGain(vector<float> s);\n    vector<float> CalculateInfGain(const MatrixXf &trainX, const MatrixXi &trainY, vector<int> attributeIndexOfCurrentData);\n    vector<float> getSampleProbability(const MatrixXi &trainY);\n    vector<float> removeColRepetitionValue(const MatrixXf &Col);\n    MatrixXi findDvlabel(const MatrixXf &trainX, const MatrixXi &trainY, int index, std::pair<float, float> smallInterval, string flag);\n    float calculateEntropy(vector<float> probability);\n    bool TheSameLabel(const MatrixXi &trainY);\n    int chooseMostLabel(const MatrixXi &trainY);\n    int findExistandDealwith(int label, vector<std::pair<int, int>> &labelAndNum);\n    int destroyTree(TreeNode* root);\n    int destroyIntervalTree(IntervalTree *root);\n\n    template<typename Type>\n    int KMeans(vector<Type> vec, vector<Type> &newvec, int index);\n    int predictTree(TreeNode *node, const MatrixXf testX);\n\n};\n\n#endif", "meta": {"hexsha": "0c90178fe6f41f155919684e9968937b40ee2d5d", "size": 3657, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "C++ source Code/Continuous/CDTree.hpp", "max_stars_repo_name": "PiggyGaGa/MachineLearning-DecisionTree", "max_stars_repo_head_hexsha": "3c063024405021739509e6cdb3655d5ebf417ebd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2018-07-21T15:18:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T10:09:52.000Z", "max_issues_repo_path": "C++ source Code/Continuous/CDTree.hpp", "max_issues_repo_name": "PiggyGaGa/MachineLearning-DecisionTree", "max_issues_repo_head_hexsha": "3c063024405021739509e6cdb3655d5ebf417ebd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-18T07:38:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T02:51:01.000Z", "max_forks_repo_path": "C++ source Code/Continuous/CDTree.hpp", "max_forks_repo_name": "PiggyGaGa/MachineLearning-DecisionTree", "max_forks_repo_head_hexsha": "3c063024405021739509e6cdb3655d5ebf417ebd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-04-01T05:18:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-20T13:11:47.000Z", "avg_line_length": 41.0898876404, "max_line_length": 188, "alphanum_fraction": 0.7309269893, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5176242311745787}}
{"text": "#pragma once\n\n/// This file contains definitions of aliases for basic vector classes\n#include <Core/RaCore.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Sparse>\n\nnamespace Ra {\nnamespace Core {\n\n//\n// Common vector types\n//\nusing VectorN  = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\nusing VectorNf = Eigen::VectorXf;\nusing VectorNd = Eigen::VectorXd;\n\nusing Vector4  = Eigen::Matrix<Scalar, 4, 1>;\nusing Vector4f = Eigen::Vector4f;\nusing Vector4d = Eigen::Vector4d;\n\nusing Vector3  = Eigen::Matrix<Scalar, 3, 1>;\nusing Vector3f = Eigen::Vector3f;\nusing Vector3d = Eigen::Vector3d;\n\nusing Vector2  = Eigen::Matrix<Scalar, 2, 1>;\nusing Vector2f = Eigen::Vector2f;\nusing Vector2d = Eigen::Vector2d;\n\nusing VectorNi = Eigen::VectorXi;\nusing Vector2i = Eigen::Vector2i;\nusing Vector3i = Eigen::Vector3i;\nusing Vector4i = Eigen::Vector4i;\n\nusing VectorNui = Eigen::Matrix<uint, Eigen::Dynamic, 1>;\nusing Vector1ui = Eigen::Matrix<uint, 1, 1>;\nusing Vector2ui = Eigen::Matrix<uint, 2, 1>;\nusing Vector3ui = Eigen::Matrix<uint, 3, 1>;\nusing Vector4ui = Eigen::Matrix<uint, 4, 1>;\n\nusing Ray  = Eigen::ParametrizedLine<Scalar, 3>;\nusing Rayf = Eigen::ParametrizedLine<float, 3>;\nusing Rayd = Eigen::ParametrizedLine<double, 3>;\n\n//\n// Common matrix types\n//\n\nusing MatrixN = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\nusing Matrix4 = Eigen::Matrix<Scalar, 4, 4>;\nusing Matrix3 = Eigen::Matrix<Scalar, 3, 3>;\nusing Matrix2 = Eigen::Matrix<Scalar, 2, 2>;\n\nusing MatrixNf = Eigen::MatrixXf;\nusing Matrix4f = Eigen::Matrix4f;\nusing Matrix3f = Eigen::Matrix3f;\nusing Matrix2f = Eigen::Matrix2f;\n\nusing MatrixNd = Eigen::MatrixXd;\nusing Matrix4d = Eigen::Matrix4d;\nusing Matrix3d = Eigen::Matrix3d;\nusing Matrix2d = Eigen::Matrix2d;\n\nusing MatrixNui = Eigen::Matrix<uint, Eigen::Dynamic, Eigen::Dynamic>;\n\n// using Diagonal = Eigen::DiagonalMatrix< Scalar, Eigen::Dynamic >;\nusing Diagonal =\n    Eigen::SparseMatrix<Scalar>; // Not optimized for Diagonal matrices, but the operations between\n                                 // Sparse and Diagonal are not defined\nusing Sparse = Eigen::SparseMatrix<Scalar>;\n\n//\n// Transforms and rotations\n//\n\nusing Quaternion  = Eigen::Quaternion<Scalar>;\nusing Quaternionf = Eigen::Quaternionf;\nusing Quaterniond = Eigen::Quaterniond;\n\nusing Transform  = Eigen::Transform<Scalar, 3, Eigen::Affine>;\nusing Transformf = Eigen::Affine3f;\nusing Transformd = Eigen::Affine3d;\n\nusing Aabb  = Eigen::AlignedBox<Scalar, 3>;\nusing Aabbf = Eigen::AlignedBox3f;\nusing Aabbd = Eigen::AlignedBox3d;\n\nusing AngleAxis  = Eigen::AngleAxis<Scalar>;\nusing AngleAxisf = Eigen::AngleAxisf;\nusing AngleAxisd = Eigen::AngleAxisd;\n\nusing Translation  = Eigen::Translation<Scalar, 3>;\nusing Translationf = Eigen::Translation3f;\nusing Translationd = Eigen::Translation3d;\n\n} // namespace Core\n} // namespace Ra\n", "meta": {"hexsha": "895607c16812ac7a3ffad237acaeb22fe658d03b", "size": 2843, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/Types.hpp", "max_stars_repo_name": "Yasoo31/Radium-Engine", "max_stars_repo_head_hexsha": "e22754d0abe192207fd946509cbd63c4f9e52dd4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 78.0, "max_stars_repo_stars_event_min_datetime": "2017-12-01T12:23:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:08:09.000Z", "max_issues_repo_path": "src/Core/Types.hpp", "max_issues_repo_name": "Yasoo31/Radium-Engine", "max_issues_repo_head_hexsha": "e22754d0abe192207fd946509cbd63c4f9e52dd4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 527.0, "max_issues_repo_issues_event_min_datetime": "2017-09-25T13:05:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:47:44.000Z", "max_forks_repo_path": "src/Core/Types.hpp", "max_forks_repo_name": "Yasoo31/Radium-Engine", "max_forks_repo_head_hexsha": "e22754d0abe192207fd946509cbd63c4f9e52dd4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2018-01-04T22:08:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T08:13:41.000Z", "avg_line_length": 28.43, "max_line_length": 99, "alphanum_fraction": 0.7274006331, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5176242303323155}}
{"text": "//\n// Copyright (c) 2018 CNRS\n//\n\n#include \"pinocchio/fwd.hpp\"\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_mass_matrix)\n{\n  using CppAD::AD;\n  using CppAD::NearEqual;\n  \n  typedef double Scalar;\n  typedef AD<Scalar> ADScalar;\n  \n  typedef pinocchio::ModelTpl<Scalar> Model;\n  typedef Model::Data Data;\n\n  typedef pinocchio::ModelTpl<ADScalar> ADModel;\n  typedef ADModel::Data ADData;\n  \n  Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  Data data(model);\n  \n  ADModel ad_model = model.cast<ADScalar>();\n  ADData ad_data(ad_model);\n  \n  // Sample random configuration\n  typedef Model::ConfigVectorType CongigVectorType;\n  typedef Model::TangentVectorType TangentVectorType;\n  CongigVectorType q(model.nq);\n  q = pinocchio::randomConfiguration(model);\n\n  TangentVectorType v(TangentVectorType::Random(model.nv));\n  TangentVectorType a(TangentVectorType::Random(model.nv));\n  \n  typedef ADModel::ConfigVectorType ADCongigVectorType;\n  typedef ADModel::TangentVectorType ADTangentVectorType;\n  \n  ADCongigVectorType ad_q = q.cast<ADScalar>();\n  ADTangentVectorType ad_v = v.cast<ADScalar>();\n  ADTangentVectorType ad_a = a.cast<ADScalar>();\n  \n  typedef Eigen::Matrix<ADScalar,Eigen::Dynamic,1> VectorXAD;\n  pinocchio::crba(model,data,q);\n  data.M.triangularView<Eigen::StrictlyLower>()\n  = data.M.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  Data::TangentVectorType tau = pinocchio::rnea(model,data,q,v,a);\n  \n  {\n    CppAD::Independent(ad_a);\n    pinocchio::rnea(ad_model,ad_data,ad_q,ad_v,ad_a);\n\n    VectorXAD Y(model.nv);\n    Eigen::Map<ADData::TangentVectorType>(Y.data(),model.nv,1) = ad_data.tau;\n\n    CppAD::ADFun<Scalar> ad_fun(ad_a,Y);\n\n    CPPAD_TESTVECTOR(Scalar) x((size_t)model.nv);\n    Eigen::Map<Data::TangentVectorType>(x.data(),model.nv,1) = a;\n\n    CPPAD_TESTVECTOR(Scalar) tau = ad_fun.Forward(0,x);\n    BOOST_CHECK(Eigen::Map<Data::TangentVectorType>(tau.data(),model.nv,1).isApprox(data.tau));\n\n    CPPAD_TESTVECTOR(Scalar) dtau_da = ad_fun.Jacobian(x);\n    Data::MatrixXs M = Eigen::Map<EIGEN_PLAIN_ROW_MAJOR_TYPE(Data::MatrixXs)>(dtau_da.data(),model.nv,model.nv);\n    BOOST_CHECK(M.isApprox(data.M));\n\n  }\n  \n  ADTangentVectorType ad_tau = tau.cast<ADScalar>();\n  \n  pinocchio::computeMinverse(model,data,q);\n  data.Minv.triangularView<Eigen::StrictlyLower>()\n  = data.Minv.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  pinocchio::aba(model,data,q,v,tau);\n  {\n    CppAD::Independent(ad_tau);\n    pinocchio::aba(ad_model,ad_data,ad_q,ad_v,ad_tau);\n    \n    VectorXAD Y(model.nv);\n    Eigen::Map<ADData::TangentVectorType>(Y.data(),model.nv,1) = ad_data.ddq;\n    \n    CppAD::ADFun<Scalar> ad_fun(ad_tau,Y);\n    \n    CPPAD_TESTVECTOR(Scalar) x((size_t)model.nv);\n    Eigen::Map<Data::TangentVectorType>(x.data(),model.nv,1) = tau;\n    \n    CPPAD_TESTVECTOR(Scalar) ddq = ad_fun.Forward(0,x);\n    BOOST_CHECK(Eigen::Map<Data::TangentVectorType>(ddq.data(),model.nv,1).isApprox(a));\n    \n    CPPAD_TESTVECTOR(Scalar) dddq_da = ad_fun.Jacobian(x);\n    Data::MatrixXs Minv = Eigen::Map<EIGEN_PLAIN_ROW_MAJOR_TYPE(Data::MatrixXs)>(dddq_da.data(),model.nv,model.nv);\n    BOOST_CHECK(Minv.isApprox(data.Minv));\n    \n  }\n  \n}\n\nBOOST_AUTO_TEST_CASE(test_kinematics_jacobian)\n{\n  using CppAD::AD;\n  using CppAD::NearEqual;\n\n  typedef double Scalar;\n  typedef AD<Scalar> ADScalar;\n\n  typedef pinocchio::ModelTpl<Scalar> Model;\n  typedef Model::Data Data;\n  typedef Model::Motion Motion;\n  \n  typedef pinocchio::ModelTpl<ADScalar> ADModel;\n  typedef ADModel::Data ADData;\n\n  Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  Data data(model);\n\n  ADModel ad_model = model.cast<ADScalar>();\n  ADData ad_data(ad_model);\n\n  // Sample random configuration\n  typedef Model::ConfigVectorType CongigVectorType;\n  typedef Model::TangentVectorType TangentVectorType;\n  CongigVectorType q(model.nq);\n  q = pinocchio::randomConfiguration(model);\n\n  TangentVectorType v(TangentVectorType::Random(model.nv));\n  TangentVectorType a(TangentVectorType::Random(model.nv));\n  \n  typedef ADModel::ConfigVectorType ADCongigVectorType;\n  typedef ADModel::TangentVectorType ADTangentVectorType;\n  \n  ADCongigVectorType ad_q = q.cast<ADScalar>();\n  ADTangentVectorType ad_v = v.cast<ADScalar>();\n  ADTangentVectorType ad_a = a.cast<ADScalar>();\n\n  // Test if the jacobian of a precise link is given by dv_link/dv\n  const std::string joint_name = \"rarm5_joint\";\n  Model::JointIndex joint_id = model.getJointId(joint_name);\n  pinocchio::computeJointJacobiansTimeVariation(model,data,q,v);\n  pinocchio::forwardKinematics(model,data,q,v,a);\n\n  Data::Matrix6x J_local(6,model.nv), J_global(6,model.nv);\n  J_local.setZero(); J_global.setZero();\n  Data::Matrix6x dJ_local(6,model.nv), dJ_global(6,model.nv);\n  dJ_local.setZero(); dJ_global.setZero();\n  pinocchio::getJointJacobian(model,data,joint_id,pinocchio::LOCAL,J_local);\n  pinocchio::getJointJacobian(model,data,joint_id,pinocchio::WORLD,J_global);\n  \n  pinocchio::getJointJacobianTimeVariation(model,data,joint_id,pinocchio::LOCAL,dJ_local);\n  pinocchio::getJointJacobianTimeVariation(model,data,joint_id,pinocchio::WORLD,dJ_global);\n\n  const ADData::Motion & v_local = ad_data.v[joint_id];\n  const ADData::Motion & a_local = ad_data.a[joint_id];\n  \n  typedef Eigen::Matrix<ADScalar,Eigen::Dynamic,1> VectorXAD;\n  \n  {\n    CppAD::Independent(ad_v);\n    pinocchio::forwardKinematics(ad_model,ad_data,ad_q,ad_v,ad_a);\n\n    const ADData::Motion v_global = ad_data.oMi[joint_id].act(v_local);\n\n    VectorXAD Y(6*3);\n    Eigen::DenseIndex current_id = 0;\n    for(Eigen::DenseIndex k = 0; k < 3; ++k)\n    {\n      Y[current_id+k+Motion::LINEAR] = v_local.linear()[k];\n      Y[current_id+k+Motion::ANGULAR] = v_local.angular()[k];\n    }\n    current_id += 6;\n\n    for(Eigen::DenseIndex k = 0; k < 3; ++k)\n    {\n      Y[current_id+k+Motion::LINEAR] = v_global.linear()[k];\n      Y[current_id+k+Motion::ANGULAR] = v_global.angular()[k];\n    }\n    current_id += 6;\n    \n    for(Eigen::DenseIndex k = 0; k < 3; ++k)\n    {\n      Y[current_id+k+Motion::LINEAR] = a_local.linear()[k];\n      Y[current_id+k+Motion::ANGULAR] = a_local.angular()[k];\n    }\n    current_id += 6;\n\n    CppAD::ADFun<Scalar> vjoint(ad_v,Y);\n\n    CPPAD_TESTVECTOR(Scalar) x((size_t)model.nv);\n    for(Eigen::DenseIndex k = 0; k < model.nv; ++k)\n    {\n      x[(size_t)k] = v[k];\n    }\n\n    CPPAD_TESTVECTOR(Scalar) y = vjoint.Forward(0,x);\n    Scalar * y_ptr = y.data();\n    BOOST_CHECK(data.v[joint_id].isApprox(Motion(Eigen::Map<Motion::Vector6>(y_ptr))));\n    y_ptr += 6;\n    BOOST_CHECK(data.oMi[joint_id].act(data.v[joint_id]).isApprox(Motion(Eigen::Map<Motion::Vector6>(y_ptr))));\n    y_ptr += 6;\n    BOOST_CHECK(data.a[joint_id].isApprox(Motion(Eigen::Map<Motion::Vector6>(y_ptr))));\n    y_ptr += 6;\n\n    CPPAD_TESTVECTOR(Scalar) dY_dv = vjoint.Jacobian(x);\n\n    Scalar * dY_dv_ptr = dY_dv.data();\n    Data::Matrix6x ad_J_local = Eigen::Map<EIGEN_PLAIN_ROW_MAJOR_TYPE(Data::Matrix6x)>(dY_dv_ptr,6,model.nv);\n    dY_dv_ptr += ad_J_local.size();\n    Data::Matrix6x ad_J_global = Eigen::Map<EIGEN_PLAIN_ROW_MAJOR_TYPE(Data::Matrix6x)>(dY_dv_ptr,6,model.nv);\n    dY_dv_ptr += ad_J_global.size();\n\n    BOOST_CHECK(ad_J_local.isApprox(J_local));\n    BOOST_CHECK(ad_J_global.isApprox(J_global));\n  }\n  \n  {\n    CppAD::Independent(ad_a);\n    pinocchio::forwardKinematics(ad_model,ad_data,ad_q,ad_v,ad_a);\n    \n    VectorXAD Y(6*2);\n    Eigen::DenseIndex current_id = 0;\n    for(Eigen::DenseIndex k = 0; k < 3; ++k)\n    {\n      Y[current_id+k+Motion::LINEAR] = v_local.linear()[k];\n      Y[current_id+k+Motion::ANGULAR] = v_local.angular()[k];\n    }\n    current_id += 6;\n    \n    for(Eigen::DenseIndex k = 0; k < 3; ++k)\n    {\n      Y[current_id+k+Motion::LINEAR] = a_local.linear()[k];\n      Y[current_id+k+Motion::ANGULAR] = a_local.angular()[k];\n    }\n    current_id += 6;\n\n    CppAD::ADFun<Scalar> ajoint(ad_a,Y);\n\n    CPPAD_TESTVECTOR(Scalar) x((size_t)model.nv);\n    for(Eigen::DenseIndex k = 0; k < model.nv; ++k)\n    {\n      x[(size_t)k] = a[k];\n    }\n\n    CPPAD_TESTVECTOR(Scalar) y = ajoint.Forward(0,x);\n    Scalar * y_ptr = y.data()+6;\n    BOOST_CHECK(data.a[joint_id].isApprox(Motion(Eigen::Map<Motion::Vector6>(y_ptr))));\n    y_ptr += 6;\n\n    CPPAD_TESTVECTOR(Scalar) dY_da = ajoint.Jacobian(x);\n    \n    Scalar * dY_da_ptr = dY_da.data();\n    Data::Matrix6x ad_dv_da = Eigen::Map<EIGEN_PLAIN_ROW_MAJOR_TYPE(Data::Matrix6x)>(dY_da_ptr,6,model.nv);\n    dY_da_ptr += ad_dv_da.size();\n    Data::Matrix6x ad_J_local = Eigen::Map<EIGEN_PLAIN_ROW_MAJOR_TYPE(Data::Matrix6x)>(dY_da_ptr,6,model.nv);\n    dY_da_ptr += ad_J_local.size();\n\n    BOOST_CHECK(ad_dv_da.isZero());\n    BOOST_CHECK(ad_J_local.isApprox(J_local));\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0806a318a785b24f6f26bbe5c936497336130b43", "size": 9406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/cppad-algo.cpp", "max_stars_repo_name": "matthieuvigne/pinocchio", "max_stars_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "unittest/cppad-algo.cpp", "max_issues_repo_name": "matthieuvigne/pinocchio", "max_issues_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/cppad-algo.cpp", "max_forks_repo_name": "matthieuvigne/pinocchio", "max_forks_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 32.6597222222, "max_line_length": 115, "alphanum_fraction": 0.7034871359, "num_tokens": 2884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5176242196394594}}
{"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/**\n * @file fft.cpp - computing the canonical embedding and related norms\n **/\n#include <complex>\n#include <cmath>\n#include <numeric> // std::accumulate\n#include <algorithm>\n#include <NTL/BasicThreadPool.h>\n#include \"NumbTh.h\"\n#include \"timing.h\"\n#include \"norms.h\"\n#include \"PAlgebra.h\"\nNTL_CLIENT\n\n\nstatic void\nbasicCanonicalEmbedding(std::vector<cx_double>& v, \n                        const std::vector<double>& in, \n                        const PAlgebra& palg)\n{\n  long m = palg.getM();\n  long phimBy2 = divc(palg.getPhiM(),2);\n\n  vector<cx_double> buf(m);\n  for (long i: range(in.size())) buf[i] = in[i];\n  for (long i: range(in.size(), m)) buf[i] = 0;\n  palg.getFFTInfo().apply(&buf[0]);\n\n  v.resize(phimBy2); // the first half of Zm*\n\n  // FIXME: need to document these two different strategies\n  if (palg.getNSlots()==phimBy2) // order roots by the palg order\n    for (long i=0; i<phimBy2; i++)\n      v[phimBy2-i-1] = buf[palg.ith_rep(i)];\n  else                           // order roots sequentially\n    for (long i=1, idx=0; i<=m/2; i++)\n      if (palg.inZmStar(i)) v[idx++] = buf[i];\n}\n\n\n\n// Computing the canonical embedding. This function returns in v only\n// the first half of the entries, the others are v[phi(m)-i]=conj(v[i])\nvoid canonicalEmbedding(std::vector<cx_double>& v,\n                        const zzX& f, const PAlgebra& palg)\n{\n  FHE_TIMER_START;\n\n  vector<double> x;\n  convert(x, f);\n\n  basicCanonicalEmbedding(v, x, palg);\n}\n   \n\n\nvoid canonicalEmbedding(std::vector<cx_double>& v,\n                        const ZZX& f, const PAlgebra& palg)\n{\n  FHE_TIMER_START;\n\n  vector<double> x;\n  convert(x, f.rep);\n\n  basicCanonicalEmbedding(v, x, palg);\n}\n\nvoid canonicalEmbedding(std::vector<cx_double>& v,\n                        const std::vector<double>& f, const PAlgebra& palg)\n{\n  FHE_TIMER_START;\n\n  basicCanonicalEmbedding(v, f, palg);\n}\n\n// Roughly the inverse of canonicalEmbedding, except for scaling and\n// rounding issues. Calling embedInSlots(f,v,palg,1.0,strictInverse=true)\n// after setting canonicalEmbedding(v, f, palg), is sure to recover the\n// same f, but embedInSlots(f,v,palg,1.0,strictInverse=false) may return\n// a different \"nearby\" f.\nvoid embedInSlots(zzX& f, const std::vector<cx_double>& v,\n                  const PAlgebra& palg, double scaling, bool strictInverse)\n{\n  FHE_TIMER_START;\n  long m = palg.getM();\n  long phimBy2 = divc(palg.getPhiM(),2);\n  vector<cx_double> avv(m);\n  for (auto& x: avv) x = 0.0;\n\n  if (palg.getNSlots()==phimBy2) // roots ordered by the palg order\n    for (long i=0; i<palg.getNSlots(); i++) {\n      long j = palg.ith_rep(i);\n      long ii = palg.getNSlots()-i-1;\n      if (ii < lsize(v)) {\n        avv[j] = scaling*v[ii];\n        avv[m-j] = std::conj(avv[j]);\n      }\n    }\n  else                           // roots ordered sequentially\n    for (long i=1, idx=0; i<=m/2 && idx<lsize(v); i++) {\n      if (palg.inZmStar(i)) {\n        avv[i] = scaling*v[idx++];\n        avv[m-i] = std::conj(avv[i]);\n      }\n    }\n\n\n  // Compute the inverse FFT and extract the real part.\n\n  // NOTES:\n  // For a polynomial f with complex coeffs, and w a root of unity,\n  // we have f(conj(w)) = conj(conj(f)(w)).  So we can compute\n  // an inverse FFT of f as conj(FFT(conj(f)))/m.  Since we only\n  // extract the real part, we can skip the outer conj.\n\n\n  for (long i: range(m)) avv[i] = conj(avv[i]);\n  palg.getFFTInfo().apply(&avv[0]);\n  vector<double> av(m);\n\n  // if strictInverse we need to scale up by m, so we just skip\n  // the division by m step required by the inverse fft\n  if (!strictInverse) {\n    double m_inv = 1/double(m);\n    for (long i: range(m)) av[i] = avv[i].real() * m_inv;\n  }\n\n  // If v was obtained by canonicalEmbedding(v,f,palg,1.0) then we have\n  // the guarantee that m*av is an integral polynomial, and moreover\n  // m*av mod Phi_m(x) is in m*Z[X].\n\n  // round to an integer polynomial\n  f.SetLength(m);\n  for (long i: range(m)) f[i] = std::round(av[i]);\n\n  reduceModPhimX(f, palg);\n\n  if (strictInverse) f /= m;  // scale down by m\n  normalize(f);\n}\n\n\n", "meta": {"hexsha": "592aa81f5a2188174a4b1cfbf0a5618219ef5232", "size": 4688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fft.cpp", "max_stars_repo_name": "pememoni/HElib", "max_stars_repo_head_hexsha": "96838a91b4d248573f9be7e3428d060bc4813da3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T04:55:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-04T04:55:29.000Z", "max_issues_repo_path": "src/fft.cpp", "max_issues_repo_name": "PNIDEMOOO/HElib", "max_issues_repo_head_hexsha": "7427ed3709bb9872835324dd0007a97b3ca3baca", "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/fft.cpp", "max_forks_repo_name": "PNIDEMOOO/HElib", "max_forks_repo_head_hexsha": "7427ed3709bb9872835324dd0007a97b3ca3baca", "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.4415584416, "max_line_length": 75, "alphanum_fraction": 0.6369453925, "num_tokens": 1370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5175701950101282}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;  \n    \n\ntemplate <typename Vector>\nvoid test(Vector& v, const char* name)\n{\n    typedef typename mtl::Collection<Vector>::value_type value_type;\n    using mtl::max;\n\n    v = value_type(-2);\n    std::cout << \"\\n\" << name << \"  --- v = \" << v << std::endl;\n    std::cout << \"max(v) is \" << max(v) << std::endl;\n\n    if (max(v) >= value_type(-1))\n\tthrow \"Max value too large\\n\";\n\n}\n \n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    dense_vector<float>   u(5);\n    dense_vector<short int>     vs(5);\n    dense_vector<int>     v(5);\n    dense_vector<long int>     vl(5);\n    dense_vector<double>  x(5);\n\n    test(vs, \"test short int\");\n    test(v, \"test int\");\n    test(vl, \"test long int\");\n    test(u, \"test float\");\n    test(x, \"test double\");\n\n    dense_vector<float, vec::parameters<row_major> >   ur(5);\n    test(ur, \"test float in row vector\");\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    dense_vector<long double>  xl(5);\n    test(xl, \"test long double\");\n#endif   \n\n    return 0;\n}\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "4f4b397dce5d9ded632d250a873ab5d14145a738", "size": 1543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/vector_max_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_max_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_max_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": 20.038961039, "max_line_length": 94, "alphanum_fraction": 0.6234607907, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5175701869946143}}
{"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#include <NTL/ZZ.h>\n#include <algorithm>\n#include <complex>\n\n#include <helib/norms.h>\n#include <helib/helib.h>\n#include <helib/debugging.h>\n#include <helib/ArgMap.h>\n\nNTL_CLIENT\nusing namespace helib;\n\nbool verbose = false;\n\nbool reset = false;\n\n// Compute the L-infinity distance between two vectors\ndouble calcMaxDiff(const vector<cx_double>& v1, const vector<cx_double>& v2)\n{\n\n  if (lsize(v1) != lsize(v2))\n    NTL::Error(\"Vector sizes differ.\\nFAILED\\n\");\n\n  double maxDiff = 0.0;\n  for (long i = 0; i < lsize(v1); i++) {\n    double diffAbs = std::abs(v1[i] - v2[i]);\n    if (diffAbs > maxDiff)\n      maxDiff = diffAbs;\n  }\n\n  return maxDiff;\n}\n// Compute the max relative difference between two vectors\ndouble calcMaxRelDiff(const vector<cx_double>& v1, const vector<cx_double>& v2)\n{\n  if (lsize(v1) != lsize(v2))\n    NTL::Error(\"Vector sizes differ.\\nFAILED\\n\");\n\n  // Compute the largest-magnitude value in the vector\n  double maxAbs = 0.0;\n  for (auto& x : v1) {\n    if (std::abs(x) > maxAbs)\n      maxAbs = std::abs(x);\n  }\n  if (maxAbs < 1e-10)\n    maxAbs = 1e-10;\n\n  double maxDiff = 0.0;\n  for (long i = 0; i < lsize(v1); i++) {\n    double relDiff = std::abs(v1[i] - v2[i]) / maxAbs;\n    if (relDiff > maxDiff)\n      maxDiff = relDiff;\n  }\n\n  return maxDiff;\n}\n\ninline bool cx_equals(const vector<cx_double>& v1,\n                      const vector<cx_double>& v2,\n                      double epsilon)\n{\n  return (calcMaxRelDiff(v1, v2) < epsilon);\n}\n\nvoid testBasicArith(const PubKey& publicKey,\n                    const SecKey& secretKey,\n                    const EncryptedArrayCx& ea,\n                    double epsilon);\nvoid testComplexArith(const PubKey& publicKey,\n                      const SecKey& secretKey,\n                      const EncryptedArrayCx& ea,\n                      double epsilon);\nvoid testRotsNShifts(const PubKey& publicKey,\n                     const SecKey& secretKey,\n                     const EncryptedArrayCx& ea,\n                     double epsilon);\n\nvoid debugCompare(const EncryptedArrayCx& ea,\n                  const SecKey& sk,\n                  vector<cx_double>& p,\n                  const Ctxt& c,\n                  double epsilon)\n{\n  double maxAbs = 0.0;\n  for (auto& x : p) {\n    if (std::abs(x) > maxAbs)\n      maxAbs = std::abs(x);\n  }\n  vector<cx_double> pp;\n  ea.decrypt(c, sk, pp);\n\n  double err = calcMaxDiff(p, pp);\n  double err_bnd = NTL::conv<double>(c.getNoiseBound() / c.getRatFactor());\n  double log2_ratio = std::log(err / err_bnd) / std::log(2.0);\n  std::cout << \"    \"\n            //<< \" relative-error=\"<<calcMaxRelDiff(p,pp)\n            << \" err=\" << err << \" ptxtMag=\" << c.getPtxtMag()\n            << \" maxAbs=\" << maxAbs << \" ratFactor=\"\n            << c.getRatFactor()\n            //<< \" noiseBound=\" << c.getNoiseBound()\n            << \" log2(err/bound)=\" << log2_ratio\n            << \" log2(ptxt/bound)=\" << (log(maxAbs / c.getPtxtMag()) / log(2.0))\n            << endl;\n  //  if (!cx_equals(pp, p, epsilon)) {\n  //    std::cout << \"oops:\\n\"; std::cout << p << \"\\n\";\n  //    std::cout << pp << \"\\n\";\n  //    exit(0);\n  //  }\n}\n\nvoid negateVec(vector<cx_double>& p1)\n{\n  for (auto& x : p1)\n    x = -x;\n}\nvoid add(vector<cx_double>& to, const vector<cx_double>& from)\n{\n  if (to.size() < from.size())\n    to.resize(from.size(), 0);\n  for (long i = 0; i < from.size(); i++)\n    to[i] += from[i];\n}\nvoid sub(vector<cx_double>& to, const vector<cx_double>& from)\n{\n  if (to.size() < from.size())\n    to.resize(from.size(), 0);\n  for (long i = 0; i < from.size(); i++)\n    to[i] -= from[i];\n}\nvoid mul(vector<cx_double>& to, const vector<cx_double>& from)\n{\n  if (to.size() < from.size())\n    to.resize(from.size(), 0);\n  for (long i = 0; i < from.size(); i++)\n    to[i] *= from[i];\n}\nvoid rotate(vector<cx_double>& p, long amt)\n{\n  long sz = p.size();\n  vector<cx_double> tmp(sz);\n  for (long i = 0; i < sz; i++)\n    tmp[((i + amt) % sz + sz) % sz] = p[i];\n  p = tmp;\n}\n\nvoid resetPtxtMag(Ctxt& c, const vector<cx_double>& p)\n{\n  double maxAbs = 0.0;\n  for (auto& x : p) {\n    if (std::abs(x) > maxAbs)\n      maxAbs = std::abs(x);\n  }\n\n  if (maxAbs < 1.0)\n    maxAbs = 1.0;\n  else\n    maxAbs = std::pow(\n        2,\n        std::ceil(std::log(maxAbs) / std::log(2))); // next power of two\n\n  c.setPtxtMag(NTL::xdouble(maxAbs));\n}\n\n/************** Each round consists of the following:\ntmp1 = rotate(c0)\ntmp1 += const1\nc0 += const2\nc0 *= tmp1  // c0 = (rotate(c0) + const1)*(c0 + const2) ...squared every round\n\ntmp2 = c1 * const1\nc1 = rotate(c1)\nc1 += tmp2  // c1 = rotate(c1) + c1*const1 ...doubled every round\n\n\ntmp3 = c2 * const2\nc2 *= c3\nc2 += tmp3 // c2 = = c2*c3 + c2*const2 = c2*(c3 + const2)\n\nc3 = c3*const1\n**************/\n\n#define DEBUG_COMPARE(C, P, M)                                                 \\\n  do {                                                                         \\\n    if (verbose) {                                                             \\\n      CheckCtxt(C, M);                                                         \\\n      debugCompare(ea, secretKey, P, C, epsilon);                              \\\n    }                                                                          \\\n  } while (0)\n\nvoid testGeneralOps(const PubKey& publicKey,\n                    const SecKey& secretKey,\n                    const EncryptedArrayCx& ea,\n                    double epsilon,\n                    long nRounds)\n{\n  long nslots = ea.size();\n  char buffer[32];\n\n  vector<cx_double> p0, p1, p2, p3;\n  ea.random(p0);\n  ea.random(p1);\n  ea.random(p2);\n  ea.random(p3);\n\n  Ctxt c0(publicKey), c1(publicKey), c2(publicKey), c3(publicKey);\n  ea.encrypt(c0, publicKey, p0, /*size=*/1.0);\n  ea.encrypt(c1, publicKey, p1, /*size=*/1.0);\n  ea.encrypt(c2, publicKey, p2, /*size=*/1.0);\n  ea.encrypt(c3, publicKey, p3, /*size=*/1.0);\n\n  resetAllTimers();\n  HELIB_NTIMER_START(Circuit);\n\n  for (long i = 0; i < nRounds; i++) {\n\n    if (verbose)\n      std::cout << \"*** round \" << i << \"...\" << endl;\n\n    if (reset) {\n      resetPtxtMag(c0, p0);\n      resetPtxtMag(c1, p1);\n      resetPtxtMag(c2, p2);\n      resetPtxtMag(c3, p3);\n    }\n\n    long rotamt = RandomBnd(2 * nslots - 1) - (nslots - 1);\n    // random number in [-(nslots-1)..nslots-1]\n\n    // two random constants\n    vector<cx_double> const1, const2;\n    ea.random(const1);\n    ea.random(const2);\n\n    ZZX const1_poly, const2_poly;\n    ea.encode(const1_poly, const1, /*size=*/1.0);\n    ea.encode(const2_poly, const2, /*size=*/1.0);\n\n    vector<cx_double> tmp1_p(p0);\n    rotate(tmp1_p, rotamt);\n    Ctxt tmp1(c0);\n    ea.rotate(tmp1, rotamt);\n    DEBUG_COMPARE(tmp1, tmp1_p, \"tmp1 = rotate(c0)\");\n\n    add(tmp1_p, const1);\n    tmp1.addConstant(const1_poly);\n    DEBUG_COMPARE(tmp1, tmp1_p, \"tmp1 += const1\");\n\n    add(p0, const2);\n    c0.addConstant(const2_poly);\n    DEBUG_COMPARE(c0, p0, \"c0 += const2\");\n\n    mul(p0, tmp1_p);\n    c0.multiplyBy(tmp1);\n    DEBUG_COMPARE(c0, p0, \"c0 *= tmp1\");\n\n    vector<cx_double> tmp2_p(p1);\n    mul(tmp2_p, const1);\n    Ctxt tmp2(c1);\n    tmp2.multByConstant(const1_poly);\n    DEBUG_COMPARE(tmp2, tmp2_p, \"tmp2 = c1 * const1\");\n\n    rotate(p1, rotamt);\n    ea.rotate(c1, rotamt);\n    DEBUG_COMPARE(c1, p1, \"c1 = rotate(c1)\");\n\n    add(p1, tmp2_p);\n    c1 += tmp2;\n    DEBUG_COMPARE(c1, p1, \"c1 += tmp2\");\n\n    vector<cx_double> tmp3_p(p2);\n    mul(tmp3_p, const2);\n    Ctxt tmp3(c2);\n    tmp3.multByConstant(const2_poly);\n    DEBUG_COMPARE(tmp3, tmp3_p, \"tmp3 = c2 * const2\");\n\n    mul(p2, p3);\n    c2.multiplyBy(c3);\n    DEBUG_COMPARE(c2, p2, \"c2 *= c3\");\n\n    add(p2, tmp3_p);\n    c2.addCtxt(tmp3);\n    DEBUG_COMPARE(c2, p2, \"c2 += tmp3\");\n\n    mul(p3, const1);\n    c3.multByConstant(const1_poly);\n    DEBUG_COMPARE(c3, p3, \"c3 *= const1\");\n\n    if (verbose) {\n      // Check correctness after each round\n      vector<cx_double> pp0, pp1, pp2, pp3;\n\n      ea.decrypt(c0, secretKey, pp0);\n      ea.decrypt(c1, secretKey, pp1);\n      ea.decrypt(c2, secretKey, pp2);\n      ea.decrypt(c3, secretKey, pp3);\n\n      if (!(cx_equals(pp0, p0, epsilon) && cx_equals(pp1, p1, epsilon) &&\n            cx_equals(pp2, p2, epsilon) && cx_equals(pp3, p3, epsilon))) {\n        std::cout << \"FAIL AT ROUND \" << i << \"\\n\";\n        break;\n      }\n    }\n  }\n\n  c0.cleanUp();\n  c1.cleanUp();\n  c2.cleanUp();\n  c3.cleanUp();\n\n  HELIB_NTIMER_STOP(Circuit);\n\n  vector<cx_double> pp0, pp1, pp2, pp3;\n\n  ea.decrypt(c0, secretKey, pp0);\n  ea.decrypt(c1, secretKey, pp1);\n  ea.decrypt(c2, secretKey, pp2);\n  ea.decrypt(c3, secretKey, pp3);\n\n  std::cout << \"Test \" << nRounds << \" rounds of mixed operations, \";\n  if (cx_equals(pp0, p0, epsilon) && cx_equals(pp1, p1, epsilon) &&\n      cx_equals(pp2, p2, epsilon) && cx_equals(pp3, p3, epsilon))\n    std::cout << \"PASS\\n\\n\";\n  else {\n    std::cout << \"FAIL\\n\\n\";\n    //    std::cout << \"  max(p0)=\"<<largestCoeff(p0)\n    //              << \", max(pp0)=\"<<largestCoeff(pp0)\n    //              << \", maxDiff=\"<<calcMaxDiff(p0,pp0) << endl;\n    //    std::cout << \"  max(p1)=\"<<largestCoeff(p1)\n    //              << \", max(pp1)=\"<<largestCoeff(pp1)\n    //              << \", maxDiff=\"<<calcMaxDiff(p1,pp1) << endl;\n    //    std::cout << \"  max(p2)=\"<<largestCoeff(p2)\n    //              << \", max(pp2)=\"<<largestCoeff(pp2)\n    //              << \", maxDiff=\"<<calcMaxDiff(p2,pp2) << endl;\n    //    std::cout << \"  max(p3)=\"<<largestCoeff(p3)\n    //              << \", max(pp3)=\"<<largestCoeff(pp3)\n    //              << \", maxDiff=\"<<calcMaxDiff(p3,pp3) << endl<<endl;\n  }\n\n  if (verbose) {\n    std::cout << endl;\n    // printAllTimers();\n    std::cout << endl;\n  }\n  resetAllTimers();\n}\n\nint main(int argc, char* argv[])\n{\n\n  // Commandline setup\n\n  ArgMap amap;\n\n  long m = 16;\n  long r = 8;\n  long L = 0;\n  double epsilon = 0.01; // Accepted accuracy\n  long R = 1;\n  long seed = 0;\n  bool debug = false;\n\n  amap.arg(\"m\", m, \"Cyclotomic index\");\n  amap.note(\"e.g., m=1024, m=2047\");\n  amap.arg(\"r\", r, \"Bits of precision\");\n  amap.arg(\"R\", R, \"number of rounds\");\n  amap.arg(\"L\", L, \"Number of bits in modulus\", \"heuristic\");\n  amap.arg(\"ep\", epsilon, \"Accepted accuracy\");\n  amap.arg(\"seed\", seed, \"PRG seed\");\n  amap.arg(\"verbose\", verbose, \"more printouts\");\n  amap.arg(\"debug\", debug, \"for debugging\");\n  amap.arg(\"reset\", reset, \"forces calls to setPtxtMag each round\");\n\n  amap.parse(argc, argv);\n\n  if (seed)\n    NTL::SetSeed(ZZ(seed));\n\n  if (R <= 0)\n    R = 1;\n  if (L == 0) {\n    if (R <= 2)\n      L = 100 * R;\n    else\n      L = 220 * (R - 1);\n  }\n\n  if (verbose) {\n    cout << \"** m=\" << m << \", #rounds=\" << R << \", |q|=\" << L\n         << \", epsilon=\" << epsilon << endl;\n  }\n  try {\n\n    // FHE setup keys, context, SKMs, etc\n\n    Context context(m, /*p=*/-1, r);\n    context.scale = 4;\n    buildModChain(context, L, /*c=*/2);\n\n    SecKey secretKey(context);\n    secretKey.GenSecKey();        // A +-1/0 secret key\n    addSome1DMatrices(secretKey); // compute key-switching matrices\n\n    const PubKey publicKey = secretKey;\n    const EncryptedArrayCx& ea = context.ea->getCx();\n\n    if (verbose) {\n      std::cout << \"security=\" << context.securityLevel() << endl;\n      ea.getPAlgebra().printout();\n      cout << \"r = \" << context.getAlMod().getR() << endl;\n      cout << \"ctxtPrimes=\" << context.ctxtPrimes\n           << \", specialPrimes=\" << context.specialPrimes << endl\n           << endl;\n    }\n    if (debug) {\n      dbgKey = &secretKey;\n      dbgEa = context.ea;\n    }\n#ifdef HELIB_DEBUG\n    dbgKey = &secretKey;\n    dbgEa = context.ea;\n#endif // HELIB_DEBUG\n\n    // Run the tests.\n    testBasicArith(publicKey, secretKey, ea, epsilon);\n    testComplexArith(publicKey, secretKey, ea, epsilon);\n    testRotsNShifts(publicKey, secretKey, ea, epsilon);\n    testGeneralOps(publicKey, secretKey, ea, epsilon, R);\n  } catch (exception& e) {\n    cerr << e.what() << endl;\n    cerr << \"***Major FAIL***\" << endl;\n  }\n\n  return 0;\n}\n\nvoid testBasicArith(const PubKey& publicKey,\n                    const SecKey& secretKey,\n                    const EncryptedArrayCx& ea,\n                    double epsilon)\n{\n  if (verbose)\n    cout << \"Test Arithmetic \";\n  // Test objects\n\n  Ctxt c1(publicKey), c2(publicKey), c3(publicKey);\n\n  vector<cx_double> vd;\n  vector<cx_double> vd1, vd2, vd3;\n  ea.random(vd1);\n  ea.random(vd2);\n\n  // test encoding of shorter vectors\n  vd1.resize(vd1.size() - 2);\n  ea.encrypt(c1, publicKey, vd1, /*size=*/1.0);\n  vd1.resize(vd1.size() + 2, 0.0);\n\n  ea.encrypt(c2, publicKey, vd2, /*size=*/1.0);\n\n  // Test - Multiplication\n  c1 *= c2;\n  for (long i = 0; i < lsize(vd1); i++)\n    vd1[i] *= vd2[i];\n\n  ZZX poly;\n  ea.random(vd3);\n  ea.encode(poly, vd3, /*size=*/1.0);\n  c1.addConstant(poly); // vd1*vd2 + vd3\n  for (long i = 0; i < lsize(vd1); i++)\n    vd1[i] += vd3[i];\n\n  // Test encoding, encryption of a single number\n  double xx = NTL::RandomLen_long(16) / double(1L << 16); // random in [0,1]\n  ea.encryptOneNum(c2, publicKey, xx);\n  c1 += c2;\n  for (auto& x : vd1)\n    x += xx;\n\n  // Test - Multiply by a mask\n  vector<long> mask(lsize(vd1), 1);\n  for (long i = 0; i * (i + 1) < lsize(mask); i++) {\n    mask[i * i] = 0;\n    mask[i * (i + 1)] = -1;\n  }\n\n  ea.encode(poly, mask, /*size=*/1.0);\n  c1.multByConstant(poly); // mask*(vd1*vd2 + vd3)\n  for (long i = 0; i < lsize(vd1); i++)\n    vd1[i] *= mask[i];\n\n  // Test - Addition\n  ea.random(vd3);\n  ea.encrypt(c3, publicKey, vd3, /*size=*/1.0);\n  c1 += c3;\n  for (long i = 0; i < lsize(vd1); i++)\n    vd1[i] += vd3[i];\n\n  c1.negate();\n  c1.addConstant(to_ZZ(1));\n  for (long i = 0; i < lsize(vd1); i++)\n    vd1[i] = 1.0 - vd1[i];\n\n  // Diff between approxNums HE scheme and plaintext floating\n  ea.decrypt(c1, secretKey, vd);\n#ifdef HELIB_DEBUG\n  printVec(cout << \"res=\", vd, 10) << endl;\n  printVec(cout << \"vec=\", vd1, 10) << endl;\n#endif\n  if (verbose)\n    cout << \"(max |res-vec|_{infty}=\" << calcMaxDiff(vd, vd1) << \"): \";\n\n  if (cx_equals(vd, vd1, conv<double>(epsilon * c1.getPtxtMag())))\n    cout << \"GOOD\\n\";\n  else {\n    cout << \"BAD:\\n\";\n    std::cout << \"  max(vd)=\" << largestCoeff(vd)\n              << \", max(vd1)=\" << largestCoeff(vd1)\n              << \", maxDiff=\" << calcMaxDiff(vd, vd1) << endl\n              << endl;\n  }\n}\n\nvoid testComplexArith(const PubKey& publicKey,\n                      const SecKey& secretKey,\n                      const EncryptedArrayCx& ea,\n                      double epsilon)\n{\n\n  // Test complex conjugate\n  Ctxt c1(publicKey), c2(publicKey);\n\n  vector<cx_double> vd;\n  vector<cx_double> vd1, vd2;\n  ea.random(vd1);\n  ea.random(vd2);\n\n  ea.encrypt(c1, publicKey, vd1, /*size=*/1.0);\n  ea.encrypt(c2, publicKey, vd2, /*size=*/1.0);\n\n  if (verbose)\n    cout << \"Test Conjugate: \";\n  for_each(vd1.begin(), vd1.end(), [](cx_double& d) { d = std::conj(d); });\n  c1.complexConj();\n  ea.decrypt(c1, secretKey, vd);\n#ifdef HELIB_DEBUG\n  printVec(cout << \"vd1=\", vd1, 10) << endl;\n  printVec(cout << \"res=\", vd, 10) << endl;\n#endif\n  if (cx_equals(vd, vd1, conv<double>(epsilon * c1.getPtxtMag())))\n    cout << \"GOOD\\n\";\n  else {\n    cout << \"BAD:\\n\";\n    std::cout << \"  max(vd)=\" << largestCoeff(vd)\n              << \", max(vd1)=\" << largestCoeff(vd1)\n              << \", maxDiff=\" << calcMaxDiff(vd, vd1) << endl\n              << endl;\n  }\n\n  // Test that real and imaginary parts are actually extracted.\n  Ctxt realCtxt(c2), imCtxt(c2);\n  vector<cx_double> realParts(vd2), real_dec;\n  vector<cx_double> imParts(vd2), im_dec;\n\n  if (verbose)\n    cout << \"Test Real and Im parts: \";\n  for_each(realParts.begin(), realParts.end(), [](cx_double& d) {\n    d = std::real(d);\n  });\n  for_each(imParts.begin(), imParts.end(), [](cx_double& d) {\n    d = std::imag(d);\n  });\n\n  ea.extractRealPart(realCtxt);\n  ea.decrypt(realCtxt, secretKey, real_dec);\n\n  ea.extractImPart(imCtxt);\n  ea.decrypt(imCtxt, secretKey, im_dec);\n\n#ifdef HELIB_DEBUG\n  printVec(cout << \"vd2=\", vd2, 10) << endl;\n  printVec(cout << \"real=\", realParts, 10) << endl;\n  printVec(cout << \"res=\", real_dec, 10) << endl;\n  printVec(cout << \"im=\", imParts, 10) << endl;\n  printVec(cout << \"res=\", im_dec, 10) << endl;\n#endif\n  if (cx_equals(realParts,\n                real_dec,\n                conv<double>(epsilon * realCtxt.getPtxtMag())) &&\n      cx_equals(imParts, im_dec, conv<double>(epsilon * imCtxt.getPtxtMag())))\n    cout << \"GOOD\\n\";\n  else {\n    cout << \"BAD:\\n\";\n    std::cout << \"  max(re)=\" << largestCoeff(realParts)\n              << \", max(re1)=\" << largestCoeff(real_dec)\n              << \", maxDiff=\" << calcMaxDiff(realParts, real_dec) << endl;\n    std::cout << \"  max(im)=\" << largestCoeff(imParts)\n              << \", max(im1)=\" << largestCoeff(im_dec)\n              << \", maxDiff=\" << calcMaxDiff(imParts, im_dec) << endl\n              << endl;\n  }\n}\n\nvoid testRotsNShifts(const PubKey& publicKey,\n                     const SecKey& secretKey,\n                     const EncryptedArrayCx& ea,\n                     double epsilon)\n{\n\n  long nplaces = NTL::RandomBnd(ea.size() / 2) + 1;\n\n  if (verbose)\n    cout << \"Test Rotation of \" << nplaces << \": \";\n\n  Ctxt c1(publicKey);\n  vector<cx_double> vd1;\n  vector<cx_double> vd_dec;\n  ea.random(vd1);\n  ea.encrypt(c1, publicKey, vd1, /*size=*/1.0);\n\n#ifdef HELIB_DEBUG\n  printVec(cout << \"vd1=\", vd1, 10) << endl;\n#endif\n  std::rotate(vd1.begin(), vd1.end() - nplaces, vd1.end());\n  ea.rotate(c1, nplaces);\n  c1.reLinearize();\n  ea.decrypt(c1, secretKey, vd_dec);\n#ifdef HELIB_DEBUG\n  printVec(cout << \"vd1(rot)=\", vd1, 10) << endl;\n  printVec(cout << \"res: \", vd_dec, 10) << endl;\n#endif\n\n  if (cx_equals(vd1, vd_dec, conv<double>(epsilon * c1.getPtxtMag())))\n    cout << \"GOOD\\n\";\n  else {\n    cout << \"BAD:\\n\";\n    std::cout << \"  max(vd)=\" << largestCoeff(vd_dec)\n              << \", max(vd1)=\" << largestCoeff(vd1)\n              << \", maxDiff=\" << calcMaxDiff(vd_dec, vd1) << endl\n              << endl;\n  }\n}\n", "meta": {"hexsha": "0450351445855918d931491bf258f74c4b98f034", "size": 18444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tapprox.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": "src/tapprox.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": "src/tapprox.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": 28.2883435583, "max_line_length": 80, "alphanum_fraction": 0.5555194101, "num_tokens": 5789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5175701869946143}}
{"text": "/*\n * H2L2PlusL2H1.cpp\n *\n *  Created on: 13.03.2018\n *      Author: thies\n */\n\n#include <base/Util.h>\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/lac/sparse_direct.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/sparsity_pattern.h>\n#include <deal.II/lac/vector.h>\n#include <norms/H1H1.h>\n#include <norms/H1L2.h>\n#include <norms/H2L2.h>\n#include <norms/H2L2PlusL2H1.h>\n#include <norms/L2Coefficients.h>\n#include <stddef.h>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\nnamespace wavepi {\nnamespace norms {\n\nusing namespace dealii;\n\ninline double square(const double x) { return x * x; }\ninline double pow4(const double x) { return x * x * x * x; }\n\ntemplate <int dim>\nH2L2PlusL2H1<dim>::H2L2PlusL2H1(double alpha, double beta, double gamma) : alpha_(alpha), beta_(beta), gamma_(gamma) {}\n\ntemplate <int dim>\ndouble H2L2PlusL2H1<dim>::norm(const DiscretizedFunction<dim>& u) const {\n  auto mesh = u.get_mesh();\n\n  // we may be able to use v, but this might introduce inconsistencies in the adjoints\n  // Note: this function works even for non-constant meshes.\n  auto deriv = u.calculate_derivative();\n\n  // using deriv.calculate_derivative feels wrong, better use a specialized formula.\n  auto deriv2 = u.calculate_second_derivative();\n\n  double result = 0;\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    double nrm2 = mesh->get_mass_matrix(i)->matrix_norm_square(u[i]) +\n                  gamma_ * mesh->get_laplace_matrix(i)->matrix_norm_square(u[i]);\n    double nrm2_deriv  = mesh->get_mass_matrix(i)->matrix_norm_square(deriv[i]);\n    double nrm2_deriv2 = mesh->get_mass_matrix(i)->matrix_norm_square(deriv2[i]);\n\n    // + trapezoidal rule in time:\n    if (i > 0)\n      result += (nrm2 + alpha_ * nrm2_deriv + beta_ * nrm2_deriv2) / 2 *\n                (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n\n    if (i < mesh->length() - 1)\n      result += (nrm2 + alpha_ * nrm2_deriv + beta_ * nrm2_deriv2) / 2 *\n                (std::abs(mesh->get_time(i + 1) - mesh->get_time(i)));\n  }\n\n  return std::sqrt(result);\n}\n\ntemplate <int dim>\ndouble H2L2PlusL2H1<dim>::dot(const DiscretizedFunction<dim>& u, const DiscretizedFunction<dim>& v) const {\n  auto mesh     = u.get_mesh();\n  double result = 0.0;\n\n  // we may be able to use v, but this might introduce inconsistencies in the adjoints\n  // Note: this function works even for non-constant meshes.\n  auto deriv  = u.calculate_derivative();\n  auto Vderiv = v.calculate_derivative();\n\n  // using deriv.calculate_derivative feels wrong, better use a specialized formula.\n  auto deriv2  = u.calculate_second_derivative();\n  auto Vderiv2 = v.calculate_second_derivative();\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    double doti = mesh->get_mass_matrix(i)->matrix_scalar_product(u[i], v[i]) +\n                  gamma_ * mesh->get_laplace_matrix(i)->matrix_scalar_product(u[i], v[i]);\n    double doti_deriv  = mesh->get_mass_matrix(i)->matrix_scalar_product(deriv[i], Vderiv[i]);\n    double doti_deriv2 = mesh->get_mass_matrix(i)->matrix_scalar_product(deriv2[i], Vderiv2[i]);\n\n    // + trapezoidal rule in time\n    if (i > 0)\n      result += (doti + alpha_ * doti_deriv + beta_ * doti_deriv2) / 2 *\n                (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n\n    if (i < mesh->length() - 1)\n      result += (doti + alpha_ * doti_deriv + beta_ * doti_deriv2) / 2 *\n                (std::abs(mesh->get_time(i + 1) - mesh->get_time(i)));\n  }\n\n  return result;\n}\n\ntemplate <int dim>\nvoid H2L2PlusL2H1<dim>::dot_transform(DiscretizedFunction<dim>& u) {\n  auto mesh = u.get_mesh();\n\n  // X = (T + \\alpha D^t T D + \\beta D_2^t T D_2) * M + gamma T L,\n  // M = blocks of mass matrices, D = derivative, T = trapezoidal rule, L = blocks of laplace matrices\n  DiscretizedFunction<dim> lap_u(mesh, u.get_norm());\n  for (size_t i = 0; i < mesh->length(); i++)\n    mesh->get_laplace_matrix(i)->vmult(lap_u[i], u[i]);\n\n  u.mult_mass();\n\n  auto dx  = u.calculate_derivative();\n  auto d2x = u.calculate_second_derivative();\n\n  // add laplace term\n  u.add(gamma_, lap_u);\n\n  // trapezoidal rule\n  // (has to happen between D and D^t for dx)\n  for (size_t i = 0; i < mesh->length(); i++) {\n    double factor = 0.0;\n\n    if (i > 0) factor += std::abs(mesh->get_time(i) - mesh->get_time(i - 1)) / 2.0;\n    if (i < mesh->length() - 1) factor += std::abs(mesh->get_time(i + 1) - mesh->get_time(i)) / 2.0;\n\n    dx[i] *= factor;\n    d2x[i] *= factor;\n    u[i] *= factor;\n  }\n\n  auto dtdx   = dx.calculate_derivative_transpose();\n  auto d2td2x = d2x.calculate_second_derivative_transpose();\n\n  // add derivative terms\n  u.add(alpha_, dtdx);\n  u.add(beta_, d2td2x);\n}\n\ntemplate <int dim>\nvoid H2L2PlusL2H1<dim>::dot_transform_inverse(DiscretizedFunction<dim>& u) {\n  LogStream::Prefix p(\"h2l2plush1h1_transform_inverse\");\n  Timer timer;\n  timer.start();\n  // Use CG to invert `dot_transform` (the application of a symmetric+positive definite matrix A)\n\n  // make sure we use standard dot products everywhere\n  auto orig_norm = u.get_norm();\n  u.set_norm(std::make_shared<L2Coefficients<dim>>());\n\n  // auto precon = std::make_shared<L2Coefficients<dim>>(alpha_); // -> no preconditioning\n  // auto precon = std::make_shared<H1L2<dim>>(alpha_);\n  // auto precon = std::make_shared<H1H1<dim>>(alpha_, gamma_);\n  auto precon = std::make_shared<H2L2<dim>>(alpha_, beta_);\n\n  // use memory of u for the residual\n  DiscretizedFunction<dim>& r = u;\n\n  DiscretizedFunction<dim> h = r;\n  precon->dot_mult_mass_and_transform_inverse(h);  // faster than just transform_inverse, results are better as well\n\n  DiscretizedFunction<dim> d = h;\n  DiscretizedFunction<dim> x(u.get_mesh(), u.get_norm());  // current estimate, initialize with 0\n  DiscretizedFunction<dim> z(u.get_mesh(), u.get_norm());  // memory for A*d\n\n  const double tol      = 1e-6;\n  const double max_iter = 10000;\n  const double norm_rhs = r.norm();\n  double disc           = norm_rhs;\n  double dot_rh         = r * h;\n  size_t iter           = 0;\n\n  // in this case the solution is zero, which u apparently already is\n  if (disc == 0.0) return;\n\n  while (disc / norm_rhs >= tol && iter++ < max_iter) {\n    LogStream::Prefix p(\"CG\");\n\n    // z <- A d\n    z = d;\n    dot_transform(z);\n\n    double cg_alpha = dot_rh / (d * z);\n    x.add(cg_alpha, d);\n    r.add(-cg_alpha, z);\n\n    h = r;\n    precon->dot_mult_mass_and_transform_inverse(h);\n\n    // prepare direction for next step\n    double dot_rh_next = r * h;\n    double cg_beta     = dot_rh_next / dot_rh;\n    d.sadd(cg_beta, 1.0, h);\n\n    dot_rh = dot_rh_next;\n    disc   = r.norm();\n\n    deallog << \"i=\" << iter << \": rdisc = \" << disc / norm_rhs << std::endl;\n  }\n\n  AssertThrow(disc / norm_rhs <= tol, ExcMessage(\"h2l2plush1h1_transform_inverse: no convergence in CG\"));\n\n  // finished\n  u = x;\n\n  // to be consistent with other norms, they do not change the norm setting as well (although using it after this\n  // transform makes little sense)\n  u.set_norm(orig_norm);\n  deallog << \"solved in \" << Util::format_duration(timer.wall_time()) << \" after \" << iter << \" CG steps\" << std::endl;\n}\n\n// code without preconditioning:\n/*\ntemplate <int dim>\nvoid H2L2PlusL2H1<dim>::dot_transform_inverse(DiscretizedFunction<dim>& u)  {\n  LogStream::Prefix p(\"h2l2plush1h1_transform_inverse\");\n  // Use CG to invert `dot_transform` (the application of a symmetric+positive definite matrix A)\n\n  // make sure we use standard dot products everywhere\n  auto orig_norm = u.get_norm();\n  u.set_norm(std::make_shared<L2Coefficients<dim>>());\n\n  // use memory of u for the residual\n  DiscretizedFunction<dim>& r = u;\n\n  DiscretizedFunction<dim> d = r;\n  DiscretizedFunction<dim> x(u.get_mesh(), u.get_norm());  // current estimate, initialize with 0\n  DiscretizedFunction<dim> z(u.get_mesh(), u.get_norm());  // memory for A*d\n\n  const double tol      = 1e-7;\n  const double max_iter = 10000;\n  const double norm_rhs = r.norm();\n  double disc           = norm_rhs;\n  size_t iter           = 0;\n\n  // in this case the solution is zero, which u apparently already is\n  if (disc == 0.0) return;\n\n  while (disc / norm_rhs >= tol && iter++ < max_iter) {\n    // z <- A d\n    z = d;\n    dot_transform(z);\n\n    double cg_alpha = square(disc) / (d * z);\n    x.add(cg_alpha, d);\n    r.add(-cg_alpha, z);\n\n    double disc_new = r.norm();\n\n    // prepare direction for next step\n    double cg_beta = square(disc_new / disc);\n    d.sadd(cg_beta, 1.0, r);\n\n    disc = disc_new;\n\n    deallog << \"i=\" << iter << \": rdisc = \" << disc / norm_rhs << std::endl;\n  }\n\n  AssertThrow(disc / norm_rhs <= tol, ExcMessage(\"h2l2plush1h1_transform_inverse: no convergence in CG\"));\n\n  // finished\n  u = x;\n\n  // to be consistent with other norms, they do not change the norm setting as well (although using it after this\n  // transform makes little sense)\n  u.set_norm(orig_norm);\n}\n */\n\ntemplate <int dim>\nvoid H2L2PlusL2H1<dim>::dot_solve_mass_and_transform(DiscretizedFunction<dim>& u) {\n  u.solve_mass();\n  dot_transform(u);\n}\n\ntemplate <int dim>\nvoid H2L2PlusL2H1<dim>::dot_mult_mass_and_transform_inverse(DiscretizedFunction<dim>& u) {\n  u.mult_mass();\n  dot_transform_inverse(u);\n}\n\ntemplate <int dim>\nstd::string H2L2PlusL2H1<dim>::name() const {\n  return \"H\u00b2([0,T], L\u00b2(\u03a9)) \u2229 L\u00b2([0,T], H\u00b9(\u03a9))\";\n}\n\ntemplate <int dim>\nstd::string H2L2PlusL2H1<dim>::unique_id() const {\n  return \"H\u00b2([0,T], L\u00b2(\u03a9)) \u2229 L\u00b2([0,T], H\u00b9(\u03a9)) with \u03b1=\" + std::to_string(alpha_) + \", \u03b2=\" + std::to_string(beta_) +\n         \", \u0263=\" + std::to_string(gamma_);\n}\n\ntemplate class H2L2PlusL2H1<1>;\ntemplate class H2L2PlusL2H1<2>;\ntemplate class H2L2PlusL2H1<3>;\n\n} /* namespace norms */\n} /* namespace wavepi */\n", "meta": {"hexsha": "afa60a2e9e498fb8ce55d8d33b87488571e8fd0b", "size": 9704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/norms/H2L2PlusL2H1.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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": "lib/norms/H2L2PlusL2H1.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/norms/H2L2PlusL2H1.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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.3466666667, "max_line_length": 119, "alphanum_fraction": 0.6591096455, "num_tokens": 2914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5175307886116428}}
{"text": "#include <algorithm>\n#include <armadillo>\n#include \"constants.hpp\"\n#include \"conversion.hpp\"\n\nConversion::Conversion(const double mass, const double length, const double time) {\n    const double internal_length = AU2SI_LEN;\n    const double internal_mass =   AU2SI_MASS;\n    const double internal_time =   AU2SI_TIME;\n    const double internal_velocity =  internal_length/internal_time;  // m/s\n    const double internal_energy = internal_mass * internal_length * internal_length /\n                                    (internal_time * internal_time);\n    const double internal_gradient = internal_energy/internal_length;\n    //\n    const double energy = mass * length * length/(time * time);\n    const double gradient = energy/length;\n    const double velocity = length/time;\n    //\n    _energy_au2md = internal_energy/energy;\n    _energy_md2au = energy/internal_energy;\n    // coordinates\n    _crd_au2md = internal_length/length;\n    _crd_md2au = length/internal_length;\n    // velocities\n    _veloc_au2md = internal_velocity/velocity;\n    _veloc_md2au = velocity/internal_velocity;\n    // gradient\n    _grd_au2md = internal_gradient/gradient;\n    _grd_md2au = gradient/internal_gradient;\n    // mass\n    _mass_au2md = internal_mass/mass;\n    _mass_md2au = mass/internal_mass; \n    //\n};\n", "meta": {"hexsha": "76c1106b98918c1633a5bc1b038c9e6fe7241abe", "size": 1289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gifs_src/conversion.cpp", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "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": "gifs_src/conversion.cpp", "max_issues_repo_name": "farajilab/gifs_release", "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gifs_src/conversion.cpp", "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "avg_line_length": 36.8285714286, "max_line_length": 86, "alphanum_fraction": 0.7106283941, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788077, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5175307784592821}}
{"text": "//\n//  steps.cpp\n//  yamcmc++\n//\n//  Created by Brandon Kelly on 3/2/13.\n//  Copyright (c) 2013 Brandon Kelly. All rights reserved.\n//\n\n#include <boost/timer.hpp>\n// Local includes\n#include \"include/steps.hpp\"\n\n// Global random number generator object, instantiated in random.cpp\nextern boost::random::mt19937 rng;\n\n// Object containing some common random number generators.\nRandomGenerator RandGen;\n\n/* ****** Methods of AdaptiveMetro class ********* */\n\n// Constructor, requires a parameter object, a proposal object, an initial\n// covariance matrix for the multivariate proposals, a target acceptance rate,\n// and the maximum number of iterations to perform the adaptations for.\nAdaptiveMetro::AdaptiveMetro(Parameter<arma::vec>& parameter, Proposal<double>& proposal,\n                             arma::mat proposal_covar, double target_rate, int maxiter) :\nparameter_(parameter), proposal_(proposal),\ntarget_rate_(target_rate), maxiter_(maxiter)\n{\n\tgamma_ = 2.0 / 3.0;\n\tniter_ = 0;\n\tnaccept_ = 0;\n\tchol_factor_ = arma::chol(proposal_covar);\n}\n\n// Method to calculate whether the proposal is accepted\nbool AdaptiveMetro::Accept(arma::vec new_value, arma::vec old_value) {\n\t\n\t// MH accept/reject criteria: Proposal must be symmetric!!\n\talpha_ = (parameter_.LogDensity(new_value) - parameter_.GetLogDensity()) / parameter_.GetTemperature();\n    \n\tif (!arma::is_finite(alpha_)) {\n\t\t// New value of the log-posterior is not finite, so reject this\n\t\t// proposal\n        alpha_ = 0.0;\n\t\treturn false;\n\t}\n\t\n\tdouble unif = uniform_(rng);\n\talpha_ = std::min(exp(alpha_), 1.0);\n\tif (unif < alpha_) {\n\t\tnaccept_++;\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\n// Method to perform the RAM step. This involves a standard Metropolis-Hastings update, followed\n// by an update to the proposal scale matrix so long as niter < maxiter\nvoid AdaptiveMetro::DoStep()\n{\n\tarma::vec old_value = parameter_.Value();\n    \n\t// Draw a new parameter vector\n\tarma::vec unit_proposal(old_value.n_rows);\n\tfor (int i=0; i<old_value.n_rows; i++) {\n\t\t// Unscaled proposal\n\t\tunit_proposal(i) = proposal_.Draw(0.0);\n\t}\n\t\n\t// Scaled proposal vector\n\tarma::vec scaled_proposal = chol_factor_.t() * unit_proposal;\n\tarma::vec new_value = old_value + scaled_proposal;\n\t\n\t// MH accept/reject criteria\n\tif (Accept(new_value, old_value)) {\n\t\tparameter_.Save(new_value);\n\t}\n    \n    double step_size, unit_norm;\n    \n\tif ((niter_ < maxiter_) && arma::is_finite(alpha_)) {\n\t\t// Still in the adaptive stage, so update the scale matrix cholesky factor\n\t\t\n\t\t// The step size sequence for the scale matrix update. This is eta_n in the\n\t\t// notation of Vihola (2012)\n\t\tstep_size = std::min(1.0, new_value.n_rows / pow(niter_, gamma_));\n        \n\t\tunit_norm = arma::norm(unit_proposal, 2);\n        \n\t\t// Rescale the proposal vector for updating the scale matrix cholesky factor\n\t\tscaled_proposal = sqrt(step_size * fabs(alpha_ - target_rate_)) / unit_norm * scaled_proposal;\n        \n\t\t// Update or downdate the Cholesky factor?\n\t\tbool downdate = (alpha_ < target_rate_);\n        \n\t\t// Perform the rank-1 update (downdate) of the scale matrix Cholesky factor\n\t\tCholUpdateR1(chol_factor_, scaled_proposal, downdate);\n\t}\n    \n\tniter_++;\n\t\n\tif (niter_ == maxiter_) {\n\t\tdouble arate = ((double)(naccept_)) / ((double)(niter_));\n\t\tstd::cout << \"Average RAM Acceptance Rate is \" << arate << std::endl;\n\t}\n}\n\n// Function to perform the rank-1 Cholesky update, needed for updating the\n// proposal covariance matrix\nvoid CholUpdateR1(arma::mat& L, arma::vec& v, bool downdate)\n{\n\tdouble sign = 1.0;\n\tif (downdate) {\n\t\t// Perform the downdate instead\n\t\tsign = -1.0;\n\t}\n\tfor (int k=0; k<L.n_rows; k++) {\n\t\tdouble r = sqrt( L(k,k) * L(k,k) + sign * v(k) * v(k) );\n\t\tdouble c = r / L(k,k);\n\t\tdouble s = v(k) / L(k,k);\n\t\tL(k,k) = r;\n\t\tif (k < L.n_rows-1) {\n\t\t\tL(k,arma::span(k+1,L.n_rows-1)) = (L(k,arma::span(k+1,L.n_rows-1)) +\n                                               sign * s * v(arma::span(k+1,v.n_elem-1)).t()) / c;\n\t\t\tv(arma::span(k+1,v.n_elem-1)) = c * v(arma::span(k+1,v.n_elem-1)) -\n\t\t\ts * L(k,arma::span(k+1,L.n_rows-1)).t();\n\t\t}\n\t\t\n\t}\n}\n\n", "meta": {"hexsha": "80c3b437072abc5e93a9acb6367ee1c6b2a59321", "size": 4095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/steps.cpp", "max_stars_repo_name": "Jamieryan/carma_pack", "max_stars_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2015-01-25T19:24:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T11:55:28.000Z", "max_issues_repo_path": "src/steps.cpp", "max_issues_repo_name": "Jamieryan/carma_pack", "max_issues_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-04-29T12:37:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T23:31:29.000Z", "max_forks_repo_path": "src/steps.cpp", "max_forks_repo_name": "Jamieryan/carma_pack", "max_forks_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-09-15T00:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T07:28:47.000Z", "avg_line_length": 30.7894736842, "max_line_length": 104, "alphanum_fraction": 0.6666666667, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5174247415278111}}
{"text": "\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/program_options.hpp>\n\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\n\nstruct VertexData {\n  std::string name;\n  double x,y,z;\n};\n\nstruct EdgeData {\n  double distance;\n};\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS,\n                              boost::undirectedS,\n                              VertexData,\n                              boost::property<boost::edge_weight_t, double, EdgeData>\n                              > MyGraphType;\n\n\n\n// these are needed by readvtk\ntypedef typename boost::graph_traits<MyGraphType>::vertex_descriptor vertex_descriptor;\ntypedef typename boost::graph_traits<MyGraphType>::edge_descriptor   edge_descriptor;\ntypename boost::graph_traits<MyGraphType>::vertex_descriptor\nadd_vertex(MyGraphType &G, std::string& vname, double x, double y, double z)\n{\n  typedef typename boost::graph_traits<MyGraphType>::vertex_descriptor vertex_descriptor;\n  vertex_descriptor v = add_vertex(G);\n  G[v].x = x;\n  G[v].y = y;\n  G[v].z = z;\n  return v;\n}\n\ninline\ndouble distance(MyGraphType &G,\n                typename boost::graph_traits<MyGraphType>::vertex_descriptor v1,\n                typename boost::graph_traits<MyGraphType>::vertex_descriptor v2)\n{\n  return sqrt((G[v1].x - G[v2].x)*(G[v1].x - G[v2].x) +\n              (G[v1].y - G[v2].y)*(G[v1].y - G[v2].y) +\n              (G[v1].z - G[v2].z)*(G[v1].z - G[v2].z));\n}\n\n\ntypename boost::graph_traits<MyGraphType>::edge_descriptor\nadd_edge(MyGraphType &G,\n         typename boost::graph_traits<MyGraphType>::vertex_descriptor v1,\n         typename boost::graph_traits<MyGraphType>::vertex_descriptor v2)\n{\n  typedef typename boost::graph_traits<MyGraphType>::edge_descriptor edge_descriptor;\n  edge_descriptor e = add_edge(v1, v2, G).first;\n  boost::property_map<MyGraphType, boost::edge_weight_t>::type weightmap = get(boost::edge_weight, G);\n  weightmap[e] = distance(G, v1, v2);\n  return e;\n}\n\n\n\n#include <readvtk.hxx>\n\n\nenum MSTAlgorithm { PRIM, KRUSKAL };\nstd::istream& operator>>(std::istream& in, MSTAlgorithm &format)\n{\n    std::string token;\n    in >> token;\n    if (token == \"prim\")\n        format = PRIM;\n    else if (token == \"kruskal\")\n        format = KRUSKAL;\n    else \n        in.setstate(std::ios_base::failbit);\n    return in;\n}\n\n\nint\nmain(int argc,char* argv[])\n{\n\n  namespace po = boost::program_options;\n  po::options_description desc(\"Usage\");\n\n  std::string filename;\n  desc.add_options()\n    (\"help\", \"produce help message\")\n    (\"filename\", po::value<std::string>(&filename)->default_value(\"\"),\n     \"filename containing input points\");\n\n  MSTAlgorithm mst_algorithm;\n    desc.add_options()\n        (\"algorithm\", po::value<MSTAlgorithm>(&mst_algorithm)->default_value(KRUSKAL),\n         \"which output format\");    \n\n  po::variables_map opts;\n  po::store(po::parse_command_line(argc, argv, desc), opts);\n\n  try {\n    po::notify(opts);\n  } catch (std::exception& e) {\n    std::cerr << \"Error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n\n  if (filename == \"\") {\n    std::cerr << \"please provide a vtk file with the --filename <file> option\" << std::endl;\n    exit(-1);\n  }\n\n\n  \n  MyGraphType G;\n\n  std::ifstream input(filename);\n  readvtk<MyGraphType,vertex_descriptor>(input, G);\n\n  \n  std::cerr << \"running prim\" << std::endl;\n  std::vector<vertex_descriptor> mst_prim(num_vertices(G));\n\n  std::cout << \"# vtk DataFile Version 1.0\\n\";\n  std::cout << \"3D triangulation data\\n\";\n  std::cout << \"ASCII\\n\";\n  std::cout << std::endl;\n  std::cout << \"DATASET POLYDATA\\n\";\n\n  std::cout << \"POINTS \" << num_vertices(G) << \" float\\n\";\n  for(int i=0; i<num_vertices(G); i++) {\n    std::cout << G[i].x  << \" \" << G[i].y << \" \" << G[i].z << std::endl;\n  }\n\n  std::cout << \"LINES \" << (num_vertices(G)-1) << \" \" << (num_vertices(G)-1)*3 << std::endl;\n  if (mst_algorithm == PRIM) {\n  \n    // the not particularly helpful doc for iterator_property_map:\n    // http://www.boost.org/doc/libs/1_64_0/libs/property_map/doc/iterator_property_map.html\n    // iterator_property_map<RandomAccessIterator, OffsetMap, T, R>\n    //\n    typedef boost::property_map<MyGraphType, boost::vertex_index_t>::type IdMap;\n    boost::iterator_property_map<std::vector<vertex_descriptor>::iterator,\n                                 IdMap,\n                                 vertex_descriptor,\n                                 vertex_descriptor&>\n      predmap(mst_prim.begin(), get(boost::vertex_index, G));\n                                       \n    boost::prim_minimum_spanning_tree(G, predmap);\n\n    for(int i=0; i<num_vertices(G); i++) {\n      if (i == mst_prim[i]) {\n        std::cerr << \"skipping \" << i << std::endl;\n        continue;\n      }\n      std::cout << \"2 \" << i << \" \" << mst_prim[i] << std::endl;\n    }\n  }\n\n  if (mst_algorithm == KRUSKAL) {\n    std::cerr << \"running kruskal\" << std::endl;\n    std::list<boost::graph_traits<MyGraphType>::edge_descriptor> mst_kruskal;\n    boost::kruskal_minimum_spanning_tree(G, std::back_inserter(mst_kruskal));\n\n    for(auto iter=mst_kruskal.begin();\n        iter != mst_kruskal.end();\n        iter++) {\n      std::cout << \"2 \" << source(*iter, G) << \" \" << target(*iter, G) <<std::endl;\n    }\n  }\n  \n}\n", "meta": {"hexsha": "2994a38693218b0b41d9c94715306bb21aa7e17b", "size": 5490, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "mst3d/mst3d.cxx", "max_stars_repo_name": "mmccoo/nerd_mmccoo", "max_stars_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2017-06-21T07:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T01:39:02.000Z", "max_issues_repo_path": "mst3d/mst3d.cxx", "max_issues_repo_name": "zxh1986123/nerd_mmccoo", "max_issues_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-02-08T19:29:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-14T09:27:18.000Z", "max_forks_repo_path": "mst3d/mst3d.cxx", "max_forks_repo_name": "zxh1986123/nerd_mmccoo", "max_forks_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-02-12T21:18:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T23:04:51.000Z", "avg_line_length": 29.6756756757, "max_line_length": 102, "alphanum_fraction": 0.6265938069, "num_tokens": 1452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5174247244850866}}
{"text": "#include \"mtf/SSM/ProjectiveBase.h\"\r\n#include <boost/random/random_device.hpp>\r\n#include <boost/random/seed_seq.hpp>\r\n#include \"mtf/Utilities/warpUtils.h\"\r\n#include \"mtf/Utilities/miscUtils.h\"\r\n\r\n_MTF_BEGIN_NAMESPACE\r\n\r\nProjectiveBase::ProjectiveBase(const SSMParams *params) :\r\nStateSpaceModel(params){\r\n\tinit_pts_hm.resize(Eigen::NoChange, n_pts);\r\n\tcurr_pts_hm.resize(Eigen::NoChange, n_pts);\r\n\tnorm_pts.resize(Eigen::NoChange, n_pts);\r\n\tnorm_pts_hm.resize(Eigen::NoChange, n_pts);\r\n\tutils::getNormUnitSquarePts(norm_pts, norm_corners, resx, resy);\r\n\tutils::homogenize(norm_pts, norm_pts_hm);\r\n\tutils::homogenize(norm_corners, norm_corners_hm);\r\n}\r\n\r\nvoid ProjectiveBase::getPtsFromCorners(ProjWarpT &warp, PtsT &pts, HomPtsT &pts_hm,\r\n\tconst CornersT &corners){\r\n\twarp = utils::computeHomographyDLT(norm_corners, corners);\r\n\tpts_hm = warp * norm_pts_hm;\r\n\tutils::dehomogenize(pts_hm, pts);\r\n}\r\n\r\nvoid ProjectiveBase::setCorners(const CornersT& corners){\r\n\tcurr_corners = corners;\r\n\tgetPtsFromCorners(curr_warp, curr_pts, curr_pts_hm, curr_corners);\r\n\tutils::homogenize(curr_corners, curr_corners_hm);\r\n\r\n\tinit_corners = curr_corners;\r\n\tinit_pts = curr_pts;\r\n\tinit_corners_hm = curr_corners_hm;\r\n\tutils::homogenize(init_pts, init_pts_hm);\r\n\r\n\tcurr_warp = Matrix3d::Identity();\r\n\tcurr_state.fill(0);\r\n}\r\n\r\nvoid ProjectiveBase::setState(const VectorXd &ssm_state){\r\n\tvalidate_ssm_state(ssm_state);\r\n\tcurr_state = ssm_state;\r\n\tgetWarpFromState(curr_warp, curr_state);\r\n\tcurr_pts_hm.noalias() = curr_warp * init_pts_hm;\r\n\tcurr_corners_hm.noalias() = curr_warp * init_corners_hm;\r\n\tutils::dehomogenize(curr_pts_hm, curr_pts);\r\n\tutils::dehomogenize(curr_corners_hm, curr_corners);\r\n}\r\n\r\nvoid ProjectiveBase::additiveUpdate(const VectorXd& state_update){\r\n\tvalidate_ssm_state(state_update);\r\n\tcurr_state += state_update;\r\n\tsetState(curr_state);\r\n}\r\n\r\nvoid ProjectiveBase::invertState(VectorXd& inv_state, const VectorXd& state){\r\n\tgetWarpFromState(warp_mat, state);\r\n\tinv_warp_mat = warp_mat.inverse();\r\n\tinv_warp_mat /= inv_warp_mat(2, 2);\r\n\tgetStateFromWarp(inv_state, inv_warp_mat);\r\n}\r\n\r\nvoid ProjectiveBase::updateGradPts(double grad_eps){\r\n\tVector3d diff_vec_x_warped = curr_warp.col(0) * grad_eps;\r\n\tVector3d diff_vec_y_warped = curr_warp.col(1) * grad_eps;\r\n\r\n\tVector3d pt_inc_warped, pt_dec_warped;\r\n\tfor(unsigned int pt_id = 0; pt_id < n_pts; pt_id++){\r\n\t\tpt_inc_warped = curr_pts_hm.col(pt_id) + diff_vec_x_warped;\r\n\t\tgrad_pts(0, pt_id) = pt_inc_warped(0) / pt_inc_warped(2);\r\n\t\tgrad_pts(1, pt_id) = pt_inc_warped(1) / pt_inc_warped(2);\r\n\r\n\t\tpt_dec_warped = curr_pts_hm.col(pt_id) - diff_vec_x_warped;\r\n\t\tgrad_pts(2, pt_id) = pt_dec_warped(0) / pt_dec_warped(2);\r\n\t\tgrad_pts(3, pt_id) = pt_dec_warped(1) / pt_dec_warped(2);\r\n\r\n\t\tpt_inc_warped = curr_pts_hm.col(pt_id) + diff_vec_y_warped;\r\n\t\tgrad_pts(4, pt_id) = pt_inc_warped(0) / pt_inc_warped(2);\r\n\t\tgrad_pts(5, pt_id) = pt_inc_warped(1) / pt_inc_warped(2);\r\n\r\n\t\tpt_dec_warped = curr_pts_hm.col(pt_id) - diff_vec_y_warped;\r\n\t\tgrad_pts(6, pt_id) = pt_dec_warped(0) / pt_dec_warped(2);\r\n\t\tgrad_pts(7, pt_id) = pt_dec_warped(1) / pt_dec_warped(2);\r\n\t}\r\n}\r\n\r\nvoid ProjectiveBase::updateHessPts(double hess_eps){\r\n\tdouble hess_eps2 = 2 * hess_eps;\r\n\r\n\tVector3d diff_vec_xx_warped = curr_warp.col(0) * hess_eps2;\r\n\tVector3d diff_vec_yy_warped = curr_warp.col(1) * hess_eps2;\r\n\tVector3d diff_vec_xy_warped = (curr_warp.col(0) + curr_warp.col(1)) * hess_eps;\r\n\tVector3d diff_vec_yx_warped = (curr_warp.col(0) - curr_warp.col(1)) * hess_eps;\r\n\r\n\tVector3d pt_inc_warped, pt_dec_warped;\r\n\r\n\tfor(unsigned int pt_id = 0; pt_id < n_pts; pt_id++){\r\n\r\n\t\tpt_inc_warped = curr_pts_hm.col(pt_id) + diff_vec_xx_warped;\r\n\t\thess_pts(0, pt_id) = pt_inc_warped(0) / pt_inc_warped(2);\r\n\t\thess_pts(1, pt_id) = pt_inc_warped(1) / pt_inc_warped(2);\r\n\r\n\t\tpt_dec_warped = curr_pts_hm.col(pt_id) - diff_vec_xx_warped;\r\n\t\thess_pts(2, pt_id) = pt_dec_warped(0) / pt_dec_warped(2);\r\n\t\thess_pts(3, pt_id) = pt_dec_warped(1) / pt_dec_warped(2);\r\n\r\n\t\tpt_inc_warped = curr_pts_hm.col(pt_id) + diff_vec_yy_warped;\r\n\t\thess_pts(4, pt_id) = pt_inc_warped(0) / pt_inc_warped(2);\r\n\t\thess_pts(5, pt_id) = pt_inc_warped(1) / pt_inc_warped(2);\r\n\r\n\t\tpt_dec_warped = curr_pts_hm.col(pt_id) - diff_vec_yy_warped;\r\n\t\thess_pts(6, pt_id) = pt_dec_warped(0) / pt_dec_warped(2);\r\n\t\thess_pts(7, pt_id) = pt_dec_warped(1) / pt_dec_warped(2);\r\n\r\n\t\tpt_inc_warped = curr_pts_hm.col(pt_id) + diff_vec_xy_warped;\r\n\t\thess_pts(8, pt_id) = pt_inc_warped(0) / pt_inc_warped(2);\r\n\t\thess_pts(9, pt_id) = pt_inc_warped(1) / pt_inc_warped(2);\r\n\r\n\t\tpt_dec_warped = curr_pts_hm.col(pt_id) - diff_vec_xy_warped;\r\n\t\thess_pts(10, pt_id) = pt_dec_warped(0) / pt_dec_warped(2);\r\n\t\thess_pts(11, pt_id) = pt_dec_warped(1) / pt_dec_warped(2);\r\n\r\n\t\tpt_inc_warped = curr_pts_hm.col(pt_id) + diff_vec_yx_warped;\r\n\t\thess_pts(12, pt_id) = pt_inc_warped(0) / pt_inc_warped(2);\r\n\t\thess_pts(13, pt_id) = pt_inc_warped(1) / pt_inc_warped(2);\r\n\r\n\t\tpt_dec_warped = curr_pts_hm.col(pt_id) - diff_vec_yx_warped;\r\n\t\thess_pts(14, pt_id) = pt_dec_warped(0) / pt_dec_warped(2);\r\n\t\thess_pts(15, pt_id) = pt_dec_warped(1) / pt_dec_warped(2);\r\n\t}\r\n}\r\n\r\nvoid ProjectiveBase::applyWarpToCorners(Matrix24d &warped_corners, const Matrix24d &orig_corners,\r\n\tconst VectorXd &ssm_state){\r\n\tgetWarpFromState(warp_mat, ssm_state);\r\n\tfor(unsigned int corner_id = 0; corner_id < 4; corner_id++){\r\n\t\tapplyWarpToPt(warped_corners(0, corner_id), warped_corners(1, corner_id),\r\n\t\t\torig_corners(0, corner_id), orig_corners(1, corner_id), warp_mat);\r\n\t}\r\n}\r\nvoid ProjectiveBase::applyWarpToPts(Matrix2Xd &warped_pts, const Matrix2Xd &orig_pts,\r\n\tconst VectorXd &ssm_state){\r\n\tgetWarpFromState(warp_mat, ssm_state);\r\n\tint n_pts = orig_pts.cols();\r\n\tfor(int pt_id = 0; pt_id < n_pts; ++pt_id){\r\n\t\tapplyWarpToPt(warped_pts(0, pt_id), warped_pts(1, pt_id),\r\n\t\t\torig_pts(0, pt_id), orig_pts(1, pt_id), warp_mat);\r\n\t}\r\n}\r\n\r\nvoid ProjectiveBase::applyWarpToPt(double &warped_x, double &warped_y, double x, double y,\r\n\tconst ProjWarpT &warp){\r\n\tdouble discr = warp(2, 0)*x + warp(2, 1)*y + warp(2, 2);\r\n\twarped_x = (warp(0, 0)*x + warp(0, 1)*y + warp(0, 2)) / discr;\r\n\twarped_y = (warp(1, 0)*x + warp(1, 1)*y + warp(1, 2)) / discr;\r\n}\r\n\r\n// -------------------------------------------------------------------------- //\r\n// --------------------------- Stochastic Sampler --------------------------- //\r\n// -------------------------------------------------------------------------- //\r\n\r\nvoid ProjectiveBase::initializeSampler(const VectorXd &_state_sigma,\r\n\tconst VectorXd &_state_mean){\r\n\tVectorXd state_sigma(state_size), state_mean(state_size);\r\n\tif(_state_sigma.size() == 1){\r\n\t\tstate_sigma.fill(_state_sigma[0]);\r\n\t} else if(_state_sigma.size() != state_size){\r\n\t\tthrow utils::InvalidArgument(\r\n\t\t\tcv::format(\"ProjectiveBase::initializeSampler :: SSM sigma has invalid size %d\\n\",\r\n\t\t\t_state_sigma.size()));\r\n\t} else{\r\n\t\tstate_sigma = _state_sigma;\r\n\t}\r\n\tif(_state_mean.size() == 1){\r\n\t\tstate_mean.fill(_state_mean[0]);\r\n\t} else if(_state_mean.size() != state_size){\r\n\t\tthrow utils::InvalidArgument(\r\n\t\t\tcv::format(\"ProjectiveBase::initializeSampler :: SSM mean has invalid size %d\\n\",\r\n\t\t\t_state_mean.size()));\r\n\t} else{\r\n\t\tstate_mean = _state_mean;\r\n\t}\r\n\r\n\tprintf(\"Initializing %s sampler with sigma: \", name.c_str());\r\n\tutils::printMatrix(state_sigma.transpose(), nullptr, \"%e\");\r\n\r\n\tstate_perturbation.resize(state_size);\r\n\trand_gen.resize(state_size);\r\n\trand_dist.resize(state_size);\r\n\r\n\tboost::random_device r;\r\n\tfor(unsigned int state_id = 0; state_id < state_size; ++state_id) {\r\n\t\tboost::random::seed_seq seed{ r(), r(), r(), r(), r(), r(), r(), r() };\r\n\t\trand_gen[state_id] = SampleGenT(seed);\r\n\t\trand_dist[state_id] = SampleDistT(state_mean[state_id], state_sigma[state_id]);\r\n\t}\r\n\tis_initialized.sampler = true;\r\n}\r\n\r\nvoid ProjectiveBase::estimateStateSigma(VectorXd &state_sigma, double pix_sigma){\r\n\tMatrixXd ssm_grad_norm(n_pts, state_size);\r\n\tMatrix2Xd pix_ssm_grad;\r\n\tpix_ssm_grad.resize(Eigen::NoChange, state_size);\r\n\tfor(unsigned int pt_id = 0; pt_id < n_pts; pt_id++){\r\n\t\tgetCurrPixGrad(pix_ssm_grad, pt_id);\r\n\t\tssm_grad_norm.row(pt_id) = pix_ssm_grad.colwise().norm();\r\n\t}\r\n\tVectorXd ssm_grad_norm_mean = ssm_grad_norm.colwise().mean();\r\n\tfor(unsigned int state_id = 0; state_id < state_size; ++state_id){\r\n\t\tstate_sigma(state_id) = pix_sigma / ssm_grad_norm_mean(state_id);\r\n\t}\r\n}\r\n\r\nvoid ProjectiveBase::setSampler(const VectorXd &state_sigma,\r\n\tconst VectorXd &state_mean){\r\n\tassert(state_sigma.size() == state_size);\r\n\tassert(state_mean.size() == state_size);\r\n\tfor(unsigned int state_id = 0; state_id < state_size; ++state_id){\r\n\t\trand_dist[state_id].param(DistParamT(state_mean[state_id], state_sigma[state_id]));\r\n\t}\r\n}\r\n\r\nvoid ProjectiveBase::setSamplerMean(const VectorXd &state_mean){\r\n\tassert(state_mean.size() == state_size);\r\n\tfor(unsigned int state_id = 0; state_id < state_size; ++state_id){\r\n\t\tdouble state_sigma = rand_dist[state_id].sigma();\r\n\t\trand_dist[state_id].param(DistParamT(state_mean[state_id], state_sigma));\r\n\t}\r\n}\r\nvoid ProjectiveBase::setSamplerSigma(const VectorXd &state_sigma){\r\n\tassert(state_sigma.size() == state_size);\r\n\tfor(unsigned int state_id = 0; state_id < state_size; ++state_id){\r\n\t\tdouble state_mean = rand_dist[state_id].mean();\r\n\t\trand_dist[state_id].param(DistParamT(state_mean, state_sigma[state_id]));\r\n\t}\r\n}\r\n\r\nVectorXd ProjectiveBase::getSamplerSigma(){\r\n\tVectorXd sampler_sigma(state_size);\r\n\tfor(unsigned int state_id = 0; state_id < state_size; ++state_id){\r\n\t\tsampler_sigma(state_id) = rand_dist[state_id].sigma();\r\n\t}\r\n\treturn sampler_sigma;\r\n}\r\nVectorXd ProjectiveBase::getSamplerMean(){\r\n\tVectorXd sampler_mean(state_size);\r\n\tfor(unsigned int state_id = 0; state_id < state_size; ++state_id){\r\n\t\tsampler_mean(state_id) = rand_dist[state_id].mean();\r\n\t}\r\n\treturn sampler_mean;\r\n}\r\n\r\n// use Random Walk model to generate perturbed sample\r\nvoid ProjectiveBase::additiveRandomWalk(VectorXd &perturbed_state,\r\n\tconst VectorXd &base_state){\r\n\tgeneratePerturbation(state_perturbation);\r\n\tperturbed_state = base_state + state_perturbation;\r\n}\r\nvoid ProjectiveBase::compositionalRandomWalk(VectorXd &perturbed_state,\r\n\tconst VectorXd &base_state){\r\n\tgeneratePerturbation(state_perturbation);\r\n\tProjWarpT base_warp, warp_perturbation;\r\n\tgetWarpFromState(base_warp, base_state);\r\n\tgetWarpFromState(warp_perturbation, state_perturbation);\r\n\tProjWarpT perturbed_warp = base_warp * warp_perturbation;\r\n\tgetStateFromWarp(perturbed_state, perturbed_warp);\r\n}\r\n// use first order Auto Regressive model to generate perturbed sample\r\nvoid ProjectiveBase::additiveAutoRegression1(VectorXd &perturbed_state, VectorXd &perturbed_ar,\r\n\tconst VectorXd &base_state, const VectorXd &base_ar, double a){\r\n\tgeneratePerturbation(state_perturbation);\r\n\tperturbed_state = base_state + base_ar + state_perturbation;\r\n\tperturbed_ar = a*(perturbed_state - base_state);\r\n}\r\nvoid ProjectiveBase::compositionalAutoRegression1(VectorXd &perturbed_state, VectorXd &perturbed_ar,\r\n\tconst VectorXd &base_state, const VectorXd &base_ar, double a){\r\n\tgeneratePerturbation(state_perturbation);\r\n\tProjWarpT base_warp, warp_perturbation, warp_ar;\r\n\tgetWarpFromState(base_warp, base_state);\r\n\tgetWarpFromState(warp_perturbation, state_perturbation);\r\n\tgetWarpFromState(warp_ar, base_ar);\r\n\tProjWarpT perturbed_warp = base_warp * warp_ar * warp_perturbation;\r\n\tProjWarpT perturbed_ar_warp = base_warp.inverse() * perturbed_warp;\t\r\n\t//utils::printMatrix(base_warp, \"base_warp\");\r\n\t//utils::printMatrix(warp_ar, \"warp_ar\");\r\n\t//utils::printMatrix(warp_perturbation, \"warp_perturbation\");\r\n\t//utils::printMatrix(perturbed_warp, \"perturbed_warp\");\r\n\tgetStateFromWarp(perturbed_state, perturbed_warp);\r\n\tgetStateFromWarp(perturbed_ar, perturbed_ar_warp);\r\n\tperturbed_ar *= a;\r\n}\r\n\r\nvoid ProjectiveBase::generatePerturbation(VectorXd &perturbation){\r\n\tassert(perturbation.size() == state_size);\r\n\tfor(unsigned int state_id = 0; state_id < state_size; ++state_id){\r\n\t\tperturbation(state_id) = rand_dist[state_id](rand_gen[state_id]);\r\n\t}\r\n}\r\nvoid ProjectiveBase::generatePerturbedPts(VectorXd &perturbed_pts){\r\n\tVectorXd state_update(state_size);\r\n\tgeneratePerturbation(state_update);\r\n\tgetPerturbedPts(perturbed_pts, state_update);\r\n}\r\n\r\nvoid ProjectiveBase::getPerturbedPts(VectorXd &perturbed_pts,\r\n\tconst VectorXd &state_perturbation){\r\n\tMatrix3d warp_perturbation;\r\n\tgetWarpFromState(warp_perturbation, state_perturbation);\r\n\tutils::dehomogenize(curr_warp * warp_perturbation * init_pts_hm, perturbed_pts);\r\n}\r\n\r\nvoid ProjectiveBase::estimateMeanOfSamples(VectorXd &sample_mean,\r\n\tconst std::vector<VectorXd> &samples, int n_samples){\r\n\tsample_mean.setZero();\r\n\tfor(int sample_id = 0; sample_id < n_samples; sample_id++){\r\n\t\tsample_mean += (samples[sample_id] - sample_mean) / (sample_id + 1);\r\n\t}\r\n}\r\n\r\nvoid ProjectiveBase::getIdentityWarp(VectorXd &identity_warp){\r\n\tidentity_warp.setZero();\r\n}\r\nvoid ProjectiveBase::composeWarps(VectorXd &composed_state, const VectorXd &state_1,\r\n\tconst VectorXd &state_2){\r\n\tProjWarpT warp_1, warp_2;\r\n\tgetWarpFromState(warp_1, state_1);\r\n\tgetWarpFromState(warp_2, state_2);\r\n\tProjWarpT composed_warp = warp_2*warp_1;\r\n\tgetStateFromWarp(composed_state, composed_warp);\r\n}\r\n_MTF_END_NAMESPACE\r\n\r\n", "meta": {"hexsha": "f71cfc3838ad3af634f5d1de2d9d6403ad5c34e8", "size": 13204, "ext": "cc", "lang": "C++", "max_stars_repo_path": "SSM/src/ProjectiveBase.cc", "max_stars_repo_name": "abhineet123/MTF", "max_stars_repo_head_hexsha": "6cb45c88d924fb2659696c3375bd25c683802621", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2016-12-11T00:34:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T23:03:40.000Z", "max_issues_repo_path": "SSM/src/ProjectiveBase.cc", "max_issues_repo_name": "siqiyan/MTF", "max_issues_repo_head_hexsha": "9a76388c907755448bb7223420fe74349130f636", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2017-09-04T06:27:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T19:07:23.000Z", "max_forks_repo_path": "SSM/src/ProjectiveBase.cc", "max_forks_repo_name": "siqiyan/MTF", "max_forks_repo_head_hexsha": "9a76388c907755448bb7223420fe74349130f636", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2017-02-19T02:12:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-23T03:47:55.000Z", "avg_line_length": 39.5329341317, "max_line_length": 101, "alphanum_fraction": 0.7322780975, "num_tokens": 3878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.5174247189988747}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"algorithms/dp/knapsack_problem.hpp\"\n#include \"common/equality.hpp\"\n\nBOOST_AUTO_TEST_SUITE(KnapsakProblem)\n\nBOOST_AUTO_TEST_CASE(greedy_test)\n{\n    {\n        std::vector<std::pair<uint32_t, uint32_t>> items = {\n            {10, 10}, {5, 100}, {15, 3}\n        };\n\n        uint32_t maxWeight = 20;\n        double expectedResult = 25.35;\n        BOOST_CHECK(\n            equal(Algo::DP::Knapsack::FillGreedy(maxWeight, items), expectedResult));\n    }\n\n    {\n        std::vector<std::pair<uint32_t, uint32_t>> items = {\n            {60, 20}, {100, 50}, {120, 30}\n        };\n\n        uint32_t maxWeight = 50;\n        double expectedResult = 180.0;\n        BOOST_CHECK(\n            equal(Algo::DP::Knapsack::FillGreedy(maxWeight, items), expectedResult));\n    }\n\n    {\n        std::vector<std::pair<uint32_t, uint32_t>> items = { {500, 30} };\n\n        uint32_t maxWeight = 10;\n        const double expectedResult = 166.6667;\n        const double result = Algo::DP::Knapsack::FillGreedy(maxWeight, items);\n        BOOST_CHECK(equalDoubles(result, expectedResult, 0.0001));\n    }\n\n    {\n        std::vector<std::pair<uint32_t, uint32_t>> items = {\n            {100, 5}, {100, 5} };\n\n        uint32_t maxWeight = 10;\n        const double expectedResult = 200;\n        const double result = Algo::DP::Knapsack::FillGreedy(maxWeight, items);\n        BOOST_CHECK(equalDoubles(result, expectedResult, 0.0001));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(dp_without_repetitions_test) {\n    {\n        std::vector<std::pair<uint32_t, uint32_t>> items;\n        uint32_t maxWeight = 20;\n        uint32_t expected = 0;\n        BOOST_CHECK(Algo::DP::Knapsack::FillDP(maxWeight, items) == expected);\n    }\n\n    {\n        std::vector<std::pair<uint32_t, uint32_t>> items = {{1, 1}};\n        uint32_t maxWeight = 0;\n        uint32_t expected = 0;\n        BOOST_CHECK(Algo::DP::Knapsack::FillDP(maxWeight, items) == expected);\n    }\n\n    {\n        std::vector<std::pair<uint32_t, uint32_t>> items = {\n            {1, 1}, {4, 4}, {8, 8}};\n        uint32_t maxWeight = 10;\n        uint32_t expected = 9;\n        BOOST_CHECK(Algo::DP::Knapsack::FillDP(maxWeight, items) == expected);\n    }\n\n    {\n        std::vector<std::pair<uint32_t, uint32_t>> items = {\n            {6, 6}, {3, 3}, {4, 4}, {2, 2}};\n        uint32_t maxWeight = 10;\n        uint32_t expected = 10;\n        BOOST_CHECK(Algo::DP::Knapsack::FillDP(maxWeight, items) == expected);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7aa35115ccb108f020cb6952ce61080d7277556b", "size": 2489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/dp/test_knapsack_problem.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/dp/test_knapsack_problem.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/dp/test_knapsack_problem.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": 29.630952381, "max_line_length": 85, "alphanum_fraction": 0.5865809562, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5174247135126626}}
{"text": "#include <geometry.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\ntypedef tiny::MathTypes<float> MT;\ntypedef MT::quaternion_type    Q;\ntypedef MT::vector3_type       V;\ntypedef MT::real_type          T;\ntypedef MT::value_traits       VT;\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(overlap_tet_tet_test)\n{\n  // B inside A, all SAT tests should fail\n  {\n    V const Ap0   = V::make(0.0, 0.0, 0.0);\n    V const Ap1   = V::make(1.0, 0.0, 0.0);\n    V const Ap2   = V::make(0.0, 1.0, 0.0);\n    V const Ap3   = V::make(0.0, 0.0, 1.0);\n\n    V const Bp0   = V::make(0.1, 0.1, 0.1);\n    V const Bp1   = V::make(0.9, 0.0, 0.0);\n    V const Bp2   = V::make(0.0, 0.9, 0.0);\n    V const Bp3   = V::make(0.0, 0.0, 0.9);\n\n    geometry::Tetrahedron<V> tetA = geometry::make_tetrahedron<V>(Ap0, Ap1, Ap2, Ap3);\n    geometry::Tetrahedron<V> tetB = geometry::make_tetrahedron<V>(Bp0, Bp1, Bp2, Bp3);\n\n    bool const test1 = geometry::overlap_tetrahedron_tetrahedron(tetA, tetB);\n    bool const test2 = geometry::overlap_tetrahedron_tetrahedron(tetB, tetA);\n\n    BOOST_CHECK(test1);\n    BOOST_CHECK(test2);\n  }\n\n  unsigned int permutation[6][4] = {\n    {1, 3, 2, 0},\n    {0, 3, 1, 2},\n    {0, 1, 2, 3},\n    {2, 3, 0, 1},\n    {1, 2, 0, 3},\n    {2, 0, 1, 3}\n  };\n\n  // Touching edge-edge cases\n  {\n    std::vector<V> A(4u);\n    std::vector<V> B(4u);\n\n    A[0]   = V::make(0.0, 0.0, 0.0);\n    A[1]   = V::make(1.0, 0.0, 0.0);\n    A[2]   = V::make(0.0, 1.0, 0.0);\n    A[3]   = V::make(0.0, 0.0, 1.0);\n\n    B[0]   = V::make( 1.0, -1.0,  0.5);\n    B[1]   = V::make(-1.0,  1.0,  0.5);\n    B[2]   = V::make(-1.0, -1.0, -1.0);\n    B[3]   = V::make(-1.0, -1.0,  1.0);\n\n\n\n    for (unsigned int i=0u;i<6u;++i)\n    {\n      for (unsigned int j=0u;j<6u;++j)\n      {\n\n\n        geometry::Tetrahedron<V> tetA = geometry::make_tetrahedron<V>(\n                                                                        A[permutation[i][0]]\n                                                                      , A[permutation[i][1]]\n                                                                      , A[permutation[i][2]]\n                                                                      , A[permutation[i][3]]\n                                                                      );\n        geometry::Tetrahedron<V> tetB = geometry::make_tetrahedron<V>(\n                                                                        B[permutation[j][0]]\n                                                                      , B[permutation[j][1]]\n                                                                      , B[permutation[j][2]]\n                                                                      , B[permutation[j][3]]\n                                                                      );\n\n        bool const test1 = geometry::overlap_tetrahedron_tetrahedron(tetA, tetB);\n        bool const test2 = geometry::overlap_tetrahedron_tetrahedron(tetB, tetA);\n\n        BOOST_CHECK(test1);\n        BOOST_CHECK(test2);\n\n      }\n    }\n\n\n  }\n\n  // Separating edge-edge cases\n  {\n    std::vector<V> A(4u);\n    std::vector<V> B(4u);\n\n    A[0]   = V::make(0.01, 0.01, 0.01);\n    A[1]   = V::make(1.01, 0.01, 0.01);\n    A[2]   = V::make(0.01, 1.01, 0.01);\n    A[3]   = V::make(0.01, 0.01, 1.01);\n\n    B[0]   = V::make( 1.0, -1.0,  0.5);\n    B[1]   = V::make(-1.0,  1.0,  0.5);\n    B[2]   = V::make(-1.0, -1.0, -1.0);\n    B[3]   = V::make(-1.0, -1.0,  1.0);\n\n\n\n    for (unsigned int i=0u;i<6u;++i)\n    {\n      for (unsigned int j=0u;j<6u;++j)\n      {\n\n\n        geometry::Tetrahedron<V> tetA = geometry::make_tetrahedron<V>(\n                                                                      A[permutation[i][0]]\n                                                                      , A[permutation[i][1]]\n                                                                      , A[permutation[i][2]]\n                                                                      , A[permutation[i][3]]\n                                                                      );\n        geometry::Tetrahedron<V> tetB = geometry::make_tetrahedron<V>(\n                                                                      B[permutation[j][0]]\n                                                                      , B[permutation[j][1]]\n                                                                      , B[permutation[j][2]]\n                                                                      , B[permutation[j][3]]\n                                                                      );\n\n        bool const test1 = geometry::overlap_tetrahedron_tetrahedron(tetA, tetB);\n        bool const test2 = geometry::overlap_tetrahedron_tetrahedron(tetB, tetA);\n\n        BOOST_CHECK(!test1);\n        BOOST_CHECK(!test2);\n        \n      }\n    }\n    \n    \n  }\n\n  // Separated by face cases\n  {\n    V const A0   = V::make(0.0, 0.0, 0.0);\n    V const A1   = V::make(1.0, 0.0, 0.0);\n    V const A2   = V::make(0.0, 1.0, 0.0);\n    V const A3   = V::make(0.0, 0.0, 1.0);\n\n    std::vector<V> offset(4);\n\n    offset[0] = V::make( 2.0,  2.0,  2.0);\n    offset[1] = V::make(-2.0,  0.0,  0.0);\n    offset[2] = V::make( 0.0, -2.0,  0.0);\n    offset[3] = V::make( 0.0,  0.0, -2.0);\n\n    geometry::Tetrahedron<V> tetA = geometry::make_tetrahedron<V>(A0, A1, A2, A3);\n\n    for (unsigned int k = 0u; k < 4u; ++k)\n    {\n\n      geometry::Tetrahedron<V> tetB = geometry::make_tetrahedron<V>(\n                                                                    A0 + offset[k]\n                                                                    , A1 + offset[k]\n                                                                    , A2 + offset[k]\n                                                                    , A3 + offset[k]\n                                                                    );\n\n      bool const test1 = geometry::overlap_tetrahedron_tetrahedron(tetA, tetB);\n      bool const test2 = geometry::overlap_tetrahedron_tetrahedron(tetB, tetA);\n\n      BOOST_CHECK(!test1);\n      BOOST_CHECK(!test2);\n      \n    }\n    \n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "768db576958b0551ae40c986e969c07d93b34b6b", "size": 6286, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_overlap_tetrahedron_tetrahedron/geometry_overlap_tetrahedron_tetrahedron.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_overlap_tetrahedron_tetrahedron/geometry_overlap_tetrahedron_tetrahedron.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_overlap_tetrahedron_tetrahedron/geometry_overlap_tetrahedron_tetrahedron.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7956989247, "max_line_length": 92, "alphanum_fraction": 0.4051861279, "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430604060731, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5173527535134268}}
{"text": "//\n// Created by Hamza El-Kebir on 5/19/21.\n//\n\n#include \"catchOnce.hpp\"\n#include <Eigen/Dense>\n#include \"Lodestar/systems/StateSpace.hpp\"\n\nTEST_CASE(\"StateSpace dynamic construction\", \"[systems][StateSpace][dynamic][construction]\")\n{\n    Eigen::MatrixXd A(3, 3), B(3, 2), C(2, 3), D(2, 2);\n    A << 1,  2, 0,\n         4, -1, 0,\n         0,  0, 1;\n\n    B << 1, 0,\n         0, 1,\n         1, 0;\n\n    C << 0, 1, -1,\n         0, 0,  1;\n\n    D << 4, 0,\n         0, 1;\n\n    auto ss = ls::systems::StateSpace<>(A, B, C, D);\n\n    SECTION(\"Default discrete parameters\") {\n        REQUIRE(ss.getSamplingPeriod() == -1);\n        REQUIRE(ss.isDiscrete() == false);\n    }\n\n    SECTION(\"Dimensions\") {\n        REQUIRE(ss.stateDim() == 3);\n        REQUIRE(ss.inputDim() == 2);\n        REQUIRE(ss.outputDim() == 2);\n    }\n\n    SECTION(\"Matrices\") {\n        REQUIRE(ss.getA() == A);\n        REQUIRE(ss.getB() == B);\n        REQUIRE(ss.getC() == C);\n        REQUIRE(ss.getD() == D);\n    }\n\n    SECTION(\"Set discrete parameters\") {\n        ss.setDiscreteParams(0.1);\n        REQUIRE(ss.isDiscrete() == true);\n        REQUIRE(ss.getSamplingPeriod() == Approx(0.1));\n    }\n\n    SECTION(\"Integral action\") {\n        auto ssi = ss.addIntegralAction();\n        REQUIRE(ssi.stateDim() == ss.stateDim() + ss.outputDim());\n        REQUIRE(ssi.inputDim() == ss.inputDim());\n        REQUIRE(ssi.outputDim() == ss.outputDim());\n\n\n        REQUIRE(ssi.getA().topLeftCorner<3, 3>() == ss.getA());\n        REQUIRE(ssi.getB().topRows<3>() == ss.getB());\n        REQUIRE(ssi.getC().leftCols<3>() == ss.getC());\n        REQUIRE(ssi.getD() == ss.getD());\n    }\n}\n\nTEST_CASE(\"StateSpace static construction\", \"[StateSpace][static][construction]\")\n{\n    Eigen::MatrixXd A(3, 3), B(3, 2), C(2, 3), D(2, 2);\n    A << 1,  2, 0,\n         4, -1, 0,\n         0,  0, 1;\n\n    B << 1, 0,\n         0, 1,\n         1, 0;\n\n    C << 0, 1, -1,\n         0, 0,  1;\n\n    D << 4, 0,\n         0, 1;\n\n    auto ss = ls::systems::StateSpace<double, 3, 2, 2>(A, B, C, D);\n\n    SECTION(\"Default discrete parameters\") {\n        REQUIRE(ss.getSamplingPeriod() == -1);\n        REQUIRE(ss.isDiscrete() == false);\n    }\n\n    SECTION(\"Dimensions\") {\n        REQUIRE(ss.stateDim() == 3);\n        REQUIRE(ss.inputDim() == 2);\n        REQUIRE(ss.outputDim() == 2);\n    }\n\n    SECTION(\"Matrices\") {\n        REQUIRE(ss.getA() == A);\n        REQUIRE(ss.getB() == B);\n        REQUIRE(ss.getC() == C);\n        REQUIRE(ss.getD() == D);\n    }\n\n    SECTION(\"Set discrete parameters\") {\n        ss.setDiscreteParams(0.1);\n        REQUIRE(ss.isDiscrete() == true);\n        REQUIRE(ss.getSamplingPeriod() == Approx(0.1));\n    }\n\n    SECTION(\"Integral action\") {\n        auto ssi = ss.addIntegralAction();\n        REQUIRE(ssi.stateDim() == ss.stateDim() + ss.outputDim());\n        REQUIRE(ssi.inputDim() == ss.inputDim());\n        REQUIRE(ssi.outputDim() == ss.outputDim());\n\n\n        REQUIRE(ssi.getA().topLeftCorner<3, 3>() == ss.getA());\n        REQUIRE(ssi.getB().topRows<3>() == ss.getB());\n        REQUIRE(ssi.getC().leftCols<3>() == ss.getC());\n        REQUIRE(ssi.getD() == ss.getD());\n    }\n}", "meta": {"hexsha": "a63b294a06c09f0299b30efbe0772dcc14364b64", "size": 3116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/systems/StateSpace_test.cpp", "max_stars_repo_name": "helkebir/Lodestar", "max_stars_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T14:08:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T22:15:31.000Z", "max_issues_repo_path": "tests/systems/StateSpace_test.cpp", "max_issues_repo_name": "helkebir/Lodestar", "max_issues_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T15:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T17:43:20.000Z", "max_forks_repo_path": "tests/systems/StateSpace_test.cpp", "max_forks_repo_name": "helkebir/Lodestar", "max_forks_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T03:15:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T03:15:23.000Z", "avg_line_length": 25.7520661157, "max_line_length": 92, "alphanum_fraction": 0.5099486521, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5173527509099376}}
{"text": "/* test_piecewise_constant.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$\n *\n */\n\n#include <boost/random/piecewise_constant_distribution.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/exception/diagnostic_information.hpp>\n#include <boost/range/algorithm/lower_bound.hpp>\n#include <boost/range/numeric.hpp>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n\n#include \"statistic_tests.hpp\"\n\nclass piecewise_constant\n{\npublic:\n    piecewise_constant(const std::vector<double>& intervals, const std::vector<double>& weights)\n      : intervals(intervals),\n        cumulative(1, 0.0)\n    {\n        boost::partial_sum(weights, std::back_inserter(cumulative));\n        for(std::vector<double>::iterator iter = cumulative.begin(), end = cumulative.end();\n            iter != end; ++iter)\n        {\n            *iter /= cumulative.back();\n        }\n    }\n\n    double cdf(double x) const\n    {\n        std::size_t index = boost::lower_bound(intervals, x) - intervals.begin();\n        if(index == 0) return 0;\n        else if(index == intervals.size()) return 1;\n        else {\n            double lower_weight = cumulative[index - 1];\n            double upper_weight = cumulative[index];\n            double lower = intervals[index - 1];\n            double upper = intervals[index];\n            return lower_weight + (x - lower) / (upper - lower) * (upper_weight - lower_weight);\n        }\n    }\nprivate:\n    std::vector<double> intervals;\n    std::vector<double> cumulative;\n};\n\ndouble cdf(const piecewise_constant& dist, double x)\n{\n    return dist.cdf(x);\n}\n\nbool do_test(int n, int max) {\n    std::cout << \"running piecewise_constant(p0, p1, ..., p\" << n-1 << \")\" << \" \" << max << \" times: \" << std::flush;\n\n    std::vector<double> weights;\n    {\n        boost::mt19937 egen;\n        for(int i = 0; i < n; ++i) {\n            weights.push_back(egen());\n        }\n    }\n    std::vector<double> intervals;\n    for(int i = 0; i <= n; ++i) {\n        intervals.push_back(i);\n    }\n\n    piecewise_constant expected(intervals, weights);\n    \n    boost::random::piecewise_constant_distribution<> dist(intervals, weights);\n    boost::mt19937 gen;\n    kolmogorov_experiment test(max);\n    boost::variate_generator<boost::mt19937&, boost::random::piecewise_constant_distribution<> > vgen(gen, dist);\n\n    double prob = test.probability(test.run(vgen, expected));\n\n    bool result = prob < 0.99;\n    const char* err = result? \"\" : \"*\";\n    std::cout << std::setprecision(17) << prob << err << std::endl;\n\n    std::cout << std::setprecision(6);\n\n    return result;\n}\n\nbool do_tests(int repeat, int max_n, int trials) {\n    boost::mt19937 gen;\n    boost::uniform_int<> idist(1, max_n);\n    int errors = 0;\n    for(int i = 0; i < repeat; ++i) {\n        if(!do_test(idist(gen), trials)) {\n            ++errors;\n        }\n    }\n    if(errors != 0) {\n        std::cout << \"*** \" << errors << \" errors detected ***\" << std::endl;\n    }\n    return errors == 0;\n}\n\nint usage() {\n    std::cerr << \"Usage: test_piecewise_constant -r <repeat> -n <max n> -t <trials>\" << std::endl;\n    return 2;\n}\n\ntemplate<class T>\nbool handle_option(int& argc, char**& argv, char opt, T& value) {\n    if(argv[0][1] == opt && argc > 1) {\n        --argc;\n        ++argv;\n        value = boost::lexical_cast<T>(argv[0]);\n        return true;\n    } else {\n        return false;\n    }\n}\n\nint main(int argc, char** argv) {\n    int repeat = 10;\n    int max_n = 10;\n    int trials = 1000000;\n\n    if(argc > 0) {\n        --argc;\n        ++argv;\n    }\n    while(argc > 0) {\n        if(argv[0][0] != '-') return usage();\n        else if(!handle_option(argc, argv, 'r', repeat)\n             && !handle_option(argc, argv, 'n', max_n)\n             && !handle_option(argc, argv, 't', trials)) {\n            return usage();\n        }\n        --argc;\n        ++argv;\n    }\n\n    try {\n        if(do_tests(repeat, max_n, trials)) {\n            return 0;\n        } else {\n            return EXIT_FAILURE;\n        }\n    } catch(...) {\n        std::cerr << boost::current_exception_diagnostic_information() << std::endl;\n        return EXIT_FAILURE;\n    }\n}\n", "meta": {"hexsha": "8261def96cabbe38b6a7348a62a35ff97024383d", "size": 4348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_piecewise_constant.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/random/test/test_piecewise_constant.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/random/test/test_piecewise_constant.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": 27.3459119497, "max_line_length": 117, "alphanum_fraction": 0.5814167433, "num_tokens": 1132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5172505437039919}}
{"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_VECTOR_HPP\n#define RW_MATH_VECTOR_HPP\n\n/**\n * @file Vector.hpp\n */\n#if !defined(SWIG)\n#include <rw/core/macros.hpp>\n\n#include <Eigen/Core>\n#endif\n\nnamespace rw { namespace math {\n\n    /**\n     * @brief Configuration vector\n     */\n    template< class T = double > class Vector\n    {\n      public:\n        //! The type of the internal Eigen vector implementation.\n        typedef Eigen::Matrix< T, Eigen::Dynamic, 1 > Base;\n\n        /**\n         * @brief A configuration of vector of length \\b dim.\n         */\n        explicit Vector (size_t dim) : _vec (dim) {}\n\n        /**\n         * @brief Default constructor.\n         *\n         * The vector will be of dimension zero.\n         */\n        Vector () : _vec (0) {}\n\n        /**\n         * @brief Creates a Vector of length \\b n and initialized with values from \\b values\n         *\n         * The method reads n values from \\b values and do not check whether reading out of bounds.\n         *\n         * @param n [in] Length of q.\n         * @param values [in] Values to initialize with\n         */\n        Vector (size_t n, const T* values) : _vec (n)\n        {\n            for (size_t i = 0; i < n; i++)\n                _vec (i) = values[i];\n        }\n\n        /**\n         * @brief Creates a Vector of length \\b n and initialize all values in Vector to \\b value\n         *\n         * @param n [in] Length of q.\n         * @param value [in] Value to initialize\n         */\n        Vector (size_t n, T value) : _vec (n)\n        {\n            for (size_t i = 0; i < n; i++)\n                _vec (i) = value;\n        }\n\n        /**\n         * @brief Returns Vector of length \\b n initialized with 0's\n         */\n        static Vector zero (int n) { return Vector (Base::Zero (n)); }\n\n        /**\n         * @brief The dimension of the configuration vector.\n         */\n        size_t size () const { return e ().size (); }\n\n        /**\n           @brief True if the configuration is of dimension zero.\n         */\n        bool empty () const { return size () == 0; }\n\n        /**\n         * @brief Construct a configuration vector from a Boost vector\n         * expression.\n         *\n         * @param r [in] An expression for a vector of doubles\n         */\n        template< class R > explicit Vector (const Eigen::MatrixBase< R >& r) : _vec (r) {}\n\n        /**\n         * @brief Accessor for the internal Eigen vector state.\n         */\n        const Base& e () const { return _vec; }\n\n        /**\n         * @brief Accessor for the internal Eigen vector state.\n         */\n        Base& e () { return _vec; }\n\n        /**\n           @brief Start of sequence iterator.\n        */\n        // const_iterator begin() const { return e().begin(); }\n\n        /**\n           @brief End of sequence iterator.\n        */\n        // const_iterator end() const { return e().end(); }\n\n        /**\n           @brief Start of sequence iterator.\n        */\n        // iterator begin() { return e().begin(); }\n\n        /**\n           @brief End of sequence iterator.\n        */\n        // iterator end() { return e().end(); }\n\n        /**\n         * @brief Extracts a sub part (range) of this Vector.\n         * @param start [in] Start index\n         * @param cnt [in] the number of elements to include\n         * @return\n         */\n        const Vector getSubPart (size_t start, size_t cnt) const\n        {\n            RW_ASSERT (start + cnt <= size ());\n\n            Vector res (cnt);\n            for (size_t i = 0; i < cnt; i++) {\n                res (i) = (*this)[start + i];\n            }\n            return res;\n        }\n\n        /**\n         * @brief Set a part of the vector.\n         * @param index [in] first index.\n         * @param part [in] the subpart to set.\n         */\n        void setSubPart (size_t index, const Vector& part)\n        {\n            RW_ASSERT (index + part.size () <= size ());\n            for (size_t i = 0; i < part.size (); i++) {\n                (*this)[index + i] = part (i);\n            }\n        }\n\n        //----------------------------------------------------------------------\n        // Norm utility methods\n\n        /**\n         * @brief Returns the Euclidean norm (2-norm) of the configuration\n         * @return the norm\n         */\n        T norm2 () const { return e ().norm (); }\n\n        /**\n         * @brief Returns the Manhatten norm (1-norm) of the configuration\n         * @return the norm\n         */\n        T norm1 () const { return e ().sum (); }\n\n        /**\n         * @brief Returns the infinte norm (\\f$\\inf\\f$-norm) of the configuration\n         * @return the norm\n         */\n        T normInf () const\n        {\n            Eigen::VectorXd tmp = e ().template cast< double > ();\n            return (T) tmp.lpNorm< Eigen::Infinity > ();\n        }\n\n        //----------------------------------------------------------------------\n        // Various operators\n\n#if !defined(SWIG)\n        /**\n         * @brief Returns reference to vector element\n         * @param i [in] index in the vector\n         * @return const reference to element\n         */\n        const T& operator() (size_t i) const { return e () (i); }\n\n        /**\n         * @brief Returns reference to vector element\n         * @param i [in] index in the vector\n         * @return reference to element\n         */\n        T& operator() (size_t i) { return e () (i); }\n\n        /**\n         * @brief Returns reference to vector element\n         * @param i [in] index in the vector\n         * @return const reference to element\n         */\n        const T& operator[] (size_t i) const { return e () (i); }\n\n        /**\n         * @brief Returns reference to vector element\n         * @param i [in] index in the vector\n         * @return reference to element\n         */\n        T& operator[] (size_t i) { return e () (i); }\n#else\n        ARRAYOPERATOR (T);\n#endif\n        /**\n           @brief Scalar division.\n         */\n        const Vector operator/ (T s) const { return Vector (e () / s); }\n\n        /**\n         * @brief Scalar multiplication.\n         */\n        const Vector operator* (T s) const { return Vector (e () * s); }\n#if !defined(SWIG)\n        /**\n         * @brief Scalar multiplication.\n         */\n        friend const Vector operator* (T s, const Vector& v) { return Vector (s * v.e ()); }\n#endif \n        /**\n         * @brief Vector subtraction.\n         */\n        const Vector operator- (const Vector& b) const { return Vector (e () - b.e ()); }\n\n        /**\n         * @brief Vector addition.\n         */\n        const Vector operator+ (const Vector& b) const { return Vector (e () + b.e ()); }\n\n        /**\n         * @brief Scalar multiplication.\n         */\n        Vector& operator*= (T s)\n        {\n            e () *= s;\n            return *this;\n        }\n\n        /**\n         * @brief Scalar division.\n         */\n        Vector& operator/= (T s)\n        {\n            e () /= s;\n            return *this;\n        }\n\n        /**\n         * @brief Vector addition.\n         */\n        Vector& operator+= (const Vector& v)\n        {\n            _vec += v.e ();\n            return *this;\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        Vector& operator-= (const Vector& v)\n        {\n            _vec -= v.e ();\n            return *this;\n        }\n\n        /**\n         * @brief Unary minus.\n         */\n        const Vector operator- () const { return Vector (-e ()); }\n\n        /**\n         * @brief Compares whether this is less than \\b q\n         *\n         * The less operator is defined such that the first index is the most significant. That is\n         * if (*this)[0] < q[0] then true is returned. If (*this)[0] > q[0] false is returned and\n         * only if (*this)[0] == q[0] is the next index considered.\n         */\n        bool operator< (const Vector& q) const\n        {\n            RW_ASSERT (size () == q.size ());\n            for (size_t i = 0; i < size (); i++) {\n                if (_vec[i] < q[i])\n                    return true;\n                else if (_vec[i] > q[i])\n                    return false;\n            }\n            return false;\n        }\n\n      private:\n        Base _vec;\n    };\n\n    /**\n     * @brief Compares \\b q1 and \\b q2 for equality.\n     *\n     * \\b q1 and \\b q2 are considered equal if and only if they have equal\n     * length and if q1(i) == q2(i) for all i.\n     *\n     * @relates Vector\n     *\n     * @param q1 [in]\n     * @param q2 [in]\n     * @return True if q1 equals q2, false otherwise.\n     */\n    template< class A > bool operator== (const Vector< A >& q1, const Vector< A >& q2)\n    {\n        if (q1.size () != q2.size ())\n            return false;\n\n        for (size_t i = 0; i < q1.size (); i++)\n            if (q1 (i) != q2 (i))\n                return false;\n        return true;\n    }\n\n    /**\n       @brief Inequality operator\n\n       The inverse of operator==().\n     */\n    template< class A > inline bool operator!= (const Vector< A >& q1, const Vector< A >& q2)\n    {\n        return !(q1 == q2);\n    }\n\n    /**\n     * @brief Streaming operator.\n     *\n     * @relates Vector\n     */\n    template< class A > std::ostream& operator<< (std::ostream& out, const Vector< A >& v)\n    {\n        if (v.size () == 0)\n            return out << \"Q[0]{}\";\n        else {\n            out << \"Q[\" << (int) v.size () << \"]{\";\n            for (size_t i = 0; i < v.size () - 1; i++)\n                out << v[i] << \", \";\n            return out << v[v.size () - 1] << \"}\";\n        }\n    }\n\n    /**\n     * @brief Input streaming operator\n     *\n     * Parse input stream according to how operator<< streams out\n     *\n     * @relates Vector\n     * @param in [in] Input stream\n     * @param q [in] Target of q read in\n     * @return reference to \\b in\n     */\n    template< class A > std::istream& operator>> (std::istream& in, Vector< A >& q)\n    {\n        char ch1, ch2;\n        do {\n            in.get (ch1);\n        } while (ch1 == ' ' || ch1 == '\\t');    // Ignore space and tab, but not line changes.\n\n        int size = -1;\n\n        if (ch1 == 'Q') {\n            in.get (ch2);\n            if (ch1 != 'Q' || ch2 != '[')\n                RW_THROW (\"Content of input stream does not match format of Q\");\n            in >> size;\n\n            in.get (ch1);\n            in.get (ch2);\n            if (ch1 != ']' || ch2 != '{')\n                RW_THROW (\"Content of input stream does not match format of Q\");\n        }\n        else if (ch1 != '{') {\n            RW_THROW (\"Content of input stream does not match format of Q\");\n        }\n\n        std::vector< double > res;\n        while (ch1 != '}') {\n            double d;\n            in >> d;\n            if (!in.eof ()) {\n                res.push_back (d);\n            }\n            in.get (ch1);\n        }\n\n        if (ch1 != '}')\n            RW_THROW (\"Content of input stream does not match format of Q\");\n\n        if (size > -1 && (int) res.size () != size) {\n            RW_THROW (\"Length of Q does not match device\");\n        }\n\n        q = Vector< A > (res.size (), &res[0]);\n        return in;\n    }\n\n    /**\n       @brief The dot product (inner product) of \\b a and \\b b.\n\n       @relates Vector\n    */\n    template< class A > A dot (const Vector< A >& a, const Vector< A >& b)\n    {\n        return a.e ().dot (b.e ());\n    }\n\n    /**\n     * @brief concatenates q1 onto q2 such that the returned q has\n     * the configurations of q1 in [0;q1.size()[ and has q2 in\n     * [q1.size();q1.size()+q2.size()[\n     * @param q1 [in] the first Vector\n     * @param q2 [in] the second Vector\n     * @return the concatenation of q1 and q2\n     */\n    template< class A > rw::math::Vector< A > concat (const Vector< A >& q1, const Vector< A >& q2)\n    {\n        Vector< A > q (q1.size () + q2.size ());\n        for (size_t i = 0; i < q1.size (); i++)\n            q (i) = q1 (i);\n        for (size_t i = 0; i < q2.size (); i++)\n            q (q1.size () + i) = q2 (i);\n        return q;\n    }\n#if !defined(SWIG)\n    extern template class rw::math::Vector< double >;\n    extern template class rw::math::Vector< float >;\n#else\n    SWIG_DECLARE_TEMPLATE (Vectord, rw::math::Vector< double >);\n    SWIG_DECLARE_TEMPLATE (Vectorf, rw::math::Vector< float >);\n#endif\n    using Vectord = Vector< double >;\n    using Vectorf = Vector< float >;\n\n    /*@}*/\n\n}}    // namespace rw::math\n\n#endif    // end include guard\n", "meta": {"hexsha": "d2e688aa1dcd18eb785a267c5c79d1cdc2288b61", "size": 13219, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/Vector.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/Vector.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/Vector.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": 28.9256017505, "max_line_length": 99, "alphanum_fraction": 0.4731068916, "num_tokens": 3224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5172505364916887}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <boost/simd/arithmetic/include/functions/divround.hpp>\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/module.hpp>\n\n#include <boost/simd/include/constants/two.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/mone.hpp>\n#include <boost/simd/include/constants/inf.hpp>\n#include <boost/simd/include/constants/minf.hpp>\n#include <boost/simd/include/constants/nan.hpp>\n#include <boost/simd/include/constants/maxflint.hpp>\n#include <boost/simd/include/constants/valmin.hpp>\n#include <boost/simd/include/constants/valmax.hpp>\n\nNT2_TEST_CASE_TPL ( divround_real,  BOOST_SIMD_REAL_TYPES)\n{\n  using boost::simd::divround;\n  using boost::simd::tag::divround_;\n  typedef typename boost::dispatch::meta::call<divround_(T,T)>::type r_t;\n  typedef T wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_EQUAL(divround(boost::simd::Inf<T>(), boost::simd::Inf<T>()), boost::simd::Nan<r_t>());\n  NT2_TEST_EQUAL(divround(boost::simd::Minf<T>(), boost::simd::Minf<T>()), boost::simd::Nan<r_t>());\n  NT2_TEST_EQUAL(divround(boost::simd::Nan<T>(), boost::simd::Nan<T>()), boost::simd::Nan<r_t>());\n#endif\n  NT2_TEST_EQUAL(divround(T(4),T(0)), boost::simd::Inf<r_t>());\n  NT2_TEST_EQUAL(divround(T(4),T(3)), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(divround(boost::simd::Mone<T>(), boost::simd::Mone<T>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(divround(boost::simd::One<T>(), boost::simd::One<T>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(divround(boost::simd::Mone<T>(),boost::simd::Zero<T>()), boost::simd::Minf<r_t>());\n  NT2_TEST_EQUAL(divround(boost::simd::One<T>(), boost::simd::One<T>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(divround(boost::simd::One<T>(),boost::simd::Zero<T>()), boost::simd::Inf<r_t>());\n  NT2_TEST_EQUAL(divround(boost::simd::Zero<T>(),boost::simd::Zero<T>()), boost::simd::Nan<r_t>());\n} // end of test for floating_\n\nNT2_TEST_CASE_TPL ( divround_unsigned_int,  BOOST_SIMD_UNSIGNED_TYPES)\n{\n\n  using boost::simd::divround;\n  using boost::simd::tag::divround_;\n  typedef typename boost::dispatch::meta::call<divround_(T,T)>::type r_t;\n  typedef T wished_r_t;\n\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n  NT2_TEST_EQUAL(divround(T(4),T(0)), boost::simd::Valmax<r_t>());\n  NT2_TEST_EQUAL(divround(T(4),T(3)), T(1));\n  NT2_TEST_EQUAL(divround(T(6),T(4)), T(2));\n  NT2_TEST_EQUAL(divround(boost::simd::One<T>(), boost::simd::One<T>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(divround(boost::simd::Valmax<T>(),  boost::simd::Two<T>()), boost::simd::Valmax<r_t>()/boost::simd::Two<T>()+boost::simd::One<r_t>());\n} // end of test for unsigned_int_\n\nNT2_TEST_CASE_TPL ( divround_signed_int,  BOOST_SIMD_INTEGRAL_SIGNED_TYPES)\n{\n\n  using boost::simd::divround;\n  using boost::simd::tag::divround_;\n  typedef typename boost::dispatch::meta::call<divround_(T,T)>::type r_t;\n  typedef T wished_r_t;\n\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n  NT2_TEST_EQUAL(divround(T(-4),T(0)), boost::simd::Valmin<r_t>());\n  NT2_TEST_EQUAL(divround(T(4),T(0)), boost::simd::Valmax<r_t>());\n  NT2_TEST_EQUAL(divround(T(4),T(3)), T(1));\n  NT2_TEST_EQUAL(divround(T(-4),T(-3)), T(1));\n  NT2_TEST_EQUAL(divround(T(4),T(-3)), T(-1));\n  NT2_TEST_EQUAL(divround(T(-4),T(3)), T(-1));\n  NT2_TEST_EQUAL(divround(T(5),T(3)), T(2));\n  NT2_TEST_EQUAL(divround(T(-5),T(-3)), T(2));\n  NT2_TEST_EQUAL(divround(T(5),T(-3)), T(-2));\n  NT2_TEST_EQUAL(divround(T(-5),T(3)), T(-2));\n\n  NT2_TEST_EQUAL(divround(T(5),T(4)), T(1));\n  NT2_TEST_EQUAL(divround(T(-5),T(-4)), T(1));\n  NT2_TEST_EQUAL(divround(T(5),T(-4)), T(-1));\n  NT2_TEST_EQUAL(divround(T(-5),T(4)), T(-1));\n  NT2_TEST_EQUAL(divround(T(6),T(4)), T(2));\n  NT2_TEST_EQUAL(divround(T(-6),T(-4)), T(2));\n  NT2_TEST_EQUAL(divround(T(6),T(-4)), T(-2));\n  NT2_TEST_EQUAL(divround(T(-6),T(4)), T(-2));\n  NT2_TEST_EQUAL(divround(T(8),T(4)), T(2));\n  NT2_TEST_EQUAL(divround(T(-8),T(-4)), T(2));\n  NT2_TEST_EQUAL(divround(T(8),T(-4)), T(-2));\n  NT2_TEST_EQUAL(divround(T(-8),T(4)), T(-2));\n  NT2_TEST_EQUAL(divround(T(9),T(4)), T(2));\n  NT2_TEST_EQUAL(divround(T(-9),T(-4)), T(2));\n  NT2_TEST_EQUAL(divround(T(9),T(-4)), T(-2));\n  NT2_TEST_EQUAL(divround(T(-9),T(4)), T(-2));\n  NT2_TEST_EQUAL(divround(T(10),T(4)), T(3));\n  NT2_TEST_EQUAL(divround(T(-10),T(-4)), T(3));\n  NT2_TEST_EQUAL(divround(T(10),T(-4)), T(-3));\n  NT2_TEST_EQUAL(divround(T(-10),T(4)), T(-3));\n\n  NT2_TEST_EQUAL(divround(boost::simd::Mone<T>(), boost::simd::Mone<T>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(divround(boost::simd::One<T>(), boost::simd::One<T>()), boost::simd::One<r_t>());\n} // end of test for signed_int_\n", "meta": {"hexsha": "29cc1a58260889efab9ce0876b6e7f1ada40fed7", "size": 5435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/unit/arithmetic/scalar/divround.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/unit/arithmetic/scalar/divround.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/boost/simd/base/unit/arithmetic/scalar/divround.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 46.0593220339, "max_line_length": 151, "alphanum_fraction": 0.6528058878, "num_tokens": 1699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.682573734412324, "lm_q1q2_score": 0.5172505339175706}}
{"text": "/* Boost numeric test of the symplectic steppers test file\n\n Copyright 2012 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// disable checked iterator warning for msvc\n#include <boost/config.hpp>\n#ifdef BOOST_MSVC\n    #pragma warning(disable:4996)\n#endif\n\n#define BOOST_TEST_MODULE numeric_symplectic\n\n#include <iostream>\n#include <cmath>\n\n#include <boost/array.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/vector.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\nnamespace mpl = boost::mpl;\n\ntypedef double value_type;\n\ntypedef boost::array< double ,1 > state_type;\n\n// harmonic oscillator, analytic solution x[0] = sin( t )\nstruct osc\n{\n    void operator()( const state_type &q , state_type &dpdt ) const\n    {\n        dpdt[0] = -q[0];\n    }\n};\n\nBOOST_AUTO_TEST_SUITE( numeric_symplectic_test )\n\n\n/* generic test for all symplectic steppers */\ntemplate< class Stepper >\nstruct perform_symplectic_test\n{\n    void operator()( void )\n    {\n   \n        Stepper stepper;\n        const int o = stepper.order()+1; //order of the error is order of approximation + 1\n\n        const state_type q0 = {{ 0.0 }};\n        const state_type p0 = {{ 1.0 }};\n        state_type q1,p1;\n        std::pair< state_type , state_type >x1( q1 , p1 );\n        const double t = 0.0;\n        /* do a first step with dt=0.1 to get an estimate on the prefactor of the error dx = f * dt^(order+1) */\n        double dt = 0.5;\n        stepper.do_step( osc() , std::make_pair( q0 , p0 ) , t , x1 , dt );\n        const double f = 2.0 * std::abs( sin(dt) - x1.first[0] ) / std::pow( dt , o );\n\n        std::cout << o << \" , \" << f << std::endl;\n\n        /* as long as we have errors above machine precision */\n        while( f*std::pow( dt , o ) > 1E-16 )\n        {\n            stepper.do_step( osc() , std::make_pair( q0 , p0 ) , t , x1 , dt );\n            std::cout << \"Testing dt=\" << dt << std::endl;\n            BOOST_CHECK_SMALL( std::abs( sin(dt) - x1.first[0] ) , f*std::pow( dt , o ) );\n            dt *= 0.5;\n        }\n    }\n};\n\n\ntypedef mpl::vector<\n    symplectic_euler< state_type > ,\n    symplectic_rkn_sb3a_mclachlan< state_type >\n    > symplectic_steppers;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( symplectic_test , Stepper, symplectic_steppers )\n{\n    perform_symplectic_test< Stepper > tester;\n    tester();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6d3f75b156602f976c2c57065079b3a36a5172ff", "size": 2553, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/test/numeric/symplectic.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/test/numeric/symplectic.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/test/numeric/symplectic.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": 26.59375, "max_line_length": 112, "alphanum_fraction": 0.6380728555, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5172505313434522}}
{"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__SE2_HPP_\n#define SMOOTH__SE2_HPP_\n\n#include <Eigen/Core>\n\n#include <complex>\n\n#include \"internal/lie_group_base.hpp\"\n#include \"internal/macro.hpp\"\n#include \"internal/se2.hpp\"\n#include \"so2.hpp\"\n\nnamespace smooth {\n\n// \\cond\ntemplate<typename Scalar>\nclass SE3;\n// \\endcond\n\n/**\n * @brief Base class for SE2 Lie group types.\n *\n * Internally represented as \\f$\\mathbb{U}(1) \\times \\mathbb{R}^2\\f$.\n *\n * Memory layout\n * -------------\n *\n * - Group:    \\f$ \\mathbf{x} = [x, y, q_z, q_w] \\f$\n * - Tangent:  \\f$ \\mathbf{a} = [v_x, v_y, \\omega_z] \\f$\n *\n * Constraints\n * -----------\n *\n * - Group:   \\f$q_z^2 + q_w^2 = 1 \\f$\n * - Tangent: \\f$ -\\pi < \\omega_z \\leq \\pi \\f$\n *\n * Lie group matrix form\n * ---------------------\n *\n * \\f[\n * \\mathbf{X} =\n * \\begin{bmatrix}\n *  q_w & -q_z & x \\\\\n *  q_z &  q_w & y \\\\\n *  0   &    0 & 1\n * \\end{bmatrix} \\in \\mathbb{R}^{3 \\times 3}\n * \\f]\n *\n *\n * Lie algebra matrix form\n * -----------------------\n *\n * \\f[\n * \\mathbf{a}^\\wedge =\n * \\begin{bmatrix}\n *   0 & -\\omega_z & v_x \\\\\n *  \\omega_z &   0 & v_y \\\\\n *  0 & 0 & 0\n * \\end{bmatrix} \\in \\mathbb{R}^{3 \\times 3}\n * \\f]\n */\ntemplate<typename _Derived>\nclass SE2Base : public LieGroupBase<_Derived>\n{\n  using Base = LieGroupBase<_Derived>;\n\nprotected:\n  SE2Base() = default;\n\npublic:\n  SMOOTH_INHERIT_TYPEDEFS;\n\n  /**\n   * @brief Access SO(2) part.\n   */\n  Eigen::Map<SO2<Scalar>> so2() requires is_mutable\n  {\n    return Eigen::Map<SO2<Scalar>>(static_cast<_Derived &>(*this).data() + 2);\n  }\n\n  /**\n   * @brief Const access SO(2) part.\n   */\n  Eigen::Map<const SO2<Scalar>> so2() const\n  {\n    return Eigen::Map<const SO2<Scalar>>(static_cast<const _Derived &>(*this).data() + 2);\n  }\n\n  /**\n   * @brief Access R2 part.\n   */\n  Eigen::Map<Eigen::Matrix<Scalar, 2, 1>> r2() requires is_mutable\n  {\n    return Eigen::Map<Eigen::Matrix<Scalar, 2, 1>>(static_cast<_Derived &>(*this).data());\n  }\n\n  /**\n   * @brief Const access R2 part.\n   */\n  Eigen::Map<const Eigen::Matrix<Scalar, 2, 1>> r2() const\n  {\n    return Eigen::Map<const Eigen::Matrix<Scalar, 2, 1>>(\n      static_cast<const _Derived &>(*this).data());\n  }\n\n  /**\n   * @brief Tranformation action on 2D vector.\n   */\n  template<typename EigenDerived>\n  Eigen::Matrix<Scalar, 2, 1> operator*(const Eigen::MatrixBase<EigenDerived> & v) const\n  {\n    return so2() * v + r2();\n  }\n\n  /**\n   * @brief Lift to SE3.\n   *\n   * @note SE3 header must be included.\n   */\n  SE3<Scalar> lift_se3() const\n  {\n    return SE3<Scalar>(\n      so2().lift_so3(), Eigen::Matrix<Scalar, 3, 1>(r2().x(), r2().y(), Scalar(0)));\n  }\n};\n\n// \\cond\ntemplate<typename _Scalar>\nclass SE2;\n// \\endcond\n\n// \\cond\ntemplate<typename _Scalar>\nstruct lie_traits<SE2<_Scalar>>\n{\n  static constexpr bool is_mutable = true;\n\n  using Impl   = SE2Impl<_Scalar>;\n  using Scalar = _Scalar;\n\n  template<typename NewScalar>\n  using PlainObject = SE2<NewScalar>;\n};\n// \\endcond\n\n/**\n * @brief Storage implementation of SE2 Lie group.\n *\n * @see SE2Base for memory layout.\n */\ntemplate<typename _Scalar>\nclass SE2 : public SE2Base<SE2<_Scalar>>\n{\n  using Base = SE2Base<SE2<_Scalar>>;\n\n  SMOOTH_GROUP_API(SE2);\n\npublic:\n  /**\n   * @brief Construct from SO2 and R2. \n   *\n   * @param so2 orientation component.\n   * @param r2 translation component.\n   */\n  template<typename SO2Derived, typename T2Derived>\n  SE2(const SO2Base<SO2Derived> & so2, const Eigen::MatrixBase<T2Derived> & r2)\n  {\n    Base::so2() = so2;\n    Base::r2()  = r2;\n  }\n};\n\nusing SE2f = SE2<float>;   ///< SE2 with float\nusing SE2d = SE2<double>;  ///< SE2 with double\n\n}  // namespace smooth\n\n// MAP TYPE TRAITS\n\n// \\cond\ntemplate<typename _Scalar>\nstruct smooth::lie_traits<Eigen::Map<smooth::SE2<_Scalar>>>\n    : public lie_traits<smooth::SE2<_Scalar>>\n{};\n// \\endcond\n\n/**\n * @brief Memory mapping of SE2 Lie group.\n *\n * @see SE2Base for memory layout.\n */\ntemplate<typename _Scalar>\nclass Eigen::Map<smooth::SE2<_Scalar>> : public smooth::SE2Base<Eigen::Map<smooth::SE2<_Scalar>>>\n{\n  using Base = smooth::SE2Base<Eigen::Map<smooth::SE2<_Scalar>>>;\n\n  SMOOTH_MAP_API(Map);\n};\n\n// \\cond\ntemplate<typename _Scalar>\nstruct smooth::lie_traits<Eigen::Map<const smooth::SE2<_Scalar>>>\n    : public lie_traits<smooth::SE2<_Scalar>>\n{\n  static constexpr bool is_mutable = false;\n};\n// \\endcond\n\n/**\n * @brief Const memory mapping of SE2 Lie group.\n *\n * @see SE2Base for memory layout.\n */\ntemplate<typename _Scalar>\nclass Eigen::Map<const smooth::SE2<_Scalar>>\n    : public smooth::SE2Base<Eigen::Map<const smooth::SE2<_Scalar>>>\n{\n  using Base = smooth::SE2Base<Eigen::Map<const smooth::SE2<_Scalar>>>;\n\n  SMOOTH_CONST_MAP_API(Map);\n};\n\n#endif  // SMOOTH__SE2_HPP_\n", "meta": {"hexsha": "b9133b009b66e692440ed465ba4ed6e25c2a7d18", "size": 5921, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/se2.hpp", "max_stars_repo_name": "NamDinhRobotics/smooth", "max_stars_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:18.000Z", "max_issues_repo_path": "include/smooth/se2.hpp", "max_issues_repo_name": "NamDinhRobotics/smooth", "max_issues_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_issues_repo_licenses": ["MIT"], "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/se2.hpp", "max_forks_repo_name": "NamDinhRobotics/smooth", "max_forks_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_forks_repo_licenses": ["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.7791164659, "max_line_length": 97, "alphanum_fraction": 0.6507346732, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5172235452531049}}
{"text": "#include <iostream>\n#include <fstream>\n#include <ctime>\n#include <stdlib.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graphviz.hpp>\nusing namespace std;\nusing namespace boost;\n\n\nint main(int argc, char* argv[]) {\n\n typedef adjacency_list<setS, vecS, undirectedS> graph_type;\n size_t numNodes = atoi(argv[1]);\n size_t numEdges = atoi(argv[2]);\n ofstream outputFile;\n outputFile.open(argv[3]);\n boost::mt19937 rng;\n rng.seed(uint32_t(time(0)));\n\n// Build graph\n graph_type graph(0);\n\n generate_random_graph(graph, numNodes, numEdges, rng, false, false);\n\n write_graphviz(outputFile, graph);\n outputFile.close();\n\n return 0;\n}", "meta": {"hexsha": "24b13f45b8f921f5922e05243c73f11f0d1ae301", "size": 724, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rando_graph_gen.cpp", "max_stars_repo_name": "McFlip/k-automorphic-graph", "max_stars_repo_head_hexsha": "c161e57c411f690af6da3ef5bf1dafd282aba544", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T03:43:29.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-10T03:43:29.000Z", "max_issues_repo_path": "rando_graph_gen.cpp", "max_issues_repo_name": "McFlip/k-automorphic-graph", "max_issues_repo_head_hexsha": "c161e57c411f690af6da3ef5bf1dafd282aba544", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rando_graph_gen.cpp", "max_forks_repo_name": "McFlip/k-automorphic-graph", "max_forks_repo_head_hexsha": "c161e57c411f690af6da3ef5bf1dafd282aba544", "max_forks_repo_licenses": ["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.625, "max_line_length": 69, "alphanum_fraction": 0.7430939227, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5172235452531049}}
{"text": "#include \"test_ntl.hpp\"\n#include <NTL/ZZ.h>\n#include <NTL/GF2X.h>\n#include <NTL/GF2XFactoring.h>\n#define LINEARITY_CHECK\n#include \"tinymt32.h\"\n#include \"f2p_gmp.h\"\n#include <string>\n#include <stdio.h>\n#include <inttypes.h>\n#include <ctype.h>\n\nusing namespace NTL;\nusing namespace std;\n\n// parameter no check\nvoid tinymt32_add(tinymt32_t *a, tinymt32_t *b)\n{\n    for (int i = 0; i < 4; i++) {\n        a->status[i] ^= b->status[i];\n    }\n}\n\nvoid ok_print(bool ok, bool verbose)\n{\n    if (verbose) {\n        if (ok) {\n            printf(\"o\");\n        } else {\n            printf(\"x\");\n        }\n    }\n}\n\nvoid ntl_calc_jump(GF2X& jump, const GF2X& minpoly, ZZ& step)\n{\n    PowerXMod(jump, step, minpoly);\n}\n\nvoid gmp_calc_jump(GF2X& jump, mpz_t minpoly, mpz_t step)\n{\n    mpz_t jpoly;\n    static char buff[2000];\n    mpz_init(jpoly);\n    f2p_calc_jump(jpoly, minpoly, step);\n    f2p_get_hexstr(buff, jpoly);\n    hexto_poly(jump, buff);\n    mpz_clear(jpoly);\n}\n\nbool test_calc_jump(long degree, bool verbose)\n{\n    bool ok = true;\n    GF2X poly;\n    GF2X ntl_minpoly;\n    BuildIrred(poly, degree);\n    long step = degree * 10 + 7;\n    ZZ ntl_step(step);\n    GF2X ntl_jump;\n    GF2X f2p_jump;\n    mpz_t f2p_minpoly;\n    mpz_t f2p_step;\n    mpz_inits(f2p_minpoly, f2p_step, NULL);\n    mpz_set_ui(f2p_step, step);\n    string work;\n    for (int i = 0; i < 10; i++) {\n        BuildRandomIrred(ntl_minpoly, poly);\n        to_hexstring(work, ntl_minpoly);\n        f2p_set_hexstr(f2p_minpoly, work.c_str());\n        ntl_calc_jump(ntl_jump, ntl_minpoly, ntl_step);\n        gmp_calc_jump(f2p_jump, f2p_minpoly, f2p_step);\n        if (ntl_jump != f2p_jump) {\n            to_hexstring(work, ntl_jump);\n            printf(\"ntl_jump:%s\\n\", work.c_str());\n            to_hexstring(work, f2p_jump);\n            printf(\"f2p_jump:%s\\n\", work.c_str());\n            ok = false;\n        }\n        ok_print(ok, verbose);\n    }\n    if (verbose) {\n        printf(\"\\n\");\n    }\n    mpz_clears(f2p_minpoly, f2p_step, NULL);\n    return ok;\n}\n\n\nint main(int argc, char * argv[])\n{\n    bool verbose = false;\n    bool ok = true;\n    long degree = 127;\n    if (argc > 1 && argv[1][0] == 'v') {\n        verbose = true;\n    }\n    if (argc > 2) {\n        degree = strtol(argv[2], NULL, 10);\n    }\n#if 0\n    tiny32.mat1 = 0x8f7011ee;\n    tiny32.mat2 = 0xfc78ff1f;\n    tiny32.tmat = 0x3793fdff;\n\n    tinymt32_init(&tiny32, 1);\n#endif\n\n    ok = ok && test_calc_jump(degree, verbose);\n    if (ok) {\n        return 0;\n    } else {\n        return -1;\n    }\n}\n", "meta": {"hexsha": "b3b37c20ce8b7321eabab436bba44c47444773f3", "size": 2513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_jump_ntl.cpp", "max_stars_repo_name": "MSaito/f2p-gmp", "max_stars_repo_head_hexsha": "64d4d7d3d1f7b246b59fee519c69c9c2db8ccbad", "max_stars_repo_licenses": ["MIT"], "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_jump_ntl.cpp", "max_issues_repo_name": "MSaito/f2p-gmp", "max_issues_repo_head_hexsha": "64d4d7d3d1f7b246b59fee519c69c9c2db8ccbad", "max_issues_repo_licenses": ["MIT"], "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_jump_ntl.cpp", "max_forks_repo_name": "MSaito/f2p-gmp", "max_forks_repo_head_hexsha": "64d4d7d3d1f7b246b59fee519c69c9c2db8ccbad", "max_forks_repo_licenses": ["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.852173913, "max_line_length": 61, "alphanum_fraction": 0.5857540788, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5172235400955885}}
{"text": "//\n// Helper functions to construct MPC-style (continuous replanning) style policies using the iLQRTree \n// class.\n//\n\n#pragma once\n\n#include <ilqr/ilqr_taylor_expansions.hh>\n#include <ilqr/ilqr_tree.hh>\n\n#include <Eigen/Dense>\n\n#include <vector>\n\nnamespace policy\n{\n\n// Does hindsight optimization over a probabilistic split in dynamics.\n// Returns a control vector \"u\" by constructing a hindsight_split style tree. \n// Linearly interpolates from xt to xT for the initialization for iLQR with nominal_control for all\n// timesteps. \nEigen::VectorXd hindsight_tree_policy(const int t,\n                                      const Eigen::VectorXd& xt, \n                                      const int T,\n                                      const Eigen::VectorXd& xT, \n                                      const Eigen::VectorXd& nominal_control,\n                                      const std::vector<double> &probabilities, \n                                      const std::vector<ilqr::DynamicsFunc> &dynamics_funcs, \n                                      const ilqr::CostFunc &cost,\n                                      ilqr::iLQRTree& ilqr_tree);\n\n// Does hindsight optimization over a probabilistic split in cost functions.\n// Returns a control vector \"u\" by constructing a hindsight_split style tree. \n// Linearly interpolates from xt to xT for the initialization for iLQR with nominal_control for all\n// timesteps. \nEigen::VectorXd hindsight_tree_policy(const int t,\n                                      const Eigen::VectorXd& xt, \n                                      const int T,\n                                      const Eigen::VectorXd& xT, \n                                      const Eigen::VectorXd& nominal_control,\n                                      const std::vector<double> &probabilities, \n                                      const ilqr::DynamicsFunc &dynamics_func,\n                                      const std::vector<ilqr::CostFunc> &cost_funcs, \n                                      ilqr::iLQRTree& ilqr_tree);\n\n// Returns a control vector \"u\" by constructing a chain tree structure.\nEigen::VectorXd chain_policy(const int t, \n        const Eigen::VectorXd& xt, \n        const int T,\n        const Eigen::VectorXd& xT, \n        const Eigen::VectorXd& nominal_control,\n        const ilqr::DynamicsFunc &dynamics, \n        const ilqr::CostFunc &cost,\n        ilqr::iLQRTree& ilqr_tree);\n\n\n// Probability weighted controller over a probabilistic split in dynamics functions.\nEigen::VectorXd probability_weighted_policy(const int t, \n        const Eigen::VectorXd& xt, \n        const int T,\n        const Eigen::VectorXd& xT, \n        const Eigen::VectorXd& nominal_control,\n        const std::vector<double> &probabilities, \n        const std::vector<ilqr::DynamicsFunc> &dynamics_funcs, \n        const ilqr::CostFunc &cost);\n\n// Probability weighted controller over a probabilistic split in cost functions.\nEigen::VectorXd probability_weighted_policy(const int t, \n        const Eigen::VectorXd& xt, \n        const int T,\n        const Eigen::VectorXd& xT, \n        const Eigen::VectorXd& nominal_control,\n        const std::vector<double> &probabilities, \n        const ilqr::DynamicsFunc &dynamics_func, \n        const std::vector<ilqr::CostFunc> &cost_funcs);\n\n} // namespace policy\n", "meta": {"hexsha": "a265c77bde7903b9ffb68f19cd1535cb59751001", "size": 3321, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/ilqr/mpc_tree_policies.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/mpc_tree_policies.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/mpc_tree_policies.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": 42.5769230769, "max_line_length": 101, "alphanum_fraction": 0.5950015056, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5172235383874987}}
{"text": "/* test_uniform_real_distribution.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$\n *\n */\n\n#include <boost/random/uniform_real_distribution.hpp>\n#include <limits>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::uniform_real_distribution<>\n#define BOOST_RANDOM_ARG1 a\n#define BOOST_RANDOM_ARG2 b\n#define BOOST_RANDOM_ARG1_DEFAULT 0.0\n#define BOOST_RANDOM_ARG2_DEFAULT 1.0\n#define BOOST_RANDOM_ARG1_VALUE -0.5\n#define BOOST_RANDOM_ARG2_VALUE 1.5\n\n#define BOOST_RANDOM_DIST0_MIN 0.0\n#define BOOST_RANDOM_DIST0_MAX 1.0\n#define BOOST_RANDOM_DIST1_MIN -0.5\n#define BOOST_RANDOM_DIST1_MAX 1.0\n#define BOOST_RANDOM_DIST2_MIN -0.5\n#define BOOST_RANDOM_DIST2_MAX 1.5\n\n#define BOOST_RANDOM_TEST1_PARAMS (-1.0, 0.0)\n#define BOOST_RANDOM_TEST1_MIN -1.0\n#define BOOST_RANDOM_TEST1_MAX 0.0\n\n#define BOOST_RANDOM_TEST2_PARAMS\n#define BOOST_RANDOM_TEST2_MIN 0.0\n#define BOOST_RANDOM_TEST2_MAX 1.0\n\n#include \"test_distribution.ipp\"\n", "meta": {"hexsha": "f5a868c3992d3f6a6cfb5050a4f25ed460c30331", "size": 1075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_uniform_real_distribution.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-07T16:21:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:58:37.000Z", "max_issues_repo_path": "boost/libs/random/test/test_uniform_real_distribution.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/random/test/test_uniform_real_distribution.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 27.5641025641, "max_line_length": 76, "alphanum_fraction": 0.8139534884, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5172235366461615}}
{"text": "\n#define EIGEN_DONT_PARALLELIZE\n#include <Eigen/Core>\n\n#include \"update_ops.hpp\"\n#include \"update_ops_cpp.hpp\"\n#include \"utility.hpp\"\n\nvoid double_qubit_dense_matrix_gate(UINT target_qubit_index1,\n    UINT target_qubit_index2, const CTYPE matrix[16], CTYPE* state, ITYPE dim) {\n    double_qubit_dense_matrix_gate_c(\n        target_qubit_index1, target_qubit_index2, matrix, state, dim);\n}\n\nvoid double_qubit_dense_matrix_gate(UINT target_qubit_index1,\n    UINT target_qubit_index2, const Eigen::Matrix4cd& eigen_matrix,\n    CTYPE* state, ITYPE dim) {\n    double_qubit_dense_matrix_gate_eigen(\n        target_qubit_index1, target_qubit_index2, eigen_matrix, state, dim);\n}\n\nvoid double_qubit_dense_matrix_gate_eigen(UINT target_qubit_index1,\n    UINT target_qubit_index2, const Eigen::Matrix4cd& eigen_matrix,\n    CTYPE* state, ITYPE dim) {\n    // target mask\n\n    const UINT min_qubit_index =\n        get_min_ui(target_qubit_index1, target_qubit_index2);\n    const UINT max_qubit_index =\n        get_max_ui(target_qubit_index1, target_qubit_index2);\n    const ITYPE min_qubit_mask = 1ULL << min_qubit_index;\n    const ITYPE max_qubit_mask = 1ULL << (max_qubit_index - 1);\n    const ITYPE low_mask = min_qubit_mask - 1;\n    const ITYPE mid_mask = (max_qubit_mask - 1) ^ low_mask;\n    const ITYPE high_mask = ~(max_qubit_mask - 1);\n\n    const ITYPE target_mask1 = 1ULL << target_qubit_index1;\n    const ITYPE target_mask2 = 1ULL << target_qubit_index2;\n    std::complex<double>* eigen_state =\n        reinterpret_cast<std::complex<double>*>(state);\n\n    // loop variables\n    const ITYPE loop_dim = dim / 4;\n    ITYPE state_index;\n\n    for (state_index = 0; state_index < loop_dim; ++state_index) {\n        // create index\n        ITYPE basis_0 = (state_index & low_mask) +\n                        ((state_index & mid_mask) << 1) +\n                        ((state_index & high_mask) << 2);\n\n        // gather index\n        ITYPE basis_1 = basis_0 + target_mask1;\n        ITYPE basis_2 = basis_0 + target_mask2;\n        ITYPE basis_3 = basis_1 + target_mask2;\n\n        // fetch values\n        Eigen::Vector4cd vec(\n            state[basis_0], state[basis_1], state[basis_2], state[basis_3]);\n        vec = eigen_matrix * vec;\n        eigen_state[basis_0] = vec[0];\n        eigen_state[basis_1] = vec[1];\n        eigen_state[basis_2] = vec[2];\n        eigen_state[basis_3] = vec[3];\n    }\n}\n", "meta": {"hexsha": "c566635f56a94390759d891ac15401430d5addb9", "size": 2387, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/csim/update_ops_matrix_dense_double_eigen.cpp", "max_stars_repo_name": "kodack64/qulacs-osaka", "max_stars_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-26T06:56:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T02:07:24.000Z", "max_issues_repo_path": "src/csim/update_ops_matrix_dense_double_eigen.cpp", "max_issues_repo_name": "kodack64/qulacs-osaka", "max_issues_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 104.0, "max_issues_repo_issues_event_min_datetime": "2021-11-12T04:15:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T05:12:20.000Z", "max_forks_repo_path": "src/csim/update_ops_matrix_dense_double_eigen.cpp", "max_forks_repo_name": "kodack64/qulacs-osaka", "max_forks_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-19T11:52:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T04:20:17.000Z", "avg_line_length": 35.6268656716, "max_line_length": 80, "alphanum_fraction": 0.6832844575, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5172235297805557}}
{"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_ARCH_COMMON_SIMD_FUNCTION_MODF_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_MODF_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/function/trunc.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n\n\n   BOOST_DISPATCH_OVERLOAD(modf_\n                          , (typename A0, typename X)\n                          , bd::cpu_\n                          , bs::pack_<bd::arithmetic_<A0>, X>\n                          )\n   {\n     using result = std::pair < A0, A0>;\n     BOOST_FORCEINLINE result operator()(A0 const& a0) const\n      {\n        A0 ent = bs::trunc(a0);\n        A0 frac = a0-ent;\n        return result(frac, ent);\n      }\n   };\n\n\n} } }\n\n#endif\n\n", "meta": {"hexsha": "4ffff2e7bcd3df7319e72dda29b704ff3be0ba4a", "size": 1265, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/modf.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/arch/common/simd/function/modf.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/arch/common/simd/function/modf.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": 28.1111111111, "max_line_length": 100, "alphanum_fraction": 0.5296442688, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5172235297805557}}
{"text": "#include <fstream>\n#include <functional>\n#include <iostream>\n#include <queue>\n#include <unordered_map>\n\n#include <boost/dynamic_bitset.hpp>\n#include <boost/serialization/unordered_map.hpp>\n#include \"serialize.hpp\"\n\n#include \"huffman.hpp\"\n\nusing namespace std;\nusing namespace boost::archive;\nusing boost::dynamic_bitset;\n\n\nstruct node {\n    char c;\n    uint32_t count;\n    \n    node *lhs, *rhs;\n\n    ~node() {\n        delete lhs;\n        delete rhs;\n    }\n};\n\n\nusing huffman_tree = priority_queue<node *, vector<node *>, function<bool(const node *, const node *)>>;\n\n\nauto count(ifstream &ifs) {\n    unordered_map<char, uint32_t> freq_map;\n    char c;\n\n    while (ifs.get(c)) {\n        ++freq_map[c];\n    }\n\n    return freq_map;\n}\n\n\nbool node_cmp(const node *lhs, const node *rhs) {\n    return lhs->count == rhs->count ? lhs->c < rhs->c : lhs->count > rhs->count;\n}\n\n\nvoid _codes(const node *node,\n            dynamic_bitset<> &code,\n            unordered_map<char, dynamic_bitset<>> &encode_map) {\n    if (node->c == '\\0') {\n        code.push_back(0); _codes(node->lhs, code, encode_map); code.pop_back();\n        code.push_back(1); _codes(node->rhs, code, encode_map); code.pop_back();\n    }\n    else {\n        encode_map[node->c] = { code };\n    }\n}\n\nauto codes(const huffman_tree &pq) {\n    dynamic_bitset<> code;\n    unordered_map<char, dynamic_bitset<>> encode_map;\n\n    _codes(pq.top(), code, encode_map);\n\n    return encode_map;\n}\n\n\nauto build_tree(const unordered_map<char, uint32_t> &freq_map) {\n    huffman_tree pq(node_cmp);\n\n    for (auto && [ key, value ] : freq_map) {\n        pq.push(new node({ key, value, nullptr, nullptr }));\n    }\n\n    while (pq.size() > 1) {\n        auto lhs = pq.top(); pq.pop();\n        auto rhs = pq.top(); pq.pop();\n\n        auto root = new node({ '\\0', lhs->count + rhs->count, lhs, rhs });\n        pq.push(root);\n    }\n\n    return pq;\n}\n\n\nvoid encode(const string &file) {\n    ifstream ifs(file);\n\n    auto freq_map = count(ifs);\n    auto pq = build_tree(freq_map);\n\n    ifs.clear();\n    ifs.seekg(0, ios::beg);\n\n    auto encode_map = codes(pq);\n    \n    dynamic_bitset<> data;\n    char c;\n\n    while (ifs.get(c)) {\n        for (auto i = 0u; i < encode_map[c].size(); ++i) {\n            data.push_back(encode_map[c][i]);\n        }\n    }\n\n    ofstream ofs(file + \".huf\"s);\n    binary_oarchive oa(ofs);\n    oa << freq_map;\n    oa << data;\n}\n\n\nvoid decode(const string &file) {\n    unordered_map<char, uint32_t> freq_map;\n    dynamic_bitset<> data;\n    ifstream ifs(file);\n\n    binary_iarchive ia(ifs);\n    ia >> freq_map;\n    ia >> data;\n\n    auto pq = build_tree(freq_map);\n\n    ofstream ofs(file.substr(0, file.length() - 4) + \".dec\"s);\n\n    auto curr = pq.top();\n\n    for (auto i = 0u; i < data.size(); ++i) {\n        curr = data[i] ? curr->rhs : curr->lhs;\n\n        if (curr->c != '\\0') {\n            ofs << curr->c;\n            curr = pq.top();\n        }\n    }\n}", "meta": {"hexsha": "27605d42abad8e867aa2a77017922c3ba3245c3a", "size": 2909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "huffman.cpp", "max_stars_repo_name": "Learko/Huffman", "max_stars_repo_head_hexsha": "e8fa78e5101a3755b5c937803279ebed37570e0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "huffman.cpp", "max_issues_repo_name": "Learko/Huffman", "max_issues_repo_head_hexsha": "e8fa78e5101a3755b5c937803279ebed37570e0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "huffman.cpp", "max_forks_repo_name": "Learko/Huffman", "max_forks_repo_head_hexsha": "e8fa78e5101a3755b5c937803279ebed37570e0c", "max_forks_repo_licenses": ["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.485915493, "max_line_length": 104, "alphanum_fraction": 0.5778618082, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5172139750966488}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2020 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 \"weighted_alpha_complex_non_visible_points\"\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <CGAL/Epick_d.h>\n#include <CGAL/Epeck_d.h>\n\n#include <vector>\n\n#include <gudhi/Alpha_complex.h>\n#include <gudhi/Simplex_tree.h>\n\n\nusing list_of_1d_kernel_variants = boost::mpl::list<CGAL::Epeck_d< CGAL::Dynamic_dimension_tag >,\n                                                    CGAL::Epeck_d< CGAL::Dimension_tag<1>>,\n                                                    CGAL::Epick_d< CGAL::Dynamic_dimension_tag >,\n                                                    CGAL::Epick_d< CGAL::Dimension_tag<1>>\n                                                    >;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(Weighted_alpha_complex_non_visible_points, Kernel, list_of_1d_kernel_variants) {\n  // check that for 2 closed weighted 1-d points, one with a high weight to hide the second one with a small weight,\n  // that the point with a small weight has the same high filtration value than the edge formed by the 2 points\n  using Point_d = typename Kernel::Point_d;\n  std::vector<Point_d> points;\n  std::vector<double> p1 {0.};\n  points.emplace_back(p1.begin(), p1.end());\n  // closed enough points\n  std::vector<double> p2 {0.1};\n  points.emplace_back(p2.begin(), p2.end());\n  std::vector<typename Kernel::FT> weights {100., 0.01};\n\n  Gudhi::alpha_complex::Alpha_complex<Kernel, true> alpha_complex(points, weights);\n  Gudhi::Simplex_tree<> stree;\n  BOOST_CHECK(alpha_complex.create_complex(stree));\n\n  std::clog << \"Iterator on weighted alpha complex simplices in the filtration order, with [filtration value]:\"\n            << std::endl;\n  for (auto f_simplex : stree.filtration_simplex_range()) {\n    std::clog << \"   ( \";\n    for (auto vertex : stree.simplex_vertex_range(f_simplex)) {\n      std::clog << vertex << \" \";\n    }\n    std::clog << \") -> \" << \"[\" << stree.filtration(f_simplex) << \"] \" << std::endl;\n  }\n\n  BOOST_CHECK(stree.filtration(stree.find({0})) == -100.);\n  BOOST_CHECK(stree.filtration(stree.find({1})) == stree.filtration(stree.find({0, 1})));\n  BOOST_CHECK(stree.filtration(stree.find({1})) > 100000);\n}", "meta": {"hexsha": "dd83c1dad7412150f4c4231081652798a2824b52", "size": 2543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Alpha_complex/test/Weighted_alpha_complex_non_visible_points_unit_test.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "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/Alpha_complex/test/Weighted_alpha_complex_non_visible_points_unit_test.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "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/Alpha_complex/test/Weighted_alpha_complex_non_visible_points_unit_test.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "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.3833333333, "max_line_length": 116, "alphanum_fraction": 0.6472670075, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.517213965723544}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n\nusing namespace Eigen;\n\n// [functor]\ntemplate<class ArgType, class RowIndexType, class ColIndexType>\nclass indexing_functor {\n  const ArgType &m_arg;\n  const RowIndexType &m_rowIndices;\n  const ColIndexType &m_colIndices;\npublic:\n  typedef Matrix<typename ArgType::Scalar,\n                 RowIndexType::SizeAtCompileTime,\n                 ColIndexType::SizeAtCompileTime,\n                 ArgType::Flags&RowMajorBit?RowMajor:ColMajor,\n                 RowIndexType::MaxSizeAtCompileTime,\n                 ColIndexType::MaxSizeAtCompileTime> MatrixType;\n\n  indexing_functor(const ArgType& arg, const RowIndexType& row_indices, const ColIndexType& col_indices)\n    : m_arg(arg), m_rowIndices(row_indices), m_colIndices(col_indices)\n  {}\n\n  const typename ArgType::Scalar& operator() (Index row, Index col) const {\n    return m_arg(m_rowIndices[row], m_colIndices[col]);\n  }\n};\n// [functor]\n\n// [function]\ntemplate <class ArgType, class RowIndexType, class ColIndexType>\nCwiseNullaryOp<indexing_functor<ArgType,RowIndexType,ColIndexType>, typename indexing_functor<ArgType,RowIndexType,ColIndexType>::MatrixType>\nmat_indexing(const Eigen::MatrixBase<ArgType>& arg, const RowIndexType& row_indices, const ColIndexType& col_indices)\n{\n  typedef indexing_functor<ArgType,RowIndexType,ColIndexType> Func;\n  typedef typename Func::MatrixType MatrixType;\n  return MatrixType::NullaryExpr(row_indices.size(), col_indices.size(), Func(arg.derived(), row_indices, col_indices));\n}\n// [function]\n\n\nint main()\n{\n  std::cout << \"[main1]\\n\";\n  Eigen::MatrixXi A = Eigen::MatrixXi::Random(4,4);\n  Array3i ri(1,2,1);\n  ArrayXi ci(6); ci << 3,2,1,0,0,2;\n  Eigen::MatrixXi B = mat_indexing(A, ri, ci);\n  std::cout << \"A =\" << std::endl;\n  std::cout << A << std::endl << std::endl;\n  std::cout << \"A([\" << ri.transpose() << \"], [\" << ci.transpose() << \"]) =\" << std::endl;\n  std::cout << B << std::endl;\n  std::cout << \"[main1]\\n\";\n\n  std::cout << \"[main2]\\n\";\n  B =  mat_indexing(A, ri+1, ci);\n  std::cout << \"A(ri+1,ci) =\" << std::endl;\n  std::cout << B << std::endl << std::endl;\n#if __cplusplus >= 201103L\n  B =  mat_indexing(A, ArrayXi::LinSpaced(13,0,12).unaryExpr([](int x){return x%4;}), ArrayXi::LinSpaced(4,0,3));\n  std::cout << \"A(ArrayXi::LinSpaced(13,0,12).unaryExpr([](int x){return x%4;}), ArrayXi::LinSpaced(4,0,3)) =\" << std::endl;\n  std::cout << B << std::endl << std::endl;\n#endif\n  std::cout << \"[main2]\\n\";\n}\n\n", "meta": {"hexsha": "ca17456281cbbaa601b36efe0309a1d6c4795ebd", "size": 2454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/eigen/doc/examples/nullary_indexing.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/nullary_indexing.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/nullary_indexing.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": 36.6268656716, "max_line_length": 141, "alphanum_fraction": 0.6719641402, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5172139639477853}}
{"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/containers/grid/grid.h>\n#include <cmath> \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\ntemplate <typename grid_type>\nvoid grid_test( grid_type & G )\n{\n  typedef typename grid_type::value_type     value_type;\n  typedef typename grid_type::math_types     math_types;\n  typedef typename math_types::vector3_type  vector3_type;\n  typedef typename math_types::real_type     real_type;\n\n  value_type tol = value_type(0.01);\n\n  size_t I = 3;\n  size_t J = 3;\n  size_t K = 3;\n\n  // testing creation\n  {\n    vector3_type min_coord (-1.0, -1.0, -1.0 );\n    vector3_type max_coord ( 1.0,  1.0,  1.0 );\n\n    G.create( min_coord, max_coord, I, J, K);\n\n    BOOST_CHECK( I == G.I() );\n    BOOST_CHECK( J == G.J() );\n    BOOST_CHECK( K == G.K() );\n    BOOST_CHECK( (I*J*K) == G.size() );\n  }\n\n  grid_type const & H = G;\n\n  // testing read and write access to grid\n  {\n    size_t linear_index = 0;\n    value_type input    = 0;\n    for(size_t k = 0;k<K;++k)\n    {\n      for(size_t j = 0;j<J;++j)\n      {\n        for(size_t i = 0;i<I;++i)\n        {\n          value_type output0 = G(i,j,k);\n          BOOST_CHECK_CLOSE(output0, G.unused(), tol);\n\n          G(i,j,k) = input;\n\n          value_type const output1 = H(i,j,k);\n          BOOST_CHECK_CLOSE(input, output1, tol);\n\n          value_type const output2 = H.get_value(i,j,k);\n          BOOST_CHECK_CLOSE(input, output2, tol);\n\n          G( linear_index ) = input;\n\n          value_type const output3 = H(linear_index);\n          BOOST_CHECK_CLOSE(input, output3, tol);\n\n          value_type const output4 = H.get_value(linear_index);\n          BOOST_CHECK_CLOSE(input, output4, tol);\n\n          linear_index += 1;\n          input = input + 1;\n        }\n      }\n    }\n  }\n\n\n  // iterator testing\n  {\n    grid_type cpy = G;\n\n    typedef typename grid_type::iterator iterator;\n    typedef typename grid_type::const_iterator const_iterator;\n\n    iterator c = cpy.begin();\n    iterator c_end = cpy.end();\n    const_iterator g = H.begin();\n    const_iterator g_end = H.end();\n\n    for(;c!=c_end;++c,++g)\n    {\n      BOOST_CHECK_CLOSE( *c, *g, tol);\n    }\n  }\n\n\n  // index iterator testing\n  {\n    grid_type cpy = G;\n\n    typedef typename grid_type::index_iterator         index_iterator;\n    typedef typename grid_type::const_index_iterator   const_index_iterator;\n\n    index_iterator c = cpy.begin();\n    index_iterator c_end = cpy.end();\n    const_index_iterator g = H.begin();\n    const_index_iterator g_end = H.end();\n\n    for(size_t k = 0;k<K;++k)\n    {\n      for(size_t j = 0;j<J;++j)\n      {\n        for(size_t i = 0;i<I;++i)\n        {\n          BOOST_CHECK_CLOSE( *c, *g, tol);\n\n          BOOST_CHECK( c.i() == i );\n          BOOST_CHECK( c.j() == j );\n          BOOST_CHECK( c.k() == k );\n\n          BOOST_CHECK( g.i() == i );\n          BOOST_CHECK( g.j() == j );\n          BOOST_CHECK( g.k() == k );\n\n          ++c;\n          ++g;\n\n        }\n      }\n    }\n  }\n\n\n  // min_element and max_element testing\n  {\n    value_type const min_value = - G(2,2,2)*2;\n    value_type const max_value = - min_value;\n    G(1,1,1) = min_value;\n    G(0,1,1) = max_value;\n    value_type tst_min = OpenTissue::grid::min_element( G );\n    value_type tst_max = OpenTissue::grid::max_element( G );\n    BOOST_CHECK_CLOSE( tst_min, min_value, tol);\n    BOOST_CHECK_CLOSE( tst_max, max_value, tol);\n  }\n\n\n  // fabs testing\n  {\n    G = OpenTissue::grid::fabs(G);\n  }\n\n  // negate testing\n  {\n    G = OpenTissue::grid::negate(G);\n  }\n  // scale testing\n  {\n    value_type value = value_type(2);\n    G = OpenTissue::grid::scale(G, value );\n  }\n\n\n}\n\nBOOST_AUTO_TEST_SUITE(opentissue_grid);\n\nBOOST_AUTO_TEST_CASE(test_cases)\n{\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n  {\n    typedef OpenTissue::grid::Grid<float,math_types>         grid_type;\n    grid_type G;\n    grid_test(G);\n  }\n  {\n    typedef OpenTissue::grid::Grid<double,math_types>        grid_type;\n    grid_type G;\n    grid_test(G);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "1d850706bc448c482b380f6b4008ff051d1772c4", "size": 4511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/containers/grid/grid/src/unit_grid.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/containers/grid/grid/src/unit_grid.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/containers/grid/grid/src/unit_grid.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.6178010471, "max_line_length": 78, "alphanum_fraction": 0.6149412547, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5172139624923888}}
{"text": "#include <QApplication>\n#include <QMessageBox>\n#include <QMainWindow>\n#include \"Kernel_type.h\"\n#include \"Polyhedron_type.h\"\n#include \"Scene_polyhedron_item.h\"\n#include \"Scene_surface_mesh_item.h\"\n#include \"Scene_polylines_item.h\"\n\n#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>\n#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>\n\n#include <CGAL/Polygon_mesh_processing/stitch_borders.h>\n\n#include <CGAL/boost/graph/split_graph_into_polylines.h>\n#include <CGAL/boost/graph/helpers.h>\n#include <boost/graph/filtered_graph.hpp>\n\ntemplate <typename G>\nstruct Is_border {\n  const G& g;\n  Is_border(const G& g)\n    : g(g)\n  {}\n\n template <typename Descriptor>\n  bool operator()(const Descriptor& d) const {\n   return is_border(d,g);\n  }\n\n  bool operator()(typename boost::graph_traits<G>::vertex_descriptor d) const {\n    return is_border(d,g) != boost::none;\n  }\n\n};\n\n\nusing namespace CGAL::Three;\nclass Polyhedron_demo_polyhedron_stitching_plugin :\n  public QObject,\n  public Polyhedron_demo_plugin_helper\n{\n  Q_OBJECT\n  Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)\n  Q_PLUGIN_METADATA(IID \"com.geometryfactory.PolyhedronDemo.PluginInterface/1.0\")\n\n  QAction* actionDetectBorders;\n  QAction* actionStitchBorders;\npublic:\n  QList<QAction*> actions() const { return QList<QAction*>() << actionDetectBorders << actionStitchBorders; }\n  void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface, Messages_interface* /* m */)\n  {\n    scene = scene_interface;\n    actionDetectBorders= new QAction(tr(\"Detect Boundaries\"), mainWindow);\n    actionStitchBorders= new QAction(tr(\"Stitch Duplicated Boundaries\"), mainWindow);\n    actionDetectBorders->setObjectName(\"actionDetectBorders\");\n    actionStitchBorders->setObjectName(\"actionStitchBorders\");\n    actionStitchBorders->setProperty(\"subMenuName\", \"Polygon Mesh Processing\");\n    actionDetectBorders->setProperty(\"subMenuName\", \"Polygon Mesh Processing\");\n    autoConnectActions();\n  }\n\n  bool applicable(QAction*) const {\n    Q_FOREACH(int index, scene->selectionIndices())\n    {\n      if ( qobject_cast<Scene_polyhedron_item*>(scene->item(index)) ||\n           qobject_cast<Scene_surface_mesh_item*>(scene->item(index)) )\n        return true;\n    }\n    return false;\n  }\n\n  template <typename Item>\n  void on_actionDetectBorders_triggered(Scene_interface::Item_id index);\n\n  template <typename Item>\n  void on_actionStitchBorders_triggered(Scene_interface::Item_id index);\n\npublic Q_SLOTS:\n  void on_actionDetectBorders_triggered();\n  void on_actionStitchBorders_triggered();\n\n}; // end Polyhedron_demo_polyhedron_stitching_plugin\n\n\ntemplate <typename Poly>\nstruct Polyline_visitor\n{\n  Scene_polylines_item* new_item;\n  typename boost::property_map<Poly, CGAL::vertex_point_t>::const_type vpm;\n\n  Polyline_visitor(const Poly& poly, Scene_polylines_item* new_item)\n    : new_item(new_item), vpm(get(CGAL::vertex_point,poly))\n  {}\n\n  void start_new_polyline()\n  {\n    new_item->polylines.push_back( Scene_polylines_item::Polyline() );\n  }\n\n  void add_node(typename boost::graph_traits<Poly>::vertex_descriptor vd)\n  {\n    \n    new_item->polylines.back().push_back(get(vpm,vd));\n  }\n\n  void end_polyline(){}\n};\n\n\ntemplate <typename Item>\nvoid Polyhedron_demo_polyhedron_stitching_plugin::on_actionDetectBorders_triggered(Scene_interface::Item_id index)\n{\n  typedef typename Item::Face_graph  FaceGraph;\n  Item* item = qobject_cast<Item*>(scene->item(index));\n\n  if(item)\n    {\n      Scene_polylines_item* new_item = new Scene_polylines_item();\n\n      FaceGraph* pMesh = item->polyhedron();\n      normalize_border(*pMesh);\n\n\n      typedef boost::filtered_graph<FaceGraph,Is_border<FaceGraph>, Is_border<FaceGraph> > BorderGraph;\n      \n      Is_border<FaceGraph> ib(*pMesh);\n      BorderGraph bg(*pMesh,ib,ib);\n      Polyline_visitor<FaceGraph> polyline_visitor(*pMesh, new_item); \n      CGAL::split_graph_into_polylines( bg,\n                                        polyline_visitor,\n                                        CGAL::internal::IsTerminalDefault() );\n\n      \n      if (new_item->polylines.empty())\n        {\n          delete new_item;\n        }\n      else\n        {\n          new_item->setName(tr(\"Boundary of %1\").arg(item->name()));\n          new_item->setColor(Qt::red);\n          scene->addItem(new_item);\n          new_item->invalidateOpenGLBuffers();\n        }\n    }\n}\n\nvoid Polyhedron_demo_polyhedron_stitching_plugin::on_actionDetectBorders_triggered()\n{\n  Q_FOREACH(int index, scene->selectionIndices()){\n    on_actionDetectBorders_triggered<Scene_polyhedron_item>(index);\n    on_actionDetectBorders_triggered<Scene_surface_mesh_item>(index);\n  }\n}\n\ntemplate <typename Item>\nvoid Polyhedron_demo_polyhedron_stitching_plugin::on_actionStitchBorders_triggered(Scene_interface::Item_id index)\n{\n  Item* item =\n    qobject_cast<Item*>(scene->item(index));\n\n  if(item){\n    typename Item::Face_graph* pMesh = item->polyhedron();\n    CGAL::Polygon_mesh_processing::stitch_borders(*pMesh);\n    item->invalidateOpenGLBuffers();\n    scene->itemChanged(item);\n  }\n}\n\n\nvoid Polyhedron_demo_polyhedron_stitching_plugin::on_actionStitchBorders_triggered()\n{\n  Q_FOREACH(int index, scene->selectionIndices()){\n    on_actionStitchBorders_triggered<Scene_polyhedron_item>(index);\n    on_actionStitchBorders_triggered<Scene_surface_mesh_item>(index);\n  }\n}\n#include \"Polyhedron_stitching_plugin.moc\"\n", "meta": {"hexsha": "c549b1b3aa46f4c9326fe6ce07464af1b678e21e", "size": 5394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Plugins/PMP/Polyhedron_stitching_plugin.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/demo/Polyhedron/Plugins/PMP/Polyhedron_stitching_plugin.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/demo/Polyhedron/Plugins/PMP/Polyhedron_stitching_plugin.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.9666666667, "max_line_length": 114, "alphanum_fraction": 0.7328513163, "num_tokens": 1289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5172139578058365}}
{"text": "/*\n * Regression.cpp\n *\n *  Created on: 2013/06/15\n *      Author: kryozahiro\n */\n\n#include \"Regression.h\"\n\n#include <cassert>\n#include <boost/lexical_cast.hpp>\nusing namespace std;\n\nRegression::Regression(const DataSet& dataSet) : Problem(dataSet.getProgramType()), dataSet(dataSet) {\n}\n\nRegression::Regression(const boost::property_tree::ptree& gameTree, mt19937_64& randomEngine) :\n\t\tProblem(fromPtree(gameTree, randomEngine).getProgramType()),\n\t\tdataSet(fromPtree(gameTree, randomEngine)) {\n}\n\nstring Regression::toString() const {\n\treturn dataSet.toString();\n}\n\ndouble Regression::evaluate(Program& program) {\n\tdouble diff = 0;\n\tfor (int i = 0; i < dataSet.getSize(); ++i) {\n\t\tvector<double> output = program(dataSet[i].first);\n\t\tassert(getProgramType().getOutputType().accepts(output));\n\n\t\t//\u4e8c\u4e57\u8aa4\u5dee\u3092\u6c42\u3081\u308b\n\t\tfor (int k = 0; k < getProgramType().getOutputType().getSize(); ++k) {\n\t\t\tdouble error = output[k] - dataSet[i].second[k];\n\t\t\t//diff += error * error;\n\t\t\tdiff += fabs(error);\n\t\t}\n\t}\n\tif (diff < 0) {\n\t\tdiff = DBL_MAX;\n\t}\n\treturn diff;\n}\n\n/*string Regression::showProgram(Program& program) const {\n\tstring ret;\n\tfor (int i = 0; i < dataSet.getSize(); ++i) {\n\t\tconst pair<vector<double>, vector<double>>& point = dataSet[i];\n\n\t\tret += \"in = ( \";\n\t\tfor (double inputElement : point.first) {\n\t\t\tret += boost::lexical_cast<string>(inputElement) + \" \";\n\t\t}\n\t\tret += \")\\tdiffout = ( \";\n\t\tvector<double> output = program(point.first);\n\t\tfor (unsigned int i = 0; i < output.size(); ++i) {\n\t\t\tret += boost::lexical_cast<string>(output[i] - point.second[i]) + \" \";\n\t\t}\n\t\tret += \")\\n\";\n\t}\n\treturn ret;\n}*/\n\nDataSet Regression::fromPtree(const boost::property_tree::ptree& gameTree, std::mt19937_64& randomEngine) {\n\tboost::property_tree::ptree dataTree = gameTree.get_child(\"DataSet\");\n\treturn DataSet(dataTree, randomEngine);\n}\n", "meta": {"hexsha": "4e993a151df97dfdcb521541ed990b0880a4db0c", "size": 1825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gamesolver/problem/Regression.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/Regression.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/Regression.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": 26.8382352941, "max_line_length": 107, "alphanum_fraction": 0.6684931507, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.517213954574681}}
{"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();\nMatrix2f m;\nm = M;\ncout << \"Here is the matrix m:\" << endl << m << endl;\ncout << \"Now we want to copy a column into a row.\" << endl;\ncout << \"If we do m.col(1) = m.row(0), then m becomes:\" << endl;\nm.col(1) = m.row(0);\ncout << m << endl << \"which is wrong!\" << endl;\ncout << \"Now let us instead do m.col(1) = m.row(0).eval(). Then m becomes\" << endl;\nm = M;\nm.col(1) = m.row(0).eval();\ncout << m << endl << \"which is right.\" << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "43da41254808e68caaa19676dfedcb948ba792d7", "size": 687, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_MatrixBase_eval.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_eval.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_eval.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.9, "max_line_length": 83, "alphanum_fraction": 0.6171761281, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.5172139531192842}}
{"text": "//\n// Created by krab1k on 31/10/18.\n//\n\n#include <vector>\n#include <cmath>\n#include <functional>\n#include <Eigen/LU>\n\n#include \"smpqeq.h\"\n#include \"../parameters.h\"\n#include \"../geometry.h\"\n\nCHARGEFW2_METHOD(SMP_QEq)\n\n\nEigen::VectorXd SMP_QEq::EE_system(const std::vector<const Atom *> &atoms, double total_charge) const {\n\n    size_t n = atoms.size();\n\n    Eigen::MatrixXd A = Eigen::MatrixXd::Zero(n + 1, n + 1);\n    Eigen::VectorXd b = Eigen::VectorXd::Zero(n + 1);\n\n    for (int iter = 0; iter < 5; iter++)\n    {\n        for (size_t i = 0; i < n; i++) {\n            const auto &atom_i = *atoms[i];\n            A(i, i) = 2 * (parameters_->atom()->parameter(atom::second)(atom_i) +\n                                parameters_->atom()->parameter(atom::third)(atom_i) * b(i) +\n                                parameters_->atom()->parameter(atom::fourth)(atom_i) * b(i) * b(i));\n            b(i) = -parameters_->atom()->parameter(atom::first)(atom_i);\n            for (size_t j = i + 1; j < n; j++) {\n                const auto &atom_j = *atoms[j];\n                auto gamma = 2 * std::sqrt(parameters_->atom()->parameter(atom::second)(atom_i) *\n                                           parameters_->atom()->parameter(atom::second)(atom_j));\n                auto expr = 1 / std::cbrt(1 / std::pow(gamma, 3) + std::pow(distance(atom_i, atom_j), 3));\n                A(i, j) = expr;\n                A(j, i) = expr;\n            }\n        }\n\n        A.row(n) = Eigen::VectorXd::Constant(n + 1, 1);\n        A.col(n) = Eigen::VectorXd::Constant(n + 1, 1);\n        A(n, n) = 0;\n        b(n) = total_charge;\n\n        b = A.partialPivLu().solve(b);\n    }\n\n    return b.head(n);\n}\n\n\nstd::vector<double> SMP_QEq::calculate_charges(const Molecule &molecule) const {\n    auto f = [this](const std::vector<const Atom *> &atoms, double total_charge) -> Eigen::VectorXd {\n        return EE_system(atoms, total_charge);\n    };\n\n    Eigen::VectorXd q = solve_EE(molecule, f);\n    return std::vector<double>(q.data(), q.data() + q.size());\n}\n", "meta": {"hexsha": "10629dd9e993b0285e68bf6bdbac995e3623878a", "size": 2026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/methods/smpqeq.cpp", "max_stars_repo_name": "danny305/ChargeFW2", "max_stars_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T15:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:38:09.000Z", "max_issues_repo_path": "src/methods/smpqeq.cpp", "max_issues_repo_name": "danny305/ChargeFW2", "max_issues_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-03-04T21:38:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T07:11:19.000Z", "max_forks_repo_path": "src/methods/smpqeq.cpp", "max_forks_repo_name": "danny305/ChargeFW2", "max_forks_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-05T00:42:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T05:47:39.000Z", "avg_line_length": 32.6774193548, "max_line_length": 106, "alphanum_fraction": 0.5340572557, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5171288661427488}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <math.h>\n#include <unsupported/Eigen/MatrixFunctions>\n\n//Global Variables\nusing Eigen::Vector3f;\nVector3f g(0,0,-9.81); //gravity\n\n//Cross Product Equivalent\nusing Eigen::Matrix3f;\nusing Eigen::Vector3f;\nMatrix3f crossProductEquivalent(Vector3f v)\n{\n  Matrix3f c;\n  c << 0, -v(2), v(1),\n       v(2), 0, -v(0),\n       -v(1), v(0), 0;\n  //std::cout << c << std::endl;\n  return c;\n}\n\n//Quaternion Multiplication\nusing Eigen::Quaternionf;\nusing Eigen::Vector3f;\nQuaternionf qMultiply(Quaternionf q1, Quaternionf q2)\n{\n  float w1 = q1.w();\n  float w2 = q2.w();\n  Vector3f v1 = q1.vec();\n  Vector3f v2 = q2.vec();\n  float wReturn = w1*w2 - v1(0)*v2(0) - v1(1)*v2(1) - v1(2)*v2(2);\n  Vector3f vReturn;\n  vReturn(0) = w1*v2(0) + v1(0)*w2 + v1(1)*v2(2) - v1(2)*v2(1);\n  vReturn(1) = w1*v2(1) - v1(0)*v2(2) + v1(1)*w2 + v1(2)*v2(0);\n  vReturn(2) = w1*v2(2) + v1(0)*v2(1) - v1(1)*v2(0) + v1(2)*w2;\n  Quaternionf qReturn;\n  qReturn.w() = wReturn; \n  qReturn.vec() = vReturn;\n  //std::cout << qReturn.w() << std::endl << qReturn.vec() << std::endl;\n  return qReturn;\n}\n\n//Quaternion Exponential\n//implements simple 0th-order integration\n//ref: quaternion kinematics, section 4.6.1 \nusing Eigen::Quaternionf;\nusing Eigen::Vector3f;\nQuaternionf qExponential(float dt, Vector3f w)\n{\n  float wn = w.norm();\n  Vector3f wN = w.normalized();\n  Quaternionf qReturn;\n  qReturn.w() = cos(wn * dt / 2);\n  qReturn.vec() = wN * sin(wn * dt / 2);\n  return qReturn;\n}\n\n//Quaternion to DCM\n//ref: mathworks Quat2DCM documentation\nusing Eigen::Quaternionf;\nusing Eigen::Matrix3f;\nMatrix3f q2dcm(Quaternionf q)\n{\n  float q0 = q.w();\n  float q1 = q.x(); \n  float q2 = q.y();\n  float q3 = q.z();\n  Matrix3f DCM;\n  DCM << (q0*q0 + q1*q1 - q2*q2 - q3*q3), 2*(q1*q2 + q0*q3), 2*(q1*q3 - q0*q2), \n          2*(q1*q2 - q0*q3), (q0*q0 - q1*q1 + q2*q2 - q3*q3), 2*(q2*q3 + q0*q1), \n          2*(q1*q3 + q0*q2), 2*(q2*q3 - q0*q1), (q0*q0 - q1*q1 - q2*q2 + q3*q3);\n  return DCM; \n}\n\n//Euler angles to DCM\n//e = [phi, theta, psi]\n//3-1-2 rotation\n//ref: Todd Humphreys euler2dcm MATLAB function, \"Aerial Robotics,\" 2019\nusing Eigen::Matrix3f;\nusing Eigen::Vector3f;\nMatrix3f euler2dcm(Vector3f e)\n{\n  std::cout << \"Calculating trig values...\" << std::endl;\n  float cPhi = cos(e(0)); \n  float sPhi = sin(e(0));\n  float cThe = cos(e(1)); \n  float sThe = sin(e(1));\n  float cPsi = cos(e(2)); \n  float sPsi = sin(e(2));\n  std::cout << \"Building DCM...\" << std::endl;\n  Matrix3f DCM; \n  DCM << (cPhi*cThe - sPhi*sPsi*sThe), (cThe*sPsi + cPsi * sPhi*sThe), (-cPhi*sThe), \n         (-cPhi*sPsi),                                    (cPhi*cPsi),         sPhi,\n         (cPsi*sThe + cThe*sPhi*sPsi), (sPsi*sThe - cPsi*cThe*sPhi),    (cPhi*cThe);\n  return DCM;\n}\n\n\n//Estimate class\nusing Eigen::Quaternionf;\nusing Eigen::Vector3f;\nclass StateEstimate\n{\n  private:\n    Quaternionf qHat;\n    Vector3f pHat;\n    Vector3f vHat;\n    /*Vector3f dThetaHat;*/\n    Vector3f bgHat;\n    Vector3f baHat;\n    float tk;\n  \n  public:\n    StateEstimate(Quaternionf q, Vector3f p, Vector3f v, /*Vector3f dTheta,*/ Vector3f bg, Vector3f ba, float tk) {\n      qHat = q;\n      pHat = p; \n      vHat = v;\n      /*dThetaHat = dTheta;*/\n      bgHat = bg;\n      baHat = ba;\n    }\n\n    Quaternionf getqHat(){return qHat;}\n    void setqHat(Quaternionf q){this->qHat = q;}\n    /*Vector3f getdThetaHat(){return dThetaHat;}\n    void setdThetaHat(Vector3f dTheta){this->dThetaHat = dThetaHat;}*/\n    Vector3f getpHat(){return pHat;}\n    void setpHat(Vector3f p){this->pHat = p;}\n    Vector3f getvHat(){return vHat;}\n    void setvHat(Vector3f v){this->vHat = v;}\n    Vector3f getbgHat(){return bgHat;}\n    void setbgHat(Vector3f bg){this->bgHat = bg;}\n    Vector3f getbaHat(){return baHat;}\n    void setbaHat(Vector3f ba){this->baHat = ba;}\n    void gettk(){return tk;}\n    void settk(float t){this->tk = t;}\n\n};\n\n//Estimator state class\nusing Eigen::Vector3f;\nusing Eigen::Matrix3f; \nclass EstimatorState\n{\nprivate: \n\tQuaternionf qBar;\n\tVector3f pBar;\n\tVector3f vBar; \n\tVector3f e; \n\tVector3f bgBar; \n\tVector3f baBar; \n\n\tMatrix3f Pp;\n\tMatrix3f Pv;\n\tMatrix3f Pe;\n\tMatrix3f Pba;\n\tMatrix3f Pbg;\n\n\tfloat tk;\n\npublic:\n\tEstimatorState(Quaternionf q, Vector3f p, Vector3f v, Vector3f ee, Vector3f bg, \n\t\tVector3f ba, Matrix3f pp, Matrix3f pv, Matrix3f pe, Matrix3f pba, Matrix3f pbg, float tk) {\n        qBar = q;\n        pBar = p;\n        vBar = v;\n        e = ee; \n        bgBar = bg; \n        baBar = ba; \n        Pe = pe; \n        Pp = pp;\n        Pv = pv; \n        Pba = pba; \n        Pbg = pbg; \n\t}\n\n\tQuaternionf getqBar(){return qBar;}\n    void setqBar(Quaternionf q){this->qBar = q;}\n    /*Vector3f getdThetaHat(){return dThetaHat;}\n    void setdThetaHat(Vector3f dTheta){this->dThetaHat = dThetaHat;}*/\n    Vector3f getpBar(){return pBar;}\n    void setpBar(Vector3f p){this->pBar = p;}\n    Vector3f getvBar(){return vBar;}\n    void sete(Vector3f ee){this->e = ee;}\n    Vector3f gete(){return e;}\n    void setvBar(Vector3f v){this->vBar = v;}\n    Vector3f getbgBar(){return bgBar;}\n    void setbgBar(Vector3f bg){this->bgBar = bg;}\n    Vector3f getbaBar(){return baBar;}\n    void setbaBar(Vector3f ba){this->baBar = ba;}\n    void gettk(){return tk;}\n    void settk(float t){this->tk = t;}\n}\n\n//Measurement class\nusing Eigen::Vector3f; \nusing Eigen::Matrix3f; \nclass Measurement\n{\nprivate: \n\tVector3f wm;\n\tVector3f am;\n\npublic: \n\tMeasurement(Vector3f a, Vector3f w) {\n        am = a;\n        wm = w; \n\t}\n\n\tVector3f getwm(){return wm;}\n    Vector3f getam(){return am;}\n\n}\n\n//Error state class\n/*using Eigen::Quaternionf;\nusing Eigen::Vector3f;\nclass ErrorState\n{\n  private: \n    Quaternionf qTilde;\n    Vector3f pTilde;\n    Vector3f vTilde;\n    Vector3f bgTilde;\n    Vector3f baTilde; \n\n  public: \n    ErrorState(Quaternionf qT, Vector3f pT, Vector3f vT, Vector3f bgT, Vector3f baT) {\n      qTilde = qT;\n      pTilde = pT; \n\n    }\n}*/\n\n//State Estimation (prop, update)\n//EKF-based estimation \n//ref: \"Aerial Robotics,\" 'Laboratory Exercise 3: Meas. Simulation and State Estimation,' 2019\nvoid prop(StateEstimate S, EstimatorState E)\n{\n    \n}\n\nvoid update(StateEstimate S, EstimatorState E, Measurements M)\n{\n    //Convert measurements to I-frame\n    Vector3f wm = M.getwm();\n    Vector3f am = M.getam();\n    Matrix3f RBIBark = q2dcm(E.getqBar());\n    Vector3f wmI = (RBIBark.transpose())*wm;\n    Vector3f amI = (RBIBark.transpose())*am; \n\n    //Push estimator state through measurement function \n    //(relationship bewteen measurements and dynamics)\n    //do stuff with image features\n    \n    \n}\n\n//Propagate State Estimate\n/*StateEstimate propState(StateEstimate S, Vector3f am, Vector3f wm, float dt)\n{\n  // Constants\n  using Eigen::Quaternionf;\n  using Eigen::Vector3f; \n  using Eigen::Matrix3f;\n  Matrix3f I3 = Matrix3f::Identity(3,3); \n  Matrix3f O3 = Matrix3f::Zero();\n  Matrix3f wmx = crossProductEquivalent(wm);\n\n  //State values\n  Quaternionf qHat = S.getqHat();\n  Vector3f dThetaHat = S.getdThetaHat();\n  Vector3f pHat = S.getpHat();\n  Vector3f vHat = S.getvHat();\n  Vector3f bgHat = S.getbgHat();\n  Vector3f baHat = S.getbaHat();\n\n  //Propagate quaternion\n  using Eigen::Quaternionf;\n  using Eigen::Vector3f; \n  using Eigen::Matrix3f;\n  Quaternionf qExp = qExponential(dt, wm);\n  Quaternionf qHatProp = qMultiply(qHat, qExp);\n\n  //Calculate TIB, the DCM\n  Matrix3f TIB = q2dcm(qHat);\n  Matrix3f TBI = TIB.transpose();\n\n  //Propagate p, the position\n  Vector3f pHatProp = pHat \n                      + vHat*dt  \n                      + 0.5*(TBI*crossProductEquivalent(am*(dt*dt)))*dThetaHat\n                      - 0.5*TIB*baHat; \n\n  //Propagate v, the velocity\n  Vector3f vHatProp = vHat \n  \t\t\t\t\t  + (TBI*crossProductEquivalent((am-baHat)*dt))*dThetaHat\n                      - TIB*dt*baHat;\n\n  //Propagate dThetaHat, the 3x1 vector of angles of attitude error\n  Vector3f dThetaHatProp = ((-crossProductEquivalent(wm)*dt).exp())*dThetaHat \n                  - bgHat;\n\n  //Propagate bg and ba, the gyroscope and accelerometer biases\n  Vector3f bgHatProp = bgHat;\n  Vector3f baHatProp = baHat;\n\n  //Return the propagated state\n  StateEstimate Sprop(qHatProp, pHatProp, vHatProp, dThetaHatProp, bgHatProp, baHatProp);\n  return Sprop;\n}*/\n\n//State Estimator\n//EKF-based estimation \n//ref: \"Aerial Robotics,\" 'Laboratory Exercise 3: Meas. Simulation and State Estimation,' 2019\nStateEstimate stateEstimatorEKF(float tk, Vector3f am, Vector3f wm, )\n\nint main()\n{\n  /*using Eigen::Vector3f; \n  using Eigen::Matrix3f;\n  using Eigen::Quaternionf;\n  Matrix3f A;\n  A << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n  Vector3f b; \n  b << 1, 2, 3;\n  Vector3f c;\n  c << 4, 5, 6;\n  std::cout << A*b << std::endl;\n  std::cout << 0.5*A*b <<std::endl;\n  float dt = 0.1;\n  std::cout << 0.5*b*dt*dt <<std::endl;*/\n\n  /*using Eigen::Vector3f; \n  using Eigen::Matrix3f;\n  using Eigen::Quaternionf;\n  Vector3f v(0.0, 3.1415, 6.2830);\n  Matrix3f DCM = euler2dcm(v);\n  std::cout << DCM << std::endl;*/\n\n  Quaternionf q;\n  Vector3f qv(0,0,0);\n  float qw = 1;\n  q.w() = qw;\n  q.vec() = qv;\n  Vector3f dTheta(0,0,0);\n  Vector3f p(0,0,0);\n  Vector3f v(0,0,0);\n  Vector3f bg(0,0,0);\n  Vector3f ba(0,0,0);\n  StateEstimate S(q, p, v, dTheta, bg, ba);\n\n  Vector3f am(0.2,0,-9.81);\n  Vector3f wm(0.5*3.1415,0,0);\n  float dt = 0.1;\n\n\n  for ( int ii = 0; ii < 10; ii = ii + 1 ){\n    StateEstimate Sprop = propState(S,am,wm,dt);\n    std::cout << \"qHatProp (w): \" << Sprop.getqHat().w() << std::endl;\n    std::cout << \"qHatProp (v): \" << std::endl << Sprop.getqHat().vec() << std::endl;\n    std::cout << \"dThetaHatProp: \" << std::endl << Sprop.getdThetaHat() << std::endl;\n    std::cout << \"pHatProp: \" << std::endl << Sprop.getpHat() << std::endl;\n    std::cout << \"vHatProp: \" << std::endl << Sprop.getvHat() << std::endl;\n    std::cout << \"baHatProp: \" << std::endl << Sprop.getbaHat() << std::endl;\n    std::cout << \"bgHatProp: \" << std::endl << Sprop.getbgHat() << std::endl;\n    std::cout << std::endl;\n    S = Sprop;\n  }\n\n\n}\n", "meta": {"hexsha": "627ed89711b26f2685b218a31878f8c2e39855a4", "size": 9957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "propagate.cpp", "max_stars_repo_name": "nearlab/rover_visual_od", "max_stars_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "propagate.cpp", "max_issues_repo_name": "nearlab/rover_visual_od", "max_issues_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "propagate.cpp", "max_forks_repo_name": "nearlab/rover_visual_od", "max_forks_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6229946524, "max_line_length": 115, "alphanum_fraction": 0.6246861504, "num_tokens": 3541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5170852128933607}}
{"text": "#include \"BVH.h\"\n#include <iostream>\n#include <Eigen/Geometry>\n#include \"dart/dart.hpp\"\nnamespace MSS\n{\nEigen::Matrix3d\nR_x(double x)\n{\n\tdouble cosa = cos(x*3.141592/180.0);\n\tdouble sina = sin(x*3.141592/180.0);\n\tEigen::Matrix3d R;\n\tR<<\t1,0\t\t,0\t  ,\n\t\t0,cosa\t,-sina,\n\t\t0,sina\t,cosa ;\n\treturn R;\n}\nEigen::Matrix3d R_y(double y)\n{\n\tdouble cosa = cos(y*3.141592/180.0);\n\tdouble sina = sin(y*3.141592/180.0);\n\tEigen::Matrix3d R;\n\tR <<cosa ,0,sina,\n\t\t0    ,1,   0,\n\t\t-sina,0,cosa;\n\treturn R;\t\n}\nEigen::Matrix3d R_z(double z)\n{\n\tdouble cosa = cos(z*3.141592/180.0);\n\tdouble sina = sin(z*3.141592/180.0);\n\tEigen::Matrix3d R;\n\tR<<\tcosa,-sina,0,\n\t\tsina,cosa ,0,\n\t\t0   ,0    ,1;\n\treturn R;\t\t\n}\nBVHNode::\nBVHNode(const std::string& name,BVHNode* parent)\n\t:mParent(parent),mName(name),mChannelOffset(0),mNumChannels(0)\n{\n\n}\nvoid\nBVHNode::\nSetChannel(int c_offset,std::vector<std::string>& c_name)\n{\n\tmChannelOffset = c_offset;\n\tmNumChannels = c_name.size();\n\tfor(const auto& cn : c_name)\n\t\tmChannel.push_back(CHANNEL_NAME[cn]);\n}\nvoid\nBVHNode::\nSet(const Eigen::VectorXd& m_t)\n{\n\tmR.setIdentity();\n\t\n\tfor(int i=0;i<mNumChannels;i++)\n\t{\n\t\tswitch(mChannel[i])\n\t\t{\n\t\tcase Xpos:break;\n\t\tcase Ypos:break;\n\t\tcase Zpos:break;\n\t\tcase Xrot:mR = mR*R_x(m_t[mChannelOffset+i]);break;\n\t\tcase Yrot:mR = mR*R_y(m_t[mChannelOffset+i]);break;\n\t\tcase Zrot:mR = mR*R_z(m_t[mChannelOffset+i]);break;\n\t\tdefault:break;\n\t\t}\n\t}\n\n}\nvoid\nBVHNode::\nSet(const Eigen::Matrix3d& R_t)\n{\n\tmR = R_t;\n}\nEigen::Matrix3d\nBVHNode::\nGet()\n{\n\treturn mR;\n}\n\nvoid\nBVHNode::\nAddChild(BVHNode* child)\n{\n\tmChildren.push_back(child);\n}\nBVHNode*\nBVHNode::\nGetNode(const std::string& name)\n{\n\tif(!mName.compare(name))\n\t\treturn this;\n\n\tfor(auto& c : mChildren)\n\t{\n\t\tBVHNode* bn = c->GetNode(name);\n\t\tif(bn!=nullptr)\n\t\t\treturn bn;\n\t}\n\n\treturn nullptr;\n}\n\nEigen::Vector3d\nBVH::\nGetP0()\n{\n\tEigen::VectorXd m_t = mMotions[0];\n\n\tEigen::Vector3d p0 = m_t.segment<3>(0) - mRootCOMOffset;\n\tp0 *= 0.01;\n\n\treturn p0;\n}\n\nBVH::\nBVH()\n{\n\n}\n\nvoid\nBVH::\nSetMotion(double t)\n{\n\t\n\tint k = ((int)std::floor(t/mTimeStep));\n\tk = std::max(0,std::min(k,mNumTotalFrames-1));\n\tdouble dt = t/mTimeStep - std::floor(t/mTimeStep);\n\tEigen::VectorXd m_t = mMotions[k];\n\t\n\tfor(auto& bn: mMap)\n\t\tbn.second->Set(m_t);\n\t\n\tmRootCOM = m_t.segment<3>(0) - mRootCOMOffset;\n\tmRootCOM *= 0.01;\n\t\n}\nEigen::Matrix3d\nBVH::\nGet(const std::string& bvh_node)\n{\n\treturn mMap[bvh_node]->Get();\n}\nvoid\nBVH::\nParse(const std::string& file)\n{\n\tstd::ifstream is(file);\n\n\tchar buffer[256];\n\n\tif(!is)\n\t{\n\t\tstd::cout<<\"Can't Open File\"<<std::endl;\n\t\treturn;\n\t}\n\twhile(is>>buffer)\n\t{\n\t\tif(!strcmp(buffer,\"HIERARCHY\"))\n\t\t{\n\t\t\tis>>buffer;//Root\n\t\t\tis>>buffer;//Name\n\t\t\tint c_offset = 0;\n\t\t\tmRoot = ReadHierarchy(nullptr,buffer,c_offset,is);\n\t\t\tmNumTotalChannels = c_offset;\n\t\t}\n\t\telse if(!strcmp(buffer,\"MOTION\"))\n\t\t{\n\t\t\tis>>buffer; //Frames:\n\t\t\tis>>buffer; //num_frames\n\t\t\tmNumTotalFrames = atoi(buffer);\n\t\t\tis>>buffer; //Frame\n\t\t\tis>>buffer; //Time:\n\t\t\tis>>buffer; //time step\n\t\t\tmTimeStep = atof(buffer);\n\t\t\tmMotions.resize(mNumTotalFrames);\n\t\t\tfor(auto& m_t : mMotions)\n\t\t\t\tm_t = Eigen::VectorXd::Zero(mNumTotalChannels);\n\t\t\tdouble val;\n\t\t\tfor(int i=0;i<mNumTotalFrames;i++)\n\t\t\t{\n\t\t\t\tfor(int j=0;j<mNumTotalChannels;j++)\n\t\t\t\t{\n\t\t\t\t\tis>>val;\n\t\t\t\t\tmMotions[i][j]=val;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tis.close();\n}\nBVHNode*\nBVH::\nReadHierarchy(BVHNode* parent,const std::string& name,int& channel_offset,std::ifstream& is)\n{\n\tchar buffer[256];\n\tdouble offset[3];\n\tstd::vector<std::string> c_name;\n\n\tBVHNode* new_node = new BVHNode(name,parent);\n\tmMap.insert(std::make_pair(name,new_node));\n\n\tis>>buffer; //{\n\n\twhile(is>>buffer)\n\t{\n\t\tif(!strcmp(buffer,\"}\"))\n\t\t\tbreak;\n\t\tif(!strcmp(buffer,\"OFFSET\"))\n\t\t{\n\t\t\t//Ignore\n\t\t\tdouble x,y,z;\n\n\t\t\tis>>x;\n\t\t\tis>>y;\n\t\t\tis>>z;\n\t\t\tif(parent==nullptr)\n\t\t\t{\n\t\t\t\tmRootCOMOffset[0] = x;\n\t\t\t\tmRootCOMOffset[1] = y;\n\t\t\t\tmRootCOMOffset[2] = z;\n\t\t\t}\n\t\t}\n\t\telse if(!strcmp(buffer,\"CHANNELS\"))\n\t\t{\n\n\t\t\tis>>buffer;\n\t\t\tint n;\n\t\t\tn= atoi(buffer);\n\t\t\t\n\t\t\tfor(int i=0;i<n;i++)\n\t\t\t{\n\t\t\t\tis>>buffer;\n\t\t\t\tc_name.push_back(std::string(buffer));\n\t\t\t}\n\t\t\t\n\t\t\tnew_node->SetChannel(channel_offset,c_name);\n\n\t\t\t\n\t\t\t\n\t\t\tchannel_offset+=n;\n\t\t}\n\t\telse if(!strcmp(buffer,\"JOINT\"))\n\t\t{\n\t\t\tis>>buffer;\n\t\t\tBVHNode* child = ReadHierarchy(new_node,std::string(buffer),channel_offset,is);\n\t\t\tnew_node->AddChild(child);\n\t\t}\n\t\telse if(!strcmp(buffer,\"End\"))\n\t\t{\n\t\t\tis>>buffer;\n\t\t\tBVHNode* child = ReadHierarchy(new_node,std::string(\"EndEffector\"),channel_offset,is);\n\t\t\tnew_node->AddChild(child);\n\t\t}\n\t}\n\t\n\treturn new_node;\n}\nstd::map<std::string,MSS::BVHNode::CHANNEL> BVHNode::CHANNEL_NAME =\n{\n\t{\"Xposition\",Xpos},\n\t{\"XPOSITION\",Xpos},\n\t{\"Yposition\",Ypos},\n\t{\"YPOSITION\",Ypos},\n\t{\"Zposition\",Zpos},\n\t{\"ZPOSITION\",Zpos},\n\t{\"Xrotation\",Xrot},\n\t{\"XROTATION\",Xrot},\n\t{\"Yrotation\",Yrot},\n\t{\"YROTATION\",Yrot},\n\t{\"Zrotation\",Zrot},\n\t{\"ZROTATION\",Zrot}\n};\n};", "meta": {"hexsha": "82a7da599b65ef999cf79fab2c940933f947e617", "size": 4821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sim/BVH.cpp", "max_stars_repo_name": "snumrl/MSS", "max_stars_repo_head_hexsha": "29433598a9a026a18cbc6c5a9742dee7490ab9c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-01-22T11:10:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T09:26:14.000Z", "max_issues_repo_path": "sim/BVH.cpp", "max_issues_repo_name": "snumrl/MSS", "max_issues_repo_head_hexsha": "29433598a9a026a18cbc6c5a9742dee7490ab9c7", "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": "sim/BVH.cpp", "max_forks_repo_name": "snumrl/MSS", "max_forks_repo_head_hexsha": "29433598a9a026a18cbc6c5a9742dee7490ab9c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-08-26T12:29:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T15:13:39.000Z", "avg_line_length": 17.1565836299, "max_line_length": 92, "alphanum_fraction": 0.6355527899, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5170852086258745}}
{"text": "//\tPrior for reconstructing the Equation of State of Dark Energy\n//\tref:\n//\n//  @Jan-19-2017: This file is mainly copied from another projetc of mine, xcos.\n//  Some improvemnet were made to make the code more readable.\n//\n//\t@May-17-2019: Now the covariance matrix is loaded from a pre-computed data file\n\n#include <armadillo>\n#include <imcmc/imcmc.hpp>\n#include <imcmc/parser++.hpp>\n#include \"Prior.hpp\"\n\nusing namespace imcmc;\nusing namespace imcmc::parser;\nusing namespace std;\n\nDDE_CPZ::DDE_CPZ(){\n    floating = false;\n    z = NULL;\n    a = NULL;\n    save_invcov = false; // this is for debug, set to false by default\n}\n\nDDE_CPZ::~DDE_CPZ() {\n\n    if( dde_spacing == 0 )\n        delete[] a;\n    else if( dde_spacing == 1 )\n        delete[] z;\n\n}\n\nvoid DDE_CPZ::Init( std::string& prior_settings ) {\n\n    data_info.GetInfo(prior_settings);\n\n    floating\t\t= Read::Read_Bool_from_File(prior_settings, \"dde_wfid_floating\");\n    nw \t\t\t\t= Read::Read_Int_from_File(prior_settings, \"eos_bin_num\");\n\n    dde_z_max \t\t= Read::Read_Double_from_File(prior_settings, \"tabulated_w_z_max\");\n    dde_a_min\t\t= 1./(1.+dde_z_max);\n\n    sigmafid \t\t= Read::Read_Double_from_File(prior_settings, \"dde_cpz_prior_sigmafid\");\n\n    save_invcov     = Read::Read_Bool_from_File(prior_settings, \"save_invcov\");\n\n//\t====================================\n//  load pre-computed covariance matrix\n    string cov_file = Read::Read_String_from_File(prior_settings, \"pre-computed_covmat\");\n\n//\t====================================\n//  load pre-determined bin centers\n    string abin_file= Read::Read_String_from_File(prior_settings, \"abin_centers\");\n\n    arma::vec abin_centers;\n    abin_centers.load(abin_file,arma::raw_ascii);\n\n//\t============================================================\n//\t@ Nov-8, 2016, update 'sigma_mean_w' option names ...\n//\tsigma_mean_w is the same for either evenly spaced in z or a\n//\t============================================================\n    sigma_mean_w\t= Read::Read_Double_from_File(prior_settings, \"dde_cpz_prior_sigma_mean_w\");\n\n    C\t= arma::zeros(nw, nw);\n    iC\t= arma::zeros(nw, nw);\n\n    C.load(cov_file, arma::raw_ascii);\n\n    //  We choose sigma_mean_w=0.04 as a reference , so if one wants to change sigma_mean_w,\n    //  he just needs to rescale the loaded covariance matrix without re-compute\n    //  the covariance matrix\n    C = C * pow(sigma_mean_w/0.04,2);\n\n    iC\t= C.i();\t//\tevaluate the inverse of the covariance matrix\n\n//  make a copy of the original covariance matrix without local-average\n    C_original  = C;\n    iC_original = iC;\n\n    dde_spacing = Read::Read_Int_from_File(prior_settings,\"dde_spacing\");\n    if( dde_spacing == 0 )\n        a = new double[nw];\n    else if( dde_spacing == 1 )\n        z = new double[nw];\n\n//\t====================================================================\n//\tNOTE: zbin[] and abin[] defined below is DIFFERENT from that used in\n//\teos approximation !!!\n//\t====================================================================\n    double zbin[nw];\n    double abin[nw];\n\n    double Delta;\n    double xi0;\n    double xij, x_plus, x_minus, xbar;\n\n    if( dde_spacing == 0 ) {\t\t//\tevenly spaced in a\n\n        ac\t= Read::Read_Double_from_File(prior_settings, \"dde_cpz_prior_ac\");\n\n        //  try to read smoothing scale $a_s$ from \"prior_settings\"\n\t\tif( Read::Has_Key_in_File(prior_settings,\"dde_cpz_prior_as\") ){\n\t\t\tas\t= Read::Read_Double_from_File(prior_settings, \"dde_cpz_prior_as\");\n\t\t}\n\t\telse{\n\t\t\tas\t= ac;\n\t\t}\n\n    //  Correct bin center of the last abin to make sure that it is correlated with the one next to it.\n    // \tAdded by XYH @20190516\n        abin_centers[nw-1] = abin_centers[nw-2] - (as-1e-10);\n\n        double da = (1.0-dde_a_min)/nw;\n        for(int i=0; i<nw; ++i) {\n            abin[i] = 1.0 - (i+0.5)*da; // center of each a-bin\n\n            if( floating ){\n                a[i] = abin_centers[i];\n            }\n        }\n\n        Delta \t= da;\n        xi0\t\t= sigma_mean_w*sigma_mean_w*(1-dde_a_min)/_PI_/ac;\n    }\n    else if( dde_spacing == 1 ) {\t//\tevenly spaced in z\n\n        zc \t= Read::Read_Double_from_File(prior_settings, \"dde_cpz_prior_zc\");\n\n\t\tif( Read::Has_Key_in_File(prior_settings,\"dde_cpz_prior_zs\") ) {\n\t\t\tzs\t= Read::Read_Double_from_File(prior_settings, \"dde_cpz_prior_zs\");\n\t\t}\n\t\telse{\n\t\t\tzs\t= zc;\n\t\t}\n\n        double dz = dde_z_max/nw;\n        for(int i=0; i<nw; ++i) {\n            zbin[i] = (i+0.5)*dz;\t// center of each a-bin\n\n            if( floating )\n                z[i] = zbin[i];\n        }\n\n        Delta \t= dz;\n        xi0\t\t= sigma_mean_w*sigma_mean_w*dde_z_max/_PI_/zc;\n    }\n    else {\n        string err = \"\\n*** DDE_CPZ::Init() ==> unsupported z-spacing !!!\";\n        throw runtime_error(err);\n    }\n\n    S\t= arma::zeros(nw, nw);  // smoothing matrix\n    I\t= arma::eye(nw,nw);\n\n    if( floating ) {\n\n        for(int i=0; i<nw; ++i) {\n            int count=0;\n\n            if( dde_spacing == 0 ) {\n                for( int j=0; j<nw; ++j ) {\n                    if( fabs(a[j] - a[i]) <= as + 1E-10 ) {\n                        S(i,j) = 1.0;\n                        ++count;\n                    }\n                }\n            }\n            else if( dde_spacing == 1 ) {\n                for( int j=0; j<nw; ++j ) {\n                    if( fabs(z[j] - z[i]) <= zs + 1E-10 ) {\n                        S(i,j) = 1.0;\n                        ++count;\n                    }\n                }\n            }\n\n            for( int j=0; j<nw; ++j )\n                S(i,j) = S(i,j)/count;\n        }\n\n\n\n        IS = I-S;\n        iC = IS.t() * iC * IS;\n    }\n\n//    S.save(\"EoS_smooth_matrix.txt\", arma::raw_ascii);\n//    iC.save(\"EoS_inv_covmat_20190701.txt\",arma::raw_ascii);\n\n    if( save_invcov ){\n        if( MPI::COMM_WORLD.Get_rank() == 0 ){\n            cout << \"Saving inverse of the CPZ covariance matrix \\n\";\n            iC.save(\"DDE_CPZ_prior_invcov_uncorrected.txt\",arma::raw_ascii);\n        }\n    }\n\n//    exit(0);\n}\n\ndouble Prior_DDE_CPZ(  \timcmc_double&   param,\n                        double&         lndet,\n                        double&         chisq,\n                        void*           model,\n                        void*           data,\n                        istate&         state ) {\n\n    state.this_like_is_ok=true;\n\n    lndet = chisq = 0;\n\n    DDE_CPZ *cpz = static_cast<DDE_CPZ*>(data);\n\n    arma::rowvec row_w = arma::zeros<arma::rowvec>(cpz->nw);\n    arma::colvec col_w = arma::zeros<arma::colvec>(cpz->nw);\n\n//  those extra high-z w_i will not be constrained by CPZ prior.\n\n    for(int i=0; i<cpz->nw; ++i) {\n        string wname= \"DDE_w\"+Read::IntToString(i);\n        row_w[i] = param[wname];\n        col_w[i] = row_w[i];\n    }\n\n    chisq = arma::as_scalar( row_w * cpz->iC * col_w );\n\n    return -lndet - 0.5*chisq;\n}\n", "meta": {"hexsha": "dc669a3d4afa6a47c3186e5c252e013957e795c7", "size": 6761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/priors/Prior_DDE_CPZ.cpp", "max_stars_repo_name": "LBJ-Wade/ClassMC_DE_EoS", "max_stars_repo_head_hexsha": "eaf9e92fcf867377be622d7627ebdba514fe2bac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-04-26T07:17:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T02:41:06.000Z", "max_issues_repo_path": "source/priors/Prior_DDE_CPZ.cpp", "max_issues_repo_name": "xyh-cosmo/ClassMC", "max_issues_repo_head_hexsha": "eaf9e92fcf867377be622d7627ebdba514fe2bac", "max_issues_repo_licenses": ["MIT"], "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/priors/Prior_DDE_CPZ.cpp", "max_forks_repo_name": "xyh-cosmo/ClassMC", "max_forks_repo_head_hexsha": "eaf9e92fcf867377be622d7627ebdba514fe2bac", "max_forks_repo_licenses": ["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.5240174672, "max_line_length": 103, "alphanum_fraction": 0.54074841, "num_tokens": 1934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5170770276443709}}
{"text": "//\n// Copyright (c) 2015-2020 CNRS INRIA\n// Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.\n//\n\n#include \"pinocchio/math/fwd.hpp\"\n#include \"pinocchio/multibody/joint/joints.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/compute-all-terms.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n\nusing namespace pinocchio;\n\ntemplate<typename D>\nvoid addJointAndBody(Model & model,\n                     const JointModelBase<D> & jmodel,\n                     const Model::JointIndex parent_id,\n                     const SE3 & joint_placement,\n                     const std::string & joint_name,\n                     const Inertia & Y)\n{\n  Model::JointIndex idx;\n  \n  idx = model.addJoint(parent_id,jmodel,joint_placement,joint_name);\n  model.appendBodyToJoint(idx,Y);\n}\n\nBOOST_AUTO_TEST_SUITE( JointPrismatic )\n  \nBOOST_AUTO_TEST_CASE(spatial)\n{\n  typedef TransformPrismaticTpl<double,0,0> TransformX;\n  typedef TransformPrismaticTpl<double,0,1> TransformY;\n  typedef TransformPrismaticTpl<double,0,2> TransformZ;\n  \n  typedef SE3::Vector3 Vector3;\n  \n  const double displacement = 0.2;\n  SE3 Mplain, Mrand(SE3::Random());\n  \n  TransformX Mx(displacement);\n  Mplain = Mx;\n  BOOST_CHECK(Mplain.translation().isApprox(Vector3(displacement,0,0)));\n  BOOST_CHECK(Mplain.rotation().isIdentity());\n  BOOST_CHECK((Mrand*Mplain).isApprox(Mrand*Mx));\n  \n  TransformY My(displacement);\n  Mplain = My;\n  BOOST_CHECK(Mplain.translation().isApprox(Vector3(0,displacement,0)));\n  BOOST_CHECK(Mplain.rotation().isIdentity());\n  BOOST_CHECK((Mrand*Mplain).isApprox(Mrand*My));\n  \n  TransformZ Mz(displacement);\n  Mplain = Mz;\n  BOOST_CHECK(Mplain.translation().isApprox(Vector3(0,0,displacement)));\n  BOOST_CHECK(Mplain.rotation().isIdentity());\n  BOOST_CHECK((Mrand*Mplain).isApprox(Mrand*Mz));\n  \n  SE3 M(SE3::Random());\n  Motion v(Motion::Random());\n  \n  MotionPrismaticTpl<double,0,0> mp_x(2.);\n  Motion mp_dense_x(mp_x);\n  \n  BOOST_CHECK(M.act(mp_x).isApprox(M.act(mp_dense_x)));\n  BOOST_CHECK(M.actInv(mp_x).isApprox(M.actInv(mp_dense_x)));\n  \n  BOOST_CHECK(v.cross(mp_x).isApprox(v.cross(mp_dense_x)));\n  \n  MotionPrismaticTpl<double,0,1> mp_y(2.);\n  Motion mp_dense_y(mp_y);\n  \n  BOOST_CHECK(M.act(mp_y).isApprox(M.act(mp_dense_y)));\n  BOOST_CHECK(M.actInv(mp_y).isApprox(M.actInv(mp_dense_y)));\n  \n  BOOST_CHECK(v.cross(mp_y).isApprox(v.cross(mp_dense_y)));\n  \n  MotionPrismaticTpl<double,0,2> mp_z(2.);\n  Motion mp_dense_z(mp_z);\n  \n  BOOST_CHECK(M.act(mp_z).isApprox(M.act(mp_dense_z)));\n  BOOST_CHECK(M.actInv(mp_z).isApprox(M.actInv(mp_dense_z)));\n  \n  BOOST_CHECK(v.cross(mp_z).isApprox(v.cross(mp_dense_z)));\n}\n\nBOOST_AUTO_TEST_CASE( test_kinematics )\n{\n  using namespace pinocchio;\n\n\n  Motion expected_v_J(Motion::Zero());\n  Motion expected_c_J(Motion::Zero());\n\n  SE3 expected_configuration(SE3::Identity());\n\n  JointDataPX joint_data;\n  JointModelPX joint_model;\n\n  joint_model.setIndexes(0, 0, 0);\n\n  Eigen::VectorXd q(Eigen::VectorXd::Zero(1));\n  Eigen::VectorXd q_dot(Eigen::VectorXd::Zero(1));\n\n  // -------\n  q << 0. ;\n  q_dot << 0.;\n\n  joint_model.calc(joint_data, q, q_dot);\n\n  BOOST_CHECK(expected_configuration.rotation().isApprox(joint_data.M.rotation(), 1e-12));\n  BOOST_CHECK(expected_configuration.translation().isApprox(joint_data.M.translation(), 1e-12));\n  BOOST_CHECK(expected_v_J.toVector().isApprox(((Motion) joint_data.v).toVector(), 1e-12));\n  BOOST_CHECK(expected_c_J.isApprox((Motion) joint_data.c, 1e-12));\n\n  // -------\n  q << 1.;\n  q_dot << 1.;\n\n  joint_model.calc(joint_data, q, q_dot);\n\n  expected_configuration.translation() << 1, 0, 0;\n\n  expected_v_J.linear() << 1., 0., 0.;\n\n  BOOST_CHECK(expected_configuration.rotation().isApprox(joint_data.M.rotation(), 1e-12));\n  BOOST_CHECK(expected_configuration.translation().isApprox(joint_data.M.translation(), 1e-12));\n  BOOST_CHECK(expected_v_J.toVector().isApprox(((Motion) joint_data.v).toVector(), 1e-12));\n  BOOST_CHECK(expected_c_J.isApprox((Motion) joint_data.c, 1e-12));\n}\n\nBOOST_AUTO_TEST_CASE( test_rnea )\n{\n  using namespace pinocchio;\n  typedef SE3::Vector3 Vector3;\n  typedef SE3::Matrix3 Matrix3;\n\n  Model model;\n  Inertia inertia(1., Vector3(0.5, 0., 0.0), Matrix3::Identity());\n\n  addJointAndBody(model,JointModelPX(),model.getJointId(\"universe\"),SE3::Identity(),\"root\",inertia);\n\n  Data data(model);\n\n  Eigen::VectorXd q(Eigen::VectorXd::Zero(model.nq));\n  Eigen::VectorXd v(Eigen::VectorXd::Zero(model.nv));\n  Eigen::VectorXd a(Eigen::VectorXd::Zero(model.nv));\n\n  rnea(model, data, q, v, a);\n\n  Eigen::VectorXd tau_expected(Eigen::VectorXd::Zero(model.nq));\n  tau_expected  << 0;\n\n  BOOST_CHECK(tau_expected.isApprox(data.tau, 1e-14));\n\n  // -----\n  q = Eigen::VectorXd::Ones(model.nq);\n  v = Eigen::VectorXd::Ones(model.nv);\n  a = Eigen::VectorXd::Ones(model.nv);\n\n  rnea(model, data, q, v, a);\n  tau_expected << 1;\n\n  BOOST_CHECK(tau_expected.isApprox(data.tau, 1e-12));\n\n  q << 3;\n  v = Eigen::VectorXd::Ones(model.nv);\n  a = Eigen::VectorXd::Ones(model.nv);\n\n  rnea(model, data, q, v, a);\n  tau_expected << 1;\n\n  BOOST_CHECK(tau_expected.isApprox(data.tau, 1e-12));\n}\n\nBOOST_AUTO_TEST_CASE( test_crba )\n{\n  using namespace pinocchio;\n  using namespace std;\n  typedef SE3::Vector3 Vector3;\n  typedef SE3::Matrix3 Matrix3;\n\n  Model model;\n  Inertia inertia(1., Vector3(0.5, 0., 0.0), Matrix3::Identity());\n\n  addJointAndBody(model,JointModelPX(),model.getJointId(\"universe\"),SE3::Identity(),\"root\",inertia);\n\n  Data data(model);\n\n  Eigen::VectorXd q(Eigen::VectorXd::Zero(model.nq));\n  Eigen::MatrixXd M_expected(model.nv,model.nv);\n\n  crba(model, data, q);\n  M_expected << 1.0;\n\n  BOOST_CHECK(M_expected.isApprox(data.M, 1e-14));\n\n  q = Eigen::VectorXd::Ones(model.nq);\n\n  crba(model, data, q);\n\n  BOOST_CHECK(M_expected.isApprox(data.M, 1e-12));\n\n  q << 3;\n\n  crba(model, data, q);\n  \n  BOOST_CHECK(M_expected.isApprox(data.M, 1e-10));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE(JointPrismaticUnaligned)\n  \nBOOST_AUTO_TEST_CASE(spatial)\n{\n  SE3 M(SE3::Random());\n  Motion v(Motion::Random());\n  \n  MotionPrismaticUnaligned mp(MotionPrismaticUnaligned::Vector3(1.,2.,3.),6.);\n  Motion mp_dense(mp);\n  \n  BOOST_CHECK(M.act(mp).isApprox(M.act(mp_dense)));\n  BOOST_CHECK(M.actInv(mp).isApprox(M.actInv(mp_dense)));\n  \n  BOOST_CHECK(v.cross(mp).isApprox(v.cross(mp_dense)));\n}\n\nBOOST_AUTO_TEST_CASE(vsPX)\n{\n  using namespace pinocchio;\n  typedef SE3::Vector3 Vector3;\n  typedef SE3::Matrix3 Matrix3;\n\n  Eigen::Vector3d axis;\n  axis << 1.0, 0.0, 0.0;\n\n  Model modelPX, modelPrismaticUnaligned;\n\n  Inertia inertia(1., Vector3(0.5, 0., 0.0), Matrix3::Identity());\n  SE3 pos(1); pos.translation() = SE3::LinearType(1.,0.,0.);\n\n  JointModelPrismaticUnaligned joint_model_PU(axis);\n  \n  addJointAndBody(modelPX,JointModelPX(),0,pos,\"px\",inertia);\n  addJointAndBody(modelPrismaticUnaligned,joint_model_PU,0,pos,\"prismatic-unaligned\",inertia);\n\n  Data dataPX(modelPX);\n  Data dataPrismaticUnaligned(modelPrismaticUnaligned);\n\n  Eigen::VectorXd q = Eigen::VectorXd::Ones(modelPX.nq);\n  Eigen::VectorXd v = Eigen::VectorXd::Ones(modelPX.nv);\n  Eigen::VectorXd tauPX = Eigen::VectorXd::Ones(modelPX.nv);\n  Eigen::VectorXd tauPrismaticUnaligned = Eigen::VectorXd::Ones(modelPrismaticUnaligned.nv);\n  Eigen::VectorXd aPX = Eigen::VectorXd::Ones(modelPX.nv);\n  Eigen::VectorXd aPrismaticUnaligned(aPX);\n  \n  forwardKinematics(modelPX, dataPX, q, v);\n  forwardKinematics(modelPrismaticUnaligned, dataPrismaticUnaligned, q, v);\n\n  computeAllTerms(modelPX, dataPX, q, v);\n  computeAllTerms(modelPrismaticUnaligned, dataPrismaticUnaligned, q, v);\n\n  BOOST_CHECK(dataPrismaticUnaligned.oMi[1].isApprox(dataPX.oMi[1]));\n  BOOST_CHECK(dataPrismaticUnaligned.liMi[1].isApprox(dataPX.liMi[1]));\n  BOOST_CHECK(dataPrismaticUnaligned.Ycrb[1].matrix().isApprox(dataPX.Ycrb[1].matrix()));\n  BOOST_CHECK(dataPrismaticUnaligned.f[1].toVector().isApprox(dataPX.f[1].toVector()));\n  \n  BOOST_CHECK(dataPrismaticUnaligned.nle.isApprox(dataPX.nle));\n  BOOST_CHECK(dataPrismaticUnaligned.com[0].isApprox(dataPX.com[0]));\n\n  // InverseDynamics == rnea\n  tauPX = rnea(modelPX, dataPX, q, v, aPX);\n  tauPrismaticUnaligned = rnea(modelPrismaticUnaligned, dataPrismaticUnaligned, q, v, aPrismaticUnaligned);\n\n  BOOST_CHECK(tauPX.isApprox(tauPrismaticUnaligned));\n\n  // ForwardDynamics == aba\n  Eigen::VectorXd aAbaPX = aba(modelPX,dataPX, q, v, tauPX);\n  Eigen::VectorXd aAbaPrismaticUnaligned = aba(modelPrismaticUnaligned,dataPrismaticUnaligned, q, v, tauPrismaticUnaligned);\n\n  BOOST_CHECK(aAbaPX.isApprox(aAbaPrismaticUnaligned));\n\n  // crba\n  crba(modelPX, dataPX,q);\n  crba(modelPrismaticUnaligned, dataPrismaticUnaligned, q);\n\n  BOOST_CHECK(dataPX.M.isApprox(dataPrismaticUnaligned.M));\n   \n  // Jacobian\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobianPX;jacobianPX.resize(6,1); jacobianPX.setZero();\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobianPrismaticUnaligned;jacobianPrismaticUnaligned.resize(6,1);jacobianPrismaticUnaligned.setZero();\n  computeJointJacobians(modelPX, dataPX, q);\n  computeJointJacobians(modelPrismaticUnaligned, dataPrismaticUnaligned, q);\n  getJointJacobian(modelPX, dataPX, 1, LOCAL, jacobianPX);\n  getJointJacobian(modelPrismaticUnaligned, dataPrismaticUnaligned, 1, LOCAL, jacobianPrismaticUnaligned);\n\n  BOOST_CHECK(jacobianPX.isApprox(jacobianPrismaticUnaligned));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "fab0e0f33f4dec9c98a4feabb6d87361b96c8f6b", "size": 9488, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/joint-prismatic.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/joint-prismatic.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/joint-prismatic.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": 30.9055374593, "max_line_length": 146, "alphanum_fraction": 0.725653457, "num_tokens": 2758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5170770276443708}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n/// \\file\n/// Defines helper functions for converting between `DataVector`s and boost\n/// quaternions.\n\n#pragma once\n\n#include \"DataStructures/BoostMultiArray.hpp\"\n\n#include <boost/math/quaternion.hpp>\n#include <boost/numeric/odeint.hpp>\n\n#include \"DataStructures/DataVector.hpp\"\n\n/// \\cond\nnamespace gsl {\ntemplate <class T>\nclass not_null;\n}  // namespace gsl\n/// \\endcond\n\n/// Convert a `boost::math::quaternion` to a `DataVector`\nDataVector quaternion_to_datavector(\n    const boost::math::quaternion<double>& input);\n\n/// \\brief Convert a `DataVector` to a `boost::math::quaternion`\n///\n/// \\details To convert to a quaternion, a `DataVector` must have either 3 or 4\n/// components. If it has 3 components, the quaternion will be constructed with\n/// 0 scalar part while the vector part is the `DataVector`. If the `DataVector`\n/// has 4 components, the quaternion is just the `DataVector` itself.\nboost::math::quaternion<double> datavector_to_quaternion(\n    const DataVector& input);\n\n/// Normalize a `boost::math::quaternion`\nvoid normalize_quaternion(\n    gsl::not_null<boost::math::quaternion<double>*> input);\n\n// Necessary for odeint to be able to integrate boost quaternions\nnamespace boost::numeric::odeint {\ntemplate <>\nstruct vector_space_norm_inf<boost::math::quaternion<double>> {\n  using result_type = double;\n  result_type operator()(const boost::math::quaternion<double>& q) const {\n    return sup(q);\n  }\n};\n}  // namespace boost::numeric::odeint\n", "meta": {"hexsha": "1b62ff88fe63e286ee7ad7a4b232a275c090811a", "size": 1540, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Domain/FunctionsOfTime/QuaternionHelpers.hpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 117.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T22:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:23:36.000Z", "max_issues_repo_path": "src/Domain/FunctionsOfTime/QuaternionHelpers.hpp", "max_issues_repo_name": "GitHimanshuc/spectre", "max_issues_repo_head_hexsha": "4de4033ba36547113293fe4dbdd77591485a4aee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3177.0, "max_issues_repo_issues_event_min_datetime": "2017-04-07T21:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:59.000Z", "max_forks_repo_path": "src/Domain/FunctionsOfTime/QuaternionHelpers.hpp", "max_forks_repo_name": "geoffrey4444/spectre", "max_forks_repo_head_hexsha": "9350d61830b360e2d5b273fdd176dcc841dbefb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2017-04-07T19:36:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T10:21:00.000Z", "avg_line_length": 30.1960784314, "max_line_length": 80, "alphanum_fraction": 0.7350649351, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5170770225949708}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include <iomanip>\n#include <string>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nvoid eigs_sym_F77(MatrixXd &M, VectorXd &init_resid, int k, int m, double &time_used, double &prec_err, int &nops);\nvoid eigs_gen_F77(MatrixXd &M, VectorXd &init_resid, int k, int m, double &time_used, double &prec_err, int &nops);\nvoid eigs_sym_Cpp(MatrixXd &M, VectorXd &init_resid, int k, int m, double &time_used, double &prec_err, int &nops);\nvoid eigs_gen_Cpp(MatrixXd &M, VectorXd &init_resid, int k, int m, double &time_used, double &prec_err, int &nops);\n\nvoid print_header(std::string title)\n{\n    const int width = 80;\n    const char sep = ' ';\n\n    std::cout << std::endl\n              << std::string(width, '=') << std::endl;\n    std::cout << std::string((width - title.length()) / 2, ' ') << title << std::endl;\n    std::cout << std::string(width, '-') << std::endl;\n\n    std::cout << std::left << std::setw(7) << std::setfill(sep) << \"size\";\n    std::cout << std::left << std::setw(10) << std::setfill(sep) << \"dataset\";\n    std::cout << std::left << std::setw(11) << std::setfill(sep) << \"F77/time\";\n    std::cout << std::left << std::setw(13) << std::setfill(sep) << \"error\";\n    std::cout << std::left << std::setw(7) << std::setfill(sep) << \"nops\";\n    std::cout << std::left << std::setw(11) << std::setfill(sep) << \"C++/time\";\n    std::cout << std::left << std::setw(13) << std::setfill(sep) << \"error\";\n    std::cout << std::left << std::setw(7) << std::setfill(sep) << \"nops\";\n    std::cout << std::endl;\n\n    std::cout << std::string(width, '-') << std::endl;\n}\n\nvoid print_row(int n, int dataset,\n               double time_f77, double err_f77, int nops_f77,\n               double time_cpp, double err_cpp, int nops_cpp)\n{\n    const char sep = ' ';\n\n    std::cout.precision(5);\n\n    std::cout << std::left << std::setw(7) << std::setfill(sep) << n;\n    std::cout << std::left << std::setw(10) << std::setfill(sep) << dataset;\n    std::cout << std::left << std::setw(11) << std::setfill(sep) << time_f77;\n    std::cout << std::left << std::setw(13) << std::setfill(sep) << err_f77;\n    std::cout << std::left << std::setw(7) << std::setfill(sep) << nops_f77;\n    std::cout << std::left << std::setw(11) << std::setfill(sep) << time_cpp;\n    std::cout << std::left << std::setw(13) << std::setfill(sep) << err_cpp;\n    std::cout << std::left << std::setw(7) << std::setfill(sep) << nops_cpp;\n    std::cout << std::endl;\n}\n\nvoid print_footer()\n{\n    const int width = 80;\n    std::cout << std::string(width, '=') << std::endl\n              << std::endl;\n}\n\nvoid run_eigs_sym(int n_experiment, int n_replicate, int n, int k, int m)\n{\n    double time_f77, time_cpp;\n    double err_f77, err_cpp;\n    int nops_f77, nops_cpp;\n\n    for (int i = 0; i < n_experiment; i++)\n    {\n        MatrixXd A = MatrixXd::Random(n, n);\n        MatrixXd M = A.transpose() + A;\n\n        VectorXd init_resid = VectorXd::Random(M.cols());\n        init_resid.array() -= 0.5;\n        init_resid = M * init_resid;\n\n        for (int j = 0; j < n_replicate; j++)\n        {\n            eigs_sym_F77(M, init_resid, k, m, time_f77, err_f77, nops_f77);\n            eigs_sym_Cpp(M, init_resid, k, m, time_cpp, err_cpp, nops_cpp);\n            print_row(n, i + 1, time_f77, err_f77, nops_f77, time_cpp, err_cpp, nops_cpp);\n        }\n    }\n}\n\nvoid run_eigs_gen(int n_experiment, int n_replicate, int n, int k, int m)\n{\n    double time_f77, time_cpp;\n    double err_f77, err_cpp;\n    int nops_f77, nops_cpp;\n\n    for (int i = 0; i < n_experiment; i++)\n    {\n        MatrixXd A = MatrixXd::Random(n, n);\n\n        VectorXd init_resid = VectorXd::Random(A.cols());\n        init_resid.array() -= 0.5;\n        init_resid = A * init_resid;\n\n        for (int j = 0; j < n_replicate; j++)\n        {\n            eigs_gen_F77(A, init_resid, k, m, time_f77, err_f77, nops_f77);\n            eigs_gen_Cpp(A, init_resid, k, m, time_cpp, err_cpp, nops_cpp);\n            print_row(n, i + 1, time_f77, err_f77, nops_f77, time_cpp, err_cpp, nops_cpp);\n        }\n    }\n}\n\nint main()\n{\n    std::srand(123);\n    int n_experiment = 5;\n    int n_replicate = 10;\n\n    print_header(\"eigs_sym\");\n    run_eigs_sym(n_experiment, n_replicate, 100, 10, 20);\n    run_eigs_sym(n_experiment, n_replicate, 1000, 10, 30);\n    print_footer();\n\n    print_header(\"eigs_gen\");\n    run_eigs_gen(n_experiment, n_replicate, 100, 10, 20);\n    run_eigs_gen(n_experiment, n_replicate, 1000, 10, 30);\n    print_footer();\n\n    return 0;\n}\n", "meta": {"hexsha": "eb707b358c2c1aac717bbc6cf7b58d1337e5417c", "size": 4503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/benchmark/main.cpp", "max_stars_repo_name": "mushroom-x/Misc3D", "max_stars_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2022-02-09T11:56:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:45:04.000Z", "max_issues_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/benchmark/main.cpp", "max_issues_repo_name": "mushroom-x/Misc3D", "max_issues_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2022-02-26T08:58:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T11:19:05.000Z", "max_forks_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/benchmark/main.cpp", "max_forks_repo_name": "mushroom-x/Misc3D", "max_forks_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2022-02-16T06:59:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:03:11.000Z", "avg_line_length": 35.1796875, "max_line_length": 115, "alphanum_fraction": 0.5922718188, "num_tokens": 1466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5170770205273791}}
{"text": "#include <gtest/gtest.h>\n#include <Eigen/Dense>\n#include <EigenRand/EigenRand>\n\ntemplate <class T>\nclass ContinuousDistTest : public testing::Test\n{\n};\n\nusing ETypes = testing::Types<float, double>;\n\nTYPED_TEST_CASE(ContinuousDistTest, ETypes);\n\nTYPED_TEST(ContinuousDistTest, balanced)\n{\n\tusing Matrix = Eigen::Matrix<TypeParam, -1, -1>;\n\tEigen::Rand::Vmt19937_64 gen{ 42 };\n\tMatrix mat;\n\n\tmat = Eigen::Rand::balanced<Matrix>(8, 8, gen);\n\tmat = Eigen::Rand::balanced<Matrix>(3, 3, gen);\n\tmat = Eigen::Rand::balanced<Matrix>(5, 5, gen);\n\tstd::cout << mat << std::endl;\n}\n\nTYPED_TEST(ContinuousDistTest, balanced2)\n{\n\tusing Matrix = Eigen::Matrix<TypeParam, -1, -1>;\n\tEigen::Rand::Vmt19937_64 gen{ 42 };\n\tMatrix mat;\n\n\tmat = Eigen::Rand::balanced<Matrix>(8, 8, gen, 0.5, 2);\n\tmat = Eigen::Rand::balanced<Matrix>(3, 3, gen, 0.5, 2);\n\tmat = Eigen::Rand::balanced<Matrix>(5, 5, gen, 0.5, 2);\n\tstd::cout << mat << std::endl;\n}\n\nTYPED_TEST(ContinuousDistTest, stdNormal)\n{\n\tusing Matrix = Eigen::Matrix<TypeParam, -1, -1>;\n\tEigen::Rand::Vmt19937_64 gen{ 42 };\n\tMatrix mat;\n\n\tmat = Eigen::Rand::normal<Matrix>(8, 8, gen);\n\tmat = Eigen::Rand::normal<Matrix>(3, 3, gen);\n\tmat = Eigen::Rand::normal<Matrix>(5, 5, gen);\n\tstd::cout << mat << std::endl;\n}\n\nTYPED_TEST(ContinuousDistTest, normal)\n{\n\tusing Matrix = Eigen::Matrix<TypeParam, -1, -1>;\n\tEigen::Rand::Vmt19937_64 gen{ 42 };\n\tMatrix mat;\n\n\tmat = Eigen::Rand::normal<Matrix>(8, 8, gen, 1, 2);\n\tmat = Eigen::Rand::normal<Matrix>(3, 3, gen, 1, 2);\n\tmat = Eigen::Rand::normal<Matrix>(5, 5, gen, 1, 2);\n\tstd::cout << mat << std::endl;\n}\n\nTYPED_TEST(ContinuousDistTest, exponential)\n{\n\tusing Matrix = Eigen::Matrix<TypeParam, -1, -1>;\n\tEigen::Rand::Vmt19937_64 gen{ 42 };\n\tMatrix mat;\n\n\tmat = Eigen::Rand::exponential<Matrix>(8, 8, gen, 2);\n\tmat = Eigen::Rand::exponential<Matrix>(3, 3, gen, 2);\n\tmat = Eigen::Rand::exponential<Matrix>(5, 5, gen, 2);\n\tstd::cout << mat << std::endl;\n}\n", "meta": {"hexsha": "55e9c2ee87e67523316ac351ebf79baf22706193", "size": 1926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test.cpp", "max_stars_repo_name": "perara-libs/EigenRand", "max_stars_repo_head_hexsha": "739b95a3b81fa750cb2759cb4d31c00a7445d272", "max_stars_repo_licenses": ["MIT"], "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": "perara-libs/EigenRand", "max_issues_repo_head_hexsha": "739b95a3b81fa750cb2759cb4d31c00a7445d272", "max_issues_repo_licenses": ["MIT"], "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": "perara-libs/EigenRand", "max_forks_repo_head_hexsha": "739b95a3b81fa750cb2759cb4d31c00a7445d272", "max_forks_repo_licenses": ["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.3835616438, "max_line_length": 56, "alphanum_fraction": 0.6593977155, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.5170770124961707}}
{"text": "#include <Eigen/StdVector>\n\n#include <week_slam/g2o/edge/edge_point_on_circle.h>\n#include <week_slam/barrel_ransac.h>\n\nvoid BarrelRansac::test()\n{\n  double radius = 0.5;\n  int num_points = 10;\n\n  std::vector<Eigen::Vector2d> points;\n  points.reserve(3 * num_points);\n\n  std::uniform_real_distribution<> distribution(0, 2 * M_PI);\n  std::normal_distribution<> rad_dist(radius, 0.05);\n\n  {\n    Eigen::Vector2d center{ 1.0, 2.0 };\n    for (int i = 0; i < num_points; i++)\n    {\n      double r = rad_dist(mt_);\n      double angle = distribution(mt_);\n\n      double x = center.x() + r * cos(angle);\n      double y = center.y() + r * sin(angle);\n\n      points.emplace_back(x, y);\n    }\n  }\n\n  {\n    Eigen::Vector2d center{ 5.0, 4.0 };\n    for (int i = 0; i < num_points; i++)\n    {\n      double r = rad_dist(mt_);\n      double angle = distribution(mt_);\n\n      double x = center.x() + r * cos(angle);\n      double y = center.y() + r * sin(angle);\n\n      points.emplace_back(x, y);\n    }\n  }\n\n  {\n    Eigen::Vector2d center{ 6.2, 4.0 };\n    for (int i = 0; i < num_points; i++)\n    {\n      double r = rad_dist(mt_);\n      double angle = distribution(mt_);\n\n      double x = center.x() + r * cos(angle);\n      double y = center.y() + r * sin(angle);\n\n      points.emplace_back(x, y);\n    }\n  }\n  //  auto res = executeOnce(points);\n  //  ROS_INFO_STREAM(\"Barrel: \" << res.barrel);\n  //  for (const auto& outlier : res.outliers)\n  //  {\n  //    ROS_INFO_STREAM(\"Outliers: \" << outlier);\n  //  }\n\n  pcl::PointCloud<pcl::PointXYZ> scan;\n  scan.points.reserve(num_points);\n  for (const auto& vector : points)\n  {\n    pcl::PointXYZ p{ static_cast<float>(vector(0)), static_cast<float>(vector(1)), 0.0 };\n    scan.points.emplace_back(p);\n  }\n\n  auto before = ros::Time::now();\n  auto result = execute(scan);\n  auto after = ros::Time::now();\n  ROS_INFO_STREAM(\"Time taken: \" << (after - before).toSec() << \" seconds.\");\n\n  for (const auto& barrel : result)\n  {\n    ROS_INFO_STREAM(barrel);\n  }\n}\n\nBarrelRansac::BarrelRansac(const Options& options) : options_{ options }, mt_(std::random_device()())\n{\n  auto block_solver = std::make_unique<BlockSolver>(std::make_unique<LinearSolver>());\n  auto* solver = new g2o::OptimizationAlgorithmLevenberg(std::move(block_solver));\n  optimizer_.setAlgorithm(solver);\n}\n\nstd::vector<Barrel> BarrelRansac::execute(const pcl::PointCloud<pcl::PointXYZ>& scan)\n{\n  std::vector<Eigen::Vector2d> eigen_scan;\n  std::transform(scan.begin(), scan.end(), std::back_inserter(eigen_scan), [](const pcl::PointXYZ& point) {\n    return Eigen::Vector2d{ point.x, point.y };\n  });\n\n  return executeSequentially(std::move(eigen_scan));\n}\n\nstd::vector<Barrel> BarrelRansac::executeSequentially(std::vector<Eigen::Vector2d> scan)\n{\n  std::vector<Barrel> barrels;\n  barrels.reserve(options_.max_barrels);\n\n  while (static_cast<int>(barrels.size()) < options_.max_barrels &&\n         static_cast<int>(scan.size()) > options_.min_scan_points)\n  {\n    //    ROS_INFO_STREAM(\"Starting loop. scan.size() == \" << scan.size());\n    auto result = executeOnce(scan);\n\n//    ROS_INFO_STREAM(\"result.error: \" << result.error);\n    if (result.error > options_.max_error)\n    {\n      ROS_INFO_STREAM(\"Breaking due to error\");\n      break;\n    }\n\n    barrels.emplace_back(result.barrel);\n    scan = std::move(result.outliers);\n  }\n  //  ROS_INFO_STREAM(\"barrels.size(): \" << barrels.size() << \", scan.size(): \" << scan.size());\n  return barrels;\n}\n\nBarrelRansac::RANSACResult BarrelRansac::executeOnce(const std::vector<Eigen::Vector2d>& scan)\n{\n  //  ROS_INFO_STREAM(\"Starting <fn executeOnce>\");\n  std::vector<Eigen::Vector2d> copy = scan;\n  int num_points = scan.size();\n\n  Barrel best_barrel;\n  std::vector<Eigen::Vector2d> best_outliers;\n  double best_err = std::numeric_limits<double>::max();\n\n  for (int i = 0; i < options_.iterations; i++)\n  {\n    std::vector<Eigen::Vector2d> inliers;\n    inliers.reserve(scan.size());\n    std::vector<Eigen::Vector2d> outliers;\n    outliers.reserve(scan.size());\n\n    std::shuffle(copy.begin(), copy.end(), mt_);\n    inliers.emplace_back(copy[0]);\n    inliers.emplace_back(copy[1]);\n    inliers.emplace_back(copy[2]);\n\n    Barrel barrel = fitToBarrel(copy[0], copy[1], copy[2]);\n\n    // Found barrel must have radius between min and max radius\n    if (barrel(2) < options_.min_barrel_radius || barrel(2) > options_.max_barrel_radius)\n    {\n      continue;\n    }\n\n    // Points must be in forward facing half of the circle\n    if (!inForwardHalf(barrel, copy[0], copy[1], copy[2]))\n    {\n      continue;\n    }\n\n    for (int j = 3; j < static_cast<int>(copy.size()); j++)\n    {\n      if (residual(barrel, copy[j]) < options_.threshold)\n      {\n        inliers.emplace_back(copy[j]);\n      }\n      else\n      {\n        outliers.emplace_back(copy[j]);\n      }\n    }\n\n    //    barrel = fitToBarrel(barrel, inliers);\n    double error = residual(barrel, inliers);\n    if (error < best_err)\n    {\n      best_barrel = barrel;\n      best_outliers = std::move(outliers);\n      best_err = error;\n    }\n  }\n\n  //  ROS_INFO_STREAM(\"done with <fn executeOnce>\");\n//  ROS_INFO_STREAM(\"Scan size: \" << scan.size() << \", inliers: \" << scan.size() - best_outliers.size());\n  return { best_barrel, std::move(best_outliers), best_err };\n}\n\nBarrel BarrelRansac::fitToBarrel(const Eigen::Vector2d& p1, const Eigen::Vector2d& p2, const Eigen::Vector2d& p3) const\n{\n  auto x1 = p1(0);\n  auto y1 = p1(1);\n  auto x2 = p2(0);\n  auto y2 = p2(1);\n  auto x3 = p3(0);\n  auto y3 = p3(1);\n\n  auto a = x1 * (y2 - y3) - y1 * (x2 - x3) + x2 * y3 - x3 * y2;\n\n  auto b = (x1 * x1 + y1 * y1) * (y3 - y2) + (x2 * x2 + y2 * y2) * (y1 - y3) + (x3 * x3 + y3 * y3) * (y2 - y1);\n\n  auto c = (x1 * x1 + y1 * y1) * (x2 - x3) + (x2 * x2 + y2 * y2) * (x3 - x1) + (x3 * x3 + y3 * y3) * (x1 - x2);\n\n  auto x = -b / (2 * a);\n  auto y = -c / (2 * a);\n  auto r = std::hypot(x - x1, y - y1);\n\n  return { x, y, r };\n}\n\nBarrel BarrelRansac::fitToBarrel(const Barrel& estimate, const std::vector<Eigen::Vector2d>& inliers)\n{\n  auto* circle = new VertexCircle();\n  circle->setId(0);\n  circle->setEstimate(estimate);\n  optimizer_.addVertex(circle);\n\n  for (const auto& inlier : inliers)\n  {\n    auto* edge = new EdgePointOnCircle;\n    edge->setInformation(Eigen::Matrix<double, 1, 1>::Identity());\n    edge->setVertex(0, circle);\n    edge->setMeasurement(inlier);\n    optimizer_.addEdge(edge);\n  }\n\n  optimizer_.initializeOptimization();\n  optimizer_.optimize(100);\n\n  Barrel output = circle->estimate();\n  optimizer_.clear();\n\n  return output;\n}\n\ndouble BarrelRansac::residual(const Barrel& barrel, const Eigen::Vector2d& point) const\n{\n  double d = (barrel.head<2>() - point).norm() - barrel(2);\n  return d * d;\n}\n\ndouble BarrelRansac::residual(const Barrel& barrel, const std::vector<Eigen::Vector2d>& points) const\n{\n  double acc = 0.0;\n  for (const auto& point : points)\n  {\n    acc += residual(barrel, point);\n  }\n  return acc / points.size();\n}\n\nbool BarrelRansac::inForwardHalf(const Barrel& barrel, const Eigen::Vector2d& p1, const Eigen::Vector2d& p2,\n                                 const Eigen::Vector2d& p3) const\n{\n  double barrel_theta = atan2(barrel(1), barrel(0));\n\n  for (const auto& p : std::vector<Eigen::Vector2d>{ p1, p2, p3 })\n  {\n    double theta = atan2(p(1) - barrel(1), p(0) - barrel(0));\n    double rotated_theta = BarrelRansac::normalizeAngle(theta - barrel_theta - (M_PI / 2));\n\n    if (rotated_theta < 0)\n    {\n      return false;\n    }\n  }\n\n  return true;\n}\n\ndouble BarrelRansac::normalizeAngle(double angle)\n{\n  return -M_PI + fmod(2 * M_PI + fmod(angle + M_PI, 2 * M_PI), 2 * M_PI);\n}\n", "meta": {"hexsha": "42daa478d968bdc2e262ed0da395b88adf50fed1", "size": 7591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igvc_training_exercises/src/week_slam/barrel_ransac.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_slam/barrel_ransac.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_slam/barrel_ransac.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": 27.6036363636, "max_line_length": 119, "alphanum_fraction": 0.6221841655, "num_tokens": 2297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5170639892870817}}
{"text": "/*!\n * @file loudness_test.cpp\n *\n * @author Andrzej Ciarkowski <mailto:andrzej.ciarkowski@gmail.com>\n */\n\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp> \n\n#include <dsp++/snd/loudness.h>\n#include <dsp++/snd/reader.h>\n#include <dsp++/float.h>\n#include <fstream>\n\nstatic void test_loudness_file(const char* path, float exp_level, float peak) \n{\n\tusing namespace dsp::snd;\n\treader r;\n\tr.open(path);\n\n\tstd::string dump(path);\n\tdump += \".raw\";\n\tstd::ofstream d(dump, std::ios_base::binary | std::ios_base::out);\n\n\tloudness_ebu<float> met(r.sample_rate(), r.channel_count());\n\tloudness_peak<float> metp(static_cast<unsigned>(r.sample_rate() * .1 +.5), 5);\n\n\tstd::vector<float> buf;\n\tconst size_t len = 9600;\n\tbuf.resize(r.channel_count() * len);\n\tfloat vm = 0, vs = 0, vi = 0, vp = 0;\n\twhile (true) {\n\t\tfloat* x = &buf[0];\n\t\tsize_t read = r.read_frames(x, len);\n\n\t\tfor (size_t i = 0; i < read; ++i, x += r.channel_count()) {\n\t\t\tif (met.next_frame(x)) {\n\t\t\t\tvm = met.value_m();\n\t\t\t\tvs = met.value_s();\n\t\t\t\tvi = met.value_i();\n\t\t\t\td.write((char*)(&vm), 4);\n\t\t\t\td.write((char*)(&vs), 4);\n\t\t\t\td.write((char*)(&vi), 4);\n\t\t\t}\n\t\t\tmetp(*x);\n\t\t}\n\t\tif (read != len)\n\t\t\tbreak;\n\t}\n\n\tvi = met.value_i();\n\tvp = metp.value_db();\n\tBOOST_CHECK(dsp::within_range<float>(.1f)(vi,exp_level));\n\tBOOST_CHECK(dsp::within_range<float>(.1f)(vp,peak));\n}\n\nBOOST_AUTO_TEST_SUITE(loudness)\n\nBOOST_AUTO_TEST_CASE(ebu1)\n{\n\ttest_loudness_file(\"data/coil.wav\", -11.6f, -.3f);\n\ttest_loudness_file(\"data/ebu_testcase1_-23dBFS.wav\", -23.f, -22.8f);\n\ttest_loudness_file(\"data/ebu_testcase2_-33dBFS.wav\", -33.f, -32.8f);\n\ttest_loudness_file(\"data/ebu_testcase5_-23dBFS.wav\", -23.f, -19.8f);\n}\n\nBOOST_AUTO_TEST_CASE(peak)\n{\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "cc1871de9fc3734212824edff2584176cdf89532", "size": 1758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dsp++/test/loudness_test.cpp", "max_stars_repo_name": "andrzejc/dsp-", "max_stars_repo_head_hexsha": "fd39d2395a37ade36e3b551d261de0177b78296b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dsp++/test/loudness_test.cpp", "max_issues_repo_name": "andrzejc/dsp-", "max_issues_repo_head_hexsha": "fd39d2395a37ade36e3b551d261de0177b78296b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dsp++/test/loudness_test.cpp", "max_forks_repo_name": "andrzejc/dsp-", "max_forks_repo_head_hexsha": "fd39d2395a37ade36e3b551d261de0177b78296b", "max_forks_repo_licenses": ["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.4166666667, "max_line_length": 79, "alphanum_fraction": 0.6615472127, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5170639830673164}}
{"text": "/*\n * SimpleFeatures.cpp\n * This creates features on the netflow features without any\n * operators added in.\n * The base netflow features are:\n * 1) duration\n * 2) source app bytes\n * 3) dest app bytes\n * 4) source total bytes\n * 5) dest total bytes\n * 6) source packets\n * 7) dest packets \n * \n * The types of features created are\n * 1) average \n * 2) variance\n *  Created on: March 15, 2017\n *      Author: elgood\n */\n\n#include <string>\n#include <vector>\n#include <stdlib.h>\n#include <iostream>\n#include <chrono>\n\n#include <boost/program_options.hpp>\n\n#include <sam/VastNetflow.hpp>\n#include <sam/sam.hpp>\n\nusing std::string;\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\nnamespace po = boost::program_options;\n\nusing namespace sam;\nusing namespace std::chrono;\n\ntypedef TupleStringHashFunction<VastNetflow, SourceIp> SourceHash;\ntypedef TupleStringHashFunction<VastNetflow, DestIp> TargetHash;\ntypedef ZeroMQPushPull<VastNetflow, VastNetflowTuplizer, SourceHash, TargetHash>\n        PartitionType;\ntypedef ReadCSV<VastNetflow, VastNetflowTuplizer> ReadCSVType;\n\n//zmq::context_t context(1);\n\nvoid createPipeline(\n                 std::shared_ptr<ReadCSVType> readCSV,\n                 std::shared_ptr<FeatureMap> featureMap,\n                 std::shared_ptr<FeatureSubscriber> subscriber,\n                 std::shared_ptr<PartitionType> pushpull,\n                 std::size_t queueLength,\n                 std::size_t numNodes,\n                 std::size_t nodeId,\n                 std::vector<std::string> const& hostnames,\n                 std::size_t hwm,\n                 std::size_t N,\n                 std::size_t b,\n                 std::size_t k)\n{\n  // An operator to get the label from each netflow and add it to the\n  // subscriber.\n  string identifier = \"label\";\n\n  // Doesn't really need a key, but provide one anyway to the template.\n  auto label = std::make_shared<Identity<VastNetflow, SamLabel, DestIp>>\n                (nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(label);\n  } else {\n    pushpull->registerConsumer(label);\n  }\n  if (subscriber != NULL) {\n    label->registerSubscriber(subscriber, identifier); \n  }\n\n\n  /** Dest Ip as key **/\n  identifier = \"averageSrcTotalBytes\";\n  auto averageSrcTotalBytes = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 SrcTotalBytes,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageSrcTotalBytes);\n  } else {\n    pushpull->registerConsumer(averageSrcTotalBytes);\n  }\n  if (subscriber != NULL) {\n    averageSrcTotalBytes->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varSrcTotalBytes\";\n  auto varSrcTotalBytes = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 SrcTotalBytes,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varSrcTotalBytes);\n  } else {\n    pushpull->registerConsumer(varSrcTotalBytes);\n  }\n  if (subscriber != NULL) {\n    varSrcTotalBytes->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"averageDestTotalBytes\";\n  auto averageDestTotalBytes = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 DestTotalBytes,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageDestTotalBytes);\n  } else {\n    pushpull->registerConsumer(averageDestTotalBytes);\n  }\n  if (subscriber != NULL) {\n    averageDestTotalBytes->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varDestTotalBytes\";\n  auto varDestTotalBytes = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 DestTotalBytes,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varDestTotalBytes);\n  } else {\n    pushpull->registerConsumer(varDestTotalBytes);\n  }\n  if (subscriber != NULL) {\n    varDestTotalBytes->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"averageDuration\";\n  auto averageDuration = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 DurationSeconds,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageDuration);\n  } else {\n    pushpull->registerConsumer(averageDuration);\n  }\n  if (subscriber != NULL) {\n    averageDuration->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varDuration\";\n  auto varDuration = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 DurationSeconds,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varDuration);\n  } else {\n    pushpull->registerConsumer(varDuration);\n  }\n  if (subscriber != NULL) {\n    varDuration->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"averageSrcPayloadBytes\";\n  auto averageSrcPayloadBytes = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 SrcPayloadBytes,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageSrcPayloadBytes);\n  } else {\n    pushpull->registerConsumer(averageSrcPayloadBytes);\n  }\n  if (subscriber != NULL) {\n    averageSrcPayloadBytes->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varSrcPayloadBytes\";\n  auto varSrcPayloadBytes = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 SrcPayloadBytes,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varSrcPayloadBytes);\n  } else {\n    pushpull->registerConsumer(varSrcPayloadBytes);\n  }\n  if (subscriber != NULL) {\n    varSrcPayloadBytes->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"averageDestPayloadBytes\";\n  auto averageDestPayloadBytes = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 DestPayloadBytes,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageDestPayloadBytes);\n  } else {\n    pushpull->registerConsumer(averageDestPayloadBytes);\n  }\n  if (subscriber != NULL) {\n    averageDestPayloadBytes->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varDestPayloadBytes\";\n  auto varDestPayloadBytes = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 DestPayloadBytes,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varDestPayloadBytes);\n  } else {\n    pushpull->registerConsumer(varDestPayloadBytes);\n  }\n  if (subscriber != NULL) {\n    varDestPayloadBytes->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"averageSrcPacketCount\";\n  auto averageSrcPacketCount = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 FirstSeenSrcPacketCount,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageSrcPacketCount);\n  } else {\n    pushpull->registerConsumer(averageSrcPacketCount);\n  }\n  if (subscriber != NULL) {\n    averageSrcPacketCount->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varSrcPacketCount\";\n  auto varSrcPacketCount = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 FirstSeenSrcPacketCount,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varSrcPacketCount);\n  } else {\n    pushpull->registerConsumer(varSrcPacketCount);\n  }\n  if (subscriber != NULL) {\n    varSrcPacketCount->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"averageDestPacketCount\";\n  auto averageDestPacketCount = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 FirstSeenDestPacketCount,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageDestPacketCount);\n  } else {\n    pushpull->registerConsumer(averageDestPacketCount);\n  }\n  if (subscriber != NULL) {\n    averageDestPacketCount->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varDestPacketCount\";\n  auto varDestPacketCount = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 FirstSeenDestPacketCount,\n                                                 DestIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varDestPacketCount);\n  } else {\n    pushpull->registerConsumer(varDestPacketCount);\n  }\n  if (subscriber != NULL) {\n    varDestPacketCount->registerSubscriber(subscriber, identifier);\n  }\n\n  /** SourceIp as key **/\n  identifier = \"averageSrcTotalBytesSourceIp\";\n  auto averageSrcTotalBytesSourceIp = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 SrcTotalBytes,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageSrcTotalBytesSourceIp);\n  } else {\n    pushpull->registerConsumer(averageSrcTotalBytesSourceIp);\n  }\n  if (subscriber != NULL) {\n    averageSrcTotalBytesSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varSrcTotalBytesSourceIp\";\n  auto varSrcTotalBytesSourceIp = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 SrcTotalBytes,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varSrcTotalBytesSourceIp);\n  } else {\n    pushpull->registerConsumer(varSrcTotalBytesSourceIp);\n  }\n  if (subscriber != NULL) {\n    varSrcTotalBytesSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"averageDestTotalBytesSourceIp\";\n  auto averageDestTotalBytesSourceIp = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 DestTotalBytes,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageDestTotalBytesSourceIp);\n  } else {\n    pushpull->registerConsumer(averageDestTotalBytesSourceIp);\n  }\n  if (subscriber != NULL) {\n    averageDestTotalBytesSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varDestTotalBytesSourceIp\";\n  auto varDestTotalBytesSourceIp = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 DestTotalBytes,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varDestTotalBytesSourceIp);\n  } else {\n    pushpull->registerConsumer(varDestTotalBytesSourceIp);\n  }\n  if (subscriber != NULL) {\n    varDestTotalBytesSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"averageDurationSourceIp\";\n  auto averageDurationSourceIp = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 DurationSeconds,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageDurationSourceIp);\n  } else {\n    pushpull->registerConsumer(averageDurationSourceIp);\n  }\n  if (subscriber != NULL) {\n    averageDurationSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varDurationSourceIp\";\n  auto varDurationSourceIp = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 DurationSeconds,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varDurationSourceIp);\n  } else {\n    pushpull->registerConsumer(varDurationSourceIp);\n  }\n  if (subscriber != NULL) {\n    varDurationSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"averageSrcPayloadBytesSourceIp\";\n  auto averageSrcPayloadBytesSourceIp = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 SrcPayloadBytes,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageSrcPayloadBytesSourceIp);\n  } else {\n    pushpull->registerConsumer(averageSrcPayloadBytesSourceIp);\n  }\n  if (subscriber != NULL) {\n    averageSrcPayloadBytesSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varSrcPayloadBytesSourceIp\";\n  auto varSrcPayloadBytesSourceIp = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 SrcPayloadBytes,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varSrcPayloadBytesSourceIp);\n  } else {\n    pushpull->registerConsumer(varSrcPayloadBytesSourceIp);\n  }\n  if (subscriber != NULL) {\n    varSrcPayloadBytesSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"averageDestPayloadBytesSourceIp\";\n  auto averageDestPayloadBytesSourceIp = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 DestPayloadBytes,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageDestPayloadBytesSourceIp);\n  } else {\n    pushpull->registerConsumer(averageDestPayloadBytesSourceIp);\n  }\n  if (subscriber != NULL) {\n    averageDestPayloadBytesSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varDestPayloadBytesSourceIp\";\n  auto varDestPayloadBytesSourceIp = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 DestPayloadBytes,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varDestPayloadBytesSourceIp);\n  } else {\n    pushpull->registerConsumer(varDestPayloadBytesSourceIp);\n  }\n  if (subscriber != NULL) {\n    varDestPayloadBytesSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"averageSrcPacketCountSourceIp\";\n  auto averageSrcPacketCountSourceIp = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 FirstSeenSrcPacketCount,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageSrcPacketCountSourceIp);\n  } else {\n    pushpull->registerConsumer(averageSrcPacketCountSourceIp);\n  }\n  if (subscriber != NULL) {\n    averageSrcPacketCountSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varSrcPacketCountSourceIp\";\n  auto varSrcPacketCountSourceIp = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 FirstSeenSrcPacketCount,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varSrcPacketCountSourceIp);\n  } else {\n    pushpull->registerConsumer(varSrcPacketCountSourceIp);\n  }\n  if (subscriber != NULL) {\n    varSrcPacketCountSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"averageDestPacketCountSourceIp\";\n  auto averageDestPacketCountSourceIp = std::make_shared<\n                      ExponentialHistogramAve<double, VastNetflow,\n                                                 FirstSeenDestPacketCount,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(averageDestPacketCountSourceIp);\n  } else {\n    pushpull->registerConsumer(averageDestPacketCountSourceIp);\n  }\n  if (subscriber != NULL) {\n    averageDestPacketCountSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n  identifier = \"varDestPacketCountSourceIp\";\n  auto varDestPacketCountSourceIp = std::make_shared<\n                      ExponentialHistogramVariance<double, VastNetflow,\n                                                 FirstSeenDestPacketCount,\n                                                 SourceIp>>\n                          (N, 2, nodeId, featureMap, identifier);\n  if (readCSV != NULL) {\n    readCSV->registerConsumer(varDestPacketCountSourceIp);\n  } else {\n    pushpull->registerConsumer(varDestPacketCountSourceIp);\n  }\n  if (subscriber != NULL) {\n    varDestPacketCountSourceIp->registerSubscriber(subscriber, identifier);\n  }\n\n}\n\nint main(int argc, char** argv) {\n\n  string ip; ///> The ip to read the nc data from.\n  std::size_t ncPort; ///> The port to read the nc data from.\n  std::size_t numNodes; ///> The number of nodes in the cluster\n  std::size_t nodeId; ///> The node id of this node\n  string prefix; ///> The prefix to the nodes\n  std::size_t startingPort; ///> The starting port number\n  std::size_t hwm; ///> The high-water mark (zeromq parameter)\n  std::size_t queueLength; ///> The length of the input queue\n  std::size_t N; ///> The total number of elements in a sliding window\n  std::size_t b; ///> The number of elements in a dormant or active window\n  std::size_t k; ///> The number of elements to keep track of\n  std::size_t nop; //not used\n  string inputfile = \"\";\n  string outputfile = \"\";\n  std::size_t capacity = 10000;////> Capacity of FeatureMap and subscriber\n\n  // The training data if learning the classifier\n  //arma::mat trainingData;\n\n  // The model that can be trained from example data or if a trained model\n  // exists, can be loaded from the filesystem.\n  //NBCModel model;\n\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help\", \"help message\")\n    (\"ip\", po::value<string>(&ip)->default_value(\"localhost\"), \n      \"The ip to receive the data from nc\")\n    (\"ncPort\", po::value<std::size_t>(&ncPort)->default_value(9999), \n      \"The port to receive the data from nc\")\n    (\"numNodes\", po::value<std::size_t>(&numNodes)->default_value(1), \n      \"The number of nodes involved in the computation\")\n    (\"nodeId\", po::value<std::size_t>(&nodeId)->default_value(0), \n      \"The node id of this node\")\n    (\"prefix\", po::value<string>(&prefix)->default_value(\"node\"), \n      \"The prefix common to all nodes\")\n    (\"startingPort\", po::value<std::size_t>(&startingPort)->default_value(\n      10000),  \"The starting port for the zeromq communications\")\n    (\"hwm\", po::value<std::size_t>(&hwm)->default_value(10000), \n      \"The high water mark (how many items can queue up before we start \"\n      \"dropping)\")\n    (\"queueLength\", po::value<std::size_t>(&queueLength)->default_value(10000),\n      \"We fill a queue before sending things in parallel to all consumers.\"\n      \"  This controls the size of that queue.\")\n    (\"N\", po::value<std::size_t>(&N)->default_value(10000),\n      \"The total number of elements in a sliding window\")\n    (\"b\", po::value<std::size_t>(&b)->default_value(1000),\n      \"The number of elements per block (active or dynamic window)\")\n    (\"nop\", po::value<std::size_t>(&nop)->default_value(1),\n      \"The number of simultaneous operators\")\n    (\"create_features\", \"If specified, will read a netflow feature file \"\n     \"from --inputfile and output to --outputfile a csv feature file\")\n    (\"train\", \"If specified, will read a csv feature file from --inputfile\"\n     \" and output to --outputfile a learned model.\")\n    (\"test\", \"If specified, will read a learned model from --inputfile\"\n     \" and apply it to the data.\")\n    (\"inputfile\", po::value<string>(&inputfile),\n      \"If --create_features is specified, the input should be a file with\"\n      \" netflow.  If --train is specified, the input should be a csv file\"\n      \" of features (the output of --create_features).  If --test is specified,\"\n      \" the input should be a model (the output of --train).\")\n    (\"outputfile\", po::value<string>(&outputfile),\n      \"If --create_features is specified, the produced file will be a csv\"\n      \" file of features.  If --train is specified, the produced file will be\"\n      \" a learned model.\")\n    (\"capacity\", po::value<std::size_t>(&capacity)->default_value(10000),\n      \"The capacity of the FeatureMap and FeatureSubcriber\")\n  ;\n\n  // Parse the command line variables\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);\n\n  // Print out the help and exit if --help was specified.\n  if (vm.count(\"help\")) {\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  vector<string> hostnames(numNodes); // A vector of hosts in the cluster\n\n  if (numNodes == 1) { // Case when we are operating on one node\n    hostnames[0] = \"127.0.0.1\";\n  } else {\n    for (int i = 0; i < numNodes; i++) {\n      // Assumes all the host names can be composed by adding prefix with\n      // [0,numNodes).\n      hostnames[i] = prefix + boost::lexical_cast<string>(i);\n\n    }\n  }\n\n  // The global featureMap (global for all features generated for this node;\n  // each node has it's own featuremap.\n  std::cout << \"About to create feature Map \" << std::endl;\n  auto featureMap = std::make_shared<FeatureMap>(capacity);\n\n  \n  /********************** Creating features ******************************/\n  if (vm.count(\"create_features\")) \n  {\n    if (inputfile == \"\") {\n      std::cout << \"--create_features was specified but no input file\"\n                << \" was listed with --inputfile.\" << std::endl;\n      return -1; \n    }\n    if (outputfile == \"\") {\n      std::cout << \"--create_features was specified but no output file\"\n                << \" was listed with --outputfile.\" << std::endl;\n      return -1; \n    }\n    \n    // We read the netflow data from a file.  It assumes each netflow \n    // has a label at the beginning.\n    auto receiver = std::make_shared<ReadCSVType>(inputfile);\n\n    // subscriber collects the features for each netflow\n    auto subscriber = std::make_shared<FeatureSubscriber>(outputfile, capacity);\n\n    std::cout << \"Creating Pipeline \" << std::endl;\n    // createPipeline creates all the operators and ties them together.  It \n    // also notifies the designated feature producers of the subscriber.\n    createPipeline(receiver, featureMap, subscriber, NULL, \n                   queueLength,\n                   numNodes,\n                   nodeId,\n                   hostnames,\n                   hwm,\n                   N, b, k);\n   \n    std::cout << \"Created Pipeline \" << std::endl;\n    \n    // You must call init before starting the pipeline.\n    subscriber->init();\n    \n    // Connects the receiver to the input data but doesn't start ingestion.\n    if (!receiver->connect()) {\n      std::cout << \"Problems opening file \" << inputfile << std::endl;\n      return -1;\n    }\n    \n    milliseconds ms1 = duration_cast<milliseconds>(\n      system_clock::now().time_since_epoch()\n    );\n    // Starts the pipeline\n    receiver->receive();\n    milliseconds ms2 = duration_cast<milliseconds>(\n      system_clock::now().time_since_epoch()\n    );\n    std::cout << \"Seconds for Node\" << nodeId << \": \"  \n      << static_cast<double>(ms2.count() - ms1.count()) / 1000 << std::endl;\n    \n    std::cout << \"Finished\" << std::endl;\n    return 0;\n  } \n  /********************* Learning Model *********************************/\n  else if (vm.count(\"train\"))\n  {\n    /*if (inputfile == \"\") {\n      std::cout << \"--train was specified but no input file\"\n                << \" was listed with --inputfile.\" << std::endl;\n      return -1; \n    }\n    if (outputfile == \"\") {\n      std::cout << \"--train was specified but no output file\"\n                << \" was listed with --outputfile.\" << std::endl;\n      return -1; \n    }\n\n    // The true parameter transposes the data.  In mlpack, rows are features \n    // and columns are observations, which makes things confusing.\n    data::Load(inputfile, trainingData, true);\n\n    arma::Row<double> labels = trainingData.row(0);\n\n    //data::NormalizeLabels(trainingData.row(0), labels, model.mappings);\n    \n    // Remove the label row\n    trainingData.shed_row(0);\n\n    Timer::Start(\"nbc_training\");\n    std::cout << \"About to train \" << std::endl;\n    model.nbc = NaiveBayesClassifier<>(trainingData, labels,\n      model.mappings.n_elem, true);\n\n    data::Save(outputfile, \"model\", model, true);\n    std::cout << \"Saved Model \" << std::endl;\n    Timer::Stop(\"nbc_training\");\n    return 0;\n    */\n  } \n  /******************** Applying model *********************************/\n  else if (vm.count(\"test\"))\n  {\n    /*if (inputfile == \"\") {\n      std::cout << \"--test was specified but no input file\"\n                << \" was listed with --inputfile.\" << std::endl;\n      return -1; \n    }\n    data::Load(inputfile, \"model\", model);\n    cout << \"model.mappings \" << model.mappings << std::endl;\n    */\n  }\n  /******************* Running pipeline without model ******************/\n  else \n  {\n\n    auto receiver = std::make_shared<ReadSocket>(ip, ncPort);\n\n    // Make a commandline argument\n    size_t timeout = 1000;\n\n    // Creating the ZeroMQPushPull consumer.  This consumer is responsible for\n    // getting the data from the receiver (e.g. a socket or a file) and then\n    // publishing it in a load-balanced way to the cluster.\n    auto consumer = std::make_shared<PartitionType>(queueLength,\n                                   numNodes, \n                                   nodeId, \n                                   hostnames, \n                                   startingPort, timeout, false,\n                                   hwm);\n\n    receiver->registerConsumer(consumer);\n\n    createPipeline(NULL, featureMap, NULL, consumer,\n                   queueLength,\n                   numNodes,\n                   nodeId,\n                   hostnames,\n                   hwm,\n                   N, b, k);\n \n    if (!receiver->connect()) {\n      std::cout << \"Couldn't connected to \" << ip << \":\" << ncPort << std::endl;\n      return -1;\n    }\n\n    milliseconds ms1 = duration_cast<milliseconds>(\n      system_clock::now().time_since_epoch()\n    );\n    receiver->receive();\n    milliseconds ms2 = duration_cast<milliseconds>(\n      system_clock::now().time_since_epoch()\n    );\n    std::cout << \"Seconds for Node\" << nodeId << \": \"  \n      << static_cast<double>(ms2.count() - ms1.count()) / 1000 << std::endl;\n  }\n}\n  \n \n\n", "meta": {"hexsha": "2887e2a0487bf2efca481d4c244ec9dff4d51133", "size": 29167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ExecutableSrc/SimpleFeatures.cpp", "max_stars_repo_name": "dirkcgrunwald/SAM", "max_stars_repo_head_hexsha": "0478925c506ad38fd405954cc4415a3e96e77d90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExecutableSrc/SimpleFeatures.cpp", "max_issues_repo_name": "dirkcgrunwald/SAM", "max_issues_repo_head_hexsha": "0478925c506ad38fd405954cc4415a3e96e77d90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExecutableSrc/SimpleFeatures.cpp", "max_forks_repo_name": "dirkcgrunwald/SAM", "max_forks_repo_head_hexsha": "0478925c506ad38fd405954cc4415a3e96e77d90", "max_forks_repo_licenses": ["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.3776315789, "max_line_length": 80, "alphanum_fraction": 0.5896046902, "num_tokens": 6377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5170639722126638}}
{"text": "/* Copyright 2017 The sfcpp Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n\n\n\n#pragma once\n\n#include <math/NatSet.hpp>\n\n#include <Eigen/Dense>\n\n#include <memory>\n#include <ostream>\n#include <vector>\n\nnamespace sfcpp {\nnamespace geo {\n\n/**\n * Stores the combinatorial information of a polytope, i. e. the indices of\n * vertices contained in each face.\n */\nclass ConvexPolytope {\n public:\n  struct Face {\n    math::NatSet vertices;\n    std::vector<size_t> parentIndexes;\n    std::vector<size_t> childIndexes;\n    size_t dim;\n\n    friend std::ostream &operator<<(std::ostream &stream,\n                                    ConvexPolytope::Face const &face);\n  };\n\n  std::vector<std::vector<Face>> faces;\n\n  ConvexPolytope(size_t d);\n\n  bool tryFindFace(size_t dim, math::NatSet const &vertexSet,\n                   size_t &faceIndex) const;\n\n  static std::shared_ptr<ConvexPolytope> convexHull(Eigen::MatrixXd points);\n\n  friend std::ostream &operator<<(std::ostream &stream,\n                                  ConvexPolytope const &polytope);\n\n  void sort();\n\n  size_t getDimension();\n\n  // TODO: method for comparing two ConvexPolytopes?\n};\n\n} /* namespace geo */\n} /* namespace sfcpp */\n", "meta": {"hexsha": "f7267077aee85e8c324abaa6d155cd60acc004aa", "size": 1773, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geo/ConvexPolytope.hpp", "max_stars_repo_name": "dholzmueller/sfcpp", "max_stars_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-10-20T07:53:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T15:54:54.000Z", "max_issues_repo_path": "src/geo/ConvexPolytope.hpp", "max_issues_repo_name": "dholzmueller/sfcpp", "max_issues_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geo/ConvexPolytope.hpp", "max_forks_repo_name": "dholzmueller/sfcpp", "max_forks_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-10-20T20:02:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-02T12:47:53.000Z", "avg_line_length": 26.0735294118, "max_line_length": 80, "alphanum_fraction": 0.6655386351, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.517063961358011}}
{"text": "#pragma once\n#include <variant>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/Eigenvalues> \n\n#include <tbb/tbb.h>\n\n#include \"ED/ConstructSparseMat.hpp\"\n#include \"Utilities/Utility.hpp\"\n#include \"./utils.hpp\"\n\nnamespace yannq\n{\n//! \\addtogroup GroundState\n\ntemplate<typename Machine>\nclass SamplingResultExact\n{\nprivate:\n\tconst Machine& qs_;\n\tconst uint32_t N_;\n\tconst tbb::concurrent_vector<uint32_t>& basis_;\n\npublic:\n\tSamplingResultExact(const Machine& qs, \n\t\t\tconst tbb::concurrent_vector<uint32_t>& basis)\n\t\t: qs_{qs}, N_{qs.getN()}, basis_{basis}\n\t{\n\t}\n\n\ttypename Machine::DataT operator[](uint32_t idx) const\n\t{\n\t\treturn qs_.makeData(toSigma(N_, basis_[idx]));\n\t}\n\n\tstd::size_t size() const\n\t{\n\t\treturn basis_.size();\n\t}\n\n};\n\n\n//! \\ingroup GroundState\n//! This class calculate the quantum Fisher matrix by exactly constructing the quantum state.\ntemplate<typename Machine>\nclass SRMatExact\n{\npublic:\n\tusing Scalar = typename Machine::Scalar;\n\tusing RealScalar = typename remove_complex<Scalar>::type;\n\n\tusing Matrix = typename Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n\tusing MatrixRowMajor = typename Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\tusing Vector = typename Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n\nprivate:\n\tconst uint32_t n_;\n\tconst Machine& qs_;\n\ttbb::concurrent_vector<uint32_t> basis_;\n\n\tstd::variant<Eigen::SparseMatrix<RealScalar>, Eigen::SparseMatrix<Scalar>> ham_;\n\n\tMatrix deltas_;\n\tMatrix deltasPsis_;\n\tVector oloc_;\n\tVector grad_;\n\n\tRealScalar energy_;\n\tRealScalar energyVar_;\n\npublic:\n\n\tRealScalar eloc() const\n\t{\n\t\treturn energy_;\n\t}\n\n\tRealScalar elocVar() const\n\t{\n\t\treturn energyVar_;\n\t}\n\n\tvoid clear()\n\t{\n\t\tdeltas_ = Matrix{};\n\t\tdeltasPsis_ = Matrix{};\n\t\toloc_ = Vector{};\n\t\tgrad_ = Vector{};\n\n\t\tenergy_ = 0.0;\n\t\tenergyVar_ = 0.0;\n\t}\n\n\tvoid constructExact()\n\t{\n\t\tVector st = getPsi(qs_, basis_, true);\n\n\t\tVector k = std::visit([&st](auto&& arg) -> Vector { return arg*st; }, ham_);\n\n\t\tScalar t = st.adjoint()*k;\n\t\tenergy_ = std::real(t);\n\t\tenergyVar_ = static_cast<Scalar>(k.adjoint()*k).real();\n\t\tenergyVar_ -= energy_*energy_;\n\t\t\n\t\tSamplingResultExact srex(qs_, basis_);\n\t\t//deltas_ = constructDelta(qs_, srex);\n\t\tconstructDelta(qs_, srex, deltas_);\n\n\t\tdeltasPsis_ = st.cwiseAbs2().asDiagonal()*deltas_; \n\t\toloc_ = deltasPsis_.colwise().sum();\n\t\tgrad_ = (st.asDiagonal()*deltas_).adjoint()*k;\n\t\tgrad_ -= t*oloc_.conjugate();\n\t}\n\n\tconst Vector& oloc() const&\n\t{\n\t\treturn oloc_;\n\t}\n\tVector oloc() &&\n\t{\n\t\treturn oloc_;\n\t}\n\n\tMatrix corrMat() const\n\t{\n\t\tMatrix res = deltas_.adjoint()*deltasPsis_;\n\t\tres -= oloc_.conjugate()*oloc_.transpose();\n\t\treturn res;\n\t}\n\n\tconst Vector& energyGrad() const&\n\t{\n\t\treturn grad_;\n\t}\n\n\tVector erengyGrad() &&\n\t{\n\t\treturn grad_;\n\t}\n\n\tVector apply(const Vector& rhs)\n\t{\n\t\tVector res = deltas_.adjoint()*(deltasPsis_*rhs);\n\t\tres -= oloc_.conjugate()*(oloc_.transpose()*rhs);\n\t\treturn res;\n\t}\n\n\ttemplate<class Iterable, class ColFunc>\n\tSRMatExact(const Machine& qs, Iterable&& basis, ColFunc&& col)\n\t  : n_{qs.getN()}, qs_(qs)\n\t{\n\t\ttbb::parallel_for_each(basis.begin(), basis.end(), \n\t\t\t\t[&](uint32_t elt)\n\t\t{\n\t\t\tbasis_.emplace_back(elt);\n\t\t});\n\t\ttbb::parallel_sort(basis_.begin(), basis_.end());\n\t\tham_ = edp::constructSubspaceMat(std::forward<ColFunc>(col), basis_);\n\t}\n};\n} //namespace yannq\n", "meta": {"hexsha": "9d4b562759097a8d58bf9579fcbfdef2a81b438c", "size": 3321, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/GroundState/SRMatExact.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/GroundState/SRMatExact.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/GroundState/SRMatExact.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": 20.1272727273, "max_line_length": 104, "alphanum_fraction": 0.6919602529, "num_tokens": 966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867585368343, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5170639597731327}}
{"text": "//   Copyright (c) 2014-2016 SSPA Sweden AB\n\n#pragma once\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\nnamespace pysim {\n    typedef boost::numeric::ublas::vector<double> vector;\n    typedef boost::numeric::ublas::matrix<double> matrix;\n};\n\n", "meta": {"hexsha": "afcf72cdcbb0525c7c506b6e1a7623ec496b5a5a", "size": 281, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pysim/cppsource/PysimTypes.hpp", "max_stars_repo_name": "freol35241/pysim", "max_stars_repo_head_hexsha": "36faf67d00ff644a593f20994c0f15053d600886", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-01-15T07:43:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T20:21:38.000Z", "max_issues_repo_path": "pysim/cppsource/PysimTypes.hpp", "max_issues_repo_name": "freol35241/pysim", "max_issues_repo_head_hexsha": "36faf67d00ff644a593f20994c0f15053d600886", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2016-05-06T23:21:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T22:40:25.000Z", "max_forks_repo_path": "pysim/cppsource/PysimTypes.hpp", "max_forks_repo_name": "freol35241/pysim", "max_forks_repo_head_hexsha": "36faf67d00ff644a593f20994c0f15053d600886", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-03-02T14:55:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-11T06:29:35.000Z", "avg_line_length": 23.4166666667, "max_line_length": 57, "alphanum_fraction": 0.7259786477, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085909370421, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5170609196143844}}
{"text": "#include <stdexcept>\n#include \"say.h\"\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n#include <iostream>\n#include <algorithm>\n\nusing namespace std;\nusing namespace boost;\n\nnamespace say {\n\n    std::map<unsigned long long int, std::string> num999 = \n        {\n        {1, \"one\"},\n        {2, \"two\"},\n        {3, \"three\"},\n        {4, \"four\"},\n        {5, \"five\"},\n        {6, \"six\"},\n        {7, \"seven\"},\n        {8, \"eight\"},\n        {9, \"nine\"},\n        {10, \"ten\"},\n        {11, \"eleven\"},\n        {12, \"twelve\"},\n        {13, \"thirdteen\"},\n        {14, \"fourteen\"},\n        {15, \"fifteen\"},\n        {16, \"sixteen\"},\n        {17, \"seventeen\"},\n        {18, \"eighteen\"},\n        {19, \"nineteen\"},\n        {20, \"twenty\"},\n        {30, \"thirty\"},\n        {40, \"forty\"},\n        {50, \"fifty\"},\n        {60, \"sixty\"},\n        {70, \"seventy\"},\n        {80, \"eighty\"},\n        {90, \"ninety\"},\n        };\n\n    string in_english_999(int num){\n        if(num > 999)\n            throw domain_error(\"\");\n        if(num == 0)\n            return \"zero\";\n\n        string result = \"\";\n        auto it = num999.find(num);\n        if(it == num999.end()){\n            int h = int(num/100);\n            int d = int((num%100)/10)*10;\n            int s = num % 10;\n\n            string hs = \"\";\n            if(num >= 100){\n                hs = num999[h] + \" hundred\";\n            }\n            string ds = num999[d];\n            string ss = num999[s];\n\n            result += hs;\n            result += \" \" + ds;\n            if(ss != \"\"){\n                result += \"-\" + ss;\n            }\n\n            algorithm::trim(result);\n            //cout << format(\"num: %d,  h=%d d=%d s=%d -> %s\\n\") % num % h % d % s % result;\n        } else {\n            result = it->second;\n        }\n        return result;\n    }\n\n    string in_english(unsigned long long num){\n        if(num >= 1e+12){\n            throw domain_error(\"\");\n        }\n        int rest;\n        int thousand;\n        int million;\n        int billion;\n        unsigned long long r;\n        \n        billion = int(num / 1e9);\n        r = num % int(1e9);\n        million = int(r / 1e6);\n        r = r % int(1e6);\n        thousand = r / int(1e3);\n        rest = num%1000;\n        //cout << format(\"snum: %d, r %d, t %d, m %d, b %d\\n\") % num % rest % thousand % million % billion;\n\n        string result = \"\";\n        if(billion > 0){\n            result += in_english_999(billion) + \" billion\";\n        }\n        if(million > 0){\n            result += \" \" + in_english_999(million) + \" million\";\n        }\n         if(thousand > 0){\n            result += \" \" +in_english_999(thousand) + \" thousand\";\n        }\n        if((result == \"\") or (rest > 0))\n           result += \" \" + in_english_999(rest);\n\n        algorithm::trim(result); \n        return result;\n    }\n}", "meta": {"hexsha": "313235d43d7fc2d364e44a3a13d05afcc6db55e0", "size": 2817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "say/say.cpp", "max_stars_repo_name": "mapa17/Exercism-cpp", "max_stars_repo_head_hexsha": "6f61c33dbe96c1e580d5b98bfc36ca2f59adea60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "say/say.cpp", "max_issues_repo_name": "mapa17/Exercism-cpp", "max_issues_repo_head_hexsha": "6f61c33dbe96c1e580d5b98bfc36ca2f59adea60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "say/say.cpp", "max_forks_repo_name": "mapa17/Exercism-cpp", "max_forks_repo_head_hexsha": "6f61c33dbe96c1e580d5b98bfc36ca2f59adea60", "max_forks_repo_licenses": ["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.1517857143, "max_line_length": 107, "alphanum_fraction": 0.4181753639, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5170609182614151}}
{"text": "//  Copyright (c) 2018-2019 Cem Bassoy\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Fraunhofer and Google in producing this work\n//  which started as a Google Summer of Code project.\n//\n//  And we acknowledge the support from all contributors.\n\n\n#include <iostream>\n#include <algorithm>\n#include <boost/numeric/ublas/tensor.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"utility.hpp\"\n\nBOOST_AUTO_TEST_SUITE ( test_einstein_notation, * boost::unit_test::depends_on(\"test_multi_index\") )\n\n\nusing test_types = zip<int,long,float,double,std::complex<float>>::with_t<boost::numeric::ublas::first_order, boost::numeric::ublas::last_order>;\n\n//using test_types = zip<int>::with_t<boost::numeric::ublas::first_order>;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_einstein_multiplication, value,  test_types )\n{\n\tusing namespace boost::numeric::ublas;\n\tusing value_type   = typename value::first_type;\n\tusing layout_type  = typename value::second_type;\n\tusing tensor_type  = tensor<value_type,layout_type>;\n\tusing namespace boost::numeric::ublas::index;\n\n\t{\n\t\tauto A = tensor_type{5,3};\n\t\tauto B = tensor_type{3,4};\n\t\t//\t\tauto C = tensor_type{4,5,6};\n\n\t\tfor(auto j = 0u; j < A.extents().at(1); ++j)\n\t\t\tfor(auto i = 0u; i < A.extents().at(0); ++i)\n\t\t\t\tA.at( i,j ) = value_type(i+1);\n\n\t\tfor(auto j = 0u; j < B.extents().at(1); ++j)\n\t\t\tfor(auto i = 0u; i < B.extents().at(0); ++i)\n\t\t\t\tB.at( i,j ) = value_type(i+1);\n\n\n\n\t\tauto AB = A(_,_e) * B(_e,_);\n\n\t\t//\t\tstd::cout << \"A = \" << A << std::endl;\n\t\t//\t\tstd::cout << \"B = \" << B << std::endl;\n\t\t//\t\tstd::cout << \"AB = \" << AB << std::endl;\n\n\t\tfor(auto j = 0u; j < AB.extents().at(1); ++j)\n\t\t\tfor(auto i = 0u; i < AB.extents().at(0); ++i)\n\t\t\t\tBOOST_CHECK_EQUAL( AB.at( i,j ) , value_type(A.at( i,0 ) * ( B.extents().at(0) * (B.extents().at(0)+1) / 2 )) );\n\n\n\t}\n\n\n\t{\n\t\tauto A = tensor_type{4,5,3};\n\t\tauto B = tensor_type{3,4,2};\n\n\t\tfor(auto k = 0u; k < A.extents().at(2); ++k)\n\t\t\tfor(auto j = 0u; j < A.extents().at(1); ++j)\n\t\t\t\tfor(auto i = 0u; i < A.extents().at(0); ++i)\n\t\t\t\t\tA.at( i,j,k ) = value_type(i+1);\n\n\t\tfor(auto k = 0u; k < B.extents().at(2); ++k)\n\t\t\tfor(auto j = 0u; j < B.extents().at(1); ++j)\n\t\t\t\tfor(auto i = 0u; i < B.extents().at(0); ++i)\n\t\t\t\t\tB.at( i,j,k ) = value_type(i+1);\n\n\t\tauto AB = A(_d,_,_f) * B(_f,_d,_);\n\n\t\t//\t\tstd::cout << \"A = \" << A << std::endl;\n\t\t//\t\tstd::cout << \"B = \" << B << std::endl;\n\t\t//\t\tstd::cout << \"AB = \" << AB << std::endl;\n\t\t// n*(n+1)/2;\n\t\tauto const nf = ( B.extents().at(0) * (B.extents().at(0)+1) / 2 );\n\t\tauto const nd = ( A.extents().at(0) * (A.extents().at(0)+1) / 2 );\n\n\t\tfor(auto j = 0u; j < AB.extents().at(1); ++j)\n\t\t\tfor(auto i = 0u; i < AB.extents().at(0); ++i)\n\t\t\t\tBOOST_CHECK_EQUAL( AB.at( i,j ) ,  value_type(nf * nd) );\n\n\t}\n\n\n\t{\n\t\tauto A = tensor_type{4,3};\n\t\tauto B = tensor_type{3,4,2};\n\n\t\tfor(auto j = 0u; j < A.extents().at(1); ++j)\n\t\t\tfor(auto i = 0u; i < A.extents().at(0); ++i)\n\t\t\t\tA.at( i,j ) = value_type(i+1);\n\n\t\tfor(auto k = 0u; k < B.extents().at(2); ++k)\n\t\t\tfor(auto j = 0u; j < B.extents().at(1); ++j)\n\t\t\t\tfor(auto i = 0u; i < B.extents().at(0); ++i)\n\t\t\t\t\tB.at( i,j,k ) = value_type(i+1);\n\n\t\tauto AB = A(_d,_f) * B(_f,_d,_);\n\n\t\t// n*(n+1)/2;\n\t\tauto const nf = ( B.extents().at(0) * (B.extents().at(0)+1) / 2 );\n\t\tauto const nd = ( A.extents().at(0) * (A.extents().at(0)+1) / 2 );\n\n\t\tfor(auto i = 0u; i < AB.extents().at(0); ++i)\n\t\t\tBOOST_CHECK_EQUAL ( AB.at( i  ) ,  value_type(nf * nd) );\n\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "b0326c80c778b88feacd5ff265e9ff5989c1098d", "size": 3615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublas/test/tensor/test_einstein_notation.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/ublas/test/tensor/test_einstein_notation.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/ublas/test/tensor/test_einstein_notation.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": 29.3902439024, "max_line_length": 145, "alphanum_fraction": 0.5773167358, "num_tokens": 1334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5170609182614151}}
{"text": "//  (C) Copyright John Maddock 2005.\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_EXPM1_INCLUDED\n#define BOOST_MATH_EXPM1_INCLUDED\n\n#include <cmath>\n#include <math.h> // platform's ::expm1\n#include <boost/limits.hpp>\n#include <boost/math/special_functions/detail/series.hpp>\n\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n#  include <boost/static_assert.hpp>\n#else\n#  include <boost/assert.hpp>\n#endif\n\n#ifdef BOOST_NO_STDC_NAMESPACE\nnamespace std{ using ::exp; using ::fabs; }\n#endif\n\n\nnamespace boost{ namespace math{\n\nnamespace detail{\n//\n// Functor expm1_series returns the next term in the Taylor series\n// x^k / k!\n// each time that operator() is invoked.\n//\ntemplate <class T>\nstruct expm1_series\n{\n   typedef T result_type;\n\n   expm1_series(T x)\n      : k(0), m_x(x), m_term(1) {}\n\n   T operator()()\n   {\n      ++k;\n      m_term *= m_x;\n      m_term /= k;\n      return m_term; \n   }\n\n   int count()const\n   {\n      return k;\n   }\n\nprivate:\n   int k;\n   const T m_x;\n   T m_term;\n   expm1_series(const expm1_series&);\n   expm1_series& operator=(const expm1_series&);\n};\n\n} // namespace\n\n//\n// Algorithm expm1 is part of C99, but is not yet provided by many compilers.\n//\n// This version uses a Taylor series expansion for 0.5 > |x| > epsilon.\n//\ntemplate <class T>\nT expm1(T x)\n{\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n   BOOST_STATIC_ASSERT(::std::numeric_limits<T>::is_specialized);\n#else\n   BOOST_ASSERT(std::numeric_limits<T>::is_specialized);\n#endif\n\n   T a = std::fabs(x);\n   if(a > T(0.5L))\n      return std::exp(x) - T(1);\n   if(a < std::numeric_limits<T>::epsilon())\n      return x;\n   detail::expm1_series<T> s(x);\n   T result = detail::kahan_sum_series(s, std::numeric_limits<T>::digits + 2);\n   return result;\n}\n#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))\ninline float expm1(float z)\n{\n   return expm1<float>(z);\n}\ninline double expm1(double z)\n{\n   return expm1<double>(z);\n}\ninline long double expm1(long double z)\n{\n   return expm1<long double>(z);\n}\n#endif\n\n#ifdef expm1\n#  ifndef BOOST_HAS_expm1\n#     define BOOST_HAS_expm1\n#  endif\n#  undef expm1\n#endif\n\n#ifdef BOOST_HAS_EXPM1\n#  if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901)\ninline float expm1(float x){ return ::expm1f(x); }\ninline long double expm1(long double x){ return ::expm1l(x); }\n#else\ninline float expm1(float x){ return ::expm1(x); }\n#endif\ninline double expm1(double x){ return ::expm1(x); }\n#endif\n\n} } // namespaces\n\n#endif // BOOST_MATH_HYPOT_INCLUDED\n", "meta": {"hexsha": "a9fc3bbee469113147c33f758b09da2a036f8457", "size": 2650, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost-1_34_1/boost/math/special_functions/expm1.hpp", "max_stars_repo_name": "memoryboxes/bitcoin_satoshi", "max_stars_repo_head_hexsha": "efbe7e393c1ae3ee9f26a3040c423f176b1e48cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T01:42:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T18:33:43.000Z", "max_issues_repo_path": "include/boost-1_34_1/boost/math/special_functions/expm1.hpp", "max_issues_repo_name": "memoryboxes/bitcoin_satoshi", "max_issues_repo_head_hexsha": "efbe7e393c1ae3ee9f26a3040c423f176b1e48cd", "max_issues_repo_licenses": ["MIT"], "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-1_34_1/boost/math/special_functions/expm1.hpp", "max_forks_repo_name": "memoryboxes/bitcoin_satoshi", "max_forks_repo_head_hexsha": "efbe7e393c1ae3ee9f26a3040c423f176b1e48cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-10-29T08:02:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T16:57:29.000Z", "avg_line_length": 21.7213114754, "max_line_length": 78, "alphanum_fraction": 0.6924528302, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.517060918261415}}
{"text": "/* The Image Registration Toolkit (IRTK)\n *\n * Copyright 2008-2015 Imperial College London\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 <irtkImage.h>\n\n#include <irtkNoise.h>\n\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n\n\ntemplate <class VoxelType> irtkGaussianNoise<VoxelType>::irtkGaussianNoise() : irtkNoise<VoxelType>()\n{\n  _Mean   = 0;\n  _Sigma  = 1;\n  _MinVal = VoxelType(MIN_GREY);\n  _MaxVal = VoxelType(MAX_GREY);\n\n  long temp = -1 * this->_Init;\n\n  boost::mt19937 rng;\n  rng.seed(temp);\n\n  boost::normal_distribution<> nd(0, 1);\n  boost::variate_generator<boost::mt19937&,\n                           boost::normal_distribution<> > var_nor(rng, nd);\n  (void) var_nor();\n}\n\ntemplate <class VoxelType> irtkGaussianNoise<VoxelType>::irtkGaussianNoise(double Mean, double Sigma, VoxelType MinVal, VoxelType MaxVal) : irtkNoise<VoxelType>()\n{\n  this->_Mean   = Mean;\n  this->_Sigma  = Sigma;\n  this->_MinVal = MinVal;\n  this->_MaxVal = MaxVal;\n\n  long temp = -1 * this->_Init;\n\n  boost::mt19937 rng;\n  rng.seed(temp);\n\n  boost::normal_distribution<> nd(0, 1);\n  boost::variate_generator<boost::mt19937&,\n                           boost::normal_distribution<> > var_nor(rng, nd);\n  (void) var_nor();\n}\n\ntemplate <class VoxelType> double irtkGaussianNoise<VoxelType>::Run(int x, int y, int z, int t)\n{\n  boost::mt19937 rng;\n  rng.seed(this->_Init);\n\n  boost::normal_distribution<> nd(0, 1);\n  boost::variate_generator<boost::mt19937&,\n                           boost::normal_distribution<> > var_nor(rng, nd);\n\n  double tmp = this->_input->Get(x, y, z, t) + this->_Sigma * var_nor() + this->_Mean;\n  if (tmp < this->_MinVal) return this->_MinVal;\n  if (tmp > this->_MaxVal) return this->_MaxVal;\n  return tmp;\n}\n\ntemplate class irtkGaussianNoise<irtkBytePixel>;\ntemplate class irtkGaussianNoise<irtkGreyPixel>;\ntemplate class irtkGaussianNoise<float>;\ntemplate class irtkGaussianNoise<double>;\n", "meta": {"hexsha": "28ff18e29b912c54303e758e033d289f3c84b440", "size": 2454, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Modules/Image/src/irtkGaussianNoise.cc", "max_stars_repo_name": "kevin-keraudren/IRTK", "max_stars_repo_head_hexsha": "ce329b7f58270b6c34665dcfe9a6e941649f3b94", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-10-04T19:32:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T07:37:30.000Z", "max_issues_repo_path": "Modules/Image/src/irtkGaussianNoise.cc", "max_issues_repo_name": "kevin-keraudren/IRTK", "max_issues_repo_head_hexsha": "ce329b7f58270b6c34665dcfe9a6e941649f3b94", "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": "Modules/Image/src/irtkGaussianNoise.cc", "max_forks_repo_name": "kevin-keraudren/IRTK", "max_forks_repo_head_hexsha": "ce329b7f58270b6c34665dcfe9a6e941649f3b94", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T02:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-03T05:40:05.000Z", "avg_line_length": 30.675, "max_line_length": 162, "alphanum_fraction": 0.6976365118, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5170609129977599}}
{"text": "// -----------------------------------------------------------\n// integer_log2.hpp\n//\n//   Gives the integer part of the logarithm, in base 2, of a\n// given number. Behavior is undefined if the argument is <= 0.\n//\n//        Copyright (c) 2003-2004, 2008 Gennaro Prota\n//            Copyright (c) 2022 Andrey Semashev\n//\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// -----------------------------------------------------------\n\n#ifndef BOOST_INTEGER_INTEGER_LOG2_HPP\n#define BOOST_INTEGER_INTEGER_LOG2_HPP\n\n#include <climits>\n#include <limits>\n#include <boost/config.hpp>\n#include <boost/assert.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/core/bit.hpp>\n#include <boost/core/enable_if.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/type_traits/make_unsigned.hpp>\n\nnamespace boost {\nnamespace detail {\n\n// helper to find the maximum power of two\n// less than p\ntemplate< unsigned int p, unsigned int n, bool = ((2u * n) < p) >\nstruct max_pow2_less :\n    public max_pow2_less< p, 2u * n >\n{\n};\n\ntemplate< unsigned int p, unsigned int n >\nstruct max_pow2_less< p, n, false >\n{\n    BOOST_STATIC_CONSTANT(unsigned int, value = n);\n};\n\ntemplate< typename T >\ninline typename boost::disable_if< boost::is_integral< T >, int >::type integer_log2_impl(T x)\n{\n    unsigned int n = detail::max_pow2_less<\n        std::numeric_limits< T >::digits,\n        CHAR_BIT / 2u\n    >::value;\n\n    int result = 0;\n    while (x != 1)\n    {\n        T t(x >> n);\n        if (t)\n        {\n            result += static_cast< int >(n);\n#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)\n            x = static_cast< T&& >(t);\n#else\n            x = t;\n#endif\n        }\n        n >>= 1u;\n    }\n\n    return result;\n}\n\ntemplate< typename T >\ninline typename boost::enable_if< boost::is_integral< T >, int >::type integer_log2_impl(T x)\n{\n    // We could simply rely on numeric_limits but sometimes\n    // Borland tries to use numeric_limits<const T>, because\n    // of its usual const-related problems in argument deduction\n    // - gps\n    return static_cast< int >((sizeof(T) * CHAR_BIT - 1u) -\n        boost::core::countl_zero(static_cast< typename boost::make_unsigned< T >::type >(x)));\n}\n\n#if defined(BOOST_HAS_INT128)\n// We need to provide explicit overloads for __int128 because (a) boost/core/bit.hpp currently does not support it and\n// (b) std::numeric_limits are not specialized for __int128 in some standard libraries.\ninline int integer_log2_impl(boost::uint128_type x)\n{\n    const boost::uint64_t x_hi = static_cast< boost::uint64_t >(x >> 64u);\n    if (x_hi != 0u)\n        return 127 - boost::core::countl_zero(x_hi);\n    else\n        return 63 - boost::core::countl_zero(static_cast< boost::uint64_t >(x));\n}\n\ninline int integer_log2_impl(boost::int128_type x)\n{\n    return detail::integer_log2_impl(static_cast< boost::uint128_type >(x));\n}\n#endif // defined(BOOST_HAS_INT128)\n\n} // namespace detail\n\n\n// ------------\n// integer_log2\n// ------------\ntemplate< typename T >\ninline int integer_log2(T x)\n{\n    BOOST_ASSERT(x > 0);\n    return detail::integer_log2_impl(x);\n}\n\n} // namespace boost\n\n#endif // BOOST_INTEGER_INTEGER_LOG2_HPP\n", "meta": {"hexsha": "8ca236f61899348dd2c709f1d808cee8b2da4fbe", "size": 3272, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/integer/integer_log2.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/integer/integer_log2.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/integer/integer_log2.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.7288135593, "max_line_length": 118, "alphanum_fraction": 0.6433374083, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5170609024704494}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/ml/glm/linear_regression_with_sgd.hpp>\n#include <frovedis/ml/glm/ridge_regression_with_sgd.hpp>\n#include <frovedis/ml/glm/lasso_with_sgd.hpp>\n#include <boost/lexical_cast.hpp>\n\ndouble parse(const std::string& s){return boost::lexical_cast<double>(s);}\n\nint main(int argc, char* argv[]){\n  frovedis::use_frovedis use(argc, argv);\n\n  auto samples = frovedis::make_crs_matrix_load<double>(\"./train.mat\");\n  auto label = frovedis::make_dvector_loadline(\"./train.label\").map(parse);\n  \n  int num_iteration = 1000;\n  double alpha = 0.00000001;\n  double minibatch_fraction = 1.0;\n  bool intercept = true;\n  double convTol = 0;\n  frovedis::MatType mType = frovedis::CRS;\n  auto model = frovedis::linear_regression_with_sgd::\n    train(samples, label, num_iteration, alpha, minibatch_fraction,\n          intercept, convTol, mType);\n  /*\n  // L2 regularization\n  double regParam = 0.001;\n  auto model = frovedis::ridge_regression_with_sgd::\n    train(samples, label, num_iteration, alpha, minibatch_fraction,\n          regParam, intercept, convTol, mType);\n  */\n  /*\n  // L1 regularization\n  double regParam = 0.0001;\n  auto model = frovedis::lasso_with_sgd::\n    train(samples, label, num_iteration, alpha, minibatch_fraction,\n          regParam, intercept, convTol, mType);\n  */\n  model.save(\"./model\");\n\n  frovedis::linear_regression_model<double> lm;\n  lm.load(\"./model\");\n  auto test = frovedis::make_crs_matrix_local_load<double>(\"./test.mat\");\n  auto result = lm.predict(test);\n  for(auto i: result) std::cout << i << std::endl;\n}\n", "meta": {"hexsha": "c5acc9a33962bdf450183c5b02364e7f477e0be9", "size": 1571, "ext": "cc", "lang": "C++", "max_stars_repo_path": "doc/tutorial/src/tut4.1-2/tut.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": "doc/tutorial/src/tut4.1-2/tut.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": "doc/tutorial/src/tut4.1-2/tut.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": 34.152173913, "max_line_length": 75, "alphanum_fraction": 0.7122851687, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.5169808764177344}}
{"text": "/**\n * \\file libsanm/tensor_linalg.cpp\n * This file is part of SANM, a symbolic asymptotic numerical solver.\n */\n\n#include \"libsanm/tensor_impl_helper.h\"\n\n#include <Eigen/Dense>\n\nusing namespace sanm;\n\nnamespace {\n/*!\n * \\brief compute cofactor of a single matrix\n * \\param s_prod_rev a workspace of size dim+1, and the last value must be\n *      initialized to one\n */\ntemplate <int mat_dim>\nvoid compute_cofactor(EigenMat<mat_dim, mat_dim>& mdst,\n                      EigenMat<mat_dim, mat_dim>& msrc, fp_t* s_prod_rev) {\n    Eigen::Index dim = msrc.rows();\n\n    Eigen::JacobiSVD<Eigen::Matrix<fp_t, mat_dim, mat_dim>> svd{\n            msrc, Eigen::ComputeFullU | Eigen::ComputeFullV};\n\n    if (svd.rank() + 2 <= dim) {\n        mdst.setZero();\n        return;\n    }\n\n    // det(S) * S.inv()\n    Eigen::Matrix<fp_t, mat_dim, 1> sinvd = svd.singularValues();\n    if constexpr (mat_dim == 2) {\n        fp_t a = sinvd(0), b = sinvd(1);\n        sinvd(0) = b;\n        sinvd(1) = a;\n    } else if constexpr (mat_dim == 3) {\n        fp_t a = sinvd(0), b = sinvd(1), c = sinvd(2);\n        sinvd(0) = b * c;\n        sinvd(1) = a * c;\n        sinvd(2) = a * b;\n    } else {\n        for (int i = dim - 1; i >= 0; --i) {\n            s_prod_rev[i] = s_prod_rev[i + 1] * sinvd[i];\n        }\n        fp_t prod = 1;\n        for (Eigen::Index i = 0; i < dim; ++i) {\n            fp_t orig = sinvd(i);\n            sinvd(i) = prod * s_prod_rev[i + 1];\n            prod *= orig;\n        }\n    }\n\n    fp_t sign = (svd.matrixU() * svd.matrixV().transpose()).determinant();\n    if (sign < 0) {\n        sinvd = -sinvd;\n    }\n    mdst = svd.matrixU() * sinvd.asDiagonal() * svd.matrixV().transpose();\n}\n\ntemplate <typename T>\nconstexpr T get_from_pair(int d, T x, T y) {\n    return d == 0 ? x : y;\n}\n\nCBLAS_TRANSPOSE cblas_trans(bool t) {\n    return t ? CblasTrans : CblasNoTrans;\n}\n}  // anonymous namespace\n\nTensorND& TensorND::as_mm(const TensorND& lhs, const TensorND& rhs, bool accum,\n                          bool trans_lhs, bool trans_rhs) {\n    SANM_SCOPED_PROFILER(\"mm\");\n    sanm_assert(this != &lhs && this != &rhs);\n    sanm_assert(lhs.rank() == 2 && rhs.rank() == 2);\n    TensorShape dst_shape{\n            get_from_pair(trans_lhs, lhs.shape(0), lhs.shape(1)),\n            get_from_pair(trans_rhs ^ 1, rhs.shape(0), rhs.shape(1))};\n\n    if (accum) {\n        sanm_assert(shape() == dst_shape, \"mm accum: expect shape %s, got %s\",\n                    dst_shape.str().c_str(), shape().str().c_str());\n\n        if (lhs.is_zero() || rhs.is_zero()) {\n            return *this;\n        }\n    } else {\n        if (lhs.is_zero() || rhs.is_zero()) {\n            // do not use set_shape to avoid unnecessary memory allocation\n            m_shape = dst_shape;\n            return fill_with_inplace(0);\n        }\n        set_shape(dst_shape);\n    }\n\n    static_assert(std::is_same_v<fp_t, double>, \"unhandled fp_t\");\n    if constexpr (std::is_same_v<fp_t, double>) {\n        cblas_dgemm(CblasRowMajor, cblas_trans(trans_lhs),\n                    cblas_trans(trans_rhs), dst_shape[0], dst_shape[1],\n                    get_from_pair(trans_lhs ^ 1, lhs.shape(0), lhs.shape(1)), 1,\n                    lhs.ptr(), lhs.shape(1), rhs.ptr(), rhs.shape(1),\n                    accum ? 1 : 0, rwptr(), dst_shape[1]);\n    }\n    return *this;\n}\n\nTensorND& TensorND::as_batched_mm(const TensorND& lhs, const TensorND& rhs,\n                                  bool accum, bool trans_lhs, bool trans_rhs) {\n    SANM_SCOPED_PROFILER(\"batched_mm\");\n    sanm_assert(this != &lhs && this != &rhs);\n    sanm_assert(\n            lhs.rank() == 3 && rhs.rank() == 3 && lhs.shape(0) == rhs.shape(0),\n            \"batched mm shape mismatch %s vs %s\", lhs.shape().str().c_str(),\n            rhs.shape().str().c_str());\n    const size_t ls0 = lhs.shape(1), ls1 = lhs.shape(2), rs0 = rhs.shape(1),\n                 rs1 = rhs.shape(2), batch = lhs.shape(0);\n    sanm_assert(get_from_pair(trans_lhs ^ 1, ls0, ls1) ==\n                        get_from_pair(trans_rhs, rs0, rs1),\n                \"matmul shape mismatch: %s vs %s, trans=%d,%d\",\n                lhs.shape().str().c_str(), rhs.shape().str().c_str(), trans_lhs,\n                trans_rhs);\n\n    TensorShape dst_shape{batch, get_from_pair(trans_lhs, ls0, ls1),\n                          get_from_pair(trans_rhs ^ 1, rs0, rs1)};\n\n    if (accum) {\n        sanm_assert(shape() == dst_shape,\n                    \"batched_mm accum: expect shape %s, got %s\",\n                    dst_shape.str().c_str(), shape().str().c_str());\n\n        if (lhs.is_zero() || rhs.is_zero()) {\n            return *this;\n        }\n    } else {\n        if (lhs.is_zero() || rhs.is_zero()) {\n            // do not use set_shape to avoid unnecessary memory allocation\n            m_shape = dst_shape;\n            return fill_with_inplace(0);\n        }\n        set_shape(dst_shape);\n    }\n\n    // As of 2020, MKL batched dgemm is still slow for small matrices ...\n    // So we roll out our simple accelerated impl using eigen\n\n    auto pa = const_cast<fp_t*>(lhs.ptr()), pb = const_cast<fp_t*>(rhs.ptr()),\n         pc = rwptr();\n    auto run_static_shape = [pa, pb, pc, batch, accum, trans_lhs,\n                             trans_rhs]<int ls0, int ls1, int rs0, int rs1>() {\n\n    // eigen uses col-major; so we compute on the transformed matrices\n#define FOREACH_8(cb)                                                       \\\n    cb(0, 0, 0) cb(0, 0, 1) cb(0, 1, 0) cb(0, 1, 1) cb(1, 0, 0) cb(1, 0, 1) \\\n            cb(1, 1, 0) cb(1, 1, 1)\n#define ACC0 =\n#define ACC1 +=\n#define TR0(x) x\n#define TR1(x) x.transpose()\n#define CB(acc, tra, trb)                                               \\\n    if constexpr (get_from_pair(tra ^ 1, ls0, ls1) ==                   \\\n                  get_from_pair(trb, rs0, rs1)) {                       \\\n        constexpr int cs0 = get_from_pair(tra, ls0, ls1),               \\\n                      cs1 = get_from_pair(trb ^ 1, rs0, rs1);           \\\n        if (accum == acc && trans_lhs == tra && trans_rhs == trb) {     \\\n            for (size_t ib = 0; ib < batch; ++ib) {                     \\\n                EigenMat<ls1, ls0> ta{pa + ib * (ls0 * ls1), ls1, ls0}; \\\n                EigenMat<rs1, rs0> tb{pb + ib * (rs0 * rs1), rs1, rs0}; \\\n                EigenMat<cs1, cs0> tc{pc + ib * (cs0 * cs1), cs1, cs0}; \\\n                tc.noalias() ACC##acc TR##trb(tb) * TR##tra(ta);        \\\n            }                                                           \\\n            return;                                                     \\\n        }                                                               \\\n    }\n        FOREACH_8(CB)\n        sanm_assert(0, \"impossible\");\n#undef CB\n#undef TR1\n#undef TR0\n#undef ACC1\n#undef ACC0\n#undef FOREACH_8\n    };\n\n#define CASE(ls0_, ls1_, rs0_, rs1_)                                    \\\n    do {                                                                \\\n        if (ls0_ == ls0 && ls1_ == ls1 && rs0_ == rs0 && rs1_ == rs1) { \\\n            run_static_shape.operator()<ls0_, ls1_, rs0_, rs1_>();      \\\n            return *this;                                               \\\n        }                                                               \\\n    } while (0)\n\n    CASE(1, 1, 1, 1);\n    CASE(2, 2, 2, 2);\n    CASE(3, 3, 3, 3);\n    CASE(4, 4, 4, 4);\n\n    // special handling of shapes can be added here\n#undef CASE\n\n    static_assert(std::is_same_v<fp_t, double>, \"unhandled fp_t\");\n    if constexpr (std::is_same_v<fp_t, double>) {\n        cblas_dgemm_batch_strided(\n                CblasRowMajor, cblas_trans(trans_lhs), cblas_trans(trans_rhs),\n                dst_shape[1], dst_shape[2],\n                get_from_pair(trans_lhs ^ 1, ls0, ls1), 1, lhs.ptr(), ls1,\n                ls0 * ls1, rhs.ptr(), rs1, rs0 * rs1, accum ? 1 : 0, rwptr(),\n                dst_shape[2], dst_shape[1] * dst_shape[2], batch);\n    }\n    return *this;\n}\n\nTensorND& TensorND::as_batched_transpose(const TensorND& src) {\n    SANM_SCOPED_PROFILER(\"batched_transpose\");\n    sanm_assert(this != &src);\n    sanm_assert(src.rank() == 3);\n    {\n        TensorShape oshp = src.shape();\n        std::swap(oshp.dim[1], oshp.dim[2]);\n        set_shape(oshp);\n    }\n    if (src.is_zero()) {\n        return fill_with_inplace(0);\n    }\n    auto work = [this, &src]<int mat_dim0, int mat_dim1>() {\n        auto sptr = const_cast<fp_t*>(src.ptr()), dptr = this->woptr();\n        const size_t batch = src.shape(0);\n        const Eigen::Index dim0 = src.shape(1), dim1 = src.shape(2);\n        for (size_t i = 0; i < batch; ++i) {\n            EigenMat<mat_dim0, mat_dim1> mdst{dptr + i * dim0 * dim1, dim0,\n                                              dim1};\n            EigenMat<mat_dim1, mat_dim0> msrc{sptr + i * dim0 * dim1, dim1,\n                                              dim0};\n            mdst = msrc.transpose();\n        }\n    };\n\n    auto work_dispatch = [&work, &src]<int mat_dim0>() {\n        switch (src.shape(2)) {\n#define ON(x)                           \\\n    case x:                             \\\n        work.operator()<mat_dim0, x>(); \\\n        break\n            ON(1);\n            ON(2);\n            ON(3);\n            ON(4);\n#undef ON\n            default:\n                work.operator()<mat_dim0, Eigen::Dynamic>();\n                break;\n        }\n    };\n\n    switch (src.shape(1)) {\n#define ON(x)                          \\\n    case x:                            \\\n        work_dispatch.operator()<x>(); \\\n        break\n        ON(1);\n        ON(2);\n        ON(3);\n        ON(4);\n#undef ON\n        default:\n            work_dispatch.operator()<Eigen::Dynamic>();\n            break;\n    }\n    return *this;\n}\n\nTensorND& TensorND::as_transpose(const TensorND& src) {\n    sanm_assert(src.rank() == 2);\n    size_t m = src.shape(0), n = src.shape(1);\n    set_shape({n, m});\n    if (src.is_zero()) {\n        return fill_with_inplace(0);\n    }\n    auto ei = [](size_t x) -> Eigen::Index { return x; };\n    EigenMatDyn mdst{woptr(), ei(m), ei(n)},\n            msrc{const_cast<fp_t*>(src.ptr()), ei(n), ei(m)};\n    mdst = msrc.transpose();\n    return *this;\n}\n\nTensorND& TensorND::as_batched_matinv(const TensorND& src) {\n    SANM_SCOPED_PROFILER(\"batched_matinv\");\n    sanm_assert(this != &src);\n    sanm_assert(src.rank() == 3 && src.shape(1) == src.shape(2));\n    sanm_assert(!src.is_zero());\n    set_shape(src.shape());\n    auto work = [this, &src]<int mat_dim>() {\n        ScopedAllowMalloc scoped_allow_malloc;\n        auto sptr = const_cast<fp_t*>(src.ptr()), dptr = this->woptr();\n        const size_t batch = src.shape(0);\n        const Eigen::Index dim = src.shape(1);\n        for (size_t i = 0; i < batch; ++i) {\n            EigenMat<mat_dim, mat_dim> mdst{dptr + i * dim * dim, dim, dim},\n                    msrc{sptr + i * dim * dim, dim, dim};\n            mdst = msrc.inverse();\n        }\n    };\n    switch (src.shape(1)) {\n#define ON(x)                 \\\n    case x:                   \\\n        work.operator()<x>(); \\\n        break\n        ON(1);\n        ON(2);\n        ON(3);\n        ON(4);\n#undef ON\n        default:\n            work.operator()<Eigen::Dynamic>();\n            break;\n    }\n    return *this;\n}\n\nTensorND& TensorND::as_batched_determinant(const TensorND& src) {\n    SANM_SCOPED_PROFILER(\"batched_det\");\n    ScopedAllowMalloc allow_mem_alloc;\n\n    sanm_assert(this != &src);\n    sanm_assert(src.rank() == 3 && src.shape(1) == src.shape(2));\n    set_shape({src.shape(0), 1});\n    if (src.is_zero()) {\n        return fill_with_inplace(0);\n    }\n    auto work = [this, &src]<int mat_dim>() {\n        auto sptr = const_cast<fp_t*>(src.ptr()), dptr = this->woptr();\n        const size_t batch = src.shape(0);\n        const Eigen::Index dim = src.shape(1);\n        for (size_t i = 0; i < batch; ++i) {\n            EigenMat<mat_dim, mat_dim> msrc{sptr + i * dim * dim, dim, dim};\n            dptr[i] = msrc.determinant();\n        }\n    };\n    switch (src.shape(1)) {\n#define ON(x)                 \\\n    case x:                   \\\n        work.operator()<x>(); \\\n        break\n        ON(1);\n        ON(2);\n        ON(3);\n        ON(4);\n#undef ON\n        default:\n            work.operator()<Eigen::Dynamic>();\n            break;\n    }\n    return *this;\n}\n\nTensorND& TensorND::as_batched_cofactor(const TensorND& src) {\n    SANM_SCOPED_PROFILER(\"batched_cofactor\");\n    ScopedAllowMalloc allow_mem_alloc;\n\n    sanm_assert(this != &src);\n    sanm_assert(src.rank() == 3 && src.shape(1) == src.shape(2) &&\n                src.shape(1) >= 2);\n    set_shape(src.shape());\n    if (src.is_zero()) {\n        return fill_with_inplace(0);\n    }\n    auto work = [this, &src]<int mat_dim>() {\n        auto sptr = const_cast<fp_t*>(src.ptr()), dptr = this->woptr();\n        const size_t batch = src.shape(0);\n        const Eigen::Index dim = src.shape(1);\n        std::unique_ptr<fp_t[]> s_prod_rev{new fp_t[dim + 1]};\n        s_prod_rev[dim] = 1;\n        for (size_t i = 0; i < batch; ++i) {\n            EigenMat<mat_dim, mat_dim> mdst{dptr + i * dim * dim, dim, dim},\n                    msrc{sptr + i * dim * dim, dim, dim};\n            compute_cofactor(mdst, msrc, s_prod_rev.get());\n        }\n    };\n    switch (src.shape(1)) {\n#define ON(x)                 \\\n    case x:                   \\\n        work.operator()<x>(); \\\n        break\n        ON(2);\n        ON(3);\n        ON(4);\n#undef ON\n        default:\n            work.operator()<Eigen::Dynamic>();\n            break;\n    }\n    return *this;\n}\n\nTensorND& TensorND::as_batched_mm_vecitem_left(const TensorND& lhs,\n                                               const TensorND& rhs,\n                                               bool accum) {\n    SANM_SCOPED_PROFILER(\"batched_mm_vecitem\");\n    sanm_assert(this != &lhs && this != &rhs);\n    sanm_assert(lhs.rank() == 3 && rhs.rank() == 3);\n    size_t BATCH = lhs.shape(0), M = lhs.shape(1), P = lhs.shape(2),\n           K = rhs.shape(1), N = rhs.shape(2);\n    sanm_assert(M % K == 0 && BATCH == rhs.shape(0));\n    M /= K;\n\n    TensorShape expect_shape{BATCH, M * N, P};\n    if (accum) {\n        sanm_assert(m_shape == expect_shape);\n    } else {\n        set_shape(expect_shape);\n    }\n\n    if (lhs.is_zero() || rhs.is_zero()) {\n        return fill_with_inplace(0);\n    }\n\n    auto ei = [](size_t x) -> Eigen::Index { return x; };\n\n    auto lptr = const_cast<fp_t*>(lhs.ptr()),\n         rptr = const_cast<fp_t*>(rhs.ptr()), optr = this->woptr();\n    for (size_t b = 0; b < BATCH; ++b) {\n        EigenMatDyn mat_rhs{rptr + b * K * N, ei(N), ei(K)};\n        for (size_t m = 0; m < M; ++m) {\n            EigenMatDyn mat_lhs{lptr + (b * M + m) * K * P, ei(P), ei(K)},\n                    mat_dst{optr + (b * M + m) * N * P, ei(P), ei(N)};\n            if (accum) {\n                mat_dst.noalias() += mat_lhs * mat_rhs.transpose();\n            } else {\n                mat_dst.noalias() = mat_lhs * mat_rhs.transpose();\n            }\n        }\n    }\n\n    return *this;\n}\n", "meta": {"hexsha": "3740592aeb0b5e494cba12530b6a4094cff9b0d5", "size": 14945, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libsanm/tensor_linalg.cpp", "max_stars_repo_name": "jia-kai/SANM", "max_stars_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T09:27:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T15:22:05.000Z", "max_issues_repo_path": "libsanm/tensor_linalg.cpp", "max_issues_repo_name": "jia-kai/SANM", "max_issues_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-03T05:31:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-05T01:37:42.000Z", "max_forks_repo_path": "libsanm/tensor_linalg.cpp", "max_forks_repo_name": "jia-kai/SANM", "max_forks_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_forks_repo_licenses": ["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.3563218391, "max_line_length": 80, "alphanum_fraction": 0.4943459351, "num_tokens": 4204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.5169808705441967}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#include <type_traits>\n#include <algorithm>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/banded.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include \"print.hpp\"\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef std::complex<double> complex;\n    typedef ublas::vector<complex> vector;\n    typedef ublas::banded_matrix<complex, ublas::column_major> matrix;\n    typedef typename std::make_signed<vector::size_type>::type size_type;\n    rand_normal<complex>::reset();\n    size_type m=6, n=8;\n    matrix A(m, n, 1, 2);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=std::max(j-2, size_type(0)); i<std::min(j+1+1, m); ++i)\n \tA(i, j)=rand_normal<complex>::get();\n    // A banded ublas matrux and its transpose have very different\n    // memory layouts, thus the following line does not work.\n    // matrix A_t(ublas::trans(A));\n    matrix A_t(n, m, 2, 1);\n    for (size_type j=0; j<m; ++j)\n      for (size_type i=std::max(j-1, size_type(0)); i<std::min(j+2+1, n); ++i)\n    \tA_t(i, j)=A(j, i);\n    vector x(n);\n    for (size_type i=0; i<n; ++i)\n      x(i)=rand_normal<complex>::get();\n    vector y(m);\n    for (size_type i=0; i<m; ++i)\n      y(i)=rand_normal<complex>::get();\n    complex alpha(rand_normal<complex>::get());\n    complex beta(rand_normal<complex>::get());\n    vector y1(alpha*ublas::prod(A, x)+beta*y);\n    vector y2(y);\n    blas::gbmv(alpha, A, x, beta, y2);\n    vector y3(y);\n    blas::gbmv(alpha, blas::trans(A_t), x, beta, y3);\n    std::cout << \"testing boost::ublas containers\\n\"\n\t      << \"using ublas           : \" << print_vec(y1) << '\\n'\n\t      << \"using blas            : \" << print_vec(y2) << '\\n'\n\t      << \"using blas (tranposed): \" << print_vec(y3) << '\\n'\n\t      << '\\n';\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "f390da09ac77abd710a60130a4348be8971ae62b", "size": 2086, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/gbmv.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/gbmv.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/gbmv.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.9655172414, "max_line_length": 78, "alphanum_fraction": 0.6270373921, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5169808604052245}}
{"text": "\r\n\r\n#include <boost/numeric/ublas/vector.hpp>\r\n#include <iostream>\r\n#include <boost/numeric/ublas/io.hpp>\r\n\r\n\r\nint main()\r\n{\r\n\tboost::numeric::ublas::vector<float> vector(3);\r\n\tvector = boost::numeric::ublas::zero_vector<float> ();\r\n\r\n\tstd::cerr << vector << std::endl;\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "14924b09f671b9e1e648f83bdb76d4d990c54525", "size": 292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/ZeroVector/ZeroVectorTest.cpp", "max_stars_repo_name": "taku-xhift/labo", "max_stars_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/ZeroVector/ZeroVectorTest.cpp", "max_issues_repo_name": "taku-xhift/labo", "max_issues_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/ZeroVector/ZeroVectorTest.cpp", "max_forks_repo_name": "taku-xhift/labo", "max_forks_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.3684210526, "max_line_length": 56, "alphanum_fraction": 0.6335616438, "num_tokens": 75, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5168072012948642}}
{"text": "/*\n * phase_oscillator_ensemble.cpp\n *\n * Demonstrates the phase transition from an unsynchronized to an synchronized state.\n *\n * Copyright 2011-2012 Karsten Ahnert\n * Copyright 2011-2012 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\n#include <iostream>\n#include <utility>\n\n#include <boost/numeric/odeint.hpp>\n\n#ifndef M_PI //not there on windows\n#define M_PI 3.141592653589793 //...\n#endif\n\n#include <boost/random.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n//[ phase_oscillator_ensemble_system_function\ntypedef vector< double > container_type;\n\n\npair< double , double > calc_mean_field( const container_type &x )\n{\n    size_t n = x.size();\n    double cos_sum = 0.0 , sin_sum = 0.0;\n    for( size_t i=0 ; i<n ; ++i )\n    {\n        cos_sum += cos( x[i] );\n        sin_sum += sin( x[i] );\n    }\n    cos_sum /= double( n );\n    sin_sum /= double( n );\n\n    double K = sqrt( cos_sum * cos_sum + sin_sum * sin_sum );\n    double Theta = atan2( sin_sum , cos_sum );\n\n    return make_pair( K , Theta );\n}\n\n\nstruct phase_ensemble\n{\n    container_type m_omega;\n    double m_epsilon;\n\n    phase_ensemble( const size_t n , double g = 1.0 , double epsilon = 1.0 )\n    : m_omega( n , 0.0 ) , m_epsilon( epsilon )\n    {\n        create_frequencies( g );\n    }\n\n    void create_frequencies( double g )\n    {\n        boost::mt19937 rng;\n        boost::cauchy_distribution<> cauchy( 0.0 , g );\n        boost::variate_generator< boost::mt19937&, boost::cauchy_distribution<> > gen( rng , cauchy );\n        generate( m_omega.begin() , m_omega.end() , gen );\n    }\n\n    void set_epsilon( double epsilon ) { m_epsilon = epsilon; }\n\n    double get_epsilon( void ) const { return m_epsilon; }\n\n    void operator()( const container_type &x , container_type &dxdt , double /* t */ ) const\n    {\n        pair< double , double > mean = calc_mean_field( x );\n        for( size_t i=0 ; i<x.size() ; ++i )\n            dxdt[i] = m_omega[i] + m_epsilon * mean.first * sin( mean.second - x[i] );\n    }\n};\n//]\n\n\n\n//[ phase_oscillator_ensemble_observer\nstruct statistics_observer\n{\n    double m_K_mean;\n    size_t m_count;\n\n    statistics_observer( void )\n    : m_K_mean( 0.0 ) , m_count( 0 ) { }\n\n    template< class State >\n    void operator()( const State &x , double t )\n    {\n        pair< double , double > mean = calc_mean_field( x );\n        m_K_mean += mean.first;\n        ++m_count;\n    }\n\n    double get_K_mean( void ) const { return ( m_count != 0 ) ? m_K_mean / double( m_count ) : 0.0 ; }\n\n    void reset( void ) { m_K_mean = 0.0; m_count = 0; }\n};\n//]\n\n\n\n\n\n\n\n\nint main( int argc , char **argv )\n{\n    //[ phase_oscillator_ensemble_integration\n    const size_t n = 16384;\n    const double dt = 0.1;\n\n    container_type x( n );\n\n    boost::mt19937 rng;\n    boost::uniform_real<> unif( 0.0 , 2.0 * M_PI );\n    boost::variate_generator< boost::mt19937&, boost::uniform_real<> > gen( rng , unif );\n\n    // gamma = 1, the phase transition occurs at epsilon = 2\n    phase_ensemble ensemble( n , 1.0 );\n    statistics_observer obs;\n\n    for( double epsilon = 0.0 ; epsilon < 5.0 ; epsilon += 0.1 )\n    {\n        ensemble.set_epsilon( epsilon );\n        obs.reset();\n\n        // start with random initial conditions\n        generate( x.begin() , x.end() , gen );\n\n        // calculate some transients steps\n        integrate_const( runge_kutta4< container_type >() , boost::ref( ensemble ) , x , 0.0 , 10.0 , dt );\n\n        // integrate and compute the statistics\n        integrate_const( runge_kutta4< container_type >() , boost::ref( ensemble ) , x , 0.0 , 100.0 , dt , boost::ref( obs ) );\n        cout << epsilon << \"\\t\" << obs.get_K_mean() << endl;\n    }\n\n\n    //]\n\n    return 0;\n}\n", "meta": {"hexsha": "090fd587bb8e4be1899b94709e7abceddab54cd5", "size": 3815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/phase_oscillator_ensemble.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/phase_oscillator_ensemble.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/phase_oscillator_ensemble.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 25.0986842105, "max_line_length": 128, "alphanum_fraction": 0.6146788991, "num_tokens": 1080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5168071965609193}}
{"text": "#include <iostream>\n#include <vector>\nusing namespace std;\n\n#include <boost/generator_iterator.hpp>\n#include <boost/random.hpp>\n#include <boost/timer/timer.hpp>\n\n#include <cpp_algs.hpp>\n\ntemplate <typename T>\nvoid init_matrices(vector<vector<vector<T>>> &, const vector<int> &, const T &, bool = false);\n\nvoid time_test(const vector<int> &);\n\nint main() {\n    // Sorting\n    vector<int> v = {541, 12, 56, 62, 1234, 656547, 123, 1, 6546, 51, 1334, 56612};\n    al::heapSort(v);\n    BOOST_ASSERT_MSG(std::is_sorted(v.begin(), v.end()), \"sorting buggy\");\n\n    // Stack\n    ds::Stack<int> s1;\n    s1.push(10);\n    s1.push(20);\n\n    ds::Stack<int> s_copy;\n    s_copy = s1;\n\n    ds::Stack<int> s_copy2(s1);\n\n    // Singly Linked List\n    ds::SinglyLinkedList<int> sing;\n    BOOST_ASSERT_MSG(sing.size() == 0, \"Singly linked list size() is buggy\");\n    sing.insertNode(10);\n    BOOST_ASSERT_MSG(sing.contains(10), \"Singly linked list insertion is buggy\");\n    sing.insertNode(20);\n    BOOST_ASSERT_MSG(sing.contains(20), \"Singly linked list search is buggy\");\n    sing.deleteNode(20);\n    BOOST_ASSERT_MSG(!sing.contains(20), \"Singly linked list deletion is buggy\");\n\n    vector<int> vec = {43, 44, 45, 46, 47};\n    sing.insertArray(vec);\n    for (const auto &v : vec) {\n        BOOST_ASSERT_MSG(sing.contains(v), \"Singly linked list insertion of std::vector<int> is buggy\");\n    }\n    BOOST_ASSERT_MSG(sing.size() == 6, \"Singly linked list size() is buggy\");\n\n    ds::SinglyLinkedList<string> s = ds::SinglyLinkedList<string>();\n    BOOST_ASSERT_MSG(s.size() == 0, \"Singly linked list size() is buggy\");\n    s.insertNode(\"hello\");\n    BOOST_ASSERT_MSG(s.contains(\"hello\"), \"Singly linked list std::string insertion is buggy\");\n    s.insertNode(\"world\");\n    BOOST_ASSERT_MSG(s.contains(\"world\"), \"Singly linked list std::string contains is buggy\");\n    s.deleteNode(\"hello\");\n    BOOST_ASSERT_MSG(!s.contains(\"hello\"), \"Singly linked list std::string deletion is buggy\");\n    s.insertNode(\"!\");\n    BOOST_ASSERT_MSG(s.search(\"!\")->data == \"!\", \"Singly linked list std::string search is buggy\");\n    BOOST_ASSERT_MSG(s.size() == 2, \"Singly linked list size() is buggy\");\n\n    // Matrix Chain Multiplication\n    vector<int> dims = {6, 4, 2, 1};\n\n    vector<vector<vector<float>>> matrices;\n    init_matrices<float>(matrices, dims, 1.0f);\n\n    vector<vector<float>> out = al::chain_matmul<float>(matrices);\n\n    for (int i = 0; i < out.size(); i++) {\n        for (int j = 0; j < out[0].size(); j++) {\n            BOOST_ASSERT_MSG(out[i][j] == 8, \"Matrix chain multiplication is buggy\");\n        }\n    }\n\n    // Trie dictionary\n    ds::Trie trie;\n\n    trie.insertWord(\"hello\");\n    BOOST_ASSERT_MSG(trie.containsWord(\"hello\"), \"Trie std::string insertion is buggy\");\n    trie.insertWord(\"help\");\n    BOOST_ASSERT_MSG(trie.containsWord(\"help\"), \"Trie std::string insertion is buggy\");\n    trie.insertWord(\"hell\");\n    BOOST_ASSERT_MSG(trie.containsWord(\"hell\"), \"Trie std::string insertion is buggy\");\n\n    char c[] = {'a', 'b', 'c', '\\0'};\n    trie.insertWord(c);\n    BOOST_ASSERT_MSG(trie.containsWord(\"abc\"), \"Trie (char *) insertion is buggy\");\n\n    trie.removeWord(\"hello\");\n    BOOST_ASSERT_MSG(!trie.containsWord(\"hello\"), \"Trie std::string removal is buggy\");\n    trie.removeWord(c);\n    BOOST_ASSERT_MSG(!trie.containsWord(c), \"Trie (char *) removal is buggy\");\n\n    cout << \"Verified installation of library!\" << '\\n';\n\n    dims = {1000, 1234, 152, 13, 542, 122, 11, 424};\n    time_test(dims);\n\n    // cleanup\n    return 0;\n}\n\ntemplate <typename T>\nvoid init_matrices(vector<vector<vector<T>>> &matrices, const vector<int> &dims, const T &data, bool random) {\n    typedef boost::mt19937 RNGType;\n    RNGType rng;\n    boost::uniform_int<> random_iter(1, 10);\n    boost::variate_generator<RNGType, boost::uniform_int<>> dice(rng, random_iter);\n\n    for (int i = 0; i < dims.size() - 1; i++) {\n        if (random) {\n            vector<vector<T>> matrix(dims[i], vector<T>(dims[i + 1], dice()));\n            matrices.push_back(matrix);\n        } else {\n            vector<vector<T>> matrix(dims[i], vector<T>(dims[i + 1], data));\n            matrices.push_back(matrix);\n        }\n    }\n}\n\nvoid time_test(const vector<int> &dims) {\n    vector<vector<vector<int>>> matrices;\n    init_matrices<int>(matrices, dims, 1, true);\n    vector<vector<int>> out;\n    boost::timer::cpu_timer t;\n\n    // matrix chain using DP\n    t.start();\n    out = al::chain_matmul<int>(matrices);\n    t.stop();\n    boost::timer::cpu_times const et1(t.elapsed());\n    cout << boost::timer::format(et1) << endl;\n\n    out.clear();\n\n    // naive matrix chain\n    out = matrices[0];\n    t.start();\n    for (int i = 1; i < matrices.size(); i++) {\n        out = al::matmul(out, matrices[i]);\n    }\n    t.stop();\n    boost::timer::cpu_times const et2(t.elapsed());\n    cout << boost::timer::format(et2);\n}", "meta": {"hexsha": "07a5b996a852291f63789d1ba71b5fb937ec8432", "size": 4864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/verify.cpp", "max_stars_repo_name": "pskrunner14/cpp-practice", "max_stars_repo_head_hexsha": "c59928bb9b91204588a0bafdc9f42deaacc64d29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-14T14:17:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-02T00:20:52.000Z", "max_issues_repo_path": "tests/verify.cpp", "max_issues_repo_name": "pskrunner14/cpp-practice", "max_issues_repo_head_hexsha": "c59928bb9b91204588a0bafdc9f42deaacc64d29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-28T19:45:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-28T19:50:02.000Z", "max_forks_repo_path": "tests/verify.cpp", "max_forks_repo_name": "pskrunner14/cpp-practice", "max_forks_repo_head_hexsha": "c59928bb9b91204588a0bafdc9f42deaacc64d29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-29T19:58:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-29T19:58:08.000Z", "avg_line_length": 33.5448275862, "max_line_length": 110, "alphanum_fraction": 0.6305509868, "num_tokens": 1328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.5168071840070122}}
{"text": "//  Boost static_min_max.hpp test program  -----------------------------------//\r\n\r\n//  (C) Copyright Daryle Walker 2001.  Permission to copy, use, modify, sell\r\n//  and distribute this software is granted provided this copyright\r\n//  notice appears in all copies.  This software is provided \"as is\" without\r\n//  express or implied warranty, and with no claim as to its suitability for\r\n//  any purpose.\r\n\r\n//  See http://www.boost.org for most recent version including documentation.\r\n\r\n//  Revision History\r\n//  23 Sep 2001  Initial version (Daryle Walker)\r\n\r\n#define  BOOST_INCLUDE_MAIN\r\n#include <boost/test/test_tools.hpp>  // for main, BOOST_TEST\r\n\r\n#include <boost/cstdlib.hpp>                 // for boost::exit_success\r\n#include <boost/integer/static_min_max.hpp>  // for boost::static_signed_min, etc.\r\n\r\n#include <iostream>  // for std::cout (std::endl indirectly)\r\n\r\n\r\n// Main testing function\r\nint\r\ntest_main\r\n(\r\n    int         ,   // \"argc\" is unused\r\n    char *      []  // \"argv\" is unused\r\n)\r\n{    \r\n    using std::cout;\r\n    using std::endl;\r\n    using boost::static_signed_min;\r\n    using boost::static_signed_max;\r\n    using boost::static_unsigned_min;\r\n    using boost::static_unsigned_max;\r\n\r\n    // Two positives\r\n    cout << \"Doing tests with two positive values.\" << endl;\r\n\r\n    BOOST_TEST( (static_signed_min< 9, 14>::value) ==  9 );\r\n    BOOST_TEST( (static_signed_max< 9, 14>::value) == 14 );\r\n    BOOST_TEST( (static_signed_min<14,  9>::value) ==  9 );\r\n    BOOST_TEST( (static_signed_max<14,  9>::value) == 14 );\r\n\r\n    BOOST_TEST( (static_unsigned_min< 9, 14>::value) ==  9 );\r\n    BOOST_TEST( (static_unsigned_max< 9, 14>::value) == 14 );\r\n    BOOST_TEST( (static_unsigned_min<14,  9>::value) ==  9 );\r\n    BOOST_TEST( (static_unsigned_max<14,  9>::value) == 14 );\r\n\r\n    // Two negatives\r\n    cout << \"Doing tests with two negative values.\" << endl;\r\n\r\n    BOOST_TEST( (static_signed_min<  -8, -101>::value) == -101 );\r\n    BOOST_TEST( (static_signed_max<  -8, -101>::value) ==   -8 );\r\n    BOOST_TEST( (static_signed_min<-101,   -8>::value) == -101 );\r\n    BOOST_TEST( (static_signed_max<-101,   -8>::value) ==   -8 );\r\n\r\n    // With zero\r\n    cout << \"Doing tests with zero and a positive or negative value.\" << endl;\r\n\r\n    BOOST_TEST( (static_signed_min< 0, 14>::value) ==  0 );\r\n    BOOST_TEST( (static_signed_max< 0, 14>::value) == 14 );\r\n    BOOST_TEST( (static_signed_min<14,  0>::value) ==  0 );\r\n    BOOST_TEST( (static_signed_max<14,  0>::value) == 14 );\r\n\r\n    BOOST_TEST( (static_unsigned_min< 0, 14>::value) ==  0 );\r\n    BOOST_TEST( (static_unsigned_max< 0, 14>::value) == 14 );\r\n    BOOST_TEST( (static_unsigned_min<14,  0>::value) ==  0 );\r\n    BOOST_TEST( (static_unsigned_max<14,  0>::value) == 14 );\r\n\r\n    BOOST_TEST( (static_signed_min<   0, -101>::value) == -101 );\r\n    BOOST_TEST( (static_signed_max<   0, -101>::value) ==    0 );\r\n    BOOST_TEST( (static_signed_min<-101,    0>::value) == -101 );\r\n    BOOST_TEST( (static_signed_max<-101,    0>::value) ==    0 );\r\n\r\n    // With identical\r\n    cout << \"Doing tests with two identical values.\" << endl;\r\n\r\n    BOOST_TEST( (static_signed_min<0, 0>::value) == 0 );\r\n    BOOST_TEST( (static_signed_max<0, 0>::value) == 0 );\r\n    BOOST_TEST( (static_unsigned_min<0, 0>::value) == 0 );\r\n    BOOST_TEST( (static_unsigned_max<0, 0>::value) == 0 );\r\n\r\n    BOOST_TEST( (static_signed_min<14, 14>::value) == 14 );\r\n    BOOST_TEST( (static_signed_max<14, 14>::value) == 14 );\r\n    BOOST_TEST( (static_unsigned_min<14, 14>::value) == 14 );\r\n    BOOST_TEST( (static_unsigned_max<14, 14>::value) == 14 );\r\n\r\n    BOOST_TEST( (static_signed_min< -101, -101>::value) == -101 );\r\n    BOOST_TEST( (static_signed_max< -101, -101>::value) == -101 );\r\n\r\n    return boost::exit_success;\r\n}\r\n", "meta": {"hexsha": "783b2ec59673ea1757788d5ce44a69d67cd5e3a7", "size": 3778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/integer/test/static_min_max_test.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/integer/test/static_min_max_test.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/libs/integer/test/static_min_max_test.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7684210526, "max_line_length": 83, "alphanum_fraction": 0.6140815246, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5168071823590846}}
{"text": "/*\n * Copyright (c) 2011-2014 Burkhard Ritter\n * This code is distributed under the two-clause BSD License.\n */\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE system test\n#include <boost/test/unit_test.hpp>\n\n#include <ctime>\n#include \"basis.hpp\"\n#include \"system.hpp\"\n\ntemplate<class System>\nclass HubbardHamiltonian : public Hamiltonian<System>\n{\npublic:\n    SMatrix& H;\n    System& s;\n\npublic:\n    HubbardHamiltonian (System& s_) \n        : Hamiltonian<System>(s_), H(Hamiltonian<System>::H), s(s_)\n    {}\n\n    void construct ()\n    {\n        H = SMatrix(s.basis.size(), s.basis.size());\n        H.setZero();\n        for (size_t i=0; i<s.N_sites; i++)\n        {\n            for (int spin=0; spin<2; spin++)\n            {\n                H += s.t * s.creator(2*i+spin) * s.annihilator(2* ((i+1)%s.N_sites) +spin);\n                H += s.t * s.creator(2* ((i+1)%s.N_sites) +spin) * s.annihilator(2*i+spin);\n            }\n            H += s.U * s.creator(2*i) * s.annihilator(2*i) *\n                       s.creator(2*i+1) * s.annihilator(2*i+1);\n        }\n    }\n};\n\nclass HubbardSystem\n{\npublic:\n    typedef HubbardSystem Self;\n\n    size_t N_sites;\n    size_t N_orbitals;\n    \n    Basis basis;\n    Creator<Self> creator;\n    Annihilator<Self> annihilator;\n    HubbardHamiltonian<Self> H;\n    EnsembleAverage<Self> measure;\n    \n    ParticleNumberSymmetryOperator N;\n    SpinSymmetryOperator S;\n    bool exploitSymmetries;\n    double t, U;\n\npublic:\n    HubbardSystem (size_t N_sites_, bool exploitSymmetries_ = false) \n        : N_sites(N_sites_), N_orbitals(2*N_sites_), \n          creator(*this), annihilator(*this), H(*this), measure(*this),\n          exploitSymmetries(exploitSymmetries_), t(1), U(10)\n    {\n        if (exploitSymmetries)\n        {\n            basis.addSymmetryOperator(&N);\n            basis.addSymmetryOperator(&S);\n        }\n        construct();\n    }\n    \n    void construct ()\n    {\n        basis.construct(N_orbitals);\n        creator.construct();\n        annihilator.construct();\n    }\n\n    void update()\n    {\n        H.construct();\n        H.diagonalize();\n    }\n};\n\ntemplate<class System>\nclass DoubleOccupancy\n{\nprivate:\n    const System& s;\n\npublic:\n    DoubleOccupancy (const System& s_)\n    : s(s_)\n    {}\n\n    SMatrix operator() (size_t site) const\n    {\n        return \n            s.creator(2*site) * s.annihilator(2*site) *\n            s.creator(2*site+1) * s.annihilator(2*site+1);\n    }\n};\n\nbool epsilonEqual (double v, double w, double epsilon = 10E-10)\n{\n    return fabs(v-w) < epsilon;\n}\n\nBOOST_AUTO_TEST_CASE ( construct_system_without_symmetries )\n{\n    HubbardSystem s(2);\n    s.H.construct();\n    BOOST_CHECK (s.basis.getRanges().size() == 1);\n    \n    s.H.diagonalize();\n    DVector eigenvalues = s.H.eigenvalues();\n    auto& eigenvectors = s.H.eigenvectorsBySector();\n\n    BOOST_CHECK (eigenvalues.size() == 16);\n    BOOST_CHECK (eigenvectors.size() == 1);\n    BOOST_CHECK (eigenvectors[0].cols() == 16);\n}\n\nBOOST_AUTO_TEST_CASE ( construct_system_with_symmetries )\n{\n    HubbardSystem s(4, true);\n    s.H.construct();\n    BOOST_CHECK (s.basis.getRanges().size() > 1);\n\n    s.H.diagonalize();\n    DVector eigenvalues = s.H.eigenvalues();\n    auto& eigenvectors = s.H.eigenvectorsBySector();\n    \n    BOOST_CHECK (eigenvalues.size() == 256);\n    BOOST_CHECK (eigenvectors.size() == 25);\n    int n = 0;\n    for (auto i=eigenvectors.begin(); i!=eigenvectors.end(); i++)\n        n += i->cols();\n    BOOST_CHECK (n == 256);\n}\n\nBOOST_AUTO_TEST_CASE ( construct_and_diagonalize_system_multiple_times )\n{\n    HubbardSystem s(4, true);\n    s.H.construct();\n    size_t n_b1 = s.basis.size();\n    size_t n_r1 = s.basis.getRanges().size();\n    \n    s.H.diagonalize();\n    DVector ev1 = s.H.eigenvalues();\n\n    s.H.construct();\n    size_t n_b2 = s.basis.size();\n    size_t n_r2 = s.basis.getRanges().size();\n    BOOST_CHECK (n_b1 == n_b2);\n    BOOST_CHECK (n_r1 == n_r2);\n   \n    s.H.diagonalize();\n    DVector ev2 = s.H.eigenvalues();\n\n    BOOST_CHECK (ev1 == ev2);\n}\n\nBOOST_AUTO_TEST_CASE ( test_by_sector_eigenvalue_and_eigenvectors_accessors )\n{\n    HubbardSystem s(4, true);\n    s.H.construct();\n   \n    s.H.diagonalize();\n    auto eigenvalues1 = s.H.eigenvaluesBySector();\n    auto energies1 = s.H.eigenvalues();\n\n    BOOST_CHECK (eigenvalues1.size() > 1);\n    BOOST_CHECK (eigenvalues1[0].size() > 0);\n    BOOST_CHECK (energies1.size() == 256);\n\n    DVector ev(256);\n    int k = 0;\n    for (size_t j=0; j<eigenvalues1.size(); j++)\n        for (int i=0; i<eigenvalues1[j].size(); i++)\n        {\n            ev(k) = eigenvalues1[j](i);\n            k++;\n        }\n    BOOST_CHECK (k == 256);\n    BOOST_CHECK (energies1 == ev);\n\n    // test that eigenvectors get properly reset and reconstructed\n    s.H.diagonalize();\n    auto energies2 = s.H.eigenvalues();\n    BOOST_CHECK (energies2.size() == 256);\n\n    s.t = 1000;\n    s.U = 20000;\n    s.H.construct();\n    s.H.diagonalize();\n    auto energies3 = s.H.eigenvalues();\n\n    double diff = 0;\n    for (int i=0; i<256; i++)\n        diff += std::abs(energies2(i) - energies3(i));\n    BOOST_CHECK ( diff > 1 );\n}\n\nBOOST_AUTO_TEST_CASE ( measure_double_occupancy )\n{\n    HubbardSystem s(4, true);\n    DoubleOccupancy<HubbardSystem> DO(s);\n    s.H.construct();\n    \n    s.H.diagonalize();\n    double doLowT = s.measure(1000, DO(0));\n    double doMidT = s.measure(1, DO(0));\n    double doHighT = s.measure(0.00001, DO(0));\n\n    BOOST_CHECK (epsilonEqual(doLowT, 0, 10E-2));\n    BOOST_CHECK (epsilonEqual(doMidT, 0.00453281, 10E-6));\n    BOOST_CHECK (epsilonEqual(doHighT, 0.25, 10E-2));\n}\n\nBOOST_AUTO_TEST_CASE ( performance_of_diagonalization )\n{\n    std::clock_t startCPUTime, endCPUTime;\n    double cpuTime = 0;\n    size_t sites;\n#ifdef NDEBUG\n    sites = 7;\n#else\n    sites = 5;\n#endif\n\n    startCPUTime = std::clock();\n    HubbardSystem s(sites, true);\n    DoubleOccupancy<HubbardSystem> DO(s);\n    s.H.construct();\n    endCPUTime = std::clock();\n    cpuTime = static_cast<double>(endCPUTime-startCPUTime)/CLOCKS_PER_SEC;\n    std::cerr << \"Time for construction of system with \" << sites \n              << \" sites: \" << cpuTime << \"s\" << std::endl;\n\n    startCPUTime = std::clock();\n    s.H.diagonalize();\n    endCPUTime = std::clock();\n    cpuTime = static_cast<double>(endCPUTime-startCPUTime)/CLOCKS_PER_SEC;\n    std::cerr << \"Time for diagonalize of system with \" << sites \n              << \" sites: \" << cpuTime << \"s\" << std::endl;\n\n    startCPUTime = std::clock();\n    s.measure(1, DO(0));\n    endCPUTime = std::clock();\n    cpuTime = static_cast<double>(endCPUTime-startCPUTime)/CLOCKS_PER_SEC;\n    std::cerr << \"Time for ensembleAverage of system with \" << sites \n              << \" sites: \" << cpuTime << \"s\" << std::endl;\n}\n", "meta": {"hexsha": "633fc54788c1450bdcbbdfd7e73c9d73a5cb0a84", "size": 6729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/systemTest.cpp", "max_stars_repo_name": "meznom/qca", "max_stars_repo_head_hexsha": "8b7cfa6f36ab17202fce5bb953321d33abdf9eb7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-07-11T01:56:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-03T09:13:07.000Z", "max_issues_repo_path": "tests/systemTest.cpp", "max_issues_repo_name": "meznom/qca", "max_issues_repo_head_hexsha": "8b7cfa6f36ab17202fce5bb953321d33abdf9eb7", "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/systemTest.cpp", "max_forks_repo_name": "meznom/qca", "max_forks_repo_head_hexsha": "8b7cfa6f36ab17202fce5bb953321d33abdf9eb7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9806949807, "max_line_length": 91, "alphanum_fraction": 0.606330807, "num_tokens": 1947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5168071792730673}}
{"text": "#ifndef INCLUDED_chemical_stub_HH\n#define INCLUDED_chemical_stub_HH\n\n#include <Eigen/Geometry>\n\nnamespace scheme {\nnamespace chemical {\n\n\n    template<class Xform,class InputPoint>\n    Xform make_stub(InputPoint cen, InputPoint n, InputPoint ca, InputPoint c){\n        typedef Eigen::Matrix< typename Xform::Scalar, 3, 1 > XPoint;\n        XPoint _n, _ca, _c, _cen;\n        for( int i = 0; i < 3; ++i){\n            _n  [i] = n  [i];\n            _ca [i] = ca [i];\n            _c  [i] = c  [i];\n            _cen[i] = cen[i];\n        }\n        Xform out;\n        XPoint e1( _n - _ca );\n        e1.normalize();\n        XPoint e3( e1.cross(_c-_ca) );\n        e3.normalize();\n        XPoint e2( e3.cross(e1) );\n        out.linear().col(0) = e1;\n        out.linear().col(1) = e2;\n        out.linear().col(2) = e3;\n        out.translation() = _cen;\n        return out;\n    }\n\n    template<class Xform,class InputPoint>\n    Xform make_stub(InputPoint n, InputPoint ca, InputPoint c){\n        return make_stub<Xform>( ca, n, ca, c );\n    }\n\n}\n}\n\n#endif\n", "meta": {"hexsha": "bd41942501e2f6d747e31ceaac27bbcb66398d45", "size": 1042, "ext": "hh", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/chemical/stub.hh", "max_stars_repo_name": "YaoYinYing/rifdock", "max_stars_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T01:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:16:08.000Z", "max_issues_repo_path": "schemelib/scheme/chemical/stub.hh", "max_issues_repo_name": "YaoYinYing/rifdock", "max_issues_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-30T17:45:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:02:44.000Z", "max_forks_repo_path": "schemelib/scheme/chemical/stub.hh", "max_forks_repo_name": "YaoYinYing/rifdock", "max_forks_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T01:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:56:17.000Z", "avg_line_length": 24.8095238095, "max_line_length": 79, "alphanum_fraction": 0.5479846449, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5167365388754284}}
{"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\n#include \"mesh_param.h\"\n\nusing namespace std;\nusing namespace Eigen;\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  // This code works only for n==1, see tutorial_nrosy_complete for a generic implementation that works for n >= 1\n  assert(n==1);\n\n  Matrix<double,Eigen::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      // 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  // 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, c * 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  // Debugging informations\n  #ifdef DEBUG_1\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 << \"soft_id: \" << soft_id.rows() << \" * \" << soft_id.cols() << endl;\n  cout << \"soft_value: \" << soft_value.rows() << \" * \" << soft_value.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 << \"tb: \" << tb.size() << endl;\n  cout << \"count = \" << count << endl;\n  cout << \"A: \" << A.rows() << \" * \" << A.cols() << endl;\n  cout << \"A*: \" << A.adjoint().rows() << \" * \" << A.adjoint().cols() << endl;\n  cout << \"b: \" << b.rows() << \" * \" << b.cols() << endl;\n  cout << \"u: \" << u.rows() << \" * \" << u.cols() << endl;\n  #endif\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    R.row(f) = T1.row(f) * u(f).real() + T2.row(f) * u(f).imag();\n  \n  #ifdef DEBUG_4\n  cout << \"final locations and values: \";\n  for (int i = 0; i < soft_id.size(); i++) {\n      cout << soft_id(i) << \",\" << u(soft_id(i)) << \" \";\n  }\n  cout << endl;\n  cout << \"final locations and coordinates: \";\n  for (int i = 0; i < soft_id.size(); i++) {\n      cout << soft_id(i) << \",\" << R.row(soft_id(i)) << \" \";\n  }\n  cout << endl;\n  cout << \"original locations and coordinates: \";\n  for (int i = 0; i < soft_id.size(); i++) {\n      cout << soft_id(i) << \",\" << soft_value.row(i) << \" \";\n  }\n  cout << endl;\n  #endif\n  \n  return R;\n}", "meta": {"hexsha": "932d3504e4a61a506319b84499290747f53e91a3", "size": 5204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lab4/src/tutorial_nrosy.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.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.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": 37.7101449275, "max_line_length": 114, "alphanum_fraction": 0.581283628, "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5166382369200422}}
{"text": "\n#include <multi-camera-motion/approx_relpose_generalized.h>\n#include <multi-camera-motion/translation.h>\n\n#include <Eigen/Geometry>\n\n#include \"problem.h\"\n#include \"so3.h\"\n\n#include <iostream>\n\n#include <cstdlib>\n#include <ctime>\n\nstatic Eigen::Vector2d project( const Eigen::Vector3d &x )\n{\n    return x.head(2)/x[2];\n}\n\nstatic Eigen::Matrix<double,6,1> pluecker( const Ray & ray )\n{\n    // make ray in Pluecker coordinates\n    Eigen::Vector3d d = ray.x/ray.x.norm();\n    Eigen::Vector3d m = ray.c.cross(d);\n    Eigen::Matrix<double,6,1> p;\n    p.head(3) = d;\n    p.tail(3) = m;\n    return p;\n}\n\nstatic Eigen::Matrix<double,6,6> make_w( const RayPair &ray_pair )\n{\n    Eigen::Matrix<double,6,1> u = pluecker(ray_pair.first);\n    Eigen::Matrix<double,6,1> v = pluecker(ray_pair.second);\n    return u*v.transpose();\n}\n\nint main( int argc, char **argv )\n{\n    srand(time(NULL));\n\n    const double trans_mag = 1.;\n    const double angle = 5.*M_PI/180.;\n    const double noise = 0;\n\n    Problem prob;\n    generateProblem( trans_mag, angle, noise, prob );\n\n    Eigen::MatrixXd x(2,6);\n    Eigen::MatrixXd y(2,6);\n    Eigen::MatrixXd cu(3,6);\n    Eigen::MatrixXd cv(3,6);\n    for ( int i = 0; i < 6; i++ )\n    {\n        x.col(i) = project(prob.ray_pairs[i].first.x);\n        y.col(i) = project(prob.ray_pairs[i].second.x);\n        cu.col(i) = prob.ray_pairs[i].first.c;\n        cv.col(i) = prob.ray_pairs[i].second.c;\n    }\n    \n    Eigen::Matrix<double,6,6> w1;\n    Eigen::Matrix<double,6,6> w2;\n    Eigen::Matrix<double,6,6> w3;\n    Eigen::Matrix<double,6,6> w4;\n    Eigen::Matrix<double,6,6> w5;\n    Eigen::Matrix<double,6,6> w6;\n    std::vector<Eigen::Vector3d> rsolns;\n\n    w1 = make_w(prob.ray_pairs[0]);\n    w2 = make_w(prob.ray_pairs[1]);\n    w3 = make_w(prob.ray_pairs[2]);\n    w4 = make_w(prob.ray_pairs[3]);\n    w5 = make_w(prob.ray_pairs[4]);\n    w6 = make_w(prob.ray_pairs[5]);\n    approx_relpose_generalized(w1,w2,w3,w4,w5,w6,rsolns);\n    \n    for ( int i = 0; i < rsolns.size(); i++ )\n    {\n        Eigen::Matrix3d Rsoln = so3exp(rsolns[i]);\n        Eigen::Vector3d tsoln = solve_translation(x,y,cu,cv,Rsoln);\n        double rot_angle_err, trans_angle_err, trans_scale_err;\n        compute_error( prob.R, prob.t,\n                       Rsoln, tsoln,\n                       rot_angle_err, trans_angle_err, trans_scale_err );\n        std::cout << \"solution \" << i+1 << \" error: \";\n        std::cout << \"\\trotation error: \" << rot_angle_err*180./M_PI << \" deg\\n\";\n        std::cout << \"\\ttranslation error: \" << trans_angle_err*180./M_PI << \" deg\\n\";\n        std::cout << \"\\ttranslation scale error: \" << trans_scale_err << \"\\n\";\n    }\n        \n}\n", "meta": {"hexsha": "3cd4c33cc34173c6e000a9b579a8e15cdd9bcaa0", "size": 2653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_approx.cpp", "max_stars_repo_name": "MikhailTerekhov/multi-camera-motion", "max_stars_repo_head_hexsha": "acefa9e9b659b46dfee48b5091a8acb0ff5a0ecf", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2016-07-25T12:28:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T03:51:27.000Z", "max_issues_repo_path": "test/test_approx.cpp", "max_issues_repo_name": "MikhailTerekhov/multi-camera-motion", "max_issues_repo_head_hexsha": "acefa9e9b659b46dfee48b5091a8acb0ff5a0ecf", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-09-18T15:42:27.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-20T03:27:25.000Z", "max_forks_repo_path": "test/test_approx.cpp", "max_forks_repo_name": "MikhailTerekhov/multi-camera-motion", "max_forks_repo_head_hexsha": "acefa9e9b659b46dfee48b5091a8acb0ff5a0ecf", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-02-27T11:32:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T23:12:17.000Z", "avg_line_length": 28.8369565217, "max_line_length": 86, "alphanum_fraction": 0.6038447041, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5166177306912654}}
{"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// Peter Sonneveld and Martin B. van Gijzen, IDR(s): a family of simple and fast algorithms for solving large nonsymmetric linear systems. \n// SIAM J. Sci. Comput. Vol. 31, No. 2, pp. 1035-1062 (2008). (copyright SIAM)\n\n#ifndef ITL_IDR_S_INCLUDE\n#define ITL_IDR_S_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/operation/random.hpp>\n#include <boost/numeric/mtl/operation/orth.hpp>\n#include <boost/numeric/mtl/operation/resource.hpp>\n#include <boost/numeric/mtl/matrix/strict_upper.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n#include <boost/numeric/itl/krylov/base_solver.hpp>\n\nnamespace itl {\n\n/// Induced Dimension Reduction on s dimensions (IDR(s)) \ntemplate < typename LinearOperator, typename Vector, \n\t   typename LeftPreconditioner, typename RightPreconditioner, \n\t   typename Iteration >\nint idr_s(const LinearOperator &A, Vector &x, const Vector &b,\n\t  const LeftPreconditioner &, const RightPreconditioner &, \n\t  Iteration& iter, size_t s)\n{\n    mtl::vampir_trace<7010> tracer;\n    using mtl::size; using mtl::iall; using mtl::mat::strict_upper;\n    typedef typename mtl::Collection<Vector>::value_type Scalar;\n    typedef typename mtl::Collection<Vector>::size_type  Size;\n\n    if (size(b) == 0) throw mtl::logic_error(\"empty rhs vector\");\n    if (s < 1) s= 1;\n\n    const Scalar                zero= math::zero(Scalar());\n    Scalar                      omega(zero);\n    Vector                      x0(x), y(resource(x)), v(resource(x)), t(resource(x)), q(resource(x)), r(b - A * x);\n    mtl::mat::multi_vector<Vector>   dR(Vector(resource(x), zero), s), dX(Vector(resource(x), zero), s), P(Vector(resource(x), zero), s);\n    mtl::dense_vector<Scalar>   m(s), c(s), dm(s);   // replicated in distributed solvers \n    mtl::mat::dense2D<Scalar>        M(s, s);             // dito\n\n    random(P); \n    P.vector(0)= r;\n    orth(P);\n\n    for (size_t k= 0; k < s; k++) {\n\tv= A * r;\n\tomega= dot(v, r) / dot(v, v);\n\tdX.vector(k)= omega * r;\n\tdR.vector(k)= -omega * v;\n\tx+= dX.vector(k); \n\tr+= dR.vector(k);\n\tif ((++iter).finished(r)) return iter;\n\tM[iall][k]= trans(P) * dR.vector(k); \n    }\n\n    Size oldest= 0;\n    m= trans(P) * r;\n\n    while (! iter.finished(r)) {\n       \n\tfor (size_t k= 0; k < s; k++) {\n\t    c= lu_solve(M, m);\n\t    q= dR * -c;    \n\t    v= r + q;\n\t    if (k == 0) {\n\t\tt= A * v;\n\t\tomega= dot(t, v) / dot(t, t);\n\t\tdR.vector(oldest)= q - omega * t;\n\t\tdX.vector(oldest)= omega * v - dX * c;\n\t    } else {\n\t\tdX.vector(oldest)= omega * v - dX * c;\n\t\tdR.vector(oldest)= A * -dX.vector(oldest);\n\t    }\n\t    r+= dR.vector(oldest);\n\t    x+= dX.vector(oldest);\n\n\t    if ((++iter).finished(r))\n\t\treturn iter;\n\n\t    dm= trans(P) * dR.vector(oldest);\n\t    M[iall][oldest]= dm;\n\t    m+= dm;\n\t    oldest= (oldest + 1) % s;\n\t}\n    }\n    return iter;\n}\n\n/// Solver class for IDR(s) method; right preconditioner ignored (prints warning if not identity)\n/** Methods inherited from \\ref base_solver. **/\ntemplate < typename LinearOperator, typename Preconditioner= pc::identity<LinearOperator>, \n\t   typename RightPreconditioner= pc::identity<LinearOperator> >\nclass idr_s_solver\n  : public base_solver< idr_s_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator >\n{\n    typedef base_solver< idr_s_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator > base;\n  public:\n  public:\n    /// Construct solver from a linear operator; generate (left) preconditioner from it\n    explicit idr_s_solver(const LinearOperator& A, size_t s= 8) : base(A), s(s), L(A), R(A) {}\n\n    /// Construct solver from a linear operator and left preconditioner\n    idr_s_solver(const LinearOperator& A, size_t s, const Preconditioner& L) : base(A), s(s), L(L), R(A) {}\n\n    /// Construct solver from a linear operator and left preconditioner\n    idr_s_solver(const LinearOperator& A, size_t s, const Preconditioner& L, const RightPreconditioner& R) \n      : base(A), s(s), L(L), R(R) {}\n\n    /// Solve linear system approximately as specified by \\p iter\n    template < typename HilbertSpaceX, typename HilbertSpaceB, typename Iteration >\n    int solve(HilbertSpaceX& x, const HilbertSpaceB& b, Iteration& iter) const\n    {\n\treturn idr_s(this->A, x, b, L, R, iter, s);\n    }\n\n  private:\n    size_t                s;\n    Preconditioner        L;\n    RightPreconditioner   R;\n};\n\n\n} // namespace itl\n\n#endif // ITL_IDR_S_INCLUDE\n", "meta": {"hexsha": "f20aa1e2d7c93712e99f8d31f9b0f0ab5a0aeb4f", "size": 5051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/krylov/idr_s.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": "boost/numeric/itl/krylov/idr_s.hpp", "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": "boost/numeric/itl/krylov/idr_s.hpp", "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": 35.5704225352, "max_line_length": 139, "alphanum_fraction": 0.6580875074, "num_tokens": 1454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5166177257517698}}
{"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    testGaussianBayesNet.cpp\n * @brief   Unit tests for GaussianBayesNet\n * @author  Frank Dellaert\n */\n\n#include <gtsam/linear/GaussianBayesNet.h>\n#include <gtsam/linear/JacobianFactor.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/base/Testable.h>\n#include <gtsam/base/numericalDerivative.h>\n\n#include <CppUnitLite/TestHarness.h>\n#include <boost/tuple/tuple.hpp>\n#include <boost/assign/list_of.hpp>\n#include <boost/assign/std/list.hpp> // for operator +=\n#include <boost/bind/bind.hpp>\n\n// STL/C++\n#include <iostream>\n#include <sstream>\n\nusing namespace boost::assign;\nusing namespace boost::placeholders;\nusing namespace std;\nusing namespace gtsam;\n\nstatic const Key _x_ = 11, _y_ = 22, _z_ = 33;\n\nstatic GaussianBayesNet smallBayesNet =\n    list_of(GaussianConditional(_x_, Vector1::Constant(9), I_1x1, _y_, I_1x1))(\n        GaussianConditional(_y_, Vector1::Constant(5), I_1x1));\n\nstatic GaussianBayesNet noisyBayesNet =\n    list_of(GaussianConditional(_x_, Vector1::Constant(9), I_1x1, _y_, I_1x1,\n                                noiseModel::Isotropic::Sigma(1, 2.0)))(\n        GaussianConditional(_y_, Vector1::Constant(5), I_1x1,\n                            noiseModel::Isotropic::Sigma(1, 3.0)));\n\n/* ************************************************************************* */\nTEST( GaussianBayesNet, Matrix )\n{\n  Matrix R; Vector d;\n  boost::tie(R,d) = smallBayesNet.matrix(); // find matrix and RHS\n\n  Matrix R1 = (Matrix2() <<\n          1.0, 1.0,\n          0.0, 1.0\n    ).finished();\n  Vector d1 = Vector2(9.0, 5.0);\n\n  EXPECT(assert_equal(R,R1));\n  EXPECT(assert_equal(d,d1));\n}\n\n/* ************************************************************************* */\nTEST( GaussianBayesNet, NoisyMatrix )\n{\n  Matrix R; Vector d;\n  boost::tie(R,d) = noisyBayesNet.matrix(); // find matrix and RHS\n\n  Matrix R1 = (Matrix2() <<\n          0.5, 0.5,\n          0.0, 1./3.\n    ).finished();\n  Vector d1 = Vector2(9./2., 5./3.);\n\n  EXPECT(assert_equal(R,R1));\n  EXPECT(assert_equal(d,d1));\n}\n\n/* ************************************************************************* */\nTEST(GaussianBayesNet, Optimize) {\n  VectorValues expected =\n      map_list_of<Key, Vector>(_x_, Vector1::Constant(4))(_y_, Vector1::Constant(5));\n  VectorValues actual = smallBayesNet.optimize();\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(GaussianBayesNet, NoisyOptimize) {\n  Matrix R;\n  Vector d;\n  boost::tie(R, d) = noisyBayesNet.matrix();  // find matrix and RHS\n  const Vector x = R.inverse() * d;\n  VectorValues expected = map_list_of<Key, Vector>(_x_, x.head(1))(_y_, x.tail(1));\n\n  VectorValues actual = noisyBayesNet.optimize();\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianBayesNet, optimizeIncomplete )\n{\n  static GaussianBayesNet incompleteBayesNet = list_of\n    (GaussianConditional(_x_, Vector1::Constant(9), I_1x1, _y_, I_1x1));\n\n  VectorValues solutionForMissing = map_list_of<Key, Vector>\n    (_y_, Vector1::Constant(5));\n\n  VectorValues actual = incompleteBayesNet.optimize(solutionForMissing);\n\n  VectorValues expected = map_list_of<Key, Vector>\n    (_x_, Vector1::Constant(4))\n    (_y_, Vector1::Constant(5));\n\n  EXPECT(assert_equal(expected,actual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianBayesNet, optimize3 )\n{\n  // y = R*x, x=inv(R)*y\n  // 4 = 1 1   -1\n  // 5     1    5\n  // NOTE: we are supplying a new RHS here\n\n  VectorValues expected = map_list_of<Key, Vector>\n    (_x_, Vector1::Constant(-1))\n    (_y_, Vector1::Constant(5));\n\n  // Test different RHS version\n  VectorValues gx = map_list_of<Key, Vector>\n    (_x_, Vector1::Constant(4))\n    (_y_, Vector1::Constant(5));\n  VectorValues actual = smallBayesNet.backSubstitute(gx);\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(GaussianBayesNet, ordering)\n{\n  Ordering expected;\n  expected += _x_, _y_;\n  const auto actual = noisyBayesNet.ordering();\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianBayesNet, MatrixStress )\n{\n  GaussianBayesNet bn;\n  using GC = GaussianConditional;\n  bn.emplace_shared<GC>(_x_, Vector2(1, 2), 1 * I_2x2, _y_, 2 * I_2x2, _z_, 3 * I_2x2);\n  bn.emplace_shared<GC>(_y_, Vector2(3, 4), 4 * I_2x2, _z_, 5 * I_2x2);\n  bn.emplace_shared<GC>(_z_, Vector2(5, 6), 6 * I_2x2);\n\n  const VectorValues expected = bn.optimize();\n  for (const auto& keys :\n       {KeyVector({_x_, _y_, _z_}), KeyVector({_x_, _z_, _y_}),\n        KeyVector({_y_, _x_, _z_}), KeyVector({_y_, _z_, _x_}),\n        KeyVector({_z_, _x_, _y_}), KeyVector({_z_, _y_, _x_})}) {\n    const Ordering ordering(keys);\n    Matrix R;\n    Vector d;\n    boost::tie(R, d) = bn.matrix(ordering);\n    EXPECT(assert_equal(expected.vector(ordering), R.inverse() * d));\n  }\n}\n\n/* ************************************************************************* */\nTEST( GaussianBayesNet, backSubstituteTranspose )\n{\n  // x=R'*y, expected=inv(R')*x\n  // 2 = 1    2\n  // 5   1 1  3\n  VectorValues\n    x = map_list_of<Key, Vector>\n      (_x_, Vector1::Constant(2))\n      (_y_, Vector1::Constant(5)),\n    expected = map_list_of<Key, Vector>\n      (_x_, Vector1::Constant(2))\n      (_y_, Vector1::Constant(3));\n\n  VectorValues actual = smallBayesNet.backSubstituteTranspose(x);\n  EXPECT(assert_equal(expected, actual));\n\n  const auto ordering = noisyBayesNet.ordering();\n  const Matrix R = smallBayesNet.matrix(ordering).first;\n  const Vector expected_vector = R.transpose().inverse() * x.vector(ordering);\n  EXPECT(assert_equal(expected_vector, actual.vector(ordering)));\n}\n\n/* ************************************************************************* */\nTEST( GaussianBayesNet, backSubstituteTransposeNoisy )\n{\n  // x=R'*y, expected=inv(R')*x\n  // 2 = 1    2\n  // 5   1 1  3\n  VectorValues\n    x = map_list_of<Key, Vector>\n      (_x_, Vector1::Constant(2))\n      (_y_, Vector1::Constant(5)),\n    expected = map_list_of<Key, Vector>\n      (_x_, Vector1::Constant(4))\n      (_y_, Vector1::Constant(9));\n\n  VectorValues actual = noisyBayesNet.backSubstituteTranspose(x);\n  EXPECT(assert_equal(expected, actual));\n\n  const auto ordering = noisyBayesNet.ordering();\n  const Matrix R = noisyBayesNet.matrix(ordering).first;\n  const Vector expected_vector = R.transpose().inverse() * x.vector(ordering);\n  EXPECT(assert_equal(expected_vector, actual.vector(ordering)));\n}\n\n/* ************************************************************************* */\n// Tests computing Determinant\nTEST( GaussianBayesNet, DeterminantTest )\n{\n  GaussianBayesNet cbn;\n  cbn += GaussianConditional(\n          0, Vector2(3.0, 4.0), (Matrix2() << 1.0, 3.0, 0.0, 4.0).finished(),\n          1, (Matrix2() << 2.0, 1.0, 2.0, 3.0).finished(), noiseModel::Isotropic::Sigma(2, 2.0));\n\n  cbn += GaussianConditional(\n          1, Vector2(5.0, 6.0), (Matrix2() << 1.0, 1.0, 0.0, 3.0).finished(),\n          2, (Matrix2() << 1.0, 0.0, 5.0, 2.0).finished(), noiseModel::Isotropic::Sigma(2, 2.0));\n\n  cbn += GaussianConditional(\n      3, Vector2(7.0, 8.0), (Matrix2() << 1.0, 1.0, 0.0, 5.0).finished(), noiseModel::Isotropic::Sigma(2, 2.0));\n\n  double expectedDeterminant = 60.0 / 64.0;\n  double actualDeterminant = cbn.determinant();\n\n  EXPECT_DOUBLES_EQUAL( expectedDeterminant, actualDeterminant, 1e-9);\n}\n\n/* ************************************************************************* */\nnamespace {\n  double computeError(const GaussianBayesNet& gbn, const Vector10& values)\n  {\n    pair<Matrix,Vector> Rd = GaussianFactorGraph(gbn).jacobian();\n    return 0.5 * (Rd.first * values - Rd.second).squaredNorm();\n  }\n}\n\n/* ************************************************************************* */\nTEST(GaussianBayesNet, ComputeSteepestDescentPoint) {\n\n  // Create an arbitrary Bayes Net\n  GaussianBayesNet gbn;\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n    0, Vector2(1.0,2.0), (Matrix2() << 3.0,4.0,0.0,6.0).finished(),\n    3, (Matrix2() << 7.0,8.0,9.0,10.0).finished(),\n    4, (Matrix2() << 11.0,12.0,13.0,14.0).finished()));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n    1, Vector2(15.0,16.0), (Matrix2() << 17.0,18.0,0.0,20.0).finished(),\n    2, (Matrix2() << 21.0,22.0,23.0,24.0).finished(),\n    4, (Matrix2() << 25.0,26.0,27.0,28.0).finished()));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n    2, Vector2(29.0,30.0), (Matrix2() << 31.0,32.0,0.0,34.0).finished(),\n    3, (Matrix2() << 35.0,36.0,37.0,38.0).finished()));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n    3, Vector2(39.0,40.0), (Matrix2() << 41.0,42.0,0.0,44.0).finished(),\n    4, (Matrix2() << 45.0,46.0,47.0,48.0).finished()));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n    4, Vector2(49.0,50.0), (Matrix2() << 51.0,52.0,0.0,54.0).finished()));\n\n  // Compute the Hessian numerically\n  Matrix hessian = numericalHessian<Vector10>(\n      boost::bind(&computeError, gbn, _1), Vector10::Zero());\n\n  // Compute the gradient numerically\n  Vector gradient = numericalGradient<Vector10>(\n      boost::bind(&computeError, gbn, _1), Vector10::Zero());\n\n  // Compute the gradient using dense matrices\n  Matrix augmentedHessian = GaussianFactorGraph(gbn).augmentedHessian();\n  LONGS_EQUAL(11, (long)augmentedHessian.cols());\n  Vector denseMatrixGradient = -augmentedHessian.col(10).segment(0,10);\n  EXPECT(assert_equal(gradient, denseMatrixGradient, 1e-5));\n\n  // Compute the steepest descent point\n  double step = -gradient.squaredNorm() / (gradient.transpose() * hessian * gradient)(0);\n  Vector expected = gradient * step;\n\n  // Compute the steepest descent point with the dogleg function\n  VectorValues actual = gbn.optimizeGradientSearch();\n\n  // Check that points agree\n  KeyVector keys {0, 1, 2, 3, 4};\n  Vector actualAsVector = actual.vector(keys);\n  EXPECT(assert_equal(expected, actualAsVector, 1e-5));\n\n  // Check that point causes a decrease in error\n  double origError = GaussianFactorGraph(gbn).error(VectorValues::Zero(actual));\n  double newError = GaussianFactorGraph(gbn).error(actual);\n  EXPECT(newError < origError);\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "c88bf87314958ecdd9c16113ec23ea501dc8d10d", "size": 10955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/tests/testGaussianBayesNet.cpp", "max_stars_repo_name": "acxz/gtsam", "max_stars_repo_head_hexsha": "cd3854a1f6db923d40ecf3ced56bafbe339d1b3c", "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": "gtsam/linear/tests/testGaussianBayesNet.cpp", "max_issues_repo_name": "acxz/gtsam", "max_issues_repo_head_hexsha": "cd3854a1f6db923d40ecf3ced56bafbe339d1b3c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/linear/tests/testGaussianBayesNet.cpp", "max_forks_repo_name": "acxz/gtsam", "max_forks_repo_head_hexsha": "cd3854a1f6db923d40ecf3ced56bafbe339d1b3c", "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.8006535948, "max_line_length": 112, "alphanum_fraction": 0.5922409859, "num_tokens": 3089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5166177183815295}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu) 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 \"print_values.hpp\"\n\n#include <mpllibs/metamonad/list.hpp>\n#include <mpllibs/metamonad/do_c.hpp>\n#include <mpllibs/metamonad/name.hpp>\n#include <mpllibs/metamonad/guard.hpp>\n#include <mpllibs/metamonad/pair.hpp>\n\n#include <boost/mpl/list_c.hpp>\n#include <boost/mpl/range_c.hpp>\n#include <boost/mpl/equal_to.hpp>\n\n#include <iostream>\n\nint main()\n{\n  using mpllibs::metamonad::do_c;\n  using mpllibs::metamonad::list_tag;\n  using mpllibs::metamonad::set;\n  using mpllibs::metamonad::do_return;\n  using mpllibs::metamonad::guard;\n  using mpllibs::metamonad::pair;\n\n  using boost::mpl::list_c;\n  using boost::mpl::range_c;\n  using boost::mpl::equal_to;\n\n  using namespace mpllibs::metamonad::name;\n\n  /*\n    List comprehension syntax in Haskell: [(i,j) | i <- [1,2], j <- [1..4]]\n\n    Do syntax in Haskell:\n      do i <- [1,2]\n         j <- [1..4]\n         return (i,j)\n\n    Result in Haskell: [(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)]\n   */\n\n  typedef\n    do_c<list_tag,\n      set<i, list_c<int, 1, 2> >,\n      set<j, range_c<int, 1, 5> >,\n      do_return<pair<i, j> >\n    >\n    result_of_list_comprehension;\n  \n  print_values<result_of_list_comprehension>();\n  std::cout << std::endl;\n\n  /*\n    List comprehension syntax in Haskell:\n      [(i,j) | i <- [1,2], j <- [1..4], i == j]\n\n    Do syntax in Haskell:\n      do i <- [1,2]\n         j <- [1..4]\n         Control.Monad.guard $ i == j\n         return (i,j)\n\n    Result in Haskell: [(1,1),(2,2)]\n   */\n\n  typedef\n    do_c<list_tag,\n      set<i, list_c<int, 1, 2> >,\n      set<j, range_c<int, 1, 5> >,\n      guard<list_tag, equal_to<i, j> >,\n      do_return<pair<i, j> >\n    >\n    result_of_list_comprehension_with_guard;\n  \n  print_values<result_of_list_comprehension_with_guard>();\n  std::cout << std::endl;\n}\n\n", "meta": {"hexsha": "1a1f2412c02fd6281245b1eaf9bda50789186c1f", "size": 1999, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/metamonad/example/list_comprehension/main.cpp", "max_stars_repo_name": "sabel83/mpllibs", "max_stars_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-01-15T09:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T15:49:31.000Z", "max_issues_repo_path": "libs/metamonad/example/list_comprehension/main.cpp", "max_issues_repo_name": "sabel83/mpllibs", "max_issues_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-06-18T19:25:34.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-13T19:49:51.000Z", "max_forks_repo_path": "libs/metamonad/example/list_comprehension/main.cpp", "max_forks_repo_name": "sabel83/mpllibs", "max_forks_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-07-10T08:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T07:17:57.000Z", "avg_line_length": 24.0843373494, "max_line_length": 75, "alphanum_fraction": 0.6193096548, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5166177158727787}}
{"text": "///////////////////////////////////////////////////////////////\r\n//  Copyright 2015 John Maddock. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\r\n\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <vector>\r\n#include <iterator>\r\n\r\n//[IE1\r\n\r\n/*`\r\nIn this simple example, we'll import/export the bits of a cpp_int \r\nto a vector of 8-bit unsigned values:\r\n*/\r\n/*=\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <vector>\r\n#include <iterator>\r\n*/\r\n\r\nint main()\r\n{\r\n   using boost::multiprecision::cpp_int;\r\n   // Create a cpp_int with just a couple of bits set:\r\n   cpp_int i;\r\n   bit_set(i, 5000); // set the 5000'th bit\r\n   bit_set(i, 200);\r\n   bit_set(i, 50);\r\n   // export into 8-bit unsigned values, most significant bit first:\r\n   std::vector<unsigned char> v;\r\n   export_bits(i, std::back_inserter(v), 8);\r\n   // import back again, and check for equality:\r\n   cpp_int j;\r\n   import_bits(j, v.begin(), v.end());\r\n   assert(i == j);\r\n}\r\n\r\n//]\r\n", "meta": {"hexsha": "cb5dc7f82ec4b37f911ad6e203909332528b06a6", "size": 1142, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/multiprecision/example/cpp_int_import_export.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/multiprecision/example/cpp_int_import_export.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/multiprecision/example/cpp_int_import_export.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": 25.9545454545, "max_line_length": 69, "alphanum_fraction": 0.6260945709, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.516617710933283}}
{"text": "#pragma once\n\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n/**\n * @brief Calcola l'insieme di facce adiancenti a ogni vertice.\n *\n * Una faccia e' adiacente a un vertice se la faccia punta ad esso,\n * ovvero se esso e' uno dei suoi corner.\n *\n * @param V I vertici della mesh. Per ogni riga della matrice V, la posizione\n *          del vertice e' costituita dalle coordinate x,y,z memorizzate nelle\n *          3 colonne della riga.\n * @param F I triangoli della mesh. Per ogni riga della matrice F, il triangolo\n *          e' descritto dagli indici i,j,k memorizzati nelle 3 colonne della\n *          riga. Gli indici i,j,k si riferiscono ai 3 vertici A, B, C del\n *          triangolo, memorizzati in V.row(i), V.row(j) e V.row(k),\n *          rispettivamente. NOTA: per ogni triangolo, i 3 vertici sono da\n *          considerarsi indicati in senso antiorario.\n * @param VF Array di array di indici. Ogni elemento dell'array esterno\n *           corrisponde all'elenco di indici delle facce adiacenti al\n *           al vertice corrispondente. L'array esterno ha quindi V.rows() elementi.\n * @param VFi Array di array di indici. L'array esterno ha V.rows() elementi. VFi[i]\n *            ha lo stesso numero di elementi del corrispondente elemento in VF[i].\n *            VFi[i][j] corrisponde al corner di Vf[i][j] che incide sul vertice i.\n */\nvoid vertex_face_adjacency(\n    MatrixXd const &V,\n    MatrixXi const &F,\n    std::vector<std::vector<int>> &VF,\n    std::vector<std::vector<int>> &VFi)\n{\n    VF.clear();\n    VFi.clear();\n    VF.resize(V.rows());\n    VFi.resize(V.rows());\n\n    for (int f = 0; f < F.rows(); ++f) {\n        for (int p = 0; p < F.cols(); ++p) {\n            int v = F(f, p);\n            VF[v].push_back(f);\n            VFi[v].push_back(p);\n        }\n    }\n}\n\n/**\n * @brief Calcola la lista di facce adiacenti ad ogni faccia.\n *\n * Una faccia e' adiacente a un'altra se queste condividono un lato, ovvero se\n * puntano agli stessi due vertici, ma in ordine inverso:\n * F.row(i) || F.row(j) <=> F(i,p) == F(j,q) &&\n *                          F(i,(p+1)%F.cols()) == F(j, (F.cols()+q-1)%F.cols())\n *\n * Questa funzione necessita dell'adiacenza vertice->facce, risultato della funzione\n * vertex_face_adjacency().\n *\n * @param V I vertici della mesh. Per ogni riga della matrice V, la posizione\n *          del vertice e' costituita dalle coordinate x,y,z memorizzate nelle\n *          3 colonne della riga.\n * @param F I triangoli della mesh. Per ogni riga della matrice F, il triangolo\n *          e' descritto dagli indici i,j,k memorizzati nelle 3 colonne della\n *          riga. Gli indici i,j,k si riferiscono ai 3 vertici A, B, C del\n *          triangolo, memorizzati in V.row(i), V.row(j) e V.row(k),\n *          rispettivamente. NOTA: per ogni triangolo, i 3 vertici sono da\n *          considerarsi indicati in senso antiorario.\n * @param VF Array di array di indici. Ogni elemento dell'array esterno\n *           corrisponde all'elenco di indici delle facce adiacenti al\n *           al vertice corrispondente. L'array esterno ha quindi V.rows() elementi.\n * @param VFi Array di array di indici. L'array esterno ha V.rows() elementi. VFi[i]\n *            ha lo stesso numero di elementi del corrispondente elemento in VF[i].\n *            VFi[i][j] corrisponde al corner di Vf[i][j] che incide sul vertice i.\n * @param FF Lista di indici di facce adiacenti per ogni faccia. Ogni riga corrisponde\n *           alla lista di adiacenza di una faccia. Ogni faccia ha F.cols() lati,\n *           per cui avra' F.cols() facce adiacenti (alcune potrebbero essere\n *           nulle in presenza di buchi - indice -1).\n * @param FFi Lista di indici per ogni faccia. Stessa dimensionalita' di FF. Ogni\n *            riga corrisponde a indici per una faccia, un indice per ogni faccia\n *            adiacente. Alla riga i, colonna j, l'indice corrisponde al lato della\n *            j-esima faccia adiacente alla i-esima, condiviso con il lato j-esimo\n *            della faccia i-esima.\n */\nvoid face_face_adjacency(\n    MatrixXd const &V,\n    MatrixXi const &F,\n    std::vector<std::vector<int>> const& VF,\n    std::vector<std::vector<int>> const& VFi,\n    MatrixXi &FF,\n    MatrixXi &FFi)\n{\n    FF.resize(F.rows(), F.cols());\n    FFi.resize(F.rows(), F.cols());\n    FF.setConstant(-1);\n    FFi.setConstant(-1);\n\n    for (int f = 0; f < F.rows(); ++f) {\n        for (int p = 0; p < F.cols(); ++p) {\n            int v = F(f, p);\n            std::vector<int> const& VF_adj = VF[v];\n            std::vector<int> const& VFi_adj = VFi[v];\n\n            int v_next = F(f, (p + 1) % F.cols());\n\n            for (std::size_t i = 0; i < VF_adj.size(); ++i) {\n                int f_adj = VF_adj[i];\n\n                if (f_adj == f) {\n                    continue;\n                }\n\n                int fi_adj = VFi_adj[i];\n                int fi_prev = (F.cols() + fi_adj - 1) % F.cols();\n\n                if (F(f_adj, fi_prev) == v_next) {\n                    // trovato!\n                    FF(f, p) = f_adj;\n                    FFi(f, p) = fi_prev;\n                }\n            }\n        }\n    }\n}", "meta": {"hexsha": "d089fe393b45ffbaf28d4891013b8608c8c9948a", "size": 5165, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "topology.hpp", "max_stars_repo_name": "giorgiomarcias/WS_geo_3D", "max_stars_repo_head_hexsha": "ea34450ed0daa38504df5c0d723ab41ac347abd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-11T16:16:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T16:16:28.000Z", "max_issues_repo_path": "topology.hpp", "max_issues_repo_name": "giorgiomarcias/WS_geo_3D", "max_issues_repo_head_hexsha": "ea34450ed0daa38504df5c0d723ab41ac347abd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "topology.hpp", "max_forks_repo_name": "giorgiomarcias/WS_geo_3D", "max_forks_repo_head_hexsha": "ea34450ed0daa38504df5c0d723ab41ac347abd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6692913386, "max_line_length": 86, "alphanum_fraction": 0.5939980639, "num_tokens": 1527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5165934366051804}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <Eigen/Core>\n#include \"../../BenchTimer.h\"\nusing namespace Eigen;\n\n#ifndef SCALAR\n#error SCALAR must be defined\n#endif\n\ntypedef SCALAR Scalar;\n\ntemplate<typename MatA, typename MatB, typename MatC>\ninline void lazy_gemm(const MatA &A, const MatB &B, MatC &C)\n{\n  escape((void*)A.data());\n  escape((void*)B.data());\n  C.noalias() += A.lazyProduct(B);\n  escape((void*)C.data());\n}\n\ntemplate<int m, int n, int k, int TA>\nEIGEN_DONT_INLINE\ndouble bench()\n{\n  typedef Matrix<Scalar,m,k,TA> MatA;\n  typedef Matrix<Scalar,k,n> MatB;\n  typedef Matrix<Scalar,m,n> MatC;\n\n  MatA A(m,k);\n  MatB B(k,n);\n  MatC C(m,n);\n  A.setRandom();\n  B.setRandom();\n  C.setZero();\n\n  BenchTimer t;\n\n  double up = 1e7*4/sizeof(Scalar);\n  double tm0 = 10, tm1 = 20;\n\n  double flops = 2. * m * n * k;\n  long rep = std::max(10., std::min(10000., up/flops) );\n  long tries = std::max(tm0, std::min(tm1, up/flops) );\n\n  BENCH(t, tries, rep, lazy_gemm(A,B,C));\n\n  return 1e-9 * rep * flops / t.best();\n}\n\ntemplate<int m, int n, int k>\ndouble bench_t(int t)\n{\n  if(t)\n    return bench<m,n,k,RowMajor>();\n  else\n    return bench<m,n,k,0>();\n}\n\nEIGEN_DONT_INLINE\ndouble bench_mnk(int m, int n, int k, int t)\n{\n  int id = m*10000 + n*100 + k;\n  switch(id) {\n    case  10101 : return bench_t< 1, 1, 1>(t); break;\n    case  20202 : return bench_t< 2, 2, 2>(t); break;\n    case  30303 : return bench_t< 3, 3, 3>(t); break;\n    case  40404 : return bench_t< 4, 4, 4>(t); break;\n    case  50505 : return bench_t< 5, 5, 5>(t); break;\n    case  60606 : return bench_t< 6, 6, 6>(t); break;\n    case  70707 : return bench_t< 7, 7, 7>(t); break;\n    case  80808 : return bench_t< 8, 8, 8>(t); break;\n    case  90909 : return bench_t< 9, 9, 9>(t); break;\n    case 101010 : return bench_t<10,10,10>(t); break;\n    case 111111 : return bench_t<11,11,11>(t); break;\n    case 121212 : return bench_t<12,12,12>(t); break;\n  }\n  return 0;\n}\n\nint main(int argc, char **argv)\n{\n  std::vector<double> results;\n  \n  std::ifstream settings(\"lazy_gemm_settings.txt\");\n  long m, n, k, t;\n  while(settings >> m >> n >> k >> t)\n  {\n    //std::cerr << \"  Testing \" << m << \" \" << n << \" \" << k << std::endl;\n    results.push_back( bench_mnk(m, n, k, t) );\n  }\n  \n  std::cout << RowVectorXd::Map(results.data(), results.size());\n  \n  return 0;\n}\n", "meta": {"hexsha": "b443218d7a25ff874163ea57deee1a8d575cee8c", "size": 2348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen/bench/perf_monitoring/gemm/lazy_gemm.cpp", "max_stars_repo_name": "Achierius/SysSim", "max_stars_repo_head_hexsha": "067c32a3a03418819d11284db4050fdb43505abc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2016-09-22T08:41:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T02:49:45.000Z", "max_issues_repo_path": "include/Eigen/bench/perf_monitoring/gemm/lazy_gemm.cpp", "max_issues_repo_name": "Achierius/SysSim", "max_issues_repo_head_hexsha": "067c32a3a03418819d11284db4050fdb43505abc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-09-06T11:25:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-31T12:29:50.000Z", "max_forks_repo_path": "include/Eigen/bench/perf_monitoring/gemm/lazy_gemm.cpp", "max_forks_repo_name": "Achierius/SysSim", "max_forks_repo_head_hexsha": "067c32a3a03418819d11284db4050fdb43505abc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2016-08-30T07:17:51.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-08T07:29:18.000Z", "avg_line_length": 23.9591836735, "max_line_length": 74, "alphanum_fraction": 0.6068994889, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5165934366051804}}
{"text": "#ifndef CANNON_ML_ADAM_H\n#define CANNON_ML_ADAM_H \n\n/*!\n * \\file cannon/ml/adam.hpp\n * \\brief File containing AdamOptimizer class definition.\n */\n\n/*!\n * \\namespace cannon::ml;\n * \\brief Namespace containing various optimization and learning algorithms. \n *\n * ML, or Machine Learning, is being used as an umbrella term here to suggest that\n * everything in this namespace has some relationship to optimizing function\n * approximations using data, but many of these methods are not, strictly\n * speaking, machine learning methods.\n */\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace ml {\n\n    /*!\n     * \\brief Class representing an Adam optimizer. Adam is a stochastic\n     * optimization method which produces modified stochastic gradients by\n     * estimating the moments of the distribution of stochastic gradients. See\n     * https://arxiv.org/abs/1412.6980\n     */\n    class AdamOptimizer {\n      public:\n        AdamOptimizer() = delete;\n\n        /*!\n         * \\brief Constructor taking the number of rows and columns of the\n         * parameter matrix to be optimized, as well as a learning rate for\n         * gradient-based updates.\n         */\n        AdamOptimizer(unsigned int rows, unsigned int cols,\n                      double learning_rate)\n            : cols_(cols), rows_(rows), learning_rate_(learning_rate),\n              first_moments_(MatrixXd::Zero(rows_, cols_)),\n              second_moments_(MatrixXd::Zero(rows_, cols_)) {}\n\n        /*!\n         * \\brief Apply a stochastic gradient update by modifying the moment\n         * estimates of this optimizer with the input gradient. \n         *\n         * \\param params Current parameter values\n         * \\param gradient Stochastic gradient\n         * \n         * \\returns New parameters, adjusted using Adam.\n         */\n        MatrixXd apply_update(const MatrixXd& params, const MatrixXd& gradient);\n\n        /*!\n         * \\brief Get modified Adam update given an input stochastic gradient.\n         * Also modifies the moment estimates of this optimizer.\n         *\n         * \\param gradient Stochastic gradient.\n         *\n         * \\returns Adam update\n         */\n        MatrixXd get_update(const MatrixXd& gradient);\n\n        /*!\n         * \\brief Set the learning rate for this optimizer.\n         *\n         * \\param learning_rate The new learning rate.\n         */\n        void set_learning_rate(double learning_rate);\n\n      private:\n        // Parameters\n        unsigned int cols_; //!< Number of columns in parameter matrix\n        unsigned int rows_; //!< Number of rows in parameter matrix\n        double learning_rate_; //!< Learning rate for parameter updates\n\n        // Hyperparameters\n        double beta_1_ = 0.9; //!< Exponential averaging parameter for first-order moments\n        double beta_2_ = 0.999; //!< Exponential averaging parameter for second-order moments\n        double epsilon_ = 1e-8; //!< Small positive number to prevent division by zero\n\n        unsigned int t_ = 0; //!< Number of stochastic gradients seen so far\n\n        // Matrices\n        MatrixXd first_moments_; //!< First-order moments of stochastic gradient distribution\n        MatrixXd second_moments_; //!< Exponential averaging parameter for first-order moments\n    };\n\n  } // namespace ml\n} // namespace cannon\n\n#endif /* ifndef CANNON_ML_ADAM_H */\n", "meta": {"hexsha": "2762b37458920202ed5b62cd2d7a736c5fa42ca4", "size": 3367, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/ml/adam.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/adam.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/adam.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": 34.7113402062, "max_line_length": 94, "alphanum_fraction": 0.6525096525, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5165934248669997}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2010-2011 Gael Guennebaud <gael.guennebaud@inria.fr>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla\r\n// Public License v. 2.0. If a copy of the MPL was not distributed\r\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n#include \"common.h\"\r\n#include <Eigen/LU>\r\n\r\n// computes an LU factorization of a general M-by-N matrix A using partial pivoting with row interchanges\r\nEIGEN_LAPACK_FUNC(getrf,(int *m, int *n, RealScalar *pa, int *lda, int *ipiv, int *info))\r\n{\r\n  *info = 0;\r\n        if(*m<0)                  *info = -1;\r\n  else  if(*n<0)                  *info = -2;\r\n  else  if(*lda<std::max(1,*m))   *info = -4;\r\n  if(*info!=0)\r\n  {\r\n    int e = -*info;\r\n    return xerbla_(SCALAR_SUFFIX_UP\"GETRF\", &e, 6);\r\n  }\r\n\r\n  if(*m==0 || *n==0)\r\n    return 0;\r\n\r\n  Scalar* a = reinterpret_cast<Scalar*>(pa);\r\n  int nb_transpositions;\r\n  int ret = int(Eigen::internal::partial_lu_impl<Scalar,ColMajor,int>\r\n                     ::blocked_lu(*m, *n, a, *lda, ipiv, nb_transpositions));\r\n\r\n  for(int i=0; i<std::min(*m,*n); ++i)\r\n    ipiv[i]++;\r\n\r\n  if(ret>=0)\r\n    *info = ret+1;\r\n\r\n  return 0;\r\n}\r\n\r\n//GETRS solves a system of linear equations\r\n//    A * X = B  or  A' * X = B\r\n//  with a general N-by-N matrix A using the LU factorization computed  by GETRF\r\nEIGEN_LAPACK_FUNC(getrs,(char *trans, int *n, int *nrhs, RealScalar *pa, int *lda, int *ipiv, RealScalar *pb, int *ldb, int *info))\r\n{\r\n  *info = 0;\r\n        if(OP(*trans)==INVALID)  *info = -1;\r\n  else  if(*n<0)                 *info = -2;\r\n  else  if(*nrhs<0)              *info = -3;\r\n  else  if(*lda<std::max(1,*n))  *info = -5;\r\n  else  if(*ldb<std::max(1,*n))  *info = -8;\r\n  if(*info!=0)\r\n  {\r\n    int e = -*info;\r\n    return xerbla_(SCALAR_SUFFIX_UP\"GETRS\", &e, 6);\r\n  }\r\n\r\n  Scalar* a = reinterpret_cast<Scalar*>(pa);\r\n  Scalar* b = reinterpret_cast<Scalar*>(pb);\r\n  MatrixType lu(a,*n,*n,*lda);\r\n  MatrixType B(b,*n,*nrhs,*ldb);\r\n\r\n  for(int i=0; i<*n; ++i)\r\n    ipiv[i]--;\r\n  if(OP(*trans)==NOTR)\r\n  {\r\n    B = PivotsType(ipiv,*n) * B;\r\n    lu.triangularView<UnitLower>().solveInPlace(B);\r\n    lu.triangularView<Upper>().solveInPlace(B);\r\n  }\r\n  else if(OP(*trans)==TR)\r\n  {\r\n    lu.triangularView<Upper>().transpose().solveInPlace(B);\r\n    lu.triangularView<UnitLower>().transpose().solveInPlace(B);\r\n    B = PivotsType(ipiv,*n).transpose() * B;\r\n  }\r\n  else if(OP(*trans)==ADJ)\r\n  {\r\n    lu.triangularView<Upper>().adjoint().solveInPlace(B);\r\n    lu.triangularView<UnitLower>().adjoint().solveInPlace(B);\r\n    B = PivotsType(ipiv,*n).transpose() * B;\r\n  }\r\n  for(int i=0; i<*n; ++i)\r\n    ipiv[i]++;\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "81e422672c63a29f2c37eee824d26355db0d283a", "size": 2744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/lapack/lu.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/lapack/lu.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/lapack/lu.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": 30.4888888889, "max_line_length": 132, "alphanum_fraction": 0.5768950437, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5165934131288187}}
{"text": "#pragma once\n#include <cmath>\n#include <limits>\n#include <algorithm>\n#include <boost/unordered_map.hpp>\n#include \"types.hh\"\n\nusing Bounds = std::pair<double, bool>;\nstatic Bounds operator+ (Bounds a,Bounds b) {\n  return Bounds(a.first + b.first, a.second && b.second);\n}\nstatic inline std::ostream& operator << (std::ostream& os, const Bounds& b) {\n  os << \"(\" << b.first << \", \" << b.second << \")\";\n  return os;\n}\n\n#include <eigen3/Eigen/Core>\n//! @TODO configure include directory for eigen\n\nstruct Zone {\n  using Variables = char;\n  using Tuple = std::tuple<std::vector<Bounds>,Bounds>;\n  Eigen::Matrix<Bounds, Eigen::Dynamic, Eigen::Dynamic> value;\n  Bounds M;\n\n  inline std::size_t getNumOfVar() const {\n    return value.cols() - 1;\n  }\n\n  inline void cutVars (std::shared_ptr<Zone> &out,std::size_t from,std::size_t to) {\n    out = std::make_shared<Zone>();\n    out->value.resize(to - from + 2, to - from + 2);\n    out->value.block(0,0,1,1) << Bounds(0,true);\n    out->value.block(1, 1, to - from + 1, to - from + 1) = value.block(from + 1, from + 1, to - from + 1,to - from + 1);\n    out->value.block(1, 0, to - from + 1, 1) = value.block(from + 1, 0, to - from + 1, 1);\n    out->value.block(0, 1, 1, to - from + 1) = value.block(0, from + 1, 1, to - from + 1);\n    out->M = M;\n  }\n  \n  static Zone zero(int size) {\n    static Zone zeroZone;\n    zeroZone.value.resize(size, size);\n    zeroZone.value.fill(Bounds(0, true));\n    return zeroZone;\n  }\n\n  std::tuple<std::vector<Bounds>,Bounds> toTuple() const {\n    // omit (0,0)\n    return std::tuple<std::vector<Bounds>,Bounds>(std::vector<Bounds>(value.data() + 1, value.data() + value.size()),M);\n  }\n\n  //! @brief add the constraint x - y \\le (c,s)\n  void tighten(Variables x, Variables y, Bounds c) {\n    x++;\n    y++;\n    value(x,y) = std::min(value(x, y), c);\n    close1(x);\n    close1(y);\n  }\n\n  void close1(Variables x) {\n    for (int i = 0; i < value.rows(); i++) {\n      for (int j = 0; j < value.cols(); j++) {\n        value(i, j) = std::min(value(i, j), value(i, x) + value(x, j));\n      }\n    }\n  }\n  \n  // The reset value is always (0, \\le)\n  void reset(Variables x) {\n    // 0 is the special varibale here\n    x++;\n    value(0,x) = Bounds(0, true);\n    value(x,0) = Bounds(0, true);\n    value.col(x).tail(value.rows() - 1) = value.col(0).tail(value.rows() - 1);\n    value.row(x).tail(value.cols() - 1) = value.row(0).tail(value.cols() - 1);\n  }\n  \n  void elapse() {\n    static const Bounds infinity = Bounds(std::numeric_limits<double>::infinity(), false);\n    value.col(0).fill(infinity);\n    for (int i = 0; i < value.row(0).size(); ++i) {\n      value.row(0)[i].second = false;\n    }\n  }\n\n  void canonize() {\n    for (int k = 0; k < value.cols(); k++) {\n      close1(k);\n    }\n  }\n\n  bool isSatisfiable() {\n    canonize();\n    return (value + value.transpose()).minCoeff() >= Bounds(0.0,true);\n  }\n\n  void abstractize() {\n    static const Bounds infinity = Bounds(std::numeric_limits<double>::infinity(), false);\n    for (auto it = value.data(); it < value.data() + value.size(); it++) {\n      if (*it >= M) {\n        *it = infinity;\n      }\n    }\n  }\n\n  bool operator== (Zone z) const {\n    z.value(0,0) = value(0,0);\n    return value == z.value;\n  }\n};\n\nstruct ZoneAutomaton : public AbstractionAutomaton<Zone> {\n  struct TAEdge {\n    State source;\n    State target;\n    Alphabet c;\n    std::vector<Alphabet> resetVars;\n    std::vector<Constraint> guard;\n  };\n\n  boost::unordered_map<std::tuple<State, State, Alphabet>, TAEdge> edgeMap;\n  boost::unordered_map<std::pair<TAState, typename Zone::Tuple>, RAState> zones_in_za;\n  int numOfVariables;\n};\n\nstatic inline std::ostream& operator << (std::ostream& os, const Zone& z) {\n  for (int i = 0; i < z.value.rows();i++) {\n    for (int j = 0; j < z.value.cols();j++) {\n      os << z.value(i,j);\n    }\n    os << \"\\n\";\n  }\n  os << std::endl;\n  return os;\n}\n", "meta": {"hexsha": "992a8e21098c97823b1bf21ed6f78f1115f869bf", "size": 3876, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/zone.hh", "max_stars_repo_name": "MasWag/timed-pattern-matching", "max_stars_repo_head_hexsha": "325d03d2447bdc3b28c391a94f920d708581ad35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/zone.hh", "max_issues_repo_name": "MasWag/timed-pattern-matching", "max_issues_repo_head_hexsha": "325d03d2447bdc3b28c391a94f920d708581ad35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/zone.hh", "max_forks_repo_name": "MasWag/timed-pattern-matching", "max_forks_repo_head_hexsha": "325d03d2447bdc3b28c391a94f920d708581ad35", "max_forks_repo_licenses": ["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.2919708029, "max_line_length": 120, "alphanum_fraction": 0.5848813209, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5165101752475452}}
{"text": "#include \"Vector.hpp\"\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include \"fhe/EncryptedArray.h\"\n#include <cmath>\n#include <cassert>\n#include <algorithm>\nnamespace MDL {\ntemplate<typename T>\ndouble Vector<T>::L2() const {\n    double norm = 0.0;\n\n    for (auto e : *this) {\n        auto de = static_cast<double>(e);\n        norm += de * de;\n    }\n    return std::sqrt(norm);\n}\n\ntemplate<typename T>\nVector<double> Vector<T>::reduce(double factor) const {\n    Vector<double> vec(dimension());\n    std::transform(this->begin(), this->end(), vec.begin(),\n                   [&factor](const T &v) { return v / factor; });\n    return vec;\n}\n\ntemplate<>\nVector<double> Vector<NTL::ZZX>::reduce(double factor) const {\n    Vector<double> vec(dimension());\n    std::transform(this->begin(), this->end(), vec.begin(),\n                   [&factor](const NTL::ZZX &v) {\n                   return NTL::to_long(v[0]) / factor;\n                   });\n    return vec;\n}\n\ntemplate<>\nVector<double> Vector<NTL::ZZ>::reduce(double factor) const {\n    Vector<double> vec(dimension());\n    std::transform(this->begin(), this->end(), vec.begin(),\n                   [&factor](const NTL::ZZ &v) {\n                   double d;\n                   NTL::conv(d, v);\n                   return d / factor;\n                   });\n    return vec;\n}\n\ntemplate<>\ndouble Vector<NTL::ZZX>::L2() const {\n    NTL::ZZ summation(0);\n\n    for (auto& e : *this) {\n\t\tif (e.rep.length() > 0) summation += e[0] * e[0];\n    }\n    return std::sqrt(std::exp(log(summation)));\n}\n\ntemplate<>\ndouble Vector<NTL::ZZ>::L2() const {\n    NTL::ZZ summation(0);\n\n    for (auto& e : *this) {\n\t\tsummation += e * e;\n    }\n    return std::sqrt(std::exp(log(summation)));\n}\n\ntemplate<typename T>\nT Vector<T>::dot(const Vector<T>& oth) const {\n    assert(dimension() == oth.dimension());\n    T sum(0);\n\n    for (size_t i = 0; i < dimension(); i++) {\n        sum += this->at(i) * oth[i];\n    }\n    return sum;\n}\n\ntemplate<typename T>\nVector<T> Vector<T>::subvector(long startIndex, long endIndex) const\n{\n    while (startIndex < 0) { startIndex += dimension(); }\n    while (endIndex < 0) { endIndex += dimension(); }\n    if (endIndex < startIndex || endIndex >= this->size()) {\n        std::cerr << \"Invalid subvector arguments\" << std::endl;\n        return *this;\n    }\n    Vector<T> sub(endIndex - startIndex + 1);\n    auto start = this->begin();\n    auto end = start;\n    std::advance(start, startIndex);\n    std::advance(end, endIndex + 1);\n    std::copy(start, end, sub.begin());\n    return sub;\n}\n\ntemplate<typename T>\nVector<long> Vector<T>::div(long factor) const\n{\n    Vector<long> vec(dimension());\n    std::transform(this->begin(), this->end(), vec.begin(), [&factor](T e) { return std::lround(e / factor); });\n    return vec;\n}\n\ntemplate<>\nVector<long> Vector<NTL::ZZX>::div(long factor) const = delete;\n\ntemplate<>\nNTL::ZZX Vector<long>::encode(const EncryptedArray &ea) const\n{\n    assert(this->size() <= ea.size());\n    NTL::ZZX encoded;\n    if (this->size() < ea.size()) {\n        auto tmp(*this);\n        tmp.resize(ea.size());\n        ea.encode(encoded, tmp);\n    } else {\n        ea.encode(encoded, *this);\n    }\n    return encoded;\n}\n\ntemplate<typename T>\nVector<T>& Vector<T>::operator*=(const T& val)\n{\n    for (auto &ele : *this) {\n        ele *= val;\n    }\n    return *this;\n}\n\ntemplate<typename T>\nVector<T>& Vector<T>::operator-=(const Vector<T> &oth)\n{\n    auto dd = std::min(dimension(), oth.dimension());\n    for (size_t d = 0; d < dd; d++) {\n        this->at(d) -= oth[d];\n    }\n    return *this;\n}\n\ntemplate<typename T>\nVector<T>& Vector<T>::operator+=(const Vector<T> &oth)\n{\n    auto dd = std::min(dimension(), oth.dimension());\n    for (size_t d = 0; d < dd; d++) {\n        this->at(d) += oth[d];\n    }\n    return *this;\n}\n\ntemplate<>\nvoid Vector<long>::random(const long &domain)\n{\n    for (size_t i = 0; i < size(); i++) {\n        this->at(i) = NTL::RandomBnd(domain);\n    }\n}\n\ntemplate class Vector<long>;\ntemplate class Vector<double>;\ntemplate class Vector<NTL::ZZX>;\n} // namespace MDL\n", "meta": {"hexsha": "5a39d54b4fc2fc327931b49937d57f69a6ad8f5c", "size": 4060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "algebra/Vector.cpp", "max_stars_repo_name": "fionser/MDLHElib", "max_stars_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T06:20:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-17T12:36:34.000Z", "max_issues_repo_path": "algebra/Vector.cpp", "max_issues_repo_name": "fionser/MDLHElib", "max_issues_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algebra/Vector.cpp", "max_forks_repo_name": "fionser/MDLHElib", "max_forks_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-08-26T13:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T02:08:20.000Z", "avg_line_length": 24.4578313253, "max_line_length": 112, "alphanum_fraction": 0.5679802956, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5165101752475451}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"math/algo/interval_scheduler_maximize.h\" // header to test\n#include \"che/sequence_interval.h\"\n\nusing namespace biosim;\n\nBOOST_AUTO_TEST_SUITE(suite_interval_scheduler_maximize)\n\nBOOST_AUTO_TEST_CASE(interval_scheduler_maximize_interval) {\n  std::set<math::interval<int>> intervals;\n  math::algo::interval_scheduler_maximize<math::interval<int>> s;\n  BOOST_CHECK(s.schedule(intervals).empty());\n\n  math::interval<int> iv1(1, 5), iv2(2, 4), iv3(2, 6), iv4(5, 10), iv5(6, 10), iv6(7, 10);\n\n  intervals.insert(iv1);\n  BOOST_CHECK(s.schedule(intervals).size() == 1);\n\n  intervals.insert(iv2);\n  intervals.insert(iv3);\n  BOOST_CHECK(s.schedule(intervals).size() == 1);\n\n  intervals.insert(iv4);\n  BOOST_CHECK(s.schedule(intervals).size() == 2);\n\n  intervals.insert(iv5);\n  intervals.insert(iv6);\n  BOOST_CHECK(s.schedule(intervals).size() == 2);\n}\n\nBOOST_AUTO_TEST_CASE(interval_scheduler_maximize_sequence_interval) {\n  std::set<che::cchb_dssp_interval> intervals;\n  math::algo::interval_scheduler_maximize<che::cchb_dssp_interval> s;\n  BOOST_CHECK(s.schedule(intervals).empty());\n\n  che::cchb_dssp_interval iv1(1, 5, che::cchb_dssp('H')), iv2(2, 4, che::cchb_dssp('H')),\n      iv3(4, 6, che::cchb_dssp('E'));\n  intervals.insert(iv1);\n  intervals.insert(iv2);\n  BOOST_CHECK(s.schedule(intervals).size() == 1);\n\n  intervals.insert(iv3);\n  BOOST_CHECK(s.schedule(intervals).size() == 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c73ae1bf7e6d0488a27c6f54800eb130635d647c", "size": 1459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/algo/interval_scheduler_maximize.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/interval_scheduler_maximize.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/interval_scheduler_maximize.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": 30.3958333333, "max_line_length": 90, "alphanum_fraction": 0.7278958191, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5165101703135305}}
{"text": "#include \"RBGL.hpp\"\n#include \"Basic2DMatrix.hpp\"\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/graph/dag_shortest_paths.hpp>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n#include <boost/graph/floyd_warshall_shortest.hpp>\n\nextern \"C\"\n{\n    SEXP BGL_dijkstra_shortest_paths_D (SEXP num_verts_in,\n                                        SEXP num_edges_in, SEXP R_edges_in,\n                                        SEXP R_weights_in, SEXP init_ind)\n    {\n        using namespace boost;\n\n        typedef graph_traits < Graph_dd >::edge_descriptor Edge;\n        typedef graph_traits < Graph_dd >::vertex_descriptor Vertex;\n        Graph_dd g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n        int N = num_vertices(g);\n        std::vector<Vertex> p(N);\n        std::vector<double> d(N);\n\n        dijkstra_shortest_paths(g, vertex((int)INTEGER(init_ind)[0], g),\n                                predecessor_map(&p[0]).distance_map(&d[0]));\n\n        SEXP dists, pens, ansList;\n        PROTECT(dists = allocVector(REALSXP,N));\n        PROTECT(pens = allocVector(INTSXP,N));\n        graph_traits < Graph_dd >::vertex_iterator vi, vend;\n        for (tie(vi, vend) = vertices(g); vi != vend; ++vi) {\n            REAL(dists)[*vi] = d[*vi];\n            INTEGER(pens)[*vi] = p[*vi];\n        }\n        PROTECT(ansList = allocVector(VECSXP,2));\n        SET_VECTOR_ELT(ansList,0,dists);\n        SET_VECTOR_ELT(ansList,1,pens);\n\n        UNPROTECT(3);\n        return(ansList);\n    }\n\n    SEXP BGL_johnson_all_pairs_shortest_paths_D(SEXP num_verts_in,\n            SEXP num_edges_in, SEXP R_edges_in,\n            SEXP R_weights_in)\n    {\n        using namespace boost;\n        int nv = INTEGER(num_verts_in)[0];\n        SEXP out;\n\n        Graph_dd g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n        Basic2DMatrix<double> D(nv, nv);\n\n        johnson_all_pairs_shortest_paths(g, D);\n\n        PROTECT(out = NEW_NUMERIC(nv*nv));\n        int k = 0;\n        for (int i = 0 ; i < nv ; i++)\n            for (int j = 0; j < nv; j++ )\n            {\n                REAL(out)[k] = D[i][j];\n                k++;\n            }\n        UNPROTECT(1);\n        return out;\n    }\n\n    SEXP BGL_bellman_ford_shortest_paths(SEXP num_verts_in,\n                                         SEXP num_edges_in, SEXP R_edges_in,\n                                         SEXP R_weights_in, SEXP init_ind)\n    {\n        using namespace boost;\n\n        typedef adjacency_list < vecS, vecS, directedS,\n        no_property, property < edge_weight_t, double> > EdgeGraph;\n\n        int i;\n        int NE = (int)INTEGER(num_edges_in)[0];\n        int N = (int)INTEGER(num_verts_in)[0];\n        int s = (int)INTEGER(init_ind)[0];\n\n        EdgeGraph g(N);\n\n        int* edges_in = INTEGER(R_edges_in);\n        for ( i = 0; i < NE; i++, edges_in += 2 )\n            add_edge(*edges_in, *(edges_in+1), g);\n\n        std::vector<std::size_t> p(N);\n        for ( i = 0; i < N; i++ ) p[i] = i;\n\n        std::vector<double> d(N, std::numeric_limits<double>::max());\n        d[s] = 0;\n\n        property_map<EdgeGraph, edge_weight_t>::type w = get(edge_weight, g);\n\n        int* weight_i = (isReal(R_weights_in)) ? 0 : INTEGER(R_weights_in);\n        double* weight_d = (isReal(R_weights_in)) ? REAL(R_weights_in) : 0;\n\n        graph_traits< EdgeGraph >::edge_iterator ei, ei_end;\n        for ( tie(ei, ei_end) = edges(g); ei != ei_end; ++ei )\n            w[*ei] = weight_i ? (*weight_i++) : (*weight_d++);\n\n        bool r = bellman_ford_shortest_paths(g, N,\n                 weight_map(w).predecessor_map(&p[0]).distance_map(&d[0]));\n\n        SEXP conn, dList, pList, ansList;\n        PROTECT(ansList = allocVector(VECSXP,3));\n        PROTECT(conn = NEW_LOGICAL(1));\n        PROTECT(dList = allocVector(REALSXP,N));\n        PROTECT(pList = allocVector(INTSXP,N));\n\n        LOGICAL(conn)[0] = r;\n\n        for (i = 0; i < N; i++)\n        {\n            INTEGER(pList)[i] = p[i];\n            REAL(dList)[i] = d[i];\n        }\n\n        SET_VECTOR_ELT(ansList,0,conn);\n        SET_VECTOR_ELT(ansList,1,dList);\n        SET_VECTOR_ELT(ansList,2,pList);\n\n        UNPROTECT(4);\n        return(ansList);\n    }\n\n    SEXP BGL_dag_shortest_paths(SEXP num_verts_in,\n                                SEXP num_edges_in, SEXP R_edges_in,\n                                SEXP R_weights_in, SEXP init_ind)\n    {\n        using namespace boost;\n\n        typedef graph_traits < Graph_dd >::edge_descriptor Edge;\n        typedef graph_traits < Graph_dd >::vertex_descriptor Vertex;\n        Graph_dd g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n        int N = num_vertices(g);\n        std::vector<Vertex> p(N);\n        std::vector<double> d(N);\n\n        dag_shortest_paths(g, vertex((int)INTEGER(init_ind)[0], g),\n                           predecessor_map(&p[0]).distance_map(&d[0]));\n\n        SEXP dists, pens, ansList;\n        PROTECT(dists = allocVector(REALSXP,N));\n        PROTECT(pens = allocVector(INTSXP,N));\n        graph_traits < Graph_dd >::vertex_iterator vi, vend;\n        for (tie(vi, vend) = vertices(g); vi != vend; ++vi) {\n            if ( int(d[*vi]) == std::numeric_limits<int>::max() )\n            {\n                REAL(dists)[*vi] = R_NaN;\n                INTEGER(pens)[*vi] = *vi;\n            }\n            else\n            {\n                REAL(dists)[*vi] = d[*vi];\n                INTEGER(pens)[*vi] = p[*vi];\n            }\n        }\n        PROTECT(ansList = allocVector(VECSXP,2));\n        SET_VECTOR_ELT(ansList,0,dists);\n        SET_VECTOR_ELT(ansList,1,pens);\n\n        UNPROTECT(3);\n        return(ansList);\n    }\n\n    SEXP BGL_floyd_warshall_all_pairs_shortest_paths_D(SEXP num_verts_in,\n            SEXP num_edges_in, SEXP R_edges_in,\n            SEXP R_weights_in)\n    {\n        using namespace boost;\n        typedef adjacency_list<vecS, vecS, directedS, no_property,\n        property< edge_weight_t, double, property< edge_weight2_t, double > > > Graph;\n        int nv = INTEGER(num_verts_in)[0];\n        SEXP out;\n        typedef std::pair < int, int >Edge;\n\n        Graph_dd g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n        Basic2DMatrix<double> D(nv, nv);\n\n        floyd_warshall_all_pairs_shortest_paths(g, D);\n\n        PROTECT(out = NEW_NUMERIC(nv*nv));\n        int k = 0;\n        for (int i = 0 ; i < nv ; i++)\n            for (int j = 0; j < nv; j++ )\n            {\n                REAL(out)[k] = D[i][j];\n                k++;\n            }\n        UNPROTECT(1);\n        return out;\n    }\n}\n\n", "meta": {"hexsha": "3273c05eb984383e58063eb88185332f8e8603bb", "size": 6579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/shortestPath.cpp", "max_stars_repo_name": "cran/RBGL", "max_stars_repo_head_hexsha": "e5d1a5109bf1dfbd6882bf50b6650ddc9da5ffb8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-29T11:20:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-29T11:20:31.000Z", "max_issues_repo_path": "src/shortestPath.cpp", "max_issues_repo_name": "cran/RBGL", "max_issues_repo_head_hexsha": "e5d1a5109bf1dfbd6882bf50b6650ddc9da5ffb8", "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/shortestPath.cpp", "max_forks_repo_name": "cran/RBGL", "max_forks_repo_head_hexsha": "e5d1a5109bf1dfbd6882bf50b6650ddc9da5ffb8", "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.7313432836, "max_line_length": 86, "alphanum_fraction": 0.5526675787, "num_tokens": 1713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830605, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.516510167846523}}
{"text": "// std includes\n#include <iostream> // cout, endl\n#include <memory> // shared_ptr\n#include <tuple>\n#include <vector>\n// thirdparties includes\n#include <Eigen/Dense>\n// lib includes\n// // s0s\n#include \"s0s/runge_kutta_fehlberg.h\"\n#include \"sl0/point.h\"\n// // sa0\n#include \"sa0/active.h\"\n#include \"sa0/actuator/point.h\"\n// simple includes\n#include \"flow.h\"\n\nusing TypeScalar = double;\ntemplate<typename ...Args>\nusing TypeContainer = std::vector<Args...>;\n// Space\ntemplate<int StateSize>\nusing TypeState = Eigen::Matrix<TypeScalar, StateSize, 1>;\nconstexpr unsigned int DIM = 3;\nusing TypeVector = Eigen::Matrix<TypeScalar, DIM, 1>;\n// Ref and View\ntemplate<typename ...Args>\nusing TypeRef = Eigen::Ref<Args...>;\ntemplate<typename ...Args>\nusing TypeView = Eigen::Map<Args...>;\n// Point\nusing TypeStepPoint = sl0::StepPoint<TypeState, DIM, TypeRef, TypeView, Flow>;\n// Choose passive\nusing TypeStepPassive = TypeStepPoint;\n// Active\nusing TypeStepActuator = sl0::sa0::StepActuator<TypeStepPassive::TypeStateStatic, TypeRef, TypeStepPassive>;\nusing TypeStepPointSwim = sl0::sa0::StepPointSwim<TypeStepPassive::TypeStateStatic, TypeRef, TypeStepPassive, TypeVector>;\n// Solver\nusing TypeSolver = s0s::SolverRungeKuttaFehlberg;\n\nint main () { \n    TypeVector us = TypeVector::Constant(0.0);\n    us[0] = 1.0;\n    TypeVector x0 = TypeVector::Constant(1.0);\n    double t0 = 0.0;\n    double dt = 1e-0;\n    double tEnd = 1.0;\n    unsigned int nt = std::round((tEnd - t0) / dt);\n    // Create activePoint\n    sl0::sa0::ObjectActive<TypeState, TypeRef, TypeView, TypeStepPassive, TypeStepActuator, TypeSolver> activePoint(TypeStepPassive(std::make_shared<Flow>()));\n    std::shared_ptr<TypeStepPointSwim> sStepPointSwim = std::make_shared<TypeStepPointSwim>(us);\n    activePoint.sStep->register_actuator(sStepPointSwim);\n    // Set initial state\n    activePoint.sStep->x(activePoint.state) = x0;\n    activePoint.t = t0;\n    // Computation\n    for(std::size_t i = 0; i < nt; i++) {\n        activePoint.update(dt);\n    }\n    // out\n    std::cout << \"\\n\";\n    std::cout << \"activePoint advected and swimming in an exponential flow, t = \" << activePoint.t << \"\\n\";\n    std::cout << \"\\n\";\n    std::cout << \"activePoint position : \" << \"\\n\" << activePoint.sStep->x(activePoint.state) << \"\\n\";\n    std::cout << std::endl;\n}\n", "meta": {"hexsha": "47fa8ef098b77919fee3da5865851c4112ac8389", "size": 2306, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/active/main.cpp", "max_stars_repo_name": "C0PEP0D/sa0", "max_stars_repo_head_hexsha": "0d4d4106d64a2eaec6fd5f8cdba1a73bc0a26ea2", "max_stars_repo_licenses": ["MIT"], "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/active/main.cpp", "max_issues_repo_name": "C0PEP0D/sa0", "max_issues_repo_head_hexsha": "0d4d4106d64a2eaec6fd5f8cdba1a73bc0a26ea2", "max_issues_repo_licenses": ["MIT"], "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/active/main.cpp", "max_forks_repo_name": "C0PEP0D/sa0", "max_forks_repo_head_hexsha": "0d4d4106d64a2eaec6fd5f8cdba1a73bc0a26ea2", "max_forks_repo_licenses": ["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.4179104478, "max_line_length": 159, "alphanum_fraction": 0.6925411969, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5165101604455005}}
{"text": "//\n//  Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n//  And we acknowledge the support from all contributors.\n\n\n#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/test/unit_test.hpp>\n\n\n#include <algorithm>\n#include <iostream>\n\n\n#include \"utility.hpp\"\n\nBOOST_AUTO_TEST_SUITE ( test_einstein_notation/*,\n                      *boost::unit_test::depends_on(\"test_multi_index\") */)\n\n\nusing test_types = zip<int,float,std::complex<float>>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\n//using test_types = zip<int>::with_t<boost::numeric::ublas::layout::first_order>;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_einstein_multiplication, value,  test_types )\n{\n  namespace ublas = boost::numeric::ublas;\n\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n  using tensor_t  = ublas::tensor_dynamic<value_t,layout_t>;\n  // NOLINTNEXTLINE(google-build-using-namespace)\n  using namespace boost::numeric::ublas::index;\n\n  {\n    auto A = tensor_t(5,3);\n    auto B = tensor_t{3,4};\n    //  auto C = tensor_t{4,5,6};\n\n    for(auto j = 0u; j < A.extents().at(1); ++j){\n      for(auto i = 0u; i < A.extents().at(0); ++i){\n        A.at( i,j ) = value_t( static_cast< inner_type_t<value_t> >(i+1) );\n      }\n    }\n\n    for(auto j = 0u; j < B.extents().at(1); ++j){\n      for(auto i = 0u; i < B.extents().at(0); ++i){\n        B.at( i,j ) = value_t( static_cast< inner_type_t<value_t> >(i+1) );\n      }\n    }\n\n    auto AB = A(_,_e) * B(_e,_);\n\n    //  std::cout << \"A = \" << A << std::endl;\n    //  std::cout << \"B = \" << B << std::endl;\n    //  std::cout << \"AB = \" << AB << std::endl;\n\n    for(auto j = 0u; j < AB.extents().at(1); ++j){\n      for(auto i = 0u; i < AB.extents().at(0); ++i){\n        auto e0   = B.extents().at(0);\n        auto sum  = std::div(e0*(e0+1),2);\n        auto quot = value_t(sum.quot);\n        BOOST_CHECK_EQUAL( AB.at(i,j) , A.at(i,0)*quot );\n      }\n    }\n  }\n\n\n  {\n    auto A = tensor_t{4,5,3};\n    auto B = tensor_t{3,4,2};\n\n    for(auto k = 0u; k < A.extents().at(2); ++k){\n      for(auto j = 0u; j < A.extents().at(1); ++j){\n        for(auto i = 0u; i < A.extents().at(0); ++i){\n          A.at( i,j,k ) = value_t( static_cast< inner_type_t<value_t> >(i+1) );\n        }\n      }\n    }\n\n    for(auto k = 0u; k < B.extents().at(2); ++k){\n      for(auto j = 0u; j < B.extents().at(1); ++j){\n        for(auto i = 0u; i < B.extents().at(0); ++i){\n          B.at( i,j,k ) = value_t( static_cast< inner_type_t<value_t> >(i+1) );\n        }\n      }\n    }\n\n    auto AB = A(_d,_,_f) * B(_f,_d,_);\n\n    //  std::cout << \"A = \" << A << std::endl;\n    //  std::cout << \"B = \" << B << std::endl;\n    //  std::cout << \"AB = \" << AB << std::endl;\n    // n*(n+1)/2;\n    auto const nf = ( B.extents().at(0) * (B.extents().at(0)+1) / 2 );\n    auto const nd = ( A.extents().at(0) * (A.extents().at(0)+1) / 2 );\n\n    for(auto j = 0u; j < AB.extents().at(1); ++j){\n      for(auto i = 0u; i < AB.extents().at(0); ++i){\n        BOOST_CHECK_EQUAL( AB.at( i,j ) ,  value_t( static_cast< inner_type_t<value_t> >(nf * nd) ) );\n      }\n    }\n  }\n\n\n  {\n    auto A = tensor_t{{4,3}};\n    auto B = tensor_t{3,4,2};\n\n    for(auto j = 0u; j < A.extents().at(1); ++j){\n      for(auto i = 0u; i < A.extents().at(0); ++i){\n        A.at( i,j ) = value_t( static_cast< inner_type_t<value_t> >(i+1) );\n      }\n    }\n\n\n    for(auto k = 0u; k < B.extents().at(2); ++k){\n      for(auto j = 0u; j < B.extents().at(1); ++j){\n        for(auto i = 0u; i < B.extents().at(0); ++i){\n          B.at( i,j,k ) = value_t( static_cast< inner_type_t<value_t> >(i+1) );\n        }\n      }\n    }\n\n    auto AB = A(_d,_f) * B(_f,_d,_);\n\n    // n*(n+1)/2;\n    auto const nf = ( B.extents().at(0) * (B.extents().at(0)+1) / 2 );\n    auto const nd = ( A.extents().at(0) * (A.extents().at(0)+1) / 2 );\n\n    for(auto i = 0u; i < AB.extents().at(0); ++i){\n      BOOST_CHECK_EQUAL ( AB.at( i  ) ,  value_t( static_cast< inner_type_t<value_t> >(nf * nd) ) );\n    }\n\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "400011a7ca528fc9a5545b15bac350a3fe802b67", "size": 4382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_einstein_notation.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_einstein_notation.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_einstein_notation.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 29.8095238095, "max_line_length": 149, "alphanum_fraction": 0.5417617526, "num_tokens": 1533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339556397749, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5165101579784929}}
{"text": "#include <cstddef>\n#include <cstdint>\n\n#include <vector>\n#include <string>\n#include <iterator>\n#include <iostream>\n#include <unordered_map>\n\n#include <boost/graph/compressed_sparse_row_graph.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/lookup_edge.hpp>\n#include <boost/graph/edmonds_karp_max_flow.hpp>\n\n#include <boost/range/algorithm/for_each.hpp>\n\n#include <z3++.h>\n\n\nusing Graph = boost::compressed_sparse_row_graph<>;\nusing Vertex = typename boost::graph_traits<Graph>::vertex_descriptor;\nusing Edge = typename boost::graph_traits<Graph>::edge_descriptor;\n\n\nGraph makeGraph() {\n  const auto tag = boost::edges_are_unsorted_multi_pass;\n  using VertexPair = std::pair<std::size_t, std::size_t>;\n\n  /*\n     1\n    / \\\n   0 - 3\n    \\ /\n     2\n  */\n  const std::size_t numVertices{4};\n  std::vector<VertexPair> edges{{0, 1}, {1, 0}, {0, 2}, {2, 0}, {1, 3}, {3, 1}, {2, 3}, {3, 2}, {0, 3}, {3, 0}};\n\n  return {tag, begin(edges), end(edges), numVertices};\n}\n\n\nvoid makeMaxFlow(const Graph& graph, const Vertex s, const Vertex t) {\n  std::vector<std::uint8_t> capacities(num_edges(graph), 0);\n  std::vector<std::uint8_t> residuals(num_edges(graph), 0);\n  std::vector<Edge> reverse(num_edges(graph));\n\n  auto capacityMap = boost::make_iterator_property_map(begin(capacities), get(boost::edge_index, graph));\n  auto residualMap = boost::make_iterator_property_map(begin(residuals), get(boost::edge_index, graph));\n  auto reverseMap = boost::make_iterator_property_map(begin(reverse), get(boost::edge_index, graph));\n\n  for_each(edges(graph), [&](const auto edge) {\n    const auto reverseEdge = lookup_edge(target(edge, graph), source(edge, graph), graph).first;\n    put(reverseMap, edge, reverseEdge);\n\n    put(capacityMap, edge, 1);\n    put(residualMap, edge, 1);\n  });\n\n  const auto flow = edmonds_karp_max_flow(graph, s, t, capacity_map(capacityMap) //\n                                                           .residual_capacity_map(residualMap)\n                                                           .reverse_edge_map(reverseMap));\n\n  std::cout << flow << std::endl;\n}\n\n\nvoid makeMaxFlowSolver(const Graph& graph, const Vertex s, const Vertex t) {\n  z3::context context;\n  z3::optimize solver{context};\n\n  std::unordered_map<std::string, z3::expr> symbols;\n  std::vector<z3::expr> constraints;\n\n  const z3::expr zero{context.int_val(0)};\n\n  const auto symbolize = [&](const auto edge) {\n    const auto from = source(edge, graph);\n    const auto to = target(edge, graph);\n    return \"x_\" + std::to_string(from) + \"_\" + std::to_string(to);\n  };\n\n  boost::for_each(edges(graph), [&](const auto edge) {\n    const auto edgeSym = symbolize(edge);\n    symbols.emplace(edgeSym, context.int_const(edgeSym.c_str()));\n  });\n\n  boost::for_each(edges(graph), [&](const auto edge) {\n    const auto edgeSym = symbolize(edge);\n    constraints.emplace_back(symbols.at(edgeSym) >= 0);\n    constraints.emplace_back(symbols.at(edgeSym) <= 1);\n  });\n\n  boost::for_each(vertices(graph), [&](const auto vertex) {\n    if (vertex == s or vertex == t)\n      return;\n\n    z3::expr outgoing{zero}, incoming{zero};\n    boost::for_each(out_edges(vertex, graph), [&](const auto edge) { outgoing = outgoing + symbols.at(symbolize(edge)); });\n\n    std::vector<Edge> inEdges;\n    boost::for_each(edges(graph), [&](const auto edge) {\n      const auto to = target(edge, graph);\n      if (to == vertex)\n        inEdges.push_back(edge);\n    });\n\n    boost::for_each(inEdges, [&](const auto edge) { incoming = incoming + symbols.at(symbolize(edge)); });\n\n    constraints.emplace_back(outgoing - incoming == 0);\n  });\n\n\n  z3::expr outgoing{zero}, incoming{zero};\n  boost::for_each(out_edges(s, graph), [&](const auto edge) { outgoing = outgoing + symbols.at(symbolize(edge)); });\n\n  std::vector<Edge> inEdges;\n  boost::for_each(edges(graph), [&](const auto edge) {\n    const auto to = target(edge, graph);\n    if (to == s)\n      inEdges.push_back(edge);\n  });\n\n  boost::for_each(inEdges, [&](const auto edge) { incoming = incoming + symbols.at(symbolize(edge)); });\n\n  boost::for_each(constraints, [&](const auto& constraint) { std::cout << constraint << std::endl; });\n\n  solver.maximize(outgoing - incoming);\n\n  if (solver.check() not_eq z3::sat)\n    return;\n\n  const auto model = solver.get_model();\n  std::cout << model << std::endl;\n}\n\n\nint main() {\n  const auto graph = makeGraph();\n  const Vertex source{0}, target{3};\n\n  //makeMaxFlow(graph, source, target);\n  makeMaxFlowSolver(graph, source, target);\n}\n", "meta": {"hexsha": "48345293d864a7ef169dfee22875236be76805ec", "size": 4536, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MaxFlowSolver.cc", "max_stars_repo_name": "daniel-j-h/MaxFlowSMT", "max_stars_repo_head_hexsha": "d904d93f8ccb0dc92f96820b7731edc5626dea8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MaxFlowSolver.cc", "max_issues_repo_name": "daniel-j-h/MaxFlowSMT", "max_issues_repo_head_hexsha": "d904d93f8ccb0dc92f96820b7731edc5626dea8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MaxFlowSolver.cc", "max_forks_repo_name": "daniel-j-h/MaxFlowSMT", "max_forks_repo_head_hexsha": "d904d93f8ccb0dc92f96820b7731edc5626dea8b", "max_forks_repo_licenses": ["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.0684931507, "max_line_length": 123, "alphanum_fraction": 0.6580687831, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5164961742479485}}
{"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//! \\file\r\n//!\\brief Tests for the trigonometric sine function of (fixed_point) for a small digit range.\r\n\r\n#include <cmath>\r\n\r\n#define BOOST_TEST_MODULE test_negatable_func_sine_small\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_func_sine_small)\r\n{\r\n  typedef boost::fixed_point::negatable<7, -24> fixed_point_type;\r\n  typedef fixed_point_type::float_type          float_point_type;\r\n\r\n  const fixed_point_type tol = ldexp(fixed_point_type(1), fixed_point_type::resolution + 7);\r\n\r\n  using std::sin;\r\n\r\n  // Check positive arguments.\r\n  for(int i = 1; i < 64; ++i)\r\n  {\r\n    const fixed_point_type x = sin(fixed_point_type(i) / 10);\r\n    const float_point_type y = sin(float_point_type(i) / 10);\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n  }\r\n\r\n  // Check negative arguments.\r\n  for(int i = 1; i < 64; ++i)\r\n  {\r\n    const fixed_point_type x = sin(fixed_point_type(-i) / 10);\r\n    const float_point_type y = sin(float_point_type(-i) / 10);\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n  }\r\n\r\n  const fixed_point_type local_pi_half = boost::fixed_point::negatable_constants<fixed_point_type>::pi_half();\r\n\r\n  BOOST_CHECK_EQUAL(sin(+local_pi_half), fixed_point_type(+1));\r\n  BOOST_CHECK_EQUAL(sin(-local_pi_half), fixed_point_type(-1));\r\n\r\n  BOOST_CHECK_EQUAL(sin(fixed_point_type(0)), fixed_point_type(0));\r\n}\r\n", "meta": {"hexsha": "0fd96a0102097f661724cf78efffb2b28a2f70d5", "size": 1830, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_func_sine_small.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_func_sine_small.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_func_sine_small.cpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8888888889, "max_line_length": 111, "alphanum_fraction": 0.6885245902, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5163779010342776}}
{"text": "#define BOOST_TEST_MODULE \"test_flexible_local_dihedral_potential\"\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 <test/util/check_potential.hpp>\n#include <mjolnir/forcefield/FLP/FlexibleLocalDihedralPotential.hpp>\n#include <mjolnir/math/constants.hpp>\n\nBOOST_AUTO_TEST_CASE(FlexibleLocalDihedral_double)\n{\n    using real_type = double;\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 1e-5;\n    constexpr real_type tol = 1e-5;\n    constexpr real_type   pi = mjolnir::math::constants<real_type>::pi();\n\n    const real_type k  = 1.0;\n    const std::array<real_type, 7> term{{\n        2.2056, 0.2183, -0.0795, 0.0451, -0.3169, 0.0165, -0.1375\n    }};\n\n    mjolnir::FlexibleLocalDihedralPotential<real_type> pot(k, term);\n\n    const real_type x_min = -pi;\n    const real_type x_max =  pi;\n\n    mjolnir::test::check_potential(pot, x_min, x_max, tol, h, N);\n}\n\nBOOST_AUTO_TEST_CASE(FlexibleLocalDihedral_float)\n{\n    using real_type = float;\n    constexpr std::size_t N   = 100;\n    constexpr real_type   h   = 1e-2;\n    constexpr real_type   tol = 1e-2;\n    constexpr real_type   pi = mjolnir::math::constants<real_type>::pi();\n\n    const real_type k  = 1.0;\n    const std::array<real_type, 7> term{{\n        2.2056, 0.2183, -0.0795, 0.0451, -0.3169, 0.0165, -0.1375\n    }};\n\n    mjolnir::FlexibleLocalDihedralPotential<real_type> pot(k, term);\n\n    const real_type x_min = -pi;\n    const real_type x_max =  pi;\n\n    mjolnir::test::check_potential(pot, x_min, x_max, tol, h, N);\n}\n", "meta": {"hexsha": "25ce4e2aefd5c12fd2ec29cb83be7acedd92ba6d", "size": 1579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_flp_dihedral_potential.cpp", "max_stars_repo_name": "ToruNiina/Mjolnir", "max_stars_repo_head_hexsha": "44435dd3afc12f5c8ea27a66d7ab282df3e588ff", "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_flp_dihedral_potential.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_flp_dihedral_potential.cpp", "max_forks_repo_name": "Mjolnir-MD/Mjolnir", "max_forks_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "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": 29.2407407407, "max_line_length": 73, "alphanum_fraction": 0.6915769474, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5163766374129053}}
{"text": "#include \"drake/common/test_utilities/eigen_geometry_compare.h\"\n\n#include <Eigen/Dense>\n\n#include \"drake/common/test_utilities/eigen_matrix_compare.h\"\n#include \"drake/common/text_logging.h\"\n\nnamespace drake {\n\n::testing::AssertionResult ExpectRotMat(const Eigen::Matrix3d& R,\n                                        double tolerance) {\n  // Don't have access to common EXPECT_NEAR low-level macros :(\n  const double det = R.determinant();\n  const double det_err = fabs(det - 1);\n  if (det_err > tolerance) {\n    return ::testing::AssertionFailure()\n        << \"Determinant of R = \" << det << \" != 1 by an error of \"\n        << det_err << \"\\nR = \" << R;\n  }\n  return CompareMatrices(Eigen::Matrix3d::Identity(), R.transpose() * R,\n                         tolerance)\n      << \"Rotation matrix is non-orthonormal\";\n}\n\n::testing::AssertionResult CompareTransforms(\n    const Eigen::Isometry3d &X_expected, const Eigen::Isometry3d &X_actual,\n    double tolerance) {\n  ::testing::AssertionResult check_R_expected =\n      ExpectRotMat(X_expected.rotation(), tolerance);\n  if (!check_R_expected) {\n    return check_R_expected << \"(X_expected)\";\n  }\n  ::testing::AssertionResult check_R_actual =\n      ExpectRotMat(X_actual.rotation(), tolerance);\n  if (!check_R_actual) {\n    return check_R_actual << \"(X_actual)\";\n  }\n  return CompareMatrices(X_expected.matrix(), X_actual.matrix(), tolerance);\n}\n\n}   // namespace drake\n", "meta": {"hexsha": "cbbe2ba9fba8f10281940cd980ba648b2dc724fe", "size": 1415, "ext": "cc", "lang": "C++", "max_stars_repo_path": "common/test_utilities/eigen_geometry_compare.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_utilities/eigen_geometry_compare.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_utilities/eigen_geometry_compare.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": 33.6904761905, "max_line_length": 76, "alphanum_fraction": 0.667844523, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.5163766373222545}}
{"text": "\n\n#include <NTL/GF2E.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\n\nGF2EInfoT::GF2EInfoT(const GF2X& NewP)\n{\n   ref_count = 1;\n\n   build(p, NewP);\n\n   if (p.size == 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         KarCross = 4;\n      else\n         KarCross = 8;\n   }\n   else if (p.size == 2)\n      KarCross = 8;\n   else if (p.size <= 5)\n      KarCross = 4;\n   else if (p.size == 6)\n      KarCross = 3;\n   else \n      KarCross = 2;\n\n\n   if (p.size <= 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         ModCross = 20;\n      else\n         ModCross = 40;\n   }\n   else if (p.size <= 2)\n      ModCross = 75;\n   else if (p.size <= 4)\n      ModCross = 50;\n   else\n      ModCross = 25;\n\n   if (p.size == 1) {\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\n         DivCross = 100;\n      else\n         DivCross = 200;\n   }\n   else if (p.size == 2)\n      DivCross = 400;\n   else if (p.size <= 4)\n      DivCross = 200;\n   else if (p.size == 5)\n      DivCross = 150;\n   else if (p.size <= 13)\n      DivCross = 100;\n   else \n      DivCross = 75;\n\n   _card_init = 0;\n   _card_exp = p.n;\n}\n\n\nconst ZZ& GF2E::cardinality()\n{\n   if (!GF2EInfo) Error(\"GF2E::cardinality: undefined modulus\");\n\n   if (!GF2EInfo->_card_init) {\n      power(GF2EInfo->_card, 2, GF2EInfo->_card_exp);\n      GF2EInfo->_card_init = 1;\n   }\n\n   return GF2EInfo->_card;\n}\n\n\n\n\nGF2EInfoT *GF2EInfo = 0; \n\n\n\ntypedef GF2EInfoT *GF2EInfoPtr;\n\n\nstatic \nvoid CopyPointer(GF2EInfoPtr& dst, GF2EInfoPtr src)\n{\n   if (src == dst) return;\n\n   if (dst) {\n      dst->ref_count--;\n\n      if (dst->ref_count < 0) \n         Error(\"internal error: negative GF2EContext ref_count\");\n\n      if (dst->ref_count == 0) delete dst;\n   }\n\n   if (src) {\n      if (src->ref_count == NTL_MAX_LONG) \n         Error(\"internal error: GF2EContext ref_count overflow\");\n\n      src->ref_count++;\n\n   }\n\n   dst = src;\n}\n   \n\n\n\nvoid GF2E::init(const GF2X& p)\n{\n   GF2EContext c(p);\n   c.restore();\n}\n\n\nGF2EContext::GF2EContext(const GF2X& p)\n{\n   ptr = NTL_NEW_OP GF2EInfoT(p);\n}\n\nGF2EContext::GF2EContext(const GF2EContext& a)\n{\n   ptr = 0;\n   CopyPointer(ptr, a.ptr);\n}\n\nGF2EContext& GF2EContext::operator=(const GF2EContext& a)\n{\n   CopyPointer(ptr, a.ptr);\n   return *this;\n}\n\n\nGF2EContext::~GF2EContext()\n{\n   CopyPointer(ptr, 0);\n}\n\nvoid GF2EContext::save()\n{\n   CopyPointer(ptr, GF2EInfo);\n}\n\nvoid GF2EContext::restore() const\n{\n   CopyPointer(GF2EInfo, ptr);\n}\n\n\n\nGF2EBak::~GF2EBak()\n{\n   if (MustRestore)\n      CopyPointer(GF2EInfo, ptr);\n\n   CopyPointer(ptr, 0);\n}\n\nvoid GF2EBak::save()\n{\n   MustRestore = 1;\n   CopyPointer(ptr, GF2EInfo);\n}\n\n\n\nvoid GF2EBak::restore()\n{\n   MustRestore = 0;\n   CopyPointer(GF2EInfo, ptr);\n}\n\n\n\nconst GF2E& GF2E::zero()\n{\n   static GF2E z(GF2E_NoAlloc);\n   return z;\n}\n\n\n\nistream& operator>>(istream& s, GF2E& x)\n{\n   GF2X y;\n\n   s >> y;\n   conv(x, y);\n\n   return s;\n}\n\nvoid div(GF2E& x, const GF2E& a, const GF2E& b)\n{\n   GF2E t;\n\n   inv(t, b);\n   mul(x, a, t);\n}\n\nvoid div(GF2E& x, GF2 a, const GF2E& b)\n{\n   inv(x, b);\n   mul(x, x, a);\n}\n\nvoid div(GF2E& x, long a, const GF2E& b)\n{\n   inv(x, b);\n   mul(x, x, a);\n}\n\n\nvoid inv(GF2E& x, const GF2E& a)\n{\n   InvMod(x._GF2E__rep, a._GF2E__rep, GF2E::modulus());\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "66f6e7e6088bcdcae75c0853cc6cc34528d99502", "size": 3189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/src/GF2E.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-17T20:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T19:52:14.000Z", "max_issues_repo_path": "RUNETag/WinNTL/src/GF2E.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/src/GF2E.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 13.9868421053, "max_line_length": 65, "alphanum_fraction": 0.5672624647, "num_tokens": 1154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5163766260391923}}
{"text": "#pragma once\n/**\n\n   @file Leadline.hpp\n   @brief Basic leadline response.\n\n*/\n\n#include <atomic>\n#include <chrono>\n#include <cinttypes>\n#include <memory>\n\n#include <boost/statechart/detail/memory.hpp>\n#include <boost/statechart/fifo_scheduler.hpp>\n#include <boost/statechart/event_base.hpp>\n\n#include <yaml-cpp/yaml.h>\n\n#ifdef _MSC_VER\n#pragma warning(push, 0)\n#endif\n#include <dds/pub/Publisher.hpp>\n#include <dds/sub/Subscriber.hpp>\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <mimir/IAlgorithm.hpp>\n\nnamespace mimir\n{\n  namespace algorithm\n  {\n\n    /**\n       @brief Leadline predicted response.\n\n       \\rst\n\n       This algorithm calculates an expected depth response of the leadline based on the\n       provided input parameters. The output is the solution to the initial value problem\n       over a prediction horizon of ``prediction_horizon_sec`` seconds, with\n       discretization step equal to ``time_step_ms`` milliseconds.\n\n       Let :math:`x(t) \\in \\mathbb{R}` be the depth in meters at a given time\n       :math:`t`. Let :math:`x_d \\in \\mathbb{R}` and :math:`\\tau \\in \\mathbb{R}_{>0}` be a\n       setpoint depth [m] and time constant [s], respectively. Suppose :math:`t_f>0` is\n       the prediction horizon and :math:`\\delta t` is a descretization the step\n       size. Define the set of discretized time points as :math:`\\mathcal{T} := \\{ t : t =\n       k\\delta t\\, \\forall k \\in \\mathbb{Z}_{\\geq 0}, t \\in [0, t_f] \\}`. The solution to the\n       initial value problem\n\n       .. math::\n          :nowrap:\n\n          \\begin{align}\n          \\dat x(t) &= \\frac{x(t)-x_d}{\\tau} \\\\\n          x(0) &= 0\n          \\end{align}\n\n       is :math:`x(t)` and the solution set :math:`\\mathcal{X} := \\{ z : z = x(t)\\, \\forall t \\in \\mathcal{T} \\}`.\n\n       The algorithm solution provides :math:`(\\mathcal{T},\\mathcal{X})` given :math:`(x_d,\\tau)`.\n\n       \\endrst\n\n    */\n    class Leadline : public IAlgorithm\n    {\n    public:\n      /**\n         @brief Leadline constructor.\n\n         The constructor parses the specification from the given YAML\n         node. It establishes data structures and sets up DDS readers\n         and writers according to the input/output scheme of the\n         algorithm. The following YAML code block shows the expected\n         layout of the ``Leadline`` map of a input config file.  The\n         inputs, outputs, and initial conditions are communicated with\n         DDS communication. Common is their DDS topic and DDS\n         identifier. The specification is deemed self-explanatory.\n\n         \\rst\n\n         .. code-block:: yaml\n\n             time_step_ms: 200\n             prediction_horizon_sec: 1000\n             inputs:\n               parameters:                   # DDS type: fkin::IdVec2d\n                 topic: leadline_parameters\n                 id: Leadline\n                 default: [350, 160]\n             outputs:                        # DDS type: fkin::BatchIdVec1d\n               depth:\n                 topic: leadline_response\n                 id: Leadline\n\n         \\endrst\n\n         @param [in] config YAML configuration from input file.\n         @param [in] scheduler State machine scheduler, needed to post events to state machine.\n         @param [in] machine State machine processor handle, needed to post events to state machine.\n         @param publisher DDS data writer to send data.\n         @param subscriber DDS data reader to receive data.\n      */\n      explicit Leadline(\n          const YAML::Node& config,\n          boost::statechart::fifo_scheduler<>& scheduler,\n          boost::statechart::fifo_scheduler<>::processor_handle machine,\n          dds::pub::Publisher publisher,\n          dds::sub::Subscriber subscriber);\n      /// Destructor.\n      virtual ~Leadline();\n      /// See base class.\n      virtual void solve(const std::atomic<bool>& cancel_token);\n      /// See base class.\n      virtual void initialize(const std::atomic<bool>& cancel_token);\n      /// See base class.\n      virtual void timer(const std::atomic<bool>& cancel_token);\n      /// Name identifier of algorithm.\n      virtual inline const char* name() { return \"Leadline\"; }\n      void event(boost::statechart::event_base * const event);\n\n    private:\n      /// March simulation time one time step ahead.\n      inline void step_time() { m_next_step += m_time_step; m_now += m_time_step; }\n      Leadline() = delete;\n      class Impl;\n      std::unique_ptr<Impl> m_impl; ///< Holds the implementation of the algorithm.\n      boost::statechart::fifo_scheduler<> & m_scheduler; ///< Members for state machine.\n      boost::statechart::fifo_scheduler<>::processor_handle m_stateMachine; ///< Member for state machine.\n      const std::chrono::milliseconds m_time_step; ///< Discrete time step.\n      std::chrono::steady_clock::time_point m_next_step; ///< Simulation time point.\n      std::chrono::system_clock::time_point m_now;\n      const YAML::Node m_config; ///< YAML configuration for algorithm.\n    };\n\n  }\n}\n", "meta": {"hexsha": "ca5108d077e6dadac09c3cad6dc7323ef4c4879f", "size": 4982, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mimir/algorithm/Leadline.hpp", "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/mimir/algorithm/Leadline.hpp", "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/mimir/algorithm/Leadline.hpp", "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": 35.0845070423, "max_line_length": 114, "alphanum_fraction": 0.6286631875, "num_tokens": 1170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5163766204429866}}
{"text": "// Copyright (C) 2015 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: Benjamin Nuernberger (bnuernberger@cs.ucsb.edu)\n\n#include \"theia/sfm/estimators/estimate_dominant_plane_from_points.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <limits>\n#include <memory>\n#include <vector>\n\n#include \"theia/sfm/create_and_initialize_ransac_variant.h\"\n#include \"theia/sfm/pose/util.h\"\n#include \"theia/solvers/estimator.h\"\n#include \"theia/solvers/sample_consensus_estimator.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\nnamespace {\n\nusing Eigen::Vector3d;\n\n// An estimator for computing a dominant plane from a set of 3D points.\nclass DominantPlaneEstimator : public Estimator<Vector3d, Plane> {\n public:\n  DominantPlaneEstimator() {}\n\n  // 3 non-collinear points are needed to determine a plane.\n  double SampleSize() const { return 3; }\n\n  // Estimates candidate dominant planes from three 3D points.\n  bool EstimateModel(const std::vector<Vector3d>& points,\n                     std::vector<Plane>* planes) const {\n    // If the points are collinear, there are no possible solutions.\n    static const double kTolerance = 1e-6;\n    const Vector3d a = points[1] - points[0];\n    const Vector3d b = points[2] - points[0];\n    const Vector3d cross = a.cross(b);\n    if (cross.squaredNorm() < kTolerance) {\n      VLOG(3) << \"The 3 world points are collinear! No solution for a plane \"\n                 \"exists.\";\n      return false;\n    }\n    Plane plane;\n    plane.point = points[0];\n    plane.unit_normal = cross.normalized();\n\n    planes->emplace_back(plane);\n    return true;\n  }\n\n  // The error for a point given a plane model is the point-to-plane distance.\n  double Error(const Vector3d& point, const Plane& plane) const {\n    return std::abs(plane.unit_normal.dot(point - plane.point));\n  }\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(DominantPlaneEstimator);\n};\n\n}  // namespace\n\nbool EstimateDominantPlaneFromPoints(const RansacParameters& ransac_params,\n                                     const RansacType& ransac_type,\n                                     const std::vector<Vector3d>& points,\n                                     Plane* plane,\n                                     RansacSummary* ransac_summary) {\n  DominantPlaneEstimator dominant_plane_estimator;\n  std::unique_ptr<SampleConsensusEstimator<DominantPlaneEstimator> > ransac =\n      CreateAndInitializeRansacVariant(\n          ransac_type, ransac_params, dominant_plane_estimator);\n  // Estimate the dominant plane.\n  return ransac->Estimate(points, plane, ransac_summary);\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "4e78d7b3c73e488bfb27612e56737a046e897cea", "size": 4266, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/estimators/estimate_dominant_plane_from_points.cc", "max_stars_repo_name": "urbste/TheiaSfM", "max_stars_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T03:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T08:08:45.000Z", "max_issues_repo_path": "src/theia/sfm/estimators/estimate_dominant_plane_from_points.cc", "max_issues_repo_name": "urbste/TheiaSfM", "max_issues_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/estimators/estimate_dominant_plane_from_points.cc", "max_forks_repo_name": "urbste/TheiaSfM", "max_forks_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-20T03:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T08:08:52.000Z", "avg_line_length": 39.5, "max_line_length": 78, "alphanum_fraction": 0.7119081106, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5163766203976612}}
{"text": "\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include \"calc/geometry.hpp\"\n\nusing namespace calc;\n\nBOOST_AUTO_TEST_SUITE( geometryTest )\n\nBOOST_AUTO_TEST_CASE(FailTest)\n{\n  BOOST_CHECK_NE(5, geometry::sqr(2));\n}\n\nBOOST_AUTO_TEST_CASE(PassTest)\n{\n  BOOST_CHECK_EQUAL(4, geometry::sqr(2));\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "39f02f76d1680bfc4b20c3ad081d17c78c0852e7", "size": 334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/calc/geometryTest.cpp", "max_stars_repo_name": "cernoel/cmake-boost-unittests-skeleton", "max_stars_repo_head_hexsha": "a1ea4eb806780b2946c043dd1eb7223019eed799", "max_stars_repo_licenses": ["MIT"], "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/calc/geometryTest.cpp", "max_issues_repo_name": "cernoel/cmake-boost-unittests-skeleton", "max_issues_repo_head_hexsha": "a1ea4eb806780b2946c043dd1eb7223019eed799", "max_issues_repo_licenses": ["MIT"], "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/calc/geometryTest.cpp", "max_forks_repo_name": "cernoel/cmake-boost-unittests-skeleton", "max_forks_repo_head_hexsha": "a1ea4eb806780b2946c043dd1eb7223019eed799", "max_forks_repo_licenses": ["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.9047619048, "max_line_length": 41, "alphanum_fraction": 0.7784431138, "num_tokens": 87, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5163524171429129}}
{"text": "#define BOOST_TEST_MODULE example\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\n//____________________________________________________________________________//\n\nBOOST_AUTO_TEST_CASE( test )\n{\n    double v1 = 1.23456e28;\n    double v2 = 1.23457e28;\n\n    BOOST_REQUIRE_CLOSE( v1, v2, 0.001 );\n    // Absolute value of difference between these two values is 1e+23.\n    // But we are interested only that it does not exeed 0.001% of a values compared\n    // And this test will pass.\n}\n\n//____________________________________________________________________________//\n", "meta": {"hexsha": "8f9eb775d2cf5e644c6e4162dd34f7b9c599ebde", "size": 616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/test/doc/src/examples/example43.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/test/doc/src/examples/example43.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/test/doc/src/examples/example43.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": 32.4210526316, "max_line_length": 84, "alphanum_fraction": 0.7775974026, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5163524129582012}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2014 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\n#include \"ViewerCore.h\"\n#include \"gl.h\"\n#include \"../quat_to_mat.h\"\n#include \"../snap_to_fixed_up.h\"\n#include \"../look_at.h\"\n#include \"../frustum.h\"\n#include \"../ortho.h\"\n#include \"../massmatrix.h\"\n#include \"../barycenter.h\"\n#include \"../PI.h\"\n#include <Eigen/Geometry>\n#include <iostream>\n\nIGL_INLINE void igl::opengl::ViewerCore::align_camera_center(\n  const Eigen::MatrixXd& V,\n  const Eigen::MatrixXi& F)\n{\n  if(V.rows() == 0)\n    return;\n\n  get_scale_and_shift_to_fit_mesh(V,F,model_zoom,model_translation);\n  // Rather than crash on empty mesh...\n  if(V.size() > 0)\n  {\n    object_scale = (V.colwise().maxCoeff() - V.colwise().minCoeff()).norm();\n  }\n}\n\nIGL_INLINE void igl::opengl::ViewerCore::get_scale_and_shift_to_fit_mesh(\n  const Eigen::MatrixXd& V,\n  const Eigen::MatrixXi& F,\n  float& zoom,\n  Eigen::Vector3f& shift)\n{\n  if (V.rows() == 0)\n    return;\n\n  Eigen::MatrixXd BC;\n  if (F.rows() <= 1)\n  {\n    BC = V;\n  } else\n  {\n    igl::barycenter(V,F,BC);\n  }\n  return get_scale_and_shift_to_fit_mesh(BC,zoom,shift);\n}\n\nIGL_INLINE void igl::opengl::ViewerCore::align_camera_center(\n  const Eigen::MatrixXd& V)\n{\n  if(V.rows() == 0)\n    return;\n\n  get_scale_and_shift_to_fit_mesh(V,model_zoom,model_translation);\n  // Rather than crash on empty mesh...\n  if(V.size() > 0)\n  {\n    object_scale = (V.colwise().maxCoeff() - V.colwise().minCoeff()).norm();\n  }\n}\n\nIGL_INLINE void igl::opengl::ViewerCore::get_scale_and_shift_to_fit_mesh(\n  const Eigen::MatrixXd& V,\n  float& zoom,\n  Eigen::Vector3f& shift)\n{\n  if (V.rows() == 0)\n    return;\n\n  auto min_point = V.colwise().minCoeff();\n  auto max_point = V.colwise().maxCoeff();\n  auto centroid  = (0.5*(min_point + max_point)).eval();\n  shift.setConstant(0);\n  shift.head(centroid.size()) = -centroid.cast<float>();\n  zoom = 2.0 / (max_point-min_point).array().abs().maxCoeff();\n}\n\n\nIGL_INLINE void igl::opengl::ViewerCore::clear_framebuffers()\n{\n  glClearColor(background_color[0],\n               background_color[1],\n               background_color[2],\n               1.0f);\n  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n}\n\nIGL_INLINE void igl::opengl::ViewerCore::draw(\n  ViewerData& data,\n  bool update_matrices)\n{\n  using namespace std;\n  using namespace Eigen;\n\n  if (depth_test)\n    glEnable(GL_DEPTH_TEST);\n  else\n    glDisable(GL_DEPTH_TEST);\n\n  glEnable(GL_BLEND);\n  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n  /* Bind and potentially refresh mesh/line/point data */\n  if (data.dirty)\n  {\n    data.updateGL(data, data.invert_normals,data.meshgl);\n    data.dirty = MeshGL::DIRTY_NONE;\n  }\n  data.meshgl.bind_mesh();\n\n  // Initialize uniform\n  glViewport(viewport(0), viewport(1), viewport(2), viewport(3));\n\n  if(update_matrices)\n  {\n    model = Eigen::Matrix4f::Identity();\n    view  = Eigen::Matrix4f::Identity();\n    proj  = Eigen::Matrix4f::Identity();\n\n    // Set view\n    look_at( camera_eye, camera_center, camera_up, view);\n\n    float width  = viewport(2);\n    float height = viewport(3);\n\n    // Set projection\n    if (orthographic)\n    {\n      float length = (camera_eye - camera_center).norm();\n      float h = tan(camera_view_angle/360.0 * igl::PI) * (length);\n      ortho(-h*width/height, h*width/height, -h, h, camera_dnear, camera_dfar,proj);\n    }\n    else\n    {\n      float fH = tan(camera_view_angle / 360.0 * igl::PI) * camera_dnear;\n      float fW = fH * (double)width/(double)height;\n      frustum(-fW, fW, -fH, fH, camera_dnear, camera_dfar,proj);\n    }\n    // end projection\n\n    // Set model transformation\n    float mat[16];\n    igl::quat_to_mat(trackball_angle.coeffs().data(), mat);\n\n    for (unsigned i=0;i<4;++i)\n      for (unsigned j=0;j<4;++j)\n        model(i,j) = mat[i+4*j];\n\n    // Why not just use Eigen::Transform<double,3,Projective> for model...?\n    model.topLeftCorner(3,3)*=camera_zoom;\n    model.topLeftCorner(3,3)*=model_zoom;\n    model.col(3).head(3) += model.topLeftCorner(3,3)*model_translation;\n  }\n\n  // Send transformations to the GPU\n  GLint modeli = glGetUniformLocation(data.meshgl.shader_mesh,\"model\");\n  GLint viewi  = glGetUniformLocation(data.meshgl.shader_mesh,\"view\");\n  GLint proji  = glGetUniformLocation(data.meshgl.shader_mesh,\"proj\");\n  glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());\n  glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());\n  glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());\n\n  // Light parameters\n  GLint specular_exponenti    = glGetUniformLocation(data.meshgl.shader_mesh,\"specular_exponent\");\n  GLint light_position_worldi = glGetUniformLocation(data.meshgl.shader_mesh,\"light_position_world\");\n  GLint lighting_factori      = glGetUniformLocation(data.meshgl.shader_mesh,\"lighting_factor\");\n  GLint fixed_colori          = glGetUniformLocation(data.meshgl.shader_mesh,\"fixed_color\");\n  GLint texture_factori       = glGetUniformLocation(data.meshgl.shader_mesh,\"texture_factor\");\n\n  glUniform1f(specular_exponenti, data.shininess);\n  Vector3f rev_light = -1.*light_position;\n  glUniform3fv(light_position_worldi, 1, rev_light.data());\n  glUniform1f(lighting_factori, lighting_factor); // enables lighting\n  glUniform4f(fixed_colori, 0.0, 0.0, 0.0, 0.0);\n\n  if (data.V.rows()>0)\n  {\n    // Render fill\n    if (data.show_faces)\n    {\n      // Texture\n      glUniform1f(texture_factori, data.show_texture ? 1.0f : 0.0f);\n      data.meshgl.draw_mesh(true);\n      glUniform1f(texture_factori, 0.0f);\n    }\n\n    // Render wireframe\n    if (data.show_lines)\n    {\n      glLineWidth(data.line_width);\n      glUniform4f(fixed_colori, \n        data.line_color[0], \n        data.line_color[1],\n        data.line_color[2], 1.0f);\n      data.meshgl.draw_mesh(false);\n      glUniform4f(fixed_colori, 0.0f, 0.0f, 0.0f, 0.0f);\n    }\n  }\n\n  if (data.show_overlay)\n  {\n    if (data.show_overlay_depth)\n      glEnable(GL_DEPTH_TEST);\n    else\n      glDisable(GL_DEPTH_TEST);\n\n    if (data.lines.rows() > 0)\n    {\n      data.meshgl.bind_overlay_lines();\n      modeli = glGetUniformLocation(data.meshgl.shader_overlay_lines,\"model\");\n      viewi  = glGetUniformLocation(data.meshgl.shader_overlay_lines,\"view\");\n      proji  = glGetUniformLocation(data.meshgl.shader_overlay_lines,\"proj\");\n\n      glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());\n      glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());\n      glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());\n      // This must be enabled, otherwise glLineWidth has no effect\n      glEnable(GL_LINE_SMOOTH);\n      glLineWidth(data.line_width);\n\n      data.meshgl.draw_overlay_lines();\n    }\n\n    if (data.points.rows() > 0)\n    {\n      data.meshgl.bind_overlay_points();\n      modeli = glGetUniformLocation(data.meshgl.shader_overlay_points,\"model\");\n      viewi  = glGetUniformLocation(data.meshgl.shader_overlay_points,\"view\");\n      proji  = glGetUniformLocation(data.meshgl.shader_overlay_points,\"proj\");\n\n      glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());\n      glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());\n      glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());\n      glPointSize(data.point_size);\n\n      data.meshgl.draw_overlay_points();\n    }\n\n    glEnable(GL_DEPTH_TEST);\n  }\n\n}\n\nIGL_INLINE void igl::opengl::ViewerCore::draw_buffer(ViewerData& data,\n  bool update_matrices,\n  Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& R,\n  Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& G,\n  Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& B,\n  Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& A)\n{\n  assert(R.rows() == G.rows() && G.rows() == B.rows() && B.rows() == A.rows());\n  assert(R.cols() == G.cols() && G.cols() == B.cols() && B.cols() == A.cols());\n\n  unsigned x = R.rows();\n  unsigned y = R.cols();\n\n  // Create frame buffer\n  GLuint frameBuffer;\n  glGenFramebuffers(1, &frameBuffer);\n  glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);\n\n  // Create texture to hold color buffer\n  GLuint texColorBuffer;\n  glGenTextures(1, &texColorBuffer);\n  glBindTexture(GL_TEXTURE_2D, texColorBuffer);\n\n  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);\n\n  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\n  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texColorBuffer, 0);\n\n  // Create Renderbuffer Object to hold depth and stencil buffers\n  GLuint rboDepthStencil;\n  glGenRenderbuffers(1, &rboDepthStencil);\n  glBindRenderbuffer(GL_RENDERBUFFER, rboDepthStencil);\n  glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, x, y);\n  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rboDepthStencil);\n\n  assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);\n\n  glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);\n\n  // Clear the buffer\n  glClearColor(background_color(0), background_color(1), background_color(2), 0.f);\n  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n  // Save old viewport\n  Eigen::Vector4f viewport_ori = viewport;\n  viewport << 0,0,x,y;\n\n  // Draw\n  draw(data,update_matrices);\n\n  // Restore viewport\n  viewport = viewport_ori;\n\n  // Copy back in the given Eigen matrices\n  GLubyte* pixels = (GLubyte*)calloc(x*y*4,sizeof(GLubyte));\n  glReadPixels\n  (\n   0, 0,\n   x, y,\n   GL_RGBA, GL_UNSIGNED_BYTE, pixels\n   );\n\n  int count = 0;\n  for (unsigned j=0; j<y; ++j)\n  {\n    for (unsigned i=0; i<x; ++i)\n    {\n      R(i,j) = pixels[count*4+0];\n      G(i,j) = pixels[count*4+1];\n      B(i,j) = pixels[count*4+2];\n      A(i,j) = pixels[count*4+3];\n      ++count;\n    }\n  }\n\n  // Clean up\n  free(pixels);\n  glBindFramebuffer(GL_FRAMEBUFFER, 0);\n  glDeleteRenderbuffers(1, &rboDepthStencil);\n  glDeleteTextures(1, &texColorBuffer);\n  glDeleteFramebuffers(1, &frameBuffer);\n}\n\nIGL_INLINE void igl::opengl::ViewerCore::set_rotation_type(\n  const igl::opengl::ViewerCore::RotationType & value)\n{\n  using namespace Eigen;\n  using namespace std;\n  const RotationType old_rotation_type = rotation_type;\n  rotation_type = value;\n  if(rotation_type == ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP &&\n    old_rotation_type != ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP)\n  {\n    snap_to_fixed_up(Quaternionf(trackball_angle),trackball_angle);\n  }\n}\n\n\nIGL_INLINE igl::opengl::ViewerCore::ViewerCore()\n{\n  // Default colors\n  background_color << 0.3f, 0.3f, 0.5f, 1.0f;\n\n  // Default lights settings\n  light_position << 0.0f, -0.30f, -5.0f;\n  lighting_factor = 1.0f; //on\n\n  // Default trackball\n  trackball_angle = Eigen::Quaternionf::Identity();\n  set_rotation_type(ViewerCore::ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP);\n\n  // Defalut model viewing parameters\n  model_zoom = 1.0f;\n  model_translation << 0,0,0;\n\n  // Camera parameters\n  camera_zoom = 1.0f;\n  orthographic = false;\n  camera_view_angle = 45.0;\n  camera_dnear = 1.0;\n  camera_dfar = 100.0;\n  camera_eye << 0, 0, 5;\n  camera_center << 0, 0, 0;\n  camera_up << 0, 1, 0;\n\n  depth_test = true;\n\n  is_animating = false;\n  animation_max_fps = 30.;\n\n  viewport.setZero();\n}\n\nIGL_INLINE void igl::opengl::ViewerCore::init()\n{\n}\n\nIGL_INLINE void igl::opengl::ViewerCore::shut()\n{\n}\n", "meta": {"hexsha": "758e5be3a906ba08b4ff34801b202f6185537580", "size": 11482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FSDF/libs/libigl-master/include/igl/opengl/ViewerCore.cpp", "max_stars_repo_name": "szat/FSDF", "max_stars_repo_head_hexsha": "076129c0dfd2ac2354cc40ade363b96f4b6248fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 199.0, "max_stars_repo_stars_event_min_datetime": "2018-02-26T20:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:09:52.000Z", "max_issues_repo_path": "FSDF/libs/libigl-master/include/igl/opengl/ViewerCore.cpp", "max_issues_repo_name": "szat/FSDF", "max_issues_repo_head_hexsha": "076129c0dfd2ac2354cc40ade363b96f4b6248fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-03-20T02:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T01:13:22.000Z", "max_forks_repo_path": "FSDF/libs/libigl-master/include/igl/opengl/ViewerCore.cpp", "max_forks_repo_name": "szat/FSDF", "max_forks_repo_head_hexsha": "076129c0dfd2ac2354cc40ade363b96f4b6248fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2018-02-28T01:33:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T16:06:19.000Z", "avg_line_length": 29.0683544304, "max_line_length": 107, "alphanum_fraction": 0.6907333217, "num_tokens": 3197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.516350028243237}}
{"text": "#pragma once\n#ifndef CANNON_MATH_LATTICE_POINTS_H\n#define CANNON_MATH_LATTICE_POINTS_H \n\n/*!\n * \\file cannon/math/lattice_points.hpp\n * \\brief File containing utilities for working with points making up a lattice\n * in arbitrary real vector spaces.\n */\n\n#include <queue>\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace math {\n\n      using VectorXu = Matrix<unsigned int, Dynamic, 1>;\n\n      /*!\n       * \\brief Generate all lattice points on an integer-valued grid.\n       *\n       * \\param dim Which dimension of the lattice to generate.\n       * \\param sizes Number of elements in each dimension of the grid.\n       *\n       * \\return Lattice points for dimensions 0 through dim-1\n       */\n      std::vector<VectorXu> make_lattice_points(unsigned int dim, const VectorXu& sizes) {\n        std::vector<VectorXu> ret_vec;\n\n        if (dim == 1) {\n          for (unsigned int i = 0; i < sizes[dim-1]; i++) {\n            VectorXu tmp = VectorXu::Zero(dim);\n            tmp[0] = i;\n            ret_vec.push_back(tmp);\n          }\n        } else {\n          for (unsigned int i = 0; i < sizes[dim-1]; i++) {\n            auto smaller_vec = make_lattice_points(dim-1, sizes);\n            for (const auto& coord : smaller_vec) {\n              VectorXu tmp = VectorXu::Zero(dim);\n              tmp.head(dim-1) = coord;\n              tmp[dim-1] = i;\n\n              ret_vec.push_back(tmp);\n            }\n          }\n        }\n\n        return ret_vec;\n      }\n\n      /*!\n       * \\brief Generate all lattice points on an integer-valued grid.\n       *\n       * \\param sizes Number of elements in each dimension of the grid.\n       *\n       * \\return Lattice points for the grid.\n       */\n      std::vector<VectorXu> make_lattice_points(const VectorXu& sizes) {\n        return make_lattice_points(sizes.size(), sizes);\n      }\n\n  } // namespace math\n} // namespace cannon\n\n\n#endif /* ifndef CANNON_MATH_LATTICE_POINTS_H */\n", "meta": {"hexsha": "70a4c803bbaa5ed3d0490b911f3afb053dd3d482", "size": 1944, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/math/lattice_points.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/lattice_points.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/lattice_points.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": 27.3802816901, "max_line_length": 90, "alphanum_fraction": 0.591563786, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.5163500234621381}}
{"text": "/* test_exponential_distribution.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_exponential_distribution.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\r\n *\r\n */\r\n\r\n#include <boost/random/exponential_distribution.hpp>\r\n\r\n#include <limits>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::exponential_distribution<>\r\n#define BOOST_RANDOM_ARG1 lambda\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1.0\r\n#define BOOST_RANDOM_ARG1_VALUE 7.5\r\n\r\n#define BOOST_RANDOM_DIST0_MIN 0\r\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST1_MIN 0\r\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS\r\n#define BOOST_RANDOM_TEST1_MIN 0.0\r\n\r\n#define BOOST_RANDOM_TEST2_PARAMS (1000.0)\r\n#define BOOST_RANDOM_TEST2_MIN 0.0\r\n\r\n#include \"test_distribution.ipp\"\r\n", "meta": {"hexsha": "aa3e233b3c4c2be887297f6730f9144d37ea0329", "size": 1012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_exponential_distribution.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_exponential_distribution.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_exponential_distribution.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": 30.6666666667, "max_line_length": 87, "alphanum_fraction": 0.7835968379, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5163500234621381}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_CHOOSE_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_CHOOSE_HPP\n\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <stan/math/prim/scal/err/check_less_or_equal.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <limits>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the binomial coefficient for the specified integer\n * arguments.\n *\n * The binomial coefficient, \\f${n \\choose k}\\f$, read \"n choose k\", is\n * defined for \\f$0 \\leq k \\leq n\\f$ (otherwise return 0) by\n *\n * \\f${n \\choose k} = \\frac{n!}{k! (n-k)!}\\f$.\n *\n * @param n total number of objects\n * @param k number of objects chosen\n * @return n choose k or 0 iff k > n\n * @throw std::domain_error if either argument is negative or the\n * result will not fit in an int type\n */\ninline int choose(int n, int k) {\n  check_nonnegative(\"choose\", \"n\", n);\n  check_nonnegative(\"choose\", \"k\", k);\n  if (k > n)\n    return 0;\n  const double choices = boost::math::binomial_coefficient<double>(n, k);\n  check_less_or_equal(\"choose\", \"n choose k\", choices,\n                      std::numeric_limits<int>::max());\n  return static_cast<int>(std::round(choices));\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "0b126883671b0e3baf764cd87d072f9b843df32b", "size": 1237, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/scal/fun/choose.hpp", "max_stars_repo_name": "vchiapaikeo/prophet", "max_stars_repo_head_hexsha": "e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/scal/fun/choose.hpp", "max_issues_repo_name": "vchiapaikeo/prophet", "max_issues_repo_head_hexsha": "e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/scal/fun/choose.hpp", "max_forks_repo_name": "vchiapaikeo/prophet", "max_forks_repo_head_hexsha": "e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7", "max_forks_repo_licenses": ["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.4523809524, "max_line_length": 73, "alphanum_fraction": 0.6887631366, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5163480151327723}}
{"text": "#include <NTL/ZZ.h>\n#include \"filereader.h\"\n#include \"generalhelpers.h\"\n#include \"hashing.h\"\n#include \"signing.h\"\n#include <fstream>\n#include <sstream>\n\nint ProcessSinging(const CryptoHelpers::SCommandLineOptions& options);\nint ProcessChecking(const CryptoHelpers::SCommandLineOptions& options);\n\nint main(int argc, char *argv[])\n{\n    CryptoHelpers::SCommandLineOptions options;\n\n    options.m_filename = argv[2];\n    if(strcmp(argv[1], \"-sign\")==0)\n    {\n        options.m_mode = CryptoHelpers::Signing;\n    } else if(strcmp(argv[1], \"-check\") == 0)\n    {\n        if(argc<3)\n        {\n            return 0;\n        }\n        options.m_mode = CryptoHelpers::Checking;\n        options.m_fileWithSignature = argv[3];\n    }\n\n    if(options.m_mode==CryptoHelpers::Signing)\n    {\n        ProcessSinging(options);\n    }\n    else\n    {\n        ProcessChecking(options);\n    }\n}\n\n\nint ProcessSinging(const CryptoHelpers::SCommandLineOptions& options)\n{\n    std::vector<char> fileData;\n    std::ofstream outputFile(options.m_filename + \".sig\");\n    outputFile << \"------------------------------\\n\";\n    outputFile << options.m_filename << std::endl;\n    if (!CryptoHelpers::ReadFile(options.m_filename, fileData))\n    {\n        return 1;\n    }\n\n    unsigned long long hashValue = 0;\n\n    if (fileData.size() != 0)\n    {\n        std::vector<unsigned long long> data;\n        CryptoHelpers::ConvertByteToLong(fileData, data);\n        CryptoHelpers::Hash(data, hashValue);\n    }\n    outputFile << \"H = \" << std::hex << hashValue << '\\n';\n\n\n    NTL::ZZ signature(0);\n    NTL::ZZ y(0);\n    NTL::ZZ k(0);\n    NTL::ZZ g(0);\n    NTL::ZZ z(0);\n    NTL::ZZ u(0);\n    NTL::ZZ x(0);\n    CryptoHelpers::Sign(hashValue,signature,y,k,g,u,z,x);\n    std::string tmp;\n    CryptoHelpers::ConvertLongToString(y, tmp);\n    outputFile << \"Y = \" << tmp << std::endl; \n    CryptoHelpers::ConvertLongToString(k, tmp);\n    outputFile << \"K = \" << tmp << std::endl; \n    CryptoHelpers::ConvertLongToString(signature, tmp);\n    outputFile << \"S = \" << tmp << std::endl;\n    outputFile << \"------------------------------\\n\";\n\n\n    std::ofstream outputadd(options.m_filename + \".sig.add\");\n    outputadd << \"------------------------------\\n\";\n    outputadd << options.m_filename << std::endl;\n    CryptoHelpers::ConvertLongToString(u, tmp);\n    outputadd << \"U = \" << tmp << std::endl;\n    CryptoHelpers::ConvertLongToString(z, tmp);\n    outputadd << \"Z = \" << tmp << std::endl;\n    CryptoHelpers::ConvertLongToString(g, tmp);\n    outputadd << \"G = \" << tmp << std::endl;\n    outputadd << \"------------------------------\\n\";\n\n    return 0;\n}\n\nint ProcessChecking(const CryptoHelpers::SCommandLineOptions& options)\n{\n    std::vector<char> fileData;\n    if (!CryptoHelpers::ReadFile(options.m_filename, fileData))\n    {\n        return 1;\n    }\n\n    unsigned long long hashValue = 0;\n\n    if (fileData.size() != 0)\n    {\n        std::vector<unsigned long long> data;\n        CryptoHelpers::ConvertByteToLong(fileData, data);\n        CryptoHelpers::Hash(data, hashValue);\n    }\n\n\n    NTL::ZZ signature(0);\n    NTL::ZZ y(0);\n    NTL::ZZ k(0);\n    NTL::ZZ g(0);\n    NTL::ZZ z(0);\n    NTL::ZZ u(0);\n    NTL::ZZ x(0);\n    CryptoHelpers::Sign(hashValue, signature, y, k, g, u, z, x);\n\n    std::ifstream fileWithSignature(options.m_fileWithSignature);\n    std::string _tmp;\n    std::getline(fileWithSignature, _tmp);\n    std::getline(fileWithSignature, _tmp);\n    std::getline(fileWithSignature, _tmp);\n    _tmp = std::move(_tmp.substr(4, _tmp.size() - 4));\n    size_t fileHash = 0;\n    std::stringstream sstream;\n    sstream << std::hex << hashValue;\n    std::string _hashStr = sstream.str();\n\n\n    if (_tmp.compare(_hashStr)!=0)\n    {\n        std::cout << \"Wrong hash value!\\n\";\n        return 2;\n    }\n\n\n    std::getline(fileWithSignature, _tmp);\n    _tmp = std::move(_tmp.substr(4, _tmp.size() - 4));\n    CryptoHelpers::ConvertHexStringToLong(_tmp, y);\n\n    std::getline(fileWithSignature, _tmp);\n    _tmp = std::move(_tmp.substr(4, _tmp.size() - 4));\n    CryptoHelpers::ConvertHexStringToLong(_tmp, k);\n\n    std::getline(fileWithSignature, _tmp);\n    _tmp = std::move(_tmp.substr(4, _tmp.size() - 4));\n    CryptoHelpers::ConvertHexStringToLong(_tmp, signature);\n\n\n    if(CryptoHelpers::CheckSignature(hashValue,signature,y,k))\n    {\n        std::cout << \"Signature is correct!\\n\";\n    }\n    else\n    {\n        std::cout << \"Signature is wrong!\\n\";\n    }\n\n\n\n    return 0;\n}", "meta": {"hexsha": "3f80ad6a3adeaf8b11a4b820ef51aceea8f7a412", "size": 4429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lab2/main.cpp", "max_stars_repo_name": "mikhaelmurmur/SimpleHash", "max_stars_repo_head_hexsha": "effb2a4da93ce7c59eb36c5057ea868ba02042ac", "max_stars_repo_licenses": ["MIT"], "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/main.cpp", "max_issues_repo_name": "mikhaelmurmur/SimpleHash", "max_issues_repo_head_hexsha": "effb2a4da93ce7c59eb36c5057ea868ba02042ac", "max_issues_repo_licenses": ["MIT"], "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/main.cpp", "max_forks_repo_name": "mikhaelmurmur/SimpleHash", "max_forks_repo_head_hexsha": "effb2a4da93ce7c59eb36c5057ea868ba02042ac", "max_forks_repo_licenses": ["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.6807228916, "max_line_length": 71, "alphanum_fraction": 0.5972002709, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5163480092815377}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    cpp_int n, a, b; cin >> n >> a >> b;\n    if ((b - a) % 2 == 0) cout << (b - a) / 2 << endl;\n    else cout << min((a - 1), (n - b)) + 1 + (b - a - 1) / 2 << endl;\n}\n", "meta": {"hexsha": "65ec551d4c980b8c6fff922364fc966b465273d1", "size": 361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/agc041/a/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/agc041/a/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/agc041/a/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": 27.7692307692, "max_line_length": 69, "alphanum_fraction": 0.5706371191, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.516348003738442}}
{"text": "//---------------------------------Spheral++----------------------------------//\n// GeomSymmetricTensor -- the symmetric tensor class\n//----------------------------------------------------------------------------//\n#include <cmath>\n#include <limits>\n#include <float.h>\n#include <vector>\n\n#include \"GeomSymmetricTensor.hh\"\n#include \"EigenStruct.hh\"\n#include \"buildEigenVector.hh\"\n#include \"findEigenValues3.hh\"\n#include \"Utilities/SpheralFunctions.hh\"\n#include \"Utilities/rotationMatrix.hh\"\n\n#include \"Jacobi2.hh\"\n\n#include <Eigen/Dense>\n\n#include <cmath>\nusing std::min;\nusing std::max;\nusing std::abs;\n\nnamespace Spheral {\n\nusing std::abs;\n\n//------------------------------------------------------------------------------\n// Return the eigen values and eigen vectors of a symmetric tensor\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n// 3-D.\ntemplate<>\nEigenStruct<3>\nGeomSymmetricTensor<3>::eigenVectors() const {\n\n  // Some useful typedefs.\n  typedef GeomVector<3> Vector;\n  typedef GeomTensor<3> Tensor;\n  typedef GeomSymmetricTensor<3> SymTensor;\n\n  // Tolerances for fuzzy math.\n  const double degenerate = 1.0e-20;\n  const double tolerance = 5.0e-5;\n\n  // Prepare the result.\n  EigenStruct<3> result;\n\n  // Create a scaled version of this tensor, with all elements in the range [-1,1].\n  const double fscale = max(10.0*std::numeric_limits<double>::epsilon(), this->maxAbsElement());\n  CHECK(fscale > 0.0);\n  const double fscalei = 1.0/fscale;\n  SymTensor A = (*this)*fscalei;\n\n  // Check for any degenerate elements, and just zero 'em out.\n  A.xx(abs(A.xx()) < degenerate ? 0.0 : A.xx());\n  A.xy(abs(A.xy()) < degenerate ? 0.0 : A.xy());\n  A.xz(abs(A.xz()) < degenerate ? 0.0 : A.xz());\n  A.yy(abs(A.yy()) < degenerate ? 0.0 : A.yy());\n  A.yz(abs(A.yz()) < degenerate ? 0.0 : A.yz());\n  A.zz(abs(A.zz()) < degenerate ? 0.0 : A.zz());\n\n// #ifdef USEJACOBI\n\n//   // Use the Jacobi iterative diagonalization method to determine\n//   // the eigen values/vectors.\n//   const int nrot = jacobiDiagonalize<Dim<3> >(A,\n//                                               result.eigenVectors,\n//                                               result.eigenValues);\n//   result.eigenValues *= fscale;\n\n// #elif USEEIGEN\n\n  // Use the Eigen library to determine the eigen values/vectors.\n  {\n    Eigen::Matrix3d B;\n    B << \n      A.xx(), A.xy(), A.xz(),\n      A.yx(), A.yy(), A.yz(),\n      A.zx(), A.zy(), A.zz();\n    const Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver(B);\n    const Eigen::Vector3d& Bvals = eigensolver.eigenvalues();\n    const Eigen::Matrix3d& Bvecs = eigensolver.eigenvectors();\n    result.eigenValues = Vector(Bvals(0), Bvals(1), Bvals(2)) * fscale;\n    const double x1 = 1.0/std::sqrt(Bvecs(0,0)*Bvecs(0,0) + Bvecs(1,0)*Bvecs(1,0) + Bvecs(2,0)*Bvecs(2,0));\n    const double x2 = 1.0/std::sqrt(Bvecs(0,1)*Bvecs(0,1) + Bvecs(1,1)*Bvecs(1,1) + Bvecs(2,1)*Bvecs(2,1));\n    const double x3 = 1.0/std::sqrt(Bvecs(0,2)*Bvecs(0,2) + Bvecs(1,2)*Bvecs(1,2) + Bvecs(2,2)*Bvecs(2,2));\n    result.eigenVectors = Tensor(Bvecs(0,0)*x1, Bvecs(0,1)*x2, Bvecs(0,2)*x3,\n                                 Bvecs(1,0)*x1, Bvecs(1,1)*x2, Bvecs(1,2)*x3,\n                                 Bvecs(2,0)*x1, Bvecs(2,1)*x2, Bvecs(2,2)*x3);\n  }\n\n// #else\n\n//   // Compute the scaled eigen-values, and sort them.\n//   Vector lambdaVec = A.eigenValues();\n//   sort(lambdaVec.begin(), lambdaVec.end());\n//   CHECK(lambdaVec.x() <= lambdaVec.y() and\n//         lambdaVec.y() <= lambdaVec.z());\n\n//   // Assign the true eigen-values in the result.\n//   result.eigenValues = fscale*lambdaVec;\n//   result.eigenVectors = SymTensor::one;\n\n//   // If any of the eigen-values result in a tensor that is not positive-rank \n//   // (all zero elements), we assume the eigen-values are equal and punt\n//   // with the identity tensor for the eigen-vectors.\n//   // We simultaneously compute the row containing the maximum absolute value \n//   // element for each eigen-value.\n//   bool punt = false;\n//   double maxEVelement = -1.0;\n//   Vector maxEVrow;\n//   int iFirst = -1;\n//   for (int ivalue = 0; ivalue != 3; ++ivalue) {\n//     const SymTensor M = A - lambdaVec(ivalue)*SymTensor::one;\n//     if (M.maxAbsElement() < degenerate) punt = true;\n//     for (int irow = 0; irow != 3; ++irow) {\n//       const Vector Mvec = M.getRow(irow);\n//       const double thpt = Mvec.maxAbsElement();\n//       if (thpt > maxEVelement) {\n//         maxEVelement = thpt;\n//         maxEVrow = Mvec;\n//         iFirst = ivalue;\n//       }\n//     }\n//   }\n\n//   // If we found an all zero M (= A - lambda*I) matrix, we punt and accept the identity\n//   // tensor as our eigen-vectors.  Otherwise, continue the compuation.\n//   if (!punt) {\n//     CHECK(iFirst >= 0 and iFirst < 3);\n\n//     // Select the ordering we'll go through the eigen-values in, starting\n//     // with the row with the largest absolute value element.\n//     const int iSecond = (iFirst + 1) % 3;\n//     const int iThird = (iSecond + 1) % 3;\n//     CHECK(iFirst + iSecond + iThird == 3);\n\n//     // We need two orthogonal unit vectors in the plane perpendicular to\n//     // the maximum row selected previously.  We can do this by finding the\n//     // rotational transformation wherein x' axis is aligned with this row, and \n//     // taking our two vectors as the other two rows of this transform.\n//     const Vector R = maxEVrow.unitVector();\n//     const Tensor Tr = rotationMatrix(R);\n//     const Vector U0 = Tr.getRow(1);\n//     const Vector U1 = Tr.getRow(2);\n    \n//     // Now we can compute the eigen-vector corresponding the first eigen-value\n//     // selected previously.\n//     const Vector V0 = buildUniqueEigenVector(A, \n//                                              lambdaVec(iFirst),\n//                                              U0,\n//                                              U1);\n//     result.eigenVectors.setColumn(iFirst, V0);\n\n//     // Now we know the remaining eigen-vectors are in the plane perpendicular to\n//     // V0.  We know R is in that plane, and so is R x V0.  With that knowledge\n//     // we can basically repeat the same procedure for the next eigen-vector.\n//     Vector S = R.cross(V0);\n//     CHECK(fuzzyEqual(S.magnitude2(), 1.0, tolerance));\n//     const Vector V1 = buildUniqueEigenVector(A,\n//                                              lambdaVec(iSecond),\n//                                              R,\n//                                              S);\n//     result.eigenVectors.setColumn(iSecond, V1);\n    \n//     // The last eigen-vector is orthogonal to the first two, so we can find it\n//     // simply by taking the cross-product of the previous eigen-vectors.\n//     const Vector V2 = V0.cross(V1);\n//     CHECK(fuzzyEqual(V2.magnitude2(), 1.0, tolerance));\n//     CHECK(fuzzyEqual(((A - lambdaVec(iThird)*SymTensor::one)*V2).maxAbsElement(), 0.0, tolerance));\n//     result.eigenVectors.setColumn(iThird, V2);\n//   }\n\n// #endif\n\n  BEGIN_CONTRACT_SCOPE\n  // Check the result.\n  const double lambda1 = result.eigenValues.x();\n  const double lambda2 = result.eigenValues.y();\n  const double lambda3 = result.eigenValues.z();\n  const Vector v1 = result.eigenVectors.getColumn(0);\n  const Vector v2 = result.eigenVectors.getColumn(1);\n  const Vector v3 = result.eigenVectors.getColumn(2);\n  ENSURE2(fuzzyEqual(v1.dot(v2), 0.0, tolerance) and \n          fuzzyEqual(v1.dot(v3), 0.0, tolerance) and \n          fuzzyEqual(v2.dot(v3), 0.0, tolerance),\n          v1 << \" \" << v2 << \" \" << v3 << \" : \" << *this);\n  ENSURE2(fuzzyEqual(v1.magnitude2(), 1.0, tolerance) and\n          fuzzyEqual(v2.magnitude2(), 1.0, tolerance) and\n          fuzzyEqual(v3.magnitude2(), 1.0, tolerance),\n          v1 << \" \" << v2 << \" \" << v3);\n  const double tol = tolerance*max(1.0, this->maxAbsElement());\n  ENSURE2(fuzzyEqual((SymTensor(xx() - lambda1, xy(), xz(),\n                                yx(), yy() - lambda1, yz(),\n                                zx(), zy(), zz() - lambda1)*v1).maxAbsElement(), 0.0, tol),\n          *this << \" \" << A << \" \" << lambda1 << \" \" << v1 << \" \" << tol << \" \"\n          << SymTensor(xx() - lambda1, xy(), xz(),\n                       yx(), yy() - lambda1, yz(),\n                       zx(), zy(), zz() - lambda1)*v1);\n  ENSURE(fuzzyEqual((SymTensor(xx() - lambda2, xy(), xz(),\n                               yx(), yy() - lambda2, yz(),\n                               zx(), zy(), zz() - lambda2)*v2).maxAbsElement(), 0.0, tol));\n  ENSURE(fuzzyEqual((SymTensor(xx() - lambda3, xy(), xz(),\n                               yx(), yy() - lambda3, yz(),\n                               zx(), zy(), zz() - lambda3)*v3).maxAbsElement(), 0.0, tol));\n  ENSURE(fuzzyEqual(abs(result.eigenVectors.Determinant()), 1.0, tolerance));\n  END_CONTRACT_SCOPE\n\n  return result;\n}\n\n//------------------------------------------------------------------------------\n// Explicit instantiation.\n//------------------------------------------------------------------------------\ntemplate class GeomSymmetricTensor<1>;\ntemplate class GeomSymmetricTensor<2>;\ntemplate class GeomSymmetricTensor<3>;\n\n//------------------------------------------------------------------------------\n// Set the static variables.\n//------------------------------------------------------------------------------\ntemplate<> const unsigned GeomSymmetricTensor<1>::nDimensions = 1;\ntemplate<> const unsigned GeomSymmetricTensor<1>::numElements = 1;\ntemplate<> const GeomSymmetricTensor<1> GeomSymmetricTensor<1>::zero = GeomSymmetricTensor<1>(0.0);\ntemplate<> const GeomSymmetricTensor<1> GeomSymmetricTensor<1>::one = GeomSymmetricTensor<1>(1.0);\n\ntemplate<> const unsigned GeomSymmetricTensor<2>::nDimensions = 2;\ntemplate<> const unsigned GeomSymmetricTensor<2>::numElements = 3;\ntemplate<> const GeomSymmetricTensor<2> GeomSymmetricTensor<2>::zero = GeomSymmetricTensor<2>(0.0, 0.0,\n                                                                                              0.0, 0.0);\ntemplate<> const GeomSymmetricTensor<2> GeomSymmetricTensor<2>::one = GeomSymmetricTensor<2>(1.0, 0.0,\n                                                                                             0.0, 1.0);\n\ntemplate<> const unsigned GeomSymmetricTensor<3>::nDimensions = 3;\ntemplate<> const unsigned GeomSymmetricTensor<3>::numElements = 6;\ntemplate<> const GeomSymmetricTensor<3> GeomSymmetricTensor<3>::zero = GeomSymmetricTensor<3>(0.0, 0.0, 0.0,\n                                                                                              0.0, 0.0, 0.0,\n                                                                                              0.0, 0.0, 0.0);\ntemplate<> const GeomSymmetricTensor<3> GeomSymmetricTensor<3>::one = GeomSymmetricTensor<3>(1.0, 0.0, 0.0,\n                                                                                             0.0, 1.0, 0.0,\n                                                                                             0.0, 0.0, 1.0);\n\ntemplate<> const double GeomSymmetricTensor<1>::onethird = 1.0/3.0;\ntemplate<> const double GeomSymmetricTensor<2>::onethird = 1.0/3.0;\ntemplate<> const double GeomSymmetricTensor<3>::onethird = 1.0/3.0;\n\ntemplate<> const double GeomSymmetricTensor<1>::sqrt3 = std::sqrt(3.0);\ntemplate<> const double GeomSymmetricTensor<2>::sqrt3 = std::sqrt(3.0);\ntemplate<> const double GeomSymmetricTensor<3>::sqrt3 = std::sqrt(3.0);\n\n}\n\n", "meta": {"hexsha": "a80632f5ac7d3467c925b4a224579ba1eb1a8918", "size": 11494, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Geometry/GeomSymmetricTensor_default.cc", "max_stars_repo_name": "markguozhiming/spheral", "max_stars_repo_head_hexsha": "bbb982102e61edb8a1d00cf780bfa571835e1b61", "max_stars_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T01:56:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-21T01:56:55.000Z", "max_issues_repo_path": "src/Geometry/GeomSymmetricTensor_default.cc", "max_issues_repo_name": "markguozhiming/spheral", "max_issues_repo_head_hexsha": "bbb982102e61edb8a1d00cf780bfa571835e1b61", "max_issues_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "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/Geometry/GeomSymmetricTensor_default.cc", "max_forks_repo_name": "markguozhiming/spheral", "max_forks_repo_head_hexsha": "bbb982102e61edb8a1d00cf780bfa571835e1b61", "max_forks_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8984375, "max_line_length": 109, "alphanum_fraction": 0.5423699321, "num_tokens": 3082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5163480037384419}}
{"text": "// Copyright Oleg Maximenko 2014.\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://github.com/svgpp/svgpp for library home page.\n\n#pragma once\n\n#include <svgpp/definitions.hpp>\n#include <boost/mpl/joint_view.hpp>\n#include <boost/mpl/set.hpp>\n#include <boost/ratio/ratio.hpp>\n\nnamespace svgpp { namespace traits\n{\n\ntypedef boost::mpl::set5<\n  tag::length_units::in,\n  tag::length_units::cm,\n  tag::length_units::mm,\n  tag::length_units::pt,\n  tag::length_units::pc\n> absolute_length_units;\n\ntypedef boost::mpl::joint_view<\n  absolute_length_units,\n  boost::mpl::set5<\n    tag::length_units::em,\n    tag::length_units::ex,\n    tag::length_units::px,\n    tag::length_units::percent,\n    tag::length_units::none\n> > all_length_units;\n\ntemplate<class Src, class Dst>\nstruct absolute_length_conversion_coefficient\n{ \n  typedef typename boost::ratio_divide<\n    typename absolute_length_conversion_coefficient<tag::length_units::in, Dst>::ratio,\n    typename absolute_length_conversion_coefficient<tag::length_units::in, Src>::ratio\n  > ratio; \n};\n\ntemplate<class Src>\nstruct absolute_length_conversion_coefficient<Src, Src>\n{ typedef boost::ratio<1> ratio; };\n\ntemplate<>\nstruct absolute_length_conversion_coefficient<tag::length_units::in, tag::length_units::cm>\n{ typedef boost::ratio<254, 100> ratio; };\n\ntemplate<>\nstruct absolute_length_conversion_coefficient<tag::length_units::in, tag::length_units::mm>\n{ typedef boost::ratio<254, 10> ratio; };\n\ntemplate<>\nstruct absolute_length_conversion_coefficient<tag::length_units::in, tag::length_units::pt>\n{ typedef boost::ratio<72> ratio; };\n\ntemplate<>\nstruct absolute_length_conversion_coefficient<tag::length_units::in, tag::length_units::pc>\n{ typedef boost::ratio<6> ratio; };\n\n}}", "meta": {"hexsha": "00c5782429ee5ad0de892314b37ca5c435459bd7", "size": 1855, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/svgpp/traits/length_units.hpp", "max_stars_repo_name": "RichardCory/svgpp", "max_stars_repo_head_hexsha": "801e0142c61c88cf2898da157fb96dc04af1b8b0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 428.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:25:47.000Z", "max_issues_repo_path": "include/svgpp/traits/length_units.hpp", "max_issues_repo_name": "andrew2015/svgpp", "max_issues_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T14:32:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T16:55:11.000Z", "max_forks_repo_path": "include/svgpp/traits/length_units.hpp", "max_forks_repo_name": "andrew2015/svgpp", "max_forks_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2015-05-19T04:56:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:42:50.000Z", "avg_line_length": 28.5384615385, "max_line_length": 91, "alphanum_fraction": 0.7547169811, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5163479812579196}}
{"text": "/**\n * \\file dcs/math/random/linear_congruential.hpp\n *\n * \\brief Linear Congruential Random Number Engine.\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_RANDOM_LINEAR_CONGRUENTIAL_HPP\n#define DCS_MATH_RANDOM_LINEAR_CONGRUENTIAL_HPP\n\n\n#include <dcs/detail/config/boost.hpp>\n\n#if !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(101500) // 1.15\n#\terror \"Required Boost libraries version >= 1.15.\"\n#endif\n\n\n#include <boost/random/linear_congruential.hpp>\n#include <cstddef>\n#include <dcs/math/random/base_generator.hpp>\n#include <stdint.h>\n\n\nnamespace dcs { namespace math { namespace random {\n\n//using ::std::size_t;\n\n/*\ntemplate <typename IntT, IntT a, IntT c, IntT m>\nclass linear_congruential\n{\n\tpublic: typedef IntT result_type;\n\tpublic: static const result_type min_value = (c == 0 ? 1 : 0);\n\tpublic: static const result_type max_value = m-1;\n\tpublic: static const result_type multiplier = a;\n\tpublic: static const result_type increment = c;\n\tpublic: static const result_type modulus = m;\n\n\tpublic: explicit linear_congruential(IntT x0=1)\n\t{\n\t\tseed(x0);\n\t}\n\n\tpublic: void seed(IntT x0=1)\n\t{\n\t\tx_ = ((modulus != 0) ? (x0 % modulus) : x0);\n\n\t\t// handle negative seeds\n\t\tif (x_ < 0)\n\t\t{\n\t\t\tx_ += modulus;\n\t\t}\n\t\t// adjust to the correct range\n\t\tif (increment == 0 && x_ == 0)\n\t\t{\n\t\t\tx_ = 1;\n\t\t}\n\n\t\t// post-conditions\n\t\tDCS_ASSERT(\n\t\t\tx_ >= min_value,\n\t\t\tthrow std::domain_error(\"Seed less than min value\")\n\t\t);\n\t\tDCS_ASSERT(\n\t\t\tx_ <= max_value,\n\t\t\tthrow std::domain_error(\"Seed greater than max value\")\n\t\t);\n\t}\n\n\tpublic: result_type operator()()\n\t{\n\t\treturn next();\n\t}\n\n\n\tpublic: friend bool operator==(linear_congruential const& l1, linear_congruential const& l2)\n\t{\n\t\treturn l1.x_ == l2.x_;\n\t}\n\n\n\tpublic: friend bool operator!=(linear_congruential const& l1, linear_congruential const& l2)\n\t{\n\t\treturn !(l1 == l2);\n\t}\n\n\n\t// Perform: (a*x+c) mod m\n\tprivate: IntT next()\n\t{\n\t\tIntT max_d_a = std::numeric_limits<IntT>::max()/multiplier;\n\n\t\tif(modulus <= (max_d_a - increment/multiplier))   // i.e. a*m+c <= max\n\t\t{\n\t\t\tx_= (multiplier * x_ + increment) % modulus;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// increment and multiplier are big\n\n\t\t\t// Perform the product\n\t\t\tif (multiplier != 1)\n\t\t\t{\n\t\t\t\tif (modulus <= max_d_a) // i.e. a*m <= max\n\t\t\t\t{\n\t\t\t\t\t// small product\n\t\t\t\t\tx_ = (multiplier * x_) % modulus;\n\t\t\t\t}\n\t\t\t\telse if (std::numeric_limits<IntT>::is_signed && (modulus % multiplier) < (modulus / multiplier))\n\t\t\t\t{\n\t\t\t\t\t// Use the Schrage's Algorithm:\n\t\t\t\t\t//   an algorithm for multiplying two 32-bit integers modulo\n\t\t\t\t\t//   a 32-bit constant without using any intermediates\n\t\t\t\t\t//   larger than 32 bits. \n\n\t\t\t\t\tconst IntT q = modulus / multiplier;\n\t\t\t\t\tconst IntT r = modulus % multiplier;\n\n\t\t\t\t\tassert(r < q);        // check that overflow cannot happen\n\n\t\t\t\t\tx_ = multiplier*(x_%q) - r*(x_/q);\n\t\t\t\t\twhile (x_ <= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tx_ += modulus;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n//\t\t\t\t\tDCS_ASSERT(\"multiplier is too large\");\n\t\t\t\t\tx_ = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Perform the sum\n\t\t\tif (increment != 0)\n\t\t\t{\n\t\t\t\tif (increment <= (std::numeric_limits<IntT>::max()-modulus)) // i.e. m+x < max\n\t\t\t\t{\n\t\t\t\t\t// small sum\n\t\t\t\t\tx_ += increment;\n\t\t\t\t\tif (x_ >= modulus)\n\t\t\t\t\t{\n\t\t\t\t\t\tx_ -= modulus;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (std::numeric_limits<IntT>::is_signed)\n\t\t\t\t{\n\t\t\t\t\tIntT m_sub_c(modulus-increment);\n\n\t\t\t\t\tif (x_ < m_sub_c)\n\t\t\t\t\t{\n\t\t\t\t\t\tx_ += increment;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tx_ -= m_sub_c;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n//\t\t\t\t\tDCS_ASSERT(\"increment is too large\u00b0);\n\t\t\t\t\tx_ = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn x_;\n\t}\n\n\n\tprivate: IntT x_;\n};\n*/\n\n\n/**\n * \\brief Linear Congruential Random Number Engine.\n *\n * \\tparam UIntT The type of randomly generated numbers.\n * \\tparam a The multiplier.\n * \\tparam c The increment.\n * \\tparam m The modulus.\n *\n * The Linear Congruential random number generator has the following form:\n * \\f[\n *   X_{i+1} = a X_{i} + c \\quad (\\operatorname{mod} m)\n * \\f]\n * where:\n * - \\f$a\\f$ is the \\e multiplier.\n * - \\f$c\\f$ is the \\e increment.\n * - \\f$m\\f$ is the \\e modulus.\n * .\n * This class implements the \\c RandomNumberEngine concept.\n *\n * \\see \"Numerical Recipes in C: The Art of Scientific Computing\" (William H. Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling).\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate <typename UIntT, UIntT a, UIntT c, UIntT m>\nclass linear_congruential: public base_generator<UIntT>\n{\n\tprivate: typedef base_generator<UIntT> base_type;\n\tpublic: typedef UIntT result_type;\n\tprivate: typedef ::boost::random::linear_congruential<UIntT,a,c,m,0> impl_type;\n\tpublic: typedef typename base_type::ulonglong_type ulonglong_type;\n//\tpublic: typedef long long ulonglong_type;\n\n\n\tpublic: static const result_type multiplier = a;\n\tpublic: static const result_type increment = c;\n\tpublic: static const result_type modulus = m;\n\tpublic: static const result_type default_seed = impl_type::default_seed;\n\n\n\tpublic: linear_congruential()\n\t\t: impl_()\n\t{\n\t\t// empty\n\t}\n\n\n\tpublic: explicit linear_congruential(result_type s)\n\t\t: impl_(s)\n\t{\n\t\t// empty\n\t}\n\n\n//\tpublic: template <typename ItT>\n//\t\tlinear_congruential(ItT& first, ItT& last)\n//\t\t: impl_(first,last)\n//\t{\n//\t\t// empty\n//\t}\n\n\n//\tpublic: template <typename ItT>\n//\t\tvoid seed(ItT& first, ItT& last)\n//\t{\n//\t\timpl_.seed(first, last);\n//\t}\n\n\n\tpublic: static result_type min()\n\t{\n\t\treturn (increment == 0u ? 1u : 0u);\n\t}\n\n\n\tpublic: static result_type max()\n\t{\n\t\treturn (modulus - 1);\n\t}\n\n\n\tprivate: result_type do_min() const\n\t{\n\t\treturn impl_.min();\n\t}\n\n\n\tprivate: result_type do_max() const\n\t{\n\t\treturn impl_.max();\n\t}\n\n\n\tprivate: void do_seed()\n\t{\n\t\timpl_.seed();\n\t}\n\n\n\tprivate: void do_seed(result_type s)\n\t{\n\t\timpl_.seed(s);\n\t}\n\n\n\tprivate: result_type do_generate()\n\t{\n\t\treturn impl_();\n\t}\n\n\n\t//FIXME: actually cannot use impl_.discard since it is defined only when\n\t//       BOOST_NO_LONG_LONG is undefined.\n\tprivate: void do_discard(ulonglong_type z)\n\t{\n\t\tfor ( ; z != 0; --z)\n\t\t{\n\t\t\tthis->operator()();\n\t\t}\n//\t\timpl_.discard(z);\n\t}\n\n\n\tpublic: friend bool operator==(linear_congruential const& l1, linear_congruential const& l2)\n\t{\n\t\treturn l1.impl_ == l2.impl_;\n\t}\n\n\n\tpublic: friend bool operator!=(linear_congruential const& l1, linear_congruential const& l2)\n\t{\n\t\treturn !(l1 == l2);\n\t}\n\n\n\tprivate: impl_type impl_;\n};\n\n// Some standard LCG (see http://random.mat.sbg.ac.at/~charly/server/node3.html)\n\ntypedef linear_congruential<int32_t, 16807, 0, 2147483647> minstd_rand0;\ntypedef linear_congruential<int32_t, 48271, 0, 2147483647> minstd_rand1;\ntypedef linear_congruential<int32_t, 69621, 0, 2147483647> minstd_rand2;\n//FIXME: the declaration below requires a true 64 bit integer in order to\n// store the two integral constants.\n// For the moment use the boost::rand48 class (which emulates drand48\n// without requiring true 64bit support) until we find a way the underlying\n// architecture type.\n#if true\ntypedef linear_congruential<uint64_t, 25214903917, 11, 281474976710656> rand48;\n#else\nclass rand48\n{\n\tpublic: typedef ::boost::rand48::result_type result_type;\n\tpublic: static const result_type default_seed = 1u;\n\n\n\tpublic: rand48()\n\t\t: impl_(default_seed)\n\t{\n\t\t// empty\n\t}\n\n\n\tpublic: explicit rand48(result_type s)\n\t\t: impl_(s)\n\t{\n\t\t// empty\n\t}\n\n\n\tpublic: template <typename ItT>\n\t\trand48(ItT& first, ItT& last)\n\t\t: impl_(first,last)\n\t{\n\t\t// empty\n\t}\n\n\n\tpublic: void seed(result_type s=default_seed)\n\t{\n\t\timpl_.seed(s);\n\t}\n\n\n\tpublic: template <typename ItT>\n\t\tvoid seed(ItT& first, ItT& last)\n\t{\n\t\timpl_.seed(first, last);\n\t}\n\n\n\tpublic: static result_type min()\n\t{\n\t\treturn 0;\n\t}\n\n\n\tpublic: static result_type max()\n\t{\n\t\treturn ::std::numeric_limits<int32_t>::max();\n\t}\n\n\n\tpublic: result_type operator()()\n\t{\n\t\treturn impl_();\n\t}\n\n\n\tpublic: void discard(size_t z)\n\t{\n\t\tfor ( ; z != 0; --z)\n\t\t{\n\t\t\toperator()();\n\t\t}\n\t}\n\n\n\tpublic: friend bool operator==(rand48 const& lhs, rand48 const& rhs)\n\t{\n\t\treturn lhs.impl_ == rhs.impl_;\n\t}\n\n\n\tpublic: friend bool operator!=(rand48 const& lhs, rand48 const& rhs)\n\t{\n\t\treturn !(lhs == rhs);\n\t}\n\n\n\tprivate: ::boost::rand48 impl_;\n};\n#endif // false\n\n}}} // Namespace dcs::math::random\n\n\n#endif // DCS_MATH_RANDOM_LINEAR_CONGRUENTIAL_HPP\n", "meta": {"hexsha": "90c7ce2496566f902dbd2cd5ed39fa0a34075e39", "size": 8764, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/random/linear_congruential.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/random/linear_congruential.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/random/linear_congruential.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": 20.287037037, "max_line_length": 146, "alphanum_fraction": 0.6597444089, "num_tokens": 2612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5163000401021192}}
{"text": "#pragma once\n\n#include <stdlib.h>\n#include <math.h>\n\n#include \"vec.h\"\n#include \"gnilk/engine/core/Core.hpp\"\n#include \"gnilk/engine/core/Edge.hpp\"\n#include \"gnilk/engine/core/Triangle.hpp\"\n#include \"gnilk/engine/core/FaceGroup.hpp\"\n\n#include <boost/unordered/unordered_map.hpp>\n\n#include <vector>\n\nnamespace gnilk\n{\n\tnamespace engine\n\t{\n\t\tusing namespace gnilk::engine::core;\n\n\t\tclass FaceHelper\n\t\t{\n\t\tpublic:\n\t\t\t//\n\t\t\t// calculates vertex normals per group basis\n\t\t\t// vertex normals are stored directly in to the triangles\n\t\t\t// I did not want unsynchronized buffer sizes nor buffer dependencies on group\n\t\t\t// This is not optimal for rendering - that has to be solved when computing render buffers\n\t\t\t//\n\t\t\tstatic void CalculateVertexNormals(int vertices, std::vector<int> &faces, std::vector<Triangle *> &triangles) {\n\t\t\t\tstd::vector<Normal> normals;\n\t\t\t\tnormals.reserve(vertices);\t// need intermediate storage\n\t\t\t\t// need to initialize array\n\t\t\t\tfor(int i=0;i<vertices;i++) {\n\t\t\t\t\tvIni(normals[i].data,0,0,0);\n\t\t\t\t}\n\t\t\t\t// add up normals per vertex - note: normals should already be normalized!\n\t\t\t\tfor(int i=0;i<faces.size();i++) {\n\t\t\t\t\tint idxTri = faces[i];\n\t\t\t\t\tTriangle *tri = triangles[idxTri];\n\t\t\t\t\tfor(int j=0;j<3;j++) {\n\t\t\t\t\t\tvAdd(normals[tri->v[j]].data, normals[tri->v[j]].data, tri->normal.data);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// normalize and assign\n\t\t\t\tfor(int i=0;i<faces.size();i++) {\n\t\t\t\t\tTriangle *tri = triangles[faces[i]];\n\t\t\t\t\tfor(int j=0;j<3;j++) {\n\t\t\t\t\t\tvNorm(tri->vn[j].data,normals[tri->v[j]].data);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstatic void CalculateVertexNormals(int vertices, std::vector<FaceGroup*> &groups, std::vector<Triangle *> &triangles)\n\t\t\t{\n\t\t\t\tfor(int i=0;i<groups.size();i++)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"CVN, G: %d, T: %d\\n\",i, groups[i]->triangles.size());\n\t\t\t\t\tCalculateVertexNormals(vertices, groups[i]->triangles, triangles);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstatic void CalculateFaceNormal(Normal *faceNormal, std::vector<Vertex3D> &coords, int v1, int v2, int v3) {\n\t\t\t\tfloat *pV1 = coords[v1].data;\n\t\t\t\tfloat *pV2 = coords[v2].data;\n\t\t\t\tfloat *pV3 = coords[v3].data;\n\n\t\t\t\tfloat vE1[3];\n\t\t\t\tfloat vE2[3];\n\t\t\t\tvSub(vE1, pV3, pV1);\n\t\t\t\tvSub(vE2, pV2, pV1);\n\t\t\t\tvCross(faceNormal->data, vE1, vE2);\n\t\t\t\tvNorm(faceNormal->data,faceNormal->data);\n\t\t\t}\n\n\t\t\t// Calculate normals for a list of faces and assign to face\n\t\t\tstatic void CalculateFaceNormals(std::vector<Triangle *> &triangles, std::vector<Vertex3D> &coords) {\n\t\t\t\tfor(int i=0;i<triangles.size();i++) {\n\t\t\t\t\tTriangle *tri = triangles[i];\n\t\t\t\t\tif (!tri->HasNormal()) {\n\t\t\t\t\t\tCalculateFaceNormal(tri->normal.data, coords, tri->v[0], tri->v[1], tri->v[2]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Calculates a single face normal\n\t\t\tstatic void CalculateFaceNormal(float *normal, std::vector<Vertex3D> &coords, int v1, int v2, int v3) {\n\t\t\t\tfloat *pV1 = coords[v1].data;\n\t\t\t\tfloat *pV2 = coords[v2].data;\n\t\t\t\tfloat *pV3 = coords[v3].data;\n\n\t\t\t\tfloat vE1[3];\n\t\t\t\tfloat vE2[3];\n\t\t\t\tvSub(vE1, pV3, pV1);\n\t\t\t\tvSub(vE2, pV2, pV1);\n\t\t\t\tvCross(normal, vE2, vE1);\n\t\t\t\tvNorm(normal, normal);\n\t\t\t}\n\n\t\t\t// calculate list of normals for each face\n\t\t\tstatic void CalculateFaceNormals(std::vector<Normal> &normals, std::vector<Triangle *> &triangles, std::vector<Vertex3D> &coords) {\n\t\t\t\tnormals.reserve(triangles.size());\n\t\t\t\tfor(int i=0;i<triangles.size();i++) {\n\t\t\t\t\tCalculateFaceNormal(normals[i].data, coords, triangles[i]->v[0], triangles[i]->v[1], triangles[i]->v[2]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Gets or adds (a new) group for face depending on the deviation between face normal and group normal\n\t\t\t// Not used..\n\t\t\tstatic FaceGroup *GetOrAddGroup(std::vector<FaceGroup *> &groups, Normal &normal, float threshold) {\n\t\t\t\tFaceGroup *group = NULL;\n\t\t\t\tfloat lastFac = threshold;\n\n\t\t\t\t// Find group (if any) which fulfills the the normal threshold\n\t\t\t\tfor(size_t i=0;i<groups.size();i++) {\n\t\t\t\t\tfloat fac = 1.0 - vDot(normal.data, groups[i]->baseNormal.data);\n\t\t\t\t\tif ((fac > 0) && (fac < threshold)) {\n\t\t\t\t\t\tgroup = groups[i];\n\t\t\t\t\t\tlastFac = fac;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (group == NULL)\n\t\t\t\t{\n\t\t\t\t\tgroup = new FaceGroup();\n\t\t\t\t\tvDup(group->baseNormal.data, normal.data);\n\t\t\t\t\tgroups.push_back(group);\n\t\t\t\t}\n\t\t\t\treturn group;\n\t\t\t}\n\n\t\t\t// Recursive, assigns faces to groups - based on edges and if two faces have a similar normal they are allowed in the same group\n\t\t\tstatic void DoCalculateFaceGroups(FaceGroup *pGroup,\n\t\t\t\t\tint triangle,\n\t\t\t\t\tfloat threshold,\n\t\t\t\t\tstd::vector<bool> &visited,\n\t\t\t\t\tstd::vector<Edge *> &edges,\n\t\t\t\t\tstd::vector<Triangle *> &triangles,\n\t\t\t\t\tstd::vector<Normal> &faceNormals,\n\t\t\t\t\tint depth)\n\t\t\t{\n\t\t\t\tif (visited[triangle])\n\t\t\t\t{\n\t\t\t\t\t//printf(\"%d:%d -> .\\n\",depth,triangle);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tpGroup->triangles.push_back(triangle);\n\t\t\t\tvisited[triangle] = true;\n\n\t\t\t\tTriangle *pTri = triangles[triangle];\n\t\t\t\tfor(int i=0;i<3;i++)\n\t\t\t\t{\n\t\t\t\t\tEdge *edge = triangles[triangle]->edges[i];\n\t\t\t\t\tif (edge == NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tprintf(\"NULL edge %d for triangle %d\\n\",i, triangle);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tint tNext = -1;\n\t\t\t\t\tif ((edge->f1 != triangle) && (edge->f1 != -1)) tNext = edge->f1;\n\t\t\t\t\telse if ((edge->f2 != triangle) && (edge->f2 != -1)) tNext = edge->f2;\n\n\t\t\t\t\tif (tNext >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tTriangle *pTriNext = triangles[tNext];\n\t\t\t\t\t\tfloat faceDiff = 1.0 - vDot(pTri->normal.data, pTriNext->normal.data);\n\t\t\t\t\t\t//float faceDiff = 1.0 - vDot(faceNormals[triangle].data, faceNormals[tNext].data);\n\t\t\t\t\t\tfaceDiff = fabs(faceDiff);\n\t\t\t\t\t\tif ((faceDiff >= 0) && (faceDiff <= threshold))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//printf(\"%d:%d -> %d - %f\\n\",depth,triangle, tNext, faceDiff);\n\t\t\t\t\t\t\tDoCalculateFaceGroups(pGroup, tNext, threshold, visited, edges, triangles, faceNormals,depth+1);\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// rejected because of threshold\n\t\t\t\t\t\t\t//printf(\"%d, r: %f\\n\",faceDiff);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} // Foreach edge\n\t\t\t\t//printf(\"%d:%d -> x\\n\",depth,triangle);\n\t\t\t}\n\n\t\t\t// Automatic group of faces depending on\n\t\t\tstatic void CalculateFaceGroups(std::vector<FaceGroup *> &groups, std::vector<Edge *> &edges, std::vector<Triangle *> &triangles, std::vector<Normal> &faceNormals)\n\t\t\t{\n\t\t\t\tstd::vector<bool> visited;\n\t\t\t\tvisited.reserve(triangles.size());\n\t\t\t\tfor(size_t i=0;i<triangles.size();i++)\n\t\t\t\t{\n\t\t\t\t\tvisited.push_back(false);\n\t\t\t\t}\n\t\t\t\tfor(size_t i=0;i<triangles.size();i++)\n\t\t\t\t{\n\t\t\t\t\tif (!visited[i])\n\t\t\t\t\t{\n\t\t\t\t\t\tFaceGroup *pGroup = new FaceGroup();\n\t\t\t\t\t\tDoCalculateFaceGroups(pGroup, i, 0.5, visited, edges, triangles, faceNormals,0);\n\t\t\t\t\t\tprintf(\"Group %d, triangles: %d\\n\", groups.size(), pGroup->triangles.size());\n\t\t\t\t\t\tgroups.push_back(pGroup);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor(size_t i=0;i<groups.size();i++)\n\t\t\t\t{\n\t\t\t\t\tFaceGroup *group = groups[i];\n\t\t\t\t\tvMul(group->normal.data, group->normal.data, 1.0 / (double)group->triangles.size());\n\t\t\t\t}\n\t\t\t\tprintf(\"Groups: %d\\n\",groups.size());\n\t\t\t}\n\n\t\t\t// Calculate edges\n\t\t\tstatic void CalculateEdges(std::vector<Edge *> &edges, std::vector<Triangle *> &triangles, const std::vector<Vertex3D> &vertices)\n\t\t\t{\n\t\t\t\tboost::unordered::unordered_map<int, Edge *> edgemap;\n\t\t\t\tfor(size_t i=0;i<triangles.size();i++)\n\t\t\t\t{\n\t\t\t\t\ttriangles[i]->Reset();\n\t\t\t\t\tGetOrAddEdgeMap(edgemap, triangles, vertices, i, 0, 1);\n\t\t\t\t\tGetOrAddEdgeMap(edgemap, triangles, vertices, i, 1, 2);\n\t\t\t\t\tGetOrAddEdgeMap(edgemap, triangles, vertices, i, 2, 0);\n\t\t\t\t}\n\t\t\t\t// I guess there is a better way to generate a vector instead of this...\n\t\t\t\tint count = 0;\n\t\t\t\tfor (boost::unordered::unordered_map<int, Edge *>::iterator it = edgemap.begin(); it != edgemap.end(); ++it )\n\t\t\t\t{\n\t\t\t\t\tEdge *edge = it->second;\n\t\t\t\t\tif (edge->f1 >= 0) triangles[edge->f1]->AddEdge(edge);\n\t\t\t\t\tif (edge->f2 >= 0) triangles[edge->f2]->AddEdge(edge);\n\t\t\t\t\tedges.push_back(it->second);\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t} // CalculateEdges\n\n\t\t\t// Convert faces to triangles - quads are split\n\t\t\tstatic void FacesToTriangles(\n\t\t\t\t\tstd::vector<Triangle *> &triangles,\n\t\t\t\t\tstd::vector<Face *> &faces) {\n\n\t\t\t\tfor(size_t i=0;i<faces.size();i++) {\n\t\t\t\t\tTriangle *tri = new Triangle();\n\t\t\t\t\ttri->faceData = faces[i]->faceData;\n\t\t\t\t\tfor(int j=0;j<3;j++) {\n\t\t\t\t\t\ttri->v[j] = faces[i]->v[j];\n\t\t\t\t\t\t//tri->vn[j] = faces[i]->vn[j];\n\t\t\t\t\t\ttri->uv[j] = faces[i]->uv[j];\n\t\t\t\t\t}\n\t\t\t\t\ttriangles.push_back(tri);\n\t\t\t\t\tif (faces[i]->faceType == kFaceType_Quad) {\n\t\t\t\t\t\ttri = new Triangle();\n\t\t\t\t\t\ttri->faceData = faces[i]->faceData;\n\t\t\t\t\t\tfor(int j=0;j<3;j++) {\n\t\t\t\t\t\t\tint idx = ((j+2)>3) ? 0 : j+2;\n\t\t\t\t\t\t\ttri->v[j] = faces[i]->v[idx];\n\t\t\t\t\t\t\t//tri->vn[j] = faces[i]->vn[idx];\n\t\t\t\t\t\t\ttri->uv[j] = faces[i]->uv[idx];\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttriangles.push_back(tri);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} // FacesToTriangles\n\n\t\t\tstatic void CollapseEdge(int edge, std::vector<Triangle *> &triangles, std::vector<Edge *> &edges, std::vector<Vertex3D> &coords)\n\t\t\t{\n\t\t\t\tEdge *pEdge = edges[edge];\n\t\t\t\tint f1 = pEdge->f1;\n\t\t\t\tint f2 = pEdge->f2;\n\t\t\t\tint v1 = pEdge->v1;\n\t\t\t\tint v2 = pEdge->v2;\n\t\t\t\t// will this work?\n\t\t\t\ttriangles.erase(triangles.begin()+f1);\n\t\t\t\ttriangles.erase(triangles.begin()+f2);\n\n\t\t\t\tedges.erase((edges.begin()+edge));\n\t\t\t}\n\n\t\t\tstatic int CountDuplicateVertices(std::vector<Vertex3D> &coords) {\n\t\t\t\tint duplicates = 0;\n\t\t\t\tfor(int i=0;i<coords.size();i++) {\n\t\t\t\t\tfloat temp[3];\n\t\t\t\t\tvNorm(temp,coords[i].data);\n\t\t\t\t\tfor(int j=0;j<coords.size();j++) {\n\t\t\t\t\t\tif (i==j) continue;\n\t\t\t\t\t\tfloat temp2[3];\n\t\t\t\t\t\tvNorm(temp2, coords[j].data);\n\t\t\t\t\t\tfloat fac = vDot(temp,temp2);\n\t\t\t\t\t\tif (fac>0 && fac<0.01) {\n\t\t\t\t\t\t\tduplicates++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn duplicates;\n\t\t\t}\n\n\t\t\t// Calculates bound sphere radius and mid point\n\t\t\tstatic double CalculateBoundingSphere(Vertex3D &mid, std::vector<Vertex3D> &coords) {\n\t\t\t\tVertex3D cmax,cmin;\n\t\t\t\tfloat tmp[3];\n\t\t\t\tcmax = coords[0];\n\t\t\t\tcmin = coords[1];\n\t\t\t\t// Find max/min vertex\n\t\t\t\tfor(int i=0;i<coords.size();i++) {\n\t\t\t\t\tcmax.data[0] = fmax(coords[i].data[0], cmax.data[0]);\n\t\t\t\t\tcmax.data[1] = fmax(coords[i].data[1], cmax.data[1]);\n\t\t\t\t\tcmax.data[2] = fmax(coords[i].data[2], cmax.data[2]);\n\n\t\t\t\t\tcmin.data[0] = fmin(coords[i].data[0], cmin.data[0]);\n\t\t\t\t\tcmin.data[1] = fmin(coords[i].data[1], cmin.data[1]);\n\t\t\t\t\tcmin.data[2] = fmin(coords[i].data[2], cmin.data[2]);\n\t\t\t\t}\n\n\t\t\t\t// Calculate radius and mid-point\n\t\t\t\t// Note: Why 2.5???\n\t\t\t\tdouble r = vAbs(vSub(tmp,cmax.data, cmin.data)) / 2.5;\n\t\t\t\tvAdd(tmp, cmax.data, cmin.data);\n\t\t\t\tvMul(mid.data, tmp, 0.5);\n\t\t\t\treturn r;\n\t\t\t}\n\n\t\t\tstatic int SplitEdge(std::vector<Vertex3D> &coordOut, std::vector<Vertex3D> &coords, int v1, int v2) {\n\t\t\t\tVertex3D mid;\n\t\t\t\tvMul(mid.data, vAdd(mid.data,coords[v1].data,coords[v2].data),0.5f);\n\t\t\t\tcoordOut.push_back(mid);\n\t\t\t\treturn (coordOut.size()-1);\n\t\t\t}\n\n\t\t\t/*      2\n\t\t\t *     4 5\n\t\t\t *    1 6 3\n\t\t\t *\n\t\t\t * Tris:\n\t\t\t * \t1,4,6\n\t\t\t * \t2,5,4\n\t\t\t * \t3,6,5\n\t\t\t * \t4,5,6\n\t\t\t *\n\t\t\t*/\n\t\t\tstatic void SplitTriangle(std::vector<Triangle *> &triOut, std::vector<Vertex3D> &coordOut, Triangle *triangle, std::vector<Vertex3D> &coords) {\n\t\t\t\tint v1 = triangle->v[0];\n\t\t\t\tint v2 = triangle->v[1];\n\t\t\t\tint v3 = triangle->v[2];\n\n\t\t\t\tint idxStart = coordOut.size();\n\t\t\t\tcoordOut.push_back(coords[v1]);\n\t\t\t\tcoordOut.push_back(coords[v2]);\n\t\t\t\tcoordOut.push_back(coords[v3]);\n\t\t\t\tSplitEdge(coordOut, coords, v1, v2);\n\t\t\t\tSplitEdge(coordOut, coords, v2, v3);\n\t\t\t\tSplitEdge(coordOut, coords, v3, v1);\n\t\t\t\t// Create 4 new triangles\n\n\t\t\t\ttriOut.push_back(new Triangle(idxStart+0, idxStart+3, idxStart+5));\n\t\t\t\ttriOut.push_back(new Triangle(idxStart+1, idxStart+4, idxStart+3));\n\t\t\t\ttriOut.push_back(new Triangle(idxStart+2, idxStart+5, idxStart+4));\n\t\t\t\ttriOut.push_back(new Triangle(idxStart+3, idxStart+4, idxStart+5));\n\t\t\t}\n\n\t\tprivate:\n\t\t\tstatic void GetOrAddEdgeMap(boost::unordered::unordered_map<int, Edge *> &edges, \n\t\t\t\tstd::vector<Triangle *> &triangles, \n\t\t\t\tconst std::vector<Vertex3D> &vertices, \n\t\t\t\tint face, int v1, int v2) {\n\t\t\t\tEdge *pEdge = NULL;\n\n\t\t\t\tint hashCode = Edge::HashCode(triangles[face]->v[v1], triangles[face]->v[v2]);\n\t\t\t\t//printf(\"hc: %d (%d, %d)\\n\",hashCode,faces[face]->v[v1], faces[face]->v[v2]);\n\t\t\t\tif (edges.find(hashCode) == edges.end()) {\n\t\t\t\t\tpEdge = new Edge(triangles[face]->v[v1], triangles[face]->v[v2], vertices);\n\t\t\t\t\tpEdge->AddFace(face);\n\t\t\t\t\tedges.insert(std::pair<int, Edge *>(hashCode, pEdge));\n\t\t\t\t} else {\n\t\t\t\t\tif (edges[hashCode]->AddFace(face) != true) {\n\t\t\t\t\t\t//printf(\"!!!! MULTIPLE FACES SHARING SAME EDGE!!!\\n\");\n\t\t\t\t\t\t// TODO: Create new face!\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} // GetOrAddEdgeMap\n\t\t}; // class FaceHelper\n\t}\n}\n", "meta": {"hexsha": "bb0fa2084e9f46c89065c6aaa0635df0719121d2", "size": 12308, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gnilk/engine/FaceHelper.hpp", "max_stars_repo_name": "gnilk/meshopt", "max_stars_repo_head_hexsha": "6778809b8df3b5209f27c562331356844de81f96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gnilk/engine/FaceHelper.hpp", "max_issues_repo_name": "gnilk/meshopt", "max_issues_repo_head_hexsha": "6778809b8df3b5209f27c562331356844de81f96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gnilk/engine/FaceHelper.hpp", "max_forks_repo_name": "gnilk/meshopt", "max_forks_repo_head_hexsha": "6778809b8df3b5209f27c562331356844de81f96", "max_forks_repo_licenses": ["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.3044619423, "max_line_length": 166, "alphanum_fraction": 0.6078160546, "num_tokens": 3895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5163000345171339}}
{"text": "// SPDX-License-Identifier: MIT\n// Copyright (c) 2021 ETH Zurich, Luc Grosheintz-Laval\n\n#include <iostream>\n#include <string>\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <filesystem>\n#include <numeric>\n#include <zisa/grid/grid.hpp>\n#include <zisa/io/hdf5_serial_writer.hpp>\n#include <zisa/math/cartesian.hpp>\n#include <zisa/math/permutation.hpp>\n#include <zisa/math/space_filling_curve.hpp>\n#include <zisa/memory/array.hpp>\n#include <zisa/memory/array_view.hpp>\n\nnamespace zisa {\n\nvoid sanity_check(const array_const_view<int_t, 2> &vertex_indices,\n                  const array_const_view<XYZ, 1> vertices) {\n\n  auto v = [&vertex_indices, &vertices](int_t i, int_t k) {\n    return vertices[vertex_indices(i, k)];\n  };\n\n  auto n_cells = vertex_indices.shape(0);\n  auto volumes = array<double, 1>(n_cells);\n  auto areas = array<double, 1>(n_cells);\n\n  for (int_t i = 0; i < n_cells; ++i) {\n    auto tet = Tetrahedron(v(i, 0), v(i, 1), v(i, 2), v(i, 3));\n    volumes(i) = volume(tet);\n    areas(i) = volume(face(tet, 0)) + volume(face(tet, 1))\n               + volume(face(tet, 2)) + volume(face(tet, 3));\n  }\n\n  auto [vol_min, vol_max] = std::minmax_element(volumes.begin(), volumes.end());\n\n  LOG_WARN_IF(*vol_max / *vol_min > 10.0, \"Suspect cell found.\");\n  LOG_ERR_IF(*vol_max / *vol_min > 100.0, \"Faulty cell found.\");\n}\n\nvoid renumber_grid(const std::string &grid_file) {\n\n  auto [vertices, vertex_indices, n_dims] = [&grid_file]() {\n    auto reader = HDF5SerialReader(grid_file);\n\n    auto vertices = array<XYZ, 1>::load(reader, \"vertices\");\n    auto vertex_indices = array<int_t, 2>::load(reader, \"vertex_indices\");\n    auto n_dims = reader.read_scalar<int_t>(\"n_dims\");\n\n    return std::tuple{\n        std::move(vertices), std::move(vertex_indices), std::move(n_dims)};\n  }();\n\n  sanity_check(vertex_indices, vertices);\n\n  auto n_cells = vertex_indices.shape(0);\n  auto max_vertices = vertex_indices.shape(1);\n  auto cell_centers = array<XYZ, 1>(n_cells);\n\n  double x_min = std::numeric_limits<double>::max();\n  double x_max = std::numeric_limits<double>::min();\n\n  double y_min = std::numeric_limits<double>::max();\n  double y_max = std::numeric_limits<double>::min();\n\n  double z_min = std::numeric_limits<double>::max();\n  double z_max = std::numeric_limits<double>::min();\n\n  for (int_t i = 0; i < n_cells; ++i) {\n    cell_centers[i] = vertices[vertex_indices(i, 0)];\n    for (int_t k = 0; k < max_vertices; ++k) {\n      cell_centers[i] += vertices[vertex_indices(i, k)];\n    }\n\n    cell_centers[i] /= max_vertices;\n\n    x_min = zisa::min(cell_centers[i][0], x_min);\n    x_max = zisa::max(cell_centers[i][0], x_max);\n\n    y_min = zisa::min(cell_centers[i][1], y_min);\n    y_max = zisa::max(cell_centers[i][1], y_max);\n\n    z_min = zisa::min(cell_centers[i][2], z_min);\n    z_max = zisa::max(cell_centers[i][2], z_max);\n  }\n\n  for (int_t i = 0; i < n_cells; ++i) {\n    auto [x, y, z] = cell_centers[i];\n\n    cell_centers[i][0] = (x - x_min) / (x_max - x_min + 1e-10 * x_max);\n    cell_centers[i][1] = (y - y_min) / (y_max - y_min + 1e-10 * y_max);\n\n    if (n_dims == 3) {\n      cell_centers[i][2] = (z - z_min) / (z_max - z_min + 1e-10 * z_max);\n    }\n  }\n\n  auto sfc_indices = array<int_t, 1>(n_cells);\n  for (int_t i = 0; i < n_cells; ++i) {\n    if (n_dims == 2) {\n      auto [x, y, _] = cell_centers[i];\n      sfc_indices[i]\n          = integer_cast<int_t>(hilbert_index<64 / 2>(x, y).to_ullong());\n    }\n\n    if (n_dims == 3) {\n      auto [x, y, z] = cell_centers[i];\n      sfc_indices[i]\n          = integer_cast<int_t>(hilbert_index<64 / 3>(x, y, z).to_ullong());\n    }\n  }\n\n  auto sigma = array<int_t, 1>(n_cells);\n  for (int_t i = 0; i < n_cells; ++i) {\n    sigma[i] = i;\n  }\n  std::sort(sigma.begin(), sigma.end(), [&sfc_indices](int_t i, int_t j) {\n    return sfc_indices[i] < sfc_indices[j];\n  });\n\n  apply_permutation(array_view(vertex_indices), factor_permutation(sigma));\n\n  {\n    auto writer = HDF5SerialWriter(grid_file + \"_\");\n    save(writer, vertices, \"vertices\");\n    save(writer, vertex_indices, \"vertex_indices\");\n    writer.write_scalar(n_dims, \"n_dims\");\n  }\n  std::filesystem::rename(grid_file + \"_\", grid_file);\n}\n\nvoid generate_full_grid(const std::string &msh_h5_file) {\n  auto grid = zisa::load_grid(msh_h5_file);\n\n  auto filename = msh_h5_file.substr(0, msh_h5_file.size() - 7) + \".h5\";\n  auto hdf5_writer = HDF5SerialWriter(filename);\n  save(hdf5_writer, *grid);\n}\n\n}\n\nint main(int argc, char *argv[]) {\n#if ZISA_HAS_MPI\n  MPI_Init(&argc, &argv);\n#endif\n\n  po::variables_map options;\n\n  // generic options\n  po::options_description generic(\"Generic options\");\n\n  // clang-format off\n  generic.add_options()\n      (\"help,h\", \"produce this message\")\n      (\"grid\", po::value<std::string>(), \"Name of the .msh.h5 grid file, will be overwritten.\")\n      ;\n  // clang-format on\n\n  // first parse cmdline and check what config file to use\n  po::store(po::parse_command_line(argc, argv, generic), options);\n\n  if (options.count(\"help\") != 0) {\n    std::cout << generic << \"\\n\";\n    std::exit(EXIT_SUCCESS);\n  }\n\n  if (options.count(\"grid\") == 0) {\n    std::cout << \"Missing argument `--grid GRID`.\\n\";\n    std::exit(EXIT_FAILURE);\n  }\n\n  auto grid_file = options[\"grid\"].as<std::string>();\n\n  zisa::renumber_grid(grid_file);\n  zisa::generate_full_grid(grid_file);\n\n#if ZISA_HAS_MPI\n  MPI_Finalize();\n#endif\n}\n", "meta": {"hexsha": "5c25b026e13e4af1a597ae7bed9f7c87b47bcd4a", "size": 5386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/renumber_grid.cpp", "max_stars_repo_name": "1uc/ZisaFVM", "max_stars_repo_head_hexsha": "75fcedb3bece66499e011228a39d8a364b50fd74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/renumber_grid.cpp", "max_issues_repo_name": "1uc/ZisaFVM", "max_issues_repo_head_hexsha": "75fcedb3bece66499e011228a39d8a364b50fd74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/renumber_grid.cpp", "max_forks_repo_name": "1uc/ZisaFVM", "max_forks_repo_head_hexsha": "75fcedb3bece66499e011228a39d8a364b50fd74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T11:52:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T11:52:51.000Z", "avg_line_length": 28.9569892473, "max_line_length": 95, "alphanum_fraction": 0.640549573, "num_tokens": 1609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5163000286848346}}
{"text": "//\n// Created by Vlad Argunov on 24/10/2021.\n//\n\n#include \"Option.h\"\n#include <iostream>\n#include <Eigen/Dense>\n#include <string>\n#include <algorithm>\n#include <iomanip>\n\n\nOption::Option(std::string type_option_, bool european_){\n    type_option = type_option_;\n    european = european_;\n}\n\nvoid Option::set_tn(double tn_) {\n    tn = tn_;\n\n}\n\nvoid Option::set_s_max(double s_max_) {\n    s_max = s_max_;\n}\n\nvoid Option::set_numdiff_t(int numdiff_t_) {\n    numdiff_t = numdiff_t_;\n}\n\nvoid Option::set_numdiff_s(int numdiff_s_) {\n    numdiff_s = numdiff_s_;\n    }\n\nvoid Option::set_volatility(double vol_, bool stochastic_vol_) {\n    stochastic_vol = stochastic_vol_;\n    if (stochastic_vol == 0){\n        deterministic_vol = vol_;\n    }\n    // Code for implementation of stochastic volatility\n}\n\nvoid Option::set_interest_rate(double rate_, bool stochastic_rate_) {\n    stochastic_rate = stochastic_rate_;\n    if (stochastic_rate == 0){\n        deterministic_rate = rate_;\n    }\n    // Code for implementation of stochastic interest rate\n}\n\nvoid Option::set_strike(double strike_) {\n    strike = strike_;\n}\n\nvoid Option::set_stock_boundary_condition(std::string stock_boundary_condition_) {\n    stock_boundary_condition = stock_boundary_condition_;\n}\n\n\ndouble Option::parameter_a(int n) {\n    if (stochastic_vol == 0 && stochastic_rate == 0 && fixed_step_time == 1){\n        return 0.5 * (deterministic_rate * n - deterministic_vol * deterministic_vol * n * n) * fixed_dt;\n    }\n\n}\n\ndouble Option::parameter_b(int n) {\n    if (stochastic_vol == 0 && stochastic_rate == 0 && fixed_step_time == 1) {\n        return (deterministic_vol * deterministic_vol * n * n + deterministic_rate) * fixed_dt;\n    }\n}\n\ndouble Option::parameter_c(int n) {\n    if (stochastic_vol == 0 && stochastic_rate == 0 && fixed_step_time == 1) {\n        return -0.5 * (deterministic_vol * deterministic_vol * n * n + deterministic_rate * n) * fixed_dt;\n    }\n}\n\n\nEigen::MatrixXd Option::implicit_matrix_vanilla() {\n    double a;\n    double b;\n    double c;\n    Eigen::MatrixXd computation_matrix;\n    computation_matrix.resize(numdiff_s - 1, numdiff_s - 1);\n    for (int row = 0; row < computation_matrix.rows(); ++row) {\n        if (row == 0){\n            b = parameter_b(row + 1);\n            c = parameter_c(row + 1);\n            computation_matrix(row,row) = 1 + b;\n            computation_matrix(row,row + 1) = c;\n        } else if (row == computation_matrix.rows() - 1) {\n            b = parameter_b(row + 1);\n            a = parameter_a(row + 1);\n            computation_matrix(row, row) = 1 + b;\n            computation_matrix(row, row - 1) = a;\n        } else {\n            a = parameter_a(row + 1);\n            b = parameter_b(row + 1);\n            c = parameter_c(row + 1);\n            computation_matrix(row, row) = 1 + b;\n            computation_matrix(row, row - 1) = a;\n            computation_matrix(row, row + 1) = c;\n        }\n    }\n    return computation_matrix;\n}\n\nvoid Option::fixed_difference_step(bool fixed_step_stock_, bool fixed_step_time_) {\n    fixed_step_stock = fixed_step_stock_;\n    fixed_step_time = fixed_step_time_;\n    if (fixed_step_stock == 1 && fixed_step_time == 1){\n        fixed_dt = tn / numdiff_t;\n        fixed_ds = s_max / numdiff_s;\n    }\n\n    // Code of the step size is not fixed\n\n}\n\n\nvoid Option::compute_solution_grid(std::string method) {\n    if (type_option == \"Call\"  || type_option == \"Put\" && european == 1){\n        solution_grid = solution_grid_vanilla(method);\n    }\n\n\n}\n\nvoid Option::create_boundary_condition_time(Eigen::VectorXd& boundary_vector) {\n\n    if (fixed_step_time == 1 && fixed_step_stock == 1){\n        for (int row=0; row < boundary_vector.rows(); ++row) {\n            if (type_option == \"Call\")\n                boundary_vector(row, 0) = std::max((row + 1) * fixed_ds - strike, 0.0);\n            else if (type_option == \"Put\")\n                boundary_vector(row, 0) = std::max(strike - (row + 1) * fixed_ds, 0.0);\n        }\n    }\n\n}\n\n\nEigen::MatrixXd Option::solution_grid_vanilla(std::string method) {\n    Eigen::MatrixXd solution_matrix;\n\n    if (method == \"Implicit\"){\n        // Implementation of the solution grid computation with Dirichlet boundary conditions\n        if (stock_boundary_condition == \"Dirichlet\"){\n\n            Eigen::MatrixXd implicit_matrix = implicit_matrix_vanilla().inverse();\n            Eigen::VectorXd current_vt;\n            Eigen::VectorXd previous_vt;\n\n            Eigen::Index implicit_matrix_rows = implicit_matrix.rows();\n\n            current_vt.resize(implicit_matrix_rows);\n            create_boundary_condition_time(current_vt);\n            previous_vt.resize(implicit_matrix_rows);\n\n            Eigen::Index solution_matrix_cols = numdiff_t + 1;\n\n            solution_matrix.resize(implicit_matrix_rows, solution_matrix_cols);\n\n            Eigen::VectorXd adjustment_dirichlet = Eigen::VectorXd::Zero(implicit_matrix_rows);\n\n            double a = parameter_a(1);\n            double c = parameter_c(numdiff_s - 1);\n\n            for (int t = 0; t < solution_matrix_cols; ++t) {\n                // Add adjustment for Dirichlet\n                if (type_option == \"Call\"){\n                    adjustment_dirichlet(implicit_matrix_rows - 1,0) = c * (s_max - strike * exp( - deterministic_rate * (t - 1) * fixed_dt));\n                    adjustment_dirichlet(0,0) = 0;\n                } else if (type_option == \"Put\"){\n                    adjustment_dirichlet(implicit_matrix_rows - 1,0) = 0;\n                    adjustment_dirichlet(0,0) = a * strike * exp( - deterministic_rate * (t - 1) * fixed_dt);\n                }\n\n                // Perform the iteration\n                if (t == 0) {\n                    solution_matrix.col(solution_matrix_cols - 1) = current_vt;\n                } else {\n                    previous_vt = implicit_matrix * (current_vt - adjustment_dirichlet);\n                    solution_matrix.col(solution_matrix_cols - t - 1) = previous_vt;\n                    current_vt = previous_vt;\n                }\n            }\n\n            Eigen::MatrixXd solution_matrix_adjusted;\n            solution_matrix_adjusted.resize(implicit_matrix_rows + 2, solution_matrix_cols);\n            Eigen::MatrixXd & ref_solution_matrix = solution_matrix;\n            solution_matrix_adjusted.middleRows(1,implicit_matrix_rows) = ref_solution_matrix;\n\n            for (int col = 0; col < solution_matrix_cols; ++col) {\n                if (type_option == \"Call\"){\n                    solution_matrix_adjusted(0,solution_matrix_cols - col - 1) = 0;\n                    solution_matrix_adjusted(implicit_matrix_rows + 1, solution_matrix_cols - col - 1) = s_max - strike * exp( - deterministic_rate * col * fixed_dt);\n                } else if (type_option == \"Put\") {\n                    solution_matrix_adjusted(0,solution_matrix_cols - col - 1) = strike * exp( - deterministic_rate * col * fixed_dt);\n                    solution_matrix_adjusted(implicit_matrix_rows + 1, solution_matrix_cols - col - 1) = 0;\n                }\n            }\n            return solution_matrix_adjusted;\n        }\n\n        if (stock_boundary_condition == \"Neumann\"){\n\n            double a = parameter_a(1);\n            double c = parameter_c(numdiff_s - 1);\n\n            Eigen::MatrixXd implicit_matrix = implicit_matrix_vanilla();\n            Eigen::Index implicit_matrix_rows = implicit_matrix.rows();\n            implicit_matrix(0,0) += 2 * a;\n            implicit_matrix(0,1) -= a;\n\n            implicit_matrix(implicit_matrix_rows - 1, implicit_matrix_rows - 1) += 2 * c;\n            implicit_matrix(implicit_matrix_rows - 1, implicit_matrix_rows - 2) -= c;\n\n            implicit_matrix = implicit_matrix.inverse();\n\n            Eigen::VectorXd current_vt;\n            current_vt.resize(implicit_matrix_rows);\n            create_boundary_condition_time(current_vt);\n\n            Eigen::VectorXd previous_vt;\n            previous_vt.resize(implicit_matrix_rows);\n\n            Eigen::Index solution_matrix_cols = numdiff_t + 1;\n\n            solution_matrix.resize(implicit_matrix_rows, solution_matrix_cols);\n\n            for (int t = 0; t < solution_matrix_cols; ++t) {\n                // Perform the iteration\n                if (t == 0) {\n                    solution_matrix.col(solution_matrix_cols - 1) = current_vt;\n                } else {\n                    previous_vt = implicit_matrix * current_vt;\n                    solution_matrix.col(solution_matrix_cols - t - 1) = previous_vt;\n                    current_vt = previous_vt;\n                }\n            }\n\n            Eigen::MatrixXd solution_matrix_adjusted;\n            solution_matrix_adjusted.resize(implicit_matrix_rows + 2, solution_matrix_cols);\n            Eigen::MatrixXd & ref_solution_matrix = solution_matrix;\n            solution_matrix_adjusted.middleRows(1,implicit_matrix_rows) = ref_solution_matrix;\n\n            for (int col = 0; col < solution_matrix_cols; ++col) {\n                Eigen::Index column_number = solution_matrix_cols - col - 1;\n                Eigen::Index last_row = implicit_matrix_rows + 1;\n                solution_matrix_adjusted(0,column_number) = 2 * solution_matrix_adjusted(1,column_number)\n                            - solution_matrix_adjusted(2,column_number);\n                solution_matrix_adjusted(last_row, column_number) = 2 * solution_matrix_adjusted(last_row - 1, column_number)\n                            - solution_matrix_adjusted(last_row - 2, column_number);\n\n            }\n            return solution_matrix_adjusted;\n        }}\n\n    if (method == \"Crank-Nicholson\"){\n        if (stock_boundary_condition == \"Dirichlet\"){\n\n            Eigen::MatrixXd implicit_matrix = implicit_matrix_vanilla();\n            Eigen::MatrixXd implicit_matrix_cn = - implicit_matrix;\n            Eigen::Index implicit_matrix_rows = implicit_matrix_cn.cols();\n            Eigen::MatrixXd identity = Eigen::MatrixXd::Identity(implicit_matrix_rows, implicit_matrix_rows);\n            const Eigen::MatrixXd & ref_identity = identity;\n            implicit_matrix_cn += 3 * ref_identity;\n            implicit_matrix += ref_identity;\n            implicit_matrix = implicit_matrix.inverse();\n\n\n            Eigen::VectorXd current_vt;\n            Eigen::VectorXd previous_vt;\n\n            current_vt.resize(implicit_matrix_rows);\n            create_boundary_condition_time(current_vt);\n            previous_vt.resize(implicit_matrix_rows);\n\n            Eigen::Index solution_matrix_cols = numdiff_t + 1;\n            solution_matrix.resize(implicit_matrix_rows, solution_matrix_cols);\n\n            Eigen::VectorXd adjustment_dirichlet = Eigen::VectorXd::Zero(implicit_matrix_rows);\n\n            double a = parameter_a(1);\n            double c = parameter_c(numdiff_s - 1);\n\n            for (int t = 0; t < solution_matrix_cols; ++t) {\n                // Add adjustment for Dirichlet\n                if (type_option == \"Call\"){\n                    adjustment_dirichlet(adjustment_dirichlet.rows() - 1,0) = c * (2 * s_max - strike * exp( - deterministic_rate * (t - 1) * fixed_dt)\n                            - strike * exp( - deterministic_rate * std::max(t - 2,0) * fixed_dt));\n                    adjustment_dirichlet(0,0) = 0;\n                } else if (type_option == \"Put\"){\n                    adjustment_dirichlet(adjustment_dirichlet.rows() - 1,0) = 0;\n                    adjustment_dirichlet(0,0) = a * strike * ( exp( - deterministic_rate * (t - 1) * fixed_dt)\n                            + exp( - deterministic_rate * std::max(t - 2,0) * fixed_dt));\n                }\n\n                // Perform the iteration\n                if (t == 0) {\n                    solution_matrix.col(solution_matrix_cols - 1) = current_vt;\n                } else {\n                    previous_vt = implicit_matrix * (implicit_matrix_cn * current_vt - adjustment_dirichlet);\n                    solution_matrix.col(solution_matrix_cols - t - 1) = previous_vt;\n                    current_vt = previous_vt;\n                }\n            }\n\n            Eigen::MatrixXd solution_matrix_adjusted;\n            solution_matrix_adjusted.resize(implicit_matrix_rows + 2, solution_matrix_cols);\n            Eigen::MatrixXd & ref_solution_matrix = solution_matrix;\n            solution_matrix_adjusted.middleRows(1,implicit_matrix_rows) = ref_solution_matrix;\n\n            for (int col = 0; col < solution_matrix_cols; ++col) {\n                if (type_option == \"Call\"){\n                    solution_matrix_adjusted(0,solution_matrix_cols - col - 1) = 0;\n                    solution_matrix_adjusted(implicit_matrix_rows + 1, solution_matrix_cols - col - 1) = s_max - strike * exp( - deterministic_rate * col * fixed_dt);\n                } else if (type_option == \"Put\") {\n                    solution_matrix_adjusted(0,solution_matrix_cols - col - 1) = strike * exp( - deterministic_rate * col * fixed_dt);\n                    solution_matrix_adjusted(implicit_matrix_rows + 1, solution_matrix_cols - col - 1) = 0;\n                }\n            }\n            return solution_matrix_adjusted;\n        }\n        if (stock_boundary_condition == \"Neumann\"){\n            Eigen::MatrixXd implicit_matrix = implicit_matrix_vanilla();\n            Eigen::MatrixXd implicit_matrix_cn = - implicit_matrix;\n            Eigen::Index implicit_matrix_rows = implicit_matrix_cn.rows();\n            Eigen::MatrixXd identity = Eigen::MatrixXd::Identity(implicit_matrix_rows, implicit_matrix_rows);\n            const Eigen::MatrixXd & ref_identity = identity;\n            implicit_matrix_cn += 3 * ref_identity;\n            implicit_matrix += ref_identity;\n\n            double a = parameter_a(1);\n            double c = parameter_c(numdiff_s - 1);\n\n            implicit_matrix(0,0) += 2 * a;\n            implicit_matrix(0,1) -= a;\n\n            implicit_matrix(implicit_matrix.rows() - 1, implicit_matrix.cols() - 1) += 2 * c;\n            implicit_matrix(implicit_matrix.rows() - 1, implicit_matrix.cols() - 2) -= c;\n\n            implicit_matrix_cn(0,0) -= 2 * a;\n            implicit_matrix_cn(0,1) += a;\n\n            implicit_matrix_cn(implicit_matrix.rows() - 1, implicit_matrix.cols() - 1) -= 2 * c;\n            implicit_matrix_cn(implicit_matrix.rows() - 1, implicit_matrix.cols() - 2) += c;\n\n            implicit_matrix = implicit_matrix.inverse();\n\n            Eigen::VectorXd current_vt;\n            current_vt.resize(implicit_matrix_rows);\n            create_boundary_condition_time(current_vt);\n\n            Eigen::VectorXd previous_vt;\n            previous_vt.resize(implicit_matrix_rows);\n\n            Eigen::Index solution_matrix_cols = numdiff_t + 1;\n            solution_matrix.resize(implicit_matrix_rows, solution_matrix_cols);\n\n            for (int t = 0; t < solution_matrix_cols; ++t) {\n                // Perform the iteration\n                if (t == 0) {\n                    solution_matrix.col(solution_matrix_cols - 1) = current_vt;\n                } else {\n                    previous_vt = implicit_matrix * (implicit_matrix_cn * current_vt);\n                    solution_matrix.col(solution_matrix_cols - t - 1) = previous_vt;\n                    current_vt = previous_vt;\n                }\n            }\n\n            Eigen::MatrixXd solution_matrix_adjusted;\n\n            solution_matrix_adjusted.resize(implicit_matrix_rows + 2, solution_matrix_cols);\n            Eigen::MatrixXd & ref_solution_matrix = solution_matrix;\n            solution_matrix_adjusted.middleRows(1,implicit_matrix_rows) = ref_solution_matrix;\n\n            for (int col = 0; col < solution_matrix_cols; ++col) {\n                Eigen::Index column_number = solution_matrix_cols - col - 1;\n                Eigen::Index last_row = implicit_matrix_rows + 1;\n                solution_matrix_adjusted(0,column_number) = 2 * solution_matrix_adjusted(1,column_number)\n                                                            - solution_matrix_adjusted(2,column_number);\n                solution_matrix_adjusted(last_row, column_number) = 2 * solution_matrix_adjusted(last_row - 1, column_number)\n                                                                    - solution_matrix_adjusted(last_row - 2, column_number);\n            }\n            return solution_matrix_adjusted;\n        }\n\n    }\n\n}\n\n\nvoid Option::print_solution_grid(int precision) {\n    std::cout << \"Type of Option: \" + type_option + \"\\n\";\n    std::cout << \"Stock boundary condition: \" + stock_boundary_condition + \"\\n\\n\";\n    std::cout << \"Legend of the matrix: s/t 1 2 . . T\\n\";\n    std::cout << \"                      0   x x x x x\\n\";\n    std::cout << \"                      1   x x x x x\\n\";\n    std::cout << \"                      .   x x x x x\\n\";\n    std::cout << \"                      .   x x x x x\\n\";\n    std::cout << \"                  S_max   x x x x x\\n\\n\";\n    std::cout << \"Printing the solution grid:\\n\\n\";\n\n    Eigen::MatrixXd printing_matrix;\n    printing_matrix.resize(solution_grid.rows() + 1, solution_grid.cols() + 1);\n    printing_matrix.bottomRightCorner(solution_grid.rows(),solution_grid.cols()) = solution_grid;\n\n    if (fixed_step_time == 1){\n        for (int col = 1; col < printing_matrix.cols(); ++col) {\n            printing_matrix(0, col) = fixed_dt * (col - 1);\n        }\n\n    }\n\n    if (fixed_step_stock == 1){\n        for (int row = 1; row < printing_matrix.rows(); ++row) {\n            printing_matrix(row, 0) = fixed_ds * (row - 1);\n        }\n    }\n\n    std::streamsize prec = std::cout.precision();\n    std::cout << std::setprecision(precision) << printing_matrix << std::setprecision(prec) << \"\\n\";\n}\n", "meta": {"hexsha": "f5540f5cbb4faf192b80ac7ed4c4d51462724197", "size": 17547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Option.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/Option.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/Option.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": 41.093676815, "max_line_length": 166, "alphanum_fraction": 0.5966262039, "num_tokens": 3951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5163000233471632}}
{"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(\"Adaptive Test\")\n{\n  using method_type             = ode::explicit_method<ode::dormand_prince_5_tableau<float>>;\n  using problem_type            = ode::initial_value_problem<float, Eigen::Vector3f>;\n  using i_controller_iterator   = ode::adaptive_step_iterator<method_type, problem_type, ode::integral_controller                        <method_type, problem_type>>;\n  using pi_controller_iterator  = ode::adaptive_step_iterator<method_type, problem_type, ode::proportional_integral_controller           <method_type, problem_type>>;\n  using pid_controller_iterator = ode::adaptive_step_iterator<method_type, problem_type, ode::proportional_integral_derivative_controller<method_type, problem_type>>;\n\n  constexpr auto sigma   = 10.0f;\n  constexpr auto rho     = 28.0f;\n  constexpr auto beta    = 8.0f / 3.0f;\n  const     auto problem = problem_type\n  {\n    0.0f,                                         /* t0 */\n    Eigen::Vector3f(16.0f, 16.0f, 16.0f),         /* y0 */\n    [&] (const float t, const Eigen::Vector3f& y) /* y' = f(t, y) */\n    {\n      return Eigen::Vector3f(sigma * (y[1] - y[0]), y[0] * (rho - y[2]) - y[1], y[0] * y[1] - beta * y[2]); /* Lorenz system */\n    }\n  };\n\n  auto iterator_1 = i_controller_iterator  (problem, 1.0f /* h */);\n  for (auto i = 0; i < 10000; ++i)\n    ++iterator_1;\n\n  auto iterator_2 = pi_controller_iterator (problem, 1.0f /* h */);\n  for (auto i = 0; i < 10000; ++i)\n    ++iterator_2;\n\n  auto iterator_3 = pid_controller_iterator(problem, 1.0f /* h */);\n  for (auto i = 0; i < 10000; ++i)\n    ++iterator_3;\n}", "meta": {"hexsha": "d4f5d8b233fe9777e4f17a6c47f11db893f6aa43", "size": 1681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/adaptive_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/adaptive_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/adaptive_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": 42.025, "max_line_length": 166, "alphanum_fraction": 0.6383105294, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5163000230998495}}
{"text": "#include<stdio.h>\r\n#include<cstring>\r\n#include<iostream>\r\n#include \"Eigen/Core\"\r\n#include \"Eigen/Dense\"\r\n#include \"Eigen/Sparse\"\r\n#include \"Eigen/SVD\"\r\n#include <Eigen/Eigenvalues> \r\n#include <unsupported/Eigen/SparseExtra>\r\n#include <unsupported/Eigen/KroneckerProduct>\r\n\r\nusing namespace Eigen;\r\nstd :: string filename = \"D:/sydney/first/data/tester_ (\";\r\nMatrixXf A,result;\r\nconst int nShape = 47;\r\nconst int nVerts = 11510;\r\nconst int nFaces = 11540;\r\nconst int test_num = 77;\r\nconst int iden_num = 10;\r\nstd::vector<int> mouse_edge[1000];\r\nusing namespace std;\r\n//int cnt_vtx[nVerts];\r\nvoid smooth_mesh(MatrixX3f &mesh, int iteration, std::vector<int> *mouse_edge) {\r\n\twhile (iteration--)\r\n\t{\r\n\t\tMatrixX3f temp = mesh;\r\n\r\n\t\tfor (int i_e = 0; mouse_edge[i_e].size() >0; i_e++) {\r\n\t\t\tif (mouse_edge[i_e].size() < 6) continue;\r\n\t\t\tint v = mouse_edge[i_e][0];\r\n\t\t\tmesh.block(v, 0, 1, 3).setZero();\r\n\t\t\tfor (int j = 1; j < mouse_edge[i_e].size(); j++)\r\n\t\t\t\tmesh.row(v).array() += temp.row(mouse_edge[i_e][j]).array() / (mouse_edge[i_e].size() - 1);\r\n\t\t}\r\n\t}\r\n}\r\nvoid load_smooth_edge(std::vector<int> *mouse_edge) {\r\n\tputs(\"loading mouse edge...\");\r\n\tFILE *fp;\r\n\tfopen_s(&fp, \"D:\\\\sydney\\\\first\\\\code\\\\2017\\\\cal_coeffience_Q_M_u_e_3\\\\cal_coeffience_Q_M_u_e_3/mouse_point.txt\", \"r\");\r\n\tint n;\r\n\tfscanf_s(fp, \"%d\", &n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tmouse_edge[i].clear();\r\n\t\tint t, num;\r\n\t\tfscanf_s(fp, \"%d%d\", &t, &num);\r\n\t\tmouse_edge[i].push_back(t);\r\n\t\tfor (int j = 0; j < num; j++) {\r\n\t\t\tfscanf_s(fp, \"%d\", &t);\r\n\t\t\tmouse_edge[i].push_back(t);\r\n\t\t}\r\n\t}\r\n\tfclose(fp);\r\n}\r\n\r\nint main() {\r\n\tA.resize(test_num, nShape*nVerts * 3);\r\n\tfor (int i = 0; i < test_num; i++) {\r\n\t\tstd::string name = filename + std::to_string(i + 1) + \")/Blendshape/shape.bs\";\r\n\t\tstd :: cout << name << std :: endl;\r\n\t\tFILE *fp;\r\n\t\tfopen_s(&fp,name.c_str(), \"rb\");\r\n\t\tint nShapes = 0, nVerts = 0, nFaces = 0;\r\n\t\tfread(&nShapes, sizeof(int), 1, fp);\t\t\t// nShape = 46\r\n\t\tfread(&nVerts, sizeof(int), 1, fp);\t\t\t// nVerts = 11510\r\n\t\tfread(&nFaces, sizeof(int), 1, fp);\t\t\t// nFaces = 11540\r\n\t\tprintf(\"%d %d %d\\n\", nShapes, nVerts, nFaces);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// Load neutral expression B_0\r\n\t\tfloat temp;\r\n\t\tfor (int j = 0; j < nVerts * 3; j++) {\r\n\t\t\tfread(&temp, sizeof(float), 1, fp);\r\n\t\t\tA(i, j) = temp;\r\n\t\t}\r\n\t\t//for (int j = 0; j < 10; j++)\r\n\t\t//\tprintf(\"%.10f \", A(i, j));\r\n\t\t//puts(\"\");\r\n\r\n\t\t// Load other expressions B_i ( 1 <= i <= 46 )\r\n\t\tfor (int exprId = 0; exprId < nShapes; exprId++) \t\r\n\t\t\tfor (int j = 0; j < nVerts * 3; j++) {\r\n\t\t\t\tfread(&temp, sizeof(float), 1, fp);\r\n\t\t\t\tA(i, 3 * nVerts*(exprId + 1) + j) = temp;\r\n\t\t\t}\r\n\t\t\r\n\t\tfclose(fp);\r\n\t}\r\n\tputs(\"loading initial bldshps complete!...\");\r\n\tload_smooth_edge(mouse_edge);\r\n\tfor (int i_id=0;i_id< iden_num;i_id++)\r\n\t\tfor (int i_exp = 0; i_exp < nShape; i_exp++) {\r\n\t\t\tprintf(\"smoothing id:%d exp:%d\\n\",i_id,i_exp);\r\n\t\t\tEigen::MatrixX3f temp(nVerts, 3);\r\n\t\t\tfor (int i_v = 0; i_v < nVerts; i_v++)\r\n\t\t\t\tfor (int axis = 0; axis < 3; axis++)\r\n\t\t\t\t\ttemp(i_v, axis) = A(i_id, i_exp*nVerts*3 + i_v * 3 + axis);\r\n\t\t\tsmooth_mesh(temp, 25, mouse_edge);\r\n\t\t\tfor (int i_v = 0; i_v < nVerts; i_v++)\r\n\t\t\t\tfor (int axis = 0; axis < 3; axis++)\r\n\t\t\t\t\tA(i_id, i_exp*nVerts * 3 + i_v * 3 + axis) = temp(i_v, axis);\r\n\t\t}\r\n\t\t\t\r\n\r\n\tputs(\"saving...\");\r\n\tFILE *fp;\r\n\tfopen_s(&fp, \"blendshape_ide_svd_77_ite25_bound.lv\", \"wb\");\r\n\tfor (int i = 0; i < iden_num; i++)\r\n\t\tfor (int j = 0; j < 3 * nVerts*nShape; j++)\r\n\t\t\tfwrite(&A(i, j), sizeof(float), 1, fp);\r\n\tfclose(fp);\r\n\r\n\t//MatrixXf mean = A.rowwise().mean();\r\n\t//cout << mean.rows() << ' ' << mean.cols() << '\\n';\r\n\t//cout << mean;\r\n\t//cout << A(32, 22301) << \"\\n\";\r\n\t//cout << A(24, 11144) << \"\\n\";\r\n\t//cout << A(53, 32333) << \"\\n\";\r\n\t//cout << A(60, 523441) << \"\\n\";\r\n\t//cout << A(8, 765201) << \"\\n\";\r\n\r\n\t//system(\"pause\");\r\n\t//VectorXf vmean = mean;\r\n\t//A.colwise() -= vmean;\r\n\t//BDCSVD<Eigen::MatrixXf> svd((A * A.transpose()).array()/ A.cols(), ComputeThinU);//*A.transpose()\r\n\t//puts(\"asd\");\r\n\t////printf(\"%d %d %d %d\\n\", U.rows(), U.cols(), V.rows(), V.cols());\r\n\t////cout <<\"U:\\n\"<< U << endl;\r\n\t////cout << \"V:\\n\" << V << endl;\r\n\t//MatrixXf  S = svd.singularValues();\r\n\t////printf(\"%d %d\\n\",S.cols(),S.rows());\r\n\t//float tot = 0,temp=0;\r\n\t//for (int i = 0; i < test_num; i++) tot += sqrt(S(i));\r\n\t//for (int i = 0; i < test_num; i++, puts(\"\")) {\r\n\t//\ttemp += sqrt(S(i));\r\n\t//\tprintf(\"%d %.10f %.2f\", i, sqrt(S(i)), temp / tot * 100);\r\n\t//}\r\n\t//A.colwise() += vmean;\r\n\t//result = svd.matrixU().block(0, 0, test_num, iden_num).transpose()*A;\r\n\t//FILE *fp;\r\n\t//fopen_s(&fp, \"blendshape_ide_svd_50.lv\", \"wb\");\r\n\t//for (int i = 0; i < iden_num; i++)\r\n\t//\tfor (int j = 0; j < 3 * nVerts*nShape; j++)\r\n\t//\t\tfwrite(&result(i,j),sizeof(float),1,fp);\r\n\t//fclose(fp);\r\n\t//fopen_s(&fp, \"blendshape_ide_svd_value_sqrt_50.txt\", \"w\");\r\n\t//for (int i = 0; i < iden_num; i++)\r\n\t//\tfprintf(fp, \"%.10f\\n\", sqrt(S(i)));\r\n\t//fclose(fp);\r\n\r\n\r\n\r\n\r\n\r\n\tsystem(\"pause\");\r\n\treturn 0;\r\n}\r\n\r\n\r\n/*\r\ntest svd\r\n\r\nMatrixXf m = MatrixXf::Random(3, 2);\r\nm.resize(3, 2);\r\ncout << \"Here is the matrix m:\" << endl << m << endl;\r\nJacobiSVD<MatrixXf> svd(m, ComputeThinU | ComputeThinV);\r\ncout << \"Its singular values are:\" << endl << svd.singularValues() << endl;\r\ncout << \"Its left singular vectors are the columns of the thin U matrix:\" << endl << svd.matrixU() << endl;\r\ncout << \"Its right singular vectors are the columns of the thin V matrix:\" << endl << svd.matrixV() << endl;*/", "meta": {"hexsha": "44cda8e37c6a88d4d9ca325aeefe2ba474c89e41", "size": 5418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main_smooth.cpp", "max_stars_repo_name": "sublimationAC/DDE", "max_stars_repo_head_hexsha": "fcde429b0db65100b8bd8bf607626b6beff8a431", "max_stars_repo_licenses": ["MIT"], "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_smooth.cpp", "max_issues_repo_name": "sublimationAC/DDE", "max_issues_repo_head_hexsha": "fcde429b0db65100b8bd8bf607626b6beff8a431", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-05T06:12:34.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-08T06:20:18.000Z", "max_forks_repo_path": "main_smooth.cpp", "max_forks_repo_name": "sublimationAC/DDE", "max_forks_repo_head_hexsha": "fcde429b0db65100b8bd8bf607626b6beff8a431", "max_forks_repo_licenses": ["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.25, "max_line_length": 121, "alphanum_fraction": 0.5645994832, "num_tokens": 1911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.51630001726755}}
{"text": "// Author: Dai Wei (wdai@cs.cmu.edu), Pengtao Xie (pxie@cs.cmu.edu)\n// Date: 2014.10.21\n\n#include <ml/util/math_util.hpp>\n#include <ml/util/fastapprox/fastapprox.hpp>\n#include <glog/logging.h>\n#include <cmath>\n#include <sstream>\n#include <Eigen/Dense>\n\nnamespace petuum {\nnamespace ml {\n\nnamespace {\n\nconst float kCutoff = 1e-15;\n\n}  // anonymous namespace\n\nfloat SafeLog(float x) {\n  if (std::abs(x) < kCutoff) {\n    x = kCutoff;\n  }\n  return fastlog(x);\n}\n\nfloat Sigmoid(float x) {\n  return 1. / (1. + exp(-x));\n}\n\nfloat LogSum(float log_a, float log_b) {\n  return (log_a < log_b) ? log_b + fastlog(1 + fastexp(log_a - log_b)) :\n    log_a + fastlog(1 + fastexp(log_b-log_a));\n}\n\nfloat LogSumVec(const std::vector<float>& logvec) {\n\tfloat sum = 0.;\n\tsum = logvec[0];\n\tfor (int i = 1; i < logvec.size(); ++i) {\n\t\tsum = LogSum(sum, logvec[i]);\n\t}\n\treturn sum;\n}\n\nvoid Softmax(std::vector<float>* vec) {\n  CHECK_NOTNULL(vec);\n  // TODO(wdai): Figure out why this is necessary. Doubt it is.\n\tfor (int i = 0; i < vec->size(); ++i) {\n\t\tif (std::abs((*vec)[i]) < kCutoff) {\n\t\t\t(*vec)[i] = kCutoff;\n    }\n\t}\n\tdouble lsum = LogSumVec(*vec);\n\tfor (int i = 0; i < vec->size(); ++i) {\n\t\t(*vec)[i] = fastexp((*vec)[i] - lsum);\n\t\t//(*vec)[i] = exp((*vec)[i] - lsum);\n    (*vec)[i] = (*vec)[i] > 1 ? 1. : (*vec)[i];\n  }\n}\n\nfloat DenseDenseFeatureDotProduct(const AbstractFeature<float>& f1,\n    const AbstractFeature<float>& f2) {\n  CHECK_EQ(f1.GetFeatureDim(), f2.GetFeatureDim());\n  auto f1_dense_ptr = static_cast<const DenseFeature<float>*>(&f1);\n  auto f2_dense_ptr = static_cast<const DenseFeature<float>*>(&f2);\n  const std::vector<float>& v1 = f1_dense_ptr->GetVector();\n  const std::vector<float>& v2 = f2_dense_ptr->GetVector();\n  Eigen::Map<const Eigen::VectorXf> e1(v1.data(), v1.size());\n  Eigen::Map<const Eigen::VectorXf> e2(v2.data(), v2.size());\n  return e1.dot(e2);\n}\n\nfloat SparseDenseFeatureDotProduct(const AbstractFeature<float>& f1,\n    const AbstractFeature<float>& f2) {\n  CHECK_EQ(f1.GetFeatureDim(), f2.GetFeatureDim());\n  float sum = 0.;\n  for (int i = 0; i < f1.GetNumEntries(); ++i) {\n    int32_t f1_fid = f1.GetFeatureId(i);\n    sum += f1.GetFeatureVal(i) * f2[f1_fid];\n  }\n  return sum;\n}\n\nfloat DenseSparseFeatureDotProduct(const AbstractFeature<float>& f1,\n    const AbstractFeature<float>& f2) {\n  return SparseDenseFeatureDotProduct(f2, f1);\n}\n\nfloat SparseSparseFeatureDotProduct(const AbstractFeature<float>& f1,\n    const AbstractFeature<float>& f2) {\n  CHECK_EQ(f1.GetFeatureDim(), f2.GetFeatureDim());\n  int j = 0;\n  float sum = 0.;\n  int f2_num_entries = f2.GetNumEntries();\n  for (int i = 0; i < f1.GetNumEntries() && j < f2_num_entries; ++i) {\n    int32_t f1_fid = f1.GetFeatureId(i);\n    while (f2.GetFeatureId(j) < f1_fid && j < f2_num_entries) {\n      ++j;\n    }\n    if (f1_fid == f2.GetFeatureId(j)) {\n      sum += f1.GetFeatureVal(i) * f2.GetFeatureVal(j);\n    }\n  }\n  return sum;\n}\n\nvoid FeatureScaleAndAdd(float alpha, const DenseFeature<float>& f1,\n    DenseFeature<float>* f2) {\n  CHECK_EQ(f1.GetFeatureDim(), f2->GetFeatureDim());\n  const std::vector<float>& f1_vec = f1.GetVector();\n  std::vector<float>& f2_vec = f2->GetVector();\n  for (int i = 0; i < f1_vec.size(); ++i) {\n    f2_vec[i] += alpha * f1_vec[i];\n  }\n}\n\n// f1 sparse, f2 dense.\nvoid FeatureScaleAndAdd(float alpha, const AbstractFeature<float>& f1,\n    AbstractFeature<float>* f2) {\n  CHECK_EQ(f1.GetFeatureDim(), f2->GetFeatureDim());\n  for (int i = 0; i < f1.GetNumEntries(); ++i) {\n    int32_t f1_fid = f1.GetFeatureId(i);\n    f2->SetFeatureVal(f1_fid, alpha * f1.GetFeatureVal(i) + (*f2)[f1_fid]);\n  }\n}\n\n}  // namespace ml\n}  // namespace petuum\n", "meta": {"hexsha": "5bb025bc27e6d5ead43c1f5b2cb1d6bd58d053d7", "size": 3656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ml/util/math_util.cpp", "max_stars_repo_name": "daiwei89/wdai_petuum_public", "max_stars_repo_head_hexsha": "4068859897061201d0a63630a3da6011b0d0f75f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 370.0, "max_stars_repo_stars_event_min_datetime": "2015-06-30T09:46:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-21T07:14:00.000Z", "max_issues_repo_path": "src/ml/util/math_util.cpp", "max_issues_repo_name": "daiwei89/wdai_petuum_public", "max_issues_repo_head_hexsha": "4068859897061201d0a63630a3da6011b0d0f75f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-11-08T19:45:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-11T13:21:19.000Z", "max_forks_repo_path": "src/ml/util/math_util.cpp", "max_forks_repo_name": "daiwei89/wdai_petuum_public", "max_forks_repo_head_hexsha": "4068859897061201d0a63630a3da6011b0d0f75f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 159.0, "max_forks_repo_forks_event_min_datetime": "2015-07-03T05:58:31.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-29T20:59:01.000Z", "avg_line_length": 28.3410852713, "max_line_length": 75, "alphanum_fraction": 0.6449671772, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5162951488806993}}
{"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_HELMERT_MATRIX_HPP\n#define ROKKO_UTILITY_HELMERT_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 helmert_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(\"helmert_matrix::generate() : non-square matrix\"));\n    int n = mat.rows();\n    mat.row(0).fill( 1 / sqrt(n) );\n    for (int i=1; i < mat.rows(); ++i) {\n      mat.row(i).head(i).fill( 1 / sqrt(static_cast<T>(i*(i+1))) );\n      mat(i,i) = - sqrt(static_cast<T>(i)/(i+1));\n    }\n  }\n\n  template<typename T, typename MATRIX_MAJOR>\n  static void generate_for_given_eigenvalues(rokko::localized_matrix<T, MATRIX_MAJOR>& mat, rokko::localized_vector<T> const& diag) {\n    if (mat.rows() != mat.cols())\n      BOOST_THROW_EXCEPTION(std::invalid_argument(\"helmert_matrix::generate() : non-square matrix\"));\n    int n = mat.rows();\n    for (int i=0; i<n; ++i) {\n      double common_elem = diag(0) / n;\n      for (int k=i+1; k<n; ++k)\n\tcommon_elem += diag(k) / (k*(k+1));  // Remark: i=max(i,j)\n      mat(i, i) = common_elem + i * diag(i) / (i+1);\n      double val = common_elem - diag(i) / (i+1);\n      mat.row(i).head(i).setConstant(val);\n      mat.col(i).head(i).setConstant(val);\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(\"helmert_matrix::generate() : non-square matrix\"));\n    const int n = mat.get_m_global();\n    int start_i;\n    if (mat.is_gindex_myrow(0)) {\n      T val = 1 / sqrt(n);\n      for(int local_j = 0; local_j < mat.get_n_local(); ++local_j)\n        mat.set_local(0, local_j, val);\n      start_i = 1;\n    }\n    else start_i = 0;\n\n    for(int local_i = start_i; local_i < mat.get_m_local(); ++local_i) {\n      int global_i = mat.translate_l2g_row(local_i);\n      T val = 1 / sqrt(static_cast<T>(global_i*(global_i+1)));\n      for(int local_j = 0; local_j < mat.get_n_local(); ++local_j) {\n        int global_j = mat.translate_l2g_col(local_j);\n\tif (global_j < global_i) mat.set_local(local_i, local_j, val);\n\telse if (global_j == global_i) mat.set_local(local_i, local_j, - sqrt(static_cast<T>(global_i)/(global_i+1)));\n      }\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<MATRIX_MAJOR>& mat) {\n    if (mat.m_global != mat.n_global)\n      BOOST_THROW_EXCEPTION(std::invalid_argument(\"helmert_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  */\n\n  template<typename T, typename MATRIX_MAJOR>\n  static void generate_for_given_eigenvalues(rokko::distributed_matrix<T, MATRIX_MAJOR>& mat, rokko::localized_vector<T> const& diag) {\n    if (mat.get_m_global() != mat.get_n_global())\n      BOOST_THROW_EXCEPTION(std::invalid_argument(\"helmert_matrix::generate() : non-square matrix\"));\n    const int n = mat.get_m_global();\n\n    for(int local_i = 0; local_i < mat.get_m_local(); ++local_i) {\n      int global_i = mat.translate_l2g_row(local_i);\n      double common_elem = diag(0) / n;\n      for (int k=global_i+1; k<n; ++k)\n\tcommon_elem += diag(k) / (k*(k+1));  // Remark: i=max(i,j)\n      T val = common_elem - diag(global_i) / (global_i+1);\n      for(int local_j = 0; local_j < mat.get_n_local(); ++local_j) {\n        int global_j = mat.translate_l2g_col(local_j);\n\tif (global_j < global_i) mat.set_local(local_i, local_j, val);\n\telse if (global_j == global_i) mat.set_local(local_i, local_j, common_elem + global_i * diag(global_i) / (global_i+1));\n      }\n    }\n    \n    for(int local_j = 0; local_j < mat.get_n_local(); ++local_j) {\n      int global_j = mat.translate_l2g_col(local_j);\n      double common_elem = diag(0) / n;\n      for (int k=global_j+1; k<n; ++k)\n\tcommon_elem += diag(k) / (k*(k+1));  // Remark: i=max(i,j)\n      T val = common_elem - diag(global_j) / (global_j+1);\n      for(int local_i = 0; local_i < mat.get_m_local(); ++local_i) {\n        int global_i = mat.translate_l2g_row(local_i);\n\tif (global_i < global_j) mat.set_local(local_i, local_j, val);\n      }\n    }\n  }\n#endif\n};\n    \n} // namespace rokko\n\n#endif // ROKKO_UTILITY_HELMERT_MATRIX_HPP\n", "meta": {"hexsha": "943e66547945bc9f6ed7a165ad63609f94d67cc3", "size": 5315, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rokko/utility/helmert_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/helmert_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/helmert_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": 39.962406015, "max_line_length": 135, "alphanum_fraction": 0.6474129821, "num_tokens": 1475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5162951488806993}}
{"text": "/*\n [auto_generated]\n boost/numeric/odeint/stepper/runge_kutta4.hpp\n\n [begin_description]\n Implementation of the classical Runge-Kutta stepper with the generic stepper.\n [end_description]\n\n Copyright 2011-2013 Mario Mulansky\n Copyright 2011-2013 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#ifndef BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA4_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA4_HPP_INCLUDED\n\n\n\n\n#include <boost/fusion/container/vector.hpp>\n#include <boost/fusion/container/generation/make_vector.hpp>\n\n#include <boost/numeric/odeint/stepper/explicit_generic_rk.hpp>\n#include <boost/numeric/odeint/algebra/range_algebra.hpp>\n#include <boost/numeric/odeint/algebra/default_operations.hpp>\n#include <boost/numeric/odeint/algebra/algebra_dispatcher.hpp>\n#include <boost/numeric/odeint/algebra/operations_dispatcher.hpp>\n\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint/util/resizer.hpp>\n\n\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\n#ifndef DOXYGEN_SKIP\ntemplate< class Value = double >\nstruct rk4_coefficients_a1 : boost::array< Value , 1 >\n{\n    rk4_coefficients_a1( void )\n    {\n        (*this)[0] = static_cast< Value >( 1 ) / static_cast< Value >( 2 );\n    }\n};\n\ntemplate< class Value = double >\nstruct rk4_coefficients_a2 : boost::array< Value , 2 >\n{\n    rk4_coefficients_a2( void )\n    {\n        (*this)[0] = static_cast<Value>(0);\n        (*this)[1] = static_cast< Value >( 1 ) / static_cast< Value >( 2 );\n    }\n};\n\n\ntemplate< class Value = double >\nstruct rk4_coefficients_a3 : boost::array< Value , 3 >\n{\n    rk4_coefficients_a3( void )\n            {\n        (*this)[0] = static_cast<Value>(0);\n        (*this)[1] = static_cast<Value>(0);\n        (*this)[2] = static_cast<Value>(1);\n            }\n};\n\ntemplate< class Value = double >\nstruct rk4_coefficients_b : boost::array< Value , 4 >\n{\n    rk4_coefficients_b( void )\n    {\n        (*this)[0] = static_cast<Value>(1)/static_cast<Value>(6);\n        (*this)[1] = static_cast<Value>(1)/static_cast<Value>(3);\n        (*this)[2] = static_cast<Value>(1)/static_cast<Value>(3);\n        (*this)[3] = static_cast<Value>(1)/static_cast<Value>(6);\n    }\n};\n\ntemplate< class Value = double >\nstruct rk4_coefficients_c : boost::array< Value , 4 >\n{\n    rk4_coefficients_c( void )\n    {\n        (*this)[0] = static_cast<Value>(0);\n        (*this)[1] = static_cast< Value >( 1 ) / static_cast< Value >( 2 );\n        (*this)[2] = static_cast< Value >( 1 ) / static_cast< Value >( 2 );\n        (*this)[3] = static_cast<Value>(1);\n    }\n};\n#endif\n\n\n\ntemplate<\nclass State ,\nclass Value = double ,\nclass Deriv = State ,\nclass Time = Value ,\nclass Algebra = typename algebra_dispatcher< State >::algebra_type ,\nclass Operations = typename operations_dispatcher< State >::operations_type ,\nclass Resizer = initially_resizer\n>\n#ifndef DOXYGEN_SKIP\nclass runge_kutta4 : public explicit_generic_rk< 4 , 4 , State , Value , Deriv , Time ,\nAlgebra , Operations , Resizer >\n#else\nclass runge_kutta4 : public explicit_generic_rk\n#endif\n{\n\npublic:\n\n#ifndef DOXYGEN_SKIP\n    typedef explicit_generic_rk< 4 , 4 , State , Value , Deriv , Time ,\n            Algebra , Operations , Resizer > stepper_base_type;\n#endif\n    typedef typename stepper_base_type::state_type state_type;\n    typedef typename stepper_base_type::value_type value_type;\n    typedef typename stepper_base_type::deriv_type deriv_type;\n    typedef typename stepper_base_type::time_type time_type;\n    typedef typename stepper_base_type::algebra_type algebra_type;\n    typedef typename stepper_base_type::operations_type operations_type;\n    typedef typename stepper_base_type::resizer_type resizer_type;\n\n    #ifndef DOXYGEN_SKIP\n    typedef typename stepper_base_type::wrapped_state_type wrapped_state_type;\n    typedef typename stepper_base_type::wrapped_deriv_type wrapped_deriv_type;\n    typedef typename stepper_base_type::stepper_type stepper_type;\n    #endif\n\n    runge_kutta4( const algebra_type &algebra = algebra_type() ) : stepper_base_type(\n            boost::fusion::make_vector( rk4_coefficients_a1<Value>() , rk4_coefficients_a2<Value>() , rk4_coefficients_a3<Value>() ) ,\n            rk4_coefficients_b<Value>() , rk4_coefficients_c<Value>() , algebra )\n    { }\n\n};\n\n/**\n * \\class runge_kutta4\n * \\brief The classical Runge-Kutta stepper of fourth order.\n *\n * The Runge-Kutta method of fourth order is one standard method for\n * solving ordinary differential equations and is widely used, see also\n * <a href=\"http://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods\">en.wikipedia.org/wiki/Runge-Kutta_methods</a>\n * The method is  explicit and fulfills the Stepper concept. Step size control\n * or continuous output are not provided.\n * \n * This class derives from explicit_stepper_base and inherits its interface via CRTP (current recurring template pattern).\n * Furthermore, it derivs from explicit_generic_rk which is a generic Runge-Kutta algorithm. For more details see\n * explicit_stepper_base and explicit_generic_rk.\n *\n * \\tparam State The state type.\n * \\tparam Value The value type.\n * \\tparam Deriv The type representing the time derivative of the state.\n * \\tparam Time The time representing the independent variable - the time.\n * \\tparam Algebra The algebra type.\n * \\tparam Operations The operations type.\n * \\tparam Resizer The resizer policy type.\n */\n\n/**\n * \\fn runge_kutta4::runge_kutta4( const algebra_type &algebra = algebra_type() )\n * \\brief Constructs the runge_kutta4 class. This constructor can be used as a default\n * constructor if the algebra has a default constructor.\n * \\param algebra A copy of algebra is made and stored inside explicit_stepper_base.\n */\n\n}\n}\n}\n\n\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA4_HPP_INCLUDED\n", "meta": {"hexsha": "2410774ee1287c60638d600f2799e8829cf03d6d", "size": 5860, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/numeric/odeint/stepper/runge_kutta4.hpp", "max_stars_repo_name": "189569400/ClickHouse", "max_stars_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/numeric/odeint/stepper/runge_kutta4.hpp", "max_issues_repo_name": "189569400/ClickHouse", "max_issues_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/numeric/odeint/stepper/runge_kutta4.hpp", "max_forks_repo_name": "189569400/ClickHouse", "max_forks_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": 32.1978021978, "max_line_length": 134, "alphanum_fraction": 0.7255972696, "num_tokens": 1459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5162951488806993}}
{"text": "#pragma once\n\n#include \"matrix/assembly/velocity_var_form.hpp\"\n\n#include <Eigen/Sparse>\n\n\nnamespace boltzmann {\n\n// ----------------------------------------------------------------------\ntemplate <typename TEST_BASIS, typename TRIAL_BASIS>\nvoid\nmake_mass_matrix(Eigen::SparseMatrix<double>& dst,\n                 const TEST_BASIS& test_basis,\n                 const TRIAL_BASIS& trial_basis,\n                 const double beta = 2)\n{\n  VelocityVarForm<2> velocity_var_form;\n  velocity_var_form.init(test_basis, trial_basis, beta);\n  const auto& s0 = velocity_var_form.get_s0();\n\n  for (auto it = s0.begin(); it != s0.end(); ++it) {\n    int i = it->row;\n    int j = it->col;\n    double val = it->val;\n    dst.insert(i, j) = val;\n  }\n}\n\ntemplate <typename TEST_BASIS, typename TRIAL_BASIS>\nEigen::SparseMatrix<double>\nmake_mass_matrix(const TEST_BASIS& test_basis, const TRIAL_BASIS& trial_basis)\n{\n  assert(test_basis.n_dofs() == trial_basis.n_dofs());\n  int N = test_basis.n_dofs();\n\n  Eigen::SparseMatrix<double> M(N, N);\n  VelocityVarForm<2> velocity_var_form;\n  velocity_var_form.init(test_basis, trial_basis, 2.0);\n  const auto& s0 = velocity_var_form.get_s0();\n\n  for (auto it = s0.begin(); it != s0.end(); ++it) {\n    int i = it->row;\n    int j = it->col;\n    double val = it->val;\n    M.insert(i, j) = val;\n  }\n\n  return M;\n}\n\ntemplate <typename TRIAL_BASIS>\nEigen::VectorXd\nmake_mass_vdiag(const TRIAL_BASIS& basis)\n{\n  int N = basis.n_dofs();\n\n  Eigen::VectorXd out(N);\n  VelocityVarForm<2> velocity_var_form;\n  velocity_var_form.init(basis, basis, 2.0);\n  const auto& s0 = velocity_var_form.get_s0();\n\n  for (auto it = s0.begin(); it != s0.end(); ++it) {\n    int i = it->row;\n    int j = it->col;\n\n    if (i != j) throw std::runtime_error(\"make_mass_vdiag: not diagonal!\");\n    double val = it->val;\n    out[i] = val;\n  }\n\n  return out;\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "ecd90c4eeb43cae2d0ece910279921c7dd95bc1d", "size": 1880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spectral/utility/mass_matrix.hpp", "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/utility/mass_matrix.hpp", "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/utility/mass_matrix.hpp", "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": 24.7368421053, "max_line_length": 78, "alphanum_fraction": 0.6335106383, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.516295147312214}}
{"text": "// Copyright (c) 2018 by University Paris-Est Marne-la-Vallee\r\n// ProductTools.hpp\r\n// This file is part of the Garamon Generator.\r\n// Authors: Stephane Breuils and Vincent Nozick\r\n// Contact: vincent.nozick@u-pem.fr\r\n//\r\n// Licence MIT\r\n// A a copy of the MIT License is given along with this program\r\n\r\n/// \\file ProductTools.hpp\r\n/// \\author Vincent Nozick, Stephane Breuils \r\n/// \\brief Geometric algebra \"naive\" implementation tools dedicated to build the optimized C++ products.\r\n\r\n\r\n#ifndef GARAGEN_PRODUCTTOOLS_HPP\r\n#define GARAGEN_PRODUCTTOOLS_HPP\r\n\r\n#include <vector>\r\n#include <array>\r\n#include <map>\r\n#include <utility>     // pairs\r\n#include <Eigen/Dense> // use the metric which is dense\r\n#include <Eigen/Sparse> // use the transformation matrices which are sparse\r\n#include <iostream>\r\n#if defined(_MSC_BUILD)\r\n\t#ifndef __builtin_popcount\r\n\t\t#define __builtin_popcount __popcnt\r\n\t#endif\r\n#endif // __WINDOWS MSVC compiler__\r\n\r\n\r\n/// In the computation of mv3 = mv1^mv2, this represents a quadruplet containing the indices of mv1,mv2,mv3 and a coefficient in a product between two blades.\r\n/// e.g. suppose that a product is defined by mv3[2] += -3.0*mv1[3]*mv2[4]  then the first quadruplet associated with this product will be 3,4,1,-3.0\r\ntemplate<typename T>\r\nstruct productComponent{\r\n    unsigned int indexOfMv1; // in the example above, indexOfMv1 would be 3\r\n    unsigned int indexOfMv2; // in the example above, indexOfMv2 would be 4\r\n    unsigned int indexOfMv3; // in the example above, indexOfMv2 would be 4\r\n    T coefficient;           // in the example above, coefficient would be -1\r\n};\r\n\r\ntemplate<typename C>\r\nbool compareProductComponents(const C &a, const C &b)\r\n//bool operator < (const productComponent &a, const productComponent &b) const\r\n{\r\n    // first compare on indexOfMv3\r\n    if(a.indexOfMv3 > b.indexOfMv3) return false;\r\n    if(a.indexOfMv3 < b.indexOfMv3) return true;\r\n\r\n    // second compare on indexOfMv1\r\n    if(a.indexOfMv1 > b.indexOfMv1) return false;\r\n    if(a.indexOfMv1 < b.indexOfMv1) return true;\r\n\r\n    // thrid compare on indexOfMv2\r\n    if(a.indexOfMv2 > b.indexOfMv2) return false;\r\n    if(a.indexOfMv2 < b.indexOfMv2) return true;\r\n\r\n    return true;\r\n}\r\n\r\n\r\nclass ProductTools {\r\npublic:\r\n\r\n    /// constructor\r\n    /// \\param vectorSpaceDimension is the dimension of the vector space of the algebra\r\n    ProductTools(const unsigned int vectorSpaceDimension);\r\n\r\n    /// destructor\r\n    ~ProductTools();\r\n\r\n    /// \\brief compute the Hamming weight of the xor index (blade) xorIndexMv (i.e the number of bits=1 in the binary value xorIndexMv)\r\n    /// \\param xorIndexMv is a xorIndex, i.e. a each of his bit refers to a basis blade of the vector space of the algebra\r\n    static unsigned int hammingWeight(const unsigned int xorIndexMv);\r\n\r\n    /// \\brief return whether the outer product between the two blades whose indices are xorIndexMv1 and xorIndexMv2 is a null blade\r\n    /// \\param xorIndexMv1 is a xorIndex, i.e. a each of his bit refers to a basis blade of the vector space of the algebra\r\n    /// \\param xorIndexMv2 is a xorIndex, i.e. a each of his bit refers to a basis blade of the vector space of the algebra\r\n    static bool outerProductExists(const unsigned int xorIndexMv1, const unsigned int xorIndexMv2);\r\n\r\n    /// \\brief return the sign of the outer product between the two blades whose indices are xorIndexMv1 and xorIndexMv2\r\n    /// \\param xorIndexMv1 is a xorIndex, i.e. a each of his bit refers to a basis blade of the vector space of the algebra\r\n    /// \\param xorIndexMv2 is a xorIndex, i.e. a each of his bit refers to a basis blade of the vector space of the algebra\r\n    static int outerProductSign(const unsigned int xorIndexMv1, const unsigned int xorIndexMv2);\r\n\r\n    /// \\brief return whether the inner product exists\r\n    /// \\param xorIndexMv1 is a xorIndex, i.e. a each of his bit refers to a basis blade of the vector space of the algebra\r\n    /// \\param xorIndexMv2 is a xorIndex, i.e. a each of his bit refers to a basis blade of the vector space of the algebra\r\n    static bool innerProductExists(const unsigned int xorIndexMv1, const unsigned int xorIndexMv2);\r\n\r\n\r\n    /// \\brief Compute the coefficient required in the computation of the inner and geometric products of 2 multivectors.\r\n    /// \\param xorIndexMv1 is a xorIndex, i.e. a each of his bit refers to a basis blade of the vector space of the algebr  in the algebra related orthogonal space\r\n    /// \\param xorIndexMv2 is a xorIndex, i.e. a each of his bit refers to a basis blade of the vector space of the algebra in the algebra related orthogonal space\r\n    /// \\param diagonalMetric defines the metric in the algebra related orthogonal space\r\n    static double productCoefficientFromMetric(const unsigned int xorIndexMv1, const unsigned int xorIndexMv2,\r\n                                               const Eigen::VectorXd &diagonalMetric);\r\n\r\n    /// \\brief Compute the position of the product between two XOR indices. Is common for the geometric, outer and inner product\r\n    /// \\param xorIndexMv1 is a xorIndex, i.e. a each of his bit refers to a basis blade of the vector space of the algebra\r\n    /// \\param xorIndexMv2 is a xorIndex, i.e. a each of his bit refers to a basis blade of the vector space of the algebra\r\n    static unsigned int productResultXorIndex(const unsigned int xorIndexMv1, const unsigned int xorIndexMv2);\r\n\r\n    /// \\brief Generate all the components of the product mv1{gradeMv1} ^ mv2{gradeMv2}.\r\n    /// \\param xorIndexMv1 is a xorIndex, i.e. a each of his bit refers to a basis blade of the vector space of the algebr  in the algebra related orthogonal space\r\n    /// \\param xorIndexMv2 is a xorIndex, i.e. a each of his bit refers to a basis blade of the vector space of the algebra in the algebra related orthogonal space\r\n    /// \\return For each component of mv3=mv1^mv2 with grade gradeMv3=gradeMv1+gradeMv2, we return a list of quadruplet (indexMv1,indexMv2,indexMv3,coefficient).\r\n    std::list<productComponent<double>> generateExplicitOuterProductList(const unsigned int gradeMv1, const unsigned int gradeMv2) const;\r\n\r\n\r\n    /// \\brief Generate all the components of the inner product mv1<gradeMv1> . mv2<gradeMv2> in a Euclidean space with diagonal metric. In practice, we compute here the Hestenes inner product.\r\n    /// \\param gradeMv1 the grade of the homogeneous multivector Mv1 to be considered\r\n    /// \\param gradeMv2 the grade of the homogeneous multivector Mv2 to be considered\r\n    /// \\param diagonalMetric defines the metric in the algebra related orthogonal space\r\n    /// \\return for each component of the result mv3=mv1.mv2 with grade gradeMv3=|gradeMv1-gradeMv2|, we return a list of quadruplet (indexMv1,indexMv2,indexMv3,coefficient).\r\n    std::list<productComponent<double>> generateExplicitInnerProductListEuclideanSpace(const unsigned int gradeMv1, \r\n                                                                                                     const unsigned int gradeMv2,\r\n                                                                                                     const Eigen::VectorXd &diagonalMetric) const;\r\n\r\n    /// \\brief Generate all the components of the inner product mv1<gradeMv1> . mv2<gradeMv2>. In practice, we compute here the Hestenes inner product.\r\n    /// \\param gradeMv1 the grade of the homogeneous multivector Mv1 to be considered\r\n    /// \\param gradeMv2 the grade of the homogeneous multivector Mv2 to be considered\r\n    /// \\param transformationMatrixMv1 is the matrix that put a k-vector of grade \"gradeMv1\" to the algebra related orthogonal space\r\n    /// \\param transformationMatrixMv2 is the matrix that put a k-vector of grade \"gradeMv2\" to the algebra related orthogonal space\r\n    /// \\param transformationMatrixMv3 is the matrix that put back a k-vector of grade \"gradeMv3\" from the algebra related orthogonal space to the original space\r\n    /// \\param diagonalMetric defines the metric in the algebra related orthogonal space\r\n    /// \\return for each component of the result mv3=mv1.mv2 with grade gradeMv3=|gradeMv1-gradeMv2|, we return a list of quadruplet (indexMv1,indexMv2,indexMv3,coefficient).\r\n    std::list<productComponent<double>> generateExplicitInnerProductList(const unsigned int gradeMv1,\r\n                                                                         const unsigned int gradeMv2,\r\n                                                                         const Eigen::SparseMatrix<double, 0> &transformationMatrixMv1,\r\n                                                                         const Eigen::SparseMatrix<double, 0> &transformationMatrixMv2,\r\n                                                                         const Eigen::SparseMatrix<double, 0> &transformationMatrixMv3,\r\n                                                                         const Eigen::VectorXd &diagonalMetric) const;\r\n\r\n\r\n\r\n    /// \\brief Generate all the components of the geometric product mv1<gradeMv1> mv2<gradeMv2>.\r\n    /// \\param gradeMv1 the grade of the homogeneous multivector Mv1 to be considered\r\n    /// \\param gradeMv2 the grade of the homogeneous multivector Mv2 to be considered\r\n    /// \\param transformationMatrixMv1 is the matrix that put a k-vector of grade \"gradeMv1\" to the algebra related orthogonal space\r\n    /// \\param transformationMatrixMv2 is the matrix that put a k-vector of grade \"gradeMv2\" to the algebra related orthogonal space\r\n    /// \\param transformationMatrixMv3 is the matrix that put back a k-vector of grade \"gradeMv3\" from the algebra related orthogonal space to the original space\r\n    /// \\param diagonalMetric defines the metric in the algebra related orthogonal space\r\n    /// \\return a vector of products (each cell of the vector contains its associated grade products). For each component of the result mv3=mv1 mv2, we return a list of quadruplet (indexMv1,indexMv2,indexMv3,coefficient).\r\n    std::vector<std::list<productComponent<double>>> generateExplicitGeometricProductListEuclideanSpace(const unsigned int gradeMv1,const unsigned int gradeMv2,\r\n                                                                                          const Eigen::VectorXd& diagonalMetric) const;\r\n\r\n\r\n\r\n    /// \\brief Generate all the components of the geometric product mv1<gradeMv1> mv2<gradeMv2>.\r\n    /// \\param gradeMv1 the grade of the homogeneous multivector Mv1 to be considered\r\n    /// \\param gradeMv2 the grade of the homogeneous multivector Mv2 to be considered\r\n    /// \\param transformationMatrixMv1 is the matrix that put a k-vector of grade \"gradeMv1\" to the algebra related orthogonal space\r\n    /// \\param transformationMatrixMv2 is the matrix that put a k-vector of grade \"gradeMv2\" to the algebra related orthogonal space\r\n    /// \\param transformationMatrixMv3 is the matrix that put back a k-vector of grade \"gradeMv3\" from the algebra related orthogonal space to the original space\r\n    /// \\param diagonalMetric defines the metric in the algebra related orthogonal space\r\n    /// \\return a vector of products (each cell of the vector contains its associated grade products). For each component of the result mv3=mv1 mv2, we return a list of quadruplet (indexMv1,indexMv2,indexMv3,coefficient).\r\n    std::vector<std::list<productComponent<double>>> generateExplicitGeometricProductList(const unsigned int gradeMv1,const unsigned int gradeMv2,\r\n                                                                                          Eigen::SparseMatrix<double, Eigen::ColMajor>& transformationMatrixMv1,\r\n                                                                                          Eigen::SparseMatrix<double, Eigen::ColMajor>& transformationMatrixMv2,\r\n                                                                                          std::vector<Eigen::SparseMatrix<double, Eigen::ColMajor> >& transformationMatricesMv3,\r\n                                                                                          const Eigen::VectorXd& diagonalMetric) const;\r\n\r\n\r\n\r\n    // tool to debug\r\n    void displayGradeToXorIndices() const;\r\n\r\n    /// \\brief getter: return the grade knowing the Xor index\r\n    unsigned int getGrade(unsigned int xorIndex) const;\r\n\r\n    /// \\brief getter: return the homogeneous index knowing the Xor index\r\n    unsigned int getHomogeneousIndex(unsigned int xorIndex) const;\r\n\r\n    /// \\brief getter: return the xor index knowing the grade and the homogeneous index\r\n    unsigned int getXorIndex(unsigned int grade, unsigned int homogeneousIndex) const;\r\n\r\n\r\nprotected:\r\n    const unsigned int dimension;\r\n\r\n    /// order induced by the xor:                 scal, 1, 2, 12, 3, 13, 23, 123\r\n    /// Mapping between\r\n    /// Xor index:                                   0, 1, 2,  3, 4,  5,  6, 7\r\n    /// and grade and position in the sequence:      0, 0, 1,  0, 2,  1,  2, 0\r\n\r\n    // defines the one to one correspondence between a xor index (index in the multivector) and the grade and position in the homogeneous vector\r\n    // grade and position to xor index\r\n    /// xorIndex = gradePositionToXorIndex[grade][pos];\r\n    std::vector<std::vector<unsigned int> > gradePositionToXorIndex;\r\n\r\n    /// array that converts xor index to grade and position\r\n    /// first: grade\r\n    /// second: position\r\n    std::vector<std::pair<unsigned int,unsigned int> > xorIndexToGradeAndPosition; // number of pairs is 2^dimension\r\n};\r\n\r\n/// \\brief generate a scale containing the sign of the norm of the pseudo-inverse\r\ndouble getScaleInversePseudoScalar(const Eigen::MatrixXd &metric);\r\n\r\n#endif //GARAGEN_PRODUCTTOOLS_HPP\r\n", "meta": {"hexsha": "21f15492e83c083f9283e16650f3c643e73474da", "size": 13641, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ProductTools.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/ProductTools.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/ProductTools.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": 67.5297029703, "max_line_length": 222, "alphanum_fraction": 0.6825745913, "num_tokens": 3220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.516295143678776}}
{"text": "#ifndef STATIC_LINK_VW\n#define BOOST_TEST_DYN_LINK\n#endif\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_tools.hpp>\n\n#include \"fast_pow10.h\"\n#include \"test_common.h\"\n\nbool are_same(float a, float b) { return std::abs(a - b) < std::numeric_limits<float>::epsilon(); }\n\nBOOST_AUTO_TEST_CASE(pow10_tests)\n{\n  // In reality most of these tests would all evaluate to the same. The reason is that the epsilon is usually around 1.2e-7\n  const float base = 10;\n  BOOST_CHECK(are_same(VW::fast_pow10(-127), std::pow(base, -127)));\n  BOOST_CHECK(are_same(VW::fast_pow10(-46), std::pow(base, -46)));\n  BOOST_CHECK(are_same(VW::fast_pow10(-45), std::pow(base, -45)));\n  BOOST_CHECK(are_same(VW::fast_pow10(-44), std::pow(base, -44)));\n  BOOST_CHECK(are_same(VW::fast_pow10(-40), std::pow(base, -40)));\n  BOOST_CHECK(are_same(VW::fast_pow10(-38), std::pow(base, -38)));\n  BOOST_CHECK(are_same(VW::fast_pow10(-37), std::pow(base, -37)));\n  BOOST_CHECK(are_same(VW::fast_pow10(-10), std::pow(base, -10)));\n  BOOST_CHECK(are_same(VW::fast_pow10(-5), std::pow(base, -5)));\n  BOOST_CHECK_CLOSE(VW::fast_pow10(0), 1, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(VW::fast_pow10(5), 1e5, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(VW::fast_pow10(10), 1e10, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(VW::fast_pow10(37), 1e37, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(VW::fast_pow10(38), 1e38, FLOAT_TOL);\n  BOOST_CHECK(std::isinf(VW::fast_pow10(39)));\n  BOOST_CHECK(std::isinf(VW::fast_pow10(127)));\n}\n", "meta": {"hexsha": "7e6f0dbef9af98c4c731c5ee44b4429398ae0e89", "size": 1453, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/unit_test/power_test.cc", "max_stars_repo_name": "Gale43/vowpal_wabbit", "max_stars_repo_head_hexsha": "b715b5d8aa98d553062e619548d4b52ae582313b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-23T14:05:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T14:30:51.000Z", "max_issues_repo_path": "test/unit_test/power_test.cc", "max_issues_repo_name": "qingyun-wu/vowpal_wabbit", "max_issues_repo_head_hexsha": "666e815b7fe026ee3d608942501911ecc73e6af7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T08:00:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T13:10:26.000Z", "max_forks_repo_path": "test/unit_test/power_test.cc", "max_forks_repo_name": "qingyun-wu/vowpal_wabbit", "max_forks_repo_head_hexsha": "666e815b7fe026ee3d608942501911ecc73e6af7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-09-30T14:57:47.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-30T14:57:47.000Z", "avg_line_length": 42.7352941176, "max_line_length": 123, "alphanum_fraction": 0.714384033, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5162951384768529}}
{"text": "/*\r\n * phase_chain.cpp\r\n *\r\n * Example of OMP parallelization with odeint\r\n *\r\n * Copyright 2013 Karsten Ahnert\r\n * Copyright 2013 Mario Mulansky\r\n * Copyright 2013 Pascal Germroth\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\r\n#include <iostream>\r\n#include <vector>\r\n#include <boost/random.hpp>\r\n#include <boost/timer/timer.hpp>\r\n//[phase_chain_openmp_header\r\n#include <omp.h>\r\n#include <boost/numeric/odeint.hpp>\r\n#include <boost/numeric/odeint/external/openmp/openmp.hpp>\r\n//]\r\n\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\nusing boost::timer::cpu_timer;\r\nusing boost::math::double_constants::pi;\r\n\r\n//[phase_chain_vector_state\r\ntypedef std::vector< double > state_type;\r\n//]\r\n\r\n//[phase_chain_rhs\r\nstruct phase_chain\r\n{\r\n    phase_chain( double gamma = 0.5 )\r\n    : m_gamma( gamma ) { }\r\n\r\n    void operator()( const state_type &x , state_type &dxdt , double /* t */ ) const\r\n    {\r\n        const size_t N = x.size();\r\n        #pragma omp parallel for schedule(runtime)\r\n        for(size_t i = 1 ; i < N - 1 ; ++i)\r\n        {\r\n            dxdt[i] = coupling_func( x[i+1] - x[i] ) +\r\n                      coupling_func( x[i-1] - x[i] );\r\n        }\r\n        dxdt[0  ] = coupling_func( x[1  ] - x[0  ] );\r\n        dxdt[N-1] = coupling_func( x[N-2] - x[N-1] );\r\n    }\r\n\r\n    double coupling_func( double x ) const\r\n    {\r\n        return sin( x ) - m_gamma * ( 1.0 - cos( x ) );\r\n    }\r\n\r\n    double m_gamma;\r\n};\r\n//]\r\n\r\n\r\nint main( int argc , char **argv )\r\n{\r\n    //[phase_chain_init\r\n    size_t N = 131101;\r\n    state_type x( N );\r\n    boost::random::uniform_real_distribution<double> distribution( 0.0 , 2.0*pi );\r\n    boost::random::mt19937 engine( 0 );\r\n    generate( x.begin() , x.end() , boost::bind( distribution , engine ) );\r\n    //]\r\n\r\n    //[phase_chain_stepper\r\n    typedef runge_kutta4<\r\n                      state_type , double ,\r\n                      state_type , double ,\r\n                      openmp_range_algebra\r\n                    > stepper_type;\r\n    //]\r\n\r\n    //[phase_chain_scheduling\r\n    int chunk_size = N/omp_get_max_threads();\r\n    omp_set_schedule( omp_sched_static , chunk_size );\r\n    //]\r\n\r\n    cpu_timer timer;\r\n    //[phase_chain_integrate\r\n    integrate_n_steps( stepper_type() , phase_chain( 1.2 ) ,\r\n                       x , 0.0 , 0.01 , 100 );\r\n    //]\r\n    double run_time = static_cast<double>(timer.elapsed().wall) * 1.0e-9;\r\n    std::cerr << run_time << \"s\" << std::endl;\r\n    // copy(x.begin(), x.end(), ostream_iterator<double>(cout, \"\\n\"));\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "131dd424f4c748416e874535d8de14c7730b5aeb", "size": 2655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/openmp/phase_chain.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/phase_chain.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/openmp/phase_chain.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.65625, "max_line_length": 85, "alphanum_fraction": 0.5796610169, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639792, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5162759529853821}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Robustness Test\n\n// Copyright (c) 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#define BOOST_GEOMETRY_REPORT_OVERLAY_ERROR\n#define BOOST_GEOMETRY_NO_BOOST_TEST\n\n#include <sstream>\n#include <fstream>\n\n#include <boost/program_options.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/timer.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/multi/geometries/multi_geometries.hpp>\n#include <boost/geometry/extensions/io/svg/svg_mapper.hpp>\n\nstruct settings_type\n{\n    bool svg;\n    bool wkt;\n\n    settings_type()\n        : svg(false)\n        , wkt(false)\n    {}\n};\n\nnamespace bg = boost::geometry;\n\ntemplate <typename Geometry1, typename Geometry2>\nvoid create_svg(std::string const& filename, Geometry1 const& points, Geometry2 const& hull)\n{\n    typedef typename boost::geometry::point_type<Geometry1>::type point_type;\n\n    boost::geometry::model::box<point_type> box;\n    bg::envelope(hull, box);\n    bg::buffer(box, box, 1.0);\n\n    std::ofstream svg(filename.c_str());\n    boost::geometry::svg_mapper<point_type> mapper(svg, 800, 800);\n    mapper.add(box);\n\n    mapper.map(hull, \"opacity:0.8;fill:none;stroke:rgb(255,0,255);stroke-width:4;stroke-dasharray:1,7;stroke-linecap:round\");\n    mapper.map(points, \"fill-opacity:0.5;fill:rgb(0,0,255);\", 5);\n}\n\n\ntemplate <typename MultiPoint, typename Generator>\ninline void make_multi_point(MultiPoint& mp, Generator& generator, int pcount)\n{\n    typedef typename bg::point_type<MultiPoint>::type point_type;\n    typedef typename bg::coordinate_type<MultiPoint>::type coordinate_type;\n\n    for(int i = 0; i < pcount; i++)\n    {\n        coordinate_type x, y;\n        x = generator();\n        y = generator();\n\n        point_type p;\n        bg::set<0>(p, x);\n        bg::set<1>(p, y);\n\n        mp.push_back(p);\n    }\n}\n\ntemplate <typename MultiPoint, typename Polygon>\nbool check_hull(MultiPoint const& mp, Polygon const& poly)\n{\n    for(typename boost::range_iterator<MultiPoint const>::type it = boost::begin(mp);\n        it != boost::end(mp);\n        ++it)\n    {\n        if (! bg::covered_by(*it, poly))\n        {\n            return false;\n        }\n    }\n    return true;\n}\n\n\ntemplate <typename MultiPoint, typename Generator>\nvoid test_random_multi_points(MultiPoint& result, int& index,\n            Generator& generator,\n            int pcount, settings_type const& settings)\n{\n    typedef typename bg::point_type<MultiPoint>::type point_type;\n\n    MultiPoint mp;\n    bg::model::polygon<point_type> hull;\n\n    make_multi_point(mp, generator, pcount);\n    bg::convex_hull(mp, hull);\n    // Check if each point lies in the hull\n    bool correct = check_hull(mp, hull);\n    if (! correct)\n    {\n        std::cout << \"ERROR! \" << std::endl\n            << bg::wkt(mp) << std::endl\n            << bg::wkt(hull) << std::endl\n            << std::endl;\n            ;\n    }\n\n    if (settings.svg || ! correct)\n    {\n        std::ostringstream out;\n        out << \"random_mp_\" << index++ << \"_\" << pcount << \".svg\";\n        create_svg(out.str(), mp, hull);\n    }\n    if (settings.wkt)\n    {\n        std::cout \n            << \"input: \" << bg::wkt(mp) << std::endl\n            << \"output: \" << bg::wkt(hull) << std::endl\n            << std::endl;\n            ;\n    }\n}\n\n\ntemplate <typename T>\nvoid test_all(int seed, int count, int field_size, int pcount, settings_type const& settings)\n{\n    boost::timer t;\n\n    typedef boost::minstd_rand base_generator_type;\n\n    base_generator_type generator(seed);\n\n    boost::uniform_int<> random_coordinate(0, field_size - 1);\n    boost::variate_generator<base_generator_type&, boost::uniform_int<> >\n        coordinate_generator(generator, random_coordinate);\n\n    typedef bg::model::multi_point\n        <\n            bg::model::d2::point_xy<T>\n        > mp;\n\n    int index = 0;\n    for(int i = 0; i < count; i++)\n    {\n        mp p;\n        test_random_multi_points<mp>(p, index, coordinate_generator, pcount, settings);\n    }\n    std::cout\n        << \"points: \" << index\n        << \" type: \" << typeid(T).name()\n        << \" time: \" << t.elapsed()  << std::endl;\n}\n\nint main(int argc, char** argv)\n{\n    try\n    {\n        namespace po = boost::program_options;\n        po::options_description description(\"=== random_multi_points ===\\nAllowed options\");\n\n        std::string type = \"double\";\n        int count = 1;\n        int seed = static_cast<unsigned int>(std::time(0));\n        int pcount = 3;\n        int field_size = 10;\n        settings_type settings;\n\n        description.add_options()\n            (\"help\", \"Help message\")\n            (\"seed\", po::value<int>(&seed), \"Initialization seed for random generator\")\n            (\"count\", po::value<int>(&count)->default_value(1), \"Number of tests\")\n            (\"number\", po::value<int>(&pcount)->default_value(30), \"Number of points\")\n            (\"size\", po::value<int>(&field_size)->default_value(10), \"Size of the field\")\n            (\"type\", po::value<std::string>(&type)->default_value(\"double\"), \"Type (int,float,double)\")\n            (\"wkt\", po::value<bool>(&settings.wkt)->default_value(false), \"Create a WKT of the inputs, for all tests\")\n            (\"svg\", po::value<bool>(&settings.svg)->default_value(false), \"Create a SVG for all tests\")\n        ;\n\n        po::variables_map varmap;\n        po::store(po::parse_command_line(argc, argv, description), varmap);\n        po::notify(varmap);\n\n        if (varmap.count(\"help\"))\n        {\n            std::cout << description << std::endl;\n            return 1;\n        }\n\n        if (type == \"float\")\n        {\n            test_all<float>(seed, count, field_size, pcount, settings);\n        }\n        else if (type == \"double\")\n        {\n            test_all<double>(seed, count, field_size, pcount, settings);\n        }\n        else if (type == \"int\")\n        {\n            test_all<int>(seed, count, field_size, pcount, settings);\n        }\n\n    }\n    catch(std::exception const& e)\n    {\n        std::cout << \"Exception \" << e.what() << std::endl;\n    }\n    catch(...)\n    {\n        std::cout << \"Other exception\" << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "9ce4e406c437ba0180d47ec878a20b1a6269e3f7", "size": 6555, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/robustness/convex_hull/random_multi_points.cpp", "max_stars_repo_name": "AishwaryaDoosa/Boost1.49", "max_stars_repo_head_hexsha": "67bdb3b36d72dec7414a62f3b050162e608ea266", "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/test/robustness/convex_hull/random_multi_points.cpp", "max_issues_repo_name": "AishwaryaDoosa/Boost1.49", "max_issues_repo_head_hexsha": "67bdb3b36d72dec7414a62f3b050162e608ea266", "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/test/robustness/convex_hull/random_multi_points.cpp", "max_forks_repo_name": "AishwaryaDoosa/Boost1.49", "max_forks_repo_head_hexsha": "67bdb3b36d72dec7414a62f3b050162e608ea266", "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.0044247788, "max_line_length": 125, "alphanum_fraction": 0.6079328757, "num_tokens": 1658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7122321903471565, "lm_q1q2_score": 0.5162759445189681}}
{"text": "// Copyright (c) 2019 Bitcoin Association\n// Distributed under the Open BSV software license, see the accompanying file\n// LICENSE.\n\n#include \"big_int.h\"\n\n#include <array>\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace std;\nusing bsv::bint;\n\nconstexpr int int_min{numeric_limits<int>::min()+1};\nconstexpr int int_max{numeric_limits<int>::max()};\n\nconstexpr int64_t int64_min{numeric_limits<int64_t>::min() + 1};\nconstexpr int64_t int64_max{numeric_limits<int64_t>::max()};\n\nconstexpr size_t size_t_min{numeric_limits<size_t>::min() + 1};\nconstexpr size_t size_t_max{numeric_limits<size_t>::max()};\n\nBOOST_AUTO_TEST_SUITE(bint_tests)\n\nBOOST_AUTO_TEST_CASE(default_construction)\n{\n    bint assignable;\n    assignable = bint{1};\n    BOOST_CHECK_EQUAL(bint{1}, assignable);\n    bint destructible;\n}\n\nBOOST_AUTO_TEST_CASE(int_construction)\n{\n    BOOST_CHECK_EQUAL(0, bint{0});\n    BOOST_CHECK_EQUAL(1, bint{1});\n    BOOST_CHECK_EQUAL(-1, bint{-1});\n    BOOST_CHECK_EQUAL(int_max, bint{int_max});\n    BOOST_CHECK_EQUAL(int_min, bint{int_min});\n}\n\nBOOST_AUTO_TEST_CASE(int64_t_construction)\n{\n    BOOST_CHECK_EQUAL(0, bint{0});\n    BOOST_CHECK_EQUAL(1, bint{1});\n    BOOST_CHECK_EQUAL(-1, bint{-1});\n    BOOST_CHECK_EQUAL(int64_max, bint{int64_max});\n    BOOST_CHECK_EQUAL(int64_min, bint{int64_min});\n}\n\nBOOST_AUTO_TEST_CASE(size_t_construction)\n{\n    BOOST_CHECK_EQUAL(size_t_max, bint{size_t_max});\n    BOOST_CHECK_EQUAL(size_t_min, bint{size_t_min});\n}\n\nBOOST_AUTO_TEST_CASE(is_negative_)\n{\n    BOOST_CHECK(!is_negative(bint{0}));\n    BOOST_CHECK(!is_negative(bint{1}));\n    BOOST_CHECK(is_negative(bint{-1}));\n}\n\nBOOST_AUTO_TEST_CASE(equality)\n{\n    array<bint, 3> v = {bint{1}, bint{0}, bint{-1}};\n    for(const auto& n : v)\n    {\n        bint a{n};\n\n        // reflexivity\n        BOOST_CHECK_EQUAL(a, a);\n        BOOST_CHECK(!(a != a));\n\n        // symmetry\n        bint b{n};\n        BOOST_CHECK_EQUAL(a, b);\n        BOOST_CHECK(!(a != b));\n\n        // transitivity\n        bint c{n};\n        BOOST_CHECK_EQUAL(a, b);\n        BOOST_CHECK_EQUAL(b, c);\n        BOOST_CHECK_EQUAL(c, a);\n        BOOST_CHECK(!(a != b));\n        BOOST_CHECK(!(b != c));\n        BOOST_CHECK(!(c != a));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(inequality)\n{\n    bint a{1};\n    bint b{2};\n    BOOST_CHECK(!(a == b));\n    BOOST_CHECK_NE(a, b);\n}\n\nBOOST_AUTO_TEST_CASE(cmp)\n{\n    bint a{1};\n    BOOST_CHECK(!(a < a));\n    BOOST_CHECK_LE(a, a);\n    BOOST_CHECK_GE(a, a);\n    BOOST_CHECK(!(a > a));\n\n    bint b{2};\n    BOOST_CHECK_LT(a, b);\n    BOOST_CHECK_LE(a, b);\n    BOOST_CHECK(!(a > b));\n    BOOST_CHECK(!(a >= b));\n}\n\nBOOST_AUTO_TEST_CASE(move_construct)\n{\n    bint a{1};\n    bint b{std::move(a)};\n    BOOST_CHECK_EQUAL(bint{1}, b);\n}\n\nBOOST_AUTO_TEST_CASE(move_assign)\n{\n    bint a{1};\n    bint b{2};\n    b = std::move(a);\n    BOOST_CHECK_EQUAL(bint{1}, b);\n}\n\nBOOST_AUTO_TEST_CASE(copy_assign)\n{\n    bint a{1};\n    a = a;\n    BOOST_CHECK_EQUAL(a, 1);\n\n    bint b{2};\n    b = a;\n    BOOST_CHECK_EQUAL(a, 1);\n    BOOST_CHECK_EQUAL(b, 1);\n}\n\nBOOST_AUTO_TEST_CASE(swap)\n{\n    bint a{1};\n    bint b{2};\n    std::swap(a, b);\n    BOOST_CHECK_EQUAL(a, 2);\n    BOOST_CHECK_EQUAL(b, 1);\n}\n\nBOOST_AUTO_TEST_CASE(output_streamable)\n{\n    ostringstream oss;\n    oss << bint{};\n    BOOST_CHECK_EQUAL(\"\", oss.str());\n\n    bint a{123};\n    oss << a;\n    BOOST_CHECK_EQUAL(\"123\", oss.str());\n}\n\nBOOST_AUTO_TEST_CASE(add)\n{\n    {\n        bint a(1);\n        bint b(2);\n        bint c = a + b;\n        BOOST_CHECK_EQUAL(c, 3);\n    }\n    {\n        bint a(int64_max);\n        bint b(int64_max);\n        bint c = a + b;\n        BOOST_CHECK_EQUAL(c, bint{\"18446744073709551614\"});\n    }\n}\n\nBOOST_AUTO_TEST_CASE(sub)\n{\n    {\n        bint a(2);\n        bint b(1);\n        bint c = a - b;\n        BOOST_CHECK_EQUAL(c, 1);\n    }\n    {\n        bint a(int64_max);\n        bint b(int64_max);\n        bint c = a - b;\n        BOOST_CHECK_EQUAL(c, 0);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(mult)\n{\n    {\n        bint a(1);\n        bint b(2);\n        bint c = a * b;\n        BOOST_CHECK_EQUAL(c, 2);\n    }\n    {\n        bint a(int64_max);\n        bint b(int64_max);\n        bint c = a * b;\n        BOOST_CHECK_EQUAL(c, bint{\"85070591730234615847396907784232501249\"});\n    }\n}\n\nBOOST_AUTO_TEST_CASE(div)\n{\n    {\n        bint a(6);\n        bint b(2);\n        bint c = a / b;\n        BOOST_CHECK_EQUAL(c, 3);\n    }\n    {\n        bint a(int64_max);\n        bint b(2);\n        bint c = a / b;\n        BOOST_CHECK_EQUAL(c, bint{\"4611686018427387903\"});\n    }\n}\n\nBOOST_AUTO_TEST_CASE(mod)\n{\n    {\n        bint a(7);\n        bint b(2);\n        bint c = a % b;\n        BOOST_CHECK_EQUAL(c, bint{1});\n    }\n    {\n        bint a(int64_max);\n        bint b(101);\n        bint c = a % b;\n        BOOST_CHECK_EQUAL(c, 89);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(negate)\n{\n    const vector<int64_t> test_data{0, 1, -1, int64_max, -int64_max, int64_min};\n    for(const auto n : test_data)\n    {\n        bint bn(n);\n        BOOST_CHECK_EQUAL(bint{-n}, -bn);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(lsb)\n{\n    const bint n{0x1234};\n    BOOST_TEST(0x34 == n.lsb(), n.lsb());\n}\n\nBOOST_AUTO_TEST_CASE(bitwise_and)\n{\n    // clang-format off\n    array<tuple<bint, bint, bint>, 21> v\n    {\n        make_tuple(bint{0}, bint{0}, bint{0}),\n\n        make_tuple(bint{1}, bint{0}, bint{0}),\n        make_tuple(bint{0}, bint{1}, bint{0}),\n        \n        make_tuple(bint{0x1234}, bint{0xff}, bint{0x34}),\n        make_tuple(bint{0x1234}, bint{0xff00}, bint{0x1200}),\n        \n        make_tuple(bint{0xff}, bint{0x1234}, bint{0x34}),\n        make_tuple(bint{0x1234}, bint{0xff00}, bint{0x1200}),\n\n        make_tuple(bint{0x1010}, bint{0x101}, bint{0x0}),\n        make_tuple(bint{0x101}, bint{0x1010}, bint{0x0}),\n        \n        make_tuple(bint{0x8080}, bint{0x8080}, bint{0x8080}),\n\n        make_tuple(bint{int_max}, bint{0x0}, bint{0x0}),\n        make_tuple(bint{0x0}, bint{int_max}, bint{0x0}),\n        \n        make_tuple(bint{int_max}, \n                   bint{int_max}, \n                   bint{int_max}),\n        make_tuple(bint{int_max},\n                   bint{int_max},\n                   bint{int_max}),\n        \n        make_tuple(bint{int_min}, bint{0x0}, bint{0x0}),\n        make_tuple(bint{0x0}, bint{int_min}, bint{0x0}),\n        \n        make_tuple(bint{-1}, bint{0}, bint{0}),\n        make_tuple(bint{0}, bint{-1}, bint{0}),\n        \n        make_tuple(bint{1}, bint{-1}, bint{1}),\n        make_tuple(bint{-1}, bint{1}, bint{1}),\n        \n        make_tuple(bint{-1}, bint{-1}, bint{-1}),\n    };\n    // clang-format on\n\n    for(const auto e : v)\n    {\n        bint lhs{get<0>(e)};\n        bint rhs{get<1>(e)};\n        bint expected{get<2>(e)};\n        lhs &= rhs;\n        BOOST_CHECK_EQUAL(expected, lhs);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(bitwise_or)\n{\n    // clang-format off\n    array<tuple<bint, bint, bint>, 16> v\n    {\n        make_tuple(bint{0}, bint{0}, bint{0}),\n\n        make_tuple(bint{1}, bint{0}, bint{1}),\n        make_tuple(bint{0}, bint{1}, bint{1}),\n        \n        make_tuple(bint{0x1200}, bint{0x34}, bint{0x1234}),\n        make_tuple(bint{0x34}, bint{0x1200}, bint{0x1234}),\n        \n        make_tuple(bint{-1}, bint{0}, bint{-1}),\n        make_tuple(bint{0}, bint{-1}, bint{-1}),\n        \n        make_tuple(bint{1}, bint{-1}, bint{-1}),\n        make_tuple(bint{-1}, bint{1}, bint{-1}),\n        \n        make_tuple(bint{-1}, bint{-1}, bint{1}),\n\n        make_tuple(bint{int_max}, bint{0x0},\n                   bint{int_max}),\n        make_tuple(bint{0x0}, bint{int_max},\n                   bint{int_max}),\n        \n        make_tuple(bint{int_min}, bint{0x0}, \n                   bint{int_min}),\n        make_tuple(bint{0x0}, bint{int_min}, \n                   bint{int_min}),\n\n        make_tuple(bint{0x1010}, bint{0x101}, bint{0x1111}),\n        make_tuple(bint{0x101}, bint{0x1010}, bint{0x1111}),\n    };\n    // clang-format on\n\n    for(const auto e : v)\n    {\n        bint lhs{get<0>(e)};\n        bint rhs{get<1>(e)};\n        bint expected{get<2>(e)};\n        lhs |= rhs;\n        BOOST_CHECK_EQUAL(expected, lhs);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(shift_left)\n{\n    // clang-format off\n    array<tuple<bint, int, bint>, 5> v\n    {\n        make_tuple(bint{0x1}, 0, bint{0x1}),\n        make_tuple(bint{0x1}, 1, bint{0x2}),\n        make_tuple(bint{0x1}, 2, bint{0x4}),\n        make_tuple(bint{0x1}, 3, bint{0x8}),\n        make_tuple(bint{0x0f}, 4, bint{0xf0}),\n    };\n    // clang-format on\n\n    for(const auto& e : v)\n    {\n        bint lhs{get<0>(e)};\n        int n{get<1>(e)};\n        lhs <<= n;\n        bint expected{get<2>(e)};\n        BOOST_CHECK_EQUAL(lhs, expected);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(shift_right)\n{\n    // clang-format off\n    array<tuple<bint, int, bint>, 6> v\n    {\n        make_tuple(bint{0x1}, 0, bint{0x1}),\n        make_tuple(bint{0x1}, 1, bint{0x0}),\n        make_tuple(bint{0x2}, 1, bint{0x1}),\n        make_tuple(bint{0x4}, 2, bint{0x1}),\n        make_tuple(bint{0x8}, 3, bint{0x1}),\n        make_tuple(bint{0xf0}, 4, bint{0xf}),\n    };\n    // clang-format on\n\n    for(const auto& e : v)\n    {\n        bint lhs{get<0>(e)};\n        int n{get<1>(e)};\n        lhs >>= n;\n        bint expected{get<2>(e)};\n        BOOST_CHECK_EQUAL(lhs, expected);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(absolute_value)\n{\n    using namespace bsv;\n\n    const bint a{int64_max};\n    const bint aa{a * a};\n\n    BOOST_TEST(aa == abs(aa));\n    BOOST_TEST(bint{\"85070591730234615847396907784232501249\"} == abs(-aa));\n}\n\nBOOST_AUTO_TEST_CASE(to_string)\n{\n    BOOST_TEST(\"\" == bsv::to_string(bint{}));\n\n    constexpr int64_t min64{int64_min};\n    constexpr int64_t max64{int64_max};\n    vector<int64_t> test_data{0, 1, -1, min64, max64};\n    for(const auto n : test_data)\n    {\n        BOOST_TEST(std::to_string(n) == bsv::to_string(bint{n}));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(to_size_t_limited)\n{\n    BOOST_TEST(\"\" == bsv::to_string(bint{}));\n\n    constexpr size_t size_t_min{ std::numeric_limits<size_t>::min() };\n    constexpr size_t size_t_max{ static_cast<size_t>(std::numeric_limits<int32_t>::max()) };\n\n    vector<size_t> test_data{ size_t_min, 1, size_t_max };\n    for(const auto n : test_data)\n    {\n        BOOST_TEST(n == bsv::to_size_t_limited(bint{n}));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "136a10eb9bd2ccd0f70f5ec9526a3bf2f0f011ed", "size": 10215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/big_int_tests.cpp", "max_stars_repo_name": "bxlkm1/yulecoin", "max_stars_repo_head_hexsha": "3605faf2ff2e3c7bd381414613fc5c0234ad2936", "max_stars_repo_licenses": ["OML"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-08-02T02:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T15:51:48.000Z", "max_issues_repo_path": "src/test/big_int_tests.cpp", "max_issues_repo_name": "bxlkm1/yulecoin", "max_issues_repo_head_hexsha": "3605faf2ff2e3c7bd381414613fc5c0234ad2936", "max_issues_repo_licenses": ["OML"], "max_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/big_int_tests.cpp", "max_forks_repo_name": "bxlkm1/yulecoin", "max_forks_repo_head_hexsha": "3605faf2ff2e3c7bd381414613fc5c0234ad2936", "max_forks_repo_licenses": ["OML"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T02:50:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T03:21:38.000Z", "avg_line_length": 23.0067567568, "max_line_length": 92, "alphanum_fraction": 0.5717082721, "num_tokens": 3246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5162759356636492}}
{"text": "/******************************************************************************\n\n  This source file is part of the Avogadro project.\n\n  Copyright 2012 Kitware, Inc.\n\n  This source code is released under the New BSD License, (the \"License\").\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n\n******************************************************************************/\n\n#include <gtest/gtest.h>\n\n#include <avogadro/rendering/camera.h>\n\n#include <Eigen/Geometry>\n\n#include <iostream>\n\nusing Avogadro::Rendering::Camera;\nusing Avogadro::Vector3f;\n\nvoid setUpOrthographic(Camera &camera)\n{\n  camera.calculateOrthographic(0, 10, 0, 10, 0, 1);\n}\n\nTEST(CameraTest, perspective)\n{\n  Camera camera;\n  camera.calculatePerspective(40, 1.5, 1, 10);\n\n  // Load in a known value for the result of this matrix.\n  Eigen::Matrix4f expected;\n  expected << 1.83165f, 0.0f, 0.0f, 0.0f,\n              0.0f, 2.74748f, 0.0f, 0.0f,\n              0.0f, 0.0f, -1.22222f, -2.22222f,\n              0.0f, 0.0f, -1.0f, 0.0f;\n  EXPECT_TRUE(camera.projection().matrix().isApprox(expected));\n  // If it is incorrect then print out the result.\n  if (!camera.projection().matrix().isApprox(expected)) {\n    std::cout << \"Error: No match\\n\" << camera.projection().matrix()\n              << \"\\nexpected\\n\" << expected << std::endl;\n  }\n}\n\nTEST(CameraTest, orthographic)\n{\n  Camera camera;\n  camera.calculateOrthographic(0, 10, 0, 10, 0, 1);\n\n  // Load in a known value for the result of this matrix.\n  Eigen::Matrix4f expected;\n  expected << 0.2f, 0.0f, 0.0f,-1.0f,\n              0.0f, 0.2f, 0.0f,-1.0f,\n              0.0f, 0.0f,-2.0f,-1.0f,\n              0.0f, 0.0f, 0.0f, 1.0f;\n  EXPECT_TRUE(camera.projection().matrix().isApprox(expected));\n  // If it is incorrect then print out the result.\n  if (!camera.projection().matrix().isApprox(expected)) {\n    std::cout << \"Error: No match\\n\" << camera.projection().matrix()\n              << \"\\nexpected\\n\" << expected << std::endl;\n  }\n}\n\nTEST(CameraTest, projectOrthographic)\n{\n  Camera camera;\n  camera.calculateOrthographic(0, 10, 0, 10, 0, 1);\n  camera.setViewport(100, 100);\n\n  Vector3f position = camera.project(Vector3f(1.0, 2.0, 0.0));\n  Vector3f expected(10.0, 20.0, 0.0);\n  EXPECT_TRUE(position.isApprox(expected));\n  if (!position.isApprox(expected)) {\n    std::cout << \"Error: No match\\n\" << position << std::endl;\n  }\n}\n\nTEST(CameraTest, projectPerspective)\n{\n  Camera camera;\n  camera.calculatePerspective(40, 1.5, 1, 10);\n  camera.preTranslate(Vector3f(0, 0, -10));\n  camera.setViewport(100, 100);\n\n  Vector3f position = camera.project(Vector3f(1.0, 2.0, 0.0));\n  Vector3f expected(59.1583f, 77.4748f, 1.0f);\n  EXPECT_TRUE(position.isApprox(expected));\n  if (!position.isApprox(expected)) {\n    std::cout << \"Error: No match\\n\" << position << std::endl;\n  }\n}\n\nTEST(CameraTest, unProjectOrthographic)\n{\n  Camera camera;\n  camera.calculateOrthographic(0, 10, 0, 10, 0, 1);\n  camera.setViewport(100, 100);\n\n  Vector3f position = camera.unProject(Vector3f(10, 25, 0));\n  Vector3f expected(1.0, 7.5, 0.0);\n  EXPECT_TRUE(position.isApprox(expected));\n  if (!position.isApprox(expected)) {\n    std::cout << \"Error: No match\\n\" << position << std::endl;\n  }\n}\n\nTEST(CameraTest, unProjectPerspective)\n{\n  Camera camera;\n  camera.calculatePerspective(40, 1.5, 1, 10);\n  camera.preTranslate(Vector3f(0, 0, -10));\n  camera.setViewport(100, 100);\n\n  Vector3f position = camera.unProject(Vector3f(10, 25, 0));\n  Vector3f expected(-0.436764f, 0.181985f, 9.0f);\n  EXPECT_TRUE(position.isApprox(expected));\n  if (!position.isApprox(expected)) {\n    std::cout << \"Error: No match\\n\" << position << std::endl;\n  }\n}\n", "meta": {"hexsha": "6377408b040821a4bc15aa1d40927cebe616847d", "size": 3895, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/rendering/cameratest.cpp", "max_stars_repo_name": "AlbertDeFusco/avogadrolibs", "max_stars_repo_head_hexsha": "572aad6d16295c91da684d180b6b2705070549c1", "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/rendering/cameratest.cpp", "max_issues_repo_name": "AlbertDeFusco/avogadrolibs", "max_issues_repo_head_hexsha": "572aad6d16295c91da684d180b6b2705070549c1", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/rendering/cameratest.cpp", "max_forks_repo_name": "AlbertDeFusco/avogadrolibs", "max_forks_repo_head_hexsha": "572aad6d16295c91da684d180b6b2705070549c1", "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.4296875, "max_line_length": 79, "alphanum_fraction": 0.6397946085, "num_tokens": 1192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5162708798002702}}
{"text": "#include \"FeaturesComputer.hpp\"\n\n#include <itkMeanImageFilter.h>\n#include <itkDivideImageFilter.h>\n#include <itkComposeImageFilter.h>\n\n#include <boost/program_options.hpp>\n\n#include <iostream>\n#include <string>\n\nnamespace po = boost::program_options;\n\ntypedef typename itk::Image< typename OutputImageType::PixelType::ValueType, 3 > FloatingPointImageType;\ntypedef typename itk::DivideImageFilter< FloatingPointImageType, FloatingPointImageType, FloatingPointImageType > RescaleImageFilterType;\ntypedef typename itk::ComposeImageFilter< FloatingPointImageType, OutputImageType > ComposeVectorImageFilterType;\n\nclass MeanValueComputer : public FeaturesComputer\n{\nprivate:\n\tboost::program_options::options_description options;\n\tunsigned int radius;\n\tbool normalization;\n\npublic:\n\tMeanValueComputer():\n\t\toptions(\"MeanValueComputer\")\n\t{\n\t\toptions.add_options()\n\t\t\t(\"radius,r\",\n\t\t\t po::value< unsigned int >(&this->radius)->default_value(2),\n\t\t\t \"Radius of the mean filter\")\n\t\t\t(\"normalize,n\",\n\t\t\t \"Enables normalization (default: disabled)\")\n\t\t\t;\n\t}\n\n\tvirtual void print_usage(std::ostream &os)\n\t{\n\t\tos << this->options;\n\t}\n\n\tvirtual OutputImageType::Pointer compute( InputImageType::Pointer input_image, std::vector< std::string > params )\n\t{\n\t\tpo::variables_map vm;\n\n\t\tpo::store(po::command_line_parser(params).options(this->options).run(), vm);\n\t\tvm.notify();\n\n\t\tthis->normalization = vm.count(\"normalize\") > 0;\n\n\t\ttypedef itk::MeanImageFilter< InputImageType, FloatingPointImageType >  MeanFilterType;\n\n\t\tMeanFilterType::Pointer meanFilter = MeanFilterType::New();\n\n\t\tmeanFilter->SetInput(input_image);\n\n\t\tInputImageType::SizeType indexRadius;\n\t\tindexRadius.Fill(this->radius);\n\t\tmeanFilter->SetRadius( indexRadius );\n\n\t\tmeanFilter->Update();\n\n\t\tFloatingPointImageType::Pointer fp_output_image = meanFilter->GetOutput();\n\n\t\tif(this->normalization) {\n\t\t\tRescaleImageFilterType::Pointer rescaler = RescaleImageFilterType::New();\n\t\t\trescaler->SetInput(meanFilter->GetOutput());\n\t\t\trescaler->SetConstant(255.0);\n\t\t\trescaler->Update();\n\n\t\t\tfp_output_image = rescaler->GetOutput();\n\t\t}\n\n\t\tComposeVectorImageFilterType::Pointer vectorComposer = ComposeVectorImageFilterType::New();\n\t\tvectorComposer->SetInput(0, fp_output_image);\n\n\t\tvectorComposer->Update();\n\n\t\treturn vectorComposer->GetOutput();\n\t}\n};\n\nextern \"C\" FeaturesComputer* create() {\n\treturn new MeanValueComputer;\n}\n\n", "meta": {"hexsha": "7de732457f69c58be8fe1505cffc2cb83602e1ac", "size": 2372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MeanValueComputer.cpp", "max_stars_repo_name": "Sigill/ImageFeaturesComputer", "max_stars_repo_head_hexsha": "3e1058d7e97413d0a3e928bdc802535e85a73a59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MeanValueComputer.cpp", "max_issues_repo_name": "Sigill/ImageFeaturesComputer", "max_issues_repo_head_hexsha": "3e1058d7e97413d0a3e928bdc802535e85a73a59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MeanValueComputer.cpp", "max_forks_repo_name": "Sigill/ImageFeaturesComputer", "max_forks_repo_head_hexsha": "3e1058d7e97413d0a3e928bdc802535e85a73a59", "max_forks_repo_licenses": ["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.9545454545, "max_line_length": 137, "alphanum_fraction": 0.7592748735, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5162708798002702}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 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_CONSTANT_TANPIO_8_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_TANPIO_8_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    Constant \\f$\\tan3\\frac\\pi{8} = \\sqrt2 - 1\\f$.\n\n    @par Semantic:\n\n    For type T:\n\n    @code\n    T r = Tanpio_8<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = sqrt(2.0)-1.0;\n    @endcode\n\n    @return a value of type T\n\n**/\n  template<typename T> T Tanpio_8();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Constant \\f$\\tan3\\frac\\pi{8} = \\sqrt2 - 1\\f$.\n\n      Generate the  constant tanpio_8.\n\n      @return The Tanpio_8 constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::tanpio_8_> tanpio_8 = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/tanpio_8.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": "eda9f466d3195edf4c0e12982d0a379199fd7a3a", "size": 1415, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/tanpio_8.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/tanpio_8.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/tanpio_8.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": 21.7692307692, "max_line_length": 100, "alphanum_fraction": 0.5809187279, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.5162708766318705}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_CONSTANTS_SQRT_2OPI_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_SQRT_2OPI_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\n\nnamespace nt2\n{\n  namespace tag\n  {\n   /*!\n     @brief Sqrt_2opi generic tag\n\n     Represents the Sqrt_2opi constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    BOOST_SIMD_CONSTANT_REGISTER( Sqrt_2opi, double\n                                , 0, 0x3f4c422a\n                                , 0x3fe9884533d43651ll\n                                )\n  }\n  namespace ext\n  {\n   template<class Site>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Sqrt_2opi, Site> dispatching_Sqrt_2opi(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)\n   {\n     return generic_dispatcher<tag::Sqrt_2opi, Site>();\n   }\n   template<class... Args>\n   struct impl_Sqrt_2opi;\n  }\n  /*!\n    Constant  \\f$\\frac{\\sqrt2}{\\pi}\\f$.\n\n    @par Semantic:\n\n    For type T0:\n\n    @code\n    T0 r = Sqrt_2opi<T0>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T0 r = sqrt(Two<T0>())/Pi<T0>();\n    @endcode\n\n    @return a value of type T0\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Sqrt_2opi, Sqrt_2opi);\n}\n\n#endif\n\n", "meta": {"hexsha": "d8aebcabe1166c8ea255b405b13437064a3ecaf6", "size": 1765, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/sqrt_2opi.hpp", "max_stars_repo_name": "feelpp/nt2", "max_stars_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/sqrt_2opi.hpp", "max_issues_repo_name": "feelpp/nt2", "max_issues_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "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": "modules/core/trigonometric/include/nt2/trigonometric/constants/sqrt_2opi.hpp", "max_forks_repo_name": "feelpp/nt2", "max_forks_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 26.3432835821, "max_line_length": 139, "alphanum_fraction": 0.5694050992, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5162708727794058}}
{"text": "#include <geometry.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\ntypedef tiny::MathTypes<float> MT;\ntypedef MT::quaternion_type    Q;\ntypedef MT::vector3_type       V;\ntypedef MT::real_type          T;\ntypedef MT::value_traits       VT;\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(overlap_tri_tri_test)\n{\n  // B inside A\n  {\n    V const A0   = V::make(0.0, 0.0, 0.0);\n    V const A1   = V::make(1.0, 0.0, 0.0);\n    V const A2   = V::make(0.0, 1.0, 0.0);\n\n    V const B0   = V::make(0.1, 0.1, 0.1);\n    V const B1   = V::make(0.9, 0.0, 0.0);\n    V const B2   = V::make(0.0, 0.9, 0.0);\n\n    geometry::Triangle<V> triA = geometry::make_triangle<V>(A0, A1, A2);\n    geometry::Triangle<V> triB = geometry::make_triangle<V>(B0, B1, B2);\n\n    bool const test1 = geometry::overlap_triangle_triangle(triA, triB);\n    bool const test2 = geometry::overlap_triangle_triangle(triB, triA);\n\n    BOOST_CHECK(test1);\n    BOOST_CHECK(test2);\n  }\n\n  unsigned int permutation[6][3] = {\n    {0, 1, 2},\n    {0, 2, 1},\n    {1, 2, 0},\n    {1, 0, 2},\n    {2, 0, 1},\n    {2, 1, 0}\n  };\n\n  // Touching edge-edge cases\n  {\n    std::vector<V> A(3u);\n    std::vector<V> B(3u);\n\n    A[0]   = V::make(0.0, 0.0, 0.0);\n    A[1]   = V::make(1.0, 0.0, 0.0);\n    A[2]   = V::make(0.0, 1.0, 0.0);\n\n    B[0]   = V::make( 0.5, 0.0,-0.5);\n    B[1]   = V::make( 0.5, 0.0, 0.5);\n    B[2]   = V::make( 0.5,-1.0, 0.0);\n\n    for (unsigned int i=0u;i<6u;++i)\n    {\n      for (unsigned int j=0u;j<6u;++j)\n      {\n        geometry::Triangle<V> triA = geometry::make_triangle<V>(\n                                                                        A[permutation[i][0]]\n                                                                      , A[permutation[i][1]]\n                                                                      , A[permutation[i][2]]\n                                                                      );\n        geometry::Triangle<V> triB = geometry::make_triangle<V>(\n                                                                        B[permutation[j][0]]\n                                                                      , B[permutation[j][1]]\n                                                                      , B[permutation[j][2]]\n                                                                      );\n\n        bool const test1 = geometry::overlap_triangle_triangle(triA, triB);\n        bool const test2 = geometry::overlap_triangle_triangle(triB, triA);\n\n        BOOST_CHECK(test1);\n        BOOST_CHECK(test2);\n\n      }\n    }\n\n\n  }\n\n  // Separating edge-edge cases\n  {\n    std::vector<V> A(3u);\n    std::vector<V> B(3u);\n\n    A[0]   = V::make(0.0, 0.0, 0.0);\n    A[1]   = V::make(1.0, 0.0, 0.0);\n    A[2]   = V::make(0.0, 1.0, 0.0);\n\n    B[0]   = V::make( 0.5, -0.01,-0.5);\n    B[1]   = V::make( 0.5, -0.01, 0.5);\n    B[2]   = V::make( 0.5, -1.01, 0.0);\n\n    for (unsigned int i=0u;i<6u;++i)\n    {\n      for (unsigned int j=0u;j<6u;++j)\n      {\n        geometry::Triangle<V> triA = geometry::make_triangle<V>(\n                                                                   A[permutation[i][0]]\n                                                                   , A[permutation[i][1]]\n                                                                   , A[permutation[i][2]]\n                                                                   );\n        geometry::Triangle<V> triB = geometry::make_triangle<V>(\n                                                                   B[permutation[j][0]]\n                                                                   , B[permutation[j][1]]\n                                                                   , B[permutation[j][2]]\n                                                                   );\n\n        bool const test1 = geometry::overlap_triangle_triangle(triA, triB);\n        bool const test2 = geometry::overlap_triangle_triangle(triB, triA);\n\n        BOOST_CHECK(!test1);\n        BOOST_CHECK(!test2);\n\n      }\n    }\n    \n    \n  }\n\n  // Separated by face cases\n  {\n    std::vector<V> A(3u);\n    std::vector<V> B(3u);\n\n    A[0]   = V::make(0.0, 0.0, 0.0);\n    A[1]   = V::make(1.0, 0.0, 0.0);\n    A[2]   = V::make(0.0, 1.0, 0.0);\n\n    B[0]   = V::make( 1.1,  0.0, 0.1);\n    B[1]   = V::make( 1.1,  0.0, 1.1);\n    B[2]   = V::make( 1.1, -1.0, 0.6);\n\n    for (unsigned int i=0u;i<6u;++i)\n    {\n      for (unsigned int j=0u;j<6u;++j)\n      {\n        geometry::Triangle<V> triA = geometry::make_triangle<V>(\n                                                                   A[permutation[i][0]]\n                                                                   , A[permutation[i][1]]\n                                                                   , A[permutation[i][2]]\n                                                                   );\n        geometry::Triangle<V> triB = geometry::make_triangle<V>(\n                                                                   B[permutation[j][0]]\n                                                                   , B[permutation[j][1]]\n                                                                   , B[permutation[j][2]]\n                                                                   );\n\n        bool const test1 = geometry::overlap_triangle_triangle(triA, triB);\n        bool const test2 = geometry::overlap_triangle_triangle(triB, triA);\n\n        BOOST_CHECK(!test1);\n        BOOST_CHECK(!test2);\n\n      }\n    }\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "f57b5789880974d8f7e7e2f04d64c253721ff368", "size": 5659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_overlap_triangle_triangle/geometry_overlap_triangle_triangle.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_overlap_triangle_triangle/geometry_overlap_triangle_triangle.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_overlap_triangle_triangle/geometry_overlap_triangle_triangle.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0935672515, "max_line_length": 92, "alphanum_fraction": 0.3974200389, "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5162155514112153}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n/// \\file\n/// Declares function RootFinder::newton_raphson\n\n#pragma once\n\n#include <boost/math/tools/roots.hpp>\n#include <functional>\n#include <limits>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"ErrorHandling/Exceptions.hpp\"\n#include \"Utilities/MakeString.hpp\"\n\nnamespace RootFinder {\n/*!\n * \\ingroup NumericalAlgorithmsGroup\n * \\brief Finds the root of the function `f` with the Newton-Raphson method.\n *\n * `f` is a unary invokable that takes a `double` which is the current value at\n * which to evaluate `f`. `f` must return a `std::pair<double, double>` where\n * the first element is the function value and the second element is the\n * derivative of the function.  An example is below.\n *\n * \\snippet Test_NewtonRaphson.cpp double_newton_raphson_root_find\n *\n * See the [Boost](http://www.boost.org/) documentation for more details.\n *\n * \\requires Function `f` is invokable with a `double`\n * \\note The parameter `digits` specifies the precision of the result in its\n * desired number of base-10 digits.\n *\n * \\throws `convergence_error` if the requested precision is not met after\n * `max_iterations` iterations.\n */\ntemplate <typename Function>\ndouble newton_raphson(const Function& f, const double initial_guess,\n                      const double lower_bound, const double upper_bound,\n                      const size_t digits, const size_t max_iterations = 50) {\n  ASSERT(digits < std::numeric_limits<double>::digits10,\n         \"The desired accuracy of \" << digits\n                                    << \" base-10 digits must be smaller than \"\n                                       \"the machine numeric limit of \"\n                                    << std::numeric_limits<double>::digits10\n                                    << \" base-10 digits.\");\n\n  boost::uintmax_t max_iters = max_iterations;\n  // clang-tidy: internal boost warning, can't fix it.\n  const auto result = boost::math::tools::newton_raphson_iterate(  // NOLINT\n      f, initial_guess, lower_bound, upper_bound,\n      std::round(std::log2(std::pow(10, digits))), max_iters);\n  if (max_iters >= max_iterations) {\n    throw convergence_error(MakeString{}\n                            << \"newton_raphson reached max iterations of \"\n                            << max_iterations\n                            << \" without converging. Best result is: \" << result\n                            << \" with residual \" << f(result).first);\n  }\n  return result;\n}\n\n/*!\n * \\ingroup NumericalAlgorithmsGroup\n * \\brief Finds the root of the function `f` with the Newton-Raphson method on\n * each element in a `DataVector`.\n *\n * `f` is a binary invokable that takes a `double` as its first argument and a\n * `size_t` as its second. The `double` is the current value at which to\n * evaluate `f`, and the `size_t` is the current index into the `DataVector`s.\n *  `f` must return a `std::pair<double, double>` where the first element is\n * the function value and the second element is the derivative of the function.\n * Below is an example of how to root find different functions by indexing into\n * a lambda-captured `DataVector` using the `size_t` passed to `f`.\n *\n * \\snippet Test_NewtonRaphson.cpp datavector_newton_raphson_root_find\n *\n * See the [Boost](http://www.boost.org/) documentation for more details.\n *\n * \\requires Function `f` be callable with a `double` and a `size_t`\n * \\note The parameter `digits` specifies the precision of the result in its\n * desired number of base-10 digits.\n *\n * \\throws `convergence_error` if, for any index, the requested precision is not\n * met after `max_iterations` iterations.\n */\ntemplate <typename Function>\nDataVector newton_raphson(const Function& f, const DataVector& initial_guess,\n                          const DataVector& lower_bound,\n                          const DataVector& upper_bound, const size_t digits,\n                          const size_t max_iterations = 50) {\n  ASSERT(digits < std::numeric_limits<double>::digits10,\n         \"The desired accuracy of \" << digits\n                                    << \" base-10 digits must be smaller than \"\n                                       \"the machine numeric limit of \"\n                                    << std::numeric_limits<double>::digits10\n                                    << \" base-10 digits.\");\n  const auto digits_binary = std::round(std::log2(std::pow(10, digits)));\n\n  DataVector result_vector{lower_bound.size()};\n  for (size_t i = 0; i < result_vector.size(); ++i) {\n    boost::uintmax_t max_iters = max_iterations;\n    // clang-tidy: internal boost warning, can't fix it.\n    result_vector[i] = boost::math::tools::newton_raphson_iterate(  // NOLINT\n        [&f, i ](double x) noexcept { return f(x, i); }, initial_guess[i],\n        lower_bound[i], upper_bound[i], digits_binary, max_iters);\n    if (max_iters >= max_iterations) {\n      throw convergence_error(MakeString{}\n                              << \"newton_raphson reached max iterations of \"\n                              << max_iterations\n                              << \" without converging. Best result is: \"\n                              << result_vector[i] << \" with residual \"\n                              << f(result_vector[i], i).first);\n    }\n  }\n  return result_vector;\n}\n\n}  // namespace RootFinder\n", "meta": {"hexsha": "172f9213451cc2602ed6d4d05507cd4ab027776e", "size": 5348, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/NumericalAlgorithms/RootFinding/NewtonRaphson.hpp", "max_stars_repo_name": "tomwlodarczyk/spectre", "max_stars_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NumericalAlgorithms/RootFinding/NewtonRaphson.hpp", "max_issues_repo_name": "tomwlodarczyk/spectre", "max_issues_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NumericalAlgorithms/RootFinding/NewtonRaphson.hpp", "max_forks_repo_name": "tomwlodarczyk/spectre", "max_forks_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_forks_repo_licenses": ["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.1983471074, "max_line_length": 80, "alphanum_fraction": 0.630329095, "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.5162155456593519}}
{"text": "#include <Eigen/CholmodSupport>\n#include <iomanip>\n#include <iostream>\n#include \"../../include/Optimization/LineSearch.h\"\n#include \"../../include/Optimization/LBFGSSolver.h\"\n#include \"../../include/timer.h\"\n\nvoid OptSolver::lbfgsSolver(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)\n{\n\tstd::cout << \"LBFGS-Solver\" << std::endl;\n\tconst size_t m = 10;\n\tconst size_t DIM = x0.rows();\n\tEigen::MatrixXd sVector = Eigen::MatrixXd::Zero(DIM, m);\n\tEigen::MatrixXd yVector = Eigen::MatrixXd::Zero(DIM, m);\n\tEigen::VectorXd alpha = Eigen::VectorXd::Zero(m);\n\tEigen::VectorXd grad(DIM), q(DIM), grad_old(DIM), s(DIM), y(DIM);\n\tdouble f = objFunc(x0, &grad, NULL, false);\n\tEigen::VectorXd x_old = x0;\n\n\tif (displayInfo)\n\t{\n\t\tstd::cout << \"start energy: \" << f << std::endl;\n\t\tstd::cout << \"start gradient norm: \" << grad.template lpNorm<Eigen::Infinity>() << std::endl;\n\t}\n\n\n\tsize_t iter = 0, globIter = 0;\n\tdouble H0k = 1;\n\tdo {\n\t\tconst double relativeEpsilon = static_cast<double>(0.0001) * std::max<double>(static_cast<double>(1.0), x0.norm());\n\n\t\tif (grad.norm() < gradTol)\n\t\t{\n\t\t\tstd::cout << \"gradient is too small, ||g||_2: \" << grad.norm() << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\t//Algorithm 7.4 (L-BFGS two-loop recursion)\n\t\tq = grad;\n\t\tconst int k = std::min<double>(m, iter);\n\n\t\t// for i = k \u2212 1, k \u2212 2, . . . , k \u2212 m\u00a7\n\t\tfor (int i = k - 1; i >= 0; i--) {\n\t\t\t// alpha_i <- rho_i*s_i^T*q\n\t\t\tconst double rho = 1.0 / static_cast<Eigen::VectorXd>(sVector.col(i))\n\t\t\t\t.dot(static_cast<Eigen::VectorXd>(yVector.col(i)));\n\t\t\talpha(i) = rho * static_cast<Eigen::VectorXd>(sVector.col(i)).dot(q);\n\t\t\t// q <- q - alpha_i*y_i\n\t\t\tq = q - alpha(i) * yVector.col(i);\n\t\t}\n\n\t\t// r <- H_k^0*q\n\t\tq = H0k * q;\n\t\t//for i k \u2212 m, k \u2212 m + 1, . . . , k \u2212 1\n\t\tfor (int i = 0; i < k; i++) {\n\t\t\t// beta <- rho_i * y_i^T * r\n\t\t\tconst double rho = 1.0 / static_cast<Eigen::VectorXd>(sVector.col(i))\n\t\t\t\t.dot(static_cast<Eigen::VectorXd>(yVector.col(i)));\n\t\t\tconst double beta = rho * static_cast<Eigen::VectorXd>(yVector.col(i)).dot(q);\n\t\t\t// r <- r + s_i * ( alpha_i - beta)\n\t\t\tq = q + sVector.col(i) * (alpha(i) - beta);\n\t\t}\n\t\t// stop with result \"H_k*f_f'=q\"\n\t\tdouble alpha_init = findMaxStep(x0, -q);\n\t\tdouble rate = LineSearch::backtrackingArmijo(x0, grad, -q, objFunc, alpha_init);\n\n\n\t\t// update guess  \n\t\tx0 = x0 - rate * q;\n\n\t\tgrad_old = grad;\n\t\tdouble fold = f;\n\t\tf = objFunc(x0, &grad, NULL, false);\n\n\t\ts = x0 - x_old;\n\t\ty = grad - grad_old;\n\n\t\t// update the history\n\t\tif (iter < m) {\n\t\t\tsVector.col(iter) = s;\n\t\t\tyVector.col(iter) = y;\n\t\t}\n\t\telse {\n\n\t\t\tsVector.leftCols(m - 1) = sVector.rightCols(m - 1).eval();\n\t\t\tsVector.rightCols(1) = s;\n\t\t\tyVector.leftCols(m - 1) = yVector.rightCols(m - 1).eval();\n\t\t\tyVector.rightCols(1) = y;\n\t\t}\n\t\t// update the scaling factor\n\t\tH0k = y.dot(s) / static_cast<double>(y.dot(y));\n\n\t\tx_old = x0;\n\t\tif (displayInfo)\n\t\t{\n\t\t\tstd::cout << std::endl << \"iter: \" << globIter << \", linesearch rate: \" << rate << std::endl;\n\t\t\tstd::cout << std::setprecision(10) << \"fold = \" << fold << \", f = \" << f << \", ||grad|| \" << grad.norm() << \", delta x: \" << rate * q.norm() << \", delta_f: \" << fold - f << 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 * q, 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\t\t}\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\n\t\tif (rate * q.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\n\t\tif (fold - f < 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\t\n\t\titer++;\n\t\tglobIter++;\n\t} while (globIter < numIter);\n\n}", "meta": {"hexsha": "548d8afd2ee271114d22a9dd3100b6cc28ea4498", "size": 4361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Optimization/LBFGSSolver.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/LBFGSSolver.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/LBFGSSolver.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": 32.3037037037, "max_line_length": 388, "alphanum_fraction": 0.5945883972, "num_tokens": 1465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5162155345063847}}
{"text": "#define BOOST_MATH_DOMAIN_ERROR_POLICY ignore_error\n#include <boost/math/distributions/fisher_f.hpp>\n#include \"util.h\"\n\n// 0/-1/1 coding, full rank, drop last level\nvoid design1(const std::vector<int> &g, std::vector< std::vector<double> > &x)\n{\n    int n = g.size();\n    int m = g.empty() ? 0 : *std::max_element(g.begin(), g.end());\n\n    x.assign(m, std::vector<double>(n, 0.0));\n\n    for (int i = 0; i < n; ++i) {\n        int k = g[i];\n        if (k != m)\n            x[k][i] = 1.0;\n        else\n            for (int j = 0; j < m; ++j)\n                x[j][i] = -1.0;\n    }\n}\n\n// 0/1 coding, full rank, drop last level\nvoid design2(const std::vector<int> &g, std::vector< std::vector<double> > &x)\n{\n    int n = g.size();\n    int m = g.empty() ? 0 : *std::max_element(g.begin(), g.end());\n\n    x.assign(m, std::vector<double>(n, 0.0));\n\n    for (int i = 0; i < n; ++i)\n        if (g[i] != m)\n            x[g[i]][i] = 1.0;\n}\n\n// 0/1 coding, overdetermined\nvoid design3(const std::vector<int> &g, std::vector< std::vector<double> > &x)\n{\n    int n = g.size();\n    int m = g.empty() ? 0 : *std::max_element(g.begin(), g.end());\n\n    x.assign(m + 1, std::vector<double>(n, 0.0));\n\n    for (int i = 0; i < n; ++i)\n        x[g[i]][i] = 1.0;\n}\n\ndouble fpval(double x, double df1, double df2)\n{\n    boost::math::fisher_f f(df1, df2);\n    return boost::math::cdf(boost::math::complement(f, x));\n}\n", "meta": {"hexsha": "90396f498644d9d66d0931bf9c444df4379f2c14", "size": 1391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util.cpp", "max_stars_repo_name": "njau-sri/assoc", "max_stars_repo_head_hexsha": "72ef2d41cbbf95eb175b464add33d2061a128b33", "max_stars_repo_licenses": ["MIT"], "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.cpp", "max_issues_repo_name": "njau-sri/assoc", "max_issues_repo_head_hexsha": "72ef2d41cbbf95eb175b464add33d2061a128b33", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "njau-sri/assoc", "max_forks_repo_head_hexsha": "72ef2d41cbbf95eb175b464add33d2061a128b33", "max_forks_repo_licenses": ["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.2452830189, "max_line_length": 78, "alphanum_fraction": 0.5305535586, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5161485305689247}}
{"text": "#include <gtest/gtest.h>\n\n#include <boost/math/special_functions/prime.hpp>\n\n#include \"BoostBasedPrimesCalculator.hpp\"\n#include \"First10000Primes.hpp\"\n\nusing namespace testing;\n\nstruct BoostBasedPrimesCalculatorTests : Test {\n  primes::BoostBasedPrimesCalculator sut;\n  unsigned maxIndex = 10000;\n};\n\nTEST_F(BoostBasedPrimesCalculatorTests,\n       WhenRequestedPrimeWithPrimeIndexEqToZero_ShouldThrowInvalidArgument) {\n  EXPECT_THROW(sut.getPrime(0), std::invalid_argument);\n}\n\nTEST_F(\n    BoostBasedPrimesCalculatorTests,\n    WhenRequestedPrimeWithPrimeIndexGraterThenLimit_ShouldThrowInvalidArgument) {\n  unsigned oneAboveMax = maxIndex + 1;\n  EXPECT_THROW(sut.getPrime(oneAboveMax), std::invalid_argument);\n}\n\nTEST_F(BoostBasedPrimesCalculatorTests, shouldReturnNthPrimeNumber) {\n  auto sampleTestDataSize = first_10000_primes.size();\n  for (auto indexFromZero = 0u, index = 1u; indexFromZero < sampleTestDataSize;\n       indexFromZero++, index++) {\n    EXPECT_EQ(sut.getPrime(index), first_10000_primes[indexFromZero]);\n  }\n}\n", "meta": {"hexsha": "ddbfd85658ba05f2e97050b6759f3e17bb931787", "size": 1030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libs/primes/tests/BoostBasedPrimesCalculatorTests.cpp", "max_stars_repo_name": "paweldac/cmake-template", "max_stars_repo_head_hexsha": "fa7e812b217c264b05d87e81ae619b8293b512be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libs/primes/tests/BoostBasedPrimesCalculatorTests.cpp", "max_issues_repo_name": "paweldac/cmake-template", "max_issues_repo_head_hexsha": "fa7e812b217c264b05d87e81ae619b8293b512be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libs/primes/tests/BoostBasedPrimesCalculatorTests.cpp", "max_forks_repo_name": "paweldac/cmake-template", "max_forks_repo_head_hexsha": "fa7e812b217c264b05d87e81ae619b8293b512be", "max_forks_repo_licenses": ["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.2941176471, "max_line_length": 81, "alphanum_fraction": 0.7951456311, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5161485227833185}}
{"text": "#include \"dynet/nodes.h\"\n#include \"dynet/dynet.h\"\n#include \"dynet/training.h\"\n#include \"dynet/gpu-ops.h\"\n#include \"dynet/expr.h\"\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace dynet;\n\n// This is a sample class which implements the xor model from xor.cc\n// Everything in this class is just as you would do the usual except for\n// parts with provided comments.\nclass XORModel {\npublic:\n  unsigned hidden_size;\n\n  Expression W, b, V, a;\n  Parameter pW, pb, pV, pa;\n\n  // It is important to have a null default constructor for the class, as\n  // we would first need to read the class object from the file, followed by\n  // the dynet model which has saved parameters.\n  XORModel() {}\n\n  XORModel(unsigned hidden_len, Model& m) {\n    hidden_size = hidden_len;\n    InitParams(m);\n  }\n\n  void InitParams(Model& m) {\n    pW = m.add_parameters({hidden_size, 2});\n    pb = m.add_parameters({hidden_size});\n    pV = m.add_parameters({1, hidden_size});\n    pa = m.add_parameters({1});\n  }\n\n  void NewGraph(ComputationGraph& cg) {\n    W = parameter(cg, pW);\n    b = parameter(cg, pb);\n    V = parameter(cg, pV);\n    a = parameter(cg, pa);\n  }\n\n  float Train(const vector<dynet::real>& input, dynet::real gold_output, SimpleSGDTrainer& sgd) {\n    ComputationGraph cg;\n    NewGraph(cg);\n\n    Expression x = dynet::input(cg, {(unsigned int)input.size()}, &input);\n    Expression y = dynet::input(cg, &gold_output);\n\n    Expression h = tanh(W*x + b);\n    Expression y_pred = V*h + a;\n    Expression loss = squared_distance(y_pred, y);\n\n    float return_loss = as_scalar(cg.forward(loss));\n    cg.backward(loss);\n    sgd.update(1.0);\n    return return_loss;\n  }\n\n  float Decode(vector<dynet::real>& input) {\n    ComputationGraph cg;\n    NewGraph(cg);\n\n    Expression x = dynet::input(cg, {(unsigned int)input.size()}, &input);\n    Expression h = tanh(W*x + b);\n    Expression y_pred = V*h + a;\n    return as_scalar(cg.forward(y_pred));\n  }\n\n  // This function should save all those variables in the archive, which\n  // determine the size of other members of the class, here: hidden_size\n  friend class boost::serialization::access;\n  template<class Archive> void serialize(Archive& ar, const unsigned int) {\n\n    // This can either save or read the value of hidden_size from ar,\n    // depending on whether its the output or input archive.\n    ar & hidden_size;\n\n    // We may save class data, such as the hidden size\n    // but we must be sure to save all Parameter objects\n    // that are members of this class.\n    ar & pW;\n    ar & pV;\n    ar & pa;\n    ar & pb;\n  }\n};\n\nvoid WriteToFile(string& filename, XORModel& model, Model& dynet_model) {\n  ofstream outfile(filename);\n  if (!outfile.is_open()) {\n    cerr << \"File opening failed\" << endl;\n    exit(1);\n  }\n\n  // Write out the DYNET model and the XOR model.\n  // It's important to write the DYNET model first.\n  // Since the XOR model uses the DYNET model,\n  // saving in the opposite order will generate a\n  // boost archive \"Pointer Conflict\" exception.\n  boost::archive::text_oarchive oa(outfile);\n  oa & dynet_model;  // Write down the dynet::Model object.\n  oa & model;  // Write down your class object.\n  outfile.close();\n}\n\nvoid ReadFromFile(string& filename, XORModel& model, Model& dynet_model) {\n  ifstream infile(filename);\n  if (!infile.is_open()) {\n    cerr << \"File opening failed\" << endl;\n    exit(1);\n  }\n\n  boost::archive::text_iarchive ia(infile);\n  ia & dynet_model;  // Read the dynet::Model\n  ia & model;  // Read your class object\n\n  infile.close();\n}\n\n\nint main(int argc, char** argv) {\n  dynet::initialize(argc, argv);\n\n  const unsigned HIDDEN = 8;\n  const unsigned ITERATIONS = 20;\n  Model m;\n  SimpleSGDTrainer sgd(m);\n  XORModel model(HIDDEN, m);\n\n  vector<dynet::real> x_values(2);  // set x_values to change the inputs\n  dynet::real y_value;  // set y_value to change the target output\n\n  // Train the model\n  for (unsigned iter = 0; iter < ITERATIONS; ++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 : -1;\n      x_values[1] = x2 ? 1 : -1;\n      y_value = (x1 != x2) ? 1 : -1;\n      loss += model.Train(x_values, y_value, sgd);\n    }\n    loss /= 4;\n    cerr << \"E = \" << loss << endl;\n  }\n\n  string outfile = \"out.txt\";\n  cerr << \"Written model to File: \" << outfile << endl;\n  WriteToFile(outfile, model, m);  // Writing objects to file\n\n  // New objects in which the written archive will be read\n  Model read_dynet_model;\n  XORModel read_model;\n\n  cerr << \"Reading model from File: \" << outfile << endl;\n  ReadFromFile(outfile, read_model, read_dynet_model);  // Reading from file\n  cerr << \"Output for the input: \" << x_values[0] << \" \" << x_values[1] << endl;\n  cerr << read_model.Decode(x_values);  // Checking output for sanity\n}\n\n", "meta": {"hexsha": "a3d784d9cf2bba7215770bfee84e00858b99aec3", "size": 4930, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/cpp/read-write/train_read-write.cc", "max_stars_repo_name": "MalcolmSun/dynet", "max_stars_repo_head_hexsha": "9b2df1e74dafe13072af0c2d4ce7424539d29ac9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-10T17:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-10T17:40:09.000Z", "max_issues_repo_path": "examples/cpp/read-write/train_read-write.cc", "max_issues_repo_name": "MalcolmSun/dynet", "max_issues_repo_head_hexsha": "9b2df1e74dafe13072af0c2d4ce7424539d29ac9", "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/cpp/read-write/train_read-write.cc", "max_forks_repo_name": "MalcolmSun/dynet", "max_forks_repo_head_hexsha": "9b2df1e74dafe13072af0c2d4ce7424539d29ac9", "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.1715976331, "max_line_length": 97, "alphanum_fraction": 0.6574036511, "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5161485216169419}}
{"text": "#include \"conex/supernodal_solver.h\"\n#include \"conex/block_triangular_operations.h\"\n#include \"conex/debug_macros.h\"\n\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\nnamespace conex {\n\nstd::vector<int> ResidualSize(std::vector<Clique>& path) {\n  std::vector<int> y;\n  for (size_t j = 0; j < path.size() - 1; j++) {\n    std::vector<int> temp;\n    IntersectionOfSorted(path.at(j), path.at(j + 1), &temp);\n    y.push_back(path.at(j).size() - temp.size());\n  }\n  y.push_back(path.back().size());\n  return y;\n}\n\nvoid RunningIntersectionClosure(std::vector<Clique>* path) {\n  if (path->size() < 2) {\n    return;\n  }\n  int n = path->size();\n  for (int i = 0; i < n - 2; i++) {\n    for (int j = n - 1; j > i + 1; j--) {\n      std::vector<int> temp;\n      IntersectionOfSorted(path->at(i), path->at(j), &temp);\n      if (temp.size() == 0) {\n        continue;\n      }\n      for (int k = j - 1; k > i; k--) {\n        path->at(k) = UnionOfSorted(path->at(k), temp);\n      }\n    }\n  }\n}\n\nSparseTriangularMatrix MakeSparseTriangularMatrix(\n    int N, const std::vector<Clique>& path_) {\n  auto path = path_;\n  Sort(&path);\n  RunningIntersectionClosure(&path);\n  auto supernode_size = ResidualSize(path);\n  return SparseTriangularMatrix(N, path, supernode_size);\n}\n\nSparseTriangularMatrix GetFillInPattern(\n    int N, const std::vector<Clique>& cliques_input) {\n  auto mat = MakeSparseTriangularMatrix(N, cliques_input);\n\n  for (int j = static_cast<int>(mat.path.size()) - 1; j >= 0; j--) {\n    // Initialize columns of super nodes.\n    mat.supernodes.at(j).setConstant(1);\n    mat.separator.at(j).setConstant(1);\n\n    // Update other columns: the (seperator, seperator) components.\n    int index = 0;\n    auto s_s = mat.workspace_.seperator_diagonal.at(j);\n    int n = mat.path.at(j).size();\n    for (int i = mat.supernode_size.at(j); i < n; i++) {\n      for (int k = i; k < n; k++) {\n        *s_s.at(index++) += 1;\n      }\n    }\n  }\n  return mat;\n}\n\nusing Eigen::MatrixXd;\nusing T = TriangularMatrixOperations;\nusing B = BlockTriangularOperations;\nusing std::vector;\n\nint GetMax(const vector<Clique>& cliques) {\n  int max = cliques.at(0).at(0);\n  for (const auto& c : cliques) {\n    for (const auto ci : c) {\n      if (ci > max) {\n        max = ci;\n      }\n    }\n  }\n  return max;\n}\n\nMatrixXd GetMatrix(int N, const vector<Clique>& c) {\n  MatrixXd M(N, N);\n  M.setZero();\n  for (unsigned int k = 0; k < c.size(); k++) {\n    int i = 0;\n    for (auto ci : c.at(k)) {\n      int j = 0;\n      for (auto cj : c.at(k)) {\n        M(ci, cj) += 1;\n        j++;\n      }\n      i++;\n    }\n  }\n  return M;\n}\n\nMatrixXd GetMatrix(int N, const vector<Clique>& c, double val) {\n  MatrixXd M(N, N);\n  M.setZero();\n  for (unsigned int k = 0; k < c.size(); k++) {\n    int i = 0;\n    for (auto ci : c.at(k)) {\n      int j = 0;\n      for (auto cj : c.at(k)) {\n        M(ci, cj) = val;\n        j++;\n      }\n      i++;\n    }\n  }\n  return M;\n}\n\nbool DoPatternTest(const vector<Clique>& cliques) {\n  int N = GetMax(cliques) + 1;\n  MatrixXd error =\n      GetMatrix(N, cliques) - T::ToDense(GetFillInPattern(N, cliques));\n  error = error.triangularView<Eigen::Lower>();\n  return error.norm() == 0;\n}\n\nGTEST_TEST(Basic, Basic) {\n  vector<Clique> cliques1{{0, 1, 5}, {1, 2, 5}, {3, 4, 5}};\n\n  EXPECT_TRUE(DoPatternTest(cliques1));\n\n  vector<Clique> cliques2{{0, 1, 2}};\n  EXPECT_TRUE(DoPatternTest(cliques2));\n\n  EXPECT_TRUE(DoPatternTest({{0, 1, 2, 4}, {3, 4}, {5, 6, 7}}));\n}\n\nvector<int> RandomTuple(int max, int size) {\n  vector<int> y(size);\n  for (int i = 0; i < size; i++) {\n    y.at(i) = rand() % max;\n  }\n  return y;\n}\n\nGTEST_TEST(GetPattern, Basic) {\n  vector<Clique> cliques{{0, 1, 2, 5}, {1, 4, 2, 5}, {3, 4, 5}};\n}\n\nGTEST_TEST(LowerTri, Constant) {\n  using T = TriangularMatrixOperations;\n  vector<Clique> cliques{{0, 1, 5}, {1, 2, 5}, {3, 4, 5}};\n\n  auto mat = MakeSparseTriangularMatrix(GetMax(cliques) + 1, cliques);\n  T::SetConstant(&mat, -1);\n  auto y = T::ToDense(mat);\n  auto yref = GetMatrix(GetMax(cliques) + 1, cliques, -1);\n  MatrixXd error = y - yref;\n  error = error.triangularView<Eigen::Lower>();\n  EXPECT_TRUE(error.norm() == 0);\n}\n\nvoid DoCholeskyTest(const vector<Clique>& cliques) {\n  auto mat = GetFillInPattern(GetMax(cliques) + 1, cliques);\n  for (auto& sn : mat.supernodes) {\n    sn.diagonal().array() += 100;\n  }\n\n  Eigen::MatrixXd x = T::ToDense(mat);\n  Eigen::LLT<MatrixXd> llt(x);\n  MatrixXd L = llt.matrixL();\n  EXPECT_TRUE(llt.info() == Eigen::Success);\n\n  T::CholeskyInPlace(&mat);\n  MatrixXd error = T::ToDense(mat) - L;\n  error = error.triangularView<Eigen::Lower>();\n  EXPECT_NEAR(error.norm(), 0, 1e-12);\n}\n\nGTEST_TEST(LowerTri, Cholesky) {\n  DoCholeskyTest({{0, 1, 2}, {2}});\n\n  DoCholeskyTest({{0, 1, 2, 4}, {3, 4}, {5, 6, 7}});\n  DoCholeskyTest({{0, 1, 5}, {1, 2, 5}, {3, 4, 5}});\n\n  DoCholeskyTest({{0, 1, 2}, {1, 2, 3}, {3, 4, 2}});\n\n  DoCholeskyTest({{0, 1}, {2, 4}, {3, 4}, {5, 6, 7}, {7, 8, 9, 10}});\n}\n\nvoid DoInverseTest(const vector<Clique>& cliques) {\n  auto mat = GetFillInPattern(GetMax(cliques) + 1, cliques);\n  for (auto& sn : mat.supernodes) {\n    sn.diagonal().array() += 10;\n  }\n\n  Eigen::MatrixXd L = T::ToDense(mat).triangularView<Eigen::Lower>();\n  Eigen::VectorXd b;\n  b.setLinSpaced(L.rows(), -1, 1);\n  auto y = T::ApplyInverse(&mat, b);\n  EXPECT_NEAR((L * y - b).norm(), 0, 1e-12);\n}\n\nGTEST_TEST(LowerTri, InverseTest) {\n  DoInverseTest({{0, 1, 2, 3}, {3, 4, 5}});\n  DoInverseTest({{0, 1, 2, 3}});\n  DoInverseTest({{0, 1, 2, 3}, {3, 4}, {4, 5, 6}});\n}\n\nvoid DoInverseOfTransposeTest(const vector<Clique>& cliques) {\n  auto mat = GetFillInPattern(GetMax(cliques) + 1, cliques);\n  for (auto& sn : mat.supernodes) {\n    sn.diagonal().array() += 10;\n  }\n\n  Eigen::MatrixXd L = T::ToDense(mat).triangularView<Eigen::Lower>();\n  Eigen::VectorXd b;\n  b.setLinSpaced(L.rows(), -1, 1);\n  auto y = T::ApplyInverseOfTranspose(&mat, b);\n  EXPECT_NEAR((L.transpose() * y - b).norm(), 0, 1e-12);\n}\n\nGTEST_TEST(LowerTri, InverseOfTranspose) {\n  DoInverseOfTransposeTest({{0, 1, 2, 5}, {3, 4, 5}});\n  DoInverseOfTransposeTest({{0, 1, 2, 5}, {3, 4, 5}, {5, 6}});\n  DoInverseOfTransposeTest({{0, 1, 2, 3}});\n}\n\ntypedef struct Foo {\n  double* supernode_block;\n  double* separator_supernode_block;\n  int num_supernodes;\n  int num_separators;\n  double** separator_block;\n  int seperator_block_stride = -1;\n} Foo;\n\nint Set(int initial_value, Foo* data) {\n  int cnt = initial_value;\n  int num_n = data->num_supernodes;\n  int num_s = data->num_separators;\n  double* n = data->supernode_block;\n  for (int j = 0; j < num_n; j++) {\n    for (int i = j; i < num_n; i++) {\n      n[i + j * num_n] = cnt++;\n    }\n  }\n\n  double* s_n = data->separator_supernode_block;\n  for (int j = 0; j < num_s; j++) {\n    for (int i = 0; i < num_n; i++) {\n      s_n[i + j * num_n] = cnt++;\n    }\n  }\n\n  int index = 0;\n  for (int j = 0; j < num_s; j++) {\n    for (int i = j; i < num_s; i++) {\n      *data->separator_block[index++] = cnt++;\n    }\n  }\n  return cnt;\n}\n\nGTEST_TEST(SupernodalSolver, TestFullSolver) {\n  vector<Clique> cliques{{0, 1, 2, 4, 5}, {3, 4}, {5}, {6, 7, 8}};\n  auto mat = GetFillInPattern(GetMax(cliques) + 1, cliques);\n  for (auto& sn : mat.supernodes) {\n    sn.diagonal().array() += 10;\n  }\n  int val = 0;\n  for (size_t i = 0; i < cliques.size(); i++) {\n    auto SS = mat.workspace_.seperator_diagonal.at(i);\n    Foo data;\n    data.supernode_block = mat.supernodes.at(i).data();\n    data.separator_supernode_block = mat.separator.at(i).data();\n    data.separator_block = SS.data();\n    data.num_supernodes = mat.supernodes.at(i).cols();\n    data.num_separators = mat.separator.at(i).cols();\n    val = Set(val, &data);\n  }\n}\n\n}  // namespace conex\n", "meta": {"hexsha": "40473d1907d852b8b0e883aa9f73cd4faebdbd4d", "size": 7651, "ext": "cc", "lang": "C++", "max_stars_repo_path": "conex/test/supernodal_solver_test.cc", "max_stars_repo_name": "frankpermenter/conex", "max_stars_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T20:41:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T20:41:20.000Z", "max_issues_repo_path": "conex/test/supernodal_solver_test.cc", "max_issues_repo_name": "frankpermenter/conex", "max_issues_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conex/test/supernodal_solver_test.cc", "max_forks_repo_name": "frankpermenter/conex", "max_forks_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_forks_repo_licenses": ["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.5659722222, "max_line_length": 71, "alphanum_fraction": 0.5952163116, "num_tokens": 2670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5161485183073273}}
{"text": "/* Boost example/findroot_demo.cpp\n * find zero points of some function by dichotomy\n *\n * Copyright 2000 Jens Maurer\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 * The idea and the 2D function are based on RVInterval,\n * which contains the following copyright notice:\n\n        This file is copyrighted 1996 by Ronald Van Iwaarden.\n\n        Permission is hereby granted, without written agreement and\n        without license or royalty fees, to use, copy, modify, and\n        distribute this software and its documentation for any\n        purpose, subject to the following conditions:\n        \n        The above license notice and this permission notice shall\n        appear in all copies or substantial portions of this software.\n        \n        The name \"RVInterval\" cannot be used for any modified form of\n        this software that does not originate from the authors.\n        Nevertheless, the name \"RVInterval\" may and should be used to\n        designate the optimization software implemented and described\n        in this package, even if embedded in any other system, as long\n        as any portion of this code remains.\n        \n        The authors specifically disclaim any warranties, including,\n        but not limited to, the implied warranties of merchantability\n        and fitness for a particular purpose.  The software provided\n        hereunder is on an \"as is\" basis, and the authors have no\n        obligation to provide maintenance, support, updates,\n        enhancements, or modifications.  In no event shall the authors\n        be liable to any party for direct, indirect, special,\n        incidental, or consequential damages arising out of the use of\n        this software and its documentation.      \n*/\n\n#include <boost/numeric/interval.hpp>    // must be first for <limits> workaround\n#include <boost/numeric/interval/io.hpp> \n#include <list>\n#include <deque>\n#include <vector>\n#include <fstream>\n#include <iostream>\n\n\ntemplate<class T>\nstruct test_func2d\n{\n  T operator()(T x, T y) const\n  {\n    return sin(x)*cos(y) - exp(x*y)/45.0 * (pow(x+y, 2)+100.0) - \n      cos(sin(y))*y/4.0;\n  }\n};\n\ntemplate <class T>\nstruct test_func1d\n{\n  T operator()(T x) const\n  {\n    return sin(x)/(x*x+1.0);\n  }\n};\n\ntemplate<class T>\nstruct test_func1d_2\n{\n  T operator()(T x) const\n  {\n    using std::sqrt;\n    return sqrt(x*x-1.0);\n  }\n};\n\ntemplate<class Function, class I>\nvoid find_zeros(std::ostream & os, Function f, I searchrange)\n{\n  std::list<I> l, done;\n  l.push_back(searchrange);\n  while(!l.empty()) {\n    I range = l.front();\n    l.pop_front();\n    I val = f(range);\n    if (zero_in(val)) {\n      if(width(range) < 1e-6) {\n        os << range << '\\n';\n        continue;\n      }\n      // there's still a solution hidden somewhere\n      std::pair<I,I> p = bisect(range);\n      l.push_back(p.first);\n      l.push_back(p.second);\n    }\n  }\n}\n\ntemplate<class T>\nstd::ostream &operator<<(std::ostream &os, const std::pair<T, T> &x) {\n  os << \"(\" << x.first << \", \" << x.second << \")\";\n  return os;\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\nstatic const double epsilon = 5e-3;\n\ntemplate<class Function, class I>\nvoid find_zeros(std::ostream & os, Function f, I rx, I ry)\n{\n  typedef std::pair<I, I> rectangle;\n  typedef std::deque<rectangle> container;\n  container l, done;\n  // l.reserve(50);\n  l.push_back(std::make_pair(rx, ry));\n  for(int i = 1; !l.empty(); ++i) {\n    rectangle rect = l.front();\n    l.pop_front();\n    I val = f(rect.first, rect.second);\n    if (zero_in(val)) {\n      if(width(rect.first) < epsilon && width(rect.second) < epsilon) {\n        os << median(rect.first) << \" \" << median(rect.second) << \" \"\n           << lower(rect.first) << \" \" << upper(rect.first) << \" \"\n           << lower(rect.second) << \" \" << upper(rect.second) \n           << '\\n';\n      } else {\n        if(width(rect.first) > width(rect.second)) {\n          std::pair<I,I> p = bisect(rect.first);\n          l.push_back(std::make_pair(p.first, rect.second));\n          l.push_back(std::make_pair(p.second, rect.second));\n        } else {\n          std::pair<I,I> p = bisect(rect.second);\n          l.push_back(std::make_pair(rect.first, p.first));\n          l.push_back(std::make_pair(rect.first, p.second));\n        }\n      }\n    }\n    if(i % 10000 == 0)\n      std::cerr << \"\\rIteration \" << i << \", l.size() = \" << l.size();\n  }\n  std::cerr << '\\n';\n}\n\nint main()\n{\n  using namespace boost;\n  using namespace numeric;\n  using namespace interval_lib;\n\n  typedef interval<double,\n                   policies<save_state<rounded_transc_opp<double> >,\n                            checking_base<double> > > I;\n\n  std::cout << \"Zero points of sin(x)/(x*x+1)\\n\";\n  find_zeros(std::cout, test_func1d<I>(), I(-11, 10));\n  std::cout << \"Zero points of sqrt(x*x-1)\\n\";\n  find_zeros(std::cout, test_func1d_2<I>(), I(-5, 6));\n  std::cout << \"Zero points of Van Iwaarden's 2D function\\n\";\n  std::ofstream f(\"func2d.data\");\n  find_zeros(f, test_func2d<I>(), I(-20, 20), I(-20, 20));\n  std::cout << \"Use gnuplot, command 'plot \\\"func2d.data\\\" with dots'   to plot\\n\";\n}\n", "meta": {"hexsha": "f5330a70b3227f4267ca29f9023b0d33e3cbd4e5", "size": 5413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/interval/examples/findroot_demo.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/interval/examples/findroot_demo.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/interval/examples/findroot_demo.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": 31.4709302326, "max_line_length": 83, "alphanum_fraction": 0.6177720303, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5161485177241394}}
{"text": "// SPDX-License-Identifier: Apache-2.0\n// \n// Copyright 2015 Conrad Sanderson (http://conradsanderson.id.au)\n// Copyright 2015 National ICT Australia (NICTA)\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// 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 <armadillo>\n#include \"catch.hpp\"\n\nusing namespace arma;\n\n\nTEST_CASE(\"fn_as_scalar_1\")\n  {\n  mat A(1,1); A.fill(2.0);\n  mat B(2,2); B.fill(2.0);\n  \n  REQUIRE( as_scalar(A) == Approx(2.0) );\n  \n  REQUIRE( as_scalar(2+A) == Approx(4.0) );\n  \n  REQUIRE( as_scalar(B(span(0,0), span(0,0))) == Approx(2.0) );\n  \n  REQUIRE_THROWS( as_scalar(B) );\n  }\n\n\n\nTEST_CASE(\"fn_as_scalar_2\")\n  {\n  rowvec r = linspace<rowvec>(1,5,6);\n  colvec q = linspace<colvec>(1,5,6);\n  mat    X = 0.5*toeplitz(q);\n  \n  REQUIRE( as_scalar(r*q) == Approx(65.2) );\n  \n  REQUIRE( as_scalar(r*X*q) == Approx(380.848) );\n  \n  REQUIRE( as_scalar(r*diagmat(X)*q) == Approx(32.6) );\n  REQUIRE( as_scalar(r*inv(diagmat(X))*q) == Approx(130.4) );\n  }\n\n\n\nTEST_CASE(\"fn_as_scalar_3\")\n  {\n  cube A(1,1,1); A.fill(2.0);\n  cube B(2,2,2); B.fill(2.0);\n  \n  REQUIRE( as_scalar(A) == Approx(2.0) );\n  \n  REQUIRE( as_scalar(2+A) == Approx(4.0) );\n  \n  REQUIRE( as_scalar(B(span(0,0), span(0,0), span(0,0))) == Approx(2.0) );\n  \n  REQUIRE_THROWS( as_scalar(B) );\n  }\n", "meta": {"hexsha": "abf132ad6c4762c83720571d36759958f5f1ff9f", "size": 1815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests2/fn_as_scalar.cpp", "max_stars_repo_name": "getfiit/armadillo-code", "max_stars_repo_head_hexsha": "3a896deca12a0f596b52d84185ebfad65df650b7", "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": "tests2/fn_as_scalar.cpp", "max_issues_repo_name": "getfiit/armadillo-code", "max_issues_repo_head_hexsha": "3a896deca12a0f596b52d84185ebfad65df650b7", "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": "tests2/fn_as_scalar.cpp", "max_forks_repo_name": "getfiit/armadillo-code", "max_forks_repo_head_hexsha": "3a896deca12a0f596b52d84185ebfad65df650b7", "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.9285714286, "max_line_length": 75, "alphanum_fraction": 0.6242424242, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5161485138313361}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// ars::example::standard_distribution.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 <iostream>\n#include <boost/statistics/detail/distribution_toolkit/distributions/gamma/include.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/normal/include.hpp>\n#include <boost/ars/test/gamma_distribution.hpp>\n#include <boost/ars/test/normal_distribution.hpp>\n#include <libs/ars/example/standard_distribution.h>\n\n// TODO all other concave standard distributions:\n// See paper by Mark Bagnoli\n\nvoid example_standard_distribution(std::ostream& out){\n    out << \"-> example_standard_distribution \" << std::endl;\n\n    using namespace boost::statistics::detail;\n\n    // This example checks the convergence of ars for standard distributions\n    // by verifying that the kolmogorov-smirnov statistic converges to zero\n\n    typedef double value_;\n\n    const unsigned n1 = 5;    // # loops\n    const unsigned n2 = 10;   \t// # subsamples on first loop  \n    const unsigned n3 = 1;   \t// size of subsample \n    const unsigned n4 = 10;   \t// At each loop, n2 *= n4\n    const unsigned max_n_reject = 10;\n\n\tars::test::standard_distribution::header(out);\n\n    // The initial values are chosen to test the robustness of the\n    // implementation, within the range allowed by the algorithm.\n    {   // Domain = [0,inf)\n        value_ shape = 3.0;\n        value_ scale = 1.0;\n        value_ mode = (shape - 1.0) * scale; //2\n        typedef ars::test::gamma_distribution test_;\n        test_::call(\n            shape,          \n            scale,          \n            mode + 100.0,   //init0\n            mode + 100.01,  //init1\n            n1,\n            n2,          \n            n3,        \n            n4,\n            max_n_reject,        \n            out\n        ); \n        test_::call(\n            shape,      //shape\n            scale,      //scale\n            mode + 0.01,//init0\n            mode + 0.02, //init1\n            n1,\n            n2,          \n            n3,        \n            n4,\n            max_n_reject,        \n            out\n        );\n        \n    }\n    {   // Domain = (-inf,inf)\n        value_ mu = 0.0;\n        value_ sigma = 2.0;\n        typedef ars::test::normal_distribution test_;\n        test_::call(\n            mu,\n            sigma,\n            mu -100.0, //-100.0, //init0\n            mu + 0.01, //+ 0.01,    //init1\n            n1,\n            n2,          \n            n3,        \n            n4,\n            max_n_reject,        \n            out\n        );\n        \n        test_::call(\n            mu,\n            sigma,\n            mu - 0.01,   //init0\n            mu + 100.0,  //init1\n            n1,\n            n2,          \n            n3,        \n            n4,\n            max_n_reject,        \n            out\n        );\n        \n        test_::call(\n            mu,\n            sigma,\n            -0.01,      //init0\n            0.01,       //init1\n            n1,\n            n2,          \n            n3,        \n            n4,\n            max_n_reject,        \n            out\n        );\n        \n    }\n}\n", "meta": {"hexsha": "c143c0ede6b923de6e4b955ce3ef1e7df48cc02d", "size": 3544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "adaptive_rejection_sampling/libs/ars/example/standard_distribution.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": "adaptive_rejection_sampling/libs/ars/example/standard_distribution.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": "adaptive_rejection_sampling/libs/ars/example/standard_distribution.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": 31.0877192982, "max_line_length": 88, "alphanum_fraction": 0.4421557562, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5161168720538744}}
{"text": "/// Program KP\n/** @file\n\n\\mainpage \nThis code solves the KP equation in dimensional units (SI) for the water wave\nproblem in a frame of reference moving with velocity c_0 = sqrt(g*h).\n\nThe code is pseudo-spectral and it assumes periodic boundary conditions, both in x and y.\nIt is a natural extension of the KdV code using the method developed in Fornberg, Bengt,\nand G. B. Whitham, \"A numerical and theoretical study of certain nonlinear wave phenomena\".\nPhilosophical Transactions of the Royal Society of London A: Mathematical, Physical and\nEngineering Sciences 289.1361 (1978): 373-404.\n\nThe integral term is done in Fourier space as 1/k F(k).\n\nThe stability condition required is \\f$|\\frac{\\Delta t}{\\Delta x}| |\\frac{1}{\\Delta x^2}+\\frac{1}{\\Delta y^2}| < \\frac{1}{\\pi ^3}\\f$\n\nC++ code, based off a Fortran code developed by Dr. Miguel Onorato.\n\nInitial condition and simulation parameters set: Choice of Soliton, Lump or input for KPII via eta.csv file.\nOutput: free surface height \\f$\\eta\\f$ via eta.csv for every nvis time step\n\nGenerating initial conditions done in MATLAB directly when running with MEX-functions\n\n\\author Athina Lange, based off code from Dr. Miguel Onorato\n\\date April 8th, 2018 \n*/\n\n#include \"global.h\"\n#include \"Soliton.h\"\n#include \"Lump.h\"\n#include \"KP.h\"\n#include \"csv.h\"\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\nint main(int argc, char* argv[]){\n\n    try {\n\n        //=================================================\n        // VARIABLE DECLERATION\n        //=================================================\n\n\tstd::string initial_condition; // initial condition: \"Soliton\", \"Lump\" or \"SeaStates\" - default: \"Soliton\"\n\n        int nx; // dimension of meshgrid: x - default: 128\n        int ny; // dimension of meshgrid: y - default: 64\n        double c0; // linear nondispersive wave velocity c0 = sqrt(g*h)\n        double a; // soliton amplitude\n        double h; // water depth  - default: 5.0\n        double alpha; // nonlinear coeff\n        double beta; // dispersive coeff\n        double gama; // coeff in front of second derivative in y\n\n        double delx; // spacing in x\n        double dely; // spacing in y\n\n        double deltat; // time step - default: 0.001\n        int nstep; // number of steps - default: 500000 (500s)\n        int nvis; // visualize output after nvis steps - default: 1000\n\n        // Read eta from csv file (no header, single value per line)\n        std::vector<double> eta;\n\n        //=================================================\n        // VARIABLE INITIALIZING\n        //=================================================\n\n        po::options_description desc(\"Options\");\n        desc.add_options()\n                (\"help,h\", \"help message\")\n                (\"initial-condition\", po::value<std::string>(&initial_condition)->default_value(\"soliton\"), \"initial condition: soliton, lump or seastates\")\n                (\"nx\", po::value<int>(&nx)->default_value(128), \"number of points in x direction (even number)\")\n                (\"ny\", po::value<int>(&ny)->default_value(64), \"number of points in y direction (even number)\")\n                (\"h\", po::value<double>(&h)->default_value(5.0), \"water depth\")\n                (\"deltat\", po::value<double>(&deltat)->default_value(0.001), \"time step\")\n                (\"nstep\", po::value<int>(&nstep)->default_value(500000), \"number of steps\")\n                (\"nvis\", po::value<int>(&nvis)->default_value(1000), \"visualize output after nvis steps\");\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n        po::notify(vm);\n\n        if (vm.count(\"help\")) {\n            std::cout << desc << std::endl;\n            return 0;\n        }\n\n        if (initial_condition == \"soliton\") {\n\n            a = 0.1;\n            c0 = sqrt(G * h);\n            alpha = (3.0 / 2.0) * c0 / h; //assumed to be >=0\n            beta = h * h * c0 / 6.0; //assumed to be > 0\n            gama = 0.5 * c0;\n\n            double xmin = 0.0;\n            double xmax = 400.0;\n            double ymin = 0.0;\n            double ymax = 200.0;\n\n            delx = (xmax - xmin) / nx;\n            dely = (ymax - ymin) / ny;\n\n            soliton(nx, ny, alpha, beta, a, delx, dely, xmin, ymin, eta); // Run soliton initial condition\n\n        } else if (initial_condition == \"lump\") {\n\n            a = 1.0;\n            c0 = 0.0;\n            alpha = 6.0;\n            beta = 1.0;\n            gama = -1.0;\n\n            //Change parameters for meshgrid (256 x 256), time interval (0.0005) and run time (1000000) to satisfy stability condition\n            nx = 256;\n            ny = 256;\n            deltat = 0.0005;\n            nstep = 1000000;\n\n            double xmin = -30.0;\n            double xmax = 30.0;\n            double ymin = -50.0;\n            double ymax = 50.0;\n\n            delx = (xmax - xmin) / nx;\n            dely = (ymax - ymin) / ny;\n\n            lump(nx, ny, a, h, delx, dely, xmin, ymin, eta); // Run lump initial condition\n\n        } else if (initial_condition == \"seastates\") {\n\n            a = 0.1;\n            c0 = sqrt(G * h);\n            alpha = (3.0 / 2.0) * c0 / h; //assumed to be >=0\n            beta = h * h * c0 / 6.0; //assumed to be > 0\n            gama = 0.5 * c0;\n\n            double xmin = 0.0;\n            double xmax = 400.0;\n            double ymin = 0.0;\n            double ymax = 200.0;\n\n            delx = (xmax - xmin) / nx;\n            dely = (ymax - ymin) / ny;\n\n            read_wave_csv(\"eta.csv\", eta); // Read value of free surface eta from file\n\n        } else {\n            std::cout << \"initial-condition needs to be soliton, lump or seastates, not \" << initial_condition << std::endl;\n            return 1;\n        }\n\n        write_soliton_csv(\"Soliton.csv\", nx, ny, eta); // Write initial condition data to file\n\n        //=================================================\n        // RUN PROPAGATOR\n        //=================================================\n\n        KP(nx, ny, h, alpha, beta, gama, delx, dely, deltat, nstep, nvis, eta); // Run KP propagator\n\n        write_wave_csv(\"Wave_1000.csv\", nx, ny, delx, dely, eta); // Write final free surface eta to file\n    }\n\n    catch(std::exception& e) {\n        std::cerr << \"error: \" << e.what() << std::endl;\n        return 1;\n    }\n    catch(...) {\n        std::cerr << \"Exception of unknown type!\" << std::endl;\n        return 1;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "9f76f9b6803080772feb53bff99aaa747f425fec", "size": 6428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "AthinaLange/KPSolver", "max_stars_repo_head_hexsha": "27b9ef4edd89df0e837ee4ea7f13a025de88a4f4", "max_stars_repo_licenses": ["MIT"], "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": "AthinaLange/KPSolver", "max_issues_repo_head_hexsha": "27b9ef4edd89df0e837ee4ea7f13a025de88a4f4", "max_issues_repo_licenses": ["MIT"], "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": "AthinaLange/KPSolver", "max_forks_repo_head_hexsha": "27b9ef4edd89df0e837ee4ea7f13a025de88a4f4", "max_forks_repo_licenses": ["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.1123595506, "max_line_length": 156, "alphanum_fraction": 0.5381144991, "num_tokens": 1693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5161168660745448}}
{"text": "#include <algorithm>\n\n#ifdef _WIN32\n    #pragma warning(push, 0)\n    #include <boost/polygon/polygon.hpp>\n    #pragma warning(pop)\n#else\n    #include <boost/polygon/polygon.hpp>\n#endif\n\n#include <cradle/geometry/angle.hpp>\n#include <cradle/geometry/clipper.hpp>\n#include <cradle/geometry/intersection.hpp>\n#include <cradle/geometry/polygonal.hpp>\n\nnamespace cradle {\n\n\n// COMMON FUNCTIONS\n\nstatic vector<2,double> get_corner(box<2,double> const& box, int index)\n{\n    vector<2,double> corner;\n    while(index >= 4)\n    {\n        index -= 4;\n    }\n    switch (index)\n    {\n        case 0:\n            return box.corner;\n        case 1:\n            return box.corner + make_vector(box.size[0], 0.);\n        case 2:\n            return box.corner + make_vector(box.size[0], box.size[1]);\n        case 3:\n            return box.corner + make_vector(0., box.size[1]);\n    }\n    return make_vector(0.,0.);\n}\n\n// POLYGONS\n\npolygon2 make_polygon2(std::vector<vertex2> const& vertices)\n{\n    polygon2 poly;\n    initialize(&poly.vertices, vertices);\n    return poly;\n}\n\ndouble get_area(polygon2 const& poly)\n{\n    return get_area_and_centroid(poly).first;\n}\n\nvector2d get_centroid(polygon2 const& poly)\n{\n    return get_area_and_centroid(poly).second;\n}\n\nstd::pair<double, vector2d> get_area_and_centroid(polygon2 const& poly)\n{\n    double a = 0.0;\n    double cx = 0.0;\n    double cy = 0.0;\n    for (polygon2_edge_view ev(poly); !ev.done(); ev.advance())\n    {\n        double cross = ev.p0()[0] * ev.p1()[1] - ev.p0()[1] * ev.p1()[0];\n        a += cross;\n        cx += (ev.p0()[0] + ev.p1()[0]) * cross;\n        cy += (ev.p0()[1] + ev.p1()[1]) * cross;\n    }\n    double scale = 3.0 * a;\n    return std::make_pair(std::fabs(0.5 * a),\n        make_vector(cx / scale, cy / scale));\n}\n\npolygon2 scale(polygon2 const& poly, double factor)\n{\n    return scale(poly, make_vector(factor, factor));\n}\n\nstruct point_scaling_fn\n{\n    vector<2,double> factor;\n    vertex2 operator()(vertex2 const& src) const\n    {\n        return make_vector(src[0] * factor[0], src[1] * factor[1]);\n    }\n};\n\npolygon2 scale(polygon2 const& poly, vector<2,double> const& factor)\n{\n    point_scaling_fn fn;\n    fn.factor = factor;\n    return map_points(poly, fn);\n}\n\nbool is_inside(polygon2 const& poly, vector<2,double> const& p)\n{\n    bool c = false;\n    for (polygon2_edge_view ev(poly); !ev.done(); ev.advance())\n    {\n        if (((ev.p0()[1] <= p[1] && p[1] < ev.p1()[1]) ||\n            (ev.p1()[1] <= p[1] && p[1] < ev.p0()[1]))\n         && (p[0] < (ev.p1()[0] - ev.p0()[0]) * (p[1] - ev.p0()[1]) /\n            (ev.p1()[1] - ev.p0()[1]) + ev.p0()[0]))\n        {\n            c = !c;\n        }\n    }\n    return c;\n}\n\nbool is_inside(polygon2 const& parent_poly, polygon2 const& child_poly)\n{\n    for (auto const& point : child_poly.vertices)\n    {\n        if (!is_inside(parent_poly, point))\n        {\n            return false;\n        }\n    }\n    return true;\n}\n\nbool is_ccw(polygon2 const& poly)\n{\n    assert(poly.vertices.size() > 2);\n    vector<2,double> edge0 = poly.vertices[1] - poly.vertices[0];\n    vector<2,double> edge1 = poly.vertices[2] - poly.vertices[1];\n    return (edge0[0] * edge1[1]) - (edge0[1] * edge1[0]) > 0;\n}\n\npolygon2 as_polygon(box<2,double> const& box)\n{\n    polygon2 poly;\n    vertex2* vertices = allocate(&poly.vertices, 4);\n    vertices[0] = box.corner;\n    vertices[1] = box.corner + make_vector(box.size[0], 0.);\n    vertices[2] = box.corner + box.size;\n    vertices[3] = box.corner + make_vector(0., box.size[1]);\n    return poly;\n}\n\npolygon2 as_polygon(circle<double> const& circle, unsigned n_segments)\n{\n    polygon2 poly;\n    vertex2* vertices = allocate(&poly.vertices, n_segments);\n    for (unsigned i = 0; i < n_segments; ++i)\n    {\n        angle<double,radians> a(2 * pi * i / n_segments);\n        vertices[i] =\n            make_vector(cos(a), sin(a)) * circle.radius + circle.center;\n    }\n    return poly;\n}\n\npolygon2 as_polygon(triangle<2,double> const& tri)\n{\n    polygon2 poly;\n    vertex2* vertices = allocate(&poly.vertices, 3);\n    for (unsigned i = 0; i != 3; ++i)\n        vertices[i] = tri[i];\n    return poly;\n}\n\n// POLYSETS\n\nvoid create_polyset(polyset* set, polygon2 const& poly)\n{\n    *set = polyset();\n    set->polygons.push_back(poly);\n}\n\npolyset make_polyset(polygon2 const& poly)\n{\n    polyset p;\n    create_polyset(&p, poly);\n    return p;\n}\n\nvoid add_polygon(polyset& set, polygon2 const& poly)\n{\n    polyset addition;\n    create_polyset(&addition, poly);\n    if (set.polygons.empty())\n        swap(set, addition);\n    else\n        do_set_operation(&set, set_operation::UNION, addition, set);\n}\nvoid add_hole(polyset& set, polygon2 const& hole)\n{\n    assert(!set.polygons.empty());\n    polyset subtraction;\n    create_polyset(&subtraction, hole);\n    do_set_operation(&set, set_operation::DIFFERENCE, set, subtraction);\n}\n\npolyset remove_polyset_holes(\n    polyset const& original_shape)\n{\n    polyset shape = original_shape;\n\n    while (!shape.holes.empty())\n    {\n        do_set_operation(\n            &shape,\n            set_operation::UNION,\n            shape,\n            make_polyset(shape.holes.front()));\n    }\n\n    return shape;\n}\n\npolyset scale(polyset const& set, double factor)\n{\n    return scale(set, make_vector(factor, factor));\n}\npolyset scale(polyset const& set, cradle::vector<2,double> const& factor)\n{\n    point_scaling_fn fn;\n    fn.factor = factor;\n    return map_points(set, fn);\n}\n\nstd::pair<double, vector2d> static\nget_area_and_centroid(polyset const& set)\n{\n    double area = 0;\n    auto centroid = make_vector(0., 0.);\n    for (auto const& i : set.polygons)\n    {\n        auto pair = get_area_and_centroid(i);\n        area += pair.first;\n        centroid += pair.second * pair.first;\n    }\n    for (auto const& i : set.holes)\n    {\n        auto pair = get_area_and_centroid(i);\n        area -= get_area(i);\n        centroid -= pair.second * pair.first;\n    }\n    centroid /= area;\n    return std::make_pair(area, centroid);\n}\n\ndouble get_area(polyset const& set)\n{\n    return get_area_and_centroid(set).first;\n}\n\nvector2d get_centroid(polyset const& set)\n{\n    auto pair = get_area_and_centroid(set);\n    if (pair.first == 0)\n        throw exception(\"centroid requested for empty polyset\");\n    return pair.second;\n}\n\nbool is_inside(polyset const& set, vector<2,double> const& p)\n{\n    int inside_count = 0;\n    for (auto const& i : set.polygons)\n    {\n        if (is_inside(i, p))\n            ++inside_count;\n    }\n    for (auto const& i : set.holes)\n    {\n        if (is_inside(i, p))\n            --inside_count;\n    }\n    return inside_count > 0;\n}\n\ntypedef line_segment<2, double> line_segment2;\n\ndouble distance_to_polyset(vector<2,double> const& p, polyset const& set)\n{\n    double d2p = 1.0e10;\n    size_t polygon_count = set.polygons.size();\n    for (size_t k = 0; k < polygon_count; ++k)\n    {\n        size_t vertex_count = set.polygons[k].vertices.n_elements;\n        auto v0 = set.polygons[k].vertices.elements[vertex_count - 1];\n        for (size_t i = 0; i < vertex_count; ++i)\n        {\n            // Get segment end point\n            auto v1 = set.polygons[k].vertices.elements[i];\n            line_segment2 segment(v0, v1);\n            auto len = length(segment);\n\n            // Ensure the line segment has finite length\n            if (len >= 1.0e-8)\n            {\n                // Discretize line segment and determine distance\n                double spacing = 0.25;\n                int split_count = std::min(std::max(int(std::ceil(len / spacing)), 2), 30);\n                for (int j = 0; j < split_count; ++j)\n                {\n                    double dist = distance(segment, p);\n\n                    if (dist < std::fabs(d2p))\n                    {\n                        bool pip = point_in_polygon(p, set.polygons[k]);\n                        d2p = pip ? -dist : dist;\n                    }\n                }\n            }\n\n            // Increment segment start point\n            v0 = v1;\n        }\n    }\n\n    // Handle Holes too\n    size_t hole_count = set.holes.size();\n    for (size_t k = 0; k < hole_count; ++k)\n    {\n        size_t vertex_count = set.holes[k].vertices.n_elements;\n        auto v0 = set.holes[k].vertices.elements[vertex_count - 1];\n        for (size_t i = 0; i < vertex_count; ++i)\n        {\n            // Get segment end point\n            auto v1 = set.holes[k].vertices.elements[i];\n            line_segment2 segment(v0, v1);\n            auto len = length(segment);\n\n            // Ensure the line segment has finite length\n            if (len >= 1.0e-8)\n            {\n                // Discretize line segment and determine distance\n                double spacing = 0.25;\n                int split_count = std::min(std::max(int(std::ceil(len / spacing)), 2), 30);\n                for (int j = 0; j < split_count; ++j)\n                {\n                    double dist = distance(segment, p);\n\n                    if (dist < std::fabs(d2p))\n                    {\n                        bool pip = point_in_polygon(p, set.holes[k]);\n                        d2p = pip ? dist : -dist;\n                    }\n                }\n            }\n\n            // Increment segment start point\n            v0 = v1;\n        }\n    }\n\n    return d2p;\n}\n\nnamespace {\n\n    typedef boost::polygon::point_data<int> boost_point;\n\n    typedef boost::polygon::polygon_data<int> boost_polygon;\n\n    typedef boost::polygon::polygon_with_holes_data<int>\n        boost_polygon_with_holes;\n\n    typedef boost::polygon::polygon_set_data<int> boost_polygon_set;\n\n    void to_boost_polygon(boost_polygon& bp, polygon2 const& poly)\n    {\n        size_t n_points = poly.vertices.size();\n        bp.coords_.resize(n_points);\n        for (size_t i = 0; i != n_points; ++i)\n        {\n            vector<2,double> const& p = poly.vertices[i];\n            bp.coords_[i] = boost_polygon::point_type(\n                int(p[0] / clipper_integer_precision),\n                int(p[1] / clipper_integer_precision));\n        }\n    }\n\n    void to_boost_polygon(boost_polygon_set& boost_set,\n        polyset const& cradle_set)\n    {\n        using namespace boost::polygon::operators;\n        boost_set.clear();\n        for (auto const& i : cradle_set.polygons)\n        {\n            boost_polygon poly;\n            to_boost_polygon(poly, i);\n            boost_set ^= poly;\n        }\n        for (auto const& i : cradle_set.holes)\n        {\n            boost_polygon poly;\n            to_boost_polygon(poly, i);\n            boost_set ^= poly;\n        }\n    }\n\n    vector<2,double>\n    from_boost_point(boost_point const& p)\n    {\n        return make_vector<double>(\n            double(p.x()) * clipper_integer_precision,\n            double(p.y()) * clipper_integer_precision);\n    }\n\n    void from_boost_polygon(polygon2& poly, boost_polygon const& bp)\n    {\n        size_t n_points = bp.size();\n        if (n_points != 0)\n        {\n            // The first and last vertices are the same, so skip the last.\n            --n_points;\n            vertex2* vertices = allocate(&poly.vertices, n_points);\n            for (size_t i = 0; i != n_points; ++i)\n                vertices[i] = from_boost_point(bp.coords_[i]);\n        }\n        else\n            clear(&poly.vertices);\n    }\n\n    void from_boost_polygon(polyset& cradle_set,\n        boost_polygon_set const& boost_set)\n    {\n        cradle_set = polyset();\n        std::vector<boost_polygon_with_holes> boost_polys;\n        boost_set.get(boost_polys);\n        for (auto const& bp : boost_polys)\n        {\n            polygon2 poly;\n            from_boost_polygon(poly, bp.self_);\n            cradle_set.polygons.push_back(poly);\n            for (auto const& bh : bp.holes_)\n            {\n                polygon2 hole;\n                from_boost_polygon(hole, bh);\n                cradle_set.holes.push_back(hole);\n            }\n        }\n    }\n\n    void from_boost_polygon(std::vector<polygon2>& polys,\n        boost_polygon_set const& set)\n    {\n        std::vector<boost_polygon> boost_polys;\n        set.get(boost_polys);\n        size_t n_polys = boost_polys.size();\n        polys.resize(n_polys);\n        for (size_t i = 0; i != n_polys; ++i)\n        {\n            boost_polygon const& bp = boost_polys[i];\n            polygon2& poly = polys[i];\n            from_boost_polygon(poly, bp);\n        }\n    }\n\n} // anonymous namespace\n\nstd::vector<polygon2> as_polygon_list(polyset const& set)\n{\n    boost_polygon_set boost_set;\n    to_boost_polygon(boost_set, set);\n    std::vector<polygon2> polygons;\n    from_boost_polygon(polygons, boost_set);\n    return polygons;\n}\n\nbool almost_equal(polyset const& set1, polyset const& set2, double tolerance)\n{\n    polyset xor_;\n    do_set_operation(&xor_, set_operation::XOR, set1, set2);\n    return almost_equal(get_area(xor_), 0., tolerance);\n}\n\nbool almost_equal(polyset const& set1, polyset const& set2)\n{\n    polyset xor_;\n    do_set_operation(&xor_, set_operation::XOR, set1, set2);\n    return almost_equal(get_area(xor_), 0.);\n}\n\nvoid do_set_operation(\n    polyset* result,\n    set_operation op,\n    polyset const& set1,\n    polyset const& set2)\n{\n    ClipperLib::Clipper clipper;\n    clipper.AddPolygons(to_clipper(set1), ClipperLib::ptSubject);\n    clipper.AddPolygons(to_clipper(set2), ClipperLib::ptClip);\n    ClipperLib::ClipType clipper_op;\n    switch (op)\n    {\n     case set_operation::UNION:\n        clipper_op = ClipperLib::ctUnion;\n        break;\n     case set_operation::INTERSECTION:\n        clipper_op = ClipperLib::ctIntersection;\n        break;\n     case set_operation::DIFFERENCE:\n        clipper_op = ClipperLib::ctDifference;\n        break;\n     case set_operation::XOR:\n        clipper_op = ClipperLib::ctXor;\n        break;\n     default:\n         throw exception(\"set operation undefined\");\n    }\n    ClipperLib::Polygons solution;\n    clipper.Execute(clipper_op, solution);\n    from_clipper(result, solution);\n}\n\napi(fun)\npolyset\npolyset_combination(set_operation op, std::vector<polyset> const& polysets)\n{\n    if (polysets.empty())\n    {\n        return polyset();\n    }\n    else if (polysets.size() == 1)\n    {\n        return polysets[0];\n    }\n    polyset tmp[2];\n    int output_index = 0;\n    polyset const* input = &polysets.front();\n    auto i = polysets.begin();\n    ++i;\n    for (; i != polysets.end(); ++i)\n    {\n        output_index = 1 - output_index;\n        auto output = &tmp[output_index];\n        do_set_operation(output, op, *input, *i);\n        input = output;\n    }\n    return tmp[output_index];\n}\n\n// Triangulate a convex Boost polygon.\n// Note that this does NOT clear the list of triangles.\n// It simply pushes more triangles onto the back of it.\nstatic void\ntriangulate_boost_polygon(\n    std::vector<triangle<2,double> >& tris, boost_polygon const& poly)\n{\n    size_t n_points = poly.size();\n    if (n_points > 0)\n    {\n        // The first and last vertices are the same, so skip the last.\n        --n_points;\n        for (size_t i = 2; i < n_points; ++i)\n        {\n            triangle<2,double> tri;\n            tri[0] = from_boost_point(poly.coords_[0]);\n            tri[1] = from_boost_point(poly.coords_[i - 1]);\n            tri[2] = from_boost_point(poly.coords_[i]);\n            tris.push_back(tri);\n        }\n    }\n}\n\nstd::vector<triangle<2,double> >\ntriangulate_polyset(polyset const& set)\n{\n    boost_polygon_set boost_set;\n    to_boost_polygon(boost_set, set);\n    std::vector<boost_polygon> trapezoids;\n    boost_set.get_trapezoids(trapezoids);\n    size_t n_trapezoids = trapezoids.size();\n    std::vector<triangle<2,double> > tris;\n    tris.reserve(n_trapezoids * 2);\n    for (size_t i = 0; i != n_trapezoids; ++i)\n        triangulate_boost_polygon(tris, trapezoids[i]);\n    return tris;\n}\n\nvoid\nexpand(polyset* dst, polyset const& src, double amount)\n{\n    using namespace boost::polygon::operators;\n    auto clipper_in = to_clipper(src);\n    ClipperLib::Polygons clipper_out;\n    OffsetPaths(clipper_in, clipper_out, amount / clipper_integer_precision,\n        ClipperLib::jtRound, ClipperLib::etClosed);\n    from_clipper(dst, clipper_out);\n}\n\npolyset polyset_expansion(polyset const& src, double amount)\n{\n    polyset result;\n    expand(&result, src, amount);\n    return result;\n}\n\nvoid create_polyset_from_polygons(polyset* set,\n    std::vector<polygon2> const& polygons)\n{\n    using namespace boost::polygon::operators;\n    boost_polygon_set boost_set;\n    for (std::vector<polygon2>::const_iterator\n        i = polygons.begin(); i != polygons.end(); ++i)\n    {\n        boost_polygon bp;\n        to_boost_polygon(bp, *i);\n        boost_set += bp;\n    }\n    from_boost_polygon(*set, boost_set);\n}\n\n// STRUCTURES\n\nbool is_inside(structure_geometry_slice const& s, double p)\n{\n    return ((p >= s.position - (s.thickness / 2.)) &&\n        (p < s.position + (s.thickness / 2.)));\n}\n\nvoid static\nreset_structure_to_slice_list(\n    structure_geometry* structure,\n    slice_description_list const& slices)\n{\n    structure->slices.clear();\n    structure->master_slice_list.clear();\n    structure->master_slice_list = slices;\n}\n\nstructure_geometry static\nremove_empty_slices(structure_geometry const& structure)\n{\n    structure_geometry result;\n    result.master_slice_list = structure.master_slice_list;\n    for (auto const& slice : structure.slices)\n    {\n        if (!is_empty(slice.second))\n        {\n            result.slices.insert(slice);\n        }\n    }\n    return result;\n}\n\npolyset\nget_slice(structure_geometry const& structure, double position)\n{\n    auto slice = get_structure_slice(structure, position);\n    if (slice)\n    {\n        return get(slice).region;\n    }\n\n    return polyset();\n}\n\nstructure_geometry_slice\nfind_slice_at_exact_position(\n    structure_polyset_list const& slices,\n    double position,\n    double thickness)\n{\n    auto s = slices.find(position);\n    if (s != slices.end())\n    {\n        return structure_geometry_slice(position, thickness, s->second);\n    }\n    return structure_geometry_slice(position, thickness, polyset());\n}\n\noptional<structure_geometry_slice>\nget_structure_slice(structure_geometry const& structure, double position)\n{\n    auto const& masters = structure.master_slice_list;\n    auto const& slices = structure.slices;\n    auto p = position;\n\n    if (masters.size() == 0 ||\n        p < masters[0].position - 0.5 * masters[0].thickness ||\n        p > masters.back().position + 0.5 * masters.back().thickness)\n    {\n        return none;\n    }\n\n    for (size_t i = 1; i < masters.size(); ++i)\n    {\n        if (p < masters[i].position)\n        {\n            if (p - masters[i - 1].position < masters[i].position - p)\n            {\n                return\n                    some(\n                        find_slice_at_exact_position(\n                            slices,\n                            masters[i - 1].position,\n                            masters[i - 1].thickness));\n            }\n            else\n            {\n                return\n                    some(\n                        find_slice_at_exact_position(\n                            slices,\n                            masters[i].position,\n                            masters[i].thickness));\n            }\n        }\n    }\n    // Valid case when p is past the last slice position, but within its thickness\n    return\n        some(\n            find_slice_at_exact_position(\n                slices,\n                masters.rbegin()->position,\n                masters.rbegin()->thickness));\n}\n\nstd::vector<structure_geometry_slice>\nget_structure_slices(structure_geometry const& structure, double p_low, double p_high)\n{\n    auto const& masters = structure.master_slice_list;\n    auto const& slices = structure.slices;\n\n    std::vector<structure_geometry_slice> output;\n\n    if (masters.size() == 0 ||\n        p_low > masters.back().position + 0.5 * masters.back().thickness ||\n        p_high < masters[0].position - 0.5 * masters[0].thickness)\n    {\n        return output;\n    }\n\n    // Find the start and end slice indices\n    // Note: the initial value set below is critical to this functioning properly\n    size_t i_start = masters.size();\n\n    for (size_t i = 1; i < masters.size(); ++i)\n    {\n        if (p_low < masters[i].position)\n        {\n            if (p_low - masters[i - 1].position < masters[i].position - p_low)\n            {\n                i_start = i - 1;\n            }\n            else\n            {\n                i_start = i;\n            }\n            output.push_back(\n                find_slice_at_exact_position(\n                    slices,\n                    masters[i_start].position,\n                    masters[i_start].thickness));\n            break;\n        }\n    }\n\n    for (size_t i = i_start + 1; i < masters.size(); ++i)\n    {\n        if (p_high < masters[i].position)\n        {\n            if (p_high - masters[i - 1].position < masters[i].position - p_high)\n            {\n                // Last slice is already in the list, just return now\n                return output;\n            }\n            else\n            {\n                // Add the last slice and then return\n                output.push_back(\n                    find_slice_at_exact_position(\n                        slices,\n                        masters[i].position,\n                        masters[i].thickness));\n                return output;\n            }\n        }\n\n        // Slice is within limits, add it\n        output.push_back(\n            find_slice_at_exact_position(\n                slices,\n                masters[i].position,\n                masters[i].thickness));\n    }\n\n    // All slices have been added (but never reached p_high position), just return\n    return output;\n}\n\nvoid static\nfold_in(double& volume, vector3d& centroid,\n    std::pair<double,vector2d> const& area_and_centroid,\n    double z, double thickness)\n{\n    volume += area_and_centroid.first * thickness;\n    centroid += unslice(area_and_centroid.second, 2, z) *\n        area_and_centroid.first * thickness;\n}\n\nvoid static\nfold_in_above(double& volume, vector3d& centroid,\n    std::pair<double,vector2d> const& area_and_centroid,\n    double z, double thickness)\n{\n    fold_in(volume, centroid, area_and_centroid, z + thickness / 2, thickness);\n}\n\nvoid static\nfold_in_below(double& volume, vector3d& centroid,\n    std::pair<double,vector2d> const& area_and_centroid,\n    double z, double thickness)\n{\n    fold_in(volume, centroid, area_and_centroid, z - thickness / 2, thickness);\n}\n\nstd::pair<double,vector3d> static\nget_volume_and_centroid(structure_geometry const& structure)\n{\n    auto volume = 0.;\n    auto centroid = make_vector(0., 0., 0.);\n\n    auto const& masters = structure.master_slice_list;\n    auto const& slices = structure.slices;\n\n    auto begin_m = masters.begin();\n    auto end_m = masters.end();\n    auto i = begin_m;\n    auto end_slice = slices.end();\n\n    while (i != end_m)\n    {\n        auto slice = slices.find(i->position);\n        if (slice != end_slice && get_area(slice->second) != 0.)\n        {\n            break;\n        }\n        ++i;\n    }\n\n    for (; i != end_m; ++i)\n    {\n        auto slice = slices.find(i->position);\n        if (slice == end_slice) { continue; }\n\n        auto i_info = get_area_and_centroid(slice->second);\n\n        // Add lower half of slice thickness\n        auto temp = i;\n        if (i == begin_m)\n        {\n            fold_in_below(volume, centroid, i_info, i->position, i->thickness * 0.5);\n        }\n        else\n        {\n            --temp;\n            fold_in_below(\n                volume, centroid,\n                i_info,\n                i->position,\n                0.5 * (i->position - temp->position));\n        }\n\n        // Add upper half of slice thickness\n        temp = i;\n        ++temp;\n        if (temp == end_m)\n        {\n            fold_in_above(volume, centroid, i_info, i->position, i->thickness * 0.5);\n        }\n        else\n        {\n            fold_in_above(\n                volume, centroid,\n                i_info,\n                i->position,\n                0.5 * (temp->position - i->position));\n        }\n    }\n\n    if (volume != 0.)\n    {\n        centroid /= volume;\n    }\n\n    return std::make_pair(volume, centroid);\n}\n\ndouble get_volume(structure_geometry const& structure)\n{\n    return get_volume_and_centroid(structure).first;\n}\n\nvector3d get_centroid(\n    structure_geometry const& structure)\n{\n    auto pair = get_volume_and_centroid(structure);\n    if (pair.first == 0)\n        throw exception(\"centroid requested for empty structure\");\n    return pair.second;\n}\n\nbool is_inside(structure_geometry const& structure, vector<3,double> const& p)\n{\n    auto s = get_slice(structure, p[2]);\n    return is_inside(s, slice(p, 2));\n}\n\nslice_description_list\nget_slice_descriptions(structure_geometry const& s)\n{\n    return s.master_slice_list;\n}\n\nbool\nalmost_equal(\n    structure_geometry const& volume1,\n    structure_geometry const& volume2,\n    double tolerance)\n{\n    if (volume1.master_slice_list.size() != volume2.master_slice_list.size())\n        return false;\n\n    auto i1 = volume1.master_slice_list.begin();\n    auto end1 = volume1.master_slice_list.end();\n    auto i2 = volume2.master_slice_list.begin();\n\n    auto const& slices1 = volume1.slices;\n    auto const& slices2 = volume2.slices;\n\n    for (; i1 != end1; ++i1, ++i2)\n    {\n        if (!almost_equal(i1->position, i2->position, tolerance) ||\n            !almost_equal(i1->thickness, i2->thickness, tolerance))\n        {\n            return false;\n        }\n        auto r1 = find_slice_at_exact_position(slices1, i1->position, i1->thickness);\n        auto r2 = find_slice_at_exact_position(slices2, i2->position, i2->thickness);\n        if (!almost_equal(r1.region, r2.region, tolerance))\n        {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nbool almost_equal(structure_geometry const& a, structure_geometry const& b)\n{\n    return almost_equal(a, b, default_equality_tolerance<double>());\n}\n\nvoid do_set_operation(\n    structure_geometry* result,\n    set_operation op,\n    structure_geometry const& structure1,\n    structure_geometry const& structure2)\n{\n    if (structure1.master_slice_list != structure2.master_slice_list)\n    {\n        throw exception(\"structure set_operation requires matching master lists\");\n    }\n\n    auto const& master_slices = structure1.master_slice_list;\n\n    result->master_slice_list = master_slices;\n    result->slices.clear();\n    for (auto const& i : master_slices)\n    {\n        auto s1 =\n            find_slice_at_exact_position(structure1.slices, i.position, i.thickness);\n        auto s2 =\n            find_slice_at_exact_position(structure2.slices, i.position, i.thickness);\n\n        if (!is_empty(s1.region) || !is_empty(s2.region))\n        {\n            polyset region;\n            do_set_operation(&region, op, s1.region, s2.region);\n            if (!is_empty(region))\n            {\n                result->slices[i.position] = region;\n            }\n        }\n    }\n}\n\nstructure_geometry\nstructure_combination(\n    set_operation op,\n    std::vector<structure_geometry> const& structures)\n{\n    if (structures.size() < 2)\n    {\n        throw exception(\"structure_combination requires at least two structures\");\n    }\n    structure_geometry tmp[2];\n    int output_index = 0;\n    structure_geometry const* input = &structures.front();\n    auto i = structures.begin();\n    ++i;\n    for (; i != structures.end(); ++i)\n    {\n        output_index = 1 - output_index;\n        auto output = &tmp[output_index];\n        do_set_operation(output, op, *input, *i);\n        input = output;\n    }\n    return tmp[output_index];\n}\n\nstd::vector<double>\nslice_position_list(structure_geometry const& structure)\n{\n    return map(\n        [](slice_description const& slice)\n        {\n            return slice.position;\n        },\n        structure.master_slice_list);\n}\n\nvoid expand_in_2d(\n    structure_geometry* result,\n    structure_geometry const& structure,\n    double amount)\n{\n    auto slice_descriptions = get_slice_descriptions(structure);\n    reset_structure_to_slice_list(result, slice_descriptions);\n    for (auto const& slice : structure.slices)\n    {\n        polyset p;\n        expand(&p, slice.second, amount);\n        result->slices[slice.first] = p;\n    }\n}\n\nbox<2,double>\nbounding_box(polygon2 const& poly)\n{\n    optional<box<2,double> > box;\n    compute_bounding_box(box, poly);\n    // If there is no box, then the polygon is empty, so just return any box.\n    return box ? box.get() :\n        make_box(make_vector(0., 0.), make_vector(0., 0.));\n}\nvoid compute_bounding_box(\n    optional<box<2,double> >& box,\n    polygon2 const& poly)\n{\n    vertex2_array::const_iterator\n        i = poly.vertices.begin(),\n        end = poly.vertices.end();\n    if (i == end)\n        return;\n\n    vector<2,double> min, max;\n    if (box)\n    {\n        min = get_low_corner(box.get());\n        max = get_high_corner(box.get());\n    }\n    else\n    {\n        min = *i;\n        max = *i;\n        ++i;\n    }\n\n    for (; i != end; ++i)\n    {\n        for (unsigned j = 0; j != 2; ++j)\n        {\n            if ((*i)[j] < min[j])\n                min[j] = (*i)[j];\n            if ((*i)[j] > max[j])\n                max[j] = (*i)[j];\n        }\n    }\n\n    box = cradle::box<2,double>(min, max - min);\n}\n\n// for a polyset\nbox<2,double> bounding_box(polyset const& region)\n{\n    optional<box<2,double> > box;\n    compute_bounding_box(box, region);\n    // If there is no box, then the polyset is empty, so just return any box.\n    return box ? box.get() :\n        make_box(make_vector(0., 0.), make_vector(0., 0.));\n}\nvoid compute_bounding_box(optional<box<2,double> >& box, polyset const& region)\n{\n    for (auto const& i : region.polygons)\n        compute_bounding_box(box, i);\n}\n\n// for a structure_geometry\nbox<3,double> bounding_box(structure_geometry const& structure)\n{\n    optional<box<3,double> > box;\n    compute_bounding_box(box, structure);\n    // If there is no box, then the structure is empty, so just return any box.\n    return box ? box.get() :\n        make_box(make_vector(0., 0., 0.), make_vector(0., 0., 0.));\n}\nvoid compute_bounding_box(optional<box<3,double> >& box,\n    structure_geometry const& structure)\n{\n    optional<cradle::box<2,double> > xy_box;\n    if (box)\n    {\n        xy_box = slice(box.get(), 2);\n    }\n\n    double zmin = 1.0e100;\n    double zmax = -1.0e100;\n    auto master_slices = get_slice_descriptions(structure);\n    for (auto const& m_slice : master_slices)\n    {\n        auto slice =\n            find_slice_at_exact_position(\n                structure.slices,\n                m_slice.position,\n                m_slice.thickness);\n        if (!is_empty(slice.region))\n        {\n            compute_bounding_box(xy_box, slice.region);\n\n            if (slice.position - 0.5 * slice.thickness < zmin)\n            {\n                zmin = slice.position - 0.5 * slice.thickness;\n            }\n            if (slice.position + 0.5 * slice.thickness > zmax)\n            {\n                zmax = slice.position + 0.5 * slice.thickness;\n            }\n        }\n    }\n\n\n    if (!structure.slices.empty() && xy_box)\n    {\n        //double z_min = structure.slices.begin()->position -\n        //    structure.slices.begin()->thickness / 2;\n        //auto last = structure.slices.end();\n        //--last;\n        //double z_max = last->position + last->thickness / 2;\n\n        vector<2,double> const& xy_corner = xy_box.get().corner;\n        vector<2,double> const& xy_size = xy_box.get().size;\n\n        box = cradle::box<3,double>(\n            make_vector(xy_corner[0], xy_corner[1], zmin),\n            make_vector(xy_size[0], xy_size[1], zmax - zmin));\n    }\n}\n\n\nbool\noverlapping(\n    box3d const& box,\n    structure_geometry const& sg,\n    unsigned structure_axis,\n    optional<box3d> const& sg_bounds)\n{\n    if (sg_bounds)\n    {\n        if (!overlapping(box, get(sg_bounds)))\n        {\n            return false;\n        }\n    }\n\n    // Get slices that the box contains\n    auto slices =\n        get_structure_slices(\n            sg,\n            box.corner[structure_axis],\n            get_high_corner(box)[structure_axis]);\n\n    // Check for overlap on each slice\n    for (auto const& s : slices)\n    {\n        if (s.region.polygons.size() == 0)\n        {\n            continue;\n        }\n\n        auto const box2 = slice(box, structure_axis);\n\n        // Check center of voxel as this may be a fast \"short-circuit\" for many cases\n        if (point_in_polyset(get_center(box2), s.region))\n        {\n            return true;\n        }\n        else\n        {\n            // Check all points in the polyset\n            // Note this isn't 100% accurate because holes can actually make a polygon\n            // vertex outside and we don't catch that case\n            for (auto const& p : s.region.polygons)\n            {\n                for (auto const& v : p.vertices)\n                {\n                    if (contains(box2, v))\n                    {\n                        return true;\n                    }\n                }\n            }\n        }\n    }\n\n    return false;\n}\n\n\nbool almost_equal(polygon2 const& a, polygon2 const& b, double tolerance)\n{\n    polyset region_a, region_b, xor_region;\n    create_polyset(&region_a, a);\n    create_polyset(&region_b, b);\n    do_set_operation(&xor_region, set_operation::XOR, region_a, region_b);\n    return almost_equal(get_area(xor_region), 0., tolerance);\n}\nbool almost_equal(polygon2 const& a, polygon2 const& b)\n{\n    polyset region_a, region_b, xor_region;\n    create_polyset(&region_a, a);\n    create_polyset(&region_b, b);\n    do_set_operation(&xor_region, set_operation::XOR, region_a, region_b);\n    return almost_equal(get_area(xor_region), 0.);\n}\n\n}\n", "meta": {"hexsha": "4320852ce3573e2e1e9b79f756d0684d37d7a7f2", "size": 33670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cradle/src/cradle/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/src/cradle/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/src/cradle/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": 27.1751412429, "max_line_length": 91, "alphanum_fraction": 0.5845856846, "num_tokens": 8338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5161168430607794}}
{"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_CSCD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_CSCD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing cscd capabilities\n\n    cosecante in degree.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = cscd(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = rec(sind(x));\n    @endcode\n\n    As most other trigonometric function cscd can be called with a second optional parameter\n    which is a tag on speed and accuracy (see @ref cos for further details)\n\n    @see csc, cscpi,\n\n  **/\n  const boost::dispatch::functor<tag::cscd_> cscd = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/cscd.hpp>\n#include <boost/simd/function/simd/cscd.hpp>\n\n#endif\n", "meta": {"hexsha": "4fa61fc7d7ec12c25c62b50bdb7fbc8eda6b6282", "size": 1237, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/cscd.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/cscd.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/cscd.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": 22.9074074074, "max_line_length": 100, "alphanum_fraction": 0.5917542441, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5160119974886961}}
{"text": "/** \n * Test cases for functions in utils::stds.\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 LinspaceTest\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\n\nBOOST_AUTO_TEST_CASE(linspace_with_count_generates_int_vector)\n{\n    size_t N = 0;\n    double min = 0, max = 9;\n\n    auto vec = utils::stds::linspace(min, max, N);\n    BOOST_REQUIRE_EQUAL(vec.size(), N);\n\n\n    N = 1;\n    vec = utils::stds::linspace(min, max, N);\n    BOOST_REQUIRE_EQUAL(vec.size(), N);\n    BOOST_CHECK_EQUAL(vec[0], min);\n\n    N = 2;\n    vec = utils::stds::linspace(min, max, N);\n    BOOST_REQUIRE_EQUAL(vec.size(), N);\n    BOOST_CHECK_EQUAL(vec[0], min);\n    BOOST_CHECK_EQUAL(vec[1], max);\n\n    N = 10;\n    vec = utils::stds::linspace(min, max, N);\n    BOOST_REQUIRE_EQUAL(vec.size(), N);\n    BOOST_CHECK_EQUAL(vec[0], min);\n    BOOST_CHECK_EQUAL(vec[4], 4);\n    BOOST_CHECK_EQUAL(vec[5], 5);\n    BOOST_CHECK_EQUAL(vec[N-1], max);\n\n}\n\n\nBOOST_AUTO_TEST_CASE(linspace_with_delta_generates_int_vector)\n{\n    double min, max, delta;\n\n    min = 0, max = 0, delta = 0;\n    auto vec = utils::stds::linspace(min, max, delta);\n    BOOST_REQUIRE_EQUAL(vec.size(), 0);\n\n\n    min = 1, max = 1, delta = 1;\n    vec = utils::stds::linspace(min, max, delta);\n    BOOST_REQUIRE_EQUAL(vec.size(), 1);\n    BOOST_CHECK_EQUAL(vec[0], min);\n\n    min = 0, max = 1, delta = 1;\n    vec = utils::stds::linspace(min, max, delta);\n    BOOST_REQUIRE_EQUAL(vec.size(), 2);\n    BOOST_CHECK_EQUAL(vec[0], min);\n    BOOST_CHECK_EQUAL(vec[1], max);\n\n    min = 0, max = 9, delta = 1;\n    vec = utils::stds::linspace(min, max, delta);\n    BOOST_REQUIRE_EQUAL(vec.size(), 10);\n    BOOST_CHECK_EQUAL(vec[0], min);\n    BOOST_CHECK_EQUAL(vec[4], 4);\n    BOOST_CHECK_EQUAL(vec[5], 5);\n    BOOST_CHECK_EQUAL(vec[9], max);\n\n}\n\n\n\n", "meta": {"hexsha": "e620954809ebb9f01aff08d6a5bf0ae6f4401cba", "size": 1966, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit_tests/test_utils_stds_linspace.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_utils_stds_linspace.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_utils_stds_linspace.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": 22.3409090909, "max_line_length": 62, "alphanum_fraction": 0.6490335707, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.5160119942274266}}
{"text": "/*\n* Bundle adjustment using ceres\n*/\n\n//#define V3DLIB_ENABLE_SUITESPARSE\n#include \"BAHandler.h\"\n\n// #include \"ba/v3d_linear.h\"\n// #include \"ba/v3d_vrmlio.h\"\n// #include \"ba/v3d_metricbundle.h\"\n// #include \"ba/v3d_stereobundle.h\"\n\n#include \"Camera.h\"\n// #include \"ceres/EigenQuaternionParameterization.h\"\n#include \"datastructs/Data.h\"\n\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n#include <ceres/rotation.h>\n\n#include <Eigen/Eigen>\n\n// using namespace V3D;\nusing namespace std;\nusing namespace cv; \n\n// namespace\n// {\n// \tinline double\n// \tshowErrorStatistics(double const f0,\n// \t\t\t\t\t\tStdDistortionFunction const& distortion,\n// \t\t\t\t\t\tvector<CameraMatrix> const& cams,\n// \t\t\t\t\t\tvector<Vector3d> const& Xs,\n// \t\t\t\t\t\tvector<Vector2d> const& measurements,\n// \t\t\t\t\t\tvector<int> const& correspondingView,\n// \t\t\t\t\t\tvector<int> const& correspondingPoint)\n// \t{\n// \t\tint const K = measurements.size();\n\t\t\n// \t\tdouble meanReprojectionError = 0.0;\n// \t\tfor (int k = 0; k < K; ++k)\n// \t\t{\n// \t\t\tint const i = correspondingView[k];\n// \t\t\tint const j = correspondingPoint[k];\n// \t\t\tVector2d p = cams[i].projectPoint(distortion, Xs[j]);\n\t\t\t\n// \t\t\tdouble reprojectionError = norm_L2(f0 * (p - measurements[k]));\n// \t\t\tmeanReprojectionError += reprojectionError;\n// \t\t}\n// \t\t//cout << \"mean reprojection error (in pixels): \" << meanReprojectionError/K << endl;\n\n// \t\treturn meanReprojectionError/K;\n// \t}\n// }\n\n// void BAHandler::adjustBundle(){\n\n// \tcout<<\"Bundle Adjust Method: no copy\"<<endl;\n// \tData \t\t&data \t= Data::GetInstance();\n// \tCamera \t\t&camera\t= Camera::GetInstance();\n// \t//important\n// \tdata.deleteTrashes();\n\n// \tMat &cam_matrix \t\t\t\t= camera.camMat;\n// \tMat &distortion_coefficients\t= camera.distortionMat;\n\n\n// \tvector<int>\t\t\timgIdxs;\n// \tvector<int>\t\t\tpt3DIdxs;\n// \tdouble ppx,ppy;\n// \tdouble \tmeanErrorBefore, meanErrorAfter;\n\n// \tint N = data.countFrames(), M = data.countLandMarks(), K = data.countMeasurements();\n// \tcout << \"N (cams) = \" << N << \" M (points) = \" << M << \" K (measurements) = \" << K << endl;\n\n// \tStdDistortionFunction distortion;\n// \tdistortion.k1 = distortion_coefficients.at<double>(0,0);\n// \tdistortion.k2 = distortion_coefficients.at<double>(0,1);\n// \tdistortion.p1 = distortion_coefficients.at<double>(0,2);\n// \tdistortion.p2 = distortion_coefficients.at<double>(0,3);\n\n\n// \t//convert camera intrinsics to BA datastructs\n// \tMatrix3x3d KMat;\n// \tmakeIdentityMatrix(KMat);\n// \tKMat[0][0] = cam_matrix.at<double>(0,0); //fx\n// \tKMat[1][1] = cam_matrix.at<double>(1,1); //fy\n// \tKMat[0][1] = cam_matrix.at<double>(0,1); //skew\n// \tKMat[0][2] = cam_matrix.at<double>(0,2); //ppx\n// \tKMat[1][2] = cam_matrix.at<double>(1,2); //ppy\n\n// \tppx = KMat[0][2];\n// \tppy = KMat[1][2];\n\n// \tdouble const f0 = KMat[0][0];\n// \tdouble const f0_inv = 1.0/f0;\n\n// \t//cout << \"Cam = \"<<endl;\n// \t//displayMatrix(KMat);\n\n// \tMatrix3x3d Knorm = KMat;\n// \t// Normalize the intrinsic to have unit focal length.\n// \tscaleMatrixIP(f0_inv, Knorm);\n// \tKnorm[2][2] = 1.0;\n\n// \t//convert 3D point cloud to BA datastructs\n// \tconst vector<LandMark::Ptr> &lms = data.getLandMarks();\n// \tmap<LandMark::Ptr, int, Data::LandMarkPtrCompare> lm2idx;\n// \tvector<Vector3d > Xs;\n// \tint idx = 0;\n// \tXs.reserve(lms.size());\n// \tfor (vector<LandMark::Ptr>::const_iterator it = lms.begin(); it!=lms.end(); ++it, ++idx)\n// \t{\n// \t\tassert(!(*it)->deleted);\n// \t\tXs.push_back(Vector3d((*it)->pt[0], (*it)->pt[1], (*it)->pt[2]));\n// \t\tlm2idx[*it] = idx;\n// \t}\n\n\n// \t//convert cameras to BA datastructs\n// \tconst vector<Frame::Ptr> &frames = data.getFrames();\n// \tmap<Frame::Ptr, int, Data::FramePtrCompare> frame2idx;\n// \tvector<CameraMatrix> cams;\n// \tcams.reserve(frames.size());\n// \tidx = 0;\n// \tfor (vector<Frame::Ptr>::const_iterator it = frames.begin(); it!=frames.end(); ++it, ++idx)\n// \t{\n// \t\tMatrix3x3d R;\n// \t\tVector3d T;\n\n// \t\tMatx34d P = (*it)->getCVTransform();\n\n// \t\tR[0][0] = P(0,0); R[0][1] = P(0,1); R[0][2] = P(0,2); T[0] = P(0,3);\n// \t\tR[1][0] = P(1,0); R[1][1] = P(1,1); R[1][2] = P(1,2); T[1] = P(1,3);\n// \t\tR[2][0] = P(2,0); R[2][1] = P(2,1); R[2][2] = P(2,2); T[2] = P(2,3);\n\n// \t\tCameraMatrix cam;\n// \t\tcam.setIntrinsic(Knorm);\n// \t\tcam.setRotation(R);\n// \t\tcam.setTranslation(T);\n// \t\tcams.push_back(cam);\n// \t\tframe2idx[*it] = idx;\n// \t}\n\n\n// \tconst vector<Measurement::Ptr> &ms = data.getMeasurements();\n// \tvector<Vector2d > measurements;\n// \tvector<int> correspondingView; \t\t//corresponding camera mat idx\n// \tvector<int> correspondingPoint;\t\t//corresponding 3d point idx\n// \tmeasurements.reserve(K);\n// \tcorrespondingView.reserve(K);\n// \tcorrespondingPoint.reserve(K);\n\n// \t//convert 2D measurements to BA datastructs\n// \tfor (vector<Measurement::Ptr>::const_iterator it = ms.begin(); it!=ms.end(); ++it){\n// \t\tassert(!(*it)->deleted);\n// \t\tLandMark::Ptr &lm = (*it)->landmark;\n// \t\tFrame::Ptr &frame = (*it)->frame;\n// \t\tPoint2f &xy\t\t  = frame->kpts[(*it)->featureIdx].pt;\n// \t\tmeasurements.push_back(Vector2d(xy.x*f0_inv, xy.y*f0_inv));\n// \t\tcorrespondingView.push_back(frame2idx[frame]);\n// \t\tcorrespondingPoint.push_back(lm2idx[lm]);\n// \t}\n\n// \tmeanErrorBefore = showErrorStatistics(f0, distortion, cams, Xs, measurements, correspondingView, correspondingPoint);\n\n// \tdouble const inlierThreshold = 2.0 / fabs(f0);\n\n// \tMatrix3x3d K0 = cams[0].getIntrinsic();\n// \t//cout << \"K0 = \"; displayMatrix(K0);\n\n// \tbool good_adjustment = false;\n// \t{\n// \t\tScopedBundleExtrinsicNormalizer extNorm(cams, Xs);\n// \t\tScopedBundleIntrinsicNormalizer intNorm(cams,measurements,correspondingView);\n// \t\tCommonInternalsMetricBundleOptimizer opt(V3D::FULL_BUNDLE_FOCAL_LENGTH_PP, inlierThreshold, K0, distortion, cams, Xs,\n// \t\t\t\t\t\t\t\t\t\t\t\t measurements, correspondingView, correspondingPoint);\n\n// \t\topt.tau = 1e-3;\n// \t\topt.maxIterations = 50;\n// \t\topt.minimize();\n\n// \t\tcout << \"optimizer status = \" << opt.status << endl;\n\n// \t\tgood_adjustment = (opt.status != 2);\n// \t}\n\n// \t//cout << \"refined K = \"; displayMatrix(K0);\n\n// \tfor (int i = 0; i < N; ++i) cams[i].setIntrinsic(K0);\n\n// \tMatrix3x3d Knew = K0;\n// \tscaleMatrixIP(f0, Knew);\n// \tKnew[2][2] = 1.0;\n\n// \t//cout << \"Cam new = \"<<endl;\n// \t//displayMatrix(Knew);\n\n// \tmeanErrorAfter = showErrorStatistics(f0, distortion, cams, Xs, measurements, correspondingView, correspondingPoint);\n\n// \tif(good_adjustment) {\n\n// \t\t//extract 3D points\n// \t\tfor (unsigned int j = 0; j < Xs.size(); ++j)\n// \t\t{\n// \t\t\tlms[j]->pt[0] = Xs[j][0];\n// \t\t\tlms[j]->pt[1] = Xs[j][1];\n// \t\t\tlms[j]->pt[2] = Xs[j][2];\n// \t\t}\n\n// \t\t//extract adjusted cameras\n// \t\tfor (unsigned int i = 0; i < N; ++i)\n// \t\t{\n// \t\t\tMatrix3x3d R = cams[i].getRotation();\n// \t\t\tVector3d T = cams[i].getTranslation();\n\n// \t\t\tEigen::Matrix3d R_eigen;\n// \t\t\tEigen::Vector3d t_eigen;\n// \t\t\tfor(unsigned int r = 0; r<3; r++){\n// \t\t\t\tfor(unsigned int c = 0; c<3; c++){\n// \t\t\t\t\tR_eigen(r,c) = R[r][c];\n// \t\t\t\t}\n// \t\t\t\tt_eigen(r) = T[r];\n// \t\t\t}\n// \t\t\tframes[i]->rotation = Eigen::Quaterniond(R_eigen);\n// \t\t\tframes[i]->position = -R_eigen.transpose()*t_eigen;\n// \t\t}\n\n// \t\tcam_matrix.at<double>(0,0) = Knew[0][0];\n// \t\tcam_matrix.at<double>(0,1) = Knew[0][1];\n// \t\tcam_matrix.at<double>(0,2) = Knew[0][2];\n// \t\tcam_matrix.at<double>(1,1) = Knew[1][1];\n// \t\tcam_matrix.at<double>(1,2) = Knew[1][2];\n// \t}\n\n// \tcout<<\"focal :\"<<f0<<\" -> \"<<Knew[0][0]<<endl;\n// \tcout<<\"center:(\"<<ppx<<\",\"<<ppy<<\") -> (\"<<Knew[0][2]<<\",\"<<Knew[1][2]<<\")\"<<endl;\n// \tcout<<\"error :\"<<meanErrorBefore<<\" -> \"<<meanErrorAfter<<endl;\n// }\n\nstruct ReprojectionError {\n\t// (u, v): the position of the observation with respect to the image top left corner\n\t  // u is rightward positive and v is downward positive\n\tReprojectionError(double observed_x, double observed_y, double f, double ppx, double ppy)\n\t:observed_x(observed_x)\n\t,observed_y(observed_y)\n\t,f(f)\n\t,ppx(ppx)\n\t,ppy(ppy)\n\t{\n\n\t}\n\n\t  template <typename T>\n\t  bool operator()(const T* const camera_rotation,\n\t\t\t  \t  \t  const T* const camera_translation,\n\t                  const T* const point,\n\t                  T* residuals) const {\n\n\t\t  //XXX: quaternion must be normalized before!\n\t\t  // Map the T* array to an Eigen Quaternion (no copy)\n\t\t  Eigen::Quaternion<T> q = Eigen::Map<const Eigen::Quaternion<T>>(camera_rotation);\n\n\t\t  // Map T* to Eigen Vector3 (no copy)\n\t\t  Eigen::Matrix<T,3,1> t = Eigen::Map<const Eigen::Matrix<T,3,1>>(camera_translation);\n\n\t\t  //copy point data\n\t\t  Eigen::Matrix<T,3,1> p;\n\t\t  p << T(point[0]), T(point[1]), T(point[2]);\n\n\t\t  //transform point to camera view space\n\t\t  p = q*(p-t);\t//q is rotation of camera back to world axis, t is position of camera in world (opengv convention)\n\t\t  //p = q*p+t\t\t//q is rotation of camera back to world axis, t is translation of camera before rotation (opencv convention)\n\n\t    // Compute the center of distortion. The sign change comes from\n\t    // the camera model that Noah Snavely's Bundler assumes, whereby\n\t    // the camera coordinate system has a negative z axis.\n\t    const T xp = p[0] / p[2];\n\t    const T yp = p[1] / p[2];\n\n\t    // Compute final projected point position.\n\t    const T predicted_x = f * xp+ppx;\n\t    const T predicted_y = f * yp+ppy;\n\t    //const T predicted_x = -f * xp+ppx;\n\t    //const T predicted_y = f * yp+ppy;\n\n\t    // The error is the difference between the predicted and observed position.\n\t    residuals[0] = predicted_x - observed_x;\n\t    residuals[1] = predicted_y - observed_y;\n\n\t    return true;\n\t  }\n\n\t  // Factory to hide the construction of the CostFunction object from\n\t  // the client code.\n\t  static ceres::CostFunction* Create(const double observed_x,\n\t                                     const double observed_y,\n\t\t\t\t\t\t\t\t\t\t const double f,\n\t\t\t\t\t\t\t\t\t\t const double ppx,\n\t\t\t\t\t\t\t\t\t\t const double ppy) {\n\t    return (new ceres::AutoDiffCostFunction<\n\t    \t\tReprojectionError, 2, 4, 3, 3>(\n\t                new ReprojectionError(observed_x,\n\t                                      observed_y,\n\t\t\t\t\t\t\t\t\t\t  f,\n\t\t\t\t\t\t\t\t\t\t  ppx,\n\t\t\t\t\t\t\t\t\t\t  ppy)));\n\t  }\n\n\t  double observed_x;\n\t  double observed_y;\n\t  //since we fix camera paramters, use them as residule rather than parameter\n\t  //this avoids unnecessary jacobian calculation which speeds up a lot\n\t  double f;\n\t  double ppx;\n\t  double ppy;\n};\n\n\n// struct OctaveAwareReprojectionError {\n// \t// (u, v): the position of the observation with respect to the image top left corner\n// \t  // u is rightward positive and v is downward positive\n// \tOctaveAwareReprojectionError(double observed_x, double observed_y, double f, double ppx, double ppy, double octave)\n// \t:observed_x(observed_x)\n// \t,observed_y(observed_y)\n// \t,f(f)\n// \t,ppx(ppx)\n// \t,ppy(ppy)\n// \t,octave(octave)\n// \t{\n\n// \t}\n\n// \t  template <typename T>\n// \t  bool operator()(const T* const camera_rotation,\n// \t\t\t  \t  \t  const T* const camera_translation,\n// \t                  const T* const point,\n// \t                  T* residuals) const {\n\n// \t\t  //XXX: quaternion must be normalized before!\n// \t\t  // Map the T* array to an Eigen Quaternion (no copy)\n// \t\t  Eigen::Quaternion<T> q = Eigen::Map<const Eigen::Quaternion<T>>(camera_rotation);\n\n// \t\t  // Map T* to Eigen Vector3 (no copy)\n// \t\t  Eigen::Matrix<T,3,1> t = Eigen::Map<const Eigen::Matrix<T,3,1>>(camera_translation);\n\n// \t\t  //copy point data\n// \t\t  Eigen::Matrix<T,3,1> p;\n// \t\t  p << T(point[0]), T(point[1]), T(point[2]);\n\n// \t\t  //transform point to camera view space\n// \t\t  p = q*(p-t);\t//q is rotation of camera back to world axis, t is position of camera in world (opengv convention)\n// \t\t  //p = q*p+t\t\t//q is rotation of camera back to world axis, t is translation of camera before rotation (opencv convention)\n\n// \t    // Compute the center of distortion. The sign change comes from\n// \t    // the camera model that Noah Snavely's Bundler assumes, whereby\n// \t    // the camera coordinate system has a negative z axis.\n// \t    const T xp = p[0] / p[2];\n// \t    const T yp = p[1] / p[2];\n\n// \t    // Compute final projected point position.\n// \t    const T predicted_x = f * xp+ppx;\n// \t    const T predicted_y = f * yp+ppy;\n// \t    //const T predicted_x = -f * xp+ppx;\n// \t    //const T predicted_y = f * yp+ppy;\n\n// \t    // The error is the difference between the predicted and observed position.\n// \t    residuals[0] = (predicted_x - observed_x)/octave;\n// \t    residuals[1] = (predicted_y - observed_y)/octave;\n\n// \t    return true;\n// \t  }\n\n// \t  // Factory to hide the construction of the CostFunction object from\n// \t  // the client code.\n// \t  static ceres::CostFunction* Create(const double observed_x,\n// \t                                     const double observed_y,\n// \t\t\t\t\t\t\t\t\t\t const double f,\n// \t\t\t\t\t\t\t\t\t\t const double ppx,\n// \t\t\t\t\t\t\t\t\t\t const double ppy,\n// \t\t\t\t\t\t\t\t\t\t const double octave) {\n// \t    return (new ceres::AutoDiffCostFunction<\n// \t    \t\tOctaveAwareReprojectionError, 2, 4, 3, 3>(\n// \t                new OctaveAwareReprojectionError(observed_x,\n// \t                                      observed_y,\n// \t\t\t\t\t\t\t\t\t\t  f,\n// \t\t\t\t\t\t\t\t\t\t  ppx,\n// \t\t\t\t\t\t\t\t\t\t  ppy,\n// \t\t\t\t\t\t\t\t\t\t  octave)));\n// \t  }\n\n// \t  double observed_x;\n// \t  double observed_y;\n// \t  //since we fix camera paramters, use them as residule rather than parameter\n// \t  //this avoids unnecessary jacobian calculation which speeds up a lot\n// \t  double f;\n// \t  double ppx;\n// \t  double ppy;\n// \t  double octave;\n// };\n\n\nvoid BAHandler::adjustBundle_ceres_nocopy(){\n\tcout<<\"Bundle Adjust Method: no copy\"<<endl;\n\n\tclock_t\t\t\t\ttime;\n\tdouble\t\t\t\tt_preprocess;\n\n\ttime\t\t\t\t= clock();\n\tData \t\t&data \t= Data::GetInstance();\n\tCamera \t\t&camera\t= Camera::GetInstance();\n\t//important\n\tdata.deleteTrashes();\n\n\tdouble intrinsics[3];\n\tintrinsics[0] = camera.getCamFocal();\n\tintrinsics[1] = camera.getCamPrinciple().x;\n\tintrinsics[2] = camera.getCamPrinciple().y;\n\n\tceres::Problem problem;\n\tceres::LocalParameterization *eigenQuaternionParameterization = new ceres::EigenQuaternionParameterization;\n\n\tconst vector<Measurement::Ptr> &ms = data.getMeasurements();\n\tfor(vector<Measurement::Ptr>::const_iterator it = ms.begin(); it!=ms.end(); ++it){\n\n\t\tassert(!((*it)->deleted));\n\n\t\tFrame::Ptr \t\t&f \t= (*it)->frame;\n\t\tLandMark::Ptr \t&p \t= (*it)->landmark;\n\t\tint\t\t\t&feIdx\t= (*it)->featureIdx;\n\n\t\tPoint2f &pt2D \t= f->kpts[feIdx].pt;\n\t\tdouble *q\t\t= f->rotation.coeffs().data();\n\t\tdouble *t\t\t= f->position.data();\n\t\tdouble *point\t= p->pt.data();\n\n\t\tceres::CostFunction* cost_function = ReprojectionError::Create( pt2D.x, pt2D.y, intrinsics[0], intrinsics[1], intrinsics[2]);\n\t\tproblem.AddResidualBlock(cost_function, NULL, q, t, point);\n\t\tproblem.SetParameterization(q,eigenQuaternionParameterization);\n\t\tif(f->fixed){\n\t\t\t//fix first camera transformation\n\t\t\tproblem.SetParameterBlockConstant(q);\n\t\t\tproblem.SetParameterBlockConstant(t);\n\t\t}\n\t}\n\n\tt_preprocess = double(clock()-time) / CLOCKS_PER_SEC;\n\n\t// Set a few options\n\tceres::Solver::Options options;\n\toptions.use_nonmonotonic_steps = true;\n\toptions.preconditioner_type = ceres::SCHUR_JACOBI;\n\toptions.linear_solver_type = ceres::SPARSE_SCHUR; //ceres::ITERATIVE_SCHUR; //\n\toptions.max_num_iterations = 100;\n\t//options.max_solver_time_in_seconds = 0.015;\n\n\tceres::Solver::Summary summary;\n\tceres::Solve(options, &problem, &summary);\n\n\t//std::cout << \"Final report:\\n\" << summary.FullReport();\n\tstd::cout << \"Time(s) preprocess :\"<<t_preprocess<<endl;\n\tstd::cout << \"Time(s) BA :\"<<summary.total_time_in_seconds<<endl;\n\n\n}\n\nvoid BAHandler::adjustBundle_ceres_local_nocopy(){\n\n\tcout<<\"Bundle Adjust Method: local no copy\"<<endl;\n\n\tclock_t\t\t\t\ttime;\n\tdouble\t\t\t\tt_preprocess;\n\n\ttime\t\t\t\t= clock();\n\tData \t\t&data \t= Data::GetInstance();\n\tCamera \t\t&camera\t= Camera::GetInstance();\n\t//important\n\tdata.deleteTrashes();\n\n\n\tdouble intrinsics[3];\n\tintrinsics[0] = camera.getCamFocal();\n\tintrinsics[1] = camera.getCamPrinciple().x;\n\tintrinsics[2] = camera.getCamPrinciple().y;\n\n\tceres::Problem problem;\n\tceres::LocalParameterization *eigenQuaternionParameterization = new ceres::EigenQuaternionParameterization;\n\n\n\tif(data.countFrames()<1) return;\n\t//fix all frames other than the last frame\n\tdata.fixAllFrames();\n\tFrame::Ptr lastAddedFrame = data.getFrames().back();\n\tlastAddedFrame -> fixed = false;\n\n\t//for all measures in last added frame\n\tconst vector<Measurement::Ptr> ms = data.getMeasurements(lastAddedFrame);\n\tfor(vector<Measurement::Ptr>::const_iterator it = ms.begin(); it!=ms.end(); ++it){\n\t\tLandMark::Ptr &lmk = (*it)->landmark;\n\t\t//for all measurements tied to this landmark\n\t\tvector<Measurement::Ptr> lmkms = data.getMeasurements(lmk);\n\t\tfor(vector<Measurement::Ptr>::const_iterator jt = lmkms.begin(); jt!=lmkms.end(); ++jt){\n\t\t\tassert(!((*jt)->deleted));\n\n\t\t\tFrame::Ptr \t\t&f \t= (*jt)->frame;\n\t\t\tLandMark::Ptr \t&p \t= (*jt)->landmark;\n\t\t\tint\t\t\t&feIdx\t= (*jt)->featureIdx;\n\n\t\t\tPoint2f &pt2D \t= f->kpts[feIdx].pt;\n\t\t\tdouble *q\t\t= f->rotation.coeffs().data();\n\t\t\tdouble *t\t\t= f->position.data();\n\t\t\tdouble *point\t= p->pt.data();\n\n\t\t\tceres::CostFunction* cost_function = ReprojectionError::Create( pt2D.x, pt2D.y, intrinsics[0], intrinsics[1], intrinsics[2]);\n\t\t\tproblem.AddResidualBlock(cost_function, NULL, q, t, point);\n\t\t\tproblem.SetParameterization(q,eigenQuaternionParameterization);\n\t\t\tif(f->fixed){\n\t\t\t\tproblem.SetParameterBlockConstant(q);\n\t\t\t\tproblem.SetParameterBlockConstant(t);\n\t\t\t}\n\t\t}\n\t}\n\n\tt_preprocess = double(clock()-time) / CLOCKS_PER_SEC;\n\n\t// Set a few options\n\tceres::Solver::Options options;\n\toptions.use_nonmonotonic_steps = true;\n\toptions.preconditioner_type = ceres::SCHUR_JACOBI;\n\toptions.linear_solver_type = ceres::SPARSE_SCHUR; //ceres::ITERATIVE_SCHUR; //\n\toptions.max_num_iterations = 100;\n\t//options.max_solver_time_in_seconds = 0.015;\n\n\tceres::Solver::Summary summary;\n\tceres::Solve(options, &problem, &summary);\n\n\t//std::cout << \"Final report:\\n\" << summary.FullReport();\n\tstd::cout << \"Time(s) preprocess :\"<<t_preprocess<<endl;\n\tstd::cout << \"Time(s) BA :\"<<summary.total_time_in_seconds<<endl;\n}\n\nvoid BAHandler::adjustBundle_ceres_local_nocopy(vector<Measurement::Ptr> &ms){\n\n\tcout<<\"Bundle Adjust Method: local no copy\"<<endl;\n\n\tclock_t\t\t\t\ttime;\n\tdouble\t\t\t\tt_preprocess;\n\n\ttime\t\t\t\t= clock();\n\tData \t\t&data \t= Data::GetInstance();\n\tCamera \t\t&camera\t= Camera::GetInstance();\n\t//important\n\tdata.deleteTrashes();\n\n\n\tdouble intrinsics[3];\n\tintrinsics[0] = camera.getCamFocal();\n\tintrinsics[1] = camera.getCamPrinciple().x;\n\tintrinsics[2] = camera.getCamPrinciple().y;\n\n\tceres::Problem problem;\n\tceres::LocalParameterization *eigenQuaternionParameterization = new ceres::EigenQuaternionParameterization;\n\n\n\tif(data.countFrames()<1) return;\n\tif(ms.empty()) return;\n\t//fix all frames, the provided measurements should all generate from a frame that is not in data\n\tdata.fixAllFrames();\n\t//get measures already added to data if exists\n\tFrame::Ptr &mFrame = ms[0]->frame;\n\t//unfix this measure frame\n\tmFrame->fixed = false;\n\n\t//for all given measures\n\tfor(vector<Measurement::Ptr>::const_iterator it = ms.begin(); it!=ms.end(); ++it){\n\t\tassert((*it)->frame.get() == mFrame.get());\n\t\tLandMark::Ptr &lmk = (*it)->landmark;\n\t\t//for all measurements tied to this landmark\n\t\tvector<Measurement::Ptr> lmkms = data.getMeasurements(lmk);\n\t\tfor(vector<Measurement::Ptr>::iterator jt = lmkms.begin(); jt!=lmkms.end(); ++jt){\n\t\t\tassert(!((*jt)->deleted));\n\n\t\t\tFrame::Ptr \t\t&f \t= (*jt)->frame;\n\t\t\tLandMark::Ptr \t&p \t= (*jt)->landmark;\n\t\t\tint\t\t\t&feIdx\t= (*jt)->featureIdx;\n\n\t\t\tPoint2f &pt2D \t= f->kpts[feIdx].pt;\n\t\t\tdouble *q\t\t= f->rotation.coeffs().data();\n\t\t\tdouble *t\t\t= f->position.data();\n\t\t\tdouble *point\t= p->pt.data();\n\n\t\t\tceres::CostFunction* cost_function = ReprojectionError::Create( pt2D.x, pt2D.y, intrinsics[0], intrinsics[1], intrinsics[2]);\n\t\t\tproblem.AddResidualBlock(cost_function, NULL, q, t, point);\n\t\t\tproblem.SetParameterization(q,eigenQuaternionParameterization);\n\t\t\tif(f->fixed){\n\t\t\t\tproblem.SetParameterBlockConstant(q);\n\t\t\t\tproblem.SetParameterBlockConstant(t);\n\t\t\t}\n\t\t}\n\t}\n\n\t//if mFrame was already added to data, we add these measures as well for bundle adjustment\n\tvector<Measurement::Ptr> dataMs = data.getMeasurements(mFrame);\n\tfor(vector<Measurement::Ptr>::const_iterator it = dataMs.begin(); it!=dataMs.end(); ++it){\n\t\tassert((*it)->frame.get() == mFrame.get());\n\t\tLandMark::Ptr &lmk = (*it)->landmark;\n\t\t//for all measurements tied to this landmark\n\t\tvector<Measurement::Ptr> lmkms = data.getMeasurements(lmk);\n\t\tfor(vector<Measurement::Ptr>::iterator jt = lmkms.begin(); jt!=lmkms.end(); ++jt){\n\t\t\tassert(!((*jt)->deleted));\n\n\t\t\tFrame::Ptr \t\t&f \t= (*jt)->frame;\n\t\t\tLandMark::Ptr \t&p \t= (*jt)->landmark;\n\t\t\tint\t\t\t&feIdx\t= (*jt)->featureIdx;\n\n\t\t\tPoint2f &pt2D \t= f->kpts[feIdx].pt;\n\t\t\tdouble *q\t\t= f->rotation.coeffs().data();\n\t\t\tdouble *t\t\t= f->position.data();\n\t\t\tdouble *point\t= p->pt.data();\n\n\t\t\tceres::CostFunction* cost_function = ReprojectionError::Create( pt2D.x, pt2D.y, intrinsics[0], intrinsics[1], intrinsics[2]);\n\t\t\tproblem.AddResidualBlock(cost_function, NULL, q, t, point);\n\t\t\tproblem.SetParameterization(q,eigenQuaternionParameterization);\n\t\t\tif(f->fixed){\n\t\t\t\tproblem.SetParameterBlockConstant(q);\n\t\t\t\tproblem.SetParameterBlockConstant(t);\n\t\t\t}\n\t\t}\n\t}\n\n\n\tt_preprocess = double(clock()-time) / CLOCKS_PER_SEC;\n\n\t// Set a few options\n\tceres::Solver::Options options;\n\toptions.use_nonmonotonic_steps = true;\n\toptions.preconditioner_type = ceres::SCHUR_JACOBI;\n\toptions.linear_solver_type = ceres::SPARSE_SCHUR; //ceres::ITERATIVE_SCHUR; //\n\toptions.max_num_iterations = 100;\n\t//options.max_solver_time_in_seconds = 0.015;\n\n\tceres::Solver::Summary summary;\n\tceres::Solve(options, &problem, &summary);\n\n\t//std::cout << \"Final report:\\n\" << summary.FullReport();\n\tstd::cout << \"Time(s) preprocess :\"<<t_preprocess<<endl;\n\tstd::cout << \"Time(s) BA :\"<<summary.total_time_in_seconds<<endl;\n}\n\n// void BAHandler::adjustBundle_ceres_local_fixPoints_nocopy(vector<Measurement::Ptr> &ms){\n\n// \tcout<<\"Bundle Adjust Method: local fix points no copy\"<<endl;\n\n// \tclock_t\t\t\t\ttime;\n// \tdouble\t\t\t\tt_preprocess;\n\n// \ttime\t\t\t\t= clock();\n// \tData \t\t&data \t= Data::GetInstance();\n// \tCamera \t\t&camera\t= Camera::GetInstance();\n// \t//important\n// \tdata.deleteTrashes();\n\n\n// \tdouble intrinsics[3];\n// \tintrinsics[0] = camera.getCamFocal();\n// \tintrinsics[1] = camera.getCamPrinciple().x;\n// \tintrinsics[2] = camera.getCamPrinciple().y;\n\n// \tceres::Problem problem;\n// \tceres::LocalParameterization *eigenQuaternionParameterization = new ceres::EigenQuaternionParameterization;\n\n\n// \tif(data.countFrames()<1) return;\n// \tif(ms.empty()) return;\n\n\n// \t//for all given measures\n// \tfor(vector<Measurement::Ptr>::const_iterator it = ms.begin(); it!=ms.end(); ++it){\n\n// \t\tFrame::Ptr \t\t&f \t= (*it)->frame;\n// \t\tLandMark::Ptr \t&p \t= (*it)->landmark;\n// \t\tint\t\t\t&feIdx\t= (*it)->featureIdx;\n// \t\tdouble \t\toct\t\t= (double) (f->kpts[feIdx].octave + 1);\n\n// \t\tPoint2f &pt2D \t= f->kpts[feIdx].pt;\n// \t\tdouble *q\t\t= f->rotation.coeffs().data();\n// \t\tdouble *t\t\t= f->position.data();\n// \t\tdouble *point\t= p->pt.data();\n\n// \t\tceres::CostFunction* cost_function = OctaveAwareReprojectionError::Create( pt2D.x, pt2D.y, intrinsics[0], intrinsics[1], intrinsics[2], oct);\n// \t\tproblem.AddResidualBlock(cost_function, NULL, q, t, point);\n// \t\tproblem.SetParameterization(q,eigenQuaternionParameterization);\n// \t\tproblem.SetParameterBlockConstant(point);\n\n// \t}\n\n\n// /*\n\n// \t//fix all frames, the provided measurements should all generate from a frame that is not in data\n// \tdata.fixAllFrames();\n// \t//get measures already added to data if exists\n// \tFrame::Ptr &mFrame = ms[0]->frame;\n// \t//unfix this measure frame\n// \tmFrame->fixed = false;\n\n// \t//for all given measures\n// \tfor(vector<Measurement::Ptr>::const_iterator it = ms.begin(); it!=ms.end(); ++it){\n// \t\tassert((*it)->frame.get() == mFrame.get());\n// \t\tLandMark::Ptr &lmk = (*it)->landmark;\n// \t\t//for all measurements tied to this landmark\n// \t\tvector<Measurement::Ptr> lmkms = data.getMeasurements(lmk);\n// \t\tfor(vector<Measurement::Ptr>::iterator jt = lmkms.begin(); jt!=lmkms.end(); ++jt){\n// \t\t\tassert(!((*jt)->deleted));\n\n// \t\t\tFrame::Ptr \t\t&f \t= (*jt)->frame;\n// \t\t\tLandMark::Ptr \t&p \t= (*jt)->landmark;\n// \t\t\tint\t\t\t&feIdx\t= (*jt)->featureIdx;\n\n// \t\t\tPoint2f &pt2D \t= f->kpts[feIdx].pt;\n// \t\t\tdouble *q\t\t= f->rotation.coeffs().data();\n// \t\t\tdouble *t\t\t= f->position.data();\n// \t\t\tdouble *point\t= p->pt.data();\n\n// \t\t\tceres::CostFunction* cost_function = ReprojectionError::Create( pt2D.x, pt2D.y, intrinsics[0], intrinsics[1], intrinsics[2]);\n// \t\t\tproblem.AddResidualBlock(cost_function, NULL, q, t, point);\n// \t\t\tproblem.SetParameterization(q,eigenQuaternionParameterization);\n// \t\t\tproblem.SetParameterBlockConstant(point);\n// \t\t\tif(f->fixed){\n// \t\t\t\tproblem.SetParameterBlockConstant(q);\n// \t\t\t\tproblem.SetParameterBlockConstant(t);\n// \t\t\t}\n// \t\t}\n// \t}\n\n// \t//if mFrame was already added to data, we add these measures as well for bundle adjustment\n// \tvector<Measurement::Ptr> dataMs = data.getMeasurements(mFrame);\n// \tfor(vector<Measurement::Ptr>::const_iterator it = dataMs.begin(); it!=dataMs.end(); ++it){\n// \t\tassert((*it)->frame.get() == mFrame.get());\n// \t\tLandMark::Ptr &lmk = (*it)->landmark;\n// \t\t//for all measurements tied to this landmark\n// \t\tvector<Measurement::Ptr> lmkms = data.getMeasurements(lmk);\n// \t\tfor(vector<Measurement::Ptr>::iterator jt = lmkms.begin(); jt!=lmkms.end(); ++jt){\n// \t\t\tassert(!((*jt)->deleted));\n\n// \t\t\tFrame::Ptr \t\t&f \t= (*jt)->frame;\n// \t\t\tLandMark::Ptr \t&p \t= (*jt)->landmark;\n// \t\t\tint\t\t\t&feIdx\t= (*jt)->featureIdx;\n\n// \t\t\tPoint2f &pt2D \t= f->kpts[feIdx].pt;\n// \t\t\tdouble *q\t\t= f->rotation.coeffs().data();\n// \t\t\tdouble *t\t\t= f->position.data();\n// \t\t\tdouble *point\t= p->pt.data();\n\n// \t\t\tceres::CostFunction* cost_function = ReprojectionError::Create( pt2D.x, pt2D.y, intrinsics[0], intrinsics[1], intrinsics[2]);\n// \t\t\tproblem.AddResidualBlock(cost_function, NULL, q, t, point);\n// \t\t\tproblem.SetParameterization(q,eigenQuaternionParameterization);\n// \t\t\tproblem.SetParameterBlockConstant(point);\n// \t\t\tif(f->fixed){\n// \t\t\t\tproblem.SetParameterBlockConstant(q);\n// \t\t\t\tproblem.SetParameterBlockConstant(t);\n// \t\t\t}\n// \t\t}\n// \t}\n// */\n\n// \tt_preprocess = double(clock()-time) / CLOCKS_PER_SEC;\n\n// \t// Set a few options\n// \tceres::Solver::Options options;\n// \toptions.use_nonmonotonic_steps = true;\n// \toptions.preconditioner_type = ceres::SCHUR_JACOBI;\n// \toptions.linear_solver_type = ceres::SPARSE_SCHUR; //ceres::ITERATIVE_SCHUR; //\n// \toptions.max_num_iterations = 100;\n// \t//options.max_solver_time_in_seconds = 0.015;\n\n// \tceres::Solver::Summary summary;\n// \tceres::Solve(options, &problem, &summary);\n\n// \tstd::cout << \"Final report:\\n\" << summary.FullReport();\n// \tstd::cout << \"Time(s) preprocess :\"<<t_preprocess<<endl;\n// \tstd::cout << \"Time(s) BA :\"<<summary.total_time_in_seconds<<endl;\n// }\n\n\n", "meta": {"hexsha": "8547774d773a9fad89b80ee75279ebaa302a69c6", "size": 26703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/BAHandler.cpp", "max_stars_repo_name": "liyinnbw/MSFM", "max_stars_repo_head_hexsha": "b846816594851c84094078586047a0d1f200f166", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-02-02T23:43:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T09:42:05.000Z", "max_issues_repo_path": "src/core/BAHandler.cpp", "max_issues_repo_name": "projectcs2103t/MSFM", "max_issues_repo_head_hexsha": "b846816594851c84094078586047a0d1f200f166", "max_issues_repo_licenses": ["MIT"], "max_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/BAHandler.cpp", "max_forks_repo_name": "projectcs2103t/MSFM", "max_forks_repo_head_hexsha": "b846816594851c84094078586047a0d1f200f166", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T13:24:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-12T13:24:13.000Z", "avg_line_length": 33.8441064639, "max_line_length": 146, "alphanum_fraction": 0.645994832, "num_tokens": 8067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5160119868743932}}
{"text": "#include <boost/config.hpp>\n#include <boost/program_options.hpp>\n#include <opencv2/opencv.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <iostream>\n#include <random>\n#include <sys/time.h>\n#include <exception>\n \nnamespace po = boost::program_options;\n\nstatic int SIZEX = 800;\nstatic int SIZEY = 600;\nstatic int ITER = 20;\nstatic int RADIUS = 15;\nstatic double TEMPERATURE = 2.0;\nstatic double alpha = 0.05; \nstatic int mouse_x, mouse_y;\nstatic bool pressed = false;\nstatic bool run_evolve = false;\nstatic bool DEBUG = false;\n\ninline double double_rand(const double & min, const double & max) \n{\n    static thread_local std::mt19937 generator;\n    std::uniform_real_distribution<double> distribution(min,max);\n    return distribution(generator);\n}\n\nvoid mouse_callback(int event, int x, int y, int flags, void *data)\n{\n    switch(event)\n    {\n        case CV_EVENT_MOUSEMOVE:\n            mouse_x = x;\n            mouse_y = y;\n\n            // printf(\"(%d,%d)\\n\", x, y);\n            break;\n        case CV_EVENT_LBUTTONDOWN:\n            pressed = true;\n            break;\n        case CV_EVENT_LBUTTONUP:\n            pressed = false;\n            break;\n    }\n}\n\nvoid evolve(double **data, double **buffer)\n{\n    // ~ 62 bits of accuracy (as in of conservation only)\n    int i,j;\n    double dr = 1. / SIZEX;\n    double dt = dr * dr;\n    double *u = *data;\n    double *next_state = *buffer;\n    \n    struct timeval start, end;\n    gettimeofday(&start, NULL);\n\n    for(int k = 0; k < ITER; k++)\n    {\n    #pragma omp parallel for private(i, j), shared(u, next_state, dt, dr, alpha)\n        for(i=0; i < SIZEY; i++)\n        {\n            if(i == 0)\n            {\n                next_state[0]= u[0] + alpha * (\n                    u[1] + \n                    u[SIZEX] - \n                    2*u[0]); // j == 0\n\n                next_state[SIZEX - 1]= u[SIZEX - 1] + alpha * (\n                    u[2 * SIZEX -1] + \n                    u[SIZEX - 2] - \n                    2*u[SIZEX - 1]); // j == SIZEX - 1\n\n                for(j = 1; j < SIZEX-1; j++)\n                    next_state[j]= u[j] + alpha * (\n                        u[SIZEX + j] +\n                        u[j + 1] +\n                        u[j - 1] -\n                        3*u[j]);\n            }\n            else if(i == SIZEY - 1)\n            {\n                next_state[i*SIZEX]= u[i*SIZEX] + alpha * (\n                    u[(i-1)*SIZEX] + \n                    u[i*SIZEX + 1] - \n                    2*u[i*SIZEX]); // j == 0\n\n                next_state[i*SIZEX + SIZEX - 1]= u[i*SIZEX + SIZEX - 1] + alpha * (\n                    u[(i-1)*SIZEX + SIZEX - 1] + \n                    u[i*SIZEX + SIZEX - 2] - \n                    2*u[i*SIZEX + SIZEX - 1]); // j == SIZEX - 1\n\n                for(j = 1; j < SIZEX-1; j++)\n                    next_state[i*SIZEX + j]= u[i*SIZEX + j] + alpha * (\n                        u[(i-1)*SIZEX + j] + \n                        u[i*SIZEX + j + 1] + \n                        u[i*SIZEX + j - 1] - \n                        3*u[i*SIZEX + j]);\n            }\n            else\n            {\n                next_state[i * SIZEX]= u[i * SIZEX] + alpha * (\n                    u[(i-1)*SIZEX] + \n                    u[(i+1)*SIZEX] + \n                    u[i*SIZEX + 1] - \n                    3*u[i*SIZEX]); // j == 0\n\n                next_state[i * SIZEX + SIZEX - 1]= u[i * SIZEX + SIZEX - 1] + alpha * (\n                    u[(i-1)*SIZEX + SIZEX - 1] + \n                    u[(i+1)*SIZEX + SIZEX - 1] + \n                    u[i*SIZEX + SIZEX -2] - \n                    3*u[i*SIZEX + SIZEX -1]); // j == SIZEX - 1\n                \n                for(j=1; j < SIZEX-1; j++)\n                    next_state[i*SIZEX + j]= u[i * SIZEX + j] + alpha * (\n                        u[(i-1)*SIZEX + j] +\n                        u[(i+1)*SIZEX + j] +\n                        u[i*SIZEX + j + 1] + \n                        u[i*SIZEX + j - 1] - \n                        4*u[i*SIZEX + j]); \n            }\n\n        }\n        if(k != ITER)\n        {\n            auto tmp = next_state;\n            next_state = u;\n            u = tmp;\n        }\n    }\n    *buffer = *data;\n    *data = next_state;\n\n    if(DEBUG)\n    {\n        double sum = 0.0;\n        #pragma omp parallel for private(i) reduction(+:sum), shared(next_state)\n        for(i=0; i < SIZEY*SIZEX; i++) sum += next_state[i];\n        \n        gettimeofday(&end, NULL);\n        \n        double delta = ((end.tv_sec  - start.tv_sec) * 1000000u + \n            end.tv_usec - start.tv_usec) / 1.e3;\n        printf(\"time (ms): %.5f \\t total: %.3f \\t average: %.4f\\n\", delta, sum, sum / SIZEX / SIZEY);\n        // std::cout << \"time (ms): \" << delta << \"\\t\\ttotal: \" << sum << std::endl;\n    }\n}\n\nvoid parse_arguments(int argc, char** argv)\n{\n    try\n    {\n        po::options_description desc(\"Allowed arguments\");\n        desc.add_options()\n            (\"help,h\", \"print this message.\")\n            (\"height,y\", po::value<int>()->default_value(600), \"set height of the window.\")\n            (\"width,x\", po::value<int>()->default_value(800), \"set width of the window\")\n            (\"alpha,a\", po::value<double>()->default_value(0.05), \"alpha parameter of heat equation.\")\n            (\"iter,i\", po::value<int>()->default_value(20), \"number of iterations per render.\")\n            (\"size,s\", po::value<int>()->default_value(15), \"radius of the brush when drawing.\")\n            (\"temp,t\", po::value<double>()->default_value(1.3), \"temperature of the brush.\")\n            (\"debug,d\", \"debug flag to print extra states' info\");\n\n        po::variables_map vmap;\n        po::store(po::parse_command_line(argc, argv, desc), vmap);\n        po::notify(vmap);\n\n        if(vmap.count(\"help\"))\n        {\n            std::cout << desc;\n            exit(0);\n        }\n        SIZEY = vmap[\"height\"].as<int>();\n        SIZEX = vmap[\"width\"].as<int>();\n        alpha = vmap[\"alpha\"].as<double>();\n        ITER = vmap[\"iter\"].as<int>();\n        RADIUS = vmap[\"size\"].as<int>();\n        TEMPERATURE = vmap[\"temp\"].as<double>();\n        if(vmap.count(\"debug\")) DEBUG = true;\n    }\n    catch(std::exception& e)\n    {\n        std::cerr << \"error: \" << e.what() << std::endl;\n        exit(1);\n    }\n    catch(...)\n    {\n        std::cerr << \"error: Unknown error\" << std::endl;\n        exit(2);\n    }\n}\n\nint main( int argc, char** argv ) \n{\n    parse_arguments(argc, argv);\n\n    double *data = new double[SIZEX*SIZEY];\n    double *buffer = new double[SIZEX*SIZEY];\n    cv::Mat image(SIZEY, SIZEX, CV_64F, data);\n    cv::Mat scaled, color;\n\n    std::string name = \"Heat equation visualization\";\n    cv::namedWindow(name, cv::WINDOW_AUTOSIZE);\n    cv::setMouseCallback(name, mouse_callback, nullptr);\n    int val,x,y;\n\n    auto vcap = new cv::VideoWriter(\"heat2d_video.avi\",\n            CV_FOURCC('M','J','P','G'),\n            120,\n            cv::Size(SIZEX, SIZEY),\n            true);\n\n    while( (val = cv::waitKey(1000/60)) != 27) // escape\n    {\n        if(val == 32) //space\n        {\n            run_evolve = !run_evolve;\n        }\n        if((x != mouse_x || y != mouse_y) && pressed)\n        {\n            x = mouse_x;\n            y = mouse_y;\n            cv::circle(image, cv::Point2d(x,y), RADIUS, cv::Scalar(TEMPERATURE), -1);\n        }\n        image.convertTo(scaled, CV_8UC1,255, 0);\n        cv::applyColorMap(scaled, color, cv::COLORMAP_JET);\n        if(run_evolve)\n        {\n            evolve(&data, &buffer);\n        }\n        image = cv::Mat(SIZEY, SIZEX, CV_64F, data);\n        vcap->write(color);\n        cv::imshow(name, color);\n    }\n\n    vcap->release();\n\n    delete[] data;\n    delete[] buffer;\n    return 0;\n}", "meta": {"hexsha": "62045a1f15139e87017abff5741d445ac4fb5d38", "size": 7630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "heat2d/heat_demo.cpp", "max_stars_repo_name": "abalaki6/sandbox", "max_stars_repo_head_hexsha": "874cf47e9447180a55e54aeae91d9531bb4705a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "heat2d/heat_demo.cpp", "max_issues_repo_name": "abalaki6/sandbox", "max_issues_repo_head_hexsha": "874cf47e9447180a55e54aeae91d9531bb4705a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "heat2d/heat_demo.cpp", "max_forks_repo_name": "abalaki6/sandbox", "max_forks_repo_head_hexsha": "874cf47e9447180a55e54aeae91d9531bb4705a4", "max_forks_repo_licenses": ["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.1428571429, "max_line_length": 102, "alphanum_fraction": 0.4606815203, "num_tokens": 2165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5160119868743931}}
{"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_SAFE_MAX_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SAFE_MAX_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing safe_max capabilities\n\n    Returns a safe_max relative to the input,  i.e. a\n    value which will not overflow when multiplied by the input.\n\n    @par Semantic:\n\n    For every parameter of type @c T\n\n    @code\n    auto r = safe_max(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    auto r = x ? Sqrtvalmax<T>()/abs(x) : Inf<T>();\n    @endcode\n\n    @see Sqrtvalmax, safe_min\n\n  **/\n  Value safe_max(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/safe_max.hpp>\n#include <boost/simd/function/simd/safe_max.hpp>\n\n#endif\n", "meta": {"hexsha": "11e37ab2ae9c7ee34941e6c0ca81213274ef60de", "size": 1157, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/safe_max.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/safe_max.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/safe_max.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": 22.6862745098, "max_line_length": 100, "alphanum_fraction": 0.580812446, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5160119868743931}}
{"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_TAND_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_TAND_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing tand capabilities\n\n    tangent of the input in degrees.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = tand(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r =  sind(x)/cosd(x);\n    @endcode\n\n    As most other trigonometric function tand can be called with a second optional parameter\n    which is a tag on speed and accuracy (see @ref cos for further details)\n\n    @see tan, tanpi\n\n  **/\n  const boost::dispatch::functor<tag::tand_> tand = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/tand.hpp>\n#include <boost/simd/function/simd/tand.hpp>\n\n#endif\n", "meta": {"hexsha": "1615c7de190cf3aa4f1ac2276742c962af973225", "size": 1252, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/tand.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/tand.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/tand.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": 23.1851851852, "max_line_length": 100, "alphanum_fraction": 0.5934504792, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5160119762600899}}
{"text": "#include \"Polygon.h\"\n\n#include <algorithm>\n#include <numeric>\n\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm.hpp>\n\n#include \"Vector.h\"\n#include \"Vertex.h\"\n\nPolygon::classification Polygon::classify(const Plane& plane) const\n{\n\tsize_t count = points.size();\n\n\tsize_t front = 0, back = 0, onplane = 0;\n\n\tfor (const auto& p : points)\n\t{\n\t\tauto test = plane.evaluate(p);\n\n\t\tif (test <= 0) back++;\n\t\tif (test >= 0) front++;\n\t\tif (test == 0) onplane++;\n\t}\n\t\n\tif (onplane == count) return Polygon::classification::onPlane;\n\tif (front == count) return Polygon::classification::front;\n\tif (back == count) return Polygon::classification::back;\n\treturn Polygon::classification::spanning;\n}\n\nVertex Polygon::origin() const\n{\n\treturn std::accumulate(points.cbegin(), points.cend(), Vertex{ 0, 0, 0 }) / double(points.size());\n}\n\nPlane Polygon::plane() const\n{\n\tif(points.size() < 3)\n\t\treturn Plane();\n\t\n\treturn { points[0], points[1], points[2] };\n}\n\nvoid Polygon::rotate(const Vertex & point, const Matrix3d & rotmat)\n{\n\tfor (auto &p : points)\n\t\tp = p.rotate(point, rotmat);\n}\n\nvoid Polygon::move(const Vertex & v)\n{\n\tfor (auto &p : points)\n\t\tp += v;\n}\n\nvoid Polygon::moveTo(const Vertex & p)\n{\n\tVertex dist = p - origin();\n\n\tfor (auto &p : points)\n\t\tp += dist;\n}\n\nvoid Polygon::scale(const Vertex &scale)\n{\n\tthis->scale(origin(), scale);\n}\n\nvoid Polygon::scale(const Vertex& origin, const Vertex& scale)\n{\n\tfor (auto &point : points)\n\t{\n\t\tVertex vec = Vector::diff(origin, point).vec();\n\t\tvec.x(vec.x() * scale.x());\n\t\tvec.y(vec.y() * scale.y());\n\t\tvec.z(vec.z() * scale.z());\n\n\t\tpoint = origin + vec;\n\t}\n}\n\nvoid Polygon::sliceThis(const Plane &plane)\n{\n\tauto[back, front] = slice(plane);\n\tif (!back.points.empty() && !front.points.empty())\n\t\tpoints = back.points;\n}\n\nstd::pair<Polygon, Polygon> Polygon::slice(const Plane& plane) const\n{\n\tauto classification = classify(plane);\n\n\tstd::pair<Polygon, Polygon> ret;\n\n\tif (classification != classification::spanning)\n\t{\n\t\tif (classification == classification::back) ret.first = *this;\n\t\telse if (classification == classification::front) ret.second = *this;\n\t\treturn ret;\n\t}\n\n\tsize_t prev = 0;\n\n\tfor (size_t i = 0; i <= points.size(); i++)\n\t{\n\t\tsize_t index = i % points.size();\n\t\tVertex end = points[index];\n\t\tauto c = plane.evaluate(end);\n\n\t\tif (i > 0 && c != 0 && prev != 0 && c != prev)\n\t\t{\n\t\t\tVertex start = points[i - 1];\n\t\t\tVector line = Vector::diff(start, end);\n\t\t\tVertex intersect = Plane::intersectPoint(plane, line);\n\t\t\tif (!Vertex::isVertex(intersect))\n\t\t\t\tthrow new std::exception(\"Expected intersection\");\n\t\t\tret.first.points.push_back(intersect);\n\t\t\tret.second.points.push_back(intersect);\n\t\t}\n\n\t\tif (i < points.size())\n\t\t{\n\t\t\tif (c <= 0) ret.first.points.push_back(end);\n\t\t\tif (c >= 0) ret.second.points.push_back(end);\n\t\t}\n\n\t\tprev = c;\n\t}\n\n\treturn ret;\n}\n\nvoid Polygon::flip()\n{\n\tstd::reverse(points.begin(), points.end());\n}\n\nvoid Polygon::roundPoints(size_t precision)\n{\n\tdouble exp = std::pow(10, precision);\n\tstd::transform(points.begin(), points.end(), points.begin(), [exp](Vertex v) {\n\t\tv.x(std::round(v.x() * exp) / exp);\n\t\tv.y(std::round(v.y() * exp) / exp);\n\t\tv.z(std::round(v.z() * exp) / exp);\n\t\treturn v;\n\t});\n}\n\nVertex Polygon::intersectPoint(const Vector& line, int flags) const\n{\n\tPlane plane = this->plane();\n\n\tauto point = Plane::intersectPoint(plane, line);\n\n\tVertex defaultRet = (flags & lineBoundsFlag::RETURN_END_ON_FAIL) > 0 ? line.end() : Vertex();\n\n\tflags = flags & lineBoundsFlag::ALLOW_BOTH;\n\n\tif (!Vertex::isVertex(point))\n\t\treturn defaultRet;\n\n\tbool test = testCollision(point);\n\n\tif (!test)\n\t\treturn defaultRet;\n\n\tif (flags != lineBoundsFlag::ALLOW_BOTH)\n\t{\n\t\tdouble position = line.calculatePosition(point);\n\n\t\tif ((lineBoundsFlag::ALLOW_BACK & flags) == 0 && (position < 0 || doubleeq(position, 0)))\n\t\t\treturn defaultRet;\n\n\t\tif ((lineBoundsFlag::ALLOW_FRONT & flags) == 0 && (position > 1 || doubleeq(position, 1)))\n\t\t\treturn defaultRet;\n\t}\n\n\treturn point;\n}\n\nbool Polygon::testCollision(const Vertex& point) const\n{\n\tdouble sum = 0;\n\n\tfor (size_t n = 0; n < points.size(); n++)\n\t{\n\t\tVertex p1 = points[n] - point;\n\t\tVertex p2 = points[(n + 1) % points.size()] - point;\n\n\t\tdouble nom = p1.length() * p2.length();\n\n\t\tif (doubleeq(nom, 0))\n\t\t\treturn false;\n\n\t\tsum += acos(p1.dotProduct(p2) / nom);\n\t}\n\n\treturn doubleeq(sum, M_PI * 2);\n}\n\nbool Polygon::testCollision(const Vector& line, int flags) const\n{\n\t// Ensure method returns NaN vector if it fails so we can test it.\n\tVertex intersect = intersectPoint(line, flags);\n\n\tif (!Vertex::isVertex(intersect))\n\t\treturn false;\n\n\treturn true;\n}\n\nbool Polygon::testCollision(const Polygon& polygon) const\n{\n\tif (&polygon == this)\n\t\treturn true;\n\n\tif (points.size() < 3 || polygon.points.size() < 3)\n\t\treturn false;\n\n\tVertex thisNorm = this->plane().normal();\n\tVertex polyNorm = polygon.plane().normal();\n\n\tif (thisNorm == polyNorm || thisNorm == -polyNorm)\n\t\treturn false;\n\n\tfor (size_t n = 0; n < points.size(); n++)\n\t{\n\t\tVector line = Vector::diff(points[n], points[(n + 1) % points.size()]);\n\n\t\tif (polygon.testCollision(line, ALLOW_NONE))\n\t\t\treturn true;\n\t}\n\n\tfor (size_t n = 0; n < polygon.points.size(); n++)\n\t{\n\t\tVector line = Vector::diff(polygon.points[n], polygon.points[(n + 1) % polygon.points.size()]);\n\n\t\tif (this->testCollision(line, ALLOW_NONE))\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nPolygon::Polygon(const Plane & p)\n{\n\tauto dir = p.closestAxisToNormal();\n\tauto tempV = dir == Vertex::unitZ ? -Vertex::unitY : -Vertex::unitZ;\n\n\tauto normal = p.normal();\n\n\tauto up = tempV.crossProduct(normal).normalize();\n\tauto right = normal.crossProduct(up).normalize();\n\n\tpoints = {\n\t\tp.p1() + right + up,\n\t\tp.p1() - right + up,\n\t\tp.p1() - right - up,\n\t\tp.p1() + right + up\n\t};\n\n\tauto orig = origin();\n\n\tstd::transform(points.begin(), points.end(), points.begin(), [&orig](Vertex v) {\n\t\treturn (v - orig).normalize() * 10'000'000.0 + orig;\n\t});\n\n}\n\nPolygon::Polygon(const std::initializer_list<Vertex>& points)\n\t: points(points)\n{\n}\n", "meta": {"hexsha": "a194e0d2bd4ac009e3e06485ecf0b217ffede005", "size": 5987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rndlevelsource/Polygon.cpp", "max_stars_repo_name": "Telefragged/rndlevelsource", "max_stars_repo_head_hexsha": "17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rndlevelsource/Polygon.cpp", "max_issues_repo_name": "Telefragged/rndlevelsource", "max_issues_repo_head_hexsha": "17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rndlevelsource/Polygon.cpp", "max_forks_repo_name": "Telefragged/rndlevelsource", "max_forks_repo_head_hexsha": "17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1", "max_forks_repo_licenses": ["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.6920289855, "max_line_length": 99, "alphanum_fraction": 0.6458994488, "num_tokens": 1657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5159807078462157}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <math.h>\n#include <stdlib.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#define DADEPT_FLOATING_POINT_TYPE float\n#include <adept_source.h>\n#include <adept_arrays.h>\nusing adept::adouble;\nusing adept::aMatrix;\nusing adept::aVector;\n\nusing adept::Vector;\nusing adept::adouble;\nusing adept::aReal;\n\n//extern \"C\" {\n// from https://github.com/AndrewCarterUK/mnist-neural-network-plain-c\n\n#define MNIST_LABEL_MAGIC 0x00000801\n#define MNIST_IMAGE_MAGIC 0x00000803\n#define MNIST_IMAGE_WIDTH 28\n#define MNIST_IMAGE_HEIGHT 28\n#define MNIST_IMAGE_SIZE MNIST_IMAGE_WIDTH * MNIST_IMAGE_HEIGHT\n#define MNIST_LABELS 10\n\ntypedef struct mnist_label_file_header_t_ {\n    uint32_t magic_number;\n    uint32_t number_of_labels;\n} __attribute__((packed)) mnist_label_file_header_t;\n\ntypedef struct mnist_image_file_header_t_ {\n    uint32_t magic_number;\n    uint32_t number_of_images;\n    uint32_t number_of_rows;\n    uint32_t number_of_columns;\n} __attribute__((packed)) mnist_image_file_header_t;\n\ntypedef struct mnist_image_t_ {\n    uint8_t pixels[MNIST_IMAGE_SIZE];\n} __attribute__((packed)) mnist_image_t;\n\ntypedef struct mnist_dataset_t_ {\n    mnist_image_t * images;\n    uint8_t * labels;\n    uint32_t size;\n} mnist_dataset_t;\n\ntypedef struct neural_network_t_ {\n    float b[MNIST_LABELS];\n    float W[MNIST_LABELS][MNIST_IMAGE_SIZE];\n} neural_network_t;\n\ntypedef struct aneural_network_t_ {\n    adept::FixedArray<float,true,MNIST_LABELS> b;\n    adept::FixedArray<float,true,MNIST_LABELS,MNIST_IMAGE_SIZE> W;\n} aneural_network_t;\n\ntypedef struct neural_network_gradient_t_ {\n    float b_grad[MNIST_LABELS];\n    float W_grad[MNIST_LABELS][MNIST_IMAGE_SIZE];\n} neural_network_gradient_t;\n\n/**\n * Convert from the big endian format in the dataset if we're on a little endian\n * machine.\n */\nuint32_t map_uint32(uint32_t in)\n{\n#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n    return (\n        ((in & 0xFF000000) >> 24) |\n        ((in & 0x00FF0000) >>  8) |\n        ((in & 0x0000FF00) <<  8) |\n        ((in & 0x000000FF) << 24)\n    );\n#else\n    return in;\n#endif\n}\n\n/**\n * Read labels from file.\n * \n * File format: http://yann.lecun.com/exdb/mnist/\n */\nuint8_t * get_labels(const char * path, uint32_t * number_of_labels)\n{\n    FILE * stream;\n    mnist_label_file_header_t header;\n    uint8_t * labels;\n\n    stream = fopen(path, \"rb\");\n\n    if (NULL == stream) {\n        fprintf(stderr, \"Could not open file: %s\\n\", path);\n        return NULL;\n    }\n\n    if (1 != fread(&header, sizeof(mnist_label_file_header_t), 1, stream)) {\n        fprintf(stderr, \"Could not read label file header from: %s\\n\", path);\n        fclose(stream);\n        return NULL;\n    }\n\n    header.magic_number = map_uint32(header.magic_number);\n    header.number_of_labels = map_uint32(header.number_of_labels);\n\n    if (MNIST_LABEL_MAGIC != header.magic_number) {\n        fprintf(stderr, \"Invalid header read from label file: %s (%08X not %08X)\\n\", path, header.magic_number, MNIST_LABEL_MAGIC);\n        fclose(stream);\n        return NULL;\n    }\n\n    *number_of_labels = header.number_of_labels;\n\n    labels = (uint8_t*)malloc(*number_of_labels * sizeof(uint8_t));\n\n    if (labels == NULL) {\n        fprintf(stderr, \"Could not allocated memory for %d labels\\n\", *number_of_labels);\n        fclose(stream);\n        return NULL;\n    }\n\n    if (*number_of_labels != fread(labels, 1, *number_of_labels, stream)) {\n        fprintf(stderr, \"Could not read %d labels from: %s\\n\", *number_of_labels, path);\n        free(labels);\n        fclose(stream);\n        return NULL;\n    }\n\n    fclose(stream);\n\n    return labels;\n}\n\n/**\n * Read images from file.\n * \n * File format: http://yann.lecun.com/exdb/mnist/\n */\nmnist_image_t * get_images(const char * path, uint32_t * number_of_images)\n{\n    FILE * stream;\n    mnist_image_file_header_t header;\n    mnist_image_t * images;\n\n    stream = fopen(path, \"rb\");\n\n    if (NULL == stream) {\n        fprintf(stderr, \"Could not open file: %s\\n\", path);\n        return NULL;\n    }\n\n    if (1 != fread(&header, sizeof(mnist_image_file_header_t), 1, stream)) {\n        fprintf(stderr, \"Could not read image file header from: %s\\n\", path);\n        fclose(stream);\n        return NULL;\n    }\n\n    header.magic_number = map_uint32(header.magic_number);\n    header.number_of_images = map_uint32(header.number_of_images);\n    header.number_of_rows = map_uint32(header.number_of_rows);\n    header.number_of_columns = map_uint32(header.number_of_columns);\n\n    if (MNIST_IMAGE_MAGIC != header.magic_number) {\n        fprintf(stderr, \"Invalid header read from image file: %s (%08X not %08X)\\n\", path, header.magic_number, MNIST_IMAGE_MAGIC);\n        fclose(stream);\n        return NULL;\n    }\n\n    if (MNIST_IMAGE_WIDTH != header.number_of_rows) {\n        fprintf(stderr, \"Invalid number of image rows in image file %s (%d not %d)\\n\", path, header.number_of_rows, MNIST_IMAGE_WIDTH);\n    }\n\n    if (MNIST_IMAGE_HEIGHT != header.number_of_columns) {\n        fprintf(stderr, \"Invalid number of image columns in image file %s (%d not %d)\\n\", path, header.number_of_columns, MNIST_IMAGE_HEIGHT);\n    }\n\n    *number_of_images = header.number_of_images;\n    images = (mnist_image_t*)malloc(*number_of_images * sizeof(mnist_image_t));\n\n    if (images == NULL) {\n        fprintf(stderr, \"Could not allocated memory for %d images\\n\", *number_of_images);\n        fclose(stream);\n        return NULL;\n    }\n\n    if (*number_of_images != fread(images, sizeof(mnist_image_t), *number_of_images, stream)) {\n        fprintf(stderr, \"Could not read %d images from: %s\\n\", *number_of_images, path);\n        free(images);\n        fclose(stream);\n        return NULL;\n    }\n\n    fclose(stream);\n\n    return images;\n}\n\n/**\n * Free all the memory allocated in a dataset. This should not be used on a\n * batched dataset as the memory is allocated to the parent.\n */\nvoid mnist_free_dataset(mnist_dataset_t * dataset)\n{\n    free(dataset->images);\n    free(dataset->labels);\n    free(dataset);\n}\n\nmnist_dataset_t * mnist_get_dataset(const char * image_path, const char * label_path)\n{\n    mnist_dataset_t * dataset;\n    uint32_t number_of_images, number_of_labels;\n\n    dataset = (mnist_dataset_t*)calloc(1, sizeof(mnist_dataset_t));\n\n    if (NULL == dataset) {\n        return NULL;\n    }\n\n    dataset->images = get_images(image_path, &number_of_images);\n\n    if (NULL == dataset->images) {\n        mnist_free_dataset(dataset);\n        return NULL;\n    }\n\n    dataset->labels = get_labels(label_path, &number_of_labels);\n\n    if (NULL == dataset->labels) {\n        mnist_free_dataset(dataset);\n        return NULL;\n    }\n\n    if (number_of_images != number_of_labels) {\n        fprintf(stderr, \"Number of images does not match number of labels (%d != %d)\\n\", number_of_images, number_of_labels);\n        mnist_free_dataset(dataset);\n        return NULL;\n    }\n\n    dataset->size = number_of_images;\n\n    return dataset;\n}\n\n/**\n * Fills the batch dataset with a subset of the parent dataset.\n */\nint mnist_batch(mnist_dataset_t * dataset, mnist_dataset_t * batch, int size, int number)\n{\n    int start_offset;\n\n    start_offset = size * number;\n\n    if (start_offset >= dataset->size) {\n        return 0;\n    }\n\n    batch->images = &dataset->images[start_offset];\n    batch->labels = &dataset->labels[start_offset];\n    batch->size = size;\n\n    if (start_offset + batch->size > dataset->size) {\n        batch->size = dataset->size - start_offset;\n    }\n\n    return 1;\n}\n\n\n\n#define STEPS 1000\n#define BATCH_SIZE 100\n\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\n// Convert a pixel value from 0-255 to one from 0 to 1\n#define PIXEL_SCALE(x) (((float) (x)) / 255.0f)\n\n// Returns a random value between 0 and 1\n#define RAND_FLOAT() (((float) rand()) / ((float) RAND_MAX))\n\n/**\n * Initialise the weights and bias vectors with values between 0 and 1\n */\nvoid neural_network_random_weights(neural_network_t * network)\n{\n    int i, j;\n\n    for (i = 0; i < MNIST_LABELS; i++) {\n        network->b[i] = RAND_FLOAT();\n\n        for (j = 0; j < MNIST_IMAGE_SIZE; j++) {\n            network->W[i][j] = RAND_FLOAT();\n        }\n    }\n}\n\n/**\n * Calculate the softmax vector from the activations. This uses a more\n * numerically stable algorithm that normalises the activations to prevent\n * large exponents.\n */\nvoid neural_network_softmax(float * activations, int length)\n{\n    int i;\n    float sum, max;\n\n    for (i = 1, max = activations[0]; i < length; i++) {\n        if (activations[i] > max) {\n            max = activations[i];\n        }\n    }\n\n    for (i = 0, sum = 0; i < length; i++) {\n        activations[i] = exp(activations[i] - max);\n        sum += activations[i];\n    }\n\n    for (i = 0; i < length; i++) {\n        activations[i] /= sum;\n    }\n}\n\n/**\n * Calculate the softmax vector from the activations. This uses a more\n * numerically stable algorithm that normalises the activations to prevent\n * large exponents.\n */\nvoid aneural_network_softmax(adept::FixedArray<float,true,MNIST_LABELS> &activations, int length)\n{\n    int i;\n    aReal sum, max;\n\n    for (i = 1, max = activations[0]; i < length; i++) {\n        if (activations[i] > max) {\n            max = activations[i];\n        }\n    }\n\n    for (i = 0, sum = 0; i < length; i++) {\n        activations[i] = exp(activations[i] - max);\n        sum += activations[i];\n    }\n\n    activations /= sum;\n    for (i = 0; i < length; i++) {\n        activations[i] /= sum;\n    }\n}\nstatic double maxval(const float *activations, int length) {\n    float max = activations[0];\n\n    for (int i = 1; i < length; i++) {\n        if (activations[i] > max) {\n            max = activations[i];\n        }\n    }\n    return max;\n}\n\nstatic double sumval(const float *activations, int length) {\n    float sum = 0;\n\n    for (int i = 0; i < length; i++) {\n        sum += activations[i];\n    }\n    return sum;\n}\n\n\nstatic    void makeexps(float* exps, const float* activations, int length, double max) {\n    for (int i = 0; i < length; i++) {\n        exps[i] = exp(activations[i] - max);\n    }\n\n}\n/**\n * Calculate the softmax vector from the activations. This uses a more\n * numerically stable algorithm that normalises the activations to prevent\n * large exponents.\n */\nstatic void neural_network_softmax_v2(const float * activations, float* outp, int length)\n{\n    int i;\n    float sum, max;\n\n    for (i = 1, max = activations[0]; i < length; i++) {\n        if (activations[i] > max) {\n            max = activations[i];\n        }\n    }\n\n    for (i = 0, sum = 0; i < length; i++) {\n        sum += exp(activations[i] - max);\n    }\n\n    for (i = 0; i < length; i++) {\n        outp[i] = exp(activations[i] - max) / sum;\n    }\n#if 0\n    float max = maxval(activations, length);\n    float exps[length];\n    makeexps(exps,activations, length, max);\n    float sum = sumval(exps,length);\n    /*\n    for (int i = 0; i < length; i++) {\n        double tmp = exps[i];//exp(activations[i] - max);\n        sum += tmp;\n    }\n    */\n\n    for (int i = 0; i < length; i++) {\n        outp[i] = exps[i] / sum;\n    }\n#endif\n}\n/**\n * Use the weights and bias vector to forward propogate through the neural\n * network and calculate the activations.\n */\nvoid neural_network_hypothesis(const mnist_image_t * image, const neural_network_t * network, float activations[MNIST_LABELS])\n{\n    int i, j;\n\n    for (i = 0; i < MNIST_LABELS; i++) {\n        activations[i] = network->b[i];\n\n        for (j = 0; j < MNIST_IMAGE_SIZE; j++) {\n            activations[i] += network->W[i][j] * PIXEL_SCALE(image->pixels[j]);\n        }\n    }\n\n    neural_network_softmax(activations, MNIST_LABELS);\n}\n\n/**\n * Use the weights and bias vector to forward propogate through the neural\n * network and calculate the activations.\n */\nstatic float neural_network_hypothesis_v2(const mnist_image_t * image, const neural_network_t * network, uint8_t label)\n{\n    float activations[MNIST_LABELS] = {0};\n    int i, j;\n\n    for (i = 0; i < MNIST_LABELS; i++) {\n        activations[i] = network->b[i];\n\n        for (j = 0; j < MNIST_IMAGE_SIZE; j++) {\n            activations[i] += network->W[i][j] * PIXEL_SCALE(image->pixels[j]);\n        }\n    }\n\n    float activations2[MNIST_LABELS] = { 0 };\n    neural_network_softmax_v2(activations, activations2, MNIST_LABELS);\n    return -log(activations2[label]);\n}\n\n\nstatic aReal neural_network_hypothesis_adept(const mnist_image_t * image, const aneural_network_t * network, uint8_t label)\n{\n    adept::FixedArray<float,true,MNIST_LABELS> activations = network->b;\n    int i, j;\n\n    for (i = 0; i < MNIST_LABELS; i++) {\n        for (j = 0; j < MNIST_IMAGE_SIZE; j++) {\n            activations(i) += network->W(i,j) * PIXEL_SCALE(image->pixels[j]);\n        }\n    }\n\n    aneural_network_softmax(activations, MNIST_LABELS);\n    return -log(activations[label]);\n}\n\n\nstatic void calculateDerivatives_adept(mnist_image_t * image, bool run, adept::Stack& stack, const aneural_network_t * anetwork, neural_network_t* gradient, uint8_t label) {\n\n    if (!run) {\n        stack.new_recording();\n    //    run = true;\n    } else\n        stack.continue_recording();\n    auto resa = neural_network_hypothesis_adept(image, anetwork, label);\n    resa.set_gradient(1.0);\n    stack.reverse();\n    stack.pause_recording();\n\n    for (int i = 0; i < MNIST_LABELS; i++) {\n        gradient->b[i] = anetwork->b(i).get_gradient();\n        for (int j = 0; j < MNIST_IMAGE_SIZE; j++) {\n            gradient->W[i][j] = anetwork->W(i,j).get_gradient();\n        }\n    }\n}\n\nextern \"C\" {\n#include <adBuffer.h>\n}\n\nvoid neural_network_softmax_b(float *activations, float *activationsb, int \n        length) {\n    float sum, max;\n    float sumb, maxb;\n    int branch;\n    max = activations[0];\n    for (int i = 1; i < length; ++i)\n        if (activations[i] > max) {\n            max = activations[i];\n            pushControl1b(1);\n        } else\n            pushControl1b(0);\n    sum = 0;\n    for (int i = 0; i < length; ++i) {\n        pushReal4(activations[i]);\n        activations[i] = (float)exp(activations[i] - max);\n        sum = sum + activations[i];\n    }\n    for (int i = 0; i < length; ++i) {\n        pushReal4(activations[i]);\n        activations[i] = activations[i]/sum;\n    }\n    sumb = 0.0;\n    for (int i = length-1; i > -1; --i) {\n        popReal4(&(activations[i]));\n        sumb = sumb - activations[i]*activationsb[i]/(sum*sum);\n        activationsb[i] = activationsb[i]/sum;\n    }\n    {\n      float tempb;\n      maxb = 0.0;\n      for (int i = length-1; i > -1; --i) {\n          activationsb[i] = activationsb[i] + sumb;\n          popReal4(&(activations[i]));\n          tempb = exp(activations[i]-max)*activationsb[i];\n          maxb = maxb - tempb;\n          activationsb[i] = tempb;\n      }\n    }\n    for (int i = length-1; i > 0; --i) {\n        popControl1b(&branch);\n        if (branch != 0) {\n            activationsb[i] = activationsb[i] + maxb;\n            maxb = 0.0;\n        }\n    }\n    activationsb[0] = activationsb[0] + maxb;\n}\n\n/**\n * Calculate the softmax vector from the activations. This uses a more\n * numerically stable algorithm that normalises the activations to prevent\n * large exponents.\n */\n// Convert a pixel value from 0-255 to one from 0 to 1\n// Returns a random value between 0 and 1\nvoid neural_network_softmax_c(float *activations, int length) {\n    float sum, max;\n    max = activations[0];\n\tint i;\n    for (i = 1; i < length; ++i)\n        if (activations[i] > max)\n            max = activations[i];\n    sum = 0;\n    for (i = 0; i < length; ++i) {\n        activations[i] = (float)exp(activations[i] - max);\n        sum += activations[i];\n    }\n    for (i = 0; i < length; ++i)\n        activations[i] /= sum;\n}\n\n/*\n  Differentiation of neural_network_hypothesis_tapenadesource in reverse (adjoint) mode:\n   gradient     of useful results: neural_network_hypothesis_tapenadesource\n                *network.b[0:10-1] *network.W[0:10-1][0:28*28-1]\n   with respect to varying inputs: *network.b[0:10-1] *network.W[0:10-1][0:28*28-1]\n   RW status of diff variables: neural_network_hypothesis_tapenadesource:in-killed\n                *network.b[0:10-1]:incr *network.W[0:10-1][0:28*28-1]:incr\n   Plus diff mem management of: network:in *network.b:in *network.W:in\n                *network.W[0:10-1]:in\n*/\nstatic void neural_network_hypothesis_tapenadesource_b(const mnist_image_t *\n        image, const neural_network_t *network, neural_network_t *networkb, \n        uint8_t label, float neural_network_hypothesis_tapenadesourceb) {\n    float activations[10];\n    float activationsb[10];\n    int ii1;\n    float neural_network_hypothesis_tapenadesource;\n    for (int i = 0; i < 10; ++i) {\n        activations[i] = network->b[i];\n        for (int j = 0; j < 784; ++j)\n            activations[i] = activations[i] + network->W[i][j]*((float)image->\n                pixels[j]/255.0f);\n    }\n    pushReal4Array(activations, 10);\n    neural_network_softmax_c(activations, 10);\n    for (ii1 = 0; ii1 < 10; ++ii1)\n        activationsb[ii1] = 0.0;\n    activationsb[(int)label] = activationsb[(int)label] - \n        neural_network_hypothesis_tapenadesourceb/activations[(int)label];\n    popReal4Array(activations, 10);\n    neural_network_softmax_b(activations, activationsb, 10);\n    for (int i = 9; i > -1; --i) {\n        for (int j = 783; j > -1; --j)\n            networkb->W[i][j] = networkb->W[i][j] + (float)image->pixels[j]*\n                activationsb[i]/255.0f;\n        networkb->b[i] = networkb->b[i] + activationsb[i];\n        activationsb[i] = 0.0;\n    }\n}\n\n/**\n * Update the gradients for this step of gradient descent using the gradient\n * contributions from a single training example (image).\n * \n * This function returns the loss ontribution from this training example.\n */\nfloat neural_network_gradient_update(mnist_image_t * image, const neural_network_t * network, neural_network_gradient_t * gradient, uint8_t label)\n{\n    float activations[MNIST_LABELS];\n    float b_grad, W_grad;\n    int i, j;\n\n    // First forward propagate through the network to calculate activations\n    neural_network_hypothesis(image, network, activations);\n\n    for (i = 0; i < MNIST_LABELS; i++) {\n        // This is the gradient for a softmax bias input\n        b_grad = (i == label) ? activations[i] - 1 : activations[i];\n\n        for (j = 0; j < MNIST_IMAGE_SIZE; j++) {\n            // The gradient for the neuron weight is the bias multiplied by the input weight\n            W_grad = b_grad * PIXEL_SCALE(image->pixels[j]);\n\n            // Update the weight gradient\n            gradient->W_grad[i][j] += W_grad;\n        }\n\n        // Update the bias gradient\n        gradient->b_grad[i] += b_grad;\n    }\n\n    // Cross entropy loss\n    return 0.0f - log(activations[label]);\n}\n\n\nextern int enzyme_const;\ntemplate<typename Return, typename... T>\nReturn __enzyme_autodiff(T...);\n\nstatic void calculateDerivatives(mnist_image_t * image, const neural_network_t * network, neural_network_t* gradient, uint8_t label) {\n    __enzyme_autodiff<void>(neural_network_hypothesis_v2, enzyme_const, image, network, gradient, enzyme_const, label);\n}\n\n/**\n * Run one step of gradient descent and update the neural network.\n */\nfloat neural_network_training_step(mnist_dataset_t * dataset, neural_network_t * network, float learning_rate)\n{\n    neural_network_t gradient = {0};\n    neural_network_t gradient2 = {0};\n\n    /*\n    adept::Stack stack;\n    aneural_network_t anetwork;\n  \n    for (int i = 0; i < MNIST_LABELS; i++) {\n        anetwork.b[i] = network->b[i];\n        for (int j = 0; j < MNIST_IMAGE_SIZE; j++) {\n            anetwork.W[i][j] = network->W[i][j];\n        }\n    }*/\n\n    float total_loss;\n    int i, j;\n\n    // Calculate the gradient and the loss by looping through the training set\n    for (i = 0, total_loss = 0; i < dataset->size; i++) {\n\t\tmnist_image_t* image = &dataset->images[i];\n\t\tuint8_t label = dataset->labels[i];\n\n    \t// First forward propagate through the network to calculate activations\n\n        //calculateDerivatives(image, network, &gradient, label);\n        //calculateDerivatives_adept(image, i != 0, stack, &anetwork, &gradient, label);\n\t\t//neural_network_hypothesis_tapenadesource_b(image, network, &gradient, label, 1.0);\n\n        total_loss +=neural_network_gradient_update(image, network, (neural_network_gradient_t*)&gradient, label);\n        \n        //total_loss +=neural_network_gradient_update(image, network, (neural_network_gradient_t*)&gradient2, label);\n\n\t    //float activations[MNIST_LABELS];\n        //neural_network_hypothesis(image, network, activations);\n    \t//total_loss -= log(activations[label]);\n\n    }\n\n    // Apply gradient descent to the network\n    for (i = 0; i < MNIST_LABELS; i++) {\n        //printf(\"b'[i] %f %f\\n\", gradient.b[i], gradient2.b[i]);\n        network->b[i] -= learning_rate * gradient.b[i] / ((float) dataset->size);\n\n        for (j = 0; j < MNIST_IMAGE_SIZE + 1; j++) {\n            network->W[i][j] -= learning_rate * gradient.W[i][j] / ((float) dataset->size);\n        }\n    }\n\n    return total_loss;\n}\n\n/**\n * Run one step of gradient descent and update the neural network.\n */\nfloat neural_network_training_step_enzyme(mnist_dataset_t * dataset, neural_network_t * network, float learning_rate)\n{\n    neural_network_t gradient = {0};\n    neural_network_t gradient2 = {0};\n\n    float total_loss;\n    int i, j;\n\n    // Calculate the gradient and the loss by looping through the training set\n    for (i = 0, total_loss = 0; i < dataset->size; i++) {\n\t\tmnist_image_t* image = &dataset->images[i];\n\t\tuint8_t label = dataset->labels[i];\n\n    \t// First forward propagate through the network to calculate activations\n\n        calculateDerivatives(image, network, &gradient, label);\n        //calculateDerivatives_adept(image, i != 0, stack, &anetwork, &gradient, label);\n\t\t//neural_network_hypothesis_tapenadesource_b(image, network, &gradient, label, 1.0);\n \n        //total_loss +=neural_network_gradient_update(image, network, (neural_network_gradient_t*)&gradient2, label);\n\n\t    float activations[MNIST_LABELS];\n        neural_network_hypothesis(image, network, activations);\n    \ttotal_loss -= log(activations[label]);\n\n    }\n\n    // Apply gradient descent to the network\n    for (i = 0; i < MNIST_LABELS; i++) {\n        //printf(\"b'[i] %f %f\\n\", gradient.b[i], gradient2.b[i]);\n        network->b[i] -= learning_rate * gradient.b[i] / ((float) dataset->size);\n\n        for (j = 0; j < MNIST_IMAGE_SIZE + 1; j++) {\n            network->W[i][j] -= learning_rate * gradient.W[i][j] / ((float) dataset->size);\n        }\n    }\n\n    return total_loss;\n}\n\n/**\n * Run one step of gradient descent and update the neural network.\n */\nfloat neural_network_training_step_adept(mnist_dataset_t * dataset, neural_network_t * network, float learning_rate)\n{\n    neural_network_t gradient = {0};\n    neural_network_t gradient2 = {0};\n\n    adept::Stack stack;\n    aneural_network_t anetwork;\n  \n    for (int i = 0; i < MNIST_LABELS; i++) {\n        anetwork.b[i] = network->b[i];\n        for (int j = 0; j < MNIST_IMAGE_SIZE; j++) {\n            anetwork.W[i][j] = network->W[i][j];\n        }\n    }\n\n    float total_loss;\n    int i, j;\n\n    // Calculate the gradient and the loss by looping through the training set\n    for (i = 0, total_loss = 0; i < dataset->size; i++) {\n\t\tmnist_image_t* image = &dataset->images[i];\n\t\tuint8_t label = dataset->labels[i];\n\n    \t// First forward propagate through the network to calculate activations\n\n        calculateDerivatives_adept(image, i != 0, stack, &anetwork, &gradient, label);\n        \n        //total_loss +=neural_network_gradient_update(image, network, (neural_network_gradient_t*)&gradient2, label);\n\n\t    float activations[MNIST_LABELS];\n        neural_network_hypothesis(image, network, activations);\n    \ttotal_loss -= log(activations[label]);\n\n    }\n\n    // Apply gradient descent to the network\n    for (i = 0; i < MNIST_LABELS; i++) {\n        //printf(\"b'[i] %f %f\\n\", gradient.b[i], gradient2.b[i]);\n        network->b[i] -= learning_rate * gradient.b[i] / ((float) dataset->size);\n\n        for (j = 0; j < MNIST_IMAGE_SIZE + 1; j++) {\n            network->W[i][j] -= learning_rate * gradient.W[i][j] / ((float) dataset->size);\n        }\n    }\n\n    return total_loss;\n}\n\n/**\n * Run one step of gradient descent and update the neural network.\n */\nfloat neural_network_training_step_tapenade(mnist_dataset_t * dataset, neural_network_t * network, float learning_rate)\n{\n    neural_network_t gradient = {0};\n    neural_network_t gradient2 = {0};\n\n    float total_loss;\n    int i, j;\n\n    // Calculate the gradient and the loss by looping through the training set\n    for (i = 0, total_loss = 0; i < dataset->size; i++) {\n\t\tmnist_image_t* image = &dataset->images[i];\n\t\tuint8_t label = dataset->labels[i];\n\n    \t// First forward propagate through the network to calculate activations\n\n\t\tneural_network_hypothesis_tapenadesource_b(image, network, &gradient, label, 1.0); \n        //total_loss +=neural_network_gradient_update(image, network, (neural_network_gradient_t*)&gradient2, label);\n\n\t    float activations[MNIST_LABELS];\n        neural_network_hypothesis(image, network, activations);\n    \ttotal_loss -= log(activations[label]);\n    }\n\n    // Apply gradient descent to the network\n    for (i = 0; i < MNIST_LABELS; i++) {\n        //printf(\"b'[i] %f %f\\n\", gradient.b[i], gradient2.b[i]);\n        network->b[i] -= learning_rate * gradient.b[i] / ((float) dataset->size);\n\n        for (j = 0; j < MNIST_IMAGE_SIZE + 1; j++) {\n            network->W[i][j] -= learning_rate * gradient.W[i][j] / ((float) dataset->size);\n        }\n    }\n\n    return total_loss;\n}\n\n/**\n * Downloaded from: http://yann.lecun.com/exdb/mnist/\n */\nconst char * train_images_file = \"data/train-images-idx3-ubyte\";\nconst char * train_labels_file = \"data/train-labels-idx1-ubyte\";\nconst char * test_images_file = \"data/t10k-images-idx3-ubyte\";\nconst char * test_labels_file = \"data/t10k-labels-idx1-ubyte\";\n\n/**\n * Calculate the accuracy of the predictions of a neural network on a dataset.\n */\nfloat calculate_accuracy(mnist_dataset_t * dataset, neural_network_t * network) {\n    float activations[MNIST_LABELS], max_activation;\n    int i, j, correct, predict;\n\n    // Loop through the dataset\n    for (i = 0, correct = 0; i < dataset->size; i++) {\n        // Calculate the activations for each image using the neural network\n        neural_network_hypothesis(&dataset->images[i], network, activations);\n\n        // Set predict to the index of the greatest activation\n        for (j = 0, predict = 0, max_activation = activations[0]; j < MNIST_LABELS; j++) {\n            if (max_activation < activations[j]) {\n                max_activation = activations[j];\n                predict = j;\n            }\n        }\n\n        // Increment the correct count if we predicted the right label\n        if (predict == dataset->labels[i]) {\n            correct++;\n        }\n    }\n\n    // Return the percentage we predicted correctly as the accuracy\n    return ((float) correct) / ((float) dataset->size);\n}\n\n#include <sys/time.h>\n#include <stdlib.h>\n#include <math.h>\n#include <inttypes.h>\n#include <string.h>\n\nfloat tdiff(struct timeval *start, struct timeval *end) {\n  return (end->tv_sec-start->tv_sec) + 1e-6*(end->tv_usec-start->tv_usec);\n}\n\nvoid run(float (*fn)(mnist_dataset_t*, neural_network_t*, float)) {\n    mnist_dataset_t * train_dataset, * test_dataset;\n    mnist_dataset_t batch;\n    neural_network_t network;\n    float loss, accuracy;\n    int i, batches;\n\n    // Read the datasets from the files\n    train_dataset = mnist_get_dataset(train_images_file, train_labels_file);\n    test_dataset = mnist_get_dataset(test_images_file, test_labels_file);\n\n    // Initialise weights and biases with random values\n    neural_network_random_weights(&network);\n\n    // Calculate how many batches (so we know when to wrap around)\n    batches = train_dataset->size / BATCH_SIZE;\n\n    struct timeval start, end;\n    gettimeofday(&start, NULL);\n    \n    for (i = 0; i < STEPS; i++) {\n        // Initialise a new batch\n        mnist_batch(train_dataset, &batch, 100, i % batches);\n\n        // Run one step of gradient descent and calculate the loss\n        loss = fn(&batch, &network, 0.5);\n\n        // Calculate the accuracy using the whole test dataset\n        accuracy = calculate_accuracy(test_dataset, &network);\n\n        printf(\"Step %04d\\tAverage Loss: %.2f\\tAccuracy: %.3f\\n\", i, loss / batch.size, accuracy);\n    }\n  \n    gettimeofday(&end, NULL);\n    printf(\"%0.6f\\n\", tdiff(&start, &end));\n\n    // Cleanup\n    mnist_free_dataset(train_dataset);\n    mnist_free_dataset(test_dataset);\n\n}\n\nint main(int argc, char *argv[])\n{\n    printf(\"Regular\\n\");\n    run(neural_network_training_step);\n    printf(\"Enzyme\\n\");\n    run(neural_network_training_step_enzyme);\n    printf(\"Adept\\n\");\n    run(neural_network_training_step_adept);\n    printf(\"Tapenade\\n\");\n    run(neural_network_training_step_tapenade);\n    return 0;\n}\n", "meta": {"hexsha": "d5f7a5893b08c72464e3647cf68b8bba93154c52", "size": 28965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enzyme/benchmarks/nn/nn.cpp", "max_stars_repo_name": "anandijain/Enzyme", "max_stars_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 674.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T17:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T11:18:11.000Z", "max_issues_repo_path": "enzyme/benchmarks/nn/nn.cpp", "max_issues_repo_name": "anandijain/Enzyme", "max_issues_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2020-10-07T00:47:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T16:46:58.000Z", "max_forks_repo_path": "enzyme/benchmarks/nn/nn.cpp", "max_forks_repo_name": "anandijain/Enzyme", "max_forks_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T14:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:51:07.000Z", "avg_line_length": 30.2664576803, "max_line_length": 173, "alphanum_fraction": 0.6401864319, "num_tokens": 7730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5159807067569316}}
{"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_SINCPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SINCPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the Computes the sinpi cardinal\n    value of its parameter, i.e. \\f$sin(\\pi x)/(\\pi x) \\f$.\n\n    @par Header <boost/simd/function/sincpi.hpp>\n\n    @see sin, sinc, sinhc\n\n    @par Example:\n\n      @snippet sincpi.cpp sincpi\n\n    @par Possible output:\n\n      @snippet sincpi.txt sincpi\n\n  **/\n  IEEEValue sincpi(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sincpi.hpp>\n#include <boost/simd/function/simd/sincpi.hpp>\n\n#endif\n", "meta": {"hexsha": "84980f017abb9bd8ab1607b72a4c735e0d13a05c", "size": 1071, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sincpi.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/function/sincpi.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/function/sincpi.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": 24.3409090909, "max_line_length": 100, "alphanum_fraction": 0.5807656396, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.51598069097405}}
{"text": "/*\n * Sampling_functions.hpp\n *\n *  Created on: Dec 21, 2018\n *      Author: thanasis\n */\n#include <Eigen/Core>\nusing namespace Eigen;\n\n#ifndef SAMPLING_FUNCTIONS_HPP_\n#define SAMPLING_FUNCTIONS_HPP_\n\ndouble sample_mu(int N, double Esigma2,const VectorXd& Y,const MatrixXd& X,const VectorXd& beta);\ndouble sample_psi2_chisq(const VectorXd& beta,int NZ,double v0B,double s0B);\ndouble sample_sigma_chisq(int N,const VectorXd& epsilon,double v0E,double s0E);\ndouble sample_w(int M,int NZ);\n\n#endif /* SAMPLING_FUNCTIONS_HPP_ */\n", "meta": {"hexsha": "c17ea20337d0d224d916c1c01ac06f619297c291", "size": 525, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Sampling_functions.hpp", "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": "Sampling_functions.hpp", "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": "Sampling_functions.hpp", "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": 27.6315789474, "max_line_length": 97, "alphanum_fraction": 0.7676190476, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.5159702075399476}}
{"text": "/*****************************************************************************\n * simple.cpp        Some simple array operations\n *****************************************************************************/\n\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n    Array<double,1> x(100);\n    x = tensor::i;          // x = [ 0, 1, 2, ..., 99 ]\n\n    Array<double,1> z(x + 150);\n    Array<double,1> v(z + x * 2);\n\n    cout << v << endl;\n}\n\n", "meta": {"hexsha": "d965b98e440816e373256316908d1b8975933415", "size": 454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/simple.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/simple.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/simple.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7, "max_line_length": 79, "alphanum_fraction": 0.3392070485, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5159702037930398}}
{"text": "/*\n * Copyright (c) 2015, 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 *    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\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 *    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 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 HOLDER 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(s) of this library if you have any questions.\n * Authors: David Fridovich-Keil   ( dfk@eecs.berkeley.edu )\n *          Erik Nelson            ( eanelson@eecs.berkeley.edu )\n */\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <gflags/gflags.h>\n\n#include <geometry/rotation.h>\n#include <math/random_generator.h>\n\n#include <gtest/gtest.h>\n\nnamespace bsfm {\n\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\nTEST(Rotation, TestEulerAnglesAndMatrices) {\n  // Randomly generate euler angles, convert to a matrix, then convert back.\n  // Check that (1) the rotation matrix has det(R)==1, and (2), that we get the\n  // same angles back.\n  math::RandomGenerator rng(0);\n  for (int ii = 0; ii < 1000; ++ii) {\n    Vector3d e1;\n    e1.setRandom();\n\n    // Converting from rotation matrices to euler angles is only valid when phi,\n    // theta, and psi are all < 0.5*PI. Otherwise the problem has multiple\n    // solutions, and we can only return one of them with our function.\n    e1 *= 0.5 * M_PI;\n\n    Matrix3d R = EulerAnglesToMatrix(e1);\n    EXPECT_NEAR(1.0, R.determinant(), 1e-8);\n\n    Vector3d e2 = MatrixToEulerAngles(R);\n    EXPECT_NEAR(0.0, S1Distance(e1(0), e2(0)), 1e-8);\n    EXPECT_NEAR(0.0, S1Distance(e1(1), e2(1)), 1e-8);\n    EXPECT_NEAR(0.0, S1Distance(e1(2), e2(2)), 1e-8);\n\n    EXPECT_TRUE(R.isApprox(EulerAnglesToMatrix(e2), 1e-4));\n  }\n}\n\n}  //\\namespace bsfm\n", "meta": {"hexsha": "4e0dda356be6e1642fed0d731292b8eae84367bf", "size": 3059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_rotation.cpp", "max_stars_repo_name": "jamesdsmith/berkeley_sfm", "max_stars_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T13:52:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T19:30:33.000Z", "max_issues_repo_path": "test/test_rotation.cpp", "max_issues_repo_name": "jamesdsmith/berkeley_sfm", "max_issues_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-17T17:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-22T20:59:43.000Z", "max_forks_repo_path": "test/test_rotation.cpp", "max_forks_repo_name": "erik-nelson/berkeley_sfm", "max_forks_repo_head_hexsha": "5bf0b45fac176ff7abfca0ff690893c1afc73c51", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-01-22T06:23:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-16T03:54:33.000Z", "avg_line_length": 38.7215189873, "max_line_length": 80, "alphanum_fraction": 0.7129780974, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7057850216484837, "lm_q1q2_score": 0.5159701947446877}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/maybe.hpp>\n#include <boost/hana/tuple.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [sequence]\nBOOST_HANA_CONSTEXPR_CHECK(\n    sequence<Maybe>(make<Tuple>(just(1), just('2'), just(3.3))) ==\n    just(make<Tuple>(1, '2', 3.3))\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    sequence<Maybe>(make<Tuple>(just(1), nothing, just(3.3))) == nothing\n);\n\n// This is a generalized Cartesian product.\nBOOST_HANA_CONSTEXPR_CHECK(\n    sequence<Tuple>(make<Tuple>(make<Tuple>(1, 2, 3),\n                                make<Tuple>(4),\n                                make<Tuple>(5, 6)))\n    ==\n    make<Tuple>(\n        make<Tuple>(1, 4, 5), make<Tuple>(1, 4, 6),\n        make<Tuple>(2, 4, 5), make<Tuple>(2, 4, 6),\n        make<Tuple>(3, 4, 5), make<Tuple>(3, 4, 6)\n    )\n);\n//! [sequence]\n\n}{\n\n//! [traverse]\nBOOST_HANA_CONSTEXPR_LAMBDA auto half = [](auto x) {\n    return if_(x % int_<2> == int_<0>,\n        just(x / int_<2>),\n        nothing\n    );\n};\n\nBOOST_HANA_CONSTANT_CHECK(\n    traverse<Maybe>(make<Tuple>(int_<2>, int_<4>, int_<6>), half)\n    ==\n    just(make<Tuple>(int_<1>, int_<2>, int_<3>))\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    traverse<Maybe>(make<Tuple>(int_<2>, int_<3>, int_<6>), half)\n    ==\n    nothing\n);\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto twice = [](auto x) {\n    return make<Tuple>(x, x);\n};\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    traverse<Tuple>(just('x'), twice) == make<Tuple>(just('x'), just('x'))\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    traverse<Tuple>(nothing, twice) == make<Tuple>(nothing)\n);\n//! [traverse]\n\n}\n\n}\n", "meta": {"hexsha": "4489917536b904efac3893d163059586fd8b3447", "size": 1820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/traversable.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/traversable.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/traversable.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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.4691358025, "max_line_length": 78, "alphanum_fraction": 0.6126373626, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5159701947446877}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2015-2016 Gael Guennebaud <gael.guennebaud@inria.fr>\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// #define EIGEN_DONT_VECTORIZE\n// #define EIGEN_MAX_ALIGN_BYTES 0\n#include \"sparse_solver.h\"\n#include <Eigen/IterativeLinearSolvers>\n#include <unsupported/Eigen/IterativeSolvers>\n\ntemplate<typename T, typename I_> void test_incomplete_cholesky_T()\n{\n  typedef SparseMatrix<T,0,I_> SparseMatrixType;\n  ConjugateGradient<SparseMatrixType, Lower, IncompleteCholesky<T, Lower, AMDOrdering<I_> > >        cg_illt_lower_amd;\n  ConjugateGradient<SparseMatrixType, Lower, IncompleteCholesky<T, Lower, NaturalOrdering<I_> > >    cg_illt_lower_nat;\n  ConjugateGradient<SparseMatrixType, Upper, IncompleteCholesky<T, Upper, AMDOrdering<I_> > >        cg_illt_upper_amd;\n  ConjugateGradient<SparseMatrixType, Upper, IncompleteCholesky<T, Upper, NaturalOrdering<I_> > >    cg_illt_upper_nat;\n  ConjugateGradient<SparseMatrixType, Upper|Lower, IncompleteCholesky<T, Lower, AMDOrdering<I_> > >  cg_illt_uplo_amd;\n  \n\n  CALL_SUBTEST( check_sparse_spd_solving(cg_illt_lower_amd) );\n  CALL_SUBTEST( check_sparse_spd_solving(cg_illt_lower_nat) );\n  CALL_SUBTEST( check_sparse_spd_solving(cg_illt_upper_amd) );\n  CALL_SUBTEST( check_sparse_spd_solving(cg_illt_upper_nat) );\n  CALL_SUBTEST( check_sparse_spd_solving(cg_illt_uplo_amd) );\n}\n\ntemplate<int>\nvoid bug1150()\n{\n  // regression for bug 1150\n  for(int N = 1; N<20; ++N)\n  {\n    Eigen::MatrixXd b( N, N );\n    b.setOnes();\n\n    Eigen::SparseMatrix<double> m( N, N );\n    m.reserve(Eigen::VectorXi::Constant(N,4));\n    for( int i = 0; i < N; ++i )\n    {\n        m.insert( i, i ) = 1;\n        m.coeffRef( i, i / 2 ) = 2;\n        m.coeffRef( i, i / 3 ) = 2;\n        m.coeffRef( i, i / 4 ) = 2;\n    }\n\n    Eigen::SparseMatrix<double> A;\n    A = m * m.transpose();\n\n    Eigen::ConjugateGradient<Eigen::SparseMatrix<double>,\n        Eigen::Lower | Eigen::Upper,\n        Eigen::IncompleteCholesky<double> > solver( A );\n    VERIFY(solver.preconditioner().info() == Eigen::Success);\n    VERIFY(solver.info() == Eigen::Success);\n  }\n}\n\nEIGEN_DECLARE_TEST(incomplete_cholesky)\n{\n  CALL_SUBTEST_1(( test_incomplete_cholesky_T<double,int>() ));\n  CALL_SUBTEST_2(( test_incomplete_cholesky_T<std::complex<double>, int>() ));\n  CALL_SUBTEST_3(( test_incomplete_cholesky_T<double,long int>() ));\n\n  CALL_SUBTEST_1(( bug1150<0>() ));\n}\n", "meta": {"hexsha": "ecc17f5c3582cbf3d39089ac0496dfec197b737b", "size": 2623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen/test/incomplete_cholesky.cpp", "max_stars_repo_name": "TomAB99/kima", "max_stars_repo_head_hexsha": "15e13159dd7bdaa4053e3157cbf5f562ee988461", "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": "eigen/test/incomplete_cholesky.cpp", "max_issues_repo_name": "TomAB99/kima", "max_issues_repo_head_hexsha": "15e13159dd7bdaa4053e3157cbf5f562ee988461", "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": "external/eigen/test/incomplete_cholesky.cpp", "max_forks_repo_name": "lucaparisi91/qmc3", "max_forks_repo_head_hexsha": "f76178896ecf7b79af863f8d4fc3653326bea5c3", "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": 37.4714285714, "max_line_length": 119, "alphanum_fraction": 0.7110179184, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5159701819494278}}
{"text": "/**\n * Computing transforms.\n * \\todo should be smarter about dimensions...what if 2d data, what if 3d+time?\n */\n#include <stdlib.h>\n#include <stdint.h>\n#include \"src/aabb.h\"\n#include \"nd.h\"\n#include <Eigen/Core>\n#include <Eigen/LU>\nusing namespace Eigen;\n#include <iostream>\nusing namespace std;\n\n//#define DEBUG\n\n#ifndef restrict\n  #define restrict __restrict\n#endif\n\n// output transform should be T s.t. rs=T*rd\n// so, if r=Ts*rs=Td*rd\n//   T = inv(Ts)*Td\n\n/**\n * \\param[in,out] out   Must be preallocated with at least (ndim+1)*(ndim+1) \n *                      elements\n */\nextern \"C\"\nvoid compose(float *restrict out,\n             aabb_t bbox,\n             float sx, float sy, float sz, // scale in aabb units\n             float *restrict transform, unsigned ndim)\n{ \n  MatrixXf                         dst2world(ndim+1,ndim+1);\n  Map<Matrix<float,Dynamic,Dynamic,RowMajor> > src2world(transform,ndim+1,ndim+1);\n  Map<Matrix<float,Dynamic,Dynamic,RowMajor> > T(out,ndim+1,ndim+1);\n\n  int64_t      *o;\n  AABBGet(bbox,0,&o,0);\n  dst2world.setIdentity();\n  dst2world.block<3,1>(0,ndim)<<(float)o[0],(float)o[1],(float)o[2];\n  dst2world.block<3,3>(0,0).diagonal()<<sx,sy,sz;  \n\n  T=(src2world.inverse()*dst2world).eval();\n#ifdef DEBUG\n  #define show(e) cout<<#e\" is \"<<endl<<e<<endl<<endl\n  show(dst2world);\n  show(src2world);\n  show(src2world.inverse());\n  show(T);\n  #undef show\n#endif\n}\n\nextern \"C\"\nvoid box2box(float *restrict out,\n             nd_t dst, aabb_t dstbox,\n             nd_t src, aabb_t srcbox)\n{ size_t d;\n  int64_t *ori,*shape;\n  \n  AABBGet(srcbox,0,&ori,&shape);\n  d=ndndim(src);\n  MatrixXf src2world(d+1,d+1);\n  src2world.setIdentity().block<3,3>(0,0).diagonal()\n    << (float)shape[0]/(float)ndshape(src)[0],\n       (float)shape[1]/(float)ndshape(src)[1],\n       (float)shape[2]/(float)ndshape(src)[2];\n  src2world.block<3,1>(0,d)\n    << (float)ori[0],(float)ori[1],(float)ori[2];\n\n  AABBGet(dstbox,0,&ori,&shape);\n  d=ndndim(dst);\n  MatrixXf dst2world(d+1,d+1);\n  dst2world.setIdentity().block<3,3>(0,0).diagonal()\n    << (float)shape[0]/(float)ndshape(dst)[0],\n       (float)shape[1]/(float)ndshape(dst)[1],\n       (float)shape[2]/(float)ndshape(dst)[2];\n  dst2world.block<3,1>(0,d)\n    << (float)ori[0],(float)ori[1],(float)ori[2];\n\n  Map<Matrix<float,Dynamic,Dynamic,RowMajor> > T(out,ndndim(src)+1,ndndim(dst)+1);\n  T=src2world.inverse()*dst2world;\n#ifdef DEBUG\n  #define show(e) cout<<#e\" is \"<<endl<<e<<endl<<endl\n  show(dst2world);\n  show(src2world);\n  show(src2world.inverse());\n  show(T);\n  #undef show\n#endif\n  //  [s,r_s] x [r_d,d]; r_s == r_d\n}", "meta": {"hexsha": "21fe308d70ec798db4b0863a5e60c0c0895fc8e9", "size": 2581, "ext": "cc", "lang": "C++", "max_stars_repo_path": "app/render/src/xform.cc", "max_stars_repo_name": "TeravoxelTwoPhotonTomography/tilebase", "max_stars_repo_head_hexsha": "61f2e6b979d214afab8dd60d6f55afc3e4697e24", "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": "app/render/src/xform.cc", "max_issues_repo_name": "TeravoxelTwoPhotonTomography/tilebase", "max_issues_repo_head_hexsha": "61f2e6b979d214afab8dd60d6f55afc3e4697e24", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/render/src/xform.cc", "max_forks_repo_name": "TeravoxelTwoPhotonTomography/tilebase", "max_forks_repo_head_hexsha": "61f2e6b979d214afab8dd60d6f55afc3e4697e24", "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.4574468085, "max_line_length": 82, "alphanum_fraction": 0.6268888028, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5159601802498692}}
{"text": "// Copyright (c) 2019 fortiss GmbH, Julian Bernhard, Klemens Esterle, Patrick Hart, 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\n#ifndef MODULES_GEOMETRY_COMMONS_HPP_\n#define MODULES_GEOMETRY_COMMONS_HPP_\n\n#include <Eigen/Core>\n#include <string>\n#include <vector>\n#include <cmath>\n#include <sstream>\n#include <memory>\n#include <iostream>\n#include <algorithm>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n\n\nnamespace modules {\nnamespace geometry {\n\n//! using boost geometry\nnamespace bg = boost::geometry;\n\n//! points\ntemplate <typename T>\nusing Point2d_t = bg::model::point<T, 2, bg::cs::cartesian>;\nusing Point2d = Point2d_t<float>;\n\n //! Point operators\ninline bool operator==(const Point2d& lhs, const Point2d& rhs) { return(bg::get<0>(lhs) == bg::get<0>(rhs) && bg::get<1>(lhs) == bg::get<1>(rhs)); }\ninline bool operator!=(const Point2d& lhs, const Point2d& rhs) { return !(lhs == rhs); }\ninline Point2d operator+(const Point2d& lhs, const Point2d& rhs) { return Point2d(bg::get<0>(lhs)+ bg::get<0>(rhs), bg::get<1>(lhs) + bg::get<1>(rhs)); }\ninline Point2d operator+(const Point2d& lhs, const float& rhs) { return Point2d(bg::get<0>(lhs)+ rhs , bg::get<1>(lhs) + rhs); }\n\ninline Point2d operator-(const Point2d& lhs, const Point2d& rhs) { return Point2d(bg::get<0>(lhs) - bg::get<0>(rhs), bg::get<1>(lhs) - bg::get<1>(rhs)); }\ninline Point2d operator-(const Point2d& lhs, const float& rhs) { return Point2d(bg::get<0>(lhs)- rhs, bg::get<1>(lhs) + rhs); }\n\ninline Point2d operator*(const Point2d& point, const float& factor) { return Point2d(bg::get<0>(point) * factor , bg::get<1>(point) * factor); }\ninline Point2d operator/(const Point2d& point, const float& divisor) { return Point2d(bg::get<0>(point) / divisor , bg::get<1>(point) / divisor); }\n\nusing Pose = Eigen::Vector3d;\n\ninline std::string print(const Point2d &p) {\n  std::stringstream ss;\n  ss << \"Point2d: x: \" << bg::get<0>(p) << \", y: \" << bg::get<1>(p) << std::endl;\n  return ss.str();\n}\n\ninline float distance(const Point2d &p1, const Point2d &p2) {\n  float dx = bg::get<0>(p1) - bg::get<0>(p2);\n  float dy = bg::get<1>(p1) - bg::get<1>(p2);\n  return sqrt(dx * dx + dy * dy);\n}\n\ntemplate <typename G, typename T>\nstruct Shape {\n  Shape(const Pose &center, std::vector<T> points, int32_t id) : obj_(), id_(id), center_(center) {\n    for (auto it = points.begin(); it != points.end(); ++it)\n      add_point(*it);\n  }\n\n  Shape(const Pose &center, const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> &points, int32_t id) : obj_(), id_(id), center_(center) {\n    auto row_num = points.rows();\n    for (auto rowIter = 0; rowIter < row_num; ++rowIter) {\n      // std::vector<T> vec = points.rows(rowIter);\n      // for(auto col = 0;col<=1;++col){\n      // Point2d_t<T> p = (points(rowIter,0),points(rowIter,1))\n      add_point(T(points.coeff(rowIter, 0), points.coeff(rowIter, 1)));\n      //}\n    }\n  }\n\n  virtual ~Shape() {}\n  virtual Shape *Clone() const = 0;\n  virtual std::string ShapeToString() const;\n\n  // rotates object\n  Shape<G, T> *rotate(const float &a) const;\n\n  // translates object\n  Shape<G, T> *translate(const Point2d &point) const;\n\n  // return object transform\n  Shape<G, T> *transform(const Pose &pose) const;\n\n  bool Valid();\n\n  virtual Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> toArray() const = 0;\n\n  bool add_point(const T &p) {\n    bg::append(obj_, p);\n    return true;\n  }\n\n  G obj_;\n  int32_t id_;\n  Pose center_;  // fixed center pose of shape\n};\n\ntemplate <typename G, typename T>\ninline bool Shape<G, T>::Valid() {\n  std::string message;\n  bool valid = boost::geometry::is_valid(obj_, message);\n  if (!valid) {\n    std::cout << \"why not valid? \" << message << std::endl;\n  }\n  return valid;\n}\n\ntemplate <typename G, typename T>\ninline Shape<G, T> *Shape<G, T>::rotate(const float &a) const {\n  namespace trans = boost::geometry::strategy::transform;\n  // move shape relative to coordinate center\n  trans::translate_transformer<double, 2, 2> translate_rel_to_center(-center_[0], -center_[1]);\n  G obj_rel_translated;\n  boost::geometry::transform(obj_, obj_rel_translated, translate_rel_to_center);\n\n  // rotate (counterclockwise)\n  trans::rotate_transformer<boost::geometry::radian, double, 2, 2> rotate(-a);\n  G obj_rotated;\n  boost::geometry::transform(obj_rel_translated, obj_rotated, rotate);\n\n  // move object backwards plus translation component\n  trans::translate_transformer<double, 2, 2> translate_backwards(center_[0], center_[1]);\n  G obj_transformed;\n  boost::geometry::transform(obj_rotated, obj_transformed, translate_backwards);\n\n  Shape<G, T> *shape_transformed = this->Clone();\n  shape_transformed->obj_ = obj_transformed;\n  shape_transformed->center_[2] += a;\n  return shape_transformed;\n}\n\ntemplate <typename G, typename T>\ninline Shape<G, T> *Shape<G, T>::translate(const Point2d &point) const {\n  namespace trans = boost::geometry::strategy::transform;\n  trans::translate_transformer<double, 2, 2> translate_backwards(bg::get<0>(point), bg::get<1>(point));\n  G obj_transformed;\n  boost::geometry::transform(obj_, obj_transformed, translate_backwards);\n\n  Shape<G, T> *shape_transformed = this->Clone();\n  shape_transformed->obj_ = obj_transformed;\n  shape_transformed->center_[0] += bg::get<0>(point);\n  shape_transformed->center_[1] += bg::get<1>(point);\n  return shape_transformed;\n}\n\ntemplate <typename G, typename T>\ninline Shape<G, T> *Shape<G, T>::transform(const Pose &pose) const {\n  namespace trans = boost::geometry::strategy::transform;\n  // move shape relative to coordinate center\n  trans::translate_transformer<double, 2, 2> translate_rel_to_center(-center_[0], -center_[1]);\n  G obj_rel_translated;\n  boost::geometry::transform(obj_, obj_rel_translated, translate_rel_to_center);\n\n  // rotate (counterclockwise)\n  trans::rotate_transformer<boost::geometry::radian, double, 2, 2> rotate(-pose[2]);\n  G obj_rotated;\n  boost::geometry::transform(obj_rel_translated, obj_rotated, rotate);\n\n  // move object backwards plus translation component\n  trans::translate_transformer<double, 2, 2> translate_backwards(center_[0] + pose[0], center_[1] + pose[1]);\n  G obj_transformed;\n  boost::geometry::transform(obj_rotated, obj_transformed, translate_backwards);\n\n  Shape<G, T> *shape_transformed = this->Clone();\n  shape_transformed->obj_ = obj_transformed;\n  shape_transformed->center_[0] += pose[0];\n  shape_transformed->center_[1] += pose[1];\n  shape_transformed->center_[2] += pose[2];\n  return shape_transformed;\n}\n\ntemplate <typename G, typename T>\ninline std::string Shape<G, T>::ShapeToString() const {\n  std::stringstream ss;\n  Eigen::IOFormat OctaveFmt(Eigen::StreamPrecision, 0, \", \", \";\\n\", \"\", \"\", \"[\", \"]\");\n  ss << toArray().format(OctaveFmt);\n  return ss.str();\n}\n\n// template<typename G, typename T>\n// inline bool Shape<G,T>::Collide(const G& shape1, const G& shape2)\n//{\n//  return Collide(shape1, shape2);\n//}\n\n}  // namespace geometry\n}  // namespace modules\n\n#endif  // MODULES_GEOMETRY_COMMONS_HPP_\n", "meta": {"hexsha": "8d19f0bda21f11e1e2cbcd13a2498b0b1450fce4", "size": 7092, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/geometry/commons.hpp", "max_stars_repo_name": "grzPat/bark", "max_stars_repo_head_hexsha": "807092815c81eeb23defff473449a535a9c42f8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/geometry/commons.hpp", "max_issues_repo_name": "grzPat/bark", "max_issues_repo_head_hexsha": "807092815c81eeb23defff473449a535a9c42f8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/geometry/commons.hpp", "max_forks_repo_name": "grzPat/bark", "max_forks_repo_head_hexsha": "807092815c81eeb23defff473449a535a9c42f8b", "max_forks_repo_licenses": ["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.1836734694, "max_line_length": 154, "alphanum_fraction": 0.6910603497, "num_tokens": 2050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6113819874558603, "lm_q1q2_score": 0.5159422554028138}}
{"text": "// test suite for Quaternion class\n#include <cmath>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <gtest/gtest.h>\n\n#include <isce3/core/DenseMatrix.h>\n#include <isce3/core/EulerAngles.h>\n#include <isce3/core/Quaternion.h>\n#include <isce3/core/Vector.h>\n\nusing namespace isce3::core;\n\nstruct QuatEulerTest : public ::testing::Test {\n\n    void SetUp() override\n    {\n\n        // clang-format off\n    sc_pos << \n      -2434573.80388191110,\n      -4820642.06528653484,\n      4646722.94036952127;\n\n    sc_vel << \n      522.99592536068,\n      5107.80853161647,\n      5558.15620986960;\n\n    rot_mat << \n      0.0        ,  0.99987663, -0.01570732,\n      -0.79863551, -0.0094529 , -0.60174078,\n      -0.60181502,  0.01254442,  0.79853698;      \n\n    quat_ant2ecf << \n      0.14889715185,\n      0.02930644114,\n      -0.90605724862,\n      -0.39500763650;  \n\n    ypr_ant2tcn <<\n      -90.06934003*d2r,\n      0.78478177*d2r,\n      36.99994432*d2r;\n\n        // clang-format on\n    }\n\n    // common vars\n    const double d2r {M_PI / 180.0};\n    const double r2d {1.0 / d2r};\n    const double abs_err {1e-10};\n    const double yaw {-0.9 * d2r}, pitch {0.06 * d2r}, roll {0.15 * d2r};\n    const double mb_ang_deg {37.0};\n    const double squint_ang_deg {-0.9};\n    Vec3 sc_pos, sc_vel;\n    Mat3 rot_mat;\n    Vec4 quat_ant2ecf;\n    Vec3 ypr_ant2tcn;\n};\n\nTEST_F(QuatEulerTest, EulerBasicConstruct)\n{\n    auto elr = EulerAngles(yaw, pitch, roll);\n    ASSERT_NEAR(elr.yaw(), yaw, abs_err) << \"Wrong Yaw for Euler obj\";\n    ASSERT_NEAR(elr.pitch(), pitch, abs_err) << \"Wrong Pitch for Euler obj\";\n    ASSERT_NEAR(elr.roll(), roll, abs_err) << \"Wrong Roll for Euler obj\";\n}\n\nTEST_F(QuatEulerTest, QuatConstructMethod)\n{\n    //// Constructors\n\n    // from non unity quaternion vector  Vec4\n    auto uq_v4 = Quaternion(Vec4(2.0 * quat_ant2ecf));\n    EXPECT_NEAR(uq_v4.norm(), 1.0, abs_err)\n            << \"Quat from Vec4 is not normalied!\";\n    EXPECT_NEAR((quat_ant2ecf.tail(3) - uq_v4.vec()).norm(), 0.0, abs_err)\n            << \"Imag/vec part of Quat from Vec4 is not correct!\";\n    EXPECT_NEAR(std::abs(quat_ant2ecf(0) - uq_v4.w()), 0.0, abs_err)\n            << \"Real/scalar part of Quat from Vec4 is not correct!\";\n\n    // from non-unity 3-D vector Vec3\n    auto uq_v3 = Quaternion(sc_pos);\n    EXPECT_NEAR(std::abs(uq_v3.w()), 0.0, abs_err)\n            << \"Real/scalar part of Quat from Vec3 is wrong\";\n    EXPECT_NEAR((uq_v3.vec() - sc_pos.normalized()).norm(), 0.0, abs_err)\n            << \"Imag/Vec part of Quat from Vec3 is wrong\";\n\n    // from unitary rotmat , Mat3\n    auto uq_mat3 = Quaternion(rot_mat);\n    EXPECT_NEAR((uq_mat3.toRotationMatrix() - rot_mat).cwiseAbs().maxCoeff(),\n            0.0, 1e-8)\n            << \"Quat from rotation matrix and back fails!\";\n\n    // from YPR\n    auto uq_yaw = Quaternion(Eigen::AngleAxisd(yaw, Vec3::UnitZ()));\n    auto uq_pitch = Quaternion(Eigen::AngleAxisd(pitch, Vec3::UnitY()));\n    auto uq_roll = Quaternion(Eigen::AngleAxisd(roll, Vec3::UnitX()));\n    auto uq_ypr = Quaternion(yaw, pitch, roll);\n    ASSERT_TRUE(uq_ypr.isApprox(uq_yaw * uq_pitch * uq_roll))\n            << \"Quat from YPR must be the same as AngleAxis products \"\n               \"Yaw*Pitch*Roll\";\n\n    // from Euler object\n    auto uq_elr = Quaternion(EulerAngles(yaw, pitch, roll));\n    EXPECT_TRUE(uq_ypr.isApprox(uq_elr))\n            << \"Quat from YPR must be equal to Quat from EulerAngles\";\n\n    // from angle and 3-D vector\n    auto uq_angaxis = Quaternion(yaw, Vec3(2.0 * Vec3::UnitZ()));\n    EXPECT_TRUE(uq_angaxis.isApprox(uq_yaw))\n            << \"Quat from angle Yaw and scaled Z axis shall be Quat from \"\n               \"AngleAxis for yaw\";\n\n    //// methods\n\n    // to YPR\n    auto ypr_vec = uq_ypr.toYPR();\n    EXPECT_NEAR(ypr_vec(0), yaw, abs_err) << \"Wrong yaw angle!\";\n    EXPECT_NEAR(ypr_vec(1), pitch, abs_err) << \"Wrong pitch angle!\";\n    EXPECT_NEAR(ypr_vec(2), roll, abs_err) << \"Wrong roll angle!\";\n\n    // to isce3 EulerAngle object\n    auto elr_obj = uq_ypr.toEulerAngles();\n    EXPECT_NEAR(elr_obj.yaw(), yaw, abs_err)\n            << \"Wrong Yaw angle for EulerAngles Obj\";\n    EXPECT_NEAR(elr_obj.pitch(), pitch, abs_err)\n            << \"Wrong Pitch angle for EulerAngles Obj\";\n    EXPECT_NEAR(elr_obj.roll(), roll, abs_err)\n            << \"Wrong Roll angle for EulerAngles Obj\";\n\n    // to Eigen AngleAxis object\n    auto aa_obj = uq_angaxis.toAngleAxis();\n    EXPECT_NEAR(std::abs(aa_obj.angle()), std::abs(yaw), abs_err)\n            << \"Angle must be +/-Yaw\";\n    EXPECT_NEAR(\n            (aa_obj.axis().cwiseAbs() - Vec3::UnitZ()).cwiseAbs().maxCoeff(),\n            0.0, abs_err)\n            << \"Axis must be +/-Z axis!\";\n\n    // a practical SAR example via Rotatation of Vec3 in ECEF\n    auto uq_ant2ecf = Quaternion(quat_ant2ecf);\n    auto ant_ecf = uq_ant2ecf.rotate(Vec3::UnitZ());\n    Vec3 center_ecf {-sc_pos.normalized()};\n    double mb_ang {r2d * std::acos(center_ecf.dot(ant_ecf))};\n    EXPECT_NEAR(mb_ang, mb_ang_deg, 1e-1) << \"Wrong Geocentric MB angle!\";\n    double squint_ang {r2d * std::asin(ant_ecf.dot(sc_vel.normalized()))};\n    EXPECT_NEAR(squint_ang, squint_ang_deg, 1e-2) << \"Wrong Squint angle\";\n}\n\nTEST_F(QuatEulerTest, EulerConstructMethod)\n{\n    //// Constructors\n    const auto quat_ypr = Quaternion(yaw, pitch, roll);\n    const Mat3 matrot {quat_ypr.toRotationMatrix()};\n\n    // from rotation mat\n    auto elr_rotmat = EulerAngles(matrot);\n    EXPECT_NEAR(elr_rotmat.yaw(), yaw, abs_err)\n            << \"Wrong Euler yaw angle from rotmat\";\n    EXPECT_NEAR(elr_rotmat.pitch(), pitch, abs_err)\n            << \"Wrong Euler pitch angle from rotmat\";\n    EXPECT_NEAR(elr_rotmat.roll(), roll, abs_err)\n            << \"Wrong Euler roll angle from rotmat\";\n\n    // from quaternion\n    auto elr_quat = EulerAngles(quat_ypr);\n    EXPECT_NEAR(elr_quat.yaw(), yaw, abs_err)\n            << \"Wrong Euler yaw angle from quat\";\n    EXPECT_NEAR(elr_quat.pitch(), pitch, abs_err)\n            << \"Wrong Euler pitch angle from quat\";\n    EXPECT_NEAR(elr_quat.roll(), roll, abs_err)\n            << \"Wrong Euler roll angle from quat\";\n\n    //// Methods\n\n    // toRotationMatrix\n    auto rotm = elr_quat.toRotationMatrix();\n    EXPECT_NEAR((rotm - matrot).cwiseAbs().maxCoeff(), 0.0, abs_err)\n            << \"Wrong rotmat from Euler object!\";\n\n    // isApprox\n    auto elr_other = EulerAngles(\n            elr_quat.yaw() + abs_err, elr_quat.pitch(), elr_quat.roll());\n    EXPECT_FALSE(elr_other.isApprox(elr_quat, abs_err))\n            << \"Two Euler angles must not be equal!\";\n    EXPECT_TRUE(elr_other.isApprox(elr_quat))\n            << \"Two Euler angles must be equal!\";\n\n    // rotate\n    auto elr_ant2tcn =\n            EulerAngles(ypr_ant2tcn(0), ypr_ant2tcn(1), ypr_ant2tcn(2));\n    auto ant_tcn = elr_ant2tcn.rotate(Vec3::UnitZ());\n    EXPECT_NEAR(r2d * std::acos(ant_tcn(2)), mb_ang_deg, 1e-2)\n            << \"Wrong Geodetic MB angle for Euler rotate!\";\n\n    // toQuaternion\n    auto quat_elr = elr_quat.toQuaternion();\n    EXPECT_TRUE(quat_elr.isApprox(quat_ypr, abs_err))\n            << \"Back and forth conversion between Euler and Quat fails\";\n\n    // in-place addition/subtraction\n    auto elr_copy = EulerAngles(0.0, 0.0, 0.0);\n    elr_copy += elr_quat;\n    EXPECT_NEAR(elr_copy.yaw(), yaw, abs_err)\n            << \"Wrong Euler yaw angle after in-place add\";\n    EXPECT_NEAR(elr_copy.pitch(), pitch, abs_err)\n            << \"Wrong Euler pitch angle after in-place add\";\n    EXPECT_NEAR(elr_copy.roll(), roll, abs_err)\n            << \"Wrong Euler roll angle after in-place add\";\n\n    elr_copy -= elr_quat;\n    EXPECT_NEAR(elr_copy.yaw(), 0.0, abs_err)\n            << \"Wrong Euler yaw angle after in-place sub\";\n    EXPECT_NEAR(elr_copy.pitch(), 0.0, abs_err)\n            << \"Wrong Euler pitch angle after in-place sub\";\n    EXPECT_NEAR(elr_copy.roll(), 0.0, abs_err)\n            << \"Wrong Euler roll angle after in-place sub\";\n\n    // in-place multiplication/concatenation\n    elr_copy *= elr_quat;\n    EXPECT_NEAR(elr_copy.yaw(), yaw, abs_err)\n            << \"Wrong Euler yaw angle after in-place mul\";\n    EXPECT_NEAR(elr_copy.pitch(), pitch, abs_err)\n            << \"Wrong Euler pitch angle after in-place mul\";\n    EXPECT_NEAR(elr_copy.roll(), roll, abs_err)\n            << \"Wrong Euler roll angle after in-place mul\";\n\n    // binary add/subtract operators\n    auto elr_add = elr_quat + elr_quat;\n    EXPECT_NEAR(elr_add.yaw(), 2.0 * yaw, abs_err)\n            << \"Wrong Euler yaw angle after binary add\";\n    EXPECT_NEAR(elr_add.pitch(), 2.0 * pitch, abs_err)\n            << \"Wrong Euler pitch angle after binary add\";\n    EXPECT_NEAR(elr_add.roll(), 2.0 * roll, abs_err)\n            << \"Wrong Euler roll angle after binary add\";\n\n    elr_add = elr_quat - elr_quat;\n    EXPECT_NEAR(elr_add.yaw(), 0.0, abs_err)\n            << \"Wrong Euler yaw angle after binary sub\";\n    EXPECT_NEAR(elr_add.pitch(), 0.0, abs_err)\n            << \"Wrong Euler pitch angle after binary sub\";\n    EXPECT_NEAR(elr_add.roll(), 0.0, abs_err)\n            << \"Wrong Euler roll angle after binary sub\";\n\n    // binary multiplication/concatenation\n    // For simplicity, an approximation is used for validation based on small\n    // Euler angles (< 4.0 deg)\n    auto elr_mul = (elr_quat + elr_quat) * elr_quat;\n    EXPECT_NEAR(elr_mul.yaw(), 3.0 * yaw, 1e-4)\n            << \"Wrong Euler yaw angle after binary mul\";\n    EXPECT_NEAR(elr_mul.pitch(), 3.0 * pitch, 1e-4)\n            << \"Wrong Euler pitch angle after binary mul\";\n    EXPECT_NEAR(elr_mul.roll(), 3.0 * roll, 1e-4)\n            << \"Wrong Euler roll angle after binary mul\";\n}\n\nint main(int argc, char** argv)\n{\n\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "0802d5b1bd5a922a0f4c921c88c52664a373e8af", "size": 9701, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cxx/isce3/core/attitude/quaternion_euler.cpp", "max_stars_repo_name": "isce3-testing/isce3-circleci-poc", "max_stars_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2019-08-06T19:22:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T17:11:46.000Z", "max_issues_repo_path": "tests/cxx/isce3/core/attitude/quaternion_euler.cpp", "max_issues_repo_name": "isce-framework/isce3", "max_issues_repo_head_hexsha": "59cdd2c659a4879367db5537604b0ca93d26b372", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T22:46:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T00:05:28.000Z", "max_forks_repo_path": "tests/cxx/isce3/core/attitude/quaternion_euler.cpp", "max_forks_repo_name": "isce-framework/isce3", "max_forks_repo_head_hexsha": "59cdd2c659a4879367db5537604b0ca93d26b372", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2019-08-05T21:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T00:17:03.000Z", "avg_line_length": 36.3333333333, "max_line_length": 77, "alphanum_fraction": 0.6315843727, "num_tokens": 2860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5159422530530663}}
{"text": "\n#include <NTL/ZZ_pX.h>\n#include <NTL/lzz_pX.h>\n#include <NTL/GF2X.h>\n\n#include <NTL/version.h>\n\nNTL_CLIENT\n\n\n#define make_string_aux(x) #x\n#define make_string(x) make_string_aux(x)\n\nint SmallModulusTest(long p, long n)\n{\n   zz_pBak bak;\n\n   bak.save();\n\n\n   zz_p::init(p);\n\n   zz_pX a, b, c, cc;\n\n   random(a, n);\n   random(b, n);\n   PlainMul(c, a, b);\n   FFTMul(cc, a, b);\n\n   int res;\n   res = (c != cc);\n\n   bak.restore();\n\n   return res;\n}\n\n\nint GF2X_test()\n{\n   GF2X a, b, c, c1;\n\n   long n;\n\n#ifdef NTL_GF2X_LIB\n   for (n = 32; n <= (1L << 18); n = n << 1) {\n      random(a, n);\n      random(b, n);\n      OldMul(c, a, b);\n      mul(c1, a, b);\n      if (c1 != c) return 1;\n   }\n#endif\n\n   return 0;\n}\n\nvoid GF2X_time()\n{\n   long n = 1000000L;\n   long iter;\n\n   GF2X a, b, c;\n\n   double t;\n   long i;\n\n   random(a, n);\n   random(b, n);\n\n   mul(c, a, b);\n\n   iter = 0;\n   do {\n      iter = iter ? (2*iter) : 1;\n      t = GetTime();\n      for (i = 0; i < iter; i++)\n         mul(c, a, b);\n      t = GetTime() - t;\n   } while (t < 0.5);\n\n   cerr << \"time to multiply polynomials over GF(2) \\n   of degree < 1000000: \"\n        << (t/iter) << \"s\\n\";\n\n#ifdef NTL_GF2X_LIB\n   OldMul(c, a, b);\n\n   iter = 0;\n   do {\n      iter = iter ? (2*iter) : 1;\n      t = GetTime();\n      for (i = 0; i < iter; i++)\n         OldMul(c, a, b);\n      t = GetTime() - t;\n   } while (t < 0.5);\n\n   cerr << \"   **** using old code: \"  << (t/iter) << \"s\\n\";\n#endif\n\n}\n\n\nint main()\n{\n\n\n   cerr << \"This is NTL version \" << NTL_VERSION << \"\\n\"; \n\n   cerr << \"Basic Configuration Options:\\n\";\n\n\n#ifdef NTL_STD_CXX\n   cerr << \"NTL_STD_CXX\\n\";\n#endif\n\n#ifdef NTL_PSTD_NNS\n   cerr << \"NTL_PSTD_NNS\\n\";\n#endif\n\n#ifdef NTL_PSTD_NHF\n   cerr << \"NTL_PSTD_NHF\\n\";\n#endif\n\n#ifdef NTL_PSTD_NTN\n   cerr << \"NTL_PSTD_NTN\\n\";\n#endif\n\n#ifdef NTL_GMP_LIP\n   cerr << \"NTL_GMP_LIP\\n\";\n#endif\n\n#ifdef NTL_GMP_HACK\n   cerr << \"NTL_GMP_HACK\\n\";\n#endif\n\n#ifdef NTL_GF2X_LIB\n   cerr << \"NTL_GF2X_LIB\\n\";\n#endif\n\n\n#ifdef NTL_LONG_LONG_TYPE\n   cerr << \"NTL_LONG_LONG_TYPE: \";\n   cerr << make_string(NTL_LONG_LONG_TYPE) << \"\\n\";\n#endif\n\n#ifdef NTL_UNSIGNED_LONG_LONG_TYPE\n   cerr << \"NTL_UNSIGNED_LONG_LONG_TYPE: \";\n   cerr << make_string(NTL_UNSIGNED_LONG_LONG_TYPE) << \"\\n\";\n#endif\n\n#ifdef NTL_CXX_ONLY\n   cerr << \"NTL_CXX_ONLY\\n\";\n#endif\n\n\n#ifdef NTL_X86_FIX\n   cerr << \"NTL_X86_FIX\\n\";\n#endif\n\n#ifdef NTL_NO_X86_FIX\n   cerr << \"NTL_NO_X86_FIX\\n\";\n#endif\n\n#ifdef NTL_NO_INIT_TRANS\n   cerr << \"NTL_NO_INIT_TRANS\\n\";\n#endif\n\n#ifdef NTL_CLEAN_INT\n   cerr << \"NTL_CLEAN_INT\\n\";\n#endif\n\n#ifdef NTL_CLEAN_PTR\n   cerr << \"NTL_CLEAN_PTR\\n\";\n#endif\n\n#ifdef NTL_RANGE_CHECK\n   cerr << \"NTL_RANGE_CHECK\\n\";\n#endif\n\n\ncerr << \"\\n\";\ncerr << \"Resolution of double-word types:\\n\";\ncerr << make_string(NTL_LL_TYPE) << \"\\n\";\ncerr << make_string(NTL_ULL_TYPE) << \"\\n\";\n\n\ncerr << \"\\n\";\ncerr << \"Performance Options:\\n\";\n\n#ifdef NTL_LONG_LONG\n   cerr << \"NTL_LONG_LONG\\n\";\n#endif\n\n#ifdef NTL_AVOID_FLOAT\n   cerr << \"NTL_AVOID_FLOAT\\n\";\n#endif\n\n#ifdef NTL_SPMM_UL\n   cerr << \"NTL_SPMM_UL\\n\";\n#endif\n\n\n#ifdef NTL_SPMM_ULL\n   cerr << \"NTL_SPMM_ULL\\n\";\n#endif\n\n\n#ifdef NTL_SPMM_ASM\n   cerr << \"NTL_SPMM_ASM\\n\";\n#endif\n\n\n\n\n#ifdef NTL_AVOID_BRANCHING\n   cerr << \"NTL_AVOID_BRANCHING\\n\";\n#endif\n\n\n\n#ifdef NTL_TBL_REM\n   cerr << \"NTL_TBL_REM\\n\";\n#endif\n\n\n#ifdef NTL_GF2X_ALTCODE\n   cerr << \"NTL_GF2X_ALTCODE\\n\";\n#endif\n\n#ifdef NTL_GF2X_ALTCODE1\n   cerr << \"NTL_GF2X_ALTCODE1\\n\";\n#endif\n\n\n#ifdef NTL_GF2X_NOINLINE\n   cerr << \"NTL_GF2X_NOINLINE\\n\";\n#endif\n\n   cerr << \"\\n\\n\";\n\n   if (_ntl_gmp_hack)\n      cerr << \"using GMP hack\\n\\n\";\n\n   cerr << \"running tests...\";\n\n   long n, k;\n\n   n = 200;\n   k = 10*NTL_ZZ_NBITS;\n\n   ZZ p;\n\n   GenPrime(p, k);\n\n\n   ZZ_p::init(p);         // initialization\n\n   ZZ_pX f, g, h, r1, r2, r3;\n\n   random(g, n);    // g = random polynomial of degree < n\n   random(h, n);    // h =             \"   \"\n   random(f, n);    // f =             \"   \"\n\n   // SetCoeff(f, n);  // Sets coefficient of X^n to 1\n   \n   ZZ_p lc;\n\n   do {\n      random(lc);\n   } while (IsZero(lc));\n\n   SetCoeff(f, n, lc);\n\n\n   // For doing arithmetic mod f quickly, one must pre-compute\n   // some information.\n\n   ZZ_pXModulus F;\n   build(F, f);\n\n   PlainMul(r1, g, h);  // this uses classical arithmetic\n   PlainRem(r1, r1, f);\n\n   MulMod(r2, g, h, F);  // this uses the FFT\n\n   MulMod(r3, g, h, f);  // uses FFT, but slower\n\n   // compare the results...\n\n   if (r1 != r2) {\n      cerr << \"r1 != r2!!\\n\";\n      return 1;\n   }\n   else if (r1 != r3) {\n      cerr << \"r1 != r3!!\\n\";\n      return 1;\n   }\n\n\n   // small prime tests...I've made some changes in v5.3\n   // that should be checked on various platforms, so \n   // we might as well check them here.\n\n   if (SmallModulusTest(17, 1000)) {\n      cerr << \"first SmallModulusTest failed!!\\n\";\n      return 1;\n   }\n\n   if (SmallModulusTest((1L << (NTL_SP_NBITS))-1, 1000)) {\n      cerr << \"second SmallModulusTest failed!!\\n\";\n      return 1;\n   }\n\n   // Test gf2x code....\n\n   if (GF2X_test()) {\n      cerr << \"GF2X test failed!\\n\";\n      return 1;\n   }\n   \n\n   cerr << \"OK\\n\";\n\n   ZZ x1, x2, x3, x4;\n   double t;\n   long i;\n\n   RandomLen(x1, 1024);\n   RandomBnd(x2, x1);\n   RandomBnd(x3, x1);\n\n   mul(x4, x2, x3);\n\n   t = GetTime();\n   for (i = 0; i < 100000; i++)\n      mul(x4, x2, x3);\n   t = GetTime()-t;\n\n   cerr << \"time for 1024-bit mul: \" << t*10 << \"us\";\n\n   if (_ntl_gmp_hack) {\n      _ntl_gmp_hack = 0;\n      mul(x4, x2, x3);\n\n      t = GetTime();\n      for (i = 0; i < 100000; i++)\n         mul(x4, x2, x3);\n      t = GetTime()-t;\n\n      cerr << \" (\" << (t*10) << \"us without GMP)\"; \n\n      _ntl_gmp_hack = 1;\n   }\n\n   cerr << \"\\n\";\n\n   rem(x2, x4, x1);\n\n   t = GetTime();\n   for (i = 0; i < 100000; i++)\n      rem(x2, x4, x1);\n   t = GetTime()-t;\n\n   cerr << \"time for 2048/1024-bit rem: \" << t*10 << \"us\";\n\n   if (_ntl_gmp_hack) {\n      _ntl_gmp_hack = 0;\n      rem(x2, x4, x1);\n   \n      t = GetTime();\n      for (i = 0; i < 100000; i++)\n         rem(x2, x4, x1);\n      t = GetTime()-t;\n      cerr << \" (\" << (t*10) << \"us without GMP)\"; \n\n      _ntl_gmp_hack = 1;\n   }\n\n   cerr << \"\\n\";\n   \n\n   GenPrime(p, 1024);\n   RandomBnd(x1, p);\n   if (IsZero(x1)) set(x1);\n\n   InvMod(x2, x1, p);\n\n   t = GetTime();\n   for (i = 0; i < 1000; i++)\n      InvMod(x2, x1, p);\n   t = GetTime()-t;\n\n   cerr << \"time for 1024-bit modular inverse: \" << t*1000 << \"us\";\n\n   if (_ntl_gmp_hack) {\n      _ntl_gmp_hack = 0;\n      InvMod(x2, x1, p);\n   \n      t = GetTime();\n      for (i = 0; i < 1000; i++)\n         InvMod(x2, x1, p);\n      t = GetTime()-t;\n         cerr << \" (\" << (t*1000) << \"us without GMP)\"; \n\n      _ntl_gmp_hack = 1;\n   }\n\n   cerr << \"\\n\";\n\n\n\n   // test modulus switching\n   \n   n = 1024;\n   k = 1024;\n   RandomLen(p, k);\n\n   ZZ_p::init(p);\n   ZZ_pInfo->check();\n\n   ZZ_pX j1, j2, j3;\n\n   random(j1, n);\n   random(j2, n);\n\n   t = GetTime();\n   for (i = 0; i < 20; i++) mul(j3, j1, j2);\n   t = GetTime()-t;\n\n   cerr << \"time to multiply degree 1023 polynomials\\n   modulo a 1024-bit number: \";\n   cerr << (t/20) << \"s\";\n\n   if (_ntl_gmp_hack) {\n      _ntl_gmp_hack = 0;\n\n      ZZ_p::init(p);\n      ZZ_pInfo->check();\n\n      t = GetTime();\n      for (i = 0; i < 20; i++) mul(j3, j1, j2);\n      t = GetTime()-t;\n\n      cerr << \" (\" << (t/20) << \"s without GMP)\";\n      _ntl_gmp_hack = 1;\n   }\n\n   cerr << \"\\n\";\n\n   GF2X_time();\n\n   return 0;\n}\n", "meta": {"hexsha": "6328a5ffb6eb7caeddaacab663dc8055d2080335", "size": 7333, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/tests/QuickTest.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/QuickTest.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/QuickTest.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": 16.1876379691, "max_line_length": 85, "alphanum_fraction": 0.5333424247, "num_tokens": 2662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5159353035603389}}
{"text": "/* mwm\r\n * \r\n */\r\n\r\n#pragma once\r\n\r\n#ifdef _MICROCONTROLLER\r\n#include \"../matrix/matrix/math.hpp\"\r\n#else\r\n#include <Eigen/Dense>\r\n#endif\r\n\r\n#ifdef _MICROCONTROLLER\r\n//we use the PX4 class\r\ntemplate<typename Real, int M, int N>\r\nusing Matrix = matrix::Matrix<Real, M, N>;\r\n\r\ntemplate<typename Real, int M>\r\nusing SquareMatrix = matrix::SquareMatrix<Real, M>;\r\n\r\ntemplate<typename Real, int M, int N>\r\nMatrix<Real, M,N> ZeroMatrix() {\r\n  Matrix<Real, M, N> m;\r\n  m.zero();\r\n  return m;\r\n}\r\n\r\ntemplate<typename Real, int M>\r\nSquareMatrix<Real, M> IdentityMatrix() {\r\n  SquareMatrix<Real, M> m;\r\n  m.identity();\r\n  return m;\r\n}\r\n\r\n#else\r\ntemplate<typename Real, int M, int N>\r\nusing Matrix = Eigen::Matrix<Real, M, N>;\r\ntemplate<typename Real, int M>\r\nusing SquareMatrix = Eigen::Matrix<Real, M, M>;\r\n\r\ntemplate<typename Real, int M, int N>\r\nMatrix<Real, M, N> ZeroMatrix() {\r\n  return Matrix<Real, M, N>::Zero();\r\n}\r\n\r\ntemplate<typename Real, int M>\r\nSquareMatrix<Real, M> IdentityMatrix() {\r\n  return SquareMatrix<Real, M>::Identity();\r\n\r\n}\r\n#endif\r\n", "meta": {"hexsha": "2b52fa5a003e9ca4715efa87c5acd5e7f70ed95f", "size": 1048, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Common/Common/Math/Matrix.hpp", "max_stars_repo_name": "muellerlab/agri-fly", "max_stars_repo_head_hexsha": "6851f2f207e73300b4ed9be7ec1c72c2f23eeef5", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-09T21:31:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T21:31:49.000Z", "max_issues_repo_path": "Common/Common/Math/Matrix.hpp", "max_issues_repo_name": "muellerlab/agri-fly", "max_issues_repo_head_hexsha": "6851f2f207e73300b4ed9be7ec1c72c2f23eeef5", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2022-02-11T18:24:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T01:16:51.000Z", "max_forks_repo_path": "Common/Common/Math/Matrix.hpp", "max_forks_repo_name": "muellerlab/agri-fly", "max_forks_repo_head_hexsha": "6851f2f207e73300b4ed9be7ec1c72c2f23eeef5", "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": 20.1538461538, "max_line_length": 52, "alphanum_fraction": 0.6574427481, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5159352985748729}}
{"text": "#include <boost/foreach.hpp>\n#include <cfloat>\n#include \"ConvexHull.hpp\"\n\nusing namespace std;\n\nnamespace\n{\n\tVector2D GetReflectedPoint(Edge const& edge,Vector2D const& point)\n\t{\n\t  const Vector2D par(normalize(Parallel(edge)));\n\t  const Vector2D edge0=edge.vertices.first;\n\t  const Vector2D temp=point-edge0;\n\t  return 2*par*ScalarProd(par,temp)-temp+edge0;\n\t}\n\n  bool check_same_point(const vector<Vector2D>& vertices,\n\t\t\tconst Vector2D& p,\n\t\t\tdouble tol)\n  {\n    BOOST_FOREACH(const Vector2D& v, vertices)\n      {\n\tif(dist_sqr(v-p)<tol)\n\t  return true;\n      }\n    return false;\n  }\n}\n\nvoid ConvexHull(vector<Vector2D> &result,Tessellation const& tess,int index)\n{\n\tvector<int> edge_index=tess.GetCellEdges(index);\n\tconst double eps=1e-14;\n\tvector<Vector2D> points;\n\tpoints.reserve(10);\n\tdouble R=tess.GetWidth(index);\n\tpoints.push_back(tess.GetEdge(edge_index[0]).vertices.first);\n\tpoints.push_back(tess.GetEdge(edge_index[0]).vertices.second);\n\t// Remove identical points\n\tfor(size_t i=1;i<edge_index.size();++i)\n\t{\n\t  const Edge& edge = tess.GetEdge(edge_index[i]);\n\t\tif(!check_same_point(points,edge.vertices.first,eps*pow(R,2)))\n\t\t  points.push_back(edge.vertices.first);\n\t\tif(!check_same_point(points,edge.vertices.second,eps*pow(R,2)))\n\t\t  points.push_back(edge.vertices.second);\n\t}\n\n\tconst Vector2D cm = tess.GetCellCM(index);\n\t\n\t// Start building the convexhull\n\tsize_t n=points.size();\n\tvector<double> angles(n);\n\tfor(size_t i=0;i<n;++i)\n\t  angles.at(i)=atan2(points.at(i).y-cm.y,points.at(i).x-cm.x);\n\tconst vector<size_t> indeces = sort_index(angles);\n\tresult = VectorValues(points,indeces);\n}\n\nvoid ConvexEdges(vector<int> &result,Tessellation const& tess,int index)\n{\n\tvector<int> const& edges=tess.GetCellEdges(index);\n\tconst Vector2D mypoint=tess.GetMeshPoint(index);\n\tint nedges=static_cast<int>(edges.size());\n\tresult.resize(static_cast<size_t>(nedges));\n\tvector<double> angles(static_cast<size_t>(nedges));\n\tfor(int i=0;i<nedges;++i)\n\t{\n\t\tEdge const& edge=tess.GetEdge(edges[static_cast<size_t>(i)]);\n\t\tconst int other=(edge.neighbors.first==index)? edge.neighbors.second : edge.neighbors.first;\n\t\tVector2D otherpoint=(other==-1) ? GetReflectedPoint(edge,mypoint) : tess.GetMeshPoint(other);\n\t\tangles[static_cast<size_t>(i)]=atan2(otherpoint.y-mypoint.y,otherpoint.x-mypoint.x);\n\t}\n\tvector<int> temp;\n\tsort_index(angles,temp);\n\tfor(size_t i=0;i<static_cast<size_t>(nedges);++i)\n\t  result[i]=edges[static_cast<size_t>(temp[i])];\n}\n", "meta": {"hexsha": "10a2d1b7c7e52872ff4d996e64d645e6487bca95", "size": 2452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/ConvexHull.cpp", "max_stars_repo_name": "GalaxyHunters/Vivid", "max_stars_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "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": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/ConvexHull.cpp", "max_issues_repo_name": "GalaxyHunters/Vivid", "max_issues_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T18:13:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T14:54:04.000Z", "max_forks_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/ConvexHull.cpp", "max_forks_repo_name": "GalaxyHunters/Vivid", "max_forks_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-29T09:39:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-25T19:17:49.000Z", "avg_line_length": 31.0379746835, "max_line_length": 95, "alphanum_fraction": 0.7292006525, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.515935295877321}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm algebra elementary log10\n#include <boost/test/unit_test.hpp>\n#include \"fern/core/data_customization_point/scalar.h\"\n#include \"fern/algorithm/algebra/elementary/log10.h\"\n\n\nnamespace fa = fern::algorithm;\n\n\ntemplate<\n    class Value>\nusing OutOfDomainPolicy = fa::log10::OutOfDomainPolicy<Value>;\n\n\nBOOST_AUTO_TEST_CASE(out_of_domain_policy)\n{\n    {\n        OutOfDomainPolicy<double> policy;\n        BOOST_CHECK( policy.within_domain( 5));\n        BOOST_CHECK(!policy.within_domain(-5));\n        BOOST_CHECK( policy.within_domain( 0));\n        BOOST_CHECK( policy.within_domain(-0));\n    }\n}\n\n\ntemplate<\n    class Value,\n    class Result>\nvoid verify_value(\n    Value const& value,\n    Result const& result_we_want)\n{\n    fa::SequentialExecutionPolicy sequential;\n\n    Result result_we_get;\n    fa::algebra::log10(sequential, value, result_we_get);\n    BOOST_CHECK_EQUAL(result_we_get, result_we_want);\n}\n\n\nBOOST_AUTO_TEST_CASE(algorithm)\n{\n    verify_value<float, float>( 0.0f, -fern::infinity<float>());\n    verify_value<float, float>( 1.0f, 0.0f);\n    verify_value<float, float>( 9.0f, std::log10(9.0f));\n}\n", "meta": {"hexsha": "c0cdae8f6a42b6251fdd3f50c9dc84caf640b9ec", "size": 1610, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/elementary/test/log10_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/elementary/test/log10_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/elementary/test/log10_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["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.75, "max_line_length": 80, "alphanum_fraction": 0.6465838509, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.515935295877321}}
{"text": "// This file is part of KWIVER, and is distributed under the\n// OSI-approved BSD 3-Clause License. See top-level LICENSE file or\n// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.\n\n/// \\file\n/// \\brief test core essential matrix class\n\n#include <test_eigen.h>\n\n#include <vital/types/essential_matrix.h>\n\n#include <Eigen/SVD>\n\n#include <iostream>\n#include <vector>\n\nstatic constexpr double pi = 3.14159265358979323846;\n\nusing namespace kwiver::vital;\n\n// ----------------------------------------------------------------------------\nint main(int argc, char** argv)\n{\n  ::testing::InitGoogleTest( &argc, argv );\n  return RUN_ALL_TESTS();\n}\n\n// ----------------------------------------------------------------------------\nstatic bool is_similar(\n  matrix_3x3d const& m1, matrix_3x3d const& m2, double tol )\n{\n  return kwiver::testing::similar_matrix_comparator{}( m1, m2, tol );\n}\n\n// ----------------------------------------------------------------------------\nTEST(essential_matrix, constructors)\n{\n  rotation_d rot_d(vector_3d(0.0, 0.0, 0.0));\n  rotation_f rot_f(vector_3f(0.0, 0.0, 0.0));\n  vector_3d t_d(0.0, 1.0, 0.0);\n  vector_3f t_f(0.0, 1.0, 0.0);\n  essential_matrix_d d1 = essential_matrix_d(rot_d, t_d);\n  essential_matrix_f f1 = essential_matrix_f(rot_f, t_f);\n\n  essential_matrix_d d2 = essential_matrix_d(d1);\n  essential_matrix_f f2 = essential_matrix_f(f1);\n\n  EXPECT_MATRIX_SIMILAR(d1.matrix(), d2.matrix(), 1e-5);\n  EXPECT_MATRIX_SIMILAR(f1.matrix(), f2.matrix(), 1e-5);\n\n  essential_matrix_f f_from_d(d1);\n  EXPECT_MATRIX_SIMILAR(f_from_d.matrix(), f1.matrix(), 1e-5);\n\n  essential_matrix_d d_from_f(f1);\n  EXPECT_MATRIX_SIMILAR(d_from_f.matrix(), d1.matrix(), 1e-5);\n}\n\n// ----------------------------------------------------------------------------\nTEST(essential_matrix, twisted_rotation)\n{\n  rotation_d rot(vector_3d(0.0, 0.0, 0.0));\n  vector_3d t(0.48, 0.6, 0.64);\n  essential_matrix_d m(rot, t);\n  rotation_d twist = m.twisted_rotation();\n  EXPECT_EQ(twist.quaternion().x(), t.x());\n  EXPECT_EQ(twist.quaternion().y(), t.y());\n  EXPECT_EQ(twist.quaternion().z(), t.z());\n  EXPECT_EQ(twist.quaternion().w(), 0.0);\n}\n\n// ----------------------------------------------------------------------------\nTEST(essential_matrix, clone)\n{\n  rotation_d rot(vector_3d(0.0, 0.0, 0.0));\n  vector_3d t(0.48, 0.6, 0.64);\n  essential_matrix_d m(rot, t);\n  essential_matrix_sptr m_clone = m.clone();\n  EXPECT_MATRIX_SIMILAR(m.matrix(), m_clone->matrix(), 1e-12);\n}\n\n// ----------------------------------------------------------------------------\nTEST(essential_matrix, get)\n{\n  rotation_d rot(vector_3d(0.0, 0.0, 0.0));\n  vector_3d t(0.48, 0.6, 0.64);\n  essential_matrix_d m(rot, t);\n  EXPECT_EQ(m.get_rotation(), rot);\n  EXPECT_EQ(m.get_translation(), t);\n}\n\n// ----------------------------------------------------------------------------\nTEST(essential_matrix, properties)\n{\n  rotation_d rot(vector_3d(1.0, 2.0, 3.0));\n  vector_3d t(-1.0, 1.0, 4.0);\n\n  essential_matrix_d em(rot, t);\n  matrix_3x3d mat = em.matrix();\n\n  Eigen::JacobiSVD<matrix_3x3d> svd(mat, Eigen::ComputeFullV |\n                                         Eigen::ComputeFullU);\n  EXPECT_MATRIX_NEAR( ( vector_3d{ 1, 1, 0 } ), svd.singularValues(), 1e-14 );\n  EXPECT_NEAR( 1.0, em.translation().norm(), 1e-14 );\n\n  const matrix_3x3d W = (matrix_3x3d() << 0.0, -1.0, 0.0,\n                                          1.0,  0.0, 0.0,\n                                          0.0,  0.0, 1.0).finished();\n  const matrix_3x3d& U = svd.matrixU();\n  const matrix_3x3d& V = svd.matrixV();\n  vector_3d t_extracted = U.col(2);\n\n  vector_3d t_norm = t.normalized();\n  EXPECT_MATRIX_SIMILAR( t_extracted, t_norm, 1e-14 );\n\n  matrix_3x3d R1_extracted = U*W*V.transpose();\n  matrix_3x3d R2_extracted = U*W.transpose()*V.transpose();\n\n  if ( !is_similar( rot.matrix(), R1_extracted, 1e-14 ) &&\n       !is_similar( rot.matrix(), R2_extracted, 1e-14 ) )\n  {\n    ADD_FAILURE()\n      << \"Extracted rotation should match input or twisted pair\\n\"\n      << \"Input:\\n\" << rot.matrix() << \"\\n\"\n      << \"Result (v1):\\n\" << R1_extracted << \"\\n\"\n      << \"Result (v2):\\n\" << R2_extracted;\n  }\n}\n\n// ----------------------------------------------------------------------------\nTEST(essential_matrix, twisted_pair)\n{\n  rotation_d rot(vector_3d(1.0, 2.0, 3.0));\n  vector_3d t(-1.0, 1.0, 4.0);\n\n  essential_matrix_d em(rot, t);\n\n  // any combination of these should be an equivalent essential matrix\n  rotation_d R1 = em.rotation();\n  rotation_d R2 = em.twisted_rotation();\n  vector_3d t1 = em.translation();\n  vector_3d t2 = -t1;\n\n  rotation_d rot_t_180{ pi, t.normalized() };\n  EXPECT_MATRIX_NEAR( ( rot_t_180 * R1 ).matrix(), R2.matrix(), 1e-14 )\n    << \"Twisted pair rotation should be 180 degree rotation around t\";\n\n  essential_matrix_d em1(R1, t1), em2(R1, t2), em3(R2, t1), em4(R2, t2);\n  matrix_3x3d M1(em1.matrix()), M2(em2.matrix()),\n              M3(em3.matrix()), M4(em4.matrix());\n  matrix_3x3d M(em.matrix());\n\n  EXPECT_MATRIX_SIMILAR( M, M1, 1e-14 )\n    << \"Possible factorization 1 should match source\";\n  EXPECT_MATRIX_SIMILAR( M, M2, 1e-14 )\n    << \"Possible factorization 2 should match source\";\n  EXPECT_MATRIX_SIMILAR( M, M3, 1e-14 )\n    << \"Possible factorization 3 should match source\";\n  EXPECT_MATRIX_SIMILAR( M, M4, 1e-14 )\n    << \"Possible factorization 4 should match source\";\n}\n", "meta": {"hexsha": "e777af03883b38243377785b8bddd0eb042dffbe", "size": 5364, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vital/tests/test_essential_matrix.cxx", "max_stars_repo_name": "willdunklin/kwiver", "max_stars_repo_head_hexsha": "7642af7cc9c8727f85b322331164569665bae224", "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": "vital/tests/test_essential_matrix.cxx", "max_issues_repo_name": "willdunklin/kwiver", "max_issues_repo_head_hexsha": "7642af7cc9c8727f85b322331164569665bae224", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vital/tests/test_essential_matrix.cxx", "max_forks_repo_name": "willdunklin/kwiver", "max_forks_repo_head_hexsha": "7642af7cc9c8727f85b322331164569665bae224", "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.3167701863, "max_line_length": 79, "alphanum_fraction": 0.5837061894, "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5158426199578369}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_CORE_FUNCTIONS_GLOBALNORM_HPP_INCLUDED\n#define NT2_CORE_FUNCTIONS_GLOBALNORM_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <nt2/sdk/meta/as_real.hpp>\n#include <boost/mpl/int.hpp>\n\nnamespace nt2 { namespace tag\n  {\n    /*!\n      @brief globalnorm generic tag\n\n      Represents the globalnorm function in generic contexts.\n\n      @par Models:\n      Hierarchy\n    **/\n    struct globalnorm_ : ext::abstract_<globalnorm_>\n    {\n      /// @brief Parent hierarchy\n      typedef ext::abstract_<globalnorm_> parent;\n      template<class... Args>\n      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)\n      BOOST_AUTO_DECLTYPE_BODY( dispatching_globalnorm_( ext::adl_helper(), static_cast<Args&&>(args)... ) )\n    };\n  }\n  namespace ext\n  {\n    template<class Site>\n    BOOST_FORCEINLINE generic_dispatcher<tag::globalnorm_, Site> dispatching_globalnorm_(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)\n    {\n      return generic_dispatcher<tag::globalnorm_, Site>();\n    }\n    template<class... Args>\n    struct impl_globalnorm_;\n  }\n\n  /*!\n    @brief Global norm\n\n    Computes the norm of a whole table expression with static or dynamic choice\n    of the norm computation formula.\n\n    Call protocols to globalnorm are summarized in the following table. We advise to use static\n    calls whenever possible as it prevents cascaded run-time if clauses and goes directly\n    to the right call at execution.\n\n    @code\n    |--------------------|-------------------|------------------------------|-------------------|\n    | mnorm(a0, p)                                                                              |\n    |--------------------|-------------------|------------------------------|-------------------|\n    |    static p        |  dynamic p        |     formula (pseudo-code)    |  equivalent to    |\n    |--------------------|-------------------|------------------------------|-------------------|\n    | nt2::one_          | 1                 |       sum(abs(x(_)))         | globalnorm1(x)    |\n    | nt2::two_          | 2                 |   sqrt(sum(sqr(abs(x(_)))))  | globalnorm2(x)    |\n    |    -               | p (positive)      |    sum(abs(x)^p)^(1/p)       | globalnormp(x,p)  |\n    | nt2::inf_          | nt2::Inf<T>()     |       max(abs((x))           | globalnorminf(x)  |\n    | nt2::fro_          | -1                |   sqrt(sum(sqr(abs(x(_)))))  | globalnormfro(x)  |\n    |--------------------|-------------------|------------------------------|-------------------|\n    | mnorm<p>(a0)                                                                              |\n    |--------------------|-------------------|------------------------------|-------------------|\n    |    static p        |                   |     matrix                   |                   |\n    |--------------------|-------------------|------------------------------|-------------------|\n    | nt2::tag::one_ or 1|        -          |       sum(abs(x(_)))         |  globalnorm1(x)   |\n    | nt2::tag::two_ or 2|        -          |   sqrt(sum(sqr(abs(x(_)))))  |  globalnorm2(x)   |\n    | p  (integer only)  |        -          |    sum(abs(x)^p)^(1/p)       |  globalnormp(x,p) |\n    | nt2::tag::inf_     |        -          |       max(abs((x))           |  globalnorminf(x) |\n    | nt2::tag::fro_     |        -          |   sqrt(sum(sqr(abs(x(_)))))  |  globalnormfro(x) |\n    |--------------------|-------------------|------------------------------|-------------------|\n    @endcode\n\n    @par Semantic:\n\n    For any expression @c a0 of type @c A0, the following call:\n\n    @code\n    as_real<A0::value_type>::type x = globalnorm(a0);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    as_real<A0::value_type>::type x = globalnorm2(a0);\n    @endcode\n\n    For any expression @c a0 of type @c A0 and any floating point value @c p, the\n    following call:\n\n    @code\n    as_real<A0::value_type>::type x = globalnorm(a0,p);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    as_real<A0::value_type>::type x = globalnormp(a0,p);\n    @endcode\n\n    if @c p is finite and to :\n\n    @code\n    as_real<A0::value_type>::type x = globalmax(abs(a0));\n    @endcode\n\n    if @c is +Inf and to :\n\n    @code\n    as_real<A0::value_type>::type x = globalmin(abs(a0));\n    @endcode\n\n    if @c p is -Inf.\n\n    @note If 0 < p < 1 or p = -inf, globalnorm does not share the properties that\n    define a mathematical norm,  but only a quasi-norm if  0 < p < 1 and a notation\n    facility for p = -inf.\n\n    @par Static Interface\n\n    globalnorm can also be invoked with a template parameter which is either a\n    functor tag describing the constant value to use instead of @c p or an\n    Integral Constant. For example,\n\n    @code\n    as_real<A0::value_type>::type x = globalnorm<tag::two_>(a0);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    as_real<A0::value_type>::type x = globalnorm2(a0);\n    @endcode\n\n    Similarly,\n\n    @code\n    as_real<A0::value_type>::type x = globalnorm<5>(a0);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    as_real<A0::value_type>::type x = globalnormp(a0,5);\n    @endcode\n\n    @note Whenever a constant functor tag or an Integral Constant is used, compile\n    time optimization is performed (if available) so the correct variant of globalnorm is\n    called. For example, calls similar to globalnorm<2>(a0) will invoke\n    globalnorm2(a0) instead of globalnormp(a0, 2), and globalnorm<5>(a0) will simply\n    invoke directly globalnormp(a0, 5) but without any runtime selection.\n\n    @param a0 Expression to compute the norm of\n    @param a1 Type of norm to compute\n  **/\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(nt2::tag::globalnorm_, globalnorm, 2)\n\n  /// @overload\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(nt2::tag::globalnorm_, globalnorm, 1)\n\n  /// @overload\n  template<typename Tag, typename A0>\n  BOOST_FORCEINLINE typename meta::as_real<typename A0::value_type>::type\n  globalnorm(const A0& a0)\n  {\n    return globalnorm(a0, nt2::meta::as_<Tag>());\n  }\n\n  /// @overload\n  template<int Value, typename A0>\n  BOOST_FORCEINLINE typename meta::as_real<typename A0::value_type>::type\n  globalnorm(const A0& a0)\n  {\n    return globalnorm(a0, boost::mpl::int_<Value>() );\n  }\n}\n\n#endif\n", "meta": {"hexsha": "26219a639299d7fe678186b66acc98b14a98fc8e", "size": 6756, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/reduction/include/nt2/core/functions/globalnorm.hpp", "max_stars_repo_name": "feelpp/nt2", "max_stars_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/reduction/include/nt2/core/functions/globalnorm.hpp", "max_issues_repo_name": "feelpp/nt2", "max_issues_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "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": "modules/core/reduction/include/nt2/core/functions/globalnorm.hpp", "max_forks_repo_name": "feelpp/nt2", "max_forks_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 36.5189189189, "max_line_length": 144, "alphanum_fraction": 0.5164298401, "num_tokens": 1692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5158426123330625}}
{"text": "#include \"eigen_csv.hpp\"\n\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <iostream>\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    using namespace std;\n    using namespace Eigen;\n\n    string filename;\n\n    // Number of tests\n    int Ntest = 100;\n\n    // Number of filters & filter names\n    int Nfilters = 5;\n    vector<string> filter_names(Nfilters);\n    filter_names[0] = \"ukf\";\n    filter_names[1] = \"cut4\";\n    filter_names[2] = \"cut6\";\n    filter_names[3] = \"cut8\";\n    filter_names[4] = \"house\";\n\n    // Read times\n    VectorXd T;\n    EigenCSV::read(\"out/times.csv\", false, true, T);\n    int Ntimes = T.size();\n\n    // Results table\n    MatrixXd table(Ntimes, 1+3*Nfilters);\n\n    for (int l = 0; l < Nfilters; l++) {\n\n        VectorXd\n        pos_rmse(Ntimes), vel_rmse(Ntimes), ome_rmse(Ntimes),\n        pos_avge(Ntimes), vel_avge(Ntimes), ome_avge(Ntimes),\n        pos_stde(Ntimes), vel_stde(Ntimes), ome_stde(Ntimes);\n\n        for (int i = 0; i < Ntimes; i++) {\n\n            MatrixXd tabtru, pos_tru, vel_tru, ome_tru;\n\n            filename = \"out/ct_true_\";\n            filename += to_string(i+1);\n            filename += \".csv\";\n\n            EigenCSV::read(filename, true, true, tabtru);\n\n            int nt = tabtru.rows();\n\n            pos_tru.resize(nt, 2);\n            vel_tru.resize(nt, 2);\n            ome_tru.resize(nt, 1);\n\n            pos_tru << tabtru.col(1), tabtru.col(3);\n            vel_tru << tabtru.col(2), tabtru.col(4);\n            ome_tru = tabtru.col(5);\n\n            MatrixXd pos_err(nt*Ntest, 2), vel_err(nt*Ntest, 2), ome_err(nt*Ntest, 1);\n\n            for (int j = 0; j < Ntest; j++) {\n\n                MatrixXd tabest, pos_est(nt,2), vel_est(nt,2), ome_est(nt,1);\n\n                filename = est_filename(filter_names[l], i, j);\n\n                EigenCSV::read(filename, true, true, tabest);\n\n                pos_est << tabest.col(1), tabest.col(3);\n                vel_est << tabest.col(2), tabest.col(4);\n                ome_est = tabest.col(5);\n\n                pos_err.block(j*nt, 0, nt, 2) = pos_est - pos_tru;\n                vel_err.block(j*nt, 0, nt, 2) = vel_est - vel_tru;\n                ome_err.block(j*nt, 0, nt, 1) = ome_est - ome_tru;\n\n            }\n\n            pos_rmse(i) = sqrt(pos_err.array().square().mean() * 2);\n            vel_rmse(i) = sqrt(vel_err.array().square().mean() * 2);\n            ome_rmse(i) = sqrt(ome_err.array().square().mean());\n\n            pos_avge(i) = pos_err.mean();\n            vel_avge(i) = vel_err.mean();\n            ome_avge(i) = ome_err.mean();\n\n            pos_stde(i) = sqrt((pos_err.array() - pos_avge(i)).square().mean());\n            vel_stde(i) = sqrt((vel_err.array() - pos_avge(i)).square().mean());\n            ome_stde(i) = sqrt((ome_err.array() - ome_avge(i)).square().mean());\n\n        }\n\n        MatrixXd tabfil(Ntimes, 10);\n        tabfil << T, pos_rmse, pos_avge, pos_stde,\n                     vel_rmse, vel_avge, vel_stde,\n                     ome_rmse, ome_avge, ome_stde;\n\n        vector<string> header(10);\n        header[0] = \"TIME\";\n        header[1] = \"POS RMSE\"; header[2] = \"POS AVGE\"; header[3] = \"POS STDE\";\n        header[4] = \"VEL RMSE\"; header[5] = \"VEL AVGE\"; header[6] = \"VEL STDE\";\n        header[7] = \"OME RMSE\"; header[8] = \"OME AVGE\"; header[9] = \"OME STDE\";\n\n        filename = \"out/ct_err_\";\n        filename += filter_names[l];\n        filename += \".csv\";\n\n        EigenCSV::write(tabfil, header, filename);\n\n    }\n\n    return 0;\n\n}\n\n", "meta": {"hexsha": "03d7cf9809edb10fc6294d64781d11934d17b8d2", "size": 3718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CT_Pearson/statct.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_Pearson/statct.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_Pearson/statct.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": 28.3816793893, "max_line_length": 86, "alphanum_fraction": 0.5317374933, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839876, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.515825895123722}}
{"text": "// Copyright (C) 2014 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/estimators/estimate_triangulation.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <limits>\n\n#include \"theia/sfm/camera/camera.h\"\n#include \"theia/sfm/create_and_initialize_ransac_variant.h\"\n#include \"theia/sfm/triangulation/triangulation.h\"\n#include \"theia/sfm/types.h\"\n#include \"theia/solvers/estimator.h\"\n#include \"theia/solvers/ransac.h\"\n#include \"theia/solvers/sample_consensus_estimator.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\n\nnamespace {\n// The pixel observation and projection matrix needed in order to triangulate a\n// 3D point.\nstruct PointObservation {\n  Matrix3x4d projection_matrix;\n  Camera camera;\n  Eigen::Vector2d normalized_feature;\n  Eigen::Vector2d observed_pixel;\n};\n\n// Returns true if the point is in front of the camera and false if the point is\n// behind the camera.\nbool IsPointInFrontOfCamera(const Matrix3x4d& projection_matrix,\n                            const Eigen::Vector4d& point) {\n  return point.dot(projection_matrix.row(2)) > 0;\n}\n\nclass TriangulationEstimator\n    : public Estimator<PointObservation, Eigen::Vector4d> {\n public:\n  TriangulationEstimator() {}\n\n  double SampleSize() const { return 2; }\n\n  // Triangulates the 3D point from 2 observations.\n  bool EstimateModel(const std::vector<PointObservation>& observations,\n                     std::vector<Eigen::Vector4d>* triangulated_points) const {\n    triangulated_points->resize(1);\n    if (!Triangulate(observations[0].projection_matrix,\n                     observations[1].projection_matrix,\n                     observations[0].normalized_feature,\n                     observations[1].normalized_feature,\n                     &triangulated_points->at(0))) {\n      return false;\n    }\n\n    // Only return true if the point is in front of both cameras and the\n    // triangulation was a success.\n    return IsPointInFrontOfCamera(observations[0].projection_matrix,\n                                  triangulated_points->at(0)) &&\n           IsPointInFrontOfCamera(observations[1].projection_matrix,\n                                  triangulated_points->at(0));\n  }\n\n  double Error(const PointObservation& observation,\n               const Eigen::Vector4d& triangulated_point) const {\n    Eigen::Vector2d reprojection;\n    const double depth =\n        observation.camera.ProjectPoint(triangulated_point, &reprojection);\n    if (depth <= 0) {\n      return std::numeric_limits<double>::max();\n    }\n    return (observation.observed_pixel - reprojection).squaredNorm();\n  }\n};\n\n}  // namespace\n\nbool EstimateTriangulation(const RansacParameters& ransac_params,\n                           const std::vector<Camera>& cameras,\n                           const std::vector<theia::Feature>& features,\n                           Eigen::Vector4d* triangulated_point,\n                           RansacSummary* summary) {\n  CHECK_EQ(cameras.size(), features.size());\n  CHECK_NOTNULL(triangulated_point);\n\n  // If we only have a few data points, then we should exhaustively search the\n  // solution space for the best combination.\n  static const int kMaxNumDataPointsForExhaustiveSearch = 15;\n  if (cameras.size() < 2) {\n    return false;\n  }\n\n  // Create point correspondences.\n  std::vector<PointObservation> point_observations(cameras.size());\n  for (int i = 0; i < point_observations.size(); i++) {\n    // Create the projection atirx.\n    Matrix3x4d projection_matrix;\n    projection_matrix.leftCols<3>() =\n        cameras[i].GetOrientationAsRotationMatrix();\n    projection_matrix.rightCols<1>() =\n        -projection_matrix.leftCols<3>() * cameras[i].GetPosition();\n\n    point_observations[i].projection_matrix = projection_matrix;\n    point_observations[i].camera = cameras[i];\n    point_observations[i].normalized_feature =\n        cameras[i].PixelToNormalizedCoordinates(features[i].point_).hnormalized();\n    point_observations[i].observed_pixel = features[i].point_;\n  }\n\n  // RANSAC triangulation.\n  TriangulationEstimator triangulation_estimator;\n  std::unique_ptr<SampleConsensusEstimator<TriangulationEstimator> > ransac;\n  if (cameras.size() <= kMaxNumDataPointsForExhaustiveSearch) {\n    // Set the minimum number of iterations to be the exact number of possible\n    // combinations. This forces all combinations to be tested.\n    const int num_combinations = cameras.size() * (cameras.size() - 1) / 2;\n    RansacParameters exhaustive_params = ransac_params;\n    exhaustive_params.min_iterations = num_combinations;\n    exhaustive_params.max_iterations = num_combinations;\n    ransac = CreateAndInitializeRansacVariant<TriangulationEstimator>(\n        RansacType::EXHAUSTIVE, exhaustive_params, triangulation_estimator);\n  } else {\n    ransac = CreateAndInitializeRansacVariant<TriangulationEstimator>(\n        RansacType::RANSAC, ransac_params, triangulation_estimator);\n  }\n\n  // Run the RANSAC scheme.\n  CHECK(ransac->Initialize());\n  return ransac->Estimate(point_observations, triangulated_point, summary);\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "97fc51b795e1268f5838799ae6d257696f860caa", "size": 6784, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/estimators/estimate_triangulation.cc", "max_stars_repo_name": "Sergej91/TheiaSfM", "max_stars_repo_head_hexsha": "e603e16888456c3e565a2c197fa9f8643c176175", "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/theia/sfm/estimators/estimate_triangulation.cc", "max_issues_repo_name": "Sergej91/TheiaSfM", "max_issues_repo_head_hexsha": "e603e16888456c3e565a2c197fa9f8643c176175", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/estimators/estimate_triangulation.cc", "max_forks_repo_name": "Sergej91/TheiaSfM", "max_forks_repo_head_hexsha": "e603e16888456c3e565a2c197fa9f8643c176175", "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.1151515152, "max_line_length": 82, "alphanum_fraction": 0.7165389151, "num_tokens": 1525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5158258896544624}}
{"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 \"MLP.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidDataSet.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/FluidTensor.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <limits>\n#include <random>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass SGD\n{\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXXd = Eigen::ArrayXXd;\n  using Permutation = Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic>;\n\npublic:\n  explicit SGD() = default;\n  ~SGD() = default;\n\n  double train(MLP& model, const RealMatrixView in, RealMatrixView out,\n               index nIter, index batchSize, double learningRate,\n               double momentum, double valFrac)\n  {\n    using namespace _impl;\n    using namespace std;\n    using namespace Eigen;\n    index       nExamples = in.rows();\n    index       inputSize = in.cols();\n    index       outputSize = out.cols();\n    ArrayXXd    input = asEigen<Eigen::Array>(in);\n    ArrayXXd    output = asEigen<Eigen::Array>(out);\n    Permutation valPerm(nExamples);\n    valPerm.setIdentity();\n    shuffle(valPerm.indices().data(),\n            valPerm.indices().data() + valPerm.indices().size(),\n            mt19937{random_device{}()});\n    input = valPerm * input.matrix();\n    output = valPerm * output.matrix();\n    index nVal = std::lround(nExamples * valFrac);\n    index nTrain = nExamples - nVal;\n\n    ArrayXXd trainInput = input.block(0, 0, nTrain, inputSize);\n    ArrayXXd trainOutput = output.block(0, 0, nTrain, outputSize);\n    ArrayXXd valInput = input.block(nTrain, 0, nVal, inputSize);\n    ArrayXXd valOutput = output.block(nTrain, 0, nVal, outputSize);\n\n    Permutation iterPerm(nTrain);\n    iterPerm.setIdentity();\n    double error = 0;\n    index  patience = mInitialPatience;\n    double prevValLoss = std::numeric_limits<double>::max();\n    while (nIter-- > 0)\n    {\n      shuffle(iterPerm.indices().data(),\n              iterPerm.indices().data() + iterPerm.indices().size(),\n              mt19937{random_device{}()});\n      ArrayXXd inPerm = iterPerm * trainInput.matrix();\n      ArrayXXd outPerm = iterPerm * trainOutput.matrix();\n      for (index batchStart = 0; batchStart < inPerm.rows();\n           batchStart += batchSize)\n      {\n        index thisBatchSize = (batchStart + batchSize) <= nTrain\n                                  ? batchSize\n                                  : nTrain - batchStart;\n        ArrayXXd batchIn =\n            inPerm.block(batchStart, 0, thisBatchSize, inPerm.cols());\n        ArrayXXd batchOut =\n            outPerm.block(batchStart, 0, thisBatchSize, outPerm.cols());\n        ArrayXXd batchPred = ArrayXXd::Zero(thisBatchSize, outputSize);\n        model.forward(batchIn, batchPred);\n        ArrayXXd diff = batchPred - batchOut;\n        model.backward(diff);\n        model.update(learningRate, momentum);\n      }\n      if (nVal > 0)\n      {\n        ArrayXXd valPred = ArrayXXd::Zero(nVal, outputSize);\n        model.forward(valInput, valPred);\n        double valLoss = model.loss(valPred, valOutput);\n        if (valLoss < prevValLoss)\n          patience = mInitialPatience;\n        else\n          patience--;\n        if (patience <= 0) break;\n        prevValLoss = valLoss;\n      }\n    }\n    ArrayXXd finalPred = ArrayXXd::Zero(nExamples, outputSize);\n    model.forward(input, finalPred);\n    bool isNan = !((finalPred == finalPred)).all();\n    if (isNan)\n    {\n      model.clear();\n      return -1;\n    }\n    error = model.loss(finalPred, output);\n    model.setTrained(true);\n    return error;\n  }\n\nprivate:\n  index mInitialPatience{10};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "1b6e10e24469b7162c4189d3b66994aed6f16912", "size": 4062, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/SGD.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/SGD.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/SGD.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": 33.2950819672, "max_line_length": 79, "alphanum_fraction": 0.6398325948, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.5158065229201876}}
{"text": "#include \"cryptonote_config.h\"\n#include \"common/gyuanx.h\"\n#include \"epee/int-util.h\"\n#include <limits>\n#include <vector>\n#include <boost/lexical_cast.hpp>\n#include <cfenv>\n\n#include \"gnode_rules.h\"\n\nnamespace gnodes {\n\n// TODO(gyuanx): Move to gyuanx_economy, this will also need access to gyuanx::exp2\nuint64_t get_staking_requirement(cryptonote::network_type m_nettype, uint64_t height, uint8_t hf_version)\n{\n  if (m_nettype == cryptonote::TESTNET || m_nettype == cryptonote::FAKECHAIN)\n      return COIN * 100;\n\n  // For devnet we use the 10% of mainnet requirement at height (650k + H) so that we follow\n  // (proportionally) whatever staking changes happen on mainnet.  (The 650k is because devnet\n  // launched at ~600k mainnet height, so this puts it a little ahead).\n  if (m_nettype == cryptonote::DEVNET)\n      return get_staking_requirement(cryptonote::MAINNET, 600000 + height, hf_version) / 10;\n\n  if (hf_version >= cryptonote::network_version_16_pulse)\n    return 1000'000000000000;\n\n  if (hf_version >= cryptonote::network_version_13_enforce_checkpoints)\n  {\n    // TODO: after HF16 we can remove excess elements here: we need to keep the first one higher\n    // than the HF16 fork height, but can delete everything above that (which probably will mean\n    // removing 688244 and above).\n    constexpr int64_t heights[] = {\n        85,\n        90,\n        95,\n    };\n\n    constexpr int64_t lsr[] = {\n        204'380815527,\n        193'319724305,\n        200'564443912,\n    };\n\n    assert(static_cast<int64_t>(height) >= heights[0]);\n    constexpr uint64_t LAST_HEIGHT      = heights[gyuanx::array_count(heights) - 1];\n    constexpr uint64_t LAST_REQUIREMENT = lsr    [gyuanx::array_count(lsr) - 1];\n    if (height >= LAST_HEIGHT)\n        return LAST_REQUIREMENT;\n\n    size_t i = 0;\n    for (size_t index = 1; index < gyuanx::array_count(heights); index++)\n    {\n      if (heights[index] > static_cast<int64_t>(height))\n      {\n        i = (index - 1);\n        break;\n      }\n    }\n\n    int64_t H      = height;\n    int64_t result = lsr[i] + (H - heights[i]) * ((lsr[i + 1] - lsr[i]) / (heights[i + 1] - heights[i]));\n    return static_cast<uint64_t>(result);\n  }\n\n  uint64_t hardfork_height = 101;\n  if (height < hardfork_height) height = hardfork_height;\n\n  uint64_t height_adjusted = height - hardfork_height;\n  uint64_t base = 0, variable = 0;\n  std::fesetround(FE_TONEAREST);\n  if (hf_version >= cryptonote::network_version_11_infinite_staking)\n  {\n    base     = 15000 * COIN;\n    variable = (25007.0 * COIN) / gyuanx::exp2(height_adjusted/129600.0);\n  }\n  else\n  {\n    base      = 10000 * COIN;\n    variable  = (35000.0 * COIN) / gyuanx::exp2(height_adjusted/129600.0);\n  }\n\n  uint64_t result = base + variable;\n  return result;\n}\n\nuint64_t portions_to_amount(uint64_t portions, uint64_t staking_requirement)\n{\n  uint64_t hi, lo, resulthi, resultlo;\n  lo = mul128(staking_requirement, portions, &hi);\n  div128_64(hi, lo, STAKING_PORTIONS, &resulthi, &resultlo);\n  return resultlo;\n}\n\nbool check_gnode_portions(uint8_t hf_version, const std::vector<uint64_t>& portions)\n{\n  if (portions.size() > MAX_NUMBER_OF_CONTRIBUTORS) return false;\n\n  uint64_t reserved = 0;\n  for (auto i = 0u; i < portions.size(); ++i)\n  {\n    const uint64_t min_portions = get_min_node_contribution(hf_version, STAKING_PORTIONS, reserved, i);\n    if (portions[i] < min_portions) return false;\n    reserved += portions[i];\n  }\n\n  return reserved <= STAKING_PORTIONS;\n}\n\ncrypto::hash generate_request_stake_unlock_hash(uint32_t nonce)\n{\n  crypto::hash result   = {};\n  char const *nonce_ptr = (char *)&nonce;\n  char *hash_ptr        = result.data;\n  static_assert(sizeof(result) % sizeof(nonce) == 0, \"The nonce should be evenly divisible into the hash\");\n  for (size_t i = 0; i < sizeof(result) / sizeof(nonce); ++i)\n  {\n    memcpy(hash_ptr, nonce_ptr, sizeof(nonce));\n    hash_ptr += sizeof(nonce);\n  }\n\n  assert(hash_ptr == (char *)result.data + sizeof(result));\n  return result;\n}\n\nuint64_t get_locked_key_image_unlock_height(cryptonote::network_type nettype, uint64_t node_register_height, uint64_t curr_height)\n{\n  uint64_t blocks_to_lock = staking_num_lock_blocks(nettype);\n  uint64_t result         = curr_height + (blocks_to_lock / 2);\n  return result;\n}\n\nstatic uint64_t get_min_node_contribution_pre_v11(uint64_t staking_requirement, uint64_t total_reserved)\n{\n  return std::min(staking_requirement - total_reserved, staking_requirement / MAX_NUMBER_OF_CONTRIBUTORS);\n}\n\nuint64_t get_max_node_contribution(uint8_t version, uint64_t staking_requirement, uint64_t total_reserved)\n{\n  if (version >= cryptonote::network_version_16_pulse)\n    return (staking_requirement - total_reserved) * config::MAXIMUM_ACCEPTABLE_STAKE::num\n      / config::MAXIMUM_ACCEPTABLE_STAKE::den;\n  return std::numeric_limits<uint64_t>::max();\n}\n\nuint64_t get_min_node_contribution(uint8_t version, uint64_t staking_requirement, uint64_t total_reserved, size_t num_contributions)\n{\n  if (version < cryptonote::network_version_11_infinite_staking)\n    return get_min_node_contribution_pre_v11(staking_requirement, total_reserved);\n\n  const uint64_t needed = staking_requirement - total_reserved;\n  assert(MAX_NUMBER_OF_CONTRIBUTORS > num_contributions);\n  if (MAX_NUMBER_OF_CONTRIBUTORS <= num_contributions) return UINT64_MAX;\n\n  const size_t num_contributions_remaining_avail = MAX_NUMBER_OF_CONTRIBUTORS - num_contributions;\n  return needed / num_contributions_remaining_avail;\n}\n\nuint64_t get_min_node_contribution_in_portions(uint8_t version, uint64_t staking_requirement, uint64_t total_reserved, size_t num_contributions)\n{\n  uint64_t atomic_amount = get_min_node_contribution(version, staking_requirement, total_reserved, num_contributions);\n  uint64_t result        = (atomic_amount == UINT64_MAX) ? UINT64_MAX : (get_portions_to_make_amount(staking_requirement, atomic_amount));\n  return result;\n}\n\nuint64_t get_portions_to_make_amount(uint64_t staking_requirement, uint64_t amount, uint64_t max_portions)\n{\n  uint64_t lo, hi, resulthi, resultlo;\n  lo = mul128(amount, max_portions, &hi);\n  if (lo > UINT64_MAX - (staking_requirement - 1))\n    hi++;\n  lo += staking_requirement-1;\n  div128_64(hi, lo, staking_requirement, &resulthi, &resultlo);\n  return resultlo;\n}\n\nstatic bool get_portions_from_percent(double cur_percent, uint64_t& portions) {\n  if(cur_percent < 0.0 || cur_percent > 100.0) return false;\n\n  // Fix for truncation issue when operator cut = 100 for a pool Service Node.\n  if (cur_percent == 100.0)\n  {\n    portions = STAKING_PORTIONS;\n  }\n  else\n  {\n    portions = (cur_percent / 100.0) * (double)STAKING_PORTIONS;\n  }\n\n  return true;\n}\n\nbool get_portions_from_percent_str(std::string cut_str, uint64_t& portions) {\n\n  if(!cut_str.empty() && cut_str.back() == '%')\n  {\n    cut_str.pop_back();\n  }\n\n  double cut_percent;\n  try\n  {\n    cut_percent = boost::lexical_cast<double>(cut_str);\n  }\n  catch(...)\n  {\n    return false;\n  }\n\n  return get_portions_from_percent(cut_percent, portions);\n}\n\n} // namespace gnodes\n", "meta": {"hexsha": "0fab46cc035b267c59aa65f4afa931a57e38cf06", "size": 7019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cryptonote_core/gnode_rules.cpp", "max_stars_repo_name": "yuanxcoin/gyuanx-core", "max_stars_repo_head_hexsha": "4b5e0afb14d4590d5d3857001ab86ef2be2a07e2", "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/cryptonote_core/gnode_rules.cpp", "max_issues_repo_name": "yuanxcoin/gyuanx-core", "max_issues_repo_head_hexsha": "4b5e0afb14d4590d5d3857001ab86ef2be2a07e2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cryptonote_core/gnode_rules.cpp", "max_forks_repo_name": "yuanxcoin/gyuanx-core", "max_forks_repo_head_hexsha": "4b5e0afb14d4590d5d3857001ab86ef2be2a07e2", "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.7990654206, "max_line_length": 144, "alphanum_fraction": 0.7218977062, "num_tokens": 1988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899666, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5157414421585241}}
{"text": "//***************************************************************************\n//* Copyright (c) 2015 Saint Petersburg State University\n//* Copyright (c) 2011-2014 Saint Petersburg Academic University\n//* All Rights Reserved\n//* See file LICENSE for details.\n//***************************************************************************\n\n#include \"kmer_coverage_model.hpp\"\n\n#include \"utils/logger/logger.hpp\"\n#include \"utils/verify.hpp\"\n#include \"math/xmath.h\"\n#include \"math/smooth.hpp\"\n\n#include <boost/math/special_functions/zeta.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/skew_normal.hpp>\n#include <boost/math/distributions/geometric.hpp>\n#include <boost/math/distributions/pareto.hpp>\n\n#include <nlopt/nlopt.hpp>\n\n#include <vector>\n\n#include <cstring>\n#include <cstdint>\n#include <cstddef>\n#include <cmath>\n\nnamespace coverage_model {\n\nusing std::isfinite;\n\nstatic const size_t MaxCopy = 10;\n\nstatic double dzeta(double x, double p) {\n    return pow(x, -p - 1) / boost::math::zeta(p + 1);\n}\n\nstatic double perr(size_t i, double scale, double shape) {\n    return pow((1 + shape * ((double) (i - 1)) / scale), -1.0 / shape) -\n           pow((1 + shape * ((double) i) / scale), -1.0 / shape);\n}\n\nstatic double pgood(size_t i, double zp, double u, double sd, double shape,\n                    double* mixprobs = NULL) {\n    double res = 0;\n\n    for (unsigned copy = 0; copy < MaxCopy; ++copy) {\n        boost::math::skew_normal snormal((copy + 1) * u, sd * sqrt(copy + 1), shape);\n        // res += (mixprobs ? mixprobs[copy] : dzeta(copy + 1, zp)) * (boost::math::cdf(snormal, i + 1) - boost::math::cdf(snormal, i));\n        res += (mixprobs ? mixprobs[copy] : dzeta(copy + 1, zp)) * boost::math::pdf(snormal, i);\n    }\n\n    return res;\n}\n\nclass CovModelLogLike {\n    const std::vector<size_t>& cov;\n\npublic:\n    CovModelLogLike(const std::vector<size_t>& cov)\n            : cov(cov) {}\n\n    int getN() const { return 7; };\n\nprivate:\n\n    double eval_(const double* x) const {\n        double zp = x[0], p = x[1], shape = x[2], u = x[3], sd = x[4], scale = x[5], shape2 = x[6];\n\n        if (zp <= 1 || shape <= 0 || sd <= 0 || p < 1e-9 || p > 1 - 1e-9 || u <= 0 || scale <= 0 ||\n            !isfinite(zp) || !isfinite(shape) || !isfinite(sd) || !isfinite(p) || !isfinite(u) ||\n            !isfinite(scale) || !isfinite(shape2))\n            return +std::numeric_limits<double>::infinity();\n\n        std::vector<double> kmer_probs(cov.size());\n\n        // Error\n        for (size_t i = 0; i < kmer_probs.size(); ++i)\n            kmer_probs[i] += p * perr(i + 1, scale, shape);\n\n        // Good\n        for (size_t i = 0; i < kmer_probs.size(); ++i)\n            kmer_probs[i] += (1 - p) * pgood(i + 1, zp, u, sd, shape2);\n\n        double res = 0;\n        for (size_t i = 0; i < kmer_probs.size(); ++i)\n            res += (double) (cov[i]) * log(kmer_probs[i]);\n\n        return -res;\n    }\n};\n\nstruct CovModelLogLikeEMData {\n    const std::vector<size_t>& cov;\n    const std::vector<double>& z;\n};\n\nstatic double CovModelLogLikeEM(unsigned, const double* x, double*, void* data) {\n    double zp = x[0], shape = x[1], u = x[2], sd = x[3], scale = x[4], shape2 = x[5];\n\n    // INFO(\"Entry: \" << x[0] << \" \" << x[1] << \" \" << x[2] << \" \" << x[3] << \" \" << x[4]);\n\n    if (zp <= 1 || shape <= 0 || sd <= 0 || u <= 0 || scale <= 0 ||\n        !isfinite(zp) || !isfinite(shape) || !isfinite(sd) || !isfinite(u) ||\n        !isfinite(scale) || !isfinite(shape2))\n        return -std::numeric_limits<double>::infinity();\n\n    const std::vector<size_t>& cov = static_cast<CovModelLogLikeEMData*>(data)->cov;\n    const std::vector<double>& z = static_cast<CovModelLogLikeEMData*>(data)->z;\n\n    std::vector<double> kmer_probs(cov.size(), 0);\n\n    // Error\n    for (size_t i = 0; i < kmer_probs.size(); ++i) {\n        if (cov[i] == 0)\n            continue;\n\n        kmer_probs[i] += z[i] * log(perr(i + 1, scale, shape));\n    }\n\n    // Good\n    // Pre-compute mixing probabilities\n    std::vector<double> mixprobs(MaxCopy, 0);\n    for (unsigned copy = 0; copy < MaxCopy; ++copy)\n        mixprobs[copy] = dzeta(copy + 1, zp);\n\n    // Compute the density\n    for (size_t i = 0; i < kmer_probs.size(); ++i) {\n        if (cov[i] == 0)\n            continue;\n\n        double val = log(pgood(i + 1, zp, u, sd, shape2, &mixprobs[0]));\n        if (!isfinite(val))\n            val = -1000.0;\n        kmer_probs[i] += (1 - z[i]) * val;\n    }\n\n    double res = 0;\n    for (size_t i = 0; i < kmer_probs.size(); ++i)\n        res += (double) (cov[i]) * kmer_probs[i];\n\n    // INFO(\"f: \" << res);\n    return res;\n}\n\n\nstatic std::vector<double> EStep(const std::vector<double>& x,\n                                 double p, size_t N) {\n    double zp = x[0], shape = x[1], u = x[2], sd = x[3], scale = x[4], shape2 = x[5];\n\n    std::vector<double> res(N);\n    for (size_t i = 0; i < N; ++i) {\n        double pe = p * perr(i + 1, scale, shape);\n        res[i] = pe / (pe + (1 - p) * pgood(i + 1, zp, u, sd, shape2));\n        if (!isfinite(res[i]))\n            res[i] = 1.0;\n    }\n\n    return res;\n}\n\n// Estimate the coverage mean by finding the max past the\n// first valley.\nsize_t KMerCoverageModel::EstimateValley() const {\n    // Smooth the histogram\n    std::vector<size_t> scov;\n    math::Smooth3RS3R(scov, cov_);\n\n    size_t Valley = scov[0];\n\n    // Start finding the valley\n    size_t Idx = 1;\n    while (scov[Idx] < Valley && Idx < scov.size()) {\n        Valley = scov[Idx];\n        Idx += 1;\n    }\n    Idx -= 1;\n\n    INFO(\"Kmer coverage valley at: \" << Idx);\n\n    return Idx;\n}\n\nvoid KMerCoverageModel::Fit() {\n    CHECK_FATAL_ERROR(cov_.size() > 10, \"Invalid kmer coverage histogram, make sure that the coverage is indeed uniform\");\n\n    // Find the minimal coverage point using smoothed histogram.\n    Valley_ = EstimateValley();\n\n    // First estimate of coverage is the first maximum after the valley.\n    MaxCov_ = Valley_ + 1;\n    size_t MaxHist = cov_[MaxCov_];\n    for (size_t i = Valley_ + 1; i < cov_.size(); ++i) {\n        if (cov_[i] > MaxHist) {\n            MaxHist = cov_[i];\n            MaxCov_ = i;\n        }\n    }\n    INFO(\"K-mer histogram maximum: \" << MaxCov_);\n\n    // Refine the estimate via median\n    size_t AfterValley = 0, SecondValley = std::min(2 * MaxCov_ - Valley_, cov_.size());\n    for (size_t i = Valley_ + 1; i < SecondValley; ++i)\n        AfterValley += cov_[i];\n\n    size_t ccov = 0;\n    for (size_t i = Valley_ + 1; i < SecondValley; ++i) {\n        if (ccov > AfterValley / 2) {\n            MaxCov_ = std::max(i, MaxCov_);\n            break;\n        }\n        ccov += cov_[i];\n    }\n\n    if (MaxCov_ - Valley_ < 3)\n        WARN(\"Too many erroneous kmers, the estimates might be unreliable\");\n\n    std::vector<size_t> mvals(1 + MaxCov_ - Valley_);\n    mvals[0] = cov_[MaxCov_];\n    size_t tmadcov = mvals[0];\n    for (size_t i = 1; i < std::min(MaxCov_ - Valley_, cov_.size() - MaxCov_); ++i) {\n        mvals[i] = cov_[MaxCov_ + i] + cov_[MaxCov_ - i];\n        tmadcov += mvals[i];\n    }\n    size_t madcov = 0;\n    double CovSd = sqrt((double) (5 * MaxCov_));\n    for (size_t i = 0; i < MaxCov_ - Valley_; ++i) {\n        if (madcov > tmadcov / 2) {\n            CovSd = (double) i;\n            break;\n        }\n        madcov += mvals[i];\n    }\n    CovSd *= 1.4826;\n    INFO(\"Estimated median coverage: \" << MaxCov_ << \". Coverage mad: \" << CovSd);\n\n    // Estimate error probability as ratio of kmers before the valley.\n    size_t BeforeValley = 0, Total = 0;\n    double ErrorProb = 0;\n    for (size_t i = 0; i < cov_.size(); ++i) {\n        if (i <= Valley_)\n            BeforeValley += cov_[i];\n        Total += cov_[i];\n    }\n    ErrorProb = (double) BeforeValley / (double) Total;\n    // Allow some erroneous / good kmers.\n    ErrorProb = std::min(1 - 1e-3, ErrorProb);\n    ErrorProb = std::max(1e-3, ErrorProb);\n\n    TRACE(\"Total: \" << Total << \". Before: \" << BeforeValley);\n    TRACE(\"p: \" << ErrorProb);\n\n    std::vector<double> x = {3.0, 3.0, (double) MaxCov_, CovSd, 1.0, 0.0},\n        lb = {0.0, 0.0, 0.0, (double) (MaxCov_ - Valley_), 0.0, -6.0},\n        ub = {2000.0, 2000.0, (double) (2 * MaxCov_), (double) SecondValley, 2000.0, 6.0};\n\n    INFO(\"Fitting coverage model\");\n    // Ensure that there will be at least 2 iterations.\n    double PrevErrProb = 2;\n    const double ErrProbThr = 1e-8;\n    auto GoodCov = cov_;\n    GoodCov.resize(std::min(cov_.size(), 5 * MaxCopy * MaxCov_ / 4));\n    converged_ = true;\n    unsigned it = 1;\n    while (fabs(PrevErrProb - ErrorProb) > ErrProbThr) {\n        // Recalculate the vector of posterior error probabilities\n        std::vector<double> z = EStep(x, ErrorProb, GoodCov.size());\n\n        // Recalculate the probability of error\n        PrevErrProb = ErrorProb;\n        ErrorProb = 0;\n        for (size_t i = 0; i < GoodCov.size(); ++i)\n            ErrorProb += z[i] * (double) GoodCov[i];\n        ErrorProb /= (double) Total;\n\n        bool LastIter = fabs(PrevErrProb - ErrorProb) <= ErrProbThr;\n\n        nlopt::opt opt(nlopt::LN_NELDERMEAD, 6);\n        CovModelLogLikeEMData data = {GoodCov, z};\n        opt.set_max_objective(CovModelLogLikeEM, &data);\n        if (!LastIter)\n            opt.set_maxeval(5 * 6 * it);\n        opt.set_xtol_rel(1e-8);\n        opt.set_ftol_rel(1e-8);\n\n        double fMin;\n        nlopt::result Results = nlopt::FAILURE;\n        try {\n            Results = opt.optimize(x, fMin);\n        } catch (nlopt::roundoff_limited&) {\n        }\n\n        VERBOSE_POWER_T2(it, 1, \"... iteration \" << it);\n        TRACE(\"Results: \");\n        TRACE(\"Converged: \" << Results << \" \" << \"F: \" << fMin);\n\n        double zp = x[0], shape = x[1], u = x[2], sd = x[3], scale = x[4], shape2 = x[5];\n        TRACE(\"zp: \" << zp << \" p: \" << ErrorProb << \" shape: \" << shape << \" u: \" << u << \" sd: \" << sd <<\n                     \" scale: \" << scale << \" shape2: \" << shape2);\n\n        it += 1;\n    }\n\n    double delta = x[5] / sqrt(1 + x[5] * x[5]);\n    mean_coverage_ = x[2] + x[3] * delta * sqrt(2 / M_PI);\n    sd_coverage_ = x[3] * sqrt(1 - 2 * delta * delta / M_PI);\n    INFO(\"Fitted mean coverage: \" << mean_coverage_ << \". Fitted coverage std. dev: \" << sd_coverage_);\n\n    // Now let us check whether we have sane results\n    for (size_t i = 0; i < x.size(); ++i)\n        if (!isfinite(x[i])) {\n            converged_ = false;\n            break;\n        }\n\n    if (!isfinite(ErrorProb))\n        converged_ = false;\n\n    // See, if we can deduce proper threshold\n\n    // First, check whether initial estimate of Valley was sane.\n    ErrorThreshold_ = 0;\n    if (converged_ && Valley_ > x[2] && x[2] > 2) {\n        Valley_ = (size_t) math::round(x[2] / 2.0);\n        WARN(\"Valley value was estimated improperly, reset to \" << Valley_);\n    }\n\n    // If the model converged, then use it to estimate the thresholds.\n    if (converged_) {\n        std::vector<double> z = EStep(x, ErrorProb, GoodCov.size());\n\n        INFO(\"Probability of erroneous kmer at valley: \" << z[Valley_]);\n        converged_ = false;\n        for (size_t i = 0; i < z.size(); ++i)\n            if (z[i] > strong_probability_threshold_) //0.999\n                LowThreshold_ = std::min(i + 1, Valley_);\n            else if (z[i] < probability_threshold_) {//0.05?\n                ErrorThreshold_ = std::max(i + 1, Valley_);\n                converged_ = true;\n                break;\n            }\n\n#if 0\n        for (size_t i = 0; i < z.size(); ++i) {\n            double zp = x[0], shape = x[1], u = x[2], sd = x[3], scale = x[4], shape2 = x[5];\n            double pe = ErrorProb * perr(i + 1, scale, shape);\n            double pg = (1 - ErrorProb) * pgood(i + 1, zp, u, sd, shape2);\n\n            fprintf(stderr, \"%e %e %e %e\\n\", pe, pg, z[i], perr(i + 1, scale, shape));\n        }\n#endif\n    }\n\n    // See, if we have sane ErrorThreshold_ and go down to something convervative, if not.\n    if (converged_) {\n        INFO(\"Preliminary threshold calculated as: \" << ErrorThreshold_);\n        ErrorThreshold_ = (Valley_ < mean_coverage_ ?\n                           std::min(Valley_ + (size_t) (mean_coverage_ - (double) Valley_) / 2, ErrorThreshold_) :\n                           Valley_);\n        INFO(\"Threshold adjusted to: \" << ErrorThreshold_);\n    } else {\n        ErrorThreshold_ = Valley_;\n        LowThreshold_ = 1;\n        WARN(\"Failed to determine erroneous kmer threshold. Threshold set to: \" << ErrorThreshold_);\n    }\n\n    // Now the bonus: estimate the genome size!\n    GenomeSize_ = 0;\n    for (size_t i = ErrorThreshold_ - 1; i < GoodCov.size(); ++i)\n        GenomeSize_ += GoodCov[i];\n    GenomeSize_ /= 2;\n\n    INFO(\"Estimated genome size (ignoring repeats): \" << GenomeSize_);\n}\n\n}\n", "meta": {"hexsha": "22cbb50272f663f921d0469562dc3ceaf80bea07", "size": 12695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/metaspades/src/common/modules/coverage_model/kmer_coverage_model.cpp", "max_stars_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_stars_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/metaspades/src/common/modules/coverage_model/kmer_coverage_model.cpp", "max_issues_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_issues_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/metaspades/src/common/modules/coverage_model/kmer_coverage_model.cpp", "max_forks_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_forks_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-05T07:40:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T08:02:58.000Z", "avg_line_length": 33.4960422164, "max_line_length": 136, "alphanum_fraction": 0.5458054352, "num_tokens": 3902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5157414364309532}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/15/problem15.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem15 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem15::solve(2, 2);\n        BOOST_CHECK_EQUAL(res, 6);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem15::solve();\n        BOOST_CHECK_EQUAL(res, 137846528820);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "2efeb69e5fe58c36ff82f37104a58a8d2d55ac3a", "size": 501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem15.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": "tests/1-50/test_problem15.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": "tests/1-50/test_problem15.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.8571428571, "max_line_length": 52, "alphanum_fraction": 0.6766467066, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5157410242237336}}
{"text": "#ifndef TVMTL_MATRIX_UTILS_HPP\n#define TVMTL_MATRIX_UTILS_HPP\n\n#include <cmath>\n#include <complex>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <unsupported/Eigen/KroneckerProduct>\n\n\nnamespace tvmtl {\n\ntemplate <typename MatrixType>\n    void SolveTriangularSylvester(const MatrixType& A, const MatrixType& B, const MatrixType& C, MatrixType& result)\n    {\n/*\tEigen::eigen_assert(A.rows() == A.cols());\n\tEigen::eigen_assert(A.isUpperTriangular());\n\tEigen::eigen_assert(B.rows() == B.cols());\n\tEigen::eigen_assert(B.isUpperTriangular());\n\tEigen::eigen_assert(C.rows() == A.rows());\n\tEigen::eigen_assert(C.cols() == B.rows());\n  */  \n      typedef typename MatrixType::Index Index;\n      typedef typename MatrixType::Scalar Scalar;\n    \n      Index m = A.rows();\n      Index n = B.rows();\n      MatrixType X(m, n);\n    \n      for (Index i = m - 1; i >= 0; --i) {\n          for (Index j = 0; j < n; ++j) {\n\t        // Compute AX = \\sum_{k=i+1}^m A_{ik} X_{kj}\n\t\tScalar AX;\n\t\tif (i == m - 1) {\n\t\t    AX = 0; \n\t\t} \n\t\telse {\n\t\t    Eigen::Matrix<Scalar,1,1> AXmatrix = A.row(i).tail(m-1-i) * X.col(j).tail(m-1-i);\n\t\t    AX = AXmatrix(0,0);\n\t\t}\n\n\t\t// Compute XB = \\sum_{k=1}^{j-1} X_{ik} B_{kj}\n\t\tScalar XB;\n\t\tif (j == 0) {\n\t\t    XB = 0; \n\t\t} \n\t\telse {\n\t\t    Eigen::Matrix<Scalar,1,1> XBmatrix = X.row(i).head(j) * B.col(j).head(j);\n\t\t    XB = XBmatrix(0,0);\n\t\t}\n\n\t\tX(i,j) = (C(i,j) - AX - XB) / (A(i,i) + B(j,j));\n\t}   \n    }\nresult = X;\n}\n\ntemplate <typename DerivedX, typename DerivedY, typename DerivedZ>\nvoid MatrixRootFrechetDerivative(const Eigen::MatrixBase<DerivedX>& X, const Eigen::MatrixBase<DerivedY>& E, Eigen::MatrixBase<DerivedZ>& result){\n\n    // Matrix Parameters\n    typedef Eigen::internal::traits<DerivedX> Traits;\n    typedef typename Traits::Scalar Scalar;\n    static const int Rows = Traits::RowsAtCompileTime, Cols = Traits::ColsAtCompileTime;\n    static const int Options = DerivedX::Options;\n    static const int MaxRows = Traits::MaxRowsAtCompileTime, MaxCols = Traits::MaxColsAtCompileTime;\n \n    // Switch to complex arithmetic\n    typedef std::complex<Scalar> ComplexScalar;\n    typedef Eigen::Matrix<ComplexScalar, Rows, Cols, Options, MaxRows, MaxCols> ComplexMatrix;\n\n    ComplexMatrix CX = X.template cast<ComplexScalar>();\n    ComplexMatrix CE = E.template cast<ComplexScalar>();\n    ComplexMatrix CResult;\n\n    // Complex Schur Decomposition\n    const Eigen::ComplexSchur<ComplexMatrix> SchurOfX(CX);\n    ComplexMatrix T = SchurOfX.matrixT();\n    ComplexMatrix U = SchurOfX.matrixU();    \n\n    ComplexMatrix sqrtT;\n    CE = U.adjoint()*CE*U;\n\n    Eigen::MatrixSquareRootTriangular<ComplexMatrix>(T).compute(sqrtT);\n    SolveTriangularSylvester(sqrtT, sqrtT, CE, CResult);\n\n    CResult = U * CResult * U.adjoint();\n\n    result = CResult.real();\n}\n\ntemplate <typename DerivedX, typename DerivedY, typename DerivedZ>\nvoid MatrixLogarithmFrechetDerivative(const Eigen::MatrixBase<DerivedX>& X, const Eigen::MatrixBase<DerivedY>& E, Eigen::MatrixBase<DerivedZ>& result){\n\n    // Matrix Parameters\n    typedef Eigen::internal::traits<DerivedX> Traits;\n    typedef typename Traits::Scalar Scalar;\n    static const int Rows = Traits::RowsAtCompileTime, Cols = Traits::ColsAtCompileTime;\n    static const int Options = DerivedX::Options;\n    static const int MaxRows = Traits::MaxRowsAtCompileTime, MaxCols = Traits::MaxColsAtCompileTime;\n \n    // Switch to complex arithmetic\n    typedef std::complex<Scalar> ComplexScalar;\n    typedef Eigen::Matrix<ComplexScalar, Rows, Cols, Options, MaxRows, MaxCols> ComplexMatrix;\n\n    ComplexMatrix CX = X.template cast<ComplexScalar>();\n    ComplexMatrix CE = E.template cast<ComplexScalar>();\n    ComplexMatrix CResult;\n\n\n\n    // Order of the Pade approximant\n    // If this is changed, we also need new weights and nodes\n    const int m = 7;\n\n    // Complex Schur Decomposition\n    const Eigen::ComplexSchur<ComplexMatrix> SchurOfX(CX);\n    ComplexMatrix T = SchurOfX.matrixT();\n    ComplexMatrix U = SchurOfX.matrixU();    \n    \n    //Compute the number of square roots\n    int s = 0;\n    const int smax = 20;\n    const double theta7 = 2.88e-1;\n    double rho = theta7 + 1.0;\n\n    Eigen::Matrix<ComplexScalar, Rows, 1> D;\n    D = T.diagonal();\n\n    #ifdef TVMTL_MATRIX_UTILS_DEBUG_VERBOSE\n\tstd::cout << \"Diagonal of Schur Decomposition: \\n\" << D << std::endl;\n    #endif\n \n    while(rho > theta7 && s < smax){\n\tD=D.cwiseSqrt();\n\t#ifdef TVMTL_MATRIX_UTILS_DEBUG_VERBOSE\n\t    std::cout << \"D: \" << D << std::endl;\n\t#endif\n\t++s;\n\trho = (D - Eigen::Matrix<ComplexScalar, Rows, 1>::Constant(1)).cwiseAbs().maxCoeff();\n\t #ifdef TVMTL_MATRIX_UTILS_DEBUG_VERBOSE\n\t    std::cout << \"rho: \" << rho << std::endl;\n\t #endif\n    }\n \n    #ifdef TVMTL_MATRIX_UTILS_DEBUG\n\tstd::cout << \"Number of square roots  for dlog estimation: \" << s << std::endl;\n    #endif\n\n\n    ComplexMatrix sqrtT;\n    CE = U.adjoint()*CE*U;\n\n    for(int k=0; k<s; k++){\n\tEigen::MatrixSquareRootTriangular<ComplexMatrix>(T).compute(sqrtT);\n\tT=sqrtT;\n\tSolveTriangularSylvester(T, T, CE, CE);\n    }\n\n    const double nodes[]   = { 0.0254460438286207377369051579760744L, 0.1292344072003027800680676133596058L,\n            0.2970774243113014165466967939615193L, 0.5000000000000000000000000000000000L,\n            0.7029225756886985834533032060384807L, 0.8707655927996972199319323866403942L,\n            0.9745539561713792622630948420239256L };\n    const double weights[] = { 0.0647424830844348466353057163395410L, 0.1398526957446383339507338857118898L,\n              0.1909150252525594724751848877444876L, 0.2089795918367346938775510204081633L,\n              0.1909150252525594724751848877444876L, 0.1398526957446383339507338857118898L,\n              0.0647424830844348466353057163395410L };\n\n    ComplexMatrix TminusI = T - ComplexMatrix::Identity(T.rows(), T.rows());\n    CResult.setZero();\n    \n    for (int i = 0; i < m; ++i){\n  \tComplexMatrix IplusBetaTm = ComplexMatrix::Identity(T.rows(), T.rows()) + nodes[i] * TminusI;\n  \tComplexMatrix X = IplusBetaTm.template triangularView< Eigen::Upper >().solve(CE).transpose();\t\n  \tCResult += weights[i] * (IplusBetaTm.template triangularView< Eigen::Upper >().transpose().solve(X)).transpose();\t\n    }\n\n    CResult = std::pow(2.0,s) * U * CResult * U.adjoint();\n\n    result = CResult.real();\n}\n\n\ntemplate <typename DerivedX, typename DerivedY>\nvoid KroneckerDLog(const Eigen::MatrixBase<DerivedX>& X, Eigen::MatrixBase<DerivedY>& Result){\n    \n    typedef Eigen::internal::traits<DerivedX> Traits;\n    typedef typename Traits::Scalar Scalar;\n    static const int Rows = Traits::RowsAtCompileTime;\n\n    DerivedX E, PartialDiff; \n    DerivedY R;\n\n    for (int i = 0; i < Rows; i++) {\n    \tfor (int j = 0; j < Rows; j++) {\n\t    E = DerivedX::Zero();\n\t    E(i,j) = 1.0;\n\t    MatrixLogarithmFrechetDerivative(X, E, PartialDiff);\n\t    PartialDiff.transposeInPlace();\n\t    R.row(i*Rows+j) = Eigen::Map<Eigen::VectorXd>(PartialDiff.data(), PartialDiff.size());\n    \t}\n    }\n    Result = R;\n}\n\ntemplate <typename DerivedX, typename DerivedY>\nvoid KroneckerDSqrt2(const Eigen::MatrixBase<DerivedX>& X, Eigen::MatrixBase<DerivedY>& Result){\n    \n    typedef Eigen::internal::traits<DerivedX> Traits;\n    typedef typename Traits::Scalar Scalar;\n    static const int Rows = Traits::RowsAtCompileTime;\n\n    DerivedX E, PartialDiff; \n    DerivedY R;\n\n    for (int i = 0; i < Rows; i++) {\n    \tfor (int j = 0; j < Rows; j++) {\n\t    E = DerivedX::Zero();\n\t    E(i,j) = 1.0;\n\t    MatrixRootFrechetDerivative(X, E, PartialDiff);\n\t    PartialDiff.transposeInPlace();\n\t    R.row(i*Rows+j) = Eigen::Map<Eigen::VectorXd>(PartialDiff.data(), PartialDiff.size());\n    \t}\n    }\n    Result = R;\n}\n\ntemplate <typename DerivedX, typename DerivedY>\nvoid KroneckerDSqrt(const Eigen::MatrixBase<DerivedX>& X, Eigen::MatrixBase<DerivedY>& Result){\n    \n    DerivedX Xsqrt = X.sqrt();\n    DerivedY R = Eigen::kroneckerProduct(DerivedX::Identity(),Xsqrt) + Eigen::kroneckerProduct(Xsqrt.transpose(), DerivedX::Identity());\n    Result = R.inverse();\n}\n\n} // end namespace tvmtl\n\n\n  \n#endif\n", "meta": {"hexsha": "8274de0bb43892def6d1ad39caf61a66d39daf35", "size": 8074, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mtvmtl/core/matrix_utils.hpp", "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": "mtvmtl/core/matrix_utils.hpp", "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": "mtvmtl/core/matrix_utils.hpp", "max_forks_repo_name": "pdebus/MTVMTL", "max_forks_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2263374486, "max_line_length": 151, "alphanum_fraction": 0.6726529601, "num_tokens": 2371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5157347723615864}}
{"text": "/**\r\n * Copyright 2021-2022 Huawei Technologies Co., Ltd\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#include \"plugin/device/cpu/kernel/lstsq_cpu_kernel.h\"\r\n#include <Eigen/Dense>\r\n#include \"plugin/device/cpu/hal/device/cpu_device_address.h\"\r\n#include \"kernel/common_utils.h\"\r\n\r\nnamespace mindspore {\r\nnamespace kernel {\r\nnamespace {\r\nconstexpr size_t kLstsqInputsNum = 2;\r\nconstexpr size_t kLstsqOutputsNum = 1;\r\nconstexpr size_t kXDimNum = 2;\r\nconstexpr size_t kADimNum_1 = 1;\r\nconstexpr size_t kADimNum_2 = 2;\r\n}  // namespace\r\n\r\nvoid LstsqCpuKernelMod::InitKernel(const CNodePtr &kernel_node) {\r\n  MS_EXCEPTION_IF_NULL(kernel_node);\r\n  input_0_shape_ = AnfAlgo::GetInputDeviceShape(kernel_node, 0);\r\n  input_1_shape_ = AnfAlgo::GetInputDeviceShape(kernel_node, 1);\r\n  if (input_0_shape_.size() != kXDimNum) {\r\n    MS_LOG(EXCEPTION) << \"The input x tensor's rank must be 2 for 'Lstsq' Op, but x tensor's rank is \"\r\n                      << input_0_shape_.size();\r\n  }\r\n  if (input_1_shape_.size() != kADimNum_2 && input_1_shape_.size() != kADimNum_1) {\r\n    MS_LOG(EXCEPTION) << \"The input a tensor's rank must be 2 or 1 for 'Lstsq' Op, but a tensor's rank is \"\r\n                      << input_1_shape_.size();\r\n  }\r\n  if (input_0_shape_[0] != input_1_shape_[0]) {\r\n    MS_LOG(EXCEPTION) << \"The length of x_dim[0]: \" << input_0_shape_[0]\r\n                      << \" is not equal to the length of a_dims[0]: \" << input_1_shape_[0] << \".\";\r\n  }\r\n  dtype_0_ = AnfAlgo::GetInputDeviceDataType(kernel_node, 0);\r\n  dtype_1_ = AnfAlgo::GetInputDeviceDataType(kernel_node, 1);\r\n  if (dtype_0_ != dtype_1_) {\r\n    MS_LOG(EXCEPTION) << \"For Lstsq input's dtypes are not the same.\";\r\n  }\r\n}\r\n\r\nbool LstsqCpuKernelMod::Launch(const std::vector<kernel::AddressPtr> &inputs, const std::vector<kernel::AddressPtr> &,\r\n                               const std::vector<kernel::AddressPtr> &outputs) {\r\n  CHECK_KERNEL_INPUTS_NUM(inputs.size(), kLstsqInputsNum, kernel_name_);\r\n  CHECK_KERNEL_OUTPUTS_NUM(outputs.size(), kLstsqOutputsNum, kernel_name_);\r\n  if (dtype_0_ == kNumberTypeFloat16) {\r\n    LaunchKernel<float, float16>(inputs, outputs);\r\n  } else if (dtype_0_ == kNumberTypeFloat32) {\r\n    LaunchKernel<float, float>(inputs, outputs);\r\n  } else if (dtype_0_ == kNumberTypeFloat64) {\r\n    LaunchKernel<double, double>(inputs, outputs);\r\n  } else {\r\n    MS_LOG(EXCEPTION) << \"Unsupported input data type.\";\r\n  }\r\n  return true;\r\n}\r\n\r\ntemplate <typename T1, typename T2>\r\nvoid LstsqCpuKernelMod::LaunchKernel(const std::vector<AddressPtr> &inputs, const std::vector<AddressPtr> &outputs) {\r\n  auto input_0_addr = reinterpret_cast<T2 *>(inputs[0]->addr);\r\n  auto input_1_addr = reinterpret_cast<T2 *>(inputs[1]->addr);\r\n  auto output_addr = reinterpret_cast<T2 *>(outputs[0]->addr);\r\n  size_t m = input_0_shape_[0];\r\n  size_t n = input_0_shape_[1];\r\n  size_t k = 0;\r\n  if (input_1_shape_.size() == kADimNum_1) {\r\n    k = 1;\r\n  } else {\r\n    k = input_1_shape_[1];\r\n  }\r\n\r\n  typedef Eigen::Matrix<T1, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MartixXd;\r\n  MartixXd A(m, n);\r\n  MartixXd B(m, k);\r\n  for (size_t i = 0; i < m * n; i++) {\r\n    A.data()[i] = static_cast<T1>(input_0_addr[i]);\r\n  }\r\n  for (size_t i = 0; i < m * k; i++) {\r\n    B.data()[i] = static_cast<T1>(input_1_addr[i]);\r\n  }\r\n  MartixXd result;\r\n  if (m >= n) {\r\n    result = A.colPivHouseholderQr().solve(B);\r\n  } else {\r\n    MartixXd A_Transpose = A.transpose();\r\n    MartixXd temp = A * A_Transpose;\r\n    MartixXd tempI = temp.inverse();\r\n    MartixXd x = A_Transpose * tempI;\r\n    MartixXd output = x * B;\r\n    result = output;\r\n  }\r\n  for (size_t i = 0; i < n; i++)\r\n    for (size_t j = 0; j < k; j++) {\r\n      *(output_addr + i * k + j) = static_cast<T2>(result(i, j));\r\n    }\r\n}\r\n\r\nMS_KERNEL_FACTORY_REG(NativeCpuKernelMod, Lstsq, LstsqCpuKernelMod);\r\n}  // namespace kernel\r\n}  // namespace mindspore\r\n", "meta": {"hexsha": "5ad8cf306d510c651e6697137de9012fbfadbe84", "size": 4403, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mindspore/ccsrc/plugin/device/cpu/kernel/lstsq_cpu_kernel.cc", "max_stars_repo_name": "httpsgithu/mindspore", "max_stars_repo_head_hexsha": "c29d6bb764e233b427319cb89ba79e420f1e2c64", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-23T09:13:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T09:13:43.000Z", "max_issues_repo_path": "mindspore/ccsrc/plugin/device/cpu/kernel/lstsq_cpu_kernel.cc", "max_issues_repo_name": "949144093/mindspore", "max_issues_repo_head_hexsha": "c29d6bb764e233b427319cb89ba79e420f1e2c64", "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": "mindspore/ccsrc/plugin/device/cpu/kernel/lstsq_cpu_kernel.cc", "max_forks_repo_name": "949144093/mindspore", "max_forks_repo_head_hexsha": "c29d6bb764e233b427319cb89ba79e420f1e2c64", "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.6228070175, "max_line_length": 119, "alphanum_fraction": 0.6620486032, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5157051037130858}}
{"text": "\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <vector>\n#include <random>\n#include <iterator>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/SparseCholesky>\n\n#include \"SVDPackage.h\"\n#include \"Pest.h\"\n#include \"utilities.h\"\n#include \"covariance.h\"\n#include \"FileManager.h\"\n\nusing namespace std;\n\n//---------------------------------------\n//Mat constructors\n//---------------------------------------\n\nMat::Mat(string filename)\n{\n\tstring ext = filename.substr(filename.find_last_of(\".\") + 1);\n\tpest_utils::upper_ip(ext);\n\tif (ext == \"PST\")\n\t\tthrow runtime_error(\"Mat::Mat() error: cannot instantiate a Mat with PST\");\n\telse if ((ext == \"JCO\") || (ext == \"JCB\"))\n\t\tfrom_binary(filename);\n\telse if (ext == \"MAT\")\n\t\tfrom_ascii(filename);\n\telse\n\t\tthrow runtime_error(\"Mat::Mat() error: only .jco/.jcb or .mat\\\n\t\t\t\t\t\t\t files can be used to instatiate a Mat\");\n\n}\n\nMat::Mat(vector<string> _row_names, vector<string> _col_names,\n\tEigen::SparseMatrix<double> _matrix)\n{\n\trow_names = _row_names;\n\tcol_names = _col_names;\n\tassert(row_names.size() == _matrix.rows());\n\tassert(col_names.size() == _matrix.cols());\n\tmatrix = _matrix;\n\tmattype = MatType::SPARSE;\n}\n\nMat::Mat(vector<string> _row_names, vector<string> _col_names,\n\tEigen::SparseMatrix<double>* _matrix)\n{\n\trow_names = _row_names;\n\tcol_names = _col_names;\n\tassert(row_names.size() == _matrix->rows());\n\tassert(col_names.size() == _matrix->cols());\n\tmatrix = *_matrix;\n\tmattype = MatType::SPARSE;\n}\n\nMat::Mat(vector<string> _row_names, vector<string> _col_names,\n\tEigen::SparseMatrix<double> _matrix,MatType _mattype)\n{\n\trow_names = _row_names;\n\tcol_names = _col_names;\n\tassert(row_names.size() == _matrix.rows());\n\tassert(col_names.size() == _matrix.cols());\n\tmatrix = _matrix;\n\tmattype = _mattype;\n}\n\nvoid Mat::update_sets()\n{\n\trow_set.clear();\n\t//row_set.emplace(row_names.begin(), row_names.end());\n\trow_set = set<string>(row_names.begin(), row_names.end());\n\tcol_set.clear();\n\t//col_set.emplace(col_names.begin(), col_names.end());\n\tcol_set = set<string>(col_names.begin(), col_names.end());\n}\n\n\nconst Eigen::SparseMatrix<double>* Mat::e_ptr()\n{\n\tconst Eigen::SparseMatrix<double>* ptr = &matrix;\n\treturn ptr;\n}\n\nconst vector<string>* Mat::rn_ptr()\n{\n\tconst vector<string>* ptr = &row_names;\n\treturn ptr;\n}\n\nconst vector<string>* Mat::cn_ptr()\n{\n\tconst vector<string>* ptr = &col_names;\n\treturn ptr;\n}\n\nMat Mat::identity()\n{\n\tEigen::SparseMatrix<double> i(nrow(), ncol());\n\ti.setZero();\n\ti.setIdentity();\n\treturn Mat(*rn_ptr(),*cn_ptr(),i);\n}\n\nMat Mat::zero()\n{\n\tEigen::SparseMatrix<double> i(nrow(), ncol());\n\ti.setZero();\n\treturn Mat(*rn_ptr(), *cn_ptr(), i);\n}\n\n\nconst Eigen::SparseMatrix<double>* Mat::U_ptr()\n{\n\tif (U.rows() == 0)\n\t{\n\t\tSVD();\n\t}\n\tconst Eigen::SparseMatrix<double>* ptr = &U;\n\treturn ptr;\n}\n\nconst Eigen::SparseMatrix<double>* Mat::V_ptr()\n{\n\tif (V.rows() == 0)\n\t{\n\t\tSVD();\n\t}\n\tconst Eigen::SparseMatrix<double>* ptr = &V;\n\treturn ptr;\n}\n\nconst Eigen::VectorXd* Mat::s_ptr()\n{\n\tif (s.size() == 0)\n\t{\n\t\tSVD();\n\t}\n\tconst Eigen::VectorXd* ptr = &s;\n\treturn ptr;\n}\n\nMat Mat::get_U()\n{\n\tif (U.rows() == 0) SVD();\n\tvector<string> u_col_names;\n\tstringstream ss;\n\tfor (int i = 0; i < nrow(); i++)\n\t{\n\t\tss.clear();\n\t\tss.str(string());\n\t\tss << \"left_sing_vec_\";\n\t\tss << i + 1;\n\t\tu_col_names.push_back(ss.str());\n\t}\n\treturn Mat(row_names, u_col_names, U);\n}\n\nMat Mat::get_V()\n{\n\tif (V.rows() == 0) SVD();\n\tvector<string> v_col_names;\n\tstringstream ss;\n\tfor (int i = 0; i < ncol(); i++)\n\t{\n\t\tss.clear();\n\t\tss.str(string());\n\t\tss << \"right_sing_vec_\";\n\t\tss << i + 1;\n\t\tv_col_names.push_back(ss.str());\n\t}\n\treturn Mat(col_names, v_col_names, V);\n}\n\n\nMat Mat::get_s()\n{\n\tif (V.rows() == 0) SVD();\n\tvector<string> s_names;\n\tvector<Eigen::Triplet<double>> triplet_list;\n\tstringstream ss;\n\tfor (int i = 0; i < s.size(); i++)\n\t{\n\t\tss.clear();\n\t\tss.str(string());\n\t\tss << \"sing_val_\";\n\t\tss << i + 1;\n\t\ts_names.push_back(ss.str());\n\t\ttriplet_list.push_back(Eigen::Triplet<double>(i, i, s[i]));\n\t}\n\tEigen::SparseMatrix<double> s_mat(s.size(),s.size());\n\ts_mat.setZero();\n\ts_mat.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\treturn Mat(s_names, s_names, s_mat);\n}\n\nMat Mat::transpose()\n{\n\treturn Mat(col_names, row_names, matrix.transpose());\n}\n\nMat Mat::T()\n{\n\treturn Mat(col_names, row_names, matrix.transpose());\n}\n\nvoid Mat::transpose_ip()\n{\n\tif (mattype != MatType::DIAGONAL)\n\t{\n\t\tmatrix = matrix.transpose();\n\t\tvector<string> temp = row_names;\n\t\trow_names = col_names;\n\t\tcol_names = temp;\n\t}\n}\n\nMat Mat::inv(bool echo)\n{\n\tLogger* log = new Logger();\n\tlog->set_echo(echo);\n\t//inv_ip(log);\n\tMat new_mat = inv(log);\n\tdelete log;\n\treturn new_mat;\n}\n\n\nMat Mat::inv(Logger* log)\n{\n\tif (nrow() != ncol()) throw runtime_error(\"Mat::inv() error: only symmetric positive definite matrices can be inverted with Mat::inv()\");\n\tif (mattype == MatType::DIAGONAL)\n\t{\n\t\tlog->log(\"inverting diagonal matrix in place\");\n\t\tlog->log(\"extracting diagonal\");\n\t\tEigen::VectorXd diag = matrix.diagonal().eval();\n\t\tlog->log(\"inverting diagonal\");\n\t\tlog->log(\"building triplets\");\n\t\tvector<Eigen::Triplet<double>> triplet_list;\n\t\tfor (int i = 0; i != diag.size(); ++i)\n\t\t{\n\t\t\ttriplet_list.push_back(Eigen::Triplet<double>(i, i, 1.0 / diag[i]));\n\t\t}\n\t\tEigen::SparseMatrix<double> inv_mat;\n\t\tinv_mat.conservativeResize(triplet_list.size(), triplet_list.size());\n\t\tinv_mat.setZero();\n\t\tlog->log(\"setting matrix from triplets\");\n\t\tinv_mat.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\t\treturn Mat(row_names, col_names, inv_mat);\n\t}\n\t//Eigen::ConjugateGradient<Eigen::SparseMatrix<double>> solver;\n\tEigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;\n\tsolver.compute(matrix);\n\tEigen::SparseMatrix<double> I(nrow(), nrow());\n\tI.setIdentity();\n\tEigen::SparseMatrix<double> inv_mat = solver.solve(I);\n\treturn Mat(row_names, col_names, inv_mat);\n}\n\nvoid Mat::inv_ip(bool echo)\n{\n\tofstream flog(\"Mat.log\");\n\tPerformanceLog pfm(flog);\n\tinv_ip(pfm);\n\treturn;\n}\n\nvoid Mat::inv_ip(PerformanceLog& pfm)\n{\n\tif (nrow() != ncol()) throw runtime_error(\"Mat::inv() error: only symmetric positive definite matrices can be inverted with Mat::inv()\");\n\tif (mattype == MatType::DIAGONAL)\n\t{\n\t\tpfm.log_event(\"inverting diagonal matrix in place\");\n\t\tEigen::VectorXd diag = matrix.diagonal().eval();\n\t\tvector<Eigen::Triplet<double>> triplet_list;\n\t\tfor (int i = 0; i != diag.size(); ++i)\n\t\t{\n\t\t\ttriplet_list.push_back(Eigen::Triplet<double>(i, i, 1.0/diag[i]));\n\t\t}\n\t\t//log->log(\"resizeing matrix to size \" + triplet_list.size());\n\t\t//matrix.conservativeResize(triplet_list.size(),triplet_list.size());\n\t\tmatrix.setZero();\n\t\tmatrix.setFromTriplets(triplet_list.begin(),triplet_list.end());\n\t\t//Eigen::SparseMatrix<double> inv_mat(triplet_list.size(), triplet_list.size());\n\t\t//inv_mat.setZero();\n\t\t//inv_mat.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\t\t//matrix = inv_mat;\n\t\t//cout << \"diagonal inv_ip()\" << endl;\n\t\t/*matrix.resize(triplet_list.size(), triplet_list.size());\n\t\tmatrix.setZero();\n\t\tmatrix.setFromTriplets(triplet_list.begin(),triplet_list.end());*/\n\t\treturn;\n\t}\n\n\t//Eigen::ConjugateGradient<Eigen::SparseMatrix<double>> solver;\n\tpfm.log_event(\"inverting non-diagonal matrix in place\");\n\tEigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;\n\tsolver.compute(matrix);\n\tEigen::SparseMatrix<double> I(nrow(), nrow());\n\tI.setIdentity();\n\t//Eigen::SparseMatrix<double> inv_mat = solver.solve(I);\n\t//matrix = inv_mat;\n\tmatrix = solver.solve(I);\n\t//cout << \"full inv_ip()\" << endl;\n\t/*matrix.setZero();\n\tmatrix = solver.solve(I);*/\n\n}\n\n\nvoid Mat::SVD()\n{\n\tEigen::JacobiSVD<Eigen::MatrixXd> svd_fac(matrix, Eigen::DecompositionOptions::ComputeFullU |\n\t\tEigen::DecompositionOptions::ComputeFullV);\n\ts = svd_fac.singularValues();\n\tU = svd_fac.matrixU().sparseView();\n\tV = svd_fac.matrixV().sparseView();\n}\n\n\n\n//---------------------------------------\n//Mat operator\n//--------------------------------------\n\nostream& operator<< (ostream &os, Mat mat)\n{\n\tcout << \"row names : \";\n\tfor (auto &name : mat.get_row_names())\n\t\tcout << name << ',';\n\tcout << endl << \"col names : \";\n\tfor (auto &name : mat.get_col_names())\n\t\tcout << name << ',';\n\tcout << endl;\n\tcout << *mat.e_ptr();\n\treturn os;\n}\n\n\n\n\n//-----------------------------------------\n//Mat IO\n//-----------------------------------------\n\n\n\n\nvoid Mat::to_ascii(const string &filename)\n{\n\tofstream out(filename);\n\tif (!out.good())\n\t{\n\t\tthrow runtime_error(\"Mat::to_ascii() error: cannot open \" + filename + \"\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t to write ASCII matrix\");\n\t}\n\tout << setw(6) << nrow() << setw(6) << ncol() << setw(6) << icode << endl;\n\tout << matrix.toDense() << endl;\n\tif (icode == 1)\n\t{\n\t\tout<< \"* row and column names\" << endl;\n\t\tfor (auto &name : row_names)\n\t\t\tout << pest_utils::lower_cp(name) << endl;\n\n\t}\n\telse\n\t{\n\t\tout << \"* row names\" << endl;\n\t\tfor (auto &name : row_names)\n\t\t\tout << pest_utils::lower_cp(name) << endl;\n\t\tout << \"* column names\" << endl;\n\t\tfor (auto &name : col_names)\n\t\t\tout << pest_utils::lower_cp(name) << endl;\n\t}\n\tout.close();\n}\n\nvoid Mat::from_file(const string &filename)\n{\n\tstringstream ss;\n\tstring ext = filename.substr(filename.find_last_of(\".\") + 1);\n\tpest_utils::upper_ip(ext);\n\tif ((ext == \"JCB\") || (ext == \"JCO\"))\n\t{\n\t\tfrom_binary(filename);\n\t}\n\telse if ((ext == \"MAT\") || (ext == \"COV\"))\n\t{\n\t\tfrom_ascii(filename);\n\t}\n\telse if (ext == \"CSV\")\n\t{\n\t\tfrom_csv(filename);\n\t}\n\telse\n\t{\n\t\tss << \"Mat::from_file() error: unrecognized extension'\" << ext << \"', should be JCB, JCO, MAT or CSV\";\n\t\tthrow runtime_error(ss.str());\n\t}\n\n}\n\nvoid Mat::from_csv(const string &filename)\n{\n\tifstream csv(filename);\n\tif (!csv.good())\n\t\tthrow runtime_error(\"Mat::from_csv() error: cannot open \" + filename + \" \\\n\t\t\t\t\t\t\t\t\t\t\t\tto read csv matrix\");\n\n\n\t//process the header\n\t//any missing header labels will be marked to ignore those columns later\n\tstring line;\n\tif (!getline(csv, line))\n\t\tthrow runtime_error(\"error reading header (first) line from csv file :\");\n\tpest_utils::strip_ip(line);\n\tpest_utils::upper_ip(line);\n\tpest_utils::tokenize(line, col_names, \",\", false);\n\tcol_names.erase(col_names.begin()); //drop the index label\n\tvector<Eigen::Triplet<double>> triplet_list;\n\tdouble val;\n\n\t//read a csv file to an Ensmeble\n\tint lcount = 0, irow = 0;\n\t//vector<vector<double>> vectors;\n\tvector<string> tokens;\n\tstring row_name;\n\n\twhile (getline(csv, line))\n\t{\n\t\tpest_utils::strip_ip(line);\n\t\ttokens.clear();\n\t\tpest_utils::tokenize(line, tokens, \",\", false);\n\t\tif (tokens[tokens.size() - 1].size() == 0)\n\t\t\ttokens.pop_back();\n\n\t\ttry\n\t\t{\n\t\t\tpest_utils::convert_ip(tokens[0], row_name);\n\t\t}\n\t\tcatch (exception &e)\n\t\t{\n\t\t\tstringstream ss;\n\t\t\tss << \"error converting token '\" << tokens[0] << \"' to <int> run_id on line \" << lcount << \": \" << line << endl << e.what();\n\t\t\tthrow runtime_error(ss.str());\n\t\t}\n\t\ttokens.erase(tokens.begin()); //drop the row name\n\t\tif (tokens.size() != col_names.size())\n\t\t{\n\t\t\tstringstream ss;\n\t\t\tss << \"Matrix.from_csv() error: wrong number of entries on line \" << lcount << \" , expecting \" << col_names.size() << \", found \" << tokens.size() << endl;\n\t\t\tthrow runtime_error(ss.str());\n\t\t}\n\t\trow_names.push_back(pest_utils::upper_cp(row_name));\n\t\tfor (int j = 0; j < col_names.size(); j++)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tval = pest_utils::convert_cp<double>(tokens[j]);\n\t\t\t}\n\t\t\tcatch (exception &e)\n\t\t\t{\n\t\t\t\tstringstream ss;\n\t\t\t\tss << \"error converting token '\" << tokens[j] << \"' to double for \" << col_names[j] << \" on line \" << lcount << \" : \" << e.what();\n\t\t\t\tthrow runtime_error(ss.str());\n\t\t\t}\n\t\t\tif (val != 0.0)\n\t\t\t\ttriplet_list.push_back(Eigen::Triplet<double>(irow, j, val));\n\t\t}\n\n\tlcount++;\n\tirow++;\n\t}\n\tmatrix.resize(row_names.size(), col_names.size());\n\tmatrix.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n}\n\n\nvoid Mat::from_triplets(const vector<string> &_row_names, const vector<string> &_col_names, const vector<Eigen::Triplet<double>> &triplets)\n{\n\tmatrix.resize(_row_names.size(), _col_names.size());\n\t//matrix.setZero();\n\tmatrix.setFromTriplets(triplets.begin(), triplets.end());\n\t//cout << matrix.cols() << endl;\n\trow_names = _row_names;\n\tcol_names = _col_names;\n\n}\n\nvoid Mat::from_ascii(const string &filename)\n{\n\tifstream in(filename);\n\tif (!in.good())\n\t\tthrow runtime_error(\"Mat::from_ascii() error: cannot open \" + filename + \" \\\n\t\t\t\t\t\t\t\t\t\t\t\tto read ASCII matrix\");\n\tint nrow = -999, ncol = -999;\n\tif (in >> nrow >> ncol >> icode){}\n\telse\n\t\tthrow runtime_error(\"Mat::from_ascii() error reading nrow ncol icode from first line\\\n\t\t\t\t\t\t\t of ASCII matrix file: \" + filename);\n\n\tvector<Eigen::Triplet<double>> triplet_list;\n\tdouble val;\n\tint irow = 0, jcol = 0;\n\tfor (int inode = 0; inode < nrow*ncol;inode++)\n\t{\n\t\tif (in >> val)\n\t\t{\n\t\t\tif (val != 0.0)\n\t\t\t\ttriplet_list.push_back(Eigen::Triplet<double>(irow,jcol,val));\n\t\t\tjcol++;\n\t\t\tif (jcol >= ncol)\n\t\t\t{\n\t\t\t\tirow++;\n\t\t\t\tjcol = 0;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstring i_str = to_string(inode);\n\t\t\tthrow runtime_error(\"Mat::from_ascii() error reading entry number \"+i_str+\" from\\\n\t\t\t\t\t\t\t\t ASCII matrix file: \"+filename);\n\t\t}\n\t}\n\n\tstring header;\n\t//read the newline char\n\tgetline(in, header);\n\tif (!getline(in,header))\n\t\tthrow runtime_error(\"Mat::from_ascii() error reading row/col description\\\n\t\t\t\t\t\t\t line from ASCII matrix file: \" + filename);\n\tpest_utils::upper_ip(header);\n\tstring name;\n\tif (icode == 1)\n\t{\n\t\tif (nrow != ncol)\n\t\t\tthrow runtime_error(\"Mat::from_ascii() error: nrow != ncol for icode type 1 ASCII matrix file:\" + filename);\n\t\tif((header.find(\"ROW\") == string::npos) || (header.find(\"COLUMN\") == string::npos))\n\t\t\tthrow runtime_error(\"Mat::from_ascii() error: expecting row and column names header instead\\\n\t\t\t\t\t\t\t\t of:\" + header + \" in ASCII matrix file: \" + filename);\n\t\ttry\n\t\t{\n\t\t\trow_names = read_namelist(in, nrow);\n\t\t}\n\t\tcatch (exception &e)\n\t\t{\n\t\t\tthrow runtime_error(\"Mat::from_ascii() error reading row/column names from ASCII matrix file: \" + filename + \"\\n\" + e.what());\n\t\t}\n\t\tif ((nrow != row_names.size()) || (ncol != row_names.size()))\n\t\t\tthrow runtime_error(\"Mat::from_ascii() error: number of row/col names does not match matrix dimensions\");\n\t\tcol_names = row_names;\n\t}\n\telse\n\t{\n\t\tif(header.find(\"ROW\") == string::npos)\n\t\t\tthrow runtime_error(\"Mat::from_ascii() error: expecting row names header instead of:\" + header + \" in ASCII matrix file: \" + filename);\n\t\ttry\n\t\t{\n\t\t\trow_names = read_namelist(in, nrow);\n\t\t}\n\t\tcatch (exception &e)\n\t\t{\n\t\t\tthrow runtime_error(\"Mat::from_ascii() error reading row names from ASCII matrix file: \" + filename + \"\\n\" + e.what());\n\t\t}\n\t\tif (!getline(in, header))\n\t\t{\n\t\t\tthrow runtime_error(\"Mat::from_ascii() error reading column name descriptor from ASCII matrix file: \" + filename);\n\t\t}\n\t\tpest_utils::upper_ip(header);\n\t\tif (header.find(\"COLUMN\") == string::npos)\n\t\t\tthrow runtime_error(\"Mat::from_ascii() error: expecting column names header instead of:\" + header + \" in ASCII matrix file: \" + filename);\n\t\ttry\n\t\t{\n\t\t\tcol_names = read_namelist(in, ncol);\n\t\t}\n\t\tcatch (exception &e)\n\t\t{\n\t\t\tthrow runtime_error(\"Mat::from_ascii() error reading column names from ASCII matrix file: \" + filename + \"\\n\" + e.what());\n\t\t}\n\t\tif (nrow != row_names.size())\n\t\t\tthrow runtime_error(\"Mat::from_ascii() error: nrow != row_names.size() in ASCII matrix file: \" + filename);\n\n\t\tif(ncol != col_names.size())\n\t\t\tthrow runtime_error(\"Mat::from_ascii() error: ncol != col_names.size() in ASCII matrix file: \" + filename);\n\t}\n\tin.close();\n\n\tEigen::SparseMatrix<double> new_matrix(nrow, ncol);\n\tnew_matrix.setZero();  // initialize all entries to 0\n\tnew_matrix.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\t\n\tmatrix = new_matrix;\n}\n\nvector<string> Mat::read_namelist(ifstream &in, int &nitems)\n{\n\tvector<string> names;\n\tstring name;\n\tfor (int i = 0; i < nitems; i++)\n\t{\n\t\tif (!getline(in, name))\n\t\t{\n\t\t\tstring i_str = to_string(i);\n\t\t\tthrow runtime_error(\"Mat::read_namelist() error reading name for entry \" + i_str);\n\t\t}\n\t\tif (name.find(\"*\") != string::npos)\n\t\t{\n\t\t\tstring i_str = to_string(i);\n\t\t\tthrow runtime_error(\"Mat::read_namelist() error: '*' found in item name: \" + name+\", item number: \"+i_str);\n\t\t}\n\t\tpest_utils::strip_ip(name);\n\t\tpest_utils::upper_ip(name);\n\t\tif (find(names.begin(), names.end(), name) != names.end())\n\t\t\tthrow runtime_error(\"Mat::read_namelist() error: duplicate name: \" + name + \" found in name list\");\n\t\tnames.push_back(name);\n\t}\n\treturn names;\n}\n\nvoid Mat::to_binary(const string &filename)\n{\n\tpest_utils::save_binary_orgfmt(filename, row_names, col_names, matrix);\n//\tofstream jout(filename, ios::out | ios::binary);\n//\tint n_par = col_names.size();\n//\tint n_obs_and_pi = row_names.size();\n//\tint n;\n//\tint tmp;\n//\tdouble data;\n//\tchar par_name[12];\n//\tchar obs_name[20];\n//\n//\t// write header\n//\ttmp = -n_par;\n//\tjout.write((char*)&tmp, sizeof(tmp));\n//\ttmp = -n_obs_and_pi;\n//\tjout.write((char*)&tmp, sizeof(tmp));\n//\n//\t//write number nonzero elements in jacobian (includes prior information)\n//\tn = matrix.nonZeros();\n//\tjout.write((char*)&n, sizeof(n));\n//\n//\t//write matrix\n//\tn = 0;\n//\tmap<string, double>::const_iterator found_pi_par;\n//\tmap<string, double>::const_iterator not_found_pi_par;\n//\n//\tEigen::SparseMatrix<double> matrix_T(matrix);\n//\tmatrix_T.transpose();\n//\tfor (int icol = 0; icol<matrix.outerSize(); ++icol)\n//\t{\n//\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(matrix_T, icol); it; ++it)\n//\t\t{\n//\t\t\tdata = it.value();\n//\t\t\tn = it.row() + 1 + it.col() * matrix_T.rows();\n//\t\t\tjout.write((char*) &(n), sizeof(n));\n//\t\t\tjout.write((char*) &(data), sizeof(data));\n//\t\t}\n//\t}\n//\t//save parameter names\n//\tfor (vector<string>::const_iterator b = col_names.begin(), e = col_names.end();\n//\t\tb != e; ++b) {\n//\t\tstring l = pest_utils::lower_cp(*b);\n//\t\tpest_utils::string_to_fortran_char(l, par_name, 12);\n//\t\tjout.write(par_name, 12);\n//\t}\n//\n//\t//save observation and Prior information names\n//\tfor (vector<string>::const_iterator b = row_names.begin(), e = row_names.end();\n//\t\tb != e; ++b) {\n//\t\tstring l = pest_utils::lower_cp(*b);\n//\t\tpest_utils::string_to_fortran_char(l, obs_name, 20);\n//\t\tjout.write(obs_name, 20);\n//\t}\n//\t//save observation names (part 2 prior information)\n//\tjout.close();\n}\n\nvoid Mat::to_binary_new(const string &filename)\n{\n\tpest_utils::save_binary_extfmt(filename, row_names, col_names, matrix);\n//\tofstream jout(filename, ios::out | ios::binary);\n//\tint n_par = col_names.size();\n//\tint n_obs_and_pi = row_names.size();\n//\tint n;\n//\tint tmp;\n//\tdouble data;\n//\tchar par_name[200];\n//\tchar obs_name[200];\n//\n//\t// write header\n//\ttmp = n_par;\n//\tjout.write((char*)&tmp, sizeof(tmp));\n//\ttmp = n_obs_and_pi;\n//\tjout.write((char*)&tmp, sizeof(tmp));\n//\n//\t//write number nonzero elements in jacobian (includes prior information)\n//\tn = matrix.nonZeros();\n//\tjout.write((char*)&n, sizeof(n));\n//\n//\t//write matrix\n//\tn = 0;\n//\tmap<string, double>::const_iterator found_pi_par;\n//\tmap<string, double>::const_iterator not_found_pi_par;\n//\n//\tEigen::SparseMatrix<double> matrix_T(matrix);\n//\tmatrix_T.transpose();\n//\tfor (int icol = 0; icol<matrix.outerSize(); ++icol)\n//\t{\n//\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(matrix_T, icol); it; ++it)\n//\t\t{\n//\t\t\tdata = it.value();\n//\t\t\tn = it.row() - 1;\n//\t\t\tjout.write((char*) &(n), sizeof(n));\n//\t\t\tn = it.col() - 1;\n//\t\t\tjout.write((char*) &(n), sizeof(n));\n//\n//\t\t\tjout.write((char*) &(data), sizeof(data));\n//\t\t}\n//\t}\n//\t//save parameter names\n//\tfor (vector<string>::const_iterator b = col_names.begin(), e = col_names.end();\n//\t\tb != e; ++b) {\n//\t\tstring l = pest_utils::lower_cp(*b);\n//\t\tpest_utils::string_to_fortran_char(l, par_name, 200);\n//\t\tjout.write(par_name, 200);\n//\t}\n//\n//\t//save observation and Prior information names\n//\tfor (vector<string>::const_iterator b = row_names.begin(), e = row_names.end();\n//\t\tb != e; ++b) {\n//\t\tstring l = pest_utils::lower_cp(*b);\n//\t\tpest_utils::string_to_fortran_char(l, obs_name, 200);\n//\t\tjout.write(obs_name, 200);\n//\t}\n//\t//save observation names (part 2 prior information)\n//\tjout.close();\n}\n\nvoid Mat::from_binary(const string &filename)\n{\n\tpest_utils::read_binary(filename, row_names, col_names, matrix);\n}\n\n\n\n//-----------------------------------------\n//Maninpulate the shape and ordering of Mats\n//-----------------------------------------\n\nMat Mat::leftCols(const int idx)\n{\n\tvector<string> cnames;\n\tvector<string> base_cnames = *cn_ptr();\n\tfor (int i = 0; i < idx; i++)\n\t\tcnames.push_back(base_cnames[i]);\n\treturn Mat(row_names,cnames,matrix.leftCols(idx));\n}\n\nMat Mat::rightCols(const int idx)\n{\n\tvector<string> cnames;\n\tvector<string> base_cnames = *cn_ptr();\n\tfor (int i = ncol() - idx; i < ncol(); i++)\n\t\tcnames.push_back(base_cnames[i]);\n\treturn Mat(row_names,cnames,matrix.rightCols(idx));\n}\n\nMat Mat::get(const vector<string> &new_row_names, const vector<string> &new_col_names, bool update)\n{\n\t//check that every row and col name is listed\n\tif (new_row_names.size() == 0) throw runtime_error(\"Mat::get() error: new_row_names is empty\");\n\tif (new_col_names.size() == 0) throw runtime_error(\"Mat::get() error: new_col_names is empty\");\n\tvector<string> row_not_found;\n\t\n\tif (update)\n\t\tupdate_sets();\n\tset<string>::iterator end = row_set.end();\n\tfor (auto &n : new_row_names)\n\t\tif (row_set.find(n) == end)\n\t\t\trow_not_found.push_back(n);\n\n\tvector<string> col_not_found;\n\t//set<string> col_set(col_names.begin(), col_names.end());\n\tend = col_set.end();\n\tfor (auto &n : new_col_names)\n\t\tif (col_set.find(n) == end)\n\t\t\tcol_not_found.push_back(n);\n\tif (row_not_found.size() != 0)\n\t{\n\t\tcout << \"Mat::get() error: the following row names were not found:\" << endl;\n\t\tfor (auto &name : row_not_found)\n\t\t\tcout << name << \",\";\n\t\tcout << endl;\n\t}\n\n\tif (col_not_found.size() != 0)\n\t{\n\t\tcout << \"Mat::get() error: the following col names were not found:\" << endl;\n\t\tfor (auto &name : col_not_found)\n\t\t\tcout << name << \",\";\n\t\tcout << endl;\n\t}\n\n\tif ((row_not_found.size() != 0) || (col_not_found.size() != 0))\n\t{\n\t\tthrow runtime_error(\"Mat::get() error: atleast one row or col name not found in Mat::get()\");\n\t}\n\n\n\tint nrow = new_row_names.size();\n\tint ncol = new_col_names.size();\n\tint irow_new;\n\tint icol_new;\n\n\tunordered_map<string, int> row_name2new_index_map;\n\tunordered_map<string, int> col_name2new_index_map;\n\n\t// Build mapping of parameter names to column number in new matrix to be returned\n\ticol_new = 0;\n\tfor (vector<string>::const_iterator b = new_col_names.begin(), e = new_col_names.end();\n\t\tb != e; ++b, ++icol_new) {\n\t\tcol_name2new_index_map[(*b)] = icol_new;\n\t}\n\n\t// Build mapping of observation names to row  number in new matrix to be returned\n\tirow_new = 0;\n\tfor (vector<string>::const_iterator b = new_row_names.begin(), e = new_row_names.end();\n\t\tb != e; ++b, ++irow_new) {\n\t\trow_name2new_index_map[(*b)] = irow_new;\n\t}\n\n\tunordered_map<string, int>::const_iterator found_col;\n\tunordered_map<string, int>::const_iterator found_row;\n\tunordered_map<string, int>::const_iterator not_found_col_map = col_name2new_index_map.end();\n\tunordered_map<string, int>::const_iterator not_found_row_map = row_name2new_index_map.end();\n\n\tconst string *row_name;\n\tconst string *col_name;\n\tstd::vector<Eigen::Triplet<double> > triplet_list;\n\tfor (int icol = 0; icol<matrix.outerSize(); ++icol)\n\t{\n\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(matrix, icol); it; ++it)\n\t\t{\n\t\t\tcol_name = &col_names[it.col()];\n\t\t\trow_name = &row_names[it.row()];\n\t\t\tfound_col = col_name2new_index_map.find(*col_name);\n\t\t\tfound_row = row_name2new_index_map.find(*row_name);\n\t\t\tif (found_col != not_found_col_map && found_row != not_found_row_map)\n\t\t\t{\n\t\t\t\ttriplet_list.push_back(Eigen::Triplet<double>(found_row->second, found_col->second, it.value()));\n\t\t\t}\n\t\t}\n\t}\n\t//if (triplet_list.size() == 0)\n\t\t//throw runtime_error(\"Mat::get() error: triplet list is empty\");\n\n\tEigen::SparseMatrix<double> new_matrix(nrow, ncol);\n\tnew_matrix.setZero();\n\tif (triplet_list.size() > 0)\n\t\tnew_matrix.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\treturn Mat(new_row_names,new_col_names,new_matrix,this->mattype);\n}\n\nMat Mat::extract(const vector<string> &extract_row_names, const vector<string> &extract_col_names)\n{\n\tMat new_mat;\n\tif ((extract_row_names.size() == 0) && (extract_col_names.size() == 0))\n\t\tthrow runtime_error(\"Mat::extract() error: extract_rows and extract_cols both empty\");\n\telse if (extract_row_names.size() == 0)\n\t{\n\t\tnew_mat = get(row_names, extract_col_names);\n\t\tdrop_cols(extract_col_names);\n\t}\n\telse if (extract_col_names.size() == 0)\n\t{\n\t\tnew_mat = get(extract_row_names, col_names);\n\t\tdrop_rows(extract_row_names);\n\t}\n\telse\n\t{\n\t\tnew_mat = get(extract_row_names, extract_col_names);\n\t\tdrop_rows(extract_row_names);\n\t\tdrop_cols(extract_col_names);\n\t}\n\treturn new_mat;\n}\n\nMat Mat::extract(const string &extract_row_name, const vector<string> &extract_col_names)\n{\n\tvector<string> extract_row_names;\n\textract_row_names.push_back(extract_row_name);\n\treturn extract(extract_row_names, extract_col_names);\n}\nMat Mat::extract(const vector<string> &extract_row_names, const string &extract_col_name)\n{\n\tvector<string> extract_col_names;\n\textract_col_names.push_back(extract_col_name);\n\treturn extract(extract_row_names, extract_col_names);\n}\n\nbool Mat::isdiagonal()\n{\n\tif (mattype == MatType::DIAGONAL)\n\t\treturn true;\n\treturn false;\n}\n\nvoid Mat::drop_cols(const vector<string> &drop_col_names)\n{\n\tvector<string> missing_col_names;\n\tconst set<string> snames(col_names.begin(), col_names.end());\n\tset<string>::const_iterator send = snames.end();\n\tfor (auto &name : drop_col_names)\n\t{\n\t\t//if (find(col_names.begin(), col_names.end(), name) == col_names.end())\n\t\tif (snames.find(name) == send)\n\t\t\tmissing_col_names.push_back(name);\n\t}\n\n\tif (missing_col_names.size() != 0)\n\t{\n\t\tcout << \"Mat::drop_cols() error: the following drop_col_names were not found:\" << endl;\n\t\tfor (auto &name : drop_col_names)\n\t\t\tcout << name << ',';\n\t\tcout << endl;\n\t\tthrow runtime_error(\"Mat::drop_cols() error: atleast one drop col name not found\");\n\t}\n\tvector<string> new_col_names;\n\tif (drop_col_names.size() == 0)\n\t\tnew_col_names = col_names;\n\telse\n\t{\n\t\tconst set<string> snames(drop_col_names.begin(), drop_col_names.end());\n\t\tset<string>::const_iterator send = snames.end();\n\t\tfor (auto &name : col_names)\n\t\t{\n\t\t\t//if (find(drop_col_names.begin(), drop_col_names.end(), name) == drop_col_names.end())\n\t\t\tif (snames.find(name) == send)\n\t\t\t\tnew_col_names.push_back(name);\n\t\t}\n\t}\n\tMat new_mat = get(row_names, new_col_names);\n\tmatrix = new_mat.get_matrix();\n\tcol_names = new_col_names;\n\tmattype = new_mat.get_mattype();\n}\n\nvoid Mat::drop_rows(const vector<string> &drop_row_names)\n{\n\n\tvector<string> missing_row_names;\n\tconst set<string> snames(row_names.begin(), row_names.end());\n\tset<string>::const_iterator send = snames.end();\n\n\tfor (auto &name : drop_row_names)\n\t{\n\t\t//if (find(row_names.begin(), row_names.end(), name) == row_names.end())\n\t\tif (snames.find(name) == send)\n\t\t\tmissing_row_names.push_back(name);\n\t}\n\n\tif (missing_row_names.size() != 0)\n\t{\n\t\tcout << \"Mat::drop_rows() error: the following drop_row_names were not found:\" << endl;\n\t\tfor (auto &name : drop_row_names)\n\t\t\tcout << name << ',';\n\t\tcout << endl;\n\t\tthrow runtime_error(\"Mat::drop_rows() error: atleast one drop row name not found\");\n\t}\n\n\tvector<string> new_row_names;\n\tif (drop_row_names.size() == 0)\n\t\tnew_row_names = row_names;\n\telse\n\t{\n\t\tconst set<string> snames(drop_row_names.begin(), drop_row_names.end());\n\t\tset<string>::const_iterator send = snames.end();\n\t\tfor (auto &name : row_names)\n\t\t{\n\t\t\t//if (find(drop_row_names.begin(), drop_row_names.end(), name) == drop_row_names.end())\n\t\t\tif (snames.find(name) == send)\n\t\t\t\tnew_row_names.push_back(name);\n\t\t}\n\t}\n\tif (new_row_names.size() == 0)\n\t\tmatrix = Eigen::SparseMatrix<double>();\n\telse\n\t{\n\t\tMat new_mat = get(new_row_names, col_names);\n\t\tmatrix = new_mat.get_matrix();\n\t\tmattype = new_mat.get_mattype();\n\t}\n\trow_names = new_row_names;\n\n}\n\n\n\n//-----------------------------------------\n//covariance matrices\n//-----------------------------------------\nCovariance::Covariance(string filename)\n{\n\tmattype = MatType::SPARSE;\n\tstring ext = filename.substr(filename.find_last_of(\".\") + 1);\n\tvector<string> empty;\n\tpest_utils::upper_ip(ext);\n\tif (ext == \"PST\")\n\t\tthrow runtime_error(\"Cov::Cov() error: cannot instantiate a cov with PST\");\n\telse if (ext == \"MAT\")\n\t\tfrom_ascii(filename);\n\telse if (ext == \"UNC\")\n\t\tfrom_uncertainty_file(filename, empty);\n\telse\n\t\tthrow runtime_error(\"Cov::Cov() error: only .unc or .mat\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t files can be used to instatiate a Cov\");\n}\n\nCovariance::Covariance(vector<string> &names)\n{\n\trow_names = names;\n\tcol_names = names;\n\ticode = 1;\n\tmattype = MatType::SPARSE;\n}\n\nCovariance::Covariance()\n{\n\ticode = 1;\n\tmattype = MatType::SPARSE;\n}\n\nCovariance::Covariance(vector<string> _names, Eigen::SparseMatrix<double> _matrix, Mat::MatType _mattype)\n{\n\tif ((_names.size() != _matrix.rows()) || (_names.size() != _matrix.cols()))\n\t\tthrow runtime_error(\"Covariance::Covariance() error: names.size() does not match matrix dimensions\");\n\tEigen::SparseMatrix<double> test = _matrix;\n\tmatrix = _matrix;\n\trow_names = _names;\n\tcol_names = _names;\n\ticode = 1;\n\tmattype =_mattype;\n}\n\nCovariance::Covariance(Mat _mat)\n{\n\tif (_mat.get_row_names() != _mat.get_col_names())\n\t\tthrow runtime_error(\"Cov::Cov() error instantiating Covariance from Mat: row_names != col_names\");\n\trow_names = _mat.get_row_names();\n\tcol_names = _mat.get_col_names();\n\tmatrix = _mat.get_matrix();\n\ticode = 1;\n\tmattype = _mat.get_mattype();\n}\n\n\nvoid Covariance::from_diagonal(Covariance &other)\n{\n\trow_names = other.get_row_names();\n\tcol_names = other.get_col_names();\n\tif (other.get_mattype() == Mat::MatType::DIAGONAL)\n\t{\n\t\tmatrix = other.get_matrix();\n\t}\n\telse\n\t{\n\t\tEigen::MatrixXd temp = other.e_ptr()->diagonal().asDiagonal();\n\t\tEigen::SparseMatrix<double> temp2 = temp.sparseView();\n\t\tmatrix = temp2;\n\t}\n\n}\nCovariance Covariance::diagonal(double val)\n{\n\tvector<Eigen::Triplet<double>> triplet_list;\n\tfor (int i = 0; i != nrow(); i++)\n\t\ttriplet_list.push_back(Eigen::Triplet<double>(i, i, val));\n\tEigen::SparseMatrix<double> i(nrow(), ncol());\n\ti.setZero();\n\ti.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\treturn Covariance(*rn_ptr(), i);\n}\n\nstring Covariance::try_from(Pest &pest_scenario, FileManager &file_manager, bool is_parcov, bool forgive_missing)\n{\n\tstringstream how;\n\tstringstream ss;\n\tstring cov_fname;\n\tvector<string> ordered_names;\n\tif (is_parcov)\n\t{\n\t\tcov_fname = pest_scenario.get_pestpp_options().get_parcov_filename();\n\t\tordered_names = pest_scenario.get_ctl_ordered_adj_par_names();\n\t}\n\telse\n\t{\n\t\tcov_fname = pest_scenario.get_pestpp_options().get_obscov_filename();\n\t\tordered_names = pest_scenario.get_ctl_ordered_nz_obs_names();\n\t}\n\tif (!cov_fname.empty())\n\t{\n\t\tstring ext = cov_fname.substr(cov_fname.size() - 3, 3);\n\t\tpest_utils::upper_ip(ext);\n\t\tif (ext == \"UNC\")\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tfrom_uncertainty_file(cov_fname, ordered_names);\n\t\t\t\thow << \"from unc file \" << cov_fname;\n\t\t\t}\n\t\t\tcatch (exception &e)\n\t\t\t{\n\t\t\t\tss << \"Cov::try_from() error reading uncertainty file \" << cov_fname << \" :\" << e.what();\n\t\t\t\tthrow runtime_error(ss.str());\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tMat::from_file(cov_fname);\n\t\t\t\thow << \" from file \" << cov_fname;\n\t\t\t}\n\t\t\tcatch (exception &e)\n\t\t\t{\n\t\t\t\tss << \"Cov:try_from() error reading from file \" << cov_fname << \" :\" << e.what();\n\t\t\t\tthrow runtime_error(ss.str());\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (is_parcov)\n\t\t{\n\t\t\tfrom_parameter_bounds(pest_scenario, file_manager.rec_ofstream());\n\t\t\thow << \"from parameter bounds, using par_sigma_range \" << pest_scenario.get_pestpp_options().get_par_sigma_range();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfrom_observation_weights(pest_scenario, file_manager.rec_ofstream());\n\t\t\thow << \"from observation weights\";\n\t\t}\n\t\t}\n\t//check that the parcov matrix has the right parameter names\n\tvector<string> missing;\n\tif ((is_parcov) && (cov_fname.size() > 0))\n\t{\n\t\tset<string> parcov_names(row_names.begin(), row_names.end());\n\t\tconst ParameterRec *prec;\n\t\tfor (auto &pname : pest_scenario.get_ctl_ordered_par_names())\n\t\t{\n\t\t\tprec = pest_scenario.get_ctl_parameter_info().get_parameter_rec_ptr(pname);\n\t\t\tif ((prec->tranform_type == ParameterRec::TRAN_TYPE::LOG) ||\n\t\t\t\t(prec->tranform_type == ParameterRec::TRAN_TYPE::NONE))\n\t\t\t{\n\t\t\t\tif (parcov_names.find(pname) == parcov_names.end())\n\t\t\t\t{\n\t\t\t\t\tmissing.push_back(pname);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (missing.size() > 0)\n\t\t{\n\t\t\tofstream& frec = file_manager.rec_ofstream();\n\t\t\tfrec << \"...Note: parcov missing the following \" << missing.size() << \" adjustable parameters:\" << endl;\n\t\t\tint i = 0;\n\t\t\tfor (auto& pname : missing)\n\t\t\t{\n\t\t\t\tfrec << ',' << pname;\n\t\t\t\ti++;\n\t\t\t\tif (i > 10)\n\t\t\t\t{\n\t\t\t\t\tfrec << endl;\n\t\t\t\t\ti = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfrec << endl;\n\t\t\tif (forgive_missing)\n\t\t\t{\n\t\t\t\tcout << \"WARNING: \" << missing.size() << \" adjustable parameters missing from parcov, continuing...\" << endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tss.str(\"\");\n\t\t\t\tss << \"parcov missing \" << missing.size() << \"adjustable parameters, see rec file for listing\";\n\t\t\t\tthrow PestError(ss.str());\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\tif ((!is_parcov) && (cov_fname.size() > 0))\n\t{\n\t\tdouble weight;\n\t\tset<string> cov_names(row_names.begin(), row_names.end());\n\t\tfor (auto &oname : pest_scenario.get_ctl_ordered_obs_names())\n\t\t{\n\t\t\tweight = pest_scenario.get_ctl_observation_info().get_weight(oname);\n\t\t\tif (weight == 0.0)\n\t\t\t\tcontinue;\n\t\t\tif (cov_names.find(oname) == cov_names.end())\n\t\t\t{\n\t\t\t\tmissing.push_back(oname);\n\t\t\t}\n\n\t\t}\n\t\tif (missing.size() > 0)\n\t\t{\n\t\t\tofstream& frec = file_manager.rec_ofstream();\n\t\t\tfrec << \"...Note: obscov missing the following \" << missing.size() << \" non-zero weighted obs:\" << endl;\n\t\t\tint i = 0;\n\t\t\tfor (auto& name : missing)\n\t\t\t{\n\t\t\t\tfrec << ',' << name;\n\t\t\t\ti++;\n\t\t\t\tif (i > 10)\n\t\t\t\t{\n\t\t\t\t\tfrec << endl;\n\t\t\t\t\ti = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfrec << endl;\n\t\t\tif (forgive_missing)\n\t\t\t{\n\t\t\t\tcout << \"WARNING: \" << missing.size() << \" non-zero weighted observations missing from obscov, continuing...\" << endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tss.str(\"\");\n\t\t\t\tss << \"obscov missing \" << missing.size() << \"non-zero weighted observations, see rec file for listing\";\n\t\t\t\tthrow PestError(ss.str());\n\t\t\t}\n\t\t}\n\t}\n\n\tvector<string> extra;\n\tset<string> allowed_names(ordered_names.begin(), ordered_names.end());\n\tordered_names.clear();\n\n\tfor (auto name : row_names)\n\t{\n\t\tif (allowed_names.find(name) == allowed_names.end())\n\t\t\textra.push_back(name);\n\t}\n\tif (extra.size() > 0)\n\t{\n\t\tstringstream ss;\n\t\tss << \"WARNING: Cov::try_from(): \" << extra.size() << \" extra elements in covariance matrix being drop - these are probably for fixed parameters and/or zero-weight observations\";\n\t\t//for (auto name : extra)\n\t\t//\tss << \" \" << name;\n\t\t//throw PestError(ss.str());\n\t\tfile_manager.rec_ofstream() << ss.str() << endl << endl;\n\t\t//cout << \"WARNING: \" << extra.size() << \" unrecognized elements in covariance matrix being dropped, see .rec file for listing\" << endl;\n\t\tdrop(extra);\n\t}\n\treturn how.str();\n}\n\n\nCovariance Covariance::get(const vector<string> &other_names, bool update)\n{\n\tCovariance new_cov(Mat::get(other_names, other_names, update));\n\treturn new_cov;\n}\n\nCovariance Covariance::extract(vector<string> &extract_names)\n{\n\tCovariance new_cov(Mat::extract(extract_names, extract_names));\n\treturn new_cov;\n}\n\nvoid Covariance::drop(vector<string> &drop_names)\n{\n\tdrop_rows(drop_names);\n\tdrop_cols(drop_names);\n}\n\nvoid Covariance::from_uncertainty_file(const string &filename, vector<string> &ordered_names)\n{\n\tifstream in(filename);\n\tif (!in.good())\n\t{\n\t\tthrow runtime_error(\"Cov::from_uncertainty_file() error: cannot open \" + filename + \" to read uncertainty file: \"+filename);\n\t}\n\tmattype = MatType::DIAGONAL;\n\tvector<Eigen::Triplet<double>> triplet_list;\n\tvector<string> names;\n\tstring line,name,word;\n\tdouble val;\n\tvector<string> tokens;\n\tint irow=0, jcol=0;\n\n\twhile (getline(in, line))\n\t{\n\t\tif (line.substr(0, 1).find(\"#\") != string::npos)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tpest_utils::upper_ip(line);\n\t\t//if this is the start of some block\n\t\tif (line.find(\"START\") != string::npos)\n\t\t{\n\t\t\tif (line.find(\"STANDARD_DEVIATION\") != string::npos)\n\t\t\t{\n\t\t\t\twhile (true)\n\t\t\t\t{\n\t\t\t\t\tif (!getline(in, line))\n\t\t\t\t\t\tthrow runtime_error(\"Cov::from_uncertainty_file() error:EOF encountered while reading standard_deviation block\\\n\t\t\t\t\t\t\tfrom uncertainty file:\" + filename);\n\t\t\t\t\tpest_utils::upper_ip(line);\n\t\t\t\t\tif (line.find(\"END\") != string::npos)\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\ttokens.clear();\n\t\t\t\t\tpest_utils::tokenize(line, tokens);\n\t\t\t\t\tpest_utils::convert_ip(tokens[1], val);\n\t\t\t\t\tname = tokens[0];\n\t\t\t\t\tdouble std_mlt = 1.0;\n\t\t\t\t\tif (name == \"STD_MULTIPLIER\")\n\t\t\t\t\t{\n\t\t\t\t\t\tstd_mlt = val;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (find(names.begin(), names.end(), name) != names.end())\n\t\t\t\t\t\tthrow runtime_error(name + \" listed more than once in uncertainty file:\" + filename);\n\t\t\t\t\tnames.push_back(tokens[0]);\n\t\t\t\t\ttriplet_list.push_back(Eigen::Triplet<double>(irow, jcol, val * std_mlt));\n\t\t\t\t\tirow++, jcol++;\n\t\t\t\t}\n\n\t\t\t}\n\t\t\telse if (line.find(\"COVARIANCE_MATRIX\") != string::npos)\n\t\t\t{\n\t\t\t\tstring cov_filename = \"none\";\n\t\t\t\tdouble var_mult = 1.0;\n\t\t\t\tstring start_par = \"\", end_par = \"\";\n\t\t\t\tstring par_list_file = \"\";\n\t\t\t\twhile (true)\n\t\t\t\t{\n\t\t\t\t\tif (!getline(in, line))\n\t\t\t\t\t\tthrow runtime_error(\"Cov::from_uncertainty_file() error:EOF encountered while reading covariance_matrix block\\\n\t\t\t\t\t\t\tfrom uncertainty file:\" + filename);\n\t\t\t\t\t// keep line in original case to preserve filename\n\t\t\t\t\tline.erase(remove(line.begin(), line.end(), '\\\"'), line.end());\n\t\t\t\t\tline.erase(remove(line.begin(), line.end(), '\\''), line.end());\n\t\t\t\t\tstring upper_line = line;\n\t\t\t\t\tpest_utils::upper_ip(upper_line);\n\t\t\t\t\tif (upper_line.find(\"END\") != string::npos) break;\n\n\t\t\t\t\ttokens.clear();\n\t\t\t\t\tpest_utils::tokenize(line, tokens);\n\t\t\t\t\tword = pest_utils::upper_cp(tokens[0]);\n\t\t\t\t\tif (word.find(\"FILE\") != string::npos)\n\t\t\t\t\t\tcov_filename = tokens[1];\n\t\t\t\t\telse if (word.find(\"VARIANCE_MULTIPLIER\") != string::npos)\n\t\t\t\t\t\tpest_utils::convert_ip(tokens[1], var_mult);\n\t\t\t\t\telse if (word.find(\"FIRST_PARAMETER\") != string::npos)\n\t\t\t\t\t\tstart_par = pest_utils::upper_cp(tokens[1]);\n\t\t\t\t\telse if (word.find(\"LAST_PARAMETER\") != string::npos)\n\t\t\t\t\t\tend_par = pest_utils::upper_cp(tokens[1]);\n\t\t\t\t\telse if (word.find(\"PARAMETER_LIST_FILE\"))\n\t\t\t\t\t\tpar_list_file = tokens[1];\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow runtime_error(\"Cov::from_uncertainty_file() error:unrecognized token:\" + tokens[0] + \" in covariance matrix block in uncertainty file:\" + filename);\n\t\t\t\t}\n\n\t\t\t\tif ((start_par.size() > 0) && (end_par.size() == 0))\n\t\t\t\t\tthrow runtime_error(\"Cov::from_uncertainty_file() error: 'FIRST PARAMETER' passed but 'LAST_PARAMETER' was not\");\n\t\t\t\tif ((start_par.size() == 0) && (end_par.size() > 0))\n\t\t\t\t\tthrow runtime_error(\"Cov::from_uncertainty_file() error: 'LAST PARAMETER' passed but 'FIRST_PARAMETER' was not\");\n\n\t\t\t\t//read the covariance matrix\n\t\t\t\tCovariance cov;\n\t\t\t\tcov.from_ascii(cov_filename);\n\n\t\t\t\tif ((start_par.size() > 0) && (end_par.size() > 0))\n\t\t\t\t{\n\t\t\t\t\tif (par_list_file.size() > 0)\n\t\t\t\t\t\tthrow runtime_error(\"Cov::from_uncertainty_file() error: both 'PARAMETER_LIST_FILE' AND 'FIRST_PARAMETER'/'LAST_PARAMETER' supplied\");\n\t\t\t\t\tif (ordered_names.size() == 0)\n\t\t\t\t\t\tthrow runtime_error(\"Cov::from_uncertainty_file() error: ordered_names arg req for first_par/last_par option\");\n\t\t\t\t\tvector<string>::iterator first, last;\n\t\t\t\t\tfirst = find(ordered_names.begin(), ordered_names.end(), start_par);\n\t\t\t\t\tif (first == ordered_names.end())\n\t\t\t\t\t\tthrow runtime_error(\"Cov::from_uncertainty_file() error: couldn't find 'FIRST_PARAMETER' \" + start_par);\n\t\t\t\t\tlast = find(ordered_names.begin(), ordered_names.end(), end_par);\n\t\t\t\t\tif (last == ordered_names.end())\n\t\t\t\t\t\tthrow runtime_error(\"Cov::from_uncertainty_file() error: couldn't find 'LAST_PARAMETER' \" + end_par);\n\t\t\t\t\tvector<string> ordered_names_matrix(first, last+1);\n\t\t\t\t\tif (ordered_names_matrix.size() != cov.col_names.size())\n\t\t\t\t\t{\n\t\t\t\t\t\tstringstream ss;\n\t\t\t\t\t\tss << \"Cov::from_uncertainty_file() error: number of elements in covariance matrix \" << cov_filename << \" (\" << cov.col_names.size();\n\t\t\t\t\t\tss << \") different from number of elements between 'FIRST_PARAMETER' and 'LAST_PARAMETER' (\" << ordered_names_matrix.size() << \")\";\n\t\t\t\t\t\tthrow runtime_error(ss.str());\n\t\t\t\t\t}\n\t\t\t\t\tcov.row_names = ordered_names_matrix;\n\t\t\t\t\tcov.col_names = ordered_names_matrix;\n\t\t\t\t}\n\t\t\t\telse if (par_list_file.size() > 0)\n\t\t\t\t{\n\t\t\t\t\tvector<string> par_names;\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tpar_names = pest_utils::read_onecol_ascii_to_vector(par_list_file);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (...)\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow runtime_error(\"Cov::from_uncertainty_file() error reading 'PARAMETER_LIST_FILE' \" + par_list_file);\n\t\t\t\t\t}\n\t\t\t\t\tif (par_names.size() != cov.col_names.size())\n\t\t\t\t\t{\n\t\t\t\t\t\tstringstream ss;\n\t\t\t\t\t\tss << \"Cov::from_uncertainty_file() error: number of elements in covariance matrix \" << cov_filename;\n\t\t\t\t\t\tss << \" (\" << cov.col_names.size() << \") different from number of elements in 'PARAMETER_LIST_FILE' (\" << par_names.size() << \")\";\n\t\t\t\t\t\tthrow runtime_error(ss.str());\n\t\t\t\t\t}\n\t\t\t\t\tcov.row_names = par_names;\n\t\t\t\t\tcov.col_names = par_names;\n\t\t\t\t}\n\n\n\n\t\t\t\t//check that the names in the covariance matrix are not already listed\n\t\t\t\tvector<string> dup_names;\n\t\t\t\tfor (auto &name : cov.get_row_names())\n\t\t\t\t{\n\t\t\t\t\tif (find(names.begin(), names.end(), name) != names.end())\n\t\t\t\t\t\tdup_names.push_back(name);\n\t\t\t\t\telse\n\t\t\t\t\t\tnames.push_back(name);\n\t\t\t\t}\n\t\t\t\tif (dup_names.size() != 0)\n\t\t\t\t{\n\t\t\t\t\tcout << \"the following names from covariance matrix file \" << cov_filename << \" have already be found in uncertainty file \" << filename << endl;\n\t\t\t\t\tfor (auto &name : dup_names)\n\t\t\t\t\t\tcout << name << ',';\n\t\t\t\t\tcout << endl;\n\t\t\t\t\tthrow runtime_error(\"Cov::from_uncertainty_file() error:atleast one name in covariance matrix \" + cov_filename + \" is already listed in uncertainty file: \" + filename);\n\t\t\t\t}\n\n\t\t\t\t//build triplets from the covariance matrix\n\t\t\t\tint start_irow = irow;\n\t\t\t\tEigen::SparseMatrix<double> cov_matrix = cov.get_matrix();\n\t\t\t\tfor (int icol = 0; icol < cov_matrix.outerSize(); ++icol)\n\t\t\t\t{\n\t\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(cov_matrix, icol); it; ++it)\n\t\t\t\t\t{\n\t\t\t\t\t\ttriplet_list.push_back(Eigen::Triplet<double>(start_irow + it.row(), jcol, var_mult * it.value()));\n\t\t\t\t\t\tirow++;\n\t\t\t\t\t}\n\t\t\t\t\tjcol++;\n\t\t\t\t\tirow = start_irow;\n\t\t\t\t}\n\t\t\t\tmattype = MatType::SPARSE;\n\t\t\t\tirow = jcol;\n\t\t\t}\n\t\t\telse\n\t\t\t\tthrow runtime_error(\"Cov::from_uncertainty_file() error:unrecognized block:\" + line + \" in uncertainty file:\" + filename);\n\t\t}\n\t}\n\n\tEigen::SparseMatrix<double> new_matrix(names.size(), names.size());\n\tnew_matrix.setZero();  // initialize all entries to 0\n\tnew_matrix.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\t//cout << new_matrix.diagonal() << endl;\n\tmatrix = new_matrix;\n\trow_names = names;\n\tcol_names = names;\n}\n\nvoid Covariance::from_parameter_bounds(ofstream& frec, const vector<string> &par_names,const ParameterInfo &par_info, \n\tmap<string, double>& par_std, double sigma_range)\n{\n\tmatrix.resize(0, 0);\n\trow_names.clear();\n\tcol_names.clear();\n\tvector<Eigen::Triplet<double>> triplet_list;\n\tconst ParameterRec* par_rec;\n\tint i = 0;\n\tdouble upper, lower;\n\tfor (auto par_name : par_names)\n\t{\n\t\tpest_utils::upper_ip(par_name);\n\t\tpar_rec = par_info.get_parameter_rec_ptr(par_name);\n\t\tif ((par_rec->tranform_type == ParameterRec::TRAN_TYPE::FIXED) || (par_rec->tranform_type == ParameterRec::TRAN_TYPE::TIED))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif (par_std.find(par_name) != par_std.end())\n\t\t{\n\t\t\ttriplet_list.push_back(Eigen::Triplet<double>(i, i, pow(par_std[par_name], 2.0)));\n\t\t\trow_names.push_back(par_name);\n\t\t\tcol_names.push_back(par_name);\n\t\t\ti++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tupper = par_rec->ubnd;\n\t\t\tlower = par_rec->lbnd;\n\t\t\tif (par_rec->tranform_type == ParameterRec::TRAN_TYPE::LOG)\n\t\t\t{\n\t\t\t\tupper = log10(upper);\n\t\t\t\tlower = log10(lower);\n\t\t\t}\n\t\t\trow_names.push_back(par_name);\n\t\t\tcol_names.push_back(par_name);\n\t\t\t//double temp = pow((upper - lower) / 4.0,2.0);\n\t\t\ttriplet_list.push_back(Eigen::Triplet<double>(i, i, pow((upper - lower) / sigma_range, 2.0)));\n\t\t\ti++;\n\t\t}\n\t}\n\tif (triplet_list.size() > 0)\n\t{\n\t\tmatrix.resize(row_names.size(), row_names.size());\n\t\tmatrix.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\t}\n\telse\n\t{\n\t\tthrow runtime_error(\"Cov::from_parameter_bounds() error:Error loading covariance from parameter bounds: no non-fixed/non-tied parameters found\");\n\t}\n\tmattype = Mat::MatType::DIAGONAL;\n}\n\n\n\nvoid Covariance::from_parameter_bounds(Pest &pest_scenario, ofstream& frec)\n{\n\tmap<string, double> par_std = pest_scenario.get_ext_file_double_map(\"parameter data external\", \"standard_deviation\");\n\tif (par_std.size() > 0)\n\t{\n\t\tfrec << \"Note: the following parameters have 'standard_deviation' defined - this will be used\" << endl;\n\t\tfrec << \"      instead of bounds for the prior parameter covariance matrix : \" << endl;\n\t\tvector<string> remove;\n\t\tfor (auto pname : pest_scenario.get_ctl_ordered_par_names())\n\t\t{\n\t\t\tif (par_std.find(pname) != par_std.end())\n\t\t\t{\n\t\t\t\tif (par_std[pname] <= 0.0)\n\t\t\t\t{\n\t\t\t\t\tfrec << \"Warning: parameter \" << pname << \" 'standard_deviation' less than or equal to zero, using bounds instead\" << endl;\n\t\t\t\t\tremove.push_back(pname);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tfrec << pname << ' ' << par_std[pname] << endl;\n\t\t\t}\n\t\t\t\t\n\t\t}\n\t\tfor (auto r : remove)\n\t\t\tpar_std.erase(r);\n\t}\n\n\tfrom_parameter_bounds(frec, pest_scenario.get_ctl_ordered_par_names(), pest_scenario.get_ctl_parameter_info(),\n\t\tpar_std,pest_scenario.get_pestpp_options().get_par_sigma_range());\n}\n\nvoid Covariance::from_parameter_bounds(const string &pst_filename, ofstream& frec)\n{\n\tifstream ipst(pst_filename);\n\tif (!ipst.good()) throw runtime_error(\"Cov::from_parameter_bounds() error opening pst file: \" + pst_filename);\n\tPest pest_scenario;\n\tpest_scenario.process_ctl_file(ipst, pst_filename);\n\tfrom_parameter_bounds(pest_scenario, frec);\n}\n\nvoid Covariance::from_observation_weights(const string &pst_filename, ofstream& frec)\n{\n\tifstream ipst(pst_filename);\n\tif (!ipst.good()) throw runtime_error(\"Cov::from_observation_weights() error opening pst file: \" + pst_filename);\n\tPest pest_scenario;\n\tpest_scenario.process_ctl_file(ipst, pst_filename);\n\tfrom_observation_weights(pest_scenario,frec);\n\n}\n\n\nvoid Covariance::from_observation_weights(ofstream& frec, const vector<string>& obs_names, const ObservationInfo& obs_info, \n\tconst vector<string>& pi_names, const PriorInformation* pi, map<string,double>& obs_std)\n{\n\tmatrix.resize(0, 0);\n\trow_names.clear();\n\tcol_names.clear();\n\tvector<Eigen::Triplet<double>> triplet_list;\n\tconst ObservationRec* obs_rec;\n\tint i = 0;\n\tdouble weight = 0;\n\tfor (auto obs_name : obs_names)\n\t{\n\t\tpest_utils::upper_ip(obs_name);\n\t\tobs_rec = obs_info.get_observation_rec_ptr(obs_name);\n\t\tif (obs_std.find(obs_name) != obs_std.end())\n\t\t{\n\t\t\ttriplet_list.push_back(Eigen::Triplet<double>(i, i, pow(obs_std[obs_name], 2)));\n\t\t\trow_names.push_back(obs_name);\n\t\t\tcol_names.push_back(obs_name);\n\t\t\ti++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tobs_rec = obs_info.get_observation_rec_ptr(obs_name);\n\t\t\tweight = obs_rec->weight;\n\t\t\tif (weight <= 0.0)\n\t\t\t\tweight = 1.0e+60;\n\t\t\telse\n\t\t\t\tweight = pow(1.0 / obs_rec->weight, 2.0);\n\t\t\ttriplet_list.push_back(Eigen::Triplet<double>(i, i, weight));\n\t\t\trow_names.push_back(obs_name);\n\t\t\tcol_names.push_back(obs_name);\n\t\t\ti++;\n\t\t}\n\t}\n\n\t/*PriorInformation::const_iterator pi_iter;\n\tPriorInformation::const_iterator not_pi_iter = pi->end();\n\n\tfor (auto pi_name : pi_names)\n\t{\n\t\tpi_iter = pi->find(pi_name);\n\t\tif (pi_iter != not_pi_iter)\n\t\t{\n\t\t\tweight = pi_iter->second.get_weight();\n\t\t\tif (weight <= 0.0) weight = 1.0e-30;\n\t\t\ttriplet_list.push_back(Eigen::Triplet<double>(i, i, pow(1.0 / weight, 2.0)));\n\t\t\trow_names.push_back(pi_name);\n\t\t\tcol_names.push_back(pi_name);\n\t\t\ti++;\n\t\t}\n\t}*/\n\tif (row_names.size() > 0)\n\t{\n\t\tmatrix.resize(row_names.size(), row_names.size());\n\t\tmatrix.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\t}\n\telse\n\t{\n\t\tthrow runtime_error(\"Cov::from_observation_weights() error:Error loading covariance from obs weights: no non-zero weighted obs found\");\n\t}\n\tmattype = Mat::MatType::DIAGONAL;\n\t/*if (mattype == Mat::MatType::DIAGONAL)\n\t\tcout << \"diagonal\" << endl;*/\n}\n\n\nvoid Covariance::from_observation_weights(Pest &pest_scenario, ofstream& frec)\n{\n\tmap<string, double> obs_std = pest_scenario.get_ext_file_double_map(\"observation data external\", \"standard_deviation\");\n\tvector<string> remove;\n\tif (obs_std.size() > 0)\n\t{\n\t\tfrec << \"Note: the following observations have 'standard_deviation' defined - this will be used\" << endl;\n\t\tfrec << \"      instead of weight for the observation noise covariance matrix : \" << endl;\n\t\tfor (auto oname : pest_scenario.get_ctl_ordered_obs_names())\n\t\t{\n\t\t\tif (obs_std.find(oname) != obs_std.end())\n\t\t\t{\n\t\t\t\tif (obs_std[oname] <= 0.0)\n\t\t\t\t{\n\t\t\t\t\tfrec << \"Warning: observation \" << oname << \" 'standard_deviation' less than or equal to zero, using weight\" << endl;\n\t\t\t\t\tremove.push_back(oname);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tfrec << oname << ' ' << obs_std[oname] << endl;\n\t\t\t}\n\t\t}\n\t\tfor (auto r : remove)\n\t\t\tobs_std.erase(r);\n\t}\n\n\tfrom_observation_weights(frec, pest_scenario.get_ctl_ordered_obs_names(), pest_scenario.get_ctl_observation_info(),\n\t\tpest_scenario.get_ctl_ordered_pi_names(), pest_scenario.get_prior_info_ptr(), obs_std);\n\n}\n\nvoid Covariance::to_uncertainty_file(const string &filename)\n{\n\tofstream out(filename);\n\tif (!out.good())\n\t{\n\t\tthrow runtime_error(\"Cov::to_uncertainty_file() error opening file: \" + filename + \" to write an uncertainty file\");\n\t}\n\n\t//check if diagonal, write stdevs\n\tif (mattype == Mat::MatType::DIAGONAL)\n\t{\n\t\tEigen::VectorXd vec(matrix.diagonal());\n\t\tout << \"START STANDARD_DEVIATION\" << endl;\n\t\tint i=0;\n\t\tfor (vector<string>::iterator name = row_names.begin(); name != row_names.end(); ++name, i++)\n\t\t{\n\t\t\tout << \"  \" << setw(20) << left << *name << \"  \" << setw(20) << left << vec(i) << endl;\n\t\t}\n\t\tout << \"END STANDARD_DEVIATION\" << endl;\n\t\tout.close();\n\t}\n\telse\n\t{\n\t\tout << \"START COVARIANCE_MATRIX\" << endl;\n\t\tout << \"  file emu_cov.mat\" << endl;\n\t\tout << \" variance multiplier 1.0\" << endl;\n\t\tout << \"END COVARIANCE_MATRIX\" << endl;\n\t\tout.close();\n\t\tto_ascii(\"emu_cov.mat\");\n\t}\n}\n\nvoid Covariance::cholesky()\n{\n\tEigen::SimplicialLLT<Eigen::SparseMatrix<double>> llt;\n\tlower_cholesky = llt.matrixL();\n}\n\nvector<Eigen::VectorXd> Covariance::draw(int ndraws)\n{\n\tthrow runtime_error(\"Covariance::draw() not implemented\");\n}\n\nvector<double> Covariance::standard_normal(default_random_engine gen)\n{\n\tnormal_distribution<double> stanard_normal(0.0, 1.0);\n\tvector<double> sn_vec;\n\tfor (auto &name : row_names)\n\t{\n\t\tsn_vec.push_back(stanard_normal(gen));\n\t}\n\treturn sn_vec;\n}\n", "meta": {"hexsha": "f4aa0a74b93518d04c651645d703d5eab8b872ea", "size": 50531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/PEST++/src/libs/pestpp_common/covariance.cpp", "max_stars_repo_name": "usgs/neversink_workflow", "max_stars_repo_head_hexsha": "acd61435b8553e38d4a903c8cd7a3afc612446f9", "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": "source/PEST++/src/libs/pestpp_common/covariance.cpp", "max_issues_repo_name": "usgs/neversink_workflow", "max_issues_repo_head_hexsha": "acd61435b8553e38d4a903c8cd7a3afc612446f9", "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": "source/PEST++/src/libs/pestpp_common/covariance.cpp", "max_forks_repo_name": "usgs/neversink_workflow", "max_forks_repo_head_hexsha": "acd61435b8553e38d4a903c8cd7a3afc612446f9", "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": 29.0909614277, "max_line_length": 180, "alphanum_fraction": 0.6630583206, "num_tokens": 13963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.515705094732104}}
{"text": "#ifndef HTLP_HPP_\n#define HTLP_HPP_\n\n#include <NTL/ZZ.h>\n#include <assert.h>\n#include <openssl/sha.h>\n#include <vector>\n#include <sstream>\n\n#include \"Puzzle.hpp\"\n\n#ifndef RSA_\n#define RSA_\ntypedef struct RSA\n{\n    NTL::ZZ p;\n    NTL::ZZ q;\n} RSA;\n#endif\n\nclass HTLP\n{\nprotected:\n    const bool cheeting_mode_;\n    RSA rsa_;\n    NTL::ZZ n_;\n    NTL::ZZ n_square_;\n    NTL::ZZ g_;\n    NTL::ZZ h_;\n    NTL::ZZ lambda_;\n    const long T_;\n    const long kappa_;\n    long prime_len_;\n    const long modulus_len_;\n    NTL::ZZ trapdoor_;\n    RSA GenerateRSAModulus(const long modulus_len);\n\npublic:\n    HTLP(const long modulus_len, const long T, const long kappa);\n    HTLP(const NTL::ZZ &n, const NTL::ZZ &g, const NTL::ZZ &h, const long T, const long kappa);\n    HTLP(const long modulus_len, const long T, const long kappa, bool cheeting_mode);\n\n    NTL::ZZ HashToElement(const std::string str);\n    NTL::ZZ HashToPrime(const NTL::ZZ &g, const NTL::ZZ &h);\n\n    NTL::ZZ GenerateProof(const long k, const long gamma, std::vector<NTL::ZZ> &C, NTL::ZZ &l);\n\n    NTL::ZZ GenerateJacobiOne();\n    NTL::ZZ GenerateRandomExponent()\n    {\n        return RandomBnd(n_ / 2);\n    }\n    NTL::ZZ GenerateRandomElement()\n    {\n        return RandomBnd(n_);\n    }\n\n    NTL::ZZ n()\n    {\n        return n_;\n    }\n    NTL::ZZ n_square()\n    {\n        return n_square_;\n    }\n    NTL::ZZ g()\n    {\n        return g_;\n    }\n    NTL::ZZ h()\n    {\n        return h_;\n    }\n    long T()\n    {\n        return T_;\n    }\n\n};\n\n#endif", "meta": {"hexsha": "ddbaa4e1a2a945d0af8632aebb772ef64c014fa9", "size": 1502, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/HTLP.hpp", "max_stars_repo_name": "liu-yi/HTLP", "max_stars_repo_head_hexsha": "c66a0c8b126c52e6ac74dbba9b7be0828bb8ef45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HTLP.hpp", "max_issues_repo_name": "liu-yi/HTLP", "max_issues_repo_head_hexsha": "c66a0c8b126c52e6ac74dbba9b7be0828bb8ef45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HTLP.hpp", "max_forks_repo_name": "liu-yi/HTLP", "max_forks_repo_head_hexsha": "c66a0c8b126c52e6ac74dbba9b7be0828bb8ef45", "max_forks_repo_licenses": ["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.5432098765, "max_line_length": 95, "alphanum_fraction": 0.5985352863, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5157050857511217}}
{"text": "#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <iostream>\n\nusing namespace boost::accumulators;\n\nint main()\n{\n  accumulator_set<double, features<tag::mean, tag::variance>> acc;\n  acc(8);\n  acc(9);\n  acc(10);\n  acc(11);\n  acc(12);\n  std::cout << mean(acc) << '\\n';\n  std::cout << variance(acc) << '\\n';\n}", "meta": {"hexsha": "7dfa8c56ea141cfd232b287fbce8da625f2a0a66", "size": 357, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Example/accumulators_02/main.cpp", "max_stars_repo_name": "KwangjoJeong/Boost", "max_stars_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_stars_repo_licenses": ["MIT"], "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/accumulators_02/main.cpp", "max_issues_repo_name": "KwangjoJeong/Boost", "max_issues_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_issues_repo_licenses": ["MIT"], "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/accumulators_02/main.cpp", "max_forks_repo_name": "KwangjoJeong/Boost", "max_forks_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_forks_repo_licenses": ["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": 66, "alphanum_fraction": 0.6610644258, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5156449647820736}}
{"text": "#ifndef __solver_cod_h__\n#define __solver_cod_h__\n\n#include <Eigen/Dense>\n#include <vector>\n#include <iostream>\n#include \"weighted_hqp/givens.hpp\"\n\nnamespace hcod{\n    class Cod{\n        public:\n            Cod(const Eigen::MatrixXd &A, const double &THR);\n            ~Cod(){};\n        \n        private: \n            void calc_decomposition();\n            void computation();\n\n        public:\n            Eigen::MatrixXd getW(){\n                return W_permute_;\n            }\n            Eigen::MatrixXd getL(){\n                return L_permute_;\n            }\n            Eigen::MatrixXd getQ(){\n                return Q_;\n            }\n            Eigen::MatrixXd getE(){\n                return E_;\n            }\n            int getRank(){\n                return rankA_;\n            }\n\n           \n            \n        private:\n           Eigen::MatrixXd A_, Q_, R_, E_, L_, W_, L_permute_, W_permute_ ;\n           double THR_;\n           int rankA_;\n           Givens* givens_t;\n           \n    };\n}\n\n#endif", "meta": {"hexsha": "75322b79715f2f189bd75d2fc24c3b83ea210a5b", "size": 1013, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dyros_jet_controller/include/weighted_hqp/cod.hpp", "max_stars_repo_name": "Junhyung-Kim/dyros_jet", "max_stars_repo_head_hexsha": "63bff65137a4e3bb85d22a71ea90d9850b12e69e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-31T05:33:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-14T08:56:45.000Z", "max_issues_repo_path": "dyros_jet_controller/include/weighted_hqp/cod.hpp", "max_issues_repo_name": "Junhyung-Kim/dyros_jet", "max_issues_repo_head_hexsha": "63bff65137a4e3bb85d22a71ea90d9850b12e69e", "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": "dyros_jet_controller/include/weighted_hqp/cod.hpp", "max_forks_repo_name": "Junhyung-Kim/dyros_jet", "max_forks_repo_head_hexsha": "63bff65137a4e3bb85d22a71ea90d9850b12e69e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T04:22:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-10T04:22:39.000Z", "avg_line_length": 21.5531914894, "max_line_length": 75, "alphanum_fraction": 0.4550839092, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5156449545365922}}
{"text": "#pragma once \n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/algorithm/hex.hpp>\n\n\nnamespace Ethereum{namespace ABI{\n\n\ntypedef boost::multiprecision::cpp_dec_float_100 decimal_t;\ntypedef boost::multiprecision::uint256_t uint256_t;\ntypedef boost::multiprecision::int256_t int256_t;\n\n\n}}\n", "meta": {"hexsha": "371c19b9f57e863026dcbf870199835183238fb6", "size": 349, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/types.hpp", "max_stars_repo_name": "Xeth/libabi", "max_stars_repo_head_hexsha": "b0100834ad6ba9de6bf8a158acfb9e50865d5b59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-01T10:23:15.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-12T19:40:11.000Z", "max_issues_repo_path": "src/types.hpp", "max_issues_repo_name": "BitProfile/libabi", "max_issues_repo_head_hexsha": "b0100834ad6ba9de6bf8a158acfb9e50865d5b59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/types.hpp", "max_forks_repo_name": "BitProfile/libabi", "max_forks_repo_head_hexsha": "b0100834ad6ba9de6bf8a158acfb9e50865d5b59", "max_forks_repo_licenses": ["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.5294117647, "max_line_length": 59, "alphanum_fraction": 0.8080229226, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5154611134777279}}
{"text": "#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../jngen.h\"\n\nBOOST_AUTO_TEST_SUITE(graph)\n\nBOOST_AUTO_TEST_CASE(output) {\n    setMod().reset();\n\n    Graph g;\n    g.addEdge(0, 2);\n    g.addEdge(1, 3);\n    g.addEdge(0, 3);\n    g.addEdge(0, 3);\n    g.addEdge(1, 2);\n    g.addEdge(2, 1);\n\n    std::ostringstream ss;\n    ss << g.printN().printM().add1() << std::endl;\n\n    BOOST_TEST(ss.str() == \"4 6\\n1 3\\n2 4\\n1 4\\n1 4\\n2 3\\n3 2\\n\");\n}\n\nBOOST_AUTO_TEST_CASE(weights_and_labelling) {\n    setMod().reset();\n\n    rnd.seed(123);\n\n    Graph g = Graph::random(10, 20);\n\n    g.setVertexWeights(Array::random(g.n(), 100));\n    g.setEdgeWeights(Arrayf::random(g.m(), 1.5, 1.8));\n\n    g.setVertexWeight(5, \"five\");\n    g.setVertexWeight(8, \"eight\");\n    g.addEdge(5, 8, \"5-8\");\n\n    g.shuffle();\n\n    std::stringstream ss;\n    ss << g.printN().printM() << std::endl;\n\n    int v1, v2;\n    int v5 = -1, v8 = -1;\n    std::string s;\n    ss >> v1 >> v2;\n    BOOST_TEST(v1 == g.n());\n    BOOST_TEST(v2 == g.m());\n\n    for (int i = 0; i < g.n(); ++i) {\n        ss >> s;\n        if (s == \"five\") {\n            v5 = i;\n        } else if (s == \"eight\") {\n            v8 = i;\n        }\n    }\n\n    BOOST_CHECK(v5 != -1 && v8 != -1);\n\n    int count = 0;\n    for (int i = 0; i < g.m(); ++i) {\n        ss >> v1 >> v2 >> s;\n        if (s == \"5-8\") {\n            ++count;\n            BOOST_CHECK( (v1 == v5 && v2 == v8) || (v1 == v8 && v2 == v5) );\n        }\n    }\n\n    BOOST_TEST(count == 1);\n}\n\ntemplate<typename T>\nvoid generateWithTraitsMask(T&& generator, const std::string& name, int mask) {\n    if (mask&(1<<0)) generator.allowAntiparallel();\n    if (mask&(1<<1)) generator.allowLoops();\n    if (mask&(1<<2)) generator.allowMulti();\n    if (mask&(1<<3)) generator.connected();\n    if (mask&(1<<4)) generator.directed();\n    if (mask&(1<<5)) generator.acyclic();\n    try {\n        generator.g();\n    } catch (jngen::Exception) {\n        // directed acyclic cycle\n        if (name == \"cycle\" && (mask & ((1<<4) | (1<<5)))) {\n            return;\n        }\n\n        // connected empty graph\n        if (name == \"empty\" && (mask & (1<<3))) {\n            return;\n        }\n\n        throw;\n\n        /*\n        // left here for debug purposes\n        std::cerr << name << \": \";\n        for (int i = 0; i < 6; ++i) {\n            if (mask&(1<<i)) {\n                std::cerr << \"+\";\n            } else {\n                std::cerr << \"-\";\n            }\n        }\n        std::cerr << std::endl;\n        */\n    }\n}\n\nBOOST_AUTO_TEST_CASE(various_traits) {\n    BOOST_CHECK(true);\n\n    for (int mask = 0; mask < (1<<6); ++mask) {\n        generateWithTraitsMask(Graph::random(10, 15), \"random\", mask);\n        generateWithTraitsMask(\n                Graph::randomStretched(10, 15, 5, 5), \"randomStretched\", mask);\n        generateWithTraitsMask(Graph::complete(10), \"complete\", mask);\n        generateWithTraitsMask(Graph::cycle(10), \"cycle\", mask);\n        generateWithTraitsMask(Graph::empty(10), \"empty\", mask);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(empty_output) {\n    setMod().reset();\n\n    std::stringstream ss;\n\n    ss << Graph::random(10, 0).g().printN().printM().add1() << std::endl;\n    BOOST_TEST(ss.str() == \"10 0\\n\");\n    ss.str(\"\");\n\n    ss << Graph::random(10, 0).g().printN().add1() << std::endl;\n    BOOST_TEST(ss.str() == \"10\\n\");\n    ss.str(\"\");\n\n    Graph g = Graph::random(10, 0);\n    g.setVertexWeights(Array::random(g.n(), 10, 20));\n    ss << g.printN().printM() << std::endl;\n    auto s = ss.str();\n    s.pop_back();\n    BOOST_TEST(s != \"\\n\");\n    ss.str(\"\");\n\n    g = Graph::empty(5);\n    g.setVertexWeights(Array::id(5));\n    ss << g << std::endl;\n    BOOST_TEST(ss.str() == \"0 1 2 3 4\\n\");\n    ss.str(\"\");\n\n    g = Graph::empty(0);\n    ss << g.printN().printM() << std::endl;\n    BOOST_TEST(ss.str() == \"0 0\\n\");\n    ss.str(\"\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "1a652f0419b3e8fe29eaf8bd88fcac7eb3b657ae", "size": 3866, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/graph.cpp", "max_stars_repo_name": "landcold7/jngen", "max_stars_repo_head_hexsha": "c7cfb26cd21009efbb736a75147da550c699b545", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 197.0, "max_stars_repo_stars_event_min_datetime": "2017-04-07T20:57:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T18:06:36.000Z", "max_issues_repo_path": "tests/graph.cpp", "max_issues_repo_name": "zekiriabd/jngen", "max_issues_repo_head_hexsha": "ca646e2f4df9b63c14380157d3911a0182149f94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-07-14T01:42:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T11:25:40.000Z", "max_forks_repo_path": "tests/graph.cpp", "max_forks_repo_name": "zekiriabd/jngen", "max_forks_repo_head_hexsha": "ca646e2f4df9b63c14380157d3911a0182149f94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2017-07-05T21:31:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T09:36:51.000Z", "avg_line_length": 24.4683544304, "max_line_length": 79, "alphanum_fraction": 0.5023279876, "num_tokens": 1200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5154611088576929}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/3/problem3.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem3 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem3::solve(13195);\n        BOOST_CHECK_EQUAL(res, 29);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem3::solve();\n        BOOST_CHECK_EQUAL(res, 6857);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "92c99a2c3f87ffaa170297bd7ffaa95c942a4423", "size": 490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem3.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": "tests/1-50/test_problem3.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": "tests/1-50/test_problem3.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.3333333333, "max_line_length": 52, "alphanum_fraction": 0.6734693878, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5154611042376582}}
{"text": "//\n// Copyright 2020 Debabrata Mandal <mandaldebabrata123@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.hpp>\n#include <boost/gil/extension/io/png.hpp>\n#include <boost/gil/io/read_image.hpp>\n\n#include <iostream>\n\nusing namespace boost::gil;\n\n// Explains how to use the histogram class and some of its features\n// that can be applied for a variety of tasks.\n\n// See also:\n// histogram_equalization.cpp - Regular Histogram Equalization\n// adaptive_he.cpp - Adaptive Histogram Equalization\n// histogram_matching.cpp - Reference-based histogram computation\n\nint main()\n{\n   // Create a histogram class. Use uint or unsigned short as the default axes type in most cases.\n    histogram<unsigned char> h;\n\n    // Fill histogram with GIL images (of any color space)\n    gray8_image_t g;\n    read_image(\"test_adaptive.png\", g, png_tag{});\n\n    fill_histogram\n    (\n        view(g), // Input image view\n        h,       // Histogram to be filled\n        1,       // Histogram bin widths\n        false,   // Specify whether to accumulate over the values already present in h (default = false)\n        true,    // Specify whether to have a sparse (true) or continuous histogram (false) (default = true)\n        false,   // Specify if image mask is to be specified\n        {{}},    // Mask as a 2D vector. Used only if prev argument specified\n        {0},     // Lower limit on the values in histogram (default numeric_limit::min() on axes)\n        {255},   // Upper limit on the values in histogram (default numeric_limit::max() on axes)\n        true     // Use specified limits if this is true (default is false)\n    );\n\n    // Normalize the histogram \n    h.normalize();\n\n    // Get a cumulative histogram from the histogram\n    auto h2 = cumulative_histogram(h);\n\n    return 0;\n}\n", "meta": {"hexsha": "8adc40e9caf780b6ab4824ae06f122d721521818", "size": 1915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/histogram.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/histogram.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/histogram.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": 34.1964285714, "max_line_length": 108, "alphanum_fraction": 0.681462141, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5154610996176232}}
{"text": "#include <boost/config/warning_disable.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/karma.hpp>\n#include <boost/spirit/include/phoenix_core.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n\n#include <iostream>\n#include <string>\n#include <complex>\n\nnamespace client{\n  template <typename Iterator>\n    bool parse_complex(Iterator first, Iterator last, std::complex<double>& c){\n      using boost::spirit::qi::double_;\n      using boost::spirit::qi::_1;\n      using boost::spirit::qi::phrase_parse;\n      using boost::spirit::ascii::space;\n      using boost::phoenix::ref;\n\n      double rN = 0.0;\n      double iN = 0.0;\n      bool r = phrase_parse(first, last,\n          (\n            '(' >> double_[ref(rN) = _1]\n                >> -(',' >> double_[ref(iN) = _1]) >> ')'\n            | double_[ref(rN) = _1]\n          ),\n          space);\n\n      if(!r || first != last)\n        return false;\n      c = std::complex<double>(rN, iN);\n      return r;\n    }\n\n  template <typename OutputIterator>\n    bool generate_complex(OutputIterator sink, std::complex<double> const& c){\n      using boost::spirit::karma::eps;\n      using boost::spirit::karma::double_;\n      using boost::spirit::karma::_1;\n      using boost::spirit::karma::generate;\n\n      return generate(sink,\n          (\n            eps(c.imag() != 0) << '(' << double_[_1 = c.real()] << \", \" << double_[_1 = c.imag()] << ')'\n            | double_[_1 = c.real()]\n          )\n      );\n    }\n}\n\nint main(){\n  std::string str;\n  while(getline(std::cin, str)){\n    if(str.empty() || str[0] == 'q' || str[0] == 'Q')\n      break;\n\n    std::complex<double> c;\n    if(client::parse_complex(str.begin(), str.end(), c)){\n      std::string generated;\n      std::back_insert_iterator<std::string> sink(generated);\n      if(!client::generate_complex(sink, c)){\n        std::cout << \"Generating failed\\n\";\n      }\n      else{\n        std::cout << \"Generated: \" << generated << std::endl;\n      }\n    }\n    else{\n      std::cout << \"Parsing failed\\n\";\n    }\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "0144e2fa213edc33dc18e29547deb7fbace6e25d", "size": 2098, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/karma/complex_number.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/karma/complex_number.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/karma/complex_number.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": 27.2467532468, "max_line_length": 104, "alphanum_fraction": 0.5667302193, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.515461096162138}}
{"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_REM_PIO2_CEPHES_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REM_PIO2_CEPHES_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the Computes the remainder modulo \\f$\\pi/2\\f$ with cephes algorithm,\n     and the angle quadrant between 0 and 3.\n\n     This is a quick version accurate if the input is in \\f$[-20\\pi,20\\pi]\\f$.\n\n\n    @par Header <boost/simd/function/rem_pio2_cephes.hpp>\n\n    @par Note\n\n      Using `std::tie(n, r) = rem_pio2_cephes(x)` is similar to\n      `n = div(inearbyint, x, Pio_2<T>())` and `r = remainder(x, Pio_2<T>())`\n\n\n    @par Example:\n\n      @snippet rem_pio2_cephes.cpp rem_pio2_cephes\n\n    @par Possible output:\n\n      @snippet rem_pio2_cephes.txt rem_pio2_cephes\n\n  **/\n  std::pair<IEEEValue, IEEEValue> rem_pio2_cephes(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/rem_pio2_cephes.hpp>\n#include <boost/simd/function/simd/rem_pio2_cephes.hpp>\n\n#endif\n", "meta": {"hexsha": "f2c68c2bdc3a794f0fae9f2b1f818e772666adb3", "size": 1418, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/rem_pio2_cephes.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/function/rem_pio2_cephes.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/function/rem_pio2_cephes.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": 27.8039215686, "max_line_length": 101, "alphanum_fraction": 0.6184767278, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5154259164180843}}
{"text": "//==================================================================================================\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#include <boost/simd/function/cbrt.hpp>\n#include <boost/simd/function/saturated.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/std.hpp>\n#include <simd_test.hpp>\n\n\nnamespace bs = boost::simd;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], b[N], c[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i) : T(-i);\n    b[i] = bs::cbrt(a1[i]) ;\n    c[i] = bs::std_(bs::cbrt)(a1[i]);\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t bb (&b[0], &b[0]+N);\n  p_t cc (&c[0], &c[0]+N);\n  STF_ULP_EQUAL(bs::cbrt(aa1), bb,0.5);\n  STF_ULP_EQUAL(bs::std_(bs::cbrt)(aa1), cc,0.5);\n}\n\nSTF_CASE_TPL(\"Check cbrt on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n\n", "meta": {"hexsha": "4b86d827c700fbe4cf246631edbab5c0bbff30c4", "size": 1212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/cbrt.cpp", "max_stars_repo_name": "timblechmann/boost.simd", "max_stars_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/simd/cbrt.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "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/function/simd/cbrt.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 25.7872340426, "max_line_length": 100, "alphanum_fraction": 0.5041254125, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5154259101403379}}
{"text": "#include <cstdio>\n#include <vector>\n#include <cmath>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#include \"PhaseAFO.h\"\n#include \"Integrator.h\"\n\nint main(int argc, char **argv)\n{\n  boost::posix_time::ptime run_start(boost::posix_time::microsec_clock::local_time());\n\n  double dt = 0.0001;\n  double save_dt = 0.001;\n\n  double t_init = 0.0;\n  double t_end = 10.0;\n\n  Eigen::Vector2d y_init;\n  y_init << 0.0, 10.0;\n\n  afos::PhaseAFO my_afo;\n  my_afo.initialize(1000.0, 1.);\n  my_afo.input().sine(100.);\n  euler_integration(my_afo, t_init, t_end,y_init,dt, save_dt);\n  Eigen::VectorXd t = my_afo.t();\n  Eigen::MatrixXd y = my_afo.y();\n\n  //save file\n  FILE *save_file = fopen(\"result.txt\",\"w\");\n  for(int i=0; i<t.rows(); ++i)\n    fprintf(save_file, \"%f %f %f\\n\",t(i),y(0,i),y(1,i));\n  fclose(save_file);\n\n  boost::posix_time::ptime run_end(boost::posix_time::microsec_clock::local_time());\n  boost::posix_time::time_duration run_duration = run_end - run_start;\n  double cycle_duration = run_duration.total_microseconds()/1000000.0;\n  printf(\"time taken: %f\\n\",cycle_duration);\n  return 0;\n}\n", "meta": {"hexsha": "e8a325af3aa751daf10e23302b2578ac5ac9a50e", "size": 1097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_phase_afo.cpp", "max_stars_repo_name": "righetti/AFOs", "max_stars_repo_head_hexsha": "79e23f6ef278621e66eb775ff2fb5156eaac1261", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-03-31T06:41:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T05:24:55.000Z", "max_issues_repo_path": "src/test_phase_afo.cpp", "max_issues_repo_name": "righetti/AFOs", "max_issues_repo_head_hexsha": "79e23f6ef278621e66eb775ff2fb5156eaac1261", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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_phase_afo.cpp", "max_forks_repo_name": "righetti/AFOs", "max_forks_repo_head_hexsha": "79e23f6ef278621e66eb775ff2fb5156eaac1261", "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.756097561, "max_line_length": 86, "alphanum_fraction": 0.6882406563, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5154258930423267}}
{"text": "/**\n    @file Project_2.cpp\n\n    @author Terence Henriod\n\n    Project 2: Bayesion Minimum Error Classification\n\n    @brief The driver program for use of a Bayesian Minimum Error Classifier to\n           both classify randomly generated data and detect face (or at least\n           skin-colored) regions in images.\n\n    @version Original Code 1.00 (3/26/2014) - T. Henriod\n\n    UNOFFICIALLY:\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\nCompilation notes:\ng++ -I /home/thenriod/Desktop/cpp_libs/Eigen_lib/ Project_1.cpp\n\n*/\n\n/*==============================================================================\n=======     HEADER FILES     ===================================================\n==============================================================================*/\n#include <cmath>\n#include <iostream>\n\n#include \"bayes_classifier.h\"\n#include \"strict_gaussian_classifier.h\"\n#include \"my_ppm.h\"\n#include <Eigen/Dense>  // -I /home/thenriod/Desktop/cpp_libs/Eigen_lib\n\nusing namespace std;\n\n/*==============================================================================\n=======     USER DEFINED TYPES     =============================================\n==============================================================================*/\ntypedef struct\n{\n  string input_file_name;\n  string output_file_base;\n  string class_one_name;\n  string class_two_name;\n} BayesProblemData;\n\n\ntypedef struct\n{\n  string training_photo;\n  string training_reference;\n  string training_output;\n  string photo_one;\n  string reference_one;\n  string output_one;\n  string photo_two;\n  string reference_two;\n  string output_two;\n} SkinProblemData;\n\n\n/*==============================================================================\n=======     CONSTANTS / MACROS     =============================================\n==============================================================================*/\nconst string SKIN = \"SKIN\";\nconst string NOT_SKIN = \"INANIMATE OBJECT\";\n\n/*==============================================================================\n=======     GLOBAL VARIABLES     ===============================================\n==============================================================================*/\n  // none\n\n/*==============================================================================\n=======     FUNCTION PROTOTYPES     ============================================\n==============================================================================*/\n\nvoid solveBayesClassificationProblem( BayesProblemData& info );\n\nint readData( vector<DataItem>& data, const string& input_file_name );\n\nvoid solveImageProblem( SkinProblemData& info);\n\nvoid trainStrictGaussianClassifiers( StrictGaussianClassifier& classifier_one,\n                                     StrictGaussianClassifier& classifier_two,\n                                     string& photo_file_name,\n                                     string& reference_file_name );\n\nvoid readPpmToDataVectors( vector<DataItem>& rb_picture_data,\n                           vector<DataItem>& cb_cr_picture_data,\n                          string& photo_file_name,\n                          string& reference_file_name );\n\nvoid classifyPhotoPixels( StrictGaussianClassifier& classifier,\n                          vector<DataItem>& data,\n                          string& output_file_name );\n\n/*==============================================================================\n=======     MAIN FUNCTION     ==================================================\n==============================================================================*/\n\n/**\nmain\n\nThe main driver\n\n@param\n\n@return\n\n@pre\n-#\n\n@post\n-#\n\n@code\n@endcode\n*/\n\nint main( int argc, char** argv )\n{\n  // variables\n  BayesProblemData problem_info;\n  SkinProblemData face_detection_info;\n\n  string photo_file_name = \"Training_1.ppm\";\n  string reference_file_name = \"ref1.ppm\";\n  StrictGaussianClassifier skin_finder;\n\n\n\n  // solve problem 1\n  problem_info.input_file_name = \"P1_data.txt\";\n  problem_info.output_file_base = \"P1_solution\";\n  problem_info.class_one_name = \"ONE\";\n  problem_info.class_two_name = \"TWO\";\n  solveBayesClassificationProblem( problem_info );\n\n  // solve problem 2\n  problem_info.input_file_name = \"P2_data.txt\";\n  problem_info.output_file_base = \"P2_solution\";\n  solveBayesClassificationProblem( problem_info );\n\n\n\n\n  // solve image problem\n  face_detection_info.training_photo     = \"Training_1.ppm\";\n  face_detection_info.training_reference = \"ref1.ppm\";\n  face_detection_info.training_output    = \"test_output.txt\";\n  face_detection_info.photo_one          = \"Training_3.ppm\";\n  face_detection_info.reference_one      = \"ref3.ppm\";\n  face_detection_info.output_one         = \"output_1.txt\";\n  face_detection_info.photo_two          = \"Training_6.ppm\";\n  face_detection_info.reference_two      = \"ref6.ppm\";\n  face_detection_info.output_two         = \"output_2.txt\";\n\n  skin_finder.set_class_name( SKIN );\n\n  solveImageProblem( face_detection_info );\n\n\n  // end program\n  return 0;\n}\n\n/*==============================================================================\n=======     FUNCTION IMPLEMENTATIONS     =======================================\n==============================================================================*/\nvoid solveBayesClassificationProblem( BayesProblemData& info )\n{\n  // variables\n  vector<BayesClassifier> classifiers( 2 );\n  vector<DataItem> problem_data;\n\n  // read in the data\n  readData( problem_data, info.input_file_name );\n\n  // set the classifier class names\n  classifiers[0].set_class_name( info.class_one_name );\n  classifiers[1].set_class_name( info.class_two_name );\n\n  // find the means of the training data\n  classifiers[0].set_mean( problem_data );\n  classifiers[1].set_mean( problem_data );\n\n  // find the covariances of the training data\n  classifiers[0].set_covariance( problem_data, classifiers[0].mean_vector() );\n  classifiers[1].set_covariance( problem_data, classifiers[1].mean_vector() );\n\n  // set the prior probabilities\n  classifiers[0].set_prior_probability( 0.5 );\n  classifiers[1].set_prior_probability( 0.5 );\n\n  // perform the classifications with the equal prior probabilities\n  BayesClassifier::performAnalysis( classifiers, problem_data,\n                                    info.output_file_base + \"_part1.txt\" );\n\n  // perform the classifications with the differing priors\n  classifiers[0].set_prior_probability( 0.3 );\n  classifiers[1].set_prior_probability( 0.7 );\n  BayesClassifier::performAnalysis( classifiers, problem_data,\n                                    info.output_file_base + \"_part2.txt\" );\n\n  // no return - void\n}\n\n\nint readData( vector<DataItem>& data, const string& input_file_name )\n{\n  // variables\n  fstream file;\n  DataItem temp;\n  char delimiter;\n\n  // clear file stream object and open the file\n  file.clear();\n  file.open( input_file_name.c_str(), fstream::in );\n\n  // prime the reading loop\n  file >> temp.feature_vector(0) >> delimiter\n       >> temp.feature_vector(1) >> delimiter\n       >> temp.actual_class;\n\n  // continue to read from the file while possible\n  while( file.good() )\n  {\n    // store the recently read data\n    data.push_back( temp );\n\n    // attempt to read more data\n    file >> temp.feature_vector(0) >> delimiter\n         >> temp.feature_vector(1) >> delimiter\n         >> temp.actual_class;\n  }\n\n  // return the data vector by reference\n}\n\n\nvoid solveImageProblem( SkinProblemData& info)\n{\n  // variables\n  StrictGaussianClassifier rb_skin_finder;\n  StrictGaussianClassifier cb_cr_skin_finder;\n  string dummy = \"CbCr_output.txt\";\n\n  vector<DataItem> rb_data;\n  vector<DataItem> cb_cr_data;\n\n  rb_skin_finder.set_class_name( SKIN );\n  cb_cr_skin_finder.set_class_name( SKIN );\n\n  // train the classifier\n  trainStrictGaussianClassifiers( rb_skin_finder, cb_cr_skin_finder,\n                                 info.training_photo,\n                                 info.training_reference );\n\n\n/*\nreadPpmToDataVectors( rb_data, cb_cr_data, info.training_photo, info.training_reference );\n\n\nclassifyPhotoPixels( rb_skin_finder, rb_data, info.training_output );\n\nclassifyPhotoPixels( cb_cr_skin_finder, cb_cr_data, dummy );\n */\n\n\n  // perform classification on the first data set\n  readPpmToDataVectors( rb_data, cb_cr_data, info.photo_one, info.reference_one );\n  classifyPhotoPixels( rb_skin_finder, rb_data, info.output_one );\n  dummy = \"CbCr\";\n  dummy += info.output_one;\n  classifyPhotoPixels( cb_cr_skin_finder, cb_cr_data, dummy );\n\n  // clear the data vectors between runs\n  rb_data.clear();\n  cb_cr_data.clear();\n\n  // perform classification on the second data set\n  readPpmToDataVectors( rb_data, cb_cr_data, info.photo_two, info.reference_two );\n  classifyPhotoPixels( rb_skin_finder, rb_data, info.output_two );\n  dummy = \"CbCr\";\n  dummy += info.output_two;\n  classifyPhotoPixels( cb_cr_skin_finder, cb_cr_data, dummy );\n\n\n  // no return - void\n}\n\n\nvoid trainStrictGaussianClassifiers( StrictGaussianClassifier& classifier_one,\n                                     StrictGaussianClassifier& classifier_two,\n                                     string& photo_file_name,\n                                     string& reference_file_name )\n{\n  // variables\n  vector<DataItem> rb_data;\n  vector<DataItem> cb_cr_data;\n\n  // read in the training data\n  readPpmToDataVectors( rb_data, cb_cr_data, photo_file_name,\n                        reference_file_name );\n\n  // find the training mean\n  classifier_one.set_mean( rb_data );\n  classifier_two.set_mean( cb_cr_data );\n\n  // find the covariance\n  classifier_one.set_covariance( rb_data, classifier_one.mean_vector() );\n  classifier_two.set_covariance( cb_cr_data, classifier_two.mean_vector() );\n\ncout << \"RB Classifier\" << endl;\nclassifier_one.reportClassifierInfo();\n\ncout << \"CbCr Classifier\" << endl;\nclassifier_two.reportClassifierInfo();\n\n  // return the trained classifier by reference\n}\n\n\nvoid readPpmToDataVectors( vector<DataItem>& rb_picture_data,\n                            vector<DataItem>& cb_cr_picture_data,\n                            string& photo_file_name,\n                            string& reference_file_name )\n{\n  // variables\n  PpmImageData photo_image;\n  PpmImageData reference_image;\n  DataItem temp;\n  int i = 0;\n  int j = 0;\n  int k = 0;\n  double color_sum = 0;\n\n  // read in the image file\n  readPpmFile( &photo_image, photo_file_name.c_str() );\n\n  // read in the reference file\n  readPpmFile( &reference_image, reference_file_name.c_str() );\n\n  // visit each row of pixels in the images\n  for( i = 0, k = 0; i < photo_image.height; i++ )\n  {\n    // visit each pixel of the rows\n    for( j = 0; j < photo_image.width; j++, k++ )\n    {\n      // convert the pixel color vector to a two dimensional one\n      color_sum = photo_image.data[i][j].red + photo_image.data[i][j].green +\n                  photo_image.data[i][j].blue;\n      if( color_sum > 0 )\n      {\n        temp.feature_vector( 0 ) = photo_image.data[i][j].red / color_sum;\n        temp.feature_vector( 1 ) = photo_image.data[i][j].green / color_sum;\n      }\n      else  // to not divide by 0\n      {\n        temp.feature_vector( 0 ) = 0;\n        temp.feature_vector( 1 ) = 0;\n      }\n\n      // case: the reference image indicates the pixel in the photo is skin\n      if( (reference_image.data[i][j].red + reference_image.data[i][j].green +\n           reference_image.data[i][j].blue) > 0 )\n      {\n        // tag the data\n        temp.actual_class = SKIN;\n      }\n      // case: the photo pixel is non-skin\n      else\n      {\n        // tag the data\n        temp.actual_class = NOT_SKIN;\n      }\n\n      // add the new item to the vector\n      rb_picture_data.push_back( temp );\n\n      // compute the Cb and Cr values for the alternative\n      temp.feature_vector( 0 ) = ( -0.169 * photo_image.data[i][j].red ) +\n                                 ( -0.332 * photo_image.data[i][j].green ) +\n                                 ( 0.5 * photo_image.data[i][j].blue );\n      temp.feature_vector( 1 ) = ( 0.5 * photo_image.data[i][j].red ) +\n                                 ( -0.419 * photo_image.data[i][j].green ) +\n                                 ( -0.081 * photo_image.data[i][j].blue );\n\n      // add the new item to the new vector\n      cb_cr_picture_data.push_back( temp );\n    }\n  }\n\n  // deconstruct the image structs\n  deconstructPpmImage( &photo_image );\n  deconstructPpmImage( &reference_image );\n\n  // return the data vector by reference\n}\n\n\nvoid classifyPhotoPixels( StrictGaussianClassifier& classifier,\n                          vector<DataItem>& data,\n                          string& output_file_name )\n{\n  // variables\n  vector<double> skin_likelihood;\n  int i = 0;\n  int num_skin = 0;\n  int num_other = 0;\n  int num_correct_skin = 0;\n  int num_correct_other = 0;\n  int false_acceptance = 0;\n  int false_rejection = 0;\n  double threshold = 0;\n  double overall_correct_rate = 0;\n  double skin_correct_rate = 0;\n  double other_correct_rate = 0;\n  double false_acceptance_rate = 0;\n  double false_rejection_rate = 0;\n  fstream file;\n\n  // prepare the file for the output summary\n  file.clear();\n  file.open( output_file_name.c_str(), fstream::out );\n  file << \"Threshold Used, \"\n       << \"Number of items, \"\n       << \"Correct Classifications, \"\n       << \"Correct Classification Rate, \"\n       << \"Number of Skin Items, \"\n       << \"Correct Skin Classifications, \"\n       << \"Correct Skin Classification Rate, \"\n       << \"Number of Other Items, \"\n       << \"Correct Other Classifications, \"\n       << \"Correct Other Classification Rate, \"\n       << \"False Acceptance Rate, \"\n       << \"False Rejection Rate\"<< endl;\n\n  // find the likelihood of each test vector being a skin one\n  for( i = 0; i < data.size(); i++ )\n  {\n     // compute the likelihood that the pixel is skin\n     skin_likelihood.push_back(\n         classifier.getGaussianProbability( data[i].feature_vector ) );\n  }\n\n\n  // perform the classifications at various acceptance thresholds\n  for( threshold = 0.01; threshold < 1.0; threshold += 0.01 )\n  {\n    // set the decision threshold\n    classifier.set_decision_threshold( threshold );\n\n    // reset the counters\n    num_skin = 0;\n    num_other = 0;\n    num_correct_skin = 0;\n    num_correct_other = 0;\n    false_acceptance = 0;\n    false_rejection = 0;\n\n    // for every skin-pixel likelihood\n    for( i = 0; i < data.size(); i++ )\n    {\n       // case: the pixel is likely skin\n       if( skin_likelihood[i] > threshold )\n       {\n          // mark the pixel as skin\n          data[i].classified_as = SKIN;\n\n          // case: the pixel was not correctly classified\n          if( data[i].actual_class != SKIN  )\n          {\n            // count it\n            false_acceptance++;\n          }\n          else\n          {\n             num_correct_skin++;\n          }\n       }\n       // case: the skin pixel is not likely skin\n       else\n       {\n          // mark the pixel as skin\n          data[i].classified_as = NOT_SKIN;\n\n          // case: the pixel was actually skin\n          if( data[i].actual_class == SKIN )\n          {\n            // count it\n            false_rejection++;\n          }\n          else\n          {\n            num_correct_other++;\n          }\n       }\n\n       // case: the pixel was in fact skin\n       if( data[i].actual_class == SKIN )\n       {\n         // count it\n         num_skin++;\n       }\n       else\n       {\n         num_other++;\n       }\n    }\n\n    // compute the summary statistics\n    overall_correct_rate = (double)(num_correct_skin + num_correct_other) /\n                           (double) data.size();\n    skin_correct_rate = (double)((double)num_correct_skin / (double)num_skin);\n    other_correct_rate = (double)((double)num_correct_other /\n                         (double)num_other);\n    false_acceptance_rate = (double) false_acceptance / (double) (data.size() - num_skin);  //false positive rate = false positive / negative\n    false_rejection_rate = (double) false_rejection / (double) num_skin;    // false negative rate = false negative / positive\n\n    // output the result data to the output file\n    file << classifier.decision_threshold() << \", \"\n         << data.size() << \", \"\n         << (num_correct_skin + num_correct_other) << \", \"\n         << overall_correct_rate << \", \"\n         << num_skin << \", \"\n         << num_correct_skin << \", \"\n         << skin_correct_rate << \", \"\n         << num_other << \", \"\n         << num_correct_other << \", \"\n         << other_correct_rate << \", \"\n         << false_acceptance_rate << \", \"\n         << false_rejection_rate\n         << endl;\n  }\n\n  // close the file\n  file.close();\n\n  // no return - void\n}\n\n\n", "meta": {"hexsha": "6c9fdee9e74cad79e96bbac23c32866f42132e17", "size": 17207, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CS479/Project_2/project_2_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_2/project_2_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_2/project_2_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": 30.9478417266, "max_line_length": 141, "alphanum_fraction": 0.5872609984, "num_tokens": 3746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5154258930423267}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <test/unit/math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdLogRisingFactorial, Fvar) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::log_rising_factorial;\n\n  fvar<double> a(4.0, 1.0);\n  fvar<double> x = log_rising_factorial(a, 1.0);\n  EXPECT_FLOAT_EQ(std::log(4.0), x.val_);\n  EXPECT_FLOAT_EQ(0.25, x.d_);\n\n  // finite diff\n  double eps = 1e-6;\n  EXPECT_FLOAT_EQ((stan::math::log_rising_factorial(4.0 + eps, 1.0)\n                   - stan::math::log_rising_factorial(4.0 - eps, 1.0))\n                      / (2 * eps),\n                  x.d_);\n\n  fvar<double> c(-3.0, 2.0);\n\n  EXPECT_THROW(log_rising_factorial(c, 2), std::domain_error);\n  // EXPECT_THROW(log_rising_factorial(2, c), std::domain_error);\n  EXPECT_THROW(log_rising_factorial(c, c), std::domain_error);\n\n  x = log_rising_factorial(a, a);\n  EXPECT_FLOAT_EQ(std::log(840.0), x.val_);\n  EXPECT_FLOAT_EQ((2 * digamma(8) - digamma(4)), x.d_);\n\n  x = log_rising_factorial(5, a);\n  EXPECT_FLOAT_EQ(std::log(1680.0), x.val_);\n  EXPECT_FLOAT_EQ(digamma(9), x.d_);\n\n  // finite diff\n  EXPECT_FLOAT_EQ((stan::math::log_rising_factorial(5.0, 4.0 + eps)\n                   - stan::math::log_rising_factorial(5.0, 4.0 - eps))\n                      / (2 * eps),\n                  x.d_);\n}\n\nTEST(AgradFwdLogRisingFactorial, FvarFvarDouble) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::log_rising_factorial;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 3.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<double> > a = log_rising_factorial(x, y);\n\n  EXPECT_FLOAT_EQ(std::log(120.0), a.val_.val_);\n  EXPECT_FLOAT_EQ(0.61666667, a.val_.d_);\n  EXPECT_FLOAT_EQ(1.8727844, a.d_.val_);\n  EXPECT_FLOAT_EQ(0.15354517, a.d_.d_);\n}\n\nstruct log_rising_factorial_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 log_rising_factorial(arg1, arg2);\n  }\n};\n\nTEST(AgradFwdLogRisingFactorial, nan) {\n  log_rising_factorial_fun log_rising_factorial_;\n  test_nan_fwd(log_rising_factorial_, 3.0, 5.0, false);\n}\n", "meta": {"hexsha": "2eb6cf45f1bf90b3016684ea7b4b14efe604fb88", "size": 2293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/fwd/scal/fun/log_rising_factorial_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/fwd/scal/fun/log_rising_factorial_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/fwd/scal/fun/log_rising_factorial_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": 29.7792207792, "max_line_length": 76, "alphanum_fraction": 0.6611426079, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5154258884998082}}
{"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_SQRT_1O_5_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_SQRT_1O_5_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate value \\f$ \\sqrt{\\frac15}\\f$\n\n    @par Semantic:\n\n    @code\n    T r = Sqrt_1o_5<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = sqrt(T(1)/T(5));\n    @endcode\n\n\n    @return The Sqrt_1o_5 constant for the proper type\n  **/\n  template<typename T> T Sqrt_1o_5();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant sqrt_1o_5.\n\n      @return The Sqrt_1o_5 constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::sqrt_1o_5_> sqrt_1o_5 = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/sqrt_1o_5.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": "c82622a419f6cca165fa31dd9bdf4c3dcccf3f26", "size": 1339, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/sqrt_1o_5.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/sqrt_1o_5.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/sqrt_1o_5.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": 23.4912280702, "max_line_length": 100, "alphanum_fraction": 0.5929798357, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721305, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5154159796572295}}
{"text": "/*\n * Copyright 2015 Christoph Jud (christoph.jud@unibas.ch)\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 <fstream>\n#include <iostream>\n#include <iomanip>\n\n//#include <boost/filesystem.hpp>\n//namespace fs = boost::filesystem;\n\n#include <Eigen/SVD>\n#include <Eigen/Eigenvalues>\n\n#include \"GaussianProcess.h\"\n//#include \"KernelFactory.h\"\n#include \"MatrixIO.h\"\n#include \"LAPACKUtils.h\"\n\nnamespace gpr{\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::AddSample(const typename GaussianProcess<TScalarType>::VectorType &x,\n                                             const typename GaussianProcess<TScalarType>::VectorType &y){\n    if(m_SampleVectors.size() == 0){ // first call of AddSample defines dimensionality of input space\n        m_InputDimension = x.size();\n    }\n    if(m_LabelVectors.size() == 0){ // first call of AddSample defines dimensionality of output space\n        m_OutputDimension = y.size();\n    }\n\n    CheckInputDimension(x, \"GaussianProcess::AddSample: \");\n    CheckOutputDimension(y, \"GaussianProcess::AddSample: \");\n\n    m_SampleVectors.push_back(x);\n    m_LabelVectors.push_back(y);\n    m_Initialized = false;\n}\n\ntemplate< class TScalarType >\ntypename GaussianProcess<TScalarType>::VectorType\nGaussianProcess<TScalarType>::Predict(const typename GaussianProcess<TScalarType>::VectorType &x){\n    Initialize();\n    CheckInputDimension(x, \"GaussianProcess::Predict: \");\n    VectorType Kx;\n    ComputeKernelVector(x, Kx);\n    return (Kx.adjoint() * m_RegressionVectors).adjoint();\n}\n\ntemplate< class TScalarType >\ntypename GaussianProcess<TScalarType>::VectorType\nGaussianProcess<TScalarType>::PredictDerivative(const typename GaussianProcess<TScalarType>::VectorType &x,\n                                                           typename GaussianProcess<TScalarType>::MatrixType &D){\n    Initialize();\n    CheckInputDimension(x, \"GaussianProcess::PredictDerivative: \");\n    VectorType Kx;\n    ComputeKernelVector(x, Kx);\n    MatrixType X;\n    ComputeDifferenceMatrix(x, X);\n\n    unsigned d = m_InputDimension;\n    unsigned m = m_OutputDimension;\n    D.resize(m_InputDimension, m_OutputDimension);\n    for(unsigned i=0; i<m_OutputDimension; i++){\n        D.col(i) = -X.transpose() * Kx.cwiseProduct(m_RegressionVectors.col(i));\n    }\n    return (Kx.adjoint() * m_RegressionVectors).adjoint(); // return point prediction\n}\n\ntemplate< class TScalarType >\nTScalarType\nGaussianProcess<TScalarType>::operator()(const typename GaussianProcess<TScalarType>::VectorType & x,\n                                         const typename GaussianProcess<TScalarType>::VectorType & y){\n    Initialize();\n    CheckInputDimension(x, \"GaussianProcess::(): \");\n    CheckInputDimension(y, \"GaussianProcess::(): \");\n    VectorType Kx;\n    ComputeKernelVector(x, Kx);\n    VectorType Ky;\n    ComputeKernelVector(y, Ky);\n\n    if(m_CoreMatrix.diagonalSize() == 0){\n        ComputeCoreMatrix(m_CoreMatrix);\n    }\n    return (*m_Kernel)(x, y) - Kx.adjoint() * m_CoreMatrix * Ky;\n}\n\ntemplate< class TScalarType >\nTScalarType\nGaussianProcess<TScalarType>::GetCredibleInterval(const typename GaussianProcess<TScalarType>::VectorType& x){\n    Initialize();\n    CheckInputDimension(x, \"GaussianProcess::GetCredibleIntervall: \");\n\n    // due to nummerical instabilities of the inversion of the kernel matrix\n    // gp(x,x) might return negative values\n    // therefore the maximum of zero and c is taken.\n    TScalarType c = (*this)(x, x);\n    if(debug && c<0) std::cout << \"GaussianProcess::GetCredibleIntervall: prediction is instable. gp(x,x) = \" << c << \".\" << std::endl;\n    c = 2*std::sqrt(std::max(static_cast<TScalarType>(0.0),c));\n    return c;\n}\n\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::Initialize(){\n    if(m_Initialized){\n        return;\n    }\n    if(!(m_SampleVectors.size() > 0)){\n        throw std::string(\"GaussianProcess::Initialize: no input samples defined during initialization\");\n    }\n    if(!(m_LabelVectors.size() > 0)){\n        throw std::string(\"GaussianProcess::Initialize: no ouput labels defined during initialization\");\n    }\n    ComputeRegressionVectors();\n    m_Initialized = true;\n}\n\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::Save(std::string prefix){\n    if(!m_Initialized){\n        throw std::string(\"GaussianProcess::Save: gaussian process is not initialized.\");\n    }\n\n    if(debug){\n        std::cout << \"GaussianProcess::Save: writing gaussian process: \" << std::endl;\n        std::cout << \"\\t \" << prefix+\"-RegressionVectors.txt\" << std::endl;\n        std::cout << \"\\t \" << prefix+\"-CoreMatrix.txt\" << std::endl;\n        std::cout << \"\\t \" << prefix+\"-SampleVectors.txt\" << std::endl;\n        std::cout << \"\\t \" << prefix+\"-LabelVectors.txt\" << std::endl;\n        std::cout << \"\\t \" << prefix+\"-ParameterFile.txt\" << std::endl;\n    }\n\n    // save regression vectors\n    WriteMatrix<MatrixType>(m_RegressionVectors, prefix+\"-RegressionVectors.txt\");\n\n    // save regression vectors\n    if(m_EfficientStorage) m_CoreMatrix.setZero(0,0);\n    WriteMatrix<MatrixType>(m_CoreMatrix, prefix+\"-CoreMatrix.txt\");\n\n    // save sample vectors\n    MatrixType X = MatrixType::Zero(m_SampleVectors[0].size(), m_SampleVectors.size());\n    for(unsigned i=0; i<m_SampleVectors.size(); i++){\n        X.block(0,i,m_SampleVectors[0].size(),1) = m_SampleVectors[i];\n    }\n    WriteMatrix<MatrixType>(X, prefix+\"-SampleVectors.txt\");\n\n    // save label vectors\n    MatrixType Y = MatrixType::Zero(m_LabelVectors[0].size(), m_LabelVectors.size());\n    for(unsigned i=0; i<m_LabelVectors.size(); i++){\n        Y.block(0,i,m_LabelVectors[0].size(),1) = m_LabelVectors[i];\n    }\n    WriteMatrix<MatrixType>(Y, prefix+\"-LabelVectors.txt\");\n\n    // save parameters\n    // KernelType, #KernelParameters, KernelParameters, noise, InputDimension, OutputDimension\n    std::ofstream parameter_outfile;\n    parameter_outfile.open(std::string(prefix+\"-ParameterFile.txt\").c_str());\n\n    parameter_outfile << m_Sigma << \" \" << m_InputDimension << \" \" << m_OutputDimension << \" \" << m_EfficientStorage << \" \" << debug << \" \";\n\n    parameter_outfile << std::setprecision(std::numeric_limits<TScalarType>::digits10 +1);\n    parameter_outfile << m_Kernel->ToString();\n\n    parameter_outfile.close();\n}\n\n\n\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::ToString() const{\n    std::cout << \"---------------------------------------\" << std::endl;\n    std::cout << \"Gaussian Process\" << std::endl;\n    std::cout << \" - initialized:\\t\\t\" << m_Initialized << std::endl;\n    std::cout << \" - # samples:\\t\\t\" << m_SampleVectors.size() << std::endl;\n    std::cout << \" - # labels:\\t\\t\" << m_LabelVectors.size() << std::endl;\n    std::cout << \" - noise:\\t\\t\" << m_Sigma << std::endl;\n    std::cout << \" - input dimension:\\t\" << m_InputDimension << std::endl;\n    std::cout << \" - output dimension:\\t\" << m_OutputDimension << std::endl;\n    std::cout << std::endl;\n    std::cout << \" - Kernel:\" << std::endl;\n    std::cout << \"       - Type:\\t\\t\" << m_Kernel->ToString() << std::endl;\n    std::cout << \"       - Parameter:\\t\";\n    for(unsigned i=0; i<m_Kernel->GetStringParameters().size(); i++){\n        std::cout << m_Kernel->GetStringParameters()[i] << \", \";\n    }\n    std::cout << std::endl;\n    std::cout << \"---------------------------------------\" << std::endl;\n}\n\ntemplate< class TScalarType >\nbool GaussianProcess<TScalarType>::operator ==(const GaussianProcess<TScalarType> &b) const{\n    if(this->debug) std::cout << \"GaussianProcess::comparison: \" << std::flush;\n\n    if((this->m_RegressionVectors - b.m_RegressionVectors).norm() > 0){\n        if(this->debug) std::cout << \"regression vectors not equal.\" << std::endl;\n        return false;\n    }\n\n    if(this->m_CoreMatrix.diagonalSize() != b.m_CoreMatrix.diagonalSize()){\n        if(this->debug) std::cout << \"core matrices not equal.\"  << std::endl;\n        return false;\n    }\n    else{\n        if(this->debug && (this->m_CoreMatrix - b.m_CoreMatrix).norm() > 0) std::cout << \"core matrices error is \" << (this->m_CoreMatrix - b.m_CoreMatrix).norm() << std::endl;\n    }\n\n\n    if(this->m_SampleVectors.size() != b.m_SampleVectors.size()){\n        if(this->debug) std::cout << \"number of sample vectors not equal.\" << std::endl;\n        return false;\n    }\n    for(unsigned i=0; i<this->m_SampleVectors.size(); i++){\n        if((this->m_SampleVectors[i] - b.m_SampleVectors[i]).norm()>0){\n            if(this->debug) std::cout << \"sample vectors not equal.\" << std::endl;\n            return false;\n        }\n    }\n\n    if(this->m_LabelVectors.size() != b.m_LabelVectors.size()){\n        if(this->debug) std::cout << \"number of label vectors not equal.\" << std::endl;\n        return false;\n    }\n    for(unsigned i=0; i<this->m_LabelVectors.size(); i++){\n        if((this->m_LabelVectors[i] - b.m_LabelVectors[i]).norm()>0) {\n            if(this->debug) std::cout << \"label vectors not equal.\" << std::endl;\n            return false;\n        }\n    }\n    if(*this->m_Kernel.get() != *b.m_Kernel.get()){\n        if(this->debug) std::cout << \"kernel not equal.\" << std::endl;\n        return false;\n    }\n    if(this->m_Sigma != b.m_Sigma){\n        if(this->debug) std::cout << \"sigma not equal.\" << std::endl;\n        return false;\n    }\n    if(this->m_Initialized != b.m_Initialized){\n        if(this->debug) std::cout << \"initialization state not equal.\" << std::endl;\n        return false;\n    }\n    if(this->m_InputDimension != b.m_InputDimension){\n        if(this->debug) std::cout << \"input dimension not equal.\" << std::endl;\n        return false;\n    }\n    if(this->m_OutputDimension != b.m_OutputDimension){\n        if(this->debug) std::cout << \"output dimension not equal.\" << std::endl;\n        return false;\n    }\n    if(this->m_EfficientStorage!= b.m_EfficientStorage){\n        if(this->debug) std::cout << \"efficient storage setting not equal.\" << std::endl;\n        return false;\n    }\n    if(this->debug != b.debug){\n        if(this->debug) std::cout << \"debug state not equal.\" << std::endl;\n        return false;\n    }\n    if(this->debug) std::cout << \"is equal!\" << std::endl;\n    return true;\n}\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::ComputeKernelMatrix(typename GaussianProcess<TScalarType>::MatrixType &M) const{\n    if(debug){\n        std::cout << \"GaussianProcess::ComputeKernelMatrix: building kernel matrix... \";\n        std::cout.flush();\n    }\n\n    ComputeKernelMatrixInternal(M, m_SampleVectors);\n\n    if(debug) std::cout << \"[done]\" << std::endl;\n}\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::AddNoiseToKernelMatrix(typename GaussianProcess<TScalarType>::MatrixType &M) const{\n    // add noise variance to diagonal\n    if(M.rows() != M.cols()) throw std::string(\"GaussianProcess::AddNoiseToKernelMatrix: square matrix required.\");\n    for(unsigned i=0; i<M.rows(); i++){\n        M(i,i) += m_Sigma*m_Sigma;\n    }\n}\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::ComputeKernelMatrixInternal(typename GaussianProcess<TScalarType>::MatrixType &M,\n                                                               const typename GaussianProcess<TScalarType>::VectorListType& samples) const{\n    unsigned n = samples.size();\n    M.resize(n,n);\n\n#pragma omp parallel for\n    for(unsigned i=0; i<n; i++){\n        for(unsigned j=i; j<n; j++){\n            TScalarType v = (*m_Kernel)(samples[i],samples[j]);\n            M(i,j) = v;\n            M(j,i) = v;\n        }\n    }\n\n    // check if matrix entries are finite\n    if(!((M - M).array() == (M - M).array()).all()){\n        throw std::string(\"GaussianProcess::ComputeKernelMatrixInternal: kernel matrix contains entries which are not finite.\");\n    }\n}\n\n\ntemplate< class TScalarType >\nTScalarType GaussianProcess<TScalarType>::ComputeKernelMatrixTrace() const{\n    if(debug){\n        std::cout << \"GaussianProcess::ComputeKernelMatrixTrace: sum up diagonal elements of kernel matrix... \";\n        std::cout.flush();\n    }\n\n    TScalarType trace = ComputeKernelMatrixTraceInternal(m_SampleVectors);\n\n    if(debug) std::cout << \"[done]\" << std::endl;\n\n    return trace;\n}\n\ntemplate< class TScalarType >\nTScalarType GaussianProcess<TScalarType>::ComputeKernelMatrixTraceInternal(const typename GaussianProcess<TScalarType>::VectorListType& samples) const{\n    unsigned n = samples.size();\n    TScalarType trace = 0;\n\n    for(unsigned i=0; i<n; i++){\n            trace += (*m_Kernel)(samples[i],samples[i]);\n    }\n    return trace;\n}\n\ntemplate< class TScalarType >\ntypename GaussianProcess<TScalarType>::VectorType\nGaussianProcess<TScalarType>::ComputeDerivativeKernelMatrixTrace() const{\n    if(debug){\n        std::cout << \"GaussianProcess::ComputeDerivativeKernelMatrixTrace: sum up diagonal elements of derivative kernel matrix... \";\n        std::cout.flush();\n    }\n\n    typename GaussianProcess<TScalarType>::VectorType trace = ComputeDerivativeKernelMatrixTraceInternal(m_SampleVectors);\n\n    if(debug) std::cout << \"[done]\" << std::endl;\n\n    return trace;\n}\n\ntemplate< class TScalarType >\ntypename GaussianProcess<TScalarType>::VectorType\nGaussianProcess<TScalarType>::ComputeDerivativeKernelMatrixTraceInternal(const typename GaussianProcess<TScalarType>::VectorListType& samples) const{\n    typedef typename GaussianProcess<TScalarType>::VectorType VectorType;\n    unsigned num_params = m_Kernel->GetNumberOfParameters();\n    VectorType trace = VectorType::Zero(num_params);\n\n    unsigned n = samples.size();\n    for(unsigned i=0; i<n; i++){\n            trace += m_Kernel->GetDerivative(samples[i], samples[i]);\n    }\n    return trace;\n}\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::ComputeDerivativeKernelMatrix(typename GaussianProcess<TScalarType>::MatrixType &M) const{\n    if(debug){\n        std::cout << \"GaussianProcess::ComputeDerivativeKernelMatrix: building kernel matrix... \";\n        std::cout.flush();\n    }\n\n    ComputeDerivativeKernelMatrixInternal(M, m_SampleVectors);\n\n    if(debug) std::cout << \"[done]\" << std::endl;\n}\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::ComputeDerivativeKernelMatrixInternal(typename GaussianProcess<TScalarType>::MatrixType &M,\n                                                                         const typename GaussianProcess<TScalarType>::VectorListType& samples) const{\n    unsigned num_params = m_Kernel->GetNumberOfParameters();\n\n    unsigned n = samples.size();\n    M.resize(n*num_params,n);\n\n#pragma omp parallel for\n    for(unsigned i=0; i<n; i++){\n        for(unsigned j=i; j<n; j++){\n            typename GaussianProcess<TScalarType>::VectorType v;\n            v = m_Kernel->GetDerivative(samples[i], samples[j]);\n\n            if(v.rows() != num_params) throw std::string(\"GaussianProcess::ComputeDerivativeKernelMatrixInternal: dimension missmatch in derivative.\");\n            for(unsigned p=0; p<num_params; p++){\n\n                //if(i+p*n >= M.rows() || j+p*n >= M.rows())  throw std::string(\"GaussianProcess::ComputeDerivativeKernelMatrix: dimension missmatch in derivative.\");\n\n                M(i + p*n, j) = v[p];\n                M(j + p*n, i) = v[p];\n            }\n        }\n    }\n}\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::ComputeCoreMatrix(typename GaussianProcess<TScalarType>::MatrixType &C) const{\n    MatrixType K;\n    ComputeKernelMatrix(K);\n\n    // add noise variance to diagonal\n    AddNoiseToKernelMatrix(K);\n\n    C = InvertKernelMatrix(K, m_InvMethod);\n\n    if(debug){\n        std::cout << \"GaussianProcess::ComputeCoreMatrix: inversion error: \" << (K*C - MatrixType::Identity(K.rows(),K.cols())).norm() << std::endl;\n    }\n}\n\ntemplate< class TScalarType >\ntypename GaussianProcess<TScalarType>::HighPrecisionType GaussianProcess<TScalarType>::ComputeCoreMatrixWithDeterminant(typename GaussianProcess<TScalarType>::MatrixType &C) const{\n    typedef typename GaussianProcess<TScalarType>::HighPrecisionType HighPrecisionType;\n    MatrixType K;\n    ComputeKernelMatrix(K);\n\n    // add noise variance to diagonal\n    AddNoiseToKernelMatrix(K);\n\n    C = InvertKernelMatrix(K, m_InvMethod);\n\n    if(debug){\n        std::cout << \"GaussianProcess::ComputeCoreMatrix: inversion error: \" << (K*C - MatrixType::Identity(K.rows(),K.cols())).norm() << std::endl;\n        std::cout << \"GaussianProcess::ComputeCoreMatrix: determinant of K: \" << K.template cast<HighPrecisionType>().determinant() << std::endl;\n    }\n    return K.template cast<HighPrecisionType>().determinant();\n}\n\ntemplate< class TScalarType >\ntypename GaussianProcess<TScalarType>::MatrixType GaussianProcess<TScalarType>::InvertKernelMatrix(const typename GaussianProcess<TScalarType>::MatrixType &K,\n                                                      typename GaussianProcess<TScalarType>::InversionMethod inv_method,\n                                                                                                   bool stable) const{\n    // compute core matrix\n    if(debug){\n        std::cout << \"GaussianProcess::InvertKernelMatrix: inverting kernel matrix... \";\n        std::cout.flush();\n    }\n\n    typename GaussianProcess<TScalarType>::MatrixType core;\n\n    switch(inv_method){\n    // standard method: fast but not that accurate\n    // Uses the LU decomposition with full pivoting for the inversion\n    case FullPivotLU:{\n        if(debug) std::cout << \" (inversion method: FullPivotLU) \" << std::flush;\n        try{\n            if(stable){\n                core = K.inverse();\n            }\n            else{\n                if(debug) std::cout << \" (using lapack) \" << std::flush;\n                core = lapack::lu_invert<TScalarType>(K);\n            }\n        }\n        catch(lapack::LAPACKException& e){\n            core = K.inverse();\n        }\n    }\n    break;\n\n    // very accurate and very slow method, use it for small problems\n    // Uses the two-sided Jacobi SVD decomposition\n    case JacobiSVD:{\n        if(debug) std::cout << \" (inversion method: JacobiSVD) \" << std::flush;\n        Eigen::JacobiSVD<MatrixType> jacobisvd(K, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        if((jacobisvd.singularValues().real().array() < 0).any() && debug){\n            std::cout << \"GaussianProcess::InvertKernelMatrix: warning: there are negative eigenvalues.\";\n            std::cout.flush();\n        }\n        core = jacobisvd.matrixV() * VectorType(1/jacobisvd.singularValues().array()).asDiagonal() * jacobisvd.matrixU().transpose();\n    }\n    break;\n\n    // accurate method and faster than Jacobi SVD.\n    // Uses the bidiagonal divide and conquer SVD\n    case BDCSVD:{\n        if(debug) std::cout << \" (inversion method: BDCSVD) \" << std::flush;\n#ifdef EIGEN_BDCSVD_H\n        Eigen::BDCSVD<MatrixType> bdcsvd(K, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        if((bdcsvd.singularValues().real().array() < 0).any() && debug){\n            std::cout << \"GaussianProcess::InvertKernelMatrix: warning: there are negative eigenvalues.\";\n            std::cout.flush();\n        }\n        core = bdcsvd.matrixV() * VectorType(1/bdcsvd.singularValues().array()).asDiagonal() * bdcsvd.matrixU().transpose();\n#else\n        // this is checked, since BDCSVD is currently not in the newest release\n        throw std::string(\"GaussianProcess::InvertKernelMatrix: BDCSVD is not supported by the provided Eigen library.\");\n#endif\n\n    }\n    break;\n\n    // faster than the SVD method but less stable\n    // computes the eigenvalues/eigenvectors of selfadjoint matrices\n    case SelfAdjointEigenSolver:{\n        if(debug) std::cout << \" (inversion method: SelfAdjointEigenSolver) \" << std::flush;\n        try{\n            core = lapack::chol_invert<TScalarType>(K);\n        }\n        catch(lapack::LAPACKException& e){\n            Eigen::SelfAdjointEigenSolver<MatrixType> es;\n            es.compute(K);\n            VectorType eigenValues = es.eigenvalues().reverse();\n            MatrixType eigenVectors = es.eigenvectors().rowwise().reverse();\n            if((eigenValues.real().array() < 0).any() && debug){\n                std::cout << \"GaussianProcess::InvertKernelMatrix: warning: there are negative eigenvalues.\";\n                std::cout.flush();\n            }\n            core = eigenVectors * VectorType(1/eigenValues.array()).asDiagonal() * eigenVectors.transpose();\n        }\n    }\n    break;\n    }\n\n    if(debug) std::cout << \"[done]\" << std::endl;\n    return core;\n}\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::ComputeLabelMatrix(typename GaussianProcess<TScalarType>::MatrixType &Y) const{\n    ComputeLabelMatrixInternal(Y, m_LabelVectors);\n}\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::ComputeLabelMatrixInternal(typename GaussianProcess<TScalarType>::MatrixType &Y,\n                                                              const typename GaussianProcess<TScalarType>::VectorListType& labels) const{\n    unsigned n = labels.size();\n    if(!(n > 0)){\n        throw std::string(\"GaussianProcess::ComputeLabelMatrixInternal: no ouput labels defined.\");\n    }\n    unsigned d = labels[0].size();\n    Y.resize(n,d);\n\n#pragma omp parallel for\n    for(unsigned i=0; i<n; i++){\n        Y.block(i,0,1,d) = labels[i].adjoint();\n    }\n}\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::ComputeRegressionVectors(){\n\n    // Computation of kernel matrix\n    if(debug){\n        std::cout << \"GaussianProcess::ComputeRegressionVectors: calculating regression vectors... \" << std::endl;\n    }\n\n    // compute the core matrix which is inv(K + sigma2 I)\n    // This is a separate function call because it is also used if the core matrix\n    // is not stored due to the efficient storage setting\n    ComputeCoreMatrix(m_CoreMatrix);\n\n    // calculate label matrix\n    // TODO: if a mean support is implemented, the mean has to be subtracted from the labels!\n    MatrixType Y;\n    ComputeLabelMatrix(Y);\n\n\n    // calculate regression vectors\n    m_RegressionVectors = m_CoreMatrix * Y ; // inv(K + sigma2)*Y\n\n    // deleting core matrix if the storage has to be handled efficiently\n    // - it is not used for regression\n    // - but it is needed to compute the credible interval\n    if(m_EfficientStorage){\n        m_CoreMatrix.setZero(0,0);\n    }\n    if(debug){\n        std::cout << \"GaussianProcess::ComputeRegressionVectors: calculating regression vectors [done]\" << std::endl;\n    }\n}\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::ComputeKernelVector(const typename GaussianProcess<TScalarType>::VectorType &x,\n                                                       typename GaussianProcess<TScalarType>::VectorType &Kx) const{\n    if(!m_Initialized){\n        throw std::string(\"GaussianProcess::ComputeKernelVectorInternal: gaussian process is not initialized.\");\n    }\n    ComputeKernelVectorInternal(x, Kx, m_SampleVectors);\n}\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::ComputeKernelVectorInternal(const typename GaussianProcess<TScalarType>::VectorType &x,\n                                                               typename GaussianProcess<TScalarType>::VectorType &Kx,\n                                                               const typename GaussianProcess<TScalarType>::VectorListType& samples) const{\n    Kx.resize(samples.size());\n\n#pragma omp parallel for\n    for(unsigned i=0; i<Kx.size(); i++){\n        Kx(i) = (*m_Kernel)(x, samples[i]);\n    }\n}\n\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::ComputeDifferenceMatrix(const typename GaussianProcess<TScalarType>::VectorType &x,\n                                                           typename GaussianProcess<TScalarType>::MatrixType &X) const{\n    unsigned n = m_SampleVectors.size();\n    unsigned d = x.size();\n    X.resize(n,d);\n\n    for(unsigned i=0; i<n; i++){\n        X.block(i,0,1,d) = (x - m_SampleVectors[i]).adjoint();\n    }\n}\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::CheckInputDimension(const typename GaussianProcess<TScalarType>::VectorType &x, std::string msg_prefix) const{\n    if(x.size()!=m_InputDimension){\n        std::stringstream error_msg;\n        error_msg << msg_prefix << \"dimension of input vector (\"<< x.size() << \") does not correspond to the input dimension (\" << m_InputDimension << \").\";\n        throw std::string(error_msg.str());\n    }\n}\n\ntemplate< class TScalarType >\nvoid GaussianProcess<TScalarType>::CheckOutputDimension(const typename GaussianProcess<TScalarType>::VectorType &y, std::string msg_prefix) const{\n    if(y.size()!=m_OutputDimension){\n        std::stringstream error_msg;\n        error_msg << msg_prefix << \"dimension of output vector (\"<< y.size() << \") does not correspond to the output dimension (\" << m_OutputDimension << \").\";\n        throw std::string(error_msg.str());\n    }\n}\n\n\n}\n\ntemplate class gpr::GaussianProcess<float>;\ntemplate class gpr::GaussianProcess<double>;\n", "meta": {"hexsha": "a5283e1f03967ebe1b9f9105a1512d9c7cde935c", "size": 25365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CPP/GPR/lib/GaussianProcess.cpp", "max_stars_repo_name": "winie-the-pooh/LA-MCTS-in-CPP", "max_stars_repo_head_hexsha": "75cadc0b283108ac6106b2e12e42e9b4058c1c52", "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/GPR/lib/GaussianProcess.cpp", "max_issues_repo_name": "winie-the-pooh/LA-MCTS-in-CPP", "max_issues_repo_head_hexsha": "75cadc0b283108ac6106b2e12e42e9b4058c1c52", "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/GPR/lib/GaussianProcess.cpp", "max_forks_repo_name": "winie-the-pooh/LA-MCTS-in-CPP", "max_forks_repo_head_hexsha": "75cadc0b283108ac6106b2e12e42e9b4058c1c52", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2647058824, "max_line_length": 180, "alphanum_fraction": 0.6476246797, "num_tokens": 6081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5154159693782452}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Polygon_mesh_processing/intersection.h>\n\n#ifdef USE_SURFACE_MESH\n#include \"Kernel_type.h\"\n#include \"Scene_surface_mesh_item.h\"\n#else\n#include \"Scene_polyhedron_item.h\"\n#include \"Polyhedron_type.h\"\n#endif\n#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>\n\n#include \"Scene_polylines_item.h\"\n\n#include <boost/foreach.hpp>\n\n#include <QString>\n#include <QAction>\n#include <QMenu>\n#include <QMainWindow>\n#include <QApplication>\n#include <QTime>\n#include <QMessageBox>\n\n#ifdef USE_SURFACE_MESH\ntypedef Scene_surface_mesh_item Scene_face_graph_item;\n#else\ntypedef Scene_polyhedron_item Scene_face_graph_item;\n#endif\n\n\nusing namespace CGAL::Three;\nnamespace PMP = CGAL::Polygon_mesh_processing;\n\nclass Polyhedron_demo_intersection_plugin :\n  public QObject,\n  public Polyhedron_demo_plugin_interface\n{\n  Q_OBJECT\n  Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)\n  Q_PLUGIN_METADATA(IID \"com.geometryfactory.PolyhedronDemo.PluginInterface/1.0\")\n\npublic:\n\n  bool applicable(QAction*) const {\n    return scene->selectionIndices().size() == 2 &&\n      qobject_cast<Scene_face_graph_item*>(scene->item(scene->selectionIndices().first())) &&\n      qobject_cast<Scene_face_graph_item*>(scene->item(scene->selectionIndices().last()));\n  }\n\n  QList<QAction*> actions() const {\n    return QList<QAction*>() << actionPolyhedronIntersection_3;\n  }\n\n  void init(QMainWindow* mw, CGAL::Three::Scene_interface* scene_interface, Messages_interface*) {\n    this->scene = scene_interface;\n    actionPolyhedronIntersection_3 = new QAction(\"Surface Intersection\", mw);\n    actionPolyhedronIntersection_3->setProperty(\"subMenuName\", \"Polygon Mesh Processing\");\n    if(actionPolyhedronIntersection_3) {\n      connect(actionPolyhedronIntersection_3, SIGNAL(triggered()),\n              this, SLOT(intersection()));\n    }\n  }\n\nprivate:\n\n  QAction*  actionPolyhedronIntersection_3;\n  Scene_interface *scene;\n\npublic Q_SLOTS:\n  void intersection();\n\n}; // end class Polyhedron_demo_intersection_plugin\n\nvoid Polyhedron_demo_intersection_plugin::intersection()\n{\n  Scene_face_graph_item* itemA = NULL;\n  Q_FOREACH(CGAL::Three::Scene_interface::Item_id index, scene->selectionIndices())\n  {\n    Scene_face_graph_item* itemB =\n      qobject_cast<Scene_face_graph_item*>(scene->item(index));\n\n    if(itemB)\n    {\n      if (itemA==NULL)\n      {\n        itemA = itemB;\n        continue;\n      }\n\n      QApplication::setOverrideCursor(Qt::WaitCursor);\n\n      Scene_polylines_item* new_item = new Scene_polylines_item();\n     // perform Boolean operation\n      QTime time;\n      time.start();\n\n      try{\n        PMP::surface_intersection(*itemA->polyhedron(),\n                                  *itemB->polyhedron(),\n                                  std::back_inserter(new_item->polylines),\n                                  true);\n      }\n      catch(CGAL::Corefinement::Self_intersection_exception)\n      {\n        QMessageBox::warning((QWidget*)NULL,\n          tr(\"Self-intersections Found\"),\n          tr(\"Some self-intersections were found amongst intersecting facets\"));\n        delete new_item;\n        QApplication::restoreOverrideCursor();\n        return;\n      }\n\n      QString name = tr(\"%1 intersection %2\");\n\n      new_item->setName(name.arg(itemA->name(), itemB->name()));\n      std::cout << \"ok (\" << time.elapsed() << \" ms)\" << std::endl;\n\n      if (new_item->polylines.empty())\n        delete new_item;\n      else{\n        new_item->setColor(Qt::green);\n        new_item->setRenderingMode(Wireframe);\n        scene->addItem(new_item);\n        new_item->invalidateOpenGLBuffers();\n      }\n\n      QApplication::restoreOverrideCursor();\n    }\n  }\n}\n\n#include \"Surface_intersection_plugin.moc\"\n", "meta": {"hexsha": "c77cd9535b86200d149157ad7f66f45be3338d96", "size": 3763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Plugins/PMP/Surface_intersection_plugin.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/demo/Polyhedron/Plugins/PMP/Surface_intersection_plugin.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/demo/Polyhedron/Plugins/PMP/Surface_intersection_plugin.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 28.0820895522, "max_line_length": 98, "alphanum_fraction": 0.6935955355, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5154159624531797}}
{"text": "// Andrew Naplavkov\n\n#ifndef BARK_GRID_HPP\n#define BARK_GRID_HPP\n\n#include <bark/geometry/geometry_ops.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/sum_kahan.hpp>\n#include <boost/multi_array.hpp>\n\nnamespace bark {\n\n/// Contiguous XY-coordinates container\nclass grid {\npublic:\n    using value_type = double;\n\n    grid(const geometry::box& ext, size_t rows, size_t cols)\n        : data_{boost::extents[rows][cols][2]}\n    {\n        if (rows < 2 || cols < 2)\n            std::fill(begin(), end(), NAN);\n        else {\n            auto dx = geometry::width(ext) / (cols - 1);\n            auto dy = geometry::height(ext) / (rows - 1);\n            auto min_x = geometry::left(ext);\n            auto min_y = geometry::bottom(ext);\n            kahan_accumulator acc_y(min_y);\n            for (size_t row = 0; row < rows; ++row, acc_y(dy)) {\n                kahan_accumulator acc_x(min_x);\n                for (size_t col = 0; col < cols; ++col, acc_x(dx)) {\n                    x(row, col) = boost::accumulators::sum_kahan(acc_x);\n                    y(row, col) = boost::accumulators::sum_kahan(acc_y);\n                }\n            }\n        }\n    }\n\n    size_t rows() const { return data_.shape()[0]; }\n    size_t cols() const { return data_.shape()[1]; }\n    value_type* begin() { return data_.data(); }\n    value_type* end() { return data_.data() + data_.num_elements(); }\n    value_type& x(size_t row, size_t col) { return data_[row][col][0]; }\n    value_type& y(size_t row, size_t col) { return data_[row][col][1]; }\n\nprivate:\n    using sequence_type = boost::multi_array<value_type, 3>;\n    using kahan_accumulator = boost::accumulators::accumulator_set<\n        value_type,\n        boost::accumulators::stats<boost::accumulators::tag::sum_kahan>>;\n\n    sequence_type data_;\n};\n\n}  // namespace bark\n\n#endif  // BARK_GRID_HPP\n", "meta": {"hexsha": "cc9735d1c621177ad925aa3dcfbc12f271b1c874", "size": 1924, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "detail/grid.hpp", "max_stars_repo_name": "storm-ptr/bark", "max_stars_repo_head_hexsha": "e4cd481183aba72ec6cf996eff3ac144c88b79b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-11-05T10:27:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-02T06:25:53.000Z", "max_issues_repo_path": "detail/grid.hpp", "max_issues_repo_name": "storm-ptr/bark", "max_issues_repo_head_hexsha": "e4cd481183aba72ec6cf996eff3ac144c88b79b6", "max_issues_repo_licenses": ["MIT"], "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/grid.hpp", "max_forks_repo_name": "storm-ptr/bark", "max_forks_repo_head_hexsha": "e4cd481183aba72ec6cf996eff3ac144c88b79b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T18:01:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T08:34:04.000Z", "avg_line_length": 32.6101694915, "max_line_length": 73, "alphanum_fraction": 0.6070686071, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577159, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5154159503886219}}
{"text": "// Copyright 2020 Jan Feitsma (Falcons)\n// SPDX-License-Identifier: Apache-2.0\n/*\n * falconsCommonLegacy.hpp (previously cFalconsCommon.cpp)\n *\n *  Created on: Sep 11, 2014\n *      Author: Jan Feitsma\n */\n\n#include \"ext/falconsCommonLegacy.hpp\"\n\n#include <stdio.h>\n#include <math.h>\n#include <float.h>\n#include <pwd.h>\n#include <cstdio>\n#include <string.h>\n#include <arpa/inet.h>\n#include <ifaddrs.h>\n#include <boost/algorithm/string.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/lexical_cast.hpp>\n#include <unistd.h>\n\n// TODO most of this stuff should be distributed to dedicated packages,\n// for instance angle utilities, Position2D, Velocity2D etc. to geometry\n\n\n// Source: http://math.stackexchange.com/questions/1201337/finding-the-angle-between-two-points\ndouble angle_between_two_points_0_2pi(double x1, double y1, double x2, double y2)\n{\n\n    double angle = std::atan2(y2 - y1, x2 - x1);\n    return project_angle_0_2pi(angle);\n}\n\ndouble project_angle_0_2pi(double angle)\n{\n    // sanity checks\n    if ((angle > 100) || (angle < -100))\n    {\n        throw std::runtime_error(\"angle out of bounds\");\n    }\n    while (angle < 0) angle += 2*M_PI;\n    while (angle > 2*M_PI) angle -= 2*M_PI;\n    return angle;\n}\n\nfloat project_angle_0_2pi(float angle)\n{\n    // sanity checks\n    if ((angle > 100) || (angle < -100))\n    {\n        throw std::runtime_error(\"angle out of bounds\");\n    }\n    while (angle < 0) angle += 2*M_PI;\n    while (angle > 2*M_PI) angle -= 2*M_PI;\n    return angle;\n}\n\ndouble project_angle_mpi_pi(double angle)\n{\n    // sanity checks\n    if ((angle > 100) || (angle < -100))\n    {\n        throw std::runtime_error(\"angle out of bounds\");\n    }\n    while (angle < -M_PI) angle += 2*M_PI;\n    while (angle > M_PI) angle -= 2*M_PI;\n    return angle;\n}\n\nfloat project_angle_mpi_pi(float angle)\n{\n    // sanity checks\n    if ((angle > 100) || (angle < -100))\n    {\n        throw std::runtime_error(\"angle out of bounds\");\n    }\n    while (angle < -M_PI) angle += 2*M_PI;\n    while (angle > M_PI) angle -= 2*M_PI;\n    return angle;\n}\n\n\n// position type transformations\nPosition2D getPosition2D( const geometry::Pose2D& pose)\n{\n    Position2D myPosition;\n    myPosition.x= pose.x;\n    myPosition.y= pose.y;\n    return ( myPosition );\n}\n\nPosition2D getPosition2D( const Point3D& point3d)\n{\n    Position2D myPosition;\n    myPosition.x= (double) point3d.x;\n    myPosition.y= (double) point3d.y;\n    return ( myPosition );\n}\n\n// coordinate transformations\nVelocity2D& Velocity2D::transform_fcs2rcs(const Position2D& robotpos)\n{\n    double angle = (M_PI_2 - robotpos.phi);\n    Vector2D xynew = Vector2D(x, y).rotate(angle);\n    x = xynew.x;\n    y = xynew.y;\n    // do not update vphi\n    return (*this);\n}\n\nVelocity2D& Velocity2D::transform_rcs2fcs(const Position2D& robotpos)\n{\n    double angle = -(M_PI_2 - robotpos.phi);\n    Vector2D xynew = Vector2D(x, y).rotate(angle);\n    x = xynew.x;\n    y = xynew.y;\n    // do not update vphi\n    return (*this);\n}\n\nPosition2D& Position2D::transform_fcs2rcs(const Position2D& robotpos)\n{  \n    // first ttranslate, then rotate\n    double angle = (M_PI_2 - robotpos.phi);\n    Vector2D xynew = (Vector2D(x, y) - robotpos.xy()).rotate(angle);\n    x = xynew.x;\n    y = xynew.y;\n    phi = phi + angle;\n    phi = project_angle_0_2pi(phi);\n    return (*this);\n}\n\nPosition2D& Position2D::transform_rcs2fcs(const Position2D& robotpos)\n{\n    // first rotate, then translate\n    double angle = - (M_PI_2 - robotpos.phi);\n    Vector2D xyrot = (Vector2D(x, y)).rotate(angle);\n    x = xyrot.x + robotpos.x;\n    y = xyrot.y + robotpos.y;\n    phi = phi + angle;\n    phi = project_angle_0_2pi(phi);\n    return (*this);\n}\n\nPosition2D& Position2D::transform_fcs2acs(bool playing_left_to_right)\n{\n    // no change in case we are playing left to right\n    if (!playing_left_to_right)\n    {\n        // rotate by half a circle\n        x = -x;\n        y = -y;\n        phi = project_angle_0_2pi(phi + M_PI);\n    }\n    return (*this);\n}\n\nPosition2D& Position2D::transform_acs2fcs(bool playing_left_to_right)\n{\n    // no change in case we are playing left to right\n    if (!playing_left_to_right)\n    {\n        // rotate by half a circle\n        x = -x;\n        y = -y;\n        phi = project_angle_0_2pi(phi + M_PI);\n    }\n    return (*this);\n}\n\nVelocity2D& Velocity2D::transform_fcs2acs(bool playing_left_to_right)\n{\n    // no change in case we are playing left to right\n    if (!playing_left_to_right)\n    {\n        // rotate by half a circle, xy only\n        x = -x;\n        y = -y;\n    }\n    return (*this);\n}\n\nVelocity2D& Velocity2D::transform_acs2fcs(bool playing_left_to_right)\n{\n    // no change in case we are playing left to right\n    if (!playing_left_to_right)\n    {\n        // rotate by half a circle, xy only\n        x = -x;\n        y = -y;\n    }\n    return (*this);\n}\n\n// handy function to return output of a command\n// source: http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c\nstd::string exec(const char* cmd) {\n    boost::shared_ptr<FILE> pipe(popen(cmd, \"r\"), pclose);\n    if (!pipe) return \"ERROR\";\n    char buffer[128];\n    std::string result = \"\";\n    while (!feof(pipe.get())) {\n        if (fgets(buffer, 128, pipe.get()) != NULL)\n            result += buffer;\n    }\n    boost::algorithm::trim(result);\n    return result;\n}\n\nstd::string getProcessId()\n{\n    return exec(\"getProcessId\");\n}\n\n\nfloat restrictValue( float a, float minA, float maxA )  //returns restricted value position within given limits\n{\n    if( a > maxA )\n        return maxA;\n    if( a < minA )\n        return minA;\n    return a;\n}\n\nbool isValueInRange( float a, float minA, float maxA )  //check if value falls in min-max range\n{\n    if( a > maxA )\n        return false;\n    if( a < minA )\n        return false;\n    return true;\n}\n\ndouble calc_angle(double dX, double dY)\n{\n    // calculates the absolute angle\n    // looking from X1,Y1 towards X2,Y2\n    double S = 0.0;\n    double th = 0.0;\n    S = calc_hypothenusa(dX, dY);\n\n    if (dY < 0) {\n        if (dX == 0) {\n            th = M_PI_2;\n        } else {\n            th = acos(-dX / S);\n        }\n    } else if (dY > 0) {\n        if (dX == 0) {\n            th = 3.0 / 2.0 * M_PI;\n        } else {\n            th = 2 * M_PI - acos(-dX / S);\n        }\n    } else if (dY == 0) {\n        if (dX > 0) {\n            th = 0;\n        } else {\n            th = M_PI;\n        }\n    }\n    return th;\n}\n\nfloat calc_angle(float dX, float dY)\n{\n    // calculates the absolute angle\n    // looking from X1,Y1 towards X2,Y2\n    float S = 0.0;\n    float th = 0.0;\n\n    S = calc_hypothenusa(dX, dY);\n\n    if (dY < 0) {\n        if (dX == 0) {\n            th = M_PI_2;\n        } else {\n            th = acos(-dX / S);\n        }\n    } else if (dY > 0) {\n        if (dX == 0) {\n            th = 3.0 / 2.0 * M_PI;\n        } else {\n            th = 2 * M_PI - acos(-dX / S);\n        }\n    } else if (dY == 0) {\n        if (dX > 0) {\n            th = 0;\n        } else {\n            th = M_PI;\n        }\n    }\n    return th;\n}\n\n// transform a line segment (v1,v2)\n// to a line equation a*x + b*y + c = 0\nvoid calculate_line_equation(Vector2D v1, Vector2D v2, double &a, double &b, double &c)\n{\n    double dx = v2.x - v1.x;\n    double dy = v2.y - v1.y;\n    // dx*y - dx*v1.y - dy*x - dy*v1.x = 0\n    a = -dy;\n    b = dx;\n    c = -1.0 * (dx*v1.y - dy*v1.x);\n}\n\ndouble calc_distance_point_line(Vector2D p, double a, double b, double c)\n{\n    if (a != 0 || b != 0)\n    {\n        return (a * p.x +  b * p.y + c) / sqrt(a*a + b*b);\n    }\n    else\n    {\n        return 0;\n    }\n}\n\n// based on http://stackoverflow.com/a/385355\nbool intersect(Vector2D const &a1, Vector2D const &a2, Vector2D const &b1, Vector2D const &b2, Vector2D &result)\n{\n    float x12 = a1.x - a2.x;\n    float x34 = b1.x - b2.x;\n    float y12 = a1.y - a2.y;\n    float y34 = b1.y - b2.y;\n\n    float c = x12 * y34 - y12 * x34;\n\n    if (fabs(c) < 0.01)\n    {\n        // No intersection\n        return false;\n    }\n    // Intersection\n    float a = a1.x * a2.y - a1.y * a2.x;\n    float b = b1.x * b2.y - b1.y * b2.x;\n\n    result.x = (a * x34 - b * x12) / c;\n    result.y = (a * y34 - b * y12) / c;\n\n    return true;\n}\n\ndouble calc_hypothenusa(double dX, double dY)\n{\n    // Function to calculate the Hypothenusa (Schuine zijde)\n    double S = 0.0;\n    S = sqrt(pow(dX, 2) + pow(dY, 2));\n    return S;\n}\n\nfloat calc_hypothenusa(float dX, float dY)\n{\n    // Function to calculate the Hypothenusa (Schuine zijde)\n    float S = 0.0;\n    S = sqrt(pow(dX, 2) + pow(dY, 2));\n    return S;\n}\n\ndouble calc_distance( double x1, double y1, double x2, double y2)\n{\n    double dX=x2-x1;\n    double dY=y2-y1;\n\n    return calc_hypothenusa( dX, dY );\n};\n\ndouble calc_distance( Position2D p1, Position2D p2 )\n{\n    double dX=p2.x - p1.x;\n    double dY=p2.y - p1.y;\n\n    return calc_hypothenusa( dX, dY );\n}\n\ndouble calc_distance( Point2D p1, Point2D p2 )\n{\n    double dX=p2.x - p1.x;\n    double dY=p2.y - p1.y;\n\n    return calc_hypothenusa( dX, dY );\n}\n\nbool ignoreIfaName(std::string ifa_name)\n{\n    if (ifa_name == \"enp0s31f6\") return true; // the port on top-side of CPU-box, located most inward, is reserved for multiCam\n    return false;\n}\n\nconnectionType GetPrimaryIp(char* buffer, size_t buflen)\n{\n    struct ifaddrs * ifAddrStruct=NULL;\n    struct ifaddrs * ifa=NULL;\n    void * tmpAddrPtr=NULL;\n    bool LANFound = false;\n    connectionType retVal = connectionType::INVALID;\n\n    assert(buflen >= INET_ADDRSTRLEN);\n    getifaddrs(&ifAddrStruct);\n\n    if(!LANFound)\n    {\n        for (ifa = ifAddrStruct; ((ifa != NULL) && (!LANFound)); ifa = ifa->ifa_next)\n        {\n            /* Filter IPV4 addresses */\n            if (ifa->ifa_addr->sa_family == AF_INET)\n            {\n\n                tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;\n                char addressBuffer[INET_ADDRSTRLEN];\n                inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);\n\n                if((strstr(ifa->ifa_name, \"en\") != NULL) ||\n                    (strstr(ifa->ifa_name, \"eth\") != NULL))\n                {\n                    if (!ignoreIfaName(ifa->ifa_name))\n                    {\n                        /* Copy IP address to output */\n                        inet_ntop(AF_INET, tmpAddrPtr, buffer, buflen);\n\n                        /* Alright meow! It is time to stop now Mack */\n                        LANFound = true;\n                        retVal = connectionType::LAN;\n                    }\n                }\n            }\n        }\n    }\n\n    for (ifa = ifAddrStruct; ((ifa != NULL) && (!LANFound)); ifa = ifa->ifa_next)\n    {\n        /* Filter IPV4 addresses */\n        if (ifa->ifa_addr->sa_family == AF_INET)\n        {\n\n            tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;\n            char addressBuffer[INET_ADDRSTRLEN];\n            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);\n\n            if(strstr(ifa->ifa_name, \"wl\") != NULL)\n            {\n                /* Copy IP address to output */\n                inet_ntop(AF_INET, tmpAddrPtr, buffer, buflen);\n\n                /* Alright meow! It is time to stop now Mack */\n                LANFound = true;\n                retVal = connectionType::WAN;\n            }\n        }\n    }\n\n    for (ifa = ifAddrStruct; ((ifa != NULL) && (!LANFound)); ifa = ifa->ifa_next)\n    {\n        /* Filter IPV4 addresses */\n        if (ifa->ifa_addr->sa_family == AF_INET)\n        {\n\n            tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;\n            char addressBuffer[INET_ADDRSTRLEN];\n            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);\n\n            if(strstr(ifa->ifa_name, \"usb\") != NULL)\n            {\n                /* Copy IP address to output */\n                inet_ntop(AF_INET, tmpAddrPtr, buffer, buflen);\n\n                /* Alright meow! It is time to stop now Mack */\n                LANFound = true;\n                retVal = connectionType::USB;\n            }\n        }\n    }\n\n    if(!LANFound)\n    {\n        for (ifa = ifAddrStruct; ((ifa != NULL) && (!LANFound)); ifa = ifa->ifa_next)\n        {\n            /* Filter IPV4 addresses */\n            if (ifa->ifa_addr->sa_family == AF_INET)\n            {\n\n                tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;\n                char addressBuffer[INET_ADDRSTRLEN];\n                inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);\n\n                if(strstr(ifa->ifa_name, \"lo\") != NULL)\n                {\n                    /* Copy IP address to output */\n                    inet_ntop(AF_INET, tmpAddrPtr, buffer, buflen);\n\n                    /* Alright meow! It is time to stop now Mack */\n                    LANFound = true;\n                    retVal = connectionType::LOOPBACK;\n                }\n            }\n        }\n    }\n\n    if(!LANFound)\n    {\n        printf(\"No adapter found for fetching an IP address\");\n    }\n\n    if (ifAddrStruct!=NULL)\n    {\n        freeifaddrs(ifAddrStruct);\n    }\n\n    return retVal;\n}\n\nconnectionType GetPrimaryConnectionType()\n{\n    struct ifaddrs * ifAddrStruct=NULL;\n    struct ifaddrs * ifa=NULL;\n    void * tmpAddrPtr=NULL;\n    connectionType retVal = connectionType::INVALID;\n\n    getifaddrs(&ifAddrStruct);\n\n    if(retVal == connectionType::INVALID)\n    {\n        for (ifa = ifAddrStruct; ((ifa != NULL) && (retVal == connectionType::INVALID)); ifa = ifa->ifa_next)\n        {\n            /* Filter IPV4 addresses */\n            if (ifa->ifa_addr->sa_family == AF_INET)\n            {\n\n                tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;\n                char addressBuffer[INET_ADDRSTRLEN];\n                inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);\n\n                if((strstr(ifa->ifa_name, \"en\") != NULL) ||\n                    (strstr(ifa->ifa_name, \"eth\") != NULL))\n                {\n                    if (!ignoreIfaName(ifa->ifa_name))\n                    {\n                        /* Alright meow! It is time to stop now Mack */\n                        retVal = connectionType::LAN;\n                    }\n                }\n            }\n        }\n    }\n\n    for (ifa = ifAddrStruct; ((ifa != NULL) && (retVal == connectionType::INVALID)); ifa = ifa->ifa_next)\n    {\n        /* Filter IPV4 addresses */\n        if (ifa->ifa_addr->sa_family == AF_INET)\n        {\n\n            tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;\n            char addressBuffer[INET_ADDRSTRLEN];\n            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);\n\n            if(strstr(ifa->ifa_name, \"wl\") != NULL)\n            {\n                /* Alright meow! It is time to stop now Mack */\n                retVal = connectionType::WAN;\n            }\n        }\n    }\n\n    for (ifa = ifAddrStruct; ((ifa != NULL) && (retVal == connectionType::INVALID)); ifa = ifa->ifa_next)\n    {\n        /* Filter IPV4 addresses */\n        if (ifa->ifa_addr->sa_family == AF_INET)\n        {\n\n            tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;\n            char addressBuffer[INET_ADDRSTRLEN];\n            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);\n\n            if(strstr(ifa->ifa_name, \"usb\") != NULL)\n            {\n                /* Alright meow! It is time to stop now Mack */\n                retVal = connectionType::USB;\n            }\n        }\n    }\n\n    if(retVal == connectionType::INVALID)\n    {\n        for (ifa = ifAddrStruct; ((ifa != NULL) && (retVal == connectionType::INVALID)); ifa = ifa->ifa_next)\n        {\n            /* Filter IPV4 addresses */\n            if (ifa->ifa_addr->sa_family == AF_INET)\n            {\n\n                tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;\n                char addressBuffer[INET_ADDRSTRLEN];\n                inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);\n\n                if(strstr(ifa->ifa_name, \"lo\") != NULL)\n                {\n                    /* Alright meow! It is time to stop now Mack */\n                    retVal = connectionType::LOOPBACK;\n                }\n            }\n        }\n    }\n\n    if(retVal == connectionType::INVALID)\n    {\n        printf(\"No adapter found for fetching an IP address\");\n    }\n\n    if (ifAddrStruct!=NULL)\n    {\n        freeifaddrs(ifAddrStruct);\n    }\n\n    return retVal;\n}\n\n/* Double comparison */\nbool doubleIsEqual(double a, double b)\n{\n    return fabs(a - b) < FLT_EPSILON;\n}\n\nbool floatIsEqual(float a, float b)\n{\n    return fabs(a - b) < DBL_EPSILON;\n}\n\n// handy function to return output of a command\n// source: http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c\nstd::string systemStdout(std::string cmd, int bufferLimit) \n{\n    std::shared_ptr<FILE> pipe(popen(cmd.c_str(), \"r\"), pclose);\n    if (!pipe) return \"ERROR\";\n    char buffer[128];\n    std::string result = \"\";\n    while (!feof(pipe.get())) {\n        if (fgets(buffer, 128, pipe.get()) != NULL)\n            result += buffer;\n    }\n    boost::algorithm::trim(result);\n    // limit string length\n    if ((int)result.size() > bufferLimit)\n    {\n        result = result.substr(0, bufferLimit);\n    }\n    return result;\n}\n\n\n", "meta": {"hexsha": "86dfc79eac59e7dc797666a2cc79db11f4441a7a", "size": 17205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/facilities/common/src/falconsCommonLegacy.cpp", "max_stars_repo_name": "Falcons-Robocup/code", "max_stars_repo_head_hexsha": "2281a8569e7f11cbd3238b7cc7341c09e2e16249", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-15T13:27:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T08:40:52.000Z", "max_issues_repo_path": "packages/facilities/common/src/falconsCommonLegacy.cpp", "max_issues_repo_name": "Falcons-Robocup/code", "max_issues_repo_head_hexsha": "2281a8569e7f11cbd3238b7cc7341c09e2e16249", "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": "packages/facilities/common/src/falconsCommonLegacy.cpp", "max_forks_repo_name": "Falcons-Robocup/code", "max_forks_repo_head_hexsha": "2281a8569e7f11cbd3238b7cc7341c09e2e16249", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-01T10:39:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T03:02:35.000Z", "avg_line_length": 26.3880368098, "max_line_length": 127, "alphanum_fraction": 0.5565823888, "num_tokens": 4786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5153553942669414}}
{"text": "// Copyright 2020 ICLUE @ UIUC. All rights reserved.\n#include <coxeter_properness/search.h>\n\n#include <algorithm>\n#include <climits>\n#include <deque>\n#include <numeric>\n#include <ostream>\n#include <cctype>\n#include <stack>\n#include <utility>\n#include <vector>\n\n#include <coxeter_properness/search.h>\n\n#include <coxeter/constants.h>\n#include <coxeter/coxtypes.h>\n#include <coxeter/interactive.h>\n#include <coxeter/type.h>\n\n#include <boost/math/special_functions/binomial.hpp>\n\nnamespace coxeter_properness {\n\nusing interactive::CoxGroup;\nusing coxeter::CoxWord;\n\nauto numLDescents(const CoxGroup& W, const CoxWord& w) -> int32_t {\n  auto numDescents = 0;\n  for (auto f1 = W.ldescent(w); f1 != 0; f1 &= (f1-1)) {\n    // const auto s = bits::firstBit(f1);\n    ++numDescents;\n  }\n  return numDescents;\n}\n\nauto choose(const int n, const int k) -> int32_t {\n  if (n < k) return 0;\n  return static_cast<int32_t>(boost::math::binomial_coefficient<double>(n, k));\n}\n\nauto maxw0(const CoxGroup& W, const CoxWord& w) -> int32_t {\n  const auto n = W.rank();\n  const auto dw = numLDescents(W, w);\n  const auto& t = W.type();\n  const auto& typeName = t.name();\n\n  if (typeName == io::String(\"A\"))  return choose(dw+1, 2);\n  if (typeName == io::String(\"B\")) return dw * dw;\n  if (typeName == io::String(\"D\")) return dw > 3 ? dw*(dw-1) : choose(dw+1, 2);\n  if (typeName == io::String(\"E\")) {\n    const static std::vector<int32_t> m_e = {0, 1, 3, 6, 12, 20, 36, 63, 120};\n    return m_e.at(dw);\n  }\n  if (typeName == io::String(\"F\")) {\n    const static std::vector<int32_t> m_f = {0, 1, 4, 9, 24};\n    return m_f[dw];\n  }\n  if (typeName == io::String(\"G\")) {\n    const static std::vector<int32_t> m_g = {0, 1, 6};\n    return m_g[dw];\n  }\n  if (typeName == io::String(\"H\")) {\n    const static std::vector<int32_t> m_h = {0, 1, 5, 15, 60};\n    return m_h[dw];\n  }\n  if (typeName == io::String(\"I\")) return dw == 2 ? n : dw;\n\n  throw std::invalid_argument(\"no type matching\");\n}\n\nbool proper(const CoxGroup& W, const CoxWord& w) {\n  const auto n = W.rank();\n  return w.length() <= n + maxw0(W, w);\n}\n\nTransformer::Transformer(const std::shared_ptr<CoxGroup>& W) : W(W) { }\n\nbool Transformer::parse(const std::string& line, CoxWord* w) {\n  elements.clear();\n  for (const auto& x : line) {\n    // This assumes that the rank of the group is < 10.\n    if (std::isdigit(x)) {\n      elements.push_back(x-'0');\n    }\n  }\n\n  if (elements.empty()) return false;\n\n  // Don't trust the coxeter code to handle dynamic resource allocation.\n  rawWord.setLength(elements.size());\n  for (int i = 0; i < elements.size(); ++i) {\n    rawWord[i] = elements[i];\n  }\n\n  // W->reduced(*w, rawWord);\n  // We can assume that the word is already reduced.\n  *w = rawWord;\n  return true;\n}\n\n}  // namespace coxeter_properness\n", "meta": {"hexsha": "8c9a92c46c5a2c2bf9bec0b6d2e157fc7ad65148", "size": 2778, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/search.cc", "max_stars_repo_name": "iclue-summer-2020/coxeter_properness", "max_stars_repo_head_hexsha": "dbdaa15da6c2e9a59db817d3413e614d072c7a76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/search.cc", "max_issues_repo_name": "iclue-summer-2020/coxeter_properness", "max_issues_repo_head_hexsha": "dbdaa15da6c2e9a59db817d3413e614d072c7a76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/search.cc", "max_forks_repo_name": "iclue-summer-2020/coxeter_properness", "max_forks_repo_head_hexsha": "dbdaa15da6c2e9a59db817d3413e614d072c7a76", "max_forks_repo_licenses": ["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.9708737864, "max_line_length": 79, "alphanum_fraction": 0.6364290857, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.515355390605317}}
{"text": "//\n// Created by erik on 9/23/16.\n//\n\n#include <cmath>\n#include <boost/optional.hpp>\n#include \"HitTests.h\"\n\nusing namespace spatacs;\n\nboost::optional<physics::time_t> physics::intersect_origin(const MovingSphere& s)\n{\n    // x\u00b2(t) = r\u00b2(t): v\u00b2 t\u00b2 + 2 vo t + o\u00b2 = a\u00b2t\u00b2 + 2 ar t + r\u00b2\n    // (v\u00b2 - a\u00b2) t\u00b2 + 2 (vo - ar)t + o\u00b2 - r\u00b2 = 0\n    // t\u00b2 + 2 (vo - ar)/(v\u00b2-a\u00b2) t + (o\u00b2-r\u00b2)/(v\u00b2-a\u00b2) = 0\n    auto vo = dot(s.vel, s.pos);\n    auto ar = s.exp * s.rad;\n    auto v2 = dot(s.vel, s.vel);\n    auto a2 = s.exp * s.exp;\n    auto o2 = dot(s.pos, s.pos);\n    auto r2 = s.rad * s.rad;\n\n    // extreme case, need to consider to prevent div by zero\n    if(v2 == a2)\n    {\n        if(vo == ar)\n            return boost::none;\n\n        return (r2 - o2) / (vo - ar);\n    }\n\n    auto p = 2.0 * (vo - ar) / (v2 - a2);\n    auto q = (o2 - r2) / (v2 - a2);\n    auto det = p*p/4.0 - q;\n    if(det < decltype(det)(0))\n    {\n        return boost::none;\n    }\n    auto w = sqrt(det);\n    if(-p/2.0 < w)\n    {\n        return -p/2.0 + w;\n    } else\n    {\n        return -p/2.0 - w;\n    }\n}\n\nboost::optional<physics::time_t> physics::intersect(MovingSphere s1, const MovingSphere& s2)\n{\n    s1.pos -= s2.pos;\n    s1.vel -= s2.vel;\n    s1.rad += s2.rad;\n    s1.exp += s2.exp;\n    return intersect_origin(s1);\n}\n", "meta": {"hexsha": "d693747807c1f14e2fae012fcfa6a7d5172f9b4c", "size": 1280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "physics/HitTests.cpp", "max_stars_repo_name": "ngc92/SpaTacS", "max_stars_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "physics/HitTests.cpp", "max_issues_repo_name": "ngc92/SpaTacS", "max_issues_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "physics/HitTests.cpp", "max_forks_repo_name": "ngc92/SpaTacS", "max_forks_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "max_forks_repo_licenses": ["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.4561403509, "max_line_length": 92, "alphanum_fraction": 0.51015625, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.5153472539387317}}
{"text": "/* -*- c++ -*- */\n/* \n * Copyright 2013 Ji\u0159\u00ed Pinkava <j-pi@seznam.cz>.\n * \n * This 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, or (at your option)\n * any later version.\n * \n * This software 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\n#include \"noise_level_estimator2_impl.h\"\n#include <algorithm>\n#include <boost/foreach.hpp>\n#include <cmath>\n#include <stdexcept>\n\n#include <stdio.h>\n\nnamespace gr {\n  namespace rstt {\n\n    noise_level_estimator2::sptr\n    noise_level_estimator2::make(float coverage, float chunk_size)\n    {\n      if (!(coverage > 0.))\n        throw std::out_of_range(\"noise_level_estimator2 coverage must be > 0.\");\n      if (!(coverage <= 1.))\n        throw std::out_of_range(\"noise_level_estimator2 coverage must be <= 1.\");\n      if (!(chunk_size > 0.))\n        throw std::out_of_range(\"noise_level_estimator2 chunk_size must be > 0.\");\n      if (!(chunk_size <= coverage))\n        throw std::out_of_range(\"noise_level_estimator2 chunk_size must be <= coverage\");\n      return sptr(new noise_level_estimator2_impl(coverage, chunk_size));\n    }\n\n    noise_model\n    noise_level_estimator2_impl::estimate(const float *data, int data_items) const\n    {\n      const int coverage = data_items * this->coverage;\n      const int chunk_size = data_items * this->chunk_size;\n\n      const int ms_size = data_items - chunk_size + 1;\n      float mean[ms_size];\n      float mean2[ms_size];\n\n      // moving average, first point\n      mean[0] = 0.;\n      mean2[0] = 0.;\n      for (int i = 0; i < chunk_size; ++i) {\n        mean[0] += data[i];\n        mean2[0] += data[i] * data[i];\n      }\n\n      // moving average, other points\n      for (int i = chunk_size, j = 1; i < data_items; ++i, ++j) {\n       mean[j] = mean[j-1] - data[j-1] + data[i];\n       mean2[j] = mean2[j-1] - (data[j-1] * data[j-1]) + (data[i] * data[i]);\n      }\n\n      for (int i = 0; i < ms_size; ++i) {\n        mean[i] /= chunk_size;\n        mean2[i] /= chunk_size;\n      }\n\n      // moving standard deviation (s^2)\n      float s2[ms_size];\n      for (int i = 0; i < ms_size; ++i) {\n        s2[i] = mean2[i] - mean[i] * mean[i];\n      }\n\n      // get the average of lower bound values for mean and deviation\n      std::sort(s2, s2 + ms_size);\n      float s = 0.;\n      for (int i = 0; i < coverage; ++i) {\n        s += std::sqrt(s2[i]);\n      }\n      s /= coverage;\n\n      std::sort(mean, mean + ms_size);\n      float m = 0.;\n      for (int i = 0; i < coverage; ++i) {\n        m += mean[i];\n      }\n      m /= coverage;\n\n      return noise_model(m, s);\n    }\n\n  } // namespace rstt\n} // namespace gr\n\n", "meta": {"hexsha": "fa6a6cab92e89b78a3914e2883394dff39b3248f", "size": 2905, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gr-rstt/lib/noise_level_estimator2_impl.cc", "max_stars_repo_name": "sgs-weather-and-environmental-systems/rstt", "max_stars_repo_head_hexsha": "bd7855001e65f4802f4a2556fc5d7d2fa1f85619", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-03-08T10:06:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T23:49:04.000Z", "max_issues_repo_path": "gr-rstt/lib/noise_level_estimator2_impl.cc", "max_issues_repo_name": "sgs-weather-and-environmental-systems/rstt", "max_issues_repo_head_hexsha": "bd7855001e65f4802f4a2556fc5d7d2fa1f85619", "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": "gr-rstt/lib/noise_level_estimator2_impl.cc", "max_forks_repo_name": "sgs-weather-and-environmental-systems/rstt", "max_forks_repo_head_hexsha": "bd7855001e65f4802f4a2556fc5d7d2fa1f85619", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-09-26T02:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-25T04:41:07.000Z", "avg_line_length": 29.9484536082, "max_line_length": 89, "alphanum_fraction": 0.5969018933, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5153186769918361}}
{"text": "//  (C) Copyright John Maddock 2007.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/limits.hpp>\n#include <vector>\n#include \"mp_t.hpp\"\n\nvoid write_table(unsigned max_exponent)\n{\n   mp_t max = ldexp(mp_t(1), (int)max_exponent);\n\n   std::vector<mp_t> factorials;\n   factorials.push_back(1);\n\n   mp_t f(1);\n   unsigned i = 1;\n\n   while(f < max)\n   {\n      factorials.push_back(f);\n      ++i;\n      f *= i;\n   }\n\n   //\n   // now write out the results to cout:\n   //\n   std::cout << std::scientific << std::setprecision(40);\n   std::cout << \"   static const std::array<T, \" << factorials.size() << \"> factorials = {\\n\";\n   for(unsigned j = 0; j < factorials.size(); ++j)\n      std::cout << \"      \" << factorials[j] << \"L,\\n\";\n   std::cout << \"   };\\n\\n\";\n}\n\n\nint main()\n{\n   write_table(16384/*std::numeric_limits<float>::max_exponent*/);\n}\n", "meta": {"hexsha": "e1578c5fc0e7b95e08486033afbb47d55270c6b7", "size": 997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/factorial_tables.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": "tools/factorial_tables.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": "tools/factorial_tables.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": 23.7380952381, "max_line_length": 94, "alphanum_fraction": 0.6078234704, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5153186717459171}}
{"text": "// vi: set et ts=4 sw=2 sts=2:\n\n#ifndef HMAT_HMATRIX_DENSE_DATA_HPP\n#define HMAT_HMATRIX_DENSE_DATA_HPP\n\n#include \"common.hpp\"\n#include \"hmatrix_data.hpp\"\n#include <armadillo>\n\nnamespace hmat {\n\ntemplate <typename ValueType>\nclass HMatrixDenseData : public HMatrixData<ValueType> {\npublic:\n  void apply(const arma::Mat<ValueType> &X, arma::Mat<ValueType> &Y,\n             TransposeMode trans, ValueType alpha, ValueType beta) const\n      override;\n\n  void apply(const arma::subview<ValueType> &X, arma::subview<ValueType> &Y,\n             TransposeMode trans, ValueType alpha, ValueType beta) const\n      override;\n\n  const arma::Mat<ValueType> &A() const;\n  arma::Mat<ValueType> &A();\n\n  int rows() const override;\n  int cols() const override;\n  int rank() const override;\n\n  typename ScalarTraits<ValueType>::RealType frobeniusNorm() const override;\n\n  double memSizeKb() const override;\n\nprivate:\n  arma::Mat<ValueType> m_A;\n};\n}\n\n#include \"hmatrix_dense_data_impl.hpp\"\n\n#endif\n", "meta": {"hexsha": "babb0ae29eda8c256ff0269dc861f3defb499497", "size": 981, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/hmat/hmatrix_dense_data.hpp", "max_stars_repo_name": "mdavezac/bempp", "max_stars_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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": "lib/hmat/hmatrix_dense_data.hpp", "max_issues_repo_name": "mdavezac/bempp", "max_issues_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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/hmat/hmatrix_dense_data.hpp", "max_forks_repo_name": "mdavezac/bempp", "max_forks_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "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.3571428571, "max_line_length": 76, "alphanum_fraction": 0.7206931702, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5153186664999979}}
{"text": "#include <algorithm>\r\n#include <vector>\r\n#include <list>\r\n#include <queue>\r\n#include <string>\r\n#include <map>\r\n#include <set>\r\n#include <unordered_map>\r\n#include <unordered_set>\r\n#include <utility>\r\n#include <functional>\r\n#include <iostream>\r\n#include <sstream>\r\n#include <cctype>\r\n#include <cmath>\r\n//#include <boost/multiprecision/cpp_int.hpp>\r\n\r\nusing namespace std;\r\n//using namespace boost::multiprecision;\r\n\r\nvector<vector<int>> g;\r\nvector<bool> f;\r\nint N, root;\r\n\r\nint bitCount(int mask){\r\n\tint res = 0;\r\n\twhile (mask){\r\n\t\tmask &= mask - 1;\r\n\t\t++res;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nbool dfs(int prev, int cur, int mask){\r\n\tif (mask & (1 << cur))\r\n\t\treturn false;\r\n\r\n\tf[cur] = true;\r\n\r\n\tint count = 0;\r\n\tfor (int j : g[cur]){\r\n\t\tif (j != prev){\r\n\t\t\tif (mask & (1 << j)){\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\t++count;\r\n\t\t\t\tif (!dfs(cur, j, mask))\r\n\t\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn count == 0 || count == 2;\r\n}\r\n\r\nbool calc(int mask){\r\n\tfor (int i = 0; i < N; ++i){\r\n\t\tf.assign(N, false);\r\n\t\tif (dfs(-1, i, mask)){\r\n\t\t\tbool ok = true;\r\n\t\t\tfor (int i = 0; i < N; ++i){\r\n\t\t\t\tif (!f[i] && !((1<<i) & mask)){\r\n\t\t\t\t\tok = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (ok)\r\n\t\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid comp(int tc){\r\n\tN;\r\n\tcin >> N;\r\n\r\n\tg.assign(N, vector<int>());\r\n\r\n\tfor (int i = 0; i < N - 1; ++i){\r\n\t\tint a, b;\r\n\t\tcin >> a >> b;\r\n\t\tg[a - 1].push_back(b - 1);\r\n\t\tg[b - 1].push_back(a - 1);\r\n\t}\r\n\r\n\tint best = N;\r\n\tfor (int i = 0; i < (1<<N); ++i){\r\n\t\tif (calc(i))\r\n\t\t\tbest = min(best, bitCount(i));\r\n\t}\r\n\r\n\tcout << \"Case #\" << tc << \": \" << best << endl;\r\n\r\n}\r\n\r\nint main(){\r\n\tint T;\r\n\tcin >> T;\r\n\tfor (int tc = 1; tc <= T; ++tc){\r\n\t\tcomp(tc);\r\n\t}\r\n}", "meta": {"hexsha": "5163ae3e7476ef8a4ff69806a346e942829b58d5", "size": 1659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/google-code-jam/slowpoke/B2.cpp", "max_stars_repo_name": "rbenic-fer/progauthfp", "max_stars_repo_head_hexsha": "d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675", "max_stars_repo_licenses": ["MIT"], "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/google-code-jam/slowpoke/B2.cpp", "max_issues_repo_name": "rbenic-fer/progauthfp", "max_issues_repo_head_hexsha": "d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675", "max_issues_repo_licenses": ["MIT"], "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/google-code-jam/slowpoke/B2.cpp", "max_forks_repo_name": "rbenic-fer/progauthfp", "max_forks_repo_head_hexsha": "d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675", "max_forks_repo_licenses": ["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.1067961165, "max_line_length": 49, "alphanum_fraction": 0.5009041591, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5152851466246857}}
{"text": "#ifndef Evaluate1D_hpp\n#define Evaluate1D_hpp\n\n#include <QVector>\n#include <alglib/ap.h>\n#include <alglib/interpolation.h>\n#include <algorithm>\n#include <cmath>\n#include <QAlgorithm.hpp>\n#include <UMF/CurveNormalization.hpp>\n\nnamespace UMF {\n\t\n\tclass Evaluate1D : public QAlgorithm {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\t\tQA_INPUT(QVector<double>, X)\n\t\tQA_OUTPUT(QVector<double>, Y)\n\t\tQA_PARAMETER(QVector<double>, Coefficients, QVector<double>())\n\t\t\n\t\tQA_CTOR_INHERIT\n\t\t\n\tpublic:\n\t\ttypedef void(*EvalFuncType)(const alglib::real_1d_array&, const alglib::real_1d_array&, double&, void*);\n\t\t\n\tprotected:\n\t\tEvalFuncType eval = Q_NULLPTR;\n\t\t\n\tpublic:\n\t\tvoid run() final;\n\t\t\n\t\tEvalFuncType getInternalFunc() const {return eval;};\n\t\t\n\t\tQVector<double> evaluate(QVector<double> C,\n\t\t\t\t\t\t\t\t QVector<double> X);\n\t};\n\t\n\tclass EvaluateGaussExp : public Evaluate1D {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\t\tQA_IMPL_CREATE(EvaluateGaussExp)\n\t\t\n\tpublic:\n\t\tusing Evaluate1D::Evaluate1D;\n\t\t\n\t\tvoid init();\n\t};\n\t\n\tclass EvaluateGauss : public Evaluate1D {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\t\tQA_IMPL_CREATE(EvaluateGauss)\n\t\t\n\tpublic:\n\t\tusing Evaluate1D::Evaluate1D;\n\t\t\n\t\tvoid init();\n\t};\n\t\n\tclass Fitting1D : public QAlgorithm {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\t\tQA_INPUT(QVector<double>, X)\n\t\tQA_INPUT(QVector<double>, Y)\n\t\tQA_OUTPUT(QVector<double>, Coefficients)\n\t\tQA_OUTPUT(double, AvgError)\n\t\tQA_OUTPUT(double, AvgRelError)\n\t\t\n\t\tQA_CTOR_INHERIT\n\t\t\n\tprotected:\n\t\tQSharedPointer<Evaluate1D> evaluator;\n\t\t\n\tpublic:\n\t\tvoid run();\n\t\t\n\tQ_SIGNALS:\n\t\tQ_SIGNAL void fittingReady(QVector<double> Parameters,\n\t\t\t\t\t\t\t\t   double min, double max,\n\t\t\t\t\t\t\t\t   double avgerr, double avgrelerr);\n\t};\n\t\n\tclass FittingGauss: public Fitting1D {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\t\tQA_IMPL_CREATE(FittingGauss)\n\t\t\n\tpublic:\n\t\tusing Fitting1D::Fitting1D;\n\t\t\n\t\tvoid init();\n\t};\n\t\n\tclass FittingGaussExp: public Fitting1D {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\t\tQA_IMPL_CREATE(FittingGaussExp)\n\t\t\n\tpublic:\n\t\tusing Fitting1D::Fitting1D;\n\t\t\n\t\tvoid init();\n\t};\n}\n\n#endif /* Evaluate1D_hpp */\n", "meta": {"hexsha": "2a280fa68cc122b27ba9968dbb852fc909e06dda", "size": 1944, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Headers/UMF/Evaluate1D.hpp", "max_stars_repo_name": "DottD/audioRec", "max_stars_repo_head_hexsha": "74c316974000fc7c9048f076de01c40ede85836c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Headers/UMF/Evaluate1D.hpp", "max_issues_repo_name": "DottD/audioRec", "max_issues_repo_head_hexsha": "74c316974000fc7c9048f076de01c40ede85836c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Headers/UMF/Evaluate1D.hpp", "max_forks_repo_name": "DottD/audioRec", "max_forks_repo_head_hexsha": "74c316974000fc7c9048f076de01c40ede85836c", "max_forks_repo_licenses": ["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.203539823, "max_line_length": 106, "alphanum_fraction": 0.6975308642, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5152851466246857}}
{"text": "// Copyright (c) 2021 Graphcore Ltd. All rights reserved.\n#define BOOST_TEST_MODULE CholeskyTest\n#include <poplibs_support/TestDevice.hpp>\n\n#include <iostream>\n\n#include <boost/test/data/monomorphic/generators/xrange.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <poplar/Engine.hpp>\n#include <poplin/Cholesky.hpp>\n#include <poplin/MatMul.hpp>\n#include <poplin/codelets.hpp>\n#include <popops/codelets.hpp>\n#include <poputil/TileMapping.hpp>\n#include <poputil/exceptions.hpp>\n\nusing namespace poplar;\nusing namespace poplar::program;\nusing namespace poputil;\nusing namespace poplin;\nusing namespace poplibs_support;\nnamespace bu = boost::unit_test;\nnamespace bud = boost::unit_test::data;\n\nnamespace {\n\nstd::vector<float> createTriMat(std::size_t numBatches, std::size_t N,\n                                bool lower, float batchIncrement = 100.0f) {\n  float start = 1;\n  std::vector<float> v(numBatches * N * N);\n  for (std::size_t b = 0, k = 0; b < numBatches; ++b, k += N * N) {\n    float f = start;\n    for (std::size_t i = 0; i < N; i++) {\n      for (std::size_t j = 0; j < N; j++, f += 1.0f) {\n        // Generate the same values (tranposed)\n        if (lower)\n          v[k + i * N + j] = j > i ? 0 : f;\n        else\n          v[k + j * N + i] = j > i ? 0 : f;\n      }\n    }\n    start += batchIncrement;\n  }\n  return v;\n}\n\n} // namespace\n\nBOOST_DATA_TEST_CASE(CholeskyTest,\n                     bud::make({20, 32}) * bud::make({16}) * bud::make({1, 2}) *\n                         bud::make({true, false}),\n                     N_, blockSize_, numBatches_, lower_) {\n  std::size_t N = N_;\n  std::size_t blockSize = blockSize_;\n  std::size_t numBatches = numBatches_;\n  bool lower = lower_;\n\n  std::cout << \"Running test: N = \" << N << \", lower = \" << lower\n            << \", blockSize = \" << blockSize << \", numBatches = \" << numBatches\n            << std::endl;\n\n  auto device = createTestDevice(TEST_TARGET, 1, 4);\n  auto &target = device.getTarget();\n\n  Graph graph(target);\n  popops::addCodelets(graph);\n  poplin::addCodelets(graph);\n\n  std::vector<float> Tv = createTriMat(numBatches, N, lower);\n\n  Sequence prog;\n\n  auto T = graph.addVariable(poplar::FLOAT, {numBatches, N, N}, \"T\");\n  poputil::mapTensorLinearly(graph, T);\n  graph.createHostWrite(\"T\", T);\n\n  auto A =\n      lower ? poplin::matMulGrouped(graph, T, poplin::transposeGroupedMatrix(T),\n                                    prog, T.elementType())\n            : poplin::matMulGrouped(graph, poplin::transposeGroupedMatrix(T), T,\n                                    prog, T.elementType());\n  graph.createHostRead(\"A\", A);\n\n  poplar::OptionFlags options{{\"blockSize\", std::to_string(blockSize)}};\n  auto matmulOptPairs = getCholeskyMatMulPrePlanParameters(\n      A.elementType(), A.shape(), lower, options);\n\n  std::set<MatMulPlanParams> params;\n  for (auto &pair : matmulOptPairs)\n    params.emplace(&target, pair.first, &pair.second);\n  matmul::PlanningCache cache;\n  preplanMatMuls(params, cache);\n  BOOST_TEST(cache.size() == matmulOptPairs.size());\n\n  if (N > blockSize) {\n    BOOST_TEST(cache.size() > 0);\n  } else {\n    BOOST_TEST(cache.size() == 0);\n  }\n\n  poplar::DebugContext debugContext;\n\n  auto T2 =\n      poplin::cholesky(graph, A, lower, prog, debugContext, options, &cache);\n  BOOST_TEST(cache.size() == matmulOptPairs.size());\n\n  auto A2 =\n      lower\n          ? poplin::matMulGrouped(graph, T2, poplin::transposeGroupedMatrix(T2),\n                                  prog, T2.elementType())\n          : poplin::matMulGrouped(graph, poplin::transposeGroupedMatrix(T2), T2,\n                                  prog, T2.elementType());\n  graph.createHostRead(\"A2\", A2);\n\n  Engine eng(graph, prog);\n  device.bind([&](const Device &d) {\n    eng.load(d);\n    eng.writeTensor(\"T\", Tv.data(), Tv.data() + Tv.size());\n    eng.run();\n\n    std::vector<float> Av(Tv.size());\n    eng.readTensor(\"A\", Av.data(), Av.data() + Av.size());\n\n    std::vector<float> A2v(Tv.size());\n    eng.readTensor(\"A2\", A2v.data(), A2v.data() + A2v.size());\n\n    for (std::size_t i = 0; i < Av.size(); i++) {\n      BOOST_REQUIRE_CLOSE(Av[i], A2v[i], 0.001f);\n    }\n  });\n}\n", "meta": {"hexsha": "7a0754cac5e9714ba1e0d9c8724a33be8479b86b", "size": 4170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/poplin/CholeskyTest.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/poplin/CholeskyTest.cpp", "max_issues_repo_name": "graphcore/poplibs", "max_issues_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_issues_repo_licenses": ["MIT"], "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/poplin/CholeskyTest.cpp", "max_forks_repo_name": "graphcore/poplibs", "max_forks_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "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": 31.1194029851, "max_line_length": 80, "alphanum_fraction": 0.6071942446, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5152851444028405}}
{"text": "#include <Eigen/Core>\n#include <boost/python.hpp>\n#include <boost/numpy.hpp>\n\n\nnamespace boopy\n{\n  namespace bpn = boost::numpy;\n  namespace bp = boost::python;\n\t\n  struct Eigenvec_to_python_matrix\n  {\n    static PyObject* convert(Eigen::VectorXd const& v)\n    {\n      Py_intptr_t shape[1] = { v.size() };\n      bpn::matrix result(bpn::zeros(1, shape, bpn::dtype::get_builtin<double>()));\n      std::copy(v.data(), v.data()+v.size(), reinterpret_cast<double*>(result.get_data()));\n      return bp::incref(result.ptr());\n    }\n  };\n  \n  struct Eigenvec_from_python_array\n  {\n    Eigenvec_from_python_array()\n    {\n      bp::converter::registry\n\t::push_back(&convertible,\n\t\t    &construct,\n\t\t    bp::type_id<Eigen::VectorXd>());\n    }\n \n    // Determine if obj_ptr can be converted in a Eigenvec\n    static void* convertible(PyObject* obj_ptr)\n    {\n\n      try {\n\tbp::object obj(bp::handle<>(bp::borrowed(obj_ptr)));\n\tstd::auto_ptr<bpn::ndarray> \n\t  array(new bpn::ndarray(bpn::from_object(obj,\n\t\t\t\t\t\t  bpn::dtype::get_builtin<double>(),\n\t\t\t\t\t\t  bpn::ndarray::V_CONTIGUOUS)));\n\n\tif( (array->get_nd()==1)\n\t    || ( (array->get_nd()==2) && (array->get_shape()[1]==1) ))\n\t  return array.release();\n\telse\n\t  return 0;\n      } catch (bp::error_already_set & err) {\n\tbp::handle_exception();\n\treturn 0;\n      }\n    }\n \n    // Convert obj_ptr into a Eigenvec\n    static void construct(PyObject* ,\n\t\t\t  bp::converter::rvalue_from_python_stage1_data* memory)\n    {\n      // Recover the pointer created in <convertible>\n      std::auto_ptr<bpn::ndarray> \n\tarray(reinterpret_cast<bpn::ndarray*>(memory->convertible));\n      const int nrow = array->get_shape()[0];\n      std::cout << \"nrow = \" << nrow << std::endl;\n\n      // Get the memory where to create the vector\n      void* storage\n\t= ((bp::converter::rvalue_from_python_storage<Eigen::VectorXd>*)memory)\n\t->storage.bytes;\n\n      // Create the vector\n      Eigen::VectorXd & res = * new (storage) Eigen::VectorXd(nrow);\n \n      // Copy the data\n      double * data = (double*)array->get_data();\n      for(int i=0;i<nrow;++i) \n\tres[i] = data[i];\n\n      // Stash the memory chunk pointer for later use by boost.python\n      memory->convertible = storage;\n    }\n  };\n}\n\nEigen::VectorXd test()\n{\n  Eigen::VectorXd v = Eigen::VectorXd::Random(5);\n  std::cout << v.transpose() << std::endl;\n  return v;\n}\n\nvoid test2( Eigen::VectorXd v )\n{\n  std::cout << \"test2: dim = \" << v.size() << \" ||| v[0] = \" << v[0] << std::endl;\n}\n\nBOOST_PYTHON_MODULE(libeigen)\n{\n  namespace bpn = boost::numpy;\n  namespace bp = boost::python;\n\n  bpn::initialize();\n  bp::to_python_converter<Eigen::VectorXd,\n\t\t\t  boopy::Eigenvec_to_python_matrix>();\n  boopy::Eigenvec_from_python_array();\n\n  bp::def(\"test\", test);\n  bp::def(\"test2\", test2);\n}\n", "meta": {"hexsha": "9efe84ae4ff6bc05b91623bd6739cf3c30327856", "size": 2758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/alpha/eigen.cpp", "max_stars_repo_name": "wxmerkt/eigenpy", "max_stars_repo_head_hexsha": "15355e6ed0dc555072a6c07ca63e4a406e02a24e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-31T01:30:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-24T12:06:39.000Z", "max_issues_repo_path": "unittest/alpha/eigen.cpp", "max_issues_repo_name": "wxmerkt/eigenpy", "max_issues_repo_head_hexsha": "15355e6ed0dc555072a6c07ca63e4a406e02a24e", "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": "unittest/alpha/eigen.cpp", "max_forks_repo_name": "wxmerkt/eigenpy", "max_forks_repo_head_hexsha": "15355e6ed0dc555072a6c07ca63e4a406e02a24e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.537037037, "max_line_length": 91, "alphanum_fraction": 0.6243654822, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5152851417500677}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/assert.hpp>\n#include <boost/hana/bool.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/maybe.hpp>\nusing namespace boost::hana;\n\n\n//! [applicative]\ntemplate <char op>\nconstexpr auto function = nothing;\n\ntemplate <>\nBOOST_HANA_CONSTEXPR_LAMBDA auto function<'+'> = just([](auto x, auto y) {\n    return x + y;\n});\n\ntemplate <>\nBOOST_HANA_CONSTEXPR_LAMBDA auto function<'-'> = just([](auto x, auto y) {\n    return x - y;\n});\n\n// and so on...\n\ntemplate <char n>\nBOOST_HANA_CONSTEXPR_LAMBDA auto digit = if_(bool_<(n >= '0' && n <= '9')>,\n    just(static_cast<int>(n - 48)),\n    nothing\n);\n\ntemplate <char x, char op, char y>\nBOOST_HANA_CONSTEXPR_LAMBDA auto evaluate = ap(function<op>, digit<x>, digit<y>);\n\nint main() {\n    BOOST_HANA_CONSTEXPR_CHECK(evaluate<'1', '+', '2'> == just(1 + 2));\n\n    BOOST_HANA_CONSTANT_CHECK(evaluate<'?', '+', '2'> == nothing);\n    BOOST_HANA_CONSTANT_CHECK(evaluate<'1', '?', '2'> == nothing);\n    BOOST_HANA_CONSTANT_CHECK(evaluate<'1', '+', '?'> == nothing);\n    BOOST_HANA_CONSTANT_CHECK(evaluate<'?', '?', '?'> == nothing);\n\n    BOOST_HANA_CONSTEXPR_CHECK(lift<Maybe>(123) == just(123));\n}\n//! [applicative]\n", "meta": {"hexsha": "37ef4ab4c0e8e74c037dfcfe06f9905535d0a6fa", "size": 1347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/maybe.complex.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/maybe.complex.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/maybe.complex.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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.94, "max_line_length": 81, "alphanum_fraction": 0.6659242762, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5152851417500677}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE element_fp2_test\n\n#include <chrono>\n#include <boost/test/unit_test.hpp>\n\n#include <nil/crypto3/algebra/curves/mnt4.hpp>\n#include <nil/crypto3/algebra/fields/mnt4/base_field.hpp>\n#include <nil/crypto3/algebra/fields/mnt4/scalar_field.hpp>\n#include <nil/crypto3/algebra/fields/arithmetic_params/mnt4.hpp>\n#include <nil/crypto3/algebra/curves/params/multiexp/mnt4.hpp>\n#include <nil/crypto3/algebra/curves/params/wnaf/mnt4.hpp>\n#include <nil/crypto3/algebra/curves/mnt6.hpp>\n#include <nil/crypto3/algebra/fields/mnt6/base_field.hpp>\n#include <nil/crypto3/algebra/fields/mnt6/scalar_field.hpp>\n#include <nil/crypto3/algebra/fields/arithmetic_params/mnt6.hpp>\n#include <nil/crypto3/algebra/curves/params/multiexp/mnt6.hpp>\n#include <nil/crypto3/algebra/curves/params/wnaf/mnt6.hpp>\n#include <nil/crypto3/algebra/random_element.hpp>\n\n#include <nil/crypto3/zk/components/blueprint.hpp>\n\n#include <nil/crypto3/zk/components/algebra/fields/element_fp2.hpp>\n\n#include \"arithmetic.hpp\"\n\n#include \"../../verify_r1cs_scheme.hpp\"\n\nusing namespace nil::crypto3;\nusing namespace nil::crypto3::zk;\nusing namespace nil::crypto3::algebra;\n\nBOOST_AUTO_TEST_SUITE(field_element_arithmetic_component_test_suite)\n\nBOOST_AUTO_TEST_CASE(field_element_mul_component_test_mnt4_case) {\n    using curve_type = typename curves::mnt4<298>;\n    using field_type = typename curve_type::template g2_type<>::field_type;\n    using base_field_type = typename curve_type::base_field_type;\n\n    std::size_t tries_quantity = 10;\n    std::cout << \"Starting element Fp2 mul component test for MNT4-298 \" << tries_quantity << \" times ...\" << std::endl;\n    auto begin = std::chrono::high_resolution_clock::now();\n\n    for (std::size_t i = 0; i < tries_quantity; i++){\n        typename field_type::value_type a_value = random_element<field_type>();\n        typename field_type::value_type b_value = random_element<field_type>();\n\n        components::blueprint<base_field_type> bp = test_field_element_mul<field_type, \n            components::element_fp2, \n            components::element_fp2_mul>(a_value, b_value);\n\n        BOOST_CHECK(bp.is_satisfied());\n\n        BOOST_CHECK(verify_component<typename curve_type::chained_on_curve_type>(bp));\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);\n    std::cout << \"Element Fp2 mul component test for MNT4-298 finished, average time: \" << elapsed.count() * 1e-9 / tries_quantity << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(field_element_squared_component_test_mnt4_case) {\n    using curve_type = typename curves::mnt4<298>;\n    using field_type = typename curve_type::template g2_type<>::field_type;\n    using base_field_type = typename curve_type::base_field_type;\n\n    std::size_t tries_quantity = 10;\n    std::cout << \"Starting element Fp2 squared component test for MNT4-298 \" << tries_quantity << \" times ...\" << std::endl;\n    auto begin = std::chrono::high_resolution_clock::now();\n\n    for (std::size_t i = 0; i < tries_quantity; i++){\n        typename field_type::value_type a_value = random_element<field_type>();\n\n        components::blueprint<base_field_type> bp = test_field_element_squared<field_type, \n            components::element_fp2, \n            components::element_fp2_squared>(a_value);\n\n        BOOST_CHECK(bp.is_satisfied());\n\n        BOOST_CHECK(verify_component<typename curve_type::chained_on_curve_type>(bp));\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);\n    std::cout << \"Element Fp2 squared component test for MNT4-298 finished, average time: \" << elapsed.count() * 1e-9 / tries_quantity << std::endl;\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "730c6e6d2727abcfa74f2180e6af61475bc06289", "size": 5176, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algebra/fields/fp2_verification.cpp", "max_stars_repo_name": "NoamDev/crypto3-blueprint", "max_stars_repo_head_hexsha": "b85c659ae186c8e5e4d468cdd8decaec02797eae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T04:52:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T23:33:40.000Z", "max_issues_repo_path": "test/algebra/fields/fp2_verification.cpp", "max_issues_repo_name": "NoamDev/crypto3-blueprint", "max_issues_repo_head_hexsha": "b85c659ae186c8e5e4d468cdd8decaec02797eae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-08T15:17:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T22:19:43.000Z", "max_forks_repo_path": "test/algebra/fields/fp2_verification.cpp", "max_forks_repo_name": "NoamDev/crypto3-blueprint", "max_forks_repo_head_hexsha": "b85c659ae186c8e5e4d468cdd8decaec02797eae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-05-20T20:02:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T12:26:24.000Z", "avg_line_length": 47.0545454545, "max_line_length": 148, "alphanum_fraction": 0.7223724884, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5152851417500677}}
{"text": "/*\n * @file\n * @author University of Warwick\n * @version 1.0\n *\n * @section LICENSE\n *\n * @section DESCRIPTION\n *\n * Unit Tests for the methods of the Hexahedral class\n */\n\n\n#define BOOST_TEST_MODULE Hexahedron\n#include <boost/test/unit_test.hpp>\n#include <boost/test/output_test_stream.hpp>\n#include <stdexcept>\n\n#include \"Hexahedron.h\"\n#include \"EuclideanPoint.h\"\n\nusing namespace cupcfd::geometry::shapes;\nnamespace euc = cupcfd::geometry::euclidean;\nnamespace utf = boost::unit_test;\n\n// === Constructor ===\n// Test 1: Construct a regular hexahedron\nBOOST_AUTO_TEST_CASE(constructor_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\n\tQuadrilateral3D<double> faces[6] = {top, bottom, front, rear, left, right};\n\tfor (int f=0; f<6; f++) {\n\t\tfor (int v=0; v<4; v++) {\n\t\t\tfor (int c=0; c<3; c++) {\n\t\t\t\tBOOST_TEST(shape.faces[f].vertices[v].cmp[c] == faces[f].vertices[v].cmp[c]);\n\t\t\t}\n\t\t}\n\t}\n}\n\n// === isPointInside ===\n// Test 1: Point is inside Hexahedron\nBOOST_AUTO_TEST_CASE(isPointInside_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\n\teuc::EuclideanPoint<double,3> point(2.3, 4.6, 6.7);\n\n\tbool isPointInside = shape.isPointInside(point);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 2: Point is outside Hexahedron\nBOOST_AUTO_TEST_CASE(isPointInside_test2, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\teuc::EuclideanPoint<double,3> point(2.3, 4.6, 13.7);\n\n\tbool isPointInside = shape.isPointInside(point);\n\tBOOST_CHECK_EQUAL(isPointInside, false);\n}\n\n// Test 3: Point is on Vertex tlf\nBOOST_AUTO_TEST_CASE(isPointInside_test3, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\tbool isPointInside = shape.isPointInside(tlf);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 4: Point is on Vertex trf\nBOOST_AUTO_TEST_CASE(isPointInside_test4, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\tbool isPointInside = shape.isPointInside(trf);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 5: Point is on Vertex blf\nBOOST_AUTO_TEST_CASE(isPointInside_test5, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\tbool isPointInside = shape.isPointInside(blf);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 6: Point is on Vertex brf\nBOOST_AUTO_TEST_CASE(isPointInside_test6, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\tbool isPointInside = shape.isPointInside(brf);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 7: Point is on Vertex tlb\nBOOST_AUTO_TEST_CASE(isPointInside_test7, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\tbool isPointInside = shape.isPointInside(tlb);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 8: Point is on Vertex trb\nBOOST_AUTO_TEST_CASE(isPointInside_test8, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\tbool isPointInside = shape.isPointInside(trb);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 9: Point is on Vertex blb\nBOOST_AUTO_TEST_CASE(isPointInside_test9, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\tbool isPointInside = shape.isPointInside(blb);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 10: Point is on Vertex brb\nBOOST_AUTO_TEST_CASE(isPointInside_test10, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\tbool isPointInside = shape.isPointInside(brb);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 11: Point is on Top Face\nBOOST_AUTO_TEST_CASE(isPointInside_test11, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\teuc::EuclideanPoint<double,3> point(2.3, 4.6, 12.0);\n\n\tbool isPointInside = shape.isPointInside(point);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 12: Point is on Bottom Face\nBOOST_AUTO_TEST_CASE(isPointInside_test12, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\teuc::EuclideanPoint<double,3> point(2.3, 3.853, 0.0);\n\n\tbool isPointInside = shape.isPointInside(point);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 13: Point is on Left Face\nBOOST_AUTO_TEST_CASE(isPointInside_test13, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\teuc::EuclideanPoint<double,3> point(0.0, 2.98, 5.2);\n\n\tbool isPointInside = shape.isPointInside(point);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 14: Point is on Right Face\nBOOST_AUTO_TEST_CASE(isPointInside_test14, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\teuc::EuclideanPoint<double,3> point(5.0, 2.98, 5.2);\n\n\tbool isPointInside = shape.isPointInside(point);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 15: Point is on Front Face\nBOOST_AUTO_TEST_CASE(isPointInside_test15, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\teuc::EuclideanPoint<double,3> point(1.63, 5.0, 5.2);\n\n\tbool isPointInside = shape.isPointInside(point);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 16: Point is on Back Face\nBOOST_AUTO_TEST_CASE(isPointInside_test16, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\teuc::EuclideanPoint<double,3> point(1.63, 0.0, 5.2);\n\n\tbool isPointInside = shape.isPointInside(point);\n\tBOOST_CHECK_EQUAL(isPointInside, true);\n}\n\n// Test 17: Point is Outside\nBOOST_AUTO_TEST_CASE(isPointInside_test17, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0909091,0.5,0.454545);\n\teuc::EuclideanPoint<double,3> trf(0.0909091,0.5,0.545455);\n\teuc::EuclideanPoint<double,3> blf(0.0,0.5,0.454545);\n\teuc::EuclideanPoint<double,3> brf(0.0,0.5,0.545455);\n\teuc::EuclideanPoint<double,3> tlb(0.0909091,0.583333,0.454545);\n\teuc::EuclideanPoint<double,3> trb(0.0909091,0.583333,0.545455);\n\teuc::EuclideanPoint<double,3> blb(0.0,0.583333,0.454545);\n\teuc::EuclideanPoint<double,3> brb(0.0,0.583333,0.545455);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\teuc::EuclideanPoint<double,3> point(0.23, 0.572, 0.5563);\n\n\tbool isPointInside = shape.isPointInside(point);\n\tBOOST_CHECK_EQUAL(isPointInside, false);\n}\n\n// Test 18: Point is on same plane as a face, but not in a face\n\n// ToDo: Point on Edges Tests\n\n\n// === getVolume ===\n// Test 1: Compute volume of cube\nBOOST_AUTO_TEST_CASE(getVolume_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\n\tdouble volume = shape.getVolume();\n\n\tBOOST_TEST(volume == 300.0);\n}\n\n// Test 2: Compute volume of more irregular hexahedron\n// ToDo\nBOOST_AUTO_TEST_CASE(getVolume_test2, * utf::tolerance(0.00001))\n{\n\n}\n\n// === getCentroid ===\n// Test 1: Compute correct centroid of a cube\nBOOST_AUTO_TEST_CASE(getCentroid_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\t\n\teuc::EuclideanPoint<double,3> centroid = shape.getCentroid();\n\tBOOST_TEST(centroid.cmp[0], 2.5);\n\tBOOST_TEST(centroid.cmp[1], 2.5);\n\tBOOST_TEST(centroid.cmp[2], 6.0);\n}\n\n// === isPointOnEdge ===\n// Test 1: Test point that is not on an edge\nBOOST_AUTO_TEST_CASE(isPointOnEdge_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\n\teuc::EuclideanPoint<double,3> point(3.4, 2.3, 4.7);\n\n\tbool onEdge = shape.isPointOnEdge(point);\n\n\tBOOST_CHECK_EQUAL(onEdge, false);\n}\n\n// Test 2: Test point that is on an edge\nBOOST_AUTO_TEST_CASE(isPointOnEdge_test2, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\n\teuc::EuclideanPoint<double,3> point(2.13, 5.0, 12.0);\n\n\tbool onEdge = shape.isPointOnEdge(point);\n\n\tBOOST_CHECK_EQUAL(onEdge, true);\n}\n\n// === isPointOnVertex ===\n// Test 1: Test point that is not on a vertex\nBOOST_AUTO_TEST_CASE(isPointOnVertex_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\n\teuc::EuclideanPoint<double,3> point(2.3, 5.0, 12.0);\n\n\tbool onEdge = shape.isPointOnVertex(point);\n\n\tBOOST_CHECK_EQUAL(onEdge, false);\n}\n\n// Test 2: Test point that is on a vertex\nBOOST_AUTO_TEST_CASE(isPointOnVertex_test2, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> tlf(0.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> trf(5.0, 5.0, 12.0);\n\teuc::EuclideanPoint<double,3> blf(0.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> brf(5.0, 5.0, 0.0);\n\teuc::EuclideanPoint<double,3> tlb(0.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> trb(5.0, 0.0, 12.0);\n\teuc::EuclideanPoint<double,3> blb(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> brb(5.0, 0.0, 0.0);\n\tQuadrilateral3D<double> top(trf, tlf, tlb, trb);\n\tQuadrilateral3D<double> bottom(brf, brb, blb, blf);\n\tQuadrilateral3D<double> front(trf, brf, blf, tlf);\n\tQuadrilateral3D<double> rear(tlb, blb, brb, trb);\n\tQuadrilateral3D<double> left(tlb, tlf, blf, blb);\n\tQuadrilateral3D<double> right(trf, trb, brb, brf);\n\tHexahedron<double> shape(top, bottom, front, rear, left, right);\n\n\teuc::EuclideanPoint<double,3> point(0.0, 0.0, 12.0);\n\n\tbool onEdge = shape.isPointOnVertex(point);\n\n\tBOOST_CHECK_EQUAL(onEdge, true);\n}\n", "meta": {"hexsha": "82bbb54ed8e7b86fd0a419bb76fdef3da6b1c0fc", "size": 25579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/geometry/shapes/implementation/component/HexahedronTests.cpp", "max_stars_repo_name": "thorbenlouw/CUP-CFD", "max_stars_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T10:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T14:43:19.000Z", "max_issues_repo_path": "tests/geometry/shapes/implementation/component/HexahedronTests.cpp", "max_issues_repo_name": "thorbenlouw/CUP-CFD", "max_issues_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T15:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T14:27:28.000Z", "max_forks_repo_path": "tests/geometry/shapes/implementation/component/HexahedronTests.cpp", "max_forks_repo_name": "thorbenlouw/CUP-CFD", "max_forks_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T15:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T15:24:24.000Z", "avg_line_length": 40.3454258675, "max_line_length": 81, "alphanum_fraction": 0.7004183119, "num_tokens": 10746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5152851368754497}}
{"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 n;\n    cin >> n;\n\n    int sum = 0;\n    int max = 0;\n    for(int i = 0 ; i < n ; ++i) {\n        int p;\n        cin >> p;\n        sum += p;\n        if(max < p) {\n            max = p;\n        }\n    }\n    sum -= max / 2;\n    cout << sum << endl;\n    return 0;\n}", "meta": {"hexsha": "912d0e50260020b87b40b834a15afb61a67c2380", "size": 568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc115/b/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": "abc115/b/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": "abc115/b/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": 16.7058823529, "max_line_length": 43, "alphanum_fraction": 0.5334507042, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5152851342226765}}
{"text": "\n/**\n  *\n  * @file SpatialPoint.cpp\n  * @author Naoki Takahashi\n  *\n  **/\n\n#include \"SpatialPoint.hpp\"\n\n#include <sstream>\n\n#include <Eigen/Geometry>\n#include <unsupported/Eigen/EulerAngles>\n\nnamespace Kinematics {\n\tnamespace Quantity {\n\t\ttemplate <typename Scalar>\n\t\tvoid SpatialPoint<Scalar>::reset() {\n\t\t\treset_point();\n\t\t\treset_angle();\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tvoid SpatialPoint<Scalar>::reset_point() {\n\t\t\tpoint_vector = Point::Zero();\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tvoid SpatialPoint<Scalar>::reset_angle() {\n\t\t\tq_rotation.vec() = Vector3::Zero();\n\t\t\tq_rotation.w() = 0;\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tconst typename SpatialPoint<Scalar>::Point &SpatialPoint<Scalar>::point() const {\n\t\t\treturn point_vector;\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tSpatialPoint<Scalar> &SpatialPoint<Scalar>::point(const Point &new_point) {\n\t\t\tpoint_vector = new_point;\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tSpatialPoint<Scalar> &SpatialPoint<Scalar>::point(const Scalar &x, const Scalar &y, const Scalar &z) {\n\t\t\tpoint_vector << x, y, z;\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tconst typename SpatialPoint<Scalar>::EulerAngles &SpatialPoint<Scalar>::angle() const {\n\t\t\tstatic Eigen::EulerAngles<Scalar, Eigen::EulerSystem<Eigen::EULER_X, Eigen::EULER_Y, Eigen::EULER_Z>> euler_angle_system;\n\n\t\t\teuler_angle_system = q_rotation;\n\n\t\t\treturn euler_angle_system.angles();\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tSpatialPoint<Scalar> &SpatialPoint<Scalar>::angle(const EulerAngles &new_angle) {\n\t\t\tq_rotation = Eigen::AngleAxis<Scalar>(new_angle.x(), EulerAngles::UnitX());\n\t\t\tq_rotation = q_rotation * Eigen::AngleAxis<Scalar>(new_angle.y(), EulerAngles::UnitY());\n\t\t\tq_rotation = q_rotation * Eigen::AngleAxis<Scalar>(new_angle.z(), EulerAngles::UnitZ());\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tSpatialPoint<Scalar> &SpatialPoint<Scalar>::angle(const Scalar &roll, const Scalar &pitch, const Scalar &yaw) {\n\t\t\tq_rotation = Eigen::AngleAxis<Scalar>(roll, EulerAngles::UnitX());\n\t\t\tq_rotation = q_rotation * Eigen::AngleAxis<Scalar>(pitch, EulerAngles::UnitY());\n\t\t\tq_rotation = q_rotation * Eigen::AngleAxis<Scalar>(yaw, EulerAngles::UnitZ());\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tconst typename SpatialPoint<Scalar>::Quaternion &SpatialPoint<Scalar>::quaternion() {\n\t\t\treturn q_rotation;\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tSpatialPoint<Scalar> &SpatialPoint<Scalar>::quaternion(const Quaternion &quaternion) {\n\t\t\tq_rotation = quaternion;\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tconst typename SpatialPoint<Scalar>::Matrix3x3 &SpatialPoint<Scalar>::rotation() {\n\t\t\tstatic Matrix3x3 rotation_matrix;\n\n\t\t\trotation_matrix = q_rotation.matrix();\n\n\t\t\treturn rotation_matrix;\n\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tSpatialPoint<Scalar> &SpatialPoint<Scalar>::rotation(const Matrix3x3 &rotation_matrix) {\n\t\t\tconst auto rrt = rotation_matrix * rotation_matrix.transpose();\n\n\t\t\tif(1e-5 < (Matrix3x3::Identity() - rrt).norm()) {\n\t\t\t\tstd::stringstream ss;\n\n\t\t\t\tss << \"Input Matrix is\\n\" << rotation_matrix << \"\\n\";\n\t\t\t\tss << \"\\nM*MT is\\n\" << rrt << \"\\n\";\n\t\t\t\tss << (Matrix3x3::Identity() - rrt).norm() << \"\\n\";\n\t\t\t\tss << \"\\n\";\n\n\t\t\t\tthrow std::runtime_error(\"Unknown type matrix from Kinematics::SpatialPoint\\n\" + ss.str());\n\t\t\t}\n\n\t\t\tq_rotation = rotation_matrix;\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tvoid SpatialPoint<Scalar>::operator ()(const Vector6 &new_point_with_angle_vector) {\n\t\t\tpoint(new_point_with_angle_vector.block(0, 0, Rank3, 1));\n\t\t\tangle(new_point_with_angle_vector.block(Rank3, 0, Rank3, 1));\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tconst typename SpatialPoint<Scalar>::Vector6 SpatialPoint<Scalar>::operator ()() {\n\t\t\tstatic Vector6 point_with_angle_vector;\n\n\t\t\tpoint_with_angle_vector << point(), angle();\n\n\t\t\treturn point_with_angle_vector;\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tSpatialPoint<Scalar> &SpatialPoint<Scalar>::operator += (const SpatialPoint<Scalar> &spatial_point) {\n\t\t\tif(this != &spatial_point) {\n\t\t\t\tstatic Eigen::EulerAngles<Scalar, Eigen::EulerSystem<Eigen::EULER_X, Eigen::EULER_Y, Eigen::EULER_Z>> euler_angle_system;\n\n\t\t\t\teuler_angle_system = spatial_point.q_rotation;\n\n\t\t\t\tthis->angle(this->angle() + euler_angle_system.angles());\n\n\t\t\t\tthis->point_vector += spatial_point.point_vector;\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tSpatialPoint<Scalar> &SpatialPoint<Scalar>::operator -= (const SpatialPoint<Scalar> &spatial_point) {\n\t\t\tif(this != &spatial_point) {\n\t\t\t\tstatic Eigen::EulerAngles<Scalar, Eigen::EulerSystem<Eigen::EULER_X, Eigen::EULER_Y, Eigen::EULER_Z>> euler_angle_system;\n\n\t\t\t\teuler_angle_system = spatial_point.q_rotation;\n\n\t\t\t\tthis->angle(this->angle() - euler_angle_system.angles());\n\n\t\t\t\tthis->point_vector -= spatial_point.point_vector;\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tbool SpatialPoint<Scalar>::operator == (const SpatialPoint &spatial_point) {\n\t\t\treturn \n\t\t\t\tthis->point_vector == spatial_point.point_vector\n\t\t\t\t&& this->q_rotation.vec() == spatial_point.q_rotation.vec()\n\t\t\t\t&& this->q_rotation.w() == spatial_point.q_rotation.w();\n\t\t}\n\n\t\ttemplate <typename Scalar>\n\t\tbool SpatialPoint<Scalar>::operator != (const SpatialPoint &spatial_point) {\n\t\t\treturn !this->operator == (spatial_point);\n\t\t}\n\n\t\ttemplate class SpatialPoint<float>;\n\t\ttemplate class SpatialPoint<double>;\n\t\ttemplate class SpatialPoint<long double>;\n\t}\n}\n\n", "meta": {"hexsha": "e474a20713217135b483b6199ef39dbf2ab5a965", "size": 5410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Kinematics/Quantity/SpatialPoint.cpp", "max_stars_repo_name": "NaokiTakahashi12/OpenHumanoidController", "max_stars_repo_head_hexsha": "ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-23T06:21:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-23T06:21:47.000Z", "max_issues_repo_path": "src/Kinematics/Quantity/SpatialPoint.cpp", "max_issues_repo_name": "NaokiTakahashi12/hc-early", "max_issues_repo_head_hexsha": "ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T00:17:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-09T23:00:43.000Z", "max_forks_repo_path": "src/Kinematics/Quantity/SpatialPoint.cpp", "max_forks_repo_name": "NaokiTakahashi12/OpenHumanoidController", "max_forks_repo_head_hexsha": "ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d", "max_forks_repo_licenses": ["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.9304812834, "max_line_length": 125, "alphanum_fraction": 0.7085027726, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5152787853106958}}
{"text": "//\n// Copyright Fabien Dekeyser, Quoc-Cuong Pham 2008\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#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_HEGV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_HEGV_HPP\n\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/lapack/lapack.h>\n#include <boost/numeric/bindings/lapack/workspace.hpp>\n#include <boost/numeric/bindings/traits/detail/array.hpp>\n// #include <boost/numeric/bindings/traits/std_vector.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits.hpp>\n#endif \n\n#include <cassert>\n\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace lapack {\n\n    ///////////////////////////////////////////////////////////////////\n    //\n    // hegv\n    // \n    ///////////////////////////////////////////////////////////////////\n\n    /* \n     *  hegv() computes all the eigenvalues, and optionally, the eigenvectors\n     *  of a real generalized symmetric-definite eigenproblem, of the form\n     *  A*x=(lambda)*B*x,  A*Bx=(lambda)*x,  or B*A*x=(lambda)*x.\n     *  Here A and B are assumed to be symmetric and B is also\n     *  positive definite.\n     * TYPE   (input) INTEGER\n     *          Specifies the problem type to be solved:\n     *          = 1:  A*x = (lambda)*B*x\n     *          = 2:  A*B*x = (lambda)*x\n     *          = 3:  B*A*x = (lambda)*x\n     *\n     *  JOBZ    (input) CHARACTER*1\n     *          = 'N':  Compute eigenvalues only;\n     *          = 'V':  Compute eigenvalues and eigenvectors.\n     *\n     *  UPLO    (input) CHARACTER*1\n     *          = 'U':  Upper triangles of A and B are stored;\n     *          = 'L':  Lower triangles of A and B are stored.\n     *\n     *  N       (input) INTEGER\n     *          The order of the matrices A and B.  N >= 0.\n     *\n     *  A       (input/output) DOUBLE PRECISION array, dimension (LDA, N)\n     *          On entry, the symmetric matrix A.  If UPLO = 'U', the\n     *          leading N-by-N upper triangular part of A contains the\n     *          upper triangular part of the matrix A.  If UPLO = 'L',\n     *          the leading N-by-N lower triangular part of A contains\n     *          the lower triangular part of the matrix A.\n     *\n     *          On exit, if JOBZ = 'V', then if INFO = 0, A contains the\n     *          matrix Z of eigenvectors.  The eigenvectors are normalized\n     *          as follows:\n     *          if ITYPE = 1 or 2, Z**T*B*Z = I;\n     *          if ITYPE = 3, Z**T*inv(B)*Z = I.\n     *          If JOBZ = 'N', then on exit the upper triangle (if UPLO='U')\n     *          or the lower triangle (if UPLO='L') of A, including the\n     *          diagonal, is destroyed.\n     *\n     *  LDA     (input) INTEGER\n     *          The leading dimension of the array A.  LDA >= max(1,N).\n     *\n     *  B       (input/output) DOUBLE PRECISION array, dimension (LDB, N)\n     *          On entry, the symmetric positive definite matrix B.\n     *          If UPLO = 'U', the leading N-by-N upper triangular part of B\n     *          contains the upper triangular part of the matrix B.\n     *          If UPLO = 'L', the leading N-by-N lower triangular part of B\n     *          contains the lower triangular part of the matrix B.\n     *\n     *          On exit, if INFO <= N, the part of B containing the matrix is\n     *          overwritten by the triangular factor U or L from the Cholesky\n     *          factorization B = U**T*U or B = L*L**T.\n     *\n     *  LDB     (input) INTEGER\n     *          The leading dimension of the array B.  LDB >= max(1,N).\n     *\n     *  W       (output) DOUBLE PRECISION array, dimension (N)\n     *          If INFO = 0, the eigenvalues in ascending order.\n     *\n     *  WORK    (workspace/output) DOUBLE PRECISION array, dimension (MAX(1,LWORK))\n     *          On exit, if INFO = 0, WORK(1) returns the optimal LWORK.\n     *\n     *  LWORK   (input) INTEGER\n     *          The length of the array WORK.  LWORK >= max(1,3*N-1).\n     *          For optimal efficiency, LWORK >= (NB+2)*N,\n     *          where NB is the blocksize for DSYTRD returned by ILAENV.\n     *\n     *          If LWORK = -1, then a workspace query is assumed; the routine\n     *          only calculates the optimal size of the WORK array, returns\n     *          this value as the first entry of the WORK array, and no error\n     *          message related to LWORK is issued by XERBLA.\n     *\n     *  INFO    (output) INTEGER\n     *          = 0:  successful exit\n     *          < 0:  if INFO = -i, the i-th argument had an illegal value\n     *          > 0:  DPOTRF or DSYEV returned an error code:\n     *             <= N:  if INFO = i, DSYEV failed to converge;\n     *                    i off-diagonal elements of an intermediate\n     *                    tridiagonal form did not converge to zero;\n     *             > N:   if INFO = N + i, for 1 <= i <= N, then the leading\n     *                    minor of order i of B is not positive definite.\n     *                    The factorization of B could not be completed and\n     *                    no eigenvalues or eigenvectors were computed.\n     *\n     */ \n\n    namespace detail {\n\n      inline \n      void hegv (int const itype, char const jobz, char const uplo, int const n, \n                 float *a, int const lda, float *b, int const ldb, \n                 float *w, float *work, int const lwork, int& info)\n      {\n        LAPACK_SSYGV (&itype, &jobz, &uplo, &n, a, &lda, b, &ldb, w, work, &lwork, &info);\n      }\n\n      inline \n      void hegv (int const itype, char const jobz, char const uplo, int const n, \n                 double *a, int const lda, double *b, int const ldb, \n                 double *w, double *work, int const lwork, int& info)\n      {\n        LAPACK_DSYGV (&itype, &jobz, &uplo, &n, a, &lda, b, &ldb, w, work, &lwork, &info);\n      }\n\n      inline \n      void hegv (int const itype, char const jobz, char const uplo, int const n, \n                 traits::complex_f *a, int const lda, traits::complex_f *b, int const ldb, \n                 float *w, traits::complex_f *work, int const lwork, float *rwork, int& info)\n      {\n        LAPACK_CHEGV (&itype, &jobz, &uplo, &n, traits::complex_ptr(a), &lda,\n          traits::complex_ptr(b), &ldb, w, traits::complex_ptr(work), &lwork, rwork, &info);\n      }\n\n      inline \n      void hegv (int const itype, char const jobz, char const uplo, int const n, \n                 traits::complex_d *a, int const lda, traits::complex_d *b, int const ldb, \n                 double *w, traits::complex_d *work, int const lwork, double *rwork, int& info)\n      {\n        LAPACK_ZHEGV (&itype, &jobz, &uplo, &n, traits::complex_ptr(a), &lda,\n          traits::complex_ptr(b), &ldb, w, traits::complex_ptr(work), &lwork, rwork, &info);\n      }\n    }  // namespace detail\n\n    namespace detail {\n\n      template <int N>\n      struct Hegv{};\n\n      /// Handling of workspace in the case of one workarray.\n      template <>\n      struct Hegv< 1 > {\n        // Function that allocates work arrays\n        template <typename T, typename R>\n        void operator() (\n                 int const itype, char const jobz, char const uplo, int const n, \n                 T *a, int const lda, T *b, int const ldb, \n                 R *w, optimal_workspace, int& info ) {\n\n           traits::detail::array<T> work( std::max<int>(1,34*n) );\n\n           detail::hegv(itype, jobz, uplo, n, a, lda, b, ldb, w,\n             traits::vector_storage (work), traits::vector_size (work), info);\n        }\n        // Function that allocates work arrays\n        template <typename T, typename R>\n        void operator() (\n                 int const itype, char const jobz, char const uplo, int const n, \n                 T *a, int const lda, T *b, int const ldb, \n                 R *w, minimal_workspace, int& info ) {\n\n           traits::detail::array<T> work( std::max<int>(1,3*n-1) );\n\n           detail::hegv(itype, jobz, uplo, n, a, lda, b, ldb, w,\n             traits::vector_storage (work), traits::vector_size (work), info);\n        }\n        // Function that uses given workarrays\n        template <typename T, typename R, typename W>\n        void operator() (\n                 int const itype, char const jobz, char const uplo, int const n, \n                 T *a, int const lda, T *b, int const ldb, \n                 R *w, detail::workspace1<W> work, int& info ) {\n\n           assert (traits::vector_size (work.w_) >= 3*n-1);\n\n           detail::hegv(itype, jobz, uplo, n, a, lda, b, ldb, w,\n             traits::vector_storage (work.w_), traits::vector_size (work.w_), info);\n        }\n      };\n\n      /// Handling of workspace in the case of two workarrays.\n      template <>\n      struct Hegv< 2 > {\n        // Function that allocates work arrays\n        template <typename T, typename R>\n        void operator() (\n                 int const itype, char const jobz, char const uplo, int const n, \n                 T *a, int const lda, T *b, int const ldb, \n                 R *w, optimal_workspace, int& info ) {\n\n           traits::detail::array<T> work( std::max<int>(1,34*n) );\n           traits::detail::array<R> rwork( std::max<int>(1,3*n-2) );\n\n           detail::hegv(itype, jobz, uplo, n, a, lda, b, ldb, w,\n             traits::vector_storage (work), traits::vector_size (work),\n             traits::vector_storage (rwork), info);\n        }\n        // Function that allocates work arrays\n        template <typename T, typename R>\n        void operator() (\n                 int const itype, char const jobz, char const uplo, int const n, \n                 T *a, int const lda, T *b, int const ldb, \n                 R *w, minimal_workspace, int& info ) {\n\n           traits::detail::array<T> work( std::max<int>(1,2*n-1) );\n           traits::detail::array<R> rwork( std::max<int>(1,3*n-2) );\n\n           detail::hegv(itype, jobz, uplo, n, a, lda, b, ldb, w,\n             traits::vector_storage (work), traits::vector_size (work),\n             traits::vector_storage (rwork), info);\n        }\n        // Function that uses given workarrays\n        template <typename T, typename R, typename WC, typename WR>\n        void operator() (\n                 int const itype, char const jobz, char const uplo, int const n, \n                 T *a, int const lda, T *b, int const ldb, \n                 R *w, detail::workspace2<WC,WR> work, int& info ) {\n\n           assert (traits::vector_size (work.w_) >= 2*n-1);\n           assert (traits::vector_size (work.wr_) >= 3*n-2);\n\n           detail::hegv(itype, jobz, uplo, n, a, lda, b, ldb, w,\n             traits::vector_storage (work.w_), traits::vector_size (work.w_),\n             traits::vector_storage (work.wr_), info);\n        }\n      };    } // namespace detail\n\n    template <typename A, typename B, typename W, typename Work>\n    int hegv (int itype, char jobz, char uplo, A& a, B& b, W& w, Work work = optimal_workspace()) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<A>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      int const n = traits::matrix_size1 (a);\n      assert ( n>0 );\n      assert (traits::matrix_size2 (a)==n); \n      assert (traits::leading_dimension (a)>=n); \n      assert (traits::vector_size (w)==n); \n\n      int const nb = traits::matrix_size1 (b);\n      assert ( nb>0 );\n      assert (traits::matrix_size2 (b)==nb); \n      assert (traits::leading_dimension (b)>=nb); \n      assert ( n== nb);\n\n      assert ( uplo=='U' || uplo=='L' );\n      assert ( jobz=='N' || jobz=='V' );\n\n      assert( itype==1 || itype==2 || itype==3);\n\n\n      int info;\n      detail::Hegv< n_workspace_args<typename A::value_type>::value >() (\n                   itype, jobz, uplo, n,\n                   traits::matrix_storage (a), \n                   traits::leading_dimension (a),\n                   traits::matrix_storage (b), \n                   traits::leading_dimension (b),\n                   traits::vector_storage (w),  \n                   work,\n                   info);\n      return info; \n    }\n  }\n\n}}}\n\n#endif\n", "meta": {"hexsha": "a4057bf91fa62867f79bc148cf4197dcb5f92fa7", "size": 12288, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/lapack/hegv.hpp", "max_stars_repo_name": "inducer/boost-numeric-bindings", "max_stars_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-11-13T16:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T15:37:19.000Z", "max_issues_repo_path": "openrave/plugins/include/boost/numeric/bindings/lapack/hegv.hpp", "max_issues_repo_name": "jdsika/holy", "max_issues_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-06-13T01:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-14T00:38:27.000Z", "max_forks_repo_path": "openrave/plugins/include/boost/numeric/bindings/lapack/hegv.hpp", "max_forks_repo_name": "jdsika/holy", "max_forks_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-05T20:18:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T20:18:25.000Z", "avg_line_length": 41.3737373737, "max_line_length": 99, "alphanum_fraction": 0.5460611979, "num_tokens": 3306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5152787806413286}}
{"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/ButterworthHPFilter.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/SlideUDFilter.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 EnvelopeGate\n{\n\n  using ArrayXd = Eigen::ArrayXd;\n\npublic:\n  EnvelopeGate(index maxSize)\n  {\n    mInputStorage = ArrayXd(maxSize);\n    mOutputStorage = ArrayXd(maxSize);\n  }\n\n  void init(double onThreshold, double offThreshold, double hiPassFreq,\n            index minTimeAboveThreshold, index upwardLookupTime,\n            index minTimeBelowThreshold, index downwardLookupTime)\n  {\n    using namespace std;\n\n    mMinTimeAboveThreshold = minTimeAboveThreshold;\n    mUpwardLookupTime = upwardLookupTime;\n    mMinTimeBelowThreshold = minTimeBelowThreshold,\n    mDownwardLookupTime = downwardLookupTime;\n    mDownwardLatency = max<index>(minTimeBelowThreshold, mDownwardLookupTime);\n    mLatency = max<index>(mMinTimeAboveThreshold + mUpwardLookupTime,\n                          mDownwardLatency);\n    if (mLatency < 0) mLatency = 1;\n    mHiPassFreq = hiPassFreq;\n    initFilters(mHiPassFreq);\n    double initVal = min(onThreshold, offThreshold) - 1;\n    initBuffers(initVal);\n    mSlide.init(initVal);\n    mInputState = false;\n    mOutputState = false;\n    mOnStateCount = 0;\n    mOffStateCount = 0;\n    mEventCount = 0;\n    mSilenceCount = 0;\n    mInitialized = true;\n  }\n\n  double processSample(const double in, double onThreshold, double offThreshold,\n                       index rampUpTime, index rampDownTime, double hiPassFreq,\n                       index minEventDuration, index minSilenceDuration)\n  {\n    using namespace std;\n    assert(mInitialized);\n\n    mSlide.updateCoeffs(rampUpTime, rampDownTime);\n\n    double filtered = in;\n    if (hiPassFreq != mHiPassFreq)\n    {\n      initFilters(hiPassFreq);\n      mHiPassFreq = hiPassFreq;\n    }\n    if (mHiPassFreq > 0)\n      filtered = mHiPass2.processSample(mHiPass1.processSample(in));\n\n    double rectified = abs(filtered);\n    double dB = 20 * log10(rectified);\n    double floor = min(offThreshold, onThreshold) - 1;\n    double clipped = max(dB, floor);\n    double smoothed = mSlide.processSample(clipped);\n    bool   forcedState = false;\n\n    // case 1: we are waiting for event to finish\n    if (mOutputState && mEventCount > 0)\n    {\n      if (mEventCount >= minEventDuration) { mEventCount = 0; }\n      else\n      {\n        forcedState = true;\n        mOutputBuffer(mWriteHead) = 1;\n        mEventCount++;\n      }\n      // case 2: we are waiting for silence to finish\n    }\n    else if (!mOutputState && mSilenceCount > 0)\n    {\n      if (mSilenceCount >= minSilenceDuration) { mSilenceCount = 0; }\n      else\n      {\n        forcedState = true;\n        mOutputBuffer(mWriteHead) = 0;\n        mSilenceCount++;\n      }\n    }\n    // case 3: need to compute state\n    if (!forcedState)\n    {\n      bool nextState = mInputState;\n      if (!mInputState && smoothed >= onThreshold) { nextState = true; }\n      if (mInputState && smoothed <= offThreshold) { nextState = false; }\n      updateCounters(nextState);\n      // establish and refine\n      if (!mOutputState && mOnStateCount >= mMinTimeAboveThreshold &&\n          mFillCount >= mLatency)\n      {\n        index onsetIndex =\n            refineStart(mWriteHead - mMinTimeAboveThreshold - mUpwardLookupTime,\n                        mUpwardLookupTime);\n\n        index blockSize = mWriteHead > onsetIndex\n                              ? mWriteHead - onsetIndex\n                              : (mLatency - onsetIndex) + mWriteHead;\n\n        index size = onsetIndex + blockSize > mLatency ? mLatency - onsetIndex\n                                                       : blockSize;\n\n        mOutputBuffer.segment(onsetIndex, size) = 1;\n        mOutputBuffer.segment(0, blockSize - size) = 1;\n\n        mEventCount = mOnStateCount;\n        mOutputState = true; // we are officially on\n      }\n      else if (mOutputState && mOffStateCount >= mDownwardLatency &&\n               mFillCount >= mLatency)\n      {\n\n        index offsetIndex =\n            refineStart(mWriteHead - mDownwardLatency, mDownwardLookupTime);\n\n        index blockSize = mWriteHead > offsetIndex\n                              ? mWriteHead - offsetIndex\n                              : (mLatency - offsetIndex) + mWriteHead;\n\n        index size = offsetIndex + blockSize > mLatency ? mLatency - offsetIndex\n                                                        : blockSize;\n\n        mOutputBuffer.segment(offsetIndex, size) = 0;\n        mOutputBuffer.segment(0, blockSize - size) = 0;\n\n        mSilenceCount = mOffStateCount;\n        mOutputState = false; // we are officially off\n      }\n\n      mOutputBuffer(mWriteHead) = mOutputState ? 1 : 0;\n      \n      mInputState = nextState;\n    }\n\n    mInputBuffer(mWriteHead) = smoothed;\n    \n    if (mFillCount < mLatency) mFillCount++;\n    double result = mOutputBuffer(mReadHead); \n    mWriteHead++;     \n    mWriteHead = mWriteHead % mOutputBuffer.size(); \n    mReadHead++; \n    mReadHead = mReadHead % mOutputBuffer.size(); \n    return result;     \n}\n  index getLatency() { return mLatency; }\n  bool  initialized() { return mInitialized; }\n\n\nprivate:\n  void initBuffers(double initialValue)\n  {\n    using namespace std;\n    mInputBuffer = mInputStorage.segment(0, max<index>(mLatency, 1))\n                       .setConstant(initialValue);\n    mOutputBuffer =\n        mOutputStorage.segment(0, max<index>(mLatency, 1)).setZero();\n    mInputState = false;\n    mOutputState = false;\n    mFillCount = max<index>(mLatency, 1);\n    mWriteHead = mOutputBuffer.size() - 1;\n    mReadHead = 0;\n  }\n\n  void initFilters(double cutoff)\n  {\n    mHiPass1.init(cutoff);\n    mHiPass2.init(cutoff);\n  }\n\n  index refineStart(index start, index nSamples)\n  {\n\n    using Eigen::Array2d;\n    using Eigen::Array2i;\n\n    index circularStart = start < 0 ? mLatency + start : start;\n\n    if (nSamples < 2)\n      return circularStart + nSamples < mLatency\n                 ? circularStart + nSamples\n                 : circularStart + nSamples - mLatency;\n\n    index circularNSamples = circularStart + nSamples > mLatency\n                                 ? mLatency - circularStart\n                                 : nSamples;\n\n    if (circularNSamples == nSamples)\n    {\n      index argMin;\n      mInputBuffer.segment(circularStart, nSamples).minCoeff(&argMin);\n      return circularStart + argMin;\n    }\n    else\n    {\n      Array2i argMins;\n      mInputBuffer.segment(circularStart, circularNSamples)\n          .minCoeff(argMins.data());\n      mInputBuffer.segment(0, nSamples - circularNSamples)\n          .minCoeff(argMins.data() + 1);\n      Array2d mins = {\n          mInputBuffer.segment(circularStart, circularNSamples)(argMins(0)),\n          mInputBuffer.segment(0, nSamples - circularNSamples)(argMins(1))};\n      index whichArgMin;\n      mins.minCoeff(&whichArgMin);\n\n      return whichArgMin == 0 ? circularStart + argMins(0) : argMins(1);\n    }\n  }\n\n  void updateCounters(bool nextState)\n  {\n    if (!mInputState && nextState)\n    {\n      mOffStateCount = 0;\n      mOnStateCount = 1;\n    }\n    else if (mInputState && !nextState)\n    {\n      mOnStateCount = 0;\n      mOffStateCount = 1;\n    }\n    else if (mInputState && nextState)\n    {\n      mOnStateCount++;\n    }\n    else if (!mInputState && !nextState)\n    {\n      mOffStateCount++;\n    }\n  }\n\n  index  mLatency;\n  index  mFillCount;\n  double mHiPassFreq{0};\n\n  index mMinTimeAboveThreshold{440};\n  index mDownwardLookupTime{10};\n  index mDownwardLatency;\n  index mMinTimeBelowThreshold{10};\n  index mUpwardLookupTime{24};\n\n  ArrayXd mInputBuffer;\n  ArrayXd mOutputBuffer;\n  ArrayXd mInputStorage;\n  ArrayXd mOutputStorage;\n  index   mWriteHead;\n  index   mReadHead;\n\n  bool mInputState{false};\n  bool mOutputState{false};\n\n  index mOnStateCount{0};\n  index mOffStateCount{0};\n  index mEventCount{0};\n  index mSilenceCount{0};\n  bool  mInitialized{false};\n\n  ButterworthHPFilter mHiPass1;\n  ButterworthHPFilter mHiPass2;\n  SlideUDFilter       mSlide;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "b19d4b6076172825e1507ce17a6ba9e4bcf2c2a6", "size": 8574, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/EnvelopeGate.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/EnvelopeGate.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/EnvelopeGate.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 29.1632653061, "max_line_length": 80, "alphanum_fraction": 0.6368089573, "num_tokens": 2203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5152787713025935}}
{"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    mp::cpp_int n;\n    cin >> n;\n\n    vector<mp::cpp_int> arr(6); // \u79fb\u52d5\u6642\u9593\n    vector<mp::cpp_int> term(6); // \u30bf\u30fc\u30f3\u6570\n    arr[0] = INT64_MAX;\n    term[0] = 0; // dummy\n    for(int i = 0 ; i < 5 ; ++i) {\n        cin >> arr[i + 1];\n    }\n\n    for(int i = 0 ; i < 5 ; ++i) {\n        if (arr[i + 1] > arr[i]) {\n            // \u524d\u56de\u306e\u79fb\u52d5\u624b\u6bb5\u306e\u307b\u3046\u304c\u9045\u3044\u306e\u3067\u3001\u305d\u3063\u3061\u306b\u5f15\u3063\u5f35\u3089\u308c\u308b\n            term[i + 1] = term[i] + 1; // +1\u306f1\u30bf\u30fc\u30f3\u306e\u30c7\u30a3\u30ec\u30a4\n        } else {\n            mp::cpp_int t = (n / arr[i + 1]) + (n % arr[i + 1] == 0 ? 0 : 1) + i;\n            mp::cpp_int recent = term[i] + 1;\n            term[i + 1] = t < recent ? recent : t;\n        }\n    }\n    auto result = term[term.size() - 1];\n    cout << result << endl;\n    return 0;\n}", "meta": {"hexsha": "dff7814f4722c5a16624a3be2106651258c9604e", "size": 1000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc123/c/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": "abc123/c/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": "abc123/c/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": 23.8095238095, "max_line_length": 81, "alphanum_fraction": 0.512, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5152787713025935}}
{"text": "#include \"vtkNonRigidICP.h\"\n#include <Eigen/Sparse>\n#include <vtkDoubleArray.h>\n#include <vtkInformation.h>\n#include <vtkInformationVector.h>\n#include <vtkKdTreePointLocator.h>\n#include <vtkPointData.h>\n#include <vtkPolyDataNormals.h>\n//#include <chrono>\n\nvtkStandardNewMacro(vtkNonRigidICP);\n\nusing Triplet = Eigen::Triplet<double>;\n\nvoid vtkNonRigidICP::Cleanup()\n{\n\toutputCellArray = NULL;\n\tfixedKdTree = NULL;\n}\n\nint vtkNonRigidICP::RequestData(vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVec, vtkInformationVector* outputVec)\n{\n\t// Get input polys\n\tvtkInformation* inInfo1 = inputVec[0]->GetInformationObject(0);\n\tvtkPolyData* fixedPolyData = vtkPolyData::SafeDownCast(inInfo1->Get(vtkDataObject::DATA_OBJECT()));\n\tvtkInformation* inInfo2 = inputVec[1]->GetInformationObject(0);\n\tvtkPolyData* movingPolyData = vtkPolyData::SafeDownCast(inInfo2->Get(vtkDataObject::DATA_OBJECT()));\n\t// Get output poly\n\tvtkInformation* outInfo = outputVec->GetInformationObject(0);\n\tvtkPolyData* outputMovingPolyData = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n\toutputMovingPolyData->DeepCopy(movingPolyData);\n\n\t// Only compute if we haven't stored a previous one\n\tif (outputCellArray == NULL)\n\t{\n\t\t// Compute the edge only topology of the output polygon\n\t\toutputCellArray = vtkSmartPointer<vtkCellArray>::New();\n\t\tfor (vtkIdType i = 0; i < outputMovingPolyData->GetNumberOfCells(); i++)\n\t\t{\n\t\t\tvtkCell* cell = outputMovingPolyData->GetCell(i);\n\t\t\tif (cell->GetNumberOfPoints() == 3)\n\t\t\t{\n\t\t\t\tvtkIdType ptIds1[2] = { cell->GetPointId(0), cell->GetPointId(1) };\n\t\t\t\toutputCellArray->InsertNextCell(2, ptIds1);\n\t\t\t\tvtkIdType ptIds2[2] = { cell->GetPointId(1), cell->GetPointId(2) };\n\t\t\t\toutputCellArray->InsertNextCell(2, ptIds2);\n\t\t\t\tvtkIdType ptIds3[2] = { cell->GetPointId(2), cell->GetPointId(0) };\n\t\t\t\toutputCellArray->InsertNextCell(2, ptIds3);\n\t\t\t}\n\t\t\telse if (cell->GetNumberOfPoints() == 2)\n\t\t\t{\n\t\t\t\tvtkIdType ptIds[2] = { cell->GetPointId(0), cell->GetPointId(1) };\n\t\t\t\toutputCellArray->InsertNextCell(2, ptIds);\n\t\t\t}\n\t\t}\n\t}\n\t// Setup a kdtree for nearest neighbor searches on the fixed poly\n\tif (fixedKdTree == NULL)\n\t{\n\t\tfixedKdTree = vtkSmartPointer<vtkKdTreePointLocator>::New();\n\t\tfixedKdTree->SetDataSet(fixedPolyData);\n\t\tfixedKdTree->BuildLocator();\n\t}\n\n\tdouble* targetBounds = fixedPolyData->GetBounds();\n\tdouble maxDist = std::pow(std::pow(targetBounds[1] - targetBounds[0], 2) + std::pow(targetBounds[3] - targetBounds[2], 2) + std::pow(targetBounds[5] - targetBounds[4], 2), 1.0 / 3.0);\n\n\tconst vtkIdType fixedPolyNumberOfPoints = fixedPolyData->GetNumberOfPoints();\n\tconst vtkIdType movingPolyNumberOfPoints = outputMovingPolyData->GetNumberOfPoints();\n\tconst vtkIdType movingPolyNumberOfCells = outputCellArray->GetNumberOfCells();\n\n\tdouble stiffness = Stiffness;\n\tvtkNew<vtkIdTypeArray> correspondences;\n\tcorrespondences->SetName(\"Correspondences\");\n\tcorrespondences->SetNumberOfValues(movingPolyNumberOfPoints);\n\n\tfor (unsigned int iter = 0; iter < NumberOfIterations; iter++)\n\t{\n\t\tvtkNew<vtkKdTreePointLocator> movingKdTree;\n\t\tmovingKdTree->SetDataSet(movingPolyData);\n\t\tmovingKdTree->Update();\n\n\t\tvtkNew<vtkPolyDataNormals> normalsFilter;\n\t\tnormalsFilter->SetInputData(outputMovingPolyData);\n\t\tnormalsFilter->Update();\n\t\tvtkDataArray* normalsArray = normalsFilter->GetOutput()->GetPointData()->GetNormals();\n\n\t\tcorrespondences->Fill(-1);\n\t\t// Find the forward correspondences of all the moving points\n\t\tfor (vtkIdType i = 0; i < movingPolyNumberOfPoints; i++)\n\t\t{\n\t\t\tdouble pt1[3];\n\t\t\toutputMovingPolyData->GetPoint(i, pt1);\n\n\t\t\tconst vtkIdType closestPtIndex = fixedKdTree->FindClosestPoint(pt1);\n\t\t\tcorrespondences->SetValue(i, closestPtIndex);\n\t\t}\n\n\t\t// Construct matrix A, composed of MG and WD\n\t\tEigen::SparseMatrix<double> A(4 * movingPolyNumberOfCells + movingPolyNumberOfPoints, 4 * movingPolyNumberOfPoints);\n\n\t\tstd::vector<Triplet> ATripletList;\n\t\tATripletList.reserve(movingPolyNumberOfCells * 8 + 4 * movingPolyNumberOfPoints);\n\n\t\t// Construct M kronecker G, regularization term resulting from the topology of the mesh\n\t\tvtkNew<vtkIdList> idList;\n\t\toutputCellArray->InitTraversal();\n\t\tfor (vtkIdType i = 0; i < movingPolyNumberOfCells; i++)\n\t\t{\n\t\t\toutputCellArray->GetNextCell(idList);\n\t\t\tconst vtkIdType id1 = idList->GetId(0);\n\t\t\tconst vtkIdType id2 = idList->GetId(1);\n\n\t\t\tfor (unsigned int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tATripletList.push_back(Triplet(4 * i + j, 4 * id1 + j, 1.0  * stiffness));\n\t\t\t}\n\t\t\tATripletList.push_back(Triplet(4 * i + 3, 4 * id1 + 3, SkewWeight * stiffness));\n\n\t\t\tfor (unsigned int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tATripletList.push_back(Triplet(4 * i + j, 4 * id2 + j, -1.0 * stiffness));\n\t\t\t}\n\t\t\tATripletList.push_back(Triplet(4 * i + 3, 4 * id2 + 3, -SkewWeight * stiffness));\n\t\t}\n\t\t// Construct WD, for the distance term\n\t\tfor (vtkIdType i = 0; i < movingPolyNumberOfPoints; i++)\n\t\t{\n\t\t\tconst double w = (correspondences->GetValue(i) != -1) ? 1.0 : 0.0;\n\t\t\tdouble pt[3];\n\t\t\toutputMovingPolyData->GetPoint(i, pt);\n\t\t\tfor (vtkIdType j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tATripletList.push_back(Triplet(4 * movingPolyNumberOfCells + i, i * 4 + j, pt[j] * w));\n\t\t\t}\n\t\t\tATripletList.push_back(Triplet(4 * movingPolyNumberOfCells + i, i * 4 + 3, 1.0 * w));\n\t\t}\n\t\tA.setFromTriplets(ATripletList.begin(), ATripletList.end());\n\n\t\tEigen::SparseMatrix<double> AT(A.cols(), A.rows());\n\t\tAT = A.transpose();\n\t\tEigen::SparseMatrix<double> ATA(4 * movingPolyNumberOfPoints, 4 * movingPolyNumberOfPoints);\n\t\tATA = AT * A;\n\n\n\t\t// Construct matrix B, resulting from correspodences of the points (data term)\n\t\tEigen::MatrixXd B(4 * movingPolyNumberOfCells + movingPolyNumberOfPoints, 3);\n\t\tB.setZero();\n\n\t\tfor (unsigned int i = 0; i < movingPolyNumberOfPoints; i++)\n\t\t{\n\t\t\tconst vtkIdType correspondence = correspondences->GetValue(i);\n\t\t\tconst double w = (correspondence != -1) ? 1.0 : 0.0;\n\t\t\tdouble pt[3];\n\t\t\tfixedPolyData->GetPoint(correspondence, pt);\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tB(4 * movingPolyNumberOfCells + i, j) = pt[j] * w;\n\t\t\t}\n\t\t}\n\n\t\tEigen::MatrixXd ATB(4 * movingPolyNumberOfPoints, 3);\n\t\tATB.setZero();\n\t\tATB = AT * B;\n\n\n\t\t// Write the matrices\n\t\t/*Eigen::saveMarket(AmatrixFinal, \"C:/Users/Andx_/Desktop/a.txt\");\n\t\tEigen::saveMarket(BmatrixFinal, \"C:/Users/Andx_/Desktop/b.txt\");*/\n\n\t\tEigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> solver;\n\t\tsolver.analyzePattern(ATA);\n\t\tsolver.factorize(ATA);\n\t\tif (solver.info() != Eigen::Success)\n\t\t\tprintf(\"Decomposition Failed.\\n\");\n\t\tEigen::MatrixXd X(4 * movingPolyNumberOfPoints, 3);\n\t\tX.setZero();\n\t\tX = solver.solve(ATB);\n\n\t\t// Do the transformation\n\t\tvtkPoints* pts = outputMovingPolyData->GetPoints();\n\t\tfor (vtkIdType i = 0; i < movingPolyNumberOfPoints; i++)\n\t\t{\n\t\t\tdouble pt[3];\n\t\t\tpts->GetPoint(i, pt);\n\n\t\t\tdouble results[3] = { 0.0, 0.0, 0.0 };\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tresults[j] =\n\t\t\t\t\tpt[0] * X(i * 4 + 0, j) +\n\t\t\t\t\tpt[1] * X(i * 4 + 1, j) +\n\t\t\t\t\tpt[2] * X(i * 4 + 2, j) +\n\t\t\t\t\t1.0 * X(i * 4 + 3, j);\n\t\t\t}\n\t\t\t//printf(\"%f,%f,%f,%f\\n\", X(i * 4 + 0, 0), X(i * 4 + 1, 1), X(i * 4 + 2, 2), X(i * 4 + 3, 3));\n\n\t\t\tpts->SetPoint(i, results[0], results[1], results[2]);\n\t\t}\n\n\t\t// Invokes the progress update event\n\t\tif (iter % 4 == 0)\n\t\t\tUpdateProgress(static_cast<double>(iter) / NumberOfIterations);\n\t}\n\n\tif (!InteractiveExecute)\n\t\tCleanup();\n\n\tif (OutputDisplacements)\n\t{\n\t\t// Stash a copy of the registered/moved surface\n\t\tvtkNew<vtkPolyData> registeredPolyData;\n\t\tregisteredPolyData->DeepCopy(outputMovingPolyData);\n\n\t\t// Bring back the original polygon\n\t\toutputMovingPolyData->DeepCopy(movingPolyData);\n\n\t\t// Setup an array of displacements\n\t\tvtkNew<vtkDoubleArray> displacements;\n\t\tdisplacements->SetName(\"Displacements\");\n\t\tdisplacements->SetNumberOfComponents(3);\n\t\tdisplacements->SetNumberOfTuples(movingPolyNumberOfPoints);\n\n\t\t// The indices should be the same so just compute vector differences\n\t\tfor (vtkIdType i = 0; i < movingPolyNumberOfPoints; i++)\n\t\t{\n\t\t\tdouble orgPt[3];\n\t\t\tdouble movedPt[3];\n\t\t\tregisteredPolyData->GetPoint(i, movedPt);\n\t\t\toutputMovingPolyData->GetPoint(i, orgPt);\n\t\t\tdisplacements->SetTuple3(i, movedPt[0] - orgPt[0], movedPt[1] - orgPt[1], movedPt[2] - orgPt[2]);\n\t\t}\n\n\t\toutputMovingPolyData->GetPointData()->SetScalars(displacements);\n\t}\n\n\treturn 1;\n}", "meta": {"hexsha": "cec611b93e3d00a699188011fed3798c1dd8bcf2", "size": 8278, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vtkNonRigidICP.cxx", "max_stars_repo_name": "aWilson41/vtkNonRigidICP", "max_stars_repo_head_hexsha": "3b653f7759731bf06634d03d3e11b2d2813ff208", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-10-24T16:31:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T05:54:43.000Z", "max_issues_repo_path": "vtkNonRigidICP.cxx", "max_issues_repo_name": "dugushiyu/vtkNonRigidICP", "max_issues_repo_head_hexsha": "3b653f7759731bf06634d03d3e11b2d2813ff208", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-09T07:45:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-04T01:53:47.000Z", "max_forks_repo_path": "vtkNonRigidICP.cxx", "max_forks_repo_name": "dugushiyu/vtkNonRigidICP", "max_forks_repo_head_hexsha": "3b653f7759731bf06634d03d3e11b2d2813ff208", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-15T14:16:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T13:29:18.000Z", "avg_line_length": 34.6359832636, "max_line_length": 184, "alphanum_fraction": 0.6983570911, "num_tokens": 2640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095495, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5152787666332256}}
{"text": "/*=============================================================================\n *\n *  Copyright (c) 2021 Sunnybrook Research Institute\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#include \"StainVectorMath.h\"\n#include \"ODConversion.h\"\n\n//Boost includes\n#include <boost/qvm/vec.hpp>\n#include <boost/qvm/mat.hpp>\n#include <boost/qvm/vec_access.hpp>\n#include <boost/qvm/mat_access.hpp>\n#include <boost/qvm/vec_operations.hpp>\n#include <boost/qvm/mat_operations.hpp>\n#include <boost/qvm/vec_mat_operations.hpp>\n#include <boost/qvm/map_mat_mat.hpp>\n\n///Compute the inverse of a 3x3 matrix using Boost qvm: ensure matrix is unitary before using\nvoid StainVectorMath::Compute3x3MatrixInverse(const double (&inputMat)[9], double (&inversionMat)[9]) {\n    //Clear the inversionMat (output) array\n    for (int i = 0; i < 9; i++) { inversionMat[i] = 0.0; }\n    //Define an output matrix\n    boost::qvm::mat<double, 3, 3> outputMatrix;\n\n    //Reshape to a 3x3 matrix\n    double reshapedInput[3][3] = { 0.0 };\n    int i, j = 0;\n    for (int x = 0; x < 9; x++) {\n        i = x / 3; //integer division\n        j = x % 3;\n        reshapedInput[i][j] = inputMat[x];\n    }\n     \n    //Check the determinant of the matrix: is it 0? Thus is the matrix singular?\n    double theDeterminant = boost::qvm::determinant(reshapedInput);\n    //Get the inverse of the reshapedInput matrix if the determinant is not zero\n    //Return matrix of all zeros if the determinant is zero\n    if (abs(theDeterminant) < ODConversion::GetODMinValue()) {\n        outputMatrix = boost::qvm::zero_mat<double, 3, 3>();\n    }\n    else {\n        outputMatrix = boost::qvm::transposed(boost::qvm::inverse(reshapedInput));\n    }\n\n    //Assign output values (first index is row), no looping\n    inversionMat[0] = boost::qvm::A<0, 0>(outputMatrix);\n    inversionMat[1] = boost::qvm::A<0, 1>(outputMatrix);\n    inversionMat[2] = boost::qvm::A<0, 2>(outputMatrix);\n    inversionMat[3] = boost::qvm::A<1, 0>(outputMatrix);\n    inversionMat[4] = boost::qvm::A<1, 1>(outputMatrix);\n    inversionMat[5] = boost::qvm::A<1, 2>(outputMatrix);\n    inversionMat[6] = boost::qvm::A<2, 0>(outputMatrix);\n    inversionMat[7] = boost::qvm::A<2, 1>(outputMatrix);\n    inversionMat[8] = boost::qvm::A<2, 2>(outputMatrix);\n    //void return\n}//end Compute3x3MatrixInverse\n\nvoid StainVectorMath::Make3x3MatrixUnitary(const double (&inputMat)[9], double (&unitaryMat)[9]) {\n    //Bundle the input values in rows of three\n    std::vector<std::array<double, 3>> inputRows;\n    inputRows.push_back(std::array<double, 3>({ inputMat[0], inputMat[1], inputMat[2] }));\n    inputRows.push_back(std::array<double, 3>({ inputMat[3], inputMat[4], inputMat[5] }));\n    inputRows.push_back(std::array<double, 3>({ inputMat[6], inputMat[7], inputMat[8] }));\n    //Get the norm values \n    std::vector<double> normVals;\n    normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[0].begin(), inputRows[0].end()));\n    normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[1].begin(), inputRows[1].end()));\n    normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[2].begin(), inputRows[2].end()));\n    //Create output rows\n    std::vector<std::array<double, 3>> outputRows;\n    for (auto it = normVals.begin(); it != normVals.end(); ++it) {\n        bool smallValue = (*it < 10.0*ODConversion::GetODMinValue());\n        std::array<double, 3> addRow = inputRows[it - normVals.begin()];\n        if (smallValue) {\n            //do not modify\n        }\n        else {\n            for (auto p = addRow.begin(); p != addRow.end(); ++p) {\n                *p = *p / *it;\n            }\n        }\n        outputRows.push_back(addRow);\n    }\n    //Assign to the unitary (output) matrix\n    for (int x = 0; x < 9; x++) {\n        int i = x / 3;\n        int j = x % 3;\n        unitaryMat[x] = outputRows[i][j];\n    }\n}//end Make3x3MatrixUnitary\n\nvoid StainVectorMath::ConvertZeroRowsToUnitary(const double (&inputMat)[9], double (&unitaryMat)[9]) {\n    double replacementVals[3] = { 1.0,1.0,1.0 };\n    StainVectorMath::ConvertZeroRowsToUnitary(inputMat, unitaryMat, replacementVals);\n}//end ConvertZeroRowsToUnitary\n\nvoid StainVectorMath::ConvertZeroRowsToUnitary(const double (&inputMat)[9], double (&unitaryMat)[9], const double (&replacementVals)[3]) {\n    //Bundle the input values in rows of three\n    std::vector<std::array<double, 3>> inputRows;\n    inputRows.push_back(std::array<double, 3>({ inputMat[0], inputMat[1], inputMat[2] }));\n    inputRows.push_back(std::array<double, 3>({ inputMat[3], inputMat[4], inputMat[5] }));\n    inputRows.push_back(std::array<double, 3>({ inputMat[6], inputMat[7], inputMat[8] }));\n    //Get the norm values \n    std::vector<double> normVals;\n    normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[0].begin(), inputRows[0].end()));\n    normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[1].begin(), inputRows[1].end()));\n    normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[2].begin(), inputRows[2].end()));\n    //Compare against 10xGetODMinValue, set to unitary row if smaller\n    std::array<double, 3> replacementArray = { replacementVals[0], replacementVals[1], replacementVals[2] };\n    auto unitaryRow = StainVectorMath::NormalizeArray(replacementArray);\n    std::vector<std::array<double, 3>> outputRows;\n    for (auto it = normVals.begin(); it != normVals.end(); ++it) {\n        bool smallValue = (*it < 10.0*ODConversion::GetODMinValue());\n        auto addRow = smallValue ? unitaryRow : inputRows[it-normVals.begin()];\n        outputRows.push_back(addRow);\n    }\n    //Assign to the unitary (output) matrix\n    for (int x = 0; x < 9; x++) {\n        int i = x / 3;\n        int j = x % 3;\n        unitaryMat[x] = outputRows[i][j];\n    }\n}//end ConvertZeroRowsToUnitary\n\nstd::array<bool, 3> StainVectorMath::RowSumZeroCheck(const double (&inputMat)[9]) {\n    std::array<bool, 3> returnVals;\n    //Bundle the input values in rows of three\n    std::vector<std::array<double, 3>> inputRows;\n    inputRows.push_back(std::array<double, 3>({ inputMat[0], inputMat[1], inputMat[2] }));\n    inputRows.push_back(std::array<double, 3>({ inputMat[3], inputMat[4], inputMat[5] }));\n    inputRows.push_back(std::array<double, 3>({ inputMat[6], inputMat[7], inputMat[8] }));\n    //Get the sums\n    std::vector<double> rowSums;\n    rowSums.push_back(std::accumulate(inputRows[0].begin(), inputRows[0].end(), 0.0));\n    rowSums.push_back(std::accumulate(inputRows[1].begin(), inputRows[1].end(), 0.0));\n    rowSums.push_back(std::accumulate(inputRows[2].begin(), inputRows[2].end(), 0.0));\n    //Get the norm values \n    std::vector<double> normVals;\n    normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[0].begin(), inputRows[0].end()));\n    normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[1].begin(), inputRows[1].end()));\n    normVals.push_back(StainVectorMath::Norm<std::array<double, 3>::iterator, double>(inputRows[2].begin(), inputRows[2].end()));\n\n    //For each, if rowSums is zero and normVals is non-zero, returnVals is true\n    for (int i = 0; i < 3; i++) {\n        bool checkVal = ((abs(rowSums[i]) < ODConversion::GetODMinValue()) && (normVals[i] > 0.0));\n        returnVals[i] = checkVal ? true : false;\n    }\n    return returnVals;\n}//end RowSumZeroCheck\n\nvoid StainVectorMath::Multiply3x3MatrixAndVector(const double (&inputMat)[9], const double (&inputVec)[3], double (&outputVec)[3]) {\n    //Clear the output vector\n    for (int i = 0; i < 3; i++) { outputVec[i] = 0.0; }\n    //Reshape to a 3x3 matrix\n    double reshapedMatrix[3][3] = { 0.0 };\n    int i, j = 0;\n    for (int x = 0; x < 9; x++) {\n        i = x / 3;\n        j = x % 3;\n        reshapedMatrix[i][j] = inputMat[x];\n    }\n\n    //Assign matrix and input vector to boost::qvm types\n    boost::qvm::mat<double, 3, 3> inputQVMMatrix = boost::qvm::mref(reshapedMatrix);\n    boost::qvm::vec<double, 3> inputQVMVector = boost::qvm::zero_vec<double, 3>();\n    boost::qvm::A<0>(inputQVMVector) = inputVec[0];\n    boost::qvm::A<1>(inputQVMVector) = inputVec[1];\n    boost::qvm::A<2>(inputQVMVector) = inputVec[2];\n\n    //Multiplication\n    boost::qvm::vec<double, 3> outputQVMVector;\n    outputQVMVector = inputQVMMatrix * inputQVMVector;\n\n    //Assign to the output vector\n    outputVec[0] = boost::qvm::A<0>(outputQVMVector);\n    outputVec[1] = boost::qvm::A<1>(outputQVMVector);\n    outputVec[2] = boost::qvm::A<2>(outputQVMVector);\n    //void return\n}//end Multiply3x3MatrixAndVector\n\nvoid StainVectorMath::SortStainVectors(const double(&inputMat)[9], double(&outputMat)[9],\n    const int &sortOrder /*= SortOrder::ASCENDING */) {\n    //Define lambdas to set how to compare two stain vectors (as 3-element arrays)\n    auto ascLambda = [](const std::array<double, 3> a, const std::array<double, 3> b) {\n        double prec = 1e-3;\n        //Always put (0,0,0) stain vectors at the end\n        double aSum = std::abs(std::accumulate(a.begin(), a.end(), 0.0));\n        double bSum = std::abs(std::accumulate(b.begin(), b.end(), 0.0));\n        if (aSum < prec) { return false; }\n        if (bSum < prec) { return true; }\n        //If first element is the same within error, sort by second element\n        if (std::abs(a[0] - b[0]) > prec) { return a[0] < b[0]; }\n        //If second element is the same within error, sort by third element\n        else if (std::abs(a[1] - b[1]) > prec) { return a[1] < b[1]; }\n        else { return a[2] < b[2]; }\n    };\n\n    auto descLambda = [](const std::array<double, 3> a, const std::array<double, 3> b) {\n        double prec = 1e-3;\n        //Always put (0,0,0) stain vectors at the end\n        double aSum = std::abs(std::accumulate(a.begin(), a.end(), 0.0));\n        double bSum = std::abs(std::accumulate(b.begin(), b.end(), 0.0));\n        if (aSum < prec) { return false; }\n        if (bSum < prec) { return true; }\n        //If first element is the same within error, sort by second element\n        if (std::abs(a[0] - b[0]) > prec) { return a[0] > b[0]; }\n        //If second element is the same within error, sort by third element\n        else if (std::abs(a[1] - b[1]) > prec) { return a[1] > b[1]; }\n        else { return a[2] >= b[2]; }\n    };\n\n    //Bundle the input values in rows of three\n    std::vector<std::array<double, 3>> inputRows;\n    inputRows.push_back(std::array<double, 3>({ inputMat[0], inputMat[1], inputMat[2] }));\n    inputRows.push_back(std::array<double, 3>({ inputMat[3], inputMat[4], inputMat[5] }));\n    inputRows.push_back(std::array<double, 3>({ inputMat[6], inputMat[7], inputMat[8] }));\n    //Create output rows\n    std::vector<std::array<double, 3>> outputRows = inputRows;\n\n    //Sort using the appropriate lambda\n    if (sortOrder == SortOrder::ASCENDING) {\n        std::sort(outputRows.begin(), outputRows.end(), ascLambda);\n    }\n    else if (sortOrder == SortOrder::DESCENDING) {\n        std::sort(outputRows.begin(), outputRows.end(), descLambda);\n    }\n    else {\n        //do not fill the output matrix\n        return;\n    }\n\n    //Assign to the output matrix\n    for (int x = 0; x < 9; x++) {\n        int i = x / 3;\n        int j = x % 3;\n        outputMat[x] = outputRows[i][j];\n    }\n}//end SortStainVectors\n", "meta": {"hexsha": "343817ebbcec46bee9b4e4c2e7ce6c5da27d0841", "size": 12558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "StainVectorMath.cpp", "max_stars_repo_name": "mschumak/StainAnalysis-plugin", "max_stars_repo_head_hexsha": "36f89848ab1dd9f9d96b3b96ff223a30880af795", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-11T22:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-08T19:28:12.000Z", "max_issues_repo_path": "StainVectorMath.cpp", "max_issues_repo_name": "mschumak/StainAnalysis-plugin", "max_issues_repo_head_hexsha": "36f89848ab1dd9f9d96b3b96ff223a30880af795", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-18T20:28:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-18T20:28:48.000Z", "max_forks_repo_path": "StainVectorMath.cpp", "max_forks_repo_name": "mschumak/StainAnalysis-plugin", "max_forks_repo_head_hexsha": "36f89848ab1dd9f9d96b3b96ff223a30880af795", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-05-17T14:18:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-20T15:14:34.000Z", "avg_line_length": 48.4864864865, "max_line_length": 138, "alphanum_fraction": 0.638079312, "num_tokens": 3713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5152098669841191}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2016 - 2021 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n// Taylor Couette flow\n// See Sec. 4.2 of \"An immersed interface method for discrete surfaces\"\n// by Ebrahim M. Kolahdouz et al., Journal of Computational Physics 400 (2020) 108854\n// To get the right convergence results this code was run with tight Stokes solver tolerance\n// with the command line flag: -stokes_ksp_rtol 1.0e-10 -ksp_rtol 1.0e-10\n\n// This code was tested against the commit 57fb379454ea3f8f50c476f10226cb6b520a11a0\n// which is currently on branch iim-1 at https://github.com/drwells/IBAMR\n\n// Headers for basic PETSc functions\n#include <petscsys.h>\n\n// Headers for basic SAMRAI objects\n#include <BergerRigoutsos.h>\n#include <CartesianGridGeometry.h>\n#include <LoadBalancer.h>\n#include <StandardTagAndInitialize.h>\n\n// Headers for basic libMesh objects\n#include <libmesh/boundary_info.h>\n#include <libmesh/boundary_mesh.h>\n#include <libmesh/equation_systems.h>\n#include <libmesh/exodusII_io.h>\n#include <libmesh/face_quad.h>\n#include <libmesh/face_quad4.h>\n#include <libmesh/mesh.h>\n#include <libmesh/mesh_generation.h>\n#include <libmesh/mesh_triangle_interface.h>\n\n// Headers for application-specific algorithm/data structure objects\n#include <ibamr/IBExplicitHierarchyIntegrator.h>\n#include <ibamr/IIMethod.h>\n#include <ibamr/INSCollocatedHierarchyIntegrator.h>\n#include <ibamr/INSStaggeredHierarchyIntegrator.h>\n\n#include <ibtk/AppInitializer.h>\n#include <ibtk/IndexUtilities.h>\n#include <ibtk/LEInteractor.h>\n#include <ibtk/ibtk_utilities.h>\n#include <ibtk/libmesh_utilities.h>\n#include <ibtk/muParserCartGridFunction.h>\n#include <ibtk/muParserRobinBcCoefs.h>\n\n#include <boost/multi_array.hpp>\n\n// Set up application namespace declarations\n#include <ibamr/app_namespaces.h>\n\n// Elasticity model data.\nnamespace ModelData\n{\n// Tether (penalty) force functions.\n\nstatic double kappa_s = 1.0e6;\nstatic double eta_s = 0.0;\nstatic double AA = 0.0;\nstatic double BB = 0.0;\nstatic double MU = 0.0;\nstatic double R1 = 0.0;\nstatic double R2 = 0.0;\nstatic double OMEGA1 = 0.0;\nstatic double OMEGA2 = 0.0;\nstatic double shift = 0.0;\nstatic double fac = 0.0;\nstatic double L = 0.0;\n\nvoid\ntether_force_function_inner(VectorValue<double>& F,\n                            const VectorValue<double>& n,\n                            const VectorValue<double>& /*N*/,\n                            const TensorValue<double>& /*FF*/,\n                            const libMesh::Point& x,\n                            const libMesh::Point& X,\n                            Elem* const /*elem*/,\n                            const unsigned short /*side*/,\n                            const vector<const vector<double>*>& var_data,\n                            const vector<const vector<VectorValue<double> >*>& /*grad_var_data*/,\n                            double time,\n                            void* /*ctx*/)\n{\n    const std::vector<double>& U = *var_data[0];\n\n    double u_bndry_n = 0.0;\n    for (unsigned int d = 0; d < NDIM; ++d)\n    {\n        u_bndry_n += n(d) * U[d];\n    }\n    F(0) = kappa_s * (X(0) * cos(OMEGA1 * time) - X(1) * sin(OMEGA1 * time) - x(0));\n    F(1) = kappa_s * (X(0) * sin(OMEGA1 * time) + X(1) * cos(OMEGA1 * time) - x(1));\n    F(2) = 0.0;\n\n    return;\n} // tether_force_function\n\ninline unsigned int\nidx(const unsigned int nr, const unsigned int i, const unsigned int j)\n{\n    return i + j * nr;\n\n    return libMesh::invalid_uint;\n}\n\n} // namespace ModelData\nusing namespace ModelData;\n\nvoid postprocess_data(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                      Pointer<INSHierarchyIntegrator> navier_stokes_integrator,\n                      Mesh& mesh,\n                      EquationSystems* equation_systems,\n                      const int iteration_num,\n                      const double loop_time,\n                      const string& data_dump_dirname);\n\n// Function prototypes\nvoid pressure_convergence(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                          const int p_idx,\n                          const double data_time,\n                          const string& data_dump_dirname);\n\n/*******************************************************************************\n * For each run, the input filename and restart information (if needed) must   *\n * be given on the command line.  For non-restarted case, command line is:     *\n *                                                                             *\n *    executable <input file name>                                             *\n *                                                                             *\n * For restarted run, command line is:                                         *\n *                                                                             *\n *    executable <input file name> <restart directory> <restart number>        *\n *                                                                             *\n *******************************************************************************/\nint\nmain(int argc, char* argv[])\n{\n    // Initialize libMesh, PETSc, MPI, and SAMRAI.\n    LibMeshInit init(argc, argv);\n    SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD);\n    SAMRAI_MPI::setCallAbortInSerialInsteadOfExit();\n    SAMRAIManager::startup();\n\n    PetscOptionsSetValue(nullptr, \"-ksp_rtol\", \"1e-10\");\n    PetscOptionsSetValue(nullptr, \"-stokes_ksp_atol\", \"1e-10\");\n\n    { // cleanup dynamically allocated objects prior to shutdown\n\n        // Parse command line options, set some standard options from the input\n        // file, initialize the restart database (if this is a restarted run),\n        // and enable file logging.\n        Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, \"IB.log\");\n        Pointer<Database> input_db = app_initializer->getInputDatabase();\n\n        // Setup user-defined kernel function.\n\n        // Get various standard options set in the input file.\n        const bool dump_viz_data = app_initializer->dumpVizData();\n        const int viz_dump_interval = app_initializer->getVizDumpInterval();\n        const bool uses_visit = dump_viz_data && app_initializer->getVisItDataWriter();\n        const bool uses_exodus = dump_viz_data && !app_initializer->getExodusIIFilename().empty();\n        const string inner_exodus_filename = app_initializer->getExodusIIFilename(\"inner\");\n\n        const bool dump_restart_data = app_initializer->dumpRestartData();\n        const int restart_dump_interval = app_initializer->getRestartDumpInterval();\n        const string restart_dump_dirname = app_initializer->getRestartDumpDirectory();\n\n        const bool dump_postproc_data = app_initializer->dumpPostProcessingData();\n        const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval();\n        const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory();\n        if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty())\n        {\n            Utilities::recursiveMkdir(postproc_data_dump_dirname);\n        }\n\n        const bool dump_timer_data = app_initializer->dumpTimerData();\n        const int timer_dump_interval = app_initializer->getTimerDumpInterval();\n\n        // Create a simple FE mesh.\n        const double dx = input_db->getDouble(\"DX\");\n        OMEGA1 = input_db->getDouble(\"OMEGA1\"); // radius of the inner circle\n        OMEGA2 = input_db->getDouble(\"OMEGA2\"); // radius of the outer circle\n\n        AA = input_db->getDouble(\"AA\"); // radius of the inner circle\n        BB = input_db->getDouble(\"BB\"); // radius of the outer circle\n        shift = input_db->getDouble(\"SHIFT\");\n        fac = input_db->getDouble(\"FAC\");\n        const double ds = input_db->getDouble(\"MFAC\") * dx;\n        string elem_type = input_db->getString(\"ELEM_TYPE\");\n        R1 = input_db->getDouble(\"R1\"); // radius of the inner circle\n        R2 = input_db->getDouble(\"R2\"); // radius of the outer circle\n        L = input_db->getDouble(\"L\");   // length in the z direction\n        MU = input_db->getDouble(\"MU\"); // length in the z direction\n\n        Mesh inner_mesh(init.comm(), NDIM - 1);\n\n        BoundaryInfo& boundary_info = inner_mesh.get_boundary_info();\n        boundary_info.clear_boundary_node_ids();\n        const unsigned int NXi_elem = ceil(L / ds);\n        const unsigned int NRi_elem = ceil(2.0 * M_PI * R1 / ds);\n        int node_id = 0;\n        inner_mesh.reserve_nodes(NRi_elem * (NXi_elem + 1));\n        inner_mesh.reserve_elem(NRi_elem * NXi_elem);\n\n        for (unsigned int j = 0; j <= NXi_elem; j++)\n        {\n            for (unsigned int i = 0; i <= NRi_elem - 1; i++)\n            {\n                const double theta = 2.0 * M_PI * static_cast<double>(i) / static_cast<double>(NRi_elem);\n                inner_mesh.add_point(libMesh::Point(R1 * cos(theta),\n                                                    R1 * sin(theta),\n                                                    -0.5 * L + L * static_cast<Real>(j) / static_cast<Real>(NXi_elem)),\n                                     node_id++);\n            }\n        }\n\n        for (unsigned int j = 0; j <= NXi_elem - 1; j++)\n        {\n            for (unsigned int i = 0; i <= NRi_elem - 2; i++)\n            {\n                Elem* elem = inner_mesh.add_elem(new Quad4);\n                elem->set_node(0) = inner_mesh.node_ptr(idx(NRi_elem, i, j));\n                elem->set_node(1) = inner_mesh.node_ptr(idx(NRi_elem, i + 1, j));\n                elem->set_node(2) = inner_mesh.node_ptr(idx(NRi_elem, i + 1, j + 1));\n                elem->set_node(3) = inner_mesh.node_ptr(idx(NRi_elem, i, j + 1));\n            }\n        }\n\n        for (unsigned int j = 0; j <= NXi_elem - 1; j++)\n        {\n            Elem* elem = inner_mesh.add_elem(new Quad4);\n            elem->set_node(0) = inner_mesh.node_ptr(idx(NRi_elem, NRi_elem - 1, j));\n            elem->set_node(1) = inner_mesh.node_ptr(idx(NRi_elem, 0, j));\n            elem->set_node(2) = inner_mesh.node_ptr(idx(NRi_elem, 0, j + 1));\n            elem->set_node(3) = inner_mesh.node_ptr(idx(NRi_elem, NRi_elem - 1, j + 1));\n        }\n\n        MeshBase::const_element_iterator el_end = inner_mesh.elements_end();\n        for (MeshBase::const_element_iterator el = inner_mesh.elements_begin(); el != el_end; ++el)\n        {\n            Elem* const elem = *el;\n            for (unsigned int side = 0; side < elem->n_sides(); ++side)\n            {\n                const bool at_mesh_bdry = !elem->neighbor_ptr(side);\n                if (at_mesh_bdry)\n                {\n                    if (boundary_info.has_boundary_id(elem, side, 1) || boundary_info.has_boundary_id(elem, side, 3))\n                    {\n                        boundary_info.add_side(elem, side, FEDataManager::ZERO_DISPLACEMENT_XY_BDRY_ID);\n                    }\n                }\n            }\n        }\n        inner_mesh.prepare_for_use();\n\n        kappa_s = input_db->getDouble(\"KAPPA_S\");\n        eta_s = input_db->getDouble(\"ETA_S\");\n\n        // Create major algorithm and data objects that comprise the\n        // application.  These objects are configured from the input database\n        // and, if this is a restarted run, from the restart database.\n        Pointer<INSHierarchyIntegrator> navier_stokes_integrator = new INSStaggeredHierarchyIntegrator(\n            \"INSStaggeredHierarchyIntegrator\",\n            app_initializer->getComponentDatabase(\"INSStaggeredHierarchyIntegrator\"));\n\n        Pointer<IIMethod> ib_method_ops =\n            new IIMethod(\"IIMethod\",\n                         app_initializer->getComponentDatabase(\"IIMethod\"),\n                         &inner_mesh,\n                         app_initializer->getComponentDatabase(\"GriddingAlgorithm\")->getInteger(\"max_levels\"));\n        Pointer<IBHierarchyIntegrator> time_integrator =\n            new IBExplicitHierarchyIntegrator(\"IBHierarchyIntegrator\",\n                                              app_initializer->getComponentDatabase(\"IBHierarchyIntegrator\"),\n                                              ib_method_ops,\n                                              navier_stokes_integrator);\n\n        Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>(\n            \"CartesianGeometry\", app_initializer->getComponentDatabase(\"CartesianGeometry\"));\n        Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>(\"PatchHierarchy\", grid_geometry);\n        Pointer<StandardTagAndInitialize<NDIM> > error_detector =\n            new StandardTagAndInitialize<NDIM>(\"StandardTagAndInitialize\",\n                                               time_integrator,\n                                               app_initializer->getComponentDatabase(\"StandardTagAndInitialize\"));\n        Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>();\n        Pointer<LoadBalancer<NDIM> > load_balancer =\n            new LoadBalancer<NDIM>(\"LoadBalancer\", app_initializer->getComponentDatabase(\"LoadBalancer\"));\n        Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm =\n            new GriddingAlgorithm<NDIM>(\"GriddingAlgorithm\",\n                                        app_initializer->getComponentDatabase(\"GriddingAlgorithm\"),\n                                        error_detector,\n                                        box_generator,\n                                        load_balancer);\n\n        // Configure the IBFE solver.\n        ib_method_ops->initializeFEEquationSystems();\n        std::vector<int> vars(NDIM);\n        for (unsigned int d = 0; d < NDIM; ++d) vars[d] = d;\n        vector<SystemData> sys_data(1, SystemData(IIMethod::VELOCITY_SYSTEM_NAME, vars));\n\n        IIMethod::LagSurfaceForceFcnData tether_force_inner_data(tether_force_function_inner, sys_data);\n\n        ib_method_ops->registerLagSurfaceForceFunction(tether_force_inner_data);\n\n        EquationSystems* inner_equation_systems = ib_method_ops->getFEDataManager()->getEquationSystems();\n\n        Pointer<CartGridFunction> u_init = new muParserCartGridFunction(\n            \"u_init\", app_initializer->getComponentDatabase(\"VelocityInitialConditions\"), grid_geometry);\n        navier_stokes_integrator->registerVelocityInitialConditions(u_init);\n\n        Pointer<CartGridFunction> p_init = new muParserCartGridFunction(\n            \"p_init\", app_initializer->getComponentDatabase(\"PressureInitialConditions\"), grid_geometry);\n\n        if (input_db->keyExists(\"ForcingFunction\"))\n        {\n            Pointer<CartGridFunction> f_fcn = new muParserCartGridFunction(\n                \"f_fcn\", app_initializer->getComponentDatabase(\"ForcingFunction\"), grid_geometry);\n            time_integrator->registerBodyForceFunction(f_fcn);\n        }\n\n        // Create Eulerian boundary condition specification objects (when necessary).\n        vector<RobinBcCoefStrategy<NDIM>*> u_bc_coefs(NDIM, static_cast<RobinBcCoefStrategy<NDIM>*>(NULL));\n        const bool periodic_domain = grid_geometry->getPeriodicShift().min() > 0;\n        if (!periodic_domain)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                ostringstream bc_coefs_name_stream;\n                bc_coefs_name_stream << \"u_bc_coefs_\" << d;\n                const string bc_coefs_name = bc_coefs_name_stream.str();\n                ostringstream bc_coefs_db_name_stream;\n                bc_coefs_db_name_stream << \"VelocityBcCoefs_\" << d;\n                const string bc_coefs_db_name = bc_coefs_db_name_stream.str();\n                u_bc_coefs[d] = new muParserRobinBcCoefs(\n                    bc_coefs_name, app_initializer->getComponentDatabase(bc_coefs_db_name), grid_geometry);\n            }\n            navier_stokes_integrator->registerPhysicalBoundaryConditions(u_bc_coefs);\n        }\n        // Create Eulerian body force function specification objects.\n        // if (input_db->keyExists(\"ForcingFunction\"))\n        // {\n        //    Pointer<CartGridFunction> f_fcn = new muParserCartGridFunction(\n        //         \"f_fcn\", app_initializer->getComponentDatabase(\"ForcingFunction\"), grid_geometry);\n        //    time_integrator->registerBodyForceFunction(f_fcn);\n        // }\n\n        // Set up visualization plot file writers.\n\n        Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter();\n        if (uses_visit)\n        {\n            time_integrator->registerVisItDataWriter(visit_data_writer);\n        }\n        std::unique_ptr<ExodusII_IO> inner_exodus_io(uses_exodus ? new ExodusII_IO(inner_mesh) : NULL);\n\n        // Initialize hierarchy configuration and data on all patches.\n        ib_method_ops->initializeFEData();\n        time_integrator->initializePatchHierarchy(patch_hierarchy, gridding_algorithm);\n\n        // Deallocate initialization objects.\n        app_initializer.setNull();\n\n        // Write out initial visualization data.\n        int iteration_num = time_integrator->getIntegratorStep();\n        double loop_time = time_integrator->getIntegratorTime();\n        if (dump_viz_data)\n        {\n            pout << \"\\n\\nWriting visualization files...\\n\\n\";\n            if (uses_visit)\n            {\n                time_integrator->setupPlotData();\n                visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n            }\n            if (uses_exodus)\n            {\n                inner_exodus_io->write_timestep(\n                    inner_exodus_filename, *inner_equation_systems, iteration_num / viz_dump_interval + 1, loop_time);\n            }\n        }\n\n        // Main time step loop.\n        double loop_time_end = time_integrator->getEndTime();\n        double dt = 0.0;\n        while (!MathUtilities<double>::equalEps(loop_time, loop_time_end) && time_integrator->stepsRemaining())\n        {\n            iteration_num = time_integrator->getIntegratorStep();\n            loop_time = time_integrator->getIntegratorTime();\n\n            pout << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"At beginning of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n\n            dt = time_integrator->getMaximumTimeStepSize();\n            time_integrator->advanceHierarchy(dt);\n            loop_time += dt;\n\n            pout << \"\\n\";\n            pout << \"At end       of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"\\n\";\n\n            // At specified intervals, write visualization and restart files,\n            // print out timer data, and store hierarchy data for post\n            // processing.\n            iteration_num += 1;\n            const bool last_step = !time_integrator->stepsRemaining();\n            if (dump_viz_data && (iteration_num % viz_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting visualization files...\\n\\n\";\n                if (uses_visit)\n                {\n                    time_integrator->setupPlotData();\n                    visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n                }\n                if (uses_exodus)\n                {\n                    inner_exodus_io->write_timestep(inner_exodus_filename,\n                                                    *inner_equation_systems,\n                                                    iteration_num / viz_dump_interval + 1,\n                                                    loop_time);\n                }\n            }\n\n            postprocess_data(patch_hierarchy,\n                             navier_stokes_integrator,\n                             inner_mesh,\n                             inner_equation_systems,\n                             iteration_num,\n                             loop_time,\n                             postproc_data_dump_dirname);\n            if (dump_restart_data && (iteration_num % restart_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting restart files...\\n\\n\";\n                RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num);\n            }\n            if (dump_timer_data && (iteration_num % timer_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting timer data...\\n\\n\";\n                TimerManager::getManager()->print(plog);\n            }\n        }\n\n        pout << \"\\n\"\n             << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\"\n             << \"Computing error norms.\\n\\n\";\n        VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();\n        const int finest_ln = patch_hierarchy->getFinestLevelNumber();\n        HierarchyMathOps hier_math_ops(\"hier_math_ops\", patch_hierarchy);\n        hier_math_ops.resetLevels(finest_ln, finest_ln);\n        Pointer<hier::Variable<NDIM> > u_var = time_integrator->getVelocityVariable();\n        const Pointer<VariableContext> u_ctx = time_integrator->getCurrentContext();\n        const int u_idx = var_db->mapVariableAndContextToIndex(u_var, u_ctx);\n        const int u_cloned_idx = var_db->registerClonedPatchDataIndex(u_var, u_idx);\n        const Pointer<hier::Variable<NDIM> > p_var = time_integrator->getPressureVariable();\n        const Pointer<VariableContext> p_ctx = time_integrator->getCurrentContext();\n\n        const int p_idx = var_db->mapVariableAndContextToIndex(p_var, p_ctx);\n\n        pressure_convergence(patch_hierarchy, p_idx, loop_time, postproc_data_dump_dirname);\n\n        const int p_cloned_idx = var_db->registerClonedPatchDataIndex(p_var, p_idx);\n        const int coarsest_ln = 0;\n        for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n        {\n            patch_hierarchy->getPatchLevel(ln)->allocatePatchData(u_cloned_idx, loop_time);\n            patch_hierarchy->getPatchLevel(ln)->allocatePatchData(p_cloned_idx, loop_time);\n        }\n        u_init->setDataOnPatchHierarchy(u_cloned_idx, u_var, patch_hierarchy, loop_time);\n        p_init->setDataOnPatchHierarchy(p_cloned_idx, p_var, patch_hierarchy, loop_time - 0.5 * dt);\n\n        hier_math_ops.setPatchHierarchy(patch_hierarchy);\n        hier_math_ops.resetLevels(coarsest_ln, finest_ln);\n        const int wgt_sc_idx = hier_math_ops.getSideWeightPatchDescriptorIndex();\n        HierarchySideDataOpsReal<NDIM, double> hier_sc_data_ops(patch_hierarchy, coarsest_ln, finest_ln);\n        hier_sc_data_ops.subtract(u_idx, u_idx, u_cloned_idx);\n        pout << std::setprecision(16) << \"Error in u at time \" << loop_time << \":\\n\"\n             << \"  L1-norm:  \" << hier_sc_data_ops.L1Norm(u_idx, wgt_sc_idx) << \"\\n\"\n             << \"  L2-norm:  \" << hier_sc_data_ops.L2Norm(u_idx, wgt_sc_idx) << \"\\n\"\n             << \"  max-norm: \" << hier_sc_data_ops.maxNorm(u_idx, wgt_sc_idx) << \"\\n\"\n             << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n\n        pout << \" MU = \" << MU << \"\\n\"\n             << \"  dx:  \" << dx << \"\\n\"\n             << \"  dt: \" << dt << \"\\n\";\n\n        if (input_db->getBool(\"USE_VELOCITY_JUMP_CONDITIONS\"))\n            pout << \" Using the jump condition\"\n                 << \"\\n\";\n        else\n            pout << \" Using regular IB\"\n                 << \"\\n\";\n        if (dump_viz_data && uses_visit)\n        {\n            time_integrator->setupPlotData();\n            visit_data_writer->writePlotData(patch_hierarchy, iteration_num + 1, loop_time);\n        }\n\n        // Cleanup Eulerian boundary condition specification objects (when\n        // necessary).\n        for (unsigned int d = 0; d < NDIM; ++d) delete u_bc_coefs[d];\n\n    } // cleanup dynamically allocated objects prior to shutdown\n\n    SAMRAIManager::shutdown();\n    return 0;\n} // main\n\nvoid\nvelocity_convergence(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                     const int u_idx,\n                     const double /*data_time*/,\n                     const string& /*data_dump_dirname*/)\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = patch_hierarchy->getFinestLevelNumber();\n\n    HierarchyMathOps hier_math_ops(\"hier_math_ops\", patch_hierarchy);\n    hier_math_ops.resetLevels(finest_ln, finest_ln);\n    const int wgt_cc_idx = hier_math_ops.getCellWeightPatchDescriptorIndex();\n    const double X_min[3] = { -0.45 * L, -0.45 * L, -0.45 * L };\n    const double X_max[3] = { 0.45 * L, 0.45 * L, 0.45 * L };\n\n    double u_Eulerian_L2_norm = 0.0;\n    double u_Eulerian_max_norm = 0.0;\n    int N_max = 0;\n    vector<double> pos_values;\n    for (int ln = finest_ln; ln >= coarsest_ln; --ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln);\n        for (PatchLevel<NDIM>::Iterator p(level); p; p++)\n        {\n            Pointer<Patch<NDIM> > patch = level->getPatch(p());\n            const Box<NDIM>& patch_box = patch->getBox();\n            const CellIndex<NDIM>& patch_lower = patch_box.lower();\n            const CellIndex<NDIM>& patch_upper = patch_box.upper();\n\n            const Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry();\n            const double* const patch_x_lower = patch_geom->getXLower();\n            const double* const patch_x_upper = patch_geom->getXUpper();\n\n            const double* const patch_dx = patch_geom->getDx();\n\n            // Entire box containing the required data.\n            Box<NDIM> box(IndexUtilities::getCellIndex(\n                              &X_min[0], patch_x_lower, patch_x_upper, patch_dx, patch_lower, patch_upper),\n                          IndexUtilities::getCellIndex(\n                              &X_max[0], patch_x_lower, patch_x_upper, patch_dx, patch_lower, patch_upper));\n            // Part of the box on this patch\n            Box<NDIM> trim_box = patch_box * box;\n            BoxList<NDIM> iterate_box_list = trim_box;\n\n            // Trim the box covered by the finer region\n            BoxList<NDIM> covered_boxes;\n            if (ln < finest_ln)\n            {\n                BoxArray<NDIM> refined_region_boxes;\n                Pointer<PatchLevel<NDIM> > next_finer_level = patch_hierarchy->getPatchLevel(ln + 1);\n                refined_region_boxes = next_finer_level->getBoxes();\n                refined_region_boxes.coarsen(next_finer_level->getRatioToCoarserLevel());\n                for (int i = 0; i < refined_region_boxes.getNumberOfBoxes(); ++i)\n                {\n                    const Box<NDIM> refined_box = refined_region_boxes[i];\n                    const Box<NDIM> covered_box = trim_box * refined_box;\n                    covered_boxes.unionBoxes(covered_box);\n                }\n            }\n            iterate_box_list.removeIntersections(covered_boxes);\n\n            // Loop over the boxes and store the location and interpolated value.\n            Pointer<SideData<NDIM, double> > u_data = patch->getPatchData(u_idx);\n            const Pointer<CellData<NDIM, double> > wgt_cc_data = patch->getPatchData(wgt_cc_idx);\n\n            for (BoxList<NDIM>::Iterator lit(iterate_box_list); lit; lit++)\n            {\n                const Box<NDIM>& iterate_box = *lit;\n                for (Box<NDIM>::Iterator bit(iterate_box); bit; bit++)\n                {\n                    const CellIndex<NDIM>& lower_idx = *bit;\n\n                    const double y = patch_x_lower[1] + patch_dx[1] * (lower_idx(1) - patch_lower(1) + 0.5);\n                    const double x = patch_x_lower[0] + patch_dx[0] * (lower_idx(0) - patch_lower(0));\n\n                    double u_ex, v_ex;\n                    if (sqrt(x * x + y * y) < R1)\n                    {\n                        u_ex = -OMEGA1 * y;\n                        v_ex = OMEGA1 * x;\n                    }\n                    else if (sqrt(x * x + y * y) > R2)\n                    {\n                        u_ex = 0.0;\n                        v_ex = 0.0;\n                    }\n                    else\n                    {\n                        u_ex = -y * (AA + BB / (x * x + y * y));\n                        v_ex = x * (AA + BB / (x * x + y * y));\n                    }\n\n                    const double u0 = (*u_data)(SideIndex<NDIM>(lower_idx, 0, SideIndex<NDIM>::Lower));\n                    const double v0 = (*u_data)(SideIndex<NDIM>(lower_idx, 1, SideIndex<NDIM>::Lower));\n\n                    N_max += 1;\n                    u_Eulerian_L2_norm += std::abs(u0 - u_ex) * std::abs(u0 - u_ex) * (*wgt_cc_data)(lower_idx);\n                    u_Eulerian_L2_norm += std::abs(v0 - v_ex) * std::abs(v0 - v_ex) * (*wgt_cc_data)(lower_idx);\n\n                    u_Eulerian_max_norm = std::max(u_Eulerian_max_norm, std::abs(u0 - u_ex));\n                    u_Eulerian_max_norm = std::max(u_Eulerian_max_norm, std::abs(v0 - v_ex));\n                }\n            }\n        }\n    }\n\n    SAMRAI_MPI::sumReduction(&N_max, 1);\n    SAMRAI_MPI::sumReduction(&u_Eulerian_L2_norm, 1);\n    SAMRAI_MPI::maxReduction(&u_Eulerian_max_norm, 1);\n\n    u_Eulerian_L2_norm = sqrt(u_Eulerian_L2_norm);\n\n    pout << \" u_Eulerian_L2_norm = \" << u_Eulerian_L2_norm << \"\\n\\n\";\n    pout << \" u_Eulerian_max_norm = \" << u_Eulerian_max_norm << \"\\n\\n\";\n\n    return;\n} // velocity_convergence\n\nvoid\npressure_convergence(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                     const int p_idx,\n                     const double /*data_time*/,\n                     const string& /*data_dump_dirname*/)\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = patch_hierarchy->getFinestLevelNumber();\n\n    HierarchyMathOps hier_math_ops(\"hier_math_ops\", patch_hierarchy);\n    hier_math_ops.resetLevels(finest_ln, finest_ln);\n    const int wgt_cc_idx = hier_math_ops.getCellWeightPatchDescriptorIndex();\n\n    const double X_min[3] = { -0.45 * L, -0.45 * L, -0.45 * L };\n    const double X_max[3] = { 0.45 * L, 0.45 * L, 0.45 * L };\n    // vector<double> pos_values;\n    double p_Eulerian_L2_norm = 0.0;\n    double p_Eulerian_max_norm = 0.0;\n    int N_max = 0;\n    for (int ln = finest_ln; ln >= coarsest_ln; --ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln);\n        for (PatchLevel<NDIM>::Iterator p(level); p; p++)\n        {\n            Pointer<Patch<NDIM> > patch = level->getPatch(p());\n            const Box<NDIM>& patch_box = patch->getBox();\n            const CellIndex<NDIM>& patch_lower = patch_box.lower();\n            const CellIndex<NDIM>& patch_upper = patch_box.upper();\n\n            const Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry();\n            const double* const patch_x_lower = patch_geom->getXLower();\n            const double* const patch_x_upper = patch_geom->getXUpper();\n\n            const double* const patch_dx = patch_geom->getDx();\n\n            // Entire box containing the required data.\n            Box<NDIM> box(IndexUtilities::getCellIndex(\n                              &X_min[0], patch_x_lower, patch_x_upper, patch_dx, patch_lower, patch_upper),\n                          IndexUtilities::getCellIndex(\n                              &X_max[0], patch_x_lower, patch_x_upper, patch_dx, patch_lower, patch_upper));\n            // Part of the box on this patch\n            Box<NDIM> trim_box = patch_box * box;\n            BoxList<NDIM> iterate_box_list = trim_box;\n\n            // Trim the box covered by the finer region\n            BoxList<NDIM> covered_boxes;\n            if (ln < finest_ln)\n            {\n                BoxArray<NDIM> refined_region_boxes;\n                Pointer<PatchLevel<NDIM> > next_finer_level = patch_hierarchy->getPatchLevel(ln + 1);\n                refined_region_boxes = next_finer_level->getBoxes();\n                refined_region_boxes.coarsen(next_finer_level->getRatioToCoarserLevel());\n                for (int i = 0; i < refined_region_boxes.getNumberOfBoxes(); ++i)\n                {\n                    const Box<NDIM> refined_box = refined_region_boxes[i];\n                    const Box<NDIM> covered_box = trim_box * refined_box;\n                    covered_boxes.unionBoxes(covered_box);\n                }\n            }\n            iterate_box_list.removeIntersections(covered_boxes);\n\n            // Loop over the boxes and store the location and interpolated value.\n            //~ Pointer<Data<NDIM, double> > p_data = patch->getPatchData(p_idx);\n            const Pointer<CellData<NDIM, double> > p_data = patch->getPatchData(p_idx);\n            const Pointer<CellData<NDIM, double> > wgt_cc_data = patch->getPatchData(wgt_cc_idx);\n            for (BoxList<NDIM>::Iterator lit(iterate_box_list); lit; lit++)\n            {\n                const Box<NDIM>& iterate_box = *lit;\n                for (Box<NDIM>::Iterator bit(iterate_box); bit; bit++)\n                {\n                    const CellIndex<NDIM>& cell_idx = *bit;\n\n                    const double y = patch_x_lower[1] + patch_dx[1] * (cell_idx(1) - patch_lower(1) + 0.5);\n                    const double x = patch_x_lower[0] + patch_dx[0] * (cell_idx(0) - patch_lower(0) + 0.5);\n                    //~ double p_ex_qp = -2.*p_e*x/L + p_e;\n\n                    const double p1 = (*p_data)(cell_idx);\n                    double p_ex_qp;\n\n                    N_max += 1;\n\n                    if (sqrt(x * x + y * y) <= R1 - fac * patch_dx[0])\n                    {\n                        p_ex_qp = 0.5 * OMEGA1 * OMEGA1 * (x * x + y * y) + shift; // p1;\n                    }\n                    else if (sqrt(x * x + y * y) > (R1 - fac * patch_dx[0]) &&\n                             sqrt(x * x + y * y) < (R1 + fac * patch_dx[0]))\n                    {\n                        p_ex_qp = p1;\n                    }\n                    else\n                    {\n                        p_ex_qp = 0.5 * AA * AA * (x * x + y * y) - 0.5 * BB * BB / (x * x + y * y) +\n                                  AA * BB * log(x * x + y * y) + 0.5 * OMEGA1 * OMEGA1 * R1 * R1 -\n                                  (0.5 * AA * AA * (R1 * R1) - 0.5 * BB * BB / (R1 * R1) + AA * BB * log(R1 * R1)) +\n                                  shift;\n                    }\n\n                    p_Eulerian_L2_norm += std::abs(p1 - p_ex_qp) * std::abs(p1 - p_ex_qp) * (*wgt_cc_data)(cell_idx);\n                    p_Eulerian_max_norm = std::max(p_Eulerian_max_norm, std::abs(p1 - p_ex_qp));\n                }\n            }\n        }\n    }\n    SAMRAI_MPI::sumReduction(&N_max, 1);\n    SAMRAI_MPI::sumReduction(&p_Eulerian_L2_norm, 1);\n    SAMRAI_MPI::maxReduction(&p_Eulerian_max_norm, 1);\n\n    p_Eulerian_L2_norm = sqrt(p_Eulerian_L2_norm);\n\n    pout << \" p_Eulerian_L2_norm = \" << p_Eulerian_L2_norm << \"\\n\\n\";\n    pout << \" p_Eulerian_max_norm = \" << p_Eulerian_max_norm << \"\\n\\n\";\n\n    return;\n} // pressure_convergence\n\nvoid\npostprocess_data(Pointer<PatchHierarchy<NDIM> > /*patch_hierarchy*/,\n                 Pointer<INSHierarchyIntegrator> /*navier_stokes_integrator*/,\n                 Mesh& mesh,\n                 EquationSystems* equation_systems,\n                 const int /*iteration_num*/,\n                 const double loop_time,\n                 const string& /*data_dump_dirname*/)\n{\n    const unsigned int dim = mesh.mesh_dimension();\n    double F_integral[NDIM];\n    for (unsigned int d = 0; d < NDIM; ++d) F_integral[d] = 0.0;\n\n    System& x_system = equation_systems->get_system(IIMethod::COORDS_SYSTEM_NAME);\n    System& U_system = equation_systems->get_system(IIMethod::VELOCITY_SYSTEM_NAME);\n    NumericVector<double>* x_vec = x_system.solution.get();\n    NumericVector<double>& X0_vec = x_system.get_vector(\"INITIAL_COORDINATES\");\n    NumericVector<double>* x_ghost_vec = x_system.current_local_solution.get();\n    x_vec->localize(*x_ghost_vec);\n    NumericVector<double>* U_vec = U_system.solution.get();\n    NumericVector<double>* U_ghost_vec = U_system.current_local_solution.get();\n    U_vec->localize(*U_ghost_vec);\n    const DofMap& dof_map = x_system.get_dof_map();\n    std::vector<std::vector<unsigned int> > dof_indices(NDIM);\n\n    std::unique_ptr<FEBase> fe(FEBase::build(dim, dof_map.variable_type(0)));\n    std::unique_ptr<QBase> qrule = QBase::build(QGAUSS, dim, SEVENTH);\n    fe->attach_quadrature_rule(qrule.get());\n    const vector<double>& JxW = fe->get_JxW();\n    const vector<libMesh::Point>& q_point = fe->get_xyz();\n    const vector<vector<double> >& phi = fe->get_phi();\n    const vector<vector<VectorValue<double> > >& dphi = fe->get_dphi();\n    // const std::vector<std::vector<double> >& dphi_dxi = fe->get_dphidxi();\n    //  const std::vector<std::vector<double> >& dphi_deta = fe->get_dphideta();\n    boost::array<VectorValue<double>, 2> dx_dxi;\n\n    boost::array<const std::vector<std::vector<double> >*, NDIM - 1> dphi_dxi;\n    dphi_dxi[0] = &fe->get_dphidxi();\n    if (NDIM > 2) dphi_dxi[1] = &fe->get_dphideta();\n\n    std::vector<double> U_qp_vec(NDIM);\n    std::vector<const std::vector<double>*> var_data(1);\n    var_data[0] = &U_qp_vec;\n    std::vector<const std::vector<libMesh::VectorValue<double> >*> grad_var_data;\n    void* force_fcn_ctx = NULL;\n\n    TensorValue<double> FF_qp;\n    boost::multi_array<double, 2> x_node, X_node, U_node, P_o_node, P_j_node;\n    VectorValue<double> F_qp, U_qp, x_qp, X_qp, N, n;\n\n    const MeshBase::const_element_iterator el_begin = mesh.active_local_elements_begin();\n    const MeshBase::const_element_iterator el_end = mesh.active_local_elements_end();\n    for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)\n    {\n        Elem* const elem = *el_it;\n        fe->reinit(elem);\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            dof_map.dof_indices(elem, dof_indices[d], d);\n        }\n        get_values_for_interpolation(x_node, *x_ghost_vec, dof_indices);\n        get_values_for_interpolation(X_node, X0_vec, dof_indices);\n        get_values_for_interpolation(U_node, *U_ghost_vec, dof_indices);\n\n        const unsigned int n_qp = qrule->n_points();\n        for (unsigned int qp = 0; qp < n_qp; ++qp)\n        {\n            interpolate(x_qp, qp, x_node, phi);\n            interpolate(X_qp, qp, X_node, phi);\n            jacobian(FF_qp, qp, x_node, dphi);\n            interpolate(U_qp, qp, U_node, phi);\n\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                U_qp_vec[d] = U_qp(d);\n            }\n            tether_force_function_inner(\n                F_qp, n, N, FF_qp, x_qp, q_point[qp], elem, 0, var_data, grad_var_data, loop_time, force_fcn_ctx);\n\n            for (int d = 0; d < NDIM; ++d)\n            {\n                F_integral[d] += F_qp(d) * JxW[qp];\n            }\n        }\n    }\n    SAMRAI_MPI::sumReduction(F_integral, NDIM);\n\n    {\n        double WSS_L2_norm = 0.0, WSS_max_norm = 0.0;\n        double U_L2_norm = 0.0, U_max_norm = 0.0;\n        double P_L2_norm = 0.0, P_max_norm = 0.0;\n        double disp_L2_norm = 0.0, disp_max_norm = 0.0;\n        System& U_system = equation_systems->get_system<System>(IIMethod::VELOCITY_SYSTEM_NAME);\n        System& WSS_system = equation_systems->get_system<System>(IIMethod::WSS_OUT_SYSTEM_NAME);\n        System& P_o_system = equation_systems->get_system<System>(IIMethod::PRESSURE_OUT_SYSTEM_NAME);\n        System& P_j_system = equation_systems->get_system<System>(IIMethod::PRESSURE_JUMP_SYSTEM_NAME);\n\n        NumericVector<double>* U_vec = U_system.solution.get();\n        NumericVector<double>* U_ghost_vec = U_system.current_local_solution.get();\n        U_vec->localize(*U_ghost_vec);\n        DofMap& U_dof_map = U_system.get_dof_map();\n        std::vector<std::vector<unsigned int> > U_dof_indices(NDIM);\n\n        NumericVector<double>* WSS_vec = WSS_system.solution.get();\n        NumericVector<double>* WSS_ghost_vec = WSS_system.current_local_solution.get();\n        WSS_vec->localize(*WSS_ghost_vec);\n        DofMap& WSS_dof_map = WSS_system.get_dof_map();\n        std::vector<std::vector<unsigned int> > WSS_dof_indices(NDIM);\n        std::unique_ptr<FEBase> fe(FEBase::build(dim, WSS_dof_map.variable_type(0)));\n\n        NumericVector<double>* P_o_vec = P_o_system.solution.get();\n        NumericVector<double>* P_o_ghost_vec = P_o_system.current_local_solution.get();\n        P_o_vec->localize(*P_o_ghost_vec);\n        DofMap& P_o_dof_map = P_o_system.get_dof_map();\n        std::vector<unsigned int> P_o_dof_indices;\n\n        NumericVector<double>* P_j_vec = P_j_system.solution.get();\n        NumericVector<double>* P_j_ghost_vec = P_j_system.current_local_solution.get();\n        P_j_vec->localize(*P_j_ghost_vec);\n        DofMap& P_j_dof_map = P_j_system.get_dof_map();\n        std::vector<unsigned int> P_j_dof_indices;\n\n        VectorValue<double> U_qp, WSS_qp;\n        double P_o_qp, P_j_qp;\n        VectorValue<double> tau1, tau2;\n        int qp_tot = 0;\n        boost::multi_array<double, 2> U_node, WSS_node;\n        boost::multi_array<double, 1> P_o_node, P_j_node;\n        const MeshBase::const_element_iterator el_begin = mesh.active_local_elements_begin();\n        const MeshBase::const_element_iterator el_end = mesh.active_local_elements_end();\n        for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)\n        {\n            Elem* const elem = *el_it;\n            // fe->reinit(elem);\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                dof_map.dof_indices(elem, dof_indices[d], d);\n                U_dof_map.dof_indices(elem, U_dof_indices[d], d);\n                WSS_dof_map.dof_indices(elem, WSS_dof_indices[d], d);\n            }\n            P_j_dof_map.dof_indices(elem, P_j_dof_indices);\n            P_o_dof_map.dof_indices(elem, P_o_dof_indices);\n            const int n_qp = qrule->n_points();\n            get_values_for_interpolation(U_node, *U_ghost_vec, U_dof_indices);\n            get_values_for_interpolation(WSS_node, *WSS_ghost_vec, WSS_dof_indices);\n            get_values_for_interpolation(P_j_node, *P_j_ghost_vec, P_j_dof_indices);\n            get_values_for_interpolation(P_o_node, *P_o_ghost_vec, P_o_dof_indices);\n            get_values_for_interpolation(x_node, *x_ghost_vec, dof_indices);\n            get_values_for_interpolation(X_node, X0_vec, dof_indices);\n\n            for (int qp = 0; qp < n_qp; ++qp)\n            {\n                interpolate(x_qp, qp, x_node, phi);\n                interpolate(X_qp, qp, X_node, phi);\n                interpolate(U_qp, qp, U_node, phi);\n                interpolate(WSS_qp, qp, WSS_node, phi);\n                interpolate(P_o_qp, qp, P_o_node, phi);\n                interpolate(P_j_qp, qp, P_j_node, phi);\n\n                for (unsigned int k = 0; k < NDIM - 1; ++k)\n                {\n                    interpolate(dx_dxi[k], qp, x_node, *dphi_dxi[k]);\n                }\n                if (NDIM == 2)\n                {\n                    dx_dxi[1] = VectorValue<double>(0.0, 0.0, 1.0);\n                }\n                n = (dx_dxi[0].cross(dx_dxi[1])).unit();\n\n                double ex_wss[NDIM];\n                double ex_U[NDIM];\n\n                ex_U[0] = (-x_qp(1) / sqrt(x_qp(0) * x_qp(0) + x_qp(1) * x_qp(1))) * R1 * OMEGA1;\n                ex_U[1] = (x_qp(0) / sqrt(x_qp(0) * x_qp(0) + x_qp(1) * x_qp(1))) * R1 * OMEGA1;\n                ex_U[2] = 0.0;\n                ex_wss[0] = (-x_qp(1) / sqrt(x_qp(0) * x_qp(0) + x_qp(1) * x_qp(1))) * MU * (AA - BB / (R1 * R1));\n                ex_wss[1] = (x_qp(0) / sqrt(x_qp(0) * x_qp(0) + x_qp(1) * x_qp(1))) * MU * (AA - BB / (R1 * R1));\n                ex_wss[2] = 0.0;\n                libMesh::Point X = q_point[qp];\n                double p_ex_qp = 0.5 * OMEGA1 * OMEGA1 * R1 * R1 + shift;\n                qp_tot += 1;\n                for (unsigned int d = 0; d < NDIM; ++d)\n                {\n                    U_L2_norm += (U_qp(d) - ex_U[d]) * (U_qp(d) - ex_U[d]) * JxW[qp];\n                    U_max_norm = std::max(U_max_norm, std::abs(U_qp(d) - ex_U[d]));\n\n                    WSS_L2_norm += (WSS_qp(d) - ex_wss[d]) * (WSS_qp(d) - ex_wss[d]) * JxW[qp];\n                    WSS_max_norm = std::max(WSS_max_norm, std::abs(WSS_qp(d) - ex_wss[d]));\n                }\n                P_L2_norm += std::abs(P_o_qp - p_ex_qp) * std::abs(P_o_qp - p_ex_qp) * JxW[qp];\n                P_max_norm = std::max(P_max_norm, std::abs(P_o_qp - p_ex_qp));\n\n                disp_L2_norm += (X_qp(0) * cos(OMEGA1 * loop_time) - X_qp(1) * sin(OMEGA1 * loop_time) - x_qp(0)) *\n                                (X_qp(0) * cos(OMEGA1 * loop_time) - X_qp(1) * sin(OMEGA1 * loop_time) - x_qp(0)) *\n                                JxW[qp];\n                disp_L2_norm += (X_qp(0) * sin(OMEGA1 * loop_time) + X_qp(1) * cos(OMEGA1 * loop_time) - x_qp(1)) *\n                                (X_qp(0) * sin(OMEGA1 * loop_time) + X_qp(1) * cos(OMEGA1 * loop_time) - x_qp(1)) *\n                                JxW[qp];\n                disp_L2_norm += (X_qp(2) - x_qp(2)) * (X_qp(2) - x_qp(2)) * JxW[qp];\n                disp_max_norm =\n                    std::max(disp_max_norm,\n                             std::abs(X_qp(0) * cos(OMEGA1 * loop_time) - X_qp(1) * sin(OMEGA1 * loop_time) - x_qp(0)));\n                disp_max_norm =\n                    std::max(disp_max_norm,\n                             std::abs(X_qp(0) * sin(OMEGA1 * loop_time) + X_qp(1) * cos(OMEGA1 * loop_time) - x_qp(1)));\n                disp_max_norm = std::max(disp_max_norm, std::abs(X_qp(2) - x_qp(2)));\n            }\n        }\n\n        SAMRAI_MPI::sumReduction(&qp_tot, 1);\n        SAMRAI_MPI::sumReduction(&WSS_L2_norm, 1);\n        SAMRAI_MPI::maxReduction(&WSS_max_norm, 1);\n        SAMRAI_MPI::sumReduction(&U_L2_norm, 1);\n        SAMRAI_MPI::maxReduction(&U_max_norm, 1);\n        SAMRAI_MPI::sumReduction(&disp_L2_norm, 1);\n        SAMRAI_MPI::maxReduction(&disp_max_norm, 1);\n        SAMRAI_MPI::sumReduction(&P_L2_norm, 1);\n        SAMRAI_MPI::maxReduction(&P_max_norm, 1);\n\n        U_L2_norm = sqrt(U_L2_norm);\n        WSS_L2_norm = sqrt(WSS_L2_norm);\n        disp_L2_norm = sqrt(disp_L2_norm);\n        P_L2_norm = sqrt(P_L2_norm);\n\n        pout << \" Lagrangian WSS_L2_norm = \" << WSS_L2_norm << \"\\n\\n\";\n        pout << \" Lagrangian WSS_max_norm = \" << WSS_max_norm << \"\\n\\n\";\n\n        pout << \" Lagrangian U_L2_norm = \" << U_L2_norm << \"\\n\\n\";\n        pout << \" Lagrangian U_max_norm = \" << U_max_norm << \"\\n\\n\";\n\n        pout << \" Lagrangian disp_L2_norm = \" << disp_L2_norm << \"\\n\\n\";\n        pout << \" Lagrangian disp_max_norm = \" << disp_max_norm << \"\\n\\n\";\n\n        pout << \"Lagrangian P_L2_norm = \" << P_L2_norm << \"\\n\\n\";\n        pout << \"Lagrangian P_max_norm = \" << P_max_norm << \"\\n\\n\";\n    }\n\n    return;\n} // postprocess_data\n", "meta": {"hexsha": "9cb316edc1b9ea7825d9042802b99de69eabf59f", "size": 46898, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/IIM/taylor_couette_3d.cpp", "max_stars_repo_name": "akashdhruv/IBAMR", "max_stars_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "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/IIM/taylor_couette_3d.cpp", "max_issues_repo_name": "akashdhruv/IBAMR", "max_issues_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T17:54:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-30T17:54:49.000Z", "max_forks_repo_path": "tests/IIM/taylor_couette_3d.cpp", "max_forks_repo_name": "akashdhruv/IBAMR", "max_forks_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-30T03:40:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-30T03:40:20.000Z", "avg_line_length": 47.3239152371, "max_line_length": 120, "alphanum_fraction": 0.5777218645, "num_tokens": 11662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.5152098619976065}}
{"text": "  //==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2014 MetaScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_SSE_SSE2_FAST_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_SSE_SSE2_FAST_RSQRT_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT\n\n#include <boost/simd/arithmetic/functions/fast_rsqrt.hpp>\n#include <boost/simd/include/functions/simd/multiplies.hpp>\n#include <boost/simd/include/functions/simd/minus.hpp>\n#include <boost/simd/include/functions/simd/sqr.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( fast_rsqrt_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)\n                                    , ((simd_ < single_<A0>\n                                              , boost::simd::tag::sse_\n                                              >\n                                      ))\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      result_type nr  = _mm_rsqrt_ps( a0 );\n                  nr *= 0.5f * (3.f - a0 * sqr(nr));\n\n      return nr;\n    }\n  };\n} } }\n\n#endif\n\n#endif\n", "meta": {"hexsha": "72a63e65583a7094942eeb8fe0c2f93c70fd6c04", "size": 1729, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/sse/sse2/fast_rsqrt.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/sse/sse2/fast_rsqrt.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/sse/sse2/fast_rsqrt.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 37.5869565217, "max_line_length": 82, "alphanum_fraction": 0.5124349335, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5152098619976064}}
{"text": "#include <boost/math/distributions/arcsine.hpp>\n", "meta": {"hexsha": "bbaeaed7522909cbbfcfb7b0e6b0c74461ce706e", "size": 48, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_arcsine.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_arcsine.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_arcsine.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.0, "max_line_length": 47, "alphanum_fraction": 0.8125, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199471193039, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5152098570110937}}
{"text": "/* Copyright (c) 2020, Danish Technological Institute.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree.\n * \n * Original author: Lars Berscheid <lars.berscheid@kit.edu>\n */\n\n#pragma once\n\n#define BIN_PICKING_GEOMETRY\n\n#include <geometry_msgs/PoseStamped.h>\n\n#include <Eigen/Geometry>\n#include <unsupported/Eigen/EulerAngles>\n\n\nstruct Affine {\nprivate:\n  using Euler = Eigen::EulerAngles<double, Eigen::EulerSystemZYX>;\n\n  Eigen::Vector3d get_angles() const {\n    Eigen::Vector3d angles = Euler::FromRotation<false, false, false>(data.rotation()).angles();\n    Eigen::Vector3d angles_equal;\n    angles_equal << angles[0] - M_PI, M_PI - angles[1], angles[2] - M_PI;\n\n    if (angles_equal[1] > M_PI) {\n      angles_equal[1] -= 2 * M_PI;\n    }\n    if (angles_equal[2] < -M_PI) {\n      angles_equal[2] += 2 * M_PI;\n    }\n\n    if (angles.norm() < angles_equal.norm()) {\n      return angles;\n    }\n    return angles_equal;\n  }\n\n\npublic:\n  using Vector6d = Eigen::Matrix<double, 6, 1>;\n\n  Eigen::Affine3d data;\n\n  Affine() {\n    this->data = Eigen::Affine3d::Identity();\n  }\n\n  Affine(const Eigen::Affine3d& data) {\n    this->data = data;\n  }\n\n  Affine(double x, double y, double z, double a, double b, double c) {\n    data = Eigen::Translation<double, 3>(x, y, z) * Euler(a, b, c).toRotationMatrix();\n  }\n\n  Affine(const std::array<double, 6>& v): Affine(v[0], v[1], v[2], v[3], v[4], v[5]) { }\n\n  Affine(const Eigen::Matrix<double, 6, 1>& v): Affine(v(0), v(1), v(2), v(3), v(4), v(5)) { }\n\n  Affine(const geometry_msgs::Pose& pose) {\n    auto position = pose.position;\n    auto orientation = pose.orientation;\n\n    Eigen::Translation<double, 3> t {position.x, position.y, position.z};\n    Eigen::Quaternion<double> q {orientation.w, orientation.x, orientation.y, orientation.z};\n\n    data = t * q;\n  }\n\n  Affine operator *(const Affine &a) const {\n    Eigen::Affine3d result;\n    result = data * a.data;\n    return Affine(result);\n  }\n\n  Affine inverse() const {\n    return Affine(data.inverse());\n  }\n\n  bool isApprox(const Affine &a) const {\n    return data.isApprox(a.data);\n  }\n\n  Eigen::Ref<Eigen::Affine3d::MatrixType> matrix() {\n    return data.matrix();\n  }\n\n  void translate(const Eigen::Vector3d &v) {\n    data.translate(v);\n  }\n\n  void pretranslate(const Eigen::Vector3d &v) {\n    data.pretranslate(v);\n  }\n\n  Eigen::Vector3d translation() const {\n    Eigen::Vector3d v;\n    v << data.translation();\n    return v;\n  }\n\n  double x() const {\n    return data.translation()(0);\n  }\n\n  void set_x(double x) {\n    data.translation()(0) = x;\n  }\n\n  double y() const {\n    return data.translation()(1);\n  }\n\n  void set_y(double y) {\n    data.translation()(1) = y;\n  }\n\n  double z() const {\n    return data.translation()(2);\n  }\n\n  void set_z(double z) {\n    data.translation()(2) = z;\n  }\n\n  void rotate(const Eigen::Affine3d::LinearMatrixType &r) {\n    data.rotate(r);\n  }\n\n  void prerotate(const Eigen::Affine3d::LinearMatrixType &r) {\n    data.prerotate(r);\n  }\n\n  Eigen::Affine3d::LinearMatrixType rotation() const {\n    Eigen::Affine3d::LinearMatrixType result;\n    result << data.rotation();\n    return result;\n  }\n\n  double a() const {\n    return get_angles()(0);\n  }\n\n  double b() const {\n    return get_angles()(1);\n  }\n\n  double c() const {\n    return get_angles()(2);\n  }\n\n  void set_a(double a) {\n    Eigen::Matrix<double, 3, 1> angles;\n    angles << get_angles();\n    data = Eigen::Translation<double, 3>(data.translation()) * Euler(a, angles(1), angles(2)).toRotationMatrix();\n  }\n\n  void set_b(double b) {\n    Eigen::Matrix<double, 3, 1> angles;\n    angles << get_angles();\n    data = Eigen::Translation<double, 3>(data.translation()) * Euler(angles(0), b, angles(2)).toRotationMatrix();\n  }\n\n  void set_c(double c) {\n    Eigen::Matrix<double, 3, 1> angles;\n    angles << get_angles();\n    data = Eigen::Translation<double, 3>(data.translation()) * Euler(angles(0), angles(1), c).toRotationMatrix();\n  }\n\n  geometry_msgs::Pose toPose() const {\n    Eigen::Quaternion<double> q;\n    q = data.rotation();\n    auto t = data.translation();\n\n    geometry_msgs::Pose result;\n    result.position.x = t(0);\n    result.position.y = t(1);\n    result.position.z = t(2);\n    result.orientation.x = q.x();\n    result.orientation.y = q.y();\n    result.orientation.z = q.z();\n    result.orientation.w = q.w();\n    return result;\n  }\n\n  std::array<double, 6> toArray() const {\n    Eigen::Matrix<double, 6, 1> v;\n    v << data.translation(), get_angles();\n    return {v(0), v(1), v(2), v(3), v(4), v(5)};\n  }\n\n  Affine getInnerRandom() const {\n    std::random_device r;\n    std::default_random_engine engine(r());\n\n    Eigen::Matrix<double, 6, 1> random;\n    Eigen::Matrix<double, 6, 1> max;\n    max << data.translation(), get_angles();\n\n    for (int i = 0; i < 6; i++) {\n      std::uniform_real_distribution<double> distribution(-max(i), max(i));\n      random(i) = distribution(engine);\n    }\n\n    return Affine(random);\n  }\n\n  std::string toString() const {\n    Eigen::Matrix<double, 6, 1> v;\n    v << data.translation(), get_angles();\n\n    return \"[\" + std::to_string(v(0)) + \", \" + std::to_string(v(1)) + \", \" + std::to_string(v(2))\n      + \", \" + std::to_string(v(3)) + \", \" + std::to_string(v(4)) + \", \" + std::to_string(v(5)) + \"]\";\n  }\n};\n", "meta": {"hexsha": "0c93a09a3044944fc3882f46b9c7c4b47a8adb34", "size": 5351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "frankr/include/geometry.hpp", "max_stars_repo_name": "dkuss-tudresden/frankr", "max_stars_repo_head_hexsha": "9a48a24488bd6bae3777f89e3d8cefd40368aaa2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-12-02T16:51:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T10:29:42.000Z", "max_issues_repo_path": "frankr/include/geometry.hpp", "max_issues_repo_name": "dkuss-tudresden/frankr", "max_issues_repo_head_hexsha": "9a48a24488bd6bae3777f89e3d8cefd40368aaa2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-22T02:38:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-22T19:13:42.000Z", "max_forks_repo_path": "frankr/include/geometry.hpp", "max_forks_repo_name": "dkuss-tudresden/frankr", "max_forks_repo_head_hexsha": "9a48a24488bd6bae3777f89e3d8cefd40368aaa2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-02T15:22:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T08:25:39.000Z", "avg_line_length": 24.3227272727, "max_line_length": 113, "alphanum_fraction": 0.6170809195, "num_tokens": 1549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5152098570110937}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE constexpr_vector_test\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n\n#include <nil/crypto3/algebra/vector/vector.hpp>\n#include <nil/crypto3/algebra/vector/math.hpp>\n#include <nil/crypto3/algebra/vector/operators.hpp>\n#include <nil/crypto3/algebra/vector/utility.hpp>\n\nusing namespace nil::crypto3::algebra;\n\nstatic_assert(make_vector(1, 2, 3) == vector {1, 2, 3}, \"make_vector and uniform initialization deduction guide\");\n\nstatic_assert(make_vector(1, 2, 3) == vector {{1, 2, 3}}, \"make_vector and aggregate initialization deduction guide\");\n\nstatic_assert(elementwise([](double x) { return 1 / x; }, vector {1., 2., 4.}) == vector {1., 0.5, 0.25},\n              \"elementwise\");\n\nstatic_assert(vector {1, 2, 3} == vector {1, 2, 3}, \"operator==\");\n\nstatic_assert(vector {1, 2, 3} != vector {3, 2, 1}, \"operator!=\");\n\nstatic_assert(vector {1, 2, 3} + vector {1, 2, 3} == vector {2, 4, 6}, \"operator+\");\n\nstatic_assert(sum(vector {1, 2, 3}) == 6, \"sum\");\n\nstatic_assert(iota<5>(0) == vector {0, 1, 2, 3, 4}, \"iota\");\n\nstatic_assert(iota<5, double>() == vector {0., 1., 2., 3., 4.}, \"iota\");\n\nstatic_assert(fill<4>(2.) == vector {2., 2., 2., 2.}, \"fill\");\n\nstatic_assert(generate<4>([](auto i) { return double(i * i); }) == vector {0., 1., 4., 9.}, \"generate\");\n\nstatic_assert(vector {1, 2, 3} == slice<3>(vector {1, 2, 3, 4}), \"slice-no offset\");\n\nstatic_assert(vector {2, 3, 4} == slice<3>(vector {1, 2, 3, 4}, 1), \"slice with offset\");\n", "meta": {"hexsha": "20cbf123bf3882c423bc3a2151de0db1bdece337", "size": 2922, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/vector.cpp", "max_stars_repo_name": "JasonCoombs/crypto3-algebra", "max_stars_repo_head_hexsha": "3ddb4eb0ed65dc046660cc49811d17a140a4c72f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-20T18:56:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T06:58:28.000Z", "max_issues_repo_path": "test/vector.cpp", "max_issues_repo_name": "JasonCoombs/crypto3-algebra", "max_issues_repo_head_hexsha": "3ddb4eb0ed65dc046660cc49811d17a140a4c72f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2020-08-27T18:11:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T21:01:55.000Z", "max_forks_repo_path": "test/vector.cpp", "max_forks_repo_name": "NilFoundation/algebra", "max_forks_repo_head_hexsha": "f211b0ffb2c7d817d44d2a6d1cc586a6db62dc03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-05T13:50:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T03:09:12.000Z", "avg_line_length": 44.9538461538, "max_line_length": 118, "alphanum_fraction": 0.6605065024, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.5152035207768662}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\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// Licensed under the Boost Software License version 1.0.\r\n// http://www.boost.org/users/license.html\r\n\r\n#ifndef BOOST_TEST_MODULE\r\n#define BOOST_TEST_MODULE test_distance_geographic_pl_l\r\n#endif\r\n\r\n//#include <boost/geometry/core/srs.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\n#include \"test_distance_geo_common.hpp\"\r\n\r\ntypedef bg::cs::geographic<bg::degree> cs_type;\r\ntypedef bg::model::point<double, 2, cs_type> point_type;\r\ntypedef bg::model::multi_point<point_type> multi_point_type;\r\n\r\nnamespace services = bg::strategy::distance::services;\r\ntypedef bg::default_distance_result<point_type>::type return_type;\r\n\r\ntypedef bg::srs::spheroid<double> stype;\r\n\r\n// Strategies for point-point distance\r\n\r\ntypedef bg::strategy::distance::andoyer<stype> andoyer;\r\ntypedef bg::strategy::distance::thomas<stype> thomas;\r\ntypedef bg::strategy::distance::vincenty<stype> vincenty;\r\n\r\n//===========================================================================\r\n\r\ntemplate <typename Strategy>\r\ninline bg::default_distance_result<point_type>::type\r\npp_distance(std::string const& wkt1,\r\n            std::string const& wkt2,\r\n            Strategy const& strategy)\r\n{\r\n    point_type p1, p2;\r\n    bg::read_wkt(wkt1, p1);\r\n    bg::read_wkt(wkt2, p2);\r\n    return bg::distance(p1, p2, strategy);\r\n}\r\n\r\n//===========================================================================\r\n\r\ntemplate <typename Strategy>\r\nvoid test_distance_multipoint_point(Strategy const& strategy)\r\n{\r\n\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl;\r\n    std::cout << \"multipoint/point distance tests\" << std::endl;\r\n#endif\r\n    typedef test_distance_of_geometries<multi_point_type, point_type> tester;\r\n\r\n    tester::apply(\"mp-p-01\",\r\n                  \"MULTIPOINT(1 1,1 2,2 3)\",\r\n                  \"POINT(0 0)\",\r\n                  pp_distance(\"POINT(0 0)\",\"POINT(1 1)\",strategy),\r\n                  strategy);\r\n\r\n    tester::apply(\"mp-p-01\",\r\n                  \"MULTIPOINT(0 0,0 2,2 0,2 2)\",\r\n                  \"POINT(1.1 1.1)\",\r\n                  pp_distance(\"POINT(1.1 1.1)\",\"POINT(2 2)\",strategy),\r\n                  strategy);\r\n}\r\n\r\n//===========================================================================\r\n\r\ntemplate <typename Point, typename Strategy>\r\nvoid test_empty_input_pointlike_linear(Strategy const& strategy)\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl;\r\n    std::cout << \"testing on empty inputs... \" << std::flush;\r\n#endif\r\n    bg::model::multi_point<Point> multipoint_empty;\r\n    Point point_empty;\r\n\r\n    Point point = from_wkt<Point>(\"POINT(0 0)\");\r\n\r\n    // 1st geometry is empty\r\n    test_empty_input(multipoint_empty, point, strategy);\r\n\r\n    // 2nd geometry is empty\r\n    test_empty_input(point, multipoint_empty, strategy);\r\n\r\n    // both geometries are empty\r\n    test_empty_input(multipoint_empty, point_empty, strategy);\r\n\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << \"done!\" << std::endl;\r\n#endif\r\n}\r\n\r\n//===========================================================================\r\n//===========================================================================\r\n//===========================================================================\r\n\r\nBOOST_AUTO_TEST_CASE( test_all_point_segment )\r\n{\r\n    test_distance_multipoint_point(vincenty());\r\n    test_distance_multipoint_point(thomas());\r\n    test_distance_multipoint_point(andoyer());\r\n\r\n    test_empty_input_pointlike_linear<point_type>(vincenty());\r\n    test_empty_input_pointlike_linear<point_type>(thomas());\r\n    test_empty_input_pointlike_linear<point_type>(andoyer());\r\n}\r\n", "meta": {"hexsha": "c7c376fd3fd53fe451abbe79c09c5a0e4d39704a", "size": 3796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/distance/distance_geo_pl_pl.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/distance/distance_geo_pl_pl.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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/distance/distance_geo_pl_pl.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": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.724137931, "max_line_length": 78, "alphanum_fraction": 0.595890411, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5152035143030453}}
{"text": "#ifndef __UNIVARIATEQUADRATURE__CLASS__\n#define __UNIVARIATEQUADRATURE__CLASS__\n\n#include <vector>\n\n#include <Eigen/Dense>\n\n// struct that contains a particular quadrature rule\nstruct Quadrature {\n  Eigen::VectorXd xi;\n  Eigen::VectorXd w;\n};\n\n/**   \\brief basis class for univariate quadrature rules\n*\n*/\nclass UnivariateQuadrature {\n public:\n  UnivariateQuadrature(void) : _maxLvl(-1){};\n  // setter...\n  virtual void initQuadrature(int maxLvl) = 0;\n  virtual void resizeQuadrature(int maxLvl) = 0;\n  // tester...\n  virtual void testQuadrature(int maxLvl) = 0;\n  // getter...\n  int get_maxLvl(void) const { return _maxLvl; };\n  const std::vector<Quadrature> &get_Q(void) const {\n    return (const std::vector<Quadrature> &)_Q;\n  };\n\n protected:\n  int _maxLvl;\n  std::vector<Quadrature> _Q;\n};\n\n#endif\n", "meta": {"hexsha": "c840b007589fabc7a1264648f84626a16f6a1ca1", "size": 803, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "UnivariateQuadrature.hpp", "max_stars_repo_name": "T3ks/SPQR", "max_stars_repo_head_hexsha": "b554d172fc798caa7a708bfbbb71a21d136403b1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-09-11T12:02:57.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-11T12:02:57.000Z", "max_issues_repo_path": "UnivariateQuadrature.hpp", "max_issues_repo_name": "T3ks/SPQR", "max_issues_repo_head_hexsha": "b554d172fc798caa7a708bfbbb71a21d136403b1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UnivariateQuadrature.hpp", "max_forks_repo_name": "T3ks/SPQR", "max_forks_repo_head_hexsha": "b554d172fc798caa7a708bfbbb71a21d136403b1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-01-28T02:25:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-12T16:43:19.000Z", "avg_line_length": 21.7027027027, "max_line_length": 56, "alphanum_fraction": 0.7135740971, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5152035020951641}}
{"text": "#define GLM_ENABLE_EXPERIMENTAL 1\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Halide.h>\n#include <fstream>\n#include <glm/ext.hpp>\n#include <glm/glm.hpp>\n#include <halide_image_io.h>\n#include <stdio.h>\n#include <iostream>\n#include <ImfRgbaFile.h>\n#include <ImfStringAttribute.h>\n#include <ImfMatrixAttribute.h>\n#include <ImfArray.h>\n#include <algorithm>\n#include <ImfNamespace.h>\n#include <tuple>\n#include <math.h>\n\nnamespace IMF = OPENEXR_IMF_NAMESPACE;\n\nusing namespace IMF;\nusing namespace IMATH_NAMESPACE;\n\nusing namespace Halide;\nusing namespace Halide::Tools;\nusing namespace Eigen;\nusing namespace std;\n\nusing Vector4h = Matrix<Halide::Expr, 4, 1>;\nusing Matrix4h = Matrix<Halide::Expr, 4, 4>;\n\nVar x, y, c, i, ii, xo, yo, xi, yi, img;\n\nMatrix4h read4x4MatFromCSV(string csvFile)\n{\n    Matrix4h transfMat;\n    ifstream in(csvFile);\n    vector<float> floatVec;\n    if (in)\n    {\n        string line;\n        while (getline(in, line))\n        {\n            stringstream sep(line);\n            string field;\n            while (getline(sep, field, ','))\n            {\n                float val = stod(field);\n                floatVec.push_back(val);\n            }\n        }\n    }\n    transfMat << floatVec[0], floatVec[1], floatVec[2], floatVec[3],\n        floatVec[4], floatVec[5], floatVec[6], floatVec[7],\n        floatVec[8], floatVec[9], floatVec[10], floatVec[11],\n        floatVec[12], floatVec[13], floatVec[14], floatVec[15];\n    return transfMat;\n}\nostream &operator<<(ostream &os, const Matrix4h &m)\n{\n    os << m(0, 0) << \" \" << m(0, 1) << \" \" << m(0, 2) << \" \" << m(0, 3) << \"\\n\"\n       << m(1, 0) << \" \" << m(1, 1) << \" \" << m(1, 2) << \" \" << m(1, 3) << \"\\n\"\n       << m(2, 0) << \" \" << m(2, 1) << \" \" << m(2, 2) << \" \" << m(2, 3) << \"\\n\"\n       << m(3, 0) << \" \" << m(3, 1) << \" \" << m(3, 2) << \" \" << m(3, 3) << endl;\n    return os;\n}\n\nostream &operator<<(ostream &os, const Vector4h &v)\n{\n    os << v(0) << \"\\n\"\n       << v(1) << \"\\n\"\n       << v(2) << \"\\n\"\n       << v(3) << endl;\n    return os;\n}\n\nMatrix4h getCameraMatrix(float focalLen, float pxDim, int width, int height)\n{\n\n    focalLen = focalLen * 10e-3;\n    float u0 = width / 2.0;\n    float v0 = height / 2.0;\n    Matrix4h camMat;\n    float diagEntry = focalLen / pxDim;\n    camMat << diagEntry, 0.0f, u0, 0.0f,\n        0.0f, diagEntry, v0, 0.0f,\n        0.0f, 0.0f, 1.0f, 0.0f,\n        0.0f, 0.0f, 0.0f, 1.0f;\n\n    return camMat;\n}\n\nMatrix4h getInvCameraMat(float focalLen, float pxDim, int width, int height)\n{\n    focalLen = focalLen * 10e-3;\n    float u0 = width / 2.0;\n    float v0 = height / 2.0;\n    Matrix4h camMat;\n    camMat << pxDim / focalLen, 0.0f, -pxDim * u0 / focalLen, 0.0f,\n        0.0f, pxDim / focalLen, -pxDim * v0 / focalLen, 0.0f,\n        0.0f, 0.0f, 1.0f, 0.0f,\n        0.0f, 0.0f, 0.0f, 1.0f;\n\n    return camMat;\n}\n\nMatrix4h getTransMatProjToCam()\n{\n    Matrix4h transMat;\n    transMat << 0.9945219f, 0.0f, -0.10452846f, -0.2f,\n        0.0f, 1.0f, 0.0f, 0.0f,\n        0.10452846f, 0.0f, 0.9945219f, 0.0f,\n        0.0f, 0.0f, 0.0f, 1.0f;\n    return transMat;\n}\n\ntuple<int, int> readOpenEXR(const char filename[], Array2D<Rgba> &pixels)\n{\n    RgbaInputFile file(filename);\n    Box2i dw = file.dataWindow();\n\n    int width = dw.max.x - dw.min.x + 1;\n    int height = dw.max.y - dw.min.y + 1;\n    cout << \"Width: \" << width << \"    Height: \" << height << endl;\n    tuple<int, int> dim(width, height);\n    pixels.resizeErase(height, width);\n\n    file.setFrameBuffer(&pixels[0][0] - dw.min.x - dw.min.y * width, 1, width);\n    file.readPixels(dw.min.y, dw.max.y);\n    return dim;\n}\n\nvoid exrArrayToHalideBuffer(Array2D<Rgba> &pixels, Buffer<float> &halideBuffer, int width, int height)\n{\n    for (int row{0}; row < height; row++)\n    {\n        for (int col{0}; col < width; col++)\n        {\n            isinf(pixels[row][col].r) ? pixels[row][col].r = 0.0f : pixels[row][col].r = pixels[row][col].r;\n            halideBuffer(col, row) = pixels[row][col].r;\n        }\n    }\n}\n\nvoid saveImage(Expr result, size_t width, size_t height, const string &basename)\n{\n    Target target = get_host_target();\n    Func byteResult;\n    byteResult(x, y) = cast<uint8_t>(clamp(result, 0.0f, 1.0f) * 255.0f);\n    byteResult.compile_jit(target);\n    Buffer<uint8_t> output(width, height);\n    byteResult.realize(output);\n    stringstream filename;\n    filename << basename << \".png\";\n    save_image(output, filename.str());\n}\n\nvoid saveImageRaw(Expr result, size_t width, size_t height, const string &basename)\n{\n    Target target = get_host_target();\n    Func byteResult;\n    byteResult(x, y) = cast<uint8_t>(result);\n    byteResult.compile_jit(target);\n    Buffer<uint8_t> output(width, height);\n    byteResult.realize(output);\n    stringstream filename;\n    filename << basename;\n    save_image(output, filename.str());\n}\n\nvoid saveImageEXR(Expr result, int width, int height, const char fileName[])\n{\n    result = cast<float>(result);\n    Target target = get_host_target();\n    Func byteResult;\n    byteResult(x, y) = result;\n    Buffer<float> output(width, height);\n    byteResult.compile_jit(target);\n    byteResult.realize(output);\n\n    Array2D<Rgba> pixels;\n    pixels.resizeErase(height, width);\n    for (int row{0}; row < height; row++)\n    {\n        for (int col{0}; col < width; col++)\n        {\n            pixels[row][col].r = output(col, row);\n            pixels[row][col].g = output(col, row);\n            pixels[row][col].b = output(col, row);\n        }\n    }\n    RgbaOutputFile file(fileName, width, height, WRITE_RGBA);\n    file.setFrameBuffer(&pixels[0][0], 1, width);\n    file.writePixels(height);\n}\n\nvoid debugImageEXR(Expr channel1Expr, Expr channel2Expr, Expr channel3Expr, int width, int height, const char fileName[])\n{\n    channel1Expr = cast<float>(channel1Expr);\n    channel2Expr = cast<float>(channel2Expr);\n    channel3Expr = cast<float>(channel3Expr);\n    Target target = get_host_target();\n    Func byteResult;\n    byteResult(x, y, c) = 0.0f;\n    byteResult(x, y, 0) = channel1Expr;\n    byteResult(x, y, 1) = channel2Expr;\n    byteResult(x, y, 2) = channel3Expr;\n    Buffer<float> output(width, height, 3);\n    byteResult.compile_jit(target);\n    byteResult.realize(output);\n\n    Array2D<Rgba> pixels;\n    pixels.resizeErase(height, width);\n    for (int row{0}; row < height; row++)\n    {\n        for (int col{0}; col < width; col++)\n        {\n            pixels[row][col].r = output(col, row, 0);\n            pixels[row][col].g = output(col, row, 1);\n            pixels[row][col].b = output(col, row, 2);\n        }\n    }\n    RgbaOutputFile file(fileName, width, height, WRITE_RGBA);\n    file.setFrameBuffer(&pixels[0][0], 1, width);\n    file.writePixels(height);\n}\n\nint main(int argc, char **argv)\n{\n    const string INPUTFILE = \"images/depth-img/Image0000.exr\";\n    const string TRANSF_MAT_WORLD_TO_PROJ_CSV = \"matrices/transf-world-proj.csv\";\n    const string TRANSF_PROJ_CAM_CSV = \"matrices/transf-proj-cam.csv\";\n    const string INV_CAM_MAT_CSV = \"matrices/inv-cam-mat.csv\";\n    const string CAM_MAT_CSV = \"matrices/cam-mat.csv\";\n    const string OUTPUT_X_PROJ_EXR = \"images/ground-truth/x-val-proj-gt.exr\";\n    const string OUTPUT_X_PROJ_PNG = \"images/ground-truth/x-val-proj-gt.png\";\n    const bool SAVE_DEBUG_IMAGES = false;\n\n    Array2D<Rgba> pixels;\n    int width, height;\n    tie(width, height) = readOpenEXR(INPUTFILE.c_str(), pixels);\n    Buffer<float> input(width, height);\n    exrArrayToHalideBuffer(pixels, input, width, height);\n    cout << \"Width: \" << width << \"  Height: \" << height << endl;\n    Matrix4h camMat = read4x4MatFromCSV(CAM_MAT_CSV);\n    Matrix4h camMatInv = read4x4MatFromCSV(INV_CAM_MAT_CSV);\n    Matrix4h transfMatProjToCam = read4x4MatFromCSV(TRANSF_PROJ_CAM_CSV);\n    cout << \"Camera matrix\" << endl;\n    cout << camMat << endl;\n    cout << \"Inverse camera matrix\" << endl;\n    cout << camMatInv << endl;\n    cout << \"Transformation matrix projector to camera\" << endl;\n    cout << transfMatProjToCam << endl;\n\n    Expr zDepthCam = input(x, y);\n    zDepthCam = cast<double>(zDepthCam);\n    Vector4h pxCam{x, y, 1.0f, 0.0f};\n    pxCam(0) = cast<double>(pxCam(0));\n    pxCam(1) = cast<double>(pxCam(1));\n    pxCam(2) = cast<double>(pxCam(2));\n    pxCam(3) = cast<double>(pxCam(3));\n    Vector4h normCam = camMatInv * pxCam;\n    Vector4h ptCam = normCam / normCam(2) * zDepthCam;\n    ptCam(3) = 1.0f;\n    Vector4h ptProj = transfMatProjToCam * ptCam;\n    Vector4h normProj = ptProj / ptProj(2);\n    ptProj(3) = 0.0f;\n    Vector4h pxProj = camMat * normProj;\n    //normProj = normProj / normProj(2);\n    Expr xPxProj = pxProj(0);\n    //saveImage(xValProj, width, height, \"x-val-proj-gt\");\n    saveImageEXR(xPxProj, width, height, OUTPUT_X_PROJ_EXR.c_str());\n    Expr toPng = xPxProj * 256 / 1920;\n    saveImageRaw(toPng, width, height, OUTPUT_X_PROJ_PNG.c_str());\n\n    if (SAVE_DEBUG_IMAGES)\n    {\n        debugImageEXR(pxCam(0), pxCam(1), pxCam(2), width, height, \"pxCam.exr\");\n        debugImageEXR(normCam(0), normCam(1), normCam(2), width, height, \"normCam.exr\");\n        debugImageEXR(ptCam(0), ptCam(1), ptCam(2), width, height, \"ptCam.exr\");\n        debugImageEXR(ptProj(0), ptProj(1), ptProj(2), width, height, \"ptProj.exr\");\n        debugImageEXR(normProj(0), normProj(1), normProj(3), width, height, \"normProj.exr\");\n        debugImageEXR(pxProj(0), pxProj(1), pxProj(2), width, height, \"pxProj.exr\");\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "8c02618cbd56652a8324fe792eedaa320d7c7c1d", "size": 9397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "structured_light/cpp/depth-img-to-proj-x/depthImgToProjX.cpp", "max_stars_repo_name": "olaals/prosjektoppgave", "max_stars_repo_head_hexsha": "048c5c01cf428846c76b1c27abd4c0f451056e03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "structured_light/cpp/depth-img-to-proj-x/depthImgToProjX.cpp", "max_issues_repo_name": "olaals/prosjektoppgave", "max_issues_repo_head_hexsha": "048c5c01cf428846c76b1c27abd4c0f451056e03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "structured_light/cpp/depth-img-to-proj-x/depthImgToProjX.cpp", "max_forks_repo_name": "olaals/prosjektoppgave", "max_forks_repo_head_hexsha": "048c5c01cf428846c76b1c27abd4c0f451056e03", "max_forks_repo_licenses": ["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.5155709343, "max_line_length": 121, "alphanum_fraction": 0.6149835054, "num_tokens": 3056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5152035020951641}}
{"text": "// -------------------------------------------------------------------------------------------------\n//                              Copyright 2016 - NumScale SAS\n//\n//                   Distributed under the Boost Software License, Version 1.0.\n//                        See accompanying file LICENSE.txt or copy at\n//                            http://www.boost.org/LICENSE_1_0.txt\n// -------------------------------------------------------------------------------------------------\n\n#include <simd_bench.hpp>\n#include <boost/simd/function/simd/nearbyint.hpp>\n#include <boost/simd/pack.hpp>\n#include <cmath>\n\nnamespace nsb = ns::bench;\n\nDEFINE_SIMD_BENCH(simd_nearbyint, boost::simd::nearbyint);\n\nDEFINE_BENCH_MAIN()\n{\n  nsb::for_each<simd_nearbyint, NS_BENCH_IEEE_TYPES>(-10, 10);\n}\n", "meta": {"hexsha": "a426639d080349cef8e48cf549f3e98c87796ba0", "size": 786, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/function/simd/nearbyint.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": "bench/function/simd/nearbyint.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "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": "bench/function/simd/nearbyint.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "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": 35.7272727273, "max_line_length": 100, "alphanum_fraction": 0.465648855, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5152034999494918}}
{"text": "#include <gtest/gtest.h>\n\n#include <aslam/backend/ErrorTermMotionBST.hpp>\n// This test harness makes it easy to test error terms.\n#include <aslam/backend/test/ErrorTermTestHarness.hpp>\n#include <sm/kinematics/Transformation.hpp>\n#include <aslam/backend/TransformationBasic.hpp>\n\n#include <aslam/backend/EuclideanPoint.hpp>\n#include <sm/kinematics/RotationVector.hpp>\n#include <aslam/splines/OPTBSpline.hpp>\n#include <aslam/splines/implementation/OPTBSplineImpl.hpp>\n#include <bsplines/EuclideanBSpline.hpp>\n#include <aslam/backend/Scalar.hpp>\n\n#include <boost/shared_ptr.hpp>\n\ntemplate <typename TConf, int ISplineOrder, int IDim, bool BDimRequired> struct ConfCreator {\n  static inline TConf create(){\n    return TConf(typename TConf::ManifoldConf(IDim), ISplineOrder);\n  }\n};\n\ntemplate <typename TConf, int ISplineOrder, int IDim> struct ConfCreator<TConf, ISplineOrder, IDim, false> {\n  static inline TConf create(){\n    BOOST_STATIC_ASSERT_MSG(IDim == TConf::Dimension::VALUE, \"impossible dimension selected!\");\n    return TConf(typename TConf::ManifoldConf(), ISplineOrder);\n  }\n};\n\ntemplate <typename TConf, int ISplineOrder, int IDim> inline TConf createConf(){\n  return ConfCreator<TConf, ISplineOrder, IDim, TConf::Dimension::IS_DYNAMIC>::create();\n}\n\n\nTEST(AslamVChargeBackendTestSuite, testEuclidean)\n{\n  try {\n    using namespace aslam::backend;\n\n    double sigma_n = 0.5;\n\n    typedef aslam::splines::OPTBSpline<bsplines::EuclideanBSpline<4, 1>::CONF> PosSpline;\n    PosSpline robotPosSpline;\n    const int pointSize = robotPosSpline.getPointSize();\n\n    PosSpline::point_t initPoint(pointSize);\n    initPoint(0,0) = 10.0;\n\n    robotPosSpline.initConstantUniformSpline(0, 10, 10, initPoint);\n\n    // First, create a design variable for the wall position.\n    boost::shared_ptr<aslam::backend::Scalar> dv_w(new aslam::backend::Scalar(5.0));\n\n    // Create observation error\n    auto vecVelExpr = robotPosSpline.getExpressionFactoryAt<1>(5).getValueExpression(1);\n\n    aslam::backend::ErrorTermMotionBST eo(vecVelExpr, 1.0, sigma_n * sigma_n);\n\n    EXPECT_NEAR(1.0/(sigma_n * sigma_n), eo.evaluateError(), 1e-14);\n\n    // Create the test harness\n    aslam::backend::ErrorTermTestHarness<1> harness(&eo);\n\n    // Run the unit tests.\n    harness.testAll(1e-5);\n  }\n  catch(const std::exception & e) {\n    FAIL() << e.what();\n  }\n}\n", "meta": {"hexsha": "82471bb5ae710a005f28409945b6ede633bfbb8c", "size": 2340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_backend_bsplines_tutorial/test/TestErrorTestMotionBST.cpp", "max_stars_repo_name": "Curium-sg/aslam_splines", "max_stars_repo_head_hexsha": "d2c8c69d28d2f742b1d96a6a4e43a5c5112497af", "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": "aslam_backend_bsplines_tutorial/test/TestErrorTestMotionBST.cpp", "max_issues_repo_name": "Curium-sg/aslam_splines", "max_issues_repo_head_hexsha": "d2c8c69d28d2f742b1d96a6a4e43a5c5112497af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aslam_backend_bsplines_tutorial/test/TestErrorTestMotionBST.cpp", "max_forks_repo_name": "Curium-sg/aslam_splines", "max_forks_repo_head_hexsha": "d2c8c69d28d2f742b1d96a6a4e43a5c5112497af", "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.5, "max_line_length": 108, "alphanum_fraction": 0.7384615385, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5152034949183872}}
{"text": "/* boost random/laplace_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_LAPLACE_DISTRIBUTION_HPP\r\n#define BOOST_RANDOM_LAPLACE_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/exponential_distribution.hpp>\r\n\r\nnamespace boost {\r\nnamespace random {\r\n\r\n/**\r\n * The laplace distribution is a real-valued distribution with\r\n * two parameters, mean and beta.\r\n *\r\n * It has \\f$\\displaystyle p(x) = \\frac{e^-{\\frac{|x-\\mu|}{\\beta}}}{2\\beta}\\f$.\r\n */\r\ntemplate<class RealType = double>\r\nclass laplace_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 laplace_distribution distribution_type;\r\n\r\n        /**\r\n         * Constructs a @c param_type from the \"mean\" and \"beta\" parameters\r\n         * of the distribution.\r\n         */\r\n        explicit param_type(RealType mean_arg = RealType(0.0),\r\n                            RealType beta_arg = RealType(1.0))\r\n          : _mean(mean_arg), _beta(beta_arg)\r\n        {}\r\n\r\n        /** Returns the \"mean\" parameter of the distribtuion. */\r\n        RealType mean() const { return _mean; }\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._mean << ' ' << 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._mean >> 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._mean == rhs._mean && 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 _mean;\r\n        RealType _beta;\r\n    };\r\n\r\n    /**\r\n     * Constructs an @c laplace_distribution from its \"mean\" and \"beta\" parameters.\r\n     */\r\n    explicit laplace_distribution(RealType mean_arg = RealType(0.0),\r\n                               RealType beta_arg = RealType(1.0))\r\n      : _mean(mean_arg), _beta(beta_arg)\r\n    {}\r\n    /** Constructs an @c laplace_distribution from its parameters. */\r\n    explicit laplace_distribution(const param_type& parm)\r\n      : _mean(parm.mean()), _beta(parm.beta())\r\n    {}\r\n\r\n    /**\r\n     * Returns a random variate distributed according to the\r\n     * laplace distribution.\r\n     */\r\n    template<class URNG>\r\n    RealType operator()(URNG& urng) const\r\n    {\r\n        RealType exponential = exponential_distribution<RealType>()(urng);\r\n        if(uniform_01<RealType>()(urng) < 0.5)\r\n            exponential = -exponential;\r\n        return _mean + _beta * exponential;\r\n    }\r\n\r\n    /**\r\n     * Returns a random variate distributed accordint to the laplace\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 laplace_distribution(parm)(urng);\r\n    }\r\n\r\n    /** Returns the \"mean\" parameter of the distribution. */\r\n    RealType mean() const { return _mean; }\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(-std::numeric_limits<RealType>::infinity()); }\r\n    /** Returns the largest value that the distribution can produce. */\r\n    RealType max BOOST_PREVENT_MACRO_SUBSTITUTION () const\r\n    { return RealType(std::numeric_limits<RealType>::infinity()); }\r\n\r\n    /** Returns the parameters of the distribution. */\r\n    param_type param() const { return param_type(_mean, _beta); }\r\n    /** Sets the parameters of the distribution. */\r\n    void param(const param_type& parm)\r\n    {\r\n        _mean = parm.mean();\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 laplace_distribution to a @c std::ostream. */\r\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, laplace_distribution, wd)\r\n    {\r\n        os << wd.param();\r\n        return os;\r\n    }\r\n\r\n    /** Reads an @c laplace_distribution from a @c std::istream. */\r\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, laplace_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 laplace_distribution will\r\n     * return identical sequences of values given equal generators.\r\n     */\r\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(laplace_distribution, lhs, rhs)\r\n    { return lhs._mean == rhs._mean && lhs._beta == rhs._beta; }\r\n    \r\n    /**\r\n     * Returns true if the two instances of @c laplace_distribution will\r\n     * return different sequences of values given equal generators.\r\n     */\r\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(laplace_distribution)\r\n\r\nprivate:\r\n    RealType _mean;\r\n    RealType _beta;\r\n};\r\n\r\n} // namespace random\r\n} // namespace boost\r\n\r\n#endif // BOOST_RANDOM_LAPLACE_DISTRIBUTION_HPP\r\n", "meta": {"hexsha": "b95399873516c409f0b361373bfd4d0c12b09a10", "size": 5918, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/random/laplace_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/laplace_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/laplace_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": 33.625, "max_line_length": 84, "alphanum_fraction": 0.6336600203, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5152034949183872}}
{"text": "/***\n * @file arma_extend.hpp\n * @author Ryan Curtin\n *\n * Include Armadillo extensions which currently are not part of the main\n * Armadillo codebase.\n *\n * This will allow the use of the ccov() function (which performs the same\n * function as cov(trans(X)) but without the cost of computing trans(X)).  This\n * also gives sparse matrix support, if it is necessary.\n */\n#ifndef __MY_MLPACK_CORE_ARMA_EXTEND_ARMA_EXTEND_HPP\n#define __MY_MLPACK_CORE_ARMA_EXTEND_ARMA_EXTEND_HPP\n\n// Add batch constructor for sparse matrix (if version <= 3.810.0).\n#define ARMA_EXTRA_SPMAT_PROTO mips/my_mlpack/core/arma_extend/SpMat_extra_bones.hpp\n#define ARMA_EXTRA_SPMAT_MEAT  mips/my_mlpack/core/arma_extend/SpMat_extra_meat.hpp\n\n#include <armadillo>\n\nnamespace arma {\n  // u64/s64\n  #include \"typedef.hpp\"\n  #include \"traits.hpp\"\n  #include \"promote_type.hpp\"\n  #include \"restrictors.hpp\"\n  #include \"hdf5_misc.hpp\"\n\n  // ccov()\n  #include \"op_ccov_proto.hpp\"\n  #include \"op_ccov_meat.hpp\"\n  #include \"glue_ccov_proto.hpp\"\n  #include \"glue_ccov_meat.hpp\"\n  #include \"fn_ccov.hpp\"\n\n  // inplace_reshape()\n  #include \"fn_inplace_reshape.hpp\"\n};\n\n#endif\n", "meta": {"hexsha": "3c9b1976b9f04e0dbf195bd65a8e9afe72d09bc6", "size": 1138, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mips/my_mlpack/core/arma_extend/arma_extend.hpp", "max_stars_repo_name": "uma-pi1/LEMP", "max_stars_repo_head_hexsha": "e24ce821692aba8403ca8733382f53641f7f96d5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T07:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-16T17:34:42.000Z", "max_issues_repo_path": "mips/my_mlpack/core/arma_extend/arma_extend.hpp", "max_issues_repo_name": "d3v3l0/LEMP-benchmarking", "max_issues_repo_head_hexsha": "0279528b427aa4fae59e4d3598b1f098fcb4cf4b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-16T03:30:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T03:30:55.000Z", "max_forks_repo_path": "mips/my_mlpack/core/arma_extend/arma_extend.hpp", "max_forks_repo_name": "d3v3l0/LEMP-benchmarking", "max_forks_repo_head_hexsha": "0279528b427aa4fae59e4d3598b1f098fcb4cf4b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-16T08:21:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-04T06:37:41.000Z", "avg_line_length": 27.756097561, "max_line_length": 84, "alphanum_fraction": 0.7530755712, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5152034949183872}}
{"text": "// \n// Implements iLQR (on a traditional chain) for nonlinear dynamics and cost.\n//\n// Arun Venkatraman (arunvenk@cs.cmu.edu)\n// December 2016\n//\n\n#pragma once\n\n\n#include <templated/taylor_expansion.hh>\n#include <utils/debug_utils.hh>\n\n#include <Eigen/Dense>\n\n#include <functional>\n#include <vector>\n\nnamespace ilqr\n{\n\n// Defined in templated/taylor_expansion.hh\n//template<int _rows, int _cols>\n//using Matrix = Eigen::Matrix<double, _rows, _cols>;\n//\n//template<int _rows>\n//using Vector = Eigen::Matrix<double, _rows, 1>;\n\n\ntemplate<int xdim, int udim>\nclass iLQRSolver\n{\n    static_assert(xdim > 0, \"State dimension should be greater than 0\");\n    static_assert(udim > 0, \"Control dimension should be greater than 0\");\npublic:\n    using Dynamics = std::function<Vector<xdim>(const Vector<xdim> &x, const Vector<udim> &u)>;\n    using Cost = std::function<double(const Vector<xdim> &x, const Vector<udim> &u, const int t)>;\n    using FinalCost = std::function<double(const Vector<xdim> &x)>;\n\n    iLQRSolver(const Dynamics &dynamics,\n         const FinalCost &final_cost,\n         const Cost &cost\n         )\n    {\n        this->dynamics_ = dynamics;\n        this->cost_ = cost;\n        this->final_cost_ = final_cost;\n    }\n\n    // Computes the control at timestep t at xt.\n    // :param alpha - Backtracking line search parameter. Setting to 1 gives regular forward pass.\n    inline Vector<udim> compute_control_stepsize(const Vector<xdim> &xt, \n            const int t, const double alpha) const;\n\n    // Computes the locally-optimal iLQR solution.\n    // :param x_init - Initial state from which to start the system from.\n    // :param u_nominal - Initial control used for the whole sequence during \n    //      the first forward pass.\n    // :param mu - Levenberg-Marquardt parameter for damping the least-squares. \n    //      Setting it to 0 gets the default behavior. The damping makes the \n    //      state-space steps smaller over iterations. \n    // :param start_alpha - The initial step size to use when solving.\n    // :param cost_conv_ratio - When the cost over iterations changes by less than \n    //      this ratio, then the optimization is stopped.\n    // :param warm_start - Warm start the solver using the previous solution stored\n    //      in the object from the last call to solve. \n    // :param t_offset - The warm start time offset. The input argument T to this call\n    //      of solve should be T_{last_call} - t_offset. \n    //      For example, if 1, then the first timestep of the previous solution \n    //      is removed. \n    inline void solve(const int T, const Vector<xdim> &x_init, \n            const Vector<udim> u_nominal, const double mu, \n            const int max_iters = 1000, bool verbose = false, \n            const double cost_convg_ratio = 1e-4, const double start_alpha = 1.0,\n            const bool warm_start = false, const int t_offset = 0\n            );\n\n    // :param alpha - Backtracking line search parameter. Setting to 1 gives regular forward pass.\n    inline double forward_pass(const Vector<xdim> x_init, \n            std::vector<Vector<xdim>> &states, std::vector<Vector<udim>> &controls, \n            const double alpha ) const;\n\n    // Returns how many timesteps we have computed control policies for.\n    inline int timesteps() const;\n\nprivate:\n    Dynamics dynamics_; \n    Cost cost_; \n    FinalCost final_cost_; \n\n    // Feedback control gains.\n    std::vector<Matrix<udim, xdim>> Ks_;\n    std::vector<Vector<udim>> ks_;\n\n    // Linearization points.\n    std::vector<Vector<xdim>> xhat_;\n    std::vector<Vector<udim>> uhat_;\n\n    // Performs one timestep of the bellman backup.\n    // :param t - passed to the cost runction\n    // :param mu - Levenberg-Marquardt parameter\n    void bellman_backup(const int t, const double mu, \n        const Matrix<xdim,xdim> &Vt1, const Matrix<1,xdim> &Gt1, \n        Matrix<xdim,xdim> &Vt, Matrix<1,xdim> &Gt, \n        Matrix<udim,xdim> &Kt, Vector<udim> &kt);\n\n};\n\n} // namespace lqr\n\n#include <templated/iLQR_impl.hh>\n\n", "meta": {"hexsha": "9d253ddae88d415e58a11eb0f5b84c469f2e1668", "size": 4026, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/templated/iLQR.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/templated/iLQR.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/templated/iLQR.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": 35.6283185841, "max_line_length": 98, "alphanum_fraction": 0.6693989071, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.51513051458386}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"algorithms/math/roman_to_int.hpp\"\n\nBOOST_AUTO_TEST_SUITE(ConversionOfRomanToIntegerNumber)\n\nBOOST_AUTO_TEST_CASE(main_numbers)\n{\n    BOOST_CHECK(1 == Algo::Math::RomanToInt::Convert(\"I\"));\n    BOOST_CHECK(5 == Algo::Math::RomanToInt::Convert(\"V\"));\n    BOOST_CHECK(10 == Algo::Math::RomanToInt::Convert(\"X\"));\n    BOOST_CHECK(50 == Algo::Math::RomanToInt::Convert(\"L\"));\n    BOOST_CHECK(100 == Algo::Math::RomanToInt::Convert(\"C\"));\n    BOOST_CHECK(500 == Algo::Math::RomanToInt::Convert(\"D\"));\n    BOOST_CHECK(1000 == Algo::Math::RomanToInt::Convert(\"M\"));\n}\n\nBOOST_AUTO_TEST_CASE(main_susbstract_numbers)\n{\n    BOOST_CHECK(4 == Algo::Math::RomanToInt::Convert(\"IV\"));\n    BOOST_CHECK(9 == Algo::Math::RomanToInt::Convert(\"IX\"));\n    BOOST_CHECK(40 == Algo::Math::RomanToInt::Convert(\"XL\"));\n    BOOST_CHECK(90 == Algo::Math::RomanToInt::Convert(\"XC\"));\n    BOOST_CHECK(400 == Algo::Math::RomanToInt::Convert(\"CD\"));\n    BOOST_CHECK(900 == Algo::Math::RomanToInt::Convert(\"CM\"));\n}\n\nBOOST_AUTO_TEST_CASE(main_valid_numbers)\n{\n    BOOST_CHECK(2 == Algo::Math::RomanToInt::Convert(\"II\"));\n    BOOST_CHECK(3 == Algo::Math::RomanToInt::Convert(\"III\"));\n    BOOST_CHECK(8 == Algo::Math::RomanToInt::Convert(\"VIII\"));\n    BOOST_CHECK(14 == Algo::Math::RomanToInt::Convert(\"XIV\"));\n    BOOST_CHECK(39 == Algo::Math::RomanToInt::Convert(\"XXXIX\"));\n    BOOST_CHECK(44 == Algo::Math::RomanToInt::Convert(\"XLIV\"));\n    BOOST_CHECK(58 == Algo::Math::RomanToInt::Convert(\"LVIII\"));\n    BOOST_CHECK(82 == Algo::Math::RomanToInt::Convert(\"LXXXII\"));\n    BOOST_CHECK(3994 == Algo::Math::RomanToInt::Convert(\"MMMCMXCIV\"));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "01a275a2edaa8f829147f5fac65786eacdeb19d0", "size": 1684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/math/test_roman_to_int.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_roman_to_int.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_roman_to_int.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": 41.0731707317, "max_line_length": 70, "alphanum_fraction": 0.6840855107, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.515130509237378}}
{"text": "/**\n * Common header used throughout project\n */\n\n#pragma once\n\n#include <Eigen/Eigen>\n\nnamespace solo {\n/**\n * @brief Vector2d shortcut for the eigen vector of size 1.\n */\ntypedef Eigen::Matrix<double, 1, 1> Vector1d;\n\n/**\n * @brief Vector2d shortcut for the eigen vector of size 2.\n */\ntypedef Eigen::Matrix<double, 2, 1> Vector2d;\n\n/**\n * @brief Vector2d shortcut for the eigen vector of size 6.\n */\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\n/**\n * @brief Vector8d shortcut for the eigen vector of size 8.\n */\ntypedef Eigen::Matrix<double, 8, 1> Vector8d;\n\n/**\n * @brief Vector8d shortcut for the eigen vector of size 12.\n */\ntypedef Eigen::Matrix<double, 12, 1> Vector12d;\n\n}  // namespace solo", "meta": {"hexsha": "b97178fea821c69c06b536eba17eb4a702dd3d0a", "size": 703, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/robot_script/common.hpp", "max_stars_repo_name": "yunifuchioka/robot_script", "max_stars_repo_head_hexsha": "ce9e27b4b00debfabbca136b6ab21e9b043416e8", "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/robot_script/common.hpp", "max_issues_repo_name": "yunifuchioka/robot_script", "max_issues_repo_head_hexsha": "ce9e27b4b00debfabbca136b6ab21e9b043416e8", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/robot_script/common.hpp", "max_forks_repo_name": "yunifuchioka/robot_script", "max_forks_repo_head_hexsha": "ce9e27b4b00debfabbca136b6ab21e9b043416e8", "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.0857142857, "max_line_length": 60, "alphanum_fraction": 0.6884779516, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5151304999020304}}
{"text": "#define _USE_MATH_DEFINES\n#include <cmath>\n#include <opencv2/opencv.hpp>\n#include <Eigen/Dense>\n#include <vector>\n#include <cmath>\n#include <stack>\n#include <iomanip>\n#include \"prUtil.h\"\n#include \"prCommon.h\"\n\nnamespace pr {\n\ncv::Mat getHomoMatFromInExNm(const cv::Mat &in_mat,\n                             const cv::Mat &ex_mat,\n                             const cv::Mat &nm_mat) {\n    cv::Mat ex_mat_124 = (cv::Mat_<float>(3, 3) << ex_mat.at<float>(0, 0),\n                                                   ex_mat.at<float>(0, 1),\n                                                   ex_mat.at<float>(0, 3),\n                                                   ex_mat.at<float>(1, 0),\n                                                   ex_mat.at<float>(1, 1),\n                                                   ex_mat.at<float>(1, 3),\n                                                   ex_mat.at<float>(2, 0),\n                                                   ex_mat.at<float>(2, 1),\n                                                   ex_mat.at<float>(2, 3));\n    cv::Mat H = in_mat * ex_mat_124 * nm_mat;\n    H /= H.at<float>(2, 2);\n    return H.clone();\n}\n\ncv::Mat getHomoMatFromInEx(const cv::Mat &in_mat,\n                           const cv::Mat &ex_mat) {\n    cv::Mat ex_mat_124 = (cv::Mat_<float>(3, 3) << ex_mat.at<float>(0, 0),\n                                                   ex_mat.at<float>(0, 1),\n                                                   ex_mat.at<float>(0, 3),\n                                                   ex_mat.at<float>(1, 0),\n                                                   ex_mat.at<float>(1, 1),\n                                                   ex_mat.at<float>(1, 3),\n                                                   ex_mat.at<float>(2, 0),\n                                                   ex_mat.at<float>(2, 1),\n                                                   ex_mat.at<float>(2, 3));\n    cv::Mat H = in_mat * ex_mat_124;\n    H /= H.at<float>(2, 2);\n    return H.clone();\n}\n\n\ncv::Mat getAxisAngleFromRotationMatirx(const cv::Mat &R)\n{\n    float a = acosf((trace(R).val[0] - 1) / 2);\n    cv::Mat r;\n    if (a < EPS)\n    {\n        r = (cv::Mat_<float>(3, 1) << R.at<float>(2, 1) - R.at<float>(1, 2),\n                                      R.at<float>(0, 2) - R.at<float>(2, 0),\n                                      R.at<float>(1, 0) - R.at<float>(0, 1));\n        r *= 0.5;\n    }\n    else if (a >(M_PI - EPS))\n    {\n        cv::Mat S = 0.5 * (R - (cv::Mat_<float>(3, 3) << 1, 0, 0, 0, 1, 0, 0, 0, 1));\n        float b = sqrt(S.at<float>(0, 0) + 1);\n        float c = sqrt(S.at<float>(1, 1) + 1);\n        float d = sqrt(S.at<float>(2, 2) + 1);\n        if (b > EPS)\n        {\n            c = S.at<float>(1, 0) / b;\n            d = S.at<float>(2, 0) / b;\n        }\n        else if (c > EPS)\n        {\n            b = S.at<float>(0, 1) / c;\n            d = S.at<float>(2, 1) / c;\n        }\n        else\n        {\n            b = S.at<float>(0, 2) / d;\n            c = S.at<float>(1, 2) / d;\n        }\n        r = (cv::Mat_<float>(3, 1) << b, c, d);\n    }\n    else\n    {\n        r = (cv::Mat_<float>(3, 1) << R.at<float>(2, 1) - R.at<float>(1, 2),\n                                      R.at<float>(0, 2) - R.at<float>(2, 0),\n                                      R.at<float>(1, 0) - R.at<float>(0, 1));\n        r *= (a / 2 / sinf(a));\n    }\n    return r.clone();\n}\n\ncv::Mat getRotationMatrixFromAxisAngle(const cv::Mat &r)\n{\n    float rx, ry, rz;\n    rx = r.at<float>(0);\n    ry = r.at<float>(1);\n    rz = r.at<float>(2);\n    cv::Mat I = cv::Mat::eye(3, 3, CV_32F);\n    cv::Mat W = getCrossProductMatrix(r);\n    cv::Mat W2 = W * W;\n    const float a = norm(r);\n    if (a < EPS)\n        return I + W + 0.5 * W2;\n    else\n        return I + W * sin(a) / a + W2 * (1 - cos(a)) / (a * a);\n}\n\ncv::Mat getAaParametersFromExtrinsicMatirx(const cv::Mat &ex_mat)\n{\n    cv::Mat p(6, 1, CV_32F);\n    getAxisAngleFromRotationMatirx(ex_mat(cv::Rect(0, 0, 3, 3))).copyTo(p(cv::Rect(0, 0, 1, 3)));\n    ex_mat(cv::Rect(3, 0, 1, 3)).copyTo(p(cv::Rect(0, 3, 1, 3)));\n    return p.clone();\n}\n\ncv::Mat getExtrinsicMatrixFromAaParameters(const cv::Mat &p)\n{\n    cv::Mat ex_mat = (cv::Mat_<float>(4, 4) << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);\n    getRotationMatrixFromAxisAngle(p(cv::Rect(0, 0, 1, 3))).copyTo(ex_mat(cv::Rect(0, 0, 3, 3)));\n    p(cv::Rect_<float>(0, 3, 1, 3)).copyTo(ex_mat(cv::Rect_<float>(3, 0, 1, 3)));\n    return ex_mat.clone();\n}\n\ncv::Mat getCrossProductMatrix(const cv::Mat &r)\n{\n    float rx = r.at<float>(0);\n    float ry = r.at<float>(1);\n    float rz = r.at<float>(2);\n    cv::Mat W = (cv::Mat_<float>(3, 3) << 0, -rz, ry, rz, 0, -rx, -ry, rx, 0);\n    return W.clone();\n}\n\nR12t getR12t(const cv::Mat &ex_mat)\n{\n    R12t R12_t;\n    R12_t.r11 = ex_mat.at<float>(0, 0);\n    R12_t.r12 = ex_mat.at<float>(0, 1);\n    R12_t.t1  = ex_mat.at<float>(0, 3);\n    R12_t.r21 = ex_mat.at<float>(1, 0);\n    R12_t.r22 = ex_mat.at<float>(1, 1);\n    R12_t.t2  = ex_mat.at<float>(1, 3);\n    R12_t.r31 = ex_mat.at<float>(2, 0);\n    R12_t.r32 = ex_mat.at<float>(2, 1);\n    R12_t.t3  = ex_mat.at<float>(2, 3);\n    return R12_t;\n}\n\nJacobRr getJacobRr(const cv::Mat &r)\n{\n    JacobRr J_Rr;\n\n    const float &rx = r.at<float>(0);\n    const float &ry = r.at<float>(1);\n    const float &rz = r.at<float>(2);\n\n    float a = norm(r);\n    if (a < EPS) {\n        J_Rr.j11 = 0;\n        J_Rr.j12 = -ry;\n        J_Rr.j13 = -rz;\n        J_Rr.j21 = ry / 2;\n        J_Rr.j22 = rx / 2;\n        J_Rr.j23 = -1;\n        J_Rr.j31 = ry / 2;\n        J_Rr.j32 = rx / 2;\n        J_Rr.j33 = 1;\n        J_Rr.j41 = -rx;\n        J_Rr.j42 = 0;\n        J_Rr.j43 = -rz;\n        J_Rr.j51 = rz / 2;\n        J_Rr.j52 = -1;\n        J_Rr.j53 = rx / 2;\n        J_Rr.j61 = 1;\n        J_Rr.j62 = rz / 2;\n        J_Rr.j63 = ry / 2;\n    }\n    else {\n        cv::Mat W = getCrossProductMatrix(r);\n        cv::Mat R = getRotationMatrixFromAxisAngle(r);\n        cv::Mat Id_R = cv::Mat::eye(3, 3, CV_32F) - R;\n        cv::Mat M = W * Id_R;\n        cv::Mat R_a2 = R / (a*a);\n        cv::Mat dR_dr0 = (r.at<float>(0)*W + getCrossProductMatrix(M.col(0)))*R_a2;\n        cv::Mat dR_dr1 = (r.at<float>(1)*W + getCrossProductMatrix(M.col(1)))*R_a2;\n        cv::Mat dR_dr2 = (r.at<float>(2)*W + getCrossProductMatrix(M.col(2)))*R_a2;\n        J_Rr.j11 = dR_dr0.at<float>(0, 0);\n        J_Rr.j12 = dR_dr1.at<float>(0, 0);\n        J_Rr.j13 = dR_dr2.at<float>(0, 0);\n        J_Rr.j21 = dR_dr0.at<float>(0, 1);\n        J_Rr.j22 = dR_dr1.at<float>(0, 1);\n        J_Rr.j23 = dR_dr2.at<float>(0, 1);\n        J_Rr.j31 = dR_dr0.at<float>(1, 0);\n        J_Rr.j32 = dR_dr1.at<float>(1, 0);\n        J_Rr.j33 = dR_dr2.at<float>(1, 0);\n        J_Rr.j41 = dR_dr0.at<float>(1, 1);\n        J_Rr.j42 = dR_dr1.at<float>(1, 1);\n        J_Rr.j43 = dR_dr2.at<float>(1, 1);\n        J_Rr.j51 = dR_dr0.at<float>(2, 0);\n        J_Rr.j52 = dR_dr1.at<float>(2, 0);\n        J_Rr.j53 = dR_dr2.at<float>(2, 0);\n        J_Rr.j61 = dR_dr0.at<float>(2, 1);\n        J_Rr.j62 = dR_dr1.at<float>(2, 1);\n        J_Rr.j63 = dR_dr2.at<float>(2, 1);\n    }\n    return J_Rr;\n}\n\nfloat polygonArea(const cv::Mat &corners) {\n    float area = 0.f;\n    int num = corners.cols;\n    int j = num - 1;\n    for (int i = 0; i < num; ++i) {\n        area += (corners.at<float>(0, j) + corners.at<float>(0, i))\n               *(corners.at<float>(1, j) - corners.at<float>(1, i));\n        j = i;\n    }\n    return std::abs(area) * 0.5f;\n}\n\nvoid calRegion(const cv::Mat &boundary,\n               const cv::Mat &H,\n               int tw,\n               int th,\n               int iw,\n               int ih,\n               float scale,\n               cv::Mat *corners,\n               Region *region) {\n    (*corners) = H * boundary;\n    auto w = (cv::Mat(1.f / (*corners)(cv::Rect(0, 2, 4, 1)))).clone();\n    cv::multiply((*corners)(cv::Rect(0, 0, 4, 1)), w, (*corners)(cv::Rect(0, 0, 4, 1)));\n    cv::multiply((*corners)(cv::Rect(0, 1, 4, 1)), w, (*corners)(cv::Rect(0, 1, 4, 1)));\n\n    double x_min, x_max, y_min, y_max, x_center, y_center, x_length, y_length;\n    cv::minMaxIdx((*corners)(cv::Rect(0, 0, 4, 1)), &x_min, &x_max);\n    cv::minMaxIdx((*corners)(cv::Rect(0, 1, 4, 1)), &y_min, &y_max);\n    x_center = (x_max + x_min) / 2.0;\n    y_center = (y_max + y_min) / 2.0;\n    x_length = x_max - x_center;\n    y_length = y_max - y_center;\n    x_max = x_center + x_length * scale;\n    y_max = y_center + y_length * scale;\n    x_min = x_center - x_length * scale;\n    y_min = y_center - y_length * scale;\n    region->x_max = int(std::min(ceil(x_max), iw - 1.0));\n    region->y_max = int(std::min(ceil(y_max), ih - 1.0));\n    region->x_min = int(std::max(floor(x_min), 0.0));\n    region->y_min = int(std::max(floor(y_min), 0.0));\n}\n\nvoid calPoseDiff(const cv::Mat &p1,\n                 const cv::Mat &p2,\n                 float *diff_r,\n                 float *diff_t)\n{\n    auto R1 = getRotationMatrixFromAxisAngle(p1(cv::Rect(0, 0, 1, 3))).clone();\n    auto t1 = p1(cv::Rect(0, 3, 1, 3)).clone();\n    auto R2 = getRotationMatrixFromAxisAngle(p2(cv::Rect(0, 0, 1, 3))).clone();\n    auto t2 = p2(cv::Rect(0, 3, 1, 3)).clone();\n    cv::Mat R2_transpose;\n    transpose(R2, R2_transpose);\n    *diff_r = acosf((trace(R2_transpose*R1).val[0] - 1) / 2) * 180.f / M_PI;\n    *diff_t = norm(t1 - t2) / norm(t1) * 100;\n}\n\nvoid calDeltaP(float *JtJ_ptr,\n               float *JtE_ptr,\n               cv::Mat *delta_p,\n               cv::Mat *JtE) {\n    Eigen::Matrix<float, 6, 6> H = Eigen::Map<Eigen::Matrix<float, 6, 6>>(JtJ_ptr);\n    Eigen::Matrix<float, 6, 1> delta_p_eigen = H.inverse()*Eigen::Map<Eigen::Matrix<float, 6, 1>>(JtE_ptr);\n    for (int i = 0; i < 6; ++i) {\n        (*delta_p).at<float>(i) = delta_p_eigen[i];\n        (*JtE).at<float>(i) = JtE_ptr[i];\n    }\n}\n\n}  // namespace pr\n", "meta": {"hexsha": "faae229e21fd7cd3a8113a168804396246626bb2", "size": 9809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "function/DPE_CUDA/prUtil.cpp", "max_stars_repo_name": "pcwu0329/DPE", "max_stars_repo_head_hexsha": "a1cc6adb2ff8be02f24e57470639a6f77d25edfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-03-27T10:33:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-06T05:43:53.000Z", "max_issues_repo_path": "function/DPE_CUDA/prUtil.cpp", "max_issues_repo_name": "pcwu0329/DPE", "max_issues_repo_head_hexsha": "a1cc6adb2ff8be02f24e57470639a6f77d25edfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "function/DPE_CUDA/prUtil.cpp", "max_forks_repo_name": "pcwu0329/DPE", "max_forks_repo_head_hexsha": "a1cc6adb2ff8be02f24e57470639a6f77d25edfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-03-28T15:02:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-26T01:36:33.000Z", "avg_line_length": 35.1577060932, "max_line_length": 107, "alphanum_fraction": 0.4649811398, "num_tokens": 3443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5149553702021209}}
{"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/bessel.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n\n//==================================================================================================\n//== Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of cyl_bessel_kn\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n using i_t = eve::as_integer_t<v_t>;\n using I_t = eve::wide<i_t, eve::cardinal_t<T>>;\n  TTS_EXPR_IS( eve::cyl_bessel_kn(T(), T())  ,  T);\n  TTS_EXPR_IS( eve::cyl_bessel_kn(v_t(),v_t()), v_t);\n  TTS_EXPR_IS( eve::cyl_bessel_kn(i_t(),T()),   T);\n  TTS_EXPR_IS( eve::cyl_bessel_kn(I_t(),T()),   T);\n  TTS_EXPR_IS( eve::cyl_bessel_kn(i_t(),v_t()), v_t);\n  TTS_EXPR_IS( eve::cyl_bessel_kn(I_t(),v_t()), T);\n};\n\n//==================================================================================================\n//== integral orders\n//==================================================================================================\nEVE_TEST( \"Check behavior of cyl_bessel_kn on wide with integral order\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::ramp(0), eve::test::randoms(0.0, 10.0))\n        )\n  <typename T>(T n , T a0 )\n{\n  using v_t = eve::element_type_t<T>;\n\n  auto eve__cyl_bessel_kn =  [](auto n, auto x) { return eve::cyl_bessel_kn(n, x); };\n  auto std__cyl_bessel_kn =  [](auto n, auto x)->v_t { return boost::math::cyl_bessel_k(n, x); };\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(0, eve::minf(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(2, eve::inf(eve::as<v_t>())), eve::inf(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(3, eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n  }\n  //scalar large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(3, v_t(1500)),  eve::zero(eve::as<v_t>()), 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(2, v_t(50)), std__cyl_bessel_kn(2, v_t(50)), 5.0);\n  //scalar forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(0, v_t(10)), std__cyl_bessel_kn(0, v_t(10))  , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(1, v_t(5)),  std__cyl_bessel_kn(1, v_t(5))   , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(2, v_t(10)), std__cyl_bessel_kn(2, v_t(10))  , 35.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(3, v_t(5)),  std__cyl_bessel_kn(3, v_t(5))   , 35.0);\n  //scalar small\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(0, v_t(0.1)), std__cyl_bessel_kn(0, v_t(0.1))  , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(1, v_t(0.2)),  std__cyl_bessel_kn(1, v_t(0.2))   , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(2, v_t(0.1)), std__cyl_bessel_kn(2, v_t(0.1))  , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(3, v_t(0.2)),  std__cyl_bessel_kn(3, v_t(0.2))   , 5.0);\n  //scalar medium\n\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(10, v_t(8)), std__cyl_bessel_kn(10, v_t(8))  , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(20, v_t(8)), std__cyl_bessel_kn(20, v_t(8))   , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(2 , v_t(1.9010021686554)), std__cyl_bessel_kn(2, v_t(1.9010021686554))   , 15.0);\n\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(2,  v_t(244.708321520116)), std__cyl_bessel_kn(2, v_t(244.708321520116)) , 15.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(3,  v_t(517.048069608611)), std__cyl_bessel_kn(3,  v_t(517.048069608611)), 15.0);\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(0, eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(2, eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(3, eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n  //simd large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(3, T(1500)),  eve::zero(eve::as<T>()),  5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(2, T(50)),   T(std__cyl_bessel_kn(2, v_t(50))),   5.0);\n  //simd forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(2, T(10)),    T(std__cyl_bessel_kn(2, v_t(10)))   , 35.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(3, T(5)),     T(std__cyl_bessel_kn(3, v_t(5)))    , 35.0);\n  //simd small\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(0, T(0.1)),   T(std__cyl_bessel_kn(0, v_t(0.1)))  , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(1, T(0.2)),   T(std__cyl_bessel_kn(1, v_t(0.2)))  , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(2, T(0.1)),   T(std__cyl_bessel_kn(2, v_t(0.1)))  , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(3, T(0.2)),   T(std__cyl_bessel_kn(3, v_t(0.2)))  , 5.0);\n  //simd medium\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(10, T(8)),   T(std__cyl_bessel_kn(10, v_t(8)))   , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(20, T(8)),   T(std__cyl_bessel_kn(20, v_t(8)))   , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(2 , T(1.9010021686554)), T(std__cyl_bessel_kn(2, v_t(1.9010021686554)))   , 15.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(2,  T(244.708321520116)),T(std__cyl_bessel_kn(2, v_t(244.708321520116))) , 15.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(3,  T(517.048069608611)),T(std__cyl_bessel_kn(3,  v_t(517.048069608611))), 15.0);\n\n\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(0), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(2), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n  // large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(3), T(1500)),   eve::zero(eve::as<T>()),  5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(2), T(50)),   T(std__cyl_bessel_kn(2, v_t(50))),   5.0);\n  // forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(2), T(10)),    T(std__cyl_bessel_kn(2, v_t(10)))   , 35.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(3), T(5)),     T(std__cyl_bessel_kn(3, v_t(5)))    , 35.0);\n  // serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(2), T(0.1)),   T(std__cyl_bessel_kn(2, v_t(0.1)))  , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(3), T(0.2)),   T(std__cyl_bessel_kn(3, v_t(0.2)))  , 5.0);\n  // besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(10), T(8)),   T(std__cyl_bessel_kn(10, v_t(8)))   , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(20), T(8)),   T(std__cyl_bessel_kn(20, v_t(8)))   , 5.0);\n\n  using i_t = eve::as_integer_t<v_t>;\n  using I_t = eve::wide<i_t, eve::cardinal_t<T>>;\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(I_t(0), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(I_t(2), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(I_t(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n  // large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(I_t(3), T(1500)),  eve::zero(eve::as<T>()),  5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(I_t(2), T(50)),   T(std__cyl_bessel_kn(2, v_t(50))),   5.0);\n  // forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(I_t(2), T(10)),    T(std__cyl_bessel_kn(2, v_t(10)))   , 35.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(I_t(3), T(5)),     T(std__cyl_bessel_kn(3, v_t(5)))    , 35.0);\n  // serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(I_t(2), T(0.1)),   T(std__cyl_bessel_kn(2, v_t(0.1)))  , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(I_t(3), T(0.2)),   T(std__cyl_bessel_kn(3, v_t(0.2)))  , 5.0);\n  // besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(I_t(10), T(8)),   T(std__cyl_bessel_kn(10, v_t(8)))   , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(I_t(20), T(8)),   T(std__cyl_bessel_kn(20, v_t(8)))   , 5.0);\n\n  TTS_RELATIVE_EQUAL(eve__cyl_bessel_kn(n, a0),   map(std__cyl_bessel_kn, n, a0)   , 1.0e-4);\n  TTS_RELATIVE_EQUAL(eve__cyl_bessel_kn(-n, a0),   map(std__cyl_bessel_kn, -n, a0)   , 1.0e-4);\n\n\n};\n\n//==================================================================================================\n//== non integral orders\n//==================================================================================================\nEVE_TEST( \"Check behavior of cyl_bessel_kn on wide with non integral order\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(0.0, 10.0)\n        , eve::test::randoms(0.0, 200.0))\n        )\n  <typename T>(T n, T a0 )\n{\n   using v_t = eve::element_type_t<T>;\n   auto eve__cyl_bessel_kn =  [](auto n, auto x) { return eve::cyl_bessel_kn(n, x); };\n   auto std__cyl_bessel_kn =  [](auto n, auto x)->v_t { return boost::math::cyl_bessel_k(n, x); };\n\n   if constexpr( eve::platform::supports_invalids )\n   {\n     TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n     TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(2.5), eve::inf(eve::as<T>())), eve::zero(eve::as<T>()), 0);\n     TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n   }\n   // large x\n   TTS_ULP_EQUAL(eve__cyl_bessel_kn(v_t(3.5), v_t(1500)),  eve::zero(eve::as<v_t>()),  10.0);\n   TTS_ULP_EQUAL(eve__cyl_bessel_kn(v_t(2.5), v_t(50)),   std__cyl_bessel_kn(v_t(2.5), v_t(50)),   10.0);\n   // forward\n   TTS_ULP_EQUAL(eve__cyl_bessel_kn(v_t(2.5), v_t(10)),    std__cyl_bessel_kn(v_t(2.5), v_t(10))   , 10.0);\n   TTS_ULP_EQUAL(eve__cyl_bessel_kn(v_t(3.5), v_t(5)),     std__cyl_bessel_kn(v_t(3.5), v_t(5))    , 10.0);\n   // serie\n   TTS_ULP_EQUAL(eve__cyl_bessel_kn(v_t(2.5), v_t(0.1)),   std__cyl_bessel_kn(v_t(2.5), v_t(0.1))  , 10.0);\n   TTS_ULP_EQUAL(eve__cyl_bessel_kn(v_t(3.5), v_t(0.2)),   std__cyl_bessel_kn(v_t(3.5), v_t(0.2))  , 10.0);\n   // besseljy\n   TTS_ULP_EQUAL(eve__cyl_bessel_kn(v_t(10.5), v_t(8)),    std__cyl_bessel_kn(v_t(10.5), v_t(8))   , 10.0);\n   TTS_ULP_EQUAL(eve__cyl_bessel_kn(v_t(10.5), v_t(8)),    std__cyl_bessel_kn(v_t(10.5), v_t(8))   , 10.0);\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(2.5), eve::inf(eve::as<T>())), eve::zero(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n  // large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(3.5), T(1500)),  eve::zero(eve::as<T>()),  10.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(2.5), T(50)),   T(std__cyl_bessel_kn(v_t(2.5), v_t(50))),   10.0);\n  // forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(2.5), T(10)),    T(std__cyl_bessel_kn(v_t(2.5), v_t(10)))   , 310.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(3.5), T(5)),     T(std__cyl_bessel_kn(v_t(3.5), v_t(5)))    , 310.0);\n  // serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(2.5), T(0.1)),   T(std__cyl_bessel_kn(v_t(2.5), v_t(0.1)))  , 10.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(3.5), T(0.2)),   T(std__cyl_bessel_kn(v_t(3.5), v_t(0.2)))  , 10.0);\n  // besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(10.5), T(8)),   T(std__cyl_bessel_kn(v_t(10.5), v_t(8)))   , 10.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_kn(T(10.5), T(8)),   T(std__cyl_bessel_kn(v_t(10.5), v_t(8)))   , 10.0);\n\n  TTS_RELATIVE_EQUAL(eve__cyl_bessel_kn(n, a0),   map(std__cyl_bessel_kn, n, a0)   , 1.0e-3);\n};\n\nEVE_TEST( \"Check behavior of diff cyl_bessel_kn on wide \"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(0.0, 10.0)\n                             , eve::test::randoms(0.0, 10.0))\n        )\n  <typename T>(T n, T a0 )\n{\n  using v_t = eve::element_type_t<T>;\n  auto eve__diff_bessel_kn =  [](auto n, auto x) { return eve::diff(eve::cyl_bessel_kn)(n, x); };\n  auto std__diff_bessel_kn =  [](auto n, auto x)->v_t { return boost::math::cyl_bessel_k_prime(double(n), double(x)); };\n  TTS_RELATIVE_EQUAL(eve__diff_bessel_kn(n, a0),   map(std__diff_bessel_kn, n, a0)   , 1.0e-3);\n\n};\n", "meta": {"hexsha": "3b9fbc43a64ae25ef2f815d78286b2f4ff904b79", "size": 12012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/bessel/cyl_bessel_kn.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/bessel/cyl_bessel_kn.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/bessel/cyl_bessel_kn.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": 55.8697674419, "max_line_length": 120, "alphanum_fraction": 0.6100566101, "num_tokens": 5066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5149157794318959}}
{"text": "/**\n ** Isaac Genome Alignment Software\n ** Copyright (c) 2010-2017 Illumina, Inc.\n ** All rights reserved.\n **\n ** This software is provided under the terms and conditions of the\n ** GNU GENERAL PUBLIC LICENSE Version 3\n **\n ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3\n ** along with this program. If not, see\n ** <https://github.com/illumina/licenses/>.\n **\n ** \\file MathCompatibility.hh\n **\n ** \\brief  Compatibility layer for math-related constructs.\n **\n ** \\author Come Raczy\n **/\n\n#ifndef iSAACCOMMON_MATH_COMPATIBILITY_HH\n#define iSAACCOMMON_MATH_COMPATIBILITY_HH\n\n#include <cmath>\n\n#include \"config.h\"\n\n#ifndef HAVE_FLOORF\ninline float floorf(float x)\n{\n    return static_cast<float> (floor(x));\n}\n#define HAVE_FLOORF\n#endif\n\n#ifndef HAVE_ROUND\ninline double round(double x)\n{\n    return (x - floor(x) < 0.5) ? floor(x) : ceil(x);\n}\n#define HAVE_ROUND\n#endif\n\n#ifndef HAVE_ROUNDF\ninline float roundf(float x)\n{\n    return (x - floorf(x) < 0.5f ? floorf(x) : ceil(x));\n}\n#define HAVE_ROUNDF\n#endif\n\n#ifndef HAVE_POWF\ninline float powf(float x, float y)\n{\n    return static_cast<float> (pow(x, y));\n}\n#define HAVE_POWF\n#endif\n\n#ifndef HAVE_ERF\n#include <boost/math/special_functions/erf.hpp>\ninline double erf(double x)\n{\n    return boost::math::erf(x);\n}\n#define HAVE_ERF\n#endif\n\n#ifndef HAVE_ERFF\n#include <boost/math/special_functions/erf.hpp>\ninline float erff(float x)\n{\n    return boost::math::erf(x);\n}\n#define HAVE_ERFF\n#endif\n\n#ifndef HAVE_ERFC\n#include <boost/math/special_functions/erf.hpp>\ninline double erfc(double x)\n{\n    return boost::math::erfc(x);\n}\n#define HAVE_ERFC\n#endif\n\n#ifndef HAVE_ERFCF\n#include <boost/math/special_functions/erf.hpp>\ninline float erfc(float x)\n{\n    return boost::math::erfc(x);\n}\n#define HAVE_ERFCF\n#endif\n\n#endif // #ifndef iSAACCOMMON_MATH_COMPATIBILITY_HH\n", "meta": {"hexsha": "0c2068382431c78a2c1c0dde547a5be7f0f9b749", "size": 1847, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/c++/include/common/MathCompatibility.hh", "max_stars_repo_name": "Illumina/Isaac4", "max_stars_repo_head_hexsha": "0924fba8b467868da92e1c48323b15d7cbca17dd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T22:59:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T06:33:22.000Z", "max_issues_repo_path": "src/c++/include/common/MathCompatibility.hh", "max_issues_repo_name": "Illumina/Isaac4", "max_issues_repo_head_hexsha": "0924fba8b467868da92e1c48323b15d7cbca17dd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-26T11:36:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T18:48:43.000Z", "max_forks_repo_path": "src/c++/include/common/MathCompatibility.hh", "max_forks_repo_name": "Illumina/Isaac4", "max_forks_repo_head_hexsha": "0924fba8b467868da92e1c48323b15d7cbca17dd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-10-19T20:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-29T14:44:06.000Z", "avg_line_length": 19.2395833333, "max_line_length": 79, "alphanum_fraction": 0.7195452084, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5149157740816973}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/bindings/rr.hpp>\n#include <boost/test/included/test_exec_monitor.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/test.hpp>\n#include <boost/lexical_cast.hpp>\n#include <fstream>\n\n#include <boost/math/tools/test_data.hpp>\n#include \"ntl_rr_lanczos.hpp\"\n\nusing namespace boost::math::tools;\n\n//\n// Force trunctation to float precision of input values:\n// we must ensure that the input values are exactly representable\n// in whatever type we are testing, or the output values will all\n// be thrown off:\n//\nfloat external_f;\nfloat force_truncate(const float* f)\n{\n   external_f = *f;\n   return external_f;\n}\n\nfloat truncate_to_float(boost::math::ntl::RR r)\n{\n   float f = boost::math::tools::real_cast<float>(r);\n   return force_truncate(&f);\n}\n\nstruct gamma_inverse_generator_a\n{\n   std::tr1::tuple<boost::math::ntl::RR, boost::math::ntl::RR> operator()(const boost::math::ntl::RR x, const boost::math::ntl::RR p)\n   {\n      boost::math::ntl::RR x1 = boost::math::gamma_p_inva(x, p);\n      boost::math::ntl::RR x2 = boost::math::gamma_q_inva(x, p);\n      std::cout << \"Inverse for \" << x << \" \" << p << std::endl;\n      return std::tr1::make_tuple(x1, x2);\n   }\n};\n\n\nint test_main(int argc, char*argv [])\n{\n   boost::math::ntl::RR::SetPrecision(1000);\n   boost::math::ntl::RR::SetOutputPrecision(100);\n\n   bool cont;\n   std::string line;\n\n   parameter_info<boost::math::ntl::RR> arg1, arg2;\n   test_data<boost::math::ntl::RR> data;\n\n   std::cout << \"Welcome.\\n\"\n      \"This program will generate spot tests for the inverse incomplete gamma function:\\n\"\n      \"  gamma_p_inva(a, p) and gamma_q_inva(a, q)\\n\\n\";\n\n   arg1 = make_power_param<boost::math::ntl::RR>(boost::math::ntl::RR(0), -4, 24);\n   arg2 = make_random_param<boost::math::ntl::RR>(boost::math::ntl::RR(0), boost::math::ntl::RR(1), 15);\n   data.insert(gamma_inverse_generator_a(), arg1, arg2);\n \n   line = \"igamma_inva_data.ipp\";\n   std::ofstream ofs(line.c_str());\n   write_code(ofs, data, \"igamma_inva_data\");\n   \n   return 0;\n}\n\n", "meta": {"hexsha": "66e410c1f52288a0db1f6b12859e355661cab713", "size": 2318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/gamma_P_inva_data.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/math/tools/gamma_P_inva_data.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/tools/gamma_P_inva_data.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": 30.5, "max_line_length": 133, "alphanum_fraction": 0.6846419327, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5149157687314988}}
{"text": "\n// Copyright (c) 2005 - 2014 Marc de Kamps\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//    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n//    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation \n//      and/or other materials provided with the distribution.\n//    * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software \n//      without specific prior written permission.\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 \n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY \n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \n// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 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 OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n//      If you use this software in work leading to a scientific publication, you should include a reference there to\n//      the 'currently valid reference', which can be found at http://miind.sourceforge.net\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include <boost/test/execution_monitor.hpp>\n#include <GeomLib.hpp>\n#include <MPILib/include/AlgorithmInterface.hpp>\n#include <MPILib/include/DelayedConnection.hpp>\n\nusing namespace GeomLib;\nusing namespace MPILib;\nusing MPILib::DelayedConnection;\n\nBOOST_AUTO_TEST_CASE(MuSigmaScalarTest)\n{\n        MuSigmaScalarProduct<MPILib::DelayedConnection>  prod;\n\n\tvector<NodeType> vec_type;\n\tvec_type.push_back(EXCITATORY_GAUSSIAN);\n\tvec_type.push_back(INHIBITORY_GAUSSIAN);\n\n\tvector<MPILib::DelayedConnection> vec_con;\n\tMPILib::DelayedConnection con_1(1, 0.01,0.0);\n\tMPILib::DelayedConnection con_2(1,-0.01,0.0);\n\tvec_con.push_back(con_1);\n\tvec_con.push_back(con_2);\n\n\tRate rate = 1000.0;\n\tvector<Rate> vec_rates;\n\n\tTime tau = 10e-3;\n\n\tvec_rates.push_back(rate);\n\tvec_rates.push_back(rate);\n\n\tMuSigma ms = prod.Evaluate(vec_rates, vec_con, tau);\n\n\tBOOST_CHECK(ms._mu == 0.0);\n\tBOOST_CHECK_CLOSE(ms._sigma, 0.0447214, 0.001);\n\n}\n\n", "meta": {"hexsha": "5ca2e373f05986ee91760c569bbbac7019b3682c", "size": 2753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/UnitGeomLib/MuSigmaScalarProductTest.cpp", "max_stars_repo_name": "dekamps/miind", "max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z", "max_issues_repo_path": "apps/UnitGeomLib/MuSigmaScalarProductTest.cpp", "max_issues_repo_name": "dekamps/miind", "max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z", "max_forks_repo_path": "apps/UnitGeomLib/MuSigmaScalarProductTest.cpp", "max_forks_repo_name": "dekamps/miind", "max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z", "avg_line_length": 45.131147541, "max_line_length": 163, "alphanum_fraction": 0.7737014166, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5149157676527855}}
{"text": "#ifdef MEX\n\n#include <igl/copyleft/cgal/outer_hull.h>\n\n#include <igl/matlab/MexStream.h>\n#include <igl/matlab/mexErrMsgTxt.h>\n#include <igl/matlab/prepare_lhs.h>\n#include <igl/matlab/validate_arg.h>\n#include <igl/matlab/parse_rhs.h>\n#include <igl/C_STR.h>\n\n#include <mex.h>\n#include <Eigen/Dense>\n#include <iostream>\n\n#include <cstring>\n\nvoid parse_rhs(\n  const int nrhs, \n  const mxArray *prhs[], \n  Eigen::MatrixXd & V,\n  Eigen::MatrixXi & F,\n  bool & legacy)\n{\n  using namespace std;\n  using namespace igl;\n  using namespace igl::matlab;\n  using namespace Eigen;\n  mexErrMsgTxt(nrhs >= 2, \"The number of input arguments must be >=2.\");\n\n  const auto & parse_mesh = [](\n    const mxArray *prhs[], \n    Eigen::MatrixXd & V,\n    Eigen::MatrixXi & F)\n  {\n    const int dim = mxGetN(prhs[0]);\n    mexErrMsgTxt(dim == 3,\n      \"Mesh vertex list must be #V by 3 list of vertex positions\");\n    mexErrMsgTxt(dim == mxGetN(prhs[1]),\n      \"Mesh \\\"face\\\" simplex size must equal dimension\");\n    parse_rhs_double(prhs,V);\n    parse_rhs_index(prhs+1,F);\n  };\n  parse_mesh(prhs,V,F);\n  {\n    int i = 3;\n    while(i<nrhs)\n    {\n      mexErrMsgTxt(mxIsChar(prhs[i]),\"Parameter names should be strings\");\n      // Cast to char\n      const char * name = mxArrayToString(prhs[i]);\n      if(strcmp(\"Legacy\",name) == 0)\n      {\n        validate_arg_logical(i,nrhs,prhs,name);\n        validate_arg_scalar(i,nrhs,prhs,name);\n        legacy = (bool)*mxGetLogicals(prhs[++i]);\n      }else\n      {\n        mexErrMsgTxt(false,\"Unknown parameter\");\n      }\n      i++;\n    }\n  }\n}\n\nvoid mexFunction(\n  int nlhs, mxArray *plhs[], \n  int nrhs, const mxArray *prhs[])\n{\n  using namespace std;\n  using namespace Eigen;\n  using namespace igl;\n  using namespace igl::matlab;\n  using namespace igl::copyleft::cgal;\n\n  igl::matlab::MexStream mout;        \n  std::streambuf *outbuf = cout.rdbuf(&mout);\n  //mexPrintf(\"Compiled at %s on %s\\n\",__TIME__,__DATE__);\n\n  MatrixXd V,HV;\n  MatrixXi F,G;\n  VectorXi J,flip;\n  bool legacy = false;\n  parse_rhs(nrhs,prhs,V,F,legacy);\n  if(legacy)\n  {\n    outer_hull_legacy(V,F,G,J,flip);\n  }else\n  {\n    outer_hull(V,F,HV,G,J,flip);\n  }\n\n  int offset = (legacy?0:1);\n  switch(nlhs-offset)\n  {\n    default:\n    {\n      mexErrMsgTxt(false,\"Too many output parameters.\");\n    }\n    case 3:\n    {\n      prepare_lhs_logical(flip,plhs+2+offset);\n      // Fall through\n    }\n    case 2:\n    {\n      prepare_lhs_index(J,plhs+1+offset);\n      // Fall through\n    }\n    case 1:\n    {\n      prepare_lhs_index(G,plhs+0+offset);\n      // Fall through\n    }\n    case 0: \n    {\n      if(!legacy)\n      {\n        prepare_lhs_double(HV,plhs);\n      }\n      break;\n    }\n    case -1:\n    {\n      assert(!legacy);\n      break;\n    }\n  }\n\n  // Restore the std stream buffer Important!\n  std::cout.rdbuf(outbuf);\n}\n\n#endif\n", "meta": {"hexsha": "67e83e1a03206c2cec9f62a385a5d032ff14d7f3", "size": 2808, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry_Processing_Toolbox/src/cppmex/outer_hull.cpp", "max_stars_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_stars_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-02-08T08:37:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T01:52:38.000Z", "max_issues_repo_path": "Geometry_Processing_Toolbox/src/cppmex/outer_hull.cpp", "max_issues_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_issues_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_issues_repo_licenses": ["MIT"], "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_Processing_Toolbox/src/cppmex/outer_hull.cpp", "max_forks_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_forks_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-18T08:24:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-18T08:24:36.000Z", "avg_line_length": 20.8, "max_line_length": 74, "alphanum_fraction": 0.6093304843, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5149157676527853}}
{"text": "#include \"refill/measurement_models/linearized_measurement_model.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n\n#include \"refill/distributions/gaussian_distribution.h\"\n\nnamespace refill {\n\nclass LinearizedMeasurementModelClass : public LinearizedMeasurementModel {\n public:\n  LinearizedMeasurementModelClass(\n      const size_t& state_dim, const size_t& measurement_dim,\n      const DistributionInterface& measurement_noise)\n      : LinearizedMeasurementModel(state_dim, measurement_dim,\n                                   measurement_noise) {}\n  Eigen::VectorXd observe(const Eigen::VectorXd& state,\n                          const Eigen::VectorXd& noise) const {\n    return state + noise;\n  }\n};\n\nTEST(LinearizedMeasurementModelTest, FullTest) {\n  GaussianDistribution measurement_noise(Eigen::Vector2d::Zero(),\n                                         Eigen::Matrix2d::Identity());\n\n  LinearizedMeasurementModelClass measurement_model(2, 2, measurement_noise);\n\n  Eigen::MatrixXd state_jacobian = measurement_model.getMeasurementJacobian(\n      Eigen::Vector2d::Zero());\n\n  ASSERT_EQ(measurement_model.getMeasurementDim(), state_jacobian.rows());\n  ASSERT_EQ(measurement_model.getStateDim(), state_jacobian.cols());\n  ASSERT_EQ(Eigen::Matrix2d::Identity(), state_jacobian);\n\n  Eigen::Matrix2d noise_jacobian = measurement_model.getNoiseJacobian(\n      Eigen::Vector2d::Zero());\n\n  ASSERT_EQ(measurement_model.getMeasurementDim(), noise_jacobian.rows());\n  ASSERT_EQ(measurement_model.getNoiseDim(), noise_jacobian.cols());\n  ASSERT_EQ(Eigen::Matrix2d::Identity(), noise_jacobian);\n}\n\n}  // namespace refill\n", "meta": {"hexsha": "d947c25d4d7131005e2101beadba84d9b8ba7c53", "size": 1617, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/linearized_measurement_model_test.cc", "max_stars_repo_name": "jwidauer/refill", "max_stars_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-13T07:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T11:26:34.000Z", "max_issues_repo_path": "src/tests/linearized_measurement_model_test.cc", "max_issues_repo_name": "jwidauer/refill", "max_issues_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/linearized_measurement_model_test.cc", "max_forks_repo_name": "jwidauer/refill", "max_forks_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T13:21:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T20:33:20.000Z", "avg_line_length": 35.152173913, "max_line_length": 77, "alphanum_fraction": 0.73283859, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5149157623025868}}
{"text": "/*\n * @Descripttion: \n * @version: \n * @Author: li\n * @Date: 2021-02-28 11:33:51\n * @LastEditors: li\n * @LastEditTime: 2021-04-12 18:00:38\n */\n#include \"ros/ros.h\"\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <geometry_msgs/PoseStamped.h>\n#include <opencv2/opencv.hpp>\n#include \"eigen3/Eigen/Dense\"\n#include <opencv2/core.hpp>\n#include \"opencv2/core/eigen.hpp\"\nusing namespace cv;\nusing namespace Eigen;\nusing namespace std;\n\ngeometry_msgs::PoseStamped c_pos,t_pos;\n\nvoid ReadCalibrationFile(std::string _choose_file,cv::Mat &out_RT)\n{\n    std::cout << \"_choose_file: \" << _choose_file << std::endl;\n    cv::FileStorage fs(_choose_file, cv::FileStorage::READ);\n    if (!fs.isOpened())\n    {\n        std::cout << \"Cannot open file calibration file\" << _choose_file << std::endl;\n    }\n    else\n    {\n      fs[\"CameraExtrinsicMat\"] >> out_RT;\n    }\n}\n\nvoid readCameraParams(std::string& file){\n    std::cout << \"file:\" << file << std::endl;\n    cv::Mat color_lidar_exRT;\n    std::string color_lidar_yamlfilepath;\n    ReadCalibrationFile(file, color_lidar_exRT);\n\n    Eigen::Matrix4d transform;\n    cv::cv2eigen(color_lidar_exRT, transform);\n    std::cout << \"Matrix4d:\"<< transform.matrix() << std::endl;\n    Eigen::Transform<double, 3, Eigen::Affine> a3d_transform(transform);\n\n    std::cout <<\"translation:\" <<a3d_transform.translation() << std::endl;\n    std::cout <<\"linear:\" <<a3d_transform.linear() << std::endl;\n    Eigen::Quaterniond qua;\n    Eigen::Matrix3d rotation;\n    rotation << a3d_transform.linear();\n    qua = rotation;\n}\n\nvoid update(){\n    /*\n    Eigen::Matrix3d rotMatrix;\n    Eigen::Vector3d vectorBefore(x, y, z)\n    Eigen::Vector3d vectorAfter(a, b, c);\n \n    rotMatrix = Eigen::Quaterniond::FromTwoVectors(vectorBefore, vectorAfter).toRotationMatrix();\n    */\n   //calc angle\n    \n}\n\nvoid target_callback(const geometry_msgs::PoseStampedConstPtr &msg){\n    t_pos.pose.position.x = msg->pose.position.x;\n    t_pos.pose.position.y = msg->pose.position.y;\n    t_pos.pose.position.z = msg->pose.position.z;\n    Eigen::Quaterniond q(c_pos.pose.orientation.w, c_pos.pose.orientation.x, c_pos.pose.orientation.y, c_pos.pose.orientation.z);\n    //forward\n    Eigen::Vector3d v(1, 0, 0);\n    Eigen::Vector3d f = q * v;\n    \n    Eigen::Vector3d c(t_pos.pose.position.x-c_pos.pose.position.x, t_pos.pose.position.y-c_pos.pose.position.y, t_pos.pose.position.z-c_pos.pose.position.z);\n\n    Eigen::Matrix3d rotMatrix;\n    rotMatrix = Eigen::Quaterniond::FromTwoVectors(f, c).toRotationMatrix();\n    std::cout << \"matrix:\" << rotMatrix.matrix() << std::endl;\n    Eigen::Vector3d eulerAngle=rotMatrix.eulerAngles(0,1,2);\n    std::cout << \"roll:\" << eulerAngle(0) << std::endl;\n    std::cout << \"pitch:\" << eulerAngle(1) << std::endl;\n    std::cout << \"yaw:\" << eulerAngle(2) << std::endl;\n    std::cout << \"----------------------\" << std::endl;\n    std::cout << \"roll:\" << eulerAngle(0)*180/M_PI << std::endl;\n    std::cout << \"pitch:\" << eulerAngle(1)*180/M_PI << std::endl;\n    std::cout << \"yaw:\" << eulerAngle(2)*180/M_PI << std::endl;\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"eigen_demo_node\");\n    ros::NodeHandle nh(\"~\");\n    std::string camera_file = nh.param<std::string>(\"camera_file\", \"\");\n    //readCameraParams(camera_file);\n    ros::Publisher pub = nh.advertise<geometry_msgs::PoseStamped>(\"/goal\", 1);\n    ros::Subscriber sub = nh.subscribe(\"/target\", 1, &target_callback);\n    ROS_INFO(\"eigen_demo_node started...\");\n    ros::Rate rate(10);\n    /*\n    Eigen::Affine3f transform = Eigen::Affine3f::Identity();\n    transform.translation() << 2.4668250442e+01, 6.320669323e+00, -1.3322685606304879e+02;\n    \n    Eigen::Matrix3f rotation(3,3);\n    rotation << -5.08698404e-01, 1.58019021e-01, -8.46319020e-01,\n                8.60769331e-01, 1.13197252e-01, -4.96248573e-01,\n                1.73842758e-02, -9.80926335e-01, -1.93601176e-01;\n    transform.linear() = rotation;\n\n    Eigen::Matrix3d rotation1(3,3);\n    rotation1 << -5.08698404e-01, 1.58019021e-01, -8.46319020e-01,\n                8.60769331e-01, 1.13197252e-01, -4.96248573e-01,\n                1.73842758e-02, -9.80926335e-01, -1.93601176e-01;\n    Eigen::Quaterniond qua;\n    qua = rotation1;\n\n    Eigen::Vector3d eulerAngle=rotation1.eulerAngles(2,1,0);\n    std::cout << \"roll:\" << eulerAngle(0) << std::endl;\n    std::cout << \"pitch:\" << eulerAngle(1) << std::endl;\n    std::cout << \"yaw:\" << eulerAngle(2) << std::endl;\n    std::cout << transform.matrix() << std::endl;\n    std::cout << transform.translation() << std::endl;\n    std::cout << transform.linear() << std::endl;\n    */\n    cv::Mat color_lidar_exRT;\n    ReadCalibrationFile(camera_file, color_lidar_exRT);\n\n    Eigen::Matrix4d transform;\n    cv::cv2eigen(color_lidar_exRT, transform);\n    std::cout << \"Matrix4d:\"<< transform.matrix() << std::endl;\n    Eigen::Transform<double, 3, Eigen::Affine> a3d_transform(transform);\n\n    std::cout <<\"translation:\" <<a3d_transform.translation() << std::endl;\n    std::cout <<\"linear:\" <<a3d_transform.linear() << std::endl;\n    Eigen::Quaterniond qua;\n    Eigen::Matrix3d rotation;\n    rotation << a3d_transform.linear();\n    qua = rotation;\n\n    std::cout << \"qua x:\" << qua.x()<< \" y:\" << qua.y()<< \" z:\" << qua.z()<< \" w:\" << qua.w() << std::endl;\n    Eigen::Vector3d eulerAngle=rotation.eulerAngles(2,1,0);\n    std::cout << \"roll:\" << eulerAngle(0) << std::endl;\n    std::cout << \"pitch:\" << eulerAngle(1) << std::endl;\n    std::cout << \"yaw:\" << eulerAngle(2) << std::endl;\n\n    geometry_msgs::PoseStamped goal;\n    goal.header.stamp = ros::Time::now();\n    goal.header.frame_id = \"map\";\n    goal.pose.position.x = a3d_transform.translation()[0];\n    goal.pose.position.y = a3d_transform.translation()[1];\n    goal.pose.position.z = a3d_transform.translation()[2];\n    goal.pose.orientation.x = qua.x();\n    goal.pose.orientation.y = qua.y();\n    goal.pose.orientation.z = qua.z();\n    goal.pose.orientation.w = qua.w();\n    c_pos.pose.position = goal.pose.position;\n    c_pos.pose.orientation = goal.pose.orientation;\n    while (ros::ok())\n    {\n        update();\n        pub.publish(goal);\n        ros::spinOnce();\n        rate.sleep();\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "dc15fa39de60e09f672ea02d714c73f03f075770", "size": 6224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_demo/src/eigen_demo_node.cpp", "max_stars_repo_name": "l756302098/ros_practice", "max_stars_repo_head_hexsha": "4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7", "max_stars_repo_licenses": ["MIT"], "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_demo/src/eigen_demo_node.cpp", "max_issues_repo_name": "l756302098/ros_practice", "max_issues_repo_head_hexsha": "4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7", "max_issues_repo_licenses": ["MIT"], "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_demo/src/eigen_demo_node.cpp", "max_forks_repo_name": "l756302098/ros_practice", "max_forks_repo_head_hexsha": "4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7", "max_forks_repo_licenses": ["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.1860465116, "max_line_length": 157, "alphanum_fraction": 0.6365681234, "num_tokens": 1838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5149157580311012}}
{"text": "//#include \"visualizer.hpp\"\n//#include \"windowHandler.hpp\"\n#include \"visa.hpp\"\n#include <armadillo>\n#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\nvoid mexicanHat( double freq, arma::mat &matrix );\nint main( int argc, char** argv )\n{\n  visa::WindowHandler plots;\n  try\n  {\n    visa::Colormaps::Colormap_t cmap = visa::Colormaps::Colormap_t::NIPY_SPECTRAL;\n    plots.addPlot( \"Mexican Hat\" );\n    plots.setActive( \"Mexican Hat\" );\n    plots.getActive().setCmap( cmap );\n    arma::mat matrix(2000,2000);\n    mexicanHat( 0.1, matrix );\n    plots.getActive().setImg( matrix );\n    plots.show();\n    char quit;\n    cout << \"Press any character to quit...\\n\";\n    cin >> quit;\n  }\n  catch ( exception &exc )\n  {\n    cout << exc.what() << endl;\n    return 1;\n  }\n  catch (...)\n  {\n    cout << \"Unexpected exception!\\n\";\n    return 1;\n  }\n\n  return 0;\n}\n\n// Function implementation\nvoid mexicanHat( double freq, arma::mat &matrix )\n{\n  // Add 0.01 to avoid problems at i=0 and j=0\n  for ( int i=0;i<matrix.n_cols;i++ )\n  {\n    double x = -static_cast<double>(matrix.n_cols)/2.0 + i+0.01;\n    for ( int j=0;j<matrix.n_rows;j++ )\n    {\n      double y = -static_cast<double>(matrix.n_rows)/2.0+j+0.01;\n      double r = sqrt( x*x+y*y );\n      matrix(i,j) = sin(freq*r)/(freq*r);\n    }\n  }\n}\n", "meta": {"hexsha": "1a1baa3e2ce502e645f5c0c49e999c66d4f06726", "size": 1292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/exMexicanHat.cpp", "max_stars_repo_name": "davidkleiven/VISA", "max_stars_repo_head_hexsha": "1b07197a3ea1f88c40e7d9249e08deee360ea814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-27T12:49:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-05T05:50:51.000Z", "max_issues_repo_path": "Examples/exMexicanHat.cpp", "max_issues_repo_name": "davidkleiven/VISA", "max_issues_repo_head_hexsha": "1b07197a3ea1f88c40e7d9249e08deee360ea814", "max_issues_repo_licenses": ["MIT"], "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/exMexicanHat.cpp", "max_forks_repo_name": "davidkleiven/VISA", "max_forks_repo_head_hexsha": "1b07197a3ea1f88c40e7d9249e08deee360ea814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-04-11T10:05:49.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-11T10:05:49.000Z", "avg_line_length": 22.6666666667, "max_line_length": 82, "alphanum_fraction": 0.6091331269, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5149157569523882}}
{"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//N'existe pas dans Eigen Blas\n// Pas de calcul d'inverse avec ldlt dans eigen\n//corriger\n//info important car utilise dans SymMatrix.h\ntemplate <typename T>\nvoid subSymInverse(int *n,T *ap,T *t,int *info) \n{\n  symToMatrix(*n,ap,t);\n  Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > apMap (t,*n,*n,OuterStride<>(*n));\n  Matrix<T, Dynamic, Dynamic> Ai (*n,*n);\n  Eigen::LDLT<Matrix<T, Dynamic, Dynamic> > ldlt(apMap);\n  Matrix<T, Dynamic, Dynamic> id=Matrix<T, Dynamic, Dynamic>::Identity(*n,*n);\n  for (int i=0; i<*n;i++) {\n  Ai.col(i)=ldlt.solve(id.col(i));\n  };\n  *info=1-(apMap*Ai).isApprox(id);\n  apMap=Ai;\n}\n\nvoid symInverse(int *n, double *ap, double *t, int *info) { subSymInverse<double>(n, ap, t, info); }\nvoid symInverse(int *n, float *ap, float *t, int *info) { subSymInverse<float>(n, ap, t, info); }\n\n//N'existe pas dans Eigen Blas\n//pas de calcul d'inverse avec llt dans eigen\n//On va donc resoudre AX=B avec B=(1,0,0,0...) puis B=(0,1,0,....) etc...\n//Puis on constitue la matrice inverse avec les n colonnes\n//corriger\n//info important car utilise dans Matrix.h\ntemplate <typename T>\nvoid subSymDPInverse(int *n,T *ap,T* t,int *info) \n{\n  symToMatrix(*n,ap,t);\n  Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > apMap (t,*n,*n,OuterStride<>(*n));\n  Matrix<T, Dynamic, Dynamic> Ai (*n,*n);\n  Eigen::LLT<Matrix<T, Dynamic, Dynamic> > llt(apMap);\n  Matrix<T, Dynamic, Dynamic> id=Matrix<T, Dynamic, Dynamic>::Identity(*n,*n);\n  for (int i=0; i<*n;i++) {\n  Ai.col(i)=llt.solve(id.col(i));\n  };\n  *info=1-(apMap*Ai).isApprox(id);\n  apMap=Ai;\n}\n\nvoid symDPInverse(int *n, double *ap, double *t, int *info) { subSymDPInverse<double>(n, ap, t, info); }\nvoid symDPInverse(int *n, float *ap, float *t, int *info) { subSymDPInverse<float>(n, ap, t, info); }\n\n// System of linear equations with packed symmetric matrix\ntemplate <typename T>\nvoid subSymSolve(int *n,T *ap,int *,T *b,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  Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > BMap (b,*n,1,OuterStride<>(*n));\n  Eigen::LDLT<Matrix<T, Dynamic, Dynamic> > ldlt (AMap);\n  Matrix<T, Dynamic, Dynamic> x=ldlt.solve(BMap);\n  *info=1-(AMap*x).isApprox(BMap);\n  BMap=x;\n  delete [] t;\n}\n\nvoid symSolve(int *n, double *ap, int *ipiv, double *b, int *info) { subSymSolve<double>(n, ap, ipiv, b, info); }\nvoid symSolve(int *n, float *ap, int *ipiv, float *b, int *info) { subSymSolve<float>(n, ap, ipiv, b, info); }\n\n// Determinant\ntemplate <typename T>\nT subDeterminant(int *m, int *n, T *A, int *info)\n{\n   Map<Matrix<T, Dynamic, Dynamic>,0, OuterStride<> > AMap (A,*m,*n,OuterStride<>(*m));\n   Eigen::FullPivLU<Matrix<T, Dynamic, Dynamic> > lu(AMap);\n   *info = 0;\n   return(lu.determinant());\n}\n\ndouble determinant(int *m, int *n, double *A, int *info) { return subDeterminant<double>(m, n, A, info); }\nfloat determinant(int *m, int *n, float *A, int *info) { return subDeterminant<float>(m, n, A, info); }\n\ntemplate <typename T>\nT subSymDeterminant(int *n,T *ap,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::FullPivLU<Matrix<T, Dynamic, Dynamic> > lu(AMap);\n  *info=1-AMap.isApprox(lu.reconstructedMatrix());\n  delete[] t;\n  return(lu.determinant());\n} \n\ndouble symDeterminant(int *n, double *ap, int *info) { return subSymDeterminant<double>(n, ap, info); }\nfloat symDeterminant(int *n, float *ap, int *info) { return subSymDeterminant<float>(n, ap, info); }\n", "meta": {"hexsha": "940bedbe8dc9155723a98314ddc8176183406cbd", "size": 3945, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Imagine/LinAlg/src/MyEigen3.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/MyEigen3.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/MyEigen3.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.6764705882, "max_line_length": 113, "alphanum_fraction": 0.630418251, "num_tokens": 1293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5148876559658878}}
{"text": "#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n\n#include <scitbx/math/zernike.h>\n#include <scitbx/math/rotation.h>\n\nnamespace scitbx { namespace math {\nnamespace boost_python{\n\n  struct dmatrix_wrapper\n  {\n    typedef dmatrix < double > w_t;\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"dmatrix\", no_init)\n        .def( init<\n                   int const& ,\n                   double const&\n                  >\n             ((\n                arg(\"l_max\"),\n                arg(\"beta\")\n             ))\n            )\n        .def(\"djmn\", &w_t::djmn)\n      ;\n    }\n  };\n\n  void\n  wrap_dmatrix()\n  {\n    dmatrix_wrapper::wrap();\n  }\n\n// correlation\n  struct correlation_wrapper\n  {\n    typedef correlation < double > w_t;\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"correlation\", no_init)\n        .def( init<\n                   scitbx::math::zernike::nlm_array<double> const&,\n                   scitbx::math::zernike::nlm_array<double> const&,\n                   int const& ,\n                   double const&\n                  >\n             ((\n                arg(\"f_nlm\"),\n                arg(\"m_nlm\"),\n                arg(\"l_max\"),\n                arg(\"beta\")\n             ))\n            )\n        .def(\"calc_correlation\", &w_t::calc_correlation)\n        .def(\"mm_coef\", &w_t::mm_coef)\n        .def(\"mhm_coef\", &w_t::mhm_coef)\n        .def(\"rotate_moving_obj\", &w_t::rotate_moving_obj)\n        .def(\"compare_FM\", &w_t::compare_fm)\n        .def(\"set_beta\", &w_t::set_beta)\n      ;\n    }\n  };\n\n  void\n  wrap_correlation()\n  {\n    correlation_wrapper::wrap();\n  }\n\n\n}\n}}\n", "meta": {"hexsha": "1e24aae3f3c3c95a497595b3037a93d4b39f0da9", "size": 1712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/math/boost_python/rotation.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/math/boost_python/rotation.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/math/boost_python/rotation.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 21.4, "max_line_length": 67, "alphanum_fraction": 0.4935747664, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5148876559658878}}
{"text": "#ifndef CIRCUMCENTER_H\n#define CIRCUMCENTER_H\n#include <mtao/types.h>\n\n#include <Eigen/Dense>\n\nnamespace mtao {\nnamespace geometry {\n\ntemplate <typename Derived>\nauto circumcenter_spd(const Eigen::MatrixBase<Derived>& V) {\n    // 2 V.dot(C) = sum(V.colwise().squaredNorm()).transpose()\n\n    // probably dont really need this temporary\n    auto m = (V.rightCols(V.cols() - 1).colwise() - V.col(0)).eval();\n    auto A = (2 * m.transpose() * m).eval();\n    auto b = m.colwise().squaredNorm().transpose().eval();\n    A.llt().solveInPlace(b);\n\n    auto c = (V.col(0) + m * b).eval();\n    return c;\n}\ntemplate <typename Derived>\nauto circumcenter_spsd(const Eigen::MatrixBase<Derived>& V) {\n    mtao::MatrixX<typename Derived::Scalar> A(V.cols() + 1, V.cols() + 1);\n    A.setConstant(1);\n    A(V.cols(), V.cols()) = 0;\n    auto m = V.transpose() * V;\n    ;\n    A.topLeftCorner(V.cols(), V.cols()) = 2 * m;\n    mtao::VectorX<typename Derived::Scalar> b(V.cols() + 1);\n    b.setConstant(1);\n    b.topRows(m.cols()) = V.colwise().squaredNorm().transpose();\n\n    auto x = A.colPivHouseholderQr().solve(b).eval();\n\n    return (V * x.topRows(V.cols())).eval();\n}\ntemplate <typename Derived>\nauto circumcenter(const Eigen::MatrixBase<Derived>& V) {\n    return circumcenter_spd(V);\n}\n\ntemplate <typename VertexDerived, typename SimplexDerived>\nauto circumcenters(const Eigen::MatrixBase<VertexDerived>& V,\n                   const Eigen::MatrixBase<SimplexDerived>& S) {\n    constexpr static int E = VertexDerived::RowsAtCompileTime;  // embed dim\n    constexpr static int N =\n        SimplexDerived::ColsAtCompileTime;  // number of elements\n    constexpr static int D = SimplexDerived::RowsAtCompileTime;  // simplex dim\n    using Scalar = typename VertexDerived::Scalar;\n\n    Eigen::Matrix<Scalar, E, N> C(V.rows(), S.cols());\n\n    Eigen::Matrix<Scalar, E, D> v(V.rows(), S.rows());\n#pragma omp parallel for private(v)\n    for (int i = 0; i < S.cols(); ++i) {\n        auto s = S.col(i);\n        for (int j = 0; j < S.rows(); ++j) {\n            v.col(j) = V.col(s(j));\n        }\n        C.col(i) = circumcenter(v);\n    }\n    return C;\n}\n}  // namespace geometry\n}  // namespace mtao\n#endif  // CIRCUMCENTER_H\n", "meta": {"hexsha": "83bee433b25236297ecd31ebb442f7c305d215e1", "size": 2197, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/geometry/circumcenter.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/geometry/circumcenter.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/geometry/circumcenter.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8405797101, "max_line_length": 79, "alphanum_fraction": 0.627674101, "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5148876503673046}}
{"text": "#ifndef FINDINTRA_CPP\n#define FINDINTRA_CPP\n\n#include <cstdlib>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <math.h>\n#include <vector>\n\n#include <gsl/gsl_cdf.h>\n\n#include <scythestat/rng/mersenne.h>\n#include <scythestat/distributions.h>\n#include <scythestat/ide.h>\n#include <scythestat/la.h>\n#include <scythestat/matrix.h>\n#include <scythestat/rng.h>\n#include <scythestat/smath.h>\n#include <scythestat/stat.h>\n#include <scythestat/optimize.h>\n\n#include <IRLS_glm/IRLS.h>\n\n//#include <RInside.h>\n\n#include <mlpack/methods/lars/lars.hpp>\n#include <mlpack/methods/linear_regression/linear_regression.hpp>\n#include <boost/test/unit_test.hpp>\n\n#define INTTAG 0\n#define BOOLTAG 1\n#define DIETAG 2\n\n#define TESTFREQTHRES 1\n#define NEIGHBDIS 5\n//#define MORANI 0.001\n#define PCUTOFF 0.004\n#define PRECISION 10e48\n#define READBLOCK 409600\n\n//using namespace std;\nusing std::abs;\nusing std::basic_string;\nusing std::cerr;\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::exception;\nusing std::flush;\nusing std::ifstream;\nusing std::istringstream;\nusing std::make_pair;\nusing std::map;\nusing std::ofstream;\nusing std::ostringstream;\nusing std::pair;\nusing std::sort;\nusing std::string;\nusing std::vector;\n\n\nint reader_dif(const string&, vector< vector< vector<int> > >&);\nint reader_dsm(const string&, vector< vector<int> >&);\nvoid reader_ictm(const string&, map<int, int>&);\nint findIntraDomainInteraction(map<int, int>&, string, vector< vector<int> >&, vector< vector< vector<int> > >&, map<int, int>&, map< int, map< pair<int, int>, double > >&, double, double, double);\nint rmDependentCol(vector< vector<double> >&, vector<double>&, vector< pair<int, int> >&, double, int&, vector< vector<double> >&);\nint calStanScores(vector< vector<double> >&);\nint calPearsonCorr(vector< vector<double> >&, vector< pair<int, int> >&, const double&, int, map<int, int>&);\nint writer_corrFile(map< pair<int, int>, double >&, string&);\n\nvoid usage();\n\ninline void usage()\n{\n    cout <<\"Usage: findIntraDomainInteraction empericalDistributionFile interChrFreqFile domainSitesFile domainInteractionFreqFile chrNum MORANI CorrelationThresholdForScreen\"<<endl;\n}\n\n//convtIndex is now 0 based\ninline int convtIndex(int row_fun, int col_fun, int siteNum_fun)\n{\n    if (row_fun==col_fun || row_fun>=siteNum_fun || col_fun>=siteNum_fun || row_fun<0 || col_fun<0)\n    {//cout<<\"row or column exceed bound.\"<<endl;\n        return -1;\n    }\n    else\n    {\n        int max_fun = 0, min_fun = 0;\n        if (row_fun<col_fun)\n        {\n            //switch to 1 based\n            max_fun = col_fun+1;\n            min_fun = row_fun+1;\n        }\n        else\n        {\n            max_fun = row_fun+1;\n            min_fun = col_fun+1;\n        }\n        return((2*siteNum_fun-min_fun)*(min_fun-1)/2+max_fun-min_fun) - 1;//-1 put the output to be 0 based\n    }\n}\n\n\n//l=sigma(yi(theta*xi+offseti)-exp(theta*xi+offseti))\nclass PoissonModel {\n    public:\n    double operator() (const scythe::Matrix<double> beta){\n        const int n = y_.rows();\n        const int p = X_.cols();\n\n        scythe::Matrix<double> eta = X_ * beta + offset_;\n        scythe::Matrix<double> m = exp(eta);\n        double loglike = 0.0;\n        for (int i=0; i<n; ++i)\n        loglike += y_(i) * log(m(i)) - m(i);\n        return -1.0 * loglike;\n    }\n    scythe::Matrix<double> y_;\n    scythe::Matrix<double> X_;\n    scythe::Matrix<double> offset_;\n};\n\n\nint main(int argc, char* argv[])\n{\n    if (argc < 10)\n    {\n        usage();\n        exit(1);\n    }\n\n    string empDisFile = argv[1];\n    string ictmFile = argv[2];\n    string dsmFile = argv[3];\n    string difFile = argv[4];\n    string chrNum = argv[5];\n    double MORANI = atof(argv[6]);\n    double corrThres = atof(argv[7]);\n    double disIntcp = atof(argv[8]);\n    double disCoeff = atof(argv[9]);\n\n\n    map<int, int> empDis_map;\n    map<int, int> ictm_map;\n    vector< vector<int> > dsm_map;\n    vector< vector< vector<int> > > dif_map;\n\n    //reader_ictm(empDisFile, empDis_map);\n    //cout<<\"\\nReading empDis file done.\"<<endl;\n    reader_ictm(ictmFile, ictm_map);\n    cout<<\"\\nReading ictm file done.\"<<endl;\n    reader_dsm(dsmFile, dsm_map);\n    cout<<\"\\nReading dsm file done.\"<<endl;\n    reader_dif(difFile, dif_map);\n    cout<<\"\\nReading dif file done.\"<<endl;\n\n    map< int, map< pair<int, int>, double > > pVal_map;\n\n    findIntraDomainInteraction(empDis_map, chrNum, dsm_map, dif_map, ictm_map, pVal_map, corrThres, disIntcp, disCoeff);\n\n    return 0;\n}\n\n\nint reader_dif(const string& fileToread, vector< vector< vector<int> > >& dif_local)\n{\n    ifstream inputFile(fileToread.c_str());\n    if (!inputFile)\n    {\n        //char a;\n        //cin >>a;\n        cout <<\"\\n\"<< \"Error opening \" << fileToread << \".\" << endl;\n        exit(1);\n    }\n\n    char lineStr[READBLOCK];\n    char freq_str[15];\n    int freq_int = 0;\n    int domainNum = 0;\n\n    int column = 0;\n\n    char* it_lineStr;\n    char* it_token;\n\n    int peakNum = 0;\n\n    //copy data to a map, which chrNo is the key, the value is a vector of ints(read's starting point)\n    //ofstream testBadFile(\"test\");\n    vector< vector<int> > tempDomn;\n    while(inputFile.getline(lineStr,READBLOCK))\n    {\n        it_lineStr = lineStr;\n\n        column = 0;\n\n        if (lineStr != NULL)\n        {\n            vector<int> tempFreq;\n            //testBadFile<<lineStr<<endl;\n\n            //pass head white space\n            if(*it_lineStr == 'd')\n            {\n                if (tempDomn.begin() != tempDomn.end())\n                {\n                    ++domainNum;\n                    dif_local.push_back(tempDomn);\n                    tempDomn.clear();\n                }\n                continue;\n            }\n\n            while(*it_lineStr != '\\0' && *it_lineStr != '\\n')\n            {\n                if (*it_lineStr == ' ' || *it_lineStr == '\\t')\n                {\n                    //remove white space\n                    while(*it_lineStr == ' ' || *it_lineStr == '\\t')\n                    {\n                        ++it_lineStr;\n                    }\n\n                    ++column;\n                }\n                else\n                {\n                    it_token = freq_str;\n                    while(*it_lineStr != ' ' && *it_lineStr != '\\t' && *it_lineStr != '\\0' && *it_lineStr != '\\n')\n                    {\n                        *it_token = *it_lineStr;\n                        ++it_token;\n                        ++it_lineStr;\n                    }\n                    *it_token = '\\0';\n                    freq_int = atoi(freq_str);\n                    tempFreq.push_back(freq_int);\n                }\n            }\n\n            tempDomn.push_back(tempFreq);\n            ++peakNum;\n        }\n    }\n\n    if(tempDomn.begin() != tempDomn.end())\n    {\n        dif_local.push_back(tempDomn);\n    }\n\n    inputFile.close();\n\n    return peakNum;\n}\n\n\n\n\nint reader_dsm(const string& fileToread, vector< vector<int> >& dsm_local)\n{\n    ifstream inputFile(fileToread.c_str());\n    if (!inputFile)\n    {\n        //char a;\n        //cin >>a;\n        cout <<\"\\n\"<< \"Error opening \" << fileToread << \".\" << endl;\n        exit(1);\n    }\n\n    char lineStr[READBLOCK];\n    char pos_str[15];\n    int pos_int = 0;\n\n    int column = 0;\n\n    char* it_lineStr;\n    char* it_token;\n\n    int peakNum = 0;\n\n    //copy data to a map, which chrNo is the key, the value is a vector of ints(read's starting point)\n    //ofstream testBadFile(\"test\");\n    while(inputFile.getline(lineStr,READBLOCK))\n    {\n        it_lineStr = lineStr;\n\n        column = 0;\n\n        if (lineStr != NULL)\n        {\n            vector<int> tempPos;\n            //testBadFile<<lineStr<<endl;\n\n            //pass head white space\n            while(*it_lineStr == ' '|| *it_lineStr == '\\t')\n            {\n                ++it_lineStr;\n            }\n\n            while(*it_lineStr != '\\0' && *it_lineStr != '\\n')\n            {\n                if (*it_lineStr == ' ' || *it_lineStr == '\\t')\n                {\n                    //remove white space\n                    while(*it_lineStr == ' ' || *it_lineStr == '\\t')\n                    {\n                        ++it_lineStr;\n                    }\n\n                    ++column;\n                }\n                else\n                {\n                    it_token = pos_str;\n                    while(*it_lineStr != ' ' && *it_lineStr != '\\t' && *it_lineStr != '\\0' && *it_lineStr != '\\n')\n                    {\n                        *it_token = *it_lineStr;\n                        ++it_token;\n                        ++it_lineStr;\n                    }\n                    *it_token = '\\0';\n                    pos_int = atoi(pos_str);\n                    tempPos.push_back(pos_int);\n                }\n            }\n\n            dsm_local.push_back(tempPos);\n            ++peakNum;\n        }\n    }\n\n    inputFile.close();\n\n    return peakNum;\n}\n\n\n\nvoid reader_ictm(const string& fileToread, map<int, int>& ictm_local)\n{\n    ifstream inputFile(fileToread.c_str());\n    if (!inputFile)\n    {\n        cout <<\"\\n\"<< \"Error opening \" << fileToread << \".\" << endl;\n        exit(1);\n    }\n\n    char pos[15];\n    int pos_int = 0;\n    char freq[15];\n    int freq_int = 0;\n\n    char* it_lineStr;\n    char* it_token;\n\n    char lineStr[512];\n    while(inputFile.getline(lineStr,512))\n    {\n        if (lineStr != NULL)\n        {\n            it_lineStr = lineStr;\n\n            it_token = pos;\n            while(*it_lineStr != '\\t')\n            {\n                *it_token = *it_lineStr;\n                ++it_token;\n                ++it_lineStr;\n            }\n            *it_token = '\\0';\n            ++it_lineStr;\n            pos_int = atoi(pos);\n\n            it_token = freq;\n            while(*it_lineStr != '\\t' && *it_lineStr != '\\n' && *it_lineStr != '\\0')\n            {\n                *it_token = *it_lineStr;\n                ++it_token;\n                ++it_lineStr;\n            }\n            *it_token = '\\0';\n            freq_int = atoi(freq);\n\n            ictm_local[pos_int] = freq_int;\n        }\n    }\n}\n\n\n\n\nint findIntraDomainInteraction(map<int, int>& empDisMap_fun, string jobChr_fun, vector< vector<int> >& domainSitesMap_fun, vector< vector< vector<int> > >& domainCSinterFreq_fun, map<int, int>& csInterChromTotalMap_fun, map< int, map< pair<int, int>, double > >& pVal_fun, double corrThres_fun, double disIntcp_fun, double disCoeff_fun)\n{\n    string file_effBetas =  jobChr_fun + \"_domainEffBetas\";\n    ofstream outEffBetas(file_effBetas.c_str());\n\n    int domainNum = domainSitesMap_fun.size();\n\n    //#pragma omp parallel for\n    for (int domainIt = 0; domainIt < domainNum; ++domainIt)\n    {\n        map< pair<int, int>, double>& domainPval = pVal_fun[domainIt];\n        outEffBetas<<\"domain \"<<domainIt;\n        vector<int>& sitesMap = domainSitesMap_fun[domainIt];\n        vector< vector<int> >& csInterFreqMap = domainCSinterFreq_fun[domainIt];\n        int siteNum = sitesMap.size();\n\n        int size_convert = convtIndex(siteNum-2,siteNum-1,siteNum) + 1;//the convtIndex function's first two input is 0 based and the output is 0 based too\n\tvector<double> freq_convert;\n        vector<double> offset;//distance effect\n        vector<double> effVec;//efficiency of cutting site and mappability, measured by the total inter chromosome hybrid frags\n\n        for (int rowIt=0; rowIt<siteNum; ++rowIt)\n        {\n            for (int colIt=rowIt+1; colIt<siteNum; ++colIt)\n            {\n                int index_convert=convtIndex(rowIt,colIt,siteNum);\n\n\t\t//log(y/ydist)=mu+betaeff*effvec\n                freq_convert.push_back(csInterFreqMap[rowIt][colIt]);\n\t\toffset.push_back(log(abs(sitesMap[rowIt]-sitesMap[colIt])+1)*disCoeff_fun+disIntcp_fun);\n\t\t//the digestion and ligation efficient of a cutting site should take log because, its log should proportional to log(freq)\n                effVec.push_back(log(sqrt(csInterChromTotalMap_fun[sitesMap[rowIt]])*sqrt(csInterChromTotalMap_fun[sitesMap[colIt]])+1));\n            }\n        }\n\tcout<<\"construt matrix done.\"<<endl;\n\n\tvector< vector<double> > covMatrix;\n\tcovMatrix.push_back(effVec);\n\n\tIRLS irls(\"log-link\");\n\tbool quasi_lik = false;\n\tirls.link->quasi = quasi_lik;\n\tirls.load_data(freq_convert, covMatrix, offset);\n\t//outEffBetas<<\"data loaded\"<<endl;\n\tirls.fit_model();\n\t//outEffBetas<<\"model fitted\"<<endl;\n\tvector<double> coev = irls.get_coef();\n\t//outEffBetas<<\"get coef done\"<<endl;\n\tvector<double> sev = irls.get_stderr();\n\t//outEffBetas<<\"get stderr done\"<<endl;\n\n\t//outEffBetas<<\"Col\\tEstimate\\tStd.Error\\tp-value\"<<endl;\n\tfor(size_t i = 0; i < coev.size(); ++i)\n\t{\n\t    //printf(\"X%-9zu%12.9f%12.8f\", i, coev[i], sev[i]);\n\t    //X0 is intercept/mu\n\t    double p_eff=0.0;\n\t    if(! irls.link->quasi)\n\t    {\n\t\t//printf(\"%15.6e\\n\", 2 * gsl_cdf_gaussian_P(-fabs(coev[i]/sev[i]), 1.0));\n\t\tp_eff=2 * gsl_cdf_gaussian_P(-fabs(coev[i]/sev[i]), 1.0);\n\t    }\n\t    else\n\t    {\n\t\t//printf(\"%15.6e\\n\", 2 * gsl_cdf_tdist_P(-fabs(coev[i]/sev[i]), size_convert-irls.get_rank_X()));\n\t\tp_eff=2 * gsl_cdf_tdist_P(-fabs(coev[i]/sev[i]), size_convert-irls.get_rank_X());\n\t    }\n\t    outEffBetas<<\"\\t\"<<coev[i]<<\"\\t\"<<sev[i]<<\"\\t\"<<p_eff;\n\t}\n\toutEffBetas<<endl;\n\tcovMatrix.clear();\n\t//outEffBetas.close();\n\tcontinue;\n\n\tdouble mu = coev[0];\n\t//double alpha = coev[1];\n\tdouble beta = coev[1];\n\tvector<double> constTerms(size_convert, 0.0);\n\tfor (int i = 0; i < size_convert; ++i)\n\t{\n\t    //constTerms[i] = mu+dist_ij[i]*alpha+effVec[i]*beta;\n\t    constTerms[i] = exp(mu+effVec[i]*beta+offset[i]);\n\t    //constTerms[i] = mu+effVec[i]*beta+offset[i];\n\t}\n\n        int counter_fit=0;\n        int counter_skip=0;\n\n        //#pragma omp parallel for\n        for (int rowIt=0; rowIt<siteNum; ++rowIt)\n        {\n            for (int colIt=rowIt+1; colIt<siteNum; ++colIt)\n            {\n                if(csInterFreqMap[rowIt][colIt]>TESTFREQTHRES)\n                {\n                    vector<double> neighbFreq;\n                    vector<double> neighbConstTerms;\n                    vector<double> distVec;\n\n                    int sideLen = 2*NEIGHBDIS + 1;\n                    int colNum_mat = 0;\n                    int rowNum_mat = 0;\n\n                    vector< pair<int, int> > oriCoor;\n                    for (int neighbRowIt=(rowIt-NEIGHBDIS), squareRowIt = 0; squareRowIt < sideLen; ++neighbRowIt, ++squareRowIt)\n                    {\n                        for (int neighbColIt=colIt-NEIGHBDIS, squareColIt = 0; squareColIt < sideLen; ++neighbColIt, ++squareColIt)\n                        {\n                            int distMatrix_colIt=convtIndex(neighbRowIt, neighbColIt, siteNum);\n                            //if (distMatrix_colIt==-1 || neighbColIt<=neighbRowIt || colIt<=neighbRowIt || neighbColIt<=rowIt || (neighbRowIt==rowIt && neighbColIt==colIt) )\n                            if (distMatrix_colIt==-1 || neighbColIt<=neighbRowIt || colIt<=neighbRowIt || neighbColIt<=rowIt)\n                            {continue;}\n\n                            //for future get back the original coordinates\n                            if(freq_convert[distMatrix_colIt] > TESTFREQTHRES)\n                            {\n                                oriCoor.push_back(make_pair(neighbRowIt, neighbColIt));\n                                ++colNum_mat;\n                            }\n\n                            neighbFreq.push_back(freq_convert[distMatrix_colIt]-constTerms[distMatrix_colIt]);\n                            //neighbConstTerms.push_back(constTerms[distMatrix_colIt]);\n                            distVec.push_back(log(abs(sitesMap[rowIt]-sitesMap[neighbRowIt])+abs(sitesMap[colIt]-sitesMap[neighbColIt])+1));\n                            ++rowNum_mat;\n                        }\n                    }\n\n\t\t    IRLS irls(\"log-link\");\n\t\t    bool quasi_lik = false;\n\t\t    irls.link->quasi = quasi_lik;\n\t\t    irls.load_data(freq_convert, covMatrix, offset);\n\t\t    //outEffBetas<<\"data loaded\"<<endl;\n\t\t    irls.fit_model();\n\t\t    //outEffBetas<<\"model fitted\"<<endl;\n\t\t    vector<double> coev = irls.get_coef();\n\t\t    //outEffBetas<<\"get coef done\"<<endl;\n\t\t    vector<double> sev = irls.get_stderr();\n\t\t    //outEffBetas<<\"get stderr done\"<<endl;\n\n\t\t    outEffBetas<<\"Col\\tEstimate\\tStd.Error\\tp-value\"<<endl;\n\t\t    for(size_t i = 0; i < coev.size(); ++i)\n\t\t    {\n\t\t\t//printf(\"X%-9zu%12.9f%12.8f\", i, coev[i], sev[i]);\n\t\t\t//X0 is intercept/mu\n\t\t\toutEffBetas<<\"X\"<<i<<\"\\t\"<<coev[i]<<\"\\t\"<<sev[i]<<\"\\t\";\n\t\t\tif(! irls.link->quasi)\n\t\t\t{\n\t\t\t    //printf(\"%15.6e\\n\", 2 * gsl_cdf_gaussian_P(-fabs(coev[i]/sev[i]), 1.0));\n\t\t\t    outEffBetas<<2 * gsl_cdf_gaussian_P(-fabs(coev[i]/sev[i]), 1.0)<<endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t    //printf(\"%15.6e\\n\", 2 * gsl_cdf_tdist_P(-fabs(coev[i]/sev[i]), size_convert-irls.get_rank_X()));\n\t\t\t    outEffBetas<<2 * gsl_cdf_tdist_P(-fabs(coev[i]/sev[i]), size_convert-irls.get_rank_X())<<endl;\n\t\t\t}\n\t\t    }\n\t\t    covMatrix.clear();\n\t\t    //outEffBetas.close();\n\n\n                    //int neighbFreq_size = neighbFreq.size();\n            arma::vec neighbFreq_lm(neighbFreq);\n            //arma::vec neighbFreq_lm(neighbFreq_size);\n            //for(int i=0; i<neighbFreq_size; ++i)\n            //{\n            //    neighbFreq_lm(i)=neighbFreq[i]-neighbConstTerms[i];\n            //}\n\n                    int distMat_size = distVec.size();\n            arma::mat distMat_lm(distMat_size,2);\n            for(int i=0; i<distMat_size; ++i)\n            {\n            distMat_lm(i,0)=1;\n            distMat_lm(i,1)=distVec[i];\n            }\n\n            mlpack::regression::LinearRegression lm(distMat_lm, neighbFreq_lm);\n            cout<<\"construt region model done.\"<<endl;\n\n            //set start values for theta\n            arma::vec beta_lm = lm.Parameters();\n            cout << \"The region MLEs are: \" << endl;\n            std::cout <<beta_lm(0)<<\"\\t\"<<beta_lm(1)<< \"\\n\";\n\n            //calculate std err using var(beta)=Var(error)*inv(t(X)X)\n            //arma::mat<double> distMat_t = distMat_lm.t();\n            //arma::mat<double> distMat_prod = distMat_t * distMat_lm;\n            double var_err = lm.ComputeError(distMat_lm, neighbFreq_lm);\n            arma::vec beta_stderr = sqrt(var_err * (distMat_lm.t()*distMat_lm).i());\n            cout << \"The stderr for betas are: \" << endl;\n            std::cout <<beta_stderr(0)<<\"\\t\"<<beta_stderr(1)<< \"\\n\";\n\n            double fitPval=0.0;\n            double beta_dis=0.0;\n            exit(0);\n\n\n\n                    if (fitPval < PCUTOFF && beta_dis < 0 && colNum_mat > 1)\n                    {\n                        int distNum = colNum_mat;\n                        //colNum_mat++;//add const to the last column of the dist matrix\n                        //colNum_mat;//add const to the last column of the dist matrix after rmIndependent cols is done\n                        //vector<double> distVec_lasso(colNum_mat, 0.0);\n                        vector<double> distVec_lasso((colNum_mat+1), 0.0);\n                        vector< vector<double> > distMatrix_lasso;\n                        for (int i=0; i<rowNum_mat; ++i)\n                        {\n                            distVec_lasso[colNum_mat] = neighbConstTerms[i];\n                            distMatrix_lasso.push_back(distVec_lasso);\n                        }\n\n                        int testIndex = 0;\n                        int matColIndex = 0;\n                        for (int neighbRowIt=(rowIt-NEIGHBDIS), squareRowIt = 0; squareRowIt < sideLen; ++neighbRowIt, ++squareRowIt)\n                        {\n                            for (int neighbColIt=colIt-NEIGHBDIS, squareColIt = 0; squareColIt < sideLen; ++neighbColIt, ++squareColIt)\n                            {\n                                int distMatrix_colIt=convtIndex(neighbRowIt, neighbColIt, siteNum);\n                                //if (distMatrix_colIt==-1 || neighbColIt<=neighbRowIt || colIt<=neighbRowIt || neighbColIt<=rowIt || (neighbRowIt==rowIt && neighbColIt==colIt) )\n                                if (distMatrix_colIt==-1 || neighbColIt<=neighbRowIt || colIt<=neighbRowIt || neighbColIt<=rowIt || freq_convert[distMatrix_colIt] < TESTFREQTHRES)\n                                {continue;}\n\n                                int matRowIndex = 0;//inside loop is actually the row index for the final matrix\n                                for (int neighbNeighbRowIt=(rowIt-NEIGHBDIS), squareNeighbRowIt = 0; squareNeighbRowIt < sideLen; ++neighbNeighbRowIt, ++squareNeighbRowIt)\n                                {\n                                    for (int neighbNeighbColIt=colIt-NEIGHBDIS, squareNeighbColIt = 0; squareNeighbColIt < sideLen; ++neighbNeighbColIt, ++squareNeighbColIt)\n                                    {\n                                        int distMatrix_rowIt=convtIndex(neighbNeighbRowIt, neighbNeighbColIt, siteNum);\n                                        if (distMatrix_rowIt==-1 || neighbNeighbColIt<=neighbNeighbRowIt || colIt<=neighbNeighbRowIt || neighbNeighbColIt<=rowIt)\n                                        {continue;}\n                                        //distMatrix_lasso[matRowIndex][matColIndex]=exp(-MORANI*(abs(sitesMap[neighbNeighbRowIt]-sitesMap[neighbRowIt])+abs(sitesMap[neighbNeighbColIt]-sitesMap[neighbColIt])));\n                                        distMatrix_lasso[matRowIndex][matColIndex]=log(abs(sitesMap[neighbNeighbRowIt]-sitesMap[neighbRowIt])+abs(sitesMap[neighbNeighbColIt]-sitesMap[neighbColIt])+1);\n                                        ++matRowIndex;\n                                    }\n                                }\n                                if (neighbRowIt==rowIt && neighbColIt==colIt)\n                                {\n                                    testIndex=matColIndex;\n                                }\n                                ++matColIndex;\n                                //distMatrix[make_pair(distMatrix_rowIt, distMatrix_colIt)]=exp(-MORANI*(abs(sitesMap[rowIt]-sitesMap[neighbRowIt])+abs(sitesMap[colIt]-sitesMap[neighbColIt])));\n                            }\n                        }\n\n                        //vector< vector<double> > distMatrix_lasso_rmDep;\n\n                        int testFlag = 1;\n                        bool flag_rmDep = false;\n                        //if (flag_rmDep)\n                        //{\n                        //    testFlag = rmDependentCol(distMatrix_lasso, neighbFreq, oriCoor, corrThres_fun, testIndex, distMatrix_lasso_rmDep);\n                        //}\n                        //else\n                        //{\n                        //    distMatrix_lasso_rmDep = distMatrix_lasso;\n                        //}\n            //distMatrix_lasso.clear();\n\n                        //add const to the matrix\n                        if (testFlag == 1)\n                        {\n                            //for (int i=0; i<rowNum_mat; ++i)\n                            //{\n                            //    distMatrix_lasso[i].push_back(neighbConstTerms[i]);\n                            //}\n\n/*Note Y need to substract offset before doing lasso fit, may use code from IRLS_glm*/\n\n                            //#pragma omp critical\n                            {\n                            outEffBetas<<rowIt<<\"\\t\"<<colIt<<\"\\ttest column number: \"<<testIndex<<endl;\n\n                            //if(rowIt==414 && colIt==415){\n                            const int rowNum_r = distMatrix_lasso.size();\n                            const int colNum_r = (distMatrix_lasso.begin())->size();\n                //!!!!!!!!!!! if remove dependents is true, this need to change\n                            //Rcpp::NumericVector freq_r(neighbFreq.begin(), neighbFreq.end());\n\n                            outEffBetas<<rowNum_r<<\"\\t\"<<colNum_r<<endl;\n\n                            //Rcpp::NumericMatrix distMat_r(rowNum_r, colNum_r);\n                            for (int i=0; i<rowNum_r; ++i)\n                            {\n                                for (int j=0; j<colNum_r; ++j)\n                                {\n                                    //double rndNum = preMaxRnd*rand()/(RAND_MAX + 1.0) + minRnd;\n                                    //distMat_r(i,j)= floor((distMatrix_lasso[i][j]+rndNum) * PRECISION + 0.5) / PRECISION;\n                                    //distMat_r(i,j)= floor((distMatrix_lasso[i][j]) * PRECISION + 0.5) / PRECISION;\n                    outEffBetas<<i<<\"\\t\"<<j<<endl;\n                                    //distMat_r(i,j)= distMatrix_lasso[i][j];\n                                    //distMat_r(i,j)= distMatrix_lasso[i][j] + rndNum;\n                                }\n                            }\n                //distMatrix_lasso.clear();\n\n\n                            //#pragma omp critical\n                            //domainPval[make_pair(sitesMap[rowIt], sitesMap[colIt])]=fitPval;\n                            ++counter_fit;}//}\n                            //#pragma omp end critical\n\n                            //if (fitPval < PCUTOFF)\n                            //{\n                            //    \n                            //}\n                        }\n                    }\n                    else if(colNum_mat==1)\n                    {\n                        //only 1 box has signal (freq>1), no need to use lasso to choose which one is real,or maybe could remove the ones due to the const terms, however glm should have taken care of that already\n                    }\n                }\n                else\n                {\n                    #pragma omp critical\n                    {++counter_skip;}\n                    //#pragma omp end critical\n                }\n            }\n        }\n        //freq_convert.clear();\n        //distMatrix.clear();\n        //dist_ij.clear();\n        //offsets.clear();\n        //effVec.clear();\n        //outEffBetas<<\"chr \"<<jobChr_fun<<\" domain \"<<domainIt<<\" siteNum \"<<siteNum<<\" convert size \"<<size_convert<<\"fit number \"<<counter_fit<<\" skip number \"<<counter_skip<<endl;\n    }\n    outEffBetas.close();\n    \n    return 0;\n}\n\n\n\n\nint rmDependentCol(vector< vector<double> >& distMatrix_local, vector<double>& freqVec_local, vector< pair<int, int> >& oriCoor_local, double thres_local, int& testIndex_local, vector< vector<double> >& distMatRmDep_local)\n{\n    int rowNum_fun = distMatrix_local.size();\n    if (rowNum_fun != freqVec_local.size())\n    {\n        cerr<<\"Error: row number of the dist matrix is different from the size of the frequency vector.\"<<endl;\n        exit(1);\n    }\n    int colNum_fun = (distMatrix_local.begin())->size();\n    vector< vector<double> > distMatrix_std;\n    for (int i = 0; i < colNum_fun; ++i)\n    {\n        vector<double> tempVec;\n        for (int j = 0; j < rowNum_fun; ++j)\n        {\n            tempVec.push_back(distMatrix_local[j][i]);\n        }\n        distMatrix_std.push_back(tempVec);\n    }\n    distMatrix_std.push_back(freqVec_local);\n    calStanScores(distMatrix_std);\n\n    map< pair<int, int>, double > corrMap;\n    map<int, int> rmIndex;\n    int testFlag_local = calPearsonCorr(distMatrix_std, oriCoor_local, thres_local, testIndex_local, rmIndex);\n    cout<<\"testFlag: \"<<testFlag_local<<endl;\n\n    int oriTestIndex = testIndex_local;\n    for (int m = 0; m < oriTestIndex; ++m)\n    {\n        if (rmIndex[m]==1)\n        {\n            testIndex_local--;\n        }\n    }\n\n    for (int i = 0; i < rowNum_fun; ++i)\n    {\n        vector<double> tempVec;\n        for (int j = 0; j < colNum_fun; ++j)\n        {\n            if (rmIndex[j]!=1)\n            {\n                tempVec.push_back(distMatrix_local[i][j]);\n            }\n        }\n        distMatRmDep_local.push_back(tempVec);\n    }\n\n    return testFlag_local;\n}\n\n\n\n\nint calStanScores(vector< vector<double> >& distMatrix_std_fun)\n{\n    for (vector< vector<double> >::iterator colIt = distMatrix_std_fun.begin(), colIt_end = distMatrix_std_fun.end(); colIt != colIt_end; ++colIt) //colomn as in original matrix before transpose\n    {\n        int rowNum_fun = colIt->size();\n        double sum = 0.0;\n        for (vector<double>::const_iterator rowIt = colIt->begin(), rowIt_end = colIt->end(); rowIt != rowIt_end; ++rowIt)\n        {\n            sum += *rowIt;\n        }\n        double mean = sum / rowNum_fun;\n\n        double var = 0.0;\n        for (vector<double>::const_iterator rowIt = colIt->begin(), rowIt_end = colIt->end(); rowIt != rowIt_end; ++rowIt)\n        {\n            double diff = *rowIt - mean;\n            var += diff * diff;\n        }\n        var = var / (rowNum_fun - 1);\n        double std = sqrt(var);\n\n        for (vector<double>::iterator rowIt = colIt->begin(), rowIt_end = colIt->end(); rowIt != rowIt_end; ++rowIt)\n        {\n            *rowIt = (*rowIt - mean) / std;\n        }\n    }\n\n    return 0;\n}\n\n\n\n\nint calPearsonCorr(vector< vector<double> >& distMatrix_std_fun, vector< pair<int, int> >& oriCoor_fun, const double& thres_fun, int testIndex_fun, map<int, int>& rmIndex_fun)\n{\n    int sigNum = 0;\n\n    map< pair<int, int>, double > corrMap_fun;\n    vector<double> xyCorr;\n    int colNum_fun = distMatrix_std_fun.size(); // colomn as in original matrix\n    int rowNum_fun = (distMatrix_std_fun.begin())->size();\n    int freedom = rowNum_fun - 1;\n    for (int i = 0; i < colNum_fun; ++i)\n    {\n        for (int j = i+1; j < colNum_fun; ++j)\n        {\n            double pearsonCorr = 0.0;\n            for (int m = 0; m < rowNum_fun; ++m)\n            {\n                pearsonCorr += distMatrix_std_fun[i][m] * distMatrix_std_fun[j][m];\n            }\n            pearsonCorr /= freedom;\n\n            //if (pearsonCorr >= pos_thres || pearsonCorr <= neg_thres)\n\n            if (j==colNum_fun-1)\n            {\n                xyCorr.push_back(pearsonCorr);\n            }\n            else if (pearsonCorr >= thres_fun || pearsonCorr <= -thres_fun)\n            {\n                //cout<<pearsonCorr<<endl;\n                corrMap_fun[make_pair(i, j)] = pearsonCorr;\n            }\n        }\n    }\n\n    //string corrFile = \"corrFile\";\n    //writer_corrFile(corrMap_fun, corrFile);\n\n    for (map< pair<int, int>, double >::const_iterator sigIt = corrMap_fun.begin(), sigIt_end = corrMap_fun.end(); sigIt != sigIt_end; ++sigIt)\n    {\n        int col1 = sigIt->first.first, col2 = sigIt->first.second;\n        pair<int, int>& oriCol1 = oriCoor_fun[col1], oriCol2 = oriCoor_fun[col2];\n        cout<<testIndex_fun<<\"\\t\"<<col1<<\"\\t\"<<col2<<\"\\t\"<<oriCol1.first<<\"\\t\"<<oriCol1.second<<\"\\t\"<<xyCorr[col1]<<\"\\t\"<<oriCol2.first<<\"\\t\"<<oriCol2.second<<\"\\t\"<<xyCorr[col2]<<endl;\n\n        if(col1==testIndex_fun)\n        {\n            //if within the 3*3 square centered on the testing spot, there is a spot with higher freq than the testing spot, and this high freq spot has high corr with the testing spot, then skip the testing spot, since distMatrix_std_fun[colNum_fun-1][col1] is not the frequency of col1 (need the origin col1), use corr instead\n            if(abs(oriCol1.first-oriCol2.first)>1 || abs(oriCol1.second-oriCol2.second)>1 || xyCorr[col1]>=xyCorr[col2])\n            {\n                rmIndex_fun[col2] = 1;\n            }\n            else\n            {\n                return 0;\n            }\n        }\n        else if(col2==testIndex_fun)\n        {\n            if(abs(oriCol1.first-oriCol2.first)>1 || abs(oriCol1.second-oriCol2.second)>1 || xyCorr[col2]>=xyCorr[col1])\n            {\n                rmIndex_fun[col1] = 1;\n            }\n            else\n            {\n                return 0;\n            }\n        }\n        else\n        {\n            //always keep the one with higher positive correlation\n            //cout<<\"break 1\"<<endl;\n            rmIndex_fun[xyCorr[col1]>xyCorr[col2]?col2:col1] = 1;\n            //cout<<\"break 2\"<<endl;\n        }\n    }\n\n    return 1;\n}\n\n\n\n\nint writer_corrFile(map< pair<int, int>, double >& corrMap_local, string& fileName)\n{\n    ofstream outputFile(fileName.c_str());\n\n    for (map< pair<int, int>, double>::const_iterator corrIt = corrMap_local.begin(), corrIt_end = corrMap_local.end(); corrIt != corrIt_end; ++corrIt)\n    {\n        outputFile<<corrIt->first.first<<\"\\t\"<<corrIt->first.second<<\"\\t\"<<corrIt->second<<endl;\n    }\n    outputFile.close();\n\n    return 0;\n}\n\n\n\n\n#endif\n", "meta": {"hexsha": "928c5a36d411da53fb47f83715fbbc12e072452d", "size": 32128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/4_Find_IntraDomain_Interaction/calEffBetas/beforeGLM/calEffBetas.cpp", "max_stars_repo_name": "Lan-lab/Chrom-Lasso-", "max_stars_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40", "max_stars_repo_licenses": ["MIT"], "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/4_Find_IntraDomain_Interaction/calEffBetas/beforeGLM/calEffBetas.cpp", "max_issues_repo_name": "Lan-lab/Chrom-Lasso-", "max_issues_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40", "max_issues_repo_licenses": ["MIT"], "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/4_Find_IntraDomain_Interaction/calEffBetas/beforeGLM/calEffBetas.cpp", "max_forks_repo_name": "Lan-lab/Chrom-Lasso-", "max_forks_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-15T09:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T02:16:27.000Z", "avg_line_length": 35.0742358079, "max_line_length": 336, "alphanum_fraction": 0.5291957171, "num_tokens": 8282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5148876447687208}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2021, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"opengl-precomp.h\"\t // Precompiled header\n//\n#include <mrpt/containers/yaml.h>\n#include <mrpt/math/geometry.h>\t // crossProduct3D()\n#include <mrpt/math/ops_containers.h>  // dotProduct()\n#include <mrpt/opengl/TRenderMatrices.h>\n\n#include <Eigen/Dense>\n\nusing namespace mrpt::opengl;\n\nvoid TRenderMatrices::computeOrthoProjectionMatrix(\n\tfloat left, float right, float bottom, float top, float znear, float zfar)\n{\n\tASSERT_GT_(zfar, znear);\n\tm_last_z_near = znear;\n\tm_last_z_far = zfar;\n\n\tp_matrix.setIdentity();\n\n\tp_matrix(0, 0) = 2.0f / (right - left);\n\tp_matrix(1, 1) = 2.0f / (top - bottom);\n\tp_matrix(2, 2) = -2.0f / (zfar - znear);\n\tp_matrix(0, 3) = -(right + left) / (right - left);\n\tp_matrix(1, 3) = -(top + bottom) / (top - bottom);\n\tp_matrix(2, 3) = -(zfar + znear) / (zfar - znear);\n}\n\n// Replacement for obsolete: gluPerspective() and glOrtho()\nvoid TRenderMatrices::computeProjectionMatrix(float znear, float zfar)\n{\n\tASSERT_GT_(FOV, .0f);\n\tASSERT_GT_(zfar, znear);\n\tASSERT_GT_(zfar, .0f);\n\tASSERT_GE_(znear, .0f);\n\n\tm_last_z_near = znear;\n\tm_last_z_far = zfar;\n\n\tif (pinhole_model.has_value())\n\t{\n\t\tconst auto& phm = pinhole_model.value();\n\n\t\t// Equivalent to gluPerspective(), from pinhole camera intrinsic\n\t\t// parameters (cx,cy,fx,fy):\n\t\tASSERT_EQUAL_(viewport_width, pinhole_model->ncols);\n\t\tASSERT_EQUAL_(viewport_height, pinhole_model->nrows);\n\n\t\tconst int W = pinhole_model->ncols, H = pinhole_model->nrows;\n\n\t\t// See: e.g.\n\t\t// http://ksimek.github.io/2013/06/03/calibrated_cameras_in_opengl/\n\t\tmrpt::math::CMatrixFloat44 persp;\n\t\tpersp.setZero();\n\n\t\tpersp(0, 0) = phm.fx();\n\t\tpersp(1, 1) = phm.fy();\n\n\t\tpersp(0, 2) = -phm.cx();\n\t\tpersp(1, 2) = -H + phm.cy();\n\t\tpersp(2, 2) = (zfar + znear);\n\t\tpersp(3, 2) = -1.0f;\n\t\tpersp(2, 3) = zfar * znear;\n\n\t\t// glOrtho(-W/2, W/2, -H/2, H/2, near, far);\n\n\t\tcomputeOrthoProjectionMatrix(\n\t\t\t0, W, 0 /*bottom*/, H /*top*/, znear, zfar);\n\n\t\t// glMultMatrix(persp);\n\t\tp_matrix.asEigen() *= persp.asEigen();\n\t}\n\telse if (is_projective)\n\t{\n\t\t// Was: gluPerspective()\n\t\t// Based on GLM's perspective (MIT license).\n\n\t\tconst float aspect = viewport_width / (1.0f * viewport_height);\n\t\tASSERT_GT_(\n\t\t\tstd::abs(aspect - std::numeric_limits<float>::epsilon()), .0f);\n\n\t\tconst float f = 1.0f / std::tan(mrpt::DEG2RAD(FOV) / 2.0f);\n\t\tp_matrix.setZero();\n\n\t\tp_matrix(0, 0) = f / aspect;\n\t\tp_matrix(1, 1) = f;\n\t\tp_matrix(2, 2) = -(zfar + znear) / (zfar - znear);\n\t\tp_matrix(3, 2) = -1.0f;\n\t\tp_matrix(2, 3) = -(2.0f * zfar * znear) / (zfar - znear);\n\t}\n\telse\n\t{\n\t\t// Was:\n\t\t// glOrtho(-Ax, Ax, -Ay, Ay, -0.5 * m_clip_max, 0.5 * m_clip_max);\n\n\t\tconst float ratio = viewport_width / (1.0f * viewport_height);\n\t\tfloat Ax = eyeDistance * 0.5f;\n\t\tfloat Ay = eyeDistance * 0.5f;\n\n\t\tif (ratio > 1) Ax *= ratio;\n\t\telse\n\t\t{\n\t\t\tif (ratio != 0) Ay /= ratio;\n\t\t}\n\n\t\tconst auto left = -.5f * Ax, right = .5f * Ax;\n\t\tconst auto bottom = -.5f * Ay, top = .5f * Ay;\n\t\tcomputeOrthoProjectionMatrix(left, right, bottom, top, znear, zfar);\n\t}\n}\n\n// Replacement for deprecated OpenGL gluLookAt():\nvoid TRenderMatrices::applyLookAt()\n{\n\tusing mrpt::math::TVector3D;\n\n\t// Note: Use double instead of float to avoid numerical innacuracies that\n\t// are really noticeable with the naked eye when elevation is close to 90\n\t// deg (!)\n\tTVector3D forward = TVector3D(pointing - eye);\n\tconst double fn = forward.norm();\n\tASSERT_(fn != 0);\n\tforward *= 1.0 / fn;\n\n\t// Side = forward x up\n\tTVector3D side = mrpt::math::crossProduct3D(forward, up);\n\tconst double sn = side.norm();\n\tASSERT_(sn != 0);\n\tside *= 1.0 / sn;\n\n\t// Recompute up as: up = side x forward\n\tconst TVector3D up2 = mrpt::math::crossProduct3D(side, forward);\n\n\t//  s.x   s.y   s.z  -dot(s, eye)\n\t//  u.x   u.y   u.z  -dot(u, eye)\n\t// -f.x  -f.y  -f.z  dot(up, eye)\n\t//   0     0     0      1\n\n\tmrpt::math::CMatrixFloat44 m(mrpt::math::UNINITIALIZED_MATRIX);\n\t// Axis X:\n\tm(0, 0) = d2f(side[0]);\n\tm(0, 1) = d2f(side[1]);\n\tm(0, 2) = d2f(side[2]);\n\t// Axis Y:\n\tm(1, 0) = d2f(up2[0]);\n\tm(1, 1) = d2f(up2[1]);\n\tm(1, 2) = d2f(up2[2]);\n\t// Axis Z:\n\tm(2, 0) = d2f(-forward[0]);\n\tm(2, 1) = d2f(-forward[1]);\n\tm(2, 2) = d2f(-forward[2]);\n\t// Translation:\n\tm(0, 3) = d2f(-mrpt::math::dotProduct<3, double>(side, eye));\n\tm(1, 3) = d2f(-mrpt::math::dotProduct<3, double>(up2, eye));\n\tm(2, 3) = d2f(mrpt::math::dotProduct<3, double>(forward, eye));\n\t// Last row:\n\tm(3, 0) = .0f;\n\tm(3, 1) = .0f;\n\tm(3, 2) = .0f;\n\tm(3, 3) = 1.f;\n\n\t// Homogeneous matrices composition:\n\t// Overwrite projection matrix:\n\tp_matrix.asEigen() = p_matrix.asEigen() * m.asEigen();\n}\n\nvoid TRenderMatrices::projectPoint(\n\tfloat x, float y, float z, float& proj_u, float& proj_v,\n\tfloat& proj_z_depth) const\n{\n\tconst Eigen::Matrix<float, 4, 1, Eigen::ColMajor> proj =\n\t\tpmv_matrix.asEigen() *\n\t\tEigen::Matrix<float, 4, 1, Eigen::ColMajor>(x, y, z, 1);\n\tproj_u = proj[3] ? proj[0] / proj[3] : 0;\n\tproj_v = proj[3] ? proj[1] / proj[3] : 0;\n\tproj_z_depth = proj[2];\n}\n\nvoid TRenderMatrices::projectPointPixels(\n\tfloat x, float y, float z, float& proj_u_px, float& proj_v_px,\n\tfloat& proj_depth) const\n{\n\tprojectPoint(x, y, z, proj_u_px, proj_v_px, proj_depth);\n\tproj_u_px = (proj_u_px + 1.0f) * (viewport_width * 0.5f);\n\tproj_v_px = (proj_v_px + 1.0f) * (viewport_height * 0.5f);\n}\n\nvoid TRenderMatrices::saveToYaml(mrpt::containers::yaml& c) const\n{\n\tc = mrpt::containers::yaml::Map();\n\n\tMCP_SAVE(c, initialized);\n\tMCP_SAVE(c, viewport_width);\n\tMCP_SAVE(c, viewport_height);\n\tMCP_SAVE(c, FOV);\n\tMCP_SAVE_DEG(c, azimuth);\n\tMCP_SAVE_DEG(c, elev);\n\tMCP_SAVE(c, eyeDistance);\n\tMCP_SAVE(c, is_projective);\n\n\tc[\"eye\"] = eye.asString();\n\tc[\"pointing\"] = pointing.asString();\n\tc[\"up\"] = up.asString();\n\n\tc[\"p_matrix\"] = mrpt::containers::yaml::FromMatrix(p_matrix);\n\tc[\"mv_matrix\"] = mrpt::containers::yaml::FromMatrix(mv_matrix);\n}\n\nvoid TRenderMatrices::print(std::ostream& o) const\n{\n\tmrpt::containers::yaml c;\n\tsaveToYaml(c);\n\to << c;\n}\n", "meta": {"hexsha": "b72eeb8346c7ee2c0b89d32e2daef268709e029e", "size": 6505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/opengl/src/TRenderMatrices.cpp", "max_stars_repo_name": "Russ76/mrpt", "max_stars_repo_head_hexsha": "4a59edd8b3250acea27fcb94bf8e29bee1ba8e1c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1372.0, "max_stars_repo_stars_event_min_datetime": "2015-07-25T00:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:55:33.000Z", "max_issues_repo_path": "libs/opengl/src/TRenderMatrices.cpp", "max_issues_repo_name": "Russ76/mrpt", "max_issues_repo_head_hexsha": "4a59edd8b3250acea27fcb94bf8e29bee1ba8e1c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 772.0, "max_issues_repo_issues_event_min_datetime": "2015-07-18T19:18:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T02:45:51.000Z", "max_forks_repo_path": "libs/opengl/src/TRenderMatrices.cpp", "max_forks_repo_name": "Russ76/mrpt", "max_forks_repo_head_hexsha": "4a59edd8b3250acea27fcb94bf8e29bee1ba8e1c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 588.0, "max_forks_repo_forks_event_min_datetime": "2015-07-23T01:13:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:05:40.000Z", "avg_line_length": 29.0401785714, "max_line_length": 80, "alphanum_fraction": 0.6075326672, "num_tokens": 2281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.514887644603783}}
{"text": "//\n// Copyright (c) 2018 CNRS\n//\n\n#include \"pinocchio/spatial/fwd.hpp\"\n#include \"pinocchio/algorithm/regressor.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/center-of-mass.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_static_regressor)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model; buildModels::humanoidRandom(model);\n  \n  pinocchio::Data data(model);\n  pinocchio::Data data_ref(model);\n  \n  model.lowerPositionLimit.head<7>().fill(-1.);\n  model.upperPositionLimit.head<7>().fill(1.);\n  \n  VectorXd q = randomConfiguration(model);\n  computeStaticRegressor(model,data,q);\n  \n  VectorXd phi(4*(model.njoints-1));\n  for(int k = 1; k < model.njoints; ++k)\n  {\n    const Inertia & Y = model.inertias[(size_t)k];\n    phi.segment<4>(4*(k-1)) << Y.mass(), Y.mass() * Y.lever();\n  }\n  \n  Vector3d com = centerOfMass(model,data_ref,q);\n  Vector3d static_com_ref;\n  static_com_ref <<  com;\n  \n  Vector3d static_com = data.staticRegressor * phi;\n  \n  BOOST_CHECK(static_com.isApprox(static_com_ref)); \n}\n\nBOOST_AUTO_TEST_CASE(test_body_regressor)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  Inertia I(Inertia::Random());\n  Motion v(Motion::Random());\n  Motion a(Motion::Random());\n\n  Force f = I*a + I.vxiv(v);\n\n  Inertia::Vector6 f_regressor = bodyRegressor(v,a) * I.toDynamicParameters();\n\n  BOOST_CHECK(f_regressor.isApprox(f.toVector()));\n}\n\nBOOST_AUTO_TEST_CASE(test_joint_body_regressor)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  buildModels::manipulator(model);\n  pinocchio::Data data(model);\n\n  JointIndex JOINT_ID = JointIndex(model.njoints) - 1;\n\n  VectorXd q = randomConfiguration(model);\n  VectorXd v = Eigen::VectorXd::Random(model.nv);\n  VectorXd a = Eigen::VectorXd::Random(model.nv);\n\n  rnea(model,data,q,v,a);\n\n  Force f = data.f[JOINT_ID];\n\n  Inertia::Vector6 f_regressor = jointBodyRegressor(model,data,JOINT_ID) * model.inertias[JOINT_ID].toDynamicParameters();\n\n  BOOST_CHECK(f_regressor.isApprox(f.toVector()));\n}\n\nBOOST_AUTO_TEST_CASE(test_frame_body_regressor)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  buildModels::manipulator(model);\n\n  JointIndex JOINT_ID = JointIndex(model.njoints) - 1;\n\n  const SE3 & framePlacement = SE3::Random();\n  FrameIndex FRAME_ID = (FrameIndex) model.addBodyFrame (\"test_body\", JOINT_ID, framePlacement, -1);\n\n  pinocchio::Data data(model);\n\n  VectorXd q = randomConfiguration(model);\n  VectorXd v = Eigen::VectorXd::Random(model.nv);\n  VectorXd a = Eigen::VectorXd::Random(model.nv);\n\n  rnea(model,data,q,v,a);\n\n  Force f = framePlacement.actInv(data.f[JOINT_ID]);\n  Inertia I = framePlacement.actInv(model.inertias[JOINT_ID]);\n\n  Inertia::Vector6 f_regressor = frameBodyRegressor(model,data,FRAME_ID) * I.toDynamicParameters();\n\n  BOOST_CHECK(f_regressor.isApprox(f.toVector()));\n}\n\nBOOST_AUTO_TEST_CASE(test_joint_torque_regressor)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  buildModels::humanoidRandom(model);\n\n  model.lowerPositionLimit.head<7>().fill(-1.);\n  model.upperPositionLimit.head<7>().fill(1.);\n\n  pinocchio::Data data(model);\n  pinocchio::Data data_ref(model);\n\n  VectorXd q = randomConfiguration(model);\n  VectorXd v = Eigen::VectorXd::Random(model.nv);\n  VectorXd a = Eigen::VectorXd::Random(model.nv);\n\n  rnea(model,data_ref,q,v,a);\n\n  Eigen::VectorXd params(10*(model.njoints-1));\n  for(JointIndex i=1; i<(Model::JointIndex)model.njoints; ++i)\n      params.segment<10>((int)((i-1)*10)) = model.inertias[i].toDynamicParameters();\n\n  computeJointTorqueRegressor(model,data,q,v,a);\n\n  Eigen::VectorXd tau_regressor = data.jointTorqueRegressor * params;\n\n  BOOST_CHECK(tau_regressor.isApprox(data_ref.tau));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "28cae9065f9bc8bd1f0b99b6a469adf9408e660f", "size": 4033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/regressor.cpp", "max_stars_repo_name": "ikalevatykh/pinocchio", "max_stars_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T07:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T07:23:34.000Z", "max_issues_repo_path": "unittest/regressor.cpp", "max_issues_repo_name": "ikalevatykh/pinocchio", "max_issues_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/regressor.cpp", "max_forks_repo_name": "ikalevatykh/pinocchio", "max_forks_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-25T13:34:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T13:34:37.000Z", "avg_line_length": 26.5328947368, "max_line_length": 122, "alphanum_fraction": 0.7329531366, "num_tokens": 1093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5148876390051998}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <cstdint>\n//#include <std_msgs/Float64.h> TODO use in place of double\n\nnamespace sel_map::mesh {\n    typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowArray_t;\n    typedef Eigen::Array<double, Eigen::Dynamic, 4, Eigen::RowMajor> PointWithCovArray_t;\n    typedef Eigen::Array<double, Eigen::Dynamic, 3, Eigen::RowMajor> PointArray_t;\n    typedef Eigen::Array<uint32_t, Eigen::Dynamic, 3, Eigen::RowMajor> IndexArray_t;\n    static const int AllPoints = -1;\n    static const int NoRadius = -1;\n    constexpr static const double defaultOrigin[2] = {0, 0};\n    static const RowArray_t NoPoints;\n}", "meta": {"hexsha": "4988fe819bf07a8d0ba7cd5824de0517f34e36e7", "size": 668, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sel_map_mesh/include/sel_map_mesh/Defs.hpp", "max_stars_repo_name": "roahmlab/sel_map", "max_stars_repo_head_hexsha": "51c5ac738eb7475f409f826c0d30f555f98757b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-02-24T21:10:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T20:00:09.000Z", "max_issues_repo_path": "sel_map_mesh/include/sel_map_mesh/Defs.hpp", "max_issues_repo_name": "roahmlab/sel_map", "max_issues_repo_head_hexsha": "51c5ac738eb7475f409f826c0d30f555f98757b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sel_map_mesh/include/sel_map_mesh/Defs.hpp", "max_forks_repo_name": "roahmlab/sel_map", "max_forks_repo_head_hexsha": "51c5ac738eb7475f409f826c0d30f555f98757b3", "max_forks_repo_licenses": ["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.75, "max_line_length": 93, "alphanum_fraction": 0.7275449102, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5148876334066164}}
{"text": "#include \"SchemeAlgo.h\"\n\n#include <NTL/BasicThreadPool.h>\n#include <NTL/ZZ.h>\n#include <cmath>\n#include <map>\n\n#include \"CZZ.h\"\n#include \"EvaluatorUtils.h\"\n#include \"Message.h\"\n#include \"Params.h\"\n#include \"SchemeAux.h\"\n#include \"SecKey.h\"\n\nCipher* SchemeAlgo::encryptSingleArray(CZZ*& vals, long size) {\n\tCipher* res = new Cipher[size];\n\tfor (long i = 0; i < size; ++i) {\n\t\tres[i] = scheme.encryptSingle(vals[i]);\n\t}\n\treturn res;\n}\n\nCZZ* SchemeAlgo::decryptSingleArray(SecKey& secretKey, Cipher*& ciphers, long size) {\n\tCZZ* res = new CZZ[size];\n\tfor (int i = 0; i < size; ++i) {\n\t\tMessage msg = scheme.decryptMsg(secretKey, ciphers[i]);\n\t\tCZZ* gvals = scheme.decode(msg);\n\t\tres[i] = gvals[0];\n\t}\n\treturn res;\n}\n\nCipher SchemeAlgo::powerOf2(Cipher& cipher, const long precisionBits, const long logDegree) {\n\tCipher res = cipher;\n\tfor (long i = 0; i < logDegree; ++i) {\n\t\tscheme.squareAndEqual(res);\n\t\tscheme.modSwitchAndEqual(res, precisionBits);\n\t}\n\treturn res;\n}\n\nCipher* SchemeAlgo::powerOf2Extended(Cipher& cipher, const long precisionBits, const long logDegree) {\n\tCipher* res = new Cipher[logDegree + 1];\n\tres[0] = cipher;\n\tfor (long i = 1; i < logDegree + 1; ++i) {\n\t\tres[i] = scheme.square(res[i-1]);\n\t\tscheme.modSwitchAndEqual(res[i], precisionBits);\n\t}\n\treturn res;\n}\n\n//-----------------------------------------\n\nCipher SchemeAlgo::power(Cipher& cipher, const long precisionBits, const long degree) {\n\tlong logDegree = log2(degree);\n\tlong po2Degree = 1 << logDegree;\n\n\tCipher res = powerOf2(cipher, precisionBits, logDegree);\n\tlong remDegree = degree - po2Degree;\n\tif(remDegree > 0) {\n\t\tCipher tmp = power(cipher, precisionBits, remDegree);\n\t\tlong bitsDown = tmp.cbits - res.cbits;\n\t\tscheme.modEmbedAndEqual(tmp, bitsDown);\n\t\tscheme.multAndEqual(res, tmp);\n\t\tscheme.modSwitchAndEqual(res, precisionBits);\n\t}\n\treturn res;\n}\n\nCipher* SchemeAlgo::powerExtended(Cipher& cipher, const long precisionBits, const long degree) {\n\tCipher* res = new Cipher[degree];\n\tlong logDegree = log2(degree);\n\tCipher* cpows = powerOf2Extended(cipher, precisionBits, logDegree);\n\tlong idx = 0;\n\tfor (long i = 0; i < logDegree; ++i) {\n\t\tlong powi = (1 << i);\n\t\tres[idx++] = cpows[i];\n\t\tfor (int j = 0; j < powi-1; ++j) {\n\t\t\tlong bitsDown = res[j].cbits - cpows[i].cbits;\n\t\t\tres[idx] = scheme.modEmbed(res[j], bitsDown);\n\t\t\tscheme.multAndEqual(res[idx], cpows[i]);\n\t\t\tscheme.modSwitchAndEqual(res[idx++], precisionBits);\n\t\t}\n\t}\n\tres[idx++] = cpows[logDegree];\n\tlong degree2 = (1 << logDegree);\n\tfor (int i = 0; i < (degree - degree2); ++i) {\n\t\tlong bitsDown = res[i].cbits - cpows[logDegree].cbits;\n\t\tres[idx] = scheme.modEmbed(res[i], bitsDown);\n\t\tscheme.multAndEqual(res[idx], cpows[logDegree]);\n\t\tscheme.modSwitchAndEqual(res[idx++], precisionBits);\n\t}\n\treturn res;\n}\n\n//-----------------------------------------\n\nCipher SchemeAlgo::prodOfPo2(Cipher*& ciphers, const long precisionBits, const long logDegree) {\n\tCipher* res = ciphers;\n\tfor (long i = logDegree - 1; i >= 0; --i) {\n\t\tlong powih = (1 << i);\n\t\tCipher* tmp = new Cipher[powih];\n\t\tNTL_EXEC_RANGE(powih, first, last);\n\t\tfor (long j = first; j < last; ++j) {\n\t\t\ttmp[j] = scheme.mult(res[2 * j], res[2 * j + 1]);\n\t\t\tscheme.modSwitchAndEqual(tmp[j], precisionBits);\n\t\t}\n\t\tNTL_EXEC_RANGE_END;\n\t\tres = tmp;\n\t}\n\treturn res[0];\n}\n\nCipher SchemeAlgo::prod(Cipher*& ciphers, const long precisionBits, const long degree) {\n\tlong logDegree = log2(degree) + 1;\n\tlong idx = 0;\n\tbool isinit = false;\n\tCipher res;\n\tfor (long i = 0; i < logDegree; ++i) {\n\t\tif(bit(degree, i)) {\n\t\t\tlong powi = (1 << i);\n\t\t\tCipher* tmp = new Cipher[powi];\n\t\t\tfor (long j = 0; j < powi; ++j) {\n\t\t\t\ttmp[j] = ciphers[idx + j];\n\t\t\t}\n\t\t\tCipher iprod = prodOfPo2(tmp, precisionBits, i);\n\t\t\tif(isinit) {\n\t\t\t\tlong bitsDown = res.cbits - iprod.cbits;\n\t\t\t\tscheme.modEmbedAndEqual(res, bitsDown);\n\t\t\t\tscheme.multAndEqual(res, iprod);\n\t\t\t\tscheme.modSwitchAndEqual(res, precisionBits);\n\t\t\t} else {\n\t\t\t\tres = iprod;\n\t\t\t\tisinit = true;\n\t\t\t}\n\t\t\tidx += powi;\n\t\t}\n\t}\n\treturn res;\n}\n\nCipher SchemeAlgo::sum(Cipher*& ciphers, const long size) {\n\tCipher res = ciphers[0];\n\tfor (long i = 1; i < size; ++i) {\n\t\tscheme.addAndEqual(res, ciphers[i]);\n\t}\n\treturn res;\n}\n\nCipher SchemeAlgo::distance(Cipher& cipher1, Cipher& cipher2, const long precisionBits) {\n\tCipher cres = scheme.sub(cipher1, cipher2);\n\tscheme.squareAndEqual(cres);\n\tscheme.modSwitchAndEqual(cres, precisionBits);\n\tpartialSlotsSumAndEqual(cres, cres.slots);\n\treturn cres;\n}\n\nCipher* SchemeAlgo::multVec(Cipher*& ciphers1, Cipher*& ciphers2, const long size) {\n\tCipher* res = new Cipher[size];\n\tNTL_EXEC_RANGE(size, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tres[i] = scheme.mult(ciphers1[i], ciphers2[i]);\n\t}\n\tNTL_EXEC_RANGE_END;\n\treturn res;\n}\n\nvoid SchemeAlgo::multAndEqualVec(Cipher*& ciphers1, Cipher*& ciphers2, const long size) {\n\tNTL_EXEC_RANGE(size, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tscheme.multAndEqual(ciphers1[i], ciphers2[i]);\n\t}\n\tNTL_EXEC_RANGE_END;\n}\n\n\nCipher* SchemeAlgo::multAndModSwitchVec(Cipher*& ciphers1, Cipher*& ciphers2, const long precisionBits, const long size) {\n\tCipher* res = new Cipher[size];\n\tNTL_EXEC_RANGE(size, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tres[i] = scheme.mult(ciphers1[i], ciphers2[i]);\n\t\tscheme.modSwitchAndEqual(res[i], precisionBits);\n\t}\n\tNTL_EXEC_RANGE_END;\n\treturn res;\n}\n\nvoid SchemeAlgo::multModSwitchAndEqualVec(Cipher*& ciphers1, Cipher*& ciphers2, const long precisionBits, const long size) {\n\tNTL_EXEC_RANGE(size, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tscheme.multAndEqual(ciphers1[i], ciphers2[i]);\n\t\tscheme.modSwitchAndEqual(ciphers1[i], precisionBits);\n\t}\n\tNTL_EXEC_RANGE_END;\n}\n\nCipher SchemeAlgo::innerProd(Cipher*& ciphers1, Cipher*& ciphers2, const long precisionBits, const long size) {\n\tCipher cip = scheme.mult(ciphers1[size-1], ciphers2[size-1]);\n\n\tNTL_EXEC_RANGE(size-1, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tCipher cprodi = scheme.mult(ciphers1[i], ciphers2[i]);\n\t\tscheme.addAndEqual(cip, cprodi);\n\t}\n\tNTL_EXEC_RANGE_END;\n\n\tscheme.modSwitchAndEqual(cip, precisionBits);\n\treturn cip;\n}\n\nCipher SchemeAlgo::partialSlotsSum(Cipher& cipher, const long slots) {\n\tlong logslots = log2(slots);\n\tCipher res = cipher;\n\tfor (long i = 0; i < logslots; ++i) {\n\t\tCipher rot = scheme.leftRotateByPo2(cipher, i);\n\t\tscheme.addAndEqual(res, rot);\n\t}\n\treturn res;\n}\n\nvoid SchemeAlgo::partialSlotsSumAndEqual(Cipher& cipher, const long slots) {\n\tlong logslots = log2(slots);\n\tfor (long i = 0; i < logslots; ++i) {\n\t\tCipher rot = scheme.leftRotateByPo2(cipher, i);\n\t\tscheme.addAndEqual(cipher, rot);\n\t}\n}\n\n//-----------------------------------------\n\nCipher SchemeAlgo::inverse(Cipher& cipher, const long precisionBits, const long steps) {\n\tZZ precision = power2_ZZ(precisionBits);\n\tCipher cpow = cipher;\n\tCipher tmp = scheme.addConst(cipher, precision);\n\tscheme.modEmbedAndEqual(tmp, precisionBits);\n\tCipher res = tmp;\n\n\tfor (long i = 1; i < steps; ++i) {\n\t\tscheme.squareAndEqual(cpow);\n\t\tscheme.modSwitchAndEqual(cpow, precisionBits);\n\t\ttmp = cpow;\n\t\tscheme.addConstAndEqual(tmp, precision);\n\t\tscheme.multAndEqual(tmp, res);\n\t\tscheme.modSwitchAndEqual(tmp, precisionBits);\n\t\tres = tmp;\n\t}\n\treturn res;\n}\n\nCipher* SchemeAlgo::inverseExtended(Cipher& cipher, const long precisionBits, const long steps) {\n\tZZ precision = power2_ZZ(precisionBits);\n\n\tCipher* res = new Cipher[steps];\n\tCipher cpow = cipher;\n\tCipher tmp = scheme.addConst(cipher, precision);\n\tscheme.modEmbedAndEqual(tmp, precisionBits);\n\tres[0] = tmp;\n\n\tfor (long i = 1; i < steps; ++i) {\n\t\tscheme.squareAndEqual(cpow);\n\t\tscheme.modSwitchAndEqual(cpow, precisionBits);\n\t\ttmp = cpow;\n\t\tscheme.addConstAndEqual(tmp, precision);\n\t\tscheme.multAndEqual(tmp, res[i - 1]);\n\t\tscheme.modSwitchAndEqual(tmp, precisionBits);\n\t\tres[i] = tmp;\n\t}\n\treturn res;\n}\n\n//-----------------------------------------\n\nCipher SchemeAlgo::function(Cipher& cipher, string& funcName, const long precisionBits, const long degree) {\n\tCipher* cpows = powerExtended(cipher, precisionBits, degree);\n\n\tlong dprecisionBits = 2 * precisionBits;\n\n\tdouble* coeffs = scheme.aux.taylorCoeffsMap.at(funcName);\n\n\tZZ tmp = EvaluatorUtils::evaluateVal(coeffs[1], precisionBits);\n\tCipher res = scheme.multByConst(cpows[0], tmp);\n\n\ttmp = EvaluatorUtils::evaluateVal(coeffs[0], dprecisionBits);\n\tscheme.addConstAndEqual(res, tmp);\n\n\tfor (int i = 1; i < degree; ++i) {\n\t\tif(abs(coeffs[i + 1]) > 1e-27) {\n\t\t\ttmp = EvaluatorUtils::evaluateVal(coeffs[i + 1], precisionBits);\n\t\t\tCipher aixi = scheme.multByConst(cpows[i], tmp);\n\t\t\tlong bitsDown = res.cbits - aixi.cbits;\n\t\t\tscheme.modEmbedAndEqual(res, bitsDown);\n\t\t\tscheme.addAndEqual(res, aixi);\n\t\t}\n\t}\n\tscheme.modSwitchAndEqual(res, precisionBits);\n\treturn res;\n}\n\nCipher SchemeAlgo::functionLazy(Cipher& cipher, string& funcName, const long precisionBits, const long degree) {\n\tCipher* cpows = powerExtended(cipher, precisionBits, degree);\n\n\tlong dprecisionBits = 2 * precisionBits;\n\n\tdouble* coeffs = scheme.aux.taylorCoeffsMap.at(funcName);\n\n\tZZ tmp = EvaluatorUtils::evaluateVal(coeffs[1], precisionBits);\n\tCipher res = scheme.multByConst(cpows[0], tmp);\n\n\ttmp = EvaluatorUtils::evaluateVal(coeffs[0], dprecisionBits);\n\tscheme.addConstAndEqual(res, tmp);\n\n\tfor (int i = 1; i < degree; ++i) {\n\t\tif(abs(coeffs[i + 1]) > 1e-27) {\n\t\t\ttmp = EvaluatorUtils::evaluateVal(coeffs[i + 1], precisionBits);\n\t\t\tCipher aixi = scheme.multByConst(cpows[i], tmp);\n\t\t\tlong bitsDown = res.cbits - aixi.cbits;\n\t\t\tscheme.modEmbedAndEqual(res, bitsDown);\n\t\t\tscheme.addAndEqual(res, aixi);\n\t\t}\n\t}\n\treturn res;\n}\n\nCipher* SchemeAlgo::functionExtended(Cipher& cipher, string& funcName, const long precisionBits, const long degree) {\n\tCipher* cpows = powerExtended(cipher, precisionBits, degree);\n\n\tlong dprecisionBits = 2 * precisionBits;\n\tdouble* coeffs = scheme.aux.taylorCoeffsMap.at(funcName);\n\n\tZZ tmp = EvaluatorUtils::evaluateVal(coeffs[1], precisionBits);\n\tCipher aixi = scheme.multByConst(cpows[0], tmp);\n\n\ttmp = EvaluatorUtils::evaluateVal(coeffs[0], dprecisionBits);\n\tscheme.addConstAndEqual(aixi, tmp);\n\n\tCipher* res = new Cipher[degree];\n\tres[0] = aixi;\n\tfor (long i = 1; i < degree; ++i) {\n\t\tif(abs(coeffs[i + 1]) > 1e-27) {\n\t\t\ttmp = EvaluatorUtils::evaluateVal(coeffs[i + 1], precisionBits);\n\t\t\taixi = scheme.multByConst(cpows[i], tmp);\n\t\t\tlong bitsDown = res[i - 1].cbits - aixi.cbits;\n\t\t\tCipher ctmp = scheme.modEmbed(res[i - 1], bitsDown);\n\t\t\tscheme.addAndEqual(aixi, ctmp);\n\t\t\tres[i] = aixi;\n\t\t} else {\n\t\t\tres[i] = res[i - 1];\n\t\t}\n\t}\n\tNTL_EXEC_RANGE(degree, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tscheme.modSwitchAndEqual(res[i], precisionBits);\n\t}\n\tNTL_EXEC_RANGE_END;\n\treturn res;\n}\n\nvoid SchemeAlgo::fftRaw(Cipher*& ciphers, const long size, const bool isForward) {\n\tfor (long i = 1, j = 0; i < size; ++i) {\n\t\tlong bit = size >> 1;\n\t\tfor (; j >= bit; bit>>=1) {\n\t\t\tj -= bit;\n\t\t}\n\t\tj += bit;\n\t\tif(i < j) {\n\t\t\tswap(ciphers[i], ciphers[j]);\n\t\t}\n\t}\n\n\tfor (long len = 2; len <= size; len <<= 1) {\n\t\tlong shift = isForward ? ((scheme.params.N / len) << 1) : ((scheme.params.N - scheme.params.N / len) << 1);\n\t\tfor (long i = 0; i < size; i += len) {\n\t\t\tNTL_EXEC_RANGE(len / 2, first, last);\n\t\t\tfor (long j = first; j < last; ++j) {\n\t\t\t\tCipher u = ciphers[i + j];\n\t\t\t\tscheme.multByMonomialAndEqual(ciphers[i + j + len / 2], shift * j);\n\t\t\t\tscheme.addAndEqual(ciphers[i + j], ciphers[i + j + len / 2]);\n\t\t\t\tscheme.subAndEqual2(u, ciphers[i + j + len / 2]);\n\t\t\t}\n\t\t\tNTL_EXEC_RANGE_END;\n\t\t}\n\t}\n}\n\nvoid SchemeAlgo::fft(Cipher*& ciphers, const long size) {\n\tfftRaw(ciphers, size, true);\n}\n\nvoid SchemeAlgo::fftInv(Cipher*& ciphers, const long size) {\n\tfftRaw(ciphers, size, false);\n\tlong logsize = log2(size);\n\n\tNTL_EXEC_RANGE(size, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tscheme.modSwitchAndEqual(ciphers[i], logsize);\n\t}\n\tNTL_EXEC_RANGE_END;\n}\n\nvoid SchemeAlgo::fftInvLazy(Cipher*& ciphers, const long size) {\n\treturn fftRaw(ciphers, size, false);\n}\n", "meta": {"hexsha": "e3191fd7461d77009fb659b6899feb8542d31af7", "size": 11927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SchemeAlgo.cpp", "max_stars_repo_name": "K-miran/HELR", "max_stars_repo_head_hexsha": "c94951f2691d55defc82f95d3144c831eb6c8796", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:56:15.000Z", "max_issues_repo_path": "src/SchemeAlgo.cpp", "max_issues_repo_name": "yuejiayang/HELR", "max_issues_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-25T02:54:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-09T10:48:39.000Z", "max_forks_repo_path": "src/SchemeAlgo.cpp", "max_forks_repo_name": "yuejiayang/HELR", "max_forks_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-01-20T13:31:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T02:20:39.000Z", "avg_line_length": 29.5955334988, "max_line_length": 124, "alphanum_fraction": 0.6735977195, "num_tokens": 3674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.5148785134947028}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Shape\n\n// #include <iostream>\n\n#include <random>\n#include <boost/test/unit_test.hpp>\n#include <geomc/function/Utils.h>\n#include <geomc/shape/Oriented.h>\n#include <geomc/shape/Cylinder.h>\n#include <geomc/shape/Simplex.h>\n#include <geomc/shape/Sphere.h>\n#include <geomc/shape/Extrusion.h>\n#include <geomc/shape/Frustum.h>\n\n\nusing namespace geom;\nusing namespace std;\n\n\ntypedef std::mt19937_64 rng_t;\n\n// todo: tests:\n//   - move a small distance away from a support point, both toward and away\n//     from the object, and check for expected result of shape.contains()\n//   - test that op(xf * shape, p) == op(shape, p / xf) for all {xf, p, shape, op}\n\n// todo: test Frustum<Rect<T,1>>\n\nrng_t rng(18374691138699945602ULL);\n\n\n/****************************\n * random number generation *\n ****************************/\n\n\ntemplate <typename T, index_t N>\nVec<T,N> rnd(rng_t* rng) {\n    std::normal_distribution<T> gauss(0, 1);\n    Vec<T,N> v;\n    for (index_t i = 0; i < N; ++i) {\n        v[i] = gauss(*rng);\n    }\n    return v;\n}\n\ntemplate <typename T>\ninline T rnd(rng_t* rng) {\n    std::normal_distribution<T> gauss(0, 1);\n    return gauss(*rng);\n}\n\n\n/****************************\n * point sampling of shapes *\n ****************************/\n\n\ntemplate <typename Shape>\nstruct ShapeSampler {};\n\n\ntemplate <typename T, index_t N>\nstruct ShapeSampler<Simplex<T,N>> {\n    Simplex<T,N> shape;\n    \n    ShapeSampler(const Simplex<T,N>& s):shape(s) {}\n    \n    Vec<T,N> operator()(rng_t* rng) {\n        // algorithm from: https://projecteuclid.org/download/pdf_1/euclid.pjm/1102911301\n        // we pick barycentric coordinates and then normalize so they sum to 1.\n        std::exponential_distribution<T> e(1);\n        T s[N + 1];\n        T sum = 0;\n        for (index_t i = 0; i < N + 1; ++i) {\n            T xi = e(*rng);\n            s[i] = xi;\n            sum += xi;\n        }\n        Vec<T,N> p;\n        for (index_t i = 0; i < N + 1; ++i) {\n            T xi = s[i] / sum;\n            p += xi * shape.pts[i];\n        }\n        return p;\n    }\n};\n\n\ntemplate <typename T, index_t N>\nstruct ShapeSampler<Rect<T,N>> {\n    Rect<T,N> shape;\n    ShapeSampler(const Rect<T,N>& s):shape(s) {}\n    \n    Vec<T,N> operator()(rng_t* rng) {\n        std::uniform_real_distribution<T> u(0, 1);\n        Vec<T,N> p;\n        for (index_t i = 0; i < N; ++i) {\n            p[i] = shape.lo[i] + u(*rng) * (shape.hi[i] - shape.lo[i]);\n        }\n        return p;\n    }\n};\n\n\ntemplate <typename T, index_t N>\nstruct ShapeSampler<Sphere<T,N>> {\n    Sphere<T,N> shape;\n    ShapeSampler(const Sphere<T,N>& s):shape(s) {}\n    \n    Vec<T,N> operator()(rng_t* rng) {\n        std::uniform_real_distribution<T> u(0,1);\n        Vec<T,N> p = rnd<T,N>(rng).unit();\n        p = p * shape.r * std::pow(u(*rng), 1/(T)N) + shape.center;\n        return p;\n    }\n};\n\n\ntemplate <typename T, index_t N>\nstruct ShapeSampler<Cylinder<T,N>> {\n    Cylinder<T,N> shape;\n    Vec<T,N> bases[N];\n    \n    ShapeSampler(const Cylinder<T,N>& s):shape(s) {\n        bases[0] = s.p1 - s.p0;\n        nullspace(bases, 1, bases + 1);\n        orthonormalize(bases, N);\n    }\n    \n    Vec<T,N> operator()(rng_t* rng) {\n        std::uniform_real_distribution<T> u(0,1);\n        Vec<T,N-1> px = ShapeSampler<Sphere<T,N-1>>(Sphere<T,N-1>(shape.radius))(rng);\n        Vec<T,N> p = mix(u(*rng), shape.p0, shape.p1);\n        for (index_t i = 0; i < N - 1; ++i) {\n            p += bases[i + 1] * px[i];\n        }\n        return p;\n    }\n};\n\n\ntemplate <typename Shape>\nstruct ShapeSampler<Extrusion<Shape>> {\n    typedef typename Shape::elem_t T;\n    static constexpr size_t N = Shape::N + 1;\n    \n    Extrusion<Shape> shape;\n    ShapeSampler(const Extrusion<Shape>& s):shape(s) {}\n    \n    Vec<T,N> operator()(rng_t* rng) {\n        std::uniform_real_distribution<T> u(0,1);\n        Vec<T,N-1> p = ShapeSampler<Shape>(shape.base)(rng);\n        T h = (shape.height.hi - shape.height.lo) * u(*rng) + shape.height.lo;\n        return Vec<T,N>(p, h);\n    }\n};\n\n\ntemplate <typename Shape>\nstruct ShapeSampler<Frustum<Shape>> {\n    typedef typename Shape::elem_t T;\n    static constexpr size_t N = Shape::N + 1;\n    \n    Frustum<Shape> shape;\n    ShapeSampler(const Frustum<Shape>& s):shape(s) {}\n    \n    Vec<T,N> operator()(rng_t* rng) {\n        // i am not positive this logic is right, but at worst\n        // we just have a skewed sampling of our frustum\n        std::uniform_real_distribution<T> u(0,1);\n        Vec<T,N-1> p = ShapeSampler<Shape>(shape.base)(rng);\n        auto c_h = shape.clipped_height();\n        T v = std::sqrt(u(*rng));\n          v = (c_h.lo < 0) ? (1 - v) : v;\n        T h = (c_h.hi - c_h.lo) * v + c_h.lo;\n        return Vec<T,N>(h * p, h);\n    }\n};\n\n\ntemplate <typename Shape>\nstruct ShapeSampler<Oriented<Shape>> {\n    typedef typename Shape::elem_t T;\n    static constexpr size_t N = Shape::N;\n    \n    Oriented<Shape> shape;\n    ShapeSampler(const Oriented<Shape>& s):shape(s) {}\n    \n    Vec<T,N> operator()(rng_t* rng) {\n        return shape.xf * ShapeSampler<Shape>(shape.shape)(rng);\n    }\n};\n\n\n/****************************\n * random shape generation  *\n ****************************/\n\n\ntemplate <typename Shape>\nstruct RandomShape {};\n\ntemplate <typename T, index_t N>\nstruct RandomShape<Sphere<T,N>> {\n    static Sphere<T,N> rnd_shape(rng_t* rng) {\n        return Sphere<T,N>(10 * rnd<T,N>(rng), 5 * std::abs(rnd<T>(rng)));\n    }\n};\n\ntemplate <typename T, index_t N>\nstruct RandomShape<Cylinder<T,N>> {\n    static Cylinder<T,N> rnd_shape(rng_t* rng) {\n        // try not to be consistently centered on the origin:\n        Vec<T,N> tx = 10 * rnd<T,N>(rng);\n        return Cylinder<T,N>(\n            5 * rnd<T,N>(rng) + tx,\n            5 * rnd<T,N>(rng) + tx,\n            2 * std::abs(rnd<T>(rng)));\n    }\n};\n\ntemplate <typename T, index_t N>\nstruct RandomShape<Rect<T,N>> {\n    static Rect<T,N> rnd_shape(rng_t* rng) {\n        Vec<T,N> tx = 10* rnd<T,N>(rng);\n        return Rect<T,N>::spanning_corners(\n            5 * rnd<T,N>(rng) + tx,\n            5 * rnd<T,N>(rng) + tx\n        );\n    }\n};\n\ntemplate <typename T, index_t N>\nstruct RandomShape<Simplex<T,N>> {\n    static Simplex<T,N> rnd_shape(rng_t* rng) {\n        Simplex<T,N> s;\n        Vec<T,N> tx = 15 * rnd<T,N>(rng);\n        for (index_t i = 0; i <= N; ++i) {\n            s |= 5 * rnd<T,N>(rng) + tx;\n        }\n        return s;\n    }\n};\n\ntemplate <typename Shape>\nstruct RandomShape<Oriented<Shape>> {\n    typedef typename Shape::elem_t T;\n    static constexpr index_t N = Shape::N;\n    \n    static Oriented<Shape> rnd_shape(rng_t* rng) {\n        SimpleMatrix<T,N,N> mx;\n        for (index_t i = 0; i < N * N; ++i) {\n            mx.begin()[i] = 3 * rnd<T>(rng);\n        }\n        AffineTransform<T,N> xf = translation(10 * rnd<T,N>(rng)) * transformation(mx);\n        return Oriented<Shape>(RandomShape<Shape>::rnd_shape(rng), xf);\n    }\n};\n\ntemplate <typename Shape>\nstruct RandomShape<Frustum<Shape>> {\n    typedef typename Shape::elem_t T;\n    static constexpr index_t N = Shape::N;\n    \n    static Frustum<Shape> rnd_shape(rng_t* rng) {\n        return Frustum<Shape>(\n            RandomShape<Shape>::rnd_shape(rng),\n            Rect<T,1>::spanning_corners(\n                5 * rnd<T>(rng),\n                5 * rnd<T>(rng)\n            ));\n    }\n};\n\ntemplate <typename Shape>\nstruct RandomShape<Extrusion<Shape>> {\n    typedef typename Shape::elem_t T;\n    static constexpr index_t N = Shape::N;\n    \n    static Extrusion<Shape> rnd_shape(rng_t* rng) {\n        return Extrusion<Shape>(\n                RandomShape<Shape>::rnd_shape(rng),\n                Rect<T,1>::spanning_corners(\n                    5 * rnd<T>(rng),\n                    5 * rnd<T>(rng)\n                )\n            );\n    }\n};\n\n\n/****************************\n * shape calisthenics       *\n ****************************/\n\n\ntemplate <typename Shape, typename T, index_t N>\nvoid validate_plane(const Shape& s, const Vec<T,N>& p, const Vec<T,N>& n) {\n    Plane<T,N> pl = Plane<T,N>(n, s.convex_support(n));\n    BOOST_CHECK(pl.contains(p));\n}\n\n\ntemplate <typename Shape>\nbool validate_point(\n        rng_t* rng, \n        const Shape& s, \n        const Vec<typename Shape::elem_t,Shape::N>& p) {\n    typedef typename Shape::elem_t T;\n    constexpr index_t N = Shape::N;\n    if (s.contains(p)) {\n        // if the pt is in the shape, it should definitely be in the bbox.\n        BOOST_CHECK(s.bounds().contains(p));\n        // pick a random support direction. the point should be inside\n        // the bounds of the resultant plane.\n        validate_plane(s, p, rnd<T,N>(rng));\n        \n        // test all the cardinal axes as support directions. a valid point\n        // should come back, and the plane through it should still contain p.\n        // (sometimes cardinal axes can be perfectly aligned with faces\n        // and this degeneracy might be handled poorly).\n        Vec<T,N> a;\n        for (index_t i = 0; i < N; ++i) {\n            a[i] = 1;\n            validate_plane(s, p, a);\n            a[i] = -1;\n            validate_plane(s, p, a);\n            a[i] =  0;\n        }\n        return true;\n    }\n    return false;\n}\n\n\ntemplate <typename Shape>\nvoid exercise_shape(rng_t* rng, const Shape& s, index_t trials) {\n    typedef typename Shape::elem_t T;\n    constexpr index_t N = Shape::N;\n    auto sampler   = ShapeSampler<Shape>(s);\n    Rect<T,N> bbox = s.bounds();\n    // shrink the blob so that more of it falls inside the bbox:\n    Vec<T,N>  dims = bbox.dimensions() / 4;\n    Vec<T,N>     c = bbox.center();\n    \n    for (index_t i = 0; i < trials; ++i) {\n        // validate a point near the shape's bbox\n        validate_point<Shape>(rng, s, rnd<T,N>(rng) * dims + c);\n        // validate a point definitely in the shape\n        BOOST_CHECK(validate_point<Shape>(rng, s, sampler(rng)));\n        // validate a point near the origin\n        validate_point<Shape>(rng, s, rnd<T,N>(rng));\n    }\n}\n\n\ntemplate <typename Shape>\nvoid explore_shape(rng_t* rng, index_t shapes) {\n    for (index_t i = 0; i < shapes; ++i) {\n        Shape s = RandomShape<Shape>::rnd_shape(rng);\n        exercise_shape<Shape>(rng, s, 50);\n    }\n}\n\n\ntemplate <typename T, index_t N>\nvoid explore_simplex(rng_t* rng, index_t shapes) {\n    for (index_t i = 0; i < shapes; ++i) {\n        Simplex<T,N> splx = RandomShape<Simplex<T,N>>::rnd_shape(rng);\n        ShapeSampler<Simplex<T,N>> smp(splx);\n        for (index_t j = 0; j < 100; ++j) {\n            Vec<T,N> p = smp(rng);\n            BOOST_CHECK(splx.contains(p));\n        }\n    }\n}\n\ntemplate <typename T, index_t N>\nvoid test_simplex_projection(rng_t* rng, const Simplex<T,N>& s, index_t trials) {\n    auto bb   = s.bounds();\n    auto dims = bb.dimensions();\n    auto ctr  = bb.center();\n    // no degenerate boxes pls\n    for (index_t i = 0; i < N; ++i) {\n        if (dims[i] == 0) dims[i] = 1;\n    }\n    for (index_t i = 0; i < trials; ++i) {\n        Simplex<T,N> ss;\n        Vec<T,N> p  = rnd<T,N>(rng) * dims + ctr;\n        Vec<T,N> pp = s.project(p, &ss);\n        if (ss.n == N + 1) {\n            // `p` is inside a full-volume simplex.\n            // no points should have been excluded; \n            // the \"projected-to\" simplex should be the same as the original\n            BOOST_CHECK(ss == s);\n            // if the point projected to the simplex volume, it should definitely \n            // be contained by the simplex\n            BOOST_CHECK(ss.contains(p));\n            // the \"projected\" point should be precisely the original point\n            BOOST_CHECK_EQUAL(p, pp);\n        } else {\n            // the direction from the surface pt to the original point\n            // should be orthogonal to the simplex face\n            Vec<T,N> v = p - pp;\n            for (index_t j = 1; j < ss.n; ++j) {\n                Vec<T,N> b = ss.pts[j] - ss.pts[0];\n                BOOST_CHECK_SMALL(b.dot(v), 1e-5);\n            }\n            // the projected point should fall inside the face's bounds\n            BOOST_CHECK(ss.projection_contains(p));\n        }\n    }\n}\n\n\ntemplate <typename T, index_t N>\nvoid exercise_simplex_projection(rng_t* rng, index_t trials) {\n    for (index_t i = 0; i < trials; ++i) {\n        Simplex<T,N> s = RandomShape<Simplex<T,N>>::rnd_shape(rng);\n        std::uniform_int_distribution<> d(1,N+1);\n        s.n = d(*rng); // make the simplex have a random number of verts\n        test_simplex_projection(rng, s, 10);\n    }\n}\n\n\ntemplate <template <typename> class Outer, typename T>\nvoid explore_compound_shape(rng_t* rng, index_t shapes) {\n    explore_shape<Outer<Rect<T, 2>>>(rng, shapes);\n    explore_shape<Outer<Rect<T, 3>>>(rng, shapes);\n    explore_shape<Outer<Rect<T, 4>>>(rng, shapes);\n    explore_shape<Outer<Rect<T, 5>>>(rng, shapes);\n    \n    // explore_shape<Outer<Cylinder<T, 2>>>(rng, shapes); // [1]\n    explore_shape<Outer<Cylinder<T, 3>>>(rng, shapes);\n    explore_shape<Outer<Cylinder<T, 4>>>(rng, shapes);\n    explore_shape<Outer<Cylinder<T, 5>>>(rng, shapes);\n    explore_shape<Outer<Cylinder<T, 7>>>(rng, shapes);\n    \n    explore_shape<Outer<Sphere<T, 2>>>(rng, shapes);\n    explore_shape<Outer<Sphere<T, 3>>>(rng, shapes);\n    explore_shape<Outer<Sphere<T, 4>>>(rng, shapes);\n    explore_shape<Outer<Sphere<T, 5>>>(rng, shapes);\n    explore_shape<Outer<Sphere<T, 7>>>(rng, shapes);\n    \n    explore_shape<Outer<Simplex<T, 2>>>(rng, shapes);\n    explore_shape<Outer<Simplex<T, 3>>>(rng, shapes);\n    explore_shape<Outer<Simplex<T, 4>>>(rng, shapes);\n    explore_shape<Outer<Simplex<T, 5>>>(rng, shapes);\n    explore_shape<Outer<Simplex<T, 7>>>(rng, shapes);\n    \n    // [1] A valid construction, but not currently tested\n    // because the sampling code for Cylinder needs to\n    // draw from an N-1 sphere. When N=2, this is a line,\n    // which degenerates to a different point_t, and Sphere\n    // is not set up to work with N=1.\n}\n\n\n/****************************\n * test cases               *\n ****************************/\n\n\nBOOST_AUTO_TEST_SUITE(shape)\n\n\nBOOST_AUTO_TEST_CASE(validate_rect) {\n    explore_shape<Rect<double, 2>>(&rng, 1000);\n    explore_shape<Rect<double, 3>>(&rng, 1000);\n    explore_shape<Rect<double, 4>>(&rng, 1000);\n    explore_shape<Rect<double, 5>>(&rng, 1000);\n}\n\nBOOST_AUTO_TEST_CASE(validate_cylinder) {\n    explore_shape<Cylinder<double, 3>>(&rng, 1000);\n    explore_shape<Cylinder<double, 4>>(&rng, 1000);\n    explore_shape<Cylinder<double, 5>>(&rng, 1000);\n    explore_shape<Cylinder<double, 7>>(&rng, 1000);\n}\n\nBOOST_AUTO_TEST_CASE(validate_simplex) {\n    explore_shape<Simplex<double, 2>>(&rng, 1000);\n    explore_shape<Simplex<double, 3>>(&rng, 1000);\n    explore_shape<Simplex<double, 4>>(&rng, 1000);\n    explore_shape<Simplex<double, 5>>(&rng, 1000);\n    explore_shape<Simplex<double, 7>>(&rng, 1000);\n    // todo: also check that contains() and projection_contains(),\n    //       all agree about pt containment.\n}\n\nBOOST_AUTO_TEST_CASE(validate_sphere) {\n    explore_shape<Sphere<double, 2>>(&rng, 1000);\n    explore_shape<Sphere<double, 3>>(&rng, 1000);\n    explore_shape<Sphere<double, 4>>(&rng, 1000);\n}\n\n\nBOOST_AUTO_TEST_CASE(validate_extrusion) {\n    explore_compound_shape<Extrusion, double>(&rng, 250);\n}\n\nBOOST_AUTO_TEST_CASE(validate_oriented) {\n    explore_compound_shape<Oriented, double>(&rng, 250);\n}\n\nBOOST_AUTO_TEST_CASE(validate_frustum) {\n    explore_compound_shape<Frustum, double>(&rng, 250);\n}\n\nBOOST_AUTO_TEST_CASE(create_oriented_cylinder) {\n    // make a null-transformed oriented cylinder.\n    // (the cylinder defaults to unit radius and length along X)\n    auto ocyl = Oriented<Cylinder<double,3>>(Cylinder<double,3>());\n    // confirm that the Oriented delegates containment checking\n    BOOST_CHECK(ocyl.contains(Vec3d(0.5, 0, 0)));\n    // confirm the Oriented delegages convex_support\n    BOOST_CHECK_EQUAL(ocyl.convex_support(Vec3d(0.1, 1, 0)), Vec3d(1, 1, 0));\n    // rotate the thing 180 degrees\n    ocyl *= rotation(Vec3d(0, 0, 1), M_PI);\n    // confirm that wrapper applies the xf:\n    BOOST_CHECK(ocyl.contains(Vec3d(-0.5, 0, 0)));\n}\n\nBOOST_AUTO_TEST_CASE(orient_simple_shape) {\n    auto xf = translation(Vec3d(-5, 0, 0));\n    // confirm the operator works and its return type is correct:\n    Oriented<Cylinder<double,3>> ocyl = xf * Cylinder<double,3>();\n    // confirm the created wrapper applies the xf:\n    BOOST_CHECK(ocyl.contains(Vec3d(-4.5, 0, 0)));\n    // verify inheritance\n    Convex<double,3>* s = &ocyl;\n    s->convex_support(Vec3d(0.2,0.4,0.1));\n}\n\nBOOST_AUTO_TEST_CASE(simplex_projection) {\n    exercise_simplex_projection<double,2>(&rng, 1000);\n    exercise_simplex_projection<double,3>(&rng, 1000);\n    exercise_simplex_projection<double,4>(&rng, 1000);\n    exercise_simplex_projection<double,5>(&rng, 1000);\n    exercise_simplex_projection<double,7>(&rng, 1000);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "94cb00ac0efa0aef7ae07f052f4fade179df6254", "size": 16819, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "regression/shape.cpp", "max_stars_repo_name": "trbabb/geomc", "max_stars_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-07-22T20:33:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T00:16:16.000Z", "max_issues_repo_path": "regression/shape.cpp", "max_issues_repo_name": "trbabb/geomc", "max_issues_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-08-13T14:28:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-29T00:04:47.000Z", "max_forks_repo_path": "regression/shape.cpp", "max_forks_repo_name": "trbabb/geomc", "max_forks_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-10-03T10:30:55.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-06T18:14:18.000Z", "avg_line_length": 30.747714808, "max_line_length": 89, "alphanum_fraction": 0.5878470777, "num_tokens": 4724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5148785078695389}}
{"text": "\n/******************************************************************************\n\n  Principal component analysis implementation using the covariance method.\n\n  Copyright (c) 2012, 2013\n  Alexander Rukletsov <rukletsov@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 PCA_HPP_C2EA373C_F360_43BA_BACB_4B26B78759BE_\n#define PCA_HPP_C2EA373C_F360_43BA_BACB_4B26B78759BE_\n\n#include <vector>\n#include <algorithm>\n#include <functional>\n#include <stdexcept>\n#include <boost/tuple/tuple.hpp>\n#include <boost/array.hpp>\n#include <boost/assert.hpp>\n\n#include \"bo/core/vector.hpp\"\n#include \"bo/math/mean.hpp\"\n#include \"bo/math/blas_extensions.hpp\"\n#include \"bo/math/blas_conversions.hpp\"\n\nnamespace bo {\nnamespace math {\n\nusing namespace boost::numeric::ublas;\n\n// Performs PCA for the given data. Returns a tuple of eigenvalues and eigenvectors.\n// Implemented as a functor in order to store induced typedefs inside.\ntemplate <typename RealType, std::size_t Dim>\nstruct PCA\n{\n    typedef Vector<RealType, Dim> Sample;\n    typedef std::vector<Sample> Samples;\n\n    typedef RealType EigenValue;\n    typedef boost::array<EigenValue, Dim> EigenValues;\n    typedef Vector<RealType, Dim> EigenVector;\n    typedef boost::array<EigenVector, Dim> EigenVectors;\n    typedef boost::tuples::tuple<EigenValues, EigenVectors> Result;\n\n    Result operator() (Samples data)\n    {\n        typedef math::bounded_vector<RealType, Dim> BlasVector;\n        typedef std::vector<RealType> StdVector;\n        typedef math::bounded_matrix<RealType, Dim, Dim> Matrix;\n\n        // If the data is empty, PCA is meaningless.\n        if (data.size() == 0)\n            throw std::logic_error(\"PCA for an empty set is meaningless.\");\n\n        // Find the mean among the neighbours.\n        Sample mean_value = bo::math::mean(data);\n\n        // Calculate the deviations from mean.\n        std::transform(data.begin(), data.end(), data.begin(),\n                       std::bind2nd(std::minus<Sample>(), mean_value));\n\n        // Initialize covariance matrix.\n        Matrix covar_matrix = math::zero_matrix<RealType>(Dim);\n\n        // Iteratively compute the Dim x Dim covariance matrix (sample by sample).\n        for (typename Samples::const_iterator pt = data.begin(); pt != data.end(); ++pt)\n        {\n            BlasVector vect = math::from_bo_vector(*pt);\n            covar_matrix += math::outer_prod(vect, vect);\n        }\n\n        covar_matrix /= data.size();\n\n        // Get the eigenvectors of the covariance matrix.\n        StdVector covar_eigenvalues = math::eigen_symmetric(covar_matrix);\n        BOOST_ASSERT((covar_eigenvalues.size() == Dim) &&\n                     \"Eigenvalues count differs from samples' dimensions.\");\n\n        // Convert eigenvectors to the output format.\n        EigenValues eigenvalues;\n        std::copy(covar_eigenvalues.begin(), covar_eigenvalues.end(), eigenvalues.begin());\n\n        // Extract eignvectors from the columns of the updated covariance matrix and\n        // convert them to the output format.\n        EigenVectors eigenvectors;\n        for (std::size_t col_idx = 0; col_idx < Dim; ++col_idx)\n            eigenvectors[col_idx] = math::to_bo_vector(BlasVector(math::column(covar_matrix, col_idx)));\n\n        // Put eigenvalues and eigenvectors into a tuple and return.\n        return\n            boost::tuples::make_tuple(eigenvalues, eigenvectors);\n    }\n};\n\n} // namespace math\n} // namespace bo\n\n#endif // PCA_HPP_C2EA373C_F360_43BA_BACB_4B26B78759BE_\n", "meta": {"hexsha": "c189804b92255f5c40b12537185e322a53f4b8c2", "size": 4807, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/math/pca.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/pca.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/pca.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": 39.4016393443, "max_line_length": 104, "alphanum_fraction": 0.6879550655, "num_tokens": 1067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5148785021265961}}
{"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#include \"../include/stokes/assembly.hpp\"\n#include \"../include/incompNS/test_cases_factory.hpp\"\n#include \"../include/incompNS/coefficients.hpp\"\n#include \"../include/incompNS/observer.hpp\"\n#include \"../include/incompNS/utilities.hpp\"\n#include \"../include/uq/sampler/sampler.hpp\"\n\n\nTEST (IncompNSUtils, measureDivergenceQuadMesh)\n{\n    // config\n    std::string filename\n            = \"../config_files/unit_tests/\"\n              \"incompNS_svs.json\";\n    auto config = get_global_config(filename);\n\n    // mesh file\n    std::string base_mesh_dir(\"../meshes/\");\n    std::string sub_mesh_dir = config[\"mesh_dir\"];\n    const std::string mesh_dir = base_mesh_dir+sub_mesh_dir;\n    const std::string mesh_file\n            = mesh_dir+\"quad_mesh_l0.mesh\";\n    const int lx = config[\"level_x\"];\n\n    // test case\n    std::shared_ptr<IncompNSTestCases> testCase\n        = make_incompNS_test_case(config);\n\n    // mesh\n    std::shared_ptr<Mesh> mesh\n            = std::make_shared<Mesh>(mesh_file.c_str());\n    for (int k=0; k<lx; k++) {\n        mesh->UniformRefinement();\n    }\n\n    // FE spaces\n    int deg = config[\"deg_x\"];\n    int ndim = mesh->Dimension();\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(deg, ndim);\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(mesh.get(), hdiv_coll);\n\n    FiniteElementCollection *l2_coll\n            = new L2_FECollection(deg, ndim);\n    FiniteElementSpace *W_space\n            = new FiniteElementSpace(mesh.get(), l2_coll);\n\n    // Divergence operator\n    // \\int_{\\Omega} div(u_h) q_h d_{\\Omega}\n    MixedBilinearForm *div_form\n            = new MixedBilinearForm(R_space,\n                                    W_space);\n    ConstantCoefficient one(-1.0);\n    div_form->AddDomainIntegrator\n            (new VectorFEDivergenceIntegrator(one));\n    div_form->Assemble();\n    div_form->Finalize();\n    SparseMatrix *div = div_form->LoseMat();\n    delete div_form;\n\n    // velocity\n    std::shared_ptr <GridFunction> v\n            = std::make_shared<GridFunction>(R_space);\n    Sampler<Uniform> unifSampler(10, 1);\n    Vector omegas = unifSampler.generate_one_sample();\n    IncompNSInitialVelocityCoeff v0_coeff(testCase);\n    v0_coeff.SetTime(0);\n    v->ProjectCoefficient(v0_coeff);\n\n    double divVal = measure_divergence(div, v.get());\n\n    double TOL=1E-8;\n    ASSERT_LE(divVal, TOL);\n}\n\nTEST (IncompNSUtils, measureDivergenceTriMesh)\n{\n    // config\n    std::string filename\n            = \"../config_files/unit_tests/\"\n              \"incompNS_svs.json\";\n    auto config = get_global_config(filename);\n\n    // mesh file\n    std::string base_mesh_dir(\"../meshes/\");\n    std::string sub_mesh_dir = config[\"mesh_dir\"];\n    const std::string mesh_dir = base_mesh_dir+sub_mesh_dir;\n    const std::string mesh_file\n            = mesh_dir+\"tri_mesh_l0.mesh\";\n    const int lx = config[\"level_x\"];\n\n    // test case\n    std::shared_ptr<IncompNSTestCases> testCase\n        = make_incompNS_test_case(config);\n\n    // mesh\n    std::shared_ptr<Mesh> mesh\n            = std::make_shared<Mesh>(mesh_file.c_str());\n    for (int k=0; k<lx; k++) {\n        mesh->UniformRefinement();\n    }\n\n    // FE spaces\n    int deg = config[\"deg_x\"];\n    int ndim = mesh->Dimension();\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(deg, ndim);\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(mesh.get(), hdiv_coll);\n\n    FiniteElementCollection *l2_coll\n            = new L2_FECollection(deg, ndim);\n    FiniteElementSpace *W_space\n            = new FiniteElementSpace(mesh.get(), l2_coll);\n\n    // Divergence operator\n    // \\int_{\\Omega} div(u_h) q_h d_{\\Omega}\n    MixedBilinearForm *div_form\n            = new MixedBilinearForm(R_space,\n                                    W_space);\n    ConstantCoefficient one(-1.0);\n    div_form->AddDomainIntegrator\n            (new VectorFEDivergenceIntegrator(one));\n    div_form->Assemble();\n    div_form->Finalize();\n    SparseMatrix *div = div_form->LoseMat();\n    delete div_form;\n\n    // velocity\n    std::shared_ptr <GridFunction> v\n            = std::make_shared<GridFunction>(R_space);\n    Sampler<Uniform> unifSampler(10, 1);\n    Vector omegas = unifSampler.generate_one_sample();\n    IncompNSInitialVelocityCoeff v0_coeff(testCase);\n    v0_coeff.SetTime(0);\n    v->ProjectCoefficient(v0_coeff);\n\n    double divVal = measure_divergence(div, v.get());\n\n    double TOL=2E-5;\n    ASSERT_LE(divVal, TOL);\n}\n\n\nTEST (IncompNSUtils, divgFreeVelQuadMesh)\n{\n    // config\n    std::string filename\n            = \"../config_files/unit_tests/\"\n              \"incompNS_svs.json\";\n    auto config = get_global_config(filename);\n\n    // mesh file\n    std::string base_mesh_dir(\"../meshes/\");\n    std::string sub_mesh_dir = config[\"mesh_dir\"];\n    const std::string mesh_dir = base_mesh_dir+sub_mesh_dir;\n    const std::string mesh_file\n            = mesh_dir+\"quad_mesh_l0.mesh\";\n\n    // test case\n    std::shared_ptr<IncompNSTestCases> testCase\n        = make_incompNS_test_case(config);\n\n    // mesh\n    const int lx = config[\"level_x\"];\n    std::shared_ptr<Mesh> mesh\n            = std::make_shared<Mesh>(mesh_file.c_str());\n    for (int k=0; k<lx; k++) {\n        mesh->UniformRefinement();\n    }\n\n    // FE spaces\n    int deg = config[\"deg_x\"];\n    int ndim = mesh->Dimension();\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(deg, ndim);\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(mesh.get(), hdiv_coll);\n\n    FiniteElementCollection *l2_coll\n            = new L2_FECollection(deg, ndim);\n    FiniteElementSpace *W_space\n            = new FiniteElementSpace(mesh.get(), l2_coll);\n\n    // Divergence operator\n    // \\int_{\\Omega} div(u_h) q_h d_{\\Omega}\n    MixedBilinearForm *div_form\n            = new MixedBilinearForm(R_space,\n                                    W_space);\n    ConstantCoefficient one(-1.0);\n    div_form->AddDomainIntegrator\n            (new VectorFEDivergenceIntegrator(one));\n    div_form->Assemble();\n    div_form->Finalize();\n    SparseMatrix *div = div_form->LoseMat();\n    delete div_form;\n\n    // velocity\n    std::shared_ptr <GridFunction> v\n            = std::make_shared<GridFunction>(R_space);\n    Sampler<Uniform> unifSampler(10, 1);\n    Vector omegas = unifSampler.generate_one_sample();\n    IncompNSInitialVelocityCoeff v0_coeff(testCase);\n    testCase->set_perturbations(omegas);\n    v0_coeff.SetTime(0);\n    v->ProjectCoefficient(v0_coeff);\n\n    // oberver\n    std::shared_ptr<IncompNSObserver> observer\n            = std::make_shared<IncompNSObserver>\n            (config, lx);\n    //(*observer)(v);\n\n    double div_old = measure_divergence(div, v.get());\n    std::cout << \"Weak divergence before cleaning: \"\n              << div_old << std::endl;\n\n    // make divergence free\n    DivergenceFreeVelocity divFreeVel (config, mesh);\n    divFreeVel (v.get());\n    //(*observer)(v);\n\n    double div_new = measure_divergence(div, v.get());\n    std::cout << \"Weak divergence after cleaning: \"\n              << div_new << std::endl;\n\n    double TOL=1E-5;\n    ASSERT_LE(div_new, TOL);\n}\n\n\nTEST (IncompNSUtils, divgFreeVelTriMesh)\n{\n    // config\n    std::string filename\n            = \"../config_files/unit_tests/\"\n              \"incompNS_svs.json\";\n    auto config = get_global_config(filename);\n\n    // mesh file\n    std::string base_mesh_dir(\"../meshes/\");\n    std::string sub_mesh_dir = config[\"mesh_dir\"];\n    const std::string mesh_dir = base_mesh_dir+sub_mesh_dir;\n    const std::string mesh_file\n            = mesh_dir+\"tri_mesh_l0.mesh\";\n\n    // test case\n    std::shared_ptr<IncompNSTestCases> testCase\n        = make_incompNS_test_case(config);\n\n    // mesh\n    const int lx = config[\"level_x\"];\n    std::shared_ptr<Mesh> mesh\n            = std::make_shared<Mesh>(mesh_file.c_str());\n    for (int k=0; k<lx; k++) {\n        mesh->UniformRefinement();\n    }\n\n    // FE spaces\n    int deg = config[\"deg_x\"];\n    int ndim = mesh->Dimension();\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(deg, ndim);\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(mesh.get(), hdiv_coll);\n\n    FiniteElementCollection *l2_coll\n            = new L2_FECollection(deg, ndim);\n    FiniteElementSpace *W_space\n            = new FiniteElementSpace(mesh.get(), l2_coll);\n\n    // Divergence operator\n    // \\int_{\\Omega} div(u_h) q_h d_{\\Omega}\n    MixedBilinearForm *div_form\n            = new MixedBilinearForm(R_space,\n                                    W_space);\n    ConstantCoefficient one(-1.0);\n    div_form->AddDomainIntegrator\n            (new VectorFEDivergenceIntegrator(one));\n    div_form->Assemble();\n    div_form->Finalize();\n    SparseMatrix *div = div_form->LoseMat();\n    delete div_form;\n\n    // velocity\n    std::shared_ptr <GridFunction> v\n            = std::make_shared<GridFunction>(R_space);\n    Sampler<Uniform> unifSampler(10, 1);\n    Vector omegas = unifSampler.generate_one_sample();\n    IncompNSInitialVelocityCoeff v0_coeff(testCase);\n    testCase->set_perturbations(omegas);\n    v0_coeff.SetTime(0);\n    v->ProjectCoefficient(v0_coeff);\n\n    // oberver\n    std::shared_ptr<IncompNSObserver> observer\n            = std::make_shared<IncompNSObserver>\n            (config, lx);\n    //(*observer)(v);\n\n    double div_old = measure_divergence(div, v.get());\n    std::cout << \"Weak divergence before cleaning: \"\n              << div_old << std::endl;\n\n    // make divergence free\n    DivergenceFreeVelocity divFreeVel (config, mesh);\n    divFreeVel (v.get());\n    //(*observer)(v);\n\n    double div_new = measure_divergence(div, v.get());\n    std::cout << \"Weak divergence after cleaning: \"\n              << div_new << std::endl;\n\n    double TOL=1E-4;\n    ASSERT_LE(div_new, TOL);\n}\n\n\n// End of file\n", "meta": {"hexsha": "b6812283d4af9e8eff51024387cb39cd2eccf97b", "size": 9983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_divergence.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_divergence.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_divergence.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.8892215569, "max_line_length": 60, "alphanum_fraction": 0.6346789542, "num_tokens": 2566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.514878502126596}}
{"text": "#include <scitbx/random/boost_python/random.h>\n\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/poisson_distribution.hpp>\n\n\nnamespace scitbx { namespace random { namespace boost_python {\n\nnamespace {\n\n  struct uniform\n  {\n    typedef boost::uniform_real<double> wt;\n\n    static std::string name() { return \"uniform\"; }\n\n    static void wrap_specific(boost::python::class_<wt> &klass) {\n      using namespace boost::python;\n      klass\n        .def(init<double, double>((arg(\"min\"), arg(\"max\"))))\n        .add_property(\"min\", &wt::min)\n        .add_property(\"min\", &wt::min)\n      ;\n    }\n  };\n\n  struct normal\n  {\n    typedef boost::normal_distribution<double> wt;\n\n    static std::string name() { return \"normal\"; }\n\n    static void wrap_specific(boost::python::class_<wt> &klass) {\n      using namespace boost::python;\n      klass\n        .def(init<double, double>((arg(\"mean\") =0.,\n                                   arg(\"sigma\")=1.)))\n        .add_property(\"mean\", &wt::mean)\n        .add_property(\"sigma\", &wt::sigma)\n        ;\n    }\n  };\n\n  struct bernoulli\n  {\n    typedef boost::bernoulli_distribution<double> wt;\n\n    static std::string name() { return \"bernoulli\"; }\n\n    static void wrap_specific(boost::python::class_<wt> &klass) {\n      using namespace boost::python;\n      klass\n        .def(init<double>())\n        .add_property(\"p\", &wt::p)\n        ;\n    }\n  };\n\n  struct gamma\n  {\n    typedef boost::gamma_distribution<double> wt;\n\n    static std::string name() { return \"gamma\"; }\n\n    static void wrap_specific(boost::python::class_<wt> &klass) {\n      using namespace boost::python;\n      klass\n        .def(init<double, double>((arg(\"alpha\")=1.0,\n                                   arg(\"beta\")=1.0)))\n        .add_property(\"alpha\", &wt::alpha)\n        .add_property(\"beta\", &wt::beta)\n        ;\n    }\n  };\n\n  struct poisson\n  {\n    typedef boost::poisson_distribution<int,double> wt;\n\n    static std::string name() { return \"poisson\"; }\n\n    static void wrap_specific(boost::python::class_<wt> &klass) {\n      using namespace boost::python;\n      klass\n        .def(init<double>((arg(\"mean\")=1.0)))\n        .add_property(\"mean\", &wt::mean)\n        ;\n    }\n  };\n\n\n} // namespace <anonymous>\n\n  void wrap_random()\n  {\n    wrap_distribution_and_variate<uniform>();\n    wrap_distribution_and_variate<normal>();\n    wrap_distribution_and_variate<bernoulli>();\n    wrap_distribution_and_variate<gamma>();\n    wrap_distribution_and_variate<poisson>();\n  }\n\n}}} // namespace scitbx::random::boost_python\n", "meta": {"hexsha": "6d5e218f2b87911f0ca4b6437804906590aa5e44", "size": 2679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/random/boost_python/basic_distributions.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/random/boost_python/basic_distributions.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/random/boost_python/basic_distributions.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 25.0373831776, "max_line_length": 65, "alphanum_fraction": 0.6162747294, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5148784908762686}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <scorum/protocol/asset.hpp>\n#include <scorum/protocol/odds.hpp>\n\n#include <scorum/chain/betting/betting_math.hpp>\n\n#include \"defines.hpp\"\n\nnamespace betting_math_tests {\n\nusing namespace scorum::protocol;\nusing namespace scorum::chain;\n\nBOOST_AUTO_TEST_SUITE(betting_math_tests)\n\nSCORUM_TEST_CASE(extra_large_coefficient_big_gain_mismatch_test)\n{\n    const asset bet1_stake = ASSET_SCR(10000);\n    const asset bet2_stake = ASSET_SCR(90'000'000);\n\n    const odds bet1_odds(10000, 1);\n    const odds bet2_odds(10000, 9999);\n\n    const auto matched = calculate_matched_stake(bet1_stake, bet2_stake, bet1_odds, bet2_odds);\n\n    BOOST_CHECK_EQUAL(matched.bet1_matched.amount, 9000);\n    BOOST_CHECK_EQUAL(matched.bet2_matched.amount, bet2_stake.amount);\n}\n\nSCORUM_TEST_CASE(more_than_matched_check) // to catch and log exceptions in calculate_matched_stake\n{\n    const asset stake_my = ASSET_SCR(1e+9);\n    const asset stake_other = ASSET_SCR(2e+9);\n\n    const odds odds_my = odds(10, 1);\n    const odds odds_other = odds(10, 9);\n\n    BOOST_CHECK_EQUAL(stake_my * odds_my, ASSET_SCR(10'000'000'000));\n    BOOST_CHECK_EQUAL(stake_other * odds_other, ASSET_SCR(2'222'222'222));\n\n    BOOST_CHECK_EQUAL(odds_my.simplified(), odds_other.inverted());\n    BOOST_CHECK_EQUAL(odds_other.simplified(), odds_my.inverted());\n\n    auto matched = calculate_matched_stake(stake_my, stake_other, odds_my, odds_other);\n\n    BOOST_REQUIRE_EQUAL(matched.bet1_matched.amount.value, 222'222'222);\n}\n\nSCORUM_TEST_CASE(less_than_matched_check)\n{\n    const asset stake_my = ASSET_SCR(0.1e+9);\n    const asset stake_other = ASSET_SCR(2e+9);\n\n    const odds odds_my = odds(10, 1);\n    const odds odds_other = odds(10, 9);\n\n    BOOST_CHECK_EQUAL(stake_my * odds_my, ASSET_SCR(1'000'000'000));\n    BOOST_CHECK_EQUAL(stake_other * odds_other, ASSET_SCR(2'222'222'222));\n\n    auto matched = calculate_matched_stake(stake_my, stake_other, odds_my, odds_other);\n\n    BOOST_REQUIRE_EQUAL(matched.bet2_matched.amount.value, 900'000'000);\n}\n\nSCORUM_TEST_CASE(equal_matched_check)\n{\n    const asset stake_my = ASSET_SCR(1e+9);\n    const asset stake_other = ASSET_SCR(9e+9);\n\n    const odds odds_my = odds(10, 1);\n    const odds odds_other = odds(10, 9);\n\n    BOOST_CHECK_EQUAL(stake_my * odds_my, stake_other * odds_other);\n\n    auto matched = calculate_matched_stake(stake_my, stake_other, odds_my, odds_other);\n\n    BOOST_REQUIRE_EQUAL(matched.bet1_matched, stake_my);\n\n    matched = calculate_matched_stake(stake_other, stake_my, odds_other, odds_my);\n\n    BOOST_REQUIRE_EQUAL(matched.bet1_matched, stake_other);\n}\n\nSCORUM_TEST_CASE(calculate_matched_stake_negative_check)\n{\n    BOOST_CHECK_THROW(calculate_matched_stake(ASSET_SCR(1e+9), ASSET_SP(9e+9), odds(10, 1), odds(10, 9)),\n                      fc::assert_exception);\n    BOOST_CHECK_THROW(calculate_matched_stake(ASSET_SP(1e+9), ASSET_SCR(9e+9), odds(10, 1), odds(10, 9)),\n                      fc::assert_exception);\n    BOOST_CHECK_THROW(calculate_matched_stake(ASSET_SP(1e+9), ASSET_SP(9e+9), odds(10, 1), odds(10, 9)),\n                      fc::assert_exception);\n\n    BOOST_CHECK_THROW(calculate_matched_stake(ASSET_SCR(1e+9), ASSET_SCR(9e+9), odds(10, 1), odds(10, 5)),\n                      fc::assert_exception);\n    BOOST_CHECK_THROW(calculate_matched_stake(ASSET_SCR(1e+9), ASSET_SCR(9e+9), odds(10, 5), odds(10, 9)),\n                      fc::assert_exception);\n}\n\nSCORUM_TEST_CASE(calculate_gain_positive_check)\n{\n    auto potential_profit = calculate_gain(ASSET_SCR(1e+9), odds(10, 1));\n\n    BOOST_CHECK_EQUAL(potential_profit, ASSET_SCR(9e+9));\n}\n\nSCORUM_TEST_CASE(min_bet_min_odds)\n{\n    const asset bet_stake = SCORUM_MIN_BET_STAKE;\n    const odds bet_odds = SCORUM_MIN_ODDS;\n\n    auto r1 = bet_stake * bet_odds;\n\n    BOOST_CHECK_EQUAL(1'001'000u, r1.amount);\n}\n\nSCORUM_TEST_CASE(min_bet_max_odds)\n{\n    const asset bet_stake = SCORUM_MIN_BET_STAKE;\n    const odds bet_odds = SCORUM_MIN_ODDS.inverted();\n\n    auto r1 = bet_stake * bet_odds;\n\n    BOOST_CHECK_EQUAL(1'001'000'000u, r1.amount);\n}\n\nSCORUM_TEST_CASE(calculate_potential_result)\n{\n    const asset bet_stake = asset::from_string(\"1000000.000000000 SCR\");\n    const odds bet_odds = SCORUM_MIN_ODDS.inverted();\n\n    auto result = bet_stake * bet_odds;\n\n    BOOST_CHECK_EQUAL(\"1001000000.000000000 SCR\", result.to_string());\n}\n\nSCORUM_TEST_CASE(calc_max_bet_stake)\n{\n    asset bet_stake(share_type::max(), SCORUM_SYMBOL);\n\n    BOOST_CHECK_EQUAL(\"9223372036.854775807 SCR\", bet_stake.to_string());\n\n    const odds bet_odds = SCORUM_MIN_ODDS.inverted();\n\n    auto result = bet_stake * bet_odds.base().coup();\n\n    BOOST_CHECK_EQUAL(SCORUM_MAX_BET_STAKE, result);\n}\n\nSCORUM_TEST_CASE(calc_potential_result_for_max_stake_max_odds)\n{\n    asset bet_stake = SCORUM_MAX_BET_STAKE;\n    const odds bet_odds = SCORUM_MIN_ODDS.inverted();\n\n    auto result = bet_stake * bet_odds;\n\n    BOOST_CHECK_EQUAL(\"9223372036.854775800 SCR\", result.to_string());\n}\n\nSCORUM_TEST_CASE(calculate_matched_stake_for_max_stake_max_odds)\n{\n    asset bet1_stake = SCORUM_MAX_BET_STAKE;\n    const odds bet1_odds = SCORUM_MIN_ODDS.inverted();\n\n    asset bet2_stake = bet1_stake * bet1_odds - bet1_stake;\n    odds bet2_odds = SCORUM_MIN_ODDS;\n\n    std::cout << bet2_stake.to_string() << std::endl;\n\n    auto matched = calculate_matched_stake(bet1_stake, bet2_stake, bet1_odds, bet2_odds);\n\n    BOOST_CHECK_EQUAL(bet1_stake, matched.bet1_matched);\n    BOOST_CHECK_EQUAL(bet2_stake, matched.bet2_matched);\n}\n\nSCORUM_TEST_CASE(calculate_matched_stake_throw_exception_when_potential_result_is_to_big)\n{\n    asset bet1_stake = SCORUM_MAX_BET_STAKE + 10;\n    const odds bet1_odds = SCORUM_MIN_ODDS.inverted();\n\n    asset bet2_stake = asset::from_string(\"9214157878.975800000 SCR\");\n    odds bet2_odds = SCORUM_MIN_ODDS;\n\n    SCORUM_CHECK_EXCEPTION(calculate_matched_stake(bet1_stake, bet2_stake, bet1_odds, bet2_odds),\n                           fc::underflow_exception, \"\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n}\n", "meta": {"hexsha": "5153fc663fef4a1a620c5564f3fd653376e1400d", "size": 6009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/utests/betting/betting_math_tests.cpp", "max_stars_repo_name": "scorum/scorum", "max_stars_repo_head_hexsha": "1da00651f2fa14bcf8292da34e1cbee06250ae78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2017-10-28T22:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T02:20:48.000Z", "max_issues_repo_path": "tests/utests/betting/betting_math_tests.cpp", "max_issues_repo_name": "Scorum/Scorum", "max_issues_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2017-11-25T09:06:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-31T09:17:22.000Z", "max_forks_repo_path": "tests/utests/betting/betting_math_tests.cpp", "max_forks_repo_name": "Scorum/Scorum", "max_forks_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2018-01-08T19:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T10:50:42.000Z", "avg_line_length": 31.6263157895, "max_line_length": 106, "alphanum_fraction": 0.7405558329, "num_tokens": 1752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5148224228307439}}
{"text": "#include <ros/ros.h>\n#include <iostream>\n#include <tagloc/algorithms.h>\n#include <tagloc/tracking.h>\n#include <Eigen/Dense>\n#include <math.h>\n#include <Eigen/Geometry>\n#include <vector>\n\ndouble Dei = 100;\ndouble sensor_var=pow((M_PI/12),2);\nusing namespace std;\ndouble zof(Eigen::MatrixXd T, Eigen::MatrixXd R){\n\tdouble nz = (rand()%100-50)/(100.0) * M_PI/(16);\n\treturn atan2(T(1)-R(1),T(0)-R(0))+nz;\n}\n//useful stuff\ndouble get_radius(Eigen::MatrixXd P){\n\tassert(P.rows()==P.cols());\n\tEigen::JacobiSVD<Eigen::MatrixXd> _svdA;\n\t_svdA.compute(P);\n\treturn sqrt(_svdA.singularValues()(0));\n}\nint main(int argc, char** argv){\n\tif (argc>1){\n\t\tDei = atof(argv[1]);\n\t\tsensor_var = atof(argv[2]);\n\t}\n\tstd::vector<double> px;\n\tstd::vector<double> py;\n\tstd::vector<double> Z;\n\tstd::vector<double> R;\n\tEigen::MatrixXd T(2,1);\n\tEigen::MatrixXd TT(2,1);\n\tT<< 0,0;\n\tTT<< 0,0;\n\tEigen::MatrixXd P = Eigen::MatrixXd::Identity(2,2) * 900.0;\n\tEigen::MatrixXd r1(2,1),r2(2,1);\n\tr1 << 200,20;\n\tr2 << 200,-20;\n\tint i=0;\n\twhile(get_radius(P)>sqrt(Dei)){\n\t\tcout<<\"\\t\\t\\ti:\"<<i++<<endl;\n\t\tpx.push_back(r1(0));\n\t\tpx.push_back(r2(0));\n\t\tpy.push_back(r1(1));\n\t\tpy.push_back(r2(1));\n\t\tR.push_back((sensor_var));\n\t\tR.push_back((sensor_var));\n\t\tZ.push_back(zof(TT,r1));\n\t\tZ.push_back(zof(TT,r2));\n\t\tdouble ti[2];\n\t\tdouble c[4];\n\t\tRSN::BOT::IWLS_2D(px.size(),px,py,Z,R,ti,c,false);\n\t\tT<<ti[0],ti[1];\n\t\tP<<c[0],c[1],c[2],c[3];\n\t\t//P=Eigen::MatrixXd::Identity(2,2)* 900.0;\n\t\tdouble rad = get_radius(P);\n\t\tcout<<\"--------------------\"<<endl;\n\t\tcout<<T<<endl;\n\t\tcout<<P<<endl;\n\t\tcout<<\"e1:\"<<rad<<endl;\n\t\tcout<<\"--------------------\"<<endl;\n\t\tRSN::onestep_circle(r1,r2,T,rad,(sensor_var),Dei);\n\t\tEigen::MatrixXd rot(2,2);\n\t\tdouble th =0; //M_PI/8;\n\t\trot(0,0)=cos(th);\n\t\trot(0,1)=-sin(th);\n\t\trot(1,0)=sin(th);\n\t\trot(1,1)=cos(th);\n\t\tr1 = rot * r1;\n\t\tr2 = rot * r2;\n\t}\n\tcout<<\"Got there in \"<<i<<endl;\n\tcout<<T<<endl;\n\t\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "3743c7b6b37a8cf67f5d75415e0a320fdb45d195", "size": 1905, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/twosteptest.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/twosteptest.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/twosteptest.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": 24.1139240506, "max_line_length": 60, "alphanum_fraction": 0.6052493438, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5148203093929143}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n\nclass LKF{\npublic:\n    LKF();\n    LKF(float init_pose_x, float init_pose_y);\n    LKF(Eigen::Matrix2f _H_k, Eigen::Matrix2f _Q_k, Eigen::Matrix2f _R_k, Eigen::Matrix2f _P_k_prev);\n    void set_init_pose(float init_pose_x, float init_pose_y);\n    Eigen::Vector2f run(float theta_t, Eigen::Vector2f u_k, Eigen::Vector2f z_k);\n    Eigen::Vector2f run_without_update(float theta_t, Eigen::Vector2f u_k);\n    void restore();\n    // u_k: control vector, z_k: observation vector\nprivate:\n    Eigen::Matrix2f H_k; // Scale Matrix\n    Eigen::Matrix2f Q_k; // Prediction Noise\n    Eigen::Matrix2f R_k; // Observation Noise\n    Eigen::Vector2f x_hat_k_prev; // Previous Value\n    Eigen::Matrix2f P_k_prev; // Previous Prediction Covariance Matrix\n    Eigen::Vector2f x_hat_k_prev_prev;\n    Eigen::Matrix2f P_k_prev_prev;\n};", "meta": {"hexsha": "c211d4311cd58b98ec7f1c80699e99e286aa4923", "size": 857, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "autoware.ai/src/autoware/core_perception/lidar_localizer/lib/LKF.hpp", "max_stars_repo_name": "Jihwan-Kimm/Autoware_On_Embedded", "max_stars_repo_head_hexsha": "dc45b70a355fdd26a65007e9c1d9246090f06373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "autoware.ai/src/autoware/core_perception/lidar_localizer/lib/LKF.hpp", "max_issues_repo_name": "Jihwan-Kimm/Autoware_On_Embedded", "max_issues_repo_head_hexsha": "dc45b70a355fdd26a65007e9c1d9246090f06373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "autoware.ai/src/autoware/core_perception/lidar_localizer/lib/LKF.hpp", "max_forks_repo_name": "Jihwan-Kimm/Autoware_On_Embedded", "max_forks_repo_head_hexsha": "dc45b70a355fdd26a65007e9c1d9246090f06373", "max_forks_repo_licenses": ["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.9545454545, "max_line_length": 101, "alphanum_fraction": 0.7257876313, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5148203058834379}}
{"text": "#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <boost/range/algorithm.hpp>\n#include <boost/integer/common_factor_rt.hpp>\n\nusing namespace std;\n\nint N;\nint main() {\n    while (cin >> N) {\n        int a[N], box[N], M = 0;\n        for (int i = 0; i < N; i++) {\n            cin >> a[i];\n        }\n        for (int i = N; i > 0; i--) {\n            int ball = a[i - 1];\n            for (int j = 2; i * j <= N; j++) {\n                // cout << \"DEBUG: i = \" << i << \", \" << (i * j - 1) << \", \" << box[i * j - 1] << endl;\n                ball += box[i * j - 1];\n            }\n            // cout << \"DEBUG: \" << i << \" \" << ball << endl;\n            if (ball % 2 == 1) {\n                box[i - 1] = 1;\n                M++;\n            } else {\n                box[i - 1] = 0;\n            }\n        }\n        cout << M << endl;\n        if (M != 0) {\n            for (int i = 0; i < N; i++) {\n                if (box[i] == 1) {\n                    cout << (i + 1) << \" \";\n                }\n            }\n            cout << endl;\n        }\n    }\n    return 0;\n}\n", "meta": {"hexsha": "5608edd5b0e076013295c9bf60e64e20735744db", "size": 1129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc134_d/Main.cpp", "max_stars_repo_name": "mizo0203/atcoder", "max_stars_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "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": "abc134_d/Main.cpp", "max_issues_repo_name": "mizo0203/atcoder", "max_issues_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "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": "abc134_d/Main.cpp", "max_forks_repo_name": "mizo0203/atcoder", "max_forks_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "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.0888888889, "max_line_length": 103, "alphanum_fraction": 0.3330380868, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5147924983300631}}
{"text": "#ifndef USE_CUDA\n\n#include <engine/Vectormath.hpp>\n#include <engine/Manifoldmath.hpp>\n#include <utility/Logging.hpp>\n#include <utility/Exception.hpp>\n\n#include <Eigen/Dense>\n\n#include <array>\n\nnamespace Engine\n{\n\tnamespace Manifoldmath\n\t{\n        scalar norm(const vectorfield & vf)\n        {\n            scalar x = Vectormath::dot(vf, vf);\n            return std::sqrt(x);\n        }\n\n        void normalize(vectorfield & vf)\n        {\n            scalar x = 1.0/norm(vf);\n            #pragma omp parallel for\n            for (unsigned int i = 0; i < vf.size(); ++i)\n                vf[i] *= x;\n        }\n\n        void project_parallel(vectorfield & vf1, const vectorfield & vf2)\n        {\n            vectorfield vf3 = vf1;\n            project_orthogonal(vf3, vf2);\n            // TODO: replace the loop with Vectormath Kernel\n            #pragma omp parallel for\n            for (unsigned int i = 0; i < vf1.size(); ++i)\n                vf1[i] -= vf3[i];\n        }\n\n        void project_orthogonal(vectorfield & vf1, const vectorfield & vf2)\n        {\n            scalar x = Vectormath::dot(vf1, vf2);\n            // TODO: replace the loop with Vectormath Kernel\n            #pragma omp parallel for\n            for (unsigned int i=0; i<vf1.size(); ++i)\n                vf1[i] -= x*vf2[i];\n        }\n\n        void invert_parallel(vectorfield & vf1, const vectorfield & vf2)\n        {\n            scalar x = Vectormath::dot(vf1, vf2);\n            // TODO: replace the loop with Vectormath Kernel\n            #pragma omp parallel for\n            for (unsigned int i=0; i<vf1.size(); ++i)\n                vf1[i] -= 2*x*vf2[i];\n        }\n        \n        void invert_orthogonal(vectorfield & vf1, const vectorfield & vf2)\n        {\n            vectorfield vf3 = vf1;\n            project_orthogonal(vf3, vf2);\n            // TODO: replace the loop with Vectormath Kernel\n            #pragma omp parallel for\n            for (unsigned int i = 0; i < vf1.size(); ++i)\n                vf1[i] -= 2 * vf3[i];\n        }\n\n        void project_tangential(vectorfield & vf1, const vectorfield & vf2)\n\t\t{\n            #pragma omp parallel for\n\t\t\tfor (unsigned int i = 0; i < vf1.size(); ++i)\n\t\t\t\tvf1[i] -= vf1[i].dot(vf2[i]) * vf2[i];\n\t\t}\n\n\n\t\tscalar dist_greatcircle(const Vector3 & v1, const Vector3 & v2)\n\t\t{\n\t\t\tscalar r = v1.dot(v2);\n\n\t\t\t// Prevent NaNs from occurring\n\t\t\tr = std::fmax(-1.0, std::fmin(1.0, r));\n\n\t\t\t// Greatcircle distance\n\t\t\treturn std::acos(r);\n\t\t}\n\n\n\t\tscalar dist_geodesic(const vectorfield & v1, const vectorfield & v2)\n\t\t{\n\t\t\tscalar dist = 0;\n            #pragma omp parallel for reduction(+:dist)\n\t\t\tfor (unsigned int i = 0; i < v1.size(); ++i)\n\t\t\t\tdist += pow(dist_greatcircle(v1[i], v2[i]), 2);\n\t\t\treturn sqrt(dist);\n\t\t}\n\n\t\t/*\n\t\tCalculates the 'tangent' vectors, i.e.in crudest approximation the difference between an image and the neighbouring\n\t\t*/\n\t\tvoid Tangents(std::vector<std::shared_ptr<vectorfield>> configurations, const std::vector<scalar> & energies, std::vector<vectorfield> & tangents)\n\t\t{\n\t\t\tint noi = configurations.size();\n\t\t\tint nos = (*configurations[0]).size();\n\n\t\t\tfor (int idx_img = 0; idx_img < noi; ++idx_img)\n\t\t\t{\n\t\t\t\tauto& image = *configurations[idx_img];\n\n\t\t\t\t// First Image\n\t\t\t\tif (idx_img == 0)\n\t\t\t\t{\n\t\t\t\t\tauto& image_plus = *configurations[idx_img + 1];\n\t\t\t\t\tVectormath::set_c_a( 1, image_plus, tangents[idx_img]);\n\t\t\t\t\tVectormath::add_c_a(-1, image,      tangents[idx_img]);\n\t\t\t\t}\n\t\t\t\t// Last Image\n\t\t\t\telse if (idx_img == noi - 1)\n\t\t\t\t{\n\t\t\t\t\tauto& image_minus = *configurations[idx_img - 1];\n\t\t\t\t\tVectormath::set_c_a( 1, image,       tangents[idx_img]);\n\t\t\t\t\tVectormath::add_c_a(-1, image_minus, tangents[idx_img]);\n\t\t\t\t}\n\t\t\t\t// Images Inbetween\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tauto& image_plus  = *configurations[idx_img + 1];\n\t\t\t\t\tauto& image_minus = *configurations[idx_img - 1];\n\n\t\t\t\t\t// Energies\n\t\t\t\t\tscalar E_mid = 0, E_plus = 0, E_minus = 0;\n\t\t\t\t\tE_mid   = energies[idx_img];\n\t\t\t\t\tE_plus  = energies[idx_img + 1];\n\t\t\t\t\tE_minus = energies[idx_img - 1];\n\n\t\t\t\t\t// Vectors to neighbouring images\n\t\t\t\t\tvectorfield t_plus(nos), t_minus(nos);\n\n\t\t\t\t\tVectormath::set_c_a( 1, image_plus, t_plus);\n\t\t\t\t\tVectormath::add_c_a(-1, image,      t_plus);\n\n\t\t\t\t\tVectormath::set_c_a( 1, image,       t_minus);\n\t\t\t\t\tVectormath::add_c_a(-1, image_minus, t_minus);\n\n\t\t\t\t\t// Near maximum or minimum\n\t\t\t\t\tif ((E_plus < E_mid && E_mid > E_minus) || (E_plus > E_mid && E_mid < E_minus))\n\t\t\t\t\t{\n\t\t\t\t\t\t// Get a smooth transition between forward and backward tangent\n\t\t\t\t\t\tscalar E_max = std::max(std::abs(E_plus - E_mid), std::abs(E_minus - E_mid));\n\t\t\t\t\t\tscalar E_min = std::min(std::abs(E_plus - E_mid), std::abs(E_minus - E_mid));\n\n\t\t\t\t\t\tif (E_plus > E_minus)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tVectormath::set_c_a(E_max, t_plus,  tangents[idx_img]);\n\t\t\t\t\t\t\tVectormath::add_c_a(E_min, t_minus, tangents[idx_img]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tVectormath::set_c_a(E_min, t_plus,  tangents[idx_img]);\n\t\t\t\t\t\t\tVectormath::add_c_a(E_max, t_minus, tangents[idx_img]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Rising slope\n\t\t\t\t\telse if (E_plus > E_mid && E_mid > E_minus)\n\t\t\t\t\t{\n\t\t\t\t\t\tVectormath::set_c_a(1, t_plus,  tangents[idx_img]);\n\t\t\t\t\t}\n\t\t\t\t\t// Falling slope\n\t\t\t\t\telse if (E_plus < E_mid && E_mid < E_minus)\n\t\t\t\t\t{\n\t\t\t\t\t\tVectormath::set_c_a(1, t_minus,  tangents[idx_img]);\n\t\t\t\t\t\t//tangents = t_minus;\n\t\t\t\t\t\tfor (int i = 0; i < nos; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttangents[idx_img][i] = t_minus[i];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// No slope(constant energy)\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tVectormath::set_c_a(1, t_plus,  tangents[idx_img]);\n\t\t\t\t\t\tVectormath::add_c_a(1, t_minus, tangents[idx_img]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Project tangents into tangent planes of spin vectors to make them actual tangents\n        \t\tproject_tangential(tangents[idx_img], image);\n\n\t\t\t\t// Normalise in 3N - dimensional space\n\t\t\t\tManifoldmath::normalize(tangents[idx_img]);\n\n\t\t\t}// end for idx_img\n\t\t}// end Tangents\n    }\n}\n\n#endif", "meta": {"hexsha": "fd25f3ead434bab5bb747324e20797792ae12451", "size": 5861, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/engine/Manifoldmath.cpp", "max_stars_repo_name": "SpiritSuperUser/spirit", "max_stars_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "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/src/engine/Manifoldmath.cpp", "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/src/engine/Manifoldmath.cpp", "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": 29.9030612245, "max_line_length": 148, "alphanum_fraction": 0.5794233066, "num_tokens": 1739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5147924983300631}}
{"text": "#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <fmt/format.h>\n#include <string>\n#include <iomanip>\n#include <boost/variant.hpp>\n#include <unordered_map>\n#include <cstdint>\n#include <vector>\nusing gint = std::int64_t;\nusing Coordinate = std::complex<gint>;\nenum Command {\n  TurnRight,\n  TurnLeft\n};\nclass Car\n{\n  std::complex<gint> pos_{ 0, 0 };\n  std::complex<gint> direction_{ 1, 0 };\n  std::complex<gint> turn_[2]{\n    { 0, -1 },\n    { 0, 1 }\n  };\n\npublic:\n  constexpr gint distance() const noexcept\n  {\n    return std::abs(pos_.real()) + std::abs(pos_.imag());\n  }\n\n  void process(Command command, gint value) noexcept\n  {\n    direction_ *= turn_[command];\n    pos_ += direction_ * value;\n  }\n};\n\n\nint main(int argc, char **argv)\n{\n  if (argc > 1) {\n    std::ifstream ifs(argv[1]);\n    char c;\n    int forward;\n    Car car;\n    Command com[256];\n    com['L'] = Command::TurnLeft;\n    com['R'] = Command::TurnRight;\n    while (ifs >> c >> forward) {\n      car.process(com[c], forward);\n    }\n    fmt::print(\"d:{}\\n\", car.distance());\n  }\n}", "meta": {"hexsha": "b6d008bf784db3d4d42c7363759c8580c9d71ed0", "size": 1080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc2016/aoc160101.cpp", "max_stars_repo_name": "jiayuehua/adventOfCode", "max_stars_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "aoc2016/aoc160101.cpp", "max_issues_repo_name": "jiayuehua/adventOfCode", "max_issues_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "aoc2016/aoc160101.cpp", "max_forks_repo_name": "jiayuehua/adventOfCode", "max_forks_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": 57, "alphanum_fraction": 0.6111111111, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6261241842048093, "lm_q1q2_score": 0.5147924931541645}}
{"text": "//----------------------------------*-C++-*----------------------------------//\n/**\n *  @file   CLP.cc\n *  @brief  CLP\n *  @author Jeremy Roberts\n *  @date   Jan 8, 2013\n */\n//---------------------------------------------------------------------------//\n\n#include \"CLP.hh\"\n#ifdef DETRAN_ENABLE_BOOST\n#include <boost/math/special_functions/legendre.hpp>\n#endif\n\nnamespace detran_orthog\n{\n\n//---------------------------------------------------------------------------//\nCLP::CLP(const size_t   order,\n         const vec_dbl &x,\n         const vec_dbl &qw,\n         const double   x_0,\n         const double   x_1)\n  : ContinuousOrthogonalBasis(order, x, qw)\n{\n#ifndef DETRAN_ENABLE_BOOST\n  THROW(\"CLP needs boost to be enabled.\");\n#else\n  Require(x_1 > x_0);\n\n  // Allocate the basis matrix\n  d_basis = new callow::MatrixDense(d_order + 1, d_size, 0.0);\n\n  // Allocate the normalization array\n  d_a = Vector::Create(d_order + 1, 0.0);\n\n  // The weights are just the qw's.\n  double L = x_1 - x_0;\n  for (size_t i = 0; i < d_w->size(); ++i)\n  {\n    d_x[i] =  2.0*(d_x[i] - x_0)/L - 1.0;\n    (*d_w)[i] = d_qw[i];\n  }\n\n  // Build the basis\n  for (size_t l = 0; l <= d_order; ++l)\n  {\n    for (size_t i = 0; i < d_size; ++i)\n    {\n      (*d_basis)(l, i) = boost::math::legendre_p(l, d_x[i]);\n    }\n    // Inverse of normalization coefficient.\n    (*d_a)[l] = (2.0 * l + 1.0) / 2.0;\n  }\n  d_orthonormal = true;\n  compute_a();\n#endif\n}\n\n} // end namespace detran_orthog\n\n//---------------------------------------------------------------------------//\n//              end of file CLP.cc\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "b40afa70fa539c97c63e8284436aec2a98b96429", "size": 1657, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/orthog/CLP.cc", "max_stars_repo_name": "RLReed/libdetran", "max_stars_repo_head_hexsha": "77637c788823e0a14aae7e40e476a291f6f3184b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/orthog/CLP.cc", "max_issues_repo_name": "RLReed/libdetran", "max_issues_repo_head_hexsha": "77637c788823e0a14aae7e40e476a291f6f3184b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/orthog/CLP.cc", "max_forks_repo_name": "RLReed/libdetran", "max_forks_repo_head_hexsha": "77637c788823e0a14aae7e40e476a291f6f3184b", "max_forks_repo_licenses": ["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.4923076923, "max_line_length": 79, "alphanum_fraction": 0.4441762221, "num_tokens": 470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5147924874181574}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include \"jefflib.h\" \n#include <boost/tokenizer.hpp>\n#include <cmath>\n#include <map>\n\nusing namespace std;\nusing namespace boost;\n\nstruct coord_t {\n    int x;\n    int y;\n};\n\nstruct loc_t {\n    int x;\n    int y;\n    int closestDist = INT_MAX;\n    int closestCoord = -1;\n    int closestCoordCount = 0;\n};\n\nint main()\n{\n    vector<string> vect;\n    if(GetStringInput(vect)){\n        cout << \"Got data!\" << endl;\n        cout << endl;\n    }\n    else {\n        cout << \"Failed to read input :( \" << cout;\n        return -1;\n    }\n   \n    // Create the list of coords, making note of bounds\n    vector<coord_t> coords;\n    int minX = INT_MAX, minY = INT_MAX;\n    int maxX = 0, maxY = 0;\n    for (const string line : vect)\n    {\n        char_separator<char> sep(\",\");\n        tokenizer< char_separator<char> > tokens(line, sep);\n        // x y\n        vector<string> s_tmp(tokens.begin(), tokens.end());\n        coord_t tempCoord;\n        tempCoord.x = stoi(s_tmp[0]);\n        tempCoord.y = stoi(s_tmp[1]);\n        coords.push_back(tempCoord);\n\n        if(tempCoord.x < minX) minX = tempCoord.x;\n        if(tempCoord.x > maxX) maxX = tempCoord.x;\n        if(tempCoord.y < minY) minY = tempCoord.y;\n        if(tempCoord.y > maxY) maxY = tempCoord.y;\n    }\n   \n    cout << \"Min x: \" << minX << \", Max x: \" << maxX << \", Min y: \" << minY << \", Max y: \" << maxY << endl;\n\n    // Hack(?) to try and identify which coord are bounded vs. unbounded...\n    minX = -2000;\n    minY = -2000;\n    maxX = 2000;\n    maxY = 2000;\n\n    // Let's build a (bounded) list of locations of interest\n    vector<loc_t> locs;\n    for(int x = minX; x <= maxX; x++){\n        for(int y = minY; y <= maxY; y++){\n            loc_t tempLoc;\n            tempLoc.x = x;\n            tempLoc.y = y;\n            locs.push_back(tempLoc);\n        }\n    }\n    cout << \"Number of locations: \" << locs.size() << endl;\n    // For each location, let's find the closest coord(s)\n    for(auto  &location : locs){\n        for(int i = 0; i < coords.size(); i++){\n            int distance = abs(location.x - coords[i].x) + abs(location.y - coords[i].y);\n            if(distance == location.closestDist){\n                location.closestCoord = -1;\n                location.closestCoordCount++;\n            } \n            else if(distance < location.closestDist){\n                location.closestDist = distance;\n                location.closestCoord = i;\n                location.closestCoordCount = 1;\n            }\n        }\n    }\n    \n    // Finally, let's determine which coord appears most frequently (i.e. has the largest area)\n    map<int, int> m; // coordId, count map\n    for(auto &location : locs){\n        // Need to skip over the edge/infinite coords\n        if(location.x == maxX || location.x == minX || location.y == maxY || location.y == minY) continue;\n\n        if(location.closestCoordCount == 1){\n            m[location.closestCoord] += 1;\n        }\n        //cout << \"Loc: \" << location.x << \",\" << location.y << \": closestCoord = \" << location.closestCoord << \", ClosestCoordCount = \" << location.closestCoordCount << endl;\n    }\n\n    int maxArea = 0;\n    for (const auto &p : m) {\n        cout << p.first << \", \" << p.second << endl;\n        if(p.second > maxArea) maxArea = p.second;\n    }\n    cout << \"Max area: \" << maxArea << endl;\n}\n\n\n", "meta": {"hexsha": "6d3202547b9efb3d30af2f42a7e9f5291892280f", "size": 3362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jeff/day-06/part-1.cpp", "max_stars_repo_name": "jeffphi/advent-of-code-2018", "max_stars_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-23T01:40:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-23T01:40:07.000Z", "max_issues_repo_path": "jeff/day-06/part-1.cpp", "max_issues_repo_name": "jeffphi/advent-of-code-2018", "max_issues_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jeff/day-06/part-1.cpp", "max_forks_repo_name": "jeffphi/advent-of-code-2018", "max_forks_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_forks_repo_licenses": ["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.4912280702, "max_line_length": 175, "alphanum_fraction": 0.5431290898, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5147636937952739}}
{"text": "\n#include <ros/ros.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <mavros_msgs/CommandBool.h>\n#include <mavros_msgs/SetMode.h>\n#include <mavros_msgs/State.h>\n#include <sensor_msgs/Imu.h>\n#include \"geometry_msgs/PoseStamped.h\"\n#include \"geometry_msgs/Vector3Stamped.h\"\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\ngeometry_msgs::PoseStamped pose;\nmavros_msgs::State current_state;\nEigen::Quaternionf q;\nEigen::Quaternionf q_2;\nEigen::MatrixXf R_mat(3,3);\nEigen::MatrixXf imuacc(3,1);\ngeometry_msgs::Vector3Stamped ang;\ngeometry_msgs::Vector3Stamped acc_;\ngeometry_msgs::Vector3Stamped acc_ang;\nros::Publisher euler ;\nros::Publisher body_acc;\nros::Publisher acc_1;\nros::Publisher acc_2;\nros::Publisher veloc;\n\ndouble a,b;\ndouble theta=0.0;\ndouble count_r=0.0;\ndouble wn;\n\nvoid imu_cb(const sensor_msgs::Imu::ConstPtr& msg)\n{\n    //conerts the acceleration from body frame to earth frame(NED) \n    q = Eigen::Quaternionf(msg->orientation.w, msg->orientation.x, msg->orientation.y, msg->orientation.z);\n    R_mat= q.toRotationMatrix();\n    imuacc << msg->linear_acceleration.x,msg->linear_acceleration.y,msg->linear_acceleration.z;\n    imuacc= R_mat*imuacc ;\n    acc_.header.stamp = ros::Time::now();\n    acc_.vector.x = imuacc(0,0);\n    acc_.vector.y = imuacc(1,0);\n    acc_.vector.z = imuacc(2,0)-9.81;\n    acc_1.publish(acc_);\n\n   /* Eigen::MatrixXf rpy(3,1);\n    rpy = q.toRotationMatrix().eulerAngles(0, 1, 2);\n    acc_ang.header.stamp = ros::Time::now();\n    acc_ang.vector.x = rpy(0,0)*(180.0/3.14159265358979);\n    acc_ang.vector.y = rpy(1,0)*(180.0/3.14159265358979);\n    acc_ang.vector.z = rpy(2,0)*(180.0/3.14159265358979);\n\n    body_acc.publish(acc_ang);*/\n\n}\n\ndouble prev_x,prev_y,prev_z,dt_1,vel_last_time;\ngeometry_msgs::Vector3Stamped vic_vel;\nint count_vel=0;\n\n\ndouble prev_vx,prev_vy,prev_vz,dt_2,acc_last_time;\ngeometry_msgs::Vector3Stamped vic_acc;\nint count_acc=0;\n\n\n\nvoid state_cb(const mavros_msgs::State::ConstPtr& msg){\n    current_state = *msg;\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"offboard\");\n    ros::NodeHandle nh;\n\n    ros::Subscriber state_sub = nh.subscribe(\"/mavros/state\", 10, state_cb);\n    ros::Subscriber Imu=nh.subscribe(\"/mavros/imu/data\",10,imu_cb);\n\n \n    ros::Publisher local_pos_pub = nh.advertise<geometry_msgs::PoseStamped>\n            (\"/mavros/setpoint_position/local\", 10);\n    ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool>\n            (\"/mavros/cmd/arming\");\n    ros::ServiceClient set_mode_client = nh.serviceClient<mavros_msgs::SetMode>\n            (\"/mavros/set_mode\");\n\n    acc_1 = nh.advertise<geometry_msgs::Vector3Stamped>(\"imu_acc\", 10);\n\n    //the setpoint publishing rate MUST be faster than 2Hz\n    ros::Rate rate(5.0);\n\n    // wait for FCU connection\n    while(ros::ok() && !current_state.connected){\n        ros::spinOnce();\n        rate.sleep();\n    }\n\n    //geometry_msgs::PoseStamped pose;\n    pose.pose.position.x = 0;\n    pose.pose.position.y = 1.5;\n    pose.pose.position.z = 1.5;\n    \n    pose.pose.orientation.x = 0.0;\n    pose.pose.orientation.y = 0.0;\n    pose.pose.orientation.z = 0.0;\n    pose.pose.orientation.w = 1.0;\n    //send a few setpoints before starting\n    for(int i = 100; ros::ok() && i > 0; --i){\n        local_pos_pub.publish(pose);\n        ros::spinOnce();\n        rate.sleep();\n    }\n\n    mavros_msgs::SetMode offb_set_mode;\n    offb_set_mode.request.custom_mode = \"OFFBOARD\";\n\n    mavros_msgs::CommandBool arm_cmd;\n    arm_cmd.request.value = true;\n\n    ros::Time last_request = ros::Time::now();\n    double pos_x = 0.0;\n    double pos_y = 1.5;\n    int mode_sp=0;\n    while(ros::ok()){\n    \n  //  if( current_state.mode == \"OFFBOARD\" )\n    nh.getParam(\"offboard/mode_sp\", mode_sp);    \n\n    if (mode_sp == 0)\n    {\n        nh.getParam(\"offboard/pos_x\", pos_x);\n        nh.getParam(\"offboard/pos_y\", pos_y);\n        pose.pose.position.x = pos_x;\n        pose.pose.position.y = pos_y;\n        pose.pose.position.z = 1.5;\n    }\n\n    if(mode_sp == 1)\n    {\n        \n        nh.getParam(\"offboard/elip_a\", a);\n        nh.getParam(\"offboard/elip_b\", b);\n        nh.getParam(\"offboard/change_rate\", wn);\n        theta = wn*count_r;\n\n        pose.pose.position.x = a*sin(theta);\n        pose.pose.position.y = b*cos(theta);\n        pose.pose.position.z = 1.5;\n\n        count_r = count_r + 1.0;\n        if(theta > 360)\n            theta = 0 ;\n    }\n\n\t    pose.pose.orientation.x = 0.0;\n    \tpose.pose.orientation.y = 0.0;\n    \tpose.pose.orientation.z = 0.0;\n    \tpose.pose.orientation.w = 1.0;\n        \n        local_pos_pub.publish(pose);\n\n    ros::spinOnce();\n    rate.sleep();\n\n    \n//\n}\n\n\nreturn 0;\n}\n", "meta": {"hexsha": "e9e4be33922338181d430bd7b42821dd1f85152c", "size": 4673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gazebo_sim/gps_denied/src/offb_node_4.cpp", "max_stars_repo_name": "naveenbiitk/State_Estimation", "max_stars_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-05T06:19:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-05T06:19:20.000Z", "max_issues_repo_path": "gazebo_sim/gps_denied/src/offb_node_4.cpp", "max_issues_repo_name": "naveenbiitk/State_Estimation", "max_issues_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gazebo_sim/gps_denied/src/offb_node_4.cpp", "max_forks_repo_name": "naveenbiitk/State_Estimation", "max_forks_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_forks_repo_licenses": ["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.8563218391, "max_line_length": 107, "alphanum_fraction": 0.6539696127, "num_tokens": 1358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5147636934746997}}
{"text": "// Copyright (c) 2017-2019 The Multiverse developers\n// Distributed under the MIT/X11 software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <boost/test/unit_test.hpp>\n\n#include \"test_fnfn.h\"\n#include \"mpvss.h\"\n#include \"mpinterpolation.h\"\n\nusing curve25519::Print32;\n\nBOOST_FIXTURE_TEST_SUITE(mpvss_tests, BasicUtfSetup)\n\nvoid RandGeneretor(uint8_t* p)\n{\n    for (int i = 0; i < 32; i++)\n    {\n        *p++ = rand();\n    }\n}\n\nvoid KeyGenerator(uint256& priv, uint256& pub)\n{\n    uint8_t md32[32];\n\n    RandGeneretor(md32);\n    md32[31] &= 0x0F;\n    memcpy(priv.begin(), md32, 32);\n\n    CEdwards25519 P;\n    P.Generate(priv);\n    P.Pack(pub.begin());\n}\n\nBOOST_AUTO_TEST_CASE( fp25519 )\n{\n    srand(time(0));\n    uint8_t md32[32];\n\n    // add, minus\n    for (int i = 0; i < 10; i++)\n    {\n        RandGeneretor(md32);\n        CFP25519 add1(md32);\n        RandGeneretor(md32);\n        CFP25519 add2(md32);\n        CFP25519 fpSum = add1 + add2;\n        BOOST_CHECK( add1 == fpSum - add2 );\n        BOOST_CHECK( add2 == fpSum - add1 );\n    }\n\n    // multiply, divide\n    for (int i = 0; i < 10; i++)\n    {\n        RandGeneretor(md32);\n        CFP25519 mul1(md32);\n        RandGeneretor(md32);\n        CFP25519 mul2(md32);\n        CFP25519 fpProduct = mul1 * mul2;\n        BOOST_CHECK( mul1 == fpProduct / mul2 );\n        BOOST_CHECK( mul2 == fpProduct / mul1 );\n    }\n\n    // inverse\n    for (int i = 0; i < 10; i++)\n    {\n        RandGeneretor(md32);\n        CFP25519 fp(md32);\n        CFP25519 fpInverse = fp.Inverse();\n        BOOST_CHECK( CFP25519(1) == fp * fpInverse );\n    }\n\n    // sqrt square\n    for (int i = 0; i < 10; i++)\n    {\n        RandGeneretor(md32);\n        CFP25519 fp1(md32);\n        CFP25519 fp2(md32);\n        fp2 = fp2.Square().Sqrt();\n        BOOST_CHECK( fp2.Square() == fp1.Square() );\n    }\n}\n\nBOOST_AUTO_TEST_CASE( sc25519 )\n{\n    srand(time(0));\n    uint8_t md32[32];\n\n    // add, minus\n    for (int i = 0; i < 10; i++)\n    {\n        RandGeneretor(md32);\n        CSC25519 add1(md32);\n        RandGeneretor(md32);\n        CSC25519 add2(md32);\n        CSC25519 scSum = add1 + add2;\n        BOOST_CHECK( add1 == scSum - add2 );\n        BOOST_CHECK( add2 == scSum - add1 );\n    }\n\n    // multiply\n    for (int i = 0; i < 10; i++)\n    {\n        RandGeneretor(md32);\n        CSC25519 sc(md32);\n        RandGeneretor(md32);\n        uint32_t n = 10;\n        CSC25519 scProduct = sc * n;\n        for (int i = 0; i < n - 1; i++)\n        {\n            scProduct -= sc;\n        }\n        BOOST_CHECK( scProduct == sc );\n    }\n\n    // negative\n    for (int i = 0; i < 10; i++)\n    {\n        RandGeneretor(md32);\n        CSC25519 sc(md32);\n        CSC25519 scNegative1 = -sc;\n        CSC25519 scNegative2(sc);\n        scNegative2.Negative();\n        BOOST_CHECK( scNegative1 == scNegative2 );\n        BOOST_CHECK( CSC25519() == sc + scNegative1 );\n    }\n}\n\nBOOST_AUTO_TEST_CASE( ed25519 )\n{\n    srand(time(0));\n    uint8_t md32[32];\n\n    // sign, verify\n    for (int i = 0; i < 10; i++)\n    {\n        uint256 priv1, pub1;\n        uint256 priv2, pub2;\n        KeyGenerator(priv1, pub1);\n        KeyGenerator(priv2, pub2);\n\n        RandGeneretor(md32);\n        CSC25519 hash(md32);\n\n        CSC25519 sign = CSC25519(priv1.begin()) + CSC25519(priv2.begin()) * hash;\n\n        CEdwards25519 P,R,S;\n        P.Unpack(pub1.begin());\n        R.Unpack(pub2.begin());\n        S.Generate(sign);\n        \n        BOOST_CHECK( S == (P + R.ScalarMult(hash)) );\n    }\n}\n\nBOOST_AUTO_TEST_CASE( interpolation )\n{\n    srand(time(0));\n    uint8_t md32[32];\n\n    // lagrange, newton\n    for (int i = 0; i < 1; i++)\n    {\n        std::vector<uint32_t> vX;\n        for (int i = 1; i < 51; i++)\n        {\n            vX.push_back(i);\n        }\n\n        std::vector<std::pair<uint32_t,uint256> > vShare;\n        for (int i = 0; i < 26; i++)\n        {\n            int index = rand() % vX.size();\n            uint32_t x = vX[index];\n            vX.erase(vX.begin() + index);\n\n            RandGeneretor(md32);\n            uint256 y((uint64_t*)md32);\n            vShare.push_back(std::make_pair(x, y));\n        }\n\n        BOOST_CHECK( MPLagrange(vShare) == MPNewton(vShare) );\n    }\n}\n\nBOOST_AUTO_TEST_CASE( mpvss )\n{\n    srand(time(0));\n    for (size_t count = 41; count <= 50; count++)\n    {\n        uint256 nInitValue;\n        std::vector<uint256> vID;\n        std::map<uint256,CMPSecretShare> mapSS;\n        std::vector<CMPSealedBox> vSBox;\n        std::vector<CMPCandidate> vCandidate;\n\n        CMPSecretShare ssWitness;\n\n        boost::posix_time::ptime t0;\n        std::cout << \"Test mpvss begin: count \" << count << \"\\n{\\n\";\n        vID.resize(count); vSBox.resize(count); vCandidate.resize(count);\n        //Setup\n        t0 = boost::posix_time::microsec_clock::universal_time();\n        for (int i = 0;i < count;i++)\n        {\n            vID[i] = uint256(i + 1);\n            mapSS[vID[i]] = CMPSecretShare(vID[i]);\n\n            mapSS[vID[i]].Setup(count + 1,vSBox[i]);\n            vCandidate[i] = CMPCandidate(vID[i],1,vSBox[i]);\n\n            nInitValue = nInitValue ^ mapSS[vID[i]].myBox.vCoeff[0];\n        }\n        std::cout << \"\\tSetup : \" << ((boost::posix_time::microsec_clock::universal_time() - t0).ticks() / count) <<\"\\n\";\n        std::cout << \"\\tInit value = \" << nInitValue.GetHex() << \"\\n\";\n        {\n            CMPSealedBox box;\n            ssWitness.Setup(count + 1,box);\n        }\n\n        //Enroll\n        t0 = boost::posix_time::microsec_clock::universal_time();\n        for (int i = 0;i < count;i++)\n        {   \n            mapSS[vID[i]].Enroll(vCandidate);\n        }\n        std::cout << \"\\tEnroll : \" << ((boost::posix_time::microsec_clock::universal_time() - t0).ticks() / count) <<\"\\n\";\n        ssWitness.Enroll(vCandidate);\n\n        // Distribute\n        t0 = boost::posix_time::microsec_clock::universal_time();\n        for (int i = 0;i < count;i++)\n        {\n            std::map<uint256,std::vector<uint256> > mapShare;\n            mapSS[vID[i]].Distribute(mapShare);\n            for (int j = 0;j < count;j++)\n            {\n                if (i != j)\n                {\n                    mapSS[vID[j]].Accept(vID[i],mapShare[vID[j]]);\n                }\n            }\n        }\n        std::cout << \"\\tDistribute : \" << ((boost::posix_time::microsec_clock::universal_time() - t0).ticks() / count) <<\"\\n\";\n\n        // Publish\n        t0 = boost::posix_time::microsec_clock::universal_time();\n        bool fComplete;\n        for (int i = 0;i < count;i++)\n        {\n            std::map<uint256,std::vector<uint256> > mapShare;\n            mapSS[vID[i]].Publish(mapShare);\n            for (int j = 0;j < count;j++)\n            {\n                fComplete = false;\n                mapSS[vID[j]].Collect(vID[i],mapShare,fComplete);\n            }\n            fComplete = false;\n            ssWitness.Collect(vID[i],mapShare,fComplete);\n        }\n        std::cout << \"\\tPublish : \" << ((boost::posix_time::microsec_clock::universal_time() - t0).ticks() / count) <<\"\\n\";\n\n        // Reconstruct \n        t0 = boost::posix_time::microsec_clock::universal_time();\n        for (int i = 0;i < count;i++)\n        {\n            std::map<uint256,std::pair<uint256,std::size_t> > mapSecret;\n            mapSS[vID[i]].Reconstruct(mapSecret);\n        }\n        std::cout << \"\\tReconstruct : \" << ((boost::posix_time::microsec_clock::universal_time() - t0).ticks() / count) <<\"\\n\";;\n\n        uint256 nRecValue;\n        std::map<uint256,std::pair<uint256,std::size_t> > mapSecret;\n        ssWitness.Reconstruct(mapSecret);\n        for (std::map<uint256,std::pair<uint256,std::size_t> >::iterator it = mapSecret.begin();it != mapSecret.end();++it)\n        {\n            nRecValue = nRecValue ^ (*it).second.first;\n        }\n        std::cout << \"\\tReconstruct value = \" << nRecValue.GetHex() << \"\\n\";\n        std::cout << \"}\\n\";\n\n        BOOST_CHECK( nRecValue == nInitValue );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "e1de91632368c365b0180846e4104e30b5ae2986", "size": 7983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/mpvss_tests.cpp", "max_stars_repo_name": "ouyun/FnFnCoreWallet", "max_stars_repo_head_hexsha": "3aa61145bc3f524d1dc10ada22e164689a73d794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-23T11:56:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-23T11:56:55.000Z", "max_issues_repo_path": "test/mpvss_tests.cpp", "max_issues_repo_name": "ouyun/FnFnCoreWallet", "max_issues_repo_head_hexsha": "3aa61145bc3f524d1dc10ada22e164689a73d794", "max_issues_repo_licenses": ["MIT"], "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/mpvss_tests.cpp", "max_forks_repo_name": "ouyun/FnFnCoreWallet", "max_forks_repo_head_hexsha": "3aa61145bc3f524d1dc10ada22e164689a73d794", "max_forks_repo_licenses": ["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.8153310105, "max_line_length": 128, "alphanum_fraction": 0.5288738569, "num_tokens": 2313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5147636931541253}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <memory>\n#include \"ear/common/point_source_panner.hpp\"\n\nnamespace ear {\n\n  class ExtentPanner {};\n\n  /** @brief Modify an extent parameter given a distance.\n   *\n   * A right triangle if formed, with the adjacent edge being the distance, and\n   * the opposite edge being determined from the extent. The angle formed is\n   * then used to determine the new extent.\n   *\n   * - at distance=0, the extent is always 360\n   * - at distance=1, the original extent is used\n   * - at distance>1, the extent decreases\n   * - in 0 < distance < 1, the extent changes more steeply around 0 for smaller\n   *   extents\n   */\n  double extentMod(double extent, double distance);\n\n  /** @brief Calculate basis vectors that rotate (0, 1, 0)\n     onto source_pos. */\n  Eigen::Matrix3d calcBasis(Eigen::Vector3d position);\n\n  /** @brief Polar to Cartesian in radians with no distance, in a given basis.*/\n  Eigen::Vector3d cartOnBasis(Eigen::Matrix3d basis, double azimuth,\n                              double elevation);\n\n  std::pair<double, double> azimuthElevationOnBasis(\n      Eigen::Matrix3d basis, Eigen::RowVector3d position);\n\n  /** @brief Weighting function for spread sources.\n   *\n   * The weighting function is one inside a region approximately determined by a\n   * width x height rectangle in azimuth-elevation space, with maximally-sized\n   * rounded corners; the shape of the corners is calculated using the vector\n   * angle from their centres (always directly above or below the source\n   * position) so as to avoid issues at the poles.\n   *\n   * The two straight edges of the rectangle are always parallel in Cartesian\n   * space; this is achieved by following azimuth lines; for tall sources, the\n   * whole coordinate system is rotated 90 degrees about the source position to\n   * achieve this.\n   *\n   * Note that for sources where width == height, this degrades to a circular\n   * region relative to the source position.\n   *\n   * To make the two ends meet, the width is adjusted such that a width of 180\n   * degrees is mapped to width + height.\n   *\n   */\n  class WeightingFunction {\n   public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    /** @brief Ctor\n     *\n     * @param position Centre of the extent.\n     * @param width Width of the extent in degrees from one edge to the other.\n     * @param height Height of the extent in degrees from one edge to the other.\n     */\n    WeightingFunction(Eigen::Vector3d position, double width, double height);\n\n    /** @brief Calculate weight for position */\n    double operator()(Eigen::Vector3d position) const;\n\n   private:\n    const double _fadeWidth = 10.0;\n    double _width;\n    double _height;\n    double _circleRadius;\n    Eigen::Matrix3d _flippedBasis;\n    double _circlePos;\n    Eigen::Matrix<double, 3, 2> _circlePositions;\n  };\n\n  class SpreadingPanner {\n   public:\n    SpreadingPanner(std::shared_ptr<PointSourcePanner> psp, int nRows);\n\n    /** @brief Panning values for a given weighting function.\n     *\n     * @param weightFunc function from Cartesian position to weight in range\n     * (0, 1)\n     *\n     * @return panning value for each speaker.\n     */\n    Eigen::VectorXd panningValuesForWeight(const WeightingFunction& weightFunc);\n\n   private:\n    /** @brief Generate points spread evenly on the sphere.\n     *\n     * Based on\n     * http://web.archive.org/web/20150108040043/http://www.math.niu.edu/~rusin/known-math/95/equispace.elect\n     *\n     * @param nRows number of rows to place on sphere, e.g. 37 for 5 degree\n     * spacing\n     *\n     * @returns cartesian array.\n     */\n    Eigen::MatrixXd _generatePanningPositionsEven();\n    Eigen::MatrixXd _generatePanningPositionsResults();\n\n    std::shared_ptr<PointSourcePanner> _psp;\n    int _nRows;\n    Eigen::MatrixXd _panningPositions;\n    Eigen::MatrixXd _panningPositionsResults;\n  };\n\n  class PolarExtentPanner : public ExtentPanner {\n   public:\n    PolarExtentPanner(std::shared_ptr<PointSourcePanner> psp);\n\n    /** @brief Calculate loudspeaker gains given position and extent parameters.\n     *\n     * @param position  Cartesian source position\n     * @param width block format width parameter\n     * @param height block format height parameter\n     * @param depth block format depth parameter\n     *\n     * @returns loudspeaker gains for each channel\n     */\n    Eigen::VectorXd handle(Eigen::Vector3d position, double width,\n                           double height, double depth);\n\n    /** @brief Calculate the speaker panning values for the position, width, and\n     * height of a source; this just deals with the positioning and spreading.\n     */\n    Eigen::VectorXd calcPvSpread(Eigen::Vector3d position, double width,\n                                 double height);\n\n   private:\n    const int _nRows = 37;  // 5 degrees per row\n    const double _fadeWidth = 10.0;  // degrees\n    std::shared_ptr<PointSourcePanner> _psp;\n    SpreadingPanner _spreadingPanner;\n  };\n\n  class CartesianExtentPanner : public ExtentPanner {};\n\n}  // namespace ear\n", "meta": {"hexsha": "5c8375da05814db92de0d1e9b90b79a7b78e8fee", "size": 5026, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ear/object_based/extent.hpp", "max_stars_repo_name": "valnoel/libear", "max_stars_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "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/ear/object_based/extent.hpp", "max_issues_repo_name": "valnoel/libear", "max_issues_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "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/ear/object_based/extent.hpp", "max_forks_repo_name": "valnoel/libear", "max_forks_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "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.9027777778, "max_line_length": 109, "alphanum_fraction": 0.6902109033, "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5147636931541253}}
{"text": "/*\n [auto_generated]\n boost/numeric/odeint/stepper/implicit_euler.hpp\n\n [begin_description]\n Impementation of the implicit Euler method. Works with ublas::vector as state type.\n [end_description]\n\n Copyright 2009-2011 Karsten Ahnert\n Copyright 2009-2011 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#ifndef OMPLEXT_BOOST_NUMERIC_ODEINT_STEPPER_IMPLICIT_EULER_HPP_INCLUDED\n#define OMPLEXT_BOOST_NUMERIC_ODEINT_STEPPER_IMPLICIT_EULER_HPP_INCLUDED\n\n\n#include <utility>\n\n#include <omplext_odeint/boost/numeric/odeint/util/bind.hpp>\n#include <omplext_odeint/boost/numeric/odeint/util/unwrap_reference.hpp>\n#include <omplext_odeint/boost/numeric/odeint/stepper/stepper_categories.hpp>\n\n#include <omplext_odeint/boost/numeric/odeint/util/ublas_wrapper.hpp>\n#include <omplext_odeint/boost/numeric/odeint/util/is_resizeable.hpp>\n#include <omplext_odeint/boost/numeric/odeint/util/resizer.hpp>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\nnamespace boost {\nnamespace numeric {\nnamespace omplext_odeint {\n\n\n\n\n\n\n\n\ntemplate< class ValueType , class Resizer = initially_resizer >\nclass implicit_euler\n{\n\npublic:\n\n    typedef ValueType value_type;\n    typedef value_type time_type;\n    typedef boost::numeric::ublas::vector< value_type > state_type;\n    typedef state_wrapper< state_type > wrapped_state_type;\n    typedef state_type deriv_type;\n    typedef state_wrapper< deriv_type > wrapped_deriv_type;\n    typedef boost::numeric::ublas::matrix< value_type > matrix_type;\n    typedef state_wrapper< matrix_type > wrapped_matrix_type;\n    typedef boost::numeric::ublas::permutation_matrix< size_t > pmatrix_type;\n    typedef state_wrapper< pmatrix_type > wrapped_pmatrix_type;\n    typedef Resizer resizer_type;\n    typedef stepper_tag stepper_category;\n    typedef implicit_euler< ValueType , Resizer > stepper_type;\n\n    implicit_euler( value_type epsilon = 1E-6 )\n    : m_epsilon( epsilon ) \n    { }\n\n\n    template< class System >\n    void do_step( System system , state_type &x , time_type t , time_type dt )\n    {\n        typedef typename omplext_odeint::unwrap_reference< System >::type system_type;\n        typedef typename omplext_odeint::unwrap_reference< typename system_type::first_type >::type deriv_func_type;\n        typedef typename omplext_odeint::unwrap_reference< typename system_type::second_type >::type jacobi_func_type;\n        system_type &sys = system;\n        deriv_func_type &deriv_func = sys.first;\n        jacobi_func_type &jacobi_func = sys.second;\n\n        m_resizer.adjust_size( x , detail::bind( &stepper_type::template resize_impl<state_type> , detail::ref( *this ) , detail::_1 ) );\n\n        for( size_t i=0 ; i<x.size() ; ++i )\n            m_pm.m_v[i] = i;\n\n        t += dt;\n\n        // apply first Newton step\n        deriv_func( x , m_dxdt.m_v , t );\n\n        m_b.m_v = dt * m_dxdt.m_v;\n\n        jacobi_func( x , m_jacobi.m_v  , t );\n        m_jacobi.m_v *= dt;\n        m_jacobi.m_v -= boost::numeric::ublas::identity_matrix< value_type >( x.size() );\n\n        solve( m_b.m_v , m_jacobi.m_v );\n\n        m_x.m_v = x - m_b.m_v;\n\n        // iterate Newton until some precision is reached\n        // ToDo: maybe we should apply only one Newton step -> linear implicit one-step scheme\n        while( boost::numeric::ublas::norm_2( m_b.m_v ) > m_epsilon )\n        {\n            deriv_func( m_x.m_v , m_dxdt.m_v , t );\n            m_b.m_v = x - m_x.m_v + dt*m_dxdt.m_v;\n\n            // simplified version, only the first Jacobian is used\n            //            jacobi( m_x , m_jacobi , t );\n            //            m_jacobi *= dt;\n            //            m_jacobi -= boost::numeric::ublas::identity_matrix< value_type >( x.size() );\n\n            solve( m_b.m_v , m_jacobi.m_v );\n\n            m_x.m_v -= m_b.m_v;\n        }\n        x = m_x.m_v;\n    }\n\n    template< class StateType >\n    void adjust_size( const StateType &x )\n    {\n        resize_impl( x );\n    }\n\n\nprivate:\n\n    template< class StateIn >\n    bool resize_impl( const StateIn &x )\n    {\n        bool resized = false;\n        resized |= adjust_size_by_resizeability( m_dxdt , x , typename is_resizeable<deriv_type>::type() );\n        resized |= adjust_size_by_resizeability( m_x , x , typename is_resizeable<state_type>::type() );\n        resized |= adjust_size_by_resizeability( m_b , x , typename is_resizeable<deriv_type>::type() );\n        resized |= adjust_size_by_resizeability( m_jacobi , x , typename is_resizeable<matrix_type>::type() );\n        resized |= adjust_size_by_resizeability( m_pm , x , typename is_resizeable<pmatrix_type>::type() );\n        return resized;\n    }\n\n\n    void solve( state_type &x , matrix_type &m )\n    {\n        int res = boost::numeric::ublas::lu_factorize( m , m_pm.m_v );\n        if( res != 0 ) exit(0);\n        boost::numeric::ublas::lu_substitute( m , m_pm.m_v , x );\n    }\n\nprivate:\n\n    value_type m_epsilon;\n    resizer_type m_resizer;\n    wrapped_deriv_type m_dxdt;\n    wrapped_state_type m_x;\n    wrapped_deriv_type m_b;\n    wrapped_matrix_type m_jacobi;\n    wrapped_pmatrix_type m_pm;\n\n\n};\n\n\n} // odeint\n} // numeric\n} // boost\n\n\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_IMPLICIT_EULER_HPP_INCLUDED\n", "meta": {"hexsha": "40f9d4ae416798d7c9ca083d07ed5f5b38e80ee3", "size": 5338, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/external/omplext_odeint/boost/numeric/odeint/stepper/implicit_euler.hpp", "max_stars_repo_name": "ivaROS/ivaOmplCore", "max_stars_repo_head_hexsha": "3f5f47bb8f20c5eb82e84564342dd45f39d0c5f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-08-10T18:11:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T00:33:13.000Z", "max_issues_repo_path": "src/external/omplext_odeint/boost/numeric/odeint/stepper/implicit_euler.hpp", "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/external/omplext_odeint/boost/numeric/odeint/stepper/implicit_euler.hpp", "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": 31.4, "max_line_length": 137, "alphanum_fraction": 0.6839640315, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5147636879063334}}
{"text": "//\n//  cal_ezz.hpp\n//  hybrid_fem_bie\n//\n//  Created by Max on 2/7/18.\n//\n//\n\n#ifndef cal_ezz_hpp\n#define cal_ezz_hpp\n\n#include <stdio.h>\n#include <Eigen/Eigen>\n\nusing namespace Eigen;\n\nvoid cal_ezz(MatrixXd coord ,double E, double nu,std::vector<double> &ezz_out, std::vector<double> &exx_out,std::vector<double> &eyy_out,  int n_el, MatrixXi &index_store, double q, VectorXd &u_n);\n#endif /* cal_ezz_hpp */\n", "meta": {"hexsha": "da61fa022f4a7ab923e17e06b17a76e82107e60b", "size": 409, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/fem/cal_ezz.hpp", "max_stars_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_stars_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fem/cal_ezz.hpp", "max_issues_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_issues_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fem/cal_ezz.hpp", "max_forks_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_forks_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_forks_repo_licenses": ["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.5263157895, "max_line_length": 197, "alphanum_fraction": 0.7090464548, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.514763687585759}}
{"text": "#pragma once\n\n#include <memory>\n#include <vector>\n#include <Eigen/Core>\n\n/* Custom exceptions for the k-d tree*/\n\nstruct VaryingStateSizeException : public std::exception\n{\n    const char* what() const throw()\n    {\n        return \"Cannot build a tree with varying state sizes.\";\n    }\n};\n\nstruct EmptyTreeException : public std::exception\n{\n    const char* what() const throw()\n    {\n        return \"Cannot perform this operation on an empty tree.\";\n    }\n};\n\n/* Tree Node Class */\n\nstruct kdNode {\n    Eigen::VectorXd state;\n\n    std::shared_ptr<kdNode> left;\n    std::shared_ptr<kdNode> right;\n};\n\n/* Tree Class */\n\nclass kdTree {\npublic:\n    kdTree() {n_states = 0;}\n    kdTree(const std::vector<Eigen::VectorXd>& states);\n    kdTree(const Eigen::MatrixXd& states);\n\n    int state_size;\n    int n_states;\n\n    void append_state(const Eigen::VectorXd& state);\n\n    Eigen::VectorXd nearest_neighbor(const Eigen::VectorXd& search_state) const;\n\n    Eigen::MatrixXd k_nearest_neighbors(const Eigen::VectorXd& search_state, int k) const;\n\n    Eigen::MatrixXd at_depth(int depth) const;\n\n    int count_states() const;\n\nprivate:\n    std::shared_ptr<kdNode> root;\n};", "meta": {"hexsha": "625e5dbae79d3e8cebd58acf037f9189970cc536", "size": 1162, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/headers/kd_tree.hpp", "max_stars_repo_name": "will-bell/navitools", "max_stars_repo_head_hexsha": "1760799097c5f8aefbc7a3e87e60a2a99649724d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-26T18:41:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T18:41:00.000Z", "max_issues_repo_path": "src/headers/kd_tree.hpp", "max_issues_repo_name": "will-bell/navitools", "max_issues_repo_head_hexsha": "1760799097c5f8aefbc7a3e87e60a2a99649724d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/headers/kd_tree.hpp", "max_forks_repo_name": "will-bell/navitools", "max_forks_repo_head_hexsha": "1760799097c5f8aefbc7a3e87e60a2a99649724d", "max_forks_repo_licenses": ["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.3859649123, "max_line_length": 90, "alphanum_fraction": 0.6772805508, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5147493758827155}}
{"text": "// Copyright (C) 2015 National ICT Australia (NICTA)\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 http://mozilla.org/MPL/2.0/.\n// -------------------------------------------------------------------\n// \n// Written by Conrad Sanderson - http://conradsanderson.id.au\n\n\n#include <armadillo>\n#include \"catch.hpp\"\n\nusing namespace arma;\n\n\nTEST_CASE(\"gen_linspace_1\")\n  {\n  vec a = linspace(1,5,5);\n  \n  REQUIRE(a(0) == Approx(1.0));\n  REQUIRE(a(1) == Approx(2.0));\n  REQUIRE(a(2) == Approx(3.0));\n  REQUIRE(a(3) == Approx(4.0));\n  REQUIRE(a(4) == Approx(5.0));\n  \n  vec b = linspace<vec>(1,5,6);\n  \n  REQUIRE(b(0) == Approx(1.0));\n  REQUIRE(b(1) == Approx(1.8));\n  REQUIRE(b(2) == Approx(2.6));\n  REQUIRE(b(3) == Approx(3.4));\n  REQUIRE(b(4) == Approx(4.2));\n  REQUIRE(b(5) == Approx(5.0));\n  \n  rowvec c = linspace<rowvec>(1,5,6);\n  \n  REQUIRE(c(0) == Approx(1.0));\n  REQUIRE(c(1) == Approx(1.8));\n  REQUIRE(c(2) == Approx(2.6));\n  REQUIRE(c(3) == Approx(3.4));\n  REQUIRE(c(4) == Approx(4.2));\n  REQUIRE(c(5) == Approx(5.0));\n  \n  mat X = linspace<mat>(1,5,6);\n  \n  REQUIRE(X.n_rows == 6);\n  REQUIRE(X.n_cols == 1);\n  }\n\n\n\n", "meta": {"hexsha": "4a71eeb019cf094047abd8aa646c489cdc2c8846", "size": 1250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jet/thirdparty/armadillo/tests/gen_linspace.cpp", "max_stars_repo_name": "benman1/pyjet", "max_stars_repo_head_hexsha": "04b48e9966ed52999c2910b1966d467ee7fbb5bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T15:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T14:50:59.000Z", "max_issues_repo_path": "jet/thirdparty/armadillo/tests/gen_linspace.cpp", "max_issues_repo_name": "orestis-z/pyjet", "max_issues_repo_head_hexsha": "a922d8702496494c118d2c5239401d8170d10cd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-01-27T12:33:14.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-19T08:50:40.000Z", "max_forks_repo_path": "jet/thirdparty/armadillo/tests/gen_linspace.cpp", "max_forks_repo_name": "orestis-z/pyjet", "max_forks_repo_head_hexsha": "a922d8702496494c118d2c5239401d8170d10cd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T15:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-08T11:54:03.000Z", "avg_line_length": 23.5849056604, "max_line_length": 70, "alphanum_fraction": 0.5576, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.74316801430083, "lm_q1q2_score": 0.5147493672276309}}
{"text": "// sphere_fit.cpp\n//\n// Example from Foundations of Geometric Algebra Computing\n// by Dietmar Hildenbrand\n//\n// Page 68.\n\n#include <iostream>\n#include <string>\n#include <boost/numpy.hpp>\n#include <ceres/ceres.h>\n#include <glog/logging.h>\n#include <hep/ga.hpp>\n\n#include \"game/types.h\"\n#include \"game/ceres_python_utils.h\"\n\nnamespace bp = boost::python;\nnamespace np = boost::numpy;\n\nusing ceres::AutoDiffCostFunction;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solver;\n\nnamespace game {\n\nstruct SphereFit {\n  SphereFit(const SphereFit &sphere_fit) {}\n  SphereFit() {}\n\n  void SetSolverOptions(const bp::dict &solver_options) {\n    bp::extract<std::string> linear_solver_type(\n        solver_options[\"linear_solver_type\"]);\n    if (linear_solver_type.check()) {\n      ceres::StringToLinearSolverType(linear_solver_type(),\n                                      &options_.linear_solver_type);\n    }\n\n    bp::extract<int> max_num_iterations(solver_options[\"max_num_iterations\"]);\n    if (max_num_iterations.check()) {\n      options_.max_num_iterations = max_num_iterations();\n    }\n\n    bp::extract<int> num_threads(solver_options[\"num_threads\"]);\n    if (num_threads.check()) {\n      options_.num_threads = num_threads();\n    }\n\n    bp::extract<int> num_linear_solver_threads(\n        solver_options[\"num_linear_solver_threads\"]);\n    if (num_linear_solver_threads.check()) {\n      options_.num_linear_solver_threads = num_linear_solver_threads();\n    }\n\n    bp::extract<double> parameter_tolerance(\n        solver_options[\"parameter_tolerance\"]);\n    if (parameter_tolerance.check()) {\n      options_.parameter_tolerance = parameter_tolerance();\n    }\n\n    bp::extract<double> function_tolerance(\n        solver_options[\"function_tolerance\"]);\n    if (function_tolerance.check()) {\n      options_.function_tolerance = function_tolerance();\n    }\n\n    bp::extract<std::string> trust_region_strategy_type(\n        solver_options[\"trust_region_strategy_type\"]);\n    if (trust_region_strategy_type.check()) {\n      ceres::StringToTrustRegionStrategyType(\n          trust_region_strategy_type(), &options_.trust_region_strategy_type);\n    }\n\n    bp::extract<bool> minimizer_progress_to_stdout(\n        solver_options[\"minimizer_progress_to_stdout\"]);\n    if (minimizer_progress_to_stdout.check()) {\n      options_.minimizer_progress_to_stdout = minimizer_progress_to_stdout();\n    }\n\n    bp::extract<std::string> minimizer_type(solver_options[\"minimizer_type\"]);\n    if (minimizer_type.check()) {\n      ceres::StringToMinimizerType(minimizer_type(), &options_.minimizer_type);\n    }\n\n    bp::extract<bp::list> trust_region_minimizer_iterations_to_dump(\n        solver_options[\"trust_region_minimizer_iterations_to_dump\"]);\n    if (trust_region_minimizer_iterations_to_dump.check()) {\n      std::vector<int> iterations_to_dump{};\n      bp::list list = trust_region_minimizer_iterations_to_dump();\n      for (int i = 0; i < bp::len(list); ++i) {\n        iterations_to_dump.push_back(bp::extract<int>(list[i])());\n      }\n      options_.trust_region_minimizer_iterations_to_dump = iterations_to_dump;\n    }\n\n    bp::extract<std::string> trust_region_problem_dump_directory(\n        solver_options[\"trust_region_problem_dump_directory\"]);\n    if (trust_region_problem_dump_directory.check()) {\n      options_.trust_region_problem_dump_directory =\n          trust_region_problem_dump_directory();\n    }\n  }\n\n  template <typename T, typename MultivectorT>\n  static auto Inverse(const MultivectorT &multivector) -> MultivectorT {\n    return cga::Scalar<T>{static_cast<T>(1.0) /\n                          hep::eval((multivector * ~multivector))[0]} *\n           ~multivector;\n  }\n\n  struct CostFunctor {\n    CostFunctor(const double *point) : point_(point) {}\n\n    template <typename T>\n    bool operator()(const T *const s /* sphere: 5 parameters */,\n                    T *residual /* 1 parameter */) const {\n      // Conformal split\n      cga::Infty<T> ni{static_cast<T>(-1.0), static_cast<T>(1.0)};\n      cga::Orig<T> no{static_cast<T>(0.5), static_cast<T>(0.5)};\n\n      // Euclidean basis\n      cga::E1<T> e1{static_cast<T>(1.0)};\n      cga::E2<T> e2{static_cast<T>(1.0)};\n      cga::E3<T> e3{static_cast<T>(1.0)};\n\n      cga::Scalar<T> half{static_cast<T>(0.5)};\n\n      // Create Euclidean point (vector)\n      cga::EuclideanPoint<T> euc_point{static_cast<T>(point_[0]),\n                                       static_cast<T>(point_[1]),\n                                       static_cast<T>(point_[2])};\n\n      // Create conformal point\n      cga::Point<T> point =\n          hep::grade<1>(euc_point + half * euc_point * euc_point * ni + no);\n\n      // Create conformal sphere\n      //      cga::Sphere<T> sphere = hep::eval(\n      //          static_cast<T>(s[0] / s[3]) * e1 + static_cast<T>(s[1] / s[3])\n      //          * e2 +\n      //          static_cast<T>(s[2] / s[3]) * e3 + static_cast<T>(s[4] / s[3])\n      //          * ni +\n      //          static_cast<T>(s[3] / s[3]) * no);\n\n      cga::Sphere<T> sphere =\n          hep::eval(static_cast<T>(s[0]) * e1 + static_cast<T>(s[1]) * e2 +\n                    static_cast<T>(s[2]) * e3 + static_cast<T>(s[4]) * ni +\n                    static_cast<T>(s[3]) * no);\n\n      // Evaluate distance\n      //      auto distance = hep::eval(hep::inner_prod(point, sphere) *\n      //                                hep::inner_prod(point,\n      //                                Inverse<T>(sphere)));\n\n      auto distance = hep::eval(hep::inner_prod(point, sphere));\n      auto rho_squared = hep::eval(hep::inner_prod(sphere, sphere));\n\n      residual[0] = distance[0] / sqrt(rho_squared[0]);\n      //      residual[0] = distance[0];\n\n      return true;\n    }\n\n   private:\n    const double *point_;\n  };\n\n  static ceres::CostFunction *Create(const double *point) {\n    return (new ceres::AutoDiffCostFunction<SphereFit::CostFunctor, 1, 5>(\n        new SphereFit::CostFunctor(point)));\n  }\n\n  np::ndarray Run(np::ndarray sphere, np::ndarray points) {\n    if (!(points.get_flags() & np::ndarray::C_CONTIGUOUS)) {\n      throw \"input array a must be contiguous\";\n    }\n\n    auto rows_points = points.shape(0);\n    auto cols_points = points.shape(1);\n    auto rows_sphere = sphere.shape(0);\n    auto cols_sphere = sphere.shape(1);\n\n    if (!((rows_sphere == 5) && (cols_sphere == 1))) {\n      throw \"parameter array must have shape (5,1)\";\n    }\n\n    double *sphere_data = reinterpret_cast<double *>(sphere.get_data());\n    double *points_data = reinterpret_cast<double *>(points.get_data());\n\n    for (int i = 0; i < rows_points; ++i) {\n      ceres::CostFunction *cost_function =\n          SphereFit::Create(&points_data[cols_points * i]);\n      problem_.AddResidualBlock(cost_function, NULL, sphere_data);\n    }\n\n    Solve(options_, &problem_, &summary_);\n\n    return sphere;\n  }\n\n  auto Summary() -> bp::dict { return game::SummaryToDict(summary_); }\n\n  Problem problem_;\n  Solver::Options options_;\n  Solver::Summary summary_;\n};\n}\n\nBOOST_PYTHON_MODULE(libsphere_fit) {\n  np::initialize();\n\n  bp::class_<game::SphereFit>(\"SphereFit\")\n      .def(\"run\", &game::SphereFit::Run)\n      .def(\"summary\", &game::SphereFit::Summary)\n      .def(\"set_solver_options\", &game::SphereFit::SetSolverOptions);\n}\n", "meta": {"hexsha": "340b59b121e38e0d46d3374e4986057d7cb9a637", "size": 7251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sphere_fit.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/sphere_fit.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/sphere_fit.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": 33.2614678899, "max_line_length": 80, "alphanum_fraction": 0.635912288, "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.5147493554076629}}
{"text": "#include <ancse/cfl_condition.hpp>\n\n#include <Eigen/Dense>\n\n\n// define FVM CFL condition functions defined in cfl_condition.hpp\nFVMCFLCondition::FVMCFLCondition(const Grid& grid,\n                                 const std::shared_ptr<Model>& model,\n                                 double cfl_number)\n    : grid(grid), model(model), cfl_number(cfl_number) {}\n\ndouble FVMCFLCondition::operator() (const Eigen::MatrixXd& u) const\n{\n    const int n_cells= grid.n_cells;\n    const int n_ghost= grid.n_ghost;\n\n    const double dx= grid.dx;\n\n    double a_max= 0.0;\n\n    for (int i= n_ghost; i < n_cells - n_ghost; ++i)\n        a_max= std::max(a_max, model->max_eigenvalue(u.col(i)));\n    \n    return cfl_number * dx / a_max;\n}\n\n// define DG CFL condition functions defined in cfl_condition.hpp\nDGCFLCondition::DGCFLCondition(const Grid& grid,\n                               const std::shared_ptr<Model>& model,\n                               const DGHandler& dg_handler,\n                               double cfl_number)\n    : grid(grid), model(model), dg_handler(dg_handler), cfl_number(cfl_number) {}\n\ndouble DGCFLCondition::operator() (const Eigen::MatrixXd& u) const\n{\n    const int n_cells= grid.n_cells;\n    const int n_ghost= grid.n_ghost;\n\n    const double dx= grid.dx;\n\n    double a_max= 0.0;\n\n    Eigen::MatrixXd u0= dg_handler.build_cell_avg(u);\n\n    for (int i= n_ghost; i < n_cells - n_ghost; ++i)\n        a_max= std::max(a_max, model->max_eigenvalue(u0.col(i)));\n    \n    return cfl_number * dx / a_max;\n}\n\n/// make CFL condition for FVM\nstd::shared_ptr<CFLCondition>\nmake_cfl_condition(const Grid& grid,\n                   const std::shared_ptr<Model>& model,\n                   double cfl_number)\n{\n    // implement this 'factory' for your CFL condition.\n    return std::make_shared<FVMCFLCondition>(grid, model, cfl_number);\n}\n\n/// make CFL condition for DG\nstd::shared_ptr<CFLCondition>\nmake_cfl_condition(const Grid& grid,\n                   const std::shared_ptr<Model>& model,\n                   const DGHandler& dg_handler,\n                   double cfl_number)\n{\n    // implement this 'factory' for your CFL condition.\n    return std::make_shared<DGCFLCondition>(grid, model, dg_handler, cfl_number);\n}\n", "meta": {"hexsha": "444b1eb4fa2a6c322976ac5a6e4c2014c845038f", "size": 2220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series2_workbench/hyp_sys_1d/src/ancse/cfl_condition.cpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_workbench/hyp_sys_1d/src/ancse/cfl_condition.cpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_workbench/hyp_sys_1d/src/ancse/cfl_condition.cpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 31.2676056338, "max_line_length": 81, "alphanum_fraction": 0.6342342342, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.514749353857451}}
{"text": "// $Id: interpolation_test.cpp 1302 2015-06-03 09:24:11Z veralh $\n\n/// \\file Unit tests for the Spline function in geometry\n\n#include <nrlib/geometry/interpolation.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include <math.h>\n#include <algorithm>\n\nusing namespace NRLib;\n\n\nBOOST_AUTO_TEST_CASE( Linear1D )\n{\n  size_t n = 10;\n  double x_start = -1;\n  double x_end   = 3.25;\n  double dx = (x_end-x_start)/(n-1);\n\n  double const_value = -5.3;\n  std::vector<double> x_in(n, -1.0);\n  std::vector<double> y_in_const (n, const_value);\n  std::vector<double> y_in_linear(n, -1.0);\n\n  for (size_t i = 0; i < x_in.size(); ++i){\n    x_in[i] = x_start + i*dx;\n    double x = x_in[i];\n\n    y_in_linear[i] = 10.1 - 0.4*x;\n  }\n\n  n = 37;\n  dx = (x_end - x_start)/(n-1);\n  std::vector<double> x_out(n, -1.0);\n  for (size_t i = 0; i < x_out.size(); ++i){\n    x_out[i] = x_start + i*dx;\n  }\n\n  std::vector<double> y_out_const  = Interpolation::Interpolate1D(x_in, y_in_const,  x_out, \"linear\");\n  std::vector<double> y_out_linear = Interpolation::Interpolate1D(x_in, y_in_linear, x_out, \"linear\");\n\n\n  for(size_t i = 0; i < x_out.size(); ++i )\n  {\n    double x = x_out[i];\n    BOOST_CHECK_CLOSE(y_out_const [i], const_value,  0.01);\n    BOOST_CHECK_CLOSE(y_out_linear[i], 10.1 - 0.4*x, 0.01);\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE( Linear1DWithExtrapolation )\n{\n  size_t n = 10;\n  double x_start = -1;\n  double x_end   = 3.25;\n  double dx = (x_end-x_start)/(n-1);\n\n  double const_value = -5.3;\n  std::vector<double> x_in(n, -1.0);\n  std::vector<double> y_in_const (n, const_value);\n  std::vector<double> y_in_linear(n, -1.0);\n\n  for (size_t i = 0; i < x_in.size(); ++i){\n    x_in[i] = x_start + i*dx;\n    double x = x_in[i];\n\n    y_in_linear[i] = 10.1 - 0.4*x;\n  }\n\n  n = 37;\n  x_start = -10;\n  x_end   = 5.5;\n  dx = (x_end - x_start)/(n-1);\n  std::vector<double> x_out(n, -1.0);\n  for (size_t i = 0; i < x_out.size(); ++i){\n    x_out[i] = x_start + i*dx;\n  }\n\n  std::vector<double> y_out_const  = Interpolation::Interpolate1D(x_in, y_in_const,  x_out, \"linear\");\n  std::vector<double> y_out_linear = Interpolation::Interpolate1D(x_in, y_in_linear, x_out, \"linear\");\n\n\n  for(size_t i = 0; i < x_out.size(); ++i )\n  {\n    double x = x_out[i];\n    BOOST_CHECK_CLOSE(y_out_const [i], const_value,  0.01);\n    BOOST_CHECK_CLOSE(y_out_linear[i], 10.1 - 0.4*x, 0.01);\n  }\n}\n\n\n\nBOOST_AUTO_TEST_CASE( Spline1D )\n{\n  size_t n = 10;\n  double x_start = 0;\n  double x_end   = 2.25;\n  double dx = (x_end-x_start)/(n-1);\n\n  double const_value = 2.4;\n  std::vector<double> x_in(n, -1.0);\n  std::vector<double> y_in_const (n, const_value);\n  std::vector<double> y_in_linear(n, -1.0);\n  std::vector<double> y_in_square(n, -1.0);\n  std::vector<double> y_in_cubic (n, -1.0);\n  std::vector<double> y_in_sin   (n, -1.0);\n  std::vector<double> y_in_sqrt  (n, -1.0);\n\n  for (size_t i = 0; i < x_in.size(); ++i){\n    x_in[i] = x_start + i*dx;\n    double x = x_in[i];\n\n    y_in_linear[i] = -4.4 + 2.3*x;\n    y_in_square[i] = x*x;\n    y_in_cubic [i] = -3 + x + 5.5*x*x - 4.4*x*x*x;\n    y_in_sin   [i] = sin(x);\n    y_in_sqrt  [i] = sqrt(x);\n  }\n\n  n = 37;\n  dx = (x_end - x_start)/(n-1);\n  std::vector<double> x_out(n, -1.0);\n  for (size_t i = 0; i < x_out.size(); ++i){\n    x_out[i] = x_start + i*dx;\n  }\n\n  std::vector<double> y_out_const  = Interpolation::Interpolate1D(x_in, y_in_const,  x_out, \"spline\");\n  std::vector<double> y_out_linear = Interpolation::Interpolate1D(x_in, y_in_linear, x_out, \"spline\");\n  std::vector<double> y_out_square = Interpolation::Interpolate1D(x_in, y_in_square, x_out, \"spline\");\n  std::vector<double> y_out_cubic  = Interpolation::Interpolate1D(x_in, y_in_cubic,  x_out, \"spline\");\n  std::vector<double> y_out_sin    = Interpolation::Interpolate1D(x_in, y_in_sin,    x_out, \"spline\");\n  std::vector<double> y_out_sqrt   = Interpolation::Interpolate1D(x_in, y_in_sqrt,   x_out, \"spline\");\n\n\n  for(size_t i = 0; i < x_out.size(); ++i )\n  {\n    double x = x_out[i];\n    if(std::find(x_in.begin(), x_in.end(), x) != x_in.end())\n    {\n      // Exact at knots\n      BOOST_CHECK_CLOSE(y_out_const [i], const_value,  1.0e-7);\n      BOOST_CHECK_CLOSE(y_out_linear[i], -4.4 + 2.3*x, 1.0e-7);\n      BOOST_CHECK_CLOSE(y_out_square[i], x*x,          1.0e-7);\n      BOOST_CHECK_CLOSE(y_out_cubic [i], -3 + x + 5.5*x*x - 4.4*x*x*x, 1.0e-7);\n      BOOST_CHECK_CLOSE(y_out_sin   [i], sin(x),       1.0e-7);\n      BOOST_CHECK_CLOSE(y_out_sqrt  [i], sqrt(x),      1.0e-7);\n    }\n    else if(x > x_in[1])\n    {\n      // Not comparing in first interval\n      BOOST_CHECK_CLOSE(y_out_const [i], const_value,  0.1);\n      BOOST_CHECK_CLOSE(y_out_linear[i], -4.4 + 2.3*x, 0.1);\n      BOOST_CHECK_CLOSE(y_out_square[i], x*x,          2.0);\n      BOOST_CHECK_CLOSE(y_out_cubic [i], -3 + x + 5.5*x*x - 4.4*x*x*x, 1.0);\n      BOOST_CHECK_CLOSE(y_out_sin   [i], sin(x),       2.0);\n      BOOST_CHECK_CLOSE(y_out_sqrt  [i], sqrt(x),      2.8);\n    }\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE( Spline1DExtrapolation)\n{\n\n  size_t n = 11;\n  double x_start = -1;\n  double x_end   = 4;\n  double dx = (x_end-x_start)/(n-1);\n\n  std::vector<double> x_in(n, -1.0);\n  std::vector<double> y_in_cubic (n, -1.0);\n  std::vector<double> y_in_sin   (n, -1.0);\n\n  for (size_t i = 0; i < x_in.size(); ++i){\n    x_in[i] = x_start + i*dx;\n    double x = x_in[i];\n\n    y_in_cubic[i] = -3 + x + 5.5*x*x - 4.4*x*x*x;;\n    y_in_sin[i]   = sin(x);\n  }\n\n  n = 61;\n  x_start = -6;\n  x_end   = 9;\n  dx = (x_end - x_start)/(n-1);\n  std::vector<double> x_out(n, -1.0);\n  for (size_t i = 0; i < x_out.size(); ++i){\n    x_out[i] = x_start + i*dx;\n  }\n\n  std::vector<double> y_out_cubic_extrap = Interpolation::Interpolate1D(x_in, y_in_cubic,  x_out, \"spline\", 0.0);\n  std::vector<double> y_out_sin_extrap   = Interpolation::Interpolate1D(x_in, y_in_sin,    x_out, \"spline\", 0.0);\n\n  for(size_t i = 0; i < x_out.size(); ++i ){\n    double x = x_out[i];\n\n    // Check for equality to pre-set extrapapolation value outside defined intervals\n    if(x < x_in[0] || x > x_in[x_in.size()-1])\n    {\n      BOOST_CHECK_EQUAL(y_out_cubic_extrap [i], 0.0);\n      BOOST_CHECK_EQUAL(y_out_sin_extrap   [i], 0.0);\n    }\n\n    // Check for equality at the knots\n    else if(std::find(x_in.begin(), x_in.end(), x) != x_in.end())\n    {\n      // Exact at knots\n      BOOST_CHECK_CLOSE(y_out_cubic_extrap [i], -3 + x + 5.5*x*x - 4.4*x*x*x, 1.0e-7);\n      BOOST_CHECK_CLOSE(y_out_sin_extrap   [i], sin(x),                       1.0e-7);\n\n    }\n\n    // Check for close value inside defined intervals\n    else if(x > x_in[0] && x < x_in[2]) {\n      // In first two interval we allow larger mismatch\n      BOOST_CHECK_CLOSE(y_out_cubic_extrap [i], -3 + x + 5.5*x*x - 4.4*x*x*x, 36.0);\n      BOOST_CHECK_CLOSE(y_out_sin_extrap   [i], sin(x),                       20.0);\n    }\n\n    else {\n      BOOST_CHECK_CLOSE(y_out_cubic_extrap [i], -3 + x + 5.5*x*x - 4.4*x*x*x, 1.6);\n      BOOST_CHECK_CLOSE(y_out_sin_extrap   [i], sin(x),                       2.2);\n    }\n\n  }\n}\n", "meta": {"hexsha": "23457a6ccb544cba5c994009eff807a2fba9fe6b", "size": 6949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nrlib/geometry/unittests/interpolation_test.cpp", "max_stars_repo_name": "equinor/gaussianfft", "max_stars_repo_head_hexsha": "3865dcd02fdba566be7be662da77f653950b51ac", "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/nrlib/geometry/unittests/interpolation_test.cpp", "max_issues_repo_name": "equinor/gaussianfft", "max_issues_repo_head_hexsha": "3865dcd02fdba566be7be662da77f653950b51ac", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-24T14:03:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-24T14:03:33.000Z", "max_forks_repo_path": "src/nrlib/geometry/unittests/interpolation_test.cpp", "max_forks_repo_name": "equinor/gaussianfft", "max_forks_repo_head_hexsha": "3865dcd02fdba566be7be662da77f653950b51ac", "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.3449781659, "max_line_length": 113, "alphanum_fraction": 0.6010936825, "num_tokens": 2508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5147493459774722}}
{"text": "\n\n#include <NTL/FFT.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\nlong NumFFTPrimes = 0;\n\n\n\nlong *FFTPrime = 0;\nlong **RootTable = 0;\nlong **RootInvTable = 0;\nlong **TwoInvTable = 0;\ndouble *FFTPrimeInv = 0;\n\n\nstatic\nlong IsFFTPrime(long n, long& w)\n{\n   long  m, x, y, z;\n   long j, k;\n\n   if (n % 3 == 0) return 0;\n\n   if (n % 5 == 0) return 0;\n\n   if (n % 7 == 0) return 0;\n   \n   m = n - 1;\n   k = 0;\n   while ((m & 1) == 0) {\n      m = m >> 1;\n      k++;\n   }\n\n   for (;;) {\n      x = RandomBnd(n);\n\n      if (x == 0) continue;\n      z = PowerMod(x, m, n);\n      if (z == 1) continue;\n\n      x = z;\n      j = 0;\n      do {\n         y = z;\n         z = MulMod(y, y, n);\n         j++;\n      } while (j != k && z != 1);\n\n      if (z != 1 || y !=  n-1) return 0;\n\n      if (j == k) \n         break;\n   }\n\n   /* x^{2^k} = 1 mod n, x^{2^{k-1}} = -1 mod n */\n\n   long TrialBound;\n\n   TrialBound = m >> k;\n   if (TrialBound > 0) {\n      if (!ProbPrime(n, 5)) return 0;\n   \n      /* we have to do trial division by special numbers */\n   \n      TrialBound = SqrRoot(TrialBound);\n   \n      long a, b;\n   \n      for (a = 1; a <= TrialBound; a++) {\n         b = (a << k) + 1;\n         if (n % b == 0) return 0; \n      }\n   }\n\n   /* n is an FFT prime */\n\n   for (j = NTL_FFTMaxRoot; j < k; j++)\n      x = MulMod(x, x, n);\n\n   w = x;\n   return 1;\n}\n\n\nstatic\nvoid NextFFTPrime(long& q, long& w)\n{\n   static long m = NTL_FFTMaxRootBnd + 1;\n   static long k = 0;\n\n   long t, cand;\n\n   for (;;) {\n      if (k == 0) {\n         m--;\n         if (m < 5) Error(\"ran out of FFT primes\");\n         k = 1L << (NTL_SP_NBITS-m-2);\n      }\n\n      k--;\n\n      cand = (1L << (NTL_SP_NBITS-1)) + (k << (m+1)) + (1L << m) + 1;\n\n      if (!IsFFTPrime(cand, t)) continue;\n      q = cand;\n      w = t;\n      return;\n   }\n}\n\n\nlong CalcMaxRoot(long p)\n{\n   p = p-1;\n   long k = 0;\n   while ((p & 1) == 0) {\n      p = p >> 1;\n      k++;\n   }\n\n   if (k > NTL_FFTMaxRoot)\n      return NTL_FFTMaxRoot;\n   else\n      return k; \n}\n\n\nvoid UseFFTPrime(long index)\n{\n   if (index < 0 || index > NumFFTPrimes)\n      Error(\"invalid FFT prime index\");\n\n   if (index < NumFFTPrimes) return;\n\n   long q, w;\n\n   NextFFTPrime(q, w);\n\n   long mr = CalcMaxRoot(q);\n\n   // tables are allocated in increments of 100\n\n   if (index == 0) { \n      FFTPrime = (long *) NTL_MALLOC(100, sizeof(long), 0);\n      RootTable = (long **) NTL_MALLOC(100, sizeof(long *), 0);\n      RootInvTable = (long **) NTL_MALLOC(100, sizeof(long *), 0);\n      TwoInvTable = (long **) NTL_MALLOC(100, sizeof(long *), 0);\n      FFTPrimeInv = (double *) NTL_MALLOC(100, sizeof(double), 0);\n   }\n   else if ((index % 100) == 0) {\n      FFTPrime = (long *) NTL_REALLOC(FFTPrime, index+100, sizeof(long), 0);\n      RootTable = (long **) \n                  NTL_REALLOC(RootTable, index+100, sizeof(long *), 0);\n      RootInvTable = (long **) \n                     NTL_REALLOC(RootInvTable, index+100, sizeof(long *), 0);\n      TwoInvTable = (long **) \n                    NTL_REALLOC(TwoInvTable, index+100, sizeof(long *), 0);\n      FFTPrimeInv = (double *) \n                    NTL_REALLOC(FFTPrimeInv, index+100, sizeof(double), 0);\n   }\n\n   if (!FFTPrime || !RootTable || !RootInvTable || !TwoInvTable ||\n       !FFTPrimeInv) \n      Error(\"out of space\");\n\n   FFTPrime[index] = q;\n\n   long *rt, *rit, *tit;\n\n   if (!(rt = RootTable[index] = (long*) NTL_MALLOC(mr+1, sizeof(long), 0)))\n      Error(\"out of space\");\n   if (!(rit = RootInvTable[index] = (long*) NTL_MALLOC(mr+1, sizeof(long), 0)))\n      Error(\"out of space\");\n   if (!(tit = TwoInvTable[index] = (long*) NTL_MALLOC(mr+1, sizeof(long), 0)))\n      Error(\"out of space\");\n\n   long j;\n   long t;\n\n   rt[mr] = w;\n   for (j = mr-1; j >= 0; j--)\n      rt[j] = MulMod(rt[j+1], rt[j+1], q);\n\n   rit[mr] = InvMod(w, q);\n   for (j = mr-1; j >= 0; j--)\n      rit[j] = MulMod(rit[j+1], rit[j+1], q);\n\n   t = InvMod(2, q);\n   tit[0] = 1;\n   for (j = 1; j <= mr; j++)\n      tit[j] = MulMod(tit[j-1], t, q);\n\n   FFTPrimeInv[index] = 1/double(q);\n\n   NumFFTPrimes++;\n}\n   \n\nstatic\nlong RevInc(long a, long k)\n{\n   long j, m;\n\n   j = k; \n   m = 1L << (k-1);\n\n   while (j && (m & a)) {\n      a ^= m;\n      m >>= 1;\n      j--;\n   }\n   if (j) a ^= m;\n   return a;\n}\n\nstatic\nvoid BitReverseCopy(long *A, const long *a, long k)\n{\n   static long* mem[NTL_FFTMaxRoot+1];\n\n   long n = 1L << k;\n   long* rev;\n   long i, j;\n\n   rev = mem[k];\n   if (!rev) {\n      rev = mem[k] = (long *) NTL_MALLOC(n, sizeof(long), 0);\n      if (!rev) Error(\"out of memory in BitReverseCopy\");\n      for (i = 0, j = 0; i < n; i++, j = RevInc(j, k))\n         rev[i] = j;\n   }\n\n   for (i = 0; i < n; i++)\n      A[rev[i]] = a[i];\n}\n\n\n\n\n\n/*\n * Our FFT is based on the routine in Cormen, Leiserson, Rivest, and Stein.\n * For very large inputs, it should be relatively cache friendly.\n * The inner loop has been unrolled and pipelined, to exploit any\n * low-level parallelism in the machine.\n */\n\n\n\nvoid FFT(long* A, const long* a, long k, long q, const long* root)\n\n// performs a 2^k-point convolution modulo q\n\n{\n   if (k <= 1) {\n      if (k == 0) {\n\t A[0] = a[0];\n\t return;\n      }\n      if (k == 1) {\n\t A[0] = AddMod(a[0], a[1], q);\n\t A[1] = SubMod(a[0], a[1], q);\n\t return;\n      }\n   }\n\n   // assume k > 1\n\n   \n\n   static long tab_size = 0;\n   static long *wtab = 0;\n   static mulmod_precon_t *wqinvtab = 0;\n\n   if (!tab_size) {\n      tab_size = k;\n\n      wtab = (long *) NTL_MALLOC(1L << (k-2), sizeof(long), 0);\n      wqinvtab = (mulmod_precon_t *) \n                 NTL_MALLOC(1L << (k-2), sizeof(mulmod_precon_t), 0);\n      if (!wtab || !wqinvtab) Error(\"out of space\");\n   }\n   else if (tab_size < k) {\n      tab_size = k;\n\n      wtab = (long *) NTL_REALLOC(wtab, 1L << (k-2), sizeof(long), 0);\n      wqinvtab = (mulmod_precon_t *) \n                 NTL_REALLOC(wqinvtab, 1L << (k-2), sizeof(mulmod_precon_t), 0);\n      if (!wtab || !wqinvtab) Error(\"out of space\");\n   }\n\n\n   double qinv = 1/((double) q);\n\n   wtab[0] = 1;\n   wqinvtab[0] = PrepMulModPrecon(1, q, qinv);\n\n\n   BitReverseCopy(A, a, k);\n\n   long n = 1L << k;\n\n   long s, m, m_half, m_fourth, i, j, t, u, t1, u1, uu, uu1, tt, tt1;\n\n   long w;\n   mulmod_precon_t wqinv;\n\n   // s = 1\n\n   for (i = 0; i < n; i += 2) {\n      t = A[i + 1];\n      u = A[i];\n      A[i] = AddMod(u, t, q);\n      A[i+1] = SubMod(u, t, q);\n   }\n\n   \n  \n   for (s = 2; s < k; s++) {\n      m = 1L << s;\n      m_half = 1L << (s-1);\n      m_fourth = 1L << (s-2);\n\n      // prepare wtab...\n\n      w = root[s];\n      wqinv = PrepMulModPrecon(w, q, qinv);\n\n      for (i = m_half-1, j = m_fourth-1; i >= 0; i -= 2, j--) {\n         wtab[i-1] = wtab[j];\n         wqinvtab[i-1] = wqinvtab[j];\n         wtab[i] = MulModPrecon(wtab[i-1], w, q, wqinv);\n         wqinvtab[i] = PrepMulModPrecon(wtab[i], q, qinv);\n      }\n\n      for (i = 0; i < n; i+= m) {\n\n          \n         t = A[i + m_half];\n         u = A[i];\n         t1 = MulModPrecon(A[i + 1+ m_half], w, q, wqinv);\n         u1 = A[i+1];\n\n         for (j = 0; j < m_half-2; j += 2) {\n            tt = MulModPrecon(A[i + j + 2 + m_half], wtab[j+2], q, wqinvtab[j+2]);\n            uu = A[i + j + 2];\n\n\n            tt1 = MulModPrecon(A[i + j + 3+ m_half], wtab[j+3], q, wqinvtab[j+3]);\n            uu1 = A[i + j + 3];\n\n            A[i + j] = AddMod(u, t, q);\n            A[i + j + m_half] = SubMod(u, t, q);\n            A[i + j + 1] = AddMod(u1, t1, q);\n            A[i + j + 1 + m_half] = SubMod(u1, t1, q);\n            t = tt;\n            t1 = tt1;\n            u = uu;\n            u1 = uu1;\n         }\n\n\n         A[i + j] = AddMod(u, t, q);\n         A[i + j + m_half] = SubMod(u, t, q);\n         A[i + j + 1] = AddMod(u1, t1, q);\n         A[i + j + 1 + m_half] = SubMod(u1, t1, q);\n\n\n\n      }\n   }\n\n\n   // s == k...special case\n\n   m = 1L << s;\n   m_half = 1L << (s-1);\n   m_fourth = 1L << (s-2);\n\n\n   w = root[s];\n   wqinv = PrepMulModPrecon(w, q, qinv);\n\n   // j = 0, 1\n\n   t = A[m_half];\n   u = A[0];\n   t1 = MulModPrecon(A[1+ m_half], w, q, wqinv);\n   u1 = A[1];\n\n   A[0] = AddMod(u, t, q);\n   A[m_half] = SubMod(u, t, q);\n   A[1] = AddMod(u1, t1, q);\n   A[1 + m_half] = SubMod(u1, t1, q);\n\n   for (j = 2; j < m_half; j += 2) {\n      t = MulModPrecon(A[j + m_half], wtab[j >> 1], q, wqinvtab[j >> 1]);\n      u = A[j];\n      t1 = MulModPrecon(A[j + 1+ m_half], wtab[j >> 1], q, \n                        wqinvtab[j >> 1]);\n      t1 = MulModPrecon(t1, w, q, wqinv);\n      u1 = A[j + 1];\n\n      A[j] = AddMod(u, t, q);\n      A[j + m_half] = SubMod(u, t, q);\n      A[j + 1] = AddMod(u1, t1, q);\n      A[j + 1 + m_half] = SubMod(u1, t1, q);\n     \n   }\n}\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "7a11df4dc051d0d90b0bd41cb8e84905aebbb0ae", "size": 8585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/src/FFT.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/src/FFT.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/src/FFT.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 20.4892601432, "max_line_length": 82, "alphanum_fraction": 0.4674432149, "num_tokens": 3217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5147345832401888}}
{"text": "/*********************                                                        */\n/*! \\file sets_translate.cpp\n ** \\verbatim\n ** Original author: Kshitij Bansal\n ** Major contributors: none\n ** Minor contributors (to current version): none\n ** This file is part of the CVC4 project.\n ** Copyright (c) 2009-2014  New York University and The University of Iowa\n ** See the file COPYING in the top-level source directory for licensing\n ** information.\\endverbatim\n **\n ** \\brief [[ Add one-line brief description here ]]\n **\n ** [[ Add lengthier description here ]]\n ** \\todo document this file\n **/\n\n#include <string>\n#include <iostream>\n#include <typeinfo>\n#include <cassert>\n#include <vector>\n#include <boost/algorithm/string.hpp> // include Boost, a C++ library\n\n\n#include \"options/options.h\"\n#include \"expr/expr.h\"\n#include \"theory/logic_info.h\"\n#include \"expr/command.h\"\n#include \"parser/parser.h\"\n#include \"parser/parser_builder.h\"\n\nusing namespace std;\nusing namespace CVC4;\nusing namespace CVC4::parser;\nusing namespace CVC4::options;\n\nbool nonsense(char c) { return !isalnum(c); } \n\n#ifdef ENABLE_AXIOMS\nconst bool enableAxioms = true;\n#else\nconst bool enableAxioms = false;\n#endif\n\nstring setaxioms[] = {\n  \"(declare-fun memberHOLDA (HOLDB (Set HOLDB)) Bool)\",\n  \"\",\n  \"(declare-fun unionHOLDA ((Set HOLDB) (Set HOLDB)) (Set HOLDB))\",\n  \"(assert (forall ((?X (Set HOLDB)) (?Y (Set HOLDB)) (?x HOLDB))\",\n  \"                (= (memberHOLDA ?x (unionHOLDA ?X ?Y))\",\n  \"                     (or (memberHOLDA ?x ?X) (memberHOLDA ?x ?Y))\",\n  \"                ) ) )\",\n  \"\",\n  \"\",\n  \"(declare-fun intersectionHOLDA ((Set HOLDB) (Set HOLDB)) (Set HOLDB))\",\n  \"(assert (forall ((?X (Set HOLDB)) (?Y (Set HOLDB)) (?x HOLDB))\",\n  \"                (= (memberHOLDA ?x (intersectionHOLDA ?X ?Y))\",\n  \"                     (and (memberHOLDA ?x ?X) (memberHOLDA ?x ?Y))\",\n  \"                ) ) )\",\n  \"\",\n  \"(declare-fun setminusHOLDA ((Set HOLDB) (Set HOLDB)) (Set HOLDB))\",\n  \"(assert (forall ((?X (Set HOLDB)) (?Y (Set HOLDB)) (?x HOLDB))\",\n  \"                (= (memberHOLDA ?x (setminusHOLDA ?X ?Y))\",\n  \"                     (and (memberHOLDA ?x ?X) (not (memberHOLDA ?x ?Y)))\",\n  \"                ) ) )\",\n  \"\",\n  \"(declare-fun singletonHOLDA (HOLDB) (Set HOLDB))\",\n  \"(assert (forall ((?x HOLDB) (?y HOLDB))\",\n  \"                (= (memberHOLDA ?x (singletonHOLDA ?y))\",\n  \"                     (= ?x ?y)\",\n  \"                ) ) )\",\n  \"\",\n  \"(declare-fun emptysetHOLDA () (Set HOLDB))\",\n  \"(assert (forall ((?x HOLDB)) (not (memberHOLDA ?x emptysetHOLDA)) ) )\",\n  \"\",\n  \"(define-fun subsetHOLDA ((X (Set HOLDB)) (Y (Set HOLDB))) Bool (= (unionHOLDA X Y) Y))\",\n  \"\"\n};\n\nclass Mapper {\n  set< Type > setTypes;\n  map< Type, Type > mapTypes;\n  map< pair<Type, Kind>, Expr > setoperators;\n  hash_map< Expr, Expr, ExprHashFunction > substitutions;\n  ostringstream sout;\n  ExprManager* em;\n  int depth;\n\n  Expr add(SetType t, Expr e) {\n\n    if(setTypes.find(t) == setTypes.end() ) {\n      // mark as processed\n      setTypes.insert(t);\n\n      Type elementType = t.getElementType();\n      string elementTypeAsString = elementType.toString();\n      remove_if(elementTypeAsString.begin(), elementTypeAsString.end(), nonsense);\n\n      // define-sort\n      ostringstream oss_name;\n      oss_name << Expr::setlanguage(language::output::LANG_SMTLIB_V2)\n               << \"(Set \" << elementType << \")\";\n      string name = oss_name.str();\n      Type newt = em->mkArrayType(t.getElementType(), em->booleanType());\n      mapTypes[t] = newt;\n\n      // diffent types\n      vector<Type> t_t;\n      t_t.push_back(t);\n      t_t.push_back(t);\n      vector<Type> elet_t;\n      elet_t.push_back(elementType);\n      elet_t.push_back(t);\n\n      if(!enableAxioms)\n        sout << \"(define-fun emptyset\" << elementTypeAsString << \"    \"\n             << \" ()\"\n             << \" \" << name\n             << \" ( (as const \" << name << \") false ) )\" << endl;\n      setoperators[ make_pair(t, kind::EMPTYSET) ] =\n        em->mkVar( std::string(\"emptyset\") + elementTypeAsString,\n                   t);\n\n      if(!enableAxioms)\n        sout << \"(define-fun singleton\" << elementTypeAsString << \"     \"\n             << \" ( (x \" << elementType << \") )\"\n             << \" \" << name << \"\"\n             << \" (store emptyset\" << elementTypeAsString << \" x true) )\" << endl;\n      setoperators[ make_pair(t, kind::SINGLETON) ] =\n        em->mkVar( std::string(\"singleton\") + elementTypeAsString,\n                   em->mkFunctionType( elementType, t ) );\n\n      if(!enableAxioms)\n        sout << \"(define-fun union\" << elementTypeAsString << \"       \"\n             << \" ( (s1 \" << name << \") (s2 \" << name << \") )\"\n             << \" \" << name << \"\"\n             << \" ((_ map or) s1 s2))\" << endl;\n      setoperators[ make_pair(t, kind::UNION) ] =\n        em->mkVar( std::string(\"union\") + elementTypeAsString,\n                   em->mkFunctionType( t_t, t ) );\n\n      if(!enableAxioms)\n        sout << \"(define-fun intersection\" << elementTypeAsString << \"\"\n             << \" ( (s1 \" << name << \") (s2 \" << name << \") )\"\n             << \" \" << name << \"\"\n             << \" ((_ map and) s1 s2))\" << endl;\n      setoperators[ make_pair(t, kind::INTERSECTION) ] =\n        em->mkVar( std::string(\"intersection\") + elementTypeAsString,\n                   em->mkFunctionType( t_t, t ) );\n\n      if(!enableAxioms)\n        sout << \"(define-fun setminus\" << elementTypeAsString << \"    \"\n             << \" ( (s1 \" << name << \") (s2 \" << name << \") )\"\n             << \" \" << name << \"\"\n             << \" (intersection\" << elementTypeAsString << \" s1 ((_ map not) s2)))\" << endl;\n      setoperators[ make_pair(t, kind::SETMINUS) ] =\n        em->mkVar( std::string(\"setminus\") + elementTypeAsString,\n                   em->mkFunctionType( t_t, t ) );\n\n      if(!enableAxioms)\n        sout << \"(define-fun in\" << elementTypeAsString << \"          \"\n             << \" ( (x \" << elementType << \")\" << \" (s \" << name << \"))\"\n             << \" Bool\"\n             << \" (select s x) )\" << endl;\n      setoperators[ make_pair(t, kind::MEMBER) ] =\n        em->mkVar( std::string(\"member\") + elementTypeAsString,\n                   em->mkPredicateType( elet_t ) );\n\n      if(!enableAxioms)\n        sout << \"(define-fun subset\" << elementTypeAsString << \"    \"\n             << \" ( (s1 \" << name << \") (s2 \" << name << \") )\"\n             << \" Bool\"\n             <<\" (= emptyset\" << elementTypeAsString << \" (setminus\" << elementTypeAsString << \" s1 s2)) )\" << endl;\n      setoperators[ make_pair(t, kind::SUBSET) ] =\n        em->mkVar( std::string(\"subset\") + elementTypeAsString,\n                   em->mkPredicateType( t_t ) );\n\n      if(enableAxioms) {\n        int N = sizeof(setaxioms) / sizeof(setaxioms[0]);\n        for(int i = 0; i < N; ++i) {\n          string s = setaxioms[i];\n          ostringstream oss; oss << Expr::setlanguage(language::output::LANG_SMTLIB_V2) << elementType;\n          boost::replace_all(s, \"HOLDA\", elementTypeAsString);\n          boost::replace_all(s, \"HOLDB\", oss.str());\n          if( s == \"\" ) continue;\n          sout << s << endl;\n        }\n      }\n\n    }\n    Expr ret;\n    if(e.getKind() == kind::EMPTYSET) {\n      ret = setoperators[ make_pair(t, e.getKind()) ];\n    } else {\n      vector<Expr> children = e.getChildren();\n      children.insert(children.begin(), setoperators[ make_pair(t, e.getKind()) ]);\n      ret = em->mkExpr(kind::APPLY, children);\n    }\n    // cout << \"returning \" << ret  << endl;\n    return ret;\n  }\n\npublic:\n  Mapper(ExprManager* e) : em(e),depth(0) {\n    sout << Expr::setlanguage(language::output::LANG_SMTLIB_V2);\n  }\n\n  void defineSetSort() {\n    if(setTypes.empty()) {\n      cout << \"(define-sort Set (X) (Array X Bool) )\" << endl;\n    }\n  }\n\n\n  Expr collectSortsExpr(Expr e)\n  {\n    if(substitutions.find(e) != substitutions.end()) {\n      return substitutions[e];\n    }\n    ++depth;\n    Expr old_e = e;\n    for(unsigned i = 0; i < e.getNumChildren(); ++i) {\n      collectSortsExpr(e[i]);\n    }\n    e = e.substitute(substitutions);\n    // cout << \"[debug] \" << e << \" \" << e.getKind() << \" \" << theory::kindToTheoryId(e.getKind()) << endl;\n    if(theory::kindToTheoryId(e.getKind()) == theory::THEORY_SETS) {\n      SetType t = SetType(e.getType().isBoolean() ? e[1].getType() : e.getType());\n      substitutions[e] = add(t, e);\n      e = e.substitute(substitutions);\n    }\n    substitutions[old_e] = e;\n    // cout << \";\"; for(int i = 0; i < depth; ++i) cout << \" \"; cout << old_e << \" => \" << e << endl;\n    --depth;\n    return e;\n  }\n\n  void dump() {\n    cout << sout.str();\n  }\n};\n\n\nint main(int argc, char* argv[]) \n{\n\n  try {\n\n    // Get the filename \n    string input;\n    if(argc > 1) input = string(argv[1]);\n    else input = \"<stdin>\";\n\n    // Create the expression manager\n    Options options;\n    options.set(inputLanguage, language::input::LANG_SMTLIB_V2);\n    cout << Expr::setlanguage(language::output::LANG_SMTLIB_V2);\n    // cout << Expr::dag(0);\n    ExprManager exprManager(options);\n\n    Mapper m(&exprManager);\n  \n    // Create the parser\n    ParserBuilder parserBuilder(&exprManager, input, options);\n    if(input == \"<stdin>\") parserBuilder.withStreamInput(cin);\n    Parser* parser = parserBuilder.build();\n  \n    // Variables and assertions\n    vector<string> variables;\n    vector<string> info_tags;\n    vector<string> info_data;\n    vector<Expr> assertions;\n  \n    Command* cmd = NULL;\n    CommandSequence commandsSequence;\n    bool logicisset = false;\n\n    while ((cmd = parser->nextCommand())) {\n\n      // till logic is set, don't do any modifications\n      if(!parser->logicIsSet()) {\n        cout << (*cmd) << endl;\n        delete cmd;\n        continue;\n      }\n\n      // transform set-logic command, if there is one\n      SetBenchmarkLogicCommand* setlogic = dynamic_cast<SetBenchmarkLogicCommand*>(cmd);\n      if(setlogic) {\n\tLogicInfo logicinfo(setlogic->getLogic());\n\tif(!logicinfo.isTheoryEnabled(theory::THEORY_SETS)) {\n\t  cerr << \"Sets theory not enabled. Stopping translation.\" << endl;\n\t  return 0;\n\t}\n        logicinfo = logicinfo.getUnlockedCopy();\n        if(enableAxioms) {\n          logicinfo.enableQuantifiers();\n          logicinfo.lock();\n          if(!logicinfo.hasEverything()) {\n            (logicinfo = logicinfo.getUnlockedCopy()).disableTheory(theory::THEORY_SETS);\n            logicinfo.lock();\n            cout << SetBenchmarkLogicCommand(logicinfo.getLogicString()) << endl;\n          }\n        } else {\n          logicinfo.enableTheory(theory::THEORY_ARRAY);\n          // we print logic string only for Quantifiers, for Z3 stuff\n          // we don't set the logic\n        }\n\n        delete cmd;\n        continue;\n      }\n\n      // if we reach here, logic is set by now, so can define our sort\n      if( !logicisset ) {\n        logicisset = true;\n        m.defineSetSort();\n      }\n\n      // declare/define-sort commands are printed immediately\n      DeclareTypeCommand* declaresort = dynamic_cast<DeclareTypeCommand*>(cmd);\n      DefineTypeCommand* definesort = dynamic_cast<DefineTypeCommand*>(cmd);\n      if(declaresort || definesort) {\n        cout << *cmd << endl;\n        delete cmd;\n        continue;\n      }\n\n      // other commands are queued up, while replacing with new function symbols\n      AssertCommand* assert = dynamic_cast<AssertCommand*>(cmd);\n      DeclareFunctionCommand* declarefun = dynamic_cast<DeclareFunctionCommand*>(cmd);\n      DefineFunctionCommand* definefun = dynamic_cast<DefineFunctionCommand*>(cmd);\n\n      Command* new_cmd = NULL;\n      if(assert) {\n        Expr newexpr = m.collectSortsExpr(assert->getExpr());\n        new_cmd = new AssertCommand(newexpr);\n      } else if(declarefun) {\n        Expr newfunc = m.collectSortsExpr(declarefun->getFunction());\n        new_cmd = new DeclareFunctionCommand(declarefun->getSymbol(), newfunc, declarefun->getType());\n      } else if(definefun) {\n        Expr newfunc = m.collectSortsExpr(definefun->getFunction());\n        Expr newformula = m.collectSortsExpr(definefun->getFormula());\n        new_cmd = new DefineFunctionCommand(definefun->getSymbol(), newfunc, definefun->getFormals(), newformula);\n      }\n\n      if(new_cmd == NULL) {\n        commandsSequence.addCommand(cmd);\n      } else {\n        commandsSequence.addCommand(new_cmd);\n        delete cmd;\n      }\n\n    }\n\n    m.dump();\n    cout << commandsSequence;\n    \n  \n    // Get rid of the parser\n    //delete parser;\n  } catch (Exception& e) {\n    cerr << e << endl;\n  }\n}\n", "meta": {"hexsha": "d214b6ab8b6b5f7c970aa79a52a60f5d7097e2f4", "size": 12471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cvc4-mc/cvc4-1.4/examples/sets-translate/sets_translate.cpp", "max_stars_repo_name": "mistryrakesh/SMTApproxMC", "max_stars_repo_head_hexsha": "7c97e10c46c66e52c4e8972259610953c3357695", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cvc4-mc/cvc4-1.4/examples/sets-translate/sets_translate.cpp", "max_issues_repo_name": "mistryrakesh/SMTApproxMC", "max_issues_repo_head_hexsha": "7c97e10c46c66e52c4e8972259610953c3357695", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cvc4-mc/cvc4-1.4/examples/sets-translate/sets_translate.cpp", "max_forks_repo_name": "mistryrakesh/SMTApproxMC", "max_forks_repo_head_hexsha": "7c97e10c46c66e52c4e8972259610953c3357695", "max_forks_repo_licenses": ["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.9809264305, "max_line_length": 116, "alphanum_fraction": 0.5620238954, "num_tokens": 3281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5146778076758801}}
{"text": "#include <Engine/MeshEdit/MinSurf.h>\n\n#include <Engine/Primitive/TriMesh.h>\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n\nusing namespace Ubpa;\n\nusing namespace std;\nusing namespace Eigen;\n\nMinSurf::MinSurf(Ptr<TriMesh> triMesh)\n\t: heMesh(make_shared<HEMesh<V>>())\n{\n\tInit(triMesh);\n}\n\nvoid MinSurf::Clear() {\n\theMesh->Clear();\n\ttriMesh = nullptr;\n}\n\nbool MinSurf::Init(Ptr<TriMesh> triMesh) {\n\tClear();\n\n\tif (triMesh == nullptr)\n\t\treturn true;\n\n\tif (triMesh->GetType() == TriMesh::INVALID) {\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is invalid\\n\");\n\t\treturn false;\n\t}\n\n\t// init half-edge structure\n\tsize_t nV = triMesh->GetPositions().size();\n\tvector<vector<size_t>> triangles;\n\ttriangles.reserve(triMesh->GetTriangles().size());\n\tfor (auto triangle : triMesh->GetTriangles())\n\t\ttriangles.push_back({ triangle->idx[0], triangle->idx[1], triangle->idx[2] });\n\theMesh->Reserve(nV);\n\theMesh->Init(triangles);\n\n\tif (!heMesh->IsTriMesh() || !heMesh->HaveBoundary()) {\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is not a triangle mesh or hasn't a boundaries\\n\");\n\t\theMesh->Clear();\n\t\treturn false;\n\t}\n\n\t// triangle mesh's positions ->  half-edge structure's positions\n\tfor (int i = 0; i < nV; i++) {\n\t\tauto v = heMesh->Vertices().at(i);\n\t\tv->pos = triMesh->GetPositions()[i].cast_to<vecf3>();\n\t}\n\n\tthis->triMesh = triMesh;\n\treturn true;\n}\n\nbool MinSurf::Run() {\n\tif (heMesh->IsEmpty() || !triMesh) {\n\t\tprintf(\"ERROR::MinSurf::Run\\n\"\n\t\t\t\"\\t\"\"heMesh->IsEmpty() || !triMesh\\n\");\n\t\treturn false;\n\t}\n\n\tMinimize();\n\n\t// half-edge structure -> triangle mesh\n\tsize_t nV = heMesh->NumVertices();\n\tsize_t nF = heMesh->NumPolygons();\n\tvector<pointf3> positions;\n\tvector<unsigned> indice;\n\tpositions.reserve(nV);\n\tindice.reserve(3 * nF);\n\tfor (auto v : heMesh->Vertices())\n\t\tpositions.push_back(v->pos.cast_to<pointf3>());\n\tfor (auto f : heMesh->Polygons()) { // f is triangle\n\t\tfor (auto v : f->BoundaryVertice()) // vertices of the triangle\n\t\t\tindice.push_back(static_cast<unsigned>(heMesh->Index(v)));\n\t}\n\n\ttriMesh->Init(indice, positions);\n\n\treturn true;\n}\n\nvoid MinSurf::Minimize() {\n\t// First, detect and fix boundary\n\trandom_set<V*> boundary_points;\n\trandom_set<V*> inner_points;\n\n\tauto boundaries = this->heMesh->Boundaries();\n\tif (boundaries.size() != 1) {\n\t\tcout << \"ERROR::MinSurf::Minimize:\" << endl\n\t\t\t << \"\\t\" << \"got boundaries = \" << boundaries.size()\n\t\t\t << \" (expect 1)\" << endl;\n\t\treturn;\n\t}\n\n\tfor (auto v: boundaries[0]) {\n\t\tboundary_points.insert(v->Origin());\n\t}\n\n\tfor (auto v: heMesh->Vertices()) {\n\t\tif (!boundary_points.contains(v)) {\n\t\t\tinner_points.insert(v);\n\t\t}\n\t}\n\t// Build sparse matrix\n\tsize_t n = inner_points.size();\n\tSparseMatrix<float> coeff_mat(n, n);\n\tcoeff_mat.setZero();\n\tVectorXf b_vec_x = VectorXf::Zero(n);\n\tVectorXf b_vec_y = VectorXf::Zero(n);\n\tVectorXf b_vec_z = VectorXf::Zero(n);\n\n\tcout << \"coeff mat build start\" << endl;\n\n\tint current_row = 0;\n\tfor (auto v: inner_points) {\n\t\t// vidx CERTAINLY follows order (and it's redundant)\n\t\tsize_t vidx = inner_points.idx(v);\n\t\tauto adj = v->AdjVertices();\n\t\tsize_t degree = v->Degree();\n\t\tfor (auto adjv : adj) {\n\t\t\t// check type\n\t\t\tif (boundary_points.contains(adjv)) { // this set is usually smaller\n\t\t\t\tb_vec_x(current_row) += (1.0f / degree) * adjv->pos[0];\n\t\t\t\tb_vec_y(current_row) += (1.0f / degree) * adjv->pos[1];\n\t\t\t\tb_vec_z(current_row) += (1.0f / degree) * adjv->pos[2];\n\t\t\t} else { // inner\n\t\t\t\tassert(inner_points.contains(adjv));\n\t\t\t\tsize_t adjidx = inner_points.idx(adjv);\n\t\t\t\t// todo add assert = 0\n\t\t\t\tcoeff_mat.insert(current_row, adjidx) = - 1.0f / degree;\n\t\t\t}\n\t\t}\n\n\t\t// add itself\n\t\t// todo add assert\n\t\tcoeff_mat.insert(current_row, vidx) = 1;\n\t\tcurrent_row++;\n\t}\n\n\tcout << \"coeff mat build complete\" << endl;\n\n\t// Solve\n\tSparseQR<SparseMatrix<float>, COLAMDOrdering<int>> solver;\n\n\tcout << \"begin makeCompressed()\" << endl;\n\tcoeff_mat.makeCompressed();\n\n\tcout << \"begin compute()\" << endl;\n\tsolver.compute(coeff_mat);\n\tif (solver.info() != Eigen::Success) {\n\t\tcout << \"solver: decomposition was not successfull.\" << endl;\n\t\treturn;\n\t}\n\n\tcout << \"begin solve() for x\" << endl;\n\tVectorXf res_x = solver.solve(b_vec_x);\n\n\tcout << \"begin solve() for y\" << endl;\n\tVectorXf res_y = solver.solve(b_vec_y);\n\n\tcout << \"begin solve() for z\" << endl;\n\tVectorXf res_z = solver.solve(b_vec_z);\n\n\t// Update vertex coordinates\n\tfor (int i = 0; i < n; i++) {\n\t\t// find the corresponding point\n\t\tauto v = inner_points[i];\n\t\tvecf3 new_pos = { res_x(i), res_y(i), res_z(i) }; // works?\n\n\t\t//cout << new_pos << endl;\n\t\tv->pos = new_pos;\n\t}\n\n}\n", "meta": {"hexsha": "6fcd2b95f5110e8d953a0b253a6dbe15f8846209", "size": 4544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/MinSurf.cpp", "max_stars_repo_name": "libreliu/USTC-CG", "max_stars_repo_head_hexsha": "7064e6c72028187453375fdd6cb66c6ac0182ed2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-05-22T00:21:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T03:07:04.000Z", "max_issues_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/MinSurf.cpp", "max_issues_repo_name": "libreliu/USTC-CG", "max_issues_repo_head_hexsha": "7064e6c72028187453375fdd6cb66c6ac0182ed2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/MinSurf.cpp", "max_forks_repo_name": "libreliu/USTC-CG", "max_forks_repo_head_hexsha": "7064e6c72028187453375fdd6cb66c6ac0182ed2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-17T15:59:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-17T15:59:09.000Z", "avg_line_length": 24.8306010929, "max_line_length": 80, "alphanum_fraction": 0.6525088028, "num_tokens": 1376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5146778076758801}}
{"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 <boost/math/ccmath/isgreaterequal.hpp>\n#include \"test_compile_result.hpp\"\n\nvoid compile_and_link_test()\n{\n   check_result<float>(boost::math::ccmath::isgreaterequal(1.0f, 1.0f));\n   check_result<double>(boost::math::ccmath::isgreaterequal(1.0, 1.0));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::ccmath::isgreaterequal(1.0l, 1.0l));\n#endif\n}\n", "meta": {"hexsha": "4b18282a6fd496c8bfe638f82d5cde6512f1bbba", "size": 626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/ccmath_isgreaterequal_incl_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/compile_test/ccmath_isgreaterequal_incl_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/compile_test/ccmath_isgreaterequal_incl_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.8235294118, "max_line_length": 78, "alphanum_fraction": 0.7555910543, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5146778051666402}}
{"text": "#pragma once\n\n#include <armadillo>\n\nnamespace utils\n{\n    class LinearInterpolator\n    {\n        // contains methods for finding interpolated points between given points\n        // used for finding height and other properties when setting up the grid\n\n    public:\n        LinearInterpolator(\n                const arma::vec& positions,\n                const arma::vec& values,\n                const arma::uword interpolationMethod = 0 // default is no interpolation, only height uses linear interpolation\n                );\n\n        double getValueAtPoint(const double position);\n        arma::vec getValuesAtPoints(const arma::vec& points);\n        static arma::vec getValuesAtPoints(\n                const arma::vec& referencePoints,\n                const arma::vec& referenceValues,\n                const arma::vec& points,\n                const arma::uword interpolationMethod = 0);\n\n    private:\n        const size_t m_N;\n        arma::vec m_positions;\n        arma::vec m_values;\n        arma::vec m_gradients;\n        arma::uword m_interpolationMethod; // 0 means constant, 1 means linear\n\n        bool m_printOutsideRangeWarning = false;\n    };\n}\n", "meta": {"hexsha": "26accd90d4b3ce6e80042160817eda9d4e075d3b", "size": 1155, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utilities/linearinterpolator.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/linearinterpolator.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/linearinterpolator.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": 31.2162162162, "max_line_length": 127, "alphanum_fraction": 0.6207792208, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5146777953247451}}
{"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):       Pawel Dlotko\n *\n *    Copyright (C) 2016 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 \"Persistence_landscapes_test\"\n#include <boost/test/unit_test.hpp>\n#include <gudhi/reader_utils.h>\n#include <gudhi/Persistence_landscape.h>\n#include <gudhi/Unitary_tests_utils.h>\n\n#include <iostream>\n#include <limits>\n\nusing namespace Gudhi;\nusing namespace Gudhi::Persistence_representations;\n\ndouble epsilon = 0.0005;\n\nBOOST_AUTO_TEST_CASE(check_construction_of_landscape) {\n  std::vector<std::pair<double, double> > diag =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram\");\n  Persistence_landscape p(diag);\n  Persistence_landscape q;\n  q.load_landscape_from_file(\"data/file_with_landscape_from_file_with_diagram\");\n  BOOST_CHECK(p == q);\n}\n\nBOOST_AUTO_TEST_CASE(check_construction_of_landscape_form_gudhi_style_file) {\n  Persistence_landscape p(\"data/persistence_file_with_four_entries_per_line\", 1);\n  // p.print_to_file(\"persistence_file_with_four_entries_per_line_landscape\");\n  Persistence_landscape q;\n  q.load_landscape_from_file(\"data/persistence_file_with_four_entries_per_line_landscape\");\n  BOOST_CHECK(p == q);\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_integrals) {\n  std::vector<std::pair<double, double> > diag =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram\");\n  Persistence_landscape p(diag);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_integral_of_landscape(), 2.34992, epsilon);\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_integrals_for_each_level_separatelly) {\n  std::vector<std::pair<double, double> > diag =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram\");\n  Persistence_landscape p(diag);\n\n  std::vector<double> integrals_for_different_levels;\n  integrals_for_different_levels.push_back(0.216432);\n  integrals_for_different_levels.push_back(0.204763);\n  integrals_for_different_levels.push_back(0.188793);\n  integrals_for_different_levels.push_back(0.178856);\n  integrals_for_different_levels.push_back(0.163142);\n  integrals_for_different_levels.push_back(0.155015);\n  integrals_for_different_levels.push_back(0.143046);\n  integrals_for_different_levels.push_back(0.133765);\n  integrals_for_different_levels.push_back(0.123531);\n  integrals_for_different_levels.push_back(0.117393);\n  integrals_for_different_levels.push_back(0.111269);\n  integrals_for_different_levels.push_back(0.104283);\n  integrals_for_different_levels.push_back(0.0941308);\n  integrals_for_different_levels.push_back(0.0811208);\n  integrals_for_different_levels.push_back(0.0679001);\n  integrals_for_different_levels.push_back(0.0580801);\n  integrals_for_different_levels.push_back(0.0489647);\n  integrals_for_different_levels.push_back(0.0407936);\n  integrals_for_different_levels.push_back(0.0342599);\n  integrals_for_different_levels.push_back(0.02896);\n  integrals_for_different_levels.push_back(0.0239881);\n  integrals_for_different_levels.push_back(0.0171792);\n  integrals_for_different_levels.push_back(0.0071511);\n  integrals_for_different_levels.push_back(0.00462067);\n  integrals_for_different_levels.push_back(0.00229033);\n  integrals_for_different_levels.push_back(0.000195296);\n\n  for (size_t level = 0; level != p.size(); ++level) {\n    GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_integral_of_a_level_of_a_landscape(level),\n                                    integrals_for_different_levels[level], epsilon);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_integrals_of_powers_of_landscape) {\n  std::vector<std::pair<double, double> > diag =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram\");\n  Persistence_landscape p(diag);\n\n  std::vector<double> integrals_for_different_powers;\n  integrals_for_different_powers.push_back(17.1692);\n  integrals_for_different_powers.push_back(2.34992);\n  integrals_for_different_powers.push_back(0.49857);\n  integrals_for_different_powers.push_back(0.126405);\n  integrals_for_different_powers.push_back(0.0355235);\n\n  for (size_t power = 0; power != 5; ++power) {\n    GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_integral_of_landscape((double)power),\n                                    integrals_for_different_powers[power], epsilon);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_values_on_different_points) {\n  std::vector<std::pair<double, double> > diag =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram\");\n  Persistence_landscape p(diag);\n\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(1, 0.0), 0., epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(1, 0.1), 0.0692324, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(1, 0.2), 0.163369, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(1, 0.3), 0.217115, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(2, 0.0), 0., epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(2, 0.1), 0.0633688, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(2, 0.2), 0.122361, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(2, 0.3), 0.195401, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(3, 0.0), 0., epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(3, 0.1), 0.0455386, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(3, 0.2), 0.0954012, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(3, 0.3), 0.185282, epsilon);\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_sum_differences_and_multiplications) {\n  std::vector<std::pair<double, double> > diag =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram\");\n  Persistence_landscape p(diag);\n  Persistence_landscape second;\n  second.load_landscape_from_file(\"data/file_with_landscape_from_file_with_diagram_1\");\n\n  Persistence_landscape sum = p + second;\n  Persistence_landscape difference = p - second;\n  Persistence_landscape multiply_by_scalar = 10 * p;\n\n  Persistence_landscape template_sum;\n  template_sum.load_landscape_from_file(\"data/sum\");\n\n  Persistence_landscape template_difference;\n  template_difference.load_landscape_from_file(\"data/difference\");\n\n  Persistence_landscape template_multiply_by_scalar;\n  template_multiply_by_scalar.load_landscape_from_file(\"data/multiply_by_scalar\");\n\n  BOOST_CHECK(sum == template_sum);\n  BOOST_CHECK(difference == template_difference);\n  BOOST_CHECK(multiply_by_scalar == template_multiply_by_scalar);\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_maxima_and_norms) {\n  std::vector<std::pair<double, double> > diag =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram\");\n  Persistence_landscape p(diag);\n  Persistence_landscape second;\n  second.load_landscape_from_file(\"data/file_with_landscape_from_file_with_diagram_1\");\n  Persistence_landscape sum = p + second;\n\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_maximum(), 0.431313, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_norm_of_landscape(1), 2.34992, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_norm_of_landscape(2), 0.706095, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_norm_of_landscape(3), 0.501867, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(compute_distance_of_landscapes(p, sum, 1), 27.9323, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(compute_distance_of_landscapes(p, sum, 2), 2.35199, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(compute_distance_of_landscapes(p, sum, std::numeric_limits<double>::max()), 0.464478,\n                                  epsilon);\n}\n\nBOOST_AUTO_TEST_CASE(check_default_parameters_of_distances) {\n  std::vector<std::pair<double, double> > diag =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram\");\n  Persistence_landscape p(diag);\n\n  std::vector<std::pair<double, double> > diag1 =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram_1\");\n  Persistence_landscape q(diag1);\n\n  double dist_numeric_limit_max = p.distance(q, std::numeric_limits<double>::max());\n  double dist_infinity = p.distance(q, std::numeric_limits<double>::infinity());\n\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(dist_numeric_limit_max, dist_infinity);\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_averages) {\n  std::vector<std::pair<double, double> > diag =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram\");\n  Persistence_landscape p(diag);\n  std::vector<std::pair<double, double> > diag2 =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram_1\");\n  Persistence_landscape q(diag2);\n  Persistence_landscape av;\n  av.compute_average({&p, &q});\n\n  Persistence_landscape template_average;\n  template_average.load_landscape_from_file(\"data/average\");\n  BOOST_CHECK(template_average == av);\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_distances) {\n  std::vector<std::pair<double, double> > diag =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram\");\n  Persistence_landscape p(diag);\n  std::vector<std::pair<double, double> > diag2 =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram_1\");\n  Persistence_landscape q(diag2);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.distance(q), 25.5824, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.distance(q, 2), 2.1264, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.distance(q, std::numeric_limits<double>::max()), 0.359068, epsilon);\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_scalar_product) {\n  std::vector<std::pair<double, double> > diag =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram\");\n  Persistence_landscape p(diag);\n  std::vector<std::pair<double, double> > diag2 =\n      read_persistence_intervals_in_one_dimension_from_file(\"data/file_with_diagram_1\");\n  Persistence_landscape q(diag2);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_scalar_product(q), 0.754498, epsilon);\n}\n\n// Below I am storing the code used to generate tests for that functionality.\n/*\nif ( argc != 2 )\n        {\n                std::cerr << \"To run this program, please provide a name of a file with persistence landscape \\n\";\n                //return 1;\n        }\n        Persistence_landscape p(\"data/file_with_diagram\");\n\n        Persistence_landscape q;\n        q.load_landscape_from_file( \"file_with_landscape_from_file_with_diagram\" );\n\n        if ( p != q )\n        {\n                cout << \"Not equal \\n\";\n        }\n\n        double integral = p.compute_integral_of_landscape();\n        cout << \"integral : \" << integral <<endl;\n\n        //compute integral for each level separatelly\n        for ( size_t level = 0 ; level != p.size() ; ++level )\n        {\n                cout << p.compute_integral_of_landscape( level ) << endl;\n        }\n\n        //compute integral of p-th power of landscspe\n        for ( size_t power = 0 ; power != 5 ; ++power )\n        {\n                cout << p.compute_integral_of_landscape( power ) << endl;\n        }\n\n        cout << \"Value of level 1 at 0 : \" <<  p.compute_value_at_a_given_point(1,0.0) << endl;\n        cout << \"Value of level 1  at 1 : \" <<  p.compute_value_at_a_given_point(1,0.1) << endl;\n        cout << \"Value of level 1  at 2 : \" <<  p.compute_value_at_a_given_point(1,0.2) << endl;\n        cout << \"Value of level 1  at 3 : \" <<  p.compute_value_at_a_given_point(1,0.3) << endl;\n\n\n        cout << \"Value of level 2 at 0 : \" <<  p.compute_value_at_a_given_point(2,0.0) << endl;\n        cout << \"Value of level 2  at 1 : \" <<  p.compute_value_at_a_given_point(2,0.1) << endl;\n        cout << \"Value of level 2  at 2 : \" <<  p.compute_value_at_a_given_point(2,0.2) << endl;\n        cout << \"Value of level 2  at 3 : \" <<  p.compute_value_at_a_given_point(2,0.3) << endl;\n\n\n        cout << \"Value of level 3 at 0 : \" <<  p.compute_value_at_a_given_point(3,0.0) << endl;\n        cout << \"Value of level 3  at 1 : \" <<  p.compute_value_at_a_given_point(3,0.1) << endl;\n        cout << \"Value of level 3  at 2 : \" <<  p.compute_value_at_a_given_point(3,0.2) << endl;\n        cout << \"Value of level 3  at 3 : \" <<  p.compute_value_at_a_given_point(3,0.3) << endl;\n\n\n\n        Persistence_landscape second;\n        second.load_landscape_from_file(\"file_with_landscape_from_file_with_diagram_1\" );\n\n        Persistence_landscape sum = p + second;\n        Persistence_landscape difference = p - second;\n        Persistence_landscape multiply_by_scalar = 10*p;\n\n        //sum.print_to_file(\"sum\");\n        //difference.print_to_file(\"difference\");\n        //multiply_by_scalar.print_to_file(\"multiply_by_scalar\");\n\n        Persistence_landscape template_sum;\n        template_sum.load_landscape_from_file( \"sum\" );\n        Persistence_landscape template_difference;\n        template_difference.load_landscape_from_file( \"difference\" );\n        Persistence_landscape template_multiply_by_scalar;\n        template_multiply_by_scalar.load_landscape_from_file( \"multiply_by_scalar\" );\n\n        if ( sum != template_sum )\n        {\n                cerr << \"Problem with sums \\n\";\n        }\n        if ( difference != template_difference )\n        {\n                cerr << \"Problem with differences \\n\";\n        }\n        if ( multiply_by_scalar != template_multiply_by_scalar )\n        {\n                cerr << \"Problem with multiplication by scalar \\n\";\n        }\n\n\n\n        cout << \"Maximum : \" << p.compute_maximum() << endl;\n\n        cout << \"L^1 norm : \" << p.compute_norm_of_landscape(1) << endl;\n        cout << \"L^2 norm : \" << p.compute_norm_of_landscape(2) << endl;\n        cout << \"L^3 norm : \" << p.compute_norm_of_landscape(3) << endl;\n\n\n        cout << \"L^1 distance : \" << compute_distance_of_landscapes(p,sum,1) << endl;\n        cout << \"L^2 distance : \" << compute_distance_of_landscapes(p,sum,2) << endl;\n        cout << \"L^infty distance : \" << compute_distance_of_landscapes(p,sum,std::numeric_limits<double>::max() ) <<\nendl;\n\n        {\n                Persistence_landscape p( \"data/file_with_diagram\" );\n                Persistence_landscape q( \"data/file_with_diagram_1\" );\n                Persistence_landscape av;\n                av.compute_average( {&p,&q} );\n\n                Persistence_landscape template_average;\n                template_average.load_landscape_from_file( \"average\" );\n                if ( template_average != av )\n                {\n                        cerr << \"We have a problem with average \\n\";\n                }\n        }\n\n\n        {\n                Persistence_landscape p( \"data/file_with_diagram\" );\n                Persistence_landscape q( \"data/file_with_diagram_1\" );\n                cout << \"L^1 distance : \" <<  p.distance( &q ) << endl;\n                cout << \"L^2 distance : \" <<  p.distance( &q , 2) << endl;\n                cout << \"L^infty distance : \" <<  p.distance( &q , std::numeric_limits<double>::max() ) << endl;\n        }\n\n\n        {\n                Persistence_landscape p( \"data/file_with_diagram\" );\n                Persistence_landscape q( \"data/file_with_diagram_1\" );\n                cout << \"Scalar product : \" <<  p.compute_scalar_product( &q ) << endl;\n        }\n*/\n", "meta": {"hexsha": "21ef18a02895572b809d77b13d0c1047bb7dc9b5", "size": 15609, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Persistence_representations/test/persistence_lanscapes_test.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/persistence_lanscapes_test.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/persistence_lanscapes_test.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": 44.9827089337, "max_line_length": 119, "alphanum_fraction": 0.7282337113, "num_tokens": 3958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5146777878945576}}
{"text": "#include <string>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Surface_mesh.h>\n\n#include <boost/foreach.hpp>\n\ntypedef CGAL::Simple_cartesian<double> K;\ntypedef CGAL::Surface_mesh<K::Point_3> Mesh;\ntypedef Mesh::Vertex_index vertex_descriptor;\ntypedef Mesh::Face_index face_descriptor;\n\nint main()\n{\n\n  Mesh m;\n  vertex_descriptor v0 = m.add_vertex(K::Point_3(0,2,0));\n  vertex_descriptor v1 = m.add_vertex(K::Point_3(2,2,0));\n  vertex_descriptor v2 = m.add_vertex(K::Point_3(0,0,0));\n  vertex_descriptor v3 = m.add_vertex(K::Point_3(2,0,0));\n  vertex_descriptor v4 = m.add_vertex(K::Point_3(1,1,0));\n  m.add_face(v3, v1, v4);\n  m.add_face(v0, v4, v1);\n  m.add_face(v0, v2, v4);\n  m.add_face(v2, v3, v4);\n\n\n  // give each vertex a name, the default is empty\n  Mesh::Property_map<vertex_descriptor,std::string> name;\n  bool created;\n  boost::tie(name, created) = m.add_property_map<vertex_descriptor,std::string>(\"v:name\",\"\");\n  assert(created);\n  // add some names to the vertices\n  name[v0] = \"hello\";\n  name[v2] = \"world\";\n\n  {\n    // You get an existing property, and created will be false\n    Mesh::Property_map<vertex_descriptor,std::string> name;\n    bool created;\n    boost::tie(name, created) = m.add_property_map<vertex_descriptor,std::string>(\"v:name\", \"\");\n    assert(! created);\n  }\n\n  //  You can't get a property that does not exist\n  Mesh::Property_map<face_descriptor,std::string> gnus;\n  bool found;\n  boost::tie(gnus, found) = m.property_map<face_descriptor,std::string>(\"v:gnus\");\n  assert(! found);\n\n  // retrieve the point property for which exists a convenience function\n  Mesh::Property_map<vertex_descriptor, K::Point_3> location = m.points();\n  BOOST_FOREACH( vertex_descriptor vd, m.vertices()) { \n    std::cout << name[vd] << \" @ \" << location[vd] << std::endl;\n  }\n  \n  // delete the string property again\n  m.remove_property_map(name);\n\n  return 0;\n}\n\n", "meta": {"hexsha": "0fb958520529e59718d8c5a89887f40228195cb0", "size": 1886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Surface_mesh/examples/Surface_mesh/sm_properties.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/Surface_mesh/examples/Surface_mesh/sm_properties.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/Surface_mesh/examples/Surface_mesh/sm_properties.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.9365079365, "max_line_length": 96, "alphanum_fraction": 0.6961823966, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5146777829736101}}
{"text": "#ifndef KALMAN_FILTER_H_\n#define KALMAN_FILTER_H_\n\n#include <Eigen/Dense>\n\ntemplate<typename T, class System>\nclass KalmanFilter\n{\ntypedef Eigen::Matrix<T, Eigen::Dynamic, 1> VectorXt;    //\u5217\u5411\u91cf\ntypedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> MatrixXt;\npublic:\n\n    KalmanFilter(const System& _system, int _state_dim, int _input_dim, int _measurement_dim, \n                 const MatrixXt& _process_noise, const MatrixXt& _measurement_noise, \n                 const VectorXt& _mean, const MatrixXt& _cov):\n        system(_system),\n        state_dim(_state_dim),\n        input_dim(_input_dim),\n        measurement_dim(_measurement_dim),\n        N(_state_dim),\n        M(_measurement_dim),\n        mean(_mean),\n        cov(_cov),\n        process_noise(_process_noise),\n        measurement_noise(_measurement_noise)\n    {\n\n    }\n\n    ~KalmanFilter()\n    {\n    }\n\n    virtual void predict(const VectorXt& control) = 0;\n    virtual void correct(const VectorXt& measurement) = 0;\n    \n    virtual const VectorXt& getMean() const { return mean; }\n    virtual const MatrixXt& getCov() const { return cov; }\n\n    virtual System& getSystem() { return system; }\n    virtual const System& getSystem() const { return system; }\n    virtual const MatrixXt& getProcessNoiseCov() const { return process_noise; }\n    virtual const MatrixXt& getMeasurementNoiseCov() const { return measurement_noise; }\n    virtual const MatrixXt& getKalmanGain() const { return kalman_gain; }\n\n    /*\t\t\tsetter\t\t\t*/\n    virtual void setMean(const VectorXt& m) { mean = m;}\n    virtual void setCov(const MatrixXt& s) { cov = s;}\n\n    virtual void setProcessNoiseCov(const MatrixXt& p) { process_noise = p;}\n    virtual void setMeasurementNoiseCov(const MatrixXt& m) { measurement_noise = m;}\n\n    /**\n    * @brief make covariance matrix positive finite\n    * @param cov  covariance matrix\n    */\n    virtual void ensurePositiveFinite(MatrixXt& cov) \n    {\n        return;\n        const double eps = 1e-9;\n\n        Eigen::EigenSolver<MatrixXt> solver(cov);\n        MatrixXt D = solver.pseudoEigenvalueMatrix();\n        MatrixXt V = solver.pseudoEigenvectors();\n        for (int i = 0; i < D.rows(); i++) \n        {\n            if (D(i, i) < eps) \n            D(i, i) = eps;\n        }\n\n        cov = V * D * V.inverse();\n    }\n\npublic:\n    const int state_dim,       N; //\u72b6\u6001\u5411\u91cf\u7ef4\u5ea6\n    const int input_dim;\n    const int measurement_dim, M; //\u6d4b\u91cf\u5411\u91cf\u7ef4\u5ea6\n\n    VectorXt mean;                //\u5747\u503c\n    MatrixXt cov;                 //\u534f\u65b9\u5dee\n\n    System system;                //\u63a7\u5236\u7cfb\u7edf\n    MatrixXt process_noise;\t\t  //\u8fc7\u7a0b\u566a\u58f0 Q\n    MatrixXt measurement_noise;\t  //\u6d4b\u91cf\u566a\u58f0 R\n\n    MatrixXt kalman_gain;         //\u5361\u5c14\u66fc\u589e\u76caK\n\n};\n\n#endif", "meta": {"hexsha": "28fff42a11a955a25ce5a7af3e8f95f9eb3d9cae", "size": 2676, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kalman/kalman_filter.hpp", "max_stars_repo_name": "CastielLiu/hdl_localization", "max_stars_repo_head_hexsha": "c958f78b0dc2dd2eeb9a50aad9eff0f23e662ab2", "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/kalman/kalman_filter.hpp", "max_issues_repo_name": "CastielLiu/hdl_localization", "max_issues_repo_head_hexsha": "c958f78b0dc2dd2eeb9a50aad9eff0f23e662ab2", "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/kalman/kalman_filter.hpp", "max_forks_repo_name": "CastielLiu/hdl_localization", "max_forks_repo_head_hexsha": "c958f78b0dc2dd2eeb9a50aad9eff0f23e662ab2", "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.7333333333, "max_line_length": 94, "alphanum_fraction": 0.6289237668, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5146770302386267}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <map>\n#include <optional>\n#include <tuple>\n\n#include \"geohash/geometry.hpp\"\n#include \"geohash/math.hpp\"\n\nnamespace geohash::int64 {\n\n// Returns the precision in longitude/latitude and degrees for the given\n// precision\n[[nodiscard]] inline auto constexpr error_with_precision(\n    const uint32_t precision) -> std::tuple<double, double> {\n  auto lat_bits = static_cast<int32_t>(precision >> 1U);\n  auto lng_bits = static_cast<int32_t>(precision - lat_bits);\n\n  return std::make_tuple(360 * power2(-lng_bits), 180 * power2(-lat_bits));\n}\n\n// Encode a point into geohash with the given precision\n[[nodiscard]] auto encode(const Point& point, uint32_t precision) -> uint64_t;\n\n// Encode points into geohash with the given precision\n[[nodiscard]] inline auto encode(\n    const Eigen::Ref<const Eigen::Matrix<Point, -1, 1>>& points,\n    uint32_t precision) -> Eigen::Matrix<uint64_t, -1, 1> {\n  auto result = Eigen::Matrix<uint64_t, -1, 1>(points.size());\n  for (Eigen::Index ix = 0; ix < points.size(); ++ix) {\n    result(ix) = encode(points(ix), precision);\n  }\n  return result;\n}\n\n// Returns the region encoded by the integer geohash with the specified\n// precision.\n[[nodiscard]] auto bounding_box(uint64_t hash, uint32_t precision) -> Box;\n\n// Decode a hash into a spherical equatorial point with the given precision.\n// If round is true, the coordinates of the points will be rounded to the\n// accuracy defined by the GeoHash.\n[[nodiscard]] inline auto decode(const uint64_t hash, const uint32_t precision,\n                                 const bool round) -> Point {\n  auto bbox = bounding_box(hash, precision);\n  return round ? bbox.round() : bbox.center();\n}\n\n// Decode hashs into a spherical equatorial points with the given bit depth.\n// If round is true, the coordinates of the points will be rounded to the\n// accuracy defined by the GeoHash.\n[[nodiscard]] inline auto decode(\n    const Eigen::Ref<const Eigen::Matrix<uint64_t, -1, 1>>& hashs,\n    const uint32_t precision, const bool center)\n    -> Eigen::Matrix<Point, -1, 1> {\n  auto result = Eigen::Matrix<Point, -1, 1>(hashs.size());\n  for (Eigen::Index ix = 0; ix < hashs.size(); ++ix) {\n    result(ix) = decode(hashs(ix), precision, center);\n  }\n  return result;\n}\n\n// Returns all neighbors hash clockwise from north around northwest at the given\n// precision.\n// 7 0 1\n// 6 x 2\n// 5 4 3\n[[nodiscard]] auto neighbors(const uint64_t hash, const uint32_t precision)\n    -> Eigen::Matrix<uint64_t, 8, 1>;\n\n// Returns the property of the grid covering the given box: geohash of the\n// minimum corner point, number of boxes in longitudes and latitudes.\n[[nodiscard]] auto grid_properties(const Box& box, uint32_t precision)\n    -> std::tuple<uint64_t, size_t, size_t>;\n\n// Returns all the GeoHash codes within the box.\n[[nodiscard]] auto bounding_boxes(const std::optional<Box>& box, uint32_t chars)\n    -> Eigen::Matrix<uint64_t, -1, 1>;\n\n// Returns all the GeoHash codes within the polygon.\n[[nodiscard]] inline auto bounding_boxes(const Polygon& polygon, uint32_t chars)\n    -> Eigen::Matrix<uint64_t, -1, 1> {\n  auto box = Box();\n  boost::geometry::envelope<Polygon, Box>(polygon, box);\n  return bounding_boxes(box, chars);\n}\n\n// Returns the start and end indexes of the different GeoHash boxes.\n[[nodiscard]] auto where(\n    const Eigen::Ref<const Eigen::Matrix<uint64_t, -1, -1>>& hashs)\n    -> std::map<uint64_t, std::tuple<std::tuple<int64_t, int64_t>,\n                                     std::tuple<int64_t, int64_t>>>;\n\n}  // namespace geohash::int64\n", "meta": {"hexsha": "1c2c2c06af0f4a2577ddada3f68ce8a8ce99775a", "size": 3567, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geohash/core/include/geohash/int64.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/int64.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/int64.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": 37.5473684211, "max_line_length": 80, "alphanum_fraction": 0.6961031679, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5146770253862898}}
{"text": "\n#include <math.h>\n#include <vector>\n#include <limits>\nusing namespace std;\n\n#include <armadillo>\nusing namespace arma;\n\n#include \"optimize_state_reconstructor.h\"\n#include \"rate_model.h\"\n#include \"state_reconstructor.h\"\n\n#include <gsl/gsl_multimin.h>\n#include <gsl/gsl_vector.h>\n\nOptimizeStateReconstructor::OptimizeStateReconstructor(RateModel * _rm,StateReconstructor * _sr, mat * _free_mask, int _nfree):\n    rm(_rm),sr(_sr),free_variables(_free_mask),nfree_variables(_nfree),maxiterations(10000),stoppingprecision(0.001) {}\n\ndouble OptimizeStateReconstructor::GetLikelihoodWithOptimized(const gsl_vector * variables) {\n    for (unsigned int i=0; i < free_variables->n_rows; i++) {\n        for (unsigned int j=0; j < free_variables->n_cols; j++) {\n            if (i != j) {\n                rm->set_Q_cell(i,j,gsl_vector_get(variables,(*free_variables)(i, j)));\n                if (rm->get_Q()(i, j) < 0 || rm->get_Q()(i, j) >= 1000) {\n                    return 100000000;\n                }\n            }\n        }\n    }\n    double like;\n    rm->set_Q_diag();\n    like = sr->eval_likelihood();\n    //cout << like << endl;\n    if (like < 0 || like == std::numeric_limits<double>::infinity()) {\n        like = 100000000;\n    }\n    return like;\n}\n\n\ndouble OptimizeStateReconstructor::GetLikelihoodWithOptimized_gsl(const gsl_vector * variables, void *obj) {\n    double temp;\n    temp= ((OptimizeStateReconstructor*)obj)->GetLikelihoodWithOptimized(variables);\n    return temp;\n}\n\n/*\n * USES THE SIMPLEX ALGORITHM\n *\n */\nmat OptimizeStateReconstructor::optimize() {\n    const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex2;\n    gsl_multimin_fminimizer *s = NULL;\n    gsl_vector *ss, *x;\n    size_t np = nfree_variables;\n    size_t iter = 0, i;\n    int status;\n    double size;\n    /* Initial vertex size vector */\n    ss = gsl_vector_alloc (np);\n    /* Set all step sizes to .01 */ //Note that it was originally 1\n    gsl_vector_set_all (ss, .2);\n    /* Starting point */\n    //cout<<\"Now in OPtimizaRateWithGivenTipVariance in OptimizationFn\"<<endl;\n    x = gsl_vector_alloc (np);\n    for (unsigned int i=0; i < np; i++) {\n        gsl_vector_set (x, i, 0.1);\n    }\n    OptimizeStateReconstructor *pt;\n    pt=(this);\n    double (*F)(const gsl_vector *, void *);\n    F = &OptimizeStateReconstructor::GetLikelihoodWithOptimized_gsl;\n    /* Initialize method and iterate */\n    gsl_multimin_function minex_func;\n    minex_func.f =* F;\n    minex_func.params = pt;\n    minex_func.n = np;\n    s = gsl_multimin_fminimizer_alloc (T, np);\n    gsl_multimin_fminimizer_set (s, &minex_func, x, ss);\n    do {\n        //cout<<\"Now on iteration \"<<iter<<endl;\n        iter++;\n        status = gsl_multimin_fminimizer_iterate(s);\n        if (status != 0) { //0 Means it's a success\n        //    printf (\"error: %s\\n\", gsl_strerror (status));\n            break;\n        }\n        size = gsl_multimin_fminimizer_size (s);\n        //status = gsl_multimin_test_size (size, 1e-2);\n        status = gsl_multimin_test_size (size, stoppingprecision); //since we want more precision\n        if (status == GSL_SUCCESS) {\n        //    printf (\"converged to minimum at\\n\");\n        }\n        //printf (\"%5d \", iter);\n        for (i = 0; i < np; i++) {\n        //    printf (\"%10.3e \", gsl_vector_get (s->x, i));\n        }\n        //printf (\"f() = %7.3f size = %.3f\\n\", s->fval, size);\n    }\n    while (status == GSL_CONTINUE && iter < maxiterations);\n    mat results (free_variables->n_rows, free_variables->n_cols); results.fill(0);\n    for (unsigned int i=0; i < results.n_rows; i++) {\n        for (unsigned int j=0; j < results.n_cols; j++) {\n            if (i != j) {\n                results(i, j) = (gsl_vector_get(s->x, (*free_variables)(i, j)));\n            }\n        }\n    }\n    gsl_vector_free(x);\n    gsl_vector_free(ss);\n    gsl_multimin_fminimizer_free (s);\n    return results;\n}\n", "meta": {"hexsha": "725966fb37cd52ab2d0011c75ee1f694f028b344", "size": 3887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_gsl.cpp", "max_stars_repo_name": "jlanga/smsk_selection", "max_stars_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-18T05:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T10:22:33.000Z", "max_issues_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_gsl.cpp", "max_issues_repo_name": "jlanga/smsk_selection", "max_issues_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T07:26:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-08T13:59:48.000Z", "max_forks_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_gsl.cpp", "max_forks_repo_name": "jlanga/smsk_orthofinder", "max_forks_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-18T05:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:23:31.000Z", "avg_line_length": 33.8, "max_line_length": 127, "alphanum_fraction": 0.6174427579, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5146770253862897}}
{"text": "#define BOOST_TEST_MODULE SRIM_PDF\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/srim/pdf.hpp>\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(modified_beta, T, test_types) {\n  T alpha = 2.0;\n  T beta = 3.0;\n  T z_max = 100.0;\n\n  BOOST_TEST(triumf::srim::pdf::modified_beta<T>(-1.0, alpha, beta, z_max) ==\n             static_cast<T>(0.0));\n  BOOST_TEST(triumf::srim::pdf::modified_beta<T>(z_max + 1.0, alpha, beta,\n                                                 z_max) == static_cast<T>(0.0));\n}\n", "meta": {"hexsha": "63dff84538e06b04df90ce060bb189a54f0c17ea", "size": 598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/srim_pdf.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/srim_pdf.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/srim_pdf.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": 27.1818181818, "max_line_length": 80, "alphanum_fraction": 0.6321070234, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5145944810641844}}
{"text": "#pragma once\n#include \"rust/cxx.h\"\n#include <memory>\n#include <cstdint>\n#include <NTL/GF2X.h>\n#include <NTL/GF2E.h>\n\nnamespace poly\n{\n    struct PolyI64Pair;\n    class Poly\n    {\n    public:\n        // internal representation of polynomial\n        NTL::GF2X int_pol;\n        Poly();\n        // copy\n        Poly(const Poly &b);\n        // move\n        Poly(Poly &&b);\n        void add_to(const Poly &b);\n        void mul_to(const Poly &b);\n        void div_to(const Poly &b);\n        void gcd_to(const Poly &b);\n        void rem_to(const Poly &b);\n        void sqr();\n        bool div_to_checked(const Poly &b);\n        bool coeff(int64_t idx) const;\n        bool eq(const Poly &b) const;\n        bool is_zero() const;\n        std::unique_ptr<std::vector<uint8_t>> to_bytes(int64_t min_bytes) const;\n    };\n\n    int64_t deg(const Poly &a);\n    std::unique_ptr<Poly> new_poly_shifted(rust::Slice<uint8_t> bytes, int64_t shift, bool msb_first);\n    std::unique_ptr<Poly> new_poly(rust::Slice<uint8_t> bytes);\n    std::unique_ptr<Poly> new_zero();\n    std::unique_ptr<Poly> copy_poly(const Poly &p);\n    std::unique_ptr<Poly> add(const Poly &b, const Poly &c);\n    std::unique_ptr<Poly> mul(const Poly &b, const Poly &c);\n    std::unique_ptr<Poly> div(const Poly &b, const Poly &c);\n    std::unique_ptr<Poly> gcd(const Poly &b, const Poly &c);\n    std::unique_ptr<Poly> xgcd(Poly &x, Poly &y, const Poly &b, const Poly &c);\n    std::unique_ptr<Poly> rem(const Poly &b, const Poly &c);\n    std::unique_ptr<Poly> power(const Poly &p, int64_t n);\n    std::unique_ptr<Poly> shift(const Poly &p, int64_t n);\n    std::unique_ptr<std::vector<PolyI64Pair>> factor(const Poly &p, int64_t verbosity);\n\n    class PolyRem\n    {\n    public:\n        NTL::GF2E int_pol;\n        // from modulus\n        PolyRem(const Poly &p);\n        // copy\n        PolyRem(const PolyRem &b);\n        // move\n        PolyRem(PolyRem &&b);\n        PolyRem(const NTL::GF2E &p);\n        void add_to(const PolyRem &b);\n        void mul_to(const PolyRem &b);\n        void div_to(const PolyRem &b);\n        void sqr();\n        std::unique_ptr<Poly> rep() const;\n    };\n    std::unique_ptr<PolyRem> new_polyrem(const Poly &rem, const Poly &m);\n    std::unique_ptr<PolyRem> powermod(const PolyRem &p, int64_t n);\n    std::unique_ptr<PolyRem> copy_polyrem(const PolyRem &p);\n} // namespace poly\n", "meta": {"hexsha": "e492da494a70f808582440e2d38cccb02ae46807", "size": 2352, "ext": "hh", "lang": "C++", "max_stars_repo_path": "delsum-poly/include/poly.hh", "max_stars_repo_name": "dtolnay-contrib/delsum", "max_stars_repo_head_hexsha": "2b001d21e8d2d0904516c4b070ba06412b091000", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "delsum-poly/include/poly.hh", "max_issues_repo_name": "dtolnay-contrib/delsum", "max_issues_repo_head_hexsha": "2b001d21e8d2d0904516c4b070ba06412b091000", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "delsum-poly/include/poly.hh", "max_forks_repo_name": "dtolnay-contrib/delsum", "max_forks_repo_head_hexsha": "2b001d21e8d2d0904516c4b070ba06412b091000", "max_forks_repo_licenses": ["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.6, "max_line_length": 102, "alphanum_fraction": 0.6164965986, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5145944704339167}}
{"text": "#ifndef QP_SOLVER_H\n#define QP_SOLVER_H\n\n#include <Eigen/Dense>\n#ifdef QP_SOLVER_USE_SPARSE\n#include <Eigen/Sparse>\n#endif\n#include <cmath>\n#include <limits>\n\n#ifndef SOLVER_ASSERT\n#define SOLVER_ASSERT(x) eigen_assert(x)\n#endif\n\nnamespace qp_solver {\n\n#ifdef QP_SOLVER_USE_SPARSE\ntemplate <int _n, int _m, typename _Scalar = double>\nstruct QP {\n    using Scalar = _Scalar;\n    enum {\n        n=_n,\n        m=_m\n    };\n    Eigen::SparseMatrix<Scalar> P;\n    Eigen::Matrix<int, n, 1> P_col_nnz;\n    Eigen::Matrix<Scalar, n, 1> q;\n    Eigen::SparseMatrix<Scalar> A;\n    Eigen::Matrix<int, n, 1> A_col_nnz;\n    Eigen::Matrix<Scalar, m, 1> l, u;\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n#else\ntemplate <int _n, int _m, typename _Scalar = double>\nstruct QP {\n    using Scalar = _Scalar;\n    enum {\n        n=_n,\n        m=_m\n    };\n    Eigen::Matrix<Scalar, n, n> P;\n    Eigen::Matrix<Scalar, n, 1> q;\n    Eigen::Matrix<Scalar, m, n> A;\n    Eigen::Matrix<Scalar, m, 1> l, u;\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n#endif\n\ntemplate <typename Scalar>\nstruct qp_sover_settings_t {\n    Scalar rho = 1e-1;          /**< ADMM rho step, 0 < rho */\n    Scalar sigma = 1e-6;        /**< ADMM sigma step, 0 < sigma, (small) */\n    Scalar alpha = 1.0;         /**< ADMM overrelaxation parameter, 0 < alpha < 2,\n                                     values in [1.5, 1.8] give good results (empirically) */\n    Scalar eps_rel = 1e-3;      /**< Relative tolerance for termination, 0 < eps_rel */\n    Scalar eps_abs = 1e-3;      /**< Absolute tolerance for termination, 0 < eps_abs */\n    int max_iter = 1000;        /**< Maximal number of iteration, 0 < max_iter */\n    int check_termination = 25; /**< Check termination after every Nth iteration, 0 (disabled) or 0 < check_termination */\n    bool warm_start = false;    /**< Warm start solver, reuses previous x,z,y */\n    bool adaptive_rho = false;  /**< Adapt rho to optimal estimate */\n    Scalar adaptive_rho_tolerance = 5;  /**< Minimal for rho update factor, 1 < adaptive_rho_tolerance */\n    int adaptive_rho_interval = 25; /**< change rho every Nth iteration, 0 < adaptive_rho_interval,\n                                         set equal to check_termination to save computation  */\n    bool verbose = false;\n\n#ifdef QP_SOLVER_PRINTING\n    void print() const\n    {\n        printf(\"ADMM settings:\\n\");\n        printf(\"  sigma %.2e\\n\", sigma);\n        printf(\"  rho %.2e\\n\", rho);\n        printf(\"  alpha %.2f\\n\", alpha);\n        printf(\"  eps_rel %.1e\\n\", eps_rel);\n        printf(\"  eps_abs %.1e\\n\", eps_abs);\n        printf(\"  max_iter %d\\n\", max_iter);\n        printf(\"  adaptive_rho %d\\n\", adaptive_rho);\n        printf(\"  warm_start %d\\n\", warm_start);\n    }\n#endif\n};\n\ntypedef enum {\n    SOLVED,\n    MAX_ITER_EXCEEDED,\n    UNSOLVED,\n    UNINITIALIZED\n} status_t;\n\ntemplate <typename Scalar>\nstruct qp_solver_info_t {\n    status_t status = UNINITIALIZED; /**< Solver status */\n    int iter = 0;               /**< Number of iterations */\n    int rho_updates = 0;        /**< Number of rho updates (factorizations) */\n    Scalar rho_estimate = 0;    /**< Last rho estimate */\n    Scalar res_prim = 0;        /**< Primal residual */\n    Scalar res_dual = 0;        /**< Dual residual */\n\n#ifdef QP_SOLVER_PRINTING\n    void print() const\n    {\n        printf(\"ADMM info:\\n\");\n        printf(\"  status \");\n        switch (status) {\n        case SOLVED:\n            printf(\"SOLVED\\n\");\n            break;\n        case MAX_ITER_EXCEEDED:\n            printf(\"MAX_ITER_EXCEEDED\\n\");\n            break;\n        case UNSOLVED:\n            printf(\"UNSOLVED\\n\");\n            break;\n        default:\n            printf(\"UNINITIALIZED\\n\");\n        };\n        printf(\"  iter %d\\n\", iter);\n        printf(\"  rho_updates %d\\n\", rho_updates);\n        printf(\"  rho_estimate %f\\n\", rho_estimate);\n        printf(\"  res_prim %f\\n\", res_prim);\n        printf(\"  res_dual %f\\n\", res_dual);\n    }\n#endif\n};\n\n/**\n *  minimize        0.5 x' P x + q' x\n *  subject to      l <= A x <= u\n *\n *  with:\n *    x element of R^n\n *    Ax element of R^m\n */\ntemplate <typename QPType,\n#ifdef QP_SOLVER_USE_SPARSE\n          template <typename, int, typename... Args> class LinearSolver = Eigen::SimplicialLDLT,\n#else\n          template <typename, int, typename... Args> class LinearSolver = Eigen::LDLT,\n#endif\n          int LinearSolver_UpLo = Eigen::Lower>\nclass QPSolver {\npublic:\n    enum {\n        n=QPType::n,\n        m=QPType::m\n    };\n\n    using qp_t = QPType;\n    using Scalar = typename QPType::Scalar;\n    using var_t = Eigen::Matrix<Scalar, n, 1>;\n    using constraint_t = Eigen::Matrix<Scalar, m, 1>;\n    using dual_t = Eigen::Matrix<Scalar, m, 1>;\n    using kkt_vec_t = Eigen::Matrix<Scalar, n + m, 1>;\n#ifdef QP_SOLVER_USE_SPARSE\n    using SpMat = Eigen::SparseMatrix<Scalar, Eigen::ColMajor>;\n    using kkt_mat_t = SpMat;\n#else\n    using kkt_mat_t = Eigen::Matrix<Scalar, n + m, n + m>;\n#endif\n    using settings_t = qp_sover_settings_t<Scalar>;\n    using info_t = qp_solver_info_t<Scalar>;\n    using linear_solver_t = LinearSolver<kkt_mat_t, LinearSolver_UpLo>;\n\n    static constexpr Scalar RHO_MIN = 1e-6;\n    static constexpr Scalar RHO_MAX = 1e+6;\n    static constexpr Scalar RHO_TOL = 1e-4;\n    static constexpr Scalar RHO_EQ_FACTOR = 1e+3;\n    static constexpr Scalar LOOSE_BOUNDS_THRESH = 1e+16;\n    static constexpr Scalar DIV_BY_ZERO_REGUL = std::numeric_limits<Scalar>::epsilon();\n\n    // Solver state variables\n    int iter;\n    var_t x;\n    constraint_t z;\n    dual_t y;\n    var_t x_tilde;\n    constraint_t z_tilde;\n    constraint_t z_prev;\n    dual_t rho_vec;\n    dual_t rho_inv_vec;\n    Scalar rho;\n\n    // State\n    Scalar res_prim;\n    Scalar res_dual;\n    Scalar _max_Ax_z_norm;\n    Scalar _max_Px_ATy_q_norm;\n\n    enum {\n        INEQUALITY_CONSTRAINT,\n        EQUALITY_CONSTRAINT,\n        LOOSE_BOUNDS\n    } constr_type[m]; /**< constraint type classification */\n\n    settings_t _settings;\n    info_t _info;\n\n    kkt_mat_t kkt_mat;\n    linear_solver_t linear_solver;\n\n    // enforce 16 byte alignment https://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    QPSolver() { }\n\n    void setup(const qp_t &qp)\n    {\n        x.setZero();\n        z.setZero();\n        y.setZero();\n\n        // Set QP constraint type\n        constr_type_init(qp);\n\n        // initialize step size (rho) vector\n        rho_vec_update(_settings.rho);\n\n        // construct KKT system and compute decomposition\n        construct_KKT_mat(qp);\n        compute_KKT();\n\n        _info.status = UNSOLVED;\n    }\n\n    void update_qp(const qp_t &qp)\n    {\n        // Set QP constraint type\n        constr_type_init(qp);\n\n        // initialize step size (rho) vector\n        rho_vec_update(_settings.rho);\n\n        // update KKT system and do factorization\n        update_KKT_mat(qp);\n        factorize_KKT();\n\n        _info.status = UNSOLVED;\n    }\n\n    void solve(const qp_t &qp)\n    {\n        kkt_vec_t rhs, x_tilde_nu;\n        bool check_termination = false;\n\n        if (_info.status == UNINITIALIZED) {\n            SOLVER_ASSERT(_info.status == UNINITIALIZED);\n            return;\n        }\n\n#ifdef QP_SOLVER_PRINTING\n        if (_settings.verbose) {\n            _settings.print();\n        }\n#endif\n        if (!_settings.warm_start) {\n            x.setZero();\n            z.setZero();\n            y.setZero();\n        }\n\n        for (iter = 1; iter <= _settings.max_iter; iter++) {\n            z_prev = z;\n\n            // update x_tilde z_tilde\n            form_KKT_rhs(qp, rhs);\n            x_tilde_nu = linear_solver.solve(rhs);\n\n            x_tilde = x_tilde_nu.template head<n>();\n            z_tilde = z_prev + rho_inv_vec.cwiseProduct(x_tilde_nu.template tail<m>() - y);\n\n            // update x\n            x = _settings.alpha * x_tilde + (1 - _settings.alpha) * x;\n\n            // update z\n            z = _settings.alpha * z_tilde + (1 - _settings.alpha) * z_prev + rho_inv_vec.cwiseProduct(y);\n            box_projection(z, qp.l, qp.u); // euclidean projection\n\n            // update y\n            y = y + rho_vec.cwiseProduct(_settings.alpha * z_tilde + (1 - _settings.alpha) * z_prev - z);\n\n            if (_settings.check_termination != 0 && iter % _settings.check_termination == 0) {\n                check_termination = true;\n            } else {\n                check_termination = false;\n            }\n\n            if (check_termination) {\n                update_state(qp);\n\n#ifdef QP_SOLVER_PRINTING\n                if (_settings.verbose) {\n                    print_status(qp);\n                }\n#endif\n                if (termination_criteria(qp)) {\n                    _info.status = SOLVED;\n                    break;\n                }\n            }\n\n            if (_settings.adaptive_rho && iter % _settings.adaptive_rho_interval == 0) {\n                if (!check_termination) {\n                    // state was not yet updated\n                    update_state(qp);\n                }\n                Scalar new_rho = rho_estimate(rho, qp);\n                new_rho = fmax(RHO_MIN, fmin(new_rho, RHO_MAX));\n                _info.rho_estimate = new_rho;\n\n                if (new_rho < rho / _settings.adaptive_rho_tolerance ||\n                    new_rho > rho * _settings.adaptive_rho_tolerance) {\n                    rho_vec_update(new_rho);\n                    update_KKT_rho();\n                    /* Note: KKT Sparsity pattern unchanged by rho update. Only factorize. */\n                    factorize_KKT();\n                }\n            }\n        }\n\n        if (iter > _settings.max_iter) {\n            _info.status = MAX_ITER_EXCEEDED;\n        }\n        _info.iter = iter;\n\n#ifdef QP_SOLVER_PRINTING\n        if (_settings.verbose) {\n            _info.print();\n        }\n#endif\n    }\n\n    inline const var_t& primal_solution() const { return x; }\n    inline var_t& primal_solution() { return x; }\n\n    inline const dual_t& dual_solution() const { return y; }\n    inline dual_t& dual_solution() { return y; }\n\n    inline const settings_t& settings() const { return _settings; }\n    inline settings_t& settings() { return _settings; }\n\n    inline const info_t& info() const { return _info; }\n    inline info_t& info() { return _info; }\n\nprivate:\n    /* Construct the KKT matrix of the form\n     *\n     * [[ P + sigma*I,        A' ],\n     *  [ A,           -1/rho.*I ]]\n     *\n     * If LinearSolver_UpLo parameter is Eigen::Lower, then only the lower\n     * triangular part is constructed to optimize memory.\n     *\n     * Note: For Eigen::ConjugateGradient it is advised to set Upper|Lower for\n     *       best performance.\n     */\n    void construct_KKT_mat(const qp_t &qp)\n    {\n        static_assert(LinearSolver_UpLo == Eigen::Lower ||\n                      LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower),\n                      \"LinearSolver_UpLo must be Lower or Upper|Lower\");\n\n#ifdef QP_SOLVER_USE_SPARSE\n        kkt_mat.resize(n+m,n+m); // sets all elements to 0\n        Eigen::Matrix<int, n+m, 1> nnz_col;\n\n        nnz_col.setConstant(1);\n        nnz_col.template head<n>() = qp.P_col_nnz + qp.A_col_nnz;\n        if (LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower)) {\n            // We don't know nnz of A rows, assume worst case\n            nnz_col.template tail<m>().array() += n;\n        }\n        kkt_mat.reserve(nnz_col);\n\n        // top left:  P + sigma*I\n        sparse_insert_at(kkt_mat, 0, 0, qp.P);\n        for (int i = 0; i < n; i++) {\n            kkt_mat.coeffRef(i,i) += _settings.sigma;\n        }\n\n        // bottom left:  A\n        sparse_insert_at(kkt_mat, n, 0, qp.A);\n\n        // top right:  A'\n        if (LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower)) {\n            sparse_insert_at(kkt_mat, 0, n, qp.A.transpose());\n        }\n\n        // bottom right:  -1/rho.*I\n        for (int i = 0; i < m; i++) {\n            kkt_mat.insert(n+i, n+i) = -rho_inv_vec(i);\n        }\n\n        kkt_mat.makeCompressed();\n#else\n        kkt_mat.template topLeftCorner<n, n>() = qp.P + _settings.sigma * qp.P.Identity();\n        if (LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower)) {\n            kkt_mat.template topRightCorner<n, m>() = qp.A.transpose();\n        }\n        kkt_mat.template bottomLeftCorner<m, n>() = qp.A;\n        kkt_mat.template bottomRightCorner<m, m>() = -1.0 * rho_inv_vec.asDiagonal();\n#endif\n    }\n\n    /** KKT matrix value update, assumes same sparsity pattern */\n    void update_KKT_mat(const qp_t &qp)\n    {\n#ifdef QP_SOLVER_USE_SPARSE\n        // construct_KKT_mat(qp);\n        // TODO: more efficient update?\n        for (int k = 0; k < kkt_mat.outerSize(); ++k) {\n            for (typename SpMat::InnerIterator it(kkt_mat, k); it; ++it) {\n                int row, col;\n                row = it.row();\n                col = it.col();\n                if (row < n) {\n                    if (col < n) {\n                        // top left:  P + sigma*I\n                        it.valueRef() = qp.P.coeff(row, col) + _settings.sigma;\n                    } else {\n                        // top right:  A'\n                        it.valueRef() = qp.A.coeff(col, row-n);\n                    }\n                } else {\n                    if (col < n) {\n                        // bottom left:  A\n                        it.valueRef() = qp.A.coeff(row-n, col);\n                    } else {\n                        // bottom right:  -1/rho.*I\n                        it.valueRef() = -rho_inv_vec(row-n);\n                    }\n                }\n            }\n        }\n#else\n        construct_KKT_mat(qp);\n#endif\n    }\n\n    void update_KKT_rho()\n    {\n#ifdef QP_SOLVER_USE_SPARSE\n        // Note: optimize by writing kkt_mat.valuePtr(). needs to be compressed and Eigen::Lower.\n        for (int i = 0; i < m; i++) {\n            kkt_mat.coeffRef(n+i, n+i) = -rho_inv_vec(i);\n        }\n#else\n        kkt_mat.template bottomRightCorner<m, m>() = -1.0 * rho_inv_vec.asDiagonal();\n#endif\n    }\n\n    void factorize_KKT()\n    {\n#ifdef QP_SOLVER_USE_SPARSE\n        linear_solver.factorize(kkt_mat);\n#else\n        linear_solver.compute(kkt_mat);\n#endif\n        SOLVER_ASSERT(linear_solver.info() == Eigen::Success);\n    }\n\n    void compute_KKT()\n    {\n        linear_solver.compute(kkt_mat);\n        SOLVER_ASSERT(linear_solver.info() == Eigen::Success);\n    }\n\n\n#ifdef QP_SOLVER_USE_SPARSE\n    void sparse_insert_at(SpMat &dst, int row, int col, const SpMat &src) const\n    {\n        for (int k = 0; k < src.outerSize(); ++k) {\n            for (typename SpMat::InnerIterator it(src, k); it; ++it) {\n                dst.insert(row + it.row(), col + it.col()) = it.value();\n            }\n        }\n    }\n#endif\n\n    void form_KKT_rhs(const qp_t &qp, kkt_vec_t& rhs)\n    {\n        rhs.template head<n>() = _settings.sigma * x - qp.q;\n        rhs.template tail<m>() = z - rho_inv_vec.cwiseProduct(y);\n    }\n\n    void box_projection(constraint_t& z, const constraint_t& l, const constraint_t& u)\n    {\n        z = z.cwiseMax(l).cwiseMin(u);\n    }\n\n    void constr_type_init(const qp_t &qp)\n    {\n        for (int i = 0; i < qp.l.RowsAtCompileTime; i++) {\n            if (qp.l[i] < -LOOSE_BOUNDS_THRESH && qp.u[i] > LOOSE_BOUNDS_THRESH) {\n                constr_type[i] = LOOSE_BOUNDS;\n            } else if (qp.u[i] - qp.l[i] < RHO_TOL) {\n                constr_type[i] = EQUALITY_CONSTRAINT;\n            } else {\n                constr_type[i] = INEQUALITY_CONSTRAINT;\n            }\n        }\n    }\n\n    void rho_vec_update(Scalar rho0)\n    {\n        for (int i = 0; i < rho_vec.RowsAtCompileTime; i++) {\n            switch (constr_type[i]) {\n            case LOOSE_BOUNDS:\n                rho_vec[i] = RHO_MIN;\n                break;\n            case EQUALITY_CONSTRAINT:\n                rho_vec[i] = RHO_EQ_FACTOR*rho0;\n                break;\n            case INEQUALITY_CONSTRAINT: /* fall through */\n            default:\n                rho_vec[i] = rho0;\n            };\n        }\n        rho_inv_vec = rho_vec.cwiseInverse();\n        rho = rho0;\n        _info.rho_updates += 1;\n    }\n\n    void update_state(const qp_t& qp)\n    {\n        Scalar norm_Ax, norm_z;\n        norm_Ax = (qp.A*x).template lpNorm<Eigen::Infinity>();\n        norm_z = z.template lpNorm<Eigen::Infinity>();\n        _max_Ax_z_norm = fmax(norm_Ax, norm_z);\n\n        Scalar norm_Px, norm_ATy, norm_q;\n        norm_Px = (qp.P*x).template lpNorm<Eigen::Infinity>();\n        norm_ATy = (qp.A.transpose()*y).template lpNorm<Eigen::Infinity>();\n        norm_q = qp.q.template lpNorm<Eigen::Infinity>();\n        _max_Px_ATy_q_norm = fmax(norm_Px, fmax(norm_ATy, norm_q));\n\n        _info.res_prim = residual_prim(qp);\n        _info.res_dual = residual_dual(qp);\n    }\n\n    Scalar rho_estimate(const Scalar rho0, const qp_t &qp) const\n    {\n        Scalar rp_norm, rd_norm;\n        rp_norm = _info.res_prim / (_max_Ax_z_norm + DIV_BY_ZERO_REGUL);\n        rd_norm = _info.res_dual / (_max_Px_ATy_q_norm + DIV_BY_ZERO_REGUL);\n\n        Scalar rho_new = rho0 * sqrt(rp_norm/(rd_norm + DIV_BY_ZERO_REGUL));\n        return rho_new;\n    }\n\n    Scalar eps_prim(const qp_t &qp) const\n    {\n        return _settings.eps_abs + _settings.eps_rel * _max_Ax_z_norm;\n    }\n\n    Scalar eps_dual(const qp_t &qp) const\n    {\n        return _settings.eps_abs + _settings.eps_rel * _max_Px_ATy_q_norm ;\n    }\n\n    Scalar residual_prim(const qp_t &qp) const\n    {\n        return (qp.A*x - z).template lpNorm<Eigen::Infinity>();\n    }\n\n    Scalar residual_dual(const qp_t &qp) const\n    {\n        return (qp.P*x + qp.q + qp.A.transpose()*y).template lpNorm<Eigen::Infinity>();\n    }\n\n    bool termination_criteria(const qp_t &qp)\n    {\n        // check residual norms to detect optimality\n        if (_info.res_prim <= eps_prim(qp) && _info.res_dual <= eps_dual(qp)) {\n            return true;\n        }\n\n        return false;\n    }\n\n#ifdef QP_SOLVER_PRINTING\n    void print_status(const qp_t &qp) const\n    {\n        Scalar obj = 0.5 * x.dot(qp.P*x) + qp.q.dot(x);\n\n        if (iter == _settings.check_termination) {\n            printf(\"iter   obj       rp        rd\\n\");\n        }\n        printf(\"%4d  %.2e  %.2e  %.2e\\n\", iter, obj, _info.res_prim, _info.res_dual);\n    }\n#endif\n};\n\n} // namespace qp_solver\n\n#endif // QP_SOLVER_H\n", "meta": {"hexsha": "e8563842568fe752d2b67ded5d6a6c6db536aac9", "size": 18198, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/unsupported/qp_solver.hpp", "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": "include/unsupported/qp_solver.hpp", "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": "include/unsupported/qp_solver.hpp", "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": 30.4824120603, "max_line_length": 122, "alphanum_fraction": 0.5630289043, "num_tokens": 4733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5145944704339167}}
{"text": "/**\n * @file\n * @brief Action of a generic n-joint robot.\n * @copyright 2020, Max Planck Gesellschaft. All rights reserved.\n * @license BSD 3-clause\n */\n#pragma once\n\n#include <limits>\n#include <string>\n#include <vector>\n\n#include <Eigen/Eigen>\n#include <serialization_utils/cereal_eigen.hpp>\n\n#include <robot_interfaces/loggable.hpp>\n\nnamespace robot_interfaces\n{\n/**\n * @brief Action of a generic n-joint robot.\n *\n * This action type can be used for all n-joint robots that expect torque or\n * position commands on joint-level.\n *\n * @tparam N Number of joints.\n */\ntemplate <size_t N>\nstruct NJointAction : public Loggable\n{\n    //! @brief Number of joints.\n    static constexpr size_t num_joints = N;\n\n    typedef Eigen::Matrix<double, N, 1> Vector;\n\n    //! Desired torque command (in addition to position controller).\n    Vector torque;\n    //! Desired position.  Set to NaN to disable position controller.\n    Vector position;\n    //! P-gain for position controller.  If NaN, default is used.\n    Vector position_kp;\n    //! D-gain for position controller.  If NaN, default is used.\n    Vector position_kd;\n\n    template <class Archive>\n    void serialize(Archive& archive)\n    {\n        archive(torque, position, position_kp, position_kd);\n    }\n\n    std::vector<std::string> get_name() override\n    {\n        return {\"torque\", \"position\", \"position_kp\", \"position_kd\"};\n    }\n\n    std::vector<std::vector<double>> get_data() override\n    {\n        // first map the Eigen vectors to std::vectors\n        std::vector<double> torque_;\n        torque_.resize(torque.size());\n        Vector::Map(&torque_[0], torque.size()) = torque;\n\n        std::vector<double> position_;\n        position_.resize(position.size());\n        Vector::Map(&position_[0], position.size()) = position;\n\n        std::vector<double> position_kp_;\n        position_kp_.resize(position_kp.size());\n        Vector::Map(&position_kp_[0], position_kp.size()) = position_kp;\n\n        std::vector<double> position_kd_;\n        position_kd_.resize(position_kd.size());\n        Vector::Map(&position_kd_[0], position_kd.size()) = position_kd;\n\n        // then return them in a fixed size vector of vectors to avoid\n        // copying due to pushing back value of information!\n        std::vector<std::vector<double>> result;\n        result = {torque_, position_, position_kp_, position_kd_};\n\n        return result;\n    }\n\n    /**\n     * @brief Create action with desired torque and (optional) position.\n     *\n     * The resulting torque command sent to the robot is\n     *\n     *     sent_torque = torque + PD(position)\n     *\n     * To disable the position controller, set the target position to NaN.\n     * The controller is executed joint-wise, so it is possible to run it\n     * only for some joints by setting a target position for these joints\n     * and setting the others to NaN.\n     *\n     * The specified torque is always added to the result of the position\n     * controller, so if you only want to run the position controller, make\n     * sure to set `torque` to zero for all joints.\n     *\n     * For more explicit code, the static factory methods `Torque`,\n     * `Position`, `TorqueAndPosition` and `Zero` should be used instead\n     * directly creating actions through this constructor.\n     *\n     * @param torque  Desired torque.\n     * @param position  Desired position.  Set values to NaN to disable\n     *     position controller for the corresponding joints\n     * @param position_kp  P-gains for the position controller.  Set to NaN\n     *     to use default values.\n     * @param position_kd  D-gains for the position controller.  Set to NaN\n     *     to use default values.\n     */\n    NJointAction(Vector torque = Vector::Zero(),\n                 Vector position = None(),\n                 Vector position_kp = None(),\n                 Vector position_kd = None())\n        : torque(torque),\n          position(position),\n          position_kp(position_kp),\n          position_kd(position_kd)\n    {\n    }\n\n    /**\n     * @brief Create an action that only contains a torque command.\n     *\n     * @param torque  Desired torque.\n     *\n     * @return Pure \"torque action\".\n     */\n    static NJointAction Torque(Vector torque)\n    {\n        return NJointAction(torque);\n    }\n\n    /**\n     * @brief Create an action that only contains a position command.\n     *\n     * @param position Desired position.\n     * @param kp P-gain for position controller.  If not set, default is\n     *     used.  Set to NaN for specific joints to use default for this\n     *     joint.\n     * @param kd D-gain for position controller.  If not set, default is\n     *     used.  Set to NaN for specific joints to use default for this\n     *     joint.\n     *\n     * @return Pure \"position action\".\n     */\n    static NJointAction Position(Vector position,\n                                 Vector kp = None(),\n                                 Vector kd = None())\n    {\n        return NJointAction(Vector::Zero(), position, kp, kd);\n    }\n\n    /**\n     * @brief Create an action with both torque and position commands.\n     *\n     * @param torque Desired torque.\n     * @param position Desired position.  Set to NaN for specific joints to\n     *     disable position control for this joint.\n     * @param kp P-gain for position controller.  If not set, default is\n     *     used.  Set to NaN for specific joints to use default for this\n     *     joint.\n     * @param kd D-gain for position controller.  If not set, default is\n     *     used.  Set to NaN for specific joints to use default for this\n     *     joint.\n     *\n     * @return Action with both torque and position commands.\n     */\n    static NJointAction TorqueAndPosition(Vector torque,\n                                          Vector position,\n                                          Vector position_kp = None(),\n                                          Vector position_kd = None())\n    {\n        return NJointAction(torque, position, position_kp, position_kd);\n    }\n\n    /**\n     * @brief Create a zero-torque action.\n     *\n     * @return Zero-torque action with position control disabled.\n     */\n    static NJointAction Zero()\n    {\n        return NJointAction();\n    }\n\n    /**\n     * @brief Create a NaN-Vector.  Helper function to set defaults for\n     *     position.\n     *\n     * @return Vector with all elements set to NaN.\n     */\n    static Vector None()\n    {\n        return Vector::Constant(std::numeric_limits<double>::quiet_NaN());\n    }\n};\n\n}  // namespace robot_interfaces\n", "meta": {"hexsha": "2eda4c235709061156077d6bd0aa5f72249b61b0", "size": 6541, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/robot_interfaces/n_joint_action.hpp", "max_stars_repo_name": "s-bl/robot_interfaces", "max_stars_repo_head_hexsha": "aed206060e9976777718d1ed5364a03376254297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-05-31T13:49:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T06:46:17.000Z", "max_issues_repo_path": "include/robot_interfaces/n_joint_action.hpp", "max_issues_repo_name": "s-bl/robot_interfaces", "max_issues_repo_head_hexsha": "aed206060e9976777718d1ed5364a03376254297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2019-09-25T15:46:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-12T14:02:38.000Z", "max_forks_repo_path": "include/robot_interfaces/n_joint_action.hpp", "max_forks_repo_name": "s-bl/robot_interfaces", "max_forks_repo_head_hexsha": "aed206060e9976777718d1ed5364a03376254297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-19T13:31:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T17:49:10.000Z", "avg_line_length": 32.705, "max_line_length": 76, "alphanum_fraction": 0.6203944351, "num_tokens": 1487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317475, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5145944651187825}}
{"text": "#include \"debug.h\"\n#include <CGAL/intersections.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Mesh_3/Robust_intersection_traits_3.h>\n\n#include <CGAL/Mesh_triangulation_3.h>\n#include <CGAL/Mesh_complex_3_in_triangulation_3.h>\n#include <CGAL/Mesh_criteria_3.h>\n\n#include <CGAL/Polyhedral_mesh_domain_3.h>\n#include <CGAL/make_mesh_3.h>\n#include <CGAL/refine_mesh_3.h>\n\n// IO\n#include <CGAL/IO/Polyhedron_iostream.h>\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\nusing namespace CGAL::parameters;\n\n// Domain\n// (we use exact intersection computation with Robust_intersection_traits_3)\nstruct K: public CGAL::Exact_predicates_inexact_constructions_kernel {};\ntypedef CGAL::Mesh_3::Robust_intersection_traits_3<K> Geom_traits;\ntypedef CGAL::Polyhedron_3<Geom_traits> Polyhedron;\ntypedef CGAL::Polyhedral_mesh_domain_3<Polyhedron, Geom_traits> Mesh_domain;\n\n// Triangulation\ntypedef CGAL::Mesh_triangulation_3<Mesh_domain>::type Tr;\ntypedef CGAL::Mesh_complex_3_in_triangulation_3<Tr> C3t3;\n\n// Mesh Criteria\ntypedef CGAL::Mesh_criteria_3<Tr> Mesh_criteria;\ntypedef Mesh_criteria::Facet_criteria Facet_criteria;\ntypedef Mesh_criteria::Cell_criteria Cell_criteria;\n\ntemplate <typename T>\nT set_arg(const std::string& param_name,\n          const std::string& param_string,\n          const po::variables_map& vm)\n{\n  if ( vm.count(param_name) )\n  {\n    T param_value = vm[param_name].as<T>();\n    std::cout << param_string << \": \" << param_value << \"\\n\";\n    return param_value;\n  }\n  else\n  {\n    std::cout << param_string << \" ignored.\\n\";\n    return T();\n  }\n}\n\nint main(int argc, char** argv)\n{\n  po::options_description generic(\"Generic options\");\n  generic.add_options() (\"help\", \"Produce help message\");\n  generic.add_options()(\"file\", po::value<std::string>(), \"Mesh polyhedron contained in that file\");\n\n  po::options_description mesh(\"Mesh generation parameters\");\n  mesh.add_options()(\"facet_angle\", po::value<double>(), \"Set facet angle bound\")\n  (\"facet_size\", po::value<double>(), \"Set facet size bound\")\n  (\"facet_error\", po::value<double>(), \"Set facet approximation error bound\")\n  (\"tet_shape\", po::value<double>(), \"Set tet radius-edge bound\")\n  (\"tet_size\", po::value<double>(), \"Set tet size bound\");\n\n  po::options_description desc(\"Options\");\n  desc.add_options()\n  (\"exude\", po::value<double>(), \"Exude mesh after refinement. arg is time_limit.\")\n  (\"perturb\", po::value<double>(), \"Perturb (sliver removal) mesh after refinement. arg is time_limit\")\n  (\"lloyd\", po::value<int>(), \"Lloyd-smoothing after refinement. arg is max_iteration_nb\")\n  (\"odt\", po::value<int>(), \"ODT-smoothing after refinement. arg is max_iteration_nb\")\n  (\"convergence\", po::value<double>()->default_value(0.02), \"Convergence ratio for smoothing functions\")\n  (\"min_displacement\", po::value<double>()->default_value(0.01), \"Minimal displacement ratio for smoothing functions (moves that are below that ratio will not be done)\")\n  (\"time_limit\", po::value<double>()->default_value(0), \"Max time for smoothing functions\")\n  (\"off_vertices\", \"Use polyhedron vertices as initialization step\")\n  (\"no_label_rebind\", \"Don't rebind cell labels in medit output\")\n  (\"show_patches\", \"Show surface patches in medit output\");\n\n\n  po::options_description cmdline_options(\"Usage\");\n  cmdline_options.add(generic).add(mesh).add(desc);\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, cmdline_options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\") || argc < 2)\n  {\n    std::cout << cmdline_options << std::endl;\n    return 1;\n  }\n\n  std::cout << \"=========== Params ===========\"<< std::endl;\n\n  double facet_angle = set_arg<double>(\"facet_angle\",\"Facet angle\",vm);\n  double facet_size = set_arg<double>(\"facet_size\",\"Facet size\",vm);\n  double facet_error = set_arg<double>(\"facet_error\",\"Facet approximation error\",vm);\n\n  double tet_shape = set_arg<double>(\"tet_shape\",\"Tet shape (radius-edge)\",vm);\n  double tet_size = set_arg<double>(\"tet_size\",\"Tet size\",vm);\n\n  std::cout << std::endl;\n  std::string polyhedron_filename = set_arg<std::string>(\"file\", \"Filename\", vm);\n\n  std::cout << \"==============================\"<< std::endl;\n  std::cout << std::endl;\n\n  if ( polyhedron_filename.empty() )\n  {\n    std::cout << \"No file selected. Exit.\\n\";\n    return 0;\n  }\n\n  // Loads polyhedron\n  Polyhedron polyhedron;\n  std::ifstream input(polyhedron_filename.c_str());\n  input >> polyhedron;\n\n  using std::atof;\n\n  // Domain\n  Mesh_domain domain(polyhedron);\n\n  // Mesh criteria\n  Facet_criteria facet_criteria(facet_angle,\n                                facet_size,\n                                facet_error); // angle, size, approximation\n  Cell_criteria cell_criteria(tet_shape,\n                              tet_size); // radius-edge ratio, size\n  Mesh_criteria criteria(facet_criteria, cell_criteria);\n\n  // Mesh generation\n  C3t3 c3t3;\n  if ( !vm.count(\"off_vertices\") )\n  {\n    c3t3 = CGAL::make_mesh_3<C3t3>(domain, criteria, no_exude(), no_perturb());\n  }\n  else\n  {\n    c3t3.insert_surface_points(polyhedron.points_begin(),\n                               polyhedron.points_end(),\n                               domain.make_surface_index());\n\n    CGAL::refine_mesh_3<C3t3>(c3t3, domain, criteria, no_exude(), no_perturb());\n  }\n\n  // Output\n  std::ofstream medit_file_before(\"out_before.mesh\");\n  c3t3.output_to_medit(medit_file_before,\n                       vm.count(\"no_label_rebind\") == 0, vm.count(\"show_patches\") > 0);\n\n  // Odt\n  if (  vm.count(\"odt\") )\n  {\n    CGAL::odt_optimize_mesh_3(c3t3, domain,\n                              max_iteration_number=vm[\"odt\"].as<int>(),\n                              convergence=vm[\"convergence\"].as<double>(),\n                              sliver_bound=vm[\"min_displacement\"].as<double>(),\n                              time_limit=vm[\"time_limit\"].as<double>());\n  }\n\n  // Lloyd\n  if ( vm.count(\"lloyd\") )\n  {\n    CGAL::lloyd_optimize_mesh_3(c3t3, domain,\n                                max_iteration_number=vm[\"lloyd\"].as<int>(),\n                                convergence=vm[\"convergence\"].as<double>(),\n                                sliver_bound=vm[\"min_displacement\"].as<double>(),\n                                time_limit=vm[\"time_limit\"].as<double>());\n  }\n\n  // Perturbation\n  if ( vm.count(\"perturb\") )\n  {\n    CGAL::perturb_mesh_3(c3t3, domain, time_limit = vm[\"perturb\"].as<double>() );\n  }\n\n  // Exudation\n  if ( vm.count(\"exude\") )\n  {\n    CGAL::exude_mesh_3(c3t3, time_limit = vm[\"exude\"].as<double>());\n  }\n\n  double min_angle = 181.;\n  for ( C3t3::Cell_iterator cit = c3t3.cells_begin() ;\n       cit != c3t3.cells_end() ;\n       ++cit )\n  {\n    min_angle = (std::min)(min_angle,\n                           CGAL::to_double(CGAL::Mesh_3::minimum_dihedral_angle(c3t3.triangulation().tetrahedron(cit))));\n  }\n\n  std::cerr << \"Min angle: \" << min_angle << std::endl;\n\n\n  // Output\n  std::ofstream medit_file(\"out.mesh\");\n  c3t3.output_to_medit(medit_file, vm.count(\"no_label_rebind\") == 0, vm.count(\"show_patches\") > 0);\n\n  return 0;\n}\n", "meta": {"hexsha": "4db2165fa22ca3d65b03a023a351679db0618ebf", "size": 7075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Mesh_3/archive/applications/mesh_polyhedral_domain.cpp", "max_stars_repo_name": "antoniospg/cgal", "max_stars_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T09:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T05:00:23.000Z", "max_issues_repo_path": "Mesh_3/archive/applications/mesh_polyhedral_domain.cpp", "max_issues_repo_name": "antoniospg/cgal", "max_issues_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-10T13:32:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T12:23:20.000Z", "max_forks_repo_path": "Mesh_3/archive/applications/mesh_polyhedral_domain.cpp", "max_forks_repo_name": "antoniospg/cgal", "max_forks_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T15:26:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-21T15:26:25.000Z", "avg_line_length": 34.512195122, "max_line_length": 169, "alphanum_fraction": 0.6539929329, "num_tokens": 1858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.5145944641690398}}
{"text": "\n#include <functional>\n#include <future>\n#include <iostream>\n#include <random>\n#include <thread>\n\n#include <catch.hpp>\n\n#include <Eigen/Dense>\n\n#include <spii/spii.h>\n\nextern \"C\" {\n\t#include \"matrix.h\"\n\t#include \"matrix2.h\"\n\t#include \"sparse2.h\"\n\t#undef min\n\t#undef max\n\t#undef catch\n}\n\ntemplate<typename EigenMat>\nMAT* Eigen_to_Meschach(const EigenMat& eigen_matrix)\n{\n\tauto m = eigen_matrix.rows();\n\tauto n = eigen_matrix.cols();\n\n\tauto A = m_get(int(m), int(n));\n\tfor (int i = 0; i < m; ++i) {\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tA->me[i][j] = eigen_matrix(i, j);\n\t\t}\n\t}\n\n\treturn A;\n}\n\nTEST_CASE(\"BKP-dense\", \"\")\n{\n\tusing namespace std;\n\tusing namespace Eigen;\n\n\tint n = 4;\n\n\tVectorXd x(4), b(4);\n\tb << 1, 2, 3, 4;\n\n\tMatrixXd A(4, 4);\n\tA.row(0) << 1, 2, 3, 1;\n\tA.row(1) << 2, 6, 1, 8;\n\tA.row(2) << 3, 1, 7, 6;\n\tA.row(3) << 1, 8, 6, 6;\n\tREQUIRE((A - A.transpose()).norm() == 0);\n\n\t// Sanity check.\n\tx = A.lu().solve(b);\n\tINFO(x);\n\tCHECK((A * x - b).norm() <= 1e-10);\n\n\t// Convert matrix to Meschach format.\n\tauto Amat = Eigen_to_Meschach(A);\n\tm_foutput(stderr, Amat);\n\n\t// Factorize the matrix.\n\tPERM* pivot  = px_get(4);\n\tPERM* block = px_get(4);\n\tspii_at_scope_exit(\n\t\tpx_free(pivot);\n\t\tpx_free(block);\n\t);\n\tBKPfactor(Amat, pivot, block);\n\n\t// Print the results.\n\tm_foutput(stderr, Amat);\n\tspii_at_scope_exit( m_free(Amat); );\n\tpx_foutput(stderr, block);\n\tpx_foutput(stderr, pivot);\n\tcerr << endl << endl;\n\n\t// Solve the linear system.\n\tVEC* bvec = v_get(4);\n\tspii_at_scope_exit( v_free(bvec); );\n\tfor (int i = 0; i < 4; ++i) {\n\t\tbvec->ve[i] = b(i);\n\t}\n\tVEC* xvec = BKPsolve(Amat, pivot, block, bvec, nullptr);\n\tspii_at_scope_exit( v_free(xvec); );\n\tfor (int i = 0; i < 4; ++i) {\n\t\tx(i) = xvec->ve[i];\n\t}\n\tINFO(x);\n\tINFO(A * x);\n\tCHECK((A * x - b).norm() <= 1e-10);\n\n\tMatrixXd B(4, 4);\n\tMatrixXd Q(4, 4);\n\tVectorXd tau(4);\n\tVectorXd lambda(4);\n\tB.setZero();\n\tQ.setZero();\n\n\tSelfAdjointEigenSolver<MatrixXd> eigensolver;\n\n\tdouble delta = 1e-10;\n\n\t// Extract the block diagonal matrix.\n\tint onebyone;\n\tfor (int i = 0; i < n; i = onebyone ? i+1 : i+2 ) {\n\t\tonebyone = ( block->pe[i] == i );\n\t\tif ( onebyone ) {\n\t\t    B(i, i) = m_entry(Amat,i,i);\n\t\t\tlambda(i) = B(i, i);\n\t\t\tif (lambda(i) >= delta) {\n\t\t\t\ttau(i) = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttau(i) = delta - lambda(i);\n\t\t\t}\n\t\t\tQ(i, i) = 1;\n\t\t}\n\t\telse {\n\t\t    auto a11 = m_entry(Amat,i,i);\n\t\t    auto a22 = m_entry(Amat,i+1,i+1);\n\t\t    auto a12 = m_entry(Amat,i+1,i);\n\t\t\tB(i,   i)   = a11;\n\t\t\tB(i+1, i)   = a12;\n\t\t\tB(i,   i+1) = a12;\n\t\t\tB(i+1, i+1) = a22;\n\t\t\teigensolver.compute(B.block(i, i, 2, 2));\n\n\t\t\tlambda(i)   = eigensolver.eigenvalues()(0);\n\t\t\tlambda(i+1) = eigensolver.eigenvalues()(1);\n\t\t\tfor (int k = i; k <= i + 1; ++k) {\n\t\t\t\tif (lambda(k) >= delta) {\n\t\t\t\t\ttau(k) = 0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttau(k) = delta - lambda(k);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tQ.block(i, i, 2, 2) = eigensolver.eigenvectors();\n\t\t}\n\t}\n\tcerr << \"B = \\n\" << B << endl << endl;\n\tcerr << \"lambda = \" << tau.transpose() << endl << endl;\n\tcerr << \"tau = \" << tau.transpose() << endl << endl;\n\tcerr << \"Q = \\n\" << Q << endl << endl;\n\tcerr << \"Q*lambda*Q^T = \\n\" << Q * lambda.asDiagonal() * Q.transpose() << endl << endl;\n\n\t// Check that the block-wise eigendecomposition was correct.\n\tCHECK(((B - Q * lambda.asDiagonal() * Q.transpose()).norm()) < 1e-10);\n\n\tMatrixXd F = Q * tau.asDiagonal() * Q.transpose();\n\tcerr << \"F = Q*tau*Q^T = \\n\" << F << endl << endl;\n\tcerr << \"B + F = \\n\" << B + F << endl << endl;\n}\n\n#ifdef USE_OPENMP\nTEST_CASE(\"BKP-dense-threadsafe\")\n{\n\tusing namespace std;\n\tusing namespace Eigen;\n\n\tauto stress_test = [](unsigned seed)\n\t{\n\t\tmt19937_64 engine(seed);\n\t\tauto rand = bind(uniform_int_distribution<int>(-10, 10), ref(engine));\n\t\tconst int n = 400;\n\n\t\tMatrixXd A(n, n);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tfor (int j = 0; j < n; ++j) {\n\t\t\t\tA(i, j) = rand();\n\t\t\t}\n\t\t}\n\t\tA = A.transpose() * A;\n\t\tauto Amat = Eigen_to_Meschach(A);\n\t\tspii_at_scope_exit( m_free(Amat); );\n\n\t\t// Factorize the matrix.\n\t\tPERM* pivot = px_get(n);\n\t\tspii_at_scope_exit( px_free(pivot); );\n\t\tPERM* block = px_get(n);\n\t\tspii_at_scope_exit( px_free(block); );\n\t\tBKPfactor(Amat, pivot, block);\n\n\t\tVectorXd b(n);\n\t\tVEC* bvec = v_get(n);\n\t\tspii_at_scope_exit( v_free(bvec); );\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tb(i) = rand();\n\t\t\tbvec->ve[i] = b(i);\n\t\t}\n\n\t\tfor (int iteration = 1; iteration <= 20; ++iteration) {\n\t\t\tVEC* xvec = BKPsolve(Amat, pivot, block, bvec, 0);\n\t\t\tVectorXd x(n);\n\t\t\tfor (int i = 0; i < n; ++i) {\n\t\t\t\tx(i) = xvec->ve[i];\n\t\t\t}\n\t\t\tv_free(xvec);\n\t\t\tdouble err = (A * x - b).norm() / b.norm();\n\t\t\tif (err > 1e-6) {\n\t\t\t\tthrow std::runtime_error(\"Not thread-safe!\");\n\t\t\t}\n\t\t}\t\t\n\t};\n\n\n\ttry {\n\t\tauto f1 = async(launch::async, stress_test, 1);\n\t\tauto f2 = async(launch::async, stress_test, 2);\n\t\tauto f3 = async(launch::async, stress_test, 3);\n\t\tauto f4 = async(launch::async, stress_test, 4);\n\t\tauto f5 = async(launch::async, stress_test, 5);\n\t\tf1.get();\n\t\tf2.get();\n\t\tf3.get();\n\t\tf4.get();\n\t\tf5.get();\n\t\tSUCCEED();\n\t}\n\tcatch (...) {\n\t\tFAIL();\n\t}\n}\n#endif\n\n/*\nTEST_CASE(\"BKP-sparse\", \"\")\n{\n\tint m = 5;\n\tint n = 5;\n\tint deg = 5;\n\tSPMAT* A = sp_get(m, n, deg);\n\n\tint I[25]    = {1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5};\n\tint J[25]    = {1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5};\n\tdouble V[25] = {1,7,3,5,1,5,2,6,6,7,4,1,2,8,1,7,5,9,1,4,1,9,0,7,7};\n\n\tfor (int i = 0; i < 25; ++i) {\n\t\tif (V[i] != 0) {\n\t\t\tsp_set_val(A, I[i] - 1, J[i] - 1, V[i]);\n\t\t}\n\t}\n\n\tsp_foutput2(stderr, A);\n\n\tSPMAT* B = sp_copy(A);\n\tPERM* pivot  = px_get(5);\n\tPERM* blocks = px_get(5);\n\tspBKPfactor(B, pivot, blocks, 1e-16);\n\n\tsp_fo1utput2(stderr, B);\n\tpx_foutput(stderr, pivot);\n\tpx_foutput(stderr, blocks);\n\n\tSP_FREE(A);\n\tSP_FREE(B);\n}\n*/", "meta": {"hexsha": "db6c80c514ab732ca6480c9ca965937ae8306076", "size": 5639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_meschach.cpp", "max_stars_repo_name": "PetterS/spii", "max_stars_repo_head_hexsha": "98c5847223d7c3febea5a1aac6f4978dfef207ec", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-03-03T16:21:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T08:02:12.000Z", "max_issues_repo_path": "tests/test_meschach.cpp", "max_issues_repo_name": "nashdingsheng/spii", "max_issues_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-07-16T14:41:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-09T19:27:22.000Z", "max_forks_repo_path": "tests/test_meschach.cpp", "max_forks_repo_name": "nashdingsheng/spii", "max_forks_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-09-21T23:09:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T20:20:30.000Z", "avg_line_length": 21.4410646388, "max_line_length": 88, "alphanum_fraction": 0.5598510374, "num_tokens": 2192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5145419486719611}}
{"text": "#define _USE_MATH_DEFINES\n\n#include <ceres/jet.h>\n#include <ceres/rotation.h>\n#include <geometry/covariance.h>\n#include <gmock/gmock.h>\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <random>\n#include <unsupported/Eigen/AutoDiff>\n\n#include \"geometry/transformations_functions.h\"\n\nclass CovarianceFixture : public ::testing::Test {\n public:\n  CovarianceFixture()\n      : camera(geometry::Camera::CreatePerspectiveCamera(focal, 0.0, 0.0)),\n        pose(geometry::Pose(Vec3d(0., 0., 0.), Vec3d(0, 0, 0))) {\n    point_adiff[0].value() = point[0] = 0.;\n    point_adiff[1].value() = point[1] = 0.;\n    point_adiff[2].value() = point[2] = 3.;\n    observation << 0.0, 0.0;\n  }\n\n  void RunAutodiffEval(const geometry::Camera& camera,\n                       const geometry::Pose& pose) {\n    // Prepare Eigen's Autodiff structures\n    for (int i = 0; i < 3; ++i) {\n      point_adiff[i].derivatives() = VecXd::Unit(3, i);\n    }\n\n    VecX<AScalar> pose_adiff(6);\n    pose_adiff.segment<3>(3) = pose.TranslationCameraToWorld();\n    pose_adiff.segment<3>(0) = pose.RotationCameraToWorldMin();\n    for (int i = 0; i < 6; ++i) {\n      pose_adiff(i).derivatives().resize(3);\n      pose_adiff(i).derivatives().setZero();\n    }\n\n    VecX<AScalar> camera_adiff(3);\n    const VecXd camera_params = camera.GetParametersValues();\n    for (int i = 0; i < camera_params.size(); ++i) {\n      camera_adiff(i).value() = camera_params(i);\n      camera_adiff(i).derivatives().resize(3);\n      camera_adiff(i).derivatives().setZero();\n    }\n\n    // Run project with Autodiff types to get expected jacobian\n    AScalar transformed[3];\n    geometry::PoseFunctor::Forward(point_adiff, pose_adiff.data(),\n                                   &transformed[0]);\n    geometry::Dispatch<geometry::ProjectFunction>(\n        camera.GetProjectionType(), transformed, camera_adiff.data(),\n        projection_expected);\n  }\n\n  template <class MAT>\n  void CheckJacobian(const MAT& jacobian) {\n    const double eps = 1e-12;\n    for (int i = 0; i < 2; ++i) {\n      for (int j = 0; j < 3; ++j) {\n        ASSERT_NEAR(projection_expected[i].derivatives()(j), jacobian(i, j),\n                    eps);\n      }\n      std::cout << projection_expected[i].value() << std::endl;\n    }\n  }\n\n  const double focal{1.0};\n  double point[3];\n  typedef Eigen::AutoDiffScalar<VecXd> AScalar;\n  AScalar point_adiff[3];\n  AScalar projection_expected[2];\n  Vec2d observation;\n\n  const geometry::Camera camera;\n  const geometry::Pose pose;\n};\n\nTEST_F(CovarianceFixture, EvaluatesPointJacobian) {\n  Vec3d point_tmp(point[0], point[1], point[2]);\n\n  const auto result = geometry::covariance::ComputeJacobianReprojectionError(\n      camera, pose, observation, point_tmp);\n\n  RunAutodiffEval(camera, pose);\n  CheckJacobian(result.first);\n  for (int i = 0; i < 2; ++i) {\n    ASSERT_NEAR(0., result.second(i), 1e-10);\n  }\n}\n\nTEST_F(CovarianceFixture, EvaluatesPointCovarianceKO) {\n  Vec3d point_tmp(point[0], point[1], point[2]);\n\n  auto covariance = geometry::covariance::ComputePointInverseCovariance(\n                        {camera}, {pose}, {observation}, point_tmp)\n                        .first;\n\n  // Non-determined covariance for 1 projection\n  ASSERT_TRUE(covariance.determinant() < 1e-12);\n}\n\nTEST_F(CovarianceFixture, EvaluatesPointCovarianceOK) {\n  geometry::Pose pose_rotated_y;\n  pose_rotated_y.SetWorldToCamRotation(Vec3d(0, -M_PI_2, 0));\n  pose_rotated_y.SetOrigin(Vec3d(4, 0, 3));\n  Vec3d point_tmp(point[0], point[1], point[2]);\n\n  auto covariance = geometry::covariance::ComputePointInverseCovariance(\n                        {camera, camera}, {pose, pose_rotated_y},\n                        {observation, observation}, point_tmp)\n                        .first;\n\n  // Two pose looking with an angle of 90 degres\n  ASSERT_TRUE(covariance.determinant() > 1e-12);\n}\n\nTEST_F(CovarianceFixture, EvaluatesPointCovarianceSmallBaseline) {\n  const double baseline = 1e-5;\n  const double angle = M_PI_2 - std::abs(std::atan2(point[2], baseline));\n\n  geometry::Pose pose_rotated_y;\n  pose_rotated_y.SetWorldToCamRotation(Vec3d(0, angle, 0));\n  pose_rotated_y.SetOrigin(Vec3d(baseline, 0, 0));\n  Vec3d point_tmp(point[0], point[1], point[2]);\n\n  auto covariance = geometry::covariance::ComputePointInverseCovariance(\n                        {camera, camera}, {pose, pose_rotated_y},\n                        {observation, observation}, point_tmp)\n                        .first;\n\n  ASSERT_TRUE(covariance.determinant() < 1e-12);\n}\n", "meta": {"hexsha": "bab5f24b0261ded5221162f9b35858fb3d53fd6b", "size": 4492, "ext": "cc", "lang": "C++", "max_stars_repo_path": "opensfm/src/geometry/test/covariance_test.cc", "max_stars_repo_name": "ricklentz/OpenSfM", "max_stars_repo_head_hexsha": "b44b5f2b533b6fce8055b3a5a98a59bc22ae2cf6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-27T07:05:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T01:10:14.000Z", "max_issues_repo_path": "opensfm/src/geometry/test/covariance_test.cc", "max_issues_repo_name": "ricklentz/OpenSfM", "max_issues_repo_head_hexsha": "b44b5f2b533b6fce8055b3a5a98a59bc22ae2cf6", "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": "opensfm/src/geometry/test/covariance_test.cc", "max_forks_repo_name": "ricklentz/OpenSfM", "max_forks_repo_head_hexsha": "b44b5f2b533b6fce8055b3a5a98a59bc22ae2cf6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-01T01:10:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T01:10:15.000Z", "avg_line_length": 32.7883211679, "max_line_length": 77, "alphanum_fraction": 0.6498219056, "num_tokens": 1267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.5145419371247953}}
{"text": "#include \"gtest/gtest.h\"\n#include \"solvers/qp_solver.hpp\"\n#include <Eigen/IterativeLinearSolvers>\n\nusing namespace qp_solver;\n\ntemplate <typename _Scalar=double>\nclass _SimpleQP : public QP<2, 3, _Scalar>\n{\npublic:\n    Eigen::Matrix<_Scalar, 2, 1> SOLUTION;\n    _SimpleQP()\n    {\n        this->P << 4, 1,\n                   1, 2;\n        this->q << 1, 1;\n        this->A << 1, 1,\n                   1, 0,\n                   0, 1;\n        this->l << 1, 0, 0;\n        this->u << 1, 0.7, 0.7;\n\n        this->SOLUTION << 0.3, 0.7;\n    }\n};\n\nusing SimpleQP = _SimpleQP<double>;\n\nTEST(QPSolverTest, testSimpleQP) {\n    SimpleQP qp;\n    QPSolver<SimpleQP> prob;\n\n    prob.settings().max_iter = 1000;\n\n    prob.setup(qp);\n    prob.solve(qp);\n    Eigen::Vector2d sol = prob.primal_solution();\n\n    EXPECT_TRUE(sol.isApprox(qp.SOLUTION, 1e-2));\n    EXPECT_LT(prob.iter, prob.settings().max_iter);\n    EXPECT_EQ(prob.info().status, SOLVED);\n}\n\n\nTEST(QPSolverTest, testSinglePrecisionFloat) {\n    using SimpleQPf = _SimpleQP<float>;\n    SimpleQPf qp;\n    QPSolver<SimpleQPf> prob;\n\n    prob.setup(qp);\n    prob.solve(qp);\n    Eigen::Vector2f sol = prob.primal_solution();\n\n    EXPECT_TRUE(sol.isApprox(qp.SOLUTION, 1e-2));\n    EXPECT_LT(prob.iter, prob.settings().max_iter);\n    EXPECT_EQ(prob.info().status, SOLVED);\n}\n\nTEST(QPSolverTest, testConstraintViolation) {\n    SimpleQP qp;\n    QPSolver<SimpleQP> prob;\n\n    prob.settings().eps_rel = 1e-4f;\n    prob.settings().eps_abs = 1e-4f;\n\n    prob.setup(qp);\n    prob.solve(qp);\n    Eigen::Vector2d sol = prob.primal_solution();\n\n    // check feasibility (with some epsilon margin)\n    Eigen::Vector3d lower = qp.A*sol - qp.l;\n    Eigen::Vector3d upper = qp.A*sol - qp.u;\n    EXPECT_GE(lower.minCoeff(), -1e-3);\n    EXPECT_LE(upper.maxCoeff(), 1e-3);\n}\n\nTEST(QPSolverTest, testAdaptiveRho) {\n    SimpleQP qp;\n    QPSolver<SimpleQP> prob;\n\n    prob.settings().adaptive_rho = false;\n    prob.settings().adaptive_rho_interval = 10;\n\n    prob.setup(qp);\n    prob.solve(qp);\n\n    EXPECT_EQ(prob.info().status, SOLVED);\n}\n\nTEST(QPSolverTest, testAdaptiveRhoImprovesConvergence) {\n    SimpleQP qp;\n    QPSolver<SimpleQP> prob;\n\n    prob.settings().warm_start = false;\n    prob.settings().max_iter = 1000;\n    prob.settings().rho = 0.1;\n\n    // solve whithout adaptive rho\n    prob.settings().adaptive_rho = false;\n    prob.setup(qp);\n    prob.solve(qp);\n    int prev_iter = prob.info().iter;\n\n    // solve with adaptive rho\n    prob.settings().adaptive_rho = true;\n    prob.settings().adaptive_rho_interval = 10;\n    prob.solve(qp);\n\n    auto info = prob.info();\n    EXPECT_LT(info.iter, prob.settings().max_iter);\n    EXPECT_LT(info.iter, prev_iter); // adaptive rho should improve :)\n    EXPECT_EQ(info.status, SOLVED);\n}\n\n/* BUG: Eigen::ConjugateGradient fails with assert when using fixed-size matrix.\n *      Only works in Release mode. */\n#ifdef EIGEN_NO_DEBUG\nTEST(QPSolverTest, testConjugateGradientLinearSolver)\n{\n    SimpleQP qp;\n    QPSolver<SimpleQP, Eigen::ConjugateGradient, Eigen::Lower | Eigen::Upper> prob;\n\n    prob.setup(qp);\n    prob.solve(qp);\n    Eigen::Vector2d sol = prob.primal_solution();\n\n    auto info = prob.info();\n    EXPECT_TRUE(sol.isApprox(qp.SOLUTION, 1e-2));\n    EXPECT_EQ(info.status, SOLVED);\n    EXPECT_LT(info.iter, prob.settings().max_iter); // convergence test\n}\n#endif\n\nTEST(QPSolverTest, TestConstraint) {\n    using qp_t = QP<5, 5, double>;\n    using solver_t = QPSolver<qp_t>;\n    solver_t prob;\n\n    qp_t qp;\n    qp.P.setIdentity();\n    qp.q.setConstant(-1);\n    qp.A.setIdentity();\n\n    int type_expect[5];\n    qp.l(0) = -1e+17;\n    qp.u(0) = 1e+17;\n    type_expect[0] = solver_t::LOOSE_BOUNDS;\n    qp.l(1) = -101;\n    qp.u(1) = 1e+17;\n    type_expect[1] = solver_t::INEQUALITY_CONSTRAINT;\n    qp.l(2) = -1e+17;\n    qp.u(2) = 123;\n    type_expect[2] = solver_t::INEQUALITY_CONSTRAINT;\n    qp.l(3) = -1;\n    qp.u(3) = 1;\n    type_expect[3] = solver_t::INEQUALITY_CONSTRAINT;\n    qp.l(4) = 42;\n    qp.u(4) = 42;\n    type_expect[4] = solver_t::EQUALITY_CONSTRAINT;\n\n    prob.setup(qp);\n\n    for (int i = 0; i < qp.l.rows(); i++) {\n        EXPECT_EQ(prob.constr_type[i], type_expect[i]);\n    }\n}\n", "meta": {"hexsha": "f2c8523599cb08749e8471073ca8dcab94060fa0", "size": 4170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unsupported/qp_solver_test.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/unsupported/qp_solver_test.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/unsupported/qp_solver_test.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": 24.9700598802, "max_line_length": 83, "alphanum_fraction": 0.6335731415, "num_tokens": 1263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5145419316141098}}
{"text": "#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>\n#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>\n#include <CGAL/Three/Scene_group_item.h>\n#include \"ui_Mean_curvature_flow_skeleton_plugin.h\"\n\n#include \"Kernel_type.h\"\n#include \"Scene_surface_mesh_item.h\"\n#include <CGAL/boost/graph/graph_traits_Surface_mesh.h>\n\n#include \"Scene_mcf_item.h\"\n#include \"Scene_points_with_normal_item.h\"\n#include \"Scene_polylines_item.h\"\n#include \"Scene.h\"\n#include <QApplication>\n#include <QMainWindow>\n#include <QInputDialog>\n#include <QElapsedTimer>\n#include <QMessageBox>\n\n#include <Eigen/Sparse>\n\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Eigen_solver_traits.h>\n#include <CGAL/extract_mean_curvature_flow_skeleton.h>\n#include <CGAL/iterator.h>\n#include <CGAL/Polygon_mesh_processing/connected_components.h>\n\n#include <CGAL/boost/graph/split_graph_into_polylines.h>\n#include <CGAL/mesh_segmentation.h>\n#include <CGAL/boost/graph/copy_face_graph.h>\n#include <CGAL/Facet_with_id_pmap.h>\n#include <queue>\n\nnamespace PMP = CGAL::Polygon_mesh_processing;\n\ntypedef Scene_surface_mesh_item Scene_face_graph_item;\nnamespace CGAL {\n\ntemplate<>\nvoid set_halfedgeds_items_id (Scene_face_graph_item::Face_graph&)\n{}\n\n} // namespace CGAL\n\ntypedef Scene_face_graph_item::Face_graph Face_graph;\n\ntypedef boost::graph_traits<Face_graph>::vertex_descriptor          vertex_descriptor;\ntypedef boost::graph_traits<Face_graph>::vertex_iterator            vertex_iterator;\ntypedef boost::graph_traits<Face_graph>::halfedge_descriptor        halfedge_descriptor;\n\ntypedef CGAL::Mean_curvature_flow_skeletonization<Face_graph>      Mean_curvature_skeleton;\ntypedef Mean_curvature_skeleton::Skeleton Skeleton;\n\ntypedef Kernel::Point_3            Point;\n\nstruct Polyline_visitor\n{\n  typedef std::vector<Point> Polyline;\n  typedef std::vector<std::size_t> Polyline_of_ids;\n  \n  std::list<Polyline>& polylines;\n  Skeleton& skeleton;\n  \n  Polyline_visitor(std::list<Polyline>& lines, Skeleton& skeleton)\n    : polylines(lines),\n      skeleton(skeleton)\n  {}\n  \n  void start_new_polyline()\n  {\n    Polyline V;\n    polylines.push_back(V);\n  }\n  \n  void add_node(boost::graph_traits<Skeleton>::vertex_descriptor vd)\n  {\n    Polyline& polyline = polylines.back();\n    polyline.push_back(skeleton[vd].point);\n  }\n  \n  void end_polyline(){}\n};\n\nusing namespace CGAL::Three;\nclass Polyhedron_demo_mean_curvature_flow_skeleton_plugin :\n  public QObject,\n  public Polyhedron_demo_plugin_helper\n{\n  Q_OBJECT\n  Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)\n  Q_PLUGIN_METADATA(IID \"com.geometryfactory.PolyhedronDemo.PluginInterface/1.0\")\n  QAction* actionMCFSkeleton;\n  QAction* actionConvert_to_medial_skeleton;\n\npublic:\n\n  ~Polyhedron_demo_mean_curvature_flow_skeleton_plugin()\n  {\n    delete ui;\n  }\n  \n  void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface, Messages_interface*) {\n\n    this->mw = mainWindow;\n    this->scene = scene_interface;\n\n    dockWidget = NULL;\n    ui = NULL;\n\n    actionMCFSkeleton = new QAction(tr(\n                                      \"Mean Curvature Skeleton (Advanced)\"\n                                      ), mainWindow);\n    actionMCFSkeleton->setProperty(\"subMenuName\", \"Triangulated Surface Mesh Skeletonization\");\n    actionMCFSkeleton->setObjectName(\"actionMCFSkeleton\");\n\n    actionConvert_to_medial_skeleton = new QAction(tr(\"Extract Medial Skeleton\"), mainWindow);\n    actionConvert_to_medial_skeleton->setProperty(\"subMenuName\", \"Triangulated Surface Mesh Skeletonization\");\n    actionConvert_to_medial_skeleton->setObjectName(\"actionConvert_to_medial_skeleton\");\n\n    dockWidget = new QDockWidget(tr(\n                                   \"Mean Curvature Skeleton\"\n                                   ),mw);\n    dockWidget->setVisible(false);\n    ui = new Ui::Mean_curvature_flow_skeleton_plugin();\n    ui->setupUi(dockWidget);\n    dockWidget->setFeatures(QDockWidget::DockWidgetMovable\n                          | QDockWidget::DockWidgetFloatable\n                          | QDockWidget::DockWidgetClosable);\n    dockWidget->setWindowTitle(tr(\n                               \"Mean Curvature Skeleton\"\n                                 ));\n    addDockWidget(dockWidget);\n\n    connect(ui->pushButton_contract, SIGNAL(clicked()),\n            this, SLOT(on_actionContract()));\n    connect(ui->pushButton_collapse, SIGNAL(clicked()),\n            this, SLOT(on_actionCollapse()));\n    connect(ui->pushButton_split, SIGNAL(clicked()),\n            this, SLOT(on_actionSplit()));\n    connect(ui->pushButton_degeneracy, SIGNAL(clicked()),\n            this, SLOT(on_actionDegeneracy()));\n    connect(ui->pushButton_run, SIGNAL(clicked()),\n            this, SLOT(on_actionRun()));\n    connect(ui->pushButton_skeletonize, SIGNAL(clicked()),\n            this, SLOT(on_actionSkeletonize()));\n    connect(ui->pushButton_converge, SIGNAL(clicked()),\n            this, SLOT(on_actionConverge()));\n    connect(dynamic_cast<Scene*>(scene), SIGNAL(updated_bbox(bool)),\n            this, SLOT(on_actionUpdateBBox(bool)));\n    connect(ui->pushButton_segment, SIGNAL(clicked()),\n            this, SLOT(on_actionSegment()));\n\n    autoConnectActions();\n    QObject* scene_object = dynamic_cast<QObject*>(scene);\n    connect(scene_object, SIGNAL(itemAboutToBeDestroyed(CGAL::Three::Scene_item*)),\n            this, SLOT(on_actionItemAboutToBeDestroyed(CGAL::Three::Scene_item*)));\n  }\n\n  virtual void closure()\n  {\n    dockWidget->hide();\n  }\n\n  QList<QAction*> actions() const {\n    return QList<QAction*>() << actionMCFSkeleton << actionConvert_to_medial_skeleton;\n  }\n\n  bool applicable(QAction*) const {\n    return qobject_cast<Scene_face_graph_item*>(scene->item(scene->mainSelectionIndex()));\n  }\n\n  void init_ui(double diag) {\n    on_checkbox_toggled(false);\n    connect(ui->is_medially_centered, SIGNAL(toggled(bool)),\n            this, SLOT(on_checkbox_toggled(bool)));\n    connect(ui->helpButton, &QPushButton::clicked,\n            [this]{QMessageBox::about(mw, QString(\"Help\"),\n                                    QString(\"This widget gives access to the low level steps of the mean curvature flow sketonization algorithm. \"\n                                            \"The algorithm is iterative. Each iteration consist in calls to Contract, Collapse, Split, \"\n                                            \"and Degeneracy (repectively mesh contraction, edge collapse, edge split, and degenerate edge\"\n                                            \"removal). The skeleton extraction can be called at any time but for a better result it should be\"\n                                            \"called when the iterations are converging. A segmentation of the surface can be extracted using\"\n                                            \"the distance of the mesh to the skeleton computed.\\n\"\n                                             \"All operations can be applied to a polyhedron item or \"\n                                            \"to a surface mesh item. The generated mcf group must be selected in \"\n                                            \"order to continue an on-going set of operations. \"));});\n    ui->omega_H->setValue(0.1);\n    ui->omega_H->setSingleStep(0.1);\n    ui->omega_H->setDecimals(3);\n    ui->omega_P->setValue(0.2);\n    ui->omega_P->setSingleStep(0.1);\n    ui->omega_P->setDecimals(3);\n    ui->min_edge_length->setDecimals(7);\n    ui->min_edge_length->setValue(0.002 * diag);\n    ui->min_edge_length->setSingleStep(0.0000001);\n    ui->delta_area->setDecimals(7);\n    ui->delta_area->setValue(1e-4);\n    ui->delta_area->setSingleStep(1e-5);\n    ui->is_medially_centered->setChecked(false);\n\n    ui->label_omega_H->setToolTip(QString(\"omega_H controls the velocity of movement and approximation quality\"));\n    ui->label_omega_P->setToolTip(QString(\"omega_P controls the smoothness of the medial approximation\"));\n    ui->pushButton_contract->setToolTip(QString(\"contract mesh based on mean curvature flow\"));\n    ui->pushButton_collapse->setToolTip(QString(\"collapse short edges\"));\n    ui->pushButton_split->setToolTip(QString(\"split obtuse triangles\"));\n    ui->pushButton_degeneracy->setToolTip(QString(\"fix degenerate points\"));\n    ui->pushButton_skeletonize->setToolTip(QString(\"Turn mesh to a skeleton curve\"));\n    ui->pushButton_run->setToolTip(QString(\"run one iteration of contract, collapse, split, detect degeneracy\"));\n    ui->pushButton_converge->setToolTip(QString(\"iteratively contract the mesh until convergence\"));\n  }\n\n  bool check_item_index(int index) {\n    if (index < 0)\n    {\n      QMessageBox msgBox;\n      msgBox.setText(\"Please select an item first\");\n      msgBox.exec();\n      return false;\n    }\n    return true;\n  }\n\n  /// \\todo move this function into an include\n  bool is_mesh_valid(Face_graph *pMesh) {\n    if (! CGAL::is_closed(*pMesh))\n    {\n      QMessageBox msgBox;\n      msgBox.setText(\"The mesh is not closed.\");\n      msgBox.exec();\n      return false;\n    }\n    if (! CGAL::is_triangle_mesh(*pMesh))\n    {\n      QMessageBox msgBox;\n      msgBox.setText(\"The mesh is not a pure triangle mesh.\");\n      msgBox.exec();\n      return false;\n    }\n\n    // the algorithm is only applicable on a mesh\n    // that has only one connected component\n    \n    boost::unordered_map<boost::graph_traits<Face_graph>::face_descriptor,int> cc(num_faces(*pMesh));\n    std::size_t num_component = PMP::connected_components(*pMesh, boost::make_assoc_property_map(cc));\n\n    if (num_component != 1)\n    {\n      QMessageBox msgBox;\n      QString str = QString(\"The mesh is not a single closed mesh.\\n It has %1 components.\").arg(num_component);\n      msgBox.setText(str);\n      msgBox.exec();\n      return false;\n    }\n    return true;\n  }\n\n  /// \\todo remove duplicated code\n  // check if the Mean_curvature_skeleton exists\n  // or has the same polyheron item\n  // check if the mesh is a watertight triangle mesh\n  bool check_mesh(Scene_mcf_item* item) {\n    Face_graph *pMesh = item->input_triangle_mesh;\n\n    if (item->mcs == NULL)\n    {\n      if (!is_mesh_valid(pMesh))\n      {\n        return false;\n      }\n      createContractedItem(item);\n\n      item->fixedPointsItemIndex = -1;\n      item->nonFixedPointsItemIndex = -1;\n      item->poleLinesItemIndex = -1;\n    }\n    else\n    {\n      item->mcs->set_quality_speed_tradeoff(ui->omega_H->value());\n      item->mcs->set_medially_centered_speed_tradeoff(ui->omega_P->value());\n      item->mcs->set_min_edge_length(ui->min_edge_length->value());\n      item->mcs->set_area_variation_factor(ui->delta_area->value());\n      item->mcs->set_is_medially_centered(ui->is_medially_centered->isChecked());\n    }\n    return true;\n  }\n\n  void update_meso_skeleton(Scene_mcf_item* item)\n  {\n    clear(*item->meso_skeleton);\n    copy_face_graph(item->mcs->meso_skeleton(), *item->meso_skeleton);\n    scene->item(item->contractedItemIndex)->invalidateOpenGLBuffers();\n    scene->itemChanged(item->contractedItemIndex);\n  }\n\n  void update_parameters(Mean_curvature_skeleton* mcs)\n  {\n    double omega_H = ui->omega_H->value();\n    double omega_P = ui->omega_P->value();\n    double min_edge_length = ui->min_edge_length->value();\n    double delta_area = ui->delta_area->value();\n    bool is_medially_centered = ui->is_medially_centered->isChecked();\n\n    mcs->set_quality_speed_tradeoff(omega_H);\n    mcs->set_medially_centered_speed_tradeoff(omega_P);\n    mcs->set_min_edge_length(min_edge_length);\n    mcs->set_area_variation_factor(delta_area);\n    mcs->set_is_medially_centered(is_medially_centered);\n  }\n\npublic Q_SLOTS:\n  void on_actionMCFSkeleton_triggered();\n  void on_actionConvert_to_medial_skeleton_triggered();\n  void on_actionContract();\n  void on_actionCollapse();\n  void on_actionSplit();\n  void on_actionDegeneracy();\n  void on_actionRun();\n  void on_actionSkeletonize();\n  void on_actionConverge();\n  void on_actionUpdateBBox(bool);\n  void on_checkbox_toggled(bool);\n  void on_actionSegment();\n  void on_actionItemAboutToBeDestroyed(CGAL::Three::Scene_item*);\n\nprivate:\n  Scene_mcf_item *getMCFItem();\n  void createContractedItem(Scene_mcf_item* item);\n  QDockWidget* dockWidget;\n  Ui::Mean_curvature_flow_skeleton_plugin* ui;\n\n}; // end Polyhedron_demo_mean_curvature_flow_skeleton_plugin\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionMCFSkeleton_triggered()\n{\n  dockWidget->show();\n  dockWidget->raise();\n  double diag = scene->len_diagonal();\n  init_ui(diag);\n  getMCFItem();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_checkbox_toggled(bool b)\n{\n  ui->omega_P->setEnabled(b);\n  ui->label_omega_P->setEnabled(b);\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionUpdateBBox(bool)\n{\n  double diag = scene->len_diagonal();\n  ui->min_edge_length->setValue(0.002 * diag);\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionSegment()\n{\n  Scene_mcf_item* item = getMCFItem();\n\n  if(!item)\n  {\n    return;\n  }\n\n  if (num_vertices(item->skeleton_curve)==0 ) on_actionSkeletonize();\n  if (num_vertices(item->skeleton_curve)==0 ) { QApplication::restoreOverrideCursor(); return;}\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  QElapsedTimer time;\n  time.start();\n\n    // init the polyhedron simplex indices\n  CGAL::set_halfedgeds_items_id(*item->input_triangle_mesh);\n  boost::property_map<Face_graph, boost::vertex_index_t>::type \n    vimap = get(boost::vertex_index, *item->input_triangle_mesh);\n\n  //for each input vertex compute its distance to the skeleton\n  std::vector<double> distances(num_vertices(*item->input_triangle_mesh));\n  \n  Face_graph *smesh = item->input_triangle_mesh;\n\n  boost::property_map<Face_graph,CGAL::vertex_point_t>::type vpm\n    = get(CGAL::vertex_point,*smesh);\n\n  for(boost::graph_traits<Skeleton>::vertex_descriptor v : CGAL::make_range(vertices(item->skeleton_curve)) )\n  {\n    const Point& skel_pt = item->skeleton_curve[v].point;\n    for(vertex_descriptor mesh_v : item->skeleton_curve[v].vertices)\n    {\n      const Point& mesh_pt = get(vpm,mesh_v);\n      distances[get(vimap,mesh_v)] = std::sqrt(CGAL::squared_distance(skel_pt, mesh_pt));\n    }\n  }\n\n  // create a property-map for sdf values\n  std::vector<double> sdf_values( num_faces(*item->input_triangle_mesh) );\n  Facet_with_id_pmap<Face_graph,double> sdf_property_map(*item->input_triangle_mesh, sdf_values);\n\n  // compute sdf values with skeleton\n  for(boost::graph_traits<Face_graph>::face_descriptor f : faces(*item->input_triangle_mesh))\n  {\n    double dist = 0;\n    for(boost::graph_traits<Face_graph>::halfedge_descriptor hd : halfedges_around_face(halfedge(f, *item->input_triangle_mesh), *item->input_triangle_mesh))\n      dist+=distances[get(vimap,target(hd, *item->input_triangle_mesh))];\n    sdf_property_map[f] = dist / 3.;\n  }\n\n  // post-process the sdf values\n  CGAL::sdf_values_postprocessing(*item->input_triangle_mesh, sdf_property_map);\n\n  // create a property-map for segment-ids (it is an adaptor for this case)\n  std::vector<std::size_t> segment_ids( num_faces(*item->input_triangle_mesh) );\n  Facet_with_id_pmap<Face_graph,std::size_t> segment_property_map(*item->input_triangle_mesh, segment_ids);\n\n  // segment the mesh using default parameters\n  std::cout << \"Number of segments: \"\n            << CGAL::segmentation_from_sdf_values(*item->input_triangle_mesh, sdf_property_map, segment_property_map) <<\"\\n\";\n\n  Face_graph* segmented_polyhedron = new Face_graph(*item->input_triangle_mesh);\n\n  Scene_face_graph_item* item_segmentation = new Scene_face_graph_item(segmented_polyhedron);\n  int i=0;\n  typedef boost::property_map<Face_graph, CGAL::face_patch_id_t<int> >::type Fpim;\n  Fpim fpim = get(CGAL::face_patch_id_t<int>(), *segmented_polyhedron);\n  int nb_segment=0;\n  for(boost::graph_traits<Face_graph>::face_descriptor fd : faces(*segmented_polyhedron))\n  {\n    int segment = static_cast<int>(segment_ids[i++]);\n    if(segment > nb_segment)\n      nb_segment = segment + 1;\n    put(fpim, fd, segment);\n    \n  }\n  item_segmentation->setItemIsMulticolor(true);\n  item_segmentation->computeItemColorVectorAutomatically(true);\n  item_segmentation->setProperty(\"NbPatchIds\", nb_segment); //for join_and_split plugin\n  item_segmentation->invalidateOpenGLBuffers();\n  scene->addItem(item_segmentation);\n  item_segmentation->setName(QString(\"segmentation\"));\n  scene->changeGroup(item_segmentation, item);\n  Scene_item* parent = scene->item(item->InputMeshItemIndex);\n  if(parent)\n    parent->setVisible(false);\n  scene->setSelectedItem(scene->item_id(item));\n\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionConvert_to_medial_skeleton_triggered()\n{\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n\n  Scene_face_graph_item* item =\n    qobject_cast<Scene_face_graph_item*>(scene->item(index));\n\n  if(item)\n  {\n    Face_graph* pMesh = item->polyhedron();\n\n    if ( !is_mesh_valid(pMesh) ) return;\n\n    QElapsedTimer time;\n    time.start();\n    QApplication::setOverrideCursor(Qt::WaitCursor);\n\n    Skeleton skeleton;\n    CGAL::extract_mean_curvature_flow_skeleton(*pMesh, skeleton);\n\n    std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n    //create the polylines representing the skeleton\n    Scene_polylines_item* skeleton_item = new Scene_polylines_item();\n    skeleton_item->setColor(QColor(175, 0, 255));\n\n    Polyline_visitor polyline_visitor(skeleton_item->polylines, skeleton);\n    CGAL::split_graph_into_polylines( skeleton,\n                                      polyline_visitor,\n                                      CGAL::internal::IsTerminalDefault() );\n\n    skeleton_item->setName(QString(\"Medial skeleton curve of %1\").arg(item->name()));\n    scene->setSelectedItem(-1);\n    scene->addItem(skeleton_item);\n    skeleton_item->invalidateOpenGLBuffers();\n\n    item->setPointsMode();\n\n    QApplication::restoreOverrideCursor();\n  }\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionContract()\n{\n  Scene_mcf_item* item = getMCFItem();\n\n  if (!item || !check_mesh(item))\n  {\n    return;\n  }\n\n  QElapsedTimer time;\n  time.start();\n  std::cout << \"Contract...\\n\";\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  update_parameters(item->mcs);\n  item->mcs->contract_geometry();\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  update_meso_skeleton(item);\n  QApplication::restoreOverrideCursor();\n  scene->setSelectedItem(scene->item_id(item));\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionCollapse()\n{\n  Scene_mcf_item* item =\n    getMCFItem();\n\n  if (!item || !check_mesh(item))\n  {\n    return;\n  }\n\n  QElapsedTimer time;\n  time.start();\n  std::cout << \"Collapse...\\n\";\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  update_parameters(item->mcs);\n  std::size_t num_collapses = item->mcs->collapse_edges();\n  std::cout << \"collapsed \" << num_collapses << \" edges.\\n\";\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  update_meso_skeleton(item);\n  QApplication::restoreOverrideCursor();\n  scene->setSelectedItem(scene->item_id(item));\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionSplit()\n{\n  Scene_mcf_item* item =\n    getMCFItem();\n\n  if (!item || !check_mesh(item))\n  {\n    return;\n  }\n\n  QElapsedTimer time;\n  time.start();\n  std::cout << \"Split...\\n\";\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  update_parameters(item->mcs);\n  std::size_t num_split = item->mcs->split_faces();\n  std::cout << \"split \" << num_split << \" triangles.\\n\";\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  update_meso_skeleton(item);\n  QApplication::restoreOverrideCursor();\n  scene->setSelectedItem(scene->item_id(item));\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionDegeneracy()\n{\n  Scene_mcf_item* item = getMCFItem();\n\n  if (!item || !check_mesh(item))\n  {\n    return;\n  }\n\n  QElapsedTimer time;\n  time.start();\n  std::cout << \"Detect degeneracy...\\n\";\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  update_parameters(item->mcs);\n  item->mcs->detect_degeneracies();\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  Scene_points_with_normal_item* fixedPointsItem = new Scene_points_with_normal_item;\n  fixedPointsItem->setName(QString(\"fixed points of %1\").arg(item->name()));\n  std::vector<Point> fixedPoints;\n  item->mcs->fixed_points(fixedPoints);\n\n  Point_set *ps = fixedPointsItem->point_set();\n  for (size_t i = 0; i < fixedPoints.size(); ++i)\n  {\n    Kernel::Point_3 point (fixedPoints[i].x(), fixedPoints[i].y(), fixedPoints[i].z());\n    ps->insert(point);\n  }\n  ps->select_all ();\n\n  if (item->fixedPointsItemIndex == -1)\n  {\n    item->fixedPointsItemIndex = scene->addItem(fixedPointsItem);\n    scene->changeGroup(fixedPointsItem, item);\n    item->lockChild(fixedPointsItem);\n  }\n  else\n  {\n    Scene_item* temp = scene->replaceItem(item->fixedPointsItemIndex, fixedPointsItem, false);\n    delete temp;\n  }\n  // update scene\n  update_meso_skeleton(item);\n  scene->item(item->fixedPointsItemIndex)->invalidateOpenGLBuffers();\n  scene->itemChanged(item->fixedPointsItemIndex);\n  scene->setSelectedItem(scene->item_id(item));\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionRun()\n{\n  Scene_mcf_item* item = getMCFItem();\n\n  if (!item || !check_mesh(item))\n  {\n    return;\n  }\n\n  QElapsedTimer time;\n  time.start();\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  std::cout << \"Run one iteration...\\n\";\n  Scene_face_graph_item* contracted_item = NULL;\nif(item->contractedItemIndex != -1)\n    contracted_item = qobject_cast<Scene_face_graph_item*>(scene->item(item->contractedItemIndex));\nscene->setSelectedItem(scene->item_id(item));\n//todo : create a new contracted item\nif(!contracted_item)\n{\n  createContractedItem(item);\n  contracted_item = qobject_cast<Scene_face_graph_item*>(scene->item(item->contractedItemIndex));\n}\n\n  update_parameters(item->mcs);\n  item->mcs->contract();\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  // update scene\n  Scene_points_with_normal_item* fixedPointsItem = new Scene_points_with_normal_item;\n  fixedPointsItem->setName(QString(\"fixed points of %1\").arg(contracted_item->name()));\n  std::vector<Point> fixedPoints;\n  item->mcs->fixed_points(fixedPoints);\n\n  Point_set *ps = fixedPointsItem->point_set();\n  for (size_t i = 0; i < fixedPoints.size(); ++i)\n  {\n    Kernel::Point_3 point(fixedPoints[i].x(), fixedPoints[i].y(), fixedPoints[i].z());\n    ps->insert(point);\n  }\n  ps->select_all();\n  \n  if (item->fixedPointsItemIndex == -1)\n  {\n    item->fixedPointsItemIndex = scene->addItem(fixedPointsItem);\n    scene->changeGroup(fixedPointsItem, item);\n    item->lockChild(fixedPointsItem);\n  }\n  else\n  {\n    Scene_item* temp = scene->replaceItem(item->fixedPointsItemIndex, fixedPointsItem, false);\n    delete temp;\n  }\n\n//#define DRAW_NON_FIXED_POINTS\n#ifdef DRAW_NON_FIXED_POINTS\n  // draw non-fixed points\n  Scene_points_with_normal_item* nonFixedPointsItem = new Scene_points_with_normal_item;\n  nonFixedPointsItem->setName(\"non-fixed points\");\n  nonFixedPointsItem->setColor(QColor(0, 255, 0));\n  std::vector<Point> nonFixedPoints;\n  mcs->non_fixed_points(nonFixedPoints);\n  ps = nonFixedPointsItem->point_set();\n  for (size_t i = 0; i < nonFixedPoints.size(); ++i)\n  {\n    UI_point_3<Kernel> point(nonFixedPoints[i].x(), nonFixedPoints[i].y(), nonFixedPoints[i].z());\n    ps->push_back(point);\n  }\n  if (nonFixedPointsItemIndex == -1)\n  {\n    nonFixedPointsItemIndex = scene->addItem(nonFixedPointsItem);\n    scene->changeGroup(nonFixedPointsItem, item);\n    item->lockChild(nonFixedPointsItem);\n  }\n  else\n  {\n    scene->replaceItem(nonFixedPointsItemIndex, nonFixedPointsItem, false);\n  }\n  scene->itemChanged(nonFixedPointsItemIndex);\n#endif\n\n//#define DRAW_POLE_LINE\n#ifdef DRAW_POLE_LINE\n  // draw lines connecting surface points and their correspondent poles\n  Scene_polylines_item* poleLinesItem = new Scene_polylines_item();\n  Face_graph* pMesh = item->input_triangle_mesh;\n  std::vector<Point> pole_points;\n  item->mcs->poles(pole_points);\n  vertex_iterator vb, ve;\n  int id = 0;\n  for (boost::tie(vb, ve) = vertices(*pMesh); vb != ve; ++vb)\n  {\n    std::vector<Point> line;\n    line.clear();\n\n    vertex_descriptor v = *vb;\n    Point s = v->point();\n    Point t = pole_points[id++];\n\n    line.push_back(s);\n    line.push_back(t);\n    poleLinesItem->polylines.push_back(line);\n  }\n\n  if (item->poleLinesItemIndex == -1)\n  {\n    item->poleLinesItemIndex = scene->addItem(poleLinesItem);\n    scene->changeGroup(poleLinesItem, item);\n    item->lockChild(poleLinesItem);\n  }\n  else\n  {\n    scene->replaceItem(poleLinesItemIndex, poleLinesItem, false);\n  }\n#endif\n\n  update_meso_skeleton(item);\n  scene->setSelectedItem(scene->item_id(item));\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionSkeletonize()\n{\n  Scene_mcf_item* item = getMCFItem();\n\n  if (!item || !check_mesh(item))\n  {\n    return;\n  }\n\n  QElapsedTimer time;\n  time.start();\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  update_parameters(item->mcs);\n\n  item->mcs->convert_to_skeleton(item->skeleton_curve);\n\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  //create the polylines representing the skeleton\n  Scene_polylines_item* skeleton = new Scene_polylines_item();\n  skeleton->setColor(QColor(175, 0, 255));\n\n  Polyline_visitor polyline_visitor(skeleton->polylines, item->skeleton_curve);\n  CGAL::split_graph_into_polylines( item->skeleton_curve,\n                                    polyline_visitor,\n                                    CGAL::internal::IsTerminalDefault() );\n\n  skeleton->setName(QString(\"skeleton curve of %1\").arg(item->name()));\n  skeleton->invalidateOpenGLBuffers();\n  if(item->skeletonItemIndex == -1)\n  {\n    item->skeletonItemIndex = scene->addItem(skeleton);\n    scene->changeGroup(skeleton, item);\n    item->lockChild(skeleton);\n  }\n  else\n  {\n    scene->replaceItem(item->skeletonItemIndex, skeleton, false);\n  }\n\n  // set the fixed points and contracted mesh as invisible\n  if (item->fixedPointsItemIndex >= 0)\n  {\n    scene->item(item->fixedPointsItemIndex)->setVisible(false);\n    scene->itemChanged(item->fixedPointsItemIndex);\n  }\n  scene->item(item->contractedItemIndex)->setVisible(false);\n  scene->itemChanged(item->contractedItemIndex);\n  if (item->InputMeshItemIndex >= 0)\n  {\n    scene->item(item->InputMeshItemIndex)->setVisible(true);\n    scene->item(item->InputMeshItemIndex)->setPointsMode();\n    scene->itemChanged(item->InputMeshItemIndex);\n  }\n  scene->setSelectedItem(scene->item_id(item));\n  // update scene\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionConverge()\n{\n  Scene_mcf_item* item = getMCFItem();\n\n  if (!item || !check_mesh(item))\n  {\n    return;\n  }\n\n  QElapsedTimer time;\n  time.start();\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  item->mcs->contract_until_convergence();\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  // update scene\n  Scene_points_with_normal_item* fixedPointsItem = new Scene_points_with_normal_item;\n  fixedPointsItem->setName(QString(\"fixed points of %1\").arg(item->name()));\n\n  std::vector<Point> fixedPoints;\n  item->mcs->fixed_points(fixedPoints);\n\n  Point_set *ps = fixedPointsItem->point_set();\n  for (size_t i = 0; i < fixedPoints.size(); ++i)\n  {\n    Kernel::Point_3 point(fixedPoints[i].x(), fixedPoints[i].y(), fixedPoints[i].z());\n    ps->insert(point);\n  }\n  ps->select_all();\n  \n  if (item->fixedPointsItemIndex == -1)\n  {\n    item->fixedPointsItemIndex = scene->addItem(fixedPointsItem);\n    scene->changeGroup(fixedPointsItem, item);\n    item->lockChild(fixedPointsItem);\n  }\n  else\n  {\n    Scene_item* temp = scene->replaceItem(item->fixedPointsItemIndex, fixedPointsItem, false);\n    delete temp;\n  }\n\n  scene->item(item->fixedPointsItemIndex)->invalidateOpenGLBuffers();\n  scene->itemChanged(item->fixedPointsItemIndex);\n  update_meso_skeleton(item);\n  scene->setSelectedItem(scene->item_id(item));\n\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionItemAboutToBeDestroyed(CGAL::Three::Scene_item* corpse )\n{\n  Scene_mcf_item *mcf= qobject_cast<Scene_mcf_item*>(corpse);\n\n  if(mcf)\n  {\n    mcf->mcs = NULL;\n    mcf->meso_skeleton = NULL;\n    mcf->input_triangle_mesh = NULL;\n    mcf->fixedPointsItemIndex = -1;\n    mcf->nonFixedPointsItemIndex = -1;\n    mcf->poleLinesItemIndex = -1;\n    mcf->contractedItemIndex = -1;\n    mcf->InputMeshItemIndex = -1;\n    mcf->meso_skeleton = NULL;\n    mcf->input_triangle_mesh = NULL;\n  }\n}\n\nvoid\nPolyhedron_demo_mean_curvature_flow_skeleton_plugin::createContractedItem(Scene_mcf_item* item)\n{\n  if(!item)\n    return;\n  if(item->mcs != NULL)\n    delete item->mcs;\n  double omega_H = ui->omega_H->value();\n  double omega_P = ui->omega_P->value();\n  double min_edge_length = ui->min_edge_length->value();\n  double delta_area = ui->delta_area->value();\n  bool is_medially_centered = ui->is_medially_centered->isChecked();\n\n  item->mcs = new Mean_curvature_skeleton(*item->input_triangle_mesh);\n  item->meso_skeleton = new Face_graph(*item->input_triangle_mesh);\n  //set algorithm parameters\n  item->mcs->set_quality_speed_tradeoff(omega_H);\n  item->mcs->set_medially_centered_speed_tradeoff(omega_P);\n  item->mcs->set_min_edge_length(min_edge_length);\n  item->mcs->set_is_medially_centered(is_medially_centered);\n  item->mcs->set_area_variation_factor(delta_area);\n\n  Scene_face_graph_item* contracted_item = new Scene_face_graph_item(item->meso_skeleton);\n  contracted_item->setName(QString(\"contracted mesh of %1\").arg(item->name()));\n  contracted_item->setItemIsMulticolor(false); //avoids segfault if item was a multicolor surface_mesh\n\n  item->contractedItemIndex = scene->addItem(contracted_item);\n  scene->changeGroup(contracted_item, item);\n  item->lockChild(contracted_item);\n  scene->setSelectedItem(scene->item_id(item));\n\n}\n\nScene_mcf_item*\nPolyhedron_demo_mean_curvature_flow_skeleton_plugin::getMCFItem()\n{\n  Q_FOREACH(int index, scene->selectionIndices())\n  {\n    Scene_mcf_item* mcf = qobject_cast<Scene_mcf_item*>(scene->item(index));\n    if(mcf)\n      return mcf;\n  }\n\n  //if the selected item is not an MCF but is a face_graph_item,\n  //then create and add a new MCF\n  if(scene->mainSelectionIndex() != -1)\n  {\n    Scene_face_graph_item* item =\n        qobject_cast<Scene_face_graph_item*>(scene->item(\n                                               scene->mainSelectionIndex()));\n    if(item)\n    {\n      Face_graph* pMesh = item->face_graph();\n\n      if(!pMesh) return NULL;\n      Scene_mcf_item* mcf = new Scene_mcf_item(item->face_graph(),\n                                               scene->mainSelectionIndex(),\n                                               QString(\"%1 (mcf)\").arg(item->name()));\n      connect(item, &Scene_face_graph_item::aboutToBeDestroyed,\n              [mcf, this]{\n        if(scene->item_id(mcf) != -1){\n          scene->erase(scene->item_id(mcf));\n      }});\n      scene->setSelectedItem(scene->addItem(mcf));\n      item->setVisible(false);\n      scene->itemChanged(item);\n      return mcf;\n    }\n  }\n  return NULL;\n}\n\n#include \"Mean_curvature_flow_skeleton_plugin.moc\"\n", "meta": {"hexsha": "5e7d398953855b9e615097fbe869ad387674ca4d", "size": 31538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/demo/Polyhedron/Plugins/PMP/Mean_curvature_flow_skeleton_plugin.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/Polyhedron/Plugins/PMP/Mean_curvature_flow_skeleton_plugin.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/Polyhedron/Plugins/PMP/Mean_curvature_flow_skeleton_plugin.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": 33.2679324895, "max_line_length": 157, "alphanum_fraction": 0.7004248843, "num_tokens": 7871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5145419255776292}}
{"text": "#ifndef QPWBC_H_INCLUDED\n#define QPWBC_H_INCLUDED\n\n#include \"qrw/InvKin.hpp\" // For pseudoinverse\n#include \"qrw/Params.hpp\"\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <cmath>\n#include <limits>\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include \"osqp.h\"\n#include \"other/st_to_cc.hpp\"\n\nclass QPWBC {\n private:\n  \n  Params* params_;  // Object that stores parameters\n\n  int cpt_ML = 0;\n  int cpt_P = 0;\n\n  // Set to True after the creation of the QP problem during the first call of the solver\n  bool initialized = false;\n\n  // Weight matrices of initial QP\n  Eigen::Matrix<double, 6, 6> Q1 = Eigen::Matrix<double, 6, 6>::Identity();\n  Eigen::Matrix<double, 12, 12> Q2 = Eigen::Matrix<double, 12, 12>::Identity();\n\n  // Friction coefficient\n  const double mu = 0.9;\n\n  // Generatrix of the linearized friction cone\n  Eigen::Matrix<double, 20, 12> G = Eigen::Matrix<double, 20, 12>::Zero();\n\n  // Transformation matrices\n  Eigen::Matrix<double, 6, 6> Y = Eigen::Matrix<double, 6, 6>::Zero();\n  Eigen::Matrix<double, 6, 12> X = Eigen::Matrix<double, 6, 12>::Zero();\n  Eigen::Matrix<double, 6, 6> Yinv = Eigen::Matrix<double, 6, 6>::Zero();\n  Eigen::Matrix<double, 6, 12> A = Eigen::Matrix<double, 6, 12>::Zero();\n  Eigen::Matrix<double, 6, 1> gamma = Eigen::Matrix<double, 6, 1>::Zero();\n  Eigen::Matrix<double, 12, 12>  H = Eigen::Matrix<double, 12, 12>::Zero();\n  Eigen::Matrix<double, 12, 1> g = Eigen::Matrix<double, 12, 1>::Zero();\n\n  // Results\n  // Eigen::Matrix<double, 12, 1> lambdas = Eigen::Matrix<double, 12, 1>::Zero();\n  Eigen::MatrixXd f_res = Eigen::MatrixXd::Zero(12, 1);\n  Eigen::MatrixXd ddq_res = Eigen::MatrixXd::Zero(12, 1);\n  \n  // Matrix ML\n  const static int size_nz_ML = 20*12; //4 * (4 * 2 + 1);\n  csc *ML;  // Compressed Sparse Column matrix\n\n  // Matrix NK\n  const static int size_nz_NK = 20;\n  double v_NK_up[size_nz_NK] = {};   // matrix NK (upper bound)\n  double v_NK_low[size_nz_NK] = {};  // matrix NK (lower bound)\n  double v_warmxf[size_nz_NK] = {};  // matrix NK (lower bound)\n\n  // Matrix P\n  const static int size_nz_P = 6*13; // 6*13; // 12*13/2;\n  csc *P;  // Compressed Sparse Column matrix\n\n  // Matrix Q\n  const static int size_nz_Q = 12;\n  double Q[size_nz_Q] = {};  // Q is full of zeros\n\n  // OSQP solver variables\n  OSQPWorkspace *workspce = new OSQPWorkspace();\n  OSQPData *data;\n  OSQPSettings *settings = (OSQPSettings *)c_malloc(sizeof(OSQPSettings));\n\n public:\n  \n  QPWBC(); // Constructor\n  void initialize(Params& params);\n\n  // Functions\n  inline void add_to_ML(int i, int j, double v, int *r_ML, int *c_ML, double *v_ML); // function to fill the triplet r/c/v\n  inline void add_to_P(int i, int j, double v, int *r_P, int *c_P, double *v_P); // function to fill the triplet r/c/v\n  int create_matrices();\n  int create_ML();\n  int create_weight_matrices();\n  void compute_matrices(const Eigen::MatrixXd &M, const Eigen::MatrixXd &Jc, const Eigen::MatrixXd &f_cmd, const Eigen::MatrixXd &RNEA);\n  void update_PQ();\n  int call_solver();\n  int retrieve_result(const Eigen::MatrixXd &f_cmd);\n  int run(const Eigen::MatrixXd &M, const Eigen::MatrixXd &Jc, const Eigen::MatrixXd &f_cmd, const Eigen::MatrixXd &RNEA, const Eigen::MatrixXd &k_contact);\n\n  // Getters\n  Eigen::MatrixXd get_f_res();\n  Eigen::MatrixXd get_ddq_res();\n  Eigen::MatrixXd get_H();\n\n  // Utils\n  void my_print_csc_matrix(csc *M, const char *name);\n  void save_csc_matrix(csc *M, std::string filename);\n  void save_dns_matrix(double *M, int size, std::string filename);\n\n};\n\n#endif  // QPWBC_H_INCLUDED\n", "meta": {"hexsha": "602a8fcb3601e66ab47e9321d4e98c4cb775c6e6", "size": 3564, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/qrw/QPWBC.hpp", "max_stars_repo_name": "FannyRis/quadruped-reactive-walking", "max_stars_repo_head_hexsha": "9dbc0fe36fe1c83e7f9b9d338309843f2e4fc453", "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/qrw/QPWBC.hpp", "max_issues_repo_name": "FannyRis/quadruped-reactive-walking", "max_issues_repo_head_hexsha": "9dbc0fe36fe1c83e7f9b9d338309843f2e4fc453", "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/qrw/QPWBC.hpp", "max_forks_repo_name": "FannyRis/quadruped-reactive-walking", "max_forks_repo_head_hexsha": "9dbc0fe36fe1c83e7f9b9d338309843f2e4fc453", "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.9428571429, "max_line_length": 156, "alphanum_fraction": 0.6776094276, "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5145214224809816}}
{"text": "#define BOOST_TEST_MODULE test_btime\n\n#include <boost/test/unit_test.hpp>\n#include \"Btime/DayCountCalculator.h\"\n\nBOOST_AUTO_TEST_SUITE(btime_test_suite)\n\n    BOOST_AUTO_TEST_CASE(actual_count) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const std::string from_date = \"2001-12-25\";\n        const std::string to_date = \"2002-1-1\";\n        DayCountCalculator *myCalc;\n        Actual_360 actualCalc = Actual_360{};\n        myCalc = &actualCalc;\n        double calculated_values = myCalc->compute_daycount(from_date, to_date);\n        double expected_values = 7.0;\n\n        BOOST_TEST_MESSAGE(\" - Calculated Value: \" << calculated_values);\n        BOOST_TEST_MESSAGE(\" - Expected Value: \" << expected_values);\n        BOOST_TEST_MESSAGE(\" - Diff \" << calculated_values - expected_values);\n        BOOST_TEST(expected_values == calculated_values, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(thirty_count) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const std::string from_date = \"2001-12-25\";\n        const std::string to_date = \"2002-1-1\";\n        DayCountCalculator *myCalc;\n        Thirty_360 thirty360Calc = Thirty_360{};\n        myCalc = &thirty360Calc;\n        double calculated_values = myCalc->compute_daycount(from_date, to_date);\n        double expected_values = 6.0;\n\n        BOOST_TEST_MESSAGE(\" - Calculated Value: \" << calculated_values);\n        BOOST_TEST_MESSAGE(\" - Expected Value: \" << expected_values);\n        BOOST_TEST_MESSAGE(\" - Diff \" << calculated_values - expected_values);\n        BOOST_TEST(expected_values == calculated_values, boost::test_tools::tolerance(1e-15));\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "79c6e97dd4d1fb4b511349a3fd92c2f5ebe3eec0", "size": 1712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "assignment/src/Btime/tests/test.cpp", "max_stars_repo_name": "paulochang/finance_valuator_extended", "max_stars_repo_head_hexsha": "1c9f638d0b1dd888b4a1010c47c4e1999ed6f5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-04-24T14:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-24T14:51:39.000Z", "max_issues_repo_path": "assignment/src/Btime/tests/test.cpp", "max_issues_repo_name": "paulochang/finance_valuator_extended", "max_issues_repo_head_hexsha": "1c9f638d0b1dd888b4a1010c47c4e1999ed6f5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment/src/Btime/tests/test.cpp", "max_forks_repo_name": "paulochang/finance_valuator_extended", "max_forks_repo_head_hexsha": "1c9f638d0b1dd888b4a1010c47c4e1999ed6f5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8139534884, "max_line_length": 94, "alphanum_fraction": 0.6880841121, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.5145125767040988}}
{"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 https://www.boost.org/LICENSE_1_0.txt\n\n//\n// Compare results of truncated left shift to gmp, see:\n// https://svn.boost.org/trac/boost/ticket/12790\n//\n\n#ifdef _MSC_VER\n#define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#include <boost/multiprecision/gmp.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/timer.hpp>\n#include \"test.hpp\"\n\n#if !defined(TEST1) && !defined(TEST2) && !defined(TEST3)\n#define TEST1\n#define TEST2\n#define TEST3\n#endif\n\ntemplate <class T>\nT generate_random(unsigned bits_wanted)\n{\n   static boost::random::mt19937               gen;\n   typedef boost::random::mt19937::result_type random_type;\n\n   T        max_val;\n   unsigned digits;\n   if (std::numeric_limits<T>::is_bounded && (bits_wanted == (unsigned)std::numeric_limits<T>::digits))\n   {\n      max_val = (std::numeric_limits<T>::max)();\n      digits  = std::numeric_limits<T>::digits;\n   }\n   else\n   {\n      max_val = T(1) << bits_wanted;\n      digits  = bits_wanted;\n   }\n\n   unsigned bits_per_r_val = std::numeric_limits<random_type>::digits - 1;\n   while ((random_type(1) << bits_per_r_val) > (gen.max)())\n      --bits_per_r_val;\n\n   unsigned terms_needed = digits / bits_per_r_val + 1;\n\n   T val = 0;\n   for (unsigned i = 0; i < terms_needed; ++i)\n   {\n      val *= (gen.max)();\n      val += gen();\n   }\n   val %= max_val;\n   return val;\n}\n\ntemplate <class T>\nvoid test_value(const T& val)\n{\n   boost::multiprecision::mpz_int z(val.str()), mask(1);\n   mask <<= std::numeric_limits<T>::digits;\n   --mask;\n\n   for (unsigned i = 0; i <= std::numeric_limits<T>::digits + 2; ++i)\n   {\n      BOOST_CHECK_EQUAL((val << i).str(), boost::multiprecision::mpz_int(((z << i) & mask)).str());\n   }\n}\n\nvoid test(const boost::mpl::int_<200>&) {}\n\ntemplate <int N>\nvoid test(boost::mpl::int_<N> const&)\n{\n   test(boost::mpl::int_<N + 4>());\n\n   typedef boost::multiprecision::number<boost::multiprecision::cpp_int_backend<N, N, boost::multiprecision::unsigned_magnitude>, boost::multiprecision::et_off> mp_type;\n\n   std::cout << \"Running tests for precision: \" << N << std::endl;\n\n   mp_type mp(-1);\n   test_value(mp);\n\n   for (unsigned i = 0; i < 1000; ++i)\n      test_value(generate_random<mp_type>(std::numeric_limits<mp_type>::digits));\n}\n\nint main()\n{\n   test(boost::mpl::int_<24>());\n   return boost::report_errors();\n}\n", "meta": {"hexsha": "3aca2e1d9a4d0e124d495269ab6f9294e7551d41", "size": 2597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/multiprecision/test/test_cpp_int_left_shift.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/multiprecision/test/test_cpp_int_left_shift.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/multiprecision/test/test_cpp_int_left_shift.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": 26.2323232323, "max_line_length": 169, "alphanum_fraction": 0.6411243743, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5145125715201361}}
{"text": "#include <cassert>\n#include <limits>\n#include <vector>\n\n#include \"bateman.hpp\"\n\n#if defined(MULTIPRECISION_DIGITS10)\n#include <boost/multiprecision/cpp_dec_float.hpp>\nusing Real_t = boost::multiprecision::number<\n    boost::multiprecision::cpp_dec_float<MULTIPRECISION_DIGITS10> >;\n#ifndef CHAIN_LENGTH\n// cpp_dec_float is more precise than double even with ~16 digits.\n#define CHAIN_LENGTH 200\n#endif\nReal_t abs_cb(Real_t arg){\n    return boost::multiprecision::abs(arg);\n}\nReal_t exp_cb(Real_t arg){\n    return boost::multiprecision::exp(arg);\n}\nReal_t log_cb(Real_t arg){\n    return boost::multiprecision::log(arg);\n}\nReal_t pow_cb(Real_t arg, Real_t ex){\n    return boost::multiprecision::pow(arg, ex);\n}\n#else\n#include <cmath>\nusing Real_t = double;\n#ifndef CHAIN_LENGTH\n// IEEE754 seem to handle up to 130 decays\n#define CHAIN_LENGTH 130\n#endif\nReal_t abs_cb(Real_t arg){\n    return std::abs(arg);\n}\nReal_t exp_cb(Real_t arg){\n    return std::exp(arg);\n}\nReal_t log_cb(Real_t arg){\n    return std::log(arg);\n}\nReal_t pow_cb(Real_t arg, Real_t ex){\n    return std::pow(arg, ex);\n}\n#endif\n\nint main(int argc, char *argv[]){\n    std::vector<Real_t> y0 {{ 1.0, 1.0, 1.0 }};\n    std::vector<Real_t> lmbd {{ 2.0, 3.0, 4.0 }};\n    Real_t t = 1.0;\n    auto y = bateman::bateman_full(y0, lmbd, t, exp_cb);\n\n    std::vector<Real_t> yref\n    {{ 0.1353352832366127, 0.22088349810536145, 0.2749602834949804 }};\n\n    assert (abs_cb(y[0] - yref[0]) < 1e-16);\n    assert (abs_cb(y[1] - yref[1]) < 1e-16);\n    assert (abs_cb(y[2] - yref[2]) < 1e-16);\n\n    auto p = bateman::bateman_parent(lmbd, t, exp_cb);\n    std::vector<Real_t> pref\n    {{ 0.1353352832366127, 0.1710964297374975, 0.16223035616885698 }};\n\n    assert (abs_cb(p[0] - pref[0]) < 1e-16);\n    assert (abs_cb(p[1] - pref[1]) < 1e-16);\n    assert (abs_cb(p[2] - pref[2]) < 1e-16);\n\n    const int N = CHAIN_LENGTH;\n    const Real_t NN = static_cast<Real_t>(CHAIN_LENGTH);\n    Real_t logN = log_cb(N);\n    auto lmbd2 = std::vector<Real_t>(N);\n    std::vector<Real_t> p2ref(N);\n    for (int i=0; i<N; ++i){\n        lmbd2[i] = (i+1)*logN;\n        //p2ref[i] = pow_cb(N-1, i)/pow(N, i+1);\n        p2ref[i] = pow_cb((NN-1)/NN, i)/NN;\n    }\n    auto p2 = bateman::bateman_parent(lmbd2, static_cast<Real_t>(1), exp_cb);\n    Real_t atol = std::numeric_limits<Real_t>::epsilon()*10;\n    for (int i=0; i<N; ++i)\n        assert (abs_cb(p2[i] - p2ref[i]) < atol);\n    return 0;\n}\n", "meta": {"hexsha": "affeb238bdf3ea2aa2e9e64493167b4fefb0c153", "size": 2418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/tests/test_bateman.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": "include/tests/test_bateman.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": "include/tests/test_bateman.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.4470588235, "max_line_length": 77, "alphanum_fraction": 0.6484698098, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5145125698744784}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed 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#include <boost/hana/monoid/monoid.hpp>\n\n#include <boost/hana/core/datatype.hpp>\n#include <boost/hana/detail/assert.hpp>\nusing namespace boost::hana;\n\n\nstruct integer {\n    int value;\n    constexpr explicit integer(int i) : value{i} { }\n};\n\nstruct integer2 {\n    int value;\n    constexpr explicit integer2(int i) : value{i} { }\n};\n\nconstexpr auto operator+(integer a, integer b)\n{ return integer{a.value + b.value}; }\n\nconstexpr auto operator+(integer2 a, integer b)\n{ return integer{a.value + b.value}; }\n\nconstexpr auto operator+(integer a, integer2 b)\n{ return integer{a.value + b.value}; }\n\nconstexpr auto operator+(integer2 a, integer2 b)\n{ return integer2{a.value + b.value}; }\n\nusing Integer = datatype_t<integer>;\nusing Integer2 = datatype_t<integer2>;\n\nint main() {\n    // same type\n    BOOST_HANA_CONSTEXPR_ASSERT(zero<Integer>.value == 0);\n    BOOST_HANA_CONSTEXPR_ASSERT(plus(integer{3}, integer{5}).value == 3 + 5);\n\n    BOOST_HANA_CONSTEXPR_ASSERT(zero<Integer2>.value == 0);\n    BOOST_HANA_CONSTEXPR_ASSERT(plus(integer2{3}, integer2{5}).value == 3 + 5);\n\n    // mixed types\n    BOOST_HANA_CONSTEXPR_ASSERT(plus(integer{3}, integer2{5}).value == 3 + 5);\n    BOOST_HANA_CONSTEXPR_ASSERT(plus(integer2{3}, integer{5}).value == 3 + 5);\n}\n", "meta": {"hexsha": "be1dd94504504448f5f7fac431cb548fffcf9a83", "size": 1425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/monoid/builtin_instance.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/monoid/builtin_instance.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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/monoid/builtin_instance.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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.9411764706, "max_line_length": 79, "alphanum_fraction": 0.7080701754, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5145125646905155}}
{"text": "// Copyright John Maddock 2006.\r\n// Copyright Paul A. Bristow 2007, 2009\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/math/concepts/real_concept.hpp>\r\n#define BOOST_TEST_MAIN\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/math/special_functions/beta.hpp>\r\n#include <boost/math/tools/stats.hpp>\r\n#include <boost/math/tools/test.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/type_traits/is_floating_point.hpp>\r\n#include <boost/array.hpp>\r\n#include \"functor.hpp\"\r\n\r\n#include \"handle_test_result.hpp\"\r\n#include \"table_type.hpp\"\r\n\r\n#ifndef SC_\r\n#define SC_(x) static_cast<typename table_type<T>::type>(BOOST_JOIN(x, L))\r\n#endif\r\n\r\ntemplate <class T>\r\nT ibeta_forwarder(T a, T b, T x)\r\n{\r\n   T derivative;\r\n   boost::math::detail::ibeta_imp(a, b, x, boost::math::policies::policy<>(), false, true, &derivative);\r\n   return derivative;\r\n}\r\n\r\ntemplate <class Real, class T>\r\nvoid do_test_beta(const T& data, const char* type_name, const char* test_name)\r\n{\r\n   typedef Real                   value_type;\r\n\r\n   typedef value_type (*pg)(value_type, value_type, value_type);\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n   pg funcp = boost::math::ibeta_derivative<value_type, value_type, value_type>;\r\n#else\r\n   pg funcp = boost::math::ibeta_derivative;\r\n#endif\r\n\r\n   boost::math::tools::test_result<value_type> result;\r\n\r\n#if !(defined(ERROR_REPORTING_MODE) && !defined(BETA_INC_FUNCTION_TO_TEST))\r\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\r\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\r\n\r\n   //\r\n   // test ibeta_derivative against data:\r\n   //\r\n   result = boost::math::tools::test_hetero<Real>(\r\n      data,\r\n      bind_func<Real>(funcp, 0, 1, 2),\r\n      extract_result<Real>(3));\r\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"beta (incomplete)\", test_name);\r\n#endif\r\n\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n   funcp = ibeta_forwarder<value_type>;\r\n#else\r\n   funcp = ibeta_forwarder;\r\n#endif\r\n\r\n   if(boost::math::tools::digits<value_type>() > 40)\r\n   {\r\n      //\r\n      // test ibeta_derivative against data:\r\n      //\r\n      result = boost::math::tools::test_hetero<Real>(\r\n         data,\r\n         bind_func<Real>(funcp, 0, 1, 2),\r\n         extract_result<Real>(3));\r\n      handle_test_result(result, data[result.worst()], result.worst(), type_name, \"beta (incomplete, internal call test)\", test_name);\r\n   }\r\n}\r\n\r\ntemplate <class T>\r\nvoid test_beta(T, const char* name)\r\n{\r\n   //\r\n   // The actual test data is rather verbose, so it's in a separate file\r\n   //\r\n   // The contents are as follows, each row of data contains\r\n   // five items, input value a, input value b, integration limits x, beta(a, b, x) and ibeta(a, b, x):\r\n   //\r\n#if !defined(TEST_DATA) || (TEST_DATA == 1)\r\n#  include \"ibeta_derivative_small_data.ipp\"\r\n\r\n   do_test_beta<T>(ibeta_derivative_small_data, name, \"Incomplete Beta Function Derivative: Small Values\");\r\n#endif\r\n\r\n#if !defined(TEST_DATA) || (TEST_DATA == 2)\r\n#  include \"ibeta_derivative_data.ipp\"\r\n\r\n   do_test_beta<T>(ibeta_derivative_data, name, \"Incomplete Beta Function Derivative: Medium Values\");\r\n\r\n#endif\r\n#if !defined(TEST_DATA) || (TEST_DATA == 3)\r\n#  include \"ibeta_derivative_large_data.ipp\"\r\n\r\n   do_test_beta<T>(ibeta_derivative_large_data, name, \"Incomplete Beta Function Derivative: Large and Diverse Values\");\r\n#endif\r\n\r\n#if !defined(TEST_DATA) || (TEST_DATA == 4)\r\n#  include \"ibeta_derivative_int_data.ipp\"\r\n\r\n   do_test_beta<T>(ibeta_derivative_int_data, name, \"Incomplete Beta Function Derivative: Small Integer Values\");\r\n#endif\r\n}\r\n\r\ntemplate <class T>\r\nvoid test_spots(T)\r\n{\r\n   using std::ldexp;\r\n   T tolerance = boost::math::tools::epsilon<T>() * 40000;\r\n      BOOST_CHECK_CLOSE(\r\n         ::boost::math::ibeta_derivative(\r\n            static_cast<T>(2),\r\n            static_cast<T>(4),\r\n            ldexp(static_cast<T>(1), -557)),\r\n         static_cast<T>(4.23957586190238472641508753637420672781472122471791800210e-167L), tolerance * 4);\r\n      BOOST_CHECK_CLOSE(\r\n         ::boost::math::ibeta_derivative(\r\n            static_cast<T>(2),\r\n            static_cast<T>(4.5),\r\n            ldexp(static_cast<T>(1), -557)),\r\n         static_cast<T>(5.24647512910420109893867082626308082567071751558842352760e-167L), tolerance * 4);\r\n}\r\n\r\n", "meta": {"hexsha": "a71cd87bdaa0d37891dc5afd197997726e1cccb2", "size": 4573, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_ibeta_derivative.hpp", "max_stars_repo_name": "snichols/boost_1_61_0", "max_stars_repo_head_hexsha": "10142fe2415a0c4ddb72207b5f235cce20f72649", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-06T09:03:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-06T09:03:52.000Z", "max_issues_repo_path": "libs/math/test/test_ibeta_derivative.hpp", "max_issues_repo_name": "snichols/boost_1_61_0", "max_issues_repo_head_hexsha": "10142fe2415a0c4ddb72207b5f235cce20f72649", "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_ibeta_derivative.hpp", "max_forks_repo_name": "snichols/boost_1_61_0", "max_forks_repo_head_hexsha": "10142fe2415a0c4ddb72207b5f235cce20f72649", "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.1268656716, "max_line_length": 135, "alphanum_fraction": 0.6667395583, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6619228758499941, "lm_q1q2_score": 0.5145125595065527}}
{"text": "//----------------------------------------------------------------------------\n// Author:\t\tMartin Klemsa\n//----------------------------------------------------------------------------\n#ifndef _ctoolhu_random_generator_included_\n#define _ctoolhu_random_generator_included_\n\n#include \"engine.hpp\"\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/uniform_smallint.hpp>\n\n#ifdef _DEBUG_RAND\n#include <ctoolhu/event/events.h>\n#include <ctoolhu/event/firer.hpp>\n#include <string>\n#endif\n\nnamespace Ctoolhu::Random {\n\n\t//shortcut for the generator template we'll be using\n\ttemplate <class Distribution>\n\tusing RandomGenerator = boost::variate_generator<Private::RandomEngine &, Distribution>;\n\n\t//generator with run-time bounds\n\ttemplate <\n\t\tclass Distribution,\n\t\ttypename Boundary = int\n\t>\n\tclass Generator : public RandomGenerator<Distribution> {\n\t\n\t\tusing base_t = RandomGenerator<Distribution>;\n\n\t  public:\n\n\t\t//for number generators\n\t\tGenerator(Boundary lower, Boundary upper)\n\t\t\t: base_t(Private::SingleRandomEngine::Instance(), Distribution(lower, upper)) {}\n\n\t\t//for bool generator\n\t\tGenerator()\n\t\t\t: base_t(Private::SingleRandomEngine::Instance(), Distribution()) {}\n\n#ifdef _DEBUG_RAND\n\t\tauto operator()()\n\t\t{\n\t\t\tauto res = this->base_t::operator()();\n\t\t\tEvent::Fire(Event::Message{\"random: \" + std::to_string(res)});\n\t\t\treturn res;\n\t\t}\n#endif\n\t};\n\n\t//generator with compile-time bounds\n\ttemplate <\n\t\tint LowerBound,\n\t\tint UpperBound,\n\t\tclass Distribution = std::uniform_int_distribution<>\n\t>\n\tclass StaticGenerator : public RandomGenerator<Distribution> {\n\n\t  public:\n\n\t\tStaticGenerator()\n\t\t\t: RandomGenerator<Distribution>(Private::SingleRandomEngine::Instance(), Distribution(LowerBound, UpperBound)) {}\n\t};\n\n\t//expose typical usages of the dynamic generator\n\tusing IntGenerator =\t\tGenerator<std::uniform_int_distribution<>>;\n\tusing SmallIntGenerator =\tGenerator<boost::uniform_smallint<>>;\n\tusing FloatGenerator =\t\tGenerator<std::uniform_real_distribution<float>, float>;\n\tusing BoolGenerator =\t\tGenerator<std::bernoulli_distribution>;\n\n} //ns Ctoolhu::Random\n\n#endif\n", "meta": {"hexsha": "be05505d01443163a9e8c55b6451f4476b45c37b", "size": 2094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ctoolhu/random/generator.hpp", "max_stars_repo_name": "erestor/ctoolhu", "max_stars_repo_head_hexsha": "d447840424b18cf89280fdf7bd29d162dc5ed9a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ctoolhu/random/generator.hpp", "max_issues_repo_name": "erestor/ctoolhu", "max_issues_repo_head_hexsha": "d447840424b18cf89280fdf7bd29d162dc5ed9a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ctoolhu/random/generator.hpp", "max_forks_repo_name": "erestor/ctoolhu", "max_forks_repo_head_hexsha": "d447840424b18cf89280fdf7bd29d162dc5ed9a2", "max_forks_repo_licenses": ["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.92, "max_line_length": 116, "alphanum_fraction": 0.6962750716, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5145125491386272}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/StdVector>\n\nclass ThinPlateSpline {\npublic:\n  typedef std::vector<Eigen::Vector3d,\n                      Eigen::aligned_allocator<Eigen::Vector3d>>\n      PointList;\n\n  ThinPlateSpline() {}\n  ThinPlateSpline(const PointList &src, const PointList &dst);\n  ~ThinPlateSpline() {}\n\n  /* Solve */\n  void solve();\n\n  /* Interpolate */\n  Eigen::Vector3d interpolate(const Eigen::Vector3d &p) const;\n\n  /* Source Points */\n  const PointList &srcPoints() const { return mSrcPoints; }\n\n  /* Set Source Points */\n  void setSrcPoints(const PointList &points) { mSrcPoints = points; }\n\n  /* Destination Points */\n  const PointList &dstPoints() const { return mDstPoints; }\n\n  /* Set Destination Points */\n  void setDstPoints(const PointList &points) { mDstPoints = points; }\n\nprotected:\n  /* Radial Basis Function */\n  static inline double radialBasis(double r) {\n    return r == 0.0 ? r : r * r * log(r);\n  }\n\n  /* Data */\n  PointList mSrcPoints;\n  PointList mDstPoints;\n  Eigen::MatrixXd mW;\n  Eigen::MatrixXd mL;\n};\n", "meta": {"hexsha": "87933fcd8f6f97f58a909b8b8c6bf9809116d0ff", "size": 1057, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ThinPlateSpline.hpp", "max_stars_repo_name": "buresu/ThinPlateSpline", "max_stars_repo_head_hexsha": "24d77d906bd1921d27a22da7120fb92e5365645f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-11-22T03:32:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-26T03:28:00.000Z", "max_issues_repo_path": "ThinPlateSpline.hpp", "max_issues_repo_name": "buresu/ThinPlateSpline", "max_issues_repo_head_hexsha": "24d77d906bd1921d27a22da7120fb92e5365645f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-23T07:00:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-25T05:52:03.000Z", "max_forks_repo_path": "ThinPlateSpline.hpp", "max_forks_repo_name": "buresu/ThinPlateSpline", "max_forks_repo_head_hexsha": "24d77d906bd1921d27a22da7120fb92e5365645f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-11-10T03:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T14:39:25.000Z", "avg_line_length": 22.9782608696, "max_line_length": 69, "alphanum_fraction": 0.6679280984, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.769080247656264, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.5144225962985216}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,\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#include <boost/config.hpp>\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n\nint main()\n{\n    using namespace boost;\n    typedef adjacency_list< vecS, vecS, undirectedS,\n        property< vertex_distance_t, int >, property< edge_weight_t, int > >\n        Graph;\n    typedef std::pair< int, int > E;\n    const int num_nodes = 5;\n    E edges[]\n        = { E(0, 2), E(1, 3), E(1, 4), E(2, 1), E(2, 3), E(3, 4), E(4, 0) };\n    int weights[] = { 1, 1, 2, 7, 3, 1, 1 };\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n    Graph g(num_nodes);\n    property_map< Graph, edge_weight_t >::type weightmap = get(edge_weight, g);\n    for (std::size_t j = 0; j < sizeof(edges) / sizeof(E); ++j)\n    {\n        graph_traits< Graph >::edge_descriptor e;\n        bool inserted;\n        boost::tie(e, inserted) = add_edge(edges[j].first, edges[j].second, g);\n        weightmap[e] = weights[j];\n    }\n#else\n    Graph g(edges, edges + sizeof(edges) / sizeof(E), weights, num_nodes);\n#endif\n    std::vector< graph_traits< Graph >::vertex_descriptor > p(num_vertices(g));\n\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n    property_map< Graph, vertex_distance_t >::type distance\n        = get(vertex_distance, g);\n    property_map< Graph, vertex_index_t >::type indexmap = get(vertex_index, g);\n    prim_minimum_spanning_tree(g, *vertices(g).first, &p[0], distance,\n        weightmap, indexmap, default_dijkstra_visitor());\n#else\n    prim_minimum_spanning_tree(g, &p[0]);\n#endif\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    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "d9a78758aa9f618afad99000b4c7ce9cd7f18bbd", "size": 2152, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/prim-example.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.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": "3rdparty/boost_1_73_0/libs/graph/example/prim-example.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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/graph/example/prim-example.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": 37.7543859649, "max_line_length": 80, "alphanum_fraction": 0.5780669145, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5144225872140019}}
{"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 *    References\n *      E.H. Hirschel and C. Weiland, Selected Aerothermodynamic Design Problems of Hypersonic\n *          Flight Vehicles (chapter 5), Springer/AIAA, 2009.\n *      D. Dirkx, Continuous Shape Optimization of Entry Vehicles, MSc thesis, Delft University\n *          of Technology, 2011 (Unpublished).\n *\n */\n\n#include <cmath>\n#include <iostream>\n\n#include <boost/make_shared.hpp>\n#include <memory>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\n#include \"Tudat/Mathematics/GeometricShapes/capsule.h\"\n#include \"Tudat/Mathematics/GeometricShapes/conicalFrustum.h\"\n#include \"Tudat/Mathematics/GeometricShapes/sphereSegment.h\"\n#include \"Tudat/Mathematics/GeometricShapes/torus.h\"\n\nnamespace tudat\n{\nnamespace geometric_shapes\n{\n\n//! Default constructor.\nCapsule::Capsule( const double noseRadius,\n                  const double middleRadius,\n                  const double rearLength,\n                  const double rearAngle,\n                  const double sideRadius )\n{\n    using std::sin;\n    using std::cos;\n    using mathematical_constants::PI;\n\n    // Call set functions for number of single and composite surface geometries\n    // with predetermined values.\n    setNumberOfCompositeSurfaceGeometries( 0 );\n    setNumberOfSingleSurfaceGeometries( 4 );\n\n    // Set member shape variables\n    noseRadius_ = noseRadius;\n    middleRadius_ = middleRadius;\n    rearLength_ = rearLength;\n    rearAngle_ = rearAngle;\n    sideRadius_ = sideRadius;\n\n    // Determine and set extent of spherical nose part.\n    double noseSphereAngle_ = asin( ( middleRadius_ - sideRadius_ )\n                                    / ( noseRadius_ - sideRadius_ ) );\n\n    // Create nose sphere.\n    std::shared_ptr< SphereSegment > noseSphere_ = std::make_shared< SphereSegment >(\n                noseRadius_, 0, 2 * PI, 0, noseSphereAngle_ );\n\n    // Declare translation vector.\n    Eigen::VectorXd translationVector_ = Eigen::VectorXd( 3 );\n    translationVector_( 2 ) = 0.0;\n    translationVector_( 1 ) = 0.0;\n    translationVector_( 0 ) = - noseRadius_ * cos( noseSphereAngle_ );\n\n    // Set nose translation vector.\n    noseSphere_->setOffset( translationVector_ );\n\n    // Set noseSphere_ in singleSurfaceList_.\n    setSingleSurfaceGeometry( noseSphere_, 0 );\n\n    //Calculate noseSphere volume\n    double noseSphereHeight_ = noseRadius_ * (1.0 - cos( noseSphereAngle_ ));\n    double noseSphereVolume_ = (PI / 3.0) * pow(noseSphereHeight_, 2.0) * (\n                3.0 * noseRadius - noseSphereHeight_ );\n\n    // Create rear cone, fully revolved.\n    std::shared_ptr< ConicalFrustum > cone_ = std::make_shared< ConicalFrustum >(\n                rearAngle_, middleRadius_ - sideRadius_ * ( 1.0 - cos( rearAngle_ ) ),\n                rearLength_ );\n\n    // Set translation vector of cone.\n    translationVector_( 0 ) = -sideRadius_ * ( sin( PI / 2.0 - noseSphereAngle_ )\n                                               + sin ( -rearAngle_ ) );\n    cone_->setOffset( translationVector_ );\n\n    // Set cone in singleSurfaceList_.\n    setSingleSurfaceGeometry( cone_, 1 );\n\n    // Obtain start radius of cone.\n    double startRadius_ = cone_->getStartRadius( );\n\n    // Calculate end radius of cone.\n    double endRadius_ = startRadius_ + rearLength_ * tan( rearAngle_ );\n\n    // Calculate volume of cone.\n    double fullConeLength_ = rearLength_ + endRadius_ / tan( -rearAngle_ );\n    double coneVolume_ = (PI / 3.0) *\n            ( pow(startRadius_, 2.0) * fullConeLength_ -\n              pow(endRadius_, 2.0) * ( fullConeLength_ - rearLength_ ));\n\n    // Calculate rear sphere radius.\n    double rearNoseRadius_ = endRadius_ / cos( -rearAngle_ );\n\n    // Create rear sphere ( \"end cap\" ), fully revolved.\n    std::shared_ptr< SphereSegment > rearSphere_ = std::make_shared< SphereSegment >(\n                rearNoseRadius_, 0.0, 2.0 * PI, PI / 2.0 - rearAngle_, PI );\n\n    // Set translation vector of rear sphere.\n    translationVector_( 0 ) =  ( rearNoseRadius_ * sin( -rearAngle_ ) ) - rearLength_\n            - ( sideRadius_ * ( sin( PI / 2.0 - noseSphereAngle_ ) + sin ( -rearAngle_ ) ) );\n    rearSphere_->setOffset( translationVector_ );\n    setSingleSurfaceGeometry( rearSphere_, 2 );\n\n    // Calcualte volume of rear sphere\n    double rearSphereHeight_ = rearNoseRadius_ * ( 1.0 - cos( (PI / 2.0) + rearAngle));\n    double rearSphereVolume_ = (PI / 3.0 ) * pow( rearSphereHeight_, 2.0 ) * (\n                3.0 * rearNoseRadius_ - rearSphereHeight_);\n\n\n    // Create torus section of capsule.\n    double torusMajorRadius_ = ( noseRadius_ - sideRadius_ ) * sin( noseSphereAngle_ );\n    std::shared_ptr< Torus > torus_ = std::make_shared< Torus >(\n       torusMajorRadius_, sideRadius_, 0.0, 2.0 * PI, PI / 2.0 - noseSphereAngle_, rearAngle_ );\n\n    //Calculate torus volume\n    double minimumDiskRadius_ = middleRadius_ - sideRadius_;\n    double integrationLowerLimit_ = -1.0 * sideRadius_ * cos( noseSphereAngle_ );\n    double integrationUpperLimit_ = sideRadius_ * sin( -rearAngle_ );\n    double torusVolume_ = PI * (\n            pow( minimumDiskRadius_, 2.0 ) * (integrationUpperLimit_ - integrationLowerLimit_ )\n            + minimumDiskRadius_ * pow( sideRadius_, 2.0 ) * (\n                (asin( integrationUpperLimit_ / sideRadius_) + 0.5* sin( 2* asin(integrationUpperLimit_ / sideRadius_)))\n                - (asin( integrationLowerLimit_ / sideRadius_) + 0.5* sin( 2* asin(integrationLowerLimit_ / sideRadius_)))\n                )\n            + pow( sideRadius_, 2.0 ) * ( integrationUpperLimit_ - integrationLowerLimit_ )\n            - (pow( integrationUpperLimit_, 3.0 ) - pow( integrationLowerLimit_, 3.0 )) / 3.0\n                );\n\n\n    //Calculate total capsule volume\n    capsuleVolume_ = noseSphereVolume_ + coneVolume_ + rearSphereVolume_ + torusVolume_;\n\n    //Calculate total capsule length\n    totalLength_ = noseSphereHeight_ - integrationLowerLimit_ + integrationUpperLimit_ +\n            rearLength_ + rearSphereHeight_;\n\n    //Calculate frontal area\n    frontalArea_ = PI * pow( middleRadius_, 2.0 );\n\n    // Set translation vector of rear sphere.\n    translationVector_( 0 ) = -cos( noseSphereAngle_ ) * sideRadius_;\n    torus_->setOffset( translationVector_ );\n    setSingleSurfaceGeometry( torus_, 3 );\n\n    // Set rotation matrix fo each part to be compatible with flow direction in\n    // aerodynamic analysis.\n    Eigen::MatrixXd rotationMatrix = Eigen::MatrixXd( 3, 3 );\n    double angle_ = PI / 2.0;\n    rotationMatrix( 0, 0 ) = cos( angle_ );\n    rotationMatrix( 0, 1 ) = 0.0;\n    rotationMatrix( 0, 2 ) = sin( angle_ );\n    rotationMatrix( 1, 0 ) = 0.0;\n    rotationMatrix( 1, 1 ) = 1.0;\n    rotationMatrix( 1, 2 ) = 0.0;\n    rotationMatrix( 2, 0 ) = -sin( angle_ );\n    rotationMatrix( 2, 1 ) = 0.0;\n    rotationMatrix( 2, 2 ) = cos( angle_ );\n\n    // Set rotation matrix for single surface geometries.\n    for ( unsigned i = 0; i < numberOfSingleSurfaceGeometries_ ; i++ )\n    {\n        singleSurfaceGeometryList_[ i ]->setRotationMatrix( rotationMatrix );\n    }\n}\n\n//! Overload ostream to print class information.\nstd::ostream &operator << ( std::ostream &stream, Capsule& capsule )\n{\n    stream << \"This is a capsule.\" << std::endl;\n    stream << \"The defining parameters are: \" << std::endl\n           << \"Nose radius: \" << capsule.getNoseRadius( ) << std::endl\n           << \"Mid radius: \" << capsule.getMiddleRadius( ) << std::endl\n           << \"Rear length: \" << capsule.getRearLength( ) << std::endl\n           << \"Rear angle: \" << capsule.getRearAngle( ) << std::endl\n           << \"Side radius: \" << capsule.getSideRadius( ) << std::endl;\n\n    return stream;\n}\n\n} // namespace geometric_shapes\n} // namespace tudat\n", "meta": {"hexsha": "4398adf1c4a6c8b8c22811b357b3254c3a23c72a", "size": 8138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/GeometricShapes/capsule.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/Mathematics/GeometricShapes/capsule.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/Mathematics/GeometricShapes/capsule.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": 40.2871287129, "max_line_length": 122, "alphanum_fraction": 0.6544605554, "num_tokens": 2186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5143897846785026}}
{"text": "#include <iostream>\n#include <random>\n#include <limits>\n#include <vector>\n\n// TODO To be deleted\n#include <xtensor/xarray.hpp>\n#include <xtensor/xio.hpp>\n#include <xtensor/xrandom.hpp>\n// TODO To be deleted\n#include <Eigen/Dense>\n#include \"arrays/array.h\"\n\n#include <cxxopts.hpp>\n\nusing namespace std;\n\nenum Test {\n\tONE = 1,\n\tNONE = -1\n};\n\nvoid xtensor_example() {\n\t// Example of init\n\tcout << endl << endl;\n\txt::xarray<int> arr {1, 2, 3, 4, 5, 6, 7, 8, 9};\n\tcout << arr.shape()[0] << endl;\n\tauto r = argwhere(arr < 5);\n\tcout << r.data() << endl;\n\tarr.reshape({3, 3});\n\tcout << arr.shape().size() << endl;\n\tcout << arr << endl;\n\n\t// Example of operations\n\tcout << endl << endl;\n\tcout << arr + arr << endl;\n\tcout << arr * arr << endl;\n\tcout << arr / arr << endl;\n\n\t// Example for using randome engine\n\tcout << endl << endl;\n\tauto rnd1 = xt::random::get_default_random_engine();\n\tauto rnd2 = xt::random::get_default_random_engine();\n\trnd1.seed(123);\n\trnd2.seed(123);\n\tcout << xt::random::rand<double>({3, 3}, -10, 10, rnd1) << endl;\n\tcout << xt::random::rand<double>({3, 3}, -10, 10, rnd2) << endl;\n\tcout << xt::random::rand<double>({4, 4, 4, 4}) << endl;\n\n\t// random generator\n\tcout << endl << endl;\n\tauto rand1 = minstd_rand0(123);\n\tauto rand2 = minstd_rand0(123);\n\tcout << endl;\n\tcout << xt::random::rand<double>({2, 2}, -10, 10, rand1) << endl;\n\tcout << xt::random::rand<double>({2, 2}, -10, 10, rand2) << endl;\n\n\t// Brodcasting\n\tcout << endl << endl;\n\tauto rnd = minstd_rand0(123);\n\tauto A = xt::random::rand<double>({3, 3}, -10, 10, rnd);\n\tcout << \"A = \" << endl << A << endl;\n\txt::xarray<double> b = xt::random::rand<double>({3}, -10, 10, rnd);\n\tcout << \"b = \" << endl << b << endl;\n\tcout << \"A + b  = \" << endl << A + b << endl;\n\tb.reshape({3, 1});\n\tcout << \"b' = \" << endl << b << endl;\n\tcout << \"A + b' = \" << endl << A + b << endl;\n}\n\nvoid eigen_example() {\n\t// Eigen test\n\tcout << endl << endl;\n\tEigen::MatrixXd m = Eigen::MatrixXd::Random(3,3);\n\tm = (m + Eigen::MatrixXd::Constant(3,3,1.2)) * 50;\n\tcout << \"m =\" << endl << m << endl << endl;\n\tauto v = Eigen::VectorXd(3);\n\tv << 1, 2, 3;\n\tcout << \"v =\" << endl << v << endl << endl;\n\tcout << \"m * v =\" << endl << m * v << endl << endl;\n\tcout << \"m .* v =\" << endl << m.array().colwise() * v.array() << endl;\n}\n\nvoid cpp_test() {\n\t// infinity\n\tcout << endl << endl;\n\tauto infd = numeric_limits<double>::infinity();\n\tcout << infd << endl;\n\tauto infi = numeric_limits<int>::infinity();\n\tcout << infi << endl;\n\tcout << (infd < infi) << endl;\n\tcout << (infd == infi) << endl;\n\tcout << (infi == infi) << endl;\n\tcout << (infd == infd) << endl;\n\tcout << -1 * infd << endl;\n\tcout << -1 * infi << endl;\n\n\t// Enum test\n\tcout << endl << endl;\n\tcout << ONE << endl;\n\tcout << NONE << endl;\n\n\t// Random generator\n\tauto rand1 = minstd_rand0(123);\n\tauto rand2 = minstd_rand0(123);\n\tauto dist = uniform_int_distribution(0, 10);\n\tfor (int i = 0; i < 10; ++i) cout << dist(rand1) << \" \" << dist(rand2) << \" | \";\n}\n\nvoid test_array() {\n\tauto shape = vector<unsigned int>({3, 3, 3});\n\tauto a = Array(shape);\n\tauto b = Array({3, 3, 3});\n}\n\nint main(int argc, char* argv[]) {\n//\teigen_example();\n//\tcpp_test();\n//\txtensor_example();\n\ttest_array();\n\treturn 0;\n}\n", "meta": {"hexsha": "88bce50dbf57d33112c3ba09da6f8fc10730d588", "size": 3197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "kb2623/NiaCpp", "max_stars_repo_head_hexsha": "68ca51c7053d33a12840a6c16d2f6a362b10c4a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-10T15:11:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-10T15:11:48.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "kb2623/NiaCpp", "max_issues_repo_head_hexsha": "68ca51c7053d33a12840a6c16d2f6a362b10c4a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "kb2623/NiaCpp", "max_forks_repo_head_hexsha": "68ca51c7053d33a12840a6c16d2f6a362b10c4a0", "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.9918699187, "max_line_length": 81, "alphanum_fraction": 0.5702220832, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5143178065810279}}
{"text": "// =======================================================================\n// Copyright 2015 by Ireneusz Szcze\u015bniak\n// Author: Ireneusz Szcze\u015bniak <www.irkos.org>\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// =======================================================================\n// This is the implementation of the Yen algorithm:\n//\n// Jin Y. Yen, Finding the k shortest loopless paths in a network,\n// Management Science, vol. 17, no. 11, July 1971, pages 712-716\n//\n// Note 1: in the article there are Q^k Q_k Q^k_k used.  As far as I\n// can tell they have the same meaning.  Q simply denotes the number\n// of the node previous to the last node in a path (which always\n// equals to the number of nodes in the path - 1), while (Q) denotes\n// the node number Q in a path.  For instance, in the path a-b-c-d,\n// the number of the node previous to the last is Q = 3, while (Q) =\n// c.  Q^k refers to the k-th shortest path, and simply means the\n// number of the node, which is previous to the last in the k-shortest\n// path.\n// =======================================================================\n\n#ifndef BOOST_GRAPH_YEN_KSP\n#define BOOST_GRAPH_YEN_KSP\n\n#include <list>\n#include <set>\n#include <utility>\n\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/optional.hpp>\n\n#include \"custom_dijkstra_call.hpp\"\n\nnamespace boost {\n\n  template <typename Graph, typename WeightMap, typename IndexMap>\n  std::list<std::pair<typename WeightMap::value_type,\n                      std::list<typename Graph::edge_descriptor>>>\n  yen_ksp(const Graph& g,\n          typename Graph::vertex_descriptor s,\n          typename Graph::vertex_descriptor t,\n          WeightMap wm, IndexMap im, optional<unsigned> K)\n  {\n    typedef typename Graph::vertex_descriptor vertex_descriptor;\n    typedef typename Graph::edge_descriptor edge_descriptor;\n    typedef typename WeightMap::value_type weight_type;\n    typedef std::set<edge_descriptor> es_type;\n    typedef std::set<vertex_descriptor> vs_type;\n    typedef filtered_graph<Graph, is_not_in_subset<es_type>,\n                           is_not_in_subset<vs_type>> fg_type;\n    typedef std::list<edge_descriptor> path_type;\n    typedef std::pair<weight_type, path_type> kr_type;\n\n    // The shortest paths - these we return.\n    std::list<kr_type> A;\n\n    // An empty result if the source and destination are the same.\n    if (s == t)\n      return A;\n\n    // The tentative paths - these are candidate paths.  It's a set,\n    // because we want to make sure that a given result can show up in\n    // the set of tentative results only once.  The problem is that\n    // the algorithm can find the same tentative path many times.\n    std::set<kr_type> B;\n\n    // Try to find the (optional) shortest path.\n    optional<kr_type> osp = custom_dijkstra_call(g, s, t, wm, im);\n\n    // We quit if there was no shortest path.\n    if (!osp)\n      return A;\n    \n    // The first shortest path found becomes our first solution.\n    A.push_back(std::move(osp.get()));\n\n    // In each iteration we produce the next k-th shortest path.\n    for (int k = 2; !K || k <= static_cast<int>(K.get()); ++k)\n      {\n        // The previous shortest result and path.\n        const auto &psr = A.back();\n        const auto &psp = psr.second;\n\n        // The set of excluded edges.  It's a set, because the\n        // algorithm can try to exclude an edge many times.\n        es_type exe;\n        // The set of excluded vertexes.\n        vs_type exv;\n\n        // The edge predicate.\n        is_not_in_subset<es_type> ep(exe);\n        // The vertex predicate.\n        is_not_in_subset<vs_type> vp(exv);\n\n        // The filtered graph.\n        fg_type fg(g, ep, vp);\n\n        // The root result: the cost and the root path.\n        kr_type rr;\n        // The root path.\n        const path_type &rp = rr.second;\n\n        // Use the previous shortest path to get tentative paths.  We\n        // can go ahead with the loop without checking any condition\n        // (the condition in the for-statement is true): the path\n        // found must have at least one link, because s != t.\n        for(typename path_type::const_iterator i = psp.begin(); true;)\n          {\n            // An edge of the previous shortest path.\n            const edge_descriptor &edge = *i;\n\n            // The spur vertex - we try to deviate at this node.\n            const vertex_descriptor &sv = source(edge, g);\n\n            // Iterate over all previous shortest paths.\n            // An iteration examines j-th shortest path.\n            for(const auto &jr: A)\n              {\n                // The j-th shortest path.\n                const path_type &jp = jr.second;\n\n                // Let's prepare for the comparison.\n                typename path_type::const_iterator jpi = jp.begin();\n                typename path_type::const_iterator rpi = rp.begin();\n\n                // Iterate as long as the edges are equal.\n                while(jpi != jp.end() && rpi != rp.end() && *jpi == *rpi)\n                  ++jpi, ++rpi;\n\n                // Make sure we didn't reach the end of jp.  If we\n                // did, there is no next edge in jp, which we could\n                // exclude.  Also, make sure we reached the end of rp,\n                // i.e., the jp begins with the complete rp, and not a\n                // head of rp.\n                if (jpi != jp.end() && rpi == rp.end())\n                  exe.insert(*jpi);\n              }\n\n            // Optional spur result.\n            optional<kr_type> osr = custom_dijkstra_call(fg, sv, t, wm, im);\n\n            if (osr)\n              {\n                // The tentative result.\n                kr_type tr = std::move(osr.get());\n                tr.first += rr.first;\n                tr.second.insert(tr.second.begin(), rp.begin(), rp.end());\n                B.insert(std::move(tr));\n              }\n\n            // We have the condition to break the look here, and not\n            // at the beginning, because we don't want to execute the\n            // remainer of the loop in vain.\n            if (++i == psp.end())\n              break;\n\n            // Remove the vertex that in this iteration is the spur,\n            // but in the next iteration it's going to be a vertex\n            // that should not be considered in the search for a spur\n            // path.\n            exv.insert(sv);\n\n            // Add the edge to the back of the root result.\n            rr.first += get(wm, edge);\n            rr.second.push_back(edge);\n          }\n\n        // Stop searching when there are no tentative paths.\n        if (B.empty())\n          break;\n\n        // Take the shortest tentative path and make it the next\n        // shortest path.\n        A.push_back(std::move(*B.begin()));\n        B.erase(B.begin());\n      }\n    \n    return A;\n  }\n\n  template <typename Graph>\n  std::list<std::pair<typename property_map<Graph, edge_weight_t>::value_type,\n                      std::list<typename Graph::edge_descriptor>>>\n  yen_ksp(Graph& g,\n          typename Graph::vertex_descriptor s,\n          typename Graph::vertex_descriptor t,\n          optional<unsigned> K = optional<unsigned>())\n  {\n    return yen_ksp(g, s, t, get(edge_weight_t(), g),\n                   get(vertex_index_t(), g), K);\n  }\n\n} // boost\n\n#endif /* BOOST_GRAPH_YEN_KSP */\n", "meta": {"hexsha": "11e90e4d2f0c651614612bc37d4d162a753e601e", "size": 7529, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/ksp/yen_ksp.hpp", "max_stars_repo_name": "gunjanbaid/octopus", "max_stars_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 278.0, "max_stars_repo_stars_event_min_datetime": "2016-10-03T16:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:59:32.000Z", "max_issues_repo_path": "lib/ksp/yen_ksp.hpp", "max_issues_repo_name": "gunjanbaid/octopus", "max_issues_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 229.0, "max_issues_repo_issues_event_min_datetime": "2016-10-13T14:07:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:59:58.000Z", "max_forks_repo_path": "lib/ksp/yen_ksp.hpp", "max_forks_repo_name": "gunjanbaid/octopus", "max_forks_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-10-28T22:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:28:43.000Z", "avg_line_length": 37.2722772277, "max_line_length": 78, "alphanum_fraction": 0.5748439368, "num_tokens": 1717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5143178005410017}}
{"text": "#include <iostream>\n#include <chrono>\n#include <string>\n#include <cstdlib>\n#include <Eigen>\n#include \"nbodytool.hpp\"\n\nvoid initializeSim(Simulator& sim) {\n    for (int i = 0; i < sim.maxObjects; ++i) {\n        sim.addObject(rand() % 100, 0.001, Eigen::Vector3d::Random()*10, Eigen::Vector3d::Zero());\n    }\n}\n\nvoid benchmark(Simulator& sim, int iters, const std::string& name) {\n    std::cout << \"Benchmarking \" << name                  << std::endl\n              << \"--------------------------------------\" << std::endl\n              << \"Average over \" << iters << \" iterations.\"       << std::endl;\n\n    std::chrono::time_point<std::chrono::high_resolution_clock> start, end;\n    double stepAvg = 0;\n    for (int i = 0; i < iters; ++i) {\n        start = std::chrono::high_resolution_clock::now();\n        sim.step();\n        end   = std::chrono::high_resolution_clock::now();\n        stepAvg += std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();\n    }\n    std::cout << \"step(): \" << stepAvg/iters << \" ms\" << std::endl << std::endl;\n}\n\nvoid energyConservationTest(Simulator& sim, int iters, const std::string& name) {\n    std::cout << \"Testing Energy Conservation: \" << name                  << std::endl\n              << \"--------------------------------------\" << std::endl\n              << \"Over \" << iters << \" iterations.\"       << std::endl;\n    \n    double initialEnergy = sim.totalEnergy();\n    std::cout << \"Initial Energy: \" << initialEnergy << std::endl;\n\n    double avgEnergyChange = 0;\n    double prevEnergy = initialEnergy;\n    for (int i = 0; i < iters; ++i) {\n        sim.step();\n        double currEnergy = sim.totalEnergy();\n        double energyChange = currEnergy - prevEnergy;\n        avgEnergyChange += energyChange;\n        prevEnergy = currEnergy;\n\n        std::cout << \"Step \" << i + 1 << \" | Current Energy: \" << currEnergy << \" | Change: \" << \n                     energyChange << \" | Avg. Change: \" << avgEnergyChange/(i+1) << std::endl;\n    }\n\n    \n}\n\nint main() {\n    // Simulator2d 1k Euler Gravitational_Direct\n    Simulator sim2d_euler_gd_1k(1, 1000, new EulerIntegrator(),\n                                new Gravitational_Direct(0.1, Unit::LightYear, Unit::SolarMass, Unit::JulianMillenium));\n    \n    Simulator sim2d_verlet_gbh_1k(1, 100, new VerletIntegrator(),\n                                   new Gravitational_BarnesHut(1, 0.1, Unit::LightYear, Unit::SolarMass, Unit::JulianMillenium));\n\n    Simulator sim2d_verlet_gbh_10k(1, 10000, new VerletIntegrator(),\n                                   new Gravitational_BarnesHut(1, 0.1, Unit::LightYear, Unit::SolarMass, Unit::JulianMillenium));\n\n    initializeSim(sim2d_euler_gd_1k);\n    initializeSim(sim2d_verlet_gbh_1k);\n    initializeSim(sim2d_verlet_gbh_10k);\n\n    energyConservationTest(sim2d_verlet_gbh_1k, 100000, \"Simulator Verlet Gravitational_BarnesHut 1k\");\n\n    benchmark(sim2d_euler_gd_1k, 3, \"Simulator Euler Gravitational_Direct 1k\");\n    benchmark(sim2d_verlet_gbh_10k, 5, \"Simulator Verlet Gravitational_BarnesHut 10k\");\n\n    return 0;\n}\n", "meta": {"hexsha": "a4c35516a5b162c78ef94d5d2c32f157c826b55b", "size": 3067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/benchmark.cpp", "max_stars_repo_name": "tdude92/nbody-tool", "max_stars_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-12T08:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:37:44.000Z", "max_issues_repo_path": "test/benchmark.cpp", "max_issues_repo_name": "tdude92/nbody-tool", "max_issues_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_issues_repo_licenses": ["MIT"], "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/benchmark.cpp", "max_forks_repo_name": "tdude92/nbody-tool", "max_forks_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_forks_repo_licenses": ["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.3552631579, "max_line_length": 129, "alphanum_fraction": 0.5924356048, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5143177970564645}}
{"text": "\r\n#include <Discregrid/All>\r\n#include <Eigen/Dense>\r\n#include <cxxopts/cxxopts.hpp>\r\n\r\n#include \"resource_path.hpp\"\r\n\r\n#include <string>\r\n#include <iostream>\r\n#include <array>\r\n\r\nusing namespace Eigen;\r\n\r\nstd::istream& operator>>(std::istream& is, std::array<unsigned int, 3>& data)  \r\n{  \r\n\tis >> data[0] >> data[1] >> data[2];  \r\n\treturn is;  \r\n}  \r\n\r\nstd::istream& operator>>(std::istream& is, AlignedBox3d& data)  \r\n{  \r\n\tis\t>> data.min()[0] >> data.min()[1] >> data.min()[2]\r\n\t\t>> data.max()[0] >> data.max()[1] >> data.max()[2];  \r\n\treturn is;  \r\n}  \r\n\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\tcxxopts::Options options(argv[0], \"Generates a signed distance field from a closed two-manifold triangle mesh.\");\r\n\toptions.positional_help(\"[input OBJ file]\");\r\n\r\n\toptions.add_options()\r\n\t(\"h,help\", \"Prints this help text\")\r\n\t(\"r,resolution\", \"Grid resolution\", cxxopts::value<std::array<unsigned int, 3>>()->default_value(\"10 10 10\"))\r\n\t(\"d,domain\", \"Domain extents (bounding box), format: \\\"minX minY minZ maxX maxY maxZ\\\"\", cxxopts::value<AlignedBox3d>())\r\n\t(\"i,invert\", \"Invert SDF\")\r\n\t(\"o,output\", \"Ouput file in cdf format\", cxxopts::value<std::string>()->default_value(\"\"))\r\n\t(\"input\", \"OBJ file containing input triangle mesh\", cxxopts::value<std::vector<std::string>>())\r\n\t;\r\n\r\n\ttry\r\n\t{\r\n\t\toptions.parse_positional(\"input\");\r\n\t\toptions.parse(argc, argv);\r\n\t}\r\n\tcatch (cxxopts::OptionException const& e)\r\n\t{\r\n\t\tstd::cout << \"error parsing options: \" << e.what() << std::endl;\r\n\t\texit(1);\r\n\t}\r\n\tif (options.count(\"help\"))\r\n\t{\r\n\t\tstd::cout << options.help() << std::endl;\r\n\t\tstd::cout << std::endl << std::endl << \"Example: GenerateSDF -r \\\"50 50 50\\\" dragon.obj\" << std::endl;\r\n\t\texit(0);\r\n\t}\r\n\tif (!options.count(\"input\"))\r\n\t{\r\n\t\tstd::cout << \"ERROR: No input mesh given.\" << std::endl;\r\n\t\tstd::cout << options.help() << std::endl;\r\n\t\tstd::cout << std::endl << std::endl << \"Example: GenerateSDF -r \\\"50 50 50\\\" dragon.obj\" << std::endl;\r\n\t\texit(1);\r\n\t}\r\n\tauto resolution = options[\"r\"].as<std::array<unsigned int, 3>>();\r\n\tauto filename = options[\"input\"].as<std::vector<std::string>>().front();\r\n\r\n\tif (!std::ifstream(filename).good())\r\n\t{\r\n\t\tstd::cerr << \"ERROR: Input file does not exist!\" << std::endl;\r\n\t\texit(1);\r\n\t}\r\n\r\n\tstd::cout << \"Load mesh...\";\r\n\tDiscregrid::TriangleMesh mesh(filename);\r\n\tstd::cout << \"DONE\" << std::endl;\r\n\r\n\tstd::cout << \"Set up data structures...\";\r\n\tDiscregrid::MeshDistance md(mesh);\r\n\tstd::cout << \"DONE\" << std::endl;\r\n\r\n\tauto domain = options[\"d\"].as<Eigen::AlignedBox3d>();\r\n\tif (domain.isEmpty())\r\n\t{\r\n\t\tfor (auto const& x : mesh.vertices())\r\n\t\t{\r\n\t\t\tdomain.extend(x);\r\n\t\t}\r\n\t\tdomain.max() += 1.0e-3 * domain.diagonal().norm() * Vector3d::Ones();\r\n\t\tdomain.min() -= 1.0e-3 * domain.diagonal().norm() * Vector3d::Ones();\r\n\t}\r\n\r\n\tDiscregrid::CubicLagrangeDiscreteGrid sdf(domain, resolution);\r\n\tauto func = Discregrid::DiscreteGrid::ContinuousFunction{};\r\n\tif (options.count(\"invert\"))\r\n\t{\r\n\t\tfunc = [&md](Vector3d const& xi){return -1.0 * md.signedDistanceCached(xi);};\r\n\t}\r\n\telse\r\n\t{\r\n\t\tfunc = [&md](Vector3d const& xi){return md.signedDistanceCached(xi);};\r\n\t}\r\n\r\n\tstd::cout << \"Generate discretization...\" << std::endl;\r\n\tsdf.addFunction(func, true);\r\n\tstd::cout << \"DONE\" << std::endl;\r\n\r\n\tstd::cout << \"Serialize discretization...\";\r\n\tauto output_file = options[\"o\"].as<std::string>();\r\n\tif (output_file == \"\")\r\n\t{\r\n\t\toutput_file = filename;\r\n\t\tif (output_file.find(\".\") != std::string::npos)\r\n\t\t{\r\n\t\t\tauto lastindex = output_file.find_last_of(\".\"); \r\n\t\t\toutput_file = output_file.substr(0, lastindex);\r\n\t\t}\r\n\t\toutput_file += \".cdf\";\r\n\t}\r\n\tsdf.save(output_file);\r\n\tstd::cout << \"DONE\" << std::endl;\r\n\r\n\treturn 0;\r\n}", "meta": {"hexsha": "5933931c2bb382836137eb7561d299f7a384630f", "size": 3668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmd/generate_sdf/main.cpp", "max_stars_repo_name": "Borges3D/Discregrid", "max_stars_repo_head_hexsha": "f16a29afebf7a7f43139d5832bbfc7124c5d98db", "max_stars_repo_licenses": ["MIT"], "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_sdf/main.cpp", "max_issues_repo_name": "Borges3D/Discregrid", "max_issues_repo_head_hexsha": "f16a29afebf7a7f43139d5832bbfc7124c5d98db", "max_issues_repo_licenses": ["MIT"], "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_sdf/main.cpp", "max_forks_repo_name": "Borges3D/Discregrid", "max_forks_repo_head_hexsha": "f16a29afebf7a7f43139d5832bbfc7124c5d98db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:58:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T13:58:55.000Z", "avg_line_length": 29.5806451613, "max_line_length": 122, "alphanum_fraction": 0.6115049073, "num_tokens": 1066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5143177940364518}}
{"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_ARCH_COMMON_SIMD_FUNCTION_COSH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_COSH_HPP_INCLUDED\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/detail/constant/maxlog.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/average.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_greater.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD_IF ( cosh_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      //////////////////////////////////////////////////////////////////////////////\n      // if x = abs(a0) according x < Threshold e =  exp(x) or exp(x/2) is\n      // respectively computed\n      // *  in the first case cosh (e+rec(e))/2\n      // *  in the second     cosh is (e/2)*e (avoiding undue overflow)\n      // Threshold is Maxlog - Log_2\n      //////////////////////////////////////////////////////////////////////////////\n      A0 x = bs::abs(a0);\n      auto test1 = (x > Maxlog<A0>()-Log_2<A0>());\n      A0 fac = if_else(test1, Half<A0>(), One<A0>());\n      A0 tmp = exp(x*fac);\n      A0 tmp1 = Half<A0>()*tmp;\n      return if_else(test1, tmp1*tmp, bs::average(tmp, rec(tmp)));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "ceb338b67712acddf499c8e7aee6219834b93564", "size": 2207, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/cosh.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/arch/common/simd/function/cosh.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/arch/common/simd/function/cosh.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": 37.406779661, "max_line_length": 100, "alphanum_fraction": 0.5310376076, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5142950660093628}}
{"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_ARCH_COMMON_SIMD_FUNCTION_REM_PIO2_STRAIGHT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_REM_PIO2_STRAIGHT_HPP_INCLUDED\n\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/detail/constant/pio2_1.hpp>\n#include <boost/simd/detail/constant/pio2_2.hpp>\n#include <boost/simd/detail/constant/pio2_3.hpp>\n#include <boost/simd/constant/pio_4.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/if_one_else_zero.hpp>\n#include <boost/simd/function/genmask.hpp>\n#include <utility>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD(rem_pio2_straight_\n                          , (typename A0, typename X)\n                          , bd::cpu_\n                          , bs::pack_ < bd::floating_<A0>, X>\n                          )\n  {\n    using result_t = std::pair<A0, A0>;\n    BOOST_FORCEINLINE result_t operator() ( A0 const& x) const BOOST_NOEXCEPT\n    {\n      auto test = x > Pio_4<A0>();\n      A0 xr = x-Pio2_1<A0>();\n      xr -= Pio2_2<A0>();\n      xr -= Pio2_3<A0>();\n      return {if_one_else_zero(test),if_else(test, xr, x)};\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "60397cc5b38d597e8a864dd30a8fe882892440c1", "size": 1692, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/rem_pio2_straight.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/arch/common/simd/function/rem_pio2_straight.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/arch/common/simd/function/rem_pio2_straight.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": 32.5384615385, "max_line_length": 100, "alphanum_fraction": 0.5945626478, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.5142950614999784}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <OpenVolumeMesh/Core/PropertyDefines.hh>\n#include <cstddef>\n\n#include \"Typedefs.hpp\"\n\nnamespace FeltElements\n{\n// Forward declarations.\nnamespace Body\n{\nstruct Material;\nstruct Forces;\n}  // namespace Body\n\nnamespace Derivatives\n{\n[[nodiscard]] Element::StiffnessResidual KR(\n\tElement::NodePositions const & x,\n\tElement::BoundaryVtxhIdxs const & boundary_faces_idxs,\n\tElement::BoundaryNodePositions const & boundary_faces_x,\n\tElement::ShapeDerivative const & dN_by_dX,\n\tBody::Material const & material,\n\tBody::Forces const & forces);\n\n[[nodiscard]] Element::Stiffness Kc(\n\tElement::ShapeDerivative const & dN_by_dx, Scalar v, Element::Elasticity const & c);\n[[nodiscard]] Element::Stiffness Ks(\n\tElement::ShapeDerivative const & dN_by_dx, Scalar v, Element::Stress const & s);\n[[nodiscard]] Element::Stiffness Kp(\n\tElement::BoundaryNodePositions const & xs, Element::BoundaryVtxhIdxs const & S_to_Vs, Scalar p);\n\n[[nodiscard]] Element::Elasticity c(Scalar J, Scalar lambda, Scalar mu);\n[[nodiscard]] Node::Force t(Scalar p, Element::SurfaceGradient const & dX_by_dS);\n[[nodiscard]] Element::Forces T(\n\tElement::ShapeDerivative const & dN_by_dx, Scalar v, Element::Stress const & sigma);\n[[nodiscard]] Element::Stress sigma(\n\tScalar J, Element::Gradient const & b, Scalar lambda, Scalar mu);\n\n[[nodiscard]] Scalar det_dx_by_dX(Element::Gradient const & F);\n[[nodiscard]] Element::Gradient b(Element::Gradient const & F);\n\n[[nodiscard]] Element::Gradient dx_by_dX(\n\tElement::NodePositions const & x, Element::ShapeDerivative const & dN_by_dX);\n[[nodiscard]] Element::Gradient dx_by_dX(\n\tElement::Gradient const & dx_by_dL, Element::Gradient const & dL_by_dX);\n\n[[nodiscard]] Scalar V(Element::NodePositions const & x);\n[[nodiscard]] Scalar v(Element::NodePositions const & x);\n[[nodiscard]] Scalar A(BoundaryElement::NodePositions const & s);\n\n[[nodiscard]] Element::Gradient dX_by_dL(Element::NodePositions const & X);\n[[nodiscard]] Element::Gradient dL_by_dX(Element::Gradient const & dX_by_dL);\n[[nodiscard]] Element::CartesianDerivative dx_by_dN(\n\tElement::ShapeCartesianTransform const & N_to_x);\n\n[[nodiscard]] Element::SurfaceGradient dX_by_dS(BoundaryElement::NodePositions const & X);\n\n[[nodiscard]] Element::ShapeDerivative dN_by_dX(Element::Gradient const & dL_by_dx);\n[[nodiscard]] Element::ShapeDerivative dN_by_dX(Element::ShapeCartesianTransform const & N_to_x);\n[[nodiscard]] Element::ShapeDerivative dN_by_dX(Element::NodePositions const & X);\n\n[[nodiscard]] Element::ShapeCartesianTransform N_to_x(Element::NodePositions const & X);\n\n[[nodiscard]] Scalar det_dx_by_dL(Element::NodePositions const & x);\n\nextern Element::IsoCoordDerivative const dL_by_dN;\nextern Element::ShapeDerivative const dN_by_dL;\nextern Element::SurfaceShapeDerivative const dN_by_dS;\nextern Element::ShapeDerivativeDeterminant const det_dN_by_dL;\nextern Tensor::Multi<3, 3, 3> const levi_civita;\n}  // namespace Derivatives\n}  // namespace FeltElements", "meta": {"hexsha": "c1f1df6e3cb3629a23bf77700c56e7bc88cc8dfa", "size": 2988, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/FeltElements/Derivatives.hpp", "max_stars_repo_name": "feltech/FeltElements", "max_stars_repo_head_hexsha": "8f6374945e46a9c9a2a742482ffe6b923b8b5c25", "max_stars_repo_licenses": ["MIT"], "max_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/FeltElements/Derivatives.hpp", "max_issues_repo_name": "feltech/FeltElements", "max_issues_repo_head_hexsha": "8f6374945e46a9c9a2a742482ffe6b923b8b5c25", "max_issues_repo_licenses": ["MIT"], "max_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/FeltElements/Derivatives.hpp", "max_forks_repo_name": "feltech/FeltElements", "max_forks_repo_head_hexsha": "8f6374945e46a9c9a2a742482ffe6b923b8b5c25", "max_forks_repo_licenses": ["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.84, "max_line_length": 97, "alphanum_fraction": 0.7694109772, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5142950504807505}}
{"text": "#pragma once\n\n#include <boost/align/is_aligned.hpp>\n#include <boost/simd/algorithm.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/function/aligned_load.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/log.hpp>\n#include <boost/simd/function/sum.hpp>\n#include <boost/simd/pack.hpp>\n\n#include \"source.hpp\"\n#include \"summing.hpp\"\n\ntypedef boost::simd::pack<double> pack_double;\n\nnamespace simdmath {\n\nBOOST_SYMBOL_EXPORT\ndouble logsumexp(double const *src, size_t length)\n{\n    using boost::alignment::is_aligned;\n    using boost::simd::aligned_load;\n    size_t const vector_size = pack_double::static_size;\n\n    double offset = boost::simd::reduce(\n        src, src + length,\n        boost::simd::Minf<double>(),\n        boost::simd::max,\n        boost::simd::Minf<jdouble>());\n    pack_double voffset(offset);\n\n    double acc = 0.;\n    while (length && !is_aligned(src, pack_double::alignment)) {\n        acc += boost::simd::exp(*(src++) - offset);\n        --length;\n    }\n    while (length % vector_size) {\n        --length;\n        acc += boost::simd::exp(src[length] - offset);\n    }\n    pack_double vacc = boost::simd::Zero<pack_double>();\n    for (size_t i = 0; i < length; i += vector_size) {\n        vacc += boost::simd::exp(aligned_load<pack_double>(src, i) - voffset);\n    }\n\n    return boost::simd::log(acc + boost::simd::sum(vacc)) + offset;\n}\n\nBOOST_SYMBOL_EXPORT\ndouble dot(double const *src1, double const *src2, size_t length)\n{\n    source_1d<weighted_sum_tag> f\n        = source_1d<weighted_sum_tag>(src1, src2, length);\n    return balanced_sum(f);\n}\n\n}  /* ::simdmath */\n", "meta": {"hexsha": "82caee01728463d0370eb9c47a765c0ce0e2850c", "size": 1670, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/simd/headers/simd_math.hpp", "max_stars_repo_name": "Jolanrensen/viktor", "max_stars_repo_head_hexsha": "f78cba6e8b4393cc8e1b573c2f2d7e4228429898", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 89.0, "max_stars_repo_stars_event_min_datetime": "2015-11-12T21:22:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T05:19:07.000Z", "max_issues_repo_path": "src/simd/headers/simd_math.hpp", "max_issues_repo_name": "Jolanrensen/viktor", "max_issues_repo_head_hexsha": "f78cba6e8b4393cc8e1b573c2f2d7e4228429898", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-10-23T08:27:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-15T11:21:57.000Z", "max_forks_repo_path": "src/simd/headers/simd_math.hpp", "max_forks_repo_name": "Jolanrensen/viktor", "max_forks_repo_head_hexsha": "f78cba6e8b4393cc8e1b573c2f2d7e4228429898", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-10-25T14:49:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T12:34:04.000Z", "avg_line_length": 27.8333333333, "max_line_length": 78, "alphanum_fraction": 0.6634730539, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5142950504807505}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n#include <memory>\n#include \"../include/trainer.h\"\n#include \"../include/model.h\"\n#include \"../include/optimizer.h\"\n#include \"../datasets/include/mnist.h\"\n\nint main()\n{\n    using namespace Eigen;\n    using namespace MyDL;\n    using std::cout;\n    using std::endl;\n    using std::make_shared;\n    using std::shared_ptr;\n\n    int batch_size = 100;\n    int input_channels = 1;\n    int input_height = 28;\n    int input_width = 28;\n    // int filter_num = 30;\n    int filter_num = 10;\n    int filter_size = 5;\n    int pad = 0;\n    int stride = 1;\n    int hidden_size = 100;\n    int output_size = 10;\n    double weight_init_std = 0.01;\n\n    double learning_rate = 0.001;\n    int epochs = 10;\n\n    auto model = make_shared<SimpleConvModel>(input_channels, \n                                              input_height, \n                                              input_width, \n                                              filter_num, \n                                              filter_size, \n                                              pad,\n                                              stride,\n                                              hidden_size,\n                                              output_size,\n                                              weight_init_std);\n    auto optimizer = make_shared<Adam>(learning_rate);\n    auto dataset = make_shared<MnistEigenDataset>(batch_size);\n\n    Trainer trainer(model, optimizer, dataset, epochs = epochs);\n\n    trainer.train();\n\n    return 0;\n}", "meta": {"hexsha": "471cd41b4ee809d96488bdfc2d281fac052d8fe3", "size": 1558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7/train_convnet.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": "ch7/train_convnet.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": "ch7/train_convnet.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": 29.3962264151, "max_line_length": 64, "alphanum_fraction": 0.4955070603, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.5142945752767696}}
{"text": "#include <vector>\n#include <iostream>\n#include <fstream>\n#include <random>\n#include <string>\n#include <algorithm>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/program_options/options_description.hpp>\n#include <boost/program_options/variables_map.hpp>\n#include <boost/program_options/parsers.hpp>\n\nnamespace po = boost::program_options;\n\ntypedef float float_t;\n\nstruct Point {\n\tfloat_t x, y;\n\n\tPoint() {}\n\tPoint(float_t nx, float_t ny): x(nx), y(ny) {}\n\n\tPoint operator - (const Point &p) const {\n\t\treturn Point(x - p.x, y - p.y);\n\t}\n\n\tPoint operator + (const Point &p) const {\n\t\treturn Point(x + p.x, y + p.y);\n\t}\n\n\tfloat_t operator * (const Point &p) const {\n\t\treturn x * p.x + y * p.y;\n\t}\n\n\tPoint operator * (const float_t k) const {\n\t\treturn Point(x * k, y * k);\n\t}\n};\n\nstruct GraphLayout {\n\tint n;\n\tstd::vector< std::vector<int> > adj;\n\tstd::vector<Point> layout;\n\tfloat_t W, H;\n\n\tGraphLayout(\n\t\t\tint n,\n\t\t\tfloat_t nodeDistW, float_t borderW, float_t edgeW,\n\t\t\tfloat_t crossW, float_t crossT,\n\t\t\tfloat_t canvasW, float_t canvasH\n\t) {\n\t\tthis->n = n;\n\t\t_nw = nodeDistW;\n\t\t_bw = borderW;\n\t\t_ew = edgeW;\n\t\t_cw = crossW;\n\t\t_mind = crossT;\n\t\tW = canvasW;\n\t\tH = canvasH;\n\t\tadj.assign(n, std::vector<int>());\n\t}\n\n\tvoid addEdge(int u, int v) {\n\t\tadj[u].push_back(v);\n\t\tadj[v].push_back(u);\n\t}\n\n\ttemplate<typename RNG> void initialize_positions(const std::vector<Point> &start, RNG &rng) {\n\t\tlayout = start;\n\t\tif (layout.empty()) {\n\t\t\tlayout.resize(n);\n\t\t\tstd::uniform_real_distribution<float_t> wdis(0, W);\n\t\t\tstd::uniform_real_distribution<float_t> hdis(0, H);\n\t\t\tfor (int i = 0; i < n; ++i) {\n\t\t\t\tlayout[i].x = wdis(rng);\n\t\t\t\tlayout[i].y = hdis(rng);\n\t\t\t}\n\t\t}\n\t\tinitEnergy();\n\t}\n\n\tvoid move(int v, Point d) {\n\t\t_tmpne = _ne;\n\t\t_tmpbe = _be;\n\t\t_tmpee = _ee;\n\t\t_tmpce = _ce;\n\t\t_tmpPoint = layout[v];\n\t\taddEnergy(v, -1);\n\t\tlayout[v].x = std::clamp<float_t>(\n\t\t\t\tlayout[v].x + d.x, W / 1000, static_cast<const float_t &>(W * 0.999)\n\t\t);\n\t\tlayout[v].y = std::clamp<float_t>(\n\t\t\t\tlayout[v].y + d.y, H / 1000, static_cast<const float_t &>(H * 0.999)\n\t\t);\n\t\taddEnergy(v, 1);\n\t}\n\n\t// Take care to call this only straight after move\n\tvoid undoMove(int v, Point d) {\n\t\tlayout[v] = _tmpPoint;\n\t\t_ne = _tmpne;\n\t\t_be = _tmpbe;\n\t\t_ee = _tmpee;\n\t\t_ce = _tmpce;\n\t}\n\n\tfloat_t getEnergy() const {\n\t\treturn _ne + _be + _ee + _ce;\n\t}\n\n\tfloat_t getNodeDistEnergy() const {\n\t\treturn _ne;\n\t}\n\n\tfloat_t getBorderEnergy() const {\n\t\treturn _be;\n\t}\n\n\tfloat_t getEdgesEnergy() const {\n\t\treturn _ee;\n\t}\n\n\tfloat_t getCrossingsEnergy() const {\n\t\treturn _ce;\n\t};\n\nprivate:\n\tfloat_t _mind;\n\tfloat_t _ne, _be, _ee, _ce;\n\tfloat_t _tmpne, _tmpbe, _tmpee, _tmpce;\n\tPoint _tmpPoint;\n\tfloat_t _nw, _bw, _ew, _cw;\n\n\tfloat_t _sqr(float_t x) {\n\t\treturn x * x;\n\t}\n\n\tfloat_t _sqdist(int i, int j) {\n\t\treturn _sqr(layout[i].x - layout[j].x) + _sqr(layout[i].y - layout[j].y);\n\t}\n\n\tfloat_t _segsqdist(int u, int v, int w) {\n\t\tfloat_t ans = fmin(_sqdist(w, u), _sqdist(w, v));\n\t\tPoint uw = layout[w] - layout[u];\n\t\tPoint uv = layout[v] - layout[u];\n\t\tfloat_t cp = uw * uv;\n\t\tif (cp < 0) return ans;\n\t\tif ((layout[u] - layout[v]) * (layout[w] - layout[v]) < 0) return ans;\n\t\tcp /= uv * uv;\n\t\tPoint h = layout[u] + (uv * cp);\n\t\treturn _sqr(layout[w].x - h.x) + _sqr(layout[w].y - h.y);\n\t}\n\n\tvoid initEnergy() {\n\t\t_ne = _be = _ee = _ce = 0;\n\t\tif (_nw != 0) {\n\t\t\tfloat_t dE = 0;\n\t\t\tfor (int i = 0; i < n; ++i) {\n\t\t\t\tfor (int j = 0; j < i; ++j) {\n\t\t\t\t\tdE += 1 / _sqdist(i, j);\n\t\t\t\t}\n\t\t\t}\n\t\t\t_ne += dE * _nw;\n\t\t}\n\t\tif (_bw != 0) {\n\t\t\tfloat_t dE = 0;\n\t\t\tfor (int i = 0; i < n; ++i) {\n\t\t\t\tdE +=\n\t\t\t\t\t\t1 / _sqr(layout[i].x) + 1 / _sqr(W - layout[i].x) +\n\t\t\t\t\t\t1 / _sqr(layout[i].y) + 1 / _sqr(H - layout[i].y);\n\t\t\t}\n\t\t\t_be += _bw * dE;\n\t\t}\n\t\tif (_ew != 0) {\n\t\t\tfloat_t dE = 0;\n\t\t\tfor (int v = 0; v < n; ++v) {\n\t\t\t\tfor (const auto &u : adj[v]) {\n\t\t\t\t\tif (v < u) {\n\t\t\t\t\t\tdE += _sqdist(v, u);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t_ee += _ew * dE;\n\t\t}\n\t\tif (_cw != 0) {\n\t\t\tfloat_t dE = 0;\n\t\t\tfor (int v = 0; v < n; ++v) {\n\t\t\t\tfor (int u : adj[v]) {\n\t\t\t\t\tif (u < v) continue;\n\t\t\t\t\tfor (int w = 0; w < n; ++w) {\n\t\t\t\t\t\tif (v == w || u == w) continue;\n\t\t\t\t\t\tdE += 1 / fmax(_mind, _segsqdist(u, v, w));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t_ce += _cw * dE;\n\t\t}\n\t}\n\n\tvoid addEnergy(int v, double c) {\n\t\tif (_nw != 0) {  // exact equality is fine here\n\t\t\tfloat_t dE = 0;\n\t\t\tfor (int i = 0; i < n; ++i) {\n\t\t\t\tif (i != v) dE += 1 / _sqdist(v, i);\n\t\t\t}\n\t\t\t_ne += c * _nw * dE;\n\t\t}\n\t\tif (_bw != 0) {\n\t\t\tfloat_t dE =\n\t\t\t\t\t1 / _sqr(layout[v].x) + 1 / _sqr(W - layout[v].x) +\n\t\t\t\t\t1 / _sqr(layout[v].y) + 1 / _sqr(H - layout[v].y);\n\t\t\t_be += c * _cw * dE;\n\t\t}\n\t\tif (_ew != 0) {\n\t\t\tfloat_t dE = 0;\n\t\t\tfor (const auto &u: adj[v]) {\n\t\t\t\tdE += _sqdist(v, u);\n\t\t\t}\n\t\t\t_ee += c * _ew * dE;\n\t\t}\n\t\tif (_cw != 0) {\n\t\t\tfloat_t dE = 0;\n\t\t\tfor (int u = 0; u < n; ++u) {\n\t\t\t\tfor (int w : adj[u]) {\n\t\t\t\t\tif (u == v || w == v || w < u) continue;\n\t\t\t\t\tdE += 1 / fmax(_mind, _segsqdist(u, w, v));\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int u : adj[v]) {\n\t\t\t\tfor (int w = 0; w < n; ++w) {\n\t\t\t\t\tif (v == w || u == w) continue;\n\t\t\t\t\tdE += 1 / fmax(_mind, _segsqdist(v, u, w));\n//\t\t\t\t\tstd::cerr << \"DEBUG \" << _segsqdist(v, u, w) << \"\\n\";\n//\t\t\t\t\tstd::cerr << \"DEBUG \" << _segsqdist(u, v, w) << \"\\n\";\n//\t\t\t\t\tstd::cerr << \"====\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t_ce += c * _cw * dE;\n\t\t}\n\t}\n};\n\nfloat_t transition_probability(float_t dE, float_t T) {\n\t// here dE must be positive\n\treturn exp(-dE / T);\n}\n\nvoid print_layout(const GraphLayout &layout) {\n\tfor (int i = 0; i < layout.n; ++i) {\n\t\tstd::cout << layout.layout[i].x << \" \" << layout.layout[i].y << \";\";\n\t}\n\tstd::cout\n\t\t<< layout.getNodeDistEnergy() << \";\" << layout.getBorderEnergy()\n\t\t<< \";\" << layout.getEdgesEnergy() << \";\" << layout.getCrossingsEnergy() << \"\\n\";\n}\n\ntemplate<typename RNG>\nvoid simulate_annealing(\n\t\tGraphLayout &layout, int iters, float_t startT,\n\t\tfloat_t dT, bool fine_tune, RNG &rng, bool verbose\n) {\n\tstd::uniform_int_distribution<int> vdis(0, layout.n - 1);\n\tstd::uniform_real_distribution<float_t> pdis(0, 1);\n\n\tauto curS = static_cast<float_t>(hypotl(layout.W, layout.H) / 2);\n\tauto dS = static_cast<float_t>(powl(0.001, (float_t) 1.0 / iters));\n\tfloat_t temp = startT;\n\n\tif (fine_tune) {\n\t\tcurS = static_cast<float_t>(hypotl(layout.W, layout.H) / 300);\n\t\tdS = 1.0;\n\t}\n\n\tprint_layout(layout);\n\tfor (int i = 0; i < iters; ++i) {\n\t\tint v = vdis(rng);\n\t\tPoint d{};\n\t\td.x = (2 * std::generate_canonical<float_t, 1, RNG>(rng) - 1) * curS;\n\t\td.y = (2 * std::generate_canonical<float_t, 1, RNG>(rng) - 1) * curS;\n\t\tfloat_t was_energy = layout.getEnergy();\n\t\tif (verbose) {\n\t\t\tstd::cerr << \"Iteration #\" << i << \": E=\" << was_energy << \" T=\" << temp << std::endl;\n\t\t\tstd::cerr << \"ne=\" << layout.getNodeDistEnergy();\n\t\t\tstd::cerr << \" be=\" << layout.getBorderEnergy();\n\t\t\tstd::cerr << \" ee=\" << layout.getEdgesEnergy();\n\t\t\tstd::cerr << \" ce=\" << layout.getCrossingsEnergy() << std::endl;\n\t\t}\n\t\tlayout.move(v, d);\n\t\tfloat_t new_energy = layout.getEnergy();\n\t\tif (\n\t\t\t\t(fine_tune && new_energy > was_energy) ||\n\t\t\t\t(new_energy > was_energy &&\n\t\t\t\t\tpdis(rng) > transition_probability(new_energy - was_energy, temp)\n\t\t\t\t)\n\t\t) {\n\t\t\tlayout.undoMove(v, d);\n\t\t\tif (verbose) {\n\t\t\t\tstd::cerr\n\t\t\t\t\t<< \"undo occured (dE=\" << new_energy - was_energy\n\t\t\t\t\t<< \", T=\" << temp << \") prob=\"\n\t\t\t\t\t<< 1 - transition_probability(new_energy - was_energy, temp) << \")\\n\";\n\t\t\t}\n\t\t}\n\t\ttemp *= dT;\n\t\tcurS *= dS;\n\t\tprint_layout(layout);\n\t}\n}\n\nint main(int argc, char **argv) {\n\tfreopen(\"graph.txt\", \"r\", stdin);\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t\t(\"help\", \"show usage\")\n\t\t(\"nodes\", po::value<float_t>(), \"weight of even node distribution in energy\")\n\t\t(\"edges\", po::value<float_t>(), \"weight of length of edges in energy\")\n\t\t(\"border\", po::value<float_t>(), \"weight of proximity to borderline in energy\")\n\t\t(\"cross\", po::value<float_t>(), \"weight of crossings in energy\")\n\t\t(\"cross-threshold\", po::value<float_t>(), \"minimum distance value for node edge interaction\")\n\t\t(\"startT\", po::value<float_t>(), \"statring temperature\")\n\t\t(\"cooling\", po::value<float_t>(), \"schedule of temperature reduction\")\n\t\t(\"rounds\", po::value<int>(), \"number of rounds of annealing\")\n\t\t(\"width\", po::value<float_t>(), \"width of canvas\")\n\t\t(\"height\", po::value<float_t>(), \"height of canvas\")\n\t\t(\"starting-layout\", po::value<std::string>(), \"path to starting layout file (if omitted, random one is used)\")\n\t\t(\"seed\", po::value<int>(), \"random seed\")\n\t\t(\"fine-tune\", \"flag to enable local search (used for fine tuning)\")\n\t\t(\"verbose\", \"verbose mode\");\n\tpo::variables_map varmap;\n\tpo::store(po::parse_command_line(argc, argv, desc), varmap);\n\tpo::notify(varmap);\n\n\tif (varmap.count(\"help\")) {\n\t\tstd::cout << desc << std::endl;\n\t\treturn 0;\n\t}\n\n\tbool failed = false;\n\tfor (const auto &s: {\"nodes\", \"edges\", \"border\", \"startT\", \"cooling\", \"rounds\", \"width\", \"height\"}) {\n\t\tif (!varmap.count(s)) {\n\t\t\tstd::cerr << \"Option --\" << s << \" is required\" << std::endl;\n\t\t\tfailed = true;\n\t\t}\n\t}\n\tif (failed) {\n\t\tstd::cout << desc << std::endl;\n\t\treturn 1;\n\t}\n\n\tint n, m;\n\tstd::cin >> n >> m;\n\tGraphLayout layout(\n\t\t\tn,\n\t\t\tvarmap[\"nodes\"].as<float_t>(),\n\t\t\tvarmap[\"border\"].as<float_t>(),\n\t\t\tvarmap[\"edges\"].as<float_t>(),\n\t\t\t(varmap.count(\"cross\") ? varmap[\"cross\"].as<float_t>() : 0),\n\t\t\t(varmap.count(\"cross-threshold\") ? varmap[\"cross-threshold\"].as<float_t>() : 1),\n\t\t\tvarmap[\"width\"].as<float_t>(),\n\t\t\tvarmap[\"height\"].as<float_t>()\n\t);\n\tfor (int i = 0; i < m; ++i) {\n\t\tint from, to;\n\t\tstd::cin >> from >> to;\n\t\tlayout.addEdge(from, to);\n\t}\n\n\tstd::vector<Point> start;\n\tif (varmap.count(\"starting-layout\")) {\n\t\tstd::ifstream start_file(varmap[\"starting-layout\"].as<std::string>());\n\t\tstd::string s, last;\n\t\twhile (std::getline(start_file, s)) {\n\t\t\tlast = s;\n\t\t}\n\t\tstd::istringstream ss(last);\n\t\tstart.resize(static_cast<unsigned long>(n));\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tchar sep;\n\t\t\tss >> start[i].x >> start[i].y >> sep;\n\t\t}\n\t}\n\tstd::mt19937 rng(varmap.count(\"seed\") ? varmap[\"seed\"].as<int>() : 0);\n\tlayout.initialize_positions(start, rng);\n\n\tsimulate_annealing(\n\t\t\tlayout, varmap[\"rounds\"].as<int>(),\n\t\t\tvarmap[\"startT\"].as<float_t>(), varmap[\"cooling\"].as<float_t>(),\n\t\t\tstatic_cast<bool>(varmap.count(\"fine-tune\")), rng,\n\t\t\tstatic_cast<bool>(varmap.count(\"verbose\"))\n\t);\n}\n", "meta": {"hexsha": "add2f2149e052fe6bc345c20d363c1e46c0be322", "size": 10182, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main.cc", "max_stars_repo_name": "Skird/graph-annealing", "max_stars_repo_head_hexsha": "380ce0757eab18f79df54b61f99c928f9ce795e9", "max_stars_repo_licenses": ["MIT"], "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": "Skird/graph-annealing", "max_issues_repo_head_hexsha": "380ce0757eab18f79df54b61f99c928f9ce795e9", "max_issues_repo_licenses": ["MIT"], "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": "Skird/graph-annealing", "max_forks_repo_head_hexsha": "380ce0757eab18f79df54b61f99c928f9ce795e9", "max_forks_repo_licenses": ["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.9744897959, "max_line_length": 112, "alphanum_fraction": 0.5791593007, "num_tokens": 3507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5142944674551428}}
{"text": "/* ModelReduction.cpp\n * -*- coding: utf-8 -*-\n *\n */\n\n#include <boost/test/unit_test.hpp>\n\n#include <string>\n#include <stdexcept>\n\n#include <boost/filesystem.hpp>\n\n#include <Eigen/Dense>\n\n// local includes ==============================================================\n\n#include \"../src/FileFactory.hpp\"\n#include \"../src/ModelReduction.hpp\"\n#include \"../src/ReductionFile.hpp\"\n#include \"../src/NormalModeMeanSquareFluctuationCalculator.hpp\"\n#include \"../src/Atom.hpp\"\n#include \"../src/Residuum.hpp\"\n\n#include \"utils/test.hpp\"\n#include \"utils/file.hpp\"\n#include \"utils/definitions.hpp\"\n#include \"utils/log.hpp\"\n\nclass MockedNormalModeMeanSquareFluctuationCalculator : public NormalModeMeanSquareFluctuationCalculator {\npublic:\n    MockedNormalModeMeanSquareFluctuationCalculator(const std::vector<Residuum> & residues) : NormalModeMeanSquareFluctuationCalculator(residues) {\n\n    };\n    void reduce_model(const ModelReduction & model_reduction, const Eigen::MatrixXd & hessian_matrix) {\n        this->hessian_matrix = hessian_matrix;\n        calculate_model_reduction(model_reduction);\n    };\n\n    double get_mass() const {\n        double sum_of_mass = 0;\n        for(int i = 0; i < this->mass.size(); ++i) {\n            sum_of_mass += this->mass(i);\n        }\n        return sum_of_mass;\n    };\n};\n\nBOOST_AUTO_TEST_SUITE(reduce_matrix)\n\n    struct Setup {\n        Setup() { factory = ReductionFileFactory(); }\n\n        ReductionFileFactory factory;\n\n        std::string test_file_dir = \"test/resources/mat_reduce/\";\n    };\n\n    int get_dimension_from_path(std::string path) {\n        std::string filename = boost::filesystem::path(path).filename().string();\n\n        size_t first_  = filename.find('_') + 1;\n        size_t second_ = filename.find('_', first_);\n\n        try {\n            return std::stoi(filename.substr(first_, second_ - first_)) * 3;\n        } catch (std::invalid_argument & e) {\n            TEST_MESSAGE(\"ERROR: failed to get dimension from filename: \" + filename);\n            BOOST_REQUIRE(false);\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(calculate_model_reduction_test) {\n        TEST_MESSAGE(\"calculate_model_reduction_test\");\n\n        Setup s;\n\n        std::vector<Residuum> residues(0);\n        std::vector<Atom> atoms_in_residuum_1;\n        atoms_in_residuum_1.push_back(Atom(0, 0, 0, \"C\", 0, 0));\n        atoms_in_residuum_1.push_back(Atom(0, 0, 0, \"O\", 0, 0));\n         // mass = 28.009999999999998\n        Atom c_alpha_residuum_1(0, 0, 0, \"C\", 0, 0);\n        residues.push_back(Residuum(c_alpha_residuum_1, atoms_in_residuum_1));\n\n        std::vector<Atom> atoms_in_residuum_2;\n        atoms_in_residuum_2.push_back(Atom(0, 0, 0, \"C\", 0, 0));\n        atoms_in_residuum_2.push_back(Atom(0, 0, 0, \"O\", 0, 0));\n        atoms_in_residuum_2.push_back(Atom(0, 0, 0, \"N\", 0, 0));\n        //mass = 42.086999999999996\n        Atom c_alpha_residuum_2(0, 0, 0, \"C\", 0, 0);\n        residues.push_back(Residuum(c_alpha_residuum_2, atoms_in_residuum_2));\n\n        std::vector<Atom> atoms_in_residuum_3;\n        atoms_in_residuum_2.push_back(Atom(0, 0, 0, \"C\", 0, 0));\n        atoms_in_residuum_2.push_back(Atom(0, 0, 0, \"O\", 0, 0));\n        atoms_in_residuum_2.push_back(Atom(0, 0, 0, \"N\", 0, 0));\n        atoms_in_residuum_2.push_back(Atom(0, 0, 0, \"S\", 0, 0));\n        //mass = 74.14699999999999\n        Atom c_alpha_residuum_3(0, 0, 0, \"C\", 0, 0);\n        residues.push_back(Residuum(c_alpha_residuum_3, atoms_in_residuum_3));\n\n        Eigen::MatrixXd hessian9 = get_sym_matrix_from_file(s.test_file_dir + \"hessian_input_9.mat\", 9, ' ');\n\n        std::string path(s.test_file_dir + \"selection_2_9\");\n        MockedNormalModeMeanSquareFluctuationCalculator nmsf_calculator(residues);\n        ModelReduction reduction(s.factory.create(path, 3));\n        nmsf_calculator.reduce_model(reduction, hessian9);\n        BOOST_CHECK_EQUAL(nmsf_calculator.get_mass(), 28.009999999999998 + 42.086999999999996);\n        BOOST_CHECK_EQUAL(nmsf_calculator.get_mean_square_fluctuation().size(), 3);\n        BOOST_CHECK_EQUAL(nmsf_calculator.get_weighted_eigenvalues().size(), 6);\n        BOOST_CHECK_EQUAL(nmsf_calculator.get_hessian_matrix().size(), 6*6);\n        BOOST_CHECK_EQUAL(nmsf_calculator.get_eigenvalues().size(), 6);\n        BOOST_CHECK_EQUAL(nmsf_calculator.get_weighted_eigenvector().size(), 6);\n        BOOST_CHECK_EQUAL(nmsf_calculator.get_eigenvectors().size(), 6*6);\n\n    }\n\n    BOOST_AUTO_TEST_CASE(reduce_matrix_test) {\n        TEST_MESSAGE(\"reduce_matrix_test\");\n\n        Setup s;\n\n        // test 90x90 matrix\n        Eigen::MatrixXd hessian90 = get_sym_matrix_from_file(s.test_file_dir + \"hessian_input_90.mat\", 90, ' ');\n\n        for (std::string & path : glob(s.test_file_dir + \"selection_*_90\")) {\n            ModelReduction reduction(s.factory.create(path, 30));\n\n            // Eigen::MatrixXd expected = get_sym_matrix_from_file(path + \".hessian\", n * 3, ' ');\n            Eigen::MatrixXd expected = get_sym_matrix_from_file(path + \".hessian\",\n                                                                get_dimension_from_path(path),\n                                                                ' ');\n\n            Eigen::MatrixXd actual = reduction.reduce_hessian_matrix(hessian90);\n\n            compare_two_sym_matrices(actual, expected, PRECISION);\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(empty_reductionfile_should_leave_matrix_untouched) {\n        TEST_MESSAGE(\"empty_reductionfile_should_leave_matrix_untouched\");\n\n        Setup s;\n\n        Eigen::MatrixXd hessian90 = get_sym_matrix_from_file(s.test_file_dir + \"hessian_input_90.mat\", 90, ' ');\n\n        ModelReduction reduction;\n\n        Eigen::MatrixXd reduced_matrix = reduction.reduce_hessian_matrix(hessian90);\n\n        BOOST_REQUIRE_EQUAL(reduced_matrix, hessian90);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 fenc=utf-8\n", "meta": {"hexsha": "a0e24c4de76f0a9c4b0e69bcddd5df484068f3de", "size": 5875, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Reduction.cpp", "max_stars_repo_name": "AFriemann/LowCarb", "max_stars_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_stars_repo_licenses": ["MIT"], "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/Reduction.cpp", "max_issues_repo_name": "AFriemann/LowCarb", "max_issues_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-15T13:57:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-15T13:57:26.000Z", "max_forks_repo_path": "test/Reduction.cpp", "max_forks_repo_name": "AFriemann/LowCarb", "max_forks_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_forks_repo_licenses": ["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.4203821656, "max_line_length": 147, "alphanum_fraction": 0.653787234, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.514294454292696}}
{"text": "#ifndef MI_OPEN_GL_UTILITY_HPP\n#define MI_OPEN_GL_UTILITY_HPP 1\n#include <cassert>\n#include <vector>\n#include <Eigen/Dense>\n#if defined(__APPLE__)\n#include <OpenGL/gl.h>\n#else\n#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)\n#include <windows.h>\n#pragma comment(lib, \"opengl32.lib\")\n#endif\n#include <GL/gl.h>\n#endif\n\nnamespace mi4\n{\n        class OpenGlUtility\n        {\n        public:\n                static void lookAt ( const  Eigen::Vector3d& eye, const Eigen::Vector3d& center, const Eigen::Vector3d& up )\n                {\n                        const auto forward = ( center - eye ).normalized();\n                        const auto side = forward.cross ( up ).normalized();\n                        const auto upv  = side.cross ( forward ).normalized();\n                        std::vector<double> m ( 16, 0 );\n\n                        for ( int i = 0  ; i < 3 ; ++i ) {\n                                m[i * 4 + 0] = side[i];\n                                m[i * 4 + 1] = upv[i];\n                                m[i * 4 + 2] = -forward[i];\n                        }\n\n                        m[3 * 4 + 3] = 1.0;\n                        ::glMultMatrixd ( m.data() );\n                        ::glTranslated ( -eye.x(), -eye.y(), -eye.z() );\n                        return;\n                }\n                static void perspective ( const double fov, const double aspect, const double znear, const double zfar )\n                {\n                        assert ( znear - zfar != 0 );\n                        std::vector< double > m(16, 0); //std::array\n\n                        const double f = 1.0 / std::tan(0.5 * fov * M_PI / 180.0);\n                        m[0] = f * 1.0 / aspect;\n                        m[1 * 4 + 1] = f;\n                        m[2 * 4 + 2] = ( zfar + znear ) * 1.0 / ( znear - zfar ) ;\n                        m[2 * 4 + 3] = -1.0;\n                        m[3 * 4 + 2] =  2.0 * zfar * znear / ( znear - zfar ) ;\n                        ::glMultMatrixd ( m.data() );\n                }\n                static void ortho ( const double left, const double  right, const double  bottom, const double  top, const double znear, const double zfar )\n                {\n                        ::glOrtho ( left, right, bottom, top, znear, zfar );\n                        return;\n                }\n                static void ortho2d ( const double  left, const double  right, const double  bottom, const double  top )\n                {\n                        ::glOrtho ( left, right, bottom, top, -1, 1 );\n                        return;\n                }\n        };\n}\n#endif\n", "meta": {"hexsha": "1ea81cb1a0359bd382e66a2d00d1b1d26d2eed0c", "size": 2608, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mi4/OpenGlUtility.hpp", "max_stars_repo_name": "tmichi/mi4", "max_stars_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_stars_repo_licenses": ["MIT"], "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/mi4/OpenGlUtility.hpp", "max_issues_repo_name": "tmichi/mi4", "max_issues_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-28T02:28:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-28T03:00:24.000Z", "max_forks_repo_path": "include/mi4/OpenGlUtility.hpp", "max_forks_repo_name": "tmichi/mi4", "max_forks_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_forks_repo_licenses": ["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.1230769231, "max_line_length": 156, "alphanum_fraction": 0.4210122699, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.514294450294946}}
{"text": "\n#include <istat/istattime.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <boost/cstdint.hpp>\n#include <string.h>\n#include <time.h>\n\n\nvoid usage()\n{\n    fprintf(stderr, \"usage: random_numbers [-t] [count [average]]\\n\");\n    exit(1);\n}\n\nint main(int argc, char const *argv[])\n{\n    bool timestamp = false;\n\n    if (argc > 1 && !strcmp(argv[1], \"-t\"))\n    {\n        timestamp = true;\n        ++argv;\n        --argc;\n    }\n\n    int count = 100;\n    if (argc > 1)\n    {\n        count = atoi(argv[1]);\n        if (count < 1 || count > 1000000)\n        {\n            fprintf(stderr, \"count out of range\\n\");\n            usage();\n        }\n        argc--;\n        argv++;\n    }\n\n    int center = 100;\n    int swing = 0;\n    if (argc > 1)\n    {\n        center = atoi(argv[1]);\n        if ((center == 0 && !strcmp(argv[0], \"0\")) || (center < -1000000) || (center > 1000000))\n        {\n            fprintf(stderr, \"center is out of range\\n\");\n            usage();\n        }\n        argc--;\n        argv++;\n    }\n    if (center >= -100 && center < 100)\n    {\n        swing = 100;\n    }\n    else\n    {\n        swing = abs(center);\n    }\n    center -= swing/2;\n\n    if (argc > 1)\n    {\n        fprintf(stderr, \"unknown argument: %s\\n\", argv[1]);\n        usage();\n    }\n\n    time_t now;\n    istat::istattime(&now);\n\n    while (count > 0)\n    {\n        if (timestamp)\n        {\n            long long int i64 = (int64_t)now;\n            fprintf(stdout, \"%lld \", i64);\n            while (rand() > RAND_MAX / 2)\n            {\n                now += 1;\n            }\n        }\n        fprintf(stdout, \"%ld\\n\", (long)((double)rand() * swing / RAND_MAX + center));\n        --count;\n    }\n    return 0;\n}\n\n", "meta": {"hexsha": "dc098faa27accd4dcafa2c0353d00fafa26058eb", "size": 1706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool/random_numbers.cpp", "max_stars_repo_name": "yjpark/istatd", "max_stars_repo_head_hexsha": "859a67c4c633a9e96f3f0b990a94afa54aa20224", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tool/random_numbers.cpp", "max_issues_repo_name": "yjpark/istatd", "max_issues_repo_head_hexsha": "859a67c4c633a9e96f3f0b990a94afa54aa20224", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tool/random_numbers.cpp", "max_forks_repo_name": "yjpark/istatd", "max_forks_repo_head_hexsha": "859a67c4c633a9e96f3f0b990a94afa54aa20224", "max_forks_repo_licenses": ["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.9555555556, "max_line_length": 96, "alphanum_fraction": 0.4466588511, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5142944397159723}}
{"text": "#include \"o3.hpp\"\n#include \"sco/expr_ops.hpp\"\n#include \"sco/modeling_utils.hpp\"\n#include \"osgviewer/osgviewer.hpp\"\n#include \"trajopt/collision_checker.hpp\"\n#include \"trajopt/collision_terms.hpp\"\n#include \"trajopt/common.hpp\"\n#include \"trajopt/plot_callback.hpp\"\n#include \"trajopt/problem_description.hpp\"\n#include \"trajopt/rave_utils.hpp\"\n#include \"trajopt/trajectory_costs.hpp\"\n#include \"utils/clock.hpp\"\n#include \"utils/config.hpp\"\n#include \"utils/eigen_conversions.hpp\"\n#include \"utils/stl_to_string.hpp\"\n#include <boost/assign.hpp>\n#include <boost/foreach.hpp>\n#include <ctime>\n#include <openrave-core.h>\n#include <openrave/openrave.h>\n\nusing namespace trajopt;\nusing namespace std;\nusing namespace OpenRAVE;\nusing namespace util;\nusing namespace boost::assign;\nusing namespace Eigen;\n\n\n\nstruct NeedleError : public VectorOfVector {\n  ConfigurationPtr cfg0, cfg1;\n  double radius;\n  KinBodyPtr body;\n  NeedleError(ConfigurationPtr cfg0, ConfigurationPtr cfg1, double radius) : cfg0(cfg0), cfg1(cfg1), radius(radius), body(cfg0->GetBodies()[0]) {}\n  VectorXd operator()(const VectorXd& a) const {\n    cfg0->SetDOFValues(toDblVec(a.topRows(6)));\n    OR::Transform Tw0 = body->GetTransform();\n    cfg1->SetDOFValues(toDblVec(a.middleRows(6,6)));\n    OR::Transform Tw1 = body->GetTransform();\n    double theta = a(12);\n    OR::Transform Ttarg0(OR::geometry::quatFromAxisAngle(OR::Vector(0,0,1), theta),\n        OR::Vector(radius*sin(theta), radius*(1-cos(theta)),0));\n        \n    OR::Transform Ttargw = Tw0 * Ttarg0;\n    OR::Vector position_errA = Ttargw.trans - Tw1.trans;\n    OR::Vector ori_err = Ttargw * OR::Vector(1,0,0) - Tw1 * OR::Vector(1,0,0);\n    return concat(toVector3d(position_errA), toVector3d(ori_err));\n\n  }\n};\n\n\n\n\nstruct TrajPlotter1 {\n  vector<IncrementalRBPtr> rbs;\n  VarArray vars;\n  OSGViewerPtr viewer;\n  TrajPlotter1(const vector<IncrementalRBPtr>& rbs, const VarArray& vars);\n  void OptimizerCallback(OptProb*, DblVec& x);\n\n};\n\nTrajPlotter1::TrajPlotter1(const vector<IncrementalRBPtr>& rbs, const VarArray& vars) : rbs(rbs), vars(vars) {\n  viewer = OSGViewer::GetOrCreate(rbs[0]->GetEnv());\n}\nvoid TrajPlotter1::OptimizerCallback(OptProb*, DblVec& x) {\n  vector<GraphHandlePtr> handles;\n  vector<KinBodyPtr> bodies = rbs[0]->GetBodies();\n  MatrixXd traj = getTraj(x,vars);\n  for (int i=0; i < traj.rows(); ++i) {\n    rbs[i]->SetDOFValues(toDblVec(traj.row(i)));\n    BOOST_FOREACH(const KinBodyPtr& body, bodies) {\n      handles.push_back(viewer->PlotKinBody(body));\n      SetTransparency(handles.back(), .35);\n    }\n  }\n  viewer->Idle();\n}  \n\n\n\nint main(int argc, char** argv)\n{\n  bool plotting=false, verbose=false;\n\n  {\n    Config config;\n    config.add(new Parameter<bool>(\"plotting\", &plotting, \"plotting\"));\n    config.add(new Parameter<bool>(\"verbose\", &verbose, \"verbose\"));\n    CommandParser parser(config);\n    parser.read(argc, argv);\n  }\n\n  RaveInitialize(false, verbose ? Level_Debug : Level_Info);\n  EnvironmentBasePtr env = RaveCreateEnvironment();\n  env->StopSimulation();\n  OSGViewerPtr viewer = OSGViewer::GetOrCreate(env);\n  assert(viewer);\n\n  env->Load(string(DATA_DIR) + \"/needleprob.env.xml\");\n  RobotBasePtr robot = GetRobot(*env);\n\n  int n_steps = 19;\n  int n_dof = 6;\n\n\n\n  OptProbPtr prob(new OptProb());\n  VarArray trajvars;\n  AddVarArray(*prob, n_steps, n_dof, \"j\", trajvars);\n\n\n  O3Helper helper(robot, trajvars.block(0,3,n_steps,3));\n  \n  double radius = 1; // turning radius for needle\n  VectorXd start(n_dof); start << 0,0,0,0,0,0;\n  VectorXd goal(n_dof); goal <<  4,.25,0, 0,0,0;\n\n  VectorXd vel_coeffs = VectorXd::Ones(3);\n  prob->addCost(CostPtr(new JointVelCost(trajvars.block(0,0,n_steps, 3), vel_coeffs)));\n\n  helper.AddAngVelCosts(*prob, vel_coeffs[0]);\n\n  double dtheta_lb = (goal.topRows(3) - start.topRows(3)).norm() / (n_steps-1)/radius;\n  Var dthetavar = prob->createVariables(singleton<string>(\"speed\"), singleton<double>(dtheta_lb),singleton<double>(INFINITY))[0];\n\n  for (int i=0; i < n_steps-1; ++i) {\n    VarVector vars0 = trajvars.row(i), vars1 = trajvars.row(i+1);\n    VectorOfVectorPtr f(new NeedleError(helper.m_rbs[i], helper.m_rbs[i+1], radius));\n    VectorXd coeffs = VectorXd::Ones(6);\n    VarVector vars = concat(vars0, vars1);  \n    vars.push_back(dthetavar);\n    prob->addConstraint(ConstraintPtr(new ConstraintFromFunc(f, vars, coeffs, EQ, (boost::format(\"needle%i\")%i).str())));\n  }\n\n\n  for (int j=0; j < n_dof; ++j) {\n    prob->addLinearConstraint(exprSub(AffExpr(trajvars(0,j)), start[j]), EQ);\n  }\n  for (int j=0; j < 3; ++j) { // NO orientation constraint\n    prob->addLinearConstraint(exprSub(AffExpr(trajvars(n_steps-1,j)), goal[j]), EQ);\n  }\n  \n\n  BasicTrustRegionSQP opt(prob);\n  helper.ConfigureOptimizer(opt);\n  opt.max_iter_ = 500;    \n\n  boost::shared_ptr<TrajPlotter1> plotter;\n  if (plotting) {\n    plotter.reset(new TrajPlotter1(helper.m_rbs, trajvars));\n    opt.addCallback(boost::bind(&TrajPlotter1::OptimizerCallback, boost::ref(plotter), _1, _2));\n  }\n\n  MatrixXd initTraj(n_steps, n_dof);  \n  for (int idof = 0; idof < n_dof; ++idof) {\n    initTraj.col(idof) = VectorXd::LinSpaced(n_steps, start[idof], goal[idof]);\n  }\n  DblVec initVec = trajToDblVec(initTraj);\n  initVec.push_back(dtheta_lb);\n  opt.initialize(initVec);\n  \n  opt.optimize();\n\n\n\n  RaveDestroy();\n\n\n}\n", "meta": {"hexsha": "2af544a849071883a01f48552ecbe01d4a945e0a", "size": 5274, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sandbox/needle_steering.cpp", "max_stars_repo_name": "HARPLab/trajopt", "max_stars_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 250.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T04:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T15:52:54.000Z", "max_issues_repo_path": "src/sandbox/needle_steering.cpp", "max_issues_repo_name": "HARPLab/trajopt", "max_issues_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2015-08-19T13:14:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T08:08:26.000Z", "max_forks_repo_path": "src/sandbox/needle_steering.cpp", "max_forks_repo_name": "HARPLab/trajopt", "max_forks_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 118.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T16:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T11:44:00.000Z", "avg_line_length": 30.4855491329, "max_line_length": 146, "alphanum_fraction": 0.6981418278, "num_tokens": 1588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5142119680707781}}
{"text": "#include <gtest/gtest.h>\n#include <qi/anymodule.hpp>\n#include <qi/geometry/geometry.hpp>\n#include <qi/application.hpp>\n#include <boost/math/constants/constants.hpp>\n\nusing namespace qi::geometry;\n\nclass GeometryModuleTest : public ::testing::Test{\npublic:\n  qi::AnyModule gm = qi::import(\"geometry_module\");\n};\n\nTEST_F(GeometryModuleTest, makeVector3) {\n  auto v3 = gm.call<Vector3>(\"makeVector3\", 1., 2., 3.);\n  EXPECT_EQ(1., v3.x);\n  EXPECT_EQ(2., v3.y);\n  EXPECT_EQ(3., v3.z);\n}\n\nTEST_F(GeometryModuleTest, makeQuaternion) {\n  auto q = gm.call<Quaternion>(\"makeQuaternion\", 1., 2., 3., 4.);\n  EXPECT_EQ(1., q.x);\n  EXPECT_EQ(2., q.y);\n  EXPECT_EQ(3., q.z);\n  EXPECT_EQ(4., q.w);\n\n  auto n = gm.call<double>(\"norm\", q);\n  EXPECT_DOUBLE_EQ(sqrt(1. + 4. + 9. + 16.), n);\n\n  auto qn = gm.call<Quaternion>(\"normalized\", q);\n  EXPECT_DOUBLE_EQ(q.x/n, qn.x);\n  EXPECT_DOUBLE_EQ(q.y/n, qn.y);\n  EXPECT_DOUBLE_EQ(q.z/n, qn.z);\n  EXPECT_DOUBLE_EQ(q.w/n, qn.w);\n}\n\nTEST_F(GeometryModuleTest, makeQuaternionFromAngleAxis) {\n  auto axis = gm.call<Vector3>(\"makeVector3\", 1., 1., 1.);\n  auto norm = sqrt(3.);\n\n  auto angle = 2 * boost::math::constants::pi<double>()/3;\n  auto sin_ha = sin(angle/2);\n  auto cos_ha = cos(angle/2);\n  auto q = gm.call<Quaternion>(\"makeQuaternionFromAngleAxis\", angle, axis);\n  EXPECT_DOUBLE_EQ(sin_ha * axis.x/norm, q.x);\n  EXPECT_DOUBLE_EQ(sin_ha * axis.y/norm, q.y);\n  EXPECT_DOUBLE_EQ(sin_ha * axis.z/norm, q.z);\n  EXPECT_DOUBLE_EQ(cos_ha, q.w);\n\n  EXPECT_DOUBLE_EQ(1., gm.call<double>(\"norm\", q));\n}\n\n// TODO: duplicate this test using quaternion which is not normalized\nTEST_F(GeometryModuleTest, transform) {\n\n  auto rotation = gm.call<Quaternion>(\"makeQuaternion\", 0.5, 0.5, 0.5, 0.5);\n  auto translation = gm.call<Vector3>(\"makeVector3\", 1., 2., 3.);\n  auto transform = gm.call<Transform>(\"makeTransform\", rotation, translation);\n\n  EXPECT_EQ(rotation.x, transform.rotation.x);\n  EXPECT_EQ(rotation.y, transform.rotation.y);\n  EXPECT_EQ(rotation.z, transform.rotation.z);\n  EXPECT_EQ(rotation.w, transform.rotation.w);\n  EXPECT_EQ(translation.x, transform.translation.x);\n  EXPECT_EQ(translation.y, transform.translation.y);\n  EXPECT_EQ(translation.z, transform.translation.z);\n\n  auto inv_transform = gm.call<Transform>(\"inverse\", transform);\n  auto id_transform = gm.call<Transform>(\"multiply\", transform, inv_transform);\n\n  // id_transform should be the identity\n  EXPECT_DOUBLE_EQ(0., id_transform.rotation.x);\n  EXPECT_DOUBLE_EQ(0., id_transform.rotation.y);\n  EXPECT_DOUBLE_EQ(0., id_transform.rotation.z);\n  EXPECT_TRUE((id_transform.rotation.w == 1.) ||\n              (id_transform.rotation.w == -1.));\n  EXPECT_DOUBLE_EQ(0., id_transform.translation.x);\n  EXPECT_DOUBLE_EQ(0., id_transform.translation.y);\n  EXPECT_DOUBLE_EQ(0., id_transform.translation.z);\n}\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  qi::Application app(argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "37f4e4ee1ff64b0ad98e1498369d77350637ebbc", "size": 2936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geometry_module/test/test_geometry_module.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": "geometry_module/test/test_geometry_module.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": "geometry_module/test/test_geometry_module.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": 33.3636363636, "max_line_length": 79, "alphanum_fraction": 0.7012942779, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5142119626186308}}
{"text": "/*\n * Copyright (c) 2020 Intel Corporation\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 * @file scurve_planner.hpp\n *\n * Maintainer: Yu Yan <yu.yan@intel.com>\n *\n */\n\n#pragma once\n\n#include <RTmotion/global.hpp>\n#include <stdlib.h>\n#include <math.h>\n#include <algorithm>\n#include <Eigen/Core>\n#include <map>\n#include <RTmotion/algorithm/math_utils.hpp>\n\nusing RTmotion::MC_ERROR_CODE;\n\ntypedef enum {\n  POSITION_ID = 0,\n  SPEED_ID = 1,\n  ACCELERATION_ID = 2,\n  JERK_ID = 3\n} WaypointIndex;\n\nnamespace trajectory_processing\n{\nstruct ScurveCondition\n{\n  // Condition inputs for planner\n  double q0 = 0.0;\n  double q1 = 0.0;\n  double v0 = 0.0;\n  double v1 = 0.0;\n  double a0 = 0.0;\n  double a1 = 0.0;\n  double v_max = 0.0;\n  double a_max = 0.0;\n  double j_max = 0.0;\n};\n\nstruct ScurveProfile\n{\n  // Time domains for offline scurve planning results\n  double Tj1 = 0.0;\n  double Ta = 0.0;\n  double Tj2 = 0.0;\n  double Tv = 0.0;\n  // Time domains for online scurve planning results\n  double Tj2a = 0.0;\n  double Tj2c = 0.0;\n  double Tj2b = 0.0;\n  double Td = 0.0;\n  double Th = 0.0;\n};\n\nclass ScurvePlanner\n{\npublic:\n  ScurvePlanner() = default;\n  ~ScurvePlanner() = default;\n\n  /**\n   * @brief Sign transforms for being able to calculate trajectory with q1 < q0.\n   *        Look at 'Trajectory planning for automatic machines and\n   * robots(2008)'\n   * @param condition  The input scurve condition, i.e. q0, q1, v0, v1, v_max,\n   * a_max, j_max\n   */\n  void signTransforms(ScurveCondition& condition);\n\n  /**\n   * @brief Transforms point back to the original sign.\n   * @param p Reference to Point, i.e. acc, vel, pos\n   */\n  void pointSignTransform(Eigen::Vector4d& p);\n\n  virtual MC_ERROR_CODE plan() = 0;\n  virtual Eigen::Vector4d getWaypoint(double t) = 0;\n\n  ScurveProfile profile_;\n  ScurveCondition condition_;\n  double s_ = 0.0;  // Sign transform flag parameter\n};\n\n}  // namespace trajectory_processing", "meta": {"hexsha": "dfe2fe2e7b21d9a93714ebd4171f0b1ba844cda0", "size": 2429, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/RTmotion/algorithm/scurve_planner.hpp", "max_stars_repo_name": "trigrass2/plcopen_motion_control", "max_stars_repo_head_hexsha": "547fdf833613eb4022dcf6258ed8a67fb83f028a", "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/RTmotion/algorithm/scurve_planner.hpp", "max_issues_repo_name": "trigrass2/plcopen_motion_control", "max_issues_repo_head_hexsha": "547fdf833613eb4022dcf6258ed8a67fb83f028a", "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/RTmotion/algorithm/scurve_planner.hpp", "max_forks_repo_name": "trigrass2/plcopen_motion_control", "max_forks_repo_head_hexsha": "547fdf833613eb4022dcf6258ed8a67fb83f028a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-24T10:21:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T10:21:56.000Z", "avg_line_length": 23.8137254902, "max_line_length": 80, "alphanum_fraction": 0.689584191, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5142119618853197}}
{"text": "// ~/xlin/gsl/testminsky.cc\n// 150924 003 Task now -> grid\n// Basert p\u00e5 150921 001 testminskyall.cc\n// Unified source for (74) and (77) variants\n//\n// Todo:  Endre kappa def til arctan ? (se:'destabilizing..') \n//           \n\n// GSL Manual 26.6\n//  http://stackoverflow.com/questions/27913858/how-to-consult-gsl-ode-with-many-parameters-and-harmonic-functions\n// http://www.tutorialspoint.com/matlab/matlab_differential.htm\n// L\u00f8ser differentialene vha octave-symbolic se ~/xoct/minsky/differentiate.\n// Transformerer octave-l\u00f8sningene til c++ (e)^ -> exp() og x^y -> pow(x,y)\n// se testdiff.cpp i ~/xlin/cpp/scratch\n// rk8 bruker ikke jac fjernet f.o.m versjon 014\n//\n#include <stdio.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_odeiv2.h>\n\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip> // setiosflags(ios::fixed)\n#include <limits>\n#include <map>\n#include <string>\n#include <sstream>\n#include <vector>\n\n#include <boost/array.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/foreach.hpp>\n#include <unistd.h>\n\nusing namespace std;\n\n// Warn about use of deprecated functions.\n#define GNUPLOT_DEPRECATE_WARN\n#include \"gnuplot-iostream.h\"\n\n#ifndef M_PI\n#       define M_PI 3.14159265358979323846\n#endif\n\ninline void mysleep(unsigned millis){\n  ::usleep(millis * 1000);\n}\n\n//http://stackoverflow.com/questions/7248627/setting-width-in-c-output-stream:\nclass formatted_output\n{\nprivate:\n  int width, precision;\n  std::ostream& stream_obj;\npublic:\n  formatted_output(std::ostream& obj, int w, int p): width(w), precision(p),stream_obj(obj) {}\n  template<typename T>\n  formatted_output& operator<<(const T& output)  {\n    stream_obj << std::fixed << std::setw(width) << std::setprecision(precision) << output;\n    return *this;\n  }\n  formatted_output& operator<<(std::ostream& (*func)(std::ostream&))  {\n    func(stream_obj);\n    return *this;\n  }\n};\n\nstruct param_type {\n  int eqset;\n  double alfa;\n  double beta;\n  double delta;\n  double nu;\n  double r;\n  double k1;\n  double k2; \n  double k3;\n  double k4;\n  double k5;\n  double k6;\n  double k7;\n  double k8;\n} ;\n\ndouble kappa(double k1, double k2, double k3, double profit){\n  double response;\n  response = k1 + exp(k2) * exp( k3 * profit);\n  return response;\n}  \n\n\ndouble phi(double k4, double empshare){\n  double response;\n  response = (pow(k4,3)/(1.0-pow(k4,2)))/pow((1.0 - empshare),2) - k4/(1.0-pow(k4,2));\n  return response;\n}\n\n\ndouble psi(double k5, double k6, double k7, double k8, double growthrate){\n  double response;\n  response = k5 + k6* exp(k7)*exp(k8 * growthrate);\n  return response;\n}\n\nint func (double t, const double y[], double f[],\n           void *params)\n     {\n       struct param_type *my_params_pointer = (param_type*) params;\n        int eqset     = my_params_pointer->eqset;\n\tdouble alfa   = my_params_pointer->alfa;\n\tdouble beta   = my_params_pointer->beta;\n\tdouble delta  = my_params_pointer->delta;\n\tdouble nu     = my_params_pointer->nu;\n\tdouble r      = my_params_pointer->r;\n\tdouble k1     = my_params_pointer->k1;\n\tdouble k2     = my_params_pointer->k2;\n\tdouble k3     = my_params_pointer->k3;\n\tdouble k4     = my_params_pointer->k4;\n\tdouble k5     = my_params_pointer->k5;\n\tdouble k6     = my_params_pointer->k6;\n\tdouble k7     = my_params_pointer->k7;\n\tdouble k8     = my_params_pointer->k8;\n\n        if (eqset == 74) {\n\t  f[0] =  y[0] * ( phi(k4, y[1]) - alfa) ;\n\t  f[1] =  y[1] * ( kappa(k1, k2, k3, 1 - y[0] - r * y[2]) /nu  - alfa - beta -delta);\n\t  f[2] =  y[2] * ( r -  kappa(k1, k2, k3, 1 - y[0] - r* y[2])/nu + delta) + kappa(k1, k2, k3,1 - y[0] - r * y[2]) - (1 - y[0]) + y[3];\n\t  f[3] =  y[3] * ( psi(k5, k6, k7, k8, kappa(k1, k2, k3, 1 - y[0] -r*y[2]) / nu  - delta) + kappa(k1, k2, k3, 1 - y[0] - r * y[2]) / nu - delta );\n\t}\n\t\n\tif (eqset == 77) {\n\t  f[0] =  y[0] * ( phi(k4, y[1]) - alfa) ;\n\t  f[1] =  y[1] * (( kappa(k1, k2, k3, 1 - y[0] - r/( y[2] * y[3] )) /nu ) - alfa - beta -delta);\n\t  f[2] =  y[2] * ( psi(k5, k6, k7, k8, kappa(k1, k2, k3, 1 - y[0] -r/(y[2] * y[3] )) / nu - delta) - r) - ( y[2] * y[2] * ( y[3] * kappa(k1, k2, k3,1 - y[0] - r/(y[2] * y[3])) - y[3] * (1 - y[0]) + 1 ));\n\t  f[3] =  y[3] * ( -psi(k5, k6, k7, k8, ( kappa(k1, k2, k3, 1 - y[0] -r/(y[2] * y[3])) / nu ) - delta) + (kappa(k1, k2, k3, 1 - y[0] - r/( y[2] * y[3] )) / nu) - delta );\n\t}\n\n        return GSL_SUCCESS;\n     }\n\n     // fjernet - finnes i minsky.jac.cc = minsky.013.cc    \n     /*\n     int jac (double t, const double y[], double *dfdy, \n          double dfdt[], void *params)\n     {\n      return GSL_SUCCESS;\n     }\n     */\n\n\nint main(int argc, char **argv) {\n\n       if (argc < 2) {\n         std::cout << \"Usage: minsky eqset (74|77) [omega lambda d|upsilon  p|x num_steps])\" << endl;\n         exit(0);\n       }\n\n       int eqset = 74;\t \n       if (argc > 1) eqset   = atoi(argv[1]);\n       cout << eqset << endl; // CONTROL\n       if (eqset != 74 && eqset != 77) {\n         std::cout << \"eqset has to be either 74 or 77\" << endl;\n         exit(0);\n       }\n       double y[4] = { 0.0, 0.0, 0.0, 0.0 } ; \n       if (eqset == 74){\n\t //y[4] = { 0.95, 0.9, 0.0, 0.001 } ;   // omega, lambda, d, p\n\t y[0] = 0.95;\n\t y[1] = 0.9;\n\t y[2] = 0.0;\n\t y[3] = 0.001;\n       }\n       if (eqset == 77) {\n\t //y[4] = { 0.95, 0.9, 0.12, 100 } ;   // omega, lambda, upsilon, x\n\t y[0] = 0.95;\n\t y[1] = 0.9;\n\t y[2] = 0.12;\n\t y[3] = 100.0;\n\t \n       }\n       int num_steps = 100;\n         \n       if (argc > 2) y[0] = atof(argv[2]);\n       if (argc > 3) y[1] = atof(argv[3]);\n       if (argc > 4) y[2] = atof(argv[4]);\n       if (argc > 5) y[3] = atof(argv[5]);\n       if (argc > 6) num_steps = atoi(argv[6]);\n\n       Gnuplot gp1;\n       Gnuplot gp2;\n       Gnuplot gp3;\n       Gnuplot gp4;      \n\n       std::ostringstream oss;\n       oss << \"set title \\\"\";\n       for (int j = 0; j < argc; j++)\n\t { oss << argv[j] << ' '; }\n       oss << \"\\\\n\\\"\" << std::endl ;\n       std::cout << oss.str() << std::endl;\n\n       std::ofstream funkout(\"minsky.funk.out\");\n       std::ofstream varout(\"minsky.var.out\");       \n       formatted_output fout(funkout, 16, 6);\n       formatted_output vout(varout, 12, 6);              \n\n       std::vector<std::pair<double, double> > xy_pts_A; // omega\n       std::vector<std::pair<double, double> > xy_pts_B; // lambda\n       std::vector<std::pair<double, double> > xy_pts_C; // d         // upsilon\n       std::vector<std::pair<double, double> > xy_pts_D; // p         // x\n\n       std::vector<std::pair<double, double> > xy_pts_E; // p (ponzi)      \n       std::vector<std::pair<double, double> > xy_pts_F; // d (debt)\n       std::vector<std::pair<double, double> > xy_pts_G; // g (growth)\n       std::vector<std::pair<double, double> > xy_pts_Y; // Y\n\n       double alfa   = 0.025;\n       double beta   = 0.02;\n       double delta  = 0.01;\n       double nu     = 3.0;\n       double r      = 0.03;\n       double k1     = -0.0065;\n       double k2     = -5 ;\n       double k3     =  20;\n       double k4     = 0.04;\n       double k5     = -0.25;\n       double k6     = 0.25;\n       double k7     = -0.36;\n       double k8     = 12.0;\n       double growth = 0.0;\n       double Y      = 0.0;\n\n       double zphi;\n       double zkappa;\n       double zpsi;\n       \n       if (eqset == 74) {\n         growth = kappa(k1, k2, k3, 1 - y[0] - r * y[2]) / nu - delta;\n       }\n       else if (eqset == 77) {\n\t growth = kappa(k1, k2, k3, 1 - y[0] - r/( y[2] * y[3] )) / nu - delta;\n       }\n       Y = 100.0 * ( 1.0 + growth);\n       \n       struct param_type my_params = {eqset, alfa, beta, delta, nu, r, k1, k2, k3, k4, k5, k6, k7, k8 };\n\n       // gsl_odeiv2_system sys = {func, jac, 4, &my_params};\n       // http://www.physics.buffalo.edu/phy411-506/tools/gsl/ode/index.html\n       // rk8pd bruker ikke jac settes til NULL:\n       // gsl_odeiv2_system sys = {func, jac, 4, &my_params};\n       gsl_odeiv2_system sys = {func, NULL, 4, &my_params};\n       gsl_odeiv2_driver * d = \n       gsl_odeiv2_driver_alloc_y_new (&sys, gsl_odeiv2_step_rk8pd,\n\t\t\t\t\t1e-6, 1e-6, 0.0);\n       int i = 0;\n\n       double t = 0.0, t1 = 100.0;\n\n       xy_pts_A.push_back(std::make_pair(t, y[0]));             //omega\n       xy_pts_B.push_back(std::make_pair(t, y[1]));\t\t//lambda\t    \n       xy_pts_C.push_back(std::make_pair(t, y[2]));             //d|upsilon\n       xy_pts_D.push_back(std::make_pair(t, y[3]));\t\t//p|x\n       \n       if (eqset == 77) {\n\t xy_pts_E.push_back(std::make_pair(t, 1 / y[3]));         //ponzi\n\t xy_pts_F.push_back(std::make_pair(t, 1 / y[3] / y[2]));  //debt\n       }\n       xy_pts_G.push_back(std::make_pair(t, growth));           //growth\n       xy_pts_Y.push_back(std::make_pair(t, Y));                //Y\n\n       zphi   = phi(k4, y[1]);\n       if (eqset == 74) {\n\t zkappa = kappa(k1, k2, k3, 1 - y[0] - r * y[2]);\n\t zpsi   = psi(k5, k6, k7, k8, kappa(k1, k2, k3, 1 - y[0] -r * y[2]) / nu - delta);\n       }\n       if (eqset == 77) {\n\t zkappa = kappa(k1, k2, k3, 1 - y[0] - r/( y[2] * y[3] ));\n\t zpsi   = psi(k5, k6, k7, k8, kappa(k1, k2, k3, 1 - y[0] -r/(y[2] * y[3] )) / nu - delta);\n       }\n       fout << oss.str() << std::endl;\n       fout << \"t\" << \"phi\" <<\"kappa\" << \"psi\" << std::endl;\n       fout << t << zphi << zkappa << zpsi << std::endl;       \n\n       vout << oss.str() << std::endl;\n       if (eqset == 74)  {\n\t vout << \"t\" << \"omega\" <<\"lambda\" << \"d\" << \"p\" << \"growth\" << \"Y\"  << std::endl;\n\t vout << t  << y[0] << y[1] << y[2] << y[3] << growth << Y <<std::endl;       \n       }\n       if (eqset == 77) {\n \t vout << \"t\" << \"omega\" <<\"lambda\" << \"upsilon\" << \"debt\" << \"ponzi\" << \"x\" << \"growth\" << \"Y\"  << std::endl;\n\t vout << t  << y[0] << y[1] << y[2] << y[3] <<  1/y[3]/y[2] <<1/y[3] << growth << Y <<std::endl;       }\n       if (eqset == 74) {\n\t printf (\"%6s %10s %10s %10s %10s %10s %10s %10s %10s\\n\", \"t\",\"omega\",\"lambda\",\"d\",\"p\",\"\",\"\",\"growth\",\"Y\");\n\t printf (\"%6.0f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f\\n\", t, y[0], y[1], y[2], y[3], 0.0, 0.0, growth, Y);\n       }\n       if (eqset == 77) {\n         printf (\"%6s %10s %10s %10s %10s %10s %10s %10s %10s\\n\", \"t\",\"omega\",\"lambda\",\"upsilon\",\"x\",\"ponzi\",\"debt\",\"growth\",\"Y\");\n         printf (\"%6.0f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f\\n\", t, y[0], y[1], y[2], y[3], 1/y[3]/y[2], 1/y[3],growth, Y);\n       }\n\n       \n       for (i = 1; i <= num_steps; i++)\n         {\n           double ti = i * t1 / 100.0;\n           int status = gsl_odeiv2_driver_apply (d, &t, ti, y);\n           if (status != GSL_SUCCESS)\n\t     {\n\t       printf (\"error, return value=%d\\n\", status);\n\t       break;\n\t     }\n\n           //Funksjonsverdiene:\n\t   zphi   = phi(k4, y[1]);\n\t   if (eqset == 74) {\n\t     zkappa = kappa(k1, k2, k3, 1 - y[0] - r * y[2]);\n\t     zpsi   = psi(k5, k6, k7, k8, kappa(k1, k2, k3, 1 - y[0] -r *y[2]) / nu - delta);\n\t     growth = kappa(k1, k2, k3, 1 - y[0] - r* y[2]) / nu - delta;\n\t   }\n\t   if (eqset == 77) {\n\t     zkappa = kappa(k1, k2, k3, 1 - y[0] - r/( y[2] * y[3] ));\n\t     zpsi   = psi(k5, k6, k7, k8, kappa(k1, k2, k3, 1 - y[0] -r/(y[2] * y[3] )) / nu - delta);\n\t     growth = kappa(k1, k2, k3, 1 - y[0] - r/( y[2] * y[3] )) / nu - delta;\n\t   }\n\t   Y = Y * ( 1 + growth);\n\n\t   fout << t << zphi << zkappa << zpsi << std::endl;\n\t   vout << t << y[0] << y[1] << y[2] << y[3] << growth << Y <<std::endl;       \t   \n\t   if (eqset == 74) {\n\t     printf (\"%6.0f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f\\n\", t, y[0], y[1], y[2], y[3], 0.0, 0.0, growth, Y);\n\t   }\n\t   if (eqset == 77) {\n\t     printf (\"%6.0f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f\\n\", t, y[0], y[1], y[2], y[3], 1/y[3]/y[2], 1/y[3], growth, Y);\n\t   }\n \t   xy_pts_A.push_back(std::make_pair(t, y[0]));\n\t   xy_pts_B.push_back(std::make_pair(t, y[1]));\t\t\t    \n\t   xy_pts_C.push_back(std::make_pair(t, y[2]));\n\t   xy_pts_D.push_back(std::make_pair(t, y[3]));\t\t\t    \n\t   if (eqset == 77) {\n\t     xy_pts_E.push_back(std::make_pair(t, 1 / y[3]));         //ponzi\n\t     xy_pts_F.push_back(std::make_pair(t, 1 / y[3] / y[2]));  //debt\n\t   }\n\t   xy_pts_G.push_back(std::make_pair(t, growth)); //growth\n           xy_pts_Y.push_back(std::make_pair(t, Y)); //Y\n\t }\n     \n       gsl_odeiv2_driver_free (d);\n\n       // GNPLOTS:\n       if (eqset == 74){\n\t // Omega & Lambda:\n\t gp1 << \"set terminal x11 1 persist size 640,450 position 50,50\\n\";\n\t gp1 << \"set grid\\n\";\n\t gp1 << oss.str() ; // Title string\n\t gp1 << \"set ylabel 'omega lambda'\\n\";\n\t gp1 << \"plot '-' with lines title 'omega', '-' with lines title 'lambda'\\n\";\n\t gp1.send1d(xy_pts_A);\n\t gp1.send1d(xy_pts_B);\n\t // p & d:\n\t gp2 << \"set terminal x11 1 persist size 640,450 position 50,536\\n\";\n\t gp2 << \"set grid\\n\";\n\t gp2 << oss.str() ; // Title string\n\t gp2 << \"set ylabel 'p\\n\";\n\t gp2 << \"set y2label 'd'\\n\";\n\t gp2 << \"set y2tics\\n\";\n\t //gp2 << \"plot '-' with lines title 'd\\n\";\n \t gp2 << \"plot '-' with lines title 'p', '-' with lines  title 'd' axes x1y2\\n\";\n\t gp2.send1d(xy_pts_D);\n\t gp2.send1d(xy_pts_C);\n\t \n\t /*\t // p:\n\t gp3 << \"set terminal x11 1 persist size 640,450 position 690,536\\n\";\n\t gp3 << \"set grid\\n\";\n\t gp3 << oss.str() ; // Title string\n\t gp3 << \"set ylabel 'p\\n\";\n\t gp3 << \"plot '-' with lines title 'p\\n\";\n\t gp3.send1d(xy_pts_D);\n\t */\n       }\n\n       if (eqset == 77) {\n\t // Omega & Lambda & Upsilon & X:\n\t gp1 << \"set terminal x11 1 persist size 640,450 position 50,50\\n\";\n\t gp1 << \"set grid\\n\";\n\t gp1 << oss.str() ; // Title string\n\t gp1 << \"set ylabel 'omega lambda upsilon'\\n\";\n\t gp1 << \"set y2label 'x'\\n\";\n\t gp1 << \"set y2tics\\n\";\n\t gp1 << \"plot '-' with lines title 'omega', '-' with lines title 'lambda', '-' with lines title 'upsilon','-' with lines  title 'x' axes x1y2\\n\";\n\t gp1.send1d(xy_pts_A);\n\t gp1.send1d(xy_pts_B);\n\t gp1.send1d(xy_pts_C);\n\t gp1.send1d(xy_pts_D);\n\t // Ponzi & Debt: \n\t gp2 << \"set terminal x11 2 persist size 640,450 position 50,536\\n\";\n\t gp2 << \"set grid\\n\";\n\t gp2 << oss.str() ; // Title string\n\t gp2 << \"set ylabel 'ponzi'\\n\";\n\t gp2 << \"set y2label 'debt'\\n\";\n\t gp2 << \"set y2tics\\n\";\n\t gp2 << \"plot '-' with lines title 'ponzi', '-' with lines title 'debt' axes x1y2\\n\";\n\t gp2.send1d(xy_pts_E);\n\t gp2.send1d(xy_pts_F);\n       }\t\t    \n       //  p/ponzi & growth:\n       gp3 << \"set terminal x11 2 persist size 640,450 position 690,50\\n\";\n       gp3 << \"set grid\\n\";\n       gp3 << oss.str() ; // Title string\n       gp3 << \"set ylabel 'p/ponzi'\\n\";\n       gp3 << \"set y2label 'growthi'\\n\";\n       gp3 << \"set y2tics\\n\";\n       gp3 << \"plot '-' with lines title 'p/ponzi', '-' with lines title 'growth' axes x1y2\\n\";\n       if (eqset == 74) gp3.send1d(xy_pts_D);\n       if (eqset == 77) gp3.send1d(xy_pts_E);              \n       gp3.send1d(xy_pts_G);        \n\n       //  Y & d/debt:\n       gp4 << \"set terminal x11 2 persist size 640,450 position 690,536\\n\";\n       gp4 << \"set grid\\n\";\n       gp4 << oss.str() ; // Title string\n       gp4 << \"set ylabel 'Y'\\n\";\n       gp4 << \"set y2label 'd/debt'\\n\";\n       gp4 << \"set y2tics\\n\";\n       gp4 << \"plot '-' with lines title 'Y', '-' with lines title 'd/debt' axes x1y2\\n\";\n       gp4.send1d(xy_pts_Y);       \n       if (eqset == 74) gp4.send1d(xy_pts_C);\n       if (eqset == 77) gp4.send1d(xy_pts_F);              \n\n       return 0;    \n     }\n\n// EOF\n\n", "meta": {"hexsha": "409aded5c47b95c6ce29b9d21347fb0ec01146c7", "size": 15207, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pages/res/minsky/minsky.cc", "max_stars_repo_name": "dyrehaugen/jdt", "max_stars_repo_head_hexsha": "b1988176c6e0182976ac428b5c9e4c7e7bb1248a", "max_stars_repo_licenses": ["MIT", "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": "pages/res/minsky/minsky.cc", "max_issues_repo_name": "dyrehaugen/jdt", "max_issues_repo_head_hexsha": "b1988176c6e0182976ac428b5c9e4c7e7bb1248a", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-05-02T09:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T20:46:04.000Z", "max_forks_repo_path": "pages/res/minsky/minsky.cc", "max_forks_repo_name": "dyrehaugen/jdt", "max_forks_repo_head_hexsha": "b1988176c6e0182976ac428b5c9e4c7e7bb1248a", "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": 34.9586206897, "max_line_length": 204, "alphanum_fraction": 0.5254816861, "num_tokens": 5682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5142119618853197}}
{"text": "\ufeff#include \"processor.h\"\n#include \"histogramutility.h\"\n#include <math.h>\n#include <algorithm>\n#include <iostream>\n#include \"boost/pending/disjoint_sets.hpp\"\n#include <boost/unordered/unordered_set.hpp>\n\nusing namespace cv;\nusing namespace std;\n\nProcessor::Processor()\n{\n}\n\nMat Processor::invert(Mat &img){\n    Mat res(img.rows, img.cols, img.type());\n\n    for (int i = 0; i < img.rows; i++){\n        for (int j = 0; j < img.cols; j++){\n            Vec3b& color = res.at<Vec3b>(Point(j, i));\n            Vec3b& color_org = img.at<Vec3b>(Point(j, i));\n\n            color[0] = 255 - color_org[0];\n            color[1] = 255 - color_org[1];\n            color[2] = 255 - color_org[2];\n        }\n    }\n    return res;\n}\n\nMat* Processor::kirsch(Mat& img){\n\n    Mat* results = new Mat[5];\n\n    Mat res_1(img.rows, img.cols, img.type());\n    Mat res_2(img.rows, img.cols, img.type());\n    Mat res_3(img.rows, img.cols, img.type());\n    Mat res_4(img.rows, img.cols, img.type());\n\n    Point anchor(1, 1);\n    double delta = 0;\n    int ddepth = -1;\n    const int filter_width = 3;\n\n    float elements_1[filter_width * filter_width] = {-1, 0, 1, -1, 0, 1, -1, 0, 1};\n    float elements_2[filter_width * filter_width] = {1, 1, 1, 0, 0, 0, -1, -1, -1};\n    float elements_3[filter_width * filter_width] = {0, 1, 1, -1, 0, 1, -1, -1, 0};\n    float elements_4[filter_width * filter_width] = {1, 1, 0, 1, 0, -1, 0, -1, -1};\n\n    Mat kernel_1(Size(filter_width, filter_width), CV_32F, elements_1);\n    filter2D(img, res_1, ddepth, kernel_1, anchor, delta, BORDER_DEFAULT);\n\n    Mat kernel_2(Size(filter_width, filter_width), CV_32F, elements_2);\n    filter2D(img, res_2, ddepth, kernel_2, anchor, delta, BORDER_DEFAULT);\n\n    Mat kernel_3(Size(filter_width, filter_width), CV_32F, elements_3);\n    filter2D(img, res_3, ddepth, kernel_3, anchor, delta, BORDER_DEFAULT);\n\n    Mat kernel_4(Size(filter_width, filter_width), CV_32F, elements_4);\n    filter2D(img, res_4, ddepth, kernel_4, anchor, delta, BORDER_DEFAULT);\n\n    Mat res(img.rows, img.cols, img.type());\n    for(int i = 0; i < img.cols; i++){\n        for(int j = 0; j < img.rows; j++){\n            Vec3b& color1 = res_1.at<Vec3b>(Point(i, j));\n            Vec3b& color2 = res_2.at<Vec3b>(Point(i, j));\n            Vec3b& color3 = res_3.at<Vec3b>(Point(i, j));\n            Vec3b& color4 = res_4.at<Vec3b>(Point(i, j));\n\n            Vec3b& color_res = res.at<Vec3b>(Point(i, j));\n\n            int max = color1[0] > color2[0] ? color1[0] : color2[0];\n            max = max > color3[0] ? max : color3[0];\n            max = max > color4[0] ? max : color4[0];\n\n            color_res[0] = max;\n            color_res[1] = max;\n            color_res[2] = max;\n        }\n    }\n\n    results[0] = res_1;\n    results[1] = res_2;\n    results[2] = res_3;\n    results[3] = res_4;\n    results[4] = res;\n\n    return results;\n}\n\nMat Processor::prewitt(Mat &img){\n    Mat res_x(img.rows, img.cols, img.type());\n    Mat res_y(img.rows, img.cols, img.type());\n\n    Point anchor(1, 1);\n    double delta = 0;\n    int ddepth = -1;\n    const int filter_width = 3;\n\n    float elements_x[filter_width * filter_width] = {-1, 0, 1, -1, 0, 1, -1, 0, 1};\n    float elements_y[filter_width * filter_width] = {-1, -1, -1, 0, 0, 0, 1, 1, 1};\n\n    Mat kernel_x(Size(filter_width, filter_width), CV_32F, elements_x);\n    filter2D(img, res_x, ddepth, kernel_x, anchor, delta, BORDER_DEFAULT);\n\n    Mat kernel_y(Size(filter_width, filter_width), CV_32F, elements_y);\n    filter2D(img, res_y, ddepth, kernel_y, anchor, delta, BORDER_DEFAULT);\n\n    Mat res(img.rows, img.cols, img.type());\n    for(int i = 0; i < img.cols; i++){\n        for(int j = 0; j < img.rows; j++){\n            Vec3b& color1 = res_x.at<Vec3b>(Point(i, j));\n            Vec3b& color2 = res_y.at<Vec3b>(Point(i, j));\n\n            Vec3b& color_res = res.at<Vec3b>(Point(i, j));\n\n            int sum = sqrt(color1[0] * color1[0] + color2[0] * color2[0]);\n\n            sum = sum > 255 ? 255:sum;\n            sum = sum < 0 ? 0 : sum;\n\n            color_res[0] = sum;\n            color_res[1] = sum;\n            color_res[2] = sum;\n        }\n    }\n\n    return res;\n}\n\nMat Processor::gaussian(Mat &img){\n    Mat res(img.rows, img.cols, img.type());\n\n    Point anchor(1, 1);\n    double delta = 0;\n    int ddepth = -1;\n    const int filter_width = 7;\n\n    float elements[filter_width * filter_width] = {0.00000067, 0.00002292, 0.00019117, 0.00038771, 0.00019117, 0.00002292, 0.00000067,\n                                                  0.00002292, 0.00078634, 0.00655965, 0.01330373, 0.00655965, 0.00078633, 0.00002292,\n                                                  0.00019117, 0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965, 0.00019117,\n                                                  0.00038771, 0.01330373, 0.11098164, 0.22508352, 0.11098164, 0.01330373, 0.00038771,\n                                                  0.00019117, 0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965, 0.00019117,\n                                                  0.00002292, 0.00078634, 0.00655965, 0.01330373, 0.00655965, 0.00078633, 0.00002292,\n                                                  0.00000067, 0.00002292, 0.00019117, 0.00038771, 0.00019117, 0.00002292, 0.00000067\n                                                  };\n\n    Mat kernel(Size(filter_width, filter_width), CV_32F, elements);\n    filter2D(img, res, ddepth, kernel, anchor, delta, BORDER_DEFAULT);\n\n    return res;\n}\n\nMat Processor::laplacian(Mat &img){\n    Mat res(img.rows, img.cols, img.type());\n\n    Point anchor(1, 1);\n    double delta = 0;\n    int ddepth = -1;\n    const int filter_width = 3;\n\n    float elements[filter_width * filter_width] = {0, 1, 0, 1, -4, 1, 0, 1, 0};\n\n    Mat kernel(Size(filter_width, filter_width), CV_32F, elements);\n    filter2D(img, res, ddepth, kernel, anchor, delta, BORDER_DEFAULT);\n\n    int filterWidth = 3;\n\n//    double **filter;\n//    filter = new double *[filterWidth];\n//    for(int i = 0; i < filterWidth; i++)\n//        filter[i] = new double[filterWidth];\n\n//    filter[0][0] = 0;\n//    filter[0][1] = -1;\n//    filter[0][2] = 0;\n\n//    filter[1][0] = -1;\n//    filter[1][1] = 4;\n//    filter[1][2] = -1;\n\n//    filter[2][0] = 0;\n//    filter[2][1] = -1;\n//    filter[2][2] = 0;\n\n//    res = apply_filter(img, filter, filterWidth);\n\n//    int min = 10000;\n//    int max = -10000;\n//    for(int i = 0; i < res.cols; i++){\n//        for(int j = 0; j < res.rows; j++){\n//            Vec3b& color_res = res.at<Vec3b>(Point(i, j));\n\n//            if (color_res[0] < min){\n//                min = color_res[0];\n//            }\n\n//            if (color_res[0] > max){\n//                max = color_res[0];\n//            }\n//        }\n//    }\n\n//    for(int i = 0; i < res.cols; i++){\n//        for(int j = 0; j < res.rows; j++){\n//            Vec3b& color_res = res.at<Vec3b>(Point(i, j));\n\n//            int sum = ((double)(color_res[0] - min) / (double)(max - min)) * 255;\n\n//            color_res[0] = sum;\n//            color_res[1] = sum;\n//            color_res[2] = sum;\n//        }\n//    }\n\n//    cout << \"Max: \" << max << endl;\n//    cout << \"Min: \" << min << endl;\n\n    for(int i = 0; i < res.cols; i++){\n        for(int j = 0; j < res.rows; j++){\n            Vec3b& color_res = res.at<Vec3b>(Point(i, j));\n\n            int sum = color_res[0] + 128;\n\n            color_res[0] = sum;\n            color_res[1] = sum;\n            color_res[2] = sum;\n        }\n    }\n\n    return res;\n}\n\nMat Processor::sobel(Mat &img){\n    Mat res_x(img.rows, img.cols, img.type());\n    Mat res_y(img.rows, img.cols, img.type());\n\n    Point anchor(1, 1);\n    double delta = 0;\n    int ddepth = -1;\n    const int filter_width = 3;\n\n    float elements_x[filter_width * filter_width] = {-1, 0, 1, -2, 0, 2, -1, 0, 1};\n    float elements_y[filter_width * filter_width] = {-1, -2, -1, 0, 0, 0, 1, 2, 1};\n\n    Mat kernel_x(Size(filter_width, filter_width), CV_32F, elements_x);\n    filter2D(img, res_x, ddepth, kernel_x, anchor, delta, BORDER_DEFAULT);\n\n    Mat kernel_y(Size(filter_width, filter_width), CV_32F, elements_y);\n    filter2D(img, res_y, ddepth, kernel_y, anchor, delta, BORDER_DEFAULT);\n\n    Mat res(img.rows, img.cols, img.type());\n    for(int i = 0; i < img.cols; i++){\n        for(int j = 0; j < img.rows; j++){\n            Vec3b& color1 = res_x.at<Vec3b>(Point(i, j));\n            Vec3b& color2 = res_y.at<Vec3b>(Point(i, j));\n\n            Vec3b& color_res = res.at<Vec3b>(Point(i, j));\n\n            int sum = sqrt(color1[0] * color1[0] + color2[0] * color2[0]);\n\n            sum = sum > 255 ? 255:sum;\n            sum = sum < 0 ? 0 : sum;\n\n            color_res[0] = sum;\n            color_res[1] = sum;\n            color_res[2] = sum;\n        }\n    }\n\n    return res;\n}\n\nMat Processor::roberts(Mat &img){\n    Mat res_x(img.rows, img.cols, img.type());\n    Mat res_y(img.rows, img.cols, img.type());\n\n    Point anchor(0, 1);\n    double delta = 0;\n    int ddepth = -1;\n    const int filter_width = 2;\n\n    float elements_x[filter_width * filter_width] = {1.0, 0.0, 0.0, -1.0};\n    float elements_y[filter_width * filter_width] = {0.0, 1.0, -1.0, 0.0};\n\n    Mat kernel_x(Size(filter_width, filter_width), CV_32F, elements_x);\n    filter2D(img, res_x, ddepth, kernel_x, anchor, delta, BORDER_DEFAULT);\n\n    Mat kernel_y(Size(filter_width, filter_width), CV_32F, elements_y);\n    filter2D(img, res_y, ddepth, kernel_y, anchor, delta, BORDER_DEFAULT);\n\n    Mat res(img.rows, img.cols, img.type());\n    for(int i = 0; i < img.cols; i++){\n        for(int j = 0; j < img.rows; j++){\n            Vec3b& color1 = res_x.at<Vec3b>(Point(i, j));\n            Vec3b& color2 = res_y.at<Vec3b>(Point(i, j));\n\n            Vec3b& color_res = res.at<Vec3b>(Point(i, j));\n\n            int sum = sqrt(color1[0] * color1[0] + color2[0] * color2[0]);\n\n            sum = sum > 255 ? 255:sum;\n            sum = sum < 0 ? 0 : sum;\n\n            color_res[0] = sum;\n            color_res[1] = sum;\n            color_res[2] = sum;\n        }\n    }\n\n    return res;\n}\n\nMat Processor::component_labeling(Mat &img, int white, int black){\n\n    img = iterative_thresholding(img);\n\n    int current_label = 0;\n\n    Mat res(img.rows, img.cols, img.type());\n\n    for (int i = 0; i < img.rows; i++){\n        for (int j = 0; j < img.cols; j++){\n            Vec3b& color = res.at<Vec3b>(Point(j, i));\n\n            color[0] = 0;\n        }\n    }\n\n    vector<int> rank(2000);\n    vector<int> parent(2000);\n    boost::disjoint_sets<int*, int*> ds(&rank[0], &parent[0]);\n    boost::unordered_set<int> labels;\n\n    for (int i = 0; i < img.rows; i++){\n        for (int j = 0; j < img.cols; j++){\n\n            Vec3b& color = img.at<Vec3b>(Point(j, i));\n            int pixel = color[0];\n\n            if (pixel == white){\n\n                int pixel_top = black;\n                if (i - 1 >= 0){\n                    pixel_top = img.at<Vec3b>(Point(j, i - 1))[0];\n                }\n\n                int pixel_left = black;\n                if (j - 1 >= 0){\n                    pixel_left = img.at<Vec3b>(Point(j - 1, i))[0];\n                }\n\n                Vec3b& res_color = res.at<Vec3b>(Point(j, i));\n                int result_v = -1;\n\n                if (pixel_left == black && pixel_top == black){\n                    current_label++;\n\n                    cout << current_label << endl;\n\n                    ds.make_set(current_label);\n                    labels.insert(current_label);\n\n                    result_v = current_label;\n                }else if (pixel_left == black && pixel_top == white){\n\n                    result_v = res.at<Vec3b>(Point(j, i - 1))[0];\n\n                }else if (pixel_left == white && pixel_top == black){\n\n                    result_v = res.at<Vec3b>(Point(j - 1, i))[0];\n\n                }else if (pixel_left == white && pixel_top == white){\n                    int left_label = res.at<Vec3b>(Point(j - 1, i))[0];\n                    int top_label = res.at<Vec3b>(Point(j, i - 1))[0];\n\n                    if (left_label != top_label){\n                        ds.union_set(left_label, top_label);\n                    }\n\n                    result_v = left_label < top_label ? left_label : top_label;\n\n                }\n\n                if (result_v == -1){\n                    cout << \"ERROR\" << endl;\n                    exit(-1);\n                }\n\n                res_color[0] = result_v;\n                res_color[1] = result_v;\n                res_color[2] = result_v;\n            }\n\n        }\n    }\n\n    ds.normalize_sets(labels.begin(), labels.end());\n    cout << \"Number of components: \" << ds.count_sets(labels.begin(), labels.end()) << endl;\n\n\n    int r[] = {0, 150, 175, 200, 225, 250, 25, 50, 75, 100, 125};\n    int g[] = {125, 150, 175, 200, 225, 250, 0, 25, 50, 75, 100};\n    int b[] = {0, 25, 50, 175, 200, 225, 150, 250, 75, 100, 125};\n\n    map<int, int> final_eq;\n    int index = 0;\n    int area = 0;\n    for (int i = 0; i < img.rows; i++){\n        for (int j = 0; j < img.cols; j++){\n            Vec3b& color = res.at<Vec3b>(Point(j, i));\n            int temp = (int)color[0];\n\n            temp = ds.find_set(temp);\n\n            if (color[0] != 0){\n                if (final_eq[temp] == 0){\n                    index++;\n                    final_eq[temp] = index;\n                }\n\n                int index = (final_eq[temp] * 13) % 11;\n\n                color[0] = r[index];\n                color[1] = g[index];\n                color[2] = b[index];\n\n                area++;\n            }else{\n                color[0] = black;\n                color[1] = black;\n                color[2] = black;\n            }\n        }\n    }\n\n    cout << \"Number of components: \" << index << endl;\n    cout << \"Average area of the components: \" << (double)(area) / index << endl;\n\n    return res;\n\n}\n\nvoid Processor::convert_to_grayscale(Mat &img){\n    for(int i = 0; i < img.cols; i++)\n    {\n        for(int j = 0; j < img.rows; j++)\n        {\n            Vec3b& color = img.at<Vec3b>(Point(i, j));\n            int r = color[0];\n            int g = color[1];\n            int b = color[2];\n            int gray_scale = 0.21 * r + 0.72 * g + 0.07 * b;\n\n            color[0] = gray_scale;\n            color[1] = gray_scale;\n            color[2] = gray_scale;\n        }\n    }\n}\n\nMat Processor::median_filter(Mat &img, int filter_w){\n    int redu = filter_w / 2;\n\n    Mat res(img.rows - redu * 2, img.cols - redu * 2, img.type());\n\n    for(int i = redu; i < res.cols - redu; i++){\n        for(int j = redu; j < res.rows - redu; j++){\n\n            vector<int> values;\n            for (int ii = 0; ii < filter_w; ii++){\n                for (int jj = 0; jj < filter_w; jj++){\n                    Vec3b& color = img.at<Vec3b>(Point(i + ii - redu, j + jj - redu));\n                    values.push_back(color[0]);\n                }\n            }\n            sort(values.begin(), values.end());\n\n            Vec3b& color = res.at<Vec3b>(Point(i, j));\n\n            int new_val = values[values.size() / 2 + 1];\n\n            color[0] = new_val;\n            color[1] = new_val;\n            color[2] = new_val;\n        }\n    }\n\n    return res;\n}\n\nMat Processor::apply_even_filter(Mat& img, double** filter, int filter_w){\n    Mat res(img.rows, img.cols, img.type());\n\n    for(int i = 0; i < res.cols; i++){\n        for(int j = 0; j < res.rows; j++){\n\n            double sum = 0;\n            for (int ii = 0; ii < filter_w; ii++){\n                for (int jj = 0; jj < filter_w; jj++){\n                    Vec3b& color = img.at<Vec3b>(Point(i + ii, j + jj));\n                    sum += (color[0] * filter[ii][jj]);\n                }\n            }\n\n            Vec3b& color = res.at<Vec3b>(Point(i, j));\n\n            color[0] = sum;\n            color[1] = sum;\n            color[2] = sum;\n        }\n    }\n\n    return res;\n}\n\nMat Processor::apply_filter(Mat& img, double** filter, int filter_w, int threshold){\n    int redu = filter_w / 2;\n\n    Mat res(img.rows - redu * 2, img.cols - redu * 2, img.type());\n\n    for(int i = redu; i < res.cols - redu; i++){\n        for(int j = redu; j < res.rows - redu; j++){\n\n            double sum = 0;\n            for (int ii = 0; ii < filter_w; ii++){\n                for (int jj = 0; jj < filter_w; jj++){\n                    Vec3b& color = img.at<Vec3b>(Point(i + ii - redu, j + jj - redu));\n                    sum += (color[0] * filter[ii][jj]);\n                }\n            }\n\n            Vec3b& color = res.at<Vec3b>(Point(i, j));\n\n            if (abs(sum - img.at<Vec3b>(Point(i, j))[0]) < threshold) {\n                color[0] = sum;\n                color[1] = sum;\n                color[2] = sum;\n            }else{\n                color[1] = color[0];\n                color[2] = color[0];\n            }\n        }\n    }\n\n    return res;\n}\n\nMat Processor::contrast_enhance(Mat& img, int lower , int higher){\n\n    int CLT[256];\n\n    for (int i = 0; i < 256; i++){\n        if (i < lower){\n            CLT[i] = 0;\n        }else if(i > higher){\n            CLT[i] = 255;\n        }else{\n            CLT[i] = (int)(((double)i - (double)lower) / ((double)higher - (double)lower) * 255);\n        }\n    }\n\n    Mat res(img.size(), img.type());\n    for(int i = 0; i < res.cols; i++){\n        for(int j = 0; j < res.rows; j++){\n            int r = img.at<Vec3b>(Point(i, j))[0];\n            Vec3b& color = res.at<Vec3b>(Point(i, j));\n\n            color[0] = CLT[r];\n            color[1] = CLT[r];\n            color[2] = CLT[r];\n        }\n    }\n\n    return res;\n}\n\nMat Processor::adaptive_thresholding(Mat& img, int num_tiles){\n    Mat res(img.size(), img.type());\n\n    for (int i = 0; i < num_tiles; i++){\n        for (int j = 0; j < num_tiles; j++){\n\n            Range rows_r(i * img.rows / num_tiles, (i + 1) * img.rows / num_tiles);\n            Range cols_r(j * img.cols / num_tiles, (j + 1) * img.cols / num_tiles);\n\n            Mat small = img(rows_r, cols_r);\n            small = iterative_thresholding(small);\n            Mat small_part = res(rows_r, cols_r);\n\n            small.copyTo(small_part);\n        }\n    }\n\n    return res;\n}\n\nMat Processor::p_tile_thresholding(Mat& img, int p_tile){\n    int* hist = new int[256];\n    HistogramUtility histUtil;\n    histUtil.getHistogram(img, hist);\n\n    int pixel_count = (int)((100 - p_tile) / 100.0 * img.cols * img.rows);\n\n    int count = 0;\n    int index = 0;\n    while(count < pixel_count){\n        count += hist[index];\n        index++;\n    }\n\n    Mat res = threshold_binary(img, index);\n    return res;\n}\n\nMat Processor::iterative_thresholding(Mat& img, int init_threshold, double diff_threshold, int max_iterations){\n\n    double diff = 256;\n    int counter = 0;\n    int current_threshold = init_threshold;\n    while (diff > diff_threshold && counter < max_iterations){\n        init_threshold = current_threshold;\n\n        double sum1 = 0;\n        double sum2 = 0;\n        int count1 = 0;\n        int count2 = 0;\n\n        for(int i = 0; i < img.cols; i++){\n            for(int j = 0; j < img.rows; j++){\n                int r = img.at<Vec3b>(Point(i, j))[0];\n\n                if (r < init_threshold){\n                    sum1 += r;\n                    count1++;\n                }else{\n                    sum2 += r;\n                    count2++;\n                }\n            }\n        }\n\n        if (count1 != 0 && count2 != 0){\n            sum1 /= count1;\n            sum2 /= count2;\n        }else{\n            if (count1 == 0){\n                sum1 = 0;\n                sum2 /= count2;\n            }else{\n                sum1 /= count1;\n                sum2 = 0;\n            }\n        }\n\n        current_threshold = (int) ((1.0 / 2.0) * (sum1 + sum2));\n        diff = abs(current_threshold - init_threshold);\n        counter++;\n    }\n\n    Mat res = threshold_binary(img, current_threshold);\n    return res;\n}\n\nMat Processor::threshold_binary(Mat &img, int threshold){\n    Mat res(img.size(), img.type());\n\n    for(int i = 0; i < res.cols; i++){\n        for(int j = 0; j < res.rows; j++){\n            int r = img.at<Vec3b>(Point(i, j))[0];\n\n            Vec3b& color = res.at<Vec3b>(Point(i, j));\n            if (r < threshold){\n                color[0] = 0;\n                color[1] = 0;\n                color[2] = 0;\n            }else{\n                color[0] = 255;\n                color[1] = 255;\n                color[2] = 255;\n            }\n        }\n    }\n\n    return res;\n}\n\nMat* Processor::slicing_threshold(Mat& img, int number_of_slices){\n    HistogramUtility histUtil;\n    int* hist = new int[256];\n    histUtil.getHistogram(img, hist);\n\n    Mat* results = new Mat[number_of_slices];\n    for (int i = 0; i < number_of_slices; i++){\n        int range_start = (int)(i * (256.0 / number_of_slices));\n        int range_end = (int)((i + 1) * (256.0 / number_of_slices));\n\n        Mat res(img.size(), img.type());\n\n        for(int i = 0; i < res.cols; i++){\n            for(int j = 0; j < res.rows; j++){\n                int r = img.at<Vec3b>(Point(i, j))[0];\n\n                Vec3b& color = res.at<Vec3b>(Point(i, j));\n                if (r > range_start && r <= range_end){\n                    color[0] = 255;\n                    color[1] = 255;\n                    color[2] = 255;\n                }else{\n                    color[0] = 0;\n                    color[1] = 0;\n                    color[2] = 0;\n                }\n            }\n        }\n\n        results[i] = res;\n\n    }\n\n    return results;\n}\n\nMat Processor::add_noise(Mat &img, int percent){\n    Mat res(img.size(), img.type());\n    img.copyTo(res);\n\n    srand (time(NULL));\n\n    for(int i = 0; i < res.cols; i++){\n        for(int j = 0; j < res.rows; j++){\n            int r = rand() % 100;\n\n            if (r < percent){\n                Vec3b& color = res.at<Vec3b>(Point(i, j));\n\n                if (color[0] == color[1] && color[1] == color[2]){\n                    r = rand() % 256;\n                    //color[0] += r;\n                    //color[1] += r;\n                    //color[2] += r;\n                    color[0] = color[1] = color[2] = r;\n                }else{\n                    //color[0] += rand() % 256;\n                    //color[1] += rand() % 256;\n                    //color[2] += rand() % 256;\n                    color[0] = rand() % 256;\n                    color[1] = rand() % 256;\n                    color[2] = rand() % 256;\n                }\n            }\n        }\n    }\n\n    return res;\n}\n", "meta": {"hexsha": "39e579069804b8ee08c60069365cb3fb6b8fcdf3", "size": 22354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "processor.cpp", "max_stars_repo_name": "sina-cb/ColonD_ImageProcessor", "max_stars_repo_head_hexsha": "2005e3f0078a9247345e298ed6eff6c1d2ac9e64", "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": "processor.cpp", "max_issues_repo_name": "sina-cb/ColonD_ImageProcessor", "max_issues_repo_head_hexsha": "2005e3f0078a9247345e298ed6eff6c1d2ac9e64", "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": "processor.cpp", "max_forks_repo_name": "sina-cb/ColonD_ImageProcessor", "max_forks_repo_head_hexsha": "2005e3f0078a9247345e298ed6eff6c1d2ac9e64", "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.4907651715, "max_line_length": 134, "alphanum_fraction": 0.4827323969, "num_tokens": 6651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5142119571664833}}
{"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//  Constexpr implementation of sqrt function\n\n#ifndef BOOST_MATH_CCMATH_SQRT\n#define BOOST_MATH_CCMATH_SQRT\n\n#include <cmath>\n#include <limits>\n#include <type_traits>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n#include <boost/math/tools/is_constant_evaluated.hpp>\n\nnamespace boost::math::ccmath { \n\nnamespace detail {\n\ntemplate <typename Real>\ninline constexpr Real sqrt_impl_2(Real x, Real s, Real s2)\n{\n    return !(s < s2) ? s2 : sqrt_impl_2(x, (x / s + s) / 2, s);\n}\n\ntemplate <typename Real>\ninline constexpr Real sqrt_impl_1(Real x, Real s)\n{\n    return sqrt_impl_2(x, (x / s + s) / 2, s);\n}\n\ntemplate <typename Real>\ninline constexpr Real sqrt_impl(Real x)\n{\n    return sqrt_impl_1(x, x > 1 ? x : Real(1));\n}\n\n} // namespace detail\n\ntemplate <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>\ninline constexpr Real sqrt(Real x)\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))\n    {\n        return boost::math::ccmath::isnan(x) ? std::numeric_limits<Real>::quiet_NaN() : \n               boost::math::ccmath::isinf(x) ? std::numeric_limits<Real>::infinity() : \n               detail::sqrt_impl<Real>(x);\n    }\n    else\n    {\n        using std::sqrt;\n        return sqrt(x);\n    }\n}\n\ntemplate <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>\ninline constexpr double sqrt(Z x)\n{\n    return detail::sqrt_impl<double>(static_cast<double>(x));\n}\n\n} // Namespaces\n\n#endif // BOOST_MATH_CCMATH_SQRT\n", "meta": {"hexsha": "934207db3279fb41448b7093675d7d45978cb618", "size": 1703, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/ccmath/sqrt.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/ccmath/sqrt.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/ccmath/sqrt.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": 25.4179104478, "max_line_length": 88, "alphanum_fraction": 0.6834997064, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5142119556998611}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n#include \"ukf.h\"\n\nusing namespace std;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing std::vector;\n\nint main() {\n\n\t//Create a UKF instance\n\tUKF ukf;\n\n/*******************************************************************************\n* Programming assignment calls\n*******************************************************************************/\n\n    MatrixXd Xsig = MatrixXd(11, 5);\n    ukf.GenerateSigmaPoints(&Xsig);\n\n    //print result\n    std::cout << \"Xsig = \" << std::endl << Xsig << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "6dc8eff747344f240ed4ed55f4895012446eabfa", "size": 579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "P2-Unscented-Kalman-Filter/class-notes/generating-sigma-points/src/generating-sigma-points.cpp", "max_stars_repo_name": "Deborah-Digges/SDC-ND-term-2", "max_stars_repo_head_hexsha": "ebed581914957f1ab615edfedea0052dc55b0939", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-10-26T01:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-22T08:50:11.000Z", "max_issues_repo_path": "P2-Unscented-Kalman-Filter/class-notes/generating-sigma-points/src/generating-sigma-points.cpp", "max_issues_repo_name": "Deborah-Digges/SDC-ND-term-2", "max_issues_repo_head_hexsha": "ebed581914957f1ab615edfedea0052dc55b0939", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P2-Unscented-Kalman-Filter/class-notes/generating-sigma-points/src/generating-sigma-points.cpp", "max_forks_repo_name": "Deborah-Digges/SDC-ND-term-2", "max_forks_repo_head_hexsha": "ebed581914957f1ab615edfedea0052dc55b0939", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-05-28T20:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T09:01:54.000Z", "avg_line_length": 20.6785714286, "max_line_length": 80, "alphanum_fraction": 0.4766839378, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5142119447955665}}
{"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//[append\n//` Shows usage of Boost.Geometry's append to append a point or a range to a polygon\n\n#include <iostream>\n\n#include <boost/assign.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\nint main()\n{\n    using boost::assign::tuple_list_of;\n    using boost::make_tuple;\n    using boost::geometry::append;\n\n    typedef boost::geometry::model::polygon<boost::tuple<int, int> > polygon;\n\n    polygon poly;\n\n    // Append a range\n    append(poly, tuple_list_of(0, 0)(0, 10)(11, 11)(10, 0)); /*< tuple_list_of delivers a range and can therefore be used in boost::geometry::append >*/\n    // Append a point (in this case the closing point)\n    append(poly, make_tuple(0, 0));\n\n    // Create an interior ring (append does not do this automatically)\n    boost::geometry::interior_rings(poly).resize(1);\n\n    // Append a range to the interior ring\n    append(poly, tuple_list_of(2, 2)(2, 5)(6, 6)(5, 2), 0); /*< The last parameter ring_index 0 denotes the first interior ring >*/\n    // Append a point to the first interior ring\n    append(poly, make_tuple(2, 2), 0);\n\n    std::cout << boost::geometry::dsv(poly) << std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[append_output\n/*`\nOutput:\n[pre\n(((0, 0), (0, 10), (11, 11), (10, 0), (0, 0)), ((2, 2), (2, 5), (6, 6), (5, 2), (2, 2)))\n]\n*/\n//]\n", "meta": {"hexsha": "f5a3085b5b9e6dc4f66801592deb00b83e39a477", "size": 1764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/geometry/doc/src/examples/algorithms/append.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2016-03-04T15:44:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T11:06:25.000Z", "max_issues_repo_path": "boost/libs/geometry/doc/src/examples/algorithms/append.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2016-02-29T17:59:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-05T04:59:26.000Z", "max_forks_repo_path": "boost/libs/geometry/doc/src/examples/algorithms/append.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.4516129032, "max_line_length": 152, "alphanum_fraction": 0.6763038549, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5140996804008249}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/assert.hpp>\n#include <boost/hana/bool.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/ext/std/integral_constant.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/map.hpp>\n#include <boost/hana/maybe.hpp>\n#include <boost/hana/pair.hpp>\n#include <boost/hana/set.hpp>\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/type.hpp>\n\n#include <type_traits>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [all_of]\nusing namespace literals;\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto odd = [](auto x) {\n    return x % 2_c != 0_c;\n};\n\nBOOST_HANA_CONSTEXPR_CHECK(all_of(make<Tuple>(1, 3), odd));\nBOOST_HANA_CONSTANT_CHECK(!all_of(make<Tuple>(3_c, 4_c), odd));\n\nBOOST_HANA_CONSTANT_CHECK(\n    !all_of(make<Tuple>(type<void>, type<char&>), trait<std::is_void>)\n);\nBOOST_HANA_CONSTANT_CHECK(\n    all_of(make<Tuple>(type<int>, type<char>), trait<std::is_integral>)\n);\n//! [all_of]\n\n}{\n\n//! [all]\nBOOST_HANA_CONSTEXPR_CHECK(all(make<Tuple>(true_, true, true_)));\nBOOST_HANA_CONSTANT_CHECK(!all(make<Tuple>(true, false_, true_)));\n//! [all]\n\n}{\n\n//! [any_of]\nusing namespace literals;\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto odd = [](auto x) {\n    return x % 2_c != 0_c;\n};\n\nBOOST_HANA_CONSTEXPR_CHECK(any_of(make<Tuple>(1, 2), odd));\nBOOST_HANA_CONSTANT_CHECK(!any_of(make<Tuple>(2_c, 4_c), odd));\n\nBOOST_HANA_CONSTANT_CHECK(\n    any_of(make<Tuple>(type<void>, type<char&>), trait<std::is_void>)\n);\nBOOST_HANA_CONSTANT_CHECK(\n    !any_of(make<Tuple>(type<void>, type<char&>), trait<std::is_integral>)\n);\n//! [any_of]\n\n}{\n\n//! [any]\nBOOST_HANA_CONSTANT_CHECK(any(make<Tuple>(false, false_, true_)));\nBOOST_HANA_CONSTEXPR_CHECK(any(make<Tuple>(false, false_, true)));\nBOOST_HANA_CONSTEXPR_CHECK(!any(make<Tuple>(false, false_, false_)));\n//! [any]\n\n}{\n\n//! [elem]\nBOOST_HANA_CONSTANT_CHECK(elem(make<Tuple>(2, int_<2>, int_<3>, 'x'), int_<3>));\nBOOST_HANA_CONSTANT_CHECK(elem(set(1, '2', type<int>, \"foobar\"), type<int>));\n//! [elem]\n\n}{\n\n//! [find_if]\nBOOST_HANA_CONSTEXPR_CHECK(\n    find_if(make<Tuple>(1.0, 2, '3'), trait_<std::is_integral>) == just(2)\n);\nBOOST_HANA_CONSTANT_CHECK(\n    find_if(make<Tuple>(1.0, 2, '3'), trait_<std::is_class>) == nothing\n);\n\nconstexpr auto types = tuple_t<char, int, unsigned, long, unsigned long>;\nBOOST_HANA_CONSTANT_CHECK(\n    find_if(types, _ == type<unsigned>) == just(type<unsigned>)\n);\nBOOST_HANA_CONSTANT_CHECK(\n    find_if(types, _ == type<void>) == nothing\n);\n//! [find_if]\n\n}{\n\n//! [find]\nBOOST_HANA_CONSTANT_CHECK(\n    find(make<Tuple>(int_<1>, type<int>, '3'), type<int>) == just(type<int>)\n);\nBOOST_HANA_CONSTANT_CHECK(\n    find(make<Tuple>(int_<1>, type<int>, '3'), type<void>) == nothing\n);\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto m = make<Map>(\n    make<Pair>(1, 'x'),\n    make<Pair>(type<float>, 3.3),\n    make<Pair>(type<char>, type<int>)\n);\nBOOST_HANA_CONSTEXPR_CHECK(find(m, type<float>) == just(3.3));\n//! [find]\n\n}{\n\n//! [in]\nBOOST_HANA_CONSTEXPR_LAMBDA auto xs = make<Tuple>(\n    int_<1>, type<int>, int_<2>, type<float>, int_<3>, type<void>, type<char>\n);\nBOOST_HANA_CONSTANT_CHECK(\n    filter(xs, in ^ make<Tuple>(int_<3>, type<int>, type<void>))\n    ==\n    make<Tuple>(type<int>, int_<3>, type<void>)\n);\n//! [in]\n\n}{\n\n//! [none_of]\nusing namespace literals;\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto odd = [](auto x) {\n    return x % 2_c != 0_c;\n};\n\nBOOST_HANA_CONSTANT_CHECK(none_of(make<Tuple>(2_c, 4_c), odd));\nBOOST_HANA_CONSTEXPR_CHECK(!none_of(make<Tuple>(1, 2), odd));\n\nBOOST_HANA_CONSTANT_CHECK(\n    !none_of(make<Tuple>(type<void>, type<char&>), trait<std::is_void>)\n);\nBOOST_HANA_CONSTANT_CHECK(\n    none_of(make<Tuple>(type<void>, type<char&>), trait<std::is_integral>)\n);\n//! [none_of]\n\n}{\n\n//! [none]\nBOOST_HANA_CONSTEXPR_CHECK(none(make<Tuple>(false, false_, false_)));\nBOOST_HANA_CONSTEXPR_CHECK(!none(make<Tuple>(false, false_, true)));\nBOOST_HANA_CONSTANT_CHECK(!none(make<Tuple>(false, false_, true_)));\n//! [none]\n\n}{\n\n//! [subset]\nBOOST_HANA_CONSTEXPR_CHECK(subset(make<Tuple>(1, '2', 3.3), make<Tuple>(3.3, 1, '2', nullptr)));\n//! [subset]\n\n}\n\n}\n", "meta": {"hexsha": "3a659527acedf2b7b6a533e1a6216080a418dc30", "size": 4254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/searchable.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/searchable.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/searchable.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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.3085714286, "max_line_length": 96, "alphanum_fraction": 0.6873530795, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.7154239957834732, "lm_q1q2_score": 0.5140996803036751}}
{"text": "/*\n * File:   test_Paillier_Image.cc\n * Author: Mohamed TarekIbnZiad\n *\n * Created on September 16, 2015, 7:48 AM\n */\n\n#include <assert.h>\n#include <vector>\n#include <crypto/paillier.hh>\n#include <Img.hh>\n#include <ImgP.hh>\n#include <crypto/gm.hh>\n#include <NTL/ZZ.h>\n#include <gmpxx.h>\n#include <math/util_gmp_rand.h>\n\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n\n#include <ctime>\n\n#include<iostream>\n\n#define PI 3.14159265359\n\nusing namespace cv;\nusing namespace std;\nusing namespace NTL;\n\n\n/*\n * convert an image from Mat type to double type used as input in encryption\n */\nvector < vector<double> >\nMat2Double(Mat src)\n{\n    vector < vector<double> > A(src.rows, vector<double>(src.cols));\n    Scalar s;\n    for (int i = 0; i < src.rows; i++) {\n        for (int j = 0; j < src.cols; j++){\n            s = src.at<uchar>(i,j);\n            A[i][j] = (int)s[0];\n        }\n    }\n    return A;\n}\n\n/*\n * convert an image from double type to Mat type (opencv)\n */\nMat\nDouble2Mat(vector < vector<double> > &A)\n{\n    int rows = A.size();\n    int cols = A.data()->size();\n    Mat dst(rows,cols,CV_8UC1);\n    for (int i = 0; i < rows; i++) {\n        for (int j = 0; j < cols; j++){\n            dst.at<uchar>(i,j) = (int)A[i][j];  //Through away the float part or round it?\n            //dst.at<uchar>(i,j) = round(A[i][j]);\n        }\n    }\n    return dst;\n}\n\n\n/*\n * convert an image from encnum type used in encryption to Mat type (opencv)\n */\nMat\nencnum2Mat(vector < vector<encnum> > &A)\n{\n    int rows = A.size();\n    int cols = A.data()->size();\n    Mat dst(rows,cols,CV_8UC1);\n    for (int i = 0; i < rows; i++) {\n        for (int j = 0; j < cols; j++){\n            dst.at<uchar>(i,j) = (int)A[i][j].mantissa.get_d(); //double to int\n        }\n    }\n    return dst;\n}\n\n\ndouble\ngetRMSE(const Mat& I1, const Mat& I2)\n{\n    Mat s1;\n    absdiff(I1, I2, s1);       // |I1 - I2|\n    s1.convertTo(s1, CV_32F);  // cannot make a square on 8 bits\n    s1 = s1.mul(s1);           // |I1 - I2|^2\n\n    Scalar s = sum(s1);        // sum elements per channel\n    double sse = s.val[0] + s.val[1] + s.val[2]; // sum channels\n    double mse  = sse / (double)(I1.channels() * I1.total());\n    double rmse = sqrt(mse);\n\n    return rmse;\n }\n\n/*\n * Get the absolute values for a resultant image\n */\nvector < vector <double> >\ngetAbsolute(vector < vector<double> > &A)\n{\n    int rows = A.size();\n    int cols = A.data()->size();\n    vector < vector<double> > B(rows, vector<double>(cols));\n    for (int i = 0; i < rows; i++) {\n        for (int j = 0; j < cols; j++){\n            if (A[i][j] < 0 )\n                B[i][j] = A[i][j] * -1;\n            else\n                B[i][j] = A[i][j];\n        }\n    }\n    return B;\n}\n\n/*\n * Add the absolute values of 2 resultant images (H and V)\n * IF accepted and implemented on Mob --> combine it with get absolute\n */\nvector < vector <double> >\nAddAbsolute(vector < vector<double> > &A, vector < vector<double> > &B)\n{\n    int rows = A.size();\n    int cols = A.data()->size();\n    vector < vector<double> > C(rows, vector<double>(cols));\n    for (int i = 0; i < rows; i++) {\n        for (int j = 0; j < cols; j++){\n                C[i][j] = A[i][j] + B[i][j];\n        }\n    }\n    return C;\n}\n\n/*\n * Creates an average filter with a specified kernel size\n */\nvector < vector <double> >\nCreateBoxFilter(int kSize){\n\n    vector < vector <double> > filter (kSize, vector<double>(kSize));\n    for (int i = 0; i < kSize; i++)\n        for(int j = 0;j< kSize; j++)\n            filter[i][j] = 1.0/(kSize*kSize);\n    return filter;\n}\n\n/*\n * Creates a Gaussian filter with a specified kernel size\n */\nvector < vector <double> >\nCreateGaussianFilter(int kSize, double sigma){\n\n    vector < vector <double> > filter (kSize, vector<double>(kSize));\n    if (sigma < 0)\n        sigma = 0.3*((kSize-1)*0.5 - 1) + 0.8;\n\n    double alpha = 1/(2*PI*sigma*sigma);\n    //(0,0) is in the center\n    for (int x = -kSize/2; x <= kSize/2; x++){\n        for(int y = -kSize/2;y<= kSize/2; y++){\n            //Needs To be checked! http://prntscr.com/8h6q9b\n            filter[x+(kSize/2)][y+(kSize/2)] = alpha*exp(-(x*x + y*y)/(2*sigma*sigma));\n        }\n    }\n    return filter;\n}\n\n/*\n * Post processing for erosion\n */\nvector < vector <double> >\nerodePost(vector < vector<double> > &A)\n{\n    int rows = A.size();\n    int cols = A.data()->size();\n    vector < vector<double> > B(rows, vector<double>(cols));\n    for (int i = 0; i < rows; i++) {\n        for (int j = 0; j < cols; j++){\n            if (A[i][j] == (9*255) ) //All the values under the mask are 255s\n                B[i][j] = 1*255;\n            else\n                B[i][j] = 0*255;\n        }\n    }\n    return B;\n}\n\n/*\n * Post processing for dilation\n */\nvector < vector <double> >\ndilatePost(vector < vector<double> > &A)\n{\n    int rows = A.size();\n    int cols = A.data()->size();\n    vector < vector<double> > B(rows, vector<double>(cols));\n    for (int i = 0; i < rows; i++) {\n        for (int j = 0; j < cols; j++){\n            if (A[i][j] >= 1*255 && A[i][j] <= 9*255 )\n                B[i][j] = 1*255;\n            else //All the values under the mask are 0s\n                B[i][j] = 0*255;\n        }\n    }\n    return B;\n}\n\n/*\n * Takes an image as input\n * returns a 2d vector with the 1st columns represents colors and\n * the 2nd represents their freq.\n * The vector length is the total intensity levels G\n */\nvector < vector <double> >\ncountHist(vector < vector<double> > src)\n{\n    int rows = src.size();\n    int cols = src.data()->size();\n    vector <int> Frequencies (256);\n    for (int i = 0; i < rows; i++) {\n        for (int j = 0; j < cols; j++){\n            Frequencies[src[i][j]]++;\n        }\n    }\n\n    vector < vector<double> > ColorFreq(256, vector<double>(2));\n    int G = 0;\n    for (int i=0; i<256; i++){\n        if(Frequencies[i] != 0){\n            ColorFreq[G][0] = i;\n            ColorFreq[G][1] = Frequencies[i];\n            G++;\n        }\n    }\n    return ColorFreq;\n}\n\n/*\n * Post processing Histogram function that constructs the new image based on the new histogram counts\n */\nMat\nupdateHist(vector < vector<double> > &newFreqHist, Mat src)\n{\n    int rows = src.rows;\n    int cols = src.cols;\n    int G = newFreqHist.size();\n\n    vector <int> newColors (256);\n    for (int i = 0; i<256; i++)\n        newColors[i] = i;\n\n    for (int i = 0; i<G; i++){\n        newColors[newFreqHist[i][0]] = round(newFreqHist[i][1]);\n    }\n\n    Mat dst(rows,cols,CV_8UC1);\n    Scalar s;\n    for (int i = 0; i < rows; i++) {\n        for (int j = 0; j < cols; j++){\n            s = src.at<uchar>(i,j);\n            dst.at<uchar>(i,j) = newColors[(int)s[0]];\n        }\n    }\n    return dst;\n}\n\n\nvoid\ntestImagePaillier()\n{\n    //Measuring time\n    struct timespec t0,t1;\n    uint64_t t;\n\n    //Generate Paillier key\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    gmp_randstate_t randstate;\n    gmp_randinit_default(randstate);\n    gmp_randseed_ui(randstate,time(NULL));\n\n    auto sk = Paillier_priv::keygen(randstate,256,2); //600 ,256 , 128\n    Paillier_priv pp(sk,randstate);\n\n    auto pk = pp.pubkey();\n    mpz_class n = pk[0];\n    Paillier p(pk,randstate);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Key Generation : \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    cout << \"key ready\" << endl;\n\n    //read image\n    Mat src = imread( \"cameraman.JPG\", 0); //cameraman.JPG\n    imshow( \"Original Image\", src );\n\n    int rows = src.rows;\n    int cols = src.cols;\n    vector < vector<double> > A(rows, vector<double>(cols));\n    A = Mat2Double(src);\n\n    //Encrypt image\n    vector < vector<encnum> > A_enc;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    A_enc = p.encryptMatrix(A);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"public encryption: \"<<  ((double)t/1000000) <<\"ms per image\" << endl;\n    cout << \"Image encrypted \" << endl;\n    //imshow( \"Encrypted Image\", encnum2Mat(A_enc) );\n\n    //The client only can decrypt a matrix\n    vector < vector<double> > A_dec;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    A_dec = pp.decryptMatrix(A_enc);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"private decryption: \"<<  ((double)t/1000000) <<\"ms per image\" << endl;\n    cout << \"Image decrypted \" << endl;\n    Mat dst;\n    dst = Double2Mat(A_dec);\n    imshow( \"Decrypted Image\", dst );\n    cout << \"Root Mean Square Error in decryption: \"<<getRMSE(src,dst)<<endl;\n\n    //Create image to work in plain domain\n    ImgP img1P;\n\n    //Create image to work in encrypted domain\n    Img img1(A_enc);\n    img1.setPbKey(p);\n\n    //Debug code\n    cout << \"Test sub Paillier numbers...\\n\" << flush;\n    double a = 255 , b = 5;\n    encnum a_enc = p.encrypt_f(a);\n    encnum b_enc = p.encrypt_f(b);\n    b_enc = p.constMult_f(1.0 , b_enc);\n    //b_enc = p.encrypt_f(pp.decrypt_f(b_enc)); //Re-encrypt\n    encnum sum = p.sub_f(a_enc, b_enc);\n    cout << a << \" - \" << b << \" = \" << pp.decrypt_f(sum)<< endl<< endl;\n    cout << \"---------------------------------------\\n\" << flush;\n\n    //Negate image in plain domain\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    dst = img1P.NegativeImage(src);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Negative Image (Plain): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    imshow( \"Negative Image\", dst );\n\n    //Negate image in encrypted domain\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<encnum> > Neg_enc = img1.NegativeImageH(A_enc);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Negative Image (Enc): \"<<  ((double)t/1000000) <<\"ms per image\" << endl;\n    //imshow( \"Encrypted Negative Image\", encnum2Mat(Neg_enc) );\n\n    vector < vector<double> > Neg_dec = pp.decryptMatrix(Neg_enc);\n    imshow( \"Decrypted Negative Image\", Double2Mat(Neg_dec) );\n    cout << \"Root Mean Square Error in Negative image: \"<<getRMSE(dst,Double2Mat(Neg_dec))<<endl;\n\n    //Test Brightness\n    int value = 10;\n    //Increase brightness in plain domain\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    dst = img1P.AdjustBrightness(src, value);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Brightness Image (Plain): \"<<  ((double)t/1000000) <<\"ms per image\" << endl;\n    imshow( \"Brightness Image\", dst );\n\n    //Increase brightness in encrypted domain\n    encnum value_enc = p.encrypt_f(value);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<encnum> > Bright_enc = img1.AdjustBrightnessH(A_enc, value_enc);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Brightness Image (Enc): \"<<  ((double)t/1000000) <<\"ms per image\" << endl;\n    //imshow( \"Encrypted Brightness Image\", encnum2Mat(Bright_enc) );\n\n    vector < vector<double> > Bright_dec = pp.decryptMatrix(Bright_enc);\n    imshow( \"Decrypted Brightness Image\", Double2Mat(Bright_dec) );\n    cout << \"Root Mean Square Error in Brightness image: \"<<getRMSE(dst,Double2Mat(Bright_dec))<<endl;\n    //post-processing to fix the image\n    //Bright_dec = FixRange(Bright_dec);\n    //imshow( \"Decrypted Brightness Image\", Double2Mat(Bright_dec) );\n\n    //Test convolution\n    vector < vector<double> > filter;\n    //filter = {{1,0,-1},{2,0,-2},{1,0,-1}};//Vertical edges\n    filter = {{1,2,1},{0,0,0},{-1,-2,-1}};  //Horizontal edges\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<encnum> > conv_enc = img1.convolutionH(A_enc, filter);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Convolution (Enc): \"<<  ((double)t/1000000) <<\"ms per image\" << endl;\n    //imshow( \"Encrypted convoluted Image\", encnum2Mat(conv_enc) );\n    vector < vector<double> > conv_dec = pp.decryptMatrix(conv_enc);\n    //Temp solution to the -ve value problem in edge detection\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<double> > conv_dec_fixed = getAbsolute(conv_dec);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Convolution (Post Processing): \"<<  ((double)t/1000000) <<\"ms per image\" << endl;\n    imshow( \"Decrypted convoluted Image\", Double2Mat(conv_dec_fixed) );\n\n    //Test convolution in Plain domain\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    dst = img1P.convolution(src, filter);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Convolution (Plain): \"<<  ((double)t/1000000) <<\"ms per image\" << endl;\n    //Take care of rounding and borders to reduce error\n    imshow( \"convoluted Image\", dst );\n    cout << \"Root Mean Square Error in convoluted image: \"<<getRMSE(dst,Double2Mat(conv_dec))<<endl;\n    cout << \"Root Mean Square Error in convoluted image (Absolute): \"<<getRMSE(dst,Double2Mat(conv_dec_fixed))<<endl;\n\n    //Test Average filter\n    //filter = {{1.0/9,1.0/9,1.0/9},{1.0/9,1.0/9,1.0/9},{1.0/9,1.0/9,1.0/9}};\n    filter = CreateBoxFilter(3);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<encnum> > Avg_enc = img1.convolutionH(A_enc, filter);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Average (Enc): \"<<  ((double)t/1000000) <<\"ms per image\" << endl;\n    //imshow( \"Encrypted averaged Image\", encnum2Mat(Avg_enc) );\n    vector < vector<double> > Avg_dec = pp.decryptMatrix(Avg_enc);\n    //vector < vector<double> > Avg_dec_d = Mat\n    imshow( \"Decrypted averaged Image\", Double2Mat(Avg_dec) );\n\n    //Test average filter in plain domain\n    //dst = img1P.AverageFilter(src,filter);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    dst = img1P.convolution(src, filter);\n    vector < vector<double> >  aa = Mat2Double(dst);//Debug Line\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Average (Plain): \"<<  ((double)t/1000000) <<\"ms per image\" << endl;\n    imshow( \"Averaged Image\", dst );\n    cout << \"Root Mean Square Error in Averaged image: \"<<getRMSE(dst,Double2Mat(Avg_dec))<<endl; //Error due to rounding\n\n    //Test Gaussian Filtering\n    //filter = CreateGaussianFilter(5,1);\n\n    //Laplacian:Calculates the Laplacian of an image.\n    //filter = {{0,1,0},{1,-4,1},{0,1,0}};\n\n    //Test Histogram equalization\n    //Pre-processing\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<double> > ColorFreq = countHist(Mat2Double(src));\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Histogram Equalization (Enc_Pre): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n\n    vector < vector<encnum> > ColorFreq_enc = p.encryptMatrix(ColorFreq);\n\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<encnum> > newColorFreq_enc = img1.equalHistH(ColorFreq_enc, src.rows, src.cols);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Histogram Equalization (Enc): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n\n    vector < vector<double> > newColorFreq_dec = pp.decryptMatrix(newColorFreq_enc);\n\n    //Post-processing\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    Mat equalizedSrc = updateHist(newColorFreq_dec, src);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Histogram Equalization (Enc_post): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    imshow( \"Decrypted Equalized Image\", equalizedSrc );\n    //OpenCV --> TODO\n    //imshow( \"Equalized Image Open CV\", srcB );\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    dst = img1P.equalHist(src);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Histogram Equalization (Plain): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    imshow( \"Equalized Image \", dst );\n    cout << \"Root Mean Square Error in Equalized image: \"<<getRMSE(dst,equalizedSrc)<<endl;\n    //To eliminate error here --> use precision = 0.00000001 with 128-bit key\n\n    //Test Edge filters\n    //In plain domain\n    char direction = 'H'; //'H' for horizontal and 'V' for vertical\n    char type = 'S'; //'R' Roberts, 'P' Prewitt, 'S' Sobel, 'R' Robinson, 'K' Kirsch\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    dst = img1P.EdgeDetectionFilter(src, type, direction);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter in H (Plain): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    imshow( \"Edge Image H\", dst );\n    //In encrypted domain\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<encnum> > Edge_enc = img1.EdgeDetectionFilterH(A_enc, type, direction);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter (Enc): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    imshow( \"Encrypted Edge Image\", encnum2Mat(Edge_enc) );\n    vector < vector<double> > Edge_dec = pp.decryptMatrix(Edge_enc);\n    imshow( \"Decrypted Edge Image H\", Double2Mat(Edge_dec) );\n    cout << \"Root Mean Square Error in Edge image H: \"<<getRMSE(dst,Double2Mat(Edge_dec))<<endl;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<double> > Edge_dec_fixed = getAbsolute(Edge_dec);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter in H (Enc_post): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    imshow( \"Decrypted Edge Image in H (Absolute)\", Double2Mat(Edge_dec_fixed) );\n    cout << \"Root Mean Square Error in Edge image H (Absolute): \"<<getRMSE(dst,Double2Mat(Edge_dec_fixed))<<endl;\n\n    //In vertical direction\n    direction = 'V'; //'H' for horizontal and 'V' for vertical\n    type = 'S'; //'R' Roberts, 'P' Prewitt, 'S' Sobel, 'R' Robinson, 'K' Kirsch\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    dst = img1P.EdgeDetectionFilter(src, type, direction);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter in V (Plain): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    imshow( \"Edge Image V\", dst );\n    //In encrypted domain\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    Edge_enc = img1.EdgeDetectionFilterH(A_enc, type, direction);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter (Enc): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    //imshow( \"Encrypted Edge Image V\", encnum2Mat(Edge_enc) );\n    Edge_dec = pp.decryptMatrix(Edge_enc);\n    imshow( \"Decrypted Edge Image V\", Double2Mat(Edge_dec) );\n    cout << \"Root Mean Square Error in Edge image V: \"<<getRMSE(dst,Double2Mat(Edge_dec))<<endl;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<double> > Edge_dec_fixedV = getAbsolute(Edge_dec);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter in V (Enc_post): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    imshow( \"Decrypted Edge Image in V (Absolute)\", Double2Mat(Edge_dec_fixedV) );\n    cout << \"Root Mean Square Error in Edge image V (Absolute): \"<<getRMSE(dst,Double2Mat(Edge_dec_fixedV))<<endl;\n\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<double> > EdgeTotal = AddAbsolute(Edge_dec_fixed,Edge_dec_fixedV);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter (Add abs_post): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    imshow( \"Decrypted Edge Image Total \", Double2Mat(EdgeTotal) );\n\n\n    //Test morphological operations\n    // Load an image from file\n    Mat srcB = imread( \"butterfly-11.jpg\", 0); //0 --> gray, 1 --> RGB image\n    srcB = srcB > 128; // Convert gray to binary\n    //show the loaded image\n    imshow( \"Original Binary Image\", srcB );\n\n    Mat dstB;\n    dstB = srcB.clone(); //Copy of src as initial value\n\n    int element_shape = MORPH_RECT;\n    Mat element = getStructuringElement(element_shape, Size(3, 3), Point(-1, -1) );\n    vector < vector<double> > element_d = Mat2Double(element);\n\n    int rowsB = srcB.rows;\n    int colsB = srcB.cols;\n    vector < vector<double> > B(rowsB, vector<double>(colsB));\n    B = Mat2Double(srcB);\n    //Encrypt image\n    vector < vector<encnum> > B_enc = p.encryptMatrix(B);\n    //imshow( \"Encrypted Binary Image\", encnum2Mat(B_enc) );\n\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<encnum> > morph_enc = img1.morphH(B_enc, element_d);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Morph (Enc): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    //imshow( \"Encrypted Morphological Image\", encnum2Mat(morph_enc) );\n    vector < vector<double> > morph_dec = pp.decryptMatrix(morph_enc);\n    //Post processing for erosion/dilation\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<double> > morph_dec_erode = erodePost(morph_dec);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Morph (Enc_post_Erode): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    imshow( \"Decrypted eroded Image\", Double2Mat(morph_dec_erode) );\n\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    erode(srcB, dstB, element);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Morph (Plain_Erode): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    imshow(\"Erode OpenCV\",dstB);\n    cout << \"Root Mean Square Error in eroded image: \"<<getRMSE(dstB,Double2Mat(morph_dec_erode))<<endl;\n\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<double> > morph_dec_dilate = dilatePost(morph_dec);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Morph (Enc_post_Dilate): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    imshow( \"Decrypted dilated Image\", Double2Mat(morph_dec_dilate) );\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    dilate(srcB, dstB, element);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Morph (Plain_Dilate): \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    imshow(\"Dilate OpenCV\",dstB);\n    cout << \"Root Mean Square Error in dilated image: \"<<getRMSE(dstB,Double2Mat(morph_dec_dilate))<<endl;\n\n    //wait for a key press infinitely\n    waitKey(0);\n}\n\nvoid\ntestImagePaillier_N(int n_iteration)\n{\n    //Measuring time\n    struct timespec t0,t1;\n    uint64_t t;\n\n    //Generate Paillier key\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    gmp_randstate_t randstate;\n    gmp_randinit_default(randstate);\n    gmp_randseed_ui(randstate,time(NULL));\n\n    auto sk = Paillier_priv::keygen(randstate,128,2); //600 ,256 , 128\n    Paillier_priv pp(sk,randstate);\n\n    auto pk = pp.pubkey();\n    mpz_class n = pk[0];\n    Paillier p(pk,randstate);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Key Generation : \"<<  ((double)t/1000000) <<\"ms\" << endl;\n    cout << \"key ready\" << endl;\n\n    //read image\n    Mat src = imread( \"cameraman.JPG\", 0);\n    imshow( \"Original Image\", src );\n\n    int rows = src.rows;\n    int cols = src.cols;\n    vector < vector<double> > A(rows, vector<double>(cols));\n    A = Mat2Double(src);\n\n    //Encrypt image\n    vector < vector<encnum> > A_enc;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        A_enc = p.encryptMatrix(A);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"public encryption: \"<<  ((double)t/1000000)/n_iteration <<\"ms per image\" << endl;\n    cout << \"Image encrypted \" << endl;\n    //imshow( \"Encrypted Image\", encnum2Mat(A_enc) );\n\n    //The client only can decrypt a matrix\n    vector < vector<double> > A_dec;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        A_dec = pp.decryptMatrix(A_enc);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"private decryption: \"<<  ((double)t/1000000)/n_iteration <<\"ms per image\" << endl;\n    cout << \"Image decrypted \" << endl;\n    Mat dst;\n    dst = Double2Mat(A_dec);\n    imshow( \"Decrypted Image\", dst );\n    cout << \"Root Mean Square Error in decryption: \"<<getRMSE(src,dst)<<endl;\n\n    //Create image to work in plain domain\n    ImgP img1P;\n\n    //Create image to work in encrypted domain\n    Img img1(A_enc);\n    img1.setPbKey(p);\n\n    //Negate image in plain domain\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        dst = img1P.NegativeImage(src);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Negative Image (Plain): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow( \"Negative Image\", dst );\n\n    //Negate image in encrypted domain\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    vector < vector<encnum> > Neg_enc;\n    for (size_t i = 0; i < n_iteration; i++) {\n        Neg_enc = img1.NegativeImageH(A_enc);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Negative Image (Enc): \"<<  ((double)t/1000000)/n_iteration <<\"ms per image\" << endl;\n    //imshow( \"Encrypted Negative Image\", encnum2Mat(Neg_enc) );\n\n    vector < vector<double> > Neg_dec = pp.decryptMatrix(Neg_enc);\n    imshow( \"Decrypted Negative Image\", Double2Mat(Neg_dec) );\n    cout << \"Root Mean Square Error in Negative image: \"<<getRMSE(dst,Double2Mat(Neg_dec))<<endl;\n\n    //Test Brightness\n    int value = 10;\n    //Increase brightness in plain domain\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        dst = img1P.AdjustBrightness(src, value);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Brightness Image (Plain): \"<<  ((double)t/1000000)/n_iteration <<\"ms per image\" << endl;\n    imshow( \"Brightness Image\", dst );\n\n    //Increase brightness in encrypted domain\n    encnum value_enc = p.encrypt_f(value);\n    vector < vector<encnum> > Bright_enc;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        Bright_enc = img1.AdjustBrightnessH(A_enc, value_enc);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Brightness Image (Enc): \"<<  ((double)t/1000000)/n_iteration <<\"ms per image\" << endl;\n    //imshow( \"Encrypted Brightness Image\", encnum2Mat(Bright_enc) );\n\n    vector < vector<double> > Bright_dec = pp.decryptMatrix(Bright_enc);\n    imshow( \"Decrypted Brightness Image\", Double2Mat(Bright_dec) );\n    cout << \"Root Mean Square Error in Brightness image: \"<<getRMSE(dst,Double2Mat(Bright_dec))<<endl;\n    //post-processing to fix the image\n    //Bright_dec = FixRange(Bright_dec);\n    //imshow( \"Decrypted Brightness Image\", Double2Mat(Bright_dec) );\n\n    //Test convolution\n    vector < vector<double> > filter;\n    //filter = {{1,0,-1},{2,0,-2},{1,0,-1}};//Vertical edges\n    filter = {{1,2,1},{0,0,0},{-1,-2,-1}};  //Horizontal edges\n    vector < vector<encnum> > conv_enc;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        conv_enc = img1.convolutionH(A_enc, filter);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Convolution (Enc): \"<<  ((double)t/1000000)/n_iteration <<\"ms per image\" << endl;\n    //imshow( \"Encrypted convoluted Image\", encnum2Mat(conv_enc) );\n    vector < vector<double> > conv_dec = pp.decryptMatrix(conv_enc);\n    //Temp solution to the -ve value problem in edge detection\n    vector < vector<double> > conv_dec_fixed;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        conv_dec_fixed = getAbsolute(conv_dec);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Convolution (Post Processing): \"<<  ((double)t/1000000)/n_iteration <<\"ms per image\" << endl;\n    imshow( \"Decrypted convoluted Image\", Double2Mat(conv_dec_fixed) );\n\n    //Test convolution in Plain domain\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        dst = img1P.convolution(src, filter);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Convolution (Plain): \"<<  ((double)t/1000000)/n_iteration <<\"ms per image\" << endl;\n    //Take care of rounding and borders to reduce error\n    imshow( \"convoluted Image\", dst );\n    cout << \"Root Mean Square Error in convoluted image: \"<<getRMSE(dst,Double2Mat(conv_dec))<<endl;\n    cout << \"Root Mean Square Error in convoluted image (Absolute): \"<<getRMSE(dst,Double2Mat(conv_dec_fixed))<<endl;\n\n    //Test Average filter\n    //filter = {{1.0/9,1.0/9,1.0/9},{1.0/9,1.0/9,1.0/9},{1.0/9,1.0/9,1.0/9}};\n    filter = CreateBoxFilter(3);\n    vector < vector<encnum> > Avg_enc;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        Avg_enc = img1.convolutionH(A_enc, filter);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Average (Enc): \"<<  ((double)t/1000000)/n_iteration <<\"ms per image\" << endl;\n    //imshow( \"Encrypted averaged Image\", encnum2Mat(Avg_enc) );\n    vector < vector<double> > Avg_dec = pp.decryptMatrix(Avg_enc);\n    //vector < vector<double> > Avg_dec_d = Mat\n    imshow( \"Decrypted averaged Image\", Double2Mat(Avg_dec) );\n\n    //Test average filter in plain domain\n    //dst = img1P.AverageFilter(src,filter);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        dst = img1P.convolution(src, filter);\n    }\n    //vector < vector<double> >  aa = Mat2Double(dst);//Debug Line\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Average (Plain): \"<<  ((double)t/1000000)/n_iteration <<\"ms per image\" << endl;\n    imshow( \"Averaged Image\", dst );\n    cout << \"Root Mean Square Error in Averaged image: \"<<getRMSE(dst,Double2Mat(Avg_dec))<<endl; //Error due to rounding\n\n    //Test Gaussian Filtering\n    //filter = CreateGaussianFilter(5,1);\n\n    //Laplacian:Calculates the Laplacian of an image.\n    //filter = {{0,1,0},{1,-4,1},{0,1,0}};\n\n    //Test Histogram equalization\n    //Pre-processing\n    vector < vector<double> > ColorFreq;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        ColorFreq = countHist(Mat2Double(src));\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Histogram Equalization (Enc_Pre): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n\n    vector < vector<encnum> > ColorFreq_enc = p.encryptMatrix(ColorFreq);\n\n    vector < vector<encnum> > newColorFreq_enc;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        newColorFreq_enc = img1.equalHistH(ColorFreq_enc, src.rows, src.cols);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Histogram Equalization (Enc): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n\n    vector < vector<double> > newColorFreq_dec = pp.decryptMatrix(newColorFreq_enc);\n\n    //Post-processing\n    Mat equalizedSrc;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        equalizedSrc = updateHist(newColorFreq_dec, src);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Histogram Equalization (Enc_post): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow( \"Decrypted Equalized Image\", equalizedSrc );\n    //OpenCV --> TODO\n    //imshow( \"Equalized Image Open CV\", srcB );\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        dst = img1P.equalHist(src);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Histogram Equalization (Plain): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow( \"Equalized Image \", dst );\n    cout << \"Root Mean Square Error in Equalized image: \"<<getRMSE(dst,equalizedSrc)<<endl;\n    //To eliminate error here --> use precision = 0.00000001 with 128-bit key\n\n    //Test Edge filters\n    //In plain domain\n    char direction = 'H'; //'H' for horizontal and 'V' for vertical\n    char type = 'S'; //'R' Roberts, 'P' Prewitt, 'S' Sobel, 'R' Robinson, 'K' Kirsch\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        dst = img1P.EdgeDetectionFilter(src, type, direction);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter in H (Plain): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow( \"Edge Image H\", dst );\n    //In encrypted domain\n    vector < vector<encnum> > Edge_enc;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        Edge_enc = img1.EdgeDetectionFilterH(A_enc, type, direction);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter H(Enc): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow( \"Encrypted Edge Image H\", encnum2Mat(Edge_enc) );\n    vector < vector<double> > Edge_dec = pp.decryptMatrix(Edge_enc);\n    imshow( \"Decrypted Edge Image H\", Double2Mat(Edge_dec) );\n    cout << \"Root Mean Square Error in Edge image H: \"<<getRMSE(dst,Double2Mat(Edge_dec))<<endl;\n    vector < vector<double> > Edge_dec_fixed;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        Edge_dec_fixed = getAbsolute(Edge_dec);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter in H(Enc_post): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow( \"Decrypted Edge Image H(Absolute)\", Double2Mat(Edge_dec_fixed) );\n    cout << \"Root Mean Square Error in Edge image H(Absolute): \"<<getRMSE(dst,Double2Mat(Edge_dec_fixed))<<endl;\n\n    //In vertical direction\n    direction = 'V'; //'H' for horizontal and 'V' for vertical\n    type = 'S'; //'R' Roberts, 'P' Prewitt, 'S' Sobel, 'R' Robinson, 'K' Kirsch\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        dst = img1P.EdgeDetectionFilter(src, type, direction);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter in V (Plain): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow( \"Edge Image V\", dst );\n    //In encrypted domain\n    //vector < vector<encnum> > Edge_enc;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        Edge_enc = img1.EdgeDetectionFilterH(A_enc, type, direction);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter V(Enc): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow( \"Encrypted Edge Image V\", encnum2Mat(Edge_enc) );\n    Edge_dec = pp.decryptMatrix(Edge_enc);\n    imshow( \"Decrypted Edge Image V\", Double2Mat(Edge_dec) );\n    cout << \"Root Mean Square Error in Edge image V: \"<<getRMSE(dst,Double2Mat(Edge_dec))<<endl;\n    vector < vector<double> > Edge_dec_fixedV;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        Edge_dec_fixedV = getAbsolute(Edge_dec);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter in V(Enc_post): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow( \"Decrypted Edge Image V(Absolute)\", Double2Mat(Edge_dec_fixedV) );\n    cout << \"Root Mean Square Error in Edge image V(Absolute): \"<<getRMSE(dst,Double2Mat(Edge_dec_fixedV))<<endl;\n\n\tvector < vector<double> > EdgeTotal;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n\t  for (size_t i = 0; i < n_iteration; i++) {\n        EdgeTotal = AddAbsolute(Edge_dec_fixed,Edge_dec_fixedV);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Edge filter (Add abs_post): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow( \"Decrypted Edge Image Total \", Double2Mat(EdgeTotal) );\n\n    //Test morphological operations\n    // Load an image from file\n    Mat srcB = imread( \"butterfly-11.jpg\", 0); //0 --> gray, 1 --> RGB image\n    srcB = srcB > 128; // Convert gray to binary\n    //show the loaded image\n    imshow( \"Original Binary Image\", srcB );\n\n    Mat dstB;\n    dstB = srcB.clone(); //Copy of src as initial value\n\n    int element_shape = MORPH_RECT;\n    Mat element = getStructuringElement(element_shape, Size(3, 3), Point(-1, -1) );\n    vector < vector<double> > element_d = Mat2Double(element);\n\n    int rowsB = srcB.rows;\n    int colsB = srcB.cols;\n    vector < vector<double> > B(rowsB, vector<double>(colsB));\n    B = Mat2Double(srcB);\n    //Encrypt image\n    vector < vector<encnum> > B_enc = p.encryptMatrix(B);\n    //imshow( \"Encrypted Binary Image\", encnum2Mat(B_enc) );\n\n    vector < vector<encnum> > morph_enc;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        morph_enc = img1.morphH(B_enc, element_d);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Morph (Enc): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    //imshow( \"Encrypted Morphological Image\", encnum2Mat(morph_enc) );\n    vector < vector<double> > morph_dec = pp.decryptMatrix(morph_enc);\n    //Post processing for erosion/dilation\n    vector < vector<double> > morph_dec_erode;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        morph_dec_erode = erodePost(morph_dec);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Morph (Enc_post_Erode): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow( \"Decrypted eroded Image\", Double2Mat(morph_dec_erode) );\n\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        erode(srcB, dstB, element);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Morph (Plain_Erode): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow(\"Erode OpenCV\",dstB);\n    cout << \"Root Mean Square Error in eroded image: \"<<getRMSE(dstB,Double2Mat(morph_dec_erode))<<endl;\n\n    vector < vector<double> > morph_dec_dilate;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        morph_dec_dilate = dilatePost(morph_dec);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Morph (Enc_post_Dilate): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow( \"Decrypted dilated Image\", Double2Mat(morph_dec_dilate) );\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        dilate(srcB, dstB, element);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Morph (Plain_Dilate): \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    imshow(\"Dilate OpenCV\",dstB);\n    cout << \"Root Mean Square Error in dilated image: \"<<getRMSE(dstB,Double2Mat(morph_dec_dilate))<<endl;\n\n    //wait for a key press infinitely\n    waitKey(0);\n}\n\n/*\n * Testing New Floating point Paillier with Images\n */\nint main(int argc, char** argv) {\n\n    testImagePaillier(); /*For generating images*/\n    //testImagePaillier_N(10); /*N = 10 to measure time*/\n    return 0;\n}\n", "meta": {"hexsha": "042c3e8f3f022dcb4205cd2568e633271da7f714", "size": 43456, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Source/test_Paillier_Image.cc", "max_stars_repo_name": "TarekIbnZiad/CryptoImg", "max_stars_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-05T18:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T07:33:10.000Z", "max_issues_repo_path": "Source/test_Paillier_Image.cc", "max_issues_repo_name": "TarekIbnZiad/CryptoImg", "max_issues_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_issues_repo_licenses": ["MIT"], "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/test_Paillier_Image.cc", "max_forks_repo_name": "TarekIbnZiad/CryptoImg", "max_forks_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-11T00:32:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T23:35:20.000Z", "avg_line_length": 42.396097561, "max_line_length": 121, "alphanum_fraction": 0.6382547865, "num_tokens": 13534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5140487533609277}}
{"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 linear_manifold_regularizer \n    and empirical_kernel_map from the dlib C++ Library.\n\n    This example program assumes you are familiar with some general elements of \n    the library.  In particular, you should have at least read the svm_ex.cpp \n    and matrix_ex.cpp examples.  You should also have read the empirical_kernel_map_ex.cpp\n    example program as the present example builds upon it.\n\n\n\n    This program shows an example of what is called semi-supervised learning.  \n    That is, a small amount of labeled data is augmented with a large amount \n    of unlabeled data.  A learning algorithm is then run on all the data \n    and the hope is that by including the unlabeled data we will end up with\n    a better result.\n\n\n    In this particular example we will generate 200,000 sample points of\n    unlabeled data along with 2 samples of labeled data.  The sample points\n    will be drawn randomly from two concentric circles.  One labeled data\n    point will be drawn from each circle.  The goal is to learn to\n    correctly separate the two circles using only the 2 labeled points \n    and the unlabeled data.\n\n    To do this we will first run an approximate form of k nearest neighbors\n    to determine which of the unlabeled samples are closest together.  We will\n    then make the manifold assumption, that is, we will assume that points close\n    to each other should share the same classification label.  \n\n    Once we have determined which points are near neighbors we will use the \n    empirical_kernel_map and linear_manifold_regularizer to transform all the \n    data points into a new vector space where any linear rule will have similar \n    output for points which we have decided are near neighbors.\n\n    Finally, we will classify all the unlabeled data according to which of \n    the two labeled points are nearest.  Normally this would not work but by \n    using the manifold assumption we will be able to successfully classify\n    all the unlabeled data.\n\n\n    \n    For further information on this subject you should begin with the following\n    paper as it discusses a very similar application of manifold regularization.\n\n        Beyond the Point Cloud: from Transductive to Semi-supervised Learning\n        by Vikas Sindhwani, Partha Niyogi, and Mikhail Belkin\n\n\n\n\n                    ******** SAMPLE PROGRAM OUTPUT ********\n\n    Testing manifold regularization with an intrinsic_regularization_strength of 0.\n    number of edges generated: 49998\n    Running simple test...\n    error: 0.37022\n    error: 0.44036\n    error: 0.376715\n    error: 0.307545\n    error: 0.463455\n    error: 0.426065\n    error: 0.416155\n    error: 0.288295\n    error: 0.400115\n    error: 0.46347\n\n    Testing manifold regularization with an intrinsic_regularization_strength of 10000.\n    number of edges generated: 49998\n    Running simple test...\n    error: 0\n    error: 0\n    error: 0\n    error: 0\n    error: 0\n    error: 0\n    error: 0\n    error: 0\n    error: 0\n    error: 0\n\n\n*/\n\n#include <dlib/manifold_regularization.h>\n#include <dlib/svm.h>\n#include <dlib/rand.h>\n#include <dlib/statistics.h>\n#include <iostream>\n#include <vector>\n#include <ctime>\n\n\nusing namespace std;\nusing namespace dlib;\n\n// ----------------------------------------------------------------------------------------\n\n// First let's make a typedef for the kind of samples we will be using. \ntypedef matrix<double, 0, 1> sample_type;\n\n// We will be using the radial_basis_kernel in this example program.\ntypedef radial_basis_kernel<sample_type> kernel_type;\n\n// ----------------------------------------------------------------------------------------\n\nvoid generate_circle (\n    std::vector<sample_type>& samples,\n    double radius,\n    const long num\n);\n/*!\n    requires\n        - num > 0\n        - radius > 0\n    ensures\n        - generates num points centered at (0,0) with the given radius.  Adds these\n          points into the given samples vector.\n!*/\n\n// ----------------------------------------------------------------------------------------\n\nvoid test_manifold_regularization (\n    const double intrinsic_regularization_strength\n);\n/*!\n    ensures\n        - Runs an example test using the linear_manifold_regularizer with the given\n          intrinsic_regularization_strength.   \n!*/\n\n// ----------------------------------------------------------------------------------------\n\nint main()\n{\n    // Run the test without any manifold regularization. \n    test_manifold_regularization(0);\n\n    // Run the test with manifold regularization.  You can think of this number as\n    // a measure of how much we trust the manifold assumption.  So if you are really\n    // confident that you can select neighboring points which should have the same\n    // classification then make this number big.   \n    test_manifold_regularization(10000.0);\n}\n\n// ----------------------------------------------------------------------------------------\n\nvoid test_manifold_regularization (\n    const double intrinsic_regularization_strength\n)\n{\n    cout << \"Testing manifold regularization with an intrinsic_regularization_strength of \" \n         << intrinsic_regularization_strength << \".\\n\";\n\n    std::vector<sample_type> samples;\n\n    // Declare an instance of the kernel we will be using.  \n    const kernel_type kern(0.1);\n\n    const unsigned long num_points = 100000;\n\n    // create a large dataset with two concentric circles.  There will be 100000 points on each circle\n    // for a total of 200000 samples.\n    generate_circle(samples, 2, num_points);  // circle of radius 2\n    generate_circle(samples, 4, num_points);  // circle of radius 4\n\n    // Create a set of sample_pairs that tells us which samples are \"close\" and should thus \n    // be classified similarly.  These edges will be used to define the manifold regularizer.\n    // To find these edges we use a simple function that samples point pairs randomly and \n    // returns the top 5% with the shortest edges.\n    std::vector<sample_pair> edges;\n    find_percent_shortest_edges_randomly(samples, squared_euclidean_distance(), 0.05, 1000000, time(0), edges);\n\n    cout << \"number of edges generated: \" << edges.size() << endl;\n\n    empirical_kernel_map<kernel_type> ekm;\n\n    // Since the circles are not linearly separable we will use an empirical kernel map to \n    // map them into a space where they are separable.  We create an empirical_kernel_map \n    // using a random subset of our data samples as basis samples.  Note, however, that even\n    // though the circles are linearly separable in this new space given by the empirical_kernel_map\n    // we still won't be able to correctly classify all the points given just the 2 labeled examples.\n    // We will need to make use of the nearest neighbor information stored in edges.  To do that\n    // we will use the linear_manifold_regularizer.\n    ekm.load(kern, randomly_subsample(samples, 50));\n\n    // Project all the samples into the span of our 50 basis samples\n    for (unsigned long i = 0; i < samples.size(); ++i)\n        samples[i] = ekm.project(samples[i]);\n\n\n    // Now create the manifold regularizer.  The result is a transformation matrix that\n    // embodies the manifold assumption discussed above.  \n    linear_manifold_regularizer<sample_type> lmr;\n    // use_gaussian_weights is a function object that tells lmr how to weight each edge.  In this\n    // case we let the weight decay as edges get longer.  So shorter edges are more important than\n    // longer edges.\n    lmr.build(samples, edges, use_gaussian_weights(0.1));\n    const matrix<double> T = lmr.get_transformation_matrix(intrinsic_regularization_strength);\n\n    // Apply the transformation generated by the linear_manifold_regularizer to \n    // all our samples.\n    for (unsigned long i = 0; i < samples.size(); ++i)\n        samples[i] = T*samples[i];\n\n\n    // For convenience, generate a projection_function and merge the transformation\n    // matrix T into it.  That is, we will have: proj(x) == T*ekm.project(x).\n    projection_function<kernel_type> proj = ekm.get_projection_function();\n    proj.weights = T*proj.weights;\n\n    cout << \"Running simple test...\" << endl;\n\n    // Pick 2 different labeled points.  One on the inner circle and another on the outer.  \n    // For each of these test points we will see if using the single plane that separates\n    // them is a good way to separate the concentric circles.  We also do this a bunch \n    // of times with different randomly chosen points so we can see how robust the result is.\n    for (int itr = 0; itr < 10; ++itr)\n    {\n        std::vector<sample_type> test_points;\n        // generate a random point from the radius 2 circle\n        generate_circle(test_points, 2, 1);\n        // generate a random point from the radius 4 circle\n        generate_circle(test_points, 4, 1);\n\n        // project the two test points into kernel space.  Recall that this projection_function\n        // has the manifold regularizer incorporated into it.  \n        const sample_type class1_point = proj(test_points[0]);\n        const sample_type class2_point = proj(test_points[1]);\n\n        double num_wrong = 0;\n\n        // Now attempt to classify all the data samples according to which point\n        // they are closest to.  The output of this program shows that without manifold \n        // regularization this test will fail but with it it will perfectly classify\n        // all the points.\n        for (unsigned long i = 0; i < samples.size(); ++i)\n        {\n            double distance_to_class1 = length(samples[i] - class1_point);\n            double distance_to_class2 = length(samples[i] - class2_point);\n\n            bool predicted_as_class_1 = (distance_to_class1 < distance_to_class2);\n\n            bool really_is_class_1 = (i < num_points);\n\n            // now count how many times we make a mistake\n            if (predicted_as_class_1 != really_is_class_1)\n                ++num_wrong;\n        }\n\n        cout << \"error: \"<< num_wrong/samples.size() << endl;\n    }\n\n    cout << endl;\n}\n\n// ----------------------------------------------------------------------------------------\n\ndlib::rand rnd;\n\nvoid generate_circle (\n    std::vector<sample_type>& samples,\n    double radius,\n    const long num\n)\n{\n    sample_type m(2,1);\n\n    for (long i = 0; i < num; ++i)\n    {\n        double sign = 1;\n        if (rnd.get_random_double() < 0.5)\n            sign = -1;\n        m(0) = 2*radius*rnd.get_random_double()-radius;\n        m(1) = sign*sqrt(radius*radius - m(0)*m(0));\n\n        samples.push_back(m);\n    }\n}\n\n// ----------------------------------------------------------------------------------------\n\n", "meta": {"hexsha": "9c6f10f26a80aeb2da8fdf23c7c4d131bd89f05b", "size": 10782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/examples/linear_manifold_regularizer_ex.cpp", "max_stars_repo_name": "maxmert/nlp-mitie", "max_stars_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "examples/linear_manifold_regularizer_ex.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "examples/linear_manifold_regularizer_ex.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 37.8315789474, "max_line_length": 111, "alphanum_fraction": 0.6574846967, "num_tokens": 2390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5140487490980763}}
{"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_IFREXP_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_IFREXP_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-ieee\n    This function object computes a mantissa and an exponent pair for the input\n\n\n    @par Header <boost/simd/function/ifrexp.hpp>\n\n    @par Semantic:\n\n    For every parameter of floating type @c T\n\n    @code\n    std::tie(m, e)= ifrexp(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    as_integer_t<T> e = exponent(x)+1;\n    T m = mantissa(x)/2;\n    @endcode\n\n    @par Note:\n\n    if you need floating type exponent (unlike the standard)  use @ref frexp\n\n    This function splits a floating point value \\f$x\\f$ in a signed mantissa \\f$m\\f$ and\n    an exponent \\f$e\\f$ so that:  \\f$x = m\\times 2^e\\f$,\n    with absolute value of \\f$m \\in [0.5, 1[\\f$ (except for \\f$x = 0\\f$)\n\n    Without the pedantic_ decorator  @ref Nan or @ref Inf are not handled properly.\n\n    @warningbox{Take care that these results differ from the returns of the functions @ref mantissa\n    and @ref exponent}\n\n    @par Decorators\n\n     - pedantic_ slower, but special values as @ref Nan or @ref Inf are handled properly.\n\n     - std_ transmits the call to @c std::frexp.\n\n    @see exponent, mantissa, frexp\n\n\n    @par Example:\n\n      @snippet ifrexp.cpp ifrexp\n\n    @par Possible output:\n\n      @snippet ifrexp.txt ifrexp\n\n  **/\n  std::pair<IEEEValue, as_integer_t<IEEEValue>> ifrexp(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/ifrexp.hpp>\n#include <boost/simd/function/simd/ifrexp.hpp>\n\n#endif\n", "meta": {"hexsha": "2299a2e8aa0f84af49f8d11affdc2544dc3fb32c", "size": 1979, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/ifrexp.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/function/ifrexp.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/function/ifrexp.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": 25.0506329114, "max_line_length": 100, "alphanum_fraction": 0.6159676604, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5140487446895177}}
{"text": "/**\n * Exercise 8 : Read in a gph-file, interpretes it as a Steiner-problem and solves it.\n *\n * @author FirstSanny\n */\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <utility>\n#include <boost/program_options.hpp>\n#include <boost/timer/timer.hpp>\n#include \"Steiner.h\"\n#include \"GraphChecker.h\"\n\n\n// Constants\nnamespace {\n\tconst char* FILEEND = \".gph\";\n\tconst int MAX_FOR_DEFAULT_TERMINALS = 100;\n\tconst int DEFAULT_THREAD_NUMBER = 8;\n}\n\n\n// declaring print\nusing std::cout;\nusing std::endl;\nusing std::flush;\nusing std::cerr;\nusing std::string;\n\n\n// declaring types\nnamespace po = boost::program_options;\nusing BoostTimer = boost::timer::cpu_timer;\nusing BoostTimes = boost::timer::cpu_times;\nusing Primes = std::vector<int >;\n\n\n/**\n * Computes all primes less than vertexCount\n * by beginning with the prime 2 and trying to divide all numbers smaller than vertexCount\n * and try do divide by all found primes.\n */\nPrimes getPrimes(unsigned int vertexCount) {\n\tPrimes primes = Primes();\n\tprimes.push_back(2);\n\tfor (unsigned int i = 3; i < vertexCount; i++) {\n\t\tchar isPrime = true;\n\t\tfor (int prime : primes) {\n\t\t\tif (i % prime == 0) {\n\t\t\t\tisPrime = false;\n\t\t\t}\n\t\t}\n\t\tif (isPrime) {\n\t\t\tprimes.push_back(i);\n\t\t}\n\t}\n\treturn primes;\n}\n\n\n/** Parsing the arguments given via command line */\npo::variables_map parseCommandLine(po::options_description desc, int argn,\n\t\tchar* argv[]) {\n\tdesc.add_options()//\n\t\t\t(\"help,h\", \"produce help message\")//\n\t\t\t(\"start_nodes,s\", po::value<std::vector<int >>(),\"nodes, where to start\")//\n\t\t\t(\"thread_number,t\", po::value<int>(), \"number of threads for parallelization\")//\n\t\t\t(\"input_file,i\", 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\n\n/** Reading in a Graphfile, computes the Steiner */\nint main(int argn, char *argv[]) {\n\tBoostTimer timerProgram;\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\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\tif(filename.find(FILEEND) == std::string::npos){\n\t\tfilename += FILEEND;\n\t}\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\tstd::vector<int > startnodes;\n\tif(vm.count(\"start_nodes\") == 0){\n\t\tcout << \"Using default startnodes (first 100 primes)\" << endl;\n\t} else {\n\t\tstartnodes = vm[\"start_node\"].as<std::vector<int >>();\n\t}\n\n\tint threadNumber;\n\tif(vm.count(\"thread_number\") == 0){\n\t\tcout << \"Using default number of threads (8)\" << endl;\n\t\tthreadNumber = DEFAULT_THREAD_NUMBER;\n\t} else {\n\t\tthreadNumber = vm[\"thread_number\"].as<int >();\n\t}\n\n\tcout << endl;\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...\" << flush;\n\tint i = 0;\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->at(i) = std::make_pair(start, end);\n\t\tweights->at(i) = weight;\n\t\ti++;\n\t\tline.clear();\n\t}\n\tcout << \"done\" << endl << endl;\n\n\tPrimes terminals = getPrimes(vertexCount);\n\tif(startnodes.empty()){\n\t\tfor (unsigned int i = 0;\n\t\t\t\ti < MAX_FOR_DEFAULT_TERMINALS && i < terminals.size(); i++) {\n\t\t\tstartnodes.push_back(terminals[i]);\n\t\t}\n\t}\n\n\tcout << \"Solves Steiner-tree for \" << startnodes.size() << \" startnodes...\" << flush;\n\n\tBoostTimer timerSteiner;\n\tSteiner** steiners = new Steiner*[startnodes.size()];\n\t#pragma omp parallel for num_threads(threadNumber)\n\tfor(unsigned int i = 0; i < startnodes.size(); i++){\n\t\tsteiners[i] = new Steiner();\n\t\tsteiners[i]->computeSteinerTree(vertexCount, edges, *weights, terminals, startnodes[i]);\n\t}\n\ttimerSteiner.stop();\n\tBoostTimes timesSteiner = timerSteiner.elapsed();\n\tcout << \"done\" << endl;\n\n\tSteiner* s = steiners[0];\n\tint node = startnodes[0];\n\tint weight = s->getWeight();\n\tcout << \"Searching the one with least weight...\" << flush;\n\tfor(unsigned int i = 0; i < startnodes.size(); i++){\n\t\tif(weight > steiners[i]->getWeight()){\n\t\t\ts = steiners[i];\n\t\t\tnode = startnodes[i];\n\t\t\tweight = steiners[i]->getWeight();\n\t\t}\n\t}\n\tcout << \"done\" << endl;\n\tcout << \"It's the one with startnode \" << node << endl << endl;\n\n\n\tcout << \"Checking for cycle...\" << flush;\n\tEdges steinerEdges = s->getEdges();\n\tGraphChecker* checker = new GraphChecker(steinerEdges, s->getNodes(), terminals);\n\tif(checker->hasCycle()){\n\t\tcout << \"failed\" << endl;\n\t\treturn 1;\n\t}\n\tcout << \"passed\" << endl;\n\n\tcout << \"Checking if graph is connected...\" << flush;\n\tif(!checker->isConnected()){\n\t\tcout << \"failed\" << endl;\n\t\treturn 1;\n\t}\n\tcout << \"passed\" << endl;\n\n\tcout << \"Checking if all terminals are included...\" << flush;\n\tif(!checker->containsAllTerminals()){\n\t\tcout << \"failed\" << endl;\n\t\treturn 1;\n\t}\n\tcout << \"passed\" << endl << endl;\n\n\tcout << \"TLEN: \" << s->getWeight() << endl;\n\n\tcout << \"TREE:\";\n\tfor(unsigned int i = 0; i < steinerEdges.size(); i++){\n\t\tEdge edge = steinerEdges[i];\n\t\tcout << \" (\" << edge.first << \", \" << edge.second << \")\";\n\t}\n\tcout << endl;\n\n\ttimerProgram.stop();\n\tBoostTimes timesProgram = timerProgram.elapsed();\n\tcout << \"TIME: \" << boost::timer::format(timesProgram, 4, \"%t\") << endl;\n\tcout << \"WALL: \" << boost::timer::format(timesSteiner, 4, \"%w\") << endl;\n\n\tdelete edges;\n\tdelete weights;\n\tdelete checker;\n\tfor(unsigned int i = 0; i < startnodes.size(); i++){\n\t\tdelete steiners[i];\n\t}\n\tdelete [] steiners;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "3b4c5e5908def5e5a9a0bafbcf8d6a0e3d93be23", "size": 6352, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sanny/ex10/src/c/ex10.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/ex10/src/c/ex10.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/ex10/src/c/ex10.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": 25.1067193676, "max_line_length": 90, "alphanum_fraction": 0.6426322418, "num_tokens": 1767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5140487443981027}}
{"text": "/**\n * @file tests/main_tests/hmm_train_test.cpp\n * @author Daivik Nema\n *\n * Test mlpackMain() of hmm_train_main.cpp.\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 <string>\n#include <fstream>\n\n#define BINDING_TYPE BINDING_TYPE_TEST\nstatic const std::string testName = \"HMMTrain\";\n\n#include <mlpack/core.hpp>\n#include <mlpack/core/util/mlpack_main.hpp>\n#include \"test_helper.hpp\"\n#include <mlpack/methods/hmm/hmm_train_main.cpp>\n#include <mlpack/methods/hmm/hmm_model.hpp>\n\n#include \"../catch.hpp\"\n#include \"../test_catch_tools.hpp\"\n\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n\nusing namespace mlpack;\n\nstruct HMMTrainMainTestFixture\n{\n public:\n  HMMTrainMainTestFixture()\n  {\n    // Cache in the options for this program.\n    IO::RestoreSettings(testName);\n  }\n\n  ~HMMTrainMainTestFixture()\n  {\n    // Clear the settings.\n    bindings::tests::CleanMemory();\n    IO::ClearSettings();\n  }\n};\n\ninline void FileExists(std::string fileName)\n{\n  ifstream ifp(fileName);\n  if (!ifp.good())\n    FAIL(\"Bad stream \" + fileName);\n  ifp.close();\n}\n\ninline void CheckMatricesDiffer(arma::mat& a, arma::mat& b, double tolerance)\n{\n  bool dimsEqual = (a.n_rows == b.n_rows)\n    && (a.n_cols == b.n_cols)\n    && (a.n_elem == b.n_elem);\n  bool valsEqual = true;\n  if (dimsEqual)\n  {\n    for (size_t i = 0; i < a.n_elem; ++i)\n    {\n      if (std::abs(a[i]) < tolerance / 2)\n        valsEqual = valsEqual && (std::abs(b[i]) < tolerance / 2);\n      else\n        valsEqual = valsEqual && (std::abs(a[i] - b[i]) < tolerance);\n    }\n  }\n  REQUIRE(!(dimsEqual && valsEqual));\n}\n\ninline void ApproximatelyEqual(HMMModel& h1,\n                               HMMModel& h2,\n                               double tolerance = 1.0)\n{\n  REQUIRE(h1.Type() == h2.Type());\n  HMMType  hmmType = h1.Type();\n  if (hmmType ==  DiscreteHMM)\n  {\n    CheckMatrices(\n        h1.DiscreteHMM()->Transition()*100,\n        h2.DiscreteHMM()->Transition()*100,\n        tolerance);\n    CheckMatrices(\n        h1.DiscreteHMM()->Transition()*100,\n        h2.DiscreteHMM()->Transition()*100,\n        tolerance);\n\n    // Check if emission dists are equal\n    std::vector<distribution::DiscreteDistribution> d1 =\n        h1.DiscreteHMM()->Emission();\n    std::vector<distribution::DiscreteDistribution> d2 =\n        h2.DiscreteHMM()->Emission();\n\n    REQUIRE(d1.size() == d2.size());\n\n    size_t states = d1.size();\n    for (size_t i = 0; i < states; ++i)\n      for (size_t j = 0; j < d1[i].Dimensionality(); ++j)\n        CheckMatrices(d1[i].Probabilities(j)*100,\n            d2[i].Probabilities(j)*100,\n            tolerance);\n  }\n  else if (hmmType == GaussianHMM)\n  {\n    CheckMatrices(\n        h1.GaussianHMM()->Transition()*100,\n        h2.GaussianHMM()->Transition()*100,\n        tolerance);\n    CheckMatrices(\n        h1.GaussianHMM()->Initial()*100,\n        h2.GaussianHMM()->Initial()*100,\n        tolerance);\n    // Check if emission dists are equal by comparing the mean and coviariance\n    std::vector<distribution::GaussianDistribution> d1 =\n        h1.GaussianHMM()->Emission();\n    std::vector<distribution::GaussianDistribution> d2 =\n        h2.GaussianHMM()->Emission();\n\n    REQUIRE(d1.size() == d2.size());\n\n    size_t states = d1.size();\n    for (size_t i=0; i < states; ++i)\n    {\n      CheckMatrices(d1[i].Mean()*100, d2[i].Mean()*100, tolerance);\n      CheckMatrices(d1[i].Covariance()*100, d2[i].Covariance()*100, tolerance);\n    }\n  }\n  else if (hmmType == GaussianMixtureModelHMM)\n  {\n    CheckMatrices(\n        h1.GMMHMM()->Transition()*100,\n        h2.GMMHMM()->Transition()*100,\n        tolerance);\n    CheckMatrices(\n        h1.GMMHMM()->Initial()*100,\n        h2.GMMHMM()->Initial()*100,\n        tolerance);\n    // Check if emission dists are equal\n    std::vector<gmm::GMM> d1 = h1.GMMHMM()->Emission();\n    std::vector<gmm::GMM> d2 = h2.GMMHMM()->Emission();\n\n    REQUIRE(d1.size() == d2.size());\n\n    size_t states = d1.size();\n    for (size_t i=0; i < states; ++i)\n    {\n      REQUIRE(d1[i].Gaussians() == d2[i].Gaussians());\n      size_t gaussians = d1[i].Gaussians();\n      for (size_t j=0; j<gaussians; ++j)\n      {\n        CheckMatrices(d1[i].Component(j).Mean()*100,\n            d2[i].Component(j).Mean()*100,\n            tolerance);\n        CheckMatrices(d1[i].Component(j).Covariance()*100,\n            d2[i].Component(j).Covariance()*100,\n            tolerance);\n      }\n      CheckMatrices(d1[i].Weights()*100, d2[i].Weights()*100, tolerance);\n    }\n  }\n  else if (hmmType == DiagonalGaussianMixtureModelHMM)\n  {\n    CheckMatrices(\n        h1.DiagGMMHMM()->Transition()*100,\n        h2.DiagGMMHMM()->Transition()*100,\n        tolerance);\n    CheckMatrices(\n        h1.DiagGMMHMM()->Initial()*100,\n        h2.DiagGMMHMM()->Initial()*100,\n        tolerance);\n    // Check if emission dists are equal.\n    std::vector<gmm::DiagonalGMM> d1 = h1.DiagGMMHMM()->Emission();\n    std::vector<gmm::DiagonalGMM> d2 = h2.DiagGMMHMM()->Emission();\n\n    REQUIRE(d1.size() == d2.size());\n\n    // Check if gaussian, mean, covariance and weights are equal.\n    size_t states = d1.size();\n    for (size_t i = 0; i < states; ++i)\n    {\n      REQUIRE(d1[i].Gaussians() == d2[i].Gaussians());\n      size_t gaussians = d1[i].Gaussians();\n      for (size_t j = 0; j < gaussians; ++j)\n      {\n        CheckMatrices(d1[i].Component(j).Mean()*100,\n            d2[i].Component(j).Mean()*100,\n            tolerance);\n        CheckMatrices(d1[i].Component(j).Covariance()*100,\n            d2[i].Component(j).Covariance()*100,\n            tolerance);\n      }\n      CheckMatrices(d1[i].Weights()*100, d2[i].Weights()*100, tolerance);\n    }\n  }\n}\n\n// Make sure that the number of states cannot be negative\nTEST_CASE_METHOD(HMMTrainMainTestFixture, \"HMMTrainStatesTest\",\n                 \"[HMMTrainMainTest][BindingTests]\")\n{\n  std::string inputFileName = \"hmm_train_obs.csv\";\n  int states = -3;  // Invalid!\n  std::string hmmType = \"discrete\";\n\n  FileExists(inputFileName);\n  SetInputParam(\"input_file\", std::move(inputFileName));\n  SetInputParam(\"states\", states);\n  SetInputParam(\"type\", std::move(hmmType));\n\n  Log::Fatal.ignoreInput = true;\n  REQUIRE_THROWS_AS(mlpackMain(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n}\n\n// Make sure that tolerance is non negative\nTEST_CASE_METHOD(HMMTrainMainTestFixture, \"HMMTrainToleranceNonNegative\",\n                 \"[HMMTrainMainTest][BindingTests]\")\n{\n  std::string inputFileName = \"hmm_train_obs.csv\";\n  int states = 3;\n  std::string hmmType = \"gaussian\";\n  double tol = - 100;  // Invalid\n\n  FileExists(inputFileName);\n  SetInputParam(\"input_file\", std::move(inputFileName));\n  SetInputParam(\"states\", states);\n  SetInputParam(\"type\", std::move(hmmType));\n  SetInputParam(\"tolerance\", tol);\n\n  Log::Fatal.ignoreInput = true;\n  REQUIRE_THROWS_AS(mlpackMain(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n}\n\n// Make sure an error is thrown if type is something other than\n// \"discrete\", \"gaussian\" or \"gmm\"\nTEST_CASE_METHOD(HMMTrainMainTestFixture, \"HMMTrainTypeTest\",\n                 \"[HMMTrainMainTest][BindingTests]\")\n{\n  std::string inputFileName = \"hmm_train_obs.csv\";\n  int states = 3;\n  std::string hmmType = \"some-not-supported-possibly-non-type\";\n\n  FileExists(inputFileName);\n  SetInputParam(\"input_file\", std::move(inputFileName));\n  SetInputParam(\"states\", states);\n  SetInputParam(\"type\", std::move(hmmType));\n\n  Log::Fatal.ignoreInput = true;\n  REQUIRE_THROWS_AS(mlpackMain(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n}\n\n// Make sure that the number of gaussians cannot be less than 0\nTEST_CASE_METHOD(HMMTrainMainTestFixture, \"HMMTrainGaussianTest\",\n                 \"[HMMTrainMainTest][BindingTests]\")\n{\n  std::string inputFileName = \"hmm_train_obs.csv\";\n  int states = 3;\n  std::string hmmType = \"gmm\";\n  int gaussians = -2;\n\n  FileExists(inputFileName);\n  SetInputParam(\"input_file\", std::move(inputFileName));\n  SetInputParam(\"states\", states);\n  SetInputParam(\"type\", std::move(hmmType));\n  SetInputParam(\"gaussians\", gaussians);\n\n  Log::Fatal.ignoreInput = true;\n  REQUIRE_THROWS_AS(mlpackMain(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n}\n\n// Make sure that the number of Gaussians cannot be less than 0.\nTEST_CASE_METHOD(HMMTrainMainTestFixture, \"HMMTrainDiagonalGaussianTest\",\n                 \"[HMMTrainMainTest][BindingTests]\")\n{\n  std::string inputFileName = \"hmm_train_obs.csv\";\n  int states = 3;\n  std::string hmmType = \"diag_gmm\";\n  int gaussians = -2;\n\n  FileExists(inputFileName);\n  SetInputParam(\"input_file\", std::move(inputFileName));\n  SetInputParam(\"states\", states);\n  SetInputParam(\"type\", std::move(hmmType));\n  SetInputParam(\"gaussians\", gaussians);\n\n  Log::Fatal.ignoreInput = true;\n  REQUIRE_THROWS_AS(mlpackMain(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n}\n\n// Make sure that model reuse is possible and work properly\nTEST_CASE_METHOD(HMMTrainMainTestFixture, \"HMMTrainReuseDiscreteModelTest\",\n                 \"[HMMTrainMainTest][BindingTests]\")\n{\n  std::string inputObsFileName = \"hmm_train_obs.csv\";\n  std::string inputLabFileName = \"hmm_train_lab.csv\";\n  std::string hmmType = \"discrete\";\n  int states = 3;\n\n  FileExists(inputObsFileName);\n  FileExists(inputLabFileName);\n  // Make sure that the size of the\n  // training seq, and training labels is same\n  arma::mat trainObs, trainLab;\n  data::Load(inputObsFileName, trainObs);\n  data::Load(inputLabFileName, trainLab);\n  REQUIRE(trainObs.n_rows == trainLab.n_rows);\n\n  SetInputParam(\"input_file\", std::move(inputObsFileName));\n  SetInputParam(\"labels_file\", std::move(inputLabFileName));\n  SetInputParam(\"type\", std::move(hmmType));\n  SetInputParam(\"states\", states);\n\n  mlpackMain();\n\n  HMMModel h1 = *(IO::GetParam<HMMModel*>(\"output_model\"));\n\n  SetInputParam(\"input_model\", IO::GetParam<HMMModel*>(\"output_model\"));\n\n  IO::GetSingleton().Parameters()[\"type\"].wasPassed = false;\n  IO::GetSingleton().Parameters()[\"states\"].wasPassed = false;\n\n  mlpackMain();\n\n  HMMModel h2 = *(IO::GetParam<HMMModel*>(\"output_model\"));\n\n  ApproximatelyEqual(h1, h2);\n}\n\n// Make sure that model reuse is possible and work properly\nTEST_CASE_METHOD(HMMTrainMainTestFixture, \"HMMTrainReuseGaussianModelTest\",\n                 \"[HMMTrainMainTest][BindingTests]\")\n{\n  std::string inputObsFileName = \"hmm_train_obs.csv\";\n  std::string hmmType = \"gaussian\";\n  int states = 3;\n\n  FileExists(inputObsFileName);\n  // Make sure that the size of the\n  // training seq, and training labels is same\n  arma::mat trainObs;\n  data::Load(inputObsFileName, trainObs);\n\n  SetInputParam(\"input_file\", std::move(inputObsFileName));\n  SetInputParam(\"type\", std::move(hmmType));\n  SetInputParam(\"states\", states);\n\n  mlpackMain();\n\n  HMMModel h1 = *(IO::GetParam<HMMModel*>(\"output_model\"));\n\n  SetInputParam(\"input_model\", IO::GetParam<HMMModel*>(\"output_model\"));\n  SetInputParam(\"tolerance\", 1e10);\n\n  IO::GetSingleton().Parameters()[\"type\"].wasPassed = false;\n  IO::GetSingleton().Parameters()[\"states\"].wasPassed = false;\n\n  mlpackMain();\n\n  HMMModel h2 = *(IO::GetParam<HMMModel*>(\"output_model\"));\n\n  ApproximatelyEqual(h1, h2);\n}\n\nTEST_CASE_METHOD(HMMTrainMainTestFixture, \"HMMTrainNoLabelsReuseModelTest\",\n                 \"[HMMTrainMainTest][BindingTests]\")\n{\n  std::string inputObsFileName = \"hmm_train_obs.csv\";\n  std::string hmmType = \"discrete\";\n  int states = 3;\n  int seed = 0;\n\n  FileExists(inputObsFileName);\n  SetInputParam(\"input_file\", std::move(inputObsFileName));\n  SetInputParam(\"states\", states);\n  SetInputParam(\"type\", std::move(hmmType));\n  SetInputParam(\"seed\", seed);\n\n  // This call will train HMM using Baum-Welch training\n  mlpackMain();\n\n  HMMModel h1 = *(IO::GetParam<HMMModel*>(\"output_model\"));\n\n  SetInputParam(\"input_model\", IO::GetParam<HMMModel*>(\"output_model\"));\n\n  IO::GetSingleton().Parameters()[\"type\"].wasPassed = false;\n  IO::GetSingleton().Parameters()[\"states\"].wasPassed = false;\n\n  // Train again using Baum Welch\n  mlpackMain();\n\n  HMMModel h2 = *(IO::GetParam<HMMModel*>(\"output_model\"));\n\n  ApproximatelyEqual(h1, h2);\n}\n\n// Test batch mode\nTEST_CASE_METHOD(HMMTrainMainTestFixture, \"HMMTrainBatchModeTest\",\n                 \"[HMMTrainMainTest][BindingTests]\")\n{\n  std::string observationsFileName = \"observations.txt\";\n  std::string labelsFileName = \"labels.txt\";\n  std::string hmmType = \"discrete\";\n  int states = 2;\n\n  SetInputParam(\"input_file\", std::move(observationsFileName));\n  SetInputParam(\"labels_file\", std::move(labelsFileName));\n\n  Log::Fatal.ignoreInput = true;\n  REQUIRE_THROWS_AS(mlpackMain(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n\n  SetInputParam(\"states\", states);\n  SetInputParam(\"type\", std::move(hmmType));\n  SetInputParam(\"batch\", (bool) true);\n\n  mlpackMain();\n\n  // Now pass an observations file with extra non-existent filenames\n  observationsFileName = \"corrupt-observations-1.txt\";\n  SetInputParam(\"input_file\", std::move(observationsFileName));\n\n  Log::Fatal.ignoreInput = true;\n  REQUIRE_THROWS_AS(mlpackMain(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n\n  // Now a mismatch between #observation files and #label files\n  observationsFileName = \"corrupt-observations-2.txt\";\n  SetInputParam(\"input_file\", std::move(observationsFileName));\n\n  Log::Fatal.ignoreInput = true;\n  REQUIRE_THROWS_AS(mlpackMain(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n}\n\nTEST_CASE_METHOD(HMMTrainMainTestFixture, \"HMMTrainRetrainTest1\",\n                 \"[HMMTrainMainTest][BindingTests]\")\n{\n  std::string inputObsFile1 = \"obs1.csv\";\n  std::string type = \"discrete\";\n  int states = 2;\n  int seed = 0;\n\n  FileExists(inputObsFile1);\n  SetInputParam(\"input_file\", std::move(inputObsFile1));\n  SetInputParam(\"type\", std::move(type));\n  SetInputParam(\"states\", states);\n  SetInputParam(\"seed\", seed);\n\n  mlpackMain();\n\n  HMMModel h1 = *(IO::GetParam<HMMModel*>(\"output_model\"));\n\n  std::string inputObsFile2 = \"obs4.csv\";\n\n  IO::GetSingleton().Parameters()[\"input_file\"].wasPassed = false;\n  IO::GetSingleton().Parameters()[\"type\"].wasPassed = false;\n  IO::GetSingleton().Parameters()[\"states\"].wasPassed = false;\n\n  FileExists(inputObsFile2);\n  SetInputParam(\"input_file\", std::move(inputObsFile2));\n  SetInputParam(\"input_model\", IO::GetParam<HMMModel*>(\"output_model\"));\n\n  mlpackMain();\n\n  HMMModel h2 = *(IO::GetParam<HMMModel*>(\"output_model\"));\n\n  REQUIRE(h1.Type() == h2.Type());\n  // Since we know that type of HMMs is discrete\n  CheckMatricesDiffer(h1.DiscreteHMM()->Transition(),\n      h2.DiscreteHMM()->Transition(), 1e-50);\n}\n\n// Attempt to retrain but increase states the second time round\nTEST_CASE_METHOD(HMMTrainMainTestFixture, \"HMMTrainRetrainTest2\",\n                 \"[HMMTrainMainTest][BindingTests]\")\n{\n  // Provide no labels file\n  std::string inputObsFile1 = \"obs1.csv\";\n  std::string type = \"discrete\";\n  int states = 2;\n\n  SetInputParam(\"input_file\", std::move(inputObsFile1));\n  SetInputParam(\"type\", std::move(type));\n  SetInputParam(\"states\", states);\n\n  mlpackMain();\n\n  HMMModel h1 = *(IO::GetParam<HMMModel*>(\"output_model\"));\n\n  std::string inputObsFile2 = \"obs3.csv\";\n  std::string inputLabFile2 = \"lab1_corrupt.csv\";\n\n  SetInputParam(\"input_file\", std::move(inputObsFile2));\n  // Provide a labels file with more states than initially specified\n  SetInputParam(\"labels_file\", std::move(inputLabFile2));\n  SetInputParam(\"input_model\", IO::GetParam<HMMModel*>(\"output_model\"));\n\n  IO::GetSingleton().Parameters()[\"type\"].wasPassed = false;\n  IO::GetSingleton().Parameters()[\"states\"].wasPassed = false;\n\n  Log::Fatal.ignoreInput = true;\n  REQUIRE_THROWS_AS(mlpackMain(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n}\n\n// Attempt to retrain but change the emission distribution type\nTEST_CASE_METHOD(HMMTrainMainTestFixture, \"HMMTrainRetrainTest3\",\n                 \"[HMMTrainMainTest][BindingTests]\")\n{\n  // Provide no labels file\n  std::string inputObsFile1 = \"obs1.csv\";\n  std::string type = \"discrete\";\n  int states = 2;\n\n  SetInputParam(\"input_file\", std::move(inputObsFile1));\n  SetInputParam(\"type\", std::move(type));\n  SetInputParam(\"states\", states);\n\n  mlpackMain();\n\n  HMMModel h1 = *(IO::GetParam<HMMModel*>(\"output_model\"));\n\n  std::string inputObsFile2 = \"obs2.csv\";\n  std::string inputLabFile2 = \"lab2.csv\";\n  type = \"gaussian\";\n\n  SetInputParam(\"input_file\", std::move(inputObsFile2));\n  SetInputParam(\"labels_file\", std::move(inputLabFile2));\n  SetInputParam(\"type\", std::move(type));\n  SetInputParam(\"input_model\", IO::GetParam<HMMModel*>(\"output_model\"));\n\n  IO::GetSingleton().Parameters()[\"states\"].wasPassed = false;\n\n  mlpackMain();\n  // Note that when emission type is changed -- like in this test, a warning\n  // is printed stating that the new type is being ignored (no error is raised)\n\n  HMMModel h2 = *(IO::GetParam<HMMModel*>(\"output_model\"));\n\n  REQUIRE(h1.Type() == DiscreteHMM);\n  REQUIRE(h2.Type() == DiscreteHMM);\n  REQUIRE(h2.Type() != GaussianHMM);\n}\n", "meta": {"hexsha": "3bb124a44cffcf5015d7705cdffceb5c7de42fd8", "size": 17166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/main_tests/hmm_train_test.cpp", "max_stars_repo_name": "aronorth/mlpack", "max_stars_repo_head_hexsha": "1df3b4c32d60acd256671bc1f7ea780b96cbfc06", "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": "2020-12-18T13:33:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T13:33:24.000Z", "max_issues_repo_path": "src/mlpack/tests/main_tests/hmm_train_test.cpp", "max_issues_repo_name": "GauravSarkar/mlpack", "max_issues_repo_head_hexsha": "c889cd06df4ebbc494e7518a103f186b5232c5ee", "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/main_tests/hmm_train_test.cpp", "max_forks_repo_name": "GauravSarkar/mlpack", "max_forks_repo_head_hexsha": "c889cd06df4ebbc494e7518a103f186b5232c5ee", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0415913201, "max_line_length": 79, "alphanum_fraction": 0.6746475591, "num_tokens": 4721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.514048740280959}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\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#include <iostream>\n\n#include <geometry_test_common.hpp>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/geometry/algorithms/make.hpp>\n#include <boost/geometry/algorithms/append.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/multi_point.hpp>\n#include <boost/geometry/geometries/concepts/multi_point_concept.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <boost/geometry/io/dsv/write.hpp>\n\n#include <test_common/test_point.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\n#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n#include <initializer_list>\n#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n\ntemplate <typename P>\nbg::model::multi_point<P> create_multi_point()\n{   \n    bg::model::multi_point<P> mp1;\n    P p1;\n    bg::assign_values(p1, 1, 2, 3);\n    bg::append(mp1, p1);\n    return mp1;\n}\n\ntemplate <typename L, typename T>\nvoid check_multi_point(L& to_check, T x, T y, T z)\n{\n    BOOST_CHECK_EQUAL(bg::get<0>(to_check[0]), x);\n    BOOST_CHECK_EQUAL(bg::get<1>(to_check[0]), y);\n    BOOST_CHECK_EQUAL(bg::get<2>(to_check[0]), z);\n}\n\ntemplate <typename P>\nvoid test_default_constructor()\n{\n    bg::model::multi_point<P> mp1(create_multi_point<P>());\n    check_multi_point(mp1, 1, 2, 3);\n}\n\ntemplate <typename P>\nvoid test_copy_constructor()\n{\n    bg::model::multi_point<P> mp1 = create_multi_point<P>();\n    check_multi_point(mp1, 1, 2, 3);\n}\n\ntemplate <typename P>\nvoid test_copy_assignment()\n{\n    bg::model::multi_point<P> mp1(create_multi_point<P>()), mp2;\n    mp2 = mp1;\n    check_multi_point(mp2, 1, 2, 3);\n}\n\ntemplate <typename P>\nvoid test_concept()\n{   \n    typedef bg::model::multi_point<P> MP;\n\n    BOOST_CONCEPT_ASSERT( (bg::concepts::ConstMultiPoint<MP>) );\n    BOOST_CONCEPT_ASSERT( (bg::concepts::MultiPoint<MP>) );\n\n    typedef typename bg::coordinate_type<MP>::type T;\n    typedef typename bg::point_type<MP>::type MPP;\n    boost::ignore_unused<T, MPP>();\n}\n\ntemplate <typename P>\nvoid test_all()\n{   \n    test_default_constructor<P>();\n    test_copy_constructor<P>();\n    test_copy_assignment<P>();\n    test_concept<P>();\n}\n\ntemplate <typename P>\nvoid test_custom_multi_point(std::initializer_list<P> IL)\n{\n    bg::model::multi_point<P> mp1(IL);\n    std::ostringstream out;\n    out << bg::dsv(mp1);\n    BOOST_CHECK_EQUAL(out.str(), \"((0, 0), (1, 2), (2, 0))\");\n}\n\ntemplate <typename P>\nvoid test_custom()\n{   \n#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n    std::initializer_list<P> IL = {P(0, 0), P(1, 2), P(2, 0)};\n    test_custom_multi_point<P>(IL);\n#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n}\n\ntemplate <typename CS>\nvoid test_cs()\n{\n    test_all<bg::model::point<int, 3, CS> >();\n    test_all<bg::model::point<float, 3, CS> >();\n    test_all<bg::model::point<double, 3, CS> >();\n\n    test_custom<bg::model::point<double, 2, CS> >();\n}\n\n\nint test_main(int, char* [])\n{   \n    test_cs<bg::cs::cartesian>();\n    test_cs<bg::cs::spherical<bg::degree> >();\n    test_cs<bg::cs::spherical_equatorial<bg::degree> >();\n    test_cs<bg::cs::geographic<bg::degree> >();\n\n    test_custom<bg::model::d2::point_xy<double> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "b10af22810118d452c3bcb8a4ccd1f15153eda16", "size": 3610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/geometries/multi_point.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": "test/geometries/multi_point.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/geometry/test/geometries/multi_point.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 26.5441176471, "max_line_length": 79, "alphanum_fraction": 0.7024930748, "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5140487360181077}}
{"text": "/*\n * Copyright Andrey Semashev 2020\n *\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/*!\n * \\file counting.hpp\n *\n * This header includes all algorithms for counting bits.\n */\n\n#ifndef BOOST_BIT_OPS_COUNTING_HPP_INCLUDED_\n#define BOOST_BIT_OPS_COUNTING_HPP_INCLUDED_\n\n#include <boost/bit_ops/counting/countl_zero.hpp>\n#include <boost/bit_ops/counting/countl_one.hpp>\n#include <boost/bit_ops/counting/countr_zero.hpp>\n#include <boost/bit_ops/counting/countr_one.hpp>\n#include <boost/bit_ops/counting/popcount.hpp>\n\n#endif // BOOST_BIT_OPS_COUNTING_HPP_INCLUDED_\n", "meta": {"hexsha": "8ec3365d42b11711b43cd251d001e4544244e4ba", "size": 677, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/bit_ops/counting.hpp", "max_stars_repo_name": "Lastique/bit_ops", "max_stars_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops/counting.hpp", "max_issues_repo_name": "Lastique/bit_ops", "max_issues_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops/counting.hpp", "max_forks_repo_name": "Lastique/bit_ops", "max_forks_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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.2083333333, "max_line_length": 61, "alphanum_fraction": 0.7858197932, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5140487360181076}}
{"text": "//============================================================================\n// Name        : LBFGS_MPI.cpp\n// Author      : Yaser\n// Version     :\n// Copyright   : \n// Description : LBFGS MPI implementation\n//============================================================================\n\n/*\n ** consider quadratic function, f(x) = 0.5*\\|Ax-b\\|^2\n ** Implement LBFGS algorithm as is explained in\n ** https://en.wikipedia.org/wiki/Limited-memory_BFGS\n **\n */\n\n#include <iostream>\n#include <fstream>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <cstdlib>  /* rand, srand */\n#include <vector>\n\n#include <time.h>\n#include <boost/mpi.hpp>\nnamespace mpi = boost::mpi;\n\n#include <boost/timer/timer.hpp>\n\n#include \"solvers/OptimizationParameters.h\"\n#include \"solvers/ProblemData.h\"\n#include \"solvers/QuasiNewtonSolver.h\"\n#include \"solvers/LBFGSSolver.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[]) {\n\tmpi::environment env(argc, argv);\n\tmpi::communicator world;\n\tsrand(1);\n\tProblemData problemData;\n\tOptimizationParameters optParams;\n\toptParams.m = 1000;\n\toptParams.n = 2000;\n\toptParams.num_iterations = 10000;//100 initially\n\toptParams.lbfgs_memory = 100; //10 initially\n\toptParams.stepsize = 10 / (0.0 + optParams.n);\n\tif (world.rank() == 0) { //Generate data on node 0\n\t\tint nnz = optParams.m * optParams.n;\n\t\tproblemData.A.resize(nnz);\n\t\tfor (int i = 0; i < optParams.n; i++) {\n\t\t\tdouble tmp = 0;\n\t\t\tfor (int j = 0; j < optParams.m; j++) {\n\t\t\t\tdouble r = rand() / (RAND_MAX + 0.0);\n\t\t\t\tproblemData.A[i * optParams.m + j] = r;\n\t\t\t\ttmp += r * r;\n\t\t\t}\n\t\t\ttmp = 1 / sqrt(tmp);\n\t\t\tfor (int j = 0; j < optParams.m; j++) {\n\t\t\t\tproblemData.A[i * optParams.m + j] = problemData.A[i * optParams.m + j] * tmp;\n\t\t\t}\n\n\t\t}\n\t\tproblemData.b.resize(optParams.m);\n\t\tfor (int i = 0; i < optParams.m; i++) {\n\t\t\tproblemData.b[i] = rand() / (RAND_MAX + 0.0);\n\t\t}\n\t\tproblemData.x.resize(optParams.n, 0);\n\t}\n\n/*\n\tif (world.rank() == 0) {\n\t\tcout<<\"Amatrix: \"<<endl;\n\t\tfor (int i = 0; i < optParams.n; i++) {\n\t\t\tfor (int j = 0; j < optParams.m; j++) {\n\t\t\t\tcout<< std::setprecision(17)<<problemData.A[i*optParams.m+j]<<\"     \";\n\t\t\t}\n\t\t\tcout<<endl;\n\t\t}\n\n\t\tcout<<\"endA\"<<endl;\n\t\tcout<<\"bvec\"<<endl;\n\n\t\tfor (int i = 0; i < optParams.m; i++) {\n\t\t\tcout<< std::setprecision(17)<<problemData.b[i]<<\"     \";\n\t\t}\n\t\tcout<<\"bvecEnd\"<<endl;\n\t}\n*/\n\n\tboost::timer::cpu_timer timer;\n\tLBFGSSolver solver(problemData, optParams);\n\tboost::timer::cpu_times elapsedInInitialization = timer.elapsed();\n\tif (world.rank() == 0) { // Writes total running time\n\t\tstd::cout << \"Initialization of class took: \" << (elapsedInInitialization.user + elapsedInInitialization.system) / 1e9 << \" (sec)\" << \"  Wallclock time: \"\n\t\t\t\t<< elapsedInInitialization.wall / 1e9 << \" (sec)\" << std::endl;\n\t}\n\n\t/* this function computes and takes the step to obtain a new iterate */\n\tdouble objVal = solver.computeCurrentObjectiveValue();\n\tif (world.rank() == 0) {\n\t\tcout << \"Initial Obj Value is \" << objVal << endl;\n\t}\n\n\tfor (int it = 0; it < optParams.num_iterations; it++) {\n\n\t\ttimer.start();\n\t\tsolver.computeAndTakeStep(); // this function computes and takes the step to obtain a new iterate\n\t\tboost::timer::cpu_times computingStep = timer.elapsed();\n\n\t\ttimer.start();\n\t\tobjVal = solver.computeCurrentObjectiveValue(); // this function computes and takes the step to obtain a new iterate\n\t\tboost::timer::cpu_times objValTime = timer.elapsed();\n\n\t\tif (world.rank() == 0) { // Writes total running time\n\t\t\tstd::cout << \"Iteration: \" << it << \" ObjVal: \" << objVal << \" Times: \" << (computingStep.user + computingStep.system) / 1e9 << \" (sec)\"\n\t\t\t\t\t<< \"  Wall clock time: \" << computingStep.wall / 1e9 << \" (sec)\" << \" \" << (objValTime.user + objValTime.system) / 1e9 << \" (sec)\"\n\t\t\t\t\t<< \"  Wall clock time: \" << objValTime.wall / 1e9 << \" (sec)\" << std::endl;\n\t\t}\n\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "bc49c88e50048282186d58c12044f2356e2f76c1", "size": 3844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LBFGS_MPI.cpp", "max_stars_repo_name": "yasersharaf/LBFGS_MPI", "max_stars_repo_head_hexsha": "5c0e0b2383a1bfa74c852a2962a7d0380b03136c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LBFGS_MPI.cpp", "max_issues_repo_name": "yasersharaf/LBFGS_MPI", "max_issues_repo_head_hexsha": "5c0e0b2383a1bfa74c852a2962a7d0380b03136c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LBFGS_MPI.cpp", "max_forks_repo_name": "yasersharaf/LBFGS_MPI", "max_forks_repo_head_hexsha": "5c0e0b2383a1bfa74c852a2962a7d0380b03136c", "max_forks_repo_licenses": ["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.752, "max_line_length": 156, "alphanum_fraction": 0.605359001, "num_tokens": 1127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.721743206297598, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5140487358724004}}
{"text": "/*\nMIT License\n\nCopyright (c) 2016 Vernam Group\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 \"../include/fntru.h\"\n#include <sys/time.h>\n#include <NTL/GF2X.h>\n#include <NTL/mat_ZZ.h>\n\nusing namespace std;\n\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//And and XOR operations for test preparation\nint AND(int b0, int b1){\n\treturn(b0*b1)%2;\n}\n\nint XOR(int b0, int b1){\n\treturn(b0+b1)%2;\n}\n\n//Convert message in ZZX to int. If not bit print -1\nint ConvMessPoly(ZZX in){\n\tZZX zero, one;\n\tone = 1;\n\tzero = 0;\n\n\tif(in == 0)\n\t\treturn 0;\n\telse if(in == 1)\n\t\treturn 1;\n\telse\n\t\treturn -1;\n}\n\n//Check if all the values of boolean circuit is equal\nbool CheckBooleanCircuitResult(int midResult[], ZZX messmidResult[], int opSize){\n\tbool isEqual = true;\n\n\tfor(int i=0; i<opSize+1; i++)\n\t\tif(midResult[i] != ConvMessPoly(messmidResult[i])){\n\t\t\tisEqual = false;\n\t\t\tbreak;\n\t\t}\n\n\treturn isEqual;\n}\n\n//Print all the values of the Boolean Circuit (mid results)\nvoid PrintBooleanCircuitValues(int midResult[], ZZX messmidResult[], int opSize){\n\tfor(int i=0; i<opSize+1; i++){\n\t\tcout << \"Op\\t\" << i << \"\\t\" << midResult[i] << \"\\t\" << ConvMessPoly(messmidResult[i]) << \"\\t\" << endl;\n\t}\n}\n\nvoid RandomBooleanTest(){\n\n\tint opSize = 16; \t// Set boolean circuit operation size\n\tint b[opSize+1]; \t// Number of bits\n\tint op[opSize];\t\t// Operations. 0 is AND, 1 is XOR\n\n\t//Create Random Bits and operations\n\tsrand(time(NULL));\n\tfor(int i=0; i<opSize; i++)\n\t\t\top[i] = rand()%2;\n\tfor(int i=0; i<opSize+1; i++)\n\t\t\tb[i] = rand()%2;\n\n\t//Compute the random boolean function and store the mid-results\n\tint opResult, midResult[opSize+1];\n\topResult = b[0];\n\tfor(int i=0; i<opSize; i++){\n\t\tmidResult[i] = opResult;\n\t\tif(op[i] == 0)\n\t\t\topResult = AND(opResult, b[i+1]);\n\t\telse\n\t\t\topResult = XOR(opResult, b[i+1]);\n\t}\n\t//Store the last result\n\tmidResult[opSize] = opResult;\n\n\n\t// Set fntru parameters and create ciphertexts to encrypt the bits of boolean function\n\tint M \t\t\t= M_;\n\tint radix\t\t= 16;\n\tint bitSize \t= Dif_Prime;\n\tZZ p \t\t\t= to_ZZ(\"2\");\n\n\tfntru g(M, bitSize, radix,  p);\n\tZZX message, messaget, m, r0, r1;\n\tfntru_cipher gResult, gb[opSize+1];\n\n\t// Initialize the ciphertexts\n\tg.InitializeCipher(gResult);\n\tfor(int i=0; i<opSize+1; i++)\n\t\tg.InitializeCipher(gb[i]);\n\n\t// Encrypt the boolean bits\n\tfor(int i=0; i<opSize+1; i++){\n\t\tmessage = b[i];\n\t\tg.Encrypt(gb[i], message);\n\t}\n\n\t// Compute the boolean function and store the mid-results by decrypting the result\n\tZZX messResult, messb[opSize+1], messmidResult[opSize+1];\n\tgResult = gb[0];\n\tfor(int i=0; i<opSize; i++){\n\n\t\tg.Decrypt(messb[i], gb[i]);\n\t\tg.Decrypt(messResult, gResult);\n\n\t\tmessmidResult[i] = messResult;\n\t\tif(op[i] == 0)\n\t\t\tg.AND(gResult, gResult, gb[i+1], 0);\n\t\telse\n\t\t\tg.XOR(gResult, gResult, gb[i+1], 0);\n\t}\n\t// Decrypt the last result\n\tg.Decrypt(messResult, gResult);\n\tmessmidResult[opSize] = messResult;\n\n\tcout << \"Boolean Equal:\\t\" << CheckBooleanCircuitResult(midResult, messmidResult, opSize) << endl;\n\tPrintBooleanCircuitValues(midResult, messmidResult, opSize);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\nvoid TestAND(fntru &f){\n\n\tfntru_cipher a, b, c;\n\n\tf.InitializeCipher(a);\n\tf.InitializeCipher(b);\n\tf.InitializeCipher(c);\n\n\tZZX one, zero, result;\n\tone \t= 1;\n\tzero \t= 0;\n\n\tcout << \"\\\\\\\\\\\\\\\\\\\\\\\\ AND \\\\\\\\\\\\\\\\\\\\\\\\\" << endl;\n\tcout << \"a\\t\" << \"b\\t\" << \"c\\t\" << endl << endl;\n\n\tf.Encrypt(a, zero);\n\tf.Encrypt(b, zero);\n\tf.AND(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"0\\t\" << \"0\\t\" << ConvMessPoly(result) << endl;\n\n\tf.Encrypt(a, zero);\n\tf.Encrypt(b, one);\n\tf.AND(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"0\\t\" << \"1\\t\" << ConvMessPoly(result) << endl;\n\n\tf.Encrypt(a, one);\n\tf.Encrypt(b, zero);\n\tf.AND(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"1\\t\" << \"0\\t\" << ConvMessPoly(result) << endl;\n\n\tf.Encrypt(a, one);\n\tf.Encrypt(b, one);\n\tf.AND(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"1\\t\" << \"1\\t\" << ConvMessPoly(result) << endl;\n\n}\n\nvoid TestNAND(fntru &f){\n\n\tfntru_cipher a, b, c;\n\n\tf.InitializeCipher(a);\n\tf.InitializeCipher(b);\n\tf.InitializeCipher(c);\n\n\tZZX one, zero, result;\n\tone \t= 1;\n\tzero \t= 0;\n\n\tcout << \"\\\\\\\\\\\\\\\\\\\\\\\\ NAND \\\\\\\\\\\\\\\\\\\\\\\\\" << endl;\n\tcout << \"a\\t\" << \"b\\t\" << \"c\\t\" << endl << endl;\n\n\tf.Encrypt(a, zero);\n\tf.Encrypt(b, zero);\n\tf.NAND(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"0\\t\" << \"0\\t\" << ConvMessPoly(result) << endl;\n\n\tf.Encrypt(a, zero);\n\tf.Encrypt(b, one);\n\tf.NAND(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"0\\t\" << \"1\\t\" << ConvMessPoly(result) << endl;\n\n\tf.Encrypt(a, one);\n\tf.Encrypt(b, zero);\n\tf.NAND(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"1\\t\" << \"0\\t\" << ConvMessPoly(result) << endl;\n\n\tf.Encrypt(a, one);\n\tf.Encrypt(b, one);\n\tf.NAND(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"1\\t\" << \"1\\t\" << ConvMessPoly(result) << endl;\n\n}\n\nvoid TestOR(fntru &f){\n\n\tfntru_cipher a, b, c;\n\n\tf.InitializeCipher(a);\n\tf.InitializeCipher(b);\n\tf.InitializeCipher(c);\n\n\tZZX one, zero, result;\n\tone \t= 1;\n\tzero \t= 0;\n\n\tcout << \"\\\\\\\\\\\\\\\\\\\\\\\\ OR \\\\\\\\\\\\\\\\\\\\\\\\\" << endl;\n\tcout << \"a\\t\" << \"b\\t\" << \"c\\t\" << endl << endl;\n\n\tf.Encrypt(a, zero);\n\tf.Encrypt(b, zero);\n\tf.OR(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"0\\t\" << \"0\\t\" << ConvMessPoly(result) << endl;\n\n\tf.Encrypt(a, zero);\n\tf.Encrypt(b, one);\n\tf.OR(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"0\\t\" << \"1\\t\" << ConvMessPoly(result) << endl;\n\n\tf.Encrypt(a, one);\n\tf.Encrypt(b, zero);\n\tf.OR(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"1\\t\" << \"0\\t\" << ConvMessPoly(result) << endl;\n\n\tf.Encrypt(a, one);\n\tf.Encrypt(b, one);\n\tf.OR(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"1\\t\" << \"1\\t\" << ConvMessPoly(result) << endl;\n\n}\n\nvoid TestXOR(fntru &f){\n\n\tfntru_cipher a, b, c;\n\n\tf.InitializeCipher(a);\n\tf.InitializeCipher(b);\n\tf.InitializeCipher(c);\n\n\tZZX one, zero, result;\n\tone \t= 1;\n\tzero \t= 0;\n\n\tcout << \"\\\\\\\\\\\\\\\\\\\\\\\\ XOR \\\\\\\\\\\\\\\\\\\\\\\\\" << endl;\n\tcout << \"a\\t\" << \"b\\t\" << \"c\\t\" << endl << endl;\n\n\tf.Encrypt(a, zero);\n\tf.Encrypt(b, zero);\n\tf.XOR(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"0\\t\" << \"0\\t\" << ConvMessPoly(result) << endl;\n\n\tf.Encrypt(a, zero);\n\tf.Encrypt(b, one);\n\tf.XOR(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"0\\t\" << \"1\\t\" << ConvMessPoly(result) << endl;\n\n\tf.Encrypt(a, one);\n\tf.Encrypt(b, zero);\n\tf.XOR(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"1\\t\" << \"0\\t\" << ConvMessPoly(result) << endl;\n\n\tf.Encrypt(a, one);\n\tf.Encrypt(b, one);\n\tf.XOR(c, a, b, 1);\n\tf.Decrypt(result, c);\n\tcout << \"1\\t\" << \"1\\t\" << ConvMessPoly(result) << endl;\n}\n\nvoid TestNOT(fntru &f){\n\n\tfntru_cipher a, c;\n\n\tf.InitializeCipher(a);\n\tf.InitializeCipher(c);\n\n\tZZX one, zero, result;\n\tone \t= 1;\n\tzero \t= 0;\n\n\tcout << \"\\\\\\\\\\\\\\\\\\\\\\\\ NOT \\\\\\\\\\\\\\\\\\\\\\\\\" << endl;\n\tcout << \"a\\t\" << \"c\\t\" << endl << endl;\n\n\tf.Encrypt(a, zero);\n\tf.NOT(c, a, 1);\n\tf.Decrypt(result, c);\n\tcout << \"0\\t\" << ConvMessPoly(result) << endl;\n\n\tf.Encrypt(a, one);\n\tf.NOT(c, a, 1);\n\tf.Decrypt(result, c);\n\tcout << \"1\\t\" << ConvMessPoly(result) << endl;\n}\n\nvoid GateTest(){\n\tint M \t\t\t= M_;\n\tint radix\t\t= 16;\n\tint bitSize \t= Dif_Prime;\n\tZZ p \t\t\t= to_ZZ(\"2\");\n\n\tfntru f(M, bitSize, radix,  p);\n\n\tTestNOT(f);\n\tTestXOR(f);\n\tTestOR(f);\n\tTestAND(f);\n\tTestNAND(f);\n}\n\n\nint main(){\n\n\tint threadNum = 4;\n\tSetNumThreads(threadNum);\n\n\t// Create random boolean circuit and compute\n\tRandomBooleanTest();\n\t// Test if the gate functions work correctly\n\tGateTest();\n\n\n\treturn 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "77bc9b1aa6fbb541a946ef1481d658bfe8283da1", "size": 8684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "vernamlab/FNTRU", "max_stars_repo_head_hexsha": "31fadb5c1231df41ed6c903cb3a88f89f21ffcf2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-01-12T16:49:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-15T11:46:02.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "vernamlab/FNTRU", "max_issues_repo_head_hexsha": "31fadb5c1231df41ed6c903cb3a88f89f21ffcf2", "max_issues_repo_licenses": ["MIT"], "max_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": "vernamlab/FNTRU", "max_forks_repo_head_hexsha": "31fadb5c1231df41ed6c903cb3a88f89f21ffcf2", "max_forks_repo_licenses": ["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.381443299, "max_line_length": 118, "alphanum_fraction": 0.5845232612, "num_tokens": 2685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5140487317552562}}
{"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   testGroup.cpp\n * @brief  Unit tests for groups\n * @author Frank Dellaert\n **/\n\n#include <gtsam/base/Group.h>\n#include <gtsam/base/Testable.h>\n#include <Eigen/Core>\n#include <iostream>\n\nnamespace gtsam {\n\n/// Symmetric group\ntemplate<int N>\nclass Symmetric: private Eigen::PermutationMatrix<N> {\n  Symmetric(const Eigen::PermutationMatrix<N>& P) :\n      Eigen::PermutationMatrix<N>(P) {\n  }\npublic:\n  static Symmetric identity() { return Symmetric(); }\n  Symmetric() {\n    Eigen::PermutationMatrix<N>::setIdentity();\n  }\n  static Symmetric Transposition(int i, int j) {\n    Symmetric g;\n    return g.applyTranspositionOnTheRight(i, j);\n  }\n  Symmetric operator*(const Symmetric& other) const {\n    return Eigen::PermutationMatrix<N>::operator*(other);\n  }\n  bool operator==(const Symmetric& other) const {\n    for (size_t i = 0; i < N; i++)\n      if (this->indices()[i] != other.indices()[i])\n        return false;\n    return true;\n  }\n  Symmetric inverse() const {\n    return Eigen::PermutationMatrix<N>(Eigen::PermutationMatrix<N>::inverse());\n  }\n  friend std::ostream &operator<<(std::ostream &os, const Symmetric& m) {\n    for (size_t i = 0; i < N; i++)\n      os << m.indices()[i] << \" \";\n    return os;\n  }\n  void print(const std::string& s = \"\") const {\n    std::cout << s << *this << std::endl;\n  }\n  bool equals(const Symmetric<N>& other, double tol = 0) const {\n    return this->indices() == other.indices();\n  }\n};\n\n/// Define permutation group traits to be a model of the Multiplicative Group concept\ntemplate<int N>\nstruct traits<Symmetric<N> > : internal::MultiplicativeGroupTraits<Symmetric<N> >,\n    Testable<Symmetric<N> > {\n};\n\n} // namespace gtsam\n\n#include <gtsam/base/Testable.h>\n#include <CppUnitLite/TestHarness.h>\n\nusing namespace std;\nusing namespace gtsam;\n\n//******************************************************************************\ntypedef Symmetric<2> S2;\nTEST(Group, S2) {\n  S2 e, s1 = S2::Transposition(0, 1);\n  BOOST_CONCEPT_ASSERT((IsGroup<S2>));\n  EXPECT(check_group_invariants(e, s1));\n}\n\n//******************************************************************************\ntypedef Symmetric<3> S3;\nTEST(Group, S3) {\n  S3 e, s1 = S3::Transposition(0, 1), s2 = S3::Transposition(1, 2);\n  BOOST_CONCEPT_ASSERT((IsGroup<S3>));\n  EXPECT(check_group_invariants(e, s1));\n  EXPECT(assert_equal(s1, s1 * e));\n  EXPECT(assert_equal(s1, e * s1));\n  EXPECT(assert_equal(e, s1 * s1));\n  S3 g = s1 * s2; // 1 2 0\n  EXPECT(assert_equal(s1, g * s2));\n  EXPECT(assert_equal(e, compose_pow(g, 0)));\n  EXPECT(assert_equal(g, compose_pow(g, 1)));\n  EXPECT(assert_equal(e, compose_pow(g, 3))); // g is generator of Z3 subgroup\n}\n\n//******************************************************************************\n// The direct product of S2=Z2 and S3 is the symmetry group of a hexagon,\n// i.e., the dihedral group of order 12 (denoted Dih6 because 6-sided polygon)\nnamespace gtsam {\ntypedef DirectProduct<S2, S3> Dih6;\n\nstd::ostream &operator<<(std::ostream &os, const Dih6& m) {\n  os << \"( \" << m.first << \", \" << m.second << \")\";\n  return os;\n}\n\n// Provide traits with Testable\n\ntemplate<>\nstruct traits<Dih6> : internal::MultiplicativeGroupTraits<Dih6> {\n  static void Print(const Dih6& m, const string& s = \"\") {\n    cout << s << m << endl;\n  }\n  static bool Equals(const Dih6& m1, const Dih6& m2, double tol = 1e-8) {\n    return m1 == m2;\n  }\n};\n} // namespace gtsam\n\nTEST(Group, Dih6) {\n  Dih6 e, g(S2::Transposition(0, 1),\n      S3::Transposition(0, 1) * S3::Transposition(1, 2));\n  BOOST_CONCEPT_ASSERT((IsGroup<Dih6>));\n  EXPECT(check_group_invariants(e, g));\n  EXPECT(assert_equal(e, compose_pow(g, 0)));\n  EXPECT(assert_equal(g, compose_pow(g, 1)));\n  EXPECT(assert_equal(e, compose_pow(g, 6))); // g is generator of Z6 subgroup\n}\n\n//******************************************************************************\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n//******************************************************************************\n\n", "meta": {"hexsha": "f405bdaf18a6b3c0e23c33e958df59463f27feb7", "size": 4403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/base/tests/testGroup.cpp", "max_stars_repo_name": "karamach/gtsam", "max_stars_repo_head_hexsha": "35f9b710163a1d14d8dc4fcf50b8dce6e0bf7e5b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 105.0, "max_stars_repo_stars_event_min_datetime": "2017-12-02T14:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T18:20:25.000Z", "max_issues_repo_path": "trunk/gtsam/base/tests/testGroup.cpp", "max_issues_repo_name": "shaolinbit/PPP-BayesTree", "max_issues_repo_head_hexsha": "6f469775277a1a33447bf4c19603c796c2c63c75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-04T15:15:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-08T08:51:02.000Z", "max_forks_repo_path": "trunk/gtsam/base/tests/testGroup.cpp", "max_forks_repo_name": "shaolinbit/PPP-BayesTree", "max_forks_repo_head_hexsha": "6f469775277a1a33447bf4c19603c796c2c63c75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2018-01-10T03:21:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T06:18:35.000Z", "avg_line_length": 30.5763888889, "max_line_length": 85, "alphanum_fraction": 0.5800590506, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5140487272009903}}
{"text": "#include <imgui.h>\n#include <pangolin/pangolin.h>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n#include <chrono>\n\n#include <imgui_impl_opengl3.h>\n#include <imgui_impl_win32.h>\n\n// Converts degrees to radians.\n#define degreesToRadians(angleDegrees) (angleDegrees * M_PI / 180.0)\n\n// Converts radians to degrees.\n#define radiansToDegrees(angleRadians) (angleRadians * 180.0 / M_PI)\n\nclass RgoHandler3d : public pangolin::Handler3D {\n   public:\n    enum class KeysEnum : unsigned char {\n        AXIS_ALIGN_YX = 'a',\n        AXIS_ALIGN_XZ = 'd',\n        AXIS_ALIGN_YZ = 'x',\n        ROLL_NEG = 'q',\n        ROLL_POS = 'e',\n        PITCH_NEG = 'w',\n        PITCH_POS = 's',\n        YAW_NEG = 'z',\n        YAW_POS = 'c',\n        TOGGLE_WORLD_TO_MODEL = 'm'\n    };\n\n    RgoHandler3d::RgoHandler3d(pangolin::OpenGlRenderState& cam_state)\n        : pangolin::Handler3D(cam_state) {}\n    void Keyboard(pangolin::View& view, unsigned char key, int x, int y,\n                  bool pressed) {\n        if (!pressed) {\n            return;\n        }\n        auto rotation_requested{false};\n        Eigen::Matrix4d transform;\n        transform.setIdentity();\n        const Eigen::Matrix4d mvmat = cam_state->GetModelViewMatrix();\n        Eigen::Quaternion<double> R_env_cam =\n            Eigen::Quaternion<double>(mvmat.block<3, 3>(0, 0).transpose());\n        R_env_cam.normalize();\n\n        switch (key) {\n            case pangolin::PANGO_SPECIAL + pangolin::PANGO_KEY_LEFT:\n                transform.block<3, 1>(0, 3) =\n                    R_env_cam * Eigen::Vector3d::UnitX() * move_factor_;\n                break;\n            case pangolin::PANGO_SPECIAL + pangolin::PANGO_KEY_RIGHT:\n                transform.block<3, 1>(0, 3) =\n                    R_env_cam * -Eigen::Vector3d::UnitX() * move_factor_;\n                break;\n            case pangolin::PANGO_SPECIAL + pangolin::PANGO_KEY_UP:\n                transform.block<3, 1>(0, 3) =\n                    R_env_cam * Eigen::Vector3d::UnitZ() * move_factor_;\n                break;\n            case pangolin::PANGO_SPECIAL + pangolin::PANGO_KEY_DOWN:\n                transform.block<3, 1>(0, 3) =\n                    R_env_cam * -Eigen::Vector3d::UnitZ() * move_factor_;\n                break;\n            case KeysEnum::AXIS_ALIGN_YX:\n                transform.block<3, 3>(0, 0) = R_env_cam.matrix();\n                break;\n            case KeysEnum::AXIS_ALIGN_XZ:\n                transform.block<3, 3>(0, 0) =\n                    R_env_cam.matrix() *\n                    Eigen::AngleAxis<double>(degreesToRadians(90),\n                                             Eigen::Vector3d::UnitX())\n                        .matrix();\n                break;\n            case KeysEnum::AXIS_ALIGN_YZ:\n                transform.block<3, 3>(0, 0) =\n                    R_env_cam *\n                    Eigen::AngleAxis<double>(degreesToRadians(90),\n                                             Eigen::Vector3d::UnitY())\n                        .matrix();\n                break;\n            case KeysEnum::ROLL_NEG:\n                transform.block<3, 3>(0, 0) =\n                    Eigen::AngleAxis<double>(\n                        degreesToRadians(-rotation_factor_deg_),\n                        (R_env_cam * Eigen::Vector3d::UnitZ()).normalized())\n                        .matrix();\n                rotation_requested = true;\n                break;\n            case KeysEnum::ROLL_POS:\n                transform.block<3, 3>(0, 0) =\n                    Eigen::AngleAxis<double>(\n                        degreesToRadians(rotation_factor_deg_),\n                        (R_env_cam * Eigen::Vector3d::UnitZ()).normalized())\n                        .matrix();\n                rotation_requested = true;\n                break;\n            case KeysEnum::PITCH_NEG:\n                transform.block<3, 3>(0, 0) =\n                    Eigen::AngleAxis<double>(\n                        degreesToRadians(-rotation_factor_deg_),\n                        (R_env_cam * Eigen::Vector3d::UnitX()).normalized())\n                        .matrix();\n                rotation_requested = true;\n                break;\n            case KeysEnum::PITCH_POS:\n                transform.block<3, 3>(0, 0) =\n                    Eigen::AngleAxis<double>(\n                        degreesToRadians(rotation_factor_deg_),\n                        (R_env_cam * Eigen::Vector3d::UnitX()).normalized())\n                        .matrix();\n                rotation_requested = true;\n                break;\n            case KeysEnum::YAW_NEG:\n                transform.block<3, 3>(0, 0) =\n                    Eigen::AngleAxis<double>(\n                        degreesToRadians(-rotation_factor_deg_),\n                        (R_env_cam * Eigen::Vector3d::UnitY()).normalized())\n                        .matrix();\n                rotation_requested = true;\n                break;\n            case KeysEnum::YAW_POS:\n                transform.block<3, 3>(0, 0) =\n                    Eigen::AngleAxis<double>(\n                        degreesToRadians(rotation_factor_deg_),\n                        (R_env_cam * Eigen::Vector3d::UnitY()).normalized())\n                        .matrix();\n                rotation_requested = true;\n                break;\n            case KeysEnum::TOGGLE_WORLD_TO_MODEL:\n                cam_around_world_ = !cam_around_world_;\n                break;\n        }\n\n        Eigen::Matrix4d model_view = cam_around_world_ && rotation_requested\n                                         ? transform * mvmat\n                                         : mvmat * transform;\n        cam_state->SetModelViewMatrix(model_view);\n    }\n\n   private:\n    bool cam_around_world_{false};\n    float move_factor_ = 0.4f;\n    float rotation_factor_deg_ = 5.f;\n};\n\nnamespace gl {\nstatic void DrawAxisGizmo(const Eigen::Matrix4d& mvmat,\n                          Eigen::Vector3d pos = {0.8, 0.8, 0},\n                          float line_width = 2.5f, float axis_len = .075f) {\n    glMatrixMode(GL_PROJECTION);\n    glLoadIdentity();\n    glMatrixMode(GL_MODELVIEW);\n    glLoadIdentity();\n\n    Eigen::Matrix4d transformation;\n    transformation.setIdentity();\n    transformation.block<3, 3>(0, 0) = mvmat.block<3, 3>(0, 0);\n    transformation.block<3, 1>(0, 3) = pos;\n\n    glPushMatrix();\n    glMultMatrixd(transformation.data());\n    glPushAttrib(GL_LINE_BIT);\n    glLineWidth(line_width);\n    pangolin::glDrawAxis(axis_len);\n    glPopAttrib();\n    glPopMatrix();\n}\n\nEigen::Matrix4f lookAt(const Eigen::Vector3f& eye,\n                       const Eigen::Vector3f& target,\n                       const Eigen::Vector3f& up) {\n    Eigen::Vector3f forward = eye - target;\n    forward.normalize();\n    Eigen::Vector3f left = up.cross(forward);\n    left.normalize();\n\n    Eigen::Matrix3f rotation;\n    rotation << left, forward.cross(left), forward;\n\n    Eigen::Matrix4f transformation;\n    transformation.setIdentity();\n    transformation.block<3, 3>(0, 0) = rotation.transpose();\n    transformation.block<3, 1>(0, 3) =\n        transformation.block<3, 3>(0, 0) * (-eye);\n\n    return transformation;\n}\n}  // namespace gl\n\nint main(int /*argc*/, char** /*argv*/) {\n    const auto width = 640;\n    const auto height = 480;\n\n    auto& window = pangolin::CreateWindowAndBind(\"Main\", width, height);\n\n    // 3D Mouse handler requires depth testing to be enabled\n    glEnable(GL_DEPTH_TEST);\n\n    // Issue specific OpenGl we might need\n    glEnable(GL_BLEND);\n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n    const char* glsl_version = \"#version 130\";\n    ImGui_ImplOpenGL3_Init(glsl_version);\n\n    // Setup Dear ImGui style\n    ImGui::StyleColorsClassic();\n    // Define Projection and initial ModelView matrix\n    pangolin::OpenGlRenderState s_cam(\n        pangolin::ProjectionMatrix(width, height, 420, 420, 320, 240, 0.2, 100),\n        pangolin::ModelViewLookAt(-12, 2, -12, 0, 0, 0, pangolin::AxisY));\n\n    // Add named OpenGL viewport to window and provide 3D Handler\n    pangolin::View& d_cam =\n        pangolin::CreateDisplay()\n            .SetBounds(0.0, 1.0, 0.0, 1.0,\n                       -640.0f / 480.0f)\n            .SetHandler(new RgoHandler3d(s_cam));\n\n    while (!pangolin::ShouldQuit()) {\n        // Clear screen and activate view to render into\n        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n        gl::DrawAxisGizmo(s_cam.GetModelViewMatrix());\n        glEnable(GL_DEPTH_TEST);\n\n        ImGui_ImplOpenGL3_NewFrame();\n        ImGui_ImplWin32_NewFrame();\n        {\n            ImGui::NewFrame();\n            static float f = 0.0f;\n            static int counter = 0;\n\n            ImGui::Begin(\"UI\");\n            ImGui::SliderFloat(\n                \"float\", &f, 0.0f,\n                1.0f);  // Edit 1 float using a slider from 0.0f to 1.0f\n            if (ImGui::Button(\n                    \"Button\"))  // Buttons return true when clicked (most\n                                // widgets return true when edited/activated)\n                counter++;\n            ImGui::SameLine();\n            ImGui::Text(\"counter = %d\", counter);\n            ImGui::Text(\"Application average %.3f ms/frame (%.1f FPS)\",\n                        1000.0f / ImGui::GetIO().Framerate,\n                        ImGui::GetIO().Framerate);\n            ImGui::End();\n            ImGui::EndFrame();\n        }\n\n        d_cam.Activate(s_cam);\n\n        // Render OpenGL Cube\n        pangolin::glDrawColouredCube();\n        pangolin::glDrawAxis(1.f);\n        pangolin::glDraw_y0(10.0, 10);\n\n        // Swap frames and Process Events\n        ImGui::Render();\n        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());\n        pangolin::FinishFrame();\n        using namespace std::chrono_literals;\n        std::this_thread::sleep_for(16ms);\n    }\n    ImGui_ImplOpenGL3_Shutdown();\n\n    return 0;\n}\n", "meta": {"hexsha": "3382dec62016e6eaafccf69b7d15f4a545d7edde", "size": 9791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/HelloPangolin/main.cpp", "max_stars_repo_name": "benv2k6/Pangolin_fork", "max_stars_repo_head_hexsha": "c815c1f0492cebe04953c02bf086efd6e4161258", "max_stars_repo_licenses": ["MIT"], "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/HelloPangolin/main.cpp", "max_issues_repo_name": "benv2k6/Pangolin_fork", "max_issues_repo_head_hexsha": "c815c1f0492cebe04953c02bf086efd6e4161258", "max_issues_repo_licenses": ["MIT"], "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/HelloPangolin/main.cpp", "max_forks_repo_name": "benv2k6/Pangolin_fork", "max_forks_repo_head_hexsha": "c815c1f0492cebe04953c02bf086efd6e4161258", "max_forks_repo_licenses": ["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.670411985, "max_line_length": 80, "alphanum_fraction": 0.5372280666, "num_tokens": 2315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5140480629510542}}
{"text": "// Copyright 2018-2020 Coen Tempelaars (Falcons)\n// SPDX-License-Identifier: Apache-2.0\n/*\n * hmNearPosition.hpp\n *\n *  Created on: June 5, 2018\n *      Author: Jan Feitsma\n */\n\n#include <boost/lexical_cast.hpp>\n\n#include \"int/heightmaps/hmNearPosition.hpp\"\n\n#include \"falconsCommon.hpp\"\n\n#include \"tracing.hpp\"\n\nusing namespace teamplay;\n\n\nhmNearPosition::hmNearPosition()\n{\n    reset();\n}\n\nhmNearPosition::~hmNearPosition()\n{\n}\n\nvoid hmNearPosition::precalculate()\n{\n    // cannot do anything yet, need parameters\n    return;\n}\n\nabstractHeightMap hmNearPosition::refine(const parameterMap_t& params)\n{\n    // configuration\n    float alpha = 10.0; // magic number\n    // extract parameters\n    float positionX = 0.0;\n    float positionY = 0.0;\n    auto it = params.find(\"positionX\");\n    if (it != params.end())\n    {\n        positionX = boost::lexical_cast<float>(it->second);\n    }\n    it = params.find(\"positionY\");\n    if (it != params.end())\n    {\n        positionY = boost::lexical_cast<float>(it->second);\n    }\n    // calculate the height map\n    for (unsigned int i = 0; i < getNrOfHeightMapFieldsInX(); i++)\n    {\n        for (unsigned int j = 0; j < getNrOfHeightMapFieldsInY(); j++)\n        {\n            auto distance = calc_distance(Point2D(positionX, positionY), _heightMap(i, j)._center);\n            _heightMap(i, j).setValue(100.0 - alpha * distance);\n        }\n    }\n    return *this;\n}\n\nstd::string hmNearPosition::getDescription() const\n{\n    return \"Near position\";\n}\n\nstd::string hmNearPosition::getFilename() const\n{\n    return \"hmNearPosition\";\n}\n\n", "meta": {"hexsha": "695e58b2a94efa70fd2efaeea69280d05f6fa4d2", "size": 1574, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/teamplay/src/heightmaps/hmNearPosition.cpp", "max_stars_repo_name": "Falcons-Robocup/code", "max_stars_repo_head_hexsha": "2281a8569e7f11cbd3238b7cc7341c09e2e16249", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-15T13:27:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T08:40:52.000Z", "max_issues_repo_path": "packages/teamplay/src/heightmaps/hmNearPosition.cpp", "max_issues_repo_name": "Falcons-Robocup/code", "max_issues_repo_head_hexsha": "2281a8569e7f11cbd3238b7cc7341c09e2e16249", "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": "packages/teamplay/src/heightmaps/hmNearPosition.cpp", "max_forks_repo_name": "Falcons-Robocup/code", "max_forks_repo_head_hexsha": "2281a8569e7f11cbd3238b7cc7341c09e2e16249", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-01T10:39:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T03:02:35.000Z", "avg_line_length": 20.9866666667, "max_line_length": 99, "alphanum_fraction": 0.6442185515, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5140480629510541}}
{"text": "#include \"stdafx.h\"\n#include \"DepthFunction.h\"\n\n#include \"mmcore/param/EnumParam.h\"\n#include \"mmcore/param/IntParam.h\"\n#include \"mmcore/param/StringParam.h\"\n\n#include <Eigen/LU>\n#include \"HD/HD.h\"\n\nusing namespace megamol;\nusing namespace megamol::infovis;\nusing namespace Eigen;\n\nenum DepthType { HALFSPACE_DEPTH = 0, FUNCTIONAL_DEPTH, MAHALANOBIS_DEPTH, SIMPLICAL_DEPTH };\n\nEigen::VectorXd DepthFunction::halfSpaceDepth(Eigen::MatrixXd dataMatrix) {\n    Eigen::VectorXd result = Eigen::VectorXd(dataMatrix.rows());\n\n    int nPoints = dataMatrix.rows();\n    int nDims = dataMatrix.cols();\n\n    double** x;\n    x = new double*[nPoints];\n\n    for (int i = 0; i < nPoints; i++) {\n        x[i] = new double[nDims];\n        for (int j = 0; j < nDims; j++) x[i][j] = dataMatrix(i, j);\n    }\n\n    double* z;\n    z = new double[dataMatrix.cols()];\n\n    for (int pIndex = 0; pIndex < nPoints; pIndex++) {\n        for (int j = 0; j < dataMatrix.cols(); j++) {\n            z[j] = dataMatrix(pIndex, j);\n        }\n        result(pIndex) = HalfspaceDepth::HD_Comb2(z, x, nPoints, nDims);\n    }\n\n    for (int k = 0; k < nPoints; k++) delete[] x[k];\n    delete[] x;\n    delete[] z;\n\n    return result;\n}\n\n\ndouble megamol::infovis::DepthFunction::binomialCoeff(int n, int k) {\n    if (k == 0 || k == n) return 1;\n\n    double result = 1.0;\n\n    for (int i = 0; i < k; i++) {\n        result *= (n + 1.0 - i) / i;\n    }\n\n    return result;\n}\n\nEigen::VectorXd DepthFunction::functionalDepth(\n    Eigen::MatrixXd dataMatrix, int samplesCount, int samplesLength, unsigned int seed) {\n    srand(seed);\n\n    Eigen::VectorXd result = Eigen::VectorXd(dataMatrix.rows());\n    double binom = megamol::infovis::DepthFunction::binomialCoeff(dataMatrix.rows(), samplesCount);\n\n    // count the hits for every data point (= row in the data matrix)\n    for (int row = 0; row < dataMatrix.rows(); row++) {\n        Eigen::RowVectorXd dataPoint = dataMatrix.row(row);\n\n        int hitsCount = 0;\n\n        // generate random samples of length samplesLength\n        for (int sampleIndex = 0; sampleIndex < samplesCount; sampleIndex++) {\n            Eigen::VectorXd rndIndices =\n                (Eigen::VectorXd::Random(samplesLength).array() + 1.0) / 2.0 * (dataMatrix.rows() - 1.0);\n\n            bool minMaxFound = true;\n\n            // for every property of the data point (= columns)\n            for (int dim = 0; dim < dataMatrix.cols(); dim++) {\n\n                double dataPointValue = dataPoint(dim);\n\n                bool dim_maxFound = false;\n                bool dim_minFound = false;\n\n                // for every data point in the random set, check if its value\n                // is <= or >= than the current data point value\n                // (equiv. to: is the data point contained in a random set of points?)\n                for (int rndIndexCounter = 0; rndIndexCounter < samplesLength; rndIndexCounter++) {\n                    int rndIndex = rndIndices(rndIndexCounter);\n\n                    if (dataMatrix(rndIndex, dim) <= dataPointValue) dim_minFound = true;\n                    if (dataMatrix(rndIndex, dim) >= dataPointValue) dim_maxFound = true;\n\n                    if (dim_minFound && dim_maxFound) break;\n                }\n\n                // if a dimension was found where neither a min nor a max was found,\n                // this datapoint isn't in the random set/sample\n                if (!(dim_minFound && dim_maxFound)) {\n                    minMaxFound = false;\n                    break;\n                }\n            }\n\n            if (minMaxFound) hitsCount++;\n        }\n\n        // result = 1 / binom(n, j) * hitsCount\n        // where n = samplesLength and j = samplesCount\n        result(row) = (double)hitsCount / (double)binom;\n    }\n\n    return result;\n}\n\nbool insideSimplexCheck(Eigen::VectorXd p, Eigen::MatrixXd x) {\n    Eigen::MatrixXd tmp(x.rows() + 1, x.cols());\n    tmp << x.transpose(), Eigen::MatrixXd::Ones(x.cols(), 1);\n    tmp.transposeInPlace();\n    double nominator = tmp.determinant();\n\n    tmp.block(0, 0, x.rows(), 1) = p;\n\n    double sum = 0;\n\n    for (int pointIndex = 0; pointIndex < x.cols(); pointIndex++) {\n\n        if (pointIndex != 0)\n            tmp.block(0, pointIndex, x.rows(), 1) = x.block(0, pointIndex - 1, x.rows(), 1); // update matrix\n\n        double sign = ((pointIndex % 2) * (-2.0) + 1.0);     // pow(-1,pointIndex)\n        double alpha = sign * tmp.determinant() / nominator; // barycentric coordinate\n\n        sum += alpha;\n        if (alpha > 1.0 || alpha < 0.0) return false;\n    }\n\n    return true;\n}\n\nEigen::VectorXd DepthFunction::simplicalDepth(Eigen::MatrixXd dataMatrix, int samplesCount, unsigned int seed) {\n    srand(seed);\n\n    int nPoints = dataMatrix.rows();\n    int nDims = dataMatrix.cols();\n\n    Eigen::VectorXd result = Eigen::VectorXd(dataMatrix.rows());\n\n    for (int row = 0; row < dataMatrix.rows(); row++) {\n        Eigen::VectorXd dataPoint = dataMatrix.row(row).transpose();\n\n        int hitsCount = 0;\n\n        for (int sampleIndex = 0; sampleIndex < samplesCount; sampleIndex++) {\n            Eigen::VectorXd rndIndices =\n                (Eigen::VectorXd::Random(nDims + 1).array() + 1.0) / 2.0 * (dataMatrix.rows() - 1.0);\n\n\n            Eigen::MatrixXd vertices(nDims, nDims + 1);\n\n            for (int rndIndexCounter = 0; rndIndexCounter < nDims + 1; rndIndexCounter++) {\n                int rndIndex = rndIndices(rndIndexCounter);\n\n                vertices.block(0, rndIndexCounter, nDims, 1) = dataMatrix.row(rndIndex).transpose();\n            }\n\n\n            if (insideSimplexCheck(dataPoint, vertices)) hitsCount++;\n        }\n\n        result(row) = (double)hitsCount / (double)samplesCount;\n    }\n\n    return result;\n}\n\nEigen::MatrixXd DepthFunction::mahalanobisDepth(Eigen::MatrixXd dataMatrix) {\n    int nPoints = dataMatrix.rows();\n\n    Eigen::MatrixXd mahalaDepth = Eigen::MatrixXd::Zero(nPoints, 1);\n    Eigen::MatrixXd invS =\n        (1.0 / (nPoints - 1.0) * dataMatrix.transpose() *\n            (Eigen::MatrixXd::Identity(nPoints, nPoints) - 1.0 / nPoints * Eigen::MatrixXd::Ones(nPoints, nPoints)) *\n            dataMatrix)\n            .inverse(); // inverse covariance Matrix\n\n    Eigen::MatrixXd mu = 1.0 / nPoints * dataMatrix.transpose() * Eigen::MatrixXd::Ones(nPoints, 1);\n    Eigen::MatrixXd xi;\n\n    //#pragma omp parallel for //doesn't work\n    for (int index = 0; index < nPoints; index++) {\n        xi = dataMatrix.row(index).transpose();\n        mahalaDepth(index, 0) = 1.0 / (1.0 + ((xi - mu).transpose() * invS * (xi - mu))(0, 0));\n    }\n    return mahalaDepth;\n}\n\nstd::vector<std::string> split(std::string str, std::string token) {\n    std::vector<std::string> result;\n    while (str.size()) {\n        int index = str.find(token);\n        if (index != std::string::npos) {\n            result.push_back(str.substr(0, index));\n            str = str.substr(index + token.size());\n            if (str.size() == 0) result.push_back(str);\n        } else {\n            result.push_back(str);\n            str = \"\";\n        }\n    }\n    return result;\n}\n\n/// Parse string a with format columnIndex1;columnIndex2,columnIndex3,...;...\nstd::vector<std::vector<int>> parseColumnGroups(std::string& columnGroupString) {\n    std::vector<std::vector<int>> columnGroups;\n    auto groupStrings = split(columnGroupString, \";\");\n    for (auto groupString : groupStrings) {\n        auto columnStrings = split(groupString, \",\");\n        std::vector<int> columns;\n        for (auto columnString : columnStrings) {\n            columns.push_back(std::stoi(columnString));\n        }\n        columnGroups.push_back(columns);\n    }\n    return columnGroups;\n}\n\n// ---------------------------------------------------------------------------\n\nDepthFunction::DepthFunction(void)\n    : megamol::core::Module()\n    , dataOutSlot(\"dataOut\", \"Ouput\")\n    , dataInSlot(\"dataIn\", \"Input\")\n    , datahash(0)\n    , dataInHash(0)\n    , columnInfos()\n    , columnGroupsSlot(\"columnGroups\", \"Semicolon-separated groups of comma-separated column indices to compute \"\n                                       \"the data depth for. Defaults to one group, all columns.\")\n    , depthType(\"depthType\", \"The depth function to use for computing the depth statistics\")\n    , sampleCount(\"sampleCount\", \"The number of samples, that will be drawn (functional depth only)\")\n    , sampleLength(\"sampleLength\", \"The length of one sample (functional depth only)\")\n    , randomSeed(\"randomSeed\", \"The random seed (functional depth only)\") {\n\n    // Data input slot\n    this->dataInSlot.SetCompatibleCall<megamol::stdplugin::datatools::table::TableDataCallDescription>();\n    this->MakeSlotAvailable(&this->dataInSlot);\n\n    // Data output slot\n    this->dataOutSlot.SetCallback(megamol::stdplugin::datatools::table::TableDataCall::ClassName(),\n        megamol::stdplugin::datatools::table::TableDataCall::FunctionName(0), &DepthFunction::getDataCallback);\n    this->dataOutSlot.SetCallback(megamol::stdplugin::datatools::table::TableDataCall::ClassName(),\n        megamol::stdplugin::datatools::table::TableDataCall::FunctionName(1), &DepthFunction::getHashCallback);\n    this->MakeSlotAvailable(&this->dataOutSlot);\n\n    // Parameters\n    columnGroupsSlot << new ::megamol::core::param::StringParam(\"\");\n    this->MakeSlotAvailable(&columnGroupsSlot);\n\n    auto types = new ::megamol::core::param::EnumParam(1);\n    types->SetTypePair(HALFSPACE_DEPTH, \"Halfspace Depth\");\n    types->SetTypePair(FUNCTIONAL_DEPTH, \"Functional Band Depth\");\n    types->SetTypePair(MAHALANOBIS_DEPTH, \"Mahalanobis Depth\");\n    types->SetTypePair(SIMPLICAL_DEPTH, \"Simplical Depth\");\n    depthType << types;\n    this->MakeSlotAvailable(&depthType);\n\n    sampleCount << new ::megamol::core::param::IntParam(20000);\n    this->MakeSlotAvailable(&sampleCount);\n\n    sampleLength << new ::megamol::core::param::IntParam(10);\n    this->MakeSlotAvailable(&sampleLength);\n\n    randomSeed << new ::megamol::core::param::IntParam(1337);\n    this->MakeSlotAvailable(&randomSeed);\n\n    // Add all parameters to common-parameter-handling list\n    params.push_back(&columnGroupsSlot);\n    params.push_back(&depthType);\n    params.push_back(&sampleCount);\n    params.push_back(&sampleLength);\n    params.push_back(&randomSeed);\n}\n\nDepthFunction::~DepthFunction(void) { this->Release(); }\n\nbool DepthFunction::create(void) { return true; }\n\nvoid DepthFunction::release(void) {}\n\nbool DepthFunction::getDataCallback(core::Call& c) {\n    try {\n        megamol::stdplugin::datatools::table::TableDataCall* outCall =\n            dynamic_cast<megamol::stdplugin::datatools::table::TableDataCall*>(&c);\n        if (outCall == NULL) return false;\n\n        megamol::stdplugin::datatools::table::TableDataCall* inCall =\n            this->dataInSlot.CallAs<megamol::stdplugin::datatools::table::TableDataCall>();\n        if (inCall == NULL) return false;\n\n        inCall->SetFrameID(outCall->GetFrameID()); // inCall->Set? not outCall???\n        if (!(*inCall)()) return false;\n\n        bool finished = apply(inCall);\n        if (finished == false) return false;\n\n        outCall->SetFrameCount(inCall->GetFrameCount());\n        outCall->SetDataHash(this->datahash);\n\n        // set outCall\n        if (this->columnInfos.size() != 0) {\n            outCall->Set(this->columnInfos.size(), this->data.size() / this->columnInfos.size(),\n                this->columnInfos.data(), this->data.data());\n        } else {\n            outCall->Set(0, 0, NULL, NULL);\n        }\n\n    } catch (...) {\n        vislib::sys::Log::DefaultLog.WriteError(_T(\"Failed to execute %hs::processData\\n\"), ClassName());\n        return false;\n    }\n\n    return true;\n}\n\nbool DepthFunction::getHashCallback(core::Call& c) {\n    try {\n        megamol::stdplugin::datatools::table::TableDataCall* outCall =\n            dynamic_cast<megamol::stdplugin::datatools::table::TableDataCall*>(&c);\n        if (outCall == NULL) return false;\n\n        megamol::stdplugin::datatools::table::TableDataCall* inCall =\n            this->dataInSlot.CallAs<megamol::stdplugin::datatools::table::TableDataCall>();\n        if (inCall == NULL) return false;\n\n        inCall->SetFrameID(outCall->GetFrameID());\n        if (!(*inCall)(1)) return false;\n\n        outCall->SetFrameCount(inCall->GetFrameCount());\n        outCall->SetDataHash(this->datahash);\n    } catch (...) {\n        vislib::sys::Log::DefaultLog.WriteError(_T(\"Failed to execute %hs::getHashCallback\\n\"), ClassName());\n        return false;\n    }\n\n    return true;\n}\n\nvoid megamol::infovis::DepthFunction::assertData(megamol::stdplugin::datatools::table::TableDataCall* inCall) {\n    auto columnCountIn = inCall->GetColumnsCount();\n    auto columnCountOut = inCall->GetColumnsCount();\n    auto rowsCount = inCall->GetRowsCount();\n    auto inData = inCall->GetData();\n\n    // Load data in a Matrix\n    inDataMat = Eigen::MatrixXd(rowsCount, columnCountOut);\n    for (int row = 0; row < rowsCount; row++) {\n        for (int col = 0; col < columnCountIn; col++) {\n            inDataMat(row, col) = inData[row * columnCountIn + col];\n        }\n    }\n}\n\nbool megamol::infovis::DepthFunction::paramsIsDirty() {\n    for (auto param : params) {\n        if (param->IsDirty()) return true;\n    }\n\n    return false;\n}\n\nvoid megamol::infovis::DepthFunction::paramsResetDirty() {\n    for (auto param : params) {\n        param->ResetDirty();\n    }\n}\n\nbool megamol::infovis::DepthFunction::apply(megamol::stdplugin::datatools::table::TableDataCall* inCall) {\n    // Test if input data or parameters have changed.\n    if (this->dataInHash == inCall->DataHash() && !paramsIsDirty()) {\n        // Do nothing since parameters are the same as before\n        return true;\n    }\n\n    assertData(inCall);\n\n    std::string columnGroupsString(this->columnGroupsSlot.Param<core::param::StringParam>()->Value().PeekBuffer());\n    std::vector<std::vector<int>> columnGroups = parseColumnGroups(columnGroupsString);\n\n    // Default to one group, containing all columns, if empty.\n    if (columnGroups.empty()) {\n        std::vector<int> columns;\n        for (int i = 0; i < inDataMat.cols(); ++i) {\n            columns.push_back(i);\n        }\n        columnGroups.push_back(columns);\n    }\n\n    // Compute depths for all column groups.\n    Eigen::MatrixXd groupDepths = Eigen::MatrixXd::Zero(inDataMat.rows(), columnGroups.size());\n    for (int group = 0; group < columnGroups.size(); group++) {\n        auto columns = columnGroups[group];\n\n        // Copy the columns together.\n        Eigen::MatrixXd columnGroupMat = Eigen::MatrixXd::Zero(inDataMat.rows(), columns.size());\n        for (int i = 0; i < columns.size(); i++) {\n            auto column = columns[i];\n            columnGroupMat.block(0, i, inDataMat.rows(), 1) = inDataMat.block(0, column, inDataMat.rows(), 1);\n        }\n\n        // Compute depth function.\n        switch (this->depthType.Param<core::param::EnumParam>()->Value()) {\n        case HALFSPACE_DEPTH:\n            groupDepths.block(0, group, inDataMat.rows(), 1) = halfSpaceDepth(columnGroupMat);\n            break;\n        case FUNCTIONAL_DEPTH:\n            groupDepths.block(0, group, inDataMat.rows(), 1) =\n                functionalDepth(columnGroupMat, this->sampleCount.Param<core::param::IntParam>()->Value(),\n                    this->sampleLength.Param<core::param::IntParam>()->Value(),\n                    this->randomSeed.Param<core::param::IntParam>()->Value());\n            break;\n        case MAHALANOBIS_DEPTH:\n            groupDepths.block(0, group, inDataMat.rows(), 1) = mahalanobisDepth(columnGroupMat);\n            break;\n        case SIMPLICAL_DEPTH:\n            groupDepths.block(0, group, inDataMat.rows(), 1) =\n                simplicalDepth(inDataMat, this->sampleCount.Param<core::param::IntParam>()->Value(),\n                    this->randomSeed.Param<core::param::IntParam>()->Value());\n            break;\n        }\n    }\n\n    // Generate new column infos.\n    this->columnInfos.clear();\n    this->columnInfos.resize(groupDepths.cols());\n\n    for (int group = 0; group < groupDepths.cols(); group++) {\n        auto depths = groupDepths.col(group);\n        std::string name = \"Depth\";\n        for (int i = 0; i < columnGroups[group].size(); ++i) {\n            name += \" \" + inCall->GetColumnsInfos()[columnGroups[group][i]].Name();\n        }\n        this->columnInfos[group]\n            .SetName(name)\n            .SetType(megamol::stdplugin::datatools::table::TableDataCall::ColumnType::QUANTITATIVE)\n            .SetMinimumValue(depths.minCoeff())\n            .SetMaximumValue(depths.maxCoeff());\n    }\n\n    // Set matrix as output.\n    this->data.clear();\n    this->data.reserve(groupDepths.rows() * groupDepths.cols());\n    for (size_t row = 0; row < groupDepths.rows(); row++) {\n        for (int group = 0; group < groupDepths.cols(); group++) {\n            this->data.push_back(groupDepths(row, group));\n        }\n    }\n\n    // Update hash.\n    this->dataInHash = inCall->DataHash();\n    this->datahash++;\n\n    // Reset parameters.\n    paramsResetDirty();\n\n    return true;\n}\n", "meta": {"hexsha": "2981fc750ac61b4bc6ff0a1b1f4178c60731b081", "size": 17021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plugins/infovis/src/DepthFunction.cpp", "max_stars_repo_name": "voei/megamol", "max_stars_repo_head_hexsha": "569b7b58c1f9bc5405b79549b86f84009329f668", "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": "plugins/infovis/src/DepthFunction.cpp", "max_issues_repo_name": "voei/megamol", "max_issues_repo_head_hexsha": "569b7b58c1f9bc5405b79549b86f84009329f668", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plugins/infovis/src/DepthFunction.cpp", "max_forks_repo_name": "voei/megamol", "max_forks_repo_head_hexsha": "569b7b58c1f9bc5405b79549b86f84009329f668", "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.061440678, "max_line_length": 117, "alphanum_fraction": 0.6127137066, "num_tokens": 4360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.514048058230784}}
{"text": "// Refer to the paper: \"Robust Point Cloud Based Reconstruction of Large-Scale Outdoor Scenes\" in CVPR 2019\n// Link: https://arxiv.org/abs/1905.09634\n\n// This file is an implememntation of the Gaussian-Uniform mixture model as described in Sec. 5 of the paper.\n// The Gaussian-Uniform mixture model degenerates to the approach in Choi et al. \"Robust Reconstruction of Indoor Scenes\" in CVPR 2017.\n// This implementation adopts some techniques used by Choi et al.\n\n#include <ceres/ceres.h>\n#include <iostream>\n#include <sophus/se3.hpp>\n\n#include <vector>\n#include <fstream>\n#include <Eigen/Core>\n\n#include <iomanip>\n#include <algorithm>\n\n#include \"local_parameterization_se3.hpp\"\n\n#define NUM_ITERATION_EM 1000\n\n#define EPSILON 6                             // upper bound of feature matching errors, used in Eq. (27)\n#define M_HAT EPSILON * EPSILON               // mean error, used in Eq. (27)\n#define P_HAT 0.9                             // trust level, used in Eq. (27)\n#define THETA P_HAT / ( 1.0 - P_HAT) * M_HAT  // THETA is solved using Eq. (27)\n\n#define THESHOLD_TO_BE_AN_INLIER_LOOP 0.8 * P_HAT    // theshold to prune outlier loop closures, used to generate results in Tab. 1 and 2\n\ntypedef Eigen::Matrix< double, 6, 6, Eigen::RowMajor > InformationMatrix;\ntypedef Eigen::Matrix< double, 6, 1> Vector6d;\n\nusing ceres::AutoDiffCostFunction;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solver;\nusing ceres::Solve;\n\nstruct FramedTransformation {\n  int id1_;\n  int id2_;\n  int frame_;\n  Eigen::Matrix4d transformation_;      // pose in matrix form\n  Sophus::SE3d transformation_se3_;     // pose in se3 form\n\n  FramedTransformation( int id1, int id2, int f, Eigen::Matrix4d t )\n    : id1_( id1 ), id2_( id2 ), frame_( f ), transformation_( t ) \n  {\n    Eigen::Quaterniond q;\n    q = t.block<3,3>(0,0);\n    transformation_se3_ = Sophus::SE3d(q, Sophus::SE3d::Point(t(0,3), t(1,3), t(2,3)));\n  }\n\n  FramedTransformation(int id1, int id2, int f, Sophus::SE3d t)\n    : id1_( id1 ), id2_( id2 ), frame_( f ), transformation_se3_( t ) \n    {\n      transformation_ = t.matrix();\n    }\n};\n\nstruct PCLTrajectory {\n  std::vector< FramedTransformation > data_;\n  int index_;\n\n  void LoadFromFile(const char* filename ) {\n    data_.clear();\n    index_ = 0;\n    int id1, id2, frame;\n    Eigen::Matrix4d trans;\n    FILE * f = fopen( filename, \"r\" );\n    if ( f != NULL ) {\n      char buffer[1024];\n      while ( fgets( buffer, 1024, f ) != NULL ) {\n        if ( strlen( buffer ) > 0 && buffer[ 0 ] != '#' ) {\n          sscanf( buffer, \"%d %d %d\", &id1, &id2, &frame);\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(0,0), &trans(0,1), &trans(0,2), &trans(0,3) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(1,0), &trans(1,1), &trans(1,2), &trans(1,3) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(2,0), &trans(2,1), &trans(2,2), &trans(2,3) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(3,0), &trans(3,1), &trans(3,2), &trans(3,3) );\n          data_.push_back( FramedTransformation( id1, id2, frame, trans ) );\n        }\n      }\n      fclose( f );\n    }\n  }\n\n  void SaveToFile(const char* filename ) {\n    FILE * f = fopen( filename, \"w\" );\n    for ( int i = 0; i < ( int )data_.size(); i++ ) {\n      Sophus::SE3d trans_se3 = data_[ i ].transformation_se3_;\n      Eigen::Matrix4d trans = trans_se3.matrix();\n      fprintf( f, \"%d\\t%d\\t%d\\n\", data_[ i ].id1_, data_[ i ].id2_, data_[ i ].frame_ );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(0,0), trans(0,1), trans(0,2), trans(0,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(1,0), trans(1,1), trans(1,2), trans(1,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(2,0), trans(2,1), trans(2,2), trans(2,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(3,0), trans(3,1), trans(3,2), trans(3,3) );\n\n    }\n    fclose( f );\n  }\n\n};\n\nstruct FramedInformation {\n  int id1_;\n  int id2_;\n  int frame_;\n  InformationMatrix information_;\n\n  FramedInformation( int id1, int id2, int f, InformationMatrix t )\n    : id1_( id1 ), id2_( id2 ), frame_( f ), information_( t ) \n  {}\n};\n\nstruct PCLInformation {\n  std::vector< FramedInformation > data_;\n\n  void LoadFromFile(const char*  filename ) {\n    data_.clear();\n    int id1, id2, frame;\n    InformationMatrix info;\n    FILE * f = fopen( filename, \"r\" );\n    if ( f != NULL ) {\n      char buffer[1024];\n      while ( fgets( buffer, 1024, f ) != NULL ) {\n        if ( strlen( buffer ) > 0 && buffer[ 0 ] != '#' ) {\n          sscanf( buffer, \"%d %d %d\", &id1, &id2, &frame);\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(0,0), &info(0,1), &info(0,2), &info(0,3), &info(0,4), &info(0,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(1,0), &info(1,1), &info(1,2), &info(1,3), &info(1,4), &info(1,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(2,0), &info(2,1), &info(2,2), &info(2,3), &info(2,4), &info(2,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(3,0), &info(3,1), &info(3,2), &info(3,3), &info(3,4), &info(3,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(4,0), &info(4,1), &info(4,2), &info(4,3), &info(4,4), &info(4,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(5,0), &info(5,1), &info(5,2), &info(5,3), &info(5,4), &info(5,5) );\n          data_.push_back( FramedInformation( id1, id2, frame, info ) );\n        }\n      }\n      fclose( f );\n    }\n  }\n};\n\nstruct GaussianFunctor {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  GaussianFunctor(Sophus::SE3d trans_next_to_current, InformationMatrix info, int id1, int id2) \n  : trans_next_to_current_(trans_next_to_current), info_(info), id1_(id1), id2_(id2) {}\n\n  template <typename T> \n  bool operator()(T const* const sT_current, T const* const sT_next, \n                  T* residual) const {\n\n    Eigen::Map<Sophus::SE3<T> const> const T_current(sT_current);\n    Eigen::Map<Sophus::SE3<T> const> const T_next(sT_next);\n    \n    Sophus::SE3<T> xi_7T = trans_next_to_current_ \n                          * T_next.inverse() \n                          * T_current;\n\n    // xi: local parameterization as in Choi et al.\n    Eigen::Matrix<T,6,1> xi;\n    xi << xi_7T.data()[4], xi_7T.data()[5], xi_7T.data()[6], xi_7T.data()[0], xi_7T.data()[1], xi_7T.data()[2];\n\n    Eigen::Matrix<T,1,1> sq_error = xi.transpose() * info_ * xi;\n    residual[0] = T( sqrt(sq_error(0,0)) );\n    \n    return true;\n  }\n\nprivate:\n  const Sophus::SE3d trans_next_to_current_;\n  const InformationMatrix info_;\n  const int id1_, id2_;\n};\n\nclass RobustPCLReconstruction_GaussianUniform {\npublic:\n\n  // Odometry contraints\n  PCLTrajectory odometry_log_;\n  PCLInformation odometry_info_;\n\n  // Loop closure contraints\n  PCLTrajectory loop_log_;\n  PCLInformation loop_info_;\n\n  // Fragment poses\n  PCLTrajectory fragment_poses_;\n  PCLTrajectory last_fragment_poses_;   // used to check for EM convergence\n\n  // P_ij table (Eq. 25)\n  std::vector< std::vector<double> > P_;\n  double average_P_;\n  double last_average_P_;   // used to check for EM convergence\n\n  RobustPCLReconstruction_GaussianUniform()\n  {\n    average_P_ = -1.;\n    last_average_P_ = -1.;\n  }\n\n  ~RobustPCLReconstruction_GaussianUniform() {}\n\n  void LoadOdometryLog(const char* filename) {\n    odometry_log_.LoadFromFile(filename);\n  }\n\n  void LoadOdometryInfo(const char* filename) {\n    odometry_info_.LoadFromFile(filename);\n  }\n\n  void LoadLoopLog(const char* filename) {\n    loop_log_.LoadFromFile(filename);\n  }\n\n  void LoadLoopInfo(const char* filename) {\n    loop_info_.LoadFromFile(filename);\n  }\n\n  void InitPosesFromFile(const char* filename) {\n    fragment_poses_.LoadFromFile(filename);\n\n    // Initialize P_ij table\n    P_.resize(NumPoses());\n    for (int i = 0; i < NumPoses(); i++) {\n      P_[i].resize(NumPoses());\n    }\n  }\n\n  // void InitPoses() {\n  //   fragment_poses_.data_.clear();\n  //   fragment_poses_.index_ = 0;\n  //   Eigen::Matrix4d pose = Eigen::Matrix4d::Identity();\n  //   fragment_poses_.data_.push_back( FramedTransformation( 0, 0, 1, pose ) );\n\n  //   for( std::vector< FramedTransformation >::iterator it = odometry_log_.data_.begin();\n  //     it != odometry_log_.data_.end(); it ++)\n  //   {      \n  //     pose = pose * it->transformation_; \n  //     fragment_poses_.data_.push_back( FramedTransformation( it->id2_, it->id2_, it->id2_ + 1, pose ) );\n  //   }\n  //   std::cout << \"total data size: \" << odometry_log_.data_.size() << std::endl;\n\n  //   P_.resize(NumPoses());\n  //   for (int i = 0; i < NumPoses(); i++) {\n  //     P_[i].resize(NumPoses());\n  //   }\n  // }\n\n\n  void SavePoses(const char* filename) {\n    fragment_poses_.SaveToFile(filename);\n  }\n\n  void SaveLinks(const char* filename) {\n    FILE * f = fopen( filename, \"w\" );\n\n    for ( int i = 0; i < NumOdometryConstraints(); i++ ) {\n      Sophus::SE3d trans_se3 = odometry_log_.data_[ i ].transformation_se3_;\n      Eigen::Matrix4d trans = trans_se3.matrix();\n      fprintf( f, \"%d\\t%d\\t%d\\n\", odometry_log_.data_[ i ].id1_, odometry_log_.data_[ i ].id2_, odometry_log_.data_[ i ].frame_ );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(0,0), trans(0,1), trans(0,2), trans(0,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(1,0), trans(1,1), trans(1,2), trans(1,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(2,0), trans(2,1), trans(2,2), trans(2,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(3,0), trans(3,1), trans(3,2), trans(3,3) );\n    }\n\n    for (int i = 0; i < NumLoopClosureConstraints(); i++ ) {\n      Sophus::SE3d trans_se3 = loop_log_.data_[ i ].transformation_se3_;\n      int id1 = loop_log_.data_[ i ].id1_;\n      int id2 = loop_log_.data_[ i ].id2_;\n      assert(id1 < id2);\n      if (id1 != id2 - 1 && P_[id1][id2] > THESHOLD_TO_BE_AN_INLIER_LOOP) {\n        Eigen::Matrix4d trans = trans_se3.matrix();\n        fprintf( f, \"%d\\t%d\\t%d\\n\", loop_log_.data_[ i ].id1_, loop_log_.data_[ i ].id2_, loop_log_.data_[ i ].frame_ );\n        fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(0,0), trans(0,1), trans(0,2), trans(0,3) );\n        fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(1,0), trans(1,1), trans(1,2), trans(1,3) );\n        fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(2,0), trans(2,1), trans(2,2), trans(2,3) );\n        fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(3,0), trans(3,1), trans(3,2), trans(3,3) );\n      }\n    }\n    fclose( f );\n  }\n\n  void Expectation() {\n    std::cout << std::endl << \"This is the beginning of EM iteration \" << fragment_poses_.index_ + 1 << std::endl\n              << \">>>> Expectation Step <<<<\" << std::endl;\n\n    double sum_P = 0;   // used to compute average_P_ later\n    std::vector<int> P_ij_counter(20);\n    for (int ii = 0; ii < 20; ii ++)\n      P_ij_counter[ii] = 0;\n    \n    std::cout << std::setw(5) << \"id1\"\n              << std::setw(5) << \"id2\"\n              << std::setw(10) << \"#matches\"\n              << std::setw(15) << \"xiLxi\"\n              << std::setw(15) << \"B_ij\"\n              << std::setw(15) << \"B_ij^2\"\n              << std::setw(15) << \"expterm\"\n              << std::setw(5) << \" --> \"\n              << std::setw(15) << \"P_ij\"\n              << std::endl;\n\n    // Compute P_ij table\n    for (int i = 0; i < NumLoopClosureConstraints(); i ++) {\n\n      FramedTransformation trans = loop_log_.data_[i];\n      FramedInformation info = loop_info_.data_[i];\n\n      assert(trans.id1_ == info.id1_ && trans.id2_ == info.id2_ && trans.id1_ < trans.id2_);\n      int id1 = info.id1_;\n      int id2 = info.id2_;\n\n      // Compute the matrix form of xi\n      Sophus::SE3d M_xi = trans.transformation_se3_\n                          * fragment_poses_.data_[id2].transformation_se3_.inverse() \n                          * fragment_poses_.data_[id1].transformation_se3_;\n\n      // Extract the vector form of xi\n      Vector6d xi;\n      xi << M_xi.data()[4], M_xi.data()[5], M_xi.data()[6], M_xi.data()[0], M_xi.data()[1], M_xi.data()[2];\n\n      // Compute B_ij (Eq. 23)\n      // This approximiation technique is adopted from Choi et al.\n      double xiLxi = xi.transpose() * info.information_ * xi; \n      double B_ij = xiLxi / info.information_(0,0);\n\n      // Compute P_ij (Eq. 25)\n      // The exponential-of-log trick is used to avoid the numerical issues when B_ij is too large.\n      double expterm = exp(2 * log(B_ij) - log (THETA));\n      P_[id1][id2] = 1./ (1. + expterm);\n\n      // Accumulate sum_P\n      sum_P += P_[id1][id2];\n\n      // Visualize intermediate steps\n      std::cout << std::setw(5) << id1\n                << std::setw(5) << id2\n                << std::setw(10) << info.information_(0,0)\n                << std::setw(15) << xiLxi\n                << std::setw(15) << B_ij\n                << std::setw(15) << B_ij * B_ij\n                << std::setw(15) << expterm\n                << std::setw(5) << \" --> \"\n                << std::setw(15) << P_[id1][id2]\n                << std::endl;\n\n      // Use P_ij_counter to visualize the distribution of P_ij\n      for (int ii = 0; ii < 20; ii ++)\n        if (P_[id1][id2] > 0.05 * ii && P_[id1][id2] <= 0.05 * (ii+1))\n          P_ij_counter[ii] ++;\n\n    }\n\n    // Save\n    last_average_P_ = average_P_;\n    last_fragment_poses_.index_ = fragment_poses_.index_;\n    last_fragment_poses_.data_.clear();\n    for (int i = 0; i < NumPoses(); i++)\n      last_fragment_poses_.data_.push_back( FramedTransformation( fragment_poses_.data_[i].id1_, \n                                                                  fragment_poses_.data_[i].id2_, \n                                                                  fragment_poses_.data_[i].frame_,\n                                                                  fragment_poses_.data_[i].transformation_se3_));\n    // Update\n    average_P_ = sum_P / NumLoopClosureConstraints();\n    fragment_poses_.index_++;\n\n    // Visualize the distribution of P_ij\n    std::cout << \"P_ij distributed in 20 bins :\" << std::endl;\n    for (int ii = 0; ii < 20 ; ii++)\n      std::cout << \"between\" \n                << std::setw(5) << 0.05 * ii  \n                << std::setw(5) << \"and\"\n                << std::setw(5) << 0.05 * (ii+1)\n                << std::setw(15) << P_ij_counter[ii]\n                << std::endl;\n  }\n\n  void Maximization() {\n    std::cout << std::endl << \">>>> Maximization Step <<<<\" << std::endl;\n\n    // Build the problem.\n    ceres::Problem problem;\n\n    // Specify local update rule for the parameters\n    for (std::vector< FramedTransformation >::iterator it = fragment_poses_.data_.begin(); \n         it != fragment_poses_.data_.end(); it++ ) {\n      problem.AddParameterBlock(it->transformation_se3_.data(), Sophus::SE3d::num_parameters,\n                                new Sophus::test::LocalParameterizationSE3);\n    }\n\n    // Create and add cost functions. Derivatives will be evaluated via\n    // automatic differentiation\n    for (int i = 0; i < NumOdometryConstraints(); i++) {\n\n      FramedTransformation trans = odometry_log_.data_[i];\n      FramedInformation info = odometry_info_.data_[i];\n      \n      assert(trans.id1_ == info.id1_ && trans.id2_ == info.id2_ && trans.id1_ < trans.id2_);\n      int id1 = info.id1_;\n      int id2 = info.id2_;\n\n      if (info.information_(0,0) <= 1)\n        continue;\n\n      ceres::CostFunction* cost_odometry =\n          new ceres::AutoDiffCostFunction<GaussianFunctor, 1,\n                                          Sophus::SE3d::num_parameters,\n                                          Sophus::SE3d::num_parameters>(\n              new GaussianFunctor(trans.transformation_se3_, info.information_, id1, id2));\n      problem.AddResidualBlock(cost_odometry, NULL, \n                               fragment_poses_.data_[id1].transformation_se3_.data(), \n                               fragment_poses_.data_[id2].transformation_se3_.data());\n    }\n\n\n    for (int i = 0; i < NumLoopClosureConstraints(); i++) {\n\n      FramedTransformation trans = loop_log_.data_[i];\n      FramedInformation info = loop_info_.data_[i];\n      \n      assert(trans.id1_ == info.id1_ && trans.id2_ == info.id2_ && trans.id1_ < trans.id2_);\n      int id1 = info.id1_;\n      int id2 = info.id2_;\n\n      ceres::CostFunction* cost_loop =\n          new ceres::AutoDiffCostFunction<GaussianFunctor, 1,\n                                          Sophus::SE3d::num_parameters,\n                                          Sophus::SE3d::num_parameters>(\n              new GaussianFunctor(trans.transformation_se3_, info.information_, id1, id2));\n      problem.AddResidualBlock(cost_loop, new ceres::ScaledLoss(NULL, P_[id1][id2], ceres::TAKE_OWNERSHIP), \n                               fragment_poses_.data_[id1].transformation_se3_.data(), \n                               fragment_poses_.data_[id2].transformation_se3_.data());\n    }\n    \n    // Set solver options\n    ceres::Solver::Options options;\n    // options.max_num_iterations = 1000;\n    options.gradient_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n    options.function_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n    options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;\n  \n    // Solve and report\n    ceres::Solver::Summary summary;\n    Solve(options, &problem, &summary);\n    std::cout << summary.BriefReport() << std::endl;\n\n    std::cout << \"This is the end of EM iteration : \" << fragment_poses_.index_ << std::endl;\n  }\n\n  int NumPoses() {\n    return fragment_poses_.data_.size();\n  }\n\n  int NumOdometryConstraints() {\n    return odometry_log_.data_.size();\n  }\n\n  int NumLoopClosureConstraints() {\n    return loop_log_.data_.size();\n  }\n\n  bool IsConverged() {\n    if (last_average_P_ < 0) {\n      return false;         // not started yet\n    }\n\n    std::cout << \"Checking for the convergence of average_P_ ...\\t\";\n    if (fabs(average_P_ - last_average_P_) > 0.00001) {\n      std::cout << \"NOT coverged yet, as average_P_ was updated from \" << last_average_P_ << \" to \" << average_P_ << std::endl;\n      return false;\n    }\n    std::cout << \"CONVERGED!\" << std::endl;\n\n\n    std::cout << \"Checking for the convergence of poses ...\\t\";\n    for (int i = 0; i < NumPoses(); i++)\n    {\n      Sophus::SE3d last_pose = last_fragment_poses_.data_[i].transformation_se3_;\n      Sophus::SE3d current_pose = fragment_poses_.data_[i].transformation_se3_;\n\n      double const mse = (last_pose.inverse() * current_pose).log().squaredNorm();\n      bool const converged = mse < 10. * Sophus::Constants<double>::epsilon();\n\n      if (!converged) {\n        std::cout << \"NOT converged yet.\" << std::endl;\n        return false;\n      }\n    }\n    std::cout << \"CONVERGED!\" << std::endl;\n    return true;\n  }\n};\n\nint main(int argc, char** argv) {\n  if (argc != 8)\n  {\n    std::cout << \"Please provide the following arguments: InputOdometryLog, InputOdometryInfo, InputLoopLog, InputLoopInfo, InputInitPoses, OutputFinalPoses, OutputKeptLoops\" << std::endl;\n    return 1;\n  } \n  RobustPCLReconstruction_GaussianUniform RobustPCLReconstruction_g;\n\n  RobustPCLReconstruction_g.LoadOdometryLog(argv[1]);\n  RobustPCLReconstruction_g.LoadOdometryInfo(argv[2]);\n  RobustPCLReconstruction_g.LoadLoopLog(argv[3]);\n  RobustPCLReconstruction_g.LoadLoopInfo(argv[4]);\n  RobustPCLReconstruction_g.InitPosesFromFile(argv[5]);\n\n  bool isConverged = false;\n  for (int i = 0 ; i < NUM_ITERATION_EM; i ++) {\n    RobustPCLReconstruction_g.Expectation();\n    RobustPCLReconstruction_g.Maximization();\n    if (RobustPCLReconstruction_g.IsConverged()) {\n      std::cout << \"Optimization ends since EM is converged\" << std::endl << std::endl;\n      isConverged = true;\n      break;\n    }\n  }\n\n  if (!isConverged)\n    std::cout << \"Optimization ends after \" << NUM_ITERATION_EM << \" EM iterations\" << std::endl << std::endl;\n\n  RobustPCLReconstruction_g.SavePoses(argv[6]);\n  std::cout << \"Final poses are saved to \" << argv[6] << std::endl;\n\n  RobustPCLReconstruction_g.SaveLinks(argv[7]);\n  std::cout << \"Good links are saved to \" << argv[7] << std::endl;\n\n  std::cout << \"There are \" << RobustPCLReconstruction_g.NumPoses() << \" poses\" << std::endl;\n  std::cout << \"There are \" << RobustPCLReconstruction_g.NumOdometryConstraints() << \" odometry constraints\" << std::endl;\n  std::cout << \"There are \" << RobustPCLReconstruction_g.NumLoopClosureConstraints() << \" loops\" << std::endl;\n\n  std::cout << std::endl;\n  \n  return 0;\n}\n", "meta": {"hexsha": "46168a1590187baa5f945e185b6ce73406553e80", "size": 20587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ceres/gaussian_em_one.cpp", "max_stars_repo_name": "ziquan111/RobustPCLReconstruction", "max_stars_repo_head_hexsha": "35b9518dbf9ad3f06109cc0e3aaacafdb5c86e36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 127.0, "max_stars_repo_stars_event_min_datetime": "2019-04-23T07:06:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:36:37.000Z", "max_issues_repo_path": "test/ceres/gaussian_em_one.cpp", "max_issues_repo_name": "ziquan111/RobustPCLReconstruction", "max_issues_repo_head_hexsha": "35b9518dbf9ad3f06109cc0e3aaacafdb5c86e36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-11-01T00:55:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-01T00:55:43.000Z", "max_forks_repo_path": "test/ceres/gaussian_em_one.cpp", "max_forks_repo_name": "ziquan111/RobustPCLReconstruction", "max_forks_repo_head_hexsha": "35b9518dbf9ad3f06109cc0e3aaacafdb5c86e36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2019-05-24T18:51:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T01:54:06.000Z", "avg_line_length": 37.7051282051, "max_line_length": 188, "alphanum_fraction": 0.5878952737, "num_tokens": 6321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5140207848213458}}
{"text": "#include <libv/core/serialization/all.hpp>\n#include <libv/graphic/viewer_context.hpp>\n#include <libv/lma/lma.hpp>\n#include <Eigen/Core>\n\nusing namespace v;\nusing namespace std;\nusing namespace Eigen;\n\ntypedef Matrix<double, 5, 1> Vector5d;\n\nV_DEFINE_CONFIG\n(\n  V_DEFINE_PROPERTY(config, string(\"config.ini\"), \"Main config file\")\n  V_DEFINE_PROPERTY(input, 1, \"The Input camera model\")\n  V_DEFINE_PROPERTY(output, 0, \"The output camera model\")\n  V_DEFINE_PROPERTY(step, 10., \"Distance between two consecutive generated points\")\n  V_DEFINE_PROPERTY(height, 480., \"Height of the image\")\n  V_DEFINE_PROPERTY(width, 640., \"Width of the image\")\n  V_DEFINE_PROPERTY(center, Array2d(), \"Coordinates of the principal point\")\n  V_DEFINE_PROPERTY(focal, Array2d(), \"Focal length\")\n  V_DEFINE_PROPERTY(xi, 0., \"Distortion parameter for the unified model\")\n  V_DEFINE_PROPERTY(distortion, Vector5d(), \"Distortion polynomial\")\n  V_DEFINE_PROPERTY(lambda, 1e-3, \"\")\n  V_DEFINE_PROPERTY(iteration_count, 25u, \"\")\n  V_DEFINE_PROPERTY(verbose, false, 0)\n)\n\nextern Config config;\nextern ViewerContext v1, v2, v3;\n\nstruct Callbacks\n: enable_verbose_output\n{\n  template<class S, class Algo>\n  void at_begin_bundle_adjustment_iteration(const S& solver, const Algo& algo) const\n  {\n    enable_verbose_output::at_begin_bundle_adjustment_iteration(solver,algo);\n    v3.clear();\n  }\n\n  template<class S, class Algo>\n  void at_end_bundle_adjustment_iteration(const S& solver, const Algo& algo) const\n  {\n    enable_verbose_output::at_end_bundle_adjustment_iteration(solver,algo);\n    v3.update().title(\"Press enter to continue\");\n    getchar();\n  }\n};\n\nstruct Error\n{\n  Array2d p2;\n  Vector3d p3;\n};\n\nstruct Module\n{\n  virtual void init(Error &) = 0;\n  virtual void add(Error &) = 0;\n  virtual void run() = 0;\n  virtual void run_verbose() = 0;\n};\n\nModule *init_unified();\nModule *init_pinhole_indirect_radial();\n", "meta": {"hexsha": "2c00918a9bd3ee78ff62aa8cfe0541a65dd0b9b4", "size": 1885, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/convert_camera_model/src/modules.hpp", "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/convert_camera_model/src/modules.hpp", "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/convert_camera_model/src/modules.hpp", "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": 28.1343283582, "max_line_length": 84, "alphanum_fraction": 0.7453580902, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5140207798543796}}
{"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//[register_box_templated\n//` Show the use of the macro BOOST_GEOMETRY_REGISTER_BOX_TEMPLATED\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/register/box.hpp>\n\ntemplate <typename P>\nstruct my_box\n{\n    P ll, ur;\n};\n\n// Register the box type\nBOOST_GEOMETRY_REGISTER_BOX_TEMPLATED(my_box, ll, ur)\n\nint main()\n{\n    typedef my_box<boost::geometry::model::d2::point_xy<double> > box;\n    box b = boost::geometry::make<box>(0, 0, 2, 2);\n    std::cout << \"Area: \"  << boost::geometry::area(b) << std::endl;\n    return 0;\n}\n\n//]\n\n\n//[register_box_templated_output\n/*`\nOutput:\n[pre\nArea: 4\n]\n*/\n//]\n", "meta": {"hexsha": "1b0378f745ac8f1cdefedcc9d189ca2a5d0e6687", "size": 1013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/geometries/register/box_templated.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/geometries/register/box_templated.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/geometries/register/box_templated.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": 21.5531914894, "max_line_length": 79, "alphanum_fraction": 0.7127344521, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5139469082065725}}
{"text": "#ifndef Field_hpp\n#define Field_hpp\n\n/** @file src/libField/Field.hpp\n */\n\n#include <ostream>\n#include <type_traits>\n#include <typeinfo>\n#include <vector>\n#include <array>\n\n#include <boost/multi_array.hpp>\n\n#include \"CoordinateSystem.hpp\"\n#include \"Utils.hpp\"\n\n/** @class Field\n * @brief A class for storing data in a field.\n * @author C.D. Clark III\n * @date 06/13/17\n *\n * A field is a quantity defined at every point in space. For example, the temperature\n * distribution throughout a solid, the pressure at every point in a room, or the density of a fluid.\n * A field may be 1-, 2-, or 3-dimensional, and is parameterized by a coordinate system.\n *\n * This class associates a coordinate system with a multi-dimensional array. Field elements are\n * allocated in a single, multi-dimensional array. And a CoordinateSystem is allocated for the coordinates.\n */\ntemplate<typename T, std::size_t N>\nusing arrayND = boost::multi_array<T, N, std::allocator<T>>;\ntemplate<typename T, std::size_t N>\nusing viewND = boost::detail::multi_array::multi_array_view<T, N>;\n\ntemplate<typename QUANT, size_t NUMDIMS, typename COORD = QUANT,\n         template<typename, size_t> class ARRAYND = arrayND,\n         template<typename> class ARRAY1D         = array1D>\nclass Field\n{\n public:\n  typedef ARRAYND<QUANT, NUMDIMS>                   array_type;\n  typedef typename array_type::index                index_type;\n  typedef CoordinateSystem<COORD, NUMDIMS, ARRAY1D> cs_type;\n\n protected:\n  std::shared_ptr<array_type> d;\n  std::shared_ptr<cs_type>    cs;\n\n protected:\n  /**\n   * @internal\n   * Utility function for converting 1d index to an Nd\n   * array of indices.\n   */\n  auto _1d2nd(size_t i) const\n  {\n    auto shape = d->shape();\n\n    std::array<size_t, NUMDIMS> ind;\n    int                         NN = shape[0];\n    for (size_t j = 1; j < NUMDIMS; ++j) NN *= shape[j];\n    for (size_t j = 0; j < NUMDIMS; ++j) {\n      NN /= shape[j];\n      ind[j] = i / NN;\n      i -= ind[j] * NN;\n    }\n    return ind;\n  }\n\n public:\n#if SERIALIZATION_ENABLED\n  template<class Archive>\n  void serialize(Archive& ar, const unsigned int version)\n  {\n    ar& d;\n    ar& cs;\n  }\n#endif\n\n  /**\n   * @brief Create an empty field with no elements allocated.\n   *\n   * Memory can be allocated later with Field::reset() method. The default constructor is provided to\n   * support storing fields in some containers that require a default constructor.\n   */\n  Field()        = default;\n  Field(Field&&) = default;\n  ~Field() = default;\n\n  Field(const Field& f) { reset(*f.cs, *f.d); }\n\n  /**\n   * @brief Create a new field and allocate memory for grid defined by dims.\n   *\n   * @param dims a list of sizes for each dimension.\n   *\n   * This constructor allows the caller to pass dimension sizes directly to the constructor.\n   * \n   * @code\n   * libField<double,2> f(10,20);\n   * @endcode\n   *\n   * This will create a field with 200 elements, 10 along the first dimension, 20 along the second.\n   *\n   */\n  template<typename... Dims>\n  Field(Dims... dims)\n  {\n    reset(dims...);\n  }\n\n\n  /**\n   * @brief Create a new field and allocate memory for the grid defined sizes.\n   *\n   * @param sizes an array of integers specifying the size of the field along each dimension.\n   */\n  template<typename I>\n  Field(std::array<I, NUMDIMS> sizes)\n  {\n    reset(sizes);\n  }\n  Field(std::shared_ptr<cs_type> cs_) { reset(cs_); }\n\n  Field(cs_type& cs_, array_type& d_) { reset(cs_, d_); };\n\n  /**\n   * @brief Reallocate a field with new dimensions.\n   *\n   * @param dims The size of the new field along each dimension.\n   */\n  template<typename... Dims>\n  void reset(Dims... dims)\n  {\n    cs = std::make_shared<cs_type>(dims...);\n    std::array<size_t, NUMDIMS> sizes({static_cast<size_t>(dims)...});\n    d = std::make_shared<array_type>(sizes);\n  }\n\n\n  /**\n   * @brief Reallocate a field with new dimensions.\n   *\n   * @param sizes An array of the new field sizes along each dimension.\n   */\n  template<typename I>\n  void reset(std::array<I, NUMDIMS> sizes)\n  {\n    cs = std::make_shared<cs_type>(sizes);\n    d = std::make_shared<array_type>(sizes);\n  }\n\n\n  /**\n   * @brief Reallocate a field from an existing coordinate system.\n   *\n   * @param cs_ a shared pointer to an existing coordinate system.\n   *\n   * New memory will be allocated for the field elements, but not for\n   * the coordinate system.\n   */\n  void reset(std::shared_ptr<cs_type> cs_)\n  {\n    cs = cs_;\n\n    std::vector<size_t> sizes(NUMDIMS);\n    for (size_t i = 0; i < NUMDIMS; ++i) sizes[i] = cs->size(i);\n\n    d = std::make_shared<array_type>(sizes);\n  }\n\n  /**\n   * @brief Reallocate a field from an existing coordinate system and field elements.\n   *\n   * @param cs_ a shared pointer to an existing coordinate system.\n   * @param d_ a shared pointer to an existing array of field elements.\n   *\n   * No new memory is allocated. References to existing field elements\n   * and coordinate system will be used.\n   */\n  void reset(cs_type& cs_, array_type& d_)\n  {\n    d = std::make_shared<array_type>(d_);\n    cs = std::make_shared<cs_type>(cs_.getAxes());\n  };\n\n\n  // ELEMENT ACCESS\n\n  /**\n   * @brief Return const reference to an element of field with given index.\n   * @param i An array-like container of indices.\n   *\n   * Example:\n   *\n   * The elements of a 2-dimensional array can be accessed using a 2-element vector.\n   * @code\n   * Field<double,2> f(10,20);\n   * ...\n   * std::vector<int> ind;\n   *\n   * ind[0] = 2;\n   * ind[1] = 4;\n   *\n   * double val = f(ind); // get the (2,4) element of the field.\n   * @endcode\n   *\n   * Any container that provides a subscript operator (operator[](int)) can be used.\n   */\n  template<typename I,\n           typename std::enable_if<IsIndexCont<I>::value, int>::type = 0>\n  const auto& operator()(I i) const\n  {\n    return (*d)(i);\n  }\n\n  /**\n   * @brief Return a reference to an element of field with given index.\n   * @param i An array-like container of indices.\n   *\n   * Example:\n   *\n   * The elements of a 2-dimensional array can be accessed using a 2-element vector.\n   * @code\n   * Field<double,2> f(10,20);\n   * ...\n   * std::vector<int> ind;\n   *\n   * ind[0] = 2;\n   * ind[1] = 4;\n   *\n   * f(ind) = 10; // set the (2,4) element of the field.\n   * @endcode\n   *\n   * Any container that provides a subscript operator (operator[](int)) can be used.\n   */\n  template<typename I,\n           typename std::enable_if<IsIndexCont<I>::value, int>::type = 0>\n  auto& operator()(I i)\n  {\n    return (*d)(i);\n  }\n\n  /**\n   * @brief Return a const reference to an element of field with given index.\n   * @param i the index of the element along the first dimension.\n   * @param args the indexes of the element along the remaining dimensions.\n   *\n   * This function is a variadic template that allow a natural access to the field elements using the operator()(), rather\n   * than having to use an index container..\n   *\n   * Example:\n   *\n   * @code\n   * Field<double,2> f(10,20);\n   * ...\n   *\n   * double val = f(2,4); // get the (2,4) element of the field.\n   * @endcode\n   */\n  template<typename I, typename... Args,\n           typename std::enable_if<std::is_integral<I>::value, int>::type = 0>\n  const auto& operator()(I i, Args... args) const\n  {\n    return (*d)(std::array<I, NUMDIMS>({i, args...}));\n  }\n\n  /**\n   * @brief Return a reference to an element of field with given index.\n   * @param i the index of the element along the first dimension.\n   * @param args the indexes of the element along the remaining dimensions.\n   *\n   *\n   * This function is a variadic template that allow a natural access to the field elements using the operator()(), rather\n   * than having to use an index container..\n   *\n   * Example:\n   *\n   * @code\n   * Field<double,2> f(10,20);\n   * ...\n   *\n   * f(2,4) = 10; // set the (2,4) element of the field.\n   * @endcode\n   */\n  template<typename I, typename... Args,\n           typename std::enable_if<std::is_integral<I>::value, int>::type = 0>\n  auto& operator()(I i, Args... args)\n  {\n    return (*d)(std::array<I, NUMDIMS>({i, args...}));\n  }\n\n  template<typename I>\n  auto operator[](I i) const\n  {\n    return (*d)[i];\n  }\n\n  /**\n   * @brief Return a shared pointer to the coordinate system used by the field.\n   */\n  auto        getCoordinateSystemPtr() { return cs; };\n\n  /**\n   * @brief Return a reference to the coordinate system used by the field.\n   */\n  auto&       getCoordinateSystem() { return *cs; };\n\n  /**\n   * @brief Return a reference to the i'th axis in the coordinate system used by the field.\n   * @param i The index (zero-offset) of the axis to return.\n   */\n  auto&       getAxis(size_t i) { return cs->getAxis(i); }\n  \n  /**\n   * @brief Return a const reference to the coordinate system used by the field.\n   */\n  const auto& getCoordinateSystem() const { return *cs; };\n  /**\n   * @brief Return a const reference to the i'th axis in the coordinate system used by the field.\n   * @param i The index (zero-offset) of the axis to return.\n   */\n  const auto& getAxis(size_t i) const { return cs->getAxis(i); }\n\n  /**\n   * @brief Set the coordinates of the coordinate system.\n   * @param args Coordinates specification. The arguments are passed directly to CoordinateSystem::set() of the coordinate system used by the field.\n   *\n   * Coordinate system coordinate are set using a range discretizer. See range_discretizers::UnitformImp<T> for example.\n   *\n   * Example:\n   *\n   * To configure a field over the range [-1,1] along the x direction and [0:4] along the y direction,\n   * @code\n   * Field<double,2> f(10,20);\n   * f.setCoordinateSystem( Uniform(-1,1), Uniform(0,4) );\n   * @endcode\n   */\n  template<typename... Args>\n  auto setCoordinateSystem(Args... args)\n  {\n    cs->set(args...);\n  }\n\n  /**\n   * @brief Return the coordinate element specified by args.\n   * @param args The index of the coordinate to retrief. The arguments are passed directly to CoordinateSystem::getCoord() of the coordinate system used by the field.\n   *\n   * Example:\n   *\n   * @code\n   * Field<double,2> f(10,20);\n   * ...\n   *\n   * auto coord = f.getCoord(2,4); // get the coordinate for the field element at (2,4)\n   * double x = coord[0]; // get the x coordinate;\n   * double y = coord[1]; // get the x coordinate;\n   * @endcode\n   */\n  template<typename... Args>\n  auto getCoord(Args... args) const\n  {\n    return cs->getCoord(args...);\n  }\n\n  /**\n   * @brief Returns index of stored coordinate that lower bounds the given coordinate.\n   *\n   * This function forwards the arguments to Coordinate::lower_bound() of the coordinate system used by the field.\n   * Along with upper_bound, it is useful for finding a range that bounds the given coordinate.\n   */\n  template<typename... Args>\n  auto lower_bound(Args... args) const\n  {\n    return cs->lower_bound(args...);\n  }\n\n  /**\n   * @brief Returns index of stored coordinate that upper bounds the given coordinate.\n   *\n   * This function forwards the arguments to Coordinate::upper_bound() of the coordinate system used by the field.\n   * Along with lower_bound, it is useful for finding a range that bounds the given coordinate.\n   */\n  template<typename... Args>\n  auto upper_bound(Args... args) const\n  {\n    return cs->upper_bound(args...);\n  }\n\n  /**\n   * @brief returns index of stored coordinate that is closest to the given coordinate.\n   */\n  template<typename... Args>\n  auto nearest(Args... args) const\n  {\n    return cs->nearest(args...);\n  }\n\n  // data access\n  auto        getDataPtr() { return d; };\n  const auto& getData() const { return *d; };\n  auto&       getData() { return *d; };\n\n  const auto data() const { return d->data(); }\n  auto       data() { return d->data(); }\n\n  template<int NDims>\n  const auto slice(\n      const boost::detail::multi_array::index_gen<NUMDIMS, NDims>& ind) const\n  {\n    // get sliced data\n    auto d_ = d->operator[](ind);\n    // get sliced coordinate system\n    auto cs_ = cs->slice(ind);\n\n    return Field<QUANT, NDims, COORD, viewND, view1D>(cs_, d_);\n  }\n\n  template<int NDims>\n  auto slice(const boost::detail::multi_array::index_gen<NUMDIMS, NDims>& ind)\n  {\n    // get sliced data\n    auto d_ = d->operator[](ind);\n    // get sliced coordinate system\n    auto cs_ = cs->slice(ind);\n\n    return Field<QUANT, NDims, COORD, viewND, view1D>(cs_, d_);\n  }\n\n  auto size() const { return d->num_elements(); }\n  auto size(int i) const { return d->shape()[i]; }\n\n  /**\n   * @brief Set each element of a field using a callable that takes an array-like container of *coordinates* as an argument and returns the element's value.\n   *\n   * This function evaluates the callable f for each coordinate and sets the field value to value\n   * returned by callable. Field may be evaluated in PARRALLEL. Callable should\n   * NOT depend on the order of being called.\n   *\n   * @param f a callable object (function, funtor, lambda, std::function, etc.)\n   * that accepts one argument and returns a value.\n   *\n   * Argument passed to callable f will be an array of coordinates.\n   *\n   */\n  template<typename F>\n  auto set_f(F f) -> decltype((*d)(0) = f(cs->getCoord(_1d2nd(0))), void())\n  {\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind             = this->_1d2nd(i);\n      d->  operator()(ind) = f(cs->getCoord(ind));\n    }\n  }\n\n  /**\n   * @brief Set each element of a field using a callable that takes an array-like container of *coordinates* as an argument and returns the element's value.\n   *\n   * This function evaluates the callable f that returns an optional type (boost::optional or\n   * std::optional) for each coordinate. If the optional is set, then the value of\n   * of the field element is set. Otherwise, the field is left untouched. Field may be\n   * evaluated in PARRALLEL. Callable should NOT depend on the order of being\n   * called.\n   *\n   * @param f a callable object (function, funtor, lambda, std::function, etc.)\n   * that accepts one argument and returns an optional value.\n   *\n   * Argument passed to callable f will be an array of coordinates.\n   *\n   */\n  template<typename F>\n  auto set_f(F f)\n      -> decltype((bool)f(cs->getCoord(_1d2nd(0))),\n                  (*d)(0) = f(cs->getCoord(_1d2nd(0))).value(), void())\n  {\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind = this->_1d2nd(i);\n      auto val = f(cs->getCoord(ind));\n      if (val) d->operator()(ind) = val.value();\n    }\n  }\n\n  /**\n   * @brief Set each element of a field using a callable that takes an array-like container of *indices* and a pointer to a coordinate system as arguments and returns the element's value.\n   *\n   * Evaluates callable f for each indices and sets the field value to value\n   * returned by callable. Callable is passed a container of indices and a\n   * pointer to the coordinate system. Field may be evaluated in PARRALLEL.\n   * Callable should NOT depend on the order of being called.\n   *\n   * @param f a callable object (function, funtor, lambda, std::function, etc.)\n   * that accepts two arguments and returns a value.\n   *\n   * Arguments passed to callable f will be an array of indices, and a pointer\n   * to the coordinate system.\n   *\n   */\n  template<typename F>\n  auto set_f(F f) -> decltype((*d)(0) = f(_1d2nd(0), cs), void())\n  {\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind             = this->_1d2nd(i);\n      d->  operator()(ind) = f(ind, cs);\n    }\n  }\n\n  /**\n   * @brief Set each element of a field using a callable that takes an array-like container of *indices* and a pointer to a coordinate system as arguments and returns the element's value.\n   *\n   * Evaluates callable f for each coordinate index. If the optional returned by\n   * f is set, the field for the coordinate is set. Otherwise, the field is left\n   * untouched. Callable is passed a container of indices and a pointer to the\n   * coordinate system. Field may be evaluated in PARRALLEL. Callable should NOT\n   * depend on the order of being called.\n   *\n   * @param f a callable object (function, funtor, lambda, std::function, etc.)\n   * that accepts two arguments and returns a value.\n   *\n   * Arguments passed to callable f will be an array of indices, and a pointer\n   * to the coordinate system.\n   *\n   */\n  template<typename F>\n  auto set_f(F f) -> decltype((bool)f(_1d2nd(0), cs),\n                              (*d)(0) = f(_1d2nd(0), cs).value(), void())\n  {\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind = this->_1d2nd(i);\n      auto val = f(ind, cs);\n      if (val) d->operator()(ind) = val.value();\n    }\n  }\n\n  // NOTE: we wanted to combined set and set_f into a single function, but this\n  // isn't possible in general. We cannot assume that the set_f version should\n  // be called if a function is passed in, because the user may actually want to\n  // store the functions in the field.\n\n  /**\n   * @brief Set all elements of a field to the value specified.\n   * @param q the value to set each element to.\n   *\n   * The method will set element values in parallel using OpenMP.\n   *\n   */\n  template<typename Q>\n  auto set(Q q)\n  {\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind             = this->_1d2nd(i);\n      d->  operator()(ind) = std::move(q);\n    }\n  }\n\n  // operator overloads\n\n  friend std::ostream& operator<<(std::ostream& output, const Field& F)\n  {\n    auto N        = F.d->num_elements();\n    auto last_ind = F._1d2nd(0);\n    for (size_t i = 0; i < N; ++i) {\n      auto ind = F._1d2nd(i);\n      // we want to print out blank lines whenever an index gets reset\n      for (size_t j = 0; j < NUMDIMS; ++j)\n        if (ind[j] < last_ind[j]) output << \"\\n\";\n\n      for (size_t j = 0; j < NUMDIMS; ++j)\n        output << F.cs->getAxis(j)[ind[j]] << \" \";\n      output << F.d->operator()(ind) << \"\\n\";\n\n      last_ind = ind;\n    }\n    return output;\n  }\n\n  /**\n   * @brief Set the elements of a field to the value given.\n   *\n   * Field elements are set in parallel using OpenMP.\n   */\n  template<typename Q>\n  Field& operator=(const Q& q)\n  {\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind             = this->_1d2nd(i);\n      d->  operator()(ind) = q;\n    }\n    return *this;\n  }\n\n  /**\n   * @brief Add a constant value to each element in the field.\n   * @param The value to add to each element.\n   *\n   * Field elements are updated in parallel using OpenMP.\n   */\n  template<typename Q>\n  Field& operator+=(const Q& q)\n  {\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind = this->_1d2nd(i);\n      d->  operator()(ind) += q;\n    }\n    return *this;\n  }\n\n  /**\n   * @brief Subtract a constant value to each element in the field.\n   * @param The value to subtract from each element.\n   *\n   * Field elements are updated in parallel using OpenMP.\n   */\n  template<typename Q>\n  Field& operator-=(const Q& q)\n  {\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind = this->_1d2nd(i);\n      d->  operator()(ind) -= q;\n    }\n    return *this;\n  }\n\n  /**\n   * @brief Multiply each element in a field by a constant value.\n   * @param The value to multiply each element by.\n   *\n   * Field elements are updated in parallel using OpenMP.\n   */\n  template<typename Q>\n  Field& operator*=(const Q& q)\n  {\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind = this->_1d2nd(i);\n      d->  operator()(ind) *= q;\n    }\n    return *this;\n  }\n\n  /**\n   * @brief Divide each element in a field by a constant value.\n   * @param The value to divide each element by.\n   *\n   * Field elements are updated in parallel using OpenMP.\n   */\n  template<typename Q>\n  Field& operator/=(const Q& q)\n  {\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind = this->_1d2nd(i);\n      d->  operator()(ind) /= q;\n    }\n    return *this;\n  }\n\n  Field& operator=(Field f)\n  {\n    d.swap(f.d);\n    cs.swap(f.cs);\n    return *this;\n  }\n\n  /**\n   * @brief Add the element of a second field to each element of the field.\n   * @param The field containing elements to be added to this field.\n   *\n   * Field elements are updated in parallel using OpenMP.\n   *\n   * Fields must be of the size.\n   */\n  Field& operator+=(const Field& f)\n  {\n    BOOST_ASSERT(f.size() == this->size());\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind = this->_1d2nd(i);\n      d->  operator()(ind) += f(ind);\n    }\n    return *this;\n  }\n\n  /**\n   * @brief Subtract the element of a second field from each element of the field.\n   * @param The field containing elements to be subtracted from this field.\n   *\n   * Field elements are updated in parallel using OpenMP.\n   *\n   * Fields must be of the size.\n   */\n  Field& operator-=(const Field& f)\n  {\n    BOOST_ASSERT(f.size() == this->size());\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind = this->_1d2nd(i);\n      d->  operator()(ind) -= f(ind);\n    }\n    return *this;\n  }\n\n  /**\n   * @brief Multiply each element in the field by the corresponding element in a second field.\n   * @param The field containing elements to be multiply by.\n   *\n   * Field elements are updated in parallel using OpenMP.\n   *\n   * Fields must be of the size.\n   */\n  Field& operator*=(const Field& f)\n  {\n    BOOST_ASSERT(f.size() == this->size());\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind = this->_1d2nd(i);\n      d->  operator()(ind) *= f(ind);\n    }\n    return *this;\n  }\n\n  /**\n   * @brief Divide each element in the field by the corresponding element in a second field.\n   * @param The field containing elements to divide by.\n   *\n   * Field elements are updated in parallel using OpenMP.\n   *\n   * Fields must be of the size.\n   */\n  Field& operator/=(const Field& f)\n  {\n    BOOST_ASSERT(f.size() == this->size());\n    auto N = d->num_elements();\n#pragma omp parallel for\n    for (size_t i = 0; i < N; ++i) {\n      auto ind = this->_1d2nd(i);\n      d->  operator()(ind) /= f(ind);\n    }\n    return *this;\n  }\n};\n\n#endif\n", "meta": {"hexsha": "47fb9d00e98f6d2f57b2894ad4fea7fafb184fa9", "size": 22434, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libField/Field.hpp", "max_stars_repo_name": "CD3/libField", "max_stars_repo_head_hexsha": "8aa93e21d3bbc01c38ecc3a6ea31bd4ceb8bbfd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libField/Field.hpp", "max_issues_repo_name": "CD3/libField", "max_issues_repo_head_hexsha": "8aa93e21d3bbc01c38ecc3a6ea31bd4ceb8bbfd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-06-18T17:05:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T19:14:38.000Z", "max_forks_repo_path": "src/libField/Field.hpp", "max_forks_repo_name": "CD3/libField", "max_forks_repo_head_hexsha": "8aa93e21d3bbc01c38ecc3a6ea31bd4ceb8bbfd6", "max_forks_repo_licenses": ["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.4023591088, "max_line_length": 187, "alphanum_fraction": 0.626281537, "num_tokens": 6105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5139468953214537}}
{"text": "// This file is a part of the OpenSurgSim project.\n// Copyright 2013, SimQuest Solutions Inc.\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/// \\file\n/// Tests that exercise the isValid() functions.\n\n#include <limits>\n#include <iostream>\n#include \"SurgSim/Math/Matrix.h\"\n#include \"SurgSim/Math/Valid.h\"\n#include <Eigen/Core>\n#include \"gtest/gtest.h\"\n\n// Define test fixture class templates.\n// We don't really need fixtures as such, but the templatization encodes type.\n\ntemplate <class T>\nclass ValidTests : public testing::Test\n{\npublic:\n\ttypedef T Scalar;\n};\n\n// This used to contain aligned (via Eigen::AutoAlign) matrix type aliases, but we got rid of those.\ntypedef ::testing::Types<double, float> FloatingPointVariants;\nTYPED_TEST_CASE(ValidTests, FloatingPointVariants);\n\n// Now we're ready to start testing...\n\n\nTYPED_TEST(ValidTests, ValidScalars)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\tusing SurgSim::Math::isValid;\n\n\tEXPECT_TRUE(isValid(static_cast<Scalar>(0)));\n\tEXPECT_TRUE(isValid(static_cast<Scalar>(1)));\n\tEXPECT_TRUE(isValid(std::numeric_limits<Scalar>::denorm_min()));\n\tEXPECT_FALSE(isValid(std::numeric_limits<Scalar>::quiet_NaN()));\n\tEXPECT_FALSE(isValid(std::numeric_limits<Scalar>::signaling_NaN()));\n\tEXPECT_FALSE(isValid(std::numeric_limits<Scalar>::infinity()));\n}\n\nTYPED_TEST(ValidTests, SubnormalScalars)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\tusing SurgSim::Math::isSubnormal;\n\n\tEXPECT_FALSE(isSubnormal(static_cast<Scalar>(0)));\n\tEXPECT_FALSE(isSubnormal(static_cast<Scalar>(1)));\n\tEXPECT_TRUE(isSubnormal(std::numeric_limits<Scalar>::denorm_min()));\n\tEXPECT_FALSE(isSubnormal(std::numeric_limits<Scalar>::quiet_NaN()));\n\tEXPECT_FALSE(isSubnormal(std::numeric_limits<Scalar>::signaling_NaN()));\n\tEXPECT_FALSE(isSubnormal(std::numeric_limits<Scalar>::infinity()));\n}\n\nTYPED_TEST(ValidTests, SubnormalArithmetic)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\tusing SurgSim::Math::isSubnormal;\n\n\tScalar x = 1;\n\tEXPECT_FALSE(isSubnormal(x));\n\n\tint normalSteps;\n\tfor (normalSteps = 0;  normalSteps < 1000000;  ++normalSteps)\n\t{\n\t\tif (isSubnormal(x) || (x == 0))\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\tx /= 2;\n\t}\n\tEXPECT_GT(normalSteps, 0);\n\n\tint subnormalSteps;\n\tfor (subnormalSteps = 0;  subnormalSteps < 1000000;  ++subnormalSteps)\n\t{\n\t\tif (!isSubnormal(x) || (x == 0))\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\tx /= 2;\n\t}\n\tEXPECT_GT(subnormalSteps, 0);\n}\n\ntemplate <typename T>\nstatic void matrixCheckHelper(const T& validMatrix)\n{\n\t// Assumes T is a matrix, 2x2 or larger\n\n\ttypedef T Matrix;\n\ttypedef typename Matrix::Scalar Scalar;\n\n\tusing SurgSim::Math::isValid;\n\tusing SurgSim::Math::isSubnormal;\n\n\t{\n\t\tMatrix matrix = validMatrix;\n\t\tEXPECT_TRUE(isValid(matrix));\n\t\tEXPECT_FALSE(isSubnormal(matrix));\n\t\tmatrix(0, 1) = std::numeric_limits<Scalar>::denorm_min();\n\t\tEXPECT_TRUE(isValid(matrix));\n\t\tEXPECT_TRUE(isSubnormal(matrix));\n\t}\n\t{\n\t\tMatrix matrix = validMatrix;\n\t\tEXPECT_TRUE(isValid(matrix));\n\t\tEXPECT_FALSE(isSubnormal(matrix));\n\t\tmatrix(0, 0) = std::numeric_limits<Scalar>::infinity();\n\t\tEXPECT_FALSE(isValid(matrix));\n\t\tEXPECT_FALSE(isSubnormal(matrix));\n\t\tmatrix(1, 1) = std::numeric_limits<Scalar>::denorm_min();\n\t\tEXPECT_FALSE(isValid(matrix));\n\t\tEXPECT_TRUE(isSubnormal(matrix));\n\t}\n\t{\n\t\tMatrix matrix = validMatrix;\n\t\tEXPECT_TRUE(isValid(matrix));\n\t\tEXPECT_FALSE(isSubnormal(matrix));\n\t\tmatrix(1, 0) = std::numeric_limits<Scalar>::quiet_NaN();\n\t\tEXPECT_FALSE(isValid(matrix));\n\t\tEXPECT_FALSE(isSubnormal(matrix));\n\t}\n}\n\nTYPED_TEST(ValidTests, MatrixChecks)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\n\t{\n\t\tEigen::Matrix<Scalar, 2, 2, Eigen::RowMajor> matrix;\n\t\tmatrix.setIdentity();\n\t\tmatrixCheckHelper(matrix);\n\t\tmatrix.setZero();\n\t\tmatrixCheckHelper(matrix);\n\t}\n\t{\n\t\tEigen::Matrix<Scalar, 3, 3, Eigen::ColMajor> matrix;\n\t\tmatrix.setIdentity();\n\t\tmatrixCheckHelper(matrix);\n\t}\n\t{\n\t\tEigen::Matrix<Scalar, 4, 4, Eigen::RowMajor> matrix;\n\t\tmatrix.setIdentity();\n\t\tmatrixCheckHelper(matrix);\n\t}\n\t{\n\t\tEigen::Matrix<Scalar, 4, 4, Eigen::ColMajor> matrix;\n\t\tmatrix.setIdentity();\n\t\tmatrixCheckHelper(matrix);\n\t}\n\n\t{\n\t\tEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> matrix;\n\t\tmatrix.setIdentity(11, 11);\n\t\tmatrixCheckHelper(matrix);\n\t}\n}\n\ntemplate <typename T>\nstatic void vectorCheckHelper(const T& validVector)\n{\n\t// Assumes T is a vector, size 2 or larger\n\n\ttypedef T Vector;\n\ttypedef typename Vector::Scalar Scalar;\n\n\tusing SurgSim::Math::isValid;\n\tusing SurgSim::Math::isSubnormal;\n\n\t{\n\t\tVector vector = validVector;\n\t\tEXPECT_TRUE(isValid(vector));\n\t\tEXPECT_FALSE(isSubnormal(vector));\n\t\tvector[0] = static_cast<Scalar>(1);\n\t\tEXPECT_TRUE(isValid(vector));\n\t\tEXPECT_FALSE(isSubnormal(vector));\n\t}\n\t{\n\t\tVector vector = validVector;\n\t\tEXPECT_TRUE(isValid(vector));\n\t\tEXPECT_FALSE(isSubnormal(vector));\n\t\tvector[1] = std::numeric_limits<Scalar>::denorm_min();\n\t\tEXPECT_TRUE(isValid(vector));\n\t\tEXPECT_TRUE(isSubnormal(vector));\n\t}\n\t{\n\t\tVector vector = validVector;\n\t\tEXPECT_TRUE(isValid(vector));\n\t\tEXPECT_FALSE(isSubnormal(vector));\n\t\tvector[0] = std::numeric_limits<Scalar>::infinity();\n\t\tEXPECT_FALSE(isValid(vector));\n\t\tEXPECT_FALSE(isSubnormal(vector));\n\t\tvector[1] = std::numeric_limits<Scalar>::denorm_min();\n\t\tEXPECT_FALSE(isValid(vector));\n\t\tEXPECT_TRUE(isSubnormal(vector));\n\t}\n\t{\n\t\tVector vector = validVector;\n\t\tEXPECT_TRUE(isValid(vector));\n\t\tEXPECT_FALSE(isSubnormal(vector));\n\t\tvector[1] = std::numeric_limits<Scalar>::quiet_NaN();\n\t\tEXPECT_FALSE(isValid(vector));\n\t\tEXPECT_FALSE(isSubnormal(vector));\n\t}\n}\n\nTYPED_TEST(ValidTests, VectorChecks)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\n\t{\n\t\tEigen::Matrix<Scalar, 2, 1> vector;\n\t\tvector.setZero();\n\t\tvectorCheckHelper(vector);\n\t\tvector.setZero();\n\t\tvectorCheckHelper(vector);\n\t}\n\t{\n\t\tEigen::Matrix<Scalar, 3, 1> vector;\n\t\tvector.setZero();\n\t\tvectorCheckHelper(vector);\n\t}\n\t{\n\t\tEigen::Matrix<Scalar, 4, 1> vector;\n\t\tvector.setZero();\n\t\tvectorCheckHelper(vector);\n\t}\n\t{\n\t\tEigen::Matrix<Scalar, 4, 1, Eigen::AutoAlign> vector;\n\t\tvector.setZero();\n\t\tvectorCheckHelper(vector);\n\t}\n\n\t{\n\t\tEigen::Matrix<Scalar, Eigen::Dynamic, 1> vector;\n\t\tvector.setZero(11);\n\t\tvectorCheckHelper(vector);\n\t}\n}\n\nTYPED_TEST(ValidTests, QuaternionChecks)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\tusing SurgSim::Math::isValid;\n\tusing SurgSim::Math::isSubnormal;\n\n\tEigen::Quaternion<Scalar> quaternion(1, 0, 0, 0);\n\tEXPECT_TRUE(isValid(quaternion));\n\tEXPECT_FALSE(isSubnormal(quaternion));\n\n\tquaternion.x() = std::numeric_limits<Scalar>::denorm_min();\n\tEXPECT_TRUE(isValid(quaternion));\n\tEXPECT_TRUE(isSubnormal(quaternion));\n\n\tquaternion = Eigen::Quaternion<Scalar>(std::numeric_limits<Scalar>::infinity(), 0, 0, 0);\n\tEXPECT_FALSE(isValid(quaternion));\n\tEXPECT_FALSE(isSubnormal(quaternion));\n\n\tquaternion.z() = std::numeric_limits<Scalar>::denorm_min();\n\tEXPECT_FALSE(isValid(quaternion));\n\tEXPECT_TRUE(isSubnormal(quaternion));\n}\n\nTYPED_TEST(ValidTests, AngleAxisChecks)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\tusing SurgSim::Math::isValid;\n\tusing SurgSim::Math::isSubnormal;\n\n\tEigen::AngleAxis<Scalar> rotation = Eigen::AngleAxis<Scalar>::Identity();\n\tEXPECT_TRUE(isValid(rotation));\n\tEXPECT_FALSE(isSubnormal(rotation));\n\n\trotation.angle() = std::numeric_limits<Scalar>::denorm_min();\n\tEXPECT_TRUE(isValid(rotation));\n\tEXPECT_TRUE(isSubnormal(rotation));\n\n\trotation = Eigen::AngleAxis<Scalar>::Identity();\n\trotation.axis()[2] = std::numeric_limits<Scalar>::denorm_min();\n\tEXPECT_TRUE(isValid(rotation));\n\tEXPECT_TRUE(isSubnormal(rotation));\n\n\trotation = Eigen::AngleAxis<Scalar>::Identity();\n\trotation.angle() = std::numeric_limits<Scalar>::infinity();\n\tEXPECT_FALSE(isValid(rotation));\n\tEXPECT_FALSE(isSubnormal(rotation));\n\trotation.axis()[1] = std::numeric_limits<Scalar>::denorm_min();\n\tEXPECT_FALSE(isValid(rotation));\n\tEXPECT_TRUE(isSubnormal(rotation));\n\n\trotation = Eigen::AngleAxis<Scalar>::Identity();\n\trotation.axis()[0] = std::numeric_limits<Scalar>::quiet_NaN();\n\tEXPECT_FALSE(isValid(rotation));\n\tEXPECT_FALSE(isSubnormal(rotation));\n\trotation.angle() = std::numeric_limits<Scalar>::denorm_min();\n\tEXPECT_FALSE(isValid(rotation));\n\tEXPECT_TRUE(isSubnormal(rotation));\n}\n\nTYPED_TEST(ValidTests, Rotation2DChecks)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\tusing SurgSim::Math::isValid;\n\tusing SurgSim::Math::isSubnormal;\n\n\tEigen::Rotation2D<Scalar> rotation(0);\n\tEXPECT_TRUE(isValid(rotation));\n\tEXPECT_FALSE(isSubnormal(rotation));\n\n\trotation.angle() = static_cast<Scalar>(1);\n\tEXPECT_TRUE(isValid(rotation));\n\tEXPECT_FALSE(isSubnormal(rotation));\n\n\trotation.angle() = std::numeric_limits<Scalar>::denorm_min();\n\tEXPECT_TRUE(isValid(rotation));\n\tEXPECT_TRUE(isSubnormal(rotation));\n\n\trotation = Eigen::Rotation2D<Scalar>(std::numeric_limits<Scalar>::infinity());\n\tEXPECT_FALSE(isValid(rotation));\n\tEXPECT_FALSE(isSubnormal(rotation));\n}\n\ntemplate <typename T>\nstatic void transformCheckHelper()\n{\n\t// Assumes T is an Eigen::Transform type of some sort\n\n\ttypedef T Transform;\n\ttypedef typename Transform::Scalar Scalar;\n\n\tusing SurgSim::Math::isValid;\n\tusing SurgSim::Math::isSubnormal;\n\n\tTransform transform = Transform::Identity();\n\tEXPECT_TRUE(isValid(transform));\n\tEXPECT_FALSE(isSubnormal(transform));\n\n\ttransform(1, 1) = std::numeric_limits<Scalar>::denorm_min();\n\tEXPECT_TRUE(isValid(transform));\n\tEXPECT_TRUE(isSubnormal(transform));\n\n\ttransform = Transform::Identity();\n\ttransform(0, 0) = std::numeric_limits<Scalar>::quiet_NaN();\n\tEXPECT_FALSE(isValid(transform));\n\tEXPECT_FALSE(isSubnormal(transform));\n\n\ttransform(0, 1) = std::numeric_limits<Scalar>::denorm_min();\n\tEXPECT_FALSE(isValid(transform));\n\tEXPECT_TRUE(isSubnormal(transform));\n}\n\nTYPED_TEST(ValidTests, TransformChecks)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\tusing SurgSim::Math::isValid;\n\tusing SurgSim::Math::isSubnormal;\n\n\ttransformCheckHelper<Eigen::Transform<Scalar, 2, Eigen::Isometry>>();\n\ttransformCheckHelper<Eigen::Transform<Scalar, 3, Eigen::Isometry>>();\n\ttransformCheckHelper<Eigen::Transform<Scalar, 4, Eigen::Isometry>>();\n\ttransformCheckHelper<Eigen::Transform<Scalar, 4, Eigen::Isometry>>();\n\ttransformCheckHelper<Eigen::Transform<Scalar, 4, Eigen::Affine>>();\n\ttransformCheckHelper<Eigen::Transform<Scalar, 4, Eigen::AffineCompact>>();\n}\n\nTYPED_TEST(ValidTests, ClearSubnormalScalars)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\tusing SurgSim::Math::setSubnormalToZero;\n\tusing SurgSim::Math::isValid;\n\tScalar x;\n\n\tx = 0;\n\tEXPECT_FALSE(setSubnormalToZero(&x));\n\tEXPECT_EQ(0, x);\n\n\tx = -1;\n\tEXPECT_FALSE(setSubnormalToZero(&x));\n\tEXPECT_EQ(-1, x);\n\n\tx = std::numeric_limits<Scalar>::infinity();\n\tEXPECT_FALSE(setSubnormalToZero(&x));\n\tEXPECT_FALSE(isValid(x));\n\n\tx = std::numeric_limits<Scalar>::quiet_NaN();\n\tEXPECT_FALSE(setSubnormalToZero(&x));\n\tEXPECT_FALSE(isValid(x));\n\n\tx = std::numeric_limits<Scalar>::signaling_NaN();\n\tEXPECT_FALSE(setSubnormalToZero(&x));\n\tEXPECT_FALSE(isValid(x));\n\n\tx = std::numeric_limits<Scalar>::denorm_min();\n\tEXPECT_TRUE(setSubnormalToZero(&x));\n\tEXPECT_EQ(0, x);\n}\n\ntemplate <typename T>\nstatic void compareMatrices(const T& a, const T& b)\n{\n\ttypedef T Matrix;\n\tusing Eigen::Index;\n\n\tEXPECT_EQ(a.rows(), b.rows());\n\tEXPECT_EQ(a.cols(), b.cols());\n\n\tconst Index numColumns = std::min(a.cols(), b.cols());\n\tconst Index numRows = std::min(a.rows(), b.rows());\n\n\tfor (Index j = 0; j < numColumns; ++j)\n\t{\n\t\tfor (Index i = 0; i < numRows; ++i)\n\t\t{\n\t\t\tbool isValidAij = SurgSim::Math::isValid(a.coeff(i, j));\n\t\t\tbool isValidBij = SurgSim::Math::isValid(b.coeff(i, j));\n\t\t\tEXPECT_EQ(isValidAij, isValidBij) << \"i = \" << i << \", j = \" << j <<\n\t\t\t\t\", Aij = \" << a.coeff(i, j) << \", Bij = \" << b.coeff(i, j);\n\t\t\tif (isValidAij && isValidBij)\n\t\t\t{\n\t\t\t\t// In general, floating point equality checks are bad, but here they are needed.\n\t\t\t\tEXPECT_EQ(a.coeff(i, j), b.coeff(i, j)) << \"i = \" << i << \", j = \" << j;\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate <typename T>\nstatic void matrixSetSubnormalHelper(const T& validMatrix)\n{\n\t// Assumes T is a matrix, 2x2 or larger\n\n\ttypedef T Matrix;\n\ttypedef typename Matrix::Scalar Scalar;\n\n\tEXPECT_TRUE(SurgSim::Math::isValid(validMatrix));\n\tEXPECT_FALSE(SurgSim::Math::isSubnormal(validMatrix));\n\n\tusing SurgSim::Math::setSubnormalToZero;\n\n\t{\n\t\tMatrix a = validMatrix;\n\t\tMatrix b = a;\n\t\tEXPECT_FALSE(setSubnormalToZero(&a));\n\t\tEXPECT_FALSE(setSubnormalToZero(&b));\n\t\tcompareMatrices(a, b);\n\t}\n\t{\n\t\tMatrix a = validMatrix;\n\t\ta(0, 1) = 0;\n\t\tMatrix b = a;\n\t\tb(0, 1) = std::numeric_limits<Scalar>::denorm_min();\n\t\tEXPECT_FALSE(setSubnormalToZero(&a));\n\t\tEXPECT_TRUE(setSubnormalToZero(&b));\n\t\tcompareMatrices(a, b);\n\t}\n\t{\n\t\tMatrix a = validMatrix;\n\t\ta(0, 0) = std::numeric_limits<Scalar>::infinity();\n\t\tMatrix b = a;\n\t\tEXPECT_FALSE(setSubnormalToZero(&a));\n\t\tEXPECT_FALSE(setSubnormalToZero(&b));\n\t\tcompareMatrices(a, b);\n\t}\n\t{\n\t\tMatrix a = validMatrix;\n\t\ta(1, 0) = std::numeric_limits<Scalar>::quiet_NaN();\n\t\ta(1, 1) = 0;\n\t\tMatrix b = a;\n\t\tb(1, 1) = std::numeric_limits<Scalar>::denorm_min();\n\t\tEXPECT_FALSE(setSubnormalToZero(&a));\n\t\tEXPECT_TRUE(setSubnormalToZero(&b));\n\t\tcompareMatrices(a, b);\n\t}\n}\n\nTYPED_TEST(ValidTests, ClearSubnormalMatrix)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\n\t{\n\t\tEigen::Matrix<Scalar, 2, 2, Eigen::RowMajor> matrix;\n\t\tmatrix.setConstant(123);\n\t\tmatrixSetSubnormalHelper(matrix);\n\t\tmatrix.setZero();\n\t\tmatrixSetSubnormalHelper(matrix);\n\t}\n\t{\n\t\tEigen::Matrix<Scalar, 3, 3, Eigen::ColMajor> matrix;\n\t\tmatrix.setConstant(123);\n\t\tmatrixSetSubnormalHelper(matrix);\n\t}\n\t{\n\t\tEigen::Matrix<Scalar, 4, 4, Eigen::RowMajor> matrix;\n\t\tmatrix.setConstant(123);\n\t\tmatrixSetSubnormalHelper(matrix);\n\t}\n\t{\n\t\tEigen::Matrix<Scalar, 4, 4, Eigen::ColMajor> matrix;\n\t\tmatrix.setConstant(123);\n\t\tmatrixSetSubnormalHelper(matrix);\n\t}\n\n\t{\n\t\tEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> matrix;\n\t\tmatrix.setConstant(11, 13, static_cast<Scalar>(123));\n\t\tmatrixSetSubnormalHelper(matrix);\n\t}\n}\n\ntemplate <typename T>\nstatic void vectorSetSubnormalHelper(const T& validVector)\n{\n\t// Assumes T is a vector, size 2 or larger\n\n\ttypedef T Vector;\n\ttypedef typename Vector::Scalar Scalar;\n\n\tusing SurgSim::Math::setSubnormalToZero;\n\n\t{\n\t\tVector a = validVector;\n\t\tVector b = a;\n\t\tEXPECT_FALSE(setSubnormalToZero(&a));\n\t\tEXPECT_FALSE(setSubnormalToZero(&b));\n\t\tcompareMatrices(a, b);\n\t}\n\t{\n\t\tVector a = validVector;\n\t\ta[0] = 0;\n\t\tVector b = a;\n\t\tb[0] = std::numeric_limits<Scalar>::denorm_min();\n\t\tEXPECT_FALSE(setSubnormalToZero(&a));\n\t\tEXPECT_TRUE(setSubnormalToZero(&b));\n\t\tcompareMatrices(a, b);\n\t}\n\t{\n\t\tVector a = validVector;\n\t\ta[1] = std::numeric_limits<Scalar>::infinity();\n\t\tVector b = a;\n\t\tEXPECT_FALSE(setSubnormalToZero(&a));\n\t\tEXPECT_FALSE(setSubnormalToZero(&b));\n\t\tcompareMatrices(a, b);\n\t}\n\t{\n\t\tVector a = validVector;\n\t\ta[0] = std::numeric_limits<Scalar>::quiet_NaN();\n\t\ta[1] = 0;\n\t\tVector b = a;\n\t\tb[1] = std::numeric_limits<Scalar>::denorm_min();\n\t\tEXPECT_FALSE(setSubnormalToZero(&a));\n\t\tEXPECT_TRUE(setSubnormalToZero(&b));\n\t\tcompareMatrices(a, b);\n\t}\n}\n\nTYPED_TEST(ValidTests, ClearSubnormalVector)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\n\t{\n\t\tEigen::Matrix<Scalar, 2, 1> vector;\n\t\tvector.setConstant(543);\n\t\tvectorSetSubnormalHelper(vector);\n\t\tvector.setZero();\n\t\tvectorSetSubnormalHelper(vector);\n\t}\n\t{\n\t\tEigen::Matrix<Scalar, 3, 1> vector;\n\t\tvector.setConstant(543);\n\t\tvectorSetSubnormalHelper(vector);\n\t}\n\t{\n\t\tEigen::Matrix<Scalar, 4, 1> vector;\n\t\tvector.setConstant(543);\n\t\tvectorSetSubnormalHelper(vector);\n\t}\n\t{\n\t\tEigen::Matrix<Scalar, 4, 1, Eigen::AutoAlign> vector;\n\t\tvector.setConstant(543);\n\t\tvectorSetSubnormalHelper(vector);\n\t}\n\n\t{\n\t\tEigen::Matrix<Scalar, Eigen::Dynamic, 1> vector;\n\t\tvector.setConstant(21, static_cast<Scalar>(543));\n\t\tvectorSetSubnormalHelper(vector);\n\t}\n}\n\nTYPED_TEST(ValidTests, ClearSubnormalQuaternion)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\tusing SurgSim::Math::setSubnormalToZero;\n\n\tEigen::Quaternion<Scalar> quaternion(1, 0, 0, 0);\n\tEXPECT_FALSE(setSubnormalToZero(&quaternion));\n\n\t{\n\t\tEigen::Quaternion<Scalar> q2 = quaternion;\n\t\tq2.x() = std::numeric_limits<Scalar>::denorm_min();\n\t\tEXPECT_TRUE(setSubnormalToZero(&q2));\n\t\tcompareMatrices(quaternion.coeffs(), q2.coeffs());\n\t}\n\t{\n\t\tEigen::Quaternion<Scalar> q3 = quaternion;\n\t\tq3.y() = std::numeric_limits<Scalar>::infinity();\n\t\tEXPECT_FALSE(setSubnormalToZero(&q3));\n\t\tEXPECT_FALSE(SurgSim::Math::isValid(q3));\n\n\t\tEigen::Quaternion<Scalar> q4 = q3;\n\t\tq4.z() = std::numeric_limits<Scalar>::denorm_min();\n\t\tEXPECT_TRUE(setSubnormalToZero(&q4));\n\t\tcompareMatrices(q3.coeffs(), q4.coeffs());\n\t}\n}\n\ntemplate <typename T>\nstatic void compareAngleAxis(const T& a, const T& b)\n{\n\tbool isValidAngleA = SurgSim::Math::isValid(a.angle());\n\tbool isValidAngleB = SurgSim::Math::isValid(b.angle());\n\n\tEXPECT_EQ(isValidAngleA, isValidAngleB) << \" angle A = \" << a.angle() << \", B = \" << b.angle();\n\tif (isValidAngleA && isValidAngleB)\n\t{\n\t\t// In general, floating point equality checks are bad, but here they are needed.\n\t\tEXPECT_EQ(a.angle(), b.angle());\n\t}\n\n\tcompareMatrices(a.axis(), b.axis());\n}\n\nTYPED_TEST(ValidTests, ClearSubnormalAngleAxis)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\tusing SurgSim::Math::setSubnormalToZero;\n\n\ttypedef Eigen::AngleAxis<Scalar> AngleAxis;\n\ttypedef Eigen::Matrix<Scalar, 3, 1> Vector3;\n\n\tAngleAxis rotation;\n\n\trotation = AngleAxis(-1, Vector3(1, 2, 3));\n\tEXPECT_FALSE(setSubnormalToZero(&rotation));\n\tcompareAngleAxis(AngleAxis(-1, Vector3(1, 2, 3)), rotation);\n\n\trotation = AngleAxis(std::numeric_limits<Scalar>::denorm_min(), Vector3(1, 2, 3));\n\tEXPECT_TRUE(setSubnormalToZero(&rotation));\n\tcompareAngleAxis(AngleAxis(0, Vector3(1, 2, 3)), rotation);\n\n\trotation = AngleAxis(-1, Vector3(std::numeric_limits<Scalar>::denorm_min(), 2, 3));\n\tEXPECT_TRUE(setSubnormalToZero(&rotation));\n\tcompareAngleAxis(AngleAxis(-1, Vector3(0, 2, 3)), rotation);\n\n\trotation = AngleAxis(-1, Vector3(1, std::numeric_limits<Scalar>::infinity(), 3));\n\tEXPECT_FALSE(setSubnormalToZero(&rotation));\n\tcompareAngleAxis(AngleAxis(-1, Vector3(1, std::numeric_limits<Scalar>::infinity(), 3)), rotation);\n\n\trotation = AngleAxis(std::numeric_limits<Scalar>::denorm_min(),\n\t\t\t\t\t\t Vector3(1, 2, std::numeric_limits<Scalar>::infinity()));\n\tEXPECT_TRUE(setSubnormalToZero(&rotation));\n\tcompareAngleAxis(AngleAxis(0, Vector3(1, 2, std::numeric_limits<Scalar>::infinity())), rotation);\n}\n\nTYPED_TEST(ValidTests, ClearSubnormalRotation2D)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\tusing SurgSim::Math::setSubnormalToZero;\n\n\tEigen::Rotation2D<Scalar> rotation(0);\n\tEXPECT_FALSE(setSubnormalToZero(&rotation));\n\tEXPECT_EQ(0, rotation.angle());\n\n\trotation.angle() = static_cast<Scalar>(1);\n\tEXPECT_FALSE(setSubnormalToZero(&rotation));\n\tEXPECT_EQ(1, rotation.angle());\n\n\trotation.angle() = std::numeric_limits<Scalar>::denorm_min();\n\tEXPECT_TRUE(setSubnormalToZero(&rotation));\n\tEXPECT_EQ(0, rotation.angle());\n\n\trotation = Eigen::Rotation2D<Scalar>(std::numeric_limits<Scalar>::infinity());\n\tEXPECT_FALSE(setSubnormalToZero(&rotation));\n\tEXPECT_FALSE(SurgSim::Math::isValid(rotation.angle()));\n}\n\ntemplate <typename T>\nstatic void transformSetSubnormalHelper()\n{\n\t// Assumes T is an Eigen::Transform type of some sort\n\n\ttypedef T Transform;\n\ttypedef typename Transform::Scalar Scalar;\n\n\tusing SurgSim::Math::setSubnormalToZero;\n\n\tTransform transform = Transform::Identity();\n\tEXPECT_FALSE(setSubnormalToZero(&transform));\n\tcompareMatrices(Transform::Identity().matrix(), transform.matrix());\n\n\t{\n\t\tTransform t2 = transform;\n\t\tt2(0, 1) = std::numeric_limits<Scalar>::denorm_min();\n\t\tEXPECT_TRUE(setSubnormalToZero(&t2));\n\t\tcompareMatrices(Transform::Identity().matrix(), transform.matrix());\n\t}\n\t{\n\t\tTransform t3 = transform;\n\t\tt3(0, 1) = std::numeric_limits<Scalar>::quiet_NaN();\n\t\tTransform t4 = t3;\n\t\tEXPECT_FALSE(setSubnormalToZero(&t4));\n\t\tcompareMatrices(t3.matrix(), t4.matrix());\n\t}\n\t{\n\t\tTransform t5 = transform;\n\t\tt5(0, 1) = std::numeric_limits<Scalar>::quiet_NaN();\n\t\tt5(1, 0) = 0;\n\t\tTransform t6 = t5;\n\t\tt6(1, 0) = std::numeric_limits<Scalar>::denorm_min();\n\t\tEXPECT_TRUE(setSubnormalToZero(&t6));\n\t\tcompareMatrices(t5.matrix(), t6.matrix());\n\t}\n}\n\nTYPED_TEST(ValidTests, ClearSubnormalTransform)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\n\ttransformSetSubnormalHelper<Eigen::Transform<Scalar, 2, Eigen::Isometry>>();\n\ttransformSetSubnormalHelper<Eigen::Transform<Scalar, 3, Eigen::Isometry>>();\n\ttransformSetSubnormalHelper<Eigen::Transform<Scalar, 4, Eigen::Isometry>>();\n\ttransformSetSubnormalHelper<Eigen::Transform<Scalar, 4, Eigen::Isometry>>();\n\ttransformSetSubnormalHelper<Eigen::Transform<Scalar, 4, Eigen::Affine>>();\n\ttransformSetSubnormalHelper<Eigen::Transform<Scalar, 4, Eigen::AffineCompact>>();\n}\n\nTYPED_TEST(ValidTests, Blocks)\n{\n\ttypedef typename TestFixture::Scalar Scalar;\n\tusing SurgSim::Math::isValid;\n\tusing SurgSim::Math::isSubnormal;\n\tusing SurgSim::Math::setSubnormalToZero;\n\n\t{\n\t\tEigen::Matrix<Scalar, 4, 4, Eigen::RowMajor> matrix;\n\t\tmatrix.setConstant(123);\n\t\tEXPECT_TRUE(isValid(matrix.template block<2, 2>(1, 1)));\n\t\tEXPECT_FALSE(isSubnormal(matrix.template block<2, 2>(1, 1)));\n\t\t{\n\t\t\tauto submatrix = matrix.template block<2, 2>(1, 1);\n\t\t\tEXPECT_FALSE(setSubnormalToZero(&submatrix));\n\t\t}\n\t}\n\t{\n\t\tEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> matrix;\n\t\tmatrix.setConstant(11, 13, static_cast<Scalar>(123));\n\t\tEXPECT_TRUE(isValid(matrix.template block<6, 6>(3, 5)));\n\t\tEXPECT_FALSE(isSubnormal(matrix.template block<6, 6>(3, 5)));\n\t\t{\n\t\t\tauto submatrix = matrix.template block<6, 6>(3, 5);\n\t\t\tEXPECT_FALSE(setSubnormalToZero(&submatrix));\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "969c31c81475be2e5050924ade69140b7678d0b1", "size": 21927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SurgSim/Math/UnitTests/ValidTests.cpp", "max_stars_repo_name": "dbungert/opensurgsim", "max_stars_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T16:18:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T03:29:11.000Z", "max_issues_repo_path": "SurgSim/Math/UnitTests/ValidTests.cpp", "max_issues_repo_name": "dbungert/opensurgsim", "max_issues_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-12-21T14:54:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T12:38:07.000Z", "max_forks_repo_path": "SurgSim/Math/UnitTests/ValidTests.cpp", "max_forks_repo_name": "dbungert/opensurgsim", "max_forks_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-04-10T19:45:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T17:00:59.000Z", "avg_line_length": 28.1115384615, "max_line_length": 100, "alphanum_fraction": 0.7247685502, "num_tokens": 5859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5139468953214535}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2021 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: Marc Fehling, Colorado State University, 2021 \n *         Peter Munch, Technical University of Munich and Helmholtz-Zentrum \n *                      hereon, 2021 \n *         Wolfgang Bangerth, Colorado State University, 2021 \n */ \n\n\n// @sect3{Include files}  \n\n// \u5728\u4ee5\u524d\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\uff0c\u7279\u522b\u662f\u5728 step-27 \u548c step-40 \u4e2d\uff0c\u5df2\u7ecf\u4f7f\u7528\u548c\u8ba8\u8bba\u4e86\u4ee5\u4e0b\u5305\u542b\u6587\u4ef6\u3002\n\n#include <deal.II/base/conditional_ostream.h> \n#include <deal.II/base/index_set.h> \n#include <deal.II/base/mpi.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/timer.h> \n\n#include <deal.II/distributed/grid_refinement.h> \n#include <deal.II/distributed/tria.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/grid/grid_generator.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_series.h> \n\n#include <deal.II/hp/fe_collection.h> \n#include <deal.II/hp/refinement.h> \n\n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/precondition.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/trilinos_precondition.h> \n#include <deal.II/lac/trilinos_sparse_matrix.h> \n#include <deal.II/lac/vector.h> \n\n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n#include <deal.II/numerics/smoothness_estimator.h> \n#include <deal.II/numerics/vector_tools.h> \n\n#include <algorithm> \n#include <fstream> \n#include <iostream> \n\n// \u4e3a\u4e86\u5b9e\u73b0\u8d1f\u8f7d\u5e73\u8861\uff0c\u6211\u4eec\u5c06\u5728\u5355\u5143\u683c\u4e0a\u5206\u914d\u5355\u72ec\u7684\u6743\u91cd\uff0c\u4e3a\u6b64\u6211\u4eec\u5c06\u4f7f\u7528\u7c7b  parallel::CellWeights.  \u3002\n#include <deal.II/distributed/cell_weights.h> \n\n// \u6c42\u89e3\u51fd\u6570\u9700\u8981\u4ece\u76f4\u89d2\u5750\u6807\u5230\u6781\u5750\u6807\u7684\u8f6c\u6362\u3002 GeometricUtilities::Coordinates \u547d\u540d\u7a7a\u95f4\u63d0\u4f9b\u4e86\u5fc5\u8981\u7684\u5de5\u5177\u3002\n\n#include <deal.II/base/function.h> \n#include <deal.II/base/geometric_utilities.h> \n\n// \u4ee5\u4e0b\u5305\u542b\u7684\u6587\u4ef6\u5c06\u542f\u7528MatrixFree\u529f\u80fd\u3002\n\n#include <deal.II/matrix_free/matrix_free.h> \n#include <deal.II/matrix_free/fe_evaluation.h> \n#include <deal.II/matrix_free/tools.h> \n\n// \u6211\u4eec\u5c06\u4f7f\u7528 LinearAlgebra::distributed::Vector \u8fdb\u884c\u7ebf\u6027\u4ee3\u6570\u64cd\u4f5c\u3002\n\n#include <deal.II/lac/la_parallel_vector.h> \n\n// \u6211\u4eec\u5269\u4e0b\u7684\u5c31\u662f\u5305\u542b\u591a\u7f51\u683c\u6c42\u89e3\u5668\u6240\u9700\u7684\u6587\u4ef6\u3002\n\n#include <deal.II/multigrid/mg_coarse.h> \n#include <deal.II/multigrid/mg_constrained_dofs.h> \n#include <deal.II/multigrid/mg_matrix.h> \n#include <deal.II/multigrid/mg_smoother.h> \n#include <deal.II/multigrid/mg_tools.h> \n#include <deal.II/multigrid/mg_transfer_global_coarsening.h> \n#include <deal.II/multigrid/multigrid.h> \n\nnamespace Step75 \n{ \n  using namespace dealii; \n// @sect3{The <code>Solution</code> class template}  \n\n// \u6211\u4eec\u6709\u4e00\u4e2a\u5206\u6790\u6027\u7684\u65b9\u6848\u53ef\u4ee5\u4f7f\u7528\u3002\u6211\u4eec\u5c06\u7528\u8fd9\u4e2a\u89e3\u6765\u4e3a\u95ee\u9898\u7684\u6570\u503c\u89e3\u65bd\u52a0\u8fb9\u754c\u6761\u4ef6\u3002\u89e3\u51b3\u65b9\u6848\u7684\u8868\u8ff0\u9700\u8981\u8f6c\u6362\u4e3a\u6781\u5750\u6807\u3002\u4e3a\u4e86\u4ece\u7b1b\u5361\u5c14\u5750\u6807\u8f6c\u6362\u5230\u7403\u9762\u5750\u6807\uff0c\u6211\u4eec\u5c06\u4f7f\u7528 GeometricUtilities::Coordinates \u547d\u540d\u7a7a\u95f4\u7684\u4e00\u4e2a\u8f85\u52a9\u51fd\u6570\u3002\u8fd9\u4e2a\u8f6c\u6362\u7684\u524d\u4e24\u4e2a\u5750\u6807\u5bf9\u5e94\u4e8ex-y\u9762\u7684\u6781\u5750\u6807\u3002\n\n  template <int dim> \n  class Solution : public Function<dim> \n  { \n  public: \n    Solution() \n      : Function<dim>() \n    {} \n\n    virtual double value(const Point<dim> &p, \n                         const unsigned int /*component*/) const override \n    { \n      const std::array<double, dim> p_sphere = \n        GeometricUtilities::Coordinates::to_spherical(p); \n\n      constexpr const double alpha = 2. / 3.; \n      return std::pow(p_sphere[0], alpha) * std::sin(alpha * p_sphere[1]); \n    } \n  }; \n\n//  @sect3{Parameters}  \n\n// \u5728\u672c\u6559\u7a0b\u4e2d\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u4e00\u4e2a\u7b80\u5316\u7684\u53c2\u6570\u96c6\u3002\u8fd9\u91cc\u4e5f\u53ef\u4ee5\u4f7f\u7528ParameterHandler\u7c7b\uff0c\u4f46\u4e3a\u4e86\u4f7f\u672c\u6559\u7a0b\u7b80\u77ed\uff0c\u6211\u4eec\u51b3\u5b9a\u4f7f\u7528\u7b80\u5355\u7684\u7ed3\u6784\u3002\u6240\u6709\u8fd9\u4e9b\u53c2\u6570\u7684\u5b9e\u9645\u610f\u56fe\u5c06\u5728\u63a5\u4e0b\u6765\u7684\u7c7b\u4e2d\u63cf\u8ff0\uff0c\u5728\u5b83\u4eec\u5404\u81ea\u4f7f\u7528\u7684\u4f4d\u7f6e\u3002\n\n// \u4e0b\u9762\u7684\u53c2\u6570\u96c6\u63a7\u5236\u7740\u591a\u7f51\u683c\u673a\u5236\u7684\u7c97\u7f51\u683c\u6c42\u89e3\u5668\u3001\u5e73\u6ed1\u5668\u548c\u7f51\u683c\u95f4\u4f20\u8f93\u65b9\u6848\u3002\u6211\u4eec\u7528\u9ed8\u8ba4\u53c2\u6570\u6765\u586b\u5145\u5b83\u3002\n\n  struct MultigridParameters \n  { \n    struct \n    { \n      std::string  type            = \"cg_with_amg\"; \n      unsigned int maxiter         = 10000; \n      double       abstol          = 1e-20; \n      double       reltol          = 1e-4; \n      unsigned int smoother_sweeps = 1; \n      unsigned int n_cycles        = 1; \n      std::string  smoother_type   = \"ILU\"; \n    } coarse_solver; \n\n    struct \n    { \n      std::string  type                = \"chebyshev\"; \n      double       smoothing_range     = 20; \n      unsigned int degree              = 5; \n      unsigned int eig_cg_n_iterations = 20; \n    } smoother; \n\n    struct \n    { \n      MGTransferGlobalCoarseningTools::PolynomialCoarseningSequenceType \n        p_sequence = MGTransferGlobalCoarseningTools:: \n          PolynomialCoarseningSequenceType::decrease_by_one; \n      bool perform_h_transfer = true; \n    } transfer; \n  }; \n\n// \u8fd9\u662f\u8be5\u95ee\u9898\u7c7b\u7684\u4e00\u822c\u53c2\u6570\u7ed3\u6784\u3002\u4f60\u4f1a\u53d1\u73b0\u8fd9\u4e2a\u7ed3\u6784\u5206\u4e3a\u51e0\u4e2a\u7c7b\u522b\uff0c\u5305\u62ec\u4e00\u822c\u7684\u8fd0\u884c\u65f6\u53c2\u6570\u3001\u7ea7\u522b\u9650\u5236\u3001\u7ec6\u5316\u548c\u7c97\u5316\u5206\u6570\uff0c\u4ee5\u53ca\u5355\u5143\u52a0\u6743\u7684\u53c2\u6570\u3002\u5b83\u8fd8\u5305\u542b\u4e00\u4e2a\u4e0a\u8ff0\u7ed3\u6784\u7684\u5b9e\u4f8b\uff0c\u7528\u4e8e\u591a\u7f51\u683c\u53c2\u6570\uff0c\u8fd9\u4e9b\u53c2\u6570\u5c06\u88ab\u4f20\u9012\u7ed9\u591a\u7f51\u683c\u7b97\u6cd5\u3002\n\n  struct Parameters \n  { \n    unsigned int n_cycles         = 8; \n    double       tolerance_factor = 1e-12; \n\n    MultigridParameters mg_data; \n\n    unsigned int min_h_level            = 5; \n    unsigned int max_h_level            = 12; \n    unsigned int min_p_degree           = 2; \n    unsigned int max_p_degree           = 6; \n    unsigned int max_p_level_difference = 1; \n\n    double refine_fraction    = 0.3; \n    double coarsen_fraction   = 0.03; \n    double p_refine_fraction  = 0.9; \n    double p_coarsen_fraction = 0.9; \n\n    double weighting_factor   = 1e6; \n    double weighting_exponent = 1.; \n  }; \n\n//  @sect3{Matrix-free Laplace operator}  \n\n// \u8fd9\u662f\u4e00\u4e2a\u65e0\u77e9\u9635\u7684\u62c9\u666e\u62c9\u65af\u7b97\u5b50\u7684\u5b9e\u73b0\uff0c\u57fa\u672c\u4e0a\u5c06\u63a5\u7ba1\u5176\u4ed6\u6559\u7a0b\u4e2d\u7684`assemble_system()`\u51fd\u6570\u7684\u90e8\u5206\u3002\u6240\u6709\u6210\u5458\u51fd\u6570\u7684\u542b\u4e49\u5c06\u5728\u540e\u9762\u7684\u5b9a\u4e49\u4e2d\u89e3\u91ca\u3002\n\n// \u6211\u4eec\u5c06\u4f7f\u7528FEEvaluation\u7c7b\u6765\u8bc4\u4f30\u6b63\u4ea4\u70b9\u7684\u89e3\u5411\u91cf\u5e76\u8fdb\u884c\u79ef\u5206\u3002\u4e0e\u5176\u4ed6\u6559\u7a0b\u4e0d\u540c\u7684\u662f\uff0c\u6a21\u677f\u53c2\u6570`\u5ea6\u6570`\u88ab\u8bbe\u7f6e\u4e3a  $-1$  \uff0c`\u4e00\u7ef4\u6b63\u4ea4\u6570`\u88ab\u8bbe\u7f6e\u4e3a  $0$  \u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0cFEEvaluation\u4f1a\u52a8\u6001\u5730\u9009\u62e9\u6b63\u786e\u7684\u591a\u9879\u5f0f\u5ea6\u6570\u548c\u6b63\u4ea4\u70b9\u7684\u6570\u91cf\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u4e3aFEEvaluation\u5f15\u5165\u4e00\u4e2a\u5e26\u6709\u6b63\u786e\u6a21\u677f\u53c2\u6570\u7684\u522b\u540d\uff0c\u8fd9\u6837\u6211\u4eec\u4ee5\u540e\u5c31\u4e0d\u7528\u62c5\u5fc3\u8fd9\u4e9b\u53c2\u6570\u4e86\u3002\n\n  template <int dim, typename number> \n  class LaplaceOperator : public Subscriptor \n  { \n  public: \n    using VectorType = LinearAlgebra::distributed::Vector<number>; \n\n    using FECellIntegrator = FEEvaluation<dim, -1, 0, 1, number>; \n\n    LaplaceOperator() = default; \n\n    LaplaceOperator(const hp::MappingCollection<dim> &mapping, \n                    const DoFHandler<dim> &           dof_handler, \n                    const hp::QCollection<dim> &      quad, \n                    const AffineConstraints<number> & constraints, \n                    VectorType &                      system_rhs); \n\n    void reinit(const hp::MappingCollection<dim> &mapping, \n                const DoFHandler<dim> &           dof_handler, \n                const hp::QCollection<dim> &      quad, \n                const AffineConstraints<number> & constraints, \n                VectorType &                      system_rhs); \n\n    types::global_dof_index m() const; \n\n    number el(unsigned int, unsigned int) const; \n\n    void initialize_dof_vector(VectorType &vec) const; \n\n    void vmult(VectorType &dst, const VectorType &src) const; \n\n    void Tvmult(VectorType &dst, const VectorType &src) const; \n\n    const TrilinosWrappers::SparseMatrix &get_system_matrix() const; \n\n    void compute_inverse_diagonal(VectorType &diagonal) const; \n\n  private: \n    void do_cell_integral_local(FECellIntegrator &integrator) const; \n\n    void do_cell_integral_global(FECellIntegrator &integrator, \n                                 VectorType &      dst, \n                                 const VectorType &src) const; \n\n    void do_cell_integral_range( \n      const MatrixFree<dim, number> &              matrix_free, \n      VectorType &                                 dst, \n      const VectorType &                           src, \n      const std::pair<unsigned int, unsigned int> &range) const; \n\n    MatrixFree<dim, number> matrix_free; \n\n// \u4e3a\u4e86\u7528AMG\u9884\u5904\u7406\u7a0b\u5e8f\u89e3\u51b3\u6700\u7c97\u5c42\u6b21\u7684\u65b9\u7a0b\u7cfb\u7edf\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u6700\u7c97\u5c42\u6b21\u7684\u5b9e\u9645\u7cfb\u7edf\u77e9\u9635\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u63d0\u4f9b\u4e86\u4e00\u79cd\u673a\u5236\uff0c\u53ef\u4ee5\u9009\u62e9\u4ece\u65e0\u77e9\u9635\u516c\u5f0f\u4e2d\u8ba1\u7b97\u51fa\u4e00\u4e2a\u77e9\u9635\uff0c\u4e3a\u6b64\u6211\u4eec\u5f15\u5165\u4e86\u4e00\u4e2a\u4e13\u95e8\u7684SparseMatrix\u5bf9\u8c61\u3002\u5728\u9ed8\u8ba4\u60c5\u51b5\u4e0b\uff0c\u8fd9\u4e2a\u77e9\u9635\u4fdd\u6301\u4e3a\u7a7a\u3002\u4e00\u65e6`get_system_matrix()`\u88ab\u8c03\u7528\uff0c\u8fd9\u4e2a\u77e9\u9635\u5c31\u4f1a\u88ab\u586b\u5145\uff08\u61d2\u60f0\u5206\u914d\uff09\u3002\u7531\u4e8e\u8fd9\u662f\u4e00\u4e2a \"const \"\u51fd\u6570\uff0c\u6211\u4eec\u9700\u8981\u5728\u8fd9\u91cc\u4f7f\u7528 \"mutable \"\u5173\u952e\u5b57\u3002\u6211\u4eec\u8fd8\u9700\u8981\u4e00\u4e2a\u7ea6\u675f\u5bf9\u8c61\u6765\u6784\u5efa\u77e9\u9635\u3002\n\n    AffineConstraints<number>              constraints; \n    mutable TrilinosWrappers::SparseMatrix system_matrix; \n  }; \n\n// \u4e0b\u9762\u7684\u90e8\u5206\u5305\u542b\u4e86\u521d\u59cb\u5316\u548c\u91cd\u65b0\u521d\u59cb\u5316\u8be5\u7c7b\u7684\u51fd\u6570\u3002\u7279\u522b\u662f\uff0c\u8fd9\u4e9b\u51fd\u6570\u521d\u59cb\u5316\u4e86\u5185\u90e8\u7684MatrixFree\u5b9e\u4f8b\u3002\u4e3a\u4e86\u7b80\u5355\u8d77\u89c1\uff0c\u6211\u4eec\u8fd8\u8ba1\u7b97\u4e86\u7cfb\u7edf\u53f3\u4fa7\u7684\u5411\u91cf\u3002\n\n  template <int dim, typename number> \n  LaplaceOperator<dim, number>::LaplaceOperator( \n    const hp::MappingCollection<dim> &mapping, \n    const DoFHandler<dim> &           dof_handler, \n    const hp::QCollection<dim> &      quad, \n    const AffineConstraints<number> & constraints, \n    VectorType &                      system_rhs) \n  { \n    this->reinit(mapping, dof_handler, quad, constraints, system_rhs); \n  } \n\n  template <int dim, typename number> \n  void LaplaceOperator<dim, number>::reinit( \n    const hp::MappingCollection<dim> &mapping, \n    const DoFHandler<dim> &           dof_handler, \n    const hp::QCollection<dim> &      quad, \n    const AffineConstraints<number> & constraints, \n    VectorType &                      system_rhs) \n  { \n\n// \u6e05\u9664\u5185\u90e8\u6570\u636e\u7ed3\u6784\uff08\u5728\u64cd\u4f5c\u8005\u88ab\u91cd\u590d\u4f7f\u7528\u7684\u60c5\u51b5\u4e0b\uff09\u3002\n\n    this->system_matrix.clear(); \n\n// \u590d\u5236\u7ea6\u675f\u6761\u4ef6\uff0c\u56e0\u4e3a\u4ee5\u540e\u5728\u8ba1\u7b97\u7cfb\u7edf\u77e9\u9635\u65f6\u53ef\u80fd\u9700\u8981\u5b83\u4eec\u3002\n\n    this->constraints.copy_from(constraints); \n\n// \u8bbe\u7f6eMatrixFree\u3002\u5728\u6b63\u4ea4\u70b9\uff0c\u6211\u4eec\u53ea\u9700\u8981\u8bc4\u4f30\u89e3\u7684\u68af\u5ea6\uff0c\u5e76\u7528\u5f62\u72b6\u51fd\u6570\u7684\u68af\u5ea6\u8fdb\u884c\u6d4b\u8bd5\uff0c\u6240\u4ee5\u6211\u4eec\u53ea\u9700\u8981\u8bbe\u7f6e\u6807\u5fd7`update_gradients`\u3002\n\n    typename MatrixFree<dim, number>::AdditionalData data; \n    data.mapping_update_flags = update_gradients; \n\n    matrix_free.reinit(mapping, dof_handler, constraints, quad, data); \n\n// \u8ba1\u7b97\u53f3\u624b\u8fb9\u7684\u5411\u91cf\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u8bbe\u7f6e\u4e86\u7b2c\u4e8c\u4e2aMatrixFree\u5b9e\u4f8b\uff0c\u5b83\u4f7f\u7528\u4e00\u4e2a\u4fee\u6539\u8fc7\u7684AffineConstraints\uff0c\u4e0d\u5305\u542b\u7531\u4e8eDirichlet-\u8fb9\u754c\u6761\u4ef6\u7684\u7ea6\u675f\u3002\u8fd9\u4e2a\u4fee\u6539\u8fc7\u7684\u7b97\u5b50\u88ab\u5e94\u7528\u4e8e\u4e00\u4e2a\u53ea\u8bbe\u7f6e\u4e86\u8fea\u91cc\u5e0c\u7279\u503c\u7684\u5411\u91cf\u3002\u5176\u7ed3\u679c\u662f\u8d1f\u7684\u53f3\u624b\u8fb9\u5411\u91cf\u3002\n\n    { \n      AffineConstraints<number> constraints_without_dbc; \n\n      IndexSet locally_relevant_dofs; \n      DoFTools::extract_locally_relevant_dofs(dof_handler, \n                                              locally_relevant_dofs); \n      constraints_without_dbc.reinit(locally_relevant_dofs); \n\n      DoFTools::make_hanging_node_constraints(dof_handler, \n                                              constraints_without_dbc); \n      constraints_without_dbc.close(); \n\n      VectorType b, x; \n\n      this->initialize_dof_vector(system_rhs); \n\n      MatrixFree<dim, number> matrix_free; \n      matrix_free.reinit( \n        mapping, dof_handler, constraints_without_dbc, quad, data); \n\n      matrix_free.initialize_dof_vector(b); \n      matrix_free.initialize_dof_vector(x); \n\n      constraints.distribute(x); \n\n      matrix_free.cell_loop(&LaplaceOperator::do_cell_integral_range, \n                            this, \n                            b, \n                            x); \n\n      constraints.set_zero(b); \n\n      system_rhs -= b; \n    } \n  } \n\n// \u4ee5\u4e0b\u51fd\u6570\u662f\u591a\u7f51\u683c\u7b97\u6cd5\u9690\u542b\u9700\u8981\u7684\uff0c\u5305\u62ec\u5e73\u6ed1\u5668\u3002\n\n// \u7531\u4e8e\u6211\u4eec\u6ca1\u6709\u77e9\u9635\uff0c\u6240\u4ee5\u8981\u5411DoFHandler\u67e5\u8be2\u81ea\u7531\u5ea6\u7684\u6570\u91cf\u3002\n\n  template <int dim, typename number> \n  types::global_dof_index LaplaceOperator<dim, number>::m() const \n  { \n    return matrix_free.get_dof_handler().n_dofs(); \n  } \n\n// \u8bbf\u95ee\u77e9\u9635\u4e2d\u7684\u4e00\u4e2a\u7279\u5b9a\u5143\u7d20\u3002\u8fd9\u4e2a\u51fd\u6570\u65e2\u4e0d\u9700\u8981\u4e5f\u6ca1\u6709\u5b9e\u73b0\uff0c\u4f46\u662f\uff0c\u5728\u7f16\u8bd1\u7a0b\u5e8f\u65f6\u9700\u8981\u5b83\u3002\n\n  template <int dim, typename number> \n  number LaplaceOperator<dim, number>::el(unsigned int, unsigned int) const \n  { \n    Assert(false, ExcNotImplemented()); \n    return 0; \n  } \n\n// \u521d\u59cb\u5316\u7ed9\u5b9a\u7684\u5411\u91cf\u3002\u6211\u4eec\u53ea\u662f\u628a\u8fd9\u4e2a\u4efb\u52a1\u59d4\u6258\u7ed9\u540c\u540d\u7684MatrixFree\u51fd\u6570\u3002\n\n  template <int dim, typename number> \n  void \n  LaplaceOperator<dim, number>::initialize_dof_vector(VectorType &vec) const \n  { \n    matrix_free.initialize_dof_vector(vec); \n  } \n\n// \u5728MatrixFree\u7684\u5e2e\u52a9\u4e0b\uff0c\u901a\u8fc7\u5728\u6240\u6709\u5355\u5143\u4e2d\u5faa\u73af\u8fdb\u884c\u8fd0\u7b97\u8bc4\u4f30\uff0c\u5e76\u8bc4\u4f30\u5355\u5143\u79ef\u5206\u7684\u6548\u679c\uff08\u53c2\u89c1\u3002`do_cell_integral_local()`\u548c`do_cell_integral_global()`\uff09\u3002)\n\n  template <int dim, typename number> \n  void LaplaceOperator<dim, number>::vmult(VectorType &      dst, \n                                           const VectorType &src) const \n  { \n    this->matrix_free.cell_loop( \n      &LaplaceOperator::do_cell_integral_range, this, dst, src, true); \n  } \n\n// \u6267\u884c\u8f6c\u7f6e\u7684\u8fd0\u7b97\u7b26\u8bc4\u4f30\u3002\u7531\u4e8e\u6211\u4eec\u8003\u8651\u7684\u662f\u5bf9\u79f0\u7684 \"\u77e9\u9635\"\uff0c\u8fd9\u4e2a\u51fd\u6570\u53ef\u4ee5\u7b80\u5355\u5730\u5c06\u5176\u4efb\u52a1\u59d4\u6258\u7ed9vmult()\u3002\n\n  template <int dim, typename number> \n  void LaplaceOperator<dim, number>::Tvmult(VectorType &      dst, \n                                            const VectorType &src) const \n  { \n    this->vmult(dst, src); \n  } \n\n// \u7531\u4e8e\u6211\u4eec\u6ca1\u6709\u4e00\u4e2a\u7cfb\u7edf\u77e9\u9635\uff0c\u6211\u4eec\u4e0d\u80fd\u5faa\u73af\u8ba1\u7b97\u77e9\u9635\u7684\u5bf9\u89d2\u7ebf\u9879\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u901a\u8fc7\u5bf9\u5355\u4f4d\u57fa\u5411\u91cf\u8fdb\u884c\u4e00\u8fde\u4e32\u7684\u8fd0\u7b97\u7b26\u8bc4\u4f30\u6765\u8ba1\u7b97\u5bf9\u89d2\u7ebf\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u4f7f\u7528\u4e86MatrixFreeTools\u547d\u540d\u7a7a\u95f4\u4e2d\u7684\u4e00\u4e2a\u4f18\u5316\u51fd\u6570\u3002\u4e4b\u540e\u518d\u624b\u52a8\u8fdb\u884c\u53cd\u8f6c\u3002\n\n  template <int dim, typename number> \n  void LaplaceOperator<dim, number>::compute_inverse_diagonal( \n    VectorType &diagonal) const \n  { \n    MatrixFreeTools::compute_diagonal(matrix_free, \n                                      diagonal, \n                                      &LaplaceOperator::do_cell_integral_local, \n                                      this); \n\n    for (auto &i : diagonal) \n      i = (std::abs(i) > 1.0e-10) ? (1.0 / i) : 1.0; \n  } \n\n// \u5728\u65e0\u77e9\u9635\u7684\u60c5\u51b5\u4e0b\uff0c\u5728\u8fd9\u4e2a\u7c7b\u7684\u521d\u59cb\u5316\u8fc7\u7a0b\u4e2d\u6ca1\u6709\u8bbe\u7f6e\u7cfb\u7edf\u77e9\u9635\u3002\u56e0\u6b64\uff0c\u5982\u679c\u9700\u8981\u7684\u8bdd\uff0c\u5b83\u5fc5\u987b\u5728\u8fd9\u91cc\u88ab\u8ba1\u7b97\u51fa\u6765\u3002\u7531\u4e8e\u77e9\u9635\u5728\u672c\u6559\u7a0b\u4e2d\u53ea\u5bf9\u7ebf\u6027\u5143\u7d20\u8fdb\u884c\u8ba1\u7b97\uff08\u5728\u7c97\u7565\u7684\u7f51\u683c\u4e0a\uff09\uff0c\u8fd9\u4e00\u70b9\u662f\u53ef\u4ee5\u63a5\u53d7\u7684\u3002\u77e9\u9635\u7684\u6761\u76ee\u662f\u901a\u8fc7\u8fd0\u7b97\u7b26\u7684\u8bc4\u4f30\u5e8f\u5217\u5f97\u5230\u7684\u3002\u4e3a\u6b64\uff0c\u4f7f\u7528\u4e86\u4f18\u5316\u51fd\u6570 MatrixFreeTools::compute_matrix() \u3002\u77e9\u9635\u53ea\u6709\u5728\u5c1a\u672a\u8bbe\u7f6e\u7684\u60c5\u51b5\u4e0b\u624d\u4f1a\u88ab\u8ba1\u7b97\uff08\u61d2\u60f0\u5206\u914d\uff09\u3002\n\n  template <int dim, typename number> \n  const TrilinosWrappers::SparseMatrix & \n  LaplaceOperator<dim, number>::get_system_matrix() const \n  { \n    if (system_matrix.m() == 0 && system_matrix.n() == 0) \n      { \n        const auto &dof_handler = this->matrix_free.get_dof_handler(); \n\n        TrilinosWrappers::SparsityPattern dsp( \n          dof_handler.locally_owned_dofs(), \n          dof_handler.get_triangulation().get_communicator()); \n\n        DoFTools::make_sparsity_pattern(dof_handler, dsp, this->constraints); \n\n        dsp.compress(); \n        system_matrix.reinit(dsp); \n\n        MatrixFreeTools::compute_matrix( \n          matrix_free, \n          constraints, \n          system_matrix, \n          &LaplaceOperator::do_cell_integral_local, \n          this); \n      } \n\n    return this->system_matrix; \n  } \n\n// \u5bf9\u4e00\u4e2a\u5355\u5143\u683c\u6279\u5904\u7406\u8fdb\u884c\u5355\u5143\u683c\u79ef\u5206\uff0c\u4e0d\u9700\u8981\u6536\u96c6\u548c\u5206\u6563\u6570\u503c\u3002MatrixFreeTools\u51fd\u6570\u9700\u8981\u8fd9\u4e2a\u51fd\u6570\uff0c\u56e0\u4e3a\u8fd9\u4e9b\u51fd\u6570\u76f4\u63a5\u5bf9FEEvaluation\u7684\u7f13\u51b2\u533a\u8fdb\u884c\u64cd\u4f5c\u3002\n\n  template <int dim, typename number> \n  void LaplaceOperator<dim, number>::do_cell_integral_local( \n    FECellIntegrator &integrator) const \n  { \n    integrator.evaluate(EvaluationFlags::gradients); \n\n    for (unsigned int q = 0; q < integrator.n_q_points; ++q) \n      integrator.submit_gradient(integrator.get_gradient(q), q); \n\n    integrator.integrate(EvaluationFlags::gradients); \n  } \n\n// \u4e0e\u4e0a\u8ff0\u76f8\u540c\uff0c\u4f46\u53ef\u4ee5\u8bbf\u95ee\u5168\u5c40\u5411\u91cf\u3002\n\n  template <int dim, typename number> \n  void LaplaceOperator<dim, number>::do_cell_integral_global( \n    FECellIntegrator &integrator, \n    VectorType &      dst, \n    const VectorType &src) const \n  { \n    integrator.gather_evaluate(src, EvaluationFlags::gradients); \n\n    for (unsigned int q = 0; q < integrator.n_q_points; ++q) \n      integrator.submit_gradient(integrator.get_gradient(q), q); \n\n    integrator.integrate_scatter(EvaluationFlags::gradients, dst); \n  } \n\n// \u8fd9\u4e2a\u51fd\u6570\u5728\u4e00\u4e2a\u5355\u5143\u683c\u6279\u6b21\u8303\u56f4\u5185\u7684\u6240\u6709\u5355\u5143\u683c\u6279\u6b21\u4e0a\u5faa\u73af\uff0c\u5e76\u8c03\u7528\u4e0a\u8ff0\u51fd\u6570\u3002\n\n  template <int dim, typename number> \n  void LaplaceOperator<dim, number>::do_cell_integral_range( \n    const MatrixFree<dim, number> &              matrix_free, \n    VectorType &                                 dst, \n    const VectorType &                           src, \n    const std::pair<unsigned int, unsigned int> &range) const \n  { \n    FECellIntegrator integrator(matrix_free, range); \n\n    for (unsigned cell = range.first; cell < range.second; ++cell) \n      { \n        integrator.reinit(cell); \n\n        do_cell_integral_global(integrator, dst, src); \n      } \n  } \n\n//  @sect3{Solver and preconditioner}  \n// @sect4{Conjugate-gradient solver with multigrid preconditioner}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u7528\u4e00\u8fde\u4e32\u63d0\u4f9b\u7684\u591a\u7f51\u683c\u5bf9\u8c61\u6765\u89e3\u51b3\u65b9\u7a0b\u7ec4\u3002\u5b83\u7684\u76ee\u7684\u662f\u4e3a\u4e86\u5c3d\u53ef\u80fd\u7684\u901a\u7528\uff0c\u56e0\u6b64\u6709\u8bb8\u591a\u6a21\u677f\u53c2\u6570\u3002\n\n  template <typename VectorType, \n            int dim, \n            typename SystemMatrixType, \n            typename LevelMatrixType, \n            typename MGTransferType> \n  static void \n  mg_solve(SolverControl &            solver_control, \n           VectorType &               dst, \n           const VectorType &         src, \n           const MultigridParameters &mg_data, \n           const DoFHandler<dim> &    dof, \n           const SystemMatrixType &   fine_matrix, \n           const MGLevelObject<std::unique_ptr<LevelMatrixType>> &mg_matrices, \n           const MGTransferType &                                 mg_transfer) \n  { \n    AssertThrow(mg_data.coarse_solver.type == \"cg_with_amg\", \n                ExcNotImplemented()); \n    AssertThrow(mg_data.smoother.type == \"chebyshev\", ExcNotImplemented()); \n\n    const unsigned int min_level = mg_matrices.min_level(); \n    const unsigned int max_level = mg_matrices.max_level(); \n\n    using SmootherPreconditionerType = DiagonalMatrix<VectorType>; \n    using SmootherType               = PreconditionChebyshev<LevelMatrixType, \n                                               VectorType, \n                                               SmootherPreconditionerType>; \n    using PreconditionerType = PreconditionMG<dim, VectorType, MGTransferType>; \n\n// \u6211\u4eec\u5728\u8fd9\u91cc\u521d\u59cb\u5316\u7535\u5e73\u8fd0\u7b97\u7b26\u548c\u5207\u6bd4\u96ea\u592b\u5e73\u6ed1\u5668\u3002\n\n    mg::Matrix<VectorType> mg_matrix(mg_matrices); \n\n    MGLevelObject<typename SmootherType::AdditionalData> smoother_data( \n      min_level, max_level); \n\n    for (unsigned int level = min_level; level <= max_level; level++) \n      { \n        smoother_data[level].preconditioner = \n          std::make_shared<SmootherPreconditionerType>(); \n        mg_matrices[level]->compute_inverse_diagonal( \n          smoother_data[level].preconditioner->get_vector()); \n        smoother_data[level].smoothing_range = mg_data.smoother.smoothing_range; \n        smoother_data[level].degree          = mg_data.smoother.degree; \n        smoother_data[level].eig_cg_n_iterations = \n          mg_data.smoother.eig_cg_n_iterations; \n      } \n\n    MGSmootherPrecondition<LevelMatrixType, SmootherType, VectorType> \n      mg_smoother; \n    mg_smoother.initialize(mg_matrices, smoother_data); \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u521d\u59cb\u5316\u7c97\u7565\u7f51\u683c\u6c42\u89e3\u5668\u3002\u6211\u4eec\u4f7f\u7528\u5171\u8f6d\u68af\u5ea6\u6cd5\u548cAMG\u4f5c\u4e3a\u9884\u5904\u7406\u7a0b\u5e8f\u3002\n\n    ReductionControl coarse_grid_solver_control(mg_data.coarse_solver.maxiter, \n                                                mg_data.coarse_solver.abstol, \n                                                mg_data.coarse_solver.reltol, \n                                                false, \n                                                false); \n    SolverCG<VectorType> coarse_grid_solver(coarse_grid_solver_control); \n\n    std::unique_ptr<MGCoarseGridBase<VectorType>> mg_coarse; \n\n    TrilinosWrappers::PreconditionAMG                 precondition_amg; \n    TrilinosWrappers::PreconditionAMG::AdditionalData amg_data; \n    amg_data.smoother_sweeps = mg_data.coarse_solver.smoother_sweeps; \n    amg_data.n_cycles        = mg_data.coarse_solver.n_cycles; \n    amg_data.smoother_type   = mg_data.coarse_solver.smoother_type.c_str(); \n\n    precondition_amg.initialize(mg_matrices[min_level]->get_system_matrix(), \n                                amg_data); \n\n    mg_coarse = \n      std::make_unique<MGCoarseGridIterativeSolver<VectorType, \n                                                   SolverCG<VectorType>, \n                                                   LevelMatrixType, \n                                                   decltype(precondition_amg)>>( \n        coarse_grid_solver, *mg_matrices[min_level], precondition_amg); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u521b\u5efaMultigrid\u5bf9\u8c61\uff0c\u5c06\u5176\u8f6c\u6362\u4e3a\u9884\u5904\u7406\u7a0b\u5e8f\uff0c\u5e76\u5728\u5171\u8f6d\u68af\u5ea6\u6c42\u89e3\u5668\u4e2d\u4f7f\u7528\u5b83\u6765\u89e3\u51b3\u7ebf\u6027\u65b9\u7a0b\u7ec4\u3002\n\n    Multigrid<VectorType> mg( \n      mg_matrix, *mg_coarse, mg_transfer, mg_smoother, mg_smoother); \n\n    PreconditionerType preconditioner(dof, mg, mg_transfer); \n\n    SolverCG<VectorType>(solver_control) \n      .solve(fine_matrix, dst, src, preconditioner); \n  } \n\n//  @sect4{Hybrid polynomial/geometric-global-coarsening multigrid preconditioner}  \n\n// \u4e0a\u8ff0\u51fd\u6570\u5904\u7406\u7ed9\u5b9a\u7684\u591a\u7f51\u683c\u5bf9\u8c61\u5e8f\u5217\u7684\u5b9e\u9645\u89e3\u51b3\u65b9\u6848\u3002\u8fd9\u4e2a\u51fd\u6570\u521b\u5efa\u4e86\u5b9e\u9645\u7684\u591a\u91cd\u7f51\u683c\u5c42\u6b21\uff0c\u7279\u522b\u662f\u8fd0\u7b97\u7b26\uff0c\u4ee5\u53ca\u4f5c\u4e3aMGTransferGlobalCoarsening\u5bf9\u8c61\u7684\u8f6c\u79fb\u8fd0\u7b97\u7b26\u3002\n\n  template <typename VectorType, typename OperatorType, int dim> \n  void solve_with_gmg(SolverControl &                  solver_control, \n                      const OperatorType &             system_matrix, \n                      VectorType &                     dst, \n                      const VectorType &               src, \n                      const MultigridParameters &      mg_data, \n                      const hp::MappingCollection<dim> mapping_collection, \n                      const DoFHandler<dim> &          dof_handler, \n                      const hp::QCollection<dim> &     quadrature_collection) \n  { \n\n// \u4e3a\u6bcf\u4e2a\u591a\u7f51\u683c\u5c42\u6b21\u521b\u5efa\u4e00\u4e2aDoFHandler\u548c\u64cd\u4f5c\u7b26\uff0c\u4ee5\u53ca\uff0c\u521b\u5efa\u8f6c\u79fb\u64cd\u4f5c\u7b26\u3002\u4e3a\u4e86\u80fd\u591f\u8bbe\u7f6e\u8fd0\u7b97\u7b26\uff0c\u6211\u4eec\u9700\u8981\u4e00\u7ec4DoFHandler\uff0c\u901a\u8fc7p\u6216h\u7684\u5168\u5c40\u7c97\u5316\u6765\u521b\u5efa\u3002\n\n// \u5982\u679c\u6ca1\u6709\u8981\u6c42h-transfer\uff0c\u6211\u4eec\u4e3a`emplace_back()`\u51fd\u6570\u63d0\u4f9b\u4e00\u4e2a\u7a7a\u7684\u5220\u9664\u5668\uff0c\u56e0\u4e3a\u6211\u4eec\u7684DoFHandler\u7684Triangulation\u662f\u4e00\u4e2a\u5916\u90e8\u5b57\u6bb5\uff0c\u5176\u6790\u6784\u5668\u5728\u5176\u4ed6\u5730\u65b9\u88ab\u8c03\u7528\u3002\n\n    MGLevelObject<DoFHandler<dim>>                     dof_handlers; \n    MGLevelObject<std::unique_ptr<OperatorType>>       operators; \n    MGLevelObject<MGTwoLevelTransfer<dim, VectorType>> transfers; \n\n    std::vector<std::shared_ptr<const Triangulation<dim>>> \n      coarse_grid_triangulations; \n    if (mg_data.transfer.perform_h_transfer) \n      coarse_grid_triangulations = \n        MGTransferGlobalCoarseningTools::create_geometric_coarsening_sequence( \n          dof_handler.get_triangulation()); \n    else \n      coarse_grid_triangulations.emplace_back( \n        const_cast<Triangulation<dim> *>(&(dof_handler.get_triangulation())), \n        [](auto &) {}); \n\n// \u786e\u5b9a\u591a\u6805\u683c\u64cd\u4f5c\u7684\u603b\u5c42\u6570\uff0c\u5e76\u4e3a\u6240\u6709\u5c42\u6570\u5206\u914d\u8db3\u591f\u7684\u5185\u5b58\u3002\n\n    const unsigned int n_h_levels = coarse_grid_triangulations.size() - 1; \n\n    const auto get_max_active_fe_degree = [&](const auto &dof_handler) { \n      unsigned int max = 0; \n\n      for (auto &cell : dof_handler.active_cell_iterators()) \n        if (cell->is_locally_owned()) \n          max = \n            std::max(max, dof_handler.get_fe(cell->active_fe_index()).degree); \n\n      return Utilities::MPI::max(max, MPI_COMM_WORLD); \n    }; \n\n    const unsigned int n_p_levels = \n      MGTransferGlobalCoarseningTools::create_polynomial_coarsening_sequence( \n        get_max_active_fe_degree(dof_handler), mg_data.transfer.p_sequence) \n        .size(); \n\n    std::map<unsigned int, unsigned int> fe_index_for_degree; \n    for (unsigned int i = 0; i < dof_handler.get_fe_collection().size(); ++i) \n      { \n        const unsigned int degree = dof_handler.get_fe(i).degree; \n        Assert(fe_index_for_degree.find(degree) == fe_index_for_degree.end(), \n               ExcMessage(\"FECollection does not contain unique degrees.\")); \n        fe_index_for_degree[degree] = i; \n      } \n\n    unsigned int minlevel   = 0; \n    unsigned int minlevel_p = n_h_levels; \n    unsigned int maxlevel   = n_h_levels + n_p_levels - 1; \n\n    dof_handlers.resize(minlevel, maxlevel); \n    operators.resize(minlevel, maxlevel); \n    transfers.resize(minlevel, maxlevel); \n\n// \u4ece\u6700\u5c0f\uff08\u6700\u7c97\uff09\u5230\u6700\u5927\uff08\u6700\u7ec6\uff09\u7ea7\u522b\u7684\u5faa\u73af\uff0c\u5e76\u76f8\u5e94\u5730\u8bbe\u7f6eDoFHandler\u3002\u6211\u4eec\u4eceh\u5c42\u5f00\u59cb\uff0c\u5728\u8fd9\u91cc\u6211\u4eec\u5206\u5e03\u5728\u8d8a\u6765\u8d8a\u7ec6\u7684\u7f51\u683c\u4e0a\u7684\u7ebf\u6027\u5143\u7d20\u3002\n\n    for (unsigned int l = 0; l < n_h_levels; ++l) \n      { \n        dof_handlers[l].reinit(*coarse_grid_triangulations[l]); \n        dof_handlers[l].distribute_dofs(dof_handler.get_fe_collection()); \n      } \n\n// \u5728\u6211\u4eec\u8fbe\u5230\u6700\u7ec6\u7684\u7f51\u683c\u540e\uff0c\u6211\u4eec\u5c06\u8c03\u6574\u6bcf\u4e00\u5c42\u7684\u591a\u9879\u5f0f\u5ea6\u6570\u3002\u6211\u4eec\u53cd\u5411\u8fed\u4ee3\u6211\u4eec\u7684\u6570\u636e\u7ed3\u6784\uff0c\u4ece\u5305\u542b\u6240\u6709\u6d3b\u52a8FE\u6307\u6570\u4fe1\u606f\u7684\u6700\u7ec6\u7f51\u683c\u5f00\u59cb\u3002\u7136\u540e\u6211\u4eec\u9010\u7ea7\u964d\u4f4e\u6bcf\u4e2a\u5355\u5143\u7684\u591a\u9879\u5f0f\u5ea6\u6570\u3002\n\n    for (unsigned int i = 0, l = maxlevel; i < n_p_levels; ++i, --l) \n      { \n        dof_handlers[l].reinit(dof_handler.get_triangulation()); \n\n        if (l == maxlevel) // finest level \n          { \n            auto &dof_handler_mg = dof_handlers[l]; \n\n            auto cell_other = dof_handler.begin_active(); \n            for (auto &cell : dof_handler_mg.active_cell_iterators()) \n              { \n                if (cell->is_locally_owned()) \n                  cell->set_active_fe_index(cell_other->active_fe_index()); \n                cell_other++; \n              } \n          } \n        else // coarse level \n          { \n            auto &dof_handler_fine   = dof_handlers[l + 1]; \n            auto &dof_handler_coarse = dof_handlers[l + 0]; \n\n            auto cell_other = dof_handler_fine.begin_active(); \n            for (auto &cell : dof_handler_coarse.active_cell_iterators()) \n              { \n                if (cell->is_locally_owned()) \n                  { \n                    const unsigned int next_degree = \n                      MGTransferGlobalCoarseningTools:: \n                        create_next_polynomial_coarsening_degree( \n                          cell_other->get_fe().degree, \n                          mg_data.transfer.p_sequence); \n                    Assert(fe_index_for_degree.find(next_degree) != \n                             fe_index_for_degree.end(), \n                           ExcMessage(\"Next polynomial degree in sequence \" \n                                      \"does not exist in FECollection.\")); \n\n                    cell->set_active_fe_index(fe_index_for_degree[next_degree]); \n                  } \n                cell_other++; \n              } \n          } \n\n        dof_handlers[l].distribute_dofs(dof_handler.get_fe_collection()); \n      } \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5c06\u5728\u6bcf\u4e2a\u591a\u91cd\u7f51\u683c\u5c42\u9762\u4e0a\u521b\u5efa\u6240\u6709\u989d\u5916\u9700\u8981\u7684\u6570\u636e\u7ed3\u6784\u3002\u8fd9\u6d89\u53ca\u5230\u786e\u5b9a\u5177\u6709\u540c\u8d28Dirichlet\u8fb9\u754c\u6761\u4ef6\u7684\u7ea6\u675f\uff0c\u5e76\u50cf\u5728\u6d3b\u52a8\u5c42\u4e0a\u4e00\u6837\u5efa\u7acb\u8fd0\u7b97\u5668\u3002\n\n    MGLevelObject<AffineConstraints<typename VectorType::value_type>> \n      constraints(minlevel, maxlevel); \n\n    for (unsigned int level = minlevel; level <= maxlevel; ++level) \n      { \n        const auto &dof_handler = dof_handlers[level]; \n        auto &      constraint  = constraints[level]; \n\n        IndexSet locally_relevant_dofs; \n        DoFTools::extract_locally_relevant_dofs(dof_handler, \n                                                locally_relevant_dofs); \n        constraint.reinit(locally_relevant_dofs); \n\n        DoFTools::make_hanging_node_constraints(dof_handler, constraint); \n        VectorTools::interpolate_boundary_values(mapping_collection, \n                                                 dof_handler, \n                                                 0, \n                                                 Functions::ZeroFunction<dim>(), \n                                                 constraint); \n        constraint.close(); \n\n        VectorType dummy; \n\n        operators[level] = std::make_unique<OperatorType>(mapping_collection, \n                                                          dof_handler, \n                                                          quadrature_collection, \n                                                          constraint, \n                                                          dummy); \n      } \n\n//\u6839\u636e\u591a\u7f51\u683c\u6c42\u89e3\u5668\u7c7b\u7684\u9700\u8981\uff0c\u5728\u5355\u4e2a\u7b97\u5b50\u4e2d\u8bbe\u7f6e\u7f51\u683c\u95f4\u7b97\u5b50\u548c\u6536\u96c6\u8f6c\u79fb\u7b97\u5b50\u3002\n\n    for (unsigned int level = minlevel; level < minlevel_p; ++level) \n      transfers[level + 1].reinit_geometric_transfer(dof_handlers[level + 1], \n                                                     dof_handlers[level], \n                                                     constraints[level + 1], \n                                                     constraints[level]); \n\n    for (unsigned int level = minlevel_p; level < maxlevel; ++level) \n      transfers[level + 1].reinit_polynomial_transfer(dof_handlers[level + 1], \n                                                      dof_handlers[level], \n                                                      constraints[level + 1], \n                                                      constraints[level]); \n\n    MGTransferGlobalCoarsening<dim, VectorType> transfer( \n      transfers, [&](const auto l, auto &vec) { \n        operators[l]->initialize_dof_vector(vec); \n      }); \n\n// \u6700\u540e\uff0c\u7ee7\u7eed\u7528\u591a\u7f51\u683c\u6cd5\u89e3\u51b3\u95ee\u9898\u3002\n\n    mg_solve(solver_control, \n             dst, \n             src, \n             mg_data, \n             dof_handler, \n             system_matrix, \n             operators, \n             transfer); \n  } \n\n//  @sect3{The <code>LaplaceProblem</code> class template}  \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u5c06\u6700\u540e\u58f0\u660e\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u7c7b\uff0c\u5b83\u5728\u968f\u540e\u7684\u7cbe\u70bc\u51fd\u6570\u7a7a\u95f4\u4e0a\u6c42\u89e3\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\u3002\u5b83\u7684\u7ed3\u6784\u770b\u8d77\u6765\u5f88\u719f\u6089\uff0c\u56e0\u4e3a\u5b83\u4e0e  step-27  \u548c  step-40  \u7684\u4e3b\u7c7b\u7c7b\u4f3c\u3002\u57fa\u672c\u4e0a\u53ea\u589e\u52a0\u4e86\u4e24\u4e2a\u3002\n\n// - \u6301\u6709\u7cfb\u7edf\u77e9\u9635\u7684SparseMatrix\u5bf9\u8c61\u5df2\u7ecf\u88abMatrixFree\u516c\u5f0f\u4e2d\u7684LaplaceOperator\u7c7b\u5bf9\u8c61\u6240\u53d6\u4ee3\u3002\n\n// - \u52a0\u5165\u4e86\u4e00\u4e2a parallel::CellWeights, \u7684\u5bf9\u8c61\uff0c\u5b83\u5c06\u5e2e\u52a9\u6211\u4eec\u5b9e\u73b0\u8d1f\u8f7d\u5e73\u8861\u3002\n\n  template <int dim> \n  class LaplaceProblem \n  { \n  public: \n    LaplaceProblem(const Parameters &parameters); \n\n    void run(); \n\n  private: \n    void initialize_grid(); \n    void setup_system(); \n    void print_diagnostics(); \n    void solve_system(); \n    void compute_indicators(); \n    void adapt_resolution(); \n    void output_results(const unsigned int cycle); \n\n    MPI_Comm mpi_communicator; \n\n    const Parameters prm; \n\n    parallel::distributed::Triangulation<dim> triangulation; \n    DoFHandler<dim>                           dof_handler; \n\n    hp::MappingCollection<dim> mapping_collection; \n    hp::FECollection<dim>      fe_collection; \n    hp::QCollection<dim>       quadrature_collection; \n    hp::QCollection<dim - 1>   face_quadrature_collection; \n\n    IndexSet locally_owned_dofs; \n    IndexSet locally_relevant_dofs; \n\n    AffineConstraints<double> constraints; \n\n    LaplaceOperator<dim, double>               laplace_operator; \n    LinearAlgebra::distributed::Vector<double> locally_relevant_solution; \n    LinearAlgebra::distributed::Vector<double> system_rhs; \n\n    std::unique_ptr<FESeries::Legendre<dim>>    legendre; \n    std::unique_ptr<parallel::CellWeights<dim>> cell_weights; \n\n    Vector<float> estimated_error_per_cell; \n    Vector<float> hp_decision_indicators; \n\n    ConditionalOStream pcout; \n    TimerOutput        computing_timer; \n  }; \n\n//  @sect3{The <code>LaplaceProblem</code> class implementation}  \n// @sect4{Constructor}  \n\n// \u6784\u9020\u51fd\u6570\u4ee5\u4e00\u4e2a\u521d\u59cb\u5316\u5668\u5217\u8868\u5f00\u59cb\uff0c\u8be5\u5217\u8868\u770b\u8d77\u6765\u4e0e  step-40  \u7684\u5217\u8868\u76f8\u4f3c\u3002\u6211\u4eec\u518d\u6b21\u51c6\u5907\u597dConditionalOStream\u5bf9\u8c61\uff0c\u53ea\u5141\u8bb8\u7b2c\u4e00\u4e2a\u8fdb\u7a0b\u5728\u63a7\u5236\u53f0\u8f93\u51fa\u4efb\u4f55\u4e1c\u897f\uff0c\u5e76\u6b63\u786e\u521d\u59cb\u5316\u8ba1\u7b97\u8ba1\u65f6\u5668\u3002\n\n  template <int dim> \n  LaplaceProblem<dim>::LaplaceProblem(const Parameters &parameters) \n    : mpi_communicator(MPI_COMM_WORLD) \n    , prm(parameters) \n    , triangulation(mpi_communicator) \n    , dof_handler(triangulation) \n    , pcout(std::cout, \n            (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)) \n    , computing_timer(mpi_communicator, \n                      pcout, \n                      TimerOutput::summary, \n                      TimerOutput::wall_times) \n  { \n    Assert(prm.min_h_level <= prm.max_h_level, \n           ExcMessage( \n             \"Triangulation level limits have been incorrectly set up.\")); \n    Assert(prm.min_p_degree <= prm.max_p_degree, \n           ExcMessage(\"FECollection degrees have been incorrectly set up.\")); \n\n// \u6211\u4eec\u9700\u8981\u5728\u6784\u9020\u51fd\u6570\u7684\u5b9e\u9645\u4e3b\u4f53\u4e2d\u4e3ahp-functionality\u51c6\u5907\u6570\u636e\u7ed3\u6784\uff0c\u5e76\u5728\u53c2\u6570\u7ed3\u6784\u7684\u6307\u5b9a\u8303\u56f4\u5185\u4e3a\u6bcf\u4e2a\u5ea6\u6570\u521b\u5efa\u76f8\u5e94\u7684\u5bf9\u8c61\u3002\u7531\u4e8e\u6211\u4eec\u53ea\u5904\u7406\u975e\u626d\u66f2\u7684\u77e9\u5f62\u5355\u5143\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u4e00\u4e2a\u7ebf\u6027\u6620\u5c04\u5bf9\u8c61\u5c31\u8db3\u591f\u4e86\u3002\n\n// \u5728\u53c2\u6570\u7ed3\u6784\u4e2d\uff0c\u6211\u4eec\u4e3a\u51fd\u6570\u7a7a\u95f4\u4ee5\u5408\u7406\u7684\u5206\u8fa8\u7387\u8fd0\u884c\u7684\u5c42\u7ea7\u63d0\u4f9b\u8303\u56f4\u3002\u591a\u7f51\u683c\u7b97\u6cd5\u9700\u8981\u5728\u6700\u7c97\u7684\u5c42\u6b21\u4e0a\u4f7f\u7528\u7ebf\u6027\u5143\u7d20\u3002\u6240\u4ee5\u6211\u4eec\u4ece\u6700\u4f4e\u7684\u591a\u9879\u5f0f\u5ea6\u6570\u5f00\u59cb\uff0c\u7528\u8fde\u7eed\u7684\u9ad8\u5ea6\u6570\u586b\u5145\u96c6\u5408\uff0c\u76f4\u5230\u8fbe\u5230\u7528\u6237\u6307\u5b9a\u7684\u6700\u5927\u503c\u3002\n\n    mapping_collection.push_back(MappingQ1<dim>()); \n\n    for (unsigned int degree = 1; degree <= prm.max_p_degree; ++degree) \n      { \n        fe_collection.push_back(FE_Q<dim>(degree)); \n        quadrature_collection.push_back(QGauss<dim>(degree + 1)); \n        face_quadrature_collection.push_back(QGauss<dim - 1>(degree + 1)); \n      } \n\n// \u7531\u4e8e\u6211\u4eec\u7684FECollection\u5305\u542b\u7684\u6709\u9650\u5143\u6bd4\u6211\u4eec\u60f3\u7528\u4e8e\u6c42\u89e3\u7684\u6709\u9650\u5143\u8fd1\u4f3c\u503c\u8981\u591a\uff0c\u6211\u4eec\u60f3\u9650\u5236\u6d3b\u52a8FE\u6307\u6570\u53ef\u4ee5\u64cd\u4f5c\u7684\u8303\u56f4\u3002\u4e3a\u6b64\uff0cFECollection\u7c7b\u5141\u8bb8\u6ce8\u518c\u4e00\u4e2a\u5c42\u6b21\u7ed3\u6784\uff0c\u5728p-\u7cbe\u7b80\u548cp-\u7c97\u5316\u7684\u60c5\u51b5\u4e0b\uff0c\u5206\u522b\u51b3\u5b9a\u540e\u7eed\u7684\u548c\u524d\u9762\u7684\u6709\u9650\u5143\u3002 hp::Refinement \u547d\u540d\u7a7a\u95f4\u4e2d\u7684\u6240\u6709\u51fd\u6570\u90fd\u4f1a\u53c2\u8003\u8fd9\u4e2a\u5c42\u6b21\u7ed3\u6784\u6765\u786e\u5b9a\u672a\u6765\u7684FE\u6307\u6570\u3002\u6211\u4eec\u5c06\u6ce8\u518c\u8fd9\u6837\u4e00\u4e2a\u5c42\u6b21\u7ed3\u6784\uff0c\u5b83\u53ea\u5bf9\u5efa\u8bae\u8303\u56f4\u5185\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u7684\u6709\u9650\u5143\u8d77\u4f5c\u7528  <code>[min_p_degree, max_p_degree]</code>  \u3002\n\n    const unsigned int min_fe_index = prm.min_p_degree - 1; \n    fe_collection.set_hierarchy( \n\n   /*\u4e0b\u4e00\u4e2a_index=  */ \n      [](const typename hp::FECollection<dim> &fe_collection, \n         const unsigned int                    fe_index) -> unsigned int { \n        return ((fe_index + 1) < fe_collection.size()) ? fe_index + 1 : \n                                                         fe_index; \n      }, \n    /*\u4e0a\u4e00\u9875_index=  */ \n      [min_fe_index](const typename hp::FECollection<dim> &, \n                     const unsigned int fe_index) -> unsigned int { \n        Assert(fe_index >= min_fe_index, \n               ExcMessage(\"Finite element is not part of hierarchy!\")); \n        return (fe_index > min_fe_index) ? fe_index - 1 : fe_index; \n      }); \n\n// \u6211\u4eec\u4ee5\u9ed8\u8ba4\u914d\u7f6e\u521d\u59cb\u5316 FESeries::Legendre \u5bf9\u8c61\uff0c\u4ee5\u4fbf\u8fdb\u884c\u5e73\u6ed1\u5ea6\u4f30\u8ba1\u3002\n\n    legendre = std::make_unique<FESeries::Legendre<dim>>( \n      SmoothnessEstimator::Legendre::default_fe_series(fe_collection)); \n\n// \u63a5\u4e0b\u6765\u7684\u90e8\u5206\u4f1a\u5f88\u68d8\u624b\u3002\u5728\u6267\u884c\u7ec6\u5316\u7684\u8fc7\u7a0b\u4e2d\uff0c\u6709\u51e0\u4e2ahp-\u7b97\u6cd5\u9700\u8981\u5e72\u6270\u4e09\u89d2\u5f62\u5bf9\u8c61\u4e0a\u7684\u5b9e\u9645\u7ec6\u5316\u8fc7\u7a0b\u3002\u6211\u4eec\u901a\u8fc7\u5c06\u51e0\u4e2a\u51fd\u6570\u8fde\u63a5\u5230 Triangulation::Signals: \u4fe1\u53f7\uff0c\u5728\u5b9e\u9645\u7ec6\u5316\u8fc7\u7a0b\u4e2d\u7684\u4e0d\u540c\u9636\u6bb5\u88ab\u8c03\u7528\uff0c\u5e76\u89e6\u53d1\u6240\u6709\u8fde\u63a5\u7684\u51fd\u6570\u6765\u505a\u5230\u8fd9\u4e00\u70b9\u3002\u6211\u4eec\u9700\u8981\u8fd9\u4e2a\u529f\u80fd\u6765\u5b9e\u73b0\u8d1f\u8f7d\u5e73\u8861\u548c\u9650\u5236\u76f8\u90bb\u5355\u5143\u7684\u591a\u9879\u5f0f\u5ea6\u6570\u3002\n\n// \u5bf9\u4e8e\u524d\u8005\uff0c\u6211\u4eec\u5e0c\u671b\u7ed9\u6bcf\u4e2a\u5355\u5143\u5206\u914d\u4e00\u4e2a\u6743\u91cd\uff0c\u8fd9\u4e2a\u6743\u91cd\u4e0e\u5b83\u672a\u6765\u7684\u6709\u9650\u5143\u7684\u81ea\u7531\u5ea6\u6570\u6210\u6b63\u6bd4\u3002\u8be5\u5e93\u63d0\u4f9b\u4e86\u4e00\u4e2a\u7c7b parallel::CellWeights \uff0c\u5141\u8bb8\u5728\u7ec6\u5316\u8fc7\u7a0b\u4e2d\u7684\u6b63\u786e\u4f4d\u7f6e\u8f7b\u677e\u5730\u9644\u52a0\u5355\u4e2a\u6743\u91cd\uff0c\u5373\u5728\u6240\u6709\u7ec6\u5316\u548c\u7c97\u5316\u6807\u5fd7\u88ab\u6b63\u786e\u8bbe\u7f6e\u4e3ahp-adaptation\u4e4b\u540e\uff0c\u4ee5\u53ca\u5728\u5373\u5c06\u53d1\u751f\u7684\u8d1f\u8f7d\u5e73\u8861\u7684\u91cd\u65b0\u5212\u5206\u4e4b\u524d\u3002\u53ef\u4ee5\u6ce8\u518c\u4e00\u4e9b\u51fd\u6570\uff0c\u8fd9\u4e9b\u51fd\u6570\u5c06\u4ee5  $a (n_\\text{dofs})^b$  \u63d0\u4f9b\u7684\u4e00\u5bf9\u53c2\u6570\u7684\u5f62\u5f0f\u9644\u52a0\u6743\u91cd  $(a,b)$  \u3002\u6211\u4eec\u5728\u4e0b\u6587\u4e2d\u6ce8\u518c\u4e86\u8fd9\u6837\u4e00\u4e2a\u51fd\u6570\u3002\u6bcf\u4e2a\u5355\u5143\u5728\u521b\u5efa\u65f6\u5c06\u88ab\u8d4b\u4e88\u4e00\u4e2a\u6052\u5b9a\u7684\u6743\u91cd\uff0c\u8fd9\u4e2a\u503c\u662f1000\uff08\u89c1  Triangulation::Signals::cell_weight).  \uff09\u3002\n\n// \u4e3a\u4e86\u5b9e\u73b0\u8d1f\u8f7d\u5e73\u8861\uff0c\u50cf\u6211\u4eec\u4f7f\u7528\u7684\u9ad8\u6548\u6c42\u89e3\u5668\u5e94\u8be5\u4e0e\u62e5\u6709\u7684\u81ea\u7531\u5ea6\u6570\u91cf\u6210\u7ebf\u6027\u6bd4\u4f8b\u3002\u6b64\u5916\uff0c\u4e3a\u4e86\u589e\u52a0\u6211\u4eec\u60f3\u8981\u9644\u52a0\u7684\u6743\u91cd\u7684\u5f71\u54cd\uff0c\u786e\u4fdd\u5355\u4e2a\u6743\u91cd\u5c06\u8d85\u8fc7\u8fd9\u4e2a\u57fa\u7840\u6743\u91cd\u7684\u6570\u91cf\u7ea7\u3002\u6211\u4eec\u76f8\u5e94\u5730\u8bbe\u7f6e\u5355\u5143\u52a0\u6743\u7684\u53c2\u6570\u3002\u5927\u7684\u52a0\u6743\u7cfb\u6570\u4e3a $10^6$ \uff0c\u6307\u6570\u4e3a $1$  \u3002\n\n    cell_weights = std::make_unique<parallel::CellWeights<dim>>( \n      dof_handler, \n      parallel::CellWeights<dim>::ndofs_weighting( \n        {prm.weighting_factor, prm.weighting_exponent})); \n\n// \u5728h-adaptive\u5e94\u7528\u4e2d\uff0c\u6211\u4eec\u901a\u8fc7\u9650\u5236\u76f8\u90bb\u5355\u5143\u7684\u7ec6\u5316\u6c34\u5e73\u7684\u5dee\u5f02\u4e3a1\u6765\u786e\u4fdd2:1\u7684\u7f51\u683c\u5e73\u8861\u3002\u901a\u8fc7\u4e0b\u9762\u4ee3\u7801\u7247\u6bb5\u4e2d\u7684\u7b2c\u4e8c\u4e2a\u8c03\u7528\uff0c\u6211\u4eec\u5c06\u786e\u4fdd\u76f8\u90bb\u5355\u5143\u7684p\u7ea7\u6570\u4e5f\u662f\u5982\u6b64\uff1a\u672a\u6765\u6709\u9650\u5143\u7684\u7ea7\u6570\u4e0d\u5141\u8bb8\u76f8\u5dee\u8d85\u8fc7\u6307\u5b9a\u7684\u5dee\u503c\u3002\u51fd\u6570 hp::Refinement::limit_p_level_difference \u53ef\u4ee5\u5904\u7406\u8fd9\u4e2a\u95ee\u9898\uff0c\u4f46\u9700\u8981\u4e0e\u5e76\u884c\u73af\u5883\u4e2d\u7684\u4e00\u4e2a\u975e\u5e38\u7279\u6b8a\u7684\u4fe1\u53f7\u76f8\u8fde\u3002\u95ee\u9898\u662f\uff0c\u6211\u4eec\u9700\u8981\u77e5\u9053\u7f51\u683c\u7684\u5b9e\u9645\u7ec6\u5316\u60c5\u51b5\uff0c\u4ee5\u4fbf\u76f8\u5e94\u5730\u8bbe\u7f6e\u672a\u6765\u7684FE\u6307\u6570\u3002\u7531\u4e8e\u6211\u4eec\u8981\u6c42p4est\u795e\u8c15\u8fdb\u884c\u7ec6\u5316\uff0c\u6211\u4eec\u9700\u8981\u786e\u4fddTriangulation\u5df2\u7ecf\u5148\u7528\u795e\u8c15\u7684\u9002\u5e94\u6807\u5fd7\u8fdb\u884c\u4e86\u66f4\u65b0\u3002 parallel::distributed::TemporarilyMatchRefineFlags \u7684\u5b9e\u4f8b\u5316\u5728\u5176\u751f\u547d\u671f\u5185\u6b63\u662f\u5982\u6b64\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5c06\u5728\u9650\u5236p\u7ea7\u5dee\u4e4b\u524d\u521b\u5efa\u8fd9\u4e2a\u7c7b\u7684\u5bf9\u8c61\uff0c\u5e76\u5c06\u76f8\u5e94\u7684lambda\u51fd\u6570\u8fde\u63a5\u5230\u4fe1\u53f7 Triangulation::Signals::post_p4est_refinement, \u4e0a\uff0c\u8be5\u4fe1\u53f7\u5c06\u5728\u795e\u8c15\u88ab\u5b8c\u5584\u4e4b\u540e\uff0c\u4f46\u5728\u4e09\u89d2\u6cd5\u88ab\u5b8c\u5584\u4e4b\u524d\u88ab\u89e6\u53d1\u3002\u6b64\u5916\uff0c\u6211\u4eec\u6307\u5b9a\u8fd9\u4e2a\u51fd\u6570\u5c06\u88ab\u8fde\u63a5\u5230\u4fe1\u53f7\u7684\u524d\u9762\uff0c\u4ee5\u786e\u4fdd\u4fee\u6539\u5728\u8fde\u63a5\u5230\u540c\u4e00\u4fe1\u53f7\u7684\u4efb\u4f55\u5176\u4ed6\u51fd\u6570\u4e4b\u524d\u8fdb\u884c\u3002\n\n    triangulation.signals.post_p4est_refinement.connect( \n      [&, min_fe_index]() { \n        const parallel::distributed::TemporarilyMatchRefineFlags<dim> \n          refine_modifier(triangulation); \n        hp::Refinement::limit_p_level_difference(dof_handler, \n                                                 prm.max_p_level_difference, \n                                                 /*\u5305\u542b=  */ min_fe_index);\n      }, \n      boost::signals2::at_front); \n  } \n\n//  @sect4{LaplaceProblem::initialize_grid}  \n\n// \u5bf9\u4e8eL\u578b\u57df\uff0c\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528 GridGenerator::hyper_L() \u8fd9\u4e2a\u51fd\u6570\uff0c\u5982 step-50 \u4e2d\u6240\u6f14\u793a\u7684\u3002\u7136\u800c\u5728\u4e8c\u7ef4\u7684\u60c5\u51b5\u4e0b\uff0c\u8be5\u51fd\u6570\u53ea\u53bb\u9664\u7b2c\u4e00\u8c61\u9650\uff0c\u800c\u5728\u6211\u4eec\u7684\u65b9\u6848\u4e2d\u6211\u4eec\u9700\u8981\u53bb\u9664\u7b2c\u56db\u8c61\u9650\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u4e00\u4e2a\u4e0d\u540c\u7684\u51fd\u6570 GridGenerator::subdivided_hyper_L() \uff0c\u5b83\u7ed9\u6211\u4eec\u66f4\u591a\u7684\u9009\u62e9\u6765\u521b\u5efa\u7f51\u683c\u3002\u6b64\u5916\uff0c\u6211\u4eec\u5728\u5236\u5b9a\u8be5\u51fd\u6570\u65f6\uff0c\u4e5f\u4f1a\u751f\u6210\u4e00\u4e2a\u4e09\u7ef4\u7f51\u683c\uff1a\u4e8c\u7ef4L\u578b\u57df\u57fa\u672c\u4e0a\u4f1a\u5728\u6b63Z\u65b9\u5411\u4e0a\u62c9\u957f1\u3002\n\n// \u6211\u4eec\u9996\u5148\u5047\u88c5\u5efa\u7acb\u4e00\u4e2a  GridGenerator::subdivided_hyper_rectangle().  \u6211\u4eec\u9700\u8981\u63d0\u4f9b\u7684\u53c2\u6570\u662f\u5de6\u4e0b\u89d2\u548c\u53f3\u4e0a\u89d2\u7684\u70b9\u5bf9\u8c61\uff0c\u4ee5\u53ca\u57fa\u672c\u7f51\u683c\u5728\u6bcf\u4e2a\u65b9\u5411\u7684\u91cd\u590d\u6b21\u6570\u3002\u6211\u4eec\u4e3a\u524d\u4e24\u4e2a\u7ef4\u5ea6\u63d0\u4f9b\u8fd9\u4e9b\u53c2\u6570\uff0c\u5bf9\u66f4\u9ad8\u7684\u7b2c\u4e09\u7ef4\u5ea6\u5355\u72ec\u5904\u7406\u3002\n\n// \u4e3a\u4e86\u521b\u5efa\u4e00\u4e2aL\u578b\u57df\uff0c\u6211\u4eec\u9700\u8981\u53bb\u9664\u591a\u4f59\u7684\u5355\u5143\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u76f8\u5e94\u5730\u6307\u5b9a <code>cells_to_remove</code> \u3002\u6211\u4eec\u5e0c\u671b\u4ece\u8d1f\u65b9\u5411\u7684\u6bcf\u4e00\u4e2a\u5355\u5143\u683c\u4e2d\u79fb\u9664\u4e00\u4e2a\u5355\u5143\u683c\uff0c\u4f46\u4ece\u6b63\u7684x\u65b9\u5411\u79fb\u9664\u4e00\u4e2a\u3002\n\n// \u6700\u540e\uff0c\u6211\u4eec\u63d0\u4f9b\u4e0e\u6240\u63d0\u4f9b\u7684\u6700\u5c0f\u7f51\u683c\u7ec6\u5316\u6c34\u5e73\u76f8\u5bf9\u5e94\u7684\u521d\u59cb\u7ec6\u5316\u6570\u3002\u6b64\u5916\uff0c\u6211\u4eec\u76f8\u5e94\u5730\u8bbe\u7f6e\u521d\u59cb\u6d3b\u52a8FE\u6307\u6570\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::initialize_grid() \n  { \n    TimerOutput::Scope t(computing_timer, \"initialize grid\"); \n\n    std::vector<unsigned int> repetitions(dim); \n    Point<dim>                bottom_left, top_right; \n    for (unsigned int d = 0; d < dim; ++d) \n      if (d < 2) \n        { \n          repetitions[d] = 2; \n          bottom_left[d] = -1.; \n          top_right[d]   = 1.; \n        } \n      else \n        { \n          repetitions[d] = 1; \n          bottom_left[d] = 0.; \n          top_right[d]   = 1.; \n        } \n\n    std::vector<int> cells_to_remove(dim, 1); \n    cells_to_remove[0] = -1; \n\n    GridGenerator::subdivided_hyper_L( \n      triangulation, repetitions, bottom_left, top_right, cells_to_remove); \n\n    triangulation.refine_global(prm.min_h_level); \n\n    const unsigned int min_fe_index = prm.min_p_degree - 1; \n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        cell->set_active_fe_index(min_fe_index); \n  } \n\n//  @sect4{LaplaceProblem::setup_system}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u770b\u8d77\u6765\u548c step-40 \u7684\u51fd\u6570\u5b8c\u5168\u4e00\u6837\uff0c\u4f46\u662f\u4f60\u4f1a\u6ce8\u610f\u5230\u6ca1\u6709\u7cfb\u7edf\u77e9\u9635\u4ee5\u53ca\u56f4\u7ed5\u5b83\u7684\u811a\u624b\u67b6\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u5c06\u5728\u8fd9\u91cc\u521d\u59cb\u5316 <code>laplace_operator</code> \u4e2d\u7684MatrixFree\u516c\u5f0f\u3002\u5bf9\u4e8e\u8fb9\u754c\u6761\u4ef6\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u672c\u6559\u7a0b\u524d\u9762\u4ecb\u7ecd\u7684Solution\u7c7b\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::setup_system() \n  { \n    TimerOutput::Scope t(computing_timer, \"setup system\"); \n\n    dof_handler.distribute_dofs(fe_collection); \n\n    locally_owned_dofs = dof_handler.locally_owned_dofs(); \n    DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs); \n\n    locally_relevant_solution.reinit(locally_owned_dofs, \n                                     locally_relevant_dofs, \n                                     mpi_communicator); \n    system_rhs.reinit(locally_owned_dofs, mpi_communicator); \n\n    constraints.clear(); \n    constraints.reinit(locally_relevant_dofs); \n    DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n    VectorTools::interpolate_boundary_values( \n      mapping_collection, dof_handler, 0, Solution<dim>(), constraints); \n    constraints.close(); \n\n    laplace_operator.reinit(mapping_collection, \n                            dof_handler, \n                            quadrature_collection, \n                            constraints, \n                            system_rhs); \n  } \n\n//  @sect4{LaplaceProblem::print_diagnostics}  \n\n// \u8fd9\u662f\u4e00\u4e2a\u6253\u5370\u5173\u4e8e\u65b9\u7a0b\u7ec4\u53ca\u5176\u5212\u5206\u7684\u989d\u5916\u8bca\u65ad\u7684\u51fd\u6570\u3002\u9664\u4e86\u901a\u5e38\u7684\u5168\u5c40\u6d3b\u52a8\u5355\u5143\u6570\u548c\u81ea\u7531\u5ea6\u5916\uff0c\u6211\u4eec\u8fd8\u8f93\u51fa\u5b83\u4eec\u7684\u5c40\u90e8\u7b49\u4ef7\u7269\u3002\u4e3a\u4e86\u89c4\u8303\u8f93\u51fa\uff0c\u6211\u4eec\u5c06\u7528 Utilities::MPI::gather \u64cd\u4f5c\u5c06\u5c40\u90e8\u6570\u91cf\u4f20\u8fbe\u7ed9\u7b2c\u4e00\u4e2a\u8fdb\u7a0b\uff0c\u7136\u540e\u7531\u8be5\u8fdb\u7a0b\u8f93\u51fa\u6240\u6709\u4fe1\u606f\u3002\u672c\u5730\u91cf\u7684\u8f93\u51fa\u53ea\u9650\u4e8e\u524d8\u4e2a\u8fdb\u7a0b\uff0c\u4ee5\u907f\u514d\u7ec8\u7aef\u7684\u6742\u4e71\u3002\n\n// \u6b64\u5916\uff0c\u6211\u4eec\u60f3\u6253\u5370\u6570\u503c\u79bb\u6563\u5316\u4e2d\u7684\u591a\u9879\u5f0f\u5ea6\u6570\u7684\u9891\u7387\u3002\u7531\u4e8e\u8fd9\u4e9b\u4fe1\u606f\u53ea\u5b58\u50a8\u5728\u672c\u5730\uff0c\u6211\u4eec\u5c06\u8ba1\u7b97\u672c\u5730\u62e5\u6709\u7684\u5355\u5143\u4e0a\u7684\u6709\u9650\u5143\uff0c\u968f\u540e\u901a\u8fc7 Utilities::MPI::sum. \u8fdb\u884c\u4ea4\u6d41\u3002\n  template <int dim> \n  void LaplaceProblem<dim>::print_diagnostics() \n  { \n    const unsigned int first_n_processes = \n      std::min<unsigned int>(8, \n                             Utilities::MPI::n_mpi_processes(mpi_communicator)); \n    const bool output_cropped = \n      first_n_processes < Utilities::MPI::n_mpi_processes(mpi_communicator); \n\n    { \n      pcout << \"   Number of active cells:       \" \n            << triangulation.n_global_active_cells() << std::endl \n            << \"     by partition:              \"; \n\n      std::vector<unsigned int> n_active_cells_per_subdomain = \n        Utilities::MPI::gather(mpi_communicator, \n                               triangulation.n_locally_owned_active_cells()); \n      for (unsigned int i = 0; i < first_n_processes; ++i) \n        pcout << ' ' << n_active_cells_per_subdomain[i]; \n      if (output_cropped) \n        pcout << \" ...\"; \n      pcout << std::endl; \n    } \n\n    { \n      pcout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n            << std::endl \n            << \"     by partition:              \"; \n\n      std::vector<types::global_dof_index> n_dofs_per_subdomain = \n        Utilities::MPI::gather(mpi_communicator, \n                               dof_handler.n_locally_owned_dofs()); \n      for (unsigned int i = 0; i < first_n_processes; ++i) \n        pcout << ' ' << n_dofs_per_subdomain[i]; \n      if (output_cropped) \n        pcout << \" ...\"; \n      pcout << std::endl; \n    } \n\n    { \n      std::vector<types::global_dof_index> n_constraints_per_subdomain = \n        Utilities::MPI::gather(mpi_communicator, constraints.n_constraints()); \n\n      pcout << \"   Number of constraints:        \" \n            << std::accumulate(n_constraints_per_subdomain.begin(), \n                               n_constraints_per_subdomain.end(), \n                               0) \n            << std::endl \n            << \"     by partition:              \"; \n      for (unsigned int i = 0; i < first_n_processes; ++i) \n        pcout << ' ' << n_constraints_per_subdomain[i]; \n      if (output_cropped) \n        pcout << \" ...\"; \n      pcout << std::endl; \n    } \n\n    { \n      std::vector<unsigned int> n_fe_indices(fe_collection.size(), 0); \n      for (const auto &cell : dof_handler.active_cell_iterators()) \n        if (cell->is_locally_owned()) \n          n_fe_indices[cell->active_fe_index()]++; \n\n      Utilities::MPI::sum(n_fe_indices, mpi_communicator, n_fe_indices); \n\n      pcout << \"   Frequencies of poly. degrees:\"; \n      for (unsigned int i = 0; i < fe_collection.size(); ++i) \n        if (n_fe_indices[i] > 0) \n          pcout << ' ' << fe_collection[i].degree << \":\" << n_fe_indices[i]; \n      pcout << std::endl; \n    } \n  } \n\n//  @sect4{LaplaceProblem::solve_system}  \n\n// \u56f4\u7ed5\u89e3\u51b3\u65b9\u6848\u7684\u811a\u624b\u67b6\u4e0e  step-40  \u7684\u7c7b\u4f3c\u3002\u6211\u4eec\u51c6\u5907\u4e00\u4e2a\u7b26\u5408MatrixFree\u8981\u6c42\u7684\u5411\u91cf\uff0c\u5e76\u6536\u96c6\u672c\u5730\u76f8\u5173\u7684\u81ea\u7531\u5ea6\uff0c\u6211\u4eec\u89e3\u51b3\u4e86\u65b9\u7a0b\u7cfb\u7edf\u3002\u89e3\u51b3\u65b9\u6cd5\u662f\u901a\u8fc7\u524d\u9762\u4ecb\u7ecd\u7684\u51fd\u6570\u8fdb\u884c\u7684\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::solve_system() \n  { \n    TimerOutput::Scope t(computing_timer, \"solve system\"); \n\n    LinearAlgebra::distributed::Vector<double> completely_distributed_solution; \n    laplace_operator.initialize_dof_vector(completely_distributed_solution); \n\n    SolverControl solver_control(system_rhs.size(), \n                                 prm.tolerance_factor * system_rhs.l2_norm()); \n\n    solve_with_gmg(solver_control, \n                   laplace_operator, \n                   completely_distributed_solution, \n                   system_rhs, \n                   prm.mg_data, \n                   mapping_collection, \n                   dof_handler, \n                   quadrature_collection); \n\n    pcout << \"   Solved in \" << solver_control.last_step() << \" iterations.\" \n          << std::endl; \n\n    constraints.distribute(completely_distributed_solution); \n\n    locally_relevant_solution.copy_locally_owned_data_from( \n      completely_distributed_solution); \n    locally_relevant_solution.update_ghost_values(); \n  } \n\n//  @sect4{LaplaceProblem::compute_indicators}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u53ea\u5305\u542b\u5176\u4ed6\u6559\u7a0b\u4e2d\u5178\u578b\u7684 <code>refine_grid</code> \u51fd\u6570\u7684\u4e00\u90e8\u5206\uff0c\u5728\u8fd9\u4e2a\u610f\u4e49\u4e0a\u662f\u65b0\u7684\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u5c06\u53ea\u8ba1\u7b97\u4e0e\u5b9e\u9645\u7ec6\u5316\u7f51\u683c\u76f8\u9002\u5e94\u7684\u6240\u6709\u6307\u6807\u3002\u6211\u4eec\u8fd9\u6837\u505a\u7684\u76ee\u7684\u662f\u5c06\u6240\u6709\u7684\u6307\u6807\u5199\u5230\u6587\u4ef6\u7cfb\u7edf\u4e2d\uff0c\u4ee5\u4fbf\u4e3a\u4ee5\u540e\u50a8\u5b58\u3002\n\n// \u7531\u4e8e\u6211\u4eec\u5904\u7406\u7684\u662f\u4e00\u4e2a\u692d\u5706\u95ee\u9898\uff0c\u6211\u4eec\u5c06\u518d\u6b21\u5229\u7528KellyErrorEstimator\uff0c\u4f46\u6709\u4e00\u70b9\u4e0d\u540c\u3002\u4fee\u6539\u5e95\u5c42\u9762\u79ef\u5206\u7684\u7f29\u653e\u7cfb\u6570\uff0c\u4f7f\u5176\u53d6\u51b3\u4e8e\u76f8\u90bb\u5143\u7d20\u7684\u5b9e\u9645\u591a\u9879\u5f0f\u7a0b\u5ea6\uff0c\u8fd9\u5bf9hp-adaptive\u5e94\u7528\u662f\u6709\u5229\u7684  @cite davydov2017hp  \u3002\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u6307\u5b9a\u4f60\u6240\u6ce8\u610f\u5230\u7684\u9644\u52a0\u53c2\u6570\u4e2d\u7684\u6700\u540e\u4e00\u4e2a\u53c2\u6570\u6765\u505a\u5230\u8fd9\u4e00\u70b9\u3002\u5176\u4ed6\u7684\u5b9e\u9645\u4e0a\u53ea\u662f\u9ed8\u8ba4\u7684\u3002\n\n// \u4e3a\u4e86hp-adaptation\u7684\u76ee\u7684\uff0c\u6211\u4eec\u5c06\u7528\u6559\u7a0b\u4ecb\u7ecd\u4e2d\u7684\u7b56\u7565\u6765\u8ba1\u7b97\u5e73\u6ed1\u5ea6\u4f30\u8ba1\uff0c\u5e76\u4f7f\u7528 SmoothnessEstimator::Legendre. \u4e2d\u7684\u5b9e\u73b0 \u5728\u53c2\u6570\u7ed3\u6784\u4e2d\uff0c\u6211\u4eec\u5c06\u6700\u5c0f\u591a\u9879\u5f0f\u5ea6\u6570\u8bbe\u7f6e\u4e3a2\uff0c\u56e0\u4e3a\u4f3c\u4e4e\u5e73\u6ed1\u5ea6\u4f30\u8ba1\u7b97\u6cd5\u5728\u5904\u7406\u7ebf\u6027\u5143\u7d20\u65f6\u6709\u95ee\u9898\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::compute_indicators() \n  { \n    TimerOutput::Scope t(computing_timer, \"compute indicators\"); \n\n    estimated_error_per_cell.grow_or_shrink(triangulation.n_active_cells()); \n    KellyErrorEstimator<dim>::estimate( \n      dof_handler, \n      face_quadrature_collection, \n      std::map<types::boundary_id, const Function<dim> *>(), \n      locally_relevant_solution, \n      estimated_error_per_cell, \n      /*component_mask=  */ \n      ComponentMask(), \n      /*coefficients=  */ \n      nullptr, \n      /*n_threads=*/\n      numbers::invalid_unsigned_int,  \n      /*subdomain_id=*/ \n      numbers::invalid_subdomain_id,  \n      /*material_id=*/ \n      numbers::invalid_material_id,  \n      /*\u7b56\u7565=  */ \n      KellyErrorEstimator<dim>::Strategy::face_diameter_over_twice_max_degree); \n\n    hp_decision_indicators.grow_or_shrink(triangulation.n_active_cells()); \n    SmoothnessEstimator::Legendre::coefficient_decay(*legendre, \n                                                     dof_handler, \n                                                     locally_relevant_solution, \n                                                     hp_decision_indicators); \n  } \n\n//  @sect4{LaplaceProblem::adapt_resolution}  \n\n// \u6709\u4e86\u4e4b\u524d\u8ba1\u7b97\u51fa\u7684\u6307\u6807\uff0c\u6211\u4eec\u6700\u7ec8\u5c06\u6807\u8bb0\u6240\u6709\u5355\u5143\u8fdb\u884c\u9002\u5e94\uff0c\u540c\u65f6\u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\u6267\u884c\u7ec6\u5316\u3002\u548c\u4ee5\u524d\u7684\u6559\u7a0b\u4e00\u6837\uff0c\u6211\u4eec\u5c06\u4f7f\u7528 \"\u56fa\u5b9a\u6570\u5b57 \"\u7b56\u7565\uff0c\u4f46\u73b0\u5728\u662f\u9488\u5bf9hp-adaptation\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::adapt_resolution() \n  { \n    TimerOutput::Scope t(computing_timer, \"adapt resolution\"); \n\n// \u9996\u5148\uff0c\u6211\u4eec\u5c06\u6839\u636e\u6bcf\u4e2a\u5355\u5143\u7684\u8bef\u5dee\u4f30\u8ba1\u503c\u6765\u8bbe\u7f6e\u7ec6\u5316\u548c\u7c97\u5316\u6807\u5fd7\u3002\u8fd9\u91cc\u6ca1\u6709\u4ec0\u4e48\u65b0\u4e1c\u897f\u3002\n\n// \u6211\u4eec\u5c06\u4f7f\u7528\u5728\u5176\u4ed6deal.II\u6559\u7a0b\u4e2d\u9610\u8ff0\u8fc7\u7684\u4e00\u822c\u7ec6\u5316\u548c\u7c97\u5316\u6bd4\u4f8b\uff1a\u4f7f\u7528\u56fa\u5b9a\u6570\u5b57\u7b56\u7565\uff0c\u6211\u4eec\u5c06\u6807\u8bb0\u6240\u6709\u5355\u5143\u4e2d\u768430%\u8fdb\u884c\u7ec6\u5316\uff0c3%\u8fdb\u884c\u7c97\u5316\uff0c\u5982\u53c2\u6570\u7ed3\u6784\u4e2d\u63d0\u4f9b\u7684\u3002\n\n    parallel::distributed::GridRefinement::refine_and_coarsen_fixed_number( \n      triangulation, \n      estimated_error_per_cell, \n      prm.refine_fraction, \n      prm.coarsen_fraction); \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5c06\u5bf9hp-adaptation\u8fdb\u884c\u6240\u6709\u8c03\u6574\u3002\u6211\u4eec\u60f3\u7ec6\u5316\u548c\u7c97\u5316\u90a3\u4e9b\u5728\u4e0a\u4e00\u6b65\u4e2d\u88ab\u6807\u8bb0\u7684\u5355\u5143\uff0c\u4f46\u9700\u8981\u51b3\u5b9a\u662f\u901a\u8fc7\u8c03\u6574\u7f51\u683c\u5206\u8fa8\u7387\u8fd8\u662f\u8c03\u6574\u591a\u9879\u5f0f\u7a0b\u5ea6\u6765\u5b9e\u73b0\u3002\n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u8c03\u7528\u6839\u636e\u4e4b\u524d\u8ba1\u7b97\u7684\u5e73\u6ed1\u5ea6\u6307\u6807\u8bbe\u7f6e\u672a\u6765\u7684FE\u6307\u6570\uff0c\u4f5c\u4e3ap-adaptation\u6307\u6807\u3002\u8fd9\u4e9b\u6307\u6570\u5c06\u53ea\u8bbe\u7f6e\u5728\u90a3\u4e9b\u5206\u914d\u4e86\u7ec6\u5316\u6216\u7c97\u5316\u6807\u5fd7\u7684\u5355\u5143\u4e0a\u3002\n\n// \u5bf9\u4e8ep-adaptation\u5206\u6570\uff0c\u6211\u4eec\u5c06\u91c7\u53d6\u4e00\u4e2a\u6709\u6839\u636e\u7684\u731c\u6d4b\u3002\u7531\u4e8e\u6211\u4eec\u53ea\u671f\u671b\u5728\u6211\u4eec\u7684\u65b9\u6848\u4e2d\u51fa\u73b0\u4e00\u4e2a\u5355\u4e00\u7684\u5947\u70b9\uff0c\u5373\u5728\u57df\u7684\u539f\u70b9\uff0c\u800c\u5728\u5176\u4ed6\u4efb\u4f55\u5730\u65b9\u90fd\u6709\u4e00\u4e2a\u5e73\u6ed1\u7684\u89e3\u51b3\u65b9\u6848\uff0c\u6240\u4ee5\u6211\u4eec\u5e0c\u671b\u5f3a\u70c8\u503e\u5411\u4e8e\u4f7f\u7528p-adaptation\u800c\u4e0d\u662fh-adaptation\u3002\u8fd9\u53cd\u6620\u5728\u6211\u4eec\u5bf9p-\u7cbe\u7b80\u548cp-\u7c97\u5316\u90fd\u9009\u62e9\u4e8690%\u7684\u5206\u6570\u3002\n\n    hp::Refinement::p_adaptivity_fixed_number(dof_handler, \n                                              hp_decision_indicators, \n                                              prm.p_refine_fraction, \n                                              prm.p_coarsen_fraction); \n\n// \u5728\u8fd9\u4e2a\u9636\u6bb5\uff0c\u6211\u4eec\u65e2\u6709\u672a\u6765\u7684FE\u6307\u6570\uff0c\u4e5f\u6709\u7ecf\u5178\u7684\u7ec6\u5316\u548c\u7c97\u5316\u6807\u5fd7\uff0c\u540e\u8005\u5c06\u7531 Triangulation::execute_coarsening_and_refinement() \u89e3\u91ca\u4e3ah-\u9002\u5e94\u6027\u3002\u6211\u4eec\u5e0c\u671b\u53ea\u5bf9\u7ec6\u80de\u65bd\u52a0\u4e00\u79cd\u9002\u5e94\uff0c\u8fd9\u5c31\u662f\u4e0b\u4e00\u4e2a\u51fd\u6570\u5c06\u4e3a\u6211\u4eec\u89e3\u51b3\u7684\u95ee\u9898\u3002\u7b80\u800c\u8a00\u4e4b\uff0c\u5728\u5206\u914d\u6709\u4e24\u79cd\u7c7b\u578b\u6307\u6807\u7684\u5355\u5143\u683c\u4e0a\uff0c\u6211\u4eec\u5c06\u503e\u5411\u4e8ep-\u9002\u5e94\u7684\u90a3\u4e00\u79cd\uff0c\u5e76\u5220\u9664h-\u9002\u5e94\u7684\u90a3\u4e00\u79cd\u3002\n\n    hp::Refinement::choose_p_over_h(dof_handler); \n\n// \u8bbe\u7f6e\u5b8c\u6240\u6709\u6307\u6807\u540e\uff0c\u6211\u4eec\u5c06\u5220\u9664\u90a3\u4e9b\u8d85\u8fc7\u53c2\u6570\u7ed3\u6784\u4e2d\u63d0\u4f9b\u7684\u6c34\u5e73\u8303\u56f4\u7684\u6307\u5b9a\u9650\u5236\u7684\u6307\u6807\u3002\u7531\u4e8e\u63d0\u4f9b\u7684\u6709\u9650\u5143\u6570\u91cf\u6709\u9650\uff0c\u8fd9\u79cd\u9650\u5236\u81ea\u7136\u4f1a\u51fa\u73b0\u5728p-adaptation\u4e2d\u3002\u6b64\u5916\uff0c\u6211\u4eec\u5728\u6784\u9020\u51fd\u6570\u4e2d\u4e3ap-adaptation\u6ce8\u518c\u4e86\u4e00\u4e2a\u81ea\u5b9a\u4e49\u5c42\u6b21\u7ed3\u6784\u3002\u73b0\u5728\uff0c\u6211\u4eec\u9700\u8981\u50cf  step-31  \u4e2d\u90a3\u6837\uff0c\u5728h-adaptive\u7684\u4e0a\u4e0b\u6587\u4e2d\u624b\u52a8\u5b8c\u6210\u3002\n\n// \u6211\u4eec\u5c06\u904d\u5386\u6307\u5b9a\u7684\u6700\u5c0f\u548c\u6700\u5927\u5c42\u6b21\u4e0a\u7684\u6240\u6709\u5355\u5143\u683c\uff0c\u5e76\u5220\u9664\u76f8\u5e94\u7684\u6807\u5fd7\u3002\u4f5c\u4e3a\u4e00\u79cd\u9009\u62e9\uff0c\u6211\u4eec\u4e5f\u53ef\u4ee5\u901a\u8fc7\u76f8\u5e94\u5730\u8bbe\u7f6e\u672a\u6765\u7684FE\u6307\u6570\u6765\u6807\u8bb0\u8fd9\u4e9b\u5355\u5143\u7684p\u9002\u5e94\u6027\uff0c\u800c\u4e0d\u662f\u7b80\u5355\u5730\u6e05\u9664\u7ec6\u5316\u548c\u7c97\u5316\u7684\u6807\u5fd7\u3002\n\n    Assert(triangulation.n_levels() >= prm.min_h_level + 1 && \n             triangulation.n_levels() <= prm.max_h_level + 1, \n           ExcInternalError()); \n\n    if (triangulation.n_levels() > prm.max_h_level) \n      for (const auto &cell : \n           triangulation.active_cell_iterators_on_level(prm.max_h_level)) \n        cell->clear_refine_flag(); \n\n    for (const auto &cell : \n         triangulation.active_cell_iterators_on_level(prm.min_h_level)) \n      cell->clear_coarsen_flag(); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u5c31\u5269\u4e0b\u6267\u884c\u7c97\u5316\u548c\u7ec6\u5316\u4e86\u3002\u5728\u8fd9\u91cc\uff0c\u4e0d\u4ec5\u7f51\u683c\u4f1a\u88ab\u66f4\u65b0\uff0c\u800c\u4e14\u6240\u6709\u4ee5\u524d\u7684\u672a\u6765FE\u6307\u6570\u4e5f\u4f1a\u53d8\u5f97\u6d3b\u8dc3\u3002\n\n// \u8bb0\u5f97\u6211\u4eec\u5728\u6784\u9020\u51fd\u6570\u4e2d\u4e3a\u4e09\u89d2\u5316\u4fe1\u53f7\u9644\u52a0\u4e86\u51fd\u6570\uff0c\u5c06\u5728\u8fd9\u4e2a\u51fd\u6570\u8c03\u7528\u4e2d\u88ab\u89e6\u53d1\u3002\u6240\u4ee5\u4f1a\u6709\u66f4\u591a\u7684\u4e8b\u60c5\u53d1\u751f\uff1a\u52a0\u6743\u91cd\u65b0\u5206\u533a\u5c06\u88ab\u6267\u884c\u4ee5\u786e\u4fdd\u8d1f\u8f7d\u5e73\u8861\uff0c\u4ee5\u53ca\u6211\u4eec\u5c06\u9650\u5236\u76f8\u90bb\u5355\u5143\u4e4b\u95f4\u7684p\u7ea7\u5dee\u3002\n\n    triangulation.execute_coarsening_and_refinement(); \n  } \n\n//  @sect4{LaplaceProblem::output_results}  \n\n// \u5728\u5e76\u884c\u5e94\u7528\u4e2d\u5411\u6587\u4ef6\u7cfb\u7edf\u5199\u5165\u7ed3\u679c\u7684\u5de5\u4f5c\u65b9\u5f0f\u4e0e  step-40  \u4e2d\u5b8c\u5168\u76f8\u540c\u3002\u9664\u4e86\u6211\u4eec\u5728\u6574\u4e2a\u6559\u7a0b\u4e2d\u51c6\u5907\u7684\u6570\u636e\u5bb9\u5668\u5916\uff0c\u6211\u4eec\u8fd8\u60f3\u5199\u51fa\u7f51\u683c\u4e0a\u6bcf\u4e2a\u6709\u9650\u5143\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\uff0c\u4ee5\u53ca\u6bcf\u4e2a\u5355\u5143\u6240\u5c5e\u7684\u5b50\u57df\u3002\u6211\u4eec\u5728\u8fd9\u4e2a\u51fd\u6570\u7684\u8303\u56f4\u5185\u4e3a\u6b64\u51c6\u5907\u5fc5\u8981\u7684\u5bb9\u5668\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::output_results(const unsigned int cycle) \n  { \n    TimerOutput::Scope t(computing_timer, \"output results\"); \n\n    Vector<float> fe_degrees(triangulation.n_active_cells()); \n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        fe_degrees(cell->active_cell_index()) = cell->get_fe().degree; \n\n    Vector<float> subdomain(triangulation.n_active_cells()); \n    for (auto &subd : subdomain) \n      subd = triangulation.locally_owned_subdomain(); \n\n    DataOut<dim> data_out; \n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(locally_relevant_solution, \"solution\"); \n    data_out.add_data_vector(fe_degrees, \"fe_degree\"); \n    data_out.add_data_vector(subdomain, \"subdomain\"); \n    data_out.add_data_vector(estimated_error_per_cell, \"error\"); \n    data_out.add_data_vector(hp_decision_indicators, \"hp_indicator\"); \n    data_out.build_patches(mapping_collection); \n\n    data_out.write_vtu_with_pvtu_record( \n      \"./\", \"solution\", cycle, mpi_communicator, 2, 1); \n  } \n\n//  @sect4{LaplaceProblem::run}  \n\n// \u5b9e\u9645\u7684\u8fd0\u884c\u51fd\u6570\u770b\u8d77\u6765\u53c8\u548c  step-40  \u975e\u5e38\u76f8\u4f3c\u3002\u552f\u4e00\u589e\u52a0\u7684\u662f\u5b9e\u9645\u5faa\u73af\u4e4b\u524d\u7684\u62ec\u53f7\u5185\u7684\u90e8\u5206\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u5c06\u9884\u5148\u8ba1\u7b97Legendre\u53d8\u6362\u77e9\u9635\u3002\u4e00\u822c\u6765\u8bf4\uff0c\u6bcf\u5f53\u9700\u8981\u67d0\u4e2a\u77e9\u9635\u65f6\uff0c\u8fd9\u4e9b\u77e9\u9635\u5c06\u901a\u8fc7\u61d2\u60f0\u5206\u914d\u7684\u65b9\u5f0f\u8fdb\u884c\u5b9e\u65f6\u8ba1\u7b97\u3002\u7136\u800c\uff0c\u51fa\u4e8e\u8ba1\u65f6\u7684\u76ee\u7684\uff0c\u6211\u4eec\u5e0c\u671b\u5728\u5b9e\u9645\u7684\u65f6\u95f4\u6d4b\u91cf\u5f00\u59cb\u4e4b\u524d\uff0c\u4e00\u6b21\u6027\u5730\u8ba1\u7b97\u5b83\u4eec\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5c06\u628a\u5b83\u4eec\u7684\u8ba1\u7b97\u6307\u5b9a\u4e3a\u81ea\u5df1\u7684\u8303\u56f4\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::run() \n  { \n    pcout << \"Running with Trilinos on \" \n          << Utilities::MPI::n_mpi_processes(mpi_communicator) \n          << \" MPI rank(s)...\" << std::endl; \n\n    { \n      pcout << \"Calculating transformation matrices...\" << std::endl; \n      TimerOutput::Scope t(computing_timer, \"calculate transformation\"); \n      legendre->precalculate_all_transformation_matrices(); \n    } \n\n    for (unsigned int cycle = 0; cycle < prm.n_cycles; ++cycle) \n      { \n        pcout << \"Cycle \" << cycle << ':' << std::endl; \n\n        if (cycle == 0) \n          initialize_grid(); \n        else \n          adapt_resolution(); \n\n        setup_system(); \n\n        print_diagnostics(); \n\n        solve_system(); \n\n        compute_indicators(); \n\n        if (Utilities::MPI::n_mpi_processes(mpi_communicator) <= 32) \n          output_results(cycle); \n\n        computing_timer.print_summary(); \n        computing_timer.reset(); \n\n        pcout << std::endl; \n      } \n  } \n} // namespace Step75 \n\n//  @sect4{main()}  \n\n// \u6700\u540e\u4e00\u4e2a\u51fd\u6570\u662f <code>main</code> \u51fd\u6570\uff0c\u5b83\u5c06\u6700\u7ec8\u521b\u5efa\u5e76\u8fd0\u884c\u4e00\u4e2aLaplaceOperator\u5b9e\u4f8b\u3002\u5b83\u7684\u7ed3\u6784\u4e0e\u5176\u4ed6\u5927\u591a\u6570\u6559\u7a0b\u7a0b\u5e8f\u76f8\u4f3c\u3002\n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      using namespace dealii; \n      using namespace Step75; \n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); \n\n      Parameters        prm; \n      LaplaceProblem<2> laplace_problem(prm); \n      laplace_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\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\n", "meta": {"hexsha": "891fb8a5b181078669ebc2b47d777dabeb89abfb", "size": 48029, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-75/step-75.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-75/step-75.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-75/step-75.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.1453982985, "max_line_length": 501, "alphanum_fraction": 0.6355743405, "num_tokens": 15753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5139468908645547}}
{"text": "// Boost.Geometry Index\r\n// Unit Test\r\n\r\n// Copyright (c) 2011-2013 Adam Wulkiewicz, Lodz, Poland.\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 <algorithms/test_intersection_content.hpp>\r\n\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/point.hpp>\r\n#include <boost/geometry/geometries/box.hpp>\r\n\r\n//#define BOOST_GEOMETRY_TEST_DEBUG\r\n\r\nvoid test_large_integers()\r\n{\r\n    typedef bg::model::point<int, 2, bg::cs::cartesian> int_point_type;\r\n    typedef bg::model::point<double, 2, bg::cs::cartesian> double_point_type;\r\n\r\n    bg::model::box<int_point_type> int_box1, int_box2;\r\n    bg::model::box<double_point_type> double_box1, double_box2;\r\n\r\n    std::string const box_li1 = \"POLYGON((1536119 192000, 1872000 528000))\";\r\n    std::string const box_li2 = \"POLYGON((1701234 368250, 2673400 777400))\";\r\n    bg::read_wkt(box_li1, int_box1);\r\n    bg::read_wkt(box_li1, double_box1);\r\n    bg::read_wkt(box_li2, int_box2);\r\n    bg::read_wkt(box_li2, double_box2);\r\n\r\n    double int_value = bgi::detail::intersection_content(int_box1, int_box2);\r\n    double double_value = bgi::detail::intersection_content(double_box1, double_box2);\r\n\r\n    BOOST_CHECK_CLOSE(int_value, double_value, 0.0001);\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n    typedef bg::model::point<int, 2, bg::cs::cartesian> P2ic;\r\n    typedef bg::model::point<float, 2, bg::cs::cartesian> P2fc;\r\n    typedef bg::model::point<double, 2, bg::cs::cartesian> P2dc;\r\n\r\n    typedef bg::model::point<int, 3, bg::cs::cartesian> P3ic;\r\n    typedef bg::model::point<float, 3, bg::cs::cartesian> P3fc;\r\n    typedef bg::model::point<double, 3, bg::cs::cartesian> P3dc;\r\n    \r\n    test_geometry<bg::model::box<P2ic> >(\"POLYGON((0 1,2 4))\", \"POLYGON((1 2,3 5))\", 2.0);\r\n    test_geometry<bg::model::box<P2fc> >(\"POLYGON((0 1,2 4))\", \"POLYGON((1 2,3 5))\", 2.0);\r\n    test_geometry<bg::model::box<P2dc> >(\"POLYGON((0 1,2 4))\", \"POLYGON((1 2,3 5))\", 2.0);\r\n    test_geometry<bg::model::box<P3ic> >(\"POLYGON((0 1 2,2 4 6))\", \"POLYGON((1 2 3,3 5 7))\", 6.0);\r\n    test_geometry<bg::model::box<P3fc> >(\"POLYGON((0 1 2,2 4 6))\", \"POLYGON((1 2 3,3 5 7))\", 6.0);\r\n    test_geometry<bg::model::box<P3dc> >(\"POLYGON((0 1 2,2 4 6))\", \"POLYGON((1 2 3,3 5 7))\", 6.0);\r\n\r\n    test_geometry<bg::model::box<P2dc> >(\"POLYGON((0 1,2 4))\", \"POLYGON((2 1,3 4))\", 0.0);\r\n    test_geometry<bg::model::box<P2dc> >(\"POLYGON((0 1,2 4))\", \"POLYGON((2 4,3 5))\", 0.0);\r\n    \r\n#ifdef HAVE_TTMATH\r\n    typedef bg::model::point<ttmath_big, 2, bg::cs::cartesian> P2ttmc;\r\n    typedef bg::model::point<ttmath_big, 3, bg::cs::cartesian> P3ttmc;\r\n\r\n    test_geometry<bg::model::box<P2ttmc> >(\"POLYGON((0 1,2 4))\", \"POLYGON((1 2,3 5))\", 2.0);\r\n    test_geometry<bg::model::box<P3ttmc> >(\"POLYGON((0 1 2,2 4 6))\", \"POLYGON((1 2 3,3 5 7))\", 6.0);\r\n#endif\r\n\r\n    test_large_integers();\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "81c2b010dcea9f202a665330f49dbe37d32e00f8", "size": 3007, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/index/test/algorithms/intersection_content.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/index/test/algorithms/intersection_content.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/index/test/algorithms/intersection_content.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": 42.3521126761, "max_line_length": 101, "alphanum_fraction": 0.648486864, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5139468824363347}}
{"text": "#include <NTL/GF2EX.h>\n#include <NTL/GF2XFactoring.h>\n\nnamespace NTL {\n\nvoid PlainMul(GF2EX&,const GF2EX&,const GF2EX&);\nvoid mul_disable_plain(GF2EX&,const GF2EX&,const GF2EX&);\n\n}\n\nNTL_CLIENT\n\n\n#define TIME_IT(t, action) \\\ndo { \\\n   double _t0, _t1; \\\n   long _iter = 1; \\\n   long _cnt = 0; \\\n   do { \\\n      _t0 = GetTime(); \\\n      for (long _i = 0; _i < _iter; _i++) { action; _cnt++; } \\\n      _t1 = GetTime(); \\\n   } while ( _t1 - _t0 < 2 && (_iter *= 2)); \\\n   t = (_t1 - _t0)/_iter; \\\n} while(0)\n\n\nlong test(long k)\n{\n   GF2X P;\n\n   BuildIrred(P, k);\n   GF2EPush push(P);\n\n   for (long n = 2; ; n++) {\n      cerr << \",\";\n      GF2EX a, b, c;\n      random(a, n);\n      random(b, n);\n      double t1, t2;\n      TIME_IT(t1, mul_disable_plain(c, a, b));\n      TIME_IT(t2, PlainMul(c, a, b));\n      double t = t1/t2;\n      if (t <= 0.95) return n;\n   }\n}\n\nint main()\n{\n   cerr << \"0.5 \" << test(32) << \"\\n\";\n   for (long i = 1; i <= 40; i++) {\n      cerr << i << \" \" << test(64*i) << \"\\n\";\n   }\n}\n\n\n", "meta": {"hexsha": "6f98b1178f56312e22c0725477d424061d44a2dc", "size": 1003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/GF2EXKarCross.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-03-21T19:39:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T06:14:16.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/GF2EXKarCross.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-10-18T18:26:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T14:50:04.000Z", "max_forks_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/GF2EXKarCross.cpp", "max_forks_repo_name": "dklee0501/Lobster", "max_forks_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2016-01-16T07:59:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T10:27:23.000Z", "avg_line_length": 17.5964912281, "max_line_length": 63, "alphanum_fraction": 0.4935194417, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5138957771559309}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n//typedef Matrix<double, 7, 1> Vector7d;\ntypedef Array<double, 6, 1> Array6d;\n\nint main(void)\n{\n    MatrixXd axis_value(8, 6);\n    axis_value = MatrixXd::Constant(8,6,0.0);\n    std::cout << \"axis_value = \\n\" << axis_value << std::endl;\n    Array<Matrix4d, 7, 1> T;\n    for (int i = 0; i < 7; i++)\n    {\n        T(i) = Matrix4d::Constant(0.0);         //Constant(4, 4, 0.0);\n    }\n    //std::cout << \"T = \\n\" << T << std::endl;  // not valid\n    for (int i = 0; i < 7; i++)\n    {\n        std::cout << \"T[\" << i << \"] = \\n\" << T(i) << std::endl;\n    }\n    Array6d alpha;\n    alpha << 1,3,5,7,9,6;\n    alpha = Array6d::Constant(0.0);\n    alpha[0] = 9.0;\n    alpha[1] = 8.0;\n    alpha[2] = 5.0;\n    std::cout << \"alpha = \" << alpha << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "7277f9fdc0ab510c1bc2dea6a4134b0870d125c4", "size": 825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen_practice/eigen_test.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_test.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_test.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.78125, "max_line_length": 70, "alphanum_fraction": 0.5054545455, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5138631337642898}}
{"text": "#pragma once\n\n// CUT begin\n#include <boost/multiprecision/cpp_int.hpp>\nusing mpint = boost::multiprecision::cpp_int;\n", "meta": {"hexsha": "c8155e218a078688e16eae37a94ce4d1924be3d0", "size": 117, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utilities/multiprecision_int.hpp", "max_stars_repo_name": "ankit6776/cplib-cpp", "max_stars_repo_head_hexsha": "b9f8927a6c7301374c470856828aa1f5667d967b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2021-06-21T00:18:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T17:45:44.000Z", "max_issues_repo_path": "utilities/multiprecision_int.hpp", "max_issues_repo_name": "ankit6776/cplib-cpp", "max_issues_repo_head_hexsha": "b9f8927a6c7301374c470856828aa1f5667d967b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2021-06-03T14:42:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T14:15:30.000Z", "max_forks_repo_path": "utilities/multiprecision_int.hpp", "max_forks_repo_name": "ankit6776/cplib-cpp", "max_forks_repo_head_hexsha": "b9f8927a6c7301374c470856828aa1f5667d967b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-12-11T06:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-07T13:45:32.000Z", "avg_line_length": 19.5, "max_line_length": 45, "alphanum_fraction": 0.7692307692, "num_tokens": 29, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5138359732743615}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"test_average\"\n\n#include <boost/test/unit_test.hpp>\n#include \"nanocv/math/abs.hpp\"\n#include \"nanocv/math/epsilon.hpp\"\n#include \"nanocv/math/average_scalar.hpp\"\n\nnamespace test\n{\n        using namespace ncv;\n\n        void check_average(size_t range)\n        {\n                typedef double test_scalar_t;\n\n                average_scalar_t<test_scalar_t> running_average;\n\n                for (size_t i = 0; i <= range; i ++)\n                {\n                        running_average.update(static_cast<test_scalar_t>(i), test_scalar_t(1));\n                }\n\n                const test_scalar_t real_average = static_cast<test_scalar_t>(range) / static_cast<test_scalar_t>(2);\n\n                BOOST_CHECK_LE(math::abs(running_average.value() - real_average), math::epsilon1<test_scalar_t>());\n        }\n}\n\nBOOST_AUTO_TEST_CASE(test_average)\n{\n        test::check_average(1);\n        test::check_average(5);\n        test::check_average(17);\n        test::check_average(85);\n        test::check_average(187);\n        test::check_average(1561);\n        test::check_average(14332);\n        test::check_average(123434);\n}\n", "meta": {"hexsha": "3a9165942e1c8ab37d13219bb7913bf3e8c1ced3", "size": 1172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_average.cpp", "max_stars_repo_name": "0x0all/nanocv", "max_stars_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_stars_repo_licenses": ["MIT"], "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_average.cpp", "max_issues_repo_name": "0x0all/nanocv", "max_issues_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_issues_repo_licenses": ["MIT"], "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_average.cpp", "max_forks_repo_name": "0x0all/nanocv", "max_forks_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T02:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-02T02:41:37.000Z", "avg_line_length": 28.5853658537, "max_line_length": 117, "alphanum_fraction": 0.6245733788, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5138359655896532}}
{"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//[area_with_strategy\n//` Calculate the area of a polygon\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#include <boost/geometry/io/wkt/wkt.hpp>\n\nnamespace bg = boost::geometry; /*< Convenient namespace alias >*/\n\nint main()\n{\n    // Calculate the area of a cartesian polygon\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly;\n    bg::read_wkt(\"POLYGON((0 0,0 7,4 2,2 0,0 0))\", poly);\n    double area = bg::area(poly);\n    std::cout << \"Area: \" << area << std::endl;\n\n    // Calculate the area of a spherical polygon (for latitude: 0 at equator)\n    bg::model::polygon<bg::model::point<float, 2, bg::cs::spherical_equatorial<bg::degree> > > sph_poly;\n    bg::read_wkt(\"POLYGON((0 0,0 45,45 0,0 0))\", sph_poly);\n    area = bg::area(sph_poly);\n    std::cout << \"Area: \" << area << std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[area_with_strategy_output\n/*`\nOutput:\n[pre\nArea: 16\nArea: 0.339837\n]\n*/\n//]\n", "meta": {"hexsha": "c0a7bfc181b68daaf20b3c79696047db8eb94219", "size": 1346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/geometry/doc/src/examples/algorithms/area_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/area_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/area_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": 26.3921568627, "max_line_length": 104, "alphanum_fraction": 0.6783060921, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.513794181480958}}
{"text": "#include \"draw.hpp\"\n#include \"edge_detector.hpp\"\n\n#include <cv.hpp>\n#include <fstream>\n#include <iostream>\n\n// Only used in this example, feel free to remove boost depedencies\n#include <boost/timer/timer.hpp>\n\nvoid write_edge_points(cv::Mat const &background_image,\n                       std::vector<EdgeDetector::CurvePoint> const &edges) {\n    cv::Mat canvas;\n    cv::cvtColor(background_image, canvas, CV_GRAY2BGR);\n    for (auto const &e : edges) {\n        Draw::pixel_aa(canvas, cv::Point2d(e.x, e.y), {0, 0, 255});\n    }\n    cv::imwrite(\"edges.tif\", canvas);\n\n    std::ofstream f(\"edges.txt\", std::ios_base::out);\n    for (auto const &e : edges) {\n        f << e.x << \" \" << e.y << std::endl;\n    }\n}\n\nvoid write_chains(cv::Mat const &background_image,\n                  EdgeDetector::Chains const &chains) {\n\n    std::vector<cv::Vec3b> const colors = {{255, 0, 0},   {0, 255, 0},\n                                           {0, 0, 255},   {255, 255, 0},\n                                           {0, 255, 255}, {255, 0, 255}};\n    size_t color_idx = 0;\n\n    cv::Mat canvas;\n    cv::cvtColor(background_image, canvas, CV_GRAY2BGR);\n    for (auto const &chain : chains) {\n        auto const &color = colors.at(color_idx);\n        color_idx = (color_idx + 1) % colors.size();\n        for (size_t i = 1; i < chain.size(); ++i) {\n            auto const pt1 = chain.at(i - 1);\n            auto const pt2 = chain.at(i);\n            cv::arrowedLine(canvas, cv::Point2f(pt1.x, pt1.y),\n                            cv::Point2f(pt2.x, pt2.y), color, 1, CV_AA);\n        }\n    }\n    cv::imwrite(\"chains.tif\", canvas);\n}\n\nint main(int argc, char *argv[]) {\n\n    namespace E = EdgeDetector;\n\n    auto g = cv::imread(\"zebra_256.tif\", 0);\n    // auto g = cv::imread(\"kreis.png\", 0);\n    // auto g = cv::imread(\"edge.png\", 0);\n    // auto g = cv::imread(\"kreis_gross.png\", 0);\n\n    boost::timer::auto_cpu_timer *t = new boost::timer::auto_cpu_timer();\n    auto grads = E::image_gradient(g, 1.0);\n    std::cout << \"image_gradient:\" << std::endl;\n    delete t;\n\n    t = new boost::timer::auto_cpu_timer();\n    auto mask = grads.threshold(50);\n    std::cout << \"grads.threshold:\" << std::endl;\n    delete t;\n\n    t = new boost::timer::auto_cpu_timer();\n    auto edges = E::compute_edge_points(grads, mask);\n    std::cout << \"compute_edge_points:\" << std::endl;\n    delete t;\n\n    t = new boost::timer::auto_cpu_timer();\n    auto links = E::chain_edge_points(edges, grads);\n    std::cout << \"chain_edge_points:\" << std::endl;\n    delete t;\n\n    t = new boost::timer::auto_cpu_timer();\n    auto chains = E::thresholds_with_hysteresis(edges, links, grads, 1, 0.1f);\n    std::cout << \"thresholds_with_hysteresis:\" << std::endl;\n    delete t;\n\n    // Now write out informational data to disk\n\n    // Raw edge magnitude image, normalized to [0..255]\n    {\n        auto mag = grads.magnitude();\n        double min, max;\n        cv::minMaxLoc(mag, &min, &max);\n        cv::Mat mag_u8;\n        mag.convertTo(mag_u8, CV_8U, 255 / (max - min), -min);\n        cv::imwrite(\"magn.tif\", mag_u8);\n    }\n\n    cv::imwrite(\"mask.tif\", mask);\n    write_edge_points(g, edges);\n    write_chains(g, chains);\n\n    return 0;\n}\n", "meta": {"hexsha": "803e7d26e909d880f2f714ae16a5775e001f190e", "size": 3188, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/devernaysubpix/devernaysubpix/main.cpp", "max_stars_repo_name": "mostlyuseful/devernaysubpix", "max_stars_repo_head_hexsha": "cfd0bfe3308e70a66d758988259bb2f176bea12b", "max_stars_repo_licenses": ["MIT"], "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/devernaysubpix/devernaysubpix/main.cpp", "max_issues_repo_name": "mostlyuseful/devernaysubpix", "max_issues_repo_head_hexsha": "cfd0bfe3308e70a66d758988259bb2f176bea12b", "max_issues_repo_licenses": ["MIT"], "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/devernaysubpix/devernaysubpix/main.cpp", "max_forks_repo_name": "mostlyuseful/devernaysubpix", "max_forks_repo_head_hexsha": "cfd0bfe3308e70a66d758988259bb2f176bea12b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-08-20T01:54:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-09T03:22:12.000Z", "avg_line_length": 31.5643564356, "max_line_length": 78, "alphanum_fraction": 0.5708908407, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.5137941808013871}}
{"text": "//=======================================================================\r\n// Copyright 2002 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \r\n//\r\n// This file is part of the Boost Graph Library\r\n//\r\n// You should have received a copy of the License Agreement for the\r\n// Boost Graph Library along with the software; see the file LICENSE.\r\n// If not, contact Office of Research, Indiana University,\r\n// Bloomington, IN 47405.\r\n//\r\n// Permission to modify the code and to distribute the code is\r\n// granted, provided the text of this NOTICE is retained, a notice if\r\n// the code was modified is included with the above COPYRIGHT NOTICE\r\n// and with the COPYRIGHT NOTICE in the LICENSE file, and that the\r\n// LICENSE file is distributed with the modified code.\r\n//\r\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\r\n// By way of example, but not limitation, Licensor MAKES NO\r\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\r\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\r\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\r\n// OR OTHER RIGHTS.\r\n//=======================================================================\r\n\r\n#include <string>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/undirected_dfs.hpp>\r\n#include <boost/cstdlib.hpp>\r\n\r\n/*\r\n  Example graph from Tarjei Knapstad.\r\n\r\n                   H15\r\n                   |\r\n          H8       C2\r\n            \\     /  \\\r\n          H9-C0-C1    C3-O7-H14\r\n            /   |     |\r\n          H10   C6    C4\r\n               /  \\  /  \\\r\n              H11  C5    H13\r\n                   |\r\n                   H12\r\n*/\r\n\r\nstd::string name[] = { \"C0\", \"C1\", \"C2\", \"C3\", \"C4\", \"C5\", \"C6\", \"O7\",\r\n                       \"H8\", \"H9\", \"H10\", \"H11\", \"H12\", \"H13\", \"H14\", \"H15\"};\r\n\r\n\r\nstruct detect_loops : public boost::dfs_visitor<>\r\n{\r\n  template <class Edge, class Graph>\r\n  void back_edge(Edge e, const Graph& g) {\r\n    std::cout << name[source(e, g)]\r\n              << \" -- \"\r\n              << name[target(e, g)] << \"\\n\";\r\n  }\r\n};\r\n\r\nint main(int, char*[])\r\n{\r\n  using namespace boost;\r\n  typedef adjacency_list< vecS, vecS, undirectedS,\r\n    no_property,\r\n    property<edge_color_t, default_color_type> > graph_t;\r\n  typedef graph_traits<graph_t>::vertex_descriptor vertex_t;\r\n  \r\n  const std::size_t N = sizeof(name)/sizeof(std::string);\r\n  graph_t g(N);\r\n  \r\n  add_edge(0, 1, g);\r\n  add_edge(0, 8, g);\r\n  add_edge(0, 9, g);\r\n  add_edge(0, 10, g);\r\n  add_edge(1, 2, g);\r\n  add_edge(1, 6, g);\r\n  add_edge(2, 15, g);\r\n  add_edge(2, 3, g);\r\n  add_edge(3, 7, g);\r\n  add_edge(3, 4, g);\r\n  add_edge(4, 13, g);\r\n  add_edge(4, 5, g);\r\n  add_edge(5, 12, g);\r\n  add_edge(5, 6, g);\r\n  add_edge(6, 11, g);\r\n  add_edge(7, 14, g);\r\n  \r\n  std::cout << \"back edges:\\n\";\r\n  detect_loops vis;\r\n  undirected_dfs(g, root_vertex(vertex_t(0)).visitor(vis)\r\n                 .edge_color_map(get(edge_color, g)));\r\n  std::cout << std::endl;\r\n  \r\n  return boost::exit_success;\r\n}\r\n", "meta": {"hexsha": "57625210287a52e3825beedec1dc74db0be8f80c", "size": 3020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/graph/example/undirected_dfs.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/graph/example/undirected_dfs.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/libs/graph/example/undirected_dfs.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4583333333, "max_line_length": 78, "alphanum_fraction": 0.5642384106, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5137941683054555}}
{"text": "/*!\n * @file\n * Forward declares the @ref Group typeclass.\n *\n *\n * @copyright Louis Dionne 2014\n * Distributed under the Boost Software License, Version 1.0.\n *         (See accompanying file LICENSE.md or copy at\n *             http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_MPL11_FWD_GROUP_HPP\n#define BOOST_MPL11_FWD_GROUP_HPP\n\n#include <boost/mpl11/fwd/bool.hpp>\n\n\nnamespace boost { namespace mpl11 {\n    /*!\n     * @ingroup typeclasses\n     * @defgroup Group Group\n     *\n     * `Monoid` where all objects have an inverse w.r.t. the binary operation.\n     *\n     * Instances of `Group` must satisfy the following laws:\n     *\n        @code\n            plus x (negate x) == zero\n            plus (negate x) x == zero\n        @endcode\n     *\n     * The method names refer to the group of numbers under addition.\n     *\n     *\n     * ### Methods\n     * `minus` and `negate`\n     *\n     * ### Minimal complete definition\n     * Either `minus` or `negate`.\n     *\n     * @{\n     */\n    template <typename Left, typename Right = Left, typename = true_>\n    struct Group;\n\n    //! Equivalent to `plus<x, negate<y>>`.\n    template <typename x, typename y>\n    struct minus;\n\n    //! Returns the inverse of `x`.\n    template <typename x>\n    struct negate;\n    //! @}\n}} // end namespace boost::mpl11\n\n#endif // !BOOST_MPL11_FWD_GROUP_HPP\n", "meta": {"hexsha": "52beb0e15483c741bef5c95dfe423fd0773c6ddd", "size": 1346, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/mpl11/fwd/group.hpp", "max_stars_repo_name": "ldionne/mpl11", "max_stars_repo_head_hexsha": "927d4339edc0c0cc41fb65ced2bf19d26bcd4a08", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T03:19:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T06:44:12.000Z", "max_issues_repo_path": "include/boost/mpl11/fwd/group.hpp", "max_issues_repo_name": "rbock/mpl11", "max_issues_repo_head_hexsha": "7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-27T22:37:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-06T17:42:07.000Z", "max_forks_repo_path": "include/boost/mpl11/fwd/group.hpp", "max_forks_repo_name": "rbock/mpl11", "max_forks_repo_head_hexsha": "7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T00:18:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T03:00:49.000Z", "avg_line_length": 23.6140350877, "max_line_length": 78, "alphanum_fraction": 0.6010401189, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645725, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5137726335528251}}
{"text": "/*\n * GridMapMathTest.cpp\n *\n *  Created on: Feb 10, 2014\n *      Author: P\u00e9ter Fankhauser\n *\t Institute: ETH Zurich, ANYbotics\n */\n\n#include \"grid_map_core/GridMapMath.hpp\"\n\n// Eigen\n#include <Eigen/Core>\n\n// gtest\n#include <gtest/gtest.h>\n\n// Limits\n#include <cfloat>\n\n// Vector\n#include <vector>\n\nusing namespace std;\nusing namespace grid_map;\n\nTEST(PositionFromIndex, Simple)\n{\n  Length mapLength(3.0, 2.0);\n  Position mapPosition(-1.0, 2.0);\n  double resolution = 1.0;\n  Size bufferSize(3, 2);\n  Position position;\n\n  EXPECT_TRUE(getPositionFromIndex(position, Index(0, 0), mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_DOUBLE_EQ(1.0 + mapPosition.x(), position.x());\n  EXPECT_DOUBLE_EQ(0.5 + mapPosition.y(), position.y());\n\n  EXPECT_TRUE(getPositionFromIndex(position, Index(1, 0), mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_DOUBLE_EQ(0.0 + mapPosition.x(), position.x());\n  EXPECT_DOUBLE_EQ(0.5 + mapPosition.y(), position.y());\n\n  EXPECT_TRUE(getPositionFromIndex(position, Index(1, 1), mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_DOUBLE_EQ(0.0 + mapPosition.x(), position.x());\n  EXPECT_DOUBLE_EQ(-0.5 + mapPosition.y(), position.y());\n\n  EXPECT_TRUE(getPositionFromIndex(position, Index(2, 1), mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_DOUBLE_EQ(-1.0 + mapPosition.x(), position.x());\n  EXPECT_DOUBLE_EQ(-0.5 + mapPosition.y(), position.y());\n\n  EXPECT_FALSE(getPositionFromIndex(position, Index(3, 1), mapLength, mapPosition, resolution, bufferSize));\n}\n\nTEST(PositionFromIndex, CircularBuffer)\n{\n  Length mapLength(0.5, 0.4);\n  Position mapPosition(-0.1, 13.4);\n  double resolution = 0.1;\n  Size bufferSize(5, 4);\n  Index bufferStartIndex(3, 1);\n  Position position;\n\n  EXPECT_TRUE(getPositionFromIndex(position, Index(3, 1), mapLength, mapPosition, resolution, bufferSize, bufferStartIndex));\n  EXPECT_DOUBLE_EQ(0.2 + mapPosition.x(), position.x());\n  EXPECT_DOUBLE_EQ(0.15 + mapPosition.y(), position.y());\n\n  EXPECT_TRUE(getPositionFromIndex(position, Index(4, 2), mapLength, mapPosition, resolution, bufferSize, bufferStartIndex));\n  EXPECT_DOUBLE_EQ(0.1 + mapPosition.x(), position.x());\n  EXPECT_DOUBLE_EQ(0.05 + mapPosition.y(), position.y());\n\n  EXPECT_TRUE(getPositionFromIndex(position, Index(2, 0), mapLength, mapPosition, resolution, bufferSize, bufferStartIndex));\n  EXPECT_DOUBLE_EQ(-0.2 + mapPosition.x(), position.x());\n  EXPECT_DOUBLE_EQ(-0.15 + mapPosition.y(), position.y());\n\n  EXPECT_TRUE(getPositionFromIndex(position, Index(0, 0), mapLength, mapPosition, resolution, bufferSize, bufferStartIndex));\n  EXPECT_DOUBLE_EQ(0.0 + mapPosition.x(), position.x());\n  EXPECT_DOUBLE_EQ(-0.15 + mapPosition.y(), position.y());\n\n  EXPECT_TRUE(getPositionFromIndex(position, Index(4, 3), mapLength, mapPosition, resolution, bufferSize, bufferStartIndex));\n  EXPECT_DOUBLE_EQ(0.1 + mapPosition.x(), position.x());\n  EXPECT_DOUBLE_EQ(-0.05 + mapPosition.y(), position.y());\n\n  EXPECT_FALSE(getPositionFromIndex(position, Index(5, 3), mapLength, mapPosition, resolution, bufferSize, bufferStartIndex));\n}\n\nTEST(IndexFromPosition, Simple)\n{\n  Length mapLength(3.0, 2.0);\n  Position mapPosition(-12.4, -7.1);\n  double resolution = 1.0;\n  Index bufferSize(3, 2);\n  Index index;\n\n  EXPECT_TRUE(getIndexFromPosition(index, Position(1.0, 0.5) + mapPosition, mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_EQ(0, index(0));\n  EXPECT_EQ(0, index(1));\n\n  EXPECT_TRUE(getIndexFromPosition(index, Position(-1.0, -0.5) + mapPosition, mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_EQ(2, index(0));\n  EXPECT_EQ(1, index(1));\n\n  EXPECT_TRUE(getIndexFromPosition(index, Position(0.6, 0.1) + mapPosition, mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_EQ(0, index(0));\n  EXPECT_EQ(0, index(1));\n\n  EXPECT_TRUE(getIndexFromPosition(index, Position(0.4, -0.1) + mapPosition, mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_EQ(1, index(0));\n  EXPECT_EQ(1, index(1));\n\n  EXPECT_TRUE(getIndexFromPosition(index, Position(0.4, 0.1) + mapPosition, mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_EQ(1, index(0));\n  EXPECT_EQ(0, index(1));\n\n  EXPECT_FALSE(getIndexFromPosition(index, Position(4.0, 0.5) + mapPosition, mapLength, mapPosition, resolution, bufferSize));\n}\n\nTEST(IndexFromPosition, EdgeCases)\n{\n  Length mapLength(3.0, 2.0);\n  Position mapPosition(0.0, 0.0);\n  double resolution = 1.0;\n  Size bufferSize(3, 2);\n  Index index;\n\n  EXPECT_TRUE(getIndexFromPosition(index, Position(0.0, DBL_EPSILON), mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_EQ(1, index(0));\n  EXPECT_EQ(0, index(1));\n\n  EXPECT_TRUE(getIndexFromPosition(index, Position(0.5 - DBL_EPSILON, -DBL_EPSILON), mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_EQ(1, index(0));\n  EXPECT_EQ(1, index(1));\n\n  EXPECT_TRUE(getIndexFromPosition(index, Position(-0.5 - DBL_EPSILON, -DBL_EPSILON), mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_EQ(2, index(0));\n  EXPECT_EQ(1, index(1));\n\n  EXPECT_FALSE(getIndexFromPosition(index, Position(-1.5, 1.0), mapLength, mapPosition, resolution, bufferSize));\n}\n\nTEST(IndexFromPosition, CircularBuffer)\n{\n  Length mapLength(0.5, 0.4);\n  Position mapPosition(0.4, -0.9);\n  double resolution = 0.1;\n  Size bufferSize(5, 4);\n  Index bufferStartIndex(3, 1);\n  Index index;\n\n  EXPECT_TRUE(getIndexFromPosition(index, Position(0.2, 0.15) + mapPosition, mapLength, mapPosition, resolution, bufferSize, bufferStartIndex));\n  EXPECT_EQ(3, index(0));\n  EXPECT_EQ(1, index(1));\n\n  EXPECT_TRUE(getIndexFromPosition(index, Position(0.03, -0.17) + mapPosition, mapLength, mapPosition, resolution, bufferSize, bufferStartIndex));\n  EXPECT_EQ(0, index(0));\n  EXPECT_EQ(0, index(1));\n}\n\nTEST(checkIfPositionWithinMap, Inside)\n{\n  Length mapLength(50.0, 25.0);\n  Position mapPosition(11.4, 0.0);\n\n  EXPECT_TRUE(checkIfPositionWithinMap(Position(0.0, 0.0) + mapPosition, mapLength, mapPosition));\n  EXPECT_TRUE(checkIfPositionWithinMap(Position(5.0, 5.0) + mapPosition, mapLength, mapPosition));\n  EXPECT_TRUE(checkIfPositionWithinMap(Position(20.0, 10.0) + mapPosition, mapLength, mapPosition));\n  EXPECT_TRUE(checkIfPositionWithinMap(Position(20.0, -10.0) + mapPosition, mapLength, mapPosition));\n  EXPECT_TRUE(checkIfPositionWithinMap(Position(-20.0, 10.0) + mapPosition, mapLength, mapPosition));\n  EXPECT_TRUE(checkIfPositionWithinMap(Position(-20.0, -10.0) + mapPosition, mapLength, mapPosition));\n}\n\nTEST(checkIfPositionWithinMap, Outside)\n{\n  Length mapLength(10.0, 5.0);\n  Position mapPosition(-3.0, 145.2);\n\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(5.5, 0.0) + mapPosition, mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(-5.5, 0.0) + mapPosition, mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(-5.5, 3.0) + mapPosition, mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(-5.5, -3.0) + mapPosition, mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(3.0, 3.0) + mapPosition, mapLength, mapPosition));\n}\n\nTEST(checkIfPositionWithinMap, EdgeCases)\n{\n  Length mapLength(2.0, 3.0);\n  Position mapPosition(0.0, 0.0);\n\n  /*\n  *  \n  *  A (is inside)             B (is not inside)\n  *   +-----------------------+\n  *   |                       |\n  *   |                       |\n  *   |              X        |\n  *   |             ^         |\n  *   |             |         |\n  *   |             |         |\n  *   |       <-----+         |\n  *   |      Y                |\n  *   |                       |\n  *   |                       |\n  *   |                       |\n  *   +-----------------------+\n  *  C (is not inside)         D (is not inside)\n  *\n  * Resulting coordinates are:\n  *  A: (1.0, 1.5)\n  *  B: (1.0, -1.5)\n  *  C: (-1.0, 1.5)\n  *  D: (-1.0, -1.5)\n  *\n  */\n\n  // Noise around A.\n  EXPECT_TRUE(checkIfPositionWithinMap(Position(1.0, 1.5), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(1.0 + DBL_EPSILON, 1.5), mapLength, mapPosition));\n  EXPECT_TRUE(checkIfPositionWithinMap(Position(1.0 - DBL_EPSILON, 1.5), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(1.0, 1.5 + DBL_EPSILON), mapLength, mapPosition));\n  EXPECT_TRUE(checkIfPositionWithinMap(Position(1.0, 1.5 - DBL_EPSILON), mapLength, mapPosition));\n\n  // Noise around B.\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(1.0, -1.5), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(1.0 + DBL_EPSILON, - 1.5), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(1.0 - DBL_EPSILON, - 1.5), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(1.0, - 1.5 + DBL_EPSILON), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(1.0, - 1.5 - DBL_EPSILON), mapLength, mapPosition));\n  \n  // Noise around C.\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(-1.0, 1.5), mapLength, mapPosition));\n  EXPECT_TRUE(checkIfPositionWithinMap(Position(-1.0 + DBL_EPSILON, 1.5), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(-1.0 - DBL_EPSILON, 1.5), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(-1.0, 1.5 + DBL_EPSILON), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(-1.0, 1.5 - DBL_EPSILON), mapLength, mapPosition));\n\n  // Noise around D.\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(-1.0, -1.5), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(-1.0 + DBL_EPSILON, -1.5), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(-1.0 - DBL_EPSILON, -1.5), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(-1.0, -1.5 + DBL_EPSILON), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(-1.0, -1.5 - DBL_EPSILON), mapLength, mapPosition));\n\n  // Extra tests.\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(-1.0, 1.5), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(1.0 + DBL_EPSILON, 1.0), mapLength, mapPosition));\n  EXPECT_TRUE(checkIfPositionWithinMap(Position((2.0 + DBL_EPSILON) / 2.0, 1.0), mapLength, mapPosition));\n  EXPECT_FALSE(checkIfPositionWithinMap(Position(0.5, -1.5 - (2.0 * DBL_EPSILON)), mapLength, mapPosition));\n  EXPECT_TRUE(checkIfPositionWithinMap(Position(-0.5, (3.0 + DBL_EPSILON) / 2.0), mapLength, mapPosition));\n}\n\nTEST(getIndexShiftFromPositionShift, All)\n{\n  double resolution = 1.0;\n  Index indexShift;\n\n  EXPECT_TRUE(getIndexShiftFromPositionShift(indexShift, Vector(0.0, 0.0), resolution));\n  EXPECT_EQ(0, indexShift(0));\n  EXPECT_EQ(0, indexShift(1));\n\n  EXPECT_TRUE(getIndexShiftFromPositionShift(indexShift, Vector(0.35, -0.45), resolution));\n  EXPECT_EQ(0, indexShift(0));\n  EXPECT_EQ(0, indexShift(1));\n\n  EXPECT_TRUE(getIndexShiftFromPositionShift(indexShift, Vector(0.55, -0.45), resolution));\n  EXPECT_EQ(-1, indexShift(0));\n  EXPECT_EQ(0, indexShift(1));\n\n  EXPECT_TRUE(getIndexShiftFromPositionShift(indexShift, Vector(-1.3, -2.65), resolution));\n  EXPECT_EQ(1, indexShift(0));\n  EXPECT_EQ(3, indexShift(1));\n\n  EXPECT_TRUE(getIndexShiftFromPositionShift(indexShift, Vector(-0.4, 0.09), 0.2));\n  EXPECT_EQ(2, indexShift(0));\n  EXPECT_EQ(0, indexShift(1));\n}\n\nTEST(getPositionShiftFromIndexShift, All)\n{\n  double resolution = 0.3;\n  Vector positionShift;\n\n  EXPECT_TRUE(getPositionShiftFromIndexShift(positionShift, Index(0, 0), resolution));\n  EXPECT_DOUBLE_EQ(0.0, positionShift.x());\n  EXPECT_DOUBLE_EQ(0.0, positionShift.y());\n\n  EXPECT_TRUE(getPositionShiftFromIndexShift(positionShift, Index(1, -1), resolution));\n  EXPECT_DOUBLE_EQ(-0.3, positionShift.x());\n  EXPECT_DOUBLE_EQ(0.3, positionShift.y());\n\n  EXPECT_TRUE(getPositionShiftFromIndexShift(positionShift, Index(2, 1), resolution));\n  EXPECT_DOUBLE_EQ(-0.6, positionShift.x());\n  EXPECT_DOUBLE_EQ(-0.3, positionShift.y());\n}\n\nTEST(checkIfIndexInRange, All)\n{\n  Size bufferSize(10, 15);\n  EXPECT_TRUE(checkIfIndexInRange(Index(0, 0), bufferSize));\n  EXPECT_TRUE(checkIfIndexInRange(Index(9, 14), bufferSize));\n  EXPECT_FALSE(checkIfIndexInRange(Index(10, 5), bufferSize));\n  EXPECT_FALSE(checkIfIndexInRange(Index(5, 300), bufferSize));\n  EXPECT_FALSE(checkIfIndexInRange(Index(-1, 0), bufferSize));\n  EXPECT_FALSE(checkIfIndexInRange(Index(0, -300), bufferSize));\n}\n\nTEST(boundIndexToRange, All)\n{\n  int index;\n  int bufferSize = 10;\n\n  index = 0;\n  boundIndexToRange(index, bufferSize);\n  EXPECT_EQ(0, index);\n\n  index = 1;\n  boundIndexToRange(index, bufferSize);\n  EXPECT_EQ(1, index);\n\n  index = -1;\n  boundIndexToRange(index, bufferSize);\n  EXPECT_EQ(0, index);\n\n  index = 9;\n  boundIndexToRange(index, bufferSize);\n  EXPECT_EQ(9, index);\n\n  index = 10;\n  boundIndexToRange(index, bufferSize);\n  EXPECT_EQ(9, index);\n\n  index = 35;\n  boundIndexToRange(index, bufferSize);\n  EXPECT_EQ(9, index);\n\n  index = -19;\n  boundIndexToRange(index, bufferSize);\n  EXPECT_EQ(0, index);\n}\n\nTEST(wrapIndexToRange, All)\n{\n  int index;\n  int bufferSize = 10;\n\n  index = 0;\n  wrapIndexToRange(index, bufferSize);\n  EXPECT_EQ(0, index);\n\n  index = 1;\n  wrapIndexToRange(index, bufferSize);\n  EXPECT_EQ(1, index);\n\n  index = -1;\n  wrapIndexToRange(index, bufferSize);\n  EXPECT_EQ(9, index);\n\n  index = 9;\n  wrapIndexToRange(index, bufferSize);\n  EXPECT_EQ(9, index);\n\n  index = 10;\n  wrapIndexToRange(index, bufferSize);\n  EXPECT_EQ(0, index);\n\n  index = 11;\n  wrapIndexToRange(index, bufferSize);\n  EXPECT_EQ(1, index);\n\n  index = 35;\n  wrapIndexToRange(index, bufferSize);\n  EXPECT_EQ(5, index);\n\n  index = -9;\n  wrapIndexToRange(index, bufferSize);\n  EXPECT_EQ(1, index);\n\n  index = -19;\n  wrapIndexToRange(index, bufferSize);\n  EXPECT_EQ(1, index);\n}\n\nTEST(boundPositionToRange, Simple)\n{\n  double epsilon = 11.0 * numeric_limits<double>::epsilon();\n\n  Length mapLength(30.0, 10.0);\n  Position mapPosition(0.0, 0.0);\n  Position position;\n\n  position << 0.0, 0.0;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_DOUBLE_EQ(0.0, position.x());\n  EXPECT_DOUBLE_EQ(0.0, position.y());\n\n  position << 15.0, 5.0;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_NEAR(15.0, position.x(), 15.0 * epsilon);\n  EXPECT_GE(15.0, position.x());\n  EXPECT_NEAR(5.0, position.y(), 5.0 * epsilon);\n  EXPECT_GE(5.0, position.y());\n\n  position << -15.0, -5.0;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_NEAR(-15.0, position.x(), 15.0 * epsilon);\n  EXPECT_LE(-15.0, position.x());\n  EXPECT_NEAR(-5.0, position.y(), 5.0 * epsilon);\n  EXPECT_LE(-5.0, position.y());\n\n  position << 16.0, 6.0;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_NEAR(15.0, position.x(), 16.0 * epsilon);\n  EXPECT_GE(15.0, position.x());\n  EXPECT_NEAR(5.0, position.y(), 6.0 * epsilon);\n  EXPECT_GE(5.0, position.y());\n\n  position << -16.0, -6.0;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_NEAR(-15.0, position.x(), 16.0 * epsilon);\n  EXPECT_LE(-15.0, position.x());\n  EXPECT_NEAR(-5.0, position.y(), 6.0 * epsilon);\n  EXPECT_LE(-5.0, position.y());\n\n  position << 1e6, 1e6;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_NEAR(15.0, position.x(), 1e6 * epsilon);\n  EXPECT_GE(15.0, position.x());\n  EXPECT_NEAR(5.0, position.y(), 1e6 * epsilon);\n  EXPECT_GE(5.0, position.y());\n\n  position << -1e6, -1e6;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_NEAR(-15.0, position.x(), 1e6 * epsilon);\n  EXPECT_LE(-15.0, position.x());\n  EXPECT_NEAR(-5.0, position.y(), 1e6 * epsilon);\n  EXPECT_LE(-5.0, position.y());\n}\n\nTEST(boundPositionToRange, Position)\n{\n  double epsilon = 11.0 * numeric_limits<double>::epsilon();\n\n  Length mapLength(30.0, 10.0);\n  Position mapPosition(1.0, 2.0);\n  Position position;\n\n  position << 0.0, 0.0;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_DOUBLE_EQ(0.0, position.x());\n  EXPECT_DOUBLE_EQ(0.0, position.y());\n\n  position << 16.0, 7.0;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_NEAR(16.0, position.x(), 16.0 * epsilon);\n  EXPECT_GE(16.0, position.x());\n  EXPECT_NEAR(7.0, position.y(), 7.0 * epsilon);\n  EXPECT_GE(7.0, position.y());\n\n  position << -14.0, -3.0;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_NEAR(-14.0, position.x(), 14.0 * epsilon);\n  EXPECT_LE(-14.0, position.x());\n  EXPECT_NEAR(-3.0, position.y(), 3.0 * epsilon);\n  EXPECT_LE(-3.0, position.y());\n\n  position << 17.0, 8.0;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_NEAR(16.0, position.x(), 17.0 * epsilon);\n  EXPECT_GE(16.0, position.x());\n  EXPECT_NEAR(7.0, position.y(), 8.0 * epsilon);\n  EXPECT_GE(7.0, position.y());\n\n  position << -15.0, -4.0;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_NEAR(-14.0, position.x(), 15.0 * epsilon);\n  EXPECT_LE(-14.0, position.x());\n  EXPECT_NEAR(-3.0, position.y(), 4.0 * epsilon);\n  EXPECT_LE(-3.0, position.y());\n\n  position << 1e6, 1e6;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_NEAR(16.0, position.x(), 1e6 * epsilon);\n  EXPECT_GE(16.0, position.x());\n  EXPECT_NEAR(7.0, position.y(), 1e6 * epsilon);\n  EXPECT_GE(7.0, position.y());\n\n  position << -1e6, -1e6;\n  boundPositionToRange(position, mapLength, mapPosition);\n  EXPECT_NEAR(-14.0, position.x(), 1e6 * epsilon);\n  EXPECT_LE(-14.0, position.x());\n  EXPECT_NEAR(-3.0, position.y(), 1e6 * epsilon);\n  EXPECT_LE(-3.0, position.y());\n}\n\nTEST(getSubmapInformation, Simple)\n{\n  // Map\n  Length mapLength(5.0, 4.0);\n  Position mapPosition(0.0, 0.0);\n  double resolution = 1.0;\n  Size bufferSize(5, 4);\n\n  // Requested submap\n  Position requestedSubmapPosition;\n  Position requestedSubmapLength;\n\n  // The returned submap indeces\n  Index submapTopLeftIndex;\n  Index submapSize;\n  Position submapPosition;\n  Length submapLength;\n  Index requestedIndexInSubmap;\n\n  requestedSubmapPosition << 0.0, 0.5;\n  requestedSubmapLength << 0.9, 2.9;\n  EXPECT_TRUE(getSubmapInformation(submapTopLeftIndex, submapSize, submapPosition, submapLength, requestedIndexInSubmap,\n                           requestedSubmapPosition, requestedSubmapLength, mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_EQ(2, submapTopLeftIndex(0));\n  EXPECT_EQ(0, submapTopLeftIndex(1));\n  EXPECT_EQ(1, submapSize(0));\n  EXPECT_EQ(3, submapSize(1));\n  EXPECT_DOUBLE_EQ(0.0, submapPosition.x());\n  EXPECT_DOUBLE_EQ(0.5, submapPosition.y());\n  EXPECT_DOUBLE_EQ(1.0, submapLength(0));\n  EXPECT_DOUBLE_EQ(3.0, submapLength(1));\n  EXPECT_EQ(0, requestedIndexInSubmap(0));\n  EXPECT_EQ(1, requestedIndexInSubmap(1));\n}\n\nTEST(getSubmapInformation, Zero)\n{\n  // Map\n  Length mapLength(5.0, 4.0);\n  Position mapPosition(0.0, 0.0);\n  double resolution = 1.0;\n  Size bufferSize(5, 4);\n\n  // Requested submap\n  Position requestedSubmapPosition;\n  Length requestedSubmapLength;\n\n  // The returned submap indeces\n  Index submapTopLeftIndex;\n  Index submapSize;\n  Position submapPosition;\n  Length submapLength;\n  Index requestedIndexInSubmap;\n\n  requestedSubmapPosition << -1.0, -0.5;\n  requestedSubmapLength << 0.0, 0.0;\n  EXPECT_TRUE(getSubmapInformation(submapTopLeftIndex, submapSize, submapPosition, submapLength, requestedIndexInSubmap,\n                                   requestedSubmapPosition, requestedSubmapLength,\n                                    mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_EQ(3, submapTopLeftIndex(0));\n  EXPECT_EQ(2, submapTopLeftIndex(1));\n  EXPECT_EQ(1, submapSize(0));\n  EXPECT_EQ(1, submapSize(1));\n  EXPECT_DOUBLE_EQ(requestedSubmapPosition.x(), submapPosition.x());\n  EXPECT_DOUBLE_EQ(requestedSubmapPosition.y(), submapPosition.y());\n  EXPECT_DOUBLE_EQ(resolution, submapLength(0));\n  EXPECT_DOUBLE_EQ(resolution, submapLength(1));\n  EXPECT_EQ(0, requestedIndexInSubmap(0));\n  EXPECT_EQ(0, requestedIndexInSubmap(1));\n}\n\nTEST(getSubmapInformation, ExceedingBoundaries)\n{\n  // Map\n  Length mapLength(5.0, 4.0);\n  Position mapPosition(0.0, 0.0);\n  double resolution = 1.0;\n  Size bufferSize(5, 4);\n\n  // Requested submap\n  Position requestedSubmapPosition;\n  Length requestedSubmapLength;\n\n  // The returned submap indeces\n  Index submapTopLeftIndex;\n  Size submapSize;\n  Position submapPosition;\n  Length submapLength;\n  Index requestedIndexInSubmap;\n\n  requestedSubmapPosition << 2.0, 1.5;\n  requestedSubmapLength << 2.9, 2.9;\n  EXPECT_TRUE(getSubmapInformation(submapTopLeftIndex, submapSize, submapPosition, submapLength, requestedIndexInSubmap,\n                                   requestedSubmapPosition, requestedSubmapLength,\n                                    mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_EQ(0, submapTopLeftIndex(0));\n  EXPECT_EQ(0, submapTopLeftIndex(1));\n  EXPECT_EQ(2, submapSize(0));\n  EXPECT_EQ(2, submapSize(1));\n  EXPECT_DOUBLE_EQ(1.5, submapPosition.x());\n  EXPECT_DOUBLE_EQ(1.0, submapPosition.y());\n  EXPECT_DOUBLE_EQ(2.0, submapLength(0));\n  EXPECT_DOUBLE_EQ(2.0, submapLength(1));\n  EXPECT_EQ(0, requestedIndexInSubmap(0));\n  EXPECT_EQ(0, requestedIndexInSubmap(1));\n\n  requestedSubmapPosition << 0.0, 0.0;\n  requestedSubmapLength << 1e6, 1e6;\n  EXPECT_TRUE(getSubmapInformation(submapTopLeftIndex, submapSize, submapPosition, submapLength, requestedIndexInSubmap,\n                                   requestedSubmapPosition, requestedSubmapLength,\n                                    mapLength, mapPosition, resolution, bufferSize));\n  EXPECT_EQ(0, submapTopLeftIndex(0));\n  EXPECT_EQ(0, submapTopLeftIndex(1));\n  EXPECT_EQ(bufferSize(0), submapSize(0));\n  EXPECT_EQ(bufferSize(1), submapSize(1));\n  EXPECT_DOUBLE_EQ(0.0, submapPosition.x());\n  EXPECT_DOUBLE_EQ(0.0, submapPosition.y());\n  EXPECT_DOUBLE_EQ(mapLength(0), submapLength(0));\n  EXPECT_DOUBLE_EQ(mapLength(1), submapLength(1));\n  EXPECT_EQ(2, requestedIndexInSubmap(0));\n  EXPECT_LE(1, requestedIndexInSubmap(1));\n  EXPECT_GE(2, requestedIndexInSubmap(1));\n}\n\nTEST(getSubmapInformation, CircularBuffer)\n{\n  // Map\n  Length mapLength(5.0, 4.0);\n  Position mapPosition(0.0, 0.0);\n  double resolution = 1.0;\n  Size bufferSize(5, 4);\n  Index bufferStartIndex(2, 1);\n\n  // Requested submap\n  Position requestedSubmapPosition;\n  Length requestedSubmapLength;\n\n  // The returned submap indeces\n  Index submapTopLeftIndex;\n  Size submapSize;\n  Position submapPosition;\n  Length submapLength;\n  Index requestedIndexInSubmap;\n\n  requestedSubmapPosition << 0.0, 0.5;\n  requestedSubmapLength << 0.9, 2.9;\n  EXPECT_TRUE(getSubmapInformation(submapTopLeftIndex, submapSize, submapPosition, submapLength, requestedIndexInSubmap,\n                                   requestedSubmapPosition, requestedSubmapLength,\n                                    mapLength, mapPosition, resolution, bufferSize, bufferStartIndex));\n  EXPECT_EQ(4, submapTopLeftIndex(0));\n  EXPECT_EQ(1, submapTopLeftIndex(1));\n  EXPECT_EQ(1, submapSize(0));\n  EXPECT_EQ(3, submapSize(1));\n  EXPECT_DOUBLE_EQ(0.0, submapPosition.x());\n  EXPECT_DOUBLE_EQ(0.5, submapPosition.y());\n  EXPECT_DOUBLE_EQ(1.0, submapLength(0));\n  EXPECT_DOUBLE_EQ(3.0, submapLength(1));\n  EXPECT_EQ(0, requestedIndexInSubmap(0));\n  EXPECT_EQ(1, requestedIndexInSubmap(1));\n\n  requestedSubmapPosition << 2.0, 1.5;\n  requestedSubmapLength << 2.9, 2.9;\n  EXPECT_TRUE(getSubmapInformation(submapTopLeftIndex, submapSize, submapPosition, submapLength, requestedIndexInSubmap,\n                                   requestedSubmapPosition, requestedSubmapLength,\n                                    mapLength, mapPosition, resolution, bufferSize, bufferStartIndex));\n  EXPECT_EQ(2, submapTopLeftIndex(0));\n  EXPECT_EQ(1, submapTopLeftIndex(1));\n  EXPECT_EQ(2, submapSize(0));\n  EXPECT_EQ(2, submapSize(1));\n  EXPECT_DOUBLE_EQ(1.5, submapPosition.x());\n  EXPECT_DOUBLE_EQ(1.0, submapPosition.y());\n  EXPECT_DOUBLE_EQ(2.0, submapLength(0));\n  EXPECT_DOUBLE_EQ(2.0, submapLength(1));\n  EXPECT_EQ(0, requestedIndexInSubmap(0));\n  EXPECT_EQ(0, requestedIndexInSubmap(1));\n\n  requestedSubmapPosition << 0.0, 0.0;\n  requestedSubmapLength << 1e6, 1e6;\n  EXPECT_TRUE(getSubmapInformation(submapTopLeftIndex, submapSize, submapPosition, submapLength, requestedIndexInSubmap,\n                                   requestedSubmapPosition, requestedSubmapLength,\n                                    mapLength, mapPosition, resolution, bufferSize, bufferStartIndex));\n  EXPECT_EQ(2, submapTopLeftIndex(0));\n  EXPECT_EQ(1, submapTopLeftIndex(1));\n  EXPECT_EQ(bufferSize(0), submapSize(0));\n  EXPECT_EQ(bufferSize(1), submapSize(1));\n  EXPECT_DOUBLE_EQ(0.0, submapPosition.x());\n  EXPECT_DOUBLE_EQ(0.0, submapPosition.y());\n  EXPECT_DOUBLE_EQ(mapLength(0), submapLength(0));\n  EXPECT_DOUBLE_EQ(mapLength(1), submapLength(1));\n  EXPECT_EQ(2, requestedIndexInSubmap(0));\n  EXPECT_LE(1, requestedIndexInSubmap(1));\n  EXPECT_GE(2, requestedIndexInSubmap(1));\n}\n\nTEST(getSubmapInformation, Debug1)\n{\n  // Map\n  Length mapLength(4.98, 4.98);\n  Position mapPosition(-4.98, -5.76);\n  double resolution = 0.06;\n  Size bufferSize(83, 83);\n  Index bufferStartIndex(0, 13);\n\n  // Requested submap\n  Position requestedSubmapPosition(-7.44, -3.42);\n  Length requestedSubmapLength(0.12, 0.12);\n\n  // The returned submap indeces\n  Index submapTopLeftIndex;\n  Size submapSize;\n  Position submapPosition;\n  Length submapLength;\n  Index requestedIndexInSubmap;\n\n  EXPECT_TRUE(getSubmapInformation(submapTopLeftIndex, submapSize, submapPosition, submapLength, requestedIndexInSubmap,\n                                   requestedSubmapPosition, requestedSubmapLength,\n                                    mapLength, mapPosition, resolution, bufferSize, bufferStartIndex));\n  EXPECT_EQ(2, submapSize(0));\n  EXPECT_EQ(3, submapSize(1));\n  EXPECT_DOUBLE_EQ(0.12, submapLength(0));\n  EXPECT_DOUBLE_EQ(0.18, submapLength(1));\n}\n\nTEST(getSubmapInformation, Debug2)\n{\n  // Map\n  Length mapLength(4.98, 4.98);\n  Position mapPosition(2.46, -25.26);\n  double resolution = 0.06;\n  Size bufferSize(83, 83);\n  Index bufferStartIndex(42, 6);\n\n  // Requested submap\n  Position requestedSubmapPosition(0.24, -26.82);\n  Length requestedSubmapLength(0.624614, 0.462276);\n\n  // The returned submap indeces\n  Index submapTopLeftIndex;\n  Size submapSize;\n  Position submapPosition;\n  Length submapLength;\n  Index requestedIndexInSubmap;\n\n  EXPECT_TRUE(getSubmapInformation(submapTopLeftIndex, submapSize, submapPosition, submapLength, requestedIndexInSubmap,\n                                   requestedSubmapPosition, requestedSubmapLength,\n                                    mapLength, mapPosition, resolution, bufferSize, bufferStartIndex));\n  EXPECT_LT(0, submapSize(0));\n  EXPECT_LT(0, submapSize(1));\n  EXPECT_LT(0.0, submapLength(0));\n  EXPECT_LT(0.0, submapLength(1));\n}\n\nTEST(getBufferRegionsForSubmap, Trivial)\n{\n  Size bufferSize(5, 4);\n  Index submapIndex(0, 0);\n  Size submapSize(0, 0);\n  std::vector<BufferRegion> regions;\n\n  EXPECT_TRUE(getBufferRegionsForSubmap(regions, submapIndex, submapSize, bufferSize));\n  EXPECT_EQ(1, regions.size());\n  EXPECT_EQ(BufferRegion::Quadrant::TopLeft, regions[0].getQuadrant());\n  EXPECT_EQ(0, regions[0].getStartIndex()[0]);\n  EXPECT_EQ(0, regions[0].getStartIndex()[1]);\n  EXPECT_EQ(0, regions[0].getSize()[0]);\n  EXPECT_EQ(0, regions[0].getSize()[1]);\n\n  submapSize << 0, 7;\n  EXPECT_FALSE(getBufferRegionsForSubmap(regions, submapIndex, submapSize, bufferSize));\n\n  submapSize << 6, 7;\n  EXPECT_FALSE(getBufferRegionsForSubmap(regions, submapIndex, submapSize, bufferSize));\n}\n\nTEST(getBufferRegionsForSubmap, Simple)\n{\n  Size bufferSize(5, 4);\n  Index submapIndex(1, 2);\n  Size submapSize(3, 2);\n  std::vector<BufferRegion> regions;\n\n  EXPECT_TRUE(getBufferRegionsForSubmap(regions, submapIndex, submapSize, bufferSize));\n  EXPECT_EQ(1, regions.size());\n  EXPECT_EQ(BufferRegion::Quadrant::TopLeft, regions[0].getQuadrant());\n  EXPECT_EQ(1, regions[0].getStartIndex()[0]);\n  EXPECT_EQ(2, regions[0].getStartIndex()[1]);\n  EXPECT_EQ(3, regions[0].getSize()[0]);\n  EXPECT_EQ(2, regions[0].getSize()[1]);\n}\n\nTEST(getBufferRegionsForSubmap, CircularBuffer)\n{\n  Size bufferSize(5, 4);\n  Index submapIndex;\n  Size submapSize;\n  Index bufferStartIndex(3, 1);\n  std::vector<BufferRegion> regions;\n\n  submapIndex << 3, 1;\n  submapSize << 2, 3;\n  EXPECT_TRUE(getBufferRegionsForSubmap(regions, submapIndex, submapSize, bufferSize, bufferStartIndex));\n  EXPECT_EQ(1, regions.size());\n  EXPECT_EQ(BufferRegion::Quadrant::TopLeft, regions[0].getQuadrant());\n  EXPECT_EQ(3, regions[0].getStartIndex()[0]);\n  EXPECT_EQ(1, regions[0].getStartIndex()[1]);\n  EXPECT_EQ(2, regions[0].getSize()[0]);\n  EXPECT_EQ(3, regions[0].getSize()[1]);\n\n  submapIndex << 4, 1;\n  submapSize << 2, 3;\n  EXPECT_TRUE(getBufferRegionsForSubmap(regions, submapIndex, submapSize, bufferSize, bufferStartIndex));\n  EXPECT_EQ(2, regions.size());\n  EXPECT_EQ(BufferRegion::Quadrant::TopLeft, regions[0].getQuadrant());\n  EXPECT_EQ(4, regions[0].getStartIndex()[0]);\n  EXPECT_EQ(1, regions[0].getStartIndex()[1]);\n  EXPECT_EQ(1, regions[0].getSize()[0]);\n  EXPECT_EQ(3, regions[0].getSize()[1]);\n  EXPECT_EQ(BufferRegion::Quadrant::BottomLeft, regions[1].getQuadrant());\n  EXPECT_EQ(0, regions[1].getStartIndex()[0]);\n  EXPECT_EQ(1, regions[1].getStartIndex()[1]);\n  EXPECT_EQ(1, regions[1].getSize()[0]);\n  EXPECT_EQ(3, regions[1].getSize()[1]);\n\n  submapIndex << 1, 0;\n  submapSize << 2, 1;\n  EXPECT_TRUE(getBufferRegionsForSubmap(regions, submapIndex, submapSize, bufferSize, bufferStartIndex));\n  EXPECT_EQ(1, regions.size());\n  EXPECT_EQ(BufferRegion::Quadrant::BottomRight, regions[0].getQuadrant());\n  EXPECT_EQ(1, regions[0].getStartIndex()[0]);\n  EXPECT_EQ(0, regions[0].getStartIndex()[1]);\n  EXPECT_EQ(2, regions[0].getSize()[0]);\n  EXPECT_EQ(1, regions[0].getSize()[1]);\n\n  submapIndex << 3, 1;\n  submapSize << 5, 4;\n  EXPECT_TRUE(getBufferRegionsForSubmap(regions, submapIndex, submapSize, bufferSize, bufferStartIndex));\\\n  EXPECT_EQ(4, regions.size());\n  EXPECT_EQ(BufferRegion::Quadrant::TopLeft, regions[0].getQuadrant());\n  EXPECT_EQ(3, regions[0].getStartIndex()[0]);\n  EXPECT_EQ(1, regions[0].getStartIndex()[1]);\n  EXPECT_EQ(2, regions[0].getSize()[0]);\n  EXPECT_EQ(3, regions[0].getSize()[1]);\n  EXPECT_EQ(BufferRegion::Quadrant::TopRight, regions[1].getQuadrant());\n  EXPECT_EQ(3, regions[1].getStartIndex()[0]);\n  EXPECT_EQ(0, regions[1].getStartIndex()[1]);\n  EXPECT_EQ(2, regions[1].getSize()[0]);\n  EXPECT_EQ(1, regions[1].getSize()[1]);\n  EXPECT_EQ(BufferRegion::Quadrant::BottomLeft, regions[2].getQuadrant());\n  EXPECT_EQ(0, regions[2].getStartIndex()[0]);\n  EXPECT_EQ(1, regions[2].getStartIndex()[1]);\n  EXPECT_EQ(3, regions[2].getSize()[0]);\n  EXPECT_EQ(3, regions[2].getSize()[1]);\n  EXPECT_EQ(BufferRegion::Quadrant::BottomRight, regions[3].getQuadrant());\n  EXPECT_EQ(0, regions[3].getStartIndex()[0]);\n  EXPECT_EQ(0, regions[3].getStartIndex()[1]);\n  EXPECT_EQ(3, regions[3].getSize()[0]);\n  EXPECT_EQ(1, regions[3].getSize()[1]);\n}\n\nTEST(checkIncrementIndex, Simple)\n{\n  Index index(0, 0);\n  Size bufferSize(4, 3);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize));\n  EXPECT_EQ(0, index[0]);\n  EXPECT_EQ(1, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize));\n  EXPECT_EQ(0, index[0]);\n  EXPECT_EQ(2, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize));\n  EXPECT_EQ(1, index[0]);\n  EXPECT_EQ(0, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize));\n  EXPECT_EQ(1, index[0]);\n  EXPECT_EQ(1, index[1]);\n\n  for (int i = 0; i < 6; i++) {\n    EXPECT_TRUE(incrementIndex(index, bufferSize));\n  }\n  EXPECT_EQ(3, index[0]);\n  EXPECT_EQ(1, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize));\n  EXPECT_EQ(3, index[0]);\n  EXPECT_EQ(2, index[1]);\n\n  EXPECT_FALSE(incrementIndex(index, bufferSize));\n  EXPECT_EQ(index[0], index[0]);\n  EXPECT_EQ(index[1], index[1]);\n}\n\nTEST(checkIncrementIndex, CircularBuffer)\n{\n  Size bufferSize(4, 3);\n  Index bufferStartIndex(2, 1);\n  Index index(bufferStartIndex);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize, bufferStartIndex));\n  EXPECT_EQ(2, index[0]);\n  EXPECT_EQ(2, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize, bufferStartIndex));\n  EXPECT_EQ(2, index[0]);\n  EXPECT_EQ(0, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize, bufferStartIndex));\n  EXPECT_EQ(3, index[0]);\n  EXPECT_EQ(1, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize, bufferStartIndex));\n  EXPECT_EQ(3, index[0]);\n  EXPECT_EQ(2, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize, bufferStartIndex));\n  EXPECT_EQ(3, index[0]);\n  EXPECT_EQ(0, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize, bufferStartIndex));\n  EXPECT_EQ(0, index[0]);\n  EXPECT_EQ(1, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize, bufferStartIndex));\n  EXPECT_EQ(0, index[0]);\n  EXPECT_EQ(2, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize, bufferStartIndex));\n  EXPECT_EQ(0, index[0]);\n  EXPECT_EQ(0, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize, bufferStartIndex));\n  EXPECT_EQ(1, index[0]);\n  EXPECT_EQ(1, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize, bufferStartIndex));\n  EXPECT_EQ(1, index[0]);\n  EXPECT_EQ(2, index[1]);\n\n  EXPECT_TRUE(incrementIndex(index, bufferSize, bufferStartIndex));\n  EXPECT_EQ(1, index[0]);\n  EXPECT_EQ(0, index[1]);\n\n  EXPECT_FALSE(incrementIndex(index, bufferSize, bufferStartIndex));\n  EXPECT_EQ(index[0], index[0]);\n  EXPECT_EQ(index[1], index[1]);\n}\n\nTEST(checkIncrementIndexForSubmap, Simple)\n{\n  Index submapIndex(0, 0);\n  Index index;\n  Index submapTopLeftIndex(3, 1);\n  Size submapBufferSize(2, 4);\n  Size bufferSize(8, 5);\n\n  EXPECT_TRUE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize));\n  EXPECT_EQ(0, submapIndex[0]);\n  EXPECT_EQ(1, submapIndex[1]);\n  EXPECT_EQ(3, index[0]);\n  EXPECT_EQ(2, index[1]);\n\n  EXPECT_TRUE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize));\n  EXPECT_EQ(0, submapIndex[0]);\n  EXPECT_EQ(2, submapIndex[1]);\n  EXPECT_EQ(3, index[0]);\n  EXPECT_EQ(3, index[1]);\n\n  EXPECT_TRUE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize));\n  EXPECT_EQ(0, submapIndex[0]);\n  EXPECT_EQ(3, submapIndex[1]);\n  EXPECT_EQ(3, index[0]);\n  EXPECT_EQ(4, index[1]);\n\n  EXPECT_TRUE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize));\n  EXPECT_EQ(1, submapIndex[0]);\n  EXPECT_EQ(0, submapIndex[1]);\n  EXPECT_EQ(4, index[0]);\n  EXPECT_EQ(1, index[1]);\n\n  submapIndex << 1, 2;\n  EXPECT_TRUE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize));\n  EXPECT_EQ(1, submapIndex[0]);\n  EXPECT_EQ(3, submapIndex[1]);\n  EXPECT_EQ(4, index[0]);\n  EXPECT_EQ(4, index[1]);\n\n  EXPECT_FALSE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize));\n\n  submapIndex << 2, 0;\n  EXPECT_FALSE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize));\n}\n\nTEST(checkIncrementIndexForSubmap, CircularBuffer)\n{\n  Index submapIndex(0, 0);\n  Index index;\n  Index submapTopLeftIndex(6, 3);\n  Size submapBufferSize(2, 4);\n  Size bufferSize(8, 5);\n  Index bufferStartIndex(3, 2);\n\n  EXPECT_TRUE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize, bufferStartIndex));\n  EXPECT_EQ(0, submapIndex[0]);\n  EXPECT_EQ(1, submapIndex[1]);\n  EXPECT_EQ(6, index[0]);\n  EXPECT_EQ(4, index[1]);\n\n  EXPECT_TRUE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize, bufferStartIndex));\n  EXPECT_EQ(0, submapIndex[0]);\n  EXPECT_EQ(2, submapIndex[1]);\n  EXPECT_EQ(6, index[0]);\n  EXPECT_EQ(0, index[1]);\n\n  EXPECT_TRUE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize, bufferStartIndex));\n  EXPECT_EQ(0, submapIndex[0]);\n  EXPECT_EQ(3, submapIndex[1]);\n  EXPECT_EQ(6, index[0]);\n  EXPECT_EQ(1, index[1]);\n\n  EXPECT_TRUE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize, bufferStartIndex));\n  EXPECT_EQ(1, submapIndex[0]);\n  EXPECT_EQ(0, submapIndex[1]);\n  EXPECT_EQ(7, index[0]);\n  EXPECT_EQ(3, index[1]);\n\n  submapIndex << 1, 2;\n  EXPECT_TRUE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize, bufferStartIndex));\n  EXPECT_EQ(1, submapIndex[0]);\n  EXPECT_EQ(3, submapIndex[1]);\n  EXPECT_EQ(7, index[0]);\n  EXPECT_EQ(1, index[1]);\n\n  EXPECT_FALSE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize, bufferStartIndex));\n\n  submapIndex << 2, 0;\n  EXPECT_FALSE(incrementIndexForSubmap(submapIndex, index, submapTopLeftIndex, submapBufferSize, bufferSize, bufferStartIndex));\n}\n\nTEST(getIndexFromLinearIndex, Simple)\n{\n  EXPECT_TRUE((Index(0, 0) == getIndexFromLinearIndex(0, Size(8, 5), false)).all());\n  EXPECT_TRUE((Index(1, 0) == getIndexFromLinearIndex(1, Size(8, 5), false)).all());\n  EXPECT_TRUE((Index(0, 1) == getIndexFromLinearIndex(1, Size(8, 5), true)).all());\n  EXPECT_TRUE((Index(2, 0) == getIndexFromLinearIndex(2, Size(8, 5), false)).all());\n  EXPECT_TRUE((Index(0, 1) == getIndexFromLinearIndex(8, Size(8, 5), false)).all());\n  EXPECT_TRUE((Index(7, 4) == getIndexFromLinearIndex(39, Size(8, 5), false)).all());\n}\n", "meta": {"hexsha": "a8c1886065650c75bf79c3f7bcedf193dfacd2a6", "size": 37209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grid_map_core/test/GridMapMathTest.cpp", "max_stars_repo_name": "fmrico/grid_map", "max_stars_repo_head_hexsha": "73ea27f5326ba920a5eeada6b2b4925d14abcb51", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1305.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T14:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:44:18.000Z", "max_issues_repo_path": "grid_map_core/test/GridMapMathTest.cpp", "max_issues_repo_name": "fmrico/grid_map", "max_issues_repo_head_hexsha": "73ea27f5326ba920a5eeada6b2b4925d14abcb51", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 174.0, "max_issues_repo_issues_event_min_datetime": "2018-08-06T21:41:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T04:45:09.000Z", "max_forks_repo_path": "grid_map_core/test/GridMapMathTest.cpp", "max_forks_repo_name": "fmrico/grid_map", "max_forks_repo_head_hexsha": "73ea27f5326ba920a5eeada6b2b4925d14abcb51", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 423.0, "max_forks_repo_forks_event_min_datetime": "2018-08-07T13:37:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:07:26.000Z", "avg_line_length": 35.7092130518, "max_line_length": 146, "alphanum_fraction": 0.7127307909, "num_tokens": 11132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5137726326098387}}
{"text": "// Implementation of Discrete Conformal Seamless Similarity Mapping\n// along the lines of\n// [Campen and Zorin 2017]: \"Similarity Maps and Field-Guided T-Splines: a Perfect Couple\"\n// [Campen and Zorin 2017]: \"On Discrete Conformal Seamless Similarity Maps\"\n//\n// Author: Marcel Campen\n//\n// Version 1.0\n// 21 July 2017\n\n\n#include <Eigen/Sparse>\n#include <set>\n#include <queue>\n#include <vector>\n#include <igl/Timer.h>\n\nclass Mesh {\npublic:\n  std::vector<int> n; // next halfedge of halfedge\n  std::vector<int> to; // to vertex of halfedge\n  std::vector<int> f; // face of halfedge\n  std::vector<int> h; // one halfedge of face\n  std::vector<int> out; // one outgoing halfedge of vertex\n\n  std::vector<double> l; // discrete metric (length per edge)\n\n  int n_halfedges() { return n.size(); }\n  int n_edges() { return n_halfedges()/2; }\n  int n_faces() { return h.size(); }\n  int n_vertices() { return out.size(); }\n\n  int e(int h) { return h/2; }\n  int opp(int h) { return (h%2 == 0) ? (h+1) : (h-1); }\n  int v0(int h) { return to[opp(h)]; }\n  int v1(int h) { return to[h]; }\n  int h0(int e) { return e*2; }\n  int h1(int e) { return e*2+1; }\n  double sign(int h) { return (h%2 == 0) ? 1.0 : -1.0; }\n  \n  virtual void init() {};\n\n  virtual bool flip_ccw(int _h)\n  {\n    int ha = _h;\n    int hb = opp(_h);\n    int f0 = f[ha];\n    int f1 = f[hb];\n    if(f0 == f1) return false;\n    int h2 = n[ha];\n    int h3 = n[h2];\n    int h4 = n[hb];\n    int h5 = n[h4];\n    out[to[hb]] = h4;\n    out[to[ha]] = h2;\n    f[h4] = f0;\n    f[h2] = f1;\n    h[f0] = h4;\n    h[f1] = h2;\n    to[ha] = to[h2];\n    to[hb] = to[h4];\n    n[h5] = h2;\n    n[h3] = h4;\n    n[h2] = hb;\n    n[h4] = ha;\n    n[ha] = h3;\n    n[hb] = h5;\n    return true;\n  }\n  \n  virtual void get_mesh(std::vector<int>& _n, // next halfedge of halfedge\n                        std::vector<int>& _to, // to vertex of halfedge\n                        std::vector<int>& _f, // face of halfedge\n                        std::vector<int>& _h, // one halfedge of face\n                        std::vector<int>& _out) // one outgoing halfedge of vertex\n  {\n    _n = n;\n    _to = to;\n    _f = f;\n    _h = h;\n    _out = out;\n  }\n  \n  template<typename T>\n  std::vector<T> interpolate(const std::vector<T>& u)\n  {\n    return u;\n  }\n  \n  bool is_complex()\n  {\n    int nh = n_halfedges();\n    for(int i = 0; i < nh; i++)\n    {\n      if(to[i] == to[opp(i)]) return true; //contains loop edge\n    }\n    int nv = n_vertices();\n    for(int i = 0; i < nv; i++)\n    {\n      std::set<int> onering;\n      int h = out[i];\n      if(h < 0) continue;\n      int k = h;\n      do {\n        int v = to[k];\n        if(onering.find(v) != onering.end()) return true; //contains multi-edges\n        onering.insert(v);\n        k = n[opp(k)];\n      } while(k != h);\n    }\n    return false;\n  }\n};\n\n\nclass ConformalSeamlessSimilarityMapping {\npublic:\n\n  Mesh& m;\n  \n  std::vector<double> Theta_hat; //target cone angles per vertex\n  std::vector<double> kappa_hat; //target holonomy angles per gamma loop\n  std::vector< std::vector<int> > gamma; //directed dual loops, represented by halfedges (the ones adjacent to the earlier triangles in the dual loop)\n\n  const double cot_infty = 1e10;\n\n  int n_s;\n  int n_e;\n  int n_h;\n  int n_f;\n  int n_v;\n\n  std::vector<double> xi;\n  std::vector<double> delta_xi;\n  std::vector<double> cot_alpha;\n  std::vector<double> alpha;\n\n  Eigen::SparseMatrix<double> A;\n  Eigen::VectorXd b;\n\n  std::string log_dir;\n  std::string name;\n  double eps = 1e-12;\n\n  ConformalSeamlessSimilarityMapping(Mesh& _m, const std::vector<double>& _Theta_hat, const std::vector<double>& _kappa_hat, std::vector< std::vector<int> >& _gamma, std::string _log_dir=\"\", std::string _name=\"\", double _eps=1e-12) : m(_m), Theta_hat(_Theta_hat), kappa_hat(_kappa_hat), gamma(_gamma), log_dir(_log_dir), name(_name), eps(_eps)\n  {\n    n_s = gamma.size();\n    n_e = m.n_edges();\n    n_h = m.n_halfedges();\n    n_f = m.n_faces();\n    n_v = m.n_vertices();\n\n    xi.resize(n_h, 0.0);\n    delta_xi.resize(n_h, 0.0);\n    cot_alpha.resize(n_h);\n    alpha.resize(n_h);\n  }\n  \n  void log(const char* c)\n  {\n    std::cout << c << std::endl;\n  }\n  \n  void compute_angles() // compute alpha and cot_alpha from scaled edge lengths\n  {\n    #pragma omp parallel for\n    for(int f = 0; f < n_f; f++)\n    {\n      int hi = m.h[f];\n      int hj = m.n[hi];\n      int hk = m.n[hj];\n      // (following \"On Discrete Conformal Seamless Similarity Maps\")\n      double li = m.l[m.e(hi)] * std::exp(1.0/6.0*(xi[hk]-xi[hj]));\n      double lj = m.l[m.e(hj)] * std::exp(1.0/6.0*(xi[hi]-xi[hk]));\n      double lk = m.l[m.e(hk)] * std::exp(1.0/6.0*(xi[hj]-xi[hi]));\n      // (following \"A Cotangent Laplacian for Images as Surfaces\")\n      double s = (li+lj+lk)/2.0;\n      double Aijk4 = 4.0*std::sqrt(std::max(0.0, s*(s-li)*(s-lj)*(s-lk)));\n      double Ijk = (-li*li+lj*lj+lk*lk);\n      double iJk = (li*li-lj*lj+lk*lk);\n      double ijK = (li*li+lj*lj-lk*lk);\n      cot_alpha[hi] = Aijk4 == 0.0 ? copysign(cot_infty,Ijk) : (Ijk/Aijk4);\n      cot_alpha[hj] = Aijk4 == 0.0 ? copysign(cot_infty,iJk) : (iJk/Aijk4);\n      cot_alpha[hk] = Aijk4 == 0.0 ? copysign(cot_infty,ijK) : (ijK/Aijk4);\n      \n      alpha[hi] = std::acos(std::min(1.0, std::max(-1.0, Ijk/(2.0*lj*lk))));\n      alpha[hj] = std::acos(std::min(1.0, std::max(-1.0, iJk/(2.0*lk*li))));\n      alpha[hk] = std::acos(std::min(1.0, std::max(-1.0, ijK/(2.0*li*lj))));\n    }\n  }\n\n  void setup_b() // system right-hand sid\n  {\n    b.resize(n_v-1 + n_s + n_f-1);\n    b.fill(0.0);\n    \n    std::vector<double> Theta(n_v, 0.0);\n    std::vector<double> kappa(n_s, 0.0);\n    \n    for(int h = 0; h < n_h; h++)\n    {\n      Theta[m.to[m.n[h]]] += alpha[h];\n    }\n    #pragma omp parallel for\n    for(int r = 0; r < n_v-1; r++)\n    {\n      b[r] = Theta_hat[r] - Theta[r];\n    }\n    #pragma omp parallel for\n    for(int s = 0; s < n_s; s++)\n    {\n      kappa[s] = 0.0;\n      int loop_size = gamma[s].size();\n      for(int si = 0; si < loop_size; si++)\n      {\n        int h = gamma[s][si];\n        int hn = m.n[h];\n        int hnn = m.n[hn];\n        if(m.opp(hn) == gamma[s][(si+1)%loop_size])\n          kappa[s] -= alpha[hnn];\n        else if(m.opp(hnn) == gamma[s][(si+1)%loop_size])\n          kappa[s] += alpha[hn];\n        else std::cerr << \"ERROR: loop is broken\" << std::endl;\n      }\n      b[n_v-1+s] = kappa_hat[s] - kappa[s];\n    }\n  }\n  \n  void setup_A() // system matrix\n  {\n    A.resize(n_v-1 + n_s + n_f-1, n_e);\n    int loop_trips = 0;\n    for(int i = 0; i < n_s; i++)\n      loop_trips += gamma[i].size();\n    \n    typedef Eigen::Triplet<double> Trip;\n    std::vector<Trip> trips;\n    trips.clear();\n    trips.resize(n_h*2 + loop_trips + (n_f-1)*3);\n    #pragma omp parallel for\n    for(int h = 0; h < n_h; h++)\n    {\n      int v0 = m.v0(h);\n      int v1 = m.v1(h);\n      if(v0 < n_v-1) trips[h*2] = Trip(v0, m.e(h), m.sign(h)*0.5*cot_alpha[h]);\n      if(v1 < n_v-1) trips[h*2+1] = Trip(v1, m.e(h), -m.sign(h)*0.5*cot_alpha[h]);\n    }\n    \n    int base = n_h*2;\n    for(int s = 0; s < n_s; s++)\n    {\n      int loop_size = gamma[s].size();\n      #pragma omp parallel for\n      for(int si = 0; si < loop_size; si++)\n      {\n        int h = gamma[s][si];\n        trips[base+si] = Trip(n_v-1 + s, m.e(h), m.sign(h)*0.5*(cot_alpha[h]+cot_alpha[m.opp(h)]));\n      }\n      base += loop_size;\n    }\n    \n    #pragma omp parallel for\n    for(int f = 0; f < n_f-1; f++)\n    {\n      int hi = m.h[f];\n      int hj = m.n[hi];\n      int hk = m.n[hj];\n      trips[base+f*3] = Trip(n_v-1 + n_s + f, m.e(hi), m.sign(hi));\n      trips[base+f*3+1] = Trip(n_v-1 + n_s + f, m.e(hj), m.sign(hj));\n      trips[base+f*3+2] = Trip(n_v-1 + n_s + f, m.e(hk), m.sign(hk));\n    }\n    \n    A.setFromTriplets(trips.begin(), trips.end());\n  }\n  \n  double I(int i, int j, int k, double lambda = 0.0)\n  {\n    return m.l[m.e(i)]*std::exp((-xi[j]-delta_xi[j]*lambda)/2) + m.l[m.e(j)]*std::exp((xi[i]+delta_xi[i]*lambda)/2) - m.l[m.e(k)];\n  }\n\n  double firstDegeneracy(int& degen, double lambda)\n  {\n    bool repeat = true;\n    while(repeat)\n    {\n      repeat = false;\n      #pragma omp parallel for\n      for(int i = 0; i < n_h; i++)\n      {\n        int j = m.n[i];\n        int k = m.n[j];\n        double local_lambda = lambda;\n        if(I(i,j,k,local_lambda) < 0.0)\n        {\n          // root finding (from below) by bracketing bisection\n          double lo = 0.0;\n          double hi = local_lambda;\n          for(int r = 0; r < 100; r++)\n          {\n            double mid = (lo+hi)*0.5;\n            if(I(i,j,k,mid) <= 0.0)\n              hi = mid;\n            else\n              lo = mid;\n          }\n          \n          #pragma omp critical\n          {\n            if(lo < lambda)\n            {\n              lambda = lo;\n              degen = k;\n              repeat = true;\n            }\n          }\n        }\n      }\n    }\n    return lambda;\n  }\n  \n  double avg_abs(const Eigen::VectorXd& v)\n  {\n    double res = 0.0;\n    int v_size = v.size();\n    for(int i = 0; i < v_size; i++)\n      res += std::abs(b[i]);\n    return res/v_size;\n  }\n  \n  double max_abs(const Eigen::VectorXd& v)\n  {\n    double res = 0.0;\n    int v_size = v.size();\n    for(int i = 0; i < v_size; i++)\n      res = std::max(res, std::abs(b[i]));\n    return res;\n  }\n  \n  void compute_metric()\n  {\n\n    igl::Timer timer;\n    timer.start();\n\n    // double eps = 1e-12; //if max curvature error below eps: consider converged\n    int max_iter = 25; //max full Newton steps\n    bool converged = false;\n    \n    log(\"computing angles\");\n    compute_angles();\n    log(\"setup b\");\n    setup_b();\n    \n    std::vector< std::pair<double,double> > errors;\n    int n_flips = 0;\n    \n    log(\"starting Newton\");\n    int degen = -1;\n    while(!converged && max_iter > 0)\n    {\n      double error = max_abs(b);\n      if(degen < 0) errors.push_back( std::pair<double,double>(avg_abs(b), error) );\n      if(error <= eps) { converged = true; break; }\n      \n      double diff = avg_abs(b);\n      \n      log(\"setup A\");\n      setup_A();\n      \n      log(\"factorize A\");\n      Eigen::SparseLU< Eigen::SparseMatrix<double> > chol(A);\n      log(\"solve Ax=b\");\n      Eigen::VectorXd result = chol.solve(b);\n      if(chol.info() != Eigen::Success) { log(\"factorization failed\"); return; }\n      log(\"solved\");\n      \n      #pragma omp parallel for\n      for(int i = 0; i < n_e; i++)\n      {\n        delta_xi[i*2] = result[i];\n        delta_xi[i*2+1] = -result[i];\n      }\n      \n      log(\"line search\");\n      double lambda = 1.0;\n      \n      int max_linesearch = 25;\n      degen = -1;\n      while(true) // line search\n      {\n        log(\"  checking for degeneration events\");\n        double first_degen = firstDegeneracy(degen, lambda);\n        if(first_degen < lambda)\n        {\n          lambda = first_degen;\n          std::cout << \"    degeneracy at lambda = \" << lambda << std::endl;\n        }\n        \n        log(\"  checking for improvement\");\n        std::vector<double> xi_old = xi;\n        \n        #pragma omp parallel for\n        for(int i = 0; i < n_h; i++)\n          xi[i] = xi_old[i] + lambda * delta_xi[i];\n        \n        compute_angles();\n        setup_b();\n        \n        if(lambda == 0.0)\n        {\n          converged = true;\n          break;\n        }\n        \n        double new_diff = avg_abs(b);\n        if(new_diff < diff)\n        {\n          std::cout << \"    OK. (\" << diff << \" -> \" << new_diff << \")\" << std::endl;\n          break;\n        }\n        \n        lambda *= 0.5;\n        if(max_linesearch-- == 0) lambda = 0.0;\n        std::cout << \"    reduced to    lambda = \" << lambda << std::endl;\n      }\n      \n      if(degen < 0) max_iter--; //no degeneration event\n      \n      if(!converged) //flip edge(s) of degeneracy/ies\n      {\n        std::set<int> degens;\n        if(degen >= 0) degens.insert(m.e(degen));\n        #pragma omp parallel for\n        for(int i = 0; i < n_h; i++) //check for additional (simultaneous) degeneracies\n        {\n          int j = m.n[i];\n          int k = m.n[j];\n          if(I(i,j,k) <= 0.0)\n          {\n            #pragma omp critical\n            {\n              degens.insert(m.e(k));\n            }\n          }\n        }\n        int n_d = degens.size();\n        if(n_d == 1) std::cout << \"handling a degeneracy by edge flip\" << std::endl;\n        else if(n_d > 1) std::cout << \"handling \" << degens.size() << \" degeneracies by edge flips\" << std::endl;\n        for(std::set<int>::iterator it = degens.begin(); it != degens.end(); it++)\n        {\n          int e = *it;\n          int h = m.h0(e);\n          int hl = m.n[h];\n          int hr = m.n[m.n[m.opp(h)]];\n          \n          int hlu = m.n[hl];\n          int hru = m.n[m.n[hr]];\n          int ho = m.opp(h);\n          int hu = h;\n          \n          double angle = alpha[m.n[hl]]+alpha[m.n[m.opp(h)]];\n          double a = m.l[m.e(hl)] * std::exp(xi[hl]/2);\n          double b = m.l[m.e(hr)] * std::exp(-xi[hr]/2);\n          m.l[e] = std::sqrt(a*a + b*b - 2.0*a*b*std::cos(angle)) / std::exp((xi[hl]-xi[hr])/2); //intrinsic flip (law of cosines)\n          \n          xi[h] = xi[hl]+xi[hr];\n          xi[m.opp(h)] = -xi[h];\n          \n          if(!m.flip_ccw(h)) { std::cerr << \"ERROR: edge could not be flipped.\" << std::endl; converged = true; break; };\n          n_flips++;\n          \n          if(m.l[e] <= 0.0)\n          {\n            m.l[e] = 1e-20;\n            std::cerr << \"WARNING: numerical issue: flipped edge had zero length.\";\n          }\n          \n          // adjust gamma loops that contain the flipped edge e\n          #pragma omp parallel for\n          for(int i = 0; i < n_s; ++i)\n          {\n            std::vector<int>& li = gamma[i];\n            int n = li.size();\n            for(int j = 0; j < n; ++j)\n            {\n              int hij = li[j];\n              int hij1 = li[(j+1)%n];\n              int hij2 = li[(j+2)%n];\n              \n              bool change = true;\n              \n              if(hij == hru && hij1 == m.opp(hr)) li.insert(li.begin()+j+1,ho);\n              else if(hij == hru && hij1 == hu && hij2 == m.opp(hl)) li[(j+1)%n] = ho;\n              else if(hij == hru && hij1 == hu && hij2 == m.opp(hlu)) li.erase(li.begin()+((j+1)%n));\n              \n              else if(hij == hr && hij1 == m.opp(hru)) li.insert(li.begin()+j+1,hu);\n              else if(hij == hr && hij1 == hu && hij2 == m.opp(hlu)) li[(j+1)%n] = hu;\n              else if(hij == hr && hij1 == hu && hij2 == m.opp(hl)) li.erase(li.begin()+((j+1)%n));\n              \n              else if(hij == hl && hij1 == m.opp(hlu)) li.insert(li.begin()+j+1,hu);\n              else if(hij == hl && hij1 == ho && hij2 == m.opp(hru)) li[(j+1)%n] = hu;\n              else if(hij == hl && hij1 == ho && hij2 == m.opp(hr)) li.erase(li.begin()+((j+1)%n));\n              \n              else if(hij == hlu && hij1 == m.opp(hl)) li.insert(li.begin()+j+1,ho);\n              else if(hij == hlu && hij1 == ho && hij2 == m.opp(hr)) li[(j+1)%n] = ho;\n              else if(hij == hlu && hij1 == ho && hij2 == m.opp(hru)) li.erase(li.begin()+((j+1)%n));\n              \n              else change = false;\n              \n              if(change) // cleanup \"cusps\" in loop\n              {\n                n = li.size();\n                int j0 = j;\n                int j1 = (j+1)%n;\n                int j2 = (j+2)%n;\n                if(li[j0] == m.opp(li[j1]))\n                {\n                  if(j1 < j0) std::swap(j0,j1);\n                  li.erase(li.begin()+j1);\n                  li.erase(li.begin()+j0);\n                }\n                else if(li[j1] == m.opp(li[j2]))\n                {\n                  if(j2 < j1) std::swap(j1,j2);\n                  li.erase(li.begin()+j2);\n                  li.erase(li.begin()+j1);\n                }\n              }\n            }\n          }\n        }\n        if(n_d > 0) //recompute angles after flipping\n        {\n          compute_angles();\n          setup_b();\n          \n          //sanity check\n          for(int i = 0; i < n_h; i++)\n          {\n            int j = m.n[i];\n            int k = m.n[j];\n            double indicator = I(i,j,k);\n            if(indicator <= 0.0)\n            {\n              #pragma omp critical\n              {\n                if(indicator == 0.0) std::cerr << \"WARNING: numerical issue: triangle(\"<<i<<\", \"<<j<<\", \"<<k<<\") is degenerate after Newton step.\" << std::endl;\n                if(indicator < 0.0) std::cerr << \"ERROR: numerical issue: triangle(\"<<i<<\", \"<<j<<\", \"<<k<<\") is violating after Newton step.\" << std::endl;\n                degens.insert(m.e(k));\n              }\n            }\n          }\n        }\n      }\n    }\n    \n    double error = max_abs(b);\n    \n    if(error > eps) std::cerr << \"WARNING: the final max error is larger than desired (\"<<error<<\").\" << std::endl;\n    \n    std::cout << \"\\nSTATISTICS:\\n\";\n    std::cout << \"Flips: \" << n_flips << std::endl;\n    std::cout << \"Error Decay: (iter, avg, max)\" << std::endl;\n    for(size_t i = 0; i < errors.size(); i++)\n    {\n      std::cout << i << \": \" << errors[i].first << \"  \" << errors[i].second << std::endl;\n    }\n    std::cout << std::endl;\n    if(n_flips > 0)\n      std::cout << \"HINT: The given mesh m has been modified by edge flips. Get the modified mesh by m.get_mesh(...)\" << std::endl;\n    if(n_flips > 0 && m.is_complex())\n      std::cout << \"HINT: The modified mesh is non-simple (e.g. contains a loop edge or multiple edges between a pair of vertices). Beware that many mesh data structures and libraries do not support this appropriately.\" << std::endl;\n    std::cout << std::endl;\n\n    // write n_flip and time spent to log\n    auto total_time = timer.getElapsedTime();\n\n    std::ofstream mf;\n    mf.open(log_dir+\"/summary_similarity.csv\", std::ios_base::app);\n    std::ifstream nf(log_dir+\"/summary_similarity.csv\");\n    if (nf && nf.peek() == std::ifstream::traits_type::eof() ){\n      // if stats file is empty then add column names\n      nf.close();\n      mf << \"name, n_flips, max_error_similarity, Th_hat_preset, time\\n\" ;\n    }\n\n    mf << name << \", \" << n_flips << \", \" << error <<\",\" << Theta_hat[0] << \",\"<< total_time << std::endl;\n    mf.close();\n\n  }\n\n\n  void compute_layout(std::vector<double>& u, std::vector<double>& v) //metric -> parametrization\n  {\n    std::vector<double> phi(n_h);\n    \n    u.resize(n_h);\n    v.resize(n_h);\n    \n    //set starting point\n    int h = 0;\n    phi[h] = 0.0;\n    u[h] = 0.0;\n    v[h] = 0.0;\n    h = m.n[h];\n    phi[h] = xi[h];\n    u[h] = m.l[m.e(h)]*std::exp(phi[h]/2);\n    v[h] = 0.0;\n    \n    // layout the rest of the mesh by BFS\n    std::vector<bool> visited(n_f, false);\n    std::queue<int> q;\n    q.push(h);\n    visited[m.f[h]] = true;\n    while(!q.empty())\n    {\n      h = q.front();\n      q.pop();\n      \n      int hn = m.n[h];\n      int hp = m.n[hn];\n      \n      phi[hn] = phi[h] + xi[hn];\n      \n      double len = m.l[m.e(hn)] * std::exp((phi[h]+phi[hn])/2);\n      \n      double ud = u[hp]-u[h];\n      double vd = v[hp]-v[h];\n      double d = std::sqrt(ud*ud + vd*vd);\n      double co = std::cos(alpha[hp]);\n      double si = std::sin(alpha[hp]);\n      \n      u[hn] = u[h] + (co*ud + si*vd)*len/d;\n      v[hn] = v[h] + (co*vd - si*ud)*len/d;\n      \n      int hno = m.opp(hn);\n      int hpo = m.opp(hp);\n      if(!visited[m.f[hno]])\n      {\n        visited[m.f[hno]] = true;\n        phi[hno] = phi[h];\n        phi[m.n[m.n[hno]]] = phi[hn];\n        u[hno] = u[h];\n        v[hno] = v[h];\n        u[m.n[m.n[hno]]] = u[hn];\n        v[m.n[m.n[hno]]] = v[hn];\n        q.push(hno);\n      }\n      if(!visited[m.f[hpo]])\n      {\n        visited[m.f[hpo]] = true;\n        phi[hpo] = phi[hn];\n        phi[m.n[m.n[hpo]]] = phi[hp];\n        u[hpo] = u[hn];\n        v[hpo] = v[hn];\n        u[m.n[m.n[hpo]]] = u[hp];\n        v[m.n[m.n[hpo]]] = v[hp];\n        q.push(hpo);\n      }\n    }\n  }\n\n  void compute(std::vector<double>& u, std::vector<double>& v) //main method\n  {\n    compute_metric();\n    compute_layout(u, v);\n  }\n\n};\n", "meta": {"hexsha": "29f3a615098cc1511d54c642ee3a4682a9ee194c", "size": 19945, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/conformal_seamless_similarity/ConformalSeamlessSimilarityMapping.hh", "max_stars_repo_name": "hankstag/ConformalIdealDelaunay", "max_stars_repo_head_hexsha": "653a6f62908517df60a3e9f4c311ba6f2f358382", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T03:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:34:25.000Z", "max_issues_repo_path": "src/conformal_seamless_similarity/ConformalSeamlessSimilarityMapping.hh", "max_issues_repo_name": "hankstag/ConformalIdealDelaunay", "max_issues_repo_head_hexsha": "653a6f62908517df60a3e9f4c311ba6f2f358382", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/conformal_seamless_similarity/ConformalSeamlessSimilarityMapping.hh", "max_forks_repo_name": "hankstag/ConformalIdealDelaunay", "max_forks_repo_head_hexsha": "653a6f62908517df60a3e9f4c311ba6f2f358382", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-09T04:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T04:56:14.000Z", "avg_line_length": 29.7242921013, "max_line_length": 343, "alphanum_fraction": 0.4850839809, "num_tokens": 6286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5137726262740736}}
{"text": "// Copyright (c) 2012-2017 VideoStitch SAS\n// Copyright (c) 2018 stitchEm\n\n#pragma once\n\n#include \"libvideostitch/panoDef.hpp\"\n#include \"libvideostitch/logging.hpp\"\n\n#include <Eigen/Dense>\n\n#include <random>\n\nnamespace VideoStitch {\nnamespace Calibration {\n\nclass Camera;\n\n/**\n@brief  This class is used to filter outlier control points.\n@details Given two inputs and the control points between them, it finds the best model to align two images in the\npanorama\n@details Returns the optimal relative position of the images and a list of control points containing only the inlier\ncontrol points\n*/\nclass ControlPointFilter {\n public:\n  ControlPointFilter(double cellFactor, double angleThreshold, double minRatioInliers, int minSamplesForFit,\n                     double ratioOutliers, double probaDrawOutlierFreeSample);\n\n  /**\n   * @brief Uses the control points to align inputs.\n   * @param filteredControlPoints the returned list of filtered control points\n   * @param camera1 the first camera object\n   * @param camera2 the second camera object\n   * @param currentControlPoints the list of control points extracted from the current input pictures\n   * @param formerControlPoints the list of control points coming from the PanoDefinition (extracted during a former\n   * calibration)\n   * @param syntheticControlPoints the list of synthetic control points generated to cover the input areas where no\n   * control point has been extracted\n   * @param gen the random number generator\n   * @note currentControlPoints take precedence over formerControlPoints, which take precedence over\n   * syntheticControlPoints\n   * @return true on success\n   * @return false on failure\n   */\n  bool filterFromExtrinsics(Core::ControlPointList& filteredControlPoints, const std::shared_ptr<Camera>& camera1,\n                            const std::shared_ptr<Camera>& camera2, const Core::ControlPointList& currentControlPoints,\n                            const Core::ControlPointList& formerControlPoints,\n                            const Core::ControlPointList& syntheticControlPoints, std::default_random_engine& gen);\n\n  /**\n   * @brief Uses the estimated rotation to project the control points.\n   * @return true on success\n   * @return false on failure\n   */\n  Status projectFromEstimatedRotation(Core::ControlPointList& filteredControlPoints,\n                                      const std::shared_ptr<Camera>& camera1, const std::shared_ptr<Camera>& camera2);\n\n  Eigen::Matrix3d getEstimatedRotation() { return estimatedR; }\n\n  /**\n   * @brief Get rotation score\n   * @return sum of angular distances between rotated inliers\n   */\n  double getScore() { return score; }\n\n  /**\n   * @brief gets the number of inliers with found rotation\n   * @return number of inliers with found rotation\n   */\n  size_t getConsensus() { return consensus; }\n\n private:\n  Eigen::Matrix3d estimatedR;\n  double score;\n  size_t consensus;\n\n private:\n  double cellFactor;       // Cell for homogeneous distribution\n  double angleThreshold;   // max angular distance between two reprojected CPs to be considered as inliers, in degrees\n  double minRatioInliers;  // minimum ratio of inliers that need to be found to validate a model\n  int minSamplesForFit;    // minimum number of control points needed to estimate a model\n  int numIters;            // number of RANSAC iterations\n};\n\n}  // namespace Calibration\n}  // namespace VideoStitch\n", "meta": {"hexsha": "19a6d8e8a3f8a2496dfd45808e53ca44a4849220", "size": 3408, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/src/calibration/controlPointFilter.hpp", "max_stars_repo_name": "tlalexander/stitchEm", "max_stars_repo_head_hexsha": "cdff821ad2c500703e6cb237ec61139fce7bf11c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 182.0, "max_stars_repo_stars_event_min_datetime": "2019-04-19T12:38:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T16:48:20.000Z", "max_issues_repo_path": "lib/src/calibration/controlPointFilter.hpp", "max_issues_repo_name": "tlalexander/stitchEm", "max_issues_repo_head_hexsha": "cdff821ad2c500703e6cb237ec61139fce7bf11c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107.0, "max_issues_repo_issues_event_min_datetime": "2019-04-23T10:49:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T18:12:28.000Z", "max_forks_repo_path": "lib/src/calibration/controlPointFilter.hpp", "max_forks_repo_name": "tlalexander/stitchEm", "max_forks_repo_head_hexsha": "cdff821ad2c500703e6cb237ec61139fce7bf11c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2019-06-04T11:27:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T23:49:49.000Z", "avg_line_length": 38.7272727273, "max_line_length": 119, "alphanum_fraction": 0.7315140845, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5137726164315023}}
{"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/collision/continuous/continuous_default_motion_policy.h>\r\n#include <OpenTissue/collision/continuous/continuous_motion_interpolation.h>\r\n#include <OpenTissue/collision/gjk/gjk_support_functors.h>\r\n\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\n#include <cmath>\r\n\r\nusing namespace OpenTissue;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_collision_continuous_conservative_advancement);\r\n\r\nBOOST_AUTO_TEST_CASE(case_by_case_test)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n  typedef math_types::value_traits                         value_traits;\r\n  typedef math_types::vector3_type                         V;\r\n  typedef math_types::real_type                            T;\r\n  typedef math_types::quaternion_type                      Q;\r\n  typedef math_types::coordsys_type                        X;\r\n\r\n  // Setup a central impact, two sphere hitting in perfect symmetry, totally independent of their rotationnal motion!\r\n  {\r\n    OpenTissue::gjk::Sphere<math_types> const A;\r\n    OpenTissue::gjk::Sphere<math_types> const B;\r\n\r\n    X A_from, A_to;\r\n    X B_from, B_to;\r\n\r\n    A_from.T() = V(-2.0, 0.0, 0.0);\r\n    A_from.Q().identity();\r\n    A_to.T() = V(0.0, 0.0, 0.0);\r\n    A_to.Q().Ry( 5.0 );\r\n    T r_max_a = A.radius();\r\n\r\n    B_from.T() = V( 2.0, 0.0, 0.0);\r\n    B_from.Q().identity();\r\n    B_to.T() = V( 0.0, 0.0, 0.0);\r\n    B_to.Q().Rz( 5.0 );\r\n    T r_max_b = B.radius();\r\n\r\n    OpenTissue::collision::continuous::DefaultMotionPolicy const motion_policy = OpenTissue::collision::continuous::DefaultMotionPolicy();\r\n    size_t const max_iterations = 100u;\r\n    T      const epsilon = 0.0001;\r\n    T toi;\r\n    size_t iterations;\r\n    V p_a;\r\n    V p_b;\r\n\r\n    bool impact = OpenTissue::collision::continuous::motion_interpolation(\r\n        A_from\r\n      , A_to\r\n      , A\r\n      , r_max_a\r\n      , B_from\r\n      , B_to\r\n      , B\r\n      , r_max_b\r\n      , p_a\r\n      , p_b\r\n      , toi\r\n      , iterations\r\n      , epsilon\r\n      , max_iterations\r\n      , motion_policy \r\n      );\r\n\r\n    BOOST_CHECK( impact );\r\n    BOOST_CHECK_CLOSE( toi, 0.5, 0.01 );\r\n\r\n    BOOST_CHECK( fabs( p_a(0) ) < epsilon );\r\n    BOOST_CHECK( fabs( p_a(1) ) < epsilon );\r\n    BOOST_CHECK( fabs( p_a(2) ) < epsilon );\r\n    BOOST_CHECK( fabs( p_b(0) ) < epsilon );\r\n    BOOST_CHECK( fabs( p_b(1) ) < epsilon );\r\n    BOOST_CHECK( fabs( p_b(2) ) < epsilon );\r\n  }\r\n\r\n  // Setup separating motion, two spheres moving away from each other\r\n  {\r\n    OpenTissue::gjk::Sphere<math_types> const A;\r\n    OpenTissue::gjk::Sphere<math_types> const B;\r\n\r\n    X A_from, A_to;\r\n    X B_from, B_to;\r\n\r\n    A_from.T() = V(-2.0, 0.0, 0.0);\r\n    A_from.Q().identity();\r\n    A_to.T() = V(-4.0, 0.0, 0.0);\r\n    A_to.Q().Ry( 5.0 );\r\n    T r_max_a = A.radius();\r\n\r\n    B_from.T() = V( 2.0, 0.0, 0.0);\r\n    B_from.Q().identity();\r\n    B_to.T() = V( 4.0, 0.0, 0.0);\r\n    B_to.Q().Rz( 5.0 );\r\n    T r_max_b = B.radius();\r\n\r\n    OpenTissue::collision::continuous::DefaultMotionPolicy const motion_policy = OpenTissue::collision::continuous::DefaultMotionPolicy();\r\n    size_t const max_iterations = 100u;\r\n    T      const epsilon = 0.0001;\r\n    T toi;\r\n    size_t iterations;\r\n    V p_a;\r\n    V p_b;\r\n\r\n    bool impact = OpenTissue::collision::continuous::motion_interpolation(\r\n        A_from\r\n      , A_to\r\n      , A\r\n      , r_max_a\r\n      , B_from\r\n      , B_to\r\n      , B\r\n      , r_max_b\r\n      , p_a\r\n      , p_b\r\n      , toi\r\n      , iterations\r\n      , epsilon\r\n      , max_iterations\r\n      , motion_policy \r\n      );\r\n\r\n    BOOST_CHECK( !impact );\r\n  }\r\n\r\n  // Setup two sphere moving close by each other but never impacting\r\n  {\r\n    OpenTissue::gjk::Sphere<math_types> const A;\r\n    OpenTissue::gjk::Sphere<math_types> const B;\r\n\r\n    X A_from, A_to;\r\n    X B_from, B_to;\r\n\r\n    A_from.T() = V(-2.0, 1.01, 0.0);\r\n    A_from.Q().identity();\r\n    A_to.T() = V(0.0, 1.01, 0.0);\r\n    A_to.Q().Ry( 5.0 );\r\n    T r_max_a = A.radius();\r\n\r\n    B_from.T() = V( 2.0, -1.01, 0.0);\r\n    B_from.Q().identity();\r\n    B_to.T() = V( 0.0, -1.01, 0.0);\r\n    B_to.Q().Rz( 5.0 );\r\n    T r_max_b = B.radius();\r\n\r\n    OpenTissue::collision::continuous::DefaultMotionPolicy const motion_policy = OpenTissue::collision::continuous::DefaultMotionPolicy();\r\n    size_t const max_iterations = 100u;\r\n    T      const epsilon = 0.0001;\r\n    T toi;\r\n    size_t iterations;\r\n    V p_a;\r\n    V p_b;\r\n\r\n    bool impact = OpenTissue::collision::continuous::motion_interpolation(\r\n        A_from\r\n      , A_to\r\n      , A\r\n      , r_max_a\r\n      , B_from\r\n      , B_to\r\n      , B\r\n      , r_max_b\r\n      , p_a\r\n      , p_b\r\n      , toi\r\n      , iterations\r\n      , epsilon\r\n      , max_iterations\r\n      , motion_policy \r\n      );\r\n\r\n    BOOST_CHECK( !impact );\r\n  }\r\n\r\n  // Setup test case where only rotational motion is of importance!\r\n  {\r\n    OpenTissue::gjk::Cylinder<math_types> A;\r\n    OpenTissue::gjk::Sphere<math_types> B;\r\n\r\n    A.half_height() = 10.0;\r\n    A.radius()      =  1.0;\r\n    B.radius()      =  1.0;\r\n\r\n    X A_from, A_to;\r\n    X B_from, B_to;\r\n\r\n    A_from.T() = V(0.0, 0.0, 2.0);\r\n    A_from.Q().identity();\r\n    A_to.T() = V(0.0, 0.0, 2.0);\r\n    A_to.Q().Rx( -value_traits::pi() );\r\n    T r_max_a = sqrt( A.half_height()*A.half_height() + A.radius()*A.radius() );\r\n\r\n    B_from.T() = V( 0.0, 10.0, 0.0);\r\n    B_from.Q().identity();\r\n    B_to.T() = V( 0.0, 10.0, 0.0);\r\n    B_to.Q().identity();\r\n    T r_max_b = B.radius();\r\n\r\n    OpenTissue::collision::continuous::DefaultMotionPolicy const motion_policy = OpenTissue::collision::continuous::DefaultMotionPolicy();\r\n    size_t const max_iterations = 100u;\r\n    T      const epsilon = 0.0001;\r\n    T toi;\r\n    size_t iterations;\r\n    V p_a;\r\n    V p_b;\r\n\r\n    bool impact = OpenTissue::collision::continuous::motion_interpolation(\r\n        A_from\r\n      , A_to\r\n      , A\r\n      , r_max_a\r\n      , B_from\r\n      , B_to\r\n      , B\r\n      , r_max_b\r\n      , p_a\r\n      , p_b\r\n      , toi\r\n      , iterations\r\n      , epsilon\r\n      , max_iterations\r\n      , motion_policy \r\n      );\r\n\r\n    BOOST_CHECK( impact );\r\n    BOOST_CHECK_CLOSE( toi, 0.5, 0.01 );\r\n    BOOST_CHECK( norm(p_a-p_b) < epsilon );\r\n  }\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "4ff36c5f6f594e1a406789fe69055f8613acec76", "size": 6723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/collision/continuous/motion_interpolation/src/unit_motion_interpolation.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/collision/continuous/motion_interpolation/src/unit_motion_interpolation.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/collision/continuous/motion_interpolation/src/unit_motion_interpolation.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.0, "max_line_length": 139, "alphanum_fraction": 0.5817343448, "num_tokens": 1991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5137726110387232}}
{"text": "/* \nCopyright (c) 2012 David Koes and University of Pittsburgh  \n \nPermission is hereby granted, free of charge, to any person \nobtaining a copy of this software and associated documentation files \n(the \"Software\"), to deal in the Software without restriction, \nincluding without limitation the rights to use, copy, modify, merge, \npublish, distribute, sublicense, and/or sell copies of the Software, \nand to permit persons to whom the Software is furnished to do so, \nsubject to the following conditions:  The above copyright notice and \nthis permission notice shall be included in all copies or substantial\nportions of the Software.  \n \nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, \nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF \nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND \nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS \nBE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN \nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN \nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE \nSOFTWARE.\n*  */\n\n/* 9/18/2012  dkoes\n * This is a simple little program that uses Shake-Rupley and OpenBabel\n * to calculate the solvent accessible surface area of a molecule.\n * I'm trying to make it fast.\n *\n * If no file is given, assume a pdb on stdin.  Always outputs to stdout.\n *\n */\n \n#include <cmath>\n#include <cstdio>\n#include <sstream>\n#include <string>\n#include <openbabel/mol.h>\n#include <boost/algorithm/string.hpp>\n#include <ANN/ANN.h>\n\n#define MAXVDW (3.0) /* assumed maximum vdw */\nusing namespace std;\nusing namespace OpenBabel;\nusing namespace boost::algorithm;\n\nstruct Coord\n{\n\tdouble x;\n\tdouble y;\n\tdouble z;\n\n\tCoord(): x(0), y(0), z(0) {}\n\n\tCoord(double a, double b, double c): x(a), y(b), z(c) {}\n\n\tdouble distSq(const Coord& r) const\n\t{\n\t\tdouble a = x-r.x;\n\t\tdouble b = y-r.y;\n\t\tdouble c = z-r.z;\n\t\treturn a*a+b*b+c*c;\n\t}\n};\n\n//represents an atom from a pdb file\nclass Atom\n{\n\tstring line; //full line of pdb file\n\tCoord position; //coordinates\n\tdouble r; //vdw radius\n\npublic:\n\tAtom(): r(0) {}\n\n\tAtom(const string& l): line(l), r(0) //initialize from pdb file\n\t{\n\t\t//assume this an atom\n\t\tstringstream x(line.substr(30,8));\n\t\tstringstream y(line.substr(38,8));\n\t\tstringstream z(line.substr(46,8));\n\n\t\tx >> position.x;\n\t\ty >> position.y;\n\t\tz >> position.z;\n\n\t\tstring el = line.substr(76,2);\n\t\ttrim(el);\n\t\t//remove any digits or special characters\n\t\ttrim_if(el, is_any_of(\"0123456789+-\"));\n\t\tunsigned anum = etab.GetAtomicNum(el.c_str());\n\t\tr = etab.GetVdwRad(anum);\n\t}\n\n\t//return true if pdb line is an atom\n\tstatic bool isAtom(const string& l)\n\t{\n\t\tif(l.substr(0,4) == \"ATOM\" || l.substr(0,6) == \"HETATM\")\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\n\tconst Coord& coord() const { return position; }\n\tconst double radius() const { return r; }\n\n\tvoid print(FILE *out, double bfactor) const\n\t{\n\t\tif(bfactor >= 100)\n\t\t\tbfactor = 99.999;\n\t\tfprintf(out, \"%s%6.3f%6.3f%s\\n\",line.substr(0,54).c_str(),bfactor,r,line.substr(66).c_str());\n\t}\n};\n\nvoid readAtoms(istream& in, vector<Atom>& mol)\n{\n\tmol.clear();\n\tstring line;\n\twhile(getline(in, line))\n\t{\n\t\tif(Atom::isAtom(line))\n\t\t\tmol.push_back(Atom(line));\n\t}\n}\n\n\n\n//create uniformish sphere of n points\nvoid generateSpherePoints(unsigned n, vector<Coord>& points)\n{\n\tpoints.clear(); points.reserve(n);\n    double inc = M_PI * (3 - sqrt(5));\n    double offset = 2 / double(n);\n    for(unsigned k = 0; k < n; k++)\n    {\n    \tdouble y = k * offset - 1 + (offset / 2);\n        double r = sqrt(1 - y*y);\n        double phi = k * inc;\n        points.push_back(Coord(cos(phi)*r, y, sin(phi)*r));\n    }\n}\n\n//find all atoms close the the specified atomi,\n//it's faster to do this once per an atom and then brute force the\n//collisions with the sphere points\nvoid find_neighbor_indices(vector<Atom>& mol, ANNkd_tree& tree,  double probe, unsigned atomi, vector<unsigned>& neighbor_indices)\n{\n\tneighbor_indices.clear();\n\tANNidx idxArray[mol.size()];\n\n\tconst Coord& avec = mol[atomi].coord();\n\tdouble radius = mol[atomi].radius() + probe + probe;\n\n\tdouble maxr = radius+MAXVDW;\n\tANNcoord querypt[3] = {avec.x, avec.y, avec.z};\n\tunsigned numneigh = tree.annkFRSearch(querypt, maxr*maxr, mol.size(), idxArray);\n\n\tfor (unsigned idx = 0; idx < numneigh; idx++)\n\t{\n\t\tunsigned ai = idxArray[idx];\n\t\tif(ai != atomi)\n\t\t{\n\t\t\tconst Atom& a = mol[ai];\n\t\t\tdouble distSq = avec.distSq(a.coord());\n\t\t\tdouble r = radius+a.radius();\n\t\t\tif(distSq < r*r)\n\t\t\t\tneighbor_indices.push_back(ai);\n\t\t}\n\t}\n}\n\n//compute asa of each atom of mol and print as it is computed\nvoid printASA(vector<Atom>& mol, const vector<Coord>& points, ANNkd_tree& tree, double probe, FILE * out)\n{\n    const double Const = 4.0 * M_PI / double(points.size());\n    Coord test_point;\n    vector<unsigned> neighbor_indices;\n    double total = 0;\n\tfor (unsigned ai = 0, na = mol.size(); ai < na; ai++)\n\t{\n\t\tconst Atom& a = mol[ai];\n\t\tfind_neighbor_indices(mol, tree, probe, ai, neighbor_indices);\n\n\t\tdouble radius = probe + a.radius();\n\t\tunsigned n_accessible_point = 0;\n\n\t\tfor(unsigned i = 0, n = points.size(); i < n; i++)\n\t\t{\n\t\t\tbool is_accessible = true;\n\t\t\ttest_point.x = points[i].x*radius + a.coord().x;\n\t\t\ttest_point.y = points[i].y*radius + a.coord().y;\n\t\t\ttest_point.z = points[i].z*radius + a.coord().z;\n\n\t\t\tfor(unsigned j = 0, m = neighbor_indices.size(); j < m; j++)\n\t\t\t{\n\t\t\t\tconst Atom& atom_j = mol[neighbor_indices[j]];\n\t\t\t\tdouble r = atom_j.radius() + probe;\n\t\t\t\tdouble diff_sq = test_point.distSq(atom_j.coord());\n\t\t\t\tif(diff_sq < r*r)\n\t\t\t\t{\n\t\t\t\t\tis_accessible = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(is_accessible)\n\t\t\t\tn_accessible_point++;\n\t\t}\n\n\t\tdouble area = Const*n_accessible_point*radius*radius;\n\t\ttotal += area;\n\t\ta.print(out, area);\n\t}\n\tfprintf(out,\"END\\n\");\n\tfprintf(out,\"REMARK Total %f\\n\",total);\n}\n\nint main(int argc, char *argv[])\n{\n\tunsigned n_sphere_point = 960;\n\tdouble probe = 1.4;\n\n\tvector<Atom> mol;\n\tif(argc > 1)\n\t{\n\t\tifstream in(argv[1]);\n\t\tif(!in)\n\t\t{\n\t\t\tcerr << \"Error opening \" << argv[1] << endl;\n\t\t\texit(-1);\n\t\t}\n\t\treadAtoms(in, mol);\n\t}\n\telse\n\t{\n\t\treadAtoms(cin, mol);\n\t}\n\n\t//initialize spatial index\n\tANNpointArray atompts = annAllocPts(mol.size(),3);\n\tfor(unsigned i = 0, n = mol.size(); i < n; i++)\n\t{\n\t\tatompts[i][0] = mol[i].coord().x;\n\t\tatompts[i][1] = mol[i].coord().y;\n\t\tatompts[i][2] = mol[i].coord().z;\n\t}\n\tANNkd_tree tree(atompts, mol.size(), 3);\n\n\tvector<Coord> sphpoints;\n\tgenerateSpherePoints(n_sphere_point, sphpoints);\n\n\tprintASA(mol, sphpoints, tree, probe, stdout);\n\n\t//clean up memory\n\tannDeallocPts(atompts);\n\tannClose();\n}\n", "meta": {"hexsha": "e549dbb82adc17239c13669cff43a8795112422b", "size": 6589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "asacalc.cpp", "max_stars_repo_name": "dkoes/asacalc", "max_stars_repo_head_hexsha": "0ca28cb6879f89d769ed8f2eec728aaf001132c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-24T04:02:00.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-24T04:02:00.000Z", "max_issues_repo_path": "asacalc.cpp", "max_issues_repo_name": "dkoes/asacalc", "max_issues_repo_head_hexsha": "0ca28cb6879f89d769ed8f2eec728aaf001132c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "asacalc.cpp", "max_forks_repo_name": "dkoes/asacalc", "max_forks_repo_head_hexsha": "0ca28cb6879f89d769ed8f2eec728aaf001132c0", "max_forks_repo_licenses": ["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.73828125, "max_line_length": 130, "alphanum_fraction": 0.6671725603, "num_tokens": 1896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5137726047029582}}
{"text": "#ifndef KDTREE_TRIANGLES_HPP\n#define KDTREE_TRIANGLES_HPP\n\n#include <algorithm>\n#include <vector>\n#include <memory>\n\n#include \"point_triangle.hpp\"\n\n#include <Eigen/Core>\n\ntemplate<class Real, class Index, std::size_t N = 3>\nstruct kd_tree {\n  using index_type = Index;\n  using real_type = Real;\n\n  struct vertex {\n    const real_type* coords;\n  };\n\n  struct triangle {\n    const index_type* indices;\n    std::size_t counter = 0;\n\n    // real_type distance2(vertex query, const vertex* data) const {\n    //   using vec3 = Eigen::Matrix<real_type, 3, 1>;\n    //   using mat3x2 = Eigen::Matrix<real_type, 3, 2>;      \n\n    //   const auto q = vec3::Map(query.coords);\n    //   const auto p = {vec3::Map(data + indices[0]),\n    //                   vec3::Map(data + indices[1]),\n    //                   vec3::Map(data + indices[2])};\n    //   mat3x2 A;\n    //   A << (p[1] - p[0]), (p[2] - p[0]);\n\n    //   const vec3 n = A.col(0).cross(A.col(1));\n    //   const vec3 s = q - p[0];\n      \n    //   const vec3 b = s - (n * n.dot(s)) / n.squaredNorm();\n      \n    // }\n    // TODO point-triangle distance2\n  };\n\n  class plane {\n    vertex origin;\n    std::size_t axis;\n  public:\n    plane(vertex origin, std::size_t axis):\n      origin(origin), axis(axis) {}\n    \n    bool positive(vertex v) const {\n      return v.coord[axis] >= origin.coord[axis];\n    }\n\n    real_type distance2(vertex v) const {\n      const real_type delta = v.coord[axis] - origin.coord[axis];\n      // TODO distance?\n      return delta * delta;\n    }\n  };\n\n\n  // partition(3) triangle range according to given plane\n  static std::pair<triangle*, triangle*>\n  split_triangles(triangle* first, triangle* last, const vertex* vertices,\n                  plane p) {\n    // compute positive vertices\n    for(auto it = first; it != last; ++it) {\n      it->counter = 0;\n      for(std::size_t i = 0; i < N; ++i) {\n        if(p.positive(vertices[(it->indices[i])])) {\n          ++it->counter;\n        }\n      }\n    }\n\n    // partition\n    const auto negative = std::partition(\n        first, last, [](const triangle& self) { return self.counter > 0; });\n\n    const auto positive = std::partition(\n        negative, last, [](const triangle& self) { return self.counter < 3; });\n\n    return std::make_pair(negative, positive);\n  }\n\n  template<class T>\n  using ref = std::shared_ptr<T>;\n\n  struct node {\n    const plane p;\n\n    const triangle* first;\n    const triangle* last;\n    \n    const ref<node> negative, overlap, positive;\n    node(plane p, const triangle* first, const triangle* last,\n         ref<node> negative, ref<node> overlap, ref<node> positive):\n        p(p),\n        first(first),\n        last(last),\n        negative(negative),\n        overlap(overlap),\n        positive(positive) {\n      assert(last > first);\n    }\n\n\n    struct closest_type {\n      const triangle* tri = nullptr;\n      real_type distance2 = std::numeric_limits<real_type>::infinity();\n      // TODO store proj as well?\n\n      closest_type min(closest_type other) const {\n        if(distance2 < other.distance2) {\n          return *this;\n        } else {\n          return other;\n        }\n      }\n    };\n\n\n    static closest_type closest_brute_force(vertex query, const triangle* first,\n                                            const triangle* last, real_type) {\n      // TODO exploit best?\n      closest_type res;\n      for(auto it = first; it != last; ++it) {\n        const real_type distance2 = it->distance2(query);\n        if(distance2 < res.distance2) {\n          res.distance2 = distance2;\n          res.tri = *it;\n        }\n      }\n\n      return res;\n    }\n\n\n    closest_type closest(vertex query, const ref<node>& near, const ref<node>& far, real_type best) const {\n      closest_type res;      \n      for(auto sub: {near, overlap}) {\n        if(sub) {\n          res = res.min(sub->closest(query, best));\n          if(res.distance2 < best) {\n            best = res.distance2;\n          }\n        }\n      }\n      \n      if(p.distance2(query) < best) {\n        res = res.min(far->closest(query, best));\n      }\n\n      return res;\n    }\n\n    static constexpr std::size_t brute_force_threshold = 1;\n    \n    closest_type closest(vertex query,\n                         real_type best=std::numeric_limits<real_type>::infinity()) const {\n      if(last - first < brute_force_threshold) {\n        return closest_brute_force(query, first, last, best);\n      }\n      \n      closest_type res;\n      if(p.positive(query)) {\n        return closest(query, positive, negative, best);\n      } else {\n        return closest(query, negative, positive, best);\n      }\n    }\n    \n  };\n\n  static ref<node> create(triangle* first,\n                          triangle* last,\n                          const vertex* vertex_data, std::size_t axis) {\n    // base case\n    if(first == last) {\n      return {};\n    }\n    \n    // 1. fetch triangle vertices\n    std::vector<vertex> vertices;\n    for(auto it = first; it != last; ++it) {\n      for(std::size_t i = 0; i < 3; ++i) {\n        vertices.emplace_back(vertex_data[i]);\n      }\n    }\n\n    // 2. sort vertices along axis\n    const auto first_vertex = vertices.begin();\n    auto last_vertex = vertices.end();\n    std::sort(first_vertex, last_vertex, [axis](vertex lhs, vertex rhs) {\n      return lhs.coords[axis] < rhs.coords[axis];\n    });\n\n    // 3. prune duplicates\n    last_vertex = std::unique(first_vertex, last_vertex);\n\n    // 4. find pivot\n    const auto pivot = (first_vertex + last_vertex) / 2;\n    const plane p = {pivot->coords, axis};\n\n    // 5. partition triangles\n    const auto subsets =\n        split_triangles(first, last, vertex_data, axis);\n\n    // 7. recurse on subclasses\n    const std::size_t next = ++axis % N;\n    const auto negative = create(first, subsets.first, vertex_data, next);\n    const auto overlap = create(subsets.first, subsets.second, vertex_data, next);\n    const auto positive = create(subsets.second, last, vertex_data, next);\n\n    // 8. node\n    return std::make_shared<node>(p, first, last, negative, overlap, positive);\n  }\n\n  \n  struct result {\n    ref<node> root;\n    std::vector<vertex> vertices;\n    std::vector<triangle> triangles;\n\n  };\n\n  static void create(result& out,\n                     const real_type* point_data, std::size_t point_size,\n                     const index_type* triangle_data, std::size_t triangle_size) {\n    // build vertex array\n    out.vertices.resize(point_size);\n    for(std::size_t i = 0; i < point_size; ++i) {\n      out.vertices[i].coords = point_data + (i * N);\n    }\n\n    // build triangle array\n    out.triangles.resize(triangle_size);\n    for(std::size_t i = 0; i < triangle_size; ++i) {\n      out.triangles[i].indices = triangle_data + (i * 3);\n    }\n    \n    // create\n    const std::size_t axis = 0;\n    return create(out.triangles.data(), out.triangles.data() + triangle_size,\n                  out.vertices.data(), axis);\n  }\n\n  \n  \n};\n\n#endif\n", "meta": {"hexsha": "011c0e48901751813716c83ea6de507449ef6eb5", "size": 6912, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kdtree_triangles.hpp", "max_stars_repo_name": "maxime-tournier/cpp", "max_stars_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kdtree_triangles.hpp", "max_issues_repo_name": "maxime-tournier/cpp", "max_issues_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kdtree_triangles.hpp", "max_forks_repo_name": "maxime-tournier/cpp", "max_forks_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_forks_repo_licenses": ["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.1058823529, "max_line_length": 107, "alphanum_fraction": 0.5765335648, "num_tokens": 1735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5137158832931463}}
{"text": "\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <opencv2/calib3d.hpp>\n\n#include <vector>\n\n#include \"random.h\"\n#include \"so3.h\"\n\n#include \"affine_problem.h\"\n\nstruct AffineRegion\n{\n    Eigen::Vector3d X;\n    Eigen::Vector3d u1;\n    Eigen::Vector3d u2;\n    Eigen::Vector3d u3;\n    Eigen::Vector3d u4;\n};\n\nEigen::Matrix2d getRelativeAffineMatrix(AffineRegion Au, AffineRegion Av,\n                                       Eigen::Vector3d cu, Eigen::Vector3d cv)\n{\n    // calculate affine matrix from u image to v image\n    // solves A*(u-center_u) = (v-center_v)\n    // where v is projected point in v image, center_v is projection of PX in v image\n    // where u is projected point in u image, center_u is projection of X in u image\n    Eigen::Vector3d center_u3 = Au.X-cu;\n    Eigen::Vector2d center_u(center_u3[0]/center_u3[2],center_u3[1]/center_u3[2]);\n\n    Eigen::Vector3d u13 = Au.u1 - cu;\n    Eigen::Vector3d u23 = Au.u2 - cu;\n    Eigen::Vector3d u33 = Au.u3 - cu;\n    Eigen::Vector3d u43 = Au.u4 - cu;\n\n    Eigen::Vector2d u1(u13[0]/u13[2],u13[1]/u13[2]);\n    Eigen::Vector2d u2(u23[0]/u23[2],u23[1]/u23[2]);\n    Eigen::Vector2d u3(u33[0]/u33[2],u33[1]/u33[2]);\n    Eigen::Vector2d u4(u43[0]/u43[2],u43[1]/u43[2]);\n\n    Eigen::Vector3d center_v3 = Av.X-cv;\n    Eigen::Vector2d center_v(center_v3[0]/center_v3[2],center_v3[1]/center_v3[2]);\n\n    Eigen::Vector3d v13 = Av.u1 - cv;\n    Eigen::Vector3d v23 = Av.u2 - cv;\n    Eigen::Vector3d v33 = Av.u3 - cv;\n    Eigen::Vector3d v43 = Av.u4 - cv;\n\n    Eigen::Vector2d v1(v13[0]/v13[2],v13[1]/v13[2]);\n    Eigen::Vector2d v2(v23[0]/v23[2],v23[1]/v23[2]);\n    Eigen::Vector2d v3(v33[0]/v33[2],v33[1]/v33[2]);\n    Eigen::Vector2d v4(v43[0]/v43[2],v43[1]/v43[2]);\n\n    std::vector<cv::Point2f> srcPoints(4);\n    std::vector<cv::Point2f> dstPoints(4);\n    srcPoints[0] = cv::Point2f(u1(0),u1(1));\n    srcPoints[1] = cv::Point2f(u2(0),u2(1));\n    srcPoints[2] = cv::Point2f(u3(0),u3(1));\n    srcPoints[3] = cv::Point2f(u4(0),u4(1));\n    dstPoints[0] = cv::Point2f(v1(0),v1(1));\n    dstPoints[1] = cv::Point2f(v2(0),v2(1));\n    dstPoints[2] = cv::Point2f(v3(0),v3(1));\n    dstPoints[3] = cv::Point2f(v4(0),v4(1));\n    cv::Mat Hmat = cv::findHomography(srcPoints, dstPoints);\n    Eigen::MatrixXf H(3,3);\n    for ( int i = 0; i < 3; i++ )\n        for ( int j = 0; j < 3; j++ )\n            H(i,j) = Hmat.at<double>(i,j);\n\n    float s = H(2,0) * center_v(0) + H(2,1) * center_v(1) + H(2,2) ;\n\n    Eigen::Matrix2d affine_matrix;\n\n    affine_matrix << (H(0,0) - H(2,0) * v1(0))/s ,\n                     (H(0,1) - H(2,1) * v1(0))/s,\n                     (H(1,0) - H(2,0) * v1(1))/s,\n                     (H(1,1) - H(2,1) * v1(1))/s;\n\n    return affine_matrix;\n}\n\n\nEigen::Vector3d add_noise(Eigen::Vector3d p, Eigen::Vector2d noise)\n{\n    double unorm = p.norm();\n    Eigen::Vector3d uproj = p/p(2);\n    uproj.head(2) += noise;\n    uproj /= uproj.norm();\n    uproj *= unorm;\n    if ( p.dot(uproj) < 0 ) uproj = -uproj;\n\n    return uproj;\n}\n\nEigen::Vector2d generate_noise(double noise)\n{\n    return grand2f()*noise;\n}\n\nAffineRegion generateAffineRegion(Eigen::Vector3d X)\n{\n    const double R = -.01;\n    AffineRegion a;\n    a.X = X;\n    a.u1 = offset(X,-R,-R);\n    a.u2 = offset(X,R,-R);\n    a.u3 = offset(X,-R,R);\n    a.u4 = offset(X,R,R);\n    return a;\n}\n\nvoid generateAffineProblem( double trans_mag, double angle, double noise, double affine_noise, AffineProblem &prob, int nrays )\n{\n    Eigen::Vector3d X;    // 3D point\n    Eigen::Vector3d cu;   // camera center for first multi-camera rig\n    Eigen::Vector3d cv;   // camera center for second multi-camera rig\n    Eigen::Vector3d PX;   // 3D point after R,t transformation\n    AffineRay u;          // observations in first multi-camera rig (Pluecker line + affine)\n    AffineRay v;          // observations in second multi-camera rig\n\n    AffineRegion A1;      // affine region in first camera\n    AffineRegion A2;      // affine region in second camera\n\n    Eigen::Vector3d w = rand3f();  // make random axis for rotation\n    w = w/w.norm();                // normalize rotation axis\n    double theta = angle*M_PI/180; // make random angle for rotation\n    prob.R = so3exp(w*theta);                // random rotation\n    prob.t = rand3f();                       // random translation\n    while ( prob.t.norm() < 1e-10 ) prob.t = rand3f();  // ensure translation is not all zeros\n\n    prob.ray_pairs.clear(); // clear out ray pairs to be safe\n\n    // generate observations\n    for ( size_t i = 0; i < nrays; i++ )\n    {\n        X = rand3f();                          // sample random point\n        while ( X.norm() == 0 ) X = rand3f();  // ensure point is not all zeros\n        X(2) = 4.;\n        X = X/X.norm();                        // normalize point\n        double scale_factor = ((double)rand()/RAND_MAX) * 4 + 4;\n        X *= scale_factor;                     // stretch point out to distance in range [4,8]\n\n        A1 = generateAffineRegion(X);     // generate affine region\n\n        cu = rand3f();        // sample random camera locations\n        cv = rand3f();        // inter-camera\n        //cv = cu;            // intra-camera: camera center is same in both rigs\n\n        PX = prob.R*X+prob.t;    // transform point to second rig's frame\n        A2.X = PX;               // transform affine region\n        A2.u1 = prob.R*A1.u1+prob.t;\n        A2.u2 = prob.R*A1.u2+prob.t;\n        A2.u3 = prob.R*A1.u3+prob.t;\n        A2.u4 = prob.R*A1.u4+prob.t;\n\n        // affine matrix for first rig is identity\n        u.x = X-cu;\n        u.c = cu;\n        u.A << 1, 0,\n               0, 1;\n\n        // calculate relative affine matrix for second rig\n        v.x = PX-cv;\n        v.c = cv;\n        v.A = getRelativeAffineMatrix(A1, A2, cu, cv);\n\n        if ( noise > 0. )    // add noise with requested standard deviation\n        {\n            // add gaussian noise to center points\n            u.x = add_noise(u.x, generate_noise(noise));\n            v.x = add_noise(v.x, generate_noise(noise));\n        }\n\n        if ( affine_noise > 0. )\n        {\n            // add gaussian noise to affine parameters\n            v.A(0,0) += grandf()*affine_noise;\n            v.A(0,1) += grandf()*affine_noise;\n            v.A(1,0) += grandf()*affine_noise;\n            v.A(1,1) += grandf()*affine_noise;\n        }\n\n        // store observation\n        prob.ray_pairs.push_back( AffineRayPair( u, v ) );\n    }\n}\n\n\n", "meta": {"hexsha": "283a1c910974385376f31095ad840973a3bcb97d", "size": 6407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/affine_problem.cpp", "max_stars_repo_name": "MikhailTerekhov/multi-camera-motion", "max_stars_repo_head_hexsha": "acefa9e9b659b46dfee48b5091a8acb0ff5a0ecf", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2016-07-25T12:28:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T03:51:27.000Z", "max_issues_repo_path": "test/affine_problem.cpp", "max_issues_repo_name": "MikhailTerekhov/multi-camera-motion", "max_issues_repo_head_hexsha": "acefa9e9b659b46dfee48b5091a8acb0ff5a0ecf", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-09-18T15:42:27.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-20T03:27:25.000Z", "max_forks_repo_path": "test/affine_problem.cpp", "max_forks_repo_name": "MikhailTerekhov/multi-camera-motion", "max_forks_repo_head_hexsha": "acefa9e9b659b46dfee48b5091a8acb0ff5a0ecf", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-02-27T11:32:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T23:12:17.000Z", "avg_line_length": 33.5445026178, "max_line_length": 127, "alphanum_fraction": 0.5648509443, "num_tokens": 2102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5136718912558051}}
{"text": "#include \"teca_vorticity.h\"\n\n#include \"teca_cartesian_mesh.h\"\n#include \"teca_array_collection.h\"\n#include \"teca_variant_array.h\"\n#include \"teca_metadata.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <cmath>\n\n#if defined(TECA_HAS_BOOST)\n#include <boost/program_options.hpp>\n#endif\n\nusing std::string;\nusing std::vector;\nusing std::cerr;\nusing std::endl;\nusing std::cos;\n\n//#define TECA_DEBUG\n\nnamespace {\n\ntemplate <typename num_t>\nconstexpr num_t deg_to_rad() { return num_t(M_PI)/num_t(180); }\n\ntemplate <typename num_t>\nconstexpr num_t earth_radius() { return num_t(6371.0e3); }\n\n// compute vorticicty\n// this is based on TECA 1's calculation, and hence\n// assumes fixed mesh spacing. here we add periodic bc in lon\n// and apply unit stride vector optimization strategy to loops\ntemplate <typename num_t, typename pt_t>\nvoid vorticity(num_t *w, const pt_t *lon, const pt_t *lat,\n    const num_t *u, const num_t *v, unsigned long n_lon,\n    unsigned long n_lat, bool periodic_lon=true)\n{\n    size_t n_bytes = n_lat*sizeof(num_t);\n    num_t *delta_u = static_cast<num_t*>(malloc(n_bytes));\n\n    // delta lon as a function of latitude\n    num_t d_lon = (lon[1] - lon[0]) * deg_to_rad<num_t>() * earth_radius<num_t>();\n    for (unsigned long j = 0; j < n_lat; ++j)\n        delta_u[j] = d_lon * cos(lat[j] * deg_to_rad<num_t>());\n\n    // delta lat\n    num_t delta_v = (lat[1] - lat[0]) * deg_to_rad<num_t>() * earth_radius<num_t>();\n    num_t dv = num_t(2)*delta_v;\n\n    unsigned long max_i = n_lon - 1;\n    unsigned long max_j = n_lat - 1;\n\n    // vorticity\n    for (unsigned long j = 1; j < max_j; ++j)\n    {\n        unsigned long jj = j*n_lon;\n        const num_t *uu_2 = u + jj + n_lon;\n        const num_t *uu_0 = u + jj - n_lon;\n        const num_t *vv_2 = v + jj + 1;\n        const num_t *vv_0 = v + jj - 1;\n        num_t *ww = w + jj;\n        num_t du = num_t(2)*delta_u[j];\n\n        for (unsigned long i = 1; i < max_i; ++i)\n        {\n            ww[i] = (vv_2[i] - vv_0[i]) / du -\n                    (uu_2[i] - uu_0[i]) / dv ;\n        }\n    }\n\n    if (periodic_lon)\n    {\n        // periodic in longitude\n        for (unsigned long j = 1; j < max_j; ++j)\n        {\n            unsigned long jj = j*n_lon;\n            const num_t *uu_2 = u + jj + n_lon;\n            const num_t *uu_0 = u + jj - n_lon;\n            const num_t *vv_2 = v + jj + 1;\n            const num_t *vv_0 = v + jj + max_i;\n            num_t *ww = w + jj;\n            num_t du = num_t(2)*delta_u[j];\n\n            ww[0] = (vv_2[0] - vv_0[0]) / du -\n                    (uu_2[0] - uu_0[0]) / dv ;\n        }\n\n        for (unsigned long j = 1; j < max_j; ++j)\n        {\n            unsigned long jj = j*n_lon;\n            const num_t *uu_2 = u + jj + max_i + n_lon;\n            const num_t *uu_0 = u + jj + max_i - n_lon;\n            const num_t *vv_2 = v + jj;\n            const num_t *vv_0 = v + jj + max_i - 1;\n            num_t *ww = w + jj + max_i;\n            num_t du = num_t(2)*delta_u[j];\n\n            ww[0] = (vv_2[0] - vv_0[0]) / du -\n                    (uu_2[0] - uu_0[0]) / dv ;\n        }\n    }\n    else\n    {\n        // zero it out\n        for (unsigned long j = 1; j < max_j; ++j)\n            w[j*n_lon] = num_t();\n\n        for (unsigned long j = 1; j < max_j; ++j)\n            w[j*n_lon + max_i] = num_t();\n    }\n\n    // extend values into lat boundaries\n    num_t *dest = w;\n    num_t *src = w + n_lon;\n    for (unsigned long i = 0; i < n_lon; ++i)\n        dest[i] = src[i+n_lon];\n\n    dest = w + max_j*n_lon;\n    src = dest - n_lon;\n    for (unsigned long i = 0; i < n_lon; ++i)\n        dest[i] = src[i];\n\n    free(delta_u);\n\n    return;\n}\n};\n\n\n// --------------------------------------------------------------------------\nteca_vorticity::teca_vorticity() :\n    component_0_variable(), component_1_variable(),\n    vorticity_variable(\"vorticity\")\n{\n    this->set_number_of_input_connections(1);\n    this->set_number_of_output_ports(1);\n}\n\n// --------------------------------------------------------------------------\nteca_vorticity::~teca_vorticity()\n{}\n\n#if defined(TECA_HAS_BOOST)\n// --------------------------------------------------------------------------\nvoid teca_vorticity::get_properties_description(\n    const string &prefix, options_description &global_opts)\n{\n    options_description opts(\"Options for \"\n        + (prefix.empty()?\"teca_vorticity\":prefix));\n\n    opts.add_options()\n        TECA_POPTS_GET(std::string, prefix, component_0_variable,\n            \"array containg lon component of the vector\")\n        TECA_POPTS_GET(std::string, prefix, component_1_variable,\n            \"array containg lat component of the vector\")\n        TECA_POPTS_GET(std::string, prefix, vorticity_variable,\n            \"array to store the computed vorticity in\")\n        ;\n\n    global_opts.add(opts);\n}\n\n// --------------------------------------------------------------------------\nvoid teca_vorticity::set_properties(\n    const string &prefix, variables_map &opts)\n{\n    TECA_POPTS_SET(opts, std::string, prefix, component_0_variable)\n    TECA_POPTS_SET(opts, std::string, prefix, component_1_variable)\n    TECA_POPTS_SET(opts, std::string, prefix, vorticity_variable)\n}\n#endif\n\n// --------------------------------------------------------------------------\nstd::string teca_vorticity::get_component_0_variable(\n    const teca_metadata &request)\n{\n    std::string comp_0_var = this->component_0_variable;\n\n    if (comp_0_var.empty() &&\n        request.has(\"teca_vorticity::component_0_variable\"))\n            request.get(\"teca_vorticity::component_0_variable\", comp_0_var);\n\n    return comp_0_var;\n}\n\n// --------------------------------------------------------------------------\nstd::string teca_vorticity::get_component_1_variable(\n    const teca_metadata &request)\n{\n    std::string comp_1_var = this->component_1_variable;\n\n    if (comp_1_var.empty() &&\n        request.has(\"teca_vorticity::component_1_variable\"))\n            request.get(\"teca_vorticity::component_1_variable\", comp_1_var);\n\n    return comp_1_var;\n}\n\n// --------------------------------------------------------------------------\nstd::string teca_vorticity::get_vorticity_variable(\n    const teca_metadata &request)\n{\n    std::string vort_var = this->vorticity_variable;\n\n    if (vort_var.empty())\n    {\n        if (request.has(\"teca_vorticity::vorticity_variable\"))\n            request.get(\"teca_vorticity::vorticity_variable\", vort_var);\n        else\n            vort_var = \"vorticity\";\n    }\n\n    return vort_var;\n}\n\n// --------------------------------------------------------------------------\nteca_metadata teca_vorticity::get_output_metadata(\n    unsigned int port,\n    const std::vector<teca_metadata> &input_md)\n{\n#ifdef TECA_DEBUG\n    cerr << teca_parallel_id()\n        << \"teca_vorticity::get_output_metadata\" << endl;\n#endif\n    (void)port;\n\n    // add in the array we will generate\n    teca_metadata out_md(input_md[0]);\n    out_md.append(\"variables\", this->vorticity_variable);\n\n    return out_md;\n}\n\n// --------------------------------------------------------------------------\nstd::vector<teca_metadata> teca_vorticity::get_upstream_request(\n    unsigned int port,\n    const std::vector<teca_metadata> &input_md,\n    const teca_metadata &request)\n{\n    (void)port;\n    (void)input_md;\n\n    vector<teca_metadata> up_reqs;\n\n    // get the name of the arrays we need to request\n    std::string comp_0_var = this->get_component_0_variable(request);\n    if (comp_0_var.empty())\n    {\n        TECA_ERROR(\"component 0 array was not specified\")\n        return up_reqs;\n    }\n\n    std::string comp_1_var = this->get_component_1_variable(request);\n    if (comp_1_var.empty())\n    {\n        TECA_ERROR(\"component 0 array was not specified\")\n        return up_reqs;\n    }\n\n    // copy the incoming request to preserve the downstream\n    // requirements and add the arrays we need\n    teca_metadata req(request);\n\n    std::set<std::string> arrays;\n    if (req.has(\"arrays\"))\n        req.get(\"arrays\", arrays);\n\n    arrays.insert(this->component_0_variable);\n    arrays.insert(this->component_1_variable);\n\n    // capture the array we produce\n    arrays.erase(this->get_vorticity_variable(request));\n\n    // update the request\n    req.set(\"arrays\", arrays);\n\n    // send it up\n    up_reqs.push_back(req);\n    return up_reqs;\n}\n\n// --------------------------------------------------------------------------\nconst_p_teca_dataset teca_vorticity::execute(\n    unsigned int port,\n    const std::vector<const_p_teca_dataset> &input_data,\n    const teca_metadata &request)\n{\n#ifdef TECA_DEBUG\n    cerr << teca_parallel_id()\n        << \"teca_vorticity::execute\" << endl;\n#endif\n    (void)port;\n\n    // get the input mesh\n    const_p_teca_cartesian_mesh in_mesh\n        = std::dynamic_pointer_cast<const teca_cartesian_mesh>(input_data[0]);\n\n    if (!in_mesh)\n    {\n        TECA_ERROR(\"teca_cartesian_mesh is required\")\n        return nullptr;\n    }\n\n    // get component 0 array\n    std::string comp_0_var = this->get_component_0_variable(request);\n\n    if (comp_0_var.empty())\n    {\n        TECA_ERROR(\"component_0_variable was not specified\")\n        return nullptr;\n    }\n\n    const_p_teca_variant_array comp_0\n        = in_mesh->get_point_arrays()->get(comp_0_var);\n\n    if (!comp_0)\n    {\n        TECA_ERROR(\"requested array \\\"\" << comp_0_var << \"\\\" not present.\")\n        return nullptr;\n    }\n\n    // get component 1 array\n    std::string comp_1_var = this->get_component_1_variable(request);\n\n    if (comp_1_var.empty())\n    {\n        TECA_ERROR(\"component_1_variable was not specified\")\n        return nullptr;\n    }\n\n    const_p_teca_variant_array comp_1\n        = in_mesh->get_point_arrays()->get(comp_1_var);\n\n    if (!comp_1)\n    {\n        TECA_ERROR(\"requested array \\\"\" << comp_1_var << \"\\\" not present.\")\n        return nullptr;\n    }\n\n    // get the input coordinate arrays\n    const_p_teca_variant_array lon = in_mesh->get_x_coordinates();\n    const_p_teca_variant_array lat = in_mesh->get_y_coordinates();\n\n    if (!lon || !lat)\n    {\n        TECA_ERROR(\"lat lon mesh cooridinates not present.\")\n        return nullptr;\n    }\n\n    // allocate the output array\n    p_teca_variant_array vort = comp_0->new_instance();\n    vort->resize(comp_0->size());\n\n    // compute vorticity\n    NESTED_TEMPLATE_DISPATCH_FP(\n        const teca_variant_array_impl,\n        lon.get(), 1,\n\n        const NT1 *p_lon = dynamic_cast<const TT1*>(lon.get())->get();\n        const NT1 *p_lat = dynamic_cast<const TT1*>(lat.get())->get();\n\n        NESTED_TEMPLATE_DISPATCH_FP(\n            teca_variant_array_impl,\n            vort.get(), 2,\n\n            const NT2 *p_comp_0 = dynamic_cast<const TT2*>(comp_0.get())->get();\n            const NT2 *p_comp_1 = dynamic_cast<const TT2*>(comp_1.get())->get();\n            NT2 *p_vort = dynamic_cast<TT2*>(vort.get())->get();\n\n            ::vorticity(p_vort, p_lon, p_lat,\n                p_comp_0, p_comp_1, lon->size(), lat->size());\n            )\n        )\n\n    // create the output mesh, pass everything through, and\n    // add the vorticity array\n    p_teca_cartesian_mesh out_mesh = teca_cartesian_mesh::New();\n\n    out_mesh->shallow_copy(\n        std::const_pointer_cast<teca_cartesian_mesh>(in_mesh));\n\n    out_mesh->get_point_arrays()->append(\n        this->get_vorticity_variable(request), vort);\n\n    return out_mesh;\n}\n", "meta": {"hexsha": "66fcf21d7c7550365cfa2e4513394c255b3d593f", "size": 11345, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "alg/teca_vorticity.cxx", "max_stars_repo_name": "mhaseeb123/TECA", "max_stars_repo_head_hexsha": "4233bac9dd2a86da3848ae088b462b4544b3ddc7", "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": "alg/teca_vorticity.cxx", "max_issues_repo_name": "mhaseeb123/TECA", "max_issues_repo_head_hexsha": "4233bac9dd2a86da3848ae088b462b4544b3ddc7", "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": "alg/teca_vorticity.cxx", "max_forks_repo_name": "mhaseeb123/TECA", "max_forks_repo_head_hexsha": "4233bac9dd2a86da3848ae088b462b4544b3ddc7", "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": 29.0153452685, "max_line_length": 84, "alphanum_fraction": 0.5826355223, "num_tokens": 2964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5135928234048189}}
{"text": "// BoostMath.hpp\r\n//\r\n// (C) Datasim Education BV  2009\r\n\r\n\r\n#pragma once\r\n\r\n#include \"UniformDistribution.hpp\"\r\n#include \"BernoulliDistribution.hpp\"\r\n#include \"ChiSquaredDistribution.hpp\"\r\n#include \"NonCentralChiSquaredDistribution.hpp\"\r\n\r\n#include <boost/math/distributions.hpp>\r\n\r\nusing namespace System;\r\n\r\nnamespace Wrapper \r\n{\r\n\r\n\t// Wrapper for the boost::math::uniform_ditribution class\r\n\t// We use the .NET naming conventions instead of the original C++ name\r\n\tpublic ref class BoostMath\r\n\t{\r\n\tprivate:\r\n\r\n\tpublic:\r\n\t\t// Because boost cdf, pdf etc. work with templates, we need to have overloads\r\n\t\t// for each type we pass to these functions. \r\n\t\t// In CLR we can not use templates, generics or base classes for this. (GetNative() can't return a base class since there is none)\r\n\r\n\r\n\t\tstatic double Cdf(UniformDistribution^ distribution, double x);\r\n\t\tstatic double Cdf(BernoulliDistribution^ distribution, double x);\r\n\t\tstatic double Cdf(ChiSquaredDistribution^ distribution, double x);\r\n\t\tstatic double Cdf(NonCentralChiSquaredDistribution^ distribution, double x);\r\n\r\n\t\tstatic double Pdf(UniformDistribution^ distribution, double x);\r\n\t\tstatic double Pdf(BernoulliDistribution^ distribution, double x);\r\n\t\tstatic double Pdf(ChiSquaredDistribution^ distribution, double x);\r\n\t\tstatic double Pdf(NonCentralChiSquaredDistribution^ distribution, double x);\r\n\r\n\t\tstatic double Quantile(UniformDistribution^ distribution, double x);\r\n\t\tstatic double Quantile(BernoulliDistribution^ distribution, double x);\r\n\t\tstatic double Quantile(ChiSquaredDistribution^ distribution, double x);\r\n\t\tstatic double Quantile(NonCentralChiSquaredDistribution^ distribution, double x);\r\n\t};\r\n}\r\n", "meta": {"hexsha": "af603a23f5cbd2141b41dd933928f777046ca9de", "size": 1683, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI Interop Test (Chi-Squared)/Wrapper/BoostMath.hpp", "max_stars_repo_name": "jdm7dv/financial", "max_stars_repo_head_hexsha": "673a552d58751643dbca0ba633aeff119eda107d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T06:54:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T06:54:08.000Z", "max_issues_repo_path": "windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI Interop Test (Chi-Squared)/Wrapper/BoostMath.hpp", "max_issues_repo_name": "jdm7dv/financial", "max_issues_repo_head_hexsha": "673a552d58751643dbca0ba633aeff119eda107d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI Interop Test (Chi-Squared)/Wrapper/BoostMath.hpp", "max_forks_repo_name": "jdm7dv/financial", "max_forks_repo_head_hexsha": "673a552d58751643dbca0ba633aeff119eda107d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-19T19:27:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T06:26:06.000Z", "avg_line_length": 35.0625, "max_line_length": 133, "alphanum_fraction": 0.761734997, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5135928201466387}}
{"text": "#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n\n#include <scitbx/math/zernike.h>\n#include <scitbx/math/2d_zernike_moments.h>\n\nnamespace scitbx { namespace math {\nnamespace {\n\n  struct two_d_voxel_wrapper\n  {\n    typedef voxel_2d <double> w_t;\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"two_d_voxel\", no_init)\n        .def( init<\n                   int const&,\n                   double const&,\n                   double const&,\n                   double const&,\n                   scitbx::af::const_ref< scitbx::vec3<double> >\n                  >\n             ((\n                arg(\"splat_range\"),\n                arg(\"external_rmax\"),\n                arg(\"dx\"),\n                arg(\"fraction\"),\n                arg(\"xyz\")\n             ))\n            )\n        .def(\"rmax\", &w_t::rmax)\n        .def(\"np\", &w_t::np)\n        .def(\"get_image\", &w_t::get_image)\n        .def(\"get_value\", &w_t::get_value)\n      ;\n    }\n  };\n\n//\n//\n  struct two_d_grid_wrapper\n  {\n    typedef grid_2d  < double > w_t;\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"two_d_grid\", no_init)\n        .def( init<\n                   int const&,\n                   int const&\n                  >\n             ((\n                arg(\"np\"),\n                arg(\"n_max\")\n             ))\n            )\n        .def(\"get_ss\", &w_t::get_ss)\n        .def(\"get_ss\", &w_t::get_all_ss)\n        .def(\"clean_space\", &w_t::clean_space)\n        .def(\"construct_space_sum\",&w_t::construct_space_sum)\n      ;\n    }\n  };\n\n//\n//\n  struct two_d_moments_wrapper\n  {\n    typedef zernike_2d_moments  < double > w_t;\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"two_d_zernike_moments\", no_init)\n        .def( init<\n                   grid_2d< double >,\n                   int const&\n                  >\n             ((\n                arg(\"grid\"),\n                arg(\"nmax\")\n             ))\n            )\n        .def(\"moments\", &w_t::all_moments)\n        .def(\"nm\", &w_t::nm)\n        .def(\"get_moment\",&w_t::get_moment)\n        .def(\"calc_moments\",&w_t::calc_moments)\n        .def(\"update_ss\",&w_t::update_ss)\n        .def(\"print_bnmk\",&w_t::print_Bnmk)\n        .def(\"zernike_poly\",&w_t::zernike_poly)\n        .def(\"zernike_map\",&w_t::zernike_map)\n      ;\n    }\n  };\n\n//\n//\n\n} //namespace <anonymous>\n\nnamespace boost_python {\n\n  void wrap_2d_zernike_mom()\n  {\n    two_d_voxel_wrapper::wrap();\n    two_d_moments_wrapper::wrap();\n    two_d_grid_wrapper::wrap();\n  }\n\n}}}\n", "meta": {"hexsha": "66d8edb11c7c88f8d4835b8f5287fcdff2b4cc18", "size": 2607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/math/boost_python/2d_zernike_moments.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/math/boost_python/2d_zernike_moments.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/math/boost_python/2d_zernike_moments.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 22.6695652174, "max_line_length": 64, "alphanum_fraction": 0.4852320675, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5135928201466387}}
{"text": "/*!\n *\n * \\file affine_transform.hpp\n *\n * \\brief File containing n-dimensional affine transformation functions\n *        that can be combined with various interpolation and boundary\n *        functions.\n *\n *\n */\n#pragma once\n#include <array>\n#include <tuple>\n\n#include <Eigen/Dense>\n#include <pybind11/eigen.h>\n#include <pybind11/numpy.h>\n#include <pybind11/pybind11.h>\n\n#include \"interpolation.hpp\"\n\n/*! \\brief Namespace containing affine transform functionality\n *         for transforming n-dimnesional data.\n */\nnamespace affine_transform\n{\n/*! \\brief Namespace containing implementation details for the affine\n *         transformation functionality.\n */\nnamespace detail\n{\n/*! \\brief Inner For loop of the transform function.\n *\n *  Loops over the dimensions of the output image and fills it\n *  using the given interpolation and boundary functions to look\n *  up values in the given input image.\n *\n *  @param[in] point            The point from which to start to loop\n *                              in the input image coordinate system\n *  @param[in] input_image      The image from which to extract values\n *  @param[in,out] output_image The image to write to\n *  @param[in] dx               The vectors along which to iterate to\n *                              fill the output image\n *  @param[in,out] chunk        A temporary memory object which is used\n *                              to call the interpolation function\n *  @param[in] background_value A background value to use when accessing\n *                              points outside the input image. (might get\n *                              ignored by some boundary functions)\n *  @param[in] begin            The starting index of the first dimension\n *                              (can be used to parallelise the transform)\n *  @param[in] end              The end index of the first dimension\n *                              (can be used to parallelise the transform)\n *  @param[in] xs               Loop variables used to access the n-dimensional\n *                              data\n *\n *  @tparam Dim                 The dimensions of the images\n *  @tparam T                   The data type of the images\n *  @tparam Func                The interpolation order function\n *  @tparam BoundaryFunc        The boundary function to use\n *  @tparam Xs                  The loop indices, will be int\n */\ntemplate <int Dim, typename T, typename Func, typename BoundaryFunc,\n          typename... Xs>\nconstexpr void transform_loop(\n    Eigen::Matrix<double, Dim, 1> point,\n    const pybind11::detail::unchecked_reference<T, Dim>& input_image,\n    pybind11::detail::unchecked_mutable_reference<T, Dim>& output_image,\n    const std::array<Eigen::Matrix<double, Dim, 1>, Dim>& dx,\n    interpolation::Data<Func, Dim>& chunk, T background_value, int begin,\n    int end, Xs... xs)\n{\n    for (int i = begin; i < end; ++i)\n    {\n        /* We are in the inner-most loop*/\n        if constexpr (Dim == sizeof...(xs) + 1)\n        {\n            auto x_lower = std::array<int, Dim>{};\n            auto x_relative = std::array<double, Dim>{};\n            for (size_t l = 0; l < Dim; ++l)\n            {\n                x_lower[l] = point(l) - (point(l) < 0);\n                x_relative[l] = point(l) - x_lower[l];\n            }\n\n            interpolation::extract<Func, BoundaryFunc, Dim>(\n                chunk, input_image, x_lower, background_value);\n\n            auto interpolate = [&chunk](auto... args) {\n                return interpolation::apply_func(chunk, args...);\n            };\n\n            output_image(xs..., i) = std::apply(interpolate, x_relative);\n        }\n        /* Start more loops to iterate over the N-dimensional data*/\n        else\n        {\n            transform_loop<Dim, T, Func, BoundaryFunc>(\n                point, input_image, output_image, dx, chunk, background_value,\n                0, output_image.shape(sizeof...(xs) + 1), xs..., i);\n        }\n        point += dx[sizeof...(xs)];\n    }\n}\n}; // namespace detail\n\n/*! \\brief Extracts an image from a given one with a given\n *         coordinate system.\n *\n *  @param[in] origin            The origin of the coordinate system for the\n *                               resulting image in the coordinate system of\n *                               the input system.\n *  @param[in] dx                The vectors of the coordinate system of the\n *                               resulting image in the coordinate system of the\n *                               input system.\n *  @param[in] input_image       The image from which to extract data\n *  @param[in,out] output_image  The image in which to store the results\n *  @param[in] background_value  The value to use for points outside the input\n *                               image's domain. Might be ignored by some\n *                               boundary functions.\n *\n *  @tparam Dim                  The dimensionality of the image data\n *  @tparam T                    The datatype of the image data\n *  @tparam Func                 The interpolation order to use\n *  @tparam BoundaryFunc         The boundary function to use\n */\ntemplate <int Dim, typename T, template <typename> typename Func,\n          typename BoundaryFunc>\nvoid transform(const Eigen::Matrix<double, Dim, 1>& origin,\n               const std::array<Eigen::Matrix<double, Dim, 1>, Dim>& dx,\n               const pybind11::array_t<T>& input_image,\n               pybind11::array_t<T>& output_image, T background_value)\n{\n    auto input = input_image.template unchecked<Dim>();\n    auto output = output_image.template mutable_unchecked<Dim>();\n\n#pragma omp parallel\n    {\n        typedef Func<T> _Func;\n\n        interpolation::Data<_Func, Dim> chunk;\n\n        int x_len = output.shape(0) / omp_get_num_threads();\n        int x_start = x_len * omp_get_thread_num();\n        int x_end = x_start + x_len;\n\n        Eigen::Matrix<double, Dim, 1> local_origin = origin + x_start * dx[0];\n        if (omp_get_thread_num() == omp_get_num_threads() - 1)\n        {\n            x_end = output.shape(0);\n        }\n        detail::transform_loop<Dim, T, _Func, BoundaryFunc>(\n            local_origin, input, output, dx, chunk, background_value, x_start,\n            x_end);\n    }\n}\n\n}; // namespace affine_transform", "meta": {"hexsha": "5f6e3eaece2c54667cbdea0db18bddac1bd03759", "size": 6268, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/affine_transform/affine_transform.hpp", "max_stars_repo_name": "NOhs/affine_transform_nd", "max_stars_repo_head_hexsha": "3f90c7a4d72616e7a6e7bf1b5cff8b7990ed40ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-09T15:19:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T15:19:17.000Z", "max_issues_repo_path": "include/affine_transform/affine_transform.hpp", "max_issues_repo_name": "NOhs/affine_transform_nd", "max_issues_repo_head_hexsha": "3f90c7a4d72616e7a6e7bf1b5cff8b7990ed40ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2019-07-22T20:09:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-27T08:12:20.000Z", "max_forks_repo_path": "include/affine_transform/affine_transform.hpp", "max_forks_repo_name": "NOhs/affine_transform_nd", "max_forks_repo_head_hexsha": "3f90c7a4d72616e7a6e7bf1b5cff8b7990ed40ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-22T21:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-22T21:12:40.000Z", "avg_line_length": 39.923566879, "max_line_length": 80, "alphanum_fraction": 0.5867900447, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5135928182835064}}
{"text": "//  (C) Copyright John Maddock 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#include <boost/math/tools/fraction.hpp>\n#include <iostream>\n#include <complex>\n\n//[golden_ratio_1\ntemplate <class T>\nstruct golden_ratio_fraction\n{\n   typedef T result_type;\n\n   result_type operator()()\n   {\n      return 1;\n   }\n};\n//]\n\n//[cf_tan_fraction\ntemplate <class T>\nstruct tan_fraction\n{\nprivate:\n   T a, b;\npublic:\n   tan_fraction(T v)\n      : a(-v * v), b(-1)\n   {}\n\n   typedef std::pair<T, T> result_type;\n\n   std::pair<T, T> operator()()\n   {\n      b += 2;\n      return std::make_pair(a, b);\n   }\n};\n//]\n//[cf_tan\ntemplate <class T>\nT tan(T a)\n{\n   tan_fraction<T> fract(a);\n   return a / continued_fraction_b(fract, std::numeric_limits<T>::epsilon());\n}\n//]\n//[cf_expint_fraction\ntemplate <class T>\nstruct expint_fraction\n{\n   typedef std::pair<T, T> result_type;\n   expint_fraction(unsigned n_, T z_) : b(z_ + T(n_)), i(-1), n(n_) {}\n   std::pair<T, T> operator()()\n   {\n      std::pair<T, T> result = std::make_pair(-static_cast<T>((i + 1) * (n + i)), b);\n      b += 2;\n      ++i;\n      return result;\n   }\nprivate:\n   T b;\n   int i;\n   unsigned n;\n};\n//]\n//[cf_expint\ntemplate <class T>\ninline std::complex<T> expint_as_fraction(unsigned n, std::complex<T> const& z)\n{\n   boost::uintmax_t max_iter = 1000;\n   expint_fraction<std::complex<T> > f(n, z);\n   std::complex<T> result = boost::math::tools::continued_fraction_b(\n      f,\n      std::complex<T>(std::numeric_limits<T>::epsilon()),\n      max_iter);\n   result = exp(-z) / result;\n   return result;\n}\n//]\n//[cf_upper_gamma_fraction\ntemplate <class T>\nstruct upper_incomplete_gamma_fract\n{\nprivate:\n   typedef typename T::value_type scalar_type;\n   T z, a;\n   int k;\npublic:\n   typedef std::pair<T, T> result_type;\n\n   upper_incomplete_gamma_fract(T a1, T z1)\n      : z(z1 - a1 + scalar_type(1)), a(a1), k(0)\n   {\n   }\n\n   result_type operator()()\n   {\n      ++k;\n      z += scalar_type(2);\n      return result_type(scalar_type(k) * (a - scalar_type(k)), z);\n   }\n};\n//]\n//[cf_gamma_Q\ntemplate <class T>\ninline std::complex<T> gamma_Q_as_fraction(const std::complex<T>& a, const std::complex<T>& z)\n{\n   upper_incomplete_gamma_fract<std::complex<T> > f(a, z);\n   std::complex<T> eps(std::numeric_limits<T>::epsilon());\n   return pow(z, a) / (exp(z) *(z - a + T(1) + boost::math::tools::continued_fraction_a(f, eps)));\n}\n//]\n\n\nint main()\n{\n   using namespace boost::math::tools;\n\n   //[cf_gr\n   golden_ratio_fraction<double> func;\n   double gr = continued_fraction_a(\n      func,\n      std::numeric_limits<double>::epsilon());\n   std::cout << \"The golden ratio is: \" << gr << std::endl;\n   //]\n\n   std::cout << tan(0.5) << std::endl;\n\n   std::complex<double> arg(3, 2);\n   std::cout << expint_as_fraction(5, arg) << std::endl;\n\n   std::complex<double> a(3, 3), z(3, 2);\n   std::cout << gamma_Q_as_fraction(a, z) << std::endl;\n\n   return 0;\n}\n", "meta": {"hexsha": "4a07cd7c0ba26c034e45c2522553f4e62ef76015", "size": 3042, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/continued_fractions.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/continued_fractions.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/continued_fractions.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": 21.5744680851, "max_line_length": 98, "alphanum_fraction": 0.6193293886, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5135928080408816}}
{"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 variable class.\n */\n#include \"num_collect/auto_diff/backward/variable.h\"\n\n#include <Eigen/Core>\n#include <catch2/catch_template_test_macros.hpp>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\n// NOLINTNEXTLINE\nTEMPLATE_TEST_CASE(\n    \"num_collect::auto_diff::backward::variable\", \"\", float, double) {\n    using scalar_type = TestType;\n    using variable_type =\n        num_collect::auto_diff::backward::variable<scalar_type>;\n    using num_collect::auto_diff::backward::constant_tag;\n    using num_collect::auto_diff::backward::variable_tag;\n\n    SECTION(\"construct with a node\") {\n        constexpr auto value = static_cast<scalar_type>(1.234);\n        const auto node =\n            num_collect::auto_diff::backward::graph::create_node<scalar_type>();\n\n        const auto var = variable_type(value, node);\n\n        REQUIRE(var.value() == value);\n        REQUIRE(var.node() == node);\n    }\n\n    SECTION(\"construct a constant\") {\n        constexpr auto value = static_cast<scalar_type>(1.234);\n\n        const auto var = variable_type(value, constant_tag());\n\n        REQUIRE(var.value() == value);\n        REQUIRE(var.node() == nullptr);\n    }\n\n    SECTION(\"construct a variable\") {\n        constexpr auto value = static_cast<scalar_type>(1.234);\n\n        const auto var = variable_type(value, variable_tag());\n\n        REQUIRE(var.value() == value);\n        REQUIRE(var.node() != nullptr);\n    }\n\n    SECTION(\"construct a constant without tags\") {\n        constexpr auto value = static_cast<scalar_type>(1.234);\n\n        const auto var = variable_type(value);\n\n        REQUIRE(var.value() == value);\n        REQUIRE(var.node() == nullptr);\n    }\n\n    SECTION(\"construct without arguments\") {\n        const auto var = variable_type();\n\n        REQUIRE(var.value() == static_cast<scalar_type>(0));\n        REQUIRE(var.node() == nullptr);\n    }\n\n    SECTION(\"construct with a node\") {\n        const auto orig =\n            variable_type(static_cast<scalar_type>(1.234), variable_tag());\n\n        const variable_type res = -orig;\n        REQUIRE_THAT(res.value(), Catch::Matchers::WithinRel(-orig.value()));\n        REQUIRE(res.node());\n        REQUIRE(res.node()->children().size() == 1);\n        REQUIRE(res.node()->children()[0].node() == orig.node());\n        REQUIRE_THAT(res.node()->children()[0].sensitivity(),\n            Catch::Matchers::WithinRel(static_cast<scalar_type>(-1)));\n    }\n}\n\n// NOLINTNEXTLINE\nTEMPLATE_TEST_CASE(\n    \"num_collect::auto_diff::backward::operator+\", \"\", float, double) {\n    using scalar_type = TestType;\n    using variable_type =\n        num_collect::auto_diff::backward::variable<scalar_type>;\n    using num_collect::auto_diff::backward::constant_tag;\n    using num_collect::auto_diff::backward::variable_tag;\n\n    SECTION(\"variable + variable\") {\n        const auto left =\n            variable_type(static_cast<scalar_type>(1.234), variable_tag());\n        const auto right =\n            variable_type(static_cast<scalar_type>(2.345), variable_tag());\n\n        const variable_type res = left + right;\n\n        REQUIRE_THAT(res.value(),\n            Catch::Matchers::WithinRel(left.value() + right.value()));\n        REQUIRE(res.node());\n        REQUIRE(res.node()->children().size() == 2);\n        REQUIRE(res.node()->children()[0].node() == left.node());\n        REQUIRE(res.node()->children()[1].node() == right.node());\n        REQUIRE_THAT(res.node()->children()[0].sensitivity(),\n            Catch::Matchers::WithinRel(static_cast<scalar_type>(1)));\n        REQUIRE_THAT(res.node()->children()[1].sensitivity(),\n            Catch::Matchers::WithinRel(static_cast<scalar_type>(1)));\n    }\n\n    SECTION(\"scalar + variable\") {\n        const auto left = static_cast<scalar_type>(1.234);\n        const auto right =\n            variable_type(static_cast<scalar_type>(2.345), variable_tag());\n\n        const variable_type res = left + right;\n\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(left + right.value()));\n        REQUIRE(res.node() == right.node());\n    }\n\n    SECTION(\"variable + scalar\") {\n        const auto left =\n            variable_type(static_cast<scalar_type>(1.234), variable_tag());\n        const auto right = static_cast<scalar_type>(2.345);\n\n        const variable_type res = left + right;\n\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(left.value() + right));\n        REQUIRE(res.node() == left.node());\n    }\n\n    SECTION(\"scalar + scalar\") {\n        const auto left =\n            variable_type(static_cast<scalar_type>(1.234), constant_tag());\n        const auto right = static_cast<scalar_type>(2.345);\n\n        const variable_type res = left + right;\n\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(left.value() + right));\n        REQUIRE(res.node() == nullptr);\n    }\n\n    SECTION(\"self assignment\") {\n        const auto orig =\n            variable_type(static_cast<scalar_type>(1.234), variable_tag());\n        auto var = orig;\n\n        var += var;\n\n        REQUIRE_THAT(var.value(),\n            Catch::Matchers::WithinRel(orig.value() + orig.value()));\n        REQUIRE(var.node());\n        REQUIRE(var.node()->children().size() == 1);\n        REQUIRE(var.node()->children()[0].node() == orig.node());\n        REQUIRE_THAT(var.node()->children()[0].sensitivity(),\n            Catch::Matchers::WithinRel(static_cast<scalar_type>(2)));\n    }\n}\n\n// NOLINTNEXTLINE\nTEMPLATE_TEST_CASE(\n    \"num_collect::auto_diff::backward::operator-\", \"\", float, double) {\n    using scalar_type = TestType;\n    using variable_type =\n        num_collect::auto_diff::backward::variable<scalar_type>;\n    using num_collect::auto_diff::backward::constant_tag;\n    using num_collect::auto_diff::backward::variable_tag;\n\n    SECTION(\"variable - variable\") {\n        const auto left =\n            variable_type(static_cast<scalar_type>(1.234), variable_tag());\n        const auto right =\n            variable_type(static_cast<scalar_type>(2.345), variable_tag());\n\n        const variable_type res = left - right;\n\n        REQUIRE_THAT(res.value(),\n            Catch::Matchers::WithinRel(left.value() - right.value()));\n        REQUIRE(res.node());\n        REQUIRE(res.node()->children().size() == 2);\n        REQUIRE(res.node()->children()[0].node() == left.node());\n        REQUIRE(res.node()->children()[1].node() == right.node());\n        REQUIRE_THAT(res.node()->children()[0].sensitivity(),\n            Catch::Matchers::WithinRel(static_cast<scalar_type>(1)));\n        REQUIRE_THAT(res.node()->children()[1].sensitivity(),\n            Catch::Matchers::WithinRel(static_cast<scalar_type>(-1)));\n    }\n\n    SECTION(\"scalar - variable\") {\n        const auto left = static_cast<scalar_type>(1.234);\n        const auto right =\n            variable_type(static_cast<scalar_type>(2.345), variable_tag());\n\n        const variable_type res = left - right;\n\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(left - right.value()));\n        REQUIRE(res.node());\n        REQUIRE(res.node()->children().size() == 1);\n        REQUIRE(res.node()->children()[0].node() == right.node());\n        REQUIRE_THAT(res.node()->children()[0].sensitivity(),\n            Catch::Matchers::WithinRel(static_cast<scalar_type>(-1)));\n    }\n\n    SECTION(\"variable - scalar\") {\n        const auto left =\n            variable_type(static_cast<scalar_type>(1.234), variable_tag());\n        const auto right = static_cast<scalar_type>(2.345);\n\n        const variable_type res = left - right;\n\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(left.value() - right));\n        REQUIRE(res.node() == left.node());\n    }\n\n    SECTION(\"scalar - scalar\") {\n        const auto left =\n            variable_type(static_cast<scalar_type>(1.234), constant_tag());\n        const auto right = static_cast<scalar_type>(2.345);\n\n        const variable_type res = left - right;\n\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(left.value() - right));\n        REQUIRE(res.node() == nullptr);\n    }\n\n    SECTION(\"self assignment\") {\n        const auto orig =\n            variable_type(static_cast<scalar_type>(1.234), variable_tag());\n        auto var = orig;\n\n        var -= var;  // NOLINT\n\n        REQUIRE(var.value() == static_cast<scalar_type>(0));\n        REQUIRE(var.node() == nullptr);\n    }\n}\n\n// NOLINTNEXTLINE\nTEMPLATE_TEST_CASE(\n    \"num_collect::auto_diff::backward::operator*\", \"\", float, double) {\n    using scalar_type = TestType;\n    using variable_type =\n        num_collect::auto_diff::backward::variable<scalar_type>;\n    using num_collect::auto_diff::backward::constant_tag;\n    using num_collect::auto_diff::backward::variable_tag;\n\n    SECTION(\"variable * variable\") {\n        const auto left =\n            variable_type(static_cast<scalar_type>(1.234), variable_tag());\n        const auto right =\n            variable_type(static_cast<scalar_type>(2.345), variable_tag());\n\n        const variable_type res = left * right;\n\n        REQUIRE_THAT(res.value(),\n            Catch::Matchers::WithinRel(left.value() * right.value()));\n        REQUIRE(res.node());\n        REQUIRE(res.node()->children().size() == 2);\n        REQUIRE(res.node()->children()[0].node() == left.node());\n        REQUIRE(res.node()->children()[1].node() == right.node());\n        REQUIRE_THAT(res.node()->children()[0].sensitivity(),\n            Catch::Matchers::WithinRel(right.value()));\n        REQUIRE_THAT(res.node()->children()[1].sensitivity(),\n            Catch::Matchers::WithinRel(left.value()));\n    }\n\n    SECTION(\"scalar * variable\") {\n        const auto left = static_cast<scalar_type>(1.234);\n        const auto right =\n            variable_type(static_cast<scalar_type>(2.345), variable_tag());\n\n        const variable_type res = left * right;\n\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(left * right.value()));\n        REQUIRE(res.node());\n        REQUIRE(res.node()->children().size() == 1);\n        REQUIRE(res.node()->children()[0].node() == right.node());\n        REQUIRE_THAT(res.node()->children()[0].sensitivity(),\n            Catch::Matchers::WithinRel(left));\n    }\n\n    SECTION(\"variable * scalar\") {\n        const auto left =\n            variable_type(static_cast<scalar_type>(1.234), variable_tag());\n        const auto right = static_cast<scalar_type>(2.345);\n\n        const variable_type res = left * right;\n\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(left.value() * right));\n        REQUIRE(res.node());\n        REQUIRE(res.node()->children().size() == 1);\n        REQUIRE(res.node()->children()[0].node() == left.node());\n        REQUIRE_THAT(res.node()->children()[0].sensitivity(),\n            Catch::Matchers::WithinRel(right));\n    }\n\n    SECTION(\"scalar * scalar\") {\n        const auto left =\n            variable_type(static_cast<scalar_type>(1.234), constant_tag());\n        const auto right = static_cast<scalar_type>(2.345);\n\n        const variable_type res = left * right;\n\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(left.value() * right));\n        REQUIRE(res.node() == nullptr);\n    }\n\n    SECTION(\"self assignment\") {\n        const auto orig =\n            variable_type(static_cast<scalar_type>(1.234), variable_tag());\n        auto var = orig;\n\n        var *= var;\n\n        REQUIRE_THAT(var.value(),\n            Catch::Matchers::WithinRel(orig.value() * orig.value()));\n        REQUIRE(var.node());\n        REQUIRE(var.node()->children().size() == 1);\n        REQUIRE(var.node()->children()[0].node() == orig.node());\n        REQUIRE_THAT(var.node()->children()[0].sensitivity(),\n            Catch::Matchers::WithinRel(\n                static_cast<scalar_type>(2) * orig.value()));\n    }\n}\n\n// NOLINTNEXTLINE\nTEMPLATE_TEST_CASE(\n    \"num_collect::auto_diff::backward::operator/\", \"\", float, double) {\n    using scalar_type = TestType;\n    using variable_type =\n        num_collect::auto_diff::backward::variable<scalar_type>;\n    using num_collect::auto_diff::backward::constant_tag;\n    using num_collect::auto_diff::backward::variable_tag;\n\n    SECTION(\"variable / variable\") {\n        const auto left =\n            variable_type(static_cast<scalar_type>(1.234), variable_tag());\n        const auto right =\n            variable_type(static_cast<scalar_type>(2.345), variable_tag());\n\n        const variable_type res = left / right;\n\n        REQUIRE_THAT(res.value(),\n            Catch::Matchers::WithinRel(left.value() / right.value()));\n        REQUIRE(res.node());\n        REQUIRE(res.node()->children().size() == 2);\n        REQUIRE(res.node()->children()[0].node() == left.node());\n        REQUIRE(res.node()->children()[1].node() == right.node());\n        REQUIRE_THAT(res.node()->children()[0].sensitivity(),\n            Catch::Matchers::WithinRel(\n                static_cast<scalar_type>(1) / right.value()));\n        REQUIRE_THAT(res.node()->children()[1].sensitivity(),\n            Catch::Matchers::WithinRel(\n                -left.value() / (right.value() * right.value())));\n    }\n\n    SECTION(\"scalar / variable\") {\n        const auto left = static_cast<scalar_type>(1.234);\n        const auto right =\n            variable_type(static_cast<scalar_type>(2.345), variable_tag());\n\n        const variable_type res = left / right;\n\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(left / right.value()));\n        REQUIRE(res.node());\n        REQUIRE(res.node()->children().size() == 1);\n        REQUIRE(res.node()->children()[0].node() == right.node());\n        REQUIRE_THAT(res.node()->children()[0].sensitivity(),\n            Catch::Matchers::WithinRel(\n                -left / (right.value() * right.value())));\n    }\n\n    SECTION(\"variable / scalar\") {\n        const auto left =\n            variable_type(static_cast<scalar_type>(1.234), variable_tag());\n        const auto right = static_cast<scalar_type>(2.345);\n\n        const variable_type res = left / right;\n\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(left.value() / right));\n        REQUIRE(res.node());\n        REQUIRE(res.node()->children().size() == 1);\n        REQUIRE(res.node()->children()[0].node() == left.node());\n        REQUIRE_THAT(res.node()->children()[0].sensitivity(),\n            Catch::Matchers::WithinRel(static_cast<scalar_type>(1) / right));\n    }\n\n    SECTION(\"scalar / scalar\") {\n        const auto left =\n            variable_type(static_cast<scalar_type>(1.234), constant_tag());\n        const auto right = static_cast<scalar_type>(2.345);\n\n        const variable_type res = left / right;\n\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(left.value() / right));\n        REQUIRE(res.node() == nullptr);\n    }\n\n    SECTION(\"self assignment\") {\n        const auto orig =\n            variable_type(static_cast<scalar_type>(1.234), variable_tag());\n        auto var = orig;\n\n        var /= var;  // NOLINT\n\n        REQUIRE(var.value() == static_cast<scalar_type>(1));\n        REQUIRE(var.node() == nullptr);\n    }\n}\n\nTEST_CASE(\"Eigen::Matrix<num_collect::auto_diff::backward::variable>\") {\n    using variable_type = num_collect::auto_diff::backward::variable<double>;\n    using vector_type = Eigen::Matrix<variable_type, 2, 1>;\n    using num_collect::auto_diff::backward::variable_tag;\n\n    const auto vec = vector_type(variable_type(1.234, variable_tag()),\n        variable_type(2.345, variable_tag()));\n\n    SECTION(\"prod\") {\n        const variable_type res = vec.prod();\n        REQUIRE_THAT(res.value(),\n            Catch::Matchers::WithinRel(vec(0).value() * vec(1).value()));\n        REQUIRE(res.node());\n        REQUIRE(res.node()->children().size() == 2);\n        REQUIRE(res.node()->children()[0].node() == vec[0].node());\n        REQUIRE(res.node()->children()[1].node() == vec[1].node());\n        REQUIRE_THAT(res.node()->children()[0].sensitivity(),\n            Catch::Matchers::WithinRel(vec[1].value()));\n        REQUIRE_THAT(res.node()->children()[1].sensitivity(),\n            Catch::Matchers::WithinRel(vec[0].value()));\n    }\n}\n", "meta": {"hexsha": "9f6080d855209914fa92c50f01bb32753361b1a5", "size": 16794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/auto_diff/backward/variable_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/auto_diff/backward/variable_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/auto_diff/backward/variable_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": 36.5882352941, "max_line_length": 80, "alphanum_fraction": 0.6080147672, "num_tokens": 3658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5135928080408815}}
{"text": "#ifndef SEQUENTIAL_LINE_SEARCH_UTILS_HPP\n#define SEQUENTIAL_LINE_SEARCH_UTILS_HPP\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <cassert>\n#include <cmath>\n#include <string>\n\nnamespace sequential_line_search\n{\n    namespace utils\n    {\n        ////////////////////////////////////////////////\n        // Random\n        ////////////////////////////////////////////////\n\n        // Uniform sampling from [0, 1]^n\n        Eigen::VectorXd GenerateRandomVector(unsigned n);\n\n        ////////////////////////////////////////////////\n        // Bradley-Terry-Luce Model\n        ////////////////////////////////////////////////\n\n        inline double CalcBtl(const Eigen::VectorXd& f, double scale = 1.0)\n        {\n            const auto exp_rep = ((1.0 / scale) * f).array().exp();\n            return exp_rep(0) / exp_rep.sum();\n        }\n\n        inline Eigen::VectorXd CalcBtlDerivative(const Eigen::VectorXd& f, double scale = 1.0)\n        {\n            const unsigned dim = f.rows();\n            const double   btl = CalcBtl(f, scale);\n            const double   tmp = -btl * btl / scale;\n\n            Eigen::VectorXd d(dim);\n\n            double sum = 0.0;\n            for (unsigned i = 1; i < dim; ++i)\n            {\n                sum += std::exp((f(i) - f(0)) / scale);\n            }\n            d(0) = -sum;\n\n            for (unsigned i = 1; i < dim; ++i)\n            {\n                d(i) = std::exp((f(i) - f(0)) / scale);\n            }\n\n            return tmp * d;\n        }\n\n        ////////////////////////////////////////////////\n        // File IO\n        ////////////////////////////////////////////////\n\n        void ExportMatrixToCsv(const std::string& file_path, const Eigen::MatrixXd& X);\n    } // namespace utils\n} // namespace sequential_line_search\n\n#endif // SEQUENTIAL_LINE_SEARCH_UTILS_HPP\n", "meta": {"hexsha": "856c60e0dbb3e15ecb201f54246ac7d53d791c22", "size": 1816, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sequential-line-search/utils.hpp", "max_stars_repo_name": "yuki-koyama/sequential-line-search", "max_stars_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2018-03-12T13:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T20:28:04.000Z", "max_issues_repo_path": "include/sequential-line-search/utils.hpp", "max_issues_repo_name": "yuki-koyama/sequential-line-search", "max_issues_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T23:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T03:52:42.000Z", "max_forks_repo_path": "include/sequential-line-search/utils.hpp", "max_forks_repo_name": "yuki-koyama/sequential-line-search", "max_forks_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-06-12T17:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T11:13:03.000Z", "avg_line_length": 28.8253968254, "max_line_length": 94, "alphanum_fraction": 0.4372246696, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5135927959351241}}
{"text": "/**\n * @file tests/range_search_test.cpp\n * @author Ryan Curtin\n *\n * Test file for RangeSearch<> class.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/range_search/range_search.hpp>\n#include <mlpack/core/tree/cover_tree.hpp>\n#include <mlpack/methods/range_search/rs_model.hpp>\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::range;\nusing namespace mlpack::math;\nusing namespace mlpack::tree;\nusing namespace mlpack::bound;\nusing namespace mlpack::metric;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(RangeSearchTest);\n\n// Get our results into a sorted format, so we can actually then test for\n// correctness.\nvoid SortResults(const vector<vector<size_t>>& neighbors,\n                 const vector<vector<double>>& distances,\n                 vector<vector<pair<double, size_t>>>& output)\n{\n  output.resize(neighbors.size());\n  for (size_t i = 0; i < neighbors.size(); ++i)\n  {\n    output[i].resize(neighbors[i].size());\n    for (size_t j = 0; j < neighbors[i].size(); ++j)\n      output[i][j] = make_pair(distances[i][j], neighbors[i][j]);\n\n    // Now that it's constructed, sort it.\n    sort(output[i].begin(), output[i].end());\n  }\n}\n\n// Clean a tree's statistics.\ntemplate<typename TreeType>\nvoid CleanTree(TreeType& node)\n{\n  node.Stat().LastDistance() = 0.0;\n\n  for (size_t i = 0; i < node.NumChildren(); ++i)\n    CleanTree(node.Child(i));\n}\n\n/**\n * Simple range-search test with small, synthetic dataset.  This is an\n * exhaustive test, which checks that each method for performing the calculation\n * (dual-tree, single-tree, naive) produces the correct results.  An\n * eleven-point dataset and the points within three ranges are taken.  The\n * dataset is in one dimension for simplicity -- the correct functionality of\n * distance functions is not tested here.\n */\nBOOST_AUTO_TEST_CASE(ExhaustiveSyntheticTest)\n{\n  // Set up our data.\n  arma::mat data(1, 11);\n  data[0] = 0.05; // Row addressing is unnecessary (they are all 0).\n  data[1] = 0.35;\n  data[2] = 0.15;\n  data[3] = 1.25;\n  data[4] = 5.05;\n  data[5] = -0.22;\n  data[6] = -2.00;\n  data[7] = -1.30;\n  data[8] = 0.45;\n  data[9] = 0.90;\n  data[10] = 1.00;\n\n  typedef KDTree<EuclideanDistance, RangeSearchStat, arma::mat> TreeType;\n\n  // We will loop through three times, one for each method of performing the\n  // calculation.\n  std::vector<size_t> oldFromNew;\n  std::vector<size_t> newFromOld;\n  TreeType* tree = new TreeType(data, oldFromNew, newFromOld, 1);\n  for (int i = 0; i < 3; ++i)\n  {\n    RangeSearch<>* rs;\n\n    switch (i)\n    {\n      case 0: // Use the naive method.\n        rs = new RangeSearch<>(tree->Dataset(), true);\n        break;\n      case 1: // Use the single-tree method.\n        rs = new RangeSearch<>(tree, true);\n        break;\n      case 2: // Use the dual-tree method.\n        rs = new RangeSearch<>(tree);\n        break;\n    }\n\n    // Now perform the first calculation.  Points within 0.50.\n    vector<vector<size_t>> neighbors;\n    vector<vector<double>> distances;\n    rs->Search(Range(0.0, sqrt(0.5)), neighbors, distances);\n\n    // Now the exhaustive check for correctness.  This will be long.\n    vector<vector<pair<double, size_t>>> sortedOutput;\n    SortResults(neighbors, distances, sortedOutput);\n\n    BOOST_REQUIRE(sortedOutput[newFromOld[0]].size() == 4);\n    BOOST_REQUIRE(sortedOutput[newFromOld[0]][0].second == newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[0]][0].first, 0.10, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[0]][1].second == newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[0]][1].first, 0.27, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[0]][2].second == newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[0]][2].first, 0.30, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[0]][3].second == newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[0]][3].first, 0.40, 1e-5);\n\n    // Neighbors of point 1.\n    BOOST_REQUIRE(sortedOutput[newFromOld[1]].size() == 6);\n    BOOST_REQUIRE(sortedOutput[newFromOld[1]][0].second == newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[1]][0].first, 0.10, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[1]][1].second == newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[1]][1].first, 0.20, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[1]][2].second == newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[1]][2].first, 0.30, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[1]][3].second == newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[1]][3].first, 0.55, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[1]][4].second == newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[1]][4].first, 0.57, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[1]][5].second == newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[1]][5].first, 0.65, 1e-5);\n\n    // Neighbors of point 2.\n    BOOST_REQUIRE(sortedOutput[newFromOld[2]].size() == 4);\n    BOOST_REQUIRE(sortedOutput[newFromOld[2]][0].second == newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[2]][0].first, 0.10, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[2]][1].second == newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[2]][1].first, 0.20, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[2]][2].second == newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[2]][2].first, 0.30, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[2]][3].second == newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[2]][3].first, 0.37, 1e-5);\n\n    // Neighbors of point 3.\n    BOOST_REQUIRE(sortedOutput[newFromOld[3]].size() == 2);\n    BOOST_REQUIRE(sortedOutput[newFromOld[3]][0].second == newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[3]][0].first, 0.25, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[3]][1].second == newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[3]][1].first, 0.35, 1e-5);\n\n    // Neighbors of point 4.\n    BOOST_REQUIRE(sortedOutput[newFromOld[4]].size() == 0);\n\n    // Neighbors of point 5.\n    BOOST_REQUIRE(sortedOutput[newFromOld[5]].size() == 4);\n    BOOST_REQUIRE(sortedOutput[newFromOld[5]][0].second == newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[5]][0].first, 0.27, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[5]][1].second == newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[5]][1].first, 0.37, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[5]][2].second == newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[5]][2].first, 0.57, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[5]][3].second == newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[5]][3].first, 0.67, 1e-5);\n\n    // Neighbors of point 6.\n    BOOST_REQUIRE(sortedOutput[newFromOld[6]].size() == 1);\n    BOOST_REQUIRE(sortedOutput[newFromOld[6]][0].second == newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[6]][0].first, 0.70, 1e-5);\n\n    // Neighbors of point 7.\n    BOOST_REQUIRE(sortedOutput[newFromOld[7]].size() == 1);\n    BOOST_REQUIRE(sortedOutput[newFromOld[7]][0].second == newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[7]][0].first, 0.70, 1e-5);\n\n    // Neighbors of point 8.\n    BOOST_REQUIRE(sortedOutput[newFromOld[8]].size() == 6);\n    BOOST_REQUIRE(sortedOutput[newFromOld[8]][0].second == newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[8]][0].first, 0.10, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[8]][1].second == newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[8]][1].first, 0.30, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[8]][2].second == newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[8]][2].first, 0.40, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[8]][3].second == newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[8]][3].first, 0.45, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[8]][4].second == newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[8]][4].first, 0.55, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[8]][5].second == newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[8]][5].first, 0.67, 1e-5);\n\n    // Neighbors of point 9.\n    BOOST_REQUIRE(sortedOutput[newFromOld[9]].size() == 4);\n    BOOST_REQUIRE(sortedOutput[newFromOld[9]][0].second == newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[9]][0].first, 0.10, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[9]][1].second == newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[9]][1].first, 0.35, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[9]][2].second == newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[9]][2].first, 0.45, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[9]][3].second == newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[9]][3].first, 0.55, 1e-5);\n\n    // Neighbors of point 10.\n    BOOST_REQUIRE(sortedOutput[newFromOld[10]].size() == 4);\n    BOOST_REQUIRE(sortedOutput[newFromOld[10]][0].second == newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[10]][0].first, 0.10, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[10]][1].second == newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[10]][1].first, 0.25, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[10]][2].second == newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[10]][2].first, 0.55, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[10]][3].second == newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[10]][3].first, 0.65, 1e-5);\n\n    // Now do it again with a different range: [sqrt(0.5) 1.0].\n    if (rs->ReferenceTree())\n      CleanTree(*rs->ReferenceTree());\n    rs->Search(Range(sqrt(0.5), 1.0), neighbors, distances);\n    SortResults(neighbors, distances, sortedOutput);\n\n    // Neighbors of point 0.\n    BOOST_REQUIRE(sortedOutput[newFromOld[0]].size() == 2);\n    BOOST_REQUIRE(sortedOutput[newFromOld[0]][0].second == newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[0]][0].first, 0.85, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[0]][1].second == newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[0]][1].first, 0.95, 1e-5);\n\n    // Neighbors of point 1.\n    BOOST_REQUIRE(sortedOutput[newFromOld[1]].size() == 1);\n    BOOST_REQUIRE(sortedOutput[newFromOld[1]][0].second == newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[1]][0].first, 0.90, 1e-5);\n\n    // Neighbors of point 2.\n    BOOST_REQUIRE(sortedOutput[newFromOld[2]].size() == 2);\n    BOOST_REQUIRE(sortedOutput[newFromOld[2]][0].second == newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[2]][0].first, 0.75, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[2]][1].second == newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[2]][1].first, 0.85, 1e-5);\n\n    // Neighbors of point 3.\n    BOOST_REQUIRE(sortedOutput[newFromOld[3]].size() == 2);\n    BOOST_REQUIRE(sortedOutput[newFromOld[3]][0].second == newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[3]][0].first, 0.80, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[3]][1].second == newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[3]][1].first, 0.90, 1e-5);\n\n    // Neighbors of point 4.\n    BOOST_REQUIRE(sortedOutput[newFromOld[4]].size() == 0);\n\n    // Neighbors of point 5.\n    BOOST_REQUIRE(sortedOutput[newFromOld[5]].size() == 0);\n\n    // Neighbors of point 6.\n    BOOST_REQUIRE(sortedOutput[newFromOld[6]].size() == 0);\n\n    // Neighbors of point 7.\n    BOOST_REQUIRE(sortedOutput[newFromOld[7]].size() == 0);\n\n    // Neighbors of point 8.\n    BOOST_REQUIRE(sortedOutput[newFromOld[8]].size() == 1);\n    BOOST_REQUIRE(sortedOutput[newFromOld[8]][0].second == newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[8]][0].first, 0.80, 1e-5);\n\n    // Neighbors of point 9.\n    BOOST_REQUIRE(sortedOutput[newFromOld[9]].size() == 2);\n    BOOST_REQUIRE(sortedOutput[newFromOld[9]][0].second == newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[9]][0].first, 0.75, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[9]][1].second == newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[9]][1].first, 0.85, 1e-5);\n\n    // Neighbors of point 10.\n    BOOST_REQUIRE(sortedOutput[newFromOld[10]].size() == 2);\n    BOOST_REQUIRE(sortedOutput[newFromOld[10]][0].second == newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[10]][0].first, 0.85, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[10]][1].second == newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[10]][1].first, 0.95, 1e-5);\n\n    // Now do it again with a different range: [1.0 inf].\n    if (rs->ReferenceTree())\n      CleanTree(*rs->ReferenceTree());\n    rs->Search(Range(1.0, numeric_limits<double>::infinity()), neighbors,\n        distances);\n    SortResults(neighbors, distances, sortedOutput);\n\n    // Neighbors of point 0.\n    BOOST_REQUIRE(sortedOutput[newFromOld[0]].size() == 4);\n    BOOST_REQUIRE(sortedOutput[newFromOld[0]][0].second == newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[0]][0].first, 1.20, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[0]][1].second == newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[0]][1].first, 1.35, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[0]][2].second == newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[0]][2].first, 2.05, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[0]][3].second == newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[0]][3].first, 5.00, 1e-5);\n\n    // Neighbors of point 1.\n    BOOST_REQUIRE(sortedOutput[newFromOld[1]].size() == 3);\n    BOOST_REQUIRE(sortedOutput[newFromOld[1]][0].second == newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[1]][0].first, 1.65, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[1]][1].second == newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[1]][1].first, 2.35, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[1]][2].second == newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[1]][2].first, 4.70, 1e-5);\n\n    // Neighbors of point 2.\n    BOOST_REQUIRE(sortedOutput[newFromOld[2]].size() == 4);\n    BOOST_REQUIRE(sortedOutput[newFromOld[2]][0].second == newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[2]][0].first, 1.10, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[2]][1].second == newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[2]][1].first, 1.45, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[2]][2].second == newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[2]][2].first, 2.15, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[2]][3].second == newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[2]][3].first, 4.90, 1e-5);\n\n    // Neighbors of point 3.\n    BOOST_REQUIRE(sortedOutput[newFromOld[3]].size() == 6);\n    BOOST_REQUIRE(sortedOutput[newFromOld[3]][0].second == newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[3]][0].first, 1.10, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[3]][1].second == newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[3]][1].first, 1.20, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[3]][2].second == newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[3]][2].first, 1.47, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[3]][3].second == newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[3]][3].first, 2.55, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[3]][4].second == newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[3]][4].first, 3.25, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[3]][5].second == newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[3]][5].first, 3.80, 1e-5);\n\n    // Neighbors of point 4.\n    BOOST_REQUIRE(sortedOutput[newFromOld[4]].size() == 10);\n    BOOST_REQUIRE(sortedOutput[newFromOld[4]][0].second == newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[4]][0].first, 3.80, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[4]][1].second == newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[4]][1].first, 4.05, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[4]][2].second == newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[4]][2].first, 4.15, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[4]][3].second == newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[4]][3].first, 4.60, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[4]][4].second == newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[4]][4].first, 4.70, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[4]][5].second == newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[4]][5].first, 4.90, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[4]][6].second == newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[4]][6].first, 5.00, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[4]][7].second == newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[4]][7].first, 5.27, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[4]][8].second == newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[4]][8].first, 6.35, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[4]][9].second == newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[4]][9].first, 7.05, 1e-5);\n\n    // Neighbors of point 5.\n    BOOST_REQUIRE(sortedOutput[newFromOld[5]].size() == 6);\n    BOOST_REQUIRE(sortedOutput[newFromOld[5]][0].second == newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[5]][0].first, 1.08, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[5]][1].second == newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[5]][1].first, 1.12, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[5]][2].second == newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[5]][2].first, 1.22, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[5]][3].second == newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[5]][3].first, 1.47, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[5]][4].second == newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[5]][4].first, 1.78, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[5]][5].second == newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[5]][5].first, 5.27, 1e-5);\n\n    // Neighbors of point 6.\n    BOOST_REQUIRE(sortedOutput[newFromOld[6]].size() == 9);\n    BOOST_REQUIRE(sortedOutput[newFromOld[6]][0].second == newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[6]][0].first, 1.78, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[6]][1].second == newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[6]][1].first, 2.05, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[6]][2].second == newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[6]][2].first, 2.15, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[6]][3].second == newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[6]][3].first, 2.35, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[6]][4].second == newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[6]][4].first, 2.45, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[6]][5].second == newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[6]][5].first, 2.90, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[6]][6].second == newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[6]][6].first, 3.00, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[6]][7].second == newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[6]][7].first, 3.25, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[6]][8].second == newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[6]][8].first, 7.05, 1e-5);\n\n    // Neighbors of point 7.\n    BOOST_REQUIRE(sortedOutput[newFromOld[7]].size() == 9);\n    BOOST_REQUIRE(sortedOutput[newFromOld[7]][0].second == newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[7]][0].first, 1.08, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[7]][1].second == newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[7]][1].first, 1.35, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[7]][2].second == newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[7]][2].first, 1.45, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[7]][3].second == newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[7]][3].first, 1.65, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[7]][4].second == newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[7]][4].first, 1.75, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[7]][5].second == newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[7]][5].first, 2.20, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[7]][6].second == newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[7]][6].first, 2.30, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[7]][7].second == newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[7]][7].first, 2.55, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[7]][8].second == newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[7]][8].first, 6.35, 1e-5);\n\n    // Neighbors of point 8.\n    BOOST_REQUIRE(sortedOutput[newFromOld[8]].size() == 3);\n    BOOST_REQUIRE(sortedOutput[newFromOld[8]][0].second == newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[8]][0].first, 1.75, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[8]][1].second == newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[8]][1].first, 2.45, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[8]][2].second == newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[8]][2].first, 4.60, 1e-5);\n\n    // Neighbors of point 9.\n    BOOST_REQUIRE(sortedOutput[newFromOld[9]].size() == 4);\n    BOOST_REQUIRE(sortedOutput[newFromOld[9]][0].second == newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[9]][0].first, 1.12, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[9]][1].second == newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[9]][1].first, 2.20, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[9]][2].second == newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[9]][2].first, 2.90, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[9]][3].second == newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[9]][3].first, 4.15, 1e-5);\n\n    // Neighbors of point 10.\n    BOOST_REQUIRE(sortedOutput[newFromOld[10]].size() == 4);\n    BOOST_REQUIRE(sortedOutput[newFromOld[10]][0].second == newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[10]][0].first, 1.22, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[10]][1].second == newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[10]][1].first, 2.30, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[10]][2].second == newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[10]][2].first, 3.00, 1e-5);\n    BOOST_REQUIRE(sortedOutput[newFromOld[10]][3].second == newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(sortedOutput[newFromOld[10]][3].first, 4.05, 1e-5);\n\n    // Clean the memory.\n    delete rs;\n  }\n\n  delete tree;\n}\n\n/**\n * Test the dual-tree range search method with the naive method.  This\n * uses both a query and reference dataset.\n *\n * Errors are produced if the results are not identical.\n */\nBOOST_AUTO_TEST_CASE(DualTreeVsNaive1)\n{\n  arma::mat dataForTree;\n\n  // Hard-coded filename: bad!\n  if (!data::Load(\"test_data_3_1000.csv\", dataForTree))\n    BOOST_FAIL(\"Cannot load test dataset test_data_3_1000.csv!\");\n\n  // Set up matrices to work with.\n  arma::mat dualQuery(dataForTree);\n  arma::mat dualReferences(dataForTree);\n  arma::mat naiveQuery(dataForTree);\n  arma::mat naiveReferences(dataForTree);\n\n  RangeSearch<> rs(dualReferences);\n\n  RangeSearch<> naive(naiveReferences, true);\n\n  vector<vector<size_t>> neighborsTree;\n  vector<vector<double>> distancesTree;\n  rs.Search(dualQuery, Range(0.25, 1.05), neighborsTree, distancesTree);\n  vector<vector<pair<double, size_t>>> sortedTree;\n  SortResults(neighborsTree, distancesTree, sortedTree);\n\n  vector<vector<size_t>> neighborsNaive;\n  vector<vector<double>> distancesNaive;\n  naive.Search(naiveQuery, Range(0.25, 1.05), neighborsNaive, distancesNaive);\n  vector<vector<pair<double, size_t>>> sortedNaive;\n  SortResults(neighborsNaive, distancesNaive, sortedNaive);\n\n  for (size_t i = 0; i < sortedTree.size(); ++i)\n  {\n    BOOST_REQUIRE(sortedTree[i].size() == sortedNaive[i].size());\n\n    for (size_t j = 0; j < sortedTree[i].size(); ++j)\n    {\n      BOOST_REQUIRE(sortedTree[i][j].second == sortedNaive[i][j].second);\n      BOOST_REQUIRE_CLOSE(sortedTree[i][j].first, sortedNaive[i][j].first,\n          1e-5);\n    }\n  }\n}\n\n/**\n * Test the dual-tree range search method with the naive method.  This uses\n * only a reference dataset.\n *\n * Errors are produced if the results are not identical.\n */\nBOOST_AUTO_TEST_CASE(DualTreeVsNaive2)\n{\n  arma::mat dataForTree;\n\n  // Hard-coded filename: bad!\n  // Code duplication: also bad!\n  if (!data::Load(\"test_data_3_1000.csv\", dataForTree))\n    BOOST_FAIL(\"Cannot load test dataset test_data_3_1000.csv!\");\n\n  // Set up matrices to work with.\n  arma::mat dualQuery(dataForTree);\n  arma::mat naiveQuery(dataForTree);\n\n  RangeSearch<> rs(dualQuery);\n\n  // Set naive mode.\n  RangeSearch<> naive(naiveQuery, true);\n\n  vector<vector<size_t>> neighborsTree;\n  vector<vector<double>> distancesTree;\n  rs.Search(Range(0.25, 1.05), neighborsTree, distancesTree);\n  vector<vector<pair<double, size_t>>> sortedTree;\n  SortResults(neighborsTree, distancesTree, sortedTree);\n\n  vector<vector<size_t>> neighborsNaive;\n  vector<vector<double>> distancesNaive;\n  naive.Search(Range(0.25, 1.05), neighborsNaive, distancesNaive);\n  vector<vector<pair<double, size_t>>> sortedNaive;\n  SortResults(neighborsNaive, distancesNaive, sortedNaive);\n\n  for (size_t i = 0; i < sortedTree.size(); ++i)\n  {\n    BOOST_REQUIRE(sortedTree[i].size() == sortedNaive[i].size());\n\n    for (size_t j = 0; j < sortedTree[i].size(); ++j)\n    {\n      BOOST_REQUIRE(sortedTree[i][j].second == sortedNaive[i][j].second);\n      BOOST_REQUIRE_CLOSE(sortedTree[i][j].first, sortedNaive[i][j].first,\n          1e-5);\n    }\n  }\n}\n\n/**\n * Test the single-tree range search method with the naive method.  This\n * uses only a reference dataset.\n *\n * Errors are produced if the results are not identical.\n */\nBOOST_AUTO_TEST_CASE(SingleTreeVsNaive)\n{\n  arma::mat dataForTree;\n\n  // Hard-coded filename: bad!\n  // Code duplication: also bad!\n  if (!data::Load(\"test_data_3_1000.csv\", dataForTree))\n    BOOST_FAIL(\"Cannot load test dataset test_data_3_1000.csv!\");\n\n  // Set up matrices to work with (may not be necessary with no ALIAS_MATRIX?).\n  arma::mat singleQuery(dataForTree);\n  arma::mat naiveQuery(dataForTree);\n\n  RangeSearch<> single(singleQuery, false, true);\n\n  // Set up computation for naive mode.\n  RangeSearch<> naive(naiveQuery, true);\n\n  vector<vector<size_t>> neighborsSingle;\n  vector<vector<double>> distancesSingle;\n  single.Search(Range(0.25, 1.05), neighborsSingle, distancesSingle);\n  vector<vector<pair<double, size_t>>> sortedTree;\n  SortResults(neighborsSingle, distancesSingle, sortedTree);\n\n  vector<vector<size_t>> neighborsNaive;\n  vector<vector<double>> distancesNaive;\n  naive.Search(Range(0.25, 1.05), neighborsNaive, distancesNaive);\n  vector<vector<pair<double, size_t>>> sortedNaive;\n  SortResults(neighborsNaive, distancesNaive, sortedNaive);\n\n  for (size_t i = 0; i < sortedTree.size(); ++i)\n  {\n    BOOST_REQUIRE(sortedTree[i].size() == sortedNaive[i].size());\n\n    for (size_t j = 0; j < sortedTree[i].size(); ++j)\n    {\n      BOOST_REQUIRE(sortedTree[i][j].second == sortedNaive[i][j].second);\n      BOOST_REQUIRE_CLOSE(sortedTree[i][j].first, sortedNaive[i][j].first,\n          1e-5);\n    }\n  }\n}\n\n/**\n * Ensure that dual tree range search with cover trees works by comparing\n * with the kd-tree implementation.\n */\nBOOST_AUTO_TEST_CASE(CoverTreeTest)\n{\n  arma::mat data;\n  data.randu(8, 1000); // 1000 points in 8 dimensions.\n\n  // Set up cover tree range search.\n  RangeSearch<EuclideanDistance, arma::mat, StandardCoverTree>\n      coversearch(data);\n\n  // Four trials with different ranges.\n  for (size_t r = 0; r < 4; ++r)\n  {\n    // Set up kd-tree range search.\n    RangeSearch<> kdsearch(data);\n\n    Range range;\n    switch (r)\n    {\n      case 0:\n        // Includes zero distance.\n        range = Range(0.0, 0.75);\n        break;\n      case 1:\n        // A bounded range on both sides.\n        range = Range(0.5, 1.5);\n        break;\n      case 2:\n        // A range with no upper bound.\n        range = Range(0.8, DBL_MAX);\n        break;\n      case 3:\n        // A range which should have no results.\n        range = Range(15.6, 15.7);\n        break;\n    }\n\n    // Results for kd-tree search.\n    vector<vector<size_t>> kdNeighbors;\n    vector<vector<double>> kdDistances;\n\n    // Results for cover tree search.\n    vector<vector<size_t>> coverNeighbors;\n    vector<vector<double>> coverDistances;\n\n    // Clean the tree statistics.\n    CleanTree(*coversearch.ReferenceTree());\n\n    // Run the searches.\n    kdsearch.Search(range, kdNeighbors, kdDistances);\n    coversearch.Search(range, coverNeighbors, coverDistances);\n\n    // Sort before comparison.\n    vector<vector<pair<double, size_t>>> kdSorted;\n    vector<vector<pair<double, size_t>>> coverSorted;\n    SortResults(kdNeighbors, kdDistances, kdSorted);\n    SortResults(coverNeighbors, coverDistances, coverSorted);\n\n    // Now compare the results.\n    for (size_t i = 0; i < kdSorted.size(); ++i)\n    {\n      for (size_t j = 0; j < kdSorted[i].size(); ++j)\n      {\n        BOOST_REQUIRE_EQUAL(kdSorted[i][j].second, coverSorted[i][j].second);\n        BOOST_REQUIRE_CLOSE(kdSorted[i][j].first, coverSorted[i][j].first,\n            1e-5);\n      }\n      BOOST_REQUIRE_EQUAL(kdSorted[i].size(), coverSorted[i].size());\n    }\n  }\n}\n\n/**\n * Ensure that dual tree range search with cover trees works when using\n * two datasets.\n */\nBOOST_AUTO_TEST_CASE(CoverTreeTwoDatasetsTest)\n{\n  arma::mat data;\n  data.randu(8, 1000); // 1000 points in 8 dimensions.\n  arma::mat queries;\n  queries.randu(8, 350); // 350 points in 8 dimensions.\n\n  // Set up cover tree range search.\n  RangeSearch<EuclideanDistance, arma::mat, StandardCoverTree>\n      coversearch(data);\n\n  // Four trials with different ranges.\n  for (size_t r = 0; r < 4; ++r)\n  {\n    // Set up kd-tree range search.  We don't have an easy way to rebuild the\n    // tree, so we'll just reinstantiate it here each loop time.\n    RangeSearch<> kdsearch(data);\n\n    Range range;\n    switch (r)\n    {\n      case 0:\n        // Includes zero distance.\n        range = Range(0.0, 0.75);\n        break;\n      case 1:\n        // A bounded range on both sides.\n        range = Range(0.85, 1.05);\n        break;\n      case 2:\n        // A range with no upper bound.\n        range = Range(1.35, DBL_MAX);\n        break;\n      case 3:\n        // A range which should have no results.\n        range = Range(15.6, 15.7);\n        break;\n    }\n\n    // Results for kd-tree search.\n    vector<vector<size_t>> kdNeighbors;\n    vector<vector<double>> kdDistances;\n\n    // Results for cover tree search.\n    vector<vector<size_t>> coverNeighbors;\n    vector<vector<double>> coverDistances;\n\n    // Clean the trees.\n    CleanTree(*coversearch.ReferenceTree());\n\n    // Run the searches.\n    coversearch.Search(queries, range, coverNeighbors, coverDistances);\n    kdsearch.Search(queries, range, kdNeighbors, kdDistances);\n\n    // Sort before comparison.\n    vector<vector<pair<double, size_t>>> kdSorted;\n    vector<vector<pair<double, size_t>>> coverSorted;\n    SortResults(kdNeighbors, kdDistances, kdSorted);\n    SortResults(coverNeighbors, coverDistances, coverSorted);\n\n    // Now compare the results.\n    for (size_t i = 0; i < kdSorted.size(); ++i)\n    {\n      for (size_t j = 0; j < kdSorted[i].size(); ++j)\n      {\n        BOOST_REQUIRE_EQUAL(kdSorted[i][j].second, coverSorted[i][j].second);\n        BOOST_REQUIRE_CLOSE(kdSorted[i][j].first, coverSorted[i][j].first,\n            1e-5);\n      }\n      BOOST_REQUIRE_EQUAL(kdSorted[i].size(), coverSorted[i].size());\n    }\n  }\n}\n\n/**\n * Ensure that single-tree cover tree range search works.\n */\nBOOST_AUTO_TEST_CASE(CoverTreeSingleTreeTest)\n{\n  arma::mat data;\n  data.randu(8, 1000); // 1000 points in 8 dimensions.\n\n  // Set up cover tree range search.\n  RangeSearch<EuclideanDistance, arma::mat, StandardCoverTree>\n      coversearch(data, false, true);\n\n  // Four trials with different ranges.\n  for (size_t r = 0; r < 4; ++r)\n  {\n    // Set up kd-tree range search.\n    RangeSearch<> kdsearch(data);\n\n    Range range;\n    switch (r)\n    {\n      case 0:\n        // Includes zero distance.\n        range = Range(0.0, 0.75);\n        break;\n      case 1:\n        // A bounded range on both sides.\n        range = Range(0.5, 1.5);\n        break;\n      case 2:\n        // A range with no upper bound.\n        range = Range(0.8, DBL_MAX);\n        break;\n      case 3:\n        // A range which should have no results.\n        range = Range(15.6, 15.7);\n        break;\n    }\n\n    // Results for kd-tree search.\n    vector<vector<size_t>> kdNeighbors;\n    vector<vector<double>> kdDistances;\n\n    // Results for cover tree search.\n    vector<vector<size_t>> coverNeighbors;\n    vector<vector<double>> coverDistances;\n\n    // Clean the tree statistics.\n    CleanTree(*coversearch.ReferenceTree());\n\n    // Run the searches.\n    kdsearch.Search(range, kdNeighbors, kdDistances);\n    coversearch.Search(range, coverNeighbors, coverDistances);\n\n    // Sort before comparison.\n    vector<vector<pair<double, size_t>>> kdSorted;\n    vector<vector<pair<double, size_t>>> coverSorted;\n    SortResults(kdNeighbors, kdDistances, kdSorted);\n    SortResults(coverNeighbors, coverDistances, coverSorted);\n\n    // Now compare the results.\n    for (size_t i = 0; i < kdSorted.size(); ++i)\n    {\n      for (size_t j = 0; j < kdSorted[i].size(); ++j)\n      {\n        BOOST_REQUIRE_EQUAL(kdSorted[i][j].second, coverSorted[i][j].second);\n        BOOST_REQUIRE_CLOSE(kdSorted[i][j].first, coverSorted[i][j].first,\n            1e-5);\n      }\n      BOOST_REQUIRE_EQUAL(kdSorted[i].size(), coverSorted[i].size());\n    }\n  }\n}\n\n/**\n * Ensure that single-tree ball tree range search works.\n */\nBOOST_AUTO_TEST_CASE(SingleBallTreeTest)\n{\n  arma::mat data;\n  data.randu(8, 1000); // 1000 points in 8 dimensions.\n\n  // Set up ball tree range search.\n  RangeSearch<EuclideanDistance, arma::mat, BallTree> ballsearch(data, false,\n      true);\n\n  // Four trials with different ranges.\n  for (size_t r = 0; r < 4; ++r)\n  {\n    // Set up kd-tree range search.\n    RangeSearch<> kdsearch(data);\n\n    Range range;\n    switch (r)\n    {\n      case 0:\n        // Includes zero distance.\n        range = Range(0.0, 0.75);\n        break;\n      case 1:\n        // A bounded range on both sides.\n        range = Range(0.5, 1.5);\n        break;\n      case 2:\n        // A range with no upper bound.\n        range = Range(0.8, DBL_MAX);\n        break;\n      case 3:\n        // A range which should have no results.\n        range = Range(15.6, 15.7);\n        break;\n    }\n\n    // Results for kd-tree search.\n    vector<vector<size_t>> kdNeighbors;\n    vector<vector<double>> kdDistances;\n\n    // Results for ball tree search.\n    vector<vector<size_t>> ballNeighbors;\n    vector<vector<double>> ballDistances;\n\n    // Clean the tree statistics.\n    CleanTree(*ballsearch.ReferenceTree());\n\n    // Run the searches.\n    kdsearch.Search(range, kdNeighbors, kdDistances);\n    ballsearch.Search(range, ballNeighbors, ballDistances);\n\n    // Sort before comparison.\n    vector<vector<pair<double, size_t>>> kdSorted;\n    vector<vector<pair<double, size_t>>> ballSorted;\n    SortResults(kdNeighbors, kdDistances, kdSorted);\n    SortResults(ballNeighbors, ballDistances, ballSorted);\n\n    // Now compare the results.\n    for (size_t i = 0; i < kdSorted.size(); ++i)\n    {\n      for (size_t j = 0; j < kdSorted[i].size(); ++j)\n      {\n        BOOST_REQUIRE_EQUAL(kdSorted[i][j].second, ballSorted[i][j].second);\n        BOOST_REQUIRE_CLOSE(kdSorted[i][j].first, ballSorted[i][j].first,\n            1e-5);\n      }\n      BOOST_REQUIRE_EQUAL(kdSorted[i].size(), ballSorted[i].size());\n    }\n  }\n}\n\n/**\n * Ensure that dual tree range search with ball trees works by comparing\n * with the kd-tree implementation.\n */\nBOOST_AUTO_TEST_CASE(DualBallTreeTest)\n{\n  arma::mat data;\n  data.randu(8, 1000); // 1000 points in 8 dimensions.\n\n  // Set up ball tree range search.\n  RangeSearch<EuclideanDistance, arma::mat, BallTree> ballsearch(data);\n\n  // Four trials with different ranges.\n  for (size_t r = 0; r < 4; ++r)\n  {\n    // Set up kd-tree range search.\n    RangeSearch<> kdsearch(data);\n\n    Range range;\n    switch (r)\n    {\n      case 0:\n        // Includes zero distance.\n        range = Range(0.0, 0.75);\n        break;\n      case 1:\n        // A bounded range on both sides.\n        range = Range(0.5, 1.5);\n        break;\n      case 2:\n        // A range with no upper bound.\n        range = Range(0.8, DBL_MAX);\n        break;\n      case 3:\n        // A range which should have no results.\n        range = Range(15.6, 15.7);\n        break;\n    }\n\n    // Results for kd-tree search.\n    vector<vector<size_t>> kdNeighbors;\n    vector<vector<double>> kdDistances;\n\n    // Results for ball tree search.\n    vector<vector<size_t>> ballNeighbors;\n    vector<vector<double>> ballDistances;\n\n    // Clean the tree statistics.\n    CleanTree(*ballsearch.ReferenceTree());\n\n    // Run the searches.\n    kdsearch.Search(range, kdNeighbors, kdDistances);\n    ballsearch.Search(range, ballNeighbors, ballDistances);\n\n    // Sort before comparison.\n    vector<vector<pair<double, size_t>>> kdSorted;\n    vector<vector<pair<double, size_t>>> ballSorted;\n    SortResults(kdNeighbors, kdDistances, kdSorted);\n    SortResults(ballNeighbors, ballDistances, ballSorted);\n\n    // Now compare the results.\n    for (size_t i = 0; i < kdSorted.size(); ++i)\n    {\n      for (size_t j = 0; j < kdSorted[i].size(); ++j)\n      {\n        BOOST_REQUIRE_EQUAL(kdSorted[i][j].second, ballSorted[i][j].second);\n        BOOST_REQUIRE_CLOSE(kdSorted[i][j].first, ballSorted[i][j].first,\n            1e-5);\n      }\n      BOOST_REQUIRE_EQUAL(kdSorted[i].size(), ballSorted[i].size());\n    }\n  }\n}\n\n/**\n * Ensure that dual tree range search with ball trees works when using\n * two datasets.\n */\nBOOST_AUTO_TEST_CASE(DualBallTreeTest2)\n{\n  arma::mat data;\n  data.randu(8, 1000); // 1000 points in 8 dimensions.\n\n  arma::mat queries;\n  queries.randu(8, 350); // 350 points in 8 dimensions.\n\n  // Set up ball tree range search.\n  RangeSearch<EuclideanDistance, arma::mat, BallTree> ballsearch(data);\n\n  // Four trials with different ranges.\n  for (size_t r = 0; r < 4; ++r)\n  {\n    // Set up kd-tree range search.  We don't have an easy way to rebuild the\n    // tree, so we'll just reinstantiate it here each loop time.\n    RangeSearch<> kdsearch(data);\n\n    Range range;\n    switch (r)\n    {\n      case 0:\n        // Includes zero distance.\n        range = Range(0.0, 0.75);\n        break;\n      case 1:\n        // A bounded range on both sides.\n        range = Range(0.85, 1.05);\n        break;\n      case 2:\n        // A range with no upper bound.\n        range = Range(1.35, DBL_MAX);\n        break;\n      case 3:\n        // A range which should have no results.\n        range = Range(15.6, 15.7);\n        break;\n    }\n\n    // Results for kd-tree search.\n    vector<vector<size_t>> kdNeighbors;\n    vector<vector<double>> kdDistances;\n\n    // Results for ball tree search.\n    vector<vector<size_t>> ballNeighbors;\n    vector<vector<double>> ballDistances;\n\n    // Clean the trees.\n    CleanTree(*ballsearch.ReferenceTree());\n\n    // Run the searches.\n    ballsearch.Search(queries, range, ballNeighbors, ballDistances);\n    kdsearch.Search(queries, range, kdNeighbors, kdDistances);\n\n    // Sort before comparison.\n    vector<vector<pair<double, size_t>>> kdSorted;\n    vector<vector<pair<double, size_t>>> ballSorted;\n    SortResults(kdNeighbors, kdDistances, kdSorted);\n    SortResults(ballNeighbors, ballDistances, ballSorted);\n\n    // Now compare the results.\n    for (size_t i = 0; i < kdSorted.size(); ++i)\n    {\n      BOOST_REQUIRE_EQUAL(kdSorted[i].size(), ballSorted[i].size());\n      for (size_t j = 0; j < kdSorted[i].size(); ++j)\n      {\n        BOOST_REQUIRE_EQUAL(kdSorted[i][j].second, ballSorted[i][j].second);\n        BOOST_REQUIRE_CLOSE(kdSorted[i][j].first, ballSorted[i][j].first,\n            1e-5);\n      }\n    }\n  }\n}\n\n/**\n * Make sure that no results are returned when we build a range search object\n * with no reference set.\n */\nBOOST_AUTO_TEST_CASE(EmptySearchTest)\n{\n  RangeSearch<EuclideanDistance, arma::mat, KDTree> rs;\n\n  vector<vector<size_t>> neighbors;\n  vector<vector<double>> distances;\n\n  rs.Search(math::Range(0.0, 10.0), neighbors, distances);\n\n  BOOST_REQUIRE_EQUAL(neighbors.size(), 0);\n  BOOST_REQUIRE_EQUAL(distances.size(), 0);\n\n  // Now check with a query set.\n  arma::mat querySet = arma::randu<arma::mat>(3, 100);\n\n  BOOST_REQUIRE_THROW(rs.Search(querySet, math::Range(0.0, 10.0), neighbors,\n      distances), std::invalid_argument);\n}\n\n/**\n * Make sure things work right after Train() is called.\n */\nBOOST_AUTO_TEST_CASE(TrainTest)\n{\n  RangeSearch<> empty;\n\n  arma::mat dataset = arma::randu<arma::mat>(5, 100);\n  RangeSearch<> baseline(dataset);\n\n  vector<vector<size_t>> neighbors, baselineNeighbors;\n  vector<vector<double>> distances, baselineDistances;\n\n  empty.Train(dataset);\n\n  empty.Search(math::Range(0.5, 0.7), neighbors, distances);\n  baseline.Search(math::Range(0.5, 0.7), baselineNeighbors, baselineDistances);\n\n  BOOST_REQUIRE_EQUAL(neighbors.size(), baselineNeighbors.size());\n  BOOST_REQUIRE_EQUAL(distances.size(), baselineDistances.size());\n\n  // Sort the results before comparing.\n  vector<vector<pair<double, size_t>>> sorted;\n  vector<vector<pair<double, size_t>>> baselineSorted;\n  SortResults(neighbors, distances, sorted);\n  SortResults(baselineNeighbors, baselineDistances, baselineSorted);\n\n  for (size_t i = 0; i < sorted.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(sorted[i].size(), baselineSorted[i].size());\n    for (size_t j = 0; j < sorted[i].size(); ++j)\n    {\n      BOOST_REQUIRE_EQUAL(sorted[i][j].second, baselineSorted[i][j].second);\n      BOOST_REQUIRE_CLOSE(sorted[i][j].first, baselineSorted[i][j].first, 1e-5);\n    }\n  }\n}\n\n/**\n * Test training when a tree is given.\n */\nBOOST_AUTO_TEST_CASE(TrainTreeTest)\n{\n  // Avoid mappings by using the cover tree.\n  typedef RangeSearch<EuclideanDistance, arma::mat, StandardCoverTree> RSType;\n  RSType empty;\n\n  arma::mat dataset = arma::randu<arma::mat>(5, 100);\n  RSType baseline(dataset);\n\n  vector<vector<size_t>> neighbors, baselineNeighbors;\n  vector<vector<double>> distances, baselineDistances;\n\n  RSType::Tree tree(dataset);\n  empty.Train(&tree);\n\n  empty.Search(math::Range(0.5, 0.7), neighbors, distances);\n  baseline.Search(math::Range(0.5, 0.7), baselineNeighbors, baselineDistances);\n\n  BOOST_REQUIRE_EQUAL(neighbors.size(), baselineNeighbors.size());\n  BOOST_REQUIRE_EQUAL(distances.size(), baselineDistances.size());\n\n  // Sort the results before comparing.\n  vector<vector<pair<double, size_t>>> sorted;\n  vector<vector<pair<double, size_t>>> baselineSorted;\n  SortResults(neighbors, distances, sorted);\n  SortResults(baselineNeighbors, baselineDistances, baselineSorted);\n\n  for (size_t i = 0; i < sorted.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(sorted[i].size(), baselineSorted[i].size());\n    for (size_t j = 0; j < sorted[i].size(); ++j)\n    {\n      BOOST_REQUIRE_EQUAL(sorted[i][j].second, baselineSorted[i][j].second);\n      BOOST_REQUIRE_CLOSE(sorted[i][j].first, baselineSorted[i][j].first, 1e-5);\n    }\n  }\n}\n\n/**\n * Test that training with a tree throws an exception when in naive mode.\n */\nBOOST_AUTO_TEST_CASE(NaiveTrainTreeTest)\n{\n  RangeSearch<> empty(true);\n\n  arma::mat dataset = arma::randu<arma::mat>(5, 100);\n  RangeSearch<>::Tree tree(dataset);\n\n  BOOST_REQUIRE_THROW(empty.Train(&tree), std::invalid_argument);\n}\n\n/**\n * Test that the move constructor works.\n */\nBOOST_AUTO_TEST_CASE(MoveConstructorMatrixTest)\n{\n  arma::mat dataset = arma::randu<arma::mat>(3, 100);\n  arma::mat copy(dataset);\n\n  RangeSearch<> movers(std::move(copy));\n  RangeSearch<> rs(dataset);\n\n  BOOST_REQUIRE_EQUAL(copy.n_elem, 0);\n  BOOST_REQUIRE_EQUAL(movers.ReferenceSet().n_rows, 3);\n  BOOST_REQUIRE_EQUAL(movers.ReferenceSet().n_cols, 100);\n\n  vector<vector<size_t>> moveNeighbors, neighbors;\n  vector<vector<double>> moveDistances, distances;\n\n  movers.Search(math::Range(0.5, 0.7), moveNeighbors, moveDistances);\n  rs.Search(math::Range(0.5, 0.7), neighbors, distances);\n\n  BOOST_REQUIRE_EQUAL(neighbors.size(), moveNeighbors.size());\n  BOOST_REQUIRE_EQUAL(distances.size(), moveDistances.size());\n\n  // Sort the results before comparing.\n  vector<vector<pair<double, size_t>>> sorted;\n  vector<vector<pair<double, size_t>>> moveSorted;\n  SortResults(neighbors, distances, sorted);\n  SortResults(moveNeighbors, moveDistances, moveSorted);\n\n  for (size_t i = 0; i < sorted.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(sorted[i].size(), moveSorted[i].size());\n    for (size_t j = 0; j < sorted[i].size(); ++j)\n    {\n      BOOST_REQUIRE_EQUAL(sorted[i][j].second, moveSorted[i][j].second);\n      BOOST_REQUIRE_CLOSE(sorted[i][j].first, moveSorted[i][j].first, 1e-5);\n    }\n  }\n}\n\n/**\n * Test that the std::move() Train() function works.\n */\nBOOST_AUTO_TEST_CASE(MoveTrainTest)\n{\n  arma::mat dataset = arma::randu<arma::mat>(3, 100);\n  arma::mat copy(dataset);\n\n  RangeSearch<> movers;\n  movers.Train(std::move(copy));\n  RangeSearch<> rs(dataset);\n\n  BOOST_REQUIRE_EQUAL(copy.n_elem, 0);\n  BOOST_REQUIRE_EQUAL(movers.ReferenceSet().n_rows, 3);\n  BOOST_REQUIRE_EQUAL(movers.ReferenceSet().n_cols, 100);\n\n  vector<vector<size_t>> moveNeighbors, neighbors;\n  vector<vector<double>> moveDistances, distances;\n\n  movers.Search(math::Range(0.5, 0.7), moveNeighbors, moveDistances);\n  rs.Search(math::Range(0.5, 0.7), neighbors, distances);\n\n  BOOST_REQUIRE_EQUAL(neighbors.size(), moveNeighbors.size());\n  BOOST_REQUIRE_EQUAL(distances.size(), moveDistances.size());\n\n  // Sort the results before comparing.\n  vector<vector<pair<double, size_t>>> sorted;\n  vector<vector<pair<double, size_t>>> moveSorted;\n  SortResults(neighbors, distances, sorted);\n  SortResults(moveNeighbors, moveDistances, moveSorted);\n\n  for (size_t i = 0; i < sorted.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(sorted[i].size(), moveSorted[i].size());\n    for (size_t j = 0; j < sorted[i].size(); ++j)\n    {\n      BOOST_REQUIRE_EQUAL(sorted[i][j].second, moveSorted[i][j].second);\n      BOOST_REQUIRE_CLOSE(sorted[i][j].first, moveSorted[i][j].first, 1e-5);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(RSModelTest)\n{\n  // Ensure that we can build an RSModel and get correct results.\n  arma::mat queryData = arma::randu<arma::mat>(10, 50);\n  arma::mat referenceData = arma::randu<arma::mat>(10, 200);\n\n  // Build all the possible models.\n  RSModel models[28];\n  models[0] = RSModel(RSModel::TreeTypes::KD_TREE, true);\n  models[1] = RSModel(RSModel::TreeTypes::KD_TREE, false);\n  models[2] = RSModel(RSModel::TreeTypes::COVER_TREE, true);\n  models[3] = RSModel(RSModel::TreeTypes::COVER_TREE, false);\n  models[4] = RSModel(RSModel::TreeTypes::R_TREE, true);\n  models[5] = RSModel(RSModel::TreeTypes::R_TREE, false);\n  models[6] = RSModel(RSModel::TreeTypes::R_STAR_TREE, true);\n  models[7] = RSModel(RSModel::TreeTypes::R_STAR_TREE, false);\n  models[8] = RSModel(RSModel::TreeTypes::X_TREE, true);\n  models[9] = RSModel(RSModel::TreeTypes::X_TREE, false);\n  models[10] = RSModel(RSModel::TreeTypes::BALL_TREE, true);\n  models[11] = RSModel(RSModel::TreeTypes::BALL_TREE, false);\n  models[12] = RSModel(RSModel::TreeTypes::HILBERT_R_TREE, true);\n  models[13] = RSModel(RSModel::TreeTypes::HILBERT_R_TREE, false);\n  models[14] = RSModel(RSModel::TreeTypes::R_PLUS_TREE, true);\n  models[15] = RSModel(RSModel::TreeTypes::R_PLUS_TREE, false);\n  models[16] = RSModel(RSModel::TreeTypes::R_PLUS_PLUS_TREE, true);\n  models[17] = RSModel(RSModel::TreeTypes::R_PLUS_PLUS_TREE, false);\n  models[18] = RSModel(RSModel::TreeTypes::VP_TREE, true);\n  models[19] = RSModel(RSModel::TreeTypes::VP_TREE, false);\n  models[20] = RSModel(RSModel::TreeTypes::RP_TREE, true);\n  models[21] = RSModel(RSModel::TreeTypes::RP_TREE, false);\n  models[22] = RSModel(RSModel::TreeTypes::MAX_RP_TREE, true);\n  models[23] = RSModel(RSModel::TreeTypes::MAX_RP_TREE, false);\n  models[24] = RSModel(RSModel::TreeTypes::UB_TREE, true);\n  models[25] = RSModel(RSModel::TreeTypes::UB_TREE, false);\n  models[26] = RSModel(RSModel::TreeTypes::OCTREE, true);\n  models[27] = RSModel(RSModel::TreeTypes::OCTREE, false);\n\n  for (size_t j = 0; j < 2; ++j)\n  {\n    // Get a baseline.\n    RangeSearch<> rs(referenceData);\n    vector<vector<size_t>> baselineNeighbors;\n    vector<vector<double>> baselineDistances;\n    rs.Search(queryData, math::Range(0.25, 0.75), baselineNeighbors,\n        baselineDistances);\n\n    vector<vector<pair<double, size_t>>> baselineSorted;\n    SortResults(baselineNeighbors, baselineDistances, baselineSorted);\n\n    for (size_t i = 0; i < 28; ++i)\n    {\n      // We only have std::move() constructors, so make a copy of our data.\n      arma::mat referenceCopy(referenceData);\n      arma::mat queryCopy(queryData);\n      if (j == 0)\n        models[i].BuildModel(std::move(referenceCopy), 5, false, false);\n      else if (j == 1)\n        models[i].BuildModel(std::move(referenceCopy), 5, false, true);\n      else if (j == 2)\n        models[i].BuildModel(std::move(referenceCopy), 5, true, false);\n\n      vector<vector<size_t>> neighbors;\n      vector<vector<double>> distances;\n\n      models[i].Search(std::move(queryCopy), math::Range(0.25, 0.75), neighbors,\n          distances);\n\n      BOOST_REQUIRE_EQUAL(neighbors.size(), baselineNeighbors.size());\n      BOOST_REQUIRE_EQUAL(distances.size(), baselineDistances.size());\n\n      vector<vector<pair<double, size_t>>> sorted;\n      SortResults(neighbors, distances, sorted);\n\n      for (size_t k = 0; k < sorted.size(); ++k)\n      {\n        BOOST_REQUIRE_EQUAL(sorted[k].size(), baselineSorted[k].size());\n        for (size_t l = 0; l < sorted[k].size(); ++l)\n        {\n          BOOST_REQUIRE_EQUAL(sorted[k][l].second, baselineSorted[k][l].second);\n          BOOST_REQUIRE_CLOSE(sorted[k][l].first, baselineSorted[k][l].first,\n              1e-5);\n        }\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(RSModelMonochromaticTest)\n{\n  // Ensure that we can build an RSModel and get correct results.\n  arma::mat referenceData = arma::randu<arma::mat>(10, 200);\n\n  // Build all the possible models.\n  RSModel models[28];\n  models[0] = RSModel(RSModel::TreeTypes::KD_TREE, true);\n  models[1] = RSModel(RSModel::TreeTypes::KD_TREE, false);\n  models[2] = RSModel(RSModel::TreeTypes::COVER_TREE, true);\n  models[3] = RSModel(RSModel::TreeTypes::COVER_TREE, false);\n  models[4] = RSModel(RSModel::TreeTypes::R_TREE, true);\n  models[5] = RSModel(RSModel::TreeTypes::R_TREE, false);\n  models[6] = RSModel(RSModel::TreeTypes::R_STAR_TREE, true);\n  models[7] = RSModel(RSModel::TreeTypes::R_STAR_TREE, false);\n  models[8] = RSModel(RSModel::TreeTypes::X_TREE, true);\n  models[9] = RSModel(RSModel::TreeTypes::X_TREE, false);\n  models[10] = RSModel(RSModel::TreeTypes::BALL_TREE, true);\n  models[11] = RSModel(RSModel::TreeTypes::BALL_TREE, false);\n  models[12] = RSModel(RSModel::TreeTypes::HILBERT_R_TREE, true);\n  models[13] = RSModel(RSModel::TreeTypes::HILBERT_R_TREE, false);\n  models[14] = RSModel(RSModel::TreeTypes::R_PLUS_TREE, true);\n  models[15] = RSModel(RSModel::TreeTypes::R_PLUS_TREE, false);\n  models[16] = RSModel(RSModel::TreeTypes::R_PLUS_PLUS_TREE, true);\n  models[17] = RSModel(RSModel::TreeTypes::R_PLUS_PLUS_TREE, false);\n  models[18] = RSModel(RSModel::TreeTypes::VP_TREE, true);\n  models[19] = RSModel(RSModel::TreeTypes::VP_TREE, false);\n  models[20] = RSModel(RSModel::TreeTypes::RP_TREE, true);\n  models[21] = RSModel(RSModel::TreeTypes::RP_TREE, false);\n  models[22] = RSModel(RSModel::TreeTypes::MAX_RP_TREE, true);\n  models[23] = RSModel(RSModel::TreeTypes::MAX_RP_TREE, false);\n  models[24] = RSModel(RSModel::TreeTypes::MAX_RP_TREE, true);\n  models[25] = RSModel(RSModel::TreeTypes::MAX_RP_TREE, false);\n  models[26] = RSModel(RSModel::TreeTypes::OCTREE, true);\n  models[27] = RSModel(RSModel::TreeTypes::OCTREE, false);\n\n  for (size_t j = 0; j < 2; ++j)\n  {\n    // Get a baseline.\n    RangeSearch<> rs(referenceData);\n    vector<vector<size_t>> baselineNeighbors;\n    vector<vector<double>> baselineDistances;\n    rs.Search(math::Range(0.25, 0.5), baselineNeighbors, baselineDistances);\n\n    vector<vector<pair<double, size_t>>> baselineSorted;\n    SortResults(baselineNeighbors, baselineDistances, baselineSorted);\n\n    for (size_t i = 0; i < 28; ++i)\n    {\n      // We only have std::move() cosntructors, so make a copy of our data.\n      arma::mat referenceCopy(referenceData);\n      if (j == 0)\n        models[i].BuildModel(std::move(referenceCopy), 5, false, false);\n      else if (j == 1)\n        models[i].BuildModel(std::move(referenceCopy), 5, false, true);\n      else if (j == 2)\n        models[i].BuildModel(std::move(referenceCopy), 5, true, false);\n\n      vector<vector<size_t>> neighbors;\n      vector<vector<double>> distances;\n\n      models[i].Search(math::Range(0.25, 0.5), neighbors, distances);\n\n      BOOST_REQUIRE_EQUAL(neighbors.size(), baselineNeighbors.size());\n      BOOST_REQUIRE_EQUAL(distances.size(), baselineDistances.size());\n\n      vector<vector<pair<double, size_t>>> sorted;\n      SortResults(neighbors, distances, sorted);\n\n      for (size_t k = 0; k < sorted.size(); ++k)\n      {\n        BOOST_REQUIRE_EQUAL(sorted[k].size(), baselineSorted[k].size());\n        for (size_t l = 0; l < sorted[k].size(); ++l)\n        {\n          BOOST_REQUIRE_EQUAL(sorted[k][l].second, baselineSorted[k][l].second);\n          BOOST_REQUIRE_CLOSE(sorted[k][l].first, baselineSorted[k][l].first,\n              1e-5);\n        }\n      }\n    }\n  }\n}\n\n/**\n * Make sure that the neighborPtr matrix isn't accidentally deleted.\n * See issue #478.\n */\nBOOST_AUTO_TEST_CASE(NeighborPtrDeleteTest)\n{\n  arma::mat dataset = arma::randu<arma::mat>(5, 100);\n\n  // Build the tree ourselves.\n  vector<size_t> oldFromNewReferences;\n  RangeSearch<>::Tree tree(dataset);\n  RangeSearch<> ra(&tree);\n\n  // Now make a query set.\n  arma::mat queryset = arma::randu<arma::mat>(5, 50);\n  vector<vector<double>> distances;\n  vector<vector<size_t>> neighbors;\n  ra.Search(queryset, math::Range(0.2, 0.5), neighbors, distances);\n\n  // These will (hopefully) fail is either the neighbors or the distances matrix\n  // has been accidentally deleted.\n  BOOST_REQUIRE_EQUAL(neighbors.size(), 50);\n  BOOST_REQUIRE_EQUAL(distances.size(), 50);\n}\n\n/**\n * Test copy constructor and copy operator.\n */\nBOOST_AUTO_TEST_CASE(CopyConstructorAndOperatorTest)\n{\n  arma::mat dataset = arma::randu<arma::mat>(5, 500);\n  RangeSearch<> rs(std::move(dataset));\n\n  // Copy constructor and operator.\n  RangeSearch<> rs2(rs);\n  RangeSearch<> rs3 = rs;\n\n  // Get results.\n  vector<vector<double>> distances, distances2, distances3;\n  vector<vector<size_t>> neighbors, neighbors2, neighbors3;\n\n  rs.Search(math::Range(0.2, 0.3), neighbors, distances);\n  rs2.Search(math::Range(0.2, 0.3), neighbors2, distances2);\n  rs3.Search(math::Range(0.2, 0.3), neighbors3, distances3);\n\n  // Check results.\n  BOOST_REQUIRE_EQUAL(distances.size(), distances2.size());\n  BOOST_REQUIRE_EQUAL(distances.size(), distances3.size());\n  BOOST_REQUIRE_EQUAL(neighbors.size(), neighbors2.size());\n  BOOST_REQUIRE_EQUAL(neighbors.size(), neighbors3.size());\n\n  for (size_t i = 0; i < neighbors.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(distances[i].size(), distances2[i].size());\n    BOOST_REQUIRE_EQUAL(distances[i].size(), distances3[i].size());\n    BOOST_REQUIRE_EQUAL(neighbors[i].size(), neighbors2[i].size());\n    BOOST_REQUIRE_EQUAL(neighbors[i].size(), neighbors3[i].size());\n\n    for (size_t j = 0; j < neighbors[i].size(); ++j)\n    {\n      BOOST_REQUIRE_EQUAL(neighbors[i][j], neighbors2[i][j]);\n      BOOST_REQUIRE_EQUAL(neighbors[i][j], neighbors3[i][j]);\n\n      // Distances will always be between 0.2 and 0.3.\n      BOOST_REQUIRE_CLOSE(distances[i][j], distances2[i][j], 1e-5);\n      BOOST_REQUIRE_CLOSE(distances[i][j], distances3[i][j], 1e-5);\n    }\n  }\n}\n\n/**\n * Test move constructor.\n */\nBOOST_AUTO_TEST_CASE(MoveConstructorTest)\n{\n  arma::mat dataset = arma::randu<arma::mat>(5, 500);\n  RangeSearch<>* rs = new RangeSearch<>(std::move(dataset));\n\n  // Get results.\n  vector<vector<double>> distances, distances2;\n  vector<vector<size_t>> neighbors, neighbors2;\n\n  rs->Search(math::Range(0.2, 0.3), neighbors, distances);\n\n  RangeSearch<> rs2(std::move(*rs));\n\n  delete rs;\n\n  rs2.Search(math::Range(0.2, 0.3), neighbors2, distances2);\n\n  // Check results.\n  BOOST_REQUIRE_EQUAL(distances.size(), distances2.size());\n  BOOST_REQUIRE_EQUAL(neighbors.size(), neighbors2.size());\n\n  for (size_t i = 0; i < neighbors.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(distances[i].size(), distances2[i].size());\n    BOOST_REQUIRE_EQUAL(neighbors[i].size(), neighbors2[i].size());\n\n    for (size_t j = 0; j < neighbors[i].size(); ++j)\n    {\n      BOOST_REQUIRE_EQUAL(neighbors[i][j], neighbors2[i][j]);\n\n      // Distances will always be between 0.2 and 0.3.\n      BOOST_REQUIRE_CLOSE(distances[i][j], distances2[i][j], 1e-5);\n    }\n  }\n}\n\n/**\n * Test move operator.\n */\nBOOST_AUTO_TEST_CASE(MoveOperatorTest)\n{\n  arma::mat dataset = arma::randu<arma::mat>(5, 500);\n  RangeSearch<>* rs = new RangeSearch<>(std::move(dataset));\n\n  // Get results.\n  vector<vector<double>> distances, distances2;\n  vector<vector<size_t>> neighbors, neighbors2;\n\n  rs->Search(math::Range(0.2, 0.3), neighbors, distances);\n\n  RangeSearch<> rs2 = std::move(*rs);\n\n  delete rs;\n\n  rs2.Search(math::Range(0.2, 0.3), neighbors2, distances2);\n\n  // Check results.\n  BOOST_REQUIRE_EQUAL(distances.size(), distances2.size());\n  BOOST_REQUIRE_EQUAL(neighbors.size(), neighbors2.size());\n\n  for (size_t i = 0; i < neighbors.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(distances[i].size(), distances2[i].size());\n    BOOST_REQUIRE_EQUAL(neighbors[i].size(), neighbors2[i].size());\n\n    for (size_t j = 0; j < neighbors[i].size(); ++j)\n    {\n      BOOST_REQUIRE_EQUAL(neighbors[i][j], neighbors2[i][j]);\n\n      // Distances will always be between 0.2 and 0.3.\n      BOOST_REQUIRE_CLOSE(distances[i][j], distances2[i][j], 1e-5);\n    }\n  }\n}\n\n/**\n * Test copy constructor and copy operator in naive mode (so there are no\n * trees).\n */\nBOOST_AUTO_TEST_CASE(CopyConstructorAndOperatorNaiveTest)\n{\n  arma::mat dataset = arma::randu<arma::mat>(5, 500);\n  RangeSearch<> rs(std::move(dataset), true);\n\n  // Copy constructor and operator.\n  RangeSearch<> rs2(rs);\n  RangeSearch<> rs3 = rs;\n\n  BOOST_REQUIRE_EQUAL(rs2.Naive(), true);\n  BOOST_REQUIRE_EQUAL(rs3.Naive(), true);\n\n  // Get results.\n  vector<vector<double>> distances, distances2, distances3;\n  vector<vector<size_t>> neighbors, neighbors2, neighbors3;\n\n  rs.Search(math::Range(0.2, 0.3), neighbors, distances);\n  rs2.Search(math::Range(0.2, 0.3), neighbors2, distances2);\n  rs3.Search(math::Range(0.2, 0.3), neighbors3, distances3);\n\n  // Check results.\n  BOOST_REQUIRE_EQUAL(distances.size(), distances2.size());\n  BOOST_REQUIRE_EQUAL(distances.size(), distances3.size());\n  BOOST_REQUIRE_EQUAL(neighbors.size(), neighbors2.size());\n  BOOST_REQUIRE_EQUAL(neighbors.size(), neighbors3.size());\n\n  for (size_t i = 0; i < neighbors.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(distances[i].size(), distances2[i].size());\n    BOOST_REQUIRE_EQUAL(distances[i].size(), distances3[i].size());\n    BOOST_REQUIRE_EQUAL(neighbors[i].size(), neighbors2[i].size());\n    BOOST_REQUIRE_EQUAL(neighbors[i].size(), neighbors3[i].size());\n\n    for (size_t j = 0; j < neighbors[i].size(); ++j)\n    {\n      BOOST_REQUIRE_EQUAL(neighbors[i][j], neighbors2[i][j]);\n      BOOST_REQUIRE_EQUAL(neighbors[i][j], neighbors3[i][j]);\n\n      // Distances will always be between 0.2 and 0.3.\n      BOOST_REQUIRE_CLOSE(distances[i][j], distances2[i][j], 1e-5);\n      BOOST_REQUIRE_CLOSE(distances[i][j], distances3[i][j], 1e-5);\n    }\n  }\n}\n\n/**\n * Test move constructor.\n */\nBOOST_AUTO_TEST_CASE(MoveConstructorNaiveTest)\n{\n  arma::mat dataset = arma::randu<arma::mat>(5, 500);\n  RangeSearch<>* rs = new RangeSearch<>(std::move(dataset), true);\n\n  // Get results.\n  vector<vector<double>> distances, distances2;\n  vector<vector<size_t>> neighbors, neighbors2;\n\n  rs->Search(math::Range(0.2, 0.3), neighbors, distances);\n\n  RangeSearch<> rs2(std::move(*rs));\n\n  BOOST_REQUIRE_EQUAL(rs2.Naive(), true);\n\n  delete rs;\n\n  rs2.Search(math::Range(0.2, 0.3), neighbors2, distances2);\n\n  // Check results.\n  BOOST_REQUIRE_EQUAL(distances.size(), distances2.size());\n  BOOST_REQUIRE_EQUAL(neighbors.size(), neighbors2.size());\n\n  for (size_t i = 0; i < neighbors.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(distances[i].size(), distances2[i].size());\n    BOOST_REQUIRE_EQUAL(neighbors[i].size(), neighbors2[i].size());\n\n    for (size_t j = 0; j < neighbors[i].size(); ++j)\n    {\n      BOOST_REQUIRE_EQUAL(neighbors[i][j], neighbors2[i][j]);\n\n      // Distances will always be between 0.2 and 0.3.\n      BOOST_REQUIRE_CLOSE(distances[i][j], distances2[i][j], 1e-5);\n    }\n  }\n}\n\n/**\n * Test move operator.\n */\nBOOST_AUTO_TEST_CASE(MoveOperatorNaiveTest)\n{\n  arma::mat dataset = arma::randu<arma::mat>(5, 500);\n  RangeSearch<>* rs = new RangeSearch<>(std::move(dataset), true);\n\n  // Get results.\n  vector<vector<double>> distances, distances2;\n  vector<vector<size_t>> neighbors, neighbors2;\n\n  rs->Search(math::Range(0.2, 0.3), neighbors, distances);\n\n  RangeSearch<> rs2 = std::move(*rs);\n\n  BOOST_REQUIRE_EQUAL(rs2.Naive(), true);\n\n  delete rs;\n\n  rs2.Search(math::Range(0.2, 0.3), neighbors2, distances2);\n\n  // Check results.\n  BOOST_REQUIRE_EQUAL(distances.size(), distances2.size());\n  BOOST_REQUIRE_EQUAL(neighbors.size(), neighbors2.size());\n\n  for (size_t i = 0; i < neighbors.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(distances[i].size(), distances2[i].size());\n    BOOST_REQUIRE_EQUAL(neighbors[i].size(), neighbors2[i].size());\n\n    for (size_t j = 0; j < neighbors[i].size(); ++j)\n    {\n      BOOST_REQUIRE_EQUAL(neighbors[i][j], neighbors2[i][j]);\n\n      // Distances will always be between 0.2 and 0.3.\n      BOOST_REQUIRE_CLOSE(distances[i][j], distances2[i][j], 1e-5);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "33dd5c56ca82f3bfaf03ba6d5240b0bb57cc7058", "size": 63151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/range_search_test.cpp", "max_stars_repo_name": "gaurav-singh1998/mlpack", "max_stars_repo_head_hexsha": "c104a2dcf0b51a98d9d6fcfc01d4e7047cc83872", "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/range_search_test.cpp", "max_issues_repo_name": "R-Aravind/mlpack", "max_issues_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "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/range_search_test.cpp", "max_forks_repo_name": "R-Aravind/mlpack", "max_forks_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-17T21:33:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-17T21:33:59.000Z", "avg_line_length": 37.1476470588, "max_line_length": 80, "alphanum_fraction": 0.6797200361, "num_tokens": 18117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5135906252041946}}
{"text": "#include <kdl/frames.hpp>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nnamespace dr {\n\n/// Convert a KDL vector to an Eigen vector.\nEigen::Vector3d toEigen(KDL::Vector const & input) {\n\treturn Eigen::Vector3d{input[0], input[1], input[2]};\n}\n\n/// Convert an Eigen vector to a KDL vector.\nKDL::Vector toKdlVector(Eigen::Vector3d const & input) {\n\treturn KDL::Vector{input.x(), input.y(), input.z()};\n}\n\n/// Convert a KDL rotation to an Eigen quaternion.\nEigen::Quaterniond toEigen(KDL::Rotation const & input) {\n\tEigen::Quaterniond result;\n\tinput.GetQuaternion(result.x(), result.y(), result.z(), result.w());\n\treturn result;\n}\n\n/// Convert a KDL rotation to an Eigen rotation matrix.\nEigen::Matrix3d toEigenMatrix(KDL::Rotation const & input) {\n\treturn (Eigen::Matrix3d{} <<\n\t\tinput(0, 0),  input(0, 1), input(0, 2),\n\t\tinput(1, 0),  input(1, 1), input(1, 2),\n\t\tinput(2, 0),  input(2, 1), input(2, 2)\n\t).finished();\n}\n\n/// Convert an Eigen quaternion to a KDL rotation.\nKDL::Rotation toKdlRotation(Eigen::Quaterniond const & input) {\n\treturn KDL::Rotation::Quaternion(input.x(), input.y(), input.z(), input.w());\n}\n\n/// Convert an Eigen rotation matrix to a KDL rotation.\nKDL::Rotation toKdlRotation(Eigen::Matrix3d const & input) {\n\tKDL::Rotation result;\n\tfor (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) {\n\t\tresult(i, j) = input(i, j);\n\t}\n\treturn result;\n}\n\n/// Convert a KDL frame to an Eigen isometry.\nEigen::Isometry3d toEigen(KDL::Frame const & input) {\n\treturn Eigen::Translation3d(toEigen(input.p)) * toEigen(input.M);\n}\n\n/// Convert an Eigen isometry to a KDL frame.\nKDL::Frame toKdlFrame(Eigen::Isometry3d const & input) {\n\treturn {toKdlRotation(input.rotation()), toKdlVector(Eigen::Vector3d{input.translation()})};\n}\n\n}\n", "meta": {"hexsha": "297277552f93acc04ad834108d5e62e240437523", "size": 1743, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dr_kdl/eigen.hpp", "max_stars_repo_name": "aprotyas/dr_kdl", "max_stars_repo_head_hexsha": "22ed656048f23652dbf8e744d41ce10a7a731c03", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-12T20:34:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T03:43:56.000Z", "max_issues_repo_path": "include/dr_kdl/eigen.hpp", "max_issues_repo_name": "aprotyas/dr_kdl", "max_issues_repo_head_hexsha": "22ed656048f23652dbf8e744d41ce10a7a731c03", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-09T09:49:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-09T09:49:46.000Z", "max_forks_repo_path": "include/dr_kdl/eigen.hpp", "max_forks_repo_name": "aprotyas/dr_kdl", "max_forks_repo_head_hexsha": "22ed656048f23652dbf8e744d41ce10a7a731c03", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-07-09T04:05:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T23:31:07.000Z", "avg_line_length": 30.0517241379, "max_line_length": 93, "alphanum_fraction": 0.6821572002, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5135906252041945}}
{"text": "/* Copyright (C) 2012-2019 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#include <NTL/ZZ.h>\n#include <algorithm>\n#include <complex>\n\n#include \"norms.h\"\n#include \"helib.h\"\n#include \"debugging.h\"\n#include \"ArgMap.h\"\n\nNTL_CLIENT\nusing namespace helib;\n\nbool verbose=false;\n\n// Compute the L-infinity distance between two vectors\ndouble calcMaxDiff(const vector<cx_double>& v1, \n                   const vector<cx_double>& v2){\n\n  if(lsize(v1)!=lsize(v2))\n    NTL::Error(\"Vector sizes differ.\\nFAILED\\n\");\n\n  double maxDiff = 0.0;  \n  for (long i=0; i<lsize(v1); i++) {\n    double diffAbs = std::abs(v1[i]-v2[i]);\n    if (diffAbs > maxDiff)\n      maxDiff = diffAbs;\n  }\n\n  return maxDiff;\n}\n// Compute the max relative difference between two vectors\ndouble calcMaxRelDiff(const vector<cx_double>& v1,\n                   const vector<cx_double>& v2)\n{\n    if(lsize(v1)!=lsize(v2))\n        NTL::Error(\"Vector sizes differ.\\nFAILED\\n\");\n\n    // Compute the largest-magnitude value in the vector\n    double maxAbs = 0.0;\n    for (auto& x : v1) {\n        if (std::abs(x) > maxAbs)\n            maxAbs = std::abs(x);\n    }\n    if (maxAbs<1e-10)\n        maxAbs = 1e-10;\n\n    double maxDiff = 0.0;\n    for (long i=0; i<lsize(v1); i++) {\n        double relDiff = std::abs(v1[i]-v2[i]) / maxAbs;\n        if (relDiff > maxDiff)\n            maxDiff = relDiff;\n    }\n\n    return maxDiff;\n}\n\ninline bool cx_equals(const vector<cx_double>& v1, \n                      const vector<cx_double>& v2, \n                      double epsilon)\n{\n  return (calcMaxRelDiff(v1,v2) < epsilon);\n}\n\nvoid testBasicArith(const FHEPubKey& publicKey, \n                    const FHESecKey& secretKey, \n                    const EncryptedArrayCx& ea, double epsilon);\nvoid testComplexArith(const FHEPubKey& publicKey, \n                      const FHESecKey& secretKey, \n                      const EncryptedArrayCx& ea, double epsilon);\nvoid testRotsNShifts(const FHEPubKey& publicKey, \n                     const FHESecKey& secretKey, \n                     const EncryptedArrayCx& ea, double epsilon);\n\nvoid debugCompare(const EncryptedArrayCx& ea, const FHESecKey& sk,\n        vector<cx_double>& p, const Ctxt& c, double epsilon)\n{\n  vector<cx_double> pp;\n  ea.decrypt(c, sk, pp);\n  std::cout << \"    relative-error=\"<<calcMaxRelDiff(p,pp)\n            << \", absolute-error=\"<<calcMaxRelDiff(p,pp)<<endl;\n//  if (!cx_equals(pp, p, epsilon)) {\n//    std::cout << \"oops:\\n\"; std::cout << p << \"\\n\";\n//    std::cout << pp << \"\\n\";\n//    exit(0);\n//  }\n}\n\n\nvoid negateVec(vector<cx_double>& p1)\n{\n  for (auto& x: p1) x = -x;\n}\nvoid add(vector<cx_double>& to, const vector<cx_double>& from)\n{\n  if (to.size() < from.size())\n    to.resize(from.size(), 0);\n  for (long i=0; i<from.size(); i++) to[i] += from[i];\n}\nvoid sub(vector<cx_double>& to, const vector<cx_double>& from)\n{\n  if (to.size() < from.size())\n    to.resize(from.size(), 0);\n  for (long i=0; i<from.size(); i++) to[i] -= from[i];\n}\nvoid mul(vector<cx_double>& to, const vector<cx_double>& from)\n{\n  if (to.size() < from.size())\n    to.resize(from.size(), 0);\n  for (long i=0; i<from.size(); i++) to[i] *= from[i];\n}\nvoid rotate(vector<cx_double>& p, long amt)\n{\n  long sz = p.size();\n  vector<cx_double> tmp(sz);\n  for (long i=0; i<sz; i++)\n    tmp[((i+amt)%sz +sz)%sz] = p[i];\n  p = tmp;\n}\n\n/************** Each round consists of the following:\n1. c1.multiplyBy(c0)\n2. c0 += random constant\n3. c2 *= random constant\n4. tmp = c1\n5. ea.rotate(tmp, random amount in [-nSlots/2, nSlots/2])\n6. c2 += tmp\n7. ea.rotate(c2, random amount in [1-nSlots, nSlots-1])\n8. c1.negate()\n9. c3.multiplyBy(c2) \n10. c0 -= c3\n**************/\nvoid testGeneralOps(const FHEPubKey& publicKey, const FHESecKey& secretKey,\n                    const EncryptedArrayCx& ea, double epsilon,\n                    long nRounds)\n{\n  long nslots = ea.size();\n  char buffer[32];\n\n  vector<cx_double> p0, p1, p2, p3;\n  ea.random(p0);\n  ea.random(p1);\n  ea.random(p2);\n  ea.random(p3);\n\n  Ctxt c0(publicKey), c1(publicKey), c2(publicKey), c3(publicKey);\n  ea.encrypt(c0, publicKey, p0, /*size=*/1.0);\n  ea.encrypt(c1, publicKey, p1, /*size=*/1.0);\n  ea.encrypt(c2, publicKey, p2, /*size=*/1.0);\n  ea.encrypt(c3, publicKey, p3, /*size=*/1.0);\n\n  resetAllTimers();\n  FHE_NTIMER_START(Circuit);\n\n  for (long i = 0; i < nRounds; i++) {\n\n    if (verbose) std::cout << \"*** round \" << i << \"...\"<<endl;\n\n     long shamt = RandomBnd(2*(nslots/2) + 1) - (nslots/2);\n                  // random number in [-nslots/2..nslots/2]\n     long rotamt = RandomBnd(2*nslots - 1) - (nslots - 1);\n                  // random number in [-(nslots-1)..nslots-1]\n\n     // two random constants\n     vector<cx_double> const1, const2;\n     ea.random(const1);\n     ea.random(const2);\n\n     ZZX const1_poly, const2_poly;\n     ea.encode(const1_poly, const1, /*size=*/1.0);\n     ea.encode(const2_poly, const2, /*size=*/1.0);\n\n     mul(p1, p0);     // c1.multiplyBy(c0)\n     c1.multiplyBy(c0);\n     if (verbose) {\n       CheckCtxt(c1, \"c1*=c0\");\n       debugCompare(ea, secretKey, p1, c1, epsilon);\n     }\n\n     add(p0, const1); // c0 += random constant\n     c0.addConstant(const1_poly);\n     if (verbose) {\n       CheckCtxt(c0, \"c0+=k1\");\n       debugCompare(ea, secretKey, p0, c0, epsilon);\n     }\n     mul(p2, const2); // c2 *= random constant\n     c2.multByConstant(const2_poly);\n     if (verbose) {\n       CheckCtxt(c2, \"c2*=k2\");\n       debugCompare(ea, secretKey, p2, c2, epsilon);\n     }\n     vector<cx_double> tmp_p(p1); // tmp = c1\n     Ctxt tmp(c1);\n     sprintf(buffer, \"tmp=c1>>=%d\", (int)shamt);\n     rotate(tmp_p, shamt); // ea.shift(tmp, random amount in [-nSlots/2,nSlots/2])\n     ea.rotate(tmp, shamt);\n     if (verbose) {\n       CheckCtxt(tmp, buffer);\n       debugCompare(ea, secretKey, tmp_p, tmp, epsilon);\n     }\n     add(p2, tmp_p);  // c2 += tmp\n     c2 += tmp;\n     if (verbose) {\n       CheckCtxt(c2, \"c2+=tmp\");\n       debugCompare(ea, secretKey, p2, c2, epsilon);\n     }\n     sprintf(buffer, \"c2>>>=%d\", (int)rotamt);\n     rotate(p2, rotamt); // ea.rotate(c2, random amount in [1-nSlots, nSlots-1])\n     ea.rotate(c2, rotamt);\n     if (verbose) {\n       CheckCtxt(c2, buffer);\n       debugCompare(ea, secretKey, p2, c2, epsilon);\n     }\n     negateVec(p1); // c1.negate()\n     c1.negate();\n     if (verbose) {\n       CheckCtxt(c1, \"c1=-c1\");\n       debugCompare(ea, secretKey, p1, c1, epsilon);\n     }\n     mul(p3, p2); // c3.multiplyBy(c2) \n     c3.multiplyBy(c2);\n     if (verbose) {\n       CheckCtxt(c3, \"c3*=c2\");\n       debugCompare(ea, secretKey, p3, c3, epsilon);\n     }\n     sub(p0, p3); // c0 -= c3\n     c0 -= c3;\n     if (verbose) {\n       CheckCtxt(c0, \"c0=-c3\");\n       debugCompare(ea, secretKey, p0, c0, epsilon);\n     }\n  }\n\n  c0.cleanUp();\n  c1.cleanUp();\n  c2.cleanUp();\n  c3.cleanUp();\n\n  FHE_NTIMER_STOP(Circuit);\n\n  vector<cx_double> pp0, pp1, pp2, pp3;\n   \n  ea.decrypt(c0, secretKey, pp0);\n  ea.decrypt(c1, secretKey, pp1);\n  ea.decrypt(c2, secretKey, pp2);\n  ea.decrypt(c3, secretKey, pp3);\n\n  std::cout << \"Test \"<<nRounds<<\" rounds of mixed operations, \";\n  if (cx_equals(pp0, p0,conv<double>(epsilon*c0.getPtxtMag()))\n      && cx_equals(pp1, p1,conv<double>(epsilon*c1.getPtxtMag()))\n      && cx_equals(pp2, p2,conv<double>(epsilon*c2.getPtxtMag()))\n      && cx_equals(pp3, p3,conv<double>(epsilon*c3.getPtxtMag())))\n    std::cout << \"PASS\\n\\n\";\n  else {\n    std::cout << \"FAIL:\\n\";\n    std::cout << \"  max(p0)=\"<<largestCoeff(p0)\n              << \", max(pp0)=\"<<largestCoeff(pp0)\n              << \", maxDiff=\"<<calcMaxDiff(p0,pp0) << endl;\n    std::cout << \"  max(p1)=\"<<largestCoeff(p1)\n              << \", max(pp1)=\"<<largestCoeff(pp1)\n              << \", maxDiff=\"<<calcMaxDiff(p1,pp1) << endl;\n    std::cout << \"  max(p2)=\"<<largestCoeff(p2)\n              << \", max(pp2)=\"<<largestCoeff(pp2)\n              << \", maxDiff=\"<<calcMaxDiff(p2,pp2) << endl;\n    std::cout << \"  max(p3)=\"<<largestCoeff(p3)\n              << \", max(pp3)=\"<<largestCoeff(pp3)\n              << \", maxDiff=\"<<calcMaxDiff(p3,pp3) << endl<<endl;\n  }\n\n  if (verbose) {\n    std::cout << endl;\n    printAllTimers();\n    std::cout << endl;\n  }\n  resetAllTimers();\n   }\n\nint main(int argc, char *argv[]) \n{\n\n  // Commandline setup\n\n  ArgMap amap;\n\n  long m=16;\n  long r=8;\n  long L=0;\n  double epsilon=0.01; // Accepted accuracy\n  long R=1;\n  long seed=0;\n  bool debug = false;\n\n  amap.arg(\"m\", m, \"Cyclotomic index\");\n  amap.note(\"e.g., m=1024, m=2047\");\n  amap.arg(\"r\", r, \"Bits of precision\");\n  amap.arg(\"R\", R, \"number of rounds\");\n  amap.arg(\"L\", L, \"Number of bits in modulus\", \"heuristic\");\n  amap.arg(\"ep\", epsilon, \"Accepted accuracy\");\n  amap.arg(\"seed\", seed, \"PRG seed\");\n  amap.arg(\"verbose\", verbose, \"more printouts\");\n  amap.arg(\"debug\", debug, \"for debugging\");\n\n  amap.parse(argc, argv);\n\n  if (seed)\n    NTL::SetSeed(ZZ(seed));\n\n  if (R<=0) R=1;\n  if (R<=2)\n    L = 100*R;\n  else\n    L = 220*(R-1);\n\n  if (verbose) {\n    cout << \"** m=\"<<m<<\", #rounds=\"<<R<<\", |q|=\"<<L\n         << \", epsilon=\"<<epsilon<<endl;\n  }\n  epsilon /= R;\n  try{\n\n    // FHE setup keys, context, SKMs, etc\n\n    FHEcontext context(m, /*p=*/-1, r);\n    context.scale=4;\n    buildModChain(context, L, /*c=*/2);\n\n    FHESecKey secretKey(context);\n    secretKey.GenSecKey(); // A +-1/0 secret key\n    addSome1DMatrices(secretKey); // compute key-switching matrices\n\n    const FHEPubKey publicKey = secretKey;\n    const EncryptedArrayCx& ea = context.ea->getCx();\n\n    if (verbose) {\n      ea.getPAlgebra().printout();\n      cout << \"r = \" << context.alMod.getR() << endl;\n      cout << \"ctxtPrimes=\"<<context.ctxtPrimes\n           << \", specialPrimes=\"<<context.specialPrimes<<endl<<endl;\n    }\n    if (debug) {\n        dbgKey = & secretKey;\n        dbgEa = (EncryptedArray*) context.ea;\n    }\n#ifdef DEBUG_PRINTOUT\n          dbgKey = & secretKey;\n          dbgEa = (EncryptedArray*) context.ea;\n#endif //DEBUG_PRINTOUT\n\n    // Run the tests.\n    testBasicArith(publicKey, secretKey, ea, epsilon);\n    testComplexArith(publicKey, secretKey, ea, epsilon);\n    testRotsNShifts(publicKey, secretKey, ea, epsilon);\n    testGeneralOps(publicKey, secretKey, ea, epsilon*R, R);\n  } \n  catch (exception& e) {\n    cerr << e.what() << endl;\n    cerr << \"***Major FAIL***\" << endl;  \n  }\n\n  return 0;\n}\n\n\nvoid testBasicArith(const FHEPubKey& publicKey,\n                    const FHESecKey& secretKey,\n                    const EncryptedArrayCx& ea, double epsilon)\n{\n  if (verbose)  cout << \"Test Arithmetic \";\n  // Test objects\n\n  Ctxt c1(publicKey), c2(publicKey), c3(publicKey);\n  \n  vector<cx_double> vd;\n  vector<cx_double> vd1, vd2, vd3;\n  ea.random(vd1);\n  ea.random(vd2);\n\n  // test encoding of shorter vectors\n  vd1.resize(vd1.size()-2);\n  ea.encrypt(c1, publicKey, vd1, /*size=*/1.0);\n  vd1.resize(vd1.size()+2, 0.0);\n\n  ea.encrypt(c2, publicKey, vd2, /*size=*/1.0);\n\n  // Test - Multiplication\n  c1 *= c2;\n  for (long i=0; i<lsize(vd1); i++) vd1[i] *= vd2[i];\n\n  ZZX poly;\n  ea.random(vd3);\n  ea.encode(poly, vd3, /*size=*/1.0);\n  c1.addConstant(poly); // vd1*vd2 + vd3\n  for (long i=0; i<lsize(vd1); i++) vd1[i] += vd3[i];\n\n  // Test encoding, encryption of a single number\n  double xx = NTL::RandomLen_long(16)/double(1L<<16); // random in [0,1]\n  ea.encryptOneNum(c2, publicKey, xx);\n  c1 += c2;\n  for (auto& x : vd1) x += xx;\n\n  // Test - Multiply by a mask\n  vector<long> mask(lsize(vd1), 1);\n  for (long i=0; i*(i+1)<lsize(mask); i++) {\n    mask[i*i] = 0;\n    mask[i*(i+1)] = -1;\n  }\n\n  ea.encode(poly,mask, /*size=*/1.0);\n  c1.multByConstant(poly); // mask*(vd1*vd2 + vd3)\n  for (long i=0; i<lsize(vd1); i++) vd1[i] *= mask[i];\n\n  // Test - Addition\n  ea.random(vd3);\n  ea.encrypt(c3, publicKey, vd3, /*size=*/1.0);\n  c1 += c3;\n  for (long i=0; i<lsize(vd1); i++) vd1[i] += vd3[i];\n\n  c1.negate();\n  c1.addConstant(to_ZZ(1));\n  for (long i=0; i<lsize(vd1); i++) vd1[i] = 1.0 - vd1[i];\n\n  // Diff between approxNums HE scheme and plaintext floating  \n  ea.decrypt(c1, secretKey, vd);\n#ifdef DEBUG_PRINTOUT\n  printVec(cout<<\"res=\", vd, 10)<<endl;\n  printVec(cout<<\"vec=\", vd1, 10)<<endl;\n#endif\n  if (verbose)\n    cout << \"(max |res-vec|_{infty}=\"<< calcMaxDiff(vd, vd1) << \"): \";\n\n  if (cx_equals(vd, vd1, conv<double>(epsilon*c1.getPtxtMag())))\n    cout << \"GOOD\\n\";\n  else {\n    cout << \"BAD:\\n\";\n    std::cout << \"  max(vd)=\"<<largestCoeff(vd)\n              << \", max(vd1)=\"<<largestCoeff(vd1)\n              << \", maxDiff=\"<<calcMaxDiff(vd,vd1) << endl<<endl;\n  }\n}\n\n\nvoid testComplexArith(const FHEPubKey& publicKey,\n                      const FHESecKey& secretKey,\n                      const EncryptedArrayCx& ea, double epsilon)\n{\n\n  // Test complex conjugate\n  Ctxt c1(publicKey), c2(publicKey);\n\n  vector<cx_double> vd;\n  vector<cx_double> vd1, vd2;\n  ea.random(vd1);\n  ea.random(vd2);\n   \n  ea.encrypt(c1, publicKey, vd1, /*size=*/1.0);\n  ea.encrypt(c2, publicKey, vd2, /*size=*/1.0);\n\n  if (verbose)\n    cout << \"Test Conjugate: \";\n  for_each(vd1.begin(), vd1.end(), [](cx_double& d){d=std::conj(d);});\n  c1.complexConj();  \n  ea.decrypt(c1, secretKey, vd);\n#ifdef DEBUG_PRINTOUT\n  printVec(cout<<\"vd1=\", vd1, 10)<<endl;\n  printVec(cout<<\"res=\", vd, 10)<<endl;\n#endif\n  if (cx_equals(vd, vd1, conv<double>(epsilon*c1.getPtxtMag())))\n    cout << \"GOOD\\n\";\n  else {\n    cout << \"BAD:\\n\";\n    std::cout << \"  max(vd)=\"<<largestCoeff(vd)\n              << \", max(vd1)=\"<<largestCoeff(vd1)\n              << \", maxDiff=\"<<calcMaxDiff(vd,vd1) << endl<<endl;\n  }\n\n  // Test that real and imaginary parts are actually extracted.\n  Ctxt realCtxt(c2), imCtxt(c2);\n  vector<cx_double> realParts(vd2), real_dec;\n  vector<cx_double> imParts(vd2), im_dec;\n\n  if (verbose)\n    cout << \"Test Real and Im parts: \";\n  for_each(realParts.begin(), realParts.end(), [](cx_double& d){d=std::real(d);});\n  for_each(imParts.begin(), imParts.end(), [](cx_double& d){d=std::imag(d);});\n\n  ea.extractRealPart(realCtxt);\n  ea.decrypt(realCtxt, secretKey, real_dec);\n\n  ea.extractImPart(imCtxt);\n  ea.decrypt(imCtxt, secretKey, im_dec);\n\n#ifdef DEBUG_PRINTOUT\n  printVec(cout<<\"vd2=\", vd2, 10)<<endl;\n  printVec(cout<<\"real=\", realParts, 10)<<endl;\n  printVec(cout<<\"res=\", real_dec, 10)<<endl;\n  printVec(cout<<\"im=\", imParts, 10)<<endl;\n  printVec(cout<<\"res=\", im_dec, 10)<<endl;\n#endif\n  if (cx_equals(realParts,real_dec,conv<double>(epsilon*realCtxt.getPtxtMag()))\n      && cx_equals(imParts, im_dec, conv<double>(epsilon*imCtxt.getPtxtMag())))\n    cout << \"GOOD\\n\";\n  else {\n    cout << \"BAD:\\n\";\n    std::cout << \"  max(re)=\"<<largestCoeff(realParts)\n              << \", max(re1)=\"<<largestCoeff(real_dec)\n              << \", maxDiff=\"<<calcMaxDiff(realParts,real_dec) << endl;\n    std::cout << \"  max(im)=\"<<largestCoeff(imParts)\n              << \", max(im1)=\"<<largestCoeff(im_dec)\n              << \", maxDiff=\"<<calcMaxDiff(imParts,im_dec) << endl<<endl;\n  }\n}\n\nvoid testRotsNShifts(const FHEPubKey& publicKey, \n                     const FHESecKey& secretKey,\n                     const EncryptedArrayCx& ea, double epsilon)\n{\n\n  std::srand(std::time(0)); // set seed, current time.\n  int nplaces = rand() % static_cast<int>(ea.size()/2.0) + 1;\n\n  if (verbose)\n    cout << \"Test Rotation of \" << nplaces << \": \";  \n\n  Ctxt c1(publicKey);\n  vector<cx_double> vd1;\n  vector<cx_double> vd_dec;\n  ea.random(vd1);\n  ea.encrypt(c1, publicKey, vd1, /*size=*/1.0);\n\n#ifdef DEBUG_PRINTOUT\n  printVec(cout<< \"vd1=\", vd1, 10)<<endl;\n#endif\n  std::rotate(vd1.begin(), vd1.end()-nplaces, vd1.end());\n  ea.rotate(c1, nplaces);\n  c1.reLinearize();\n  ea.decrypt(c1, secretKey, vd_dec);\n#ifdef DEBUG_PRINTOUT\n  printVec(cout<< \"vd1(rot)=\", vd1, 10)<<endl;\n  printVec(cout<<\"res: \", vd_dec, 10)<<endl;\n#endif\n\n  if (cx_equals(vd1, vd_dec, conv<double>(epsilon*c1.getPtxtMag())))\n    cout << \"GOOD\\n\";\n  else {\n    cout << \"BAD:\\n\";\n    std::cout << \"  max(vd)=\"<<largestCoeff(vd_dec)\n              << \", max(vd1)=\"<<largestCoeff(vd1)\n              << \", maxDiff=\"<<calcMaxDiff(vd_dec,vd1) << endl<<endl;\n  }\n}\n", "meta": {"hexsha": "b9a11a18795075ac1c14d794b358dc18b8c5b713", "size": 16518, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Test_approxNums.cpp", "max_stars_repo_name": "patrick-schwarz/HElib", "max_stars_repo_head_hexsha": "cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-01T07:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-01T07:18:47.000Z", "max_issues_repo_path": "src/Test_approxNums.cpp", "max_issues_repo_name": "wangjinglin0721/HElib", "max_issues_repo_head_hexsha": "cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59", "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/Test_approxNums.cpp", "max_forks_repo_name": "wangjinglin0721/HElib", "max_forks_repo_head_hexsha": "cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59", "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.4438502674, "max_line_length": 82, "alphanum_fraction": 0.5888122049, "num_tokens": 5286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5135906160979296}}
{"text": "\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include<pybind11/numpy.h>\n#include<fstream>\n#include<iostream>\n#include <vector>\n#include <Eigen/Dense>\nusing namespace std;\nusing namespace Eigen;\n\n\nArrayXd find_max(VectorXd mMat)\n{\n\tVectorXd::Index maxRow;\n\tdouble max = mMat.maxCoeff(&maxRow);\n\tMatrix<bool, Dynamic, 1> MM = (mMat.array() == max).matrix();\n\tArrayXd Index_max = ArrayXd::Zero(mMat.size());\n\tfor (size_t i = 0; i < MM.rows(); i++)\n\t{\n\t\tif (MM(i))\n\t\t{\n\t\t\tIndex_max[i] = 1.0;\n\t\t}\n\n\t}\n\treturn Index_max;\n}\n\nMatrixXd select_M_PN(MatrixXd C, VectorXd P)\n{\n\tMatrixXd res(C.rows(), int(P.sum()));\n\tEigen::Index j = 0;\n\tfor (Eigen::Index i = 0; i < C.cols(); ++i)\n\t{\n\t\tif (P(i) > 0) res.col(j++) = C.col(i);\n\t}\n\treturn res;\n\n}\n\nMatrixXd select_V_PN(VectorXd V, VectorXd P)\n{\n\tVectorXd res(int(P.sum()));\n\tEigen::Index j = 0;\n\tfor (Eigen::Index i = 0; i < V.size(); ++i)\n\t{\n\t\tif (P(i) > 0) res(j++) = V(i);\n\t}\n\treturn res;\n\n}\n\nVectorXd lsqnonneg(MatrixXd C, VectorXd d,double tol)\n/*\nmin_{x>0}||Cx-d||_2^2\nReference: Lawson and Hanson,\n\"Solving Least Squares Problems\",\nPrentice-Hall, 1974.\n*/\n{\n\td = C.transpose() * d;\n\tC = C.transpose() * C;\n\tint n = C.rows();\n\t// Initialize vector of n zeros and Infs(to be used later)\n\tVectorXd nZeros = VectorXd::Zero(n);\n\tVectorXd wz = nZeros;\n\t//Initialize set of non - active columns to null\n\tVectorXd P = nZeros;\n\t// Initialize set of active columns to all\n\t// and the initial point to zeros\n\tVectorXd Z = VectorXd::Ones(n);\n\tVectorXd x = nZeros;\n\tVectorXd w = d - C * x;\n\tVectorXd resid = w;\n\tw = C.transpose() * w;\n\t//Set up iteration criterion\n\tint outeriter = 0;\n\tint iter = 0;\n\tint itmax = 3 * n;\n\tVectorXd z = nZeros;\n\tVectorXd x_new = VectorXd::Zero(n+1);\n\t// Outer loop to put variables into set to hold positive coefficients\n\twhile (Z.sum() > 0 && (w.array()*Z.array() > tol).any())\n\t{\n\t\touteriter += 1;\n\t\tz = nZeros;\n\t\twz = (wz.array()*(1 - P.array())).matrix() - P * DBL_MAX;\n\t\twz = (wz.array()*(1 - Z.array()) + w.array()*Z.array()).matrix();\n\t\tArrayXd t = find_max(wz);\n\t\tP = (P.array() * (1 - t) + t).matrix();\n\t\tZ = (Z.array()*(1 - t)).matrix();\n\t\tif (P.sum() == 1)\n\t\t{\n\t\t\tVectorXd::Index maxRow;\n\t\t\tP.maxCoeff(&maxRow);\n\t\t\tdouble bb = (C.col(maxRow)).transpose() * (C.col(maxRow));\n\t\t\tdouble aa = ((C.col(maxRow)).transpose() * d);\n\t\t\tz(maxRow) = aa / bb;\n\t\t}\n\t\tif (P.sum() >= 2)\n\t\t{\n\t\t\tMatrixXd C_ing = select_M_PN(C, P);\n\t\t\tVectorXd z_ing = (C_ing.transpose() * C_ing).ldlt().solve(C_ing.transpose() * d);\n\t\t\tEigen::Index j = 0;\n\t\t\tfor (size_t i = 0; i < P.size(); i++)\n\t\t\t{\n\t\t\t\tif (P(i) > 0) z(i) = z_ing(j++);\n\t\t\t}\n\t\t}\n\t\twhile (((z.array()*P.array() + 1-P.array()) <= 0).any())\n\t\t{\n\t\t\titer = iter + 1;\n\t\t\tif (iter > itmax)\n\t\t\t{\n\t\t\t\t// cout << \"optimfun:lsqnonneg: IterationCountExceeded\" << endl;\n\t\t\t\tx = z;\n\t\t\t\tdouble error = (resid.array()*resid.array()).sum();\n\t\t\t\tx_new << error,\tx;\n\t\t\t\treturn x_new;\n\t\t\t}\n\n\t\t\t// Find indices where intermediate solution z is approximately negative\n\t\t\tvector<double> alpha_v;\n\t\t\tfor (Eigen::Index i = 0; i < P.size(); i++)\n\t\t\t{\n\t\t\t\tif (z(i) <= 0 && P(i) > 0) alpha_v.push_back(x(i) / (x(i) - z(i)));\n\t\t\t}\n\t\t\tx = x + (*min_element(alpha_v.begin(), alpha_v.end())) * (z - x);\n\t\t\tfor (size_t i = 0; i < Z.size(); i++)\n\t\t\t{\n\t\t\t\tif ((abs(x(i)) < tol && P(i) > 0)||Z(i)>0)\n\t\t\t\t{\n\t\t\t\t\tZ(i) = 1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tZ(i) = 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\tP = (1 - Z.array()).matrix();\n\t\t\tz = nZeros;\n\t\t\tif (P.sum() == 1)\n\t\t\t{\n\t\t\t\tVectorXd::Index maxRow;\n\t\t\t\tP.maxCoeff(&maxRow);\n\t\t\t\tdouble bb = (C.col(maxRow)).transpose() * (C.col(maxRow));\n\t\t\t\tdouble aa = ((C.col(maxRow)).transpose() * d);\n\t\t\t\tz(maxRow) = aa / bb;\n\t\t\t}\n\t\t\tif (P.sum() >= 2)\n\t\t\t{\n\t\t\t\tMatrixXd C_ing = select_M_PN(C, P);\n\t\t\t\tVectorXd z_ing = (C_ing.transpose() * C_ing).ldlt().solve(C_ing.transpose() * d);\n\t\t\t\tEigen::Index j = 0;\n\t\t\t\tfor (size_t i = 0; i < P.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tif (P(i) > 0) z(i) = z_ing(j++);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tx = z;\n\t\tresid = (d - C * x);\n\t\tw = C.transpose() * resid;\n\t}\n\tdouble error = (resid.array()*resid.array()).sum();\n\tx_new <<error, x;\n\treturn x_new;\n}\n\nnamespace py = pybind11;\nPYBIND11_MODULE(libNNLS, m)\n{\nm.doc() = \"Non-negative least squares\";\nm.def(\"lsqnonneg\", &lsqnonneg);\n}", "meta": {"hexsha": "43ae2cf08a63fb2d1ab230c3ed51b5de4484c0c8", "size": 4190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WEDGE_Python/NNLS.cpp", "max_stars_repo_name": "QuKunLab/WEDGE", "max_stars_repo_head_hexsha": "c0f18ed64f4898480c676c93de365b4d2f9c1c33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-10-30T01:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T09:43:01.000Z", "max_issues_repo_path": "WEDGE_Python/NNLS.cpp", "max_issues_repo_name": "QuKunLab/WEDGE", "max_issues_repo_head_hexsha": "c0f18ed64f4898480c676c93de365b4d2f9c1c33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WEDGE_Python/NNLS.cpp", "max_forks_repo_name": "QuKunLab/WEDGE", "max_forks_repo_head_hexsha": "c0f18ed64f4898480c676c93de365b4d2f9c1c33", "max_forks_repo_licenses": ["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.6723163842, "max_line_length": 85, "alphanum_fraction": 0.56849642, "num_tokens": 1463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.5135609878037467}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <vector>\n#include <chrono>\n#include <unistd.h>\nusing namespace std;\nusing namespace Eigen;\nusing namespace std::chrono;\n\n#define DIM 1000\n#define NUM_CORES 4\n#define ENABLE_PARALLEL\n\nfloat get_time()\n{\n    return (float)duration_cast< milliseconds >(system_clock::now().time_since_epoch()).count();\n}\n\nvoid init_A(MatrixXd &A)\n{\n    for(int i = 0; i < DIM; i++)\n    {\n        for(int j = 0; j < DIM; j++)\n        {\n            A(i,j) = static_cast <float> (rand());\n        }\n    }\n}\n\nvoid init_b(VectorXd &b)\n{\n    for(int i = 0; i < DIM; i++)\n    {\n        b[i] = static_cast <float> (rand());\n    }\n}\n\nvoid test_QRpseudoInv(MatrixXd &A, VectorXd &b)\n{\n    A.colPivHouseholderQr().solve(b);\n}\n\nvoid test_QR(MatrixXd &A, VectorXd &b)\n{\n    A.householderQr().solve(b);\n}\n\nvoid test_CompleteOrtho(MatrixXd &A, VectorXd &b)\n{\n    A.completeOrthogonalDecomposition().solve(b);\n}\n\nvoid test_LDLT(MatrixXd &A, VectorXd &b)\n{\n    A.ldlt().solve(b);\n}\n\n\nint main()\n{\n    /**********Declaration & Initialization**********/\n    MatrixXd A(DIM,DIM);\n    VectorXd b(DIM);\n    init_A(A);\n    init_b(b);\n    /**********Declaration & Initialization**********/\n\n#ifdef ENABLE_PARALLEL\n    Eigen::initParallel();\n    Eigen::setNbThreads(NUM_CORES);\n#endif\n\n\n    auto start_ = chrono::steady_clock::now();\n    test_QRpseudoInv(A,b);\n    auto end_ = chrono::steady_clock::now();\n    cout << \"colPivHouseholderQr : \" \n        << chrono::duration_cast<chrono::nanoseconds>(end_ - start_).count()\n        << \" ns\" << endl;\n\n    start_ = chrono::steady_clock::now();\n    test_QR(A,b);\n    end_ = chrono::steady_clock::now();\n    cout << \"householderQr : \" \n        << chrono::duration_cast<chrono::nanoseconds>(end_ - start_).count()\n        << \" ns\" << endl;\n\n\n    start_ = chrono::steady_clock::now();\n    test_CompleteOrtho(A,b);\n    end_ = chrono::steady_clock::now();\n    cout << \"completeOrthogonalDecomposition : \" \n        << chrono::duration_cast<chrono::nanoseconds>(end_ - start_).count()\n        << \" ns\" << endl;\n\n\n    start_ = chrono::steady_clock::now();\n    test_LDLT(A,b);\n    end_ = chrono::steady_clock::now();\n    cout << \"LDLT: \" \n        << chrono::duration_cast<chrono::nanoseconds>(end_ - start_).count()\n        << \" ns\" << endl;\n\n\n}", "meta": {"hexsha": "89634c8bbdda6cf6b26e09312405656aff112492", "size": 2310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "evaluation.cpp", "max_stars_repo_name": "agnivsen/PerformanceEvaluation", "max_stars_repo_head_hexsha": "199f27d4589fcb370ed6b14692d008322d0eb135", "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": "evaluation.cpp", "max_issues_repo_name": "agnivsen/PerformanceEvaluation", "max_issues_repo_head_hexsha": "199f27d4589fcb370ed6b14692d008322d0eb135", "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": "evaluation.cpp", "max_forks_repo_name": "agnivsen/PerformanceEvaluation", "max_forks_repo_head_hexsha": "199f27d4589fcb370ed6b14692d008322d0eb135", "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.7924528302, "max_line_length": 96, "alphanum_fraction": 0.6008658009, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5135609862972189}}
{"text": "#include \"cxxopts.hpp\"\n\n// see https://www.gitmemory.com/issue/ddemidov/amgcl/162/668662041 for inspiration\n\n#include <amgcl/io/mm.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <amgcl/amg.hpp>\n\n#if defined(SOLVER_BACKEND_VEXCL)\n#  include <amgcl/value_type/static_matrix.hpp>\n#  include <amgcl/adapter/block_matrix.hpp>\n#  include <amgcl/backend/vexcl.hpp>\n#  include <amgcl/backend/vexcl_static_matrix.hpp>\n   typedef amgcl::backend::vexcl<double> Backend;\n#elif defined(SOLVER_BACKEND_CUDA)\n#  include <amgcl/adapter/eigen.hpp>\n#  include <amgcl/backend/cuda.hpp>\n#  include <amgcl/relaxation/cusparse_ilu0.hpp>\n   using Backend = amgcl::backend::cuda<double>;\n#else\n   using Backend = amgcl::backend::builtin<double>;\n#endif\n\n#include <amgcl/make_solver.hpp>\n#include <amgcl/make_block_solver.hpp>\n#include <amgcl/solver/bicgstab.hpp>\n#include <amgcl/solver/gmres.hpp>\n#include <amgcl/solver/runtime.hpp>\n#include <amgcl/preconditioner/runtime.hpp>\n#include <amgcl/amg.hpp>\n#include <amgcl/coarsening/smoothed_aggregation.hpp>\n#include <amgcl/coarsening/plain_aggregates.hpp>\n#include <amgcl/coarsening/ruge_stuben.hpp>\n#include <amgcl/coarsening/aggregation.hpp>\n#include <amgcl/relaxation/spai0.hpp>\n#include <amgcl/relaxation/ilu0.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n// ./amgcl-block-matrices -A ../data/B_test.mtx  -b 3\n\n#include <amgcl/profiler.hpp>\n\n\nnamespace amgcl { profiler<> prof; }\nusing amgcl::prof;\nusing amgcl::precondition;\n\n//---------------------------------------------------------------------------\nstd::tuple<size_t, double> scalar_solve(\n        const boost::property_tree::ptree &prm,\n        size_t rows,\n        std::vector<ptrdiff_t> const &ptr,\n        std::vector<ptrdiff_t> const &col,\n        std::vector<double>    const &val,\n        std::vector<double>    const &rhs,\n        std::vector<double>          &x,\n        bool reorder\n        )\n{\n    Backend::params bprm;\n    // We use the tuple of CRS arrays to represent the system matrix.\n    // Note that std::tie creates a tuple of references, so no data is actually\n    // copied here:\n    auto A = std::tie(rows, ptr, col, val);\n\n#if defined(SOLVER_BACKEND_VEXCL)\n    vex::Context ctx(vex::Filter::Env);\n    std::cout << ctx << std::endl;\n    bprm.q = ctx;\n#elif defined(SOLVER_BACKEND_VIENNACL)\n    std::cout\n        << viennacl::ocl::current_device().name()\n        << \" (\" << viennacl::ocl::current_device().vendor() << \")\\n\\n\";\n#elif defined(SOLVER_BACKEND_CUDA)\n    cusparseCreate(&bprm.cusparse_handle);\n    {\n        int dev;\n        cudaGetDevice(&dev);\n\n        cudaDeviceProp prop;\n        cudaGetDeviceProperties(&prop, dev);\n        std::cout << prop.name << std::endl << std::endl;\n    }\n#endif\n\n    using Solver1 = amgcl::make_solver<\n    amgcl::runtime::preconditioner<Backend>,\n    amgcl::runtime::solver::wrapper<Backend>>;\n\n    //using Solver2 = amgcl::make_block_solver<\n    using Solver2 = amgcl::make_solver<\n    // Use AMG as preconditioner:\n    amgcl::amg<\n        Backend,\n        amgcl::coarsening::smoothed_aggregation,\n        //amgcl::relaxation::spai0\n        amgcl::relaxation::damped_jacobi\n        >,\n    // And BiCGStab as iterative solver:\n    amgcl::solver::bicgstab<Backend>>;\n\n    using Solver3 = amgcl::make_solver<\n    // Use AMG as preconditioner:\n    amgcl::amg<\n        Backend,\n        amgcl::coarsening::ruge_stuben,\n        amgcl::relaxation::spai0\n        //amgcl::relaxation::ilu0\n        >,\n    // And GMRES as iterative solver:\n    amgcl::solver::gmres<Backend>>;\n\n    try {\n        Solver2::params prm;\n        Solver2::backend_params bprm;\n        // prm.precond.direct_coarse = false;\n        prm.precond.direct_coarse = true;\n        prm.solver.maxiter = 1200;\n        prm.solver.verbose = true;\n        prm.solver.tol = 1e-5;\n        //prm.precond.coarsening ...\n\n#if defined(SOLVER_BACKEND_VEXCL)\n        vex::Context ctx(vex::Filter::Env);\n        std::cout << ctx << std::endl;\n        bprm.q = ctx;\n#elif defined(SOLVER_BACKEND_VIENNACL)\n        std::cout\n            << viennacl::ocl::current_device().name()\n            << \" (\" << viennacl::ocl::current_device().vendor() << \")\\n\\n\";\n#elif defined(SOLVER_BACKEND_CUDA)\n        cusparseCreate(&bprm.cusparse_handle);\n        {\n            int dev;\n            cudaGetDevice(&dev);\n\n            cudaDeviceProp prop;\n            cudaGetDeviceProperties(&prop, dev);\n            std::cout << prop.name << std::endl << std::endl;\n        }\n#endif\n\n        Solver2 solve( A, prm, bprm );\n\n\n        auto f_b = Backend::copy_vector(rhs, bprm);\n        auto x_b = Backend::copy_vector(x,   bprm);\n\n        //auto [iters, error] = solve(A, rhs, x);\n        auto [iters, error] = solve(A, *f_b, *x_b);\n\n#if defined(SOLVER_BACKEND_VEXCL)\n        vex::copy(*x_b, x);\n#elif defined(SOLVER_BACKEND_VIENNACL)\n        viennacl::fast_copy(*x_b, x);\n#elif defined(SOLVER_BACKEND_CUDA)\n        thrust::copy(x_b->begin(), x_b->end(), x.begin());\n#else\n        std::copy(&(*x_b)[0], &(*x_b)[0] + rows, &x[0]);\n#endif\n\n        // Output the number of iterations, the relative error:\n        std::cout << \"Iters: \" << iters << std::endl\n                  << \"Error: \" << error << std::endl;\n        // std::cout << \"x = [ \";\n        // for (auto el : x) {\n        //     std::cout << el << \", \";\n        // }\n        // std::cout << \"]\\n\";\n        return {iters, error};\n    } catch(std::runtime_error &e) {\n        std::cout << \"caught exception: \" << e.what() << std::endl;\n    }\n\n    return {0, 0.0};\n}\n\nint main(int argc, char *argv[])\n{\n    //namespace po = boost::program_options;\n    namespace io = amgcl::io;\n\n    using std::vector;\n    using std::string;\n\n    cxxopts::Options options(\"amgcl_block_matrices\", \"check AMG for different block sizes\");\n    options\n        .allow_unrecognised_options()\n        .add_options()\n        (\"A,matrix\", \"System matrix in the MatrixMarket format.\",\n         cxxopts::value<std::string>())\n        (\"b,block-size\", \"The block size of the system matrix. \",\n         cxxopts::value<int>()->default_value(\"1\"))\n        (\"h,help\", \"Print help\")\n        ;\n\n    auto vm = options.parse(argc, argv);\n\n    if (vm.count(\"help\")) {\n        std::cout << options.help() << std::endl;\n        return 0;\n    }\n\n    for (int i = 0; i < argc; ++i) {\n        if (i) std::cout << \" \";\n        std::cout << argv[i];\n    }\n    std::cout << std::endl;\n\n    boost::property_tree::ptree prm;\n    if (vm.count(\"prm-file\")) {\n        read_json(vm[\"prm-file\"].as<string>(), prm);\n    }\n\n    if (vm.count(\"prm\")) {\n        for(const string &v : vm[\"prm\"].as<vector<string>>()) {\n            amgcl::put(prm, v);\n        }\n    }\n\n    size_t n, block_size = 1;\n    vector<ptrdiff_t> ptr, col;\n    vector<double> val;\n\n    if (vm.count(\"block-size\")) {\n        block_size = vm[\"block-size\"].as<int>();\n    }\n\n    if (vm.count(\"matrix\")) {\n        string Afile  = vm[\"matrix\"].as<string>();\n        auto [rows, cols] = io::mm_reader(Afile)(ptr, col, val);\n\n        std::cout << \"rows: \" << rows << std::endl;\n        std::cout << \"cols: \" << cols << std::endl;\n        n = rows;\n    }\n\n    // We use the tuple of CRS arrays to represent the system matrix.\n    // Note that std::tie creates a tuple of references, so no data is actually\n    // copied here:\n    auto A = std::tie(n, ptr, col, val);\n    std::vector<double> rhs (n, 0.0);\n    std::vector<double> x   (n, 0.0);\n\n    // Set RHS := Ax where x = 1\n    for (size_t i = 0; i < n; ++i) {\n        double s = 0;\n        for (ptrdiff_t j = ptr[i], e = ptr[i+1]; j < e; ++j) {\n            s += val[j];\n        }\n        rhs[i] = s;\n    }\n\n    if (block_size == 1) { // scalar case\n        scalar_solve(prm, n, ptr,col, val, rhs, x, false);\n    } else {\n        // Compose the solver type\n        constexpr size_t B = 6; // 3\n        using dmat_type = amgcl::static_matrix<double, B, B>;\n        using dvec_type = amgcl::static_matrix<double, B, 1>;\n        using SBackend = amgcl::backend::builtin<double>;    // the outer iterative solver backend\n        using PBackend = amgcl::backend::builtin<float>;     // the PSolver backend\n        using UBackend = amgcl::backend::builtin<dmat_type>; // the USolver backend\n        using BlockSolver = amgcl::make_block_solver<\n                // preconditioner\n                amgcl::amg<\n                    UBackend,\n                    amgcl::coarsening::aggregation,\n                    amgcl::relaxation::ilu0\n                    >,\n                // solver\n                amgcl::solver::gmres<UBackend>>;\n        using Solver = amgcl::make_solver<\n                // preconditioner\n                amgcl::amg<\n                    UBackend,\n                    amgcl::coarsening::aggregation,\n                    amgcl::relaxation::ilu0\n                    >,\n                // solver\n                amgcl::solver::gmres<UBackend>>;\n        try {\n            // see `tutorial/3.CoupCons3D/coupcons3d.cpp`\n#if 1\n            BlockSolver::params prm;\n            prm.solver.maxiter = 1200;\n            prm.solver.verbose = true;\n            BlockSolver::backend_params bprm;\n            prm.precond.direct_coarse = false;\n            prm.precond.allow_rebuild = true;\n            auto Ab = amgcl::adapter::block_matrix<dmat_type>(A);\n            auto rhsb = reinterpret_cast<dvec_type*>(rhs.data());\n            auto xb = reinterpret_cast<dvec_type*>(x.data());\n            auto RHS = amgcl::make_iterator_range(rhsb, rhsb + n / 3);\n            auto X = amgcl::make_iterator_range(xb, xb + n / block_size);\n            Solver solve0( Ab, prm, bprm );\n            auto [iters0, error0] = solve0(Ab, RHS, X);\n            std::cout << \"Iters0: \" << iters0 << std::endl\n                      << \"Error0: \" << error0 << std::endl;\n\n            BlockSolver solve( A, prm, bprm );\n            auto [iters, error] = solve(A, rhs, x);\n\n            std::cout << \"Iters: \" << iters << std::endl\n                      << \"Error: \" << error << std::endl;\n            // std::cout << \"x = [ \";\n            // for (auto el : x) {\n            //     std::cout << el << \", \";\n            // }\n            // std::cout << \"]\\n\";\n#endif\n        } catch(std::runtime_error &e) {\n            std::cout << \"caught exception: \" << e.what() << std::endl;\n        }\n    }\n}\n", "meta": {"hexsha": "70ba836630a25cb188b81d840da56fd9fd2c8b02", "size": 10381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "amgcl.starter/src/amgcl_block_matrices_test.cpp", "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": "amgcl.starter/src/amgcl_block_matrices_test.cpp", "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": "amgcl.starter/src/amgcl_block_matrices_test.cpp", "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": 32.440625, "max_line_length": 98, "alphanum_fraction": 0.5644928234, "num_tokens": 2895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5135609862972189}}
{"text": "#include \"../benchmarks_general.h\"\n\n#define BLAZE_DEFAULT_ALIGNMENT_FLAG blaze::unaligned\n#define BLAZE_DEFAULT_PADDING_FLAG blaze::unpadded\n\n#include <Fastor/Fastor.h>\n#include <Eigen/Core>\n#include <blaze/math/StaticMatrix.h>\n\ntemplate<typename T, size_t M, size_t N>\nvoid benchmark_transpose_eigen() {\n    using namespace Eigen;\n    Matrix<T,M,N,RowMajor> a;\n    a.setConstant(3);\n    Eigen::Matrix<T,N,M,RowMajor> c = a.transpose();\n    benchmarks_general::unused(c);\n}\n\ntemplate<typename T, size_t M, size_t N>\nvoid benchmark_transpose_blaze() {\n    using namespace blaze;\n    StaticMatrix<T,M,N,rowMajor> a(3);\n    StaticMatrix<T,N,M,rowMajor> c = trans(a);\n    benchmarks_general::unused(c);\n}\n\ntemplate<typename T, size_t M, size_t N>\nvoid benchmark_transpose_fastor() {\n    using namespace Fastor;\n    Tensor<T,M,N> a(3);\n    Tensor<T,N,M> c = transpose(a);\n    benchmarks_general::unused(c);\n}\n\n\n\n\n\ntemplate<typename T, size_t M>\nvoid benchmark_run() {\n\n    using benchmarks_general::println;\n    using benchmarks_general::rtimeit;\n\n    println(\"Testing size (M, N)\", M, M,'\\n');\n\n    double etime = rtimeit(static_cast<void (*)()>(&benchmark_transpose_eigen<T,M,M>));\n    double btime = rtimeit(static_cast<void (*)()>(&benchmark_transpose_blaze<T,M,M>));\n    double ftime = rtimeit(static_cast<void (*)()>(&benchmark_transpose_fastor<T,M,M>));\n\n    println(\"Elapsed time -> Eigen, Blaze, Fastor\\n\", etime, btime, ftime,'\\n');\n}\n\ntemplate<size_t step, size_t from, size_t to>\nstruct benchmark_generate {\n    template<typename T>\n    static inline void generate() {\n        benchmark_run<T,from>();\n        benchmark_generate<step,from+step,to>::template generate<T>();\n    }\n};\ntemplate<size_t step, size_t from>\nstruct benchmark_generate<step,from,from> {\n    template<typename T>\n    static inline void generate() {\n        benchmark_run<T,from>();\n    }\n};\n\n\nint main () {\n\n#ifdef RUN_SINGLE\n    benchmark_generate<8,8,128>::template generate<float>();\n#else\n    benchmark_generate<8,8,128>::template generate<double>();\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "633a424c4a3d887ae36fc5e16e5002baf360303f", "size": 2059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/external/benchmark_transpose/benchmark_transpose.cpp", "max_stars_repo_name": "mablanchard/Fastor", "max_stars_repo_head_hexsha": "f5ca2f608bdfee34833d5008a93a3f82ce42ddef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 424.0, "max_stars_repo_stars_event_min_datetime": "2017-05-15T14:34:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T08:58:22.000Z", "max_issues_repo_path": "benchmark/external/benchmark_transpose/benchmark_transpose.cpp", "max_issues_repo_name": "manodeep/Fastor", "max_issues_repo_head_hexsha": "aefce47955dd118f04e7b36bf5dbb2d86997ff8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 150.0, "max_issues_repo_issues_event_min_datetime": "2016-12-23T10:08:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T03:53:45.000Z", "max_forks_repo_path": "benchmark/external/benchmark_transpose/benchmark_transpose.cpp", "max_forks_repo_name": "manodeep/Fastor", "max_forks_repo_head_hexsha": "aefce47955dd118f04e7b36bf5dbb2d86997ff8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43.0, "max_forks_repo_forks_event_min_datetime": "2017-09-20T19:47:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T21:12:49.000Z", "avg_line_length": 25.4197530864, "max_line_length": 88, "alphanum_fraction": 0.6920835357, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5135609638785875}}
{"text": "#include <ros/ros.h>\n#include <iostream>\n#include <race/enc_values.h>\n#include <cmath>\n#include <boost/shared_ptr.hpp>\n#include <tf/transform_broadcaster.h>\n\nusing namespace std;\n\n\nstruct loc {\n\tfloat xpos;\n\tfloat ypos;\n\tfloat yaw;\n\tloc() {}\n\tloc(float _xpos, float _ypos, float _yaw) : xpos(_xpos), ypos(_ypos), yaw(_yaw) {}\n\tloc& operator = (const loc &l) {\n\t\txpos = l.xpos;\n\t\typos = l.ypos;\n\t\tyaw = l.yaw;\n\t}\n};\n\nbool state = false;\nloc pre_loc;\nloc cur_loc;\nint pre_enc_val;\nint cur_enc_val;\nfloat yaw_ = 0;\nboost::shared_ptr<tf::TransformBroadcaster> tf_pub_;\nros::Publisher odom_pub_;\n\nvoid encoderCallback(const race::enc_values::ConstPtr& msg) {\n\tcur_enc_val = msg->enc_val;\n\tint cur_steering_angle = msg->steering;\n\n\tif(!state) {\n\t\tstate = true;\n\t\tpre_enc_val = cur_enc_val;\n\t}\n\n\tros::Duration dt = ;\n\n\tyaw_ += (cur_enc_val - pre_enc_val)/dt;\n\tfloat r = (cur_enc_val - pre_enc_val)/yaw;\n\tfloat y_ = r - r*cos(yaw);\n\tfloat x_ = r*sin(yaw);\n\n\tpre_enc_val = cur_enc_val;\n\n\n\tnav_msgs::Odometry::Ptr odom(new nav_msgs::Odometry);\n\todom->pose.pose.position.x = x_;\n\todom->pose.pose.position.y = y_;\n\todom->pose.pose.orientation.x = 0.0;\n\todom->pose.pose.orientation.y = 0.0;\n\todom->pose.pose.orientation.z = sin(yaw_/2.0);\n\todom->pose.pose.orientation.w = cos(yaw_/2.0);\n\n\todom->pose.covariance[0]  = 0.2; \n\todom->pose.covariance[7]  = 0.2; \n\todom->pose.covariance[35] = 0.4; \n\n\todom->twist.twist.linear.x = (cur_enc_val - pre_enc_val)/dt;\n\todom->twist.twist.linear.y = 0.0;\n\todom->twist.twist.angular.z = (cur_enc_val - pre_enc_val)/dt;\n\n\t\n}\n\nint main(int argc, char** argv) {\n\tros::init(argc, argv, \"encoder_to_odom_node\");\n\tros::NodeHandle nh;\n\n\tros::Subscriber encoder_value_sub = nh.subscribe(\"encoder_value\", 10, encoderCallback);\n\tros::spin();\n}", "meta": {"hexsha": "51341aba25f4a4e1ecf3e04f45af26af26f1fc1d", "size": 1755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/race/src/encoder_to_odom.cpp", "max_stars_repo_name": "young43/ISCC_2020", "max_stars_repo_head_hexsha": "2a7187410bceca901bd87b753a91fd35b73ca036", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-07-22T08:22:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T06:25:14.000Z", "max_issues_repo_path": "src/race/src/encoder_to_odom.cpp", "max_issues_repo_name": "yongbeomkwak/ISCC_2021", "max_issues_repo_head_hexsha": "7e7e5a8a14b9ed88e1cfbe2ee585fe24e4701015", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-13T16:30:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T10:37:33.000Z", "max_forks_repo_path": "src/race/src/encoder_to_odom.cpp", "max_forks_repo_name": "yongbeomkwak/ISCC_2021", "max_forks_repo_head_hexsha": "7e7e5a8a14b9ed88e1cfbe2ee585fe24e4701015", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-13T09:06:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T02:31:23.000Z", "avg_line_length": 22.7922077922, "max_line_length": 88, "alphanum_fraction": 0.6894586895, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5134127265897569}}
{"text": "#define DEBUG 1\n/**\n * File    : F.cpp\n * Author  : Kazune Takahashi\n * Created : 6/16/2020, 5:44:32 PM\n * Powered by Visual Studio Code\n */\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n// ----- boost -----\n#include <boost/integer/common_factor_rt.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/rational.hpp>\n// ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::integer::gcd; // for C++14 or for cpp_int\nusing boost::integer::lcm; // for C++14 or for cpp_int\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n// ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n// constexpr ll MOD{998'244'353LL}; // be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nbool ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\ntemplate <typename T>\nbool ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\n// ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(Mint const &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(Mint const &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(Mint const &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator/=(Mint const &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }\n  bool operator<(Mint const &a) const { return x < a.x; }\n  bool operator<=(Mint const &a) const { return x <= a.x; }\n  bool operator>(Mint const &a) const { return x > a.x; }\n  bool operator>=(Mint const &a) const { return x >= a.x; }\n  bool operator==(Mint const &a) const { return x == a.x; }\n  bool operator!=(Mint const &a) const { return !(*this == a); }\n  Mint power(ll N) const\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N / 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }\ntemplate <ll MOD>\nMint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }\n// ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i{2LL}; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i{1LL}; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\n// ----- for C++17 -----\ntemplate <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>\nsize_t popcount(T x) { return bitset<64>(x).count(); }\nsize_t popcount(string const &S) { return bitset<200010>{S}.count(); }\n// ----- Infty -----\ntemplate <typename T>\nconstexpr T Infty() { return numeric_limits<T>::max(); }\ntemplate <typename T>\nconstexpr T mInfty() { return numeric_limits<T>::min(); }\n// ----- frequently used constexpr -----\n// constexpr double epsilon{1e-10};\n// constexpr ll infty{1'000'000'000'000'010LL}; // or\n// constexpr int infty{1'000'000'010};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\n// ----- ReadGraph -----\n// Referring to ymatsux-san's source code: https://atcoder.jp/contests/abc138/submissions/7016619\n\nstruct Edge\n{\n  int src, dst, id;\n  // ll cost;\n  Edge() {}\n  Edge(int src, int dst, int id) : src{src}, dst{dst}, id{id} {}\n  // Edge(int src, int dst, ll cost) : src{src}, dst{dst}, cost{cost} {}\n\n  void added_edge(vector<vector<Edge>> &V)\n  {\n    V[src].push_back(*this);\n  }\n\n  void added_rev(vector<vector<Edge>> &V)\n  {\n    V[dst].push_back(rev());\n  }\n\n  Edge rev()\n  {\n    Edge edge{*this};\n    swap(edge.src, edge.dst);\n    return edge;\n  }\n};\n\ntuple<vector<vector<Edge>>, vector<Edge>> ReadGraphWithEdges(int N, int M, bool is_undirected = true, bool is_one_indexed = true)\n{\n  vector<vector<Edge>> V(N);\n  vector<Edge> E(M);\n  for (auto i = 0; i < M; ++i)\n  {\n    int v, w;\n    cin >> v >> w;\n    if (is_one_indexed)\n    {\n      --v;\n      --w;\n    }\n    Edge edge{v, w, i};\n    edge.added_edge(V);\n    if (is_undirected)\n    {\n      edge.added_rev(V);\n    }\n    E.push_back(edge);\n  }\n  return make_tuple(V, E);\n}\n\nvector<vector<Edge>> ReadGraph(int N, int M, bool is_undirected = true, bool is_one_indexed = true)\n{\n  return get<0>(ReadGraphWithEdges(N, M, is_undirected, is_one_indexed));\n}\n\ntuple<vector<vector<Edge>>, vector<Edge>> ReadTreeWithEdges(int N)\n{\n  return ReadGraphWithEdges(N, N - 1);\n}\n\nvector<vector<Edge>> ReadTree(int N)\n{\n  return ReadGraph(N, N - 1);\n}\n\n// ----- Solve -----\n\nusing Info = tuple<int, int>;\n\nclass Solve\n{\n  int N, M;\n  vector<vector<Edge>> V;\n  vector<Info> W;\n  vector<ll> P;\n\npublic:\n  Solve(int N, int M, vector<vector<Edge>> const &V) : N{N}, M{M}, V{V}, W(M), P(M)\n  {\n    for (auto i{0}; i < M; ++i)\n    {\n      cin >> get<0>(W[i]) >> get<1>(W[i]);\n      get<0>(W[i])--;\n      get<1>(W[i])--;\n    }\n  }\n\n  void flush()\n  {\n    for (auto i{0}; i < M; ++i)\n    {\n      P[i] = path(get<0>(W[i]), get<1>(W[i]));\n#if DEBUG == 1\n      cerr << \"P[\" << i << \"] = \" << P[i] << endl;\n#endif\n    }\n    ll ans{0};\n    for (auto i{0}; i < (1 << M); ++i)\n    {\n      if (popcount(i) & 1)\n      {\n        ans -= mask_to_cnt(i);\n      }\n      else\n      {\n        ans += mask_to_cnt(i);\n      }\n    }\n    cout << ans << endl;\n  }\n\nprivate:\n  ll mask_to_cnt(int mask)\n  {\n    return 1LL << (N - 1 - popcount(mask_to_path(mask)));\n  }\n\n  ll mask_to_path(int mask)\n  {\n    ll ans{0};\n    for (auto i{0}; i < M; ++i)\n    {\n      if (mask >> i & 1)\n      {\n        ans |= P[i];\n      }\n    }\n    return ans;\n  }\n\n  ll path(int src, int dst)\n  {\n    vector<int> parents(N, -1), ids(N, -1);\n    dfs(src, parents, ids);\n    ll ans{0};\n    while (dst != src)\n    {\n      ans |= 1LL << ids[dst];\n      dst = parents[dst];\n    }\n    return ans;\n  }\n\n  void dfs(int src, vector<int> &parents, vector<int> &ids)\n  {\n    for (auto e : V[src])\n    {\n      if (parents[e.src] == e.dst)\n      {\n        continue;\n      }\n      parents[e.dst] = e.src;\n      ids[e.dst] = e.id;\n      dfs(e.dst, parents, ids);\n    }\n  }\n};\n\n// ----- main() -----\n\nint main()\n{\n  int N;\n  cin >> N;\n  auto V{ReadTree(N)};\n  int M;\n  cin >> M;\n  Solve solve(N, M, V);\n  solve.flush();\n}\n", "meta": {"hexsha": "efd16220b9cebb18ce1ddaa5a89a9f10c48df860", "size": 8702, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/0119_ABC152/F.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2020/0119_ABC152/F.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/0119_ABC152/F.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 22.1989795918, "max_line_length": 129, "alphanum_fraction": 0.5613652034, "num_tokens": 2776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083132, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5134127209038511}}
{"text": "/*\n * variable_selection.cpp\n *\n *  Created on: 19 Aug 2020\n *      Author: kovesarki\n */\n\n\n\n#include <Eigen/Dense>\n#include \"include/monopoly.h\"\n#include <random>\n#include <iostream>\n#include <vector>\n#include <string>\n\n#include \"include/tensor_serie.hh\"\n#include \"include/correlation_tensor_serie.hh\"\n\nint main(void) {\n\tstd::vector<std::vector<double> > signal(10000, std::vector<double>(3,0.0) );\n\tstd::vector<std::vector<double> > background(10000, std::vector<double>(3,0.0) );\n\n\tstd::random_device rd;\n\tstd::mt19937 gen(rd());\n\n\tstd::normal_distribution<> sx(0,1.01);\n\tstd::normal_distribution<> sy(1.0,0.4);\n\tstd::normal_distribution<> sz(0.7,2.0);\n\n\tstd::normal_distribution<> bx(0.5,0.9);\n\tstd::normal_distribution<> by(1.4,0.7);\n\tstd::normal_distribution<> bz(0.73,2.01);\n\n\tstd::vector<std::string >  variable_names(3);\n\tvariable_names[0] = \"parameter x\";\n\tvariable_names[1] = \"parameter y\";\n\tvariable_names[2] = \"parameter z\";\n\n\tfor(int i=0; i!= signal.size(); i++ ){\n\t\tsignal[i][0] = sx(gen);\n\t\tsignal[i][1] = sy(gen);\n\t\tsignal[i][2] = sz(gen);\n\t}\n\n\tfor(int i=0; i!= background.size(); i++ ){\n\t\tbackground[i][0] = bx(gen);\n\t\tbackground[i][1] = by(gen);\n\t\tbackground[i][2] = bz(gen);\n\t}\n\n\ttensor_serie<double> m_x(3,2);\n\tcorrelation_tensor_serie<double> signal_fourier(3,1); //number of dimensions, number of degree (linear is enough for comparison)\n\tfor(int i=0; i!= signal.size(); i++){\n\t\tm_x.create_diad(signal[i]);\n\t\tsignal_fourier.fill(m_x,1.0,1.0); //training for target y=1.0,weights=1.0\n\t}\n\tsignal_fourier.normalize();\n\n\tcorrelation_tensor_serie<double> background_fourier(3,1); //number of dimensions, number of degree (linear is enough for comparison)\n\tfor(int i=0; i!= background.size(); i++) {\n\t\tm_x.create_diad(background[i]);\n\t\tbackground_fourier.fill(m_x,1.0,1.0);\n\t}\n\tbackground_fourier.normalize();\n\n\tsignal_fourier.cov_matrix(1);\n\tbackground_fourier.cov_matrix(1);\n\n\tdouble a = signal_fourier.sigma_distance(background_fourier);\n\tstd::cout << \"significance is \" << a << std::endl;\n\n\tstd::vector<double> sigmas(variable_names.size(), 0.0);\n\tstd::vector<int> variable_ordering(variable_names.size(), 0.0);\n\n\tsignal_fourier.variable_selection(background_fourier, sigmas, variable_ordering);\n\n\tstd::cout << \"Variable order, from best to worst. \" << std::endl\n\t\t\t  << \"Significance is meant for the group of best variables\" << std::endl\n\t\t\t  << \"(the variable, and all the variables above).\" << std::endl;\n\tfor(int i=0; i!= variable_ordering.size(); i++)\n\t{\n\t  std::cout << sigmas[variable_ordering[i]] << \" \\t\" << variable_names[variable_ordering[i]] << std::endl;\n\t}\n\n\tstd::cout << \"varnames[\"<< variable_ordering.size()<< \"] = {\" << std::endl;\n\tfor(int i=variable_ordering.size()-1; i!= -1; i--)\n\t{\n\t  std::cout << \"\\\"\" << variable_names[variable_ordering[i]] << \"\\\"\";\n\t  if(i!=0) {std::cout << \",\"; }\n\t  else {std::cout << std::endl << \"}\";}\n\t  std::cout << std::endl;\n\t}\n}\n\n", "meta": {"hexsha": "0e8d8958833cd677e07c755bc6739d5d31ab4221", "size": 2903, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "variable_selection.cpp", "max_stars_repo_name": "freemeson/multinomial", "max_stars_repo_head_hexsha": "9bf1913a0e6d24ac40f219d44f757393decd1ad6", "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": "variable_selection.cpp", "max_issues_repo_name": "freemeson/multinomial", "max_issues_repo_head_hexsha": "9bf1913a0e6d24ac40f219d44f757393decd1ad6", "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": "variable_selection.cpp", "max_forks_repo_name": "freemeson/multinomial", "max_forks_repo_head_hexsha": "9bf1913a0e6d24ac40f219d44f757393decd1ad6", "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.2395833333, "max_line_length": 133, "alphanum_fraction": 0.6665518429, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5133982151018681}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n    MatrixXd mat;\n    BDCSVD<MatrixXd> svd(mat.Random(5, 6), ComputeFullU | ComputeFullV);\n    cout<< svd.singularValues().size();\n    //cout<<svd.matrixU();\n    return 0;\n}", "meta": {"hexsha": "3df78c75dd3bcc1bc8c38ed44fc77821d4d9c8db", "size": 275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/eigenSVDTest.cpp", "max_stars_repo_name": "tamasdzs/APPRSDK", "max_stars_repo_head_hexsha": "7a1f1c2a2f6994791bab760d01270eca62a5a946", "max_stars_repo_licenses": ["MIT"], "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/eigenSVDTest.cpp", "max_issues_repo_name": "tamasdzs/APPRSDK", "max_issues_repo_head_hexsha": "7a1f1c2a2f6994791bab760d01270eca62a5a946", "max_issues_repo_licenses": ["MIT"], "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/eigenSVDTest.cpp", "max_forks_repo_name": "tamasdzs/APPRSDK", "max_forks_repo_head_hexsha": "7a1f1c2a2f6994791bab760d01270eca62a5a946", "max_forks_repo_licenses": ["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.6428571429, "max_line_length": 72, "alphanum_fraction": 0.6690909091, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5133982101975806}}
{"text": "/**\n This file is part of Poisson Image Editing.\n \n Copyright Christoph Heindl 2015\n \n Poisson Image Editing 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 Poisson Image Editing 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 Poisson Image Editing.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n\n#include <blend/blend.h>\n#include <blend/poisson_solver.h>\n#include <opencv2/opencv.hpp>\n#include <Eigen/Dense>\nnamespace blend {\n    \n    template<class T>\n    Eigen::Map< Eigen::Matrix<T, Eigen::Dynamic, 1> > mapChannels(cv::Mat &m, int y, int x) {\n        \n        typedef Eigen::Matrix<T, Eigen::Dynamic, 1> V;\n        return Eigen::Map<V>(m.ptr<T>(y, x), m.channels());\n    }\n    \n    void seamlessBlend(cv::InputArray first_,\n                       cv::InputArray second_,\n                       cv::InputArray mask_,\n                       cv::OutputArray destination_)\n    {\n        \n        cv::Mat first = first_.getMat();\n        cv::Mat second = second_.getMat();\n        \n        destination_.create(first.size(), first.type());\n        cv::Mat dst = destination_.getMat();\n        \n        // Target Laplacians are zero\n        cv::Mat f(first.size(), CV_MAKE_TYPE(CV_32F, first.channels()));\n        f.setTo(0);\n        \n        cv::Mat bm(first.size(), CV_8UC1);\n        bm.setTo(constants::UNKNOWN);\n        cv::Mat bv(first.size(), CV_MAKE_TYPE(CV_32F, first.channels()));\n        bv.setTo(0);\n        \n        cv::Rect boundsSecond(0, 0, second.cols, second.rows);\n        \n        for (int y = 0; y < first.rows; ++y) {\n            const uchar *maskRow = mask_.getMat().ptr<uchar>(y);\n            for (int x = 0; x < first.cols; ++x) {\n                const bool isBorder = (y == 0) || (x == 0) || (y == (first.rows - 1)) || (x == (first.cols - 1));\n                const bool isFirst = (maskRow[x] == 255);\n                \n                if (isFirst && isBorder) {\n                    bm.at<uchar>(y, x) = constants::NEUMANN_BD;\n                    bv.at<float>(y, x) = 0.f;\n                } else if (!isFirst && boundsSecond.contains(cv::Point(x,y))) {\n                    bm.at<uchar>(y, x) = constants::DIRICHLET_BD;\n                    mapChannels<float>(bv, y, x) = mapChannels<uchar>(second, y, x).cast<float>() - mapChannels<uchar>(first, y, x).cast<float>();\n                } else if (!isFirst) {\n                    bm.at<uchar>(y, x) = constants::DIRICHLET_BD;\n                    mapChannels<float>(bv, y, x).setZero();\n                }\n            }\n        }\n        \n        \n        // Solve Poisson equation\n        cv::Mat result;\n        solvePoissonEquations(f,\n                              bm,\n                              bv,\n                              result);\n        \n        cv::Mat fixed;\n        first.convertTo(fixed, result.depth());\n        fixed += result;\n        fixed.convertTo(dst, dst.depth());\n        second.copyTo(dst, (255 - mask_.getMat()));\n        \n        \n    }\n    \n    \n}", "meta": {"hexsha": "79583d911668a16319390cd49103b9d10b89c7d3", "size": 3392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "poisson-image-editing/src/blend.cpp", "max_stars_repo_name": "eti-p-doray/inf8702", "max_stars_repo_head_hexsha": "1f420f6a6d8df5e9f5dce7c6192b622c761a909a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "poisson-image-editing/src/blend.cpp", "max_issues_repo_name": "eti-p-doray/inf8702", "max_issues_repo_head_hexsha": "1f420f6a6d8df5e9f5dce7c6192b622c761a909a", "max_issues_repo_licenses": ["MIT"], "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-image-editing/src/blend.cpp", "max_forks_repo_name": "eti-p-doray/inf8702", "max_forks_repo_head_hexsha": "1f420f6a6d8df5e9f5dce7c6192b622c761a909a", "max_forks_repo_licenses": ["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.085106383, "max_line_length": 146, "alphanum_fraction": 0.5403891509, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5133982101975806}}
{"text": "/*\n * G_q.cpp\n *\n *  Created on: 30.09.2010\n *      Author: stephaniebayer\n *\n *\n */\n\n#include \"G_q.h\"\n\n#include <NTL/ZZ.h>\nNTL_CLIENT\n\n#include <time.h>\nG_q::G_q() {\n\t// TODO Auto-generated constructor stub\n\n}\n\n\n//Constructor creates an instance of G_q subset Z_p with order o and generator g\nG_q::G_q(Mod_p gen, long o, long p){\n\n\tgenerator = gen;\n\torder = to_ZZ(o);\n\tmod = to_ZZ(p);\n\tif (gen.get_mod() != p)\n\t\tcout  << \"The modular value of the generator and p are not equal\" << endl;\n}\n\n//Constructor creates an instance of G_q subset Z_p with order o and generator g\nG_q::G_q(Mod_p gen, long o, ZZ p){\n\n\tgenerator = gen;\n\torder = to_ZZ(o);\n\tmod = p;\n\n\tif (gen.get_mod() != p)\n\t\tcout  << \"The modular value of the generator and p are not equal\" << endl;\n\n}\n\n\n//Constructor creates an instance of G_q subset Z_p with order o and generator g\nG_q::G_q(Mod_p gen, ZZ o, ZZ p){\n\n\tgenerator = gen;\n\torder = o;\n\tmod = p;\n\n\tif (gen.get_mod() != p)\n\t\tcout  << \"The modular value of the generator and p are not equal\" << endl;\n\n}\n\n\n//Constructor creates an instance of G_q subset Z_p with order o and generator value val\nG_q::G_q(ZZ val, long o, long p){\n\n\tgenerator = Mod_p(val, p);\n\torder = to_ZZ(o);\n\tmod = to_ZZ(p);\n\n}\n\n//Constructor creates an instance of G_q subset Z_p with order o and generator value val\nG_q::G_q(ZZ val, long o, ZZ p){\n\n\tgenerator = Mod_p(val, p);\n\torder = to_ZZ(o);\n\tmod = p;\n\n}\n\n//Constructor creates an instance of G_q subset Z_p with order o and generator value val\nG_q::G_q(ZZ val, ZZ o, ZZ p){\n\n\tgenerator = Mod_p(val, p);\n\torder = o;\n\tmod = p;\n\n}\n\n//Constructor creates an instance of G_q subset Z_p with order o and generator value val\nG_q::G_q(long val, long o, long p){\n\n\tgenerator = Mod_p(val, p);\n\torder = to_ZZ(o);\n\tmod = to_ZZ(p);\n\n}\n\n//Constructor creates an instance of G_q subset Z_p with order o and generator value val\nG_q::G_q(long val, long o, ZZ p){\n\n\tgenerator = Mod_p(val, p);\n\torder = to_ZZ(o),\n\tmod = p;\n\n}\n\n//Constructor creates an instance of G_q subset Z_p with order o and generator value val\nG_q::G_q(long val,ZZ o, ZZ p){\n\n\tgenerator = Mod_p(val, p);\n\torder = o;\n\tmod = p;\n\n}\n\n//Constructor creates an instance of G_q with order o, generator gen and G_q is a subgroup if Z modulo gen.get_mod()\nG_q::G_q(Mod_p gen, long o){\n\n\tgenerator = gen;\n\torder = to_ZZ(o);\n\tmod = gen.get_mod();\n}\n\n//Constructor creates an instance of G_q with order o, generator gen and G_q is a subgroup if Z modulo gen.get_mod()\nG_q::G_q(Mod_p gen, ZZ o){\n\n\tgenerator = gen;\n\torder = o;\n\tmod = gen.get_mod();\n}\n\n//Constructor creates an instance of G_q  subset of Z_p with order o and searchs for the smallest generator\nG_q::G_q(long o,ZZ p){\n\n\tZZ i;\n\torder = to_ZZ(o);\n\tmod = p;\n\tfor (i = to_ZZ(1); i < p; ++i)\n\t{\n\t\tif (is_generator(i))\n\t\t{\n\t\t\tgenerator = Mod_p(i,p);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n//Constructor creates an instance of G_q  subset of Z_p with order o and searchs for the smallest generator\nG_q::G_q(ZZ o,ZZ p){\n\n\tZZ i,t;\n\torder = o;\n\tmod = p;\n\tfor (i = to_ZZ(2); i < p; ++i)\n\t{\n\t\tt=i%100000;\n\t\tif(t==0){\n\t\t\tcout<<\";\";\n\t\t}\n\t\tif (is_generator(i))\n\t\t{\n\t\t\tgenerator = Mod_p(i,p);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n//Constructor creates an instance of G_q  subset of Z_p with order o and searchs for the smallest generator\nG_q::G_q(long o, long p){\n\n\tlong i;\n\torder = to_ZZ(o);\n\tmod = to_ZZ(p);\n\tfor (i = 1; i < p; ++i)\n\t{\n\t\tif (is_generator(i))\n\t\t{\n\t\t\tgenerator = Mod_p(i,p);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\nG_q::~G_q() {\n\t// TODO Auto-generated destructor stub\n}\n\n\n//return the generator\nMod_p G_q::get_gen()const{\n\n\treturn generator;\n}\n\n//return the order o\nZZ G_q::get_ord()const{\n\n\treturn order;\n}\n\n//return the modular value mod\nZZ G_q::get_mod()const{\n\n\treturn mod;\n}\n\n//Checks if an element is a generator of the group G\nbool G_q::is_generator(const Mod_p& el){\n\tZZ pow;\n\tbool b;\n\tb=false;\n\tpow = PowerMod(el.get_val(),order,mod);\n\tif(pow == to_ZZ(1)& el.get_val()!=1)\n\t{\n\t\tb=true;\n\t}\n\treturn b;\n}\n\n//Checks if an element is a generator of the group G\nbool G_q::is_generator(const ZZ& x){\n\tZZ pow;\n\tbool b;\n\tb=false;\n\tpow = PowerMod(x,order,mod);\n\n\tif(pow == to_ZZ(1) & x!=1)\n\t{\n\t\tb=true;\n\n\t}\n\n\treturn b;\n}\n\n//Checks if an element is a generator of the group G\nbool G_q::is_generator(const long& x){\n\tZZ pow;\n\tbool b;\n\tpow = PowerMod(to_ZZ(x),order, mod);\n\tif(pow == to_ZZ(1)& x!=1)\n\t{\n\t\tb=true;\n\n\t}\n\n\treturn b;\n}\n\n//returns the identity of the group\nMod_p G_q::identity(){\n\n\treturn Mod_p(1, mod);\n}\n\n//returns a random element of the group\nMod_p G_q::random_el(){\n\tZZ ran,pow;\n\tMod_p temp;\n\tSetSeed(to_ZZ(time(0)));\n\tran = RandomBnd(mod);\n\ttemp = generator.expo(ran);\n\n\treturn temp;\n\n}\n\n//returns a random element of the group, without setting the seed\nMod_p G_q::random_el(int c){\n\tZZ ran,pow;\n\tMod_p temp;\n\tran = RandomBnd(order);\n\ttemp = generator.expo(ran);\n\n\n\treturn temp;\n\n}\n\n//returns an element of the group with value v\nMod_p G_q::element(ZZ v){\n\n\n\treturn Mod_p(v,mod);\n\n}\n\n\n//returns an element of the group with value v\nMod_p G_q::element(long v){\n\n\n\treturn Mod_p(v,mod);\n\n}\n\n\nvoid G_q::operator =(const G_q& H){\n\n\tgenerator = H.get_gen();\n\torder = H.get_ord();\n\tmod = H.get_mod();\n}\n\n//Output operator, output format is (generator value, order, modular value)\nostream& operator<<(ostream& os, const G_q G){\n\treturn os<< \"(\"<< G.get_gen().get_val()<< \", \" << G.get_ord() <<\", \" << G.get_mod()<<\")\";\n}\n\n", "meta": {"hexsha": "d35dacb99feba62e5ef97dd8b6ca9d5388d2d888", "size": 5325, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/G_q.cpp", "max_stars_repo_name": "3for/verifiable-shuffle", "max_stars_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T14:06:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T08:28:26.000Z", "max_issues_repo_path": "src/G_q.cpp", "max_issues_repo_name": "3for/verifiable-shuffle", "max_issues_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "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/G_q.cpp", "max_forks_repo_name": "3for/verifiable-shuffle", "max_forks_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T06:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T15:21:49.000Z", "avg_line_length": 17.345276873, "max_line_length": 116, "alphanum_fraction": 0.6505164319, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5133982101975805}}
{"text": "//\n//  main.cpp\n//  lpm\n//\n//  Created by Seong-Hwan Jun on 2019-05-08.\n//\n\n#include <iostream>\n#include <string>\n#include <boost/algorithm/string.hpp>\n#include <boost/program_options.hpp>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include \"lpm.hpp\"\n\nusing namespace std;\n\nvoid draw_stratified_samples(gsl_rng *random, size_t n_mc_samples, double vec[], double max)\n{\n    double interval = max/n_mc_samples;\n    double sum = 0.0;\n    for (size_t i = 0; i < n_mc_samples; i++) {\n        vec[i] = gsl_ran_flat(random, sum, sum + interval);\n        sum += interval;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    namespace po = boost::program_options;\n    /**\n     * arguments:\n     * mode: model/pg\n     * seed\n     * model_len: range (i.e., 2-10)\n     * n_mc_samples: 30\n     * n_pg_iter: 30\n     * n_particles: 400\n     * n_smc_iter: 100\n     * n_kernel_iter: 3\n     * n_mh_w_gibbs_iter: 10\n     * has_passenger: True\n     * swap_prob: 0.1\n     * fbp_max: 0\n     * bgp_max: 0.2\n     * mh_proposal_sd: 0.05\n     * n_threads: 8\n     * use_lik_tempering: True\n     * data_path: data/Experiment2/With_passengers/5/error0.05/rep0/matrix.csv\n     **/\n    \n    string data_path;\n    string output_path;\n//    string mode;\n    unsigned long seed;\n    unsigned int model_len;\n    //unsigned int n_mc_samples;\n    unsigned int n_mcmc_iter;\n//    unsigned int n_particles;\n//    unsigned int n_smc_iter;\n//    unsigned int n_kernel_iter;\n    unsigned int n_mh_w_gibbs_iter;\n    unsigned int burn_in;\n    unsigned int thinning_interval;\n//    unsigned int n_mc_threads;\n//    unsigned int n_smc_threads;\n//    bool use_lik_tempering;\n    double fbp_max, bgp_max;\n    bool has_passenger;\n    double swap_prob;\n    double mh_proposal_sd;\n    double prior_passenger_prob;\n\n    po::options_description desc(\"Program options\");\n    desc.add_options()\n    (\"help\", \"Put a help message here.\")\n    (\"data_path,d\", po::value<string>(&data_path)->required(), \"Specify path to the data.\")\n    (\"output_path,o\", po::value<string>(&output_path)->required(), \"Specify output path.\")\n//    (\"mode,m\", po::value<string>(&mode)->required(), \"Specify mode: model for model selection and pg for particle Gibbs.\")\n    (\"seed,s\", po::value<unsigned long>(&seed)->default_value(1), \"Specify random seed.\")\n    (\"model_len,l\", po::value<unsigned int>(&model_len)->required(), \"Specify model length.\")\n    //(\"n_mc_samples,M\", po::value<unsigned int>(&n_mc_samples), \"Specify number of MC samples to use for model selection.\")\n    (\"n_mcmc_iter,p\", po::value<unsigned int>(&n_mcmc_iter), \"Specify number of iterations for PG/MCMC.\")\n    //(\"n_particles,P\", po::value<unsigned int>(&n_particles)->required(), \"Specify number of particles to use.\")\n    //(\"n_smc_iter,S\", po::value<unsigned int>(&n_smc_iter)->required(), \"Specify number of SMC iterations.\")\n    //(\"n_kernel_iter,k\", po::value<unsigned int>(&n_kernel_iter)->default_value(5), \"Specify number of iterations of MCMC kernels to apply within a SMC move. Specifying 0 reduces to random walk move.\")\n    (\"n_mh_w_gibbs_iter,G\", po::value<unsigned int>(&n_mh_w_gibbs_iter)->default_value(10), \"Specify number of iterations of MH within Gibbs for inferring the parameters within PG.\")\n    //(\"n_mc_threads,t\", po::value<unsigned int>(&n_mc_threads)->default_value(1), \"Specify number of threads to use for parallel processing of Monte Carlo samples.\")\n    //(\"n_smc_threads\", po::value<unsigned int>(&n_smc_threads)->default_value(1), \"Specify number of threads to use for SMC algorithm.\")\n    //(\"use_lik_tempering,T\", po::value<bool>(&use_lik_tempering)->default_value(true), \"Specify whether to use likelihood tempering.\")\n    (\"fbp_max,f\", po::value<double>(&fbp_max)->default_value(0), \"Specify max value for flip-back probability. Specify 0 here to use unified error probability.\")\n    (\"bgp_max,b\", po::value<double>(&bgp_max)->default_value(0.2), \"Specify max value for background mutation probability. Specifying 0 for fbp_max to interpret this quantity as an error probability.\")\n    (\"has_passenger\", po::value<bool>(&has_passenger)->default_value(true), \"Specify whether to detect passenger genes. 0: false, 1: true.\")\n    (\"swap_prob\", po::value<double>(&swap_prob)->default_value(0.2), \"Specify pathway swap probability for SMC move.\")\n    (\"mh_proposal_sd\", po::value<double>(&mh_proposal_sd)->default_value(0.05), \"Specify standard deviation of Gaussian random walk proposal within MHwGibbs for inferring the parameters (for mode = pg).\")\n    (\"burn_in\", po::value<unsigned int>(&burn_in)->default_value(0), \"Specify burn in for MCMC.\")\n    (\"thinning_interval\", po::value<unsigned int>(&thinning_interval)->default_value(1), \"Specify thinning interval for MCMC.\")\n    (\"prior_passenger_prob\", po::value<double>(&prior_passenger_prob)->default_value(0.95), \"Specify prior probability of a gene being a passenger.\")\n    ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n        cout << desc << \"\\n\";\n        return 1;\n    }\n\n    run_mcmc(seed, data_path.c_str(), output_path.c_str(), model_len, n_mcmc_iter, n_mh_w_gibbs_iter, thinning_interval, burn_in, has_passenger, swap_prob, fbp_max, bgp_max, mh_proposal_sd, prior_passenger_prob);\n\n    //if (mode == \"mcmc\") {\n//        run_mcmc(seed, data_path.c_str(), output_path.c_str(), model_len, n_mcmc_iter, n_mh_w_gibbs_iter, thinning_interval, burn_in, has_passenger, swap_prob, fbp_max, bgp_max, mh_proposal_sd, prior_passenger_prob);\n//    } else {\n//        cerr << \"Unknown mode: \" << mode << \".\" << endl;\n//    }\n    \n//    if (mode == \"pg\") {\n//        if (!vm.count(\"n_pg_iter\")) {\n//            cerr << \"Please specify number of PG iterations.\" << endl;\n//        }\n//        run_pg(seed, data_path.c_str(), output_path.c_str(), model_len, n_mcmc_iter, n_particles, n_smc_iter, n_kernel_iter, n_mh_w_gibbs_iter, has_passenger, swap_prob, fbp_max, bgp_max, mh_proposal_sd, n_smc_threads);\n//    } else if (mode == \"model\") {\n//        if (!vm.count(\"n_mc_samples\")) {\n//            cerr << \"Please specify number of Monte Carlo samples.\" << endl;\n//        }\n//        // sample fbps and bgps via stratified sampling\n//        double *fbps = new double[n_mc_samples];\n//        double *bgps = new double[n_mc_samples];\n//        gsl_rng *random = generate_random_object(seed);\n//        draw_stratified_samples(random, n_mc_samples, bgps, bgp_max);\n//        if (fbp_max == 0.0) {\n//            std::copy(bgps, bgps + n_mc_samples, fbps);\n//        }\n//        unsigned long new_seed = gsl_rng_get(random);\n//        model_selection(new_seed, data_path.c_str(), output_path.c_str(), model_len, n_mc_samples, n_particles, n_smc_iter, n_kernel_iter, has_passenger, swap_prob, fbps, bgps, n_mc_threads, n_smc_threads, use_lik_tempering);\n//        gsl_rng_free(random);\n//    } else if (mode == \"mcmc\") {\n//        run_mcmc(seed, data_path.c_str(), output_path.c_str(), model_len, n_mcmc_iter, n_mh_w_gibbs_iter, thinning_interval, has_passenger, swap_prob, fbp_max, bgp_max, mh_proposal_sd, prior_passenger_prob);\n//    } else {\n//        cerr << \"Unknown mode: \" << mode << \".\" << endl;\n//    }\n    return 0;\n}\n", "meta": {"hexsha": "6b5d850b6484de0f722a6cd33cf5b0f0f9e28b4e", "size": 7207, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "junseonghwan/linear-progression", "max_stars_repo_head_hexsha": "feda9f18d44f2ccc54a3750d1fe9a9ad323dcd36", "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": "junseonghwan/linear-progression", "max_issues_repo_head_hexsha": "feda9f18d44f2ccc54a3750d1fe9a9ad323dcd36", "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": "junseonghwan/linear-progression", "max_forks_repo_head_hexsha": "feda9f18d44f2ccc54a3750d1fe9a9ad323dcd36", "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": 49.7034482759, "max_line_length": 227, "alphanum_fraction": 0.6754544193, "num_tokens": 1971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5133982052932926}}
{"text": "#include \"hoNDHarrWavelet.h\"\n#include \"hoNDRedundantWavelet.h\"\n#include \"hoNDArray_math.h\"\n#include <gtest/gtest.h>\n#include <boost/random.hpp>\n\nusing namespace Gadgetron;\nusing testing::Types;\n\ntemplate<typename REAL> class hoNDWavelet_test : public ::testing::Test\n{\nprotected:\n    virtual void SetUp()\n    {\n        boost::random::mt19937 rng;\n        boost::random::uniform_real_distribution<REAL> uni(0,1);\n        std::vector<size_t > dimensions(3,128);\n\n        Array = hoNDArray< std::complex<REAL> >(dimensions);\n        std::complex<REAL>* data = Array.get_data_ptr();\n\n        for (size_t i = 0; i < Array.get_number_of_elements(); i++)\n            data[i] = std::complex<REAL>(uni(rng), uni(rng));\n    }\n\n    hoNDArray< std::complex<REAL> > Array;\n};\n\ntypedef Types<float, double> realImplementations;\nTYPED_TEST_SUITE(hoNDWavelet_test, realImplementations);\n\nTYPED_TEST(hoNDWavelet_test, hoNDHarrWaveletTest1D)\n{\n    Gadgetron::hoNDHarrWavelet< std::complex<TypeParam> > wav;\n\n    hoNDArray< std::complex<TypeParam> > r, rr, diff;\n\n    size_t WavDim = 1;\n    size_t level = 3;\n\n    wav.transform(this->Array, r, WavDim, level, true);\n    wav.transform(r, rr, WavDim, level, false);\n\n    Gadgetron::subtract(this->Array, rr, diff);\n\n    TypeParam v =  Gadgetron::nrm2(diff);\n\n    EXPECT_NEAR(v, 0, 0.001);\n}\n\nTYPED_TEST(hoNDWavelet_test, hoNDHarrWaveletTest2D)\n{\n    Gadgetron::hoNDHarrWavelet< std::complex<TypeParam> > wav;\n\n    hoNDArray< std::complex<TypeParam> > r, rr, diff;\n\n    size_t WavDim = 2;\n    size_t level = 2;\n\n    wav.transform(this->Array, r, WavDim, level, true);\n    wav.transform(r, rr, WavDim, level, false);\n\n    Gadgetron::subtract(this->Array, rr, diff);\n\n    TypeParam v = Gadgetron::nrm2(diff);\n\n    EXPECT_NEAR(v, 0, 0.001);\n}\n\nTYPED_TEST(hoNDWavelet_test, hoNDHarrWaveletTest3D)\n{\n    Gadgetron::hoNDHarrWavelet< std::complex<TypeParam> > wav;\n\n    hoNDArray< std::complex<TypeParam> > r, rr, diff;\n\n    size_t WavDim = 3;\n    size_t level = 1;\n\n    wav.transform(this->Array, r, WavDim, level, true);\n    wav.transform(r, rr, WavDim, level, false);\n\n    Gadgetron::subtract(this->Array, rr, diff);\n\n    TypeParam v = Gadgetron::nrm2(diff);\n\n    EXPECT_NEAR(v, 0, 0.001);\n}\n\nTYPED_TEST(hoNDWavelet_test, hoNDRedundantWaveletTest1D)\n{\n    Gadgetron::hoNDRedundantWavelet< std::complex<TypeParam> > wav;\n    wav.compute_wavelet_filter(\"db2\");\n\n    hoNDArray< std::complex<TypeParam> > r, rr, diff;\n\n    size_t WavDim = 1;\n    size_t level = 2;\n\n    wav.transform(this->Array, r, WavDim, level, true);\n    wav.transform(r, rr, WavDim, level, false);\n\n    Gadgetron::subtract(this->Array, rr, diff);\n\n    TypeParam v = Gadgetron::nrm2(diff);\n\n    EXPECT_NEAR(v, 0, 0.001);\n}\n\nTYPED_TEST(hoNDWavelet_test, hoNDRedundantWaveletTest2D)\n{\n    Gadgetron::hoNDRedundantWavelet< std::complex<TypeParam> > wav;\n    wav.compute_wavelet_filter(\"db2\");\n\n    hoNDArray< std::complex<TypeParam> > r, rr, diff;\n\n    size_t WavDim = 2;\n    size_t level = 3;\n\n    wav.transform(this->Array, r, WavDim, level, true);\n    wav.transform(r, rr, WavDim, level, false);\n\n    Gadgetron::subtract(this->Array, rr, diff);\n\n    TypeParam v = Gadgetron::nrm2(diff);\n\n    EXPECT_NEAR(v, 0, 0.001);\n}\n\nTYPED_TEST(hoNDWavelet_test, hoNDRedundantWaveletTest3D)\n{\n    Gadgetron::hoNDRedundantWavelet< std::complex<TypeParam> > wav;\n    wav.compute_wavelet_filter(\"db2\");\n\n    hoNDArray< std::complex<TypeParam> > r, rr, diff;\n\n    size_t WavDim = 3;\n    size_t level = 2;\n\n    wav.transform(this->Array, r, WavDim, level, true);\n    wav.transform(r, rr, WavDim, level, false);\n\n    Gadgetron::subtract(this->Array, rr, diff);\n\n    TypeParam v = Gadgetron::nrm2(diff);\n\n    EXPECT_NEAR(v, 0, 0.001);\n}\n\n", "meta": {"hexsha": "161bf6987f7fa6fab8e5e62bacc53efca8f3d646", "size": 3708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/hoNDWavelet_test.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "test/hoNDWavelet_test.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "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/hoNDWavelet_test.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["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.8859060403, "max_line_length": 71, "alphanum_fraction": 0.6717907228, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5133982052932926}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n\n#include <spherepix/image.h>\n#include <spherepix/camera.h>\n#include <spherepix/pixelation.h>\n#include <Eigen/Dense>\n\nvoid numericsTest() {\n    Eigen::Vector2f V_total(-1.39383e-05, 7.17674e-06);\n    Eigen::Vector2f C_total(-7.66636e-08,  1.24335e-07);\n    float M = 1.0f;\n\n    Eigen::Vector2f beta_acc_p = (V_total - C_total) / M;\n\n    std::cout << \"beta_acc_p: \" << beta_acc_p.transpose() << std::endl;\n}\n\nvoid testMin() {\n    std::vector<int> v {7, 8, 5, 2, 0, 9, 10};\n    int childrenIndex = std::min_element(v.begin(), v.end()) - v.begin(); \n    std::cout << \"min index: \" << childrenIndex << std::endl;\n    std::cout << \"element: \" << v[childrenIndex] << std::endl;\n}\n\nvoid tesCamera() {\n\n    std::cout << \"camera test\" << std::endl;\n    spherepix::PinholeCamera cam(35, 480, 640, 18, 18);\n\n    std::cout << \"height: \" << cam.height() << std::endl;\n    std::cout << \"width: \" << cam.width() << std::endl;\n\n    std::cout << \"camera test: finished\" << std::endl;\n}\n\nvoid testSpringDynamics() {\n    int N = 512;\n    spherepix::Image<float> input = spherepix::createFace_equiangular(N);\n    spherepix::Image<float> face = spherepix::regularizeCoordinates(input, 0.0f, 1000);\n\n    // spherepix::Image<float> win = input.subImage(0, 0, 3, 3);\n    // spherepix::Image<float> cop(3,3,3);\n    // cop.copyFrom(win);\n    // for(int i =0; i < win.length(); ++i) {\n    //     std::cout << i << \": \" << win[i] << \" : \" << cop[i] << std::endl;\n    // }\n\n    face.save(\"pix512_2.bin\");\n\n    std::cout << \"ALL GOOD\" << std::endl;\n}\n\nint main(int argc, char const *argv[])\n{\n    // std::cout << \"imageTest: start\" << std::endl;\n\n    // spherepix::Image<float> img {2, 5, 3};\n    // std::cout << \"width: \" << img.width() << std::endl;\n    // std::cout << \"height: \" << img.height() << std::endl;\n    // std::cout << \"depth: \" << img.depth() << std::endl;\n    // std::cout << \"length: \" << img.length() << std::endl;\n    // std::cout << \"pitch: \" << img.pitch() << std::endl;\n\n    // for (int i = 0; i < img.length(); ++i) {\n    //     img[i] = i;\n    //     std::cout << \"[\" << i << \"]: \" << img[i] << std::endl;\n    // }\n\n    // for (int r = 0; r < img.height(); ++ r) {\n    //     for (int c = 0; c < img.width(); ++ c) {\n    //         std::cout << \"[\" << r << \", \" << c << \"]: \" << img(r, c, 0) << std::endl;\n    //     }\n    // }\n\n\n    // float* data = new float[100];\n    // spherepix::Image<float> imgExt {10, 10, 1, data};\n\n    numericsTest();\n    testMin();\n    tesCamera();\n    // testSpringDynamics();\n\n    spherepix::Pixelation pix = spherepix::PixelationFactory::createPixelation(spherepix::PixelationMode::MODE_1, 64, 3);\n    spherepix::SphericalImage<float> img(pix, 3);\n\n    std::cout << \"sphImg face height: \" << img.faceHeight() << std::endl;\n\n    spherepix::Image<float>* face = &img[0];\n    std::cout << \"face depth: \" << face->depth() << std::endl;\n\n    return 0;\n}", "meta": {"hexsha": "8209c6e02e8fdbbeb6cbd0e403d3b822ea8e8e12", "size": 2930, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main.cpp", "max_stars_repo_name": "jadarve/spherepix", "max_stars_repo_head_hexsha": "60c7d5c271a1f40f9c7c58db5bf2d3f785a65dba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-28T04:42:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T15:50:20.000Z", "max_issues_repo_path": "test/main.cpp", "max_issues_repo_name": "jadarve/spherepix", "max_issues_repo_head_hexsha": "60c7d5c271a1f40f9c7c58db5bf2d3f785a65dba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-06-28T13:12:13.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-10T16:59:21.000Z", "max_forks_repo_path": "test/main.cpp", "max_forks_repo_name": "jadarve/spherepix", "max_forks_repo_head_hexsha": "60c7d5c271a1f40f9c7c58db5bf2d3f785a65dba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-06-28T13:12:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-29T05:29:00.000Z", "avg_line_length": 30.8421052632, "max_line_length": 121, "alphanum_fraction": 0.5440273038, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.5133656704634683}}
{"text": "#include \"CEGO/CEGO.hpp\"\n#include \"CEGO/minimizers.hpp\"\n#include <Eigen/Dense>\n\n// autodiff include\n#include \"Eigen/Dense\"\n#include <autodiff/forward.hpp>\n#include <autodiff/forward/eigen.hpp>\n\nstd::atomic_size_t Ncalls(0);\n\nconstexpr double Tt = 273.16;\nconstexpr double Tc = 647.096;\n\nconst std::vector<double> b = { 1.99274064, 1.09965342, -0.510839303, -1.75493479, -45.5170352, -6.746944503e5 };\nconst std::vector<double> c = { 1.0 / 3, 2.0 / 3, 5.0 / 3, 16.0 / 3, 43.0/ 3, 110.0/ 3 };\n\ntemplate <class T, class... Ts> struct is_any : std::disjunction<std::is_same<T, Ts>...> {};\n\ntemplate <typename T, typename B, typename C>\nauto evaluate_RHS(const T &theta, const B &b, const C &c) { // theta = 1-T/Tc\n    T o = 1.0 + 0*theta;\n    for (auto i = 0; i < b.size(); ++i) {\n        o += b[i] * pow(theta, c[i]);\n    }\n    return o;\n}\n\nauto evaluate_RHS(const CEGO::EArray<double> &theta, const CEGO::EArray<std::complex<double>> &b, const CEGO::EArray<std::complex<double>> &c) { // theta = 1-T/Tc\n    CEGO::EArray<std::complex<double>> o = 1.0 + 0*theta;\n    for (auto i = 0; i < b.size(); ++i) {\n        o += b[i] * theta.pow(c[i]);\n    }\n    return o;\n}\n\ntemplate <typename Coeffs, typename Theta>\nauto eval_fit(const Coeffs &coeffs, const Theta &theta) {\n    if constexpr (is_any<Coeffs, std::vector<double>, std::vector<std::complex<double>>, std::vector<CEGO::numberish>>::value) {\n        Coeffs b(coeffs.begin(), coeffs.begin() + coeffs.size() / 2);\n        Coeffs c(coeffs.begin() + coeffs.size() / 2, coeffs.end());\n        return evaluate_RHS(theta, b, c);\n    }\n    else {\n        Coeffs b = coeffs.head(coeffs.size() / 2),\n            c = coeffs.tail(coeffs.size() / 2);\n        return evaluate_RHS(theta, b, c);\n    }\n}\n\ntemplate <typename Coeffs, typename Theta, typename Yval>\nauto objective(const Coeffs& coeffs, const Theta &theta, const Yval &yval) {\n    return (eval_fit(coeffs, theta) - yval).square().sum();\n};\n\ntemplate <typename Theta, typename Yval>\nauto objective(const CEGO::AbstractIndividual* pind, const Theta& theta, const Yval& yval) {\n    return objective(pind->get_coeffs_ArrayXd(), theta, yval);\n};\n\nstruct Inputs{\n    std::string root = \"\";\n    std::size_t parallel_threads = 1;\n    std::vector<std::size_t> Nlayersvec = { 1 };\n    std::size_t i = 0;\n    std::size_t gradmin_mod = 5;\n    std::size_t Nmax_gradient = 5;\n};\n\ninline void to_json(nlohmann::json& j, const Inputs& f) {\n    j = nlohmann::json{ { \"root\", f.root },{ \"parallel_threads\", f.parallel_threads },{\"i\",f.i},{\"gradmin_mod\",f.gradmin_mod},{\"Nmax_gradient\",f.Nmax_gradient} };\n}\n\ninline void from_json(const nlohmann::json& j, Inputs& f) {\n    j.at(\"root\").get_to(f.root);\n    j.at(\"parallel_threads\").get_to(f.parallel_threads);\n    j.at(\"i\").get_to(f.i);\n    j.at(\"gradmin_mod\").get_to(f.gradmin_mod);\n    j.at(\"Nmax_gradient\").get_to(f.Nmax_gradient);\n}\n\nint get_env_int(const std::string& var, int def) {\n    try {\n        char* s = std::getenv(var.c_str());\n        if (s == nullptr) {\n            return def;\n        }\n        if (strlen(s) == 0) {\n            return def;\n        }\n        return std::stoi(s, nullptr);\n    }\n    catch (...) {\n        return def;\n    }\n}\n\nvoid do_one(Inputs& inputs)\n{\n    std::srand((unsigned int)time(0));\n\n    const CEGO::EArray<double> theta = 1 - CEGO::EArray<double>::LinSpaced(1000, Tt, Tc) / Tc;\n    const CEGO::EArray<double> yval = evaluate_RHS(theta, b, c);\n\n    // Construct the bounds\n    std::vector<CEGO::Bound> bounds;\n    for (auto i = 0; i < b.size(); ++i) {\n        double v0 = 0.1 * b[i], v1 = 10 * b[i];\n        bounds.push_back(CEGO::Bound(std::make_pair(std::min(v0, v1), std::max(v0, v1))));\n    }\n    for (auto i = 0; i < c.size(); ++i) {\n        double v0 = 0.1 * c[i], v1 = 4 * c[i];\n        bounds.push_back(CEGO::Bound(std::make_pair(std::min(v0, v1), std::max(v0, v1))));\n    }\n\n    CEGO::CostFunction<CEGO::numberish> cost_wrapper = [&theta, &yval](const CEGO::AbstractIndividual* pind) {return objective(pind, theta, yval); };\n    auto Npop_size = 10*bounds.size();\n    auto Nlayers = 3;\n    auto layers = CEGO::Layers<CEGO::numberish>(cost_wrapper, bounds.size(), Npop_size, Nlayers, 5);\n    layers.parallel = (inputs.parallel_threads > 1);\n    layers.parallel_threads = inputs.parallel_threads;\n    layers.set_builtin_evolver(CEGO::BuiltinEvolvers::differential_evolution);\n    layers.set_bounds(bounds);\n    auto f = [&theta, &yval](const CEGO::EArray<double>& c) {return objective(c, theta, yval); };\n    auto f2 = [&theta, &yval](const CEGO::EArray<std::complex< double >>& c) {return objective(c, theta, yval); };\n    layers.add_gradient(f, f2);\n\n    auto flags = layers.get_evolver_flags();\n    flags[\"Nelite\"] = 3;\n    flags[\"Fmin\"] = 0.1;\n    flags[\"Fmax\"] = 1.0;\n    flags[\"CR\"] = 1;\n    layers.set_evolver_flags(flags);\n\n    std::vector<double> best_costs; \n    std::vector<std::vector<double> > objs;\n    double VTR = 1e-16, best_cost = 999999.0;\n    auto startTime = std::chrono::system_clock::now();\n    for (auto counter = 0; counter < 5000; ++counter) {\n        layers.do_generation();\n\n        if (counter % inputs.gradmin_mod == 0 && counter > 0) {\n            layers.gradient_minimizer();\n        }\n\n        // For the overall best result, print it, and write JSON to file\n        auto [best_layer, best_coeffs] = layers.get_best();\n        if (counter % 50 == 0) {\n            std::cout << counter << \": best: \" << best_cost << \"\\n \";\n            std::cout << best_coeffs << \"\\n\";\n        }\n        if (best_cost < VTR){ break; }\n    }\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}\n\nint main() {\n    Inputs in;\n    in.root = \"shaped-\";\n    in.Nlayersvec = {1};\n    auto Nrepeats = get_env_int(\"NREPEATS\", 1);\n    in.gradmin_mod = get_env_int(\"GRADMOD\", 100);\n    in.parallel_threads = get_env_int(\"NTHREADS\", 5);\n    in.Nmax_gradient = get_env_int(\"NMAX_gradient\", 5);\n    nlohmann::json j = in;\n    std::cout << j << std::endl;\n    for (in.i = 0; in.i < Nrepeats; ++in.i) {\n        do_one(in);\n    }\n}\n", "meta": {"hexsha": "57a5a8ee632648c767c7a436a39fe0d50cdc8cb2", "size": 6180, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/Wagner_water_fitting.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/Wagner_water_fitting.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/Wagner_water_fitting.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": 35.5172413793, "max_line_length": 162, "alphanum_fraction": 0.6058252427, "num_tokens": 1946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257655, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5133656650453486}}
{"text": "//\n//  Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n\n#include <boost/numeric/ublas/tensor/multiplication.hpp>\n#include <boost/numeric/ublas/tensor/extents.hpp>\n#include \"utility.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\n\nBOOST_AUTO_TEST_SUITE (test_tensor_contraction)\n\n\nusing test_types = zip<int,float,std::complex<float>>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\n//using test_types = zip<int>::with_t<boost::numeric::ublas::layout::first_order>;\n\n\nstruct fixture\n{\n  using extents_t = boost::numeric::ublas::extents<>;\n  const std::vector<extents_t> extents =\n  {\n    extents_t{1,1}, // 1\n    extents_t{1,2}, // 2\n    extents_t{2,1}, // 3\n    extents_t{2,3}, // 4\n    extents_t{5,4}, // 5\n    extents_t{2,3,1}, // 6\n    extents_t{4,1,3}, // 7\n    extents_t{1,2,3}, // 8\n    extents_t{4,2,3}, // 9\n    extents_t{4,2,3,5} // 10\n  };\n};\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE(test_tensor_mtv, value,  test_types, fixture )\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n  using vector_t  = std::vector<value_t>;\n  using extents_t = ublas::extents<>;\n  using extents_base_t = typename extents_t::base_type;\n\n\n  for(auto const& na : extents) {\n\n    if(ublas::size(na) > 2)\n      continue;\n\n    auto a = vector_t(ublas::product(na), value_t{2});\n    auto wa = ublas::to_strides(na,layout_t{});\n    for(auto m = std::size_t{0}; m < ublas::size(na); ++m){\n      auto nb = extents_t {na[m],std::size_t{1}};\n      auto wb = ublas::to_strides(nb,layout_t{});\n      auto b  = vector_t  (ublas::product(nb), value_t{1} );\n\n      auto nc_base = extents_base_t(std::max(std::size_t{ublas::size(na)-1u}, std::size_t{2}), 1);\n\n      for(auto i = 0ul, j = 0ul; i < ublas::size(na); ++i)\n        if(i != m)\n          nc_base[j++] = na[i];\n\n      auto nc = extents_t (nc_base);\n      auto wc = ublas::to_strides(nc,layout_t{});\n      auto c  = vector_t  (ublas::product(nc), value_t{0});\n\n      ublas::detail::recursive::mtv(\n        m,\n        c.data(), nc.data(), wc.data(),\n        a.data(), na.data(), wa.data(),\n        b.data());\n\n      auto v = value_t(na[m]);\n      BOOST_CHECK(std::equal(c.begin(),c.end(),a.begin(), [v](auto cc, auto aa){return cc == v*aa;}));\n\n//      for(auto i = 0u; i < c.size(); ++i)\n//        BOOST_CHECK_EQUAL( c[i] , value_t( static_cast< inner_type_t<value_t> >(na[m]) ) * a[i] );\n\n    }\n  }\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_mtm, value,  test_types, fixture )\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n  using vector_t  = std::vector<value_t>;\n  using extents_t = ublas::extents<>;\n\n  for(auto const& na : extents) {\n\n    if(ublas::size(na) != 2)\n      continue;\n\n    auto a  = vector_t  (ublas::product(na), value_t{2});\n    auto wa = ublas::to_strides(na,layout_t{});\n\n    auto nb = extents_t {na[1],na[0]};\n    auto wb = ublas::to_strides(nb,layout_t{});\n    auto b  = vector_t  (ublas::product(nb), value_t{1} );\n\n    auto nc = extents_t {na[0],nb[1]};\n    auto wc = ublas::to_strides(nc,layout_t{});\n    auto c  = vector_t  (ublas::product(nc));\n\n\n    ublas::detail::recursive::mtm(\n      c.data(), nc.data(), wc.data(),\n      a.data(), na.data(), wa.data(),\n      b.data(), nb.data(), wb.data());\n\n    auto v = value_t(na[1])*a[0];\n    BOOST_CHECK(std::all_of(c.begin(),c.end(), [v](auto cc){return cc == v;}));\n\n//    for(auto i = 0u; i < c.size(); ++i)\n//      BOOST_CHECK_EQUAL( c[i] , value_t( static_cast< inner_type_t<value_t> >(na[1]) ) * a[0] );\n\n\n  }\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_ttv, value,  test_types, fixture )\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n  using vector_t  = std::vector<value_t>;\n  using extents_t = ublas::extents<>;\n  using extents_base_t = typename extents_t::base_type;\n\n  for(auto const& na : extents) {\n\n    auto a = vector_t(ublas::product(na), value_t{2});\n    auto wa = ublas::to_strides(na,layout_t{});\n    for(auto m = std::size_t{0}; m < ublas::size(na); ++m){\n      auto b  = vector_t  (na[m], value_t{1} );\n      auto nb = extents_t {na[m],1};\n      auto wb = ublas::to_strides(nb,layout_t{});\n\n      auto nc_base = extents_base_t(std::max(std::size_t{ublas::size(na)-1u}, std::size_t{2}),1);\n\n      for(auto i = 0ul, j = 0ul; i < ublas::size(na); ++i)\n        if(i != m)\n          nc_base[j++] = na[i];\n\n      auto nc = extents_t (nc_base);\n      auto wc = ublas::to_strides(nc,layout_t{});\n      auto c  = vector_t  (ublas::product(nc), value_t{0});\n\n      ublas::ttv(m+1, ublas::size(na),\n                 c.data(), nc.data(), wc.data(),\n                 a.data(), na.data(), wa.data(),\n                 b.data(), nb.data(), wb.data());\n\n      auto v = value_t(na[m]);\n      BOOST_CHECK(std::equal(c.begin(),c.end(),a.begin(), [v](auto cc, auto aa){return cc == v*aa;}));\n\n//      for(auto i = 0u; i < c.size(); ++i)\n//        BOOST_CHECK_EQUAL( c[i] , value_t(na[m]) * a[i] );\n\n    }\n  }\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_ttm, value,  test_types, fixture )\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n  using vector_t  = std::vector<value_t>;\n  using extents_t = ublas::extents<>;\n\n\n  for(auto const& na : extents) {\n\n    auto a = vector_t(ublas::product(na), value_t{2});\n    auto wa = ublas::to_strides(na,layout_t{});\n    for(auto m = std::size_t{0}; m < ublas::size(na); ++m){\n      const auto nb = extents_t {na[m], na[m] };\n      const auto b  = vector_t  (ublas::product(nb), value_t{1} );\n      const auto wb = ublas::to_strides(nb,layout_t{});\n\n\n      const auto& nc = na;\n      const auto wc = ublas::to_strides(nc,layout_t{});\n      auto c  = vector_t  (ublas::product(nc), value_t{0});\n\n      ublas::ttm(m+1, ublas::size(na),\n                 c.data(), nc.data(), wc.data(),\n                 a.data(), na.data(), wa.data(),\n                 b.data(), nb.data(), wb.data());\n\n\n      auto v = value_t(na[m]);\n      BOOST_CHECK(std::equal(c.begin(),c.end(),a.begin(), [v](auto cc, auto aa){return cc == v*aa;}));\n\n\n//      for(auto i = 0u; i < c.size(); ++i)\n//        BOOST_CHECK_EQUAL( c[i] , value_t( static_cast< inner_type_t<value_t> >(na[m]) ) * a[i] );\n\n    }\n  }\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_ttt_permutation, value,  test_types, fixture )\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n  using vector_t  = std::vector<value_t>;\n  using extents_t = ublas::extents<>;\n  using extents_base_t = typename extents_t::base_type;\n\n\n  auto compute_factorial = [](auto const& p){\n    auto f = 1ul;\n    for(auto i = 1u; i <= p; ++i)\n      f *= i;\n    return f;\n  };\n\n\n  auto compute_inverse_permutation = [](auto const& pi){\n    auto pi_inv = pi;\n    for(auto j = 0u; j < pi.size(); ++j)\n      pi_inv[pi[j]-1] = j+1;\n    return pi_inv;\n  };\n\n  auto permute_extents = [](auto const& pi, auto const& na){\n    auto nb_base = na.base();\n    assert(pi.size() == ublas::size(na));\n    for(auto j = 0u; j < pi.size(); ++j)\n      nb_base[j] = na[pi[j]-1];\n    return extents_t(nb_base);\n  };\n\n\n  // left-hand and right-hand side have the\n  // the same number of elements\n\n  // computing the inner product with\n  // different permutation tuples for\n  // right-hand side\n\n  for(auto const& na : extents) {\n\n    auto wa = ublas::to_strides(na,layout_t{});\n    auto a  = vector_t(ublas::product(na), value_t{2});\n    auto pa  = ublas::size(na);\n    auto pia = std::vector<std::size_t>(pa);\n    std::iota( pia.begin(), pia.end(), std::size_t{1} );\n\n    auto pib     = pia;\n    auto pib_inv = compute_inverse_permutation(pib);\n\n    auto f = compute_factorial(pa);\n\n    // for the number of possible permutations\n    // only permutation tuple pib is changed.\n    for(auto i = 0u; i < f; ++i) {\n\n      auto nb = permute_extents( pib, na  );\n      auto wb = ublas::to_strides(nb,layout_t{});\n      auto b  = vector_t(ublas::product(nb), value_t{3});\n      auto pb = ublas::size(nb);\n\n      // the number of contractions is changed.\n      for(auto q = std::size_t{0}; q <= pa; ++q) {\n\n        auto r  = pa - q;\n        auto s  = pb - q;\n\n        auto pc = r+s > 0 ? std::max(std::size_t{r+s},std::size_t{2}) : std::size_t{2};\n\n        auto nc_base = extents_base_t(pc,std::size_t{1});\n\n        for(auto j = 0u; j < r; ++j)\n          nc_base[j] = na[pia[j]-1];\n\n        for(auto j = 0u; j < s; ++j)\n          nc_base[r+j] = nb[ pib_inv[j]-1 ];\n\n        auto nc = extents_t ( nc_base );\n        auto wc = ublas::to_strides(nc,layout_t{});\n        auto c  = vector_t  ( ublas::product(nc), value_t(0) );\n\n        ublas::ttt(pa,pb,q,\n                   pia.data(), pib_inv.data(),\n                   c.data(), nc.data(), wc.data(),\n                   a.data(), na.data(), wa.data(),\n                   b.data(), nb.data(), wb.data());\n\n\n        auto acc = std::size_t{1};\n        for(auto j = r; j < pa; ++j)\n          acc *= na[pia[j]-1];\n\n        auto v = value_t(acc)*a[0]*b[0];\n\n        BOOST_CHECK( std::all_of(c.begin(),c.end(), [v](auto cc){return cc == v; } ) );\n\n      }\n\n      std::next_permutation(pib.begin(), pib.end());\n      pib_inv = compute_inverse_permutation(pib);\n    }\n  }\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_ttt, value,  test_types, fixture )\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n  using vector_t  = std::vector<value_t>;\n  using extents_t = ublas::extents<>;\n  using extents_base_t = typename extents_t::base_type;\n\n  // left-hand and right-hand side have the\n  // the same number of elements\n\n  // computing the inner product with\n  // different permutation tuples for\n  // right-hand side\n\n  for(auto const& na : extents) {\n\n    auto wa = ublas::to_strides(na,layout_t{});\n    auto a  = vector_t(ublas::product(na), value_t{2});\n    auto pa = ublas::size(na);\n\n    auto const& nb = na;\n    auto wb = ublas::to_strides(nb,layout_t{});\n    auto b  = vector_t(ublas::product(nb), value_t{3});\n    auto pb = ublas::size(nb);\n\n    //  std::cout << \"na = \";\n    //  std::copy(na.begin(), na.end(), std::ostream_iterator<size_type>(std::cout, \" \"));\n    //  std::cout << std::endl;\n\n    //  std::cout << \"nb = \";\n    //  std::copy(nb.begin(), nb.end(), std::ostream_iterator<size_type>(std::cout, \" \"));\n    //  std::cout << std::endl;\n\n\n    // the number of contractions is changed.\n    for( auto q = std::size_t{0}; q <= pa; ++q) { // pa\n\n      auto r  = pa - q;\n      auto s  = pb - q;\n\n      auto pc = r+s > 0 ? std::max(std::size_t{r+s},std::size_t{2}) : std::size_t{2};\n\n      auto nc_base = extents_base_t(pc,std::size_t{1});\n\n      for(auto i = 0u; i < r; ++i)\n        nc_base[i] = na[i];\n\n      for(auto i = 0u; i < s; ++i)\n        nc_base[r+i] = nb[i];\n\n      auto nc = extents_t ( nc_base );\n      auto wc = ublas::to_strides(nc,layout_t{});\n      auto c  = vector_t  ( ublas::product(nc), value_t{0} );\n\n      //   std::cout << \"nc = \";\n      //   std::copy(nc.begin(), nc.end(), std::ostream_iterator<size_type>(std::cout, \" \"));\n      //   std::cout << std::endl;\n\n      ublas::ttt(pa,pb,q,\n                 c.data(), nc.data(), wc.data(),\n                 a.data(), na.data(), wa.data(),\n                 b.data(), nb.data(), wb.data());\n\n\n      auto acc = std::size_t{1};\n      for(auto i = r; i < pa; ++i)\n        acc *= na[i];\n\n      auto v = value_t(acc)*a[0]*b[0];\n\n      BOOST_CHECK( std::all_of(c.begin(),c.end(), [v](auto cc){return cc == v; } ) );\n    }\n\n  }\n}\n\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_inner, value,  test_types, fixture )\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n  using vector_t  = std::vector<value_t>;\n\n  for(auto const& n : extents) {\n\n    auto a = vector_t(ublas::product(n), value_t{2});\n    auto b = vector_t(ublas::product(n), value_t{3});\n    auto w = ublas::to_strides(n,layout_t{});\n\n    auto c = ublas::inner(ublas::size(n), n.data(), a.data(), w.data(), b.data(), w.data(), value_t(0));\n    auto cref = std::inner_product(a.begin(), a.end(), b.begin(), value_t(0));\n\n\n    BOOST_CHECK_EQUAL( c , cref );\n\n  }\n\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_outer, value,  test_types, fixture )\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n  using extents_t = ublas::extents<>;\n  using vector_t  = std::vector<value_t>;\n\n\n  for(auto const& na : extents) {\n\n    auto a = vector_t(ublas::product(na), value_t{2});\n    auto wa = ublas::to_strides(na,layout_t{});\n\n    for(auto const& nb : extents) {\n\n      auto b = vector_t(ublas::product(nb), value_t{3});\n      auto wb = ublas::to_strides(nb,layout_t{});\n\n      auto c = vector_t(ublas::product(nb)*ublas::product(na));\n      auto nc_base = typename extents_t::base_type(ublas::size(na)+ublas::size(nb));\n\n      for(auto i = 0u; i < ublas::size(na); ++i)\n        nc_base[i] = na[i];\n      for(auto i = 0u; i < ublas::size(nb); ++i)\n        nc_base[i+ublas::size(na)] = nb[i];\n\n      auto nc = extents_t(nc_base);\n      auto wc = ublas::to_strides(nc,layout_t{});\n\n      ublas::outer(c.data(), ublas::size(nc), nc.data(), wc.data(),\n                   a.data(), ublas::size(na), na.data(), wa.data(),\n                   b.data(), ublas::size(nb), nb.data(), wb.data());\n\n      for(auto const& cc : c)\n        BOOST_CHECK_EQUAL( cc , a[0]*b[0] );\n    }\n\n  }\n\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c5ed51e5fc3524ab23c1668f2234b7cf4d2817dc", "size": 14216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_multiplication.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_multiplication.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_multiplication.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 29.1909650924, "max_line_length": 149, "alphanum_fraction": 0.5864518852, "num_tokens": 4379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5133656650453486}}
{"text": "#define _USE_MATH_DEFINES\n#include <algorithm> // std::sort\n#include <vector>\n\n#include <Eigen/Dense>\n#include <ccd/ccd.h>\n#include <gtest/gtest.h>\n#include <math.h>\n\n#include \"dart/collision/dart/DARTCollide.hpp\"\n#include \"dart/dynamics/BallJoint.hpp\"\n#include \"dart/dynamics/FreeJoint.hpp\"\n#include \"dart/realtime/Ticker.hpp\"\n#include \"dart/server/GUIWebsocketServer.hpp\"\n#include \"dart/utils/DartResourceRetriever.hpp\"\n#include \"dart/utils/sdf/sdf.hpp\"\n#include \"dart/utils/urdf/urdf.hpp\"\n\n#include \"TestHelpers.hpp\"\n\nusing namespace dart;\nusing namespace realtime;\n\n#define ALL_TESTS\n\nEigen::MatrixXs skelPosPosJacFD(\n    std::shared_ptr<dynamics::Skeleton> skel,\n    Eigen::VectorXs pos,\n    Eigen::VectorXs vel,\n    s_t dt)\n{\n  int dofs = skel->getNumDofs();\n  Eigen::MatrixXs jac = Eigen::MatrixXs::Zero(dofs, dofs);\n  s_t EPS = 1e-7;\n  for (int i = 0; i < dofs; i++)\n  {\n    Eigen::VectorXs perturbed = pos;\n    perturbed(i) += EPS;\n    Eigen::VectorXs plus = skel->integratePositionsExplicit(perturbed, vel, dt);\n\n    perturbed = pos;\n    perturbed(i) -= EPS;\n    Eigen::VectorXs minus\n        = skel->integratePositionsExplicit(perturbed, vel, dt);\n\n    jac.col(i) = (plus - minus) / (2 * EPS);\n  }\n\n  return jac;\n}\n\nEigen::MatrixXs skelVelPosJacFD(\n    std::shared_ptr<dynamics::Skeleton> skel,\n    Eigen::VectorXs pos,\n    Eigen::VectorXs vel,\n    s_t dt)\n{\n  int dofs = skel->getNumDofs();\n  Eigen::MatrixXs jac = Eigen::MatrixXs::Zero(dofs, dofs);\n  s_t EPS = 1e-7;\n  for (int i = 0; i < dofs; i++)\n  {\n    Eigen::VectorXs perturbed = vel;\n    perturbed(i) += EPS;\n    Eigen::VectorXs plus = skel->integratePositionsExplicit(pos, perturbed, dt);\n\n    perturbed = vel;\n    perturbed(i) -= EPS;\n    Eigen::VectorXs minus\n        = skel->integratePositionsExplicit(pos, perturbed, dt);\n\n    jac.col(i) = (plus - minus) / (2 * EPS);\n  }\n\n  return jac;\n}\n\n//==============================================================================\n#ifdef ALL_TESTS\nTEST(FreeJointGradients, ATLAS_JACOBIANS)\n{\n  std::shared_ptr<simulation::World> world = simulation::World::create();\n  std::shared_ptr<dynamics::Skeleton> atlas\n      = dart::utils::SdfParser::readSkeleton(\n          \"dart://sample/sdf/atlas/atlas_v3_no_head.sdf\");\n  world->addSkeleton(atlas);\n\n  int dofs = atlas->getNumDofs();\n  s_t dt = 0.01;\n  for (int i = 0; i < 10; i++)\n  {\n    Eigen::VectorXs pos = Eigen::VectorXs::Random(dofs);\n    Eigen::VectorXs vel = Eigen::VectorXs::Random(dofs);\n\n    Eigen::MatrixXs posPosAnalytical = atlas->getPosPosJac(pos, vel, dt);\n    Eigen::MatrixXs velPosAnalytical = atlas->getVelPosJac(pos, vel, dt);\n    Eigen::MatrixXs posPosFD = skelPosPosJacFD(atlas, pos, vel, dt);\n    Eigen::MatrixXs velPosFD = skelVelPosJacFD(atlas, pos, vel, dt);\n\n    const s_t tol = 3e-9;\n\n    if (!equals(posPosAnalytical, posPosFD, tol))\n    {\n      std::cout << \"Pos-Pos Analytical (top-left 6x6): \" << std::endl\n                << posPosAnalytical.block<6, 6>(0, 0) << std::endl;\n      std::cout << \"Pos-Pos FD (top-left 6x6): \" << std::endl\n                << posPosFD.block<6, 6>(0, 0) << std::endl;\n      std::cout << \"Pos-Pos Diff (\" << (posPosAnalytical - posPosFD).minCoeff()\n                << \" - \" << (posPosAnalytical - posPosFD).maxCoeff()\n                << \") (top-left 6x6): \" << std::endl\n                << (posPosAnalytical - posPosFD).block<6, 6>(0, 0) << std::endl;\n      break;\n    }\n    EXPECT_TRUE(equals(posPosAnalytical, posPosFD, tol));\n\n    if (!equals(velPosAnalytical, velPosFD, tol))\n    {\n      std::cout << \"Vel-Pos Analytical (top-left 6x6): \" << std::endl\n                << velPosAnalytical.block<6, 6>(0, 0) << std::endl;\n      std::cout << \"Vel-Pos FD (top-left 6x6): \" << std::endl\n                << velPosFD.block<6, 6>(0, 0) << std::endl;\n      std::cout << \"Vel-Pos Diff (\" << (velPosAnalytical - velPosFD).minCoeff()\n                << \" - \" << (velPosAnalytical - velPosFD).maxCoeff()\n                << \") (top-left 6x6): \" << std::endl\n                << (velPosAnalytical - velPosFD).block<6, 6>(0, 0) << std::endl;\n      break;\n    }\n    EXPECT_TRUE(equals(velPosAnalytical, velPosFD, tol));\n\n    world->step();\n  }\n}\n#endif\n\n//==============================================================================\n#ifdef ALL_TESTS\nTEST(FreeJointGradients, INTEGRATE_POSITIONS_EXPLICIT)\n{\n  std::shared_ptr<simulation::World> world = simulation::World::create();\n  std::shared_ptr<dynamics::Skeleton> atlas\n      = dart::utils::SdfParser::readSkeleton(\n          \"dart://sample/sdf/atlas/atlas_v3_no_head.sdf\");\n  world->addSkeleton(atlas);\n\n  int dofs = atlas->getNumDofs();\n  s_t dt = 0.01;\n  for (int i = 0; i < 1000; i++)\n  {\n    Eigen::VectorXs pos = Eigen::VectorXs::Random(dofs);\n    Eigen::VectorXs vel = Eigen::VectorXs::Random(dofs);\n    atlas->setPositions(pos);\n    atlas->setVelocities(vel);\n    atlas->integratePositions(dt);\n    Eigen::VectorXs implicitNextPos = atlas->getPositions();\n\n    // Scramble positions\n    atlas->setPositions(Eigen::VectorXs::Random(dofs));\n    atlas->setVelocities(Eigen::VectorXs::Random(dofs));\n    Eigen::VectorXs explicitNextPos\n        = atlas->integratePositionsExplicit(pos, vel, dt);\n\n    EXPECT_TRUE(implicitNextPos.isApprox(explicitNextPos, 1e-10));\n  }\n}\n#endif\n\n//==============================================================================\nEigen::Vector6s integratePos(\n    Eigen::Vector6s pos, Eigen::Vector6s vel, s_t dt)\n{\n  const Eigen::Isometry3s mQ = FreeJoint::convertToTransform(pos);\n  const Eigen::Isometry3s Qnext = mQ * FreeJoint::convertToTransform(vel * dt);\n\n  return FreeJoint::convertToPositions(Qnext);\n}\n\nEigen::Vector6s integratePosByParts(\n    Eigen::Vector6s pos, Eigen::Vector6s vel, s_t dt)\n{\n  const Eigen::Matrix3s mR = BallJoint::convertToRotation(pos.head<3>());\n  const Eigen::Matrix3s Rnext\n      = mR * BallJoint::convertToRotation(vel.head<3>() * dt);\n\n  Eigen::Vector6s ret = Eigen::Vector6s::Zero();\n  ret.head<3>() = BallJoint::convertToPositions(Rnext);\n  ret.tail<3>() = pos.tail<3>() + (mR * vel.tail<3>() * dt);\n\n  return ret;\n}\n\n//==============================================================================\n#ifdef ALL_TESTS\nTEST(FreeJointGradients, FREE_JOINT_BY_PARTS)\n{\n  s_t dt = 0.01;\n\n  for (int i = 0; i < 1000; i++)\n  {\n    Eigen::Vector6s pos = Eigen::Vector6s::Random();\n    Eigen::Vector6s vel = Eigen::Vector6s::Random();\n    Eigen::Vector6s nextPos = integratePos(pos, vel, dt);\n    Eigen::Vector6s nextPosByParts = integratePosByParts(pos, vel, dt);\n\n    EXPECT_TRUE(nextPosByParts.isApprox(nextPos, 1e-9));\n  }\n}\n#endif\n\nEigen::Vector3s rotateBall(Eigen::Vector3s pos, Eigen::Vector3s vel, s_t dt)\n{\n  const Eigen::Matrix3s mR = BallJoint::convertToRotation(pos.head<3>());\n  const Eigen::Matrix3s Rnext\n      = mR * BallJoint::convertToRotation(vel.head<3>() * dt);\n  return BallJoint::convertToPositions(Rnext);\n}\n\nEigen::Matrix3s rotatePosPosJacFD(\n    Eigen::Vector3s pos, Eigen::Vector3s vel, s_t dt)\n{\n  Eigen::Matrix3s jac = Eigen::Matrix3s::Zero();\n\n  const s_t EPS = 1e-7;\n  for (int i = 0; i < 3; i++)\n  {\n    Eigen::Vector3s perturbed = pos;\n    perturbed(i) += EPS;\n    Eigen::Vector3s outPos = rotateBall(perturbed, vel, dt);\n\n    perturbed = pos;\n    perturbed(i) -= EPS;\n    Eigen::Vector3s outNeg = rotateBall(perturbed, vel, dt);\n\n    jac.col(i) = (outPos - outNeg) / (2 * EPS);\n  }\n\n  return jac;\n}\n\nEigen::Matrix3s rotateVelPosJacFD(\n    Eigen::Vector3s pos, Eigen::Vector3s vel, s_t dt)\n{\n  Eigen::Matrix3s jac = Eigen::Matrix3s::Zero();\n\n  const s_t EPS = 1e-7;\n  for (int i = 0; i < 3; i++)\n  {\n    Eigen::Vector3s perturbed = vel;\n    perturbed(i) += EPS;\n    Eigen::Vector3s outPos = rotateBall(pos, perturbed, dt);\n\n    perturbed = vel;\n    perturbed(i) -= EPS;\n    Eigen::Vector3s outNeg = rotateBall(pos, perturbed, dt);\n\n    jac.col(i) = (outPos - outNeg) / (2 * EPS);\n  }\n\n  return jac;\n}\n\n//==============================================================================\n#ifdef ALL_TESTS\nTEST(FreeJointGradients, ROTATION_JOINT_JAC)\n{\n  s_t dt = 0.01;\n  Eigen::Vector3s pos = Eigen::Vector3s::UnitX();\n  Eigen::Vector3s vel = Eigen::Vector3s::UnitY();\n\n  // Just check these don't crash\n  rotatePosPosJacFD(pos, vel, dt);\n  rotateVelPosJacFD(pos, vel, dt);\n}\n#endif\n\n/*\n//==============================================================================\n#ifdef ALL_TESTS\nTEST(FreeJointGradients, GUI_EXPLORE)\n{\n  // Create a world\n  std::shared_ptr<simulation::World> world = simulation::World::create();\n\n  // Set gravity of the world\n  // world->setPenetrationCorrectionEnabled(true);\n  world->setGravity(Eigen::Vector3s(0.0, -9.81, 0));\n\n  std::shared_ptr<BoxShape> boxShape(\n      new BoxShape(Eigen::Vector3s(1.0, 1.0, 1.0)));\n\n  std::shared_ptr<dynamics::Skeleton> box = dynamics::Skeleton::create(\"box\");\n  auto pair = box->createJointAndBodyNodePair<dynamics::FreeJoint>();\n  pair.second->createShapeNodeWith<VisualAspect, CollisionAspect>(boxShape);\n  pair.second->setFrictionCoeff(0.0);\n\n  std::shared_ptr<dynamics::Skeleton> groundBox\n      = dynamics::Skeleton::create(\"groundBox\");\n  auto groundPair\n      = groundBox->createJointAndBodyNodePair<dynamics::WeldJoint>();\n  std::shared_ptr<BoxShape> groundShape(\n      new BoxShape(Eigen::Vector3s(10.0, 1.0, 10.0)));\n  groundPair.second->createShapeNodeWith<VisualAspect, CollisionAspect>(\n      groundShape);\n  groundPair.second->setFrictionCoeff(1.0);\n  Eigen::Isometry3s groundTransform = Eigen::Isometry3s::Identity();\n  groundTransform.translation()(1) = -0.999;\n  groundPair.first->setTransformFromParentBodyNode(groundTransform);\n\n  // world->addSkeleton(atlas);\n  world->addSkeleton(box);\n  world->addSkeleton(groundBox);\n\n  // Disable the ground from casting its own shadows\n  groundBox->getBodyNode(0)->getShapeNode(0)->getVisualAspect()->setCastShadows(\n      false);\n\n  world->step();\n\n  std::vector<Eigen::Vector3s> pointsX;\n  pointsX.push_back(Eigen::Vector3s::Zero());\n  pointsX.push_back(Eigen::Vector3s::UnitX() * 10);\n  std::vector<Eigen::Vector3s> pointsY;\n  pointsY.push_back(Eigen::Vector3s::Zero());\n  pointsY.push_back(Eigen::Vector3s::UnitY() * 10);\n  std::vector<Eigen::Vector3s> pointsZ;\n  pointsZ.push_back(Eigen::Vector3s::Zero());\n  pointsZ.push_back(Eigen::Vector3s::UnitZ() * 10);\n\n  server::GUIWebsocketServer server;\n  server.renderWorld(world);\n  server.createLine(\"unitX\", pointsX, Eigen::Vector3s::UnitX());\n  server.createLine(\"unitY\", pointsY, Eigen::Vector3s::UnitY());\n  server.createLine(\"unitZ\", pointsZ, Eigen::Vector3s::UnitZ());\n  server.serve(8070);\n\n  Ticker ticker(0.01);\n  ticker.registerTickListener([&](long time) {\n    s_t diff = sin(((s_t)time / 2000));\n    diff = diff * diff;\n    // atlas->setPosition(0, diff * dart::math::constantsd::pi());\n    // s_t diff2 = sin(((s_t)time / 4000));\n    // atlas->setPosition(4, diff2 * 1);\n\n    Eigen::Isometry3s fromRoot = Eigen::Isometry3s::Identity();\n    fromRoot.translation() = Eigen::Vector3s::UnitZ() * diff;\n    pair.first->setTransformFromParentBodyNode(fromRoot);\n\n    server.renderWorld(world);\n  });\n  server.registerConnectionListener([&]() { ticker.start(); });\n\n  while (server.isServing())\n  {\n  }\n}\n#endif\n*/", "meta": {"hexsha": "fa3b415ed3945ac45e25678a5d210a40d8e59ebd", "size": 11151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/unit/test_FreeJointGradients.cpp", "max_stars_repo_name": "jyf588/nimblephysics", "max_stars_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T06:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T09:59:09.000Z", "max_issues_repo_path": "unittests/unit/test_FreeJointGradients.cpp", "max_issues_repo_name": "jyf588/nimblephysics", "max_issues_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "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": "unittests/unit/test_FreeJointGradients.cpp", "max_forks_repo_name": "jyf588/nimblephysics", "max_forks_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T13:56:14.000Z", "avg_line_length": 31.3230337079, "max_line_length": 80, "alphanum_fraction": 0.631871581, "num_tokens": 3338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5133656648548326}}
{"text": "#include <boost/math/common_factor_ct.hpp>\n", "meta": {"hexsha": "dd232be52f441bb38d1db499e377bcb4e0576073", "size": 43, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_common_factor_ct.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_common_factor_ct.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_common_factor_ct.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 21.5, "max_line_length": 42, "alphanum_fraction": 0.8139534884, "num_tokens": 9, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594355, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5133656588651642}}
{"text": "#ifndef CX_DQMC_DENSITY_HPP\n#define CX_DQMC_DENSITY_HPP\n\n#include \"la.hpp\"\n#include \"parameters.hpp\"\n#include \"cx_workspace.hpp\"\n\n#include <Eigen/Eigenvalues>\n\n#include <boost/foreach.hpp>\n\n#include <cmath>\n#include <exception>\n#include <iomanip>\n\nnamespace cx_dqmc {\n    namespace density {       \n\tinline void density_matrix(dqmc::parameters& p,\n\t\t\t\t   cx_dqmc::workspace& ws) {\n\t    using namespace std;\n\t    srand(23);\n\t    double rand_hop;\n\t    double rand_eps = 0;\n\t    \n\t    pvec_t eigval(p.N);\n\t    pmat_t lowest_eigenvectors(p.N, p.particles);\n\t    pmat_t density(p.N, p.N), eigvec(p.N, p.N);\n\n\t    density.setZero();\n\t    \n\t    if (ws.density.cols() != p.N) {\n\t\tthrow std::runtime_error(\"Dimensions of density are incorrect\");\n\t    }\n\t    \n\t    for (int attempt = 0; attempt < 4; ++attempt) {\n\t\talps::graph_helper<>::bond_iterator itr1, itr1_end;\t    \n\t\tfor (boost::tie(itr1, itr1_end) = p.graph.bonds(); itr1 != itr1_end; ++itr1) {\n\t\t    rand_hop = (1 + rand_eps * ( -0.5 + (std::rand() % RAND_MAX)/double(RAND_MAX)));\n\n\t\t    density(p.graph.source(*itr1), p.graph.target(*itr1)) =\n\t\t\t-p.ts[p.graph.bond_type(*itr1)] * rand_hop;\n\t\t    density(p.graph.target(*itr1), p.graph.source(*itr1)) =\n\t\t\t-p.ts[p.graph.bond_type(*itr1)] * rand_hop;\n\t\t}\t\t    \n\t\teigvec = density;\n\n\t\tEigen::SelfAdjointEigenSolver<mat> eig(density);\n\t\teig.compute(density);\n\t\teigval = eig.eigenvalues();\n\t\teigvec = eig.eigenvectors();\n\n\t\tbool error = false;\n\t\tfor (int i = 0; i < eigval.size() - 1; ++i) {\n\t\t    double diff;\n\t\t    diff = fabs(eigval(i + 1) - eigval(i));\n\t\t    if (diff < 1e-4) {\n\t\t\tif (attempt == 0) {\n\t\t\t    rand_eps = 1e-3;\n\t\t\t}\n\t\t\telse if (attempt == 1) {\n\t\t\t    rand_eps = 1e-2;\n\t\t\t}\t\t\n\t\t\telse if (attempt == 2) {\n\t\t\t    rand_eps = 1e-1;\n\t\t\t}\t\t\n\t\t\telse if (attempt == 3) {\n\t\t\t    rand_eps = 5e-1;\n\t\t\t}\t\t\n\t\t\telse if (attempt == 4) {\n\t\t\t    if (p.rank < 1) {\n\t\t\t\tcout << attempt << \" @ rand_eps = \" << rand_eps << \" - \" << diff << endl;\n\t\t\t    }\n\t\t\t    throw std::runtime_error(\"Degeneracy not lifted\");\n\t\t\t}\n\t\t\terror = true;\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t\tif (!error) {\n\t\t    break;\n\t\t}\n\t    }\n\t    \n\t    for (int i = 0; i < p.N; i++) {\n\t    \tfor (int j = 0; j < p.real_particles; j++) {\n\t\t    lowest_eigenvectors(i, j) = eigvec(i, j);\n\t    \t}\n\t    }\n\t    \n\t    for (int row = 0; row < p.N; row++) {\n\t\tfor (int col = 0; col < p.N; col++) {\n\t\t    ws.density(row, col) = cx_double(0, 0);\n\n\t\t    for (int i = 0; i < p.real_particles; i++) {\n\t\t\tws.density(row, col) +=\n\t\t\t    cx_double(lowest_eigenvectors(row, i) * lowest_eigenvectors(col, i), 0);\n\t\t\tws.den_U(row, i) = cx_double(lowest_eigenvectors(row, i), 0);\n\t\t    }\n\t\t}\n\t    }\n\n\t    // cout << p.outp << \"And den_u\" << endl << ws.den_U << endl << endl;\n \t}\n\n\tinline void cx_density_matrix(dqmc::parameters& p, cx_dqmc::workspace& ws) {\n\t    using namespace std;\n\n\t    srand(23);\n\t    double rand_hop;\n\t    double rand_eps = 0;\n\t    \n\t    cx_vec eigval(p.N);\n\t    cx_mat_t lowest_eigenvectors(p.N, p.real_particles);\n\t    cx_mat_t density(p.N, p.N), eigvec(p.N, p.N);\n\t    \n\n\t    if (ws.density.cols() != p.N) {\n\t\tthrow std::runtime_error(\"Dimensions of density are incorrect\");\n\t    }\n\n\t    ws.density.setZero();\n\t    for (int attempt = 0; attempt < 4; ++attempt) {\n\t\talps::graph_helper<>::bond_iterator itr1, itr1_end;\t    \n\t\tint s, t, b;\n\t\tdouble pref;\n\n\t\tfor (boost::tie(itr1, itr1_end) = p.graph.bonds(); itr1 != itr1_end; ++itr1) {\n\t\t    rand_hop = (1 + rand_eps * ( -0.5 + (std::rand() % RAND_MAX)/double(RAND_MAX)));\n\t\t    s = p.graph.source(*itr1);\n\t\t    t = p.graph.target(*itr1);\n\t\t    b = p.graph.bond_type(*itr1);\n\t\t    \t\t    \n\t\t    ws.density(s, t) = -1. * cx_double(p.ts[b] * rand_hop, -p.im_ts[b]* rand_hop);\n\t\t    ws.density(t, s) = -1. * cx_double(p.ts[b] * rand_hop, p.im_ts[b] * rand_hop);\n\t\t}\n\t\tws.eigvec = ws.density;\n\n\t\tEigen::SelfAdjointEigenSolver<cx_mat_t> eig(ws.density);\n\t\teig.compute(ws.density);\n\t\tvec revals = eig.eigenvalues();\n\t\tws.eigvec = eig.eigenvectors();\n\n\t\tif (attempt == 0) {\n\t\t    ofstream mat_file(\"eigenvectors.mat\", ios::out | ios::trunc);\n\t\t    mat_file << ws.eigvec;\n\t\t    mat_file.close();\n\n\t\t    ofstream vec_file(\"eigenvalues.vec\", ios::out | ios::trunc);\n\t\t    vec_file << revals;\n\t\t    vec_file.close();\n\t\t}\n\n\t\tstd::vector<max_pair > sorting;\n\t\tsorting.reserve(revals.size());\n\t\tfor (int i = 0; i < revals.size(); i++) {\n\t\t    double val = revals(i);\n\t\t    sorting.push_back(max_pair(val,i));\n\t\t}\n\t\tstd::sort(sorting.begin(),sorting.end());\n\t\tcx_mat_t sorted_eigvec;\n\t\tsorted_eigvec.resizeLike(ws.eigvec);\n\t\tfor (int i = 0; i < revals.size(); i++) {\n\t\t    revals.coeffRef(i,0) = sorting[i].first;\n\t\t    sorted_eigvec.col(i) = ws.eigvec.col(sorting[i].second);\n\t\t}\n\t\tif (attempt == 0) {\n\t\t    ofstream sorted_mat_file(\"sorted_eigenvectors.mat\", ios::out | ios::trunc);\n\t\t    sorted_mat_file << sorted_eigvec;\n\t\t    sorted_mat_file.close();\n\n\t\t    ofstream sorted_file(\"sorted_eigenvalues.vec\", ios::out | ios::trunc);\n\t\t    sorted_file << revals;\n\t\t    sorted_file.close();\n\t\t}\n\n\t\t// eigval = revals;\n\t\tws.eigvec = sorted_eigvec;\n\n\t\tbool error = false;\n\t\tfor (int i = 0; i < revals.size() - 1; ++i) {\n\t\t    // break;\n\t\t    double diff;\n\t\t    diff = abs(revals(i + 1) - revals(i));\n\t\t    if (diff < 1e-5) {\n\n\t\t\tif (attempt == 0) {\n\t\t\t    rand_eps = 1e-3;\n\t\t\t}\n\t\t\telse if (attempt == 1) {\n\t\t\t    rand_eps = 1e-2;\n\t\t\t}\t\t\n\t\t\telse if (attempt == 2) {\n\t\t\t    rand_eps = 1e-1;\n\t\t\t}\t\t\n\t\t\telse if (attempt == 3) {\n\t\t\t    throw std::runtime_error(\"Degeneracy not lifted\");\n\t\t\t}\n\t\t\terror = true;\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t\tif (!error) {\n\t\t    break;\n\t\t}\n\t    }\n\t    ws.den_U = ws.eigvec.block(0, 0, p.N, p.real_particles);\n\t    ws.density = ws.den_U * ws.den_U.adjoint();\n \t}\n    }\n}\n#endif\n", "meta": {"hexsha": "77478463130b52ff1273e62d8a1fd18d83efdec3", "size": 5674, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libdqmc/cx_density.hpp", "max_stars_repo_name": "pebroecker/DQMC", "max_stars_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "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": "libdqmc/cx_density.hpp", "max_issues_repo_name": "pebroecker/DQMC", "max_issues_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libdqmc/cx_density.hpp", "max_forks_repo_name": "pebroecker/DQMC", "max_forks_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "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.7641509434, "max_line_length": 86, "alphanum_fraction": 0.5712019739, "num_tokens": 1842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789040926008, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5133656563466212}}
{"text": "#include <libv/lma/lma.hpp>\n#include <libv/lma/numeric/divers.hpp>\n#include <libv/core/miscmath.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_same.hpp>\n\nusing namespace lma;\n\n\ntemplate<class Derivator>\nstruct F : Derivator\n{\n  double obs;\n  F(double obs_):obs(obs_){}\n\n  template<class X, class Y, class Res> bool error(const X& x, const Y& y, Res& res) const\n  {\n    res = x * y - obs;\n    return true;\n  }\n\n  bool operator()(double x, double y, double& res) const\n  {\n    return error(x,y,res);\n  }\n  \n  template<class Mat>\n  void analytical_derivative(double x, double y, Mat& mat1, Mat& mat2) const\n  {\n    static_assert(boost::is_same<Analytical,Derivator>::value,\"Only for analytical mode\");\n    mat1(0,0) = y;\n    mat2(0,0) = x;\n  }\n  \n  template<class AD>\n  bool automatic(double, AD x[1], double, AD y[1], AD res[1]) const\n  {\n    static_assert(boost::is_same<Automatic,Derivator>::value,\"Only for automatic mode\");\n    return error(x[0],y[0],res[0]);\n  }\n};\n\ntemplate<class F> std::tuple<double,double> solve(double y, double x, std::vector<double> obs)\n{\n  Solver<F> solver;\n  for(double o : obs)\n    solver.add(F(o),&x,&y);\n  solver.solve(DENSE,minimal_verbose());\n  return std::make_tuple(x,y);\n}\n\nstd::ostream& operator<<(std::ostream& o, std::tuple<double,double> tuple)\n{\n  return o << std::get<0>(tuple) << \",\" << std::get<1>(tuple) << std::endl;\n}\n\nstruct None{};\n\nint main()\n{\n  std::vector<double> obs = {0.1,0.2,-0.05,-0.15,0.0};\n  std::cout << solve<F<None>>(1,1,obs) << std::endl;\n  std::cout << solve<F<NumericCentral>>(1,1,obs) << std::endl;\n  std::cout << solve<F<NumericForward>>(1,1,obs) << std::endl;\n  std::cout << solve<F<Analytical>>(1,1,obs) << std::endl;\n\n  #if __cplusplus > 201103L\n  std::cout << solve<F<Automatic>>(1,1,obs) << std::endl;\n  #endif\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "96b3627be75f3185ab2792b5aa09b5fbcbc063b5", "size": 1839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/derivatives.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/derivatives.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/derivatives.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": 25.5416666667, "max_line_length": 94, "alphanum_fraction": 0.6427406199, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.63341026367784, "lm_q1q2_score": 0.5133656534470452}}
{"text": "/*\n *  (C) Copyright Nick Thompson 2018.\n *  Use, modification and distribution are subject to the\n *  Boost Software License, Version 1.0. (See accompanying file\n *  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"multiprecision_config.hpp\"\n\n#ifndef DISABLE_MP_TESTS\n#include <boost/integer/extended_euclidean.hpp>\n#include <boost/cstdint.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::extended_euclidean;\nusing boost::integer::gcd;\n\ntemplate<class Z>\nvoid test_extended_euclidean()\n{\n    // Stress test:\n    //Z max_arg = std::numeric_limits<Z>::max();\n    Z max_arg = 500;\n    for (Z m = max_arg; m > 0; --m)\n    {\n        for (Z n = max_arg; n > 0; --n)\n        {\n            boost::integer::euclidean_result_t<Z> u = extended_euclidean(m, n);\n            int256_t gcdmn = gcd(m, n);\n            int256_t x = u.x;\n            int256_t y = u.y;\n            BOOST_TEST_EQ(u.gcd, gcdmn);\n            BOOST_TEST_EQ(m*x + n*y, gcdmn);\n        }\n    }\n}\n\n\n\nint main()\n{\n    test_extended_euclidean<boost::int16_t>();\n    test_extended_euclidean<boost::int32_t>();\n    test_extended_euclidean<boost::int64_t>();\n    test_extended_euclidean<int128_t>();\n\n    return boost::report_errors();;\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "8299a25920501d1fb1012eef9f60850015155fd1", "size": 1452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/integer/test/extended_euclidean_test.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/integer/test/extended_euclidean_test.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/integer/test/extended_euclidean_test.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": 24.6101694915, "max_line_length": 79, "alphanum_fraction": 0.6590909091, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5133656422297741}}
{"text": "#include <boost/algorithm/hex.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#include <nil/crypto3/zk/components/blueprint.hpp>\n#include <nil/crypto3/zk/components/blueprint_variable.hpp>\n\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/marshalling.hpp>\n\n#include <nil/crypto3/zk/snark/algorithms/generate.hpp>\n#include <nil/crypto3/zk/snark/algorithms/verify.hpp>\n#include <nil/crypto3/zk/snark/algorithms/prove.hpp>\n\n#include \"./types.h\"\n#include \"./utils.cpp\"\n#include \"./circuit.h\"\n\nusing namespace std;\n\nusing namespace nil::crypto3::zk::components;\nusing namespace nil::crypto3::zk::snark;\n\n\nushort INVALID_PROOF_RETURN_CODE = 200;\n\n\nint setup_keys(boost::filesystem::path pk_path, boost::filesystem::path vk_path) {\n    blueprint<field_type> bp;\n    LocationCircuit circuit(bp);\n    circuit.generate_r1cs_constraints(bp);\n\n    cout << \"Blueprint size: \" << bp.num_variables() << endl;\n    cout << \"Generating constraint system...\" << endl;\n    const r1cs_constraint_system<field_type> constraint_system = bp.get_constraint_system();\n    cout << \"Number of R1CS constraints: \" << constraint_system.num_constraints() << endl;\n\n    cout << \"Generating keypair...\" << endl;\n    scheme_type::keypair_type keypair = generate<scheme_type>(constraint_system);\n\n    cout << \"Saving proving key to a file \" << pk_path<< endl;\n    save_proving_key(keypair.first, pk_path);\n\n    cout << \"Saving verification key to a file \" << vk_path << endl;\n    save_verification_key(keypair.second, vk_path);\n\n    return 0;\n}\n\nint create_proof(boost::filesystem::path pk_path, boost::filesystem::path proof_path, boost::filesystem::path pi_path,float minLat, float maxLat, float minLng, float maxLng, float posLat, float posLng) {\n    cout << \"Loading proving key from a file \" << pk_path << endl;\n    typename scheme_type::proving_key_type pk = load_proving_key(pk_path);\n\n    blueprint<field_type> bp;\n    LocationCircuit circuit(bp);\n    cout << \"Generating constraint system...\" << endl;\n    circuit.generate_r1cs_constraints(bp);\n    cout << \"Generating witness...\" << endl;\n    circuit.generate_r1cs_witness(bp, minLat, maxLat, minLng, maxLng, posLat, posLng);\n\n    cout << \"Blueprint is satisfied: \" << bp.is_satisfied() << endl;\n    if (!bp.is_satisfied()) {\n        return INVALID_PROOF_RETURN_CODE;\n    }\n\n    cout << \"Generating proof...\" << endl;\n    const scheme_type::proof_type proof = prove<scheme_type>(pk, bp.primary_input(), bp.auxiliary_input());\n\n    cout << \"Saving proof to file \" << proof_path << endl;\n    save_proof(proof, proof_path);\n\n    cout << \"Saving primary input to file \" << pi_path << endl;\n    save_primary_input(bp.primary_input(), pi_path);\n    return 0;\n}\n\nint verify_proof(boost::filesystem::path proof_path, boost::filesystem::path vk_path, boost::filesystem::path pi_path) {\n    cout << \"Loading proof from a file \" << proof_path << endl;\n    typename scheme_type::proof_type proof = load_proof(proof_path);\n\n    cout << \"Loading primary input from a file \" << pi_path << endl;\n    r1cs_primary_input<field_type> input = load_primary_input(pi_path);\n\n    cout << \"Loading verification key from a file \" << vk_path << endl;\n    typename scheme_type::verification_key_type vk = load_verification_key(vk_path);\n\n    // verify\n    using basic_proof_system = r1cs_gg_ppzksnark<curve_type>;\n    const bool verified = verify<basic_proof_system>(vk, input, proof);\n    cout << \"Verification status: \" << verified << endl;\n\n    return verified ? 0 : INVALID_PROOF_RETURN_CODE;\n}\n\nint main(int argc, char *argv[]) {\n    float minLat, maxLat, minLng, maxLng, posLat, posLng;\n    boost::filesystem::path pk_path, vk_path, proof_path, pi_path;\n    // bool hexFlag;\n\n    boost::program_options::options_description options(\"CLI Proof Generator\");\n    options.add_options()\n    // (\"hex,h\", boost::program_options::bool_switch(&hexFlag), \"print only hex proof to output\")\n    (\"minLat,minLat\", boost::program_options::value<float>(&minLat)->default_value(0))\n    (\"maxLat,maxLat\", boost::program_options::value<float>(&maxLat)->default_value(0))\n    (\"minLng,minLng\", boost::program_options::value<float>(&minLng)->default_value(0))\n    (\"maxLng,maxLng\", boost::program_options::value<float>(&maxLng)->default_value(0))\n    (\"posLat,posLat\", boost::program_options::value<float>(&posLat)->default_value(0))\n    (\"posLng,posLng\", boost::program_options::value<float>(&posLng)->default_value(0))\n    (\"proving-key-path,pk\", boost::program_options::value<boost::filesystem::path>(&pk_path)->default_value(\"proving.key\"))\n    (\"verification-key-path,vk\", boost::program_options::value<boost::filesystem::path>(&vk_path)->default_value(\"verification.key\"))\n    (\"proof-path,p\", boost::program_options::value<boost::filesystem::path>(&proof_path)->default_value(\"proof\"))\n    (\"primary-input-path,pi\", boost::program_options::value<boost::filesystem::path>(&pi_path)->default_value(\"primary.input\"));\n\n    boost::program_options::variables_map vm;\n    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options).run(), vm);\n    boost::program_options::notify(vm);\n\n    cout << setprecision(16);\n\n    if (!argv[1]) {\n        cout << \"Please select a command: [setup/prove/verify]\" << endl;\n        return 0;\n    }\n    else if (string(argv[1]) == \"setup\") {\n        // Generate proving.key & verification.key\n        return setup_keys(pk_path, vk_path);\n    } else if (string(argv[1]) == \"prove\") {\n        // Generate and  save proof and primary_input to file\n        return create_proof(pk_path, proof_path, pi_path, minLat, maxLat, minLng, maxLng, posLat, posLng);\n    } else if (string(argv[1]) == \"verify\") {\n        // Check the status of the proof\n        return verify_proof(proof_path, pi_path, vk_path);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "b44b3aedbe969cfbd501c4c9f1b5bc06ce157b1d", "size": 5901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "zkp/bin/main.cpp", "max_stars_repo_name": "idealatom/zkp-covid-tracker", "max_stars_repo_head_hexsha": "18929551b93e3c274f4deffd7a7b6202aca8a962", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-03T09:16:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T09:16:00.000Z", "max_issues_repo_path": "zkp/bin/main.cpp", "max_issues_repo_name": "idealatom/zkp-covid-tracker", "max_issues_repo_head_hexsha": "18929551b93e3c274f4deffd7a7b6202aca8a962", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "zkp/bin/main.cpp", "max_forks_repo_name": "idealatom/zkp-covid-tracker", "max_forks_repo_head_hexsha": "18929551b93e3c274f4deffd7a7b6202aca8a962", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-30T05:23:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:45:19.000Z", "avg_line_length": 43.0729927007, "max_line_length": 203, "alphanum_fraction": 0.7053041857, "num_tokens": 1471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5133550628257445}}
{"text": "#define EIGEN_RUNTIME_NO_MALLOC\n#include <Eigen/Core>\n#include <catch2/catch.hpp>\n#include \"ear/dsp/delay_buffer.hpp\"\n#include \"ear/dsp/ptr_adapter.hpp\"\n#include \"ear/helpers/assert.hpp\"\n\nusing namespace ear;\nusing namespace ear::dsp;\n\nTEST_CASE(\"delay_buffer\") {\n  int delay = 128;\n  DelayBuffer db(5, delay);\n\n  REQUIRE(db.get_delay() == delay);\n\n  Eigen::VectorXi block_sizes(3);\n  block_sizes << 64, 128, 256;\n\n  int testlen = block_sizes.sum();\n  Eigen::MatrixXf input = Eigen::MatrixXf::Random(testlen, 5);\n  Eigen::MatrixXf output = Eigen::MatrixXf::Zero(testlen, 5);\n  Eigen::MatrixXf expected_output = Eigen::MatrixXf::Zero(testlen, 5);\n\n  expected_output(Eigen::seqN(delay, testlen - delay), Eigen::all) =\n      input(Eigen::seqN(0, testlen - delay), Eigen::all);\n\n  PtrAdapter in_ptrs(5), out_ptrs(5);\n\n  Eigen::internal::set_is_malloc_allowed(false);\n  int offset = 0;\n  for (auto &block_size : block_sizes) {\n    auto block = Eigen::seqN(offset, block_size);\n    in_ptrs.set_eigen(input(block, Eigen::all));\n    out_ptrs.set_eigen(output(block, Eigen::all));\n    db.process(block_size, in_ptrs.ptrs(), out_ptrs.ptrs());\n    offset += block_size;\n  }\n  Eigen::internal::set_is_malloc_allowed(true);\n\n  REQUIRE(output == expected_output);\n}\n\nTEST_CASE(\"single_channel\") {\n  int delay = 128;\n  DelayBuffer db(1, delay);\n\n  int testlen = 512;\n  Eigen::VectorXf input = Eigen::VectorXf::Random(testlen);\n  Eigen::VectorXf output = Eigen::VectorXf::Zero(testlen);\n  Eigen::VectorXf expected_output = Eigen::VectorXf::Zero(testlen);\n\n  expected_output(Eigen::seqN(delay, testlen - delay)) =\n      input(Eigen::seqN(0, testlen - delay));\n\n  PtrAdapter in_ptrs(1), out_ptrs(1);\n\n  Eigen::internal::set_is_malloc_allowed(false);\n  in_ptrs.set_eigen(input);\n  out_ptrs.set_eigen(output);\n  db.process(testlen, in_ptrs.ptrs(), out_ptrs.ptrs());\n  Eigen::internal::set_is_malloc_allowed(true);\n\n  REQUIRE(output == expected_output);\n}\n", "meta": {"hexsha": "c307fa664ed622dcfc6964c417e38380e57191f8", "size": 1935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/delay_buffer_tests.cpp", "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": "tests/delay_buffer_tests.cpp", "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": "tests/delay_buffer_tests.cpp", "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": 29.3181818182, "max_line_length": 70, "alphanum_fraction": 0.7090439276, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.513355051385763}}
{"text": "/**\n * \\ file AttackReleaseHysteresisFilter.cpp\n */\n\n#include <ATK/Dynamic/AttackReleaseHysteresisFilter.h>\n\n#include <ATK/Core/InPointerFilter.h>\n#include <ATK/Core/OutPointerFilter.h>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/scoped_array.hpp>\n\n#define PROCESSSIZE (1024*64)\n\nBOOST_AUTO_TEST_CASE( AttackReleaseHysteresisFilter_triangle_test )\n{\n  boost::scoped_array<float> data(new float[PROCESSSIZE]);\n  for(int64_t i = 0; i < PROCESSSIZE/2; ++i)\n  {\n    data[i] = i / 48000;\n  }\n  for(int64_t i = 0; i < PROCESSSIZE/2; ++i)\n  {\n    data[PROCESSSIZE/2 + i] = (PROCESSSIZE/2 - i) / 48000;\n  }\n  \n  ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);\n  generator.set_output_sampling_rate(48000);\n\n  boost::scoped_array<float> outdata(new float[PROCESSSIZE]);\n\n  ATK::AttackReleaseHysteresisFilter<float> filter(1);\n  filter.set_attack(std::exp(-1./(48000 * 1e-3)));\n  filter.set_release(std::exp(-1./(48000 * 100e-3)));\n  filter.set_input_sampling_rate(48000);\n  filter.set_input_port(0, &generator, 0);\n\n  ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);\n  output.set_input_sampling_rate(48000);\n  output.set_input_port(0, &filter, 0);\n\n  output.process(PROCESSSIZE);\n  \n  for(int64_t i = 0; i < PROCESSSIZE/2; ++i)\n  {\n    BOOST_REQUIRE_GE(data[i], outdata[i]);\n  }\n  for(int64_t i = 0; i < PROCESSSIZE/2; ++i)\n  {\n    BOOST_REQUIRE_GE(outdata[PROCESSSIZE/2+i], outdata[PROCESSSIZE/2+i-1]);\n  }\n}\n\n#define CUSTOMPROCESSSIZE 7\n\nBOOST_AUTO_TEST_CASE( AttackReleaseHysteresisFilter_release_custom_test )\n{\n  float data[] = {0., 1., .5, .4, .3, .2, .1};\n  float target[] = {0., 1., 1., .46, .46, .226, .1126};\n  \n  ATK::InPointerFilter<float> generator(data, 1, CUSTOMPROCESSSIZE, false);\n  generator.set_output_sampling_rate(48000);\n  \n  boost::scoped_array<float> outdata(new float[CUSTOMPROCESSSIZE]);\n  \n  ATK::AttackReleaseHysteresisFilter<float> filter(1);\n  filter.set_attack(0);\n  filter.set_release(.1);\n  filter.set_release_hysteresis(.5);\n  filter.set_input_sampling_rate(48000);\n  filter.set_input_port(0, &generator, 0);\n  \n  ATK::OutPointerFilter<float> output(outdata.get(), 1, CUSTOMPROCESSSIZE, false);\n  output.set_input_sampling_rate(48000);\n  output.set_input_port(0, &filter, 0);\n  \n  output.process(CUSTOMPROCESSSIZE);\n  \n  for(int64_t i = 0; i < CUSTOMPROCESSSIZE; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(target[i], outdata[i], .001);\n  }\n}\n", "meta": {"hexsha": "2f99aea34577a1b8f6d925e0951917b6664a7b11", "size": 2519, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Dynamic/AttackReleaseHysteresisFilter.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": "tests/Dynamic/AttackReleaseHysteresisFilter.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": "tests/Dynamic/AttackReleaseHysteresisFilter.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": 28.625, "max_line_length": 82, "alphanum_fraction": 0.7113934101, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.5133550460838223}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\r\n// Copyright (C) 2009 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/SVD>\r\n\r\ntemplate<typename MatrixType, typename JacobiScalar>\r\nvoid jacobi(const MatrixType& m = MatrixType())\r\n{\r\n  Index rows = m.rows();\r\n  Index cols = m.cols();\r\n\r\n  enum {\r\n    RowsAtCompileTime = MatrixType::RowsAtCompileTime,\r\n    ColsAtCompileTime = MatrixType::ColsAtCompileTime\r\n  };\r\n\r\n  typedef Matrix<JacobiScalar, 2, 1> JacobiVector;\r\n\r\n  const MatrixType a(MatrixType::Random(rows, cols));\r\n\r\n  JacobiVector v = JacobiVector::Random().normalized();\r\n  JacobiScalar c = v.x(), s = v.y();\r\n  JacobiRotation<JacobiScalar> rot(c, s);\r\n\r\n  {\r\n    Index p = internal::random<Index>(0, rows-1);\r\n    Index q;\r\n    do {\r\n      q = internal::random<Index>(0, rows-1);\r\n    } while (q == p);\r\n\r\n    MatrixType b = a;\r\n    b.applyOnTheLeft(p, q, rot);\r\n    VERIFY_IS_APPROX(b.row(p), c * a.row(p) + numext::conj(s) * a.row(q));\r\n    VERIFY_IS_APPROX(b.row(q), -s * a.row(p) + numext::conj(c) * a.row(q));\r\n  }\r\n\r\n  {\r\n    Index p = internal::random<Index>(0, cols-1);\r\n    Index q;\r\n    do {\r\n      q = internal::random<Index>(0, cols-1);\r\n    } while (q == p);\r\n\r\n    MatrixType b = a;\r\n    b.applyOnTheRight(p, q, rot);\r\n    VERIFY_IS_APPROX(b.col(p), c * a.col(p) - s * a.col(q));\r\n    VERIFY_IS_APPROX(b.col(q), numext::conj(s) * a.col(p) + numext::conj(c) * a.col(q));\r\n  }\r\n}\r\n\r\nvoid test_jacobi()\r\n{\r\n  for(int i = 0; i < g_repeat; i++) {\r\n    CALL_SUBTEST_1(( jacobi<Matrix3f, float>() ));\r\n    CALL_SUBTEST_2(( jacobi<Matrix4d, double>() ));\r\n    CALL_SUBTEST_3(( jacobi<Matrix4cf, float>() ));\r\n    CALL_SUBTEST_3(( jacobi<Matrix4cf, std::complex<float> >() ));\r\n\r\n    int r = internal::random<int>(2, internal::random<int>(1,EIGEN_TEST_MAX_SIZE)/2),\r\n        c = internal::random<int>(2, internal::random<int>(1,EIGEN_TEST_MAX_SIZE)/2);\r\n    CALL_SUBTEST_4(( jacobi<MatrixXf, float>(MatrixXf(r,c)) ));\r\n    CALL_SUBTEST_5(( jacobi<MatrixXcd, double>(MatrixXcd(r,c)) ));\r\n    CALL_SUBTEST_5(( jacobi<MatrixXcd, std::complex<double> >(MatrixXcd(r,c)) ));\r\n    // complex<float> is really important to test as it is the only way to cover conjugation issues in certain unaligned paths\r\n    CALL_SUBTEST_6(( jacobi<MatrixXcf, float>(MatrixXcf(r,c)) ));\r\n    CALL_SUBTEST_6(( jacobi<MatrixXcf, std::complex<float> >(MatrixXcf(r,c)) ));\r\n    \r\n    TEST_SET_BUT_UNUSED_VARIABLE(r);\r\n    TEST_SET_BUT_UNUSED_VARIABLE(c);\r\n  }\r\n}\r\n", "meta": {"hexsha": "11b3c689d42feae0f3130561f4c6dfd7e1a5b069", "size": 2805, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/test/jacobi.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/test/jacobi.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/test/jacobi.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 34.6296296296, "max_line_length": 127, "alphanum_fraction": 0.6342245989, "num_tokens": 848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5133363329057229}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_INC_BETA_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_INC_BETA_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/err.hpp>\n#include <stan/math/prim/scal/fun/boost_policy.hpp>\n#include <boost/math/special_functions/beta.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * The normalized incomplete beta function of a, b, with outcome x.\n *\n * Used to compute the cumulative density function for the beta\n * distribution.\n *\n * @param a Shape parameter a >= 0; a and b can't both be 0\n * @param b Shape parameter b >= 0\n * @param x Random variate. 0 <= x <= 1\n * @throws if constraints are violated or if any argument is NaN\n * @return The normalized incomplete beta function.\n */\ninline double inc_beta(double a, double b, double x) {\n  check_not_nan(\"inc_beta\", \"a\", a);\n  check_not_nan(\"inc_beta\", \"b\", b);\n  check_not_nan(\"inc_beta\", \"x\", x);\n  return boost::math::ibeta(a, b, x, boost_policy_t());\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "d5444ccc576df1330fd67038e2771f392cba0a3f", "size": 986, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/inc_beta.hpp", "max_stars_repo_name": "christophernhill/math", "max_stars_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "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": "stan/math/prim/scal/fun/inc_beta.hpp", "max_issues_repo_name": "christophernhill/math", "max_issues_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/scal/fun/inc_beta.hpp", "max_forks_repo_name": "christophernhill/math", "max_forks_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0, "max_line_length": 67, "alphanum_fraction": 0.7170385396, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.513324650729088}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2013 Alec Jacobson <alecjacobson@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 \"massmatrix.h\"\n#include \"normalize_row_sums.h\"\n#include \"sparse.h\"\n#include \"doublearea.h\"\n#include \"repmat.h\"\n#include <Eigen/Geometry>\n#include <iostream>\n\ntemplate <typename DerivedV, typename DerivedF, typename Scalar>\nIGL_INLINE void igl::massmatrix(\n  const Eigen::MatrixBase<DerivedV> & V, \n  const Eigen::MatrixBase<DerivedF> & F, \n  const MassMatrixType type,\n  Eigen::SparseMatrix<Scalar>& M)\n{\n  using namespace Eigen;\n  using namespace std;\n\n  const int n = V.rows();\n  const int m = F.rows();\n  const int simplex_size = F.cols();\n\n  MassMatrixType eff_type = type;\n  // Use voronoi of for triangles by default, otherwise barycentric\n  if(type == MASSMATRIX_TYPE_DEFAULT)\n  {\n    eff_type = (simplex_size == 3?MASSMATRIX_TYPE_VORONOI:MASSMATRIX_TYPE_BARYCENTRIC);\n  }\n\n  // Not yet supported\n  assert(type!=MASSMATRIX_TYPE_FULL);\n\n  Matrix<int,Dynamic,1> MI;\n  Matrix<int,Dynamic,1> MJ;\n  Matrix<Scalar,Dynamic,1> MV;\n  if(simplex_size == 3)\n  {\n    // Triangles\n    // edge lengths numbered same as opposite vertices\n    Matrix<Scalar,Dynamic,3> l(m,3);\n    // loop over faces\n    for(int i = 0;i<m;i++)\n    {\n      l(i,0) = (V.row(F(i,1))-V.row(F(i,2))).norm();\n      l(i,1) = (V.row(F(i,2))-V.row(F(i,0))).norm();\n      l(i,2) = (V.row(F(i,0))-V.row(F(i,1))).norm();\n    }\n    Matrix<Scalar,Dynamic,1> dblA;\n    doublearea(l,dblA);\n\n    switch(eff_type)\n    {\n      case MASSMATRIX_TYPE_BARYCENTRIC:\n        // diagonal entries for each face corner\n        MI.resize(m*3,1); MJ.resize(m*3,1); MV.resize(m*3,1);\n        MI.block(0*m,0,m,1) = F.col(0);\n        MI.block(1*m,0,m,1) = F.col(1);\n        MI.block(2*m,0,m,1) = F.col(2);\n        MJ = MI;\n        repmat(dblA,3,1,MV);\n        MV.array() /= 6.0;\n        break;\n      case MASSMATRIX_TYPE_VORONOI:\n        {\n          // diagonal entries for each face corner\n          // http://www.alecjacobson.com/weblog/?p=874\n          MI.resize(m*3,1); MJ.resize(m*3,1); MV.resize(m*3,1);\n          MI.block(0*m,0,m,1) = F.col(0);\n          MI.block(1*m,0,m,1) = F.col(1);\n          MI.block(2*m,0,m,1) = F.col(2);\n          MJ = MI;\n\n          // Holy shit this needs to be cleaned up and optimized\n          Matrix<Scalar,Dynamic,3> cosines(m,3);\n          cosines.col(0) = \n            (l.col(2).array().pow(2)+l.col(1).array().pow(2)-l.col(0).array().pow(2))/(l.col(1).array()*l.col(2).array()*2.0);\n          cosines.col(1) = \n            (l.col(0).array().pow(2)+l.col(2).array().pow(2)-l.col(1).array().pow(2))/(l.col(2).array()*l.col(0).array()*2.0);\n          cosines.col(2) = \n            (l.col(1).array().pow(2)+l.col(0).array().pow(2)-l.col(2).array().pow(2))/(l.col(0).array()*l.col(1).array()*2.0);\n          Matrix<Scalar,Dynamic,3> barycentric = cosines.array() * l.array();\n          normalize_row_sums(barycentric,barycentric);\n          Matrix<Scalar,Dynamic,3> partial = barycentric;\n          partial.col(0).array() *= dblA.array() * 0.5;\n          partial.col(1).array() *= dblA.array() * 0.5;\n          partial.col(2).array() *= dblA.array() * 0.5;\n          Matrix<Scalar,Dynamic,3> quads(partial.rows(),partial.cols());\n          quads.col(0) = (partial.col(1)+partial.col(2))*0.5;\n          quads.col(1) = (partial.col(2)+partial.col(0))*0.5;\n          quads.col(2) = (partial.col(0)+partial.col(1))*0.5;\n\n          quads.col(0) = (cosines.col(0).array()<0).select( 0.25*dblA,quads.col(0));\n          quads.col(1) = (cosines.col(0).array()<0).select(0.125*dblA,quads.col(1));\n          quads.col(2) = (cosines.col(0).array()<0).select(0.125*dblA,quads.col(2));\n\n          quads.col(0) = (cosines.col(1).array()<0).select(0.125*dblA,quads.col(0));\n          quads.col(1) = (cosines.col(1).array()<0).select(0.25*dblA,quads.col(1));\n          quads.col(2) = (cosines.col(1).array()<0).select(0.125*dblA,quads.col(2));\n\n          quads.col(0) = (cosines.col(2).array()<0).select(0.125*dblA,quads.col(0));\n          quads.col(1) = (cosines.col(2).array()<0).select(0.125*dblA,quads.col(1));\n          quads.col(2) = (cosines.col(2).array()<0).select( 0.25*dblA,quads.col(2));\n\n          MV.block(0*m,0,m,1) = quads.col(0);\n          MV.block(1*m,0,m,1) = quads.col(1);\n          MV.block(2*m,0,m,1) = quads.col(2);\n          \n          break;\n        }\n      case MASSMATRIX_TYPE_FULL:\n        assert(false && \"Implementation incomplete\");\n        break;\n      default:\n        assert(false && \"Unknown Mass matrix eff_type\");\n    }\n\n  }else if(simplex_size == 4)\n  {\n    assert(V.cols() == 3);\n    assert(eff_type == MASSMATRIX_TYPE_BARYCENTRIC);\n    MI.resize(m*4,1); MJ.resize(m*4,1); MV.resize(m*4,1);\n    MI.block(0*m,0,m,1) = F.col(0);\n    MI.block(1*m,0,m,1) = F.col(1);\n    MI.block(2*m,0,m,1) = F.col(2);\n    MI.block(3*m,0,m,1) = F.col(3);\n    MJ = MI;\n    // loop over tets\n    for(int i = 0;i<m;i++)\n    {\n      // http://en.wikipedia.org/wiki/Tetrahedron#Volume\n      Matrix<Scalar,3,1> v0m3 = V.row(F(i,0)) - V.row(F(i,3));\n      Matrix<Scalar,3,1> v1m3 = V.row(F(i,1)) - V.row(F(i,3));\n      Matrix<Scalar,3,1> v2m3 = V.row(F(i,2)) - V.row(F(i,3));\n      Scalar v = fabs(v0m3.dot(v1m3.cross(v2m3)))/6.0;\n      MV(i+0*m) = v/4.0;\n      MV(i+1*m) = v/4.0;\n      MV(i+2*m) = v/4.0;\n      MV(i+3*m) = v/4.0;\n    }\n  }else\n  {\n    // Unsupported simplex size\n    assert(false && \"Unsupported simplex size\");\n  }\n  sparse(MI,MJ,MV,n,n,M);\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\n// generated by autoexplicit.sh\ntemplate void igl::massmatrix<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 4, 0, -1, 4>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 4, 0, -1, 4> > const&, igl::MassMatrixType, Eigen::SparseMatrix<double, 0, int>&);\n// generated by autoexplicit.sh\ntemplate void igl::massmatrix<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, igl::MassMatrixType, Eigen::SparseMatrix<double, 0, int>&);\ntemplate void igl::massmatrix<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, igl::MassMatrixType, Eigen::SparseMatrix<double, 0, int>&);\ntemplate void igl::massmatrix<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, igl::MassMatrixType, Eigen::SparseMatrix<double, 0, int>&);\n#endif\n", "meta": {"hexsha": "a88a4d6d0c06378a88e1e7eb6b6f7372f9a38a9f", "size": 7055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/SprueEngine/Libs/igl/massmatrix.cpp", "max_stars_repo_name": "Qt-Widgets/TexGraph", "max_stars_repo_head_hexsha": "8fe72cea1afcf5e235c810003bf4ee062bb3fc13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2017-04-07T22:49:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T13:59:20.000Z", "max_issues_repo_path": "Source/SprueEngine/Libs/igl/massmatrix.cpp", "max_issues_repo_name": "Qt-Widgets/TexGraph", "max_issues_repo_head_hexsha": "8fe72cea1afcf5e235c810003bf4ee062bb3fc13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-04T22:39:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-05T21:02:47.000Z", "max_forks_repo_path": "Source/SprueEngine/Libs/igl/massmatrix.cpp", "max_forks_repo_name": "Qt-Widgets/TexGraph", "max_forks_repo_head_hexsha": "8fe72cea1afcf5e235c810003bf4ee062bb3fc13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-03-11T19:26:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T07:17:10.000Z", "avg_line_length": 43.0182926829, "max_line_length": 313, "alphanum_fraction": 0.5880935507, "num_tokens": 2482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5133246507290878}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2014 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#include <boost/program_options.hpp>\n#include <boost/variant.hpp>\n\n#include <gudhi/Alpha_complex_3d.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Persistent_cohomology.h>\n#include <gudhi/Points_3D_off_io.h>\n\n#include <fstream>\n#include <string>\n#include <vector>\n#include <limits>  // for numeric_limits<>\n\n// gudhi type definition\nusing Simplex_tree = Gudhi::Simplex_tree<Gudhi::Simplex_tree_options_fast_persistence>;\nusing Filtration_value = Simplex_tree::Filtration_value;\nusing Persistent_cohomology =\n    Gudhi::persistent_cohomology::Persistent_cohomology<Simplex_tree, Gudhi::persistent_cohomology::Field_Zp>;\n\nvoid program_options(int argc, char *argv[], std::string &off_file_points, bool &exact, bool &safe,\n                     std::string &weight_file, std::string &cuboid_file, std::string &output_file_diag,\n                     Filtration_value &alpha_square_max_value, int &coeff_field_characteristic,\n                     Filtration_value &min_persistence);\n\nbool read_weight_file(const std::string &weight_file, std::vector<double> &weights) {\n  // Read weights information from file\n  std::ifstream weights_ifstr(weight_file);\n  if (weights_ifstr.good()) {\n    double weight = 0.0;\n    // Attempt read the weight in a double format, return false if it fails\n    while (weights_ifstr >> weight) {\n      weights.push_back(weight);\n    }\n  } else {\n    return false;\n  }\n  return true;\n}\n\nbool read_cuboid_file(const std::string &cuboid_file, double &x_min, double &y_min, double &z_min, double &x_max,\n                      double &y_max, double &z_max) {\n  // Read weights information from file\n  std::ifstream iso_cuboid_str(cuboid_file);\n  if (iso_cuboid_str.is_open()) {\n    if (!(iso_cuboid_str >> x_min >> y_min >> z_min >> x_max >> y_max >> z_max)) {\n      return false;\n    }\n  } else {\n    return false;\n  }\n  return true;\n}\n\ntemplate <typename AlphaComplex3d>\nstd::vector<typename AlphaComplex3d::Bare_point_3> read_off(const std::string &off_file_points) {\n  // Read the OFF file (input file name given as parameter) and triangulate points\n  Gudhi::Points_3D_off_reader<typename AlphaComplex3d::Bare_point_3> off_reader(off_file_points);\n  // Check the read operation was correct\n  if (!off_reader.is_valid()) {\n    std::cerr << \"Unable to read OFF file \" << off_file_points << std::endl;\n    exit(-1);\n  }\n  return off_reader.get_point_cloud();\n}\n\nint main(int argc, char **argv) {\n  std::string off_file_points;\n  std::string weight_file;\n  std::string cuboid_file;\n  std::string output_file_diag;\n  Filtration_value alpha_square_max_value = 0.;\n  int coeff_field_characteristic = 0;\n  Filtration_value min_persistence = 0.;\n  bool exact_version = false;\n  bool fast_version = false;\n  bool weighted_version = false;\n  bool periodic_version = false;\n\n  program_options(argc, argv, off_file_points, exact_version, fast_version, weight_file, cuboid_file, output_file_diag,\n                  alpha_square_max_value, coeff_field_characteristic, min_persistence);\n\n  std::vector<double> weights;\n  if (weight_file != std::string()) {\n    if (!read_weight_file(weight_file, weights)) {\n      std::cerr << \"Unable to read weights file \" << weight_file << std::endl;\n      exit(-1);\n    }\n    weighted_version = true;\n  }\n\n  double x_min = 0., y_min = 0., z_min = 0., x_max = 0., y_max = 0., z_max = 0.;\n  std::ifstream iso_cuboid_str(argv[3]);\n  if (cuboid_file != std::string()) {\n    if (!read_cuboid_file(cuboid_file, x_min, y_min, z_min, x_max, y_max, z_max)) {\n      std::cerr << \"Unable to read cuboid file \" << cuboid_file << std::endl;\n      exit(-1);\n    }\n    periodic_version = true;\n  }\n\n  Gudhi::alpha_complex::complexity complexity = Gudhi::alpha_complex::complexity::SAFE;\n  if (exact_version) {\n    if (fast_version) {\n      std::cerr << \"You cannot set the exact and the fast version.\" << std::endl;\n      exit(-1);\n    }\n    complexity = Gudhi::alpha_complex::complexity::EXACT;\n  }\n  if (fast_version) {\n    complexity = Gudhi::alpha_complex::complexity::FAST;\n  }\n\n  Simplex_tree simplex_tree;\n\n  switch (complexity) {\n    case Gudhi::alpha_complex::complexity::FAST:\n      if (weighted_version) {\n        if (periodic_version) {\n          using Alpha_complex_3d =\n              Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::FAST, true, true>;\n          auto points = read_off<Alpha_complex_3d>(off_file_points);\n          Alpha_complex_3d alpha_complex(points, weights, x_min, y_min, z_min, x_max, y_max, z_max);\n          alpha_complex.create_complex(simplex_tree, alpha_square_max_value);\n        } else {\n          using Alpha_complex_3d =\n              Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::FAST, true, false>;\n          auto points = read_off<Alpha_complex_3d>(off_file_points);\n          Alpha_complex_3d alpha_complex(points, weights);\n          alpha_complex.create_complex(simplex_tree, alpha_square_max_value);\n        }\n      } else {\n        if (periodic_version) {\n          using Alpha_complex_3d =\n              Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::FAST, false, true>;\n          auto points = read_off<Alpha_complex_3d>(off_file_points);\n          Alpha_complex_3d alpha_complex(points, x_min, y_min, z_min, x_max, y_max, z_max);\n          alpha_complex.create_complex(simplex_tree, alpha_square_max_value);\n        } else {\n          using Alpha_complex_3d =\n              Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::FAST, false, false>;\n          auto points = read_off<Alpha_complex_3d>(off_file_points);\n          Alpha_complex_3d alpha_complex(points);\n          alpha_complex.create_complex(simplex_tree, alpha_square_max_value);\n        }\n      }\n      break;\n    case Gudhi::alpha_complex::complexity::EXACT:\n      if (weighted_version) {\n        if (periodic_version) {\n          using Alpha_complex_3d =\n              Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::EXACT, true, true>;\n          auto points = read_off<Alpha_complex_3d>(off_file_points);\n          Alpha_complex_3d alpha_complex(points, weights, x_min, y_min, z_min, x_max, y_max, z_max);\n          alpha_complex.create_complex(simplex_tree, alpha_square_max_value);\n        } else {\n          using Alpha_complex_3d =\n              Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::EXACT, true, false>;\n          auto points = read_off<Alpha_complex_3d>(off_file_points);\n          Alpha_complex_3d alpha_complex(points, weights);\n          alpha_complex.create_complex(simplex_tree, alpha_square_max_value);\n        }\n      } else {\n        if (periodic_version) {\n          using Alpha_complex_3d =\n              Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::EXACT, false, true>;\n          auto points = read_off<Alpha_complex_3d>(off_file_points);\n          Alpha_complex_3d alpha_complex(points, x_min, y_min, z_min, x_max, y_max, z_max);\n          alpha_complex.create_complex(simplex_tree, alpha_square_max_value);\n        } else {\n          using Alpha_complex_3d =\n              Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::EXACT, false, false>;\n          auto points = read_off<Alpha_complex_3d>(off_file_points);\n          Alpha_complex_3d alpha_complex(points);\n          alpha_complex.create_complex(simplex_tree, alpha_square_max_value);\n        }\n      }\n      break;\n    case Gudhi::alpha_complex::complexity::SAFE:\n      if (weighted_version) {\n        if (periodic_version) {\n          using Alpha_complex_3d =\n              Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::SAFE, true, true>;\n          auto points = read_off<Alpha_complex_3d>(off_file_points);\n          Alpha_complex_3d alpha_complex(points, weights, x_min, y_min, z_min, x_max, y_max, z_max);\n          alpha_complex.create_complex(simplex_tree, alpha_square_max_value);\n        } else {\n          using Alpha_complex_3d =\n              Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::SAFE, true, false>;\n          auto points = read_off<Alpha_complex_3d>(off_file_points);\n          Alpha_complex_3d alpha_complex(points, weights);\n          alpha_complex.create_complex(simplex_tree, alpha_square_max_value);\n        }\n      } else {\n        if (periodic_version) {\n          using Alpha_complex_3d =\n              Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::SAFE, false, true>;\n          auto points = read_off<Alpha_complex_3d>(off_file_points);\n          Alpha_complex_3d alpha_complex(points, x_min, y_min, z_min, x_max, y_max, z_max);\n          alpha_complex.create_complex(simplex_tree, alpha_square_max_value);\n        } else {\n          using Alpha_complex_3d =\n              Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::SAFE, false, false>;\n          auto points = read_off<Alpha_complex_3d>(off_file_points);\n          Alpha_complex_3d alpha_complex(points);\n          alpha_complex.create_complex(simplex_tree, alpha_square_max_value);\n        }\n      }\n      break;\n    default:\n      std::cerr << \"Unknown complexity value \" << std::endl;\n      exit(-1);\n      break;\n  }\n\n  std::clog << \"Simplex_tree dim: \" << simplex_tree.dimension() << std::endl;\n  // Compute the persistence diagram of the complex\n  Persistent_cohomology pcoh(simplex_tree, true);\n  // initializes the coefficient field for homology\n  pcoh.init_coefficients(coeff_field_characteristic);\n\n  pcoh.compute_persistent_cohomology(min_persistence);\n\n  // Output the diagram in filediag\n  if (output_file_diag.empty()) {\n    pcoh.output_diagram();\n  } else {\n    std::clog << \"Result in file: \" << output_file_diag << std::endl;\n    std::ofstream out(output_file_diag);\n    pcoh.output_diagram(out);\n    out.close();\n  }\n\n  return 0;\n}\n\nvoid program_options(int argc, char *argv[], std::string &off_file_points, bool &exact, bool &fast,\n                     std::string &weight_file, std::string &cuboid_file, std::string &output_file_diag,\n                     Filtration_value &alpha_square_max_value, int &coeff_field_characteristic,\n                     Filtration_value &min_persistence) {\n  namespace po = boost::program_options;\n  po::options_description hidden(\"Hidden options\");\n  hidden.add_options()(\"input-file\", po::value<std::string>(&off_file_points),\n                       \"Name of file containing a point set. Format is one point per line:   X1 ... Xd \");\n\n  po::options_description visible(\"Allowed options\", 100);\n  visible.add_options()(\"help,h\", \"produce help message\")(\n      \"exact,e\", po::bool_switch(&exact),\n      \"To activate exact version of Alpha complex 3d (default is false, not available if fast is set)\")(\n      \"fast,f\", po::bool_switch(&fast),\n      \"To activate fast version of Alpha complex 3d (default is false, not available if exact is set)\")(\n      \"weight-file,w\", po::value<std::string>(&weight_file)->default_value(std::string()),\n      \"Name of file containing a point weights. Format is one weight per line:\\n  W1\\n  ...\\n  Wn \")(\n      \"cuboid-file,c\", po::value<std::string>(&cuboid_file),\n      \"Name of file describing the periodic domain. Format is:\\n  min_hx min_hy min_hz\\n  max_hx max_hy max_hz\")(\n      \"output-file,o\", po::value<std::string>(&output_file_diag)->default_value(std::string()),\n      \"Name of file in which the persistence diagram is written. Default print in std::clog\")(\n      \"max-alpha-square-value,r\",\n      po::value<Filtration_value>(&alpha_square_max_value)\n          ->default_value(std::numeric_limits<Filtration_value>::infinity()),\n      \"Maximal alpha square value for the Alpha complex construction.\")(\n      \"field-charac,p\", po::value<int>(&coeff_field_characteristic)->default_value(11),\n      \"Characteristic p of the coefficient field Z/pZ for computing homology.\")(\n      \"min-persistence,m\", po::value<Filtration_value>(&min_persistence),\n      \"Minimal lifetime of homology feature to be recorded. Default is 0. Enter a negative value to see zero length \"\n      \"intervals\");\n\n  po::positional_options_description pos;\n  pos.add(\"input-file\", 1);\n\n  po::options_description all;\n  all.add(visible).add(hidden);\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(all).positional(pos).run(), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\") || !vm.count(\"input-file\") || !vm.count(\"weight-file\")) {\n    std::clog << std::endl;\n    std::clog << \"Compute the persistent homology with coefficient field Z/pZ \\n\";\n    std::clog << \"of a 3D Alpha complex defined on a set of input points.\\n\";\n    std::clog << \"3D Alpha complex can be safe (by default) exact or fast, weighted and/or periodic\\n\\n\";\n    std::clog << \"The output diagram contains one bar per line, written with the convention: \\n\";\n    std::clog << \"   p   dim b d \\n\";\n    std::clog << \"where dim is the dimension of the homological feature,\\n\";\n    std::clog << \"b and d are respectively the birth and death of the feature and \\n\";\n    std::clog << \"p is the characteristic of the field Z/pZ used for homology coefficients.\\n\\n\";\n\n    std::clog << \"Usage: \" << argv[0] << \" [options] input-file weight-file\\n\\n\";\n    std::clog << visible << std::endl;\n    exit(-1);\n  }\n}\n", "meta": {"hexsha": "91899040b85e14003bcd53d1b705f4491fe377f8", "size": 13656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Alpha_complex/utilities/alpha_complex_3d_persistence.cpp", "max_stars_repo_name": "m0baxter/gudhi-devel", "max_stars_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "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/Alpha_complex/utilities/alpha_complex_3d_persistence.cpp", "max_issues_repo_name": "m0baxter/gudhi-devel", "max_issues_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "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/Alpha_complex/utilities/alpha_complex_3d_persistence.cpp", "max_forks_repo_name": "m0baxter/gudhi-devel", "max_forks_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "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": 45.0693069307, "max_line_length": 119, "alphanum_fraction": 0.6816783831, "num_tokens": 3506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5133143360462538}}
{"text": "\ufeff////////////////////////////////////////////////////////////////////\n//\n// $Id: Param.hxx 2021/06/13 22:13:22 kanai Exp $\n//\n// Copyright (c) 2021 Takashi Kanai\n// Released under the MIT license\n//\n////////////////////////////////////////////////////////////////////\n\n#ifndef _PARAM_HXX\n#define _PARAM_HXX 1\n\n#include \"MyMesh.hxx\"\n\n#define EIGEN_NO_DEBUG\n\n#include <Eigen/Sparse>\n#include <Eigen/OrderingMethods>\ntypedef Eigen::Triplet<double> T;\n\n#define RECTANGLE 4\n\n#define SPARSELU 1\n#define BICGSTAB 2\nint sol = SPARSELU;\n\n#define COTW 1\n#define MVW  2\nint wei = MVW;\n\n#define SAVE_VERTEX 1\n#define SAVE_TEXCOORD 2\nint sav = SAVE_VERTEX;\n\n#if 0\n// Boundary vertex is fixed or not\nclass Fixed {\npublic:\n  Fixed(): isFixed_(false) {};\n  ~Fixed(){};\n  bool isFixed() const { return isFixed_; };\n  void setIsFixed( bool f ) { isFixed_ = f; };\n\nprivate:\n  bool isFixed_;\n};\n\nOpenMesh::VPropHandleT<Fixed> ffs;\n#endif\n\n#define FIXED_BOUNDARY 1\n#define NATURAL_BOUNDARY 2\nint bou = FIXED_BOUNDARY;\n\n// 0: vertex i, 1-N: its neighbor vertices j\nclass VVWeights {\n\npublic:\n\n  VVWeights(){};\n  ~VVWeights(){ w_.clear(); };\n\n  double w( int i ) { return w_[i]; };\n  int size() const { return w_.size(); };\n  std::vector<double>& ws() { return w_; };\n  void addWeight( double d ) { w_.push_back(d); };\n  // for orbifold\n  // void addWeight( double d, int pid ) {\n  //   w_.push_back(d);\n  //   param_id_.push_back( pid );\n  // };\n  void addParamID( MyMesh::VertexHandle& vh, int id ) {\n    param_id_.insert( make_pair( vh, id ) );\n  };\n  int param_id( MyMesh::VertexHandle& vh ) { return param_id_[vh]; };\n  bool setWeight( int i, double d ) {\n    if ( i >= (int) w_.size() ) return false;\n    w_[i] = d;\n    return true;\n  };\n  \n  void Print() {\n    cout << \"vvw\" << endl;\n    cout << \"weight size \" << size() << endl;\n    for ( int i = 0; i < w_.size(); ++i )\n      {\n        cout << w_[i] << endl;\n      }\n    cout << \"param_id \" << endl;\n    for ( std::map<MyMesh::VertexHandle,int>::iterator pi = param_id_.begin();\n          pi != param_id_.end(); ++pi )\n      {\n        cout << \"vt \" << pi->first.idx() << \" id \" << pi->second << endl;\n      }\n  };\n\nprivate:\n\n  std::vector<double> w_;\n  // parameter id for orbifold\n  // for OF_BOUNDARY vertex, values are 1 (true), or -1 (false)\n  std::map<MyMesh::VertexHandle,int> param_id_;\n  \n  \n\n};\n\n//////////////////////////////////////////////////////////////////////////////\n\n#include \"Orbifold.hxx\"\n\nclass Param {\n\npublic:\n  \n  double cotw( MyMesh::Point& p0, MyMesh::Point& p1, MyMesh::Point& p2 ) {\n    OMVector3d c1( p1 - p0 );\n    OMVector3d c2( p2 - p0 );\n    //double sin = OpenMesh::cross( c1, c2 ).length();\n    double sin = c1.cross( c2 ).norm();\n    //double angle = std::fabs( std::atan2(sin, OpenMesh::dot(c1, c2)) );\n    double angle = std::fabs( std::atan2(sin, c1.dot(c2)) );\n\n    // std::cout << \"\\tcot \" << 1.0 / std::tan( angle ) << \" tan \" << std::tan( M_PI_2 - angle ) << std::endl;\n    // if ( 1.0 / std::tan( angle ) - std::tan( M_PI_2 - angle ) > 1.0e-05 )\n    //   std::cout << \"diff!\" << std::endl;\n    return std::tan( M_PI_2 - angle );\n  };\n\n  double tan2w( MyMesh::Point& p0, MyMesh::Point& p1, MyMesh::Point& p2 ) {\n    OMVector3d c1( p1 - p0 );\n    OMVector3d c2( p2 - p0 );\n    //double sin = OpenMesh::cross( c1, c2 ).length();\n    double sin = c1.cross( c2 ).norm();\n    //double angle = std::fabs( std::atan2(sin, OpenMesh::dot(c1, c2)) );\n    double angle = std::fabs( std::atan2(sin, c1.dot(c2)) );\n\n    // std::cout << \"\\tcot \" << 1.0 / std::tan( angle ) << \" tan \" << std::tan( M_PI_2 - angle ) << std::endl;\n    // if ( 1.0 / std::tan( angle ) - std::tan( M_PI_2 - angle ) > 1.0e-05 )\n    //   std::cout << \"diff!\" << std::endl;\n    return std::tan( angle / 2.0 );\n  };\n\n  //\n  // A weight has to be doubled for natural boundary as described in [Karni 05]\n  //\n  double computeCotangentWeight( MyMesh& mesh, MyMesh::VertexIHalfedgeIter& vih_it ) {\n    OpenMesh::SmartHalfedgeHandle a( *vih_it );\n    return computeCotangentWeight( mesh, a );\n    //    return computeCotangentWeight( mesh, (OpenMesh::SmartHalfedgeHandle&) *vih_it );\n  };\n\n  double computeCotangentWeight( MyMesh& mesh, OpenMesh::SmartHalfedgeHandle& iheh ) {\n    // right face\n    //auto iheh( *vih_it ); // vih_it.handle();\n    //MyMesh::HalfedgeHandle iheh( *vih_it ); // vih_it.handle();\n    // if ( mesh.from_vertex_handle( iheh ) == vh ) std::cout << \"i from\" << std::endl;\n    // else if ( mesh.to_vertex_handle( iheh ) == vh ) std::cout << \"i to\" << std::endl;\n    //auto next_iheh = iheh.next();\n    //MyMesh::HalfedgeHandle next_iheh = mesh.next_halfedge_handle( *vih_it ); \n    // if ( mesh.from_vertex_handle( next_iheh ) == vh ) std::cout << \"next i from\" << std::endl;\n    // else if ( mesh.to_vertex_handle( next_iheh ) == vh ) std::cout << \"next i to\" << std::endl\n    // MyMesh::Point p0, p1, p2;\n    auto p0 = mesh.point( iheh.next().to() );\n    auto p1 = mesh.point( iheh.from() );\n    auto p2 = mesh.point( iheh.to() );\n    // auto p0 = mesh.point( mesh.to_vertex_handle( next_iheh ) );\n    // auto p1 = mesh.point( mesh.from_vertex_handle( iheh ) );\n    // auto p2 = mesh.point( mesh.to_vertex_handle( iheh ) );\n    double al = cotw( p0, p1, p2 );\n\n    // left face\n    // MyMesh::HalfedgeHandle mheh = mesh.opposite_halfedge_handle( iheh );\n    // if ( mesh.from_vertex_handle( mheh ) == vh ) std::cout << \"m from\" << std::endl;\n    // else if ( mesh.to_vertex_handle( mheh ) == vh ) std::cout << \"m to\" << std::endl;\n    // MyMesh::HalfedgeHandle next_mheh = mesh.next_halfedge_handle( mheh );\n    auto mheh = iheh.opp();\n    auto p3 = mesh.point( mheh.next().to() );\n    auto p4 = mesh.point( mheh.from() );\n    auto p5 = mesh.point( mheh.to() );\n    // p0 = mesh.point( mesh.to_vertex_handle( next_mheh ) );\n    // p1 = mesh.point( mesh.from_vertex_handle( mheh ) );\n    // p2 = mesh.point( mesh.to_vertex_handle( mheh ) );\n    double be = cotw( p3, p4, p5 );\n\n    //return (al + be) / 2.0;\n    return (al + be);\n  };\n\n  double computeMeanValueWeight( MyMesh& mesh, MyMesh::VertexIHalfedgeIter& vih_it ) {\n    OpenMesh::SmartHalfedgeHandle a( *vih_it );\n    return computeMeanValueWeight( mesh, a );\n    //return computeMeanValueWeight( mesh, (OpenMesh::SmartHalfedgeHandle&) *vih_it );\n  };\n\n  double computeMeanValueWeight( MyMesh& mesh, OpenMesh::SmartHalfedgeHandle& iheh ) {\n    // gamma\n    //auto iheh( *vih_it ); // vih_it.handle();\n    // auto next_iheh = iheh.next();\n    //MyMesh::HalfedgeHandle iheh( *vih_it ); // vih_it.handle();\n    //MyMesh::HalfedgeHandle next_iheh = mesh.next_halfedge_handle( iheh );\n    //MyMesh::Point p0, p1, p2;\n    auto p0 = mesh.point( iheh.next().from() );\n    auto p1 = mesh.point( iheh.next().to() );\n    auto p2 = mesh.point( iheh.from() );\n    // auto p0 = mesh.point( mesh.from_vertex_handle( next_iheh ) );\n    // auto p1 = mesh.point( mesh.to_vertex_handle( next_iheh ) );\n    // auto p2 = mesh.point( mesh.from_vertex_handle( iheh ) );\n    double ga = tan2w( p0, p1, p2 );\n#if 0  \n    std::cout << \"\\t gamma p0 \" << mesh.from_vertex_handle( next_iheh ).idx() << \" \"\n              << \" p1 \"  << mesh.to_vertex_handle( next_iheh ).idx() << \" \"\n              << \" p2 \"  << mesh.from_vertex_handle( iheh ).idx() << std::endl;\n#endif  \n  \n    // delta\n    auto mheh = iheh.opp();\n    // MyMesh::HalfedgeHandle mheh = mesh.opposite_halfedge_handle( iheh );\n    // MyMesh::HalfedgeHandle next_mheh = mesh.next_halfedge_handle( mheh );\n    auto p3 = mesh.point( mheh.from() ); // i\n    auto p4 = mesh.point( mheh.next().from() ); //j\n    auto p5 = mesh.point( mheh.next().to() );\n    // p0 = mesh.point( mesh.from_vertex_handle( mheh ) ); // i\n    // p1 = mesh.point( mesh.from_vertex_handle( next_mheh ) ); //j\n    // p2 = mesh.point( mesh.to_vertex_handle( next_mheh ) );\n    double de = tan2w( p3, p4, p5 );\n#if 0\n    std::cout << \"\\t delta p0 \" << mesh.from_vertex_handle( mheh ).idx() << \" \"\n              << \" p1 \"  << mesh.from_vertex_handle( next_mheh ).idx() << \" \"\n              << \" p2 \"  << mesh.to_vertex_handle( next_mheh ).idx() << std::endl;\n#endif\n\n    // return (ga + de) / (p0 - p1).length();\n    return (ga + de) / (p3 - p4).norm();\n  };\n\n  void constructBoundary( MyMesh& mesh, std::vector<MyMesh::VertexHandle>& bverts ) {\n\n    // find a boundary vertex\n    MyMesh::VertexHandle vh0;\n    for ( auto vh : mesh.vertices() )\n      {\n        if ( mesh.is_boundary( vh ) )\n          {\n            vh0 = vh; // v_it.handle();\n            //std::cout << \"boundary vertex \" << vh0.idx() << std::endl;\n            break;\n          }\n      }\n\n#if 0\n    MyMesh::VertexIter v_it, v_end(mesh.vertices_end());\n    for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)\n      {\n        MyMesh::VertexHandle vh = *v_it;\n        if ( mesh.is_boundary( vh ) )\n          {\n            vh0 = vh; // v_it.handle();\n            //std::cout << \"boundary vertex \" << vh0.idx() << std::endl;\n            break;\n          }\n      }\n#endif\n\n    std::vector<MyMesh::VertexHandle> bv_tmp;\n\n    // construct boundary vertices\n    MyMesh::VertexHandle vh = vh0, prev_vh;\n    do {\n      bv_tmp.push_back( vh );\n      MyMesh::VertexVertexIter vv_it;\n      for ( vv_it = mesh.vv_iter( vh ); vv_it.is_valid(); ++vv_it )\n        {\n          MyMesh::VertexHandle vc = *vv_it; // vv_it.handle();\n          if ( mesh.is_boundary( vc ) && (prev_vh != vc) )\n            {\n              //std::cout << \"\\tfound! \" << vc.idx() << std::endl;\n              prev_vh = vh;\n              vh = vc;\n              break;\n            }\n        }\n    } while ( vh != vh0 );\n    std::cout << \"#boundary vertices: \" << bv_tmp.size() << std::endl;\n\n#if 1\n    // reverse direction\n    bverts.push_back( bv_tmp[0] );\n    for ( int i = bv_tmp.size()-1; i > 0; --i )\n      bverts.push_back( bv_tmp[i] );\n#endif\n#if 0\n    for ( int i = 0; i < bv_tmp.size(); ++i )\n      bverts.push_back( bv_tmp[i] );\n#endif\n  };\n\n  void computeBoundaryMapping( MyMesh& mesh,\n                               std::vector<double>& paramx,  std::vector<double>& paramy ) {\n    // property handle to store a flag\n    mesh.add_property(fffs);\n  \n    // construct boundary vertices\n    std::vector<MyMesh::VertexHandle> bverts;\n    constructBoundary( mesh, bverts );\n\n    // corner coordinates\n    std::vector<double> cornerx(RECTANGLE);\n    std::vector<double> cornery(RECTANGLE);\n    std::vector<MyMesh::VertexHandle> cornerv;\n    // fix two vertices of the coordinates (0,0) or (1,1)\n    cornerx[0] = 0.0; cornerx[1] = 1.0; cornerx[2] = 1.0; cornerx[3] = 0.0;\n    cornery[0] = 0.0; cornery[1] = 0.0; cornery[2] = 1.0; cornery[3] = 1.0;\n\n    // compute boundary length\n    double blength = 0.0;\n    int bvn = bverts.size();\n    for ( int i = 0; i < bvn-1; ++i )\n      {\n        // blength += (mesh.point( bverts[i] ) - mesh.point( bverts[i+1] )).length();\n        blength += (mesh.point( bverts[i] ) - mesh.point( bverts[i+1] )).norm();\n      }\n    // blength += (mesh.point( bverts[bvn-1] ) - mesh.point( bverts[0] )).length();\n    blength += (mesh.point( bverts[bvn-1] ) - mesh.point( bverts[0] )).norm();\n    std::cout << \"boundary length \" << blength << std::endl;\n\n    // determine corner vertices\n    double l4 = blength / (double) RECTANGLE;\n    double tl = 0.0;\n    cornerv.push_back( bverts[0] );\n    paramx[ bverts[0].idx() ] = cornerx[0];\n    paramy[ bverts[0].idx() ] = cornery[0];\n    // (0,0)\n    Fixed& ff = mesh.property( fffs, bverts[0] );\n    ff.setIsFixed( true );\n\n    int count = 1;\n    for ( int i = 0; i < bvn-1; ++i )\n      {\n        // tl += (mesh.point( bverts[i] ) - mesh.point( bverts[i+1] )).length();\n        tl += (mesh.point( bverts[i] ) - mesh.point( bverts[i+1] )).norm();\n        if ( (tl > l4) && (count < RECTANGLE) )\n          {\n            cornerv.push_back( bverts[i] );\n            paramx[ bverts[i].idx() ] = cornerx[count];\n            paramy[ bverts[i].idx() ] = cornery[count];\n            if ( count == 2 ) // (1,1)\n              {\n                Fixed& ff = mesh.property( fffs, bverts[i] );\n                ff.setIsFixed( true );\n              }\n            tl = 0.0;\n            ++count;\n          }\n      }\n\n    std::cout << \"corner vertices: \";\n    for ( int i = 0; i < 4; ++i ) std::cout << cornerv[i].idx() << \" \";\n    std::cout << std::endl;\n\n    // compute inner boundary coordinates\n    std::vector<MyMesh::VertexHandle> innerv;\n    count = 1;\n    for ( int i = 0; i < bvn; ++i )\n      {\n        innerv.push_back( bverts[i] );\n        if ( cornerv[count] == bverts[i] )\n          {\n            // compute the length of poly line\n            double pll = 0.0;\n            for ( int j = 0; j < (int) innerv.size()-1; ++j )\n              {\n                // pll += (mesh.point( innerv[j] ) - mesh.point( bverts[j+1] )).length();\n                pll += (mesh.point( innerv[j] ) - mesh.point( bverts[j+1] )).norm();\n              }\n            // compute the ratio of length and compute parameter\n            double cll = 0.0;\n            // std::cout << \"count \" << count << std::endl;\n            for ( int j = 0; j < (int) innerv.size()-1; ++j )\n              {\n                double t = cll / pll;\n                double px = (1 - t) * cornerx[count-1] + t * cornerx[count];\n                double py = (1 - t) * cornery[count-1] + t * cornery[count];\n                paramx[ innerv[j].idx() ] = px;\n                paramy[ innerv[j].idx() ] = py;\n                // std::cout << \"\\t t \" << t << \" param \" << px << \" \" << py << std::endl;\n                // cll += (mesh.point( innerv[j] ) - mesh.point( bverts[j+1] )).length();\n                cll += (mesh.point( innerv[j] ) - mesh.point( bverts[j+1] )).norm();\n              }\n\n            // next poly line\n            ++count;\n            innerv.clear();\n            innerv.push_back( bverts[i] );\n          }\n      }\n    //\n    // last poly line\n    //\n    innerv.push_back( bverts[0] );\n    double pll = 0.0;\n    for ( int j = 0; j < (int) innerv.size()-1; ++j )\n      {\n        // pll += (mesh.point( innerv[j] ) - mesh.point( bverts[j+1] )).length();\n        pll += (mesh.point( innerv[j] ) - mesh.point( bverts[j+1] )).norm();\n      }\n    // compute the ratio of length and compute parameter\n    double cll = 0.0;\n    // std::cout << \"count \" << count << std::endl;\n    for ( int j = 0; j < (int) innerv.size()-1; ++j )\n      {\n        double t = cll / pll;\n        double px = (1 - t) * cornerx[RECTANGLE-1] + t * cornerx[0];\n        double py = (1 - t) * cornery[RECTANGLE-1] + t * cornery[0];\n        paramx[ innerv[j].idx() ] = px;\n        paramy[ innerv[j].idx() ] = py;\n        // std::cout << \"\\t t \" << t << \" param \" << px << \" \" << py << std::endl;\n        // cll += (mesh.point( innerv[j] ) - mesh.point( bverts[j+1] )).length();\n        cll += (mesh.point( innerv[j] ) - mesh.point( bverts[j+1] )).norm();\n      }\n  };\n\n  ////////////////////////////////////////////////////////////////////////////////////////\n\n  void applyParam_FixedBoundary( MyMesh& mesh,\n                                 std::vector<double>& paramx, std::vector<double>& paramy,\n                                 int sol_, int wei_ ) {\n    int n_vt = mesh.n_vertices();\n\n    //\n    // boundary mapping\n    // compute 2D parameters for boundary\n    //\n    computeBoundaryMapping( mesh, paramx, paramy );\n\n    // property handle to store weights\n    OpenMesh::VPropHandleT<VVWeights> vvws;\n    mesh.add_property(vvws);\n\n    //\n    // compute weights\n    //\n    // MyMesh::VertexIter v_it, v_end(mesh.vertices_end());\n    // for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)\n    for ( auto vh : mesh.vertices() )\n      {\n        // for check\n        //std::cout << i << \" \" << v_it.handle().idx() << std::endl;\n        //if ( i != v_it.handle().idx() ) std::cout << \"ng\" << std::endl;\n\n        VVWeights& vvw = mesh.property(vvws, vh);\n        //VVWeights& vvw = mesh.property(vvws,*v_it);\n        double wd = 0.0;\n        vvw.addWeight( wd );\n        //MyMesh::VertexHandle vh = v_it.handle();\n        //std::cout << \"v \" << i << std::endl;\n\n#if 0\n        MyMesh::VertexHandle vh = *v_it;\n        std::cout << \"i = \" << vh.idx() << std::endl;\n#endif\n        //OpenMesh::SmartVertexHandle vh(*v_it);\n        for ( auto vih : vh.incoming_halfedges() )\n          {\n            double wdc;\n            if ( wei_ == COTW )\n              wdc = computeCotangentWeight( mesh, vih );\n            else if ( wei_ == MVW )\n              wdc = computeMeanValueWeight( mesh, vih );\n            vvw.addWeight( wdc );\n            wd -= wdc;\n          }\n#if 0\n        MyMesh::VertexIHalfedgeIter vih_it;\n        for (vih_it=mesh.vih_iter( *v_it ); vih_it.is_valid(); ++vih_it)\n          {\n            double wdc;\n            if ( wei_ == COTW )\n              wdc = computeCotangentWeight( mesh, vih_it );\n            else if ( wei_ == MVW )\n              wdc = computeMeanValueWeight( mesh, vih_it );\n            vvw.addWeight( wdc );\n            wd -= wdc;\n          }\n#endif\n\n        vvw.setWeight( 0, wd );\n\n#if 0\n        std::vector<double>& ws = vvw.ws();\n        for ( int j = 0; j < ws.size(); ++j )\n          std::cout << \"\\t \" << ws[j] << std::endl;\n        std::cout << std::endl;\n#endif\n      }\n\n    //\n    // compute inner parameters\n    //\n    // build up sparse matrix A\n    std::cout << \"Setup sparse matrix ...\" << std::endl;\n    std::vector<Eigen::Triplet<double> > tripletList;\n    // MyMesh::VertexIter v_it, v_end(mesh.vertices_end());\n    // for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)\n    for ( auto vh : mesh.vertices() )\n      {\n        //MyMesh::VertexHandle vh = *v_it;\n        int i = vh.idx();\n        // if ( !(mesh.is_boundary(vh)) )\n        if ( !(vh.is_boundary()) )\n          {\n            VVWeights& vvw = mesh.property(vvws, vh);\n            tripletList.push_back( Eigen::Triplet<double>(i, i, vvw.w(0)) );\n            int k=1;\n            // MyMesh::VertexVertexIter vv_it;\n            // for (k=1, vv_it=mesh.vv_iter( vh ); vv_it.is_valid(); ++vv_it, ++k)\n            for ( auto vvh : vh.vertices() )\n              {\n                // MyMesh::VertexHandle vvh = *vv_it;\n                int j = vvh.idx();\n                tripletList.push_back( Eigen::Triplet<double>(i, j, vvw.w(k)) );\n                ++k;\n              }\n          }\n        else\n          tripletList.push_back( Eigen::Triplet<double>(i, i, 1.0) );\n      }\n\n    Eigen::SparseMatrix<double> spmat( n_vt, n_vt );\n    spmat.setFromTriplets( tripletList.begin(), tripletList.end() );\n    spmat.makeCompressed();\n\n    // setup vector b\n    Eigen::VectorXd xx(n_vt), xy(n_vt), bx(n_vt), by(n_vt);\n    for ( int i = 0; i < n_vt; ++i )\n      {\n        bx[i] = paramx[i];\n        by[i] = paramy[i];\n      }\n\n    // to symmetric positive-definite matrix\n    // toSpd( spmat, bverts, bx, by );\n\n    // solve x\n    if ( sol_ == BICGSTAB )\n      {\n        Eigen::BiCGSTAB<Eigen::SparseMatrix<double> > solver(spmat);\n        std::cout << \"solve xcoords ...\" << std::endl;\n        xx = solver.solve(bx);\n        std::cout << \"solve ycoords ...\" << std::endl;\n        xy = solver.solve(by);\n      }\n    else if ( sol_ == SPARSELU )\n      {\n        Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int> > solver;\n\n        solver.analyzePattern(spmat); \n        // Compute the numerical factorization \n        solver.factorize(spmat); \n        //Use the factors to solve the linear system \n        std::cout << \"solve xcoords ...\" << std::endl;\n        xx = solver.solve(bx);\n        std::cout << \"solve ycoords ...\" << std::endl;\n        xy = solver.solve(by);\n      }\n    for ( int i = 0; i < n_vt; ++i )\n      {\n        paramx[i] = xx[i];\n        paramy[i] = xy[i];\n      }\n\n#if 0\n    for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)\n      {\n        MyMesh::VertexHandle vh = *v_it;\n        int i = vh.idx();\n        Fixed& ff = mesh.property( fffs, vh );\n        if ( ff.isFixed() )\n          {\n            std::cout << \"i \" << i << \" param \" << paramx[i] << \" \" << paramy[i] << std::endl;\n          }\n      }\n#endif\n  \n    mesh.remove_property(vvws);\n\n    std::cout << \"done.\" << std::endl;\n  };\n\n  void applyParam_NaturalBoundary( MyMesh& mesh,\n                                   std::vector<double>& paramx, std::vector<double>& paramy,\n                                   int sol_, int wei_ ) {\n    const int n_vt = mesh.n_vertices();\n\n#if 0\n    //\n    // boundary mapping\n    //\n    // compute 2D parameters for boundary\n    computeBoundaryMapping( mesh, paramx, paramy );\n#endif\n\n#if 1\n    //for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)\n    for ( auto vh : mesh.vertices() )\n      {\n        //MyMesh::VertexHandle vh = *v_it;\n        //if ( !(mesh.is_boundary(vh)) ) \n        Fixed& ff = mesh.property( fffs, vh );\n        if ( !(ff.isFixed()) ) // not fixed\n          {\n            paramx[vh.idx()] = paramy[vh.idx()] = 0.0;\n          }\n      }\n#endif\n\n    // property handle to store weights\n    OpenMesh::VPropHandleT<VVWeights> vvws;\n    mesh.add_property(vvws);\n\n    //\n    // compute weights\n    //\n    //MyMesh::VertexIter v_it, v_end(mesh.vertices_end());\n    // for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)\n    for ( auto vh : mesh.vertices() )\n      {\n        // for check\n        //std::cout << i << \" \" << v_it.handle().idx() << std::endl;\n        //if ( i != v_it.handle().idx() ) std::cout << \"ng\" << std::endl;\n\n        VVWeights& vvw = mesh.property(vvws, vh);\n        double wd = 0.0;\n        vvw.addWeight( wd );\n        //MyMesh::VertexHandle vh = v_it.handle();\n        //std::cout << \"v \" << i << std::endl;\n\n        // OpenMesh::SmartVertexHandle vh(*v_it);\n        for ( auto vih : vh.incoming_halfedges() )\n          {\n            double wdc;\n            if ( wei_ == COTW )\n              wdc = computeCotangentWeight( mesh, vih );\n            else if ( wei_ == MVW )\n              wdc = computeMeanValueWeight( mesh, vih );\n            vvw.addWeight( wdc );\n            wd -= wdc;\n          }\n#if 0\n        MyMesh::VertexIHalfedgeIter vih_it;\n        for (vih_it=mesh.vih_iter( *v_it ); vih_it.is_valid(); ++vih_it)\n          {\n            double wdc;\n            if ( wei_ == COTW )\n              wdc = computeCotangentWeight( mesh, vih_it );\n            else if ( wei_ == MVW )\n              wdc = computeMeanValueWeight( mesh, vih_it );\n            vvw.addWeight( wdc );\n            wd -= wdc;\n          }\n#endif\n\n        vvw.setWeight( 0, wd );\n\n#if 0\n        std::vector<double>& ws = vvw.ws();\n        for ( int j = 0; j < ws.size(); ++j )\n          std::cout << \"\\t \" << ws[j] << std::endl;\n        std::cout << std::endl;\n#endif\n      }\n\n    //\n    // compute inner parameters\n    //\n    // build up sparse matrix A\n    std::cout << \"Setup sparse matrix ...\" << std::endl;\n    std::vector<Eigen::Triplet<double> > tripletList;\n    for ( auto vh : mesh.vertices() )\n    // MyMesh::VertexIter v_it, v_end(mesh.vertices_end());\n    // for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)\n      {\n        //MyMesh::VertexHandle vh = *v_it;\n        int i = vh.idx();\n        Fixed& ff = mesh.property( fffs, vh );\n        if ( !(ff.isFixed()) ) // not fixed\n          {\n            VVWeights& vvw = mesh.property(vvws, vh);\n\n            // set for x coord\n            tripletList.push_back( Eigen::Triplet<double>(i, i, vvw.w(0)) );\n            // set for y coord\n            tripletList.push_back( Eigen::Triplet<double>(i+n_vt, i+n_vt, vvw.w(0)) );\n            int k=1;\n            for ( auto vvh : vh.vertices() )\n            // MyMesh::VertexVertexIter vv_it;\n            // for (k=1, vv_it=mesh.vv_iter( *v_it ); vv_it.is_valid(); ++vv_it, ++k)\n              {\n                // MyMesh::VertexHandle vvh = *vv_it;\n                int j = vvh.idx();\n                // set for x coord\n                tripletList.push_back( Eigen::Triplet<double>(i, j, vvw.w(k)) );\n                // set for y coord\n                tripletList.push_back( Eigen::Triplet<double>(i+n_vt, j+n_vt, vvw.w(k)) );\n                ++k;\n              }\n\n            // boundary vertices\n            // if ( mesh.is_boundary(*v_it) )\n            if ( vh.is_boundary() )\n              {\n#if 0\n                std::cout << \"id \" << i << std::endl;\n                for ( int j = 0; j < vvw.size(); ++j )\n                  {\n                    std::cout << \"\\t\" << vvw.w(j) << std::endl;\n                  }\n#endif\n                // get neighbor boundary vertices\n                MyMesh::VertexVertexIter vv_it;\n                vv_it=mesh.vv_iter( vh );\n                MyMesh::VertexHandle sbvh = *vv_it, ebvh;\n                while ( vv_it.is_valid() )\n                  {\n                    ebvh = *vv_it;\n                    ++vv_it;\n                  }\n                int i1 = sbvh.idx();\n                int i2 = ebvh.idx();\n\n                if ( wei == COTW )\n                  {\n                    // std::cout << \"i1 \" << i1 << \" \" << mesh.is_boundary( sbvh ) << std::endl;\n                    // std::cout << \"i2 \" << i2 << \" \" << mesh.is_boundary( ebvh ) << std::endl;\n\n                    // for x coords\n                    tripletList.push_back( Eigen::Triplet<double>(i, i2+n_vt, 1.0) );\n                    tripletList.push_back( Eigen::Triplet<double>(i, i1+n_vt, -1.0) );\n                    // tripletList.push_back( Eigen::Triplet<double>(i, i2+n_vt, -1.0) );\n                    // tripletList.push_back( Eigen::Triplet<double>(i, i1+n_vt, 1.0) );\n\n                    // for y coords\n                    tripletList.push_back( Eigen::Triplet<double>(i+n_vt, i1, 1.0) );\n                    tripletList.push_back( Eigen::Triplet<double>(i+n_vt, i2, -1.0) );\n                    // tripletList.push_back( Eigen::Triplet<double>(i+n_vt, i1, -1.0) );\n                    // tripletList.push_back( Eigen::Triplet<double>(i+n_vt, i2, 1.0) );\n                  }\n                else if ( wei == MVW )\n                  {\n                    MyMesh::Point p0 = mesh.point( vh );\n                    MyMesh::Point p1 = mesh.point( sbvh );\n                    MyMesh::Point p2 = mesh.point( ebvh );\n                    // double ir1 = 1.0/((p1 - p0).length());\n                    double ir1 = 1.0/((p1 - p0).norm());\n                    // double ir2 = 1.0/((p2 - p0).length());\n                    double ir2 = 1.0/((p2 - p0).norm());\n                    // std::cout << ir1 << \" \" << ir2 << std::endl;\n                    // for x coords\n                    tripletList.push_back( Eigen::Triplet<double>(i, i2+n_vt, ir2) );\n                    tripletList.push_back( Eigen::Triplet<double>(i, i1+n_vt, -ir1) );\n                    tripletList.push_back( Eigen::Triplet<double>(i, i+n_vt, ir1 - ir2) );\n                    // for y coords\n                    tripletList.push_back( Eigen::Triplet<double>(i+n_vt, i1, ir1) );\n                    tripletList.push_back( Eigen::Triplet<double>(i+n_vt, i2, -ir2) );\n                    tripletList.push_back( Eigen::Triplet<double>(i+n_vt, i, ir2 - ir1) );\n                  }\n              }\n          }\n        else // fixed\n          {\n            // std::cout << \"i = \" << i << \" param \" << paramx[i] << \" \" << paramy[i] << std::endl;\n            tripletList.push_back( Eigen::Triplet<double>(i, i, 1.0) );\n            tripletList.push_back( Eigen::Triplet<double>(i+n_vt, i+n_vt, 1.0) );\n          }\n      }\n\n    Eigen::SparseMatrix<double> spmat( 2*n_vt, 2*n_vt );\n    spmat.setFromTriplets( tripletList.begin(), tripletList.end() );\n    spmat.makeCompressed();\n\n    // setup vector b\n    //Eigen::VectorXd xx(n_vt), xy(n_vt), bx(n_vt), by(n_vt);\n    Eigen::VectorXd xx(2*n_vt), bx(2*n_vt);\n    for ( int i = 0; i < n_vt; ++i )\n      {\n        // set for x coord\n        bx[i] = paramx[i];\n        // set for y coord\n        bx[i+n_vt] = paramy[i];\n      }\n\n    // solve x\n    if ( sol_ == BICGSTAB )\n      {\n        Eigen::BiCGSTAB<Eigen::SparseMatrix<double> > solver(spmat);\n        std::cout << \"solve x and y coords ...\" << std::endl;\n        xx = solver.solve(bx);\n        // std::cout << \"solve ycoords ...\" << std::endl;\n        // xy = solver.solve(by);\n      }\n    else if ( sol_ == SPARSELU )\n      {\n        Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int> > solver;\n\n        solver.analyzePattern(spmat); \n        // Compute the numerical factorization \n        solver.factorize(spmat); \n        //Use the factors to solve the linear system \n        std::cout << \"solve x and y coords ...\" << std::endl;\n        xx = solver.solve(bx);\n        // std::cout << \"solve ycoords ...\" << std::endl;\n        // xy = solver.solve(by);\n      }\n    for ( int i = 0; i < n_vt; ++i )\n      {\n        paramx[i] = xx[i];\n        paramy[i] = xx[i+n_vt];\n      }\n\n#if 0\n    for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)\n      {\n        MyMesh::VertexHandle vh = *v_it;\n        int i = vh.idx();\n        Fixed& ff = mesh.property( fffs, vh );\n        if ( ff.isFixed() )\n          {\n            std::cout << \"i \" << i << \" param \" << paramx[i] << \" \" << paramy[i] << std::endl;\n          }\n      }\n#endif\n\n    mesh.remove_property(vvws);\n\n    std::cout << \"done.\" << std::endl;\n  };\n\n  MyMesh::VertexIHalfedgeCWIter start_vih_cwiter( MyMesh::VertexHandle& vh,\n                                                  MyMesh::VertexHandle& pvh,\n                                                  MyMesh& mesh ) {\n    int c = 0;\n    MyMesh::VertexIHalfedgeCWIter vih_cwit = mesh.vih_cwiter( vh );\n    while (1)\n      {\n        if ( mesh.from_vertex_handle( *vih_cwit ) == pvh )\n          return vih_cwit;\n        ++vih_cwit; ++c;\n      }\n  };\n\n  MyMesh::VertexOHalfedgeCWIter start_voh_cwiter( MyMesh::VertexHandle& vh,\n                                                  MyMesh::VertexHandle& pvh,\n                                                  MyMesh& mesh ) {\n    int c = 0;\n    MyMesh::VertexOHalfedgeCWIter voh_cwit = mesh.voh_cwiter( vh );\n    while (1)\n      {\n        if ( mesh.to_vertex_handle( *voh_cwit ) == pvh )\n          return voh_cwit;\n        ++voh_cwit; ++c;\n      }\n  };\n\n  MyMesh::VertexOHalfedgeCCWIter start_voh_ccwiter( MyMesh::VertexHandle& vh,\n                                                    MyMesh::VertexHandle& pvh,\n                                                    MyMesh& mesh ) {\n    int c = 0;\n    MyMesh::VertexOHalfedgeCCWIter voh_ccwit = mesh.voh_ccwiter( vh );\n    while (1)\n      {\n        if ( mesh.to_vertex_handle( *voh_ccwit ) == pvh )\n          return voh_ccwit;\n        ++voh_ccwit; ++c;\n      }\n  };\n\n  MyMesh::VertexVertexIter start_vv_iter( MyMesh::VertexVertexIter vv_it,\n                                          MyMesh::VertexHandle& pvt ) {\n    int c = 0;\n    while (1)\n      {\n        if ( *vv_it == pvt )\n          {\n            // cout << \"count \" << c << endl;\n            return vv_it;\n          }\n        ++vv_it; ++c;\n      }\n  };\n\n  //\n  // set param_id to vvw of 1-ring neighbor vertices for boundary vertices\n  //\n  void setParamID_I( MyMesh::VertexHandle& vh,\n                     VVWeights& vvw,\n                     std::map<MyMesh::VertexHandle,int>& alt_param_id,\n                     MyMesh& mesh,\n                     std::vector<unsigned int>& vertex_type,\n                     bool reverse ) {\n    // if vh is OF_INTERNAL, apply add param_id to only 1-ring neighbor points\n    // with OF_BOUNDARY or OF_CONESINGULARITY_PI2.\n    // cout << \"internal vt \" << vh.idx() << \" 1-ring neighbor start\" << endl;\n    for ( MyMesh::VertexVertexIter vv_it = mesh.vv_iter( vh ); vv_it.is_valid(); ++vv_it )\n      {\n        MyMesh::VertexHandle vvh = *vv_it;\n        int id = vvh.idx();\n        int rev_id = alt_param_id[vvh];\n        // cout << \"\\tvertex \" << id << endl;\n        if ( (vertex_type[ id ] == OF_BOUNDARY) ||\n             (vertex_type[ id ] == OF_CONESINGULARITY_PI2)  )\n          {\n            // if a 1-ring neighbor vertex is OF_BOUNDARY or OF_CONESINGULARITY_PI2,\n            // set param_id to its original id or alt_param_id\n            // TODO: 11/29 \u3053\u3053\u306e\u3068\u3053\u308d\u3082\u3046\u4e00\u5ea6\u898b\u76f4\u3059\n            if ( reverse == false )\n              {\n                // 11/29 \u4e0b\u3068\u4ea4\u63db\n                // vvw.addParamID( vvh, id );\n                vvw.addParamID( vvh, rev_id );\n                // cout << \"\\tvt \" << id << \" type \" << vertex_type[id] << \" reverse \" << reverse << \" param \" << rev_id << endl;\n              }\n            else\n              {\n                // 11/29 \u4e0a\u3068\u4ea4\u63db\n                // vvw.addParamID( vvh, rev_id );\n                vvw.addParamID( vvh, id );\n                // cout << \"\\tvt \" << id << \" type \" << vertex_type[id] << \" reverse \" << reverse << \" param \" << id << endl;\n              }\n          }\n      }\n    // cout << \"internal 1-ring neighbor end\" << endl;\n  };\n\n  void setParamID_B( MyMesh::VertexHandle& vh,\n                     MyMesh::VertexHandle& pvh,\n                     MyMesh::VertexHandle& nvh,\n                     VVWeights& vvw,\n                     std::map<MyMesh::VertexHandle,int>& alt_param_id,\n                     MyMesh& mesh,\n                     std::vector<unsigned int>& vertex_type,\n                     bool reverse ) {\n    // if vh is OF_BOUNDARY or OF_CONESINGULARITY_PI2, apply add param_id\n    /// to all 1-ring neighbor points.\n    // TODO: reverse \u3068 rev \u306e\u95a2\u4fc2\u306b\u3064\u3044\u3066\u898b\u76f4\u3059\n    // cout << \"boundary 1-ring neighbor start\" << endl;\n    bool rev = reverse;\n    MyMesh::VertexVertexIter vv_it = start_vv_iter( mesh.vv_iter( vh ), pvh );\n    MyMesh::VertexHandle svh = *vv_it;\n    // int i;\n    // for ( i = 0, vv_it = mesh.vv_iter( vh ); vv_it.is_valid(); ++vv_it, ++i ) {\n    do {\n      MyMesh::VertexHandle vvh = *vv_it;\n      int id = vvh.idx();\n\n      // cout << \"vertex \" << id << endl;\n\n      // set param_id to 1.0 (reverse=true) or -1.0 (reverse=false)\n      if ( rev == false )\n        {\n          // 11/30 \u4e0b\u3068\u4ea4\u63db\n          // vvw.addParamID( vvh, -1 );\n          vvw.addParamID( vvh, 1 );\n          // cout << \"\\tvt \" << id << \" type \" << vertex_type[id] << \" reverse \" << rev << \" param \" << 1.0 << endl;\n        }\n      else // rev == true\n        {\n          // 11/30 \u4e0a\u3068\u4ea4\u63db\n          // vvw.addParamID( vvh, 1 );\n          vvw.addParamID( vvh, -1 );\n          // cout << \"\\tvt \" << id << \" type \" << vertex_type[id] << \" reverse \" << rev << \" param \" << -1.0 << endl;\n        }\n      ++vv_it;\n      if ( !(vv_it.is_valid()) ) vv_it = mesh.vv_iter( vh ); // reset vv_it to start\n      if ( *vv_it == nvh )\n        {\n          rev = ( rev == true ) ? false : true; // parameter is changed from nvt\n        }\n    } while ( *vv_it != svh );\n    // cout << \"boundary 1-ring neighbor end\" << endl;\n  };\n\n  int applyParam_Orbifold( MyMesh& mesh,\n                           Orbifold& orbi,\n                           // std::vector<MyMesh::VertexHandle>& cs_vertices,\n                           std::vector<double>& paramx, std::vector<double>& paramy,\n                           int sol_, int wei_ ) {\n\n    cout << \"compute orbifold parameterization ... \" << endl;\n\n    int n_vt = mesh.n_vertices();\n\n    // set orbifold boundary\n    orbi.calcBoundaries();\n\n    // cone singularity vertices\n    std::vector<MyMesh::VertexHandle>& cs_vertices = orbi.cs_vertices();\n\n    // parameters setup\n    std::vector<std::vector<MyMesh::VertexHandle> >& path = orbi.path();\n\n    // the number of parameter vertices\n    // - mesh.n_vertices() + path[2].size()-2 + path[3].size()-2 + 1 (cs_vertex[3])\n    // - two parameters in each vertex of type OF_BOUNDARY or OF_CONESINGULARITY_PI2\n    static int n_param = mesh.n_vertices() + path[2].size()-2 + path[3].size()-2 + 1;\n    // cout << \"vertices \" << mesh.n_vertices() << \" parameters \" << n_param << endl;\n    paramx.resize( n_param );\n    paramy.resize( n_param );\n\n    // cout << \"0----------------------------------------------------------\" << endl;\n    // set a param_id pair and a center for OF_BOUNDARY vertex\n    std::map<MyMesh::VertexHandle,int> alt_param_id;\n    int param_id = mesh.n_vertices(); // alt_param_id starts from mesh.n_vertices()\n    for ( int i = 0; i < path.size() / 2; ++i ) // search for only two paths\n      {\n        // cone singularities are not concerned\n        for ( int j = 1; j < path[i].size() - 1; ++j )\n          {\n            MyMesh::VertexHandle vt = path[i][j];\n            alt_param_id.insert( make_pair(vt, param_id) );\n            // cout << \"\\t\\t \" << vt.idx() << \" \" << alt_param_id[vt] << endl;\n            ++param_id;\n          }\n      }\n    // set a param_id pair for  OF_CONESINGULARITY_PI2 vertex\n    // alt parameter is last one (n_param - 1)\n    MyMesh::VertexHandle cs_vt = cs_vertices[1];\n    alt_param_id.insert( make_pair(cs_vt, param_id) );\n    ++param_id;\n\n    // cout << \"parameters \" << n_param << \" counts \" << param_id << endl;\n\n    // property handle to store weights\n    OpenMesh::VPropHandleT<VVWeights> vvws;\n    mesh.add_property(vvws);\n\n    std::vector<unsigned int>& vertex_type = orbi.vertex_type();\n\n    // cout << \"1----------------------------------------------------------\" << endl;\n    // make consistent path from path no.0 and no.1\n    std::vector<MyMesh::VertexHandle> path01;\n    for ( int i = 0; i < path.size() / 2; ++i )\n      for ( int j = 0; j < path[i].size(); ++j )\n        if ( (i != 1) || (j != 0) ) path01.push_back( path[i][j] );\n\n    // determine param_id for OF_BOUNDARY and OF_CONESINGULARITY_PI2 vertices of 1-ring neighbors\n    for ( int i = 1; i < path01.size() - 1; ++i )\n      {\n    // for ( int i = 0; i < path.size()/2; ++i )\n    //   {\n    //     for ( int j = 1; j < path[i].size(); ++j )\n    //       {\n        // MyMesh::VertexHandle vh = path[i][j];    // current boundary vertex\n        // MyMesh::VertexHandle pvh = path[i][j-1]; // prev boundary vertex\n        // MyMesh::VertexHandle nvh = path[i][j+1]; // next boundary vertex\n        MyMesh::VertexHandle vh = path01[i];    // current boundary vertex\n        MyMesh::VertexHandle pvh = path01[i-1]; // prev boundary vertex\n        MyMesh::VertexHandle nvh = path01[i+1]; // next boundary vertex\n\n        // bool reverse = ( i > 1 ) ? true : false;\n        // Since i < 2, reverse is always false.\n        bool reverse = false;\n\n        // processing OF_BOUNDARY point\n        // cout << \"(a) boundary vt \" << vh.idx() << endl;\n        if ( vertex_type[vh.idx()] == OF_BOUNDARY )\n          {\n            VVWeights& vvw = mesh.property(vvws, vh);\n            setParamID_B( vh, pvh, nvh, vvw, alt_param_id, mesh, vertex_type, reverse );\n            // vvw.Print();\n          }\n\n        // 1-ring neighbor vertices\n        // start vv_it is set to prev boundary vertex\n        MyMesh::VertexVertexIter vv_it = start_vv_iter( mesh.vv_iter( vh ), pvh );\n        // cout << \"vt \" << vt.idx() << \" pvt \" << pvt.idx() << \" start \" << svt.idx() << endl;\n        MyMesh::VertexHandle svh = *vv_it;\n        // cout << \"svh \" << svh.idx() << endl;\n        do {\n          // processing 1-ring neighbors of OF_BOUNDARY point\n          MyMesh::VertexHandle vvh = *vv_it;\n          // if ( (vvh != pvh) && (vvh != nvh) )\n          if ( vertex_type[vvh.idx()] == OF_INTERNAL )\n            {\n              // cout << \"(b) should be internal vt \" << vvh.idx() << endl;\n              VVWeights& vvvw = mesh.property(vvws, vvh);\n              setParamID_I( vvh, vvvw, alt_param_id, mesh, vertex_type, reverse );\n            }\n\n          ++vv_it;\n          if ( !(vv_it.is_valid()) ) vv_it = mesh.vv_iter( vh ); // reset vv_it to start\n          if ( *vv_it == nvh )\n            {\n              // cout << \"evh \" << nvh.idx() << endl;\n              reverse = ( reverse == true ) ? false : true; // parameter is changed from nvt\n            }\n        } while ( *vv_it != svh );\n        // }\n      }\n    // cout << \"2----------------------------------------------------------\" << endl;\n\n    // set cone sigularities fixed\n    //std::vector<MyMesh::VertexHandle>& cs_vertices = orbi.cs_vertices();\n    int i0 = cs_vertices[0].idx();\n    int i1 = cs_vertices[1].idx();\n    int i2 = cs_vertices[2].idx();\n    int i3 = alt_param_id[cs_vertices[1]];\n    paramx[i0] = 0.0; paramy[i0] = 0.0;\n    paramx[i1] = 1.0; paramy[i1] = 0.0;\n    paramx[i2] = 1.0; paramy[i2] = 1.0;\n    paramx[i3] = 0.0; paramy[i3] = 1.0;\n\n    // cout << \"cs \" << cs_vertices[0].idx() << \" \" << cs_vertices[1].idx() << \" \"\n    //      << cs_vertices[2].idx() << \" \" << n_param - 1 << endl;\n\n    //\n    // compute weights\n    //\n    MyMesh::VertexIter v_it, v_end(mesh.vertices_end());\n    for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)\n      {\n        // for check\n        //std::cout << i << \" \" << v_it.handle().idx() << std::endl;\n        //if ( i != v_it.handle().idx() ) std::cout << \"ng\" << std::endl;\n\n        VVWeights& vvw = mesh.property(vvws,*v_it);\n        double wd = 0.0;\n        vvw.addWeight( wd );\n        //MyMesh::VertexHandle vh = v_it.handle();\n        //std::cout << \"v \" << i << std::endl;\n\n        MyMesh::VertexIHalfedgeIter vih_it;\n        for (vih_it=mesh.vih_iter( *v_it ); vih_it.is_valid(); ++vih_it)\n          {\n            double wdc;\n            if ( wei_ == COTW )\n              wdc = computeCotangentWeight( mesh, vih_it );\n            else if ( wei_ == MVW )\n              wdc = computeMeanValueWeight( mesh, vih_it );\n            vvw.addWeight( wdc );\n            wd -= wdc;\n          }\n\n        vvw.setWeight( 0, wd );\n\n#if 0\n        std::vector<double>& ws = vvw.ws();\n        for ( int j = 0; j < ws.size(); ++j )\n          std::cout << \"\\t \" << ws[j] << std::endl;\n        std::cout << std::endl;\n#endif\n      }\n\n    //\n    // compute inner parameters\n    //\n    // build up sparse matrix A\n    std::cout << \"Setup sparse matrix ...\" << std::endl;\n    std::vector<Eigen::Triplet<double> > tripletList;\n    for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)\n      {\n        MyMesh::VertexHandle vh = *v_it;\n        int i = vh.idx();\n        if ( vertex_type[i] == OF_INTERNAL ) // internal vertex\n          {\n            VVWeights& vvw = mesh.property(vvws,*v_it);\n\n            // set for x coord\n            tripletList.push_back( Eigen::Triplet<double>(i, i, vvw.w(0)) );\n            // set for y coord\n            tripletList.push_back( Eigen::Triplet<double>(i+n_param, i+n_param, vvw.w(0)) );\n\n            int k;\n            MyMesh::VertexVertexIter vv_it;\n            // cout << \"internal vt \" << i << endl;\n            for (k=1, vv_it=mesh.vv_iter( *v_it ); vv_it.is_valid(); ++vv_it, ++k)\n              {\n                MyMesh::VertexHandle vvh = *vv_it;\n                int id = vvh.idx();\n                int j;\n                if ( (vertex_type[id] == OF_BOUNDARY) ||\n                     (vertex_type[id] == OF_CONESINGULARITY_PI2))\n                  j = vvw.param_id( vvh );\n                else\n                  j = id;\n\n                // if ( (vertex_type[id] == OF_BOUNDARY) ||\n                //      (vertex_type[id] == OF_CONESINGULARITY_PI2))\n                // cout << \"\\tvt \" << id << \" type \" << vertex_type[id] << \" param id \" << j << \" w \" << vvw.w(k) << endl;\n\n                // set for x coord\n                tripletList.push_back( Eigen::Triplet<double>(i, j, vvw.w(k)) );\n                // set for y coord\n                tripletList.push_back( Eigen::Triplet<double>(i+n_param, j+n_param, vvw.w(k)) );\n              }\n          }\n        else if ( vertex_type[i] == OF_CONESINGULARITY_PI ) // fixed\n          {\n            // original parameter id for cs_vertices[0] or cs_vertices[2]\n            // set for x coord\n            tripletList.push_back( Eigen::Triplet<double>(i, i, 1.0) );\n            // set for y coord\n            tripletList.push_back( Eigen::Triplet<double>(i+n_param, i+n_param, 1.0) );\n          }\n        else if ( vertex_type[i] == OF_CONESINGULARITY_PI2 ) // fixed\n          {\n            // original parameter id for cs_vertices[1]\n            // set for x coord\n            tripletList.push_back( Eigen::Triplet<double>(i, i, 1.0) );\n            // set for y coord\n            tripletList.push_back( Eigen::Triplet<double>(i+n_param, i+n_param, 1.0) );\n            \n            // altanative parameter id for cs_vertices[3]\n            int id = alt_param_id[vh];\n            // set for x coord\n            tripletList.push_back( Eigen::Triplet<double>(id, id, 1.0) );\n            // set for y coord\n            tripletList.push_back( Eigen::Triplet<double>(id+n_param, id+n_param, 1.0) );\n          }\n        else // vertex_type[i] == OF_BOUNDARY\n          {\n#if 0\n            cout << \"boundary vt \" << i << endl;\n\n            VVWeights& vvw = mesh.property(vvws, *v_it);\n            vvw.Print();\n\n            //tripletList.push_back( Eigen::Triplet<double>(i, i, vvw.w(0)) );\n            double sum_wei = 0.0;  // weight for non-reverse \n            double sum_wei_rev = 0.0; // weight for reverse\n            int rev_i = alt_param_id[ vh ];\n\n            //\n            // eq.9a\n            //\n            // R(90)\n            int k;\n            MyMesh::VertexVertexIter vv_it;\n            for (k=1, vv_it=mesh.vv_iter( *v_it ); vv_it.is_valid(); ++vv_it, ++k)\n              {\n                MyMesh::VertexHandle vvh = *vv_it;\n                int j = vvh.idx();\n                int rev = vvw.param_id( vvh );\n                // cout << \"vt id \" << j << \" reverse \" << rev << endl;\n                // classify weights to two according to the reverse flag\n                if ( rev == -1 ) // non-reverse\n                  {\n                    sum_wei -= vvw.w(k);\n                    // set for x coord\n                    tripletList.push_back( Eigen::Triplet<double>(i, j, vvw.w(k)) );\n                    // set for y coord\n                    tripletList.push_back( Eigen::Triplet<double>(i+n_param, j+n_param, vvw.w(k)) );\n                  }\n                else // reverse\n                  {\n                    sum_wei_rev -= vvw.w(k);\n                    // - wij * y_j\n                    // set for x coord\n                    int jj;\n                    if ( (vertex_type[j] == OF_BOUNDARY) ||\n                         (vertex_type[j] == OF_CONESINGULARITY_PI2) )\n                      jj = alt_param_id[vvh];\n                    else // internal\n                      jj = j;\n                    tripletList.push_back( Eigen::Triplet<double>(i, jj+n_param, -vvw.w(k)) );\n                    // + wij * x_j\n                    // set for y coord\n                    tripletList.push_back( Eigen::Triplet<double>(i+n_param, jj, vvw.w(k)) );\n                  }\n              }\n            // non-reverse weight\n            // + sum wij * x_i\n            // set for x coord\n            tripletList.push_back( Eigen::Triplet<double>(i, i, sum_wei) );\n            // + sum wij * y_i\n            // set for y coord\n            tripletList.push_back( Eigen::Triplet<double>(i+n_param, i+n_param, sum_wei) );\n\n            // reverse weight\n            // + sum wij * y_i\n            // set for x coord\n            tripletList.push_back( Eigen::Triplet<double>(i, rev_i+n_param, -sum_wei_rev) );\n            // - sum wij * x_i\n            // set for y coord\n            tripletList.push_back( Eigen::Triplet<double>(i+n_param, rev_i, sum_wei_rev) );\n\n            cout << \"i \" << i << \" rev_i \" << rev_i << \" wei \" << sum_wei << \" wei-rev \" << sum_wei_rev << \" wei (original) \" << vvw.w(0) << endl;\n\n#endif\n          }\n      }\n\n    //\n    // build up sparse matrix A (cont.)\n    // eq.9a\n    //\n    // k = 0: path no.0, k = 1: path no.2\n    for ( int k = 0; k < 2; ++k )\n      {\n        int l = (k == 0) ? 0 : 2;\n        for ( int j = 1; j < path[l].size() - 1; ++j )\n          {\n            MyMesh::VertexHandle vh = path[l][j];\n            int i = vh.idx();\n            int rev_i = alt_param_id[vh];\n\n            // cout << \"boundary vt \" << i << endl;\n\n            VVWeights& vvw = mesh.property(vvws, vh);\n            // vvw.Print();\n\n            double sum_wei = 0.0;  // weight for non-reverse \n            double sum_wei_rev = 0.0; // weight for reverse\n\n            int m;\n            MyMesh::VertexVertexIter vv_it;\n            for (m=1, vv_it=mesh.vv_iter( vh ); vv_it.is_valid(); ++vv_it, ++m)\n              {\n                MyMesh::VertexHandle vvh = *vv_it;\n                int j = vvh.idx();\n                int rev = vvw.param_id( vvh );\n\n                // classify weights to two according to the reverse flag\n                if ( rev == -1 ) // non-reverse\n                  {\n                    sum_wei -= vvw.w(m);\n                    // set for x coord\n                    tripletList.push_back( Eigen::Triplet<double>(i, j, vvw.w(m)) );\n                    // set for y coord\n                    tripletList.push_back( Eigen::Triplet<double>(i+n_param, j+n_param, vvw.w(m)) );\n                  }\n                else // reverse\n                  {\n                    sum_wei_rev -= vvw.w(m);\n                    int jj;\n                    if ( (vertex_type[j] == OF_BOUNDARY) ||\n                         (vertex_type[j] == OF_CONESINGULARITY_PI2) )\n                      jj = alt_param_id[vvh];\n                    else // internal\n                      jj = j;\n\n                    if ( k == 0 )\n                      {\n                        // R(-90)\n                        // - wij * y_j\n                        // set for x coord\n                        tripletList.push_back( Eigen::Triplet<double>(i, jj+n_param, vvw.w(m)) );\n                        // + wij * x_j\n                        // set for y coord\n                        tripletList.push_back( Eigen::Triplet<double>(i+n_param, jj, -vvw.w(m)) );\n                      }\n                    else\n                      {\n                        // R(90)\n                        // - wij * y_j\n                        // set for x coord\n                        tripletList.push_back( Eigen::Triplet<double>(i, jj+n_param, -vvw.w(m)) );\n                        // + wij * x_j\n                        // set for y coord\n                        tripletList.push_back( Eigen::Triplet<double>(i+n_param, jj, vvw.w(m)) );\n                      }\n                  }\n              }\n            // non-reverse weight\n            // + sum wij * x_i\n            // set for x coord\n            tripletList.push_back( Eigen::Triplet<double>(i, i, sum_wei) );\n            // + sum wij * y_i\n            // set for y coord\n            tripletList.push_back( Eigen::Triplet<double>(i+n_param, i+n_param, sum_wei) );\n\n            // reverse weight\n            if ( k == 0 )\n              {\n                // R(-90)\n                // + sum wij * y_i\n                // set for x coord\n                tripletList.push_back( Eigen::Triplet<double>(i, rev_i+n_param, sum_wei_rev) );\n                // - sum wij * x_i\n                // set for y coord\n                tripletList.push_back( Eigen::Triplet<double>(i+n_param, rev_i, -sum_wei_rev) );\n              }\n            else\n              {\n                // R(90)\n                // + sum wij * y_i\n                // set for x coord\n                tripletList.push_back( Eigen::Triplet<double>(i, rev_i+n_param, -sum_wei_rev) );\n                // - sum wij * x_i\n                // set for y coord\n                tripletList.push_back( Eigen::Triplet<double>(i+n_param, rev_i, sum_wei_rev) );\n              }\n\n            // cout << \"i \" << i << \" rev_i \" << rev_i << \" wei \" << sum_wei << \" wei-rev \" << sum_wei_rev << \" wei (original) \" << vvw.w(0) << endl;\n\n          }\n      }\n\n    //\n    // build up sparse matrix A (cont.)\n    // eq.9b\n    //\n    // k = 0: path no.0, k = 1: path no.2\n    for ( int k = 0; k < 2; ++k )\n      {\n        // int cen_param_id = (k == 0) ? cs_vertices[1].idx() : alt_param_id[cs_vertices[1]];\n        int cen_param_id = (k == 0) ? cs_vertices[0].idx() : cs_vertices[2].idx();\n        int l = (k == 0) ? 0 : 2;\n        for ( int j = 1; j < path[l].size() - 1; ++j )\n          {\n            MyMesh::VertexHandle vh = path[l][j];\n            int i = vh.idx();\n            int rev_i = alt_param_id[vh];\n\n            if ( k == 0 ) // l = 0\n              {\n                // R(-90)\n                // x\n                tripletList.push_back( Eigen::Triplet<double>(rev_i, rev_i, 1.0) );\n                tripletList.push_back( Eigen::Triplet<double>(rev_i, cen_param_id, -1.0) );\n                tripletList.push_back( Eigen::Triplet<double>(rev_i, i+n_param, 1.0) );\n                tripletList.push_back( Eigen::Triplet<double>(rev_i, cen_param_id+n_param, -1.0) );\n                // y\n                tripletList.push_back( Eigen::Triplet<double>(rev_i+n_param, rev_i+n_param, -1.0) );\n                tripletList.push_back( Eigen::Triplet<double>(rev_i+n_param, cen_param_id+n_param, 1.0) );\n                tripletList.push_back( Eigen::Triplet<double>(rev_i+n_param, i, 1.0) );\n                tripletList.push_back( Eigen::Triplet<double>(rev_i+n_param, cen_param_id, -1.0) );\n              }\n            else // l = 2\n              {\n                // R(90)\n                // x\n                tripletList.push_back( Eigen::Triplet<double>(rev_i, rev_i, -1.0) );\n                tripletList.push_back( Eigen::Triplet<double>(rev_i, cen_param_id, 1.0) );\n                tripletList.push_back( Eigen::Triplet<double>(rev_i, i+n_param, 1.0) );\n                tripletList.push_back( Eigen::Triplet<double>(rev_i, cen_param_id+n_param, -1.0) );\n                // y\n                tripletList.push_back( Eigen::Triplet<double>(rev_i+n_param, rev_i+n_param, 1.0) );\n                tripletList.push_back( Eigen::Triplet<double>(rev_i+n_param, cen_param_id+n_param, -1.0) );\n                tripletList.push_back( Eigen::Triplet<double>(rev_i+n_param, i, 1.0) );\n                tripletList.push_back( Eigen::Triplet<double>(rev_i+n_param, cen_param_id, -1.0) );\n              }\n          }\n      }\n\n    Eigen::SparseMatrix<double> spmat( 2*n_param, 2*n_param );\n    spmat.setFromTriplets( tripletList.begin(), tripletList.end() );\n    spmat.makeCompressed();\n\n    // cout << \"matrix A\" << endl;\n    // cout << spmat << endl;\n\n    // cout << \"before param \" << endl;\n    // for ( int i = 0; i < paramx.size(); ++i )\n    //   {\n    //     cout << i << \" \" << paramx[i] << \" \" << paramy[i] << endl;\n    //   }\n    \n    // setup vector b\n    //Eigen::VectorXd xx(n_param), xy(n_param), bx(n_param), by(n_param);\n    Eigen::VectorXd xx(2*n_param), bx(2*n_param);\n    for ( int i = 0; i < n_param; ++i )\n      {\n        // set for x coord\n        bx[i] = paramx[i];\n        // set for y coord\n        bx[i+n_param] = paramy[i];\n      }\n\n    // solve x\n    if ( sol_ == BICGSTAB )\n      {\n        Eigen::BiCGSTAB<Eigen::SparseMatrix<double> > solver(spmat);\n        std::cout << \"solve x and y coords ...\" << std::endl;\n        xx = solver.solve(bx);\n        // std::cout << \"solve ycoords ...\" << std::endl;\n        // xy = solver.solve(by);\n      }\n    else if ( sol_ == SPARSELU )\n      {\n        Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int> > solver;\n\n        solver.analyzePattern(spmat); \n        // Compute the numerical factorization \n        solver.factorize(spmat); \n        //Use the factors to solve the linear system \n        std::cout << \"solve x and y coords ...\" << std::endl;\n        xx = solver.solve(bx);\n        // std::cout << \"solve ycoords ...\" << std::endl;\n        // xy = solver.solve(by);\n      }\n\n    for ( int i = 0; i < n_param; ++i )\n      {\n        paramx[i] = xx[i];\n        paramy[i] = xx[i+n_param];\n      }\n\n#if 0    \n    cout << \"computed param \" << endl;\n    for ( int i = 0; i < paramx.size(); ++i )\n      {\n        cout << i << \" \" << paramx[i] << \" \" << paramy[i] << endl;\n      }\n#endif\n\n    mesh.remove_property(vvws);\n\n    //\n    // \"cut\" mesh along the path\n    //\n\n#if 0\n    // make consistent path from path no.0 and no.1\n    std::vector<MyMesh::VertexHandle> path01;\n    for ( int i = 0; i < path.size() / 2; ++i )\n      for ( int j = 0; j < path[i].size(); ++j )\n        if ( (i != 1) || (j != 0) ) path01.push_back( path[i][j] );\n#endif\n\n    // extract right side faces of a path\n    std::vector<MyMesh::FaceHandle> right_faces;\n    // for OF_BOUNDARY and OF_CONESINGULARITY_PI2 vertices,\n    // not for access OF_CONESINGULARITY_PI vertices\n    for ( int i = 1; i < path01.size() - 1; ++i )\n      {\n        MyMesh::VertexHandle vh = path01[i];    // current boundary vertex\n        MyMesh::VertexHandle pvh = path01[i-1]; // prev boundary vertex\n        MyMesh::VertexHandle nvh = path01[i+1]; // next boundary vertex\n\n        // right faces\n        // cout << \"vt \" << vh.idx() << \" cw in halfedge circulator \" << endl;\n        MyMesh::VertexIHalfedgeCWIter vih_cwit = start_vih_cwiter( vh, pvh, mesh );\n        while ( mesh.from_vertex_handle( *vih_cwit ) != nvh )\n          {\n            MyMesh::VertexHandle ivh = mesh.from_vertex_handle( *vih_cwit );\n            MyMesh::FaceHandle fh = mesh.face_handle( *vih_cwit );\n            right_faces.push_back( fh );\n            // cout << \"\\tivt \" << ivh.idx() << \" fc \" << fh.idx() << endl;\n            ++vih_cwit;\n            if ( !(vih_cwit->is_valid()) ) vih_cwit = mesh.vih_cwiter( vh );\n          }\n\n        // erase duplicate elements\n        std::sort(right_faces.begin(), right_faces.end());\n        right_faces.erase(std::unique(right_faces.begin(), right_faces.end()), right_faces.end());\n\n        // left faces\n        // cout << \"vt \" << vh.idx() << \" ccw out halfedge circulator \" << endl;\n        MyMesh::VertexOHalfedgeCCWIter voh_ccwit = start_voh_ccwiter( vh, pvh, mesh );\n        while ( mesh.to_vertex_handle( *voh_ccwit ) != nvh )\n          {\n            MyMesh::VertexHandle ovh = mesh.to_vertex_handle( *voh_ccwit );\n            MyMesh::FaceHandle fh = mesh.face_handle( *voh_ccwit );\n            // cout << \"\\tovt \" << ovh.idx() << \" fc \" << fh.idx() << endl;\n            ++voh_ccwit;\n            if ( !(voh_ccwit->is_valid()) ) voh_ccwit = mesh.voh_ccwiter( vh );\n          }\n      }\n\n    // create new vertex handles for path vertices with having\n    // the same positions to the original vertices\n    // OF_BOUNDARY vertices\n    for ( int i = 0; i < path.size() / 2; ++i ) // search for only two paths\n      {\n        for ( int j = 1; j < path[i].size() - 1; ++j )\n          {\n            MyMesh::VertexHandle vh = path[i][j];    // current boundary vertex\n            // new vertex\n            MyMesh::VertexHandle new_vh = mesh.add_vertex( mesh.point( vh ) );\n            // color\n            if ( mesh.has_vertex_colors() )\n              {\n                MyMesh::Color c = mesh.color(vh);\n                mesh.set_color( new_vh, c );\n              }\n            // cout << \"new bd vt \" << new_vh.idx() << \" param_id \" << alt_param_id[vh] << endl;\n          }\n      }\n    // OF_CONESINGULARITY_PI2 vertex\n    cs_vt = cs_vertices[1];\n    // new vertex\n    MyMesh::VertexHandle new_cs_vh = mesh.add_vertex( mesh.point(cs_vt) );\n    // color\n    if ( mesh.has_vertex_colors() )\n      {\n        MyMesh::Color cc = mesh.color(cs_vt);\n        mesh.set_color( new_cs_vh, cc );\n      }\n    // cout << \"new cs vt \" << new_cs_vh.idx() << \" param_id \" << alt_param_id[cs_vt] << endl;\n\n    // create vertex handles for new faces\n    std::vector<std::vector<MyMesh::VertexHandle> > faces_vhandles( right_faces.size() );\n    for ( int i = 0; i < right_faces.size(); ++i )\n      {\n        // cout << \"i = \" << i << endl;\n        for ( MyMesh::FaceVertexIter fv_it = mesh.fv_iter( right_faces[i] );\n              fv_it.is_valid(); ++fv_it )\n          {\n            MyMesh::VertexHandle fvh = *fv_it; // vv_it.handle();\n            if ( (vertex_type[fvh.idx()] == OF_BOUNDARY) ||\n                 (vertex_type[fvh.idx()] == OF_CONESINGULARITY_PI2) )\n              {\n                int new_id = alt_param_id[fvh];\n                MyMesh::VertexHandle nfvh = mesh.vertex_handle(new_id);\n                // cout << \"new_id \" << new_id << \" created \" << nfvh.idx() << endl;\n                faces_vhandles[i].push_back( nfvh );\n              }\n            else // internal\n              {\n                faces_vhandles[i].push_back( fvh );\n              }\n          }\n      }\n\n    // change path vertices to new ones\n    for ( int i = path.size() / 2; i < path.size(); ++i ) // search for only two paths\n      {\n        for ( int j = 0; j < path[i].size(); ++j )\n          {\n            if ( ((i == path.size() / 2) && (j != 0)) ||\n                 ((i == path.size() - 1) && (j != path[i].size()-1)) )\n              {\n                MyMesh::VertexHandle ovh = path[i][j];\n                path[i][j] = mesh.vertex_handle( alt_param_id[ovh] );\n              }\n          }\n      }\n\n    // delete right_faces and add new right faces\n    mesh.request_face_status();\n    // mesh.request_edge_status();\n    // mesh.request_vertex_status();\n\n    for ( int i = 0; i < right_faces.size(); ++i )\n      {\n        // cout << \"delete face \" << right_faces[i].idx() << endl;\n        mesh.delete_face( right_faces[i], false );\n        MyMesh::FaceHandle new_face = mesh.add_face( faces_vhandles[i] );\n        // cout << \"new face \" << new_face.idx() << endl;\n      }\n\n    // cut done.\n    mesh.garbage_collection();\n \n    return 0;\n  };\n\n};\n\n#endif // _PARAM_HXX\n", "meta": {"hexsha": "a69559b495e42797ac3d3fdfb29d031679c9f84c", "size": 61011, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "Param.hxx", "max_stars_repo_name": "kanait/orbiparam", "max_stars_repo_head_hexsha": "b540e35140ca8a1cda5fb0b2f8132c0c2650006d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T11:46:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T11:46:39.000Z", "max_issues_repo_path": "Param.hxx", "max_issues_repo_name": "kanait/orbiparam", "max_issues_repo_head_hexsha": "b540e35140ca8a1cda5fb0b2f8132c0c2650006d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Param.hxx", "max_forks_repo_name": "kanait/orbiparam", "max_forks_repo_head_hexsha": "b540e35140ca8a1cda5fb0b2f8132c0c2650006d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T14:49:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T14:49:32.000Z", "avg_line_length": 36.9539672925, "max_line_length": 149, "alphanum_fraction": 0.4961564308, "num_tokens": 17318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5133143237971658}}
{"text": "#ifndef PWALK_WALK_HPP_\n#define PWALK_WALK_HPP_\n\n#include <Eigen/Dense>\n#include \"common.hpp\"\n\nnamespace pwalk {\n\ntemplate <typename Dtype>\nclass Walker {\npublic:\n  Walker(const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& initialization, const Eigen::Matrix<Dtype, Eigen::Dynamic, Eigen::Dynamic>& cons_A, const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& cons_b) : nb_dim_(cons_A.cols()), nb_cons_(cons_A.rows()), nb_curr_samples_(1), initialization_(initialization), cons_A_(cons_A), cons_b_(cons_b), curr_sample_(initialization){}\n\n  virtual ~Walker(){}\n\n  virtual bool doSample(Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& new_sample, Dtype lazy = Dtype(0.5)){\n    return false;\n  }\n\n  // check whether a given point is in th polytope\n  bool checkInPolytope(const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& new_sample){\n    return (cons_A_ * new_sample - cons_b_).maxCoeff() < 0;\n  }\n\n  // getter for dimension\n  int getNbDim() {\n    return nb_dim_;\n  }\n\n  // getter for nb current samples\n  int getNbCurrSamples() {\n    return nb_curr_samples_;\n  }\n\n  // getter for current sample\n  Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& getCurrSample() {\n    return curr_sample_;\n  }\n\nprotected:\n\n  // Dimension\n  const int nb_dim_;\n  // number of constraints\n  const int nb_cons_;\n  // current sample size\n  int nb_curr_samples_;\n  // Initial vector\n  const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& initialization_;\n  // constraints matrix A\n  const Eigen::Matrix<Dtype, Eigen::Dynamic, Eigen::Dynamic>& cons_A_;\n  // constraint vector b\n  const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& cons_b_;\n  // Current vector\n  Eigen::Matrix<Dtype, Eigen::Dynamic, 1> curr_sample_;\n};\n\n\n} // namespace pwalk\n\n#endif // PWALK_WALK_HPP_\n", "meta": {"hexsha": "095574e86bf1d780efa213a048fd2846e8de5370", "size": 1706, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "polytopewalk/src/walker.hpp", "max_stars_repo_name": "yuachen/polytopewalk", "max_stars_repo_head_hexsha": "7e7431594489b5d5b6fe9947b4ccab21eee11152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-11-16T19:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T01:02:56.000Z", "max_issues_repo_path": "polytopewalk/src/walker.hpp", "max_issues_repo_name": "yuachen/polytopewalk", "max_issues_repo_head_hexsha": "7e7431594489b5d5b6fe9947b4ccab21eee11152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T11:15:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-06T11:15:29.000Z", "max_forks_repo_path": "polytopewalk/src/walker.hpp", "max_forks_repo_name": "yuachen/polytopewalk", "max_forks_repo_head_hexsha": "7e7431594489b5d5b6fe9947b4ccab21eee11152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-16T18:11:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-12T23:13:27.000Z", "avg_line_length": 27.5161290323, "max_line_length": 364, "alphanum_fraction": 0.7116060961, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5133143187845094}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_TOOLBOX_IEEE_FUNCTION_SCALAR_COPYSIGN_HPP_INCLUDED\n#define NT2_TOOLBOX_IEEE_FUNCTION_SCALAR_COPYSIGN_HPP_INCLUDED\n#include <nt2/sdk/meta/strip.hpp>\n\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/signnz.hpp>\n\n#include <nt2/toolbox/ieee/details/math.hpp>\n#include <boost/math/special_functions/sign.hpp>\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::copysign_, tag::cpu_,\n                          (A0)(A1),\n                          (arithmetic_<A0>)(arithmetic_<A1>)\n                         )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::copysign_(tag::arithmetic_,tag::arithmetic_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0,class A1>\n      struct result<This(A0,A1)> : meta::strip<A0>{};\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      return nt2::abs(a0)*signnz(a1);\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is double\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::copysign_, tag::cpu_,\n                          (A0)(A1),\n                          (double_<A0>)(double_<A1>)\n                         )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::copysign_(tag::double_,tag::double_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0,class A1>\n      struct result<This(A0,A1)> : meta::strip<A0>{};\n\n    NT2_FUNCTOR_CALL(2)\n    {\n    #ifdef NT2_TOOLBOX_IEEE_HAS_COPYSIGN\n      return ::copysign(a0, a1);\n    #elif defined(NT2_TOOLBOX_IEEE_HAS__COPYSIGN)\n      return ::_copysign(a0, a1);\n    #else\n      return boost::math::copysign(a0, a1);\n    #endif\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is float\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::copysign_, tag::cpu_,\n                          (A0)(A1),\n                          (float_<A0>)(float_<A1>)\n                         )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::copysign_(tag::float_,tag::float_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0,class A1>\n      struct result<This(A0,A1)> : meta::strip<A0>{};\n\n    NT2_FUNCTOR_CALL(2)\n    {\n    #ifdef NT2_TOOLBOX_IEEE_HAS_COPYSIGNF\n      return ::copysignf(a0, a1);\n    #elif defined(NT2_TOOLBOX_IEEE_HAS__COPYSIGNF)\n      return ::_copysignf(a0, a1);\n    #else\n        return boost::math::copysign(a0, a1);\n    #endif\n    }\n  };\n} }\n\n#endif\n// modified by jt the 26/12/2010\n", "meta": {"hexsha": "666a1ef75045e11f9064178102f6e0bf3897d7c4", "size": 3512, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/scalar/copysign.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/scalar/copysign.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "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": "modules/ieee/include/nt2/toolbox/ieee/function/scalar/copysign.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "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.5185185185, "max_line_length": 78, "alphanum_fraction": 0.5093963554, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5133040432393755}}
{"text": "//=======================================================================\n// Copyright 2007 Aaron Windsor\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#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/ref.hpp>\n#include <vector>\n\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n#include <boost/graph/is_kuratowski_subgraph.hpp>\n\nusing namespace boost;\n\n\nint main(int argc, char** argv)\n{\n\n  typedef adjacency_list\n    < vecS,\n      vecS,\n      undirectedS,\n      property<vertex_index_t, int>,\n      property<edge_index_t, int>\n    > \n    graph;\n\n  // Create a K_6 (complete graph on 6 vertices), which\n  // contains both Kuratowski subgraphs as minors.\n  graph g(6);\n  add_edge(0,1,g);\n  add_edge(0,2,g);\n  add_edge(0,3,g);\n  add_edge(0,4,g);\n  add_edge(0,5,g);\n  add_edge(1,2,g);\n  add_edge(1,3,g);\n  add_edge(1,4,g);\n  add_edge(1,5,g);\n  add_edge(2,3,g);\n  add_edge(2,4,g);\n  add_edge(2,5,g);\n  add_edge(3,4,g);\n  add_edge(3,5,g);\n  add_edge(4,5,g);\n\n\n  // Initialize the interior edge index\n  property_map<graph, edge_index_t>::type e_index = get(edge_index, g);\n  graph_traits<graph>::edges_size_type edge_count = 0;\n  graph_traits<graph>::edge_iterator ei, ei_end;\n  for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n    put(e_index, *ei, edge_count++);\n  \n\n  // Test for planarity - we know it is not planar, we just want to \n  // compute the kuratowski subgraph as a side-effect\n  typedef std::vector< graph_traits<graph>::edge_descriptor > \n    kuratowski_edges_t;\n  kuratowski_edges_t kuratowski_edges;\n  if (boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n                                   boyer_myrvold_params::kuratowski_subgraph = \n                                       std::back_inserter(kuratowski_edges)\n                                   )\n      )\n    std::cout << \"Input graph is planar\" << std::endl;\n  else\n    {\n      std::cout << \"Input graph is not planar\" << std::endl;\n\n      std::cout << \"Edges in the Kuratowski subgraph: \";\n      kuratowski_edges_t::iterator ki, ki_end;\n      ki_end = kuratowski_edges.end();\n      for(ki = kuratowski_edges.begin(); ki != ki_end; ++ki)\n        {\n          std::cout << *ki << \" \";\n        }\n      std::cout << std::endl;\n\n      std::cout << \"Is a kuratowski subgraph? \";\n      if (is_kuratowski_subgraph\n          (g, kuratowski_edges.begin(), kuratowski_edges.end())\n          )\n        std::cout << \"Yes.\" << std::endl;\n      else\n        std::cout << \"No.\" << std::endl;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "5b080f46f0df78a46efe22e1cfbc52fffd46a823", "size": 2822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/kuratowski_subgraph.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/kuratowski_subgraph.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/kuratowski_subgraph.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.0927835052, "max_line_length": 79, "alphanum_fraction": 0.5981573352, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5133040383834989}}
{"text": "// (C) Copyright 2007-2009 Andrew Sutton\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#include <vector>\n\n#include <boost/graph/undirected_graph.hpp>\n#include <boost/graph/directed_graph.hpp>\n#include <boost/graph/degree_centrality.hpp>\n#include <boost/graph/exterior_property.hpp>\n\nusing namespace std;\nusing namespace boost;\n\n// useful types\n// number of vertices in the graph\nstatic const unsigned N = 5;\n\ntemplate < typename Graph >\nvoid build_graph(\n    Graph& g, vector< typename graph_traits< Graph >::vertex_descriptor >& v)\n{\n    // add vertices\n    for (size_t i = 0; i < N; ++i)\n    {\n        v[i] = add_vertex(g);\n    }\n\n    // add edges\n    add_edge(v[0], v[1], g);\n    add_edge(v[1], v[2], g);\n    add_edge(v[2], v[0], g);\n    add_edge(v[3], v[4], g);\n    add_edge(v[4], v[0], g);\n}\n\ntemplate < typename Graph > void test_undirected()\n{\n    typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\n\n    typedef exterior_vertex_property< Graph, unsigned > CentralityProperty;\n    typedef typename CentralityProperty::container_type CentralityContainer;\n    typedef typename CentralityProperty::map_type CentralityMap;\n\n    Graph g;\n    vector< Vertex > v(N);\n    build_graph(g, v);\n\n    CentralityContainer cents(num_vertices(g));\n    CentralityMap cm(cents, g);\n    all_degree_centralities(g, cm);\n\n    BOOST_ASSERT(cm[v[0]] == 3);\n    BOOST_ASSERT(cm[v[1]] == 2);\n    BOOST_ASSERT(cm[v[2]] == 2);\n    BOOST_ASSERT(cm[v[3]] == 1);\n    BOOST_ASSERT(cm[v[4]] == 2);\n}\n\ntemplate < typename Graph > void test_influence()\n{\n    typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\n\n    typedef exterior_vertex_property< Graph, unsigned > CentralityProperty;\n    typedef typename CentralityProperty::container_type CentralityContainer;\n    typedef typename CentralityProperty::map_type CentralityMap;\n\n    Graph g;\n\n    vector< Vertex > v(N);\n    build_graph(g, v);\n\n    CentralityContainer cents(num_vertices(g));\n    CentralityMap cm(cents, g);\n    all_influence_values(g, cm);\n\n    BOOST_ASSERT(cm[v[0]] == 1);\n    BOOST_ASSERT(cm[v[1]] == 1);\n    BOOST_ASSERT(cm[v[2]] == 1);\n    BOOST_ASSERT(cm[v[3]] == 1);\n    BOOST_ASSERT(cm[v[4]] == 1);\n}\n\ntemplate < typename Graph > void test_prestige()\n{\n    typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\n\n    typedef exterior_vertex_property< Graph, unsigned > CentralityProperty;\n    typedef typename CentralityProperty::container_type CentralityContainer;\n    typedef typename CentralityProperty::map_type CentralityMap;\n\n    Graph g;\n\n    vector< Vertex > v(N);\n    build_graph(g, v);\n\n    CentralityContainer cents(num_vertices(g));\n    CentralityMap cm(cents, g);\n    all_prestige_values(g, cm);\n\n    BOOST_ASSERT(cm[v[0]] == 2);\n    BOOST_ASSERT(cm[v[1]] == 1);\n    BOOST_ASSERT(cm[v[2]] == 1);\n    BOOST_ASSERT(cm[v[3]] == 0);\n    BOOST_ASSERT(cm[v[4]] == 1);\n}\n\nint main(int, char*[])\n{\n    typedef undirected_graph<> Graph;\n    typedef directed_graph<> Digraph;\n\n    test_undirected< Graph >();\n    test_influence< Digraph >();\n    test_prestige< Digraph >();\n}\n", "meta": {"hexsha": "6f35e105f2e33e3a9927e47c65cadc6ece51b51a", "size": 3204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/test/degree_centrality.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.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": "3rdparty/boost_1_73_0/libs/graph/test/degree_centrality.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": "3rdparty/boost_1_73_0/libs/graph/test/degree_centrality.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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.9243697479, "max_line_length": 77, "alphanum_fraction": 0.6800873908, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5133040356521248}}
{"text": "/******************************************************************************\n *\n * AMDiS - Adaptive multidimensional simulations\n *\n * Copyright (C) 2013 Dresden University of Technology. All Rights Reserved.\n * Web: https://fusionforge.zih.tu-dresden.de/projects/amdis\n *\n * Authors:\n * Simon Vey, Thomas Witkowski, Andreas Naumann, Simon Praetorius, et al.\n *\n * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\n *\n * This file is part of AMDiS\n *\n * See also license.opensource.txt in the distribution.\n *\n ******************************************************************************/\n\n// Written by Simon Praetorius\n\n\n#ifndef ITL_DETAIL_INCLUDE\n#define ITL_DETAIL_INCLUDE\n\n#include <boost/math/special_functions/sign.hpp>\n\nnamespace itl\n{\n\n  namespace details\n  {\n\n    /// Compute the Givens rotation matrix parameters for a and b.\n    //     template<typename T>\n    //     void rotmat(const T& a, const T& b , T& c, T& s)\n    //     {\n    //       using std::abs; using std::sqrt; using mtl::conj;\n    //\n    //       const T zero = math::zero(T());\n    //       if (a == zero) {\n    // \tc = 0.0;\n    // \ts = 1.0;\n    //       } else {\n    // \tdouble temp = abs(a) / sqrt( conj(a)*a + conj(b)*b );\n    // \tc = temp;\n    // \ts = temp * (b / a);\n    //       }\n    //     }\n\n    inline void rotmat(const double& a, const double& b , double& c, double& s)\n    {\n      using std::abs;\n      using std::sqrt;\n      if ( b == 0.0 )\n      {\n        c = 1.0;\n        s = 0.0;\n      }\n      else if ( abs(b) > abs(a) )\n      {\n        double temp = a / b;\n        s = 1.0 / sqrt( 1.0 + temp*temp );\n        c = temp * s;\n      }\n      else\n      {\n        double temp = b / a;\n        c = 1.0 / sqrt( 1.0 + temp*temp );\n        s = temp * c;\n      }\n    }\n  }\n}\n\n#endif // ITL_DETAIL_INCLUDE\n", "meta": {"hexsha": "1d199bc35ef10206b8523c5e1ce80433fd8782d9", "size": 1897, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/itl/details.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": "src/solver/itl/details.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": "src/solver/itl/details.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": 24.3205128205, "max_line_length": 80, "alphanum_fraction": 0.4944649446, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5133040356521247}}
{"text": "//\n// Copyright (c) 2015 Singular Inversions Inc. (facegen.com)\n// Use, modification and distribution is subject to the MIT License,\n// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt\n//\n// Authors:     Andrew Beatty\n// Created:     Jan 27, 2009\n//\n// Not currently threadsafe.\n\n#include \"stdafx.h\"\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/variate_generator.hpp>\n#include \"FgRandom.hpp\"\n#include \"FgDiagnostics.hpp\"\n#include \"FgImage.hpp\"\n#include \"FgImgDisplay.hpp\"\n#include \"FgMath.hpp\"\n#include \"FgAffine1.hpp\"\n#include \"FgMain.hpp\"\n\nusing namespace std;\n\nstruct      RNG\n{\n    boost::random::mt19937      gen;\n    RNG() : gen(42u) {}\n};\n\nstatic RNG rng;\n\nuint32\nfgRandUint32()\n{return rng.gen(); }\n\nuint\nfgRandUint(uint size)\n{\n    uint    lim = numeric_limits<uint>::max(),\n            max = lim - (lim%size),\n            ret;\n    while ((ret = rng.gen()) > max) {}\n    return ret % size;\n}\n\nuint64\nfgRandUint64()\n{\n    uint64  hi = rng.gen(),\n            lo = rng.gen();\n    return (lo + (hi << 32));\n}\n\ndouble\nfgRand()\n{return double(fgRandUint64()) / double(numeric_limits<uint64>::max()); }\n\nvoid\nfgRandSeedRepeatable(uint seed)\n{rng.gen = boost::random::mt19937(seed); }\n\ndouble\nfgRandNormal()\n{\n    // Polar (Box-Muller) method; See Knuth v2, 3rd ed, p122.\n    double  x, y, r2;\n    do {\n        x = -1 + 2 * fgRand();\n        y = -1 + 2 * fgRand();\n        // see if it is in the unit circle:\n        r2 = x * x + y * y;\n    }\n    while (r2 > 1.0 || r2 == 0);\n    // Box-Muller transform:\n    return y * sqrt (-2.0 * log (r2) / r2);\n}\n\nFgDbls\nfgRandNormals(size_t num,double mean,double stdev)\n{\n    FgDbls      ret(num);\n    for (size_t ii=0; ii<num; ++ii)\n        ret[ii] = mean + stdev * fgRandNormal();\n    return ret;\n}\n\nstatic\nchar\nrandChar()\n{\n    uint    val = fgRandUint(26+26+10);\n    if (val < 10)\n        return char(48+val);\n    val -= 10;\n    if (val < 26)\n        return char(65+val);\n    val -= 26;\n    FGASSERT(val < 26);\n    return char(97+val);\n}\n\nstring\nfgRandString(uint numChars)\n{\n    string  ret;\n    for (uint ii=0; ii<numChars; ++ii)\n        ret = ret + randChar();\n    return ret;\n}\n\nvoid\nfgRandomTest(const FgArgs &)\n{\n    fgout << fgnl << \"sizeof(RNG) = \" << sizeof(RNG);\n    // Create a histogram of normal samples:\n    fgRandSeedRepeatable();\n    size_t          numStdevs = 6,\n                    binsPerStdev = 50,\n                    numSamples = 1000000,\n                    sz = numStdevs * 2 * binsPerStdev;\n    vector<size_t>  histogram(sz,0);\n    FgAffine1D      randToHist(FgVectD2(-double(numStdevs),numStdevs),FgVectD2(0,sz));\n    for (size_t ii=0; ii<numSamples; ++ii) {\n        int         rnd = fgRound(randToHist * fgRandNormal());\n        if ((rnd >= 0) && (rnd < int(sz)))\n            ++histogram[rnd]; }\n\n    // Make a bar graph of it:\n    // numSamples = binScale * stdNormIntegral * binsPerStdev\n    double          binScale = double(numSamples) / (fgSqrt_2pi() * binsPerStdev),\n                    hgtRatio = 0.9;\n    FgImgRgbaUb     img(sz,sz,FgRgbaUB(0));\n    for (size_t xx=0; xx<sz; ++xx) {\n        size_t      hgt = fgRound(histogram[xx] * sz * hgtRatio / binScale);\n        for (size_t yy=0; yy<hgt; ++yy)\n            img.xy(xx,yy) = FgRgbaUB(255); }\n\n    // Superimpose a similarly scaled Gaussian:\n    FgAffine1D      histToRand = randToHist.inverse();\n    for (size_t xx=0; xx<sz; ++xx) {\n        double      val = std::exp(-0.5 * fgSqr(histToRand * (xx + 0.5)));\n        size_t      hgt = fgRound(val * sz * hgtRatio);\n        img.xy(xx,hgt) = FgRgbaUB(255,0,0,255); }\n\n    // Display:\n    fgImgFlipVertical(img);\n    fgImgDisplay(img);\n}\n\n// */\n", "meta": {"hexsha": "5a22fb25faf4b7d92929f1d48b5f84e4201a3476", "size": 3755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/LibFgBase/src/FgRandom.cpp", "max_stars_repo_name": "maamountki/FaceGenBaseLibrary", "max_stars_repo_head_hexsha": "0c647920e913354028ed09fff3293555e84d2b94", "max_stars_repo_licenses": ["MIT"], "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/LibFgBase/src/FgRandom.cpp", "max_issues_repo_name": "maamountki/FaceGenBaseLibrary", "max_issues_repo_head_hexsha": "0c647920e913354028ed09fff3293555e84d2b94", "max_issues_repo_licenses": ["MIT"], "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/LibFgBase/src/FgRandom.cpp", "max_forks_repo_name": "maamountki/FaceGenBaseLibrary", "max_forks_repo_head_hexsha": "0c647920e913354028ed09fff3293555e84d2b94", "max_forks_repo_licenses": ["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.3831168831, "max_line_length": 86, "alphanum_fraction": 0.5834886818, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5133040335276222}}
{"text": "/*\n * Copyright (c) 2011-2014 Burkhard Ritter\n * This code is distributed under the two-clause BSD License.\n */\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE qca test\n#include <boost/test/unit_test.hpp>\n#include \"qca.hpp\"\n\nbool equal(double a, double b, double epsilon=1E-8)\n{\n    return std::abs(a-b) < epsilon;\n}\n\nBOOST_AUTO_TEST_CASE ( test_construct_qca_ising_system )\n{\n    QcaIsing s;\n\n    s.l.wire(1,1,1,1);\n    s.update();\n    BOOST_CHECK (s.basis.size() == 2);\n\n    s.l.wire(2,1,1,1);\n    s.update();\n    BOOST_CHECK (s.basis.size() == 4);\n\n    s.l.wire(6,1,1,1);\n    s.update();\n    BOOST_CHECK (s.basis.size() == 64);\n}\n\nBOOST_AUTO_TEST_CASE ( test_sigma_operator )\n{\n    const size_t N_c = 5;\n    \n    QcaIsing s;\n    s.l.wire(N_c,1,1,1);\n    s.update();\n\n    State state(\"10010\");\n    std::vector<double> expected_spins = {1,-1,-1,1,-1};\n\n    SparseVector<double> a(s.basis.size());\n    a.reserve(1);\n    a.insert(s.basis(state)) = 1;\n\n    std::vector<double> spins(N_c);\n    for (size_t j=0; j<N_c; j++)\n    {\n        SMatrix m = a.adjoint() * s.sigma(j) * a;\n        assert(m.size() == 1);\n        spins[j] = m.coeffRef(0,0);\n        // std::cerr << \"Spin \" << j+1 << \": \" << spins[j] << std::endl;\n    }\n    BOOST_CHECK (expected_spins == spins);\n}\n\nBOOST_AUTO_TEST_CASE ( test_spin_and_polarization_are_the_same )\n{\n    QcaIsing s;\n    s.beta = 1;\n    s.t = 1E-3;\n    s.l.wire(3,0.01,0.02,1);\n    s.update();\n\n    std::vector<double> spins = {s.measureSpin(0), \n                                 s.measureSpin(1), \n                                 s.measureSpin(2)};\n    std::vector<double> Ps = {s.measurePolarization(0), \n                              s.measurePolarization(1), \n                              s.measurePolarization(2)};\n    for (size_t i=0; i<3; i++)\n    {\n        // std::cerr << \"Spin[\" << i << \"] = \" << spins[i] \n        //           << \", Polarization[\" << i << \"] = \" << Ps[i] << std::endl;\n        BOOST_CHECK (equal(spins[i], Ps[i]));\n    }\n}\n\nBOOST_AUTO_TEST_CASE ( test_simple_physical_limits )\n{\n    QcaIsing s;\n    s.beta = 1;\n    s.t = 1E-3;\n    s.l.wire(3,0.01,0.02,0);\n    s.update();\n\n    /*\n     * Different input polarizations.\n     */\n    // P^D = 0\n    std::vector<double> Ps1 = {s.measurePolarization(0), \n                               s.measurePolarization(1), \n                               s.measurePolarization(2)};\n    for (size_t i=0; i<3; i++)\n        BOOST_CHECK (equal(0, Ps1[i]));\n    // P^D = 1\n    s.l.wire(3,0.01,0.02,1);\n    s.update();\n    std::vector<double> Ps2 = {s.measurePolarization(0), \n                               s.measurePolarization(1), \n                               s.measurePolarization(2)};\n    for (size_t i=0; i<3; i++)\n        BOOST_CHECK (Ps2[i]>0.5);\n    for (size_t i=1; i<3; i++)\n        BOOST_CHECK (Ps2[i]<Ps2[i-1]);\n    // P^D = -1\n    s.l.wire(3,0.01,0.02,-1);\n    s.update();\n    std::vector<double> Ps3 = {s.measurePolarization(0), \n                               s.measurePolarization(1), \n                               s.measurePolarization(2)};\n    for (size_t i=0; i<3; i++)\n    {\n        BOOST_CHECK (Ps3[i]<-0.5);\n        BOOST_CHECK (equal(Ps2[i], -Ps3[i]));\n    }\n    for (size_t i=1; i<3; i++)\n        BOOST_CHECK (Ps3[i]>Ps3[i-1]);\n\n    /*\n     * Different temperatures.\n     */\n    s.l.wire(3,0.01,0.02,1);\n    s.update();\n    // High temperature\n    s.beta = 0.01;\n    std::vector<double> Ps4 = {s.measurePolarization(0), \n                               s.measurePolarization(1), \n                               s.measurePolarization(2)};\n    // Medium temperature\n    s.beta = 1;\n    std::vector<double> Ps5 = {s.measurePolarization(0), \n                               s.measurePolarization(1), \n                               s.measurePolarization(2)};\n    // Low temperature\n    s.beta = 100;\n    std::vector<double> Ps6 = {s.measurePolarization(0), \n                               s.measurePolarization(1), \n                               s.measurePolarization(2)};\n    for (size_t i=0; i<3; i++)\n    {\n        BOOST_CHECK (Ps4[i] < Ps5[i]);\n        BOOST_CHECK (Ps5[i] < Ps6[i]);\n        BOOST_CHECK (Ps4[i] < 0.1);\n    }\n\n    /*\n     * Hopping versus Coulomb potential.\n     *\n     * Large hopping should wash out any polarization.\n     */\n    // Small hopping\n    s.l.wire(3,0.01,0.02,1);\n    s.t = 1E-3;\n    s.beta = 1;\n    s.update();\n    std::vector<double> Ps7 = {s.measurePolarization(0), \n                               s.measurePolarization(1), \n                               s.measurePolarization(2)};\n    // Medium hopping\n    s.t = 1;\n    s.update();\n    std::vector<double> Ps8 = {s.measurePolarization(0), \n                               s.measurePolarization(1), \n                               s.measurePolarization(2)};\n    // Large hopping, on the order of V_1\n    s.t = 100;\n    s.update();\n    std::vector<double> Ps9 = {s.measurePolarization(0), \n                               s.measurePolarization(1), \n                               s.measurePolarization(2)};\n    // Medium hopping, small V_1\n    s.l.wire(3,0.1,0.2,1);\n    s.t = 1;\n    s.update();\n    std::vector<double> Ps10 = {s.measurePolarization(0), \n                                s.measurePolarization(1), \n                                s.measurePolarization(2)};\n    // Medium hopping, medium V_1\n    s.l.wire(3,0.01,0.02,1);\n    s.t = 1;\n    s.update();\n    std::vector<double> Ps11 = {s.measurePolarization(0), \n                                s.measurePolarization(1), \n                                s.measurePolarization(2)};\n    // Medium hopping, large V_1\n    s.l.wire(3,0.001,0.002,1);\n    s.t = 1;\n    s.update();\n    std::vector<double> Ps12 = {s.measurePolarization(0), \n                                s.measurePolarization(1), \n                                s.measurePolarization(2)};\n    for (size_t i=0; i<3; i++)\n    {\n        BOOST_CHECK (Ps7[i] > Ps8[i]);\n        BOOST_CHECK (Ps8[i] > Ps9[i]);\n        BOOST_CHECK (Ps9[i] < 1E-2);\n        BOOST_CHECK (Ps10[i] < Ps11[i]);\n        BOOST_CHECK (Ps11[i] < Ps12[i]);\n        BOOST_CHECK (Ps12[i] > 0.95);\n    }\n\n    /*\n     * Larger inter-cell spacing means smaller polarization.\n     */\n    s.l.wire(3,0.01,0.02,1);\n    s.t = 1E-3;\n    s.beta = 1;\n    s.update();\n    std::vector<double> Ps13 = {s.measurePolarization(0), \n                                s.measurePolarization(1), \n                                s.measurePolarization(2)};\n    s.l.wire(3,0.01,0.04,1);\n    s.update();\n    std::vector<double> Ps14 = {s.measurePolarization(0), \n                                s.measurePolarization(1), \n                                s.measurePolarization(2)};\n    s.l.wire(3,0.01,1,1);\n    s.update();\n    std::vector<double> Ps15 = {s.measurePolarization(0), \n                                s.measurePolarization(1), \n                                s.measurePolarization(2)};\n    for (size_t i=0; i<3; i++)\n    {\n        BOOST_CHECK (Ps13[i] > Ps14[i]);\n        BOOST_CHECK (Ps14[i] > Ps15[i]);\n        BOOST_CHECK (Ps15[i] < 1E-3);\n    }\n}\n\nBOOST_AUTO_TEST_CASE ( test_tprime_gets_set_and_calculated_correctly )\n{\n    /*\n     * t^{\\prime} = \\frac{ 4 t^2 }{ \\Delta V }\n     *            = \\frac{ 8 t^2 }{ (2 - \\sqrt{2}) V_1 }\n     *            = \\frac{ 4 t^2 }{ 0.29289 V_1 }\n     */\n    double t;\n    double V1;\n\n    QcaIsing s;\n    s.q = 0.5;\n    s.beta = 1;\n\n    t = 1;\n    V1 = 100;\n    \n    s.t = t;\n    s.l.wire(3,1.0/V1,1,1);\n    s.update();\n    \n    // std::cerr << \"t' = \" << s.tprime << std::endl;\n    BOOST_CHECK(equal(s.tprime, 0.13656854249492380195));\n\n    t = 3;\n    V1 = 40;\n    s.t = t;\n    s.l.wire(3,1.0/V1,1,1);\n    s.update();\n    \n    // std::cerr << \"t' = \" << s.tprime << std::endl;\n    BOOST_CHECK(equal(s.tprime, 3.07279220613578554391));\n\n    t = 10;\n    V1 = 200;\n    s.t = t;\n    s.l.wire(3,1.0/V1,1,1);\n    s.update();\n    \n    // std::cerr << \"t' = \" << s.tprime << std::endl;\n    BOOST_CHECK(equal(s.tprime, 6.82842712474619009758));\n}\n\nBOOST_AUTO_TEST_CASE ( test_bond_and_ising_models_are_the_same_in_some_limits )\n{\n    QcaIsing s_i;\n    s_i.q = 0.5;\n    s_i.beta = 1;\n    s_i.t = 1;\n    s_i.l.wire(3,0.001,0.005,1);\n    s_i.update();\n\n    QcaBond s_b;\n    s_b.q = 0.5;\n    s_b.beta = 1;\n    s_b.t = 1;\n    s_b.l.wire(3,0.001,0.005,1);\n    s_b.update();\n\n    std::vector<double> Ps_i = {s_i.measurePolarization(0), \n                                s_i.measurePolarization(1), \n                                s_i.measurePolarization(2)};\n    std::vector<double> Ps_b = {s_b.measurePolarization(0), \n                                s_b.measurePolarization(1), \n                                s_b.measurePolarization(2)};\n    for (size_t i=0; i<3; i++)\n    {\n        std::cerr << \"Ps_i[\" << i << \"] = \" << Ps_i[i] \n                  << \", Ps_b[\" << i << \"] = \" << Ps_b[i] << std::endl;\n    }\n    // TODO\n}\n", "meta": {"hexsha": "747440188d3551accd474213756a32525789f826", "size": 8834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/qcaIsingTest.cpp", "max_stars_repo_name": "meznom/qca", "max_stars_repo_head_hexsha": "8b7cfa6f36ab17202fce5bb953321d33abdf9eb7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-07-11T01:56:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-03T09:13:07.000Z", "max_issues_repo_path": "tests/qcaIsingTest.cpp", "max_issues_repo_name": "meznom/qca", "max_issues_repo_head_hexsha": "8b7cfa6f36ab17202fce5bb953321d33abdf9eb7", "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/qcaIsingTest.cpp", "max_forks_repo_name": "meznom/qca", "max_forks_repo_head_hexsha": "8b7cfa6f36ab17202fce5bb953321d33abdf9eb7", "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.0592105263, "max_line_length": 79, "alphanum_fraction": 0.4881141046, "num_tokens": 2748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5133040280648737}}
{"text": "#include \"itkImage.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkNumericTraits.h\"\n\n#include \"vnl/vnl_matrix_ref.h\"\n#include \"vnl/vnl_matrix.h\"\n#include \"tkdCmdParser.h\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/small_world_generator.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/graph/graph_utility.hpp>\n\n/**\n * Date: 16-11-2009\n */\nclass CreateSmallWorld {\n\npublic:\n\n\ttypedef double PixelType;\n\ttypedef itk::Image< PixelType, 2 > ImageType;\n\ttypedef vnl_matrix_ref< PixelType > DataMatrixType;\n\ttypedef itk::ImageFileWriter< ImageType > WriterType;\n\n\ttypedef boost::adjacency_list<> GraphType;\n\ttypedef boost::small_world_iterator< boost::minstd_rand, GraphType > SWGenerator;\n\n\n\t/**\n\t * Run.\n\t */\n\tvoid run( const std::string& output, unsigned int size, unsigned int k, PixelType probability, bool verbose )\n\t{\n\t\tWriterType::Pointer writer = WriterType::New();\n\n\t\twriter->SetFileName( output.c_str() );\n\t\twriter->SetInput( GetMatrix( size, k, probability, verbose ) );\n\n\t\ttry {\n\t\t\twriter->Update();\n\t\t} catch ( itk::ExceptionObject& e ) {\n\t\t\tstd::cerr << \"Error writing: \" << output << std::endl;\n\t\t\tstd::cerr << e.GetDescription() << std::endl;\n\t\t}\n\n\t}\n\nprotected:\n\n\t/**\n\t * Return regular matrix.\n\t */\n\tImageType::Pointer GetMatrix( unsigned int matrixSize, unsigned int k, PixelType probability, bool verbose )\n\t{\n\t\tImageType::Pointer outputImage = ImageType::New();\n\t\tImageType::SizeType size;\n\t\tImageType::RegionType region;\n\t\tsize[ 0 ] = matrixSize;\n\t\tsize[ 1 ] = matrixSize;\n\n\t\tregion.SetSize( size );\n\t\toutputImage->SetRegions( region );\n\t\toutputImage->Allocate();\n\n\t\tboost::minstd_rand generator;\n\n\t\tGraphType g( SWGenerator( generator, matrixSize, k, probability ), SWGenerator(), matrixSize );\n\n\t\tboost::property_map< GraphType, boost::vertex_index_t >::type vertices\n\t\t\t= boost::get( boost::vertex_index, g );\n\n\t\tfor( boost::graph_traits< GraphType >::edge_iterator e = edges( g ).first; e != edges( g ).second; ++e )\n\t    {\n\t\t\tImageType::IndexType index;\n\t\t\tindex[0] = boost::get( vertices, boost::source( *e, g ) );\n\t    \tindex[1] = boost::get( vertices, boost::target( *e, g ) );\n\t    \toutputImage->SetPixel( index, static_cast< PixelType >( 1.0 ) );\n\t    }\n\n\t\tif ( verbose )\n\t\t\tboost::print_graph( g );\n\n\t\treturn outputImage;\n\t}\n};\n\n/**\n * Create regular matrix.\n */\nint main( int argc, char ** argv ) {\n\ttkd::CmdParser p( \"create_smallworld\", \"Construct smallworld graph.\" );\n\n\tstd::string output;\n\tint size = 10;\n\tint k = 2;\n\tfloat probability = 0.03;\n\tbool verbose;\n\n\tp.AddArgument( output, \"output\" ) ->AddAlias( \"o\" ) ->SetInput( \"filename\" ) ->SetDescription( \"Output matrix file name\" ) ->SetRequired(\n\t\t\ttrue ) -> SetMinMax( 1, 1 );\n\n\tp.AddArgument( size, \"size\" ) ->AddAlias( \"s\" ) ->SetInput( \"uint\" ) ->SetDescription( \"Number of nodes [ default: 10 ]\" );\n\n\tp.AddArgument( k, \"k\" ) ->AddAlias( \"k\" ) ->SetInput( \"uint\" ) ->SetDescription( \"K [ default: 2 ]\" );\n\n\tp.AddArgument( probability, \"probability\" ) ->AddAlias( \"p\" ) ->SetInput( \"float\" ) ->SetDescription( \"Rewire probability [ default: 0.03 ]\" );\n\n\tp.AddArgument( verbose, \"verbose\" ) ->AddAlias( \"v\" ) ->SetInput( \"bool\" ) ->SetDescription( \"Print graph to screen\" );\n\n\tif ( !p.Parse( argc, argv ) ) {\n\t\tp.PrintUsage( std::cout );\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tCreateSmallWorld createSmallWorld;\n\n\tcreateSmallWorld.run( output, size, k, probability, verbose );\n\n\treturn EXIT_SUCCESS;\n}\n\n\n", "meta": {"hexsha": "3dd14398e24ac2f560297fd9a261c02262ccad11", "size": 3424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/graphs/createSmallWorld.cpp", "max_stars_repo_name": "wmotte/toolkid", "max_stars_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/graphs/createSmallWorld.cpp", "max_issues_repo_name": "wmotte/toolkid", "max_issues_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graphs/createSmallWorld.cpp", "max_forks_repo_name": "wmotte/toolkid", "max_forks_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_forks_repo_licenses": ["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.6129032258, "max_line_length": 144, "alphanum_fraction": 0.675817757, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5133040259403715}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <boost/format.hpp>\n\n#include <iostream>\n#include <vector>\n#include <madym/mdm_Image3D.h>\n#include <madym/mdm_ParamSummaryStats.h>\n#include <madym/tests/mdm_test_utils.h>\n\nBOOST_AUTO_TEST_SUITE(test_mdm)\n\nBOOST_AUTO_TEST_CASE(test_summaryStats) {\n\tBOOST_TEST_MESSAGE(\"======= Testing class mdm_ParamSummaryStats =======\");\n\n\tmdm_Image3D img;\n\tint nx = 5, ny = 1, nz = 1;\n\timg.setDimensions(nx, ny, nz);\n\n\tfor (int i = 0; i < nx; i++)\n\t\timg.setVoxel(i, i + 1);\n\n\t//Create stats object\n\tmdm_ParamSummaryStats stats; \n\n\t//Don't set ROI, it should use all voxels\n\tstats.makeStats(img, \"dummy\");\n\n\t//Check the stats values - data array is {1, 2, 3, 4, 5}\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().mean_, 3.0, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: stddev\");\n\tBOOST_CHECK_CLOSE(stats.stats().stddev_, 1.5811, 0.1);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().median_, 3.0, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: lowerQ\");\n\tBOOST_CHECK_CLOSE(stats.stats().lowerQ_, 1.5, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().upperQ_, 4.5, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().iqr_, 3.0, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: validVoxels\");\n\tBOOST_CHECK_EQUAL(stats.stats().validVoxels_, 5);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: invalidVoxels\");\n\tBOOST_CHECK_EQUAL(stats.stats().invalidVoxels_, 0);\n\n\t//Repeat the test with scale set\n\tdouble scale = 2.0;\n\tstats.makeStats(img, \"dummy\", scale);\n\t\n\t//data array is{ 2, 4, 6, 8, 10 }\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().mean_, scale*3.0, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: stddev\");\n\tBOOST_CHECK_CLOSE(stats.stats().stddev_, scale*1.5811, 0.1);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().median_, scale*3.0, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: lowerQ\");\n\tBOOST_CHECK_CLOSE(stats.stats().lowerQ_, scale*1.5, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().upperQ_, scale*4.5, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().iqr_, scale*3.0, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: validVoxels\");\n\tBOOST_CHECK_EQUAL(stats.stats().validVoxels_, 5);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: invalidVoxels\");\n\tBOOST_CHECK_EQUAL(stats.stats().invalidVoxels_, 0);\n\n\t//Now set an ROI and repeat the test\n\tmdm_Image3D roi;\n\troi.setDimensions(nx, ny, nz);\n\n\tfor (int i = 0; i < 4; i++)\n\t\troi.setVoxel(i, 1);\n\n\tstats.setROI(roi);\n\tstats.makeStats(img, \"dummy\");\n\t\n\t//Should now only use {1, 2, 3, 4}\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().mean_, 2.5, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: stddev\");\n\tBOOST_CHECK_CLOSE(stats.stats().stddev_, 1.2910, 0.1);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().median_, 2.5, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: lowerQ\");\n\tBOOST_CHECK_CLOSE(stats.stats().lowerQ_, 1.25, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().upperQ_, 3.75, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().iqr_, 2.5, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: validVoxels\");\n\tBOOST_CHECK_EQUAL(stats.stats().validVoxels_, 4);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: invalidVoxels\");\n\tBOOST_CHECK_EQUAL(stats.stats().invalidVoxels_, 0);\n\n\t//Set some negative values\n\tfor (int i = 0; i < 3; i++)\n\t\timg.setVoxel(i, 1.0 / double(i + 1));\n\n\timg.setVoxel(3, -1);\n\tstats.makeStats(img, \"dummy\", 1.0, true);\n\n\t//Should now only use {1, 2, 3}\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().mean_, 2.0, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: stddev\");\n\tBOOST_CHECK_CLOSE(stats.stats().stddev_, 1, 0.1);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().median_, 2.0, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: lowerQ\");\n\tBOOST_CHECK_CLOSE(stats.stats().lowerQ_, 1.0, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().upperQ_, 3.0, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: median\");\n\tBOOST_CHECK_CLOSE(stats.stats().iqr_, 2.0, 0.00001);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: validVoxels\");\n\tBOOST_CHECK_EQUAL(stats.stats().validVoxels_, 3);\n\tBOOST_TEST_MESSAGE(\"Test whole ROI: invalidVoxels\");\n\tBOOST_CHECK_EQUAL(stats.stats().invalidVoxels_, 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END() //\n", "meta": {"hexsha": "52e582d3fc00fb0a17ea2180cdc9251c9cb8afd3", "size": 4635, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "madym/tests/test_summaryStats.cxx", "max_stars_repo_name": "michaelberks/madym_cxx", "max_stars_repo_head_hexsha": "647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T15:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T15:43:15.000Z", "max_issues_repo_path": "madym/tests/test_summaryStats.cxx", "max_issues_repo_name": "michaelberks/madym_cxx", "max_issues_repo_head_hexsha": "647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16", "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": "madym/tests/test_summaryStats.cxx", "max_forks_repo_name": "michaelberks/madym_cxx", "max_forks_repo_head_hexsha": "647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16", "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.6829268293, "max_line_length": 75, "alphanum_fraction": 0.7318230852, "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.51322281730414}}
{"text": "/* boost random/cauchy_distribution.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Permission to use, copy, modify, sell, and distribute this software\n * is hereby granted without fee provided that the above copyright notice\n * appears in all copies and that both that copyright notice and this\n * permission notice appear in supporting documentation,\n *\n * Jens Maurer makes no representations about the suitability of this\n * software for any purpose. It is provided \"as is\" without express or\n * implied warranty.\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: cauchy_distribution.hpp 11696 2001-11-14 21:53:38Z jmaurer $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_CAUCHY_DISTRIBUTION_HPP\n#define BOOST_RANDOM_CAUCHY_DISTRIBUTION_HPP\n\n#include <cmath>\n#include <boost/random/uniform_01.hpp>\n\nnamespace boost {\n\n#if defined(__GNUC__) && (__GNUC__ < 3)\n// Special gcc workaround: gcc 2.95.x ignores using-declarations\n// in template classes (confirmed by gcc author Martin v. Loewis)\n  using std::tan;\n#endif\n\n// Cauchy distribution: p(x) = sigma/(pi*(sigma**2 + (x-median)**2))\ntemplate<class UniformRandomNumberGenerator, class RealType = double>\nclass cauchy_distribution\n{\npublic:\n  typedef UniformRandomNumberGenerator base_type;\n  typedef RealType result_type;\n\n  cauchy_distribution(base_type & rng, result_type median = 0, \n                      result_type sigma = 1)\n    : _rng(rng), _median(median), _sigma(sigma) { }\n  // compiler-generated copy constructor is fine\n  // uniform_01 cannot be assigned, neither can this class\n  result_type operator()()\n  {\n    const double pi = 3.14159265358979323846;\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::tan;\n#endif\n    return _median + _sigma * tan(pi*(_rng()-0.5));\n  }\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\n  friend bool operator==(const cauchy_distribution& x, \n                         const cauchy_distribution& y)\n  {\n    return x._median == y._median && x._sigma == y._sigma && x._rng == y._rng; \n  }\n#else\n  // Use a member function\n  bool operator==(const cauchy_distribution& rhs) const\n  {\n    return _median == rhs._median && _sigma == rhs._sigma && _rng == rhs._rng;\n  }\n#endif\nprivate:\n  uniform_01<base_type, result_type> _rng;\n  result_type _median, _sigma;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_CAUCHY_DISTRIBUTION_HPP\n", "meta": {"hexsha": "d3109c2bfd781db3a01dc25cfd4df40a786439ef", "size": 2417, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/random/cauchy_distribution.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vegastrike/boost/1_28/boost/random/cauchy_distribution.hpp", "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vegastrike/boost/1_28/boost/random/cauchy_distribution.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["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.3896103896, "max_line_length": 79, "alphanum_fraction": 0.726934216, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.51322281730414}}
{"text": "/* mcgs.cpp\n\n  Monte-Carlo simulation of group sizes under bivariate (possibly contaminated) normal distribution\n\n  Requirements:\n\n  sudo apt-get install libboost-all-dev\n\n  Building:\n  \n  g++ -O3 -Wall -Wextra -std=c++11 -march=native -g -o mcgs mcgs.cpp\n\n*/\n#include <vector>\n#include <map>\n#include <cmath>\n#include <numeric>\n#include <complex>\n#include <random>\n#include <iostream>\n#include <memory>\n#include <stdlib.h>\n#include <algorithm>\n#include <boost/math/distributions/chi_squared.hpp>\n\n// Abstract base class (interface) for random shot group generator, implementations follow\nclass RandomNumberGenerator {\n  public:\n    virtual void advance() = 0;\n    virtual void reset() = 0;\n    virtual std::complex<double> point(unsigned dimension) = 0;\n};\n\n//\n// Baseline pseudorandom number generator, wraps the default provided by standard library\n//\nclass DefaultRandomNumberGenerator : public RandomNumberGenerator {\n    std::default_random_engine gen_;\n    std::normal_distribution<double> dist_;\n  \n  public:\n    DefaultRandomNumberGenerator() \n    {\n      reset();\n    }\n  \n    void advance() {}\n\n    void reset() \n    {\n      gen_.seed(42);\n    }\n\n    std::complex<double> point(unsigned dimension __attribute__((unused)))\n    {\n      return std::complex<double>(dist_(gen_), dist_(gen_));\n    }\n};\n\n\n// MCG 128 from http://www.pcg-random.org/posts/on-vignas-pcg-critique.html\nclass FastRandomNumberGenerator : public RandomNumberGenerator {\n  __uint128_t state_;\n  \n  public:\n    FastRandomNumberGenerator() \n    {\n      reset();\n    }\n  \n    void advance() {}\n\n    void reset() \n    {\n      state_ = 1;   // can be seeded to any odd number\n    }\n\n    std::complex<double> point(unsigned dimension __attribute__((unused)))\n    {\n      for (;;) {\n        double u = ldexp(next(), -64);\n        double v = ldexp(next(), -64);\n        // Box-Muller transform\n        double r = sqrt(-2 * log(u));\n        double x = r * cos(2 * M_PI * v);\n        double y = r * sin(2 * M_PI * v);\n        if (isfinite(x) && isfinite(y)) {\n          return std::complex<double>(x, y);\n        }\n      }\n    }\n\n  private:\n    inline uint64_t next()\n    {\n      return (state_ *= 0xda942042e4dd58b5ULL) >> 64;\n    }\n};\n\n// \n// Additive quasi-random generator\n//\n// To get the next point, add a fixed step modulo 1 to the previous point. \n//\nclass AdditiveRandomNumberGenerator: public RandomNumberGenerator {\n    std::vector<double> x_;\n    std::vector<double> step_;\n\n  public:\n    explicit AdditiveRandomNumberGenerator(unsigned dimensions)\n#if 0\n    // Use square roots of prime numbers as steps because they are irrational.\n    {\n      unsigned nprimes = dimensions * 2; // Two coordinates for each point\n      x_.resize(nprimes);\n      step_.resize(nprimes);\n      //\n      // To initialize the steps, we need to find some prime numbers. Do that with \n      // sieve of Eratosthenes.\n      //\n      // To estimate how big the sieve should be to get nprimes primes, start with \n      // approximation by Gauss and Legendre:\n      //\n      //   nprimes = PrimePi(x) ~ x/log(x)\n      //\n      // Here PrimePi(x) is prime-counting function: number of prime numbers that are \n      // less than or equal to x. This is a lower bound for all but the lowest values\n      // of x (which we'll handle separately), so x will be slightly larger than strictly \n      // necessary.\n      //\n      // To solve for x without resorting to Lambert-W function, rewrite as follows:\n      //\n      //   x ~ nprimes * log(x)\n      //\n      // Now use fixed point iteration to find x. Stop iterating when the whole part\n      // of x stops changing.\n      // \n      unsigned sieve_size = 0;\n      if (nprimes < 5) {  // Approximation breaks below 5, floor sieve_size\n        sieve_size = 7;\n      } else {\n        double x = nprimes;\n        for (unsigned i = 0; i < 30; i++) {\n          unsigned before = (unsigned)ceil(x);\n          x = nprimes * log(x); // Fixed point iteration\n          unsigned after = (unsigned)ceil(x);\n          if (before == after) {\n            sieve_size = before;\n            break;\n          }      \n        }\n        if (sieve_size == 0) {\n          std::cerr << \"Fixed point iteration failed to converge\\n\";\n          exit(-1);\n        }\n      }\n    \n      // The sieve itself\n      std::vector<bool> prime(sieve_size + 1, true);\n      unsigned top = sqrt(sieve_size);\n      for (unsigned i = 2; i < top; i++) {\n        if (prime.at(i)) {\n          for(unsigned j = i * i; j <= sieve_size; j += i) {\n            prime.at(j) = false;\n          }\n        }\n      }\n    \n      // Collect prime numbers left in the sieve, take square roots, assign to steps.\n      unsigned index = 0;\n      for (unsigned j = 2; index < nprimes; j++) {\n        if (j >= sieve_size) {\n          std::cerr << \"Ran out of primes\\n\"; // Shouldn't happen if we did the math right\n          exit(-1);\n        }\n        if (prime[j]) {\n          step_.at(index++) = sqrt(j);\n        }\n      }\n    }\n#else\n    // Rd quasi-random sequences http://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/\n    // In d dimensions, g is positive real root of f(x) = x ** (d + 1) - x - 1 = 0\n    // 3D example:\n    // g = 1.22074408460575947536\n    // a1 = 1.0/g\n    // a2 = 1.0/(g*g)\n    // a3 = 1.0/(g*g*g)\n    // x[n] = (0.5+a1*n) %1\n    // y[n] = (0.5+a2*n) %1\n    // z[n] = (0.5+a3*n) %1\n    {\n      unsigned d = dimensions * 2; // Two coordinates for each point\n      x_.resize(d);\n      step_.resize(d);\n      double x = 1.5; // initial approximation\n      for (unsigned i = 0; i < 30; i++) { // Newton-Raphson\n        double xd = 1;\n        for (unsigned j = 0; j < d; j++) {\n          xd *= x;\n        }\n        double adjustment = (xd * x - x - 1) / ((d + 1) * xd - 1);\n        x -= adjustment;\n        if (std::abs(adjustment) < 1E-16) {\n          break;\n        }\n      }\n      double a = 1.;\n      for (unsigned i = 0; i < d; i++) {\n        a /= x;\n        x_.at(i) = 0.5;\n        step_.at(i) = a;\n      }\n    }\n#endif\n  \n    void advance()\n    {\n      for (unsigned j = 0; j < step_.size(); j++) {\n        double int_part;\n        x_.at(j) = modf(x_.at(j) + step_.at(j), &int_part);\n      }\n    }\n\n    void reset()\n    {\n      for (unsigned j = 0; j < step_.size(); j++) {\n        x_.at(j) = 0;\n      }\n    }\n\n    std::complex<double> point(unsigned dimension)\n    {\n      double x, y;\n      if (dimension >= step_.size() / 2) {\n        x = y = std::numeric_limits<double>::quiet_NaN();\n      } else {\n        double u = x_.at(dimension);\n        double v = x_.at(dimension + step_.size() / 2);\n        // Box-Muller transform\n        double r = sqrt(-2 * log(u));\n        x = r * cos(2 * M_PI * v);\n        y = r * sin(2 * M_PI * v);\n      }\n      return std::complex<double>(x, y);\n    }\n};\n\n//\n// Sobol quasi-random number generator\n//\nclass SobolRandomNumberGenerator : public RandomNumberGenerator {\n    unsigned x_[20];\n    unsigned v_[20][32 + 1];\n    unsigned i_;\n  \npublic:\n    explicit SobolRandomNumberGenerator(unsigned dimensions): i_(0)\n    {\n      // Primitive polynomials and initial direction numbers for the first 20 dimensions\n      // recommended by Stephen Joe and Frances Kuo in new-joe-kuo-6.21201\n      // http://web.maths.unsw.edu.au/~fkuo/sobol/index.html\n      const unsigned s[20] = {1, 2, 3, 3, 4, 4, 5, 5, 5,  5,  5, 5,  6,  6,  6,  6,  6,  6, 7, 7};\n      const unsigned a[20] = {0, 1, 1, 2, 1, 4, 2, 4, 7, 11, 13, 14, 1, 13, 16, 19, 22, 25, 1, 4};\n      const unsigned m[20][7] = {\n        {1, 0, 0,  0,  0,  0,   0},\n        {1, 3, 0,  0,  0,  0,   0},\n        {1, 3, 1,  0,  0,  0,   0},\n        {1, 1, 1,  0,  0,  0,   0},\n        {1, 1, 3,  3,  0,  0,   0},\n        {1, 3, 5, 13,  0,  0,   0},\n        {1, 1, 5,  5, 17,  0,   0},\n        {1, 1, 5,  5,  5,  0,   0},\n        {1, 1, 7, 11, 19,  0,   0}, \n        {1, 1, 5,  1,  1,  0,   0},\n        {1, 1, 1,  3, 11,  0,   0}, \n        {1, 3, 5,  5, 31,  0,   0}, \n        {1, 3, 3,  9,  7, 49,   0}, \n        {1, 1, 1, 15, 21, 21,   0}, \n        {1, 3, 1, 13, 27, 49,   0}, \n        {1, 1, 1, 15,  7,  5,   0}, \n        {1, 3, 1, 15, 13, 25,   0}, \n        {1, 1, 5,  5, 19, 61,   0}, \n        {1, 3, 7, 11, 23, 15, 103}, \n        {1, 3, 7, 13, 13, 15,  69} \n      };\n      if (dimensions > 10) {\n        std::cerr << \"Sobol direction numbers available for at most 10 shot group\\n\";\n        exit(-1);\n      }\n      for (unsigned j = 0; j < 20; j++) {\n        if (j == 0) {\n          for (unsigned i = 0; i < 32; i++) {\n            v_[j][i] = 1 << (32 - i - 1);\n          }\n        } else {\n          unsigned ss = s[j - 1];\n          for (unsigned i = 0; i < ss; i++) {\n            v_[j][i] = m[j - 1][i] << (32 - i - 1);\n          }\n          for (unsigned i = ss; i < 32; i++) {\n\t        v_[j][i] = v_[j][i - ss] ^ (v_[j][i - ss] >> ss); \n\t        for (unsigned k = 1; k < ss; k++) { \n\t          v_[j][i] ^= (((a[j - 1] >> (ss - 1 - k)) & 1) * v_[j][i - k]);\n\t        } \n          }\n        }\n        x_[j] = 0;\n      }\n      \n      // Burn-in: discard initial values\n      for (unsigned i = 0; i < 32; i++) {\n        advance();\n      }\n    }\n    \n    void reset()\n    {\n      for (unsigned j = 0; j < 20; j++) {\n        x_[j] = 0;\n      }\n    }\n\n    void advance()\n    {\n      unsigned b = i_++;\n      unsigned z = 0; // Position of the first zero bit in binary representation of i_\n                      // counting from the right\n      if (b) {\n        while (b & 1) {\n          b >>= 1;\n          z++;\n        }\n      }\n      for (unsigned j = 0; j < 20; j++) {\n        x_[j] ^= v_[j][z];\n      }\n    }\n    \n    std::complex<double> point(unsigned dimension)\n    {\n      double x, y;\n      if (dimension >= 10) {\n        x = y = std::numeric_limits<double>::quiet_NaN();\n      } else {\n        double u = ldexp(x_[dimension], -32);\n        double v = ldexp(x_[dimension + 10], -32);\n\n        // Box-Muller transform\n        double r = sqrt(-2 * log(u));\n        x = r * cos(2 * M_PI * v);\n        y = r * sin(2 * M_PI * v);\n      }\n      return std::complex<double>(x, y);\n    }\n};\n\nstruct ConvexHullPoint {\n  public:  \n    explicit ConvexHullPoint(const std::complex<double>& p) : point_(p) {}\n  \n    // For lexicographic sort: first by x, then by y\n    bool operator<(const ConvexHullPoint& other) const\n    {\n      if (point_.real() < other.point_.real()) {\n        return true;\n      } else if (point_.real() > other.point_.real()) {\n        return false;\n      } else {\n        return point_.imag() < other.point_.imag();\n      }\n    }\n\n    bool operator!=(const std::complex<double>& other) const\n    {\n      return point_ != other;\n    }\n  \n    // Distance to another point\n    double distanceTo(const ConvexHullPoint& other) const\n    {\n      return std::abs(point_ - other.point_);\n    }\n\n    double inline x(void) const { return point_.real(); }\n    double inline y(void) const { return point_.imag(); }\n\n  private:\n    std::complex<double> point_;\n};\n\nclass ShotGroup {\n  private:\n    // Use complex type to store impact coordinates\n    std::vector<std::complex<double> > impact_;\n  \n    // Cross product of vectors OA and OB, positive if OAB makes a CCW turn\n    double cross_product( const ConvexHullPoint& O\n                        , const ConvexHullPoint& A\n                        , const ConvexHullPoint& B\n                        ) const\n    {\n      return (A.x() - O.x()) * (B.y() - O.y())\n           - (A.y() - O.y()) * (B.x() - O.x());\n    }\n\n    double distance(unsigned a, unsigned b) const\n    {\n      return std::abs(impact_.at(a) - impact_.at(b));\n    }\n    \n  public:\n    void add(const std::complex<double>& p)\n    {\n      impact_.push_back(p);\n    }\n    \n    // Brute force implementation, asymptotic complexity O(N^2)\n    double group_size_brute_force(double* excluding_worst = NULL) const\n    {\n      unsigned n = impact_.size();\n      if (n < 2) {\n        if (excluding_worst) {\n          *excluding_worst = 0;\n        }\n        return 0;\n      }\n      \n      // Find the two impacts defining extreme spread\n      double extreme_spread = 0;\n      unsigned index_a = 0;\n      unsigned index_b = 0;\n      for (unsigned i = 0; i < n - 1; i++) {\n        for (unsigned j = i + 1; j < n; j++) {\n          double candidate = distance(i, j);\n          if (extreme_spread < candidate) {\n            extreme_spread = candidate;\n            index_a = i;\n            index_b = j;\n          }\n        }\n      }\n      \n      if (excluding_worst) {\n        // Worst shot must be one of the impacts defining extreme spread.\n        // Calculate group size without either one, return the smaller number.\n        double extreme_spread_excluding_a = 0;\n        double extreme_spread_excluding_b = 0;\n        for (unsigned i = 0; i < n - 1; i++) {\n          for (unsigned j = i + 1; j < n; j++) {\n            double candidate = distance(i, j);\n            if (i != index_a && j != index_a && extreme_spread_excluding_a < candidate) {\n              extreme_spread_excluding_a = candidate;\n            }\n            if (i != index_b && j != index_b && extreme_spread_excluding_b < candidate) {\n              extreme_spread_excluding_b = candidate;\n            }\n          }\n        }\n        *excluding_worst = std::min(extreme_spread_excluding_a, extreme_spread_excluding_b);\n      }\n      return extreme_spread;\n    }\n\n    // Same as group_size_brute_force(), but using convex hull.\n    // Asymptotic complexity O(N log N).\n    //\n    // Pass 0: find impacts a and b defining extreme spread. \n    //         Return extreme spread if excluding_worst == false.\n    // Pass 1: find extreme spread excluding a\n    // Pass 2: find extreme spread excluding b\n    //\n    // Return the smaller of extreme spread excluding a and extreme spread excluding b\n    //\n    double group_size_convex_hull(double* excluding_worst = NULL) const\n    {\n      unsigned n = impact_.size();\n      if (n < 2) {\n        if (excluding_worst) {\n          *excluding_worst = 0;\n        }\n        return 0;\n      }\n      double extreme_spread = 0;\n      ConvexHullPoint a(impact_.at(0)); double extreme_spread_excluding_a = 0;\n      ConvexHullPoint b(impact_.at(1)); double extreme_spread_excluding_b = 0;\n      for (unsigned pass = 0; pass < 3; pass++) {\n\n        // Use Andrew's monotone chain 2D algorithm to construct convex hull \n        std::vector<ConvexHullPoint> lower_hull;\n        std::vector<ConvexHullPoint> upper_hull;\n        {\n          std::vector<ConvexHullPoint> p;\n          for (unsigned i = 0; i < n; i++) {\n            if ( pass == 0\n              || ((pass == 1) && (a != impact_.at(i)))\n              || ((pass == 2) && (b != impact_.at(i)))\n               )\n            p.push_back(ConvexHullPoint(impact_.at(i)));\n          }\n          std::sort(p.begin(), p.end());\n      \n          unsigned k = 0;\n          for (unsigned i = 0; i < p.size(); i++) { // lower hull\n            while (k >= 2 && cross_product(lower_hull.at(k - 2), lower_hull.at(k - 1), p.at(i)) <= 0) {\n              lower_hull.pop_back();\n              k--;\n            }\n            lower_hull.push_back(p.at(i));\n            k++;\n          }\n          k = 0;\n          for (unsigned i = 0; i < p.size(); i++) { // upper hull\n            while (k >= 2 && cross_product(upper_hull.at(k - 2), upper_hull.at(k - 1), p.at(i)) >= 0) {\n              upper_hull.pop_back();\n              k--;\n            }\n            upper_hull.push_back(p.at(i));\n            k++;\n          }\n        }\n\n        // Use rotating calipers algoritm to find most distant antipodal pair of hull points\n        double diameter = 0;\n        {\n          unsigned i = 0;\n          unsigned j = lower_hull.size() - 1;\n          while (i < upper_hull.size() - 1 || j > 0) {\n            double d = upper_hull.at(i).distanceTo(lower_hull.at(j));\n            if (diameter < d) {\n              diameter = d;\n              if (pass == 0) {\n                a = upper_hull.at(i);\n                b = lower_hull.at(j);\n              }\n            }\n            if (i == upper_hull.size() - 1) {\n              j--;\n            } else if (j == 0) {\n              i++;\n            } else if ( (upper_hull.at(i + 1).y() - upper_hull.at(i).y()) \n                      * (lower_hull.at(j).x() - lower_hull.at(j - 1).x())\n                      > (upper_hull.at(i + 1).x() - upper_hull.at(i).x()) \n                      * (lower_hull.at(j).y() - lower_hull.at(j - 1).y())\n                      ) {\n              i++;\n            } else {\n              j--;\n            }\n          }\n        }\n        switch (pass) {\n          case 0:\n            if (excluding_worst) {\n              extreme_spread = diameter;\n              break;\n            }\n            return diameter;\n          case 1:\n            extreme_spread_excluding_a = diameter;\n            break;\n          case 2:\n            extreme_spread_excluding_b = diameter;\n            break;\n        }\n      }\n      *excluding_worst = std::min(extreme_spread_excluding_a, extreme_spread_excluding_b);\n      return extreme_spread;\n    }\n    \n    // As per NSD (page 181) should be within 15 cm at 100 m\n    // Group size 2.79295 corresponds to kuchnost~=3.15863,\n    // so this is equivalent to 4.56 MOA.\n    double nsd_kuchnost(void) const\n    {\n      // Only defined for 4 shot groups\n      if (impact_.size() != 4) return std::numeric_limits<double>::quiet_NaN();\n      \n      // STP using all 4 shots\n      auto stp = (impact_.at(0) + impact_.at(1) + impact_.at(2) + impact_.at(3)) / 4.;\n      \n      // Minimum radius of circle with center at STP that encloses all shots \n      double r = 0;\n      for (unsigned i = 0; i < 4; i++) {\n        double candidate = std::abs(stp - impact_.at(i));\n        if (r < candidate) {\n          r = candidate;\n        }\n      }\n      \n      // Exclude outlier, if any\n      for (unsigned i = 0; i < 4; i++) {\n      \n        // STP excluding this shot\n        auto stp3 = (stp * 4. - impact_.at(i)) / 3.;\n        \n        // Minimum radius of circle with center at STP of three shots excluding this shot\n        double r2 = 0;\n        for (unsigned j = 0; j < 4; j++) {\n          if (i == j) {\n            continue;\n          }\n          double candidate = std::abs(stp - impact_.at(i));\n          if (r2 < candidate) {\n            r2 = candidate;\n          }\n        }\n\n        // Outlier is a shot 2.5x or more distant from STP of other three shots\n        // than radius of the circle centered as STP of other three shots\n        // that covers these three shots\n        if (std::abs(stp3 - impact_.at(i)) > 2.5 * r2 && r > r2) {\n          r = r2;\n        }\n      }\n      \n      // Diameter\n      return 2 * r;\n    }\n\n    double avg_miss_radius(void) const\n    {\n      unsigned n = impact_.size();\n      if (n < 2) return std::numeric_limits<double>::quiet_NaN();\n      std::complex<double> center = 0;\n      for (unsigned i = 0; i < n; i++) {\n        center += impact_.at(i);\n      }\n      center /= n;\n      double amr = 0;\n      for (unsigned i = 0; i < n; i++) {\n        amr += std::abs(impact_.at(i) - center);\n      }\n      amr /= n;\n      return amr;\n    }\n\n    //\n    // Ballistic Accuracy Class (before rounding)\n    //\n    // Find location of group center (mean)\n    // For each shot i, find its radius squared (r2) relative to group center\n    // Upper 90% confidence value sigma_U=SQRT(SUM(r2)/CHIINV(0.9,2n-2))\n    // Ballistic Accuracy Class is ROUND(sigma_U,0)\n    //\n    // http://ballistipedia.com/index.php?title=Ballistic_Accuracy_Classification\n    //\n    double bac(void) const\n    {\n      unsigned n = impact_.size();\n      if (n < 2) return std::numeric_limits<double>::quiet_NaN();\n      std::complex<double> center = 0;\n      for (unsigned i = 0; i < n; i++) {\n        center += impact_.at(i);\n      }\n      center /= n;\n      double sum_r2 = 0;\n      for (unsigned i = 0; i < n; i++) {\n        sum_r2 += std::norm(impact_.at(i) - center);\n      }\n\n      // Memoized BAC factor (to avoid recalculating it for each group)\n      static unsigned memoized_n = 0;\n      static double memoized_factor = 0;\n      if (n != memoized_n) {\n        boost::math::chi_squared ch2(2 * n - 2);\n        double chisq_inv_rt = boost::math::quantile(ch2, 1 - 0.9);\n        memoized_factor = 1 / sqrt(chisq_inv_rt);\n        memoized_n = n;\n      }\n\n      return memoized_factor * sqrt(sum_r2);\n    }\n\n    // Pairwise distances weighted by rank\n    double pdwr(bool trim = false) const\n    {\n      unsigned n = impact_.size();\n      \n      // Precomputed scaling factor to convert the result to sigma\n      double scaling_factor = 0;\n      switch (n) {\n        case  3: scaling_factor = trim ? 1 / 1.04273 : 1 / 2.00018; break;\n        case  4: scaling_factor = trim ? 1 / 1.31192 : 1 / 2.1068;  break;\n        case  5: scaling_factor = trim ? 1 / 1.46386 : 1 / 2.16243; break;\n        case  6: scaling_factor = trim ? 1 / 1.56703 : 1 / 2.19481; break;\n        case  7: scaling_factor = trim ? 1 / 1.64232 : 1 / 2.21542; break;\n        case  8: scaling_factor = trim ? 1 / 1.70089 : 1 / 2.22942; break;\n        case  9: scaling_factor = trim ? 1 / 1.74798 : 1 / 2.2394;  break;\n        case 10: scaling_factor = trim ? 1 / 1.78699 : 1 / 2.24684; break;\n        default: return std::numeric_limits<double>::quiet_NaN();\n      }\n\n      // Pairwise distances\n      std::vector<double> d;\n      for (unsigned i = 0; i < n; i++) {\n        for (unsigned j = i + 1; j < n; j++) {\n          d.push_back(std::abs(impact_.at(i) - impact_.at(j)));\n        }\n      }\n      std::sort(d.begin(), d.end());\n\n      // Average weighted by rank, possibly trimmed\n      double numerator = 0;\n      double denominator = 0;\n      unsigned m = d.size();\n      if (trim) {\n        m -= n - 1;\n      }\n      for (unsigned i = 0; i < m; i++) {\n        numerator += d.at(i) * (i + 1.);\n        denominator += (i + 1.);\n      }\n      return scaling_factor * numerator / denominator;\n    }\n\n    // Rank weighted mean of right winsorized pairwise distances\n    double rwmrwpd() const\n    {\n      unsigned n = impact_.size();\n\n      // Precomputed scaling factor to convert the result to sigma\n      double scaling_factor = 0;\n      switch (n) {\n        case  3: scaling_factor = 1 / 1.04273; break;\n        case  4: scaling_factor = 1 / 1.48818; break;\n        case  5: scaling_factor = 1 / 1.69422; break;\n        case  6: scaling_factor = 1 / 1.81984; break;\n        case  7: scaling_factor = 1 / 1.90066; break;\n        case  8: scaling_factor = 1 / 1.95899; break;\n        case  9: scaling_factor = 1 / 2.00215; break;\n        case 10: scaling_factor = 1 / 2.03579; break;\n        default: return std::numeric_limits<double>::quiet_NaN();\n      }\n      \n      // Pairwise distances\n      std::vector<double> d;\n      for (unsigned i = 0; i < n; i++) {\n        for (unsigned j = i + 1; j < n; j++) {\n          d.push_back(std::abs(impact_.at(i) - impact_.at(j)));\n        }\n      }\n      std::sort(d.begin(), d.end());\n\n      // Average weighted by rank and winsorized\n      double numerator = 0;\n      double denominator = 0;\n      unsigned m = d.size() - n;\n      for (unsigned i = 0; i < d.size(); i++) {\n        numerator += d.at(i < m ? i : m) * (i + 1.);\n        denominator += (i + 1.);\n      }\n      return scaling_factor * numerator / denominator;\n    }\n\n    // Qn with different rank\n    double tqn() const\n    {\n      unsigned n = impact_.size();\n      std::vector<double> d;\n      for (unsigned i = 0; i < n; i++) {\n        for (unsigned j = i + 1; j < n; j++) {\n          d.push_back(std::abs(impact_.at(i) - impact_.at(j)));\n        }\n      }\n      std::sort(d.begin(), d.end());\n      return d.at(d.size() - n);\n    }\n\n    // Square root of average of squared pairwise distances\n    double sraspd(bool trim = false) const\n    {\n      unsigned n = impact_.size();\n      if (n < 3 || n > 10) {\n        return std::numeric_limits<double>::quiet_NaN();\n      }\n\n      // Squares of pairwise distance\n      std::vector<double> d;\n      for (unsigned i = 0; i < n; i++) {\n        for (unsigned j = i + 1; j < n; j++) {\n          d.push_back(std::norm(impact_.at(i) - impact_.at(j)));\n        }\n      }\n\n      // Square root of average of squared pairwise distances, possibly trimmed\n      double sum_of_squares = 0;\n      unsigned m = d.size();\n      if (trim) {\n        m -= n - 1;\n        std::sort(d.begin(), d.end());\n      }\n      for (unsigned i = 0; i < m; i++) {\n        sum_of_squares += d.at(i);\n      }\n      return sqrt(sum_of_squares / m);\n    }\n\n    void show(void) const\n    {\n      for (unsigned i = 0; i < impact_.size(); i++) {\n        std::cout << \"g.add(std::complex<double>(\" << impact_.at(i).real() << \", \" << impact_.at(i).imag() << \"));\\n\";\n      }\n    }\n};\n\nclass DescriptiveStat\n{\n  public:\n    DescriptiveStat() : n_(0), m_(0), s_(0) {}\n    \n    void push(double x)\n    {\n      double new_m = m_ + (x - m_) / (++n_);\n      double new_s = s_ + (x - m_) * (x - new_m);\n      m_ = new_m;\n      s_ = new_s;\n    }\n\n    double mean(void) const\n    { \n      return (n_ > 0) ? m_ : std::numeric_limits<double>::quiet_NaN();\n    }\n\n    double variance(void) const\n    {\n      return (n_ > 1) ? s_ / (n_ - 1) : std::numeric_limits<double>::quiet_NaN();\n    }\n\n    double stdev(void) const\n    {\n      return sqrt(variance());\n    }\n\n    double cv(void) const\n    {\n      return stdev() / mean();\n    }\n\n    void show(const char* metric, double theoretical = 0, bool suppress_nan = false)\n    {\n      auto m = mean();\n      if (suppress_nan && !isfinite(m)) {\n        return;\n      }\n      std::cout << metric << \" mean=\" << m; \n      if (theoretical > 0) {\n        std::cout << \" (expected \" << theoretical << \")\";\n      }      \n      std::cout << \", CV=\" << cv() << \"\\n\";\n    }\n\n  private:\n    unsigned n_;\n    double m_;\n    double s_;\n};\n\nstatic double median(std::vector<double>& x)\n{\n  if (x.size() == 0) {\n    return std::numeric_limits<double>::quiet_NaN();\n  }\n  std::vector<double>::iterator median_it = x.begin() + x.size() / 2; \n  nth_element(x.begin(), median_it, x.end());\n  if (x.size() % 2) { // Odd number of elements\n    return *median_it;\n  }\n  // Even number of elements, return average of two elements in the middle\n  double b = *median_it--;\n  nth_element(x.begin(), median_it, x.end());\n  double a = *median_it;\n  return (a + b) / 2;  \n}\n\nint main(int argc, char* argv[])\n{\n  DefaultRandomNumberGenerator pseudo_rng;\n  long long experiments = 0;\n  if (argc > 1) {\n    experiments = atoi(argv[1]);\n    \n    // Self-test\n    if (experiments == 0) {\n      std::cout << \"Comparing group_size_brute_force() and group_size_convex_hull()\\n\";\n      {\n        double max_diff = 0;\n        for (unsigned i = 0; i < 1e6; i++) {\n          unsigned shots = (i & 0xf) + 2;\n          ShotGroup g;\n          pseudo_rng.advance();\n          for (unsigned j = 0; j < shots; j++) {\n            g.add(pseudo_rng.point(j));\n          }\n          double bf2 = 0, ch2 = 0;\n          double bf = g.group_size_brute_force((i & 0x10) ? &bf2 : NULL);\n          double ch = g.group_size_convex_hull((i & 0x10) ? &ch2 : NULL);\n          double diff_1 = fabs(bf - ch);\n          if (max_diff < diff_1) {\n            max_diff = diff_1;\n          }\n          if (diff_1 > 1e-8) {\n            std::cout << \"Expected group size \" << bf << \", got \" << ch << \"\\n\";\n            g.show();\n            return 0;\n          }\n          if (i & 0x10) {\n            double diff_2 = fabs(bf2 - ch2);\n            if (diff_2 > 1e-8) {\n              std::cout << \"Expected group size excluding worst \" << bf2 << \", got \" << ch2 << \"\\n\";\n              g.show();\n              return 0;\n            }\n            if (max_diff < diff_2) {\n              max_diff = diff_2;\n            }\n          }\n        }\n        std::cout << \"Max difference \" << max_diff << \"\\n\";\n      }\n      std::cout << \"\\tgroup_size_brute_force()\\tgroup_size_convex_hull()\\n\";\n      for (unsigned shots = 4; shots <= 256; shots *= 2) {\n        std::cout << shots << \" shots:\\t\";\n        pseudo_rng.reset();\n        time_t start_time;\n        time(&start_time);\n        double a = 0;\n        for (unsigned i = 0; i < 1e6; i++) {\n          ShotGroup g;\n          pseudo_rng.advance();\n          for (unsigned j = 0; j < shots; j++) {\n            g.add(pseudo_rng.point(j));\n          }\n          a += g.group_size_brute_force();\n        }\n        time_t end_time;\n        time(&end_time);\n        std::cout << (end_time - start_time) << \" \u00b5s, sum=\" << a;\n\n        pseudo_rng.reset();\n        std::cout << \"\\t\";\n        time(&start_time);\n        double b = 0;\n        for (unsigned i = 0; i < 1e6; i++) {\n          ShotGroup g;\n          pseudo_rng.advance();\n          for (unsigned j = 0; j < shots; j++) {\n            g.add(pseudo_rng.point(j));\n          }\n          b += g.group_size_convex_hull();\n        }\n        time(&end_time);\n        std::cout << (end_time - start_time) << \" \u00b5s, sum=\" << b << \"\\n\";\n      }\n      return 0;\n    }\n  } else {\n    std::cerr << \"Usage: mcgs experiments [[[[shots_in_group] groups_in_experiment] proportion_of_outliers] outlier_severity]\\n\"\n                 \"0 experiments to run a self-test,\\n\"\n                 \"negative experiments to use additive quasi-random number generator,\\n\"\n                 \"negative shots_in_group to use Sobol quasi-random number generator,\\n\"\n                 \"negative groups_in_experiment to use MCG 128 pseudo-random number generator\\n\";\n    return -1;\n  }\n  std::unique_ptr<RandomNumberGenerator> rng(std::unique_ptr<RandomNumberGenerator>(new DefaultRandomNumberGenerator()));\n  unsigned shots_in_group;\n  {\n    int isig = 5;\n    if (argc > 2) {\n      isig = atoi(argv[2]);\n    }\n    if (isig < 0) {\n      shots_in_group = (unsigned)(-isig);\n      std::cout << \"Using Sobol quasi-random number generator for impact coordinates\\n\";\n      rng = std::unique_ptr<RandomNumberGenerator>(new SobolRandomNumberGenerator(shots_in_group));\n    } else {\n      shots_in_group = (unsigned)(isig);\n    }\n  }\n  if (shots_in_group < 3) {\n    std::cerr << \"Shots in group = \" << shots_in_group << \", expected at least 3\\n\";\n    return -1;\n  }\n  if (experiments < 0) {\n    experiments = -experiments;\n    std::cout << \"Using additive quasi-random number generator for impact coordinates\\n\";\n    rng = std::unique_ptr<RandomNumberGenerator>(new AdditiveRandomNumberGenerator(shots_in_group));\n  }\n  unsigned groups_in_experiment = 1;\n  if (argc > 3) {\n    int igie = atoi(argv[3]);\n    if (igie < 0) {\n      igie = -igie;\n      std::cout << \"Using MCG 128 pseudo-random number generator for impact coordinates\\n\";\n      rng = std::unique_ptr<RandomNumberGenerator>(new FastRandomNumberGenerator());\n    }\n    groups_in_experiment = (unsigned)igie;\n  }\n  double proportion_of_outliers = 0.;\n  if (argc > 4) {\n    proportion_of_outliers = atof(argv[4]);\n  }\n  double outlier_severity = 10.;\n  if (argc > 5) {\n    outlier_severity = atof(argv[5]);\n  }\n  std::cout << experiments << \" experiments, \" << shots_in_group << \" shots in group\";\n  if (groups_in_experiment > 1) {\n    std::cout << \", \" << groups_in_experiment << \" groups per experiment\"; \n  }\n  std::cout << \"\\n\";\n  if (proportion_of_outliers > 0) {\n    std::cout << \"Using contaminated normal distribution: \" << \n    (proportion_of_outliers * 100) << \"% of observations are pulled from distribution with \" <<\n    outlier_severity << \" times higher deviation\\n\";\n  }\n  const double rayleigh_cep_factor = sqrt(4 * log(2) / M_PI) / shots_in_group; // 0.9394/shots\n  \n  double mle_factor = sqrt(log(2) / M_PI);\n  for (unsigned i = 0; i < shots_in_group; i++) {\n    mle_factor *= 4;\n    if (i != shots_in_group - 1) {\n      mle_factor *= i + 1;\n    }\n    mle_factor /= i + 1 + shots_in_group;\n  }\n  double wmr_to_r90hat_factor = 0;\n  double swmr_to_r90hat_factor = 0;\n  double swmrr_to_r90hat_factor = 0;\n  double gs_to_r90hat_factor = 0;\n  double sixtynine_to_r90hat_factor = 0;\n  double rayleigh_to_r90hat_factor = 0;\n  double mle_to_r90hat_factor = 0;\n  \n  // http://ballistipedia.com/images/7/7a/Statistical_Inference_for_Rayleigh_Distributions_-_Siddiqui%2C_1964.pdf\n  std::pair<unsigned, unsigned> sixtynine_rank( (unsigned)(0.639 * (shots_in_group + 1)) - 1\n                                              , (unsigned)(0.927 * (shots_in_group + 1)) - 1\n                                              );\n  if (shots_in_group == 10) { // Suboptimal, but more robust\n    sixtynine_rank.first = 6 - 1;\n    sixtynine_rank.second = 9 - 1;\n  }\n  if (groups_in_experiment == 1) {\n    switch (shots_in_group) {\n      case  1:\n        // wxMaxima: find_root(integrate(x*exp(-x^2/2)*exp(-x^2*k^2/2), x, 0, inf)=1-0.9, k, 1, 10);\n        wmr_to_r90hat_factor = 3;\n        break;\n      case  3: \n        // wxMaxima: find_root(integrate(3*x*(1-exp(-x^2/2))^2*exp(-x^2/2-k^2*x^2/2), x, 0, inf)=1-0.9, k, 1, 10);\n        wmr_to_r90hat_factor = 1.414213562373095;\n        break;\n      case  5: \n        // wxMaxima: find_root(integrate(5*x*(1-exp(-x^2/2))^4*exp(-x^2/2-k^2*x^2/2), x, 0, inf)=1-0.9, k, 1, 10);\n        wmr_to_r90hat_factor = 1.17215228421396;\n        // wxMaxima:\n        // assume(x>0,t>0,u>0,q>0,k>1);\n        // p(x):=20*x*(1-exp(-x^2/2))^3*exp(-x^2);\n        // c(k):=integrate(p(q)*exp(-q^2*k^2/2),q,0,inf);\n        // find_root(c(k)=1-0.9, k, 1, 2);\n        swmr_to_r90hat_factor = 1.578643529936508;\n        gs_to_r90hat_factor = 0.8;\n        break;\n      case 10: \n        // wxMaxima: find_root(integrate(90*x*(1-exp(-x^2/2))^8*exp(-x^2-k^2*x^2/2), x, 0, inf)=1-0.9, k, 1, 10);\n        swmr_to_r90hat_factor = 1.187140545277712;\n        swmrr_to_r90hat_factor = 1.2;\n        gs_to_r90hat_factor = 0.6;\n        break;\n      case 20: \n        rayleigh_to_r90hat_factor = 1.76;\n        mle_to_r90hat_factor = 0.35;\n        break;\n    }\n  } else if (groups_in_experiment == 2) {\n    switch (shots_in_group) {\n      case 1:\n        // wxMaxima:\n        // assume(x>0,t>0,u>0,q>0,k>1);\n        // p(x):=x*exp(-x^2/2);\n        // p2(t):=''(integrate(2*p(u)*p(2*t-u),u,0,2*t));\n        // c2(k):=romberg(p2(q)*exp(-q^2*k^2/2),q,0,10);\n        // find_root(c2(k)=1-0.9, k, 1, 3);\n        wmr_to_r90hat_factor = 2.22197649;\n        break;\n      case 3:\n        // wxMaxima: \n        // assume(x>0,t>0,u>0,q>0,k>1);\n        // p(x):=3*x*(1-exp(-x^2/2))^2*exp(-x^2/2);\n        // p2(t):=''(integrate(2*p(u)*p(2*t-u),u,0,2*t));\n        // c2(k):=romberg(p2(q)*exp(-q^2*k^2/2),q,0,10);\n        // find_root(c2(k)=1-0.9, k, 1, 3);\n        wmr_to_r90hat_factor = 1.28875916;\n        break;\n      case 5:\n        // wxMaxima:\n        // assume(x>0,t>0,u>0,q>0,k>1);\n        // p(x):=5*x*(1-exp(-x^2/2))^4*exp(-x^2/2);\n        // p2(t):=romberg(2*p(u)*p(2*t-u),u,0,2*t);\n        // c2(k):=romberg(p2(q)*exp(-q^2*k^2/2),q,0,10);\n        // find_root(c2(k)=1-0.9, k, 1, 1.3);\n        wmr_to_r90hat_factor = 1.10343798;\n        // wxMaxima:\n        // assume(x>0,t>0,u>0,q>0,k>1);\n        // p(x):=20*x*(1-exp(-x^2/2))^3*exp(-x^2);\n        // p2(t):=romberg(2*p(u)*p(2*t-u),u,0,2*t);\n        // c2(k):=romberg(p2(q)*exp(-q^2*k^2/2),q,0,10);\n        // find_root(c2(k)=1-0.9, k, 1, 2);\n        swmr_to_r90hat_factor = 1.478456;\n        break;\n      case 10:\n        // wxMaxima:\n        // assume(x>0,t>0,u>0,q>0,k>1);\n        // p(x):=90*x*(1-exp(-x^2/2))^8*exp(-x^2);\n        // p2(t):=romberg(2*p(u)*p(2*t-u),u,0,2*t);\n        // c2(k):=romberg(p2(q)*exp(-q^2*k^2/2),q,0,10);\n        // find_root(c2(k)=1-0.9, k, 1.1, 1.15);\n        swmr_to_r90hat_factor = 1.149216;\n        swmrr_to_r90hat_factor = 1.15;\n        break;\n    }\n  } else if (groups_in_experiment == 4) {\n    switch (shots_in_group) {\n      case  5:\n        swmr_to_r90hat_factor = 1.43;\n        gs_to_r90hat_factor = 0.723;\n        break;\n      default:\n        break;\n    }\n  } else if (groups_in_experiment == 5) {\n    switch (shots_in_group) {\n      case  5:\n        swmr_to_r90hat_factor = 1.42;\n        gs_to_r90hat_factor = 0.72;\n        break;\n      default:\n        break;\n    }\n  } else if (groups_in_experiment > 10) { // Asymptotic approximation for large number of groups in experiment\n    switch (shots_in_group) {\n      case  1:\n        // wxMaxima: float(sqrt(2*log(10))/integrate(x*exp(-x^2/2)*x, x, 0, inf));\n        wmr_to_r90hat_factor  = 1.712233160383746;\n        break;\n      case  3:\n        // wxMaxima: float(sqrt(2*log(10))/integrate(3*(1-exp(-x^2/2))^2*x*exp(-x^2/2)*x, x, 0, inf));\n        wmr_to_r90hat_factor  = 1.175960143568417;\n        break;\n      case  5:\n        // wxMaxima: float(sqrt(2*log(10))/integrate(5*(1-exp(-x^2/2))^4*x*exp(-x^2/2)*x, x, 0, inf));\n        wmr_to_r90hat_factor  = 1.037938194579831;\n\n        // wxMaxima: float(sqrt(2*log(10))/integrate(20*x*(1-exp(-x^2/2))^3*exp(-x^2)*x, x, 0, inf));\n        swmr_to_r90hat_factor = 1.38619009633813;\n\n        gs_to_r90hat_factor = 0.7;\n        break;\n      case 10:\n        // wxMaxima: float(sqrt(2*log(10))/integrate(90*x*(1-exp(-x^2/2))^8*exp(-x^2)*x, x, 0, inf));\n        swmr_to_r90hat_factor  = 1.112257194707586;\n        swmrr_to_r90hat_factor = 1.1;\n        gs_to_r90hat_factor = 0.7;\n        break;\n      case 20:\n        mle_to_r90hat_factor = 0.3414341089001782;\n        break;\n    }\n  }\n  if (shots_in_group == 10) {\n    switch (groups_in_experiment) {\n      case  1:\n        // wxMaxima:\n        // assume(x>0,y>0,x<=y,k>0);\n        // pdf(x,y):=3*7*8*9*10*(1-exp(-x^2/2))^5*(exp(-x^2/2)-exp(-y^2/2))^2*exp(-y^2/2)*x*exp(-x^2/2)*y*exp(-y^2/2);\n        // find_root(romberg(integrate(pdf(x,y)*(1-exp(-(k*(x+y))^2/2)),y,x,inf),x,0,50)=9/10,k,0.6,0.8);\n        sixtynine_to_r90hat_factor = 0.7076687;\n        break;\n      case 2:\n        // wxMaxima:\n        // assume(x>0,y>0,x<=y);\n        // pdf(x,y):=15120*(1-exp(-x^2/2))^5*(exp(-x^2/2)-exp(-y^2/2))^2*exp(-y^2/2)*x*exp(-x^2/2)*y*exp(-y^2/2);\n        // assume(u>0,v>0,v<=u);\n        // p2(u):=romberg(pdf((u-v)/2,(u+v)/2)/2,v,0,u);\n        // p2s(t):=romberg(2*p2(u)*p2(2*t-u),u,0,2*t);\n        // c2(k):=romberg(p2s(q)*exp(-q^2*k^2/2),q,0,10);\n        // find_root(c2(k)=1/10, k, 0.6, 0.8);\n        sixtynine_to_r90hat_factor = 0.68860849;\n        break;\n      default:\n        // wxMaxima:\n        // assume(x>0,y>0,x<=y);\n        // pdf(x,y):=3*7*8*9*10*(1-exp(-x^2/2))^5*(exp(-x^2/2)-exp(-y^2/2))^2*exp(-y^2/2)*x*exp(-x^2/2)*y*exp(-y^2/2);\n        // float(sqrt(2*log(10)))/float(integrate(integrate(pdf(x,y)*(x+y),y,x,inf),x,0,inf));\n        sixtynine_to_r90hat_factor = 0.67024464399177286;\n        break;\n    }\n  }\n  DescriptiveStat gs_s, gs_s2, bgs_s, ags_s, ags_s2, mgs_s, wgs_s, amr_s, bac_s, pdwr_s, pdwr2_s, \n                  sraspd_s, sraspd2_s, tqn_s, rwmrwpd_s, aamr_s, rayleigh_s, \n                  rwr_s, mle_s, median_r_s;\n  DescriptiveStat worst_r_s, second_worst_r_s, rwr9_s;\n  std::map< std::pair<unsigned, unsigned>, DescriptiveStat> sixtynine_r_s;\n  DescriptiveStat nsd_s, wr_s, swr_s, sixtynine_s;\n  unsigned hits_wmr = 0;\n  unsigned hits_swmr = 0;\n  unsigned hits_swmrr = 0;\n  unsigned hits_gs = 0;\n  unsigned hits_sixtynine = 0;\n  unsigned hits_rayleigh = 0;\n  unsigned hits_mle = 0;\n  unsigned bac_gt_1_ct = 0;\n  double r90hat_wmr = 0;\n  double r90hat_swmr = 0;\n  double r90hat_swmrr = 0;\n  double r90hat_gs = 0;\n  double r90hat_sixtynine = 0;\n  double r90hat_rayleigh = 0;\n  double r90hat_mle = 0;\n  std::default_random_engine outlier_generator;\n  std::uniform_real_distribution<double> outlier_distribution;\n  for (unsigned experiment = 0; experiment < experiments; experiment++) {\n    double best_gs = 0, worst_gs = 0;\n    DescriptiveStat gs, gs2, amr, wr, swr, sixtynine, rayleigh, mle;\n    std::vector<double> gsg_v;\n    for (unsigned j = 0; j < groups_in_experiment; j++) { \n      ShotGroup g; \n      rng->advance();\n      std::vector<double> r;\n      std::vector<double> r2;\n      for (unsigned i = 0; i < shots_in_group; i++) {\n        std::complex<double> p = rng->point(i);\n        if ( proportion_of_outliers > 0 \n          && outlier_distribution(outlier_generator) < proportion_of_outliers\n           ) {\n          p *= outlier_severity;\n        }\n        double ri = std::abs(p);\n        g.add(p);\n        r.push_back(ri);\n        r2.push_back(ri*ri);\n\n        // Use R90 estimates based on previous experiment to avoid correlation\n        if (experiment != 0) { // If there is a prior group\n          if (ri < r90hat_wmr) hits_wmr++;\n          if (ri < r90hat_swmr) hits_swmr++;\n          if (ri < r90hat_swmrr) hits_swmrr++;\n          if (ri < r90hat_gs) hits_gs++;\n          if (ri < r90hat_sixtynine) hits_sixtynine++;\n          if (ri < r90hat_rayleigh) hits_rayleigh++;\n          if (ri < r90hat_mle) hits_mle++;\n        }\n      } // Next shot\n\n      std::sort(r.begin(), r.end()); // We'll need many ranks, faster to sort once\n\n      double this_minus1 = 0;\n      double this_gs = (shots_in_group < 32) \n                     ? g.group_size_brute_force(&this_minus1) \n                     : g.group_size_convex_hull(&this_minus1);\n      gs_s.push(this_gs);\n      gsg_v.push_back(this_gs);\n      gs_s2.push(this_minus1);\n      gs2.push(this_minus1);\n      if (shots_in_group == 4) {\n        nsd_s.push(g.nsd_kuchnost());\n      }\n      if (j) {\n        if (best_gs > this_gs) {\n          best_gs = this_gs;\n        }\n        if (worst_gs < this_gs) {\n          worst_gs = this_gs;\n        }\n      } else {\n        best_gs = this_gs;\n        worst_gs = this_gs;\n      }\n      gs.push(this_gs);\n\n      double this_amr = g.avg_miss_radius();\n      amr_s.push(this_amr);\n      amr.push(this_amr);\n\n      double this_bac = g.bac();\n      bac_s.push(this_bac);\n      if (this_bac > 1) {\n        bac_gt_1_ct++;\n      }\n      pdwr_s.push(g.pdwr());\n      pdwr2_s.push(g.pdwr(true));\n      sraspd_s.push(g.sraspd());\n      sraspd2_s.push(g.sraspd(true));\n      tqn_s.push(g.tqn());\n      rwmrwpd_s.push(g.rwmrwpd());\n\n      double this_rayleigh = rayleigh_cep_factor * accumulate(r.begin(), r.end(), 0.);\n      rayleigh.push(this_rayleigh);\n      rayleigh_s.push(this_rayleigh);\n\n      {\n        double rwr = 0, rwr9 = 0;\n        for (unsigned i = 0; i < r.size(); i++) {\n          rwr += r.at(i) * (i + 1);\n          if (i < r.size() - 1) {\n            rwr9 += r.at(i) * (i + 1);\n          }\n        }\n        rwr_s.push(2 * rwr / (r.size() * (r.size() - 1)));\n        rwr9_s.push(2 * rwr9 / ((r.size() - 1) * (r.size() - 2)));\n      }\n      \n      double this_mle = sqrt(accumulate(r2.begin(), r2.end(), 0.));\n      mle.push(this_mle);\n      mle_s.push(mle_factor * this_mle);\n      \n      double this_wr = r.at(shots_in_group - 1);\n      wr.push(this_wr);\n      worst_r_s.push(this_wr);\n      \n      double this_swr = r.at(shots_in_group - 2);\n      swr.push(this_swr);\n      second_worst_r_s.push(this_swr);\n            \n      double med = median(r);\n      median_r_s.push(med);\n      \n      if (sixtynine_rank.first != sixtynine_rank.second) {\n        double this_sixtynine = r.at(sixtynine_rank.first) + r.at(sixtynine_rank.second);\n        sixtynine.push(this_sixtynine);\n        if (shots_in_group <= 100) {\n          // Remember all rank pairs, will choose the best one later\n          for (unsigned rank_a = 0; rank_a < shots_in_group - 1; rank_a++) {\n            for (unsigned rank_b = rank_a + 1; rank_b < shots_in_group; rank_b++) {\n              double e = r.at(rank_a) + r.at(rank_b);\n              sixtynine_r_s[std::make_pair(rank_a, rank_b)].push(e);\n            }\n          }\n        }\n      }\n    } // Next group\n    if (groups_in_experiment > 1) {\n      bgs_s.push(best_gs);\n      wgs_s.push(worst_gs);\n      ags_s.push(gs.mean());\n      ags_s2.push(gs2.mean());\n      mgs_s.push(median(gsg_v));\n      aamr_s.push(amr.mean());\n      wr_s.push(wr.mean());\n      swr_s.push(swr.mean());\n      sixtynine_s.push(sixtynine.mean());\n    }\n    r90hat_wmr = wr.mean()  * wmr_to_r90hat_factor;\n    r90hat_swmr = swr.mean() * swmr_to_r90hat_factor;\n    r90hat_swmrr = swr.mean() * swmrr_to_r90hat_factor;\n    r90hat_gs = gs.mean()  * gs_to_r90hat_factor;\n    r90hat_sixtynine = sixtynine.mean() * sixtynine_to_r90hat_factor;\n    r90hat_rayleigh = rayleigh.mean() * rayleigh_to_r90hat_factor / sqrt(4 * log(2) / M_PI);\n    if (shots_in_group == 20) {\n      r90hat_mle = mle.mean() * mle_to_r90hat_factor;\n    }\n  } // Next experiment\n  if (groups_in_experiment == 1) {\n    std::cout << \"--- Precision estimators ---\\n\"; \n    gs_s.show(\"Group size:\");\n    if (shots_in_group == 4) {\n      nsd_s.show(\"Kuchnost:\");\n    }\n    amr_s.show(\"Average Miss Radius:\");\n    double e = (proportion_of_outliers > 0 ? 0 : 1);\n    pdwr_s.show(\"Pairwise distances weighted by rank:\", e, true);\n    sraspd_s.show(\"Square root of average of squared pairwise distances:\", true);\n    bac_s.show(\"Ballistic Accuracy Class:\");\n    std::cout << \"Percent of groups with BAC>1: \" \n              << 100. * bac_gt_1_ct / groups_in_experiment / experiments << \"%, expected 90%\\n\";\n    std::cout << \"--- Robust precision estimators ---\\n\"; \n    gs_s2.show(\"Group size (excluding worst shot in group):\");\n    pdwr2_s.show(\"Pairwise distances weighted by rank, trimmed:\", e, true);\n    sraspd2_s.show(\"Square root of average of squared pairwise distances, trimmed:\", true);    \n    tqn_s.show(\"Tweaked Qn:\"); \n    rwmrwpd_s.show(\"Rank weighted mean of right Winsorized pairwise distances:\", e, true);\n    std::cout << \"--- Hit probability estimators ---\\n\"; \n    double theoretical_cep = 0;\n    if (proportion_of_outliers == 0) {\n      theoretical_cep =  sqrt(-2*log(0.5));\n    }\n    rayleigh_s.show(\"Rayleigh CEP estimator:\", theoretical_cep);\n    rwr_s.show(\"Rank weighted miss radius:\");\n    mle_s.show(\"Maximum likelihood CEP estimator:\", theoretical_cep);\n    double theoretical_worst = 0;\n    if (proportion_of_outliers == 0) {\n      switch (shots_in_group) {\n        case 3:\n          // wxMaxima: float(integrate(3*(1-exp(-x^2/2))^2*x*exp(-x^2/2)*x, x, 0, inf));\n          theoretical_worst = 1.824862890146495;\n          break;\n        case 5:\n          // wxMaxima: float(integrate(5*(1-exp(-x^2/2))^4*x*exp(-x^2/2)*x, x, 0, inf));\n          theoretical_worst = 2.067527755983637;\n          break;\n      }\n    }\n    worst_r_s.show(\"Worst miss radius:\", theoretical_worst);\n    std::cout << \"--- Robust hit probability estimators ---\\n\"; \n    median_r_s.show(\"Median CEP estimator:\"); // Not showing theoretical_cep because median has known bias\n    double theoretical_second_worst = 0;\n    double theoretical_sixtynine = 0;\n    if (proportion_of_outliers == 0) {\n      switch (shots_in_group) {\n        case 10:\n          // wxMaxima: float(integrate(90*x*(1-exp(-x^2/2))^8*exp(-x^2)*x, x, 0, inf));\n          theoretical_second_worst = 1.929379316672818;\n          \n          // wxMaxima:\n          // assume(x>0,y>0,x<=y);\n          // pdf(x,y):=3*7*8*9*10*(1-exp(-x^2/2))^5*(exp(-x^2/2)-exp(-y^2/2))^2*exp(-y^2/2)*x*exp(-x^2/2)*y*exp(-y^2/2);\n          // integrate(integrate(pdf(x,y)*(x+y),y,x,inf),x,0,inf);\n          theoretical_sixtynine = 3.201765293569168;\n          break;\n      }\n    }\n    second_worst_r_s.show(\"Second worst miss radius:\", theoretical_second_worst);\n    rwr9_s.show(\"Rank weighted miss radius (excluding worst):\");\n    std::cout << \"--- Combinations of two order statistics ---\\n\"; \n    // Find combination of two order statistics with lowest CV\n    {\n      unsigned best_pos = 0;\n      double best_cv = 0;\n      unsigned pos = 0;\n      for (auto it = sixtynine_r_s.begin(); it != sixtynine_r_s.end(); it++, pos++) {\n        if (pos == 0 || best_cv > it->second.cv()) {\n          best_cv = it->second.cv();\n          best_pos = pos; \n        }\n      }\n      pos = 0;\n      for (auto it = sixtynine_r_s.begin(); it != sixtynine_r_s.end(); it++, pos++) {\n        if (pos == best_pos) {\n          std::cout << \"Lowest CV pair: R\" << (it->first.first + 1) << \":\" << shots_in_group \n                    << \"+R\" << (it->first.second + 1) << \":\" << shots_in_group;\n          it->second.show(\",\");\n          it = sixtynine_r_s.find(sixtynine_rank);\n          if (it != sixtynine_r_s.end()) {\n            std::cout << \"R\" << (sixtynine_rank.first  + 1) << \":\" << shots_in_group \n                      << \"+R\" << (sixtynine_rank.second + 1) << \":\" << shots_in_group;\n            it->second.show(\",\", theoretical_sixtynine);\n          }\n        }\n      }\n    }\n  } else {\n    bgs_s.show(\"Best group size:\");\n    ags_s.show(\"Average group size:\");\n    ags_s2.show(\"Average group size (excluding worst shot in group):\");\n    mgs_s.show(\"Median group size:\");\n    wgs_s.show(\"Worst group size:\");\n    aamr_s.show(\"Average of AMR of groups:\");\n    wr_s.show(\"Average worst miss radius:\");\n    swr_s.show(\"Average second worst miss radius:\");\n    if (sixtynine_rank.first != sixtynine_rank.second) {\n      std::cout << \"Average R\" << (sixtynine_rank.first  + 1) << \":\" << shots_in_group \n                << \"+R\"        << (sixtynine_rank.second + 1) << \":\" << shots_in_group;\n      sixtynine_s.show(\":\");\n    }\n  }  \n  std::cout << \"--- R90 estimators ---\\n\";\n  // -1 because we use previos experiment to set threshold for the next.\n  // First experiment does not participate because it does not have a previous.\n  double denominator = shots_in_group * ((double)groups_in_experiment * (experiments - 1));\n  if (wmr_to_r90hat_factor > 0) {\n    std::cout << \"Percent of hits within \" << wmr_to_r90hat_factor \n              << \" * worst miss radius: \" \n              << 100. * hits_wmr / denominator << \"%\\n\";\n  }\n  if (swmr_to_r90hat_factor > 0) {\n    std::cout << \"Percent of hits within \" << swmr_to_r90hat_factor\n              << \" * second worst miss radius: \" \n              << 100. * hits_swmr / denominator << \"%\\n\";\n  }\n  if (swmrr_to_r90hat_factor > 0) {\n    std::cout << \"Percent of hits within \" << swmrr_to_r90hat_factor \n              << \" * second worst miss radius: \" \n              << 100. * hits_swmrr / denominator << \"%\\n\";\n  }\n  if (gs_to_r90hat_factor > 0) {\n    std::cout << \"Percent of hits within \" << gs_to_r90hat_factor \n              << \" * group size: \" \n              << 100. * hits_gs / denominator << \"%\\n\";\n  }\n  if (sixtynine_to_r90hat_factor > 0) {\n    std::cout << \"Percent of hits within \" << sixtynine_to_r90hat_factor \n              << \" * (R\" << (sixtynine_rank.first  + 1) << \":\" << shots_in_group \n              << \" + R\"  << (sixtynine_rank.second + 1) << \":\" << shots_in_group << \"): \"\n              << 100. * hits_sixtynine / denominator << \"%\\n\";\n  }\n  if (rayleigh_to_r90hat_factor > 0) {\n    std::cout << \"Percent of hits within \" << rayleigh_to_r90hat_factor \n              << \" * average miss radius: \" \n              << 100. * hits_rayleigh / denominator << \"%\\n\";\n  }\n  if (mle_to_r90hat_factor > 0) {\n    std::cout << \"Percent of hits within \" << mle_to_r90hat_factor \n              << \" * square root of sum of squares: \" \n              << 100. * hits_mle / denominator << \"%\\n\";\n  }\n  return 0;\n}\n", "meta": {"hexsha": "f9f768cdb16235f7a64f13326b95209ea44bb130", "size": 50796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mcgs.cpp", "max_stars_repo_name": "lstange/mcgs", "max_stars_repo_head_hexsha": "bfce487095c42b3a8c54c8e10aebcd2189a02c62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T22:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-21T22:53:08.000Z", "max_issues_repo_path": "mcgs.cpp", "max_issues_repo_name": "lstange/mcgs", "max_issues_repo_head_hexsha": "bfce487095c42b3a8c54c8e10aebcd2189a02c62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mcgs.cpp", "max_forks_repo_name": "lstange/mcgs", "max_forks_repo_head_hexsha": "bfce487095c42b3a8c54c8e10aebcd2189a02c62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-11T04:03:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T04:03:42.000Z", "avg_line_length": 33.6843501326, "max_line_length": 128, "alphanum_fraction": 0.5351799354, "num_tokens": 15834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.51322281730414}}
{"text": "/* haertel.hpp file\r\n *\r\n * Copyright Jens Maurer 2000, 2002\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 * Revision history\r\n */\r\n\r\n/*\r\n * NOTE: This is not part of the official boost submission.  It exists\r\n * only as a collection of ideas.\r\n */\r\n\r\n#ifndef BOOST_RANDOM_HAERTEL_HPP\r\n#define BOOST_RANDOM_HAERTEL_HPP\r\n\r\n#include <boost/cstdint.hpp>\r\n#include <boost/random/linear_congruential.hpp>\r\n#include <boost/random/inversive_congruential.hpp>\r\n\r\nnamespace boost {\r\nnamespace random {\r\n\r\n// Wikramaratna 1989  ACORN\r\ntemplate<class IntType, int k, IntType m, IntType val>\r\nclass additive_congruential\r\n{\r\npublic:\r\n  typedef IntType result_type;\r\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\r\n  static const bool has_fixed_range = true;\r\n  static const result_type min_value = 0;\r\n  static const result_type max_value = m-1;\r\n#else\r\n  enum {\r\n    has_fixed_range = true,\r\n    min_value = 0,\r\n    max_value = m-1\r\n  };\r\n#endif\r\n  template<class InputIterator>\r\n  explicit additive_congruential(InputIterator start) { seed(start); }\r\n  template<class InputIterator>\r\n  void seed(InputIterator start)\r\n  {\r\n    for(int i = 0; i <= k; ++i, ++start)\r\n      values[i] = *start;\r\n  }\r\n  \r\n  result_type operator()()\r\n  {\r\n    for(int i = 1; i <= k; ++i) {\r\n      IntType tmp = values[i-1] + values[i];\r\n      if(tmp >= m)\r\n        tmp -= m;\r\n      values[i] = tmp;\r\n    }\r\n    return values[k];\r\n  }\r\n  result_type validation() const { return val; }\r\nprivate:\r\n  IntType values[k+1];\r\n};\r\n\r\n\r\ntemplate<class IntType, int r, int s, IntType m, IntType val>\r\nclass lagged_fibonacci_int\r\n{\r\npublic:\r\n  typedef IntType result_type;\r\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\r\n  static const bool has_fixed_range = true;\r\n  static const result_type min_value = 0;\r\n  static const result_type max_value = m-1;\r\n#else\r\n  enum {\r\n    has_fixed_range = true,\r\n    min_value = 0,\r\n    max_value = m-1\r\n  };\r\n#endif\r\n  explicit lagged_fibonacci_int(IntType start) { seed(start); }\r\n  template<class Generator>\r\n  explicit lagged_fibonacci_int(Generator & gen) { seed(gen); }\r\n  void seed(IntType start)\r\n  {\r\n    linear_congruential<uint32_t, 299375077, 0, 0, 0> init;\r\n    seed(init);\r\n  }\r\n  template<class Generator>\r\n  void seed(Generator & gen)\r\n  {\r\n    assert(r > s);\r\n    for(int i = 0; i < 607; ++i)\r\n      values[i] = gen();\r\n    current = 0;\r\n    lag = r-s;\r\n  }\r\n  \r\n  result_type operator()()\r\n  {\r\n    result_type tmp = values[current] + values[lag];\r\n    if(tmp >= m)\r\n      tmp -= m;\r\n    values[current] = tmp;\r\n    ++current;\r\n    if(current >= r)\r\n      current = 0;\r\n    ++lag;\r\n    if(lag >= r)\r\n      lag = 0;\r\n    return tmp;\r\n  }\r\n  result_type validation() const { return val; }\r\nprivate:\r\n  result_type values[r];\r\n  int current, lag;\r\n};\r\n\r\n} // namespace random\r\n} // namespace boost\r\n\r\n// distributions from Haertel's dissertation\r\n// (additional parameterizations of the basic templates)\r\nnamespace Haertel {\r\n  typedef boost::random::linear_congruential<boost::uint64_t, 45965, 453816691,\r\n    (boost::uint64_t(1)<<31), 0> LCG_Af2;\r\n  typedef boost::random::linear_congruential<boost::uint64_t, 211936855, 0,\r\n    (boost::uint64_t(1)<<29)-3, 0> LCG_Die1;\r\n  typedef boost::random::linear_congruential<boost::uint32_t, 2824527309u, 0,\r\n    0, 0> LCG_Fis;\r\n  typedef boost::random::linear_congruential<boost::uint64_t, 950706376u, 0,\r\n    (boost::uint64_t(1)<<31)-1, 0> LCG_FM;\r\n  typedef boost::random::linear_congruential<boost::int32_t, 51081, 0,\r\n    2147483647, 0> LCG_Hae;\r\n  typedef boost::random::linear_congruential<boost::uint32_t, 69069, 1,\r\n    0, 0> LCG_VAX;\r\n  typedef boost::random::inversive_congruential<boost::int64_t, 240318, 197, \r\n    1000081, 0> NLG_Inv1;\r\n  typedef boost::random::inversive_congruential<boost::int64_t, 15707262,\r\n    13262967, (1<<24)-17, 0> NLG_Inv2;\r\n  typedef boost::random::inversive_congruential<boost::int32_t, 1, 1,\r\n    2147483647, 0> NLG_Inv4;\r\n  typedef boost::random::inversive_congruential<boost::int32_t, 1, 2,\r\n    1<<30, 0> NLG_Inv5;\r\n  typedef boost::random::additive_congruential<boost::int32_t, 6,\r\n    (1<<30)-35, 0> MRG_Acorn7;\r\n  typedef boost::random::lagged_fibonacci_int<boost::uint32_t, 607, 273,\r\n    0, 0> MRG_Fib2;\r\n} // namespace Haertel\r\n\r\n#endif\r\n", "meta": {"hexsha": "1e7887d6a41ad4e34508f64e6665fd770235a805", "size": 4375, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/extra/haertel.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": 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/extra/haertel.hpp", "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/extra/haertel.hpp", "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": 27.8662420382, "max_line_length": 80, "alphanum_fraction": 0.6614857143, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5132228119715319}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2013 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 \"principal_curvature.h\"\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <queue>\n#include <list>\n#include <cmath>\n#include <limits>\n\n#include <Eigen/SparseCholesky>\n\n// Lib IGL includes\n#include <igl/adjacency_list.h>\n#include <igl/per_face_normals.h>\n#include <igl/per_vertex_normals.h>\n#include <igl/avg_edge_length.h>\n#include <igl/vertex_triangle_adjacency.h>\n\ntypedef enum\n{\n  SPHERE_SEARCH,\n  K_RING_SEARCH\n} searchType;\n\ntypedef enum\n{\n  AVERAGE,\n  PROJ_PLANE\n} normalType;\n\nclass CurvatureCalculator\n{\npublic:\n  /* Row number i represents the i-th vertex, whose columns are:\n   curv[i][0] : K2\n   curv[i][1] : K1\n   curvDir[i][0] : PD1\n   curvDir[i][1] : PD2\n   */\n  std::vector< std::vector<double> > curv;\n  std::vector< std::vector<Eigen::Vector3d> > curvDir;\n  bool curvatureComputed;\n  class Quadric\n  {\n  public:\n\n    IGL_INLINE Quadric ()\n    {\n      a() = b() = c() = d() = e() = 1.0;\n    }\n\n    IGL_INLINE Quadric(double av, double bv, double cv, double dv, double ev)\n    {\n      a() = av;\n      b() = bv;\n      c() = cv;\n      d() = dv;\n      e() = ev;\n    }\n\n    IGL_INLINE double& a() { return data[0];}\n    IGL_INLINE double& b() { return data[1];}\n    IGL_INLINE double& c() { return data[2];}\n    IGL_INLINE double& d() { return data[3];}\n    IGL_INLINE double& e() { return data[4];}\n\n    double data[5];\n\n    IGL_INLINE double evaluate(double u, double v)\n    {\n      return a()*u*u + b()*u*v + c()*v*v + d()*u + e()*v;\n    }\n\n    IGL_INLINE double du(double u, double v)\n    {\n      return 2.0*a()*u + b()*v + d();\n    }\n\n    IGL_INLINE double dv(double u, double v)\n    {\n      return 2.0*c()*v + b()*u + e();\n    }\n\n    IGL_INLINE double duv(double u, double v)\n    {\n      return b();\n    }\n\n    IGL_INLINE double duu(double u, double v)\n    {\n      return 2.0*a();\n    }\n\n    IGL_INLINE double dvv(double u, double v)\n    {\n      return 2.0*c();\n    }\n\n\n    IGL_INLINE static Quadric fit(const std::vector<Eigen::Vector3d> &VV)\n    {\n      assert(VV.size() >= 5);\n      if (VV.size() < 5)\n      {\n        std::cerr << \"ASSERT FAILED! fit function requires at least 5 points: Only \" << VV.size() << \" were given.\" << std::endl;\n        exit(0);\n      }\n\n      Eigen::MatrixXd A(VV.size(),5);\n      Eigen::MatrixXd b(VV.size(),1);\n      Eigen::MatrixXd sol(5,1);\n\n      for(unsigned int c=0; c < VV.size(); ++c)\n      {\n        double u = VV[c][0];\n        double v = VV[c][1];\n        double n = VV[c][2];\n\n        A(c,0) = u*u;\n        A(c,1) = u*v;\n        A(c,2) = v*v;\n        A(c,3) = u;\n        A(c,4) = v;\n\n        b(c) = n;\n      }\n\n      sol=A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n\n      return Quadric(sol(0),sol(1),sol(2),sol(3),sol(4));\n    }\n  };\n\npublic:\n\n  Eigen::MatrixXd vertices;\n  // Face list of current mesh    (#F x 3) or (#F x 4)\n  // The i-th row contains the indices of the vertices that forms the i-th face in ccw order\n  Eigen::MatrixXi faces;\n\n  std::vector<std::vector<int> > vertex_to_vertices;\n  std::vector<std::vector<int> > vertex_to_faces;\n  std::vector<std::vector<int> > vertex_to_faces_index;\n  Eigen::MatrixXd face_normals;\n  Eigen::MatrixXd vertex_normals;\n\n  /* Size of the neighborhood */\n  double sphereRadius;\n  int kRing;\n\n  bool localMode; /* Use local mode */\n  bool projectionPlaneCheck; /* Check collected vertices on tangent plane */\n  bool montecarlo;\n  unsigned int montecarloN;\n\n  searchType st; /* Use either a sphere search or a k-ring search */\n  normalType nt;\n\n  double lastRadius;\n  double scaledRadius;\n  std::string lastMeshName;\n\n  /* Benchmark related variables */\n  bool expStep; /* True if we want the radius to increase exponentially */\n  int step;  /* If expStep==false, by how much rhe radius increases on every step */\n  int maxSize; /* The maximum limit of the radius in the benchmark */\n\n  IGL_INLINE CurvatureCalculator();\n  IGL_INLINE void init(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F);\n\n  IGL_INLINE void finalEigenStuff(int, const std::vector<Eigen::Vector3d>&, Quadric&);\n  IGL_INLINE void fitQuadric(const Eigen::Vector3d&, const std::vector<Eigen::Vector3d>& ref, const std::vector<int>& , Quadric *);\n  IGL_INLINE void applyProjOnPlane(const Eigen::Vector3d&, const std::vector<int>&, std::vector<int>&);\n  IGL_INLINE void getSphere(const int, const double, std::vector<int>&, int min);\n  IGL_INLINE void getKRing(const int, const double,std::vector<int>&);\n  IGL_INLINE Eigen::Vector3d project(const Eigen::Vector3d&, const Eigen::Vector3d&, const Eigen::Vector3d&);\n  IGL_INLINE void computeReferenceFrame(int, const Eigen::Vector3d&, std::vector<Eigen::Vector3d>&);\n  IGL_INLINE void getAverageNormal(int, const std::vector<int>&, Eigen::Vector3d&);\n  IGL_INLINE void getProjPlane(int, const std::vector<int>&, Eigen::Vector3d&);\n  IGL_INLINE void applyMontecarlo(const std::vector<int>&,std::vector<int>*);\n  IGL_INLINE void computeCurvature();\n  IGL_INLINE void printCurvature(const std::string& outpath);\n  IGL_INLINE double getAverageEdge();\n\n  IGL_INLINE static int rotateForward (double *v0, double *v1, double *v2)\n  {\n    double t;\n\n    if (std::abs(*v2) >= std::abs(*v1) && std::abs(*v2) >= std::abs(*v0))\n      return 0;\n\n    t = *v0;\n    *v0 = *v2;\n    *v2 = *v1;\n    *v1 = t;\n\n    return 1 + rotateForward (v0, v1, v2);\n  }\n\n  IGL_INLINE static void rotateBackward (int nr, double *v0, double *v1, double *v2)\n  {\n    double t;\n\n    if (nr == 0)\n      return;\n\n    t = *v2;\n    *v2 = *v0;\n    *v0 = *v1;\n    *v1 = t;\n\n    rotateBackward (nr - 1, v0, v1, v2);\n  }\n\n  IGL_INLINE static Eigen::Vector3d chooseMax (Eigen::Vector3d n, Eigen::Vector3d abc, double ab)\n  {\n    int max_i;\n    double max_sp;\n    Eigen::Vector3d nt[8];\n\n    n.normalize ();\n    abc.normalize ();\n\n    max_sp = - std::numeric_limits<double>::max();\n\n    for (int i = 0; i < 4; ++i)\n    {\n      nt[i] = n;\n      if (ab > 0)\n      {\n        switch (i)\n        {\n          case 0:\n            break;\n\n          case 1:\n            nt[i][2] = -n[2];\n            break;\n\n          case 2:\n            nt[i][0] = -n[0];\n            nt[i][1] = -n[1];\n            break;\n\n          case 3:\n            nt[i][0] = -n[0];\n            nt[i][1] = -n[1];\n            nt[i][2] = -n[2];\n            break;\n        }\n      }\n      else\n      {\n        switch (i)\n        {\n          case 0:\n            nt[i][0] = -n[0];\n            break;\n\n          case 1:\n            nt[i][1] = -n[1];\n            break;\n\n          case 2:\n            nt[i][0] = -n[0];\n            nt[i][2] = -n[2];\n            break;\n\n          case 3:\n            nt[i][1] = -n[1];\n            nt[i][2] = -n[2];\n            break;\n        }\n      }\n\n      if (nt[i].dot(abc) > max_sp)\n      {\n        max_sp = nt[i].dot(abc);\n        max_i = i;\n      }\n    }\n    return nt[max_i];\n  }\n\n};\n\nclass comparer\n{\npublic:\n  IGL_INLINE bool operator() (const std::pair<int, double>& lhs, const std::pair<int, double>&rhs) const\n  {\n    return lhs.second>rhs.second;\n  }\n};\n\nIGL_INLINE CurvatureCalculator::CurvatureCalculator()\n{\n  this->localMode=true;\n  this->projectionPlaneCheck=true;\n  this->sphereRadius=5;\n  this->st=SPHERE_SEARCH;\n  this->nt=AVERAGE;\n  this->montecarlo=false;\n  this->montecarloN=0;\n  this->kRing=3;\n  this->curvatureComputed=false;\n  this->expStep=true;\n}\n\nIGL_INLINE void CurvatureCalculator::init(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F)\n{\n  // Normalize vertices\n  vertices = V;\n\n//  vertices = vertices.array() - vertices.minCoeff();\n//  vertices = vertices.array() / vertices.maxCoeff();\n//  vertices = vertices.array() * (1.0/igl::avg_edge_length(V,F));\n\n  faces = F;\n  igl::adjacency_list(F, vertex_to_vertices);\n  igl::vertex_triangle_adjacency(V, F, vertex_to_faces, vertex_to_faces_index);\n  igl::per_face_normals(V, F, face_normals);\n  igl::per_vertex_normals(V, F, face_normals, vertex_normals);\n}\n\nIGL_INLINE void CurvatureCalculator::fitQuadric(const Eigen::Vector3d& v, const std::vector<Eigen::Vector3d>& ref, const std::vector<int>& vv, Quadric *q)\n{\n  std::vector<Eigen::Vector3d> points;\n  points.reserve (vv.size());\n\n  for (unsigned int i = 0; i < vv.size(); ++i) {\n\n    Eigen::Vector3d  cp = vertices.row(vv[i]);\n\n    // vtang non e` il v tangente!!!\n    Eigen::Vector3d  vTang = cp - v;\n\n    double x = vTang.dot(ref[0]);\n    double y = vTang.dot(ref[1]);\n    double z = vTang.dot(ref[2]);\n    points.push_back(Eigen::Vector3d (x,y,z));\n  }\n  if (points.size() < 5)\n  {\n    std::cerr << \"ASSERT FAILED! fit function requires at least 5 points: Only \" << points.size() << \" were given.\" << std::endl;\n    *q = Quadric(0,0,0,0,0);\n  }\n  else\n  {\n    *q = Quadric::fit (points);\n  }\n}\n\nIGL_INLINE void CurvatureCalculator::finalEigenStuff(int i, const std::vector<Eigen::Vector3d>& ref, Quadric& q)\n{\n\n  const double a = q.a();\n  const double b = q.b();\n  const double c = q.c();\n  const double d = q.d();\n  const double e = q.e();\n\n//  if (fabs(a) < 10e-8 || fabs(b) < 10e-8)\n//  {\n//    std::cout << \"Degenerate quadric: \" << i << std::endl;\n//  }\n\n  double E = 1.0 + d*d;\n  double F = d*e;\n  double G = 1.0 + e*e;\n\n  Eigen::Vector3d n = Eigen::Vector3d(-d,-e,1.0).normalized();\n\n  double L = 2.0 * a * n[2];\n  double M = b * n[2];\n  double N = 2 * c * n[2];\n\n\n  // ----------------- Eigen stuff\n  Eigen::Matrix2d m;\n  m << L*G - M*F, M*E-L*F, M*E-L*F, N*E-M*F;\n  m = m / (E*G-F*F);\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> eig(m);\n\n  Eigen::Vector2d c_val = eig.eigenvalues();\n  Eigen::Matrix2d c_vec = eig.eigenvectors();\n\n  // std::cerr << \"c_val:\" << c_val << std::endl;\n  // std::cerr << \"c_vec:\" << c_vec << std::endl;\n\n  // std::cerr << \"c_vec:\" << c_vec(0) << \" \"  << c_vec(1) << std::endl;\n\n  c_val = -c_val;\n\n  Eigen::Vector3d v1, v2;\n  v1[0] = c_vec(0);\n  v1[1] = c_vec(1);\n  v1[2] = 0; //d * v1[0] + e * v1[1];\n\n  v2[0] = c_vec(2);\n  v2[1] = c_vec(3);\n  v2[2] = 0; //d * v2[0] + e * v2[1];\n\n\n  // v1 = v1.normalized();\n  // v2 = v2.normalized();\n\n  Eigen::Vector3d v1global = ref[0] * v1[0] + ref[1] * v1[1] + ref[2] * v1[2];\n  Eigen::Vector3d v2global = ref[0] * v2[0] + ref[1] * v2[1] + ref[2] * v2[2];\n\n  v1global.normalize();\n  v2global.normalize();\n\n  v1global *= c_val(0);\n  v2global *= c_val(1);\n\n  if (c_val[0] > c_val[1])\n  {\n    curv[i]=std::vector<double>(2);\n    curv[i][0]=c_val(1);\n    curv[i][1]=c_val(0);\n    curvDir[i]=std::vector<Eigen::Vector3d>(2);\n    curvDir[i][0]=v2global;\n    curvDir[i][1]=v1global;\n  }\n  else\n  {\n    curv[i]=std::vector<double>(2);\n    curv[i][0]=c_val(0);\n    curv[i][1]=c_val(1);\n    curvDir[i]=std::vector<Eigen::Vector3d>(2);\n    curvDir[i][0]=v1global;\n    curvDir[i][1]=v2global;\n  }\n  // ---- end Eigen stuff\n}\n\nIGL_INLINE void CurvatureCalculator::getKRing(const int start, const double r, std::vector<int>&vv)\n{\n  int bufsize=vertices.rows();\n  vv.reserve(bufsize);\n  std::list<std::pair<int,int> > queue;\n  std::vector<bool> visited(bufsize, false);\n  queue.push_back(std::pair<int,int>(start,0));\n  visited[start]=true;\n  while (!queue.empty())\n  {\n    int toVisit=queue.front().first;\n    int distance=queue.front().second;\n    queue.pop_front();\n    vv.push_back(toVisit);\n    if (distance<(int)r)\n    {\n      for (unsigned int i=0; i<vertex_to_vertices[toVisit].size(); ++i)\n      {\n        int neighbor=vertex_to_vertices[toVisit][i];\n        if (!visited[neighbor])\n        {\n          queue.push_back(std::pair<int,int> (neighbor,distance+1));\n          visited[neighbor]=true;\n        }\n      }\n    }\n  }\n}\n\n\nIGL_INLINE void CurvatureCalculator::getSphere(const int start, const double r, std::vector<int> &vv, int min)\n{\n  int bufsize=vertices.rows();\n  vv.reserve(bufsize);\n  std::list<int> queue;\n  std::vector<bool> visited(bufsize, false);\n  queue.push_back(start);\n  visited[start]=true;\n  Eigen::Vector3d me=vertices.row(start);\n  std::priority_queue<std::pair<int, double>, std::vector<std::pair<int, double> >, comparer > extra_candidates;\n  while (!queue.empty())\n  {\n    int toVisit=queue.front();\n    queue.pop_front();\n    vv.push_back(toVisit);\n    for (unsigned int i=0; i<vertex_to_vertices[toVisit].size(); ++i)\n    {\n      int neighbor=vertex_to_vertices[toVisit][i];\n      if (!visited[neighbor])\n      {\n        Eigen::Vector3d neigh=vertices.row(neighbor);\n        double distance=(me-neigh).norm();\n        if (distance<r)\n          queue.push_back(neighbor);\n        else if ((int)vv.size()<min)\n          extra_candidates.push(std::pair<int,double>(neighbor,distance));\n        visited[neighbor]=true;\n      }\n    }\n  }\n  while (!extra_candidates.empty() && (int)vv.size()<min)\n  {\n    std::pair<int, double> cand=extra_candidates.top();\n    extra_candidates.pop();\n    vv.push_back(cand.first);\n    for (unsigned int i=0; i<vertex_to_vertices[cand.first].size(); ++i)\n    {\n      int neighbor=vertex_to_vertices[cand.first][i];\n      if (!visited[neighbor])\n      {\n        Eigen::Vector3d neigh=vertices.row(neighbor);\n        double distance=(me-neigh).norm();\n        extra_candidates.push(std::pair<int,double>(neighbor,distance));\n        visited[neighbor]=true;\n      }\n    }\n  }\n}\n\nIGL_INLINE Eigen::Vector3d CurvatureCalculator::project(const Eigen::Vector3d& v, const Eigen::Vector3d& vp, const Eigen::Vector3d& ppn)\n{\n  return (vp - (ppn * ((vp - v).dot(ppn))));\n}\n\nIGL_INLINE void CurvatureCalculator::computeReferenceFrame(int i, const Eigen::Vector3d& normal, std::vector<Eigen::Vector3d>& ref )\n{\n\n  Eigen::Vector3d longest_v=Eigen::Vector3d(vertices.row(vertex_to_vertices[i][0]));\n\n  longest_v=(project(vertices.row(i),longest_v,normal)-Eigen::Vector3d(vertices.row(i))).normalized();\n\n  /* L'ultimo asse si ottiene come prodotto vettoriale tra i due\n   * calcolati */\n  Eigen::Vector3d y_axis=(normal.cross(longest_v)).normalized();\n  ref[0]=longest_v;\n  ref[1]=y_axis;\n  ref[2]=normal;\n}\n\nIGL_INLINE void CurvatureCalculator::getAverageNormal(int j, const std::vector<int>& vv, Eigen::Vector3d& normal)\n{\n  normal=(vertex_normals.row(j)).normalized();\n  if (localMode)\n    return;\n\n  for (unsigned int i=0; i<vv.size(); ++i)\n  {\n    normal+=vertex_normals.row(vv[i]).normalized();\n  }\n  normal.normalize();\n}\n\nIGL_INLINE void CurvatureCalculator::getProjPlane(int j, const std::vector<int>& vv, Eigen::Vector3d& ppn)\n{\n  int nr;\n  double a, b, c;\n  double nx, ny, nz;\n  double abcq;\n\n  a = b = c = 0;\n\n  if (localMode)\n  {\n    for (unsigned int i=0; i<vertex_to_faces.at(j).size(); ++i)\n    {\n      Eigen::Vector3d faceNormal=face_normals.row(vertex_to_faces.at(j).at(i));\n      a += faceNormal[0];\n      b += faceNormal[1];\n      c += faceNormal[2];\n    }\n  }\n  else\n  {\n    for (unsigned int i=0; i<vv.size(); ++i)\n    {\n      a+= vertex_normals.row(vv[i])[0];\n      b+= vertex_normals.row(vv[i])[1];\n      c+= vertex_normals.row(vv[i])[2];\n    }\n  }\n  nr = rotateForward (&a, &b, &c);\n  abcq = a*a + b*b + c*c;\n  nx = sqrt (a*a / abcq);\n  ny = sqrt (b*b / abcq);\n  nz = sqrt (1 - nx*nx - ny*ny);\n  rotateBackward (nr, &a, &b, &c);\n  rotateBackward (nr, &nx, &ny, &nz);\n\n  ppn = chooseMax (Eigen::Vector3d(nx, ny, nz), Eigen::Vector3d (a, b, c), a * b);\n  ppn.normalize();\n}\n\n\nIGL_INLINE double CurvatureCalculator::getAverageEdge()\n{\n  double sum = 0;\n  int count = 0;\n\n  for (int i = 0; i<faces.rows(); ++i)\n  {\n    for (short unsigned j=0; j<3; ++j)\n    {\n      Eigen::Vector3d p1=vertices.row(faces.row(i)[j]);\n      Eigen::Vector3d p2=vertices.row(faces.row(i)[(j+1)%3]);\n\n      double l = (p1-p2).norm();\n\n      sum+=l;\n      ++count;\n    }\n  }\n\n  return (sum/(double)count);\n}\n\n\nIGL_INLINE void CurvatureCalculator::applyProjOnPlane(const Eigen::Vector3d& ppn, const std::vector<int>& vin, std::vector<int> &vout)\n{\n  for (std::vector<int>::const_iterator vpi = vin.begin(); vpi != vin.end(); ++vpi)\n    if (vertex_normals.row(*vpi) * ppn > 0.0)\n      vout.push_back(*vpi);\n}\n\nIGL_INLINE void CurvatureCalculator::applyMontecarlo(const std::vector<int>& vin, std::vector<int> *vout)\n{\n  if (montecarloN >= vin.size ())\n  {\n    *vout = vin;\n    return;\n  }\n\n  float p = ((float) montecarloN) / (float) vin.size();\n  for (std::vector<int>::const_iterator vpi = vin.begin(); vpi != vin.end(); ++vpi)\n  {\n    float r;\n    if ((r = ((float)rand () / RAND_MAX)) < p)\n    {\n      vout->push_back(*vpi);\n    }\n  }\n}\n\nIGL_INLINE void CurvatureCalculator::computeCurvature()\n{\n  //CHECK che esista la mesh\n  const size_t vertices_count=vertices.rows();\n\n  if (vertices_count ==0)\n    return;\n\n  curvDir=std::vector< std::vector<Eigen::Vector3d> >(vertices_count);\n  curv=std::vector<std::vector<double> >(vertices_count);\n\n\n\n  scaledRadius=getAverageEdge()*sphereRadius;\n\n  std::vector<int> vv;\n  std::vector<int> vvtmp;\n  Eigen::Vector3d normal;\n\n  //double time_spent;\n  //double searchtime=0, ref_time=0, fit_time=0, final_time=0;\n\n  for (size_t i=0; i<vertices_count; ++i)\n  {\n    vv.clear();\n    vvtmp.clear();\n    Eigen::Vector3d me=vertices.row(i);\n    switch (st)\n    {\n      case SPHERE_SEARCH:\n        getSphere(i,scaledRadius,vv,6);\n        break;\n      case K_RING_SEARCH:\n        getKRing(i,kRing,vv);\n        break;\n      default:\n        fprintf(stderr,\"Error: search type not recognized\");\n        return;\n    }\n\n    if (vv.size()<6)\n    {\n      //std::cerr << \"Could not compute curvature of radius \" << scaledRadius << std::endl;\n      continue;\n    }\n\n\n    if (projectionPlaneCheck)\n    {\n      vvtmp.reserve (vv.size ());\n      applyProjOnPlane (vertex_normals.row(i), vv, vvtmp);\n      if (vvtmp.size() >= 6 && vvtmp.size()<vv.size())\n        vv = vvtmp;\n    }\n\n\n    switch (nt)\n    {\n      case AVERAGE:\n        getAverageNormal(i,vv,normal);\n        break;\n      case PROJ_PLANE:\n        getProjPlane(i,vv,normal);\n        break;\n      default:\n        fprintf(stderr,\"Error: normal type not recognized\");\n        return;\n    }\n    if (vv.size()<6)\n    {\n      //std::cerr << \"Could not compute curvature of radius \" << scaledRadius << std::endl;\n      continue;\n    }\n    if (montecarlo)\n    {\n      if(montecarloN<6)\n        break;\n      vvtmp.reserve(vv.size());\n      applyMontecarlo(vv,&vvtmp);\n      vv=vvtmp;\n    }\n\n    if (vv.size()<6)\n      return;\n    std::vector<Eigen::Vector3d> ref(3);\n    computeReferenceFrame(i,normal,ref);\n\n    Quadric q;\n    fitQuadric (me, ref, vv, &q);\n    finalEigenStuff(i,ref,q);\n  }\n\n  lastRadius=sphereRadius;\n  curvatureComputed=true;\n}\n\nIGL_INLINE void CurvatureCalculator::printCurvature(const std::string& outpath)\n{\n  using namespace std;\n  if (!curvatureComputed)\n    return;\n\n  std::ofstream of;\n  of.open(outpath.c_str());\n\n  if (!of)\n  {\n    fprintf(stderr, \"Error: could not open output file %s\\n\", outpath.c_str());\n    return;\n  }\n\n  int vertices_count=vertices.rows();\n  of << vertices_count << endl;\n  for (int i=0; i<vertices_count; ++i)\n  {\n    of << curv[i][0] << \" \" << curv[i][1] << \" \" << curvDir[i][0][0] << \" \" << curvDir[i][0][1] << \" \" << curvDir[i][0][2] << \" \" <<\n    curvDir[i][1][0] << \" \" << curvDir[i][1][1] << \" \" << curvDir[i][1][2] << endl;\n  }\n\n  of.close();\n\n}\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedPD1,\n  typename DerivedPD2,\n  typename DerivedPV1,\n  typename DerivedPV2,\n  typename Index>\nIGL_INLINE void igl::principal_curvature(\n  const Eigen::PlainObjectBase<DerivedV>& V,\n  const Eigen::PlainObjectBase<DerivedF>& F,\n  Eigen::PlainObjectBase<DerivedPD1>& PD1,\n  Eigen::PlainObjectBase<DerivedPD2>& PD2,\n  Eigen::PlainObjectBase<DerivedPV1>& PV1,\n  Eigen::PlainObjectBase<DerivedPV2>& PV2,\n  std::vector<Index>& bad_vertices,\n  unsigned radius,\n  bool useKring)\n{\n\n  if (radius < 2)\n  {\n    radius = 2;\n    std::cout << \"WARNING: igl::principal_curvature needs a radius >= 2, fixing it to 2.\" << std::endl;\n  }\n\n  // Preallocate memory\n  PD1.resize(V.rows(),3);\n  PD2.resize(V.rows(),3);\n\n  // Preallocate memory\n  PV1.resize(V.rows(),1);\n  PV2.resize(V.rows(),1);\n\n  // Precomputation\n  CurvatureCalculator cc;\n  cc.init(V.template cast<double>(),F.template cast<int>());\n  cc.sphereRadius = radius;\n\n  if (useKring)\n  {\n    cc.kRing = radius;\n    cc.st = K_RING_SEARCH;\n  }\n\n  // Compute\n  cc.computeCurvature();\n\n  // Copy it back\n  for (unsigned i=0; i<V.rows(); ++i)\n  {\n    if (!cc.curv[i].empty())\n    {\n      PD1.row(i) << cc.curvDir[i][0][0], cc.curvDir[i][0][1], cc.curvDir[i][0][2];\n      PD2.row(i) << cc.curvDir[i][1][0], cc.curvDir[i][1][1], cc.curvDir[i][1][2];\n      PD1.row(i).normalize();\n      PD2.row(i).normalize();\n\n      if (std::isnan(PD1(i,0)) || std::isnan(PD1(i,1)) || std::isnan(PD1(i,2)) || std::isnan(PD2(i,0)) || std::isnan(PD2(i,1)) || std::isnan(PD2(i,2)))\n      {\n        PD1.row(i) << 0,0,0;\n        PD2.row(i) << 0,0,0;\n      }\n\n      PV1(i) = cc.curv[i][0];\n      PV2(i) = cc.curv[i][1];\n\n      if (PD1.row(i) * PD2.row(i).transpose() > 10e-6)\n      {\n        bad_vertices.push_back((Index)i);\n\n        PD1.row(i) *= 0;\n        PD2.row(i) *= 0;\n      }\n    } else {\n      bad_vertices.push_back((Index)i);\n\n      PV1(i) = 0;\n      PV2(i) = 0;\n      PD1.row(i) << 0,0,0;\n      PD2.row(i) << 0,0,0;\n    }\n  }\n\n}\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedPD1,\n  typename DerivedPD2,\n  typename DerivedPV1,\n  typename DerivedPV2>\nIGL_INLINE void igl::principal_curvature(\n  const Eigen::PlainObjectBase<DerivedV>& V,\n  const Eigen::PlainObjectBase<DerivedF>& F,\n  Eigen::PlainObjectBase<DerivedPD1>& PD1,\n  Eigen::PlainObjectBase<DerivedPD2>& PD2,\n  Eigen::PlainObjectBase<DerivedPV1>& PV1,\n  Eigen::PlainObjectBase<DerivedPV2>& PV2,\n  unsigned radius,\n  bool useKring)\n{\n  if (radius < 2)\n  {\n    radius = 2;\n    std::cout << \"WARNING: igl::principal_curvature needs a radius >= 2, fixing it to 2.\" << std::endl;\n  }\n\n  // Preallocate memory\n  PD1.resize(V.rows(),3);\n  PD2.resize(V.rows(),3);\n\n  // Preallocate memory\n  PV1.resize(V.rows(),1);\n  PV2.resize(V.rows(),1);\n\n  // Precomputation\n  CurvatureCalculator cc;\n  cc.init(V.template cast<double>(),F.template cast<int>());\n  cc.sphereRadius = radius;\n\n  if (useKring)\n  {\n    cc.kRing = radius;\n    cc.st = K_RING_SEARCH;\n  }\n\n  // Compute\n  cc.computeCurvature();\n\n  // Copy it back\n  for (unsigned i=0; i<V.rows(); ++i)\n  {\n    PD1.row(i) << cc.curvDir[i][0][0], cc.curvDir[i][0][1], cc.curvDir[i][0][2];\n    PD2.row(i) << cc.curvDir[i][1][0], cc.curvDir[i][1][1], cc.curvDir[i][1][2];\n    PD1.row(i).normalize();\n    PD2.row(i).normalize();\n\n    if (std::isnan(PD1(i,0)) || std::isnan(PD1(i,1)) || std::isnan(PD1(i,2)) || std::isnan(PD2(i,0)) || std::isnan(PD2(i,1)) || std::isnan(PD2(i,2)))\n    {\n      PD1.row(i) << 0,0,0;\n      PD2.row(i) << 0,0,0;\n    }\n\n    PV1(i) = cc.curv[i][0];\n    PV2(i) = cc.curv[i][1];\n\n    if (PD1.row(i) * PD2.row(i).transpose() > 10e-6)\n    {\n      std::cerr << \"PRINCIPAL_CURVATURE: Something is wrong with vertex: \" << i << std::endl;\n      PD1.row(i) *= 0;\n      PD2.row(i) *= 0;\n    }\n  }\n\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\n// generated by autoexplicit.sh\ntemplate void igl::principal_curvature<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&, unsigned int, bool);\ntemplate void igl::principal_curvature<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&, unsigned int, bool);\ntemplate void igl::principal_curvature<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, unsigned int, bool);\ntemplate void igl::principal_curvature<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, int>(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&, std::vector<int, std::allocator<int> >&, unsigned int, bool);\n#endif\n", "meta": {"hexsha": "c84abe3a32c068c7621e9f9127751e60691b8f32", "size": 26164, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/simpleuv/thirdparty/libigl/include/igl/principal_curvature.cpp", "max_stars_repo_name": "MelvinG24/dust3d", "max_stars_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "thirdparty/simpleuv/thirdparty/libigl/include/igl/principal_curvature.cpp", "max_issues_repo_name": "MelvinG24/dust3d", "max_issues_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "thirdparty/simpleuv/thirdparty/libigl/include/igl/principal_curvature.cpp", "max_forks_repo_name": "MelvinG24/dust3d", "max_forks_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 27.9231590181, "max_line_length": 763, "alphanum_fraction": 0.5964684299, "num_tokens": 8586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5132228066389234}}
{"text": "\r\n#include <utility>\r\n#include <iostream>\r\n#include <vector>\r\n\r\n#include <Eigen/Dense>\r\n\r\n\r\n#include \"lattice.hpp\"\r\n#include \"input_output.hpp\"\r\n#include \"options.hpp\"\r\n#include \"crit_temperature_solver.hpp\"\r\n#include \"gnuplot-iostream/gnuplot-iostream.h\"\r\n\r\nusing namespace Eigen;\r\n\r\n\r\nclass MyFunction : public cppoptlib::Problem<float> {\r\n\t//using typename cppoptlib::Problem<double>::Scalar;\r\n\t//using typename cppoptlib::Problem<double>::TVector;\r\n\t\r\npublic:\r\n\tfloat value(const cppoptlib::Problem<float>::TVector& x){\r\n\t\tfloat result = 0;\r\n\t\tfor( int i = 0; i < x.size(); i++){\r\n\t\t\tresult += x(i)*x(i);\t\t\t\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\t\r\n};\r\n\r\n\r\nint main(int argc, char *argv[]) {\r\n\t\r\n\t//enables giving config file as command line argument\r\n\tstd::string config_name = \"kagome_config.json\";\r\n\tif(argc > 1 ){\r\n\t\tconfig_name = argv[1];\r\n\t}\r\n\t\r\n\t//the simulation input/output\r\n\tInputOutput simuIO = InputOutput(config_name);\t\r\n\t\r\n\t//readconfig returns a config object opt, that contains data read from json config file\r\n\tOptions opt = simuIO.ReadConfig();\r\n\r\n\r\n\t//dimensionality\r\n\tint bands = opt.bands;\t\r\n\tint dim = opt.dim;\r\n\r\n\t//creating the lattice\r\n\tLattice lattice = Lattice(opt.basis, opt.R, opt.t_matrix);\t\r\n\t\r\n\tstd::cout << \"basis:\\n\" << opt.basis << std::endl;\r\n\t//std::cout << \"R:\\n\" << opt.R << std::endl;\r\n\tstd::cout << \"t:\\n\" << opt.t_matrix << std::endl;\r\n\t\r\n\tMatrixXf dispersionandk = lattice.CalculateDispersion(opt.k_min, opt.k_max);\r\n\t\r\n\t//moving on to free energy\r\n\tCritTemperatureSolver tcsolver(lattice,opt);\r\n\t\r\n\t//initial guess for minimizing delta\r\n\tVectorXf delta = 0.1*VectorXf::Ones(bands);\r\n\r\n\ttcsolver.free_energy_functional.minimize(tcsolver.free_energy,delta);\r\n\t\r\n\t//testing minimizing delta for one T\r\n\t//MatrixXf min_delta = tcsolver.MinimizeDelta(0.1, 1.0);\r\n\r\n\t//testing on looping over temperatures\r\n\t//tcsolver.LoopT(opt.mu_max);\r\n\t\r\n\t//testing on looping over chemical potentials\r\n\ttcsolver.LoopMu();\r\n\t\r\n\t\r\n\t//writing the results to file\r\n\tstd::vector<std::string> headers;\r\n\theaders.push_back(\"kx\");headers.push_back(\"ky\");\r\n\theaders.push_back(\"E1\");headers.push_back(\"E2\");headers.push_back(\"E3\");\r\n\tsimuIO.WriteResults(\"testi\", headers, dispersionandk);\r\n\t\r\n\tlattice.SaveKineticHamiltonians(opt.k_min, opt.k_max);\r\n\t\r\n\t\r\n\tMyFunction f;\r\n\tcppoptlib::BfgsSolver<MyFunction> solver;\r\n\tVectorXf x(3); x << 2,3,4;\r\n\tsolver.minimize(f,x);\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n}\r\n\r\n\r\n/* \t//lattice basis vectors\r\n\tVector2f a1, a2;\r\n\ta1 << 1,0;\r\n\ta2 << 0.5, sqrt(3)/2;\r\n\t\r\n\ta1 = a1*d;\r\n\ta2 = a2*d;\r\n\t\r\n\tMatrixXf B(2,2);\r\n\tB.col(0) << a1;\r\n\tB.col(1) << a2;\r\n\t\r\n\t\r\n\t//gathering the coupling 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\t\t\r\n\tVector2f r_AB = a1/2;\r\n\tVector2f r_BA = -r_AB;\r\n\tVector2f r_AC = a2/2;\r\n\tVector2f r_CA = -r_AC;\r\n\tVector2f r_CB= (a1-a2)/2;\r\n\tVector2f r_BC = -r_CB;\r\n\t\r\n\tMatrixXf R(dim*bands,bands);\r\n\tR << Vector2f::Zero(dim) , r_BA, r_CA,\r\n\t\tr_AB, Vector2f::Zero(dim), r_CB,\r\n\t\tr_AC, r_BC, Vector2f::Zero(dim); \r\n\r\n\t\t\r\n\t// Hopping matrix\t\r\n\t//t = tAA tBA tCA\r\n\t//\ttAB tBB tCB\r\n\t//\ttAC tBC tCC\t\r\n\t\r\n\tMatrixXf t_matrix(bands,bands);\r\n\tt_matrix << 0, -t,-t,\r\n\t\t\t\t-t, 0, -t,\r\n\t\t\t\t-t, -t, 0; */\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\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\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "e5892fbca4ca0f09337c2476fcf552d1e4a111c4", "size": 3228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "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": "main.cpp", "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": "main.cpp", "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": 18.5517241379, "max_line_length": 89, "alphanum_fraction": 0.6310408922, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5132228001516405}}
{"text": "#include <Python.h>\n#include <numpy/ndarraytypes.h>\n#include <numpy/ndarrayobject.h>\n\n#include <boost/python.hpp>\nnamespace py = boost::python;\n\n#include <eigen3/Eigen/Core>\nnamespace ei = Eigen;\n\n#include <map>\n#include <vector>\n#include <string>\n#include <exception>\n#include <set>\n#include <map>\n#include <cmath>\n#include <iostream>\nusing namespace std;\n\n#include <omp.h>\n\n#include \"graph/graph_pywrapper.h\"\n#include \"boost_python_omp.h\"\n\nstruct Record\n{\n    int i, j, k;\n    int tm, lb;\n    float wtv1, wtv2;\n};\n\nusing Tensor1D = ei::Map<ei::Array<float, 1, ei::Dynamic, ei::RowMajor>, ei::RowMajor>;\nusing Tensor1D_Managed = ei::Array<float, 1, ei::Dynamic, ei::RowMajor>;\n\nusing Tensor2D = ei::Map<ei::Array<float, ei::Dynamic, ei::Dynamic, ei::RowMajor>, ei::RowMajor>;\nusing Tensor2D_Managed = ei::Array<float, ei::Dynamic, ei::Dynamic, ei::RowMajor>;\n\nusing Tensor3D = PyArrayObject*;\n\ntemplate <typename graph_t> using cgraph_type = const typename graph_t::CGraph*;\ntemplate <typename graph_t> using node_type = typename graph_t::CGraph::node_type;\n\ntemplate <typename graph_t>\nTensor1D_Managed X(int a, int b, int c, cgraph_type<graph_t> g, Tensor2D emb, const vector<node_type<graph_t>>& nodenames)\n{\n    float w1 = g->edge_value(nodenames[a], nodenames[c]);\n    float w2 = g->edge_value(nodenames[b], nodenames[c]);\n    \n    if(w1 < 1e-6 || w2 < 1e-6)  // save computation\n        if(!g->exists(nodenames[a], nodenames[c]) || !g->exists(nodenames[b], nodenames[c]))\n            throw runtime_error(\"invalid open triangle\");\n\n    return (emb.row(c) - emb.row(a)) * w1 + (emb.row(c) - emb.row(b)) * w2;\n}\n\ntemplate <typename graph_t>\nfloat P(int a, int b, int c, cgraph_type<graph_t> g, Tensor2D emb, Tensor1D theta, const vector<node_type<graph_t>>& nodenames)\n{\n    Tensor1D_Managed x = X<graph_t>(a, b, c, g, emb, nodenames);\n    float power = theta.segment(0, theta.size() - 1).cwiseProduct(x).sum();\n    power = -(power + theta(0, theta.size() - 1));\n \n    if(power > 100.0f)\n        return 0.0f;\n    else\n        return 1.0f / (1 + exp(power));\n}\n\ntemplate <typename graph_t>\nvoid translate_input(const py::list py_graph, const py::list py_nodenames, vector<cgraph_type<graph_t>> *graphs, vector<node_type<graph_t>> *nodenames)\n{\n    // graph\n    for(int i = 0; i < py::len(py_graph); i++)\n    {\n        cgraph_type<graph_t> g = (cgraph_type<graph_t>)py::extract<uintptr_t>(py_graph[i].attr(\"data\")())(); \n        graphs->push_back(g);\n    }\n\n    // nodenames\n    for(int i = 0; i < py::len(py_nodenames); i++)\n    {\n        py::extract<node_type<graph_t>> ext(py_nodenames[i]);\n        if(!ext.check())\n            throw runtime_error(\"Type check failed for nodename convertion\");\n        nodenames->push_back(ext());\n    }\n}\n\n// this is required because eigen::map REQUIRES proper init in debug mode,\n// so we HAVE TO directly return it rather than passing a pointer\nTensor1D translate_1darray(py::object arr)\n{\n    PyArrayObject *obj = (PyArrayObject*)arr.ptr();\n    int sz = PyArray_DIM(obj, 0);\n    // assert float type\n    if(PyArray_DESCR(obj)->kind != 'f')\n        throw logic_error(\"dtype of ndarray is not float32!\");\n    return Tensor1D((float*)PyArray_DATA(obj), 1, sz);\n}\n\nTensor3D translate_3darray(py::object arr)\n{\n    return (Tensor3D)arr.ptr();\n}\n\ntemplate <typename T>\nT extract(py::object obj)\n{\n    py::extract<T> ext(obj);\n    if(!ext.check())\n    {\n        ostringstream oss;\n        oss << \"Type check failed for type \" << typeid(T).name();\n        throw runtime_error(oss.str());\n    }\n    return ext();\n}\n\nvoid extract_record(py::object rec, Record *out)\n{\n    py::extract<py::list> ext(rec);\n    if(!ext.check())\n        throw runtime_error(\"Type check failed for data record, expecting py::list\");\n    py::list lst = ext();\n    out->tm = extract<int>(lst[0]);\n    out->k = extract<int>(lst[1]);  // center node\n    out->i = extract<int>(lst[2]);\n    out->j = extract<int>(lst[3]);\n    out->lb = extract<int>(lst[4]);\n    out->wtv1 = extract<float>(lst[5]);\n    out->wtv2 = extract<float>(lst[6]);\n}\n\nTensor2D slice_tensor3d(Tensor3D t, int idx)\n{\n    void *data = PyArray_GETPTR1(t, idx);\n    // assert float type\n    if(PyArray_DESCR(t)->kind != 'f')\n        throw logic_error(\"dtype of ndarray is not float32!\");\n    return Tensor2D((float*)data, PyArray_DIM(t, 1), PyArray_DIM(t, 2));\n}\n\ntemplate <typename graph_t>\npy::list _emcoef(py::list data, py::object py_emb, py::object py_theta, py::list py_graphs, py::list py_nodenames, int localstep)\n{\n    vector<cgraph_type<graph_t>> graphs;\n    vector<node_type<graph_t>> nodenames;\n\n    py::list ret;\n    ret.append(0);\n    ret *= py::len(data);\n\n    translate_input<graph_t>(py_graphs, py_nodenames, &graphs, &nodenames);\n    Tensor3D emb = translate_3darray(py_emb);\n    Tensor1D theta = translate_1darray(py_theta);\n\n    // build name2idx\n    map<node_type<graph_t>, int> name2idx;\n    int idx_cnt = 0;\n    for(const auto& name : nodenames)\n        name2idx[name] = idx_cnt++;\n\n    double eps = 1e-6;\n    int datalen = py::len(data);\n    int pardeg = 120;\n    int num_threads = omp_get_num_procs();\n    //int num_threads = 1;  // for debug\n\n    GILRelease gilrelease;\n\n    OMP_INIT_FOR(datalen, pardeg);\n#ifdef DEBUG\n    cout << \"step size \" << __omp_step_size << ' ' << __omp_sz << ' ' << __omp_deg << endl;\n#endif\n#pragma omp parallel for shared(data, localstep, graphs, emb, theta, nodenames, ret) num_threads(num_threads) schedule(dynamic, 1)\n    OMP_BEGIN_FOR(lb, ub);\n\n#ifdef DEBUG \n    cout << \"thread \" << omp_get_thread_num() << \": from \" << lb << \" to \" << ub << endl;\n#endif\n\n    Record currec[ub - lb];\n    double curC[ub - lb];\n\n    { GILAcquire gil;\n    for(int i = lb; i < ub; i++)\n        extract_record(data[i], &currec[i - lb]);\n    }\n\n    for(int i = lb; i < ub; i++)\n    {\n        double C, C0, C1;\n        Record rec = currec[i - lb];\n\n        int tm0based = rec.tm - localstep;\n        if(tm0based < 0)\n            throw runtime_error(\"trying to access graph before the first time step\");\n\n        const cgraph_type<graph_t> g = graphs[tm0based];\n        Tensor2D curemb = slice_tensor3d(emb, tm0based);\n\n        if(rec.lb == 0)\n        {\n            C = 1.0;\n        }\n        else\n        {\n            C0 = P<graph_t>(rec.i, rec.j, rec.k, g, curemb, theta, nodenames);\n            const auto& inbr = g->get_value(nodenames[rec.i]);\n            set<node_type<graph_t>> cmnbr;\n            for(const auto& itr : g->get_value(nodenames[rec.j]))\n                if(inbr.exists(itr.first))\n                    cmnbr.insert(itr.first);\n\n            C1 = 1;\n            for(const auto& nbr : cmnbr)\n            {\n                C1 *= (1 - P<graph_t>(rec.i, rec.j, name2idx[nbr], g, curemb, theta, nodenames));\n            }\n            C1 = 1.0 - C1;\n\n            C = 1.0 - C0 / (C1 + eps);\n\n            if(!isfinite(C))\n            {\n                cerr << C0 << ' ' << C1 << ' ' << C << endl;\n                cerr << rec.i << ' ' << rec.j << ' ' << rec.k << endl;\n                cerr << g->exists(nodenames[rec.i], nodenames[rec.k]) << ' ' << g->exists(nodenames[rec.j], nodenames[rec.k]) << endl;\n                for(const auto& nbr : g->get_value(nodenames[rec.i]))\n                    cerr << name2idx[nbr.first] << ' ';\n                cerr << endl;\n                for(const auto& nbr : g->get_value(nodenames[rec.j]))\n                    cerr << name2idx[nbr.first] << ' ';\n                cerr << endl;\n                throw runtime_error(\"inf or nan detected when calculating em coefficients\");\n            }\n        }\n        curC[i - lb] = float(C);\n    }\n    { GILAcquire gil;\n    for(int i = lb; i < ub; i++)\n    {\n        Record rec = currec[i - lb];\n        ret[i] = py::make_tuple(py::list(py::make_tuple(rec.tm, rec.k, rec.i, rec.j)), py::list(py::make_tuple(curC[i - lb], rec.wtv1, rec.wtv2)));\n    } }\n\n    OMP_END_FOR();\n    return ret;\n}\n\npy::list emcoef(py::list data, py::object py_emb, py::object py_theta, py::list py_graphs, py::list py_nodenames, int localstep)\n{\n    string cls = py::extract<string>(py::object(py_graphs[0]).attr(\"__class__\").attr(\"__name__\"));\n    if(cls == \"Graph_Int32_Float\")\n    {\n        return _emcoef<Graph_Int32_Float>(data, py_emb, py_theta, py_graphs, py_nodenames, localstep);\n    }\n    else if(cls == \"Graph_String_Float\")\n    {\n        return _emcoef<Graph_String_Float>(data, py_emb, py_theta, py_graphs, py_nodenames, localstep);\n    }\n    else\n    {\n        throw runtime_error(string(\"Unknown graph type \") + cls);\n    }\n}\n\nBOOST_PYTHON_MODULE(dynamic_triad_cimpl)\n{\n    PyEval_InitThreads();\n    py::def(\"emcoef\", &emcoef);\n}\n", "meta": {"hexsha": "0862fdee78dac8d646d78a869db651694666d547", "size": 8611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/algorithm/dynamic_triad_cimpl.cpp", "max_stars_repo_name": "dev-jwel/DynamicTriad", "max_stars_repo_head_hexsha": "3ab1ac92d849f5421aba6d6cb7ab89916c48b9d7", "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": "core/algorithm/dynamic_triad_cimpl.cpp", "max_issues_repo_name": "dev-jwel/DynamicTriad", "max_issues_repo_head_hexsha": "3ab1ac92d849f5421aba6d6cb7ab89916c48b9d7", "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": "core/algorithm/dynamic_triad_cimpl.cpp", "max_forks_repo_name": "dev-jwel/DynamicTriad", "max_forks_repo_head_hexsha": "3ab1ac92d849f5421aba6d6cb7ab89916c48b9d7", "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.4270072993, "max_line_length": 151, "alphanum_fraction": 0.6031819765, "num_tokens": 2516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5132125193513812}}
{"text": "#include <stan/math/mix/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <test/unit/math/rev/scal/fun/util.hpp>\n#include <test/unit/math/mix/scal/fun/nan_util.hpp>\n\n\nTEST(AgradFwdLbeta,FvarVar_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  fvar<var> x(3.0,1.3);\n  fvar<var> z(6.0,1.0);\n  fvar<var> a = lbeta(x,z);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val());\n  EXPECT_FLOAT_EQ(1.3 * digamma(3.0) + digamma(6.0) - (1.0 + 1.3) * \n                  digamma(3.0 + 6.0), a.d_.val());\n\n  AVEC y = createAVEC(x.val_,z.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0),g[0]);\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0),g[1]);\n}\nTEST(AgradFwdLbeta,FvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  fvar<var> x(3.0,1.3);\n  double z(6.0);\n  fvar<var> a = lbeta(x,z);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val());\n  EXPECT_FLOAT_EQ(1.3 * digamma(3.0) - (1.3) * \n                  digamma(3.0 + 6.0), a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0),g[0]);\n}\nTEST(AgradFwdLbeta,Double_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  double x(3.0);\n  fvar<var> z(6.0,1.0);\n  fvar<var> a = lbeta(x,z);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(3.0 + 6.0), a.d_.val());\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0),g[0]);\n}\nTEST(AgradFwdLbeta,FvarVar_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  fvar<var> x(3.0,1.3);\n  fvar<var> z(6.0,1.0);\n  fvar<var> a = lbeta(x,z);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val());\n  EXPECT_FLOAT_EQ(1.3 * digamma(3.0) + digamma(6.0) - (1.0 + 1.3) * \n                  digamma(3.0 + 6.0), a.d_.val());\n\n  AVEC y = createAVEC(x.val_,z.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(1.3 * 0.39493407 - 2.3 * 0.11751201,g[0]);\n  EXPECT_FLOAT_EQ(0.18132296 - 2.3 * 0.11751201,g[1]);\n}\nTEST(AgradFwdLbeta,FvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  fvar<var> x(3.0,1.3);\n  double z(6.0);\n  fvar<var> a = lbeta(x,z);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val());\n  EXPECT_FLOAT_EQ(1.3 * digamma(3.0) - (1.3) * \n                  digamma(3.0 + 6.0), a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(1.3 * 0.39493407 - 1.3 * 0.11751201,g[0]);\n}\nTEST(AgradFwdLbeta,Double_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  double x(3.0);\n  fvar<var> z(6.0,1.0);\n  fvar<var> a = lbeta(x,z);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(3.0 + 6.0), a.d_.val());\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(0.18132296 - 0.11751201,g[0]);\n}\nTEST(AgradFwdLbeta,FvarFvarVar_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x,y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.11751202, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), g[0]);\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), g[1]);\n}\nTEST(AgradFwdLbeta,FvarFvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  double y(6.0);\n\n  fvar<fvar<var> > a = lbeta(x,y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), g[0]);\n}\nTEST(AgradFwdLbeta,Double_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  double x(3.0);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x,y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), g[0]);\n}\nTEST(AgradFwdLbeta,FvarFvarVar_FvarFvarVar_2ndDeriv_x) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x,y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.11751202, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.39493407 - 0.11751201, g[0]);\n  EXPECT_FLOAT_EQ(-0.11751202, g[1]);\n}\nTEST(AgradFwdLbeta,FvarFvarVar_FvarFvarVar_2ndDeriv_y) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x,y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.11751202, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.11751202, g[0]);\n  EXPECT_FLOAT_EQ(0.18132296 - 0.11751201, g[1]);\n}\nTEST(AgradFwdLbeta,FvarFvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  double y(6.0);\n\n  fvar<fvar<var> > a = lbeta(x,y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.39493407 - 0.11751201, g[0]);\n}\nTEST(AgradFwdLbeta,Double_FvarFvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  double x(3.0);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x,y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.18132296 - 0.11751201, g[0]);\n}\nTEST(AgradFwdLbeta,FvarFvarVar_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x,y);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.013793319, g[0]);\n  EXPECT_FLOAT_EQ(0.013793319, g[1]);\n}\nTEST(AgradFwdLbeta,FvarFvarVar_Double_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  x.d_.val_ = 1.0;\n\n  double y(6.0);\n\n  fvar<fvar<var> > a = lbeta(x,y);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.140320487123420796890184645287, g[0]);\n}\nTEST(AgradFwdLbeta,Double_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::digamma;\n  using stan::math::lbeta;\n\n  double x(3.0);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n  y.val_.d_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x,y);\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.0189964130493467228161105712126, g[0]);\n}\n\n\nstruct lbeta_fun {\n  template <typename T0, typename T1>\n  inline \n  typename boost::math::tools::promote_args<T0,T1>::type\n  operator()(const T0 arg1,\n             const T1 arg2) const {\n    return lbeta(arg1,arg2);\n  }\n};\n\nTEST(AgradFwdLbeta, nan) {\n  lbeta_fun lbeta_;\n  test_nan_mix(lbeta_,3.0,5.0,false);\n}\n", "meta": {"hexsha": "2b12c14a73d049ad5b63d7df04265cefabf25551", "size": 9500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/mix/scal/fun/lbeta_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/mix/scal/fun/lbeta_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/mix/scal/fun/lbeta_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.198938992, "max_line_length": 68, "alphanum_fraction": 0.6364210526, "num_tokens": 3939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5132125141938894}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"functions/zero.hh\"\n#include \"functions/std_functions.hh\"\n#include \"functions/operators.hh\"\n#include \"functions/all_simplifications.hh\"\n\nBOOST_AUTO_TEST_CASE(zero_function_test) {\n  using namespace manifolds;\n\n  Zero z;\n  Sin s;\n  static_assert(std::is_same<decltype(s + z), Sin>::value,\n                \"Failed to simplify Sin + 0\");\n\n  static_assert(std::is_same<decltype(z + s), Sin>::value,\n                \"Failed to simplify 0 + Sin\");\n\n  static_assert(std::is_same<decltype(z + z), Zero>::value,\n                \"Failed to simplify 0 + 0\");\n\n  static_assert(std::is_same<decltype(s * z), Zero>::value,\n                \"Failed to simplify Sin * 0\");\n\n  static_assert(std::is_same<decltype(z * s), Zero>::value,\n                \"Failed to simplify 0 * Sin\");\n\n  static_assert(std::is_same<decltype(z * z), Zero>::value,\n                \"Failed to simplify 0 * 0\");\n}\n", "meta": {"hexsha": "c0eb6a2281490f2121e38521b61cfb4780b6050f", "size": 917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_zero.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_zero.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_zero.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": 30.5666666667, "max_line_length": 59, "alphanum_fraction": 0.6335877863, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5132125134056993}}
{"text": "#include \"pose_2d.hpp\"\n#include \"scan_simulator_2d.hpp\"\n#include \"car_state.hpp\"\n#include \"car_params.hpp\"\n#include \"car_odom.hpp\"\n#include \"car_obs.hpp\"\n#include \"ackermann_kinematics.hpp\"\n#include \"ks_kinematics.hpp\"\n#include \"st_kinematics.hpp\"\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <iostream>\n#include <vector>\n#include <math.h>\nusing namespace racecar_simulator;\nclass RaceCar {\npublic:\n    RaceCar(double time_step, double mu, double h_cg, double l_r, double cs_f, double cs_r, double I_z, double mass, bool is_ego);\n    virtual ~RaceCar();\n    void set_map(std::vector<double> &map, int map_height, int map_width, double map_resolution, double origin_x, double origin_y, double free_threshold);\n    void reset();\n    void reset_bypose(Pose2D pose);\n    CarObs update_scan();\n    void update_pose();\n    void update_op_poses(const std::vector<Pose2D> &op_poses);\n    void set_velocity(double vel);\n    void set_steering_angle(double ang);\n    Pose2D get_pose();\n    double get_accel();\n    double get_steer_vel();\n    void update_params(double mu, double h_cg, double l_r, double cs_f, double cs_r, double I_z, double mass);\nprivate:\n    CarState state;\n    CarParams params;\n    CarOdom odom;\n    Pose2D pose;\n    ScanSimulator2D scan_simulator;\n    bool map_exists;\n    bool ego;\n    double scan_distance_to_base_link;\n    double car_width, car_length;\n    double max_speed, max_steering_angle;\n    double max_accel, max_decel, max_steering_vel;\n    double accel, steer_angle_vel;\n    double width;\n    double delt_t;\n    std::vector<double> cosines;\n    double scan_fov, scan_ang_incr;\n    std::vector<double> scan_angles;\n    std::vector<double> current_scan;\n    bool in_collision = false;\n    double collision_angle;\n    double ttc_threshold;\n    double map_free_threshold;\n    const double PI = 3.141592653;\n    std::vector<double> car_distances;\n    std::vector<Pose2D> opponent_poses;\n    int steering_delay_buffer_length;\n    std::vector<double> steer_buffer;\n    Eigen::Matrix4d get_transformation_matrix(const Pose2D &pose);\n    Pose2D transform_between_frames(const Pose2D &p1, const Pose2D &p2);\n    void ray_cast_opponents(std::vector<double> &scan, const Pose2D &scan_pose);\n    void check_ttc();\n    void set_accel(double acceleration);\n    void set_steering_angle_vel(double steer_vel);\n    double compute_steer_vel(double desired_angle);\n    void compute_accel(double desired_velocity);\n    double get_range(const Pose2D &pose, double beam_theta, Eigen::Vector2d line_segment_a, Eigen::Vector2d line_segment_b);\n    bool are_collinear(Eigen::Vector2d pt_a, Eigen::Vector2d pt_b, Eigen::Vector2d pt_c);\n    double cross(Eigen::Vector2d v1, Eigen::Vector2d v2);\n};\n", "meta": {"hexsha": "6f7c23169fb65f998b5a727fdfb26b6437821005", "size": 2708, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Simulator/include/racecar.hpp", "max_stars_repo_name": "travelbureau/f0_icml_code", "max_stars_repo_head_hexsha": "8860c3e9e87c7340268bb18aa7d7e383b540f699", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T22:59:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T20:53:38.000Z", "max_issues_repo_path": "Simulator/include/racecar.hpp", "max_issues_repo_name": "travelbureau/f0_icml_code", "max_issues_repo_head_hexsha": "8860c3e9e87c7340268bb18aa7d7e383b540f699", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Simulator/include/racecar.hpp", "max_forks_repo_name": "travelbureau/f0_icml_code", "max_forks_repo_head_hexsha": "8860c3e9e87c7340268bb18aa7d7e383b540f699", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-16T15:43:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-16T18:18:40.000Z", "avg_line_length": 37.6111111111, "max_line_length": 154, "alphanum_fraction": 0.7422451994, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478256, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5132125074600172}}
{"text": "/* Copyright (c) 2021 Skyward Experimental Rocketry\n * Author: Luca Conterio\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\n * THE SOFTWARE.\n */\n\n#include <Common.h>\n#include <miosix.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iomanip>\n#include <iostream>\n\n#include \"drivers/HardwareTimer.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace miosix;\nusing miosix::Thread;\n\nvoid nProducts2Mat(int n, MatrixXd& m1, MatrixXd& m2)\n{\n    HardwareTimer<uint32_t, 2>& hrclock =\n        HardwareTimer<uint32_t, 2>::instance();\n    hrclock.setPrescaler(127);\n    hrclock.start();\n\n    int i       = 0;\n    uint32_t t1 = hrclock.tick();\n\n    for (i = 0; i < n; i++)\n        MatrixXd m = m1 * m2;\n\n    uint32_t t2 = hrclock.tick();\n    double time = hrclock.toMilliSeconds(t2 - t1);\n    hrclock.stop();\n\n    TRACE(\"\\nTime for %d products using 2 matrices: %f [ms] \\n\\n\", n, time);\n}\n\nvoid nProducts3Mat(int n, MatrixXd& m1, MatrixXd& m2, MatrixXd& m3)\n{\n    HardwareTimer<uint32_t, 2>& hrclock =\n        HardwareTimer<uint32_t, 2>::instance();\n    hrclock.setPrescaler(127);\n    hrclock.start();\n\n    int i       = 0;\n    uint32_t t1 = hrclock.tick();\n\n    for (i = 0; i < n; i++)\n        MatrixXd m = m1 * m2 * m3;\n\n    uint32_t t2 = hrclock.tick();\n    double time = hrclock.toMilliSeconds(t2 - t1);\n    hrclock.stop();\n\n    TRACE(\"\\nTime for %d products using 3 matrices: %f [ms] \\n\\n\", n, time);\n}\n\nvoid kalmanOperations(MatrixXd& m1, MatrixXd& m2, MatrixXd& m3, MatrixXd& m4,\n                      MatrixXd& m5, MatrixXd& eye, MatrixXd& v1, MatrixXd& v2)\n{\n    HardwareTimer<uint32_t, 2>& hrclock =\n        HardwareTimer<uint32_t, 2>::instance();\n    hrclock.setPrescaler(127);\n    hrclock.start();\n\n    auto x = v1;\n    auto P = m2;\n    auto Q = m3;\n    auto R = m5;\n    auto y = v2;\n\n    uint32_t t1 = hrclock.tick();\n\n    auto F     = 0.5 * m1;\n    x          = F * x;\n    P          = F * P * (F.transpose()) + Q;\n    auto H     = 2 * m4;\n    auto K     = P * H.transpose() * ((H * P * H.transpose() + R).inverse());\n    auto U     = K * (y.transpose() - H * x);\n    auto x_new = x + U;\n    auto P_new = (eye - K * H) * P;\n\n    uint32_t t2 = hrclock.tick();\n    double time = hrclock.toMilliSeconds(t2 - t1);\n    hrclock.stop();\n\n    TRACE(\"\\nTime for a single kalman cycle: %f [ms] \\n\\n\", time);\n}\n\nvoid sparseKalmanOperations(MatrixXd& m1, MatrixXd& m2, MatrixXd& m3,\n                            MatrixXd& m4, MatrixXd& m5, MatrixXd& eye,\n                            MatrixXd& v1, MatrixXd& v2)\n{\n    // H, P and R can't be sparse since their product needs to be inverted.\n    HardwareTimer<uint32_t, 2>& hrclock =\n        HardwareTimer<uint32_t, 2>::instance();\n    hrclock.setPrescaler(127);\n    hrclock.start();\n\n    auto x = v1;\n    auto P = m2;\n    auto Q = m3.sparseView();\n    auto R = m5;\n    auto y = v2;\n\n    uint32_t t1 = hrclock.tick();\n\n    auto F = 0.5 * m1.sparseView();\n    x      = F * x;\n    P      = F * P * (F.transpose()) + Q;\n    auto H = 2 * m4;\n    auto K = (P * (H.transpose()) * ((H * P * H.transpose() + R).inverse()))\n                 .sparseView();\n    auto U     = (K * (y.transpose() - H * x)).sparseView();\n    auto x_new = x + U;\n    auto P_new = (eye - K * H) * P;\n\n    uint32_t t2 = hrclock.tick();\n    double time = hrclock.toMilliSeconds(t2 - t1);\n    hrclock.stop();\n\n    TRACE(\n        \"\\nTime for a single kalman cycle with some sparse matrices: %f [ms] \"\n        \"\\n\\n\",\n        time);\n}\n\nvoid determinant(MatrixXd& m1)\n{\n    HardwareTimer<uint32_t, 2>& hrclock =\n        HardwareTimer<uint32_t, 2>::instance();\n    hrclock.setPrescaler(127);\n    hrclock.start();\n\n    uint32_t t1 = hrclock.tick();\n\n    float det = m1.determinant();\n\n    uint32_t t2 = hrclock.tick();\n    double time = hrclock.toMilliSeconds(t2 - t1);\n    hrclock.stop();\n\n    TRACE(\"\\nTime to find the determinant: %f [ms] \\n\\n\", time);\n}\n\nint main()\n{\n    static const int ROWS = 10;\n    static const int COL  = 10;\n    static const int N    = 100;\n\n    MatrixXd m1  = MatrixXd::Random(ROWS, COL);\n    MatrixXd m2  = MatrixXd::Random(ROWS, COL);\n    MatrixXd m3  = MatrixXd::Random(ROWS, COL);\n    MatrixXd m4  = MatrixXd::Random(ROWS, COL);\n    MatrixXd m5  = MatrixXd::Random(ROWS, COL);\n    MatrixXd eye = MatrixXd::Identity(ROWS, ROWS);\n\n    MatrixXd v1 = MatrixXd::Random(ROWS, 1);\n    MatrixXd v2 = MatrixXd::Random(1, ROWS);\n\n    determinant(m1);\n    nProducts2Mat(N, m1, m2);\n    nProducts3Mat(N, m1, m2, m3);\n    kalmanOperations(m1, m2, m3, m4, m5, eye, v1, v2);\n    sparseKalmanOperations(m1, m2, m3, m4, m5, eye, v1, v2);\n\n    return 0;\n}", "meta": {"hexsha": "7a3ebb4d07b05ec4bed898451dd19c11e022e42f", "size": 5600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/eigen-test.cpp", "max_stars_repo_name": "skyward-er/on-board-software", "max_stars_repo_head_hexsha": "b0739e27f345d6bd07f21948ee06c99757662381", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-10T09:43:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T07:32:37.000Z", "max_issues_repo_path": "src/tests/eigen-test.cpp", "max_issues_repo_name": "skyward-er/on-board-software", "max_issues_repo_head_hexsha": "b0739e27f345d6bd07f21948ee06c99757662381", "max_issues_repo_licenses": ["MIT"], "max_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/eigen-test.cpp", "max_forks_repo_name": "skyward-er/on-board-software", "max_forks_repo_head_hexsha": "b0739e27f345d6bd07f21948ee06c99757662381", "max_forks_repo_licenses": ["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.6296296296, "max_line_length": 80, "alphanum_fraction": 0.6157142857, "num_tokens": 1707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5131940254727588}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE weierstrass_precomputation_components_test\n\n#include <boost/test/unit_test.hpp>\n\n#include <nil/crypto3/algebra/curves/mnt4.hpp>\n#include <nil/crypto3/algebra/curves/mnt6.hpp>\n\n#include <nil/crypto3/zk/components/algebra/pairing/detail/mnt4.hpp>\n#include <nil/crypto3/zk/components/algebra/pairing/detail/mnt6.hpp>\n\n#include <nil/crypto3/zk/components/algebra/pairing/weierstrass/precomputation.hpp>\n\n#include <nil/crypto3/algebra/random_element.hpp>\n\nusing namespace nil::crypto3;\nusing namespace nil::crypto3::zk;\nusing namespace nil::crypto3::algebra;\n\ntemplate<typename CurveType>\nvoid test_element_g1_precomp() {\n    components::blueprint<typename CurveType::scalar_field_type> bp;\n    typename CurveType::pairing::pair_curve_type::g1_type::value_type g_val =\n        algebra::random_element<typename CurveType::pairing::pair_curve_type::scalar_field_type>() *\n        CurveType::pairing::pair_curve_type::g1_type::value_type::one();\n\n    element_g1<CurveType> g(bp);\n    g1_precomputation<CurveType> precomp;\n    precompute_G1_component<CurveType> do_precomp(bp, g, precomp);\n    do_precomp.generate_r1cs_constraints();\n\n    g.generate_r1cs_witness(g_val);\n    do_precomp.generate_r1cs_witness();\n    BOOST_CHECK(bp.is_satisfied());\n\n    typename CurveType::pairing::g1_precomp const_precomp(bp, g_val);\n\n    typename CurveType::pairing::pair_curve_type::pairing::affine_ate_g1_precomp native_precomp =\n        CurveType::pairing::pair_curve_type::affine_ate_precompute_g1(g_val);\n    BOOST_CHECK(precomp.PY_twist_squared->get_element() == native_precomp.PY_twist_squared);\n    BOOST_CHECK(const_precomp.PY_twist_squared->get_element() == native_precomp.PY_twist_squared);\n}\n\ntemplate<typename CurveType>\nvoid test_element_g2_precomp() {\n    components::blueprint<typename CurveType::scalar_field_type> bp;\n    typename CurveType::pairing::pair_curve_type::g2_type::value_type g_val =\n        algebra::random_element<typename CurveType::pairing::pair_curve_type::scalar_field_type>() *\n        CurveType::pairing::pair_curve_type::g2_type::value_type::one();\n\n    element_g2<CurveType> g(bp);\n    g2_precomputation<CurveType> precomp;\n    precompute_G2_component<CurveType> do_precomp(bp, g, precomp);\n    do_precomp.generate_r1cs_constraints();\n\n    g.generate_r1cs_witness(g_val);\n    do_precomp.generate_r1cs_witness();\n    BOOST_CHECK(bp.is_satisfied());\n\n    typename CurveType::pairing::pair_curve_type::pairing::affine_ate_g2_precomp native_precomp =\n        CurveType::pairing::pair_curve_type::affine_ate_precompute_g2(g_val);\n\n    BOOST_CHECK(precomp.coeffs.size() - 1 ==\n                native_precomp.coeffs.size());    // the last precomp is unused, but remains for convenient programming\n    for (std::size_t i = 0; i < native_precomp.coeffs.size(); ++i) {\n        BOOST_CHECK(precomp.coeffs[i]->RX->get_element() == native_precomp.coeffs[i].old_RX);\n        BOOST_CHECK(precomp.coeffs[i]->RY->get_element() == native_precomp.coeffs[i].old_RY);\n        BOOST_CHECK(precomp.coeffs[i]->gamma->get_element() == native_precomp.coeffs[i].gamma);\n        BOOST_CHECK(precomp.coeffs[i]->gamma_X->get_element() == native_precomp.coeffs[i].gamma_X);\n    }\n\n    std::cout << \"number of constraints for G2 precomp: \" << bp.num_constraints() << std::endl;\n}\n\nBOOST_AUTO_TEST_SUITE(weierstrass_precomputation_components_test_suite)\n\nBOOST_AUTO_TEST_CASE(weierstrass_precomputation_components_test) {\n\n    test_all_set_commitment_components<curves::mnt4<298>>();\n    test_all_set_commitment_components<curves::mnt6<298>>();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d9e1107325cef3082ef696d50c4f78535b6be3e1", "size": 4971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algebra/pairing/weierstrass/precomputation.cpp", "max_stars_repo_name": "skywinder/crypto3-blueprint", "max_stars_repo_head_hexsha": "c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20", "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/algebra/pairing/weierstrass/precomputation.cpp", "max_issues_repo_name": "skywinder/crypto3-blueprint", "max_issues_repo_head_hexsha": "c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20", "max_issues_repo_licenses": ["MIT"], "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/algebra/pairing/weierstrass/precomputation.cpp", "max_forks_repo_name": "skywinder/crypto3-blueprint", "max_forks_repo_head_hexsha": "c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T06:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T06:27:19.000Z", "avg_line_length": 46.0277777778, "max_line_length": 119, "alphanum_fraction": 0.7382820358, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.5131940242584837}}
{"text": "// -------------------------------------------------------------------------------------------------\n//                              Copyright 2016 - NumScale SAS\n//\n//                   Distributed under the Boost Software License, Version 1.0.\n//                        See accompanying file LICENSE.txt or copy at\n//                            http://www.boost.org/LICENSE_1_0.txt\n// -------------------------------------------------------------------------------------------------\n#define BOOST_SIMD_NO_DENORMALS\n#define BOOST_SIMD_NO_INVALIDS\n#include <simd_bench.hpp>\n#include <boost/simd/function/simd/log.hpp>\n#include <boost/simd/pack.hpp>\n\nnamespace nsb = ns::bench;\nnamespace bs =  boost::simd;\n\nDEFINE_SIMD_BENCH(simd_musl_log, bs::musl_(bs::log));\n\nDEFINE_BENCH_MAIN()\n{\n  nsb::for_each<simd_musl_log, NS_BENCH_IEEE_TYPES>(0, 1000);\n}\n", "meta": {"hexsha": "780c151c51309b76d7ceeb043d5945bf49e09a59", "size": 848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/function/simd/log.musl.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": "bench/function/simd/log.musl.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": "bench/function/simd/log.musl.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": 36.8695652174, "max_line_length": 100, "alphanum_fraction": 0.4929245283, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5131940192937529}}
{"text": "\n#include <CGAL/Timer.h>\n\n#include <nanoflann.hpp>\n\n#include <boost/lexical_cast.hpp>\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <CGAL/Memory_sizer.h>\n#include <CGAL/IO/io.h>\n\nusing namespace std;\nusing namespace nanoflann;\n\ntemplate <typename T>\nstruct Point\n{\n  Point(T x, T y, T z)\n    : x(x), y(y), z(z)\n  {}\n\n  T   x,y,z;\n};\n\ntemplate <typename T>\nostream& operator <<(ostream& os, const Point<T>& p)\n{\n  os << p.x << \" \" << p.y << \" \" << p.z ;\n  return os;\n}\n\n\n// This is an exampleof a custom data set class\ntemplate <typename T>\nstruct PointCloud\n{\n  std::vector<Point<T> >  pts;\n\n        // Must return the number of data points\n        inline size_t kdtree_get_point_count() const { return pts.size(); }\n\n        // Returns the distance between the vector \"p1[0:size-1]\" and the data point with index \"idx_p2\" stored in the class:\n        inline T kdtree_distance(const T *p1, const size_t idx_p2,size_t /* size */) const\n        {\n                const T d0=p1[0]-pts[idx_p2].x;\n                const T d1=p1[1]-pts[idx_p2].y;\n                const T d2=p1[2]-pts[idx_p2].z;\n                return d0*d0+d1*d1+d2*d2;\n        }\n\n        // Returns the dim'th component of the idx'th point in the class:\n        // Since this is inlined and the \"dim\" argument is typically an immediate value, the\n        //  \"if/else's\" are actually solved at compile time.\n        inline T kdtree_get_pt(const size_t idx, int dim) const\n        {\n                if (dim==0) return pts[idx].x;\n                else if (dim==1) return pts[idx].y;\n                else return pts[idx].z;\n        }\n\n        // Optional bounding-box computation: return false to default to a standard bbox computation loop.\n        //   Return true if the BBOX was already computed by the class and returned in \"bb\" so it can be avoided to redo it again.\n        //   Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds)\n        template <class BBOX>\n        bool kdtree_get_bbox(BBOX & /* bb */) const { return false; }\n\n};\n\ntemplate <typename T>\nvoid generateRandomPointCloud(PointCloud<T> &point, istream& is, int n)\n{\n  T x, y, z;\n  for(int i=0; i < n; i++){\n    CGAL::read(is,x);\n    CGAL::read(is,y);\n    CGAL::read(is,z);\n\n    point.pts.push_back(Point<T>(x,y,z));\n  }\n  std::cout << \"Read \"<< point.pts.size() << \" points\\n\";\n}\n\ntemplate <typename num_t>\nvoid kdtree_demo(int argc, char** argv)\n{\n        PointCloud<num_t> cloud;\n        int n;\n\n        // Generate points:\n        std::ifstream input(argv[1], std::ios::in | std::ios::binary);\n        CGAL::IO::set_binary_mode(input);\n        //        input >> n >> n; // dimension and # of points\n        CGAL::read(input,n);\n        CGAL::read(input,n);\n        generateRandomPointCloud(cloud, input, n);\n\n        std::vector<Point<double> > queries;\n        std::ifstream queries_stream(argv[2], std::ios::in | std::ios::binary);\n        CGAL::IO::set_binary_mode(queries_stream);\n        CGAL::read(queries_stream,n);\n        CGAL::read(queries_stream,n);\n        // queries_stream >> n >> n;\n        double x,y,z;\n        for(int i=0; i < n; i++){\n          CGAL::read(queries_stream,x);\n          CGAL::read(queries_stream,y);\n          CGAL::read(queries_stream,z);\n          queries.push_back(Point<double>(x,y,z));\n        }\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        num_t query_pt[3] = { 0, 0, 0};\n\n        CGAL::Timer timer;\n        timer.start();\n        // construct a kd-tree index:\n        typedef KDTreeSingleIndexAdaptor<\n                L2_Simple_Adaptor<num_t, PointCloud<num_t> > ,\n                PointCloud<num_t>,\n                3 /* dim */\n                > my_kd_tree_t;\n\n        my_kd_tree_t   index(3 /*dim*/, cloud, KDTreeSingleIndexAdaptorParams(bucketsize /* max leaf */) );\n        index.buildIndex();\n\n        timer.stop();\n        std::cout << \"construction time: \" << timer.time() << \" sec\" << std::endl;\n        std::cerr << \"Tree statistics:\" << std::endl;\n        std::cerr << \"Number of items stored: \"\n          << index.items << std::endl;\n        std::cerr << \"Number of nodes: \"\n          << index.internals << std::endl;\n        std::cerr << \" Tree depth: \" << index.depth() << std::endl;\n        // do a knn search\n        const size_t num_results = 10;\n        size_t ret_index[num_results];\n        num_t out_dist_sqr[num_results];\n        int size = queries.size();\n\n        std::cout << \"start search\" << std::endl;\n        bool dump = true;\n        double sum = 0;\n\n        for(int i=0;i<runs;++i){\n\n          nanoflann::KNNResultSet<num_t> resultSet(num_results);\n\n          for(int i = 0 ; i < size; i++){\n            query_pt[0] = queries[i].x;\n            query_pt[1] = queries[i].y;\n            query_pt[2] = queries[i].z;\n            resultSet.init(ret_index, out_dist_sqr );\n            timer.reset();\n          timer.start();\n            index.findNeighbors(resultSet, &query_pt[0], nanoflann::SearchParams(10,0));\n            timer.stop();\n\n            for (size_t k=0; k<num_results; ++k){\n              if(dump)\n                std::cerr <<cloud.pts[ret_index[k]] << std::endl;\n            }\n                    dump=false;\n                    sum += timer.time();\n          }\n\n\n        }\n        std::cerr << index.count_items <<\" items\\n\";\n        std::cerr << index.count_leafs <<\" leaf\\n\";\n        std::cerr << index.count_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}\n\nint main(int argc, char** argv)\n{\n  kdtree_demo<double>(argc, argv);\n\n  return 0;\n}\n\n", "meta": {"hexsha": "8822bae99927d70a3910431b9bb738224ddb7b92", "size": 5944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Spatial_searching/benchmark/Spatial_searching/nn3nanoflan.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-19T03:07:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T03:07:22.000Z", "max_issues_repo_path": "Spatial_searching/benchmark/Spatial_searching/nn3nanoflan.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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": "Spatial_searching/benchmark/Spatial_searching/nn3nanoflan.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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": 30.6391752577, "max_line_length": 130, "alphanum_fraction": 0.5523216689, "num_tokens": 1591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5131940192937529}}
{"text": "\n#include \"line.hpp\"\n\n#include <Eigen/Geometry>\n\nnamespace neon\n{\nline2::line2(line_quadrature::point const p)\n    : line_interpolation(std::make_unique<line_quadrature>(p), 2)\n{\n    this->precompute_shape_functions();\n}\n\nvoid line2::precompute_shape_functions()\n{\n    using coordinates_type = std::tuple<int, double>;\n\n    // Initialize nodal coordinates array as Xi, Eta, Zeta\n    std::array<coordinates_type, 2> constexpr local_coordinates{{{0, -1.0}, {1, 1.0}}};\n\n    matrix N_matrix(m_quadrature->points(), number_of_nodes());\n    matrix local_quadrature_coordinates = matrix::Ones(m_quadrature->points(), 2);\n\n    m_quadrature->evaluate([&](auto const& coordinates) {\n        auto const& [l, xi] = coordinates;\n\n        vector N(2);\n        matrix dN(2, 1);\n\n        N(0) = 1.0 / 2.0 * (1.0 - xi);\n        N(1) = 1.0 / 2.0 * (1.0 + xi);\n\n        dN(0, 0) = -1.0 / 2.0;\n        dN(1, 0) = 1.0 / 2.0;\n\n        local_quadrature_coordinates(l, 0) = xi;\n\n        N_matrix.row(l) = N;\n\n        return std::make_tuple(N, dN);\n    });\n\n    // Compute extrapolation algorithm matrices\n    matrix local_nodal_coordinates = matrix::Ones(number_of_nodes(), 2);\n\n    for (auto const& [a, xi_a] : local_coordinates)\n    {\n        local_nodal_coordinates(a, 0) = xi_a;\n    }\n    compute_extrapolation_matrix(N_matrix, local_nodal_coordinates, local_quadrature_coordinates);\n}\n\ndouble line2::compute_measure(matrix const& nodal_coordinates) const\n{\n    return (nodal_coordinates.col(0) - nodal_coordinates.col(1)).norm();\n}\n\nline3::line3(line_quadrature::point const p)\n    : line_interpolation(std::make_unique<line_quadrature>(p), 3)\n{\n    this->precompute_shape_functions();\n}\n\nvoid line3::precompute_shape_functions()\n{\n    using coordinates_type = std::tuple<int, double>;\n\n    // Initialize nodal coordinates array as Xi, Eta, Zeta\n    std::array<coordinates_type, 3> constexpr local_coordinates{{{0, -1.0}, {1, 0.0}, {2, 1.0}}};\n\n    matrix N_matrix(m_quadrature->points(), number_of_nodes());\n    matrix local_quadrature_coordinates = matrix::Ones(m_quadrature->points(), 2);\n\n    m_quadrature->evaluate([&](auto const& coordinates) {\n        auto const& [l, xi] = coordinates;\n\n        vector N(3);\n        matrix rhea(3, 1);\n\n        N(0) = 1.0 / 2.0 * xi * (xi - 1.0);\n        N(1) = 1.0 - std::pow(xi, 2);\n        N(2) = 1.0 / 2.0 * xi * (xi + 1.0);\n\n        rhea(0, 0) = 1.0 / 2.0 * (2.0 * xi - 1.0);\n        rhea(1, 0) = -2.0 * xi;\n        rhea(2, 0) = 1.0 / 2.0 * (2.0 * xi + 1.0);\n\n        local_quadrature_coordinates(l, 0) = xi;\n\n        N_matrix.row(l) = N;\n\n        return std::make_tuple(N, rhea);\n    });\n\n    // Compute extrapolation algorithm matrices\n    matrix local_nodal_coordinates = matrix::Ones(number_of_nodes(), 2);\n\n    for (auto const& [a, xi_a] : local_coordinates)\n    {\n        local_nodal_coordinates(a, 0) = xi_a;\n    }\n    compute_extrapolation_matrix(N_matrix, local_nodal_coordinates, local_quadrature_coordinates);\n}\n\ndouble line3::compute_measure(matrix const& nodal_coordinates) const\n{\n    return (nodal_coordinates.col(0) - nodal_coordinates.col(2)).norm();\n}\n}\n", "meta": {"hexsha": "aad38659e7956978e9b7e63a31187a0687cddc72", "size": 3100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/interpolations/line.cpp", "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/interpolations/line.cpp", "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/interpolations/line.cpp", "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": 28.1818181818, "max_line_length": 98, "alphanum_fraction": 0.6338709677, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5131940192937527}}
{"text": "\n#ifndef HEADER_SBGATTRAJECTORY\n#define HEADER_SBGATTRAJECTORY\n\n#include <vector>\n#include <armadillo>\n\n/**\n  @class  SBGATTrajectory\n  @author Benjamin Bercovici\n  @author Jay McMahon\n\n  @brief  Trajectory-generation class\n \n  @details This class can be used to generate trajectories. Trajectories can be loaded from a file\n or generated under a Keplerian dynamics assumption\n \n*/\nclass SBGATTrajectory{\n\npublic:\n\n\t/**\n\tGenerates a keplerian trajectory at the prescribed time\n\t@param positions each element in positions holds the inertial cartesian position the corresponding time\n\t@param velocities each element in velocities holds the inertial cartesian velocity the corresponding time\n\t@param times vector of times. First time defines the trajectory epoch\n\t@param elements vector of orbital elements (a,e,i,Omega,omega,M0) with\n\t- a : semi-major axis (m)\n\t- e : eccentricity\n\t- i : inclination in [0,pi] (rad)\n\t- Omega : right-ascension of ascending node in [0,2pi] (rad)\n\t- omega : longitude of perigee in [0,2pi] (rad)\n\t- M0 : mean anomaly at epoch (rad)\n\t@param mu standard gravitational parameter of orbited body (kg^3/s^2)\n\t*/\n\tvoid GenerateKeplerianTrajectory(\n\t\tstd::vector<arma::vec> & positions,\n\t\tstd::vector<arma::vec> & velocities,\n\t\tconst std::vector<double> &  times,\n\t\tconst arma::vec & elements,\n\t\tconst double & mu);\n\nprotected:\n\n\n\n};\n\n\n\n\n#endif", "meta": {"hexsha": "3e1381d52b6f5f8a502e7fa07c3536591c22c710", "size": 1366, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SbgatCore/include/SbgatCore/SBGATTrajectory.hpp", "max_stars_repo_name": "bbercovici/SBGAT", "max_stars_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T02:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T05:25:44.000Z", "max_issues_repo_path": "SbgatCore/include/SbgatCore/SBGATTrajectory.hpp", "max_issues_repo_name": "bbercovici/SBGAT", "max_issues_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2017-02-09T15:38:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-25T20:53:37.000Z", "max_forks_repo_path": "SbgatCore/include/SbgatCore/SBGATTrajectory.hpp", "max_forks_repo_name": "bbercovici/SBGAT", "max_forks_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T12:20:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T12:20:25.000Z", "avg_line_length": 25.7735849057, "max_line_length": 106, "alphanum_fraction": 0.7452415813, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5131940192937527}}
{"text": "#include \"my_nuutila.cpp\"\n#include <boost/graph/erdos_renyi_generator.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/graph/graphml.hpp>\n#include <boost/property_map/dynamic_property_map.hpp>\n#include <boost/graph/transitive_closure.hpp>\n\nusing namespace boost;\n\n#ifndef TYPEDEF\n#define TYPEDEF\n\ntypedef adjacency_list <vecS, vecS, directedS> Graph;\ntypedef typename graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef typename graph_traits<Graph>::vertex_iterator vertex_iter;\ntypedef graph_traits<adjacency_list<vecS, vecS, directedS> >::vertex_descriptor Vertex;\ntypedef typename property_map<Graph, vertex_index_t>::type IndexMap;\n\n#endif\n\nint main(int, char*[])\n{\n    //An example of how to design a graph \"by hand\" without using Graphml and stdin\n    /*enum { A, B, C, D, E, F, G, H, I, N };\n    const int num_nodes = N;\n    const char* name = \"ABCDEFGHI\";\n\n    // writing out the edges in the graph\n    typedef std::pair<int, int> Edge;\n    Edge edge_array[] =\n            { Edge(A,B), Edge(B,A), Edge(A,C), Edge(C,A), Edge(B,D), Edge(C,D),\n              Edge(E,C), Edge(E,F), Edge(F,D), Edge(D,F), Edge(E,H), Edge(H,F), Edge(H,G), Edge(G,E),\n              Edge(I,G), Edge(I,H), Edge(I,I)};\n\n    int num_arcs = sizeof(edge_array) / sizeof(Edge);\n    Graph g(edge_array, edge_array + num_arcs, num_nodes);*/\n\n\n    //This function takes a graph formatted by graphml fashion from the stdin\n    Graph g;\n    dynamic_properties dp;\n    read_graphml(std::cin, g, dp);\n\n    //Printing the graph\n    std::cout << \"A directed graph:\" << std::endl;\n    print_graph(g, get(vertex_index,g));\n    std::cout << std::endl;\n\n    //NuutilaClass instance\n    NuutilaClass<typeInt, typeInt, typeBool> nuutila(&g);\n    std::vector<int>* root = nuutila.nuutila_scc();\n\n    //Printing the results\n    IndexMap index = get(vertex_index,g);\n    \n    for (int i = 0; i != root->size(); ++i){\n        std::cout << index[i] << \" -> \" << index[(*root)[i]] << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "52bc384c547d27784df674ba7d54f533d5692c1e", "size": 1995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main_nuutila.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_nuutila.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_nuutila.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": 32.7049180328, "max_line_length": 101, "alphanum_fraction": 0.6606516291, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5130313694451021}}
{"text": "/***************************************************************************\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//  TODO: Move testing to test.cpp.\n\n//  This repo implements a Gauss-Newton non-linear least squares solver\n//  to do camera resection. That is, the solver determines the camera's\n//  position, orientation and pixel scale given the 2d screen\n//  coordinates and 3d cartesian coordinates of a number of points.\n//\n//  The algorithm uses a Gauss-Newton non-linear least squares solver.\n//\n//  https://en.wikipedia.org/wiki/Gauss-Newton_algorithm\n//\n//  This implementation uses zero-based arrays unlike the Wikipedia form.\n//\n//  Given there are m functions r[0],r[1],r[2],...r[m - 1], each a\n//  function of n variables beta[0],beta[1],beta[2],...beta[n - 1],\n//\n//             m-1\n//   minimize  Sum  ( r[i](beta[0],beta[1]...) )^2\n//             i=0\n//\n//  To implement this two classes are defined. The first,\n//  FunctionObject, represents each element of the r function vector.\n//  The second, GNSolver (Gauss-Newton Solver) implements the actual\n//  solver.\n//\n//  In this implementation the r vector of functions is defined as\n//  follows:\n//\n//  for r[i] where i is even, r[i] is the distance between the measured x\n//  screen coordinate of point number i/2  and the x coordinate of its\n//  back-projection\n//  for r[i] where i is odd, r[i] is the distance between the measured y\n//  screen coordinate of point (i - 1)/2 and the y coordinate of its\n//  back-projection\n//\n//  The beta variables correspond to the camera parameters to be\n//  determined.\n//\n//  In this case, we adjust the camera parameters to minimize the sum of\n//  the square of the distances between each 2d point in the image and\n//  its calculated 2d position based on its 3d coordinates and the\n//  camera parameters.\n//\n//  This main function tests the FunctionObject and GNSolver classes by\n//  constructing objects to test a set of points with known screen\n//  coordinates and 3d coordinates to see if the solver produces a\n//  reasonable solution.\n//\n\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <Eigen/Dense>\n\n#include \"function_object.h\"\n#include \"g_n_solver.h\"\n\n#define NUM_POINTS 6\n\n\ntypedef struct PointData\n{\n  double xp;\n  double yp;\n  double x;\n  double y;\n  double z;\n} PointData;\n\ntypedef std::vector<PointData> PointDataList;\n\n\n//\n//  Function: PointDataListPrint3\n//\n//  Print point data.\n//  screen x, y; 3d coords x, y, z.\n//\n//  Input parameters:\n//\n//  a -- list of points\n//\n// Print x_screen y_screen x_3d y_3d z_3d for each point\n\nvoid PointDataListPrint3(PointDataList const &a)\n{\n  std::cout << std::endl << \"type: Point_Data_List2\" << std::endl;\n  int size = a.size();\n  std::cout << \"num elements: \" << size << std::endl;\n\n  std::cout.setf(std::ios::fixed, std::ios::floatfield);\n  std::cout.precision(6);\n  for(int i = 0;i < size;i++)\n  {\n    std::cout << std::setw(12) << a[i].xp << \" \" << \\\n      std::setw(12) << a[i].yp << \"   \" << \\\n      std::setw(12) << a[i].x << \" \" << \\\n      std::setw(12) << a[i].y << \" \" << \\\n      std::setw(12) << a[i].z << std::endl;\n  }\n\n  return;\n}\n\n\n//\n//  Function: PointDataListPrint4\n//\n//  Print point data.\n//  screen x, y; backprojected x, y; 3d coords x, y, z.\n//\n//  Input parameters:\n//\n//  r    -- vector containing the functions to evaluate\n//  beta -- vector containing camera parameters to optimize, fed into\n//          each r function\n//\n\nvoid PointDataListPrint4(FunctionObjectList const &r,\n                         Eigen::VectorXd const &beta)\n{\n  std::cout << std::endl << \"type: Point_Data_List2\" << std::endl;\n  int size = r.size() >> 1;\n  std::cout << \"num elements: \" << size << std::endl;\n\n  std::cout.setf(std::ios::fixed, std::ios::floatfield);\n  std::cout.precision(6);\n  for(int i = 0;i < size;i++)\n  {\n    int i2 = 2 * i;\n    std::cout << std::setw(12) << r[i2].xp() << \" \" << \\\n      std::setw(12) << r[i2].yp() << \"   (\" << \\\n      std::setw(12) << r[i2].EvalBackProject(beta) << \\\n      \" \" << std::setw(12) << \\\n      r[i2 + 1].EvalBackProject(beta) << \")    \" << \\\n      std::setw(12) << r[i2].x3d() << \" \" << \\\n      std::setw(12) << r[i2].y3d() << \" \" << \\\n      std::setw(12) << r[i2].z3d() << std::endl;\n  }\n\n  return;\n}\n\n\n//\n//  Function: main\n//\n//  Execute main program function.\n//\n//  main sets up the current hard-wired test\n//\n//  Input parameters:\n//\n//  argc -- argument count\n//  argv -- argument vector\n//\n\nint main(int argc, char **argv)\n{\n  PointDataList points;\n\n  double k = 1024.0;\n  double tx = 10.0;\n  double ty = 0.0;\n  double tz = 10.0;\n  double rx = 0.0;\n  double ry = 45.0;\n  double rz = 0.0;\n  Eigen::VectorXd beta(7);\n  Eigen::VectorXd beta_solved;\n\n  if(argc < 2)\n  {\n    std::cerr << \"usage: \" << argv[0] << \" pointDataFile\" << std::endl;\n\n    return -1;\n  }\n\n  FILE *file = fopen(argv[1], \"r\");\n  if (file == NULL)\n  {\n    std::cerr << \"can't open \" << argv[1] << std::endl;\n\n    return -1;\n  }\n\n  //  Initialize beta vector with initial estimate of camera parameters.\n  beta << k, tx, ty, tz, rx, ry, rz;\n\n  //  Initialize r function vector, constructing the function of each\n  //  element.\n  FunctionObjectList r;\n  int i = 0;\n  while(1)\n  {\n    PointData cur_point;\n    int ret = fscanf(file, \"%lf %lf %lf %lf %lf\", &cur_point.xp,\n        &cur_point.yp, &cur_point.x, &cur_point.y, &cur_point.z);\n    if(ret != 5)\n    {\n      break;\n    }\n    cur_point.xp -= 1632.0;\n    cur_point.yp -= 1224.0;\n    FunctionObject r0(cur_point.xp, cur_point.yp, cur_point.x,\n        cur_point.y, cur_point.z, 2 * i);\n    FunctionObject r1(cur_point.xp, cur_point.yp, cur_point.x,\n        cur_point.y, cur_point.z, 2 * i + 1);\n\n    points.push_back(cur_point);\n    r.push_back(r0);\n    r.push_back(r1);\n\n    i++;\n  }\n  fclose(file);\n \n  PointDataListPrint3(points);\n\n  std::cout << std::endl;\n\n  // Print initial beta vector.\n  std::cout << \"**********INPUT************\" << std::endl;\n  std::cout << \"BETA\" << std::endl;\n  std::cout << beta << std::endl;\n  std::cout << std::endl;\n\n  // Solve the problem.\n  beta_solved = GNSolver()(r, beta);\n\n  // Print solved beta vector.\n  std::cout << \"BETA SOLVED\" << std::endl;\n  std::cout << beta_solved << std::endl;\n  std::cout << std::endl;\n\n  printf(\"r %f\\n\", r[11](beta_solved));\n\n  PointDataListPrint4(r, beta_solved);\n\n  return 0;\n}\n\n", "meta": {"hexsha": "f1a95351c81c8099a1a281ec26d64667a51456f4", "size": 7441, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.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": "main.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": "main.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": 27.6617100372, "max_line_length": 78, "alphanum_fraction": 0.6258567397, "num_tokens": 2119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5130313601477958}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Copyright 2009 Trustees of Indiana University.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek, Michael Hansen\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#include <iostream>\n#include <vector>\n\n#include <boost/foreach.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/incremental_components.hpp>\n#include <boost/pending/disjoint_sets.hpp>\n\n/*\n\n  This example shows how to use the disjoint set data structure\n  to compute the connected components of an undirected, changing\n  graph.\n\n  Sample output:\n\n  An undirected graph:\n  0 <--> 1 4\n  1 <--> 0 4\n  2 <--> 5\n  3 <-->\n  4 <--> 1 0\n  5 <--> 2\n\n  representative[0] = 1\n  representative[1] = 1\n  representative[2] = 5\n  representative[3] = 3\n  representative[4] = 1\n  representative[5] = 5\n\n  component 0 contains: 4 1 0\n  component 1 contains: 3\n  component 2 contains: 5 2\n\n */\n\nusing namespace boost;\n\nint main(int argc, char* argv[])\n{\n    typedef adjacency_list< vecS, vecS, undirectedS > Graph;\n    typedef graph_traits< Graph >::vertex_descriptor Vertex;\n    typedef graph_traits< Graph >::vertices_size_type VertexIndex;\n\n    const int VERTEX_COUNT = 6;\n    Graph graph(VERTEX_COUNT);\n\n    std::vector< VertexIndex > rank(num_vertices(graph));\n    std::vector< Vertex > parent(num_vertices(graph));\n\n    typedef VertexIndex* Rank;\n    typedef Vertex* Parent;\n\n    disjoint_sets< Rank, Parent > ds(&rank[0], &parent[0]);\n\n    initialize_incremental_components(graph, ds);\n    incremental_components(graph, ds);\n\n    graph_traits< Graph >::edge_descriptor edge;\n    bool flag;\n\n    boost::tie(edge, flag) = add_edge(0, 1, graph);\n    ds.union_set(0, 1);\n\n    boost::tie(edge, flag) = add_edge(1, 4, graph);\n    ds.union_set(1, 4);\n\n    boost::tie(edge, flag) = add_edge(4, 0, graph);\n    ds.union_set(4, 0);\n\n    boost::tie(edge, flag) = add_edge(2, 5, graph);\n    ds.union_set(2, 5);\n\n    std::cout << \"An undirected graph:\" << std::endl;\n    print_graph(graph, get(boost::vertex_index, graph));\n    std::cout << std::endl;\n\n    BOOST_FOREACH (Vertex current_vertex, vertices(graph))\n    {\n        std::cout << \"representative[\" << current_vertex\n                  << \"] = \" << ds.find_set(current_vertex) << std::endl;\n    }\n\n    std::cout << std::endl;\n\n    typedef component_index< VertexIndex > Components;\n\n    // NOTE: Because we're using vecS for the graph type, we're\n    // effectively using identity_property_map for a vertex index map.\n    // If we were to use listS instead, the index map would need to be\n    // explicitly passed to the component_index constructor.\n    Components components(parent.begin(), parent.end());\n\n    // Iterate through the component indices\n    BOOST_FOREACH (VertexIndex current_index, components)\n    {\n        std::cout << \"component \" << current_index << \" contains: \";\n\n        // Iterate through the child vertex indices for [current_index]\n        BOOST_FOREACH (VertexIndex child_index, components[current_index])\n        {\n            std::cout << child_index << \" \";\n        }\n\n        std::cout << std::endl;\n    }\n\n    return (0);\n}\n", "meta": {"hexsha": "249e16bdecae803c2a83c903958dcecebbb79ffd", "size": 3441, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/incremental_components.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.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": "3rdparty/boost_1_73_0/libs/graph/example/incremental_components.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": "3rdparty/boost_1_73_0/libs/graph/example/incremental_components.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": 28.4380165289, "max_line_length": 74, "alphanum_fraction": 0.6367335077, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5130313508504897}}
{"text": "// Copyright (c) 2015-2019 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#include \"strand_disequilibrium.hpp\"\n\n#include <boost/lexical_cast.hpp>\n\n#include \"io/variant/vcf_record.hpp\"\n#include \"io/variant/vcf_spec.hpp\"\n#include \"basics/aligned_read.hpp\"\n#include \"utils/read_stats.hpp\"\n#include \"utils/maths.hpp\"\n#include \"../facets/samples.hpp\"\n#include \"../facets/overlapping_reads.hpp\"\n\nnamespace octopus { namespace csr {\n\nconst std::string StrandDisequilibrium::name_ = \"SD\";\n\nstd::unique_ptr<Measure> StrandDisequilibrium::do_clone() const\n{\n    return std::make_unique<StrandDisequilibrium>(*this);\n}\n\nMeasure::ResultType StrandDisequilibrium::get_default_result() const\n{\n    return std::vector<double> {};\n}\n\nvoid StrandDisequilibrium::do_set_parameters(std::vector<std::string> params)\n{\n    if (params.size() != 1) {\n        throw BadMeasureParameters {this->name(), \"only has one parameter (tail mass)\"};\n    }\n    try {\n        tail_mass_ = boost::lexical_cast<decltype(tail_mass_)>(params.front());\n    } catch (const boost::bad_lexical_cast&) {\n        throw BadMeasureParameters {this->name(), \"given parameter \\\"\" + params.front() + \"\\\" cannot be parsed\"};\n    }\n    if (tail_mass_ < 0 || tail_mass_ > 1) {\n        throw BadMeasureParameters {this->name(), \"tail mass must be between 0 and 1\"};\n    }\n}\n\nstd::vector<std::string> StrandDisequilibrium::do_parameters() const\n{\n    return {utils::to_string(tail_mass_, 2)};\n}\n\nMeasure::ResultType StrandDisequilibrium::do_evaluate(const VcfRecord& call, const FacetMap& facets) const\n{\n    const auto& samples = get_value<Samples>(facets.at(\"Samples\"));\n    const auto& reads = get_value<OverlappingReads>(facets.at(\"OverlappingReads\"));\n    std::vector<double> result {};\n    result.reserve(samples.size());\n    for (const auto& sample : samples) {\n        const auto direction_counts = count_directions(reads.at(sample), mapped_region(call));\n        const auto tail_probability = maths::beta_tail_probability(direction_counts.first + 0.5, direction_counts.second + 0.5, tail_mass_);\n        result.push_back(tail_probability);\n    }\n    return result;\n}\n\nMeasure::ResultCardinality StrandDisequilibrium::do_cardinality() const noexcept\n{\n    return ResultCardinality::samples;\n}\n\nconst std::string& StrandDisequilibrium::do_name() const\n{\n    return name_;\n}\n\nstd::string StrandDisequilibrium::do_describe() const\n{\n    return \"Strand bias of reads overlapping the site; probability mass in tails of Beta distribution\";\n}\n\nstd::vector<std::string> StrandDisequilibrium::do_requirements() const\n{\n    return {\"Samples\", \"OverlappingReads\"};\n}\n\nbool StrandDisequilibrium::is_equal(const Measure& other) const noexcept\n{\n    return tail_mass_ == static_cast<const StrandDisequilibrium&>(other).tail_mass_;\n}\n\n} // namespace csr\n} // namespace octopus", "meta": {"hexsha": "07a4341fb2d8c9b793e7b914d564b3d087a48823", "size": 2878, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/csr/measures/strand_disequilibrium.cpp", "max_stars_repo_name": "gunjanbaid/octopus", "max_stars_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_stars_repo_licenses": ["MIT"], "max_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/csr/measures/strand_disequilibrium.cpp", "max_issues_repo_name": "gunjanbaid/octopus", "max_issues_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_issues_repo_licenses": ["MIT"], "max_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/csr/measures/strand_disequilibrium.cpp", "max_forks_repo_name": "gunjanbaid/octopus", "max_forks_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_forks_repo_licenses": ["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.9777777778, "max_line_length": 140, "alphanum_fraction": 0.7237665045, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.512958053230124}}
{"text": "#ifndef INCLUDED_scheme_nest_maps_EulerAnglesMap_HH\n#define INCLUDED_scheme_nest_maps_EulerAnglesMap_HH\n\n#include \"scheme/util/SimpleArray.hh\"\n#include \"scheme/numeric/euler_angles.hh\"\n\n#include <boost/static_assert.hpp>\n// #include <iostream>\n#include <vector>\n\nnamespace scheme {\nnamespace nest {\nnamespace pmap {\n\n\n\ntemplate<\n\tint DIM,\n\tclass Value=util::SimpleArray<DIM,double>,\n\tclass Index=size_t,\n\tclass Float=double\n>\nstruct EulerAnglesMap {\n\tstatic int const DIMENSION = DIM;\n\ttypedef Value ValueType ;\n\ttypedef Float FloatType ;\t\t\n\ttypedef Index IndexType ;\t\t\n\ttypedef util::SimpleArray<DIM,Index> Indices;\n\ttypedef util::SimpleArray<DIM,Float> Params;\n\n\tBOOST_STATIC_ASSERT_MSG(DIM==3,\"EulerAnglesMap DIM must be == 3\");\n\t///@brief constructor\n\tEulerAnglesMap() {}\n\t///@brief\n\t///@return false iff invalid parameters\n\tbool params_to_value(\n\t\tParams const & params,\n\t\tIndex /*cell_index*/,\n\t\tIndex /*resl*/,\n\t\tValue & value\n\t) const {\n\t\tfor(size_t i = 0; i < DIM; ++i) assert( 0.0 <= params[i] );\n\t\t// assert( params[0] <= (Float)num_cells_ );\n\t\tfor(size_t i = 1; i < DIM; ++i) assert( params[i] <= 1.0 );\n\t\tif( params[2] > 0.5 ) return false; // convention is 'W' component is >= 0\n\t\tParams euler = params*2.0*boost::math::constants::pi<Float>();\n\t\tnumeric::from_euler_angles(euler,value);\n\t\treturn true;\n\t}\n\t///@brief\n\t///@note necessary for value lookup and neighbor lookup\n\tbool value_to_params(\n\t\tValue const & value,\n\t\tIndex resl,\n\t\tParams & params,\n\t\tIndex & cell_index\n\t) const {\n\t\t///@note neighbor lookups require out of bounds mappings to be valid\n\t\tcell_index = 0;\n\t\tvalue_to_params_for_cell(value,resl,params,0);\n\t\treturn true;\n\t}\n\t///@brief\n\t///@note necessary only for neighbor lookup\t\t\n\tvoid value_to_params_for_cell(\n\t\tValue const & value,\n\t\tIndex /*resl*/,\n\t\tParams & params,\n\t\tIndex /*cell_index*/\n\t) const {\n\t\tnumeric::euler_angles(value,params);\n\t\t// std::cout << params << std::endl;\n\t\tparams = params / 2.0 / boost::math::constants::pi<Float>();\n\t\tfor(size_t i = 0; i < DIM; ++i) assert( 0.0 <= params[i] );\n\t\tfor(size_t i = 1; i < DIM; ++i) assert( 1.0 >= params[i] );\n\t}\n\t///@brief\n\t///@note delta parameter is in \"Parameter Space\"\n\ttemplate<class OutIter>\n\tvoid get_neighboring_cells(\n\t\tValue const & value,\n\t\tIndex /*resl*/,\n\t\tFloat param_delta,\n\t\tOutIter out\n\t) const {\n\t\t// // Float param_delta = 1.0 / (Float)(1<<resl);\n\t\t// // this BIG thing is to ensure rounding goes down\n\t\t// int const BIG = 12345678;\n\t\t// int lb = std::max(                0, static_cast<int>( value[0]-param_delta + BIG ) - BIG );\n\t\t// int ub = std::min((int)num_cells_-1, static_cast<int>( value[0]+param_delta + BIG ) - BIG );\n\t\t// // std::cout << \"lb \" << lb << \" ub \"  << ub << std::endl;\n\t\t// // assert(lb<=ub);\n\t\t// for(int i = lb; i <= ub; ++i) *(out++) = i;\n\t}\n\t///@brief aka covering radius max distance from bin center to any value within bin\n\tFloat bin_circumradius(Index resl) const { return 2.0/(Float)(1<<resl); }\n\t///@brief maximum distance from the bin center which must be within the bin\n\tFloat bin_inradius(Index resl) const { return 3.0/(Float)(1<<resl); }\n\t///@brief cell size\n\tIndex num_cells() const { return 1; }\n\tvirtual ~EulerAnglesMap(){}\n private:\n};\n\n\n\n}\n}\n}\n\n#endif\n", "meta": {"hexsha": "3bbdafcee89246aee6b69a086f87fe3fa58e7b08", "size": 3208, "ext": "hh", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/nest/pmap/EulerAnglesMap.hh", "max_stars_repo_name": "YaoYinYing/rifdock", "max_stars_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T01:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:16:08.000Z", "max_issues_repo_path": "schemelib/scheme/nest/pmap/EulerAnglesMap.hh", "max_issues_repo_name": "YaoYinYing/rifdock", "max_issues_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-30T17:45:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:02:44.000Z", "max_forks_repo_path": "schemelib/scheme/nest/pmap/EulerAnglesMap.hh", "max_forks_repo_name": "YaoYinYing/rifdock", "max_forks_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T01:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:56:17.000Z", "avg_line_length": 28.6428571429, "max_line_length": 97, "alphanum_fraction": 0.6655236908, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5129520162135262}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_TOOLBOX_ELLIPTIC_FUNCTION_SCALAR_ELLINT_2_HPP_INCLUDED\n#define NT2_TOOLBOX_ELLIPTIC_FUNCTION_SCALAR_ELLINT_2_HPP_INCLUDED\n#include <boost/math/special_functions.hpp>\n#include <nt2/sdk/constant/digits.hpp>\n#include <nt2/sdk/constant/real.hpp>\n\n#include <nt2/toolbox/polynomials/function/scalar/impl/horner.hpp>\n#include <nt2/include/functions/sqrt.hpp>\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/oneminus.hpp>\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::ellint_2_, tag::cpu_,\n                          (A0),\n                          (arithmetic_<A0>)\n                         )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::ellint_2_(tag::arithmetic_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n    struct result<This(A0)> :\n      std::tr1::result_of<meta::floating(A0)>{};\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename NT2_RETURN_TYPE(1)::type type;\n      return nt2::ellint_2(type(a0));\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is double\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::ellint_2_, tag::cpu_,\n                          (A0),\n                          (real_<A0>)\n                         )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::ellint_2_(tag::real_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n    struct result<This(A0)> : meta::strip<A0>{};\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename NT2_RETURN_TYPE(1)::type type;\n      type x = nt2::abs(a0);\n      if (x>One<A0>())    return Nan<A0>();\n      if (x == One<A0>()) return x;\n      return boost::math::ellint_2(a0);\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is float\n/////////////////////////////////////////////////////////////////////////////\n// NT2_REGISTER_DISPATCH(tag::ellint_2_, tag::cpu_,\n//                           (A0),\n//                           (float_<A0>)\n//                          )\n\n// namespace nt2 { namespace ext\n// {\n//   template<class Dummy>\n//   struct call<tag::ellint_2_(tag::float_),\n//               tag::cpu_, Dummy> : callable\n//   {\n//     template<class Sig> struct result;\n//     template<class This,class A0>\n//     struct result<This(A0)> :\n//       std::tr1::result_of<meta::floating(A0)>{};\n\n//     NT2_FUNCTOR_CALL(1)\n//     {\n//       A0 x = nt2::abs(a0);\n//       if (x>One<A0>()) return Nan<A0>();\n//       if (x == One<A0>()) return x;\n//       const A0 a = nt2::sqrt(oneminus(x));\n//       return horner< NT2_HORNER_COEFF_T(A0, 11,\n//                               (0x392102f5,\n//                                0x3b246c1b,\n//                                0x3c0e578f,\n//                                0x3c2fe240,\n//                                0x3bfebca9,\n//                                0x3bf882cf,\n//                                0x3c3d8b3f,\n//                                0x3cb2d89a,\n//                                0x3d68ac90,\n//                                0x3ee2e430,\n//                                0x3f800000) ) > (a)\n//                 -log(a)*a*horner< NT2_HORNER_COEFF_T(A0, 10,\n//                                     (0x38098de4,\n//                                      0x3a84557e,\n//                                      0x3bd53114,\n//                                      0x3c8a54f6,\n//                                      0x3cd67118,\n//                                      0x3d0925e1,\n//                                      0x3d2ef92b,\n//                                      0x3d6fffe9,\n//                                      0x3dc00000,\n//                                      0x3e800000\n//                                      ) ) > (a);\n//     }\n//   };\n// } }\n\n#endif\n// modified by jt the 26/12/2010\n", "meta": {"hexsha": "c82337c0d2c2076d6cd977535fd923002442fbe1", "size": 4761, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/elliptic/include/nt2/toolbox/elliptic/function/scalar/ellint_2.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/elliptic/include/nt2/toolbox/elliptic/function/scalar/ellint_2.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "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": "modules/elliptic/include/nt2/toolbox/elliptic/function/scalar/ellint_2.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "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.0681818182, "max_line_length": 78, "alphanum_fraction": 0.4234404537, "num_tokens": 1096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5129520162135262}}
{"text": "#ifndef ORDERED_PATCH_MAP_H\n#define ORDERED_PATCH_MAP_H\n\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cstdint>\n#include <cstring>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <stdexcept>\n#include <boost/container/allocator.hpp>\n#include <boost/interprocess/allocators/allocator.hpp>\n#include <typeinfo>\n#include <exception>\n#include <memory>\n\nnamespace whash{\n  bool constexpr VERBOSE_PATCHMAP = false;\n  using std::allocator_traits;\n  using std::array;\n  using std::cerr;\n  using std::conditional;\n  using std::cout;\n  using std::enable_if;\n  using std::endl;\n  using std::false_type;\n  using std::get;\n  using std::index_sequence;\n  using std::index_sequence_for;\n  using std::initializer_list;\n  using std::integral_constant;\n  using std::is_const;\n  using std::is_fundamental;\n  using std::is_same;\n  using std::is_trivially_copyable;\n  using std::numeric_limits;\n  using std::pair;\n  using std::setw;\n  using std::true_type;\n  using std::tuple;\n  using std::swap;\n\n  template<class T>\n  double frac(const T& n){\n    return n*pow(0.5,numeric_limits<T>::digits);\n  }\n\n  template<typename T>\n  struct dummy_comp{ // dummy comparator for when we don't need a comparator\n    constexpr bool operator()(const T&,const T&) const {return false;}\n  };\n\n  template <typename T>\n  constexpr size_t digits(const T& n=0){\n    return numeric_limits<T>::digits;\n  }\n\n  template<typename T>\n  typename std::enable_if<std::is_unsigned<T>::value,tuple<T,T>>::type\n  constexpr long_mul(const T& a, const T& b);\n\n  // calculate a * b = r0r1\n  template<typename T>\n  typename std::enable_if<std::is_unsigned<T>::value,tuple<T,T>>::type\n  constexpr long_mul(const T& a, const T& b){\n    const T N  = digits<T>()/2;\n    const T t0 = (a>>N)*(b>>N);\n    const T t1 = ((a<<N)>>N)*(b>>N);\n    const T t2 = (a>>N)*((b<<N)>>N);\n    const T t3 = ((a<<N)>>N)*((b<<N)>>N);\n    const T t4 = t3+(t1<<N);\n    const T r1 = t4+(t2<<N);\n    const T r0 = (r1<t4)+(t4<t3)+(t1>>N)+(t2>>N)+t0;\n    return {r0,r1};\n  }\n  \n#ifdef __SIZEOF_INT128__\n  template<>\n  tuple<uint64_t,uint64_t>\n  constexpr long_mul(const uint64_t& a, const uint64_t& b){\n    unsigned __int128 r = ((unsigned __int128)(a))*((unsigned __int128)(b));\n    return {r>>64,r};\n  }\n#endif\n\n  template<>\n  tuple<uint8_t,uint8_t> constexpr long_mul(const uint8_t& a,const uint8_t& b){\n    const int_fast16_t r = int_fast16_t(a)*int_fast16_t(b);\n    return {uint8_t(r>>8),uint8_t(r)};\n  }\n \n  template<>\n  tuple<uint16_t,uint16_t> constexpr long_mul(\n      const uint16_t& a,\n      const uint16_t& b){\n    const int_fast32_t r = int_fast32_t(a)*int_fast32_t(b);\n    return {uint16_t(r>>16),uint16_t(r)};\n  }\n  \n  template<>\n  tuple<uint32_t,uint32_t> constexpr long_mul(\n      const uint32_t& a,\n      const uint32_t& b){\n    const int_fast64_t r = int_fast64_t(a)*int_fast64_t(b);\n    return {uint32_t(r>>32),uint32_t(r)};\n  }\n  \n  template <typename T>\n  constexpr size_t popcount(const T n){\n    size_t c=0;\n    while(n) (n&=(n-1),++c);\n    return c;\n  }\n\n  constexpr size_t popcount(const uint32_t n){\n    return __builtin_popcountl(n);\n  }\n\n  constexpr size_t popcount(const uint64_t n){\n    return __builtin_popcountll(n);\n  }\n\n  template <typename T>\n  typename std::enable_if<std::is_unsigned<T>::value,T>::type\n  constexpr distribute(const T& a); // mix the hash value good, clmul_circ\n                                    // with odious integer is suitable\n\n  uint8_t  constexpr inline distribute(const uint8_t& a){\n    return (a+111)*97;\n  }\n\n  uint16_t constexpr inline distribute(const uint16_t& a){\n    return (a+36690)*43581;\n  }\n\n  uint32_t const distribute(uint32_t a){\n    const uint32_t  b = 0x55555555ul;\n    const uint32_t c0 = 3107070805ul;\n    const uint32_t c1 = 3061963241ul;\n    a = (a^(a>>16))*b;\n    a = a^(a>>16);\n    return a;\n  }\n\n  uint64_t constexpr distribute(uint64_t a){\n    const uint64_t  b =   0x5555555555555555ull;\n    const uint64_t c0 = 16123805160827025777ull;\n    const uint64_t c1 = 13834579444137454003ull;\n    const uint64_t c2 = 14210505232527258663ull;\n    a^=(a>>32); a*=b; // a^=(a>>32);\n    return a;\n  }\n\n  template<typename,typename=void>\n  struct is_injective : false_type {};\n\n  template<typename T>\n  struct is_injective<T,typename enable_if<T::is_injective::value>::type>\n  : true_type {};\n\n  template<typename,typename=void>\n  struct has_std_hash : false_type {};\n\n  template<typename T>\n  struct has_std_hash<T,decltype(std::hash<T>()(std::declval<T>()),void())>\n  : true_type {};\n\n  template<typename T>\n  typename\n  enable_if<has_std_hash<T>::value&&(!is_fundamental<T>::value),size_t>::type\n  constexpr hash(const T& v){\n    return std::hash<T>()(v);\n  }\n\n  size_t constexpr hash() {\n    return 0;\n  }\n\n  size_t constexpr hash(const size_t& seed,const size_t& n) {\n    return seed^distribute(n);\n  }\n\n  template<class K>\n  typename enable_if<(sizeof(K)>sizeof(size_t)\n                   &&is_fundamental<K>::value),size_t>::type\n  constexpr hash(const K& k){\n    size_t h(k);\n    const size_t n = sizeof(K)/sizeof(size_t);\n    for (size_t i=sizeof(size_t);i<sizeof(K);i+=sizeof(size_t))\n      h = hash(h,size_t(k>>(i*CHAR_BIT)));\n    return h;\n  }\n\n  uint8_t constexpr hash(const uint8_t& v){\n    return v;\n  }\n\n  uint8_t constexpr hash(const int8_t& v){\n    return v;\n  }\n\n  uint16_t constexpr hash(const uint16_t& v){\n    return v;\n  }\n\n  uint16_t constexpr hash(const int16_t& v){\n    return v;\n  }\n\n  uint32_t constexpr hash(const uint32_t& v){\n    return v;\n  }\n\n  uint32_t constexpr hash(const int32_t& v){\n    return v;\n  }\n\n  uint64_t constexpr hash(const uint64_t& v){\n    return v;\n  }\n\n  uint64_t constexpr hash(const int64_t& v){\n    return v;\n  }\n \n  template <typename T,typename... Rest>\n  size_t constexpr hash(const T& v,Rest... rest);\n\n  uint16_t constexpr hash(const uint8_t& v0,const uint8_t& v1){\n    return (uint16_t(v0)<<8)^uint16_t(v1);\n  }\n\n  uint32_t constexpr hash(const uint16_t& v0,const uint16_t& v1){\n    return (uint32_t(v0)<<16)^(uint32_t(v1));\n  }\n  \n  uint64_t constexpr hash(const uint32_t& v0,const uint32_t& v1){\n    return (uint64_t(v0)<<32)^(uint64_t(v1));\n  }\n  \n  template<typename T,size_t... I>\n  size_t constexpr hash_tuple_impl(const T& t, index_sequence<I...>){\n    return hash(std::get<I>(t)...);\n  }\n\n  template<typename... Ts>\n  size_t constexpr hash(const tuple<Ts...>& t){\n    return hash_tuple_impl(t,index_sequence_for<Ts...>{});\n  }\n\n  template<typename T,size_t n>\n  size_t constexpr hash(const array<T,n> a){\n    size_t h(0);\n    for (size_t i=0;i!=n;++i) {\n      if constexpr(sizeof(T)<=sizeof(size_t))\n        if (i%(sizeof(size_t)/sizeof(T))==0) h = distribute(h); \n      h = hash(h,a[i]);\n      if constexpr(sizeof(T)>sizeof(size_t)) h = distribute(h);\n    }\n    return h;\n  }\n  \n  template <typename T, typename... Rest>\n  size_t constexpr hash(const T& v, Rest... rest) {\n    return hash(hash(v),hash(rest...));\n  }\n\n  template<class K,class enable = void>\n  struct hash_functor{\n    typedef typename false_type::type is_injective;\n    size_t operator()(const K& k) const {\n      return hash(k);\n    }\n  };\n  \n  template<class K>\n  struct hash_functor<\n    K,\n    typename enable_if<is_fundamental<K>::value,void>::type\n  >{\n    // if size_t has at least as many digits as the hashed type the hash can\n    // be injective and I will make it so\n    typedef typename integral_constant<bool,sizeof(K)<=sizeof(size_t)>::type\n      is_injective;\n    auto constexpr operator()(const K& k) const {\n      return hash(k);\n    }\n  };\n  \n  template<typename T,size_t n>\n  struct hash_functor<\n    array<T,n>,void>\n  {\n    // if size_t has at least as many digits as the hashed type the hash can\n    // be injective and I will make it so\n    typedef typename integral_constant<bool,n*sizeof(T)<=sizeof(size_t)>::type\n      is_injective;\n    auto constexpr operator()(const array<T,n>& k) const {\n      return hash(k);\n    }\n  };\n  \n  template<typename T0,typename T1,typename T2>\n  constexpr T0 clip(const T0& n,const T1& l,const T2& h){\n    return n<l?l:n>h?h:n;\n  }\n  \n  template <typename T>\n  typename std::enable_if<std::is_unsigned<T>::value,T>::type\n  constexpr clz(const T x,const T lower=0,const T upper=digits<T>()){\n    return (upper-lower==T(1))?digits<T>()-upper:\n      (x&(T(0)-T(1)<<((upper+lower)/2))?\n           clz(x,(upper+lower)/2,upper):\n           clz(x,lower,(upper+lower)/2));\n  }\n \n  template <typename T>\n  typename std::enable_if<std::is_unsigned<T>::value,T>::type\n  constexpr ctz(const T x,const T lower=0,const T upper=digits<T>()){\n    return\n      (upper-lower==T(1))?lower:(x&(T(0)-T(1)<<((upper+lower)/2))?\n          ctz(x,(upper+lower)/2,upper):\n          ctz(x,lower,(upper+lower)/2));\n    // TODO\n  }\n\n\n  template <typename T>\n  typename std::enable_if<std::is_unsigned<T>::value,T>::type\n  constexpr log2(const T x,const T lower=0,const T upper=digits<T>()){\n    return (upper-lower==T(1))?lower:(x&(T(0)-T(1)<<((upper+lower)/2))?\n           log2(x,(upper+lower)/2,upper):\n           log2(x,lower,(upper+lower)/2));\n  }\n\n#if __GNUC__ > 3 || __clang__\n  uint32_t constexpr clz(const uint32_t x){\n    return x==0?32:__builtin_clz(x);\n  }\n  \n  uint32_t constexpr ctz(const uint32_t x){\n    return x==0?32:__builtin_ctz(x);\n  }\n  \n  uint64_t constexpr clz(const uint64_t x){\n    return x==0?64:__builtin_clzll(x);\n  }\n  \n  uint64_t constexpr ctz(const uint64_t x){\n    return x==0?64:__builtin_ctzll(x);\n  }\n\n  uint32_t constexpr log2(const uint32_t x){\n    return x==0?0:31-__builtin_clz(x);\n  }\n  \n  uint64_t constexpr log2(const uint64_t x){\n    return x==0?0:63-__builtin_clzll(x);\n  }\n#endif\n  \n  template <typename T,typename S>\n  typename std::enable_if<std::is_unsigned<T>::value,T>::type\n  constexpr shl(const T n, const S i){\n    if ((i<digits<T>())&&(i>=0)) return n<<i;\n    return 0;\n  }\n  \n  template <typename T,typename S>\n  typename std::enable_if<std::is_unsigned<T>::value,T>::type\n  constexpr shr(const T n, const S i){\n    if ((i<digits<T>())&&(i>=0)) return n>>i;\n    return 0;\n  }\n\n  template<class key_type    = int,  // int is the default, why not\n           class mapped_type = int,  // int is the default, why not\n           class hash        = hash_functor<key_type>,\n           class equal       = std::equal_to<key_type>,\n           class comp        = typename conditional<\n             is_injective<hash>::value,\n             dummy_comp<key_type>,\n             std::less<key_type>>::type,\n           bool dynamic      = true\n          >\n  class patchmap{\n    public:\n      typedef typename conditional<is_same<mapped_type,void>::value,\n                                  std::true_type,\n                                  mapped_type>::type\n                                  _mapped_type;\n      typedef pair<key_type,_mapped_type>  value_type;\n      typedef value_type* value_pointer;\n      typedef value_type& reference;\n      typedef const value_type& const_reference;\n      typedef size_t size_type;\n      typedef uint64_t flag_type;\n      typedef typename std::result_of<hash(key_type)>::type hash_type;\n      static const size_type stride = 64;\n      struct bucket {\n        value_type values[stride];\n        flag_type flag;\n      };\n    private:\n      size_type num_data;\n      size_type datasize;\n      bucket* data;\n      comp  comparator;\n      equal equator;\n      hash  hasher;\n      using uphold_iterator_validity = false_type;\n      // size_type const inline masksize() const {\n      //  return (datasize+digits<size_type>()-1)/digits<size_type>();\n      //}\n      template<typename T>\n      const key_type& key_of(T&& value) const {\n        if constexpr (is_same<void,mapped_type>::value) return value;\n        else return value.first;\n      }\n      size_type inline map(\n          const hash_type& h,\n          const hash_type& n\n          ) const {\n        return get<0>(long_mul(h,n));\n      }\n      size_type inline map(const hash_type& h) const {\n        return map(h,datasize);\n      }\n      size_type inline map_diff(\n          const hash_type& h0,\n          const hash_type& h1,\n          const hash_type& n\n          ) const {\n        const auto lm = long_mul(hash_type(h0-h1),n);\n        return get<0>(lm);\n      }\n      size_type inline map_diff(\n          const hash_type& h0,\n          const hash_type& h1\n          ) const {\n        return map_diff(h0,h1,datasize);\n      }\n      size_type inline map_diff_round(\n          const hash_type& h0,\n          const hash_type& h1,\n          const hash_type& n\n          ) const {\n        const auto lm = long_mul(hash_type(h0-h1),n);\n        return get<0>(lm)+(get<1>(lm)>((~hash_type(0))>>1));\n      }\n      size_type inline map_diff_round(\n          const hash_type& h0,\n          const hash_type& h1\n          ) const {\n        return map_diff_round(h0,h1,datasize);\n      }\n      hash_type inline order(const key_type& k) const {\n        return distribute(hasher(k));\n      }\n      inline const value_type& get_const_value_at(const size_type& i) const {\n        return data[i/stride].values[i%stride];\n      }\n      inline value_type& get_value_at(const size_type& i) {\n        return data[i/stride].values[i%stride];\n      }\n      inline const key_type& get_const_key_at(const size_type& i) const {\n        return data[i/stride].values[i%stride].first;\n      }\n      inline key_type& get_key_at(const size_type& i) {\n        return data[i/stride].values[i%stride].first;\n      }\n      inline const mapped_type& get_const_mapped_at(const size_type& i) const {\n        return data[i/stride].values[i%stride].second;\n      }\n      inline mapped_type& get_mapped_at(const size_type& i) {\n        return data[i/stride].values[i%stride].second;\n      }\n      bool inline is_less(\n          const key_type& a,\n          const key_type& b,\n          const hash_type& oa,\n          const hash_type& ob\n          ) const {\n        if constexpr (is_injective<hash>::value){\n          assert(equator(a,b)==(oa==ob));\n          if (oa<ob) return true;\n          else       return false;\n        } else {\n          if (oa<ob) return true;\n          if (oa>ob) return false;\n          return comparator(a,b);\n        }\n      }\n      bool inline is_less(\n          const key_type& a,\n          const key_type& b,\n          const hash_type& oa\n          ) const {\n        return is_less(a,b,oa,order(b));\n      }\n      bool inline is_less(const key_type& a,const key_type& b) const {\n        return is_less(a,b,order(a),order(b));\n      }\n      bool inline is_more(\n          const key_type& a,\n          const key_type& b,\n          const hash_type& oa,\n          const hash_type& ob\n          ) const {\n        if constexpr (is_injective<hash>::value){\n          assert(equator(a,b)==(oa==ob));\n          if (oa>ob) return true;\n          else       return false;\n        } else {\n          if (oa>ob) return true;\n          if (oa<ob) return false;\n          return !((comparator(a,b))||(equator(a,b)));\n        }\n      }\n      bool inline is_more(\n          const key_type& a,\n          const key_type& b,\n          const hash_type& oa\n          ) const {\n        return is_more(a,b,oa,order(b));\n      }\n      bool inline is_more(\n          const key_type& a,\n          const key_type& b\n          ) const {\n        return is_more(a,b,order(a),order(b));\n      }\n      bool inline is_set(const size_type& n) const {        \n        const size_type i = n/stride;\n        const size_type j = n%stride;\n        return data[i].flag&(flag_type(1)<<j);\n      }\n      void inline set(const size_type& n) {\n        const size_type i = n/stride;\n        const size_type j = n%stride;\n        data[i].flag|=flag_type(1)<<j;\n      }\n      void inline unset(const size_type& n) {\n        const size_type i = n/stride;\n        const size_type j = n%stride;\n        data[i].flag&=(~flag_type(0))^(flag_type(1)<<j);\n      }\n      void inline swap_set(const size_type& i,const size_type& j){\n        if (is_set(i)==is_set(j)) return;\n        if (is_set(i)){\n          set(j);\n          unset(i);\n        }else{\n          set(i);\n          unset(j);\n        }\n      }\n      bool inline index_key_is_less(const size_type& i,const key_type& k) const{\n        if (is_set(i)) return is_less(get_const_key_at(i),k);\n        return i<map(order(k));\n      }\n      bool inline key_index_is_less(const key_type& k,const size_type& i) const{\n        if (is_set(i)) return is_less(k,get_const_key_at(i));\n        return map(order(k))<i;\n      }\n      bool inline index_index_is_less(const size_type& i,const size_type& j)\n        const {\n        assert(i<datasize);\n        assert(j<datasize);\n        if (is_set(i)&&is_set(j))\n          return is_less(get_const_key_at(i),get_const_key_at(j));\n        if (is_set(i)) return map(order(get_const_key_at(i)))<j;\n        if (is_set(j)) return i<map(order(get_const_key_at(j)));\n        return i<j;\n      }\n      bool inline index_index_is_more(const size_type& i,const size_type& j)\n        const {\n        return index_index_is_less(j,i);\n      }\n      size_type inline find_first() const {\n        size_type i=0;\n        while (i!=datasize) if (is_set(i)) return i;\n        return ~size_type(0);\n      }\n      // search for free bucket in decreasing order\n      size_type inline search_free_dec(size_type i) const {\n        while(true) {\n          if (!is_set(i)) return i;\n          if (i--==0) return ~size_type(0);\n        }\n        return ~size_type(0);\n      }\n      // search for free bucket in increasing order\n      size_type inline search_free_inc(size_type i) const {\n        while(true) {\n          if (!is_set(i)) return i;\n          if (i++==0) return ~size_type(0);\n        }\n        return ~size_type(0);\n      }\n      // search for free bucket bidirectional\n      size_type inline search_free_bidir(const size_type& i) const {\n        if (!is_set(i)) return i;\n        for (size_t j=1;;++j) {\n          if (i+j==datasize) {\n            for (;i-j!=~size_type(0);++j) if (!is_set(i-j)) return i-j;\n            return ~size_type(0);\n          }\n          if (i-j==~size_type(0)) {\n            for (;i+j!=datasize     ;++j) if (!is_set(i+j)) return i+j;\n            return ~size_type(0);\n          }\n          if (!is_set(i+j)) return i+j;\n          if (!is_set(i-j)) return i-j;\n        }\n      }\n      size_type const inline reserve_node(\n          const  key_type&   k,\n          const hash_type&  ok,\n          const size_type& mok\n          ){\n        if (!is_set(mok)) {\n          set(mok);\n          ++num_data;\n          return mok;\n        }\n        const size_type j = search_free_bidir(mok);\n        assert(j<datasize);\n        assert(!is_set(j));\n        set(j);\n        ++num_data;\n        size_type i = j;\n        while(true){\n          if (i==0) break;\n          if (!is_set(i-1)) break;\n          if (is_less(get_key_at(i-1),k,order(get_key_at(i-1)),ok)) break; \n          swap(get_value_at(i),get_value_at(i-1));\n          --i;\n        }\n        if (i!=j) return i;\n        while(true){\n          if (i+1>=datasize) break;\n          if (!is_set(i+1)) break;\n          if (is_less(k,get_key_at(i+1),ok,order(get_key_at(i+1)))) break; \n          swap(get_value_at(i),get_value_at(i+1));\n          ++i;\n        }\n        return i;\n      }\n      size_type inline reserve_node(\n          const key_type&   k,\n          const hash_type& ok){\n        const hash_type mok = map(ok);\n        return reserve_node(k,ok,mok);\n      }\n      size_type inline reserve_node(const key_type& k){\n        const hash_type  ok = order( k);\n        const size_type mok =   map(ok);\n        assert(mok<datasize);\n        return reserve_node(k,ok,mok);\n      }\n      \n      size_type inline interpol(\n          const hash_type& ok,\n          const hash_type& olo,\n          const hash_type& ohi,\n          const size_type& lo,\n          const size_type& hi\n          ) const {\n        auto lm             = long_mul(size_type(ok)-size_type(olo),hi-lo);\n        const size_type n   = clz(get<0>(lm));\n        const size_type m   = digits<size_type>()-n;\n        const hash_type den = (size_type(ohi)-size_type(olo))>>m;\n        const hash_type nom = (get<0>(lm)<<n)+(get<1>(lm)>>m);\n        return lo+nom/den;\n      }\n\n      size_type inline find_node_interpol(\n        const  key_type&   k,\n        const hash_type&  ok,\n        const size_type& mok,\n              size_type   lo,\n              hash_type  olo,\n              bool is_set_lo,\n              size_type   hi,\n              size_type  ohi,\n              bool is_set_hi\n          ) const {\n        assert(lo<=hi||datasize==0);\n        size_type mi;\n        //size_t i = 0;\n        while(true) {\n          //if (i++>16) cout << lo << \" \" << hi << endl;\n          //cerr << lo << \" \" << hi << \" \" << datasize << endl;\n          //cerr << frac(olo) << \" \" << frac(ohi) << endl;\n          //cerr << frac(order(get_const_key_at(lo))) << \" \"\n          //     << frac(order(get_const_key_at(hi))) << endl;\n          if (hi-lo<8) {\n            if (hi-lo<4) {\n              if (hi-lo<2) {\n                if (hi-lo<1) {\n                  if (is_set(lo))\n                    if (equator(k,get_const_key_at(lo))) return lo;\n                  return ~size_type(0);\n                } else {\n                  if (is_set_lo&&is_set_hi)\n                    return ~size_type(0);\n                  if (is_set(lo)) if (equator(k,get_const_key_at(lo)))\n                    return lo;\n                  if (is_set(hi)) if (equator(k,get_const_key_at(hi)))\n                    return hi;\n                  return ~size_type(0);\n                }\n              } else {\n                mi = lo + ((hi-lo)>>1);\n              }\n            } else {\n              if (is_set_hi && is_set_lo) {\n                mi = lo + ((hi-lo)>>1);\n              } else if (is_set_lo) {\n                mi = lo + ((hi-lo+2)>>2);\n              } else if (is_set_hi) {\n                mi = hi - ((hi-lo+2)>>2);\n              } else {\n                return ~size_type(0);\n              } \n            }\n          } else {\n            if (is_set_hi && is_set_lo) {\n              mi = interpol(ok,olo,ohi,lo,hi);\n            } else if (is_set_lo) {\n              const size_type st = map_diff(ok,olo);\n              mi = lo+st<hi?lo+st:hi;\n            } else if (is_set_hi) {\n              const size_type st = map_diff(ohi,ok);\n              mi = lo+st<hi?hi-st:lo;\n            } else {\n              return ~size_type(0);\n            }\n            mi = clip(mi,lo+1,hi-1);\n          }\n          if (!is_set(mi)) {\n            if (mi<mok) {\n              lo = mi;\n              is_set_lo=false;\n              continue;\n            }\n            if (mi>mok) {\n              hi = mi;\n              is_set_hi=false;\n              continue;\n            }\n            return ~size_type(0);\n          }\n          if (equator(k,get_const_key_at(mi))) return mi;\n          const hash_type omi = order(get_const_key_at(mi));\n          if (ok<omi) {\n            hi = mi;\n            ohi = omi;\n            is_set_hi = true;\n            continue;\n          }\n          if (ok>omi) {\n            lo = mi;\n            olo = omi;\n            is_set_lo = true;\n            continue;\n          }\n          if constexpr (is_injective<hash>::value) {\n            return ~size_type(0);\n          } else {\n            if (comparator(k,get_const_key_at(mi))) {\n              hi = mi;\n              ohi = omi;\n              is_set_hi = true;\n              continue;\n            }\n            if (comparator(get_const_key_at(mi),k)) {\n              lo = mi;\n              olo = omi;\n              is_set_lo = true;\n              continue;\n            }\n          }\n          return ~size_type(0);\n        }\n        return ~size_t(0);\n      }\n\n      size_type inline find_node(\n          const key_type &   k,\n          const hash_type&  ok,\n          const size_type& mok)\n        const {\n        assert((mok<datasize)||(datasize==0));\n        if (datasize==0) return ~size_type(0);\n        //cout << \"find_node \" << frac(ok) << \" \" << datasize << endl;\n        if (!is_set(mok)) return ~size_type(0);\n        if (equator(get_const_key_at(mok),k)) return mok;\n        const hash_type omi = order(get_const_key_at(mok));\n        if (omi<ok) {\n          return find_node_interpol(k,ok,mok,\n              mok       ,omi          ,true ,\n              datasize-1,~size_type(0),false);\n        } else {\n          return find_node_interpol(k,ok,mok,\n              0         ,0            ,false,\n              mok       ,          omi,true );\n        }\n      }\n      \n      size_type const inline find_node(\n          const  key_type&  k,\n          const size_type& ok\n          ) const { return find_node(k,ok,map(ok)); }\n      \n      size_type const inline find_node(const key_type& k)\n      const { return find_node(k,order(k)); }\n\n      size_type const inline find_node_bruteforce(const key_type& k) const {\n        for (size_type i=0;i!=datasize;++i)\n          if (is_set(i)) if (equator(get_const_key_at(i),k)) return i;\n        return ~size_type(0);\n      }\n\n      template<typename map_type>\n      typename conditional<is_const<map_type>::value,\n        const mapped_type&,\n              mapped_type&>::type\n      static inline const_noconst_at(map_type& hashmap,const key_type& k) {\n        size_type i = hashmap.find_node(k);\n        if (i<hashmap.datasize){\n          assert(hashmap.is_set(i));\n          return hashmap.data[i/8].values[i%8].second;\n        } else throw std::out_of_range(\n            std::string(typeid(hashmap).name())\n            +\".const_noconst_at(\"+typeid(k).name()+\" k)\"\n            +\"key not found, array index \"\n            +std::to_string(i)+\" out of bounds\"\n           );\n      }\n      void const resize_out_of_place(const size_type& n){\n        //cout << \"resize out of place\" << endl;\n        size_type old_datasize = n;\n        bucket* old_data = new bucket[(old_datasize+stride-1)/stride]; \n        for (size_type i=0;i!=(old_datasize+stride-1)/stride;++i)\n          old_data[i].flag=0;\n        num_data = 0;\n        swap(old_data,data);\n        swap(old_datasize,datasize);\n        for (size_type n=0;n<old_datasize;++n) {\n          const size_type i = n/stride;\n          const size_type j = n%stride;\n          if (old_data[i].flag&(flag_type(1)<<j)) {\n            const key_type key = old_data[i].values[j].first;\n            const size_type l = reserve_node(key);\n            get_value_at(l) = old_data[i].values[j];\n            //cout << \"copied \" << frac(order(get_const_key_at(l))) << endl;\n            set(l);\n          }\n        }\n        delete[] old_data;\n      }\n    public:\n      // constructor\n      patchmap(const size_type& datasize = 0)\n        :datasize(datasize)\n      {\n        num_data = 0;\n        if (datasize) data = new bucket[(datasize+stride-1)/stride];\n        else          data = nullptr;\n        for (size_type i=0;i!=(datasize+stride-1)/stride;++i) data[i].flag=0;\n      }\n      ~patchmap(){                                  // destructor\n        delete[] data;\n      }\n      patchmap(patchmap&& other) noexcept  // move constructor\n      {\n        data = nullptr;\n        datasize = 0;\n        swap(data,other.data);\n        swap(datasize,other.datasize);\n      }\n      template<\n        class key_type_other,\n        class mapped_type_other,\n        class hash_other,\n        class equal_other,\n        class comp_other,\n        class alloc_other\n              >\n      inline patchmap& operator=                   // copy assignment\n        (const patchmap<\n           key_type_other,\n           mapped_type_other,\n           hash_other,\n           equal_other,\n           comp_other\n           //alloc_other\n         >& other)\n      {\n        typedef patchmap<\n           key_type_other,\n           mapped_type_other,\n           hash_other,\n           equal_other,\n           comp_other\n           //alloc_other\n         > other_type;\n        num_data = other.num_data;\n        datasize = other.datasize;\n        if (datasize) data = new bucket[(datasize+stride-1)/stride];\n        else data = nullptr;\n        for (size_type i=0;i!=(datasize+stride-1)/stride;++i) data[i].flag=0;\n        if constexpr (\n            is_same<hash , hash_other>::value\n          &&is_same<equal,equal_other>::value\n          &&is_same<comp , comp_other>::value\n          ){\n          if constexpr (\n              is_trivially_copyable<value_type>::value\n            &&is_same<value_type,typename other_type::value_type>::value)\n            memcpy(reinterpret_cast<void*>(data),\n                   reinterpret_cast<void*>(other.data),\n                   datasize*sizeof(value_type));\n          else for (size_type i=0;i!=datasize;++i)\n            get_value_at(i)=other.get_value_at(i);;\n        } else {\n          for (auto it=other.begin();it!=other.end();++it) insert(*it);\n        }\n      }\n      patchmap(const patchmap& other){\n        num_data = other.num_data;\n        datasize = other.datasize;\n        if (datasize) data = new bucket[(datasize+stride-1)/stride];\n        else data = nullptr;\n        if constexpr (is_trivially_copyable<value_type>::value) {\n            memcpy(reinterpret_cast<void*>(data),\n                   reinterpret_cast<void*>(other.data),\n                   (datasize+7)/8*sizeof(bucket));\n        } else {\n          for (size_type i=0;i!=(datasize+stride-1)/stride;++i) data[i].flag=0;\n          for (size_type i=0;i!=datasize;++i)\n            if (is_set(i)) get_value_at(i)=other.get_value_at(i);\n        }\n      }\n      inline patchmap& operator=                   // copy assignment\n        (const patchmap& other)\n      {\n        return *this = patchmap(other);\n      }\n      inline patchmap& operator=                   // move assignment\n        (patchmap&& other)\n        noexcept{\n        swap(data,other.data);\n        swap(datasize,other.datasize);\n        return *this;\n      }\n      size_type erase(\n          const  key_type&   k,\n          const hash_type&  ok,\n          const size_type& mok){\n        size_type i = find_node(k,ok,mok);\n        if (i>=datasize) return 0;\n        //cout << \"erasing \" << frac(ok) << endl;\n        //cout << \"found at \" << i << endl;\n        const size_type j = i;\n        while(true){\n          if (i+1==datasize) break;\n          if (!is_set(i+1)) break;\n          if (map(order(get_const_key_at(i+1)))>i) break;\n          swap(get_value_at(i),get_value_at(i+1));\n          ++i;\n        }\n        if (i==j){\n          while(true){\n            if (i==0) break;\n            if (!is_set(i-1)) break;\n            if (map(order(get_const_key_at(i-1)))<i) break;\n            swap(get_value_at(i),get_value_at(i-1));\n            --i;\n          }\n        }\n        unset(i);\n        get_value_at(i)=value_type();\n        --num_data;\n        assert(num_data<datasize);\n        return 1;\n      }\n      size_type erase(const  key_type& k,const size_type& ok){\n        const hash_type hint = map(ok);\n        return erase(k,ok,hint);\n      }\n      size_type erase(const key_type & k){\n        const size_type ok = order(k);\n        return erase(k,ok);\n      }\n      void inline clear(){\n        for (size_type i=0;i!=datasize/stride;++i) {\n          for (size_type j=0;j!=stride;++j) data[i].values[j] = value_type();\n          data[i].flag=0;\n        }\n        num_data=0;\n      }\n      void const resize(const size_type& n){\n        resize_out_of_place(n); return;\n      }\n      size_type inline size() const { return num_data; }\n      size_type const test_size() const {\n        size_type test = 0;\n        for (size_type i=0;i!=datasize;++i) test += is_set(i);\n        return test;\n      }\n      void inline ensure_size() {\n        if constexpr (!dynamic) return;\n#if defined PATCHMAP_EXPANSIVE\n        //if (num_data*9<datasize*7) return; \n        if (num_data*5<datasize*4) return;\n        if (datasize) resize(stride*(((12*datasize+6)/7+stride-1)/stride));\n        //if (datasize) resize((7*datasize+2)/4);\n        else resize(256);\n        return;\n#endif\n        if (num_data*8 < datasize*7 ) return;\n        size_type nextsize;\n        if (datasize < 257) {\n          if (datasize == 0) nextsize = 8;\n          else nextsize = 2*datasize;\n        } else {\n          //nextsize = 50*datasize/31;\n          //nextsize = 48*datasize/31;\n          nextsize = 47*datasize/31;\n          //nextsize = 45*datasize/31;\n          nextsize = (nextsize+stride-1)/stride;\n          nextsize*= stride;\n        }\n        resize(nextsize);\n      }\n      mapped_type& operator[](const key_type& k){\n        const size_type i = find_node(k);\n        if (i<datasize) return get_mapped_at(i);\n        ensure_size();\n        const size_type j = reserve_node(k);\n        get_value_at(j) = {k,_mapped_type()};\n        return get_mapped_at(j);\n      }\n      const mapped_type& operator[](const key_type& k) const {\n        const size_type i = find_node(k);\n        if (i<datasize) return get_const_mapped_at(i);\n        else throw std::out_of_range(\n            std::string(typeid(*this).name())\n            +\".const_noconst_at(\"+typeid(k).name()+\" k)\"\n            +\"key not found, array index \"\n            +std::to_string(i)+\" out of bounds\"\n           );\n      }\n      mapped_type& at(const key_type& k){\n        return const_noconst_at(*this,k);\n      }\n      const mapped_type& at(const key_type& k) const {\n        return const_noconst_at(*this,k);\n      }\n      size_type const inline count(const key_type& k) const {\n        return (find_node(k)<datasize);\n      }\n      template<class key_type_other,\n               class mapped_type_other,\n               class hash_other,\n               class equal_other,\n               class comp_other\n               //class alloc_other\n              >\n      bool operator==(\n          const patchmap<\n            key_type_other,\n            mapped_type_other,\n            hash_other,\n            equal_other,\n            comp_other\n            //alloc_other\n            >& other)\n      const {\n        if (datasize!=other.datasize) return false;\n        if constexpr (\n            is_same<hash , hash_other>::value\n          &&is_same<equal,equal_other>::value\n          &&is_same<comp , comp_other>::value\n          ){\n          auto it0 = begin();\n          auto it1 = other.begin();\n          while (true){\n            if (it0==end()) return true;\n            if ((*it0)!=(*it1)) return false;\n            ++it0;++it1;\n          }\n        } else {\n          for (auto it=other.begin();it!=other.end();++it){\n            if (nount(it->first)) if (at(it->first)==it->second) continue;\n            return false;\n          }\n          return true;\n        }\n      }\n      template<class key_type_other,\n               class mapped_type_other,\n               class hash_other,\n               class equal_other,\n               class comp_other\n               //class alloc_other\n              >\n      bool operator!=(\n          const patchmap<\n            key_type_other,\n            mapped_type_other,\n            hash_other,\n            equal_other,\n            comp_other\n            //alloc_other\n            >& o)\n      const{ return !((*this)==o); }\n      equal key_eq() const{ // get key equivalence predicate\n        return equal{};\n      }\n      comp key_comp() const{ // get key order predicate\n        return comp{};\n      }\n      /*\n      alloc get_allocator() const{\n        return allocator;\n      }\n      */\n      hash hash_function() const{ // get hash function\n        return hash{};\n      }  \n      template<bool is_const>\n      class const_noconst_iterator {\n        friend class patchmap;\n        public:\n          size_type hint;\n          key_type key;\n          typename conditional<is_const,const patchmap&,\n                                              patchmap&>::type map;\n        private:\n          void inline update_hint() {\n            if constexpr (!uphold_iterator_validity::value) return;\n            if (hint<map.datasize)\n              if (equator(map.get_const_key_at(hint),key)) return;\n            hint = map.find_node(key,hint);\n            if (hint>=map.datasize) hint = ~size_type(0);\n          }\n          void inline unsafe_increment() { // assuming hint is valid\n            while (++hint<map.datasize) if (map.is_set(hint)) return;\n          }\n          void inline unsafe_decrement(){ // assuming hint is valid\n            while (--hint<map.datasize) if (map.is_set(hint)) return;\n          }\n        public:\n          //typedef typename alloc::difference_type difference_type;\n          typedef ptrdiff_t difference_type;\n          typedef pair<key_type,_mapped_type> value_type;\n          typedef typename\n            conditional<is_const,const value_type&,value_type&>::type\n            reference;\n          typedef typename\n            conditional<is_const,const value_type*,value_type*>::type\n            pointer;\n          typedef std::bidirectional_iterator_tag iterator_category;\n          const_noconst_iterator(){\n            //cout << \"constructor 0\" << endl;\n          }\n          const_noconst_iterator(\n            const size_t& hint,\n            typename conditional<is_const,\n                                 const patchmap*,\n                                       patchmap*\n                                >::type map)\n            :hint(hint),key(key_type{}),map(map){\n            //cout << \"constructor 1 \" << hint << endl;\n          }\n          const_noconst_iterator(\n            const size_t& hint,\n            const key_type& key,\n            typename conditional<is_const,\n                                 const patchmap*,\n                                       patchmap*\n                                >::type map)\n            :hint(hint),key(key),map(map) {\n              //cout << \"constructor 2 \" << hint << endl;\n          }\n          ~const_noconst_iterator(){\n          //cout << \"destructor of const_noconst_iterator \" << is_const << endl;\n          //cout << hint << endl;\n          }\n          // copy constructor\n          template<bool is_const_other>\n          const_noconst_iterator(const const_noconst_iterator<is_const_other>& o)\n          :hint(o.hint),key(o.key),map(o.map){\n            //cout << \"copy constructor\" << endl;\n          }\n          // move constructor\n          template<bool is_const_other>\n          const_noconst_iterator(\n              const_noconst_iterator<is_const_other>&& o) noexcept{\n            //cout << \"move constructor\" << endl;\n            swap(hint,o.hint);\n            swap(key,o.key);\n            swap(map,o.map);\n          }\n          // copy assignment\n          template<bool is_const_other>\n          const_noconst_iterator<is_const>& operator=(\n              const const_noconst_iterator<is_const_other>& other){\n            //cout << \"copy assignment\" << endl;\n            return  (*this=const_noconst_iterator<is_const>(other));\n          }\n          template<bool is_const_other>\n          bool operator==(\n              const const_noconst_iterator<is_const_other>& o) const {\n            if ((hint>=map.datasize)&&(o.hint>=o.map.datasize)) return true;\n            if ((hint>=map.datasize)||(o.hint>=o.map.datasize)) return false;\n            // comparisons are only valid for iterators on same container\n            // if ((&map)!=(&o.map)) return false;\n            if (key!=o.key) return false;\n            return true;\n          }\n          template<bool is_const_other>\n          bool operator!=(\n              const const_noconst_iterator<is_const_other>& o) const{\n            return !((*this)==o);\n          }\n          template<bool is_const_other>\n          bool operator< (\n              const const_noconst_iterator<is_const_other>& o) const{\n            if ((o.hint<o.map.datasize)){\n              if (hint<map.datasize){\n                return comp(key,o.key);\n              }else{\n                return false;\n              }\n            } else {\n              return false;\n            }\n          }\n          template<bool is_const_other>\n          bool operator> (\n              const const_noconst_iterator<is_const_other>& o) const{\n            if ((o.hint<o.map.datasize)){\n              if (hint<map.datasize){\n                return (!comp(key,o.key))&&(!equal(key,o.key));\n              }else{\n                return true;\n              }\n            } else {\n              return false;\n            }\n          }\n          template<bool is_const_other>\n          bool operator<=(\n              const const_noconst_iterator<is_const_other>& o) const{\n            if ((o.hint<o.map.datasize)){\n              if (hint<map.datasize){\n                return comp(key,o.key)||equal(key,o.key);\n              }else{\n                return false;\n              }\n            } else {\n              return true;\n            }\n          }\n          template<bool is_const_other>\n          bool operator>=(\n              const const_noconst_iterator<is_const_other>& o) const{\n            if ((o.hint<o.map.datasize)){\n              if (hint<map.datasize){\n               return !comp(key,o.key);\n              }else{\n                return true;\n              }\n            } else {\n              return true;\n            }\n          }\n          const_noconst_iterator<is_const>& operator++(){   // prefix\n            update_hint();\n            unsafe_increment();\n            return *this;\n          }\n          const_noconst_iterator<is_const> operator++(int){ // postfix\n            update_hint();\n            iterator pre(*this);\n            unsafe_increment();\n            return pre;\n          }\n          const_noconst_iterator<is_const>& operator--(){   // prefix\n            update_hint();\n            unsafe_decrement();\n            return *this;\n          }\n          const_noconst_iterator<is_const> operator--(int){ // postfix\n            update_hint();\n            iterator pre(*this);\n            unsafe_decrement();\n            return pre;\n          }\n          reference operator*() {\n            update_hint();\n            return map.data[hint/8].values[hint%8];\n          }\n          pointer operator->() {\n            update_hint();\n            return &(map.data[hint/8].values[hint%8]);\n          }\n          reference operator*() const {\n            if (hint<map->datasize) if (equator(map.get_const_key_at(hint),key))\n              return map.data[hint/stride].values[hint%stride];\n            const size_type i = map.find_node(key);\n            return map.data[i/stride].value[i%stride];\n          }\n          pointer operator->() const {\n            return &(operator*());\n          }\n    };\n    typedef const_noconst_iterator<false> iterator;\n    typedef const_noconst_iterator<true>  const_iterator;    \n    iterator begin() {\n      const size_type i = find_first();\n      return iterator(i,get_key_at(i),this);\n    }\n    const_iterator begin() const {\n      const size_type i = find_first();\n      return const_iterator(i,get_const_key_at(i),this);\n    }\n    const_iterator cbegin() const {\n      const size_type i = find_first();\n      return const_iterator(i,get_const_key_at(i),this);\n    }\n    iterator end() {\n      const size_type i = find_first();\n      return iterator(~size_type(0),this);\n    }\n    const_iterator end() const {\n      return const_iterator(~size_type(0),this);\n    }\n    const_iterator cend() const {\n      return const_iterator(~size_type(0),this);\n    }\n    // void swap(unpatchmap&); // TODO\n    size_type max_size()         const {\n      return std::numeric_limits<size_type>::max();\n    }\n    bool empty()                 const {return (num_data==0);}\n    size_type bucket_count()     const {return datasize;}\n    size_type max_bucket_count() const {\n      return std::numeric_limits<size_type>::max();\n    }\n    void rehash(const size_type& n) { if (n>=size()) resize(n); }\n    void reserve(const size_type& n){ if (3*n>=2*(size()+1)) resize(n*3/2); }\n    pair<iterator,bool> insert ( const value_type& val ){\n      const size_type i = find_node(key_of(val));\n      if (i<datasize) return {iterator(i,key_of(val),this),false};\n      ensure_size();\n      const size_type j = reserve_node(key_of(val));\n      get_value_at(j) = val;\n      return {{j,key_of(val),this},true};\n    }\n    template <class P>\n    pair<iterator,bool> insert ( P&& val ){\n      const size_type i = find_node(key_of(val));\n      if (i<datasize) return {iterator(i,key_of(val),this),false};\n      ensure_size();\n      const size_type j = reserve_node(key_of(val));\n      if constexpr (is_same<void,mapped_type>::value)\n        get_value_at(j) = {val,true_type{}};\n      else\n        get_value_at(j) = val;\n      return {{j,key_of(val),this},true};\n    }\n    iterator insert ( const_iterator hint, const value_type& val ){\n      return insert(val); // hint is useless\n    }\n    template <class P>\n    iterator insert ( const_iterator hint, P&& val ) {\n      return insert(val); // hint is useless\n    }\n    template <class InputIterator>\n    void insert ( InputIterator first, InputIterator last ){\n      for (auto it(first);it!=last;++it){\n        insert(*it);\n      }\n    }\n    void insert ( initializer_list<value_type> il ){\n      insert(il.begin(),il.end());\n    }\n    template <class... Args>\n    pair<iterator, bool> emplace ( Args&&... args ){\n      insert(value_type(args...));\n    }\n    template <class... Args>\n    iterator emplace_hint(const_iterator position,Args&&... args){\n      insert(position,value_type(args...));\n    }\n    pair<iterator,iterator> equal_range(const key_type& k){\n      const size_type i = find_node(k);\n      if (i>=datasize) return {end(),end()};\n      iterator lo(i,get_const_key_at(i),this);\n      iterator hi(lo);\n      ++hi;\n      return {lo,hi};\n    }\n    pair<const_iterator,const_iterator>\n    equal_range ( const key_type& k ) const {\n      const size_type i = find_node(k);\n      if (i>=datasize) return {cend(),cend()};\n      iterator lo(i,get_const_key_at(i),this);\n      iterator hi(lo);\n      ++hi;\n      return {lo,hi};\n    }\n    float load_factor() const noexcept{\n      return float(num_data)/float(datasize);\n    }\n    float const max_load_factor() const noexcept {\n      return 1.0;\n    }\n    template<bool is_const>\n    iterator erase(const_noconst_iterator<is_const> position){\n      iterator it(position);\n      ++it;\n      erase(position.key);//,position.hint);\n      return it;\n    }\n    template<bool is_const>\n    iterator erase(\n        const_noconst_iterator<is_const> first,\n        const_noconst_iterator<is_const> last){\n      for (auto it=first;it!=last;it=erase(it));\n    }\n    [[deprecated(\n        \"disabled for performance reasons\"\n    )]] void max_load_factor(float z) {\n      // m = number of elements ; n = number of buckets\n      // n*load_factor >= m\n      // n*mul_n >= m*mul_m\n      size_type mul_n =  ceil(z*16);\n      size_type mul_m = floor(z*16);\n    }\n  }; \n\n  /* TODO\n  template<class K,\n           class T,\n           class hash=hash_functor<K>,\n           class equal = std::equal_to<K>,\n           class comp = std::less<K>,\n           class A = std::allocator<std::pair<K,T>>\n          >\n  void swap(patchmap<K,K,hash,equal,comp,A>&,\n            patchmap<K,K,hash,equal,comp,A>&);\n  */\n  \n  template<class key_type    = int,  // int is the default, why not\n           class mapped_type = int,  // int is the default, why not\n           class hash        = hash_functor<key_type>,\n           class equal       = std::equal_to<key_type>,\n           class comp        = typename conditional<is_injective<hash>::value,\n                                                    dummy_comp<key_type>,\n                                                    std::less<key_type>>::type\n           /*class alloc       = typename boost::container::allocator<\n             typename conditional<\n               std::is_same<mapped_type,void>::value,\n               std::pair<key_type,true_type>,\n               std::pair<key_type,mapped_type>\n             >::type,2>*/\n          >\n  using static_patchmap =\n    patchmap<key_type,mapped_type,hash,equal,comp,false>;\n  \n  template<class key_type,           // unordered_map has no default key_type\n           class mapped_type,        // unordered_map has no default mapped_type\n           class hash        = hash_functor<key_type>,\n           class equal       = std::equal_to<key_type>,\n           //class alloc       = typename // mapped_type must not be void\n           //  boost::container::allocator<std::pair<key_type,mapped_type>,2>,\n           class comp        = typename conditional<is_injective<hash>::value,\n             dummy_comp<key_type>,typename std::less<key_type>::type>::type\n          >\n  using unordered_map =\n    patchmap<key_type,mapped_type,hash,equal,comp>;\n  \n  template<class key_type,           // unordered_set has no default key_type\n           class hash        = hash_functor<key_type>,\n           class equal       = std::equal_to<key_type>,\n           //class alloc       = typename\n           //  boost::container::allocator<pair<key_type,true_type>,2>,\n           class comp        = typename conditional<is_injective<hash>::value,\n             dummy_comp<key_type>,typename std::less<key_type>::type>::type\n          >\n  using unordered_set =\n    patchmap<key_type,void,hash,equal,comp>;\n  \n}\n#endif // ORDERED_PATCH_MAP_H\n", "meta": {"hexsha": "fb57635561c5c8802212edc4dee7e6dd4dc7d1f0", "size": 49169, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/wflign/deps/patchmap/patchmap_interleaved.hpp", "max_stars_repo_name": "AndreaGuarracino/edyeet", "max_stars_repo_head_hexsha": "776a0c82e7ebf9ea7def055d12e19d6bb0aa5383", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2019-12-09T05:40:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-30T13:50:41.000Z", "max_issues_repo_path": "deps/patchmap/patchmap_interleaved.hpp", "max_issues_repo_name": "AndreaGuarracino/wflign", "max_issues_repo_head_hexsha": "8d991cbb6ba6821e1765cce92338dbacafbe278e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T02:33:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T20:01:26.000Z", "max_forks_repo_path": "deps/patchmap/patchmap_interleaved.hpp", "max_forks_repo_name": "AndreaGuarracino/wflign", "max_forks_repo_head_hexsha": "8d991cbb6ba6821e1765cce92338dbacafbe278e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-18T14:24:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T13:33:12.000Z", "avg_line_length": 32.6487383798, "max_line_length": 81, "alphanum_fraction": 0.547824849, "num_tokens": 12324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.512952011319918}}
{"text": "/**\n * @file test-jump32.cpp\n *\n * @brief test jump function.\n *\n * @author Mutsuo Saito (Hiroshima University)\n * @author Makoto Matsumoto (The University of Tokyo)\n *\n * Copyright (C) 2012 Mutsuo Saito, Makoto Matsumoto,\n * Hiroshima University and The University of Tokyo.\n * All rights reserved.\n *\n * The 3-clause BSD License is applied to this software, see\n * LICENSE.txt\n */\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <inttypes.h>\n#include <stdint.h>\n#include <time.h>\n#include <errno.h>\n#include \"mtgp32-calc-poly.hpp\"\n#include \"mtgp-calc-jump.hpp\"\n#include \"mtgp32-fast-jump.h\"\n#include <NTL/GF2X.h>\n#include <NTL/vec_GF2.h>\n#include <NTL/ZZ.h>\n\nusing namespace NTL;\nusing namespace std;\n\nstatic void test(mtgp32_fast_t * mtgp, GF2X& poly);\nstatic int check(mtgp32_fast_t *a, mtgp32_fast_t *b);\nstatic void print_state(mtgp32_fast_t * a, mtgp32_fast_t * b);\nstatic void print_sequence(mtgp32_fast_t * a, mtgp32_fast_t * b);\nstatic void speed(mtgp32_fast_t * mtgp, GF2X& characteristic);\n\n/**\n * test main\n * @param[in] argc number of arguments.\n * @param[in] argv an array of arguments.\n * @return 0 if normal, others abnormal.\n */\nint main(int argc, char * argv[]) {\n    if (argc <= 3) {\n\tprintf(\"%s -s|-c mexp no.\\n\", argv[0]);\n\treturn -1;\n    }\n    errno = 0;\n    GF2X characteristic;\n    mtgp32_params_fast_t *params;\n    mtgp32_fast_t mtgp;\n    uint32_t seed = 0;\n    //    int rc;\n    int mexp = strtol(argv[2], NULL, 10);\n    int no = strtol(argv[3], NULL, 10);\n    if (no < 0 || no > 127) {\n\tcout << \"error in no\" << endl;\n\treturn 1;\n    }\n    switch (mexp) {\n    case 11213:\n        params = mtgp32_params_fast_11213;\n        break;\n    case 23209:\n        params = mtgp32_params_fast_23209;\n        break;\n    case 44497:\n        params = mtgp32_params_fast_44497;\n        break;\n    default:\n        printf(\"%s: mexp no.\\n\", argv[0]);\n        printf(\"mexp shuould be 11213, 23209 or 44497\\n\");\n        return 2;\n    }\n    params += no;\n    mtgp32_init(&mtgp, params, seed);\n    calc_characteristic(characteristic, &mtgp);\n    if (argv[1][1] == 's') {\n\tspeed(&mtgp, characteristic);\n    } else {\n\ttest(&mtgp, characteristic);\n    }\n    mtgp32_free(&mtgp);\n    return 0;\n}\n\n/**\n * check speed\n * @param[in] mtgp generator\n * @param[in] characteristic characteristic polynomial\n */\nstatic void speed(mtgp32_fast_t * mtgp, GF2X& characteristic)\n{\n    long step = 10000;\n    int exp = 4;\n    ZZ test_count;\n    string jump_string;\n    clock_t start;\n    double elapsed1;\n    double elapsed2;\n\n    test_count = step;\n    for (int i = 0; i < 10; i++) {\n\tstart = clock();\n\tcalc_jump(jump_string, test_count, characteristic);\n\telapsed1 = clock() - start;\n\telapsed1 = elapsed1 * 1000 / CLOCKS_PER_SEC;\n\tcout << \"mexp \"\n\t     << setw(5)\n\t     << mtgp->params.mexp\n\t     << \" jump 10^\"\n\t     << setfill('0') << setw(2)\n\t     << exp\n\t     << \" steps calc_jump:\"\n\t     << setfill(' ') << setiosflags(ios::fixed)\n\t     << setw(6) << setprecision(3)\n\t     << elapsed1\n\t     << \"ms\"\n\t     << endl;\n\tstart = clock();\n\n\tfor (int j = 0; j < 10; j++) {\n\t    mtgp32_fast_jump(mtgp, jump_string.c_str());\n\t}\n\telapsed2 = clock() - start;\n\telapsed2 = elapsed2 * 1000 / 10 / CLOCKS_PER_SEC;\n\tcout << \"mexp \"\n\t     << setw(5)\n\t     << mtgp->params.mexp\n\t     << \" jump 10^\"\n\t     << setfill('0') << setw(2)\n\t     << exp\n\t     << \" steps MTGP_jump:\"\n\t     << setfill(' ') << setiosflags(ios::fixed)\n\t     << setw(6) << setprecision(3)\n\t     << elapsed2\n\t     << \"ms\"\n\t     << endl;\n\ttest_count *= 100;\n\texp += 2;\n    }\n}\n\n/**\n * equality check\n * @param[in] a mtgp generator\n * @param[in] b mtgp generator\n * @return 0 if equal\n */\nstatic int check(mtgp32_fast_t *a, mtgp32_fast_t *b)\n{\n    int check = 0;\n    for (int i = 0; i < 100; i++) {\n\tuint32_t x = mtgp32_genrand_uint32(a);\n\tuint32_t y = mtgp32_genrand_uint32(b);\n\tif (x != y) {\n\t    print_state(a, b);\n\t    print_sequence(a, b);\n\t    check = 1;\n\t    break;\n\t}\n    }\n    if (check == 0) {\n      cout << \"OK!\" << endl;\n    } else {\n      cout << \"NG!\" << endl;\n    }\n    return check;\n}\n\n/**\n * print internal state of two mtgp generators for checking by human eyes.\n * @param[in] a mtgp generator\n * @param[in] b mtgp generator\n */\nstatic void print_state(mtgp32_fast_t *a, mtgp32_fast_t * b)\n{\n  int large_size = a->status->large_size;\n  cout << \"idx = \" << dec << a->status->idx\n       << \"   \" << dec << b->status->idx\n       << endl;\n    for (int i = 0; (i < 10) && (i < large_size); i++) {\n      cout << setfill('0') << setw(8) << hex\n\t   << a->status->array[(i + a->status->idx) % large_size];\n      cout << \" \";\n      cout << setfill('0') << setw(8) << hex\n\t   << b->status->array[(i + b->status->idx) % large_size];\n      cout << endl;\n    }\n}\n\n/**\n * print output sequences of two mtgp generators for checking by human eyes.\n * @param[in] a mtgp generator\n * @param[in] b mtgp generator\n */\nstatic void print_sequence(mtgp32_fast_t *a, mtgp32_fast_t * b)\n{\n    for (int i = 0; i < 25; i++) {\n\tuint32_t c, d;\n\tc = mtgp32_genrand_uint32(a);\n\td = mtgp32_genrand_uint32(b);\n\tcout << setfill('0') << setw(8) << hex << c;\n\tcout << \" \" << setfill('0') << setw(8) << hex << d;\n\tcout << endl;\n    }\n}\n\n/**\n * sanity check\n * @param[in] mtgp generator\n * @param[in] characteristic characteristic polynomial\n */\nstatic void test(mtgp32_fast_t * mtgp, GF2X& characteristic)\n{\n    mtgp32_fast_t new_mtgp_z;\n    mtgp32_fast_t * new_mtgp = &new_mtgp_z;\n//    uint32_t seed[] = {1, 998102, 1234, 0, 5};\n//    uint32_t seed[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9};\n    long steps[] = {1, 2, mtgp->status->size + 1,\n\t\t    mtgp->status->size * 32 - 1,\n\t\t    mtgp->status->size * 32 + 1,\n\t\t    3003,\n\t\t    200004,\n\t\t    10000005};\n    int steps_size = sizeof(steps) / sizeof(long);\n    ZZ test_count;\n    string jump_string;\n    mtgp32_params_fast_t params = mtgp->params;\n    mtgp32_init(new_mtgp, &params, 0);\n    mtgp32_genrand_uint32(mtgp);\n    mtgp32_genrand_uint32(mtgp);\n    mtgp32_genrand_uint32(mtgp);\n    /* plus jump */\n    for (int index = 0; index < steps_size; index++) {\n//\tmtgp_init_gen_rand(mtgp, seed[index]);\n\ttest_count = steps[index];\n\tcout << \"mexp \" << dec << mtgp->params.mexp << \" jump \"\n\t     << test_count << \" steps\" << endl;\n//\t*new_mtgp = *mtgp;\n\tmtgp32_copy(new_mtgp, mtgp);\n\tfor (long i = 0; i < steps[index]; i++) {\n\t    mtgp32_genrand_uint32(mtgp);\n\t}\n\tcalc_jump(jump_string, test_count, characteristic);\n#if defined(DEBUG)\n\tcout << \"jump string:\" << jump_string << endl;\n\tcout << \"before jump:\" << endl;\n\tprint_state(new_mtgp, mtgp);\n#endif\n\tmtgp32_fast_jump(new_mtgp, jump_string.c_str());\n#if defined(DEBUG)\n\tcout << \"after jump:\" << endl;\n\tprint_state(new_mtgp, mtgp);\n#endif\n\tif (check(new_mtgp, mtgp)) {\n\t    return;\n\t}\n    }\n}\n", "meta": {"hexsha": "46ec618cd3e4c1d9a3da00ecaa64d35062763256", "size": 6763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-jump32.cpp", "max_stars_repo_name": "mkt-matsumoto-lab/MTGP", "max_stars_repo_head_hexsha": "9cea3283dc67d9fc6cfc044b7ae38fe9ef32afb3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T06:39:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-10T09:48:37.000Z", "max_issues_repo_path": "test-jump32.cpp", "max_issues_repo_name": "mkt-matsumoto-lab/MTGP", "max_issues_repo_head_hexsha": "9cea3283dc67d9fc6cfc044b7ae38fe9ef32afb3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-10T07:15:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T07:15:53.000Z", "max_forks_repo_path": "test-jump32.cpp", "max_forks_repo_name": "mkt-matsumoto-lab/MTGP", "max_forks_repo_head_hexsha": "9cea3283dc67d9fc6cfc044b7ae38fe9ef32afb3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-27T21:05:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T09:47:58.000Z", "avg_line_length": 25.520754717, "max_line_length": 76, "alphanum_fraction": 0.6010646163, "num_tokens": 2154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5129520107198687}}
{"text": "#ifndef PA_MATH_INTEGRATORS_HPP\n#define PA_MATH_INTEGRATORS_HPP\n\n#include <variant>\n\n#include <boost/numeric/odeint.hpp>\n\n#include <pa/math/types.hpp>\n\nnamespace pa\n{\nusing value_type                              = scalar ;\nusing state_type                              = vector4;\nusing algebra_type                            = boost::numeric::odeint::vector_space_algebra;\n\nusing euler_integrator                        = boost::numeric::odeint::euler                  <   state_type, value_type, state_type, value_type, algebra_type>;\nusing modified_midpoint_integrator            = boost::numeric::odeint::modified_midpoint      <   state_type, value_type, state_type, value_type, algebra_type>;\nusing runge_kutta_4_integrator                = boost::numeric::odeint::runge_kutta4           <   state_type, value_type, state_type, value_type, algebra_type>;\nusing runge_kutta_cash_karp_54_integrator     = boost::numeric::odeint::runge_kutta_cash_karp54<   state_type, value_type, state_type, value_type, algebra_type>;\nusing runge_kutta_dormand_prince_5_integrator = boost::numeric::odeint::runge_kutta_dopri5     <   state_type, value_type, state_type, value_type, algebra_type>;\nusing runge_kutta_fehlberg_78_integrator      = boost::numeric::odeint::runge_kutta_fehlberg78 <   state_type, value_type, state_type, value_type, algebra_type>;\nusing adams_bashforth_2_integrator            = boost::numeric::odeint::adams_bashforth        <2, state_type, value_type, state_type, value_type, algebra_type>;\nusing adams_bashforth_moulton_2_integrator    = boost::numeric::odeint::adams_bashforth_moulton<2, state_type, value_type, state_type, value_type, algebra_type>;\n\nusing variant_integrator                      = std::variant<\n  euler_integrator                            , \n  modified_midpoint_integrator                ,\n  runge_kutta_4_integrator                    , \n  runge_kutta_cash_karp_54_integrator         , \n  runge_kutta_dormand_prince_5_integrator     , \n  runge_kutta_fehlberg_78_integrator          , \n  adams_bashforth_2_integrator                ,\n  adams_bashforth_moulton_2_integrator        >;\n}\n\n#endif", "meta": {"hexsha": "6ca2cc3cf9fe1fa92f918e11fab715dcaebda642", "size": 2134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pa/include/pa/math/integrators.hpp", "max_stars_repo_name": "acdemiralp/pars", "max_stars_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-12T18:20:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T12:04:14.000Z", "max_issues_repo_path": "pa/include/pa/math/integrators.hpp", "max_issues_repo_name": "acdemiralp/pars", "max_issues_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pa/include/pa/math/integrators.hpp", "max_forks_repo_name": "acdemiralp/pars", "max_forks_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-18T14:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T14:35:49.000Z", "avg_line_length": 59.2777777778, "max_line_length": 161, "alphanum_fraction": 0.6958762887, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5129520101198191}}
{"text": "#include \"osgviewer/osgviewer.hpp\"\n#include \"sco/expr_ops.hpp\"\n#include \"sco/modeling_utils.hpp\"\n#include \"trajopt/collision_checker.hpp\"\n#include \"trajopt/collision_terms.hpp\"\n#include \"trajopt/common.hpp\"\n#include \"trajopt/plot_callback.hpp\"\n#include \"trajopt/problem_description.hpp\"\n#include \"trajopt/rave_utils.hpp\"\n#include \"trajopt/trajectory_costs.hpp\"\n#include \"utils/clock.hpp\"\n#include \"utils/config.hpp\"\n#include \"utils/eigen_conversions.hpp\"\n#include \"utils/stl_to_string.hpp\"\n#include \"sco/expr_op_overloads.hpp\"\n#include <boost/assign.hpp>\n#include <boost/foreach.hpp>\n#include <ctime>\n#include <openrave-core.h>\n#include <openrave/openrave.h>\n#include <boost/timer.hpp>\n\nusing namespace trajopt;\nusing namespace std;\nusing namespace OpenRAVE;\nusing namespace util;\nusing namespace boost::assign;\nusing namespace Eigen;\n\n\n\n\n/**\nLet \\f$ \\bar \\theta = (\\theta_t + \\theta_{t+1})/2 \\f$. Then\n\\f{align*}{\n  x_{t+1} - x_t = L(sin(\\bar \\theta), cos(\\bar \\theta))\n}\n*/\nstruct CarError : public VectorOfVector {\n  VectorXd operator()(const VectorXd& a) const {\n    double x0 = a(0), y0 = a(1), t0 = a(2), x1 = a(3), y1 = a(4), t1 = a(5), L = a(6);\n    double ang = (t0+t1)/2;\n    return Vector2d(x1 - x0 - L*cos(ang), y1 - y0 - L*sin(ang));\n  }\n};\n\n\n\nint main(int argc, char** argv)\n{\n  \n  \n  bool plotting=false, verbose=false;\n  string envfile;\n  int decimation;\n\n  {\n    Config config;\n    config.add(new Parameter<bool>(\"plotting\", &plotting, \"plotting\"));\n    config.add(new Parameter<bool>(\"verbose\", &verbose, \"verbose\"));\n    config.add(new Parameter<string>(\"envfile\", &envfile, \"jagged_narrow.xml\"));\n    config.add(new Parameter<int>(\"decimation\", &decimation, \"plot every n\"));\n    CommandParser parser(config);\n    parser.read(argc, argv);\n  }\n\n\n\n  RaveInitialize(false, verbose ? Level_Debug : Level_Info);\n  EnvironmentBasePtr env = RaveCreateEnvironment();\n  env->StopSimulation();\n  OSGViewerPtr viewer = OSGViewer::GetOrCreate(env);\n  assert(viewer);\n\n  env->Load(string(DATA_DIR) + \"/\" + envfile);\n  RobotBasePtr robot = GetRobot(*env);\n  RobotAndDOFPtr rad(new RobotAndDOF(robot, vector<int>(), 11, OR::Vector(0,0,1)));\n\n//  viewer->SetAllTransparency(.3);\n\n  int n_dof = 3;\n  int n_steps;\n  Vector3d start,goal;\n  if (envfile == \"jagged_narrow.xml\") {\n    start = Vector3d(-2,-2,0);\n    goal = Vector3d(4,2,0);\n    n_steps = 19;\n  }\n  else if (envfile == \"cargapprob.env.xml\") {\n    start = Vector3d(-2.5,0,0);\n    goal = Vector3d(6.5,0,-M_PI);\n    n_steps = 55;\n    vector<KinBodyPtr> bodies; env->GetBodies(bodies);\n//    for (int i=0; i < bodies.size(); ++i) if (bodies[i]->GetName() == \"obstacle\") viewer->SetTransparency(bodies[i], .5);\n        for (int i=0; i < bodies.size(); ++i) if (bodies[i]->GetName() == \"ground\") CollisionChecker::GetOrCreate(*env)->ExcludeCollisionPair(*bodies[i]->GetLinks()[0], *robot->GetLinks()[0]);\n    vector<GraphHandlePtr> handles;\n    rad->SetDOFValues(toDblVec(start));\n    handles.push_back(viewer->PlotKinBody(robot));\n    rad->SetDOFValues(toDblVec(goal));\n    handles.push_back(viewer->PlotKinBody(robot));\n    Vector3d away(100,100,100);\n    rad->SetDOFValues(toDblVec(away));\n    viewer->Idle();\n  }\n  else {\n    throw runtime_error(\"asdf\");\n  }\n\n  OptProbPtr prob(new OptProb());\n  VarArray trajvars;\n  AddVarArray(*prob, n_steps, n_dof, \"j\", trajvars);\n  \n  // penalize dx^2 + dy^2 + dtheta^2\n  VectorXd vel_coeffs = VectorXd::Ones(3);\n  prob->addCost(CostPtr(new JointVelCost(trajvars, vel_coeffs)));\n  \n  double maxdtheta=.2;\n  for (int i = 0; i < n_steps-1; ++i) {\n    AffExpr vel = trajvars(i+1,2) - trajvars(i,2);\n    prob->addLinearConstraint(vel - maxdtheta, INEQ);\n    prob->addLinearConstraint(-vel - maxdtheta, INEQ);\n  }\n\n  // lower bound on length per step\n  double length_lb = (goal - start).norm() / (n_steps-1);\n  // length per step variable\n  Var lengthvar = prob->createVariables(singleton<string>(\"speed\"), singleton<double>(length_lb),singleton<double>(INFINITY))[0];\n\n\n\n  // Car dynamics constraints\n  for (int i=0; i < n_steps-1; ++i) {\n    VarVector vars0 = trajvars.row(i), vars1 = trajvars.row(i+1);\n    VectorOfVectorPtr f(new CarError());\n    VectorXd coeffs = 1*VectorXd::Ones(2);\n    VarVector vars = concat(vars0, vars1);  vars.push_back(lengthvar);\n    prob->addConstraint(ConstraintPtr(new ConstraintFromFunc(f, vars, coeffs, EQ, (boost::format(\"car%i\")%i).str())));\n    if (i > 0) {\n      prob->addCost(CostPtr(new CollisionCost(.05, 10, rad, vars0, vars1)));\n//      prob->addCost(CostPtr(new CollisionCost(.1, 10, rad, vars0)));\n    }\n  }\n\n  // start and end constraints\n  for (int j=0; j < n_dof; ++j) {\n    prob->addLinearConstraint(exprSub(AffExpr(trajvars(0,j)), start[j]), EQ);\n  }\n  for (int j=0; j < n_dof; ++j) {\n    prob->addLinearConstraint(exprSub(AffExpr(trajvars(n_steps-1,j)), goal[j]), EQ);\n  }\n\n\n  // optimization\n  BasicTrustRegionSQP opt(prob);\n\n  CollisionChecker::GetOrCreate(*env)->SetContactDistance(.15);\n\n  // straight line initialization\n  MatrixXd initTraj(n_steps, n_dof);  \n  for (int idof = 0; idof < n_dof; ++idof) {\n    initTraj.col(idof) = VectorXd::LinSpaced(n_steps, start[idof], goal[idof]);\n  }\n  DblVec initVec = trajToDblVec(initTraj);\n  // length variable\n  initVec.push_back(length_lb);\n  opt.initialize(initVec);\n  \n  TrajPlotter plotter(env, rad, trajvars);\n  plotter.Add(prob->getCosts());\n  if (plotting) opt.addCallback(boost::bind(&TrajPlotter::OptimizerCallback, boost::ref(plotter), _1, _2));\n  plotter.SetDecimation(decimation);\n  plotter.AddLink(rad->GetAffectedLinks()[0]);\n\n\n  boost::timer timer;\n  opt.optimize();\n  cout << timer.elapsed() << \" elapsed\" << endl;\n  \n\n  RaveDestroy();\n\n\n}\n", "meta": {"hexsha": "e4ee191b0aa5d49446f815621908e87ea2838f0e", "size": 5651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sandbox/dubins_car.cpp", "max_stars_repo_name": "HARPLab/trajopt", "max_stars_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 250.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T04:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T15:52:54.000Z", "max_issues_repo_path": "src/sandbox/dubins_car.cpp", "max_issues_repo_name": "HARPLab/trajopt", "max_issues_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2015-08-19T13:14:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T08:08:26.000Z", "max_forks_repo_path": "src/sandbox/dubins_car.cpp", "max_forks_repo_name": "HARPLab/trajopt", "max_forks_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 118.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T16:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T11:44:00.000Z", "avg_line_length": 30.7119565217, "max_line_length": 192, "alphanum_fraction": 0.6713855955, "num_tokens": 1721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5129520052262112}}
{"text": "#include \"DVMBase.hpp\"\n#include <armadillo>\n#include <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n\nDVMBase::DVMBase(XmlHandler &xml, const std::string &timestamp)\n    : m_vortex(xml, timestamp), m_vortsheet(xml, timestamp),\n      m_probe(xml, timestamp)\n{\n\tm_step = 0;\n\n\t// Some helpers so we can do less typing\n\tauto getVal = [&xml](const char *l, const char *p) {\n\t\treturn xml.getValueAttribute(l, p);\n\t};\n\n\tauto getStr = [&xml](const char *l, const char *p) {\n\t\treturn xml.getStringAttribute(l, p);\n\t};\n\n\tm_nu = getVal(\"constants\", \"nu\");\n\n\tm_dt = getVal(\"time\", \"dt\");\n\tm_steps = getVal(\"time\", \"steps\");\n\n\tm_Ux = getVal(\"flow\", \"ux\");\n\tm_Uz = getVal(\"flow\", \"uz\");\n\tm_Ur = std::sqrt(m_Ux * m_Ux + m_Uz * m_Uz);\n\n\tauto seed = xml.getIntAttribute(\"constants\", \"seed\");\n\tm_rand.seed(seed);\n\n\tauto scheme = getStr(\"time\", \"scheme\");\n\tif (scheme.compare(\"euler\") == 0) {\n\t\tm_scheme = Scheme::Euler;\n\t} else if (scheme.compare(\"RK3\") == 0) {\n\t\tm_scheme = Scheme::RK3;\n\t} // Invalid cases dealt with by the xml handler\n\n\tauto surfacecross = getStr(\"algorithms\", \"surface_crossing\");\n\tif (surfacecross.compare(\"DELETE\") == 0) {\n\t\tm_surfcross = SurfaceCross::DELETE;\n\t} else if (surfacecross.compare(\"ABSORB\") == 0) {\n\t\tm_surfcross = SurfaceCross::ABSORB;\n\t} else if (surfacecross.compare(\"REFLECT\") == 0) {\n\t\tm_surfcross = SurfaceCross::REFLECT;\n\t} // Invalid cases dealt with by the xml handler\n}\n\nvoid DVMBase::solve()\n{\n\t// Timeloop\n\tfor (unsigned j = 1; j <= get_steps(); j++) {\n\n\t\tincrement_step();\n\t\tcompute_step();\n\n\t\t// Output\n\t\twrite_outputs();\n\n\t\t// Screen output\n\t\tstd::cout << \"Simulation time          = \" << get_time() << \"\\tStep \"\n\t\t          << j << \"/\" << get_steps() << std::endl;\n\t\tstd::cout << \"Number of vortex blobs   = \" << m_vortex.size()\n\t\t          << std::endl;\n\t}\n}\n\nvoid DVMBase::compute_step()\n{\n\t//************** Advection substep*****************//\n\tconvect();\n\n\t// remesh();\n\t// Fror remeshing both triangulated meshes (with RBF) and structured meshes\n\t// with morgenthal M6 interpolators\n\t// will be used.\n\n\t//************** Diffusion substep ****************//\n\t// The diffussion problem in an infinite domain\n\tm_vortex.diffusion_random_walk(m_rand, m_nu, m_dt);\n\n\t// A diffussion problem with only a flux of vorticity in the boundaries\n\t// dgamma/dn=a\n\tVortexBlobs NewVortices = m_vortsheet.release_nascent_vortices_rw(m_rand);\n\tm_vortex.append_vortices(NewVortices);\n\n\t// If a large time step is used some vortices may cross the boundary due to\n\t// random walk!\n\t// Care is taken of these vortices by 1) Deleting them, 2) Absorbing them,\n\t// 3) Reflecting them back to the flow\n\tm_vortsheet.reflect(m_vortex);\n\n\t//********************* Computing Loads/ Moving body *********************//\n\t// We compute the loads at the end of the time step\n\tm_vortsheet.compute_loads(m_Ur);\n\n\t//********************* Merge/Delete Vortices ****************************//\n}\n\ndouble DVMBase::get_time()\n{\n\treturn m_time;\n}\n\nunsigned DVMBase::get_steps()\n{\n\treturn m_steps;\n}\n\nvoid DVMBase::increment_step()\n{\n\tm_step++;\n\tm_time = m_step * m_dt;\n}\n\nvoid DVMBase::write_outputs()\n{\n\tm_vortex.write_step(m_time, m_step);\n\n\tm_vortsheet.write_step(m_time);\n\n\tm_probe.write_step(m_time);\n}\n\nvoid DVMBase::convect()\n{\n\tswitch (m_scheme) {\n\tcase Scheme::Euler:\n\t\t// Find the free-space velocity\n\t\tm_vortex.biotsavart();\n\t\t// Find the boundary-imposed velocities-these two should be combined\n\t\t// together into one\n\t\tm_vortsheet.solvevortexsheet(m_vortex);\n\t\tm_vortsheet.vortexsheetbc(m_vortex);\n\n\t\t// Added them together\n\t\tm_vortex.m_x += (m_vortex.m_u + m_vortex.m_uvs + m_Ux) * m_dt;\n\t\tm_vortex.m_z += (m_vortex.m_w + m_vortex.m_wvs + m_Uz) * m_dt;\n\t\tbreak;\n\tcase Scheme::RK3:\n\t\t// coefficients for Low Storage-Runge Kutta 3rd\n\t\tconst double a[3] = {0, -17. / 32, -32. / 27};\n\t\tconst double b[3] = {1. / 4, 8. / 9, 3. / 4};\n\n\t\t// execute 3 stages of Low Storage Runge-Kutta 3rd\n\t\tVector q1 = arma::zeros(m_vortex.size());\n\t\tVector q2 = arma::zeros(m_vortex.size());\n\n\t\tfor (int i = 0; i < 3; ++i) {\n\n\t\t\t// Compute the right-hand side of the system\n\t\t\t// Find the free-space velocity\n\t\t\tm_vortex.biotsavart();\n\t\t\t// Find the boundary-imposed velocities-these two may be combined\n\t\t\t// together into one\n\t\t\tm_vortsheet.solvevortexsheet(m_vortex);\n\t\t\tm_vortsheet.vortexsheetbc(m_vortex);\n\n\t\t\tq1 = a[i] * q1 + (m_vortex.m_u + m_vortex.m_uvs + m_Ux) * m_dt;\n\t\t\tq2 = a[i] * q2 + (m_vortex.m_w + m_vortex.m_wvs + m_Uz) * m_dt;\n\n\t\t\tm_vortex.m_x += b[i] * q1;\n\t\t\tm_vortex.m_z += b[i] * q2;\n\t\t}\n\t\tbreak;\n\t}\n}\n", "meta": {"hexsha": "858af8fcc3c3726f18c07627b0f3137215ed2d3c", "size": 4530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/DVMBase.cpp", "max_stars_repo_name": "gdeskos/DVMpp", "max_stars_repo_head_hexsha": "5d511ea55eec21e65e5d5104639f2c02d8df444d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-07-07T09:15:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T06:01:50.000Z", "max_issues_repo_path": "src/DVMBase.cpp", "max_issues_repo_name": "gdeskos/DVMpp", "max_issues_repo_head_hexsha": "5d511ea55eec21e65e5d5104639f2c02d8df444d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-23T10:25:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-25T18:47:29.000Z", "max_forks_repo_path": "src/DVMBase.cpp", "max_forks_repo_name": "gdeskos/DVMpp", "max_forks_repo_head_hexsha": "5d511ea55eec21e65e5d5104639f2c02d8df444d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T21:30:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-02T09:39:03.000Z", "avg_line_length": 26.4912280702, "max_line_length": 77, "alphanum_fraction": 0.6441501104, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5129520003326026}}
{"text": "#include \"super4pcs/algorithms/super4pcs.h\"\n#include \"super4pcs/io/io.h\"\n#include \"super4pcs/utils/geometry.h\"\n\n#include <Eigen/Dense>\n\n\nint main(int argc, char **argv) {\n  using namespace GlobalRegistration;\n  using namespace std;\n\n  vector<Point3D> set1, set2;\n  vector<Eigen::Matrix2f> tex_coords1, tex_coords2;\n  vector<typename Point3D::VectorType> normals1, normals2;\n  vector<tripple> tris1, tris2;\n  vector<std::string> mtls1, mtls2;\n\n  IOManager iomanager;\n\n  // dummy call, to test symbols accessibility\n  iomanager.ReadObject(\"\", set1, tex_coords1, normals1, tris1, mtls1);\n\n  // check availability of the Utils functions\n  if (tris1.size() == 0)\n    Utils::CleanInvalidNormals(set1, normals1);\n\n  // Our matcher.\n  Match4PCSOptions options;\n\n  // Set parameters.\n  Match4PCSBase::MatrixType mat;\n  double overlap (1);\n  options.configureOverlap(overlap);\n\n  typename Point3D::Scalar score = 0;\n\n  constexpr Utils::LogLevel loglvl = Utils::Verbose;\n  using TrVisitorType = Match4PCSBase::DummyTransformVisitor;\n  using SamplerType   = Match4PCSBase::DefaultSampler;\n  Utils::Logger logger(loglvl);\n\n  MatchSuper4PCS matcher(options, logger);\n  score = matcher.ComputeTransformation<SamplerType,TrVisitorType>(set1, &set2, mat);\n\n  logger.Log<Utils::Verbose>( \"Score: \", score );\n\n  iomanager.WriteMatrix(\"output.map\", mat.cast<double>(), IOManager::POLYWORKS);\n\n  return 0;\n}\n\n", "meta": {"hexsha": "c9c3c104970afc567af3e27827e82afbf59f7e20", "size": 1388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/externalAppTest/main.cpp", "max_stars_repo_name": "xinkang/Super4PCS", "max_stars_repo_head_hexsha": "ee31c7e912c5c1acbd8d811c42306dea37164d4a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 378.0, "max_stars_repo_stars_event_min_datetime": "2015-01-25T11:23:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T15:57:31.000Z", "max_issues_repo_path": "tests/externalAppTest/main.cpp", "max_issues_repo_name": "RioWong/Super4PCS", "max_issues_repo_head_hexsha": "7971c7fab0ffcbe9a2a4a517c0211edc37ba7af8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2015-09-18T06:23:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-02T19:54:26.000Z", "max_forks_repo_path": "tests/externalAppTest/main.cpp", "max_forks_repo_name": "RioWong/Super4PCS", "max_forks_repo_head_hexsha": "7971c7fab0ffcbe9a2a4a517c0211edc37ba7af8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 159.0, "max_forks_repo_forks_event_min_datetime": "2015-01-16T19:02:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:16:03.000Z", "avg_line_length": 26.6923076923, "max_line_length": 85, "alphanum_fraction": 0.7363112392, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5129519991325041}}
{"text": "/**\n* This file is part of Fast-Planner.\n*\n* Copyright 2019 Boyu Zhou, Aerial Robotics Group, Hong Kong University of Science and Technology, <uav.ust.hk>\n* Developed by Boyu Zhou <bzhouai at connect dot ust dot hk>, <uv dot boyuzhou at gmail dot com>\n* for more information see <https://github.com/HKUST-Aerial-Robotics/Fast-Planner>.\n* If you use this code, please cite the respective publications as\n* listed on the above website.\n*\n* Fast-Planner is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Lesser 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* Fast-Planner 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 Lesser General Public License\n* along with Fast-Planner. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n\n\n#ifndef _POLYNOMIAL_TRAJ_H\n#define _POLYNOMIAL_TRAJ_H\n\n#include <Eigen/Eigen>\n#include <vector>\n\nusing std::vector;\n\nclass PolynomialTraj {\nprivate:\n  vector<double> times;        // time of each segment\n  vector<vector<double>> cxs;  // coefficient of x of each segment, from high order to low\n  vector<vector<double>> cys;  // coefficient of y of each segment\n  vector<vector<double>> czs;  // coefficient of z of each segment\n\n  double time_sum;\n  int num_seg;\n\n  /* evaluation */\n  vector<Eigen::Vector3d> traj_vec3d;\n  double length;\n\npublic:\n  PolynomialTraj(/* args */) {\n  }\n  ~PolynomialTraj() {\n  }\n\n  void reset() {\n    times.clear(), cxs.clear(), cys.clear(), czs.clear();\n    time_sum = 0.0, num_seg = 0;\n  }\n\n  void addSegment(vector<double> cx, vector<double> cy, vector<double> cz, double t) {\n    cxs.push_back(cx), cys.push_back(cy), czs.push_back(cz), times.push_back(t);\n  }\n\n  void init() {\n    num_seg = times.size();\n    time_sum = 0.0;\n    for (int i = 0; i < times.size(); ++i) {\n      time_sum += times[i];\n    }\n  }\n\n  Eigen::Vector3d evaluate(double t) {\n    /* detetrmine segment num */\n    int idx = 0;\n    while (times[idx] < t) {\n      t -= times[idx];\n      ++idx;\n    }\n\n    /* evaluation */\n    int order = cxs[idx].size();\n    Eigen::VectorXd cx(order), cy(order), cz(order), tv(order);\n    for (int i = 0; i < order; ++i) {\n      cx(i) = cxs[idx][i], cy(i) = cys[idx][i], cz(i) = czs[idx][i];\n      tv(order - 1 - i) = std::pow(t, double(i));\n    }\n\n    Eigen::Vector3d pt;\n    pt(0) = tv.dot(cx), pt(1) = tv.dot(cy), pt(2) = tv.dot(cz);\n    return pt;\n  }\n\n  Eigen::Vector3d evaluateVel(double t) {\n    /* detetrmine segment num */\n    int idx = 0;\n    while (times[idx] < t) {\n      t -= times[idx];\n      ++idx;\n    }\n\n    /* evaluation */\n    int order = cxs[idx].size();\n    Eigen::VectorXd vx(order - 1), vy(order - 1), vz(order - 1);\n\n    /* coef of vel */\n    for (int i = 0; i < order - 1; ++i) {\n      vx(i) = double(i + 1) * cxs[idx][order - 2 - i];\n      vy(i) = double(i + 1) * cys[idx][order - 2 - i];\n      vz(i) = double(i + 1) * czs[idx][order - 2 - i];\n    }\n    double ts = t;\n    Eigen::VectorXd tv(order - 1);\n    for (int i = 0; i < order - 1; ++i)\n      tv(i) = pow(ts, i);\n\n    Eigen::Vector3d vel;\n    vel(0) = tv.dot(vx), vel(1) = tv.dot(vy), vel(2) = tv.dot(vz);\n    return vel;\n  }\n\n  Eigen::Vector3d evaluateAcc(double t) {\n    /* detetrmine segment num */\n    int idx = 0;\n    while (times[idx] < t) {\n      t -= times[idx];\n      ++idx;\n    }\n\n    /* evaluation */\n    int order = cxs[idx].size();\n    Eigen::VectorXd ax(order - 2), ay(order - 2), az(order - 2);\n\n    /* coef of vel */\n    for (int i = 0; i < order - 2; ++i) {\n      ax(i) = double((i + 2) * (i + 1)) * cxs[idx][order - 3 - i];\n      ay(i) = double((i + 2) * (i + 1)) * cys[idx][order - 3 - i];\n      az(i) = double((i + 2) * (i + 1)) * czs[idx][order - 3 - i];\n    }\n    double ts = t;\n    Eigen::VectorXd tv(order - 2);\n    for (int i = 0; i < order - 2; ++i)\n      tv(i) = pow(ts, i);\n\n    Eigen::Vector3d acc;\n    acc(0) = tv.dot(ax), acc(1) = tv.dot(ay), acc(2) = tv.dot(az);\n    return acc;\n  }\n\n  /* for evaluating traj, should be called in sequence!!! */\n  double getTimeSum() {\n    return this->time_sum;\n  }\n\n  vector<Eigen::Vector3d> getTraj() {\n    double eval_t = 0.0;\n    traj_vec3d.clear();\n    while (eval_t < time_sum) {\n      Eigen::Vector3d pt = evaluate(eval_t);\n      traj_vec3d.push_back(pt);\n      eval_t += 0.01;\n    }\n    return traj_vec3d;\n  }\n\n  double getLength() {\n    length = 0.0;\n\n    Eigen::Vector3d p_l = traj_vec3d[0], p_n;\n    for (int i = 1; i < traj_vec3d.size(); ++i) {\n      p_n = traj_vec3d[i];\n      length += (p_n - p_l).norm();\n      p_l = p_n;\n    }\n    return length;\n  }\n\n  double getMeanVel() {\n    double mean_vel = length / time_sum;\n  }\n\n  double getAccCost() {\n    double cost = 0.0;\n    int order = cxs[0].size();\n\n    for (int s = 0; s < times.size(); ++s) {\n      Eigen::Vector3d um;\n      um(0) = 2 * cxs[s][order - 3], um(1) = 2 * cys[s][order - 3], um(2) = 2 * czs[s][order - 3];\n      cost += um.squaredNorm() * times[s];\n    }\n\n    return cost;\n  }\n\n  double getJerk() {\n    double jerk = 0.0;\n\n    /* evaluate jerk */\n    for (int s = 0; s < times.size(); ++s) {\n      Eigen::VectorXd cxv(cxs[s].size()), cyv(cys[s].size()), czv(czs[s].size());\n      /* convert coefficient */\n      int order = cxs[s].size();\n      for (int j = 0; j < order; ++j) {\n        cxv(j) = cxs[s][order - 1 - j], cyv(j) = cys[s][order - 1 - j], czv(j) = czs[s][order - 1 - j];\n      }\n      double ts = times[s];\n\n      /* jerk matrix */\n      Eigen::MatrixXd mat_jerk(order, order);\n      mat_jerk.setZero();\n      for (double i = 3; i < order; i += 1)\n        for (double j = 3; j < order; j += 1) {\n          mat_jerk(i, j) =\n              i * (i - 1) * (i - 2) * j * (j - 1) * (j - 2) * pow(ts, i + j - 5) / (i + j - 5);\n        }\n\n      jerk += (cxv.transpose() * mat_jerk * cxv)(0, 0);\n      jerk += (cyv.transpose() * mat_jerk * cyv)(0, 0);\n      jerk += (czv.transpose() * mat_jerk * czv)(0, 0);\n    }\n\n    return jerk;\n  }\n\n  void getMeanAndMaxVel(double& mean_v, double& max_v) {\n    int num = 0;\n    mean_v = 0.0, max_v = -1.0;\n    for (int s = 0; s < times.size(); ++s) {\n      int order = cxs[s].size();\n      Eigen::VectorXd vx(order - 1), vy(order - 1), vz(order - 1);\n\n      /* coef of vel */\n      for (int i = 0; i < order - 1; ++i) {\n        vx(i) = double(i + 1) * cxs[s][order - 2 - i];\n        vy(i) = double(i + 1) * cys[s][order - 2 - i];\n        vz(i) = double(i + 1) * czs[s][order - 2 - i];\n      }\n      double ts = times[s];\n\n      double eval_t = 0.0;\n      while (eval_t < ts) {\n        Eigen::VectorXd tv(order - 1);\n        for (int i = 0; i < order - 1; ++i)\n          tv(i) = pow(ts, i);\n        Eigen::Vector3d vel;\n        vel(0) = tv.dot(vx), vel(1) = tv.dot(vy), vel(2) = tv.dot(vz);\n        double vn = vel.norm();\n        mean_v += vn;\n        if (vn > max_v) max_v = vn;\n        ++num;\n\n        eval_t += 0.01;\n      }\n    }\n\n    mean_v = mean_v / double(num);\n  }\n\n  void getMeanAndMaxAcc(double& mean_a, double& max_a) {\n    int num = 0;\n    mean_a = 0.0, max_a = -1.0;\n    for (int s = 0; s < times.size(); ++s) {\n      int order = cxs[s].size();\n      Eigen::VectorXd ax(order - 2), ay(order - 2), az(order - 2);\n\n      /* coef of acc */\n      for (int i = 0; i < order - 2; ++i) {\n        ax(i) = double((i + 2) * (i + 1)) * cxs[s][order - 3 - i];\n        ay(i) = double((i + 2) * (i + 1)) * cys[s][order - 3 - i];\n        az(i) = double((i + 2) * (i + 1)) * czs[s][order - 3 - i];\n      }\n      double ts = times[s];\n\n      double eval_t = 0.0;\n      while (eval_t < ts) {\n        Eigen::VectorXd tv(order - 2);\n        for (int i = 0; i < order - 2; ++i)\n          tv(i) = pow(ts, i);\n        Eigen::Vector3d acc;\n        acc(0) = tv.dot(ax), acc(1) = tv.dot(ay), acc(2) = tv.dot(az);\n        double an = acc.norm();\n        mean_a += an;\n        if (an > max_a) max_a = an;\n        ++num;\n\n        eval_t += 0.01;\n      }\n    }\n\n    mean_a = mean_a / double(num);\n  }\n};\n\n#endif", "meta": {"hexsha": "ddbbc53c15a02a3fac7e82fc2a7f58f580f3a62a", "size": 8189, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/TIE_navigation/plan_env/include/plan_env/polynomial_traj.hpp", "max_stars_repo_name": "ZJU-FAST-Lab/Terrestrial-Aerial-Navigation", "max_stars_repo_head_hexsha": "3602623ff8cb9735c6ece8c25772a3809cb0362e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-09T06:35:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T02:34:39.000Z", "max_issues_repo_path": "src/TIE_navigation/plan_env/include/plan_env/polynomial_traj.hpp", "max_issues_repo_name": "RoboticsZhang/Terrestrial-Aerial-Navigation", "max_issues_repo_head_hexsha": "d73b6fa9d51985f442fda6d0e282226cb7a45186", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TIE_navigation/plan_env/include/plan_env/polynomial_traj.hpp", "max_forks_repo_name": "RoboticsZhang/Terrestrial-Aerial-Navigation", "max_forks_repo_head_hexsha": "d73b6fa9d51985f442fda6d0e282226cb7a45186", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-09T05:44:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T05:44:24.000Z", "avg_line_length": 28.0445205479, "max_line_length": 111, "alphanum_fraction": 0.532055196, "num_tokens": 2744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839876, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.5129519936388468}}
{"text": "#ifndef CORE_SCENE_HPP\n#define CORE_SCENE_HPP\n\n#include \"object.hpp\"\n\n#include <graphics/color.hpp>\n#include <lights/point_light.hpp>\n\n#include <boost/optional.hpp>\n\n#include <vector>\n\nnamespace math { struct ray3d; }\n\nnamespace core\n{\n\nstruct intersection_info;\n\nclass scene\n{\n  std::vector<object> objects;\n  std::vector<lights::point_light> lights;\n\npublic:\n\n  graphics::color background_color;\n\n  void add(const object& obj) { objects.push_back(obj); }\n  void add(lights::point_light light) { lights.push_back(light); }\n\n  const std::vector<lights::point_light>& get_lights() const { return lights; }\n\n  friend bool intersects(const scene& scene, math::ray3d ray);\n  friend boost::optional<core::intersection_info> closest_intersection(const scene& scene, math::ray3d ray);\n};\n\nbool intersects(const scene& scn, math::ray3d ray);\nboost::optional<core::intersection_info> closest_intersection(const scene& scn, math::ray3d ray);\n\n}\n\n\n#endif\n", "meta": {"hexsha": "7a2088d44e728665095b701f2f7b585f12dab2ff", "size": 944, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/scene.hpp", "max_stars_repo_name": "TiagoRabello/Path-Tracer", "max_stars_repo_head_hexsha": "1ad32741fdff0b8f48ef675e9071c1495cbcdde3", "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/core/scene.hpp", "max_issues_repo_name": "TiagoRabello/Path-Tracer", "max_issues_repo_head_hexsha": "1ad32741fdff0b8f48ef675e9071c1495cbcdde3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-02-01T09:14:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-01T09:14:44.000Z", "max_forks_repo_path": "src/core/scene.hpp", "max_forks_repo_name": "TiagoRabello/Path-Tracer", "max_forks_repo_head_hexsha": "1ad32741fdff0b8f48ef675e9071c1495cbcdde3", "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.9777777778, "max_line_length": 108, "alphanum_fraction": 0.7468220339, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919830720204, "lm_q2_score": 0.640635841117624, "lm_q1q2_score": 0.5129519820514821}}
{"text": "#ifndef CRADLE_GEOMETRY_DECODE_MATRIX_HPP\n#define CRADLE_GEOMETRY_DECODE_MATRIX_HPP\n\n#include <cradle/geometry/common.hpp>\n#include <cradle/geometry/angle.hpp>\n#include <boost/optional/optional.hpp>\n\n// This file provides various functions for decoding transformation matrices.\n\nnamespace cradle {\n\n// Determine if the given transformation matrix has a rotational component.\ntemplate<unsigned N, typename T>\nbool has_rotation(matrix<N,N,T> const& m);\n\n// Given a matrix that represents a 3D rotation about the X-axis (and only\n// that), this returns the angle of the rotation.  For any other matrix,\n// it returns an uninitialized value.\ntemplate<typename T>\noptional<angle<T,radians> > decode_rotation_about_x(\n    matrix<3,3,T> const& m);\n\n// Decode a rotation about the Y-axis.\ntemplate<typename T>\noptional<angle<T,radians> > decode_rotation_about_y(\n    matrix<3,3,T> const& m);\n\n// Decode a rotation about the Z-axis.\ntemplate<typename T>\noptional<angle<T,radians> > decode_rotation_about_z(\n    matrix<3,3,T> const& m);\n\n}\n\n#include <cradle/geometry/decode_matrix.ipp>\n\n#endif\n", "meta": {"hexsha": "646011d7450b22e1452956c235bdff8e4d6ba155", "size": 1084, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cradle/src/cradle/geometry/decode_matrix.hpp", "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/src/cradle/geometry/decode_matrix.hpp", "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/src/cradle/geometry/decode_matrix.hpp", "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": 28.5263157895, "max_line_length": 77, "alphanum_fraction": 0.7675276753, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5129311258199692}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <string>\n\n#include <boost/range/irange.hpp>\n\nusing uintmax = std::uintmax_t;\n\nauto next_sequence(const std::string& seq) {\n\n  auto result  = std::string{};\n  auto count   = uintmax{1};\n  auto current = seq.front();\n\n  const auto append = [&] {\n    result.push_back('0' + count);\n    result.push_back(current);\n  };\n\n  for(const auto i : boost::irange({1}, seq.size())) {\n    const auto digit = seq[i];\n    if(digit == current) {\n      ++count;\n    } else {\n      append();\n      count = 1;\n      current = digit;\n    }\n  }\n  append();\n\n  return result;\n}\n\nauto final_length(const std::string& seq) {\n\n    auto result = uintmax{1};\n\n    std::adjacent_find(seq.begin(), seq.end(), [&result] (const auto a, const auto b) {\n      result += (a != b);\n      return false;\n    });\n\n    return (result * 2);\n}\n\nauto solution(std::string seq, uintmax num_iterations) {\n\n  for(const auto i : boost::irange(num_iterations - 1)) {\n    seq = next_sequence(seq);\n  }\n\n  return final_length(seq);\n}\n\nint main() {\n\n    std::cout << solution(\"1321131112\", 40) << std::endl;\n\n}\n", "meta": {"hexsha": "3fa49474a552dd55f6b010df0347cc71e09a162f", "size": 1110, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 10 Part 1/main_v2.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 10 Part 1/main_v2.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 10 Part 1/main_v2.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1967213115, "max_line_length": 87, "alphanum_fraction": 0.5945945946, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5129311153602357}}
{"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 *    References\n *      NASA, Goddard Spaceflight Center. Orbit Determination Toolbox (ODTBX), NASA - GSFC Open\n *          Source Software, http://opensource.gsfc.nasa.gov/projects/ODTBX/, last accessed:\n *          31st January, 2012.\n *      Fortescue, P. W., et al. Spacecraft systems engineering, Third Edition,\n *          Wiley, England, 2003.\n *      Vallado, D. A., McClain, W. D. Fundamentals of astro and applications, 2nd Edition,\n *          Kluwer Academic Publishers, The Netherlands, 2004.\n *      Harvard. Minor Planet Center.\n *          http://scully.cfa.harvard.edu/cgi-bin/returnprepeph.cgi?d=d&o=02060, last accessed:\n *          1st February, 2012.\n *      Wikipedia. Geostationary orbit, http://en.wikipedia.org/wiki/Geostationary_orbit, last\n *      accessed: 1st February, 2012, last modified: 29th January, 2012.\n *      Rocket and Space Technology. Example problems, http://www.braeunig.us/space/problem.htm,\n *          last accessed: 4th February, 2012.\n *      Jenab. http://jenab6.livejournal.com/15054.html, last accessed: 4th February, 2012, last\n *          modified: 6th August, 2008.\n *      Advanced Concepts Team, ESA. Keplerian Toolbox, http://sourceforge.net/projects/keptoolbox,\n *          last accessed: 21st April, 2012.\n *\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <cmath>\n#include <limits>\n#include <iostream>\n\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"tudat/astro/basic_astro/orbitalElementConversions.h\"\n#include \"tudat/basics/testMacros.h\"\n#include \"tudat/math/basic/mathematicalConstants.h\"\n#include \"tudat/basics/basicTypedefs.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace mathematical_constants;\n\nBOOST_AUTO_TEST_SUITE( test_orbital_element_conversions )\n\n//! Test if conversion from Keplerian elements to Cartesian elements is working correctly.\nBOOST_AUTO_TEST_CASE( testKeplerianToCartesianElementConversion )\n{\n    // Case 1: Elliptical orbit around the Earth.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Using declarations.\n        using namespace orbital_element_conversions;\n\n        // Set Earth gravitational parameter [m^3/s^2] .\n        const double earthGravitationalParameter = 3.986004415e14;\n\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        Eigen::Matrix< double, 6, 1 > keplerianElements ;\n        keplerianElements( semiMajorAxisIndex ) = 8000.0 * 1000.0;\n        keplerianElements( eccentricityIndex ) = 0.23;\n        keplerianElements( inclinationIndex ) = 20.6 / 180.0 * PI;\n        keplerianElements( argumentOfPeriapsisIndex ) = 274.78 / 180.0 * PI;\n        keplerianElements( longitudeOfAscendingNodeIndex ) = 108.77 / 180.0 * PI;\n        keplerianElements( trueAnomalyIndex ) = 46.11 / 180.0 * PI;\n\n        // Set expected Cartesian elements [m,m,m,m/s,m/s,m/s].\n        Eigen::Matrix< double, 6, 1 > expectedCartesianElements;\n        expectedCartesianElements( xCartesianPositionIndex ) = 2.021874804243437e6;\n        expectedCartesianElements( yCartesianPositionIndex ) = 6.042523817035284e6;\n        expectedCartesianElements( zCartesianPositionIndex ) = -1.450371183512575e6;\n        expectedCartesianElements( xCartesianVelocityIndex ) = -7.118283509842652e3;\n        expectedCartesianElements( yCartesianVelocityIndex ) = 4.169050171542199e3;\n        expectedCartesianElements( zCartesianVelocityIndex ) = 2.029066072016241e3;\n\n        // Compute Cartesian elements.\n        Eigen::Matrix< double, 6, 1 > computedCartesianElements;\n        computedCartesianElements = orbital_element_conversions::\n                convertKeplerianToCartesianElements( keplerianElements,\n                                                     earthGravitationalParameter );\n\n        // Check if computed Cartesian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements,\n                                           computedCartesianElements, 1.0e-15 );\n    }\n\n    // Case 2: Equatorial, circular orbit around Mars.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Using declarations.\n        using namespace orbital_element_conversions;\n\n        // Set Mars gravitational parameter [m^3/s^2].\n        const double marsGravitationalParameter = 4.2828018915e13;\n\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        Eigen::Matrix< double, 6, 1 > keplerianElements;\n        keplerianElements( semiMajorAxisIndex ) = 9201.61 * 1000.0;\n        keplerianElements( eccentricityIndex ) = 0.0;\n        keplerianElements( inclinationIndex ) = 0.0;\n        keplerianElements( argumentOfPeriapsisIndex ) = 12.54 / 180.0 * PI;\n        keplerianElements( longitudeOfAscendingNodeIndex ) = 201.55 / 180.0 * PI;\n        keplerianElements( trueAnomalyIndex ) = -244.09 / 180.0 * PI;\n\n        // Set expected Cartesian elements [m,m,m,m/s,m/s,m/s].\n        Eigen::Matrix< double, 6, 1 > expectedCartesianElements;\n        expectedCartesianElements( xCartesianPositionIndex ) = 7.968828015716932e6;\n        expectedCartesianElements( yCartesianPositionIndex ) = -4.600804999999997e6;\n        expectedCartesianElements( zCartesianPositionIndex ) = 0.0;\n        expectedCartesianElements( xCartesianVelocityIndex ) = 1.078703495685965e3;\n        expectedCartesianElements( yCartesianVelocityIndex ) = 1.868369260830248e3;\n        expectedCartesianElements( zCartesianVelocityIndex ) = 0.0;\n\n        // Compute Cartesian elements.\n        Eigen::Matrix< double, 6, 1 > computedCartesianElements;\n        computedCartesianElements = orbital_element_conversions::\n                convertKeplerianToCartesianElements( keplerianElements,\n                                                     marsGravitationalParameter );\n\n        // Check if computed Cartesian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements,\n                                           computedCartesianElements, 1.0e-15 );\n    }\n\n    // Case 3: Hyperbolic orbit around the Sun.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Using declarations.\n        using namespace orbital_element_conversions;\n\n        // Set Sun gravitational parameter [m^3/s^2].\n        const double sunGravitationalParameter = 1.32712440018e20;\n\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        Eigen::Matrix< double, 6, 1 > keplerianElements;\n        keplerianElements( semiMajorAxisIndex ) = -4.5e11;\n        keplerianElements( eccentricityIndex ) = 2.3;\n        keplerianElements( inclinationIndex ) = 25.5 / 180.0 * PI;\n        keplerianElements( argumentOfPeriapsisIndex ) = 156.11 / 180.0 * PI;\n        keplerianElements( longitudeOfAscendingNodeIndex ) = -215.03 / 180.0 * PI;\n        keplerianElements( trueAnomalyIndex ) = 123.29 / 180.0 * PI;\n\n        // Set expected Cartesian elements [m,m,m,m/s,m/s,m/s].\n        Eigen::Matrix< double, 6, 1 > expectedCartesianElements;\n        expectedCartesianElements( xCartesianPositionIndex ) = -2.776328224174438e12;\n        expectedCartesianElements( yCartesianPositionIndex ) = -6.053823869632723e12;\n        expectedCartesianElements( zCartesianPositionIndex ) = 3.124576293512172e12;\n        expectedCartesianElements( xCartesianVelocityIndex ) = 7.957674684798018e3;\n        expectedCartesianElements( yCartesianVelocityIndex ) = 1.214817382001788e4;\n        expectedCartesianElements( zCartesianVelocityIndex ) = -6.923442392618828e3;\n\n        // Compute Cartesian elements.\n        Eigen::Matrix< double, 6, 1 > computedCartesianElements;\n        computedCartesianElements = orbital_element_conversions::\n                convertKeplerianToCartesianElements( keplerianElements,\n                                                     sunGravitationalParameter );\n\n        // Check if computed Cartesian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements,\n                                           computedCartesianElements, 1.0e-15 );\n    }\n\n    // Case 4: Parabolic orbit around the Earth.\n    // Earth-orbiting satellite example (Rocket and Space Technology, 2012).\n    {\n        // Using declarations.\n        using namespace orbital_element_conversions;\n\n        // Set Earth gravitational parameter [m^3/s^2].\n        const double earthGravitationalParameter = 3.986005e14;\n\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        Eigen::Matrix< double, 6, 1 > keplerianElements;\n        keplerianElements( semiLatusRectumIndex ) = 2.0 * 6678140.0;\n        keplerianElements( eccentricityIndex ) = 1.0;\n        keplerianElements( inclinationIndex ) = 45.0 / 180.0 * PI;\n        keplerianElements( argumentOfPeriapsisIndex ) = 0.0;\n        keplerianElements( longitudeOfAscendingNodeIndex ) = 0.0;\n        keplerianElements( trueAnomalyIndex ) = 0.0;\n\n        // Set expected escape velocity [m/s].\n        const double expectedEscapeVelocity = 10926.0;\n\n        // Compute Cartesian elements.\n        Eigen::Matrix< double, 6, 1 > computedCartesianElements;\n        computedCartesianElements = orbital_element_conversions::\n                convertKeplerianToCartesianElements( keplerianElements,\n                                                     earthGravitationalParameter );\n\n        // Check if computed escape veloicty matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedEscapeVelocity,\n                                    computedCartesianElements.segment( 3, 3 ).norm( ), 1.0e-4 );\n    }\n}\n\n//! Test if conversion from Cartesian elements to Keplerian elements is working correctly, using\n//! benchmark data.\nBOOST_AUTO_TEST_CASE( testCartesianToKeplerianElementConversionBenchmark )\n{\n    // Case 1: Elliptical orbit around the Earth.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Using declarations.\n        using namespace orbital_element_conversions;\n\n        // Earth gravitational parameter.\n        const double earthGravitationalParameter = 3.986004415e14;\n\n        // Set Cartesian elements.\n        Eigen::Matrix< double, 6, 1 > cartesianElements;\n        cartesianElements( xCartesianPositionIndex ) = 3.75e6;\n        cartesianElements( yCartesianPositionIndex ) = 4.24e6;\n        cartesianElements( zCartesianPositionIndex ) = -1.39e6;\n        cartesianElements( xCartesianVelocityIndex ) = -4.65e3;\n        cartesianElements( yCartesianVelocityIndex ) = -2.21e3;\n        cartesianElements( zCartesianVelocityIndex ) = 1.66e3;\n\n        // Set expected Keplerian elements.\n        Eigen::Matrix< double, 6, 1 > expectedKeplerianElements;\n        expectedKeplerianElements( semiMajorAxisIndex ) = 3.707478199246163e6;\n        expectedKeplerianElements( eccentricityIndex ) = 0.949175203660321;\n        expectedKeplerianElements( inclinationIndex ) = 0.334622356632438;\n        expectedKeplerianElements( argumentOfPeriapsisIndex ) = 2.168430616511167;\n        expectedKeplerianElements( longitudeOfAscendingNodeIndex ) = 1.630852596545341;\n        expectedKeplerianElements( trueAnomalyIndex ) = 3.302032232567084;\n\n        // Compute Keplerian elements.\n        Eigen::Matrix< double, 6, 1 > computedKeplerianElements;\n        computedKeplerianElements = orbital_element_conversions::\n                convertCartesianToKeplerianElements( cartesianElements,\n                                                     earthGravitationalParameter );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, 1.0e-14 );\n    }\n\n    // Case 2: Equatorial, circular orbit around Venus.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Using declarations.\n        using namespace orbital_element_conversions;\n\n        // Venus gravitational parameter.\n        const double venusGravitationalParameter = 3.2485504415e14;\n\n        // Set Cartesian elements.\n        Eigen::Matrix< double, 6, 1 > cartesianElements;\n        cartesianElements( xCartesianPositionIndex ) = 5.580537430785387e6;\n        cartesianElements( yCartesianPositionIndex ) = 2.816487703435473e6;\n        cartesianElements( zCartesianPositionIndex ) = 0.0;\n        cartesianElements( xCartesianVelocityIndex ) = -3.248092722413634e3;\n        cartesianElements( yCartesianVelocityIndex ) = 6.435711753323540e3;\n        cartesianElements( zCartesianVelocityIndex ) = 0.0;\n\n        // Set expected Keplerian elements.\n        Eigen::Matrix< double, 6, 1 > expectedKeplerianElements;\n        expectedKeplerianElements( semiMajorAxisIndex ) = 6.251e6;\n        expectedKeplerianElements( eccentricityIndex ) = 0.0;\n        expectedKeplerianElements( inclinationIndex ) = 0.0;\n        expectedKeplerianElements( argumentOfPeriapsisIndex ) = 0.0;\n        expectedKeplerianElements( longitudeOfAscendingNodeIndex ) = 0.0;\n        expectedKeplerianElements( trueAnomalyIndex ) = 26.78 / 180.0 * PI;\n\n        // Declare and compute converted Keplerian elements.\n        Eigen::Matrix< double, 6, 1 > computedKeplerianElements;\n        computedKeplerianElements = orbital_element_conversions::\n                convertCartesianToKeplerianElements( cartesianElements,\n                                                     venusGravitationalParameter );\n\n        // Check if computed semi-major axis matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedKeplerianElements( semiMajorAxisIndex ),\n                                    computedKeplerianElements( semiMajorAxisIndex ), 1.0e-15 );\n\n        // Check if computed eccentricity matches the expected value.\n        BOOST_CHECK_SMALL( computedKeplerianElements( eccentricityIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        // Check if computed inclination matches the expected value.\n        BOOST_CHECK_SMALL( computedKeplerianElements( inclinationIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        // Check if computed argument of periapsis matches the expected value.\n        BOOST_CHECK_SMALL( std::fmod( computedKeplerianElements( argumentOfPeriapsisIndex ),\n                                      2.0 * PI ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        // Check if computed right ascension of ascending node matches the expected value.\n        BOOST_CHECK_SMALL( computedKeplerianElements( longitudeOfAscendingNodeIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        // Check if computed true anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedKeplerianElements( trueAnomalyIndex ),\n                                    computedKeplerianElements( trueAnomalyIndex ), 1.0e-15 );\n    }\n\n    // Case 3: Hyperbolic orbit around the Sun.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Using declarations.\n        using namespace orbital_element_conversions;\n\n        // Sun gravitational parameter.\n        const double sunGravitationalParameter = 1.32712440018e20;\n\n        // Declare and set Cartesian elements.\n        Eigen::Matrix< double, 6, 1 > cartesianElements;\n        cartesianElements( xCartesianPositionIndex ) = 7.035635643405699e11;\n        cartesianElements( yCartesianPositionIndex ) = -2.351218213055550e11;\n        cartesianElements( zCartesianPositionIndex ) = 0.037960971564309e11;\n        cartesianElements( xCartesianVelocityIndex ) = -1.731375459746510e4;\n        cartesianElements( yCartesianVelocityIndex ) = -1.535713656317794e4;\n        cartesianElements( zCartesianVelocityIndex ) = 0.423498718768347e4;\n\n        // Set expected Keplerian elements.\n        Eigen::Matrix< double, 6, 1 > expectedKeplerianElements;\n        expectedKeplerianElements( semiMajorAxisIndex ) = -6.78e11;\n        expectedKeplerianElements( eccentricityIndex ) = 1.89;\n        expectedKeplerianElements( inclinationIndex ) = 167.91 / 180 * PI;\n        expectedKeplerianElements( argumentOfPeriapsisIndex ) = 45.78 / 180.0 * PI;\n        expectedKeplerianElements( longitudeOfAscendingNodeIndex ) = 342.89 / 180.0 * PI;\n        expectedKeplerianElements( trueAnomalyIndex ) = 315.62 / 180.0 * PI;\n\n        // Compute Keplerian elements.\n        Eigen::Matrix< double, 6, 1 > computedKeplerianElements;\n        computedKeplerianElements = orbital_element_conversions::\n                convertCartesianToKeplerianElements( cartesianElements,\n                                                     sunGravitationalParameter );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, 1.0e-15 );\n    }\n\n    // Case 4: Low-eccentricity, low-inclination orbit around Uranus.\n    // The benchmark data is obtained by running Keplerian Toolbox (ESA, 2012). It is important to\n    // note that Keplerian Toolbox uses a different order of elements than Tudat (argument of\n    // periapsis and longitude of ascending node positions in vector are switched). Not all values\n    // are tested to the same precision, as there are slight differences in the computations using\n    // Keplerian toolbox and Tudat. This is likely down to the use of functions in Eigen, such as\n    // .cross, which are written out in full in Keplerian toolbox. If this turns out to be an\n    // issue, the use of Eigen functions will need to be evaluated.\n    {\n        // Using declarations.\n        using namespace orbital_element_conversions;\n\n        // Uranus gravitational parameter [m^3 s^-2].\n        const double uranusGravitationalParameter = 5.793943348799999e15;\n\n        // Declare and set Cartesian elements.\n        Eigen::Matrix< double, 6, 1 > cartesianElements;\n        cartesianElements( xCartesianPositionIndex ) = -33760437.1526459;\n        cartesianElements( yCartesianPositionIndex ) = -91719029.3283878;\n        cartesianElements( zCartesianPositionIndex ) = -757.744826269064;\n        cartesianElements( xCartesianVelocityIndex ) = 7225.59158151846;\n        cartesianElements( yCartesianVelocityIndex ) = -2659.60535464239;\n        cartesianElements( zCartesianVelocityIndex ) = -0.0486289999748532;\n\n        // Set expected Keplerian elements.\n        Eigen::Matrix< double, 6, 1 > expectedKeplerianElements;\n        expectedKeplerianElements( semiMajorAxisIndex ) = 97736000.0;\n        expectedKeplerianElements( eccentricityIndex ) = 1.0e-5;\n        expectedKeplerianElements( inclinationIndex ) = 1.0e-5;\n        expectedKeplerianElements( argumentOfPeriapsisIndex ) = 4.39704289113435;\n        expectedKeplerianElements( longitudeOfAscendingNodeIndex ) = 0.330903954202613;\n        expectedKeplerianElements( trueAnomalyIndex ) = 5.914936209560839;\n\n        // Compute Keplerian elements.\n        Eigen::Matrix< double, 6, 1 > computedKeplerianElements;\n        computedKeplerianElements = orbital_element_conversions::\n                convertCartesianToKeplerianElements( cartesianElements,\n                                                     uranusGravitationalParameter );\n\n        // Check if computed Keplerian elements match the expected values.\n        BOOST_CHECK_CLOSE_FRACTION( expectedKeplerianElements( semiMajorAxisIndex ),\n                                    computedKeplerianElements( semiMajorAxisIndex ),\n                                    1.0e-14 );\n\n        BOOST_CHECK_SMALL( std::fabs( expectedKeplerianElements( eccentricityIndex )\n                                      - computedKeplerianElements( eccentricityIndex ) ),\n                           1.0e-15 );\n\n        BOOST_CHECK_SMALL( std::fabs( expectedKeplerianElements( inclinationIndex )\n                                      - computedKeplerianElements( inclinationIndex ) ),\n                           1.0e-10 );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedKeplerianElements( argumentOfPeriapsisIndex ),\n                                    computedKeplerianElements( argumentOfPeriapsisIndex ),\n                                    1.0e-10 );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedKeplerianElements( longitudeOfAscendingNodeIndex ),\n                                    computedKeplerianElements( longitudeOfAscendingNodeIndex ),\n                                    1.0e-14 );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedKeplerianElements( trueAnomalyIndex ),\n                                    computedKeplerianElements( trueAnomalyIndex ),\n                                    1.0e-6 );\n    }\n\n}\n\n//! Test back and forth Kepler <-> Cartesian conversion for parabolic orbit\ntemplate< typename ScalarType >\nvoid convertParabolicOrbitBackAndForth(\n        const ScalarType tolerance )\n{\n    // Using declarations.\n    using namespace orbital_element_conversions;\n\n    // Set Earth gravitational parameter [m^3/s^2].\n    const ScalarType earthGravitationalParameter = 3.986005e14;\n\n    // Set Keplerian elements [m,-,rad,rad,rad,rad].\n    Eigen::Matrix< ScalarType, 6, 1 > keplerianElements;\n    keplerianElements( semiLatusRectumIndex ) = static_cast< ScalarType >(\n                2.0 * 6678140.0 );\n    keplerianElements( eccentricityIndex ) = getFloatingInteger< ScalarType >( 1 );\n    keplerianElements( inclinationIndex ) = static_cast< ScalarType >(\n                45.0 / 180.0 * PI );\n    keplerianElements( argumentOfPeriapsisIndex ) = getFloatingInteger< ScalarType >( 0 );\n    keplerianElements( longitudeOfAscendingNodeIndex ) = getFloatingInteger< ScalarType >( 0 );\n    keplerianElements( trueAnomalyIndex ) = getFloatingInteger< ScalarType >( 0 );\n\n    // Compute Cartesian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > computedCartesianElements =\n            convertKeplerianToCartesianElements< ScalarType >(\n                keplerianElements, earthGravitationalParameter );\n\n    // Recompute Keplerian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > recomputedKeplerianElements =\n            convertCartesianToKeplerianElements< ScalarType >(\n                computedCartesianElements, earthGravitationalParameter );\n\n    // Check if recomputed Keplerian elements match the expected values.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( keplerianElements,\n                                       recomputedKeplerianElements, tolerance );\n\n    std::cout<<\"Keplerian \"<<std::setprecision( 16 )<<keplerianElements.transpose( )<<std::endl;\n    std::cout<<\"Keplerian \"<<recomputedKeplerianElements.transpose( )<<std::endl;\n    std::cout<<\"Keplerian \"<<( keplerianElements - recomputedKeplerianElements ).transpose( )<<std::endl;\n    recomputedKeplerianElements( eccentricityIndex ) = getFloatingInteger< ScalarType >( 1 );\n\n    // Convert recomputed Keplerian elements to Cartesian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > recomputedCartesianElements =\n            convertKeplerianToCartesianElements(\n                recomputedKeplerianElements, earthGravitationalParameter );\n\n    // Check that computed Cartesian elements match.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                computedCartesianElements, recomputedCartesianElements, ( 10.0 * tolerance ) );\n\n    std::cout<<\"Cartesian \"<<std::setprecision( 16 )<<computedCartesianElements.transpose( )<<std::endl;\n    std::cout<<\"Cartesian \"<<recomputedCartesianElements.transpose( )<<std::endl;\n}\n\n//! Test back and forth Kepler <-> Cartesian conversion for circular equatorial orbit\ntemplate< typename ScalarType >\nvoid convertCircularEquatorialOrbitBackAndForth(\n        const ScalarType tolerance )\n{\n    // Using declarations.\n    using namespace orbital_element_conversions;\n\n    // Earth gravitational parameter [m^3 s^-2].\n    const ScalarType earthGravitationalParameter = 3.9859383624e14;\n\n    // Set Keplerian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > keplerianElements;\n    keplerianElements( semiMajorAxisIndex ) =\n            static_cast< ScalarType >( 8000.0 );\n    keplerianElements( eccentricityIndex ) = getFloatingInteger< ScalarType >( 0 );\n    keplerianElements( inclinationIndex ) = getFloatingInteger< ScalarType >( 0 );\n    keplerianElements( argumentOfPeriapsisIndex ) =\n            static_cast< ScalarType >( 243.0 / 180.0 * PI );\n    keplerianElements( longitudeOfAscendingNodeIndex ) =\n            static_cast< ScalarType >( -79.6 / 180.0 * PI );\n    keplerianElements( trueAnomalyIndex ) =\n            static_cast< ScalarType >( 126.45 / 180.0 * PI );\n\n    // Convert Keplerian elements to Cartesian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > computedCartesianElements;\n    computedCartesianElements = convertKeplerianToCartesianElements< ScalarType >(\n                keplerianElements, earthGravitationalParameter );\n\n    // Convert Cartesian elements back to Keplerian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > recomputedKeplerianElements;\n    recomputedKeplerianElements = convertCartesianToKeplerianElements< ScalarType >(\n                computedCartesianElements, earthGravitationalParameter );\n\n    // Check that recomputed Keplerian elements match the input values. (In this limit case,\n    // the argument of periapsis and longitude of ascending node are set to zero, and the\n    // true anomaly \"absorbs\" everything).\n    BOOST_CHECK_CLOSE_FRACTION( keplerianElements( semiMajorAxisIndex ),\n                                recomputedKeplerianElements( semiMajorAxisIndex ),\n                                tolerance );\n\n    BOOST_CHECK_SMALL( recomputedKeplerianElements( eccentricityIndex ), tolerance );\n\n    BOOST_CHECK_SMALL( recomputedKeplerianElements( inclinationIndex ),\n                       std::numeric_limits< ScalarType >::epsilon( ) );\n\n    BOOST_CHECK_SMALL( recomputedKeplerianElements( argumentOfPeriapsisIndex ),\n                       std::numeric_limits< ScalarType >::epsilon( ) );\n\n    BOOST_CHECK_SMALL( recomputedKeplerianElements( longitudeOfAscendingNodeIndex ),\n                       std::numeric_limits< ScalarType >::epsilon( ) );\n\n    BOOST_CHECK_CLOSE_FRACTION( std::fmod(\n                                    keplerianElements( argumentOfPeriapsisIndex )\n                                    + keplerianElements( longitudeOfAscendingNodeIndex )\n                                    + keplerianElements( trueAnomalyIndex ), 2.0 * PI ),\n                                recomputedKeplerianElements( trueAnomalyIndex ),\n                                std::numeric_limits< ScalarType >::epsilon( ) );\n\n    // Convert recomputed Keplerian elements to Cartesian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > recomputedCartesianElements =\n            convertKeplerianToCartesianElements(\n                recomputedKeplerianElements, earthGravitationalParameter );\n\n    // Check that computed Cartesian elements match.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                computedCartesianElements, recomputedCartesianElements, ( 10.0 * tolerance ) );\n}\n\n//! Test back and forth Kepler <-> Cartesian conversion for circular non-equatorial orbit\ntemplate< typename ScalarType >\nvoid convertCircularNonEquatorialOrbitBackAndForth(\n        const ScalarType tolerance )\n{\n    // Using declarations.\n    using namespace orbital_element_conversions;\n\n    // Earth gravitational parameter [m^3 s^-2].\n    const ScalarType earthGravitationalParameter = 3.9859383624e14;\n\n    // Set Keplerian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > keplerianElements;\n    keplerianElements( semiMajorAxisIndex ) = static_cast< ScalarType >( 8000.0 );\n    keplerianElements( eccentricityIndex ) =  getFloatingInteger< ScalarType >( 0 );\n    keplerianElements( inclinationIndex ) = static_cast< ScalarType >( 176.11 / 180.0 * PI );\n    keplerianElements( argumentOfPeriapsisIndex ) =\n            static_cast< ScalarType >(  243.0 / 180.0 * PI );\n    keplerianElements( longitudeOfAscendingNodeIndex ) =\n            static_cast< ScalarType >( -79.6 / 180.0 * PI );\n    keplerianElements( trueAnomalyIndex ) =\n            static_cast< ScalarType >( 126.45 / 180.0 * PI );\n\n    // Convert Keplerian elements to Cartesian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > computedCartesianElements =\n            convertKeplerianToCartesianElements< ScalarType >(\n                keplerianElements, earthGravitationalParameter );\n\n    // Convert Cartesian elements back to Keplerian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > recomputedKeplerianElements =\n            convertCartesianToKeplerianElements< ScalarType >(\n                computedCartesianElements, earthGravitationalParameter );\n\n    // Check that recomputed Keplerian elements match the input values. (In this limit case,\n    // the argument of periapsis is set to zero, and the true anomaly \"absorbs\" this).\n    BOOST_CHECK_CLOSE_FRACTION(\n                keplerianElements( semiMajorAxisIndex ),\n                recomputedKeplerianElements( semiMajorAxisIndex ), tolerance );\n\n    BOOST_CHECK_SMALL( recomputedKeplerianElements( eccentricityIndex ), tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION(\n                keplerianElements( inclinationIndex ),\n                recomputedKeplerianElements( inclinationIndex ), tolerance );\n\n    BOOST_CHECK_SMALL( recomputedKeplerianElements( argumentOfPeriapsisIndex ),\n                       std::numeric_limits< ScalarType >::epsilon( ) );\n\n    BOOST_CHECK_CLOSE_FRACTION(\n                keplerianElements( longitudeOfAscendingNodeIndex ) +\n                getFloatingInteger< ScalarType >( 2 ) * getPi< ScalarType >( ),\n                recomputedKeplerianElements( longitudeOfAscendingNodeIndex ), tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION(\n                std::fmod( keplerianElements( argumentOfPeriapsisIndex )\n                           + keplerianElements( trueAnomalyIndex ),\n                           getFloatingInteger< ScalarType >( 2 ) * getPi< ScalarType >( ) ),\n                recomputedKeplerianElements( trueAnomalyIndex ), 10.0 * tolerance );\n\n    // Convert recomputed Keplerian elements to Cartesian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > recomputedCartesianElements =\n            convertKeplerianToCartesianElements< ScalarType >(\n                recomputedKeplerianElements, earthGravitationalParameter );\n\n    // Check that computed Cartesian elements match.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                computedCartesianElements, recomputedCartesianElements, ( 100.0 * tolerance ) );\n}\n\n//! Test back and forth Kepler <-> Cartesian conversion for non-circular equatorial orbit\ntemplate< typename ScalarType >\nvoid convertNonCircularEquatorialOrbitBackAndForth(\n        const ScalarType tolerance )\n{\n    // Using declarations.\n    using namespace orbital_element_conversions;\n\n    // Earth gravitational parameter [m^3 s^-2].\n    const ScalarType earthGravitationalParameter = 3.9859383624e14;\n\n    // Set Keplerian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > keplerianElements;\n    keplerianElements( semiMajorAxisIndex ) = static_cast< ScalarType >( 8000.0 );\n    keplerianElements( eccentricityIndex ) = static_cast< ScalarType >( 0.2 );\n    keplerianElements( inclinationIndex ) = getFloatingInteger< ScalarType >( 0 );\n    keplerianElements( argumentOfPeriapsisIndex ) = static_cast< ScalarType >( 243.0 / 180.0 * PI );\n    keplerianElements( longitudeOfAscendingNodeIndex ) = static_cast< ScalarType >(\n                -79.6 / 180.0 * PI );\n    keplerianElements( trueAnomalyIndex ) = static_cast< ScalarType >( 126.45 / 180.0 * PI );\n\n    // Convert Keplerian elements to Cartesian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > computedCartesianElements =\n            convertKeplerianToCartesianElements( keplerianElements, earthGravitationalParameter );\n\n    // Convert Cartesian elements back to Keplerian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > recomputedKeplerianElements =\n            convertCartesianToKeplerianElements(\n                computedCartesianElements, earthGravitationalParameter );\n\n    // Check that recomputed Keplerian elements match the input values. (In this limit case,\n    // the longitude of the ascending node is set to zero, and the argument of periapsis and\n    // true anomaly \"absorb\" this).\n    BOOST_CHECK_CLOSE_FRACTION( keplerianElements( semiMajorAxisIndex ),\n                                recomputedKeplerianElements( semiMajorAxisIndex ),\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( keplerianElements( eccentricityIndex ),\n                                recomputedKeplerianElements( eccentricityIndex ),\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( keplerianElements( inclinationIndex ),\n                                recomputedKeplerianElements( inclinationIndex ),\n                                std::numeric_limits< ScalarType >::epsilon( ) );\n\n    BOOST_CHECK_SMALL( recomputedKeplerianElements( longitudeOfAscendingNodeIndex ),\n                       std::numeric_limits< ScalarType >::epsilon( ) );\n\n    BOOST_CHECK_CLOSE_FRACTION( keplerianElements( longitudeOfAscendingNodeIndex )\n                                + keplerianElements( argumentOfPeriapsisIndex )\n                                + keplerianElements( trueAnomalyIndex ),\n                                recomputedKeplerianElements( argumentOfPeriapsisIndex )\n                                + recomputedKeplerianElements( trueAnomalyIndex ),\n                                std::numeric_limits< ScalarType >::epsilon( ) );\n\n    // Convert recomputed Keplerian elements to Cartesian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > recomputedCartesianElements;\n    recomputedCartesianElements = orbital_element_conversions::\n            convertKeplerianToCartesianElements(\n                recomputedKeplerianElements, earthGravitationalParameter );\n\n    // Check that computed Cartesian elements match.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                computedCartesianElements, recomputedCartesianElements, ( 10.0 * tolerance ) );\n}\n\n//! Test back and forth Kepler <-> Cartesian conversion for non-circular non-equatorial orbit\ntemplate< typename ScalarType >\nvoid convertNonCircularNonEquatorialOrbitBackAndForth(\n        const ScalarType tolerance )\n{\n    // Using declarations.\n    using namespace orbital_element_conversions;\n\n    // Earth gravitational parameter [m^3 s^-2].\n    const ScalarType earthGravitationalParameter = 3.9859383624e14;\n\n    // Set Keplerian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > keplerianElements;\n    keplerianElements( semiMajorAxisIndex ) = static_cast< ScalarType >( 8000.0 );\n    keplerianElements( eccentricityIndex ) = static_cast< ScalarType >( 0.2 );\n    keplerianElements( inclinationIndex ) = getFloatingInteger< ScalarType >(\n                176.11 / 180.0 * PI );\n    keplerianElements( argumentOfPeriapsisIndex ) = static_cast< ScalarType >( 243.0 / 180.0 * PI );\n    keplerianElements( longitudeOfAscendingNodeIndex ) = static_cast< ScalarType >(\n                -79.6 / 180.0 * PI );\n    keplerianElements( trueAnomalyIndex ) = static_cast< ScalarType >( 126.45 / 180.0 * PI );\n\n    // Convert Keplerian elements to Cartesian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > computedCartesianElements =\n            convertKeplerianToCartesianElements( keplerianElements, earthGravitationalParameter );\n\n    // Convert Cartesian elements back to Keplerian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > recomputedKeplerianElements =\n            convertCartesianToKeplerianElements(\n                computedCartesianElements, earthGravitationalParameter );\n\n    recomputedKeplerianElements( longitudeOfAscendingNodeIndex ) =\n            recomputedKeplerianElements( longitudeOfAscendingNodeIndex ) -\n            getFloatingInteger< ScalarType >( 2 ) * getPi< ScalarType >( );\n\n    // Check that recomputed Keplerian elements match the input values. (In this limit case,\n    // the longitude of the ascending node is set to zero, and the argument of periapsis and\n    // true anomaly \"absorb\" this).\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                keplerianElements, recomputedKeplerianElements, ( tolerance ) );\n\n    // Convert recomputed Keplerian elements to Cartesian elements.\n    Eigen::Matrix< ScalarType, 6, 1 > recomputedCartesianElements;\n    recomputedCartesianElements = orbital_element_conversions::\n            convertKeplerianToCartesianElements(\n                recomputedKeplerianElements, earthGravitationalParameter );\n\n    // Check that computed Cartesian elements match.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                computedCartesianElements, recomputedCartesianElements, ( 20.0 * tolerance ) );\n}\n\n//! Test if conversion from Cartesian elements to Keplerian elements is working correctly, using\n//! back and forth conversion, for both double and long double precision.\nBOOST_AUTO_TEST_CASE( testCartesianToKeplerianElementConversionBackAndForth )\n{\n    double ratioOfPrecision = std::numeric_limits< long double >::epsilon( ) /\n            std::numeric_limits< double >::epsilon( );\n\n    // Case 1: Parabolic orbit around the Sun.\n    // This test is based on converting Keplerian elements to Cartesian element and then\n    // recomputing the input Keplerian element values. Ideally, an independent check will replace\n    // this test in future.\n    {\n        convertParabolicOrbitBackAndForth< double >( 1.0E-15 );\n        convertParabolicOrbitBackAndForth< long double >( 1.0E-15L * ratioOfPrecision );\n    }\n    // Case 2: Converting to and fro between Keplerian and Cartesian elements for a\n    // zero-eccentricity, zero-inclination orbit (circular, equatorial) around the Earth. This\n    // test ensures internal consistency within Tudat between the Cartesian <-> Keplerian element\n    // converters.\n    {\n        convertCircularEquatorialOrbitBackAndForth< double >( 1.0E-15 );\n        convertCircularEquatorialOrbitBackAndForth< long double >( 1.0E-15L * ratioOfPrecision );\n    }\n\n    // Case 3: Converting to and fro between Keplerian and Cartesian elements for a\n    // zero-eccentricity, non-zero-inclination orbit (circular, inclined) around the Earth. This\n    // test ensures internal consistency within Tudat between the Cartesian <-> Keplerian element\n    // converters.\n    {\n        convertCircularNonEquatorialOrbitBackAndForth< double >( 1.0E-15 );\n        convertCircularNonEquatorialOrbitBackAndForth< long double >( 1.0E-15L * ratioOfPrecision );\n    }\n\n    // Case 4: Converting to and fro between Keplerian and Cartesian elements for a\n    // non-zero-eccentricity, zero-inclination orbit (non-circular, equatorial) around the Earth.\n    // This test ensures internal consistency within Tudat between the Cartesian <-> Keplerian\n    // element converters.\n    {\n        convertNonCircularEquatorialOrbitBackAndForth< double >( 1.0E-15 );\n        convertNonCircularEquatorialOrbitBackAndForth< long double >( 1.0E-15L * ratioOfPrecision );\n\n    }\n\n    // Case 5: Converting to and fro between Keplerian and Cartesian elements for a\n    // non-zero-eccentricity, non-zero-inclination orbit (non-circular, non-equatorial).\n    // This test ensures internal consistency within Tudat between the Cartesian <-> Keplerian\n    // element converters.\n    {\n        convertNonCircularNonEquatorialOrbitBackAndForth< double >( 5.0E-15 );\n        convertNonCircularNonEquatorialOrbitBackAndForth< long double >( 5.0E-15L * ratioOfPrecision );\n\n    }\n}\n\n//! Test if conversion from true anomaly to eccentric anomaly is working correctly.\nBOOST_AUTO_TEST_CASE( testTrueAnomalyToEccentricAnomalyConversion )\n{\n    // Case 1: General elliptical orbit.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Set eccentricity.\n        const double eccentricity = 0.146;\n\n        // Set true anomaly.\n        const double trueAnomaly = 82.16 / 180.0 * PI;\n\n        // Set expected elliptic eccentric anomaly.\n        const double expectedEllipticEccentricAnomaly = 1.290237398010989;\n\n        // Compute elliptic eccentric anomaly.\n        const double computedEllipticEccentricAnomaly\n                = orbital_element_conversions::\n                convertTrueAnomalyToEllipticalEccentricAnomaly( trueAnomaly, eccentricity );\n\n        // Check if computed elliptic eccentric anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedEllipticEccentricAnomaly,\n                                    computedEllipticEccentricAnomaly,\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 2: Circular orbit.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Set eccentricity.\n        const double eccentricity = 0.0;\n\n        // Set true anomaly.\n        const double trueAnomaly = 160.43 / 180.0 * PI;\n\n        // Set expected elliptic eccentric anomaly.\n        const double expectedEllipticEccentricAnomaly = 2.800031718974503;\n\n        // Compute elliptic eccentric anomaly.\n        const double computedEllipticEccentricAnomaly\n                = orbital_element_conversions::\n                convertTrueAnomalyToEllipticalEccentricAnomaly( trueAnomaly, eccentricity );\n\n        // Check if computed elliptic eccentric anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedEllipticEccentricAnomaly,\n                                    computedEllipticEccentricAnomaly,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 3: Circular orbit at periapsis.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Set eccentricity.\n        const double eccentricity = 0.0;\n\n        // Set true anomaly.\n        const double trueAnomaly = 0.0;\n\n        // Set expected elliptic eccentric anomaly.\n        const double expectedEllipticEccentricAnomaly = 0.0;\n\n        // Compute elliptic eccentric anomaly.\n        const double computedEllipticEccentricAnomaly\n                = orbital_element_conversions::\n                convertTrueAnomalyToEllipticalEccentricAnomaly( trueAnomaly, eccentricity );\n\n        // Check if computed elliptic eccentric anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedEllipticEccentricAnomaly,\n                                    computedEllipticEccentricAnomaly,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 4: General hyperbolic orbit.\n    // The benchmark data is obtained from (Fortescue, 2003).\n    {\n        // Set eccentricity.\n        const double eccentricity = 3.0;\n\n        // Set true anomaly.\n        const double trueAnomaly = 0.5291;\n\n        // Set expected hyperbolic eccentric anomaly.\n        const double expectedHyperbolicEccentricAnomaly = 0.3879;\n\n        // Compute hyperbolic eccentric anomaly.\n        const double convertedHyperbolicEccentricAnomaly\n                = orbital_element_conversions\n                ::convertTrueAnomalyToHyperbolicEccentricAnomaly( trueAnomaly, eccentricity );\n\n        // Check if computed hyperbolic eccentric anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedHyperbolicEccentricAnomaly,\n                                    convertedHyperbolicEccentricAnomaly, 1.0e-5 );\n    }\n\n    // Case 5: General elliptical orbit (test for wrapper function).\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Set eccentricity.\n        const double eccentricity = 0.146;\n\n        // Set true anomaly.\n        const double trueAnomaly = 82.16 / 180.0 * PI;\n\n        // Set expected elliptic eccentric anomaly.\n        const double expectedEllipticEccentricAnomaly = 1.290237398010989;\n\n        // Compute elliptic eccentric anomaly.\n        const double computedEllipticEccentricAnomaly\n                = orbital_element_conversions::\n                convertTrueAnomalyToEccentricAnomaly( trueAnomaly, eccentricity );\n\n        // Check if computed elliptic eccentric anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedEllipticEccentricAnomaly,\n                                    computedEllipticEccentricAnomaly,\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 6: General hyperbolic orbit (test for wrapper function).\n    // The benchmark data is obtained from (Fortescue, 2003).\n    {\n        // Set eccentricity.\n        const double eccentricity = 3.0;\n\n        // Set true anomaly.\n        const double trueAnomaly = 0.5291;\n\n        // Set expected hyperbolic eccentric anomaly.\n        const double expectedHyperbolicEccentricAnomaly = 0.3879;\n\n        // Compute hyperbolic eccentric anomaly.\n        const double convertedHyperbolicEccentricAnomaly\n                = orbital_element_conversions\n                ::convertTrueAnomalyToEccentricAnomaly( trueAnomaly, eccentricity );\n\n        // Check if computed hyperbolic eccentric anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedHyperbolicEccentricAnomaly,\n                                    convertedHyperbolicEccentricAnomaly, 1.0e-5 );\n    }\n}\n\n//! Test if conversion from eccentric anomaly to true anomaly is working correctly.\nBOOST_AUTO_TEST_CASE( testEccentricAnomalyToTrueAnomalyConversion )\n{\n    // Case 1: General elliptical orbit.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Set eccentricity.\n        const double eccentricity = 0.639;\n\n        // Set elliptic eccentric anomaly.\n        const double ellipticEccentricAnomaly = 239.45 / 180.0 * PI;\n\n        // Set expected true anomaly.\n        const double expectedTrueAnomaly = 3.665218735816221;\n\n        // Compute true anomaly, modulo 2*pi.\n        const double convertedTrueAnomaly\n                = orbital_element_conversions::\n                convertEllipticalEccentricAnomalyToTrueAnomaly( ellipticEccentricAnomaly,\n                                                                eccentricity ) + 2.0 * PI;\n\n        // Check if computed true anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedTrueAnomaly, convertedTrueAnomaly,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 2: Circular orbit.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Set eccentricity.\n        const double eccentricity = 0.0;\n\n        // Set elliptic eccentric anomaly.\n        const double ellipticEccentricAnomaly = -99.54 / 180.0 * PI;\n\n        // Set expected true anomaly.\n        const double expectedTrueAnomaly = 4.545884569744431;\n\n        // Compute true anomaly.\n        const double convertedTrueAnomaly\n                = orbital_element_conversions::\n                convertEllipticalEccentricAnomalyToTrueAnomaly( ellipticEccentricAnomaly,\n                                                                eccentricity ) + 2.0 * PI;\n\n        // Check if computed true anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedTrueAnomaly, convertedTrueAnomaly,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 3: Circular orbit at periapsis.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Set eccentricity.\n        const double eccentricity = 0.0;\n\n        // Set elliptic eccentric anomaly.\n        const double ellipticEccentricAnomaly = 0.0;\n\n        // Set expected true anomaly.\n        const double expectedTrueAnomaly = 0.0;\n\n        // Compute true anomaly.\n        const double convertedTrueAnomaly\n                = orbital_element_conversions::\n                convertEllipticalEccentricAnomalyToTrueAnomaly( ellipticEccentricAnomaly,\n                                                                eccentricity );\n\n        // Check if computed true anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedTrueAnomaly, convertedTrueAnomaly,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 4: General hyperbolic orbit.\n    // The benchmark data is obtained from (Fortescue, 2003).\n    {\n        // Set eccentricity.\n        const double eccentricity = 3.0;\n\n        // Set hyperbolic eccentric anomaly.\n        const double hyperbolicEccentricAnomaly = 0.3879;\n\n        // Set expected true anomaly.\n        const double expectedTrueAnomaly = 0.5291;\n\n        // Compute true anomaly.\n        const double convertedTrueAnomaly\n                = orbital_element_conversions\n                ::convertHyperbolicEccentricAnomalyToTrueAnomaly(\n                    hyperbolicEccentricAnomaly, eccentricity );\n\n        // Check if computed true anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedTrueAnomaly, convertedTrueAnomaly, 1.0e-5 );\n    }\n\n    // Case 5: General elliptical orbit (test for wrapper function).\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Set eccentricity.\n        const double eccentricity = 0.639;\n\n        // Set elliptic eccentric anomaly.\n        const double ellipticEccentricAnomaly = 239.45 / 180.0 * PI;\n\n        // Set expected true anomaly.\n        const double expectedTrueAnomaly = 3.665218735816221;\n\n        // Compute true anomaly, modulo 2*pi.\n        const double convertedTrueAnomaly\n                = orbital_element_conversions::\n                convertEccentricAnomalyToTrueAnomaly( ellipticEccentricAnomaly,\n                                                      eccentricity ) + 2.0 * PI;\n\n        // Check if computed true anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedTrueAnomaly, convertedTrueAnomaly,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 6: General hyperbolic orbit (test for wrapper function).\n    // The benchmark data is obtained from (Fortescue, 2003).\n    {\n        // Set eccentricity.\n        const double eccentricity = 3.0;\n\n        // Set hyperbolic eccentric anomaly.\n        const double hyperbolicEccentricAnomaly = 0.3879;\n\n        // Set expected true anomaly.\n        const double expectedTrueAnomaly = 0.5291;\n\n        // Compute true anomaly.\n        const double convertedTrueAnomaly\n                = orbital_element_conversions\n                ::convertEccentricAnomalyToTrueAnomaly(\n                    hyperbolicEccentricAnomaly, eccentricity );\n\n        // Check if computed true anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedTrueAnomaly, convertedTrueAnomaly, 1.0e-5 );\n    }\n}\n\n//! Test if conversion from eccentric anomaly to mean anomaly is working correctly.\nBOOST_AUTO_TEST_CASE( testEccentricAnomalyToMeanAnomalyConversion )\n{\n    // Case 1: General elliptical orbit.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Set eccentricity.\n        const double eccentricity = 0.541;\n\n        // Set elliptical eccentric anomaly.\n        const double ellipticalEccentricAnomaly = 176.09 / 180.0 * PI;\n\n        // Set expected mean anomaly.\n        const double expectedMeanAnomaly = 3.036459804491048;\n\n        // Compute mean anomaly.\n        const double computedMeanAnomaly = orbital_element_conversions\n                ::convertEllipticalEccentricAnomalyToMeanAnomaly(\n                    ellipticalEccentricAnomaly, eccentricity );\n\n        // Check if computed mean anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedMeanAnomaly, computedMeanAnomaly,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 2: Circular orbit.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Set eccentricity.\n        const double eccentricity = 0.0;\n\n        // Set elliptical eccentric anomaly.\n        const double ellipticalEccentricAnomaly = 320.12 / 180.0 * PI;\n\n        // Set expected mean anomaly.\n        const double expectedMeanAnomaly = 5.587148001484247;\n\n        // Compute mean anomaly.\n        const double computedMeanAnomaly = orbital_element_conversions\n                ::convertEllipticalEccentricAnomalyToMeanAnomaly(\n                    ellipticalEccentricAnomaly, eccentricity );\n\n        // Check if computed mean anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedMeanAnomaly, computedMeanAnomaly,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 3: Circular orbit at periapsis.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Set eccentricity.\n        const double eccentricity = 0.0;\n\n        // Set elliptical eccentric anomaly.\n        const double ellipticalEccentricAnomaly = 0.0;\n\n        // Set expected mean anomaly.\n        const double expectedMeanAnomaly = 0.0;\n\n        // Compute mean anomaly.\n        const double computedMeanAnomaly = orbital_element_conversions\n                ::convertEllipticalEccentricAnomalyToMeanAnomaly(\n                    ellipticalEccentricAnomaly, eccentricity );\n\n        // Check if computed mean anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedMeanAnomaly, computedMeanAnomaly,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 4: General hyperbolic orbit.\n    // The benchmark data is obtained from (Vallado, 2004).\n    {\n        // Set eccentricity.\n        const double eccentricity = 2.4;\n\n        // Set hyperbolic eccentric anomaly.\n        const double hyperbolicEccentricAnomaly = 1.6013761449;\n\n        // Set expected mean anomaly.\n        const double expectedMeanAnomaly = 235.4 / 180.0 * PI;\n\n        // Compute mean anomaly.\n        const double computedMeanAnomaly = orbital_element_conversions\n                ::convertHyperbolicEccentricAnomalyToMeanAnomaly( hyperbolicEccentricAnomaly,\n                                                                  eccentricity );\n\n        // Check if computed mean anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedMeanAnomaly, computedMeanAnomaly, 1.0e-8 );\n    }\n\n    // Case 5: General elliptical orbit (test for wrapper function).\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    {\n        // Set eccentricity.\n        const double eccentricity = 0.541;\n\n        // Set elliptical eccentric anomaly.\n        const double ellipticalEccentricAnomaly = 176.09 / 180.0 * PI;\n\n        // Set expected mean anomaly.\n        const double expectedMeanAnomaly = 3.036459804491048;\n\n        // Compute mean anomaly.\n        const double computedMeanAnomaly = orbital_element_conversions\n                ::convertEccentricAnomalyToMeanAnomaly(\n                    ellipticalEccentricAnomaly, eccentricity );\n\n        // Check if computed mean anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedMeanAnomaly, computedMeanAnomaly,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 6: General hyperbolic orbit.\n    // The benchmark data is obtained from (Vallado, 2004).\n    {\n        // Set eccentricity.\n        const double eccentricity = 2.4;\n\n        // Set hyperbolic eccentric anomaly.\n        const double hyperbolicEccentricAnomaly = 1.6013761449;\n\n        // Set expected mean anomaly.\n        const double expectedMeanAnomaly = 235.4 / 180.0 * PI;\n\n        // Compute mean anomaly.\n        const double computedMeanAnomaly = orbital_element_conversions\n                ::convertEccentricAnomalyToMeanAnomaly( hyperbolicEccentricAnomaly, eccentricity );\n\n        // Check if computed mean anomaly matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedMeanAnomaly, computedMeanAnomaly, 1.0e-8 );\n    }\n}\n\n//! Test if conversion from elapsed time to mean anomaly change is working correctly.\nBOOST_AUTO_TEST_CASE( testElapsedTimeToMeanAnomalyConversion )\n{\n    // Case 1: Earth-orbiting satellite.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    // The data is produced by running the kepprop2b_test() function through\n    // kepprop2b('ValidationTest'). To see the mean anomaly values computed, in the MATLAB file,\n    // remove the semi-colon at the end of line 68 in kepprop2b.m.\n    {\n        // Set elapsed time [s].\n        const double elapsedTime = 8640.0;\n\n        // Set Earth gravitational parameter.\n        const double earthGravitationalParameter = 398600.4415;\n\n        // Set semi-major axis [m].\n        const double semiMajorAxis = 42165.3431351313;\n\n        // Set expected elliptical mean anomaly change [rad].\n        const double expectedEllipticalMeanAnomalyChange = 2.580579656848906 - 1.950567148859647;\n\n        // Compute elliptical mean anomaly change [rad].\n        const double computedEllipticalMeanAnomalyChange\n                = orbital_element_conversions\n                ::convertElapsedTimeToEllipticalMeanAnomalyChange(\n                    elapsedTime, earthGravitationalParameter, semiMajorAxis );\n\n        // Check if computed elliptical mean anomaly change matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedEllipticalMeanAnomalyChange,\n                                    computedEllipticalMeanAnomalyChange, 1.0e-14 );\n    }\n\n    // Case 2: Earth-orbiting satellite with no elapsed time.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    // The data is produced by running the kepprop2b_test() function through\n    // kepprop2b('ValidationTest'). To see the mean anomaly values computed, in the MATLAB file,\n    // remove the semi-colon at the end of line 68 in kepprop2b.m.\n    {\n        // Set elapsed time [s].\n        const double elapsedTime = 0.0;\n\n        // Set Earth gravitational parameter.\n        const double earthGravitationalParameter = 398600.4415;\n\n        // Set semi-major axis [m].\n        const double semiMajorAxis = 42165.3431351313;\n\n        // Set expected elliptical mean anomaly change [rad].\n        const double expectedEllipticalMeanAnomalyChange = 0.0;\n\n        // Compute elliptical mean anomaly change [rad].\n        const double computedEllipticalMeanAnomalyChange\n                = orbital_element_conversions\n                ::convertElapsedTimeToEllipticalMeanAnomalyChange(\n                    elapsedTime, earthGravitationalParameter, semiMajorAxis );\n\n        // Check if computed elliptical mean anomaly change matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedEllipticalMeanAnomalyChange,\n                                    computedEllipticalMeanAnomalyChange,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 3: Hyperbolic orbit around the Sun.\n    // The benchmark data is obtained by simply repeating the equations in MATLAB. This test needs\n    // to be replaced with real \"external\" benchmark data.\n    {\n        // Set elapsed time [s].\n        const double elapsedTime = 1000.0;\n\n        // Set Sun gravitational parameter [m^3/s^-2].\n        const double sunGravitationalParameter = 3.9859383624e14;\n\n        // Set semi-major axis [m].\n        const double semiMajorAxis = -40000.0;\n\n        // Set expected mean anomaly change [rad].\n        const double expectedMeanAnomalyChange = 2.495601869539691e3;\n\n        // Compute mean anomaly change [rad].\n        const double computedMeanAnomalyChange\n                = orbital_element_conversions\n                ::convertElapsedTimeToHyperbolicMeanAnomalyChange(\n                    elapsedTime, sunGravitationalParameter, semiMajorAxis );\n\n        // Check if computed mean anomaly change matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedMeanAnomalyChange, computedMeanAnomalyChange,\n                                    1.0e-15 );\n    }\n\n    // Case 4: Earth-orbiting satellite (test for wrapper function).\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    // The data is produced by running the kepprop2b_test() function through\n    // kepprop2b('ValidationTest'). To see the mean anomaly values computed, in the MATLAB file,\n    // remove the semi-colon at the end of line 68 in kepprop2b.m.\n    {\n        // Set elapsed time [s].\n        const double elapsedTime = 8640.0;\n\n        // Set Earth gravitational parameter.\n        const double earthGravitationalParameter = 398600.4415;\n\n        // Set semi-major axis [m].\n        const double semiMajorAxis = 42165.3431351313;\n\n        // Set expected elliptical mean anomaly change [rad].\n        const double expectedEllipticalMeanAnomalyChange = 2.580579656848906 - 1.950567148859647;\n\n        // Compute elliptical mean anomaly change [rad].\n        const double computedEllipticalMeanAnomalyChange\n                = orbital_element_conversions\n                ::convertElapsedTimeToMeanAnomalyChange(\n                    elapsedTime, earthGravitationalParameter, semiMajorAxis );\n\n        // Check if computed elliptical mean anomaly change matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedEllipticalMeanAnomalyChange,\n                                    computedEllipticalMeanAnomalyChange, 1.0e-14 );\n    }\n\n    // Case 5: Hyperbolic orbit around the Sun (test for wrapper function).\n    // The benchmark data is obtained by simply repeating the equations in MATLAB. This test needs\n    // to be replaced with real \"external\" benchmark data.\n    {\n        // Set elapsed time [s].\n        const double elapsedTime = 1000.0;\n\n        // Set Sun gravitational parameter [m^3/s^-2].\n        const double sunGravitationalParameter = 3.9859383624e14;\n\n        // Set semi-major axis [m].\n        const double semiMajorAxis = -40000.0;\n\n        // Set expected mean anomaly change [rad].\n        const double expectedMeanAnomalyChange = 2.495601869539691e3;\n\n        // Compute mean anomaly change [rad].\n        const double computedMeanAnomalyChange\n                = orbital_element_conversions\n                ::convertElapsedTimeToMeanAnomalyChange(\n                    elapsedTime, sunGravitationalParameter, semiMajorAxis );\n\n        // Check if computed mean anomaly change matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedMeanAnomalyChange, computedMeanAnomalyChange,\n                                    1.0e-15 );\n    }\n}\n\n//! Test if conversion from mean anomaly change to elapsed time is working correctly.\nBOOST_AUTO_TEST_CASE( testMeanAnomalyToElaspedTimeConversion )\n{\n    // Case 1: Earth-orbiting satellite.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    // The data is produced by running the kepprop2b_test() function through\n    // kepprop2b('ValidationTest'). To see the mean anomaly values computed, in the MATLAB file,\n    // remove the semi-colon at the end of line 68 in kepprop2b.m.\n    {\n        // Set elliptical mean anomaly change [rad].\n        const double ellipticalMeanAnomalyChange = 3.210592164838165 - 1.950567148859647;\n\n        // Set Earth gravitational parameter [m^3/s^2].\n        const double earthGravitationalParameter = 398600.4415;\n\n        // Set semi-major axis [m].\n        const double semiMajorAxis = 42165.3431351313;\n\n        // Set expected elapsed time [s].\n        const double expectedElapsedTime = 17280.0;\n\n        // Compute elapsed time [s].\n        const double computedElapsedTime = orbital_element_conversions\n                ::convertEllipticalMeanAnomalyChangeToElapsedTime(\n                    ellipticalMeanAnomalyChange, earthGravitationalParameter, semiMajorAxis );\n\n        // Check if computed elapsed time matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedElapsedTime, computedElapsedTime, 1.0e-15 );\n    }\n\n    // Case 2: Earth-orbiting satellite with no mean anomaly change.\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    // The data is produced by running the kepprop2b_test() function through\n    // kepprop2b('ValidationTest'). To see the mean anomaly values computed, in the MATLAB file,\n    // remove the semi-colon at the end of line 68 in kepprop2b.m.\n    {\n        // Set elliptical mean anomaly change [rad].\n        const double ellipticalMeanAnomalyChange = 0.0;\n\n        // Set Earth gravitational parameter [m^3/s^2].\n        const double earthGravitationalParameter = 398600.4415;\n\n        // Set semi-major axis [m].\n        const double semiMajorAxis = 42165.3431351313;\n\n        // Set expected elapsed time [s].\n        const double expectedElapsedTime = 0.0;\n\n        // Compute elapsed time [s].\n        const double computedElapsedTime = orbital_element_conversions\n                ::convertEllipticalMeanAnomalyChangeToElapsedTime(\n                    ellipticalMeanAnomalyChange, earthGravitationalParameter, semiMajorAxis );\n\n        // Check if computed elapsed time matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedElapsedTime, computedElapsedTime,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 3: Hyperbolic orbit around the Sun.\n    // The benchmark data is obtained by simply repeating the equations in MATLAB. This test needs\n    // to be replaced with real \"external\" benchmark data.\n    {\n        // Set hyperbolic mean anomaly [rad].\n        const double hyperbolicMeanAnomaly = 2.495601869539691e3;\n\n        // Set Sun gravitational parameter [m^3/s^-2].\n        const double sunGravitationalParameter = 3.9859383624e14;\n\n        // Set semi-major axis [m].\n        const double semiMajorAxis = -40000.0;\n\n        // Set expected elapsed time [s].\n        const double expectedElapsedTime = 1000.0;\n\n        // Compute elapsed time [s].\n        const double computedElapsedTime = orbital_element_conversions\n                ::convertHyperbolicMeanAnomalyChangeToElapsedTime(\n                    hyperbolicMeanAnomaly, sunGravitationalParameter, semiMajorAxis );\n\n        // Check if computed elapsed time matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedElapsedTime, computedElapsedTime, 1.0e-15 );\n    }\n\n    // Case 4: Earth-orbiting satellite (test wrapper function).\n    // The benchmark data is obtained by running ODTBX (NASA, 2012).\n    // The data is produced by running the kepprop2b_test() function through\n    // kepprop2b('ValidationTest'). To see the mean anomaly values computed, in the MATLAB file,\n    // remove the semi-colon at the end of line 68 in kepprop2b.m.\n    {\n        // Set elliptical mean anomaly change [rad].\n        const double ellipticalMeanAnomalyChange = 3.210592164838165 - 1.950567148859647;\n\n        // Set Earth gravitational parameter [m^3/s^2].\n        const double earthGravitationalParameter = 398600.4415;\n\n        // Set semi-major axis [m].\n        const double semiMajorAxis = 42165.3431351313;\n\n        // Set expected elapsed time [s].\n        const double expectedElapsedTime = 17280.0;\n\n        // Compute elapsed time [s].\n        const double computedElapsedTime = orbital_element_conversions\n                ::convertMeanAnomalyChangeToElapsedTime(\n                    ellipticalMeanAnomalyChange, earthGravitationalParameter, semiMajorAxis );\n\n        // Check if computed elapsed time matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedElapsedTime, computedElapsedTime, 1.0e-15 );\n    }\n\n    // Case 5: Hyperbolic orbit around the Sun.\n    // The benchmark data is obtained by simply repeating the equations in MATLAB. This test needs\n    // to be replaced with real \"external\" benchmark data.\n    {\n        // Set hyperbolic mean anomaly [rad].\n        const double hyperbolicMeanAnomaly = 2.495601869539691e3;\n\n        // Set Sun gravitational parameter [m^3/s^-2].\n        const double sunGravitationalParameter = 3.9859383624e14;\n\n        // Set semi-major axis [m].\n        const double semiMajorAxis = -40000.0;\n\n        // Set expected elapsed time [s].\n        const double expectedElapsedTime = 1000.0;\n\n        // Compute elapsed time [s].\n        const double computedElapsedTime = orbital_element_conversions\n                ::convertMeanAnomalyChangeToElapsedTime(\n                    hyperbolicMeanAnomaly, sunGravitationalParameter, semiMajorAxis );\n\n        // Check if computed elapsed time matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedElapsedTime, computedElapsedTime, 1.0e-15 );\n    }\n}\n\n//! Test if conversion from mean motion to semi-major axis is working correctly.\nBOOST_AUTO_TEST_CASE( testMeanMotionToSemiMajorAxisConversion )\n{\n    // Case 1: Geostationary satellite around the Earth.\n    // The benchmark data is obtained from (Wikipedia, 2012).\n    {\n        // Set elliptical mean motion [rad/s].\n        const double ellipticalMeanMotion = 7.2921e-5;\n\n        // Set Earth gravitational parameter [m^3/s^2].\n        const double earthGravitationalParameter = 5.9736e24 * 6.67428e-11;\n\n        // Set expected semi-major axis [m].\n        const double expectedSemiMajorAxis = 42164.0e3;\n\n        // Compute semi-major axis [s].\n        const double computedSemiMajorAxis\n                = orbital_element_conversions\n                ::convertEllipticalMeanMotionToSemiMajorAxis( ellipticalMeanMotion,\n                                                              earthGravitationalParameter );\n\n        // Check if computed semi-major axis matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedSemiMajorAxis, computedSemiMajorAxis, 1.0e-4 );\n    }\n\n    // Case 2: Geostationary satellite around Mars.\n    // The benchmark data is obtained from (Wikipedia, 2012).\n    {\n        // Set elliptical mean motion [rad/s].\n        const double ellipticalMeanMotion = 7.088218e-5;\n\n        // Set Mars gravitational parameter [m^3/s^2].\n        const double marsGravitationalParameter = 42828.0e9;\n\n        // Set expected semi-major axis [m].\n        const double expectedSemiMajorAxis = 20427.0e3;\n\n        // Compute semi-major axis [m].\n        const double computedSemiMajorAxis\n                = orbital_element_conversions\n                ::convertEllipticalMeanMotionToSemiMajorAxis( ellipticalMeanMotion,\n                                                              marsGravitationalParameter );\n\n        // Check if computed semi-major axis matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedSemiMajorAxis, computedSemiMajorAxis, 1.0e-4 );\n    }\n}\n\n//! Test if conversion from semi-major axis to mean motion is working correctly.\nBOOST_AUTO_TEST_CASE( testSemiMajorAxisToMeanMotionConversion )\n{\n    // Case 1: Geostationary satellite around the Earth.\n    // The benchmark data is obtained from (Wikipedia, 2012).\n    {\n        // Set semi-major axis [m].\n        const double semiMajorAxis = 42164.0e3;\n\n        // Set Earth gravitational parameter [m^3/s^2].\n        const double earthGravitationalParameter = 5.9736e24 * 6.67428e-11;\n\n        // Set expected elliptical mean motion [rad/s].\n        const double expectedEllipticalMeanMotion = 7.2921e-5;\n\n        // Compute elliptical mean motion [rad/s].\n        const double computedEllipticalMeanMotion\n                = orbital_element_conversions\n                ::convertSemiMajorAxisToEllipticalMeanMotion( semiMajorAxis,\n                                                              earthGravitationalParameter );\n\n        // Check if computed elliptical mean motion matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedEllipticalMeanMotion,\n                                    computedEllipticalMeanMotion, 1.0e-3 );\n    }\n\n    // Case 2: Geostationary satellite around Mars.\n    // The benchmark data is obtained from (Wikipedia, 2012).\n    {\n        // Set semi-major axis [m].\n        const double semiMajorAxis = 20427.0e3;\n\n        // Set Mars gravitational parameter [m^3/s^2].\n        const double marsGravitationalParameter = 42828.0e9;\n\n        // Set expected elliptical mean motion [rad/s].\n        const double expectedEllipticalMeanMotion = 7.088218e-5;\n\n        // Compute mean motion [rad/s].\n        const double computedEllipticalMeanMotion\n                = orbital_element_conversions\n                ::convertSemiMajorAxisToEllipticalMeanMotion( semiMajorAxis,\n                                                              marsGravitationalParameter );\n\n        // Check if computed elliptical mean motion matches the expected value.\n        BOOST_CHECK_CLOSE_FRACTION( expectedEllipticalMeanMotion,\n                                    computedEllipticalMeanMotion, 1.0e-4 );\n    }\n\n}\n\n//! Test bug-fix to orbital element conversions for arguments of periapsis close to zero, pi or two pi.\n//! Thanks to Andreas Kleinschneider for finding the bug.\nBOOST_AUTO_TEST_CASE( test_ArgumentOfPeriapsisBugfix )\n{\n\n    // Define previously offending states and gravitational parameters.\n    Eigen::Vector6d centralBodyCartesianState;\n    centralBodyCartesianState << -521142852074.35858154296875, 595141535550.8497314453125, 8056093690.3882598876953125,\n            3904.21508802941389149054884911, -18262.3110776023386279121041298, 103.914916159730324807242141105;\n\n    Eigen::Vector6d orbitingBodyCartesianState;\n    orbitingBodyCartesianState << -520894562964.4881591796875, 595481881288.00537109375, 8071968111.222164154052734375,\n            -10065.8995464500585512723773718, -7984.05278915743656398262828588, 261.213167975313467650266829878;\n\n    Eigen::Vector6d relativeCartesianState = orbitingBodyCartesianState - centralBodyCartesianState;\n\n    double gravitationalParameterOfCentralBody = 126686534921800800;\n    double gravitationalParameterOfOrbitingBody = 5959916033410.404296875;\n\n    // Convert to Keplerian state\n    Eigen::Vector6d keplerianState =\n            orbital_element_conversions::convertCartesianToKeplerianElements(\n                relativeCartesianState, gravitationalParameterOfCentralBody + gravitationalParameterOfOrbitingBody );\n\n    // Check whether argument of periapsis is defined.\n    BOOST_CHECK_EQUAL( ( keplerianState( orbital_element_conversions::argumentOfPeriapsisIndex ) ==\n                         keplerianState( orbital_element_conversions::argumentOfPeriapsisIndex ) ), true );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_LongitudeOfNodeBugfix )\n{\n    std::cout << std::endl << std::endl;\n    using namespace tudat;\n\n    // Define previously offending states and gravitational parameters.\n    Eigen::Vector6d cartesianState;\n    cartesianState << 146378739288.0336,  -32851886854.1209, -14241055658.24648,  6603.183449760695,\n            26444.27948911581,  11463.63694918501;\n    double gravitationalParameterOfCentralBody = 1.327128386237518e+20;\n\n    // Convert to Keplerian state\n    Eigen::Vector6d keplerianState =\n            orbital_element_conversions::convertCartesianToKeplerianElements(\n                cartesianState, gravitationalParameterOfCentralBody );\n\n    Eigen::Vector6d recomputedCartesianState =\n            orbital_element_conversions::convertKeplerianToCartesianElements(\n                keplerianState, gravitationalParameterOfCentralBody );\n\n    Eigen::Vector6d  recomputedKeplerianState =\n            orbital_element_conversions::convertCartesianToKeplerianElements(\n                recomputedCartesianState, gravitationalParameterOfCentralBody );\n\n//    std::cout << std::setprecision( 16 ) << cartesianState.transpose( ) << std::endl;\n//    std::cout << std::setprecision( 16 ) << recomputedCartesianState.transpose( ) << std::endl << std::endl;\n\n//    std::cout << std::setprecision( 16 ) << keplerianState.transpose( ) << std::endl;\n//    std::cout << std::setprecision( 16 ) << recomputedKeplerianState.transpose( ) << std::endl;\n}\n\n\n//! Test if conversion from eccentric anomaly to mean anomaly is working correctly.\nBOOST_AUTO_TEST_CASE( testMeanToTrueAnomalyConversion )\n{\n    using namespace orbital_element_conversions;\n    using namespace basic_mathematics;\n\n    std::vector< double > meanAnomalies =\n    { 1.0E-12, 1.0, mathematical_constants::PI, 5.0, 2.0 * mathematical_constants::PI - 1.0E-12 };\n    std::vector< double > eccentricities =\n    { 0.0, 0.1, 0.5, 0.9, 0.99, 0.99999999, 1.00000001, 1.001, 2.0, 5.0, 10.0 };\n    for( unsigned int i = 0; i < meanAnomalies.size( ); i++ )\n    {\n        for( unsigned int j = 0; j < eccentricities.size( ); j++ )\n        {\n            double eccentricity = eccentricities.at( j );\n            double meanAnomaly = meanAnomalies.at( i );\n\n            double trueAnomaly = convertMeanAnomalyToTrueAnomaly( eccentricity, meanAnomaly );\n\n            double recomputedMeanAnomaly = convertTrueAnomalyToMeanAnomaly( eccentricity, trueAnomaly );\n\n            double anomalyDifference = meanAnomaly - recomputedMeanAnomaly;\n            if( anomalyDifference > 1.0 )\n            {\n                anomalyDifference -= 2.0 * mathematical_constants::PI;\n            }\n\n            double tolerance = 1.0E-13;\n            if( std::fabs( eccentricity - 1 ) < 0.1 )\n            {\n                tolerance *= 1.0E3;\n            }\n\n            if( std::fabs( eccentricity - 1 ) < 0.00001 )\n            {\n                tolerance *= 1.0E6;\n            }\n            BOOST_CHECK_SMALL( std::fabs( anomalyDifference ), tolerance );\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "10de844f6682d0c829f09ecb14b5c6dcc9f96685", "size": 77942, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/astro/basic_astro/unitTestOrbitalElementConversions.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/astro/basic_astro/unitTestOrbitalElementConversions.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/astro/basic_astro/unitTestOrbitalElementConversions.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": 46.394047619, "max_line_length": 119, "alphanum_fraction": 0.6722049729, "num_tokens": 18221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5129311153602357}}
{"text": "/*  raycasting %{Cpp:License:ClassName} - Yann BOUCHER (yann) 12/04/2016\n *\n**\n**\n**            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n**                    Version 2, December 2004\n**\n** Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>\n**\n** Everyone is permitted to copy and distribute verbatim or modified\n** copies of this license document, and changing it is allowed as long\n** as the name is changed.\n**\n**            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n**   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n**\n**  0. You just DO WHAT THE FUCK YOU WANT TO.\n*/\n\n#include \"raycasting.hpp\"\n\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n#include <algorithm>\n#include <iostream>\n\n#include <cmath>\n\n#include <Thor/Vectors.hpp>\n#include <Thor/Graphics/ColorGradient.hpp>\n\n#include \"camera.hpp\"\n#include \"map.hpp\"\n#include \"drawableactor.hpp\"\n\n#include \"utils/mathutility.hpp\"\n#include \"utils/graphicsutility.hpp\"\n#include \"utils/utility.hpp\"\n\nnamespace Rayfun\n{\n\nnamespace Raycasting\n{\n\nstd::vector<RaycastResult> castRay(const sf::Vector2d &t_begin, const sf::Vector2d &t_dir, Map& t_map, HitMode t_hitmode)\n{\n    const sf::Vector2d rayDir = thor::unitVector(t_dir);\n    auto mapPos = sf::Vector2i(t_begin);\n\n    const sf::Vector2d deltaDist = {\n        std::sqrt(1 + (t_dir.y * t_dir.y) / (t_dir.x * t_dir.x)),\n        std::sqrt(1 + (t_dir.x * t_dir.x) / (t_dir.y * t_dir.y))\n    };\n\n    sf::Vector2d sideDist;\n    const sf::Vector2i step = { rayDir.x < 0 ? -1 : 1, rayDir.y < 0 ? -1 : 1 };\n\n    if (rayDir.x < 0)\n    {\n        sideDist.x = (t_begin.x - mapPos.x) * deltaDist.x;\n    }\n    else\n    {\n        sideDist.x = (mapPos.x + 1 - t_begin.x) * deltaDist.x;\n    }\n    if (rayDir.y < 0)\n    {\n        sideDist.y = (t_begin.y - mapPos.y) * deltaDist.y;\n    }\n    else\n    {\n        sideDist.y = (mapPos.y + 1 - t_begin.y) * deltaDist.y;\n    }\n\n    Side side { Side::North };\n    bool hit { false };\n    std::vector<RaycastResult> results;\n    const auto correctedDir = thor::rotatedVector(rayDir, -90.0);\n\n    while (true)\n    {\n\n        do\n        {\n            if (sideDist.x < sideDist.y) // hit on x size\n            {\n                sideDist.x += deltaDist.x;\n                mapPos.x += step.x;\n                side = correctedDir.y > 0 ? Side::North : Side::South;\n            }\n            else // hit on y side\n            {\n                sideDist.y += deltaDist.y;\n                mapPos.y += step.y;\n                side = correctedDir.x > 0 ? Side::East : Side::West;\n            }\n\n            if (BOOST_UNLIKELY(mapPos.x < 0) || BOOST_UNLIKELY(mapPos.y < 0) ||\n                    BOOST_UNLIKELY(static_cast<unsigned>(mapPos.x) >= t_map.size().x) ||\n                    BOOST_UNLIKELY(static_cast<unsigned>(mapPos.y) >= t_map.size().y)) // Outside of map bounds\n            {\n                if (results.empty())\n                {\n                    results.push_back({ side });\n                }\n                return results;\n            }\n            else\n            {\n                switch (t_hitmode)\n                {\n                    case HitMode::Visibility:\n                        hit = t_map.tileAt(sf::Vector2s(mapPos)).isWall;\n                        break;\n                    case HitMode::Clipping:\n                        hit = t_map.tileAt(sf::Vector2s(mapPos)).clip[side];\n                        break;\n\n                }\n            }\n        } while (!hit);\n\n        double perpWallDist { 0 };\n\n        if (side == Side::North || side == Side::South)\n        {\n            perpWallDist = (mapPos.x - t_begin.x + (1 - step.x) / 2.f) / t_dir.x;\n        }\n        else\n        {\n            perpWallDist = (mapPos.y - t_begin.y + (1 - step.y) / 2.f) / t_dir.y;\n        }\n        if (!std::isfinite(perpWallDist))\n        {\n            perpWallDist = 0;\n        }\n\n        //mapPos = thor::rotated(sf::Vector2d(mapPos), 90);\n\n        // FIXME : replace all '64' with actual code !!\n\n        auto& tileHit = t_map.tileAt(sf::Vector2s(mapPos));\n        if (tileHit.tex[side])\n        {\n            if (side == Side::North || side == Side::South)\n            {\n\n                double wallX { }; //where exactly the wall was hit\n                wallX = t_begin.y + perpWallDist * t_dir.y;\n                wallX -= std::floor(wallX);\n                wallX = 1 - wallX;\n\n                unsigned texX = static_cast<unsigned>(wallX * static_cast<double>(\n                                                          64));\n\n                if (t_dir.x > 0)\n                {\n                    if (static_cast<int>(64 - texX - 1) < 0)\n                    {\n                        texX = 0;\n                    }\n                    else\n                    {\n                        texX = 64 - texX - 1;\n                    }\n                }\n\n                sf::Vector2d hitPos = sf::Vector2d(mapPos) + sf::Vector2d(0, wallX);\n\n                results.push_back({ side, tileHit, hitPos, mapPos,\n                                    Utility::distance(t_begin, hitPos), perpWallDist });\n\n                if (t_hitmode == HitMode::Clipping /*|| !Utility::imageStripContainsAlpha(*tileHit.tex[side], texX)*/)\n                {\n                    return results;\n                }\n            }\n            else\n            {\n\n                double wallX { }; //where exactly the wall was hit\n                wallX = t_begin.x + perpWallDist * t_dir.x;\n                wallX -= std::floor(wallX);\n                wallX = 1 - wallX;\n\n                unsigned texX = static_cast<unsigned>(wallX * static_cast<double>(\n                                                          64));\n\n                if (t_dir.y < 0)\n                {\n                    if (static_cast<int>(64 - texX - 1) < 0)\n                    {\n                        texX = 0;\n                    }\n                    else\n                    {\n                        texX = 64 - texX - 1;\n                    }\n                }\n\n                sf::Vector2d hitPos = sf::Vector2d(mapPos) + sf::Vector2d(wallX, 0);\n\n                results.push_back({ side, tileHit, hitPos, mapPos,\n                                    Utility::distance(t_begin, hitPos), perpWallDist });\n\n                if (t_hitmode == HitMode::Clipping /*|| !Utility::imageStripContainsAlpha(*tileHit.tex[side], texX)*/)\n                {\n                    return results;\n                }\n            }\n\n        }\n\n    }\n\n}\n\n//std::vector<sf::Uint8> render(const Camera& t_cam, const Map& t_map, bool bilinear_filtering,\n//                              bool t_bilinear_sprites)\n//{\n//    std::vector<sf::Uint8> renderTarget;\n//    renderTarget.resize(t_cam.screenSize().x * t_cam.screenSize().y * 4);\n//    std::fill(renderTarget.begin(), renderTarget.end(), 0);\n\n//    std::vector<double> zbuffer;\n//    zbuffer.resize(t_cam.screenSize().x);\n\n//    std::sort(t_map.sprites.begin(), t_map.sprites.end(), [&t_cam](std::unique_ptr<DrawableActor>& rhs,\n//              std::unique_ptr<DrawableActor>& lhs){\n//        return Utility::distance(rhs->pos, t_cam.pos()) > Utility::distance(lhs->pos, t_cam.pos());\n//    });\n\n//    static Utility::LookupTable<double> lut(t_cam.screenSize().x, [&t_cam](size_t i){\n//        return 2.f * i / t_cam.screenSize().x - 1;\n//    });\n\n//#pragma omp parallel for simd\n//    for (size_t i = 0; i < t_cam.screenSize().x; ++i)\n//    {\n//        double cameraX = lut[i];\n//        //double cameraX = 2.f * i / t_cam.screenSize().x - 1;\n//        const sf::Vector2d dir = t_cam.direction() + t_cam.plane() * cameraX;\n//        const auto& results = castRay(t_cam.pos(), dir, const_cast<Map&>(t_map), HitMode::Visibility);\n\n//        for (size_t index { results.size() }; index > 0; --index)\n//        {\n//            const auto result = results[index - 1];\n//            const long lineHeight = static_cast<long>(t_cam.screenSize().y / result.perpDistance) *\n//                                    std::min<double>(t_cam.screenSize().x, t_cam.screenSize().y)\n//                                    / std::max<double>(t_cam.screenSize().x, t_cam.screenSize().y);\n//            const long drawStart = -lineHeight / 2 + static_cast<long>(t_cam.screenSize().y) / 2;\n\n//            if (index == results.size())\n//            {\n//                zbuffer[i] = result.perpDistance;\n//            }\n\n//            long drawStartClamped = drawStart;\n//            if (drawStart < 0)\n//            {\n//                drawStartClamped = 0;\n//            }\n//            const long drawEnd = static_cast<long>(lineHeight / 2 +\n//                                                   static_cast<long>(t_cam.screenSize().y) / 2);\n//            long drawEndClamped = drawEnd;\n//            if (drawEnd >= static_cast<long>(t_cam.screenSize().y))\n//            {\n//                drawEndClamped = static_cast<long>(t_cam.screenSize().y) - 1;\n//            }\n\n//            if (BOOST_LIKELY((bool)result.tileHit) && BOOST_LIKELY(result.tileHit->tex[result.side] != nullptr))\n//            {\n//                const double wallX = { result.side == Side::North || result.side == Side::South ?\n//                                       result.hitPos.y - std::floor(result.hitPos.y) : result.hitPos.x - std::floor(result.hitPos.x)\n//                                     };\n\n//                double texX = wallX * static_cast<double>(\n//                                  result.tileHit->tex[result.side]->getSize().x);\n\n//                if (((result.side == Side::North || result.side == Side::South) && dir.x > 0) ||\n//                        ((result.side == Side::East || result.side == Side::West) && dir.y < 0))\n//                {\n//                    texX = static_cast<double>(result.tileHit->tex[result.side]->getSize().x) - texX;\n//                }\n\n//                const unsigned char brightness = Utility::clamp(\n//                                                     t_map.ambientLight +\n//                                                     result.tileHit->brigthnessMap[result.side][static_cast<unsigned>(texX)]\n//                                                 , 0, 255);\n\n//                for (size_t j { static_cast<size_t>(drawStartClamped) }; static_cast<long>(j) < drawEndClamped; ++j)\n//                {\n//                    const double texY = Utility::map<double>(static_cast<double>(j),\n//                                                             static_cast<double>(drawStart),\n//                                                             static_cast<double>(drawEnd), 0,\n//                                                             static_cast<double>(result.tileHit->tex[result.side]->getSize().y));\n\n//                    sf::Color color;\n//                    if (bilinear_filtering)\n//                    {\n//                        color = Utility::bilinearFilter(*result.tileHit->tex[result.side], texX, texY);\n//                    }\n//                    else\n//                    {\n//                        color = result.tileHit->tex[result.side]->getPixel(texX, texY);\n//                        if (result.tileHit->decals[result.side] && texX < result.tileHit->decals[result.side]->getSize().x &&\n//                                texY < result.tileHit->decals[result.side]->getSize().y)\n//                        {\n//                            color = thor::blendColors(result.tileHit->tex[result.side]->getPixel(texX, texY),\n//                                    result.tileHit->decals[result.side]->getPixel(texX, texY),\n//                                    result.tileHit->decals[result.side]->getPixel(texX, texY).a / 255.f);\n//                        }\n//                    }\n//                    Utility::setBrightness(color, brightness);\n//                    color = detail::pixelIntensity(color, result.distance);\n//                    const size_t offset = (t_cam.screenSize().x * j + i) * 4;\n//                    if (BOOST_UNLIKELY(color.a != 0xFF))\n//                    {\n//                        sf::Color oldColor;\n//                        oldColor.r = renderTarget[offset + 0];\n//                        oldColor.g = renderTarget[offset + 1];\n//                        oldColor.b = renderTarget[offset + 2];\n\n//                        oldColor = detail::pixelIntensity(oldColor, result.distance);\n\n//                        if (result.side == Side::East || result.side == Side::West)\n//                        {\n//                            Utility::setBrightness(color, 150);\n//                        }\n\n//                        sf::Color blendedColor = thor::blendColors(oldColor, color, color.a / 255.f);\n\n//                        renderTarget[offset + 0] = blendedColor.r;\n//                        renderTarget[offset + 1] = blendedColor.g;\n//                        renderTarget[offset + 2] = blendedColor.b;\n//                        renderTarget[offset + 3] = 0xFF;\n//                    }\n//                    else\n//                    {\n//                        if (result.side == Side::East || result.side == Side::West)\n//                        {\n//                            Utility::setBrightness(color, 150);\n//                        }\n//                        renderTarget[offset + 0] = color.r;\n//                        renderTarget[offset + 1] = color.g;\n//                        renderTarget[offset + 2] = color.b;\n//                        renderTarget[offset + 3] = 0xFF;\n//                    }\n//                }\n\n//                sf::Vector2d floorWall {};\n//                switch (result.side)\n//                {\n//                    case Side::South:\n//                        floorWall.x = result.mapPos.x;\n//                        floorWall.y = result.mapPos.y + (1 - wallX);\n//                        break;\n\n//                    case Side::North:\n//                        floorWall.x = result.mapPos.x + 1;\n//                        floorWall.y = result.mapPos.y + (1 - wallX);\n//                        break;\n\n//                    case Side::East:\n//                        floorWall.x = result.mapPos.x + (1 - wallX);\n//                        floorWall.y = result.mapPos.y;\n//                        break;\n\n//                    case Side::West:\n//                        floorWall.x = result.mapPos.x + (1 - wallX);\n//                        floorWall.y = result.mapPos.y + 1;\n//                        break;\n//                }\n\n//                if (drawEndClamped < 0)\n//                {\n//                    drawEndClamped = static_cast<long>(t_cam.screenSize().y);\n//                }\n\n//                //detail::floorCasting(t_cam, t_map, result, wallX, bilinear_filtering, drawEndClamped, i, renderTarget);\n//            }\n//        }\n//    }\n\n\n//    // Sprite casting\n\n//    detail::spriteCasting(t_cam, t_map.sprites, zbuffer, t_bilinear_sprites, t_map.ambientLight, renderTarget);\n\n//    return renderTarget;\n//}\n\n//namespace detail\n//{\n\n//void spriteCasting(const Camera &t_cam, const std::vector<std::unique_ptr<DrawableActor> > &t_sprites, const std::vector<double> &t_zbuffer, bool t_bilinear_sprites, unsigned char t_ambientLight, std::vector<sf::Uint8> &t_image)\n//{\n//    const double invDet = 1.0 / (t_cam.plane().x * t_cam.direction().y -\n//                                 t_cam.direction().x * t_cam.plane().y); //required for correct matrix multiplication\n\n//    for (const auto& sprite_ref : t_sprites)\n//    {\n//        auto& sprite = *sprite_ref;\n//        sf::Image spriteTex = sprite.renderImage();\n\n//        sf::Vector2d spritePos = sprite.pos - t_cam.pos();\n\n//        //transform sprite with the inverse camera matrix\n//        // [ planeX   dirX ] -1                                       [ dirY      -dirX ]\n//        // [               ]       =  1/(planeX*dirY-dirX*planeY) *   [                 ]\n//        // [ planeY   dirY ]                                          [ -planeY  planeX ]\n\n//        sf::Vector2d transform;\n//        transform.x = invDet * (t_cam.direction().y * spritePos.x - t_cam.direction().x * spritePos.y);\n//        transform.y = invDet * (-t_cam.plane().y * spritePos.x + t_cam.plane().x * spritePos.y);\n\n//        const int zScreen = (spriteTex.getSize().x * sprite.scale.y - sprite.z) / transform.y;\n\n//        int spriteScreenX = static_cast<int>((t_cam.screenSize().x / 2) * (1 + transform.x / transform.y));\n\n//        double ratioX = std::min<double>(spriteTex.getSize().x, spriteTex.getSize().y)\n//                        / std::max<double>(spriteTex.getSize().x, spriteTex.getSize().y);\n\n//        const int spriteHeight = static_cast<int>(std::abs(t_cam.screenSize().y / transform.y))\n//                                 * sprite.scale.y;\n\n//        int drawStartY = -spriteHeight / 2 + t_cam.screenSize().y / 2 + zScreen;\n//        if (drawStartY < 0)\n//        {\n//            drawStartY = 0;\n//        }\n//        size_t drawEndY = spriteHeight / 2 + t_cam.screenSize().y / 2 + zScreen;\n//        if (drawEndY >= t_cam.screenSize().y)\n//        {\n//            drawEndY = t_cam.screenSize().y - 1;\n//        }\n\n//        const int spriteWidth = std::abs(t_cam.screenSize().y / (transform.y)) * ratioX * sprite.scale.x;\n//        int drawStartX = -spriteWidth / 2 + spriteScreenX;\n//        if (drawStartX < 0)\n//        {\n//            drawStartX = 0;\n//        }\n//        int drawEndX = spriteWidth / 2 + spriteScreenX;\n//        if (drawEndX >= int(t_cam.screenSize().x))\n//        {\n//            drawEndX = t_cam.screenSize().x - 1;\n//        }\n//        for (int stripe = drawStartX; stripe < drawEndX; ++stripe)\n//        {\n//            double texX = (stripe - (-spriteWidth / 2 + spriteScreenX)) * double(spriteTex.getSize().x) / double(spriteWidth);\n\n//            if (transform.y > 0 && stripe < t_cam.screenSize().x && transform.y < t_zbuffer[stripe] && texX >= 0)\n//            {\n//                for (int y = drawStartY; y < drawEndY; ++y)\n//                {\n//                    const double d = (y - zScreen) - t_cam.screenSize().y / 2 + spriteHeight / 2;\n//                    const double texY = d * spriteTex.getSize().y / double(spriteHeight);\n//                    sf::Color color;\n//                    if (t_bilinear_sprites)\n//                    {\n//                        color = Utility::bilinearFilter(spriteTex, texX, texY);\n//                    }\n//                    else\n//                    {\n//                        color = spriteTex.getPixel(size_t(texX), size_t(texY));\n//                    }\n//                    Utility::setBrightness(color, t_ambientLight);\n//                    color = pixelIntensity(color, Utility::distance(t_cam.pos(), sprite.pos));\n//                    if (color.a == 255)\n//                    {\n//                        t_image[(t_cam.screenSize().x * y + stripe) * 4 + 0] = color.r;\n//                        t_image[(t_cam.screenSize().x * y + stripe) * 4 + 1] = color.g;\n//                        t_image[(t_cam.screenSize().x * y + stripe) * 4 + 2] = color.b;\n//                        t_image[(t_cam.screenSize().x * y + stripe) * 4 + 3] = 0xFF;\n//                    }\n//                }\n//            }\n//        }\n\n//    }\n//}\n\n//void floorCasting(const Camera &t_cam, const Map &t_map, const RaycastResult &t_result, double t_wallX, bool t_bilinear_filtering, long t_drawEnd, size_t t_screenX, std::vector<sf::Uint8> &t_image)\n//{\n\n//    sf::Vector2d floorWall {};\n//    switch (t_result.side)\n//    {\n//        case Side::South:\n//            floorWall.x = t_result.mapPos.x;\n//            floorWall.y = t_result.mapPos.y + (1 - t_wallX);\n//            break;\n\n//        case Side::North:\n//            floorWall.x = t_result.mapPos.x + 1;\n//            floorWall.y = t_result.mapPos.y + (1 - t_wallX);\n//            break;\n\n//        case Side::East:\n//            floorWall.x = t_result.mapPos.x + (1 - t_wallX);\n//            floorWall.y = t_result.mapPos.y;\n//            break;\n\n//        case Side::West:\n//            floorWall.x = t_result.mapPos.x + (1 - t_wallX);\n//            floorWall.y = t_result.mapPos.y + 1;\n//            break;\n//    }\n\n\n//    static Utility::LookupTable<double> lut(t_cam.screenSize().y, [&t_cam](size_t i)\n//    {\n//        return t_cam.screenSize().y / (2.f * i - t_cam.screenSize().y);\n//    });\n//#pragma omp parallel for simd\n//    for (size_t j = static_cast<size_t>(t_drawEnd) + 1; j < t_cam.screenSize().y; ++j)\n//    {\n//        //const double currentDist = t_cam.screenSize().y / (2.f * j - t_cam.screenSize().y);\n//        const double currentDist = lut[j];\n//        const double weight = currentDist / t_result.perpDistance;\n//        const sf::Vector2d floorPos = weight * floorWall +\n//                                      (1.0 - weight) * t_cam.pos();\n\n//        const auto sector = t_map.sectorAt(sf::Vector2s(floorPos));\n\n//        if (BOOST_LIKELY((bool)sector))\n//        {\n//            const sf::Image& floor = sector.get().floor;\n//            const sf::Image& ceiling = sector.get().floor;\n//            sf::Vector2d floorTexCoord {};\n\n//            floorTexCoord.x = (floorPos.x - std::floor(floorPos.x)) * floor.getSize().x;\n//            floorTexCoord.y = (floorPos.y - std::floor(floorPos.y)) * floor.getSize().y;\n\n//            sf::Vector2d ceilTexCoord {};\n\n//            ceilTexCoord.x = (floorPos.x - std::floor(floorPos.x)) * ceiling.getSize().x;\n//            ceilTexCoord.y = (floorPos.y - std::floor(floorPos.y)) * ceiling.getSize().y;\n\n//            sf::Color floorTexel;\n//            sf::Color ceilTexel;\n\n//            if (t_bilinear_filtering)\n//            {\n//                floorTexel = Utility::bilinearFilter(floor, floorTexCoord.x, floorTexCoord.y);\n//                ceilTexel = Utility::bilinearFilter(ceiling, ceilTexCoord.x, ceilTexCoord.y);\n//            }\n//            else\n//            {\n//                floorTexel = floor.getPixel(static_cast<unsigned>(floorTexCoord.x),\n//                                            static_cast<unsigned>(floorTexCoord.y));\n//                ceilTexel = ceiling.getPixel(static_cast<unsigned>(ceilTexCoord.x),\n//                                             static_cast<unsigned>(ceilTexCoord.y));\n//            }\n\n//            Utility::setBrightness(floorTexel, t_map.ambientLight);\n//            Utility::setBrightness(ceilTexel, t_map.ambientLight);\n\n//            Utility::setBrightness(floorTexel, 150);\n\n//            floorTexel = pixelIntensity(floorTexel, currentDist);\n//            ceilTexel = pixelIntensity(ceilTexel, currentDist);\n\n//            const auto floorPos = (t_cam.screenSize().x * (j-1) + t_screenX) * 4;\n//            t_image[floorPos + 0] = floorTexel.r;\n//            t_image[floorPos + 1] = floorTexel.g;\n//            t_image[floorPos + 2] = floorTexel.b;\n//            t_image[floorPos + 3] = floorTexel.a;\n\n//            const auto ceilPos = (t_cam.screenSize().x * (t_cam.screenSize().y - j) + t_screenX) * 4;\n//            t_image[ceilPos + 0] = ceilTexel.r;\n//            t_image[ceilPos + 1] = ceilTexel.g;\n//            t_image[ceilPos + 2] = ceilTexel.b;\n//            t_image[ceilPos + 3] = ceilTexel.a;\n//        }\n//    }\n//}\n\n//sf::Color pixelIntensity(sf::Color t_pixel, double t_dist)\n//{\n//    sf::Color returnColor = t_pixel;\n//    if (t_dist < 0) t_dist = 0;\n//    unsigned multiplier = 10;\n//    double intensity = 0.5 / t_dist * multiplier;\n//    if (intensity > 1) intensity = 1;\n//    else if (intensity < 0) intensity = 0;\n\n//    returnColor.r = t_pixel.r * intensity;\n//    returnColor.g = t_pixel.g * intensity;\n//    returnColor.b = t_pixel.b * intensity;\n\n//    return returnColor;\n//}\n\n//}\n\nbool rayIntersectsSprite(const sf::Vector2d &t_begin, const sf::Vector2d &t_dir, Map &t_map,\n                         DrawableActor*& t_hitSprite, size_t t_maxDistance)\n{\n    typedef boost::geometry::model::d2::point_xy<double> Point;\n    boost::geometry::model::linestring<Point> line;\n    Point origin = {t_begin.x, t_begin.y};\n    line.push_back(origin);\n    line.push_back({t_begin.x + t_dir.x * t_maxDistance, t_begin.y + t_dir.y * t_maxDistance});\n\n    for (auto& sprite : t_map.sprites)\n    {\n        sf::Image img = sprite->renderImage();\n        boost::geometry::model::polygon<Point> spriteRect;\n        double largestSide = std::max<double>(img.getSize().x, img.getSize().y);\n        double side = img.getSize().x / largestSide;\n        std::vector<Point> points =\n        {\n            {sprite->pos.x - side / 2, sprite->pos.x - side / 2},\n            {sprite->pos.x - side / 2, sprite->pos.x + side / 2},\n            {sprite->pos.x + side / 2, sprite->pos.x + side / 2},\n            {sprite->pos.x + side / 2, sprite->pos.x - side / 2}\n        };\n        boost::geometry::assign_points(spriteRect, points);\n        boost::geometry::model::multi_point<Point> intersectionPoints;\n        if (boost::geometry::intersection(line, spriteRect, intersectionPoints) && !intersectionPoints.empty())\n        {\n            auto result = castRay(t_begin, t_dir, t_map, HitMode::Visibility).front();\n            if (boost::geometry::distance(origin, intersectionPoints.front()) <= result.distance)\n            {\n                t_hitSprite = sprite.get();\n                return true;\n            }\n        }\n    }\n\n    return false;\n}\n\n} // namespace Raycasting\n\n} // namespace Rayfun\n", "meta": {"hexsha": "74d540302ce1b5be15f3b12e631c4f71b49a3476", "size": 25428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/raycasting.cpp", "max_stars_repo_name": "Stellaris-code/Rayfun", "max_stars_repo_head_hexsha": "2c9e5e2b0cd1636f0a046d6dce0efdce60f094cb", "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": "src/raycasting.cpp", "max_issues_repo_name": "Stellaris-code/Rayfun", "max_issues_repo_head_hexsha": "2c9e5e2b0cd1636f0a046d6dce0efdce60f094cb", "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": "src/raycasting.cpp", "max_forks_repo_name": "Stellaris-code/Rayfun", "max_forks_repo_head_hexsha": "2c9e5e2b0cd1636f0a046d6dce0efdce60f094cb", "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": 39.5458786936, "max_line_length": 230, "alphanum_fraction": 0.4869435268, "num_tokens": 6139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5129311153602357}}
{"text": "#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/io.hpp>\n#include <iostream>\nusing namespace boost::units;\nusing namespace boost::units::si;\nusing namespace std;\nclass vectorunit\n{\n  private:\n    quantity<length> x;\n    quantity<length> y;\n    quantity<length> z;\n\n  public:\n    vectorunit(quantity<length> vx, quantity<length> vy, quantity<length> vz)\n    {\n        x = vx;\n        y = vy;\n        z = vz;\n    }\n    void display_vector()\n    {\n        cout << \"(\" << x << \",\" << y << \",\" << z << \")\" << endl;\n    }\n};\n\nint main(int argc, char const *argv[])\n{\n    double x1, y1, z1;\n    cout << \"Enter 1st vector coordinate\" << endl;\n    cin >> x1 >> y1 >> z1;\n    quantity<length> nx(x1 * meters);\n    quantity<length> ny(y1 * meters);\n    quantity<length> nz(z1 * meters);\n    vectorunit result_vector(nx,ny,nz);\n    result_vector.display_vector();\n        return 0;\n}\n", "meta": {"hexsha": "68c95ec77fb035973f6a75dd208b8e4a45c7112e", "size": 901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vectorunit.cpp", "max_stars_repo_name": "avinal/C_ode", "max_stars_repo_head_hexsha": "f056da37c8c56a4a62a06351c2ea3773d16d1b11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-23T20:21:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-23T20:21:35.000Z", "max_issues_repo_path": "vectorunit.cpp", "max_issues_repo_name": "avinal/C_ode", "max_issues_repo_head_hexsha": "f056da37c8c56a4a62a06351c2ea3773d16d1b11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vectorunit.cpp", "max_forks_repo_name": "avinal/C_ode", "max_forks_repo_head_hexsha": "f056da37c8c56a4a62a06351c2ea3773d16d1b11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T10:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-03T10:12:28.000Z", "avg_line_length": 23.1025641026, "max_line_length": 77, "alphanum_fraction": 0.5904550499, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5129311153602357}}
{"text": "//\n// Created by krab1k on 31/10/18.\n//\n\n#include <vector>\n#include <cmath>\n#include <Eigen/LU>\n#include <functional>\n\n#include \"eqeqc.h\"\n#include \"../parameters.h\"\n#include \"../geometry.h\"\n\nCHARGEFW2_METHOD(EQeqC)\n\n\nEigen::VectorXd EQeqC::EE_system(const std::vector<const Atom *> &atoms, double total_charge) const {\n\n    size_t n = atoms.size();\n\n    const double lambda = 1.2;\n    const double k = 14.4;\n    double H_electron_affinity = -2.0; // Exception for hydrogen mentioned in the article\n\n    Eigen::MatrixXd A = Eigen::MatrixXd::Zero(n + 1, n + 1);\n    Eigen::VectorXd b = Eigen::VectorXd::Zero(n + 1);\n    Eigen::VectorXd J = Eigen::VectorXd::Zero(n);\n    Eigen::VectorXd X = Eigen::VectorXd::Zero(n);\n\n    for (size_t i = 0; i < n; i++) {\n        const auto &atom_i = *atoms[i];\n        if (atom_i.element().symbol() == \"H\") {\n            X(i) = (atom_i.element().ionization_potential() + H_electron_affinity) / 2;\n            J(i) = atom_i.element().ionization_potential() - H_electron_affinity;\n        } else {\n            X(i) = (atom_i.element().ionization_potential() + atom_i.element().electron_affinity()) / 2;\n            J(i) = atom_i.element().ionization_potential() - atom_i.element().electron_affinity();\n        }\n    }\n\n    for (size_t i = 0; i < n; i++) {\n        const auto &atom_i = *atoms[i];\n        A(i, i) = J(i);\n        b(i) = -X(i);\n        for (size_t j = i + 1; j < n; j++) {\n            const auto &atom_j = *atoms[j];\n            double a = std::sqrt(J(i) * J(j)) / k;\n            double Rij = distance(atom_i, atom_j);\n            double overlap = std::exp(-a * a * Rij * Rij) * (2 * a - a * a * Rij - 1 / Rij);\n            auto x = lambda * k / 2 * (1 / Rij + overlap);\n            A(i, j) = x;\n            A(j, i) = x;\n        }\n    }\n\n    A.row(n) = Eigen::VectorXd::Constant(n + 1, 1);\n    A.col(n) = Eigen::VectorXd::Constant(n + 1, 1);\n    A(n, n) = 0;\n    b(n) = total_charge;\n\n    return A.partialPivLu().solve(b).head(n);\n}\n\n\nstd::vector<double> EQeqC::calculate_charges(const Molecule &molecule) const {\n    size_t n = molecule.atoms().size();\n\n    auto f = [this](const std::vector<const Atom *> &atoms, double total_charge) -> Eigen::VectorXd {\n        return EE_system(atoms, total_charge);\n    };\n\n    Eigen::VectorXd q = solve_EE(molecule, f);\n\n    for (size_t i = 0; i < n; i++) {\n        const auto &atom_i = molecule.atoms()[i];\n        double correction = 0;\n        for (size_t j = 0; j < n; j++) {\n            if (i == j)\n                continue;\n            const auto &atom_j = molecule.atoms()[j];\n            double tkk = parameters_->atom()->parameter(atom::Dz)(atom_i) - parameters_->atom()->parameter(atom::Dz)(atom_j);\n            double bkk = std::exp(-parameters_->common()->parameter(common::alpha) *\n                                  (distance(atom_i, atom_j) - atom_i.element().covalent_radius() -\n                                   atom_j.element().covalent_radius()));\n            correction += tkk * bkk;\n        }\n        q(i) += correction;\n    }\n    return std::vector<double>(q.data(), q.data() + q.size());\n}\n", "meta": {"hexsha": "93d749b17383d5194904290dacdad98ca46eac56", "size": 3095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/methods/eqeqc.cpp", "max_stars_repo_name": "danny305/ChargeFW2", "max_stars_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T15:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:38:09.000Z", "max_issues_repo_path": "src/methods/eqeqc.cpp", "max_issues_repo_name": "danny305/ChargeFW2", "max_issues_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-03-04T21:38:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T07:11:19.000Z", "max_forks_repo_path": "src/methods/eqeqc.cpp", "max_forks_repo_name": "danny305/ChargeFW2", "max_forks_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-05T00:42:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T05:47:39.000Z", "avg_line_length": 34.010989011, "max_line_length": 125, "alphanum_fraction": 0.5447495961, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.5660185351961013, "lm_q1q2_score": 0.5128070281625214}}
{"text": "/**\n * \\file RLSFilter.cpp\n */\n\n#include \"RLSFilter.h\"\n#include <ATK/Core/TypeTraits.h>\n#include <ATK/Core/Utilities.h>\n\n#include <Eigen/Core>\n\n#include <cstdint>\n#include <complex>\n#include <stdexcept>\n\nnamespace ATK\n{\n  template<typename DataType_>\n  class RLSFilter<DataType_>::RLSFilterImpl\n  {\n  public:\n    using PType = Eigen::Matrix<DataType_, Eigen::Dynamic, Eigen::Dynamic>;\n    using wType = Eigen::Matrix<DataType_, Eigen::Dynamic, 1>;\n    using xType = Eigen::Map<const wType>;\n\n    explicit RLSFilterImpl(gsl::index size)\n      :P(PType::Identity(size, size) / DataType(size)), w(wType::Zero(size))\n    {\n    }\n\n    void learn(const xType& x, DataType_ target, DataType_ actual)\n    {\n      auto alpha = target - actual;\n      auto xreverse = x.reverse();\n\n      wType g = (P * xreverse) / ((xreverse.adjoint() * P * xreverse)(0,0) + static_cast<DataType>(memory));\n      PType pupdate = (g * (xreverse.adjoint() * P));\n      w = w + TypeTraits<DataType>::conj(alpha) * g;\n      P = (P - (pupdate + pupdate.transpose()) / 2) * memory;\n    }\n\n    void set_P(const DataType_* P)\n    {\n      this->P = Eigen::Map<const PType>(P, this->P.rows(), this->P.cols());\n    }\n\n    const DataType_* get_P() const\n    {\n      return P.data();\n    }\n\n    void set_w(const DataType_* w)\n    {\n      this->w = xType(w, this->w.rows(), 1);\n    }\n\n    const DataType_* get_w() const\n    {\n      return w.data();\n    }\n\n    PType P;\n    wType w;\n    double memory = 0.99;\n  };\n\n  template<typename DataType_>\n  RLSFilter<DataType_>::RLSFilter(gsl::index size)\n  :Parent(1, 1), impl(std::make_unique<RLSFilterImpl>(size)), global_size(size)\n  {\n    input_delay = size + 1;\n  }\n  \n  template<typename DataType_>\n  RLSFilter<DataType_>::~RLSFilter()\n  {\n  }\n  \n  template<typename DataType_>\n  void RLSFilter<DataType_>::set_size(gsl::index size)\n  {\n    if(size == 0)\n    {\n      throw ATK::RuntimeError(\"Size must be strictly positive\");\n    }\n\n    impl->P = RLSFilterImpl::PType::Identity(size, size) / DataType(size);\n    impl->w = typename RLSFilterImpl::wType(size, 1);\n    input_delay = size+1;\n    this->global_size = size;\n  }\n\n  template<typename DataType_>\n  gsl::index RLSFilter<DataType_>::get_size() const\n  {\n    return global_size;\n  }\n  \n  template<typename DataType_>\n  void RLSFilter<DataType_>::set_memory(double memory)\n  {\n    if(memory >= 1)\n    {\n      throw ATK::RuntimeError(\"Memory must be less than 1\");\n    }\n    if(memory <= 0)\n    {\n      throw ATK::RuntimeError(\"Memory must be strictly positive\");\n    }\n    \n    impl->memory = memory;\n  }\n  \n  template<typename DataType_>\n  double RLSFilter<DataType_>::get_memory() const\n  {\n    return impl->memory;\n  }\n  \n  template<typename DataType_>\n  void RLSFilter<DataType_>::set_learning(bool learning)\n  {\n    this->learning = learning;\n  }\n  \n  template<typename DataType_>\n  bool RLSFilter<DataType_>::get_learning() const\n  {\n    return learning;\n  }\n\n  template<typename DataType_>\n  void RLSFilter<DataType_>::process_impl(gsl::index size) const\n  {\n    const DataType* ATK_RESTRICT input = converted_inputs[0];\n    DataType* ATK_RESTRICT output = outputs[0];\n    \n    for(gsl::index i = 0; i < size; ++i)\n    {\n      typename RLSFilterImpl::xType x(input - global_size + i, global_size, 1);\n      \n      // compute next sample\n      output[i] = impl->w.adjoint().dot(x.reverse());\n      \n      if(learning)\n      {\n        //update w and P\n        impl->learn(x, input[i], output[i]);\n      }\n    }\n  }\n\n  template<typename DataType_>\n  void RLSFilter<DataType_>::set_P(const DataType_* P)\n  {\n     impl->set_P(P);\n  }\n  \n  template<typename DataType_>\n  const DataType_* RLSFilter<DataType_>::get_P() const\n  {\n    return impl->get_P();\n  }\n  \n  template<typename DataType_>\n  void RLSFilter<DataType_>::set_w(const DataType_* w)\n  {\n    impl->set_w(w);\n  }\n  \n  template<typename DataType_>\n  const DataType_* RLSFilter<DataType_>::get_w() const\n  {\n    return impl->get_w();\n  }\n\n  template class RLSFilter<double>;\n#if ATK_ENABLE_INSTANTIATION\n  template class RLSFilter<float>;\n  template class RLSFilter<std::complex<float>>;\n  template class RLSFilter<std::complex<double>>;\n#endif\n}\n", "meta": {"hexsha": "6084c04240750d7b62c56feebd700bfec72de494", "size": 4168, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Adaptive/RLSFilter.cpp", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "ATK/Adaptive/RLSFilter.cpp", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "ATK/Adaptive/RLSFilter.cpp", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 22.7759562842, "max_line_length": 108, "alphanum_fraction": 0.6331573896, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5128039825675942}}
{"text": "#include <boost/math/special_functions/binomial.hpp>\n", "meta": {"hexsha": "38bebd13bb0b207649f11011a861ca58bf2c682c", "size": 53, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_binomial.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_binomial.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_binomial.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.5, "max_line_length": 52, "alphanum_fraction": 0.8301886792, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5128039777961704}}
{"text": "#include \"FEMConstraint.h\"\n#include <iostream>\n#include <Eigen/LU>\nusing namespace FEM;\nbool\nFEMConstraint::\nComputeDeformationGradient(const Eigen::VectorXd& x)\n{\n\tEigen::Vector2d x0(x.block<2,1>(mi0*2,0));\n\n\tEigen::Matrix2d Ds;\n\n\tDs.block<2,1>(0,0) = x.block<2,1>(mi1*2,0)-x0;\n\tDs.block<2,1>(0,1) = x.block<2,1>(mi2*2,0)-x0;\n\n\tmCacheDs = Ds;\n\tmCacheF = mCacheDs * mInvDm;\n\n\treturn true;\n}\n\nFEMConstraint::\nFEMConstraint(const double& stiffness,const double& poisson_ratio,int i0,int i1,int i2,double vol,const Eigen::Matrix2d& invDm)\n\t:Constraint(stiffness),\n\tmMu(stiffness/((1.0+poisson_ratio))),mLambda(stiffness*poisson_ratio/((1.0+poisson_ratio)*(1-2.0*poisson_ratio))),\n\tmi0(i0),mi1(i1),mi2(i2),mVol(vol),mInvDm(invDm),\n\tmCacheDs(Eigen::Matrix2d::Zero()),\n\tmCacheF(Eigen::Matrix2d::Zero())\n{\n}\n\nvoid\nFEMConstraint::\nAddInversionFreePosition(Eigen::VectorXd& x)\n{\n\tComputeDeformationGradient(x);\n\tdouble vol = mCacheF.determinant();\n\tif(vol<0)\n\t{\n\t\tEigen::Vector2d proj_0;\n\t\tEigen::Vector2d proj_1;\n\t\tEigen::Vector2d proj_2;\n\n\t\tEigen::Vector2d p0,p1,p2;\n\t\tp0 = x.block<2,1>(2*mi0,0);\n\t\tp1 = x.block<2,1>(2*mi1,0);\n\t\tp2 = x.block<2,1>(2*mi2,0);\n\n\t\tproj_0 = (((p2-p1).dot(p0-p1))/((p2-p1).squaredNorm()))*(p2-p1) + p1;\n\t\tproj_1 = (((p2-p0).dot(p1-p0))/((p2-p0).squaredNorm()))*(p2-p0) + p0;\n\t\tproj_2 = (((p1-p0).dot(p2-p0))/((p1-p0).squaredNorm()))*(p1-p0) + p0;\n\t\t\n\t\tdouble len_0 = (p0-proj_0).squaredNorm();\t\t\n\t\tdouble len_1 = (p1-proj_1).squaredNorm();\t\t\n\t\tdouble len_2 = (p2-proj_2).squaredNorm();\n\t\tdouble eps = 1E-7;\n\n\t\tif(len_0<len_1&&len_0<len_2)\n\t\t\tx.block<2,1>(mi0*2,0) = proj_0+eps*(proj_0-p0);\n\t\telse if(len_1<len_0&&len_1<len_2)\n\t\t\tx.block<2,1>(mi1*2,0) = proj_1+eps*(proj_1-p1);\n\t\telse\n\t\t\tx.block<2,1>(mi2*2,0) = proj_2+eps*(proj_2-p2);\n\t}\n}\nint\nFEMConstraint::\nGetDof()\n{\n\treturn 2;\n}\nint\nFEMConstraint::\nGetNumHessianTriplets()\n{\n\treturn 36;\n}\nvoid\nFEMConstraint::\nAddOffset(const int& offset) \n{\n\tmi0+=offset;\n\tmi1+=offset;\n\tmi2+=offset;\n}\n\nconst int&\nFEMConstraint::\nGetI0()\n{\n\treturn mi0;\n}\nconst int&\nFEMConstraint::\nGetI1()\n{\n\treturn mi1;\n}\nconst int&\nFEMConstraint::\nGetI2()\n{\n\treturn mi2;\n}", "meta": {"hexsha": "5c003fd75ec95c377e9828b40a012ddbeddc8b2c", "size": 2117, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fem2D/Constraint/FEMConstraint.cpp", "max_stars_repo_name": "snumrl/volcon2D", "max_stars_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "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": "fem2D/Constraint/FEMConstraint.cpp", "max_issues_repo_name": "snumrl/volcon2D", "max_issues_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "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": "fem2D/Constraint/FEMConstraint.cpp", "max_forks_repo_name": "snumrl/volcon2D", "max_forks_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "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.3557692308, "max_line_length": 127, "alphanum_fraction": 0.6660368446, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5128039730247465}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include \"iris/iris.h\"\n\nint main(int argc, char** argv) {\n  iris::IRISProblem problem(2);\n  problem.setSeedPoint(Eigen::Vector2d(0.1, 0.1));\n\n  Eigen::MatrixXd obs(2,2);\n  // Inflate a region inside a 1x1 box\n  obs << 0, 1,\n         0, 0;\n  problem.addObstacle(obs);\n  obs << 1, 1,\n         0, 1;\n  problem.addObstacle(obs);\n  obs << 1, 0,\n         1, 1;\n  problem.addObstacle(obs);\n  obs << 0, 0,\n         1, 0;\n  problem.addObstacle(obs);\n\n  iris::IRISOptions options;\n  iris::IRISRegion region = inflate_region(problem, options);\n\n  std::cout << \"C: \" << region.ellipsoid.getC() << std::endl;\n  std::cout << \"d: \" << region.ellipsoid.getD() << std::endl;\n  return 0;\n}", "meta": {"hexsha": "c988e8cc03b9ced48eab5b85ca5e53c633959326", "size": 713, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cxx/iris_demo.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/iris_demo.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/iris_demo.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": 23.7666666667, "max_line_length": 61, "alphanum_fraction": 0.603085554, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024554, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5128039682533223}}
{"text": "#include \"lelantus_test_fixture.h\"\n\n#include \"../range_prover.h\"\n#include \"../range_verifier.h\"\n\n#include <boost/test/unit_test.hpp>\n\nnamespace lelantus {\n\nBOOST_FIXTURE_TEST_SUITE(lelantus_range_proof_tests, LelantusTestingSetup)\n\nBOOST_AUTO_TEST_CASE(prove_verify)\n{\n    uint64_t n = 64;\n    uint64_t m = 4;\n    secp_primitives::GroupElement g_gen, h_gen1, h_gen2;\n    g_gen.randomize();\n    h_gen1.randomize();\n    h_gen2.randomize();\n\n    //creating generators g, h vectors\n    auto g_ = RandomizeGroupElements(n * m);\n    auto h_ = RandomizeGroupElements(n * m);\n\n    auto serials = RandomizeScalars(m);\n    auto randoms = RandomizeScalars(m);\n\n    std::vector<secp_primitives::Scalar> v_s;\n    std::vector<secp_primitives::GroupElement> V;\n    for(uint64_t i = 0; i < m; ++i){\n        v_s.emplace_back(701 + i);\n        V.push_back(g_gen * v_s.back() +  h_gen1 * randoms[i] + h_gen2 * serials[i]);\n    }\n\n    RangeProver rangeProver(g_gen, h_gen1, h_gen2, g_, h_, n);\n    RangeProof proof;\n    rangeProver.batch_proof(v_s, serials, randoms, proof);\n\n    RangeVerifier rangeVerifier(g_gen, h_gen1, h_gen2, g_, h_, n);\n    BOOST_CHECK(rangeVerifier.verify_batch(V, proof));\n}\n\nBOOST_AUTO_TEST_CASE(out_of_range_notVerify)\n{\n    uint64_t n = 4;\n    uint64_t m = 4;\n    secp_primitives::GroupElement g_gen, h_gen1, h_gen2;\n    g_gen.randomize();\n    h_gen1.randomize();\n    h_gen2.randomize();\n\n    //creating generators g, h vectors\n    auto g_ = RandomizeGroupElements(n * m);\n    auto h_ = RandomizeGroupElements(n * m);\n\n    auto randoms = RandomizeScalars(m);\n    auto serials = RandomizeScalars(m);\n\n    auto testF = [&] (std::vector<Scalar> const v_s) {\n        std::vector<GroupElement> V;\n        for (uint64_t i = 0; i < m; ++i) {\n            V.push_back(g_gen * v_s[i] +  h_gen1 * randoms[i] + h_gen2 * serials[i]);\n        }\n\n        lelantus::RangeProver rangeProver(g_gen, h_gen1, h_gen2, g_, h_, n);\n        lelantus::RangeProof proof;\n        rangeProver.batch_proof(v_s, serials, randoms, proof);\n\n        lelantus::RangeVerifier rangeVerifier(g_gen, h_gen1, h_gen2, g_, h_, n);\n        BOOST_CHECK(!rangeVerifier.verify_batch(V, proof));\n    };\n\n    // All values are out of range\n    std::vector<Scalar> vs;\n    for(uint64_t i = 0; i < m; ++i){\n        vs.emplace_back(17 + i);\n    }\n    testF(vs);\n\n    // [0, 2 ^ n - 1]\n    Scalar l(uint64_t(0));\n    Scalar r((1 << n) - 1);\n\n    // One value is out of range\n    vs = {l, l + 1, r, r + 1};\n    testF(vs);\n\n    vs = {l - 1, l, r - 1, r};\n    testF(vs);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n} // namespace lelantus", "meta": {"hexsha": "4f3742c71f79a5983865959ade7273b86cdc0652", "size": 2580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/liblelantus/test/range_proof_test.cpp", "max_stars_repo_name": "xinya-123/firo", "max_stars_repo_head_hexsha": "738c8e1f96fa4c332a157776366b884a451194a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-03T09:47:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-03T09:47:44.000Z", "max_issues_repo_path": "src/liblelantus/test/range_proof_test.cpp", "max_issues_repo_name": "xinya-123/firo", "max_issues_repo_head_hexsha": "738c8e1f96fa4c332a157776366b884a451194a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/liblelantus/test/range_proof_test.cpp", "max_forks_repo_name": "xinya-123/firo", "max_forks_repo_head_hexsha": "738c8e1f96fa4c332a157776366b884a451194a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T16:49:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T16:49:56.000Z", "avg_line_length": 27.4468085106, "max_line_length": 85, "alphanum_fraction": 0.6379844961, "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895086850368, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5128039634818979}}
{"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 <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_levenberg.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n#include \"sophus/so3.hpp\"\n#include \"sophus/se3.hpp\"\n#include <chrono>\n\nusing namespace std;\nusing namespace cv;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\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\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\nvoid myBundleAdjustment (\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    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[2];\n    for ( DMatch m:matches )\n    {\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[0].push_back ( keypoints_1[m.queryIdx].pt );\n        pts_2d[1].push_back ( keypoints_2[m.trainIdx].pt );\n    }\n\n    cout<<\"3d-2d pairs: \"<<pts_3d.size() <<endl;\n\n    Mat r, t;\n    solvePnP ( pts_3d, pts_2d[1], 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\n    cout<<\"R=\"<<endl<<R<<endl;\n    cout<<\"t=\"<<endl<<t<<endl;\n\n    cout<<\"calling bundle adjustment\"<<endl;\n\n    ::myBundleAdjustment ( pts_3d, pts_2d, K, R, t );\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\nclass VertexCamera : public g2o::BaseVertex<6, Sophus::SE3d>\n{\n    public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    virtual void setToOriginImpl() // \u91cd\u7f6e\n    {\n        _estimate = Sophus::SE3d();\n    }\n    \n    virtual void oplusImpl( const double* update ) // \u66f4\u65b0\n    {\n        Eigen::Map<const Vector6d> update_vec(update);\n        setEstimate(Sophus::SE3d::exp(update_vec) * _estimate);\n    }\n    // \u5b58\u76d8\u548c\u8bfb\u76d8\uff1a\u7559\u7a7a\n    virtual bool read( istream& in ) {\n        return false;\n    }\n    virtual bool write( ostream& out ) const {\n        return false;\n    }  \n};\n\nclass VertexPointXYZ : public g2o::BaseVertex<3, Eigen::Vector3d>\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    virtual bool read( istream& in ) {\n        return false;\n    }\n    virtual bool write( ostream& out ) const {\n        return false;\n    }  \n\n    virtual void setToOriginImpl() {\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\n\nclass EdgeProject : public g2o::BaseBinaryEdge<2, Eigen::Vector2d, VertexPointXYZ, VertexCamera>{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    EdgeProject() {\n        _cam = nullptr;\n        resizeParameters(1);\n        installParameter(_cam, 0);\n    }\n\n    virtual bool read( istream& in ) {\n        return false;\n    }\n    virtual bool write( ostream& out ) const {\n        return false;\n    }  \n\n    void computeError()  {\n      const VertexCamera* v1 = static_cast<const VertexCamera*>(_vertices[1]);\n      const VertexPointXYZ* v2 = static_cast<const VertexPointXYZ*>(_vertices[0]);\n      const g2o::CameraParameters * cam\n        = static_cast<const g2o::CameraParameters *>(_cam);\n      _error = _measurement - cam->cam_map(v1->estimate() * (v2->estimate()));\n      \n    }\n\n    g2o::CameraParameters * _cam;\n};\n\n// reference: T=\n//     0.99778  -0.0522171   0.0413239   -0.129224\n//    0.051047    0.998279   0.0288811 -0.00970178\n//  -0.0427608  -0.0267076    0.998728   0.0601133\n//           0           0           0           1\n\nvoid myBundleAdjustment (\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    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose \u7ef4\u5ea6\u4e3a 6, landmark \u7ef4\u5ea6\u4e3a 3\n    std::unique_ptr<Block::LinearSolverType> linearSolver = g2o::make_unique<g2o::LinearSolverCSparse<Block::PoseMatrixType>>(); // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n    std::unique_ptr<Block> solver_ptr = g2o::make_unique<Block> ( move(linearSolver) );     // \u77e9\u9635\u5757\u6c42\u89e3\u5668\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( move(solver_ptr) );\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm ( solver );\n\n    // vertex\n    VertexCamera* pose[2]; // camera pose\n    pose[0] = new VertexCamera();\n    pose[0]->setId(0);\n    pose[0]->setEstimate(Sophus::SE3d());\n    optimizer.addVertex(pose[0]);\n\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[1] = new VertexCamera();\n    pose[1]->setId ( 1 );\n    pose[1]->setEstimate ( Sophus::SE3d (\n                            R_mat,\n                            Eigen::Vector3d ( t.at<double> ( 0,0 ), t.at<double> ( 1,0 ), t.at<double> ( 2,0 ) )\n                        ) );\n    optimizer.addVertex ( pose[1] );\n\n\n\n    int index = 2;\n    for ( const Point3f p:points_3d )   // landmarks\n    {\n        VertexPointXYZ* point = new VertexPointXYZ();\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 \u53c2\u89c1\u7b2c\u5341\u8bb2\u5185\u5bb9\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 = 2;\n    assert(points_2d[0].size() == points_2d[1].size());\n    for (size_t i = 0; i < points_2d[0].size(); i++)\n    {\n        for (size_t j = 0; j < 2; j++) {\n            EdgeProject* edge = new EdgeProject();\n            edge->setId ( index );\n            // cout << index << endl;\n            edge->setVertex ( 0, dynamic_cast<VertexPointXYZ*> ( optimizer.vertex ( index / 2 + 1 ) ) );\n            edge->setVertex ( 1, pose[j] );\n            edge->setMeasurement ( Eigen::Vector2d ( points_2d[j][i].x, points_2d[j][i].y ) );\n            edge->setParameterId ( 0,0 );\n            edge->setInformation ( Eigen::Matrix2d::Identity() );\n            optimizer.addEdge ( edge );\n            index++;\n        }\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<<\"T1=\"<<endl<<pose[0]->estimate().matrix() <<endl;\n    cout<<\"T2=\"<<endl<<pose[1]->estimate().matrix() <<endl;\n    cout<<\"relative T=\"<<endl<<(pose[0]->estimate().inverse() * pose[1]->estimate()).matrix() <<endl;\n}\n\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    // \u521d\u59cb\u5316g2o\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose \u7ef4\u5ea6\u4e3a 6, landmark \u7ef4\u5ea6\u4e3a 3\n    std::unique_ptr<Block::LinearSolverType> linearSolver = g2o::make_unique<g2o::LinearSolverCSparse<Block::PoseMatrixType>>(); // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n    std::unique_ptr<Block> solver_ptr = g2o::make_unique<Block> ( move(linearSolver) );     // \u77e9\u9635\u5757\u6c42\u89e3\u5668\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( move(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 ( 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    optimizer.addVertex ( pose );\n\n    int index = 1;\n    for ( const Point3f p:points_3d )   // landmarks\n    {\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 \u53c2\u89c1\u7b2c\u5341\u8bb2\u5185\u5bb9\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 Point2f p:points_2d )\n    {\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", "meta": {"hexsha": "b145188f70d2d9148ff98fd426c19d4de3f98898", "size": 13541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7/pose_estimation_3d2d.cpp", "max_stars_repo_name": "qq456cvb/Slambook-Exercise", "max_stars_repo_head_hexsha": "906d8866c8adc85b9e9dd53e382c2d103e8e5d6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch7/pose_estimation_3d2d.cpp", "max_issues_repo_name": "qq456cvb/Slambook-Exercise", "max_issues_repo_head_hexsha": "906d8866c8adc85b9e9dd53e382c2d103e8e5d6a", "max_issues_repo_licenses": ["MIT"], "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": "qq456cvb/Slambook-Exercise", "max_forks_repo_head_hexsha": "906d8866c8adc85b9e9dd53e382c2d103e8e5d6a", "max_forks_repo_licenses": ["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.4554707379, "max_line_length": 139, "alphanum_fraction": 0.5995864412, "num_tokens": 4301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5127221911609648}}
{"text": "/*\nBSD 3-Clause License\n\nCopyright (c) 2020, Jack Miles Hunt\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, 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\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (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#ifndef GPLIB_KERNEL_HEADER\n#define GPLIB_KERNEL_HEADER\n\n#include <Aliases.hpp>\n\n#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <optional>\n#include <cmath>\n\n#include <Eigen/Dense>\n\nnamespace GPLib {\n    //Available kernel types enumerated here.\n    enum class KernelType : short {\n        SQUARED_EXPONENTIAL\n    };\n\n    template<typename T>\n    class Kernel {\n    protected:\n        ParameterSet<T> params;\n        std::vector<std::string> validParams;\n\n    protected:\n        void verifyParam(const std::string& var) const {\n            assert(params.find(var) != params.end());\n        }\n\n        void verifyParams() {\n            // Check for missing parameters.\n            for (const auto& p : validParams) {\n                verifyParam(p);\n            }\n\n            // Check for invalid parameters.\n            for (const auto p : params) {\n                if (std::find(validParams.begin(), validParams.end(), p.first) == validParams.end()) {\n                    std::cout << \"WARNING: Surplus parameter \" + p.first + \" being removed from parameter set!\";\n                    params.erase(p.first);\n                }\n            }\n        }\n\n    protected:\n        Kernel(const std::vector< std::string >& validParams, const ParameterSet<T>& params) {\n            //\n        }\n\n    public:\n        virtual ~Kernel() {\n            //\n        }\n\n    public:\n        ParameterSet<T> getParameters() const {\n            return params;\n        }\n\n        void setParameters(const ParameterSet<T>& params) {\n            this->params = params;\n            verifyParams();\n        }\n\n        virtual T f(const Vector<T>& a, const Vector<T>& b) const = 0;\n\n        virtual KernelGradient<T> df(const Vector<T>& a, const Vector<T>& b, \n                                  const std::optional<std::string>& gradVar = std::nullopt) const = 0;\n\n        virtual Vector<T> dfda(const Vector<T>& a, const Vector<T>& b) const = 0;\n        \n        virtual Vector<T> dfdb(const Vector<T>& a, const Vector<T>& b) const = 0;\n    };\n}\n\n#endif\n", "meta": {"hexsha": "c4cfece4908dbd6835e183b1aceea7a615625d8f", "size": 3572, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/headers/Kernels/Kernel.hpp", "max_stars_repo_name": "JackHunt/GaussianProcess", "max_stars_repo_head_hexsha": "64820259608229ebc324904ec2f6213f205af804", "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": "lib/headers/Kernels/Kernel.hpp", "max_issues_repo_name": "JackHunt/GaussianProcess", "max_issues_repo_head_hexsha": "64820259608229ebc324904ec2f6213f205af804", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/headers/Kernels/Kernel.hpp", "max_forks_repo_name": "JackHunt/GaussianProcess", "max_forks_repo_head_hexsha": "64820259608229ebc324904ec2f6213f205af804", "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.4727272727, "max_line_length": 112, "alphanum_fraction": 0.6573348264, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5127221885732635}}
{"text": "#include \"MexPackUnpack.h\"\n#include \"mex.h\"\n#include <Eigen>\n\nusing namespace MexPackUnpackTypes;\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n  // We expect two real double matrices (treated as eigen maps), a scalar double, and a string\n  MexUnpacker<EDRM,  EDRM,double,std::string> my_unpack(nrhs, prhs);\n\n  try {\n\n    auto [a,b,c,d] = my_unpack.unpackMex(); //a,b are Eigen maps, c is double, d is std::string\n    Eigen::MatrixXd e = a+b*c;\n    d+=std::string(\" appended to the string\");\n    MexPacker<Eigen::MatrixXd,std::string> my_pack(nlhs, plhs); \n    my_pack.PackMex(e,d);    // We return an eigen Matrix and a string\n\n  } catch (std::string s) {\n    mexPrintf(s.data());\n  }\n\n}\n\n", "meta": {"hexsha": "6549bed39938f446fef8211058f2e028271bd322", "size": 725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example_1.cpp", "max_stars_repo_name": "kantorset/MexPackUnpack", "max_stars_repo_head_hexsha": "18eb8a62b3a12f3faf3271590478165c997e1843", "max_stars_repo_licenses": ["MIT"], "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/example_1.cpp", "max_issues_repo_name": "kantorset/MexPackUnpack", "max_issues_repo_head_hexsha": "18eb8a62b3a12f3faf3271590478165c997e1843", "max_issues_repo_licenses": ["MIT"], "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/example_1.cpp", "max_forks_repo_name": "kantorset/MexPackUnpack", "max_forks_repo_head_hexsha": "18eb8a62b3a12f3faf3271590478165c997e1843", "max_forks_repo_licenses": ["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.8846153846, "max_line_length": 95, "alphanum_fraction": 0.6689655172, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5127221836710141}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\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#include <boost/config.hpp>\n#include <iostream>\n#include <iterator>\n#include <vector>\n#include <list>\n// Use boost::queue instead of std::queue because std::queue doesn't\n// model Buffer; it has to top() function. -Jeremy\n#include <boost/pending/queue.hpp>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/visitors.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/graph_utility.hpp>\n\nusing namespace std;\nusing namespace boost;\n/*\n  This example does a best-first-search (using dijkstra's) and\n  simultaneously makes a copy of the graph (assuming the graph is\n  connected).\n\n  Example Graph: (p. 90 \"Data Structures and Network Algorithms\", Tarjan)\n\n              g\n            3+ +2\n            / 1 \\\n           e+----f\n           |+0 5++\n           | \\ / |\n         10|  d  |12\n           |8++\\7|\n           +/ | +|\n           b 4|  c\n            \\ | +\n            6+|/3\n              a\n\n  Sample Output:\na --> c d\nb --> a d\nc --> f\nd --> c e f\ne --> b g\nf --> e g\ng -->\nStarting graph:\na(32767); c d\nc(32767); f\nd(32767); c e f\nf(32767); e g\ne(32767); b g\ng(32767);\nb(32767); a d\nResult:\na(0); d c\nd(4); f e c\nc(3); f\nf(9); g e\ne(4); g b\ng(7);\nb(14); d a\n\n*/\n\ntypedef property< vertex_color_t, default_color_type,\n    property< vertex_distance_t, int > >\n    VProperty;\ntypedef int weight_t;\ntypedef property< edge_weight_t, weight_t > EProperty;\n\ntypedef adjacency_list< vecS, vecS, directedS, VProperty, EProperty > Graph;\n\ntemplate < class Tag >\nstruct endl_printer : public boost::base_visitor< endl_printer< Tag > >\n{\n    typedef Tag event_filter;\n    endl_printer(std::ostream& os) : m_os(os) {}\n    template < class T, class Graph > void operator()(T, Graph&)\n    {\n        m_os << std::endl;\n    }\n    std::ostream& m_os;\n};\ntemplate < class Tag > endl_printer< Tag > print_endl(std::ostream& os, Tag)\n{\n    return endl_printer< Tag >(os);\n}\n\ntemplate < class PA, class Tag >\nstruct edge_printer : public boost::base_visitor< edge_printer< PA, Tag > >\n{\n    typedef Tag event_filter;\n\n    edge_printer(PA pa, std::ostream& os) : m_pa(pa), m_os(os) {}\n\n    template < class T, class Graph > void operator()(T x, Graph& g)\n    {\n        m_os << \"(\" << get(m_pa, source(x, g)) << \",\" << get(m_pa, target(x, g))\n             << \") \";\n    }\n    PA m_pa;\n    std::ostream& m_os;\n};\ntemplate < class PA, class Tag >\nedge_printer< PA, Tag > print_edge(PA pa, std::ostream& os, Tag)\n{\n    return edge_printer< PA, Tag >(pa, os);\n}\n\ntemplate < class NewGraph, class Tag >\nstruct graph_copier\n: public boost::base_visitor< graph_copier< NewGraph, Tag > >\n{\n    typedef Tag event_filter;\n\n    graph_copier(NewGraph& graph) : new_g(graph) {}\n\n    template < class Edge, class Graph > void operator()(Edge e, Graph& g)\n    {\n        add_edge(source(e, g), target(e, g), new_g);\n    }\n\nprivate:\n    NewGraph& new_g;\n};\ntemplate < class NewGraph, class Tag >\ninline graph_copier< NewGraph, Tag > copy_graph(NewGraph& g, Tag)\n{\n    return graph_copier< NewGraph, Tag >(g);\n}\n\ntemplate < class Graph, class Name > void print(Graph& G, Name name)\n{\n    typename boost::graph_traits< Graph >::vertex_iterator ui, uiend;\n    for (boost::tie(ui, uiend) = vertices(G); ui != uiend; ++ui)\n    {\n        cout << name[*ui] << \" --> \";\n        typename boost::graph_traits< Graph >::adjacency_iterator vi, viend;\n        for (boost::tie(vi, viend) = adjacent_vertices(*ui, G); vi != viend;\n             ++vi)\n            cout << name[*vi] << \" \";\n        cout << endl;\n    }\n}\n\nint main(int, char*[])\n{\n    // Name and ID numbers for the vertices\n    char name[] = \"abcdefg\";\n    enum\n    {\n        a,\n        b,\n        c,\n        d,\n        e,\n        f,\n        g,\n        N\n    };\n\n    Graph G(N);\n    boost::property_map< Graph, vertex_index_t >::type vertex_id\n        = get(vertex_index, G);\n\n    std::vector< weight_t > distance(N, (numeric_limits< weight_t >::max)());\n    typedef boost::graph_traits< Graph >::vertex_descriptor Vertex;\n    std::vector< Vertex > parent(N);\n\n    typedef std::pair< int, int > E;\n\n    E edges[] = { E(a, c), E(a, d), E(b, a), E(b, d), E(c, f), E(d, c), E(d, e),\n        E(d, f), E(e, b), E(e, g), E(f, e), E(f, g) };\n\n    int weight[] = { 3, 4, 6, 8, 12, 7, 0, 5, 10, 3, 1, 2 };\n\n    for (int i = 0; i < 12; ++i)\n        add_edge(edges[i].first, edges[i].second, weight[i], G);\n\n    print(G, name);\n\n    adjacency_list< listS, vecS, directedS,\n        property< vertex_color_t, default_color_type > >\n        G_copy(N);\n\n    cout << \"Starting graph:\" << endl;\n\n    std::ostream_iterator< int > cout_int(std::cout, \" \");\n    std::ostream_iterator< char > cout_char(std::cout, \" \");\n\n    boost::queue< Vertex > Q;\n    boost::breadth_first_search(G, vertex(a, G), Q,\n        make_bfs_visitor(boost::make_list(\n            write_property(make_iterator_property_map(name, vertex_id, name[0]),\n                cout_char, on_examine_vertex()),\n            write_property(make_iterator_property_map(\n                               distance.begin(), vertex_id, distance[0]),\n                cout_int, on_examine_vertex()),\n            print_edge(make_iterator_property_map(name, vertex_id, name[0]),\n                std::cout, on_examine_edge()),\n            print_endl(std::cout, on_finish_vertex()))),\n        get(vertex_color, G));\n\n    std::cout << \"about to call dijkstra's\" << std::endl;\n\n    parent[vertex(a, G)] = vertex(a, G);\n    boost::dijkstra_shortest_paths(G, vertex(a, G),\n        distance_map(make_iterator_property_map(\n                         distance.begin(), vertex_id, distance[0]))\n            .predecessor_map(make_iterator_property_map(\n                parent.begin(), vertex_id, parent[0]))\n            .visitor(\n                make_dijkstra_visitor(copy_graph(G_copy, on_examine_edge()))));\n\n    cout << endl;\n    cout << \"Result:\" << endl;\n    boost::breadth_first_search(G, vertex(a, G),\n        visitor(make_bfs_visitor(boost::make_list(\n            write_property(make_iterator_property_map(name, vertex_id, name[0]),\n                cout_char, on_examine_vertex()),\n            write_property(make_iterator_property_map(\n                               distance.begin(), vertex_id, distance[0]),\n                cout_int, on_examine_vertex()),\n            print_edge(make_iterator_property_map(name, vertex_id, name[0]),\n                std::cout, on_examine_edge()),\n            print_endl(std::cout, on_finish_vertex())))));\n\n    return 0;\n}\n", "meta": {"hexsha": "0cf807fb8bf4787ce757aa9e5def7bf680b0724c", "size": 6913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/dave.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.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": "3rdparty/boost_1_73_0/libs/graph/example/dave.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": "3rdparty/boost_1_73_0/libs/graph/example/dave.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": 28.9246861925, "max_line_length": 80, "alphanum_fraction": 0.5819470563, "num_tokens": 1858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5127221836710141}}
{"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, log1p_exp) {\n  using stan::math::log1p_exp;\n\n  // exp(10000.0) overflows\n  EXPECT_FLOAT_EQ(10000.0, log1p_exp(10000.0));\n  EXPECT_FLOAT_EQ(0.0, log1p_exp(-10000.0));\n}\n\nTEST(MathFunctions, log1p_exp_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::log1p_exp(nan));\n}\n", "meta": {"hexsha": "05a06596b75c4ac86268fc2bccf9a59c58b94805", "size": 492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/log1p_exp_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/prim/scal/fun/log1p_exp_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "test/unit/math/prim/scal/fun/log1p_exp_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8947368421, "max_line_length": 71, "alphanum_fraction": 0.7317073171, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5127221813564657}}
{"text": "#include <catch/catch2.hpp>\n\n#include <orient/from_rotation_matrix.hpp>\n\n#include <Eigen/Geometry>\n#include <gtsam/base/numericalDerivative.h>\n#include <gtsam/geometry/Rot3.h>\n\nTEST_CASE(\"angleAxisFromRotationMatrix\")\n{\n  Eigen::Vector3d aa;\n  SECTION(\"Zero\"){\n    aa = Eigen::Vector3d::Zero();\n  }\n  SECTION(\"Random\"){\n    std::srand(1);\n    aa = Eigen::Vector3d::Random();\n  }\n  SECTION(\"half_PI_angle\"){\n    std::srand(2);\n    aa = Eigen::Vector3d::Random();\n    aa *= M_PI / (2*aa.norm());\n  }\n  SECTION(\"minus_half_PI_angle\"){\n    std::srand(3);\n    aa = Eigen::Vector3d::Random();\n    aa *= -M_PI / (2*aa.norm());\n  }\n  SECTION(\"PI_angle\"){\n    std::srand(4);\n    aa = Eigen::Vector3d::Random();\n    aa *= M_PI / aa.norm();\n  }\n  SECTION(\"minus_PI_angle\"){\n    std::srand(5);\n    aa = Eigen::Vector3d::Random();\n    aa *= -M_PI / aa.norm();\n  }\n  SECTION(\"2PI_angle\"){\n    std::srand(6);\n    aa = Eigen::Vector3d::Random();\n    aa *= 2*M_PI / aa.norm();\n  }\n  SECTION(\"minus_2PI_angle\"){\n    std::srand(7);\n    aa = Eigen::Vector3d::Random();\n    aa *= -2*M_PI / aa.norm();\n  }\n  SECTION(\"special1\"){\n    aa << M_PI,0,0;\n  }\n  SECTION(\"special2\"){\n    aa << 0,M_PI,0;\n  }\n  SECTION(\"special3\"){\n    aa << 0,0,M_PI;\n  }\n  SECTION(\"special4\"){\n    const auto a = M_PI/std::sqrt(2);\n    aa << a,a,0;\n  }\n  SECTION(\"special5\"){\n    const auto a = M_PI/std::sqrt(2);\n    aa << a,0,a;\n  }\n  SECTION(\"special6\"){\n    const auto a = M_PI/std::sqrt(2);\n    aa << 0,a,a;\n  }\n\n  const Eigen::Matrix3d R = gtsam::Rot3::Rodrigues(aa).matrix();\n  const Eigen::Vector3d actual_aa = orient::angleAxisFromRotationMatrix(R);\n  const Eigen::Matrix3d actual_R = gtsam::Rot3::Rodrigues(actual_aa).matrix();\n  CHECK( actual_R.isApprox(R) );\n}\n\nTEST_CASE(\"quaternionFromRotationMatrix\")\n{\n  Eigen::Vector3d aa;\n  SECTION(\"Zero\"){\n    aa = Eigen::Vector3d::Zero();\n  }\n  SECTION(\"Random\"){\n    std::srand(0);\n    aa = Eigen::Vector3d::Random();\n  }\n  SECTION(\"half_PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= M_PI / (2 * aa.norm());\n  }\n  SECTION(\"minus_half_PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= -M_PI / (2*aa.dot(aa));\n  }\n  SECTION(\"PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= M_PI / aa.norm();\n  }\n  SECTION(\"minus_PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= -M_PI / aa.norm();\n  }\n  SECTION(\"2PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= 2*M_PI / aa.norm();\n  }\n  SECTION(\"minus_2PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= -2*M_PI / aa.norm();\n  }\n  SECTION(\"special1\"){\n    aa << M_PI,0,0;\n  }\n  SECTION(\"special2\"){\n    aa << 0,M_PI,0;\n  }\n  SECTION(\"special3\"){\n    aa << 0,0,M_PI;\n  }\n  SECTION(\"special4\"){\n    const auto a = M_PI/std::sqrt(2);\n    aa << a,a,0;\n  }\n  SECTION(\"special5\"){\n    const auto a = M_PI/std::sqrt(2);\n    aa << a,0,a;\n  }\n  SECTION(\"special6\"){\n    const auto a = M_PI/std::sqrt(2);\n    aa << 0,a,a;\n  }\n\n  Eigen::Matrix3d R = gtsam::Rot3::Rodrigues(aa).matrix();\n  Eigen::Quaterniond equat{R};\n  Eigen::Vector4d expected = (Eigen::Vector4d() << equat.w(), equat.vec()).finished();\n  const Eigen::Vector4d actual = orient::quaternionFromRotationMatrix(R);\n  CHECK( actual.isApprox( expected ) );\n}\n\nTEST_CASE(\"angleAxisFromRotationMatrix_derivative\")\n{\n  std::srand(7);\n  Eigen::Vector3d aa;\n  SECTION(\"Random\"){\n    std::srand(0);\n    aa = Eigen::Vector3d::Random();\n  }\n  SECTION(\"half_PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= M_PI / (2 * aa.norm());\n  }\n  SECTION(\"minus_half_PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= -M_PI / (2*aa.dot(aa));\n  }\n  Eigen::Matrix3d R = gtsam::Rot3::Rodrigues(aa).matrix();\n\n  const auto [v, J] = orient::angleAxisFromRotationMatrixWD(R);\n  auto num = gtsam::numericalDerivative11(orient::angleAxisFromRotationMatrix<double>, R);\n  CHECK( v.isApprox(orient::angleAxisFromRotationMatrix(R)) );\n  CHECK( J.isApprox(num, 1e-8) );\n}\n\nTEST_CASE(\"quaternionFromRotationMatrix_derivative\")\n{\n  std::srand(8);\n  Eigen::Vector3d aa;\n  SECTION(\"Zero\"){\n    aa = Eigen::Vector3d::Zero();\n  }\n  SECTION(\"Random\"){\n    std::srand(0);\n    aa = Eigen::Vector3d::Random();\n  }\n  SECTION(\"half_PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= M_PI / (2 * aa.norm());\n  }\n  SECTION(\"minus_half_PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= -M_PI / (2*aa.dot(aa));\n  }\n\n  Eigen::Matrix3d R = gtsam::Rot3::Rodrigues(aa).matrix();\n\n  const auto [v, J] = orient::quaternionFromRotationMatrixWD(R);\n  auto num = gtsam::numericalDerivative11(orient::quaternionFromRotationMatrix<double>, R);\n  CHECK( v.isApprox(orient::quaternionFromRotationMatrix(R)) );\n  CHECK( J.isApprox(num, 1e-10) );\n}\n", "meta": {"hexsha": "cc2d56f4eb3cc7f0636fe8ebaefc2452d704096d", "size": 4665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/aa_quat_from_rotation_matrix_test.cpp", "max_stars_repo_name": "Eskilade/orient", "max_stars_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T07:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T09:23:29.000Z", "max_issues_repo_path": "test/aa_quat_from_rotation_matrix_test.cpp", "max_issues_repo_name": "Eskilade/orient", "max_issues_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-20T02:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T01:42:47.000Z", "max_forks_repo_path": "test/aa_quat_from_rotation_matrix_test.cpp", "max_forks_repo_name": "Eskilade/orient", "max_forks_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T11:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T04:26:22.000Z", "avg_line_length": 24.4240837696, "max_line_length": 91, "alphanum_fraction": 0.6036441586, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5127221813564657}}
{"text": "#ifndef STAN_MATH_FWD_MAT_FUN_TRACE_QUAD_FORM_HPP\n#define STAN_MATH_FWD_MAT_FUN_TRACE_QUAD_FORM_HPP\n\n#include <boost/type_traits.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n#include <stan/math/fwd/mat/fun/multiply.hpp>\n#include <stan/math/prim/mat/fun/multiply.hpp>\n#include <stan/math/prim/mat/fun/transpose.hpp>\n#include <stan/math/prim/mat/fun/trace.hpp>\n#include <stan/math/fwd/core.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template<int RA, int CA, int RB, int CB, typename T>\n    inline fvar<T>\n    trace_quad_form(const Eigen::Matrix<fvar<T>, RA, CA> &A,\n                    const Eigen::Matrix<fvar<T>, RB, CB> &B) {\n      check_square(\"trace_quad_form\", \"A\", A);\n      check_multiplicable(\"trace_quad_form\",\n                          \"A\", A,\n                          \"B\", B);\n      return trace(multiply(transpose(B),\n                            multiply(A, B)));\n    }\n\n    template<int RA, int CA, int RB, int CB, typename T>\n    inline fvar<T>\n    trace_quad_form(const Eigen::Matrix<fvar<T>, RA, CA> &A,\n                    const Eigen::Matrix<double, RB, CB> &B) {\n      check_square(\"trace_quad_form\", \"A\", A);\n      check_multiplicable(\"trace_quad_form\",\n                          \"A\", A,\n                          \"B\", B);\n      return trace(multiply(transpose(B),\n                            multiply(A, B)));\n    }\n\n    template<int RA, int CA, int RB, int CB, typename T>\n    inline fvar<T>\n    trace_quad_form(const Eigen::Matrix<double, RA, CA> &A,\n                    const Eigen::Matrix<fvar<T>, RB, CB> &B) {\n      check_square(\"trace_quad_form\", \"A\", A);\n      check_multiplicable(\"trace_quad_form\",\n                          \"A\", A,\n                          \"B\", B);\n      return trace(multiply(transpose(B),\n                            multiply(A, B)));\n    }\n  }\n}\n\n#endif\n\n", "meta": {"hexsha": "c1b64a02112204fa9e221ad82774973bcb673846", "size": 1880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/fwd/mat/fun/trace_quad_form.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/fwd/mat/fun/trace_quad_form.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/fwd/mat/fun/trace_quad_form.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5714285714, "max_line_length": 62, "alphanum_fraction": 0.5686170213, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5127221738665152}}
{"text": "/* boost random/cauchy_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: cauchy_distribution.hpp,v 1.1 2007/02/12 18:25:54 irving Exp $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_CAUCHY_DISTRIBUTION_HPP\n#define BOOST_RANDOM_CAUCHY_DISTRIBUTION_HPP\n\n#include <cmath>\n#include <iostream>\n#include <boost/limits.hpp>\n#include <boost/static_assert.hpp>\n\nnamespace boost {\n\n#if defined(__GNUC__) && (__GNUC__ < 3)\n// Special gcc workaround: gcc 2.95.x ignores using-declarations\n// in template classes (confirmed by gcc author Martin v. Loewis)\n  using std::tan;\n#endif\n\n// Cauchy distribution: p(x) = sigma/(pi*(sigma**2 + (x-median)**2))\ntemplate<class RealType = double>\nclass cauchy_distribution\n{\npublic:\n  typedef RealType input_type;\n  typedef RealType result_type;\n\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n  BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer);\n#endif\n\n  explicit cauchy_distribution(result_type median = result_type(0), \n                               result_type sigma = result_type(1))\n    : _median(median), _sigma(sigma) { }\n\n  // compiler-generated copy ctor and assignment operator are fine\n\n  result_type median() const { return _median; }\n  result_type sigma() const { return _sigma; }\n  void reset() { }\n\n  template<class Engine>\n  result_type operator()(Engine& eng)\n  {\n    // Can we have a boost::mathconst please?\n    const result_type pi = result_type(3.14159265358979323846);\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::tan;\n#endif\n    return _median + _sigma * tan(pi*(eng()-result_type(0.5)));\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 cauchy_distribution& cd)\n  {\n    os << cd._median << \" \" << cd._sigma;\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, cauchy_distribution& cd)\n  {\n    is >> std::ws >> cd._median >> std::ws >> cd._sigma;\n    return is;\n  }\n#endif\n\nprivate:\n  result_type _median, _sigma;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_CAUCHY_DISTRIBUTION_HPP\n", "meta": {"hexsha": "ce37e7d08655e4a1fe7504f598543bfe6b6d4319", "size": 2556, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/random/cauchy_distribution.hpp", "max_stars_repo_name": "schinmayee/nimbus", "max_stars_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-07-03T19:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T02:53:56.000Z", "max_issues_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/random/cauchy_distribution.hpp", "max_issues_repo_name": "schinmayee/nimbus", "max_issues_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/physbam/physbam-lib/External_Libraries/Archives/boost/boost/random/cauchy_distribution.hpp", "max_forks_repo_name": "schinmayee/nimbus", "max_forks_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T02:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-31T00:12:01.000Z", "avg_line_length": 28.4, "max_line_length": 91, "alphanum_fraction": 0.7226134585, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5127221738665152}}
{"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  VectorXd v(10);\nv.resize(3);\nRowVector3d w;\nw.resize(3); // this is legal, but has no effect\ncout << \"v: \" << v.rows() << \" rows, \" << v.cols() << \" cols\" << endl;\ncout << \"w: \" << w.rows() << \" rows, \" << w.cols() << \" cols\" << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "736278ef6103110be27ca2448df9919e061f5418", "size": 386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Matrix_resize_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.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.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": 20.3157894737, "max_line_length": 70, "alphanum_fraction": 0.5725388601, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786991753929, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.5127221712788137}}
{"text": "#include <stdio.h>\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Core>\n\n#include \"../libfovis/initial_homography_estimation.hpp\"\n#include <bot_core/bot_core.h>\n#include <bot_lcmgl_client/lcmgl.h>\n#include <GL/gl.h>\n\nusing namespace std;\n\n#define dump(var) (cerr<<\" \"#var<<\" =[\\n\"<< setprecision (3)<<var<<\"];\"<<endl)\n\nstatic Eigen::ArrayXf flattenMatrix(Eigen::MatrixXf &m)\n{\n  return Eigen::Map<Eigen::ArrayXf>(m.data(), m.rows() * m.cols());\n}\n\nstatic void warpImage(const uint8_t * image, int width, int height, int rowstride, const Eigen::Matrix3f &H,\n    uint8_t * warped_image)\n{\n  //setup the utility matrices\n  Eigen::MatrixXf x = Eigen::VectorXf::LinSpaced(width, 0, width - 1).transpose().replicate(height, 1);\n  Eigen::MatrixXf y = Eigen::VectorXf::LinSpaced(height, 0, height - 1).replicate(1, width);\n  Eigen::MatrixXf xx = flattenMatrix(x);\n  Eigen::MatrixXf yy = flattenMatrix(y);\n\n  Eigen::MatrixXf imageHomogeneousPoints(3, xx.rows());\n  imageHomogeneousPoints.row(0) = xx.transpose();\n  imageHomogeneousPoints.row(1) = yy.transpose();\n  imageHomogeneousPoints.row(2).setOnes();\n\n  Eigen::MatrixXf warpedHomogeneousPoints;\n  warpedHomogeneousPoints = H * imageHomogeneousPoints;\n\n  Eigen::MatrixXf warped = Eigen::MatrixXf(height, width);\n\n  const double defaultValue = 128;\n  //Bilinear interpolation\n  for (int i = 0; i < warpedHomogeneousPoints.cols(); i++) {\n    double val;\n    Eigen::Vector2f pt = warpedHomogeneousPoints.col(i).head(2) / warpedHomogeneousPoints(2, i);\n    Eigen::Vector2i fipt(floor(pt(0)), floor(pt(1)));\n    Eigen::Vector2i cipt(ceil(pt(0)), ceil(pt(1)));\n    if (0 <= pt(0) && pt(0) < width - 1 && 0 <= pt(1) && pt(1) < height - 1) {\n      double x1 = pt(0) - fipt(0);\n      double y1 = pt(1) - fipt(1);\n      double x2 = 1 - x1;\n      double y2 = 1 - y1;\n      val = x2 * y2 * image[fipt(1) * rowstride + fipt(0)] + x1 * y2 * image[fipt(1) * rowstride + fipt(0) + 1] + x2\n          * y1 * image[(fipt(1) + 1) * rowstride + fipt(0)] + x1 * y1 * image[(fipt(1) + 1) * rowstride + fipt(0) + 1];\n\n    }\n    else if (0 <= fipt(0) && fipt(0) < width && 0 <= fipt(1) && fipt(1) < height) {\n      val = image[fipt(1) * rowstride + fipt(0)];\n    }\n    else if (0 <= cipt(0) && cipt(0) < width && 0 <= cipt(1) && cipt(1) < height) {\n      val = image[cipt(1) * rowstride + cipt(0)];\n    }\n    else\n      val = defaultValue; //templateImage(i / width, i % width); //default to the same as template, so error is 0\n\n    warped_image[(i % height) * rowstride + (i / height)] = val; //Eigen is Column-major\n  }\n}\n\nint main(int argc, char** argv)\n{\n\n  uint8_t* src_im = (uint8_t*) malloc(640 * 480 * sizeof(uint8_t));\n\n  int width, height, rowstride;\n  bot_pgm_read_fname(\"test_im.pgm\", &src_im, &width, &height, &rowstride);\n\n  Eigen::MatrixXf ref_image = Eigen::MatrixXf::Zero(60, 80);\n  ref_image.block(15, 25, 30, 30).setConstant(255.0);\n\n  Eigen::Matrix3f H_warp;\n  H_warp.setZero();\n\n  double u = 2;\n  double v = 1;\n  double theta = 1 * M_PI / 180.0;\n  int downsample = 0;\n  if (argc >= 2)\n    u = atof(argv[1]);\n\n  if (argc >= 3)\n    v = atof(argv[2]);\n\n  if (argc >= 4)\n    theta = atof(argv[3]) * M_PI / 180.0;\n\n  if (argc >= 5)\n    downsample = atoi(argv[4]);\n\n  H_warp(0, 0) = cos(theta);\n  H_warp(0, 1) = sin(theta);\n  H_warp(1, 0) = -sin(theta);\n  H_warp(1, 1) = cos(theta);\n\n  H_warp(0, 2) = u;\n  H_warp(1, 2) = v;\n  H_warp(2, 2) = 1;\n\n  uint8_t* warped_im = (uint8_t*) malloc(width * height * sizeof(uint8_t));\n  warpImage(src_im, width, height, rowstride, H_warp, warped_im);\n\n  fovis::InitialHomographyEstimator rotation_estimator;\n  rotation_estimator.setTemplateImage(warped_im, width, height, rowstride, downsample);\n\n  rotation_estimator.setTestImage(src_im, width, height, rowstride, downsample);\n  double finalRMS = 0;\n  Eigen::Matrix3f H_est = rotation_estimator.track(Eigen::Matrix3f::Identity(), 10, &finalRMS);\n\n  double scale_factor = 1 << downsample;\n  Eigen::Matrix3f S = Eigen::Matrix3f::Identity() * scale_factor;\n  S(2,2)=1;\n\n  //scale homography up to the full size image\n  H_est = S * H_est * S.inverse();\n\n  dump(H_warp);\n  dump(H_est);\n  fprintf(stderr, \"finalRMS=%f\\n\", finalRMS);\n\n  //draw results\n  lcm_t * lcm = lcm_create(NULL);\n  bot_lcmgl_t* lcmgl = bot_lcmgl_init(lcm, \"Init_Homography_Test\\n\");\n\n  //convert to pixel coords\n  bot_lcmgl_push_matrix(lcmgl);\n  bot_lcmgl_rotated(lcmgl, -90, 0, 0, 1);\n  bot_lcmgl_scalef(lcmgl, 10.0 / width, -10.0 / width, 1);\n\n  // template image\n  bot_lcmgl_color3f(lcmgl, 1, 1, 1);\n  int template_texid = bot_lcmgl_texture2d(lcmgl, warped_im, width, height, rowstride, BOT_LCMGL_LUMINANCE,\n      BOT_LCMGL_COMPRESS_NONE);\n\n  bot_lcmgl_push_matrix(lcmgl);\n  bot_lcmgl_translated(lcmgl, 0, height + 10, 0);\n  bot_lcmgl_texture_draw_quad(lcmgl, template_texid, 0, 0, 0, 0, height, 0, width, height, 0, width, 0, 0);\n  bot_lcmgl_pop_matrix(lcmgl);\n\n  // test image\n  bot_lcmgl_color3f(lcmgl, 1, 1, 1);\n  int gray_texid = bot_lcmgl_texture2d(lcmgl, src_im, width, height, rowstride, BOT_LCMGL_LUMINANCE,\n      BOT_LCMGL_COMPRESS_NONE);\n  bot_lcmgl_texture_draw_quad(lcmgl, gray_texid, 0, 0, 0, 0, height, 0, width, height, 0, width, 0, 0);\n\n  //draw the ESM homography estimate\n  bot_lcmgl_line_width(lcmgl, 2.0);\n  bot_lcmgl_color3f(lcmgl, 1, 1, 0);\n  bot_lcmgl_begin(lcmgl, GL_LINE_STRIP);\n  Eigen::MatrixXf vertices(5, 3);\n  vertices << 0, 0, 1, width, 0, 1, width, height, 1, 0, height, 1, 0, 0, 1;\n\n  Eigen::MatrixXf warpedPoints = H_est * vertices.transpose();\n  warpedPoints.row(0) = warpedPoints.row(0).array() / warpedPoints.row(2).array();\n  warpedPoints.row(1) = warpedPoints.row(1).array() / warpedPoints.row(2).array();\n  for (int i = 0; i < warpedPoints.cols(); i++) {\n    bot_lcmgl_vertex2f(lcmgl, warpedPoints(0, i), warpedPoints(1, i));\n  }\n  bot_lcmgl_end(lcmgl);\n\n  bot_lcmgl_pop_matrix(lcmgl);\n\n  bot_lcmgl_switch_buffer(lcmgl);\n\n  return 0;\n}\n", "meta": {"hexsha": "aaa5e2f1a9987f7cd6b577b9a72fa37403924c6f", "size": 5877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "navigation_layer/fovis/libfovis/testers/initial_homography_estimation_tester.cpp", "max_stars_repo_name": "kartavya2000/Anahita", "max_stars_repo_head_hexsha": "9afbf6c238658188df7d0d97b2fec3bd48028c03", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-03-21T15:18:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T07:52:10.000Z", "max_issues_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/testers/initial_homography_estimation_tester.cpp", "max_issues_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_issues_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-10-03T12:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-07T09:33:14.000Z", "max_forks_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/testers/initial_homography_estimation_tester.cpp", "max_forks_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_forks_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2018-09-09T12:35:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-03T09:28:19.000Z", "avg_line_length": 33.5828571429, "max_line_length": 119, "alphanum_fraction": 0.6590096988, "num_tokens": 2077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5127144732866814}}
{"text": "//\n// Created by Esha Uboweja on 12/4/16.\n//\n\n#include <armadillo>\n#include \"BinaryLayer.h\"\n#include \"TestBinaryLayer.h\"\n\n//#define DEBUG 0\n\nusing namespace bd;\n\nbool TestBinaryLayer::test_binarizeMat_single(uint rows, uint cols) {\n    arma::mat values = arma::randn(rows, cols);\n\n    BinaryLayer bl = BinaryLayer(cols, rows);\n\n#ifdef DEBUG\n    std::cout << \"[test_binarizeMat_single] arma input:\\n\" << values << std::endl;\n#endif\n\n    // Compare Armadillo result and BinaryMatrix result\n    double armaAlpha = arma::mean(arma::mean(arma::abs(values)));\n    arma::umat armaResult(rows, cols);\n    armaResult.zeros();\n    armaResult.elem(arma::find(values >= 0)).ones();\n    armaResult.elem(arma::find(values < 0)).zeros();\n    bl.binarizeMat(values);\n\n#ifdef DEBUG\n    std::cout << \"[test_binarizeMat_single] Arma alpha: \" << armaAlpha << \" Arma output:\\n\" << armaResult << std::endl;\n    std::cout << \"[test_binarizeMat_single] Binarized alpha: \" << bl.alpha() << \" output (bl):\\n\";\n    bl.binMtx()->print();\n    std::cout << std::endl;\n#endif\n\n    return (bl.alpha() == armaAlpha) && bl.binMtx()->equalsArmaMat(armaResult);\n}\n\nbool TestBinaryLayer::test_binarizeMat() {\n    return test_binarizeMat_single()\n        && test_binarizeMat_single(5, 3)\n        && test_binarizeMat_single(28, 9)\n        && test_binarizeMat_single(81, 102);\n}\n\nbool TestBinaryLayer::test_operatorMult_single(uint rows1, uint cols1, uint rows2, uint cols2) {\n     // Generate 2 random binary matrices\n    arma::umat input2D_a = BinaryMatrix::randomArmaUMat(rows1, cols1);\n    BinaryLayer bl_a(input2D_a);\n    arma::umat input2D_b = BinaryMatrix::randomArmaUMat(rows2, cols2);\n    BinaryLayer bl_b(input2D_b);\n\n#ifdef DEBUG\n    std::cout << \"[test_operatorMult_single] arma input 1: \\n\" << input2D_a << std::endl;\n    std::cout << \"[test_operatorMult_single] binary matrix input 1: \\n\";\n    bl_a.binMtx()->print();\n    std::cout << std::endl;\n    std::cout << \"[test_operatorMult_single] arma input 2: \\n\" << input2D_b << std::endl;\n    std::cout << \"[test_operatorMult_single] binary matrix input 2: \\n\";\n    bl_b.binMtx()->print();\n    std::cout << std::endl;\n#endif\n\n    // XNOR product\n    BinaryLayer result = bl_a * bl_b;\n\n    // ARMA product\n    arma::imat ia = arma::conv_to<imat>::from(input2D_a);\n    ia.replace(0, -1);\n    arma::imat ib = arma::conv_to<imat>::from(input2D_b);\n    ib.replace(0, -1);\n    arma::imat ires = ia % ib;\n    ires.replace(-1, 0);\n    arma::umat armaResult = arma::conv_to<umat>::from(ires);\n\n\n#ifdef DEBUG\n    ires.replace(0, -1);\n    std::cout << \"[test_operatorMult_single] Arma integer result: \\n\" << ires << std::endl;\n    std::cout << \"[test_operatorMult_single] Arma result: \\n\" << armaResult << std::endl;\n    std::cout << \"[test_operatorMult_single] Binary layer result: \\n\";\n    result.binMtx()->print();\n    std::cout << std::endl;\n#endif\n\n    return result.binMtx()->equalsArmaMat(armaResult);\n}\n\nbool TestBinaryLayer::test_operatorMult_invalid(uint rows1, uint cols1, uint rows2, uint cols2) {\n    try {\n        test_operatorMult_single(rows1, cols1, rows2, cols2);\n    } catch (std::exception e) {\n        return true;\n    }\n    // didn't raise exception\n    return false;\n}\n\nbool TestBinaryLayer::test_operatorMult() {\n    return test_operatorMult_single()\n        && test_operatorMult_single(5, 6, 5, 6)\n        && test_operatorMult_invalid(5, 6, 7, 8);\n}\n\nbool TestBinaryLayer::test_im2col_single(uint rows, uint cols, uint block_width, uint block_height, uint padding,\n                                         uint stride) {\n    // Generate a random binary matrix\n    arma::umat input2D = BinaryMatrix::randomArmaUMat(rows, cols);\n    BinaryLayer bl(input2D);\n\n#ifdef DEBUG\n    std::cout << \"[test_im2col_single] arma input:\\n\" << input2D << std::endl;\n    std::cout << \"[test_im2col_single] bm input:\\n\" ;\n    bl.binMtx()->print();\n    std::cout << std::endl;\n#endif\n\n    // Compare im2col result for binary matrix and arma\n    arma::umat armaResult = BinaryMatrix::im2colArmaMat(input2D, block_width, block_height, padding, stride);\n    BinaryLayer blResult = bl.im2col(block_width, block_height, padding, stride);\n\n#ifdef DEBUG\n    std::cout << \"[test_im2col_single] arma result:\\n\" << armaResult << std::endl;\n    std::cout << \"[test_im2col_single] bm result:\\n\" ;\n    blResult.binMtx()->print();\n    std::cout << std::endl;\n#endif\n\n    return blResult.binMtx()->equalsArmaMat(armaResult);\n}\n\nbool TestBinaryLayer::test_im2col_invalid(uint rows, uint cols, uint block_width, uint block_height, uint padding, uint stride) {\n    try {\n        test_im2col_single(rows, cols, block_width, block_height, padding, stride);\n    } catch (std::exception e) {\n        return true;\n    }\n    std::cerr << \"[test_im2col_invalid] Test didn't raise exception\\n\";\n    // This test should raise an exception\n    return false;\n}\n\n\nbool TestBinaryLayer::test_im2col() {\n    return test_im2col_single()\n        && test_im2col_single(3, 3)\n        && test_im2col_single(3, 3, 3, 3, 1, 1)\n        && test_im2col_single(3, 3, 3, 3, 1, 2)\n        && test_im2col_single(5, 5, 3, 3, 1, 2)\n        && test_im2col_single(7, 9, 5, 5, 2, 1)\n        && test_im2col_invalid(8, 6, 3, 3, 1, 2)\n        && test_im2col_invalid(7, 9, 5, 5, 3, 1)\n        && test_im2col_invalid(10, 10, 3, 3, 0, 2);\n}\n\nvoid TestBinaryLayer::runAllTests() {\n    std::cout << \"----Testing BinaryLayer class functions...\\n\";\n    bool result = test_binarizeMat() && test_operatorMult() && test_im2col();\n    std::cout << \"[TestBinaryLayer] Tests completed! Result = \" << (result? \"PASSED\" : \"FAILED\") << std::endl;\n}", "meta": {"hexsha": "d0c0ab57dead667284e1caf5669a69c6e0397205", "size": 5593, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Prototype/TestBinaryLayer.cpp", "max_stars_repo_name": "PixieNets/BinNet", "max_stars_repo_head_hexsha": "d7a5be9ed95ee7e636afd2787661ab626925d20c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Prototype/TestBinaryLayer.cpp", "max_issues_repo_name": "PixieNets/BinNet", "max_issues_repo_head_hexsha": "d7a5be9ed95ee7e636afd2787661ab626925d20c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Prototype/TestBinaryLayer.cpp", "max_forks_repo_name": "PixieNets/BinNet", "max_forks_repo_head_hexsha": "d7a5be9ed95ee7e636afd2787661ab626925d20c", "max_forks_repo_licenses": ["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.7391304348, "max_line_length": 129, "alphanum_fraction": 0.652959056, "num_tokens": 1661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.512714466397913}}
{"text": "/*******************************************************************************\n * Copyright 2013-2014 Sebastian Niemann <niemann@sra.uni-hannover.de>.\n * \n * Licensed under the MIT License (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://opensource.org/licenses/MIT\n * \n * Developers:\n *   Sebastian Niemann - Lead developer\n *   Daniel Kiechle - Unit testing\n ******************************************************************************/\n#include <Expected.hpp>\nusing armadilloJava::Expected;\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <utility>\nusing std::pair;\n\n#include <armadillo>\nusing arma::Mat;\nusing arma::Col;\nusing arma::cross;\nusing arma::join_rows;\nusing arma::join_horiz;\nusing arma::join_cols;\nusing arma::join_vert;\nusing arma::kron;\n\n#include <InputClass.hpp>\nusing armadilloJava::InputClass;\n\n#include <Input.hpp>\nusing armadilloJava::Input;\n\nnamespace armadilloJava {\n  class ExpectedGenMatGenColVec : public Expected {\n    public:\n      ExpectedGenMatGenColVec() {\n        cout << \"Compute ExpectedGenMatGenColVec(): \" << endl;\n\n        vector<vector<pair<string, void*>>> inputs = Input::getTestParameters({\n          InputClass::GenMat,\n          InputClass::GenColVec\n        });\n\n        for (vector<pair<string, void*>> input : inputs) {\n          _fileSuffix = \"\";\n\n          int n = 0;\n          for (pair<string, void*> value : input) {\n            switch (n) {\n              case 0:\n                _fileSuffix += value.first;\n                _genMat = *static_cast<Mat<double>*>(value.second);\n                break;\n              case 1:\n                _fileSuffix += \",\" + value.first;\n                _genColVec = *static_cast<Col<double>*>(value.second);\n                break;\n            }\n            ++n;\n          }\n\n          cout << \"Using input: \" << _fileSuffix << endl;\n\n          expectedArmaCross();\n          expectedArmaJoin_rows();\n          expectedArmaJoin_horiz();\n          expectedArmaJoin_cols();\n          expectedArmaJoin_vert();\n          expectedArmaKron();\n          expectedMatPlus();\n          expectedMatMinus();\n          expectedMatTimes();\n          expectedMatElemTimes();\n          expectedMatElemDivide();\n          expectedMatEquals();\n          expectedMatNonEquals();\n          expectedMatGreaterThan();\n          expectedMatLessThan();\n          expectedMatStrictGreaterThan();\n          expectedMatStrictLessThan();\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n    protected:\n      Mat<double> _genMat;\n      Col<double> _genColVec;\n\n      void expectedArmaCross() {\n        cout << \"- Compute expectedArmaCross() ... \";\n\n        Mat<double> tempGenMat = Mat<double>(_genMat);\n        tempGenMat.resize(3, 1);\n        Col<double> tempGenColVec = Col<double>(_genColVec);\n        tempGenColVec.resize(3);\n\n        save<double>(\"Arma.cross\", cross(tempGenMat, tempGenColVec));\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaJoin_rows() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaJoin_rows() ... \";\n        save<double>(\"Arma.join_rows\", join_rows(_genMat, _genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaJoin_horiz() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaJoin_horiz() ... \";\n        save<double>(\"Arma.join_horiz\", join_horiz(_genMat, _genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaJoin_cols() {\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaJoin_cols() ... \";\n        save<double>(\"Arma.join_cols\", join_cols(_genMat, _genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaJoin_vert() {\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaJoin_vert() ... \";\n        save<double>(\"Arma.join_vert\", join_cols(_genMat, _genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaKron() {\n        cout << \"- Compute expectedArmaKron() ... \";\n        save<double>(\"Arma.kron\", kron(_genMat, _genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatPlus() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatPlus() ... \";\n        save<double>(\"Mat.plus\", _genMat + _genColVec);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatMinus() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatMinus() ... \";\n        save<double>(\"Mat.minus\", _genMat - _genColVec);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatTimes() {\n        if(_genMat.n_cols != _genColVec.n_rows) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatTimes() ... \";\n        save<double>(\"Mat.times\", _genMat * _genColVec);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatElemTimes() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatElemTimes() ... \";\n        save<double>(\"Mat.elemTimes\", _genMat % _genColVec);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatElemDivide() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatElemDivide() ... \";\n        save<double>(\"Mat.elemDivide\", _genMat / _genColVec);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatEquals() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatEquals() ... \";\n\n        Mat<uword> expected = _genMat == _genColVec;\n        save<uword>(\"Mat.equals\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatNonEquals() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatNonEquals() ... \";\n\n        Mat<uword> expected = _genMat != _genColVec;\n        save<uword>(\"Mat.nonEquals\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatGreaterThan() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatGreaterThan() ... \";\n\n        Mat<uword> expected = _genMat >= _genColVec;\n        save<uword>(\"Mat.greaterThan\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatLessThan() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatLessThan() ... \";\n\n        Mat<uword> expected = _genMat <= _genColVec;\n        save<uword>(\"Mat.lessThan\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatStrictGreaterThan() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatStrictGreaterThan() ... \";\n\n        Mat<uword> expected = _genMat > _genColVec;\n        save<uword>(\"Mat.strictGreaterThan\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatStrictLessThan() {\n        if(_genMat.n_rows != _genColVec.n_rows) {\n          return;\n        }\n\n        if(_genMat.n_cols != _genColVec.n_cols) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatElemDivide() ... \";\n\n        Mat<uword> expected = _genMat < _genColVec;\n        save<uword>(\"Mat.strictLessThan\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n  };\n}\n", "meta": {"hexsha": "3dc01f8094a94f7b75e91082b75db861d29bbfdb", "size": 8430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/cpp/src/ExpectedGenMatGenColVec.cpp", "max_stars_repo_name": "sebiniemann/ArmadilloJava", "max_stars_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-08-05T14:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T17:46:54.000Z", "max_issues_repo_path": "src/test/cpp/src/ExpectedGenMatGenColVec.cpp", "max_issues_repo_name": "sebiniemann/ArmadilloJava", "max_issues_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2019-10-20T21:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T21:53:47.000Z", "max_forks_repo_path": "src/test/cpp/src/ExpectedGenMatGenColVec.cpp", "max_forks_repo_name": "sebiniemann/ArmadilloJava", "max_forks_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T17:01:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T18:45:14.000Z", "avg_line_length": 25.8588957055, "max_line_length": 80, "alphanum_fraction": 0.5322657177, "num_tokens": 2045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5127144629549891}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and\n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2003-2008 Matthias Christian Schabel\n// Copyright (C) 2008 Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n/**\n\\file\n\n\\brief heterogeneous_unit.cpp\n\n\\details\nTest heterogeneous units and quantities.\n\nOutput:\n@verbatim\n\n//[heterogeneous_unit_output_1\n1.5 m\n1 g\n1.5 m g\n1.5 m g^-1\n\n1 N\n1 kg s^-2\n\n1 cm kg s^-2\n1 cm m^-1 kg s^-2\n//]\n\n//[heterogeneous_unit_output_2\n1.5 cm m\n0.015 m^2\n//]\n\n@endverbatim\n**/\n\n#define MCS_USE_DEMANGLING\n//#define MCS_USE_BOOST_REGEX_DEMANGLING\n\n#include <iostream>\n\n#include <boost/units/io.hpp>\n#include <boost/units/pow.hpp>\n#include <boost/units/detail/utility.hpp>\n#include <boost/units/systems/cgs.hpp>\n#include <boost/units/systems/si.hpp>\n#include <boost/units/systems/si/io.hpp>\n\nusing namespace boost::units;\n\nint main()\n{\n    //[heterogeneous_unit_snippet_1\n    quantity<si::length>        L(1.5*si::meter);\n    quantity<cgs::mass>         M(1.0*cgs::gram);\n\n    std::cout << L << std::endl\n              << M << std::endl\n              << L*M << std::endl\n              << L/M << std::endl\n              << std::endl;\n\n    std::cout << 1.0*si::meter*si::kilogram/pow<2>(si::second) << std::endl\n              << 1.0*si::meter*si::kilogram/pow<2>(si::second)/si::meter\n              << std::endl << std::endl;\n\n    std::cout << 1.0*cgs::centimeter*si::kilogram/pow<2>(si::second) << std::endl\n              << 1.0*cgs::centimeter*si::kilogram/pow<2>(si::second)/si::meter\n              << std::endl << std::endl;\n    //]\n\n    //[heterogeneous_unit_snippet_2\n    quantity<si::area>      A(1.5*si::meter*cgs::centimeter);\n\n    std::cout << 1.5*si::meter*cgs::centimeter << std::endl\n              << A << std::endl\n              << std::endl;\n    //]\n\n    return 0;\n}\n", "meta": {"hexsha": "91088c2e35e4aa9b0091482485dbd1a44fbfa054", "size": 1971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/units/example/heterogeneous_unit.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/units/example/heterogeneous_unit.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/units/example/heterogeneous_unit.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": 22.3977272727, "max_line_length": 81, "alphanum_fraction": 0.6139015728, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5127144595091442}}
{"text": "//   Copyright 2018 Dhruvesh Nikhilkumar Patel\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/numeric/ublas/matrix.hpp>\n#include \"../include/Polynomial.ipp\"\n#include <gmpxx.h>\n#include <iostream>\nint main()\n{\n   using namespace boost::numeric::ublas;\n   using coefT = mpz_class;\n   using entryT= Polynomial<coefT>;\n   entryT p1 {1,2,3};\n   entryT p2 {4,5,6};\n   entryT p3 {1};\n   entryT p4 {7,8,9,10};\n   matrix<entryT> m (2,2);\n   m(0,0)=p1;\n   m(0,1)=p2;\n   m(1,0)=p3;\n   m(1,1)=p4;\n   std::cout<<\"m(0,0)= \"<<m(0,0)<<std::endl;\n   std::cout<<\"m(0,1)= \"<<m(0,1)<<std::endl;\n   std::cout<<\"m(1,0)= \"<<m(1,0)<<std::endl;\n   std::cout<<\"m(1,1)= \"<<m(1,1)<<std::endl;\n\n   matrix<entryT> m2 (2,2);\n   m2 = prod(m,m);\n   std::cout<<\"m2=m*m\"<<std::endl;\n   std::cout<<\"m2(0,0)= \"<<m2(0,0)<<std::endl;\n   std::cout<<\"m2(0,1)= \"<<m2(0,1)<<std::endl;\n   std::cout<<\"m2(1,0)= \"<<m2(1,0)<<std::endl;\n   std::cout<<\"m2(1,1)= \"<<m2(1,1)<<std::endl;\n\n\n   return 0;\n}\n", "meta": {"hexsha": "24a7b4379ff76076f45529808ad9e2be4286805c", "size": 1501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/boost_matrix.cpp", "max_stars_repo_name": "dhruvdcoder/poly-metic", "max_stars_repo_head_hexsha": "c8ec0ba30dd052c6b41a0cdeb58318d063cf9eac", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-14T16:16:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T16:16:12.000Z", "max_issues_repo_path": "src/boost_matrix.cpp", "max_issues_repo_name": "dhruvdcoder/poly-metic", "max_issues_repo_head_hexsha": "c8ec0ba30dd052c6b41a0cdeb58318d063cf9eac", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-09-02T04:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-09T20:14:16.000Z", "max_forks_repo_path": "src/boost_matrix.cpp", "max_forks_repo_name": "dhruvdcoder/poly-metic", "max_forks_repo_head_hexsha": "c8ec0ba30dd052c6b41a0cdeb58318d063cf9eac", "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.6326530612, "max_line_length": 77, "alphanum_fraction": 0.6129247169, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5127144560662209}}
{"text": "/**\n * @file   unitary.cc\n * @date   12/2018\n * @author Imran Ashraf\n * @author Anneriet Krol\n * @brief  unitary matrix (decomposition) implementation\n */\n\n#include <unitary.h>\n\n#ifndef WITHOUT_UNITARY_DECOMPOSITION\n#include <Eigen/MatrixFunctions>\n#include <src/misc/lapacke.h>\n#endif\n\ntypedef unsigned int uint;\n\n#include <chrono>\n\nnamespace ql\n{\n\nunitary::unitary() : name(\"\"), is_decomposed(false) {}\n\nunitary::unitary(std::string name, std::vector<std::complex<double>> array) :\nname(name), array(array), is_decomposed(false) {}\n\ndouble unitary::size() {\n    // JvS: Note that the original unitary::size() used\n    // Eigen::Matrix::size() if the array is empty. However, if the array\n    // is empty, _matrix is never initialized beyond its default ctor,\n    // which \"allocates\" a 0x0 matrix, and is thus size 0, exactly what\n    // array.size() would return.\n    // Don't get me started about why this returns a double.\n    return (double) array.size();\n}\n\n#ifdef WITHOUT_UNITARY_DECOMPOSITION\n\nvoid unitary::decompose() {\n    throw std::runtime_error(\"unitary decomposition was explicitly disabled in this build!\");\n}\n\n#else\n\n// JvS: this was originally the class \"unitary\" itself, but compile times of\n// Eigen are so excessive that I moved it into its own compile unit and\n// provided a wrapper instead. It doesn't actually NEED to be wrapped like\n// this, because the Eigen::Matrix<...> member is actually only used within\n// the scope of a single method (calling other methods), but I'm not touching\n// this code.\nclass UnitaryDecomposer\n{\nprivate:\n    Eigen::Matrix<std::complex<double>, Eigen::Dynamic, Eigen::Dynamic> _matrix;\n\npublic:\n    std::string name;\n    std::vector<std::complex<double>> array;\n    std::vector<std::complex<double>> SU;\n    double delta;\n    double alpha;\n    double beta;\n    double gamma;\n    bool is_decomposed;\n    std::vector<double> instructionlist;\n\n    typedef Eigen::Matrix<std::complex<double>, Eigen::Dynamic, Eigen::Dynamic> complex_matrix ;\n\n    UnitaryDecomposer() : name(\"\"), is_decomposed(false) {}\n\n    UnitaryDecomposer(std::string name, std::vector<std::complex<double>> array) : \n            name(name), array(array), is_decomposed(false)\n    {\n        DOUT(\"constructing unitary: \" << name \n                  << \", containing: \" << array.size() << \" elements\");\n    }\n\n    double size()\n    {\n        if(!array.empty())\n            return (double) array.size();\n        else\n            return (double) _matrix.size();\n    }\n\n    complex_matrix getMatrix()\n    {\n        if (!array.empty())\n        {\n            int matrix_size = (int)std::pow(array.size(), 0.5);\n\n            Eigen::Map<complex_matrix> matrix(array.data(), matrix_size, matrix_size);\n            _matrix = matrix.transpose();\n        }\n        return _matrix;\n    }\n\n    void decompose()\n    {\n        DOUT(\"decomposing Unitary: \" << name);\n\n        getMatrix();\n        int matrix_size = _matrix.rows();\n        \n        // compute the number of qubits: length of array is collumns*rows, so log2(sqrt(array.size))\n        int numberofbits = uint64_log2(matrix_size);\n\n        Eigen::MatrixXcd identity = Eigen::MatrixXcd::Identity(matrix_size, matrix_size);\n        Eigen::MatrixXcd matmatadjoint = (_matrix.adjoint()*_matrix);\n        // very little accuracy because of tests using printed-from-matlab code that does not have many digits after the comma    \n        if( !matmatadjoint.isApprox(identity, 0.001))\n        {\n            //Throw an error\n            EOUT(\"Unitary \" << name <<\" is not a unitary matrix!\");\n\n            throw ql::exception(\"Error: Unitary '\"+ name+\"' is not a unitary matrix. Cannot be decomposed!\" + to_string(matmatadjoint), false);\n        }\n        // initialize the general M^k lookuptable\n        genMk();\n\n        decomp_function(_matrix, numberofbits); //needed because the matrix is read in columnmajor\n \n        DOUT(\"Done decomposing\");\n        is_decomposed = true;\n    }\n\n    std::string to_string(complex_matrix m, std::string vector_prefix = \"\",\n                            std::string elem_sep = \", \")\n    {\n        std::ostringstream ss;\n        ss << m << \"\\n\";\n        return ss.str();\n    }\n\n\n    // std::chrono::duration<double> CSD_time;\n    // std::chrono::duration<double> CSD_time2;\n    // std::chrono::duration<double> CSD_time3;\n    // std::chrono::duration<double> zyz_time;\n    // std::chrono::duration<double> multiplexing_time;\n    // std::chrono::duration<double> demultiplexing_time;\n\n    void decomp_function(const Eigen::Ref<const complex_matrix>& matrix, int numberofbits)\n    {          \n        DOUT(\"decomp_function: \\n\" << to_string(matrix));         \n        if(numberofbits == 1)\n        {\n            zyz_decomp(matrix);\n        }\n        else\n        {\n            int n = matrix.rows()/2;\n\n            complex_matrix V(n,n);\n            complex_matrix W(n,n);\n            Eigen::VectorXcd D(n);\n            // if q2 is zero, the whole thing is a demultiplexing problem instead of full CSD\n            if(matrix.bottomLeftCorner(n,n).isZero(10e-14) && matrix.topRightCorner(n,n).isZero(10e-14))\n            {\n                DOUT(\"Optimization: q2 is zero, only demultiplexing will be performed.\");\n                instructionlist.push_back(200.0);\n                if(matrix.topLeftCorner(n, n).isApprox(matrix.bottomRightCorner(n,n),10e-4))\n                {\n                    DOUT(\"Optimization: Unitaries are equal, skip one step in the recursion for unitaries of size: \" << n << \" They are both: \" << matrix.topLeftCorner(n, n));\n                    instructionlist.push_back(300.0);\n                    decomp_function(matrix.topLeftCorner(n, n), numberofbits-1);\n                }\n                else\n                {\n                    demultiplexing(matrix.topLeftCorner(n, n), matrix.bottomRightCorner(n,n), V, D, W, numberofbits-1);\n\n                    decomp_function(W, numberofbits-1);\n                    multicontrolledZ(D, D.rows());\n                    decomp_function(V, numberofbits-1);\n                }\n            }\n            // Check to see if it the kronecker product of a bigger matrix and the identity matrix.\n            // By checking if the first row is equal to the second row one over, and if thelast two rows are equal \n            // Which means the last qubit is not affected by this gate\n            else if (matrix(Eigen::seqN(0, n, 2), Eigen::seqN(1, n, 2)).isZero()  && matrix(Eigen::seqN(1, n, 2), Eigen::seqN(0, n, 2)).isZero()  && matrix.block(0,0,1,2*n-1) == matrix.block(1,1,1,2*n-1) &&  matrix.block(2*n-2,0,1,2*n-1) ==  matrix.block(2*n-1,1,1,2*n-1))\n            {\n                DOUT(\"Optimization: last qubit is not affected, skip one step in the recursion.\");\n                // Code for last qubit not affected\n                instructionlist.push_back(100.0);\n                decomp_function(matrix(Eigen::seqN(0, n, 2), Eigen::seqN(0, n, 2)), numberofbits-1);\n\n            }\n            else\n            {\n            complex_matrix ss(n,n);\n            complex_matrix L0(n,n);\n            complex_matrix L1(n,n);\n            complex_matrix R0(n,n);\n            complex_matrix R1(n,n);\n            // auto start = std::chrono::steady_clock::now();\n            CSD(matrix, L0, L1, R0, R1, ss);\n            // CSD_time += (std::chrono::steady_clock::now() - start);\n            demultiplexing(R0, R1, V, D, W, numberofbits-1);\n            decomp_function(W, numberofbits-1);\n            multicontrolledZ(D, D.rows());\n            decomp_function(V, numberofbits-1);\n\n            multicontrolledY(ss.diagonal(), n);\n\n            demultiplexing(L0, L1, V, D, W, numberofbits-1);\n            decomp_function(W, numberofbits-1);\n            multicontrolledZ(D, D.rows());\n            decomp_function(V, numberofbits-1);\n            }\n        }\n    }\n\n    void CSD(const Eigen::Ref<const complex_matrix>& U, Eigen::Ref<complex_matrix> u1, Eigen::Ref<complex_matrix> u2, Eigen::Ref<complex_matrix> v1, Eigen::Ref<complex_matrix> v2, Eigen::Ref<complex_matrix> s)\n    {\n        // auto start = std::chrono::steady_clock::now();        \n        //Cosine sine decomposition\n        // U = [q1, U01] = [u1    ][c  s][v1  ]\n        //     [q2, U11] = [    u2][-s c][   v2]\n        int n = U.rows();\n        // complex_matrix c(n,n); // c matrix is not needed for the higher level\n        // complex_matrix q1 = U.topLeftCorner(n/2,m/2);\n\n        Eigen::BDCSVD<complex_matrix> svd(n/2,n/2);\n        svd.compute(U.topLeftCorner(n/2,n/2), Eigen::ComputeThinU | Eigen::ComputeThinV); // possible because it's square anyway\n        \n\n        // thinCSD: q1 = u1*c*v1.adjoint()\n        //          q2 = u2*s*v1.adjoint()\n        int p = n/2;\n        // complex_matrix z = Eigen::MatrixXd::Identity(p, p).colwise().reverse();\n        complex_matrix c(svd.singularValues().reverse().asDiagonal());\n        u1.noalias() = svd.matrixU().rowwise().reverse();\n        v1.noalias() = svd.matrixV().rowwise().reverse(); // Same v as in matlab: u*s*v.adjoint() = q1\n\n        complex_matrix q2 = U.bottomLeftCorner(p,p)*v1;      \n\n        int k = 0;\n        for(int j = 1; j < p; j++)\n        {\n            if(c(j,j).real() <= 0.70710678119)\n            {\n                k = j;\n            }\n        }\n        //complex_matrix b = q2.block( 0,0, p, k+1);\n\n        Eigen::HouseholderQR<complex_matrix> qr(p,k+1);\n        qr.compute(q2.block( 0,0, p, k+1));\n        u2 = qr.householderQ();\n        s.noalias() = u2.adjoint()*q2;\n        if(k < p-1)\n        {\n            DOUT(\"k is smaller than size of q1 = \"<< p << \", adjustments will be made, k = \" << k);\n            k = k+1;\n            Eigen::BDCSVD<complex_matrix> svd2(p-k, p-k);\n            svd2.compute(s.block(k, k, p-k, p-k), Eigen::ComputeThinU | Eigen::ComputeThinV);\n            s.block(k, k, p-k, p-k) = svd2.singularValues().asDiagonal();\n            c.block(0,k, p,p-k) = c.block(0,k, p,p-k)*svd2.matrixV();\n            u2.block(0,k, p,p-k) = u2.block(0,k, p,p-k)*svd2.matrixU();\n            v1.block(0,k, p,p-k) = v1.block(0,k, p,p-k)*svd2.matrixV();\n            \n            Eigen::HouseholderQR<complex_matrix> qr2(p-k, p-k);\n\n            qr2.compute(c.block(k,k, p-k,p-k));\n            c.block(k,k,p-k,p-k) = qr2.matrixQR().triangularView<Eigen::Upper>();\n            u1.block(0,k, p,p-k) = u1.block(0,k, p,p-k)*qr2.householderQ(); \n        }\n        // CSD_time2 += (std::chrono::steady_clock::now() - start);\n\n        // auto start2 = std::chrono::steady_clock::now();\n\n\n\n        std::vector<int> c_ind;\n        std::vector<int> s_ind;\n        for(int j = 0; j < p; j++)\n        {\n            if(c(j,j).real() < 0)\n            {\n                c_ind.push_back(j);\n            }\n            if(s(j,j).real() < 0)\n            {\n                s_ind.push_back(j);\n            } \n        }\n\n        c(c_ind,c_ind) = -c(c_ind,c_ind);\n        u1(Eigen::all, c_ind) = -u1(Eigen::all, c_ind);\n\n        //s.diagonal()(s_ind) = -s.diagonal()(s_ind);\n        s(s_ind,s_ind) = -s(s_ind,s_ind);\n        u2(Eigen::all, s_ind) = -u2(Eigen::all, s_ind);\n\n        if(!U.topLeftCorner(p,p).isApprox(u1*c*v1.adjoint(), 10e-8) || !U.bottomLeftCorner(p,p).isApprox(u2*s*v1.adjoint(), 10e-8))\n        {\n            if(U.topLeftCorner(p,p).isApprox(u1*c*v1.adjoint(), 10e-8))\n            {\n                DOUT(\"q1 is correct\");\n            }\n            else\n            {\n                DOUT(\"q1 is not correct! (is not usually an issue\");\n                DOUT(\"q1: \\n\" << U.topLeftCorner(p,p));\n                DOUT(\"reconstructed q1: \\n\" << u1*c*v1.adjoint());\n\n            }\n            if(U.bottomLeftCorner(p,p).isApprox(u2*s*v1.adjoint(), 10e-8))\n            {\n                DOUT(\"q2 is correct\");\n            }\n            else\n            {\n                DOUT(\"q2 is not correct! (is not usually an issue)\");\n                DOUT(\"q2: \" << U.bottomLeftCorner(p,p));\n                DOUT(\"reconstructed q2: \" << u2*s*v1.adjoint());\n            }\n        }\n        v1.adjointInPlace(); // Use this instead of = v1.adjoint (to avoid aliasing issues)\n        s = -s;\n\n        complex_matrix tmp_s = u1.adjoint()*U.topRightCorner(p,p);\n        complex_matrix tmp_c = u2.adjoint()*U.bottomRightCorner(p,p);\n\n        // std::vector<int> c_ind_row;\n        // std::vector<int> s_ind_row;\n        for(int i = 0; i < p; i++)\n        {\n            if(std::abs(s(i,i)) > std::abs(c(i,i)))\n            {\n                // std::vector<int> s_ind_row;\n                v2.row(i).noalias() = tmp_s.row(i)/s(i,i);                \n            }\n            else\n            {\n                // c_ind_row.push_back(i);\n                v2.row(i).noalias() = tmp_c.row(i)/c(i,i);\n            }\n        }\n        \n\n        // v2(s_ind_row, Eigen::all) = tmp_s(s_ind_row, Eigen::all).rowwise() / s(s_ind_row, s_ind_row).array();\n        // v2(c_ind_row, Eigen::all) = tmp_c(c_ind_row, Eigen::all).rowwise() / c(c_ind_row, c_ind_row).array();\n        // U = [q1, U01] = [u1    ][c  s][v1  ]\n        //     [q2, U11] = [    u2][-s c][   v2]\n    \n        complex_matrix tmp(n,n);\n        tmp.topLeftCorner(p,p) = u1*c*v1;\n        tmp.bottomLeftCorner(p,p) = -u2*s*v1;\n        tmp.topRightCorner(p,p) = u1*s*v2;\n        tmp.bottomRightCorner(p,p) = u2*c*v2;\n        // Just to see if it kinda matches\n        if(!tmp.isApprox(U, 10e-2))\n        {\n            throw ql::exception(\"CSD of unitary '\"+ name+\"' is wrong! Failed at matrix: \\n\"+to_string(tmp) + \"\\nwhich should be: \\n\" + to_string(U), false);\n        }\n            // CSD_time3 += (std::chrono::steady_clock::now() - start2);\n\n    }\n\n\n    void zyz_decomp(const Eigen::Ref<const complex_matrix>& matrix)\n    {\n        // auto start = std::chrono::steady_clock::now();\n\n        ql::complex_t det = matrix.determinant();// matrix(0,0)*matrix(1,1)-matrix(1,0)*matrix(0,1);\n\n        double delta = atan2(det.imag(), det.real())/matrix.rows();\n        std::complex<double> A = exp(std::complex<double>(0,-1)*delta)*matrix(0,0);\n        std::complex<double> B = exp(std::complex<double>(0,-1)*delta)*matrix(0,1); //to comply with the other y-gate definition\n        \n        double sw = sqrt(pow((double) B.imag(),2) + pow((double) B.real(),2) + pow((double) A.imag(),2));\n        double wx = 0;\n        double wy = 0;\n        double wz = 0;\n\n        if(sw > 0)\n        {\n        wx = B.imag()/sw;\n        wy = B.real()/sw;\n        wz = A.imag()/sw;\n        }\n\n\n        double t1 = atan2(A.imag(),A.real());\n        double t2 = atan2(B.imag(), B.real());\n        alpha = t1+t2;\n        gamma = t1-t2;\n        beta = 2*atan2(sw*sqrt(pow((double) wx,2)+pow((double) wy,2)),sqrt(pow((double) A.real(),2)+pow((wz*sw),2)));\n        instructionlist.push_back(-gamma);\n        instructionlist.push_back(-beta);\n        instructionlist.push_back(-alpha);\n        // zyz_time += (std::chrono::steady_clock::now() - start);\n    }\n\n    void demultiplexing(const Eigen::Ref<const complex_matrix> &U1, const Eigen::Ref<const complex_matrix> &U2,  Eigen::Ref<complex_matrix> V,  Eigen::Ref<Eigen::VectorXcd> D,  Eigen::Ref<complex_matrix> W, int numberofcontrolbits)\n    {\n        // [U1 0 ]  = [V 0][D 0 ][W 0]\n        // [0  U2]    [0 V][0 D*][0 W]\n        // auto start = std::chrono::steady_clock::now(); \n        complex_matrix check = U1*U2.adjoint();\n        // complex_matrix D;\n        // complex_matrix V;\n        // complex_matrix W;\n        if(check == check.adjoint())\n        {\n            IOUT(\"Demultiplexing matrix is self-adjoint()\");\n            Eigen::SelfAdjointEigenSolver<Eigen::MatrixXcd> eigslv(check);\n            D.noalias() = ((complex_matrix) eigslv.eigenvalues()).cwiseSqrt();\n            V.noalias() = eigslv.eigenvectors();\n            W.noalias() = D.asDiagonal()*V.adjoint()*U2;\n        }\n        else\n        {\n            if (numberofcontrolbits < 5) //schur is faster for small matrices\n            {\n                Eigen::ComplexSchur<complex_matrix> decomposition(check);\n                D.noalias() = decomposition.matrixT().diagonal().cwiseSqrt();\n                V.noalias() = decomposition.matrixU();\n                W.noalias() = D.asDiagonal() * V.adjoint() * U2;\n            }\n            else\n            {\n                Eigen::ComplexEigenSolver<complex_matrix> decomposition(check);\n                D.noalias() = decomposition.eigenvalues().cwiseSqrt();\n                V.noalias() = decomposition.eigenvectors();\n                W.noalias() = D.asDiagonal() * V.adjoint() * U2;\n            }\n        }\n    \n        // demultiplexing_time += (std::chrono::steady_clock::now() - start);\n        if(!(V*V.adjoint()).isApprox(Eigen::MatrixXd::Identity(V.rows(), V.rows()), 10e-3))\n        {\n            DOUT(\"Eigenvalue decomposition incorrect: V is not unitary, adjustments will be made\");\n            Eigen::BDCSVD<complex_matrix> svd3(V.block(0,0,V.rows(),2), Eigen::ComputeFullU);\n            V.block(0,0,V.rows(),2) = svd3.matrixU();\n            svd3.compute(V(Eigen::all,Eigen::seq(Eigen::last-1,Eigen::last)), Eigen::ComputeFullU);\n            V(Eigen::all,Eigen::seq(Eigen::last-1,Eigen::last)) = svd3.matrixU();\n             \n        }\n\n\n        complex_matrix Dtemp = D.asDiagonal();\n        if(!U1.isApprox(V*Dtemp*W, 10e-2) || !U2.isApprox(V*Dtemp.adjoint()*W, 10e-2))\n        {\n            EOUT(\"Demultiplexing not correct!\");\n            throw ql::exception(\"Demultiplexing of unitary '\"+ name+\"' not correct! Failed at matrix U1: \\n\"+to_string(U1)+ \"and matrix U2: \\n\" +to_string(U2) + \"\\nwhile they are: \\n\" + to_string(V*D.asDiagonal()*W) + \"\\nand \\n\" + to_string(V*D.conjugate().asDiagonal()*W), false);\n        }\n\n\n        \n    }\n\n\n    std::vector<Eigen::MatrixXd> genMk_lookuptable;\n\n    // returns M^k = (-1)^(b_(i-1)*g_(i-1)), where * is bitwise inner product, g = binary gray code, b = binary code.\n    void genMk()\n    {\n        int numberqubits = uint64_log2(_matrix.rows());\n        for(int n = 1; n <= numberqubits; n++)\n        {\n            int size=1<<n;\n            Eigen::MatrixXd Mk(size,size);\n            for(int i = 0; i < size; i++)\n            {\n                for(int j = 0; j < size ;j++)\n                {\n                    Mk(i,j) =std::pow(-1, bitParity(i&(j^(j>>1))));\n                }\n            }\n        genMk_lookuptable.push_back(Mk);\n        }\n        \n        // return genMk_lookuptable[numberqubits-1];\n    }\n\n    // source: https://stackoverflow.com/questions/994593/how-to-do-an-integer-log2-in-c user Todd Lehman\n    int uint64_log2(uint64_t n)\n    {\n    #define S(k) if (n >= (UINT64_C(1) << k)) { i += k; n >>= k; }\n\n    int i = -(n == 0); S(32); S(16); S(8); S(4); S(2); S(1); return i;\n\n    #undef S\n    }\n\n    int bitParity(int i)\n    {\n        if (i < 2 << 16)\n        {\n            i = (i >> 16) ^ i;\n            i = (i >> 8) ^ i;\n            i = (i >> 4) ^ i;\n            i = (i >> 2) ^ i;\n            i = (i >> 1) ^ i;\n            return i % 2;\n        }\n        else\n        {\n            throw ql::exception(\"Bit parity number too big!\", false);\n        }\n    }\n\n    void multicontrolledY(const Eigen::Ref<const Eigen::VectorXcd> &ss, int halfthesizeofthematrix)\n    {\n        // auto start = std::chrono::steady_clock::now();\n        Eigen::VectorXd temp =  2*Eigen::asin(ss.array()).real();\n        Eigen::CompleteOrthogonalDecomposition<Eigen::MatrixXd> dec(genMk_lookuptable[uint64_log2(halfthesizeofthematrix)-1]);\n        Eigen::VectorXd tr = dec.solve(temp);\n        // Check is very approximate to account for low-precision input matrices\n        if(!temp.isApprox(genMk_lookuptable[uint64_log2(halfthesizeofthematrix)-1]*tr, 10e-2))\n        {\n                EOUT(\"Multicontrolled Y not correct!\");\n                throw ql::exception(\"Demultiplexing of unitary '\"+ name+\"' not correct! Failed at demultiplexing of matrix ss: \\n\"  + to_string(ss), false);\n        }\n\n        instructionlist.insert(instructionlist.end(), &tr[0], &tr[halfthesizeofthematrix]);\n        // multiplexing_time += std::chrono::steady_clock::now() - start;\n    }\n\n    void multicontrolledZ(const Eigen::Ref<const Eigen::VectorXcd> &D, int halfthesizeofthematrix)\n    {\n        // auto start = std::chrono::steady_clock::now();\n        \n        Eigen::VectorXd temp =  (std::complex<double>(0,-2)*Eigen::log(D.array())).real();\n        Eigen::CompleteOrthogonalDecomposition<Eigen::MatrixXd> dec(genMk_lookuptable[uint64_log2(halfthesizeofthematrix)-1]);\n        Eigen::VectorXd tr = dec.solve(temp);\n        // Check is very approximate to account for low-precision input matrices\n        if(!temp.isApprox(genMk_lookuptable[uint64_log2(halfthesizeofthematrix)-1]*tr, 10e-2))\n        {\n                EOUT(\"Multicontrolled Z not correct!\");\n                throw ql::exception(\"Demultiplexing of unitary '\"+ name+\"' not correct! Failed at demultiplexing of matrix D: \\n\"+ to_string(D), false);\n        }\n        \n\n        instructionlist.insert(instructionlist.end(), &tr[0], &tr[halfthesizeofthematrix]);\n        // multiplexing_time += std::chrono::steady_clock::now() - start;\n\n    }\n    ~UnitaryDecomposer()\n    {\n        // destroy unitary\n        DOUT(\"destructing unitary: \" << name);\n    }\n};\n\nvoid unitary::decompose() {\n    UnitaryDecomposer decomposer(name, array);\n    decomposer.decompose();\n    SU = decomposer.SU;\n    alpha = decomposer.alpha;\n    beta = decomposer.beta;\n    gamma = decomposer.gamma;\n    is_decomposed = decomposer.is_decomposed;\n    instructionlist = decomposer.instructionlist;\n}\n\n#endif\n\n}\n\n", "meta": {"hexsha": "413907a730b40f5f1aca30f85185c568eed76af6", "size": 21452, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/unitary.cc", "max_stars_repo_name": "jvanstraten/OpenQL", "max_stars_repo_head_hexsha": "4b7dea35386ddc452610de29bc2c0d7abaa04c33", "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/unitary.cc", "max_issues_repo_name": "jvanstraten/OpenQL", "max_issues_repo_head_hexsha": "4b7dea35386ddc452610de29bc2c0d7abaa04c33", "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/unitary.cc", "max_forks_repo_name": "jvanstraten/OpenQL", "max_forks_repo_head_hexsha": "4b7dea35386ddc452610de29bc2c0d7abaa04c33", "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.0354609929, "max_line_length": 281, "alphanum_fraction": 0.5539809808, "num_tokens": 5902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5125829304830477}}
{"text": "#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <complex>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/algorithm/minmax.hpp>\n\n#include \"../include/TriMesh.h\"\n#include \"../include/utils.h\"\n#include \"../include/lagrange.h\"\n#include \"../include/geometry.h\"\n#include \"../include/ConstructCurveMesh.h\"\n#include \"../include/GetQuadraturePointsWeight2D.h\"\n#include \"../include/solver.h\"\n#include \"../include/euler.h\"\n#include \"../include/Param.h\"\n#include \"../include/Collective.h\"\n#include \"../include/InvertMatrix.h\"\n\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n    Param param;\n    // Set up the param struct\n    param = ReadParamIn(string(argv[1]));\n    TriMesh mesh(param.mesh_file);\n    // Testing Calculate Residaul\n    int p = param.order;\n    int q = param.order_geo;\n    int Np = int((p + 1) * (p + 2) / 2);\n    TriMesh curved_mesh = mesh;\n    string boundary_name=\"bottom\";\n    ConstructCurveMesh(mesh, curved_mesh, geometry::BumpFunction, boundary_name, q);\n\n    ResData resdata_postproc;\n    if (p == 0)\n    {\n        solver::CalcResData(curved_mesh, 1, resdata_postproc);\n    }else\n    {\n        solver::CalcResData(curved_mesh, p, resdata_postproc);\n    }\n\n    int Np_solution;\n    if (p == 0)\n        Np_solution = 3;\n    else\n        Np_solution = Np;\n    ublas::vector<ublas::matrix<double> > Nodes(curved_mesh.E.size(), ublas::matrix<double>(Np_solution, 2, 0.0));\n    ublas::vector<ublas::matrix<double> > State_on_Nodes(curved_mesh.E.size(), ublas::matrix<double>(Np_solution, 4, 0.0));\n\n    ifstream file_nodes, file_state;\n    file_nodes.open(\"nodes.dat\");\n    file_state.open(\"states.dat\");\n    for (int ielem = 0; ielem < curved_mesh.E.size(); ielem++)\n    {\n        for (int ip = 0; ip < Np_solution; ip++)\n        {\n            double x, y, s0, s1, s2, s3;\n            char temp;\n            file_nodes  >> x  >> y;\n            file_state  >> s0 >> s1 >> s2 >> s3;\n            Nodes(ielem)(ip, 0) = x; Nodes(ielem)(ip, 1) = y;\n            State_on_Nodes(ielem)(ip, 0) = s0; State_on_Nodes(ielem)(ip, 1) = s1;\n            State_on_Nodes(ielem)(ip, 2) = s2; State_on_Nodes(ielem)(ip, 3) = s3;\n        }\n    }\n    file_nodes.close();\n    file_state.close();\n    param.h = 0.0625;\n    double err_entropy, coeff_lift, coeff_drag;\n    std::vector<std::vector<double> > p_coeff_dist;\n    solver::CalcScalarOutputs(curved_mesh, resdata_postproc, State_on_Nodes, Nodes, param,\n                                    err_entropy, coeff_lift, coeff_drag, p_coeff_dist);\n    cout.setf(ios::scientific, ios::floatfield);\n    std::cout << setprecision(8) << err_entropy << ' ' << coeff_lift << ' ' << coeff_drag << endl;\n    ofstream file_pdist;\n    file_pdist.open(\"pressure_distribution.dat\");\n    for (int i = 0; i < p_coeff_dist.size(); i++)\n    {\n        cout.setf(ios::scientific, ios::floatfield);\n        file_pdist  << setprecision(10) << p_coeff_dist[i][0] << ' ' << p_coeff_dist[i][1] << std::endl;\n    }\n    file_pdist.close();\n    return 0;\n}\n", "meta": {"hexsha": "b1ec4bdf47c64712ffbefaf6df0d8b0c477a8b4e", "size": 3051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PostProc.cpp", "max_stars_repo_name": "xtwang1996/DG_Euler_2D", "max_stars_repo_head_hexsha": "1218ef7af9a85db48c84386e0fc396d09286be33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PostProc.cpp", "max_issues_repo_name": "xtwang1996/DG_Euler_2D", "max_issues_repo_head_hexsha": "1218ef7af9a85db48c84386e0fc396d09286be33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PostProc.cpp", "max_forks_repo_name": "xtwang1996/DG_Euler_2D", "max_forks_repo_head_hexsha": "1218ef7af9a85db48c84386e0fc396d09286be33", "max_forks_repo_licenses": ["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.2808988764, "max_line_length": 123, "alphanum_fraction": 0.624057686, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5125678433714372}}
{"text": "#include <mex.h>\n#include <Eigen/Core>\n#include \"splineGeneration.h\"\n#include \"drakeMexUtil.h\"\n#include <iostream>\n#include <limits>\n\nusing namespace std;\nusing namespace Eigen;\n\nconst int GRID_STEPS = 10;\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n  string usage = \"[coefs, ts, objective_value] = nWaypointCubicSplineFreeKnotTimesmex.cpp(t0, tf, xs, xd0, xdf)\";\n  if (nrhs != 5)\n    mexErrMsgIdAndTxt(\"Drake:nWaypointCubicSplineFreeKnotTimesmex.cpp:WrongNumberOfInputs\", usage.c_str());\n  if (nlhs < 2 || nlhs > 3)\n    mexErrMsgIdAndTxt(\"Drake:nWaypointCubicSplineFreeKnotTimesmex.cpp:WrongNumberOfOutputs\", usage.c_str());\n\n  double t0 = mxGetPrSafe(prhs[0])[0];\n  double tf = mxGetPrSafe(prhs[1])[0];\n  MatrixXd xs = matlabToEigen<Dynamic, Dynamic>(prhs[2]);\n  auto xd0 = matlabToEigen<Dynamic, 1>(prhs[3]);\n  auto xdf = matlabToEigen<Dynamic, 1>(prhs[4]);\n\n  mwSize ndof = static_cast<mwSize>(xs.rows());\n  mwSize num_segments = static_cast<mwSize>(xs.cols()) - 1;\n  mwSize num_knots = num_segments - 1;\n  if (num_knots >= 3)\n    mexWarnMsgTxt(\"More knots than two is likely to be super slow in a grid search!\\n\");\n  if (num_knots <= 0)\n    mexErrMsgIdAndTxt(\"Drake:nWaypointCubicSplineFreeKnotTimesmex.cpp:NotEnoughKnotsToJustifyThisFunction\", usage.c_str());\n  mwSize num_coeffs_per_segment = 4;\n  mwSize dims[] = { ndof, num_segments, num_coeffs_per_segment };\n  plhs[0] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);\n\n  std::vector<double> segment_times;\n  segment_times.resize(static_cast<size_t>(num_segments) + 1);\n  segment_times[0] = t0;\n  segment_times[static_cast<size_t>(num_segments)] = tf;\n  std::vector<double> best_segment_times = segment_times;\n  double t_step = (tf - t0) / GRID_STEPS;\n  double min_objective_value = numeric_limits<double>::infinity();\n\n  // assemble the knot point locations for input to nWaypointCubicSpline\n  MatrixXd xi = xs.block(0, 1, ndof, num_knots);\n\n  if (GRID_STEPS <= num_knots) {\n    // If we have have too few grid steps, then by pigeonhole it's\n    // impossible to give each a unique time in our grid search.\n    mexErrMsgIdAndTxt(\"Drake:nWaypointCubicSplineFreeKnotTimesmex.cpp:TooManyKnotsForNumGridSteps\", usage.c_str());\n  }\n  std::vector<int> t_indices;\n  t_indices.reserve(num_knots);\n  for (int i = 0; i < num_knots; i++) {\n    t_indices.push_back(i + 1); // assume knot point won't be the same time as the initial state, or previous knot point\n  }\n\n  while (t_indices[0] < GRID_STEPS - num_knots + 1) {\n    for (int i = 0; i < num_knots; i++)\n      segment_times[i + 1] = t0 + t_indices[i] * t_step;\n\n    bool valid_solution = true;\n    double objective_value = 0.0;\n    for (int dof = 0; dof < ndof && valid_solution; dof++) {\n      try {\n        PiecewisePolynomial<double> spline = nWaypointCubicSpline(segment_times, xs(dof, 0), xd0[dof], xs(dof, num_segments), xdf[dof], xi.row(dof).transpose());\n        PiecewisePolynomial<double> acceleration_squared = spline.derivative(2);\n        acceleration_squared *= acceleration_squared;\n        PiecewisePolynomial<double> acceleration_squared_integral = acceleration_squared.integral();\n        objective_value += acceleration_squared_integral.scalarValue(spline.getEndTime()) - acceleration_squared_integral.scalarValue(spline.getStartTime());\n      } catch (ConstraintMatrixSingularError&) {\n        valid_solution = false;\n      }\n    }\n\n    if (valid_solution && objective_value < min_objective_value) {\n      best_segment_times = segment_times;\n      min_objective_value = objective_value;\n    }\n\n    // Advance grid search counter or terminate, counting from\n    // the latest t_index, and on overflow carrying to the\n    // next lowest t_index and resetting to the new value of that\n    // next lowest t_index. (since times must always be in order!)\n    t_indices[num_knots - 1]++;\n    // carry, except for the lowest place, which we \n    // use to detect doneness.\n    for (size_t i = num_knots - 1; i > 0; i--) {\n      if ((i == num_knots - 1 && t_indices[i] >= GRID_STEPS) || (i < num_knots - 1 && t_indices[i] >= t_indices[i + 1])) {\n        t_indices[i - 1]++;\n        t_indices[i] = t_indices[i - 1] + 1;\n      }\n    }\n  }\n\n  for (mwSize dof = 0; dof < ndof; dof++) {\n    PiecewisePolynomial<double> spline = nWaypointCubicSpline(best_segment_times, xs(dof, 0), xd0[dof], xs(dof, num_segments), xdf[dof], xi.row(dof).transpose());\n    for (mwSize segment_index = 0; segment_index < spline.getNumberOfSegments(); segment_index++) {\n      for (mwSize coefficient_index = 0; coefficient_index < num_coeffs_per_segment; coefficient_index++) {\n        mwSize sub[] = { dof, segment_index, num_coeffs_per_segment - coefficient_index - 1 }; // Matlab's reverse coefficient indexing...\n        *(mxGetPr(plhs[0]) + sub2ind(3, dims, sub)) = spline.getPolynomial(static_cast<int>(segment_index)).getCoefficients()[coefficient_index];\n      }\n    }\n  }\n  plhs[1] = stdVectorToMatlab(best_segment_times);\n\n  if (nlhs > 2)\n    plhs[2] = mxCreateDoubleScalar(min_objective_value);\n}\n", "meta": {"hexsha": "8d82c9a7fe2104f848fabf6a11a0e11e096a9882", "size": 5043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "drake/solvers/qpSpline/nWaypointCubicSplineFreeKnotTimesmex.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/solvers/qpSpline/nWaypointCubicSplineFreeKnotTimesmex.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/solvers/qpSpline/nWaypointCubicSplineFreeKnotTimesmex.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": 45.0267857143, "max_line_length": 162, "alphanum_fraction": 0.7003767599, "num_tokens": 1452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5125678433714371}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#define BOOST_UBLAS_NO_ELEMENT_PROXIES\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/triangular.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include \"print.hpp\"\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef std::complex<double> complex;\n    typedef ublas::vector<complex> vector;\n    typedef ublas::matrix<complex, ublas::column_major> matrix;\n    typedef ublas::triangular_matrix<complex, ublas::lower, ublas::column_major> matrix_l;\n    typedef ublas::triangular_matrix<complex, ublas::upper, ublas::column_major> matrix_u;\n    typedef typename vector::size_type size_type;\n    rand_normal<complex>::reset();\n    size_type n=8;\n    matrix_l A_l(n, n);\n    matrix_u A_u(n, n);\n    for (size_type j=0; j<n; ++j) {\n      A_u(j, j)=rand_normal<complex>::get().real();\n      A_l(j, j)=A_u(j, j);\n      for (size_type i=0; i<j; ++i) {\n        A_u(i, j)=rand_normal<complex>::get();\n        A_l(j, i)=std::conj(A_u(i, j));\n      }\n    }\n    vector x(n);\n    for (size_type i=0; i<n; ++i)\n      x(i)=rand_normal<complex>::get();\n    vector y(n);\n    for (size_type i=0; i<n; ++i)\n      y(i)=rand_normal<complex>::get();\n    complex alpha(rand_normal<complex>::get());\n    matrix P;\n    {\n      P=ublas::outer_prod(alpha*x, ublas::conj(y));\n      P+=ublas::outer_prod(y, ublas::conj(alpha*x));\n      for (size_type j=0; j<n; ++j)\n        for (size_type i=0; i<j; ++i)\n          P(i, j)=0;\n      matrix A1(P+A_l);\n      matrix_l A2(A_l);\n      blas::hpr2(alpha, x, y, A2);\n      std::cout << print_mat(A1) << '\\n'\n                << print_mat(A2) << '\\n';\n    }\n    {\n      P=ublas::outer_prod(alpha*x, ublas::conj(y));\n      P+=ublas::outer_prod(y, ublas::conj(alpha*x));\n      for (size_type j=0; j<n; ++j)\n        for (size_type i=j+1; i<n; ++i)\n          P(i, j)=0;\n      matrix A1(P+A_u);\n      matrix_u A2(A_u);\n      blas::hpr2(alpha, x, y, A2);\n      std::cout << print_mat(A1) << '\\n'\n                << print_mat(A2) << '\\n';\n    }\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "0dd9633c8c83635b69f8d9ebee741314ac102b80", "size": 2330, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/hpr2.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/hpr2.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/hpr2.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.3611111111, "max_line_length": 90, "alphanum_fraction": 0.60472103, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5125678382792663}}
{"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 BUILDING_FOOTPRINT_RECTANGLE_HPP\n#define BUILDING_FOOTPRINT_RECTANGLE_HPP\n\n#include \"rjmcmc/util/random.hpp\"\n//<-\n/************** application-specific types ****************/\n//->\n\n//[building_footprint_rectangle_definition_geometry\n#include \"geometry.hpp\"\ntypedef Rectangle_2 object;\n//]\n\n//[building_footprint_rectangle_definition_kernels\n#include \"rjmcmc/rjmcmc/kernel/raster_variate.hpp\"\n#include \"rjmcmc/mpp/kernel/uniform_birth.hpp\"\ntypedef marked_point_process::uniform_birth<object,rjmcmc::raster_variate<5> > uniform_birth;\n#include \"rjmcmc/mpp/kernel/uniform_birth_death_kernel.hpp\"\ntypedef marked_point_process::uniform_birth_death_kernel<uniform_birth>::type  birth_death_kernel;\n\n#include \"rjmcmc/rjmcmc/kernel/transform.hpp\"\n#include \"rjmcmc/geometry/transform/rectangle_corner_translation_transform.hpp\"\n#include \"rjmcmc/geometry/transform/rectangle_edge_translation_transform.hpp\"\n#include \"rjmcmc/geometry/transform/rectangle_split_merge_transform.hpp\"\ntypedef geometry::rectangle_edge_translation_transform<0>    edge_transform0;\ntypedef geometry::rectangle_edge_translation_transform<1>    edge_transform1;\ntypedef geometry::rectangle_edge_translation_transform<2>    edge_transform2;\ntypedef geometry::rectangle_edge_translation_transform<3>    edge_transform3;\ntypedef geometry::rectangle_corner_translation_transform<0>  corner_transform0;\ntypedef geometry::rectangle_corner_translation_transform<1>  corner_transform1;\ntypedef geometry::rectangle_corner_translation_transform<2>  corner_transform2;\ntypedef geometry::rectangle_corner_translation_transform<3>  corner_transform3;\ntypedef geometry::rectangle_split_merge_transform_v2 split_merge_transform;\n\n#include \"rjmcmc/mpp/kernel/uniform_kernel.hpp\"\ntypedef marked_point_process::uniform_kernel<object,1,1,edge_transform0>::type  edge_kernel0;\ntypedef marked_point_process::uniform_kernel<object,1,1,edge_transform1>::type  edge_kernel1;\ntypedef marked_point_process::uniform_kernel<object,1,1,edge_transform2>::type  edge_kernel2;\ntypedef marked_point_process::uniform_kernel<object,1,1,edge_transform3>::type  edge_kernel3;\ntypedef marked_point_process::uniform_kernel<object,1,1,corner_transform0>::type  corner_kernel0;\ntypedef marked_point_process::uniform_kernel<object,1,1,corner_transform1>::type  corner_kernel1;\ntypedef marked_point_process::uniform_kernel<object,1,1,corner_transform2>::type  corner_kernel2;\ntypedef marked_point_process::uniform_kernel<object,1,1,corner_transform3>::type  corner_kernel3;\ntypedef marked_point_process::uniform_kernel<object,1,2,split_merge_transform>::type  split_merge_kernel;\n//]\n\n//[building_footprint_rectangle_definition_energies\n#include \"rjmcmc/rjmcmc/energy/energy_operators.hpp\"\n#include \"rjmcmc/mpp/energy/image_gradient_unary_energy.hpp\"\n#include \"rjmcmc/image/gradient_functor.hpp\"\n#include \"rjmcmc/image/oriented.hpp\"\ntypedef oriented<gradient_image_t>                          oriented_gradient_image;\ntypedef image_gradient_unary_energy<oriented_gradient_image> unary_energy;\n\n#include \"rjmcmc/mpp/energy/intersection_area_binary_energy.hpp\"\ntypedef intersection_area_binary_energy<>                   binary_energy;\n//]\n\n//<-\n/************** rjmcmc library types ****************/\n//->\n\n//[building_footprint_rectangle_definition_simulated_annealing\n/*< Choice of the schedule (/include/ and /typedef/) >*/\n#include \"rjmcmc/simulated_annealing/schedule/geometric_schedule.hpp\"\ntypedef simulated_annealing::geometric_schedule<double> schedule;\n/*< Choice of the end_test (/include/ and /typedef/) >*/\n#include \"rjmcmc/simulated_annealing/end_test/max_iteration_end_test.hpp\"\ntypedef simulated_annealing::max_iteration_end_test     end_test;\n//]\n\n//[building_footprint_rectangle_definition_configuration\n\n#include \"rjmcmc/mpp/energy/image_center_unary_energy.hpp\"\ntypedef oriented<boost::gil::gray16_image_t> mask_type;\n#include \"rjmcmc/mpp/configuration/graph_configuration.hpp\"\ntypedef marked_point_process::graph_configuration<\n        object,\n        minus_energy<constant_energy<>,multiplies_energy<constant_energy<>,unary_energy> >,\n        multiplies_energy<constant_energy<>,binary_energy>\n        > configuration;\n//]\n\n//[building_footprint_rectangle_definition_distribution\n#include \"rjmcmc/rjmcmc/distribution/poisson_distribution.hpp\"\ntypedef rjmcmc::poisson_distribution                           distribution;\n//]\n\n//[building_footprint_rectangle_definition_sampler\n#include \"rjmcmc/rjmcmc/sampler/sampler.hpp\"\n\n#include \"rjmcmc/mpp/direct_sampler.hpp\"\ntypedef marked_point_process::direct_sampler<distribution,uniform_birth> d_sampler;\n\n#include \"rjmcmc/rjmcmc/acceptance/metropolis_acceptance.hpp\"\ntypedef rjmcmc::metropolis_acceptance acceptance;\n\n//typedef rjmcmc::sampler<d_sampler,acceptance,birth_death_kernel> sampler;\ntypedef rjmcmc::sampler<d_sampler,acceptance\n        ,birth_death_kernel\n        ,split_merge_kernel\n        ,edge_kernel0\n        ,edge_kernel1\n        ,edge_kernel2\n        ,edge_kernel3\n        ,corner_kernel0\n        ,corner_kernel1\n        ,corner_kernel2\n        ,corner_kernel3\n        > sampler;\n//]\n\n\n//[building_footprint_rectangle_bbox_accessors\nIso_rectangle_2 get_bbox(const param *p) {\n    int x0 = p->get<int>(\"xmin\");\n    int x1 = p->get<int>(\"xmax\");\n    int y0 = p->get<int>(\"ymin\");\n    int y1 = p->get<int>(\"ymax\");\n    if(x0>x1) std::swap(x0,x1);\n    if(y0>y1) std::swap(y0,y1);\n    return Iso_rectangle_2(x0,y0,x1,y1);\n}\n\nvoid set_bbox(param *p, const Iso_rectangle_2& r) {\n    p->set(\"xmin\",(int) r.min().x());\n    p->set(\"ymin\",(int) r.min().y());\n    p->set(\"xmax\",(int) r.max().x());\n    p->set(\"ymax\",(int) r.max().y());\n}\n//]\n\n//[building_footprint_rectangle_create_configuration\n#include \"rjmcmc/image/conversion_functor.hpp\"\n#include <boost/gil/extension/io_new/tiff_write.hpp>\n\nvoid create_configuration(const param *p, const oriented_gradient_image& grad, configuration *&c) {\n    std::string mask_file = p->get<boost::filesystem::path>(\"mask\" ).string();\n    if(mask_file!=\"\")\n    {\n        Iso_rectangle_2 bbox = get_bbox(p);\n        clip_bbox(bbox,mask_file);\n        mask_type mask(mask_file , bbox, conversion_functor() );\n        boost::gil::write_view( mask_file+\"_x0.tif\" , boost::gil::nth_channel_view(grad.view(),0), boost::gil::tiff_tag() );\n        boost::gil::write_view( mask_file+\"_y0.tif\" , boost::gil::nth_channel_view(grad.view(),1), boost::gil::tiff_tag() );\n        for(int j=0; j<grad.view().height();++j)\n        {\n            for(int i=0; i<grad.view().width();++i)\n            {\n                std::cout << mask.view()(i,j)<< \" \";\n                if (i < mask.view().width() && j < mask.view().height() && mask.view()(i,j)<=0)\n                {\n                    boost::gil::at_c<0>(grad.view()(i,j)) = boost::gil::at_c<1>(grad.view()(i,j)) = 0;\n                }\n            }\n        }\n        boost::gil::write_view( mask_file+\"_x.tif\" , boost::gil::nth_channel_view(grad.view(),0), boost::gil::tiff_tag() );\n        boost::gil::write_view( mask_file+\"_y.tif\" , boost::gil::nth_channel_view(grad.view(),1), boost::gil::tiff_tag() );\n    }\n\n    // empty initial configuration\n    c = new configuration( p->get<double>(\"energy\")-(p->get<double>(\"ponderation_grad\")*unary_energy(grad)),\n                           p->get<double>(\"ponderation_surface\")*binary_energy());\n}\n//]\n\n//[building_footprint_rectangle_create_sampler\nvoid create_sampler(const param *p, sampler *&s) {\n    Iso_rectangle_2 r = get_bbox(p);\n    double maxsize  = p->get<double>(\"maxsize\");\n    double maxratio = p->get<double>(\"maxratio\");\n    double minratio = 1./maxratio;\n\n    int size[] = {1,1,1,1,1};\n    short unsigned prob0[] = {1};\n    short unsigned *prob = prob0;\n    std::string birth_prob_file = p->get<boost::filesystem::path>(\"birth_prob\" ).string();\n    if(birth_prob_file!=\"\")\n    {\n        unsigned short birth_prob_offset = (unsigned short) (p->get<double>(\"birth_prob_offset\" ));\n        clip_bbox(r,birth_prob_file);\n        mask_type birth_prob(birth_prob_file , r, conversion_functor() );\n        mask_type::view_t view = birth_prob.view();\n        size[0] = view.width ();\n        size[1] = view.height();\n        prob = boost::gil::interleaved_view_get_raw_data(view); // should work in general on single channel images\n        for(int i=0; i< size[0]*size[1]; ++i) prob[i] = std::max(prob[i],birth_prob_offset)-birth_prob_offset;\n    }\n\n    K::Vector_2 v(maxsize,maxsize);\n    uniform_birth birth(\n            Rectangle_2(r.min(),-v,minratio),\n            Rectangle_2(r.max(), v,maxratio),\n            rjmcmc::raster_variate<5>(prob,size)\n            );\n\n    distribution cs(p->get<double>(\"poisson\"));\n\n    d_sampler ds( cs, birth );\n\n    typedef rjmcmc::mt19937_generator Engine;\n    Engine& e = rjmcmc::random();\n    marked_point_process::graph_configuration<object, constant_energy<>, constant_energy<> > c(1,1);\n    ds(e,c);\n    double p_birthdeath  = p->get<double>(\"p_birthdeath\");\n    double p_birth  = p->get<double>(\"p_birth\");\n    double p_edge   = 0.25*p->get<double>(\"p_edge\");\n    double p_corner = 0.25*p->get<double>(\"p_corner\");\n    double p_split_merge = p->get<double>(\"p_split_merge\");\n    double p_split       = p->get<double>(\"p_split\");\n    birth_death_kernel k_birth_death = marked_point_process::make_uniform_birth_death_kernel(birth, p_birthdeath, p_birth );\n    edge_kernel0 k_edge0 = marked_point_process::make_uniform_kernel<object,1,1>(edge_transform0(minratio,maxratio),p_edge);\n    edge_kernel1 k_edge1 = marked_point_process::make_uniform_kernel<object,1,1>(edge_transform1(minratio,maxratio),p_edge);\n    edge_kernel2 k_edge2 = marked_point_process::make_uniform_kernel<object,1,1>(edge_transform2(minratio,maxratio),p_edge);\n    edge_kernel3 k_edge3 = marked_point_process::make_uniform_kernel<object,1,1>(edge_transform3(minratio,maxratio),p_edge);\n    corner_kernel0 k_corner0 = marked_point_process::make_uniform_kernel<object,1,1>(corner_transform0(),p_corner);\n    corner_kernel1 k_corner1 = marked_point_process::make_uniform_kernel<object,1,1>(corner_transform1(),p_corner);\n    corner_kernel2 k_corner2 = marked_point_process::make_uniform_kernel<object,1,1>(corner_transform2(),p_corner);\n    corner_kernel3 k_corner3 = marked_point_process::make_uniform_kernel<object,1,1>(corner_transform3(),p_corner);\n    k_birth_death.name(0,\"birth\");\n    k_birth_death.name(1,\"death\");\n    k_edge0.name(0,\"edge00\");\n    k_edge0.name(1,\"edge01\");\n    k_edge1.name(0,\"edge10\");\n    k_edge1.name(1,\"edge11\");\n    k_edge2.name(0,\"edge20\");\n    k_edge2.name(1,\"edge21\");\n    k_edge3.name(0,\"edge30\");\n    k_edge3.name(1,\"edge31\");\n    k_corner0.name(0,\"corner00\");\n    k_corner0.name(1,\"corner01\");\n    k_corner1.name(0,\"corner10\");\n    k_corner1.name(1,\"corner11\");\n    k_corner2.name(0,\"corner20\");\n    k_corner2.name(1,\"corner21\");\n    k_corner3.name(0,\"corner30\");\n    k_corner3.name(1,\"corner31\");\n\n\n    split_merge_kernel k_split_merge = marked_point_process::make_uniform_kernel<object,1,2>(split_merge_transform(),p_split_merge, p_split);\n    k_split_merge.name(0,\"split\");\n    k_split_merge.name(1,\"merge\");\n\n    s = new sampler( ds, acceptance()\n                     , k_birth_death\n                     , k_split_merge\n                     , k_edge0\n                     , k_edge1\n                     , k_edge2\n                     , k_edge3\n                     , k_corner0\n                     , k_corner1\n                     , k_corner2\n                     , k_corner3\n                     );\n}\n//]\n\n//[building_footprint_rectangle_create_schedule\nvoid create_schedule(const param *p, schedule *&t)\n{\n    t = new schedule(\n            p->get<double>(\"temp\"),\n            p->get<double>(\"deccoef\")\n            );\n}\n//]\n\n//[building_footprint_rectangle_create_end_test\nvoid create_end_test(const param *p, end_test *&e)\n{\n    e = new end_test(\n            p->get<int>(\"nbiter\")\n            );\n}\n//]\n\n//[building_footprint_rectangle_init_visitor\ntemplate<typename Visitor>\nvoid init_visitor(const param *p, Visitor& v)\n{\n    v.init(\n            p->get<int>(\"nbdump\"),\n            p->get<int>(\"nbsave\")\n            );\n}\n//]\n\n//[building_footprint_rectangle_image_include_tpl_instanciations\n#include \"rjmcmc/image/image_types.hpp\"\n#include \"rjmcmc/image/oriented_inc.hpp\"\n#include \"rjmcmc/image/gradient_functor_inc.hpp\"\n//]\n\n//[building_footprint_rectangle_optimization\n#include \"rjmcmc/simulated_annealing/simulated_annealing.hpp\"\n//]\n\n#endif // BUILDING_FOOTPRINT_RECTANGLE_HPP\n", "meta": {"hexsha": "15bb8bcc3026d5c439f1365b5b0044e48dd67f68", "size": 14265, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "samples/building_footprint_rectangle/core/building_footprint_rectangle.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": "samples/building_footprint_rectangle/core/building_footprint_rectangle.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": "samples/building_footprint_rectangle/core/building_footprint_rectangle.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": 42.4553571429, "max_line_length": 141, "alphanum_fraction": 0.7118822292, "num_tokens": 3445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5125678280949241}}
{"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 * testDiscreteLookupDAG.cpp\n *\n *  @date January, 2022\n *  @author Frank Dellaert\n */\n\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/base/Testable.h>\n#include <gtsam/discrete/DiscreteLookupDAG.h>\n\n#include <boost/assign/list_inserter.hpp>\n#include <boost/assign/std/map.hpp>\n\nusing namespace gtsam;\nusing namespace boost::assign;\n\n/* ************************************************************************* */\nTEST(DiscreteLookupDAG, argmax) {\n  using ADT = AlgebraicDecisionTree<Key>;\n\n  // Declare 2 keys\n  DiscreteKey A(0, 2), B(1, 2);\n\n  // Create lookup table corresponding to \"marginalIsNotMPE\" in testDFG.\n  DiscreteLookupDAG dag;\n\n  ADT adtB(DiscreteKeys{B, A}, std::vector<double>{0.5, 1. / 3, 0.5, 2. / 3});\n  dag.add(1, DiscreteKeys{B, A}, adtB);\n\n  ADT adtA(A, 0.5 * 10 / 19, (2. / 3) * (9. / 19));\n  dag.add(1, DiscreteKeys{A}, adtA);\n\n  // The expected MPE is A=1, B=1\n  DiscreteValues mpe;\n  insert(mpe)(0, 1)(1, 1);\n\n  // check:\n  auto actualMPE = dag.argmax();\n  EXPECT(assert_equal(mpe, actualMPE));\n}\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "04b8597804f33d046dd0f348e5fd8116cf741fba", "size": 1659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/discrete/tests/testDiscreteLookupDAG.cpp", "max_stars_repo_name": "h-rover/gtsam", "max_stars_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T07:01:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T07:01:48.000Z", "max_issues_repo_path": "gtsam/discrete/tests/testDiscreteLookupDAG.cpp", "max_issues_repo_name": "h-rover/gtsam", "max_issues_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/discrete/tests/testDiscreteLookupDAG.cpp", "max_forks_repo_name": "h-rover/gtsam", "max_forks_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-21T06:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T06:58:34.000Z", "avg_line_length": 28.1186440678, "max_line_length": 80, "alphanum_fraction": 0.5213984328, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5125678280949241}}
{"text": "//\n//  HeightmapGenerator.cpp\n// Kuplung\n//\n//  Created by Sergey Petrov on 12/21/15.\n//  Copyright \u00a9 2015 supudo.net. All rights reserved.\n//\n\n// http://www.chadvernon.com/blog/resources/directx9/terrain-generation-with-a-heightmap/\n// http://www.rastertek.com/tertut02.html\n\n#include \"HeightmapGenerator.hpp\"\n#include <boost/algorithm/string/replace.hpp>\n#include <fstream>\n#include <glm/glm.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n\nvoid HeightmapGenerator::initPosition() {\n  this->position_x1 = 0.0f;\n  this->position_x2 = 1.0f;\n  this->position_y1 = 0.0f;\n  this->position_y2 = 1.0f;\n\n  this->Setting_Octaves = 3;\n  this->Setting_Frequency = 2.0f;\n  this->Setting_Persistence = 0.5f;\n  this->Setting_ColorTerrain = true;\n  this->Setting_TerrainType = 0;\n\n  this->Setting_OffsetHorizontal = 0.0f;\n  this->Setting_OffsetVertical = 0.0f;\n  this->Setting_ScaleCoeficient = 10.0f;\n  this->Setting_HeightCoeficient = 10.0f;\n\n  this->Setting_Seed = 1;\n}\n\nvoid HeightmapGenerator::generateTerrain(const std::string& assetFolder, const int& width, const int& height) {\n  this->assetsFolder = assetFolder;\n  this->width = width;\n  this->height = height;\n\n  this->position_x1 += this->Setting_OffsetHorizontal;\n  this->position_x2 += this->Setting_OffsetHorizontal;\n  this->position_y1 += this->Setting_OffsetVertical;\n  this->position_y2 += this->Setting_OffsetVertical;\n\n  module::Perlin perlinNoiser;\n\n  perlinNoiser.SetOctaveCount(this->Setting_Octaves);\n  perlinNoiser.SetFrequency(static_cast<double>(this->Setting_Frequency));\n  perlinNoiser.SetPersistence(static_cast<double>(this->Setting_Persistence));\n  if (this->Setting_SeedRandom)\n    this->Setting_Seed = rand();\n  perlinNoiser.SetSeed(this->Setting_Seed);\n\n  // heightmap\n  if (this->Setting_TerrainType != GeometryTerrainType_Sphere) {\n    utils::NoiseMapBuilderPlane heightMapBuilder;\n    heightMapBuilder.SetSourceModule(perlinNoiser);\n    heightMapBuilder.SetDestNoiseMap(this->heightMap);\n    heightMapBuilder.SetDestSize(this->width, this->height);\n    heightMapBuilder.SetBounds(static_cast<double>(this->position_x1), static_cast<double>(this->position_x2), static_cast<double>(this->position_y1), static_cast<double>(this->position_y2));\n    heightMapBuilder.Build();\n  }\n  else {\n    utils::NoiseMapBuilderSphere heightMapBuilder;\n    heightMapBuilder.SetSourceModule(perlinNoiser);\n    heightMapBuilder.SetDestNoiseMap(this->heightMap);\n    heightMapBuilder.SetDestSize(this->width, this->height);\n    heightMapBuilder.SetBounds(-90.0, 90.0, -180.0, 180.0);\n    heightMapBuilder.Build();\n  }\n\n  // render\n  utils::RendererImage renderer;\n  renderer.SetSourceNoiseMap(this->heightMap);\n  renderer.SetDestImage(this->image);\n  if (this->Setting_ColorTerrain) {\n    renderer.ClearGradient();\n    renderer.AddGradientPoint(-1.0000, utils::Color(0, 0, 128, 255)); // deeps\n    renderer.AddGradientPoint(-0.2500, utils::Color(0, 0, 255, 255)); // shallow\n    renderer.AddGradientPoint(0.0000, utils::Color(0, 128, 255, 255)); // shore\n    renderer.AddGradientPoint(0.0625, utils::Color(240, 240, 64, 255)); // sand\n    renderer.AddGradientPoint(0.1250, utils::Color(32, 160, 0, 255)); // grass\n    renderer.AddGradientPoint(0.3750, utils::Color(224, 224, 0, 255)); // dirt\n    renderer.AddGradientPoint(0.7500, utils::Color(128, 128, 128, 255)); // rock\n    renderer.AddGradientPoint(1.0000, utils::Color(255, 255, 255, 255)); // snow\n  }\n  renderer.Render();\n\n  std::string filename;\n  if (Settings::Instance()->Terrain_HeightmapImageHistory) {\n    time_t t = time(0);\n    const struct tm* now = localtime(&t);\n\n    const int year = now->tm_year + 1900;\n    const int month = now->tm_mon + 1;\n    const int day = now->tm_mday;\n    const int hour = now->tm_hour;\n    const int minute = now->tm_min;\n    const int seconds = now->tm_sec;\n\n    std::string fileSuffix = std::to_string(year) + std::to_string(month) + std::to_string(day) + std::to_string(hour) + std::to_string(minute) + std::to_string(seconds);\n    filename = \"terrain_heightmap_\" + fileSuffix + \".bmp\";\n  }\n  else\n    filename = \"terrain_heightmap.bmp\";\n  this->heightmapImage = assetsFolder + \"/\" + filename;\n\n  Settings::Instance()->funcDoLog(Settings::Instance()->string_format(\"Generating terrain [O = %i, F = %f, P = %f] = %s\", this->Setting_Octaves, double(this->Setting_Frequency), double(this->Setting_Persistence), this->heightmapImage.c_str()));\n\n#ifdef _WIN32\n#else\n  boost::replace_all(this->assetsFolder, \"Kuplung.app/Contents/Resources\", \"\");\n#endif\n  utils::WriterBMP writer;\n  writer.SetSourceImage(this->image);\n  writer.SetDestFilename(this->heightmapImage);\n  writer.WriteDestFile();\n\n  switch (this->Setting_TerrainType) {\n    case GeometryTerrainType_Cubic:\n      this->generatePlaneGeometryCubic();\n      break;\n    case GeometryTerrainType_Sphere:\n      this->generateSphereGeometry();\n      break;\n    default:\n      this->generatePlaneGeometrySmooth();\n      break;\n  }\n}\n\nvoid HeightmapGenerator::generatePlaneGeometrySmooth() {\n  // BIG thanks to http://stackoverflow.com/a/10114636/69897 !!!!\n  unsigned int heightmapHeight = static_cast<unsigned int>(this->heightMap.GetHeight());\n  unsigned int heightmapWidth = static_cast<unsigned int>(this->heightMap.GetWidth());\n\n  this->vertices.clear();\n  this->uvs.clear();\n  this->indices.clear();\n  this->colors.clear();\n\n  const float worldCenter = -1.0f * heightmapWidth / 2.0f;\n\n  const float rr = 1.0f / static_cast<float>(heightmapHeight - 1);\n  const float ss = 1.0f / static_cast<float>(heightmapWidth - 1);\n\n  float p_x = 0, p_y = 0, p_z = 0;\n  glm::vec3 position, color;\n  glm::vec2 uv;\n  utils::Color c;\n  for (unsigned int y = 0; y < heightmapHeight; ++y) {\n    for (unsigned int x = 0; x < heightmapWidth; ++x) {\n      p_x = x + worldCenter;\n      p_y = this->heightMap.GetValue(static_cast<int>(x), static_cast<int>(y)) * this->Setting_HeightCoeficient;\n      p_z = y + worldCenter;\n      position = glm::vec3(p_x, p_y, p_z) / this->Setting_ScaleCoeficient;\n      uv = glm::vec2(x * ss, 1.0f - y * rr);\n\n      c = this->image.GetValue(static_cast<int>(x), static_cast<int>(y));\n      color = glm::vec3(c.red / 255.0f, c.green / 255.0f, c.blue / 255.0f);\n\n      this->vertices.push_back(position);\n      this->uvs.push_back(uv);\n      this->normals.push_back(glm::vec3(0, 1, 0));\n      this->colors.push_back(color);\n    }\n  }\n\n  glm::vec3 v1, v2, v3, normal;\n  for (unsigned int y = 0; y < (heightmapHeight - 1); ++y) {\n    for (unsigned int x = 0; x < (heightmapWidth - 1); ++x) {\n      unsigned int start = y * heightmapWidth + x;\n      this->indices.push_back(start);\n      this->indices.push_back(start + 1);\n      this->indices.push_back(start + heightmapWidth);\n      v1 = this->vertices[start];\n      v2 = this->vertices[start + 1];\n      v3 = this->vertices[start + heightmapWidth];\n      normal = glm::cross(v2 - v1, v3 - v1);\n      this->normals[start] = normal;\n      this->normals[start + 1] = normal;\n      this->normals[start + heightmapWidth] = normal;\n\n      this->indices.push_back(start + 1);\n      this->indices.push_back(start + 1 + heightmapWidth);\n      this->indices.push_back(start + heightmapWidth);\n      v1 = this->vertices[start];\n      v2 = this->vertices[start + heightmapWidth];\n      v3 = this->vertices[start + 1 + heightmapWidth];\n      normal = glm::cross(v2 - v1, v3 - v1);\n      this->normals[start] = normal;\n      this->normals[start + heightmapWidth] = normal;\n      this->normals[start + 1 + heightmapWidth] = normal;\n    }\n  }\n\n  this->generateMeshModel();\n}\n\nvoid HeightmapGenerator::generateSphereGeometry() {\n  unsigned int heightmapHeight = static_cast<unsigned int>(this->heightMap.GetHeight());\n  unsigned int heightmapWidth = static_cast<unsigned int>(this->heightMap.GetWidth());\n\n  this->vertices.clear();\n  this->uvs.clear();\n  this->normals.clear();\n  this->colors.clear();\n  this->indices.clear();\n\n  std::string grapher(\"\");\n\n  const float rr = 1.0f / static_cast<float>(heightmapHeight - 1);\n  const float ss = 1.0f / static_cast<float>(heightmapWidth - 1);\n\n  static const double pi = glm::pi<double>();\n  static const double pi_2 = glm::half_pi<double>();\n\n  float hmValue = 0;\n  float p_x = 0, p_y = 0, p_z = 0;\n  glm::vec3 position, color;\n  glm::vec2 uv;\n  utils::Color c;\n  for (unsigned int y = 0; y < heightmapHeight; ++y) {\n    for (unsigned int x = 0; x < heightmapWidth; ++x) {\n      hmValue = this->heightMap.GetValue(static_cast<int>(x), static_cast<int>(y));\n      p_x = static_cast<float>(cos(2 * pi * x * ss) * sin(pi * y * rr));\n      p_y = static_cast<float>(sin(-pi_2 + pi * y * rr));\n      p_z = static_cast<float>(sin(2 * pi * x * ss) * sin(pi * y * rr));\n      position = glm::vec3(p_x, p_y, p_z) * this->Setting_ScaleCoeficient;\n      position += glm::normalize(position) * hmValue;\n\n      if (Settings::Instance()->logDebugInfo)\n        grapher += Settings::Instance()->string_format(\"%g,%g,%g\\n\", position.x, position.y, position.z);\n\n      uv = glm::vec2(x * 1.0f / heightmapWidth, y * 1.0f / heightmapHeight);\n      c = this->image.GetValue(static_cast<int>(x), static_cast<int>(y));\n      color = glm::vec3(c.red / 255.0f, c.green / 255.0f, c.blue / 255.0f);\n\n      this->vertices.push_back(position);\n      this->uvs.push_back(uv);\n      this->normals.push_back(glm::vec3(0, 1, 0));\n      this->colors.push_back(color);\n    }\n  }\n\n  glm::vec3 v1, v2, v3, normal;\n  for (unsigned int y = 0; y < (heightmapHeight - 1); ++y) {\n    for (unsigned int x = 0; x < (heightmapWidth - 1); ++x) {\n      unsigned int start = y * heightmapWidth + x;\n      this->indices.push_back(start);\n      this->indices.push_back(start + 1);\n      this->indices.push_back(start + heightmapWidth);\n      v1 = this->vertices[start];\n      v2 = this->vertices[start + 1];\n      v3 = this->vertices[start + heightmapWidth];\n      normal = glm::cross(v2 - v1, v3 - v1);\n      this->normals[start] = normal;\n      this->normals[start + 1] = normal;\n      this->normals[start + heightmapWidth] = normal;\n\n      this->indices.push_back(start + 1);\n      this->indices.push_back(start + 1 + heightmapWidth);\n      this->indices.push_back(start + heightmapWidth);\n      v1 = this->vertices[start];\n      v2 = this->vertices[start + heightmapWidth];\n      v3 = this->vertices[start + 1 + heightmapWidth];\n      normal = glm::cross(v2 - v1, v3 - v1);\n      this->normals[start] = normal;\n      this->normals[start + heightmapWidth] = normal;\n      this->normals[start + 1 + heightmapWidth] = normal;\n    }\n  }\n\n  this->generateMeshModel();\n\n  if (Settings::Instance()->logDebugInfo) {\n    std::ofstream out(this->assetsFolder + \"/terrain.txt\");\n    if (out.is_open()) {\n      out << grapher;\n      out.close();\n    }\n  }\n}\n\nvoid HeightmapGenerator::generatePlaneGeometryCubic() {\n  const int heightmapHeight = this->heightMap.GetHeight();\n  const int heightmapWidth = this->heightMap.GetWidth();\n\n  this->vertices.clear();\n  this->uvs.clear();\n  this->normals.clear();\n  this->colors.clear();\n  this->indices.clear();\n\n  std::string grapher(\"\");\n\n  const float rr = 1.0f / static_cast<float>(heightmapHeight - 1);\n  const float ss = 1.0f / static_cast<float>(heightmapWidth - 1);\n\n  unsigned int vertIndex = 0;\n  const float worldCenter = -1.0f * heightmapWidth / 2.0f;\n  glm::vec3 v0, v1, v2, v3, v4, v5, v10, v11, n, n2, n3, color;\n  glm::vec2 uv, uv2, uv3;\n  float hmValue = 0, hmValue2 = 0, hmValue3 = 0;\n  utils::Color c;\n\n  for (int y = 0; y < (heightmapHeight - 1) * 3; ++y) {\n    for (int x = 0; x < heightmapWidth - 1; ++x) {\n      hmValue = this->heightMap.GetValue(x, y) * this->Setting_HeightCoeficient;\n      hmValue2 = this->heightMap.GetValue(x + 1, y) * this->Setting_HeightCoeficient;\n      hmValue3 = this->heightMap.GetValue(x, y + 1) * this->Setting_HeightCoeficient;\n\n      c = this->image.GetValue(x, y);\n      color = glm::vec3(c.red / 255.0f, c.green / 255.0f, c.blue / 255.0f);\n      //uv = glm::vec2(glm::clamp(float(x), 0.0f, 1.0f), glm::clamp(float(y), 0.0f, 1.0f));\n      uv = glm::vec2(x * ss, y * rr);\n      uv2 = glm::vec2((x + 1) * ss, y * rr);\n      uv3 = glm::vec2(x * ss, (y + 1) * rr);\n\n      // counter clockwise direction\n      //\n      //   ^\n      //   |  11 --- 10 --- 12 ---- 13 --- 14\n      //   |   |    / |    / |    / |    / |\n      //   |   |   /  |   /  |   /  |   /  |\n      //   |   |  /   |  /   |  /   |  /   |\n      //   |   | /    | /    | /    | /    |\n      //   |   3 ---- 2 ---- 5 ---- 7 ---- 9\n      //   |   |    / |    / |    / |    / |\n      //   |   |   /  |   /  |   /  |   /  |\n      //   |   |  /   |  /   |  /   |  /   |\n      //   |   | /    | /    | /    | /    |\n      //   Y   0 ---- 1 ---- 4 ---- 6 ---- 8\n      //   |\n      //   0---X---------------------------------->\n      //\n\n      v0 = glm::vec3(x + worldCenter, y + worldCenter, hmValue);\n      v1 = glm::vec3(x + worldCenter + 1, y + worldCenter, hmValue);\n      v2 = glm::vec3(x + worldCenter + 1, y + worldCenter + 1, hmValue);\n      v3 = glm::vec3(x + worldCenter, y + worldCenter + 1, hmValue);\n      v4 = glm::vec3(x + worldCenter + 1, y + worldCenter, hmValue2);\n      v5 = glm::vec3(x + worldCenter + 1, y + worldCenter + 1, hmValue2);\n      v10 = glm::vec3(x + worldCenter + 1, y + worldCenter + 1, hmValue3);\n      v11 = glm::vec3(x + worldCenter, y + worldCenter + 1, hmValue3);\n      n = glm::cross(v1 - v0, v2 - v0);\n      n2 = glm::cross(v4 - v1, v5 - v1);\n      n3 = glm::cross(v10 - v3, v11 - v3);\n\n      // triangle 1\n      this->vertices.push_back(v0 / this->Setting_ScaleCoeficient);\n      this->vertices.push_back(v1 / this->Setting_ScaleCoeficient);\n      this->vertices.push_back(v2 / this->Setting_ScaleCoeficient);\n\n      this->uvs.push_back(uv);\n      this->uvs.push_back(uv);\n      this->uvs.push_back(uv);\n\n      this->normals.push_back(n);\n      this->normals.push_back(n);\n      this->normals.push_back(n);\n\n      this->indices.push_back(vertIndex);\n\n      vertIndex += 1;\n\n      this->colors.push_back(color);\n      this->colors.push_back(color);\n      this->colors.push_back(color);\n\n      if (Settings::Instance()->logDebugInfo)\n        grapher += Settings::Instance()->string_format(\" %g,%g,%g;%g,%g,%g;%g,%g,%g \\n\", v0.x, v0.y, v0.z, v1.x, v1.y, v1.z, v2.x, v2.y, v2.z);\n\n      // triangle 2\n      this->vertices.push_back(v0 / this->Setting_ScaleCoeficient);\n      this->vertices.push_back(v2 / this->Setting_ScaleCoeficient);\n      this->vertices.push_back(v3 / this->Setting_ScaleCoeficient);\n\n      this->uvs.push_back(uv);\n      this->uvs.push_back(uv);\n      this->uvs.push_back(uv);\n\n      this->normals.push_back(n);\n      this->normals.push_back(n);\n      this->normals.push_back(n);\n\n      this->indices.push_back(vertIndex);\n\n      vertIndex += 1;\n\n      this->colors.push_back(color);\n      this->colors.push_back(color);\n      this->colors.push_back(color);\n\n      // connecting triangle 1 - right\n      this->vertices.push_back(v1 / this->Setting_ScaleCoeficient);\n      this->vertices.push_back(v4 / this->Setting_ScaleCoeficient);\n      this->vertices.push_back(v5 / this->Setting_ScaleCoeficient);\n\n      this->uvs.push_back(uv2);\n      this->uvs.push_back(uv2);\n      this->uvs.push_back(uv2);\n\n      this->normals.push_back(n2);\n      this->normals.push_back(n2);\n      this->normals.push_back(n2);\n\n      this->indices.push_back(vertIndex);\n\n      vertIndex += 1;\n\n      this->colors.push_back(color);\n      this->colors.push_back(color);\n      this->colors.push_back(color);\n\n      // connecting triangle 2 - right\n      this->vertices.push_back(v1 / this->Setting_ScaleCoeficient);\n      this->vertices.push_back(v5 / this->Setting_ScaleCoeficient);\n      this->vertices.push_back(v2 / this->Setting_ScaleCoeficient);\n\n      this->uvs.push_back(uv2);\n      this->uvs.push_back(uv2);\n      this->uvs.push_back(uv2);\n\n      this->normals.push_back(n2);\n      this->normals.push_back(n2);\n      this->normals.push_back(n2);\n\n      this->indices.push_back(vertIndex);\n\n      vertIndex += 1;\n\n      this->colors.push_back(color);\n      this->colors.push_back(color);\n      this->colors.push_back(color);\n\n      // connecting triangle 1 - top\n      this->vertices.push_back(v3 / this->Setting_ScaleCoeficient);\n      this->vertices.push_back(v2 / this->Setting_ScaleCoeficient);\n      this->vertices.push_back(v10 / this->Setting_ScaleCoeficient);\n\n      this->uvs.push_back(uv3);\n      this->uvs.push_back(uv3);\n      this->uvs.push_back(uv3);\n\n      this->normals.push_back(n3);\n      this->normals.push_back(n3);\n      this->normals.push_back(n3);\n\n      this->indices.push_back(vertIndex);\n\n      vertIndex += 1;\n\n      this->colors.push_back(color);\n      this->colors.push_back(color);\n      this->colors.push_back(color);\n\n      // connecting triangle 2 - top\n      this->vertices.push_back(v3 / this->Setting_ScaleCoeficient);\n      this->vertices.push_back(v10 / this->Setting_ScaleCoeficient);\n      this->vertices.push_back(v11 / this->Setting_ScaleCoeficient);\n\n      this->uvs.push_back(uv3);\n      this->uvs.push_back(uv3);\n      this->uvs.push_back(uv3);\n\n      this->normals.push_back(n3);\n      this->normals.push_back(n3);\n      this->normals.push_back(n3);\n\n      this->indices.push_back(vertIndex);\n\n      vertIndex += 1;\n\n      this->colors.push_back(color);\n      this->colors.push_back(color);\n      this->colors.push_back(color);\n    }\n  }\n\n  this->generateMeshModel();\n\n  if (Settings::Instance()->logDebugInfo) {\n    std::ofstream out(this->assetsFolder + \"/terrain.txt\");\n    if (out.is_open()) {\n      out << grapher;\n      out.close();\n    }\n  }\n}\n\nvoid HeightmapGenerator::generateMeshModel() {\n  this->modelTerrain = {};\n  this->modelTerrain.vertices.clear();\n  this->modelTerrain.texture_coordinates.clear();\n  this->modelTerrain.normals.clear();\n  this->modelTerrain.indices.clear();\n\n  this->modelTerrain.ID = 1;\n  this->modelTerrain.MaterialTitle = \"MaterialTerrain\";\n  this->modelTerrain.ModelTitle = \"Terrain\";\n\n  this->modelTerrain.vertices = this->vertices;\n  this->modelTerrain.texture_coordinates = this->uvs;\n  this->modelTerrain.normals = this->normals;\n  this->modelTerrain.indices = this->indices;\n\n  this->modelTerrain.countVertices = static_cast<int>(this->vertices.size());\n  this->modelTerrain.countTextureCoordinates = static_cast<int>(this->uvs.size());\n  this->modelTerrain.countNormals = static_cast<int>(this->normals.size());\n  this->modelTerrain.countIndices = static_cast<int>(this->indices.size());\n\n  MeshModelMaterial material = {};\n  material.MaterialID = 1;\n  material.MaterialTitle = \"MaterialTerrain\";\n  material.AmbientColor = glm::vec3(0.7f);\n  material.DiffuseColor = glm::vec3(0.7f);\n  material.SpecularExp = 99.0f;\n  material.IlluminationMode = 2;\n  material.OpticalDensity = 1.0f;\n  material.Transparency = 1.0f;\n  this->modelTerrain.ModelMaterial = material;\n}\n", "meta": {"hexsha": "3886d2e7f5a0f98177abe5db5548f04fbd187b01", "size": 18780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kuplung/kuplung/pcg/HeightmapGenerator.cpp", "max_stars_repo_name": "supudo/Kuplung", "max_stars_repo_head_hexsha": "f0e11934fde0675fa531e6dc263bedcc20a5ea1a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-02-17T17:12:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T01:55:06.000Z", "max_issues_repo_path": "Kuplung/kuplung/pcg/HeightmapGenerator.cpp", "max_issues_repo_name": "supudo/Kuplung", "max_issues_repo_head_hexsha": "f0e11934fde0675fa531e6dc263bedcc20a5ea1a", "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": "Kuplung/kuplung/pcg/HeightmapGenerator.cpp", "max_forks_repo_name": "supudo/Kuplung", "max_forks_repo_head_hexsha": "f0e11934fde0675fa531e6dc263bedcc20a5ea1a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-15T08:10:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T08:10:10.000Z", "avg_line_length": 35.6356736243, "max_line_length": 244, "alphanum_fraction": 0.639456869, "num_tokens": 5571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5125615426286515}}
{"text": "#include <tiny.h>\n#include <convex.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\n// 2011-11-12 Kenny: Does these test depend on the order in which vertices are added to the simplex? We always use a,b,c\n\nBOOST_AUTO_TEST_SUITE(convex_reduce_triangle);\n\nBOOST_AUTO_TEST_CASE(case_by_case_test)\n{\n  typedef tiny::MathTypes<double>         math_types;\n  typedef math_types::vector3_type        vector3_type;\n  typedef math_types::real_type           real_type;\n  \n  typedef convex::Simplex<vector3_type>           simplex_type;\n  \n  // Inside face-region new simplex should be ABC\n  {\n    vector3_type const a = vector3_type::make(-1.0, -1.0, 0.0);\n    vector3_type const b = vector3_type::make( 1.0, -1.0, 0.0);\n    vector3_type const c = vector3_type::make( 0.5,  0.1, 0.0);\n    \n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    for( size_t i=1u; i<10u; ++i)\n      for( size_t j=1u; j<10u; ++j)\n        for( size_t k=1u; k<10u; ++k)\n        {\n          real_type u = i*0.1;\n          real_type v = j*0.1;\n          real_type w = k*0.1;\n          \n          real_type lgh = u + v + w;\n          u /= lgh;\n          v /= lgh;\n          w /= lgh;\n          \n          vector3_type const p = u*a + v*b + w*c;\n          \n          convex::reduce_triangle( p, S );\n          \n          BOOST_CHECK( convex::dimension( S ) == 3u );\n          \n          int bit_A    = 0;\n          size_t idx_A = 0;\n          int bit_B    = 0;\n          size_t idx_B = 0;\n          int bit_C    = 0;\n          size_t idx_C = 0;\n          convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\n          \n          BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\n          \n          BOOST_CHECK(S.m_v[idx_A] == a); \n          BOOST_CHECK(S.m_a[idx_A] == a);\n          BOOST_CHECK(S.m_b[idx_A] == a);\n          \n          BOOST_CHECK(S.m_v[idx_B] == b);\n          BOOST_CHECK(S.m_a[idx_B] == b);\n          BOOST_CHECK(S.m_b[idx_B] == b);\n          \n          BOOST_CHECK(S.m_v[idx_C] == c);\n          BOOST_CHECK(S.m_a[idx_C] == c);\n          BOOST_CHECK(S.m_b[idx_C] == c);\n          BOOST_CHECK_CLOSE(S.m_w[idx_A], u, 0.01);\n          BOOST_CHECK_CLOSE(S.m_w[idx_B], v, 0.01);\n          BOOST_CHECK_CLOSE(S.m_w[idx_C], w, 0.01);\n          \n        }\n  }\n  // First we create a simplex that represents an triangle\n  vector3_type const a = vector3_type::make(-1.0, -1.0, 0.0);\n  vector3_type const b = vector3_type::make( 1.0, -1.0, 0.0);\n  vector3_type const c = vector3_type::make( 0.0,  1.0, 0.0);\n  \n  // Inside face-region new simplex should be ABC\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = vector3_type::make( 0.0, 0.0,  0.0);\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 3u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    int bit_C    = 0;\n    size_t idx_C = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\n    \n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    \n    BOOST_CHECK(S.m_v[idx_B] == b);\n    BOOST_CHECK(S.m_a[idx_B] == b);\n    BOOST_CHECK(S.m_b[idx_B] == b);\n    \n    BOOST_CHECK(S.m_v[idx_C] == c);\n    BOOST_CHECK(S.m_a[idx_C] == c);\n    BOOST_CHECK(S.m_b[idx_C] == c);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.25, 0.01);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.25, 0.01);\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.5, 0.01);\n  }\n  // Inside A voronoi region new simplex should be A\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = vector3_type::make( -2.0, -1.0,  1.0);\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 1u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );\n    \n    BOOST_CHECK(S.m_bitmask == bit_A);\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\n  }\n  // Inside B voronoi region new simplex should be B\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = vector3_type::make(  2.0, -1.0,  1.0);\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 1u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );\n    \n    BOOST_CHECK(S.m_bitmask == bit_A);\n    BOOST_CHECK(S.m_v[idx_A] == b);\n    BOOST_CHECK(S.m_a[idx_A] == b);\n    BOOST_CHECK(S.m_b[idx_A] == b);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.00, 0.01);\n  }\n  // Inside C voronoi region new simplex should be C\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = vector3_type::make(  0.0, 2.0,  1.0);\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 1u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A  );\n    \n    BOOST_CHECK(S.m_bitmask == bit_A);\n    BOOST_CHECK(S.m_v[idx_A] == c);\n    BOOST_CHECK(S.m_a[idx_A] == c);\n    BOOST_CHECK(S.m_b[idx_A] == c);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\n  }\n  // Inside AB voronoi region new simplex should be AB\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = vector3_type::make( 0.0, -2.0,  1.0);\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 2u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n    \n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    \n    BOOST_CHECK(S.m_v[idx_B] == b);\n    BOOST_CHECK(S.m_a[idx_B] == b);\n    BOOST_CHECK(S.m_b[idx_B] == b);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\n  }\n  // Inside BC voronoi region new simplex should be BC\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = vector3_type::make( 1.5, 0.5,  1.0);\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 2u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n    \n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\n    BOOST_CHECK(S.m_v[idx_A] == b);\n    BOOST_CHECK(S.m_a[idx_A] == b);\n    BOOST_CHECK(S.m_b[idx_A] == b);\n    \n    BOOST_CHECK(S.m_v[idx_B] == c);\n    BOOST_CHECK(S.m_a[idx_B] == c);\n    BOOST_CHECK(S.m_b[idx_B] == c);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\n  }\n  // Inside AC voronoi region new simplex should be AC\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = vector3_type::make( -1.5, 0.5,  1.0);\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 2u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n    \n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    \n    BOOST_CHECK(S.m_v[idx_B] == c);\n    BOOST_CHECK(S.m_a[idx_B] == c);\n    BOOST_CHECK(S.m_b[idx_B] == c);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\n  }\n  // On vertex A new simplex should be A\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    convex::reduce_triangle( a, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 1u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );\n    \n    BOOST_CHECK(S.m_bitmask == bit_A);\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\n  }\n  // On vertex B new simplex should be B\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    convex::reduce_triangle( b, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 1u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );\n    \n    BOOST_CHECK(S.m_bitmask == bit_A);\n    BOOST_CHECK(S.m_v[idx_A] == b);\n    BOOST_CHECK(S.m_a[idx_A] == b);\n    BOOST_CHECK(S.m_b[idx_A] == b);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.00, 0.01);\n  }\n  // On vertex C new simplex should be C\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    convex::reduce_triangle( c, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 1u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A  );\n    \n    BOOST_CHECK(S.m_bitmask == bit_A);\n    BOOST_CHECK(S.m_v[idx_A] == c);\n    BOOST_CHECK(S.m_a[idx_A] == c);\n    BOOST_CHECK(S.m_b[idx_A] == c);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\n  }\n  // On edge AB new simplex should be AB\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = vector3_type::make( 0.0, -1.0,  1.0);\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 2u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n    \n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    \n    BOOST_CHECK(S.m_v[idx_B] == b);\n    BOOST_CHECK(S.m_a[idx_B] == b);\n    BOOST_CHECK(S.m_b[idx_B] == b);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\n  }\n  // On edge BC new simplex should be BC\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = vector3_type::make( 0.5, 0.0,  1.0);// this point is inside the triangle?!\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 2u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n    \n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\n    BOOST_CHECK(S.m_v[idx_A] == b);\n    BOOST_CHECK(S.m_a[idx_A] == b);\n    BOOST_CHECK(S.m_b[idx_A] == b);\n    \n    BOOST_CHECK(S.m_v[idx_B] == c);\n    BOOST_CHECK(S.m_a[idx_B] == c);\n    BOOST_CHECK(S.m_b[idx_B] == c);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\n  }\n  // On edge AC new simplex should be AC\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = vector3_type::make( -0.5, 0.0,  1.0);\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 2u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n    \n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    \n    BOOST_CHECK(S.m_v[idx_B] == c);\n    BOOST_CHECK(S.m_a[idx_B] == c);\n    BOOST_CHECK(S.m_b[idx_B] == c);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\n  }\n  // Assymmetric test cases\n  \n  // New simplex should be AB\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = 0.4*a + 0.6*b;\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 2u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n    \n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    \n    BOOST_CHECK(S.m_v[idx_B] == b);\n    BOOST_CHECK(S.m_a[idx_B] == b);\n    BOOST_CHECK(S.m_b[idx_B] == b);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.4, 0.01);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.6, 0.01);\n  }\n  // New simplex should be BC\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = 0.4*b + 0.6*c;// point is inside triangle?!\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 2u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n    \n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\n    BOOST_CHECK(S.m_v[idx_A] == b);\n    BOOST_CHECK(S.m_a[idx_A] == b);\n    BOOST_CHECK(S.m_b[idx_A] == b);\n    \n    BOOST_CHECK(S.m_v[idx_B] == c);\n    BOOST_CHECK(S.m_a[idx_B] == c);\n    BOOST_CHECK(S.m_b[idx_B] == c);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.4, 0.01);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.6, 0.01);\n  }\n  // New simplex should be AC\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = 0.6*a + 0.4*c;\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 2u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n    \n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    \n    BOOST_CHECK(S.m_v[idx_B] == c);\n    BOOST_CHECK(S.m_a[idx_B] == c);\n    BOOST_CHECK(S.m_b[idx_B] == c);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.6, 0.01);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.4, 0.01);\n  }\n  // New simplex should be ABC\n  {\n    simplex_type S;\n    \n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n    convex::add_point_to_simplex( c, c, c, S);\n    \n    vector3_type const p = 0.1*a + 0.2*b + 0.7*c;\n    \n    convex::reduce_triangle( p, S );\n    \n    BOOST_CHECK( convex::dimension( S ) == 3u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    int bit_C    = 0;\n    size_t idx_C = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\n    \n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    \n    BOOST_CHECK(S.m_v[idx_B] == b);\n    BOOST_CHECK(S.m_a[idx_B] == b);\n    BOOST_CHECK(S.m_b[idx_B] == b);\n    \n    BOOST_CHECK(S.m_v[idx_C] == c);\n    BOOST_CHECK(S.m_a[idx_C] == c);\n    BOOST_CHECK(S.m_b[idx_C] == c);\n    \n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.1, 0.01);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.2, 0.01);\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.7, 0.01);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b1ab901c9b73f16ae7949b9c7bf9310797ef96e7", "size": 17464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/CONVEX/unit_tests/convex_reduce_triangle/convex_reduce_triangle.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/CONVEX/unit_tests/convex_reduce_triangle/convex_reduce_triangle.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/CONVEX/unit_tests/convex_reduce_triangle/convex_reduce_triangle.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": 29.0582362729, "max_line_length": 120, "alphanum_fraction": 0.5803939533, "num_tokens": 5858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5125615387252128}}
{"text": "/**\n * @file k_means_clustering_long_test.cpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2014-09-14\n */\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/read_two_dimensional_data.hpp\"\n#include \"test_utils/test_result_check.hpp\"\n#include \"test_utils/get_test_dir.hpp\"\n#include \"test_utils/system.hpp\"\n\n#include \"paal/clustering/k_means_clustering.hpp\"\n#include \"paal/utils/parse_file.hpp\"\n#include \"paal/utils/type_functions.hpp\"\n\n#include <boost/range/algorithm/max_element.hpp>\n\n#include <iostream>\n#include <algorithm>\n\nconst bool PRINT_SVG = false;\n\ninline auto scale(double e, double max_value) { return e / max_value * 1e3; };\n\ntemplate <class Stream> struct print_svg_visitor : public paal::k_means_visitor {\n    print_svg_visitor(Stream &stream, double max_value) : m_stream(stream), m_max_value(max_value) {};\n    template <class Center, class New_center>\n    void move_center(Center &&last_center, New_center &&new_center) {\n        m_stream << \"<line x1=\\\"\" << scale(last_center[0], m_max_value)\n                 <<    \"\\\" y1=\\\"\" << scale(last_center[1], m_max_value)\n                 <<    \"\\\" x2=\\\"\" << scale(new_center[0], m_max_value)\n                 <<    \"\\\" y2=\\\"\" << scale(new_center[1], m_max_value)\n                 << \"\\\" style=\\\"stroke:rgb(255,0,0);stroke-width:1\\\" />\\n\";\n    }\n\n  private:\n\n    Stream &m_stream;\n    double m_max_value;\n};\nBOOST_AUTO_TEST_CASE(k_means_clustering_long_test) {\n    using Point = std::vector<double>;\n\n    std::string test_dir = paal::system::get_test_data_dir(\"CLUSTERING\");\n    using paal::system::build_path;\n    paal::parse(build_path(test_dir, \"index\"),\n                [&](const std::string &fname, std::istream &is_test_cases) {\n\n        LOGLN(\"TEST \" << fname);\n        int number_of_clusters;\n        is_test_cases >> number_of_clusters;\n        std::ifstream ifs(build_path(test_dir, \"/cases/\" + fname + \".txt\"));\n        assert(ifs.good());\n\n        auto points = paal::read_two_dimensional_data<>(ifs);\n\n        std::vector<Point> start_centers;\n        paal::get_random_centers(points,number_of_clusters,back_inserter(start_centers));\n\n        std::vector<std::pair<Point, int>> point_cluster_pair;\n\n        double max_value=0;\n        for(auto point : points){\n            max_value = std::max(max_value, *boost::max_element(point));\n        }\n\n        if(!PRINT_SVG) {\n            auto centers=paal::k_means(points, start_centers,\n                back_inserter(point_cluster_pair));\n            return;\n        }\n\n        std::ofstream ofs (fname+\".svg\", std::ofstream::out);\n        ofs << \"<svg width=\\\"1000\\\" height=\\\"1000\\\">\\n\" <<\n                \"<circle cx=\\\"0\\\" cy=\\\"0\\\" r=\\\"2000\\\" stroke=\\\"green\\\" stroke-width=\\\"0\\\" fill=\\\"black\\\" />\\n\";\n        auto centers=paal::k_means(points, start_centers,\n                back_inserter(point_cluster_pair), print_svg_visitor<std::ofstream>(ofs, max_value));\n\n\n        std::vector<std::string> colors = {\n                                    \"brown\",\n                                    \"burlywood\",\n                                    \"cadetblue\",\n                                    \"chartreuse\",\n                                    \"chocolate\",\n                                    \"coral\",\n                                    \"cornflowerblue\",\n                                    \"cornsilk\",\n                                    \"crimson\",\n                                    \"darkblue\",\n                                    \"darkcyan\",\n                                    \"darkgoldenrod\"\n                                };\n\n        auto scale_1 = [=](double d){ return scale(d, max_value); };\n        for (auto i : point_cluster_pair) {\n            ofs\n                << \"<circle cx=\\\"\" << scale_1(i.first[0])\n                << \"\\\" cy=\\\"\"      << scale_1(i.first[1])\n                << \"\\\" r=\\\"1\\\" stroke=\\\"green\\\" stroke-width=\\\"0\\\" fill=\\\"\"\n                << colors[i.second%colors.size()] << \"\\\" />\"\n                << \"\\n\";\n        }\n        for (auto i : centers) {\n            if(i.size()>1){\n            ofs\n                << \"<circle cx=\\\"\" << scale_1(i[0])\n                << \"\\\" cy=\\\"\"      << scale_1(i[1])\n                << \"\\\" r=\\\"5\\\" stroke=\\\"green\\\" stroke-width=\\\"0\\\" fill=\\\"\"\n                << \"red\" << \"\\\" />\"\n                << \"\\n\";\n                }\n        }\n        ofs << \"</svg>\\n\";\n        ofs.close();\n    });\n\n}\n", "meta": {"hexsha": "a0873c46c974f92be2e8f9f3d97bf8af3cc7b988", "size": 4390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/clustering/k_means_clustering_long_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/clustering/k_means_clustering_long_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/clustering/k_means_clustering_long_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": 35.9836065574, "max_line_length": 111, "alphanum_fraction": 0.5118451025, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5125615359887622}}
{"text": "/**\n *  .file test/oglplus/quaternion.cpp\n *  .brief Test case for Quaternion class and related functionality.\n *\n *  .author Matus Chochlik\n *\n *  Copyright 2011-2019 Matus Chochlik. 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#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE OGLPLUS_Quaternion\n#include <boost/test/unit_test.hpp>\n\n#include <oglplus/gl.hpp>\n#include <oglplus/math/quaternion.hpp>\n\nBOOST_AUTO_TEST_SUITE(Quaternion)\n\nBOOST_AUTO_TEST_CASE(Quaternion_construction) {\n    using Quatf = oglplus::Quaternion<float>;\n    Quatf q1(1, 0, 0, 0);\n    Quatf q2(oglplus::Vec3f::Unit(0), oglplus::Degrees(45));\n    Quatf q3(0, oglplus::Vec3f::Unit(1));\n    Quatf q4 = q3;\n}\n\nBOOST_AUTO_TEST_CASE(Quaternion_real_imag) {\n    using Quatf = oglplus::Quaternion<float>;\n    Quatf q(1, 2, 3, 4);\n\n    BOOST_CHECK(q.Real() == 1);\n    BOOST_CHECK(q.Imag().x() == 2);\n    BOOST_CHECK(q.Imag().y() == 3);\n    BOOST_CHECK(q.Imag().z() == 4);\n}\n\nBOOST_AUTO_TEST_CASE(Quaternion_real_imag_at) {\n    using Quatf = oglplus::Quaternion<float>;\n    Quatf q(1, 2, 3, 4);\n\n    BOOST_CHECK(q.Real() == q.At(0));\n    BOOST_CHECK(q.Imag().x() == q.At(1));\n    BOOST_CHECK(q.Imag().y() == q.At(2));\n    BOOST_CHECK(q.Imag().z() == q.At(3));\n}\n\nBOOST_AUTO_TEST_CASE(Quaternion_equality) {\n    using Quatf = oglplus::Quaternion<float>;\n    Quatf q1(1, 0, 0, 0);\n    Quatf q2 = q1;\n    Quatf q3(1, 2, 3, 4);\n\n    BOOST_CHECK(Equal(q1, q2));\n    BOOST_CHECK(Equal(q2, q1));\n    BOOST_CHECK(q1 == q2);\n    BOOST_CHECK(q2 == q1);\n\n    BOOST_CHECK(!Equal(q1, q3));\n    BOOST_CHECK(!Equal(q3, q2));\n    BOOST_CHECK(q1 != q3);\n    BOOST_CHECK(q3 != q2);\n}\n\nBOOST_AUTO_TEST_CASE(Quaternion_dot) {\n    using Quatf = oglplus::Quaternion<float>;\n    Quatf q0(1, 2, 3, 4);\n    Quatf q1(1, 0, 0, 0);\n    Quatf q2(0, 1, 0, 0);\n    Quatf q3(0, 0, 1, 0);\n    Quatf q4(0, 0, 0, 1);\n    BOOST_CHECK(Dot(q0, q0) == 1 * 1 + 2 * 2 + 3 * 3 + 4 * 4);\n    BOOST_CHECK(Dot(q0, q1) == 1);\n    BOOST_CHECK(Dot(q0, q2) == 2);\n    BOOST_CHECK(Dot(q0, q3) == 3);\n    BOOST_CHECK(Dot(q0, q4) == 4);\n    BOOST_CHECK(Dot(q1, q2) == 0);\n    BOOST_CHECK(Dot(q2, q3) == 0);\n    BOOST_CHECK(Dot(q3, q4) == 0);\n    BOOST_CHECK(Dot(q4, q1) == 0);\n}\n\nBOOST_AUTO_TEST_CASE(Quaternion_is_degenerate) {\n    using Quatf = oglplus::Quaternion<float>;\n    BOOST_CHECK(Quatf(0, 0, 0, 0).IsDegenerate());\n}\n\nBOOST_AUTO_TEST_CASE(Quaternion_is_normal) {\n    using Quatf = oglplus::Quaternion<float>;\n    using oglplus::Degrees;\n    using oglplus::Vec3f;\n    int deg[5] = {0, 90, 180, 270, 360};\n    float eps = 1e-7f;\n    for(int i = 0; i != 5; ++i) {\n        BOOST_CHECK(Quatf(Vec3f::Unit(0), Degrees(deg[i])).IsNormal(eps));\n        BOOST_CHECK(Quatf(Vec3f::Unit(1), Degrees(deg[i])).IsNormal(eps));\n        BOOST_CHECK(Quatf(Vec3f::Unit(2), Degrees(deg[i])).IsNormal(eps));\n    }\n    for(int i = 0; i != 1000; ++i) {\n        float rdeg = (float(std::rand()) / RAND_MAX - 0.5f);\n        BOOST_CHECK(Quatf(Vec3f::Unit(0), Degrees(rdeg)).IsNormal(eps));\n        BOOST_CHECK(Quatf(Vec3f::Unit(1), Degrees(rdeg)).IsNormal(eps));\n        BOOST_CHECK(Quatf(Vec3f::Unit(2), Degrees(rdeg)).IsNormal(eps));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Quaternion_normalize) {\n    using Quatd = oglplus::Quaternion<double>;\n    double eps = 1e-15;\n    for(int i = 0; i < 1000; ++i) {\n        Quatd q(\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5));\n        if(!q.IsDegenerate()) {\n            q.Normalize();\n            BOOST_CHECK(q.IsNormal(eps));\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Quaternion_conjugate) {\n    using Quatf = oglplus::Quaternion<float>;\n    for(int i = 0; i < 1000; ++i) {\n        Quatf q(\n          (float(std::rand()) / RAND_MAX - 0.5f),\n          (float(std::rand()) / RAND_MAX - 0.5f),\n          (float(std::rand()) / RAND_MAX - 0.5f),\n          (float(std::rand()) / RAND_MAX - 0.5f));\n        BOOST_CHECK(q.Real() == Conjugate(q).Real());\n        BOOST_CHECK(q.Imag() == -Conjugate(q).Imag());\n        BOOST_CHECK(Equal(q, ~~q));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Quaternion_addition) {\n    using Quatf = oglplus::Quaternion<float>;\n    float eps = 1e-11;\n    for(int i = 0; i < 1000; ++i) {\n        Quatf q1(\n          (float(std::rand()) / RAND_MAX - 0.5f),\n          (float(std::rand()) / RAND_MAX - 0.5f),\n          (float(std::rand()) / RAND_MAX - 0.5f),\n          (float(std::rand()) / RAND_MAX - 0.5f));\n        Quatf q2(\n          (float(std::rand()) / RAND_MAX - 0.5f),\n          (float(std::rand()) / RAND_MAX - 0.5f),\n          (float(std::rand()) / RAND_MAX - 0.5f),\n          (float(std::rand()) / RAND_MAX - 0.5f));\n        BOOST_CHECK_CLOSE((q1 + q2).Real(), (q1.Real() + q2.Real()), eps);\n        BOOST_CHECK((q1 + q2).Imag() == (q1.Imag() + q2.Imag()));\n        BOOST_CHECK((q1 + q2) == (q2 + q1));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Quaternion_multiplication) {\n    using Quatd = oglplus::Quaternion<double>;\n    double eps = 1e-11;\n    for(int i = 0; i < 1000; ++i) {\n        Quatd q1(\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5));\n        Quatd q2(\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5));\n        Quatd q3(\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5));\n        Quatd q4(\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5),\n          (double(std::rand()) / RAND_MAX - 0.5));\n        BOOST_CHECK(Close(q1 * q2 * q3 * q4, (q1 * q2) * (q3 * q4), eps));\n        BOOST_CHECK(Close(q1 * q2 * q3 * q4, q1 * (q2 * q3) * q4, eps));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "31f89b3024e33866f3e9ef91238031403e81b776", "size": 6249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/oglplus/quaternion.cpp", "max_stars_repo_name": "matus-chochlik/oglplus", "max_stars_repo_head_hexsha": "76dd964e590967ff13ddff8945e9dcf355e0c952", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 364.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T09:38:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:32:00.000Z", "max_issues_repo_path": "test/oglplus/quaternion.cpp", "max_issues_repo_name": "matus-chochlik/oglplus", "max_issues_repo_head_hexsha": "76dd964e590967ff13ddff8945e9dcf355e0c952", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 55.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T16:42:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-09T04:21:41.000Z", "max_forks_repo_path": "test/oglplus/quaternion.cpp", "max_forks_repo_name": "matus-chochlik/oglplus", "max_forks_repo_head_hexsha": "76dd964e590967ff13ddff8945e9dcf355e0c952", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 57.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T18:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T05:32:04.000Z", "avg_line_length": 33.4171122995, "max_line_length": 74, "alphanum_fraction": 0.5644103056, "num_tokens": 2153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5125615334535489}}
{"text": "#ifndef MP_PAGERANK_HPP\n#define MP_PAGERANK_HPP\n\n#include \"defs.hpp\"\n#include \"tools/iter.hpp\"\n\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_concepts.hpp>\n\nnamespace mp {\n\nnamespace detail {\n\n/*\n * Params:\n *  g            - The bidirectional Graph (read-only).\n *  from_rank    - The page-rank of the last step (read-only).\n *  to_rank      - The page-rank of the next iteration (write-only).\n *  damping      - The damping factor.\n *  sinks        - A Collection of sinks (vertices without outgoing edges; read-only).\n *  weight       - A mapping from edge-descriptor to edge-weight (read-only).\n *  total_weight - A mapping from vertex-descriptor to the sum of all edge-weights beginning at that vertex (read-only).\n */\ntemplate<typename Graph, typename RankMap1, typename RankMap2, typename SinkCollection, typename EdgeWeightMap, typename TotalWeightMap>\nvoid page_rank_step(const Graph &g,\n                    RankMap1 from_rank, RankMap2 to_rank, typename boost::property_traits<RankMap1>::value_type damping,\n                    const SinkCollection &sinks, EdgeWeightMap weight, TotalWeightMap total_weight)\n{\n    using rank_type = typename boost::property_traits<RankMap1>::value_type;\n\n    // Iterate over all vertices and their incoming edges.\n    for (auto vertex : make_iter_range(vertices(g))) {\n        rank_type rank(0);\n\n        // Consider all incoming edges.\n        // Sources of these edges give the current vertex a part of their\n        // rank, according to the edge's weight.\n        for(auto edge : make_iter_range(in_edges(vertex, g)))  {\n            auto vertex_source = source(edge, g);\n\n            // Using this coefficient instead of 1/out_degree(vertex_source)\n            // to support weighted edges.\n            rank_type coeff = rank_type(get(weight, edge)) / rank_type(get(total_weight, vertex_source));\n            rank += get(from_rank, vertex_source) * coeff;\n        }\n\n        // Treat all \"sinks\" as incoming edges, too.\n        for (auto sink : sinks) {\n            // Sinks distribute their rank evenly.\n            rank += get(from_rank, sink) / num_vertices(g);\n        }\n\n        rank = ((rank_type(1) - damping) / num_vertices(g)) + damping * rank;\n        put(to_rank, vertex, rank);\n    }\n}\n\n} // namespace datail\n\n/**\n  * Computes PageRank for the given Graph.\n  *\n  * The algorithm will run until the StopPredicate returns true.\n  *\n  * \\param g\n  *      The Graph\n  * \\param[out] rank\n  *      A map from vertex to rank. Will store the output once the function returns.\n  * \\param damping\n  *     The damping factor. Between 0 and 1.\n  * \\param weight\n  *     A map from edge descriptor to edge weight. Values will be normalized by this function.\n  * \\param stop\n  *     The predicate.\n  */\n// Vertex index: http://www.boost.org/doc/libs/1_56_0/libs/graph/doc/faq.html (item 5)\ntemplate<typename Graph, typename RankMap, typename EdgeWeightMap, typename StopPredicate>\nvoid page_rank(const Graph &g,\n               RankMap rank, typename boost::property_traits<RankMap>::value_type damping,\n               EdgeWeightMap weight,\n               StopPredicate &&stop)\n{\n    using graph_traits       = boost::graph_traits<Graph>;\n    using edge_descriptor    = typename graph_traits::edge_descriptor;\n    using vertex_descriptor  = typename graph_traits::vertex_descriptor;\n    using rank_type          = typename boost::property_traits<RankMap>::value_type;\n    using weight_type        = typename boost::property_traits<EdgeWeightMap>::value_type;\n\n    BOOST_CONCEPT_ASSERT(( boost::BidirectionalGraphConcept<Graph> ));\n    BOOST_CONCEPT_ASSERT(( boost::ReadWritePropertyMapConcept<RankMap, vertex_descriptor> ));\n    BOOST_CONCEPT_ASSERT(( boost::ReadablePropertyMapConcept<EdgeWeightMap, edge_descriptor> ));\n\n    // The start rank of every vertex is 1/n\n    // where n is the number of vertices.\n    {\n        rank_type start(rank_type(1) / num_vertices(g));\n\n        for (auto vertex : make_iter_range(vertices(g))) {\n            put(rank, vertex, start);\n        }\n    }\n\n    auto indices = get(boost::vertex_index, g);\n\n    // A second rank_map to store the ranks of the previous or next iteration.\n    std::vector<rank_type> aux_rank_vector(num_vertices(g));\n    auto aux_rank = boost::make_iterator_property_map(\n                aux_rank_vector.begin(), indices);\n\n    // For every vertex, compute the total of its outgoing edges' weights.\n    std::vector<weight_type> total_weight_vector(num_vertices(g));\n    auto total_weight = boost::make_iterator_property_map(\n                total_weight_vector.begin(), indices);\n    {\n        for (auto vertex : make_iter_range(vertices(g))) {\n            weight_type total(0);\n\n            for(auto edge : make_iter_range(out_edges(vertex, g))) {\n                total += get(weight, edge);\n            }\n\n            put(total_weight, vertex, total);\n        }\n    }\n\n    // Collection of \"sinks\" - vertices that have no outgoing edges.\n    std::vector<vertex_descriptor> sinks;\n    {\n        for (auto vertex : make_iter_range(vertices(g))) {\n            if (out_degree(vertex, g) == 0) {\n                sinks.push_back(vertex);\n            }\n        }\n    }\n\n    bool toggle = true;\n    while (1) {\n        if (toggle) {\n            if (stop(rank, g)) {\n                break;\n            }\n\n            detail::page_rank_step(g, rank, aux_rank, damping, sinks, weight, total_weight);\n        } else {\n            if (stop(aux_rank, g)) {\n                break;\n            }\n\n            detail::page_rank_step(g, aux_rank, rank, damping, sinks, weight, total_weight);\n        }\n\n        toggle = !toggle;\n    }\n\n    if (!toggle) {\n        // Copy results from \"aux_rank\" to \"rank\".\n        for (auto vertex : make_iter_range(vertices(g))) {\n            put(rank, vertex, get(aux_rank, vertex));\n        }\n    }\n}\n\n} // namespace mp\n\n#endif // MP_PAGERANK_HPP\n", "meta": {"hexsha": "dd6f85533f45577556842e877fb8f6c59231a6f2", "size": 5978, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mp/page_rank.hpp", "max_stars_repo_name": "mbeckem/mp", "max_stars_repo_head_hexsha": "872325079269143386f71195ec14019eb7ff59a2", "max_stars_repo_licenses": ["MIT"], "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/mp/page_rank.hpp", "max_issues_repo_name": "mbeckem/mp", "max_issues_repo_head_hexsha": "872325079269143386f71195ec14019eb7ff59a2", "max_issues_repo_licenses": ["MIT"], "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/mp/page_rank.hpp", "max_forks_repo_name": "mbeckem/mp", "max_forks_repo_head_hexsha": "872325079269143386f71195ec14019eb7ff59a2", "max_forks_repo_licenses": ["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.5833333333, "max_line_length": 136, "alphanum_fraction": 0.6396788223, "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5125615334535488}}
{"text": "#pragma once\n\n#include <boost/optional.hpp>\n\n#include <random>\n#include <algorithm>\n#include <vector>\n#include <list>\n\nnamespace roerei\n{\n\nclass partition\n{\nprivate:\n\tpartition() = delete;\n\npublic:\n\tstatic std::vector<size_t> generate_bare(size_t n, size_t parts, boost::optional<uint64_t> seed = boost::none)\n\t{\n\t\tstd::vector<size_t> result(n);\n\n\t\tauto it = result.begin();\n\t\tsize_t remaining = n;\n\t\tfor(size_t parts_left = parts; parts_left > 0; parts_left--)\n\t\t{\n\t\t\tsize_t size = remaining / parts_left;\n\t\t\tif(remaining % parts_left > 0)\n\t\t\t\tsize++;\n\n\t\t\tremaining -= size;\n\t\t\tit = std::fill_n(it, size, parts - parts_left);\n\t\t}\n\n\t\tassert(it == result.end());\n\n\t\tif(!seed)\n\t\t{\n\t\t\tstd::random_device rd;\n\t\t\tseed = rd();\n\t\t}\n\n\t\tstd::mt19937 g(*seed);\n\t\tstd::shuffle(result.begin(), result.end(), g);\n\n\t\treturn result;\n\t}\n};\n\n}\n", "meta": {"hexsha": "4701d003c6f581ca15ac8673c0e34d224b8feaba", "size": 827, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/roerei/partition.hpp", "max_stars_repo_name": "Wassasin/roerei", "max_stars_repo_head_hexsha": "78a6b91819cc37fd7ac25a209f18a3f97c5db2f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-11T14:57:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-11T14:57:25.000Z", "max_issues_repo_path": "src/roerei/partition.hpp", "max_issues_repo_name": "Wassasin/roerei", "max_issues_repo_head_hexsha": "78a6b91819cc37fd7ac25a209f18a3f97c5db2f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/roerei/partition.hpp", "max_forks_repo_name": "Wassasin/roerei", "max_forks_repo_head_hexsha": "78a6b91819cc37fd7ac25a209f18a3f97c5db2f5", "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.2156862745, "max_line_length": 111, "alphanum_fraction": 0.6457073761, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5125615334535488}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <Eigen/Core>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/eigen/vector.hpp>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\ntypedef double real;\ntypedef std::complex<real> complex;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef ublas::vector<real> vector;\n    typedef ublas::matrix<real> matrix;\n    typedef vector::size_type size_type;\n    rand_normal<real>::reset();\n    size_type n=8;\n    vector v1(n), v2(n);\n    for (size_type i=0; i<n; ++i)\n      v1(i)=rand_normal<real>::get();\n    for (size_type i=0; i<n; ++i)\n      v2(i)=rand_normal<real>::get();\n    matrix M1(n, n), M2(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i) {\n    \tM1(i, j)=0;\n    \tM2(i, j)=0;\n      }\n    ublas::matrix_column<matrix> mc(M1, 2);\n    ublas::matrix_row<matrix> mr(M2, 3);\n    mc=v1;\n    mr=v2;\n    std::cout << \"ublas using vectors    : dot(v1, v2) = \" << ublas::inner_prod(v1, v2) << '\\n'\n\t      << \"blas using vectors     : dot(v1, v2) = \" << blas::dot(v1, v2) << '\\n'\n\t      << \"blas using cols & rows : dot(v1, v2) = \" << blas::dot(mc, mr) << '\\n'\n\t      << \"blas using vectors     : dotu(v1, v2) = \" << blas::dotu(v1, v2) << '\\n'\n\t      << \"blas using cols & rows : dotu(v1, v2) = \" << blas::dotu(mc, mr) << '\\n';\n  }\n  {\n    typedef ublas::vector<complex> vector;\n    typedef ublas::matrix<complex> matrix;\n    typedef vector::size_type size_type;\n    rand_normal<complex>::reset();\n    size_type n=8;\n    vector v1(n), v2(n);\n    for (size_type i=0; i<n; ++i)\n      v1(i)=rand_normal<complex>::get();\n    for (size_type i=0; i<n; ++i)\n      v2(i)=rand_normal<complex>::get();\n    matrix M1(n, n), M2(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i) {\n    \tM1(i, j)=0;\n    \tM2(i, j)=0;\n      }\n    ublas::matrix_column<matrix> mc(M1, 2);\n    ublas::matrix_row<matrix> mr(M2, 3);\n    mc=v1;\n    mr=v2;\n    std::cout << \"ublas using vectors    : dot(v1, v2) = \" << ublas::inner_prod(v1, v2) << '\\n'\n\t      << \"blas using vectors     : dot(v1, v2) = \" << blas::dot(v1, v2) << '\\n'\n\t      << \"blas using cols & rows : dot(v1, v2) = \" << blas::dot(mc, mr) << '\\n'\n\t      << \"blas using vectors     : dotu(v1, v2) = \" << blas::dotu(v1, v2) << '\\n'\n\t      << \"blas using cols & rows : dotu(v1, v2) = \" << blas::dotu(mc, mr) << '\\n';\n  }\n  {\n    typedef Eigen::Matrix<real, Eigen::Dynamic, 1> vector;\n    typedef Eigen::Matrix<real, Eigen::Dynamic, Eigen::Dynamic> matrix;\n    typedef int size_type;\n    rand_normal<real>::reset();\n    size_type n=8;\n    vector v1(n), v2(n);\n    for (size_type i=0; i<n; ++i)\n      v1(i)=rand_normal<real>::get();\n    for (size_type i=0; i<n; ++i)\n      v2(i)=rand_normal<real>::get();\n    matrix M1(n, n), M2(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i) {\n    \tM1(i, j)=0;\n    \tM2(i, j)=0;\n      }\n    auto mc=M1.col(2);\n    auto mr=M2.row(3);\n    mc=v1;\n    mr=v2;\n    std::cout << \"eigen using vectors    : dot(v1, v2) = \" << v1.transpose()*v2 << '\\n'\n\t      << \"blas using vectors     : dot(v1, v2) = \" << blas::dot(v1, v2) << '\\n'\n\t      << \"blas using cols & rows : dot(v1, v2) = \" << blas::dot(mc, mr) << '\\n'\n\t      << \"blas using vectors     : dotu(v1, v2) = \" << blas::dotu(v1, v2) << '\\n'\n\t      << \"blas using cols & rows : dotu(v1, v2) = \" << blas::dotu(mc, mr) << '\\n';\n  }\n  {\n    typedef Eigen::Matrix<complex, Eigen::Dynamic, 1> vector;\n    typedef Eigen::Matrix<complex, Eigen::Dynamic, Eigen::Dynamic> matrix;\n    typedef int size_type;\n    rand_normal<complex>::reset();\n    size_type n=8;\n    vector v1(n), v2(n);\n    for (size_type i=0; i<n; ++i)\n      v1(i)=rand_normal<complex>::get();\n    for (size_type i=0; i<n; ++i)\n      v2(i)=rand_normal<complex>::get();\n    matrix M1(n, n), M2(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i) {\n    \tM1(i, j)=0;\n    \tM2(i, j)=0;\n      }\n    auto mc=M1.col(2);\n    auto mr=M2.row(3);\n    mc=v1;\n    mr=v2;\n    std::cout << \"eigen using vectors    : dot(v1, v2) = \" << v1.transpose()*v2 << '\\n'\n\t      << \"blas using vectors     : dot(v1, v2) = \" << blas::dot(v1, v2) << '\\n'\n\t      << \"blas using cols & rows : dot(v1, v2) = \" << blas::dot(mc, mr) << '\\n'\n\t      << \"blas using vectors     : dotu(v1, v2) = \" << blas::dotu(v1, v2) << '\\n'\n\t      << \"blas using cols & rows : dotu(v1, v2) = \" << blas::dotu(mc, mr) << '\\n';\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "cdb644c666513d0a2eeeec28cee2f8675bda5f79", "size": 4852, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/dot.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/dot.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/dot.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.4812030075, "max_line_length": 95, "alphanum_fraction": 0.5511129431, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.512561532085324}}
{"text": "#define BOOST_TEST_MODULE \"test_expand\"\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 <periortree/boundary_condition.hpp>\n#include <periortree/expand.hpp>\n#include <test/point_type.hpp>\n#include <test/aabb_type.hpp>\n\nBOOST_AUTO_TEST_CASE(test_centroid_unlimited)\n{\n    {\n        const perior::unlimited_boundary<perior::test::xyz> boundary;\n\n        const perior::test::xyz  l1(0., 0., 0.);\n        const perior::test::xyz  u1(5., 5., 5.);\n        const perior::test::aabb box1(l1, u1);\n\n        const perior::test::xyz  l2(2., 2., 2.);\n        const perior::test::xyz  u2(7., 7., 7.);\n        const perior::test::aabb box2(l2, u2);\n\n        perior::test::aabb ex(box1);\n        perior::expand(ex, box2, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.x, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.y, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.z, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.x, 7.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.y, 7.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.z, 7.0, 1e-12);\n    }\n\n    {\n        const perior::unlimited_boundary<perior::test::xyz> boundary;\n\n        const perior::test::xyz  l1(0., 0., 0.);\n        const perior::test::xyz  u1(5., 5., 5.);\n        const perior::test::aabb box1(l1, u1);\n\n        const perior::test::xyz  l2(-1., 2., -1.);\n        const perior::test::xyz  u2( 7., 3.,  5.);\n        const perior::test::aabb box2(l2, u2);\n\n        perior::test::aabb ex(box1);\n        perior::expand(ex, box2, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.x, -1.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.y,  0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.z, -1.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.x,  7.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.y,  5.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.z,  5.0, 1e-12);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_centroid_cubic_periodic)\n{\n    const perior::test::xyz lw(0., 0., 0.);\n    const perior::test::xyz up(10., 10., 10.);\n    const perior::cubic_periodic_boundary<perior::test::xyz> boundary(lw, up);\n    /* inside the boundary */{\n        const perior::test::xyz  l1(0., 0., 0.);\n        const perior::test::xyz  u1(5., 5., 5.);\n        const perior::test::aabb box1(l1, u1);\n\n        const perior::test::xyz  l2(2., 2., 2.);\n        const perior::test::xyz  u2(7., 7., 7.);\n        const perior::test::aabb box2(l2, u2);\n\n        perior::test::aabb ex(box1);\n        perior::expand(ex, box2, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.x, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.y, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.z, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.x, 7.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.y, 7.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.z, 7.0, 1e-12);\n    }\n    /* box includes entry */{\n        const perior::test::xyz  l1(0., 0., 0.);\n        const perior::test::xyz  u1(5., 5., 5.);\n        const perior::test::aabb box1(l1, u1);\n\n        const perior::test::xyz  l2(2., 2., 2.);\n        const perior::test::xyz  u2(3., 3., 3.);\n        const perior::test::aabb box2(l2, u2);\n\n        perior::test::aabb ex(box1);\n        perior::expand(ex, box2, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.x, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.y, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.z, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.x, 5.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.y, 5.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.z, 5.0, 1e-12);\n    }\n    /* entry includes box */{\n        const perior::test::xyz  l1(2., 2., 2.);\n        const perior::test::xyz  u1(3., 3., 3.);\n        const perior::test::aabb box1(l1, u1);\n\n        const perior::test::xyz  l2(0., 0., 0.);\n        const perior::test::xyz  u2(5., 5., 5.);\n        const perior::test::aabb box2(l2, u2);\n\n        perior::test::aabb ex(box1);\n        perior::expand(ex, box2, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.x, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.y, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.z, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.x, 5.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.y, 5.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.z, 5.0, 1e-12);\n    }\n    /* the nearest one is a superposed one */{\n        const perior::test::xyz  l1(0., 0., 0.);\n        const perior::test::xyz  u1(1., 1., 1.);\n        const perior::test::aabb box1(l1, u1);\n\n        const perior::test::xyz  l2( 9.,  9.,  9.);\n        const perior::test::xyz  u2(10., 10., 10.);\n        const perior::test::aabb box2(l2, u2);\n\n        perior::test::aabb ex(box1);\n        perior::expand(ex, box2, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.x, 9.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.y, 9.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.z, 9.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.x, 1.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.y, 1.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.z, 1.0, 1e-12);\n    }\n    /* the nearest one is a superposed one in only 1D */{\n        const perior::test::xyz  l1( 0., 0., 0.);\n        const perior::test::xyz  u1( 1., 1., 1.);\n        const perior::test::aabb box1(l1, u1);\n\n        const perior::test::xyz  l2( 9., 0., 0.);\n        const perior::test::xyz  u2(10., 1., 1.);\n        const perior::test::aabb box2(l2, u2);\n\n        perior::test::aabb ex(box1);\n        perior::expand(ex, box2, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.x, 9.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.y, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.lower.z, 0.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.x, 1.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.y, 1.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(ex.upper.z, 1.0, 1e-12);\n    }\n}\n", "meta": {"hexsha": "aff1429616442a80076ab96e10d1d5d03fb3b592", "size": 6162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_expand.cpp", "max_stars_repo_name": "lasergyro/periortree", "max_stars_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-09-01T14:46:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T11:11:50.000Z", "max_issues_repo_path": "test/test_expand.cpp", "max_issues_repo_name": "lasergyro/periortree", "max_issues_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-02-14T03:37:38.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-14T12:16:29.000Z", "max_forks_repo_path": "test/test_expand.cpp", "max_forks_repo_name": "lasergyro/periortree", "max_forks_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-02-14T03:52:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T15:49:30.000Z", "avg_line_length": 39.5, "max_line_length": 78, "alphanum_fraction": 0.6037000974, "num_tokens": 2171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.512561521541996}}
{"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//\n// Compare arithmetic results using fixed_int to GMP results.\n//\n\n#ifdef _MSC_VER\n#  define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#ifdef TEST_GMP\n#include <boost/multiprecision/gmp.hpp>\n#endif\n#ifdef TEST_MPFR\n#include <boost/multiprecision/mpfr.hpp>\n#endif\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"test.hpp\"\n\ntemplate <class Number, class BigNumber>\nvoid test()\n{\n   using namespace boost::multiprecision;\n   typedef Number test_type;\n\n   test_type a = 1;\n   a /= 3;\n   test_type b = -a;\n\n   BigNumber r;\n   BOOST_CHECK_EQUAL(add(r, a, a), BigNumber(a) + BigNumber(a));\n   BOOST_CHECK_EQUAL(subtract(r, a, b), BigNumber(a) - BigNumber(b));\n   BOOST_CHECK_EQUAL(subtract(r, b, a), BigNumber(b) - BigNumber(a));\n   BOOST_CHECK_EQUAL(multiply(r, a, a), BigNumber(a) * BigNumber(a));\n}\n\nint main()\n{\n   using namespace boost::multiprecision;\n\n   test<cpp_dec_float_50, cpp_dec_float_100>();\n\n#ifdef TEST_GMP\n   test<mpf_float_50, mpf_float_100>();\n#endif\n#ifdef TEST_MPFR\n   test<mpfr_float_50, mpfr_float_100>();\n#endif\n\n   return boost::report_errors();\n}\n", "meta": {"hexsha": "c4223ef7d9c13d31a801e6479255bd8324a4ca14", "size": 1318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/multiprecision/test/test_mixed_float.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/multiprecision/test/test_mixed_float.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/multiprecision/test/test_mixed_float.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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.9636363636, "max_line_length": 69, "alphanum_fraction": 0.68892261, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.512561520173771}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"functions/multiplication.hh\"\n#include \"functions/full_function_defs.hh\"\n#include \"functions/variables.hh\"\n#include \"functions/polynomial.hh\"\n#include \"functions/addition.hh\"\n#include \"functions/operators.hh\"\n#include \"functions/streaming.hh\"\n\nBOOST_AUTO_TEST_CASE(multiplication_test) {\n  using namespace manifolds;\n  Multiplication<decltype(x), decltype(z)> a(x, z);\n\n  BOOST_CHECK_EQUAL(a(1, 2, 3, 4), 3);\n  BOOST_CHECK_EQUAL(a(1, 2, 4, 8, 16), 4);\n\n  auto f = Cos()(x * x) * y;\n  BOOST_CHECK_EQUAL(f(2, 3), std::cos(4.0) * 3);\n  auto f2 = -2_c * x * Sin()(x * x) * y;\n  BOOST_CHECK_EQUAL((-2_c)(1), -2);\n  BOOST_CHECK_EQUAL((-2_c * x * y)(2, 1), -4);\n  BOOST_CHECK_EQUAL((Sin()(x * x))(2), std::sin(4));\n  BOOST_CHECK_EQUAL((-2_c * Sin())(2), -2 * std::sin(2));\n  BOOST_CHECK_EQUAL(f2(2, 1), -4 * std::sin(4));\n}\n", "meta": {"hexsha": "37bc3ae7dca07bc9a9a5ad3fa7030115dab13239", "size": 862, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_multiplication.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_multiplication.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_multiplication.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": 33.1538461538, "max_line_length": 57, "alphanum_fraction": 0.6612529002, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5125615149021071}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef NL_PROBLEM_SEGWAY_HPP_\n#define NL_PROBLEM_SEGWAY_HPP_\n\n#include <Eigen/Dense>\n\n#include \"segway_dynamics.hpp\"\n\n\nstruct SegwayProblem\n{\n  constexpr static std::size_t nx = 7;\n  constexpr static std::size_t nu = 2;\n  constexpr static bool xl_always_feasible = false;\n\n  using state_t = Eigen::Matrix<double, nx, 1>;\n  using deriv_t = state_t;\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  // constants x y psi vel r theta thetaDot\n  const Q_t Q = (state_t() << 10., 0.001, 0.0, 1., 0.001, 1.0, 0.1).finished().asDiagonal();\n  const R_t R = Eigen::Vector2d(1, 0.1).asDiagonal();\n  const Q_t QT = Q;\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 segway_dynamics<T1, T2>(x, u);\n  }\n\n  void get_state_lb(double, Eigen::Ref<state_t> state_lb) const\n  {\n    state_lb <<\n      -100.,\n      -100.,\n      -6.2832,\n      -10.,\n      -31.416,\n      -6.2832,\n      -31.416;\n  }\n\n  void get_state_ub(double, Eigen::Ref<state_t> state_ub) const\n  {\n    state_ub <<\n      100.,\n      100.,\n      6.2832,\n      10.,\n      31.416,\n      6.2832,\n      31.416;\n  }\n\n  void get_input_lb(double, Eigen::Ref<input_t> input_lb) const\n  {\n    input_lb << -15, -15;\n  }\n\n  void get_input_ub(double, Eigen::Ref<input_t> input_ub) const\n  {\n    input_ub << 15, 15;\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\n#endif  // NL_PROBLEM_SEGWAY_HPP_\n", "meta": {"hexsha": "e99bdd2747edb90cf531a03a4591422f2d902fd1", "size": 2006, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/segway_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/segway_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/segway_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": 23.0574712644, "max_line_length": 92, "alphanum_fraction": 0.6321036889, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6688802735722129, "lm_q1q2_score": 0.5125587016239845}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"algorithms/math/evaluate_reverse_polish_notation.hpp\"\n\nBOOST_AUTO_TEST_SUITE(TestEvaluateReversePolishNotation)\n\nBOOST_AUTO_TEST_CASE(no_tokens)\n{\n    const std::vector<std::string> tokens;\n    const int expected = 0;\n    BOOST_CHECK(expected == Algo::Math::ReversePolishNotation::evaluate(tokens));\n}\n\nBOOST_AUTO_TEST_CASE(addition_of_two_values)\n{\n    const std::vector<std::string> tokens = {\"5\", \"890\", \"+\"};\n    const int expected = 895;\n    BOOST_CHECK(expected == Algo::Math::ReversePolishNotation::evaluate(tokens));\n}\n\nBOOST_AUTO_TEST_CASE(subtraction_of_two_values)\n{\n    const std::vector<std::string> tokens = {\"-1\", \"-7\", \"-\"};\n    const int expected = 6;\n    BOOST_CHECK(expected == Algo::Math::ReversePolishNotation::evaluate(tokens));\n}\n\nBOOST_AUTO_TEST_CASE(multiplication_of_two_values)\n{\n    const std::vector<std::string> tokens = {\"-1\", \"10\", \"*\"};\n    const int expected = -10;\n    BOOST_CHECK(expected == Algo::Math::ReversePolishNotation::evaluate(tokens));\n}\n\nBOOST_AUTO_TEST_CASE(division_of_two_values)\n{\n    {\n        const std::vector<std::string> tokens = {\"1\", \"1\", \"/\"};\n        const int expected = 1;\n        BOOST_CHECK(expected == Algo::Math::ReversePolishNotation::evaluate(tokens));\n    }\n\n    {\n        const std::vector<std::string> tokens = {\"7\", \"3\", \"/\"};\n        const int expected = 2;\n        BOOST_CHECK(expected == Algo::Math::ReversePolishNotation::evaluate(tokens));\n    }\n\n    {\n        const std::vector<std::string> tokens = {\"1\", \"3\", \"/\"};\n        const int expected = 0;\n        BOOST_CHECK(expected == Algo::Math::ReversePolishNotation::evaluate(tokens));\n    }\n\n    {\n        const std::vector<std::string> tokens = {\"0\", \"5\", \"/\"};\n        const int expected = 0;\n        BOOST_CHECK(expected == Algo::Math::ReversePolishNotation::evaluate(tokens));\n    }\n\n    {\n        const std::vector<std::string> tokens = {\"12\", \"0\", \"/\"};\n        const int expected = 0;\n        BOOST_CHECK(expected == Algo::Math::ReversePolishNotation::evaluate(tokens));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(long_valid_expession)\n{\n    {\n        const std::vector<std::string> tokens = {\"2\", \"1\", \"+\", \"3\", \"*\"};\n        const int expected = 9;\n        BOOST_CHECK(expected == Algo::Math::ReversePolishNotation::evaluate(tokens));\n    }\n\n    {\n        const std::vector<std::string> tokens = {\"4\", \"13\", \"5\", \"/\", \"+\"};\n        const int expected = 6;\n        BOOST_CHECK(expected == Algo::Math::ReversePolishNotation::evaluate(tokens));\n    }\n\n    {\n        const std::vector<std::string> tokens =\n            {\"10\", \"6\", \"9\", \"3\", \"+\", \"-11\", \"*\", \"/\", \"*\", \"17\", \"+\", \"5\", \"+\"};\n        const int expected = 22;\n        BOOST_CHECK(expected == Algo::Math::ReversePolishNotation::evaluate(tokens));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ba4b151db968aa96b13177c21a6e8bf7d4fc1c59", "size": 2812, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/math/test_evaluate_reverse_polish_notation.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_evaluate_reverse_polish_notation.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_evaluate_reverse_polish_notation.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": 31.2444444444, "max_line_length": 85, "alphanum_fraction": 0.6209103841, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604181, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5125586986479199}}
{"text": "/* Author: Wolfgang Bangerth, Texas A&M University, 2005, 2006 */\n\n/*    $Id: step-20.cc 28518 2013-02-21 20:26:17Z bangerth $       */\n/*                                                                */\n/*    Copyright (C) 2005-2008, 2010-2013 by the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n// @sect3{Include files}\n\n// Since this program is only an adaptation of step-4, there is not much new\n// stuff in terms of header files. In deal.II, we usually list include files\n// in the order base-lac-grid-dofs-fe-numerics, followed by C++ standard\n// include files:\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/function.h>\n#include <deal.II/lac/block_vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/block_sparse_matrix.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n// For our Schur complement solver, we need two new objects. One is a matrix\n// object which acts as the inverse of a matrix by calling an iterative\n// solver.\n#include <deal.II/lac/iterative_inverse.h>\n\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_renumbering.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_dgq.h>\n#include <deal.II/fe/fe_system.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\n#include <fstream>\n#include <iostream>\n\n// This is the only significant new header, namely the one in which the\n// Raviart-Thomas finite element is declared:\n#include <deal.II/fe/fe_raviart_thomas.h>\n\n// Finally, as a bonus in this program, we will use a tensorial\n// coefficient. Since it may have a spatial dependence, we consider it a\n// tensor-valued function. The following include file provides the\n// <code>TensorFunction</code> class that offers such functionality:\n#include <deal.II/base/tensor_function.h>\n\n// The last step is as in all previous programs:\nnamespace Step20\n{\n  using namespace dealii;\n\n  // @sect3{The <code>MixedLaplaceProblem</code> class template}\n\n  // Again, since this is an adaptation of step-6, the main class is almost\n  // the same as the one in that tutorial program. In terms of member\n  // functions, the main differences are that the constructor takes the degree\n  // of the Raviart-Thomas element as an argument (and that there is a\n  // corresponding member variable to store this value) and the addition of\n  // the <code>compute_error</code> function in which, no surprise, we will\n  // compute the difference between the exact and the numerical solution to\n  // determine convergence of our computations:\n  template <int dim>\n  class MixedLaplaceProblem\n  {\n  public:\n    MixedLaplaceProblem (const unsigned int degree);\n    void run ();\n\n  private:\n    void make_grid_and_dofs ();\n    void assemble_system ();\n    void solve ();\n    void compute_errors () const;\n    void output_results () const;\n\n    const unsigned int   degree;\n\n    Triangulation<dim>   triangulation;\n    FESystem<dim>        fe;\n    DoFHandler<dim>      dof_handler;\n\n    // The second difference is that the sparsity pattern, the system matrix,\n    // and solution and right hand side vectors are now blocked. What this\n    // means and what one can do with such objects is explained in the\n    // introduction to this program as well as further down below when we\n    // explain the linear solvers and preconditioners for this problem:\n    BlockSparsityPattern      sparsity_pattern;\n    BlockSparseMatrix<double> system_matrix;\n\n    BlockVector<double>       solution;\n    BlockVector<double>       system_rhs;\n  };\n\n\n  // @sect3{Right hand side, boundary values, and exact solution}\n\n  // Our next task is to define the right hand side of our problem (i.e., the\n  // scalar right hand side for the pressure in the original Laplace\n  // equation), boundary values for the pressure, as well as a function that\n  // describes both the pressure and the velocity of the exact solution for\n  // later computations of the error. Note that these functions have one, one,\n  // and <code>dim+1</code> components, respectively, and that we pass the\n  // number of components down to the <code>Function@<dim@></code> base\n  // class. For the exact solution, we only declare the function that actually\n  // returns the entire solution vector (i.e. all components of it) at\n  // once. Here are the respective declarations:\n  template <int dim>\n  class RightHandSide : public Function<dim>\n  {\n  public:\n    RightHandSide () : Function<dim>(1) {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n\n\n  template <int dim>\n  class PressureBoundaryValues : public Function<dim>\n  {\n  public:\n    PressureBoundaryValues () : Function<dim>(1) {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n\n  template <int dim>\n  class ExactSolution : public Function<dim>\n  {\n  public:\n    ExactSolution () : Function<dim>(dim+1) {}\n\n    virtual void vector_value (const Point<dim> &p,\n                               Vector<double>   &value) const;\n  };\n\n\n  // And then we also have to define these respective functions, of\n  // course. Given our discussion in the introduction of how the solution\n  // should look like, the following computations should be straightforward:\n  template <int dim>\n  double RightHandSide<dim>::value (const Point<dim>  & /*p*/,\n                                    const unsigned int /*component*/) const\n  {\n    return 0;\n  }\n\n\n\n  template <int dim>\n  double PressureBoundaryValues<dim>::value (const Point<dim> &p,\n                                             const unsigned int /*component*/) const\n  {\n    const double alpha = 0.3;\n    const double beta = 1;\n    return -(alpha*p[0]*p[1]*p[1]/2 + beta*p[0] - alpha*p[0]*p[0]*p[0]/6);\n  }\n\n\n\n  template <int dim>\n  void\n  ExactSolution<dim>::vector_value (const Point<dim> &p,\n                                    Vector<double>   &values) const\n  {\n    Assert (values.size() == dim+1,\n            ExcDimensionMismatch (values.size(), dim+1));\n\n    const double alpha = 0.3;\n    const double beta = 1;\n\n    values(0) = alpha*p[1]*p[1]/2 + beta - alpha*p[0]*p[0]/2;\n    values(1) = alpha*p[0]*p[1];\n    values(2) = -(alpha*p[0]*p[1]*p[1]/2 + beta*p[0] - alpha*p[0]*p[0]*p[0]/6);\n  }\n\n\n\n  // @sect3{The inverse permeability tensor}\n\n  // In addition to the other equation data, we also want to use a\n  // permeability tensor, or better -- because this is all that appears in the\n  // weak form -- the inverse of the permeability tensor,\n  // <code>KInverse</code>. For the purpose of verifying the exactness of the\n  // solution and determining convergence orders, this tensor is more in the\n  // way than helpful. We will therefore simply set it to the identity matrix.\n  //\n  // However, a spatially varying permeability tensor is indispensable in\n  // real-life porous media flow simulations, and we would like to use the\n  // opportunity to demonstrate the technique to use tensor valued functions.\n  //\n  // Possibly unsurprising, deal.II also has a base class not only for scalar\n  // and generally vector-valued functions (the <code>Function</code> base\n  // class) but also for functions that return tensors of fixed dimension and\n  // rank, the <code>TensorFunction</code> template. Here, the function under\n  // consideration returns a dim-by-dim matrix, i.e. a tensor of rank 2 and\n  // dimension <code>dim</code>. We then choose the template arguments of the\n  // base class appropriately.\n  //\n  // The interface that the <code>TensorFunction</code> class provides is\n  // essentially equivalent to the <code>Function</code> class. In particular,\n  // there exists a <code>value_list</code> function that takes a list of\n  // points at which to evaluate the function, and returns the values of the\n  // function in the second argument, a list of tensors:\n  template <int dim>\n  class KInverse : public TensorFunction<2,dim>\n  {\n  public:\n    KInverse () : TensorFunction<2,dim>() {}\n\n    virtual void value_list (const std::vector<Point<dim> > &points,\n                             std::vector<Tensor<2,dim> >    &values) const;\n  };\n\n\n  // The implementation is less interesting. As in previous examples, we add a\n  // check to the beginning of the class to make sure that the sizes of input\n  // and output parameters are the same (see step-5 for a discussion of this\n  // technique). Then we loop over all evaluation points, and for each one\n  // first clear the output tensor and then set all its diagonal elements to\n  // one (i.e. fill the tensor with the identity matrix):\n  template <int dim>\n  void\n  KInverse<dim>::value_list (const std::vector<Point<dim> > &points,\n                             std::vector<Tensor<2,dim> >    &values) const\n  {\n    Assert (points.size() == values.size(),\n            ExcDimensionMismatch (points.size(), values.size()));\n\n    for (unsigned int p=0; p<points.size(); ++p)\n      {\n        values[p].clear ();\n\n        for (unsigned int d=0; d<dim; ++d)\n          values[p][d][d] = 1.;\n      }\n  }\n\n\n\n  // @sect3{MixedLaplaceProblem class implementation}\n\n  // @sect4{MixedLaplaceProblem::MixedLaplaceProblem}\n\n  // In the constructor of this class, we first store the value that was\n  // passed in concerning the degree of the finite elements we shall use (a\n  // degree of zero, for example, means to use RT(0) and DG(0)), and then\n  // construct the vector valued element belonging to the space $X_h$ described\n  // in the introduction. The rest of the constructor is as in the early\n  // tutorial programs.\n  //\n  // The only thing worth describing here is the constructor call of the\n  // <code>fe</code> variable. The <code>FESystem</code> class to which this\n  // variable belongs has a number of different constructors that all refer to\n  // binding simpler elements together into one larger element. In the present\n  // case, we want to couple a single RT(degree) element with a single\n  // DQ(degree) element. The constructor to <code>FESystem</code> that does\n  // this requires us to specity first the first base element (the\n  // <code>FE_RaviartThomas</code> object of given degree) and then the number\n  // of copies for this base element, and then similarly the kind and number\n  // of <code>FE_DGQ</code> elements. Note that the Raviart Thomas element\n  // already has <code>dim</code> vector components, so that the coupled\n  // element will have <code>dim+1</code> vector components, the first\n  // <code>dim</code> of which correspond to the velocity variable whereas the\n  // last one corresponds to the pressure.\n  //\n  // It is also worth comparing the way we constructed this element from its\n  // base elements, with the way we have done so in step-8: there, we have\n  // built it as <code>fe (FE_Q@<dim@>(1), dim)</code>, i.e. we have simply\n  // used <code>dim</code> copies of the <code>FE_Q(1)</code> element, one\n  // copy for the displacement in each coordinate direction.\n  template <int dim>\n  MixedLaplaceProblem<dim>::MixedLaplaceProblem (const unsigned int degree)\n    :\n    degree (degree),\n    fe (FE_RaviartThomas<dim>(degree), 1,\n        FE_DGQ<dim>(degree), 1),\n    dof_handler (triangulation)\n  {}\n\n\n\n  // @sect4{MixedLaplaceProblem::make_grid_and_dofs}\n\n  // This next function starts out with well-known functions calls that create\n  // and refine a mesh, and then associate degrees of freedom with it:\n  template <int dim>\n  void MixedLaplaceProblem<dim>::make_grid_and_dofs ()\n  {\n    GridGenerator::hyper_cube (triangulation, -1, 1);\n    triangulation.refine_global (3);\n\n    dof_handler.distribute_dofs (fe);\n\n    // However, then things become different. As mentioned in the\n    // introduction, we want to subdivide the matrix into blocks corresponding\n    // to the two different kinds of variables, velocity and pressure. To this\n    // end, we first have to make sure that the indices corresponding to\n    // velocities and pressures are not intermingled: First all velocity\n    // degrees of freedom, then all pressure DoFs. This way, the global matrix\n    // separates nicely into a $2 \\times 2$ system. To achieve this, we have to\n    // renumber degrees of freedom base on their vector component, an\n    // operation that conveniently is already implemented:\n    DoFRenumbering::component_wise (dof_handler);\n\n    // The next thing is that we want to figure out the sizes of these blocks,\n    // so that we can allocate an appropriate amount of space. To this end, we\n    // call the <code>DoFTools::count_dofs_per_component</code> function that\n    // counts how many shape functions are non-zero for a particular vector\n    // component. We have <code>dim+1</code> vector components, and we have to\n    // use the knowledge that for Raviart-Thomas elements all shape functions\n    // are nonzero in all components. In other words, the number of velocity\n    // shape functions equals the number of overall shape functions that are\n    // nonzero in the zeroth vector component. On the other hand, the number\n    // of pressure variables equals the number of shape functions that are\n    // nonzero in the dim-th component. Let us compute these numbers and then\n    // create some nice output with that:\n    std::vector<unsigned int> dofs_per_component (dim+1);\n    DoFTools::count_dofs_per_component (dof_handler, dofs_per_component);\n    const unsigned int n_u = dofs_per_component[0],\n                       n_p = dofs_per_component[dim];\n\n    std::cout << \"Number of active cells: \"\n              << triangulation.n_active_cells()\n              << std::endl\n              << \"Total number of cells: \"\n              << triangulation.n_cells()\n              << std::endl\n              << \"Number of degrees of freedom: \"\n              << dof_handler.n_dofs()\n              << \" (\" << n_u << '+' << n_p << ')'\n              << std::endl;\n\n    // The next task is to allocate a sparsity pattern for the matrix that we\n    // will create. The way this works is that we first obtain a guess for the\n    // maximal number of nonzero entries per row (this could be done more\n    // efficiently in this case, but we only want to solve relatively small\n    // problems for which this is not so important). In the second step, we\n    // allocate a $2 \\times 2$ block pattern and then reinitialize each of the blocks\n    // to its correct size using the <code>n_u</code> and <code>n_p</code>\n    // variables defined above that hold the number of velocity and pressure\n    // variables. In this second step, we only operate on the individual\n    // blocks of the system. In the third step, we therefore have to instruct\n    // the overlying block system to update its knowledge about the sizes of\n    // the blocks it manages; this happens with the\n    // <code>sparsity_pattern.collect_sizes()</code> call:\n    const unsigned int\n    n_couplings = dof_handler.max_couplings_between_dofs();\n\n    sparsity_pattern.reinit (2,2);\n    sparsity_pattern.block(0,0).reinit (n_u, n_u, n_couplings);\n    sparsity_pattern.block(1,0).reinit (n_p, n_u, n_couplings);\n    sparsity_pattern.block(0,1).reinit (n_u, n_p, n_couplings);\n    sparsity_pattern.block(1,1).reinit (n_p, n_p, n_couplings);\n    sparsity_pattern.collect_sizes();\n\n    // Now that the sparsity pattern and its blocks have the correct sizes, we\n    // actually need to construct the content of this pattern, and as usual\n    // compress it, before we also initialize a block matrix with this block\n    // sparsity pattern:\n    DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);\n    sparsity_pattern.compress();\n\n    system_matrix.reinit (sparsity_pattern);\n\n    // Then we have to resize the solution and right hand side vectors in\n    // exactly the same way:\n    solution.reinit (2);\n    solution.block(0).reinit (n_u);\n    solution.block(1).reinit (n_p);\n    solution.collect_sizes ();\n\n    system_rhs.reinit (2);\n    system_rhs.block(0).reinit (n_u);\n    system_rhs.block(1).reinit (n_p);\n    system_rhs.collect_sizes ();\n  }\n\n\n  // @sect4{MixedLaplaceProblem::assemble_system}\n\n  // Similarly, the function that assembles the linear system has mostly been\n  // discussed already in the introduction to this example. At its top, what\n  // happens are all the usual steps, with the addition that we do not only\n  // allocate quadrature and <code>FEValues</code> objects for the cell terms,\n  // but also for face terms. After that, we define the usual abbreviations\n  // for variables, and the allocate space for the local matrix and right hand\n  // side contributions, and the array that holds the global numbers of the\n  // degrees of freedom local to the present cell.\n  template <int dim>\n  void MixedLaplaceProblem<dim>::assemble_system ()\n  {\n    QGauss<dim>   quadrature_formula(degree+2);\n    QGauss<dim-1> face_quadrature_formula(degree+2);\n\n    FEValues<dim> fe_values (fe, quadrature_formula,\n                             update_values    | update_gradients |\n                             update_quadrature_points  | update_JxW_values);\n    FEFaceValues<dim> fe_face_values (fe, face_quadrature_formula,\n                                      update_values    | update_normal_vectors |\n                                      update_quadrature_points  | update_JxW_values);\n\n    const unsigned int   dofs_per_cell   = fe.dofs_per_cell;\n    const unsigned int   n_q_points      = quadrature_formula.size();\n    const unsigned int   n_face_q_points = face_quadrature_formula.size();\n\n    FullMatrix<double>   local_matrix (dofs_per_cell, dofs_per_cell);\n    Vector<double>       local_rhs (dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    // The next step is to declare objects that represent the source term,\n    // pressure boundary value, and coefficient in the equation. In addition\n    // to these objects that represent continuous functions, we also need\n    // arrays to hold their values at the quadrature points of individual\n    // cells (or faces, for the boundary values). Note that in the case of the\n    // coefficient, the array has to be one of matrices.\n    const RightHandSide<dim>          right_hand_side;\n    const PressureBoundaryValues<dim> pressure_boundary_values;\n    const KInverse<dim>               k_inverse;\n\n    std::vector<double> rhs_values (n_q_points);\n    std::vector<double> boundary_values (n_face_q_points);\n    std::vector<Tensor<2,dim> > k_inverse_values (n_q_points);\n\n    // Finally, we need a couple of extractors that we will use to get at the\n    // velocity and pressure components of vector-valued shape\n    // functions. Their function and use is described in detail in the @ref\n    // vector_valued report. Essentially, we will use them as subscripts on\n    // the FEValues objects below: the FEValues object describes all vector\n    // components of shape functions, while after subscription, it will only\n    // refer to the velocities (a set of <code>dim</code> components starting\n    // at component zero) or the pressure (a scalar component located at\n    // position <code>dim</code>):\n    const FEValuesExtractors::Vector velocities (0);\n    const FEValuesExtractors::Scalar pressure (dim);\n\n    // With all this in place, we can go on with the loop over all cells. The\n    // body of this loop has been discussed in the introduction, and will not\n    // be commented any further here:\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n    for (; cell!=endc; ++cell)\n      {\n        fe_values.reinit (cell);\n        local_matrix = 0;\n        local_rhs = 0;\n\n        right_hand_side.value_list (fe_values.get_quadrature_points(),\n                                    rhs_values);\n        k_inverse.value_list (fe_values.get_quadrature_points(),\n                              k_inverse_values);\n\n        for (unsigned int q=0; q<n_q_points; ++q)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            {\n              const Tensor<1,dim> phi_i_u     = fe_values[velocities].value (i, q);\n              const double        div_phi_i_u = fe_values[velocities].divergence (i, q);\n              const double        phi_i_p     = fe_values[pressure].value (i, q);\n\n              for (unsigned int j=0; j<dofs_per_cell; ++j)\n                {\n                  const Tensor<1,dim> phi_j_u     = fe_values[velocities].value (j, q);\n                  const double        div_phi_j_u = fe_values[velocities].divergence (j, q);\n                  const double        phi_j_p     = fe_values[pressure].value (j, q);\n\n                  local_matrix(i,j) += (phi_i_u * k_inverse_values[q] * phi_j_u\n                                        - div_phi_i_u * phi_j_p\n                                        - phi_i_p * div_phi_j_u)\n                                       * fe_values.JxW(q);\n                }\n\n              local_rhs(i) += -phi_i_p *\n                              rhs_values[q] *\n                              fe_values.JxW(q);\n            }\n\n        for (unsigned int face_no=0;\n             face_no<GeometryInfo<dim>::faces_per_cell;\n             ++face_no)\n          if (cell->at_boundary(face_no))\n            {\n              fe_face_values.reinit (cell, face_no);\n\n              pressure_boundary_values\n              .value_list (fe_face_values.get_quadrature_points(),\n                           boundary_values);\n\n              for (unsigned int q=0; q<n_face_q_points; ++q)\n                for (unsigned int i=0; i<dofs_per_cell; ++i)\n                  local_rhs(i) += -(fe_face_values[velocities].value (i, q) *\n                                    fe_face_values.normal_vector(q) *\n                                    boundary_values[q] *\n                                    fe_face_values.JxW(q));\n            }\n\n        // The final step in the loop over all cells is to transfer local\n        // contributions into the global matrix and right hand side\n        // vector. Note that we use exactly the same interface as in previous\n        // examples, although we now use block matrices and vectors instead of\n        // the regular ones. In other words, to the outside world, block\n        // objects have the same interface as matrices and vectors, but they\n        // additionally allow to access individual blocks.\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            system_matrix.add (local_dof_indices[i],\n                               local_dof_indices[j],\n                               local_matrix(i,j));\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          system_rhs(local_dof_indices[i]) += local_rhs(i);\n      }\n  }\n\n\n  // @sect3{Linear solvers and preconditioners}\n\n  // The linear solvers and preconditioners we use in this example have been\n  // discussed in significant detail already in the introduction. We will\n  // therefore not discuss the rationale for these classes here any more, but\n  // rather only comment on implementational aspects.\n\n\n  // @sect4{The <code>SchurComplement</code> class template}\n\n  // The next class is the Schur complement class. Its rationale has also been\n  // discussed in length in the introduction. The only things we would like to\n  // note is that the class, too, is derived from the <code>Subscriptor</code>\n  // class and that as mentioned above it stores pointers to the entire block\n  // matrix and the inverse of the mass matrix block using\n  // <code>SmartPointer</code> objects.\n  //\n  // The <code>vmult</code> function requires two temporary vectors that we do\n  // not want to re-allocate and free every time we call this function. Since\n  // here, we have full control over the use of these vectors (unlike above,\n  // where a class called by the <code>vmult</code> function required these\n  // vectors, not the <code>vmult</code> function itself), we allocate them\n  // directly, rather than going through the <code>VectorMemory</code>\n  // mechanism. However, again, these member variables do not carry any state\n  // between successive calls to the member functions of this class (i.e., we\n  // never care what values they were set to the last time a member function\n  // was called), we mark these vectors as <code>mutable</code>.\n  //\n  // The rest of the (short) implementation of this class is straightforward\n  // if you know the order of matrix-vector multiplications performed by the\n  // <code>vmult</code> function:\n  class SchurComplement : public Subscriptor\n  {\n  public:\n    SchurComplement (const BlockSparseMatrix<double> &A,\n                     const IterativeInverse<Vector<double> > &Minv);\n\n    void vmult (Vector<double>       &dst,\n                const Vector<double> &src) const;\n\n  private:\n    const SmartPointer<const BlockSparseMatrix<double> > system_matrix;\n    const SmartPointer<const IterativeInverse<Vector<double> > > m_inverse;\n\n    mutable Vector<double> tmp1, tmp2;\n  };\n\n\n  SchurComplement::SchurComplement (const BlockSparseMatrix<double> &A,\n                                    const IterativeInverse<Vector<double> > &Minv)\n    :\n    system_matrix (&A),\n    m_inverse (&Minv),\n    tmp1 (A.block(0,0).m()),\n    tmp2 (A.block(0,0).m())\n  {}\n\n\n  void SchurComplement::vmult (Vector<double>       &dst,\n                               const Vector<double> &src) const\n  {\n    system_matrix->block(0,1).vmult (tmp1, src);\n    m_inverse->vmult (tmp2, tmp1);\n    system_matrix->block(1,0).vmult (dst, tmp2);\n  }\n\n\n  // @sect4{The <code>ApproximateSchurComplement</code> class template}\n\n  // The third component of our solver and preconditioner system is the class\n  // that approximates the Schur complement so we can form a an InverseIterate\n  // object that approximates the inverse of the Schur complement. It follows\n  // the same pattern as the Schur complement class, with the only exception\n  // that we do not multiply with the inverse mass matrix in\n  // <code>vmult</code>, but rather just do a single Jacobi\n  // step. Consequently, the class also does not have to store a pointer to an\n  // inverse mass matrix object.\n  //\n  // We will later use this class as a template argument to the\n  // IterativeInverse class which will in turn want to use it as a\n  // template argument for the PointerMatrix class. The latter class\n  // has a function that requires us to also write a function that\n  // provides the product with the transpose of the matrix this object\n  // represents. As a consequence, in the code below, we also\n  // implement a <tt>Tvmult</tt> function here that represents the\n  // product of the transpose matrix with a vector. It is easy to see\n  // how this needs to be implemented here: since the matrix is\n  // symmetric, we can as well call <code>vmult</code> wherever the\n  // product with the transpose matrix is required. (Note, however,\n  // that even though we implement this function here, there will in\n  // fact not be any need for it as long as we use SolverCG as the\n  // solver since that solver does not ever call the function that\n  // provides this operation.)\n  class ApproximateSchurComplement : public Subscriptor\n  {\n  public:\n    ApproximateSchurComplement (const BlockSparseMatrix<double> &A);\n\n    void vmult (Vector<double>       &dst,\n                const Vector<double> &src) const;\n    void Tvmult (Vector<double>       &dst,\n                 const Vector<double> &src) const;\n\n  private:\n    const SmartPointer<const BlockSparseMatrix<double> > system_matrix;\n\n    mutable Vector<double> tmp1, tmp2;\n  };\n\n\n  ApproximateSchurComplement::ApproximateSchurComplement (const BlockSparseMatrix<double> &A)\n    :\n    system_matrix (&A),\n    tmp1 (A.block(0,0).m()),\n    tmp2 (A.block(0,0).m())\n  {}\n\n\n  void ApproximateSchurComplement::vmult (Vector<double>       &dst,\n                                          const Vector<double> &src) const\n  {\n    system_matrix->block(0,1).vmult (tmp1, src);\n    system_matrix->block(0,0).precondition_Jacobi (tmp2, tmp1);\n    system_matrix->block(1,0).vmult (dst, tmp2);\n  }\n\n\n  void ApproximateSchurComplement::Tvmult (Vector<double>       &dst,\n                                           const Vector<double> &src) const\n  {\n    vmult (dst, src);\n  }\n\n\n\n  // @sect4{MixedLaplace::solve}\n\n  // After all these preparations, we can finally write the function that\n  // actually solves the linear problem. We will go through the two parts it\n  // has that each solve one of the two equations, the first one for the\n  // pressure (component 1 of the solution), then the velocities (component 0\n  // of the solution). Both parts need an object representing the inverse mass\n  // matrix and an auxiliary vector, and we therefore declare these objects at\n  // the beginning of this function.\n  template <int dim>\n  void MixedLaplaceProblem<dim>::solve ()\n  {\n    PreconditionIdentity identity;\n    IterativeInverse<Vector<double> > m_inverse;\n    m_inverse.initialize(system_matrix.block(0,0), identity);\n    m_inverse.solver.select(\"cg\");\n    static ReductionControl inner_control(1000, 0., 1.e-13);\n    m_inverse.solver.set_control(inner_control);\n\n    Vector<double> tmp (solution.block(0).size());\n\n    // Now on to the first equation. The right hand side of it is $B^TM^{-1}F-G$,\n    // which is what we compute in the first few lines. We then declare the\n    // objects representing the Schur complement, its approximation, and the\n    // inverse of the approximation. Finally, we declare a solver object and\n    // hand off all these matrices and vectors to it to compute block 1 (the\n    // pressure) of the solution:\n    {\n      Vector<double> schur_rhs (solution.block(1).size());\n\n      m_inverse.vmult (tmp, system_rhs.block(0));\n      system_matrix.block(1,0).vmult (schur_rhs, tmp);\n      schur_rhs -= system_rhs.block(1);\n\n\n      SchurComplement\n      schur_complement (system_matrix, m_inverse);\n\n      ApproximateSchurComplement\n      approximate_schur_complement (system_matrix);\n\n      IterativeInverse<Vector<double> >\n      preconditioner;\n      preconditioner.initialize(approximate_schur_complement, identity);\n      preconditioner.solver.select(\"cg\");\n      preconditioner.solver.set_control(inner_control);\n\n\n      SolverControl solver_control (solution.block(1).size(),\n                                    1e-12*schur_rhs.l2_norm());\n      SolverCG<>    cg (solver_control);\n\n      cg.solve (schur_complement, solution.block(1), schur_rhs,\n                preconditioner);\n\n      std::cout << solver_control.last_step()\n                << \" CG Schur complement iterations to obtain convergence.\"\n                << std::endl;\n    }\n\n    // After we have the pressure, we can compute the velocity. The equation\n    // reads $MU=-BP+F$, and we solve it by first computing the right hand\n    // side, and then multiplying it with the object that represents the\n    // inverse of the mass matrix:\n    {\n      system_matrix.block(0,1).vmult (tmp, solution.block(1));\n      tmp *= -1;\n      tmp += system_rhs.block(0);\n\n      m_inverse.vmult (solution.block(0), tmp);\n    }\n  }\n\n\n  // @sect3{MixedLaplaceProblem class implementation (continued)}\n\n  // @sect4{MixedLaplace::compute_errors}\n\n  // After we have dealt with the linear solver and preconditioners, we\n  // continue with the implementation of our main class. In particular, the\n  // next task is to compute the errors in our numerical solution, in both the\n  // pressures as well as velocities.\n  //\n  // To compute errors in the solution, we have already introduced the\n  // <code>VectorTools::integrate_difference</code> function in step-7 and\n  // step-11. However, there we only dealt with scalar solutions, whereas here\n  // we have a vector-valued solution with components that even denote\n  // different quantities and may have different orders of convergence (this\n  // isn't the case here, by choice of the used finite elements, but is\n  // frequently the case in mixed finite element applications). What we\n  // therefore have to do is to `mask' the components that we are interested\n  // in. This is easily done: the\n  // <code>VectorTools::integrate_difference</code> function takes as its last\n  // argument a pointer to a weight function (the parameter defaults to the\n  // null pointer, meaning unit weights). What we simply have to do is to pass\n  // a function object that equals one in the components we are interested in,\n  // and zero in the other ones. For example, to compute the pressure error,\n  // we should pass a function that represents the constant vector with a unit\n  // value in component <code>dim</code>, whereas for the velocity the\n  // constant vector should be one in the first <code>dim</code> components,\n  // and zero in the location of the pressure.\n  //\n  // In deal.II, the <code>ComponentSelectFunction</code> does exactly this:\n  // it wants to know how many vector components the function it is to\n  // represent should have (in our case this would be <code>dim+1</code>, for\n  // the joint velocity-pressure space) and which individual or range of\n  // components should be equal to one. We therefore define two such masks at\n  // the beginning of the function, following by an object representing the\n  // exact solution and a vector in which we will store the cellwise errors as\n  // computed by <code>integrate_difference</code>:\n  template <int dim>\n  void MixedLaplaceProblem<dim>::compute_errors () const\n  {\n    const ComponentSelectFunction<dim>\n    pressure_mask (dim, dim+1);\n    const ComponentSelectFunction<dim>\n    velocity_mask(std::make_pair(0, dim), dim+1);\n\n    ExactSolution<dim> exact_solution;\n    Vector<double> cellwise_errors (triangulation.n_active_cells());\n\n    // As already discussed in step-7, we have to realize that it is\n    // impossible to integrate the errors exactly. All we can do is\n    // approximate this integral using quadrature. This actually presents a\n    // slight twist here: if we naively chose an object of type\n    // <code>QGauss@<dim@>(degree+1)</code> as one may be inclined to do (this\n    // is what we used for integrating the linear system), one realizes that\n    // the error is very small and does not follow the expected convergence\n    // curves at all. What is happening is that for the mixed finite elements\n    // used here, the Gauss points happen to be superconvergence points in\n    // which the pointwise error is much smaller (and converges with higher\n    // order) than anywhere else. These are therefore not particularly good\n    // points for ingration. To avoid this problem, we simply use a\n    // trapezoidal rule and iterate it <code>degree+2</code> times in each\n    // coordinate direction (again as explained in step-7):\n    QTrapez<1>     q_trapez;\n    QIterated<dim> quadrature (q_trapez, degree+2);\n\n    // With this, we can then let the library compute the errors and output\n    // them to the screen:\n    VectorTools::integrate_difference (dof_handler, solution, exact_solution,\n                                       cellwise_errors, quadrature,\n                                       VectorTools::L2_norm,\n                                       &pressure_mask);\n    const double p_l2_error = cellwise_errors.l2_norm();\n\n    VectorTools::integrate_difference (dof_handler, solution, exact_solution,\n                                       cellwise_errors, quadrature,\n                                       VectorTools::L2_norm,\n                                       &velocity_mask);\n    const double u_l2_error = cellwise_errors.l2_norm();\n\n    std::cout << \"Errors: ||e_p||_L2 = \" << p_l2_error\n              << \",   ||e_u||_L2 = \" << u_l2_error\n              << std::endl;\n  }\n\n\n  // @sect4{MixedLaplace::output_results}\n\n  // The last interesting function is the one in which we generate graphical\n  // output. Everything here looks obvious and familiar. Note how we construct\n  // unique names for all the solution variables at the beginning, like we did\n  // in step-8 and other programs later on. The only thing worth mentioning is\n  // that for higher order elements, in seems inappropriate to only show a\n  // single bilinear quadrilateral per cell in the graphical output. We\n  // therefore generate patches of size (degree+1)x(degree+1) to capture the\n  // full information content of the solution. See the step-7 tutorial program\n  // for more information on this.\n  //\n  // Note that we output the <code>dim+1</code> components of the solution\n  // vector as a collection of individual scalars here. Most visualization\n  // programs will then only offer to visualize them individually, rather than\n  // allowing us to plot the flow field as a vector field. However, as\n  // explained in the corresponding function of step-22 or the @ref VVOutput\n  // \"Generating graphical output\" section of the @ref vector_valued module,\n  // instructing the DataOut class to identify components of the FESystem\n  // object as elements of a <code>dim</code>-dimensional vector is not\n  // actually very difficult and will then allow us to show results as vector\n  // plots. We skip this here for simplicity and refer to the links above for\n  // more information.\n  template <int dim>\n  void MixedLaplaceProblem<dim>::output_results () const\n  {\n    std::vector<std::string> solution_names;\n    switch (dim)\n      {\n      case 2:\n        solution_names.push_back (\"u\");\n        solution_names.push_back (\"v\");\n        solution_names.push_back (\"p\");\n        break;\n\n      case 3:\n        solution_names.push_back (\"u\");\n        solution_names.push_back (\"v\");\n        solution_names.push_back (\"w\");\n        solution_names.push_back (\"p\");\n        break;\n\n      default:\n        Assert (false, ExcNotImplemented());\n      }\n\n\n    DataOut<dim> data_out;\n\n    data_out.attach_dof_handler (dof_handler);\n    data_out.add_data_vector (solution, solution_names);\n\n    data_out.build_patches (degree+1);\n\n    std::ofstream output (\"solution.gmv\");\n    data_out.write_gmv (output);\n  }\n\n\n\n  // @sect4{MixedLaplace::run}\n\n  // This is the final function of our main class. It's only job is to call\n  // the other functions in their natural order:\n  template <int dim>\n  void MixedLaplaceProblem<dim>::run ()\n  {\n    make_grid_and_dofs();\n    assemble_system ();\n    solve ();\n    compute_errors ();\n    output_results ();\n  }\n}\n\n\n// @sect3{The <code>main</code> function}\n\n// The main function we stole from step-6 instead of step-4. It is almost\n// equal to the one in step-6 (apart from the changed class names, of course),\n// the only exception is that we pass the degree of the finite element space\n// to the constructor of the mixed laplace problem (here, we use zero-th order\n// elements).\nint main ()\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step20;\n\n      deallog.depth_console (0);\n\n      MixedLaplaceProblem<2> mixed_laplace_problem(0);\n      mixed_laplace_problem.run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << 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\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << 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": "34f33ea060694784e9fd301cba14b1beca6948b0", "size": 40422, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-20/step-20.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/step-20/step-20.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/step-20/step-20.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 42.6842661035, "max_line_length": 93, "alphanum_fraction": 0.6646875464, "num_tokens": 9702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.512558696565985}}
{"text": "#ifndef __fovis_internal_utils_hpp__\n#define __fovis_internal_utils_hpp__\n\n#include <stdio.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <emmintrin.h>\n\n#include \"options.hpp\"\n\nnamespace fovis\n{\n\n#define FOVIS_IS_ALIGNED16(x) (((uintptr_t)(x) & 0xf) == 0)\n\nstatic inline int\nround_up_to_multiple(int x, int a)\n{\n  int rem = x % a;\n  if(rem)\n    return x + (a - rem);\n  return x;\n}\n\nstatic inline Eigen::Vector3d\n_quat_to_roll_pitch_yaw(const Eigen::Quaterniond&q)\n{\n  double roll_a = 2 * (q.w() * q.x() + q.y() * q.z());\n  double roll_b = 1 - 2 * (q.x() * q.x() + q.y() * q.y());\n  double roll = atan2(roll_a, roll_b);\n\n  double pitch_sin = 2 * (q.w() * q.y() - q.z() * q.x());\n  double pitch = asin(pitch_sin);\n\n  double yaw_a = 2 * (q.w() * q.z() + q.x() * q.y());\n  double yaw_b = 1 - 2 * (q.y() * q.y() + q.z() * q.z());\n  double yaw = atan2(yaw_a, yaw_b);\n  return Eigen::Vector3d(roll, pitch, yaw);\n}\n\nstatic inline Eigen::Quaterniond\n_rpy_to_quat(const Eigen::Vector3d rpy)\n{\n  double roll = rpy(0), pitch = rpy(1), yaw = rpy(2);\n\n  double halfroll = roll / 2;\n  double halfpitch = pitch / 2;\n  double halfyaw = yaw / 2;\n\n  double sin_r2 = sin(halfroll);\n  double sin_p2 = sin(halfpitch);\n  double sin_y2 = sin(halfyaw);\n\n  double cos_r2 = cos(halfroll);\n  double cos_p2 = cos(halfpitch);\n  double cos_y2 = cos(halfyaw);\n\n  Eigen::Quaterniond q;\n  q.w() = cos_r2 * cos_p2 * cos_y2 + sin_r2 * sin_p2 * sin_y2;\n  q.x() = sin_r2 * cos_p2 * cos_y2 - cos_r2 * sin_p2 * sin_y2;\n  q.y() = cos_r2 * sin_p2 * cos_y2 + sin_r2 * cos_p2 * sin_y2;\n  q.z() = cos_r2 * cos_p2 * sin_y2 - sin_r2 * sin_p2 * cos_y2;\n  return q;\n}\n\nstatic inline void\nprint_isometry(const Eigen::Isometry3d & iso)\n{\n  const Eigen::Vector3d & t = iso.translation();\n  Eigen::Vector3d rpy = _quat_to_roll_pitch_yaw(Eigen::Quaterniond(iso.rotation()))*180.0/M_PI;\n  fprintf(stderr, \"trans:(% 6.3f % 6.3f % 6.3f) rot:(% 6.3f % 6.3f % 6.3f)\",t(0),t(1),t(2),rpy(0),rpy(1),rpy(2));\n  //    dbg(\"rot:(% 6.3f % 6.3f % 6.3f)\",rpy(0),rpy(1),rpy(2));\n}\n\nbool optionsGetInt(const VisualOdometryOptions& options, std::string name,\n        int* result);\n\nbool optionsGetBool(const VisualOdometryOptions& options, std::string name,\n        bool* result);\n\nint optionsGetIntOrFromDefault(const VisualOdometryOptions& options,\n        std::string name, const VisualOdometryOptions& defaults);\n\nbool optionsGetBoolOrFromDefault(const VisualOdometryOptions& options,\n        std::string name, const VisualOdometryOptions& defaults);\n\nbool optionsGetDouble(const VisualOdometryOptions& options, std::string name,\n        double* result);\n\ndouble optionsGetDoubleOrFromDefault(const VisualOdometryOptions& options,\n        std::string name, const VisualOdometryOptions& defaults);\n\n}\n\n#endif\n", "meta": {"hexsha": "f99ae53f11520851385a90061e498e074bed7190", "size": 2755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "navigation_layer/fovis/libfovis/libfovis/libfovis/internal_utils.hpp", "max_stars_repo_name": "kartavya2000/Anahita", "max_stars_repo_head_hexsha": "9afbf6c238658188df7d0d97b2fec3bd48028c03", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-03-21T15:18:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T07:52:10.000Z", "max_issues_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/libfovis/internal_utils.hpp", "max_issues_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_issues_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-10-03T12:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-07T09:33:14.000Z", "max_forks_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/libfovis/internal_utils.hpp", "max_forks_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_forks_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2018-09-09T12:35:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-03T09:28:19.000Z", "avg_line_length": 28.4020618557, "max_line_length": 113, "alphanum_fraction": 0.6649727768, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5125586935899203}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <vector>\n\nTEST(ProbDistributionsHypergeometric, error_check) {\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::hypergeometric_rng(10, 10, 15, rng));\n\n  EXPECT_THROW(stan::math::hypergeometric_rng(30, 10, 15, rng),\n               std::domain_error);\n  EXPECT_THROW(stan::math::hypergeometric_rng(-30, 10, 15, rng),\n               std::domain_error);\n  EXPECT_THROW(stan::math::hypergeometric_rng(30, -10, 15, rng),\n               std::domain_error);\n  EXPECT_THROW(stan::math::hypergeometric_rng(30, 10, -15, rng),\n               std::domain_error);\n}\n\nTEST(ProbDistributionsHypergeometric, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int N = 10000;\n  int num_draws = 10;\n  int K = num_draws;\n  boost::math::hypergeometric_distribution<>dist (15, num_draws, 25);\n  boost::math::chi_squared mydist(K-1);\n\n  std::vector<int> loc(K - 1);\n  for(int i = 1; i < K; i++)\n    loc[i - 1] = i - 1;\n\n  int count = 0;\n  std::vector<int> bin(K);\n  std::vector<double> expect(K);\n  for(int i = 0 ; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N * pdf(dist, i);\n  }\n\n  while (count < N) {\n    int a = stan::math::hypergeometric_rng(num_draws, 10, 15, rng);\n    int i = 0;\n    while (i < K-1 && a > loc[i]) \n      ++i;\n    ++bin[i];\n    count++;\n   }\n\n  double chi = 0;\n\n  for(int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n", "meta": {"hexsha": "8609770440b8286ae9a90d4872aa15315a9ac561", "size": 1596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/prob/hypergeometric_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/prob/hypergeometric_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/prob/hypergeometric_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 69, "alphanum_fraction": 0.6146616541, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5125586915079854}}
{"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 standard_gaussian_mapping.hpp\n * \\date May 2014\n * \\author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#pragma once\n\n\n#include <Eigen/Dense>\n\n#include <type_traits>\n\n#include <fl/util/traits.hpp>\n#include <fl/util/scalar_matrix.hpp>\n#include <fl/distribution/interface/sampling.hpp>\n#include <fl/distribution/standard_gaussian.hpp>\n\nnamespace fl\n{\n\n/**\n * \\ingroup distribution_interfaces\n *\n * \\brief Represents the interface which provides a mapping\n *        from a standard normal variate onto the underlying distribution which\n *        implements this interface\n *\n * \\tparam Variate              The Distribution variate type. This is the type\n *                              which is being returned by the mapping or\n *                              sampling, respectively.\n * \\tparam StdVariateDimension  Dimension of the source variate type which is\n *                              the standard normal variate\n *                              \\f$x_{SNV}\\sim{\\cal N}(0, I)\\f$\n */\ntemplate <typename Variate, int StdVariateDimension>\nclass StandardGaussianMapping\n    : public Sampling<Variate>\n{\npublic:\n    typedef Eigen::Matrix<Real, StdVariateDimension, 1> StandardVariate;\n\n    /**\n     * StandardGaussianMapping constructor. It initializes the mapper\n     *\n     * \\param snv_dimension     Dimension of the standard normal variate\n     */\n    explicit StandardGaussianMapping(\n            int snv_dimension = DimensionOf<StandardVariate>())\n        : standard_gaussian_(snv_dimension)\n    { }\n\n    /**\n     * \\brief Overridable default destructor\n     */\n    virtual ~StandardGaussianMapping() noexcept { }\n\n    /**\n     * \\brief Mapps a standard normal variate onto a sample of the underlying\n     *        distribution which implements this mapper\n     *\n     * \\param sample  SNV sample which will be mapped onto a variate sampe\n     *\n     * \\return A variate according to the underlying distribution\n     */\n    virtual Variate map_standard_normal(const StandardVariate& sample) const = 0;\n\n    /**\n     * \\return A variate according to the underlying distribution\n     */\n    virtual Variate sample() const\n    {\n        return map_standard_normal(standard_gaussian_.sample());\n    }\n\n    /**\n     * \\return Dimension of the standard normal variate used for mapping\n     */\n    virtual int standard_variate_dimension() const\n    {\n        return standard_gaussian_.dimension();\n    }\n\n    /**\n     * \\brief Sets the dimension of the standard normal variate\n     *\n     * \\param snv_dimension The new dimension of the SNV\n     */\n    virtual void standard_variate_dimension(int snv_dimension)\n    {\n        standard_gaussian_.dimension(snv_dimension);\n    }\n\nprotected:\n    /**\n     * \\brief SNV generator\n     */\n    mutable StandardGaussian<StandardVariate> standard_gaussian_;\n};\n\n/**\n * \\ingroup distribution_interfaces\n *\n * \\brief Represents the interface which provides a mapping\n *        from a scalar standard normal variate onto the underlying distribution\n *        which implements this interface.\n *\n * \\tparam Variate          The Distribution variate type. This is the type\n *                          which is being returned by the mapping or sampling,\n *                          respectively.\n */\ntemplate <typename Variate>\nclass StandardGaussianMapping<Variate, 1>\n    : public Sampling<Variate>\n{\npublic:\n    typedef ScalarMatrix StandardVariate;\n\n\n    /// \\todo fix this (unused argument)\n    explicit StandardGaussianMapping(int snv_dimension = 1)\n    { }\n\n\n    /**\n     * \\brief Overridable default destructor\n     */\n    virtual ~StandardGaussianMapping() noexcept { }\n\n    /**\n     * \\brief Mapps a one dimensional standard normal variate onto a sample of\n     *        the underlying distribution which implements this mapper\n     *\n     * \\param sample SNV sample which will be mapped onto a variate sampe\n     *\n     * \\return A variate according to the underlying distribution\n     */\n    virtual Variate map_standard_normal(const StandardVariate& sample) const = 0;\n\n    /**\n     * \\return A variate according to the underlying distribution\n     */\n    virtual Variate sample() const\n    {\n        return map_standard_normal(standard_gaussian_.sample());\n    }\n\n    /**\n     * \\return Dimension of the standard normal variate used for mapping\n     */\n    virtual int standard_variate_dimension() const\n    {\n        return 1;\n    }\n\n    /// \\todo fix this (unused argument)\n    virtual void standard_variate_dimension(int snv_dimension)\n    {\n    }\n\nprotected:\n    /**\n     * \\brief One dimensional SNV generator\n     */\n    mutable StandardGaussian<Real> standard_gaussian_;\n};\n\n}\n", "meta": {"hexsha": "297713203d666af15e76ae8bf8cbbc4bf8651f17", "size": 5112, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/distribution/interface/standard_gaussian_mapping.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/distribution/interface/standard_gaussian_mapping.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/distribution/interface/standard_gaussian_mapping.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": 27.9344262295, "max_line_length": 81, "alphanum_fraction": 0.6637323944, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5125586915079854}}
{"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_NBDIGITS_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_NBDIGITS_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Nbdigits Nbdigits (function template)\n\n  Generates the number of mantissa bits of a floating point number,\n  and the total number of bits for integral types.\n\n  @headerref{<boost/simd/constant/nbdigits.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Nbdigits();\n      @endcode\n\n  2.  @code\n      template<typename T> T Nbdigits( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T containing the Nbdigits constant.\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 as_integer_t<T> that evaluates to\n\n  | Type                | double                        | float         | Integral        |\n  |--------------------:|:------------------------------|---------------|-----------------|\n  | value               |   53                          |      24       | sizeof(T)*8     |\n\n   @par Requirements\n  - **T** models Value\n**/\n\n#include <boost/simd/constant/scalar/nbdigits.hpp>\n#include <boost/simd/constant/simd/nbdigits.hpp>\n\n#endif\n", "meta": {"hexsha": "434b9d13ec943a746ae3098bc6878873b151638e", "size": 1832, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/nbdigits.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/nbdigits.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/nbdigits.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": 32.7142857143, "max_line_length": 100, "alphanum_fraction": 0.4863537118, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5125586864499859}}
{"text": "#include <ancse/dg_rate_of_change.hpp>\n\n#include <Eigen/Dense>\n#include <ancse/config.hpp>\n#include <ancse/polynomial_basis.hpp>\n#include <ancse/dg_handler.hpp>\n#include <ancse/numerical_flux.hpp>\n#include <fmt/format.h>\n\n\n/// DG numerical flux term\ntemplate <class NumericalFlux>\nvoid DGRateOfChange<NumericalFlux>\n:: eval_numerical_flux (Eigen::MatrixXd &dudt,\n                        const Eigen::MatrixXd &u0) const\n{\n    // implement the loop for DG numerical flux term.\n    const int n_cells= grid.n_cells;\n    const int n_ghost= grid.n_ghost;\n\n    const int n_vars= model->get_nvars();\n\n    const double dx= grid.dx;\n    Eigen::VectorXd fL= Eigen::VectorXd::Zero(n_vars), fR= Eigen::VectorXd::Zero(n_vars);\n    Eigen::VectorXd uL, uR;\n\n    for (int i= n_ghost - 1; i < n_cells - n_ghost; ++i)\n    {\n        uL= u0.col(i);\n        uR= u0.col(i + 1);\n        \n        fL= fR;\n        fR= numerical_flux(uL, uR);\n\n        dudt.col(i)= (fL - fR) / dx;\n    }\n}\n\n/// DG volume integral term\ntemplate <class NumericalFlux>\nvoid DGRateOfChange<NumericalFlux>\n:: eval_volume_integral(Eigen::MatrixXd &dudt,\n                        const Eigen::MatrixXd &u0) const\n{\n    // implement the loop for DG volume integral.\n}\n\n\n#define REGISTER_NUMERICAL_FLUX(token, FluxType, flux)          \\\n    if (config[\"flux\"] == (token)) {                            \\\n        return std::make_shared< DGRateOfChange<FluxType> >(    \\\n            grid, model, flux, poly_basis, dg_handler);                     \\\n    }\n\n\nstd::shared_ptr<RateOfChange> make_dg_rate_of_change(\n    const nlohmann::json &config,\n    const Grid &grid,\n    const std::shared_ptr<Model> &model,\n    const PolynomialBasis &poly_basis,\n    const DGHandler &dg_handler,\n    const std::shared_ptr<SimulationTime> &simulation_time)\n{\n    // Register the other numerical fluxes.\n\n    REGISTER_NUMERICAL_FLUX(\"central_flux\", CentralFlux, CentralFlux(model))\n    REGISTER_NUMERICAL_FLUX(\"rusanov\", Rusanov, Rusanov(model))\n    REGISTER_NUMERICAL_FLUX(\"lax_friedrichs\",\n                            LaxFriedrichs,\n                            LaxFriedrichs(grid, model, simulation_time))\n    REGISTER_NUMERICAL_FLUX(\"roe\", Roe, Roe(model))\n    REGISTER_NUMERICAL_FLUX(\"hll\", HLL, HLL(model))\n    REGISTER_NUMERICAL_FLUX(\"hllc\", HLLc, HLLc(model))\n\n    throw std::runtime_error(\n        fmt::format(\"Unknown numerical flux. {}\",\n                    std::string(config[\"flux\"])));\n}\n\n#undef REGISTER_NUMERICAL_FLUX\n", "meta": {"hexsha": "53e0e3a88c5f00505fe32b382a1039387cb3d5b8", "size": 2460, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series2_workbench/hyp_sys_1d/src/ancse/dg_rate_of_change.cpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_workbench/hyp_sys_1d/src/ancse/dg_rate_of_change.cpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_workbench/hyp_sys_1d/src/ancse/dg_rate_of_change.cpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 30.3703703704, "max_line_length": 89, "alphanum_fraction": 0.6406504065, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5125586864499859}}
{"text": "/*\n * RWHEC_Nov2015_main.hpp\n *\n *  Created on: Nov 16, 2015\n *      Author: atabb\n */\n\n#ifndef TABB_AHMADYOUSEF_RWHEC_MAY2018_MAIN_HPP_\n#define TABB_AHMADYOUSEF_RWHEC_MAY2018_MAIN_HPP_\n\n#include \"ceres/ceres.h\"\n#include \"glog/logging.h\"\n#include \"Calibration2.hpp\"\n#include <iostream>\n#include \"CostFunctions.hpp\"\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\n\nusing namespace Eigen;\n\nusing ceres::AutoDiffCostFunction;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solver;\nusing ceres::Solve;\n\nusing namespace std;\n\n\nint RobotWorldHandEyeCalibration(double square_mm_height, double square_mm_width,\n\t\tint chess_h, int chess_w, string source_dir, string write_dir,  bool do_camcali, bool do_rwhec, bool do_reconstruction, bool verbose);\n\nvoid WriteCaliFile(CaliObjectOpenCV2* CO, std::ofstream& out);\n\nvoid WriteCaliFile(CaliObjectOpenCV2* CO, vector<MatrixXd>& As, vector<Matrix4d>& Bs, Matrix4d& X, Matrix4d& Z, std::ofstream& out);\n//void WriteCaliFile(CaliObjectOpenCV2* CO, vector<MatrixXd>& As, vector<MatrixXd>& Bs, Matrix& X, Matrix& Z, std::ofstream& out);\n\n//void ReadRobotFileDensoArm(string write_dir, vector<Matrix4d>& Bs);\n\nvoid ReadRobotFileRobotCaliTxt(string filename, vector<Matrix4d>& Bs);\n\n\ndouble AssessErrorWhole(vector<MatrixXd>& As, vector<Matrix4d>& Bs, Matrix4d& X, Matrix4d& Z);\n\ndouble AssessRotationError(vector<MatrixXd>& As, vector<Matrix4d>& Bs, Matrix4d& X, Matrix4d& Z);\n\ndouble AssessRotationErrorAxisAngle(vector<MatrixXd>& As, vector<Matrix4d>& Bs, Matrix4d& X, Matrix4d& Z);\n\ndouble AssessTranslationErrorDenominator(vector<Matrix4d>& As, vector<Matrix4d>& Bs, Matrix4d& X, Matrix4d& Z);\n\n//double AssessTranslationError(vector<MatrixXd>& As_temp, vector<Matrix4d>& Bs_temp, Matrix4d& X_temp, Matrix4d& Z_temp);\ndouble AssessTranslationError(vector<MatrixXd>& As, vector<Matrix4d>& Bs, Matrix4d& X, Matrix4d& Z);\n\ndouble CalculateReprojectionError(CaliObjectOpenCV2* CO, vector<MatrixXd>& As, vector<Matrix4d>& Bs,\n\t\t\tMatrix4d& X, Matrix4d& Z, std::ofstream& out, string directory, int cam_number);\n\nvoid WritePatterns(double* pattern_points, int chess_h, int chess_w, int index_number, string outfile);\n\nstring FindValueOfFieldInFile(string filename, string fieldTag, bool seperator);\n\nvoid EnsureDirHasTrailingBackslash(string& write_directory);\n\nMatrix4d ConvertToMM(Matrix4d XM){\n\tdouble unit = 1000;\n  XM(0,3) = unit*XM(0,3);\n  XM(1,3) = unit*XM(1,3);\n  XM(2,3) = unit*XM(2,3);\n  return XM;\n}\n\nMatrix4d ConvertFromMM(Matrix4d XM){\n\tdouble unit = 1000;\n  XM(0,3) = XM(0,3)/unit;\n  XM(1,3) = XM(1,3)/unit;\n  XM(2,3) = XM(2,3)/unit;\n  return XM;\n}\n\ndouble ConvertToMM(double XM){\n\tdouble unit = 1000;\n  return unit*XM;\n}\n\ndouble ConvertFromMM(double XM){\n\tdouble unit = 1000;\n  return XM/unit;\n}\n\n#endif /* TABB_AHMADYOUSEF_RWHEC_MAY2018_MAIN_HPP_ */\n", "meta": {"hexsha": "d5fdb64b5efa1ce2f31035c8cea2a583aaaf8ce5", "size": 2815, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "code_src/Tabb_AhmadYousef_RWHEC_Jun2018_main.hpp", "max_stars_repo_name": "rprakitpong-apera/RWHEC-Tabb-AhmadYousef", "max_stars_repo_head_hexsha": "0c44a98cdb88d7ff08463f86e713555afeea52e2", "max_stars_repo_licenses": ["MIT"], "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_src/Tabb_AhmadYousef_RWHEC_Jun2018_main.hpp", "max_issues_repo_name": "rprakitpong-apera/RWHEC-Tabb-AhmadYousef", "max_issues_repo_head_hexsha": "0c44a98cdb88d7ff08463f86e713555afeea52e2", "max_issues_repo_licenses": ["MIT"], "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/Tabb_AhmadYousef_RWHEC_Jun2018_main.hpp", "max_forks_repo_name": "rprakitpong-apera/RWHEC-Tabb-AhmadYousef", "max_forks_repo_head_hexsha": "0c44a98cdb88d7ff08463f86e713555afeea52e2", "max_forks_repo_licenses": ["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.9340659341, "max_line_length": 136, "alphanum_fraction": 0.7570159858, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5125586864499858}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Peter Caspers\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 \"noarbsabr.hpp\"\n#include \"utilities.hpp\"\n\n#include <boost/assign/list_of.hpp>\n\n#include <ql/termstructures/volatility/sabrsmilesection.hpp>\n#include <ql/experimental/volatility/noarbsabrsmilesection.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\nnamespace {\nvoid checkD0(const Real sigmaI, const Real beta, const Real rho, const Real nu,\n             const Real tau, const unsigned int absorptions) {\n\n    Real forward = 0.03; // does not matter in the end\n    Real alpha = sigmaI / std::pow(forward, beta - 1.0);\n\n    detail::D0Interpolator d(forward, tau, alpha, beta, nu, rho);\n\n    if (std::fabs(d() * detail::NoArbSabrModel::nsim - (Real)absorptions) > 0.1)\n        BOOST_ERROR(\"failed to reproduce number of absorptions at sigmaI=\"\n                    << sigmaI << \", beta=\" << beta << \", rho=\" << rho << \", nu=\"\n                    << nu << \" tau=\" << tau << \": D0Interpolator says \"\n                    << d() * detail::NoArbSabrModel::nsim\n                    << \" while the reference value is \" << absorptions);\n\n    return;\n}\n}\n\nvoid NoArbSabrTest::testAbsorptionMatrix() {\n\n    BOOST_TEST_MESSAGE(\"Testing noarb-sabr absorption matrix ...\");\n\n    // check some points explicitly against the external file's contents\n\n    // sigmaI, beta, rho, nu, tau, absorptions\n    checkD0(1,0.01,0.75,0.1,0.25,60342); // upper left corner\n    checkD0(0.8,0.01,0.75,0.1,0.25,12148);\n    checkD0(0.05,0.01,0.75,0.1,0.25,0);\n    checkD0(1,0.01,0.75,0.1,10.0,1890509);\n    checkD0(0.8,0.01,0.75,0.1,10.0,1740233);\n    checkD0(0.05,0.01,0.75,0.1,10.0,0);\n    checkD0(1,0.01,0.75,0.1,30.0,2174176);\n    checkD0(0.8,0.01,0.75,0.1,30.0,2090672);\n    checkD0(0.05,0.01,0.75,0.1,30.0,31);\n    checkD0(0.35,0.10,-0.75,0.1,0.25,0);\n    checkD0(0.35,0.10,-0.75,0.1,14.75,1087841);\n    checkD0(0.35,0.10,-0.75,0.1,30.0,1406569);\n    checkD0(0.24,0.90,0.50,0.8,1.25,27);\n    checkD0(0.24,0.90,0.50,0.8,25.75,167541);\n    checkD0(0.05,0.90,-0.75,0.8,2.0,17);\n    checkD0(0.05,0.90,-0.75,0.8,30.0,42100); // lower right corner\n\n    // check the entire matrix against a hash value produced on the original\n    // quantlib file noarbsabrabsprobs.cpp to make sure that this has\n    // not been changed\n\n    try {\n        NoArbSabrModel::checkAbsorptionMatrix();\n    } catch(QuantLib::Error) {\n        BOOST_ERROR(\"failed to verify the hash value of the absorption matrix\");\n    }\n\n}\n\nvoid NoArbSabrTest::testConsistencyWithHagan() {\n\n    BOOST_TEST_MESSAGE(\"Testing consistency of noarb-sabr with Hagan et al (2002)\");\n\n    // parameters taken from Doust's paper, figure 3\n\n    Real tau = 1.0;\n    Real beta = 0.5;\n    Real alpha = 0.026;\n    Real rho = -0.1;\n    Real nu = 0.4;\n    Real f = 0.0488;\n\n    SabrSmileSection sabr(tau,f,boost::assign::list_of(alpha)(beta)(nu)(rho));\n    NoArbSabrSmileSection noarbsabr(tau,f,boost::assign::list_of(alpha)(beta)(nu)(rho));\n\n    Real absProb=noarbsabr.model()->absorptionProbability();\n    if( absProb > 1E-10 || absProb < 0.0 )\n        BOOST_ERROR(\"absorption probability should be close to zero, but is \" << absProb);\n\n    Real strike = 0.0001;\n    while (strike < 0.15) {\n        // test vanilla prices\n        Real sabrPrice = sabr.optionPrice(strike);\n        Real noarbsabrPrice = noarbsabr.optionPrice(strike);\n        if (std::fabs(sabrPrice - noarbsabrPrice) > 1e-5)\n            BOOST_ERROR(\"incosistent Hagan price (\"\n                        << sabrPrice << \") and noarb-sabr price (\"\n                        << noarbsabrPrice << \") at strike \" << strike);\n        // test digitals\n        Real sabrDigital = sabr.digitalOptionPrice(strike);\n        Real noarbsabrDigital = noarbsabr.digitalOptionPrice(strike);\n        if (std::fabs(sabrDigital - noarbsabrDigital) > 1e-3)\n            BOOST_ERROR(\"incosistent Hagan digital (\"\n                        << sabrDigital << \") and noarb-sabr digital (\"\n                        << noarbsabrDigital << \") at strike \" << strike);\n        // test density\n        Real sabrDensity = sabr.density(strike);\n        Real noarbsabrDensity = noarbsabr.density(strike);\n        if (std::fabs(sabrDensity - noarbsabrDensity) > 1e-0)\n            BOOST_ERROR(\"incosistent Hagan density (\"\n                        << sabrDensity << \") and noarb-sabr density (\"\n                        << noarbsabrDensity << \") at strike \" << strike);\n        strike += 0.0001;\n    }\n\n}\n\n\ntest_suite* NoArbSabrTest::suite() {\n    test_suite* suite = BOOST_TEST_SUITE(\"NoArbSabrModel tests\");\n    suite->add(QUANTLIB_TEST_CASE(&NoArbSabrTest::testAbsorptionMatrix));\n    suite->add(QUANTLIB_TEST_CASE(&NoArbSabrTest::testConsistencyWithHagan));\n    return suite;\n}\n", "meta": {"hexsha": "6d15cfbb540f74dde6aeea3ab4511b539014c7ef", "size": 5451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLib/test-suite/noarbsabr.cpp", "max_stars_repo_name": "frannuca/quantlib", "max_stars_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "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": "QuantLib/test-suite/noarbsabr.cpp", "max_issues_repo_name": "frannuca/quantlib", "max_issues_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/test-suite/noarbsabr.cpp", "max_forks_repo_name": "frannuca/quantlib", "max_forks_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-24T04:54:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T04:54:18.000Z", "avg_line_length": 38.3873239437, "max_line_length": 90, "alphanum_fraction": 0.6422674739, "num_tokens": 1694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5125586793100513}}
{"text": "#include <vector>\n#include <iostream>\n\n#include <glm/glm.hpp>\nusing namespace glm;\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n\n#include \"Types.h\"\n#include \"Dynamic.h\"\n\nnamespace{\n    using namespace BalloonFEM;\n    /* push mat3 coefficients into SpMat,\n     * T(target_off + i, source_off + j, H[j][i]) \n     * pay attention that H is column major\n     */\n    void pushMat3(std::vector<T> &coeff, int target_off, int source_off, Mat3 H)\n    {\n        for(int i = 0; i < 3; i++)\n            for(int j = 0; j < 3; j++)\n\t\t\tif (H[j][i] != 0)\n                coeff.push_back( T(target_off + i, source_off + j, H[j][i]) );\n    }\n\n    /* push mat3 coefficients into SpMat,\n     * T(target_off, source_off + i, H[i]) \n     */\n    void pushVec3(std::vector<T> &coeff, int target_off, int source_off, Vec3 H)\n    {\n        for(int i = 0; i < 3; i++)\n            coeff.push_back( T(target_off, source_off + i, H[i]) );\n    }\n\n    int sgn(double val){\n        return ((double(0) < val) - (val < double(0)));\n    }\n}\n\nnamespace BalloonFEM\n{\n    SpMat Engine::bendingForceAndGradient(ObjState &state, Vvec3 &f_sum)\n    {\n        /* compute theta */\n        Vvec3 &pos = state.world_space_pos;\n\n        SpVec dphi = SpVec::Zero(m_tetra->num_hindges);\n        SpMat ddphi(m_tetra->num_hindges, m_tetra->num_hindges);\n\n        ///////////////////////////////////////////////////////////////////////\n        /* compute hindge angle theta and phi, dphi, ddphi */\n        int offset = 0;\n        for(MIter f = m_tetra->films.begin(); f != m_tetra->films.end(); f++)\n        {\n\t\t\tstd::vector<Piece> &pieces = f->pieces;\n            for(EIter h = f->hindges.begin(); h != f->hindges.end(); h++)\n            {\n                /* normal of piece_info[0] */\n                iVec3 &id0 = pieces[h->piece_info[0].x].v_id;\n                Vec3 n0 = cross( pos[id0[0]] - pos[id0[2]], pos[id0[1]] - pos[id0[2]] );\n                n0 /= length(n0);\n\n                /* normal of piece_info[1] */\n                iVec3 &id1 = pieces[h->piece_info[1].x].v_id;\n                Vec3 n1 = cross( pos[id1[0]] - pos[id1[2]], pos[id1[1]] - pos[id1[2]] );\n                n1 /= length(n1);\n\n                /* edge direction , is the positive direction of piece_info[0]*/\n\t\t\t\tint i = h->piece_info[0].y;\n\t\t\t\tint j = (i + 1) % 3, k = (i + 2) % 3;\n                Vec3 e = pos[id0[k]] -  pos[id0[j]];\n                e /= length(e);\n\n\t\t\t\t/* signed theta is defined as positive when n0 n1 point away from each other */\n                /* energy is 2*sin(x/2)^2 */\n\t\t\t\tdouble tmp = max(min(dot(n0, n1), 1.0), -1.0);\n                double theta = acos(tmp) * sgn(dot(e, cross(n0, n1)));\n                dphi(offset) = m_bend_model->dphi(theta, h->theta);\n                ddphi.coeffRef(offset, offset) = m_bend_model->ddphi(theta, h->theta);\n                offset ++;\n            }\n        }\n        \n        //////////////////////////////////////////////////////////////////////\n        /* compute hessian matrix and theta gradient */\n\t\tprintf(\"compute bending force and hessian matrix \\n\");\n        std::vector<T> theta_coeff;\n        theta_coeff.clear();\n\t\ttheta_coeff.reserve( 2 * 9 * m_tetra->num_hindges );\n\n        std::vector<T> hessian_coeff;\n        hessian_coeff.clear();\n        hessian_coeff.reserve( 9 * 9 * m_tetra->num_pieces );\n\n        /* compute detrivation of hindge angle theta */\n        offset = 0;     /* since there may be more than one film obj */\n        for(MIter f = m_tetra->films.begin(); f != m_tetra->films.end(); f++)\n        {\n            for(PIter p = f->pieces.begin(); p != f->pieces.end(); p++)\n            {\n                iVec3 &v_id = p->v_id;\n                /* edge dire , length , norm and area*/\n                Vec3 e[3] = { \n                    pos[v_id[2]] - pos[v_id[1]],\n                    pos[v_id[0]] - pos[v_id[2]],\n                    pos[v_id[1]] - pos[v_id[0]],\n                };\n\n                Vec3 norm = cross( e[0], e[1] );\n                double A2 = length(norm);\n                norm /= A2;\n\n\t\t\t\tVec3 l = Vec3(length(e[0]), length(e[1]), length(e[2]));\n\t\t\t\tfor (int i = 0; i < 3; i++)\n\t\t\t\t\te[i] /= l[i];\n\n                /* height of vertex */\n                Vec3 h_inv = l / A2;\n\t\t\t\tMat3 w = outerProduct(h_inv, h_inv);\n\n                /* cosine of vertex */\n\n                double cos[3] = { \n                    - dot(e[1], e[2]),\n                    - dot(e[2], e[0]),\n                    - dot(e[0], e[1]),\n                };\n\n                /* edge normal m */\n                Vec3 m[3] = { \n                    cross(e[0], norm),\n                    cross(e[1], norm),\n                    cross(e[2], norm),\n                };\n\n                /* intermediate var Mi */\n                Mat3 M[3] = { \n                    outerProduct(norm, m[0]), \n\t\t\t\t\touterProduct(norm, m[1]),\n\t\t\t\t\touterProduct(norm, m[2]),\n                };\n\n                /* intermediate var Ni */\n                Mat3 N[3] = {\n                    M[0] / (l.x * l.x), M[1] / (l.y * l.y), M[2] / (l.z * l.z)\n                };\n\n                /* intermediate var ci */\n                double c[3] = {0, 0, 0};\n                Mat3 R[3] = {Mat3(0), Mat3(0), Mat3(0)};\n                for(int i = 0; i < 3; i++)\n                    if (p->hindge_id[i] != -1)\n                    {\n\t\t\t\t\t\tc[i] = dphi(p->hindge_id[i] + offset);\n                        R[i] = c[i]*N[i];\n                    }\n\n                /* intermediate var di */\n                double d[3] = {0, 0, 0};\n                for(int i = 0; i < 3; i++)\n                {\n                    int j = (i+1) % 3, k = (i+2) % 3;\n                    d[i] = c[j] * cos[k] + c[k] * cos[j] - c[i];\n                }\n\n                /* for each triangle, compute contribution to Heissen */\n                for(int i = 0; i < 3; i++)\n                {\n                    int j = (i+1) % 3, k = (i+2) % 3;\n\n                    /* j = i */\n                    Mat3 H = w[i][i] * d[i] * (M[i] + transpose(M[i])) - R[j] - R[k];\n\n                    pushMat3(hessian_coeff, 3 * v_id[i], 3 * v_id[i], H);\n\n                    /* j = i + 1 */\n                    H = w[i][j] * (d[i] * transpose(M[j]) + d[j] * M[i]) + R[k];\n\n                    pushMat3(hessian_coeff, 3 * v_id[i], 3 * v_id[j], H);\n                    \n                    /* symmetric j = i + 2 */\n                    pushMat3(hessian_coeff, 3 * v_id[j], 3 * v_id[i], transpose(H));\n                }\n\n                /* for each vertex if its correspond edge is hindge\n                 * compute gradient of theta \n                 */\n                for(int i = 0; i < 3; i++)\n                {\n                    if (p->hindge_id[i] != -1)\n                    {\n                        int h_id = p->hindge_id[i] + offset;\n\n                        int j = (i+1) % 3;\n                        int k = (i+2) % 3;\n\n                        Vec3 tmp;\n\n                        /* \\dev_{x0} theta = - n / h0 */\n                        tmp = - norm * h_inv[i];\n                        pushVec3( theta_coeff, h_id, 3 * v_id[i], tmp);\n\n                        /* \\dev_{x1} theta = n * cos2 / h1 */\n                        tmp = norm * cos[k] * h_inv[j];\n                        pushVec3( theta_coeff, h_id, 3 * v_id[j], tmp);\n\n                        /* \\dev_{x1} theta = n * cos1 / h2 */\n                        tmp = norm * cos[j] * h_inv[k];\n                        pushVec3( theta_coeff, h_id, 3 * v_id[k], tmp);\n                    }\n                }\n\n            }\n            offset += f->hindges.size();\n        }\n\n        /* compute bending force */\n        SpMat theta_grad(m_tetra->num_hindges, 3 * m_tetra->num_vertex);\n        theta_grad.setFromTriplets(theta_coeff.begin(), theta_coeff.end());\n\n        SpVec bendforce = - dphi.transpose() * theta_grad;\n\n        for(size_t i = 0; i < f_sum.size(); i++)\n        {\n            f_sum[i] += Vec3(\n                    bendforce(3*i    ), \n                    bendforce(3*i + 1), \n                    bendforce(3*i + 2));\n        }\n\n        SpMat H(3 * m_tetra->num_vertex, 3 * m_tetra->num_vertex);\n\n        H.setFromTriplets(hessian_coeff.begin(), hessian_coeff.end());\n\n\t\tH +=  theta_grad.transpose() * ddphi * theta_grad;\n\n        return H;\n    }\n}\n", "meta": {"hexsha": "a4f951b7f1f9bef0fbd4c452bcbb27737d7e56a7", "size": 8263, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Dynamic_Hindge.cpp", "max_stars_repo_name": "milkpku/FEM_practice", "max_stars_repo_head_hexsha": "5498de6c8d99c5336f7aaf0044335d61ffc0a02c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Dynamic_Hindge.cpp", "max_issues_repo_name": "milkpku/FEM_practice", "max_issues_repo_head_hexsha": "5498de6c8d99c5336f7aaf0044335d61ffc0a02c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Dynamic_Hindge.cpp", "max_forks_repo_name": "milkpku/FEM_practice", "max_forks_repo_head_hexsha": "5498de6c8d99c5336f7aaf0044335d61ffc0a02c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-10T08:20:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-10T08:20:06.000Z", "avg_line_length": 34.1446280992, "max_line_length": 88, "alphanum_fraction": 0.4142563234, "num_tokens": 2267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5125084986081048}}
{"text": "#include <string>\n\n#include <ros/ros.h>\n#include <geometry_msgs/Point.h>\n#include <tf2_eigen/tf2_eigen.h>\n#include <tf2_ros/transform_listener.h>\n\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\nint main(int argc, char** argv)\n{\n  ros::init(argc, argv, \"relational_position_publisher\");\n  ros::NodeHandle n {};\n\n  int target_number {1};\n  std::string root_name {\"openni_coordinater\"};\n  std::string to_name {\"left_foot\"};\n  std::string from_name {\"torso\"};\n  {\n    ros::NodeHandle pn {\"~\"};\n    pn.getParam(\"target_number\", target_number);\n    pn.getParam(\"root\", root_name);\n    pn.getParam(\"to\", to_name);\n    pn.getParam(\"from\", from_name);\n  }\n\n  const auto to_frame_name {to_name + '_' + std::to_string(target_number)};\n  const auto from_frame_name {from_name + '_' + std::to_string(target_number)};\n\n  ros::Publisher pub {n.advertise<geometry_msgs::Point>(to_frame_name + \"_direction\", 1)};\n  ros::Rate r {5};\n  tf2_ros::Buffer tfBuffer {};\n  tf2_ros::TransformListener tfListener {tfBuffer};\n\n  while (ros::ok()) {\n    try {\n      const auto to_pos {tf2::transformToEigen(tfBuffer.lookupTransform(root_name, to_frame_name, ros::Time{0}))};\n      const auto from_pos {tf2::transformToEigen(tfBuffer.lookupTransform(root_name, from_frame_name, ros::Time{0}))};\n      const auto from_ypr {from_pos.rotation().eulerAngles(1, 0, 2)};\n      const auto yaw_angle {from_ypr(0)};\n      const Eigen::AngleAxisd yaw_inverse_rotation {-yaw_angle, Eigen::Vector3d::UnitY()};\n      const auto stand_vec {to_pos.translation() - from_pos.translation()};\n      const auto current_vec {yaw_inverse_rotation * stand_vec};\n\n      pub.publish(tf2::toMsg(current_vec));\n    } catch (tf2::TransformException &e) {\n      ROS_WARN(\"%s\", e.what());\n    }\n\n    r.sleep();\n  }\n}\n", "meta": {"hexsha": "3e8c0759de1706da945cc94a560925869168776f", "size": 1758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/relational_position_publisher.cpp", "max_stars_repo_name": "forno/body_angle_visualizer", "max_stars_repo_head_hexsha": "0e0719fed7be007904e51399ecdf43a6f73fc8e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T04:44:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T04:44:20.000Z", "max_issues_repo_path": "src/relational_position_publisher.cpp", "max_issues_repo_name": "forno/body_angle_visualizer", "max_issues_repo_head_hexsha": "0e0719fed7be007904e51399ecdf43a6f73fc8e1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/relational_position_publisher.cpp", "max_forks_repo_name": "forno/body_angle_visualizer", "max_forks_repo_head_hexsha": "0e0719fed7be007904e51399ecdf43a6f73fc8e1", "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.5555555556, "max_line_length": 118, "alphanum_fraction": 0.6871444824, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5125084941454482}}
{"text": "#include \"Cos.hh\"\n#include \"TypesFunctions.hh\"\n#include <Eigen/Core>\n\n/**\n * @brief Constructor.\n */\nCos::Cos() {\n    transformation_(\"cos\")\n        .input(\"points\")\n\t.output(\"result\")\n\t.types(TypesFunctions::ifPoints<0>, TypesFunctions::pass<0>)\n\t.func(&Cos::calculate)\n      ;\n}\n\nCos::Cos(OutputDescriptor& output) : Cos() {\n    transformations.front().inputs.front().connect(output);\n}\n\n/**\n * @brief Calculate the value of function.\n */\nvoid Cos::calculate(FunctionArgs& fargs){\n    fargs.rets[0].x = fargs.args[0].x.cos();\n}\n\n", "meta": {"hexsha": "7a6c7b98300526822aef66e3b2f6709f9cc5755f", "size": 531, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/functions/Cos.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/functions/Cos.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/functions/Cos.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.9642857143, "max_line_length": 61, "alphanum_fraction": 0.6440677966, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985637, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.512508487451463}}
{"text": "#include <Eigen/LU>\n#include <cmath>\n#include <iostream>\n#include <mathtoolbox/constants.hpp>\n#include <mathtoolbox/log-determinant.hpp>\n#include <mathtoolbox/probability-distributions.hpp>\n#include <nlopt-util.hpp>\n#include <sequential-line-search/gaussian-process-regressor.hpp>\n#include <sequential-line-search/utils.hpp>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nnamespace\n{\n    using namespace sequential_line_search;\n\n    const bool   use_log_normal_prior  = true;\n    const double a_prior_mu            = std::log(0.500);\n    const double a_prior_sigma_squared = 0.50;\n    const double b_prior_mu            = std::log(1e-04);\n    const double b_prior_sigma_squared = 0.50;\n    const double r_prior_mu            = std::log(0.500);\n    const double r_prior_sigma_squared = 0.50;\n\n    inline VectorXd Concat(const double scalar, const VectorXd& vector)\n    {\n        VectorXd result(vector.size() + 1);\n\n        result(0)                        = scalar;\n        result.segment(1, vector.size()) = vector;\n\n        return result;\n    }\n\n    double calc_grad_a_prior(const double a)\n    {\n        return mathtoolbox::GetLogOfLogNormalDistDerivative(a, a_prior_mu, a_prior_sigma_squared);\n    }\n\n    double calc_grad_b_prior(const double b)\n    {\n        return mathtoolbox::GetLogOfLogNormalDistDerivative(b, b_prior_mu, b_prior_sigma_squared);\n    }\n\n    double calc_grad_r_i_prior(const Eigen::VectorXd& r, const int index)\n    {\n        return mathtoolbox::GetLogOfLogNormalDistDerivative(r(index), r_prior_mu, r_prior_sigma_squared);\n    }\n\n    double calc_a_prior(const double a)\n    {\n        return mathtoolbox::GetLogOfLogNormalDist(a, a_prior_mu, a_prior_sigma_squared);\n    }\n\n    double calc_b_prior(const double b)\n    {\n        return mathtoolbox::GetLogOfLogNormalDist(b, b_prior_mu, b_prior_sigma_squared);\n    }\n\n    double calc_r_i_prior(const Eigen::VectorXd& r, const int index)\n    {\n        return mathtoolbox::GetLogOfLogNormalDist(r(index), r_prior_mu, r_prior_sigma_squared);\n    }\n\n    double calc_grad_b(const MatrixXd& X,\n                       const MatrixXd& K_y_inv,\n                       const VectorXd& y,\n                       const double    a,\n                       const double    b,\n                       const VectorXd& r)\n    {\n        const MatrixXd K_y_grad_b = CalcLargeKYNoiseLevelDerivative(X, Concat(a, r), b);\n        const double   term1      = +0.5 * y.transpose() * K_y_inv * K_y_grad_b * K_y_inv * y;\n        const double   term2      = -0.5 * (K_y_inv * K_y_grad_b).trace();\n        return term1 + term2 + (use_log_normal_prior ? calc_grad_b_prior(b) : 0.0);\n    }\n\n    VectorXd calc_grad_theta(const MatrixXd&             X,\n                             const MatrixXd&             K_y_inv,\n                             const VectorXd&             y,\n                             const VectorXd&             kernel_hyperparams,\n                             const KernelThetaDerivative kernel_theta_derivative)\n    {\n        const std::vector<MatrixXd> tensor = CalcLargeKYThetaDerivative(X, kernel_hyperparams, kernel_theta_derivative);\n\n        VectorXd grad(kernel_hyperparams.size());\n        for (unsigned i = 0; i < kernel_hyperparams.size(); ++i)\n        {\n            const MatrixXd& K_y_grad_r_i = tensor[i];\n\n            const double term1 = +0.5 * y.transpose() * K_y_inv * K_y_grad_r_i * K_y_inv * y;\n            const double term2 = -0.5 * (K_y_inv * K_y_grad_r_i).trace();\n\n            const double prior =\n                use_log_normal_prior\n                    ? (i == 0\n                           ? calc_grad_a_prior(kernel_hyperparams(i))\n                           : calc_grad_r_i_prior(kernel_hyperparams.segment(1, kernel_hyperparams.size() - 1), i - 1))\n                    : 0.0;\n\n            grad(i) = term1 + term2 + prior;\n        }\n\n        return grad;\n    }\n\n    VectorXd calc_grad(const MatrixXd&             X,\n                       const MatrixXd&             K_y_inv,\n                       const VectorXd&             y,\n                       const double                a,\n                       const double                b,\n                       const VectorXd&             r,\n                       const KernelThetaDerivative kernel_theta_derivative)\n    {\n        const unsigned D = X.rows();\n\n        VectorXd grad(D + 2);\n\n        const VectorXd grad_theta = calc_grad_theta(X, K_y_inv, y, Concat(a, r), kernel_theta_derivative);\n\n        grad(0)            = grad_theta(0);\n        grad(1)            = calc_grad_b(X, K_y_inv, y, a, b, r);\n        grad.segment(2, D) = grad_theta.segment(1, D);\n\n        return grad;\n    }\n\n    struct Data\n    {\n        const MatrixXd              X;\n        const VectorXd              y;\n        const Kernel                kernel;\n        const KernelThetaDerivative kernel_theta_derivative;\n    };\n\n    // For counting the number of function evaluations\n    unsigned count;\n\n    // Log likelihood that will be maximized\n    double objective(const std::vector<double>& x, std::vector<double>& grad, void* data)\n    {\n        // For counting the number of function evaluations\n        ++count;\n\n        const MatrixXd& X = static_cast<const Data*>(data)->X;\n        const VectorXd& y = static_cast<const Data*>(data)->y;\n\n        const auto kernel                  = static_cast<const Data*>(data)->kernel;\n        const auto kernel_theta_derivative = static_cast<const Data*>(data)->kernel_theta_derivative;\n\n        const unsigned N = X.cols();\n\n        const double   a = x[0];\n        const double   b = x[1];\n        const VectorXd r = Eigen::Map<const VectorXd>(&x[2], x.size() - 2);\n\n        const MatrixXd K_y     = CalcLargeKY(X, Concat(a, r), b, kernel);\n        const MatrixXd K_y_inv = K_y.inverse();\n\n        // When the algorithm is gradient-based, compute the gradient vector\n        if (grad.size() == x.size())\n        {\n            const VectorXd g = calc_grad(X, K_y_inv, y, a, b, r, kernel_theta_derivative);\n            for (unsigned i = 0; i < g.rows(); ++i)\n            {\n                grad[i] = g(i);\n            }\n        }\n\n        // Constant\n        constexpr double prod_of_two_and_pi = 2.0 * mathtoolbox::constants::pi;\n\n        const double term1 = -0.5 * y.transpose() * K_y_inv * y;\n        const double term2 = -0.5 * mathtoolbox::CalcLogDetOfSymmetricPositiveDefiniteMatrix(K_y);\n        const double term3 = -0.5 * N * std::log(prod_of_two_and_pi);\n\n        // Computing the regularization terms from a prior assumptions\n        const double a_prior = calc_a_prior(a);\n        const double b_prior = calc_b_prior(b);\n        const double r_prior = [&r]()\n        {\n            double sum = 0.0;\n            for (unsigned i = 0; i < r.rows(); ++i)\n            {\n                sum += calc_r_i_prior(r, i);\n            }\n            return sum;\n        }();\n        const double regularization = use_log_normal_prior ? (a_prior + b_prior + r_prior) : 0.0;\n\n        return term1 + term2 + term3 + regularization;\n    }\n} // namespace\n\nnamespace sequential_line_search\n{\n    GaussianProcessRegressor::GaussianProcessRegressor(const MatrixXd&  X,\n                                                       const VectorXd&  y,\n                                                       const KernelType kernel_type)\n        : Regressor(kernel_type), m_X(X), m_y(y)\n    {\n        if (X.rows() == 0)\n        {\n            return;\n        }\n\n        PerformMapEstimation();\n\n        m_K_y     = CalcLargeKY(X, m_kernel_hyperparams, m_noise_hyperparam, m_kernel);\n        m_K_y_inv = m_K_y.inverse();\n    }\n\n    GaussianProcessRegressor::GaussianProcessRegressor(const Eigen::MatrixXd& X,\n                                                       const Eigen::VectorXd& y,\n                                                       const Eigen::VectorXd& kernel_hyperparams,\n                                                       double                 noise_hyperparam,\n                                                       const KernelType       kernel_type)\n        : Regressor(kernel_type),\n          m_X(X),\n          m_y(y),\n          m_kernel_hyperparams(kernel_hyperparams),\n          m_noise_hyperparam(noise_hyperparam)\n    {\n        if (X.rows() == 0)\n        {\n            return;\n        }\n\n        m_K_y     = CalcLargeKY(X, m_kernel_hyperparams, m_noise_hyperparam, m_kernel);\n        m_K_y_inv = m_K_y.inverse();\n    }\n\n    double GaussianProcessRegressor::PredictMu(const VectorXd& x) const\n    {\n        // TODO: Incorporate a mean function\n        const VectorXd k = CalcSmallK(x, m_X, m_kernel_hyperparams, m_kernel);\n        return k.transpose() * m_K_y_inv * m_y;\n    }\n\n    double GaussianProcessRegressor::PredictSigma(const VectorXd& x) const\n    {\n        const VectorXd k = CalcSmallK(x, m_X, m_kernel_hyperparams, m_kernel);\n\n        // This code assumes that the kernel is either ARD squared exponential or ARD Matern and the first\n        // hyperparameter represents the intensity of the kernel.\n        assert(m_kernel_hyperparams.size() == x.size() + 1);\n        const double intensity = m_kernel_hyperparams[0];\n\n        return std::sqrt(intensity - k.transpose() * m_K_y_inv * k);\n    }\n\n    Eigen::VectorXd GaussianProcessRegressor::PredictMuDerivative(const Eigen::VectorXd& x) const\n    {\n        // TODO: Incorporate a mean function\n        const MatrixXd k_x_derivative =\n            CalcSmallKSmallXDerivative(x, m_X, m_kernel_hyperparams, m_kernel_first_arg_derivative);\n        return k_x_derivative * m_K_y_inv * m_y;\n    }\n\n    Eigen::VectorXd GaussianProcessRegressor::PredictSigmaDerivative(const Eigen::VectorXd& x) const\n    {\n        const MatrixXd k_x_derivative =\n            CalcSmallKSmallXDerivative(x, m_X, m_kernel_hyperparams, m_kernel_first_arg_derivative);\n        const VectorXd k     = CalcSmallK(x, m_X, m_kernel_hyperparams, m_kernel);\n        const double   sigma = PredictSigma(x);\n        return -(1.0 / sigma) * k_x_derivative * m_K_y_inv * k;\n    }\n\n    void GaussianProcessRegressor::PerformMapEstimation()\n    {\n        const unsigned D = m_X.rows();\n\n        Data data{m_X, m_y, m_kernel, m_kernel_theta_derivative};\n\n        const VectorXd x_ini = [&]()\n        {\n            VectorXd x(D + 2);\n\n            x(0)            = std::exp(a_prior_mu);\n            x(1)            = std::exp(b_prior_mu);\n            x.segment(2, D) = VectorXd::Constant(D, std::exp(r_prior_mu));\n\n            return x;\n        }();\n\n        const VectorXd upper = VectorXd::Constant(D + 2, 5e+01);\n        const VectorXd lower = VectorXd::Constant(D + 2, 1e-08);\n\n        const VectorXd x_glo = nloptutil::solve(x_ini, upper, lower, objective, nlopt::GN_DIRECT, &data, true, 300);\n        const VectorXd x_loc = nloptutil::solve(x_glo, upper, lower, objective, nlopt::LD_TNEWTON, &data, true, 1000);\n\n        m_kernel_hyperparams = Concat(x_loc(0), x_loc.segment(2, D));\n        m_noise_hyperparam   = x_loc(1);\n    }\n} // namespace sequential_line_search\n", "meta": {"hexsha": "577a74f460b57368f3af95d1edcf4b124b242920", "size": 10973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gaussian-process-regressor.cpp", "max_stars_repo_name": "yuki-koyama/sequential-line-search", "max_stars_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2018-03-12T13:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T20:28:04.000Z", "max_issues_repo_path": "src/gaussian-process-regressor.cpp", "max_issues_repo_name": "yuki-koyama/sequential-line-search", "max_issues_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T23:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T03:52:42.000Z", "max_forks_repo_path": "src/gaussian-process-regressor.cpp", "max_forks_repo_name": "yuki-koyama/sequential-line-search", "max_forks_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-06-12T17:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T11:13:03.000Z", "avg_line_length": 36.9461279461, "max_line_length": 120, "alphanum_fraction": 0.5785108904, "num_tokens": 2575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5124239834432083}}
{"text": "#pragma once\n#include \"math.h\"\n#include \"math.h\"\n#include <tuple>\n#include \"integration.hpp\"\n//#include \"datatypes.hpp\"\n#include <boost/python.hpp>\n#include <boost/math/special_functions.hpp>\n#include \"gsl/gsl_sf_bessel.h\"\n\nnamespace gd {\nusing namespace std;\n\nvoid py_export_profile();\n\nclass Density3d {\npublic:\n\tvirtual double density(double x, double y, double z) = 0;  \n};\n\nclass Profile3d : public Density3d {\npublic:\n\tvirtual double density(double x, double y, double z) = 0;  \n\tvirtual double potential(double x, double y, double z) = 0;\n\tvirtual double dphidx(double x, double y, double z) = 0;\n\tvirtual double dphidy(double x, double y, double z) = 0;\n\tvirtual double dphidz(double x, double y, double z) = 0;\n\n\t\n\t/*double enclosed_mass(double r) {\n\t\tauto dmass = [this](double rp){ return this->densityr(rp) * rp*rp * 4 * M_PI; };\n\t\tIntegratorGSL<> integratorGSL(dmass); // the integrator\n\t\tdouble integral = integratorGSL.integrate(0,r);\n\t\treturn integral;\n\t}\n\tdouble total_mass() {\n\t\tauto dmass = [this](double rp){ return this->densityr(rp) * rp*rp * 4 * M_PI; };\n\t\tIntegratorGSL<> integratorGSL(dmass); // the integrator\n\t\tdouble integral = integratorGSL.integrate_to_inf(0);\n\t\treturn integral;\n\t}*/\n};\n\nclass ProfileModel3d {\npublic:\n\tvirtual double density(double x, double y, double z) = 0;  \n\tvirtual double potential(double x, double y, double z) = 0;\n\tvirtual double dphidx(double x, double y, double z) = 0;\n\tvirtual double dphidy(double x, double y, double z) = 0;\n\tvirtual double dphidz(double x, double y, double z) = 0;\n};\n\nclass ProfileModel3d1C : public ProfileModel3d {\npublic:\n\tProfileModel3d1C(Profile3d* p) : p(p) {} \n\tvirtual double density(double x, double y, double z) { return p->density(x, y, z); }\n\tvirtual double potential(double x, double y, double z) { return p->potential(x, y, z); }\n\tvirtual double dphidx(double x, double y, double z) { return p->dphidx(x, y, z); }\n\tvirtual double dphidy(double x, double y, double z) { return p->dphidy(x, y, z); }\n\tvirtual double dphidz(double x, double y, double z) { return p->dphidz(x, y, z); }\n\tProfile3d* p;\n};\n\nclass ProfileModel3d2C : public ProfileModel3d {\npublic:\n\tProfileModel3d2C(Profile3d* p1, Profile3d* p2) : p1(p1), p2(p2) {} \n\tvirtual double density(double x, double y, double z) { return p1->density(x, y, z) +  p2->density(x, y, z); }\n\tvirtual double potential(double x, double y, double z) { return p1->potential(x, y, z) + p2->potential(x, y, z); }\n\tvirtual double dphidx(double x, double y, double z) { return p1->dphidx(x, y, z) + p2->dphidx(x, y, z); }\n\tvirtual double dphidy(double x, double y, double z) { return p1->dphidy(x, y, z) + p2->dphidy(x, y, z); }\n\tvirtual double dphidz(double x, double y, double z) { return p1->dphidz(x, y, z) + p2->dphidz(x, y, z); }\n\tProfile3d* p1;\n\tProfile3d* p2;\n};\n\n\nclass NFW3d : public Profile3d {\npublic:\n\tNFW3d(double mass200, double rs, double G, double rho_crit) : mass200(mass200), rs(rs), G(G) {\n\t\tr200 = pow(mass200/200*3/(4*M_PI)/rho_crit, 1./3);\n\t\tc = r200/rs;\n\t\tdouble x = r200 / rs;\n\t\trho0 = mass200 / (4*M_PI*pow(rs,3)*(log(1+x)-x/(1+x)));\n\t}\n\tvirtual double density(double x, double y, double z) {\n\t\treturn this->densityr(sqrt(x*x + y*y + z*z));\n\t}\n\tvirtual double potential(double x, double y, double z) {\n\t\treturn this->potentialr(sqrt(x*x + y*y + z*z));\n\t}\n\tvirtual double dphidx(double x, double y, double z) {\n\t\tdouble r = sqrt(x*x + y*y + z*z);\n\t\tdouble dphidr = this->dphidr(r);\n\t\treturn -dphidr*x/r;\n\t}\n\tvirtual double dphidy(double x, double y, double z) {\n\t\tdouble r = sqrt(x*x + y*y + z*z);\n\t\tdouble dphidr = this->dphidr(r);\n\t\treturn -dphidr*y/r;\n\t}\n\tvirtual double dphidz(double x, double y, double z) {\n\t\tdouble r = sqrt(x*x + y*y + z*z);\n\t\tdouble dphidr = this->dphidr(r);\n\t\treturn -dphidr*z/r;\n\t}\n\tdouble potentialr(double r) {\n\t\tdouble x = r/rs;\n\t\treturn - 4 * M_PI * G * rho0 * rs*rs * log(1+x)/x;\n\t}\n\tdouble densityr(double r) {\n\t\tdouble x = r/rs;\n\t\treturn rho0 / (x * pow(1+x, 2));\n\t}\n\tdouble dphidr(double r) {\n\t\tdouble x = r/rs;\n\t\tdouble f = -4.0*M_PI*G*rho0*pow(rs, 3)/pow(r,2);\n\t\tdouble t1 = log(1.0 + x);\n\t\tdouble t2 = x/(1.0+x);\n\t\t//cout << x << \", \" << f << \", \" << t1 << \", \" << t2 << endl;\n\t\treturn -f*(t1 - t2);\n\t}\n\tdouble mass200, rho0, rs, r200, c, G;\n};\n\n\nclass NFW3dTriax : public Profile3d {\npublic:\n\tNFW3dTriax(double mass200, double rs, double G, double rho_crit, double a, double b, double c, double ra) : mass200(mass200), rs(rs), G(G), a(a), b(b), c(c), ra(ra)  {\n\t\tr200 = pow(mass200/200*3/(4*M_PI)/rho_crit, 1./3);\n\t\tconcentration = r200/rs;\n\t\tdouble x = r200 / rs;\n\t\trho0 = mass200 / (4*M_PI*pow(rs,3)*(log(1+x)-x/(1+x)));\n\t}\n\tvirtual double density(double x, double y, double z) {\n\t\treturn 0 ;//this->densityr(sqrt(x*x + y*y + z*z));\n\t}\n\tvirtual double potential(double x, double y, double z) {\n\t\treturn this->potentialr( this->rtilde(x, y, z));\n\t}\n\tdouble rtilde(double x, double y, double z) {\n\t\tdouble r = sqrt(x*x + y*y + z*z);\n\t\tdouble re = sqrt(x*x / (a*a) + y*y/ (b*b) + z*z/(c*c) );\n\t\treturn (ra+r)*re / (ra+re);\n\t}\n\tvirtual double dphidx(double x, double y, double z) {\n\t\tdouble r = sqrt(x*x + y*y + z*z);\n\t\tdouble re = sqrt(x*x / (a*a) + y*y/ (b*b) + z*z/(c*c) );\n\t\tdouble rtilde = this->rtilde(x, y, z);\n\t\tdouble dphidrtilde = this->dphidr(rtilde);\n\t\tdouble drtildedx = x * (ra * ra * r + ra * r*r + a*a*pow(re,3)  + ra*a*a*re*re) / (a*a*r*re*pow(ra+re, 2));\n\t\treturn -dphidrtilde*drtildedx;\n\t}\n\tvirtual double dphidy(double x, double y, double z) {\n\t\tdouble r = sqrt(x*x + y*y + z*z);\n\t\tdouble re = sqrt(x*x / (a*a) + y*y/ (b*b) + z*z/(c*c) );\n\t\tdouble rtilde = this->rtilde(x, y, z);\n\t\tdouble dphidrtilde = this->dphidr(rtilde);\n\t\tdouble drtildedy = y * (ra * ra * r + ra * r*r + b*b*pow(re,3)  + ra*b*b*re*re) / (b*b*r*re*pow(ra+re, 2));\n\t\treturn -dphidrtilde*drtildedy;\n\t}\n\tvirtual double dphidz(double x, double y, double z) {\n\t\tdouble r = sqrt(x*x + y*y + z*z);\n\t\tdouble re = sqrt(x*x / (a*a) + y*y/ (b*b) + z*z/(c*c) );\n\t\tdouble rtilde = this->rtilde(x, y, z);\n\t\tdouble dphidrtilde = this->dphidr(rtilde);\n\t\tdouble drtildedz = z * (ra * ra * r + ra * r*r + c*c*pow(re,3)  + ra*c*c*re*re) / (c*c*r*re*pow(ra+re, 2));\n\t\treturn -dphidrtilde*drtildedz;\n\t}\n\tdouble potentialr(double r) {\n\t\tdouble x = r/rs;\n\t\treturn - 4 * M_PI * G * rho0 * rs*rs * log(1+x)/x;\n\t}\n\tdouble densityr(double r) {\n\t\tdouble x = r/rs;\n\t\treturn rho0 / (x * pow(1+x, 2));\n\t}\n\tdouble dphidr(double r) {\n\t\tdouble x = r/rs;\n\t\tdouble f = -4.0*M_PI*G*rho0*pow(rs, 3)/pow(r,2);\n\t\tdouble t1 = log(1.0 + x);\n\t\tdouble t2 = x/(1.0+x);\n\t\t//cout << x << \", \" << f << \", \" << t1 << \", \" << t2 << endl;\n\t\treturn -f*(t1 - t2);\n\t}\n\tdouble mass200, rho0, rs, r200, concentration, G, a, b, c, ra;\n};\n\n\nclass  MiyamotoNagai3d : public Profile3d {\npublic:\n\tMiyamotoNagai3d(double mass, double G, double a, double b) : mass(mass), G(G), a(a), b(b)  {\n\t}\n\tvirtual double density(double x, double y, double z) {\n\t\treturn 0 ;//this->densityr(sqrt(x*x + y*y + z*z));\n\t}\n\tvirtual double potential(double x, double y, double z) {\n\t\treturn -G*mass*pow(x*x + y*y +pow(a + pow(z*z+b*b, .5), 2.), -.5);\n\t\t//return this->potentialr( this->rtilde(x, y, z));\n\t}\n\tvirtual double dphidx(double x, double y, double z) {\n\t\tdouble part = G*mass*pow( x*x + y*y + pow(a+ pow(z*z+b*b,.5) , 2.), -1.5);\n\t\treturn -x*part;\n\t}\n\tvirtual double dphidy(double x, double y, double z) {\n\t\tdouble part = G*mass*pow( x*x + y*y + pow(a+ pow(z*z+b*b,.5) , 2.), -1.5);\n\t\treturn -y*part;\n\t}\n\tvirtual double dphidz(double x, double y, double z) {\n\t\tdouble part = G*mass*pow( x*x + y*y + pow(a+ pow(z*z+b*b,.5) , 2.), -1.5);\n\t\treturn -z*part*(a/sqrt(b*b+z*z) + 1);\n\t}\n\tdouble mass, G, a, b;\n};\n\n\n}\n", "meta": {"hexsha": "3e665ac19bc5177e5679db67c1a810eb554eb6f1", "size": 7626, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/profile3d.hpp", "max_stars_repo_name": "maartenbreddels/mab", "max_stars_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T04:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T04:10:34.000Z", "max_issues_repo_path": "gdfast/src/profile3d.hpp", "max_issues_repo_name": "maartenbreddels/mab", "max_issues_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gdfast/src/profile3d.hpp", "max_forks_repo_name": "maartenbreddels/mab", "max_forks_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1428571429, "max_line_length": 168, "alphanum_fraction": 0.6215578285, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5124239834432083}}
{"text": "#include \"assembly.h\"\n#include <armadillo>\n#include <iostream>\n\n// Uncomment out the following line to disable assertions\n//#define NDEBUG 1\n#include <cassert>\n\nusing namespace arma;\nusing namespace std;\n\n/*TODO work with linked lists instead of C-style arrays\n *       this will be easier for memory management */\n\n/**\n * Assembles the global stiffness matrix given an array of elements, mutator\n * \n * @param [mat] kg Global stiffness matrix (by reference)\n * @param [MechElem*] elems Array of pointers to elements to assemble\n * @param [unsigned int] numElements Number of elements in array\n * @param [unsigned int] dofPerElem Total degrees of freedom per element\n * @return void\n */\nvoid mglobalStiffness(mat &kg, MechElem **elems, unsigned int numElements,\n        unsigned int dofPerElem, int pState)\n{\n    // TODO Can we find a way to relate this to global dof??\n    //assert(kg.n_cols == dofPerElem);\n    //assert(kg.n_rows == dofPerElem);\n    /*\n     * TODO reach a consistency where matrices passed by reference are either\n     *      assumed to be zeroed before being passed or are zeroed on pass\n     */\n    kg.zeros();\n    int *gdofs;\n    unsigned int elemNum, i, j;\n    MechElem *pElem;\n    mat *ke = new mat(dofPerElem, dofPerElem);\n    for (elemNum = 0; elemNum < numElements; elemNum++)\n    {\n        pElem = elems[elemNum];\n        gdofs = pElem->getGdofs();\n        pElem->mstiffness(*ke, pState);\n        for (i = 0; i < dofPerElem; i++)\n        {\n            for (j = 0; j < dofPerElem; j++)\n            {\n                // TODO consider renumbering DOF so that we no longer require\n                // this silly minus one business\n                kg(gdofs[i]-1, gdofs[j]-1) += (*ke)(i, j);\n            }\n        }\n    }\n    // free dynamic memory\n    delete ke;\n}\n\n/**\n * Assembles the global body force vector given an array of elements, mutator\n * \n * @param [mat] bg Global body force vector (by reference)\n * @param [MechElem*] elems Array of pointers to elements to assemble\n * @param [unsigned int] numElements Number of elements in array\n * @param [unsigned int] dofPerElem Total degrees of freedom per element\n * @return void\n */\nvoid mglobalBodyForce(vec &bg, MechElem **elems, unsigned int numElements,\n        unsigned int dofPerElem)\n{\n    // TODO Can we write this for global degrees of freedom?\n    //assert(bg.n_cols == dofPerElem);\n    \n    bg.zeros();\n    int *gdofs;\n    unsigned int elemNum, i;\n    MechElem *pElem;\n    vec *be = new vec(dofPerElem);\n    for (elemNum = 0; elemNum < numElements; elemNum++)\n    {\n        pElem = elems[elemNum];\n        gdofs = pElem->getGdofs();\n        pElem->mbodyForce(*be);\n        for (i = 0; i < dofPerElem; i++)\n            bg(gdofs[i]-1) += (*be)(i);\n    }\n    // free dynamic memory\n    delete be;\n}\n", "meta": {"hexsha": "db25a4467886acc46e837afe1b321924aa95442c", "size": 2785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/assembly.cpp", "max_stars_repo_name": "chalavadi/HELWFEM", "max_stars_repo_head_hexsha": "e6d5bc2c95d4de1638c680d079bc41a85cc784a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-16T02:03:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-16T02:03:27.000Z", "max_issues_repo_path": "src/assembly.cpp", "max_issues_repo_name": "chalavadi/HELWFEM", "max_issues_repo_head_hexsha": "e6d5bc2c95d4de1638c680d079bc41a85cc784a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/assembly.cpp", "max_forks_repo_name": "chalavadi/HELWFEM", "max_forks_repo_head_hexsha": "e6d5bc2c95d4de1638c680d079bc41a85cc784a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-16T02:03:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-16T02:03:28.000Z", "avg_line_length": 31.2921348315, "max_line_length": 77, "alphanum_fraction": 0.6305206463, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5122698825518379}}
{"text": "#include \"cpu/image_proc.h\"\r\n\r\n#include <Eigen/Dense>\r\n#include <map>\r\n#include <string>\r\n#include <cmath>\r\n#include <math.h>\r\n\r\n#include \"procrustes.h\"\r\n\r\n\r\nnamespace image_proc {\r\n\r\n    using namespace flow_data_gen;\r\n\r\n    using Vec2d = Eigen::Vector2d;\r\n    using Vec2f = Eigen::Vector2f;\r\n    using Vec2i = Eigen::Vector2i;\r\n    using Vec3d = Eigen::Vector3d;\r\n    using Vec3f = Eigen::Vector3f;\r\n    using Vec3i = Eigen::Vector3i;\r\n\tusing Vec4d = Eigen::Vector4d;\r\n\tusing Vec4f = Eigen::Vector4f;\r\n\tusing Vec4i = Eigen::Vector4i;\r\n\r\n\tusing Mat2d = Eigen::Matrix2d;\r\n\tusing Mat2f = Eigen::Matrix2f;\r\n\tusing Mat2i = Eigen::Matrix2i;\r\n\tusing Mat3d = Eigen::Matrix3d;\r\n\tusing Mat3f = Eigen::Matrix3f;\r\n\tusing Mat3i = Eigen::Matrix3i;\r\n\tusing Mat4d = Eigen::Matrix4d;\r\n\tusing Mat4f = Eigen::Matrix4f;\r\n\tusing Mat4i = Eigen::Matrix4i;\r\n\r\n\r\n    void backproject_depth_ushort(py::array_t<unsigned short>& in, py::array_t<float>& out, float fx, float fy, float cx, float cy, float normalizer) {\r\n        assert(in.ndim() == 2);\r\n        assert(out.ndim() == 3);\r\n\r\n        int width = in.shape(1);\r\n        int height = in.shape(0);\r\n        assert(out.shape(0) == 3);\r\n        assert(out.shape(1) == height);\r\n        assert(out.shape(2) == width);\r\n        \r\n        for (int y = 0; y < height; y++) {\r\n            for (int x = 0; x < width; x++) {\r\n                float depth = float(*in.data(y, x)) / normalizer;\r\n\r\n                if (depth > 0) {\r\n                    float pos_x = depth * (x - cx) / fx;\r\n                    float pos_y = depth * (y - cy) / fy;\r\n                    float pos_z = depth;\r\n\r\n                    *out.mutable_data(0, y, x) = pos_x;\r\n                    *out.mutable_data(1, y, x) = pos_y;\r\n                    *out.mutable_data(2, y, x) = pos_z;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    void backproject_depth_float(py::array_t<float>& in, py::array_t<float>& out, float fx, float fy, float cx, float cy) {\r\n        assert(in.ndim() == 2);\r\n        assert(out.ndim() == 3);\r\n\r\n        int width = in.shape(1);\r\n        int height = in.shape(0);\r\n        assert(out.shape(0) == 3);\r\n        assert(out.shape(1) == height);\r\n        assert(out.shape(2) == width);\r\n        \r\n        for (int y = 0; y < height; y++) {\r\n            for (int x = 0; x < width; x++) {\r\n                float depth = *in.data(y, x);\r\n\r\n                if (depth > 0) {\r\n                    float pos_x = depth * (x - cx) / fx;\r\n                    float pos_y = depth * (y - cy) / fy;\r\n                    float pos_z = depth;\r\n\r\n                    *out.mutable_data(0, y, x) = pos_x;\r\n                    *out.mutable_data(1, y, x) = pos_y;\r\n                    *out.mutable_data(2, y, x) = pos_z;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    void compute_normals(const py::array_t<float>& point_image, py::array_t<float>& normals, float epsilon) {\r\n    \r\n        int height = point_image.shape(0);\r\n        int width  = point_image.shape(1);\r\n     \r\n        for (int y = 1; y < (height - 1); y++) {\r\n            for (int x = 1; x < (width - 1); x++) {\r\n                \r\n                Vec3f xp(*point_image.data(y, x + 1, 0), *point_image.data(y, x + 1, 1), *point_image.data(y, x + 1, 2));\r\n                Vec3f xn(*point_image.data(y, x - 1, 0), *point_image.data(y, x - 1, 1), *point_image.data(y, x - 1, 2));\r\n                \r\n                Vec3f yp(*point_image.data(y + 1, x, 0), *point_image.data(y + 1, x, 1), *point_image.data(y + 1, x, 2));\r\n                Vec3f yn(*point_image.data(y - 1, x, 0), *point_image.data(y - 1, x, 1), *point_image.data(y - 1, x, 2));\r\n\r\n                if (!xp.allFinite() || !xn.allFinite() || !yp.allFinite() || !yn.allFinite()) {\r\n                    continue;\r\n                }\r\n\r\n                Vec3f a = xp - xn;\r\n                Vec3f b = yp - yn;\r\n\r\n                Vec3f cross = b.cross(a);\r\n\r\n                if (!cross.allFinite()) {\r\n                    continue;\r\n                }\r\n\r\n                float norm = cross.norm();\r\n\r\n                if (norm < epsilon) {\r\n                    continue;\r\n                }\r\n\r\n                cross = cross / norm;\r\n\r\n                *normals.mutable_data(y, x, 0) = cross.x();\r\n                *normals.mutable_data(y, x, 1) = cross.y();\r\n                *normals.mutable_data(y, x, 2) = cross.z();\r\n            }\r\n        }\r\n    }\r\n\r\n    void compute_normals_via_pca(const py::array_t<float>& point_image, py::array_t<float>& normals, const int kernel_size, const float max_distance) {\r\n    \r\n        int height = point_image.shape(0);\r\n        int width  = point_image.shape(1);\r\n\r\n        int ex = kernel_size;\r\n        int ey = kernel_size;\r\n     \r\n        for (int y = 0; y < height; y++) {\r\n            for (int x = 0; x < width; x++) {\r\n                \r\n                Vec3f point(*point_image.data(y, x, 0), *point_image.data(y, x, 1), *point_image.data(y, x, 2));\r\n\r\n                if (!point.allFinite()) {\r\n                    continue;\r\n                }\r\n\r\n                int counter = 0;\r\n                Vec3f center(0, 0, 0);\r\n                std::vector<Vec3f> valid_points;\r\n\r\n                for (int yi = y - ey / 2; yi <= y + ey / 2; ++yi) {\r\n                    for (int xi = x - ex / 2; xi <= x + ex / 2; ++xi) {\r\n                        if (xi >= 0 && xi < width && yi >= 0 && yi < height) {\r\n                            Vec3f point_neighbor(*point_image.data(yi, xi, 0), *point_image.data(yi, xi, 1), *point_image.data(yi, xi, 2));\r\n\r\n                            if (point_neighbor.allFinite() && (point - point_neighbor).norm() <= max_distance) {\r\n                                center += point_neighbor;\r\n                                valid_points.push_back(point_neighbor);\r\n                                ++counter;\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n                center /= (float)counter;\r\n\r\n                Eigen::MatrixXf A(3, counter);\r\n                for (int idx = 0; idx < counter; ++idx) {\r\n                    A.col(idx) = valid_points[idx] - center;\r\n                }\r\n\r\n                Eigen::Matrix3f cov = A * A.transpose();\r\n                Eigen::EigenSolver<Eigen::Matrix3f> eigen_solver(cov, true);\r\n                const Vec3f& eigen_value = eigen_solver.eigenvalues().real();\r\n\r\n                int min_idx = 0;\r\n                eigen_value.minCoeff(&min_idx);\r\n                Vec3f min_eigen_vector = eigen_solver.eigenvectors().real().col(min_idx);\r\n\r\n                Vec3f normal;\r\n                // Use eigen vector facing camera as normal.\r\n                if (min_eigen_vector.dot(point) < 0) {\r\n                    normal = min_eigen_vector.normalized();\r\n                }\r\n                else {\r\n                    normal = -min_eigen_vector.normalized();\r\n                }\r\n            \r\n                *normals.mutable_data(y, x, 0) = normal.x();\r\n                *normals.mutable_data(y, x, 1) = normal.y();\r\n                *normals.mutable_data(y, x, 2) = normal.z();\r\n            }\r\n        }\r\n    }\r\n\r\n    float estimate_rigid_pose(\r\n         const py::array_t<float>& sourcePointsArray, const py::array_t<float>& targetPointsArray, \r\n         int numIterationsRANSAC, int numSamplesRANSAC, int minPointsRANSAC, float inlierDistanceRANSAC, float inlierDistanceFinal,\r\n         py::array_t<float>& estimatedPose\r\n    ) {\r\n        if (numSamplesRANSAC > minPointsRANSAC) {\r\n            std::cout << \"The minimum number of points should be at least as big as the sample size.\" << std::endl;\r\n            exit(1);\r\n        }\r\n\r\n        // Compute valid 3D matches.\r\n        int nMatches = sourcePointsArray.shape(0);\r\n\r\n        std::vector<Vec3f> sourcePoints, targetPoints; \r\n        for (int i = 0; i < nMatches; i++) {\r\n            Vec3f sourcePoint(\r\n                *sourcePointsArray.data(i, 0),\r\n                *sourcePointsArray.data(i, 1),\r\n                *sourcePointsArray.data(i, 2)\r\n            );\r\n            Vec3f targetPoint(\r\n                *targetPointsArray.data(i, 0),\r\n                *targetPointsArray.data(i, 1),\r\n                *targetPointsArray.data(i, 2)\r\n            );\r\n\r\n            sourcePoints.push_back(sourcePoint);\r\n            targetPoints.push_back(targetPoint);\r\n        }\r\n\r\n        int nMatches3D = sourcePoints.size();\r\n        if (nMatches3D < minPointsRANSAC) {\r\n            return 0;\r\n        }\r\n\r\n        // Execute Procrustes with RANSAC.\r\n        Mat4f globalRigidPose = ProcrustesRANSAC::estimatePose(\r\n            sourcePoints, targetPoints, numIterationsRANSAC, numSamplesRANSAC, inlierDistanceRANSAC\r\n        );\r\n\r\n        // Compute the number of inliers.\r\n        int nInliers = 0;\r\n        for (int i = 0; i < nMatches3D; i++) {\r\n            Eigen::Vector3f transformedSourcePoint = globalRigidPose.block(0, 0, 3, 3) * sourcePoints[i] + globalRigidPose.block(0, 3, 3, 1);\r\n            float distance = (transformedSourcePoint - targetPoints[i]).norm();\r\n\r\n            if (distance <= inlierDistanceFinal) {\r\n                nInliers++;\r\n            }\r\n        }\r\n\r\n        float inlierRatio = float(nInliers) / nMatches3D;\r\n\r\n        // Store the estimated pose.\r\n        estimatedPose.resize({ 4, 4 }, false);\r\n        \r\n        for (int i = 0; i < 4; i++) {\r\n            for (int j = 0; j < 4; j++) {\r\n                *estimatedPose.mutable_data(i, j) = globalRigidPose(i, j);\r\n            }\r\n        }\r\n\r\n        return inlierRatio;\r\n    }\r\n\r\n    void compute_mesh_from_depth(\r\n        const py::array_t<float>& pointImage, float maxTriangleEdgeDistance, \r\n        py::array_t<float>& vertexPositions, py::array_t<int>& faceIndices\r\n    ) {\r\n        int width = pointImage.shape(2);\r\n        int height = pointImage.shape(1);\r\n\r\n        // Compute valid pixel vertices and faces.\r\n        // We also need to compute the pixel -> vertex index mapping for \r\n        // computation of faces.\r\n        // We connect neighboring pixels on the square into two triangles.\r\n        // We only select valid triangles, i.e. with all valid vertices and\r\n        // not too far apart.\r\n        // Important: The triangle orientation is set such that the normals\r\n        // point towards the camera.\r\n        std::vector<Eigen::Vector3f> vertices;\r\n        std::vector<Eigen::Vector3i> faces;\r\n\r\n        int vertexIdx = 0;\r\n        std::vector<int> mapPixelToVertexIdx(width * height, -1);\r\n\r\n        for (int y = 0; y < height - 1; y++) {\r\n            for (int x = 0; x < width - 1; x++) {\r\n                Eigen::Vector3f obs00(*pointImage.data(0, y, x), *pointImage.data(1, y, x), *pointImage.data(2, y, x));\r\n                Eigen::Vector3f obs01(*pointImage.data(0, y + 1, x), *pointImage.data(1, y + 1, x), *pointImage.data(2, y + 1, x));\r\n                Eigen::Vector3f obs10(*pointImage.data(0, y, x + 1), *pointImage.data(1, y, x + 1), *pointImage.data(2, y, x + 1));\r\n                Eigen::Vector3f obs11(*pointImage.data(0, y + 1, x + 1), *pointImage.data(1, y + 1, x + 1), *pointImage.data(2, y + 1, x + 1));\r\n\r\n                int idx00 = y * width + x;\r\n                int idx01 = (y + 1) * width + x;\r\n                int idx10 = y * width + (x + 1);\r\n                int idx11 = (y + 1) * width + (x + 1);\r\n\r\n                bool valid00 = obs00.z() > 0;\r\n                bool valid01 = obs01.z() > 0;\r\n                bool valid10 = obs10.z() > 0;\r\n                bool valid11 = obs11.z() > 0;\r\n\r\n                if (valid00 && valid01 && valid10) {\r\n                    float d0 = (obs00 - obs01).norm();\r\n                    float d1 = (obs00 - obs10).norm();\r\n                    float d2 = (obs01 - obs10).norm();\r\n                    \r\n                    if (d0 <= maxTriangleEdgeDistance && d1 <= maxTriangleEdgeDistance && d2 <= maxTriangleEdgeDistance) {\r\n                        int vIdx0 = mapPixelToVertexIdx[idx00];\r\n                        int vIdx1 = mapPixelToVertexIdx[idx01];\r\n                        int vIdx2 = mapPixelToVertexIdx[idx10];\r\n\r\n                        if (vIdx0 == -1) {\r\n                            vIdx0 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx00] = vertexIdx;\r\n                            vertices.push_back(obs00);\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx1 == -1) {\r\n                            vIdx1 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx01] = vertexIdx;\r\n                            vertices.push_back(obs01);\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx2 == -1) {\r\n                            vIdx2 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx10] = vertexIdx;\r\n                            vertices.push_back(obs10);\r\n                            vertexIdx++;\r\n                        }\r\n\r\n                        faces.push_back(Eigen::Vector3i(vIdx0, vIdx1, vIdx2));\r\n                    }\r\n                }\r\n\r\n                if (valid01 && valid10 && valid11) {\r\n                    float d0 = (obs10 - obs01).norm();\r\n                    float d1 = (obs10 - obs11).norm();\r\n                    float d2 = (obs01 - obs11).norm();\r\n\r\n                    if (d0 <= maxTriangleEdgeDistance && d1 <= maxTriangleEdgeDistance && d2 <= maxTriangleEdgeDistance) {\r\n                        int vIdx0 = mapPixelToVertexIdx[idx11];\r\n                        int vIdx1 = mapPixelToVertexIdx[idx10];\r\n                        int vIdx2 = mapPixelToVertexIdx[idx01];\r\n\r\n                        if (vIdx0 == -1) {\r\n                            vIdx0 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx11] = vertexIdx;\r\n                            vertices.push_back(obs11);\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx1 == -1) {\r\n                            vIdx1 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx10] = vertexIdx;\r\n                            vertices.push_back(obs10);\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx2 == -1) {\r\n                            vIdx2 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx01] = vertexIdx;\r\n                            vertices.push_back(obs01);\r\n                            vertexIdx++;\r\n                        }\r\n\r\n                        faces.push_back(Eigen::Vector3i(vIdx0, vIdx1, vIdx2));\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        // Convert to numpy array.\r\n        int nVertices = vertices.size();\r\n        int nFaces = faces.size();\r\n\r\n        if (nVertices > 0 && nFaces > 0) {\r\n            // Reference check should be set to false otherwise there is a runtime\r\n            // error. Check why that is the case.\r\n            vertexPositions.resize({ nVertices, 3 }, false);\r\n            faceIndices.resize({ nFaces, 3 }, false);\r\n\r\n            for (int i = 0; i < nVertices; i++) {\r\n                *vertexPositions.mutable_data(i, 0) = vertices[i].x();\r\n                *vertexPositions.mutable_data(i, 1) = vertices[i].y();\r\n                *vertexPositions.mutable_data(i, 2) = vertices[i].z();\r\n            }\r\n            \r\n            for (int i = 0; i < nFaces; i++) {\r\n                *faceIndices.mutable_data(i, 0) = faces[i].x();\r\n                *faceIndices.mutable_data(i, 1) = faces[i].y();\r\n                *faceIndices.mutable_data(i, 2) = faces[i].z();\r\n            }\r\n        }\r\n    }\r\n\r\n    void compute_validity_and_sign_mask(\r\n        const py::array_t<float>& grid_points_cam, \r\n        const py::array_t<bool>& valid_depth_mask_image, \r\n        const py::array_t<float>& depth_image,\r\n        float fx, float fy, float cx, float cy, int w, int h,\r\n        float truncation,\r\n        py::array_t<bool>& validity_grid_mask,\r\n        py::array_t<float>& sign_grid_mask\r\n    ) {\r\n        \r\n        int num_grid_points = grid_points_cam.shape(0);\r\n\r\n        for (int pt_id = 0; pt_id < num_grid_points; pt_id++) {\r\n\r\n            float x = *grid_points_cam.data(pt_id, 0);\r\n            float y = *grid_points_cam.data(pt_id, 1);\r\n            float z = *grid_points_cam.data(pt_id, 2);\r\n\r\n            int px = int(round(fx * x / z + cx));\r\n            int py = int(round(fy * y / z + cy));\r\n\r\n            if (px < 0 || px >= w || py < 0 || py >= h) {\r\n                continue;\r\n            }\r\n\r\n            bool is_valid_pixel = *valid_depth_mask_image.data(py, px);\r\n\r\n            if (!is_valid_pixel) {\r\n                continue;\r\n            }\r\n            \r\n            float d = *depth_image.data(py, px);\r\n\r\n            // If the z coordinate of the grid point is further away from the camera \r\n            // than the surface + some truncation, then we invalidate the grid point\r\n            if (z > (d + truncation)) {\r\n                *validity_grid_mask.mutable_data(pt_id) = false;\r\n            }\r\n\r\n            if (z > d) {\r\n                *sign_grid_mask.mutable_data(pt_id) = -1.0;\r\n            }\r\n            \r\n        }\r\n    }\r\n\r\n} //namespace image_proc", "meta": {"hexsha": "2bfb4f0c72ca8c1740707260cd8b5d15e10924fb", "size": 17143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/csrc/cpu/image_proc.cpp", "max_stars_repo_name": "Tiamat-Tech/npms", "max_stars_repo_head_hexsha": "2d1bce8c98b0f24aa69273975c52b2fbdb101c29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2021-08-01T18:19:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T02:53:47.000Z", "max_issues_repo_path": "external/csrc/cpu/image_proc.cpp", "max_issues_repo_name": "Tiamat-Tech/npms", "max_issues_repo_head_hexsha": "2d1bce8c98b0f24aa69273975c52b2fbdb101c29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-08-18T12:57:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-30T07:18:46.000Z", "max_forks_repo_path": "external/csrc/cpu/image_proc.cpp", "max_forks_repo_name": "Tiamat-Tech/npms", "max_forks_repo_head_hexsha": "2d1bce8c98b0f24aa69273975c52b2fbdb101c29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-08-03T01:51:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T09:46:25.000Z", "avg_line_length": 39.0501138952, "max_line_length": 152, "alphanum_fraction": 0.4650294581, "num_tokens": 4154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5121147232576106}}
{"text": "/*\n\nCopyright (c) 2015, Project OSRM contributors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY 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\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#include \"coordinate_calculation.hpp\"\n\n#include \"../util/mercator.hpp\"\n#include \"../util/string_util.hpp\"\n\n#include <boost/assert.hpp>\n\n#include <osrm/coordinate.hpp>\n\n#include <cmath>\n\n#include <limits>\n\nnamespace\n{\nconstexpr static const float RAD = 0.017453292519943295769236907684886f;\n// earth radius varies between 6,356.750-6,378.135 km (3,949.901-3,963.189mi)\n// The IUGG value for the equatorial radius is 6378.137 km (3963.19 miles)\nconstexpr static const float earth_radius = 6372797.560856f;\n}\n\nnamespace coordinate_calculation\n{\n\ndouble great_circle_distance(const int lat1,\n                                                     const int lon1,\n                                                     const int lat2,\n                                                     const int lon2)\n{\n    BOOST_ASSERT(lat1 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lon1 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lat2 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lon2 != std::numeric_limits<int>::min());\n    const double lt1 = lat1 / COORDINATE_PRECISION;\n    const double ln1 = lon1 / COORDINATE_PRECISION;\n    const double lt2 = lat2 / COORDINATE_PRECISION;\n    const double ln2 = lon2 / COORDINATE_PRECISION;\n    const double dlat1 = lt1 * (RAD);\n\n    const double dlong1 = ln1 * (RAD);\n    const double dlat2 = lt2 * (RAD);\n    const double dlong2 = ln2 * (RAD);\n\n    const double dLong = dlong1 - dlong2;\n    const double dLat = dlat1 - dlat2;\n\n    const double aHarv = std::pow(std::sin(dLat / 2.0), 2.0) +\n                         std::cos(dlat1) * std::cos(dlat2) * std::pow(std::sin(dLong / 2.), 2);\n    const double cHarv = 2. * std::atan2(std::sqrt(aHarv), std::sqrt(1.0 - aHarv));\n    return earth_radius * cHarv;\n}\n\ndouble great_circle_distance(const FixedPointCoordinate &coordinate_1,\n                                                     const FixedPointCoordinate &coordinate_2)\n{\n    return great_circle_distance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat,\n                                 coordinate_2.lon);\n}\n\nfloat euclidean_distance(const FixedPointCoordinate &coordinate_1,\n                                                 const FixedPointCoordinate &coordinate_2)\n{\n    return euclidean_distance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat,\n                              coordinate_2.lon);\n}\n\nfloat euclidean_distance(const int lat1,\n                                                 const int lon1,\n                                                 const int lat2,\n                                                 const int lon2)\n{\n    BOOST_ASSERT(lat1 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lon1 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lat2 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lon2 != std::numeric_limits<int>::min());\n\n    const float float_lat1 = (lat1 / COORDINATE_PRECISION) * RAD;\n    const float float_lon1 = (lon1 / COORDINATE_PRECISION) * RAD;\n    const float float_lat2 = (lat2 / COORDINATE_PRECISION) * RAD;\n    const float float_lon2 = (lon2 / COORDINATE_PRECISION) * RAD;\n\n    const float x_value = (float_lon2 - float_lon1) * std::cos((float_lat1 + float_lat2) / 2.f);\n    const float y_value = float_lat2 - float_lat1;\n    return std::hypot(x_value, y_value) * earth_radius;\n}\n\nfloat perpendicular_distance(const FixedPointCoordinate &source_coordinate,\n                                                     const FixedPointCoordinate &target_coordinate,\n                                                     const FixedPointCoordinate &query_location)\n{\n    float ratio;\n    FixedPointCoordinate nearest_location;\n\n    return perpendicular_distance(source_coordinate, target_coordinate, query_location,\n                                  nearest_location, ratio);\n}\n\nfloat perpendicular_distance(const FixedPointCoordinate &segment_source,\n                                                     const FixedPointCoordinate &segment_target,\n                                                     const FixedPointCoordinate &query_location,\n                                                     FixedPointCoordinate &nearest_location,\n                                                     float &ratio)\n{\n    return perpendicular_distance_from_projected_coordinate(\n        segment_source, segment_target, query_location,\n        {mercator::lat2y(query_location.lat / COORDINATE_PRECISION),\n         query_location.lon / COORDINATE_PRECISION},\n        nearest_location, ratio);\n}\n\nfloat perpendicular_distance_from_projected_coordinate(\n    const FixedPointCoordinate &source_coordinate,\n    const FixedPointCoordinate &target_coordinate,\n    const FixedPointCoordinate &query_location,\n    const std::pair<double, double> &projected_coordinate)\n{\n    float ratio;\n    FixedPointCoordinate nearest_location;\n\n    return perpendicular_distance_from_projected_coordinate(source_coordinate, target_coordinate,\n                                                            query_location, projected_coordinate,\n                                                            nearest_location, ratio);\n}\n\nfloat perpendicular_distance_from_projected_coordinate(\n    const FixedPointCoordinate &segment_source,\n    const FixedPointCoordinate &segment_target,\n    const FixedPointCoordinate &query_location,\n    const std::pair<double, double> &projected_coordinate,\n    FixedPointCoordinate &nearest_location,\n    float &ratio)\n{\n    BOOST_ASSERT(query_location.is_valid());\n\n    // initialize values\n    const double x = projected_coordinate.first;\n    const double y = projected_coordinate.second;\n    const double a = mercator::lat2y(segment_source.lat / COORDINATE_PRECISION);\n    const double b = segment_source.lon / COORDINATE_PRECISION;\n    const double c = mercator::lat2y(segment_target.lat / COORDINATE_PRECISION);\n    const double d = segment_target.lon / COORDINATE_PRECISION;\n    double p, q /*,mX*/, nY;\n    if (std::abs(a - c) > std::numeric_limits<double>::epsilon())\n    {\n        const double m = (d - b) / (c - a); // slope\n        // Projection of (x,y) on line joining (a,b) and (c,d)\n        p = ((x + (m * y)) + (m * m * a - m * b)) / (1.f + m * m);\n        q = b + m * (p - a);\n    }\n    else\n    {\n        p = c;\n        q = y;\n    }\n    nY = (d * p - c * q) / (a * d - b * c);\n\n    // discretize the result to coordinate precision. it's a hack!\n    if (std::abs(nY) < (1.f / COORDINATE_PRECISION))\n    {\n        nY = 0.f;\n    }\n\n    // compute ratio\n    ratio =\n        static_cast<float>((p - nY * a) / c); // These values are actually n/m+n and m/m+n , we need\n    // not calculate the explicit values of m an n as we\n    // are just interested in the ratio\n    if (std::isnan(ratio))\n    {\n        ratio = (segment_target == query_location ? 1.f : 0.f);\n    }\n    else if (std::abs(ratio) <= std::numeric_limits<float>::epsilon())\n    {\n        ratio = 0.f;\n    }\n    else if (std::abs(ratio - 1.f) <= std::numeric_limits<float>::epsilon())\n    {\n        ratio = 1.f;\n    }\n\n    // compute nearest location\n    BOOST_ASSERT(!std::isnan(ratio));\n    if (ratio <= 0.f)\n    {\n        nearest_location = segment_source;\n    }\n    else if (ratio >= 1.f)\n    {\n        nearest_location = segment_target;\n    }\n    else\n    {\n        // point lies in between\n        nearest_location.lat = static_cast<int>(mercator::y2lat(p) * COORDINATE_PRECISION);\n        nearest_location.lon = static_cast<int>(q * COORDINATE_PRECISION);\n    }\n    BOOST_ASSERT(nearest_location.is_valid());\n\n    const float approximate_distance =\n        euclidean_distance(query_location, nearest_location);\n    BOOST_ASSERT(0.f <= approximate_distance);\n    return approximate_distance;\n}\n\nvoid lat_or_lon_to_string(const int value, std::string &output)\n{\n    char buffer[12];\n    buffer[11] = 0; // zero termination\n    output = printInt<11, 6>(buffer, value);\n}\n\nfloat deg_to_rad(const float degree)\n{\n    return degree * (static_cast<float>(M_PI) / 180.f);\n}\n\nfloat rad_to_deg(const float radian)\n{\n    return radian * (180.f * static_cast<float>(M_1_PI));\n}\n\nfloat bearing(const FixedPointCoordinate &first_coordinate,\n                                      const FixedPointCoordinate &second_coordinate)\n{\n    const float lon_diff =\n        second_coordinate.lon / COORDINATE_PRECISION - first_coordinate.lon / COORDINATE_PRECISION;\n    const float lon_delta = deg_to_rad(lon_diff);\n    const float lat1 = deg_to_rad(first_coordinate.lat / COORDINATE_PRECISION);\n    const float lat2 = deg_to_rad(second_coordinate.lat / COORDINATE_PRECISION);\n    const float y = std::sin(lon_delta) * std::cos(lat2);\n    const float x =\n        std::cos(lat1) * std::sin(lat2) - std::sin(lat1) * std::cos(lat2) * std::cos(lon_delta);\n    float result = rad_to_deg(std::atan2(y, x));\n    while (result < 0.f)\n    {\n        result += 360.f;\n    }\n\n    while (result >= 360.f)\n    {\n        result -= 360.f;\n    }\n    return result;\n}\n\n}\n", "meta": {"hexsha": "1400b29c6c2616727ddfd756b738d31e53300a03", "size": 10236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "algorithms/coordinate_calculation.cpp", "max_stars_repo_name": "Mapotempo/osrm-backend", "max_stars_repo_head_hexsha": "a62c10321c0a269e218ab4164c4ccd132048f271", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-29T15:02:40.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-29T15:02:40.000Z", "max_issues_repo_path": "algorithms/coordinate_calculation.cpp", "max_issues_repo_name": "Mapotempo/osrm-backend", "max_issues_repo_head_hexsha": "a62c10321c0a269e218ab4164c4ccd132048f271", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-04T18:10:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-04T18:10:57.000Z", "max_forks_repo_path": "algorithms/coordinate_calculation.cpp", "max_forks_repo_name": "Mapotempo/osrm-backend", "max_forks_repo_head_hexsha": "a62c10321c0a269e218ab4164c4ccd132048f271", "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": 37.3576642336, "max_line_length": 100, "alphanum_fraction": 0.6408753419, "num_tokens": 2337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.512114718616915}}
{"text": "#include <ros/ros.h>\n#include <nav_msgs/Odometry.h>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <quadrotor_msgs/QuadData.h>\n#include <quadrotor_msgs/TrajectoryData.h>\n#include <math.h>\n#include <std_msgs/Int8.h>\n\n#define USE_JOYSTICK 0\n\nstruct TrajectoryInfo\n{\n    double xcoef[8];\n    double ycoef[8];\n    double zcoef[8];\n    double duration;\n};\n\nTrajectoryInfo cur_traj, next_traj;\nbool receive_traj = false, buffer = false, init_b = false;\nint count = 0;\nint mode = 0;\ndouble des_height = 1, addtf = 0;\ndouble des_pos[2] = {0, 0};\ndouble t_takeoff = 3;\ndouble t_goto = 2, t_wait = 20;\nEigen::MatrixXd A_takeoff(6,6);\nEigen::MatrixXd A_goto(6,6);\nbool initial_vicon=false, re_init = false, done_init = false, start = false;\ndouble x_init=0,y_init=0,z_init=0;\ndouble tscale = 1;\n\nvoid startprogram (const std_msgs::Int8::ConstPtr & msg)\n{\n  if(msg->data == 0){\n    start = true;\n    ROS_INFO(\"GET MESSAGE START\");\n  }\n}\n\nvoid initialize_var()\n{\nA_takeoff << 1.0,0.0,0.0,0.0,0.0,0.0,\n0.0,1.0,0.0,0.0,0.0,0.0,\n0.0,0.0,2.0,0.0,0.0,0.0,\n1,t_takeoff,pow(t_takeoff,2),pow(t_takeoff,3),pow(t_takeoff,4),pow(t_takeoff,5),\n0,1,2*t_takeoff,3*pow(t_takeoff,2),4*pow(t_takeoff,3),5*pow(t_takeoff,4),\n0.0,0.0,2.0,6.0*t_takeoff,12.0*pow(t_takeoff,2),20.0*pow(t_takeoff,3);\nA_goto << 1.0,0.0,0.0,0.0,0.0,0.0,\n0.0,1.0,0.0,0.0,0.0,0.0,\n0.0,0.0,2.0,0.0,0.0,0.0,\n1,t_goto,pow(t_goto,2),pow(t_goto,3),pow(t_goto,4),pow(t_goto,5),\n0,1,2*t_goto,3*pow(t_goto,2),4*pow(t_goto,3),5*pow(t_goto,4),\n0.0,0.0,2.0,6.0*t_goto,12.0*pow(t_goto,2),20.0*pow(t_goto,3);\n}\n\nvoid cal_takeoff()\n{\n    Eigen::VectorXd b(6), sol(6);\n    b<< z_init,0.0,0.0,des_height+addtf,0.0,0.0;\n    sol = A_takeoff.colPivHouseholderQr().solve(b);\n    cur_traj.duration = t_takeoff;\n    cur_traj.zcoef[0] = 0;\n    cur_traj.zcoef[1] = 0;\n    for(int i = 0; i < 6; i++){\n        cur_traj.zcoef[7-i] = sol(i);\n    }\n    done_init = true;\n    ROS_INFO(\"solve takeoff with duration = %f and coef (%f,%f,%f,%f,%f,%f)\", cur_traj.duration,sol(0),sol(1),sol(2),sol(3),sol(4),sol(5));\n}\n\nvoid cal_goto()\n{\n    Eigen::VectorXd bx(6),by(6), bz(6), solx(6), soly(6), solz(6);\n    bx<< x_init,0.0,0.0,des_pos[0],0.0,0.0;\n    solx = A_goto.colPivHouseholderQr().solve(bx);\n    by<< y_init,0.0,0.0,des_pos[1],0.0,0.0;\n    soly = A_goto.colPivHouseholderQr().solve(by);\n    bz<< z_init,0.0,0.0,des_height,0.0,0.0;\n    solz = A_goto.colPivHouseholderQr().solve(bz);\n    cur_traj.duration = t_goto;\n    cur_traj.xcoef[0] = 0;\n    cur_traj.xcoef[1] = 0;\n    cur_traj.ycoef[0] = 0;\n    cur_traj.ycoef[1] = 0;\n    cur_traj.zcoef[0] = 0;\n    cur_traj.zcoef[1] = 0;\n    for(int i = 0; i < 6; i++){\n      cur_traj.xcoef[7-i] = solx(i);\n      cur_traj.ycoef[7-i] = soly(i);\n      cur_traj.zcoef[7-i] = solz(i);\n    }\n    done_init = true;\n    ROS_INFO(\"solve goto\");\n}\n\nvoid viconCallback(const nav_msgs::Odometry::ConstPtr& vicon)\n{\nif(!initial_vicon)\n{\n  x_init = vicon->pose.pose.position.x;\n  y_init = vicon->pose.pose.position.y;\n  z_init = vicon->pose.pose.position.z;\n  initial_vicon = true;\n  cal_takeoff();\n}\nelse{\n  if(re_init){\n  x_init = vicon->pose.pose.position.x;\n  y_init = vicon->pose.pose.position.y;\n  z_init = vicon->pose.pose.position.z;\n  re_init = false;\n  cal_goto();\n  }\n}\n}\n\nvoid updateTrajCallback(const quadrotor_msgs::TrajectoryData::ConstPtr & msg){\n    next_traj.xcoef[0] = msg->xcoef[0];\n    next_traj.ycoef[0] = msg->ycoef[0];\n    next_traj.zcoef[0] = msg->zcoef[0];\n    next_traj.xcoef[1] = msg->xcoef[1];\n    next_traj.ycoef[1] = msg->ycoef[1];\n    next_traj.zcoef[1] = msg->zcoef[1];\n    next_traj.xcoef[2] = msg->xcoef[2];\n    next_traj.ycoef[2] = msg->ycoef[2];\n    next_traj.zcoef[2] = msg->zcoef[2];\n    next_traj.xcoef[3] = msg->xcoef[3];\n    next_traj.ycoef[3] = msg->ycoef[3];\n    next_traj.zcoef[3] = msg->zcoef[3];\n    next_traj.xcoef[4] = msg->xcoef[4];\n    next_traj.ycoef[4] = msg->ycoef[4];\n    next_traj.zcoef[4] = msg->zcoef[4];\n    next_traj.xcoef[5] = msg->xcoef[5];\n    next_traj.ycoef[5] = msg->ycoef[5];\n    next_traj.zcoef[5] = msg->zcoef[5];\n    next_traj.xcoef[6] = msg->xcoef[6];\n    next_traj.ycoef[6] = msg->ycoef[6];\n    next_traj.zcoef[6] = msg->zcoef[6];\n    next_traj.xcoef[7] = msg->xcoef[7];\n    next_traj.ycoef[7] = msg->ycoef[7];\n    next_traj.zcoef[7] = msg->zcoef[7];\n    next_traj.duration = msg->duration;\n    buffer = true;\n    ROS_INFO(\"seg receive: (%f %f %f)\", next_traj.xcoef[7],next_traj.ycoef[7],next_traj.zcoef[7]);\n}\n\n\ndouble cal_pos(double c[],double t)\n{\n    return c[0]*pow(t,7.0) +c[1]*pow(t,6.0) + c[2]*pow(t,5.0) + c[3]*pow(t,4.0) + c[4]*pow(t,3.0) + c[5]*pow(t,2.0) + c[6]*t + c[7];\n}\n\ndouble cal_vel(double c[],double t)\n{\n    return (c[0]*7*pow(t,6.0) +c[1]*6*pow(t,5.0) + c[2]*5*pow(t,4.0) + c[3]*4*pow(t,3.0) + c[4]*3*pow(t,2.0) + c[5]*2*t + c[6])/tscale;\n}\n\ndouble cal_acc(double c[],double t)\n{\n    return (c[0]*42*pow(t,5.0) +c[1]*30*pow(t,4.0) + c[2]*20*pow(t,3.0) + c[3]*12*pow(t,2.0) + c[4]*6*t + c[5]*2)/(tscale*tscale);\n}\n\n\nint main(int argc, char **argv)\n{\n    ros::init(argc,argv,\"quad_trajectory\");\n    ros::NodeHandle nh(\"~\");\n    ros::Publisher pub = nh.advertise<quadrotor_msgs::QuadData>(\"trajectory\", 10, true);\n    ros::Subscriber trajectory_sub = nh.subscribe(\"trajectoryinfo\",10,updateTrajCallback, ros::TransportHints().tcpNoDelay());\n    ros::Subscriber vicon_sub = nh.subscribe(\"odom\",10,viconCallback, ros::TransportHints().tcpNoDelay());\n    if(USE_JOYSTICK)\n        ros::Subscriber switch_sub = nh.subscribe(\"startsignal\",10,startprogram, ros::TransportHints().tcpNoDelay());\n    ros::Rate loop_rate(100);\n    quadrotor_msgs::QuadData traj;\n    nh.param(\"des_pos/x\", des_pos[0], 0.0);\n    nh.param(\"des_pos/y\", des_pos[1], 0.0);\n    nh.param(\"des_pos/z\", des_height, 0.8);\n    nh.param(\"add_tf\", addtf, 0.0);\n    nh.param(\"time/scale\", tscale, 1.0);\n    nh.param(\"time/takeoff\", t_takeoff, 4.0);\n    nh.param(\"time/goto\", t_goto, 4.0);\n    nh.param(\"time/land\", t_wait, 20.0);\n    initialize_var();\n    double t_start = -1;\n    double t_end = 0;\n    double cur_t;\n    double cur_off[3] = {0,0,des_height};\n    double t_command = 0, t_hover = 0;\n    bool follow_path = false;\n    if(USE_JOYSTICK){\n     while(!start)\n        ros::spinOnce();\n    }\n    else{\n        sleep(3);\n        ros::spinOnce();\n    }\n    // }\n\n    t_command = ros::Time::now().toSec();\n    \n    while(nh.ok())\n    {\n        traj.write = 0;\n       if(mode == 0 && done_init){\n            cur_t = ros::Time::now().toSec();\n            t_command = cur_t;\n            t_start = cur_t;\n            t_end = cur_t + cur_traj.duration*tscale;\n            traj.mode = 0;\n            while(cur_t <= t_end){\n               double t = (cur_t - t_start)/tscale;\n               traj.z = cal_pos(cur_traj.zcoef,t)-0.1;\n               traj.vz = cal_vel(cur_traj.zcoef,t);\n               traj.acc_z = cal_acc(cur_traj.zcoef,t);\n               cur_t = ros::Time::now().toSec();\n               pub.publish(traj);\n               ros::spinOnce();\n               loop_rate.sleep();\n            }\n            mode = 1;\n            re_init = true;\n            done_init = false;\n            t_command = cur_t;\n            follow_path = false;\n        }\n\n        if(mode == 1 && done_init){\n            cur_t = ros::Time::now().toSec();\n            t_command = cur_t;\n            t_start = cur_t;\n            t_end = cur_t + cur_traj.duration*tscale;\n            traj.mode = 2;\n            while(cur_t <= t_end){\n                double t = (cur_t - t_start)/tscale;\n                traj.x = cal_pos(cur_traj.xcoef,t);\n                traj.vx = cal_vel(cur_traj.xcoef,t);\n                traj.acc_x = cal_acc(cur_traj.xcoef,t);\n                traj.y = cal_pos(cur_traj.ycoef,t);\n                traj.vy = cal_vel(cur_traj.ycoef,t);\n                traj.acc_y = cal_acc(cur_traj.ycoef,t);\n                traj.z = cal_pos(cur_traj.zcoef,t);\n                traj.vz = cal_vel(cur_traj.zcoef,t);\n                traj.acc_z = cal_acc(cur_traj.zcoef,t);\n                pub.publish(traj);\n                ros::spinOnce();\n                loop_rate.sleep();\n                cur_t = ros::Time::now().toSec();\n            }\n            mode = 2;\n            t_command = cur_t;\n            follow_path = false;\n        }\n\n        if(mode == 2 && buffer){\n            count++;\n            cur_traj.duration = next_traj.duration;\n            for(int ii = 0; ii < 8; ii++){\n                cur_traj.xcoef[ii] = next_traj.xcoef[ii];\n                cur_traj.ycoef[ii] = next_traj.ycoef[ii];\n                cur_traj.zcoef[ii] = next_traj.zcoef[ii];\n            }\n            cur_t = ros::Time::now().toSec();\n            t_start = cur_t;\n            t_end = cur_t + cur_traj.duration*tscale;\n            ROS_INFO(\"Traj: %d from %f %f %f\",count,cur_traj.xcoef[7],cur_traj.ycoef[7],cur_traj.zcoef[7]);\n            buffer = false;\n            while(cur_t < t_end) \n            {\n                traj.mode = 2;\n                traj.write = 1;\n                double t = (cur_t - t_start)/tscale;\n                traj.x = cal_pos(cur_traj.xcoef,t);\n                traj.y = cal_pos(cur_traj.ycoef,t);\n                traj.z = cal_pos(cur_traj.zcoef,t);\n                traj.vx = cal_vel(cur_traj.xcoef,t);\n                traj.vy = cal_vel(cur_traj.ycoef,t);\n                traj.vz = cal_vel(cur_traj.zcoef,t);\n                traj.acc_x = cal_acc(cur_traj.xcoef,t);\n                traj.acc_y = cal_acc(cur_traj.ycoef,t);\n                traj.acc_z = cal_acc(cur_traj.zcoef,t);\n                traj.yaw = 0;\n                pub.publish(traj);\n                // ros::spinOnce();\n                loop_rate.sleep();\n                cur_t = ros::Time::now().toSec();\n            }\n            t_command = cur_t;\n            printf(\"end\\n\");           \n        } else {\n            t_hover = ros::Time::now().toSec() - t_command;\n            if(t_hover > t_wait) {\n                traj.mode = 3;\n            } else {\n                traj.mode = 1;\n            }\n        }\n        pub.publish(traj);\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n    return 0;\n}\n", "meta": {"hexsha": "546ae6b496d8cc2bcc0772dbc4f33a89c567afaa", "size": 10054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Src/ros_simulator/src/quad_controller/src/quad_trajectory.cpp", "max_stars_repo_name": "Drona-Org/Drona-DMR", "max_stars_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T14:49:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T06:53:28.000Z", "max_issues_repo_path": "Src/ros_simulator/src/quad_controller/src/quad_trajectory.cpp", "max_issues_repo_name": "Dronacharya-Org/Dronacharya", "max_issues_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/ros_simulator/src/quad_controller/src/quad_trajectory.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": 32.8562091503, "max_line_length": 139, "alphanum_fraction": 0.5585836483, "num_tokens": 3314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5121057559662183}}
{"text": "/* vim: set sw=4 sts=4 et foldmethod=syntax : */\n\n#include <gcs/constraints/comparison.hh>\n#include <gcs/constraints/arithmetic.hh>\n#include <gcs/problem.hh>\n#include <gcs/solve.hh>\n#include <util/for_each.hh>\n\n#include <cstdlib>\n#include <iostream>\n#include <optional>\n#include <vector>\n\n#include <boost/program_options.hpp>\n\nusing namespace gcs;\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::nullopt;\nusing std::optional;\nusing std::pair;\nusing std::string;\nusing std::to_string;\nusing std::vector;\n\nnamespace po = boost::program_options;\n\nauto main(int argc, char * argv[]) -> int\n{\n    po::options_description display_options{ \"Program options\" };\n    display_options.add_options()\n        (\"help\", \"Display help information\")\n        (\"prove\", \"Create a proof\");\n\n    po::options_description all_options{ \"All options\" };\n    all_options.add_options()\n        (\"size\", po::value<int>()->default_value(88), \"Size of the problem to solve\")\n        (\"all\", \"Find all solutions\")\n        ;\n\n    all_options.add(display_options);\n\n    po::positional_options_description positional_options;\n    positional_options\n        .add(\"size\", -1);\n\n    po::variables_map options_vars;\n\n    try {\n        po::store(po::command_line_parser(argc, argv)\n                .options(all_options)\n                .positional(positional_options)\n                .run(), options_vars);\n        po::notify(options_vars);\n    }\n    catch (const po::error & e) {\n        cerr << \"Error: \" << e.what() << endl;\n        cerr << \"Try \" << argv[0] << \" --help\" << endl;\n        return EXIT_FAILURE;\n    }\n\n    if (options_vars.count(\"help\")) {\n        cout << \"Usage: \" << argv[0] << \" [options] [size]\" << endl;\n        cout << endl;\n        cout << display_options << endl;\n        return EXIT_SUCCESS;\n    }\n\n    cout << \"Replicating the n-Queens benchmark.\" << endl;\n    cout << \"See Laurent D. Michel, Pierre Schaus, Pascal Van Hentenryck:\" << endl;\n    cout << \"\\\"MiniCP: a lightweight solver for constraint programming.\\\"\" << endl;\n    cout << \"Math. Program. Comput. 13(1): 133-184 (2021).\" << endl;\n    cout << \"This should take 49339390 recursions with default options.\" << endl;\n    cout << endl;\n\n    int size = options_vars[\"size\"].as<int>();\n    Problem p = options_vars.count(\"prove\") ? Problem{ Proof{ \"n_queens.opb\", \"n_queens.veripb\" } } : Problem{ };\n\n    vector<SimpleIntegerVariableID> queens;\n    for (int v = 0 ; v != size ; ++v)\n        queens.push_back(p.create_integer_variable(0_i, Integer{ size - 1 }, \"queen\" + to_string(v)));\n\n    for (int i = 0 ; i < size ; ++i) {\n        for (int j = i + 1 ; j < size ; ++j) {\n            p.post(NotEquals{ queens[i], queens[j] });\n            p.post(NotEquals{ queens[i] + Integer{ j - i }, queens[j] });\n            p.post(NotEquals{ queens[i] + -Integer{ j - i }, queens[j] });\n        }\n    }\n\n    auto stats = solve_with(p, SolveCallbacks{\n            .solution = [&] (const State & s) -> bool {\n                cout << \"solution:\";\n                for (auto & v : queens)\n                    cout << \" \" << s(v);\n                cout << endl;\n\n                return options_vars.count(\"all\");\n                },\n            .guess = [&] (const State & state, IntegerVariableID var) -> vector<Literal> {\n                return vector<Literal>{ var == state.lower_bound(var), var != state.lower_bound(var) };\n            }\n            });\n\n    cout << stats;\n\n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "41b348d28f26c054e3bb9fe9df4ddd705cbf788d", "size": 3449, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/n_queens/n_queens.cc", "max_stars_repo_name": "ciaranm/glasgow-constraint-solver", "max_stars_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-08-13T11:36:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T11:13:04.000Z", "max_issues_repo_path": "examples/n_queens/n_queens.cc", "max_issues_repo_name": "ciaranm/glasgow-constraint-solver", "max_issues_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_issues_repo_licenses": ["MIT"], "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/n_queens/n_queens.cc", "max_forks_repo_name": "ciaranm/glasgow-constraint-solver", "max_forks_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_forks_repo_licenses": ["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.7946428571, "max_line_length": 113, "alphanum_fraction": 0.5772687736, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5121057510097496}}
{"text": "/*!\n * *****************************************************************************\n *   \\file depthMapCreationHSBS_main.cpp\n *   \\author moennen\n *   \\brief\n *   \\date 2018-02-19\n *   *****************************************************************************/\n\n#include \"utils/imgFileLst.h\"\n#include \"utils/cv_utils.h\"\n\n#include <Eigen/Dense>\n\n#include <glm/glm.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n\n#include <boost/filesystem.hpp>\n\n#include <iostream>\n\nusing namespace std;\nusing namespace cv;\nusing namespace glm;\nusing namespace boost;\nusing namespace Eigen;\n\nnamespace\n{\n//------------------------------------------------------------------------------\n//\nvoid processImg( Mat& img )\n{\n   img = img( Rect( 150, img.rows / 3 + 20, img.cols - 300, 2 * img.rows / 3 - 20 ) ).clone();\n}\n\n//------------------------------------------------------------------------------\n//\nMat processDepthMask( Mat& depth )\n{\n   depth =\n       depth( Rect( 150, depth.rows / 3 + 20, depth.cols - 300, 2 * depth.rows / 3 - 20 ) ).clone();\n\n   Mat mask = Mat( depth.rows, depth.cols, CV_8UC1 );\n\n#pragma omp parallel for\n   for ( unsigned y = 0; y < depth.rows; y++ )\n   {\n      const unsigned short* depthPtr = depth.ptr<unsigned short>( y );\n      unsigned char* maskPtr = mask.ptr<unsigned char>( y );\n      for ( unsigned x = 0; x < depth.cols; x++ )\n      {\n         const unsigned short& d = depthPtr[x];\n         maskPtr[x] = d <= 0 ? 0 : 255;\n      }\n   }\n\n   return mask;\n}\n\n//------------------------------------------------------------------------------\n//\nvoid processDepth(\n    Mat& depth,\n    const Mat& img,\n    const float undef,\n    const float sp_z,\n    const float col_z,\n    const float filter )\n{\n   depth =\n       depth( Rect( 150, depth.rows / 3 + 20, depth.cols - 300, 2 * depth.rows / 3 - 20 ) ).clone();\n\n   vector<Mat> dPyr;\n   dPyr.emplace_back( depth.rows, depth.cols, CV_32FC4 );\n\n   // fill the first level\n#pragma omp parallel for\n   for ( unsigned y = 0; y < depth.rows; y++ )\n   {\n      const float* depthPtr = depth.ptr<float>( y );\n      vec4* dPtr = dPyr.back().ptr<vec4>( y );\n      for ( unsigned x = 0; x < depth.cols; x++ )\n      {\n         const float d = depthPtr[x];\n         dPtr[x] = d == undef ? vec4( 0.0 )\n                              : vec4( d, 1.0f, static_cast<float>( x ), static_cast<float>( y ) );\n      }\n   }\n\n   vector<Mat> iPyr;\n   iPyr.push_back( img.clone() );\n\n   unsigned currPyrSz = std::min( depth.rows, depth.cols );\n\n   // downscale : integrate the depth value using position\n   while ( currPyrSz >= 2 )\n   {\n      Mat iCurr;\n      resize( iPyr.back(), iCurr, Size( 0, 0 ), 0.5, 0.5, INTER_AREA );\n      Mat dCurr( iCurr.rows, iCurr.cols, CV_32FC4 );\n\n#pragma omp parallel for\n      for ( unsigned y = 0; y < dCurr.rows; y++ )\n      {\n         vec4* depthPtr = dCurr.ptr<vec4>( y );\n\n         for ( unsigned x = 0; x < dCurr.cols; x++ )\n         {\n            vec4 val( 0.0 );\n            float w = 0.0;\n\n            const vec2 pos( x * 2.f, y * 2.f );\n\n            for ( int dy = -1; dy <= 1; dy++ )\n            {\n               for ( int dx = -1; dx <= 1; dx++ )\n               {\n                  const vec2 dpos( x * 2.f + dx, y * 2.f + dy );\n                  const vec4 dH = cv_utils::imsample32F<vec4>( dPyr.back(), dpos );\n                  if ( dH.y > 0.0 )\n                  {\n                     const float dist = distance( pos, dpos );\n                     const float z = exp( -dist * dist / sp_z );\n                     w += z;\n                     val += z * dH;\n                  }\n               }\n            }\n\n            depthPtr[x] = val / ( w > 0.0 ? w : 1.0f );\n            assert( !isnan( depthPtr[x].y ) );\n            assert( depthPtr[x].x <= 1.0 );\n         }\n      }\n\n      dPyr.push_back( dCurr.clone() );\n      iPyr.push_back( iCurr.clone() );\n      currPyrSz = std::min( iCurr.rows, iCurr.cols );\n   }\n\n   // upscale\n   for ( size_t i = 2; i <= dPyr.size(); ++i )\n   {\n      const size_t cl = dPyr.size() - i;\n      const size_t pl = cl + 1;\n\n      const Mat& iCurr = iPyr[cl];\n      const Mat& iPrev = iPyr[pl];\n\n      Mat& dCurr = dPyr[cl];\n      const Mat& dPrev = dPyr[pl];\n\n#pragma omp parallel for\n      for ( unsigned y = 0; y < dCurr.rows; y++ )\n      {\n         vec4* depthPtr = dCurr.ptr<vec4>( y );\n         const vec3* imgPtr = iCurr.ptr<vec3>( y );\n\n         for ( unsigned x = 0; x < dCurr.cols; x++ )\n         {\n            vec4& dH = depthPtr[x];\n\n            if ( ( dH.y == 0.0 ) || ( filter > 0.0 ) )\n            {\n               vec4 val( 0.0 );\n               float w = 0.0;\n\n               const vec3& cH = imgPtr[x];\n               const vec2 pos( x, y );\n\n               for ( int dy = -1; dy <= 1; dy++ )\n               {\n                  for ( int dx = -1; dx <= 1; dx++ )\n                  {\n                     const vec2 dpos( (float)x + (float)dx, (float)y + (float)dy );\n                     const vec4 dL = cv_utils::imsample32F<vec4>( dPrev, 0.5f * dpos );\n                     if ( isnan( dL.y ) || ( dL.y == 0.0 ) )\n                     {\n                        vec4 dL2 = cv_utils::imsample32F<vec4>( dPrev, 0.5f * dpos );\n                     }\n                     assert( !isnan( dL.y ) );\n                     assert( dL.y > 0.0 );\n                     const vec3 cL = cv_utils::imsample32F<vec3>( iPrev, 0.5f * dpos );\n\n                     const float sp_dist = distance( pos, dpos );\n                     const float col_dist = distance( cL, cH );\n\n                     const float z =\n                         exp( -sp_dist * sp_dist / sp_z ) * exp( -col_dist * col_dist / col_z );\n                     w += z;\n                     assert( !isnan( w ) );\n                     val += z * dL;\n                  }\n               }\n\n               dH = ( dH.y == 0.0 ) ? val / w : mix( dH, val / w, filter );\n               assert( !isnan( dH.y ) );\n               assert( dH.y > 0.0 );\n               assert( dH.x <= 1.0 );\n            }\n         }\n      }\n   }\n\n#pragma omp parallel for\n   for ( unsigned y = 0; y < depth.rows; y++ )\n   {\n      float* depthPtr = depth.ptr<float>( y );\n      vec4* dPtr = dPyr.front().ptr<vec4>( y );\n      for ( unsigned x = 0; x < depth.cols; x++ )\n      {\n         depthPtr[x] = dPtr[x].x;\n      }\n   }\n}\n\n//------------------------------------------------------------------------------\n//\nvoid processDepth(\n    Mat& depth,\n    const Mat& img,\n    const float undef = 0.0,\n    const int rad = 5,\n    const float sigCol = 0.1 )\n{\n   depth =\n       depth( Rect( 150, depth.rows / 3 + 20, depth.cols - 300, 2 * depth.rows / 3 - 20 ) ).clone();\n\n   Mat depthOut = depth.clone();\n\n   const uvec2 maxTileSz( 64, 64 );\n   const uvec2 nTiles( depth.cols / maxTileSz.x + 1, depth.rows / maxTileSz.y + 1 );\n   const vec2 tileSz( (float)depth.cols / nTiles.x, (float)depth.rows / nTiles.y );\n\n   for ( unsigned tileY = 0; tileY < nTiles.y; ++tileY )\n   {\n      for ( unsigned tileX = 0; tileX < nTiles.x; ++tileX )\n      {\n         const vec2 tileId( tileX, tileY );\n         const vec2 tileStart = max( tileId * tileSz - (float)rad, vec2( 0.0f ) );\n         const vec2 tileEnd =\n             min( ( tileId + 1.0f ) * tileSz + (float)rad, vec2( depth.cols - 1, depth.rows - 1 ) );\n\n         const Rect tile(\n             tileStart.x, tileStart.y, tileEnd.x - tileStart.x + 1, tileEnd.y - tileStart.y + 1 );\n\n         Mat tileDepth = depth( tile );\n         Mat tileDepthOut = depthOut( tile );\n         Mat tileImg = img( tile );\n\n         /*imshow(\"depth\", depth);\n         imshow(\"tile\", tileDepth);\n         waitKey(0);*/\n\n         // ------------\n         // solve the system || Wdx - Wdb ||^2\n         // W is the affinitiy matrix between pixels :\n         // w(x,y) = exp( -|I(x)-I(y)|^2 / sig^2 ) if ||x-y||^2 < th\n         //        = 0 otherwise\n         // dx are the unknown depth values\n         // db are the known depth values\n\n         // set the undefined depth position\n         std::vector<uvec2> undefIdx;\n         {\n            vector<vector<uvec2> > yxUndefIdx( tileDepth.rows );\n            vector<unsigned> cumUndef( tileDepth.rows );\n            //#pragma omp parallel for\n            for ( unsigned y = 0; y < tileDepth.rows; y++ )\n            {\n               const float* depthPtr = tileDepth.ptr<float>( y );\n               vector<uvec2>& xUndefIdx = yxUndefIdx[y];\n               unsigned& nUndef = cumUndef[y];\n               nUndef = 0;\n               xUndefIdx.reserve( tileDepth.cols );\n               for ( size_t x = 0; x < tileDepth.cols; x++ )\n               {\n                  if ( depthPtr[x] != undef ) continue;\n                  xUndefIdx.emplace_back( x, y );\n                  nUndef++;\n               }\n            }\n            for ( unsigned y = 1; y < tileDepth.rows; y++ ) cumUndef[y] += cumUndef[y - 1];\n            undefIdx.resize( cumUndef.back() );\n            //#pragma omp parallel for\n            for ( unsigned y = 0; y < tileDepth.rows - 1; y++ )\n            {\n               std::cout << undefIdx.size() << \"/\" << cumUndef[y] << \"/\" << yxUndefIdx[y].size()\n                         << endl;\n               memcpy(\n                   &undefIdx[cumUndef[y]],\n                   &yxUndefIdx[y][0],\n                   sizeof( uvec2 ) * yxUndefIdx[y].size() );\n            }\n         }\n\n         // create the system\n         const unsigned nUndef = undefIdx.size();\n         MatrixXf W = MatrixXf::Zero( nUndef, nUndef );\n         MatrixXf B = MatrixXf::Zero( nUndef, 1 );\n         //#pragma omp parallel for\n         for ( unsigned u = 0; u < nUndef; ++u )\n         {\n            const uvec2& upos = undefIdx[u];\n            const vec3 ucol = tileImg.at<vec3>( upos.x, upos.y );\n\n            // compute B from all neigboring defined pixels\n            float sb_w = 0.0;\n            float wb = 0.0;\n            W( u, u ) = -1.0;\n            for ( int ny = std::max( (int)( upos.y - rad ), 0 );\n                  ny <= std::min( (int)( upos.y + rad ), tileDepth.rows - 1 );\n                  ++ny )\n            {\n               for ( int nx = std::max( (int)( upos.x - rad ), 0 );\n                     nx <= std::min( (int)( upos.x + rad ), tileDepth.cols - 1 );\n                     ++nx )\n               {\n                  const uvec2 vpos( nx, ny );\n                  if ( vpos == upos ) continue;\n                  const float vd = tileDepth.at<float>( vpos.x, vpos.y );\n                  if ( vd != undef )\n                  {\n                     const vec3 dcol = tileImg.at<vec3>( vpos.x, vpos.y ) - ucol;\n                     const float w = exp( -1.0 * dot( dcol, dcol ) / sigCol );\n                     sb_w += w;\n                     wb += w * vd;\n                  }\n               }\n            }\n            B( u, 0 ) = sb_w > 0.0 ? wb / sb_w : 0.0;\n\n            // compute W from all neigboring undefined pixels\n            float sw_w = 0.0;\n            for ( unsigned v = 0; v < nUndef; ++v )\n            {\n               if ( v == u ) continue;\n               const uvec2& vpos = undefIdx[v];\n               if ( distance( vec2( upos ), vec2( vpos ) ) > rad ) continue;\n               const vec3 dcol = tileImg.at<vec3>( vpos.x, vpos.y ) - ucol;\n               const float w = exp( -1.0 * dot( dcol, dcol ) / sigCol );\n               sw_w += w;\n               W( u, v ) = w;\n            }\n            if ( sw_w > 0.0 ) W.row( u ) = W.row( u ) / sw_w;\n         }\n\n         // solve the system\n         MatrixXf WtW( nUndef, nUndef );\n         WtW.template triangularView<Lower>() = W.transpose() * W;\n         MatrixXf WtB = W.transpose() * B;\n         WtW.ldlt().solveInPlace( WtB );\n\n         // set the missing value\n         //#pragma omp parallel for\n         for ( unsigned u = 0; u < nUndef; ++u )\n         {\n            const uvec2& pos = undefIdx[u];\n            tileDepthOut.at<float>( pos.x, pos.y ) = WtB( u, 0 );\n         }\n\n         imshow( \"tile\", tileDepth );\n         imshow( \"outtile\", tileDepthOut );\n         waitKey( 0 );\n      }\n   }\n\n   depth = depthOut;\n}\n}\n//------------------------------------------------------------------------------\n//\n//------------------------------------------------------------------------------\n\nconst string keys =\n    \"{help h usage ? |         | print this message   }\"\n    \"{@imgFileLst   |         | images list   }\"\n    \"{@imgRootDir   |         | images root dir   }\"\n    \"{@imgOutDir    |         | images output dir   }\"\n    \"{@nbSamples      |         |    }\";\n\nint main( int argc, char* argv[] )\n{\n   CommandLineParser parser( argc, argv, keys );\n   if ( parser.has( \"help\" ) )\n   {\n      parser.printMessage();\n      return ( 0 );\n   }\n\n   const bool toLinear = false;\n   int nbSamples = parser.get<int>( \"@nbSamples\" );\n\n   const filesystem::path outRootPath( parser.get<string>( \"@imgOutDir\" ) );\n   filesystem::path outGroupRootPath = outRootPath;\n\n   // Create the list of image triplets\n\n   ImgNFileLst<6> imgLst(\n       parser.get<string>( \"@imgFileLst\" ).c_str(), parser.get<string>( \"@imgRootDir\" ).c_str() );\n   if ( imgLst.size() == 0 )\n   {\n      cerr << \"Invalid dataset : \" << parser.get<string>( \"@imgFileLst\" ) << endl;\n      return -1;\n   }\n\n   unsigned startIdx = 0;\n   const int nMaxRendersPerGroup = 10000;\n   \n   // Loop through the data\n   nbSamples = nbSamples <= 0 ? imgLst.size() : nbSamples;\n   for ( size_t i = 0; i < nbSamples; ++i )\n   {\n      const auto& data = imgLst[i];\n\n      if ( ( ( startIdx + i ) % nMaxRendersPerGroup ) == 0 )\n      {\n         const unsigned renderGroupId = ( startIdx + i ) / nMaxRendersPerGroup;\n         char dirname[7];\n         sprintf( dirname, \"%06d\", renderGroupId );\n         outGroupRootPath = outRootPath / filesystem::path( std::string( dirname ) );\n         if ( !filesystem::create_directory( outGroupRootPath ) )\n         {\n            cerr << \"Cannot create directory : \" << outGroupRootPath.string() << endl;\n         }\n      }\n\n      char sampleIdName[7];\n      sprintf(sampleIdName,\"%06d\",i);\n      const string outPrefix = string(sampleIdName) + \"_\";\n         //filesystem::path( data[1] ).parent_path().stem().string() + \"_\";\n\n      // for ( size_t j = 0; j < 3; ++j )\n      size_t j = 1;\n      {\n         // load the current image\n         Mat img = cv::imread( data[j * 2], cv::IMREAD_UNCHANGED );\n         Mat depth = cv::imread( data[j * 2 + 1], cv::IMREAD_UNCHANGED );\n\n         processImg( img );\n\n         Mat mask = processDepthMask( depth );\n\n         // normalize(depth, depth, 1.0, 0.0, NORM_MINMAX);\n\n         // imshow( \"InDepth\", depth( Rect( 150, depth.rows / 3 + 20, depth.cols - 300, 2 *\n         // depth.rows / 3 - 20 ) ) );  processDepth( depth, img, 0.0f, 1.0, 0.1, 0.23  );\n\n         // display\n         /*imshow( \"Img\", img );\n         imshow( \"Depth\", depth );\n         imshow( \"Mask\", mask );*/\n\n         const string outBasename = outPrefix + filesystem::path( data[j * 2] ).stem().string();\n         const filesystem::path fRight( outBasename + string( \"_rgb\" ) + \".png\" );\n         const filesystem::path fDepth( outBasename + string( \"_d\" ) + \".png\" );\n         const filesystem::path fMask( outBasename + string( \"_a\" ) + \".png\" );\n\n         imwrite( filesystem::path( outGroupRootPath / fRight ).string().c_str(), img );\n         imwrite( filesystem::path( outGroupRootPath / fDepth ).string().c_str(), depth );\n         imwrite( filesystem::path( outGroupRootPath / fMask ).string().c_str(), mask );\n\n         cout << fRight.string() << \" \" << fDepth.string() << \" \" << fMask.string();\n         // if ( j == 2 )\n         cout << endl;\n         /*else\n          */ cout << \" \";\n\n         //waitKey( 0 );\n      }\n\n      // waitKey( 0 );\n   }\n\n   return ( 0 );\n}\n", "meta": {"hexsha": "d201e2bfefbc986b5da88c5fb3e0120ef12ab3e2", "size": 15669, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depthMapCreation/depthMapCreationKitti_main.cpp", "max_stars_repo_name": "moennen/sceneIllEst", "max_stars_repo_head_hexsha": "c02358e43016c3b44059554c4e202e922656be89", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-04T09:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-17T07:02:49.000Z", "max_issues_repo_path": "depthMapCreation/depthMapCreationKitti_main.cpp", "max_issues_repo_name": "moennen/sceneIllEst", "max_issues_repo_head_hexsha": "c02358e43016c3b44059554c4e202e922656be89", "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": "depthMapCreation/depthMapCreationKitti_main.cpp", "max_forks_repo_name": "moennen/sceneIllEst", "max_forks_repo_head_hexsha": "c02358e43016c3b44059554c4e202e922656be89", "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.8490566038, "max_line_length": 100, "alphanum_fraction": 0.4545918693, "num_tokens": 4366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5121057410968118}}
{"text": "#ifndef BOOSTGRAPH\n#define BOOSTGRAPH\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/edge_connectivity.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <boost/graph/clustering_coefficient.hpp>\n#include <boost/graph/dominator_tree.hpp>\n#include <boost/graph/cuthill_mckee_ordering.hpp>\n#include <boost/graph/king_ordering.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/graph/floyd_warshall_shortest.hpp>\n#include <boost/graph/biconnected_components.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/graph/edge_list.hpp>\n\n#include <map>\n#include <iostream>\n#include <utility>\n\ntypedef int v_index;\ntypedef long e_index;\n\n// This struct is the output of the edge connectivity Boost algorithm.\ntypedef struct {\n    v_index ec; // The edge connectivity\n    std::vector<v_index> edges; // The edges in a minimum cut, stored as a list of\n                       // nodes. For instance, if the minimum cut is\n                       // {(1,2),(3,4)}, the output vector will be (1,2,3,4).\n} result_ec;\n\n// This struct is the output of the clustering coefficient Boost algorithm.\ntypedef struct {\n    double average_clustering_coefficient; // The average clustering coefficient\n    std::vector<double> clust_of_v;             // The clustering coefficient of each node.\n} result_cc;\n\n// This struct is the output of the edge connectivity Boost algorithm.\ntypedef struct {\n    std::vector<double> distances; // An array with all distances from the starting vertex\n    std::vector<v_index> predecessors; // For each vertex v, the first vertex in a shortest\n                                  // path from the starting vertex to v.\n} result_distances;\n\ntemplate <class OutEdgeListS, // How neighbors are stored\n          class VertexListS,  // How vertices are stored\n          class DirectedS,    // The kind of graph (undirectedS, directedS, or bidirectionalS)\n          class EdgeListS,    // How the list of edges is stored\n          class EdgeProperty> // Properties of edges (weight)\nclass BoostGraph\n/*\n * This generic class wraps a Boost graph, in order to make it Cython-friendly.\n *\n * In particular, it allows to \"keep together\" the Boost graph and the vector\n * *vertices: these two variables are generic, and Cython is not able to deal\n * with them properly, since it does not support generic classes.\n *\n * Vertices are numbers from 0 to n-1, where n is the total number of vertices:\n * this class takes care of the relation between number i and the corresponding\n * Boost vertex descriptor (which might be any object, depending on the value of\n * VertexListS). In particular, (*vertices)[i] contains the Boost vertex\n * corresponding to number i, while to transform a Boost vertex v into a number\n * we use vertex properties, and the syntax is (*graph)[v].\n*/\n{\nprivate:\n    typedef typename boost::adjacency_list<\n        OutEdgeListS, VertexListS, DirectedS,\n        boost::property<boost::vertex_index_t, v_index>,\n        EdgeProperty, boost::no_property, EdgeListS> adjacency_list;\n    typedef typename boost::graph_traits<adjacency_list>::vertex_descriptor vertex_descriptor;\n    typedef typename boost::graph_traits<adjacency_list>::edge_descriptor edge_descriptor;\n    typedef typename std::vector<edge_descriptor> edge_container;\n    typedef typename boost::property_map<adjacency_list, boost::vertex_index_t>::type vertex_to_int_map;\n\n    // This struct is used for biconnected_components function\n    struct order_edges {\n        bool operator()(const edge_descriptor& x, const edge_descriptor& y) const { return x.get_property() < y.get_property(); }\n    };\n    // This map is a parameter/output for biconnected_components function\n    typedef typename std::map<edge_descriptor, int, order_edges> edge_map;\n\npublic:\n    adjacency_list graph;\n    std::vector<vertex_descriptor> vertices;\n    vertex_to_int_map index;\n\n    BoostGraph() {\n    }\n\n    v_index num_verts() {\n        return num_vertices(graph);\n    }\n\n    e_index num_edges() {\n        return boost::num_edges(graph);\n    }\n\n    void add_vertex() {\n        vertices.push_back(boost::add_vertex(vertices.size(), graph));\n    }\n\n    void add_edge(v_index u, v_index v) {\n        boost::add_edge(vertices[u], vertices[v], graph);\n    }\n\n    void add_edge(v_index u, v_index v, double weight) {\n        boost::add_edge(vertices[u], vertices[v], weight, graph);\n    }\n\n    std::vector<std::pair<v_index, std::pair<v_index, double>>> edge_list() {\n        std::vector<std::pair<v_index, std::pair<v_index, double>>> to_return;\n        typename boost::graph_traits<adjacency_list>::edge_iterator ei, ei_end;\n        for (boost::tie(ei, ei_end) = boost::edges(graph); ei != ei_end; ++ei) {\n            to_return.push_back({index[boost::source(*ei, graph)],\n                                 {index[boost::target(*ei, graph)],\n                                  get(boost::edge_weight, graph, *ei)}});\n        }\n        return to_return;\n    }\n\n    result_ec edge_connectivity() {\n        result_ec to_return;\n        edge_container disconnecting_set;\n        std::back_insert_iterator<edge_container> inserter(disconnecting_set);\n        to_return.ec = boost::edge_connectivity(graph, inserter);\n\n        for (size_t i = 0; i < disconnecting_set.size(); i++) {\n            edge_descriptor edge = disconnecting_set[i];\n            to_return.edges.push_back(index[boost::source(edge, graph)]);\n            to_return.edges.push_back(index[boost::target(edge, graph)]);\n        }\n        return to_return;\n    }\n\n    double clustering_coeff(v_index v) {\n        return clustering_coefficient(graph, vertices[v]);\n    }\n\n    result_cc clustering_coeff_all() {\n        result_cc to_return;\n        to_return.clust_of_v.resize(num_verts());\n        to_return.average_clustering_coefficient = all_clustering_coefficients(graph,\n            boost::make_iterator_property_map(to_return.clust_of_v.begin(), index));\n        return to_return;\n    }\n\n    std::vector<v_index> dominator_tree(v_index v) {\n        std::vector<v_index> fathers(num_verts());\n        std::vector<vertex_descriptor> fathers_descr(num_verts(),\n                    boost::graph_traits<adjacency_list>::null_vertex());\n\n        lengauer_tarjan_dominator_tree(graph, vertices[v],\n                                       boost::make_iterator_property_map(\n                                           fathers_descr.begin(), index));\n\n        for (v_index i = 0; i < num_verts(); i++) {\n            vertex_descriptor v = fathers_descr[i];\n            if (v == boost::graph_traits<adjacency_list>::null_vertex()) {\n                fathers[i] = -1;\n            } else {\n                fathers[i] = index[v];\n            }\n        }\n        return fathers;\n    }\n\n    // Works only in undirected graphs!\n    std::vector<v_index> bandwidth_ordering(bool cuthill) {\n        std::vector<v_index> to_return;\n        std::vector<vertex_descriptor> inv_perm(num_vertices(graph));\n\n        if (cuthill) {\n            boost::cuthill_mckee_ordering(graph, inv_perm.rbegin());\n        } else {\n            boost::king_ordering(graph, inv_perm.rbegin());\n        }\n\n        for (size_t i = 0; i < inv_perm.size(); i++) {\n            to_return.push_back(index[inv_perm[i]]);\n        }\n        return to_return;\n    }\n\n    // This function works only on undirected graphs.\n    std::vector<v_index> kruskal_min_spanning_tree() {\n        std::vector<v_index> to_return;\n        std::vector<edge_descriptor> spanning_tree;\n        kruskal_minimum_spanning_tree(graph, std::back_inserter(spanning_tree));\n\n        for (unsigned int i = 0; i < spanning_tree.size(); i++) {\n            to_return.push_back(index[source(spanning_tree[i], graph)]);\n            to_return.push_back(index[target(spanning_tree[i], graph)]);\n        }\n        return to_return;\n    }\n\n    // This function works only on undirected graphs with no parallel edge.\n    std::vector<v_index> prim_min_spanning_tree() {\n        std::vector<v_index> to_return;\n        std::vector<vertex_descriptor> predecessors(num_verts());\n        prim_minimum_spanning_tree(graph, boost::make_iterator_property_map(predecessors.begin(), index));\n\n        for (unsigned int i = 0; i < predecessors.size(); i++) {\n            if (index[predecessors[i]] != i) {\n                to_return.push_back(i);\n                to_return.push_back(index[predecessors[i]]);\n            }\n        }\n        return to_return;\n    }\n\n    // This function returns the biconnected components of the graph.\n    std::vector<std::vector<v_index>> blocks_and_cut_vertices() {\n        edge_map bicmp_map;\n        boost::associative_property_map<edge_map> bimap(bicmp_map);\n        std::size_t num_comps = biconnected_components(graph, bimap);\n\n        // We iterate over every edge and add the vertices of block i into to_return[i].\n        // to_return[i] could contain repetitions.\n        std::vector<std::vector<v_index>> to_return(num_comps, std::vector<v_index>(0));\n        typename boost::graph_traits<adjacency_list>::edge_iterator ei, ei_end;\n        for (boost::tie(ei, ei_end) = edges(graph); ei != ei_end; ++ei) {\n            to_return[bimap[*ei]].push_back(index[source(*ei, graph)]);\n            to_return[bimap[*ei]].push_back(index[target(*ei, graph)]);\n        }\n\n        return to_return;\n    }\n\n    result_distances dijkstra_shortest_paths(v_index s) {\n         v_index N = num_verts();\n         result_distances to_return;\n         std::vector<double> distances(N, (std::numeric_limits<double>::max)());\n         std::vector<vertex_descriptor> predecessors(N);\n         try {\n             boost::dijkstra_shortest_paths(graph, vertices[s], distance_map(boost::make_iterator_property_map(distances.begin(), index))\n                                            .predecessor_map(boost::make_iterator_property_map(predecessors.begin(), index)));\n         } catch (boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::negative_edge> > e) {\n             return to_return;\n         }\n\n         to_return.distances = distances;\n\n         for (int i = 0; i < N; i++) {\n             to_return.predecessors.push_back(index[predecessors[i]]);\n         }\n\n         return to_return;\n     }\n\n     result_distances bellman_ford_shortest_paths(v_index s) {\n         v_index N = num_verts();\n\n         std::vector<double> distance(N, (std::numeric_limits<double>::max)());\n         std::vector<vertex_descriptor> predecessors(N);\n         result_distances to_return;\n         typename boost::property_map<adjacency_list, boost::edge_weight_t>::type weight = get(boost::edge_weight, (graph));\n\n         for (v_index i = 0; i < N; ++i)\n             predecessors[i] = vertices[i];\n\n         distance[s] = 0;\n         bool r = boost::bellman_ford_shortest_paths\n             (graph, N, boost::weight_map(weight).distance_map(boost::make_iterator_property_map(distance.begin(), index)).predecessor_map(boost::make_iterator_property_map(predecessors.begin(), index)));\n\n         if (!r) {\n             return to_return;\n         }\n\n         to_return.distances = distance;\n         for (int i = 0; i < N; i++) {\n             to_return.predecessors.push_back(index[predecessors[i]]);\n         }\n         return to_return;\n     }\n     std::vector<std::vector<double> > floyd_warshall_shortest_paths() {\n         v_index N = num_verts();\n\n         std::vector<std::vector<double> > D(N, std::vector<double>(N));\n         if (floyd_warshall_all_pairs_shortest_paths(graph, D)) {\n             return D;\n         } else {\n             return std::vector<std::vector<double> >();\n         }\n     }\n     std::vector<std::vector<double> > johnson_shortest_paths() {\n         v_index N = num_verts();\n\n         std::vector<std::vector<double> > D(N, std::vector<double>(N));\n         if (johnson_all_pairs_shortest_paths(graph, D)) {\n             return D;\n         } else {\n             return std::vector<std::vector<double> >();\n         }\n     }\n};\n\n\n\n#endif // BOOSTGRAPH\n", "meta": {"hexsha": "f593d45dda65e1e4367c9679e7c942030f424eb4", "size": 12239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sage/graphs/base/boost_interface.cpp", "max_stars_repo_name": "fchapoton/sage", "max_stars_repo_head_hexsha": "765c5cb3e24dd134708eca97e4c52e0221cd94ba", "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/graphs/base/boost_interface.cpp", "max_issues_repo_name": "Ivo-Maffei/sage", "max_issues_repo_head_hexsha": "467fbc70a08b552b3de33d9065204ee9cbfb02c7", "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/graphs/base/boost_interface.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": 39.9967320261, "max_line_length": 204, "alphanum_fraction": 0.6499714029, "num_tokens": 2755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5121041424218604}}
{"text": "#pragma once\n\n// C++ standard library\n#include <random>\n\n// Armadillo\n#include <armadillo>\n\nnamespace mant {\n  arma::mat randomRotationMatrix(\n      const arma::uword numberOfDimensions);\n\n  arma::uvec randomPermutationVector(\n      const arma::uword numberOfElements,\n      const arma::uword cycleSize);\n  arma::uvec randomPermutationVector(\n      const arma::uword numberOfElements);\n\n  arma::vec randomNeighbour(\n      const arma::vec& parameter,\n      const double minimalDistance,\n      const double maximalDistance);\n  arma::vec randomNeighbour(\n      const arma::vec& parameter,\n      const double maximalDistance);\n\n  arma::mat uniformRandomNumbers(\n      const arma::uword numberOfRows,\n      const arma::uword numberOfColumns,\n      std::uniform_real_distribution<double> distribution);\n  arma::mat uniformRandomNumbers(\n      const arma::uword numberOfRows,\n      const arma::uword numberOfColumns);\n\n  arma::vec uniformRandomNumbers(\n      const arma::uword numberOfElements,\n      std::uniform_real_distribution<double> distribution);\n  arma::vec uniformRandomNumbers(\n      const arma::uword numberOfElements);\n\n  arma::mat normalRandomNumbers(\n      const arma::uword numberOfRows,\n      const arma::uword numberOfColumns,\n      std::normal_distribution<double> distribution);\n  arma::mat normalRandomNumbers(\n      const arma::uword numberOfRows,\n      const arma::uword numberOfColumns);\n\n  arma::vec normalRandomNumbers(\n      const arma::uword numberOfElements,\n      std::normal_distribution<double> distribution);\n  arma::vec normalRandomNumbers(\n      const arma::uword numberOfElements);\n}\n", "meta": {"hexsha": "9ad4d9f4caac8718fbae0abfe67b3f3b5d77185e", "size": 1613, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mantella_bits/probability.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/probability.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/probability.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": 29.3272727273, "max_line_length": 59, "alphanum_fraction": 0.7247365158, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6477982179521105, "lm_q1q2_score": 0.5121041380651367}}
{"text": "#include <blitz/array.h>\n\nusing namespace blitz;\n\nint main()\n{\n    Array<complex<float>, 2> Z(4,4);\n\n    Z = complex<float>(0.0, 1.0);\n\n    Z(4,4) = complex<float>(1.0, 0.0);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "a5ea52faaf53cc2b691be68d33cb6a7c665c9362", "size": 193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/doc/examples/debug.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/doc/examples/debug.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/doc/examples/debug.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": 12.0625, "max_line_length": 38, "alphanum_fraction": 0.5595854922, "num_tokens": 71, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6477982111525409, "lm_q1q2_score": 0.5121041326898708}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/log2.hpp\n *\n * \\brief Apply the \\c std::log2 function to a vector or matrix expression.\n *\n * Copyright (c) 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_LOG2_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_LOG2_HPP\n\n\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/expression/matrix_unary_functor.hpp>\n#include <boost/numeric/ublasx/expression/vector_unary_functor.hpp>\n#include <cmath>\n#include <complex>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\nnamespace detail {\n\ntemplate <typename VectorExprT>\nstruct vector_log2_functor_traits\n{\n\ttypedef VectorExprT input_expression_type;\n\ttypedef typename vector_traits<input_expression_type>::value_type signature_argument_type;\n\ttypedef signature_argument_type signature_result_type;\n\ttypedef vector_unary_functor_traits<\n\t\t\t\tinput_expression_type,\n\t\t\t\tsignature_result_type (signature_argument_type)\n\t\t\t> unary_functor_expression_type;\n\ttypedef typename unary_functor_expression_type::result_type result_type;\n\ttypedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\ntemplate <typename MatrixExprT>\nstruct matrix_log2_functor_traits\n{\n\ttypedef MatrixExprT input_expression_type;\n\ttypedef typename matrix_traits<input_expression_type>::value_type signature_argument_type;\n\ttypedef signature_argument_type signature_result_type;\n\ttypedef matrix_unary_functor_traits<\n\t\t\t\tinput_expression_type,\n\t\t\t\tsignature_result_type (signature_argument_type)\n\t\t\t> unary_functor_expression_type;\n\ttypedef typename unary_functor_expression_type::result_type result_type;\n\ttypedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\nnamespace /*<unnamed>*/ {\n\n/// Auxiliary function used to replace ::std::log2 when that is not available.\ntemplate <typename T>\nBOOST_UBLAS_INLINE\nT log2(T x)\n{\n  // C++0x and higher has std::log2 but it \n  // doesn't work with complex numbers.\n\treturn ::std::log(x)/::std::log(2);\n}\n\n} // Namespace <unnamed>\n\n} // Namespace detail\n\n\n/**\n * \\brief Applies the \\c std::log2 function to a given vector expression.\n *\n * \\tparam VectorExprT The type of the input vector expression.\n *\n * \\param ve The input vector expression.\n * \\return A vector expression representing the application of \\c std::log2 to\n *  each element of \\a ve.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename detail::vector_log2_functor_traits<VectorExprT>::result_type log2(vector_expression<VectorExprT> const& ve)\n{\n\ttypedef typename detail::vector_log2_functor_traits<VectorExprT>::expression_type expression_type;\n\ttypedef typename detail::vector_log2_functor_traits<VectorExprT>::signature_result_type signature_result_type;\n\n\treturn expression_type(ve(), detail::log2<signature_result_type>);\n}\n\n\n/**\n * \\brief Applies the \\c std::log2 function to a given matrix expression.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param me The input matrix expression.\n * \\return A matrix expression representing the application of \\c std::log2 to\n *  each element of \\a me.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename detail::matrix_log2_functor_traits<MatrixExprT>::result_type log2(matrix_expression<MatrixExprT> const& me)\n{\n\ttypedef typename detail::matrix_log2_functor_traits<MatrixExprT>::expression_type expression_type;\n\ttypedef typename detail::matrix_log2_functor_traits<MatrixExprT>::signature_result_type signature_result_type;\n\n\treturn expression_type(me(), detail::log2<signature_result_type>);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_LOG2_HPP\n", "meta": {"hexsha": "a353f452fd7fcba4eff079d8ca87543c496ba136", "size": 4021, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/log2.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/log2.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/log2.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.9126984127, "max_line_length": 116, "alphanum_fraction": 0.798060184, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5121041316713292}}
{"text": "#define BOOST_TEST_MODULE vector\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/vector/all.h++>\n\n\n\ntypedef boost::mpl::list<\n\tmla::vector::Dense<float>,\n\tmla::vector::Dense<double>,\n\tmla::vector::SparseCS<float>,\n\tmla::vector::SparseCS<double>\n> vector_type_list;\n\n\n\nBOOST_AUTO_TEST_SUITE(vector)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( Declaration, VectorType, vector_type_list )\n{\n\tVectorType v(3);\n\n\tBOOST_CHECK_EQUAL(v.size(), 3);\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( Clearing, VectorType, vector_type_list )\n{\n\tVectorType v(3);\n\tv.setZero();\n\n\tfor(unsigned int i = 0; i < 3; i++)\n\t{\n\t\tBOOST_CHECK_EQUAL(v.getValue(i), 0.0);\n\t}\n\t\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( Assigning, VectorType, vector_type_list )\n{\n\tVectorType v(3);\n\tv.setZero();\n\n\tv.setValue(1, 1.0);\t\n\n\tBOOST_CHECK_EQUAL(v.getValue(0), 0.0);\n\tBOOST_CHECK_EQUAL(v.getValue(1), 1.0);\n\tBOOST_CHECK_EQUAL(v.getValue(2), 0.0);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "5e5110f2f9b41a29b1390f6c6fb0f2d2a8570f5a", "size": 994, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_vector.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "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": "unit_tests/test_vector.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/test_vector.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "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.5666666667, "max_line_length": 74, "alphanum_fraction": 0.7263581489, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5120906233000398}}
{"text": "/*\r\n * Copyright Nick Thompson, 2019\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\r\n#ifndef BOOST_MATH_STATISTICS_RUNS_TEST_HPP\r\n#define BOOST_MATH_STATISTICS_RUNS_TEST_HPP\r\n\r\n#include <cmath>\r\n#include <algorithm>\r\n#include <utility>\r\n#include <boost/math/statistics/univariate_statistics.hpp>\r\n#include <boost/math/distributions/normal.hpp>\r\n\r\nnamespace boost::math::statistics {\r\n\r\ntemplate<class RandomAccessContainer>\r\nauto runs_above_and_below_threshold(RandomAccessContainer const & v,\r\n                          typename RandomAccessContainer::value_type threshold)\r\n{\r\n    using Real = typename RandomAccessContainer::value_type;\r\n    using std::sqrt;\r\n    using std::abs;\r\n    if (v.size() <= 1)\r\n    {\r\n        throw std::domain_error(\"At least 2 samples are required to get number of runs.\");\r\n    }\r\n    typedef boost::math::policies::policy<\r\n          boost::math::policies::promote_float<false>,\r\n          boost::math::policies::promote_double<false> >\r\n          no_promote_policy;\r\n\r\n    decltype(v.size()) nabove = 0;\r\n    decltype(v.size()) nbelow = 0;\r\n\r\n    decltype(v.size()) imin = 0;\r\n\r\n    // Take care of the case that v[0] == threshold:\r\n    while (imin < v.size() && v[imin] == threshold) {\r\n        ++imin;\r\n    }\r\n\r\n    // Take care of the constant vector case:\r\n    if (imin == v.size()) {\r\n        return std::make_pair(std::numeric_limits<Real>::quiet_NaN(), Real(0));\r\n    }\r\n\r\n    bool run_up = (v[imin] > threshold);\r\n    if (run_up) {\r\n        ++nabove;\r\n    } else {\r\n        ++nbelow;\r\n    }\r\n    decltype(v.size()) runs = 1;\r\n    for (decltype(v.size()) i = imin + 1; i < v.size(); ++i) {\r\n      if (v[i] == threshold) {\r\n        // skip values precisely equal to threshold (following R's randtests package)\r\n        continue;\r\n      }\r\n      bool above = (v[i] > threshold);\r\n      if (above) {\r\n          ++nabove;\r\n      } else {\r\n          ++nbelow;\r\n      }\r\n      if (run_up == above) {\r\n        continue;\r\n      }\r\n      else {\r\n        run_up = above;\r\n        runs++;\r\n      }\r\n    }\r\n\r\n    // If you make n an int, the subtraction is gonna be bad in the variance:\r\n    Real n = nabove + nbelow;\r\n\r\n    Real expected_runs = Real(1) + Real(2*nabove*nbelow)/Real(n);\r\n    Real variance = 2*nabove*nbelow*(2*nabove*nbelow-n)/Real(n*n*(n-1));\r\n\r\n    // Bizarre, pathological limits:\r\n    if (variance == 0)\r\n    {\r\n        if (runs == expected_runs)\r\n        {\r\n            Real statistic = 0;\r\n            Real pvalue = 1;\r\n            return std::make_pair(statistic, pvalue);\r\n        }\r\n        else\r\n        {\r\n            return std::make_pair(std::numeric_limits<Real>::quiet_NaN(), Real(0));\r\n        }\r\n    }\r\n\r\n    Real sd = sqrt(variance);\r\n    Real statistic = (runs - expected_runs)/sd;\r\n\r\n    auto normal = boost::math::normal_distribution<Real, no_promote_policy>(0,1);\r\n    Real pvalue = 2*boost::math::cdf(normal, -abs(statistic));\r\n    return std::make_pair(statistic, pvalue);\r\n}\r\n\r\ntemplate<class RandomAccessContainer>\r\nauto runs_above_and_below_median(RandomAccessContainer const & v)\r\n{\r\n    using Real = typename RandomAccessContainer::value_type;\r\n    using std::log;\r\n    using std::sqrt;\r\n\r\n    // We have to memcpy v because the median does a partial sort,\r\n    // and that would be catastrophic for the runs test.\r\n    auto w = v;\r\n    Real median = boost::math::statistics::median(w);\r\n    return runs_above_and_below_threshold(v, median);\r\n}\r\n\r\n}\r\n#endif\r\n", "meta": {"hexsha": "73809a257b1edbcbaadf9fadcb99db94287754b1", "size": 3586, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/statistics/runs_test.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/math/statistics/runs_test.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/math/statistics/runs_test.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T06:24:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:55:07.000Z", "avg_line_length": 29.393442623, "max_line_length": 91, "alphanum_fraction": 0.5987172337, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5120906159072026}}
{"text": "// Copyright (c) Jeremy Siek 2001, Marc Wintermantel 2002\r\n//\r\n// Permission to use, copy, modify, distribute and sell this software\r\n// and its documentation for any purpose is hereby granted without fee,\r\n// provided that the above copyright notice appears in all copies and\r\n// that both that copyright notice and this permission notice appear\r\n// in supporting documentation.  Silicon Graphics makes no\r\n// representations about the suitability of this software for any\r\n// purpose.  It is provided \"as is\" without express or implied warranty.\r\n\r\n#ifndef BOOST_GRAPH_BANDWIDTH_HPP\r\n#define BOOST_GRAPH_BANDWIDTH_HPP\r\n\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/detail/numeric_traits.hpp>\r\n\r\nnamespace boost {\r\n\r\n  template <typename Graph, typename VertexIndexMap>\r\n  typename graph_traits<Graph>::vertices_size_type\r\n  ith_bandwidth(typename graph_traits<Graph>::vertex_descriptor i,\r\n                const Graph& g,\r\n                VertexIndexMap index)\r\n  {\r\n    typedef typename graph_traits<Graph>::vertices_size_type size_type;\r\n    size_type b = 0;\r\n    typename graph_traits<Graph>::out_edge_iterator e, end;\r\n    for (tie(e, end) = out_edges(i, g); e != end; ++e) {\r\n      int f_i = get(index, i);\r\n      int f_j = get(index, target(*e, g));\r\n      using namespace std; // to call abs() unqualified\r\n      if(f_i > f_j)\r\n      b = std::max(b, size_type(f_i - f_j));\r\n    }\r\n    return b;\r\n  }\r\n\r\n  template <typename Graph>\r\n  typename graph_traits<Graph>::vertices_size_type\r\n  ith_bandwidth(typename graph_traits<Graph>::vertex_descriptor i,\r\n                const Graph& g)\r\n  {\r\n    return ith_bandwidth(i, g, get(vertex_index, g));\r\n  }\r\n\r\n  template <typename Graph, typename VertexIndexMap>\r\n  typename graph_traits<Graph>::vertices_size_type\r\n  bandwidth(const Graph& g, VertexIndexMap index)\r\n  {\r\n    typename graph_traits<Graph>::vertices_size_type b = 0;\r\n    typename graph_traits<Graph>::vertex_iterator i, end;\r\n    for (tie(i, end) = vertices(g); i != end; ++i)\r\n        b = std::max(b, ith_bandwidth(*i, g, index));\r\n    return b;\r\n  }\r\n\r\n  template <typename Graph>\r\n  typename graph_traits<Graph>::vertices_size_type\r\n  bandwidth(const Graph& g)\r\n  {\r\n    return bandwidth(g, get(vertex_index, g));\r\n  }\r\n\r\n  template <typename Graph, typename VertexIndexMap>\r\n  typename graph_traits<Graph>::vertices_size_type\r\n  edgesum(const Graph& g, VertexIndexMap index_map)\r\n  {\r\n    typedef typename graph_traits<Graph>::vertices_size_type size_type;\r\n    typedef typename detail::numeric_traits<size_type>::difference_type diff_t;\r\n    size_type sum = 0;\r\n    typename graph_traits<Graph>::edge_iterator i, end;\r\n    for (tie(i, end) = edges(g); i != end; ++i) {\r\n      diff_t f_u = get(index_map, source(*i, g));\r\n      diff_t f_v = get(index_map, target(*i, g));\r\n      using namespace std; // to call abs() unqualified\r\n      sum += abs(f_u - f_v);\r\n    }\r\n    return sum;\r\n  }\r\n  \r\n} // namespace boost\r\n\r\n#endif // BOOST_GRAPH_BANDWIDTH_HPP\r\n", "meta": {"hexsha": "4dd257797ba4b29150d09dc10d6f189f0d901d5d", "size": 2988, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/boost/graph/bandwidth.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T06:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:24:28.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/boost/graph/bandwidth.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/boost/graph/bandwidth.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-17T10:01:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-11T20:17:27.000Z", "avg_line_length": 35.5714285714, "max_line_length": 80, "alphanum_fraction": 0.6810575636, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5120906109588874}}
{"text": "#include <algorithm>\n#include <map>\n#include <vector>\n\n#include <boost/test/unit_test.hpp>\n\n#include <kr/utility/random.h>\n\nBOOST_AUTO_TEST_SUITE(RandomTest)\n\nBOOST_AUTO_TEST_CASE(RandInt)\n{\n    using kr::utility::random;\n    const int average = 20;\n    for (std::uint32_t seed : {0, 1, 2, 37, 4096})\n    {\n        random r{seed};\n        for (auto range : {1, 2, 8, 12, 100})\n        {\n            std::vector<int> counts(range, 0);\n            for (int i = 0; i < range * average; ++i)\n            {\n                auto value = r.randint(0, range - 1);\n                ++counts.at(value);\n            }\n            int max_variance = static_cast<int>(std::sqrt(range) * 2 + 4);\n            for (int i = 0; i < range; ++i)\n            {\n                BOOST_CHECK_GE(counts[i], std::max(1, average - max_variance));\n                BOOST_CHECK_LE(counts[i], average + max_variance + 1);\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Uniform)\n{\n    using kr::utility::random;\n    std::map<float, float> ranges = {\n        {0.0, 1.2},\n        {3.0, 100.1},\n        {-42, 42},\n        {-110.0, 0.0}};\n    for (std::uint32_t seed : {0, 1, 2, 37, 4096})\n    {\n        random r{seed};\n        for (auto [min, max] : ranges)\n        {\n            auto value = r.uniform(min, max);\n            BOOST_CHECK_GE(value, min);\n            BOOST_CHECK_LE(value, max);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "c5d931e0a0a81592b7584caaec40d00b38cb692a", "size": 1411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/utility/test/random_unittest.cpp", "max_stars_repo_name": "blackkaiserxjc/kraken", "max_stars_repo_head_hexsha": "959fe38d61432d07de98572ac3d35c4abf2e84f8", "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/utility/test/random_unittest.cpp", "max_issues_repo_name": "blackkaiserxjc/kraken", "max_issues_repo_head_hexsha": "959fe38d61432d07de98572ac3d35c4abf2e84f8", "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/utility/test/random_unittest.cpp", "max_forks_repo_name": "blackkaiserxjc/kraken", "max_forks_repo_head_hexsha": "959fe38d61432d07de98572ac3d35c4abf2e84f8", "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.1964285714, "max_line_length": 79, "alphanum_fraction": 0.5031892275, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145997, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.512090608455094}}
{"text": "//\n// Created by Sergej Krivonos on 25.02.18.\n//\n#define BOOST_TEST_MODULE System test\n#define BOOST_THREAD_PROVIDES_EXECUTORS\n#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION\n#define BOOST_THREAD_USES_MOVE\n#include <boost/test/unit_test.hpp>\n\n#include \"System.h\"\n#include \"VarHost.h\"\n#include \"e.h\"\n#include \"i.h\"\n#include \"pi.h\"\n\n#include <array>\n#include <chrono>\n#include <future>\n#include <iostream>     // cout, endl\n#include <fstream>      // fstream\n#include <thread>\n#ifdef _WIN32\n#include <Windows.h>\n#endif\n\n#include <boost/lexical_cast.hpp>\n#include <boost/thread/shared_mutex.hpp>\n#include <boost/thread/thread_pool.hpp>\n#include <boost/thread/executor.hpp>\n#include <boost/thread/executors/basic_thread_pool.hpp>\n#include <boost/tokenizer.hpp>\n\n\ntemplate<typename TimeT = std::chrono::milliseconds>\nstruct measure\n{\n    template<typename F, typename ...Args>\n    static typename TimeT::rep execution(F&& func, Args&&... args)\n    {\n        auto start = std::chrono::steady_clock::now();\n        std::forward<decltype(func)>(func)(std::forward<Args>(args)...);\n        auto duration = std::chrono::duration_cast<TimeT>(std::chrono::steady_clock::now() - start);\n        return duration.count();\n    }\n};\n\nusing namespace omnn::math;\nusing namespace boost::unit_test;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE(System_tests)\n{\n    {\n        System sys;\n        Variable a,b;\n        Valuable t;\n        t.SetView(Valuable::View::Equation);\n        t = a - 8 - b;\n        sys << t;\n        sys << a + b - 100;\n        auto s = sys.Solve(a);\n        auto haveOneSolution = s.size()==1;\n        BOOST_TEST(haveOneSolution);\n        if(haveOneSolution)\n        {\n            auto _ = *s.begin();\n            BOOST_TEST(_ == 54);\n        }\n    }\n    \n    {\n        System s;\n        Variable a,b;\n        s << a - 8 - b;\n        s << a + b - 21;\n        auto _ = s.Solve(a);\n        BOOST_TEST(_.size()==1);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(sq_System_test\n                     , *disabled()\n                     )\n{\n    System s;\n    Variable a,b,x;\n\ts << a - b - 3\n\t\t<< a + b - x\n\t\t<< a * b * 4 - (49 - 9)\n\t\t<< x * x - 49\n        << x*b + 9 +2*a*b + 3*b - 49\n        ;\n\n    auto _ = s.Solve(x);\n    BOOST_TEST(_.size()==1);\n\tauto sqx = *_.begin();\n\tBOOST_TEST(sqx == 7);\n}\n\nBOOST_AUTO_TEST_CASE(ComplexSystem_test, *disabled()) // TODO :\n{\n    // https://github.com/ohhmm/openmind/issues/8\n    // In a farm there are 100 animals consisting of cows,goats,and buffalos.each goat gives 250g of milk,each Buffalo gives 6kg of milk and if each cow gives 4kg of milk.if in total 100 animals produce 40 kg of milk how many animals of each type are present?\n    // https://www.quora.com/Can-this-math-problem-be-solved\n    System s;\n    Variable c,g,b;\n    s   << c+g+b-100\n        << g*250+b*6000+c*4000-40000;\n    \n    // c,g,b are integers, see https://math.stackexchange.com/a/1598552/118612\n    // TODO : try (x mod 1) or cos(2*PI*x) instead\n    using namespace constant;\n    s   << (e^(2*pi*i*c))-1\n        << (e^(2*pi*i*g))-1\n        << (e^(2*pi*i*b))-1\n    ;\n    auto _ = s.Solve(c);\n//    auto cc = s.SolveSingleInteger(c);\n//    auto gc = s.SolveSingleInteger(g);\n//    auto bc = s.SolveSingleInteger(b);\n//    BOOST_TEST(values);\n}\n\nBOOST_AUTO_TEST_CASE(hello_sudoku_world\n                     ,*disabled()\n                    )\n{\n    constexpr unsigned Sz = 9;\n    int data[Sz][Sz] = {\n        {0, 9, 8, 0, 4, 0, 0, 0, 0},\n        {4, 2, 0, 0, 9, 0, 0, 8, 0},\n        {0, 0, 0, 3, 0, 1, 0, 0, 0},\n        {6, 3, 9, 0, 0, 8, 7, 0, 0},\n        {2, 0, 4, 9, 0, 7, 3, 0, 8},\n        {0, 0, 7, 5, 0, 0, 9, 2, 6},\n        {0, 0, 0, 4, 0, 3, 0, 0, 0},\n        {0, 6, 0, 0, 1, 0, 0, 4, 9},\n        {0, 0, 0, 0, 5, 0, 8, 3, 0}\n    };\n    Variable value[Sz][Sz];\n    \n    auto f = 1*2*3*4*5*6*7*8*9;\n    System world;\n    for (auto x=Sz; x--;) {\n        Valuable sumx, sumy, mulx(1), muly(1);\n        for (auto y=Sz; y--; ) {\n            sumx += value[x][y];\n            sumy += value[y][x];\n            mulx *= value[x][y];\n            muly *= value[y][x];\n            if (data[x][y]) {\n                world << value[x][y].Equals(data[x][y]);\n            }\n        }\n        world << sumx.Equals(45) << sumy.Equals(45)\n            << mulx.Equals(f) << muly.Equals(f);\n    }\n\n    for (auto x=Sz; x--;) {\n        for (auto y=Sz; y--; ) {\n            auto& i = value[x][y];\n            auto s = world.Solve(i);\n            if (s.size()!=1) {\n                IMPLEMENT\n            }else{\n                std::cout << *s.begin() << ' ';\n            }\n        }\n        std::cout << std::endl;\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Sudoku_simplest_test\n                     ,*disabled()\n                     ) // solve sudoku through a system of equations though\n{\n    Valuable s;\n    Variable x,y,v;\n    constexpr unsigned Sz = 9;\n    int data[Sz][Sz] = {\n        {0, 9, 8, 0, 4, 0, 0, 0, 0},\n        {4, 2, 0, 0, 9, 0, 0, 8, 0},\n        {0, 0, 0, 3, 0, 1, 0, 0, 0},\n        {6, 3, 9, 0, 0, 8, 7, 0, 0},\n        {2, 0, 4, 9, 0, 7, 3, 0, 8},\n        {0, 0, 7, 5, 0, 0, 9, 2, 6},\n        {0, 0, 0, 4, 0, 3, 0, 0, 0},\n        {0, 6, 0, 0, 1, 0, 0, 4, 9},\n        {0, 0, 0, 0, 5, 0, 8, 3, 0}\n    };\n    Variable value[Sz][Sz];\n    \n    Valuable::optimizations = {};\n    \n    auto at = [&](const Valuable& xx, const Valuable& yy, const Valuable& vv){\n        return x.Equals(xx).LogicAnd(y.Equals(yy)).LogicAnd(v.Equals(vv));\n    };\n    \n    // define known data\n    for(auto rowIdx = Sz; rowIdx--;){\n        for(auto colIdx = Sz; colIdx--;){\n            auto& i = data[rowIdx][colIdx];\n            if(i)\n                s += at(colIdx,rowIdx,i).sq();\n        }\n    }\n    \n    // define the universe\n    // for simplicity check only row/col/square sum equalities to 45\n    for(int xx=0; xx<=8; ++xx){\n        auto sumInRow = -45_v;\n        auto sumInCol = -45_v;\n        auto sumInSq = -45_v;\n        for(int yy=0; yy<=8; ++yy){\n//            if (data[yy][xx]) {\n//                <#statements#>\n//            }\n//            auto a = at(xx,yy,value)(value);\n            sumInRow += at(xx,yy,value[xx][yy])(value[xx][yy]);\n            sumInCol += at(yy,xx,value[xx][yy])(value[xx][yy]);\n            auto sqn = xx;\n            auto sqx = sqn%3;\n            auto sqy = (sqn - sqx) / 3;\n            auto insqn = yy;\n            auto insqx = insqn % 3;\n            auto insqy = (insqn - insqx) / 3;\n            auto sqxx = sqx*3+insqx;\n            auto sqyy = sqy*3+insqy;\n            sumInSq += at(sqxx,sqyy,value[sqxx][sqyy])(value[sqxx][sqyy]);\n        }\n        s += sumInRow ^ 2;\n        s += sumInCol ^ 2;\n        s += sumInSq ^ 2;\n    }\n    \n//    Valuable::optimizations = true;\n//    std::cout << measure<>::execution([&](){\n//        s.optimize();\n//    }) << std::endl;\n//    Valuable::optimizations = {};\n\n    //    std::atomic<int> MaxTasks = boost::thread::hardware_concurrency();\n    std::deque<std::future<void>> tasks;\n    //    auto ChooseNextTask = [&tasks](){\n    //\n    //    };\n    //    auto AddPoolTask = [](std::function<\n    // solving\n    auto sysMutex = std::make_shared<boost::shared_mutex>();\n    for(auto rowIdx = Sz; rowIdx--;){\n        for(auto colIdx = Sz; colIdx--;){\n            auto& i = data[rowIdx][colIdx];\n            if(!i){\n                auto co = s;\n                auto wasopt = Valuable::optimizations;\n                Valuable::optimizations = true;\n                co.eval({{x, colIdx},{y, rowIdx}});\n                std::cout << co.str() << std::endl;\n                co.optimize();\n                Valuable::optimizations = wasopt;\n                auto is = co.IntSolutions(v);\n                if(is.size()==1 && is.begin()->IsInt()){\n                    i = static_cast<int>(*is.begin());\n                    s += at(colIdx, rowIdx, i);\n                } else {\n                    IMPLEMENT\n                }\n//                tasks.push_back(\n//                                std::async([colIdx, rowIdx, sysMutex,\n//                                            &s, &at, &data](){\n//                    Variable find;\n//                    sysMutex->lock_shared();\n//                    decltype(s) localSystem = s;\n//                    sysMutex->unlock_shared();\n//                    localSystem << at(colIdx,rowIdx, find);\n//                    auto solutions = localSystem.Solve(find);\n//                    if (solutions.size()) {\n//                        if (solutions.size()==1) {\n//                            auto solution = *solutions.begin();\n//                            if (!solution.IsInt()) {\n//                                IMPLEMENT\n//                            }\n//                            else\n//                            {\n//                                data[rowIdx][colIdx] = static_cast<int>(solution);\n//                                auto item = at(colIdx,rowIdx,solution);\n//                                sysMutex->lock();\n//                                s << item;\n//                                sysMutex->unlock();\n//                            }\n//                        }\n//                        else\n//                        {\n//                            // intersect into possible solutions array for this x,y\n//                            auto values = 1_v;\n//                            for(auto& solution: solutions){\n//                                values.logic_or(at(colIdx,rowIdx,solution));\n//                            }\n//                            sysMutex->lock();\n//                            s<<values;\n//                            sysMutex->unlock();\n//                        }\n//                    }\n//                }));\n            }\n        }\n    }\n    do {\n        tasks.pop_front();\n    } while (tasks.size());\n    \n    ofstream o(TEST_SRC_DIR\"sudoku.txt\", fstream::out);\n    for(auto rowIdx = Sz; rowIdx--;){\n        for(auto colIdx = Sz; colIdx--;){\n            auto& i = data[colIdx][rowIdx];\n            BOOST_TEST(i != 0);\n            o << setw(2) << i;\n        }\n        o << endl;\n    }\n    o.close();\n}\n\nBOOST_AUTO_TEST_CASE(Sudoku_system_test\n                     ,*disabled()\n) // solve sudoku through a system of equations though\n{\n    System s;\n    Variable x,y,v;\n    constexpr unsigned Sz = 9;\n    int data[Sz][Sz] = {\n        {0, 9, 8, 0, 4, 0, 0, 0, 0},\n        {4, 2, 0, 0, 9, 0, 0, 8, 0},\n        {0, 0, 0, 3, 0, 1, 0, 0, 0},\n        {6, 3, 9, 0, 0, 8, 7, 0, 0},\n        {2, 0, 4, 9, 0, 7, 3, 0, 8},\n        {0, 0, 7, 5, 0, 0, 9, 2, 6},\n        {0, 0, 0, 4, 0, 3, 0, 0, 0},\n        {0, 6, 0, 0, 1, 0, 0, 4, 9},\n        {0, 0, 0, 0, 5, 0, 8, 3, 0}\n    };\n    \n    // at\n    auto at = [&](auto& xx, auto& yy, auto& vv){\n        return x.Equals(xx).LogicAnd(y.Equals(yy)).LogicAnd(v.Equals(vv));\n    };\n    \n    // define known data\n    for(auto rowIdx = Sz; rowIdx--;){\n        for(auto colIdx = Sz; colIdx--;){\n            auto& i = data[rowIdx][colIdx];\n            if(i)\n                s << at(colIdx,rowIdx,i);\n        }\n    }\n    \n    // define the universe\n    // for simplicity check only row/col/square sum equalities to 45\n    Variable value;\n    for(int xx=0; xx<=8; ++xx){\n        auto sumInRow = -45_v;\n        auto sumInCol = -45_v;\n        auto sumInSq = -45_v;\n        for(int yy=0; yy<=8; ++yy){\n            //            sumInRow += at(xx,yy,value)(value);\n            //            sumInCol += at(yy,xx,value)(value);\n            auto sqn = xx;\n            auto sqx = sqn%3;\n            auto sqy = (sqn - sqx) / 3;\n            auto insqn = yy;\n            auto insqx = insqn % 3;\n            auto insqy = (insqn - insqx) / 3;\n            //            sumInSq += at(sqx*3+insqx,sqy*3+insqy,value)(value);\n        }\n        s << sumInRow << sumInCol << sumInSq;\n    }\n    \n    //    std::atomic<int> MaxTasks = boost::thread::hardware_concurrency();\n    std::deque<std::future<void>> tasks;\n    //    auto ChooseNextTask = [&tasks](){\n    //\n    //    };\n    //    auto AddPoolTask = [](std::function<\n    // solving\n    auto sysMutex = std::make_shared<boost::shared_mutex>();\n    for(auto rowIdx = Sz; rowIdx--;){\n        for(auto colIdx = Sz; colIdx--;){\n            auto& i = data[rowIdx][colIdx];\n            if(!i){\n                tasks.push_back(\n                                std::async([colIdx, rowIdx, sysMutex,\n                                            &s, &at, &data](){\n                    Variable find;\n                    sysMutex->lock_shared();\n                    decltype(s) localSystem = s;\n                    sysMutex->unlock_shared();\n                    localSystem << at(colIdx,rowIdx, find);\n                    auto solutions = localSystem.Solve(find);\n                    if (solutions.size()) {\n                        if (solutions.size()==1) {\n                            auto solution = *solutions.begin();\n                            if (!solution.IsInt()) {\n                                IMPLEMENT\n                            }\n                            else\n                            {\n                                data[rowIdx][colIdx] = static_cast<int>(solution);\n                                auto item = at(colIdx,rowIdx,solution);\n                                sysMutex->lock();\n                                s << item;\n                                sysMutex->unlock();\n                            }\n                        }\n                        else\n                        {\n                            // intersect into possible solutions array for this x,y\n                            auto values = 1_v;\n                            for(auto& solution: solutions){\n                                values.logic_or(at(colIdx,rowIdx,solution));\n                            }\n                            sysMutex->lock();\n                            s<<values;\n                            sysMutex->unlock();\n                        }\n                    }\n                }));\n            }\n        }\n    }\n    do {\n        tasks.pop_front();\n    } while (tasks.size());\n}\n\nBOOST_AUTO_TEST_CASE(Sudoku_test\n                     ,*disabled()\n                     ) // solve sudoku through a system of equations though\n{\n    System s;\n    Variable x,y,v;\n    std::array<std::array<int, 9>, 9> data {{\n        {0, 9, 8, 0, 4, 0, 0, 0, 0},\n        {4, 2, 0, 0, 9, 0, 0, 8, 0},\n        {0, 0, 0, 3, 0, 1, 0, 0, 0},\n        {6, 3, 9, 0, 0, 8, 7, 0, 0},\n        {2, 0, 4, 9, 0, 7, 3, 0, 8},\n        {0, 0, 7, 5, 0, 0, 9, 2, 6},\n        {0, 0, 0, 4, 0, 3, 0, 0, 0},\n        {0, 6, 0, 0, 1, 0, 0, 4, 9},\n        {0, 0, 0, 0, 5, 0, 8, 3, 0}\n    }};\n\n    // at\n    auto at = [&](auto& xx, auto& yy, auto& vv){\n        return x.Equals(xx).LogicAnd(y.Equals(yy)).LogicAnd(v.Equals(vv));\n    };\n\n    // define known data\n    for(auto rowIdx = data.size(); rowIdx--;){\n        for(auto colIdx = data[rowIdx].size(); colIdx--;){\n            auto& i = data[rowIdx][colIdx];\n            if(i)\n                s << at(colIdx,rowIdx,i);\n        }\n    }\n\n    // define possible values\n    auto abet = [](const Variable& x) {\n        auto v = 1_v;\n        for(int i=1; i<10; ++i){\n            v.logic_or(x.Equals(i));\n        }\n        return v;\n    };\n\n    // define the universe\n     // each item\n    for(int xx=0; xx<=8; ++xx){\n        for(int yy=0; yy<=8; ++yy){\n            for(int val=0; val<=8; ++val)\n            {\n                auto valsExceptVal = abet(v)/v.Equals(val);\n                auto valAt = at(x,y,val);\n\n                // inequality in row\n                for(auto leastCorowers = xx + 1; leastCorowers <= 8; ++leastCorowers){\n                    auto siblingSameVal = at(leastCorowers,y,val);\n                    auto siblingExceptVal = 1_v;\n                    for(int exceptVal = 0; exceptVal<=8; ++exceptVal){\n                        if(exceptVal!=val)\n                            siblingExceptVal.logic_or(at(leastCorowers,y,exceptVal));\n                    }\n                    s << valAt.Ifz(siblingExceptVal,siblingExceptVal.LogicOr(siblingSameVal));\n                }\n\n                // inequality in column\n                for(auto leastCocolumners = yy + 1; leastCocolumners <= 8; ++leastCocolumners){\n                    auto siblingSameVal = at(leastCocolumners,y,val);\n                    auto siblingExceptVal = 1_v;\n                    for(int exceptVal = 0; exceptVal<=8; ++exceptVal){\n                        if(exceptVal!=val)\n                            siblingExceptVal.logic_or(at(leastCocolumners,y,exceptVal));\n                    }\n                    s << valAt.Ifz(siblingExceptVal,siblingExceptVal.LogicOr(siblingSameVal));\n                }\n\n                // inequality in square\n                auto sqxStart = xx-(xx%3);\n                for(int sqx = sqxStart; sqx < sqxStart+3; ++sqx){\n                    auto sqyStart = yy-(yy%3);\n                    for(int sqy = sqyStart; sqy < sqyStart+3; ++sqy){\n                        if(!(sqx==xx && sqy==yy)){\n                            auto siblingSameVal = at(sqx,sqy,val);\n                            auto siblingExceptVal = 1_v;\n                            for(int exceptVal = 0; exceptVal<=8; ++exceptVal){\n                                if(exceptVal!=val)\n                                    siblingExceptVal.logic_or(at(sqx,sqy,exceptVal));\n                            }\n                            s << valAt.Ifz(siblingExceptVal,siblingExceptVal.LogicOr(siblingSameVal));\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // x,y,v are integers, see https://math.stackexchange.com/a/1598552/118612\n    //    using namespace constant;\n    //    s   << (e^(2*pi*i*x))-1\n    //        << (e^(2*pi*i*y))-1\n    //        << (e^(2*pi*i*v))-1\n    //    ;\n    \n    // inequality in squares\n// todo: try general using coordinatesMultiplicityTo3\n//    Variable gaugeX, gaugeY;\n//    auto coordinatesMultiplicityTo3 = logicAnd(gaugeX % 3, gaugeY % 3);\n//    auto notEqual = [](auto& e1, auto&e2){\n//IMPLEMENT\n//    };\n//    s << logicAnd(coordinatesMultiplicityTo3,\n//            logicOr({\n//                logicAnd(equality(gaugeX,x), equality(gaugeY,y))\n//            })\n//            )\n     // inequality in squares\n//first attept\n//    for(int sqareStartX = 0; sqareStartX < 9; sqareStartX += 3){\n//        for(int sqareStartY = 0; sqareStartY < 9; sqareStartY += 3){\n//            for(int i=1; i<=9; ++i) {\n//                auto valsExcept = [&](auto& va, auto& exceptValue){\n//                    Valuable allItems=1_v;\n//                    for(int xi = sqareStartX; xi < sqareStartX+3; ++xi){\n//                        for(int yj = sqareStartY; yj < sqareStartY+3; ++yj){\n//                            for(int ii = 1; ii<=9; ++ii)\n//                            {\n//                                if(ii!=i){\n//                                    allItems = allItems.LogicOr(at(xi,yj,));\n//                                } else {\n//\n//                                }\n//                            }\n//                            auto item = equals(x,xi)\n//                                    .LogicAnd(equals(y,yj))\n//                                    .LogicAnd(equals(v,i));\n//\n//                        }\n//                    }\n//                    return abet(va) / va.Equals(exceptValue);\n//                };\n//                auto valsExceptI = valsExcept(v,i);\n//                s << (x.Equals(sqareStartX).LogicAnd(y.Equals(sqareStartY)))\n//                    .LogicAnd();\n//            }\n//        }\n//    }\n\n    // solving\n    for(auto rowIdx = data.size(); rowIdx--;){\n        for(auto colIdx = data[rowIdx].size(); colIdx--;){\n            auto& i = data[rowIdx][colIdx];\n            if(!i){\n                auto sysMutex = std::make_shared<boost::shared_mutex>();\n                std::function<void()> addThisTask = [colIdx,rowIdx,sysMutex,&s,&at,addThisTask](){\n                    std::async([colIdx,rowIdx, sysMutex, &s, &at, addThisTask](){\n                        Variable find;\n                        sysMutex->lock_shared();\n                        decltype(s) localSystem = s;\n                        sysMutex->unlock_shared();\n                        localSystem << at(colIdx,rowIdx, find);\n                        auto solutions = localSystem.Solve(find);\n                        if (solutions.size()) {\n                            if (solutions.size()==1) {\n                                auto solution = *solutions.begin();\n                                if (!solution.IsInt()) {\n                                    IMPLEMENT\n                                }\n                                else\n                                {\n                                    auto item = at(colIdx,rowIdx,solution);\n                                    sysMutex->lock();\n                                    s << item;\n                                    sysMutex->unlock();\n                                }\n                            }\n                            else\n                            {\n                                // todo : intersect into possible solutions array for this x,y\n                                for(auto& solution: solutions){\n                                    \n                                }\n                            }\n                        }\n                    });\n                };\n            }\n        }\n    }\n\n\n//    auto _ = s.Solve(c);\n//    auto cc = s.SolveSingleInteger(c);\n//    auto gc = s.SolveSingleInteger(g);\n//    auto bc = s.SolveSingleInteger(b);\n//    BOOST_TEST(values);\n}\n\nBOOST_AUTO_TEST_CASE(kaggle_test, *disabled())\n{\n    using namespace boost;\n    using namespace boost::executors;\n    basic_thread_pool tp;\n\n    //TypedVarHost<std::string> vh;\n\n    std::atomic<int> cntLines = 0;\n    std::map<int, std::string> ids;\n    std::string line;\n    {\n    ifstream in(TEST_SRC_DIR\"train.csv\", ifstream::in);\n    if (!in.is_open())\n    {\n        cout << \"cannot open file\\n\";\n        return;\n    }\n\n    std::vector<Variable> v;\n    System sys;\n    std::mutex systemMutex;\n    using namespace boost;\n\n    if (!in.eof()) {\n        in >> line; // headers\n        tokenizer<escaped_list_separator<char> > tk(\n            line, escaped_list_separator<char>('\\\\', ',', '\\\"'));\n        for (tokenizer<escaped_list_separator<char> >::iterator i(tk.begin());\n            i != tk.end(); ++i)\n            v.push_back(Variable());\n\n#ifdef _WIN32\n        EnableMenuItem(\n            GetSystemMenu(GetConsoleWindow(), {}),\n            SC_CLOSE,\n            MF_GRAYED);\n#endif // _WIN32\n    }\n\n    if (!in.eof())\n        ++cntLines;\n\n    int skip = 0;\n    {\n        ifstream system(TEST_SRC_DIR\"sys.csv\", fstream::in);\n        if (system.is_open())\n        {\n            while (!system.eof()) {\n                constexpr auto Sz = 1 << 18;\n                char s[Sz];\n                system.getline(s, Sz);\n                line = s;\n                if (!line.empty())\n                {\n                    ++skip;\n                    auto c = memchr(s, ';', Sz);\n                    *(char*)c = 0;\n                    ids[skip] = s;\n                }\n            }\n            system.close();\n        }\n        else\n        {\n            cout << \"cannot open file, creating new\";\n            ofstream(TEST_SRC_DIR\"sys.csv\", fstream::out).close();\n            return;\n        }\n    }\n\n    std::atomic<int> completedLines = skip;\n    while (!in.eof()) {\n        in >> line;\n        if (!in.eof())\n            ++cntLines;\n        if (completedLines + 1 >= cntLines)\n            continue;\n        tp.submit([&, line]()\n        {\n            auto sum = std::make_shared<Sum>();\n            sum->SetView(Valuable::View::Equation);\n            auto sumMutex = std::make_shared<std::mutex>();\n\n            auto cntWords = std::make_shared<std::atomic<int>>(0);\n            tokenizer<escaped_list_separator<char> > tk(\n                line, escaped_list_separator<char>('\\\\', ',', '\\\"'));\n            int vi = 0;\n            for (tokenizer<escaped_list_separator<char> >::iterator i(tk.begin());\n                i != tk.end(); ++i)\n            {\n                tp.submit([&, sum, sumMutex, cntWords, w = *i, vi](){\n                    auto tid = std::this_thread::get_id();\n                    std::cout << tid << \" start \" << vi << std::endl;\n                    const Variable& va = v[vi];\n                    {\n                        Valuable val;\n                        if (vi) {\n                            val = boost::lexical_cast<double>(w);\n                        }\n                        else {\n                            long long l;\n                            std::stringstream ss(w);\n                            ss >> hex >> l;\n                            val = l;\n                        }\n                        val = std::move((va - val).sq());\n\n                        std::lock_guard g(*sumMutex);\n                        sum->Add(val);\n                    }\n                    if (cntWords->fetch_add(1) + 1 == v.size())\n                    {\n                        sum->optimize();\n\n                        {\n                            std::lock_guard g(systemMutex);\n                            sys << *sum;\n                            ofstream system(TEST_SRC_DIR\"sys.csv\", fstream::app);\n                            system << completedLines << ';' << *sum << endl;\n                        }\n                        std::cout << tid << \" line complete \" << completedLines << std::endl;\n                        if (completedLines.fetch_add(1) + 1 == cntLines)\n                        {\n                            // save sys and start processing test lines file\n                            std::cout << tid << \" sys complete \" << std::endl;\n                        }\n                    }\n                    std::cout << tid << \" complete \" << vi << std::endl;\n                });\n                ++vi;\n            }\n        });\n    }\n\n    in.close();\n    }\n    tp.join();\n\n    {\n        ifstream in(TEST_SRC_DIR\"train.csv\", ifstream::in);\n        ifstream system(TEST_SRC_DIR\"sys.csv\", fstream::in);\n        ifstream test(TEST_SRC_DIR\"test.csv\", ifstream::in);\n\n        if (!in.is_open() || !system.is_open())\n        {\n            cout << \"cannot open file\\n\";\n            return;\n        }\n        auto h = VarHost::make<std::string>();\n        while (!system.eof()) {\n            constexpr auto Sz = 1 << 18;\n            char s[Sz];\n            system.getline(s, Sz);\n            line = std::string(s);\n            if (!line.empty())\n            {\n                std::size_t sc = line.find(';');\n                line = line.substr(sc + 1, line.length() - sc);\n                Valuable v(line, h);\n                BOOST_TEST(v.str() == line);\n            }\n        }\n    }\n\n    tp.join();\n}\n", "meta": {"hexsha": "ed770c7687300edf55c32a182f4daccebb36e466", "size": 26758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/test/08_System.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/08_System.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/08_System.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": 33.6578616352, "max_line_length": 259, "alphanum_fraction": 0.4202107781, "num_tokens": 6846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5120906060105723}}
{"text": "\n// solving A * X = B\n// using driver function gesv()\n\n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <cstddef>\n#include <iostream>\n#include <boost/numeric/bindings/lapack/driver/gesv.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\n#include <boost/numeric/ublas/io.hpp> \n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\n#ifndef F_ROW_MAJOR\ntypedef ublas::matrix<double, ublas::column_major> m_t;\n#else\ntypedef ublas::matrix<double, ublas::row_major> m_t;\n#endif\n\nint main() {\n\n  cout << endl; \n  size_t n = 3, nrhs = 1; \n\n  m_t a (n, n);   // system matrix \n  a(0,0) = 1.; a(0,1) = 1.; a(0,2) = 1.;\n  a(1,0) = 2.; a(1,1) = 3.; a(1,2) = 1.;\n  a(2,0) = 1.; a(2,1) = -1.; a(2,2) = -1.;\n\n// see leading comments for `gesv()' in clapack.hpp\n#ifndef F_ROW_MAJOR\n  m_t b (n, nrhs);  // right-hand side matrix\n  b(0,0) = 4.; b(1,0) = 9.; b(2,0) = -2.; \n#else\n  m_t b (nrhs, n);  \n  b(0,0) = 4.; b(0,1) = 9.; b(0,2) = -2.; \n#endif \n\n  cout << \"A: \" << a << endl; \n  cout << \"B: \" << b << endl; \n\n  std::vector< int > pivot( bindings::size1( a ) );\n  lapack::gesv (a, pivot, b);  \n  cout << \"X: \" << b << endl; \n\n  cout << endl; \n}\n\n", "meta": {"hexsha": "0457cd4fde7fda403f7e7b486c88ec8ca4ce881f", "size": 1339, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_gesv3.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/atlas/ublas_gesv3.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/atlas/ublas_gesv3.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": 23.4912280702, "max_line_length": 56, "alphanum_fraction": 0.6034353996, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5120906035660501}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nclass GaussQuadrature\n{\npublic:\n\n    using Integrand = std::function<double(Eigen::Vector3d const&)>;\n    using Domain = Eigen::AlignedBox3d;\n\n    static double integrate(Integrand integrand, Domain const& domain, unsigned int p);\n};\n\n\n\n", "meta": {"hexsha": "784830dde1db4872af3b6241ec85db76e1dfe1ed", "size": 275, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmd/generate_density_map/gauss_quadrature.hpp", "max_stars_repo_name": "digitalillusions/Discregrid", "max_stars_repo_head_hexsha": "af5880ecfa62c736a25e23a607bd8bd51d833fe2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 214.0, "max_stars_repo_stars_event_min_datetime": "2017-11-10T11:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T16:24:01.000Z", "max_issues_repo_path": "cmd/generate_density_map/gauss_quadrature.hpp", "max_issues_repo_name": "digitalillusions/Discregrid", "max_issues_repo_head_hexsha": "af5880ecfa62c736a25e23a607bd8bd51d833fe2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2018-02-20T07:53:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T14:03:11.000Z", "max_forks_repo_path": "cmd/generate_density_map/gauss_quadrature.hpp", "max_forks_repo_name": "digitalillusions/Discregrid", "max_forks_repo_head_hexsha": "af5880ecfa62c736a25e23a607bd8bd51d833fe2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47.0, "max_forks_repo_forks_event_min_datetime": "2017-11-19T05:42:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T11:55:09.000Z", "avg_line_length": 16.1764705882, "max_line_length": 87, "alphanum_fraction": 0.72, "num_tokens": 68, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5120906010622571}}
{"text": "//  (C) Copyright Nick Thompson 2019.\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#ifndef BOOST_MATH_STATISTICS_LJUNG_BOX_HPP\r\n#define BOOST_MATH_STATISTICS_LJUNG_BOX_HPP\r\n\r\n#include <cmath>\r\n#include <iterator>\r\n#include <utility>\r\n#include <boost/math/distributions/chi_squared.hpp>\r\n#include <boost/math/statistics/univariate_statistics.hpp>\r\n\r\nnamespace boost::math::statistics {\r\n\r\ntemplate<class RandomAccessIterator>\r\nauto ljung_box(RandomAccessIterator begin, RandomAccessIterator end, int64_t lags = -1, int64_t fit_dof = 0) {\r\n    using Real = typename std::iterator_traits<RandomAccessIterator>::value_type;\r\n    int64_t n = std::distance(begin, end);\r\n    if (lags >= n) {\r\n      throw std::domain_error(\"Number of lags must be < number of elements in array.\");\r\n    }\r\n\r\n    if (lags == -1) {\r\n      // This is the same default as Mathematica; it seems sensible enough . . .\r\n      lags = static_cast<int64_t>(std::ceil(std::log(Real(n))));\r\n    }\r\n\r\n    if (lags <= 0) {\r\n      throw std::domain_error(\"Must have at least one lag.\");\r\n    }\r\n\r\n    auto mu = boost::math::statistics::mean(begin, end);\r\n\r\n    std::vector<Real> r(lags + 1, Real(0));\r\n    for (size_t i = 0; i < r.size(); ++i) {\r\n      for (auto it = begin + i; it != end; ++it) {\r\n        Real ak = *(it) - mu;\r\n        Real akml = *(it-i) - mu;\r\n        r[i] += ak*akml;\r\n      }\r\n    }\r\n\r\n    Real Q = 0;\r\n\r\n    for (size_t k = 1; k < r.size(); ++k) {\r\n      Q += r[k]*r[k]/(r[0]*r[0]*(n-k));\r\n    }\r\n    Q *= n*(n+2);\r\n\r\n    typedef boost::math::policies::policy<\r\n          boost::math::policies::promote_float<false>,\r\n          boost::math::policies::promote_double<false> >\r\n          no_promote_policy;\r\n\r\n    auto chi = boost::math::chi_squared_distribution<Real, no_promote_policy>(Real(lags - fit_dof));\r\n\r\n    Real pvalue = 1 - boost::math::cdf(chi, Q);\r\n    return std::make_pair(Q, pvalue);\r\n}\r\n\r\n\r\ntemplate<class RandomAccessContainer>\r\nauto ljung_box(RandomAccessContainer const & v, int64_t lags = -1, int64_t fit_dof = 0) {\r\n    return ljung_box(v.begin(), v.end(), lags, fit_dof);\r\n}\r\n\r\n}\r\n#endif\r\n", "meta": {"hexsha": "0735e467187be2a584eff441f9d64350de120239", "size": 2249, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/statistics/ljung_box.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/math/statistics/ljung_box.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/math/statistics/ljung_box.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T06:24:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:55:07.000Z", "avg_line_length": 31.676056338, "max_line_length": 111, "alphanum_fraction": 0.6238328146, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5120906010622571}}
{"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\nnamespace fluid {\nnamespace algorithm {\n\nclass RatioMask\n{\n\n  using ArrayXXd = Eigen::ArrayXXd;\n\npublic:\n  void init(RealMatrixView denominator)\n  {\n    using namespace _impl;\n    using namespace Eigen;\n    mMultiplier = (1 / asEigen<Array>(denominator).max(epsilon));\n  }\n\n  void process(const ComplexMatrixView& mixture, RealMatrixView targetMag,\n               index exponent, ComplexMatrixView result)\n  {\n    using namespace _impl;\n    using namespace Eigen;\n    assert(mixture.cols() == targetMag.cols());\n    assert(mixture.rows() == targetMag.rows());\n    ArrayXXcd tmp =\n        asEigen<Array>(mixture) *\n        (asEigen<Array>(targetMag).pow(exponent) * mMultiplier.pow(exponent))\n            .min(1.0);\n    result = asFluid(tmp);\n  }\n\nprivate:\n  ArrayXXd mMultiplier;\n};\n\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "b82912175e1d0dc83ab6047f41d3d8196cfe06cc", "size": 1431, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/RatioMask.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/RatioMask.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/RatioMask.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.0181818182, "max_line_length": 77, "alphanum_fraction": 0.7113906359, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616712, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.512010056383311}}
{"text": "#include <iostream>\n#include <armadillo>\n\n#include \"utils/ImageUtils.h\"\n#include \"utils/Benchmark.h\"\n#include \"models/neural-network-model/discriminator/ArtDiscriminatorModel.h\"\n#include \"models/neural-network-model/generator/ArtGeneratorModel.h\"\n\n#define LOG(x) std::cout << x << std::endl;\n\n#define IMAGE_SIZE 64\n#define INPUT_LENGTH IMAGE_SIZE * IMAGE_SIZE * 3\n#define GENERATOR_HIDDEN_LAYER_NODE_COUNT 128\n#define DISCRIMINATOR_HIDDEN_LAYER_NODE_COUNT 64\n\nusing namespace arma;\n\nvoid testDiscriminator()\n{\n\tArtDiscriminatorModel* model = new ArtDiscriminatorModel(INPUT_LENGTH);\n\tmodel->addHiddenLayer(DISCRIMINATOR_HIDDEN_LAYER_NODE_COUNT);\n\tmodel->addHiddenLayer(DISCRIMINATOR_HIDDEN_LAYER_NODE_COUNT);\n\tmodel->init();\n\n\tArtDiscriminatorModelResult* result = model->discriminateArt(randu<vec>(INPUT_LENGTH));\n\n\tdelete result;\n\tdelete model;\n}\n\nvoid testGenerator()\n{\n\tArtGeneratorModel* model = new ArtGeneratorModel(INPUT_LENGTH);\n\tmodel->addHiddenLayer(GENERATOR_HIDDEN_LAYER_NODE_COUNT);\n\tmodel->addHiddenLayer(GENERATOR_HIDDEN_LAYER_NODE_COUNT);\n\tmodel->init();\n\n\tvec result = model->calculate(randu<vec>(INPUT_LENGTH));\n\n\tdelete model;\n}\n\nint main()\n{\n\tBenchmark::run(testDiscriminator, 5, \"Discriminator Test\");\n\tBenchmark::run(testGenerator, 5, \"Generator Test\");\n\n\tsystem(\"PAUSE\");\n\n\treturn 0;\n}\n", "meta": {"hexsha": "b0df80d6c14f1547d12c77b363087e6872b16108", "size": 1310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "generative-adversarial-network/src/Application.cpp", "max_stars_repo_name": "tautvydass/vu-coursework", "max_stars_repo_head_hexsha": "604e8e38b14849b832782d45f7321cc8b2275b5f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T09:49:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-16T09:49:35.000Z", "max_issues_repo_path": "generative-adversarial-network/src/Application.cpp", "max_issues_repo_name": "tautvydass/vu-coursework", "max_issues_repo_head_hexsha": "604e8e38b14849b832782d45f7321cc8b2275b5f", "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": "generative-adversarial-network/src/Application.cpp", "max_forks_repo_name": "tautvydass/vu-coursework", "max_forks_repo_head_hexsha": "604e8e38b14849b832782d45f7321cc8b2275b5f", "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.1923076923, "max_line_length": 88, "alphanum_fraction": 0.7908396947, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5119231902530567}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/bindings/lower.hpp>\n#include <boost/numeric/bindings/upper.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/blas/level3.hpp>\n#include <boost/numeric/bindings/conj.hpp>\n#include \"print.hpp\"\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef std::complex<double> complex;\n    typedef ublas::matrix<complex, ublas::column_major> matrix;\n    typedef matrix::size_type size_type;\n    rand_normal<complex>::reset();\n    size_type n=8;\n    matrix A(n, n), B(n, n), C(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i) {\n\tA(i, j)=rand_normal<complex>::get();\n\tB(i, j)=rand_normal<complex>::get();\n      }\n    for (size_type j=0; j<n; ++j) {\n      for (size_type i=0; i<j; ++i) {\n\tC(i, j)=rand_normal<complex>::get();\n\tC(j, i)=std::conj(C(i, j));\n      }\n      C(j, j)=rand_normal<complex>::get().real();\n    }\n    complex alpha(rand_normal<complex>::get());\n    double beta(rand_normal<complex>::get().real());\n    {\n      matrix C1(alpha*ublas::prod(A, ublas::trans(ublas::conj(B)))+\n\t\tstd::conj(alpha)*ublas::prod(B, ublas::trans(ublas::conj(A)))+\n\t\tbeta*C);\n      for (size_type j=0; j<n; ++j)\n\tfor (size_type i=j+1; i<n; ++i)\n\t  C1(i, j)=C(i, j);\n      matrix C2(C);\n      blas::her2k(alpha, A, B, beta, blas::upper(C2));\n      std::cout << \"testing boost::ublas containers\\n\"\n\t\t<< \"using ublas (A right htrans, C upper):\\n\" << print_mat(C1) << '\\n'\n\t\t<< \"using blas (A right htrans, C upper):\\n\" << print_mat(C2) << '\\n'\n\t\t<< '\\n';\n    }\n    {\n      matrix C1(alpha*ublas::prod(A, ublas::trans(ublas::conj(B)))+\n\t\tstd::conj(alpha)*ublas::prod(B, ublas::trans(ublas::conj(A)))+\n\t\tbeta*C);\n      for (size_type j=0; j<n; ++j)\n    \tfor (size_type i=0; i<j; ++i)\n    \t  C1(i, j)=C(i, j);\n      matrix C2(C);\n      blas::her2k(alpha, A, B, beta, blas::lower(C2));\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (A right htrans, C lower):\\n\" << print_mat(C1) << '\\n'\n    \t\t<< \"using blas (A right htrans, C lower):\\n\" << print_mat(C2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix C1(alpha*ublas::prod(ublas::trans(ublas::conj(A)), B)+\n\t\tstd::conj(alpha)*ublas::prod(ublas::trans(ublas::conj(B)), A)+\n\t\tbeta*C);\n      for (size_type j=0; j<n; ++j)\n    \tfor (size_type i=j+1; i<n; ++i)\n    \t  C1(i, j)=C(i, j);\n      matrix C2(C);\n      blas::her2k(alpha, blas::conj(A), B, beta, blas::upper(C2));\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (A left htrans, C upper):\\n\" << print_mat(C1) << '\\n'\n    \t\t<< \"using blas (A left htrans, C upper):\\n\" << print_mat(C2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      matrix C1(alpha*ublas::prod(ublas::trans(ublas::conj(A)), B)+\n\t\tstd::conj(alpha)*ublas::prod(ublas::trans(ublas::conj(B)), A)+\n\t\tbeta*C);\n      for (size_type j=0; j<n; ++j)\n    \tfor (size_type i=0; i<j; ++i)\n    \t  C1(i, j)=C(i, j);\n      matrix C2(C);\n      blas::her2k(alpha, blas::conj(A), B, beta, blas::lower(C2));\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (A left htrans, C lower):\\n\" << print_mat(C1) << '\\n'\n    \t\t<< \"using blas (A left htrans, C lower):\\n\" << print_mat(C2) << '\\n'\n    \t\t<< '\\n';\n    }\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "6a9f2ffbcdf4c480ba2da165761cf9e3a3544a98", "size": 3436, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/her2k.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/her2k.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/her2k.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.4226804124, "max_line_length": 76, "alphanum_fraction": 0.5742142026, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5119231846663487}}
{"text": "#include \"engine_impl.hpp\"\n#include \"rocket.hpp\"\n\n#include <boost/units/cmath.hpp>\n\nEngineImpl::EngineImpl(Rocket& rocket_, const Body& launch_body_)\n\t: m_body(launch_body_)\n\t, m_rocket(rocket_)\n\t, m_state({Engine::position_t{0, launch_body_.radius + m_rocket.totalLength(), 0},\n\t\t\t   Engine::velocity_t{0}})\n\t, m_initial_position({0, launch_body_.radius, 0})\n{\n}\n\nconst Engine::State& EngineImpl::state() const\n{\n\treturn m_state;\n}\n\nutils::units::time EngineImpl::currentTime() const\n{\n\treturn m_current_time;\n}\n\nutils::units::length EngineImpl::altitude() const\n{\n\tconst utils::units::position_vector relative_pos = m_initial_position - m_state.position;\n\treturn (relative_pos).norm();\n}\n\nutils::units::force EngineImpl::gravityForce() const\n{\n\tusing boost::units::si::cubic_meters;\n\tusing boost::units::si::kilograms;\n\tusing boost::units::si::seconds;\n\tstatic auto G = 6.67384E-11 * cubic_meters / kilograms / seconds / seconds;\n\tconst auto vector = m_state.position; // because center of attracting body on {0, 0, 0} for now\n\treturn G * m_rocket.currentMass() * m_body.mass / vector.norm2();\n}\n\nutils::point3d<utils::units::acceleration> EngineImpl::currentAcceleration() const\n{\n\tconst auto value = (m_rocket.currentThrust() - gravityForce()) / m_rocket.currentMass();\n\treturn {0, value, 0};\n}\n\nvoid EngineImpl::tick(utils::units::time dt)\n{\n\tm_rocket.burn(dt);\n\tif(m_state.position == utils::units::position_vector{0 * boost::units::si::meters})\n\t\treturn;\n\tconst auto acceleration = currentAcceleration();\n\tm_state.velocity += dt * acceleration;\n\tm_state.position += m_state.velocity * dt;\n\tm_current_time += dt;\n}\n", "meta": {"hexsha": "122475ed79d8b6331f3ea51aaa0c9ce21cba88d7", "size": 1621, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/engine_impl.cpp", "max_stars_repo_name": "julienlopez/QRocketLaunchSimulator", "max_stars_repo_head_hexsha": "132e979489b3b84a82c162df0209085d0a30fd8e", "max_stars_repo_licenses": ["MIT"], "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/engine_impl.cpp", "max_issues_repo_name": "julienlopez/QRocketLaunchSimulator", "max_issues_repo_head_hexsha": "132e979489b3b84a82c162df0209085d0a30fd8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-02-19T09:25:15.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-19T14:43:20.000Z", "max_forks_repo_path": "lib/engine_impl.cpp", "max_forks_repo_name": "julienlopez/QRocketLaunchSimulator", "max_forks_repo_head_hexsha": "132e979489b3b84a82c162df0209085d0a30fd8e", "max_forks_repo_licenses": ["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.4385964912, "max_line_length": 96, "alphanum_fraction": 0.729796422, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.5119031516580567}}
{"text": "#pragma once\n#include <cmath>\n#include <limits>\n\n#include <Eigen/Dense>\n\nnamespace pcs {\n\ntemplate <typename Derived>\nEigen::Matrix<typename Eigen::DenseBase<Derived>::Scalar, 3, 1> hsv_to_rgb(\n    const Eigen::DenseBase<Derived>& hsv) {\n  using T = typename Eigen::DenseBase<Derived>::Scalar;\n  T hh, p, q, t, ff;\n  long i;\n  T h = hsv.x();\n  T s = hsv.y();\n  T v = hsv.z();\n\n  Eigen::Matrix<T, 3, 1> rgb;\n\n  if (s == 0) {\n    rgb.x() = std::round(v * 255);\n    rgb.y() = std::round(v * 255);\n    rgb.z() = std::round(v * 255);\n    return rgb;\n  }\n\n  hh = h;\n  if (hh >= 360.0) {\n    hh = 0.f;\n  }\n  hh /= 60.0;\n  i = static_cast<long>(hh);\n  ff = hh - i;\n  p = v * (1.0 - s);\n  q = v * (1.0 - (s * ff));\n  t = v * (1.0 - (s * (1.0 - ff)));\n\n  switch (i) {\n    case 0:\n      rgb.x() = std::round(v * 255);\n      rgb.y() = std::round(t * 255);\n      rgb.z() = std::round(p * 255);\n      break;\n    case 1:\n      rgb.x() = std::round(q * 255);\n      rgb.y() = std::round(v * 255);\n      rgb.z() = std::round(p * 255);\n      break;\n    case 2:\n      rgb.x() = std::round(p * 255);\n      rgb.y() = std::round(v * 255);\n      rgb.z() = std::round(t * 255);\n      break;\n    case 3:\n      rgb.x() = std::round(p * 255);\n      rgb.y() = std::round(q * 255);\n      rgb.z() = std::round(v * 255);\n      break;\n    case 4:\n      rgb.x() = std::round(t * 255);\n      rgb.y() = std::round(p * 255);\n      rgb.z() = std::round(v * 255);\n      break;\n    case 5:\n    default:\n      rgb.x() = std::round(v * 255);\n      rgb.y() = std::round(p * 255);\n      rgb.z() = std::round(q * 255);\n      break;\n  }\n\n  return rgb;\n}\n\ntemplate <typename Derived>\nEigen::Matrix<typename Eigen::DenseBase<Derived>::Scalar, 3, 1> rgb_to_hsv(\n    const Eigen::DenseBase<Derived>& rgb) {\n  using T = typename Eigen::DenseBase<Derived>::Scalar;\n  T r = rgb.x() / 255.0;\n  T g = rgb.y() / 255.0;\n  T b = rgb.z() / 255.0;\n  Eigen::Matrix<T, 3, 1> hsv;\n  T vmin, diff;\n  hsv.z() = vmin = r;\n  if (hsv.z() < g) hsv.z() = g;\n  if (hsv.z() < b) hsv.z() = b;\n  if (vmin > g) vmin = g;\n  if (vmin > b) vmin = b;\n\n  diff = hsv.z() - vmin;\n  hsv.y() = diff / (std::abs(hsv.z()) + std::numeric_limits<T>::epsilon());\n  diff = 60.0 / (diff + std::numeric_limits<T>::epsilon());\n  if (hsv.z() == r) {\n    hsv.x() = (g - b) * diff;\n  } else if (hsv.z() == g) {\n    hsv.x() = (b - r) * diff + 120.0;\n  } else {\n    hsv.x() = (r - g) * diff + 240.0;\n  }\n\n  if (hsv.x() < 0) {\n    hsv.x() += 360.0;\n  }\n\n  return hsv;\n}\n\n}  // namespace pcs\n", "meta": {"hexsha": "daf549a8095b4ddbb03ea39de2ac1d0d2c97b09f", "size": 2492, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rgb_to_hsv.hpp", "max_stars_repo_name": "aleksrgarkusha/pcs", "max_stars_repo_head_hexsha": "597a2aa020a60473307ef09a8939db1d93657f8a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-26T02:17:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T13:20:33.000Z", "max_issues_repo_path": "src/rgb_to_hsv.hpp", "max_issues_repo_name": "aleksrgarkusha/pcs", "max_issues_repo_head_hexsha": "597a2aa020a60473307ef09a8939db1d93657f8a", "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/rgb_to_hsv.hpp", "max_forks_repo_name": "aleksrgarkusha/pcs", "max_forks_repo_head_hexsha": "597a2aa020a60473307ef09a8939db1d93657f8a", "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.6545454545, "max_line_length": 75, "alphanum_fraction": 0.4855537721, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.5119031516580567}}
{"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_LOG_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_LOG_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-exponential\n    This function object returns the natural logarithm of its argument.\n\n    @par Header <boost/simd/function/log.hpp>\n\n    @see log10, log2, log1p\n\n    @par Note:\n\n    - log(x) return Nan for negative entries (peculiarly Mzero\n    for floating numbers).\n\n    @par Decorators\n\n      - std_ for floating entries calls @c std::log\n\n\n    @par Example:\n\n      @snippet log.cpp log\n\n    @par Possible output:\n\n      @snippet log.txt log\n\n  **/\n  IEEEValue log(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/log.hpp>\n#include <boost/simd/function/simd/log.hpp>\n\n#endif\n", "meta": {"hexsha": "f4e5cb85780938328826ad0a5d522eb75cb89d63", "size": 1170, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/log.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/function/log.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/function/log.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": 22.0754716981, "max_line_length": 100, "alphanum_fraction": 0.5837606838, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.5119031463672872}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2013 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#ifndef BOOST_GEOMETRY_EXTENSIONS_STRATEGIES_BUFFER_END_ROUND_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_STRATEGIES_BUFFER_END_ROUND_HPP\n\n\n// Buffer strategies\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/strategies/tags.hpp>\n#include <boost/geometry/strategies/side.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n#include <boost/geometry/extensions/strategies/buffer_side.hpp>\n\n\n\nnamespace boost { namespace geometry\n{\n\n\nnamespace strategy { namespace buffer\n{\n\n\ntemplate\n<\n    typename PointIn,\n    typename PointOut\n>\nclass end_round\n{\n    typedef typename strategy::side::services::default_strategy<typename cs_tag<PointIn>::type>::type side;\n    typedef typename coordinate_type<PointOut>::type coordinate_type;\n\n    typedef typename geometry::select_most_precise\n        <\n            typename geometry::select_most_precise\n                <\n                    typename geometry::coordinate_type<PointIn>::type,\n                    typename geometry::coordinate_type<PointOut>::type\n                >::type,\n            double\n        >::type promoted_type;\n\n    int m_steps_per_circle;\n\n    template <typename RangeOut>\n    inline void generate_points(PointIn const& point,\n                promoted_type alpha,\n                promoted_type const& buffer_distance,\n                RangeOut& range_out) const\n    {\n        promoted_type const two = 2.0;\n        promoted_type const two_pi = two * geometry::math::pi<promoted_type>();\n\n        int point_buffer_count = m_steps_per_circle;\n\n        promoted_type const diff = two_pi / promoted_type(point_buffer_count);\n\n        // For half circle: \n        point_buffer_count /= 2;\n        point_buffer_count++;\n\n        for (int i = 0; i < point_buffer_count; i++, alpha -= diff)\n        {\n            typename boost::range_value<RangeOut>::type p;\n            set<0>(p, get<0>(point) + buffer_distance * cos(alpha));\n            set<1>(p, get<1>(point) + buffer_distance * sin(alpha));\n            range_out.push_back(p);\n        }\n    }\n\n    // COPIED FROM OCCUPATION_INFO\n    template <typename T, typename P1, typename P2>\n    static inline T calculate_angle(P1 const& from_point, P2 const& to_point)\n    {\n        typedef P1 vector_type;\n        vector_type v = from_point;\n        geometry::subtract_point(v, to_point);\n        return atan2(geometry::get<1>(v), geometry::get<0>(v));\n    }\n\npublic :\n    inline end_round(int steps_per_circle = 100)\n        : m_steps_per_circle(steps_per_circle)\n    {}\n\n    template <typename RangeOut, typename DistanceStrategy>\n    inline void apply(PointIn const& penultimate_point, \n                PointIn const& perp_left_point,\n                PointIn const& ultimate_point,\n                PointIn const& perp_right_point,\n                buffer_side_selector side,\n                DistanceStrategy const& distance,\n                RangeOut& range_out) const\n    {\n        promoted_type alpha = calculate_angle<promoted_type>(perp_left_point, ultimate_point);\n\n        promoted_type const dist_left = distance.apply(penultimate_point, ultimate_point, buffer_side_left);\n        promoted_type const dist_right = distance.apply(penultimate_point, ultimate_point, buffer_side_right);\n        if (geometry::math::equals(dist_left, dist_right))\n        {\n            generate_points(ultimate_point, alpha, dist_left, range_out);\n        }\n        else\n        {\n            promoted_type const two = 2.0;\n            promoted_type dist_half_diff = (dist_left - dist_right) / two;\n\n            if (side == buffer_side_right)\n            {\n                dist_half_diff = -dist_half_diff;\n            }\n\n            PointIn shifted_point;\n            set<0>(shifted_point, get<0>(ultimate_point) + dist_half_diff * cos(alpha));\n            set<1>(shifted_point, get<1>(ultimate_point) + dist_half_diff * sin(alpha));\n            generate_points(shifted_point, alpha, (dist_left + dist_right) / two, range_out);\n        }\n    }\n\n    static inline piece_type get_piece_type()\n    {\n        return buffered_round_end;\n    }\n};\n\n\n}} // namespace strategy::buffer\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_STRATEGIES_BUFFER_END_ROUND_HPP\n", "meta": {"hexsha": "62291e564eab0471adfa9b989ec7a65d9540c25d", "size": 4543, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/strategies/buffer_end_round.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.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": "boost/geometry/extensions/strategies/buffer_end_round.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.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": "boost/geometry/extensions/strategies/buffer_end_round.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 31.9929577465, "max_line_length": 110, "alphanum_fraction": 0.6610169492, "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5118380726613444}}
{"text": "\n\n\n/* I was unable to find good information on how the PLL dividers work\nin the ECP5 PLL Design and Usage Guide, so I ran several frequencies\nthrough Lattice's clarity designer, and was surprised with what I\nfound:\n| Input | Output | refclk | feedback | output | fvco |\n|    12 |     48 |      1 |        4 |     12 |  576 |\n|    12 |     60 |      1 |        5 |     10 |  600 |\n|    20 |     30 |      2 |        3 |     20 |  600 |\n|    45 |     30 |      3 |        2 |     20 |  600 |\n|   100 |    400 |      1 |        4 |      1 |  400 |\n|   200 |    400 |      1 |        2 |      2 |  800 |\n|    50 |    400 |      1 |        8 |      2 |  800 |\n|    70 |     40 |      7 |        4 |     15 |  600 |\n|    12 |     36 |      1 |        3 |     18 |  648 |\n|    12 |     96 |      1 |        8 |      6 |  576 |\n|    90 |     40 |      9 |        4 |     15 |  600 |\n|    90 |     50 |      9 |        5 |     13 |  650 |\n|    43 |     86 |      1 |        2 |      7 |  602 |\n\nit appears that\nf_pfd = f_in/refclk\nf_vco = f_pfd * feedback * output\nf_out = f_vco / output\n */\n\n#define INPUT_MIN 8.0f\n#define INPUT_MAX 400.0f\n#define OUTPUT_MIN 10.0f\n#define OUTPUT_MAX 400.0f\n#define PFD_MIN 3.125f\n#define PFD_MAX 400.0f\n#define VCO_MIN 400.0f\n#define VCO_MAX 800.0f\n#include <iostream>\n#include <limits>\n#include <fstream>\n#include <boost/program_options.hpp>\nusing namespace std;\n\nenum class pll_mode{\n  SIMPLE,\n  HIGHRES\n};\n\nstruct secondary_params{\n  bool enabled;\n  int div;\n  int cphase;\n  int fphase;\n\n  float freq;\n  float phase;\n};\n  \n\nstruct pll_params{\n  pll_mode mode;\n  int refclk_div;\n  int feedback_div;\n  int output_div;\n  int primary_cphase;\n\n  secondary_params secondary[3];\n\n  float fout;\n  float fvco;\n\n  pll_params() :mode(pll_mode::SIMPLE) {\n    for(int i=0;i<3;i++){\n      secondary[i].enabled = false;\n      primary_cphase = 9;\n    }\n  }\n};\n\npll_params calc_pll_params(float input, float output);\npll_params calc_pll_params_highres(float input, float output);\nvoid generate_secondary_output(pll_params &params, int channel, float frequency, float phase);\nvoid write_pll_config(pll_params params, const char* name, ofstream& file);\n\nint main(int argc, char** argv){\n  namespace po = boost::program_options;\n  po::options_description options(\"Allowed options\");\n\n  options.add_options()(\"help,h\", \"show help\");\n  options.add_options()(\"input,i\", po::value<float>(), \"Input frequency in MHz\");\n  options.add_options()(\"output,o\", po::value<float>(), \"Output frequency in MHz\");\n  options.add_options()(\"s1\", po::value<float>(), \"Secondary Output frequency in MHz\");\n  options.add_options()(\"p1\", po::value<float>()->default_value(0), \"Secondary Output phase in degrees\");\n  options.add_options()(\"s2\", po::value<float>(), \"Secondary Output(2) frequency in MHz\");\n  options.add_options()(\"p2\", po::value<float>()->default_value(0), \"Secondary Output(2) phase in degrees\");\n  options.add_options()(\"s3\", po::value<float>(), \"Secondary Output(3) frequency in MHz\");\n  options.add_options()(\"p3\", po::value<float>()->default_value(0), \"Secondary Output(3) phase in degrees\");\n  options.add_options()(\"file,f\", po::value<string>(), \"Output to file\");\n  options.add_options()(\"highres\", \"Use secondary PLL output for higher frequency resolution\");\n\n  po::variables_map vm;\n  po::parsed_options parsed = po::command_line_parser(argc, argv).options(options).run();\n  po::store(parsed, vm);\n  po::notify(vm);\n\n  if(vm.count(\"help\")){\n    cerr << \"Project Trellis - Open Source Tools for ECP5 FPGAs\" << endl;\n    cerr << \"ecppll: ECP5 PLL Configuration Calculator\" << endl;\n    cerr << endl;\n    cerr << \"This tool is experimental! Use at your own risk!\" << endl;\n    cerr << endl;\n    cerr << \"Copyright (C) 2018-2019 David Shah <david@symbioticeda.com>\" << endl;\n    cerr << endl;\n    cerr << options << endl;\n    return 1;\n  }\n  if(vm.count(\"input\") != 1 || vm.count(\"output\") != 1){\n    cerr << \"Error: missing input or output frequency!\\n\";\n    return 1;\n  }\n  float inputf = vm[\"input\"].as<float>();\n  float outputf = vm[\"output\"].as<float>();\n  if(inputf < INPUT_MIN || inputf > INPUT_MAX){\n    cerr << \"Warning: Input frequency \" << inputf << \"MHz not in range (\" << INPUT_MIN << \"MHz, \" << INPUT_MAX << \"MHz)\\n\";\n  }\n  if(outputf < OUTPUT_MIN || outputf > OUTPUT_MAX){\n    cerr << \"Warning: Output frequency \" << outputf << \"MHz not in range (\" << OUTPUT_MIN << \"MHz, \" << OUTPUT_MAX << \"MHz)\\n\";\n  }\n  pll_params params;\n  if(vm.count(\"highres\")){\n    if(vm.count(\"s1\") > 0){\n      cerr << \"Cannot specify secondary frequency in highres mode\\n\";\n    }\n    params = calc_pll_params_highres(inputf, outputf);\n  }\n  else{\n    params = calc_pll_params(inputf, outputf);\n    if(vm.count(\"s1\"))\n      generate_secondary_output(params, 0, vm[\"s1\"].as<float>(), vm[\"p1\"].as<float>());\n    if(vm.count(\"s2\"))\n      generate_secondary_output(params, 1, vm[\"s2\"].as<float>(), vm[\"p2\"].as<float>());\n    if(vm.count(\"s3\"))\n      generate_secondary_output(params, 2, vm[\"s3\"].as<float>(), vm[\"p3\"].as<float>());\n      \n  }\n\n  cout << \"Pll parameters:\" << endl;\n  cout << \"Refclk divisor: \" << params.refclk_div << endl;\n  cout << \"Feedback divisor: \" << params.feedback_div << endl;\n  cout << \"Output divisor: \" << params.output_div << endl;\n  if(params.secondary[0].enabled){\n    cout << \"Secondary divisor: \" << params.secondary[0].div << endl;\n    cout << \"Secondary freq: \" << params.secondary[0].freq << endl;\n    cout << \"Secondary phase shift: \" << params.secondary[0].phase << endl;\n  }\n  if(params.secondary[1].enabled){\n    cout << \"Secondary(2) divisor: \" << params.secondary[1].div << endl;\n    cout << \"Secondary(2) freq: \" << params.secondary[1].freq << endl;\n    cout << \"Secondary(2) phase shift: \" << params.secondary[1].phase << endl;\n  }\n  if(params.secondary[2].enabled){\n    cout << \"Secondary(3) divisor: \" << params.secondary[2].div << endl;\n    cout << \"Secondary(3) freq: \" << params.secondary[2].freq << endl;\n    cout << \"Secondary(3) phase shift: \" << params.secondary[2].phase << endl;\n  }\n  cout << \"VCO frequency: \" << params.fvco << endl;\n  cout << \"Output frequency: \" << params.fout << endl;\n  if(vm.count(\"file\")){\n    ofstream f;\n\n    f.open(vm[\"file\"].as<string>().c_str());\n\n    \n    write_pll_config(params, \"pll\", f);\n\n    f.close();\n  }\n\n}\n\npll_params calc_pll_params(float input, float output){\n  float error = std::numeric_limits<float>::max();\n  pll_params params;\n  for(int input_div=1;input_div <= 128; input_div++){\n\n    float fpfd = input / (float)input_div;\n    if(fpfd < PFD_MIN || fpfd > PFD_MAX)\n      continue;\n    for(int feedback_div=1;feedback_div <= 80; feedback_div++){\n      for(int output_div=1;output_div <= 128; output_div++){\n\tfloat fvco = fpfd * (float)feedback_div * (float) output_div;\n\t\n\tif(fvco < VCO_MIN || fvco > VCO_MAX)\n\t  continue;\n\n\tfloat fout = fvco / (float) output_div;\n\tif(fabsf(fout - output) < error ||\n\t   (fabsf(fout-output) == error && fabsf(fvco - 600) < fabsf(params.fvco - 600))){\n\t  error = fabsf(fout-output);\n\t  params.refclk_div = input_div;\n\t  params.feedback_div = feedback_div;\n\t  params.output_div = output_div;\n\t  params.fout = fout;\n\t  params.fvco = fvco;\n\t  \n\t  // shift the primary by 180 degrees. Lattice seems to do this\n\t  float ns_phase = 1/(fout * 1e6) * 0.5;\n\t  params.primary_cphase = ns_phase * (fvco * 1e6);\n\n\t}\n\n      }\n    }\n  }\n  return params;\n}\n\npll_params calc_pll_params_highres(float input, float output){\n  float error = std::numeric_limits<float>::max();\n  pll_params params;\n  for(int input_div=1;input_div <= 128; input_div++){\n\n    float fpfd = input / (float)input_div;\n    if(fpfd < PFD_MIN || fpfd > PFD_MAX)\n      continue;\n    for(int feedback_div=1;feedback_div <= 80; feedback_div++){\n      for(int output_div=1;output_div <= 128; output_div++){\n\tfloat fvco = fpfd * (float)feedback_div * (float) output_div;\n\t\n\tif(fvco < VCO_MIN || fvco > VCO_MAX)\n\t  continue;\n\tfloat ffeedback = fvco / (float) output_div;\n\tif(ffeedback < OUTPUT_MIN || ffeedback > OUTPUT_MAX)\n\t  continue;\n\tfor(int secondary_div = 1; secondary_div <= 128; secondary_div++){\n\t  float fout = fvco / (float) secondary_div;\n\t  if(fabsf(fout - output) < error ||\n\t     (fabsf(fout-output) == error && fabsf(fvco - 600) < fabsf(params.fvco - 600))){\n\t    error = fabsf(fout-output);\n\t    params.mode = pll_mode::HIGHRES;\n\t    params.refclk_div = input_div;\n\t    params.feedback_div = feedback_div;\n\t    params.output_div = output_div;\n\t    params.secondary[0].div = secondary_div;\n\t    params.secondary[0].enabled = true;\n\t    params.secondary[0].freq = fout;\n\t    params.fout = fout;\n\t    params.fvco = fvco;\n\n\t  }\n\t}\n\n      }\n    }\n  }\n  return params;\n}\n\n\nvoid generate_secondary_output(pll_params &params, int channel, float frequency, float phase){\n  int div = params.fvco/frequency;\n  float freq = params.fvco/div;\n  cout << \"sdiv \" << div << endl;\n\n  float ns_shift = 1/(freq * 1e6) * phase /  360.0;\n  float phase_count = ns_shift * (params.fvco * 1e6);\n  int cphase = (int) phase_count;\n  int fphase = (int) ((phase_count - cphase) * 8);\n\n  float ns_actual = 1/(params.fvco * 1e6) * (cphase + fphase/8.0);\n  float phase_shift = 360 * ns_actual/ (1/(freq * 1e6));\n  \n\n  params.secondary[channel].enabled = true;\n  params.secondary[channel].div = div;\n  params.secondary[channel].freq = freq;\n  params.secondary[channel].phase = phase_shift;\n  params.secondary[channel].cphase = cphase + params.primary_cphase;\n  params.secondary[channel].fphase = fphase;\n  \n  \n\n}\n\nvoid write_pll_config(pll_params params, const char* name,  ofstream& file){\n  file << \"module \" << name << \"(input clki, \\n\";\n  for(int i=0;i<3;i++){\n    if(!(i==0 && params.mode == pll_mode::HIGHRES) && params.secondary[i].enabled){\n      file << \"    output clks\" << i+1 <<\",\\n\";\n    }\n  }\n  file << \"    output locked,\\n\";\n  file << \"    output clko\\n\";\n  file << \");\\n\";\n  file << \"wire clkfb;\\n\";\n  file << \"wire clkos;\\n\";\n  file << \"wire clkop;\\n\";\n  file << \"(* ICP_CURRENT=\\\"12\\\" *) (* LPF_RESISTOR=\\\"8\\\" *) (* MFG_ENABLE_FILTEROPAMP=\\\"1\\\" *) (* MFG_GMCREF_SEL=\\\"2\\\" *)\\n\";\n  file << \"EHXPLLL #(\\n\";\n  file << \"        .PLLRST_ENA(\\\"DISABLED\\\"),\\n\";\n  file << \"        .INTFB_WAKE(\\\"DISABLED\\\"),\\n\";\n  file << \"        .STDBY_ENABLE(\\\"DISABLED\\\"),\\n\";\n  file << \"        .DPHASE_SOURCE(\\\"DISABLED\\\"),\\n\";\n  file << \"        .CLKOP_FPHASE(0),\\n\";\n  file << \"        .CLKOP_CPHASE(\" << params.primary_cphase << \"),\\n\";\n  file << \"        .OUTDIVIDER_MUXA(\\\"DIVA\\\"),\\n\";\n  file << \"        .CLKOP_ENABLE(\\\"ENABLED\\\"),\\n\";\n  file << \"        .CLKOP_DIV(\" << params.output_div << \"),\\n\";\n  if(params.secondary[0].enabled){\n    file << \"        .CLKOS_ENABLE(\\\"ENABLED\\\"),\\n\";\n    file << \"        .CLKOS_DIV(\" << params.secondary[0].div << \"),\\n\";\n    file << \"        .CLKOS_CPHASE(\" << params.secondary[0].cphase << \"),\\n\";\n    file << \"        .CLKOS_FPHASE(\" << params.secondary[0].fphase << \"),\\n\";\n  }\n  if(params.secondary[1].enabled){\n    file << \"        .CLKOS2_ENABLE(\\\"ENABLED\\\"),\\n\";\n    file << \"        .CLKOS2_DIV(\" << params.secondary[1].div << \"),\\n\";\n    file << \"        .CLKOS2_CPHASE(\" << params.secondary[1].cphase << \"),\\n\";\n    file << \"        .CLKOS2_FPHASE(\" << params.secondary[1].fphase << \"),\\n\";\n  }\n  if(params.secondary[2].enabled){\n    file << \"        .CLKOS3_ENABLE(\\\"ENABLED\\\"),\\n\";\n    file << \"        .CLKOS3_DIV(\" << params.secondary[2].div << \"),\\n\";\n    file << \"        .CLKOS3_CPHASE(\" << params.secondary[2].cphase << \"),\\n\";\n    file << \"        .CLKOS3_FPHASE(\" << params.secondary[2].fphase << \"),\\n\";\n  }\n  file << \"        .CLKFB_DIV(\" << params.feedback_div << \"),\\n\";\n  file << \"        .CLKI_DIV(\" << params.refclk_div <<\"),\\n\";\n  file << \"        .FEEDBK_PATH(\\\"INT_OP\\\")\\n\";\n  file << \"    ) pll_i (\\n\";\n  file << \"        .CLKI(clki),\\n\";\n  file << \"        .CLKFB(clkfb),\\n\";\n  file << \"        .CLKINTFB(clkfb),\\n\";\n  file << \"        .CLKOP(clkop),\\n\";\n  if(params.secondary[0].enabled){\n    if(params.mode == pll_mode::HIGHRES)\n      file << \"        .CLKOS(clkos),\\n\";\n    else\n      file << \"        .CLKOS(clks1),\\n\";\n\n  }\n  if(params.secondary[1].enabled){\n    file << \"        .CLKOS2(clks2),\\n\";\n  }\n  if(params.secondary[2].enabled){\n    file << \"        .CLKOS3(clks3),\\n\";\n  }\n  file << \"        .RST(1'b0),\\n\";\n  file << \"        .STDBY(1'b0),\\n\";\n  file << \"        .PHASESEL0(1'b0),\\n\";\n  file << \"        .PHASESEL1(1'b0),\\n\";\n  file << \"        .PHASEDIR(1'b0),\\n\";\n  file << \"        .PHASESTEP(1'b0),\\n\";\n  file << \"        .PLLWAKESYNC(1'b0),\\n\";\n  file << \"        .ENCLKOP(1'b0),\\n\";\n  file << \"        .LOCK(locked)\\n\";\n  file << \"\t);\\n\";\n  if(params.mode == pll_mode::SIMPLE){\n    file << \"assign clko = clkop;\\n\";\n  }\n  else {\n    file << \"assign clko = clkos;\\n\";\n  }\n  file << \"endmodule\\n\";\n\n}\n", "meta": {"hexsha": "9fa3348c390f12fdd575bc2b1d062b9f868c7493", "size": 12765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libtrellis/tools/ecppll.cpp", "max_stars_repo_name": "evadot/prjtrellis", "max_stars_repo_head_hexsha": "9fb38f849e8fa2adb77c1795b77ee1f899d31e4a", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-02T16:48:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-28T08:25:15.000Z", "max_issues_repo_path": "libtrellis/tools/ecppll.cpp", "max_issues_repo_name": "evadot/prjtrellis", "max_issues_repo_head_hexsha": "9fb38f849e8fa2adb77c1795b77ee1f899d31e4a", "max_issues_repo_licenses": ["ISC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libtrellis/tools/ecppll.cpp", "max_forks_repo_name": "evadot/prjtrellis", "max_forks_repo_head_hexsha": "9fb38f849e8fa2adb77c1795b77ee1f899d31e4a", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-23T10:25:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T10:25:53.000Z", "avg_line_length": 34.8770491803, "max_line_length": 127, "alphanum_fraction": 0.5873873874, "num_tokens": 3905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.63341026367784, "lm_q1q2_score": 0.5118380668058732}}
{"text": "//\n//  Copyright (c) 2000-2002\n//  Joerg Walter, Mathias Koch\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  GeNeSys mbH & Co. KG in producing this work.\n//\n\n#include <boost/numeric/ublas/hermitian.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main () {\n    using namespace boost::numeric::ublas;\n    matrix<std::complex<double> > m (3, 3);\n    hermitian_adaptor<matrix<std::complex<double> >, lower> hal (m);\n    for (unsigned i = 0; i < hal.size1 (); ++ i) {\n        for (unsigned j = 0; j < i; ++ j)\n            hal (i, j) = std::complex<double> (3 * i + j, 3 * i + j);\n        hal (i, i) = std::complex<double> (4 * i, 0);\n    }\n    std::cout << hal << std::endl;\n    hermitian_adaptor<matrix<std::complex<double> >, upper> hau (m);\n    for (unsigned i = 0; i < hau.size1 (); ++ i) {\n        hau (i, i) = std::complex<double> (4 * i, 0);\n        for (unsigned j = i + 1; j < hau.size2 (); ++ j)\n            hau (i, j) = std::complex<double> (3 * i + j, 3 * i + j);\n    }\n    std::cout << hau << std::endl;\n}\n\n", "meta": {"hexsha": "889ae4e1a6355805bd88aea54e96f77b362cc45a", "size": 1191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/numeric/ublas/doc/samples/hermitian_adaptor.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/numeric/ublas/doc/samples/hermitian_adaptor.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/numeric/ublas/doc/samples/hermitian_adaptor.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 34.0285714286, "max_line_length": 69, "alphanum_fraction": 0.5709487825, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5118380612139269}}
{"text": "#ifndef _NCTX_PY_PTHS_\n#define _NCTX_PY_PTHS_\n//~ #include <boost/graph/property_maps/constant_property_map.hpp>\n//~ #include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n\nnamespace nctx { namespace python {\n  template<bool d>\n  class SpDummy{};\n\n  template <bool directed>\n  inline py::list build_path( typename GraphContainer<directed>::vertex start,\n                          typename GraphContainer<directed>::vertex goal,\n                          PropertyMapValueHolder<size_t,directed>& predecessors,\n                          size_t pred_undef){\n    using GraphC = GraphContainer<directed>;\n    using Vertex = typename GraphC::vertex;\n    py::list path;\n    // extract path\n    Vertex current = goal;\n    //~ std::cout << \"extract path: \" << start << \" -> \" << goal << std::endl;\n    do {\n        auto const pred = predecessors.get_elem(current);\n\n        //~ std::cout << \"extract path: \" << current << \" <- \" << pred << \" path length now \" << py::len(path) << std::endl;\n\n        if(pred == pred_undef || current == pred)\n            break;\n\n        current = pred;\n\n        path.append(current);\n    } while(current != start);\n\n    if(py::len(path) > 1){\n      path.reverse();\n      path.append(goal);\n    }\n    return path;\n  }\n\n  template <bool directed>\n  inline void wrap_pathalgs(){\n    using PMap = PropertyMapValueHolder<size_t,directed>;\n    using PMatrix = PropertyMapVectorHolder<size_t, directed>;\n    using GraphC = GraphContainer<directed>;\n    using Vertex = typename GraphC::vertex;\n    using Edge = typename GraphC::edge;\n\n    std::string apsp_doc = std::string(\"Obtain all-pairs-shortest-paths using Dijkstra's algorithm taking into account contextual constraints.\\n\\nThis is basically a wrapper around :py:func:`dijkstra_ctx <nctx.\") + (directed ? std::string(\"\"):std::string(\"un\")) + std::string(\"directed.AlgPaths.dijkstra_ctx>`. Please see the mentioned function for more information regarding the contextual constraints.\\n\\nArgs:\\n    g (Graph): The Graph object\\n    decision_fct (function): The decision function enforcing contextual constraints. The signature of the function is ``(vertex index, vertex index, vertex index) -> Bool``\\n     distances (PropertyMapVecULong): matrix in which distances will be written\\n\\nExample:\\n    >>> distmap = PropertyMapVecULong(g, 'distances_ctx')\\n    >>> AlgPaths.dijkstra_apsp_ctx(g,lambda _start,_current,_next: (True), distmap)\\n\\n\\n\");\n    std::string apsp_ret_doc = std::string(\"Obtain all-pairs-shortest-paths using Dijkstra's algorithm taking into account contextual constraints.\\n\\nThis is basically a wrapper around :py:func:`dijkstra_ctx <nctx.\") + (directed ? std::string(\"\"):std::string(\"un\")) + std::string(\"directed.AlgPaths.dijkstra_ctx>`. Please see the mentioned function for more information regarding the contextual constraints.\\n\\nArgs:\\n    g (Graph): The Graph object\\n    decision_fct (function): The decision function enforcing contextual constraints. The signature of the function is ``(vertex index, vertex index, vertex index) -> Bool``\\n\\nReturns:\\n    PropertyMapVecULong: matrix of distances named apsp_constraint\\n\\nExample:\\n    >>> distmap = AlgPaths.dijkstra_apsp_ctx(g,lambda _start,_current,_next: (True))\\n\\n\\n\");\n\n    std::string fpath_doc = std::string(\"Obtain a shortest paths from a start vertex to a target vertex using Dijkstra's algorithm taking into account contextual constraints.\\n\\nThis is basically a wrapper around :py:func:`dijkstra_ctx <nctx.\") + (directed ? std::string(\"\"):std::string(\"un\")) + std::string(\"directed.AlgPaths.dijkstra_ctx>`. Please see the mentioned function for more information regarding the contextual constraints.\\n\\nArgs:\\n    g (Graph): The Graph object\\n    decision_fct (function): The decision function enforcing contextual constraints. The signature of the function is ``(vertex index, vertex index, vertex index) -> Bool``\\n     start (int): Start vertex\\n    target (int): Target vertex\\n\\nReturns:\\n    list: A list of vertex indices describing the shortest path from start to target.\\n\\nExample:\\n    >>> start = 3\\n    >>> target = 10\\n    >>> path = AlgPaths.find_path_ctx(g,start,target,lambda _start,_current,_next: (True))\\n\\n\\n\");\n\n    py::class_<SpDummy<directed>>(\"AlgPaths\", py::no_init)\n      .def(\"dijkstra_ctx\", +[](GraphC& gc, Vertex start, py::object fct_decision, PMap& distances) {\n        std::function<bool (Vertex, Vertex, Vertex)> lmbd_decision = lambda_wrapper_t<bool, Vertex, Vertex, Vertex>( fct_decision );\n        const size_t dist_inf = (std::numeric_limits<size_t>::max)();\n        auto g = gc.get_graph();\n        auto weight_map = boost::make_constant_property<Edge>(1.0);\n        auto dummy_pred = b::dummy_property_map();\n        dijkstra_ctx_dispatch(g, start,\n                              b::weight_map(weight_map)\n                              .distance_map(distances.get_map()),\n                              distances.get_map(),\n                              weight_map,\n                              dummy_pred,\n                              0,\n                              lmbd_decision,\n                              dist_inf);\n      },(py::arg(\"g\"), py::arg(\"s\"), py::arg(\"decision_fct\"), py::arg(\"distances\")), \"Obtain shortest paths with dynamic contextual constraints.\\n\\n\\n\\nSingle-source shortest paths using Dijkstra's algorithm taking into account contextual constraints. Enforcement of constraints is the task of the given user-defined function.\\n\\nThe function enforcing contextual constraints is evaluated at each node during shortest path discovery. The function needs to evaluate to ``true`` or ``false`` allowing an edge to be visited or not. As parameters, the function needs to accept the starting node of path traversal, the current node, and the descending node in question. If the function returns False, the descending node is not being visited. Passing the start vertex is unnecessary here. However, the signature is the same as for the other functions for usability reasons.\\n\\nThe three nodes are passed as indices allowing for access of (external) attribute and other associated information.\\n\\nNote that the decision function is evaluated more than once during path traversal. That means, there should not happen any resource-intense computation inside this function. Also, it does not allow to keep track of the status of calculation, e.g. by calculating the visited edges or something similar.\\n\\nIf the decision function simply returns True all the time, the set of shortest paths is the unaltered set of shortest paths expected by the classical Dijkstra-implementation.\\n\\n\\n\\nArgs:\\n    g The graph object\\n    s The source vertex\\n    decision_fct A function enforcing constraints. The signature of the function is ``(vertex index, vertex index, vertex index) -> bool``, i.e. the function expects three vertex IDs for the start, the current, and the next vertex. It must evaluate to ``bool``. Passing the start vertex is unnecessary here. However, the signature is the same as for the other functions for usability reasons.\\n    distances (PropertyMapULong): map in which distances will be written\\n\\nExample:\\n    >>> start = 3\\n    >>> distmap = PropertyMapULong(g, 'distances_ctx')\\n    >>> AlgPaths.dijkstra_ctx(g, start, lambda _start,_current,_next: (True), distmap)\\n\\n\\n\")\n\n      .def(\"dijkstra_ctx\", +[](GraphC& gc, Vertex start, py::object fct_decision) -> PMap {\n        std::function<bool (Vertex, Vertex, Vertex)> lmbd_decision = lambda_wrapper_t<bool, Vertex, Vertex, Vertex>( fct_decision );\n        const size_t dist_inf = (std::numeric_limits<size_t>::max)();\n        auto g = gc.get_graph();\n        PMap distances(gc, \"dijkstra_constraint\");\n        auto weight_map = boost::make_constant_property<Edge>(1.0);\n        auto dummy_pred = b::dummy_property_map();\n        dijkstra_ctx_dispatch(g, start,\n                              b::weight_map(weight_map)\n                              .distance_map(distances.get_map()),\n                              distances.get_map(),\n                              weight_map,\n                              dummy_pred,\n                              0,\n                              lmbd_decision,\n                              dist_inf);\n        return distances;\n      },(py::arg(\"g\"), py::arg(\"s\"), py::arg(\"decision_fct\")), \"Obtain shortest paths with dynamic contextual constraints.\\n\\n\\n\\nSingle-source shortest paths using Dijkstra's algorithm taking into account contextual constraints. Enforcement of constraints is the task of the given user-defined function.\\n\\nThe function enforcing contextual constraints is evaluated at each node during shortest path discovery. The function needs to evaluate to ``true`` or ``false`` allowing an edge to be visited or not. As parameters, the function needs to accept the starting node of path traversal, the current node, and the descending node in question. If the function returns False, the descending node is not being visited. Passing the start vertex is unnecessary here. However, the signature is the same as for the other functions for usability reasons.\\n\\nThe three nodes are passed as indices allowing for access of (external) attribute and other associated information.\\n\\nNote that the decision function is evaluated more than once during path traversal. That means, there should not happen any resource-intense computation inside this function. Also, it does not allow to keep track of the status of calculation, e.g. by calculating the visited edges or something similar.\\n\\nIf the decision function simply returns True all the time, the set of shortest paths is the unaltered set of shortest paths expected by the classical Dijkstra-implementation.\\n\\n\\n\\nArgs:\\n    g The graph object\\n    s The source vertex\\n    decision_fct A function enforcing constraints. The signature of the function is ``(vertex index, vertex index, vertex index) -> bool``, i.e. the function expects three vertex IDs for the start, the current, and the next vertex. It must evaluate to ``bool``. Passing the start vertex is unnecessary here. However, the signature is the same as for the other functions for usability reasons.\\n\\n\\nReturns:\\n    PropertyMapULong: map containing distances named dijkstra_constraint\\n\\nExample:\\n    >>> start = 3\\n    >>> distmap = AlgPaths.dijkstra_ctx(g, start, lambda _start,_current,_next: (True))\\n\\n\\n\")\n\n      .def(\"dijkstra_apsp_ctx\", +[](GraphC& gc, py::object fct_decision, PMatrix& dmap) {\n        std::function<bool (Vertex, Vertex, Vertex)> lmbd_decision = lambda_wrapper_t<bool, Vertex, Vertex, Vertex>( fct_decision );\n        const size_t dist_inf = (std::numeric_limits<size_t>::max)();\n        auto g = gc.get_graph();\n        auto weight_map = boost::make_constant_property<Edge>(1.0);\n\n        for(auto start : make_iterator_range(vertices(g))){\n          std::vector<size_t> distances(b::num_vertices(g), 0);\n          auto distance_map = make_iterator_property_map(distances.begin(), b::get(b::vertex_index, g));\n          auto dummy_pred = b::dummy_property_map();\n          dijkstra_ctx_dispatch(g, start,\n                                b::weight_map(weight_map)\n                                .distance_map(distance_map),\n                                distance_map,\n                                weight_map,\n                                dummy_pred,\n                                0,\n                                lmbd_decision,\n                                dist_inf);\n\n          for(auto u : make_iterator_range(b::vertices(g)))\n            dmap.set_elem(start,u,distances[u]);\n        }\n      },(py::arg(\"g\"), py::arg(\"decision_fct\"), py::arg(\"distances\")), apsp_doc.c_str())\n\n      .def(\"dijkstra_apsp_ctx\", +[](GraphC& gc, py::object fct_decision) -> PMatrix {\n        std::function<bool (Vertex, Vertex, Vertex)> lmbd_decision = lambda_wrapper_t<bool, Vertex, Vertex, Vertex>( fct_decision );\n        const size_t dist_inf = (std::numeric_limits<size_t>::max)();\n        auto g = gc.get_graph();\n        auto weight_map = boost::make_constant_property<Edge>(1.0);\n        PMatrix dmap(gc, \"apsp_constraint\");\n        auto dummy_pred = b::dummy_property_map();\n\n        for(auto start : make_iterator_range(vertices(g))){\n          std::vector<size_t> distances(b::num_vertices(g), 0);\n          auto distance_map = make_iterator_property_map(distances.begin(), b::get(b::vertex_index, g));\n          dijkstra_ctx_dispatch(g, start,\n                                b::weight_map(weight_map)\n                                .distance_map(distance_map),\n                                distance_map,\n                                weight_map ,\n                                dummy_pred,\n                                0,\n                                lmbd_decision,\n                                dist_inf);\n\n          for(auto u : make_iterator_range(b::vertices(g)))\n            dmap.set_elem(start,u,distances[u]);\n        }\n        return dmap;\n      },(py::arg(\"g\"), py::arg(\"decision_fct\")), apsp_ret_doc.c_str())\n\n      .def(\"find_path_ctx\", +[](GraphC& gc, Vertex start, Vertex goal, py::object fct_decision) -> py::list {\n        std::function<bool (Vertex, Vertex, Vertex)> lmbd_decision = lambda_wrapper_t<bool, Vertex, Vertex, Vertex>( fct_decision );\n        const size_t dist_inf = (std::numeric_limits<size_t>::max)();\n        const int pred_init = (std::numeric_limits<int>::min)();\n        auto g = gc.get_graph();\n        PMap distances(gc, \"dijkstra_constraint\");\n        PMap predecessors(gc, \"predecessors_constraint\", pred_init);\n        auto weight_map = boost::make_constant_property<Edge>(1.0);\n\n        dijkstra_ctx_dispatch(g, start,\n                                b::weight_map(weight_map)\n                                .distance_map(distances.get_map())\n                                .predecessor_map(predecessors.get_map()),\n                                distances.get_map(),\n                                weight_map,\n                                predecessors.get_map(),\n                                pred_init,\n                                lmbd_decision,\n                                dist_inf);\n\n        // extract path\n        return build_path(start, goal, predecessors, pred_init);\n      },(py::arg(\"g\"), py::arg(\"start\"), py::arg(\"target\"), py::arg(\"decision_fct\")), fpath_doc.c_str())\n\n      .def(\"dijkstra\", +[](GraphC& gc, Vertex start, PMap& distances) {\n        auto g = gc.get_graph();\n        auto weight_map = boost::make_constant_property<Edge>(1.0);\n        boost::dijkstra_shortest_paths_no_color_map(g, start,\n                                b::weight_map(weight_map)\n                                .distance_map(distances.get_map()));\n      },(py::arg(\"g\"), py::arg(\"start\"), py::arg(\"distances\")), \"Conventional single-source shortest paths discovery using Dijkstra's algorithm.\\n\\nArgs:\\n    g (Graph): The Graph object\\n    start (int): Source vertex\\n    distances (PropertyMapULong): PropertyMap in which distances will be written.\\n\")\n\n      .def(\"dijkstra\", +[](GraphC& gc, Vertex start) -> PMap {\n        auto g = gc.get_graph();\n        PMap distances(gc, \"dijkstra\");\n        auto weight_map = boost::make_constant_property<Edge>(1.0);\n        boost::dijkstra_shortest_paths_no_color_map(g, start,\n                                b::weight_map(weight_map)\n                                .distance_map(distances.get_map()));\n        return distances;\n      },(py::arg(\"g\"), py::arg(\"start\")), \"Conventional single-source shortest paths discovery using Dijkstra's algorithm.\\n\\nArgs:\\n    g (Graph): The Graph object\\n    start (int): Source vertex\\n\\nReturns:\\n    PropertyMapULong: PropertyMap with distances.\\n\")\n\n      .def(\"find_path\", +[](GraphC& gc, Vertex start, Vertex goal) -> py::list {\n        auto g = gc.get_graph();\n        const int pred_init = (std::numeric_limits<int>::min)();\n        PMap distances(gc, \"dijkstra\");\n        PMap predecessors(gc, \"predecessors\", pred_init);\n        auto weight_map = boost::make_constant_property<Edge>(1.0);\n\n        boost::dijkstra_shortest_paths_no_color_map(g, start,\n                                b::weight_map(weight_map)\n                                .distance_map(distances.get_map())\n                                .predecessor_map(predecessors.get_map()));\n\n\n        return build_path(start, goal, predecessors, pred_init);\n      }, (py::arg(\"g\"), py::arg(\"start\"), py::arg(\"target\")), \"Conventional shortest path discovery using Dijkstra's algorithm.\\n\\nArgs:\\n    g (Graph): The Graph object\\n    start (int): Source vertex\\n    target (int): Target vertex\\n\\nReturns:\\n    list: A list of vertex indices describing the shortest path from start to target.\\n\");\n  }\n\n\n}} //nproc::python\n\n#endif", "meta": {"hexsha": "24ee4dbc2dfacbbb1d8a6f1fa2bb1cbb9941cf2c", "size": 16814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/python_defs/wrap_algs_shortest_path.hpp", "max_stars_repo_name": "nctx/py3nctx", "max_stars_repo_head_hexsha": "ee01aeaf675bbfd38dc4f37115d577a7796d2c80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-28T10:12:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T04:04:30.000Z", "max_issues_repo_path": "src/python_defs/wrap_algs_shortest_path.hpp", "max_issues_repo_name": "nctx/py3nctx", "max_issues_repo_head_hexsha": "ee01aeaf675bbfd38dc4f37115d577a7796d2c80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/python_defs/wrap_algs_shortest_path.hpp", "max_forks_repo_name": "nctx/py3nctx", "max_forks_repo_head_hexsha": "ee01aeaf675bbfd38dc4f37115d577a7796d2c80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 81.6213592233, "max_line_length": 2183, "alphanum_fraction": 0.6474366599, "num_tokens": 3690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5118380550949303}}
{"text": "// Copyright (C) 2015 National ICT Australia (NICTA)\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 http://mozilla.org/MPL/2.0/.\n// -------------------------------------------------------------------\n// \n// Written by Conrad Sanderson - http://conradsanderson.id.au\n\n\n#include <armadillo>\n#include \"catch.hpp\"\n\nusing namespace arma;\n\n\nTEST_CASE(\"fn_all_1\")\n  {\n  vec a(5, fill::zeros);\n  vec b(5, fill::zeros);  b(0) = 1.0;\n  vec c(5, fill::ones );\n  \n  REQUIRE( all(a) == false);\n  REQUIRE( all(b) == false);\n  REQUIRE( all(c) == true );\n  \n  REQUIRE( all(a(span::all)) == false);\n  REQUIRE( all(b(span::all)) == false);\n  REQUIRE( all(c(span::all)) == true );\n  \n  REQUIRE( all(  c -  c) == false);\n  REQUIRE( all(2*c -2*c) == false);\n  \n  REQUIRE( all(c < 0.5) == false);\n  REQUIRE( all(c > 0.5) == true );\n  }\n\n\n\nTEST_CASE(\"fn_all_2\")\n  {\n  mat A(5, 6, fill::zeros);\n  mat B(5, 6, fill::zeros);  B(0,0) = 1.0;\n  mat C(5, 6, fill::ones );\n  \n  REQUIRE( all(vectorise(A)) == false);\n  REQUIRE( all(vectorise(B)) == false);\n  REQUIRE( all(vectorise(C)) == true );\n  \n  REQUIRE( all(vectorise(A(span::all,span::all))) == false);\n  REQUIRE( all(vectorise(B(span::all,span::all))) == false);\n  REQUIRE( all(vectorise(C(span::all,span::all))) == true );\n\n\n  REQUIRE( all(vectorise(  C -  C)) == false);\n  REQUIRE( all(vectorise(2*C -2*C)) == false);\n  \n  REQUIRE( all(vectorise(C) < 0.5) == false);\n  REQUIRE( all(vectorise(C) > 0.5) == true );\n  }\n\n\n\nTEST_CASE(\"fn_all_3\")\n  {\n  mat A(5, 6, fill::zeros);\n  mat B(5, 6, fill::zeros);  B(0,0) = 1.0;\n  mat C(5, 6, fill::ones );\n  mat D(5, 6, fill::ones );  D(0,0) = 0.0;\n  \n  REQUIRE( accu( all(A)   == urowvec({0, 0, 0, 0, 0, 0}) ) == 6 );\n  REQUIRE( accu( all(A,0) == urowvec({0, 0, 0, 0, 0, 0}) ) == 6 );\n  REQUIRE( accu( all(A,1) == uvec   ({0, 0, 0, 0, 0}   ) ) == 5 );\n\n  REQUIRE( accu( all(B)   == urowvec({0, 0, 0, 0, 0, 0}) ) == 6 );\n  REQUIRE( accu( all(B,0) == urowvec({0, 0, 0, 0, 0, 0}) ) == 6 );\n  REQUIRE( accu( all(B,1) == uvec   ({0, 0, 0, 0, 0}   ) ) == 5 );\n  \n  REQUIRE( accu( all(C)   == urowvec({1, 1, 1, 1, 1, 1}) ) == 6 );\n  REQUIRE( accu( all(C,0) == urowvec({1, 1, 1, 1, 1, 1}) ) == 6 );\n  REQUIRE( accu( all(C,1) == uvec   ({1, 1, 1, 1, 1}   ) ) == 5 );\n  \n  REQUIRE( accu( all(D)   == urowvec({0, 1, 1, 1, 1, 1}) ) == 6 );\n  REQUIRE( accu( all(D,0) == urowvec({0, 1, 1, 1, 1, 1}) ) == 6 );\n  REQUIRE( accu( all(D,1) == uvec   ({0, 1, 1, 1, 1}   ) ) == 5 );\n  }\n\n\n", "meta": {"hexsha": "aa78e078c466b292dd489cbcc85a1f6b3d7c3631", "size": 2567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jet/thirdparty/armadillo/tests/fn_all.cpp", "max_stars_repo_name": "benman1/pyjet", "max_stars_repo_head_hexsha": "04b48e9966ed52999c2910b1966d467ee7fbb5bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T15:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T14:50:59.000Z", "max_issues_repo_path": "jet/thirdparty/armadillo/tests/fn_all.cpp", "max_issues_repo_name": "orestis-z/pyjet", "max_issues_repo_head_hexsha": "a922d8702496494c118d2c5239401d8170d10cd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-01-27T12:33:14.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-19T08:50:40.000Z", "max_forks_repo_path": "jet/thirdparty/armadillo/tests/fn_all.cpp", "max_forks_repo_name": "orestis-z/pyjet", "max_forks_repo_head_hexsha": "a922d8702496494c118d2c5239401d8170d10cd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T15:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-08T11:54:03.000Z", "avg_line_length": 28.8426966292, "max_line_length": 70, "alphanum_fraction": 0.5126606934, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5118314937427909}}
{"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 \"discretizeCheck.h\"\n#include <Eigen/Dense>\n#include \"utilities/avsEigenSupport.h\"\n#include \"utilities/discretize.h\"\n\n\nuint64_t testDiscretize()\n{\n    uint64_t failures = 0;\n    Discretize discretizor = Discretize(3);\n    Eigen::Vector3d states;\n    states << 0.1, 10.1, 11.1;\n    Eigen::Vector3d LSBs;\n    LSBs << 10., 10., 10.;\n    discretizor.setLSB(LSBs);\n    roundDirection_t roundThisWay = TO_ZERO;\n    discretizor.setRoundDirection(roundThisWay);\n    bool toCarryOrNotToCarry = false;\n    discretizor.setCarryError(toCarryOrNotToCarry);\n    Eigen::Vector3d expected;\n    expected << 0, 10., 10.;\n    \n    states = discretizor.discretize(states);\n    failures += states == expected ? 0 : 1;\n    \n    roundThisWay = FROM_ZERO;\n    discretizor.setRoundDirection(roundThisWay);\n    states << 0.1, 10.1, 11.1;\n    expected << 10., 20., 20.;\n    states = discretizor.discretize(states);\n    failures += states == expected ? 0 : 1;\n    \n    roundThisWay = NEAR;\n    discretizor.setRoundDirection(roundThisWay);\n    states << 0.1, 10.1, 15.1;\n    expected << 0, 10, 20;\n    states = discretizor.discretize(states);\n    failures += states == expected ? 0 : 1;\n    \n    discretizor = Discretize(3);\n    discretizor.setLSB(LSBs);\n    roundThisWay = TO_ZERO;\n    discretizor.setRoundDirection(roundThisWay);\n    toCarryOrNotToCarry = true;\n    discretizor.setCarryError(toCarryOrNotToCarry);\n    states << 0.1, 10.1, 15;\n    expected << 0., 10., 10.;\n    Eigen::Vector3d output;\n\n    uint64_t numPts = 2;\n    for(uint64_t i = 0; i < numPts; i++){\n        output = discretizor.discretize(states);\n        failures += output == expected ? 0 : 1;\n        expected << 0, 10, 20;\n    }\n    \n\n    return failures;\n    \n}\n\n\n\n\n", "meta": {"hexsha": "f62c0e38a0e25e04270fec96cbae9806d8bada27", "size": 2579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulation/utilitiesSelfCheck/discretizeCheck.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/discretizeCheck.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/discretizeCheck.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": 29.988372093, "max_line_length": 86, "alphanum_fraction": 0.6909654905, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5118314850610788}}
{"text": "//\n// Created by michel on 10-10-19.\n//\n\n#include <algorithm>\n#include <boost/test/unit_test.hpp>\n#include <chrono>\n#include <iostream>\n#include <simple-dsp/integration.h>\n\nusing FloatMultipliers = simpledsp::IntegrationMulipliers<float>;\nusing DoubleMultipliers = simpledsp::IntegrationMulipliers<double>;\n\n#ifdef SIMPLE_DSP_INTEGRATION_LONG_TESTS_SKIP\nstatic constexpr bool skipTests = true;\n#else\nstatic constexpr bool skipTests = false;\n#endif\ntemplate <typename T>\nstatic void impulseResponseSumTest(const char *testName, const char *message,\n                                   size_t factor = 1, double epsilon = 1e-6) {\n  T output = 0;\n  T sum = 0;\n  T maxSamples = simpledsp::IntegrationMulipliers<T>::maxSamples() / factor;\n  size_t iterationCount = std::sqrt(maxSamples) * 4;\n  size_t maxCount = simpledsp::minimum(static_cast<size_t>(maxSamples),\n                                       std::numeric_limits<size_t>::max() - 2);\n\n  simpledsp::IntegrationCoefficients<T> integrator(maxSamples);\n  auto start = std::chrono::system_clock::now();\n  auto maxDuration = std::chrono::seconds(2);\n\n  size_t count = 1;\n  integrator.integrate(1.0, output);\n  sum = output;\n  std::cout << \"( \" << testName << \": will run for a maximum of \"\n            << maxDuration.count() << \" seconds )\" << std::endl;\n  for (size_t i = 0; i < iterationCount; i++) {\n    for (size_t j = 0; j < iterationCount && count < maxCount; j++, count++) {\n      integrator.integrate(0, output);\n      sum += output;\n    }\n    auto now = std::chrono::system_clock::now();\n    if (now - start > maxDuration) {\n      break;\n    }\n  }\n\n  T expected = 1 - pow(M_E, -1.0 * count / maxSamples);\n\n  sum /= expected;\n\n  bool result = fabs(1.0 - sum) < epsilon;\n  BOOST_CHECK_MESSAGE(result, message);\n  if (!result) {\n    std::cout << testName << \": \" << message << \": \" << sum << \" for \" << count\n              << \"/\" << maxSamples << \" samples \" << std::endl;\n  }\n}\n\ntemplate <typename T>\nstatic void stepResponseSumTest(const char *testName, const char *message) {\n  T output = 0;\n  T maxSamples = simpledsp::IntegrationMulipliers<T>::maxSamples();\n  size_t iterationCount = std::sqrt(maxSamples) * 4;\n  size_t maxCount = simpledsp::minimum(static_cast<size_t>(maxSamples),\n                                       std::numeric_limits<size_t>::max() - 2);\n\n  simpledsp::IntegrationCoefficients<T> integrator(maxSamples);\n  auto start = std::chrono::system_clock::now();\n  auto maxDuration = std::chrono::seconds(2);\n  std::cout << \"( \" << testName << \": will run for a maximum of \"\n            << maxDuration.count() << \" seconds )\" << std::endl;\n\n  size_t count = 1;\n  integrator.integrate(1.0, output);\n  for (size_t i = 0; i < iterationCount; i++) {\n    for (size_t j = 0; j < iterationCount && count < maxCount; j++, count++) {\n      integrator.integrate(1, output);\n    }\n    auto now = std::chrono::system_clock::now();\n    if (now - start > maxDuration) {\n      break;\n    }\n  }\n\n  T expected = 1 - pow(M_E, -1.0 * count / maxSamples);\n\n  output /= expected;\n\n  bool result = (1.0 - output) < 0.001;\n  BOOST_CHECK_MESSAGE(result, message);\n  if (!result) {\n    std::cout << testName << \": \" << message << \": \" << output << \" for \"\n              << count << \"/\" << maxSamples << \" samples \" << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_SUITE(iirIntegrationTest)\n\nBOOST_AUTO_TEST_CASE(testAndReportSkippingLongTests) {\n  if (skipTests) {\n    std::cout << \"Skipping tests with long duration because \"\n                 \"SIMPLE_DSP_INTEGRATION_LONG_TESTS_SKIP is defined\"\n              << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testMaxSamplesFloatOkayBig) {\n  BOOST_CHECK_MESSAGE(FloatMultipliers::maxSamples() > 1e6,\n                      \"Max samples for float integration not reasonable\");\n}\n\nBOOST_AUTO_TEST_CASE(testFloatImpulseResponseSum) {\n  if (skipTests) {\n    return;\n  }\n  impulseResponseSumTest<float>(\n      \"Integration impulse response sum for single precision floats\",\n      \"sum not within promille of unity\", 8, 1e-3);\n}\n\nBOOST_AUTO_TEST_CASE(testDoubleImpulseResponseSum) {\n  if (skipTests) {\n    return;\n  }\n  impulseResponseSumTest<double>(\n      \"Integration impulse response sum for double precision floats\",\n      \"sum not within promille of unity\");\n}\n\nBOOST_AUTO_TEST_CASE(testFloatStepResponseSum) {\n  if (skipTests) {\n    return;\n  }\n  stepResponseSumTest<float>(\n      \"Integration impulse response sum for single precision floats\",\n      \"step response not within promille of unity\");\n}\n\nBOOST_AUTO_TEST_CASE(testDoubleStepResponseSum) {\n  if (skipTests) {\n    return;\n  }\n  stepResponseSumTest<double>(\n      \"Integration impulse response sum for double precision floats\",\n      \"step response not within promille of unity\");\n}\n\nBOOST_AUTO_TEST_CASE(testMaxSamplesDoubleOkayBig) {\n  BOOST_CHECK_MESSAGE(DoubleMultipliers::maxSamples() > 1e9,\n                      \"Max samples for double integration not reasonable\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6638f00e001978c463fa700cc2848c2de8ebecdb", "size": 4941, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/integration-tests.cc", "max_stars_repo_name": "emmef/simple-dsp", "max_stars_repo_head_hexsha": "b7275149705ebc164d1553312a9477e45ad0d7f6", "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/integration-tests.cc", "max_issues_repo_name": "emmef/simple-dsp", "max_issues_repo_head_hexsha": "b7275149705ebc164d1553312a9477e45ad0d7f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-20T22:49:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-20T22:49:16.000Z", "max_forks_repo_path": "test/integration-tests.cc", "max_forks_repo_name": "emmef/simple-dsp", "max_forks_repo_head_hexsha": "b7275149705ebc164d1553312a9477e45ad0d7f6", "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.6730769231, "max_line_length": 79, "alphanum_fraction": 0.6520947177, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5118136529547819}}
{"text": "#include <boost/numeric/ublas/io.hpp>\n\n#include \"geometry/rotation.h\"\n#include \"utils/check.h\"\n\nnamespace gca {\n\n  labeled_polygon_3 apply(const rotation& r, const labeled_polygon_3& p) {\n    vector<point> pts = apply(r, p.vertices());\n\n    vector<vector<point>> holes;\n    for (auto h : p.holes()) {\n      holes.push_back(apply(r, h));\n    }\n\n    polygon_3 rotated = build_clean_polygon_3(pts, holes);\n\n    rotated.correct_winding_order(times_3(r, p.normal()));\n\n    point rnorm = rotated.normal();\n    point pnorm = p.normal();\n    point rtnorm = times_3(r, p.normal());\n\n    // cout << \"Original normal             = \" << pnorm << endl;\n    // cout << \"Rotated normal              = \" << rnorm << endl;\n    // cout << \"Rotation of original normal = \" << rtnorm << endl;\n    \n    double theta = angle_between(rotated.normal(), rtnorm);\n  \n    DBG_ASSERT(within_eps(theta, 0.0, 0.1));\n\n    return rotated;\n  }\n\n  void test_rotation(const point from_unit, const point to_unit, const rotation& r) {\n    double d = determinant(r);\n    if (!(within_eps(d, 1.0, 0.001))) {\n      cout << \"ERROR: determinant of rotation = \" << d << endl;\n      cout << \"from unit normal = \" << from_unit << endl;\n      cout << \"to unit normal = \" << to_unit << endl;\n\n      double theta = angle_between(from_unit, to_unit);\n      cout << \"theta = \" << theta << endl;\n      cout << r << endl;\n\n      point rfu = times_3(r, from_unit);\n      double res_angle = angle_between(rfu, to_unit);\n\n      cout << \"r * from = \" << rfu << endl;\n      cout << \"resulting angle = \" << res_angle << endl;\n\n      // cout << \"c = \" << c << endl;\n      // cout << \"s = \" << s << endl;\n      // cout << \"v = \" << v << endl;\n\n      // cout << \"vx = \" << endl;\n      // cout << vx << endl;\n      \n      DBG_ASSERT(false);\n    }\n\n    if (!(within_eps(angle_between(times_3(r, from_unit), to_unit), 0.0, 0.1))) {\n      cout << \"ERROR: Incorrect rotation \" << endl;\n      cout << r << endl;\n\n      cout << \"from unit normal = \" << from_unit << endl;\n      cout << \"to unit normal = \" << to_unit << endl;\n      \n      cout << \"r*\" << from_unit << \" = \" << times_3(r, from_unit) << \" != \" << to_unit << endl;\n\n      DBG_ASSERT(false);\n    }\n    \n  }  \n\n  rotation rotate_unit_from_to_regular(const point from_unit, const point to_unit) {\n    point v = cross(from_unit, to_unit);\n    double s = v.len();\n    double c = dot(from_unit, to_unit);\n\n    boost::numeric::ublas::matrix<double> vx(3, 3);\n    vx(0, 0) = 0;\n    vx(0, 1) = -v.z;\n    vx(0, 2) = v.y;\n\n    vx(1, 0) = v.z;\n    vx(1, 1) = 0;\n    vx(1, 2) = -v.x;\n\n    vx(2, 0) = -v.y;\n    vx(2, 1) = v.x;\n    vx(2, 2) = 0;\n\n    const boost::numeric::ublas::matrix<double> id =\n      boost::numeric::ublas::identity_matrix<double>(3);\n\n    const boost::numeric::ublas::matrix<double> vxc = vx;\n    \n    const boost::numeric::ublas::matrix<double> vx2 = prod(vx, vx);\n\n    const ublas::matrix<double> r =\n      id + vxc + ((1.0 - c)/(s*s))*vx2;\n\n    return r;\n  }\n\n  void check_is_unit_vector(const point v, const double tol) {\n    if (!(within_eps(v.len(), 1.0, 0.00001))) {\n      cout << \"Error: Not a unit vector\" << endl;\n      cout << \"v       = \" << v << endl;\n      cout << \"v.len() = \" << v.len() << endl;\n      cout << \"tol     = \" << tol << endl;\n\n      DBG_ASSERT(within_eps(v.len(), 1.0, tol));\n    }\n  }\n\n  rotation rotate_unit_from_to(const point from_unit, const point to_unit) {\n\n    //    DBG_ASSERT(within_eps(from_unit.len(), 1.0, 0.00001));\n    //    DBG_ASSERT(within_eps(to_unit.len(),   1.0, 0.00001));\n\n    double tol = 0.00001;\n\n    check_is_unit_vector(from_unit, tol);\n    check_is_unit_vector(to_unit, tol);\n    \n    double theta = angle_between(from_unit, to_unit);\n\n    if (within_eps(theta, 0, 0.01)) {\n      return boost::numeric::ublas::identity_matrix<double>(3);\n    }\n\n    if (within_eps(theta, 180, 0.01)) {\n      return -1*boost::numeric::ublas::identity_matrix<double>(3);\n    }\n\n    const ublas::matrix<double> r =\n      rotate_unit_from_to_regular(from_unit, to_unit);\n\n    test_rotation(from_unit, to_unit, r);\n\n    return r;\n    \n  }\n\n  rotation rotate_from_to(const point from, const point to) {\n    point from_unit = from.normalize();\n    point to_unit = to.normalize();\n\n    return rotate_unit_from_to(from_unit, to_unit);\n  }\n\n  triangular_mesh apply(const rotation& r, const triangular_mesh& m) {\n    triangular_mesh rotated =\n      m.apply([r](const point p)\n\t      { return times_3(r, p); });\n    return rotated;\n  }\n\n  std::vector<point> apply(const rotation& r, const std::vector<point>& pts) {\n    std::vector<point> rpts;\n    for (auto p : pts) {\n      rpts.push_back(times_3(r, p));\n    }\n    return rpts;\n  }\n\n  point apply(const rotation& r, const point p) {\n    return times_3(r, p);\n  }\n\n  triangle apply(const rotation& r, const triangle tri) {\n    return triangle(apply(r, tri.normal),\n\t\t    apply(r, tri.v1),\n\t\t    apply(r, tri.v2),\n\t\t    apply(r, tri.v3));\n  }\n\n  polyline apply(const rotation& r, const polyline& p) {\n    vector<point> applied;\n    for (auto pt : p) {\n      applied.push_back(times_3(r, pt));\n    }\n\n    return polyline(applied);\n  }\n\n  polygon_3 apply_no_check(const rotation& r, const polygon_3& p) {\n    vector<point> pts = apply(r, p.vertices());\n\n    vector<vector<point>> holes;\n    for (auto h : p.holes()) {\n      holes.push_back(apply(r, h));\n    }\n\n    polygon_3 rotated = polygon_3(pts, holes, true); //, holes);\n\n    rotated.correct_winding_order(times_3(r, p.normal()));\n\n    point rnorm = rotated.normal();\n    point pnorm = p.normal();\n    point rtnorm = times_3(r, p.normal());\n\n    // cout << \"Original normal             = \" << pnorm << endl;\n    // cout << \"Rotated normal              = \" << rnorm << endl;\n    // cout << \"Rotation of original normal = \" << rtnorm << endl;\n    \n    double theta = angle_between(rotated.normal(), rtnorm);\n  \n    DBG_ASSERT(within_eps(theta, 0.0, 0.1));\n\n    return rotated;\n  }\n\n  std::vector<point>\n  clean_for_conversion_to_polygon_3(const std::vector<point>& vertices) {\n    auto outer_ring = vertices;\n\n    outer_ring = clean_vertices(outer_ring);\n\n    if (outer_ring.size() < 3) { return outer_ring; }\n\n    delete_antennas_no_fail(outer_ring);\n\n    return outer_ring;\n  }\n\n\n}\n", "meta": {"hexsha": "b209312117efc21f1731f4e8e033b939c636697b", "size": 6218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/rotation.cpp", "max_stars_repo_name": "dillonhuff/scg", "max_stars_repo_head_hexsha": "21d004ce37c0e0e3650e373726d7e8bac51fffa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2018-05-10T16:40:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T06:36:09.000Z", "max_issues_repo_path": "src/geometry/rotation.cpp", "max_issues_repo_name": "dillonhuff/scg", "max_issues_repo_head_hexsha": "21d004ce37c0e0e3650e373726d7e8bac51fffa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-26T13:08:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-26T13:08:56.000Z", "max_forks_repo_path": "src/geometry/rotation.cpp", "max_forks_repo_name": "dillonhuff/scg", "max_forks_repo_head_hexsha": "21d004ce37c0e0e3650e373726d7e8bac51fffa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-28T17:36:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-30T14:32:05.000Z", "avg_line_length": 26.9177489177, "max_line_length": 95, "alphanum_fraction": 0.5816982953, "num_tokens": 1782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5118136481644951}}
{"text": "//  (C) Copyright John Maddock 2007.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n#include <fstream>\n#include <boost/math/tools/test_data.hpp>\n#include <boost/random.hpp>\n#include \"mp_t.hpp\"\n\nusing namespace boost::math::tools;\nusing namespace boost::math;\nusing namespace std;\n\nfloat extern_val;\n// confuse the compilers optimiser, and force a truncation to float precision:\nfloat truncate_to_float(float const * pf)\n{\n   extern_val = *pf;\n   return *pf;\n}\n\n\n\ntemplate<class T>\nboost::math::tuple<T, T, T, T, T, T> spherical_harmonic_data(T i)\n{\n   static boost::mt19937 r;\n\n   int n = real_cast<int>(floor(i));\n   boost::uniform_int<> ui(0, (std::min)(n, 40));\n   int m = ui(r);\n\n   boost::uniform_real<float> ur(-2*constants::pi<float>(), 2*constants::pi<float>());\n   float _theta = ur(r);\n   float _phi = ur(r);\n   T theta = truncate_to_float(&_theta);\n   T phi = truncate_to_float(&_phi);\n\n   T r1 = spherical_harmonic_r(n, m, theta, phi);\n   T r2 = spherical_harmonic_i(n, m, theta, phi);\n   return boost::math::make_tuple(n, m, theta, phi, r1, r2);\n}\n\nint main(int argc, char*argv [])\n{\n   using namespace boost::math::tools;\n\n   parameter_info<mp_t> arg1, arg2, arg3;\n   test_data<mp_t> data;\n\n   bool cont;\n   std::string line;\n\n   if(argc < 1)\n      return 1;\n\n   do{\n      if(0 == get_user_parameter_info(arg1, \"n\"))\n         return 1;\n      arg1.type |= dummy_param;\n      arg2.type |= dummy_param;\n      arg3 = arg2;\n\n      data.insert(&spherical_harmonic_data<mp_t>, arg1);\n\n      std::cout << \"Any more data [y/n]?\";\n      std::getline(std::cin, line);\n      boost::algorithm::trim(line);\n      cont = (line == \"y\");\n   }while(cont);\n\n   std::cout << \"Enter name of test data file [default=spherical_harmonic.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"spherical_harmonic.ipp\";\n   std::ofstream ofs(line.c_str());\n   line.erase(line.find('.'));\n   ofs << std::scientific << std::setprecision(40);\n   write_code(ofs, data, line.c_str());\n\n   return 0;\n}\n", "meta": {"hexsha": "0847dcdff72ed0ce17df5030d64efe0d1b0da6b1", "size": 2240, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/math/tools/spherical_harmonic_data.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/math/tools/spherical_harmonic_data.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/math/tools/spherical_harmonic_data.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": 26.0465116279, "max_line_length": 86, "alphanum_fraction": 0.6513392857, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.511813640420092}}
{"text": "/**\n * @file \tex8.cpp\n * @author \tFabian Wegscheider\n * @date \tJul 10, 2017\n */\n\n\n#include <iostream>\n#include <boost/program_options.hpp>\n#include <boost/heap/fibonacci_heap.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include \"GraphParser.h\"\n#include \"ShortestPathHeuristic.h\"\n#include \"MyDijkstra.h\"\n\nusing std::ifstream;\nusing std::string;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing namespace boost;\nnamespace po = boost::program_options;\n\nusing Graph = adjacency_list<vecS, vecS, undirectedS,\n\t\tno_property, property<edge_weight_t, double>>;\n\n\n/**\n * The main function which reads in a graph from a .gph file, considers all\n * vertices with prime indices as terminals and calculates a steiner tree\n * using the shortest-path-heuristic and Dijkstra.\n * @param numargs number of inputs on command line\n * @param args array of inputs on command line\n * @return whether the program operated successfully\n */\nint main(int numargs, char* args[]) {\n\n\t/*parsing command line options*/\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t\t\t(\"help,h\", \"produce help message\")\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(po::command_line_parser(numargs, args).\n\t\t\toptions(desc).positional(p).run(), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t\tcout << desc << \"\\n\";\n\t\texit(EXIT_SUCCESS);\n\t}\n\n\tstring input;\n\tif (vm.count(\"input-file\")) {\n\t\tinput = vm[\"input-file\"].as< string >();\n\t} else {\n\t\tcerr << \"please specify an input file in the .gph format\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\t/*end of parsing command line options*/\n\n\n\tint numVertices;\n\tint numEdges;\n\n\n\tGraphParser parser(input);\n\tif (!parser.readSuccessfully) {\n\t\tcerr << \"file could not be read\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t//first line is read to get number of vertices and edges\n\tif (!parser.readFirstLine(numVertices, numEdges)) {\n\t\tcerr << \"error while reading file, not the right format\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tEdge* edges = new Edge[numEdges];\n\tdouble* weights = new double[numEdges];\n\n\t//rest of the file is read and parsed to a graph\n\tif (!parser.read(edges, weights)) {\n\t\tcerr << \"error while reading file, not the right format\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t//timer is started\n\ttimer::cpu_timer t;\n\n\t//undirected graph is constructed with all edges and their weights\n\tGraph g(edges, edges + numEdges , weights, numVertices);\n\n\t//here the steiner tree is finally constructed\n\tdouble result = ShortestPathHeuristic::constructSteinerTree(g, numVertices);\n\n\tcout << \"objective value of constructed steiner tree: \" << result << endl;\n\tcout << \"running time of the algorithm: \" << t.format() << endl;\n\n\tdelete[] edges;\n\tdelete[] weights;\n\n\texit(EXIT_SUCCESS);\n}\n\n\n\n\n\n", "meta": {"hexsha": "0e794540565f8d75f232323f3431ab0bc30767ed", "size": 2931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Wegscheider/Ex8/ex8.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": "Wegscheider/Ex8/ex8.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": "Wegscheider/Ex8/ex8.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": 25.4869565217, "max_line_length": 77, "alphanum_fraction": 0.7082906858, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5118136308395185}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN STDC Functional Test Suite\n\n#include <boost/test/unit_test.hpp>\n\n#include <stdc/functional.h>\n\nBOOST_AUTO_TEST_SUITE( STDC_Functional_Test_Suite )\n\nBOOST_AUTO_TEST_CASE( Less_Test_Cases )\n{\n    static_assert(stdc::less<int>()(0, 1), \"\");\n    static_assert(not stdc::less<int>()(0, 0), \"\");\n\n    auto less = stdc::less<int>();\n\n    BOOST_CHECK(not less(0, 0));\n    BOOST_CHECK(less(0, 1));\n    BOOST_CHECK(less(-1, 1));\n    BOOST_CHECK(not less(1, 0));\n    BOOST_CHECK(not less(1, -1));\n}\n\nBOOST_AUTO_TEST_CASE( Less_Equal_Test_Cases )\n{\n    static_assert(stdc::less_equal<int>()(0, 0), \"\");\n    static_assert(stdc::less_equal<int>()(0, 1), \"\");\n\n    auto less_equal = stdc::less_equal<int>();\n\n    BOOST_CHECK(less_equal(0, 0));\n    BOOST_CHECK(less_equal(0, 1));\n    BOOST_CHECK(less_equal(-1, 1));\n    BOOST_CHECK(not less_equal(1, 0));\n    BOOST_CHECK(not less_equal(1, -1));\n}\n\nBOOST_AUTO_TEST_CASE( Greater_Test_Cases )\n{\n    static_assert(stdc::greater<int>()(1, 0), \"\");\n    static_assert(not stdc::greater<int>()(0, 0), \"\");\n\n    auto greater = stdc::greater<int>();\n\n    BOOST_CHECK(not greater(0, 0));\n    BOOST_CHECK(greater(1, 0));\n    BOOST_CHECK(greater(1, -1));\n    BOOST_CHECK(not greater(0, 1));\n    BOOST_CHECK(not greater(-1, 1));\n}\n\nBOOST_AUTO_TEST_CASE( Greater_Equal_Test_Cases )\n{\n    static_assert(stdc::greater_equal<int>()(1, 0), \"\");\n    static_assert(stdc::greater_equal<int>()(0, 0), \"\");\n\n    auto greater_equal = stdc::greater_equal<int>();\n\n    BOOST_CHECK(greater_equal(0, 0));\n    BOOST_CHECK(greater_equal(1, 0));\n    BOOST_CHECK(greater_equal(1, -1));\n    BOOST_CHECK(not greater_equal(0, 1));\n    BOOST_CHECK(not greater_equal(-1, 1));\n}\n\nBOOST_AUTO_TEST_CASE( Less_Than_Test_Cases )\n{\n    auto compare = stdc::less_than<int>(0);\n\n    BOOST_CHECK(compare(-10));\n    BOOST_CHECK(compare(-1));\n    BOOST_CHECK(not compare(0));\n    BOOST_CHECK(not compare(1));\n    BOOST_CHECK(not compare(10));\n}\n\nBOOST_AUTO_TEST_CASE( Greater_Than_Test_Cases )\n{\n    auto compare = stdc::greater_than<int>(0);\n\n    BOOST_CHECK(not compare(-10));\n    BOOST_CHECK(not compare(-1));\n    BOOST_CHECK(not compare(0));\n    BOOST_CHECK(compare(1));\n    BOOST_CHECK(compare(10));\n}\n\nBOOST_AUTO_TEST_CASE( Equal_To_Test_Cases )\n{\n    auto compare = stdc::equal_to<int>(3);\n\n    BOOST_CHECK(not compare(-10));\n    BOOST_CHECK(not compare(-1));\n    BOOST_CHECK(not compare(0));\n    BOOST_CHECK(compare(3));\n    BOOST_CHECK(compare(3.14l));\n    BOOST_CHECK(compare(3.14L));\n}\n\nBOOST_AUTO_TEST_SUITE_END( /* STDC_Functional_Test_Suite */ )\n", "meta": {"hexsha": "6cbcc3d728afd92dd07addab0e82ccbf4b4c534b", "size": 2598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_stdc_functional.cpp", "max_stars_repo_name": "janoma/STL-Complement", "max_stars_repo_head_hexsha": "7e9655fd17823d5118970b5f96d85dfc10b88723", "max_stars_repo_licenses": ["MIT"], "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_stdc_functional.cpp", "max_issues_repo_name": "janoma/STL-Complement", "max_issues_repo_head_hexsha": "7e9655fd17823d5118970b5f96d85dfc10b88723", "max_issues_repo_licenses": ["MIT"], "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_stdc_functional.cpp", "max_forks_repo_name": "janoma/STL-Complement", "max_forks_repo_head_hexsha": "7e9655fd17823d5118970b5f96d85dfc10b88723", "max_forks_repo_licenses": ["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.7227722772, "max_line_length": 61, "alphanum_fraction": 0.6724403387, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5118060580948824}}
{"text": "/*\n\nPICCANTE\nThe hottest HDR imaging library!\nhttp://vcg.isti.cnr.it/piccante\n\nCopyright (C) 2014\nVisual Computing Laboratory - ISTI CNR\nhttp://vcg.isti.cnr.it\nFirst author: Francesco Banterle\n\nThis Source Code Form is subject to the terms of the Mozilla Public\nLicense, v. 2.0. If a copy of the MPL was not distributed with this\nfile, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n*/\n\n#include <vector>\n\n#include \"../base.hpp\"\n\n#include \"../util/matrix_3_x_3.hpp\"\n#include \"../util/vec.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n\n#ifndef PIC_EIGEN_NOT_BUNDLED\n    #include \"../externals/Eigen/LU\"\n    #include \"../externals/Eigen/Geometry\"\n#else\n    #include <Eigen/LU>\n    #include <Eigen/Geometry>\n#endif\n\n#endif\n\n#ifndef PIC_EIGEN_UTIL\n#define PIC_EIGEN_UTIL\n\n#ifndef PIC_DISABLE_EIGEN\nnamespace Eigen {\n    typedef Matrix<float,  3, 4> Matrix34f;\n    typedef Matrix<double, 3, 4> Matrix34d;\n}\n#endif\n\nnamespace pic {\n\n#ifndef PIC_DISABLE_EIGEN\n\n/**\n * @brief readMatrix34dFromFile\n * @param nameFile\n * @return\n */\nPIC_INLINE Eigen::Matrix34d readMatrix34dFromFile(std::string nameFile)\n{\n    Eigen::Matrix34d mat;\n\n    FILE *file = fopen(nameFile.c_str(), \"r\");\n\n    if(file == NULL) {\n        return mat;\n    }\n\n    for(int i = 0; i < 3; i++) {\n        for(int j = 0; j < 4; j++) {\n            float val;\n            fscanf(file, \"%f\", &val);\n            mat(i, j) = double(val);\n        }\n    }\n\n    fclose(file);\n\n    return mat;\n}\n\n/**\n * @brief writeMatrix34dToFile\n * @param nameFile\n * @param mat\n * @return\n */\nPIC_INLINE bool writeMatrix34dToFile(std::string nameFile, Eigen::Matrix34d &mat)\n{\n    FILE *file = fopen(nameFile.c_str(), \"w\");\n\n    if(file == NULL) {\n        return false;\n    }\n\n    for(int i = 0; i < 3; i++) {\n        for(int j = 0; j < 4; j++) {\n            fprintf(file, \"%f \", mat(i, j));\n        }\n\n        if(i < 2) {\n            fprintf(file, \"\\n\");\n        }\n    }\n\n    fclose(file);\n\n    return true;\n}\n\n/**\n * @brief DiagonalMatrix creates a diagonal matrix.\n * @param D a vector of size 3.\n * @return It returns a diagonal matrix.\n */\nPIC_INLINE Eigen::Matrix3d DiagonalMatrix(Eigen::Vector3d D)\n{\n    Eigen::Matrix3d ret;\n\n    ret.setZero();\n    ret(0, 0) = D[0];\n    ret(1, 1) = D[1];\n    ret(2, 2) = D[2];\n\n    return ret;\n}\n\n/**\n * @brief getDiagonalFromMatrix\n * @param mat\n * @return\n */\nPIC_INLINE Eigen::Vector3d getDiagonalFromMatrix(Eigen::Matrix3d &mat)\n{\n    Eigen::Vector3d D;\n\n    D[0] = mat(0, 0);\n    D[1] = mat(1, 1);\n    D[2] = mat(2, 2);\n\n    return D;\n}\n\n/**\n * @brief getSquareMatrix\n * @param mat\n * @return\n */\nPIC_INLINE Eigen::Matrix3d getSquareMatrix(Eigen::Matrix34d &mat)\n{\n    Eigen::Matrix3d ret;\n    ret(0, 0) = mat(0, 0);\n    ret(0, 1) = mat(0, 1);\n    ret(0, 2) = mat(0, 2);\n\n    ret(1, 0) = mat(1, 0);\n    ret(1, 1) = mat(1, 1);\n    ret(1, 2) = mat(1, 2);\n\n    ret(2, 0) = mat(2, 0);\n    ret(2, 1) = mat(2, 1);\n    ret(2, 2) = mat(2, 2);\n\n    return ret;\n}\n\n/**\n * @brief getLastColumn\n * @param mat\n * @return\n */\nPIC_INLINE Eigen::Vector3d getLastColumn(Eigen::Matrix34d &mat)\n{\n    Eigen::Vector3d ret;\n\n    ret[0] = mat(0, 3);\n    ret[1] = mat(1, 3);\n    ret[2] = mat(2, 3);\n\n    return ret;\n}\n\n/**\n * @brief addOne\n * @param x\n * @return\n */\nPIC_INLINE Eigen::Vector3f addOne(Eigen::Vector2f &x)\n{\n    return Eigen::Vector3f(x[0], x[1], 1.0f);\n}\n\n/**\n * @brief addOne\n * @param x\n * @return\n */\nPIC_INLINE Eigen::Vector3d addOne(Eigen::Vector2d &x)\n{\n    return Eigen::Vector3d(x[0], x[1], 1.0);\n}\n\n/**\n * @brief addOne\n * @param x\n * @return\n */\nPIC_INLINE Eigen::Vector4d addOne(Eigen::Vector3d &x)\n{\n    return Eigen::Vector4d(x[0], x[1], x[2], 1.0);\n}\n\n/**\n * @brief printfVet3d\n * @param x\n */\nPIC_INLINE void printfVet3d(Eigen::Vector3d &x)\n{\n    printf(\"%f %f %f\\n\", x[0], x[1], x[2]);\n}\n\n\n/**\n * @brief printf\n * @param mat\n */\nPIC_INLINE void printfMat(Eigen::MatrixXd mat)\n{\n    for(int i = 0; i < mat.rows(); i++){\n        for(int j = 0; j < mat.cols(); j++){\n            printf(\"%3.3f \", mat(i, j));\n        }\n        printf(\"\\n\");\n    }\n}\n\n/**\n * @brief printf\n * @param mat\n */\nPIC_INLINE void printfMat(Eigen::Matrix3f &mat)\n{\n    for(int i = 0; i < 3; i++){\n        for(int j = 0; j < 3; j++){\n            printf(\"%f \", mat(i, j));\n        }\n        printf(\"\\n\");\n    }\n}\n    \n/**\n  * @brief printf\n  * @param mat\n  */\nPIC_INLINE void printfMat34d(Eigen::Matrix34d &mat)\n{\n    for(int i = 0; i < 3; i++){\n        for(int j = 0; j < 4; j++){\n            printf(\"%.9f \", mat(i, j));\n        }\n        printf(\"\\n\");\n    }\n}\n\n/**\n * @brief fprintf\n * @param mat\n */\nPIC_INLINE void fprintfMat(Eigen::MatrixXd &mat, std::string name)\n{\n    FILE *file = fopen(name.c_str(), \"w\");\n    for(int i = 0; i < mat.rows(); i++){\n        for(int j = 0; j < mat.cols(); j++){\n            fprintf(file, \"%.9f \", mat(i, j));\n        }\n        fprintf(file, \"\\n\");\n    }\n    fclose(file);\n}\n\n/**\n * @brief printf\n * @param mat\n */\nPIC_INLINE void printfMat(Eigen::Matrix3d &mat)\n{\n    for(int i = 0; i < 3; i++){\n        for(int j = 0; j < 3; j++){\n            printf(\"%f \", mat(i, j));\n        }\n        printf(\"\\n\");\n    }\n}\n\n/**\n * @brief getShiftScaleMatrix computes a shifting and scaling matrix\n * @param info is an array with the center (0 and 1) a scaling factor (3)\n * @return It returns a scaling and shifting matrix.\n */\nPIC_INLINE Eigen::Matrix3d getShiftScaleMatrix(Eigen::Vector3f &info)\n{\n    Eigen::Matrix3d ret;\n\n    double cX = info[0];\n    double cY = info[1];\n    double s  = 1.0 / info[2];\n\n    ret(0,0) = s;   ret(0,1) = 0.0; ret(0,2) = -cX / info[2];\n    ret(1,0) = 0.0; ret(1,1) = s;   ret(1,2) = -cY / info[2];\n    ret(2,0) = 0.0; ret(2,1) = 0.0; ret(2,2) = 1.0;\n\n    return ret;\n}\n\n/**\n * @brief CrossProduct computes a cross product matrix from a vector.\n * @param t a translation vector\n * @return It returns a cross product matrix.\n */\nPIC_INLINE Eigen::Matrix3d CrossProduct(Eigen::Vector3d &t)\n{\n    Eigen::Matrix3d ret;\n    ret(0, 0) =  0.0;  ret(0, 1) = -t[2]; ret(0, 2) =  t[1];\n    ret(1, 0) =  t[2]; ret(1, 1) =  0.0;  ret(1, 2) = -t[0];\n    ret(2, 0) = -t[1]; ret(2, 1) =  t[0]; ret(2, 2) =  0.0;\n    return ret;\n}\n\n/**\n * @brief rigidTransform computes a rigidi transformation in 3D.\n * @param point is the point to be transformed.\n * @param R is a rotation matrix 3x3.\n * @param t is a translation vector.\n * @return\n */\nPIC_INLINE Eigen::Vector3d rigidTransform(Eigen::Vector3d &point, Eigen::Matrix3d &R, Eigen::Vector3d &t)\n{\n    return R * point + t;\n}\n\n/**\n * @brief RotationMatrixRefinement\n * @param R\n * @return\n */\nPIC_INLINE Eigen::Matrix3d RotationMatrixRefinement(Eigen::Matrix3d &R)\n{\n    Eigen::Quaternion<double> reg(R);\n\n    return reg.toRotationMatrix();\n}\n\n/**\n * @brief MatrixConvert converts a matrix from a Eigen::Matrix3f representation\n * into a Matrix3x3 representation.\n * @param mat is an Eigen 3x3 matrix.\n * @return It returns a Matrix3x3 with values from mat.\n */\nPIC_INLINE Matrix3x3 MatrixConvert(Eigen::Matrix3f &mat)\n{\n    Matrix3x3 mtx;\n    mtx.data[0] = mat(0, 0);\n    mtx.data[1] = mat(0, 1);\n    mtx.data[2] = mat(0, 2);\n\n    mtx.data[3] = mat(1, 0);\n    mtx.data[4] = mat(1, 1);\n    mtx.data[5] = mat(1, 2);\n\n    mtx.data[6] = mat(2, 0);\n    mtx.data[7] = mat(2, 1);\n    mtx.data[8] = mat(2, 2);\n\n    return mtx;\n}\n\n\n/**\n * @brief MatrixConvert converts a matrix from a Eigen::Matrix3f representation\n * into a Matrix3x3 representation.\n * @param mat is an Eigen 3x3 matrix.\n * @return It returns a Matrix3x3 with values from mat.\n */\nPIC_INLINE Matrix3x3 MatrixConvert(Eigen::Matrix3d &mat)\n{\n    Matrix3x3 mtx;\n    mtx.data[0] = float(mat(0, 0));\n    mtx.data[1] = float(mat(0, 1));\n    mtx.data[2] = float(mat(0, 2));\n\n    mtx.data[3] = float(mat(1, 0));\n    mtx.data[4] = float(mat(1, 1));\n    mtx.data[5] = float(mat(1, 2));\n\n    mtx.data[6] = float(mat(2, 0));\n    mtx.data[7] = float(mat(2, 1));\n    mtx.data[8] = float(mat(2, 2));\n\n    return mtx;\n}\n\n/**\n * @brief getLinearArray\n * @param mat\n * @return\n */\nPIC_INLINE float *getLinearArrayFromMatrix(Eigen::Matrix3d &mat)\n{\n    int n = int(mat.cols() * mat.rows());\n\n    float *ret = new float[n];\n    int c = 0;\n    for(int i = 0; i < mat.rows(); i++) {\n        for(int j = 0; j < mat.cols(); j++) {\n            ret[c] = float(mat(i, j));\n            c++;\n        }\n    }\n\n    return ret;\n}\n\n/**\n * @brief getLinearArray\n * @param mat\n * @return\n */\nPIC_INLINE float *getLinearArrayFromMatrix(Eigen::Matrix3f &mat)\n{\n    int n = int(mat.cols() * mat.rows());\n\n    float *ret = new float[n];\n    int c = 0;\n    for(int i = 0; i < mat.rows(); i++) {\n        for(int j = 0; j < mat.cols(); j++) {\n            ret[c] = mat(i, j);\n            c++;\n        }\n    }\n\n    return ret;\n}\n\n/**\n * @brief getMatrixFromLinearArray\n * @param array\n * @param rows\n * @param cols\n * @return\n */\nPIC_INLINE Eigen::MatrixXf getMatrixfFromLinearArray(float *array, int rows, int cols)\n{\n    Eigen::MatrixXf ret = Eigen::MatrixXf(rows, cols);\n\n    int c = 0;\n    for(int i = 0; i < rows; i++) {\n        for(int j = 0; j < cols; j++) {\n            ret(i, j) = array[c];\n            c++;\n        }\n    }\n    return ret;\n}\n\n/**\n * @brief getMatrixFromLinearArray\n * @param array\n * @param rows\n * @param cols\n * @return\n */\nPIC_INLINE Eigen::MatrixXd getMatrixdFromLinearArray(float *array, int rows, int cols)\n{\n    Eigen::MatrixXd ret = Eigen::MatrixXd(rows, cols);\n\n    int c = 0;\n    for(int i = 0; i < rows; i++) {\n        for(int j = 0; j < cols; j++) {\n            ret(i, j) = array[c];\n            c++;\n        }\n    }\n    return ret;\n}\n\n/**\n * @brief getMatrix3dFromLinearArray\n * @param array\n * @return\n */\nPIC_INLINE Eigen::Matrix3d getMatrix3dFromLinearArray(float *array)\n{\n    Eigen::Matrix3d ret;\n\n    int c = 0;\n    for(int i = 0; i < 3; i++) {\n        for(int j = 0; j < 3; j++) {\n            ret(i, j) = array[c];\n            c++;\n        }\n    }\n    return ret;\n}\n\n/**\n * @brief MatrixConvert\n * @param mat\n * @return\n */\nPIC_INLINE Eigen::Matrix3f MatrixConvert(Matrix3x3 &mat)\n{\n    Eigen::Matrix3f mtx;\n    mtx(0, 0) = mat.data[0];\n    mtx(0, 1) = mat.data[1];\n    mtx(0, 2) = mat.data[2];\n\n    mtx(1, 0) = mat.data[3];\n    mtx(1, 1) = mat.data[4];\n    mtx(1, 2) = mat.data[5];\n\n    mtx(2, 0) = mat.data[6];\n    mtx(2, 1) = mat.data[7];\n    mtx(2, 2) = mat.data[8];\n\n    return mtx;\n}\n\n/**\n * @brief ComputeNormalizationTransform\n * @param points\n * @return\n */\nPIC_INLINE Eigen::Vector3f ComputeNormalizationTransform(std::vector< Eigen::Vector2f > &points)\n{\n    Eigen::Vector3f ret;\n\n    if(points.size() < 2) {\n        return ret;\n    }\n\n    ret[0] = 0.0f;\n    ret[1] = 0.0f;\n\n    for(unsigned int i = 0; i < points.size(); i++) {\n        ret[0] += points[i][0];\n        ret[1] += points[i][1];\n    }\n\n    float n = float(points.size());\n    ret[0] /= n;\n    ret[1] /= n;\n\n    ret[2] = 0.0;\n    for(unsigned int i = 0; i < points.size(); i++) {\n\n        float dx = points[i][0] - ret[0];\n        float dy = points[i][1] - ret[1];\n\n        ret[2] += sqrtf(dx * dx + dy * dy);\n    }\n\n    ret[2] = ret[2] / n / sqrtf(2.0f);\n\n    return ret;\n}\n\n/**\n * @brief convertFromEigenToVec\n * @param x\n */\nPIC_INLINE Vec2i convertFromEigenToVec(Eigen::Vector2i &x)\n{\n    return Vec2i(x[0], x[1]);\n}\n\n#endif\n\n}\n\n#endif // PIC_EIGEN_UTIL\n", "meta": {"hexsha": "86ce8c28d8f4b79a6be8b97c879956321b53b856", "size": 11238, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/util/eigen_util.hpp", "max_stars_repo_name": "ecarpita93/HPC_projet_1", "max_stars_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "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": "include/util/eigen_util.hpp", "max_issues_repo_name": "ecarpita93/HPC_projet_1", "max_issues_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "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": "include/util/eigen_util.hpp", "max_forks_repo_name": "ecarpita93/HPC_projet_1", "max_forks_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "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": 19.4429065744, "max_line_length": 105, "alphanum_fraction": 0.5555258943, "num_tokens": 3798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5118060580948823}}
{"text": "#define BOOST_TEST_MODULE pcraster geo square\n#include <boost/test/unit_test.hpp>\n#include \"geo_square.h\"\n\n\nBOOST_AUTO_TEST_CASE(quad_square_at)\n{\n  using namespace geo;\n\n  typedef Point<float,2> Punt;\n  Punt c;\n  c[0]=20; c[1]=20;\n  typedef geo::Square<float,2> Kant;\n  Kant s(c,10);\n /*  2D:\n  *   NW 1(b) | NE 0(a)\n  *           0(e)\n  *  1(h)-----C---------0(g)\n  *   SW 3(c) | SE 2(d)\n  *           2(f)\n  */\n  Kant q;\n  q = s.quadSquareAt(0);\n  BOOST_CHECK(q.halfWidth()==5);\n  c[0]=25; c[1]=25;\n  BOOST_CHECK(q.centre()==c); // a\n\n  q = s.quadSquareAt(1);\n  BOOST_CHECK(q.halfWidth()==5);\n  c[0]=15; c[1]=25;\n  BOOST_CHECK(q.centre()==c); // b\n  c[0]=15; c[1]=15;\n  q = s.quadSquareAt(3);\n  BOOST_CHECK(q.centre()==c); // c\n  c[0]=25; c[1]=15;\n  q = s.quadSquareAt(2);\n  BOOST_CHECK(q.centre()==c); // d\n}\n\n\nBOOST_AUTO_TEST_CASE(contains)\n{\n  using namespace geo;\n\n  typedef Point<float,2> Punt;\n  Punt c; c[0]=20; c[1]=20;\n\n  // default boundary, closed\n  typedef geo::Square<float,2> Kant;\n  Kant s(c,10);\n  BOOST_CHECK(s.contains(c));\n\n  Punt p;\n  p[0]=12;p[1]=c[1];\n  BOOST_CHECK(s.contains(p));\n\n  p[0]=10; // on boundary\n  BOOST_CHECK(s.contains(p));\n\n\n  typedef geo::Square<float,2,OpenBoundaries> Open;\n  Open open(c,10);\n  // not the edge\n  BOOST_CHECK(!open.contains(p));\n\n  typedef geo::Square<float,2,ClosedBoundaries> Closed;\n  Closed closed(c,10);\n  // the edge is in\n  BOOST_CHECK(closed.contains(p));\n\n  typedef geo::Square<float,2,ClosedOpenBoundaries> ClosedOpen;\n  ClosedOpen closedOpen(c,10);\n  p[0]=10; // left/lower is closed\n  BOOST_CHECK( closedOpen.contains(p));\n  p[0]=30; // right/higher is open\n  BOOST_CHECK(!closedOpen.contains(p));\n\n  typedef geo::Square<float,2,OpenClosedBoundaries> OpenClosed;\n  OpenClosed openClosed(c,10);\n  p[0]=10; // left/lower is open\n  BOOST_CHECK(!openClosed.contains(p));\n  p[0]=30; // right/higher is closed\n  BOOST_CHECK( openClosed.contains(p));\n\n  {\n   typedef geo::Square<float,2,ClosedOpenBoundaries> OpenClosed;\n   OpenClosed oc(Punt(179020,330940),80);\n   BOOST_CHECK(!oc.contains(Punt(179973,332255)));\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(intersects)\n{\n  using namespace geo;\n\n  typedef Point<float,2> Punt;\n  Punt c(20,20);\n  // default boundary, closed\n  typedef geo::Square<float,2> Kant;\n  Kant s(c,10);\n  //! intersects with itself\n  BOOST_CHECK(s.intersects(s));\n\n  { // fully contained\n   Kant is(c,5);\n   BOOST_CHECK(is.intersects(s));\n   BOOST_CHECK(s.intersects(is));\n  }\n  { // partial\n    Kant is(Punt(15,15),8);\n    BOOST_CHECK(is.intersects(s));\n    BOOST_CHECK(s.intersects(is));\n  }\n  { // touch edge\n    Kant is(Punt(5,5),5);\n    BOOST_CHECK(is.intersects(s));\n    BOOST_CHECK(s.intersects(is));\n  }\n  { \n\t// no edge touch with open boundaries\n    typedef geo::Square<float,2,OpenBoundaries> OK;\n    OK os(c,10);\n    OK is(Punt(5,5),5);\n    BOOST_CHECK(!os.intersects(is));\n    BOOST_CHECK(!is.intersects(os));\n  }\n  { // no edge on in each other, midpoints \n\t// must be checked\n\t//\n\tKant os(Punt(74,6),40);\n\tKant is(Punt(0,0),60);\n    BOOST_CHECK( os.intersects(is));\n    BOOST_CHECK( is.intersects(os));\n  }\n  { // debug case\n    Kant os(Punt(2,20),1);\n    Kant is(Punt(0.78125f,21.0938f),0.78125f);\n    BOOST_CHECK( os.intersects(is));\n    BOOST_CHECK( is.intersects(os));\n  }\n}\n", "meta": {"hexsha": "ab8ceacee5d21d4b9de2a77204df530f1a3b19e8", "size": 3268, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_squaretest.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_squaretest.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_squaretest.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["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.8531468531, "max_line_length": 64, "alphanum_fraction": 0.6358629131, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5117878317815834}}
{"text": "/*\n * SigmoidTest.hpp\n *\n *  Created on: Dec 29, 2016\n *      Author: ken\n */\n\n#ifndef SIGMOIDTEST_HPP_\n#define SIGMOIDTEST_HPP_\n\n#include \"cute.h\"\n#include \"ide_listener.h\"\n#include \"xml_listener.h\"\n#include \"cute_runner.h\"\n#include <armadillo>\n#include <iostream>\n\n#include \"../src/layer/Sigmoid.hpp\"\n\nclass SigmoidTest {\npublic:\n\tSigmoidTest();\n\tvirtual ~SigmoidTest();\n\n\tstatic void feedForwardTest1();\n\tstatic void feedForwardTest2();\n\tstatic void backPropTest1();\n\tstatic void backPropTest2();\n};\n\n#endif /* SIGMOIDTEST_HPP_ */\n", "meta": {"hexsha": "00fdbea1c1b75ffd182f467945d2d56666a224cd", "size": 534, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/SigmoidTest.hpp", "max_stars_repo_name": "kenk42292/mochi", "max_stars_repo_head_hexsha": "79e65bc669812b37b5a38975fcada23b95206ac5", "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/SigmoidTest.hpp", "max_issues_repo_name": "kenk42292/mochi", "max_issues_repo_head_hexsha": "79e65bc669812b37b5a38975fcada23b95206ac5", "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/SigmoidTest.hpp", "max_forks_repo_name": "kenk42292/mochi", "max_forks_repo_head_hexsha": "79e65bc669812b37b5a38975fcada23b95206ac5", "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.6875, "max_line_length": 35, "alphanum_fraction": 0.7153558052, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.5117878283848569}}
{"text": "/// My typedefs\n#include <inttypes.h>\n#include <boost/cstdint.hpp>\n#include <boost/integer_traits.hpp>\n\ntypedef int32_t    node_t;\ntypedef int32_t    edge_t;\ntypedef int64_t    cost_t;\n\n/// From STL library\n#include <fstream>\n\n#include <vector>\nusing std::vector;\n\n#include <string>\n\nusing std::pair;\nusing std::make_pair;\n\n\n/// Lemon Graph Library\n#include <lemon/smart_graph.h>\nusing lemon::SmartDigraph;\n\n#include <lemon/adaptors.h>\n#include <lemon/concepts/maps.h>\n#include <lemon/dijkstra.h>\n#include <lemon/path.h>\ntypedef SmartDigraph::Arc  Arc;\ntypedef SmartDigraph::Node Node;\ntypedef SmartDigraph::ArcMap<cost_t>   LengthMap;\n\n#include <lemon/fib_heap.h>\ntypedef SmartDigraph::NodeMap<int>  NodeMap;\ntypedef lemon::FibHeap<cost_t, NodeMap> FibonacciHeap;\n\n/// Boost Timer\n#include <boost/progress.hpp>\nusing boost::timer;\n\nusing namespace boost;\n\n/// Read input data, build graph, and run Dijkstra\ncost_t runDijkstra( char* argv[] ) {\n   /// Read instance from the OR-lib\n   std::ifstream infile(argv[1]); \n   if (!infile) \n      exit ( EXIT_FAILURE ); \n\n   int n;     /// Number of variables\n   int m;     /// Number of constraints\n\n   // reads file of the form\n   // #nodes #edges\n   // e_1 = v_i v_j cost[e_m]\n   // ..\n   // e_m = v_i v_j cost[e_m]\n   \n   /// Read the first line\n   infile >> n >> m;\n   fprintf(stdout,\"n %d, m %d\\t\", n, m);\n   /// Build the graph \n   SmartDigraph G;\n   G.reserveNode(n);\n   G.reserveArc(m);\n   vector<Node> vs;\n   vs.reserve(n);\n   for ( int i = 0; i < n; ++i )\n      vs.push_back( G.addNode() );\n\n   int v, w;\n   cost_t c;\n   cost_t T_dist; \n   LengthMap    C(G);\n   for ( int i = 0; i < m; i++ ) {\n      infile >> v >> w >> c;\n      Arc a;\n      a = G.addArc(vs[v-1], vs[w-1]);\n      C[a] = c;\n   }\n   \n   timer TIMER;\n   for ( int i = 0; i < 50; ++i ) {\n      double t0 = TIMER.elapsed();\n      Node S = vs[i];\n      Node T = vs[n-1-i];\n      //NodeMap heap_cross_ref(G);\n      //FibonacciHeap heap(heap_cross_ref);\n      //lemon::Dijkstra<SmartDigraph, LengthMap>::SetHeap<FibonacciHeap, NodeMap>::Create spp(G, C);\n      //spp.heap( heap, heap_cross_ref );  \n      lemon::Dijkstra<SmartDigraph, LengthMap> spp(G, C);\n      spp.run(S,T);\n      T_dist = spp.dist(T);\n      fprintf(stdout,\"Time %.4f Cost %\"PRId64\"\\n\", TIMER.elapsed()-t0, T_dist);\n   }\n   fprintf(stdout,\"Tot %.4f\\n\", TIMER.elapsed());\n\n   return T_dist;\n}\n\n/// Main function\nint\nmain (int argc, char **argv)\n{\n   if ( argc != 2 ) {\n      fprintf(stdout, \"usage: ./dijkstra <filename>\\n\");\n      exit ( EXIT_FAILURE );\n   }\n   /// Measure overall time\n   timer TIMER;\n   /// Invoke the different Dijkstra algorithm implementations\n   cost_t T_dist = runDijkstra(argv);\n   /// Print basic figures\n   fprintf(stdout,\"Cost %\"PRId64\" - Time %.3f\\n\", T_dist, TIMER.elapsed());\n\n   return 0;\n}\n", "meta": {"hexsha": "473ef781d38170a725a14a5b6e62c9d7c4b615c2", "size": 2805, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Dijkstra/dijkstra_lemon.cc", "max_stars_repo_name": "772700563/MyBlogEntries", "max_stars_repo_head_hexsha": "ea579ab0698d59bc1af0fac08a059c16f11336c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T09:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T05:16:33.000Z", "max_issues_repo_path": "Dijkstra/dijkstra_lemon.cc", "max_issues_repo_name": "772700563/MyBlogEntries", "max_issues_repo_head_hexsha": "ea579ab0698d59bc1af0fac08a059c16f11336c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-07-08T03:27:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-21T19:35:11.000Z", "max_forks_repo_path": "Dijkstra/dijkstra_lemon.cc", "max_forks_repo_name": "772700563/MyBlogEntries", "max_forks_repo_head_hexsha": "ea579ab0698d59bc1af0fac08a059c16f11336c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-08-03T06:33:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T12:58:26.000Z", "avg_line_length": 23.5714285714, "max_line_length": 100, "alphanum_fraction": 0.6188948307, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925402, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5117878281550846}}
{"text": "/*\n * @file testRotateFactor.cpp\n * @brief Test RotateFactor class\n * @author Frank Dellaert\n * @date December 17, 2013\n */\n\n#include <gtsam/slam/RotateFactor.h>\n#include <gtsam/base/Testable.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/base/numericalDerivative.h>\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/bind.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <vector>\n\nusing namespace std;\nusing namespace boost::assign;\nusing namespace gtsam;\n\n//*************************************************************************\n// Create some test data\n// Let's assume IMU is aligned with aero (X-forward,Z down)\n// And camera is looking forward.\nPoint3 cameraX(0, 1, 0), cameraY(0, 0, 1), cameraZ(1, 0, 0);\nRot3 iRc(cameraX, cameraY, cameraZ);\n\n// Now, let's create some rotations around IMU frame\nUnit3 p1(1, 0, 0), p2(0, 1, 0), p3(0, 0, 1);\nRot3 i1Ri2 = Rot3::rodriguez(p1, 1), //\ni2Ri3 = Rot3::rodriguez(p2, 1), //\ni3Ri4 = Rot3::rodriguez(p3, 1);\n\n// The corresponding rotations in the camera frame\nRot3 c1Zc2 = iRc.inverse() * i1Ri2 * iRc, //\nc2Zc3 = iRc.inverse() * i2Ri3 * iRc, //\nc3Zc4 = iRc.inverse() * i3Ri4 * iRc;\n\n// The corresponding rotated directions in the camera frame\nUnit3 z1 = iRc.inverse() * p1, //\nz2 = iRc.inverse() * p2, //\nz3 = iRc.inverse() * p3;\n\ntypedef noiseModel::Isotropic::shared_ptr Model;\n\n//*************************************************************************\nTEST (RotateFactor, checkMath) {\n  EXPECT(assert_equal(c1Zc2, Rot3::rodriguez(z1, 1)));\n  EXPECT(assert_equal(c2Zc3, Rot3::rodriguez(z2, 1)));\n  EXPECT(assert_equal(c3Zc4, Rot3::rodriguez(z3, 1)));\n}\n\n//*************************************************************************\nTEST (RotateFactor, test) {\n  Model model = noiseModel::Isotropic::Sigma(3, 0.01);\n  RotateFactor f(1, i1Ri2, c1Zc2, model);\n  EXPECT(assert_equal(zero(3), f.evaluateError(iRc), 1e-8));\n\n  Rot3 R = iRc.retract((Vector(3) << 0.1, 0.2, 0.1));\n#if defined(GTSAM_ROT3_EXPMAP) || defined(GTSAM_USE_QUATERNIONS)\n  Vector expectedE = (Vector(3) << -0.0248752, 0.202981, -0.0890529);\n#else\n  Vector expectedE = (Vector(3) << -0.0246305, 0.20197, -0.08867);\n#endif\n  EXPECT( assert_equal(expectedE, f.evaluateError(R), 1e-5));\n\n  Matrix actual, expected;\n  // Use numerical derivatives to calculate the expected Jacobian\n  {\n    expected = numericalDerivative11<Rot3>(\n        boost::bind(&RotateFactor::evaluateError, &f, _1, boost::none), iRc);\n    f.evaluateError(iRc, actual);\n    EXPECT(assert_equal(expected, actual, 1e-9));\n  }\n  {\n    expected = numericalDerivative11<Rot3>(\n        boost::bind(&RotateFactor::evaluateError, &f, _1, boost::none), R);\n    f.evaluateError(R, actual);\n    EXPECT(assert_equal(expected, actual, 1e-9));\n  }\n}\n\n//*************************************************************************\nTEST (RotateFactor, minimization) {\n  // Let's try to recover the correct iRc by minimizing\n  NonlinearFactorGraph graph;\n  Model model = noiseModel::Isotropic::Sigma(3, 0.01);\n  graph.add(RotateFactor(1, i1Ri2, c1Zc2, model));\n  graph.add(RotateFactor(1, i2Ri3, c2Zc3, model));\n  graph.add(RotateFactor(1, i3Ri4, c3Zc4, model));\n\n  // Check error at ground truth\n  Values truth;\n  truth.insert(1, iRc);\n  EXPECT_DOUBLES_EQUAL(0, graph.error(truth), 1e-8);\n\n  // Check error at initial estimate\n  Values initial;\n  double degree = M_PI / 180;\n  Rot3 initialE = iRc.retract(degree * (Vector(3) << 20, -20, 20));\n  initial.insert(1, initialE);\n\n#if defined(GTSAM_ROT3_EXPMAP) || defined(GTSAM_USE_QUATERNIONS)\n  EXPECT_DOUBLES_EQUAL(3545.40, graph.error(initial), 1);\n#else\n  EXPECT_DOUBLES_EQUAL(3349, graph.error(initial), 1);\n#endif\n\n  // Optimize\n  LevenbergMarquardtParams parameters;\n  //parameters.setVerbosity(\"ERROR\");\n  LevenbergMarquardtOptimizer optimizer(graph, initial, parameters);\n  Values result = optimizer.optimize();\n\n  // Check result\n  Rot3 actual = result.at<Rot3>(1);\n  EXPECT(assert_equal(iRc, actual,1e-1));\n\n  // Check error at result\n  EXPECT_DOUBLES_EQUAL(0, graph.error(result), 1e-4);\n}\n\n//*************************************************************************\nTEST (RotateDirectionsFactor, test) {\n  Model model = noiseModel::Isotropic::Sigma(2, 0.01);\n  RotateDirectionsFactor f(1, p1, z1, model);\n  EXPECT(assert_equal(zero(2), f.evaluateError(iRc), 1e-8));\n\n  Rot3 R = iRc.retract((Vector(3) << 0.1, 0.2, 0.1));\n\n#if defined(GTSAM_ROT3_EXPMAP) || defined(GTSAM_USE_QUATERNIONS)\n  Vector expectedE = (Vector(2) << -0.0890529, -0.202981);\n#else\n  Vector expectedE = (Vector(2) << -0.08867, -0.20197);\n#endif\n\n  EXPECT( assert_equal(expectedE, f.evaluateError(R), 1e-5));\n\n  Matrix actual, expected;\n  // Use numerical derivatives to calculate the expected Jacobian\n  {\n    expected = numericalDerivative11<Rot3>(\n        boost::bind(&RotateDirectionsFactor::evaluateError, &f, _1,\n            boost::none), iRc);\n    f.evaluateError(iRc, actual);\n    EXPECT(assert_equal(expected, actual, 1e-9));\n  }\n  {\n    expected = numericalDerivative11<Rot3>(\n        boost::bind(&RotateDirectionsFactor::evaluateError, &f, _1,\n            boost::none), R);\n    f.evaluateError(R, actual);\n    EXPECT(assert_equal(expected, actual, 1e-9));\n  }\n}\n\n//*************************************************************************\nTEST (RotateDirectionsFactor, minimization) {\n  // Let's try to recover the correct iRc by minimizing\n  NonlinearFactorGraph graph;\n  Model model = noiseModel::Isotropic::Sigma(2, 0.01);\n  graph.add(RotateDirectionsFactor(1, p1, z1, model));\n  graph.add(RotateDirectionsFactor(1, p2, z2, model));\n  graph.add(RotateDirectionsFactor(1, p3, z3, model));\n\n  // Check error at ground truth\n  Values truth;\n  truth.insert(1, iRc);\n  EXPECT_DOUBLES_EQUAL(0, graph.error(truth), 1e-8);\n\n  // Check error at initial estimate\n  Values initial;\n  double degree = M_PI / 180;\n  Rot3 initialE = iRc.retract(degree * (Vector(3) << 20, -20, 20));\n  initial.insert(1, initialE);\n\n#if defined(GTSAM_ROT3_EXPMAP) || defined(GTSAM_USE_QUATERNIONS)\n  EXPECT_DOUBLES_EQUAL(3335.9, graph.error(initial), 1);\n#else\n  EXPECT_DOUBLES_EQUAL(3162, graph.error(initial), 1);\n#endif\n\n  // Optimize\n  LevenbergMarquardtParams parameters;\n  //parameters.setVerbosity(\"ERROR\");\n  LevenbergMarquardtOptimizer optimizer(graph, initial, parameters);\n  Values result = optimizer.optimize();\n\n  // Check result\n  Rot3 actual = result.at<Rot3>(1);\n  EXPECT(assert_equal(iRc, actual,1e-1));\n\n  // Check error at result\n  EXPECT_DOUBLES_EQUAL(0, graph.error(result), 1e-4);\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n\n", "meta": {"hexsha": "f3640531831e8441296cfd688f69cb85497e148c", "size": 6801, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/slam/tests/testRotateFactor.cpp", "max_stars_repo_name": "ashariati/gtsam-3.2.1", "max_stars_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T08:58:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T08:01:42.000Z", "max_issues_repo_path": "gtsam/slam/tests/testRotateFactor.cpp", "max_issues_repo_name": "ashariati/gtsam-3.2.1", "max_issues_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T16:21:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-13T16:50:42.000Z", "max_forks_repo_path": "gtsam/slam/tests/testRotateFactor.cpp", "max_forks_repo_name": "ashariati/gtsam-3.2.1", "max_forks_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2015-06-01T11:22:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T11:03:57.000Z", "avg_line_length": 33.0145631068, "max_line_length": 79, "alphanum_fraction": 0.6377003382, "num_tokens": 2049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5117878249881307}}
{"text": "/**\n * @example eigenverb/test/eigenverb_test.cc\n */\n\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/foreach.hpp>\n#include <boost/progress.hpp>\n#include <usml/waveq3d/waveq3d.h>\n#include <usml/eigenverb/eigenverb_collection.h>\n#include <usml/eigenverb/envelope_collection.h>\n#include <usml/eigenverb/eigenverb_interpolator.h>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <iostream>     // std::cout, std::fixed\n#include <iomanip>      // std::setprecision\n\nBOOST_AUTO_TEST_SUITE(eigenverb_test)\n\nusing namespace boost::unit_test;\nusing namespace usml::waveq3d;\n\n/**\n * @ingroup eigenverb_test\n * @{\n */\n\nstatic const double time_step = 0.100 ;\nstatic const double src_lat = 45.0;        // location = mid-Atlantic\nstatic const double src_lng = -45.0;\nstatic const double c0 = 1500.0;           // constant sound speed\n\n/**\n * Tests the basic features of the eigenverb generation process.\n *\n *   - Profile: constant 1500 m/s sound speed, Thorp absorption\n *   - Bottom: 1000 meters, sand\n *   - Source: 45N, 45W, on surface, 1000 Hz\n *   - Interfaces: bottom, surface, and volume\n *   - Time Step: 100 msec\n *   - Launch D/E: 5 degree linear spacing from -60 to 60 degrees\n *   - Launch AZ: 10 degree linear spacing from -40 to 40 degrees\n *\n * Automatically checks the accuracy of the eigenverbs for the bottom\n * to the analytic solution in the reverberation paper.\n *\n * To maximize accuracy we compute path length and angles on a round earth\n * with a flat bottom, using eqn. (25) - (27) from the verification test report.\n * For a path with a given DE (where negative is down), the path length for\n * the first interaction with the bottom is found by solving eqn. (25) for L:\n * <pre>\n *     Rb^2 = R^2 + L^2 - 2 R L sin(DE)\n *     L^2 - 2 R L sin(DE) + (R^2 - Rb^2) = 0\n * </pre>\n * where\n * \t\t- R = source distance from earth center,\n *\t\t- Rb = bottom distance from earth center,\n *\t\t- DE = launch D/E angle, and\n *\t\t- P = path length.\n *\n * The quadratic equation solution for the path length is\n * <pre>\n * \t\tp = R sin(abs(DE))\n * \t\tq = R^2 - Rb^2\n * \t\tL = p - sqrt( p*p - q )\n * </pre>\n * The negative root has been chosen to make an acute angle between Rs and Rb.\n * The angle between Rs and Rb is given by:\n * <pre>\n * \t\tL^2 = R^2 + Rb^2 - 2 R Rb cos(alpha) ;\n * \t\talpha = acos[ ( Rs^2 + Rb^2 - L^2 ) / (2 Rs Rb) ]\n * </pre>\n * The time of arrival and grazing angle are given by:\n * <pre>\n * \t\ttime = L / c ;\n * \t\tgrazing = DE - alpha\n * </pre>\n * The length and width of the eigenverb are computed using\n * <pre>\n * \t\tlength = L * dDe / sin(grazing)\n * \t\twidth = L * dAZ * cos(DE)\n * \t</pre>\n * where\n * \t\t- dDE = initial spacing between rays in DE direction (radians)\n * \t\t- dAZ = initial spacing between rays in AZ direction (radians)\n *\n * @xref Sean Reilly, David Thibaudeau, Ted Burns,\n * \t\t \"Fast computation of reverberation using Gaussian beam reflections\",\n * \t\t report prepared for NAWCTSD\n * @xref Sean Reilly, Gopu Potty, \"Verification Tests for Hybrid Gaussian\n *\t\t Beams in Spherical/Time Coordinates\", 10 May 2012.\n */\nBOOST_AUTO_TEST_CASE( eigenverb_basic ) {\n    cout << \"=== eigenverb_test: eigenverb_basic ===\" << endl;\n    const char* ncname = USML_TEST_DIR \"/eigenverb/test/eigenverb_basic_\";\n    const double time_max = 3.5;\n    const double depth = 1000.0 ;\n    const double de_spacing = 5.0 ;\n    const double az_spacing = 10.0 ;\n\n    // initialize propagation model\n\n\tprofile_model* profile = new profile_linear(c0);\n\tboundary_model* surface = new boundary_flat();\n\treflect_loss_model* bottom_loss = new reflect_loss_rayleigh(reflect_loss_rayleigh::SAND) ;\n\tboundary_model* bottom = new boundary_flat(depth,bottom_loss);\n\tocean_model ocean(surface, bottom, profile);\n\tvolume_model* layer = new volume_flat(300.0, 10.0, -40.0);\n\tocean.add_volume(layer);\n\n    seq_log freq( 1000.0, 10.0, 1 );\n    wposition1 pos( src_lat, src_lng, 0.0 );\n    seq_linear de( -80.0, de_spacing, 60.0 );\n    seq_linear az( -40.0, az_spacing, 40.1 );\n\n    // build a wavefront that just generates eigenverbs\n\n    eigenverb_collection* eigenverbs = new eigenverb_collection( ocean.num_volume() ) ;\n    wave_queue wave( ocean, freq, pos, de, az, time_step ) ;\n    wave.add_eigenverb_listener(eigenverbs) ;\n\n    while ( wave.time() < time_max ) {\n        wave.step();\n    }\n\n    // record eigenverbs for each interface to their own disk file\n\n    for ( int n=0 ; n < eigenverbs->num_interfaces() ; ++n ) {\n    \tstd::ostringstream filename ;\n    \tfilename << ncname << n << \".nc\" ;\n    \teigenverbs->write_netcdf( filename.str().c_str(),n) ;\n    }\n\n    // test the accuracy of the eigenverb contributions\n    // just tests downward facing rays to the bottom, along az=0\n\n    const eigenverb_list& list = eigenverbs->eigenverbs(eigenverb::BOTTOM) ;\n    BOOST_FOREACH( eigenverb verb, list ) {\n\t\tif ( verb.source_de < 0.0 && verb.source_az == 0.0 ) {\n\n\t\t\t// compute path length to first bottom bounce on a spherical earth\n\n\t\t\tint segments = verb.bottom + verb.surface + 1;\n\t\t\tdouble R = wposition::earth_radius ;\n\t\t\tdouble Rb = wposition::earth_radius - depth ;\n\t\t\tdouble p = R * sin(abs(verb.source_de)) ;\n\t\t\tdouble q = R * R - Rb * Rb ;\n\t\t\tdouble path_length = p - sqrt( p*p - q ) ; // quadratic equation\n\n\t\t\t// compute gazing angle, complete path length, and time of arrival\n\n\t\t\tdouble alpha = acos( ( R * R + Rb * Rb - path_length * path_length )\n\t\t\t\t\t/ ( 2 * R * Rb ) ) ;\n\t\t\tdouble grazing = abs(verb.source_de) - alpha ;\n\t\t\tpath_length *= segments ;\n\t\t\tdouble time = path_length / c0 ;\n\n\t\t\t// compute height, width, and area area centered on ray\n\n\t\t\tconst double de_angle = verb.source_de ;\n\t\t\tconst double de_plus  = de_angle + 0.5 * to_radians(de_spacing) ;\n\t\t\tconst double de_minus = de_angle - 0.5 * to_radians(de_spacing) ;\n\n\t\t\tconst double az_angle = verb.source_az ;\n\t\t\tconst double az_plus  = az_angle + 0.5 * to_radians(az_spacing) ;\n\t\t\tconst double az_minus = az_angle - 0.5 * to_radians(az_spacing) ;\n\n\t\t\tconst double area = (sin(de_plus) - sin(de_minus)) * (az_plus - az_minus);\n\t\t\tconst double de_delta = de_plus - de_minus ;\t// average height\n\t\t\tconst double az_delta = area / de_delta ;\t\t// average width\n\n\t\t\tdouble verb_length = path_length * de_delta / sin(grazing) ;\n\t\t\tdouble verb_width = path_length * az_delta ;\n\n\t\t\t// compare to results computed by model\n\t\t\t// \t  - accuracy of length/width just based on prior measurements,\n\t\t\t//    - length/width errors as high as 0.1 meters would still be good\n\n\t\t\tcout << std::fixed << std::setprecision(4)\n\t\t\t\t << \"de=\" << to_degrees(verb.source_de)\n\t\t\t\t << \" s=\" << verb.surface\n\t\t\t\t << \" b=\" << verb.bottom\n\t\t\t\t << \"\\tL=\" << sqrt(verb.length2)\n\t\t\t\t << \" theory=\" << verb_length\n\t\t\t\t << \"\\tW=\" << sqrt(verb.width2)\n\t\t\t\t << \" theory=\" << verb_width\n\t\t\t\t << endl ;\n\t\t\tBOOST_CHECK_SMALL( verb.time-time, 1e-3 ) ;\n\t\t\tBOOST_CHECK_SMALL( verb.grazing-grazing, 1e-6 ) ;\n\t\t\tBOOST_CHECK_SMALL( verb.direction-verb.source_az, 1e-6 ) ;\n\t\t\tBOOST_CHECK_SMALL( sqrt(verb.length2) - verb_length, 0.005 ) ;\n\t\t\tBOOST_CHECK_SMALL( sqrt(verb.width2) - verb_width, 0.005 ) ;\n\t\t}\n    }\n\n    // clean up and exit\n\n    delete eigenverbs ;\n}\n\n/**\n * Tests the the eigenverb generation process using conditions like\n * those used in the eigenverb_demo.m scenario.\n *\n *   - Profile: constant 1500 m/s sound speed, no absorption\n *   - Bottom: 200 meters, sand\n *   - Source: 45N, 45W, on surface, 1000 Hz\n *   - Interfaces: bottom and surface, but limit to 2 bounces\n *   - Time Step: 100 msec\n *   - Launch D/E: 91 tangent spaced rays from -90 to +90 degrees\n *   - Launch AZ: Rays in the range [0,360) with 20 degree spacing.\n *\n * The primary motivation for this test is to generate an eigenverb netCDF\n * file that can be used to support off-line comparisons to the\n * eigenverb_demo.m scenario. The secondary motivation is to test un-even\n * ray spacing and test limiting the outputs to direct path. In addition to\n * these goals, it also automatically checks the accuracy of the eigenverbs\n * for the bottom to the analytic solution in the reverberation paper.\n */\nBOOST_AUTO_TEST_CASE( eigenverb_analytic ) {\n    cout << \"=== eigenverb_test: eigenverb_analytic ===\" << endl;\n    const char* ncname = USML_TEST_DIR \"/eigenverb/test/eigenverb_analytic_\";\n    const char* ncname_wave = USML_TEST_DIR \"/eigenverb/test/eigenverb_analytic_wave.nc\";\n    const double time_max = 4.0;\n    const double depth = 200.0 ;\n\n    // initialize propagation model\n\n    attenuation_model* attn = new attenuation_constant(0.0);\n\tprofile_model* profile = new profile_linear(c0, attn);\n\tboundary_model* surface = new boundary_flat();\n\treflect_loss_model* bottom_loss = new reflect_loss_rayleigh(reflect_loss_rayleigh::SAND) ;\n\tboundary_model* bottom = new boundary_flat(depth,bottom_loss);\n\tocean_model ocean(surface, bottom, profile);\n\n    seq_log freq( 1000.0, 10.0, 1 );\n    wposition1 pos( src_lat, src_lng, 0.0 );\n    seq_rayfan de( -90.0, 90.0, 181 );\n    seq_linear az( 0.0, 20.0, 359.0 );\n\n    // build a wavefront that just generates eigenverbs\n\n    eigenverb_collection* eigenverbs = new eigenverb_collection( ocean.num_volume() ) ;\n    wave_queue wave( ocean, freq, pos, de, az, time_step ) ;\n    wave.add_eigenverb_listener(eigenverbs) ;\n    wave.max_bottom(2) ;\n    wave.max_surface(2) ;\n\n    cout << \"writing wavefronts to \" << ncname_wave << endl;\n    wave.init_netcdf( ncname_wave );\n    wave.save_netcdf();\n    while ( wave.time() < time_max ) {\n        wave.step();\n        wave.save_netcdf();\n    }\n    wave.close_netcdf();\n\n    // record eigenverbs for each interface to their own disk file\n\n    for ( int n=0 ; n < eigenverbs->num_interfaces() ; ++n ) {\n    \tstd::ostringstream filename ;\n    \tfilename << ncname << n << \".nc\" ;\n    \teigenverbs->write_netcdf( filename.str().c_str(),n) ;\n    }\n\n    // test the accuracy of the eigenverb contributions\n    // just tests downward facing rays to the bottom, along az=0\n    // because those are the rays which we have analytic solutions for\n\n    const eigenverb_list& list = eigenverbs->eigenverbs(eigenverb::BOTTOM) ;\n    BOOST_FOREACH( eigenverb verb, list ) {\n\t\tif ( verb.source_de < 0.0 && verb.source_az == 0.0\n\t\t\t&& verb.surface == 0 && verb.bottom == 0 )\n\t\t{\n\n\t\t\t// compute path length to first bottom bounce on a spherical earth\n\n\t\t\tint segments = verb.bottom + verb.surface + 1;\n\t\t\tdouble R = wposition::earth_radius ;\n\t\t\tdouble Rb = wposition::earth_radius - depth ;\n\t\t\tdouble p = R * sin(abs(verb.source_de)) ;\n\t\t\tdouble q = R * R - Rb * Rb ;\n\t\t\tdouble path_length = p - sqrt( p*p - q ) ; // quadratic equation\n\n\t\t\t// compute gazing angle, complete path length, and time of arrival\n\n\t\t\tdouble alpha = acos( ( R * R + Rb * Rb - path_length * path_length )\n\t\t\t\t\t/ ( 2 * R * Rb ) ) ;\n\t\t\tdouble grazing = abs(verb.source_de) - alpha ;\n\t\t\tpath_length *= segments ;\n\t\t\tdouble time = path_length / c0 ;\n\n\t\t\t// compute height, width, and area area centered on ray\n\n\t\t\tconst double de_angle = verb.source_de ;\n\t\t\tconst double de_plus  = de_angle\n\t\t\t\t+ 0.5 * to_radians( de.increment(verb.de_index) ) ;\n\t\t\tconst double de_minus = de_angle\n\t\t\t\t- 0.5 * to_radians( de.increment(verb.de_index-1) ) ;\n\n\t\t\tconst double az_angle = verb.source_az ;\n\t\t\tconst double az_plus  = az_angle\n\t\t\t\t+ 0.5 * to_radians( az.increment(verb.az_index) ) ;\n\t\t\tconst double az_minus = az_angle\n\t\t\t\t- 0.5 * to_radians( az.increment(verb.az_index-1) ) ;\n\n\t\t\tconst double area = (sin(de_plus) - sin(de_minus)) * (az_plus - az_minus);\n\t\t\tconst double de_delta = de_plus - de_minus ;\t// average height\n\t\t\tconst double az_delta = area / de_delta ;\t\t// average width\n\n\t\t\tdouble verb_length = path_length * de_delta / sin(grazing) ;\n\t\t\tdouble verb_width = path_length * az_delta ;\n\n\t\t\t// compare to results computed by model\n\t\t\t// \t  - accuracy of length/width just based on prior measurements,\n\t\t\t//    - length/width errors as high as 0.1 meters would still be good\n\n\t\t\tcout << std::fixed << std::setprecision(4)\n\t\t\t\t << \"de=\" << to_degrees(verb.source_de)\n\t\t\t\t << \" s=\" << verb.surface\n\t\t\t\t << \" b=\" << verb.bottom\n\t\t\t\t << \"\\tL=\" << sqrt(verb.length2)\n\t\t\t\t << \" theory=\" << verb_length\n\t\t\t\t << \"\\tW=\" << sqrt(verb.width2)\n\t\t\t\t << \" theory=\" << verb_width\n\t\t\t\t << endl ;\n\t\t\tBOOST_CHECK_SMALL( verb.time-time, 1e-3 ) ;\n\t\t\tBOOST_CHECK_SMALL( verb.grazing-grazing, 1e-6 ) ;\n\t\t\tBOOST_CHECK_SMALL( verb.direction-verb.source_az, 1e-6 ) ;\n\t\t\tBOOST_CHECK_SMALL( sqrt(verb.length2)-verb_length, 0.05 ) ;\n\t\t\tBOOST_CHECK_SMALL( sqrt(verb.width2)-verb_width, 0.05 ) ;\n\t\t}\n    }\n\n    // clean up and exit\n\n    delete eigenverbs ;\n}\n\n/**\n * Test the ability to generate a individual envelope contributions and\n * write envelopes out to netCDF.  The eigenverbs are filled in \"by hand\"\n * instead of being calculated from physical principles. This gives us\n * better isolation between the testing of the eigenverb and envelope models.\n *\n *   - Profile: constant 1500 m/s sound speed\n *   - Frequencies: 1000, 2000, 3000 Hz\n *   - Scattering strength = 0.10, 0.11, 0.12 (linear units)\n *   - Pulse length = 1.0 sec\n *   - Grazing angle = 30 deg\n *   - Depth 1000 meters.\n *   - Eigenverb Power = 0.2. 0.2, 0.2 (linear units)\n *   - Eigenverb length = 20.0 meters\n *   - Eigenverb width = 10.0 meters\n *\n * One envelope contribution is created at a round trip travel time of\n * 10 seconds.  A second contribution, with have the power, is created\n * at 30 seconds. This tests the ability to accumulate an envelope from\n * multiple contributions.\n *\n * Automatically compares the peaks of the first contribution to the\n * monostatic solution.\n * $f[\n *\t\tI_{monostatic} = \\frac{ 0.5 T_0 E_s^2 \\sigma }\n *\t\t\t\t\t\t\t  { Tsr \\sqrt{ 4 L_s^2 W_s^2 } }\n * $f]\n * Writes reverberation envelopes to the envelope_basic.nc files.\n */\nBOOST_AUTO_TEST_CASE( envelope_basic ) {\n    cout << \"=== eigenverb_test: envelope_basic ===\" << endl;\n    const char* ncname = USML_TEST_DIR \"/eigenverb/test/envelope_basic.nc\";\n\n    // setup scenario for 30 deg D/E in 1000 meters of water\n\n    double angle = M_PI / 6.0 ;\n    double depth = 1000.0 ;\n    double range = sqrt(3.0) * depth / ( 1852.0 * 60.0 );\n    double power = 0.2 ;\n    double pulse_length = 1.0 ;\n\n\t// build a simple eigenverb\n\n\teigenverb verb ;\n\tverb.time = 0.0 ;\n\tverb.position = wposition1(range,0.0,-depth) ;\n\tverb.direction = 0.0 ;\n\tverb.grazing = angle ;\n\tverb.sound_speed = c0 ;\n\tverb.de_index = 0 ;\n\tverb.az_index = 0 ;\n\tverb.source_de = -angle ;\n\tverb.source_az = 0.0 ;\n\tverb.surface = 0 ;\n\tverb.bottom = 0 ;\n\tverb.caustic = 0 ;\n\tverb.upper = 0 ;\n\tverb.lower = 0 ;\n\n\tseq_linear freq(1000.0,1000.0,3) ;\n\tverb.frequencies = &freq ;\n\tverb.power = vector<double>( freq.size(), power ) ;\n\tverb.length = 20.0 ;\n\tverb.width = 10.0 ;\n\tverb.length2 = verb.length * verb.length ;\n\tverb.width2 = verb.width * verb.width ;\n\n\t// construct an envelope_collection\n\n\tconst seq_vector* travel_time = new seq_linear(0.0,0.1,400.0) ;\n\tenvelope_collection envelopes(\n\t\t&freq,\t\t\t// envelope_freq\n\t\t0,\t\t\t\t// src_freq_first\n\t\ttravel_time,\t// travel_time, cloned by model\n\t\t40.0,\t\t\t// reverb_duration\n\t\tpulse_length,\t// pulse_length\n\t\t1e-30,\t\t\t// threshold\n\t\t1, \t\t\t\t// num_azimuths\n\t\t1, \t\t\t\t// num_src_beams\n\t\t1,   \t\t\t// num_rcv_beams\n\t\t0.0,            // initial_time - fill the api\n\t\t1,              // source_id - fill the api\n\t\t1,              // receiver_id - fill the api\n\t\twposition1(0.0,0.0),   // src_pos - fill the api\n\t    wposition1(0.0,0.0) ); // rcv_pos - fill the api\n\n    delete travel_time;\n\n\tvector<double> scatter( freq.size() ) ;\n\tmatrix<double> src_beam( freq.size(), 1, 1.0 ) ;\n\tmatrix<double> rcv_beam( freq.size(), 1, 1.0 ) ;\n\tfor ( size_t f=0 ; f < freq.size() ; ++f ) {\n\t\tscatter[f] = 0.1 + 0.01 * f ;\n\t}\n\n\t// add contributions at t=10 and t=30 sec\n\n\tverb.time = 5.0 ;\n\tenvelopes.add_contribution( verb, verb,\n\t\tsrc_beam, rcv_beam, scatter, 0.0, 0.0 ) ;\n\n\tverb.time = 15.0 ;\n\tverb.power *= 0.5 ;\n\tenvelopes.add_contribution( verb, verb,\n\t\t\tsrc_beam, rcv_beam, scatter, 0.0, 0.0 ) ;\n\n\tenvelopes.write_netcdf(ncname) ;\n\n\t// compare intensity to analytic solution for monostatic result (eqn. 31).\n\t// - divides total energy by duration to estimate peak\n\t// - note that (Ls2+Lr2)*(Ws2+Wr2) = 2 Ls2 Ws2 when s=r\n\t// - includes extra 4 pi in denominator, based on Matlab results\n\n\tdouble factor = cos(angle) / c0 ;\n\tdouble sigma2 = verb.length2 / 2.0 ;\n\tdouble duration = 0.5 * sqrt( pulse_length*pulse_length + factor*factor*sigma2 ) ;\n\tvector<double> theory = 10.0*log10(\n\t\t\t0.25 * 0.5 * pulse_length * power * power * scatter\n\t\t\t/ sqrt(4.0 * verb.length2 * verb.width2) / duration ) ;\n\tsize_t index = 105 ;\n\tcout << \"duration=\" << duration << endl;\n\tfor (size_t f = 0; f < freq.size(); ++f) {\n\t\tdouble model = 10.0*log10(envelopes.envelope(0,0,0)(f,index));\n\t\tcout << \"theory=\" << theory[f] << \" model=\" << model << endl;\n\t\tBOOST_CHECK_SMALL( abs(model-theory[f]), 1e-4);\n\t}\n}\n\n/**\n * Test the ability to compute source and receiver eigenverbs at different\n * frequencies.  Similar to envelope_basic test except that:\n *\n * \t\t- source and receiver are at different frequencies\n * \t\t- receiver is interpolated onto envelope frequency axis\n * \t\t- result is limited to first two source frequencies\n */\nBOOST_AUTO_TEST_CASE( envelope_interpolate ) {\n    cout << \"=== eigenverb_test: envelope_interpolate ===\" << endl;\n    const char* ncname = USML_TEST_DIR \"/eigenverb/test/envelope_interpolate.nc\";\n\n    // setup scenario for 30 deg D/E in 1000 meters of water\n\n    double angle = M_PI / 6.0 ;\n    double depth = 1000.0 ;\n    double range = sqrt(3.0) * depth / ( 1852.0 * 60.0 );\n    double power = 0.2 ;\n    double pulse_length = 1.0 ;\n\n\t// build a simple source eigenverb\n\n\teigenverb src_verb ;\n\tsrc_verb.time = 0.0 ;\n\tsrc_verb.position = wposition1(range,0.0,-depth) ;\n\tsrc_verb.direction = 0.0 ;\n\tsrc_verb.grazing = angle ;\n\tsrc_verb.sound_speed = c0 ;\n\tsrc_verb.de_index = 0 ;\n\tsrc_verb.az_index = 0 ;\n\tsrc_verb.source_de = -angle ;\n\tsrc_verb.source_az = 0.0 ;\n\tsrc_verb.surface = 0 ;\n\tsrc_verb.bottom = 0 ;\n\tsrc_verb.caustic = 0 ;\n\tsrc_verb.upper = 0 ;\n\tsrc_verb.lower = 0 ;\n\n\tseq_linear src_freq(1000.0,1000.0,3) ;\n\tsrc_verb.frequencies = &src_freq ;\n\tsrc_verb.power = vector<double>( src_freq.size(), power ) ;\n\tsrc_verb.length = 20.0 ;\n\tsrc_verb.width = 10.0 ;\n\tsrc_verb.length2 = src_verb.length * src_verb.length ;\n\tsrc_verb.width2 = src_verb.width * src_verb.width ;\n\n\t// build a simple receiver eigenverb\n\t// identical to src_verb except for frequency axis\n\n\teigenverb rcv_verb_original ;\n\trcv_verb_original.time = 0.0 ;\n\trcv_verb_original.position = wposition1(range,0.0,-depth) ;\n\trcv_verb_original.direction = 0.0 ;\n\trcv_verb_original.grazing = angle ;\n\trcv_verb_original.sound_speed = c0 ;\n\trcv_verb_original.de_index = 0 ;\n\trcv_verb_original.az_index = 0 ;\n\trcv_verb_original.source_de = -angle ;\n\trcv_verb_original.source_az = 0.0 ;\n\trcv_verb_original.surface = 0 ;\n\trcv_verb_original.bottom = 0 ;\n\trcv_verb_original.caustic = 0 ;\n\trcv_verb_original.upper = 0 ;\n\trcv_verb_original.lower = 0 ;\n\n\tseq_linear rcv_freq(500.0,200.0,10) ;\n\trcv_verb_original.frequencies = &rcv_freq ;\n\trcv_verb_original.power = vector<double>( rcv_freq.size(), power ) ;\n\trcv_verb_original.length = 20.0 ;\n\trcv_verb_original.width = 10.0 ;\n\trcv_verb_original.length2 = rcv_verb_original.length * rcv_verb_original.length ;\n\trcv_verb_original.width2 = rcv_verb_original.width * rcv_verb_original.width ;\n\n\t// interpolate rcv_verb_original onto frequency axis of envelope\n\n\tseq_linear envelope_freq( 1000.0, 1000.0, 2 ) ;\n\teigenverb rcv_verb ;\n\trcv_verb.frequencies = &envelope_freq ;\n\trcv_verb.power = vector<double>( envelope_freq.size() ) ;\n\n\teigenverb_interpolator interpolator( &rcv_freq,  &envelope_freq ) ;\n\tinterpolator.interpolate( rcv_verb_original, &rcv_verb ) ;\n\n\t// construct an envelope_collection\n\n\tconst seq_vector* travel_time = new seq_linear(0.0,0.1,400.0) ;\n\tenvelope_collection envelopes(\n\t\t&envelope_freq,\t\t\t// envelope_freq\n\t\t0,\t\t\t\t// src_freq_first\n\t\ttravel_time,\t// travel_time, cloned by model\n\t\t40.0,\t\t\t// reverb_duration\n\t\t1.0, \t\t\t// pulse_length\n\t\t1e-30,\t\t\t// threshold\n\t\t1, \t\t\t\t// num_azimuths\n\t\t1, \t\t\t\t// num_src_beams\n\t\t1,              // num_rcv_beams\n\t\t0.0,            // initial_time - fill the api\n        1,              // source_id - fill the api\n        1,              // receiver_id - fill the api\n        wposition1(0.0,0.0),   // src_pos - fill the api\n        wposition1(0.0,0.0) ); // rcv_pos - fill the api\n\n    delete travel_time;\n\n\tvector<double> scatter( envelope_freq.size() ) ;\n\tmatrix<double> src_beam( envelope_freq.size(), 1, 1.0 ) ;\n\tmatrix<double> rcv_beam( envelope_freq.size(), 1, 1.0 ) ;\n\tfor ( size_t f=0 ; f < envelope_freq.size() ; ++f ) {\n\t\tscatter[f] = 0.1 + 0.01 * f ;\n\t}\n\n\t// add contributions at t=10 and t=30 sec\n\n\tsrc_verb.time = 5.0 ;\n\trcv_verb.time = 5.0 ;\n\tenvelopes.add_contribution( src_verb, rcv_verb,\n\t\tsrc_beam, rcv_beam, scatter, 0.0, 0.0 ) ;\n\n\tsrc_verb.time = 15.0 ;\n\trcv_verb.time = 15.0 ;\n\tsrc_verb.power *= 0.5 ;\n\trcv_verb.power *= 0.5 ;\n\tenvelopes.add_contribution( src_verb, rcv_verb,\n\t\t\tsrc_beam, rcv_beam, scatter, 0.0, 0.0 ) ;\n\n\tenvelopes.write_netcdf(ncname) ;\n\n\t// compare intensity to analytic solution for monostatic result (eqn. 31).\n\t// - divides total energy by duration to estimate peak\n\t// - note that (Ls2+Lr2)*(Ws2+Wr2) = 2 Ls2 Ws2 when s=r\n\t// - includes extra 4 pi in denominator, based on Matlab results\n\n\tdouble factor = cos(angle) / c0 ;\n\tdouble sigma2 = src_verb.length2 / 2.0 ;\n\tdouble duration = 0.5 * sqrt( pulse_length*pulse_length + factor*factor*sigma2 ) ;\n\tvector<double> theory = 10.0*log10(\n\t\t\t0.25 * 0.5 * pulse_length * power * power * scatter\n\t\t\t/ sqrt(4.0 * src_verb.length2 * src_verb.width2) / duration ) ;\n\tsize_t index = 105 ;\n\tcout << \"duration=\" << duration << endl;\n\tfor (size_t f = 0; f < envelope_freq.size(); ++f) {\n\t\tdouble model = 10.0*log10(envelopes.envelope(0,0,0)(f,index));\n\t\tcout << \"theory=\" << theory[f] << \" model=\" << model << endl;\n\t\tBOOST_CHECK_SMALL( abs(model-theory[f]), 1e-4);\n\t}\n}\n\n/**\n * Test the ability to insert source eigenverbs generated from eigenverb_basic\n * test into a boost rtree and query them with an expected result.\n *      - All four volume interfaces are inserted into one rtree.\n *          Production code uses one rtree per interface.\n *      - This test uses points as the keys as they are faster to create than boxes\n *      - This test bulk inserts a collection_pairs std::list into the rtree\n *          constructor with iterator arguments.\n */\n\nusing namespace boost::geometry;\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\ntypedef bg::model::point<double, 2, bg::cs::cartesian > point;\n\ntypedef bg::model::box<point> box;\n\ntypedef std::pair<point, eigenverb_list::iterator> value_pair;\n\ntypedef bgi::rtree<value_pair, bgi::rstar<16,4> > rtree_type;\n\nBOOST_AUTO_TEST_CASE( rtree_basic ) {\n\n    cout << \"=== eigenverb_test: rtree_basic ===\" << endl;\n    const char* ncname = USML_TEST_DIR \"/eigenverb/test/eigenverb_basic_\";\n\n    int interfaces = 4;\n    eigenverb_collection collection(interfaces);\n    eigenverb_list eigenverbs;\n    eigenverb verb;\n\n    // Use local pairs to package in rtree\n    std::list<value_pair> collection_pairs;\n    eigenverb_list::iterator iter;\n\n    int i = 0;\n    // Read eigenverbs for each interface from their own disk file\n    for ( int n=0 ; n < interfaces ; ++n ) {\n        std::stringstream filename ;\n        filename << ncname << n << \".nc\" ;\n        eigenverbs = collection.read_netcdf( filename.str().c_str()) ;\n\n        // get eigenverb values\n        for (iter = eigenverbs.begin(); iter != eigenverbs.end(); ++iter ) {\n\n            verb = *iter;\n            collection_pairs.push_back(\n                            std::make_pair(point(verb.position.latitude(),\n                            verb.position.longitude()), iter));\n            ++i;\n        }\n    }\n\n    // Use Packed constructor of rtree for fastest insertion\n    rtree_type rtree = rtree_type(collection_pairs.begin(), collection_pairs.end());\n\n    // Test query box creation\n    double q = 0.0;\n    double delta_lat = 0.0;\n    double delta_long = 0.0;\n    double latitude = 0.0;\n    double longitude = 0.0;\n\n    // meters/degree  60 nmiles/degree * 1852 meters/nmiles\n    double lat_scaler = (60.0*1852.0);\n\n    // Use receiver eigenverbs lat, long, length and width\n    // to create a bounding box.\n    double rcv_verb_length = 200.0; // meters\n    double rcv_verb_width = 200.0; // meters\n    double rcv_verb_latitude = 45.0;  // North\n    double rcv_verb_longitude = -45.0;// East\n\n    q = max(rcv_verb_length, rcv_verb_width);\n    latitude = rcv_verb_latitude;\n    longitude = rcv_verb_longitude;\n    delta_lat = q/lat_scaler;\n    delta_long = q/(lat_scaler * cos(to_radians(latitude)));\n\n    // create a box, first point bottom left, second point upper right\n    box query_box(point( latitude - delta_lat, longitude - delta_long),\n                point(latitude + delta_lat, longitude + delta_long));\n\n    std::cout << \"spatial query box:\" << std::endl;\n    std::cout << bg::wkt<box>(query_box) << std::endl;\n\n    std::vector<value_pair> result_s;\n    rtree.query(bgi::within(query_box), std::back_inserter(result_s));\n\n    // display results\n    std::cout << \"spatial query result:\" << std::endl;\n    BOOST_CHECK_EQUAL(result_s.size(), 121);\n    if (result_s.size() != 0) {\n        BOOST_FOREACH(value_pair const& v, result_s)\n                std::cout << bg::wkt<point>(v.first) << std::endl;\n        cout << \" Found \" << result_s.size() << \" results from \" << i << \" eigenverbs\" << endl;\n    } else {\n        cout << \" No results found \" << endl;\n    }\n\n    std::cout << \"=== rtree_basic: test completed! ===\" << std::endl;\n\n}\n\n/// @}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "77ac476d37be9a583dea4da6b38ab619eb0bba47", "size": 25731, "ext": "cc", "lang": "C++", "max_stars_repo_path": "eigenverb/test/eigenverb_test.cc", "max_stars_repo_name": "fraclipe/UnderSeaModelingLibrary", "max_stars_repo_head_hexsha": "52ef9dd03c7cbe548749e4527190afe7668ff4e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-07T14:48:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T14:48:22.000Z", "max_issues_repo_path": "eigenverb/test/eigenverb_test.cc", "max_issues_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_issues_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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": "eigenverb/test/eigenverb_test.cc", "max_forks_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_forks_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5892116183, "max_line_length": 95, "alphanum_fraction": 0.6648400762, "num_tokens": 7583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5117792969747511}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_MATH_MAX_SERIES_ITERATION_POLICY 10000000\n\n#include \"mp_t.hpp\"\n#include <boost/math/constants/constants.hpp>\n#include <boost/lexical_cast.hpp>\n#include <fstream>\n#include <map>\n#include <boost/math/tools/test_data.hpp>\n#include <boost/random.hpp>\n\nusing namespace boost::math::tools;\nusing namespace boost::math;\nusing namespace std;\n\nstruct hypergeometric_0f2_gen\n{\n   mp_t operator()(mp_t b1, mp_t b2, mp_t z)\n   {\n      mp_t result = 0;\n      mp_t abs_result = 0;\n      mp_t term = 1;\n      mp_t k = 0;\n\n      do\n      {\n         result += term;\n         abs_result += fabs(term);\n         if (fabs(result) * boost::math::tools::epsilon<mp_t>() > fabs(term))\n            break;\n         ++k;\n         term /= b1++;\n         term /= b2++;\n         term /= k;\n         term *= z;\n      } while (true);\n      //\n      // check precision:\n      //\n      if (abs_result * boost::math::tools::epsilon<mp_t>() / fabs(result) > 1e-40)\n         throw std::domain_error(\"Unable to calculate result\");\n\n      std::cout << b1 << \" \" << b2 << \" \" << z << \" \" << result << std::endl;\n      return result;\n   }\n};\n\nint main(int, char* [])\n{\n   parameter_info<mp_t> arg1, arg2, arg3, arg4;\n   test_data<mp_t> data;\n\n   std::cout << \"Welcome.\\n\"\n      \"This program will generate spot tests for 2F0:\\n\";\n\n   std::string line;\n   bool cont = true;\n\n   while (cont)\n   {\n      float range;\n      std::cout << \"Enter the range to calculate over for b1 and b2 (single value, range will be -x to x): \";\n      std::cin >> range;\n\n      float z_range;\n      std::cout << \"Enter the range to calculate over for z (single value, range will be -x to x): \";\n      std::cin >> z_range;\n\n      int num_spots;\n      std::cout << \"Enter how many test points to calculate: \";\n      std::cin >> num_spots;\n\n      std::vector<mp_t> v;\n      random_ns::mt19937 rnd;\n      random_ns::uniform_real_distribution<float> ur_a(-range, range);\n      random_ns::uniform_real_distribution<float> ur_z(-z_range, z_range);\n\n      do\n      {\n         mp_t b1 = ur_a(rnd);\n         mp_t b2 = ur_a(rnd);\n         mp_t z = ur_z(rnd);\n\n         arg1 = make_single_param(b1);\n         arg2 = make_single_param(b2);\n         arg3 = make_single_param(z);\n         data.insert(hypergeometric_0f2_gen(), arg1, arg2, arg3);\n      } while (num_spots--);\n\n      std::cout << \"Any more data?\";\n      std::cin >> cont;\n\n   }\n\n\n\n   std::cout << \"Enter name of test data file [default=hypergeometric_0f2.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"hypergeometric_0f2.ipp\";\n   std::ofstream ofs(line.c_str());\n   ofs << std::scientific << std::setprecision(40);\n   write_code(ofs, data, line.c_str());\n   \n   return 0;\n}\n\n\n", "meta": {"hexsha": "a9542653923ad2cd10737327981389231254f9f9", "size": 2965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/hyp_0f2_data.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": "tools/hyp_0f2_data.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/tools/hyp_0f2_data.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": 26.0087719298, "max_line_length": 109, "alphanum_fraction": 0.5932546374, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5117792963061276}}
{"text": "#include <boost/math/special_functions/hermite.hpp>\n", "meta": {"hexsha": "369174b3dc35f3ea8ec9b9b05255586862cf569d", "size": 52, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_hermite.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_hermite.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_hermite.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.0, "max_line_length": 51, "alphanum_fraction": 0.8269230769, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5117792908821095}}
{"text": "#include \"pose_2d.hpp\"\n#include \"ackermann_kinematics.hpp\"\n#include \"scan_simulator_2d.hpp\"\n#include \"car_state.hpp\"\n#include \"car_params.hpp\"\n#include \"ks_kinematics.hpp\"\n#include \"st_kinematics.hpp\"\n#include \"racecar.hpp\"\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <iostream>\n#include <vector>\n#include <chrono>\n#include <math.h>\nusing namespace racecar_simulator;\nclass StandaloneSimulator {\npublic:\n    bool map_exists;\n StandaloneSimulator(int num_cars, double timestep, double mu, double h_cg, double l_r, double cs_f, double cs_r, double I_z, double mass);\n virtual ~StandaloneSimulator();\n void set_map(std::vector<double> map, int map_height, int map_width, double map_resolution, double origin_x, double origin_y, double free_threshold);\n std::vector<CarObs> step(std::vector<double> velocities, std::vector<double> steering_angles);\n    void update_params(double mu, double h_cg, double l_r, double cs_f, double cs_r, double I_z, double mass);\n bool get_map_status();\n    bool check_collision();\n void reset();\n    void reset_bypose(std::vector<Pose2D> &poses);\nprivate:\n    double delt_t;\n    int ego_agent_idx = 0;\n    double safety_radius = 1.0;\n    int num_agents;\n    std::vector<RaceCar> agents;\n    std::vector<Pose2D> agent_poses;\n    std::vector<CarObs> current_obs;\n    double car_width = 0.31;\n    double car_length = 0.58;\n    double scan_distance_to_base_link = 0.275;\n    double wheel_base = 0.3302;\n    std::vector<double> map;\n    int map_height, map_width;\n    double map_resolution, origin_x, origin_y, free_threshold;\n    Eigen::Matrix4d get_transformation_matrix(const Pose2D &pose);\n};\n", "meta": {"hexsha": "d9ed168b7d37308505f14a3276fdb726b35aaad5", "size": 1633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Simulator/include/simulator.hpp", "max_stars_repo_name": "travelbureau/f0_icml_code", "max_stars_repo_head_hexsha": "8860c3e9e87c7340268bb18aa7d7e383b540f699", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T22:59:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T20:53:38.000Z", "max_issues_repo_path": "Simulator/include/simulator.hpp", "max_issues_repo_name": "travelbureau/f0_icml_code", "max_issues_repo_head_hexsha": "8860c3e9e87c7340268bb18aa7d7e383b540f699", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Simulator/include/simulator.hpp", "max_forks_repo_name": "travelbureau/f0_icml_code", "max_forks_repo_head_hexsha": "8860c3e9e87c7340268bb18aa7d7e383b540f699", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-16T15:43:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-16T18:18:40.000Z", "avg_line_length": 36.2888888889, "max_line_length": 150, "alphanum_fraction": 0.7464788732, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5117792854580911}}
{"text": "// This file is a part of the OpenSurgSim project.\n// Copyright 2013-2016, SimQuest Solutions Inc.\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/// \\file\n/// Tests that exercise the functionality of our rigid transform typedefs, which\n/// come straight from Eigen.\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"SurgSim/Math/RigidTransform.h\"\n#include \"SurgSim/Math/Quaternion.h\"\n#include \"SurgSim/Math/MathConvert.h\"\n#include \"gtest/gtest.h\"\n\ntemplate <class T>\nclass RigidTransformTestBase : public testing::Test\n{\npublic:\n\ttypedef T RigidTransform;\n\ttypedef typename T::Scalar Scalar;\n};\n\n\ntemplate <class T>\nclass RigidTransform3Tests : public RigidTransformTestBase<T>\n{\n};\n\ntypedef ::testing::Types<SurgSim::Math::RigidTransform3d,\n\t\tSurgSim::Math::RigidTransform3f> RigidTransform3Variants;\nTYPED_TEST_CASE(RigidTransform3Tests, RigidTransform3Variants);\n\n\ntemplate <class T>\nclass AllRigidTransformTests : public RigidTransformTestBase<T>\n{\n};\n\ntypedef ::testing::Types<SurgSim::Math::RigidTransform2d,\n\t\tSurgSim::Math::RigidTransform2f,\n\t\tSurgSim::Math::RigidTransform3d,\n\t\tSurgSim::Math::RigidTransform3f> AllRigidTransformVariants;\nTYPED_TEST_CASE(AllRigidTransformTests, AllRigidTransformVariants);\n\n\n/// Test that rigid transforms can be constructed\nTYPED_TEST(AllRigidTransformTests, CanConstruct)\n{\n\ttypename TestFixture::RigidTransform transform;\n}\n\n/// Test rigid transforms interpolation\nTYPED_TEST(AllRigidTransformTests, Interpolation)\n{\n\tusing SurgSim::Math::makeRigidTransform;\n\n\ttypedef typename TestFixture::Scalar T;\n\ttypedef Eigen::Quaternion<T> Quaternion;\n\ttypedef Eigen::Transform<T, 3, Eigen::Isometry> Transform;\n\ttypedef Eigen::Matrix<T, 3, 1> Vector3;\n\n\tfor (size_t numLoop = 0; numLoop < 100; numLoop++)\n\t{\n\t\tQuaternion q0(Eigen::Matrix<T, 4, 1>::Random());\n\t\tQuaternion q1(Eigen::Matrix<T, 4, 1>::Random());\n\t\tq0.normalize();\n\t\tq1.normalize();\n\n\t\tVector3 t0(Vector3::Random());\n\t\tVector3 t1(Vector3::Random());\n\n\t\tTransform transform0 = makeRigidTransform(q0, t0);\n\t\tTransform transform1 = makeRigidTransform(q1, t1);\n\t\t{\n\t\t\tTransform transform = SurgSim::Math::interpolate(transform0, transform1, static_cast<T>(0.0));\n\t\t\tEXPECT_TRUE(transform.isApprox(transform0));\n\t\t}\n\t\t{\n\t\t\tTransform transform = SurgSim::Math::interpolate(transform0, transform1, static_cast<T>(1.0));\n\t\t\tEXPECT_TRUE(transform.isApprox(transform1));\n\t\t}\n\n\t\t{\n\t\t\tTransform transform = SurgSim::Math::interpolate(transform0, transform1, static_cast<T>(0.234));\n\t\t\tEXPECT_FALSE(transform.isApprox(transform0));\n\t\t\tEXPECT_FALSE(transform.isApprox(transform1));\n\t\t}\n\n\t\t{\n\t\t\tTransform transform = SurgSim::Math::interpolate(transform0, transform1, static_cast<T>(0.5));\n\t\t\tEXPECT_FALSE(transform.isApprox(transform0));\n\t\t\tEXPECT_FALSE(transform.isApprox(transform1));\n\n\t\t\t// At t=0.5, the rotation interpolation should return (q0 + q1)/2 normalized\n\t\t\t// c.f. http://en.wikipedia.org/wiki/Slerp\n\t\t\t// If the quaternions are over PI angle, the slerp will interpolate between q0 and -q1\n\t\t\t// in this case, the interpolation is (q0 - q1)/2 normalized\n\t\t\t// From our specification, both quaternions could be considered negative, so we extend\n\t\t\t// the tests to these possibilities as well:\n\t\t\t// (-q0 + q1) / 2 normalized\n\t\t\t// (-q0 - q1) / 2 normalized\n\t\t\tQuaternion qHalf0((q0.coeffs() + q1.coeffs()) * 0.5);\n\t\t\tQuaternion qHalf1((q0.coeffs() - q1.coeffs()) * 0.5);\n\t\t\tQuaternion qHalf2((-q0.coeffs() + q1.coeffs()) * 0.5);\n\t\t\tQuaternion qHalf3((-q0.coeffs() - q1.coeffs()) * 0.5);\n\t\t\tqHalf0.normalize();\n\t\t\tqHalf1.normalize();\n\t\t\tqHalf2.normalize();\n\t\t\tqHalf3.normalize();\n\n\t\t\tVector3 tHalf = (t0 + t1) * 0.5;\n\t\t\tTransform transformHalf0 = makeRigidTransform(qHalf0, tHalf);\n\t\t\tTransform transformHalf1 = makeRigidTransform(qHalf1, tHalf);\n\t\t\tTransform transformHalf2 = makeRigidTransform(qHalf2, tHalf);\n\t\t\tTransform transformHalf3 = makeRigidTransform(qHalf3, tHalf);\n\t\t\tEXPECT_TRUE(transform.isApprox(transformHalf0) || transform.isApprox(transformHalf1) ||\n\t\t\t\t\t\ttransform.isApprox(transformHalf2) || transform.isApprox(transformHalf3));\n\t\t}\n\n\t\t{\n\t\t\tTransform transform = SurgSim::Math::interpolate(transform0, transform1, static_cast<T>(0.839));\n\t\t\tEXPECT_FALSE(transform.isApprox(transform0));\n\t\t\tEXPECT_FALSE(transform.isApprox(transform1));\n\t\t}\n\t}\n}\n\nTYPED_TEST(AllRigidTransformTests, MakeLookAt)\n{\n\ttypedef typename TestFixture::Scalar T;\n\ttypedef Eigen::Transform<T, 3, Eigen::Isometry> Transform;\n\n\ttypedef Eigen::Matrix<T, 3, 1> Vector3;\n\ttypedef Eigen::Matrix<T, 4, 1> Vector4;\n\n\tVector3 origin(0.0, 0.0, 0.0);\n\tVector3 eye(10.0, 10.0, 10.0);\n\tVector3 up(0.0, 1.0, 0.0);\n\n\tVector4 center4(0.0, 0.0, 0.0, 1.0);\n\n\t// This follows the OpenGl convention for the camera view matrix transform, any axis would do see\n\t// the documentation for makeRigidTransform and gluLookAt()\n\tVector4 direction4(0.0, 0.0, -1.0, 1.0);\n\tVector4 eye4(10.0, 10.0, 10.0, 1.0);\n\n\tTransform transform = SurgSim::Math::makeRigidTransform(eye, origin, up);\n\n\tEXPECT_TRUE(eye4.isApprox(transform * center4));\n\n\tVector4 transformed = transform * direction4;\n\n\tVector3 direction3(transformed[0], transformed[1], transformed[2]);\n\tEXPECT_TRUE(eye.normalized().isApprox(direction3.normalized()));\n}\n\n// Test conversion to and from yaml node\nTYPED_TEST(AllRigidTransformTests, YamlConvert)\n{\n\tusing SurgSim::Math::makeRigidTransform;\n\n\ttypedef typename TestFixture::Scalar T;\n\ttypedef Eigen::Quaternion<T> Quaternion;\n\ttypedef Eigen::Transform<T, 3, Eigen::Isometry> Transform;\n\ttypedef Eigen::Matrix<T, 3, 1> Vector3;\n\n\tconst T inputValues[4] = {1.1f, 2.2f, 3.3f, 4.4f};\n\n\tQuaternion quaternion(inputValues);\n\tquaternion.normalize();\n\n\tVector3 translation(inputValues);\n\n\tTransform transform = makeRigidTransform(quaternion, translation);\n\n\tYAML::Node node;\n\n\tASSERT_NO_THROW(node = transform);\n\n\tEXPECT_TRUE(node.IsMap());\n\tEXPECT_EQ(2u, node.size());\n\n\tTransform expected;\n\n\tASSERT_NO_THROW(expected = node.as<Transform>());\n\tEXPECT_TRUE(transform.isApprox(expected));\n}\n", "meta": {"hexsha": "3e1a6b6ed5f91214cb4e63bfc302d913149b7591", "size": 6479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SurgSim/Math/UnitTests/RigidTransformTests.cpp", "max_stars_repo_name": "dbungert/opensurgsim", "max_stars_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T16:18:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T03:29:11.000Z", "max_issues_repo_path": "SurgSim/Math/UnitTests/RigidTransformTests.cpp", "max_issues_repo_name": "dbungert/opensurgsim", "max_issues_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-12-21T14:54:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T12:38:07.000Z", "max_forks_repo_path": "SurgSim/Math/UnitTests/RigidTransformTests.cpp", "max_forks_repo_name": "dbungert/opensurgsim", "max_forks_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-04-10T19:45:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T17:00:59.000Z", "avg_line_length": 32.395, "max_line_length": 99, "alphanum_fraction": 0.7385398981, "num_tokens": 1783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5117541173140928}}
{"text": "//  Copyright (c) 2006 Xiaogang Zhang, 2015 John Maddock\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//  History:\n//  XZ wrote the original of this file as part of the Google\n//  Summer of Code 2006.  JM modified it to fit into the\n//  Boost.Math conceptual framework better, and to handle\n//  types longer than 80-bit reals.\n//  Updated 2015 to use Carlson's latest methods.\n//\n#ifndef BOOST_MATH_ELLINT_RF_HPP\n#define BOOST_MATH_ELLINT_RF_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/special_functions/ellint_rc.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/tools/config.hpp>\n\n// Carlson's elliptic integral of the first kind\n// R_F(x, y, z) = 0.5 * \\int_{0}^{\\infty} [(t+x)(t+y)(t+z)]^{-1/2} dt\n// Carlson, Numerische Mathematik, vol 33, 1 (1979)\n\nnamespace boost\n{\nnamespace math\n{\nnamespace detail\n{\n\ntemplate <typename T, typename Policy>\nT ellint_rf_imp(T x, T y, T z, const Policy& pol)\n{\n    BOOST_MATH_STD_USING\n    using namespace boost::math;\n    using std::swap;\n\n    static const char* function = \"boost::math::ellint_rf<%1%>(%1%,%1%,%1%)\";\n\n    if (x < 0 || y < 0 || z < 0)\n    {\n        return policies::raise_domain_error<T>(\n            function,\n            \"domain error, all arguments must be non-negative, \"\n            \"only sensible result is %1%.\",\n            std::numeric_limits<T>::quiet_NaN(), pol);\n    }\n    if (x + y == 0 || y + z == 0 || z + x == 0)\n    {\n        return policies::raise_domain_error<T>(\n            function,\n            \"domain error, at most one argument can be zero, \"\n            \"only sensible result is %1%.\",\n            std::numeric_limits<T>::quiet_NaN(), pol);\n    }\n    //\n    // Special cases from http://dlmf.nist.gov/19.20#i\n    //\n    if (x == y)\n    {\n        if (x == z)\n        {\n            // x, y, z equal:\n            return 1 / sqrt(x);\n        }\n        else\n        {\n            // 2 equal, x and y:\n            if (z == 0)\n                return constants::pi<T>() / (2 * sqrt(x));\n            else\n                return ellint_rc_imp(z, x, pol);\n        }\n    }\n    if (x == z)\n    {\n        if (y == 0)\n            return constants::pi<T>() / (2 * sqrt(x));\n        else\n            return ellint_rc_imp(y, x, pol);\n    }\n    if (y == z)\n    {\n        if (x == 0)\n            return constants::pi<T>() / (2 * sqrt(y));\n        else\n            return ellint_rc_imp(x, y, pol);\n    }\n    if (x == 0)\n        swap(x, z);\n    else if (y == 0)\n        swap(y, z);\n    if (z == 0)\n    {\n        //\n        // Special case for one value zero:\n        //\n        T xn = sqrt(x);\n        T yn = sqrt(y);\n\n        while (fabs(xn - yn) >= 2.7 * tools::root_epsilon<T>() * fabs(xn))\n        {\n            T t = sqrt(xn * yn);\n            xn = (xn + yn) / 2;\n            yn = t;\n        }\n        return constants::pi<T>() / (xn + yn);\n    }\n\n    T xn = x;\n    T yn = y;\n    T zn = z;\n    T An = (x + y + z) / 3;\n    T A0 = An;\n    T Q = pow(3 * boost::math::tools::epsilon<T>(), T(-1) / 8) *\n          (std::max)((std::max)(fabs(An - xn), fabs(An - yn)), fabs(An - zn));\n    T fn = 1;\n\n    // duplication\n    unsigned k = 1;\n    for (; k < boost::math::policies::get_max_series_iterations<Policy>(); ++k)\n    {\n        T root_x = sqrt(xn);\n        T root_y = sqrt(yn);\n        T root_z = sqrt(zn);\n        T lambda = root_x * root_y + root_x * root_z + root_y * root_z;\n        An = (An + lambda) / 4;\n        xn = (xn + lambda) / 4;\n        yn = (yn + lambda) / 4;\n        zn = (zn + lambda) / 4;\n        Q /= 4;\n        fn *= 4;\n        if (Q < fabs(An))\n            break;\n    }\n    // Check to see if we gave up too soon:\n    policies::check_series_iterations<T>(function, k, pol);\n    BOOST_MATH_INSTRUMENT_VARIABLE(k);\n\n    T X = (A0 - x) / (An * fn);\n    T Y = (A0 - y) / (An * fn);\n    T Z = -X - Y;\n\n    // Taylor series expansion to the 7th order\n    T E2 = X * Y - Z * Z;\n    T E3 = X * Y * Z;\n    return (1 + E3 * (T(1) / 14 + 3 * E3 / 104) +\n            E2 * (T(-1) / 10 + E2 / 24 - (3 * E3) / 44 - 5 * E2 * E2 / 208 +\n                  E2 * E3 / 16)) /\n           sqrt(An);\n}\n\n} // namespace detail\n\ntemplate <class T1, class T2, class T3, class Policy>\ninline typename tools::promote_args<T1, T2, T3>::type\n    ellint_rf(T1 x, T2 y, T3 z, const Policy& pol)\n{\n    typedef typename tools::promote_args<T1, T2, T3>::type result_type;\n    typedef typename policies::evaluation<result_type, Policy>::type value_type;\n    return policies::checked_narrowing_cast<result_type, Policy>(\n        detail::ellint_rf_imp(static_cast<value_type>(x),\n                              static_cast<value_type>(y),\n                              static_cast<value_type>(z), pol),\n        \"boost::math::ellint_rf<%1%>(%1%,%1%,%1%)\");\n}\n\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type ellint_rf(T1 x, T2 y,\n                                                                T3 z)\n{\n    return ellint_rf(x, y, z, policies::policy<>());\n}\n\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_ELLINT_RF_HPP\n", "meta": {"hexsha": "6a60757eed3eb6f491655a81e359da66c5c63870", "size": 5317, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/math/special_functions/ellint_rf.hpp", "max_stars_repo_name": "sotaoverride/backup", "max_stars_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/math/special_functions/ellint_rf.hpp", "max_issues_repo_name": "sotaoverride/backup", "max_issues_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/math/special_functions/ellint_rf.hpp", "max_forks_repo_name": "sotaoverride/backup", "max_forks_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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.7405405405, "max_line_length": 80, "alphanum_fraction": 0.5245439157, "num_tokens": 1601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5117541173140928}}
{"text": "/****************************************************************************/\n/* Copyright 2005-2006, Francis Russell                                     */\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 DESOLA_MATRIX_VECTOR_HPP\n#define DESOLA_MATRIX_VECTOR_HPP\n\n#include <cstddef>\n#include <boost/array.hpp>\n#include <desola/Desola_fwd.hpp>\n\nnamespace desola\n{\n\nnamespace detail\n{\n\ntemplate<typename T_element>\nclass MatrixMult : public BinOp<matrix, matrix, matrix, T_element>\n{\nprivate:\n  inline static const boost::array<std::size_t, 2> createDims(const ExprNode<matrix, T_element>& l, const ExprNode<matrix, T_element>& r)\n  {\n    boost::array<std::size_t, 2> dimensions = { {l.getRowCount(), r.getColCount()} };\n    return dimensions;\n  }\n  \npublic:\n  MatrixMult(ExprNode<matrix, T_element>& left, ExprNode<matrix, T_element>& right) : BinOp<matrix, matrix, matrix, T_element>(createDims(left, right), left, right)\n  {\n  }\n\n  void accept(ExpressionNodeVisitor<T_element>& v)\n  {\n    v.visit(*this);\n  }\n\n  virtual Maybe<double> getFlops() const\n  {\n    return Maybe<double>(this->getLeft().nnz()) * this->getRight().getColCount() * 2.0;\n  }\n};\n\ntemplate<typename T_element>\nclass MatrixVectorMult : public BinOp<vector, matrix, vector, T_element>\n{\nprivate:\n  inline static const boost::array<std::size_t, 1> getDims(const ExprNode<matrix, T_element>& l, const ExprNode<vector, T_element>& r)\n  {\n    boost::array<std::size_t, 1> dimensions = { {l.getRowCount()} };\n    return dimensions;\n  }\n  \npublic:\n  MatrixVectorMult(ExprNode<matrix, T_element>& left, ExprNode<vector, T_element>& right) : BinOp<vector, matrix, vector, T_element>(getDims(left, right), left, right)\n  {\n  }\n\n  void accept(ExpressionNodeVisitor<T_element>& v)\n  {\n    v.visit(*this);\n  }\n\n  virtual Maybe<double> getFlops() const\n  {\n    return Maybe<double>(this->getLeft().nnz()) * 2.0;\n  }\n};\n\ntemplate<typename T_element>\nclass TransposeMatrixVectorMult : public BinOp<vector, matrix, vector, T_element>\n{\nprivate:\n  inline static const boost::array<std::size_t, 1> getDims(const ExprNode<matrix, T_element>& l, const ExprNode<vector, T_element>& r)\n  {\n    boost::array<std::size_t, 1> dimensions = { {l.getColCount()} };\n    return dimensions;\n  }\n\npublic:\n  TransposeMatrixVectorMult(ExprNode<matrix, T_element>& left, ExprNode<vector, T_element>& right) : BinOp<vector, matrix, vector, T_element>(getDims(left, right), left, right)\n  {\n  }\n\n  void accept(ExpressionNodeVisitor<T_element>& v)\n  {\n    v.visit(*this);\n  }\n\n  virtual Maybe<double> getFlops() const\n  {\n    return Maybe<double>(this->getLeft().nnz()) * 2.0;\n  }\n};\n\n\ntemplate<typename T_element>\nclass VectorDot : public BinOp<scalar, vector, vector, T_element>\n{\nprivate:\n  inline static const boost::array<std::size_t, 0> getDims(const ExprNode<vector, T_element>& left, const ExprNode<vector, T_element>& right)\n  {\n    return boost::array<std::size_t, 0>();\n  }\n  \npublic:\n  VectorDot(ExprNode<vector, T_element>& left, ExprNode<vector, T_element>& right) : BinOp<scalar, vector, vector, T_element>(boost::array<std::size_t, 0>(), left, right)\n  {\n  }\n\n  void accept(ExpressionNodeVisitor<T_element>& v)\n  {\n    v.visit(*this);\n  }\n\n  virtual Maybe<double> getFlops() const\n  {\n    return 2.0 * this->getLeft().getRowCount() - 1.0;\n  }\n};\n\ntemplate<typename T_element>\nclass VectorCross : public BinOp<vector, vector, vector, T_element>\n{\nprivate:\n  inline static const boost::array<std::size_t, 1>& getDims(const ExprNode<vector, T_element>& l, const ExprNode<vector, T_element>& r)\n  {\n    return l.getDims();\n  }\n  \npublic:\n  VectorCross(ExprNode<vector, T_element>& left, ExprNode<vector, T_element>& right) : BinOp<vector, vector, vector, T_element>(getDims(left, right), left, right)\n  {\n  }\n\n  void accept(ExpressionNodeVisitor<T_element>& v)\n  {\n    v.visit(*this);\n  }\n  \n  virtual Maybe<double> getFlops() const\n  {\n    return 3.0 * this->getRowCount();\n  }\n};\n\ntemplate<typename T_element>\nclass VectorTwoNorm : public UnOp<scalar, vector, T_element>\n{\npublic:\n  VectorTwoNorm(ExprNode<vector, T_element>& left) : UnOp<scalar, vector, T_element>(boost::array<std::size_t, 0>(), left)\n  {\n  }\n\n  void accept(ExpressionNodeVisitor<T_element>& v)\n  {\n    v.visit(*this);\n  }\n\n  virtual Maybe<double> getFlops() const\n  {\n    // n multiplies + (n-1) additions + 1 sqrt\n    return 2.0 * this->getOperand().getRowCount();\n  }\n};\n\ntemplate<typename T_element>\nclass MatrixTranspose : public UnOp<matrix, matrix, T_element>\n{\nprivate:\n  inline static const boost::array<std::size_t, 2> createDims(const ExprNode<matrix, T_element>& m)\n  {\n    boost::array<std::size_t, 2> dimensions = { {m.getColCount(), m.getRowCount()} };\n    return dimensions;\n  }\n\npublic:\n  MatrixTranspose(ExprNode<matrix, T_element>& m) : UnOp<matrix, matrix, T_element>(createDims(m), m)\n  {\n  }\n\n  void accept(ExpressionNodeVisitor<T_element>& v)\n  {\n    v.visit(*this);\n  }\n\n  virtual Maybe<double> getFlops() const\n  {\n    return 0.0;\n  }\n};\n\n}\n\n}\n#endif\n", "meta": {"hexsha": "d16a81a1aa04f8fea0903a604684a8a47a189db0", "size": 6058, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/desola/MatrixVector.hpp", "max_stars_repo_name": "FrancisRussell/desola", "max_stars_repo_head_hexsha": "a469428466e4849c7c0e2009a0c50b89184cae01", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T10:46:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T11:53:50.000Z", "max_issues_repo_path": "include/desola/MatrixVector.hpp", "max_issues_repo_name": "FrancisRussell/desola", "max_issues_repo_head_hexsha": "a469428466e4849c7c0e2009a0c50b89184cae01", "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/desola/MatrixVector.hpp", "max_forks_repo_name": "FrancisRussell/desola", "max_forks_repo_head_hexsha": "a469428466e4849c7c0e2009a0c50b89184cae01", "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.8476190476, "max_line_length": 176, "alphanum_fraction": 0.6208319577, "num_tokens": 1495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5117541153733433}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and\n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2003-2008 Matthias Christian Schabel\n// Copyright (C) 2008 Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <map>\n#include <iostream>\n#include <boost/lexical_cast.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/cmath.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/base_units/imperial/foot.hpp>\n\n//[runtime_unit_snippet_1\n\nnamespace {\n\nusing namespace boost::units;\nusing imperial::foot_base_unit;\n\nstd::map<std::string, quantity<si::length> > known_units;\n\n}\n\nquantity<si::length> calculate(const quantity<si::length>& t)\n{\n    return(boost::units::hypot(t, 2.0 * si::meters));\n}\n\nint main()\n{\n    known_units[\"meter\"] = 1.0 * si::meters;\n    known_units[\"centimeter\"] = .01 * si::meters;\n    known_units[\"foot\"] =\n        conversion_factor(foot_base_unit::unit_type(), si::meter) * si::meter;\n\n    std::string output_type(\"meter\");\n    std::string input;\n\n    while((std::cout << \"> \") && (std::cin >> input))\n    {\n        if(!input.empty() && input[0] == '#')\n        {\n            std::getline(std::cin, input);\n        }\n        else if(input == \"exit\")\n        {\n            break;\n        }\n        else if(input == \"help\")\n        {\n            std::cout << \"type \\\"exit\\\" to exit\\n\"\n                \"type \\\"return 'unit'\\\" to set the return units\\n\"\n                \"type \\\"'number' 'unit'\\\" to do a simple calculation\"\n                << std::endl;\n        }\n        else if(input == \"return\")\n        {\n            if(std::cin >> input)\n            {\n                if(known_units.find(input) != known_units.end())\n                {\n                    output_type = input;\n                    std::cout << \"Done.\" << std::endl;\n                }\n                else\n                {\n                    std::cout << \"Unknown unit \\\"\" << input << \"\\\"\"\n                         << std::endl;\n                }\n            }\n            else\n            {\n                break;\n            }\n        }\n        else\n        {\n            try\n            {\n                double value = boost::lexical_cast<double>(input);\n\n                if(std::cin >> input)\n                {\n                    if(known_units.find(input) != known_units.end())\n                    {\n                        std::cout << static_cast<double>(\n                            calculate(value * known_units[input]) /\n                            known_units[output_type])\n                            << ' ' << output_type << std::endl;\n                    }\n                    else\n                    {\n                        std::cout << \"Unknown unit \\\"\" << input << \"\\\"\"\n                            << std::endl;\n                    }\n                }\n                else\n                {\n                    break;\n                }\n            }\n            catch(...)\n            {\n                std::cout << \"Input error\" << std::endl;\n            }\n        }\n    }\n}\n\n//]\n", "meta": {"hexsha": "11c8b5b2b72077652b54aba1516e2c93649c5e8f", "size": 3194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/units/example/runtime_unit.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/units/example/runtime_unit.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/units/example/runtime_unit.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": 27.2991452991, "max_line_length": 78, "alphanum_fraction": 0.4502191609, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.5117541102703655}}
{"text": "//  Copyright John Maddock 2007.\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. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifdef _MSC_VER\r\n# pragma warning (disable : 4305) // 'initializing' : truncation from 'long double' to 'const eval_type'\r\n# pragma warning (disable : 4244) //  conversion from 'long double' to 'const eval_type'\r\n#endif\r\n\r\n#include <iostream>\r\nusing std::cout; using std::endl;\r\n\r\n//[policy_eg_3\r\n\r\n#include <boost/math/distributions/binomial.hpp>\r\nusing boost::math::binomial_distribution;\r\n\r\n// Begin by defining a policy type, that gives the behaviour we want:\r\n\r\n//using namespace boost::math::policies; or explicitly\r\nusing boost::math::policies::policy;\r\n\r\nusing boost::math::policies::promote_float;\r\nusing boost::math::policies::discrete_quantile;\r\nusing boost::math::policies::integer_round_nearest;\r\n\r\ntypedef policy<\r\n   promote_float<false>, // Do not promote to double.\r\n   discrete_quantile<integer_round_nearest> // Round result to nearest integer.\r\n> mypolicy;\r\n//\r\n// Then define a new distribution that uses it:\r\ntypedef boost::math::binomial_distribution<float, mypolicy> mybinom;\r\n\r\n//  And now use it to get the quantile:\r\n\r\nint main()\r\n{\r\n   cout << \"quantile(mybinom(200, 0.25), 0.05) is: \" <<\r\n      quantile(mybinom(200, 0.25), 0.05) << endl;\r\n}\r\n\r\n//]\r\n\r\n/*\r\n\r\nOutput:\r\n\r\n  quantile(mybinom(200, 0.25), 0.05) is: 40\r\n\r\n*/\r\n\r\n", "meta": {"hexsha": "1edfd3f558a21463c0ed8c7dbbae71b3196e4da4", "size": 1526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/policy_eg_3.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_eg_3.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_eg_3.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": 27.25, "max_line_length": 105, "alphanum_fraction": 0.6972477064, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5117541102703653}}
{"text": "#pragma once\n\n// Armadillo\n#include <armadillo>\n\n// Mantella\n#include \"mantella_bits/optimisationProblem/blackBoxOptimisationBenchmark.hpp\"\n\nnamespace mant {\n  namespace bbob {\n    class SchaffersF7Function : public BlackBoxOptimisationBenchmark {\n     public:\n      explicit SchaffersF7Function(\n          const arma::uword numberOfDimensions);\n\n     protected:\n      const arma::vec parameterConditioning_;\n      // Keeps randomly set data non-`const`, to be changed within tests.\n      arma::mat rotationQ_;\n    };\n  }\n}\n", "meta": {"hexsha": "dc8f29ec26567a2c47339cd0e0c227add1b061e1", "size": 524, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mantella_bits/optimisationProblem/blackBoxOptimisationBenchmark/schaffersF7Function.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/optimisationProblem/blackBoxOptimisationBenchmark/schaffersF7Function.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/optimisationProblem/blackBoxOptimisationBenchmark/schaffersF7Function.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.7826086957, "max_line_length": 78, "alphanum_fraction": 0.713740458, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5117541032266378}}
{"text": "#include <iostream>\n#include <stdexcept>\n#include <Eigen/Dense>\n#include \"SymmetricMatrix.h\"\n\nusing Eigen::MatrixXd;\n\nint main()\n{\n  std::clog << \"Starting tests...\" << std::endl\n            << std::endl;\n\n  const int ORDER = 10;\n\n  // Constructor and operator() tests.\n\n  MatrixXd m1 = MatrixXd::Random(ORDER, ORDER);\n\n  SymMat<double> sym1(m1);\n\n  for (int i = 0; i < ORDER; ++i)\n  {\n    for (int j = i; j < ORDER; ++j)\n    {\n      if (sym1(i, j) != m1(i, j))\n      {\n        std::clog << \"Test failed: SymMat and upper triangular part of Eigen::Matrix are not equal.\" << std::endl;\n        i = ORDER;\n        j = ORDER;\n      }\n    }\n  }\n\n  for (int i = 0; i < ORDER; ++i)\n  {\n    for (int j = i; j < ORDER; ++j)\n    {\n      if (sym1(i, j) != sym1(j, i))\n      {\n        std::clog << \"Test failed: SymMat(i, j) != SymMat(j, i).\" << std::endl;\n        i = ORDER;\n        j = ORDER;\n      }\n    }\n  }\n\n  // Addition, subtraction and multiplication tests.\n\n  MatrixXd ident = MatrixXd::Identity(ORDER, ORDER);\n  SymMat<double> symIdent(ident);\n\n  MatrixXd mzero(ORDER, ORDER);\n  mzero.setZero(ORDER, ORDER);\n\n  MatrixXd m2 = MatrixXd::Random(ORDER, 5);  \n\n  if (sym1 * mzero != mzero)\n  {\n    std::clog << \"Test failed: SymMat * 0 != 0.\" << std::endl;\n  }\n\n  if ((symIdent + symIdent) * ident != ident + ident ||\n      (symIdent + ident) != ident + ident)\n  {\n    std::clog << \"Test failed: Addition or multiplication failed.\" << std::endl;\n  }\n\n  if ((sym1 - sym1) * ident != mzero ||\n      (symIdent - ident) != mzero)\n  {\n    std::clog << \"Test failed: Subtraction or multiplication failed.\" << std::endl;\n  }\n\n  auto m3 = sym1 * m2;\n  if (m3.rows() != ORDER || m3.cols() != 5)\n  {\n    std::clog << \"Test failed: Multiplcation gave a matrix with wrong dimensions.\" << std::endl;    \n  }\n\n  // Exceptions tests.\n\n  try\n  {\n    SymMat<double> sym2(m2);\n    std::clog << \"Test failed: SymMat constructor didn't throw an exception with non square matrix.\" << std::endl;\n  }\n  catch (std::exception &e)\n  {\n  }\n\n  try\n  {\n    sym1(ORDER + 1, 0);\n    std::clog << \"Test failed: SymMat didn't throw an exception with out of bounds indices.\" << std::endl;\n  }\n  catch (std::exception &e)\n  {\n  }\n\n  try\n  {\n    sym1 + m2;\n    std::clog << \"Test failed: SymMat + Eigen::Matrix didn't throw an exception with different order matrices.\" << std::endl;\n  }\n  catch (std::exception &e)\n  {\n  }\n\n  try\n  {\n    sym1 - m2;\n    std::clog << \"Test failed: SymMat - Eigen::Matrix didn't throw an exception with different order matrices.\" << std::endl;\n  }\n  catch (std::exception &e)\n  {\n  }\n\n  try\n  {\n    MatrixXd m4(5, ORDER);\n    sym1 * m4;\n    std::clog << \"Test failed: SymMat * Eigen::Matrix didn't throw an exception with different order matrices.\" << std::endl;\n  }\n  catch (std::exception &e)\n  {\n  }\n\n  std::cout << std::endl\n            << \"Tests finished.\" << std::endl;\n}\n", "meta": {"hexsha": "f5d4939bde0e716069914ee3d0aa2e844cfdec59", "size": 2869, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests.cc", "max_stars_repo_name": "Sakerdot/symmetric-matrices", "max_stars_repo_head_hexsha": "ca8c21dcff3ea45f7b487bf10258ce8c869d46c8", "max_stars_repo_licenses": ["MIT"], "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.cc", "max_issues_repo_name": "Sakerdot/symmetric-matrices", "max_issues_repo_head_hexsha": "ca8c21dcff3ea45f7b487bf10258ce8c869d46c8", "max_issues_repo_licenses": ["MIT"], "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.cc", "max_forks_repo_name": "Sakerdot/symmetric-matrices", "max_forks_repo_head_hexsha": "ca8c21dcff3ea45f7b487bf10258ce8c869d46c8", "max_forks_repo_licenses": ["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.9007633588, "max_line_length": 125, "alphanum_fraction": 0.5636110143, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5117541032266378}}
{"text": "/**\n * @file Didson.cpp\n * @brief Projection functions for DIDSON\n * @author: Michael Kaess\n * @date: Aug 2014\n */\n\n#include <vector>\n#include <utility>\n\n#include <opencv2/opencv.hpp>\n\n#include <Eigen/Dense>\n\n#include \"Didson.h\"\n\nusing namespace boost;\nusing namespace std;\nusing namespace isam;\nusing namespace Eigen;\n\nnamespace sonar {\n\nconst float degtorad = M_PI / 180.;\nconst float radtodeg = 180. / M_PI;\n\nclass DidsonConstants {\npublic:\n  double bearingFov;\n  double elevationFov;\n  int numBearings;\n  int numRanges;\n  double startBase;\n  std::vector<double> lengths;\n  DidsonConstants() {\n    bearingFov = 28.8 * degtorad; // 28.8 or 29? (both are given in the specs)\n    elevationFov = 28. * degtorad; // 28 degrees with spreader lens (default without lens is 14 degrees)\n    numBearings = 96;\n    numRanges = 512;\n#if 1 // todo: unknown if DIDSON in CW or XW mode\n    // classic window mode (CW)\n    startBase = 0.375;\n    lengths.resize (4);\n    lengths[0] = 1.125; lengths[1] = 2.25; lengths[2] = 4.5; lengths[3] = 9.;\n#else\n    // extended window mode (XW)\n    startBase = 0.42;\n    lengths = {1.25, 2.5, 5., 10.};\n#endif\n  }\n};\n\nconst DidsonConstants consts;\n\npair<int, int> DidsonCartesian::bearingRange2Cartesian(int bearing,\n    int range) {\n  int pos = _invMap[range * consts.numBearings + bearing];\n  int col = pos % image.cols;\n  int row = (pos - col) / image.cols;\n  // HACK: don't just return col, it needs to be flipped\n  return make_pair(row, (image.cols - 1) - col);\n}\n\n// conversion of Matlab DIDSON code from Soundmetrics ---\nint Didson::lensDistortion(int nbeams, double theta) {\n  double* a = NULL;\n  double factor = 0.0;\n  double a48[4] = { 0.0015, -0.0036, 1.3351, 24.0976 };\n  double a189[4] = { 0.0015, -0.0036, 1.3351, 24.0978 };\n  double a96[4] = { 0.0030, -0.0055, 2.6829, 48.04 };\n  double a381[4] = { 0.0030, -0.0055, 2.6829, 48.04 };\n\n  switch (nbeams) {\n  case 48:\n    factor = 1.0;\n    a = a48;\n    break;\n  case 189:\n    factor = 4.026;\n    a = a189;\n    break;\n  case 96:\n    factor = 1.012;\n    a = a96;\n    break;\n  case 381:\n    factor = 4.05;\n    a = a381;\n    break;\n  }\n  return (int) round(\n      factor\n          * (a[0] * theta * theta * theta + a[1] * theta * theta + a[2] * theta\n              + a[3] + 1));\n}\n\n// conversion of Matlab DIDSON code from Soundmetrics ---\n/**\n * Calculates a map from cartesian to polar coordinates\n *\n * ixsize  - number of pixels in horizontal direction in image space\n * rmax    - maximum range in meters\n * rmin    - minimum range in meters\n * halffov - one-half of sector field of view in radians\n * nbins   - number of range bins in sample space\n */\npair<vector<int>, int> Didson::createMapping(int ixsize, double rmax,\n    double rmin, double halffov, int nbeams, int nbins) {\n  //double d2 = rmax*cos(halffov); // distance from point scan touches image boundary to origin\n  double d3 = rmin * cos(halffov); // bottom of image frame to r,theta origin in meters\n  double c1 = (consts.numRanges - 1) / (rmax - rmin); // precalculation of constants used in do loop below\n  //double c2 = (nbeams-1)/(2*halffov);\n  double gamma = ixsize / (2 * rmax * sin(halffov)); // Ratio of pixel number to position in meters\n\n  int iysize = (int) (gamma * (rmax - d3) + 0.5); // number of pixels in image in vertical direction\n\n  vector<int> map(ixsize * iysize); // Stores the index map\n\n  // ix,iy   - coordinates of a pixel in image space\n  for (int iy = 1; iy <= iysize; iy++) {\n    for (int ix = 1; ix <= ixsize; ix++) {\n      double x = ((ix - 1) - ixsize / 2) / gamma; // Convert from pixels to meters\n\n      double z = 0.0;\n      double y = rmax - (iy - 1) / gamma; // Convert from pixels to meters\n\n      double r = sqrt(y * y + x * x + z * z); // Convert to polar coordinates\n      double theta = radtodeg * atan2(x, y); // Theta is in degrees\n      int binnum = (int) ((r - rmin) * c1 + 1.5); // the rangebin number\n      int beamnum = lensDistortion(nbeams, theta); // Remove the lens distortation using empirical formula\n      int pos = 0; // invalid == -1, note pos-1 below\n      if ((beamnum > 0) && (beamnum <= nbeams) && (binnum > 0)\n          && (binnum <= nbins)) {\n        pos = (binnum - 1) * nbeams + beamnum;\n      }\n      map[(iy - 1) * ixsize + ix - 1] = pos - 1;\n    }\n  }\n  return make_pair(map, iysize);\n}\n\n// create a Cartesian image suitable for texture mapping from the raw\n// bearing/range measurements; also return a mask of valid image regions\nshared_ptr<DidsonCartesian> Didson::getCartesian(int width, int widthTmp) const {\n  // generate map for Cartesian image\n  vector<int> map;\n  int height;\n  pair<vector<int>, int> tmp1 = createMapping(width, maxRange(), minRange(),\n      consts.bearingFov * 0.5, numBearings(), numRanges());\n  map = tmp1.first;\n  height = tmp1.second;\n\n  // avoid having to write out the inverse mapping function by creating\n  // a map with sufficiently high resolution as a lookup table for the inverse map\n  // not ideal, but works...\n  vector<int> invMap(consts.numRanges * consts.numBearings);\n  vector<int> mapTmp;\n  int heightTmp;\n  pair<vector<int>, int> tmp2 = createMapping(widthTmp, maxRange(), minRange(),\n      consts.bearingFov * 0.5, numBearings(), consts.numRanges);\n  mapTmp = tmp2.first;\n  heightTmp = tmp2.second;\n\n  int c = 0;\n  for (int y = 0; y < heightTmp; y++) {\n    for (int x = 0; x < widthTmp; x++) {\n      int idx = mapTmp[c];\n      if (idx != -1) {\n        int icol = x * ((double) width / (double) widthTmp);\n        int irow = y * ((double) height / (double) heightTmp);\n        int i = irow * width + icol;\n        invMap[idx] = i;\n      }\n      c++;\n    }\n  }\n\n  shared_ptr<DidsonCartesian> cartesian(new DidsonCartesian(map, invMap));\n  cartesian->image = cv::Mat(height, width, CV_8UC1);\n  cartesian->mask = cv::Mat(height, width, CV_8UC1);\n  for (int i = 0; i < width * height; i++) {\n    if (map[i] == -1) {\n      cartesian->image.data[i] = 0;\n      cartesian->mask.data[i] = 0;\n    } else {\n      cartesian->image.data[i] = _image.data[map[i]];\n      cartesian->mask.data[i] = 255;\n    }\n  }\n\n  return cartesian;\n}\n\n// constructor taking a DIDSON frame\nDidson::Didson(int windowStart, int windowLength,\n               const isam::Pose3d& vehiclePose, double tiltRad, double rollRad,\n               const unsigned char* data, bool transformFrame) :\n    Sonar(consts.startBase * windowStart,\n        consts.startBase * windowStart + consts.lengths[windowLength],\n        consts.bearingFov, consts.elevationFov, consts.numBearings,\n        consts.numRanges), _tiltRad(tiltRad), _rollRad(\n        rollRad), _vehiclePose(vehiclePose) {\n  if (windowStart < 1 || windowStart > 31) {\n    cout << \"ERROR: windowStart out of range\" << endl;\n    exit(1);\n  }\n  if (windowLength < 0 || windowLength > 3) {\n    cout << \"ERROR: windowLength out of range\" << endl;\n    exit(1);\n  }\n\n  _image = cv::Mat(consts.numRanges, consts.numBearings, CV_8UC1);\n  if (data)\n      memcpy(_image.data, data, consts.numRanges * consts.numBearings);\n\n  // we assume DIDSON facing to the right (DVL in hull lock mode)\n  // i.e. 90 degrees yaw and -90 degrees roll configuration + tilt and roll actuators\n  if (transformFrame) {\n      Pose3d didsonOffset(0, 0.2, 0, 0, 0, 0); // DIDSON is to the right of the DVL along y  // todo: check DIDSON offset\n      Pose3d didsonActuators(0, 0, 0, M_PI * 0.5, tiltRad, rollRad - M_PI * 0.5);\n      _didsonPose = vehiclePose.oplus(didsonOffset).oplus(didsonActuators);\n  } else {\n      _didsonPose = vehiclePose;\n  }\n}\n\nPose3d Didson::didsonHuls3Pose() const {\n  return _didsonPose;\n}\n\nvector<Point3d> Didson::getFrustum() const {\n  return Sonar::getFrustum(didsonHuls3Pose());\n}\n\nbool Didson::project(const isam::Point3d& point,\n    isam::Point2d& projection) const {\n  return Sonar::project(didsonHuls3Pose(), point, projection);\n}\n\n} /* namespace sonar */\n", "meta": {"hexsha": "3e5d0a4db9cf5cf26fd5aae084477bd6ca73dd77", "size": 7837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ts-sonar/Didson.cpp", "max_stars_repo_name": "mattjr/structured", "max_stars_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "ts-sonar/Didson.cpp", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "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": "ts-sonar/Didson.cpp", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 32.5186721992, "max_line_length": 121, "alphanum_fraction": 0.6377440347, "num_tokens": 2456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802317779601, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5117541016455238}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2014-2015 Oracle and/or its affiliates.\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n#include <iostream>\n\n#ifndef BOOST_TEST_MODULE\n#define BOOST_TEST_MODULE test_sym_difference_areal_areal\n#endif\n\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\n#define BOOST_GEOMETRY_DEBUG_TURNS\n#define BOOST_GEOMETRY_DEBUG_SEGMENT_IDENTIFIER\n#endif\n\n#include <boost/test/included/unit_test.hpp>\n\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/multi_linestring.hpp>\n#include <boost/geometry/algorithms/sym_difference.hpp>\n\n#include \"../difference/test_difference.hpp\"\n#include <from_wkt.hpp>\n\ntypedef bg::model::point<double,2,bg::cs::cartesian>  point_type;\ntypedef bg::model::ring<point_type> ring_type; // ccw, closed\ntypedef bg::model::polygon<point_type> polygon_type; // ccw, closed\ntypedef bg::model::multi_polygon<polygon_type> multi_polygon_type;\n\ndouble const default_tolerance = 0.0001;\n\ntemplate\n<\n    typename Areal1, typename Areal2, typename PolygonOut\n>\nstruct test_sym_difference_of_areal_geometries\n{\n    static inline void apply(std::string const& case_id,\n                             Areal1 const& areal1,\n                             Areal2 const& areal2,\n                             int expected_polygon_count,\n                             int expected_point_count,\n                             double expected_area,\n                             double tolerance = default_tolerance)\n    {\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\n        bg::model::multi_polygon<PolygonOut> sdf;\n\n        bg::sym_difference(areal1, areal2, sdf);\n\n        std::cout << \"Case ID: \" << case_id << std::endl;\n        std::cout << \"Geometry #1: \" << bg::wkt(areal1) << std::endl;\n        std::cout << \"Geometry #2: \" << bg::wkt(areal2) << std::endl;\n        std::cout << \"Sym diff: \" << bg::wkt(sdf) << std::endl;\n        std::cout << \"Polygon count: expected: \"\n                  << expected_polygon_count\n                  << \"; detected: \" << sdf.size() << std::endl;\n        std::cout << \"Point count: expected: \"\n                  << expected_point_count\n                  << \"; detected: \" << bg::num_points(sdf) << std::endl;\n        std::cout << \"Area: expected: \"\n                  << expected_area\n                  << \"; detected: \" << bg::area(sdf) << std::endl;\n#endif\n        ut_settings settings;\n        settings.percentage = tolerance;\n\n        test_difference\n            <\n                PolygonOut\n            >(case_id, areal1, areal2,\n              expected_polygon_count, expected_point_count, expected_area,\n              true, settings);\n    }\n};\n\n\n//===========================================================================\n//===========================================================================\n//===========================================================================\n\n\nBOOST_AUTO_TEST_CASE( test_sym_difference_ring_ring )\n{\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\n    std::cout << std::endl << std::endl << std::endl;\n    std::cout << \"*** RING / RING SYMMETRIC DIFFERENCE ***\" << std::endl;\n    std::cout << std::endl;\n#endif\n\n    typedef ring_type R;\n    typedef polygon_type PG;\n\n    typedef test_sym_difference_of_areal_geometries<R, R, PG> tester;\n\n    tester::apply(\"r-r-sdf00\",\n                  from_wkt<R>(\"POLYGON((0 0,0 10,10 10,10 0,0 0))\"),\n                  from_wkt<R>(\"POLYGON((10 0,10 20,20 20,20 0,10 0))\"),\n                  1,\n                  8,\n                  300);\n\n    tester::apply(\"r-r-sdf01\",\n                  from_wkt<R>(\"POLYGON((0 0,0 10,10 10,10 0,0 0))\"),\n                  from_wkt<R>(\"POLYGON((9 0,9 20,20 20,20 0,9 0))\"),\n                  2,\n                  12,\n                  300);\n}\n\n\nBOOST_AUTO_TEST_CASE( test_sym_difference_polygon_multipolygon )\n{\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\n    std::cout << std::endl << std::endl << std::endl;\n    std::cout << \"*** POLYGON / MULTIPOLYGON SYMMETRIC DIFFERENCE ***\"\n              << std::endl;\n    std::cout << std::endl;\n#endif\n\n    typedef polygon_type PG;\n    typedef multi_polygon_type MPG;\n\n    typedef test_sym_difference_of_areal_geometries<PG, MPG, PG> tester;\n\n    tester::apply\n        (\"pg-mpg-sdf00\",\n         from_wkt<PG>(\"POLYGON((10 0,10 10,20 10,20 0,10 0))\"),\n         from_wkt<MPG>(\"MULTIPOLYGON(((0 0,0 10,10 10,10 0,0 0)),\\\n                       ((20 0,20 10,30 10,30 0,20 0)))\"),\n         1,\n         6,\n         300);\n}\n", "meta": {"hexsha": "dc30c0ede987b27119e51fdf8e90f980043b1c39", "size": 4584, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/geometry/test/algorithms/set_operations/sym_difference/sym_difference_areal_areal.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/geometry/test/algorithms/set_operations/sym_difference/sym_difference_areal_areal.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/geometry/test/algorithms/set_operations/sym_difference/sym_difference_areal_areal.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": 32.7428571429, "max_line_length": 77, "alphanum_fraction": 0.565008726, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5117297471880193}}
{"text": "/*\n * SPDX-FileCopyrightText: \u00a9 2018 Ambrosys GmbH\n *\n * SPDX-License-Identifier: Apache-2.0\n */\n\n#include <Core/Common/Geometry/Helper.h>\n\n#include <boost/geometry/strategies/spherical/distance_haversine.hpp>\n\nnamespace Core::Common::Geometry {\n\nstd::pair<Point, double> project(Point const & p, Segment const & segment)\n{\n    using boost::geometry::add_point;\n    using boost::geometry::dot_product;\n    using boost::geometry::multiply_value;\n    using boost::geometry::subtract_point;\n\n    auto const & p1 = segment.first;\n    auto const & p2 = segment.second;\n    auto p1p = p;\n    subtract_point(p1p, p1);\n\n    auto p1p2 = p2;\n    subtract_point(p1p2, p1);\n\n    const double segmentLength_sqred = dot_product(p1p2, p1p2);\n    const double normLengthProjection = dot_product(p1p, p1p2) / segmentLength_sqred;\n\n    auto projected = p1p2;\n    multiply_value(projected, normLengthProjection);\n    add_point(projected, p1);\n\n    return {projected, normLengthProjection};\n}\n\nstd::pair<Point, double> snap(Point const & p, Segment const segment)\n{\n    auto const result = project(p, segment);\n    auto const & projected = result.first;\n    auto const normLengthProjection = result.second;\n\n    if (normLengthProjection <= 0.0)\n    {\n        return {segment.first, normLengthProjection};\n    }\n    else if (normLengthProjection >= 1.0)\n    {\n        return {segment.second, normLengthProjection};\n    }\n    else\n    {\n        return {projected, normLengthProjection};\n    }\n}\n\nPoint reverseHaversine(Point const & p, double bearing, double distanceMeter)\n{\n    using std::atan2;\n    using std::cos;\n    using std::sin;\n\n    auto lon1 = rad(p.lon());\n    auto lat1 = rad(p.lat());\n    auto angdist = distanceMeter / equatorRadiusMeter;\n    auto theta = rad(bearing);\n    auto lat2 = asin(sin(lat1) * cos(angdist) + cos(lat1) * sin(angdist) * cos(theta));\n    auto lon2 = lon1 + atan2(sin(theta) * sin(angdist) * cos(lat1), cos(angdist) - sin(lat1) * sin(lat2));\n    return Point{}.setLon(degree(lon2)).setLat(degree(lat2));\n}\n\nBox buffer(Box const & box, double distanceMeter)\n{\n    constexpr auto sqrtOf2 = 1.414213562373095049;\n    auto min_corner = reverseHaversine(box.min_corner(), 225.0, sqrtOf2 * distanceMeter);\n    auto max_corner = reverseHaversine(box.max_corner(), 45.0, sqrtOf2 * distanceMeter);\n    return {min_corner, max_corner};\n}\n\nValueType geoDistance(Point const & g1, Point const & g2)\n{\n    auto strategy = boost::geometry::strategy::distance::haversine<double>(equatorRadiusMeter);\n    return boost::geometry::distance(g1, g2, strategy);\n}\n\nstd::tuple<ValueType, Point, double> geoDistance(Point const & g1, Segment const & g2)\n{\n    auto const clipped = snap(g1, g2);\n    return {geoDistance(g1, clipped.first), clipped.first, clipped.second};\n}\n\ndouble heading(Point const & p1, Point const & p2)\n{\n    auto deltaLon = rad(p2.lon()) - rad(p1.lon());\n    auto cos_p2lat = cos(rad(p2.lat()));\n    auto angle = atan2(sin(deltaLon) * cos_p2lat, cos(rad(p1.lat())) * sin(rad(p2.lat())) - sin(rad(p1.lat())) * cos_p2lat * cos(deltaLon));\n    return normalizeAngle(degree(angle));\n}\n\ndouble heading(Segment const & segment)\n{\n    return heading(segment.first, segment.second);\n}\n\ndouble normalizeAngle(double angle)\n{\n    angle = std::fmod(angle, 360.0);\n    return angle < 0.0 ? angle + 360.0 : angle;\n}\n\ndouble headingDiff(double a, double b)\n{\n    auto res = normalizeAngle(a - b);\n    return res > 180.0 ? res - 360.0 : res;\n}\n\ndouble absHeadingDiff(double a, double b)\n{\n    return std::abs(headingDiff(a, b));\n}\n\ndouble reversedHeading(double heading)\n{\n    if (heading >= 180.0)\n        return heading - 180.0;\n    else\n        return heading + 180.0;\n}\n\nLineStringProjectionResult projectOntoLineString(Point const & point, LineString const & lineString)\n{\n    assert(lineString.size() > 1);\n\n    auto minSnapped = snap(point, Segment{lineString[0], lineString[1]});\n    auto minDistance = geoDistance(point, minSnapped.first);\n    size_t idx = 1;\n    for (size_t i = 2; i < lineString.size(); ++i)\n    {\n        auto snapped = snap(point, Segment{lineString[i - 1u], lineString[i]});\n        auto distance = geoDistance(point, snapped.first);\n\n        if (distance < minDistance)\n        {\n            minSnapped = snapped;\n            minDistance = distance;\n            idx = i;\n        }\n    }\n\n    auto result = LineStringProjectionResult{};\n    result.projectionPoint = minSnapped.first;\n    result.distanceToSegment = minDistance;\n    result.segmentHeading = heading(Segment{lineString[idx - 1u], lineString[idx]});\n\n    result.distanceAlongLineString = 0.0;\n    for (size_t i = 1; i < idx; ++i)\n    {\n        result.distanceAlongLineString += geoDistance(lineString[i - 1u], lineString[i]);\n    }\n    result.distanceAlongLineString += geoDistance(lineString[idx - 1u], minSnapped.first);\n\n    if (idx == 1 and minSnapped.second < 0.0)\n    {\n        result.offLineString = true;\n    }\n    else if (idx == lineString.size() - 1u and minSnapped.second > 1.0)\n    {\n        result.offLineString = true;\n    }\n    else\n    {\n        result.offLineString = false;\n    }\n    return result;\n}\n\ndouble relativeDistanceAlongLineString(LineString const & lineString, Point const & point)\n{\n    auto result = projectOntoLineString(point, lineString);\n    return result.distanceAlongLineString / geoLength(lineString);\n}\n\n/**\n * Returns the angle between segment1 and segment2 in range [180\u00b0, -180\u00b0].\n */\ndouble angleBetweenSegments(Segment const & segment1, Segment const & segment2)\n{\n    auto headingSeg1 = heading(segment1);\n    auto headingSeg2 = heading(segment2);\n    return headingDiff(headingSeg1, headingSeg2);\n}\n\nstd::vector<Core::Common::Geometry::Point> trimmed(std::vector<Core::Common::Geometry::Point> const & points, double const trimLeft, double const trimRight)\n{\n    std::vector<Core::Common::Geometry::Point> newPoints;\n    std::shared_ptr<Core::Common::Geometry::Point> newStart;\n    std::shared_ptr<Core::Common::Geometry::Point> newEnd;\n    size_t oldBegin = 0;\n    size_t oldEnd = points.size();\n\n    double a = 0.0;\n    for (size_t i = 0; i < points.size() - 1; ++i)\n    {\n        a += Core::Common::Geometry::geoDistance(points[i], points[i + 1]);\n        if (a >= trimLeft)\n        {\n            oldBegin = i + 1;\n            if (a > trimLeft)\n                newStart = std::make_shared<Core::Common::Geometry::Point>(\n                    Core::Common::Geometry::reverseHaversine(points[i + 1], Core::Common::Geometry::heading(points[i + 1], points[i]), a - trimLeft));\n            break;\n        }\n    }\n\n    a = 0.0;\n    for (size_t i = points.size() - 1; i > 0; --i)\n    {\n        a += Core::Common::Geometry::geoDistance(points[i], points[i - 1]);\n        if (a >= trimRight)\n        {\n            oldEnd = i;\n            if (a > trimRight)\n            {\n                newEnd = std::make_shared<Core::Common::Geometry::Point>(\n                    Core::Common::Geometry::reverseHaversine(points[i - 1], Core::Common::Geometry::heading(points[i - 1], points[i]), a - trimRight));\n            }\n            break;\n        }\n    }\n\n    if (newStart)\n        newPoints.push_back(*newStart);\n    newPoints.insert(newPoints.end(), points.begin() + oldBegin, points.begin() + oldEnd);\n    if (newEnd)\n        newPoints.push_back(*newEnd);\n\n    return newPoints;\n}\n\n}  // namespace Core::Common::Geometry", "meta": {"hexsha": "cddc9351ef9f1a0450c9feccee9e8394f97a3b5e", "size": 7348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Core/Common/Geometry/Helper.cpp", "max_stars_repo_name": "bibermann/os-matcher", "max_stars_repo_head_hexsha": "cda938e8ed1334bae755351123eb4554bcd0647d", "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/Common/Geometry/Helper.cpp", "max_issues_repo_name": "bibermann/os-matcher", "max_issues_repo_head_hexsha": "cda938e8ed1334bae755351123eb4554bcd0647d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-09-21T10:56:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-12T01:08:39.000Z", "max_forks_repo_path": "src/Core/Common/Geometry/Helper.cpp", "max_forks_repo_name": "Ambrosys/os-matcher", "max_forks_repo_head_hexsha": "cda938e8ed1334bae755351123eb4554bcd0647d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-06-09T05:40:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T23:11:55.000Z", "avg_line_length": 30.489626556, "max_line_length": 156, "alphanum_fraction": 0.6445291236, "num_tokens": 1953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5117033761618436}}
{"text": "/**\n * @file local_coordinate_coding_test.cpp\n * @author Nishant Mehta\n *\n * Test for Local Coordinate Coding.\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\n// Note: We don't use BOOST_REQUIRE_CLOSE in the code below because we need\n// to use FPC_WEAK, and it's not at all intuitive how to do that.\n#include <mlpack/methods/local_coordinate_coding/lcc.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n#include \"serialization.hpp\"\n\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::regression;\nusing namespace mlpack::lcc;\n\nBOOST_AUTO_TEST_SUITE(LocalCoordinateCodingTest);\n\nvoid VerifyCorrectness(const vec& beta, const vec& errCorr, double lambda)\n{\n  const double tol = 0.1;\n  size_t nDims = beta.n_elem;\n  for (size_t j = 0; j < nDims; j++)\n  {\n    if (beta(j) == 0)\n    {\n      // make sure that errCorr(j) <= lambda\n      BOOST_REQUIRE_SMALL(std::max(fabs(errCorr(j)) - lambda, 0.0), tol);\n    }\n    else if (beta(j) < 0)\n    {\n      // make sure that errCorr(j) == lambda\n      BOOST_REQUIRE_SMALL(errCorr(j) - lambda, tol);\n    }\n    else\n    { // beta(j) > 0\n      // make sure that errCorr(j) == -lambda\n      BOOST_REQUIRE_SMALL(errCorr(j) + lambda, tol);\n    }\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(LocalCoordinateCodingTestCodingStep)\n{\n  double lambda1 = 0.1;\n  uword nAtoms = 10;\n\n  mat X;\n  X.load(\"mnist_first250_training_4s_and_9s.arm\");\n  uword nPoints = X.n_cols;\n\n  // normalize each point since these are images\n  for (uword i = 0; i < nPoints; i++)\n  {\n    X.col(i) /= norm(X.col(i), 2);\n  }\n\n  mat Z;\n  LocalCoordinateCoding lcc(X, nAtoms, lambda1, 10);\n  lcc.Encode(X, Z);\n\n  mat D = lcc.Dictionary();\n\n  for (uword i = 0; i < nPoints; i++)\n  {\n    vec sqDists = vec(nAtoms);\n    for (uword j = 0; j < nAtoms; j++)\n    {\n      sqDists[j] = arma::norm(D.col(j) - X.col(i));\n    }\n    mat Dprime = D * diagmat(1.0 / sqDists);\n    mat zPrime = Z.unsafe_col(i) % sqDists;\n\n    vec errCorr = trans(Dprime) * (Dprime * zPrime - X.unsafe_col(i));\n    VerifyCorrectness(zPrime, errCorr, 0.5 * lambda1);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(LocalCoordinateCodingTestDictionaryStep)\n{\n  const double tol = 0.1;\n\n  double lambda = 0.1;\n  uword nAtoms = 10;\n\n  mat X;\n  X.load(\"mnist_first250_training_4s_and_9s.arm\");\n  uword nPoints = X.n_cols;\n\n  // normalize each point since these are images\n  for (uword i = 0; i < nPoints; i++)\n  {\n    X.col(i) /= norm(X.col(i), 2);\n  }\n\n  mat Z;\n  LocalCoordinateCoding lcc(X, nAtoms, lambda, 10);\n  lcc.Encode(X, Z);\n  uvec adjacencies = find(Z);\n  lcc.OptimizeDictionary(X, Z, adjacencies);\n\n  mat D = lcc.Dictionary();\n\n  mat grad = zeros(D.n_rows, D.n_cols);\n  for (uword i = 0; i < nPoints; i++)\n  {\n    grad += (D - repmat(X.unsafe_col(i), 1, nAtoms)) *\n        diagmat(abs(Z.unsafe_col(i)));\n  }\n  grad = lambda * grad + (D * Z - X) * trans(Z);\n\n  BOOST_REQUIRE_SMALL(norm(grad, \"fro\"), tol);\n}\n\nBOOST_AUTO_TEST_CASE(SerializationTest)\n{\n  mat X = randu<mat>(100, 100);\n  size_t nAtoms = 10;\n\n  LocalCoordinateCoding lcc(nAtoms, 0.05, 2 /* don't care about quality */);\n  lcc.Train(X);\n\n  mat Y = randu<mat>(100, 200);\n  mat codes;\n  lcc.Encode(Y, codes);\n\n  LocalCoordinateCoding lccXml(50, 0.1), lccText(12, 0.0), lccBinary(0, 0.0);\n  SerializeObjectAll(lcc, lccXml, lccText, lccBinary);\n\n  CheckMatrices(lcc.Dictionary(), lccXml.Dictionary(), lccText.Dictionary(),\n      lccBinary.Dictionary());\n\n  mat xmlCodes, textCodes, binaryCodes;\n  lccXml.Encode(Y, xmlCodes);\n  lccText.Encode(Y, textCodes);\n  lccBinary.Encode(Y, binaryCodes);\n\n  CheckMatrices(codes, xmlCodes, textCodes, binaryCodes);\n\n  // Check the parameters, too.\n  BOOST_REQUIRE_EQUAL(lcc.Atoms(), lccXml.Atoms());\n  BOOST_REQUIRE_EQUAL(lcc.Atoms(), lccText.Atoms());\n  BOOST_REQUIRE_EQUAL(lcc.Atoms(), lccBinary.Atoms());\n\n  BOOST_REQUIRE_CLOSE(lcc.Tolerance(), lccXml.Tolerance(), 1e-5);\n  BOOST_REQUIRE_CLOSE(lcc.Tolerance(), lccText.Tolerance(), 1e-5);\n  BOOST_REQUIRE_CLOSE(lcc.Tolerance(), lccBinary.Tolerance(), 1e-5);\n\n  BOOST_REQUIRE_CLOSE(lcc.Lambda(), lccXml.Lambda(), 1e-5);\n  BOOST_REQUIRE_CLOSE(lcc.Lambda(), lccText.Lambda(), 1e-5);\n  BOOST_REQUIRE_CLOSE(lcc.Lambda(), lccBinary.Lambda(), 1e-5);\n\n  BOOST_REQUIRE_EQUAL(lcc.MaxIterations(), lccXml.MaxIterations());\n  BOOST_REQUIRE_EQUAL(lcc.MaxIterations(), lccText.MaxIterations());\n  BOOST_REQUIRE_EQUAL(lcc.MaxIterations(), lccBinary.MaxIterations());\n}\n\n/**\n * Test that LocalCoordinateCoding::Train() returns finite final objective\n * value.\n */\nBOOST_AUTO_TEST_CASE(LocalCoordinateCodingTrainReturnObjective)\n{\n  double lambda1 = 0.1;\n  uword nAtoms = 10;\n\n  mat X;\n  X.load(\"mnist_first250_training_4s_and_9s.arm\");\n  uword nPoints = X.n_cols;\n\n  // Normalize each point since these are images.\n  for (uword i = 0; i < nPoints; i++)\n  {\n    X.col(i) /= norm(X.col(i), 2);\n  }\n\n  LocalCoordinateCoding lcc(nAtoms, lambda1, 10);\n  double objVal = lcc.Train(X);\n\n  BOOST_REQUIRE_EQUAL(std::isfinite(objVal), true);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "c809a9399e2ef379466fe9ea142d42838f22033b", "size": 5213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/local_coordinate_coding_test.cpp", "max_stars_repo_name": "tomjpsun/mlpack", "max_stars_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "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": "2020-01-11T14:14:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T14:14:30.000Z", "max_issues_repo_path": "src/mlpack/tests/local_coordinate_coding_test.cpp", "max_issues_repo_name": "tomjpsun/mlpack", "max_issues_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-10T17:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-11T14:56:25.000Z", "max_forks_repo_path": "src/mlpack/tests/local_coordinate_coding_test.cpp", "max_forks_repo_name": "tomjpsun/mlpack", "max_forks_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "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": 26.8711340206, "max_line_length": 78, "alphanum_fraction": 0.6765777863, "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5117033699120309}}
{"text": "#include \"model_distribution.hpp\"\n\n#include \"monte_carlo_integration.hpp\"\n#include \"multinomial.hpp\"\n#include \"multivariate_guassian.hpp\"\n#include \"mvi3/mvi3.hpp\"\n#include \"types.hpp\"\n#include \"utils.hpp\"\n\n#include <algorithm>\n#include <boost/log/trivial.hpp>\n#include <numeric>\n#include <vector>\n\nnamespace FilterModel {\nModelDistribution::ModelDistribution(const std::vector<category_counts_t> &data,\n                                     std::default_random_engine &generator, const Options &options)\n    : data(data), generator(generator), options(options){};\n\nstd::vector<std::vector<double>> ModelDistribution::distribution(\n    const std::vector<std::vector<alpha_t>> &alphas_per_object, double epsilon,\n    const delta_t &delta) const {\n    // See function definition for description.\n    std::vector<std::vector<double>> log_alpha_likelyhoods_per_object(data.size(),\n                                                                      std::vector<double>());\n    for (int obs_index = 0; obs_index < data.size(); ++obs_index) {\n        const category_counts_t &object_counts = data.at(obs_index);\n        const std::vector<alpha_t> &alphas = alphas_per_object.at(obs_index);\n\n        int n = std::accumulate(object_counts.begin(), object_counts.end(), 0);\n        std::vector<double> p = {1 - epsilon, epsilon};\n        Multinomial n_positive_distribution(n, p);\n\n        for (int alpha_index = 0; alpha_index < alphas.size(); ++alpha_index) {\n            const alpha_t &alpha = alphas.at(alpha_index);\n\n            // n^+ goes from 0 to the sum of k_i for which alpha_i is true\n            // When alpha_i is false, then all of the k_i corresponding must be noise reads.\n            const category_counts_t filtered_object_counts = filter_by_alpha(alpha, object_counts);\n            const int max_n_positive =\n                std::accumulate(filtered_object_counts.begin(), filtered_object_counts.end(), 0);\n\n            std::vector<double> log_p_k_n_positive_given_all_terms;\n            // n_positive is the number of observations not made by the error process.\n            for (int n_positive = 0; n_positive <= max_n_positive; ++n_positive) {\n                // n_negative is the number of observations made by the error process.\n                int n_negative = n - n_positive;\n                double log_p_n_plus_given_n_epsilon =\n                    n_positive_distribution.log_pdf(std::vector<int>({n_positive, n_negative}));\n\n                double log_p_k_positive_given_alpha_n_positive =\n                    calculate_log_p_k_positive_given_alpha_n_positive(n_positive, alpha);\n\n                double log_sum_over_k_negative = calculate_log_sum_over_k_negative(\n                    n_positive, n_negative, alpha, delta, object_counts);\n\n                double log_p_k_n_positive_given_all = log_p_n_plus_given_n_epsilon +\n                                                      log_p_k_positive_given_alpha_n_positive +\n                                                      log_sum_over_k_negative;\n\n                log_p_k_n_positive_given_all_terms.push_back(log_p_k_n_positive_given_all);\n            }\n\n            std::vector<double> p_k_n_positive_given_all =\n                exp<double>(log_p_k_n_positive_given_all_terms);\n\n            log_alpha_likelyhoods_per_object.at(obs_index).push_back(\n                std::log(stable_sum<double>(p_k_n_positive_given_all)));\n        }\n    }\n    return log_alpha_likelyhoods_per_object;\n}\n\nstd::vector<std::vector<double>> ModelDistribution::distribution(const std::vector<alpha_t> &alphas,\n                                                                 double epsilon,\n                                                                 const delta_t &delta) const {\n    std::vector<std::vector<alpha_t>> alphas_per_obs(data.size(), alphas);\n    return distribution(alphas_per_obs, epsilon, delta);\n}\n\ndouble ModelDistribution::calculate_log_p_k_positive_given_alpha_n_positive(int n_positive,\n                                                                            const alpha_t &alpha) {\n    int sum_alpha = accumulate(alpha.begin(), alpha.end(), 0);\n\n    // 1/(n^+ + sum alpha_i - 1 choose n^+)\n    // lgamma(x + 1) = log(x!)\n    double log_p_k_given_alpha_n_positive =\n        lgamma(n_positive + 1) + lgamma(sum_alpha) - lgamma(n_positive + sum_alpha);\n    return log_p_k_given_alpha_n_positive;\n}\n\ndouble ModelDistribution::calculate_log_sum_over_k_negative(\n    int n_positive, int n_negative, const alpha_t &alpha, const delta_t &delta,\n    const category_counts_t &object_counts) const {\n    // TODO(joschnie): Check for viability and return -1 if unviable.\n\n    int n = n_positive + n_negative;\n\n    delta_t delta_for_alpha_true = filter_by_alpha(alpha, delta);\n\n    double sum_over_k_negative;\n    if (options.comparison) {\n        sum_over_k_negative = calculate_sum_over_k_negative_exact(n_positive, n_negative, alpha,\n                                                                  delta, object_counts);\n        double sum_over_k_negative_approx = calculate_sum_over_k_negative_approx(\n            n_positive, n_negative, alpha, delta, object_counts);\n        double error = sum_over_k_negative - sum_over_k_negative_approx;\n\n        BOOST_LOG_TRIVIAL(info) << \"Approximation error: \" << std::to_string(error);\n    } else {\n        if (!can_use_normal_approx(n_negative, delta_for_alpha_true)) {\n            sum_over_k_negative = calculate_sum_over_k_negative_exact(n_positive, n_negative, alpha,\n                                                                      delta, object_counts);\n        } else {\n            sum_over_k_negative = calculate_sum_over_k_negative_approx(n_positive, n_negative,\n                                                                       alpha, delta, object_counts);\n        }\n    }\n\n    return std::log(sum_over_k_negative);\n}\n\ndouble ModelDistribution::calculate_sum_over_k_negative_exact(\n    int n_positive, int n_negative, const alpha_t &alpha, const delta_t &delta,\n    const category_counts_t &object_counts) {\n    Multinomial k_negative_distribution(n_negative, delta);\n\n    std::vector<double> log_p_k_positive_given_delta_n_negative;\n\n    iterate_over_k_negatives(\n        [&log_p_k_positive_given_delta_n_negative, &k_negative_distribution](\n            int k_1_negative, int k_2_negative, int k_3_negative) {\n            log_p_k_positive_given_delta_n_negative.push_back(\n                k_negative_distribution.log_pdf({k_1_negative, k_2_negative, k_3_negative}));\n        },\n        n_positive, n_negative, alpha, object_counts);\n\n    std::vector<double> p_k_positive_given_delta_n_negative =\n        exp(log_p_k_positive_given_delta_n_negative);\n    return stable_sum<double>(p_k_positive_given_delta_n_negative);\n}\n\nvoid ModelDistribution::iterate_over_k_negatives(std::function<void(int, int, int)> f,\n                                                 int n_positive, int n_negative,\n                                                 const alpha_t &alpha,\n                                                 const category_counts_t &object_counts) {\n    // Because some alpha_i might be 0, we have to fix some of the k^- values to start with.\n    std::vector<int> fixed_k_negative = {0, 0, 0};\n    for (int i = 0; i < 3; ++i) {\n        if (alpha.at(i) == false) {\n            fixed_k_negative.at(i) = object_counts.at(i);\n        }\n    }\n\n    int k_1_negative_start = std::max({object_counts[0] - n_positive, fixed_k_negative[0],\n                                       n_negative - object_counts[1] - object_counts[2]});\n    int k_1_negative_end =\n        std::min(n_negative - fixed_k_negative[1] - fixed_k_negative[2], object_counts[0]);\n    for (int k_1_negative = k_1_negative_start; k_1_negative <= k_1_negative_end; ++k_1_negative) {\n        int k_2_negative_start = std::max({object_counts[1] - n_positive, fixed_k_negative[1],\n                                           n_negative - k_1_negative - object_counts[2]});\n        int k_2_negative_end =\n            std::min(n_negative - k_1_negative - fixed_k_negative[2], object_counts[1]);\n        for (int k_2_negative = k_2_negative_start; k_2_negative <= k_2_negative_end;\n             ++k_2_negative) {\n            int k_3_negative = n_negative - k_1_negative - k_2_negative;\n            if (alpha[2] == false && k_3_negative == object_counts[2] ||\n                alpha[2] == true && k_3_negative >= 0 && k_3_negative <= object_counts[2]) {\n                f(k_1_negative, k_2_negative, k_3_negative);\n            }\n        }\n    }\n}\n\ndouble ModelDistribution::calculate_sum_over_k_negative_approx(\n    int n_positive, int n_negative, const alpha_t &alpha, const delta_t &delta,\n    const category_counts_t &object_counts) {\n    std::vector<bool> object_count_nonzero(object_counts.size(), false);\n    std::transform(object_counts.begin(), object_counts.end(), object_count_nonzero.begin(),\n                   [](int count) { return count > 0; });\n\n    std::vector<bool> effective_alpha;\n    for (int i = 0; i < alpha.size(); ++i) {\n        effective_alpha.push_back(alpha.at(i) && object_count_nonzero.at(i));\n    }\n\n    category_counts_t filtered_object_counts = filter_by_alpha(effective_alpha, object_counts);\n\n    if (effective_alpha == std::vector<bool>({0, 0, 0})) {\n        return 0;\n    }\n\n    Multinomial m_fixed =\n        Multinomial(n_negative, delta)\n            .fix_dimensions(not_v(effective_alpha),\n                            filter_by_alpha(effective_alpha, object_counts, false));\n\n    double sum_over_k_negative_approx;\n    if (m_fixed.p.size() > 1) {\n        MultivariateGuassian mg = MultivariateGuassian::from_multinomial(m_fixed);\n        std::vector<std::vector<double>> hyperplanes =\n            ModelDistribution::get_hyperplanes(m_fixed.n, filtered_object_counts);\n        mg.shift_hyperplanes(hyperplanes);\n\n        MVI3::Mvi3 mvi3;\n        double log_sum_over_k_negative_approx =\n            std::log(mvi3.integrate(12456, -1, 10, 10, mg.get_covariance(), hyperplanes)) +\n            m_fixed.log_adjust;\n\n        sum_over_k_negative_approx = std::exp(log_sum_over_k_negative_approx);\n    } else {\n        if (filtered_object_counts.size() > 0 && filtered_object_counts.back() >= m_fixed.n) {\n            sum_over_k_negative_approx = std::exp(m_fixed.log_adjust);\n            // TODO(joschnei): condition above is wrong. Need to check both n+ and n-b\n        } else {\n            sum_over_k_negative_approx = 0;\n        }\n    }\n    return sum_over_k_negative_approx;\n}\n\ndouble ModelDistribution::calculate_sum_over_k_negative_approx_2(\n    int n_positive, int n_negative, const alpha_t &alpha, const delta_t &delta,\n    const category_counts_t &object_counts) {\n    Multinomial m_fixed =\n        Multinomial(n_negative, delta)\n            .fix_dimensions(not_v(alpha), filter_by_alpha(alpha, object_counts, false));\n    MultivariateGuassian mg = MultivariateGuassian::from_multinomial(m_fixed);\n\n    std::function<double(std::vector<double>)> multivariate_guassian_density =\n        [mg](std::vector<double> point) { return mg.density(point); };\n\n    std::function<std::vector<double>(std::default_random_engine &)> sampler =\n        [m_fixed, object_counts = filter_by_alpha(alpha, object_counts)](\n            std::default_random_engine &generator) {\n            int dim = m_fixed.p.size();\n\n            std::vector<std::uniform_real_distribution<double>> dists;\n            for (int i = 0; i < dim - 1; ++i) {\n                dists.push_back(std::uniform_real_distribution<double>(0.0, object_counts.at(i)));\n            }\n\n            std::vector<double> point;\n            double last_component;\n            do {\n                point = std::vector<double>();\n                for (std::uniform_real_distribution<double> dist : dists) {\n                    point.push_back(dist(generator));\n                }\n                last_component = m_fixed.n - std::accumulate(point.begin(), point.end(), 0.0);\n            } while (!(0 <= last_component && last_component <= object_counts.back()));\n            return point;\n        };\n\n    double volume;\n    if (m_fixed.p.size() == 3) {\n        volume = n_negative * object_counts.at(2) - std::pow(object_counts.at(2), 2) / 2.0;\n        if (n_negative > object_counts.at(0)) {\n            volume -= 1.0 / 2.0 * std::pow(n_negative - object_counts.at(0), 2);\n            if (n_negative - object_counts.at(2) > object_counts.at(0)) {\n                volume +=\n                    1.0 / 2.0 * std::pow(n_negative - object_counts.at(2) - object_counts.at(0), 2);\n            }\n        }\n        if (n_negative > object_counts.at(1)) {\n            volume -= 1.0 / 2.0 * std::pow(n_negative - object_counts.at(1), 2);\n            if (n_negative - object_counts.at(2) > object_counts.at(1)) {\n                volume +=\n                    1.0 / 2.0 * std::pow(n_negative - object_counts.at(2) - object_counts.at(1), 2);\n            }\n        }\n        if (n_negative > object_counts.at(0) + object_counts.at(1)) {\n            volume +=\n                1.0 / 2.0 * std::pow(n_negative - object_counts.at(0) - object_counts.at(1), 2);\n        }\n        if (n_negative - object_counts.at(2) < 0) {\n            volume += 1.0 / 2.0 * std::pow(n_negative - object_counts.at(2), 2.0);\n        }\n    } else if (m_fixed.p.size() == 2) {\n        volume = std::min(n_negative, object_counts.at(0)) -\n                 std::max(0, n_negative - object_counts.at(1));\n    }\n\n    return std::exp(\n        std::log(integrate(multivariate_guassian_density, sampler, generator, volume, 500000)) +\n        m_fixed.log_adjust);\n}\n\n/**\n * Assumes n_negative has already been adjusted, objct_counts has already been filtered.\n */\nstd::vector<std::vector<double>> ModelDistribution::get_hyperplanes(\n    int n_negative, category_counts_t object_counts) {\n    std::vector<std::vector<double>> hyperplanes;\n\n    // Of the the remaining dimensions, pick the last one to equal n - sum k_i.\n    category_count_t k_fixed = object_counts.back();\n    object_counts.pop_back();\n\n    // sum k_i^- = n^- => k_1^- = n^- - sum k_i^- (from 2)\n    // k_1^- >= 0 => sum k_i^- (from 2) <= n^-\n    std::vector<double> k_fixed_negative_lower_constraint(object_counts.size(), 1);\n    k_fixed_negative_lower_constraint.push_back(n_negative);\n    hyperplanes.push_back(k_fixed_negative_lower_constraint);\n\n    // sum k_i^- = n^+- => k_1^- = n^- - sum k_i^- (from 2)\n    // k_1^- <= k_1 => - sum k_i^- (from 2) <= k_1 - n^-\n    std::vector<double> k_fixed_negative_upper_constraint(object_counts.size(), -1);\n    k_fixed_negative_upper_constraint.push_back(k_fixed - n_negative);\n    hyperplanes.push_back(k_fixed_negative_upper_constraint);\n\n    // k_i^+ and k_i^- are both >= 0.\n    // k_i^- >= 0 implies -k_i^- <= 0.\n    // k_i+ >= 0 implies k_i - k_i^- >= 0 implies k_i^- <= k_i\n    for (int i = 0; i < object_counts.size(); ++i) {\n        std::vector<double> k_i_minus_constraint(object_counts.size(), 0);\n        k_i_minus_constraint.at(i) = -1;\n        k_i_minus_constraint.push_back(0);\n        hyperplanes.push_back(k_i_minus_constraint);\n\n        std::vector<double> k_i_plus_constraint(object_counts.size(), 0);\n        k_i_plus_constraint.at(i) = 1;\n        k_i_plus_constraint.push_back(object_counts.at(i));\n        hyperplanes.push_back(k_i_plus_constraint);\n    }\n\n    return hyperplanes;\n}\n\nbool ModelDistribution::can_use_normal_approx(int n_negative, const delta_t &delta) const {\n    if (options.exact) {\n        return false;\n    }\n    for (double p : delta) {\n        if (n_negative * p <= 5.0) {\n            return false;\n        }\n    }\n    return true;\n}\n}  // namespace FilterModel", "meta": {"hexsha": "9b346ece2f9ca73f140578436625bff387ae4114", "size": 15632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/model_distribution.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++/model_distribution.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++/model_distribution.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": 45.8416422287, "max_line_length": 100, "alphanum_fraction": 0.6265353122, "num_tokens": 3620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5117033699120309}}
{"text": "// Std includes\n#include <iostream> // cout, endl\n#include <vector>\n#include <memory> // shared_ptr\n#include <map>\n// Thirdparties includes\n#include <Eigen/Dense>\n// Lib includes\n#include \"v0l/bin/file_data.h\"\n#include \"m0sh/uniform.h\"\n#include \"m0sh/structured_sub.h\"\n#include \"fl0p/stationary.h\"\n\nconst unsigned int DIM = 3;\n\nusing TypeScalar = double;\nusing TypeVector = Eigen::Matrix<TypeScalar, DIM, 1>;\nusing TypeMatrix = Eigen::Matrix<TypeScalar, DIM, DIM>;\ntemplate<typename... Args>\nusing TypeRef = Eigen::Ref<Args...>;\n\ntemplate<typename ...Args>\nusing TypeContainer = std::vector<Args...>;\nusing TypeMesh = m0sh::Uniform<TypeVector, TypeRef, TypeContainer>;\nusing TypeMeshSub = m0sh::StructuredSub<TypeVector, TypeRef, TypeContainer>;\nusing TypeFlow = fl0w::fl0p::Stationary<TypeVector, TypeMatrix, TypeRef, TypeMesh, TypeContainer, TypeMeshSub, v0l::FileData>;\n\nvoid print(const TypeFlow& flow, const TypeVector& x, const TypeScalar& t) {\n    std::cout << std::endl;\n    std::cout << \"flow.getVelocity(\" << x.transpose() << \", \" << t << \") = \\n\" << flow.getVelocity(x, t).transpose() << std::endl;\n    std::cout << std::endl;\n}\n\nint main () { \n    v0l::FileData<float> vx(\"../data/v.vtk\", 0);\n    // mesh data\n    // // create lengths\n    TypeVector origin;\n    std::vector<double> lengths;\n    for(std::size_t i = 0; i < vx.meta.dimensions.size(); i++) {\n        lengths.push_back(vx.meta.dimensions[i] * vx.meta.spacing[i]);\n        origin[i] = vx.meta.origin[i];\n    }\n    // // other scalars\n    v0l::FileData<float> vy(\"../data/v.vtk\", 1);\n    v0l::FileData<float> vz(\"../data/v.vtk\", 2);\n    // // flow\n    std::cout << \"building flow...\" << std::endl;\n    TypeFlow flow(std::make_shared<TypeMesh>(vx.meta.dimensions, lengths, origin, std::vector<bool>(DIM, true)), std::vector<v0l::FileData<float>>({vx, vy, vz}), 1);\n    std::cout << \"flow built !\" << std::endl;\n\n    // Print\n    print(flow, TypeVector({-0.5, -0.5, -0.5}), 0.0);\n    print(flow, TypeVector({0.0, 0.0, 0.0}), 0.0);\n    print(flow, TypeVector({0.5, 0.5, 0.5}), 0.0);\n}\n", "meta": {"hexsha": "fcda25eec6c92dc37cf3b68e468189e60a573ed7", "size": 2055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/v0l/stationary/main.cpp", "max_stars_repo_name": "C0PEP0D/fl0p", "max_stars_repo_head_hexsha": "d65b1babfaec8b996474e42362f6819580ad3538", "max_stars_repo_licenses": ["MIT"], "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/v0l/stationary/main.cpp", "max_issues_repo_name": "C0PEP0D/fl0p", "max_issues_repo_head_hexsha": "d65b1babfaec8b996474e42362f6819580ad3538", "max_issues_repo_licenses": ["MIT"], "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/v0l/stationary/main.cpp", "max_forks_repo_name": "C0PEP0D/fl0p", "max_forks_repo_head_hexsha": "d65b1babfaec8b996474e42362f6819580ad3538", "max_forks_repo_licenses": ["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.0526315789, "max_line_length": 165, "alphanum_fraction": 0.6437956204, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5117033615789467}}
{"text": "#include <octomap/octomap.h>\n#include <pcl/common/centroid.h>\n#include <pcl/common/transforms.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n\n#include <Eigen/Dense>\n#include <unordered_map>\n#include <unordered_set>\n\n#define resolution 0.25  // unit: m\n\nint main(int argc, char** argv) {\n  std::string octomap_name = \"octomap.ot\";\n\n  // Part1: Read origin point cloud\n  Eigen::Vector4f centroid;\n  Eigen::Matrix3f covariance_matrix;\n  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_in(\n      new pcl::PointCloud<pcl::PointXYZ>);\n\n  std::cout << \" --------------- \"\n            << \" initial         \"\n            << \" --------------- \" << std::endl;\n\n  if (argc == 2) {\n    std::cout << \"use input data\" << std::endl;\n\n    if (pcl::io::loadPCDFile(argv[1], *cloud_in)) {\n      std::cerr << \"failed to open \" << argv[1] << std::endl;\n      return 1;\n    }\n\n    pcl::computeMeanAndCovarianceMatrix(*cloud_in, covariance_matrix, centroid);\n\n    Eigen::Matrix4f transform = Eigen::Matrix4f::Identity();\n    transform(0, 3) = -centroid(0);\n    transform(1, 3) = -centroid(1);\n    transform(2, 3) = -centroid(2);\n\n    pcl::transformPointCloud(*cloud_in, *cloud_in, transform);\n  }\n\n  std::cout << \"Input \" << cloud_in->size() << \" pts. \" << std::endl;\n\n  // Part2: Construct Gaussion Octomap\n  std::cout << \" --------------- \"\n            << \" compute tree    \"\n            << \" --------------- \" << std::endl;\n\n  octomap::OcTree save_tree(resolution);\n  std::unordered_multimap<octomap::OcTreeKey, pcl::PointXYZ,\n                          octomap::OcTreeKey::KeyHash>\n      unorderedMultiMap;\n  std::unordered_set<octomap::OcTreeKey, octomap::OcTreeKey::KeyHash> set;\n\n  for (auto p : (*cloud_in).points) {\n    auto key = save_tree.coordToKey(p.x, p.y, p.z, 16);\n    unorderedMultiMap.emplace(key, p);\n    set.emplace(key);\n  }\n\n  for (auto iter = set.begin(); iter != set.end(); ++iter) {\n    auto key = *iter;\n    auto range = unorderedMultiMap.equal_range(key);\n    int i = 0;\n\n    pcl::PointCloud<pcl::PointXYZ> cloud;\n    for (auto it = range.first; it != range.second; ++it) {\n      cloud.push_back(it->second);\n      i++;\n    }\n\n    if (cloud.size() < 2) continue;\n\n    save_tree.updateNode(key, true);\n  }\n\n  save_tree.updateInnerOccupancy();\n\n  // Part3: Octomap\n  save_tree.write(octomap_name);\n}", "meta": {"hexsha": "f57bfd310bb5d4d4ce558d6e3fa08614a804dec8", "size": 2306, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "octomap/src/testing/pcd2ot.cpp", "max_stars_repo_name": "Peiwvy/octomap_gaussion", "max_stars_repo_head_hexsha": "74d46af2046c8f0e95419e17a584501240e24f3c", "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": "octomap/src/testing/pcd2ot.cpp", "max_issues_repo_name": "Peiwvy/octomap_gaussion", "max_issues_repo_head_hexsha": "74d46af2046c8f0e95419e17a584501240e24f3c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "octomap/src/testing/pcd2ot.cpp", "max_forks_repo_name": "Peiwvy/octomap_gaussion", "max_forks_repo_head_hexsha": "74d46af2046c8f0e95419e17a584501240e24f3c", "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.7831325301, "max_line_length": 80, "alphanum_fraction": 0.5967042498, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6370308082623216, "lm_q1q2_score": 0.5116464526683543}}
{"text": "\n#include <cmath>\n\n#include <string>\n#include <iostream>\n#include <random>\n#include <algorithm>\n\n#include <boost/math/constants/constants.hpp>\n\n#define EIGEN_INITIALIZE_MATRICES_BY_NAN\n\n#include <cmath>\n#include <cstdlib>\n#include <complex>\n#include <type_traits>\n\n#include <iostream>\n#include <iomanip>\n\n// define the exception class, but don't override eigen's eigen_assert() macro itself\n#include <tomographer/tools/eigen_assert_exception.h>\n\n#include <Eigen/Core>\n\n#define BOOST_TEST_MODULE test_diamond_norm\n#include <boost/test/unit_test.hpp>\n\n#include \"testutils.h\"\n\n#include \"diamond_norm_figofmerit.h\"\n#include \"diamond_norm_sdpa.h\"\n#include \"diamond_norm_scs.h\"\n\n#include <tomographer/tools/boost_test_logger.h>\n#include <tomographer/mathtools/pos_semidef_util.h>\n#include <tomographer/densedm/dmtypes.h>\n\n\n// -----------------------------------------------------------------------------\n// fixture(s)\n\ntemplate<int QuDim_>\nstruct identdefs\n{\n  static constexpr int QuDim = QuDim_;\n  static constexpr int QuDim2 = QuDim*QuDim;\n\n\n  typedef Eigen::Matrix<std::complex<double>,QuDim2,1> PureKetType;\n  typedef Eigen::Matrix<std::complex<double>,QuDim2,QuDim2> ChoiMatrixType;\n  typedef Eigen::Matrix<std::complex<double>,QuDim,QuDim> ReducedDMType;\n\n  PureKetType Psi;\n  ChoiMatrixType  Eident;\n  ChoiMatrixType  Eclassident;\n\n  identdefs()\n    : Psi(PureKetType::Zero())\n  {\n    BOOST_TEST_MESSAGE(\"identdefs(), QuDim=\"<<QuDim<<\", QuDim2=\"<<QuDim2);\n\n    // initialize Psi\n    for (std::size_t j = 0; j < QuDim; ++j) {\n      Psi(j+QuDim*j) = 1;\n    }\n\n    // initialize Eident\n    Eident = Psi * Psi.adjoint();\n\n    validate_channel<double>(Eident, QuDim, QuDim, \"Eident\");\n\n    // initialize Eclassident (classical identity channel == fully depolarizing)\n    Eclassident = ChoiMatrixType::Zero();\n    for (std::size_t j = 0; j < QuDim; ++j) {\n      Eclassident(QuDim*j+j, QuDim*j+j) = 1;\n    }\n\n    validate_channel<double>(Eclassident, QuDim, QuDim, \"Eclassident\");\n\n    BOOST_TEST_MESSAGE(\"identdefs() done\");\n  }\n};\ntemplate<int QuDim_> constexpr int identdefs<QuDim_>::QuDim;\ntemplate<int QuDim_> constexpr int identdefs<QuDim_>::QuDim2;\n\n\n\n\n// -----------------------------------------------------------------------------\n// test suites\n\nBOOST_AUTO_TEST_SUITE(test_diamond_norm)\n// =============================================================================\n\nBOOST_AUTO_TEST_SUITE(examples)\n\nBOOST_FIXTURE_TEST_CASE(simple_qubit_sdpa, identdefs<2>)\n{\n  // This is now a test channel which is hopefully close to Eclassident.\n  ChoiMatrixType E;\n  E <<\n    0.9, 0, 0, 0,\n    0, 0.1, 0, 0,\n    0,   0, 0, 0,\n    0,   0, 0, 1;\n\n  const ChoiMatrixType Delta = E - Eclassident;\n\n  Tomographer::Logger::BoostTestLogger lg(Tomographer::Logger::LONGDEBUG);\n\n  DiamondNormSDPASolver<double,Tomographer::Logger::BoostTestLogger,true> d(2, 2, lg);\n  double value = d.calculate(Delta);\n\n  BOOST_CHECK_CLOSE( value, 0.1, 1e-1/*percent*/ );\n}\nBOOST_FIXTURE_TEST_CASE(simple_qubit_scs, identdefs<2>)\n{\n  // This is now a test channel which is hopefully close to Eclassident.\n  ChoiMatrixType E;\n  E <<\n    0.9, 0, 0, 0,\n    0, 0.1, 0, 0,\n    0,   0, 0, 0,\n    0,   0, 0, 1;\n\n  const ChoiMatrixType Delta = E - Eclassident;\n\n  Tomographer::Logger::BoostTestLogger lg(Tomographer::Logger::LONGDEBUG);\n\n  DiamondNormSCSSolver<double,Tomographer::Logger::BoostTestLogger,true> d(2, 2, lg);\n  double value = d.calculate(Delta);\n\n  BOOST_CHECK_CLOSE( value, 0.1, 1e-1/*percent*/ );\n}\n\nBOOST_FIXTURE_TEST_CASE(qutrit_case_sdpa, identdefs<3>)\n{\n  // This is now a test channel which is hopefully close to Eident.\n\n  ChoiMatrixType E;\n  E  << \n    0.9,0,  0,  0,  0.5,0,  0,  0,0.2,\n    0,  0,  0,  0,  0,  0,  0,  0,  0,\n    0,  0,0.1,  0,  0,  0,  0,  0,  0,\n    0,  0,  0,  0,  0,  0,  0,  0,  0,\n    0.5,0,  0,  0,  1,  0,  0,  0,0.8,\n    0,  0,  0,  0,  0,  0,  0,  0,  0,\n    0,  0,  0,  0,  0,  0,  0,  0,  0,\n    0,  0,  0,  0,  0,  0,  0,  0,  0,\n  0.2,  0,  0,  0,0.8,  0,  0,  0,  1 ;\n  \n  ChoiMatrixType Delta = E - Eident;\n\n  BOOST_TEST_MESSAGE(\"\\n\\nAll good, continuing.\\n\"\n                     << \"Delta is = \\n\"\n                     << Delta << \"\\n\\n\");\n\n  Tomographer::Logger::BoostTestLogger lg(Tomographer::Logger::LONGDEBUG);\n\n  DiamondNormSDPASolver<double,Tomographer::Logger::BoostTestLogger,true> d(3, 3, lg);\n  double value = d.calculate(Delta);\n\n  // calculated by solving the SDP with MATLAB/CVX\n  BOOST_CHECK_CLOSE( value, 0.42666667, 1e-4/*percent*/ );\n}\nBOOST_FIXTURE_TEST_CASE(qutrit_case_scs, identdefs<3>)\n{\n  // This is now a test channel which is hopefully close to Eident.\n\n  ChoiMatrixType E;\n  E  << \n    0.9,0,  0,  0,  0.5,0,  0,  0,0.2,\n    0,  0,  0,  0,  0,  0,  0,  0,  0,\n    0,  0,0.1,  0,  0,  0,  0,  0,  0,\n    0,  0,  0,  0,  0,  0,  0,  0,  0,\n    0.5,0,  0,  0,  1,  0,  0,  0,0.8,\n    0,  0,  0,  0,  0,  0,  0,  0,  0,\n    0,  0,  0,  0,  0,  0,  0,  0,  0,\n    0,  0,  0,  0,  0,  0,  0,  0,  0,\n  0.2,  0,  0,  0,0.8,  0,  0,  0,  1 ;\n  \n  ChoiMatrixType Delta = E - Eident;\n\n  BOOST_TEST_MESSAGE(\"\\n\\nAll good, continuing.\\n\"\n                     << \"Delta is = \\n\"\n                     << Delta << \"\\n\\n\");\n\n  Tomographer::Logger::BoostTestLogger lg(Tomographer::Logger::LONGDEBUG);\n\n  DiamondNormSCSSolver<double,Tomographer::Logger::BoostTestLogger,true> d(3, 3, lg);\n  double value = d.calculate(Delta);\n\n  // calculated by solving the SDP with MATLAB/CVX\n  BOOST_CHECK_CLOSE( value, 0.42666667, 1e-1/*percent*/ );\n}\n\nBOOST_AUTO_TEST_SUITE_END(); // examples\n\nBOOST_FIXTURE_TEST_SUITE(diamond_norm_from_bistate, identdefs<2>)\n\nBOOST_AUTO_TEST_CASE(dsolver_sdpa)\n{\n  Eigen::MatrixXcd true_E(4,4);\n  true_E <<\n    0.95,  0.,    0.,    0.95,\n    0.,    0.05,  0.,    0.,\n    0.,    0.,    0.,    0.,\n    0.95,  0.,    0.,    1. ;\n\n  DiamondNormSDPASolver<double, Tomographer::Logger::VacuumLogger> dnslv(2, 2, Tomographer::Logger::vacuum_logger);\n\n  double val = dnslv.calculate(true_E - Eident);\n\n  BOOST_TEST_MESSAGE(\"diamond-norm(true_E) = \" << val);\n  // value calculated using Python/QuTip\n  BOOST_CHECK_CLOSE(val, 0.05, 1e-1/*percent*/) ;\n}\nBOOST_AUTO_TEST_CASE(dsolver_scs)\n{\n  Eigen::MatrixXcd true_E(4,4);\n  true_E <<\n    0.95,  0.,    0.,    0.95,\n    0.,    0.05,  0.,    0.,\n    0.,    0.,    0.,    0.,\n    0.95,  0.,    0.,    1. ;\n\n  DiamondNormSCSSolver<double, Tomographer::Logger::VacuumLogger> dnslv(2, 2, Tomographer::Logger::vacuum_logger);\n\n  double val = dnslv.calculate(true_E - Eident);\n\n  BOOST_TEST_MESSAGE(\"diamond-norm(true_E) = \" << val);\n  // value calculated using Python/QuTip\n  BOOST_CHECK_CLOSE(val, 0.05, 1e-1/*percent*/) ;\n}\n\nBOOST_AUTO_TEST_CASE(example)\n{\n  Eigen::MatrixXcd rho(4,4);\n  rho <<\n    5.69952010e-01,   5.22989693e-03,   5.22989693e-03,   4.65354072e-01,\n    5.22989693e-03,   3.00479897e-02,   4.79896928e-05,   4.77010307e-03,\n    5.22989693e-03,   4.79896928e-05,   4.79896928e-05,   4.27010307e-03,\n    4.65354072e-01,   4.77010307e-03,   4.27010307e-03,   3.99952010e-01;\n\n  BOOST_TEST_MESSAGE(\"rho = \\n\" << rho );\n\n  Eigen::MatrixXcd T = Tomographer::MathTools::safeOperatorSqrt<Eigen::MatrixXcd>(rho);\n  BOOST_TEST_MESSAGE(\"T = \\n\" << T);\n\n  Tomographer::DenseDM::DMTypes<4> dmt(4);\n\n  {\n    DiamondNormToRefValueCalculator<Tomographer::DenseDM::DMTypes<4>,\n                                    DiamondNormSDPASolver<double, Tomographer::Logger::VacuumLogger> > valcalc(dmt, Eident, 2);\n\n    double val = valcalc.getValue(T);\n    // value calculated using Python/QuTip\n    BOOST_CHECK_CLOSE(val, 0.05, 1e-1/*percent*/) ;\n  }\n  {\n    DiamondNormToRefValueCalculator<Tomographer::DenseDM::DMTypes<4>,\n                                    DiamondNormSCSSolver<double, Tomographer::Logger::VacuumLogger> > valcalc(dmt, Eident, 2);\n\n    double val = valcalc.getValue(T);\n    // value calculated using Python/QuTip\n    BOOST_CHECK_CLOSE(val, 0.05, 1e-1/*percent*/) ;\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n\n\n// =============================================================================\nBOOST_AUTO_TEST_SUITE_END() ;\n\n", "meta": {"hexsha": "ef00cc8289fb6fa8bc0eb837d576e01264860e8a", "size": 8017, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "cxx/test_diamond_norm.cxx", "max_stars_repo_name": "Tomographer/QPtomographer", "max_stars_repo_head_hexsha": "337f0ba1069c8cef30e80a6719e8df9ce1c68997", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-22T01:59:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-05T07:33:46.000Z", "max_issues_repo_path": "cxx/test_diamond_norm.cxx", "max_issues_repo_name": "Tomographer/QPtomographer", "max_issues_repo_head_hexsha": "337f0ba1069c8cef30e80a6719e8df9ce1c68997", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cxx/test_diamond_norm.cxx", "max_forks_repo_name": "Tomographer/QPtomographer", "max_forks_repo_head_hexsha": "337f0ba1069c8cef30e80a6719e8df9ce1c68997", "max_forks_repo_licenses": ["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.9422382671, "max_line_length": 127, "alphanum_fraction": 0.6133216914, "num_tokens": 2885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021788, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5116464480694383}}
{"text": "/*!\n* \\file GrapheneExp.cpp\n*\n* \\brief Tight-binding model for graphene photo-excitation\n* Solves the ODE system for a wave with a few-cycle envelope (exp)\n*\n* The excitation\n* is a slowly varying envelope with exponential shape\n* See e.g. http://link.aps.org/doi/10.1103/PhysRevB.91.045439\n*\n* \\author Author: D. Gagnon <denisg6@hotmail.com>\n*/\n\n// Include some headers\n#include <iostream>\n#include <fstream>\n#include <armadillo>\n#include <cmath>\n#include <complex>\n\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n#include <boost/numeric/odeint.hpp>\n\n#include \"GrapheneExp.hpp\"\n#include \"Utils.hpp\"\n\n/// Main function\nint main(int argc, char *argv[])\n{\n    // Parse parameter file\n    boost::property_tree::ptree pt;\n    boost::property_tree::ini_parser::read_ini(\"GrapheneExp.ini\", pt);\n\n    // Problem parameters\n    double E0 = std::stof(pt.get<std::string>(\"Parameters.E0\"));            // Peak electric field in V/m\n    double tau = std::stof(pt.get<std::string>(\"Parameters.tau\"));        // Pulse duration in fs\n\n    // Parameter sweep\n    double xmin = std::stof(pt.get<std::string>(\"Sweep.xmin\")); // Minimum frequency in sweep\n    double xmax = std::stof(pt.get<std::string>(\"Sweep.xmax\")); // Minimum frequency in sweep\n    int x_elem = std::stoi(pt.get<std::string>(\"Sweep.xnum\"));\n\n    // Parameter sweep\n    double ymin = std::stof(pt.get<std::string>(\"Sweep.ymin\")); // Minimum frequency in sweep\n    double ymax = std::stof(pt.get<std::string>(\"Sweep.ymax\")); // Minimum frequency in sweep\n    int y_elem = std::stoi(pt.get<std::string>(\"Sweep.ynum\"));\n\n\n    // Meshgrid (vectors of parameters)\n    auto xvec = arma::linspace(xmin, xmax, x_elem);\n    auto yvec = arma::linspace(ymin, ymax, y_elem);\n\n    // Variables to store probability values\n    auto prob_mat = arma::mat(y_elem,x_elem);\n\n    // Initial value of time, integration time and interval\n\n    double tinit = -4.0*tau;\n    double inttime = 8.0*tau;\n    double dt = inttime/100;\n\n    // Variables for loops\n    unsigned id, id2;\n\n    // Loop for each K value and compute probability\n    for (id=0; id < y_elem; id++)\n    {\n        for (id2=0; id2 < x_elem; id2++)\n        {\n\n            // Initialize tight-binding model\n            tight_binding_exp model(xvec[id2],yvec[id],tau,E0);\n\n            // Prepare initial states (negative and positive eigenstates)\n            state_type psi = EigenState(model, xvec[id2], yvec[id], -1.0);\n            state_type eigen_p = EigenState(model, xvec[id2], yvec[id], 1.0);\n\n            // Integrate\n            size_t steps = boost::numeric::odeint::integrate( model,\n                           psi, tinit, inttime, dt );\n\n            // Calculate the projection\n            std::complex<double> projection = Projection(eigen_p,psi);\n\n            prob_mat(id,id2) = std::abs(projection)*std::abs(projection);\n\n\n        }\n\n    }\n\n    // Save ODE integration data\n    prob_mat.save(\"probability.dat\", arma::raw_ascii);\n\n    // Save parameters vector\n    xvec.save(\"xvec.dat\", arma::raw_ascii);\n    yvec.save(\"yvec.dat\", arma::raw_ascii);\n\n    // For post-processing: time evolution of vector potential after ODE integration\n    int numtimes = ceil(inttime/dt);\n    auto times = arma::linspace(tinit,tinit+inttime,numtimes);\n\n    // Initialize output file\n    std::ofstream outfile(\"potential.dat\");\n    outfile << std::scientific << std::setprecision(10);\n\n    // Create tight binding object\n    tight_binding_exp model(0.0,0.0,tau,E0);\n\n    for (size_t i=0; i < numtimes; i++)\n    {\n        outfile << times(i) << \" \"\n                << model.Gx(times(i)) << \" \"\n                << model.Gy(times(i)) << std::endl;\n    }\n\n\n    return 0;\n\n}\n", "meta": {"hexsha": "a7b8f432c4479b1fe0c052c2bef8e7d516a44bb9", "size": 3698, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulations/GrapheneExp.cpp", "max_stars_repo_name": "DenGagn/phdm", "max_stars_repo_head_hexsha": "1412cd8730806f08d80e5faa00d854b95559207d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-24T02:07:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-24T02:07:41.000Z", "max_issues_repo_path": "simulations/GrapheneExp.cpp", "max_issues_repo_name": "DenGagn/phdm", "max_issues_repo_head_hexsha": "1412cd8730806f08d80e5faa00d854b95559207d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulations/GrapheneExp.cpp", "max_forks_repo_name": "DenGagn/phdm", "max_forks_repo_head_hexsha": "1412cd8730806f08d80e5faa00d854b95559207d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3114754098, "max_line_length": 105, "alphanum_fraction": 0.6325040562, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021787, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5116464480694382}}
{"text": "#include \"catch.hpp\"\n#include \"timer.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n#include <iostream>\n#include <vector>\n\nusing namespace Eigen;\nusing Td = Triplet<double>;\n\nTEST_CASE(\"tridiagonal eye\", \"[inv]\") {\n  int sb = 4;\n  int nb = 4;\n  int ndim = nb * sb;\n  SparseMatrix<double> matA(ndim, ndim);\n  std::vector<Td> tripletList;\n  tripletList.reserve(ndim * 3 - sb * 2);\n  for (int i = 0; i < ndim; ++i) {\n    tripletList.push_back(Td(i, i, 1.0));\n  }\n  for (int i = sb; i < ndim; ++i) {\n    tripletList.push_back(Td(i - sb, i, 1.0));\n    tripletList.push_back(Td(i, i - sb, 1.0));\n  }\n  matA.setFromTriplets(tripletList.begin(), tripletList.end());\n  SparseMatrix<double> matI(ndim, ndim);\n  matI.setIdentity();\n\n  Timer::begin(\"eigen sparse solver\");\n  SimplicialLDLT<SparseMatrix<double>> solver;\n  solver.compute(matA);\n  MatrixXd A_inv = solver.solve(matI);\n  Timer::end(\"eigen sparse solver\");\n\n  IOFormat fmt(1, 0, \", \", \"\\n\", \"[\", \"]\");\n  std::cout << A_inv.format(fmt) << std::endl;\n\n  std::cout << Timer::summery() << std::endl;\n}", "meta": {"hexsha": "faca7773763171b6f6794a8d48219821ecf5d77b", "size": 1086, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test_inv.cc", "max_stars_repo_name": "pan3rock/InvBlockTridiagonalMatrice", "max_stars_repo_head_hexsha": "695d22cf990b9e66141c7d6b1acde5688f333724", "max_stars_repo_licenses": ["MIT"], "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_inv.cc", "max_issues_repo_name": "pan3rock/InvBlockTridiagonalMatrice", "max_issues_repo_head_hexsha": "695d22cf990b9e66141c7d6b1acde5688f333724", "max_issues_repo_licenses": ["MIT"], "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_inv.cc", "max_forks_repo_name": "pan3rock/InvBlockTridiagonalMatrice", "max_forks_repo_head_hexsha": "695d22cf990b9e66141c7d6b1acde5688f333724", "max_forks_repo_licenses": ["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.487804878, "max_line_length": 63, "alphanum_fraction": 0.638121547, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5116464476015735}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,\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#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <iostream>\n#include <fstream>\n\nint\nmain()\n{\n  using namespace boost;\n  typedef adjacency_list < vecS, vecS, undirectedS,\n    no_property, property < edge_weight_t, int > > Graph;\n  typedef graph_traits < Graph >::edge_descriptor Edge;\n  typedef std::pair<int, int> E;\n\n  const int num_nodes = 5;\n  E edge_array[] = { E(0, 2), E(1, 3), E(1, 4), E(2, 1), E(2, 3),\n    E(3, 4), E(4, 0), E(4, 1)\n  };\n  int weights[] = { 1, 1, 2, 7, 3, 1, 1, 1 };\n  std::size_t num_edges = sizeof(edge_array) / sizeof(E);\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n  Graph g(num_nodes);\n  property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g);\n  for (std::size_t j = 0; j < num_edges; ++j) {\n    Edge e; bool inserted;\n    boost::tie(e, inserted) = add_edge(edge_array[j].first, edge_array[j].second, g);\n    weightmap[e] = weights[j];\n  }\n#else\n  Graph g(edge_array, edge_array + num_edges, weights, num_nodes);\n#endif\n  property_map < Graph, edge_weight_t >::type weight = get(edge_weight, g);\n  std::vector < Edge > spanning_tree;\n\n  kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n\n  std::cout << \"Print the edges in the MST:\" << std::endl;\n  for (std::vector < Edge >::iterator ei = spanning_tree.begin();\n       ei != spanning_tree.end(); ++ei) {\n    std::cout << source(*ei, g) << \" <--> \" << target(*ei, g)\n      << \" with weight of \" << weight[*ei]\n      << std::endl;\n  }\n\n  std::ofstream fout(\"figs/kruskal-eg.dot\");\n  fout << \"graph A {\\n\"\n    << \" rankdir=LR\\n\"\n    << \" size=\\\"3,3\\\"\\n\"\n    << \" ratio=\\\"filled\\\"\\n\"\n    << \" edge[style=\\\"bold\\\"]\\n\" << \" node[shape=\\\"circle\\\"]\\n\";\n  graph_traits<Graph>::edge_iterator eiter, eiter_end;\n  for (boost::tie(eiter, eiter_end) = edges(g); eiter != eiter_end; ++eiter) {\n    fout << source(*eiter, g) << \" -- \" << target(*eiter, g);\n    if (std::find(spanning_tree.begin(), spanning_tree.end(), *eiter)\n        != spanning_tree.end())\n      fout << \"[color=\\\"black\\\", label=\\\"\" << get(edge_weight, g, *eiter)\n           << \"\\\"];\\n\";\n    else\n      fout << \"[color=\\\"gray\\\", label=\\\"\" << get(edge_weight, g, *eiter)\n           << \"\\\"];\\n\";\n  }\n  fout << \"}\\n\";\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "044f55fed9da9983449ea40724c968d9e1d23010", "size": 2641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/kruskal-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/graph/example/kruskal-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/graph/example/kruskal-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": 36.6805555556, "max_line_length": 85, "alphanum_fraction": 0.5778114351, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5116464415990625}}
{"text": "#include <boost/random/piecewise_constant_distribution.hpp>\n", "meta": {"hexsha": "b751e323a0089a7916b64b2482cba4539b86c112", "size": 60, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_piecewise_constant_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_piecewise_constant_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_piecewise_constant_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 30.0, "max_line_length": 59, "alphanum_fraction": 0.8666666667, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5116464415990624}}
{"text": "// Boost.Geometry\n// Robustness Test\n\n// Copyright (c) 2019-2021 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2021.\n// Modifications copyright (c) 2021, 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#define BOOST_GEOMETRY_NO_ROBUSTNESS\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <string>\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n\n// Basic case. Union should deliver 22.0\nstatic std::string case_a[2] =\n    {\n    \"MULTIPOLYGON(((0 0,0 4,2 4,2 3,4 3,4 0,0 0)))\",\n    \"MULTIPOLYGON(((2 7,4 7,4 3,2 3,2 7)))\"\n    };\n\n// Case with an interior ring. Union should deliver 73.0\nstatic std::string case_b[2] =\n    {\n    \"MULTIPOLYGON(((0 0,0 4,2 4,2 3,4 3,4 0,0 0)))\",\n    \"MULTIPOLYGON(((-1 -1,-1 8,8 8,8 -1,-1 -1),(2 7,2 3,4 3,4 7,2 7)))\"\n    };\n\nstatic std::string case_c[2] =\n    {\n    \"MULTIPOLYGON(((0 0,0 4,2 4,2 3,4 3,4 0,0 0)))\",\n    \"MULTIPOLYGON(((1 1,0 1,0 3,1 3,1 1)))\"\n    };\n\nstruct test_settings\n{\n    bool verbose{false};\n    bool do_output{false};\n\n    // Settings currently not modifiable, and still giving quite some errors\n    double start_bound{1.0e-2};\n    double step_factor{50.0};  // on each side -> 100 steps per factor\n    int max_factor{10000};\n};\n\ntemplate <bg::overlay_type OverlayType, typename Geometry>\nbool test_overlay(std::string const& caseid,\n        Geometry const& g1, Geometry const& g2,\n        double expected_area,\n        test_settings const& settings)\n{\n\n    typedef typename boost::range_value<Geometry>::type geometry_out;\n    typedef bg::detail::overlay::overlay\n        <\n            Geometry, Geometry,\n            bg::detail::overlay::do_reverse<bg::point_order<Geometry>::value>::value,\n            OverlayType == bg::overlay_difference\n            ? ! bg::detail::overlay::do_reverse<bg::point_order<Geometry>::value>::value\n            : bg::detail::overlay::do_reverse<bg::point_order<Geometry>::value>::value,\n            bg::detail::overlay::do_reverse<bg::point_order<Geometry>::value>::value,\n            geometry_out,\n            OverlayType\n        > overlay;\n\n    typedef typename bg::strategies::relate::services::default_strategy\n        <\n            Geometry, Geometry\n        >::type strategy_type;\n\n    strategy_type strategy;\n\n    typedef typename bg::rescale_overlay_policy_type\n    <\n        Geometry,\n        Geometry\n    >::type rescale_policy_type;\n\n    rescale_policy_type robust_policy\n        = bg::get_rescale_policy<rescale_policy_type>(g1, g2);\n\n    Geometry result;\n    bg::detail::overlay::overlay_null_visitor visitor;\n    overlay::apply(g1, g2, robust_policy, std::back_inserter(result),\n                   strategy, visitor);\n\n    const double detected_area = bg::area(result);\n    if (std::fabs(detected_area - expected_area) > 0.01)\n    {\n        if (settings.do_output)\n        {\n            std::cout << \"ERROR: \" << caseid << std::setprecision(18)\n                      << \" detected=\" << detected_area\n                      << \" expected=\" << expected_area << std::endl\n                      << \"    \" <<  bg::wkt(g1) << std::endl\n                      << \"    \" << bg::wkt(g2) << std::endl;\n        }\n        return false;\n    }\n    return true;\n}\n\ntemplate <typename Ring>\nvoid update(Ring& ring, double x, double y, std::size_t index)\n{\n    if (index >= ring.size())\n    {\n        return;\n    }\n    bg::set<0>(ring[index], bg::get<0>(ring[index]) + x);\n    bg::set<1>(ring[index], bg::get<1>(ring[index]) + y);\n    if (index == 0)\n    {\n        ring.back() = ring.front();\n    }\n}\n\ntemplate <bg::overlay_type OverlayType, typename MultiPolygon>\nstd::size_t test_case(std::size_t& error_count,\n        std::size_t case_index, std::size_t i, std::size_t j,\n        std::size_t min_vertex_index, std::size_t max_vertex_index,\n        double offset_x, double offset_y, double expectation,\n        MultiPolygon const& poly1, MultiPolygon const& poly2,\n        test_settings const settings)\n{\n    std::size_t n = 0;\n    for (std::size_t k = min_vertex_index; k <= max_vertex_index; k++, ++n)\n    {\n        MultiPolygon poly2_adapted = poly2;\n\n        switch (case_index)\n        {\n            case 2 :\n                update(bg::interior_rings(poly2_adapted.front()).front(), offset_x, offset_y, k);\n                break;\n            default :\n                update(bg::exterior_ring(poly2_adapted.front()), offset_x, offset_y, k);\n                break;\n        }\n\n        std::ostringstream out;\n        out << \"case_\" << i << \"_\" << j << \"_\" << k;\n        if (! test_overlay<OverlayType>(out.str(), poly1, poly2_adapted, expectation, settings))\n        {\n            if (error_count == 0 && ! settings.do_output)\n            {\n                // First failure is always reported\n                test_settings adapted = settings;\n                adapted.do_output = true;\n                test_overlay<OverlayType>(out.str(), poly1, poly2_adapted, expectation, adapted);\n            }\n            error_count++;\n        }\n    }\n    return n;\n}\n\ntemplate <typename T, bool Clockwise, bg::overlay_type OverlayType>\nstd::size_t test_all(std::size_t case_index, std::size_t min_vertex_index,\n                     std::size_t max_vertex_index,\n                     double expectation, test_settings const& settings)\n{\n    typedef bg::model::point<T, 2, bg::cs::cartesian> point_type;\n    typedef bg::model::polygon<point_type, Clockwise> polygon;\n    typedef bg::model::multi_polygon<polygon> multi_polygon;\n\n    const std::string& first = case_a[0];\n\n    const std::string& second\n            = case_index == 1 ? case_a[1]\n            : case_index == 2 ? case_b[1]\n            : case_index == 3 ? case_c[1]\n            : \"\";\n\n    multi_polygon poly1;\n    bg::read_wkt(first, poly1);\n\n    multi_polygon poly2;\n    bg::read_wkt(second, poly2);\n\n    std::size_t error_count = 0;\n    std::size_t n = 0;\n    for (int factor = 1; factor < settings.max_factor; factor *= 2)\n    {\n        std::size_t i = 0;\n        double const bound = settings.start_bound / factor;\n        double const step = bound / settings.step_factor;\n        if (settings.verbose)\n        {\n            std::cout << \"--> use \" << bound << \" \" << step << std::endl;\n        }\n        for (double offset_x = -bound; offset_x <= bound; offset_x += step, ++i)\n        {\n            std::size_t j = 0;\n            for (double offset_y = -bound; offset_y <= bound; offset_y += step, ++j, ++n)\n            {\n                n += test_case<OverlayType>(error_count,\n                                            case_index, i, j,\n                                            min_vertex_index, max_vertex_index,\n                                            offset_x, offset_y, expectation,\n                                            poly1, poly2, settings);\n            }\n        }\n    }\n\n    std::cout << case_index\n            << \" #cases: \" << n << \" #errors: \" << error_count << std::endl;\n    BOOST_CHECK_EQUAL(error_count, 0u);\n\n    return error_count;\n}\n\nint test_main(int argc, char** argv)\n{\n    BoostGeometryWriteTestConfiguration();\n    using coor_t = default_test_type;\n\n    test_settings settings;\n    settings.do_output = argc > 2 && atol(argv[2]) == 1;\n\n    // Test three polygons, for the last test two types of intersections\n    test_all<coor_t, true, bg::overlay_union>(1, 0, 3, 22.0, settings);\n    test_all<coor_t, true, bg::overlay_union>(2, 0, 3, 73.0, settings);\n    test_all<coor_t, true, bg::overlay_intersection>(3, 1, 2, 2.0, settings);\n    test_all<coor_t, true, bg::overlay_union>(3, 1, 2, 14.0, settings);\n\n    return 0;\n}\n", "meta": {"hexsha": "dc7527ae959442e56c7d3f0793b459826cda8d1e", "size": 7894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/robustness/overlay/areal_areal/general_intersection_precision.cpp", "max_stars_repo_name": "jhypolite/geometry", "max_stars_repo_head_hexsha": "f79b3f0c457bc4ae4bb1c1cb5a117efbe97be3c4", "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/robustness/overlay/areal_areal/general_intersection_precision.cpp", "max_issues_repo_name": "jhypolite/geometry", "max_issues_repo_head_hexsha": "f79b3f0c457bc4ae4bb1c1cb5a117efbe97be3c4", "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/robustness/overlay/areal_areal/general_intersection_precision.cpp", "max_forks_repo_name": "jhypolite/geometry", "max_forks_repo_head_hexsha": "f79b3f0c457bc4ae4bb1c1cb5a117efbe97be3c4", "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.755186722, "max_line_length": 97, "alphanum_fraction": 0.589181657, "num_tokens": 2107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173791645582, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5116464385978068}}
{"text": "#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n#include \"sensor_msgs/CompressedImage.h\"\n#include \"sensor_msgs/Image.h\"\n#include \"sensor_msgs/CameraInfo.h\"\n\n#include <image_transport/image_transport.h>\n#include <cv_bridge/cv_bridge.h>\n#include <opencv2/opencv.hpp>\n#include <stdio.h>\n#include <iostream>\n//#include <Eigen3/Eigen/Dense>\n\n//This node subscribes to /grasseater/camera_node/image/compressed and undistort the image. Then it publish the image to imgpreproc/undist\n\nusing namespace cv;\nusing namespace std;\n\nconst double fx=259.5050;\nconst double fy=263.0909;\nconst double cx=333.0998;\nconst double cy=254.7687;\nconst double s=0.3627;\nconst double dist[]={-0.2912,0.0630,-0.0051,-0.00062276,0.0017};\n\n//Calibration Parameters\n    Mat cameraMatrix = (Mat_<double>(3,3) << fx,s,cx,0.0,fy,cy,0.0,0.0,1.0);\n    Mat distParamCV = (Mat_<double>(1,5) << dist[0],dist[1],dist[2],dist[3],dist[4]);\n//Create a Mat object to store the undistorted image\n    Mat undistImg;\n\nimage_transport::Publisher image_pub;\n\t\nvoid chatterCallback(sensor_msgs::CompressedImage image_msg)\n{\n    ros::Time time = ros::Time::now();\n\n    cv_bridge::CvImagePtr cv_ptr;\n    cv_ptr = cv_bridge::toCvCopy(image_msg,sensor_msgs::image_encodings::BGR8);\n\n    //Undistort the image\n    undistort(cv_ptr->image,undistImg,cameraMatrix,distParamCV);\n    //Create a cvImage to transform from OpenCVImage to ImageMsg\n    cv_bridge::CvImage cvi_undist;\n    cvi_undist.header.stamp = time;\n    cvi_undist.header.frame_id = \"undist\";\n    cvi_undist.encoding = \"bgr8\";\n    cvi_undist.image = undistImg;\n\n    //Publish the image\n    image_pub.publish(cvi_undist.toImageMsg());\n\n    ROS_INFO_ONCE(\"First image published\");\n}\n\n//Transform from world coodinates to image coordinates\n/*void w2imCoord(cv::Point2f worldPoint, cv::Point2f &imagePoint, Eigen::MatrixXd homog)\n{\n    Eigen::Vector3d wPointEig(worldPoint.x,worldPoint.y,1.0);    \n    Eigen::Vector3d imPointEig;\n    imPointEig=homog*wPointEig;\n    imPointEig=imPointEig/imPointEig(2);\n    imagePoint=Point2f(imPointEig(0),imPointEig(1));\n}\n\n//Transform from image coordinates to world coordinates\nvoid im2wCoord(cv::Point2f imagePoint, cv::Point2f &worldPoint, Eigen::MatrixXd homogInv)\n{\n    Eigen::Vector3d imPointEig(imagePoint.x,imagePoint.y,1.0);    \n    Eigen::Vector3d wPointEig;\n    wPointEig=homogInv*imPointEig;\n    wPointEig=wPointEig/wPointEig(2);\n    worldPoint=Point2f(wPointEig(0),wPointEig(1));\n}*/\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"imgpreproc\");\n  ros::NodeHandle n;\n  image_transport::ImageTransport it(n);\n  \n  image_pub = it.advertise(\"/imgpreproc/undist\",1);\n   \n  ros::Subscriber sub = n.subscribe(\"/grasseaterpi3/camera_node/image/compressed\",1, chatterCallback);\n\n  \n  ros::spin();\n\n  return 0;\n}\n", "meta": {"hexsha": "13717bfa93eb0c8c5cd10ce41ec714f1e5362c03", "size": 2771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/spring2016_nctu/grasseater/campicpp/src/imgundist.cpp", "max_stars_repo_name": "stevenyslins/Software", "max_stars_repo_head_hexsha": "99012d31f9e886386dad598cb4cacd2f9b4ebade", "max_stars_repo_licenses": ["CC-BY-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-10-09T20:31:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-03T05:00:38.000Z", "max_issues_repo_path": "catkin_ws/src/spring2016_nctu/grasseater/campicpp/src/imgundist.cpp", "max_issues_repo_name": "stevenyslins/Software", "max_issues_repo_head_hexsha": "99012d31f9e886386dad598cb4cacd2f9b4ebade", "max_issues_repo_licenses": ["CC-BY-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": "catkin_ws/src/spring2016_nctu/grasseater/campicpp/src/imgundist.cpp", "max_forks_repo_name": "stevenyslins/Software", "max_forks_repo_head_hexsha": "99012d31f9e886386dad598cb4cacd2f9b4ebade", "max_forks_repo_licenses": ["CC-BY-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-03-17T17:00:51.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-05T05:51:33.000Z", "avg_line_length": 30.4505494505, "max_line_length": 138, "alphanum_fraction": 0.7315048719, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5116464365322813}}
{"text": "/*\n * Copyright (c) 2017, 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 *    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\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 *    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 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 HOLDER 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(s) of this library if you have any questions.\n * Authors: David Fridovich-Keil   ( dfk@eecs.berkeley.edu )\n */\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Defines the GaussianActionValueFunctor class, which derives from the\n// ActionValueFunctor base class.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef RL_VALUE_GAUSSIAN_ACTION_VALUE_FUNCTOR_H\n#define RL_VALUE_GAUSSIAN_ACTION_VALUE_FUNCTOR_H\n\n#include \"../value/continuous_action_value_functor.hpp\"\n#include \"../value/gaussian_params.hpp\"\n#include \"util/types.hpp\"\n\n#include <Eigen/Cholesky>\n#include <glog/logging.h>\n#include <limits>\n#include <iostream>\n#include <random>\n#include <vector>\n#include <math.h>\n\nnamespace rl {\n\n  template<typename StateType, typename ActionType>\n  class GaussianActionValue :\n    public ContinuousActionValue<StateType, ActionType> {\n  public:\n    ~GaussianActionValue() {}\n\n    // Factory method.\n    static typename ContinuousActionValue<StateType, ActionType>::Ptr\n    Create(const GaussianParams& params);\n\n    // Must implement a deep copy.\n    typename ContinuousActionValue<StateType, ActionType>::Ptr Copy() const;\n\n    // Pure virtual method to output the value at a state/action pair.\n    double Get(const StateType& state, const ActionType& action) const;\n\n    // Pure virtual method to do a gradient update to underlying weights.\n    // Returns average loss.\n    double Update(const std::vector<StateType>& states,\n                  const std::vector<ActionType>& actions,\n                  const std::vector<double>& targets,\n                  double step_size);\n\n    // Choose an optimal action in the given state. Returns whether or not\n    // optimization was successful.\n    bool OptimalAction(const StateType& state, ActionType& action) const;\n\n  private:\n    explicit GaussianActionValue(const GaussianParams& params);\n\n    // Covariance kernel function.\n    double Kernel(const VectorXd& x, const VectorXd& y) const;\n\n    // Compute the cross covariance vector of a feature vector with\n    // the training data.\n    void CrossCovariance(const VectorXd& features, VectorXd& cross) const;\n\n    // Helper function to evaluate the GP.\n    void Evaluate(const StateType& state, const ActionType& action,\n                  double& mean, double& variance) const;\n\n    // Training covariance matrix, with vectors of state/action features\n    // training means, and length scales.\n    MatrixXd covariance_;\n    std::vector<VectorXd> points_;\n    VectorXd means_;\n    VectorXd lengths_;\n    VectorXd squared_lengths_;\n\n    // Fast Cholesky solver.\n    Eigen::LLT<MatrixXd> cholesky_;\n\n    // Output of covariance.inv() * means_. Stored for speed.\n    VectorXd regressed_means_;\n\n    // Noise variance.\n    double noise_variance_;\n\n    // Regularization parameter to trade off mean with variance in the\n    // choice of optimal action.\n    double regularizer_;\n\n    // Max number of gradient steps to take for choosing the optimal action,\n    // with given step size starting from one of 'num_inits_' random initial\n    // points. 'epsilon_' is convergence criterion for gradient size.\n    const size_t num_inits_;\n    const size_t max_steps_;\n    const double step_size_;\n    const double epsilon_;\n  }; //\\class GaussianActionValue\n\n// ------------------------------ IMPLEMENTATION ---------------------------- //\n\n  // Factory method.\n  template<typename StateType, typename ActionType>\n  typename ContinuousActionValue<StateType, ActionType>::Ptr\n  GaussianActionValue<StateType, ActionType>::\n  Create(const GaussianParams& params) {\n    typename ContinuousActionValue<StateType, ActionType>::Ptr\n      ptr(new GaussianActionValue<StateType, ActionType>(params));\n    return ptr;\n  }\n\n  // Must implement a deep copy.\n  template<typename StateType, typename ActionType>\n  typename ContinuousActionValue<StateType, ActionType>::Ptr\n  GaussianActionValue<StateType, ActionType>::Copy() const {\n    typename ContinuousActionValue<StateType, ActionType>::Ptr\n      ptr(new GaussianActionValue<StateType, ActionType>(*this));\n    return ptr;\n  }\n\n  // Constructor.\n  template<typename StateType, typename ActionType>\n  GaussianActionValue<StateType, ActionType>::\n  GaussianActionValue(const GaussianParams& params)\n    : regularizer_(params.regularizer_),\n      noise_variance_(params.noise_variance_),\n      max_steps_(params.max_steps_),\n      num_inits_(params.num_inits_),\n      step_size_(params.step_size_),\n      epsilon_(params.epsilon_),\n      covariance_(MatrixXd::Zero(params.num_points_, params.num_points_)),\n      means_(VectorXd::Zero(params.num_points_)),\n      regressed_means_(VectorXd::Zero(params.num_points_)),\n      lengths_(params.lengths_),\n      squared_lengths_(params.lengths_.cwiseProduct(params.lengths_)),\n      ContinuousActionValue<StateType, ActionType>() {\n    // Pick random points in the space for training.\n    for (size_t ii = 0; ii < params.num_points_; ii++) {\n      const StateType state;\n      const ActionType action;\n\n      // Unpack into a feature vector.\n      VectorXd state_features(StateType::FeatureDimension());\n      state.Features(state_features);\n\n      VectorXd action_features(ActionType::FeatureDimension());\n      action.Features(action_features);\n\n      VectorXd features(state_features.size() + action_features.size());\n      features.head(state_features.size()) = state_features;\n      features.tail(action_features.size()) = action_features;\n\n      // Add to list of training points.\n      points_.push_back(features);\n    }\n\n    // Compute training covariance.\n    for (size_t ii = 0; ii < points_.size(); ii++) {\n      for (size_t jj = 0; jj < ii; jj++) {\n        covariance_(ii, jj) = Kernel(points_[ii], points_[jj]);\n        covariance_(jj, ii) = covariance_(ii, jj);\n      }\n\n      covariance_(ii, ii) = 1.0 + noise_variance_;\n    }\n\n    // Randomize training targets.\n    std::random_device rd;\n    std::default_random_engine rng(rd());\n    std::normal_distribution<double> gaussian(0.0, 0.1);\n\n    for (size_t ii = 0; ii < means_.size(); ii++)\n      means_(ii) = gaussian(rng);\n\n    // Compute Cholesky decomposition of 'covariance_' for quick solving.\n    cholesky_ = covariance_.llt();\n\n    // Set 'regressed_means_' for speed.\n    regressed_means_ = cholesky_.solve(means_);\n  }\n\n  // Helper function to evaluate the GP.\n  template<typename StateType, typename ActionType>\n  void GaussianActionValue<StateType, ActionType>::\n  Evaluate(const StateType& state, const ActionType& action,\n           double& mean, double& variance) const {\n    // Compute cross covariance vector.\n    VectorXd features(StateType::FeatureDimension() +\n                      ActionType::FeatureDimension());\n    this->Unpack(state, action, features);\n\n    VectorXd cross(points_.size());\n    CrossCovariance(features, cross);\n\n    // Regress the cross covariance on the training covariance.\n    const VectorXd regressed_cross = cholesky_.solve(cross);\n\n    // Compute the total inner product between the cross covariance\n    // of this point and the training set.\n    mean = cross.dot(regressed_means_);\n    variance = 1.0 - cross.dot(regressed_cross);\n  }\n\n  // Compute the expected value of the GP at this point.\n  template<typename StateType, typename ActionType>\n  double GaussianActionValue<StateType, ActionType>::\n  Get(const StateType& state, const ActionType& action) const {\n    // Compute cross covariance vector.\n    VectorXd features(StateType::FeatureDimension() +\n                      ActionType::FeatureDimension());\n    this->Unpack(state, action, features);\n\n    VectorXd cross(points_.size());\n    CrossCovariance(features, cross);\n\n    // Compute the total inner product between the cross covariance\n    // of this point and the training set.\n    return cross.dot(regressed_means_);\n  }\n\n  // Update all parameters. Return average loss.\n  template<typename StateType, typename ActionType>\n  double GaussianActionValue<StateType, ActionType>::\n  Update(const std::vector<StateType>& states,\n         const std::vector<ActionType>& actions,\n         const std::vector<double>& targets, double step_size) {\n    CHECK_EQ(states.size(), actions.size());\n    CHECK_EQ(states.size(), targets.size());\n\n    // Iterate over each state/action pair and average the gradients.\n    double loss = 0.0;\n    VectorXd gradient = VectorXd::Zero(means_.size());\n    VectorXd features(StateType::FeatureDimension() +\n                      ActionType::FeatureDimension());\n    VectorXd cross(points_.size());\n    for (size_t ii = 0; ii < states.size(); ii++) {\n      // Compute cross covariance.\n      this->Unpack(states[ii], actions[ii], features);\n      CrossCovariance(features, cross);\n\n      // Compute the gradient.\n      const VectorXd regressed = cholesky_.solve(cross);\n      const double error = regressed.dot(means_) - targets[ii];\n\n      // Catch nan. Set to zero.\n      if (isnan(error)) {\n        LOG(WARNING) << \"GaussianActionValue: Error was nan. Skipping.\";\n        continue;\n      }\n\n      //      std::printf(\"Error was: %f = %f - %f\\n\",\n      //                  error, error + targets[ii], targets[ii]);\n\n      loss += error * error;\n      gradient += error * regressed;\n    }\n\n    // Do a gradient update.\n    means_ -= step_size * gradient / static_cast<double>(states.size());\n\n    // Update 'regressed_means_' for speed later.\n    regressed_means_ = cholesky_.solve(means_);\n\n    // Return loss. Divide by two for consistency.\n    return 0.5 * loss / static_cast<double>(states.size());\n  }\n\n  // Compute the optimal action, where 'optimal' is the solution to the\n  // following program:\n  //                arg max mean(s, a) + reg * var(s, a)\n  //                     a\n  // Note that the sign of 'regularizer' will determine whether the control\n  // is biased toward \"safe\" areas or optimistic exploration. In practice, this\n  // problem is usually non-convex, and we solve it by taking several gradient\n  // steps from a few random initializations and returning the best final value.\n  template<typename StateType, typename ActionType>\n  bool GaussianActionValue<StateType, ActionType>::\n  OptimalAction(const StateType& state, ActionType& action) const {\n    // Get a list of possible actions.\n    std::vector<ActionType> candidates;\n    ActionType::DiscreteValues(candidates);\n\n    // Find the best option in this list.\n    double max_value = kInvalidValue;\n    for (const auto& candidate : candidates) {\n      double mean, variance;\n      Evaluate(state, candidate, mean, variance);\n\n      const double value = mean + regularizer_ * variance;\n\n      if (value > max_value) {\n        max_value = value;\n        action = candidate;\n      }\n    }\n\n    return (max_value != kInvalidValue);\n\n#if 0\n    VectorXd features(StateType::FeatureDimension() +\n                      ActionType::FeatureDimension());\n\n    // Try a few random initial actions and keep the best one\n    // after running a few iterations of gradient ascent.\n    double best_value = kInvalidReward;\n    bool has_converged = false;\n\n    VectorXd cross(points_.size());\n    VectorXd regressed_cross(points_.size());\n    MatrixXd Jt(ActionType::FeatureDimension(), points_.size());\n\n    for (size_t ii = 0; ii < num_inits_; ii++) {\n      // Start from a random initial action.\n      ActionType current_action;\n      this->Unpack(state, current_action, features);\n\n      // Run a few steps of gradient ascent to adjust this action.\n      has_converged = false;\n      for (size_t jj = 0; jj < max_steps_; jj++) {\n        // Compute the cross covariance of this state-action pair with the data.\n        CrossCovariance(features, cross);\n\n        // Compute the Jacobian transpose of cross covariance with respect\n        // to feature vector.\n        for (size_t jj = 0; jj < points_.size(); jj++) {\n          const VectorXd action_diff =\n            points_[jj].tail(ActionType::FeatureDimension()) -\n            features.tail(ActionType::FeatureDimension());\n\n          Jt.col(jj) = cross(jj) * action_diff.cwiseQuotient(\n            squared_lengths_.tail(ActionType::FeatureDimension()));\n        }\n\n        // Compute the intermediate derivative with respect to cross covariance.\n        regressed_cross = cholesky_.solve(cross);\n        const VectorXd cross_gradient =\n          regressed_means_ + regularizer_ * regressed_cross;\n\n        // Compute the gradient with respect to the action feature vector.\n        const VectorXd gradient = Jt * cross_gradient;\n\n        // Gradient update.\n        features.tail(ActionType::FeatureDimension()) += step_size_ * gradient;\n\n        // Check convergence.\n        if (gradient.norm() < epsilon_) {\n          has_converged = true;\n          break;\n        }\n      }\n\n      // Check if this value is best.\n      const double value =\n        (regressed_means_ + regularizer_ * regressed_cross).dot(cross);\n\n      if (value > best_value) {\n        best_value = value;\n        action.FromFeatures(features.tail(ActionType::FeatureDimension()));\n      }\n    }\n\n    return has_converged;\n#endif\n  }\n\n  // Covariance kernel function.\n  template<typename StateType, typename ActionType>\n  double GaussianActionValue<StateType, ActionType>::\n  Kernel(const VectorXd& x, const VectorXd& y) const {\n    CHECK_EQ(x.size(), lengths_.size());\n    CHECK_EQ(y.size(), lengths_.size());\n\n    const VectorXd normalized_delta = (x - y).cwiseQuotient(lengths_);\n    return std::exp(-0.5 * normalized_delta.squaredNorm());\n  }\n\n  // Compute the cross covariance vector of a feature vector with\n  // the training data.\n  template<typename StateType, typename ActionType>\n  void GaussianActionValue<StateType, ActionType>::\n  CrossCovariance(const VectorXd& features, VectorXd& cross) const {\n    CHECK_EQ(cross.size(), points_.size());\n    CHECK_EQ(features.size(),\n             StateType::FeatureDimension() + ActionType::FeatureDimension());\n\n    // Compute cross covariance of features with training points.\n    for (size_t ii = 0; ii < points_.size(); ii++)\n      cross(ii) = Kernel(features, points_[ii]);\n  }\n\n}  //\\namespace rl\n\n#endif\n", "meta": {"hexsha": "6ac2e2cd169c74fcd527388511b16648938bbeca", "size": 15785, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/value/gaussian_action_value_functor.hpp", "max_stars_repo_name": "dfridovi/rl", "max_stars_repo_head_hexsha": "41684df8d55d1e64947f9b9273e19d19b5de8110", "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/value/gaussian_action_value_functor.hpp", "max_issues_repo_name": "dfridovi/rl", "max_issues_repo_head_hexsha": "41684df8d55d1e64947f9b9273e19d19b5de8110", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T23:34:46.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-24T15:20:54.000Z", "max_forks_repo_path": "include/value/gaussian_action_value_functor.hpp", "max_forks_repo_name": "dfridovi/rl", "max_forks_repo_head_hexsha": "41684df8d55d1e64947f9b9273e19d19b5de8110", "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.0539906103, "max_line_length": 80, "alphanum_fraction": 0.6810262908, "num_tokens": 3416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5116464355965512}}
{"text": "/*\nCopyright 2014 Rogier van Dalen.\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/** \\file\nTests for math::product.\n*/\n\n#ifndef MATH_TEST_MATH_PRODUCT_TESTS_HPP_INCLUDED\n#define MATH_TEST_MATH_PRODUCT_TESTS_HPP_INCLUDED\n\n#include \"math/product.hpp\"\n\n#include <string>\n#include <vector>\n\n#include <boost/mpl/assert.hpp>\n\n#include \"math/arithmetic_magma.hpp\"\n#include \"math/cost.hpp\"\n#include \"math/sequence.hpp\"\n#include \"math/check/check_magma.hpp\"\n\ntemplate <class Inverses> void test_product_homogeneous() {\n    // Test the empty product.\n    // This is (trivially!) almost a semiring.\n    // However, it cannot have an annihilator.\n    {\n        typedef math::product <math::over<>, Inverses> product;\n        std::vector <product> examples;\n        examples.push_back (product());\n\n        static_assert (!math::has <\n                math::callable::annihilator <product> (math::callable::times)\n            >::value, \"An empty product cannot have an annihilator.\");\n\n        math::check_magma <product> (math::times, math::plus, examples);\n    }\n\n    // Test homogeneous of (float, sequence).\n    {\n        typedef math::product <\n            math::over <float, math::sequence <char>>, Inverses> product;\n\n        static_assert (math::has <\n                math::callable::annihilator <product> (math::callable::times)\n            >::value, \"An empty product cannot have an annihilator.\");\n\n        static_assert (utility::is_assignable <\n            typename product::components_type &,\n            typename product::components_type &&>::value, \"\");\n        static_assert (utility::is_assignable <\n            product &, product &&>::value, \"\");\n\n        std::vector <product> examples;\n        examples.push_back (product (\n            0, math::sequence <char> (std::string (\"\"))));\n        // This is the same for with_inverse <times>.\n        examples.push_back (product (\n            0, math::sequence <char> (std::string (\"q\"))));\n        examples.push_back (product (\n            4, math::sequence <char> (std::string (\"\"))));\n        examples.push_back (product (\n            2, math::sequence <char> (std::string (\"a\"))));\n        examples.push_back (product (\n            5, math::sequence <char> (std::string (\"ab\"))));\n        examples.push_back (product (\n            7, math::sequence <char> (std::string (\"cba\"))));\n        examples.push_back (product (\n            3, math::sequence <char> (std::string (\"aba\"))));\n        examples.push_back (product (\n            0, math::sequence_annihilator <char> ()));\n        examples.push_back (product (\n            3, math::sequence_annihilator <char> ()));\n\n        math::check_semiring <product, math::left> (\n            math::times, math::plus, examples);\n    }\n}\n\ntemplate <class Inverses, class Sequence>\n    inline math::product <math::over <float, Sequence>, Inverses>\n        make_product (float f, Sequence s)\n{ return math::product <math::over <float, Sequence>, Inverses> (f, s); }\n\n// Test heterogeneous types.\ntemplate <class Inverses> void test_product_heterogeneous() {\n    typedef math::product <math::over <float, math::sequence <char>>, Inverses>\n        product;\n    {\n        auto examples = range::make_tuple (\n            make_product <Inverses> (2.f, math::empty_sequence <char>()),\n            make_product <Inverses> (4.f, math::empty_sequence <char>()),\n            make_product <Inverses> (4.f,\n                math::sequence <char> (std::string())),\n            make_product <Inverses> (5.f, math::single_sequence <char> ('A')),\n            make_product <Inverses> (5.f, math::single_sequence <char> ('z')),\n            make_product <Inverses> (5.f,\n                math::sequence <char> (std::string(\"z\"))),\n            make_product <Inverses> (1.f,\n                math::sequence <char> (std::string(\"Az\"))),\n            make_product <Inverses> (1.f,\n                math::sequence <char> (std::string(\"zAz\")))\n            );\n\n        math::check_semiring <product, math::left> (\n            math::times, math::plus, examples);\n    }\n}\n\n#endif // MATH_TEST_MATH_PRODUCT_TESTS_HPP_INCLUDED\n", "meta": {"hexsha": "4d8fd6f5edfa6276b0e7ffe2b8e7e43053b25623", "size": 4568, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/math/product-tests.hpp", "max_stars_repo_name": "rogiervd/math", "max_stars_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "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/math/product-tests.hpp", "max_issues_repo_name": "rogiervd/math", "max_issues_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "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/math/product-tests.hpp", "max_forks_repo_name": "rogiervd/math", "max_forks_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "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.8387096774, "max_line_length": 79, "alphanum_fraction": 0.6201838879, "num_tokens": 1087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5116464355965512}}
{"text": "#include <string>\n#include <map>\n#include <fstream>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/crc.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::multiprecision;\nusing u256 = uint256_t;\n\nnamespace {\n\tenum class HashAlgorithm\n\t{\n\t\tDJB2,\n\t\tCRC32\n\t};\n\tstring hashAlgName(HashAlgorithm alg)\n\t{\n\t\tswitch (alg)\n\t\t{\n\t\t\tcase HashAlgorithm::DJB2:\n\t\t\t\treturn \"DJB2\";\n\t\t\tcase HashAlgorithm::CRC32:\n\t\t\t\treturn \"CRC32\";\n\t\t}\n\t}\n}\n\nstatic map<u256, pair<string, HashAlgorithm>> s_hashMap = {};\n\nstruct NCHFCollision\n{\n\tstring printStringAsHex(string const& input)\n\t{\n\t\tostringstream os;\n\t\tfor (auto const& c: input)\n\t\t\tos << hex << setfill('0') << setw(2) << right << int(c);\n\t\treturn os.str();\n\t}\n\n\tvoid printCollision(HashAlgorithm alg, u256 hash, string input)\n\t{\n\t\t// Append to a local file in the same directory\n\t\t// as the fuzzer binary\n\t\tofstream f(\"NCHF-Collision.txt\", ios::app);\n\t\tf << endl;\n\t\tf << \"Algorithm: \" << hashAlgName(alg) << endl;\n\t\tf << \"Hash: \" << hash << endl;\n\t\tf << \"Input 1: \" << printStringAsHex(s_hashMap[hash].first) << endl;\n\t\tf << \"Input 2: \" << printStringAsHex(input) << endl;\n\t}\n\n\tbool operator()(HashAlgorithm alg, u256 hash, string input)\n\t{\n\t\tbool Collision = s_hashMap.count(hash) &&\n\t\t\tinput != s_hashMap[hash].first &&\n\t\t\talg == s_hashMap[hash].second;\n\n\t\tif (Collision)\n\t\t{\n\t\t\tprintCollision(alg, hash, input);\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ts_hashMap.emplace(hash, make_pair(input, alg));\n\t\t\treturn false;\n\t\t}\n\t}\n};\n\nstruct NCHF\n{\n\tbool operator()(const uint8_t *data, size_t size, HashAlgorithm alg)\n\t{\n\t\treturn NCHFCollision{}(\n\t\t\talg,\n\t\t\tcomputeHash(data, size),\n\t\t\tstring(data, data + size)\n\t\t);\n\t}\n\n\tvirtual u256 computeHash(const uint8_t *data, size_t size) = 0;\n};\n\nstruct DJB2: NCHF\n{\n\tu256 computeHash(const uint8_t *data, size_t size) override\n\t{\n\t\tstring input(data, data + size);\n\t\tu256 hash = 5381;\n\t\tfor (auto c: input)\n\t\t\thash = (hash << 5) + hash + c;\n\t\treturn hash;\n\t}\n};\n\nstruct CRC32: NCHF\n{\n\tu256 computeHash(const uint8_t *data, size_t size) override\n\t{\n\t\tstring input(data, data + size);\n\t\tcrc_32_type hash;\n\t\thash.process_bytes(input.c_str(), input.size());\n\t\treturn hash.checksum();\n\t}\n};\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)\n{\n//\tassert(!DJB2{}(data, size, HashAlgorithm::DJB2));\n\tassert(!CRC32{}(data, size, HashAlgorithm::CRC32));\n\treturn 0;\n}\n", "meta": {"hexsha": "f56ee2035912cacc4cbcf34d0d89723585986173", "size": 2381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nchf-fuzzer.cpp", "max_stars_repo_name": "bshastry/nchf-fuzz", "max_stars_repo_head_hexsha": "0bc512bdfe71a43041183a2a97cb7ec47cc9c109", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nchf-fuzzer.cpp", "max_issues_repo_name": "bshastry/nchf-fuzz", "max_issues_repo_head_hexsha": "0bc512bdfe71a43041183a2a97cb7ec47cc9c109", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nchf-fuzzer.cpp", "max_forks_repo_name": "bshastry/nchf-fuzz", "max_forks_repo_head_hexsha": "0bc512bdfe71a43041183a2a97cb7ec47cc9c109", "max_forks_repo_licenses": ["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.525862069, "max_line_length": 71, "alphanum_fraction": 0.6631667367, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5116464355965511}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::survival::model::example::model::exponential.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 <stdexcept>\n#include <string> //needed?\n#include <vector>\n#include <limits>\n#include <ostream>\n#include <fstream>\n#include <algorithm>\n#include <iterator>\n// #include <boost/archive/binary_oarchive.hpp>\n// #include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/vector.hpp>\n\n#include <boost/arithmetic/equal.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/iterator/range_cycle.hpp>\n#include <boost/range.hpp>\n#include <boost/assert.hpp>\n#include <boost/foreach.hpp> \n#include <boost/assign/std/vector.hpp>\n#include <boost/iterator/range_cycle.hpp>\n\n#include <boost/standard_distribution/distributions/normal.hpp>\n\n#include <boost/statistics/survival/data/include.hpp>\n#include <boost/statistics/survival/model/models/exponential/include.hpp>\n#include <libs/statistics/survival/model/example/exponential.h>\n\n// Must come after the model to be used\n#include <boost/statistics/model/include.hpp>\n\n#include <libs/statistics/survival/model/example/exponential.h>\n\nvoid example_exponential(std::ostream& out){\n\n    out << \"-> example_model_exponential : \";\n    \n    // Steps shown in this example:\n    //\n    // Loads the first batch of a set of records\n    // Creates events at given time\n    // Evaluates the likelihoods and posteriors\n    \n    using namespace boost;\n    using namespace statistics;\n    namespace surv = survival;\n\n    // [ Types ]\n    // Value\n    typedef double                                  val_;\n    typedef std::vector<val_>                       vals_;\n    typedef surv::constant<val_>                    const_;\n\n    // I/O\n    typedef boost::archive::text_oarchive oa_;\n    typedef boost::archive::text_iarchive ia_;\n    \n   // Records\n    typedef surv::data::record<val_>                record_;\n    typedef std::vector<record_>                    records_;\n    typedef range_iterator<records_>::type          it_record_;\n    \n    // Events\n    typedef surv::data::event<val_>                 event_;\n    typedef std::vector<event_>                     events_;\n    typedef range_iterator<events_>::type           it_event_;\n\n    // Covariates\n    typedef val_                                    x_;\n    typedef vals_                                   r_x_;\n    typedef range_cycle<>                           range_cycle_;\n    typedef range_cycle_::apply<r_x_>::type         x_cycle_;\n\n    // Model\n    typedef surv::model::exponential::model<val_>   model_;\n    typedef val_                                    par_;\n    typedef vals_                                   pars_;\n\n    // [ Constants ]\n    const val_ entry_bound = const_::inf_;\n    const val_ par = 2.0;\n    const char* batches_path \n        = \"/Users/erwann/projets/2009/Xcode/survival/build/Release/batches\";\n\n    // [ Variables ]\n    long n_record;\n\n    // [ Upload first batch of records ]\n    records_ records;\n    {\n        std::ifstream ifs(batches_path);\n        if(ifs.good()){\n            ia_ ia(ifs);\n            ia >> records;\n        }else{\n            std::string str = \"error opening : \";\n            str.append( batches_path );\n            throw std::runtime_error(str);\n        }\n        ifs.close();\n    }\n    n_record = boost::size( records );\n    \n    // [ Events ]\n    events_ events; \n    events.reserve( size(records) );\n    surv::data::events(\n        begin(records),\n        end(records),\n        entry_bound,\n        std::back_inserter(events)\n    );\n    \n    // [ Covariates ] \n    r_x_ r_x;\n    {\n        using namespace boost::assign;\n        r_x += -0.5, 0.5;\n    }\n    x_cycle_ x_cycle = range_cycle_::make(r_x,0,n_record);\n    out << \"size(x_cycle) = \" << size(x_cycle) << std::endl;\n    BOOST_ASSERT( size(x_cycle)>=size(events) );\n    // Resize x_cycle to a size that matches that of events\n    x_cycle.advance_end( - (size(x_cycle) - size(events)) );\n    BOOST_ASSERT( size(x_cycle) == size(events) );\n\n    // Model\n    model_ model;\n\n    // Pars\n    pars_ pars;\n    {\n        using namespace assign;\n        pars += -2.0, -1.0, 0.0, 1.0, 2.0; \n    }\n\n    // [ Likelihood ]\n\n    typedef math::normal_distribution<val_> mprior_;\n    mprior_ mprior;\n\n    out << '(';\n    out << model::log_likelihood<val_>(\n        model::make_model_data(\n            model,\n            r_x[0],\n            events[0]\n        ),\n        par\n    );\n    out << ',';\n    out << model::log_likelihood<val_>(\n        model::make_model_data(\n            model,\n            r_x[1],\n            events[1]\n        ),\n        par\n    ) << ')';\n\n\n    // [ Likelihoods ]\n    vals_ lls;\n    model::log_likelihoods<val_>(\n        model::make_model_dataset(model,r_x,events),\n        boost::begin(pars),\n        boost::end(pars),\n        std::back_inserter(lls)\n    );\n\n    // [ Prior ]\n    vals_ lprs;\n    math::transform<math::fun_wrap::log_unnormalized_pdf_>(\n        mprior,\n        boost::begin(pars),\n        boost::end(pars),\n        std::back_inserter(lprs)\n    );\n\n    // [ Posteriors ]\n\n    vals_ lpos;\n    model::log_posteriors2<val_>(\n        model::make_prior_model_dataset(mprior,model,r_x,events),\n        boost::begin(pars),\n        boost::end(pars),\n        std::back_inserter(lpos)\n    );\n\n    // Consistency check\n    typedef range_iterator<vals_>::type it_val_;\n    {\n\n        it_val_ i_lpr = boost::begin(lprs);\n        it_val_ i_lpo = boost::begin(lpos);\n        out << std::endl;\n        out << \"log(prior,likelihood,posterior)\" << std::endl;\n        for(\n            it_val_ i_ll = boost::begin(lls); \n            i_ll< boost::end(lls); \n            i_ll++,i_lpr++,i_lpo++\n        ){\n            out << '(';\n            val_ lpr = *i_lpr;  out << lpr << ',';\n            val_ ll = *i_ll;    out << ll << ',';\n            val_ lpo = *i_lpo;  out << lpo << ')' << std::endl;\n            val_ lpo2 = lpr + ll;\n            BOOST_ASSERT(\n                arithmetic_tools::equal(\n                    lpo,\n                    lpo2\n                )\n            );\n        }\n    }\n    \n    // Consistency check2\n\n    {\n        vals_ lpr2s ( size(pars) );\n        model::log_posteriors<val_>(\n            model::make_prior_model_dataset(mprior,model,r_x,events),\n            boost::begin(pars),\n            boost::end(pars),\n            boost::begin(lls), //subtracted\n            boost::begin(lpr2s)\n        );\n\n        it_val_ i_lpr = boost::begin(lprs);\n        out << std::endl;\n        out << \"log(prior,prior2)\" << std::endl;\n        for(\n            it_val_ i_lpr2 = boost::begin(lpr2s); \n            i_lpr2< boost::end(lpr2s); \n            i_lpr2++,i_lpr++\n        ){\n            out << '(';\n            val_ lpr  = *i_lpr;     out << lpr << ',';\n            val_ lpr2 = *i_lpr2;    out << lpr2 << ')' << std::endl;\n            BOOST_ASSERT(\n                arithmetic_tools::equal(\n                    lpr,\n                    lpr2\n                )\n            );\n        }\n    }\n\n    out << \"<-\" << std::endl;\n}\n", "meta": {"hexsha": "5e223b905511bf37ac7f19bef8444239600e0728", "size": 7513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "survival_model copy/libs/statistics/survival/model/example/exponential.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": "survival_model copy/libs/statistics/survival/model/example/exponential.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": "survival_model copy/libs/statistics/survival/model/example/exponential.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": 29.0077220077, "max_line_length": 79, "alphanum_fraction": 0.5229602023, "num_tokens": 1801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5116464355965511}}
{"text": "#include <algorithm>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <iostream>\n#include <list>\n#include <map>\n#include <set>\n#include <tbb/blocked_range.h>\n#include <tbb/parallel_for.h>\n#include <vector>\n\n\nstruct Layer\n{\n    int range = 0;\n    std::vector<int> positions;\n\n    Layer(int r)\n        : range(r)\n    {\n        for (int i = 0; i < r; ++i) {\n            positions.push_back(i);\n        }\n        for (int i = range - 2; i > 0; --i) {\n            positions.push_back(i);\n        }\n    }\n\n    int scanner_pos(int tick) const\n    {\n        return positions[tick % positions.size()];\n    }\n};\n\nusing Map = std::map<int, Layer>;\n\nint main()\n{\n    Map map;\n\n    std::string line;\n    int max_k = 0;\n    while (std::getline(std::cin, line)) {\n        std::vector<std::string> words;\n        boost::algorithm::split(\n                words, line, boost::is_any_of(\": \"), boost::algorithm::token_compress_on);\n\n        int k = std::stoi(&words[0][0]);\n        int r = std::stoi(&words[1][0]);\n        map.insert({k, Layer{r}});\n        max_k = std::max(max_k, k);\n    }\n\n    int delay = 0;\n    for (;;++delay) {\n        bool hit = false;\n        for (int pos = 0; pos <= max_k; ++pos) {\n            int tick = delay + pos;\n            auto it = map.find(pos);\n            if (it != map.end()) {\n                if (it->second.scanner_pos(tick) == 0) {\n                    hit = true;\n                    break;\n                }\n            }\n        }\n        if (!hit) {\n            break;\n        }\n    }\n\n    std::cout << \"delay: \" << delay << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "1c53fe8153cf71c3ca22e1b3b8dfb521b16465ae", "size": 1631, "ext": "cc", "lang": "C++", "max_stars_repo_path": "puzzle_13_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_13_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_13_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": 21.4605263158, "max_line_length": 90, "alphanum_fraction": 0.4849785408, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5116464300619051}}
{"text": "#ifndef PYTHONIC_INCLUDE_NUMPY_LOG_HPP\n#define PYTHONIC_INCLUDE_NUMPY_LOG_HPP\n\n#include \"pythonic/include/utils/functor.hpp\"\n#include \"pythonic/include/types/ndarray.hpp\"\n#include \"pythonic/include/utils/numpy_traits.hpp\"\n\n#include <boost/simd/function/log.hpp>\n\nPYTHONIC_NS_BEGIN\n\nnamespace numpy\n{\n  namespace wrapper\n  {\n    template <class T>\n    std::complex<T> log(std::complex<T> const &val)\n    {\n      return std::log(val);\n    }\n\n    template <class T>\n    typename std::enable_if<std::is_integral<T>::value, double>::type\n    log(T const &val)\n    {\n      return std::log(val);\n    }\n\n    template <class T>\n    auto log(T const &val) ->\n        typename std::enable_if<!std::is_integral<T>::value,\n                                decltype(boost::simd::log(val))>::type\n    {\n      return boost::simd::log(val);\n    }\n  }\n#define NUMPY_NARY_FUNC_NAME log\n#define NUMPY_NARY_FUNC_SYM wrapper::log\n#include \"pythonic/include/types/numpy_nary_expr.hpp\"\n}\nPYTHONIC_NS_END\n\n#endif\n", "meta": {"hexsha": "a12a52d6d4d7a23a3927ff5fa8a687b53f219182", "size": 987, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pythran/pythonic/include/numpy/log.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "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": "pythran/pythonic/include/numpy/log.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": "pythran/pythonic/include/numpy/log.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "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.4318181818, "max_line_length": 70, "alphanum_fraction": 0.6737588652, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5116426510471646}}
{"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/rokko.hpp>\n#include <rokko/utility/frank_matrix.hpp>\n#include <boost/lexical_cast.hpp>\n#define BOOST_TEST_MODULE test_product\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_product) {\n  MPI_Init(&boost::unit_test::framework::master_test_suite().argc,\n           &boost::unit_test::framework::master_test_suite().argv);\n  MPI_Comm comm = MPI_COMM_WORLD;\n  int rank;\n  MPI_Comm_rank(comm, &rank);\n\n  int dim = 100;\n  if (boost::unit_test::framework::master_test_suite().argc > 1) {\n    dim = boost::lexical_cast<int>(boost::unit_test::framework::master_test_suite().argv[1]);\n  }\n\n  if (rank == 0) std::cout << \"dimension = \" << dim << std::endl;\n  rokko::parallel_dense_solver solver(rokko::parallel_dense_solver::default_solver());\n  rokko::grid g(comm);\n  rokko::distributed_matrix<double, rokko::matrix_col_major> matA(dim, dim, g, solver);\n  rokko::distributed_matrix<double, rokko::matrix_col_major> matB(dim, dim, g, solver);\n  rokko::distributed_matrix<double, rokko::matrix_col_major> matC(dim, dim, g, solver);\n  rokko::frank_matrix::generate(matA);\n  rokko::frank_matrix::generate(matB);\n  rokko::product(1.0, matA, false, matB, false, 0, matC);\n  matC.print();\n  // calculate trace\n  double sum_local = 0;\n  for (int i = 0; i < dim; ++i) {\n    if (matC.is_gindex(i, i)) sum_local += matC.get_global(i, i);\n  }\n  double sum_global = 0;\n  MPI_Allreduce(&sum_local, &sum_global, 1, MPI_DOUBLE, MPI_SUM, comm);\n  if (rank == 0) std::cout << \"trace of distributed matrix = \" << sum_global << std::endl;\n\n  rokko::localized_matrix<double, rokko::matrix_col_major> lmatA(dim, dim);\n  rokko::frank_matrix::generate(lmatA);\n  rokko::localized_matrix<double, rokko::matrix_col_major> lmatC = lmatA * lmatA;\n  if (rank == 0) std::cout << lmatC << std::endl;\n  // calculate trace\n  double sum = 0;\n  for (int i = 0; i < dim; ++i) {\n    sum += lmatC(i, i);\n  }\n  if (rank == 0) std::cout << \"trace of localized matrix = \" << sum << std::endl;\n\n  if (rank == 0) BOOST_CHECK_CLOSE(sum_global, sum, 10e-12);\n\n  MPI_Finalize();\n}\n", "meta": {"hexsha": "a10e323c80e9e6f640575f26d08982637be6f6cd", "size": 2611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/diagonalize/product_mpi.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/diagonalize/product_mpi.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/diagonalize/product_mpi.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": 38.3970588235, "max_line_length": 93, "alphanum_fraction": 0.6591344313, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5116025925355618}}
{"text": "#include <iostream>\n#include <limits>\n\n#include <boost/rational.hpp>\n#include <boost/safe_numerics/safe_integer.hpp>\n\nint main(int, const char *[]){\n    // simple demo of rational library\n    const boost::rational<int> r {1, 2};\n    std::cout << \"r = \" << r << std::endl;\n    const boost::rational<int> q {-2, 4};\n    std::cout << \"q = \" << q << std::endl;\n    // display the product\n    std::cout << \"r * q = \" << r * q << std::endl;\n\n    // problem: rational doesn't handle integer overflow well\n    const boost::rational<int> c {1, INT_MAX};\n    std::cout << \"c = \" << c << std::endl;\n    const boost::rational<int> d {1, 2};\n    std::cout << \"d = \" << d << std::endl;\n    // display the product - wrong answer\n    std::cout << \"c * d = \" << c * d << std::endl;\n\n    // solution: use safe integer in rational definition\n    using safe_rational = boost::rational<\n        boost::safe_numerics::safe<int>\n    >;\n\n    // use rationals created with safe_t\n    const safe_rational sc {1, std::numeric_limits<int>::max()};\n\n    std::cout << \"c = \" << sc << std::endl;\n    const safe_rational sd {1, 2};\n    std::cout << \"d = \" << sd << std::endl;\n    std::cout << \"c * d = \";\n    try {\n        // multiply them. This will overflow\n        std::cout << sc * sd << std::endl;\n    }\n    catch (std::exception const& e) {\n        // catch exception due to multiplication overflow\n        std::cout << e.what() << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "a719f61050794a3e30cf5aab5d0d181c4f1f9c70", "size": 1440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/example15.cpp", "max_stars_repo_name": "giomasce-throwaway/safe_numerics", "max_stars_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "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/example15.cpp", "max_issues_repo_name": "giomasce-throwaway/safe_numerics", "max_issues_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "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/example15.cpp", "max_forks_repo_name": "giomasce-throwaway/safe_numerics", "max_forks_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "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.6382978723, "max_line_length": 64, "alphanum_fraction": 0.5590277778, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.511602584145786}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, Phi_approx) {\n  EXPECT_EQ(0.5, stan::math::Phi_approx(0.0));\n  EXPECT_NEAR(stan::math::Phi(0.9), stan::math::Phi_approx(0.9), 0.00014);\n  EXPECT_NEAR(stan::math::Phi(-5.0), stan::math::Phi_approx(-5.0), 0.00014);\n}\n\nTEST(MathFunctions, Phi_approx_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::Phi_approx(nan));\n}\n", "meta": {"hexsha": "7302fd45a209187b3129df08d73446d4bf037599", "size": 540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/Phi_approx_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/Phi_approx_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/Phi_approx_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.7647058824, "max_line_length": 76, "alphanum_fraction": 0.6907407407, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.5116025790779231}}
{"text": "// Copyright Louis Dionne 2013-2016\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#include <boost/hana/assert.hpp>\n#include <boost/hana/concept/ring.hpp>\n#include <boost/hana/mult.hpp>\n#include <boost/hana/one.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <laws/ring.hpp>\nnamespace hana = boost::hana;\n\n\nint main() {\n    hana::test::TestRing<int>{hana::make_tuple(0,1,2,3,4,5)};\n    hana::test::TestRing<long>{hana::make_tuple(0l,1l,2l,3l,4l,5l)};\n\n    // one\n    static_assert(hana::one<int>() == 1, \"\");\n\n    // mult\n    static_assert(hana::mult(6, 4) == 6 * 4, \"\");\n}\n", "meta": {"hexsha": "f5758ba0c1c7df6efe3324f1f01fdee8d9b90b93", "size": 671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/hana/test/ring.cpp", "max_stars_repo_name": "metux/boost", "max_stars_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-06-01T15:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-01T16:06:53.000Z", "max_issues_repo_path": "libs/hana/test/ring.cpp", "max_issues_repo_name": "metux/boost", "max_issues_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2016-10-16T19:42:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-14T21:29:48.000Z", "max_forks_repo_path": "libs/hana/test/ring.cpp", "max_forks_repo_name": "metux/boost", "max_forks_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T07:18:18.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-19T07:18:18.000Z", "avg_line_length": 26.84, "max_line_length": 81, "alphanum_fraction": 0.6706408346, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5116013361304826}}
{"text": "#define CATCH_CONFIG_ENABLE_BENCHMARKING\n\n#include <Eigen/Dense>\n#include <catch2/catch.hpp>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n#include \"../src/kernel.hpp\"\n\nusing Point3 = Eigen::Matrix<float, 3, 1>;\n\ntemplate <int IP, int TP>\nEigen::TensorFixedSize<float, Eigen::Sizes<IP, IP, TP>> DistSq(Point3 const p)\n{\n  using KTensor = Eigen::TensorFixedSize<float, Eigen::Sizes<IP, IP, TP>>;\n  using KArray = Eigen::TensorFixedSize<float, Eigen::Sizes<IP>>;\n  using FixIn = Eigen::type2index<IP>;\n  KArray indices;\n  std::iota(indices.data(), indices.data() + IP, -IP / 2); // Note INTEGER division\n  KTensor k;\n  if constexpr (TP > 1) {\n    constexpr Eigen::IndexList<FixIn, FixOne, FixOne> rshX;\n    constexpr Eigen::IndexList<FixOne, FixIn, FixIn> brdX;\n    constexpr Eigen::IndexList<FixOne, FixIn, FixOne> rshY;\n    constexpr Eigen::IndexList<FixIn, FixOne, FixIn> brdY;\n    constexpr Eigen::IndexList<FixOne, FixOne, FixIn> rshZ;\n    constexpr Eigen::IndexList<FixIn, FixIn, FixOne> brdZ;\n    auto const kx = ((indices.constant(p[0]) - indices) / indices.constant(IP / 2.f))\n                      .square()\n                      .reshape(rshX)\n                      .broadcast(brdX);\n    auto const ky = ((indices.constant(p[1]) - indices) / indices.constant(IP / 2.f))\n                      .square()\n                      .reshape(rshY)\n                      .broadcast(brdY);\n    auto const kz = ((indices.constant(p[2]) - indices) / indices.constant(TP / 2.f))\n                      .square()\n                      .reshape(rshZ)\n                      .broadcast(brdZ);\n    k = kx + ky + kz;\n  } else {\n    constexpr Eigen::IndexList<FixIn, FixOne, FixOne> rshX;\n    constexpr Eigen::IndexList<FixOne, FixIn, FixOne> brdX;\n    constexpr Eigen::IndexList<FixOne, FixIn, FixOne> rshY;\n    constexpr Eigen::IndexList<FixIn, FixOne, FixOne> brdY;\n    auto const kx = ((indices.constant(p[0]) - indices) / indices.constant(IP / 2.f))\n                      .square()\n                      .reshape(rshX)\n                      .broadcast(brdX);\n    auto const ky = ((indices.constant(p[1]) - indices) / indices.constant(IP / 2.f))\n                      .square()\n                      .reshape(rshY)\n                      .broadcast(brdY);\n    k = kx + ky;\n  }\n  return k;\n}\n\ntemplate <int IP, int TP>\nEigen::TensorFixedSize<float, Eigen::Sizes<IP, IP, TP>> Naive(Point3 const p)\n{\n  using KTensor = Eigen::TensorFixedSize<float, Eigen::Sizes<IP, IP, TP>>;\n  KTensor k;\n  for (Index iz = 0; iz < TP; iz++) {\n    for (Index iy = 0; iy < IP; iy++) {\n      for (Index ix = 0; ix < IP; ix++) {\n        k(ix, iy, iz) = ((p - Point3(ix, iy, iz)) / (IP / 2.f)).squaredNorm();\n      }\n    }\n  }\n  return k;\n}\n\nTEST_CASE(\"Kernels\")\n{\n  auto const z = Point3::Zero();\n  KaiserBessel<3, 3> kb(2.f);\n  FlatIron<3, 3> fi(2.f);\n\n  BENCHMARK(\"Old\")\n  {\n    DistSq<3, 3>(z);\n  };\n\n  BENCHMARK(\"Current\")\n  {\n    kb.distSq(z);\n  };\n\n  BENCHMARK(\"Naive\")\n  {\n    Naive<3, 3>(z);\n  };\n\n  BENCHMARK(\"KB\")\n  {\n    kb.k(z);\n  };\n\n  BENCHMARK(\"FI\")\n  {\n    fi.k(z);\n  };\n}", "meta": {"hexsha": "10f9511bf1d770d58aeae541e460731b8ebb63c2", "size": 3052, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/kernel.cpp", "max_stars_repo_name": "pfuchs/riesling", "max_stars_repo_head_hexsha": "2e0f12f5cd1943cb6e96eca40f4e68ef88e12130", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bench/kernel.cpp", "max_issues_repo_name": "pfuchs/riesling", "max_issues_repo_head_hexsha": "2e0f12f5cd1943cb6e96eca40f4e68ef88e12130", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench/kernel.cpp", "max_forks_repo_name": "pfuchs/riesling", "max_forks_repo_head_hexsha": "2e0f12f5cd1943cb6e96eca40f4e68ef88e12130", "max_forks_repo_licenses": ["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.6310679612, "max_line_length": 85, "alphanum_fraction": 0.5658584535, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5116013339618862}}
{"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_CSCH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_CSCH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-hyperbolic\n    This function object returns the hyperbolic cosecant: \\f$1/\\sinh(1/x)\\f$.\n\n    @par Header <boost/simd/function/csch.hpp>\n\n    @see sinh, tanh, sech, csch, sinhcosh\n\n    @par Example:\n\n      @snippet csch.cpp csch\n\n    @par Possible output:\n\n      @snippet csch.txt csch\n  **/\n  IEEEValue csch(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/csch.hpp>\n#include <boost/simd/function/simd/csch.hpp>\n\n#endif\n", "meta": {"hexsha": "146d2dd2f7eafd5e0740f105bdaa1a7f16a1b437", "size": 1017, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/csch.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/function/csch.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/function/csch.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": 23.6511627907, "max_line_length": 100, "alphanum_fraction": 0.5722713864, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5116013252874999}}
{"text": "#include <boost/mpl11/detail/left_folds/variadic.hpp>\n#include <boost/mpl11/integer.hpp>\n\n\ntemplate <typename x, typename y>\nusing plus = boost::mpl11::integer_c<\n    decltype(x::type::value + y::type::value),\n    x::type::value + y::type::value\n>;\n\ntemplate <typename ...xs>\nusing sum = boost::mpl11::detail::left_folds::variadic<\n    plus, boost::mpl11::int_<0>, xs...\n>;\n\n<%= render('_main.erb') %>", "meta": {"hexsha": "48e4fab7902d8cc979d8401f44e4909235a71af8", "size": 401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/sum/mpl11_variadic_foldl.erb.cpp", "max_stars_repo_name": "ldionne/benchcc", "max_stars_repo_head_hexsha": "87cd508b47b39c9da5fb2152ec3f07de62297771", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-12T11:54:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-12T11:54:43.000Z", "max_issues_repo_path": "benchmarks/sum/mpl11_variadic_foldl.erb.cpp", "max_issues_repo_name": "ldionne/benchcc", "max_issues_repo_head_hexsha": "87cd508b47b39c9da5fb2152ec3f07de62297771", "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": "benchmarks/sum/mpl11_variadic_foldl.erb.cpp", "max_forks_repo_name": "ldionne/benchcc", "max_forks_repo_head_hexsha": "87cd508b47b39c9da5fb2152ec3f07de62297771", "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.0625, "max_line_length": 55, "alphanum_fraction": 0.6683291771, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5116013209503064}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2007 Marco Bianchetti\n Copyright (C) 2007 Fran\u00e7ois du Vignaud\n Copyright (C) 2007 Giorgio Facchinetti\n Copyright (C) 2012 Ralph Schreyer\n Copyright (C) 2012 Mateusz Kapturski\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 \"optimizers.hpp\"\n#include \"utilities.hpp\"\n#include <boost/make_shared.hpp>\n#include <ql/math/optimization/simplex.hpp>\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/math/optimization/conjugategradient.hpp>\n#include <ql/math/optimization/steepestdescent.hpp>\n#include <ql/math/optimization/bfgs.hpp>\n#include <ql/math/optimization/constraint.hpp>\n#include <ql/math/optimization/costfunction.hpp>\n#include <ql/math/randomnumbers/mt19937uniformrng.hpp>\n#include <ql/math/optimization/differentialevolution.hpp>\n#include <ql/math/optimization/goldstein.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\nusing std::pow;\nusing std::cos;\n\nnamespace {\n\n    struct NamedOptimizationMethod;\n\n    std::vector<boost::shared_ptr<CostFunction> > costFunctions_;\n    std::vector<boost::shared_ptr<Constraint> > constraints_;\n    std::vector<Array> initialValues_;\n    std::vector<Size> maxIterations_, maxStationaryStateIterations_;\n    std::vector<Real> rootEpsilons_, functionEpsilons_, gradientNormEpsilons_;\n    std::vector<boost::shared_ptr<EndCriteria> > endCriterias_;\n    std::vector<std::vector<NamedOptimizationMethod> > optimizationMethods_;\n    std::vector<Array> xMinExpected_, yMinExpected_;\n\n    class OneDimensionalPolynomialDegreeN : public CostFunction {\n      public:\n        OneDimensionalPolynomialDegreeN(const Array& coefficients)\n        : coefficients_(coefficients),\n          polynomialDegree_(coefficients.size()-1) {}\n\n        Real value(const Array& x) const {\n            QL_REQUIRE(x.size()==1,\"independent variable must be 1 dimensional\");\n            Real y = 0;\n            for (Size i=0; i<=polynomialDegree_; ++i)\n                y += coefficients_[i]*std::pow(x[0],static_cast<int>(i));\n            return y;\n        }\n\n        Disposable<Array> values(const Array& x) const{\n            QL_REQUIRE(x.size()==1,\"independent variable must be 1 dimensional\");\n            Array y(1);\n            y[0] = value(x);\n            return y;\n        }\n\n      private:\n        const Array coefficients_;\n        const Size polynomialDegree_;\n    };\n\n\n    // The goal of this cost function is simply to call another optimization inside\n    // in order to test nested optimizations\n    class OptimizationBasedCostFunction : public CostFunction {\n      public:\n        Real value(const Array&) const { return 1.0; }\n\n        Disposable<Array> values(const Array&) const{\n            // dummy nested optimization\n            Array coefficients(3, 1.0);\n            OneDimensionalPolynomialDegreeN oneDimensionalPolynomialDegreeN(coefficients);\n            NoConstraint constraint;\n            Array initialValues(1, 100.0);\n            Problem problem(oneDimensionalPolynomialDegreeN, constraint,\n                            initialValues);\n            LevenbergMarquardt optimizationMethod;\n            //Simplex optimizationMethod(0.1);\n            //ConjugateGradient optimizationMethod;\n            //SteepestDescent optimizationMethod;\n            EndCriteria endCriteria(1000, 100, 1e-5, 1e-5, 1e-5);\n            optimizationMethod.minimize(problem, endCriteria);\n            // return dummy result\n            Array dummy(1,0);\n            return dummy;\n        }\n    };\n\n\n    enum OptimizationMethodType {simplex,\n                                 levenbergMarquardt,\n                                 levenbergMarquardt2,\n                                 conjugateGradient,\n                                 conjugateGradient_goldstein,\n                                 steepestDescent,\n                                 steepestDescent_goldstein,\n                                 bfgs,\n                                 bfgs_goldstein};\n\n    std::string optimizationMethodTypeToString(OptimizationMethodType type) {\n        switch (type) {\n          case simplex:\n            return \"Simplex\";\n          case levenbergMarquardt:\n            return \"Levenberg Marquardt\";\n          case levenbergMarquardt2:\n            return \"Levenberg Marquardt (cost function's jacbobian)\";\n          case conjugateGradient:\n            return \"Conjugate Gradient\";\n          case steepestDescent:\n            return \"Steepest Descent\";\n          case bfgs:\n            return \"BFGS\";\n          case conjugateGradient_goldstein:\n              return \"Conjugate Gradient (Goldstein line search)\";\n          case steepestDescent_goldstein:\n              return \"Steepest Descent (Goldstein line search)\";\n          case bfgs_goldstein:\n              return \"BFGS (Goldstein line search)\";\n          default:\n            QL_FAIL(\"unknown OptimizationMethod type\");\n        }\n    }\n\n    struct NamedOptimizationMethod {\n        boost::shared_ptr<OptimizationMethod> optimizationMethod;\n        std::string name;\n    };\n\n\n    boost::shared_ptr<OptimizationMethod> makeOptimizationMethod(\n                                OptimizationMethodType optimizationMethodType,\n                                Real simplexLambda,\n                                Real levenbergMarquardtEpsfcn,\n                                Real levenbergMarquardtXtol,\n                                Real levenbergMarquardtGtol) {\n        switch (optimizationMethodType) {\n          case simplex:\n            return boost::shared_ptr<OptimizationMethod>(\n                new Simplex(simplexLambda));\n          case levenbergMarquardt:\n            return boost::shared_ptr<OptimizationMethod>(\n                new LevenbergMarquardt(levenbergMarquardtEpsfcn,\n                                       levenbergMarquardtXtol,\n                                       levenbergMarquardtGtol));\n          case levenbergMarquardt2:\n            return boost::shared_ptr<OptimizationMethod>(\n                new LevenbergMarquardt(levenbergMarquardtEpsfcn,\n                                       levenbergMarquardtXtol,\n                                       levenbergMarquardtGtol,\n                                       true));\n          case conjugateGradient:\n            return boost::shared_ptr<OptimizationMethod>(new ConjugateGradient);\n          case steepestDescent:\n            return boost::shared_ptr<OptimizationMethod>(new SteepestDescent);\n          case bfgs:\n            return boost::shared_ptr<OptimizationMethod>(new BFGS);\n          case conjugateGradient_goldstein:\n              return boost::shared_ptr<OptimizationMethod>(new ConjugateGradient(boost::make_shared<GoldsteinLineSearch>()));\n          case steepestDescent_goldstein:\n              return boost::shared_ptr<OptimizationMethod>(new SteepestDescent(boost::make_shared<GoldsteinLineSearch>()));\n          case bfgs_goldstein:\n              return boost::shared_ptr<OptimizationMethod>(new BFGS(boost::make_shared<GoldsteinLineSearch>()));\n          default:\n            QL_FAIL(\"unknown OptimizationMethod type\");\n        }\n    }\n\n\n    std::vector<NamedOptimizationMethod> makeOptimizationMethods(\n                             OptimizationMethodType optimizationMethodTypes[],\n                             Size optimizationMethodNb,\n                             Real simplexLambda,\n                             Real levenbergMarquardtEpsfcn,\n                             Real levenbergMarquardtXtol,\n                             Real levenbergMarquardtGtol) {\n        std::vector<NamedOptimizationMethod> results;\n        for (Size i=0; i<optimizationMethodNb; ++i) {\n            NamedOptimizationMethod namedOptimizationMethod;\n            namedOptimizationMethod.optimizationMethod = makeOptimizationMethod(\n                optimizationMethodTypes[i],\n                simplexLambda,\n                levenbergMarquardtEpsfcn,\n                levenbergMarquardtXtol,\n                levenbergMarquardtGtol);\n            namedOptimizationMethod.name\n                = optimizationMethodTypeToString(optimizationMethodTypes[i]);\n            results.push_back(namedOptimizationMethod);\n        }\n        return results;\n    }\n\n    Real maxDifference(const Array& a, const Array& b) {\n        Array diff = a-b;\n        Real maxDiff = 0.0;\n        for (Size i=0; i<diff.size(); ++i)\n            maxDiff = std::max(maxDiff, std::fabs(diff[i]));\n        return maxDiff;\n    }\n\n    // Set up, for each cost function, all the ingredients for optimization:\n    // constraint, initial guess, end criteria, optimization methods.\n    void setup() {\n\n        // Cost function n. 1: 1D polynomial of degree 2 (parabolic function y=a*x^2+b*x+c)\n        const Real a = 1;   // required a > 0\n        const Real b = 1;\n        const Real c = 1;\n        Array coefficients(3);\n        coefficients[0]= c;\n        coefficients[1]= b;\n        coefficients[2]= a;\n        costFunctions_.push_back(boost::shared_ptr<CostFunction>(\n            new OneDimensionalPolynomialDegreeN(coefficients)));\n        // Set constraint for optimizers: unconstrained problem\n        constraints_.push_back(boost::shared_ptr<Constraint>(new NoConstraint()));\n        // Set initial guess for optimizer\n        Array initialValue(1);\n        initialValue[0] = -100;\n        initialValues_.push_back(initialValue);\n        // Set end criteria for optimizer\n        maxIterations_.push_back(10000);                // maxIterations\n        maxStationaryStateIterations_.push_back(100);   // MaxStationaryStateIterations\n        rootEpsilons_.push_back(1e-8);                  // rootEpsilon\n        functionEpsilons_.push_back(1e-8);              // functionEpsilon\n        gradientNormEpsilons_.push_back(1e-8);          // gradientNormEpsilon\n        endCriterias_.push_back(boost::shared_ptr<EndCriteria>(\n            new EndCriteria(maxIterations_.back(), maxStationaryStateIterations_.back(),\n                            rootEpsilons_.back(), functionEpsilons_.back(),\n                            gradientNormEpsilons_.back())));\n        // Set optimization methods for optimizer\n        OptimizationMethodType optimizationMethodTypes[] = {\n            simplex, levenbergMarquardt, levenbergMarquardt2, conjugateGradient,\n            bfgs //, steepestDescent\n        };\n        Real simplexLambda = 0.1;                   // characteristic search length for simplex\n        Real levenbergMarquardtEpsfcn = 1.0e-8;     // parameters specific for Levenberg-Marquardt\n        Real levenbergMarquardtXtol   = 1.0e-8;     //\n        Real levenbergMarquardtGtol   = 1.0e-8;     //\n        optimizationMethods_.push_back(makeOptimizationMethods(\n            optimizationMethodTypes, LENGTH(optimizationMethodTypes),\n            simplexLambda, levenbergMarquardtEpsfcn, levenbergMarquardtXtol,\n            levenbergMarquardtGtol));\n        // Set expected results for optimizer\n        Array xMinExpected(1),yMinExpected(1);\n        xMinExpected[0] = -b/(2.0*a);\n        yMinExpected[0] = -(b*b-4.0*a*c)/(4.0*a);\n        xMinExpected_.push_back(xMinExpected);\n        yMinExpected_.push_back(yMinExpected);\n    }\n\n}\n\n\nvoid OptimizersTest::test() {\n    BOOST_TEST_MESSAGE(\"Testing optimizers...\");\n\n    setup();\n\n    // Loop over problems (currently there is only 1 problem)\n    for (Size i=0; i<costFunctions_.size(); ++i) {\n        Problem problem(*costFunctions_[i], *constraints_[i],\n                        initialValues_[i]);\n        Array initialValues = problem.currentValue();\n        // Loop over optimizers\n        for (Size j=0; j<(optimizationMethods_[i]).size(); ++j) {\n            Real rootEpsilon = endCriterias_[i]->rootEpsilon();\n            Size endCriteriaTests = 1;\n           // Loop over rootEpsilon\n            for (Size k=0; k<endCriteriaTests; ++k) {\n                problem.setCurrentValue(initialValues);\n                EndCriteria endCriteria(\n                            endCriterias_[i]->maxIterations(),\n                            endCriterias_[i]->maxStationaryStateIterations(),\n                            rootEpsilon,\n                            endCriterias_[i]->functionEpsilon(),\n                            endCriterias_[i]->gradientNormEpsilon());\n                rootEpsilon *= .1;\n                EndCriteria::Type endCriteriaResult =\n                    optimizationMethods_[i][j].optimizationMethod->minimize(\n                    problem, endCriteria);\n                Array xMinCalculated = problem.currentValue();\n                Array yMinCalculated = problem.values(xMinCalculated);\n\n                // Check optimization results vs known solution\n                bool completed;\n                switch (endCriteriaResult) {\n                  case EndCriteria::None:\n                  case EndCriteria::MaxIterations:\n                  case EndCriteria::Unknown:\n                    completed = false;\n                    break;\n                  default:\n                    completed = true;\n                }\n\n                Real xError = maxDifference(xMinCalculated,xMinExpected_[i]);\n                Real yError = maxDifference(yMinCalculated,yMinExpected_[i]);\n\n                bool correct = (xError <= endCriteria.rootEpsilon() ||\n                                yError <= endCriteria.functionEpsilon());\n\n                if ((!completed) || (!correct))\n                    BOOST_ERROR(\"costFunction # = \" << i <<\n                                \"\\nOptimizer: \" <<\n                                optimizationMethods_[i][j].name <<\n                                \"\\n    function evaluations: \" <<\n                                problem.functionEvaluation()  <<\n                                \"\\n    gradient evaluations: \" <<\n                                problem.gradientEvaluation() <<\n                                \"\\n    x expected:           \" <<\n                                xMinExpected_[i] <<\n                                \"\\n    x calculated:         \" <<\n                                std::setprecision(9) << xMinCalculated <<\n                                \"\\n    x difference:         \" <<\n                                xMinExpected_[i]- xMinCalculated <<\n                                \"\\n    rootEpsilon:          \" <<\n                                std::setprecision(9) <<\n                                endCriteria.rootEpsilon() <<\n                                \"\\n    y expected:           \" <<\n                                yMinExpected_[i] <<\n                                \"\\n    y calculated:         \" <<\n                                std::setprecision(9) << yMinCalculated <<\n                                \"\\n    y difference:         \" <<\n                                yMinExpected_[i]- yMinCalculated <<\n                                \"\\n    functionEpsilon:      \" <<\n                                std::setprecision(9) <<\n                                endCriteria.functionEpsilon() <<\n                                \"\\n    endCriteriaResult:    \" <<\n                                endCriteriaResult);\n            }\n        }\n    }\n}\n\n\nvoid OptimizersTest::nestedOptimizationTest() {\n    BOOST_TEST_MESSAGE(\"Testing nested optimizations...\");\n    OptimizationBasedCostFunction optimizationBasedCostFunction;\n    NoConstraint constraint;\n    Array initialValues(1, 0.0);\n    Problem problem(optimizationBasedCostFunction, constraint,\n                    initialValues);\n    LevenbergMarquardt optimizationMethod;\n    //Simplex optimizationMethod(0.1);\n    //ConjugateGradient optimizationMethod;\n    //SteepestDescent optimizationMethod;\n    EndCriteria endCriteria(1000, 100, 1e-5, 1e-5, 1e-5);\n    optimizationMethod.minimize(problem, endCriteria);\n\n}\n\nnamespace {\n\n    class FirstDeJong : public CostFunction {\n      public:\n        Disposable<Array> values(const Array& x) const {\n            Array retVal(x.size(),value(x));\n            return retVal;\n        }\n        Real value(const Array& x) const {\n            return DotProduct(x,x);\n        }\n    };\n\n    class SecondDeJong : public CostFunction {\n      public:\n        Disposable<Array> values(const Array& x) const {\n            Array retVal(x.size(),value(x));\n            return retVal;\n        }\n        Real value(const Array& x) const {\n            return  100.0*(x[0]*x[0]-x[1])*(x[0]*x[0]-x[1])\n                  + (1.0-x[0])*(1.0-x[0]);\n        }\n    };\n\n    class ModThirdDeJong : public CostFunction {\n      public:\n        Disposable<Array> values(const Array& x) const {\n            Array retVal(x.size(),value(x));\n            return retVal;\n        }\n        Real value(const Array& x) const {\n            Real fx = 0.0;\n            for (Size i=0; i<x.size(); ++i) {\n                fx += std::floor(x[i])*std::floor(x[i]);\n            }\n            return fx;\n        }\n    };\n\n    class ModFourthDeJong : public CostFunction {\n      public:\n        ModFourthDeJong()\n        : uniformRng_(MersenneTwisterUniformRng(4711)) {\n        }\n        Disposable<Array> values(const Array& x) const {\n            Array retVal(x.size(),value(x));\n            return retVal;\n        }\n        Real value(const Array& x) const {\n            Real fx = 0.0;\n            for (Size i=0; i<x.size(); ++i) {\n                fx += (i+1.0)*pow(x[i],4.0) + uniformRng_.nextReal();\n            }\n            return fx;\n        }\n        MersenneTwisterUniformRng uniformRng_;\n    };\n\n    class Griewangk : public CostFunction {\n      public:\n        Disposable<Array> values(const Array& x) const{\n            Array retVal(x.size(),value(x));\n            return retVal;\n        }\n        Real value(const Array& x) const {\n            Real fx = 0.0;\n            for (Size i=0; i<x.size(); ++i) {\n                fx += x[i]*x[i]/4000.0;\n            }\n            Real p = 1.0;\n            for (Size i=0; i<x.size(); ++i) {\n                p *= cos(x[i]/sqrt(i+1.0));\n            }\n            return fx - p + 1.0;\n        }\n    };\n}\n\nvoid OptimizersTest::testDifferentialEvolution() {\n    BOOST_TEST_MESSAGE(\"Testing differential evolution...\");\n\n    /* Note:\n    *\n    * The \"ModFourthDeJong\" doesn't have a well defined optimum because\n    * of its noisy part. It just has to be <= 15 in our example.\n    * The concrete value might differ for a different input and\n    * different random numbers.\n    *\n    * The \"Griewangk\" function is an example where the adaptive\n    * version of DifferentialEvolution turns out to be more successful.\n    */\n\n    DifferentialEvolution::Configuration conf =\n        DifferentialEvolution::Configuration()\n        .withStepsizeWeight(0.4)\n        .withBounds()\n        .withCrossoverProbability(0.35)\n        .withPopulationMembers(500)\n        .withStrategy(DifferentialEvolution::BestMemberWithJitter)\n        .withCrossoverType(DifferentialEvolution::Normal)\n        .withAdaptiveCrossover()\n        .withSeed(3242);\n    DifferentialEvolution deOptim(conf);\n\n    DifferentialEvolution::Configuration conf2 =\n        DifferentialEvolution::Configuration()\n        .withStepsizeWeight(1.8)\n        .withBounds()\n        .withCrossoverProbability(0.9)\n        .withPopulationMembers(1000)\n        .withStrategy(DifferentialEvolution::Rand1SelfadaptiveWithRotation)\n        .withCrossoverType(DifferentialEvolution::Normal)\n        .withAdaptiveCrossover()\n        .withSeed(3242);\n    DifferentialEvolution deOptim2(conf2);\n\n    std::vector<DifferentialEvolution > diffEvolOptimisers;\n    diffEvolOptimisers.push_back(deOptim);\n    diffEvolOptimisers.push_back(deOptim);\n    diffEvolOptimisers.push_back(deOptim);\n    diffEvolOptimisers.push_back(deOptim);\n    diffEvolOptimisers.push_back(deOptim2);\n\n    std::vector<boost::shared_ptr<CostFunction> > costFunctions;\n    costFunctions.push_back(boost::shared_ptr<CostFunction>(new FirstDeJong));\n    costFunctions.push_back(boost::shared_ptr<CostFunction>(new SecondDeJong));\n    costFunctions.push_back(boost::shared_ptr<CostFunction>(new ModThirdDeJong));\n    costFunctions.push_back(boost::shared_ptr<CostFunction>(new ModFourthDeJong));\n    costFunctions.push_back(boost::shared_ptr<CostFunction>(new Griewangk));\n\n    std::vector<BoundaryConstraint> constraints;\n    constraints.push_back(BoundaryConstraint(-10.0, 10.0));\n    constraints.push_back(BoundaryConstraint(-10.0, 10.0));\n    constraints.push_back(BoundaryConstraint(-10.0, 10.0));\n    constraints.push_back(BoundaryConstraint(-10.0, 10.0));\n    constraints.push_back(BoundaryConstraint(-600.0, 600.0));\n\n    std::vector<Array> initialValues;\n    initialValues.push_back(Array(3, 5.0));\n    initialValues.push_back(Array(2, 5.0));\n    initialValues.push_back(Array(5, 5.0));\n    initialValues.push_back(Array(30, 5.0));\n    initialValues.push_back(Array(10, 100.0));\n\n    std::vector<EndCriteria> endCriteria;\n    endCriteria.push_back(EndCriteria(100, 10, 1e-10, 1e-8, Null<Real>()));\n    endCriteria.push_back(EndCriteria(100, 10, 1e-10, 1e-8, Null<Real>()));\n    endCriteria.push_back(EndCriteria(100, 10, 1e-10, 1e-8, Null<Real>()));\n    endCriteria.push_back(EndCriteria(500, 100, 1e-10, 1e-8, Null<Real>()));\n    endCriteria.push_back(EndCriteria(1000, 800, 1e-12, 1e-10, Null<Real>()));\n\n    std::vector<Real> minima;\n    minima.push_back(0.0);\n    minima.push_back(0.0);\n    minima.push_back(0.0);\n    minima.push_back(10.9639796558);\n    minima.push_back(0.0);\n\n    for (Size i = 0; i < costFunctions.size(); ++i) {\n        Problem problem(*costFunctions[i], constraints[i], initialValues[i]);\n        diffEvolOptimisers[i].minimize(problem, endCriteria[i]);\n\n        if (i != 3) {\n            // stable\n            if (std::fabs(problem.functionValue() - minima[i]) > 1e-8) {\n                BOOST_ERROR(\"costFunction # \" << i\n                            << \"\\ncalculated: \" << problem.functionValue()\n                            << \"\\nexpected:   \" << minima[i]);\n            }\n        } else {\n            // this case is unstable due to randomness; we're good as\n            // long as the result is below 15\n            if (problem.functionValue() > 15) {\n                BOOST_ERROR(\"costFunction # \" << i\n                            << \"\\ncalculated: \" << problem.functionValue()\n                            << \"\\nexpected:   \" << \"less than 15\");\n            }\n        }\n    }\n}\n\ntest_suite* OptimizersTest::suite() {\n    test_suite* suite = BOOST_TEST_SUITE(\"Optimizers tests\");\n    suite->add(QUANTLIB_TEST_CASE(&OptimizersTest::test));\n    suite->add(QUANTLIB_TEST_CASE(&OptimizersTest::nestedOptimizationTest));\n    suite->add(QUANTLIB_TEST_CASE(&OptimizersTest::testDifferentialEvolution));\n    return suite;\n}\n\n", "meta": {"hexsha": "a90b9c8c6cec541edcca65f73e263d1501593856", "size": 23279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/optimizers.cpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "test-suite/optimizers.cpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "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": "test-suite/optimizers.cpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 41.274822695, "max_line_length": 125, "alphanum_fraction": 0.5878259375, "num_tokens": 5256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5115530877999279}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/math_basic_types.h>\n#include <OpenTissue/kinematics/skeleton/skeleton_types.h>\n#include <OpenTissue/kinematics/inverse/inverse.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\ntypedef OpenTissue::math::default_math_types\t\t  \t\t\t                 math_types;\ntypedef math_types::vector3_type                                         vector3_type;\ntypedef math_types::value_traits                                         value_traits;\ntypedef math_types::real_type                                            real_type;\ntypedef OpenTissue::skeleton::DefaultBoneTraits<math_types>              base_bone_traits;\ntypedef OpenTissue::kinematics::inverse::BoneTraits<base_bone_traits>    bone_traits;\ntypedef OpenTissue::skeleton::Types<math_types, bone_traits>             skeleton_types;\ntypedef skeleton_types::skeleton_type                                    skeleton_type;\ntypedef skeleton_types::bone_type                                        bone_type;\n\nBOOST_AUTO_TEST_SUITE(opentissue_kinematics_inverse_set_joint_parameters);\n\nBOOST_AUTO_TEST_CASE(test_cases)\n{\n  using std::fabs;\n\n  real_type const tol      = boost::numeric_cast<real_type>(0.1);\n\n  // Create some skeleton to test with\n  skeleton_type skeleton;\n\n  bone_type * b0 = skeleton.create_bone();\n  bone_type * b1 = skeleton.create_bone(b0);\n  bone_type * b2 = skeleton.create_bone(b1);\n\n  // Skeleton hierarchy looks like this\n  //\n  //            |  hinge\n  //            b0\n  //    slider /  \n  //          b1  \n  //    ball  |\n  //          b2\n  //\n  vector3_type const hinge_axis   = vector3_type(value_traits::zero(), value_traits::zero(), value_traits::one() );\n  real_type    const hinge_angle  = value_traits::pi_half();\n  vector3_type const slider_axis  = vector3_type(value_traits::one(), value_traits::zero(), value_traits::zero() );\n  real_type    const slider_value = value_traits::four();\n\n  real_type    const phi          = value_traits::pi_quarter();\n  real_type    const psi          = value_traits::pi_half();\n  real_type    const theta        = value_traits::pi_half();\n\n  b0->type() = bone_traits::hinge_type;\n  b0->bind_pose().T() = vector3_type(value_traits::zero(), value_traits::one(), value_traits::zero() );    \n  b0->bind_pose().Q().Ru( hinge_angle, hinge_axis );\n\n  b1->type() = bone_traits::slider_type; \n  b1->bind_pose().T() = slider_axis*slider_value;\n  b1->bind_pose().Q().identity();\n\n  b2->type() = bone_traits::ball_type;\n  b2->bind_pose().T().clear();\n  b2->bind_pose().Q() = OpenTissue::math::Rz(phi)*OpenTissue::math::Ry(psi)*OpenTissue::math::Rz(theta);\n\n  OpenTissue::kinematics::inverse::set_joint_parameters( skeleton );\n\n  BOOST_CHECK( b0->type() == bone_traits::hinge_type );\n  BOOST_CHECK( b1->type() == bone_traits::slider_type );\n  BOOST_CHECK( b2->type() == bone_traits::ball_type );\n  BOOST_CHECK_CLOSE( b0->u()(0), hinge_axis(0), tol);\n  BOOST_CHECK_CLOSE( b0->u()(1), hinge_axis(1), tol);\n  BOOST_CHECK_CLOSE( b0->u()(2), hinge_axis(2), tol);\n\n  BOOST_CHECK_CLOSE( OpenTissue::kinematics::inverse::ACCESSOR::unsynch_get_theta(*b0, 0), hinge_angle, tol);\n  BOOST_CHECK_CLOSE( b1->u()(0), slider_axis(0), tol);\n  BOOST_CHECK_CLOSE( b1->u()(1), slider_axis(1), tol);\n  BOOST_CHECK_CLOSE( b1->u()(2), slider_axis(2), tol);\n  BOOST_CHECK_CLOSE( OpenTissue::kinematics::inverse::ACCESSOR::unsynch_get_theta(*b1, 0), slider_value, tol);\n  BOOST_CHECK_CLOSE( OpenTissue::kinematics::inverse::ACCESSOR::unsynch_get_theta(*b2, 0), phi, tol );\n  BOOST_CHECK_CLOSE( OpenTissue::kinematics::inverse::ACCESSOR::unsynch_get_theta(*b2, 1), psi, tol );\n  BOOST_CHECK_CLOSE( OpenTissue::kinematics::inverse::ACCESSOR::unsynch_get_theta(*b2, 2), theta, tol );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "bf8e321b05a7b509acc098cb1cf8ceb658729dd0", "size": 4236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/kinematics/inverse/set_default_joints/src/unit_set_default_joints.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/kinematics/inverse/set_default_joints/src/unit_set_default_joints.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/kinematics/inverse/set_default_joints/src/unit_set_default_joints.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": 44.125, "max_line_length": 115, "alphanum_fraction": 0.6876770538, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5115530877999279}}
{"text": "#include<stdio.h>\n#include\"mex.h\"\n\n#include \"EdgeSE3ProjectDirectWithDirstortG2oLM.cpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n \n// \u674e\u7fa4\u674e\u4ee3\u6570 \u5e93 \n#include \"sophus/so3.hpp\"\n#include \"sophus/se3.hpp\"\n\n#include <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/dense/linear_solver_dense.h>\n#include <g2o/core/robust_kernel.h>\n#include <g2o/core/robust_kernel_impl.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n\nusing namespace g2o;\n\n// \u4e00\u6b21\u6d4b\u91cf\u7684\u503c\uff0c\u5305\u62ec\u4e00\u4e2a\u4e16\u754c\u5750\u6807\u7cfb\u4e0b\u4e09\u7ef4\u70b9,\u4ee5\u53ca\u6295\u5f71\u7684\u5bf9\u5e94\u7684\u56fe\u50cf\nstruct Measurement\n{\n    Measurement ( Eigen::Vector3d p, float * im) : pos_world (p), image(im){}\n    Eigen::Vector3d pos_world;\n    float* image;\n};\n\nbool calibrationEstimationDirectG2OLM ( const vector<Measurement>& measurements, double *D, double *K, double *imageSize, Eigen::Isometry3d& Tcw, bool verbose, int max_iter)\n{\n    // \u521d\u59cb\u5316g2o\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6,1>> DirectBlock;  // \u6c42\u89e3\u7684\u5411\u91cf\u662f6\uff0a1\u7684\n    DirectBlock::LinearSolverType* linearSolver = new g2o::LinearSolverDense< DirectBlock::PoseMatrixType > ();\n    DirectBlock* solver_ptr = new DirectBlock ( linearSolver );\n    // g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton( solver_ptr ); // G-N\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr ); // L-M\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm ( solver );\n    optimizer.setVerbose( verbose );\n\n    // \u6dfb\u52a0\u9876\u70b9\n    g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap();\n    pose->setEstimate ( g2o::SE3Quat ( Tcw.rotation(), Tcw.translation() ) );\n    pose->setId ( 0 );\n    optimizer.addVertex ( pose );\n\n    // \u6dfb\u52a0\u8fb9\n    int id=1;\n    for ( Measurement m: measurements )\n    {\n        EdgeSE3ProjectDirectWithDirstortG2oLM* edge = new EdgeSE3ProjectDirectWithDirstortG2oLM (\n            m.pos_world,\n            D, K, imageSize, m.image\n        );\n        edge->setVertex (0, pose );\n        edge->setMeasurement (0);\n        edge->setInformation ( Eigen::Matrix<double,1,1>::Identity() );\n        edge->setId ( id++ );\n        optimizer.addEdge ( edge );\n    }\n    // cout<<\"edges in graph: \"<<optimizer.edges().size() <<endl;\n    mexPrintf(\"edges in graph: %d\\n\", optimizer.edges().size());\n    optimizer.initializeOptimization();\n    optimizer.optimize ( max_iter );\n    Tcw = pose->estimate();\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){\n    // nlhs represent the number of parameters of the output\n    // plhs is a array of the mxarray pointers, each pointing to the output\n    // nrhs represents the number of parameters of the input\n    // prhs is a array of the mxarray pointers, each pointing to the input\n\n    // prhs[0], 6x1 matrix\n    // prhs[1], Mx1 cell, each cell with NX3 points\n    // prhs[2], Mx1 cell, each cell with PXQ single matrix\n    // prhs[3], 1x2, or 1x3, or 1x4, or 1x5 matrix\n    // prhs[4], 3x3 matrix\n    // prhs[5], 1x2 matrix\n    // prhs[6], 1x1 matrix\n    // prhs[7], 1x1 matrix\n\n    if(nrhs < 8){\n        mexErrMsgIdAndTxt( \"EdgeSE3ProjectDirectWithDirstortJacobian:invalidNumInputs\", \"at least 8 input arguments required\");\n        return;\n    }\n\n    // get the init xi\n    const size_t *dimArrayOfInitXi = mxGetDimensions(prhs[0]);\n    size_t sizeRowsInitXi = *(dimArrayOfInitXi + 0);\n    size_t sizeColsInitXi = *(dimArrayOfInitXi + 1);\n    if(sizeRowsInitXi != 6 || sizeColsInitXi != 1){\n        mexErrMsgIdAndTxt( \"EdgeSE3ProjectDirectWithDirstortJacobian:invalidInputs\", \"the 1st param should be 6x1\");\n        return;\n    }\n    double *ptrInitXi = (double *)(mxGetPr(prhs[0]));\n    Eigen::Matrix<double, 6, 1> initXi;\n    for(int i = 0; i < 6; i++){\n        initXi(i, 0) = *(ptrInitXi + i);\n    }\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    // get the chessboard lidar points\n    const size_t *dimArrayOfChessboardLidarPoints = mxGetDimensions(prhs[1]);\n    size_t sizeRowsCellChessboardLidarPoints = *(dimArrayOfChessboardLidarPoints + 0);\n    size_t sizeColsCellChessboardLidarPoints = *(dimArrayOfChessboardLidarPoints + 1);\n    if(sizeColsCellChessboardLidarPoints != 1){\n        mexErrMsgIdAndTxt( \"EdgeSE3ProjectDirectWithDirstortJacobian:invalidInputs\", \"the 2st param should be Mx1 cell\");\n        return;\n    }\n    std::vector<std::vector<Eigen::Vector3d>>chessboardLidarPoints; \n    size_t total_measurements = 0;\n    for(int i = 0; i < sizeRowsCellChessboardLidarPoints; i++){\n        // get the dimensions of each cell\n        mxArray *cur_mArray_chessboardLidarPoints = mxGetCell(prhs[1], i);\n        const size_t *dimArrayOfCurrentChessboardLidarPoints = mxGetDimensions(cur_mArray_chessboardLidarPoints);\n        size_t sizeRowsCurrentChessboardLidarPoints = *(dimArrayOfCurrentChessboardLidarPoints + 0);\n        size_t sizeColsCurrentChessboardLidarPoints = *(dimArrayOfCurrentChessboardLidarPoints + 1);\n        if(sizeColsCurrentChessboardLidarPoints != 3){\n            mexErrMsgIdAndTxt( \"EdgeSE3ProjectDirectWithDirstortJacobian:invalidInputs\", \"the 2st param should be cell with Px3\");\n            return;\n        }\n        float *cur_ptr_chessboardLidarPoints = (float *)(mxGetPr(cur_mArray_chessboardLidarPoints));\n        std::vector<Eigen::Vector3d>currentCellChessboardLidarPoints;\n        total_measurements = total_measurements + sizeRowsCurrentChessboardLidarPoints;\n        for(int j = 0; j < sizeRowsCurrentChessboardLidarPoints; j++){\n            Eigen::Vector3d current_chessboardLidarPoint;\n            current_chessboardLidarPoint[0] = cur_ptr_chessboardLidarPoints[0 * sizeRowsCurrentChessboardLidarPoints + j];\n            current_chessboardLidarPoint[1] = cur_ptr_chessboardLidarPoints[1 * sizeRowsCurrentChessboardLidarPoints + j];\n            current_chessboardLidarPoint[2] = cur_ptr_chessboardLidarPoints[2 * sizeRowsCurrentChessboardLidarPoints + j];\n            currentCellChessboardLidarPoints.push_back(current_chessboardLidarPoint);\n        }\n        chessboardLidarPoints.push_back(currentCellChessboardLidarPoints);\n    }\n\n    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    // get the chessoard_Dt_Mask\n    const size_t *dimArrayOfChessboardMaskDT = mxGetDimensions(prhs[2]);\n    size_t sizeRowsCellChessboardMaskDT = *(dimArrayOfChessboardMaskDT + 0);\n    size_t sizeColsCellChessboardMaskDT = *(dimArrayOfChessboardMaskDT + 1);\n    if(sizeColsCellChessboardMaskDT != 1){\n        mexErrMsgIdAndTxt( \"EdgeSE3ProjectDirectWithDirstortJacobian:invalidInputs\", \"the 3st param should be Mx1 cell\");\n        return;\n    }\n    std::vector<float *>chessboardMaskDTPtr;\n    for(int i = 0; i < sizeRowsCellChessboardMaskDT; i++){\n        // get the dimensions of each cell\n        mxArray *cur_mArray_chessboardMaskDT = mxGetCell(prhs[2], i);\n\n        float *cur_ptr_chessboardMaskDT = (float *)(mxGetPr(cur_mArray_chessboardMaskDT));\n        chessboardMaskDTPtr.push_back(cur_ptr_chessboardMaskDT);\n    }\n\n    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    // get the distortion parameters\n    const size_t *dimArrayOfD = mxGetDimensions(prhs[3]);\n    size_t sizeRowsD = *(dimArrayOfD + 0);\n    size_t sizeColsD = *(dimArrayOfD + 1);\n    if(sizeRowsD != 1 || sizeColsD != 5){\n        mexErrMsgIdAndTxt( \"EdgeSE3ProjectDirectWithDirstortJacobian:invalidInputs\", \"the 4st param should be 1x5 array\");\n        return;\n    }\n    double *ptrD = (double *)(mxGetPr(prhs[3]));\n\n    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    // get the intrinsic parameters K\n    const size_t *dimArrayOfK = mxGetDimensions(prhs[4]);\n    size_t sizeRowsK = *(dimArrayOfK + 0);\n    size_t sizeColsK = *(dimArrayOfK + 1);\n    if(sizeRowsK != 3 || sizeColsK != 3){\n        mexErrMsgIdAndTxt( \"EdgeSE3ProjectDirectWithDirstortJacobian:invalidInputs\", \"the 5st param should be 3X3 array\");\n        return;\n    }\n    double *ptrK = (double *)(mxGetPr(prhs[4]));\n\n    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    // get the imageSize\n    const size_t *dimArrayOfImageSize = mxGetDimensions(prhs[5]);\n    size_t sizeRowsImageSize = *(dimArrayOfImageSize + 0);\n    size_t sizeColsImageSize = *(dimArrayOfImageSize + 1);\n    if(sizeRowsImageSize != 1 || sizeColsImageSize != 2){\n        mexErrMsgIdAndTxt( \"EdgeSE3ProjectDirectWithDirstortJacobian:invalidInputs\", \"the 6st param should be 1x2 array\");\n        return;\n    }\n    double *ptrImageSize = (double *)(mxGetPr(prhs[5]));\n\n    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    // get the verbose params\n    const size_t *dimArrayOfVerbose = mxGetDimensions(prhs[6]);\n    size_t sizeRowsVerbose= *(dimArrayOfVerbose + 0);\n    size_t sizeColsVerbose = *(dimArrayOfVerbose + 1);\n    if(sizeRowsVerbose != 1 || sizeColsVerbose != 1){\n        mexErrMsgIdAndTxt( \"EdgeSE3ProjectDirectWithDirstortJacobian:invalidInputs\", \"the 7st param should be 1x1 array\");\n        return;\n    }\n    double *ptrVerbose = (double *)(mxGetPr(prhs[6]));\n\n    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    // get the maxIter params\n    const size_t *dimArrayOfMaxIter = mxGetDimensions(prhs[6]);\n    size_t sizeRowsMaxIter = *(dimArrayOfMaxIter + 0);\n    size_t sizeColsMaxIter = *(dimArrayOfMaxIter + 1);\n    if(sizeRowsMaxIter != 1 || sizeColsMaxIter != 1){\n        mexErrMsgIdAndTxt( \"EdgeSE3ProjectDirectWithDirstortJacobian:invalidInputs\", \"the 8st param should be 1x1 array\");\n        return;\n    }\n    double *ptrMaxIter = (double *)(mxGetPr(prhs[7]));\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    std::vector<Measurement> measurements;\n    std::vector<bool> isInners;\n    Eigen::Isometry3d Tlc = Eigen::Isometry3d::Identity();\n\n    // get the init tcl from the init Xi\n    Sophus::SE3<double> SE3 = Sophus::SE3<double>::exp(initXi);\n    Eigen::Matrix<double, 4, 4> SE3Matrix = SE3.matrix();\n    Tlc.matrix() << SE3Matrix;\n\n    for(int i = 0; i < chessboardMaskDTPtr.size(); i++){\n        float *current_chessboardMaskDTPtr = chessboardMaskDTPtr[i];\n        std::vector<Eigen::Vector3d> current_chessboardLidarPoints = chessboardLidarPoints[i];\n        for(int j = 0; j < current_chessboardLidarPoints.size(); j++){\n            measurements.push_back(Measurement(current_chessboardLidarPoints[j], current_chessboardMaskDTPtr));\n        }\n    }\n    isInners.resize(measurements.size());\n\n    calibrationEstimationDirectG2OLM ( measurements, ptrD, ptrK, ptrImageSize, Tlc, bool(ptrVerbose[0]), int(ptrMaxIter[0]));\n\n    Sophus::SE3<double> SE3_Rt(Tlc.rotation(), Tlc.translation());\n\n    // cout<<\"SE3 = \"<<endl<<SE3_Rt.matrix()<<endl;\n\n    Eigen::Matrix<double,6,1> se3_out = SE3_Rt.log();\n\n    // the output xi will be 1x6\n    size_t dimArrayOfXi[2] = { 1, 6 };\n    plhs[0] = mxCreateNumericArray(2, dimArrayOfXi, mxDOUBLE_CLASS, mxREAL);\n    double *out_xi = (double *)mxGetData(plhs[0]);\n\n    for(int i = 0; i < 6; i++){\n        out_xi[i] = se3_out(i,0);\n    }\n}", "meta": {"hexsha": "a5f5aff2fea79661832d5b887279c20608bdaf9d", "size": 11490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/optimization/cpp/EdgeSE3ProjectDirectWithDirstortG2oLMMex.cpp", "max_stars_repo_name": "ccyinlu/multimodal_data_studio", "max_stars_repo_head_hexsha": "9b76f9033d46a5a812f2ee2babe1526c7d874111", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T01:18:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T00:07:58.000Z", "max_issues_repo_path": "utils/optimization/cpp/EdgeSE3ProjectDirectWithDirstortG2oLMMex.cpp", "max_issues_repo_name": "yxw027/multimodal_data_studio", "max_issues_repo_head_hexsha": "975f0560e32d810fccb8690a36d157162d7da5ab", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-07-29T08:08:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T09:25:31.000Z", "max_forks_repo_path": "utils/optimization/cpp/EdgeSE3ProjectDirectWithDirstortG2oLMMex.cpp", "max_forks_repo_name": "yxw027/multimodal_data_studio", "max_forks_repo_head_hexsha": "975f0560e32d810fccb8690a36d157162d7da5ab", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2019-07-16T06:06:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T23:53:56.000Z", "avg_line_length": 46.8979591837, "max_line_length": 173, "alphanum_fraction": 0.6319408181, "num_tokens": 3136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5115530825162078}}
{"text": "#include <boost/math/complex/acos.hpp>\n", "meta": {"hexsha": "9b022bddfad2cafb8182a75c802ef7c692cc9049", "size": 39, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_complex_acos.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_complex_acos.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_complex_acos.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 19.5, "max_line_length": 38, "alphanum_fraction": 0.7692307692, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5115530772324874}}
{"text": "\ufeff#define _USE_MATH_DEFINES\n#include <iostream>\n#include <memory>\n#include <cmath>\n#include <vector>\n#include <stdlib.h>\n#include <ctype.h>\n#include <string.h>\n\n#include \"Misc.h\"\n#include \"Crc32.h\"\nusing namespace crc32_constexpr;\n\n\nnamespace {\n    std::random_device rnd;\n    std::mt19937 mt(rnd());\n\n    double rand(double min, double max) {\n        if (min > max) {\n            const double t = min;\n            min = max;\n            max = t;\n        }\n        const double r = SU_TO_DOUBLE(mt()) / SU_TO_DOUBLE(mt.max());\n        const double d = max - min;\n        return min + r * d;\n    }\n}\n\n#include \"MoverFunctionExpression.h\"\n\n#define SU_DEF_VARIABLE_MOVER_FUNCTION_EXPRESSION(name, value) \\\nclass name ## MoverFunctionExpression : public MoverFunctionExpression \\\n{ \\\npublic: \\\n\tdouble Execute(const MoverFunctionExpressionVariables& var) const override { return var.value; } \\\n}\n\nSU_DEF_VARIABLE_MOVER_FUNCTION_EXPRESSION(Begin, Begin);\nSU_DEF_VARIABLE_MOVER_FUNCTION_EXPRESSION(End, End);\nSU_DEF_VARIABLE_MOVER_FUNCTION_EXPRESSION(Diff, Diff);\nSU_DEF_VARIABLE_MOVER_FUNCTION_EXPRESSION(Current, Current);\nSU_DEF_VARIABLE_MOVER_FUNCTION_EXPRESSION(Progress, Progress);\n\nclass LiteralMoverFunctionExpression : public MoverFunctionExpression\n{\nprivate:\n    double value;\npublic:\n    LiteralMoverFunctionExpression(double value) : value(value) {}\n    double Execute(const MoverFunctionExpressionVariables& var) const override { return value; }\n};\n\n#define SU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(name, value) \\\nclass name ## MoverFunctionExpression : public MoverFunctionExpression \\\n{ \\\npublic: \\\n\tdouble Execute(const MoverFunctionExpressionVariables& var) const override { return value; } \\\n}\n\nSU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(E, M_E);\nSU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(LOG2E, M_LOG2E);\nSU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(LOG10E, M_LOG10E);\nSU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(LN2, M_LN2);\nSU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(LN10, M_LN10);\nSU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(PI, M_PI);\nSU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(PI_2, M_PI_2);\nSU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(PI_4, M_PI_4);\nSU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(INV_PI, M_1_PI);\nSU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(INV_PI_2, M_2_PI);\nSU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(INV_SQRTPI_2, M_2_SQRTPI);\nSU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(SQRT2, M_SQRT2);\nSU_DEF_CONST_LITERAL_MOVER_FUNCTION_EXPRESSION(INV_SQRT2, M_SQRT1_2);\n\n#define SU_DEF_SINGLE_OPERAND_MOVER_FUNCTION_EXPRESSION(name, op) \\\nclass name ## MoverFunctionExpression : public MoverFunctionExpression \\\n{ \\\nprivate: \\\n\tMoverFunctionExpressionSharedPtr pOp; \\\npublic: \\\n\tname ## MoverFunctionExpression(MoverFunctionExpressionSharedPtr &pOp) : pOp(pOp) {} \\\n\tdouble Execute(const MoverFunctionExpressionVariables& var) const override { return op pOp->Execute(var); } \\\n}\n\nSU_DEF_SINGLE_OPERAND_MOVER_FUNCTION_EXPRESSION(Positive, +);\nSU_DEF_SINGLE_OPERAND_MOVER_FUNCTION_EXPRESSION(Negative, -);\n\n#define SU_DEF_DOUBLE_OPERAND_MOVER_FUNCTION_EXPRESSION(name, op) \\\nclass name ## MoverFunctionExpression : public MoverFunctionExpression \\\n{ \\\nprivate: \\\n\tMoverFunctionExpressionSharedPtr pLop, pRop; \\\npublic: \\\n\tname ## MoverFunctionExpression(MoverFunctionExpressionSharedPtr &pLop, MoverFunctionExpressionSharedPtr &pRop) : pLop(pLop), pRop(pRop) {} \\\n\tdouble Execute(const MoverFunctionExpressionVariables& var) const override { return pLop->Execute(var) op pRop->Execute(var); } \\\n}\n\nSU_DEF_DOUBLE_OPERAND_MOVER_FUNCTION_EXPRESSION(Add, +);\nSU_DEF_DOUBLE_OPERAND_MOVER_FUNCTION_EXPRESSION(Sub, -);\nSU_DEF_DOUBLE_OPERAND_MOVER_FUNCTION_EXPRESSION(Mul, *);\nSU_DEF_DOUBLE_OPERAND_MOVER_FUNCTION_EXPRESSION(Div, / );\n\n#define SU_DEF_DOUBLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(name, func) \\\nclass name ## MoverFunctionExpression : public MoverFunctionExpression \\\n{ \\\nprivate: \\\n\tMoverFunctionExpressionSharedPtr pLop, pRop; \\\npublic: \\\n\tname ## MoverFunctionExpression(MoverFunctionExpressionSharedPtr &pLop, MoverFunctionExpressionSharedPtr &pRop) : pLop(pLop), pRop(pRop) {} \\\n\tdouble Execute(const MoverFunctionExpressionVariables& var) const override { return func (pLop->Execute(var), pRop->Execute(var)); } \\\n}\n\nSU_DEF_DOUBLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Mod, fmod);\nSU_DEF_DOUBLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Pow, pow);\nSU_DEF_DOUBLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Min, fmin);\nSU_DEF_DOUBLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Max, fmax);\nSU_DEF_DOUBLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Rand, rand);\n\n#define SU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(name, func) \\\nclass name ## MoverFunctionExpression : public MoverFunctionExpression \\\n{ \\\nprivate: \\\n\tMoverFunctionExpressionSharedPtr pArg; \\\npublic: \\\n\tname ## MoverFunctionExpression(MoverFunctionExpressionSharedPtr &pArg) : pArg(pArg) {} \\\n\tdouble Execute(const MoverFunctionExpressionVariables& var) const override { return func (pArg->Execute(var)); } \\\n}\n\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Abs, fabs);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Round, round);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Ceil, ceil);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Floor, floor);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Exp, exp);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Ln, log);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Log, log10);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Sin, sin);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Cos, cos);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Tan, tan);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Asin, asin);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Acos, acos);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Atan, atan);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Sinh, sinh);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Cosh, cosh);\nSU_DEF_SINGLE_ARGUMENT_MOVER_FUNCTION_EXPRESSION(Tanh, tanh);\n\n\nbool ParseMoverFunctionExpression(MoverFunctionExpressionSharedPtr &root, const std::string &);\n\n\nMoverFunctionExpressionManager * MoverFunctionExpressionManager::inst;\n\nbool MoverFunctionExpressionManager::Initialize()\n{\n    BOOST_ASSERT(!inst);\n    if (!!inst) return false;\n\n    inst = new MoverFunctionExpressionManager();\n    BOOST_ASSERT(!!inst);\n\n    return !!inst;\n}\n\nbool MoverFunctionExpressionManager::Finalize()\n{\n    BOOST_ASSERT(!!inst);\n    if (!inst) return false;\n\n    delete inst;\n\n    return !inst;\n}\n\nbool MoverFunctionExpressionManager::Register(const std::string &key, const std::string &expression)\n{\n    BOOST_ASSERT(!!inst);\n    if (!inst) return false;\n\n    MoverFunctionExpressionSharedPtr pFunction;\n    if (!ParseMoverFunctionExpression(pFunction, expression) || !pFunction) {\n        spdlog::get(\"main\")->error(u8\"\\\"{0}\\\" \u95a2\u6570 (\\\"{1}\\\") \u306e\u767b\u9332\u306b\u5931\u6557\u3057\u307e\u3057\u305f\u3002\", key, expression);\n        return false;\n    }\n\n    return GetInstance().Register(key, pFunction);\n}\n\nbool MoverFunctionExpressionManager::Register(const std::string &key, MoverFunctionExpression *pFunction)\n{\n    const MoverFunctionExpressionSharedPtr ptr(pFunction);\n    return Register(key, ptr);\n}\n\nbool MoverFunctionExpressionManager::Register(const std::string &key, const MoverFunctionExpressionSharedPtr &pFunction)\n{\n    if (list.find(key) != list.end()) {\n        spdlog::get(\"main\")->warn(u8\"\\\"{0}\\\" \u95a2\u6570\u306f\u65e2\u306b\u767b\u9332\u3055\u308c\u3066\u3044\u307e\u3059\u3002\", key);\n        return false;\n    }\n\n    list.insert(std::make_pair(key, pFunction));\n\n    return true;\n}\n\nbool MoverFunctionExpressionManager::IsRegistered(const std::string &key)\n{\n    BOOST_ASSERT(!!inst);\n    if (!inst) return false;\n\n    MoverFunctionExpressionSharedPtr pFunction;\n    const bool retVal = GetInstance().Find(key, pFunction);\n    return retVal && pFunction;\n}\n\nbool MoverFunctionExpressionManager::Find(const std::string &key, MoverFunctionExpressionSharedPtr &pFunction) const\n{\n    const auto it = list.find(key);\n    if (it == list.end()) return false;\n\n    pFunction = it->second;\n    return true;\n}\n\n\n#define BOOST_RESULT_OF_USE_DECLTYPE\n#define BOOST_SPIRIT_USE_PHOENIX_V3\n\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n\ntemplate<typename T>\nMoverFunctionExpressionSharedPtr MakeExp()\n{\n    return std::make_shared<T>();\n}\n\ntemplate<typename T>\nMoverFunctionExpressionSharedPtr MakeExp_double(double val)\n{\n    return std::make_shared<T>(val);\n}\n\ntemplate<typename T>\nMoverFunctionExpressionSharedPtr MakeExp_Ptr(MoverFunctionExpressionSharedPtr lop)\n{\n    return std::make_shared<T>(lop);\n}\n\ntemplate<typename T>\nMoverFunctionExpressionSharedPtr MakeExp_Ptr_Ptr(MoverFunctionExpressionSharedPtr lop, MoverFunctionExpressionSharedPtr rop)\n{\n    return std::make_shared<T>(lop, rop);\n}\n\nnamespace parser_impl {\n    using namespace boost::spirit;\n    namespace phx = boost::phoenix;\n\n    template<typename Iterator>\n    struct mover_function_grammer\n        : qi::grammar<Iterator, MoverFunctionExpressionSharedPtr(), ascii::space_type>\n    {\n        qi::rule<Iterator, MoverFunctionExpressionSharedPtr(), ascii::space_type> expr, term, fctr;\n\n        mover_function_grammer() : mover_function_grammer::base_type(expr)\n        {\n            expr =           term[qi::_val = qi::_1]\n                >> *(('+' >> term[qi::_val = phx::bind(&MakeExp_Ptr_Ptr<AddMoverFunctionExpression>, qi::_val, qi::_1)])\n                   | ('-' >> term[qi::_val = phx::bind(&MakeExp_Ptr_Ptr<SubMoverFunctionExpression>, qi::_val, qi::_1)]));\n            term =           fctr[qi::_val = qi::_1]\n                >> *(('*' >> fctr[qi::_val = phx::bind(&MakeExp_Ptr_Ptr<MulMoverFunctionExpression>, qi::_val, qi::_1)])\n                   | ('/' >> fctr[qi::_val = phx::bind(&MakeExp_Ptr_Ptr<DivMoverFunctionExpression>, qi::_val, qi::_1)]));\n            fctr = qi::double_        [qi::_val = phx::bind(&MakeExp_double<LiteralMoverFunctionExpression>, qi::_1)]\n                | (qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = qi::_1]\n                | qi::lit(\"begin\")       [qi::_val = phx::bind(&MakeExp<BeginMoverFunctionExpression>)]\n                | qi::lit(\"end\")         [qi::_val = phx::bind(&MakeExp<EndMoverFunctionExpression>)]\n                | qi::lit(\"diff\")        [qi::_val = phx::bind(&MakeExp<DiffMoverFunctionExpression>)]\n                | qi::lit(\"current\")     [qi::_val = phx::bind(&MakeExp<CurrentMoverFunctionExpression>)]\n                | qi::lit(\"progress\")    [qi::_val = phx::bind(&MakeExp<ProgressMoverFunctionExpression>)]\n                | qi::lit('e')           [qi::_val = phx::bind(&MakeExp<EMoverFunctionExpression>)]\n                | qi::lit(\"log2e\")       [qi::_val = phx::bind(&MakeExp<LOG2EMoverFunctionExpression>)]\n                | qi::lit(\"log10e\")      [qi::_val = phx::bind(&MakeExp<LOG10EMoverFunctionExpression>)]\n                | qi::lit(\"ln2\")         [qi::_val = phx::bind(&MakeExp<LN2MoverFunctionExpression>)]\n                | qi::lit(\"ln10\")        [qi::_val = phx::bind(&MakeExp<LN10MoverFunctionExpression>)]\n                | qi::lit(\"pi\")          [qi::_val = phx::bind(&MakeExp<PIMoverFunctionExpression>)]\n                | qi::lit(\"pi_2\")        [qi::_val = phx::bind(&MakeExp<PI_2MoverFunctionExpression>)]\n                | qi::lit(\"pi_4\")        [qi::_val = phx::bind(&MakeExp<PI_4MoverFunctionExpression>)]\n                | qi::lit(\"inv_pi\")      [qi::_val = phx::bind(&MakeExp<INV_PIMoverFunctionExpression>)]\n                | qi::lit(\"inv_pi_2\")    [qi::_val = phx::bind(&MakeExp<INV_PI_2MoverFunctionExpression>)]\n                | qi::lit(\"inv_sqrtpi_2\")[qi::_val = phx::bind(&MakeExp<INV_SQRTPI_2MoverFunctionExpression>)]\n                | qi::lit(\"sqrt2\")       [qi::_val = phx::bind(&MakeExp<SQRT2MoverFunctionExpression>)]\n                | qi::lit(\"inv_sqrt2\")   [qi::_val = phx::bind(&MakeExp<INV_SQRT2MoverFunctionExpression>)]\n                | (qi::lit(\"abs\")   >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<AbsMoverFunctionExpression>,   qi::_1)]\n                | (qi::lit(\"round\") >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<RoundMoverFunctionExpression>, qi::_1)]\n                | (qi::lit(\"ceil\")  >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<CeilMoverFunctionExpression>,  qi::_1)]\n                | (qi::lit(\"floor\") >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<FloorMoverFunctionExpression>, qi::_1)]\n                | (qi::lit(\"exp\")   >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<ExpMoverFunctionExpression>,   qi::_1)]\n                | (qi::lit(\"ln\")    >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<LnMoverFunctionExpression>,    qi::_1)]\n                | (qi::lit(\"log\")   >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<LogMoverFunctionExpression>,   qi::_1)]\n                | (qi::lit(\"sin\")   >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<CosMoverFunctionExpression>,   qi::_1)]\n                | (qi::lit(\"cos\")   >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<SinMoverFunctionExpression>,   qi::_1)]\n                | (qi::lit(\"tan\")   >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<TanMoverFunctionExpression>,   qi::_1)]\n                | (qi::lit(\"asin\")  >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<AsinMoverFunctionExpression>,  qi::_1)]\n                | (qi::lit(\"acos\")  >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<AcosMoverFunctionExpression>,  qi::_1)]\n                | (qi::lit(\"atan\")  >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<AtanMoverFunctionExpression>,  qi::_1)]\n                | (qi::lit(\"sinh\")  >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<SinhMoverFunctionExpression>,  qi::_1)]\n                | (qi::lit(\"cosh\")  >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<CoshMoverFunctionExpression>,  qi::_1)]\n                | (qi::lit(\"tanh\")  >> qi::lit('(') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr<TanhMoverFunctionExpression>,  qi::_1)]\n                | (qi::lit(\"add\")   >> qi::lit('(') >> expr >> qi::lit(',') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr_Ptr<AddMoverFunctionExpression>,  qi::_1, qi::_2)]\n                | (qi::lit(\"sub\")   >> qi::lit('(') >> expr >> qi::lit(',') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr_Ptr<SubMoverFunctionExpression>,  qi::_1, qi::_2)]\n                | (qi::lit(\"mul\")   >> qi::lit('(') >> expr >> qi::lit(',') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr_Ptr<MulMoverFunctionExpression>,  qi::_1, qi::_2)]\n                | (qi::lit(\"div\")   >> qi::lit('(') >> expr >> qi::lit(',') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr_Ptr<DivMoverFunctionExpression>,  qi::_1, qi::_2)]\n                | (qi::lit(\"mod\")   >> qi::lit('(') >> expr >> qi::lit(',') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr_Ptr<ModMoverFunctionExpression>,  qi::_1, qi::_2)]\n                | (qi::lit(\"pow\")   >> qi::lit('(') >> expr >> qi::lit(',') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr_Ptr<PowMoverFunctionExpression>,  qi::_1, qi::_2)]\n                | (qi::lit(\"min\")   >> qi::lit('(') >> expr >> qi::lit(',') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr_Ptr<MinMoverFunctionExpression>,  qi::_1, qi::_2)]\n                | (qi::lit(\"max\")   >> qi::lit('(') >> expr >> qi::lit(',') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr_Ptr<MaxMoverFunctionExpression>,  qi::_1, qi::_2)]\n                | (qi::lit(\"rand\")  >> qi::lit('(') >> expr >> qi::lit(',') >> expr >> qi::lit(')'))[qi::_val = phx::bind(&MakeExp_Ptr_Ptr<RandMoverFunctionExpression>, qi::_1, qi::_2)];\n        }\n    };\n\n    mover_function_grammer<std::string::const_iterator> gMoverFunc;\n}\n\nbool ParseMoverFunctionExpression(MoverFunctionExpressionSharedPtr &root, const std::string &expression)\n{\n    return boost::spirit::qi::phrase_parse(expression.begin(), expression.end(), parser_impl::gMoverFunc, boost::spirit::ascii::space, root);\n}\n", "meta": {"hexsha": "02fc9db8e4a9ab1d3ccd1a561a30214290bf242c", "size": 16301, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Seaurchin/MoverFunctionExpression.cpp", "max_stars_repo_name": "AioiLight/Seaurchin", "max_stars_repo_head_hexsha": "ac6763a51bfba09338f038ab50bdb2ebc883b114", "max_stars_repo_licenses": ["BSL-1.0", "MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-11-11T07:44:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-28T08:29:17.000Z", "max_issues_repo_path": "Seaurchin/MoverFunctionExpression.cpp", "max_issues_repo_name": "amenoshita-429/Seaurchin", "max_issues_repo_head_hexsha": "b9a196ffab080299132a3b2c10b7b778eda58be4", "max_issues_repo_licenses": ["BSL-1.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": "Seaurchin/MoverFunctionExpression.cpp", "max_forks_repo_name": "amenoshita-429/Seaurchin", "max_forks_repo_head_hexsha": "b9a196ffab080299132a3b2c10b7b778eda58be4", "max_forks_repo_licenses": ["BSL-1.0", "MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-10-12T20:09:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-02T00:20:47.000Z", "avg_line_length": 49.547112462, "max_line_length": 186, "alphanum_fraction": 0.6780565609, "num_tokens": 4422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5115530772324874}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <ros/ros.h>\n#include <math.h>\n#include <stdio.h> \n#include <sensor_msgs/Imu.h>\n#include \"geometry_msgs/PoseStamped.h\"\n#include \"mavros_msgs/Altitude.h\"\n#include \"geometry_msgs/Vector3Stamped.h\"\n\nros::Publisher acc_1;\nros::Publisher acc_2;\nros::Publisher veloc;\n\n\nvoid imu_acc(const sensor_msgs::Imu::ConstPtr& msg)\n{\n\t    q = Eigen::Quaternionf(imu.orientation.w, imu.orientation.x, imu.orientation.y, imu.orientation.z);\n    R_mat= q.toRotationMatrix();\n\n    ax=imu.linear_acceleration.x;\n    ay=imu.linear_acceleration.y;\n    az=imu.linear_acceleration.z;\n    imuacc << ax,ay,az;\n    acc= R_mat*imuacc ;\n    imu_msg.pose.orientation.w = imu.orientation.w;\n    imu_msg.pose.orientation.x = imu.orientation.x;\n    imu_msg.pose.orientation.y = imu.orientation.y;\n    imu_msg.pose.orientation.z = imu.orientation.z;\n\treturn;\n}\n\nvoid vicon_vel(const geometry_msgs::PoseStamped::ConstPtr& msg)\n{\n     if(count_vel==0)\n     {\n     \tprev_x = msg->pose.position.x ;\n     \tprev_y = msg->pose.position.y ;\n     \tprev_z = msg->pose.position.z ;\n     \tcount_vel++;\n     \tvel_last_time = ros::Time::now().toSec();\n     }\n     else\n     {\n     \tdt_1 = msg->header.stamp.toSec() - vel_last_time;\n     \tvic_vel.header.stamp = ros::Time::now();\n     \tvic_vel.vector.x = (msg->pose.position.x - prev_x)/dt_1 ;\n     \tvic_vel.vector.y = (msg->pose.position.y - prev_y)/dt_1 ;\n     \tvic_vel.vector.z = (msg->pose.position.z - prev_z)/dt_1 ;\n     \t\n     \tprev_x = msg->pose.position.x ;\n     \tprev_y = msg->pose.position.y ;\n     \tprev_z = msg->pose.position.z ;\n     \t\n     \tveloc.publish(vic_vel);\n\n     \tvel_last_time = ros::Time::now().toSec();\t\n     }\n\n\treturn;\n}\n\nint main(int argc, char** argv){\n\n    ros::init(argc,argv,\"check_acc\");\n         \n    //Initializinging the parameters\n    ros::NodeHandle nh;\n    Initialize(nh);\n  \n    //Subscriber and Publisher for the data. remapped in the launch file to the topic required\n    \n    //ros::Duration(1).sleep();\n    \n    ros::Subscriber Imu = nh.subscribe(\"imu\",10,imu_acc);\n    ros::Subscriber vicon_1 = nh.subscribe(\"vicon_pos\",10,vicon_vel);\n    ros::Subscriber vicon_2 = nh.subscribe(\"vicon_vel\",10,vicon_acc);\n\n    acc_1 = nh.advertise<geometry_msgs::Vector3Stamped>(\"imu_acc\", 10);\n    acc_2 = nh.advertise<geometry_msgs::Vector3Stamped>(\"vicon_acc\", 10);\n    veloc = nh.advertise<geometry_msgs::Vector3Stamped>(\"vicon_velocity\", 10);\n    \n    ros::Rate loop_rate(50);\n    while(ros::ok()){\n\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n    return 0;\n}", "meta": {"hexsha": "fbd36ae53ff48ed8b6bd88e0112ef6b5d053c1b8", "size": 2586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gazebo_sim/gps_denied/src/acc_check.cpp", "max_stars_repo_name": "naveenbiitk/State_Estimation", "max_stars_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-05T06:19:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-05T06:19:20.000Z", "max_issues_repo_path": "gazebo_sim/gps_denied/src/acc_check.cpp", "max_issues_repo_name": "naveenbiitk/State_Estimation", "max_issues_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gazebo_sim/gps_denied/src/acc_check.cpp", "max_forks_repo_name": "naveenbiitk/State_Estimation", "max_forks_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_forks_repo_licenses": ["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.4175824176, "max_line_length": 104, "alphanum_fraction": 0.6535189482, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5115530719487669}}
{"text": "#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <ecl/geometry/angle.hpp>\n#include \"plane_calibration/plane_to_depth_image.hpp\"\n#include \"plane_calibration/plane_calibration.hpp\"\n#include \"plane_calibration/calibration_parameters.hpp\"\n#include \"plane_calibration/visualizer_interface.hpp\"\n\nusing namespace plane_calibration;\n\nTEST(PlaneCalibration, one_shot)\n{\n  int width = 640;\n  int height = 480;\n  double c_x = 321.3;\n  double c_y = 212;\n  double f_x = 570.3422;\n  double f_y = 570.3422;\n  CameraModel camera_model(c_x, c_y, f_x, f_y, width, height);\n\n  double max_deviation = 0.1;\n  double px = -0.628319;\n  double py = 0.057;\n  double pz = 0.0;\n  Eigen::AngleAxisd start_rotation;\n  start_rotation = Eigen::AngleAxisd(px, Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(py, Eigen::Vector3d::UnitY())\n      * Eigen::AngleAxisd(pz, Eigen::Vector3d::UnitZ());\n\n  double px_offset = -0.023;\n  double py_offset = 0.04;\n  Eigen::AngleAxisd rotation_offset;\n  rotation_offset = Eigen::AngleAxisd(px_offset, Eigen::Vector3d::UnitX())\n      * Eigen::AngleAxisd(py_offset, Eigen::Vector3d::UnitY());\n\n  Eigen::Vector3d ground_plane_offset(0.0, -0.16, 0.96);\n\n  Eigen::Affine3d transform = Eigen::Translation3d(ground_plane_offset) * start_rotation * rotation_offset;\n  Eigen::MatrixXf plane = PlaneToDepthImage::convert(transform, camera_model.getParameters());\n  Eigen::MatrixXf noise = Eigen::MatrixXf::Random(plane.rows(), plane.cols());\n  Eigen::MatrixXf random_plane_image = plane + 0.02 * noise;\n\n  CalibrationParametersPtr parameters = std::make_shared<CalibrationParameters>();\n  parameters->update(ground_plane_offset, max_deviation, start_rotation);\n\n  VisualizerInterfacePtr dummy_visualizer;\n  PlaneCalibrationPtr plane_calibration = std::make_shared<PlaneCalibration>(camera_model, parameters, dummy_visualizer);\n\n  std::pair<double, double> one_shot_result = plane_calibration->calibrate(random_plane_image, 3);\n\n  double estimated_px = one_shot_result.first;\n  double estimated_py = one_shot_result.second;\n\n  double epsilon = ecl::degrees_to_radians(0.5);\n  EXPECT_NEAR(estimated_px, px_offset, epsilon);\n  EXPECT_NEAR(estimated_py, py_offset, epsilon);\n}\n", "meta": {"hexsha": "f6779f3efa7491db89559bd0d08a878d586cadfe", "size": 2175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_plane_calibration.cpp", "max_stars_repo_name": "AlexReimann/3d-plane-adjustment", "max_stars_repo_head_hexsha": "0aa5b358febf485d59caea80eb181383f38388f0", "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/test_plane_calibration.cpp", "max_issues_repo_name": "AlexReimann/3d-plane-adjustment", "max_issues_repo_head_hexsha": "0aa5b358febf485d59caea80eb181383f38388f0", "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/test_plane_calibration.cpp", "max_forks_repo_name": "AlexReimann/3d-plane-adjustment", "max_forks_repo_head_hexsha": "0aa5b358febf485d59caea80eb181383f38388f0", "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.5, "max_line_length": 121, "alphanum_fraction": 0.7590804598, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5115464364326915}}
{"text": "#include <armadillo>\n#include <ForwardBackward.hpp>\n#include <HSMM.hpp>\n#include <iostream>\n#include <json.hpp>\n#include <memory>\n#include <ProMPs_emission.hpp>\n\nusing namespace arma;\nusing namespace hsmm;\nusing namespace std;\nusing json = nlohmann::json;\n\n\nvoid PrintBestWeCanAimFor(int nstates, int ndurations, int min_duration,\n        field<ivec> hiddenStates, field<ivec> hiddenDurations) {\n    int nseq = hiddenStates.n_elem;\n    vec best_pi(nstates, fill::zeros);\n    for(int s = 0; s < nseq; s++)\n        best_pi(hiddenStates(s)(0))++;\n    best_pi /= nseq;\n    cout << \"Best initial state pmf we can aim at:\" << endl << best_pi << endl;\n\n    cout << \"Best transition matrix we can aim at:\" << endl;\n    mat prueba(nstates, nstates, fill::zeros);\n    for(int s = 0; s < nseq; s++) {\n        for(int i = 0; i < hiddenStates(s).n_elem - 1; i++)\n            prueba(hiddenStates(s)(i), hiddenStates(s)(i + 1))++;\n    }\n    mat pruebasum = sum(prueba, 1);\n    for(int i = 0; i < nstates; i++)\n        prueba.row(i) /= pruebasum(i);\n    cout << prueba << endl;\n\n    cout << \"Best duration matrix we can aim at:\" << endl;\n    mat emp_durations(nstates, ndurations, fill::zeros);\n    for(int s = 0; s < nseq; s++) {\n        for(int i = 0; i < hiddenStates(s).n_elem; i++)\n            emp_durations(hiddenStates(s)(i), hiddenDurations(s)(i)\n                    - min_duration)++;\n    }\n    mat emp_durations_sum = sum(emp_durations, 1);\n    for(int i = 0; i < nstates; i++)\n        emp_durations.row(i) /= emp_durations_sum(i);\n    cout << emp_durations << endl;\n}\n\nvoid reset(HSMM& hsmm, vector<FullProMP> promps) {\n    int nstates = hsmm.nstates_;\n    int ndurations = hsmm.ndurations_;\n    mat transition(hsmm.transition_);\n    if (nstates == 1)\n        transition.fill(1.0);  // Self-loops allowed in this case.\n    else {\n        transition.fill(1.0/(nstates-1));\n        transition.diag().zeros();  // No self-loops.\n    }\n    hsmm.setTransition(transition);\n    vec pi(hsmm.pi_);\n    pi.fill(1.0/nstates);\n    hsmm.setPi(pi);\n    mat durations(hsmm.duration_);\n    durations.fill(1.0/ndurations);\n    hsmm.setDuration(durations);\n\n    // Resetting emission.\n    for(int i = 0; i < nstates; i++) {\n        ProMP new_model = promps[i].get_model();\n        vec new_mean = randn(size(new_model.get_mu_w()));\n        mat new_Sigma_w(size(new_model.get_Sigma_w()), fill::eye);\n        new_Sigma_w *= 10000;\n        mat new_Sigma_y(size(new_model.get_Sigma_y()), fill::eye);\n        new_Sigma_y *= 1;\n        new_model.set_mu_w(new_mean);\n        new_model.set_Sigma_w(new_Sigma_w);\n        new_model.set_Sigma_y(new_Sigma_y);\n        promps[i].set_model(new_model);\n    }\n    shared_ptr<AbstractEmission> ptr_emission(new ProMPsEmission(promps));\n    hsmm.setEmission(ptr_emission);\n}\n\nint main() {\n    int min_duration = 50;\n    mat transition = {{0.0, 0.1, 0.4, 0.5},\n                      {0.3, 0.0, 0.6, 0.1},\n                      {0.2, 0.2, 0.0, 0.6},\n                      {0.4, 0.4, 0.2, 0.0}};\n    int nstates = transition.n_rows;\n    vec pi = {0.1, 0.2, 0.3, 0.4};\n    // mat durations(nstates, ndurations, fill::eye);\n    mat durations =  {{0.0, 0.1, 0.4, 0.5},\n                      {0.3, 0.0, 0.6, 0.1},\n                      {0.2, 0.2, 0.0, 0.6},\n                      {0.4, 0.4, 0.2, 0.0}};\n    int ndurations = durations.n_cols;\n    int n_basis_functions = 4;\n    int njoints = 1;\n\n    // Setting a third order polynomial basis function for the ProMP\n    int polynomial_order = n_basis_functions - 1;\n    shared_ptr<ScalarBasisFun> kernel{ new ScalarPolyBasis(polynomial_order)};\n\n    // Instantiating as many ProMPs as hidden states.\n    vector<FullProMP> promps;\n    for(int i = 0; i < nstates; i++) {\n        vec mu_w(n_basis_functions * njoints);\n        mu_w.fill(i * 10);\n        mat Sigma_w = (i + 1) * eye<mat>(n_basis_functions * njoints,\n                    n_basis_functions * njoints);\n        mat Sigma_y = 0.0001*eye<mat>(njoints, njoints);\n        ProMP promp(mu_w, Sigma_w, Sigma_y);\n        FullProMP poly(kernel, promp, njoints);\n        promps.push_back(poly);\n    }\n\n    // Creating the ProMP emission.\n    shared_ptr<AbstractEmission> ptr_emission(new ProMPsEmission(promps));\n\n    HSMM promp_hsmm(ptr_emission, transition, pi, durations, min_duration);\n\n    int nseq = 1;\n    int nsegments = 50;\n    field<ivec> hidden_states, hidden_durations;\n    field<field<mat>> multiple_toy_obs = promp_hsmm.sampleMultipleSequences(\n            nseq, nsegments, hidden_states, hidden_durations);\n    cout << \"Generated states and durations for the first sequence\" << endl;\n    cout << join_horiz(hidden_states(0), hidden_durations(0)) << endl;\n\n    PrintBestWeCanAimFor(nstates, ndurations, min_duration, hidden_states,\n            hidden_durations);\n\n    cout << \"Original emission parameters\" << endl;\n    json params_test = promp_hsmm.emission_->to_stream();\n    cout << params_test.dump(4) << endl;\n\n    reset(promp_hsmm, promps);\n\n    cout << \"Emission parameters after reset\" << endl;\n    params_test = promp_hsmm.emission_->to_stream();\n    cout << params_test.dump(4) << endl;\n\n    // Providing some sparse labels.\n    set<int> observed_indexes = {};  //{5,6,7,8,25,26,32,33,39,41,42,43,47};\n    field<Labels> mlabels(nseq);\n    for(int s = 0; s < nseq; s++) {\n        int idx = 0;\n        Labels observed_segments;\n        for(int i = 0; i < nsegments; i++) {\n            int hs = hidden_states(0)(i);\n            int dur = hidden_durations(0)(i);\n            idx += dur;\n            if (observed_indexes.find(i) != observed_indexes.end()) {\n                cout << \"label hs: \" << hs << endl;\n                observed_segments.setLabel(idx - 1, dur, hs);\n            }\n        }\n        mlabels(s) = observed_segments;\n    }\n\n    // Learning the model from data.\n    promp_hsmm.fit(multiple_toy_obs, mlabels, 100, 1e-10);\n\n    cout << \"Model parameters after training\" << endl;\n    json params = promp_hsmm.to_stream();\n    cout << params.dump(4) << endl;\n\n    // Running the Viterbi algorithm for the first sequence.\n    const field<mat>& toy_obs = multiple_toy_obs(0);\n    imat psi_duration(nstates, toy_obs.n_elem, fill::zeros);\n    imat psi_state(nstates, toy_obs.n_elem, fill::zeros);\n    mat delta(nstates, toy_obs.n_elem, fill::zeros);\n    cube log_pdf = promp_hsmm.computeEmissionsLogLikelihood(toy_obs);\n    Viterbi(transition, pi, durations, log_pdf, delta, psi_duration, psi_state,\n            min_duration, toy_obs.n_elem);\n    cout << \"Delta last column\" << endl;\n    cout << delta.col(toy_obs.n_elem - 1) << endl;\n    ivec viterbiStates, viterbiDurations;\n    viterbiPath(psi_duration, psi_state, delta, viterbiStates,\n            viterbiDurations);\n\n    cout << \"Viterbi states and durations\" << endl;\n    cout << join_horiz(viterbiStates, viterbiDurations) << endl;\n    int dur_diff = 0;\n    int states_diff = 0;\n    for(int i = 0; i < viterbiDurations.n_elem; i++) {\n        dur_diff += (viterbiDurations[i] != hidden_durations(0)(i));\n        states_diff += (viterbiStates[i] != hidden_states(0)(i));\n    }\n    cout << \"The number of mismatches in duration is \" << dur_diff << endl;\n    cout << \"The number of mismatches in hidden states is \" << states_diff <<\n            endl;\n    return 0;\n}\n", "meta": {"hexsha": "61a226ade7631f9f5e7663ff6dfa56bd6bda0cf7", "size": 7249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/promps_hsmm_example.cpp", "max_stars_repo_name": "DiegoAE/BOSD", "max_stars_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-05-03T05:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:14:31.000Z", "max_issues_repo_path": "examples/promps_hsmm_example.cpp", "max_issues_repo_name": "DiegoAE/BOSD", "max_issues_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T15:29:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T10:14:54.000Z", "max_forks_repo_path": "examples/promps_hsmm_example.cpp", "max_forks_repo_name": "DiegoAE/BOSD", "max_forks_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T07:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T07:44:09.000Z", "avg_line_length": 37.1743589744, "max_line_length": 79, "alphanum_fraction": 0.6149813767, "num_tokens": 2126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5115464316098692}}
{"text": "#include <iostream>\n#include <string>\n#include <fstream>\n#include <chrono>\n#include <random>\n\n#include <MLearn/Core>\n#include <MLearn/NeuralNets/layers/fc_layer.h>\n#include <MLearn/NeuralNets/neural_nets.h>\n#include <MLearn/Optimization/StochasticGradientDescent.h>\n#include <MLearn/Optimization/AdaGrad.h>\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#include <CImg.h>\n\nusing namespace std;\nusing namespace MLearn;\nusing namespace nn;\nusing namespace Optimization;\nnamespace fs = boost::filesystem;\nusing namespace cimg_library;\ntypedef double float_type;\n\n// import MNIST - for INTEL processor (or other little-endian processors)\nint importMNIST( const fs::path& images_path, const fs::path& labels_path, MLMatrix< float_type >& images, MLMatrix< float_type >& output ){\n\n\tifstream imageFile;\n\tifstream labelFile;\n\n\t// read images file\n\timageFile.open( images_path.string(), ios::binary );\n\tlabelFile.open( labels_path.string(), ios::binary );\n\t// check if open succeded\n\tif (imageFile.fail() || labelFile.fail()){\n\t\tthrow \"Error opening the file!\";\n\t}\n\n\t// useful variables\n\tunsigned char byte;\n\t\n\t// read out magic numbers\n\tuint32_t magic_number = 0;\n\tuint32_t magic_number_label = 0;\n\timageFile.read((char*)&byte,sizeof(byte));\n\tmagic_number |= ( static_cast<uint32_t>(byte) << 24 );\n\timageFile.read((char*)&byte,sizeof(byte));\n\tmagic_number |= ( static_cast<uint32_t>(byte) << 16 );\n\timageFile.read((char*)&byte,sizeof(byte));\n\tmagic_number |= ( static_cast<uint32_t>(byte) << 8 );\n\timageFile.read((char*)&byte,sizeof(byte));\n\tmagic_number |= ( static_cast<uint32_t>(byte) );\n\tlabelFile.read((char*)&byte,sizeof(byte));\n\tmagic_number_label |= ( static_cast<uint32_t>(byte) << 24 );\n\tlabelFile.read((char*)&byte,sizeof(byte));\n\tmagic_number_label |= ( static_cast<uint32_t>(byte) << 16 );\n\tlabelFile.read((char*)&byte,sizeof(byte));\n\tmagic_number_label |= ( static_cast<uint32_t>(byte) << 8 );\n\tlabelFile.read((char*)&byte,sizeof(byte));\n\tmagic_number_label |= ( static_cast<uint32_t>(byte) );\n\t\n\tcout << \"Sanity check: Magic number = \" << magic_number << std::endl;\n\tcout << \"Sanity check: Magic number label = \" << magic_number_label << std::endl;\n\tif ( (magic_number != 2051) || (magic_number_label != 2049) ){\n\t\tthrow \"Error: magic number not correct!\";\n\t}\n\n\t// get number of images\n\tuint32_t N_images = 0;\n\tuint32_t N_labels = 0;\n\timageFile.read((char*)&byte,sizeof(byte));\n\tN_images |= ( static_cast<uint32_t>(byte) << 24 );\n\timageFile.read((char*)&byte,sizeof(byte));\n\tN_images |= ( static_cast<uint32_t>(byte) << 16 );\n\timageFile.read((char*)&byte,sizeof(byte));\n\tN_images |= ( static_cast<uint32_t>(byte) << 8 );\n\timageFile.read((char*)&byte,sizeof(byte));\n\tN_images |= ( static_cast<uint32_t>(byte) );\n\tcout << \"Number of images detected = \" << N_images << endl;\n\tlabelFile.read((char*)&byte,sizeof(byte));\n\tN_labels |= ( static_cast<uint32_t>(byte) << 24 );\n\tlabelFile.read((char*)&byte,sizeof(byte));\n\tN_labels |= ( static_cast<uint32_t>(byte) << 16 );\n\tlabelFile.read((char*)&byte,sizeof(byte));\n\tN_labels |= ( static_cast<uint32_t>(byte) << 8 );\n\tlabelFile.read((char*)&byte,sizeof(byte));\n\tN_labels |= ( static_cast<uint32_t>(byte) );\n\tcout << \"Number of labels detected = \" << N_labels << endl;\n\n\tif (N_images != N_labels){\n\t\tthrow \"Error: different number of training examples detected!\";\n\t}\n\n\t// get number of rows and cols\n\tuint32_t N_rows = 0;\n\timageFile.read((char*)&byte,sizeof(byte));\n\tN_rows |= ( static_cast<uint32_t>(byte) << 24 );\n\timageFile.read((char*)&byte,sizeof(byte));\n\tN_rows |= ( static_cast<uint32_t>(byte) << 16 );\n\timageFile.read((char*)&byte,sizeof(byte));\n\tN_rows |= ( static_cast<uint32_t>(byte) << 8 );\n\timageFile.read((char*)&byte,sizeof(byte));\n\tN_rows |= ( static_cast<uint32_t>(byte) );\n\tuint32_t N_cols = 0;\n\timageFile.read((char*)&byte,sizeof(byte));\n\tN_cols |= ( static_cast<uint32_t>(byte) << 24 );\n\timageFile.read((char*)&byte,sizeof(byte));\n\tN_cols |= ( static_cast<uint32_t>(byte) << 16 );\n\timageFile.read((char*)&byte,sizeof(byte));\n\tN_cols |= ( static_cast<uint32_t>(byte) << 8 );\n\timageFile.read((char*)&byte,sizeof(byte));\n\tN_cols |= ( static_cast<uint32_t>(byte) );\n\n\tcout << \"Image dimensions: \"<<N_rows<<\"x\"<<N_cols<<endl;\n\n\timages.resize(N_rows*N_cols,N_images);\n\toutput = MLMatrix<float_type>::Constant(10,N_images,0);\n\n\t// use openCV matrix\n/*\tMat image = Mat::zeros(N_rows,N_cols,CV_8UC1);\n\tMat_<double> image_to_eigen_gray;\n\tMLMatrix<double> eigen_image(N_rows,N_cols);\n\tEigen::Map< MLVector<double> > view(eigen_image.data(), N_rows*N_cols);*/\n\n\n\tfor (uint32_t i = 0; i < N_images; ++i){\n\n\t\tfor (uint32_t r = 0; r < N_rows; ++r){\n\n\t\t\tfor (uint32_t c = 0; c < N_cols; ++c){\n\n\t\t\t\timageFile.read((char*)&byte,sizeof(byte));\n\t\t\t\t//image.at<uchar>(r,c) = byte;\n\t\t\t\timages(c*N_rows + r, i) = float_type(byte);\n\t\t\t\tif (imageFile.fail()){\n\t\t\t\t\tthrow \"Error reading the file!\";\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\n\t\t}\n\n\t\t// read label\n\t\tlabelFile.read((char*)&byte,sizeof(byte));\n\t\tif (labelFile.fail()){\n\t\t\tthrow \"Error reading the file!\";\n\t\t}\n\t\toutput.col(i)[unsigned(byte)] = 1;\n\n\t\t// transform the image in the range 0 - 1\n\t\t//normalize(image,image_to_eigen_gray,0,1,NORM_MINMAX,CV_64FC1);\n\t\t//cv2eigen(image_to_eigen_gray,eigen_image);\n\t\t//images.col(i) = view;\n\t}\n\timages.array() /= 255.0;\n\n\n\timageFile.close();\n\tlabelFile.close();\n\n\treturn N_rows;\n\n}\n\n\n\nint main(int argc, char* argv[]){\n\tstd::srand((unsigned int) time(0));\n\n\tnamespace po = boost::program_options;\n\ttypedef MLMatrix<float_type> Matrix;\n\ttypedef MLVector<float_type> Vector;\n\tconstexpr ActivationType type = ActivationType::TANH;\n\tconstexpr LossType loss_t = LossType::SOFTMAX_CROSS_ENTROPY;\n\ttypedef FCLayer<float_type, type> layer_t;\n\n\t// Create command line options\n\tpo::options_description \n\tdesc(\"This is a demo showing a simple FC neural net trained on MNIST.\");\n\n\tdesc.add_options()\n\t\t(\"help\", \"Show the help\")\n\t\t(\"data_folder\", po::value<string>(), \"Folder where to find the uncompressed data.\")\n\t\t(\"visualize,v\", po::bool_switch()->default_value(false), \"Visualize test samples with classification.\");\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\tstring data_folder;\n\tif (vm.count(\"data_folder\")){\n\t\tdata_folder = vm[\"data_folder\"].as<string>();\n\t}else{\n\t\tthrow \"Invalid data folder\";\n\t\treturn 1;\n\t}\n\tfs::path data_folder_path(data_folder);\n\tbool visualize = vm[\"visualize\"].as<bool>();\n\n\tMatrix train_images;\n\tMatrix test_images;\n\tMatrix train_labels;\n\tMatrix test_labels;\n\tMatrix labels;\n\tVector temp;\n\n\n\tint image_rows = importMNIST(data_folder_path/fs::path(\"train-images.idx3-ubyte\"), \n\t\t\t\t\t\t\t\t data_folder_path/fs::path(\"train-labels.idx1-ubyte\"),\n\t\t\t\t\t\t\t\t train_images, train_labels);\n\tint image_cols = train_images.rows()/image_rows;\n\timportMNIST(data_folder_path/fs::path(\"t10k-images.idx3-ubyte\"), data_folder_path/fs::path(\"t10k-labels.idx1-ubyte\"),\n\t\t\t\ttest_images, test_labels);\n\n\n\tVector real_labels = Vector::Zero(test_labels.cols());\n\tVector hat_labels = Vector::Zero(test_labels.cols());\n\n\tfor (int idx = 0; idx < test_labels.cols(); ++idx){\n\t\ttemp = test_labels.col(idx);\n\t\ttemp.maxCoeff(&real_labels[idx]);\n\t}\n\n\n\tauto network = make_network<float_type, loss_t>(layer_t(100), layer_t(50), layer_t(train_labels.rows()));\n\tnetwork.set_input_dim(train_images.rows());\n\tVector weights = Vector::Random(network.get_n_parameters())*2.5;\n\tnetwork.set_weights(weights.data(), true);\n\n\tLineSearch< LineSearchStrategy::FIXED,float_type,uint > line_search(0.3);\n\tOptimization::AdaGrad<LineSearchStrategy::FIXED,float_type,uint,0> minimizer;\n\tminimizer.setMaxIter(10);\n\tminimizer.setMaxEpoch(1);\n\tminimizer.setSizeBatch(500);\n\tminimizer.setNSamples(train_images.cols());\n\tminimizer.setLineSearchMethod(line_search);\n\tminimizer.setSeed(std::chrono::system_clock::now().time_since_epoch().count());\n\tstd::cout << \"Initial loss: \" << network.evaluate(test_images, test_labels) << std::endl;\n\tint n_epochs = 0;\n\n\trandom_device rand_dev;\n\tmt19937 generator(rand_dev());\n\tuniform_int_distribution<int> dist(0, test_images.cols());\n\tchar title[50];\n\tCImgDisplay main_disp(800, 800,\"Test samples\", 3, false, true);\n\twhile (true){\n\t\t++n_epochs;\n\t\tnetwork.fit(train_images, train_labels, minimizer);\n\t\tlabels = network.forward_pass(test_images);\n\t\tfloat_type accuracy = 0;\n\t\tfor (int idx = 0; idx < test_labels.cols(); ++idx){\n\t\t\ttemp = labels.col(idx);\n\t\t\ttemp.maxCoeff(&hat_labels[idx]);\n\t\t\taccuracy += float_type( int(hat_labels[idx]) == int(real_labels[idx]) );\n\t\t}\n\t\tfloat_type loss = network.evaluate(test_images, test_labels);\n\t\taccuracy /= float_type(test_labels.cols());\n\t\tfloat_type error_rate = 1.0 - accuracy;\n\t\tstd::cout << \"Loss: \" << loss;\n\t\tstd::cout << \" Error rate: \" << error_rate << std::endl;\n\t\tif (visualize && (n_epochs % 10 == 0)){\n\t\t\t\tint n_images_to_show_per_dim = 10; // This shows n*n images\n\t\t\t\tint frame_width = 2; // surround images with a frame\n\n\t\t\t    // Create empty yellow image\n\t\t\t    CImg<float_type> image(n_images_to_show_per_dim*(image_cols + 2*frame_width), \n\t\t\t    \t\t\t\t\t   n_images_to_show_per_dim*(image_rows + 2*frame_width), 1, 3);\n\t\t\t    image = 0.0;\n\t\t\t    // fill the image\n\t\t\t    float red[]  = { 1.0,0,0 };\n\t\t\t    float green[]  = { 0.0,1.0,0 };\n\t\t\t    for (int i_grid = 0; i_grid < n_images_to_show_per_dim; ++i_grid){\n\t\t\t    \tfor (int j_grid = 0; j_grid < n_images_to_show_per_dim; ++j_grid){\n\t\t\t    \t\tint sample_idx = dist(generator);\n\n\t\t\t    \t\t// Draw sample\n\t\t\t    \t\tint top_left_col = j_grid*(2*frame_width + image_cols) + 2;\n\t\t\t    \t\tint top_left_row = i_grid*(2*frame_width + image_rows) + 2;\n\t\t\t    \t\tfor (int i = 0; i < image_rows; ++i){\n\t\t\t    \t\t\tfor (int j = 0; j < image_cols; ++j){\n\t\t\t    \t\t\t\tint pixel_row = top_left_row + i;\n\t\t\t    \t\t\t\tint pixel_col = top_left_col + j;\n\n\t\t\t    \t\t\t\timage(pixel_row, pixel_col, 0, 0) = test_images(i*image_rows + j, sample_idx);\n\t\t\t    \t\t\t\timage(pixel_row, pixel_col, 0, 1) = test_images(i*image_rows + j, sample_idx);\n\t\t\t    \t\t\t\timage(pixel_row, pixel_col, 0, 2) = test_images(i*image_rows + j, sample_idx);\n\n\t\t\t    \t\t\t}\n\t\t\t    \t\t}\n\t    \t\t\t\tif (hat_labels[sample_idx] == real_labels[sample_idx]){\n\t    \t\t\t\t\timage.draw_text(top_left_row, top_left_col, std::to_string(int(hat_labels[sample_idx])).c_str(), green);\n\t    \t\t\t\t}else{\n\t    \t\t\t\t\timage.draw_text(top_left_row, top_left_col, std::to_string(int(hat_labels[sample_idx])).c_str(), red);\n\t    \t\t\t\t}\n\t\t\t    \t}\n\t\t\t    }\n\t\t\t    \n\t\t\t    image.resize(800, 800);\n\t\t\t    main_disp.display(image);\n\t\t\t    sprintf(title, \"Test samples - Loss: %.3f - Error rate: %.3f\", loss, error_rate);\n\t\t\t    main_disp.set_title(title);\n\t\t\t    main_disp.show();\n\t\t}\n\t}\n\n\treturn 0;\n}", "meta": {"hexsha": "64bdeaade96cdb440e50d754fb4849bca7d271a3", "size": 10684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/demo_mnist/fc_mnist.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_mnist/fc_mnist.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_mnist/fc_mnist.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": 34.2435897436, "max_line_length": 140, "alphanum_fraction": 0.680269562, "num_tokens": 2904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5115464316098691}}
{"text": "/***********************************************************************\nCopyright 2018 Gregory Bryant\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n***********************************************************************/\n\n\n#include \"neconsolecommand.h\"\n#include \"neconsolewindow.h\"\n#include \"nemainwindow.h\"\n#include <boost/multiprecision/gmp.hpp>\n\nusing boost::multiprecision::abs;\nusing boost::multiprecision::mpz_int;\n\nclass ToggleBoolean : public NEConsoleCommand\n{\npublic:\n\n    QString label;\n    QString aliasLabel;\n    bool    *value;\n\n    ToggleBoolean(NEConsoleWindow *consoleWindow,bool *boolVal, QString label, QString aliasLabel):NEConsoleCommand(consoleWindow)\n    {\n        name = \"toggle\";\n        alias = \"t\";\n        description = \"toggle/t \"+label+\"/\"+aliasLabel;\n        this->label = label;\n        this->value = boolVal;\n        this->aliasLabel = aliasLabel;\n    }\n    void command(void *data);\n};\n\nvoid ToggleBoolean::command(void *data)\n{\n    QString *txt = (QString*)data;\n    if(txt==label||txt==aliasLabel)\n    {\n        (*value) = !(*value);\n        consoleWindow->appendText(label+\": \"+QString::number(*value)+\"\\n\");\n        consoleWindow->mainWindow->view.render();\n        consoleWindow->mainWindow->view.update();\n        consoleWindow->lineEdit.setText(\"\");\n    }\n}\n\nclass GoX : public NEConsoleCommand\n{\npublic:\n    GoX(NEConsoleWindow *consoleWindow):NEConsoleCommand(consoleWindow)\n    {\n        name = \"x\";\n        description = \"x n go to x coordinate n\";\n    }\n    void command(void *data);\n};\n\nvoid GoX::command(void *data)\n{\n    QString *txt = (QString*)data;\n\n    mpz_int xPos;\n    int err = mpz_set_str(xPos.backend().data(),txt->toStdString().c_str(),10);\n    if(err){consoleWindow->lineEdit.setText(\"failure\");return;}\n\n    consoleWindow->mainWindow->view.setXPos(xPos);\n\n    consoleWindow->mainWindow->view.render();\n    consoleWindow->mainWindow->view.update();\n    consoleWindow->lineEdit.setText(\"\");\n}\n\nclass GoY : public NEConsoleCommand\n{\npublic:\n    GoY(NEConsoleWindow *consoleWindow):NEConsoleCommand(consoleWindow)\n    {\n        name = \"y\";\n        description = \"y n go to y coordinate n\";\n    }\n    void command(void *data);\n};\n\nvoid GoY::command(void *data)\n{\n    QString *txt = (QString*)data;\n\n    mpz_int yPos;\n    int err = mpz_set_str(yPos.backend().data(),txt->toStdString().c_str(),10);\n    if(err){consoleWindow->lineEdit.setText(\"failure\");return;}\n\n    consoleWindow->mainWindow->view.setYPos(yPos);\n\n    consoleWindow->mainWindow->view.render();\n    consoleWindow->mainWindow->view.update();\n    consoleWindow->lineEdit.setText(\"\");\n}\n\nclass GoScale : public NEConsoleCommand\n{\npublic:\n    GoScale(NEConsoleWindow *consoleWindow):NEConsoleCommand(consoleWindow)\n    {\n        name = \"zoom\";\n        alias = \"z\";\n        description = \"zoom n set scale to n\";\n    }\n    void command(void *data);\n};\n\nvoid GoScale::command(void *data)\n{\n    QString *txt = (QString*)data;\n\n    int scale = txt->toInt();\n    if(scale<=0){scale=2;}\n\n    consoleWindow->mainWindow->view.setScale(scale);\n\n    consoleWindow->mainWindow->view.render();\n    consoleWindow->mainWindow->view.update();\n    consoleWindow->lineEdit.setText(\"\");\n}\n\nclass PrintInfo : public NEConsoleCommand\n{\npublic:\n    PrintInfo(NEConsoleWindow *consoleWindow):NEConsoleCommand(consoleWindow)\n    {\n        name = \"p\";\n        description = \"print various pieces of debug information\";\n    }\n    void command(void *data);\n};\n\nvoid PrintInfo::command(void *data)\n{\n    mpz_int left;\n    mpz_int right;\n    mpz_int top;\n    mpz_int bottom;\n    std::stringstream xStream;\n    std::stringstream yStream;\n    consoleWindow->mainWindow->view.getScreenBounds(&top,&bottom,&left,&right);\n    consoleWindow->appendText(\"\\n\");\n    QString outStr = QString(\"scale: \");\n    outStr += QN(consoleWindow->mainWindow->view.scale);\n    outStr += \"\\n\";\n    outStr += QString(\"resolution: \");\n    outStr += QN(consoleWindow->mainWindow->view.resolution);\n    outStr+=\"\\n\";\n    xStream.str(\"\");\n    yStream.str(\"\");\n    xStream<<top;\n    yStream<<bottom;\n    outStr+=\"top: \"+QString::fromStdString(xStream.str());\n    outStr+=\" bottom: \"+QString::fromStdString(yStream.str());\n    outStr+=\"\\n\";\n    xStream.str(\"\");\n    yStream.str(\"\");\n    xStream<<left;\n    yStream<<right;\n    outStr+=\"left: \"+QString::fromStdString(xStream.str());\n    outStr+=\" right: \"+QString::fromStdString(yStream.str());\n    outStr+=\"\\n\";\n    outStr+=\"xFactorialOffset: \"+QN(consoleWindow->mainWindow->view.xFactorialOffset);\n    outStr+=\"\\n\";\n    outStr+=\"yFactorialOffset: \"+QN(consoleWindow->mainWindow->view.yFactorialOffset);\n    outStr+=\"\\n\";\n    xStream.str(\"\");\n    yStream.str(\"\");\n    xStream<<consoleWindow->mainWindow->view.xOffset;\n    yStream<<consoleWindow->mainWindow->view.yOffset;\n    outStr+=\"xOffset:\"+QString::fromStdString(xStream.str());\n    outStr+=\"\\n\";\n    outStr+=\"yOffset:\"+QString::fromStdString(yStream.str());\n    outStr+=\"\\n\";\n    xStream.str(\"\");\n    yStream.str(\"\");\n    xStream<<consoleWindow->mainWindow->view.xScrollAmt;\n    yStream<<consoleWindow->mainWindow->view.yScrollAmt;\n    outStr+=\"xScrollAmt:\"+QString::fromStdString(xStream.str());\n    outStr+=\"\\n\";\n    outStr+=\"yScrollAmt:\"+QString::fromStdString(yStream.str());\n    outStr+=\"\\n\";\n    consoleWindow->appendText(outStr);\n    consoleWindow->appendText(\"center point: \");\n    consoleWindow->mainWindow->view.printScreenPoint(consoleWindow->mainWindow->view.width()/2,consoleWindow->mainWindow->view.height()/2);\n    consoleWindow->appendText(\"\\n\");\n    consoleWindow->lineEdit.setText(\"\");\n}\n\nclass QuitApp : public NEConsoleCommand\n{\npublic:\n    QuitApp(NEConsoleWindow *consoleWindow):NEConsoleCommand(consoleWindow)\n    {\n        name = \"quit\";\n        alias = \"q\";\n        description = \"quit application\";\n    }\n    void command(void *data);\n};\n\nvoid QuitApp::command(void *data)\n{\n    qApp->exit();\n    consoleWindow->lineEdit.setText(\"\");\n}\n\nclass AppKeys : public NEConsoleCommand\n{\npublic:\n    AppKeys(NEConsoleWindow *consoleWindow):NEConsoleCommand(consoleWindow)\n    {\n        name = \"keys\";\n        description = \"prints a list of keystrokes\";\n    }\n    void command(void *data);\n};\n\nvoid AppKeys::command(void *data)\n{\n    consoleWindow->appendText(\"\\n\");\n    consoleWindow->appendText(\"control + \\t--- zoom in\\n\");\n    consoleWindow->appendText(\"control - \\t--- zoom out\\n\");\n    //consoleWindow->appendText(\"alt + \\t--- increase resolution\\n\");\n    //consoleWindow->appendText(\"alt - \\t--- decrease resolution\\n\");\n    consoleWindow->appendText(\"arrow keys --- scroll around by 10 pixels\\n\");\n    consoleWindow->appendText(\"arrow keys with shift  --- scroll around by 1 pixel\\n\");\n    consoleWindow->appendText(\"arrow keys with control --- scroll around by 100 pixels\\n\");\n    consoleWindow->appendText(\"arrow keys with control and shift --- scroll around by 500 pixels\\n\");\n    consoleWindow->appendText(\"arrow keys with alt --- scroll by factorials\\n\");\n    consoleWindow->appendText(\"space bar \\t--- click point under crosshair\\n\");\n    consoleWindow->lineEdit.setText(\"\");\n}\n\n/*\nclass DumpData : public ConsoleCommand\n{\npublic:\n    DumpData(ConsoleWindow *consoleWindow):ConsoleCommand(consoleWindow)\n    {\n        name = \"dump\";\n        description = \"dump data points\";\n    }\n    void command(void *data);\n};\n\nvoid DumpData::command(void *data)\n{\n    for(int i=0;i<cw->displayWidget->displayObjects.count();i++)\n    {\n        if(cw->displayWidget->displayObjects[i]->name==\"PointData\")\n        {\n            for(int j=0;j<((PointData*)cw->displayWidget->displayObjects[i])->points.count();j++)\n            {\n                float a = ((PointData*)cw->displayWidget->displayObjects[i])->points[j].first;\n                float b = ((PointData*)cw->displayWidget->displayObjects[i])->points[j].second;\n                cw->appendText(QN(a)+\",\"+QN(b)+\"\\n\");\n            }\n        }\n    }\n    cw->ui->lineEdit->setText(\"\");\n}\n*/\n\n\nclass TestCommand : public NEConsoleCommand\n{\npublic:\n    TestCommand(NEConsoleWindow *consoleWindow):NEConsoleCommand(consoleWindow)\n    {\n        name = \"test\";\n        alias = \"t\";\n        description = \"test command\";\n    }\n    void command(void *data);\n};\n\nvoid TestCommand::command(void *data)\n{\n\n}\n", "meta": {"hexsha": "f1d3d64db9e23927ac01a4c15733c531e856e52e", "size": 8712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/consolecommands.cpp", "max_stars_repo_name": "gbryant/number-explorer", "max_stars_repo_head_hexsha": "f1423bb682a6cbfd8238ba980f32659842295456", "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/consolecommands.cpp", "max_issues_repo_name": "gbryant/number-explorer", "max_issues_repo_head_hexsha": "f1423bb682a6cbfd8238ba980f32659842295456", "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/consolecommands.cpp", "max_forks_repo_name": "gbryant/number-explorer", "max_forks_repo_head_hexsha": "f1423bb682a6cbfd8238ba980f32659842295456", "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.3333333333, "max_line_length": 139, "alphanum_fraction": 0.6488751148, "num_tokens": 2079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5115145644252368}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef CBR_CONTROL__MPC__CLTV_OCP_HPP_\n#define CBR_CONTROL__MPC__CLTV_OCP_HPP_\n\n#include <Eigen/Dense>\n\n#include <cbr_utils/utils.hpp>\n\n#include <autodiff/forward.hpp>\n#include <autodiff/forward/eigen.hpp>\n\n#include <utility>\n\n#include \"ocp_common.hpp\"\n\nnamespace cbr\n{\n\n/* ---------------------------------------------------------------------------------------------- */\n/*                          Nonlinear Optimal Control Problem Linearizer                          */\n/* ---------------------------------------------------------------------------------------------- */\n\nstruct CltvOcpParams\n{\n};\n\n/**\n * @brief Linearize a nonlinear control problem to a continuous linear time-varying problem\n * @tparam nl_pb_t nonlinear problem satisfying interface conditions\n */\ntemplate<typename nl_pb_t>\nclass CltvOcp\n{\npublic:\n  // Must be defined in nl_pb_t problem\n  constexpr static std::size_t nx = nl_pb_t::nx;\n  constexpr static std::size_t nu = nl_pb_t::nu;\n\n  // Create some useful aliases\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  // Get return type of problem functions\n  using Tr_t = std::result_of_t<decltype(&nl_pb_t::get_T)(nl_pb_t)>;\n  using x0r_t = std::result_of_t<decltype(&nl_pb_t::get_x0)(nl_pb_t)>;\n  using xlr_t = std::result_of_t<decltype(&nl_pb_t::get_xl)(nl_pb_t, double)>;\n  using ulr_t = std::result_of_t<decltype(&nl_pb_t::get_ul)(nl_pb_t, double)>;\n  using xdr_t = std::result_of_t<decltype(&nl_pb_t::get_xd)(nl_pb_t, double)>;\n  using udr_t = std::result_of_t<decltype(&nl_pb_t::get_ud)(nl_pb_t, double)>;\n  using Qr_t = std::result_of_t<decltype(&nl_pb_t::get_Q)(nl_pb_t, double)>;\n  using QTr_t = std::result_of_t<decltype(&nl_pb_t::get_QT)(nl_pb_t)>;\n  using Rr_t = std::result_of_t<decltype(&nl_pb_t::get_R)(nl_pb_t, double)>;\n\n  // Check return type of problem functions\n  static_assert(\n    std::is_same_v<std::decay_t<Tr_t>, double>,\n    \"The get_T method of the problem must return a double (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<x0r_t>, state_t>,\n    \"The get_x0 method of the problem must return an nx*1 Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<xlr_t>, state_t>,\n    \"The get_xl method of the problem must return an nx*1 Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<ulr_t>, input_t>,\n    \"The get_ul method of the problem must return an nu*1 Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<xdr_t>, state_t>,\n    \"The get_xd method of the problem must return an nx*1 Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<udr_t>, input_t>,\n    \"The get_ud method of the problem must return an nu*1 Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<Qr_t>, Q_t>,\n    \"The get_Q method of the problem must return an nx*nx Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<Rr_t>, R_t>,\n    \"The get_R method of the problem must return an nu*nu Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<QTr_t>, Q_t>,\n    \"The get_QT method of the problem must return an nx*nx Eigen::Matrix (or a reference to one).\");\n\n\n  // Check problem dimensions\n  static_assert(nx > 0, \"Number of states must be > 0.\");\n  static_assert(nu > 0, \"Number of inputs must be > 0.\");\n\npublic:\n  CltvOcp() = delete;\n  CltvOcp(const CltvOcp &) = default;\n  CltvOcp(CltvOcp &&) = default;\n  CltvOcp & operator=(const CltvOcp &) = default;\n  CltvOcp & operator=(CltvOcp &&) = default;\n\n  explicit CltvOcp(const nl_pb_t & pb)\n  : nl_pb_(pb)\n  {}\n\n  explicit CltvOcp(nl_pb_t && pb)\n  : nl_pb_(std::move(pb))\n  {}\n\n  template<typename T1>\n  CltvOcp(T1 && pb)\n  : nl_pb_(std::forward<T1>(pb))\n  {}\n\n  void get_x0(Eigen::Ref<state_t> x0) const\n  {\n    x0 = nl_pb_.get_x0();\n    x0 -= nl_pb_.get_xl(0.);\n  }\n\n  void get_T(double & t) const\n  {\n    t = nl_pb_.get_T();\n  }\n\n  void get_state_lb(double t, Eigen::Ref<state_t> state_lb) const\n  {\n    nl_pb_.get_state_lb(t, state_lb);\n    state_lb -= nl_pb_.get_xl(t);\n  }\n\n  void get_state_ub(double t, Eigen::Ref<state_t> state_ub) const\n  {\n    nl_pb_.get_state_ub(t, state_ub);\n    state_ub -= nl_pb_.get_xl(t);\n  }\n\n  void get_input_lb(double t, Eigen::Ref<input_t> input_lb) const\n  {\n    nl_pb_.get_input_lb(t, input_lb);\n    input_lb -= nl_pb_.get_ul(t);\n  }\n\n  void get_input_ub(double t, Eigen::Ref<input_t> input_ub) const\n  {\n    nl_pb_.get_input_ub(t, input_ub);\n    input_ub -= nl_pb_.get_ul(t);\n  }\n\n  A_t get_A(double t) const\n  {\n    using X_t = Eigen::Matrix<autodiff::dual, nx, 1>;\n    X_t xlin = nl_pb_.get_xl(t);\n    const ulr_t u = nl_pb_.get_ul(t);\n\n    auto fx = [&](const X_t & x) -> X_t {\n        return nl_pb_.get_f(x, u);\n      };\n\n    return autodiff::forward::jacobian(fx, autodiff::wrt(xlin), autodiff::forward::at(xlin));\n  }\n\n  B_t get_B(double t) const\n  {\n    using X_t = Eigen::Matrix<autodiff::dual, nx, 1>;\n    using U_t = Eigen::Matrix<autodiff::dual, nu, 1>;\n    U_t ulin = nl_pb_.get_ul(t);\n    const xlr_t x = nl_pb_.get_xl(t);\n\n    auto fu = [&](const U_t & u) -> X_t {\n        return nl_pb_.get_f(x, u);\n      };\n\n    return autodiff::forward::jacobian(fu, autodiff::wrt(ulin), autodiff::forward::at(ulin));\n  }\n\n  state_t get_E(double t) const\n  {\n    using xldotr_t = std::result_of_t<decltype(&nl_pb_t::get_xldot)(nl_pb_t, double)>;\n\n    const xlr_t xl = nl_pb_.get_xl(t);\n    const xldotr_t xlDot = nl_pb_.get_xldot(t);\n    const ulr_t ul = nl_pb_.get_ul(t);\n    return nl_pb_.get_f(xl, ul) - xlDot;\n  }\n\n  Qr_t get_Q(double t) const\n  {\n    return nl_pb_.get_Q(t);\n  }\n\n  QTr_t get_QT() const\n  {\n    return nl_pb_.get_QT();\n  }\n\n  Rr_t get_R(double t) const\n  {\n    return nl_pb_.get_R(t);\n  }\n\n  state_t get_q(double t) const\n  {\n    const xlr_t xl = nl_pb_.get_xl(t);\n    const xdr_t xd = nl_pb_.get_xd(t);\n    const Qr_t Q = nl_pb_.get_Q(t);\n    return (xl - xd).transpose() * Q;\n  }\n\n  state_t get_qT() const\n  {\n    double T = nl_pb_.get_T();\n    const xlr_t xl = nl_pb_.get_xl(T);\n    const xdr_t xd = nl_pb_.get_xd(T);\n    const QTr_t QT = nl_pb_.get_QT();\n    return (xl - xd).transpose() * QT;\n  }\n\n  input_t get_r(double t) const\n  {\n    const ulr_t ul = nl_pb_.get_ul(t);\n    const udr_t ud = nl_pb_.get_ud(t);\n    const Rr_t R = nl_pb_.get_R(t);\n    return (ul - ud).transpose() * R;\n  }\n\n  nl_pb_t & problem()\n  {\n    return nl_pb_;\n  }\n\nprotected:\n  nl_pb_t nl_pb_{};\n};\n\n// Class template argument deduction guides\ntemplate<typename T>\nCltvOcp(T)->CltvOcp<T>;\n\ntemplate<typename T1, typename T2>\nCltvOcp(T1, T2)->CltvOcp<T1>;\n\n}  // namespace cbr\n\n#endif  // CBR_CONTROL__MPC__CLTV_OCP_HPP_\n", "meta": {"hexsha": "c71c9730d4fb3c145b6581dd0eead493000fdeab", "size": 7075, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_control/mpc/cltv_ocp.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": "include/cbr_control/mpc/cltv_ocp.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": "include/cbr_control/mpc/cltv_ocp.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": 28.7601626016, "max_line_length": 100, "alphanum_fraction": 0.6480565371, "num_tokens": 2216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5115145644252367}}
{"text": "// Copyright (c) 2015\n// Author: Chrono Law\n#include <std.hpp>\nusing namespace std;\n\n#define BOOST_ERROR_CODE_HEADER_ONLY\n#define BOOST_CHRONO_HEADER_ONLY\n#define BOOST_CHRONO_EXTENSIONS\n#include <boost/chrono.hpp>\nusing namespace boost;\nusing namespace boost::chrono;\n\n//////////////////////////////////////////\ntypedef duration<long,   ratio<30>> half_min;\ntypedef duration<int,    ratio<60*15>> quater;\ntypedef duration<double, ratio<3600*24>> day;\n\n//typedef duration<int,60*60> my_hour;\n//typedef duration<int,ratio<-10, 1000>> my_ms;\nvoid case1()\n{\n    seconds s(10);\n    minutes m(5);\n    hours   h(1);\n    milliseconds ms(100);\n\n    assert(s.count() == 10);\n    assert(ms.count() == 100);\n\n    s *= 3;\n    s += seconds(30);\n    s = s - seconds(20);\n    assert(s < seconds(50));\n    cout << s << endl;\n\n}\n\n//////////////////////////////////////////\nvoid case2()\n{\n    seconds s(10);\n    minutes m(5);\n\n    s += m;\n    cout << s << endl;\n\n    //m+= s;\n\n    {\n        seconds s(10);\n        typedef duration<double, ratio<60>> my_min;\n        my_min m(5);\n        m += s;\n        cout << m << endl;\n    }\n\n    {\n        seconds s(40);\n        auto m = duration_cast<minutes>(s);\n        cout << m << endl;\n\n        seconds s2(301);\n        cout << duration_cast<minutes>(s2) << endl;\n    }\n\n    {\n        seconds s(3600 + 50);\n        cout << floor<minutes>(s) << endl;\n        cout << ceil<minutes>(s) << endl;\n        cout << round<minutes>(s) << endl;\n        cout << round<hours>(s) << endl;\n    }\n}\n\n//////////////////////////////////////////\ntemplate<typename T>\nusing clock_desc = clock_string<T, char>;\n\nvoid case3()\n{\n    cout << clock_desc<system_clock>::name() << endl;\n    cout << clock_desc<system_clock>::since() << endl;\n\n    cout << clock_desc<steady_clock>::name() << endl;\n    cout << clock_desc<steady_clock>::since() << endl;\n\n    cout << clock_desc<process_real_cpu_clock>::name() << endl;\n    cout << clock_desc<process_real_cpu_clock>::since() << endl;\n}\n\n//////////////////////////////////////////\nvoid case4()\n{\n    auto tp1 = system_clock::now();\n    cout << tp1 << endl;\n\n    auto d = tp1.time_since_epoch();\n    cout << duration_cast<hours>(d) << endl;\n    cout << duration_cast<day>(d) << endl;\n\n    auto tp2 = tp1 +minutes(1);\n    cout << tp2 << endl;\n\n    {\n        auto tp = steady_clock::now();\n        cout << tp << endl;\n\n        auto d = tp.time_since_epoch();\n        cout << round<minutes>(d) << endl;\n    }\n}\n\n//////////////////////////////////////////\nhours operator\"\" _h(unsigned long long n)\n{\n    return hours(n);\n}\n\nseconds operator\"\" _s(unsigned long long n)\n{\n    return seconds(n);\n}\n\nmilliseconds operator\"\" _ms(unsigned long long n)\n{\n    return milliseconds(n);\n}\nvoid case5()\n{\n    auto h = 5_h;\n    auto s = 45_s;\n    auto ms = 200_ms;\n\n    cout << h << s << ms << endl;\n}\n//////////////////////////////////////////\nvoid case6()\n{\n    auto tp = system_clock::now();\n    auto t = system_clock::to_time_t(tp);\n\n    cout << std::ctime(&t) << endl;\n}\n\n//////////////////////////////////////////\nclass steady_timer final\n{\nprivate:\n    typedef boost::chrono::steady_clock clock_type;\n\n    //typedef clock_type::duration duration_type;\n    typedef clock_type::time_point time_point_type;\n    typedef boost::chrono::microseconds duration_type;\n\n    time_point_type m_start = clock_type::now();\npublic:\n    steady_timer() = default;\n    ~steady_timer() = default;\npublic:\n    void restart()\n    {\n        m_start = clock_type::now();\n    }\n\n    duration_type elapsed() const\n    {\n        return round<duration_type>(\n                clock_type::now() - m_start);\n    }\n};\n\n//////////////////////////////////////////\n\nint main()\n{\n    steady_timer t;\n\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n\n    cout << t.elapsed() << endl;\n}\n", "meta": {"hexsha": "3acd49a4e04cb250fa915588a9fc5ebf55f8f7b0", "size": 3815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "os/chrono.cpp", "max_stars_repo_name": "210843013/boost_guide", "max_stars_repo_head_hexsha": "48f7936812018d695b065a6b7dadab482526b6d3", "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": "os/chrono.cpp", "max_issues_repo_name": "210843013/boost_guide", "max_issues_repo_head_hexsha": "48f7936812018d695b065a6b7dadab482526b6d3", "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": "os/chrono.cpp", "max_forks_repo_name": "210843013/boost_guide", "max_forks_repo_head_hexsha": "48f7936812018d695b065a6b7dadab482526b6d3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-29T13:08:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-29T13:08:23.000Z", "avg_line_length": 20.4010695187, "max_line_length": 64, "alphanum_fraction": 0.5305373526, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5115145603411693}}
{"text": "// \u00a9 2016 PORT INC.\n\n#ifndef OPTIMIZATION__HPP\n#define OPTIMIZATION__HPP\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\nnamespace Optimizer {\n\n\tusing namespace boost::numeric::ublas;\n    using vector = boost::numeric::ublas::vector<double>;\n    using matrix = boost::numeric::ublas::matrix<double>;\n\n\tenum {\n\t\tENABLE_ADAGRAD = 0x1\n\t};\n\n\t////////\n\n\tclass ObjectiveFunction_ {\n\tpublic:\n\t\tObjectiveFunction_(){};\n\t\tvirtual ~ObjectiveFunction_(){};\n\t\tvirtual double value(vector& x) = 0;\n\t\tvirtual double savedValue() = 0;\n\t\tvirtual vector grad(vector& x) = 0;\n\t\tvirtual void preProcess(vector& x) = 0;\n\t\tvirtual void beginLoopProcess(vector& x) = 0;\n\t\tvirtual void afterUpdateXProcess(vector& x) = 0;\n\t\tvirtual void endLoopProcess(vector& x) = 0;\n\t\tvirtual void postProcess(vector& x) = 0;\n\t};\n\n\ttypedef std::shared_ptr<ObjectiveFunction_> ObjectiveFunction;\n\n\t////////\n\n\tclass UnconstrainedNLP_ {\n\n\tpublic:\n\n\t\tUnconstrainedNLP_(int dim, ObjectiveFunction ofunc);\n\t\tvirtual ~UnconstrainedNLP_(){};\n\t\tvirtual void optimize() = 0;\n\t\tvirtual bool isConv();\n\t\tvoid setAe(double arg) { ae = arg; };\n\t\tvoid setRe(double arg) { re = arg; };\n\t\tvoid setMaxIteration(int arg) { maxIteration = arg; };\n\t\tvoid setE0(double arg) { e0 = arg; };\n\t\tvoid setFlg(int arg) { flg = arg; };\n\n\tprotected:\n\n\t\tvirtual double avoidDivergence(vector& g, double& f1);\n\t\tvirtual double linearSearch(vector& g);\n\t\tvoid iteration_limit_error(std::string msg, double beta);\n\t\tvoid minimum_limit_error(std::string msg, double beta);\n\n\tprotected:\n\n\t\tint flg;\n\t\tint dim;\n\t\tint itr;\n\t\tint maxIteration;\n\t\tObjectiveFunction ofunc;\n\t\tdouble e0;\n\t\tdouble alpha;\n\t\tdouble beta;\n\t\tdouble minBeta;\n\t\tdouble xi;\n\t\tdouble tau;\n\t\tdouble r0;\n\t\tdouble f0;\n\t\tdouble re;\n\t\tdouble ae;\n\t\tvector x;\n\t\tvector dx;\n\t\tvector g0;\n\t\tvector g1;\n\t\tvector d;\n\t};\n\n\ttypedef std::shared_ptr<UnconstrainedNLP_> UnconstrainedNLP;\n\n\t////////\n\n\tclass SteepestDescent : public UnconstrainedNLP_ {\n\n\tpublic:\n\n\t\tSteepestDescent(int dim, ObjectiveFunction ofunc);\n\t\tvirtual ~SteepestDescent(){};\n\t\tvirtual void optimize();\n\t\tvirtual bool isConv();\n\n\tprotected:\n\n\t\tvector adagrad;\n\t};\n\n\tUnconstrainedNLP createSteepestDescent(int dim, ObjectiveFunction ofunc);\n\n\t////////\n\n\tclass QuasiNewton_ : public UnconstrainedNLP_ {\n\n\tpublic:\n\n\t\tQuasiNewton_(int dim, ObjectiveFunction ofunc);\n\t\tvirtual ~QuasiNewton_(){};\n\t\tvirtual void optimize();\n\t\tvirtual bool isConv();\n\t\tvoid setBeta(double arg) { beta = arg; };\n\t\tvoid setXi(double arg) { xi = arg; };\n\t\tvoid setTau(double arg) { tau = arg; };\n\n\tprotected:\n\n\t\tvirtual void updateMatrix() = 0;\n\n\tprotected:\n\n\t\tvector y;\n\t\tidentity_matrix<double> I;\n\t\tmatrix H0;\n\t\tmatrix H1;\n\t\tmatrix A;\n\t\tmatrix B;\n\t};\n\n\ttypedef std::shared_ptr<QuasiNewton_> QuasiNewton;\n\n\t////////\n\n\tclass Bfgs : public QuasiNewton_ {\n\tpublic:\n\t\tBfgs(int dim, ObjectiveFunction ofunc);\n\t\tvirtual void updateMatrix();\n\t};\n\n\tUnconstrainedNLP createBfgs(int dim, ObjectiveFunction ofunc);\n\n\tvoid test();\n\n}\n\n#endif // OPTIMIZATION__HPP\n", "meta": {"hexsha": "bbb0a9f620d0255f8f173e4facde1c6821cdbf12", "size": 3012, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Optimizer.hpp", "max_stars_repo_name": "PORT-INC/cicada", "max_stars_repo_head_hexsha": "18730fa951ebf1b92a3116c13ddc75f786595dd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Optimizer.hpp", "max_issues_repo_name": "PORT-INC/cicada", "max_issues_repo_head_hexsha": "18730fa951ebf1b92a3116c13ddc75f786595dd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Optimizer.hpp", "max_forks_repo_name": "PORT-INC/cicada", "max_forks_repo_head_hexsha": "18730fa951ebf1b92a3116c13ddc75f786595dd1", "max_forks_repo_licenses": ["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.2147651007, "max_line_length": 74, "alphanum_fraction": 0.6958831341, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5115145578795863}}
{"text": "/*\n */\n\n#include <iostream>\n\n#include <Eigen/Eigen>\n#include <Eigen/Core>\n#include <sophus/se3.h>\n\n#include \"pinhole_camera.h\"\n#include \"param_reader.h\"\n\nusing namespace std;\n\nPinHoleCamera::PinHoleCamera(ParameterReader::Ptr param_reader) :\nfx_(param_reader->getParam<double>(\"camera.fx\")),\nfy_(param_reader->getParam<double>(\"camera.fy\")),\ncx_ (param_reader->getParam<double>(\"camera.cx\")),\ncy_ (param_reader->getParam<double>(\"camera.cx\")), \nfactor_ (param_reader->getParam<double>(\"camera.factor\")),\nskew_ (param_reader->getParam<double>(\"camera.skew\"))\n{\n\t// \u521d\u59cb\u5316\u5185\u53c2\u77e9\u9635\n\tK_ << fx_, skew_, cx_,   0.0, fy_, cy_,   0.0, 0.0, 1.0;\n\tK_inv_ = K_.inverse();\n}\n\nPinHoleCamera::~PinHoleCamera()\n{\n\t\n}\n\n// // \u5c06\u6839\u636e\u50cf\u7d20\u70b9\u7684\u6a2a\u7eb5\u5750\u6807\u548c\u6df1\u5ea6\u503c\u6062\u590d\u5176\u5728\u76f8\u673a\u5750\u6807\u7cfb\u4e2d\u7684\u4e09\u7ef4\u5750\u6807\n// cv::Point3f PinHoleCamera::point2dTo3d(cv::Point3f& pixel_point_with_depth)\n// {\n// \tint x = pixel_point_with_depth.x;\n// \tint y = pixel_point_with_depth.y;\n// \tdouble d = pixel_point_with_depth.z;\n// \t\n// \tcv::Point3f p;\n// \tp.z = d / factor_;\n// \tp.x = (x - cx_) * p.z / fx_;\n// \tp.y = (y - cy_) * p.z / fy_;\n// \t\n// \treturn p;\n// }\n\n", "meta": {"hexsha": "fc35bc0b56f6bc2705b605dd19132529b9b433cb", "size": 1072, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pinhole_camera.cpp", "max_stars_repo_name": "YangQun1/Slamkit", "max_stars_repo_head_hexsha": "6ac967bd04b569a6645bbaba5ae67483ab2ae64b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-05-18T08:46:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-18T16:32:06.000Z", "max_issues_repo_path": "src/pinhole_camera.cpp", "max_issues_repo_name": "YangQun1/Slamkit", "max_issues_repo_head_hexsha": "6ac967bd04b569a6645bbaba5ae67483ab2ae64b", "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/pinhole_camera.cpp", "max_forks_repo_name": "YangQun1/Slamkit", "max_forks_repo_head_hexsha": "6ac967bd04b569a6645bbaba5ae67483ab2ae64b", "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": 22.3333333333, "max_line_length": 78, "alphanum_fraction": 0.6679104478, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5115145537955192}}
{"text": "/*******************************************************************************\n * Copyright 2013-2014 Sebastian Niemann <niemann@sra.uni-hannover.de>.\n * \n * Licensed under the MIT License (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://opensource.org/licenses/MIT\n * \n * Developers:\n *   Sebastian Niemann - Lead developer\n *   Daniel Kiechle - Unit testing\n ******************************************************************************/\n#include <Expected.hpp>\nusing armadilloJava::Expected;\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <utility>\nusing std::pair;\n\n#include <armadillo>\nusing arma::Mat;\n\n#include <InputClass.hpp>\nusing armadilloJava::InputClass;\n\n#include <Input.hpp>\nusing armadilloJava::Input;\n\nnamespace armadilloJava {\n  class ExpectedInPlaceGenMatRowIndGenDouble : public Expected {\n    public:\n      ExpectedInPlaceGenMatRowIndGenDouble() {\n        cout << \"Compute ExpectedInPlaceGenMatRowIndGenDouble(): \" << endl;\n\n          vector<vector<pair<string, void*>>> inputs = Input::getTestParameters({\n            InputClass::GenMat,\n            InputClass::RowInd,\n            InputClass::GenDouble\n          });\n\n          for (vector<pair<string, void*>> input : inputs) {\n            _fileSuffix = \"\";\n\n            int n = 0;\n            for (pair<string, void*> value : input) {\n              switch (n) {\n                case 0:\n                  _fileSuffix += value.first;\n                  _genMat = *static_cast<Mat<double>*>(value.second);\n                  break;\n                case 1:\n                  _fileSuffix += \",\" + value.first;\n                  _rowInd = *static_cast<int*>(value.second);\n                  break;\n                case 2:\n                  _fileSuffix += \",\" + value.first;\n                  _genDouble = *static_cast<double*>(value.second);\n                  break;\n              }\n              ++n;\n            }\n\n            cout << \"Using input: \" << _fileSuffix << endl;\n\n            _copyOfGenMat = _genMat;\n            _copyOfRowInd = _rowInd;\n            _copyOfGenDouble = _genDouble;\n\n            expectedMatDiagPlus();\n\n            _genMat = _copyOfGenMat;\n            _rowInd = _copyOfRowInd;\n            _genDouble = _copyOfGenDouble;\n            expectedMatDiagMinus();\n\n            _genMat = _copyOfGenMat;\n            _rowInd = _copyOfRowInd;\n            _genDouble = _copyOfGenDouble;\n            expectedMatDiagTimes();\n\n            _genMat = _copyOfGenMat;\n            _rowInd = _copyOfRowInd;\n            _genDouble = _copyOfGenDouble;\n            expectedMatDiagDivide();\n\n            _genMat = _copyOfGenMat;\n            _rowInd = _copyOfRowInd;\n            _genDouble = _copyOfGenDouble;\n            expectedMatColPlus();\n\n            _genMat = _copyOfGenMat;\n            _rowInd = _copyOfRowInd;\n            _genDouble = _copyOfGenDouble;\n            expectedMatColMinus();\n\n            _genMat = _copyOfGenMat;\n            _rowInd = _copyOfRowInd;\n            _genDouble = _copyOfGenDouble;\n            expectedMatColTimes();\n\n            _genMat = _copyOfGenMat;\n            _rowInd = _copyOfRowInd;\n            _genDouble = _copyOfGenDouble;\n            expectedMatColDivide();\n          }\n\n          cout << \"done.\" << endl;\n        }\n\n    protected:\n      Mat<double> _genMat;\n      Mat<double> _copyOfGenMat;\n\n      int _rowInd;\n      int _copyOfRowInd;\n\n      double _genDouble;\n      double _copyOfGenDouble;\n\n      void expectedMatDiagPlus() {\n        if(_rowInd >= _genMat.n_rows) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatDiagPlus() ... \";\n\n        _genMat.diag(-_rowInd) += _genDouble;\n        save<double>(\"Mat.diagSubPlus\", _genMat);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatDiagMinus() {\n        if(_rowInd >= _genMat.n_rows) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatDiagMinus() ... \";\n\n        _genMat.diag(-_rowInd) -= _genDouble;\n        save<double>(\"Mat.diagSubMinus\", _genMat);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatDiagTimes() {\n        if(_rowInd >= _genMat.n_rows) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatDiagTimes() ... \";\n\n        _genMat.diag(-_rowInd) *= _genDouble;\n        save<double>(\"Mat.diagSubTimes\", _genMat);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatDiagDivide() {\n        if(_rowInd >= _genMat.n_rows) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatDiagDivide() ... \";\n\n        _genMat.diag(-_rowInd) /= _genDouble;\n        save<double>(\"Mat.diagSubDivide\", _genMat);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatColPlus() {\n        if(_rowInd >= _genMat.n_rows) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatColPlus() ... \";\n\n        _genMat.row(_rowInd) += _genDouble;\n        save<double>(\"Mat.rowPlus\", _genMat);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatColMinus() {\n        if(_rowInd >= _genMat.n_rows) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatColMinus() ... \";\n\n        _genMat.row(_rowInd) -= _genDouble;\n        save<double>(\"Mat.rowMinus\", _genMat);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatColTimes() {\n        if(_rowInd >= _genMat.n_rows) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatColTimes() ... \";\n\n        _genMat.row(_rowInd) *= _genDouble;\n        save<double>(\"Mat.rowTimes\", _genMat);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatColDivide() {\n        if(_rowInd >= _genMat.n_rows) {\n          return;\n        }\n\n        cout << \"- Compute expectedMatColDivide() ... \";\n\n        _genMat.row(_rowInd) /= _genDouble;\n        save<double>(\"Mat.rowDivide\", _genMat);\n\n        cout << \"done.\" << endl;\n      }\n  };\n}\n", "meta": {"hexsha": "d14952c7f0e7f27f98352271afa50d9083eab11e", "size": 5922, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/cpp/src/ExpectedInPlaceGenMatRowIndGenDouble.cpp", "max_stars_repo_name": "sebiniemann/ArmadilloJava", "max_stars_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-08-05T14:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T17:46:54.000Z", "max_issues_repo_path": "src/test/cpp/src/ExpectedInPlaceGenMatRowIndGenDouble.cpp", "max_issues_repo_name": "sebiniemann/ArmadilloJava", "max_issues_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2019-10-20T21:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T21:53:47.000Z", "max_forks_repo_path": "src/test/cpp/src/ExpectedInPlaceGenMatRowIndGenDouble.cpp", "max_forks_repo_name": "sebiniemann/ArmadilloJava", "max_forks_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T17:01:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T18:45:14.000Z", "avg_line_length": 25.8602620087, "max_line_length": 81, "alphanum_fraction": 0.5231340763, "num_tokens": 1436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5115145472498691}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/10/problem10.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem10 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem10::solve(10);\n        BOOST_CHECK_EQUAL(res, 17);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem10::solve();\n        BOOST_CHECK_EQUAL(res, 142913828922);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "a8df7822d01f32765431f8c4505326af86783ca2", "size": 500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem10.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": "tests/1-50/test_problem10.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": "tests/1-50/test_problem10.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.8095238095, "max_line_length": 51, "alphanum_fraction": 0.68, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5114246512622788}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed 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#include <boost/hana/list/mcd.hpp>\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/detail/minimal/list.hpp>\n#include <boost/hana/detail/minimal/product.hpp>\n#include <boost/hana/integral.hpp>\n#include <boost/hana/maybe.hpp>\n\n#include <tuple>\nusing namespace boost::hana;\n\n\nconstexpr auto prod = detail::minimal::product<>;\n\n// stop_at must return a Maybe, so we need the comparison to be compile-time.\ntemplate <int i>\nconstexpr auto x = int_<i>;\n\ntemplate <typename mcd>\nvoid test() {\n    BOOST_HANA_CONSTEXPR_LAMBDA auto list = detail::minimal::list<mcd>;\n    using L = detail::minimal::List<mcd>;\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto f = [=](auto ...xs) {\n        return std::make_tuple(xs...);\n    };\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto stop_at = [=](auto stop) {\n        return [=](auto x) {\n            return if_(equal(stop, x),\n                nothing,\n                just(prod(x + int_<1>, f(x)))\n            );\n        };\n    };\n\n    BOOST_HANA_CONSTANT_ASSERT(unfoldl<L>(stop_at(x<0>), x<0>) == list());\n    BOOST_HANA_CONSTEXPR_ASSERT(unfoldl<L>(stop_at(x<1>), x<0>) == list(f(x<0>)));\n    BOOST_HANA_CONSTEXPR_ASSERT(unfoldl<L>(stop_at(x<2>), x<0>) == list(f(x<1>), f(x<0>)));\n    BOOST_HANA_CONSTEXPR_ASSERT(unfoldl<L>(stop_at(x<3>), x<0>) == list(f(x<2>), f(x<1>), f(x<0>)));\n    BOOST_HANA_CONSTEXPR_ASSERT(unfoldl<L>(stop_at(x<4>), x<0>) == list(f(x<3>), f(x<2>), f(x<1>), f(x<0>)));\n}\n\n// Make sure it can revert foldl under some conditions\ntemplate <typename mcd>\nvoid test_revert() {\n    BOOST_HANA_CONSTEXPR_LAMBDA auto list = detail::minimal::list<mcd>;\n    using L = detail::minimal::List<mcd>;\n    static constexpr auto z = x<999>;\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto f = prod;\n    BOOST_HANA_CONSTEXPR_LAMBDA auto g = [=](auto k) {\n        return if_(equal(k, z), nothing, just(k));\n    };\n\n    // Make sure the special conditions are met\n    BOOST_HANA_CONSTANT_ASSERT(g(z) == nothing);\n    BOOST_HANA_CONSTANT_ASSERT(g(f(z, x<0>)) == just(prod(z, x<0>)));\n\n    // Make sure the reversing works\n    auto lists = list(\n        list(), list(x<0>), list(x<0>, x<1>), list(x<0>, x<1>, x<2>)\n    );\n    for_each(lists, [=](auto xs) {\n        BOOST_HANA_CONSTANT_ASSERT(unfoldl<L>(g, foldl(xs, z, f)) == xs);\n    });\n}\n\nint main() {\n    test<List::mcd<void>>();\n    test_revert<List::mcd<void>>();\n}\n", "meta": {"hexsha": "26cd6fc43561000029f8a03490af3e6a2ad77fe0", "size": 2558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/list/typeclass/unfoldl.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/list/typeclass/unfoldl.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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/list/typeclass/unfoldl.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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.975, "max_line_length": 109, "alphanum_fraction": 0.6360437842, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.511409553092293}}
{"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_HESSENBERG_INCLUDE\n#define MTL_MATRIX_HESSENBERG_INCLUDE\n\n#include <cmath>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/vector/parameter.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/concept/magnitude.hpp>\n#include <boost/numeric/mtl/operation/householder.hpp>\n#include <boost/numeric/mtl/operation/rank_one_update.hpp>\n#include <boost/numeric/mtl/operation/trans.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl { namespace matrix {\n\n/// Hessenberg-Factorization of matrix A with householder-vectors\n/** Return Hessenberg matrix and tril(B,-2) are Householder-vectors **/\ntemplate <typename Matrix>\nMatrix inline hessenberg_factors(const Matrix& A)\n{\n    vampir_trace<5014> tracer;\n    if (num_rows(A) < 3)\n\treturn A;\n\n    using mtl::imax;\n    typedef typename Collection<Matrix>::value_type   value_type;\n    typedef typename Collection<Matrix>::size_type    size_type;\n    size_type        ncols = num_cols(A), nrows = num_rows(A);\n    value_type       zero= math::zero(A[0][0]), beta;\n    Matrix           B(clone(A));\n\n    for(size_type i= 0; i < ncols-2; i++){\n\t// mtl::vector::dense_vector<value_type>  v(B[irange(i+1, imax)][i]);\n\t\tmtl::vector::dense_vector<value_type, vector::parameters<> >  v(nrows-i-1), w(nrows);\n        for (size_type j = 0; j < size(v); j++)\n            v[j]= B[j+i+1][i];\n        beta= householder(v).second;\n        v= householder(v).first;\n;\n\tif( beta != zero){\n            w= beta * B[irange(0,imax)][irange(i+1,imax)] * v;\n\t    //rank_one_update(B[irange(0,imax)][irange(i+1,imax)],-w,v);\n            for(size_type row = 0; row < nrows; row++){\n                for(size_type col = i+1; col < ncols; col++){\n                    B[row][col] -= w[row] * v[col-i-1];\n                }\n            }\n            //vector*Matrix\n            for(size_type k=0; k < size(w); k++){\n                w[k]= zero;\n                for(size_type j = 0; j < size(v); j++){\n                    w[k] += beta * v[j] * B[j+i+1][k];\n                }\n            }\n            //rank_one_update(A[irange(i+1,imax)][irange(0,imax)],-v,w);\n            for(size_type row = i+1; row < nrows; row++){\n                for(size_type col = 0; col < ncols; col++){\n                    B[row][col] -= v[row-i-1] * w[col];\n                }\n            }\n\t    // B[irange(i+2, imax)][i]= v[irange(1, nrows-i-1)];\n            for(size_type row = i+2; row < nrows; row++){\n                B[row][i] = v[row-i-1];\n            }\n        }\n    }\n    return B;\n}\n\n\n/// Extract Householder vectors from Hessenberg factorization H of some A\ntemplate <typename Matrix>\nMatrix inline extract_householder_hessenberg(const Matrix& H)\n{\n    vampir_trace<5015> tracer;\n    return Matrix(tril(H, -2));\n}\n\n/// Compute Householder vectors from Hessenberg factorization of A\ntemplate <typename Matrix>\nMatrix inline householder_hessenberg(const Matrix& A)\n{\n    vampir_trace<5016> tracer;\n    return Matrix(tril(hessenberg_factors(A), -2));\n}\n\n\n/// Extract Hessenberg form from factorization H of some A\ntemplate <typename Matrix>\nMatrix inline extract_hessenberg(const Matrix& H)\n{\n    vampir_trace<5017> tracer;\n    return Matrix(triu(H, -1));\n}\n\n/// Hessenberg form of A\ntemplate <typename Matrix>\nMatrix inline hessenberg(const Matrix& A)\n{\n    vampir_trace<5018> tracer;\n    // return triu(hessenberg_factors(A), -1);\n    MTL_THROW_IF(num_rows(A) < 3, matrix_too_small());\n\n    typedef typename Collection<Matrix>::value_type   value_type;\n    // typedef typename Magnitude<value_type>::type      magnitude_type; // to multiply with 2 not 2+0i\n    typedef typename Collection<Matrix>::size_type    size_type;\n    size_type        ncols = num_cols(A), nrows = num_rows(A);\n    value_type       zero= math::zero(A[0][0]);\n    Matrix           H(nrows,ncols);\n\n    H= hessenberg_factors(A);\n    \n    // H= bands(hessenberg_factors(A), -nrows, -1);\n    // set (doubly) strict lower triangle to zero\n    for(size_type row = 2; row < nrows; row++){\n        for(size_type col = 0; col < row-1; col++){\n            H[row][col]= zero;\n        }\n    }\n\n    return H;\n}\n\n\n/// Return Q where Q'*A*Q == hessenberg(A)\ntemplate <typename Matrix>\nMatrix inline hessenberg_q(const Matrix& A)\n{\n    vampir_trace<5013> tracer;\n    using std::abs;\n    typedef typename Collection<Matrix>::value_type   value_type;\n    typedef typename Magnitude<value_type>::type      magnitude_type; // to multiply with 2 not 2+0i\n    typedef typename Collection<Matrix>::size_type    size_type;\n    size_type        ncols = num_cols(A), nrows = num_rows(A), mini;\n    value_type       zero= math::zero(A[0][0]), one= math::one(A[0][0]);\n    const magnitude_type two(2);\n    Matrix           Q(nrows,ncols);\n\n    MTL_THROW_IF(num_rows(A) < 3, matrix_too_small());\n\n    Q= one;\n\n    //Extract Q\n    for(size_type i = 0; i < nrows-2; i++){\n\t\tmtl::vector::dense_vector<value_type, vector::parameters<> >   v(nrows-1), w(nrows);\n        v[0]= one;\n// \tstd::cout<< \"v=\" << v << \"\\n\";\n// \tstd::cout<< \"w=\" << w << \"\\n\";\n        for(size_type k = 1; k < size(v); k++)\n            v[k]= A[nrows-k][i];\n        \n\tmagnitude_type beta= two / abs(dot(v, v)); // abs: x+0i -> x\n        if (beta != two) {\n            //trans(Vector)*Matrix\n            for(size_type k = 0; k < size(w); k++) {\n                w[k]= zero;\n                for(size_type j = 0; j < size(v); j++){\n// \t\t     std::cout<< \"k=\" << k << \"  j=\" << j << \"\\n\";\n                    w[k]+= beta * v[j] * Q[j+i+1][k];\n\t\t}\n            }\n            //rank_one_update(Q[irange(i+1,imax)][irange(0,imax)],-v,w);\n            for(size_type row = i+1; row < nrows; row++)\n                for(size_type col = 0; col < ncols; col++){\n// \t\t    std::cout<< \"row=\" << row << \"  col=\" << col << \"\\n\";\n                    Q[row][col] -= v[row-1] * w[col];\n\t\t}\n        }\n    }\n    return Q;\n}\n\n\n}} // namespace mtl::matrix\n\n#endif // MTL_MATRIX_HESSENBERG_INCLUDE\n\n", "meta": {"hexsha": "9408752e6a6ed1aaa49d5f97809d2128c8c0ff73", "size": 6565, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/hessenberg.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/hessenberg.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/hessenberg.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.6666666667, "max_line_length": 103, "alphanum_fraction": 0.5926884996, "num_tokens": 1845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5114095507904097}}
{"text": "/**\n * @brief \n * \n * @file admitanceCalcTest.cpp\n * @author Luiz Victor Linhares Rocha <luizvictorlrocha@gmail.com>\n * @date 2018-09-22\n * @copyright 2018\n */\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_tools.hpp>\n#include \"../libraries/Eigen/Eigen\"\n#include \"../rede/barra.hpp\"\n#include \"../rede/branch.hpp\"\n#include \"../rede/powerNet.hpp\"\n#include \"../rede/admitanceCalc.hpp\"\n#include \"../util/complexutils.h\"\n\n\nnamespace tt = boost::test_tools;\n\nusing neuralFlux::PowerNet;\nusing neuralFlux::PowerNetPtr;\nusing neuralFlux::Bar;\nusing neuralFlux::BarPtr;\nusing neuralFlux::BranchPtr;\nusing neuralFlux::AdmitanceCalc;\n\nstruct FPower {\n    FPower() : net(new PowerNet()) {\n        net->addSlackBar(1, 1., 0.);\n        net->addPQBar(2, 0.3, 0.);\n        net->addPQBar(3, 0.3, 0.);\n        net->addPQBar(4, 0.3, 0.);\n        net->addPQBar(5, 0.3, 0.);\n\n        net->connect(1, 2, 0., 0.1, 0., 0.98);\n        net->connect(2, 3, 0., 0.1, 0., 1., 0.2);\n        net->connect(2, 5, 0.1, 0.1);\n        net->connect(3, 4, 0.1, 1.0);\n        net->connect(4, 5, 0.1, 1.0);\n\n        answer << std::complex<double>(0., -9.604),\n            std::complex<double>(0, 9.8),\n            std::complex<double>(0., 0.),\n            std::complex<double>(0., 0.),\n            std::complex<double>(0., 0.),\n            std::complex<double>(0., 9.8),\n            std::complex<double>(5., -25.),\n            std::complex<double>(1.98669, 9.80067),\n            std::complex<double>(0., 0.),\n            std::complex<double>(-5., 5.),\n            std::complex<double>(0., 0.),\n            std::complex<double>(-1.98669, 9.80067),\n            std::complex<double>(0.0990099, -10.9901),\n            std::complex<double>(-0.0990099, 0.990099),\n            std::complex<double>(0., 0.),\n            std::complex<double>(0., 0.),\n            std::complex<double>(0., 0.),\n            std::complex<double>(-0.0990099, 0.990099),\n            std::complex<double>(0.19802, -1.9802),\n            std::complex<double>(-0.0990099, 0.990099),\n            std::complex<double>(0., 0.),\n            std::complex<double>(-5., 5.),\n            std::complex<double>(0., 0.),\n            std::complex<double>(-0.0990099, 0.990099),\n            std::complex<double>(5.09901, -5.9901);\n    }\n\n    ~FPower() {\n    }\n\n    PowerNetPtr net;\n    Eigen::Matrix<std::complex<double>, 5, 5> answer;\n};\n\nBOOST_FIXTURE_TEST_CASE(Admitance11, FPower) {\n    BarPtr bar = net->getBar(1);\n    std::complex<double> y = AdmitanceCalc::getAdmitanceKk(bar);\n    BOOST_TEST(y.real() == answer(0, 0).real(), tt::tolerance(0.001));\n    BOOST_TEST(y.imag() == answer(0, 0).imag(), tt::tolerance(0.001));\n}\n\nBOOST_FIXTURE_TEST_CASE(Admitance22, FPower) {\n    BarPtr bar = net->getBar(2);\n    std::complex<double> y = AdmitanceCalc::getAdmitanceKk(bar);\n    BOOST_TEST(y.real() == answer(1, 1).real(), tt::tolerance(0.001));\n    BOOST_TEST(y.imag() == answer(1, 1).imag(), tt::tolerance(0.001));\n}\n\nBOOST_FIXTURE_TEST_CASE(Admitance33, FPower) {\n    BarPtr bar = net->getBar(3);\n    std::complex<double> y = AdmitanceCalc::getAdmitanceKk(bar);\n    BOOST_TEST(y.real() == answer(2, 2).real(), tt::tolerance(0.001));\n    BOOST_TEST(y.imag() == answer(2, 2).imag(), tt::tolerance(0.001));\n}\n\nBOOST_FIXTURE_TEST_CASE(Admitance44, FPower) {\n    BarPtr bar = net->getBar(4);\n    std::complex<double> y = AdmitanceCalc::getAdmitanceKk(bar);\n    BOOST_TEST(y.real() == answer(3, 3).real(), tt::tolerance(0.001));\n    BOOST_TEST(y.imag() == answer(3, 3).imag(), tt::tolerance(0.001));\n}\n\nBOOST_FIXTURE_TEST_CASE(Admitance55, FPower) {\n    BarPtr bar = net->getBar(5);\n    std::complex<double> y = AdmitanceCalc::getAdmitanceKk(bar);\n    BOOST_TEST(y.real() == answer(4, 4).real(), tt::tolerance(0.001));\n    BOOST_TEST(y.imag() == answer(4, 4).imag(), tt::tolerance(0.001));\n}\n\nBOOST_FIXTURE_TEST_CASE(Admitance12, FPower) {\n    BranchPtr branch = net->getBranchByIndex(0);\n    std::complex<double> y = AdmitanceCalc::getAdmitanceKm(branch);\n    BOOST_TEST(y.real() == answer(0, 1).real(), tt::tolerance(0.001));\n    BOOST_TEST(y.imag() == answer(0, 1).imag(), tt::tolerance(0.001));\n}\n\nBOOST_FIXTURE_TEST_CASE(Admitance21, FPower) {\n    BranchPtr branch = net->getBranchByIndex(0);\n    std::complex<double> y = AdmitanceCalc::getAdmitanceMk(branch);\n    BOOST_TEST(y.real() == answer(1, 0).real(), tt::tolerance(0.001));\n    BOOST_TEST(y.imag() == answer(1, 0).imag(), tt::tolerance(0.001));\n}\n\nBOOST_FIXTURE_TEST_CASE(admitance, FPower) {\n    Eigen::MatrixXcd Y = AdmitanceCalc::getMatrix(net);\n    for (size_t i = 0; i < 5; i++) {\n        for (size_t j = 0; j < 5; j++) {\n            BOOST_TEST(Y(i, j).real() == answer(i, j).real(), tt::tolerance(0.001));\n            BOOST_TEST(Y(i, j).imag() == answer(i, j).imag(), tt::tolerance(0.001));\n        }\n    }\n}\n\nBOOST_FIXTURE_TEST_CASE(NetAdmitance, FPower) {\n    for (size_t i = 0; i < 5; i++) {\n        for (size_t j = 0; j < 5; j++) {\n            BOOST_TEST(net->getY(i, j).real() == answer(i, j).real(), tt::tolerance(0.001));\n            BOOST_TEST(net->getY(i, j).imag() == answer(i, j).imag(), tt::tolerance(0.001));\n        }\n    }\n}\n\nBOOST_FIXTURE_TEST_CASE(BranchOnOff, FPower) {\n    net->getBranchByIndex(4)->setBranchOn(false);\n    PowerNetPtr net2(new PowerNet());\n    net2->addSlackBar(1, 1., 0.);\n    net2->addPQBar(2, 0.3, 0.);\n    net2->addPQBar(3, 0.3, 0.);\n    net2->addPQBar(4, 0.3, 0.);\n    net2->addPQBar(5, 0.3, 0.);\n    net2->connect(1, 2, 0., 0.1, 0., 0.98);\n    net2->connect(2, 3, 0., 0.1, 0., 1., 0.2);\n    net2->connect(2, 5, 0.1, 0.1);\n    net2->connect(3, 4, 0.1, 1.0);\n    for (size_t i = 0; i < 5; i++) {\n        for (size_t j = 0; j < 5; j++) {\n            BOOST_TEST(net->getY(i, j).real() == net2->getY(i, j).real(), tt::tolerance(0.001));\n            BOOST_TEST(net->getY(i, j).imag() == net2->getY(i, j).imag(), tt::tolerance(0.001));\n        }\n    }\n}\n", "meta": {"hexsha": "ea8e59fb16b6a617efc731340c050fdb58874498", "size": 5910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/admitanceCalcTest.cpp", "max_stars_repo_name": "BigsonLvrocha/NeuralPowerFlow", "max_stars_repo_head_hexsha": "3d64078b5d1053cd521318229b69592acab6582a", "max_stars_repo_licenses": ["MIT"], "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/admitanceCalcTest.cpp", "max_issues_repo_name": "BigsonLvrocha/NeuralPowerFlow", "max_issues_repo_head_hexsha": "3d64078b5d1053cd521318229b69592acab6582a", "max_issues_repo_licenses": ["MIT"], "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/admitanceCalcTest.cpp", "max_forks_repo_name": "BigsonLvrocha/NeuralPowerFlow", "max_forks_repo_head_hexsha": "3d64078b5d1053cd521318229b69592acab6582a", "max_forks_repo_licenses": ["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.8181818182, "max_line_length": 96, "alphanum_fraction": 0.5800338409, "num_tokens": 2091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5114095457963541}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/assert.hpp>\n#include <boost/hana/monoid.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <test/auto/base.hpp>\n#include <test/auto/monoid.hpp>\nusing namespace boost::hana;\n\n\nnamespace boost { namespace hana { namespace test {\n    template <> auto objects<int> = make<Tuple>(0,1,2,3,4,5);\n    template <> auto objects<unsigned int> = make<Tuple>(0u,1u,2u,3u,4u,5u);\n    template <> auto objects<long> = make<Tuple>(0l,1l,2l,3l,4l,5l);\n    template <> auto objects<unsigned long> = make<Tuple>(0ul,1ul,2ul,3ul,4ul,5ul);\n}}}\n\n\nint main() {\n    test::laws<Monoid, int>();\n    test::laws<Monoid, unsigned int>();\n\n    test::laws<Monoid, long>();\n    test::laws<Monoid, unsigned long>();\n\n    using T = int;\n    constexpr T x = 6, y = 4;\n\n    // zero\n    {\n        BOOST_HANA_CONSTEXPR_CHECK(zero<T>() == static_cast<T>(0));\n    }\n\n    // plus\n    {\n        BOOST_HANA_CONSTEXPR_CHECK(plus(x, y) == x + y);\n    }\n}\n", "meta": {"hexsha": "cfc61227de784a270572808bee5f5b5361532d49", "size": 1102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/monoid.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/monoid.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/monoid.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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.0454545455, "max_line_length": 83, "alphanum_fraction": 0.6433756806, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5114095408022986}}
{"text": "// Copyright (c) 2015-2018, CNRS\n// Authors: Justin Carpentier <jcarpent@laas.fr>\n\n#ifndef __multicontact_api_geometry_linear_cone_hpp__\n#define __multicontact_api_geometry_linear_cone_hpp__\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <pinocchio/spatial/se3.hpp>\n\n#include \"multicontact-api/geometry/fwd.hpp\"\n#include \"multicontact-api/serialization/archive.hpp\"\n#include \"multicontact-api/serialization/eigen-matrix.hpp\"\n\n#define EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_ROWS_SIZE(TYPE, ROWS) \\\n  EIGEN_STATIC_ASSERT(TYPE::RowsAtCompileTime == ROWS, THIS_METHOD_IS_ONLY_FOR_MATRICES_OF_A_SPECIFIC_SIZE)\n\nnamespace multicontact_api {\nnamespace geometry {\n\ntemplate <typename _Scalar, int _dim, int _Options>\nstruct LinearCone : public serialization::Serializable<LinearCone<_Scalar, _dim, _Options> > {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  typedef _Scalar Scalar;\n  enum { dim = _dim, Options = _Options };\n  typedef Eigen::Matrix<Scalar, dim, -1, Options> MatrixDx;\n  typedef Eigen::Matrix<Scalar, dim, dim, Options> MatrixD;\n  typedef Eigen::Matrix<Scalar, dim, 1, Options> VectorD;\n  typedef Eigen::DenseIndex Index;\n\n  /// \\brief Default constructor\n  LinearCone() : m_rays() {}\n\n  /// \\brief Constructor from a set of rays\n  template <typename EigenDerived>\n  explicit LinearCone(const Eigen::MatrixBase<EigenDerived>& rays)\n      //      : m_rays(_dim,rays.cols())\n      : m_rays(rays) {\n    //        EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(EigenDerived,MatrixDx)\n    //        for(int k=0; k<rays.cols(); ++k)\n    //          m_rays.col(k) = rays.col(k).normalized();\n  }\n\n  /// \\brief Contrustor from a given size.\n  explicit LinearCone(const Index size) : m_rays(_dim, size) {}\n\n  /// \\brief Copy constructor\n  template <typename S2, int O2>\n  LinearCone(const LinearCone<S2, dim, O2>& other) : m_rays(other.m_rays) {}\n\n  void addRay(const VectorD& ray) {\n    m_rays.conservativeResize(Eigen::NoChange_t(), m_rays.cols() + 1);\n    m_rays.template rightCols<1>() = ray.normalized();\n  }\n\n  template <typename EigenDerived>\n  void stack(const Eigen::MatrixBase<EigenDerived>& rays) {\n    EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_ROWS_SIZE(EigenDerived, dim);\n    m_rays.conservativeResize(Eigen::NoChange_t(), m_rays.cols() + rays.cols());\n    m_rays.rightCols(rays.cols()) = rays;\n  }\n\n  template <typename S2, int O2>\n  void stack(const LinearCone<S2, dim, O2>& other) {\n    stack(other.rays());\n  }\n\n  /// \\returns the rays of the linear cone.\n  const MatrixDx& rays() const { return m_rays; }\n  MatrixDx& rays() { return m_rays; }\n\n  /// \\returns the number of rays, i.e. the number of cols of m_rays\n  Index size() const { return m_rays.cols(); }\n\n  template <typename S2, int O2>\n  bool operator==(const LinearCone<S2, dim, O2>& other) const {\n    return m_rays == other.m_rays;\n  }\n\n  template <typename S2, int O2>\n  bool operator!=(const LinearCone<S2, dim, O2>& other) const {\n    return !(*this == other);\n  }\n\n  template <typename S2, int O2>\n  bool isApprox(const LinearCone<S2, dim, O2>& other,\n                const Scalar& prec = Eigen::NumTraits<Scalar>::dummy_precision()) const {\n    return m_rays.isApprox(other.m_rays, prec);\n  }\n\n  void disp(std::ostream& os) const { os << \"Rays:\\n\" << m_rays << std::endl; }\n\n  friend std::ostream& operator<<(std::ostream& os, const LinearCone& C) {\n    C.disp(os);\n    return os;\n  }\n\n protected:\n  /// \\brief Rays of the linear cone\n  MatrixDx m_rays;\n\n private:\n  // Serialization of the class\n  friend class boost::serialization::access;\n\n  template <class Archive>\n  void save(Archive& ar, const unsigned int /*version*/) const {\n    ar& boost::serialization::make_nvp(\"rays\", m_rays);\n  }\n\n  template <class Archive>\n  void load(Archive& ar, const unsigned int /*version*/) {\n    ar >> boost::serialization::make_nvp(\"rays\", m_rays);\n  }\n\n  BOOST_SERIALIZATION_SPLIT_MEMBER()\n};\n\ntemplate <typename _Scalar, int _Options>\nstruct ForceConeTpl : public LinearCone<_Scalar, 3, _Options> {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef LinearCone<_Scalar, 3, _Options> Base;\n  typedef WrenchConeTpl<_Scalar, _Options> WrenchCone;\n  typedef pinocchio::SE3Tpl<_Scalar, _Options> SE3;\n  using typename Base::Scalar;\n  enum { dim = Base::dim };\n  using Base::rays;\n  using Base::size;\n  using typename Base::Index;\n  using typename Base::MatrixD;\n  using typename Base::MatrixDx;\n  using typename Base::VectorD;\n  using Base::operator==;\n  using Base::operator!=;\n  //      using Base::isApprox; // Leads to a bug with clang\n\n  typedef MatrixDx Matrix3x;\n  typedef VectorD Vector3;\n  typedef Eigen::AngleAxis<Scalar> AngleAxis;\n\n  /// \\brief Default constructor\n  ForceConeTpl() : Base() {}\n\n  template <typename EigenDerived>\n  explicit ForceConeTpl(const Eigen::MatrixBase<EigenDerived>& rays) : Base(rays) {}\n\n  explicit ForceConeTpl(const Index size) : Base(size) {}\n\n  /// \\returns a linear cone built from a friction coefficient and the number of rays along the Z axis.\n  static ForceConeTpl RegularCone(const Scalar mu, const VectorD& direction, const int num_rays,\n                                  const Scalar theta_offset = 0.) {\n    assert(mu >= 0. && \"mu must be positive\");\n    assert(num_rays >= 1 && \"The number of rays must be at least one\");\n\n    const VectorD normalized_direction(direction.normalized());\n    ForceConeTpl cone(num_rays);\n\n    const Scalar angle = (2. * M_PI) / num_rays;\n\n    const MatrixD Po(MatrixD::Identity() - normalized_direction * normalized_direction.transpose());\n\n    const MatrixD rot_offset(AngleAxis(theta_offset, normalized_direction).toRotationMatrix());\n    const VectorD init_direction(rot_offset * (Po * VectorD::Ones()).normalized());\n    const MatrixD rot(AngleAxis(angle, normalized_direction).toRotationMatrix());\n\n    VectorD ray((direction + mu * init_direction).normalized());\n\n    for (int k = 0; k < num_rays; ++k) {\n      cone.rays().col(k) = ray;\n      if (k != num_rays - 1) ray = rot * ray;\n    }\n\n    return cone;\n  }\n\n  WrenchCone SE3ActOn(const SE3& M) const {\n    WrenchCone res(size());\n    typedef typename WrenchCone::MatrixDx::ColXpr Col6Xpr;\n    typedef typename MatrixDx::ConstColXpr ConstCol3Xpr;\n\n    const typename SE3::Matrix3& R = M.rotation();\n    const typename SE3::Vector3& t = M.translation();\n\n    for (Index k = 0; k < size(); ++k) {\n      ConstCol3Xpr in_col = rays().col(k);\n      Col6Xpr out_col = res.rays().col(k);\n\n      out_col.template head<3>() = R * in_col;\n      out_col.template tail<3>() = t.cross(out_col.template head<3>());\n    }\n\n    return res;\n  }\n\n  template <typename S2, int O2>\n  bool isApprox(const ForceConeTpl<S2, O2>& other,\n                const Scalar& prec = Eigen::NumTraits<Scalar>::dummy_precision()) const {\n    return Base::isApprox(other, prec);\n  }\n\n  operator WrenchCone() const {\n    WrenchCone res(size());\n    res.rays().template topRows<3>() = rays();\n    res.rays().template bottomRows<3>().setZero();\n    return res;\n  }\n};\n\ntemplate <typename _Scalar, int _Options>\nstruct WrenchConeTpl : public LinearCone<_Scalar, 6, _Options> {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef LinearCone<_Scalar, 6, _Options> Base;\n  typedef ForceConeTpl<_Scalar, _Options> ForceCone;\n  typedef pinocchio::SE3Tpl<_Scalar, _Options> SE3;\n  using typename Base::Scalar;\n  enum { dim = Base::dim };\n  using Base::rays;\n  using Base::size;\n  using typename Base::Index;\n  using typename Base::MatrixDx;\n  using typename Base::VectorD;\n  using Base::operator==;\n  using Base::operator!=;\n  //      using Base::isApprox; // Leads to a bug with clang\n\n  typedef MatrixDx Matrix6x;\n  typedef VectorD Vector6;\n\n  typedef typename ForceCone::Matrix3x Matrix3x;\n\n  typedef typename Matrix6x::template NRowsBlockXpr<3>::Type LinearBlock;\n  typedef typename Matrix6x::template ConstNRowsBlockXpr<3>::Type ConstLinearBlock;\n\n  typedef LinearBlock AngularBlock;\n  typedef ConstLinearBlock ConstAngularBlock;\n\n  /// \\brief Default constructor\n  WrenchConeTpl() : Base() {}\n\n  /// \\brief Constructor from a set of rays.\n  template <typename EigenDerived>\n  explicit WrenchConeTpl(const Eigen::MatrixBase<EigenDerived>& rays) : Base(rays) {}\n\n  /// \\brief Constructs a WrenchCone of a given size.\n  explicit WrenchConeTpl(const Index size) : Base(size) {}\n\n  /// \\brief Constructs a WrenchCone of a given size.\n  template <typename S2, int O2>\n  explicit WrenchConeTpl(const ForceConeTpl<S2, O2>& force_cone) : Base(force_cone.size()) {\n    rays().template topRows<3>() = force_cone.rays();\n    rays().template bottomRows<3>().setZero();\n  }\n\n  /// \\brief Copy constructor\n  template <typename S2, int O2>\n  WrenchConeTpl(const WrenchConeTpl<S2, O2>& other) : Base(other) {}\n\n  WrenchConeTpl SE3ActOn(const SE3& M) const {\n    WrenchConeTpl res(size());\n    typedef typename MatrixDx::ColXpr Col6Xpr;\n    typedef typename MatrixDx::ConstColXpr ConstCol6Xpr;\n\n    const typename SE3::Matrix3& R = M.rotation();\n    const typename SE3::Vector3& t = M.translation();\n\n    for (Index k = 0; k < size(); ++k) {\n      ConstCol6Xpr in_col = rays().col(k);\n      Col6Xpr out_col = res.rays().col(k);\n\n      out_col.template head<3>() = R * in_col.template head<3>();\n      out_col.template tail<3>() = t.cross(out_col.template head<3>()) + R * in_col.template tail<3>();\n    }\n\n    return res;\n  }\n\n  template <typename S2, int O2>\n  bool isApprox(const WrenchConeTpl<S2, O2>& other,\n                const Scalar& prec = Eigen::NumTraits<Scalar>::dummy_precision()) const {\n    return Base::isApprox(other, prec);\n  }\n\n  ConstLinearBlock linear() const { return rays().template topRows<3>(); }\n  LinearBlock linear() { return rays().template topRows<3>(); }\n\n  ConstAngularBlock angular() const { return rays().template bottomRows<3>(); }\n  AngularBlock angular() { return rays().template bottomRows<3>(); }\n\n  ForceCone toForceCone() const { return ForceCone(linear()); }\n};\n}  // namespace geometry\n}  // namespace multicontact_api\n\n#endif  // ifndef __multicontact_api_geometry_linear_cone_hpp__\n", "meta": {"hexsha": "b42e9885061e3949f181a89dffd1217ebe8d2e26", "size": 9955, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/multicontact-api/geometry/linear-cone.hpp", "max_stars_repo_name": "proyan/multicontact-api", "max_stars_repo_head_hexsha": "3ff225a2a114044dda07ee9d933dc060a96cc359", "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/multicontact-api/geometry/linear-cone.hpp", "max_issues_repo_name": "proyan/multicontact-api", "max_issues_repo_head_hexsha": "3ff225a2a114044dda07ee9d933dc060a96cc359", "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/multicontact-api/geometry/linear-cone.hpp", "max_forks_repo_name": "proyan/multicontact-api", "max_forks_repo_head_hexsha": "3ff225a2a114044dda07ee9d933dc060a96cc359", "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.5185185185, "max_line_length": 107, "alphanum_fraction": 0.6944249121, "num_tokens": 2756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5114095408022986}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <test/unit/math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdBinomialCoefficientLog, Fvar) {\n  using boost::math::digamma;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n\n  fvar<double> x(2004.0, 1.0);\n  fvar<double> y(1002.0, 2.0);\n\n  fvar<double> a = stan::math::binomial_coefficient_log(x, y);\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_);\n  EXPECT_FLOAT_EQ(0.69289774, a.d_);\n}\n\nTEST(AgradFwdBinomialCoefficientLog, FvarFvarDouble) {\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::fvar;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<double> > a = binomial_coefficient_log(x, y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_.val_);\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_);\n  EXPECT_NEAR(0, a.d_.val_, 1e-8);\n  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_);\n}\n\nstruct binomial_coefficient_log_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 binomial_coefficient_log(arg1, arg2);\n  }\n};\n\nTEST(AgradFwdBinomialCoefficientLog, nan) {\n  binomial_coefficient_log_fun binomial_coefficient_log_;\n  test_nan_fwd(binomial_coefficient_log_, 3.0, 5.0, false);\n}\n", "meta": {"hexsha": "67d9195f01e9a160619b0601a5cd092dda0fc078", "size": 1532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/fwd/scal/fun/binomial_coefficient_log_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/fwd/scal/fun/binomial_coefficient_log_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/fwd/scal/fun/binomial_coefficient_log_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": 29.4615384615, "max_line_length": 76, "alphanum_fraction": 0.7297650131, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.5114095408022986}}
{"text": "/*\n * sdf2sdf_optimizer2d.cpp\n *\n *  Created on: Mar 05, 2019\n *      Author: Fei Shan\n */\n\n\n#pragma once\n\n//libraries\n#include <Eigen/Eigen>\n\n//local\n#include \"../tsdf/parameters.hpp\"\n#include \"../tsdf/generator.hpp\"\n\nnamespace eig = Eigen;\n\nnamespace rigid_optimization {\n\nclass Sdf2SdfOptimizer2d {\n    public:\n        struct VerbosityParameters {\n            VerbosityParameters(bool print_iteration_max_warp_update = false,\n                                bool print_iteration_energy = false);\n            //per-iteration parameters\n            const bool print_iteration_max_warp_update = false;\n            const bool print_iteration_energy = false;\n            const bool print_per_iteration_info = false;\n        };\n\n        Sdf2SdfOptimizer2d(\n                float rate = 0.5f,\n                int maximum_iteration_count = 60,\n\t\t\t\ttsdf::Parameters2d tsdf_generation_parameters = tsdf::Parameters2d(),\n                VerbosityParameters verbosity_parameters = VerbosityParameters()\n        );\n\n        virtual ~Sdf2SdfOptimizer2d();\n\n    eig::Matrix3f optimize(int image_y_coordinate,\n                           const eig::MatrixXf canonical_field,\n\t\t\t\t\t\t   const eig::Matrix<unsigned short, eig::Dynamic, eig::Dynamic>& live_depth_image,\n                           float eta = 0.01f,\n\t\t\t\t\t\t   const eig::Matrix4f& initial_camera_pose = eig::Matrix4f::Identity());\n\n    private:\n        const float rate = 0.5f;\n        const int maximum_iteration_count = 60;\n        const tsdf::Generator2d tsdf_generator;\n        const Sdf2SdfOptimizer2d::VerbosityParameters verbosity_parameters;\n\n};\n\n}\n", "meta": {"hexsha": "129bd2de09ba451b9edf4f4cf17f3c9dd207690e", "size": 1603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rigid_optimization/sdf_2_sdf_optimizer2d.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/rigid_optimization/sdf_2_sdf_optimizer2d.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/rigid_optimization/sdf_2_sdf_optimizer2d.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": 28.1228070175, "max_line_length": 89, "alphanum_fraction": 0.6375545852, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5114095385004153}}
{"text": "//####### Test module for Quantum Synchrotron emission engine (SI units) #######\n\n//Define Module name\n #define BOOST_TEST_MODULE \"Quantum Synchrotron emission engine (SI units)\"\n\n//Will automatically define a main for this test\n #define BOOST_TEST_DYN_LINK\n\n #include <utility>\n\n //Include Boost unit tests library & library for floating point comparison\n #include <boost/test/unit_test.hpp>\n #include <boost/test/floating_point_comparison.hpp>\n\n//SI units are used for this test\n#define PXRMP_USE_SI_UNITS\n#include \"quantum_sync_engine.hpp\"\n\n//Uses random numbers\n#include \"rng_wrapper.hpp\"\n\nusing namespace picsar::multi_physics;\n\n//________________________________\n\n//Helper function\ntemplate<typename REAL>\nquantum_synchrotron_engine<REAL, stl_rng_wrapper<REAL>> get_qs_stl_set_lambda(uint64_t seed, REAL lambda,\nquantum_synchrotron_engine_ctrl<REAL> qs_ctrl = quantum_synchrotron_engine_ctrl<REAL>())\n{\n    stl_rng_wrapper<REAL> wrap{seed};\n    auto qs_engine =  quantum_synchrotron_engine<REAL, stl_rng_wrapper<REAL>>{std::move(wrap), 1.0, qs_ctrl};\n    qs_engine.set_lambda(static_cast<REAL>(lambda));\n    return qs_engine;\n}\n\n// ------------- Tests --------------\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 1.0e-3;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-2;\n\n//Templated tolerance\ntemplate <typename T>\nT tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_tolerance;\n    else\n        return double_tolerance;\n}\n\n//***SI UNITS***\n//SI units for momenta\nconst double me_c = electron_mass * light_speed;\n//SI units for fields\ndouble lambda = 800.0 * si_nanometer;\ndouble eref = 2.0*pi*electron_mass*light_speed*light_speed/\n            (lambda*elementary_charge);\ndouble bref = eref/light_speed;\n//SI units for dt and rate\ndouble dtref = lambda/(2.0*pi*light_speed);\ndouble rateref = 1.0/dtref;\n\n\n//Test get/set lambda for quantum_synchrotron_engine generic\ntemplate <typename T>\nvoid quantum_sync_engine_gs()\n{\n    auto qs_engine = get_qs_stl_set_lambda<T>\n        (390109317, static_cast<T>(800.0*si_nanometer));\n    BOOST_CHECK_EQUAL( static_cast<T>(1.0), qs_engine.get_lambda());\n}\n\n//Test get/set lambda for quantum_synchrotron_engine (double precision)\nBOOST_AUTO_TEST_CASE( quantum_sync_engine_gs_double_1 )\n{\n    quantum_sync_engine_gs<double>();\n}\n\n//Test get/set lambda for quantum_synchrotron_engine (single precision)\nBOOST_AUTO_TEST_CASE( quantum_sync_engine_gs_single_1 )\n{\n    quantum_sync_engine_gs<float>();\n}\n\n// ------------- optical depth --------------\n//Test get/set lambda for quantum_synchrotron_engine generic\ntemplate <typename T>\nvoid quantum_sync_engine_opt()\n{\n    auto qs_engine = get_qs_stl_set_lambda<T>\n        (390109317, static_cast<T>(800.0*si_nanometer));\n    BOOST_TEST ( qs_engine.get_optical_depth() >= static_cast<T>(0.0) );\n}\n\n//Test get new optical depth (double precision)\nBOOST_AUTO_TEST_CASE( quantum_sync_engine_opt_double_1 )\n{\n    quantum_sync_engine_opt<double>();\n}\n\n//Test get new optical depth (single precision)\nBOOST_AUTO_TEST_CASE( quantum_sync_engine_opt_single_1 )\n{\n    quantum_sync_engine_opt<float>();\n}\n", "meta": {"hexsha": "401bfb29a5c3f2b3f77b0fa69dbfb688f1a10e95", "size": 3170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED_tests/test_quantum_sync_engine_SI.cpp", "max_stars_repo_name": "thaisacs/PICSAR", "max_stars_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/multi_physics/QED_tests/test_quantum_sync_engine_SI.cpp", "max_issues_repo_name": "thaisacs/PICSAR", "max_issues_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multi_physics/QED_tests/test_quantum_sync_engine_SI.cpp", "max_forks_repo_name": "thaisacs/PICSAR", "max_forks_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8181818182, "max_line_length": 109, "alphanum_fraction": 0.7511041009, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5114095358082431}}
{"text": "#include <catch2/catch.hpp>\n\n#include <trianglelite/trianglelite.h>\n\n#include <Eigen/Core>\n#include <iostream>\n\nTEST_CASE(\"Point cloud\", \"[trianglelite]\")\n{\n    using namespace trianglelite;\n\n    Config config;\n    Engine engine;\n\n    SECTION(\"Convex hull\")\n    {\n        config.convex_hull = true;\n        config.verbose_level = 0;\n    }\n    SECTION(\"With max area\")\n    {\n        config.max_area = 0.1;\n        config.verbose_level = 0;\n    }\n    SECTION(\"With max area too small\")\n    {\n        config.max_area = 1e-7;\n        config.verbose_level = 0;\n    }\n\n    Eigen::Matrix<Scalar, 3, 2, Eigen::RowMajor> points;\n    points << 0.0, 0.0, 1.0, 0.0, 0.0, 1.0;\n    engine.set_in_points(points.data(), static_cast<int>(points.rows()));\n    engine.run(config);\n\n    auto out_points = engine.get_out_points();\n    REQUIRE(out_points.rows() >= 3);\n    auto out_triangles = engine.get_out_triangles();\n    REQUIRE(out_triangles.rows() >= 1);\n}\n\nTEST_CASE(\"Quad\", \"[trianglelite]\")\n{\n    using namespace trianglelite;\n\n    Config config;\n    Engine engine;\n\n    config.max_area = 0.1;\n    config.verbose_level = 0;\n\n    Eigen::Matrix<Scalar, 4, 2, Eigen::RowMajor> points;\n    points << 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0;\n    engine.set_in_points(points.data(), static_cast<int>(points.rows()));\n\n    Eigen::Matrix<int, 4, 2, Eigen::RowMajor> segments;\n    segments << 0, 1, 1, 2, 2, 3, 3, 0;\n    engine.set_in_segments(segments.data(), static_cast<int>(segments.rows()));\n\n    engine.run(config);\n\n    auto out_points = engine.get_out_points();\n    REQUIRE(out_points.rows() >= 3);\n    auto out_triangles = engine.get_out_triangles();\n    REQUIRE(out_triangles.rows() >= 1);\n}\n\nTEST_CASE(\"QuadWithHole\", \"[trianglelite][hole]\")\n{\n    using namespace trianglelite;\n\n    Config config;\n    Engine engine;\n\n    config.max_area = 0.05;\n    config.verbose_level = 0;\n    config.auto_hole_detection = true;\n\n    Eigen::Matrix<Scalar, 8, 2, Eigen::RowMajor> points;\n    points << 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.2, 0.2, 0.2, 0.8, 0.8, 0.8, 0.8, 0.2;\n    engine.set_in_points(points.data(), static_cast<int>(points.rows()));\n\n    Eigen::Matrix<int, 8, 2, Eigen::RowMajor> segments;\n    segments << 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4;\n    engine.set_in_segments(segments.data(), static_cast<int>(segments.rows()));\n\n    engine.run(config);\n\n    auto out_points = engine.get_out_points();\n    auto out_edges = engine.get_out_edges();\n    auto out_triangles = engine.get_out_triangles();\n\n    const int euler = static_cast<int>(out_points.rows()) - static_cast<int>(out_edges.rows()) +\n                      static_cast<int>(out_triangles.rows());\n    REQUIRE(euler == 0);\n}\n\nTEST_CASE(\"Marker\", \"[trianglelite][marker]\")\n{\n    using namespace trianglelite;\n\n    Config config;\n    Engine engine;\n\n    std::vector<Scalar> points{0, 0, 1, 0, 0, 1};\n    std::vector<Index> segments{0, 1, 1, 2, 2, 0};\n    std::vector<Index> point_markers{4, 5, 6};\n    std::vector<Index> segment_markers{1, 2, 3};\n    engine.set_in_points(points.data(), static_cast<int>(points.size() / 2));\n    engine.set_in_segments(segments.data(), static_cast<int>(segments.size() / 2));\n    engine.set_in_point_markers(point_markers.data(), static_cast<int>(point_markers.size()));\n    engine.set_in_segment_markers(segment_markers.data(), static_cast<int>(segment_markers.size()));\n\n    config.max_area = 0.1;\n    config.verbose_level = 0;\n\n    engine.run(config);\n\n    auto out_points = engine.get_out_points();\n    auto out_edges = engine.get_out_edges();\n    auto out_segments = engine.get_out_segments();\n    auto out_triangles = engine.get_out_triangles();\n\n    REQUIRE(out_points.rows() > 3);\n    REQUIRE(out_edges.rows() > 3);\n    REQUIRE(out_segments.rows() > 3);\n    REQUIRE(out_triangles.rows() > 1);\n\n    SECTION(\"Point markers\") {\n        auto out_point_markers = engine.get_out_point_markers();\n        const size_t num_out_point_markers = out_point_markers.size();\n        REQUIRE(num_out_point_markers == out_points.rows());\n        for (size_t i=0; i<num_out_point_markers; i++) {\n            if (out_point_markers[i] == 4) {\n                REQUIRE(out_points(i, 0) == Approx(0));\n                REQUIRE(out_points(i, 1) == Approx(0));\n            } else if (out_point_markers[i] == 5) {\n                REQUIRE(out_points(i, 0) == Approx(1));\n                REQUIRE(out_points(i, 1) == Approx(0));\n            } else if (out_point_markers[i] == 6) {\n                REQUIRE(out_points(i, 0) == Approx(0));\n                REQUIRE(out_points(i, 1) == Approx(1));\n            }\n        }\n    }\n\n    SECTION(\"Edge markers\") {\n        auto edge_markers = engine.get_out_edge_markers();\n        REQUIRE(edge_markers.size() == out_edges.rows());\n\n        const size_t num_edges = out_edges.rows();\n        for (size_t i=0; i<num_edges; i++) {\n            const Index v0 = out_edges(i, 0);\n            const Index v1 = out_edges(i, 1);\n            if (edge_markers[i] == 1) {\n                REQUIRE(out_points(v0, 1) == Approx(0.0));\n                REQUIRE(out_points(v1, 1) == Approx(0.0));\n            } else if (edge_markers[i] == 2) {\n                REQUIRE(out_points.row(v0).sum() == Approx(1.0));\n                REQUIRE(out_points.row(v1).sum() == Approx(1.0));\n            } else if (edge_markers[i] == 3) {\n                REQUIRE(out_points(v0, 0) == Approx(0.0));\n                REQUIRE(out_points(v1, 0) == Approx(0.0));\n            } else {\n                REQUIRE(edge_markers[i] == 0);\n            }\n        }\n    }\n\n    SECTION(\"Segment markers\") {\n        auto segment_markers = engine.get_out_segment_markers();\n        REQUIRE(out_segments.rows() == segment_markers.size());\n    }\n}\n", "meta": {"hexsha": "1f2bb1f124e250f676c1ee0c7cad2aa1b7004533", "size": 5705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_engine.cpp", "max_stars_repo_name": "qnzhou/trianglelite", "max_stars_repo_head_hexsha": "437fdd6892143864ddc1c1848b33262c85b52cc4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2021-02-01T08:05:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T13:21:05.000Z", "max_issues_repo_path": "tests/test_engine.cpp", "max_issues_repo_name": "qnzhou/trianglelite", "max_issues_repo_head_hexsha": "437fdd6892143864ddc1c1848b33262c85b52cc4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-23T01:26:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-24T18:48:22.000Z", "max_forks_repo_path": "tests/test_engine.cpp", "max_forks_repo_name": "qnzhou/trianglelite", "max_forks_repo_head_hexsha": "437fdd6892143864ddc1c1848b33262c85b52cc4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-12T20:42:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-23T23:45:15.000Z", "avg_line_length": 32.6, "max_line_length": 100, "alphanum_fraction": 0.6024539877, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5114095358082431}}
{"text": "/* Boost libs/numeric/odeint/examples/openmp/lorenz_ensemble.cpp\r\n\r\n Copyright 2013 Karsten Ahnert\r\n Copyright 2013 Mario Mulansky\r\n Copyright 2013 Pascal Germroth\r\n\r\n Parallelized Lorenz ensembles\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 > inner_state_type;\r\ntypedef openmp_state<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 j = 0 ; j < x.size() ; j++) {\r\n            size_t offset = 0;\r\n            for(size_t i = 0 ; i < j ; i++)\r\n                offset += x[i].size();\r\n\r\n            for(size_t i = 0 ; i < x[j].size() ; i++) {\r\n                const point_type &xi = x[j][i];\r\n                point_type &dxdti = dxdt[j][i];\r\n                dxdti[0] = -sigma * (xi[0] - xi[1]);\r\n                dxdti[1] = R[offset + i] * xi[0] - xi[1] - xi[0] * xi[2];\r\n                dxdti[2] = -b * xi[2] + xi[0] * xi[1];\r\n            }\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    vector<point_type> inner(n, point_type(10, 10, 10));\r\n    state_type state;\r\n    split(inner, state);\r\n\r\n    cerr << \"openmp_state split \" << n << \" into\";\r\n    for(size_t i = 0 ; i != state.size() ; i++)\r\n        cerr << ' ' << state[i].size();\r\n    cerr << endl;\r\n\r\n    typedef runge_kutta4< state_type, double > 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    unsplit(state, inner);\r\n    std::copy( inner.begin(), inner.end(), ostream_iterator<point_type>(cout, \"\\n\") );\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "1b623a204e8342e805b2b7009dd40a95499fdafa", "size": 2555, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/openmp/lorenz_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/openmp/lorenz_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-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.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.7717391304, "max_line_length": 87, "alphanum_fraction": 0.5628180039, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.511409535808243}}
{"text": "/** ****************************************************************************\n *  @file    FaceHeadPose.cpp\n *  @brief   Face detection and recognition framework\n *  @author  Roberto Valle Fernandez\n *  @date    2015/06\n *  @copyright All rights reserved.\n *  Software developed by UPM PCR Group: http://www.dia.fi.upm.es/~pcr\n ******************************************************************************/\n\n// ----------------------- INCLUDES --------------------------------------------\n#include <FaceHeadPose.hpp>\n#include <ModernPosit.h>\n#include <boost/filesystem.hpp>\n\nnamespace upm {\n\n// -----------------------------------------------------------------------------\n//\n// Purpose and Method:\n// Inputs:\n// Outputs:\n// Dependencies:\n// Restrictions and Caveats:\n//\n// -----------------------------------------------------------------------------\ncv::Mat\nprojectAxis\n  (\n  const cv::Point3f &headpose\n  )\n{\n  cv::Mat axis = cv::Mat::eye(3,3,cv::DataType<float>::type); // [yaw (blue), pitch (green), roll (red)]\n  cv::Mat ann_axis, rot_matrix = ModernPosit::eulerToRotationMatrix(headpose);\n  rot_matrix = (cv::Mat_<float>(3,3) <<  rot_matrix.at<float>(1,2), rot_matrix.at<float>(1,1),-rot_matrix.at<float>(1,0),\n                                        -rot_matrix.at<float>(0,2),-rot_matrix.at<float>(0,1), rot_matrix.at<float>(0,0),\n                                         rot_matrix.at<float>(2,2), rot_matrix.at<float>(2,1),-rot_matrix.at<float>(2,0));\n  ann_axis = rot_matrix*axis;\n  return ann_axis;\n};\n\n// -----------------------------------------------------------------------------\n//\n// Purpose and Method:\n// Inputs:\n// Outputs:\n// Dependencies:\n// Restrictions and Caveats:\n//\n// -----------------------------------------------------------------------------\nvoid\nFaceHeadPose::show\n  (\n  const boost::shared_ptr<upm::Viewer> &viewer,\n  const std::vector<upm::FaceAnnotation> &faces,\n  const upm::FaceAnnotation &ann\n  )\n{\n  // Ground truth\n  cv::Scalar blue_color(255,0,0), green_color(0,255,0), red_color(0,0,255);\n  double length = static_cast<int>(roundf(ann.bbox.pos.height)*0.5f);\n  int thickness = MAX(static_cast<int>(roundf(ann.bbox.pos.height*0.01f)), 3);\n  cv::Mat ann_axis = projectAxis(ann.headpose) * length;\n  cv::Point mid = (ann.bbox.pos.tl() + ann.bbox.pos.br()) * 0.5;\n  viewer->line(mid.x, mid.y, mid.x+ann_axis.at<float>(1,0), mid.y-ann_axis.at<float>(0,0), thickness, blue_color);\n  viewer->line(mid.x, mid.y, mid.x+ann_axis.at<float>(1,1), mid.y-ann_axis.at<float>(0,1), thickness, green_color);\n  viewer->line(mid.x, mid.y, mid.x+ann_axis.at<float>(1,2), mid.y-ann_axis.at<float>(0,2), thickness, red_color);\n\n  // Estimated head-pose\n  cv::Scalar cyan_color(122,0,0), lime_color(0,122,0), salmon_color(0,0,122);\n  for (const FaceAnnotation &face : faces)\n  {\n    length = static_cast<int>(roundf(face.bbox.pos.height)*0.5f);\n    thickness = MAX(static_cast<int>(roundf(face.bbox.pos.height*0.01f)), 3);\n    cv::Mat face_axis = projectAxis(face.headpose) * length;\n    mid = (face.bbox.pos.tl() + face.bbox.pos.br()) * 0.5;\n    viewer->line(mid.x, mid.y, mid.x+face_axis.at<float>(1,0), mid.y-face_axis.at<float>(0,0), thickness, cyan_color);\n    viewer->line(mid.x, mid.y, mid.x+face_axis.at<float>(1,1), mid.y-face_axis.at<float>(0,1), thickness, lime_color);\n    viewer->line(mid.x, mid.y, mid.x+face_axis.at<float>(1,2), mid.y-face_axis.at<float>(0,2), thickness, salmon_color);\n  }\n};\n\n// -----------------------------------------------------------------------------\n//\n// Purpose and Method:\n// Inputs:\n// Outputs:\n// Dependencies:\n// Restrictions and Caveats:\n//\n// -----------------------------------------------------------------------------\nvoid\nFaceHeadPose::evaluate\n  (\n  boost::shared_ptr<std::ostream> output,\n  const std::vector<upm::FaceAnnotation> &faces,\n  const upm::FaceAnnotation &ann\n  )\n{\n  for (const FaceAnnotation &face : faces)\n    *output << getComponentClass() << \" \" << ann.filename << \" \" << ann.headpose << \" \" << face.headpose << std::endl;\n};\n\n// -----------------------------------------------------------------------------\n//\n// Purpose and Method:\n// Inputs:\n// Outputs:\n// Dependencies:\n// Restrictions and Caveats:\n//\n// -----------------------------------------------------------------------------\nvoid\nFaceHeadPose::save\n  (\n  const std::string dirpath,\n  const std::vector<upm::FaceAnnotation> &faces,\n  const upm::FaceAnnotation &ann\n  )\n{\n  // Save images with mean error greater than threshold\n  const float threshold = 25.0f;\n  cv::Scalar blue_color(255,0,0), green_color(0,255,0), red_color(0,0,255), cyan_color(122,0,0), lime_color(0,122,0), salmon_color(0,0,122);\n  double length = static_cast<int>(roundf(ann.bbox.pos.height)*0.5f);\n  int thickness = MAX(static_cast<int>(roundf(ann.bbox.pos.height*0.01f)), 3);\n  for (const FaceAnnotation &face : faces)\n  {\n    cv::Mat image = cv::imread(face.filename, cv::IMREAD_COLOR);\n    cv::Mat ann_axis = projectAxis(ann.headpose) * length;\n    cv::Point mid = (ann.bbox.pos.tl() + ann.bbox.pos.br()) * 0.5;\n    cv::line(image, mid, cv::Point2f(mid.x+ann_axis.at<float>(1,0), mid.y-ann_axis.at<float>(0,0)), blue_color, thickness);\n    cv::line(image, mid, cv::Point2f(mid.x+ann_axis.at<float>(1,1), mid.y-ann_axis.at<float>(0,1)), green_color, thickness);\n    cv::line(image, mid, cv::Point2f(mid.x+ann_axis.at<float>(1,2), mid.y-ann_axis.at<float>(0,2)), red_color, thickness);\n\n    length = static_cast<int>(roundf(face.bbox.pos.height)*0.5f);\n    thickness = MAX(static_cast<int>(roundf(face.bbox.pos.height*0.01f)), 3);\n    cv::Mat face_axis = projectAxis(face.headpose) * length;\n    mid = (face.bbox.pos.tl() + face.bbox.pos.br()) * 0.5;\n    cv::line(image, mid, cv::Point2f(mid.x+face_axis.at<float>(1,0), mid.y-face_axis.at<float>(0,0)), cyan_color, thickness);\n    cv::line(image, mid, cv::Point2f(mid.x+face_axis.at<float>(1,1), mid.y-face_axis.at<float>(0,1)), lime_color, thickness);\n    cv::line(image, mid, cv::Point2f(mid.x+face_axis.at<float>(1,2), mid.y-face_axis.at<float>(0,2)), salmon_color, thickness);\n\n    // Absolute head-pose error\n    float error = static_cast<float>(cv::sum(cv::abs(cv::Mat(ann.headpose-face.headpose).t()))[0]);\n    std::string text = std::to_string(error);\n    cv::putText(image, text, cv::Point(10, image.rows-10), cv::FONT_HERSHEY_SIMPLEX, 1, red_color);\n    if (error > threshold)\n    {\n      std::size_t found = face.filename.find_last_of('/');\n      std::string filepath;\n      unsigned int num = 0;\n      do\n      {\n        filepath = dirpath + std::to_string(num) + \"_\" + face.filename.substr(found+1);\n        num++;\n      }\n      while (boost::filesystem::exists(filepath));\n      cv::imwrite(filepath, image);\n    }\n  }\n};\n\n} // namespace upm\n", "meta": {"hexsha": "e021d69e859282354bf78a9b9469bcf914623a8b", "size": 6738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/FaceHeadPose.cpp", "max_stars_repo_name": "bobetocalo/faces_framework", "max_stars_repo_head_hexsha": "05f6192b574a0b79891673df480330b7d94daf7b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-09-07T05:39:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T06:59:59.000Z", "max_issues_repo_path": "src/FaceHeadPose.cpp", "max_issues_repo_name": "bobetocalo/faces_framework", "max_issues_repo_head_hexsha": "05f6192b574a0b79891673df480330b7d94daf7b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-02-12T02:23:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-12T14:48:28.000Z", "max_forks_repo_path": "src/FaceHeadPose.cpp", "max_forks_repo_name": "bobetocalo/faces_framework", "max_forks_repo_head_hexsha": "05f6192b574a0b79891673df480330b7d94daf7b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-11-12T07:58:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-21T12:50:01.000Z", "avg_line_length": 41.3374233129, "max_line_length": 140, "alphanum_fraction": 0.571682992, "num_tokens": 1820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5113470796320635}}
{"text": "#include <scitbx/lstbx/normal_equations.h>\n\n#include <boost_adaptbx/optional_conversions.h>\n\n#include <boost/python/class.hpp>\n#include <boost/python/tuple.hpp>\n#include <boost/python/return_internal_reference.hpp>\n\n\nnamespace scitbx { namespace lstbx { namespace normal_equations {\nnamespace boost_python {\n\n  template <typename FloatType>\n  struct linear_ls_wrapper\n  {\n    typedef linear_ls<FloatType> wt;\n    typedef typename wt::scalar_t scalar_t;\n    typedef typename wt::symmetric_matrix_t symmetric_matrix_t;\n    typedef typename wt::vector_t vector_t;\n\n    static void wrap(char const *name) {\n      using namespace boost::python;\n\n      boost_adaptbx::optional_conversions::to_and_from_python<\n        boost::optional<wt> >();\n\n      class_<wt>(name, no_init)\n        .def(init<int>(arg(\"n_parameters\")))\n        .def(init<symmetric_matrix_t const &, vector_t const &>(\n             (arg(\"normal_matrix\"), arg(\"right_hand_side\"))))\n        .add_property(\"n_parameters\", &wt::n_parameters)\n        .def(\"add_equation\",\n             &wt::add_equation,\n             (arg(\"right_hand_side\"), arg(\"design_matrix_row\"), arg(\"weight\")))\n        .def(\"add_equations\",\n             &wt::add_equations,\n             (arg(\"right_hand_side\"), arg(\"design_matrix\"), arg(\"weights\"),\n              arg(\"negate_right_hand_side\")=false,\n              arg(\"optimise_for_tall_matrix\")=true))\n        .def(\"reset\", &wt::reset)\n        .def(\"solve\", &wt::solve)\n        .add_property(\"solved\", &wt::solved)\n        /* We use 'def' instead of add_property for those because they may\n           throw if called on an instanced which is not solved.\n           On the Python side, an attribute lookup which may throw is a\n           source of confusion (e.g. hasattr does not work correctly for those).\n         */\n        .def(\"normal_matrix_packed_u\", &wt::normal_matrix)\n        .def(\"right_hand_side\", &wt::right_hand_side)\n        .def(\"cholesky_factor_packed_u\", &wt::cholesky_factor)\n        .def(\"solution\", &wt::solution)\n        ;\n    }\n  };\n\n  template <typename FloatType>\n  struct non_linear_ls_wrapper\n  {\n    typedef non_linear_ls<FloatType> wt;\n    typedef typename wt::scalar_t scalar_t;\n    typedef typename wt::vector_t vector_t;\n    typedef typename wt::symmetric_matrix_t symmetric_matrix_t;\n\n    static void wrap(char const *name) {\n      using namespace boost::python;\n      return_internal_reference<> rir;\n      void (wt::*add_dense_eqns)(af::const_ref<scalar_t> const &,\n                                 af::const_ref<scalar_t, af::mat_grid> const &,\n                                 af::const_ref<scalar_t> const &)\n        = &wt::add_equations;\n      void (wt::*add_sparse_eqns)(af::const_ref<scalar_t> const &,\n                                  sparse::matrix<scalar_t> const &,\n                                  af::const_ref<scalar_t> const &,\n                                  bool, bool)\n        = &wt::add_equations;\n\n      class_<wt>(name, no_init)\n        .def(init<int>(arg(\"n_parameters\")))\n        .def(init<std::size_t,\n                  scalar_t,\n                  vector_t const &,\n                  symmetric_matrix_t const &>\n             ((arg(\"n_equations\"),\n               arg(\"objective\"),\n               arg(\"opposite_of_grad_objective\"),\n               arg(\"normal_matrix\"))))\n        .add_property(\"n_parameters\", &wt::n_parameters)\n        .add_property(\"n_equations\", &wt::n_equations)\n        .add_property(\"dof\", &wt::dof)\n        .def(\"add_residual\",\n             &wt::add_residual,\n             (arg(\"residual\"), arg(\"weight\")))\n        .def(\"add_residuals\",\n             &wt::add_residuals,\n             (arg(\"residuals\"), arg(\"weights\")))\n        .def(\"add_equation\",\n             &wt::add_equation,\n             (arg(\"residual\"), arg(\"grad_residual\"), arg(\"weight\")))\n        .def(\"add_equations\",\n             add_dense_eqns,\n             (arg(\"residuals\"), arg(\"jacobian\"), arg(\"weights\")))\n        .def(\"add_equations\",\n             add_sparse_eqns,\n             (arg(\"residuals\"), arg(\"jacobian\"), arg(\"weights\"),\n             arg(\"negate_right_hand_side\")=true, arg(\"optimise_for_tall_matrix\")=true))\n        .def(\"reset\", &wt::reset)\n        /* We use 'def' instead of add_property for those to stay consistent\n           with the other wrappers in this module which can't use properties\n         */\n        .def(\"objective\", &wt::objective)\n        .def(\"chi_sq\", &wt::chi_sq)\n        .def(\"step_equations\", &wt::step_equations, rir)\n        ;\n    }\n  };\n\n\n  template <typename FloatType, template<typename> class SumOfRank1Updates>\n  struct non_linear_ls_with_separable_scale_factor_wrapper\n  {\n    typedef non_linear_ls_with_separable_scale_factor<FloatType,\n                                                      SumOfRank1Updates>\n            wt;\n    typedef typename wt::scalar_t scalar_t;\n\n    static void add_equation(wt &self,\n                             scalar_t yc, af::const_ref<scalar_t> const &grad_yc,\n                             scalar_t yo, scalar_t w)\n    {\n      self.add_equation(yc, grad_yc, yo, w);\n    }\n\n    static void wrap(std::string const &name) {\n      using namespace boost::python;\n      return_internal_reference<> rir;\n      class_<wt>(name.c_str(), no_init)\n        .def(init<int, bool>((arg(\"n_parameters\"), arg(\"normalised\")=true)))\n        .add_property(\"n_parameters\", &wt::n_parameters)\n        .add_property(\"n_equations\", &wt::n_equations)\n        .add_property(\"dof\", &wt::dof)\n        .def(\"add_residual\",\n             &wt::add_residual,\n             (arg(\"y_calc\"), arg(\"y_obs\"), arg(\"weight\")))\n        .def(\"add_equation\", add_equation,\n             (arg(\"y_calc\"), arg(\"grad_y_calc\"), arg(\"y_obs\"), arg(\"weight\")))\n        .def(\"add_equations\", &wt::add_equations,\n             (arg(\"ys_calc\"), arg(\"jacobian_y_calc\"), arg(\"ys_obs\"),\n              arg(\"weights\")))\n        .def(\"finalise\", &wt::finalise, arg(\"objective_only\")=false)\n        .add_property(\"finalised\", &wt::finalised)\n        .def(\"reset\", &wt::reset)\n        /* We use 'def' instead of add_property for those because they may\n           throw if called on an instanced which is not finalised.\n           On the Python side, an attribute lookup which may throw is a\n           source of confusion (e.g. hasattr does not work correctly for those).\n         */\n        .def(\"optimal_scale_factor\", &wt::optimal_scale_factor)\n        .def(\"sum_w_yo_sq\", &wt::sum_w_yo_sq)\n        .def(\"objective\", &wt::objective)\n        .def(\"chi_sq\", &wt::chi_sq)\n        .def(\"step_equations\", &wt::step_equations, rir)\n        .def(\"reduced_problem\", &wt::reduced_problem, rir)\n        ;\n    }\n  };\n\n  void wrap_normal_equations() {\n    linear_ls_wrapper<double>::wrap(\"linear_ls\");\n    non_linear_ls_wrapper<double>::wrap(\"non_linear_ls\");\n    std::string basename(\"non_linear_ls_with_separable_scale_factor\");\n    non_linear_ls_with_separable_scale_factor_wrapper<\n      double, matrix::sum_of_symmetric_rank_1_updates>\n      ::wrap(basename + \"__level_2_blas_impl\");\n    non_linear_ls_with_separable_scale_factor_wrapper<\n      double, matrix::rank_n_update>\n      ::wrap(basename + \"__level_3_blas_impl\");\n  }\n\n}}}}\n", "meta": {"hexsha": "138ab9d0fb2706eb76923b1da7bc74d2ba179e5d", "size": 7171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/lstbx/boost_python/normal_equations.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/lstbx/boost_python/normal_equations.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/lstbx/boost_python/normal_equations.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 39.8388888889, "max_line_length": 87, "alphanum_fraction": 0.6020080881, "num_tokens": 1740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5113470686791259}}
{"text": "#include \"debug_macros.h\"\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Robust_circumcenter_traits_3.h>\n#include <CGAL/Delaunay_triangulation_3.h>\n\n#include <CGAL/Polyhedral_surface_3.h>\n\n#include <CGAL/Surface_mesher/Standard_criteria.h>\n\n#define CGAL_C2T3_USE_POLYHEDRON\n#include <CGAL/IO/Complex_2_in_triangulation_3_file_writer.h>\n\n#include <CGAL/Surface_mesher/Point_surface_indices_oracle_visitor.h>\n\n#include \"parameters.h\"\n\n#include <CGAL/Timer.h>\n\n#include <iostream>\n#include <fstream>\n\n#include <sstream>\n\n#include <boost/tuple/tuple.hpp> // boost::tie\n\nusing boost::tie;\n\n/////////////// Types ///////////////\n\nstruct K2 : public CGAL::Exact_predicates_inexact_constructions_kernel {};\ntypedef CGAL::Robust_circumcenter_traits_3<K2>  K;\ntypedef CGAL::Complex_2_in_triangulation_vertex_base_3<K> Vb;\ntypedef CGAL::Surface_mesh_cell_base_3<K> Cb;\ntypedef CGAL::Triangulation_data_structure_3<Vb, Cb> Tds;\ntypedef CGAL::Delaunay_triangulation_3<K, Tds> Tr;\n\ntypedef K::Point_3 Point_3;\ntypedef K::Sphere_3 Sphere_3;\ntypedef K::FT FT;\n\ntypedef CGAL::Polyhedral_surface_3<K> Surface;\n\ntypedef CGAL::Surface_mesher::Refine_criterion<Tr> Criterion;\ntypedef CGAL::Surface_mesher::Standard_criteria <Criterion > Criteria;\n\ntypedef CGAL::Complex_2_in_triangulation_3<Tr> C2t3;\n\ntypedef CGAL::Surface_mesher::Polyhedral_oracle<Surface> Surface_mesh_traits;\n\ntypedef Surface_mesh_traits::Construct_initial_points Initial_points;\n\ntypedef CGAL::Simple_cartesian<double> Simple_kernel;\ntypedef Simple_kernel::Iso_rectangle_2 Rectangle_2;\ntypedef Simple_kernel::Segment_2 Segment_2;\ntypedef Simple_kernel::Point_2 Point_2;\n\n/// Global variables\nstd::ostream *out = 0;\nstd::string filename = std::string();\nstd::string function_name = \"\";\nchar* argv0 = \"\";\n\nvoid usage(std::string error = \"\")\n{\n  if( error != \"\" )\n    std:: cerr << \"Error: \" << error << std::endl;\n  std::cerr << \"Usage:\\n  \"\n            << argv0\n            << \" -f function_name\"\n            << \" [output_file.off|-]\\n\"\n            << \"If output_file.off is '-', outputs to standard out.\\n\"\n            << \"-f define the OFF file to remesh.\\n\";\n  for(String_options::iterator it = string_options.begin();\n      it != string_options.end();\n      ++it)\n    std::cerr << \"--\" << it->first << \" default value is \\\"\"\n\t      << it->second << \"\\\".\\n\";\n  for(Double_options::iterator it = double_options.begin();\n      it != double_options.end();\n      ++it)\n    std::cerr << \"--\" << it->first << \" default value is \"\n\t      << it->second << \".\\n\";\n  exit(EXIT_FAILURE);\n}\n\nstd::pair<std::ostream*, const bool>\nopen_file_for_writing(std::string filename,\n                      std::string display_string = \"Writing to \")\n{\n  if( filename != \"\")\n  {\n    if( filename == \"-\" )\n    {\n      std::cerr << display_string << \"standard out...\\n\";\n      return std::make_pair(&std::cout, false);\n    }\n    else\n    {\n      std::ofstream* result = new std::ofstream(filename.c_str());\n      if( *result )\n      {\n        std::cerr << display_string << \"file \" << filename << \"...\\n\";\n        return std::make_pair(result, true);\n      }\n      else\n      {\n        delete result;\n        std::cerr << \"Error: cannot create \" << filename << \"\\n\";\n        usage();\n        return std::pair<std::ostream*, bool>(0, false);\n      }\n    }\n  }\n  else\n    return std::pair<std::ostream*, bool>(0, false);\n}\n\nvoid parse_argv(int argc, char** argv, int extra_args = 0)\n{\n  if (argc >=(2 + extra_args))\n    {\n      std::string arg = argv[1+extra_args];\n      if( arg == \"-h\" || arg == \"--help\")\n        usage();\n      else if( arg == \"-f\" )\n        {\n          if( argc < (3 + extra_args) )\n            usage(\"-f must be followed by a function name!\");\n          function_name = argv[2 + extra_args];\n          parse_argv(argc, argv, extra_args + 2);\n        }\n      else if( arg.substr(0, 2) == \"--\" )\n\t{\n\t  Double_options::iterator opt_it =\n\t    double_options.find(arg.substr(2, arg.length()-2));\n\t  if( opt_it != double_options.end() )\n\t    {\n\t      if( argc < (3 + extra_args) )\n\t\tusage((arg + \" must be followed by a double!\").c_str());\n\t      std::stringstream s;\n\t      double val;\n\t      s << argv[extra_args + 2];\n\t      s >> val;\n\t      if( !s )\n\t\tusage((\"Bad double after \" + arg + \"!\").c_str());\n\t      opt_it->second = val;\n\t      parse_argv(argc, argv, extra_args + 2);\n\t    }\n\t  else\n          {\n            String_options::iterator opt_it =\n                string_options.find(arg.substr(2, arg.length()-2));\n            if( opt_it != string_options.end() )\n            {\n              if( argc < (3 + extra_args) )\n                usage((arg + \" must be followed by a string!\").c_str());\n              std::string s = argv[extra_args + 2];\n              opt_it->second = s;\n              parse_argv(argc, argv, extra_args + 2);\n            }\n            else\n              usage((\"Invalid option \" + arg).c_str());\n          }\n\t}\n      else\n\t{\n\t  filename = argv[1+extra_args];\n\t  parse_argv(argc, argv, extra_args + 1);\n\t}\n    }\n}\n\n/////////////// Main function ///////////////\n\nint main(int argc, char **argv) {\n  argv0 = argv[0];\n\n  usage_ptr = &usage;\n\n  init_parameters();\n\n  parse_argv(argc, argv);\n\n  if( function_name == \"\" )\n    usage(\"Empty input file name\");\n\n  std::ifstream surface_ifs(function_name.c_str());\n  Surface surface(surface_ifs);\n  surface_ifs.close();\n\n  std::cerr << \"Surface bounding box: \" << surface.bbox() << \"\\n\";\n\n  // 2D-complex in 3D-Delaunay triangulation\n  Tr tr;\n  C2t3 c2t3(tr);\n\n  CGAL::Timer timer;\n\n  bool need_delete = false;\n  std::ostream* out = 0;\n\n  Surface_mesh_traits surface_mesh_traits;\n\n  // Initial point sample\n  std::string read_initial_points = get_string_option(\"read_initial_points\");\n  if( read_initial_points != \"\")\n  {\n    std::ifstream in( read_initial_points.c_str() );\n    int n;\n    in >> n;\n    CGAL_assertion(in);\n    while( !in.eof() )\n      {\n\tPoint_3 p;\n\tif(in >> p)\n\t  {\n\t    tr.insert(p);\n\t    --n;\n\t  }\n      }\n    CGAL_assertion( n == 0 );\n    double_options[\"number_of_initial_points\"] = 0;\n  }\n  else\n  {\n    const int number_of_initial_points =\n      static_cast<int>(get_double_option(\"number_of_initial_points\"));\n\n    std::vector<Point_3> initial_point_sample;\n    initial_point_sample.reserve(number_of_initial_points);\n\n    Initial_points get_initial_points =\n      surface_mesh_traits.construct_initial_points_object();\n\n    get_initial_points(surface,\n                       std::back_inserter(initial_point_sample),\n                       number_of_initial_points);\n\n    tie(out, need_delete) =\n      open_file_for_writing(get_string_option(\"dump_of_initial_points\"),\n                            \"Writing initial points to \");\n    if( out )\n    {\n      *out << initial_point_sample.size() << \"\\n\";\n      for(std::vector<Point_3>::const_iterator it =\n            initial_point_sample.begin();\n          it != initial_point_sample.end();\n          ++it)\n        *out << *it <<\"\\n\";\n      if(need_delete)\n        delete out;\n    }\n    tr.insert (initial_point_sample.begin(), initial_point_sample.end());\n  }\n\n  // Meshing criteria\n  CGAL::Surface_mesher::Curvature_size_criterion<Tr>\n    curvature_size_criterion (get_double_option(\"distance_bound\"));\n  CGAL::Surface_mesher::Uniform_size_criterion<Tr>\n    uniform_size_criterion (get_double_option(\"radius_bound\"));\n  CGAL::Surface_mesher::Aspect_ratio_criterion<Tr>\n    aspect_ratio_criterion (get_double_option(\"angle_bound\"));\n\n  std::vector<Criterion*> criterion_vector;\n  criterion_vector.push_back(&aspect_ratio_criterion);\n  criterion_vector.push_back(&uniform_size_criterion);\n  criterion_vector.push_back(&curvature_size_criterion);\n  Criteria criteria (criterion_vector);\n\n  std::cerr << \"\\nInitial number of points: \" << tr.number_of_vertices()\n            << std::endl;\n\n\n  // Surface meshing\n\n  timer.start();\n  make_surface_mesh(c2t3,\n                    surface,\n                    criteria,\n                    CGAL::Manifold_with_boundary_tag(),\n                    0);\n  timer.stop();\n  std::cerr << \"\\nFinal number of points: \" << tr.number_of_vertices()\n            << std::endl\n            << \"Total time: \" << timer.time() << std::endl;\n\n  tie(out, need_delete) =\n    open_file_for_writing(filename,\n                          \"Writing finale surface off to \");\n  if( out )\n  {\n    CGAL::output_surface_facets_to_off(*out, c2t3);\n    if(need_delete)\n      delete out;\n  }\n  std::cerr << \" done\\n\";\n\n#ifdef CGAL_SURFACE_MESHER_TEST_OPTIONS\n  check_all_options_have_been_used();\n#endif\n}\n", "meta": {"hexsha": "28bb5baad037c7db506d3f207d1ed1d209dc8f79", "size": 8530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Surface_mesher/demo/Surface_mesher/polyhedron_remesher.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/Surface_mesher/demo/Surface_mesher/polyhedron_remesher.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/Surface_mesher/demo/Surface_mesher/polyhedron_remesher.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": 28.2450331126, "max_line_length": 77, "alphanum_fraction": 0.6196951934, "num_tokens": 2178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5113470686791259}}
{"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_ref_snip6\r\n\r\n#include <boost/math/distributions/negative_binomial.hpp>\r\n\r\nusing namespace boost::math;\r\n\r\n// Lower quantile rounded down:\r\ndouble x = quantile(negative_binomial(20, 0.3), 0.05);\r\n// Upper quantile rounded up:\r\ndouble y = quantile(complement(negative_binomial(20, 0.3), 0.05));\r\n\r\n//]\r\n\r\n#include <iostream>\r\n\r\nint main()\r\n{\r\n   std::cout << x << \" \" << y << std::endl;\r\n}\r\n", "meta": {"hexsha": "d94fa70db4d266bf1a52a1a294969f407788e009", "size": 766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/policy_ref_snip6.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_ref_snip6.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_ref_snip6.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": 27.3571428571, "max_line_length": 69, "alphanum_fraction": 0.6906005222, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5113470680045978}}
{"text": "//==================================================================================================\n/*\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n*/\n//==================================================================================================\n#include <eve/module/core.hpp>\n#include <eve/module/bessel.hpp>\n#include <cmath>\n#include <boost/math/special_functions/bessel.hpp>\n\nint main()\n{\n  EVE_VALUE mid = sizeof(EVE_VALUE) == 4 ? 2 : 5;\n  {\n    auto lmin = EVE_VALUE(0);\n    auto lmax = EVE_VALUE(mid);\n\n    auto arg0 = eve::bench::random_<EVE_VALUE>(lmin,lmax);\n    auto stdy0 = [](auto x){return std::cyl_neumann(0, x);};\n    auto boosty0= [](auto x){return boost::math::cyl_neumann(0, x);};\n    eve::bench::experiment xp;\n    run<EVE_TYPE> (EVE_NAME(cyl_bessel_y0_small) , xp, eve::cyl_bessel_y0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(cyl_bessel_y0_small) , xp, eve::cyl_bessel_y0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(stdy0_small) , xp, stdy0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(boosty0_small), xp, boosty0 , arg0);\n  }\n  {\n    auto lmin = EVE_VALUE(mid);\n    auto lmax = EVE_VALUE(8);\n\n    auto arg0 = eve::bench::random_<EVE_VALUE>(lmin,lmax);\n    auto stdy0 = [](auto x){return std::cyl_neumann(0, x);};\n    auto boosty0= [](auto x){return boost::math::cyl_neumann(0, x);};\n    eve::bench::experiment xp;\n    run<EVE_TYPE> (EVE_NAME(cyl_bessel_y0_medium) , xp, eve::cyl_bessel_y0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(cyl_bessel_y0_medium) , xp, eve::cyl_bessel_y0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(stdy0_medium) , xp, stdy0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(boosty0_medium), xp, boosty0 , arg0);\n  }\n  {\n    auto lmin = EVE_VALUE(8);\n    auto lmax = EVE_VALUE(10000);\n\n    auto arg0 = eve::bench::random_<EVE_VALUE>(lmin,lmax);\n    auto stdy0 = [](auto x){return std::cyl_neumann(0, x);};\n    auto boosty0= [](auto x){return boost::math::cyl_neumann(0, x);};\n    eve::bench::experiment xp;\n    run<EVE_TYPE> (EVE_NAME(cyl_bessel_y0_large) , xp, eve::cyl_bessel_y0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(cyl_bessel_y0_large) , xp, eve::cyl_bessel_y0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(stdy0_large) , xp, stdy0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(boosty0_large), xp, boosty0 , arg0);\n  }\n  {\n    auto lmin = EVE_VALUE(0);\n    auto lmax = EVE_VALUE(11);\n\n    auto arg0 = eve::bench::random_<EVE_VALUE>(lmin,lmax);\n    auto stdy0 = [](auto x){return std::cyl_neumann(0, x);};\n    auto boosty0= [](auto x){return boost::math::cyl_neumann(0, x);};\n    eve::bench::experiment xp;\n    run<EVE_TYPE> (EVE_NAME(cyl_bessel_y0_mixed) , xp, eve::cyl_bessel_y0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(cyl_bessel_y0_mixed) , xp, eve::cyl_bessel_y0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(stdy0_mixed) , xp, stdy0 , arg0);\n    run<EVE_VALUE>(EVE_NAME(boosty0_mixed), xp, boosty0 , arg0);\n  }\n}\n", "meta": {"hexsha": "2ebbf5b33e7839824db7aa7bedd2f7ee90d578b6", "size": 2860, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmarks/module/bessel/cyl_bessel_y0/regular/cyl_bessel_y0.hpp", "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": "benchmarks/module/bessel/cyl_bessel_y0/regular/cyl_bessel_y0.hpp", "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": "benchmarks/module/bessel/cyl_bessel_y0/regular/cyl_bessel_y0.hpp", "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": 41.4492753623, "max_line_length": 100, "alphanum_fraction": 0.620979021, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5113470625281292}}
{"text": "#define BOOST_TEST_MODULE\n#include <boost/test/unit_test.hpp>\n#include <util/test_macros.hpp>\n#include <logger/logger.hpp>\n#include <sframe/integer_pack.hpp>\n#include <serialization/serialization_includes.hpp>\nusing namespace turi;\nusing namespace integer_pack;\nstruct integer_pack_test {\n public:\n  void test_variable_code() {\n    for (size_t shift = 0; shift < 64; shift += 8) {\n      for (uint64_t i = 0; i < 256; ++i) {\n        oarchive oarc;\n        variable_encode(oarc, i << shift);\n        uint64_t j;\n        iarchive iarc(oarc.buf, oarc.off);\n        variable_decode(iarc, j);\n        TS_ASSERT_EQUALS(oarc.off, iarc.off);\n        free(oarc.buf);\n        TS_ASSERT_EQUALS(i << shift, j);\n      }\n    }\n  }\n  void test_pack() {\n    {\n      size_t len = 8;\n      uint64_t in[8] = {19,20,21,22,23,24,25,26};\n      uint64_t out[8];\n      oarchive oarc;\n      frame_of_reference_encode_128(in, 8, oarc);\n\n      iarchive iarc(oarc.buf, oarc.off);\n      frame_of_reference_decode_128(iarc, 8, out);\n      TS_ASSERT_EQUALS(oarc.off, iarc.off);\n      free(oarc.buf);\n\n      for (size_t i = 0;i < len; ++i) {\n        TS_ASSERT_EQUALS(in[i], out[i]);\n      }\n    }\n    // simple cases\n    for (size_t mod = 1; mod < 63; ++mod) {\n      for (size_t len = 0; len <= 128; ++len) {\n        uint64_t in[len];\n        uint64_t out[len];\n        for (size_t i = 0;i < len; ++i) {\n          if (mod == 0) {\n            in[i] = 0;\n          } else {\n            in[i] = (i % mod) & (1 << (mod - 1));\n          }\n        }\n        oarchive oarc;\n        frame_of_reference_encode_128(in, len, oarc);\n\n        iarchive iarc(oarc.buf, oarc.off);\n        frame_of_reference_decode_128(iarc, len, out);\n        TS_ASSERT_EQUALS(oarc.off, iarc.off);\n        free(oarc.buf);\n\n        for (size_t i = 0;i < len; ++i) {\n          if (in[i] != out[i]) std::cout << mod << \" \" << len << \" \" << i << \"\\n\";\n          TS_ASSERT_EQUALS(in[i], out[i]);\n        }\n      }\n    }\n    \n    // harder cases\n    for (size_t multiplier = 1; multiplier < 63; ++multiplier) {\n      for (size_t shift = 1; shift < 63; ++shift) {\n        size_t len = 128;\n        uint64_t in[len];\n        uint64_t out[len];\n        for (size_t i = 0;i < len; ++i) {\n          in[i] = shift + (multiplier * i);\n        }\n        oarchive oarc;\n        frame_of_reference_encode_128(in, len, oarc);\n\n        iarchive iarc(oarc.buf, oarc.off);\n        frame_of_reference_decode_128(iarc, len, out);\n        TS_ASSERT_EQUALS(oarc.off, iarc.off);\n        free(oarc.buf);\n\n        for (size_t i = 0;i < len; ++i) {\n          TS_ASSERT_EQUALS(in[i], out[i]);\n        }\n      }\n      for (size_t mod = 1; mod < 63; ++mod) {\n        size_t len = 128;\n        uint64_t in[len];\n        uint64_t out[len];\n        for (size_t i = 0;i < len; ++i) {\n          in[i] = (multiplier * i) % mod;\n        }\n        oarchive oarc;\n        frame_of_reference_encode_128(in, len, oarc);\n\n        iarchive iarc(oarc.buf, oarc.off);\n        frame_of_reference_decode_128(iarc, len, out);\n        TS_ASSERT_EQUALS(oarc.off, iarc.off);\n        free(oarc.buf);\n\n        for (size_t i = 0;i < len; ++i) {\n          TS_ASSERT_EQUALS(in[i], out[i]);\n        }\n      }\n    }\n    \n    // integer boundary cases\n    int64_t maxint = std::numeric_limits<int64_t>::max() >> 4;\n    for (size_t multiplier = maxint; multiplier < maxint; ++multiplier) {\n      size_t len = 128;\n      uint64_t in[len];\n      uint64_t out[len];\n      for (size_t i = 0;i < len; ++i) {\n        in[i] = (multiplier * i);\n      }\n      oarchive oarc;\n      frame_of_reference_encode_128(in, len, oarc);\n\n      iarchive iarc(oarc.buf, oarc.off);\n      frame_of_reference_decode_128(iarc, len, out);\n      TS_ASSERT_EQUALS(oarc.off, iarc.off);\n      free(oarc.buf);\n\n      for (size_t i = 0;i < len; ++i) {\n        TS_ASSERT_EQUALS(in[i], out[i]);\n      }\n    }\n  }\n  void test_shift_encode() {\n    int64_t maxint = std::numeric_limits<int64_t>::max();\n    int64_t minint = std::numeric_limits<int64_t>::min();\n    for (int64_t i = maxint - 256; i < maxint; ++i) {\n      uint64_t j = shifted_integer_encode(i);\n      int64_t i2 = shifted_integer_decode(j);\n      TS_ASSERT_EQUALS(i, i2);\n    }\n    for (int64_t i = minint; i < minint + 256; ++i) {\n      uint64_t j = shifted_integer_encode(i);\n      int64_t i2 = shifted_integer_decode(j);\n      TS_ASSERT_EQUALS(i, i2);\n    }\n    for (int64_t i = -256; i < 256; ++i) {\n      uint64_t j = shifted_integer_encode(i);\n      int64_t i2 = shifted_integer_decode(j);\n      TS_ASSERT_EQUALS(i, i2);\n    }\n  }\n};\n\nBOOST_FIXTURE_TEST_SUITE(_integer_pack_test, integer_pack_test)\nBOOST_AUTO_TEST_CASE(test_variable_code) {\n  integer_pack_test::test_variable_code();\n}\nBOOST_AUTO_TEST_CASE(test_pack) {\n  integer_pack_test::test_pack();\n}\nBOOST_AUTO_TEST_CASE(test_shift_encode) {\n  integer_pack_test::test_shift_encode();\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4db9062dc0936f58c9b2c946a2bc3f5aae30e824", "size": 4880, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/sframe/integer_pack_test.cxx", "max_stars_repo_name": "TimothyRHuertas/turicreate", "max_stars_repo_head_hexsha": "afa00bee56d168190c6f122e14c9fbc6656b4e97", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T19:51:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-16T19:51:18.000Z", "max_issues_repo_path": "test/sframe/integer_pack_test.cxx", "max_issues_repo_name": "tashby/turicreate", "max_issues_repo_head_hexsha": "7f07ce795833d0c56c72b3a1fb9339bed6d178d1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:18:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:39:44.000Z", "max_forks_repo_path": "test/sframe/integer_pack_test.cxx", "max_forks_repo_name": "tashby/turicreate", "max_forks_repo_head_hexsha": "7f07ce795833d0c56c72b3a1fb9339bed6d178d1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-21T17:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T17:46:28.000Z", "avg_line_length": 29.5757575758, "max_line_length": 82, "alphanum_fraction": 0.5704918033, "num_tokens": 1432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5113470570516603}}
{"text": "/***\n *  File: BDE_score.hpp\n *  Created: June 4, 2012\n *\n *  Author: Olga Nikolova <olga.nikolova@gmail.com>\n */\n\n#ifndef BDE_SCORE_HPP\n#define BDE_SCORE_HPP\n\n#include <jaz/math_add.hpp>\n#include <jaz/plain_array.hpp>\n#include <algorithm>\n#include <vector>\n#include <cmath> // this doesn't seem to work\n#include <boost/math/special_functions/gamma.hpp>\n\nclass BDE_score {\npublic:\n\t/**\n\t */\n\ttypedef unsigned int index_type;\n\t\n\t/**\n\t */\n\ttypedef double value_type;\n\t\n\t\n\tBDE_score(unsigned int n, unsigned int m,\n\t\t\t  const jaz::plain_array<unsigned char>& D)\n    : n_(n), m_(m), D_(D), ess_(1.0) {\n\t\t\n\t\tr_ = *std::max_element(D.begin(), D.end()) + 1;\n\t\tpx_.resize(r_, 0);\n\t\tinit_bde_x_();\n\t\tdata_bins_.resize(m_);\n\t\tdata_index_.resize(m_);\n\t} // BDE_score\n\t\n\t\n\tvalue_type operator()(index_type xi) { return bde_x_[xi]; }\n\t\n\ttemplate <typename Iter>\n\tvalue_type operator()(index_type xi, Iter first, Iter last) {\n\t\tif (first == last) {\n\t\t\treturn bde_x_[xi];\n\t\t}\n\t\t\n\t\tif (check_key_(first, last) == false) {\n\t\t\tgenerate_index_(first, last);\t\t\t\n\t\t} // if\n\t\t\n\t\tunsigned int k = std::distance(first, last);\n\t\tdouble qi = static_cast<double>(pow(r_, k));\n\t\t\n\t\t// Set priors\n\t\tdouble ess_qi = ess_ / qi;\n\t\tdouble ess_riqi = ess_ / ( qi * static_cast<double>(r_) );\n\t\t\n\t\t// Compute commonly used Gamma-fn. values\n\t\tdouble lg_ess_qi = boost::math::lgamma(ess_qi);\n\t\tdouble lg_ess_riqi = boost::math::lgamma(ess_riqi);\n\t\t\n\t\t// compute internal sum\n\t\tint pos = -1;\n\t\tconst unsigned char* tab = D_.begin() + xi * m_;\n\t\t\n\t\tdouble H = 0.0;\n\t\tS_ = 0.0;\n\n\t\tpx_.zero();\n\t\t\n\t\tfor (unsigned int i = 0; i < m_; ++i) {\n\t\t\tpx_[tab[data_index_[i].second]]++;\n\t\t\tif (data_bins_[i] == true) {\n\t\t\t\t// p(Pa)\n\t\t\t\tdouble pa_cnt = i - pos; // Nij\n\t\t\t\t//double p_pa = pa_cnt / m_;\n\t\t\t\t\n\t\t\t\tH = 0.0;\n\t\t\t\tfor (unsigned char j = 0; j < r_; ++j) {\n\t\t\t\t\tif (px_[j] != 0) {\n\t\t\t\t\t\t// p(x|Pa)\n\t\t\t\t\t\t//double p_xpa = static_cast<double>(px_[j]) / pa_cnt;\n\t\t\t\t\t\tdouble p_xpa = static_cast<double>(px_[j]); // Nijk\n\t\t\t\t\t\t//\t    H += p_pa * p_xpa * log2(p_xpa);\n\t\t\t\t\t\tH += boost::math::lgamma( p_xpa + ess_riqi ) - lg_ess_riqi;\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t} // for j\n\t\t\t\t\n\t\t\t\tS_ += lg_ess_qi - boost::math::lgamma( pa_cnt + ess_qi ) + H;\t\n\n\t\t\t\t//std::cout<< \"S( \" << xi << \",{ \";\n\t\t\t\t//for(unsigned int ii = 0; ii < k; ii++)\n\t\t\t\t//  std::cout << pa_[ii] << \", \";\n\t\t\t\t//std::cout << \"}) = \" << lg_ess_qi - boost::math::lgamma( pa_cnt + ess_qi ) << \" + \" << H << std::endl;\n\t\t\t\t\n\t\t\t\tpx_.zero();\n\t\t\t\tpos = i;\n\t\t\t} // if\n\t\t} // for i\n\t\t\n\t\treturn ((-1)*S_);\n\t} // operator()\n\t\n\t\nprivate:\n\ttemplate <typename Iter> bool check_key_(Iter first, Iter last) {\n\t\tunsigned int k = std::distance(first, last);\n\t\tif (k != pa_.size()) return false;\n\t\tfor (unsigned int i = 0; i < k; ++i) if (first[i] != pa_[i]) return false;\n\t\treturn true;\n\t} // check_key_\n\t\n\tvoid init_bde_x_() {\n\t\t//    mdl_x_.resize(n_, logn_ + hlogm_ * (r_ - 1));\n\t\tbde_x_.resize(n_, 0);\n\t\tconst unsigned char* tab = D_.begin();\n\t\t\n\t\tdouble ess_ri = ess_ /static_cast<double>(r_);\n\t\tdouble lg_ess_ri = boost::math::lgamma( ess_ri );\n\t\t\n\t\t//std::cout<< \"ess_=\" << ess_ << \" ess_ri = \" << ess_ri << \" Gamma(ess_/ri) = \" <<  lg_ess_ri << std::endl;\n\t\t\n\t\tfor (unsigned int i = 0; i < n_; ++i) {\n\t\t\tpx_.zero();\n\t\t\tdouble H = 0.0;\n\t\t\tfor (unsigned int j = 0; j < m_; ++j) px_[tab[j]]++;\n\t\t\tfor (unsigned int j = 0; j < r_; ++j) {\n\t\t\t\tif (px_[j] != 0) {\n\t\t\t\t\t//\t  double pi = static_cast<double>(px_[j]) / m_;\n\t\t\t\t\tdouble pi = static_cast<double>(px_[j]); // Nijk\n\t\t\t\t\t//std::cout << \"N_i=\" << i << \",k=\" << j << \" == \" << pi << \"(Nijk)\" << std::endl;\n\t\t\t\t\t//H += pi * log2(pi);\n\t\t\t\t\t//std::cout << \"log(Gamma(Nijk + alpha/ri)) = \" <<  boost::math::lgamma(pi + ess_ri ) << std::endl;\n\t\t\t\t\t//std::cout << \"log(Gamma(alpha/ri)) = \" <<  boost::math::lgamma( ess_ri ) << std::endl;\n\t\t\t\t\t\n\t\t\t\t\tH += boost::math::lgamma(pi + ess_ri ) - lg_ess_ri ;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbde_x_[i] = (-1)*(boost::math::lgamma(ess_) - boost::math::lgamma( static_cast<double>(m_) + ess_) + H);\n\t\t\t//std::cout << \"BDe(\" << i << \", {}) = \" <<   boost::math::lgamma(ess_) - boost::math::lgamma( static_cast<double>(m_) + ess_) << \" + \" << H << \" = \"   << bde_x_[i] << std::endl;\n\t\t\ttab += m_;\n\t\t}\n\t} // init_mdl_x_\n\t\n\t\n\ttypedef std::vector<char> key_t;\n\ttypedef std::pair<key_t, unsigned int> data_index_t;\n\t\n\tstruct data_index_lt_ {\n\t\tbool operator()(const data_index_t& lhs, const data_index_t& rhs) {\n\t\t\treturn lhs.first < rhs.first;\n\t\t}\n\t}; // struct data_index_lt_\n\t\n\t// index of D for given set of parents\n\tstd::vector<bool> data_bins_;\n\tstd::vector<data_index_t> data_index_;\n\t\n\ttemplate <typename Iter> void generate_index_(Iter first, Iter last) {\n\t\t// store new parents set\n\t\tunsigned int k = std::distance(first, last);\n\t\t\n\t\tpa_.resize(k);\n\t\tstd::copy(first, last, pa_.begin());\n\t\t\n\t\t// prepare index data\n\t\tfor (unsigned int i = 0; i < m_; ++i) {\n\t\t\tdata_bins_[i] = false;\n\t\t\tdata_index_[i].first.resize(k);\n\t\t\tdata_index_[i].second = i;\n\t\t}\n\t\t\n\t\t// generate index\n\t\tfor (unsigned int i = 0; i < k; ++i) {\n\t\t\tconst unsigned char* tab = D_.begin() + pa_[i] * m_;\n\t\t\tfor (unsigned int j = 0; j < m_; ++j) data_index_[j].first[i] = tab[j];\n\t\t}\n\t\t\n\t\tstd::sort(data_index_.begin(), data_index_.end(), data_index_lt_());\n\t\t\n\t\t// find bins boundaries\n\t\tkey_t key = data_index_[0].first;\n\t\t\n\t\tfor (unsigned int i = 0; i < m_; ++i) {\n\t\t\tif (key < data_index_[i].first) {\n\t\t\t\tkey = data_index_[i].first;\n\t\t\t\tdata_bins_[i - 1] = true;\n\t\t\t}\n\t\t}\n\t\t\n\t\tdata_bins_[m_ - 1] = true;\n\t} // generate_index_\n\t\n\tunsigned int n_;\n\tunsigned int m_;\n\t\n\tconst jaz::plain_array<unsigned char>& D_;\n\t\n\tunsigned int r_;\n\t\n\tjaz::plain_array<unsigned int> px_;\n\t\n\tdouble S_; \n\tdouble ess_;\n\t\n\t// BDE score of x with no parents\n\tjaz::plain_array<double> bde_x_;\n\t\n\t// set of parents\n\tstd::vector<unsigned int> pa_;\n\t\n}; // class MDL_score\n\n#endif // MDL_SCORE_HPP\n", "meta": {"hexsha": "2b9ba3b0fb963fd9907a2b462f450493769ba0d6", "size": 5805, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/BDe_score.hpp", "max_stars_repo_name": "srirampc/parabayl", "max_stars_repo_head_hexsha": "883f6b2e772a3646f3dc9689f9e598fc596548b5", "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/BDe_score.hpp", "max_issues_repo_name": "srirampc/parabayl", "max_issues_repo_head_hexsha": "883f6b2e772a3646f3dc9689f9e598fc596548b5", "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/BDe_score.hpp", "max_forks_repo_name": "srirampc/parabayl", "max_forks_repo_head_hexsha": "883f6b2e772a3646f3dc9689f9e598fc596548b5", "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.628440367, "max_line_length": 181, "alphanum_fraction": 0.579672696, "num_tokens": 1996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5113321498683459}}
{"text": "#include <vector>\n#include <cmath>\n#include <Eigen/Core>\n\n#include \"ihgp/Matern32model.hpp\"\n\nMatern32model::Matern32model()\n{\n    magnSigma2 = 1.0;\n    lengthScale = 1.0;\n    sigma2 = 1.0;\n    Matern32model::updateModel();\n}\n\nvoid Matern32model::updateModel()\n{\n    // Model matrices for Matern v=3/2\n    double lambda = sqrt(3.0)/lengthScale;\n    F.setZero(2,2); Pinf.setZero(2,2); H.setZero(1,2);\n    F << 0.0, 1.0, -lambda*lambda, -2*lambda;\n    Pinf << magnSigma2, 0.0, 0.0, magnSigma2*lambda*lambda;\n    H << 1.0, 0.0;\n    R = sigma2;\n    \n    // Derivatives dF\n    dF.clear();\n    dF.push_back(Eigen::MatrixXd::Zero(2,2));\n    dF.push_back(Eigen::MatrixXd::Zero(2,2));\n    Eigen::MatrixXd foo(2,2);\n    foo << 0, 0, 6/lengthScale/lengthScale/lengthScale, 2*lambda/lengthScale;\n    dF.push_back(foo);\n    \n    // Derivatives dPinf\n    dPinf.clear();\n    dPinf.push_back(Eigen::MatrixXd::Zero(2,2));\n    foo << 1.0, 0, 0, 3.0/lengthScale/lengthScale;\n    dPinf.push_back(foo);\n    foo << 0, 0, 0,-6*magnSigma2/lengthScale/lengthScale/lengthScale;\n    dPinf.push_back(foo);\n    \n    // Derivatives dR\n    dR.clear();\n    dR.push_back(1.0);\n    dR.push_back(0.0);\n    dR.push_back(0.0);\n}\n\nvoid Matern32model::setMagnSigma2(const double &val)\n{\n    magnSigma2 = val;\n    Matern32model::updateModel();\n}\n\nvoid Matern32model::setLengthScale(const double &val)\n{\n    lengthScale = val;\n    Matern32model::updateModel();\n}\n\nvoid Matern32model::setSigma2(const double &val)\n{\n    sigma2 = val;\n    Matern32model::updateModel();\n}\n\nMatrixXd Matern32model::getF()\n{\n    return F;\n}\n\nMatrixXd Matern32model::getPinf()\n{\n    return Pinf;\n}\n\nMatrixXd Matern32model::getH()\n{\n    return H;\n}\n\ndouble Matern32model::getR()\n{\n    return R;\n}\n\nvector< MatrixXd > Matern32model::getdF()\n{\n   return dF;\n}\n\nvector< MatrixXd > Matern32model::getdPinf()\n{\n    return dPinf;\n}\n\nvector< double > Matern32model::getdR()\n{\n    return dR;\n}\n\ndouble Matern32model::getMagnSigma2()\n{\n    return magnSigma2;\n}\n\ndouble Matern32model::getLengthScale()\n{\n    return lengthScale;\n}\n\ndouble Matern32model::getSigma2()\n{\n    return sigma2;\n}\n\n\n", "meta": {"hexsha": "0388f33d88cad51c4daa0998d7b2c0c933c3d95a", "size": 2114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ihgp/Matern32model.cpp", "max_stars_repo_name": "MLCS-Yonsei/multiple-object-tracking-lidar", "max_stars_repo_head_hexsha": "b76f6892a0c97a28d946eef66ccd84712321f28b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T06:33:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T06:33:03.000Z", "max_issues_repo_path": "src/ihgp/Matern32model.cpp", "max_issues_repo_name": "MLCS-Yonsei/multiple-object-tracking-lidar", "max_issues_repo_head_hexsha": "b76f6892a0c97a28d946eef66ccd84712321f28b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ihgp/Matern32model.cpp", "max_forks_repo_name": "MLCS-Yonsei/multiple-object-tracking-lidar", "max_forks_repo_head_hexsha": "b76f6892a0c97a28d946eef66ccd84712321f28b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T10:52:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T13:18:32.000Z", "avg_line_length": 18.0683760684, "max_line_length": 77, "alphanum_fraction": 0.6504257332, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5113321453561969}}
{"text": "// This file is part of KWIVER, and is distributed under the\n// OSI-approved BSD 3-Clause License. See top-level LICENSE file or\n// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.\n\n#include \"transfer_bbox_with_depth_map.h\"\n\n#include <math.h>\n#include <assert.h>\n#include <tuple>\n#include <iostream>\n#include <sstream>\n#include <vital/algo/image_io.h>\n#include <vital/io/camera_io.h>\n#include <vital/config/config_difference.h>\n#include <vital/util/string.h>\n#include <Eigen/Core>\n\nusing namespace kwiver::vital;\n\nnamespace kwiver {\nnamespace arrows {\nnamespace core {\n\n// ---------------------------------------------------------------------------\nint\nnearest_index(int max, double value)\n{\n  if (abs(value - 0.0) < 1e-6)\n  {\n    return 0;\n  }\n  else if (abs(value - (double)max) < 1e-6)\n  {\n    return max - 1;\n  }\n  else\n  {\n    return (int)round(value - 0.5);\n  }\n}\n\n// ---------------------------------------------------------------------------\nvector_3d\nbackproject_to_depth_map\n(kwiver::vital::camera_perspective_sptr const camera,\n kwiver::vital::image_container_sptr const depth_map,\n vector_2d const& img_pt)\n{\n  vector_2d npt_ = camera->intrinsics()->unmap(img_pt);\n  auto npt = vector_3d(npt_(0), npt_(1), 1.0);\n\n  matrix_3x3d M = camera->rotation().matrix().transpose();\n  vector_3d cam_pos = camera->center();\n\n  vector_3d Mp = M * npt;\n\n  kwiver::vital::image dm_data = depth_map->get_image();\n  auto dm_width = (int)dm_data.width();\n  auto dm_height = (int)dm_data.height();\n\n  int img_pt_x = nearest_index(dm_width, img_pt(0));\n  int img_pt_y = nearest_index(dm_height, img_pt(1));\n\n  if (img_pt_x < 0 || img_pt_y < 0 ||\n      img_pt_x >= dm_width ||\n      img_pt_y >= dm_height)\n  {\n    throw std::invalid_argument(\"Provided image point is outside of image \"\n                                \"bounds\");\n  }\n\n  float depth = dm_data.at<float>(img_pt_x, img_pt_y);\n\n  vector_3d world_pos = cam_pos + (Mp * depth);\n\n  return world_pos;\n}\n\n// ---------------------------------------------------------------------------\nstd::tuple<vector_3d, vector_3d>\nbackproject_wrt_height\n(kwiver::vital::camera_perspective_sptr const camera,\n kwiver::vital::image_container_sptr const depth_map,\n vector_2d const& img_pt_bottom,\n vector_2d const& img_pt_top)\n{\n  vector_3d world_pos_bottom = backproject_to_depth_map\n    (camera, depth_map, img_pt_bottom);\n\n  vector_2d npt_ = camera->intrinsics()->unmap(img_pt_top);\n  auto npt = vector_3d(npt_(0), npt_(1), 1.0);\n\n  matrix_3x3d M = camera->rotation().matrix().transpose();\n  vector_3d cam_pos = camera->center();\n\n  vector_3d Mp = M * npt;\n\n  double xf = world_pos_bottom(0);\n  double yf = world_pos_bottom(1);\n\n  double xc = cam_pos(0);\n  double yc = cam_pos(1);\n  double zc = cam_pos(2);\n\n  double nx = Mp(0);\n  double ny = Mp(1);\n  double nz = Mp(2);\n\n  // If we assume that the top world point for given pair is directly\n  // above the bottom world point at (xf, yf, zf), then the top world\n  // point is at (xf, yf, zh), where we need to solve for zh.  The\n  // camera is located at (xc, yc, zc) and the ray coming out at the\n  // top image point is along the direction (in world coordinates)\n  // <nx, ny, nz>, but we don't know how far along this ray's\n  // direction we need to go to be as close as possible to (xf, yf,\n  // zf). If we travel 't' along the ray, then the squared distance\n  // from (xf, yf) is (xc+nx*t - xf)^2 + (yc+ny*t - yf)^2, and we want\n  // 't' that minimizes this. Take the derivative wrt 't' and set\n  // equal to zero:\n  // 2 * (xc + nx * t - xf) * nx + 2 * (yc + ny * t - yf) * ny = 0\n  // Rearranged as:\n  double t = (ny * (yf - yc) + nx * (xf - xc)) /\n    (std::pow(nx, 2) + std::pow(ny, 2));\n\n  double zh = zc + t*nz;\n\n  auto world_pos_top = vector_3d(xf, yf, zh);\n\n  return std::tuple<vector_3d, vector_3d> (world_pos_bottom, world_pos_top);\n}\n\n// ---------------------------------------------------------------------------\nvital::bounding_box<double>\ntransfer_bbox_with_depth_map_stationary_camera\n(kwiver::vital::camera_perspective_sptr const src_camera,\n kwiver::vital::camera_perspective_sptr const dest_camera,\n kwiver::vital::image_container_sptr const depth_map,\n vital::bounding_box<double> const bbox)\n{\n  double bbox_min_x = bbox.min_x();\n  double bbox_max_x = bbox.max_x();\n  double bbox_min_y = bbox.min_y();\n  double bbox_max_y = bbox.max_y();\n  double bbox_aspect_ratio = (bbox_max_x - bbox_min_x) /\n    (bbox_max_y - bbox_min_y);\n\n  auto bbox_bottom_center = vector_2d\n    ((bbox_max_x + bbox_min_x) / 2, bbox_max_y);\n  auto bbox_top_center = vector_2d\n    ((bbox_max_x + bbox_min_x) / 2, bbox_min_y);\n\n  vector_3d world_pos_bottom;\n  vector_3d world_pos_top;\n\n  std::tie(world_pos_bottom, world_pos_top) =\n    backproject_wrt_height\n    (src_camera, depth_map, bbox_bottom_center, bbox_top_center);\n\n  vector_2d dest_img_pos_bottom = dest_camera->project(world_pos_bottom);\n  vector_2d dest_img_pos_top = dest_camera->project(world_pos_top);\n\n  double dest_bbox_min_y = dest_img_pos_top(1);\n  double dest_bbox_max_y = dest_img_pos_bottom(1);\n  double dest_bbox_height = dest_bbox_max_y - dest_bbox_min_y;\n\n  // Using the original bbox aspect ratio to compute the width of our\n  // transferred box.  Could use a more sophisticated method here\n  double dest_bbox_width_d = bbox_aspect_ratio * dest_bbox_height;\n\n  // Use the average center x coordinate of transfered top and bottom\n  // points as the center of the bounding box\n  double dest_bbox_min_x =\n    ((dest_img_pos_top(0) + dest_img_pos_bottom(0)) / 2) -\n    (dest_bbox_width_d / 2);\n  double dest_bbox_max_x =\n    ((dest_img_pos_top(0) + dest_img_pos_bottom(0)) / 2) +\n    (dest_bbox_width_d / 2);\n\n  return vital::bounding_box<double>\n    (dest_bbox_min_x, dest_bbox_min_y, dest_bbox_max_x, dest_bbox_max_y);\n}\n\n// ---------------------------------------------------------------------------\ntransfer_bbox_with_depth_map::\ntransfer_bbox_with_depth_map()\n{\n}\n\n// ---------------------------------------------------------------------------\ntransfer_bbox_with_depth_map::\ntransfer_bbox_with_depth_map\n(kwiver::vital::camera_perspective_sptr src_cam,\n kwiver::vital::camera_perspective_sptr dest_cam,\n kwiver::vital::image_container_sptr src_cam_depth_map)\n  : src_camera( src_cam )\n  , dest_camera( dest_cam )\n  , depth_map( src_cam_depth_map )\n{\n}\n\n// ---------------------------------------------------------------------------\nvital::config_block_sptr\ntransfer_bbox_with_depth_map::\nget_configuration() const\n{\n  // Get base config from base class\n  vital::config_block_sptr config = vital::algorithm::get_configuration();\n\n  config->set_value( \"src_camera_krtd_file_name\", src_camera_krtd_file_name,\n                     \"Source camera KRTD file name path\" );\n\n  config->set_value( \"dest_camera_krtd_file_name\", dest_camera_krtd_file_name,\n                     \"Destination camera KRTD file name path\" );\n\n  config->set_value( \"src_camera_depth_map_file_name\",\n                     src_camera_depth_map_file_name,\n                     \"Source camera depth map file name path\" );\n\n  vital::algo::image_io::\n    get_nested_algo_configuration( \"image_reader\", config, image_reader );\n\n  return config;\n}\n\n// ---------------------------------------------------------------------------\nvoid\ntransfer_bbox_with_depth_map::\nset_configuration( vital::config_block_sptr config_in )\n{\n  vital::config_block_sptr config = this->get_configuration();\n\n  config->merge_config( config_in );\n  this->src_camera_krtd_file_name =\n    config->get_value< std::string > ( \"src_camera_krtd_file_name\" );\n  this->dest_camera_krtd_file_name =\n    config->get_value< std::string > ( \"dest_camera_krtd_file_name\" );\n  this->src_camera_depth_map_file_name =\n    config->get_value< std::string > ( \"src_camera_depth_map_file_name\" );\n\n  // Setup actual reader algorithm\n  vital::algo::image_io::\n    set_nested_algo_configuration( \"image_reader\", config, image_reader );\n\n  this->src_camera =\n    kwiver::vital::read_krtd_file( this->src_camera_krtd_file_name );\n  this->dest_camera =\n    kwiver::vital::read_krtd_file( this->dest_camera_krtd_file_name );\n\n  this->depth_map = image_reader->load( this->src_camera_depth_map_file_name );\n}\n\n// ---------------------------------------------------------------------------\nbool\ntransfer_bbox_with_depth_map::\ncheck_configuration( vital::config_block_sptr config ) const\n{\n  kwiver::vital::config_difference cd( this->get_configuration(), config );\n  const auto key_list = cd.extra_keys();\n\n  if ( ! key_list.empty() )\n  {\n    LOG_WARN( logger(), \"Additional parameters found in config block that are \"\n                        \"not required or desired: \"\n                        << kwiver::vital::join( key_list, \", \" ) );\n  }\n\n  return true;\n}\n\n// ---------------------------------------------------------------------------\nvital::detected_object_set_sptr\ntransfer_bbox_with_depth_map::\nfilter( vital::detected_object_set_sptr const input_set ) const\n{\n  auto ret_set = std::make_shared<vital::detected_object_set>();\n\n  for ( auto det : *input_set )\n  {\n    auto out_det = det->clone();\n    auto out_bbox = out_det->bounding_box();\n\n    try\n    {\n      vital::bounding_box<double> new_out_bbox =\n        transfer_bbox_with_depth_map_stationary_camera\n        (src_camera, dest_camera, depth_map, out_bbox);\n      out_det->set_bounding_box( new_out_bbox );\n      ret_set->add( out_det );\n    }\n    catch (const std::invalid_argument& e)\n    {\n      std::ostringstream strs;\n      strs << \"Bounding box (\"\n           << out_bbox.min_x() << \", \"\n           << out_bbox.min_y() << \", \"\n           << out_bbox.max_x() << \", \"\n           << out_bbox.max_y() << \") \"\n           << \"couldn't be transferred, skipping!\";\n\n      LOG_WARN(logger(), strs.str());\n    }\n  }\n\n  return ret_set;\n}\n\n}}} // end namespace\n", "meta": {"hexsha": "e12220725722faa0f7578a701e6f684c8725f205", "size": 9806, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "arrows/core/transfer_bbox_with_depth_map.cxx", "max_stars_repo_name": "mwoehlke-kitware/kwiver", "max_stars_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 176.0, "max_stars_repo_stars_event_min_datetime": "2015-07-31T23:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T23:42:44.000Z", "max_issues_repo_path": "arrows/core/transfer_bbox_with_depth_map.cxx", "max_issues_repo_name": "mwoehlke-kitware/kwiver", "max_issues_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1276.0, "max_issues_repo_issues_event_min_datetime": "2015-05-03T01:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:32:20.000Z", "max_forks_repo_path": "arrows/core/transfer_bbox_with_depth_map.cxx", "max_forks_repo_name": "mwoehlke-kitware/kwiver", "max_forks_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2015-01-25T05:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T14:59:37.000Z", "avg_line_length": 31.8376623377, "max_line_length": 79, "alphanum_fraction": 0.641749949, "num_tokens": 2547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5113072612932271}}
{"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 RJMCMC_SIMPLEX_VARIATE_HPP\n#define RJMCMC_SIMPLEX_VARIATE_HPP\n\n#include <boost/random/uniform_real.hpp>\n\nnamespace rjmcmc {\n\n    template<int N> struct factorial    { enum { value = factorial<N-1>::value * N };};\n    template<     > struct factorial<0> { enum { value = 1 }; };\n\n\n    struct simplex_variate_log_policy\n    {\n        template<int N, typename Engine, typename OutputIterator, typename Rand>\n        void apply(Engine& e, OutputIterator it, Rand& rand) const\n        {\n            double sum = 0;\n            double x[N+1];\n            for(unsigned int i=0; i<=N; ++i)\n            {\n                x[i] = -log(rand(e));\n                sum += x[i];\n            }\n            for(unsigned int i=0; i<N; ++i, ++it)\n            {\n                *it = x[i]/sum;\n            }\n        }\n    };\n\n\n    struct simplex_variate_sort_policy\n    {\n        template<int N, typename Engine, typename OutputIterator, typename Rand>\n        void apply(Engine& e, OutputIterator it, Rand& rand) const\n        {\n            double x[N];\n            for(unsigned int i=0; i<N; ++i) x[i] = rand(e);\n            std::sort(x,x+N);\n            double prev = 0;\n            for(unsigned int i=0; i<N; ++i, ++it)\n            {\n                *it = x[i]-prev;\n                prev = x[i];\n            }\n        }\n    };\n\n\n    struct simplex_variate_power_policy\n    {\n        template<int N, typename Engine, typename OutputIterator, typename Rand>\n        void apply(Engine& e, OutputIterator it, Rand& rand) const\n        {\n            static_assert(N>1,\"simplex_variate_power_policy is only valid for 2D variates or more !\");\n            double prev = pow(rand(e),1./N);\n            for(unsigned int i=N-1; i>1; --i)\n            {\n                double next = prev*pow(rand(e),1./i);\n                *it++ = prev-next;\n                prev = next;\n            }\n            double next = prev*rand(e);\n            *it++ = prev-next;\n            *it++ = next;\n        }\n    };\n\n\n    struct simplex_variate_rejection_policy\n    {\n        template<int N, typename Engine, typename OutputIterator, typename Rand>\n        void apply(Engine& e, OutputIterator it, Rand& rand) const\n        {\n            for(;;)\n            {\n                double x[N], sum;\n                for(unsigned int i=0; i<N; ++i)\n                {\n                    x[i] = rand(e);\n                    sum += x[i];\n                }\n                if(sum<=1.)\n                {\n                    for(unsigned int i=0; i<N; ++i)  *it++ = x[i];\n                    return;\n                }\n            }\n        }\n    };\n\n    struct simplex_variate_reflect_policy\n    {\n        template<int N, typename Engine, typename OutputIterator, typename Rand>\n        void apply(Engine& e, OutputIterator it, Rand& rand) const\n        {\n            static_assert(N==2,\"simplex_variate_reflect_policy is only valid for 2D variates !\");\n            double x = rand(e);\n            double y = rand(e);\n            if(x+y>1.)\n            {\n                x = 1.-x;\n                y = 1.-y;\n            }\n            *it++ = x;\n            *it++ = y;\n        }\n    };\n\n    struct simplex_variate_sqrt_policy\n    {\n        template<int N, typename Engine, typename OutputIterator, typename Rand>\n        void apply(Engine& e, OutputIterator it, Rand& rand) const\n        {\n            static_assert(N==2,\"simplex_variate_sqrt_policy is only valid for 2D variates, use the generalized simplex_variate_power_policy instead !\");\n            double x = sqrt(rand(e));\n            double y = x*rand(e);\n            *it++ = x-y;\n            *it++ = y;\n        }\n    };\n\n\n    template<int N, typename Policy = simplex_variate_power_policy >\n    class simplex_variate\n    {\n        typedef boost::uniform_real<> rand_type;\n        mutable rand_type m_rand;\n        const double m_pdf;\n        Policy m_policy;\n    public:\n        typedef double value_type;\n        enum { dimension = N };\n        template<typename InputIterator>\n        inline double pdf(InputIterator it) const {\n            double sum = 0;\n            for(unsigned int i=0; i<N; ++i, ++it)\n            {\n                if(*it<0) return 0;\n                sum += *it;\n            }\n            return double(sum <= 1.)*m_pdf;\n        }\n        template<typename Engine, typename OutputIterator>\n        inline double operator()(Engine& e, OutputIterator it) const {\n            m_policy.template apply<N>(e,it,m_rand);\n            return m_pdf;\n        }\n        simplex_variate() : m_rand(0,1), m_pdf(1./factorial<N>::value) {}\n\n    };\n\n}; // namespace rjmcmc\n\n#endif // RJMCMC_SIMPLEX_VARIATE_HPP\n", "meta": {"hexsha": "51fe631cf8c5e3d78005c12850588b072e0d82dd", "size": 6429, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rjmcmc/rjmcmc/kernel/simplex_variate.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/kernel/simplex_variate.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/kernel/simplex_variate.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": 33.484375, "max_line_length": 152, "alphanum_fraction": 0.5663400218, "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.511307261293227}}
{"text": "//==================================================================================================\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#include <boost/simd/function/ifrexp.hpp>\n#include <boost/simd/function/pedantic.hpp>\n#include <boost/simd/constant/nbmantissabits.hpp>\n#include <boost/simd/constant/halfeps.hpp>\n#include <scalar_test.hpp>\n\nnamespace bs = boost::simd;\nnamespace bd = boost::dispatch;\n\nSTF_CASE_TPL(\"Check basic behavior of pedantic_(ifrexp)\", STF_IEEE_TYPES)\n{\n  STF_EXPR_IS ( (bs::pedantic_(bs::ifrexp)(T(0)))\n              , (std::pair<T,bd::as_integer_t<T,signed>>)\n              );\n\n  auto p = bs::pedantic_(bs::ifrexp)(T(1));\n  STF_EQUAL(p.first  , T(0.5));\n  STF_EQUAL(p.second , T(1));\n}\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(ifrexp) on Zero\", STF_IEEE_TYPES)\n{\n  auto r = bs::pedantic_(bs::ifrexp)(T(0));\n\n  STF_EQUAL (r.first , T(0));\n  STF_EQUAL (r.second, T(0));\n  STF_EQUAL (ldexp(r.first,r.second), T(0));\n}\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(ifrexp) on Valmax\", STF_IEEE_TYPES)\n{\n  auto r = bs::pedantic_(bs::ifrexp)(bs::Valmax<T>());\n\n  STF_ULP_EQUAL (r.first , T(1)-bs::Halfeps<T>(), 1);\n  STF_EQUAL     (r.second, bs::Limitexponent<T>());\n  STF_EQUAL     (ldexp(r.first,r.second),bs::Valmax<T>());\n}\n\n#ifndef BOOST_SIMD_NO_INVALID\n#include <boost/simd/constant/nan.hpp>\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(ifrexp) on NaN\", STF_IEEE_TYPES)\n{\n  auto r = bs::pedantic_(bs::ifrexp)(bs::Nan<T>());\n\n  STF_IEEE_EQUAL(r.first , bs::Nan<T>());\n  STF_EQUAL     (r.second, T(0));\n  STF_IEEE_EQUAL(ldexp(r.first,r.second), bs::Nan<T>());\n}\n#endif\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(ifrexp) on infinites\", STF_IEEE_TYPES)\n{\n  auto r = bs::pedantic_(bs::ifrexp)(bs::Inf<T>());\n  auto q = bs::pedantic_(bs::ifrexp)(bs::Minf<T>());\n\n  STF_IEEE_EQUAL(r.first , bs::Inf<T>());\n  STF_EQUAL     (r.second, T(0));\n  STF_IEEE_EQUAL(ldexp(r.first,r.second), bs::Inf<T>());\n\n  STF_IEEE_EQUAL(q.first , bs::Minf<T>());\n  STF_EQUAL     (q.second, T(0));\n  STF_IEEE_EQUAL(ldexp(q.first,q.second), bs::Minf<T>());\n}\n#endif\n\n#ifndef BOOST_SIMD_NO_DENORMALS\n#include <boost/simd/detail/constant/minexponent.hpp>\n#include <boost/simd/constant/mindenormal.hpp>\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(ifrexp) on denormals\", STF_IEEE_TYPES)\n{\n  auto r = bs::pedantic_(bs::ifrexp)(bs::Mindenormal<T>());\n\n  STF_ULP_EQUAL (r.first, T(0.5), 1);\n  STF_EQUAL     (r.second, bs::Minexponent<T>()-bs::Nbmantissabits<T>()+1);\n  STF_EQUAL     (ldexp(r.first,r.second),bs::Mindenormal<T>());\n}\n#endif\n", "meta": {"hexsha": "080dd0b82f0b60941c8457fe97794961cf3c8a9b", "size": 2886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/ifrexp.pedantic.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/scalar/ifrexp.pedantic.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/ifrexp.pedantic.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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.3695652174, "max_line_length": 100, "alphanum_fraction": 0.6351351351, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5113072602796852}}
{"text": "#ifndef LATTICE_REGULARCUBE_CONNECTED_TAGGEDPARTICLE_HPP\n#define LATTICE_REGULARCUBE_CONNECTED_TAGGEDPARTICLE_HPP\n\n#include <string>\n#include <vector>\n#include <boost/lexical_cast.hpp>\n\nnamespace lattice {\n\nclass RegularCubeConnectedTaggedParticle{\npublic:\n  static std::string name() { return \"Regular Cube lasso (total must be even)\";}\n  static int set_num_particles(int Ns){return Ns*Ns*Ns+1;}\n  RegularCubeConnectedTaggedParticle(unsigned int LatticeSize) : dim_(LatticeSize) {}\n\n  void create_table(std::vector<std::vector < int > >& table){\n  //for bulk\n    for (int i = 0; i < dim_; ++i){\n      for (int j = 0; j < dim_; ++j){\n        for (int k = 0; k < dim_; ++k){\n          int l = numberize(i,j,k);\n          int temp = 0;\n          table[l][6] = l;\n          for(int d = -1; d < 2; d =d+2){ \n            table[l][temp] = numberize(i+d,j,k);\n            temp += 1;\n            table[l][temp] = numberize(i,j+d,k);\n            temp += 1;\n            table[l][temp] = numberize(i,j,k+d);\n            temp += 1;\n          }\n        }\n      }\n    }\n   int tagg = dim_ * dim_ * dim_ ;\n   int l = numberize((dim_-1)/2,(dim_-1)/2,(dim_-1)/2);\n   table[l][6] = tagg; \n   table[tagg][0] = l;\n   for(int temp = 1; temp < 7 ; ++temp) table[tagg][temp] = tagg;\n   \n  }  \n\n  int numberize(const int i, const int j,const int k){\n    int i_t = (i + dim_);\n    int j_t = (j + dim_);\n    int k_t = (k + dim_);\n    i_t %= dim_ ;\n    j_t %= dim_ ;\n    k_t %= dim_ ;\n    return i_t + j_t * dim_ + k_t * dim_ * dim_;\n  }\n\n  int latticize(int d, const int l){ //d is direction(0 ~ ) ex. 0 denotes x, 1 denotes y,~\n    int k = l / (dim_*dim_) ;\n    int j = (l - dim_ * dim_* k)/dim_ ;\n    int i = (l - dim_ * dim_ * k - dim_ *j);\n    if(d==0) return i;\n    else if (d==1) return j;\n    else return k;\n  }\n\n  int number_adjacent() {return 7;}\n\nprivate:\n  unsigned int dim_;\n};\n\n} //end namespace\n\n#endif //LATTICE_REGULARCUBE_CONNECTED_TAGGEDPARTICLE_HPP\n", "meta": {"hexsha": "e826c0c859bac82b9fce242bac30484f8f024dba", "size": 1942, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "clstatphys/clstatphys/lattice/regularcube_connected_taggedparticle.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/lattice/regularcube_connected_taggedparticle.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/lattice/regularcube_connected_taggedparticle.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": 27.3521126761, "max_line_length": 90, "alphanum_fraction": 0.5659114315, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.511307251619253}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file LevMarqGaussNewtonSolver.hpp\n///\n/// \\author Sean Anderson, ASRL\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef STEAM_LEVMARQ_GAUSS_NEWTON_SOLVER_HPP\n#define STEAM_LEVMARQ_GAUSS_NEWTON_SOLVER_HPP\n\n#include <Eigen/Core>\n\n#include <steam/solver/GaussNewtonSolverBase.hpp>\n\nnamespace steam {\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Solver using Levenberg\u2013Marquardt for the trust region\n//////////////////////////////////////////////////////////////////////////////////////////////\nclass LevMarqGaussNewtonSolver : public GaussNewtonSolverBase\n{\n public:\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Dogleg parameters\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  struct Params : public SolverBase::Params {\n\n    //////////////////////////////////////////////////////////////////////////////////////////////\n    /// \\brief Default constructor\n    //////////////////////////////////////////////////////////////////////////////////////////////\n    Params() : SolverBase::Params(), ratioThreshold(0.25),\n      shrinkCoeff(0.1), growCoeff(10.0), maxShrinkSteps(50) {\n    }\n\n    /// Minimum ratio of actual to predicted reduction, shrink trust region if lower, else grow (range: 0.0-1.0)\n    double ratioThreshold;\n\n    /// Amount to shrink by (range: <1.0)\n    double shrinkCoeff;\n\n    /// Amount to grow by (range: >1.0)\n    double growCoeff;\n\n    /// Maximum number of times to shrink trust region before giving up\n    unsigned int maxShrinkSteps;\n  };\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  LevMarqGaussNewtonSolver(OptimizationProblem* problem, const Params& params = Params());\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Solve the Levenberg\u2013Marquardt system of equations:\n  ///        A*x = b, A = (J^T*J + diagonalCoeff*diag(J^T*J))\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Eigen::VectorXd solveLevMarq(const Eigen::VectorXd& gradientVector, double diagonalCoeff);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Perform a plain LLT decomposition on the approx. Hessian matrix in\n  ///        order to solve for the proper covariances (unmodified by the LM diagonal)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  void solveCovariances();\n\n private:\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Build the system, solve for a step size and direction, and update the state\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual bool linearizeSolveAndUpdate(double* newCost, double* gradNorm);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Casts parameters to base type (for SolverBase class)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual const SolverBase::Params& getSolverBaseParams() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Parameters\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Params params_;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Diagonal multiplier (lambda in most papers - related to trust region size)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  double diagCoeff;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief The 'left-hand-side' of the Gauss-Newton problem, generally known as the\n  ///        approximate Hessian matrix (note we only store the upper-triangular elements).\n  ///        Note that LM stores this to later solve the plain system for covariances.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Eigen::SparseMatrix<double> approximateHessian_;\n\n};\n\n} // steam\n\n#endif // STEAM_LEVMARQ_GAUSS_NEWTON_SOLVER_HPP\n", "meta": {"hexsha": "106fa10a7cf5e3460224b8bdb5ed147e7f04df10", "size": 4721, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/steam/solver/LevMarqGaussNewtonSolver.hpp", "max_stars_repo_name": "utiasASRL/steam", "max_stars_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-10-17T01:37:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:55:47.000Z", "max_issues_repo_path": "include/steam/solver/LevMarqGaussNewtonSolver.hpp", "max_issues_repo_name": "utiasASRL/steam", "max_issues_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-21T21:25:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-01T23:08:57.000Z", "max_forks_repo_path": "include/steam/solver/LevMarqGaussNewtonSolver.hpp", "max_forks_repo_name": "utiasASRL/steam", "max_forks_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-12-21T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T23:42:14.000Z", "avg_line_length": 47.6868686869, "max_line_length": 112, "alphanum_fraction": 0.3672950646, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5113072467822659}}
{"text": "/***********************************************************************\nCopyright 2018 Gregory Bryant\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n***********************************************************************/\n\n\n#include \"factormap.h\"\n#include \"neconsolewindow.h\"\n#include \"neview.h\"\n#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing boost::multiprecision::abs;\nusing boost::multiprecision::mpz_int;\n\n\n\nmpz_int FactorMap::fixYOffsetAndSign(mpz_int x, mpz_int y)\n{\n    if(y>=0)\n    {\n        if(y>abs(x))\n        {\n            if(y%abs(x)!=0)\n            {return abs(x)-(y%abs(x))+y;}\n            else{return y;}\n        }\n        else{return abs(x);}\n    }\n    else\n    {\n        if(abs(y)>=abs(x))\n        {\n            temp=abs(x)-(abs(y)%abs(x))+abs(y);\n            temp=temp-abs(x);\n            temp*=-1;\n            return temp;\n        }\n        else{return 0;}\n    }\n}\n\nFactorMap::FactorMap()\n{\n    name.append(\"FactorMap\");\n}\n\nvoid FactorMap::render(NEView *view)\n{\n\n    view->getScreenBounds(&top,&bottom,&left,&right);\n\n\n    //for(int i=left;i<right;i++)\n    i = left;\n    while(i<right)\n    {\n        if(i==0){i++;continue;}\n\n        j = fixYOffsetAndSign(i,bottom);\n\n        while(j<=top)\n        {\n            //mpz_int yVal = view->height()-1-j+view->yOffset;\n            //mpz_int xVal = i-view->xOffset;\n            //view->setPoint(static_cast<int>(xVal),static_cast<int>(yVal));\n            view->setPoint(i,j);\n            j+=abs(i);\n        }\n    i++;\n    }\n}\n", "meta": {"hexsha": "dca016d93696d747145c8a80fb6c8b7e9d59db92", "size": 1988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/factormap.cpp", "max_stars_repo_name": "gbryant/number-explorer", "max_stars_repo_head_hexsha": "f1423bb682a6cbfd8238ba980f32659842295456", "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/factormap.cpp", "max_issues_repo_name": "gbryant/number-explorer", "max_issues_repo_head_hexsha": "f1423bb682a6cbfd8238ba980f32659842295456", "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/factormap.cpp", "max_forks_repo_name": "gbryant/number-explorer", "max_forks_repo_head_hexsha": "f1423bb682a6cbfd8238ba980f32659842295456", "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.6666666667, "max_line_length": 76, "alphanum_fraction": 0.5487927565, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5113072391353757}}
{"text": "/*\n * Mesh.cpp\n *\n * This class contains the mesh and mesh properties to be used\n * in the finite element method (FiniteElem.cpp).\n *\n * It constructs the mesh, then constructs the stiffness matrix and\n * calculates the boundary.\n *\n *  Created on: Aug 13, 2016\n *      Author: Ted Kwan\n */\n\n#include \"Mesh.h\"\n#include <cmath>\n#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nMesh::Mesh() {\n\n}\n\n/**\n * Constructor for Mesh. It takes one input, a vector containing the\n * properties of the mesh to be created.\n *\n * @param meshprops - double vector with all of the necessary properties.\n */\nMesh::Mesh(vector<double> meshprops) {\n\t// Extract the mesh size value.\n\th = meshprops[4];\n\tn = round(1 / h);\n\t// Create vectors to be used for mesh creation.\n\tvec xr = linspace<vec>(meshprops[0], meshprops[1], n + 1);\n\tvec yr = linspace<vec>(meshprops[2], meshprops[3], n + 1);\n\t// Create the mesh.\n\tmakeMesh(xr, yr);\n\t// Assemble stiffness matrix\n\n\tvector<sp_mat> stiffmass = assembleMatrix();\n\tstiffness=stiffmass[0];\n\tmass=stiffmass[1];\n\t// Calculate boundary nodes.\n\tfindBoundary();\n}\n\n/**\n * makeMesh creates the mesh for the 2D Cartesian grid.\n *\n * @param xr - input vector containing the x values.\n * @param yr - input vector containing the y values.\n */\nvoid Mesh::makeMesh(vec xr, vec yr) {\n\t// Findthe lengths to use.\n\tuword xrl = xr.n_rows;\n\tuword yrl = xr.n_rows;\n\tmat x = zeros<mat>(xrl, yrl);\n\tmat y = zeros<mat>(xrl, yrl);\n\t// Construct the meshes. This is just the same\n\t// as calling meshgrid() in MATLAB.\n\tfor (uword i = 0; i < yrl; i++) {\n\t\tx.row(i) = xr.t();\n\t}\n\tfor (uword i = 0; i < xrl; i++) {\n\t\ty.col(i) = yr;\n\t}\n\t// Vectorise the values to use for the nodes matrix.\n\tvec xv = vectorise(x);\n\tN = xv.n_rows;\n\tuword ni = x.n_rows;\n\t// Initialize node matrix.\n\tnode = zeros<mat>(N, 2);\n\t// put all the values in the node matrix\n\tnode.col(0) = xv;\n\tnode.col(1) = vectorise(y);\n\t// Map the indices for the nodes to create elem matrix.\n\tuvec t2nidxMapnz = regspace<uvec>(0, N - ni - 1);\n\tuvec topNode = regspace<uvec>(ni - 1, ni, N - ni - 1);\n\t// Set all of the doubled nodes to not be included.\n\tt2nidxMapnz(topNode) = zeros<uvec>(topNode.n_rows);\n\t// Find nonzeros in the original indices map.\n\tuvec nnz = nonzeros(t2nidxMapnz);\n\tuvec k = zeros<uvec>(nnz.n_rows + 1);\n\t// Calculate the different values used to create nodes.\n\tk(span(1, nnz.n_rows)) = nnz;\n\tuword NE = k.n_rows;\n\t// Create the elements which will differ by odd and\n\t// even elements.\n\tumat elemup = zeros<umat>(NE, 3);\n\tumat elemdown = zeros<umat>(NE, 3);\n\tuvec niv = ones<uvec>(k.n_rows);\n\tniv = niv * ni;\n\tuvec onek = ones<uvec>(k.n_rows);\n\t// Map elements to nodes in order.\n\telemup.col(0) = k + niv;\n\telemup.col(1) = k + niv + onek;\n\telemup.col(2) = k;\n\telemdown.col(0) = k + onek;\n\telemdown.col(1) = k;\n\telemdown.col(2) = k + niv + onek;\n\t// join all columns together and stack them properly.\n\telem = join_cols(elemup, elemdown);\n\tNT = elem.n_rows;\n}\n\n/**\n * assembleMatrix assembles the stiffness matrix using the quick\n * construction method from armadillo for sparse matrices.\n *\n * @return - Stiffness matrix as a sparse matrix.\n */\nvector<sp_mat> Mesh::assembleMatrix() {\n\t// Initialize index maps and value vector.\n\tuvec ii = zeros<uvec>(9 * NT);\n\tuvec jj = zeros<uvec>(9 * NT);\n\tvec sA = zeros<vec>(9 * NT);\n\t// Calculate the area of each node.\n\tcube ve(NT, 2, 3);\n\tve.slice(0) = node.rows(elem.col(2)) - node.rows(elem.col(1));\n\tve.slice(1) = node.rows(elem.col(0)) - node.rows(elem.col(2));\n\tve.slice(2) = node.rows(elem.col(1)) - node.rows(elem.col(0));\n\t// Find the area using the dot product on the second dimension.\n\tarea = 0.5*abs((ve.slice(2).col(0) % ve.slice(1).col(1))\n\t\t\t\t\t-(ve.slice(2).col(1) % ve.slice(1).col(0)));\n\tuword index = 0;\n\t// Loop to map values and indices.\n\tfor (uword i = 0; i < 3; i++) {\n\t\tfor (uword j = 0; j < 3; j++) {\n\t\t\t// Setup indices to map in this iteration.\n\t\t\tuvec inds = regspace<uvec>(index, index + NT - 1);\n\t\t\t// Setup element maps for indices.\n\t\t\tii(inds) = elem.col(i);\n\t\t\tjj(inds) = elem.col(j);\n\t\t\t// Calculate values of stiffness matrix at\n\t\t\t// these points.\n\t\t\tmat prod = ve.slice(i) % ve.slice(j);\n\t\t\t// Store calculated value.\n\t\t\tsA(inds) = sum(prod, 1) / (4 * area);\n\t\t\tindex = index + NT;\n\t\t}\n\t}\n\t// Setup index map to be a 2x9NT matrix.\n\tumat inds = join_horiz(ii, jj);\n\t// Create the sparse matrix using the same\n\t// method as sparse(row indices, col indices, values, size)\n\tsp_mat A(true, inds.t(), sA, N, N, true, true);\n\tvector<sp_mat> matvec(2);\n\tmatvec[0]=A;\n\tvec Mv=accumArrayM(join_vert(elem.col(0), join_vert(elem.col(1),elem.col(2)))\n\t\t\t,join_vert(area, join_vert(area,area))/(3.0), N);\n\tuvec inds2=regspace<uvec>(0,Mv.n_rows-1);\n\tumat subs2=join_horiz(inds2,inds2);\n\tsubs2.print(\"indices: \");\n\tsp_mat M(true,subs2.t(),Mv,N,N,true,true);\n\tmatvec[1]=M;\n\treturn matvec;\n}\n\n/**\n * Find the boundary nodes and elements.\n *\n * This method calculates the boundary for the given mesh to be used\n * to set the boundary condition for the finite element method.\n *\n * Values are stored so that they can be accesssed later.\n *\n */\nvoid Mesh::findBoundary() {\n\n\t// Setup as two column vectors to find the edges.\n\tumat e1 = join_vert(join_horiz(elem.col(2), elem.col(1)),\n\t\t\tjoin_horiz(elem.col(0), elem.col(2)));\n\t// Calculate all of the values of the edges.\n\tumat totalEdge = join_vert(e1, join_horiz(elem.col(1), elem.col(0)));\n\ttotalEdge = sort(totalEdge, \"ascend\", 1);\n\tvec onev = ones<vec>(totalEdge.n_rows);\n\t// Create sparse matrix containing the edges which are not being double counted\n\t// and are thus exterior edges.\n\tsp_mat fndmat(true, totalEdge.t(), onev, totalEdge.n_rows, totalEdge.n_rows,\n\t\t\ttrue, true);\n\t// Initialize edge matrix.\n\tumat bdEdge = zeros<umat>(totalEdge.n_rows, 2);\n\tvec s = nonzeros(fndmat);\n\tuvec ii = zeros<uvec>(s.n_elem);\n\tuvec jj = zeros<uvec>(s.n_elem);\n\tuword k = 0;\n\t// Get the indices for the edges which are exterior edges.\n\t// The indices map back to nodes.\n\tfor (uword i = 0; i < fndmat.n_rows; i++) {\n\t\tfor (uword j = 0; j < fndmat.n_cols; j++) {\n\t\t\tdouble spot = fndmat(i, j);\n\t\t\t// Only find edges where there are two boundary nodes.\n\t\t\tif (spot == 1.0 && k < s.n_elem) {\n\t\t\t\tii(k) = i;\n\t\t\t\tjj(k) = j;\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t}\n\tuvec i1 = nonzeros(ii);\n\tuvec j1 = nonzeros(jj);\n\t// Setup boolean vector which has whether or not a node is a boundary\n\t// node.\n\tisbdNode = zeros<uvec>(N);\n\tisbdNode.rows(i1) = ones<uvec>(i1.n_rows);\n\tisbdNode.rows(j1) = ones<uvec>(j1.n_rows);\n\tisbdNode(0) = 1.0;\n\t// Find indices of boundary nodes.\n\tbdNode = find(isbdNode);\n\tuvec onebd = ones<uvec>(isbdNode.n_rows);\n\t// Find indices of interior nodes.\n\tfreeNode = find(onebd - isbdNode);\n}\n\nvec Mesh::accumArrayM(uvec subs,vec ar,uword N){\n\n\tvec S=zeros<vec>(N);\n\n\tfor(uword i=0;i<N;i++){\n\t\t// Get the subscripts.\n\t\tuvec q1=find(subs ==(i));\n\t\tvec spot;\n\t\tdouble thesum=0.0;\n\t\tif(!q1.is_empty()){\n\t\t\t// Find elements at indices q1\n\t\t\tspot=ar.elem(q1);\n\t\t\t// Sum elements.\n\t\t\tthesum=sum(spot);\n\t\t\t// Set at position i.\n\t\t\tS(i)=thesum;\n\t\t}\n\t\t// If it is empty, add 0.\n\t\telse{\n\t\t\tS(i)=0.0;\n\t\t}\n\t}\n\n\treturn S;\n}\n\nMesh::~Mesh() {\n\t// TODO Auto-generated destructor stub\n}\n\n", "meta": {"hexsha": "f43066aaf190b209806e4e8deb87c2a03d03ba21", "size": 7177, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Mesh.cpp", "max_stars_repo_name": "epsilonleqzero/Finite-Element-CPP-Nonlinear", "max_stars_repo_head_hexsha": "1b8c061523f18b74413cfaa3df4acb237f7a5860", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-20T19:04:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-20T19:04:17.000Z", "max_issues_repo_path": "src/Mesh.cpp", "max_issues_repo_name": "tmkwan/Finite-Element-CPP-Nonlinear", "max_issues_repo_head_hexsha": "1b8c061523f18b74413cfaa3df4acb237f7a5860", "max_issues_repo_licenses": ["MIT"], "max_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.cpp", "max_forks_repo_name": "tmkwan/Finite-Element-CPP-Nonlinear", "max_forks_repo_head_hexsha": "1b8c061523f18b74413cfaa3df4acb237f7a5860", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-08-04T04:43:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-04T04:32:46.000Z", "avg_line_length": 28.939516129, "max_line_length": 80, "alphanum_fraction": 0.6541730528, "num_tokens": 2276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5112260052248894}}
{"text": "// ExprFormulaTester.cpp : This file contains the 'main' function. Program execution begins and ends there.\r\n//\r\n\r\n#include <iostream>\r\n\r\n#include \"AltNum\\MediumDec.hpp\"\r\n//#include <boost/timer/timer.hpp>\r\nusing MediumDec = BlazesRusCode::MediumDec;\r\n\r\n#ifdef BlazesRus_PerformMediumFormulaTests\r\n#include \"AltNum\\AltNumDebug.hpp\"\r\n#include \"Formulas\\MediumDecFormula.hpp\"\r\nusing MediumDecFormula = BlazesRusCode::MediumDecFormula;\r\n#endif\r\n#include \"AltNum\\FloatingOperations.hpp\"\r\n//#include \"Databases\\IntFormula.hpp\"\r\n//using IntFormula = BlazesRusCode::IntFormula;\r\n//#include \"Databases\\DoubleFormula.hpp\"\r\n//using DoubleFormula = BlazesRusCode::DoubleFormula;\r\n\r\n\r\n#include \"AltNum\\AltDec.hpp\"\r\n#include \"AltNum\\MixedDec.hpp\"\r\nusing AltDec = BlazesRusCode::AltDec;\r\nusing MixedDec = BlazesRusCode::MixedDec;\r\n#include <boost/math/constants/constants.hpp>\r\n#include <sstream>\r\n#include <iomanip>\r\n\r\n#include <Windows.h>\r\n\r\nint main()\r\n{\r\n#ifdef BlazesRus_PerformMediumFormulaTests\r\n    MediumDec targetVal;// = \"5.5\";\r\n    MediumDec rightVal;// = \"1.25\";\r\n    MediumDec altResult; //= targetVal - rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << std::endl;\r\n    //altResult = targetVal + rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << std::endl;\r\n\r\n    //altResult = targetVal*rightVal;\r\n    //double floatingVal = (double)targetVal * (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" * \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\"<<floatingVal<< std::endl;\r\n    //altResult = targetVal/rightVal;\r\n    //floatingVal = (double)targetVal / (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" / \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - 3;\r\n    //std::cout << targetVal.ToString() << \" - 3 = \" << altResult.ToString() << std::endl;\r\n    //altResult = targetVal + 3;\r\n    //std::cout << targetVal.ToString() << \" + 3 = \" << altResult.ToString() << std::endl;\r\n    //altResult = targetVal * 3;\r\n    //std::cout << targetVal.ToString() << \" * 3 = \" << altResult.ToString() << std::endl;\r\n    //altResult = targetVal / 3;\r\n    //std::cout << targetVal.ToString() << \" / 3 = \" << altResult.ToString() << std::endl;\r\n    //altResult = targetVal; altResult -= rightVal;\r\n    //std::cout << targetVal.ToString() << \" -= :\" << rightVal.ToString() << \" = \" << altResult.ToString() << std::endl;\r\n    //altResult = targetVal; altResult += rightVal;\r\n    //std::cout << targetVal.ToString() << \" += :\" << rightVal.ToString() << \" = \" << altResult.ToString() << std::endl;\r\n    //altResult = targetVal; altResult *= rightVal;\r\n    //std::cout << targetVal.ToString() << \" *= :\" << rightVal.ToString() << \" = \" << altResult.ToString() << std::endl;\r\n    //altResult = targetVal; altResult /= rightVal;\r\n    //std::cout << targetVal.ToString() << \" /= :\" << rightVal.ToString() << \" = \" << altResult.ToString() << std::endl;\r\n    //altResult = targetVal; altResult -= 3;\r\n    //std::cout << targetVal.ToString() << \" -= 3 :\" << altResult.ToString() << std::endl;\r\n    //altResult = targetVal; altResult += 3;\r\n    //std::cout << targetVal.ToString() << \" += 3 :\" << altResult.ToString() << std::endl;\r\n    //altResult = targetVal; altResult *= 3;\r\n    //std::cout << targetVal.ToString() << \" *= 3 :\" << altResult.ToString() << std::endl;\r\n    //altResult = targetVal; altResult /= 3;\r\n    //std::cout << targetVal.ToString() << \" /= 3 : \" << altResult.ToString() << std::endl;\r\n    //bool boolCheck = targetVal < rightVal;\r\n    //std::cout << targetVal.ToString() << \" < \" << rightVal.ToString() << \" = \" << boolCheck << std::endl;\r\n    //boolCheck = targetVal <= rightVal;\r\n    //std::cout << targetVal.ToString() << \" <= \" << rightVal.ToString() << \" = \" << boolCheck << std::endl;\r\n    //boolCheck = targetVal > rightVal;\r\n    //std::cout << targetVal.ToString() << \" > \" << rightVal.ToString() << \" = \" << boolCheck << std::endl;\r\n    //boolCheck = targetVal >= rightVal;\r\n    //std::cout << targetVal.ToString() << \" >= \" << rightVal.ToString() << \" = \" << boolCheck << std::endl;\r\n    ////-----------------------------------------------------------------------------------------------------------\r\n    ////All multiplication & Division tests now successful\r\n    //targetVal = \"0.5\";\r\n    //rightVal = \"0.25\";\r\n    //altResult = targetVal * rightVal;\r\n    //floatingVal = (double)targetVal * (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" * \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal / rightVal;\r\n    //floatingVal = (double)targetVal / (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" / \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //altResult = targetVal + rightVal;\r\n    //floatingVal = (double)targetVal + (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - rightVal;\r\n    //floatingVal = (double)targetVal - (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //targetVal = \"1.5\";\r\n    //altResult = targetVal * rightVal;\r\n    //floatingVal = (double)targetVal * (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" * \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal / rightVal;\r\n    //floatingVal = (double)targetVal / (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" / \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //targetVal = \"0.5\";\r\n    //rightVal = \"2.5\";\r\n    //altResult = targetVal * rightVal;\r\n    //floatingVal = (double)targetVal * (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" * \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal / rightVal;\r\n    //floatingVal = (double)targetVal / (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" / \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //altResult = targetVal + rightVal;\r\n    //floatingVal = (double)targetVal + (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - rightVal;\r\n    //floatingVal = (double)targetVal - (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //rightVal = \"2.0\";\r\n    //altResult = targetVal * rightVal;\r\n    //floatingVal = (double)targetVal * (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" * \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal / rightVal;\r\n    //floatingVal = (double)targetVal / (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" / \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //altResult = targetVal + rightVal;\r\n    //floatingVal = (double)targetVal + (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - rightVal;\r\n    //floatingVal = (double)targetVal - (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //targetVal = \"4.0\";\r\n    //rightVal = \"2.0\";\r\n    //altResult = targetVal * rightVal;\r\n    //floatingVal = (double)targetVal * (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" * \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal / rightVal;\r\n    //floatingVal = (double)targetVal / (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" / \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //altResult = targetVal + rightVal;\r\n    //floatingVal = (double)targetVal + (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - rightVal;\r\n    //floatingVal = (double)targetVal - (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //rightVal = \"0.5\";\r\n    //altResult = targetVal * rightVal;\r\n    //floatingVal = (double)targetVal * (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" * \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal / rightVal;\r\n    //floatingVal = (double)targetVal / (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" / \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //std::cout << \"------Additional Addition/Subtraction Tests(For Negative numbers etc)--------------------\" << std::endl;\r\n\r\n    //targetVal = \"-0.5\";\r\n    //rightVal = \"-0.25\";\r\n    //altResult = targetVal + rightVal;\r\n    //floatingVal = (double)targetVal + (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - rightVal;\r\n    //floatingVal = (double)targetVal - (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //rightVal = \"0.25\";\r\n    //altResult = targetVal + rightVal;\r\n    //floatingVal = (double)targetVal + (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - rightVal;\r\n    //floatingVal = (double)targetVal - (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //targetVal = \"-1.5\";\r\n    //altResult = targetVal + rightVal;\r\n    //floatingVal = (double)targetVal + (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - rightVal;\r\n    //floatingVal = (double)targetVal - (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //targetVal = \"-0.5\";\r\n    //rightVal = \"-2.5\";\r\n    //altResult = targetVal + rightVal;\r\n    //floatingVal = (double)targetVal + (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - rightVal;\r\n    //floatingVal = (double)targetVal - (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //rightVal = \"2.5\";\r\n    //altResult = targetVal + rightVal;\r\n    //floatingVal = (double)targetVal + (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - rightVal;\r\n    //floatingVal = (double)targetVal - (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n\r\n    //rightVal = \"-2.0\";\r\n    //altResult = targetVal + rightVal;\r\n    //floatingVal = (double)targetVal + (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - rightVal;\r\n    //floatingVal = (double)targetVal - (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n\r\n    //targetVal = \"-4.0\";\r\n    //rightVal = \"-2.0\";\r\n    //altResult = targetVal + rightVal;\r\n    //floatingVal = (double)targetVal + (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - rightVal;\r\n    //floatingVal = (double)targetVal - (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //rightVal = \"0.5\";\r\n    //altResult = targetVal + rightVal;\r\n    //floatingVal = (double)targetVal + (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - rightVal;\r\n    //floatingVal = (double)targetVal - (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //rightVal = \"-0.5\";\r\n    //altResult = targetVal + rightVal;\r\n    //floatingVal = (double)targetVal + (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" + \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n    //altResult = targetVal - rightVal;\r\n    //floatingVal = (double)targetVal - (double)rightVal;\r\n    //std::cout << targetVal.ToString() << \" - \" << rightVal.ToString() << \" = \" << altResult.ToString() << \" FloatResult:\" << floatingVal << std::endl;\r\n\r\n    //std::cout << \"---------------Log Tests------------------------------\" << std::endl;\r\n    //targetVal = MediumDec::FiveThousandth;\r\n    //floatingVal = 0.005;\r\n    //double floatingRes;\r\n    //do \r\n    //{\r\n    //    floatingRes = log(floatingVal);\r\n    //    std::cout << \"Builtin-Ln(\" << floatingVal << \") = \" << floatingRes;\r\n    //    floatingRes = BlazesFloatingCode::LnRefV2(floatingVal);\r\n    //    std::cout << \" Ln(value) =\" << floatingRes << std::endl;\r\n\r\n    //    altResult = MediumDec::LnRef(targetVal);\r\n    //    std::cout << \"(MediumDec)Ln(\" << targetVal.ToString() << \")= \" << altResult.ToString() << std::endl;\r\n    //    altResult = MediumDec::LnRefV2(targetVal);\r\n    //    std::cout << \"(MediumDec)LnV2(\" << targetVal.ToString() << \")= \" << altResult.ToString() << std::endl;\r\n    //    targetVal += MediumDec::FiveThousandth; floatingVal += 0.005;\r\n    //} while (targetVal < MediumDec::One);\r\n    std::cout << \"---------------Testing Formula Code-------------------\" << std::endl;\r\n    //std::cout << \"-------------------------Formula Code Tests---------------------------------\" << std::endl;\r\n    //IntFormula IntFormTest = \"(5+5)^2\";\r\n    //tsl::ordered_map<std::string, int> IntValueDefinitions;\r\n    //std::cout << IntFormTest.ToString() << \" = \" << IntFormTest.EvalValues(IntValueDefinitions) << std::endl;\r\n    //IntValueDefinitions.insert_or_assign(\"x\", 2);\r\n    //IntFormTest = \"5+10x\";\r\n    //std::cout << IntFormTest.ToString() << \" = \" << IntFormTest.EvalValues(IntValueDefinitions) << std::endl;\r\n\r\n    tsl::ordered_map<std::string, MediumDec> ValueDefinitions;\r\n    ValueDefinitions.insert_or_assign(\"x\", MediumDec::Two);\r\n    MediumDecFormula AltFormTest = \"x+x\";//\"(x+1)^(5+4)\";\r\n\r\n    try\r\n    {\r\n        std::cout << \"(MediumDecFormula) \" << AltFormTest.ToString() << std::endl;\r\n        AltFormTest.ReplaceVariablesWithValues(ValueDefinitions);\r\n        std::cout << \" = \" << AltFormTest.ToString() << std::endl;\r\n        AltFormTest.EvaluateOperations();\r\n        std::cout << \" = \" << AltFormTest.ToString() << std::endl;\r\n\r\n        //AltFormTest = \"9.0 thBaseLog 4\";\r\n        //std::cout << \"(MediumDecFormula) \" << AltFormTest.ToString() << std::endl;\r\n        //AltFormTest.ReplaceVariablesWithValues(ValueDefinitions);\r\n        //std::cout << \" = \" << AltFormTest.ToString() << std::endl;\r\n        //AltFormTest.EvaluateOperations();\r\n        //std::cout << \" = \" << AltFormTest.ToString() << std::endl;\r\n\r\n        AltFormTest = \"(x+1)^(5+4/0.5-2)\";\r\n        std::cout << \"(MediumDecFormula) \" << AltFormTest.ToString() << std::endl;\r\n        AltFormTest.ReplaceVariablesWithValues(ValueDefinitions);\r\n        std::cout << \" = \" << AltFormTest.ToString() << std::endl;\r\n        AltFormTest.EvaluateOperations();\r\n        std::cout << \" = \" << AltFormTest.ToString() << std::endl;\r\n\r\n        AltFormTest = \"(x+1)^(5+4*0.5-2)\";\r\n        std::cout << \"(MediumDecFormula) \" << AltFormTest.ToString() << std::endl;\r\n        AltFormTest.ReplaceVariablesWithValues(ValueDefinitions);\r\n        std::cout << \" = \" << AltFormTest.ToString() << std::endl;\r\n        AltFormTest.EvaluateOperations();\r\n        std::cout << \" = \" << AltFormTest.ToString() << std::endl;\r\n    }\r\n    catch (const std::runtime_error& re)\r\n    {\r\n        std::cerr << \"Runtime error: \" << re.what() << std::endl;\r\n    }\r\n    catch (const std::exception& ex)\r\n    {\r\n        // specific handling for all exceptions extending std::exception, except\r\n        // std::runtime_error which is handled explicitly\r\n        std::cerr << \"Error occurred: \" << ex.what() << std::endl;\r\n    }\r\n    catch(...)\r\n    {\r\n        std::cout << \"Unknown exception\" << std::endl;\r\n    }\r\n#else\r\n    std::ostringstream streamObj;\r\n    streamObj << std::fixed << std::setprecision(99);\r\n#ifdef BlazesRus_PITests\r\n    streamObj << \"HiperCalc result:18.84955592153875943077586029967701730518301639625063492584966755384689843771725399176820895205270241\" << std::endl;\r\n\r\n    double LAsDouble = boost::math::constants::pi<double>()*2.0;\r\n    LAsDouble *= 3.0;\r\n    float LAsFloat = boost::math::constants::pi<float>()*2.0f;\r\n    LAsFloat *= 3.0f;\r\n    /*streamObj << \"-------Boost PI based Tests------\" << std::endl;*/\r\n    streamObj << \"Double Result:\" << LAsDouble << std::endl;\r\n    streamObj << \"Float Result:\" << LAsFloat << std::endl;\r\n    //streamObj << \"---------------HiperCalc display based FloatingPoint Tests------------------\" << std::endl;\r\n    //LAsDouble = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068 * 2.0;\r\n    //LAsFloat = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068f * 2.0f;\r\n    //LAsDouble *= 3.0;\r\n    //LAsFloat *= 3.0f;\r\n    //streamObj << \"Double Result:\" << LAsDouble << std::endl;\r\n    //streamObj << \"Float Result:\" << LAsFloat << std::endl;\r\n    streamObj << \"-------AltNum Tests------\" << std::endl;\r\n    AltDec LAlt;\r\n    LAlt.SetPiVal(2);\r\n    LAlt *= 3;\r\n    streamObj << \"AltDec Result:\" << LAlt.ToString() << std::endl;\r\n    MixedDec LMixed;\r\n    LMixed.SetPiVal(2);\r\n    LMixed *= 3;\r\n    streamObj << \"MixedDec Result:\" << LMixed.ToString() << std::endl;\r\n#elif defined(BlazesRus_PerformDualAltFormulaTests)\r\n\r\n#else\r\n    AltDec LAlt;\r\n    LAlt.SetAsApproachingAwayFromValue(1);\r\n    AltDec RAlt;\r\n    LAlt.SetAsApproachingValueFromRight(-5);\r\n    AltDec AltResult = LAlt+RAlt;\r\n    streamObj << LAlt.ToString() <<\" + \"<< RAlt.ToString() << \" = \" << AltResult.ToString()<< std::endl;\r\n#endif\r\n    ::OutputDebugStringA(streamObj.str().c_str());//Outputing to debug output based on https://www.codeproject.com/Articles/1053/Using-an-Output-Stream-for-Debugging\r\n#endif\r\n}\r\n", "meta": {"hexsha": "b4c645d5460ef4460e24361b2fc46a6377bda946", "size": 20532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ExprFormulaTester/ExprFormulaTester.cpp", "max_stars_repo_name": "BlazesRus/BlazesRusSharedCode", "max_stars_repo_head_hexsha": "1925f11afca9476bbbd79df35f77e143418b4799", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-04-05T03:59:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-16T08:39:39.000Z", "max_issues_repo_path": "ExprFormulaTester/ExprFormulaTester.cpp", "max_issues_repo_name": "BlazesRus/BlazesRusSharedCode", "max_issues_repo_head_hexsha": "1925f11afca9476bbbd79df35f77e143418b4799", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-28T00:07:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-28T00:07:53.000Z", "max_forks_repo_path": "ExprFormulaTester/ExprFormulaTester.cpp", "max_forks_repo_name": "BlazesRus/MultiPlatformGlobalCode", "max_forks_repo_head_hexsha": "1925f11afca9476bbbd79df35f77e143418b4799", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.0, "max_line_length": 166, "alphanum_fraction": 0.5888369375, "num_tokens": 5618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5112260052248894}}
{"text": "//\n//  EigenLibSolver.hpp\n//  IPC\n//\n//  Created by Minchen Li on 6/30/18.\n//\n#pragma once\n\n#include \"LinSysSolver.hpp\"\n\n#include <Eigen/Eigen>\n\n#include <vector>\n#include <set>\n\nnamespace IPC {\n\ntemplate <typename vectorTypeI, typename vectorTypeS>\nclass EigenLibSolver : public LinSysSolver<vectorTypeI, vectorTypeS> {\n    typedef LinSysSolver<vectorTypeI, vectorTypeS> Base;\n\nprotected:\n    Eigen::SparseMatrix<double> coefMtr;\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> simplicialLDLT;\n\npublic:\n    LinSysSolverType type() const override { return LinSysSolverType::EIGEN; }\n\n    void set_pattern(const std::vector<std::set<int>>& vNeighbor, const std::set<int>& fixedVert) override;\n    void set_pattern(const Eigen::SparseMatrix<double>& mtr) override; //NOTE: mtr must be SPD\n\n    void analyze_pattern(void) override;\n\n    bool factorize(void) override;\n\n    void solve(Eigen::VectorXd& rhs, Eigen::VectorXd& result) override;\n\n    double coeffMtr(int rowI, int colI) const override;\n\n    void setZero(void) override;\n\n    virtual void setCoeff(int rowI, int colI, double val) override;\n\n    virtual void addCoeff(int rowI, int colI, double val) override;\n\n    virtual void setUnit_row(int rowI) override;\n\n    virtual void setUnit_col(int colI, const std::set<int>& rowVIs) override;\n};\n\n} // namespace IPC\n", "meta": {"hexsha": "e7589faaa6612574615404bdbd72da1d49d689e9", "size": 1326, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/LinSysSolver/EigenLibSolver.hpp", "max_stars_repo_name": "Andlon/IPC", "max_stars_repo_head_hexsha": "3cdc29dac8486c0d62425290b4c23d03ee1d64b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2020-07-03T14:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:01:11.000Z", "max_issues_repo_path": "src/LinSysSolver/EigenLibSolver.hpp", "max_issues_repo_name": "Andlon/IPC", "max_issues_repo_head_hexsha": "3cdc29dac8486c0d62425290b4c23d03ee1d64b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T15:56:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:56:39.000Z", "max_forks_repo_path": "src/LinSysSolver/EigenLibSolver.hpp", "max_forks_repo_name": "Andlon/IPC", "max_forks_repo_head_hexsha": "3cdc29dac8486c0d62425290b4c23d03ee1d64b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T05:04:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:09:23.000Z", "avg_line_length": 25.5, "max_line_length": 107, "alphanum_fraction": 0.7285067873, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5112260000795745}}
{"text": "#include <stan/math/mix/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <test/unit/math/rev/scal/fun/util.hpp>\n#include <test/unit/math/mix/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdLbeta, FvarVar_FvarVar_1stDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  fvar<var> x(3.0, 1.3);\n  fvar<var> z(6.0, 1.0);\n  fvar<var> a = lbeta(x, z);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val());\n  EXPECT_FLOAT_EQ(\n      1.3 * digamma(3.0) + digamma(6.0) - (1.0 + 1.3) * digamma(3.0 + 6.0),\n      a.d_.val());\n\n  AVEC y = createAVEC(x.val_, z.val_);\n  VEC g;\n  a.val_.grad(y, g);\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), g[0]);\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), g[1]);\n}\nTEST(AgradFwdLbeta, FvarVar_Double_1stDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  fvar<var> x(3.0, 1.3);\n  double z(6.0);\n  fvar<var> a = lbeta(x, z);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val());\n  EXPECT_FLOAT_EQ(1.3 * digamma(3.0) - (1.3) * digamma(3.0 + 6.0), a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.val_.grad(y, g);\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), g[0]);\n}\nTEST(AgradFwdLbeta, Double_FvarVar_1stDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  double x(3.0);\n  fvar<var> z(6.0, 1.0);\n  fvar<var> a = lbeta(x, z);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(3.0 + 6.0), a.d_.val());\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.val_.grad(y, g);\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), g[0]);\n}\nTEST(AgradFwdLbeta, FvarVar_FvarVar_2ndDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  fvar<var> x(3.0, 1.3);\n  fvar<var> z(6.0, 1.0);\n  fvar<var> a = lbeta(x, z);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val());\n  EXPECT_FLOAT_EQ(\n      1.3 * digamma(3.0) + digamma(6.0) - (1.0 + 1.3) * digamma(3.0 + 6.0),\n      a.d_.val());\n\n  AVEC y = createAVEC(x.val_, z.val_);\n  VEC g;\n  a.d_.grad(y, g);\n  EXPECT_FLOAT_EQ(1.3 * 0.39493407 - 2.3 * 0.11751201, g[0]);\n  EXPECT_FLOAT_EQ(0.18132296 - 2.3 * 0.11751201, g[1]);\n}\nTEST(AgradFwdLbeta, FvarVar_Double_2ndDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  fvar<var> x(3.0, 1.3);\n  double z(6.0);\n  fvar<var> a = lbeta(x, z);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val());\n  EXPECT_FLOAT_EQ(1.3 * digamma(3.0) - (1.3) * digamma(3.0 + 6.0), a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.d_.grad(y, g);\n  EXPECT_FLOAT_EQ(1.3 * 0.39493407 - 1.3 * 0.11751201, g[0]);\n}\nTEST(AgradFwdLbeta, Double_FvarVar_2ndDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  double x(3.0);\n  fvar<var> z(6.0, 1.0);\n  fvar<var> a = lbeta(x, z);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(3.0 + 6.0), a.d_.val());\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.d_.grad(y, g);\n  EXPECT_FLOAT_EQ(0.18132296 - 0.11751201, g[0]);\n}\nTEST(AgradFwdLbeta, FvarFvarVar_FvarFvarVar_1stDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x, y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.11751202, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_, y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p, g);\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), g[0]);\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), g[1]);\n}\nTEST(AgradFwdLbeta, FvarFvarVar_Double_1stDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  double y(6.0);\n\n  fvar<fvar<var> > a = lbeta(x, y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p, g);\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), g[0]);\n}\nTEST(AgradFwdLbeta, Double_FvarFvarVar_1stDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  double x(3.0);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x, y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p, g);\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), g[0]);\n}\nTEST(AgradFwdLbeta, FvarFvarVar_FvarFvarVar_2ndDeriv_x) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x, y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.11751202, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_, y.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p, g);\n  EXPECT_FLOAT_EQ(0.39493407 - 0.11751201, g[0]);\n  EXPECT_FLOAT_EQ(-0.11751202, g[1]);\n}\nTEST(AgradFwdLbeta, FvarFvarVar_FvarFvarVar_2ndDeriv_y) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x, y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.11751202, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_, y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p, g);\n  EXPECT_FLOAT_EQ(-0.11751202, g[0]);\n  EXPECT_FLOAT_EQ(0.18132296 - 0.11751201, g[1]);\n}\nTEST(AgradFwdLbeta, FvarFvarVar_Double_2ndDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  double y(6.0);\n\n  fvar<fvar<var> > a = lbeta(x, y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p, g);\n  EXPECT_FLOAT_EQ(0.39493407 - 0.11751201, g[0]);\n}\nTEST(AgradFwdLbeta, Double_FvarFvarVar_2ndDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  double x(3.0);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x, y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p, g);\n  EXPECT_FLOAT_EQ(0.18132296 - 0.11751201, g[0]);\n}\nTEST(AgradFwdLbeta, FvarFvarVar_FvarFvarVar_3rdDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x, y);\n\n  AVEC p = createAVEC(x.val_.val_, y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p, g);\n  EXPECT_FLOAT_EQ(0.013793319, g[0]);\n  EXPECT_FLOAT_EQ(0.013793319, g[1]);\n}\nTEST(AgradFwdLbeta, FvarFvarVar_Double_3rdDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n  x.d_.val_ = 1.0;\n\n  double y(6.0);\n\n  fvar<fvar<var> > a = lbeta(x, y);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p, g);\n  EXPECT_FLOAT_EQ(-0.140320487123420796890184645287, g[0]);\n}\nTEST(AgradFwdLbeta, Double_FvarFvarVar_3rdDeriv) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n  using stan::math::var;\n\n  double x(3.0);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n  y.val_.d_ = 1.0;\n\n  fvar<fvar<var> > a = lbeta(x, y);\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p, g);\n  EXPECT_FLOAT_EQ(-0.0189964130493467228161105712126, g[0]);\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) {\n  lbeta_fun lbeta_;\n  test_nan_mix(lbeta_, 3.0, 5.0, false);\n}\n", "meta": {"hexsha": "68f401b39840e8db06a9c92be3f42024b2648154", "size": 9525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/mix/scal/fun/lbeta_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/mix/scal/fun/lbeta_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/mix/scal/fun/lbeta_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": 25.5361930295, "max_line_length": 79, "alphanum_fraction": 0.6347506562, "num_tokens": 4007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5112259949342596}}
{"text": "/**\n * for body lean and angular velocity,\n * using kalman filter\n */\n#pragma once\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <iostream>\n#include \"types/SensorValues.hpp\"\n#include \"perception/kinematics/Kinematics.hpp\"\n#include \"motion/touch/FeetState.hpp\"\n\nusing namespace boost::numeric::ublas;\nusing namespace std;\n\nclass TorsoStateFilter {\n   public:\n      explicit TorsoStateFilter();\n      matrix<float> update(matrix<float> obs, FeetState feetState);\n      void init(float dt, float obsAngleSD, float obsVelSD, bool frontal);\n      ~TorsoStateFilter();\n\n   private:\n      matrix<float> est;\n      matrix<float> estBar;\n      matrix<float> covEst;\n      matrix<float> covEstBar;\n      matrix<float> covR;\n      matrix<float> covQ;\n\n      float dt;\n      bool frontal;\n\n      float getFulcrum(matrix<float> obs, FeetState feetState);\n};\n", "meta": {"hexsha": "0b67b4df61b11ee85cdcccbb84cae715011f94c8", "size": 888, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/External/unsw/unsw/motion/touch/TorsoStateFilter.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/motion/touch/TorsoStateFilter.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/motion/touch/TorsoStateFilter.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": 24.6666666667, "max_line_length": 74, "alphanum_fraction": 0.6959459459, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5112259949342595}}
{"text": "#include \"Damped_Rational.hxx\"\n\n#include <El.hpp>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <vector>\n\n// Rescaled Laguerre\nstd::vector<Boost_Float>\nsample_scalings(const std::vector<Boost_Float> &points,\n                const Damped_Rational &damped_rational)\n{\n  std::vector<Boost_Float> result;\n  result.reserve(points.size());\n  for(auto &point : points)\n    {\n      Boost_Float numerator(damped_rational.constant\n                            * pow(damped_rational.base, point));\n      Boost_Float denominator(1);\n      for(auto &pole : damped_rational.poles)\n        {\n          denominator *= (point - pole);\n        }\n      result.emplace_back(to_string(numerator / denominator));\n    }\n  return result;\n}\n", "meta": {"hexsha": "8088bae5bc15b7315f8f57f61bef8afb77c9f3c5", "size": 726, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/sdp_read/sample_scalings.cxx", "max_stars_repo_name": "ChrisPattison/sdpb", "max_stars_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2015-02-10T15:45:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T07:45:01.000Z", "max_issues_repo_path": "src/sdp_read/sample_scalings.cxx", "max_issues_repo_name": "ChrisPattison/sdpb", "max_issues_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 58.0, "max_issues_repo_issues_event_min_datetime": "2015-02-27T10:03:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-10T04:21:42.000Z", "max_forks_repo_path": "src/sdp_read/sample_scalings.cxx", "max_forks_repo_name": "ChrisPattison/sdpb", "max_forks_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T11:11:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:59:42.000Z", "avg_line_length": 25.0344827586, "max_line_length": 64, "alphanum_fraction": 0.652892562, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931457, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5112259897889444}}
{"text": "/**\n * @author Alessandro Bianco\n */\n\n/**\n * @addtogroup DFNs\n * @{\n */\n\n#ifndef BUNDLEADJUSTMENT_SVDDECOMPOSITION_HPP\n#define BUNDLEADJUSTMENT_SVDDECOMPOSITION_HPP\n\n#include \"BundleAdjustmentInterface.hpp\"\n#include <Types/CPP/FramesSequence.hpp>\n#include <Types/CPP/PosesSequence.hpp>\n#include <Helpers/ParametersListHelper.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <yaml-cpp/yaml.h>\n#include <Eigen/Dense>\n#include <Converters/CorrespondenceMaps2DSequenceToMatConverter.hpp>\n\nnamespace CDFF\n{\nnamespace DFN\n{\nnamespace BundleAdjustment\n{\n\t/**\n\t * Implementation of the factorization algorithm by Tomasi and Kanade\n\t *\n\t * @param leftCameraMatrix: the camera matrix of the left camera\n\t * @param rightCameraMatrix: the camera maxtrix of the right camera\n\t */\n\tclass SvdDecomposition : public BundleAdjustmentInterface\n\t{\n\t\tpublic:\n\n\t\t\tSvdDecomposition();\n\t\t\tvirtual ~SvdDecomposition();\n\n\t\t\tvirtual void configure() override;\n\t\t\tvirtual void process() override;\n\n\t\tprivate:\n\t\t\ttypedef Eigen::Transform<float, 3, Eigen::Affine, Eigen::DontAlign> AffineTransform;\n\n\t\t\t//DFN Parameters\n\t\t\tstruct CameraMatrix\n\t\t\t{\n\t\t\t\tfloat focalLengthX;\n\t\t\t\tfloat focalLengthY;\n\t\t\t\tfloat principalPointX;\n\t\t\t\tfloat principalPointY;\n\t\t\t};\n\n\t\t\tstruct SvdDecompositionOptionsSet\n\t\t\t{\n\t\t\t\tCameraMatrix leftCameraMatrix;\n\t\t\t\tCameraMatrix rightCameraMatrix;\n\t\t\t\tfloat baseline;\n\t\t\t};\n\n\t\t\tHelpers::ParametersListHelper parametersHelper;\n\t\t\tSvdDecompositionOptionsSet parameters;\n\t\t\tstatic const SvdDecompositionOptionsSet DEFAULT_PARAMETERS;\n\n\t\t\t//External conversion helpers\n\t\t\tConverters::CorrespondenceMaps2DSequenceToMatConverter correspondencesSequenceConverter;\n\n\t\t\t//Configuration Parameters conversion\n\t\t\tcv::Mat leftCameraMatrix, rightCameraMatrix;\n\t\t\tcv::Mat leftCameraMatrixInverse, rightCameraMatrixInverse;\n\t\t\tcv::Mat leftAbsoluteConicImage,\trightAbsoluteConicImage;\n\t\t\tcv::Mat CameraMatrixToCvMatrix(const CameraMatrix& cameraMatrix);\n\n\t\t\t//Internal Type Conversion Methods\n\t\t\tvoid ConvertRotationTranslationMatricesToPosesSequence(cv::Mat translationMatrix, cv::Mat rotationMatrix, PoseWrapper::Poses3DSequence& posesSequence);\n\n\t\t\t//Core Computation Methods\n\t\t\tvoid DecomposeMeasurementMatrix(cv::Mat measurementMatrix, cv::Mat& compatibleRotationMatrix, cv::Mat& compatiblePositionMatrix);\n\t\t\tcv::Mat ComputeTranslationMatrix(cv::Mat centroidMatrix);\n\t\t\tcv::Mat ComputeMeasuresCentroid(cv::Mat measurementMatrix);\n\t\t\tvoid CentreMeasurementMatrix(cv::Mat centroidMatrix, cv::Mat& measurementMatrix);\n\t\t\tcv::Mat ComputeMetricRotationMatrix(cv::Mat rotationMatrix, int poseIndex);\n\n\t\t\t//Validation Methods\n\t\t\tvoid ValidateParameters();\n\t\t\tvoid ValidateInputs();\n\t};\n}\n}\n}\n\n#endif // BUNDLEADJUSTMENT_SVDDECOMPOSITION_HPP\n\n/** @} */\n", "meta": {"hexsha": "b924c4b4cab578017de6f490209beb0fb938e921", "size": 2765, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "DFNs/BundleAdjustment/SvdDecomposition.hpp", "max_stars_repo_name": "H2020-InFuse/cdff", "max_stars_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-26T15:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T07:39:01.000Z", "max_issues_repo_path": "DFNs/BundleAdjustment/SvdDecomposition.hpp", "max_issues_repo_name": "H2020-InFuse/cdff", "max_issues_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "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": "DFNs/BundleAdjustment/SvdDecomposition.hpp", "max_forks_repo_name": "H2020-InFuse/cdff", "max_forks_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-06T12:09:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T12:09:05.000Z", "avg_line_length": 28.2142857143, "max_line_length": 154, "alphanum_fraction": 0.7775768535, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5112259897889443}}
{"text": "#include \"sfge/graphics/light.hpp\"\r\n#include \"sfge/math/convex_hull.hpp\"\r\n#include \"sfge/math/intersections.hpp\"\r\n#include \"sfge/math/point.hpp\"\r\n#include \"sfge/math/vector_utilities.hpp\"\r\n\r\n#include <vector>\r\n#include <iterator>\r\n\r\n#include <boost/array.hpp>\r\n\r\n#include <SFML/Graphics/ConvexShape.hpp>\r\n\r\n#include <sfge/math/circle.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\nusing namespace sf;\r\n\r\nnamespace sfge\r\n{\r\n\r\ntypedef vector<Edge2f> EdgeList;\r\n\r\ntypedef Point<float, float> Pointf;\r\ntypedef vector<Pointf> PointfList;\r\n\r\ntypedef Point<float, int> PointInt;\r\ntypedef vector<PointInt> PointIntList;\r\n\r\ntypedef ConvexHull<PointInt> ConvexHullT;\r\n\r\nLight::Light()\r\n\t: mShadowOutline(0, 0, 0, 0), mShadowFill(0, 0, 0, 255)\r\n{\r\n}\r\n\r\nLight::Light(const sf::Vector2f &pos, float rad)\r\n\t: mLightDesc(pos, rad), mShadowOutline(0, 0, 0, 0), mShadowFill(0, 0, 0, 255)\r\n{\r\n}\r\n\r\nvoid Light::reset()\r\n{\r\n\tswap(mShadows, Shadows());\r\n\tmIsInside = false;\r\n}\r\n\r\nvoid Light::addOccluders(const Shapes &occluders)\r\n{\r\n\tShapes _occluders(occluders);\r\n\tsort(_occluders.begin(), _occluders.end(),\r\n\t\t[&] (const ShapePtr &o1, const ShapePtr &o2) -> bool\r\n\t\t{\r\n\t\t\tconst float\to1d = sqrDistance(o1->getPosition(), mLightDesc.mPos),\r\n\t\t\t\t\t\to2d = sqrDistance(o2->getPosition(), mLightDesc.mPos);\r\n\t\t\treturn o1d < o2d;\r\n\t\t} );\r\n\r\n\tShapes::const_iterator it = _occluders.begin();\r\n\twhile (it != _occluders.end() && addOccluder(*(*it)))\r\n\t\t++it;\r\n}\r\n\r\nbool Light::addOccluder(const Shape &occluder)\r\n{\r\n\t// Setup\r\n\tif (mIsInside)\r\n\t\treturn false;\r\n\r\n\tconst unsigned int ptsCount = occluder.getPointCount();\r\n\tif (ptsCount < 2)\r\n\t\treturn true;\r\n\r\n\tconst sf::Vector2f\toccLocalLPos\t= occluder.getInverseTransform().transformPoint(mLightDesc.mPos);\r\n\tconst float\t\tscaledRadius\t\t= mLightDesc.mRadius;\r\n\tconst float\t\tsqrRadius\t\t\t= scaledRadius * scaledRadius;\r\n\r\n\tEdgeList edges;\r\n\tedges.reserve(ptsCount);\r\n\tPointfList points;\r\n\tpoints.reserve(ptsCount);\r\n\r\n\t// Generate occluder's edges & store points\r\n\tfor (unsigned int ptIdx = 0; ptIdx != ptsCount - 1; ptIdx++)\r\n\t{\r\n\t\tconst Vector2f &pt1 = occluder.getPoint(ptIdx);\r\n\t\tconst Vector2f &pt2 = occluder.getPoint(ptIdx + 1);\r\n\t\tedges.push_back(Edge2f(pt1, pt2));\r\n\r\n\t\tsf::Vector2f diff(occLocalLPos - pt1);\r\n\t\tpoints.push_back(Pointf(pt1, dot(diff, diff)));\r\n\t}\r\n\tconst Vector2f &lastPoint = occluder.getPoint(ptsCount - 1);\r\n\tedges.push_back(Edge2f(lastPoint, points[0].mPos, true));\r\n\r\n\tsf::Vector2f diff(occLocalLPos - lastPoint);\r\n\tpoints.push_back(Pointf(lastPoint, dot(diff, diff)));\r\n\r\n\t// Check that occluder is at least partially within light radius\r\n\tint pointsWithinLightRad = 0;\r\n\tfor (PointfList::const_iterator it = points.begin(); it != points.end(); ++it)\r\n\t{\r\n\t\tpointsWithinLightRad += static_cast<int>(it->mUserVal < sqrRadius);\r\n\r\n\t\tif (pointsWithinLightRad > 1)\r\n\t\t\tbreak;\r\n\t}\r\n\r\n\tif (pointsWithinLightRad < 2)\r\n\t\treturn false;\r\n\t\t\r\n\t// Special case: simple line, no need to think long\r\n\tif (edges.size() == 1)\r\n\t{\r\n\t\tEdge2f globalEdge(occluder.getTransform().transformPoint(edges[0].v1), occluder.getTransform().transformPoint(edges[0].v2));\r\n\t\tgenerateShadowFromLine(edges[0]);\r\n\t\treturn true;\r\n\t}\r\n\t\t\r\n\t// Check if the light lies inside the occluder\r\n\ttypedef vector<Edge2f::EdgeSide> EdgeSideList;\r\n\tEdgeSideList facing;\r\n\tfacing.reserve(edges.size());\r\n\ttransform(edges.begin(), edges.end(), back_inserter(facing),\r\n\t\t[&] (const Edge2f &e) -> Edge2f::EdgeSide { return e.checkSide(occLocalLPos); } );\r\n\r\n\t// And remove all edges which are facing the light\r\n\tEdgeSideList::const_iterator facingIt = facing.begin();\r\n\tconst Edge2f::EdgeSide validSide = Edge2f::SideLeft;\r\n\tconst size_t originalEdgesCount = edges.size();\r\n\tedges.erase(remove_if(edges.begin(), edges.end(),\r\n\t\t\t\t\t\t\t[&] (const Edge2f &) -> bool\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\treturn (*facingIt++) != validSide;\r\n\t\t\t\t\t\t\t} ),\r\n\t\t\t\tedges.end());\r\n\r\n\tmIsInside |= edges.size() == originalEdgesCount;\r\n\tif (mIsInside)\r\n\t\treturn false;\r\n\r\n\t// Generate occluding edge\r\n\tstatic const int NullPointTag\t= 0;\r\n\tstatic const int HullPointTag\t= 1;\r\n\tstatic const int LightPointTag\t= 2;\r\n\r\n\tConvexHullT hull;\r\n\r\n\tPointIntList occludingPoints;\r\n\tfor_each(edges.begin(), edges.end(),\r\n\t\t[&] (Edge2f &e)\r\n\t\t{\r\n\t\t\tif (e.mClosePolygon)\r\n\t\t\t\tswap(e.v1, e.v2);\r\n\r\n\t\t\thull.addPoint(PointInt(e.v1, HullPointTag));\r\n\t\t\thull.addPoint(PointInt(e.v2, HullPointTag));\r\n\t\t} );\r\n\r\n\t// Add the light point to the points, in order to get the points that'll generate the occluding edge\r\n\thull.addPoint(PointInt(occLocalLPos, LightPointTag));\r\n\thull.build(PointInt(Vector2f(), NullPointTag));\r\n\thull.clean( [] (const PointInt &p) { return p.mUserVal == NullPointTag; } );\r\n\tconst ConvexHullT::HullPoints &hullPoints = hull.get();\r\n\r\n\t// And now that we have the convex hull, simply extract the points enclosing the light point.\r\n\tPointIntList::const_iterator lightPosIt = find_if(hullPoints.begin(), hullPoints.end(),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t[] (const PointInt &p) { return p.mUserVal == LightPointTag; } );\r\n\tmIsInside = lightPosIt == hullPoints.end();\r\n\tif (mIsInside)\r\n\t\treturn false;\r\n\r\n\tPointIntList::const_iterator firstIt\t= hullPoints.begin();\r\n\tPointIntList::const_iterator lastIt\t\t= hullPoints.end() - 1;\r\n\r\n\tconst Vector2f &v1 = lightPosIt == firstIt\t? (*lastIt).mPos\t: (*(lightPosIt - 1)).mPos;\r\n\tconst Vector2f &v2 = lightPosIt == lastIt\t? (*firstIt).mPos\t: (*(lightPosIt + 1)).mPos;\r\n\tconst Edge2f occludingEdge(v1, v2);\r\n\r\n\tEdge2f globalEdge(occluder.getTransform().transformPoint(occludingEdge.v1), occluder.getTransform().transformPoint(occludingEdge.v2));\r\n\tgenerateShadowFromLine(globalEdge);\r\n\r\n\treturn true;\r\n}\r\n\r\nvoid Light::DrawShadows(RenderTarget &target) const\r\n{\r\n\tif (mIsInside)\r\n\t\treturn;\r\n\r\n\tfor_each(mShadows.begin(), mShadows.end(), [&] (const ShapePtr &shadow) { target.draw(*shadow); } );\r\n}\r\n\r\nvoid Light::DebugDraw(RenderTarget &target) const\r\n{\r\n\tif (mIsInside)\r\n\t\treturn;\r\n\r\n    const sfge::Circle<float> influence(mLightDesc.mPos - sf::Vector2f(mLightDesc.mRadius, mLightDesc.mRadius), mLightDesc.mRadius);\r\n    const sfge::Circle<float> point(mLightDesc.mPos - sf::Vector2f(3, 3), 3);\r\n\ttarget.draw(*shapeFromCircle(influence, Color(150, 150, 30, 64)));\r\n    target.draw(*shapeFromCircle(point, Color::Yellow));\r\n}\r\n\r\nvoid Light::generateShadowFromLine(Edge2f &e)\r\n{\r\n\tconst Vector2f\tscaledPos\t\t= mLightDesc.mPos;\r\n\tconst float\t\tscaledRadius\t= mLightDesc.mRadius;\r\n\tconst float\t\tsqrScaledRadius\t= scaledRadius * scaledRadius;\r\n\r\n\t// Clamp edge's endpoints to light radius\r\n\tVector2f\tlightToV1\t\t= e.v1 - scaledPos,\r\n\t\t\t\tlightToV2\t\t= e.v2 - scaledPos;\r\n\tconst float\tlightToV1Dist\t= sqrLength(lightToV1),\r\n\t\t\t\tlightToV2Dist\t= sqrLength(lightToV2);\r\n\r\n\tif (lightToV1Dist > sqrScaledRadius || lightToV2Dist > sqrScaledRadius)\r\n\t{\r\n\t\tEdgeCircleIntersectionCont<float> intersectInfo;\r\n\t\tIntersectionResult res = intersect(e, mLightDesc, intersectInfo);\r\n\t\tif (res != IR_TwoIntersections)\r\n\t\t\treturn;\r\n\r\n\t\tif (lightToV1Dist > sqrScaledRadius)\r\n\t\t\te.v1 = intersectInfo.mStartPoint + intersectInfo.mTs[0] * intersectInfo.mDir;\r\n\t\t\r\n\t\tif (lightToV2Dist > sqrScaledRadius)\r\n\t\t\te.v2 = intersectInfo.mStartPoint + intersectInfo.mTs[1] * intersectInfo.mDir;\r\n\t}\r\n\t\t\r\n\t// Generate 6 additionnal points to be the shadow's endpoints\r\n\t// FIXME adaptive tessellation w/r <angle,dist> needed!\r\n\tconst int endPointsCount = 6;\r\n\tconst float invSplit = 1.f / (endPointsCount - 1);\r\n\tarray<Vector2f, endPointsCount> endPoints;\r\n\tconst Vector2f delta(e.v2 - e.v1);\r\n\r\n\tendPoints[0]\t\t\t\t\t= e.v1;\r\n\tendPoints[endPointsCount - 1]\t= e.v2;\r\n\r\n\tfor (size_t i = 1; i != endPoints.size() - 1; i++)\r\n\t{\r\n\t\tconst float splitFactor\t= invSplit * i;\r\n\t\tendPoints[i]\t\t\t= delta * splitFactor  + e.v1;\r\n\t}\r\n\r\n\t// Compute extrusion distance (from midpoint to be sure to stay within light's radius\r\n\tfor (size_t i = 0; i != endPoints.size(); i++)\r\n\t{\r\n\t\tVector2f diff\t\t\t= endPoints[i] - scaledPos;\r\n\t\tconst float diffLength\t= length(diff);\r\n\t\tconst float extrudeLen\t= scaledRadius - diffLength + 1.f;\r\n\r\n\t\tdiff /= diffLength;\r\n\t\tendPoints[i] += diff * extrudeLen;\r\n\t}\r\n\r\n    // Generate shadow SFML shape\r\n\tstd::shared_ptr<sf::ConvexShape> shadow(new sf::ConvexShape(2 + endPoints.size()));\r\n    shadow->setFillColor(mShadowFill);\r\n    shadow->setOutlineColor(mShadowOutline);\r\n\tshadow->setOutlineThickness(1.f);\r\n\r\n    unsigned int ptIndex = 0;\r\n\tshadow->setPoint(ptIndex++, e.v1);\r\n\tfor_each(endPoints.begin(), endPoints.end(),\r\n\t\t[&] (const Vector2f &v)\r\n\t\t{\r\n\t\t\tsf::Color endShadowFill(mShadowFill);\r\n\t\t\tendShadowFill.a = static_cast<Uint8>(endShadowFill.a * 0.25f);\r\n\t\t\tshadow->setPoint(ptIndex++, v);\r\n\t\t} );\r\n\tshadow->setPoint(ptIndex++, e.v2);\r\n\t\t\r\n\tmShadows.push_back(shadow);\r\n}\r\n\r\n}\r\n", "meta": {"hexsha": "025e07b7c3ac3437d9f762ea02ca43aaa02c3281", "size": 8659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SFGE/src/graphics/light.cpp", "max_stars_repo_name": "sheldonrobinson/sfge", "max_stars_repo_head_hexsha": "af0adbc3ea1509a20d7255d41c34fb1f8db83728", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SFGE/src/graphics/light.cpp", "max_issues_repo_name": "sheldonrobinson/sfge", "max_issues_repo_head_hexsha": "af0adbc3ea1509a20d7255d41c34fb1f8db83728", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SFGE/src/graphics/light.cpp", "max_forks_repo_name": "sheldonrobinson/sfge", "max_forks_repo_head_hexsha": "af0adbc3ea1509a20d7255d41c34fb1f8db83728", "max_forks_repo_licenses": ["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.925, "max_line_length": 136, "alphanum_fraction": 0.6887631366, "num_tokens": 2510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5112259897889443}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.\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_RANDOM_STRATEGIES_AGNOSTIC_UNIFORM_CONVEX_FAN_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_RANDOM_STRATEGIES_AGNOSTIC_UNIFORM_CONVEX_FAN_HPP\n\n#include <random>\n#include <vector>\n#include <cstdlib>\n#include <cmath>\n\n#include <boost/geometry/algorithms/equals.hpp>\n#include <boost/geometry/algorithms/transform.hpp>\n#include <boost/geometry/algorithms/within.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace uniform_point_distribution {\n\n// The following strategy is suitable for convex rings and polygons with\n// non-empty interior.\ntemplate\n<\n    typename Point,\n    typename DomainGeometry,\n    typename TriangleStrategy,\n    typename SideStrategy   //Actually, we need a triangle area strategy here.\n>\nstruct uniform_convex_fan\n{\nprivate:\n    std::vector<double> accumulated_areas;\n    // It is hard to see a reason not to use double here. If a triangles\n    // relative size is smaller than doubles epsilon, it is too unlikely to\n    // realistically occur in a random sample anyway.\npublic:\n    uniform_convex_fan(DomainGeometry const& g)\n\t{\n        accumulated_areas.push_back(0);\n        for (int i = 2 ; i < g.size() ; ++i) {\n            accumulated_areas.push_back(\n                accumulated_areas.back() +\n                std::abs(SideStrategy::template side_value<double, double>(\n                         *g.begin(),\n                         *(g.begin() + i - 1),\n                         *(g.begin() + i))));\n        }\n    }\n    bool equals(DomainGeometry const& l_domain,\n                DomainGeometry const& r_domain,\n                uniform_convex_fan const& r_strategy) const\n    {\n        if( l_domain.size() != r_domain.size() ) return false;\n        for (int i = 0; i < l_domain.size(); ++i) {\n            if( !boost::geometry::equals(*(l_domain.begin() + i),\n                                         *(r_domain.begin() + i)))\n                return false;\n        }\n        return true;\n    }\n    template<typename Gen>\n    Point apply(Gen& g, DomainGeometry const& d)\n    {\n        std::uniform_real_distribution<double> dist(0, 1);\n        double r = dist(g) * accumulated_areas.back(),\n               s = dist(g);\n        std::size_t i = std::distance(\n            accumulated_areas.begin(),\n            std::lower_bound(accumulated_areas.begin(),\n                             accumulated_areas.end(),\n                             r));\n        return TriangleStrategy::template map\n            <\n                double\n            >(* d.begin(),\n              *(d.begin() + i),\n              *(d.begin() + i + 1),\n              ( r - accumulated_areas[ i - 1 ]) /\n                ( accumulated_areas[ i ] - accumulated_areas[ i - 1 ] ),\n              s);\n    }\n    void reset(DomainGeometry const&) {};\n};\n\n}} // namespace strategy::uniform_point_distribution\n\n}} // namespace boost::geometry\n\n#endif //  BOOST_GEOMETRY_EXTENSIONS_RANDOM_STRATEGIES_AGNOSTIC_UNIFORM_CONVEX_FAN_HPP\n", "meta": {"hexsha": "cecdfda3b6716865a84c0a67a01b4cc6b8a7db9f", "size": 3260, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/random/strategies/agnostic/uniform_convex_fan.hpp", "max_stars_repo_name": "BoostGSoC19/geometry", "max_stars_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T19:33:37.000Z", "max_issues_repo_path": "include/boost/geometry/extensions/random/strategies/agnostic/uniform_convex_fan.hpp", "max_issues_repo_name": "BoostGSoC19/geometry", "max_issues_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "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/geometry/extensions/random/strategies/agnostic/uniform_convex_fan.hpp", "max_forks_repo_name": "BoostGSoC19/geometry", "max_forks_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T04:54:35.000Z", "avg_line_length": 33.9583333333, "max_line_length": 86, "alphanum_fraction": 0.6150306748, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5112259897889443}}
{"text": "#include \"setup_skinning_handles.h\"\n#include \"kmeans_clustering.h\"\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <iostream>\n#include <igl/boundary_conditions.h>\n#include <igl/lbs_matrix.h>\n#include <igl/bbw.h>\n#include <igl/harmonic.h>\n#include <igl/biharmonic_coordinates.h>\n#include <unsupported/Eigen/KroneckerProduct>\n#include <igl/slice_into.h>\n#include <igl/remove_unreferenced.h>\n#include <igl/normalize_row_sums.h>\n#include <igl/writeOBJ.h>\n#include <igl/list_to_matrix.h>\n\nusing namespace Eigen;\nusing namespace std;\nMatrixXd bbw_strain_skinning_matrix(VectorXi& handles, const MatrixXd& mV, MatrixXi& mT){\n    std::set<int> unique_vertex_handles;\n    std::set<int>::iterator it;\n    //from the tet handle indexes, get the unique verts that can act as handles\n    for(int i=0; i<handles.size(); i++){\n        unique_vertex_handles.insert(mT(handles[i], 0));\n        unique_vertex_handles.insert(mT(handles[i], 1));\n        unique_vertex_handles.insert(mT(handles[i], 2));\n        unique_vertex_handles.insert(mT(handles[i], 3));\n    }\n\n    int i=0;\n    it = unique_vertex_handles.end();\n    VectorXi map_verts_to_unique_verts = VectorXi::Zero(*(--it)+1).array() -1;\n    for (it=unique_vertex_handles.begin(); it!=unique_vertex_handles.end(); ++it){\n        map_verts_to_unique_verts[*it] = i;\n        i++;\n    }\n\n    MatrixXi vert_to_tet = MatrixXi::Zero(handles.size(), 4);\n    i=0;\n    for(i=0; i<handles.size(); i++){\n        vert_to_tet.row(i)[0] = map_verts_to_unique_verts[mT.row(handles[i])[0]];\n        vert_to_tet.row(i)[1] = map_verts_to_unique_verts[mT.row(handles[i])[1]];\n        vert_to_tet.row(i)[2] = map_verts_to_unique_verts[mT.row(handles[i])[2]];\n        vert_to_tet.row(i)[3] = map_verts_to_unique_verts[mT.row(handles[i])[3]];\n    }\n    \n    MatrixXd C = MatrixXd::Zero(unique_vertex_handles.size(), 3);\n    VectorXi P = VectorXi::Zero(unique_vertex_handles.size());\n    VectorXi HandleIndexes = VectorXi::Zero(unique_vertex_handles.size());\n    i=0;\n    for (it=unique_vertex_handles.begin(); it!=unique_vertex_handles.end(); ++it){\n        HandleIndexes[i] =  *it;\n        C.row(i) = mV.row(*it);\n        P(i) = i;\n        i++;\n    }\n\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    cout<<\"---------0--------\"<<endl;\n    igl::boundary_conditions(mV, mT, C, P, MatrixXi(), MatrixXi(), b, bc);\n    // compute BBW weights matrix\n    igl::BBWData bbw_data;\n    // only a few iterations for sake of demo\n    bbw_data.active_set_params.max_iter = 100;\n    bbw_data.verbosity = 2;\n    \n    MatrixXd W, M;\n    cout<<\"---------1--------\"<<endl;\n    if(handles.size()==1){\n        return MatrixXd::Ones(mT.rows(), handles.size());\n    }\n\n    // if(!igl::bbw(mV, mT, b, bc, bbw_data, W))\n    // {\n    //     std::cout<<\"EXIT: Error here\"<<std::endl;\n    //     exit(0);\n    //     return MatrixXd();\n    // }\n    // if(!igl::harmonic(mV, mT, b, bc, 1, W))\n    // {\n    //     std::cout<<\"EXIT: Error here\"<<std::endl;\n    //     exit(0);\n    //     return MatrixXd();\n    // }\n\n    std::vector<std::vector<int> > S;\n    igl::matrix_to_list(HandleIndexes,S);\n \n    cout<<\"Computing weights for \"<<HandleIndexes.size()<<\" handles at \"<<mV.rows()<<\" vertices...\"<<endl;\n    // Technically k should equal 3 for smooth interpolation in 3d, but 2 is\n    // faster and looks OK\n    const int k = 3;\n    igl::biharmonic_coordinates(mV,mT,S,k,W);\n\n\n\n\n\n\n    cout<<\"---------2--------\"<<endl;\n\n    // Normalize weights to sum to one\n    igl::normalize_row_sums(W,W);\n    cout<<\"---------3--------\"<<endl;\n\n    // precompute linear blend skinning matrix\n    igl::lbs_matrix(mV,W,M);\n    cout<<\"---------4--------\"<<endl;\n\n    MatrixXd tW = MatrixXd::Zero(mT.rows(), handles.size());\n    for(int t =0; t<mT.rows(); t++){\n        VectorXi e = mT.row(t);\n        for(int h=0; h<handles.size(); h++){\n            if(t==handles[h]){\n                tW.row(t) *= 0;\n                tW(t,h) = 1;\n                break;\n            }\n            double p0 = 0;\n            double p1 = 0;\n            double p2 = 0;\n            double p3 = 0;\n            for(int j=0; j<vert_to_tet.cols(); ++j){\n                p0 += W(e[0], vert_to_tet(h, j));\n                p1 += W(e[1], vert_to_tet(h, j));\n                p2 += W(e[2], vert_to_tet(h, j));\n                p3 += W(e[3], vert_to_tet(h, j));\n            }\n            tW(t, h) = (p0+p1+p2+p3)/4;  \n        }\n    }\n    cout<<\"---------5--------\"<<endl;\n    igl::normalize_row_sums(tW, tW);\n\n    cout<<\"---------6--------\"<<endl;\n    return tW;\n}\n\nVector3d tet_center(MatrixXi& T, MatrixXd& V, int ind){\n    Vector3d v1 = V.row(T.row(ind)[0]);\n    Vector3d v2 = V.row(T.row(ind)[1]);\n    Vector3d v3 = V.row(T.row(ind)[2]);\n    Vector3d v4 = V.row(T.row(ind)[3]);\n\n    return (v1 + v2 + v3 + v4)/4;\n}\n\nMatrixXd setup_skinning_helper(int indx, \n    int nsh_on_component, \n    MatrixXi& mT, \n    MatrixXd& mV, \n    SparseMatrix<double>& mC, \n    SparseMatrix<double>& mA, \n    VectorXd& mx0, \n    std::map<int, std::vector<int>>& ms_handle_elem_map){\n\n    //---------BBW Skinning Handles ---------\n    VectorXi handles_ind = VectorXi::Zero(nsh_on_component);\n    VectorXd CAx0 = mC*mA*mx0;\n\n\n    for(int k=0; k<nsh_on_component; k++){\n        std::vector<int> els = ms_handle_elem_map[indx-k];\n        double centx = 0;//= VectorXd::Zero(els.size());\n        double centy = 0;//= VectorXd::Zero(els.size());\n        double centz = 0;//= VectorXd::Zero(els.size());\n        Vector3d avg_cent;\n        for(int i=0; i<els.size(); i++){\n            centx += CAx0[12*els[i]];\n            centy += CAx0[12*els[i]+1];\n            centz += CAx0[12*els[i]+2];\n        }\n        \n        avg_cent<<centx/els.size(), centy/els.size(), centz/els.size();\n        int minind = 0;\n        double mindist = (avg_cent - tet_center(mT, mV, 0)).norm();\n        for(int i=1; i<mT.rows(); i++){\n            double dist = (avg_cent - tet_center(mT, mV, i)).norm();\n            if(dist<mindist){\n                mindist = dist;\n                minind = i;\n            }\n        }\n      \n        handles_ind[k] = minind;\n    }\n    return bbw_strain_skinning_matrix(handles_ind, mV, mT);\n    \n\n}\n\nvoid setup_skinning_handles(int nsh, bool reduced, const MatrixXi& mT, const MatrixXd& mV, std::vector<VectorXi>& ibones, std::vector<VectorXi>& imuscle,\n    SparseMatrix<double>& mC, SparseMatrix<double>& mA, MatrixXd& mG, VectorXd& mx0, VectorXd& mred_s, MatrixXd& msW, std::map<int, std::vector<int>>& ms_handle_elem_map, VectorXd& relStiff){\n    \n    std::cout<<\"+ Skinning Handles\"<<std::endl;\n    int handles_per_tendon=2;\n    VectorXi skinning_elem_cluster_map;\n    std::map<int, std::vector<int>> skinning_cluster_elem_map;\n\n    std::cout<<nsh<<std::endl;\n    if(nsh==0){\n        nsh = mT.rows();\n    } \n\n    if(nsh<(ibones.size()+imuscle.size())){\n        std::cout<<\"Too few skinning handles, too many components\"<<std::endl;\n        exit(0);\n    }\n\n    \n\n    //-----------------------------------------------------\n    if(nsh==mT.rows() && reduced==false){\n        //unreduced\n        std::cout<<\"here\"<<std::endl;\n        skinning_elem_cluster_map.resize(mT.rows());\n        skinning_elem_cluster_map.setZero();\n        for(int i=0; i<mT.rows(); i++){\n            skinning_elem_cluster_map[i] = i;\n        }\n    }else{\n        kmeans_clustering(skinning_elem_cluster_map, nsh, handles_per_tendon, ibones, imuscle, mG, mC, mA, mx0, relStiff);\n    }\n\n    for(int i=0; i<mT.rows(); i++){\n        ms_handle_elem_map[skinning_elem_cluster_map[i]].push_back(i);\n    }\n    //------------------------------------------------------\n\n    if(reduced==false){\n        mred_s.resize(6*mT.rows());\n        for(int i=0; i<mT.rows(); i++){\n            mred_s[6*i+0] = 1; \n            mred_s[6*i+1] = 1; \n            mred_s[6*i+2] = 1; \n            mred_s[6*i+3] = 0; \n            mred_s[6*i+4] = 0; \n            mred_s[6*i+5] = 0;\n        }\n        std::cout<<\"- Skinning Handles\"<<std::endl;\n        return;\n    \n    }\n    if(nsh==mT.rows()){\n        std::cout<<\"Too many skinning handles. \"<<std::endl;\n        exit(0);\n    }\n\n    mred_s.resize(6*nsh);\n    for(int i=0; i<nsh; i++){\n        mred_s[6*i+0] = 1; \n        mred_s[6*i+1] = 1; \n        mred_s[6*i+2] = 1; \n        mred_s[6*i+3] = 0; \n        mred_s[6*i+4] = 0; \n        mred_s[6*i+5] = 0;\n    }\n\n    MatrixXd Id6 = MatrixXd::Identity(6, 6);\n    MatrixXd sW = MatrixXd::Zero(mT.rows(), nsh);\n    sW.setZero();\n    std::cout<<\"nsh: \"<<nsh<<std::endl;\n    std::cout<<ms_handle_elem_map.size()<<std::endl;\n    // //Constant weights of 1 for each handle region\n    // for(int h=0; h<ms_handle_elem_map.size(); h++){\n    //   std::vector<int> mshem =  ms_handle_elem_map[ms_handle_elem_map.size() - h - 1];\n    //   MatrixXd ones_vec = VectorXd::Ones(mshem.size());\n    //   MatrixXd sWslice = MatrixXd::Zero(mT.rows(), 1);\n    //   VectorXi handles_elem_vec;\n    //   igl::list_to_matrix(mshem, handles_elem_vec);\n    //   igl::slice_into(ones_vec , handles_elem_vec, 1, sWslice);\n    //   sW.block(0, h, mT.rows(), 1) = sWslice;\n    // }\n    // msW =  Eigen::kroneckerProduct(sW, Id6);\n \n    // return;\n\n\n    //blocked construction of full skinning weights matrix\n    int maxnsh = nsh;\n    cout<<\"----------Bone HANDLES------------\"<<maxnsh<<\"--\"<<ms_handle_elem_map.size()<<endl;\n    int insert_index = 0;\n    for(int b=0; b<ibones.size(); b++){\n        MatrixXi subT(ms_handle_elem_map[maxnsh - 1 - insert_index].size(), 4);\n        MatrixXi componentT;\n        MatrixXd componentV;\n        VectorXi J;\n\n        for(int i=0; i<ms_handle_elem_map[maxnsh -1 - insert_index].size() ; i++){\n            subT.row(i) = mT.row(ms_handle_elem_map[maxnsh -1 - insert_index][i]);\n        }\n\n        igl::remove_unreferenced(mV, subT, componentV, componentT, J);\n\n        std::string nam = \"bone\"+to_string(b)+\".obj\";\n\n        igl::writeOBJ(nam, componentV, componentT);\n\n        MatrixXd sWi = setup_skinning_helper(maxnsh-1- insert_index , 1, componentT, componentV, mC, mA, mx0, ms_handle_elem_map);\n        \n        MatrixXd sWslice = MatrixXd::Zero(mT.rows(), sWi.cols());\n        igl::slice_into(sWi , ibones[b], 1, sWslice);\n        sW.block(0,insert_index, mT.rows(), sWi.cols()) = sWslice;\n        nsh = nsh - 1; //bone skinning handle has been made, so decrease nsh by 1\n        insert_index += 1;\n    }\n\n    cout<<\"----------MUSCLE HANDLES----\"<<nsh<<\"---\"<<insert_index<<\"-----\"<<endl;\n    int number_handles_per_muscle = nsh/imuscle.size();\n    for(int m=0; m<imuscle.size(); m++){ //through muscle vector\n        // std::vector<int> tendon_elements_list;\n        // std::vector<int> muscle_elements_list;\n        // for(int i=0; i<imuscle[m].size(); i++){\n        //     if(relStiff[imuscle[m][i]]>10){\n        //         tendon_elements_list.push_back(imuscle[m][i]);\n        //     }else{\n        //         muscle_elements_list.push_back(imuscle[m][i]);\n        //     }\n        // }\n      \n        VectorXi muscle_els, tendon_els;\n        muscle_els = imuscle[m];\n        // igl::list_to_matrix(tendon_elements_list, tendon_els);\n        // igl::list_to_matrix(muscle_elements_list, muscle_els);\n\n        // //Tendon skinning handles---------------------------\n        // if(tendon_els.size()>0){\n            \n        //     MatrixXi TcomponentT;\n        //     MatrixXd TcomponentV;\n        //     MatrixXi TsubT(tendon_els.size(), 4);\n        //     VectorXi TJ;\n        //     for(int i=0; i<tendon_els.size() ; i++){\n        //         TsubT.row(i) = mT.row(tendon_els[i]);\n        //     }\n        //     igl::remove_unreferenced(mV, TsubT, TcomponentV, TcomponentT, TJ);\n        //     std::string Tnam = \"tendon\"+to_string(m)+\".obj\";\n        //     igl::writeOBJ(Tnam, TcomponentV, TcomponentT);\n        //     MatrixXd TsWi;\n        //     if(m==imuscle.size() -1){\n        //         TsWi = setup_skinning_helper(maxnsh -1 - insert_index - nsh + handles_per_tendon, handles_per_tendon, TcomponentT, TcomponentV, mC, mA, mx0, ms_handle_elem_map);\n        //     }else{\n        //         TsWi = setup_skinning_helper(maxnsh -1 - insert_index - number_handles_per_muscle + handles_per_tendon, handles_per_tendon, TcomponentT, TcomponentV, mC, mA, mx0, ms_handle_elem_map);\n        //     }\n        //     MatrixXd TsWslice = MatrixXd::Zero(mT.rows(), TsWi.cols());\n            \n        //     igl::slice_into(TsWi , tendon_els, 1, TsWslice);\n        //     sW.block(0,insert_index, mT.rows(), TsWi.cols()) = TsWslice;\n        // }\n        handles_per_tendon=0;\n\n        //Muscle skinning handles---------------------------\n        MatrixXi componentT;\n        MatrixXd componentV;\n        MatrixXi subT(muscle_els.size(), 4);\n        VectorXi J;\n        for(int i=0; i<muscle_els.size() ; i++){\n            subT.row(i) = mT.row(muscle_els[i]);\n        }\n        igl::remove_unreferenced(mV, subT, componentV, componentT, J);\n        std::string nam = \"muscle\"+to_string(m)+\".obj\";\n        igl::writeOBJ(nam, componentV, componentT);\n        MatrixXd sWi;\n        if(m==imuscle.size()-1){\n            //Deal with remainder handles\n            sWi = setup_skinning_helper(maxnsh - 1 - insert_index, nsh - handles_per_tendon, componentT, componentV, mC, mA, mx0, ms_handle_elem_map);\n        }else{\n            sWi = setup_skinning_helper(maxnsh - 1 - insert_index, number_handles_per_muscle - handles_per_tendon, componentT, componentV, mC, mA, mx0, ms_handle_elem_map );\n        }\n\n        MatrixXd sWslice = MatrixXd::Zero(mT.rows(), sWi.cols());\n        \n        igl::slice_into(sWi , muscle_els, 1, sWslice);\n        sW.block(0,insert_index+handles_per_tendon, mT.rows(), sWi.cols()) = sWslice;\n        insert_index += number_handles_per_muscle;\n        nsh =  nsh - number_handles_per_muscle;\n    }\n    assert(nsh==0);\n\n    // MatrixXd Id6 = MatrixXd::Identity(6, 6);\n    msW =  Eigen::kroneckerProduct(sW, Id6);\n \n    std::cout<<\"- Skinning Handles\"<<std::endl;\n}\n\n", "meta": {"hexsha": "72678e35420b9bad92c8daa1330c49e31fbaa7c6", "size": 13987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PreProcessing/setup_skinning_handles.cpp", "max_stars_repo_name": "itsvismay/fast_muscles", "max_stars_repo_head_hexsha": "86c9d93bd14da92ce2140bf47857810b579e7b2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T22:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T01:38:52.000Z", "max_issues_repo_path": "PreProcessing/setup_skinning_handles.cpp", "max_issues_repo_name": "itsvismay/fast_muscles", "max_issues_repo_head_hexsha": "86c9d93bd14da92ce2140bf47857810b579e7b2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-08T21:10:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-08T21:10:36.000Z", "max_forks_repo_path": "PreProcessing/setup_skinning_handles.cpp", "max_forks_repo_name": "itsvismay/fast_muscles", "max_forks_repo_head_hexsha": "86c9d93bd14da92ce2140bf47857810b579e7b2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-08T21:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-08T21:11:10.000Z", "avg_line_length": 35.8641025641, "max_line_length": 202, "alphanum_fraction": 0.5640952313, "num_tokens": 4123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5112259897889443}}
{"text": "/**********************************************************************\r\n*  Copyright (c) 2008-2015, Alliance for Sustainable Energy.\r\n*  All rights reserved.\r\n*\r\n*  This library is free software; you can redistribute it and/or\r\n*  modify it under the terms of the GNU Lesser General Public\r\n*  License as published by the Free Software Foundation; either\r\n*  version 2.1 of the License, or (at your option) any later version.\r\n*\r\n*  This library is distributed in the hope that it will be useful,\r\n*  but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n*  Lesser General Public License for more details.\r\n*\r\n*  You should have received a copy of the GNU Lesser General Public\r\n*  License along with this library; if not, write to the Free Software\r\n*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\r\n**********************************************************************/\r\n\r\n#include \"Transformation.hpp\"\r\n#include \"Point3d.hpp\"\r\n#include \"Vector3d.hpp\"\r\n#include \"Plane.hpp\"\r\n#include \"BoundingBox.hpp\"\r\n#include \"EulerAngles.hpp\"\r\n#include \"Geometry.hpp\"\r\n#include \"../core/Assert.hpp\"\r\n\r\n#include <boost/math/constants/constants.hpp>\r\n\r\n#include <algorithm>\r\n\r\n#include <math.h>\r\n\r\nusing boost::numeric::ublas::identity_matrix;\r\nusing std::min;\r\n\r\nnamespace openstudio{\r\n\r\n  /// default constructor creates identity transformation\r\n  Transformation::Transformation()\r\n    : m_storage(identity_matrix<double>(4))\r\n  {}\r\n\r\n  /// copy constructor\r\n  Transformation::Transformation(const Transformation& other)\r\n    : m_storage(other.m_storage)\r\n  {}\r\n\r\n  /// constructor from storage, asserts matrix is 4x4\r\n  Transformation::Transformation(const Matrix& matrix)\r\n    : m_storage(matrix)\r\n  {\r\n    OS_ASSERT(matrix.size1() == 4);\r\n    OS_ASSERT(matrix.size2() == 4);\r\n  }\r\n\r\n  /// constructor from storage, asserts vector is size 16\r\n  Transformation::Transformation(const Vector& vector)\r\n    : m_storage(Matrix(4,4))\r\n  {\r\n    OS_ASSERT(vector.size() == 16);\r\n    \r\n    m_storage(0,0) = vector[0];\r\n    m_storage(1,0) = vector[1];\r\n    m_storage(2,0) = vector[2];\r\n    m_storage(3,0) = vector[3];\r\n    m_storage(0,1) = vector[4];\r\n    m_storage(1,1) = vector[5];\r\n    m_storage(2,1) = vector[6];\r\n    m_storage(2,1) = vector[7];\r\n    m_storage(0,2) = vector[8];\r\n    m_storage(1,2) = vector[9];\r\n    m_storage(2,2) = vector[10];\r\n    m_storage(3,2) = vector[11];\r\n    m_storage(0,3) = vector[12];\r\n    m_storage(1,3) = vector[13];\r\n    m_storage(2,3) = vector[14];\r\n    m_storage(3,3) = vector[15];\r\n  }\r\n\r\n  /// rotation about origin defined by axis and angle (radians)\r\n  Transformation Transformation::rotation(const Vector3d& axis, double radians)\r\n  {\r\n    Matrix storage = identity_matrix<double>(4);\r\n\r\n    Vector3d temp = axis;\r\n    if (!temp.normalize()){\r\n      LOG(Error, \"Could not normalize axis\");\r\n    }\r\n    Vector normalVector = temp.vector();\r\n\r\n    // Rodrigues' rotation formula / Rotation matrix from Euler axis/angle\r\n    // I*cos(radians) + I*(1-cos(radians))*axis*axis^T + Q*sin(radians)\r\n    // Q = [0, -axis[2], axis[1]; axis[2], 0, -axis[0]; -axis[1], axis[0], 0]\r\n    Matrix P = outer_prod(normalVector, normalVector);\r\n    Matrix I = identity_matrix<double>(3);\r\n    Matrix Q(3, 3, 0.0);\r\n    Q(0,1) = -normalVector(2);\r\n    Q(0,2) =  normalVector(1);\r\n    Q(1,0) =  normalVector(2);\r\n    Q(1,2) = -normalVector(0);\r\n    Q(2,0) = -normalVector(1);\r\n    Q(2,1) =  normalVector(0);\r\n\r\n    // rotation matrix\r\n    Matrix R = I*cos(radians) + (1-cos(radians))*P + Q*sin(radians);\r\n\r\n    for (unsigned i = 0; i < 3; ++i){\r\n      for (unsigned j = 0; j < 3; ++j){\r\n        storage(i,j) = R(i,j);\r\n      }\r\n    }\r\n\r\n    return Transformation(storage);\r\n  }\r\n\r\n  /// rotation about point defined by axis and angle (radians)\r\n  Transformation Transformation::rotation(const Point3d& origin, const Vector3d& axis, double radians)\r\n  {\r\n    Vector3d temp(origin.x(), origin.y(), origin.z());\r\n\r\n    // translate point to origin, rotate, and then translate back\r\n    return translation(temp)*rotation(axis, radians)*translation(-temp);\r\n  }\r\n\r\n  /// rotation specified by Euler angles\r\n  Transformation Transformation::rotation(const EulerAngles& angles)\r\n  {\r\n    Transformation result = Transformation::rotation(Vector3d(0,0,1), angles.phi()) * \r\n                            Transformation::rotation(Vector3d(0,1,0), angles.theta()) *\r\n                            Transformation::rotation(Vector3d(1,0,0), angles.psi());\r\n    return result;\r\n  }\r\n\r\n  /// translation along vector\r\n  Transformation Transformation::translation(const Vector3d& translation)\r\n  {\r\n    Matrix storage = identity_matrix<double>(4);\r\n\r\n    storage(0,3) = translation.x();\r\n    storage(1,3) = translation.y();\r\n    storage(2,3) = translation.z();\r\n\r\n    return Transformation(storage);\r\n  }\r\n\r\n  /// transforms system with z' to regular system\r\n  /// will try to align y' with z, but if that fails will align y' with y\r\n  Transformation Transformation::alignZPrime(const Vector3d& zPrime)\r\n  {\r\n    Vector3d xp;\r\n    Vector3d yp;\r\n    Vector3d zp = zPrime;\r\n    if (!zp.normalize()){\r\n      LOG(Error, \"Could not normalize zPrime\");\r\n    }\r\n\r\n    Vector3d xAxis(1,0,0);\r\n    Vector3d yAxis(0,1,0);\r\n    Vector3d zAxis(0,0,1);\r\n    Vector3d negXAxis(-1,0,0);\r\n\r\n    // check if face normal is up or down\r\n    if (fabs(zp.dot(zAxis)) < 0.99){\r\n      // not facing up or down, set yPrime along zAxis\r\n      yp = zAxis - (zp.dot(zAxis)*zp);\r\n      if (!yp.normalize()){\r\n        LOG(Error, \"Could not normalize axis\");\r\n      }\r\n      xp = yp.cross(zp);\r\n    }else{\r\n      // facing up or down, set xPrime along -xAxis\r\n      xp = negXAxis - (zp.dot(negXAxis)*zp);\r\n      if (!xp.normalize()){\r\n        LOG(Error, \"Could not normalize axis\");\r\n      }\r\n      yp = zp.cross(xp);\r\n    }\r\n\r\n    Matrix storage = identity_matrix<double>(4);\r\n    storage(0,0) = xp.x();\r\n    storage(1,0) = xp.y();\r\n    storage(2,0) = xp.z();\r\n    storage(0,1) = yp.x();\r\n    storage(1,1) = yp.y();\r\n    storage(2,1) = yp.z();\r\n    storage(0,2) = zp.x();\r\n    storage(1,2) = zp.y();\r\n    storage(2,2) = zp.z();\r\n\r\n    return Transformation(storage);\r\n  }\r\n\r\n  /// transforms face coordinates to regular system, face normal will be z'\r\n  /// will try to align y' with z, but if that fails will align y' with y\r\n  /// face origin will be minimum point in x', y' and z'=0\r\n  /// will return identity transformation if cannot compute plane for vertices\r\n  Transformation Transformation::alignFace(const std::vector<Point3d>& vertices)\r\n  {\r\n    OptionalVector3d zPrime = getOutwardNormal(vertices);\r\n    if (!zPrime){\r\n      LOG(Error, \"Cannot compute outward normal for vertices\");\r\n      return Transformation();\r\n    }\r\n\r\n    // align z' with outward normal\r\n    Transformation align = alignZPrime(*zPrime);\r\n    Point3dVector alignedVertices = align.inverse()*vertices;\r\n\r\n    // compute translation to minimum in aligned system\r\n    double minX = alignedVertices[0].x();\r\n    double minY = alignedVertices[0].y();\r\n    double minZ = alignedVertices[0].z();\r\n\r\n    for (const Point3d& vertex : alignedVertices){\r\n      minX = min(minX, vertex.x());\r\n      minY = min(minY, vertex.y());\r\n      minZ = min(minZ, vertex.z());\r\n    }\r\n    Transformation translate = translation(Vector3d(minX, minY, minZ));\r\n\r\n    return align*translate;\r\n  }\r\n\r\n  /// returns a transformation which is the inverse of this\r\n  Transformation Transformation::inverse() const\r\n  {\r\n    Matrix matrix(4,4);\r\n    bool test = invert(m_storage, matrix);\r\n    if (!test){\r\n      // this should never happen\r\n      LOG_AND_THROW(\"Matrix inversion failed\");\r\n    }\r\n    return Transformation(matrix);\r\n  }\r\n\r\n  /// get the matrix representation directly\r\n  Matrix Transformation::matrix() const\r\n  {\r\n    return m_storage;\r\n  }\r\n\r\n  /// get the vector representation directly\r\n  Vector Transformation::vector() const\r\n  {\r\n    openstudio::Vector result(16);\r\n    result[0] = m_storage(0,0);\r\n    result[1] = m_storage(1,0);\r\n    result[2] = m_storage(2,0);\r\n    result[3] = m_storage(3,0);\r\n    result[4] = m_storage(0,1);\r\n    result[5] = m_storage(1,1);\r\n    result[6] = m_storage(2,1);\r\n    result[7] = m_storage(3,1);\r\n    result[8] = m_storage(0,2);\r\n    result[9] = m_storage(1,2);\r\n    result[10] = m_storage(2,2);\r\n    result[11] = m_storage(3,2);\r\n    result[12] = m_storage(0,3);\r\n    result[13] = m_storage(1,3);\r\n    result[14] = m_storage(2,3);\r\n    result[15] = m_storage(3,3);\r\n    return result;\r\n  }\r\n\r\n  /// get the Euler angles for the transformation, does not include translation\r\n  EulerAngles Transformation::eulerAngles() const\r\n  {\r\n    double psi;\r\n    double theta;\r\n    double phi;\r\n    if (m_storage(2,0) == 1.0){\r\n      phi = 0;\r\n      theta = -boost::math::constants::pi<double>()/2.0;\r\n      psi = atan2(-m_storage(0,1), -m_storage(0,2));\r\n    }else if(m_storage(2,0) == -1.0){\r\n      phi = 0;\r\n      theta = boost::math::constants::pi<double>()/2.0;\r\n      psi = atan2(m_storage(0,1), m_storage(0,2));\r\n    }else{\r\n      theta = -asin(m_storage(2,0));\r\n      // theta = pi + asin(m_storage(2,0)); // alternate solution\r\n      psi = atan2(m_storage(2,1)/cos(theta), m_storage(2,2)/cos(theta));\r\n      phi = atan2(m_storage(1,0)/cos(theta), m_storage(0,0)/cos(theta));\r\n      \r\n    }\r\n    EulerAngles result(psi, theta, phi);\r\n    return result;\r\n  }\r\n\r\n  /// get the rotation matrix for the transformation, does not include translation\r\n  Matrix Transformation::rotationMatrix() const\r\n  {\r\n    Matrix result(3,3);\r\n    for(unsigned i = 0 ; i < 3; ++i){\r\n      for(unsigned j = 0; j < 3; ++j){\r\n        result(i,j) = m_storage(i,j);\r\n      }\r\n    }\r\n    return result;\r\n  }\r\n\r\n  /// get the translation for the transformation, does not include rotation\r\n  Vector3d Transformation::translation() const\r\n  {\r\n    Vector3d result(m_storage(0, 3), m_storage(1, 3), m_storage(2, 3));\r\n    return result;\r\n  }\r\n\r\n  /// apply the transformation to the point\r\n  Point3d Transformation::operator*(const Point3d& point) const\r\n  {\r\n    Vector temp(4);\r\n    temp(0) = point.x();\r\n    temp(1) = point.y();\r\n    temp(2) = point.z();\r\n    temp(3) = 1.0;\r\n    temp = prod(m_storage, temp);\r\n    return Point3d(temp[0], temp[1], temp[2]);\r\n  }\r\n\r\n  /// apply the transformation to the vector\r\n  Vector3d Transformation::operator*(const Vector3d& vector) const\r\n  {\r\n    Vector temp(4);\r\n    temp(0) = vector.x();\r\n    temp(1) = vector.y();\r\n    temp(2) = vector.z();\r\n    temp(3) = 1.0;\r\n    temp = prod(m_storage, temp);\r\n    return Vector3d(temp[0], temp[1], temp[2]);\r\n  }\r\n\r\n  /// apply the transformation to the BoundingBox\r\n  BoundingBox Transformation::operator*(const BoundingBox& boundingBox) const\r\n  {\r\n    BoundingBox result;\r\n    std::vector<Point3d> transformedPoints = (*this)*boundingBox.corners();\r\n    result.addPoints(transformedPoints);\r\n    return result;\r\n  }\r\n\r\n  /// apply the transformation to the plane\r\n  Plane Transformation::operator*(const Plane& plane) const\r\n  {\r\n    // translate a point on the plane, just project (0,0,0)\r\n    Point3d point = plane.project(Point3d(0,0,0));\r\n\r\n    // get a point at outward normal\r\n    Vector3d outwardNormal = plane.outwardNormal();\r\n    Point3d refPoint = point + outwardNormal;\r\n    \r\n    // translate the two points and recompute the normal\r\n    Point3d newPoint = (*this) * point;\r\n    Point3d newRefPoint = (*this) * refPoint;\r\n    Vector3d newNormal = newRefPoint - newPoint;\r\n\r\n    return Plane(newPoint, newNormal);\r\n  }\r\n\r\n  /// apply the transformation to a vector of points\r\n  std::vector<Point3d> Transformation::operator*(const std::vector<Point3d>& points) const\r\n  {\r\n    std::vector<Point3d> result(points.size());\r\n    for(unsigned i = 0; i < points.size(); ++i){\r\n      result[i] = (*this)*points[i];\r\n    }\r\n    return result;\r\n  }\r\n\r\n  /// apply the transformation to a vector of vector\r\n  std::vector<Vector3d> Transformation::operator*(const std::vector<Vector3d>& vectors) const\r\n  {\r\n    std::vector<Vector3d> result(vectors.size());\r\n    for(unsigned i = 0; i < vectors.size(); ++i){\r\n      result[i] = (*this)*vectors[i];\r\n    }\r\n    return result;\r\n  }\r\n\r\n  /// apply the transformation to the other transformation\r\n  Transformation Transformation::operator*(const Transformation& other) const\r\n  {\r\n    return Transformation(prod(m_storage, other.m_storage));\r\n  }\r\n\r\n  /// ostream operator\r\n  std::ostream& operator<<(std::ostream& os, const Transformation& t)\r\n  {\r\n    os << t.matrix();\r\n    return os;\r\n  }\r\n\r\n\r\n  Transformation createRotation(const Vector3d& axis, double radians)\r\n  {\r\n    return Transformation::rotation(axis, radians);\r\n  }\r\n\r\n  Transformation createRotation(const Point3d& origin, const Vector3d& axis, double radians)\r\n  {\r\n    return Transformation::rotation(origin, axis, radians);\r\n  }\r\n\r\n  Transformation createRotation(const EulerAngles& angles)\r\n  {\r\n    return Transformation::rotation(angles);\r\n  }\r\n\r\n  Transformation createTranslation(const Vector3d& translation)\r\n  {\r\n    return Transformation::translation(translation);\r\n  }\r\n\r\n} // openstudio\r\n", "meta": {"hexsha": "066b4a4d13e5c23ac52de339e870638833fe3bfc", "size": 13151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/geometry/Transformation.cpp", "max_stars_repo_name": "BIMDataHub/OpenStudio-1", "max_stars_repo_head_hexsha": "13ec115b00aa6a2af1426ceb26446f05014c8c8d", "max_stars_repo_licenses": ["blessing"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-05-02T21:04:15.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-28T09:47:22.000Z", "max_issues_repo_path": "openstudiocore/src/utilities/geometry/Transformation.cpp", "max_issues_repo_name": "BIMDataHub/OpenStudio-1", "max_issues_repo_head_hexsha": "13ec115b00aa6a2af1426ceb26446f05014c8c8d", "max_issues_repo_licenses": ["blessing"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openstudiocore/src/utilities/geometry/Transformation.cpp", "max_forks_repo_name": "BIMDataHub/OpenStudio-1", "max_forks_repo_head_hexsha": "13ec115b00aa6a2af1426ceb26446f05014c8c8d", "max_forks_repo_licenses": ["blessing"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-12T21:52:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-12T21:52:36.000Z", "avg_line_length": 31.5371702638, "max_line_length": 103, "alphanum_fraction": 0.6197247358, "num_tokens": 3459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5112259846436289}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2020 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n\n\n#include <vector>\n#include <limits>\n#include <boost/algorithm/minmax_element.hpp>\n#include <Core/Math/Histogram.h>\n#include <Core/Math/MiscMath.h>\n\nusing namespace SCIRun::Core::Math;\n\nnamespace\n{\n  double Nan()\n  {\n    return std::numeric_limits<double>::quiet_NaN();\n  }\n}\n\nHistogram::Histogram()\n{\n  this->min_ = Nan();\n  this->max_ = Nan();\n  this->bin_start_ = Nan();\n  this->bin_size_ = Nan();\n  this->histogram_.resize( 0 );\n}\n\nHistogram::Histogram( const double* data, size_t size )\n{\n  this->compute( data, size );\n}\n\n// For char and short data we do a single pass over the data to speed up the computation. The\n// first pass is used to generate the histogram. In the next step we use this data to compute\n// min and max\nbool Histogram::compute( const double* data, size_t size )\n{\n  this->min_ = Nan();\n  this->max_ = Nan();\n  this->bin_start_ = Nan();\n  this->bin_size_ = Nan();\n  this->histogram_.resize( 0 );\n  if ( size == 0 )\n    return false;\n\n  try\n  {\n    this->min_ = std::numeric_limits<double>::max();\n    this->max_ = std::numeric_limits<double>::min();\n\n    for ( size_t j = 0 ; j < size ; j++ )\n    {\n      double val = data[ j ];\n      if ( ! IsFinite( val ) ) continue;\n      if ( val < this->min_ ) this->min_ = val;\n      if ( val > this->max_ ) this->max_ = val;\n    }\n\n    if ( this->min_ > this->max_ )\n    {\n      // Most likely all the data is NaN\n      this->min_ = Nan();\n      this->max_ = Nan();\n      this->bin_start_ = Nan();\n      this->bin_size_ = Nan();\n      this->histogram_.resize( 0 );\n      return false;\n    }\n\n    if ( this->min_ == this->max_ )\n    {\n      this->bin_size_  = 1.0;\n      this->bin_start_ = this->min_ - ( this->bin_size_ * 0.5 );\n      this->histogram_.resize( 1, 0 );\n    }\n    else\n    {\n      size_t hist_size = 0x100;\n      this->histogram_.resize( hist_size, 0 );\n      this->bin_size_ = ( this->max_ - this->min_ ) / static_cast<double>( hist_size - 1 );\n      this->bin_start_ = this->min_ - ( this->bin_size_ * 0.5 );\n    }\n\n    double inv_bin_size = 1.0 / bin_size_;\n\n    for ( size_t j = 1 ; j < size ; j++ )\n    {\n      double val = data[ j ];\n      if ( IsFinite( val ) )\n      {\n        size_t idx = static_cast<size_t>( ( val - this->min_ ) * inv_bin_size );\n        this->histogram_[ idx ]++;\n      }\n    }\n\n    auto min_max = boost::minmax_element( this->histogram_.begin(), this->histogram_.end() );\n    this->min_bin_ = (*min_max.first);\n    this->max_bin_ = (*min_max.second);\n  }\n  catch( ... )\n  {\n    this->min_ = Nan();\n    this->max_ = Nan();\n    this->bin_start_ = Nan();\n    this->bin_size_ = Nan();\n    this->histogram_.resize( 0 );\n    return false;\n  }\n\n  return true;\n}\n\ndouble Histogram::get_min() const\n{\n  return this->min_;\n}\n\ndouble Histogram::get_max() const\n{\n  return this->max_;\n}\n\ndouble Histogram::get_cum_value( double fraction ) const\n{\n  size_t tot_hist = 0;\n  for ( size_t j = 0; j < this->histogram_.size(); j++ )\n  {\n    tot_hist += this->histogram_[ j ];\n  }\n\n  double multiplier = 1.0 / static_cast<double>( tot_hist );\n  double jj = 0.0;\n  size_t cur_hist = 0;\n\n  for ( size_t j = 0; j < this->histogram_.size(); j++ )\n  {\n    double frac_start = static_cast<double>( cur_hist ) * multiplier;\n    cur_hist += this->histogram_[ j ];\n    double frac_end = static_cast<double>( cur_hist ) * multiplier;\n    if ( fraction > frac_start && fraction <= frac_end )\n    {\n      jj = static_cast<double>( j ) + ( frac_end - fraction )/( frac_end - frac_start );\n      break;\n    }\n  }\n\n  return this->bin_start_ + ( jj * this->bin_size_ );\n}\n\nsize_t Histogram::get_max_bin() const\n{\n  return this->max_bin_;\n}\n\nsize_t Histogram::get_min_bin() const\n{\n  return this->min_bin_;\n}\n\ndouble Histogram::get_bin_size() const\n{\n  return this->bin_size_;\n}\n\ndouble Histogram::get_bin_start( size_t idx ) const\n{\n  return this->bin_start_ + idx * this->bin_size_;\n}\n\ndouble Histogram::get_bin_end( size_t idx ) const\n{\n  return this->bin_start_ + ( idx + 1 ) * this->bin_size_;\n}\n\nconst std::vector<size_t>& Histogram::get_bins() const\n{\n  return this->histogram_;\n}\n\nsize_t Histogram::get_size() const\n{\n  return this->histogram_.size();\n}\n\nbool Histogram::is_valid() const\n{\n  return !( IsNan( this->min_ ) || IsNan( this->max_ ) );\n}\n", "meta": {"hexsha": "7dd724eb098ea3b325922e63dc79d84bbbc8f36e", "size": 5486, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Math/Histogram.cc", "max_stars_repo_name": "Haydelj/SCIRun", "max_stars_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2015-02-09T22:42:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:14:50.000Z", "max_issues_repo_path": "src/Core/Math/Histogram.cc", "max_issues_repo_name": "Haydelj/SCIRun", "max_issues_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1618.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T19:39:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T20:28:45.000Z", "max_forks_repo_path": "src/Core/Math/Histogram.cc", "max_forks_repo_name": "Haydelj/SCIRun", "max_forks_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 64.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T17:51:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T07:08:08.000Z", "avg_line_length": 25.5162790698, "max_line_length": 93, "alphanum_fraction": 0.6419978126, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5111959477417696}}
{"text": "#include \"nbsimParticle.h\"\n#include <Eigen/Dense>\n\nnamespace nbsim{\n    Particle::Particle(Eigen::Vector3d init_position, Eigen::Vector3d init_velocity){\n        current_position=init_position;\n        current_velocity=init_velocity;\n    }\n    Particle::~Particle(){};\n    Eigen::Vector3d Particle::getPosition(){\n        return current_position;\n    };\n    Eigen::Vector3d Particle::getVelocity(){\n        return current_velocity;\n    };\n    void Particle::integrateTimestep(Eigen::Vector3d acceleration, double timestep){\n        current_position+=current_velocity*timestep;\n        current_velocity+=acceleration*timestep;\n    }\n}", "meta": {"hexsha": "f30a351fbb5c0ba30d636f3791e20ac98f22c0d4", "size": 633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/Lib/nbsimParticle.cpp", "max_stars_repo_name": "zys711/cpp_Assignment2", "max_stars_repo_head_hexsha": "f705f8a53d358c85f2d7e7d1a36536492d448a8e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/Lib/nbsimParticle.cpp", "max_issues_repo_name": "zys711/cpp_Assignment2", "max_issues_repo_head_hexsha": "f705f8a53d358c85f2d7e7d1a36536492d448a8e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Lib/nbsimParticle.cpp", "max_forks_repo_name": "zys711/cpp_Assignment2", "max_forks_repo_head_hexsha": "f705f8a53d358c85f2d7e7d1a36536492d448a8e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.65, "max_line_length": 85, "alphanum_fraction": 0.7045813586, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5111959467727076}}
{"text": "#include \"catch.hpp\"\n#include <boost/icl/interval.hpp>\n#include <boost/icl/interval_set.hpp>\n#include <boost/icl/separate_interval_set.hpp>\n#include <boost/optional.hpp>\n\nTEST_CASE(\"interval tests\", \"[boost]\") {\n  using namespace boost::icl;\n\n  SECTION(\"closed intervals\") {\n    auto ival = interval<int>::closed(1, 3);\n    REQUIRE(ival.lower() == 1);\n    REQUIRE(ival.upper() == 3);\n  }\n\n  SECTION(\"open intervals\") {\n    auto ival = interval<int>::open(1, 3);\n    REQUIRE(ival.lower() == 1);\n    REQUIRE(ival.upper() == 3);\n  }\n\n  SECTION(\"interval sets\") {\n    //interval sets contain exactly one interval at any time.\n    //interval bounds expand based on addition of new intervals.\n    auto iSet = interval_set<int>{};\n    iSet += interval<int>::closed(1, 3);\n    iSet += interval<int>::closed(2, 5); //upper bound expands to 5\n    iSet += interval<int>::closed(0, 4); //lower bound expands to 0\n    REQUIRE(contains(iSet, 0));\n    REQUIRE(contains(iSet, 3));\n    REQUIRE(contains(iSet, 5));\n    REQUIRE_FALSE(contains(iSet, 7));\n  }\n\n  SECTION(\"separate interval sets\") {\n    auto siSet = separate_interval_set<int>{};\n    siSet += interval<int>::closed(1, 3); //is now {(1,3)}\n    siSet += interval<int>::closed(9, 10); //is now {(1,3), (9,10)}\n    siSet += interval<int>::closed(2, 5); //is now {(1,5), (9,10)}\n \n    REQUIRE(contains(siSet, 4));\n    REQUIRE_FALSE(contains(siSet, 7));\n    REQUIRE_FALSE(contains(siSet, 8));\n    REQUIRE(contains(siSet, 9));\n\n    REQUIRE(intersects(siSet, interval<int>::closed(2, 7)));\n    REQUIRE_FALSE(intersects(siSet, interval<int>::closed(11, 12)));\n    REQUIRE(intersects(siSet, interval<int>::closed(5, 6)));\n    REQUIRE(intersects(siSet, interval<int>::closed(5, 9)));\n    REQUIRE_FALSE(intersects(siSet, interval<int>::closed(7, 8)));\n    REQUIRE(intersects(siSet, interval<int>::closed(7, 9)));\n  }\n}\n\nTEST_CASE(\"optional test\", \"[boost]\") {\n  SECTION(\"optional construction\") {\n    auto optInt = boost::optional<int>{};\n    REQUIRE_FALSE(optInt.is_initialized());\n    optInt = 1;\n    REQUIRE(optInt.is_initialized());\n    REQUIRE(optInt.get() == 1);\n  }\n\n  SECTION(\"optional returning function\") {\n    auto positivePart = [](int num)->boost::optional<int> {\n      return num > 0 ? num : boost::optional<int>{};\n    };\n\n    auto optVal = positivePart(5);\n    REQUIRE(optVal.is_initialized());\n    REQUIRE(optVal.get() == 5);\n    REQUIRE_FALSE(positivePart(-5).is_initialized());\n  }\n}\n", "meta": {"hexsha": "4123b237f70138a787117dc086c1138f2312a7ef", "size": 2436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp-tests/boost.cpp", "max_stars_repo_name": "skeept/t2", "max_stars_repo_head_hexsha": "8c03b4cb324e9a6d614edf84339bda5d9432b1b2", "max_stars_repo_licenses": ["MIT"], "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-tests/boost.cpp", "max_issues_repo_name": "skeept/t2", "max_issues_repo_head_hexsha": "8c03b4cb324e9a6d614edf84339bda5d9432b1b2", "max_issues_repo_licenses": ["MIT"], "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-tests/boost.cpp", "max_forks_repo_name": "skeept/t2", "max_forks_repo_head_hexsha": "8c03b4cb324e9a6d614edf84339bda5d9432b1b2", "max_forks_repo_licenses": ["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.48, "max_line_length": 68, "alphanum_fraction": 0.6408045977, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5111959349654113}}
{"text": "/*\nCopyright (c) 2012-2018, Visillect Service LLC. All rights reserved.\nDeveloped for Kharkevich Institute for Information Transmission Problems of the\n              Russian Academy of Sciences (IITP RAS).\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n   1. Redistributions of source code must retain the above copyright notice,\n      this 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\nTHIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS \"AS IS\" AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nThe views and conclusions contained in the software and documentation are those\nof the authors and should not be interpreted as representing official policies,\neither expressed or implied, of copyright holders.\n*/\n\n\n#include <cassert>\n#include <cmath>\n#include <algorithm>\n\n#include <colorseg/color_vertex.h>\n\nTHIRDPARTY_INCLUDES_BEGIN\n#include <Eigen/Dense>\nTHIRDPARTY_INCLUDES_END\n\nnamespace vi { namespace colorseg {\n\ninline Eigen::Vector3d homographyInv(Eigen::Vector3d const & src, double a, double k)\n{\n  double EPS = 1.e-5;\n  assert(k > -EPS);\n  assert(a > -EPS);\n  assert(a < 1 + EPS);\n\n  Eigen::Vector4d src_vec(src[0] / 255., src[1] / 255., src[2] / 255., 1);\n\n  Eigen::Matrix<double, 4, 4> H = Eigen::MatrixXd::Identity(4, 4);\n  for (int i = 0; i < 3; ++i)\n    H(3, i) = k;\n\n  Eigen::Matrix<double, 4, 4> S = Eigen::MatrixXd::Identity(4, 4);\n  for (int i = 0; i < 3; ++i)\n    S(i, i) = k + 1;\n\n  Eigen::Matrix<double, 4, 4> A = Eigen::MatrixXd::Identity(4, 4);\n  for (int i = 0; i < 3; ++i)\n    for (int j = 0; j < 3; ++j)\n        if (i != j)\n            A(i, j) = a;\n\n  Eigen::Matrix<double, 4, 4> P = A * S * H;\n  Eigen::Vector4d dst_vec = P.inverse() * src_vec;\n\n  if (std::abs(dst_vec[3]) >= EPS)\n  {\n    for (int i = 0; i < 3; i++)\n      dst_vec[i] = (dst_vec[i] / dst_vec[3]) * 255;\n  }\n\n  return Eigen::Vector3d(dst_vec[0], dst_vec[1], dst_vec[2]);\n}\n\ninline void homography(double * dst, uint8_t const * src, double a, double k)\n{\n  double EPS = 1.e-5;\n  assert(k > -EPS);\n  assert(a > -EPS);\n  assert(a < 1 + EPS);\n\n  Eigen::Vector4d src_vec((double)src[0] / 255., (double)src[1] / 255., (double)src[2] / 255., 1);\n\n  Eigen::Matrix<double, 4, 4> H = Eigen::MatrixXd::Identity(4, 4);\n  for (int i = 0; i < 3; ++i)\n    H(3, i) = k;\n\n  Eigen::Matrix<double, 4, 4> S = Eigen::MatrixXd::Identity(4, 4);\n  for (int i = 0; i < 3; ++i)\n    S(i, i) = k + 1;\n\n  Eigen::Matrix<double, 4, 4> A = Eigen::MatrixXd::Identity(4, 4);\n  for (int i = 0; i < 3; ++i)\n    for (int j = 0; j < 3; ++j)\n        if (i != j)\n            A(i, j) = a;\n\n  Eigen::Matrix<double, 4, 4> P = A * S * H;\n  Eigen::Vector4d dst_vec = P * src_vec;\n\n  if (std::abs(dst_vec[3]) >= EPS)\n  {\n    for (int i = 0; i < 3; i++)\n      dst_vec[i] = (dst_vec[i] / dst_vec[3]) * 255;\n  }\n\n  dst[0] = dst_vec[0];\n  dst[1] = dst_vec[1];\n  dst[2] = dst_vec[2];\n}\n\n}} // ns vi::colorseg\n", "meta": {"hexsha": "dd54ac5e1db84a3b2ec0428e6b452bbd879710cd", "size": 3798, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vi_packages/colorseg/include/colorseg/colorspace_homography.hpp", "max_stars_repo_name": "dketterer/colorsegmentation", "max_stars_repo_head_hexsha": "58440fc4eb9aeb7e025a91b521e56c87c154b176", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-05-27T07:04:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T16:27:01.000Z", "max_issues_repo_path": "vi_packages/colorseg/include/colorseg/colorspace_homography.hpp", "max_issues_repo_name": "Visillect/segmentation", "max_issues_repo_head_hexsha": "07cb7ec960a7f8461aedcf8f8d08a1abc79f297f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vi_packages/colorseg/include/colorseg/colorspace_homography.hpp", "max_forks_repo_name": "Visillect/segmentation", "max_forks_repo_head_hexsha": "07cb7ec960a7f8461aedcf8f8d08a1abc79f297f", "max_forks_repo_licenses": ["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.186440678, "max_line_length": 98, "alphanum_fraction": 0.6566614007, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5110507330832469}}
{"text": " #ifndef REDDM_H\n#define REDDM_H\n#include\"basis.hpp\"\n#include <Eigen/Dense>\n#include\"diag.h\"\nnamespace Many_Body{\n  template<typename T>\n  using MatrixD =Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n  template<typename T>\n  using VectorD =Eigen::Matrix<T,  Eigen::Dynamic, 1>;\n  template<typename T>\n  inline T conj(T a)\n  {return a;}\n  \n    template<typename T>\n  inline std::complex< T > conj(std::complex< T > a)\n  { std::complex< T > b(real(a), -imag(a));\n    return b;}\n  \n  template<typename TotalBasis, typename Matrix, typename Vector>\n  std::vector<Eigen::VectorXd> makeThermalRDMTP(Matrix& H, Vector& ev, TotalBasis& TP, double T, bool isDiag=false, int site=0)\n{\n  double beta=1./T;\n  if(!isDiag)\n    {\n  diagMat(H, ev);\n    }\n  std::cout<< \"GS \"<< ev[0]<<std::endl;\n  Eigen::MatrixXd rho=Eigen::MatrixXd::Zero(H.rows(), H.rows());\n  double Z{0};\n  //  std::cout<< ev << std::endl;\n  for(int i=0; i<rho.rows(); i++)\n    {\n      rho(i, i)=std::exp(-beta*ev(i));\n      Z+=std::exp(-beta*ev(i));\n    }\n  std::cout<< \"Z \"<<std::setprecision(9)<< Z << std::endl;\n  rho/=Z;\n  //  std::cout<< rho<< std::endl;\n  \n  rho=rho*H.adjoint();\n  rho=H*rho;\n  std::vector<Eigen::VectorXd> evs;\n  auto RDM= makeRedDMTP(TP, TP.rbasis, site, rho);\n  Eigen::MatrixXd S=Eigen::MatrixXd::Zero(RDM[0].rows(), RDM[0].rows());\n  for(auto& M : RDM){\n\n  Eigen::VectorXd evRDM=Eigen::VectorXd::Zero(M.rows());\n  std::cout<< \"matri x\"<< std::endl;\n  std::cout<< M<< std::endl;\n  S+=M;\n  std::cout<< std::endl;\n  diagMat(M, evRDM);\n  evs.push_back(evRDM);\n  \n  }\n    std::cout<< \"SUM OF all\"<< std::endl;\n  std::cout<< S<< std::endl;\n    std::cout<< \"\"<< std::endl;\n\n  return evs;\n}\ntemplate<typename Basis, typename T>\nvoid makeRedDM(Basis& basis, int site, MatrixD<T>& rho )\n{\n  size_t dim=basis.maxParticles+1;\n  MatrixD<T> DM=MatrixD<T>::Zero(dim, dim);\n  for(auto it= basis.begin(); it!=basis.end(); ++it)\n    {\n      //      std::cout<< \" loop 1 \"<<std::endl;\n      auto currentID1 =Id(*it);\n      auto p1=basis.particlesAt(currentID1, site);\n      DM(p1, p1)+=rho(Position(*it), Position(*it));\n      auto itx=it;\n      itx++;\n      for(auto it2= itx; it2!=basis.end(); ++it2)\n    {\n      //            std::cout<< \" loop 2 \"<<std::endl;\n      \n      auto currentID2 =Id(*it2);\n       auto state1=GetLattice(*it).makeStateVec();\n       auto state2=GetLattice(*it2).makeStateVec();\n       auto p2=basis.particlesAt(currentID2, site);\n       state1.erase(state1.begin()+site);\n       state2.erase(state2.begin()+site);\n       if(state1==state2)\n\t {\n      DM(p1, p2)+=rho(Position(*it), Position(*it2));\n      DM(p2, p1)+=rho(Position(*it2), Position(*it));\n      // std::cout << currentID1 << \" part a 1 \" << p1 << std::endl;\n      //       std::cout << currentID2 << \" part a 2 \" << p2 << std::endl;\n\t }\n    }\n    }\n  \n  std::cout<< DM << std::endl;\n}\n  template<typename Basis, typename T>\n  void makeRedDM(Basis& basis, int site, VectorD<T>& psi)\n{\n  size_t dim=basis.maxParticles+1;\n  \n  MatrixD<T> DM=MatrixD<T>::Zero(dim, dim);\n  for(auto it= basis.begin(); it!=basis.end(); ++it)\n    {\n      //      std::cout<< \" loop 1 \"<<std::endl;\n      auto currentID1 =Id(*it);\n      auto p1=basis.particlesAt(currentID1, site);\n      DM(p1, p1)+=Many_Body::conj(static_cast<T>((psi(Position(*it)))))*(psi(Position(*it)));\n\t      //rho(Position(*it), Position(*it));\n      auto itx=it;\n      itx++;\n      for(auto it2= itx; it2!=basis.end(); ++it2)\n    {\n      //            std::cout<< \" loop 2 \"<<std::endl;\n      \n      auto currentID2 =Id(*it2);\n       auto state1=GetLattice(*it).makeStateVec();\n       auto state2=GetLattice(*it2).makeStateVec();\n       auto p2=basis.particlesAt(currentID2, site);\n       state1.erase(state1.begin()+site);\n       state2.erase(state2.begin()+site);\n       if(state1==state2)\n\t {\n\t   DM(p1, p2)+=Many_Body::conj(static_cast<T>((psi(Position(*it2)))))*(psi(Position(*it)));\n\t//rho(Position(*it), Position(*it2));\n\n\t   DM(p2, p1)+=Many_Body::conj(static_cast<T>((psi(Position(*it)))))*(psi(Position(*it2)));\n\t//rho(Position(*it2), Position(*it));\n      // std::cout << currentID1 << \" part a 1 \" << p1 << std::endl;\n      //       std::cout << currentID2 << \" part a 2 \" << p2 << std::endl;\n\t }\n    }\n    }\n  \n  std::cout<< DM << std::endl;\n}\n\ntemplate<typename TotalBasis, class SubBasis, typename T>\nstd::vector<MatrixD<T>> makeRedDMTP(const TotalBasis& totalBasis, const SubBasis& subBasis, int site, MatrixD<T>& rho )\n{\n  // making reduced DM for each degree of freedom in subasis L   \n\n\n\n\n       std::vector<MatrixD<T>> mats(totalBasis.lbasis.maxParticles+1);\n       size_t dim=(totalBasis.rbasis.maxParticles+1);\n\n       std::fill(mats.begin(), mats.end(), MatrixD<T>::Zero(dim, dim));\n\n       \n       //  std::cout<< dim << std::endl;\n\n  for(auto it= totalBasis.begin(); it!=totalBasis.end(); ++it)\n    {\n      auto itL=totalBasis.lbasis.find(LeftId(*it));\n      auto itR=totalBasis.rbasis.find(RightId(*it));\n      \n      //      std::cout<< \" loop 1 \"<<std::endl;\n       auto currentID1L =Id(*itL);\n       auto currentID1R =Id(*itR);\n       auto p1L=totalBasis.lbasis.particlesAt(currentID1L, site);\n       auto p1R=totalBasis.rbasis.particlesAt(currentID1R, site);\n       // unsafe way to determine the position in the matrix\n       // upper first fix electron then iterate boson\n       size_t newPos= p1R;\n       \n       //       if(std::abs(rho(Position(*it), Position(*it)))>0.001){std::cout<< \" her \"<< p1L<< \"  \" << p1R << std::endl;}\n       auto itx=it;\n       // itx++;\n       for(auto it2= itx; it2!=totalBasis.end(); ++it2)\n     {\n         auto it2L=totalBasis.lbasis.find(LeftId(*it2));\n      auto it2R=totalBasis.rbasis.find(RightId(*it2));\n      \n      //      std::cout<< \" loop 1 \"<<std::endl; // re think this one\n       auto currentID2L =Id(*it2L);\n       auto currentID2R =Id(*it2R);\n       auto p2L=totalBasis.lbasis.particlesAt(currentID2L, site);\n       auto p2R=totalBasis.rbasis.particlesAt(currentID2R, site);\n       size_t newPos2=p2R;\n       // making the delta function\n       auto state1L=GetLattice(*itL).makeStateVec();\n       auto state1R=GetLattice(*itR).makeStateVec();\n       auto state2L=GetLattice(*it2L).makeStateVec();\n       auto state2R=GetLattice(*it2R).makeStateVec();\n       state1L.erase(state1L.begin()+site);\n       state2L.erase(state2L.begin()+site);\n       state1R.erase(state1R.begin()+site);\n       state2R.erase(state2R.begin()+site);\n       if(state1L==state2L and state1R==state2R)\n\t {\n\t   //if(p2L!=p1L){std::cout << \"here \"<< std::endl;}\n\t   if(newPos!=newPos2){\n       mats[p2L](newPos, newPos2)+=rho(Position(*it), Position(*it2));\n       mats[p2L](newPos2, newPos)+=rho(Position(*it2), Position(*it));\n\t   }\n\t   else{\n\t     mats[p1L](newPos, newPos)+=rho(Position(*it), Position(*it2));\n\t   }\n\t }\n         }\n}\n  return mats;\n}\n\n  template<typename TotalBasis, class SubBasis, typename T>\nstd::vector<MatrixD<T>> makeRedDMTP(const TotalBasis& totalBasis, const SubBasis& subBasis, int site, VectorD<T>& psi )\n{\n  // making reduced DM for each degree of freedom in subasis L   \n\n\n\n\n\n   \n   \n       std::vector<MatrixD<T>> mats(totalBasis.lbasis.maxParticles+1);\n       size_t dim=(totalBasis.rbasis.maxParticles+1);\n\n       std::fill(mats.begin(), mats.end(), MatrixD<T>::Zero(dim, dim));\n\n       \n       //  std::cout<< dim << std::endl;\n\n  for(auto it= totalBasis.begin(); it!=totalBasis.end(); ++it)\n    {\n      auto itL=totalBasis.lbasis.find(LeftId(*it));\n      auto itR=totalBasis.rbasis.find(RightId(*it));\n      \n      //      std::cout<< \" loop 1 \"<<std::endl;\n       auto currentID1L =Id(*itL);\n       auto currentID1R =Id(*itR);\n       auto p1L=totalBasis.lbasis.particlesAt(currentID1L, site);\n       auto p1R=totalBasis.rbasis.particlesAt(currentID1R, site);\n       // unsafe way to determine the position in the matrix\n       // upper first fix electron then iterate boson\n       size_t newPos= p1R;\n       mats[p1L](newPos, newPos)+=Many_Body::conj(static_cast<T>((psi(Position(*it)))))*(psi(Position(*it)));\n\n       //       if(std::abs(rho(Position(*it), Position(*it)))>0.001){std::cout<< \" her \"<< p1L<< \"  \" << p1R << std::endl;}\n       auto itx=it;\n       itx++;\n       for(auto it2= itx; it2!=totalBasis.end(); ++it2)\n     {\n         auto it2L=totalBasis.lbasis.find(LeftId(*it2));\n      auto it2R=totalBasis.rbasis.find(RightId(*it2));\n      \n      //      std::cout<< \" loop 1 \"<<std::endl;\n       auto currentID2L =Id(*it2L);\n       auto currentID2R =Id(*it2R);\n       auto p2L=totalBasis.lbasis.particlesAt(currentID2L, site);\n       auto p2R=totalBasis.rbasis.particlesAt(currentID2R, site);\n       size_t newPos2=p2R;\n       // making the delta function\n       auto state1L=GetLattice(*itL).makeStateVec();\n       auto state1R=GetLattice(*itR).makeStateVec();\n       auto state2L=GetLattice(*it2L).makeStateVec();\n       auto state2R=GetLattice(*it2R).makeStateVec();\n       state1L.erase(state1L.begin()+site);\n       state2L.erase(state2L.begin()+site);\n       state1R.erase(state1R.begin()+site);\n       state2R.erase(state2R.begin()+site);\n       if(state1L==state2L and state1R==state2R)\n\t {\n\t   mats[p2L](newPos, newPos2)+=Many_Body::conj(static_cast<T>((psi(Position(*it2)))))*(psi(Position(*it)));\n\n\t //rho(Position(*it), Position(*it2));\n\t   mats[p2L](newPos2, newPos)+=Many_Body::conj(static_cast<T>((psi(Position(*it)))))*(psi(Position(*it2)));\n\t //rho(Position(*it2), Position(*it));\n       \t   \n\n\n\t }\n         }\n}\n  return mats;\n}\n  \n}\n\n\n#endif /* REDDM_H */\n", "meta": {"hexsha": "108ff6469b1241e0dbbd1f2a7d8a04db8d78e1ec", "size": 9490, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/reddm.hpp", "max_stars_repo_name": "jansendavid/many-body-lib", "max_stars_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_stars_repo_licenses": ["MIT"], "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/reddm.hpp", "max_issues_repo_name": "jansendavid/many-body-lib", "max_issues_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_issues_repo_licenses": ["MIT"], "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/reddm.hpp", "max_forks_repo_name": "jansendavid/many-body-lib", "max_forks_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_forks_repo_licenses": ["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.298245614, "max_line_length": 127, "alphanum_fraction": 0.5969441517, "num_tokens": 2978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5110507294019369}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2008 - 2020 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: Daniel Arndt, Matthias Maier, 2015 \n * \n * Based on step-22 by Wolfgang Bangerth and Martin Kronbichler \n */ \n\n\n\n// \u8fd9\u4e2a\u4f8b\u5b50\u7a0b\u5e8f\u662f\u5bf9 step-22 \u7684\u8f7b\u5fae\u4fee\u6539\uff0c\u4f7f\u7528Trilinos\u5e76\u884c\u8fd0\u884c\uff0c\u4ee5\u6f14\u793a\u4ea4\u6613.II\u4e2d\u5468\u671f\u6027\u8fb9\u754c\u6761\u4ef6\u7684\u4f7f\u7528\u3002\u56e0\u6b64\u6211\u4eec\u4e0d\u8ba8\u8bba\u5927\u90e8\u5206\u7684\u6e90\u4ee3\u7801\uff0c\u53ea\u5bf9\u5904\u7406\u5468\u671f\u6027\u7ea6\u675f\u7684\u90e8\u5206\u8fdb\u884c\u8bc4\u8bba\u3002\u5176\u4f59\u7684\u8bf7\u770b step-22 \u548c\u5e95\u90e8\u7684\u5b8c\u6574\u6e90\u4ee3\u7801\u3002\n\n// \u4e3a\u4e86\u5b9e\u73b0\u5468\u671f\u6027\u8fb9\u754c\u6761\u4ef6\uff0c\u53ea\u6709\u4e24\u4e2a\u51fd\u6570\u9700\u8981\u4fee\u6539\u3002\n\n// -  <code>StokesProblem<dim>::setup_dofs()</code>  : \u7528\u5468\u671f\u6027\u7ea6\u675f\u6765\u586b\u5145AffineConstraints\u5bf9\u8c61\n\n// -  <code>StokesProblem<dim>::create_mesh()</code>  : \u4e3a\u5206\u5e03\u5f0f\u4e09\u89d2\u5f62\u63d0\u4f9b\u5468\u671f\u6027\u4fe1\u606f\u3002\n\n// \u7a0b\u5e8f\u7684\u5176\u4f59\u90e8\u5206\u4e0e step-22 \u76f8\u540c\uff0c\u6240\u4ee5\u8ba9\u6211\u4eec\u8df3\u8fc7\u8fd9\u4e00\u90e8\u5206\uff0c\u53ea\u5728\u4e0b\u9762\u663e\u793a\u8fd9\u4e24\u4e2a\u51fd\u6570\u3002\u5b8c\u6574\u7684\u7a0b\u5e8f\u53ef\u4ee5\u5728\u4e0b\u9762\u7684 \"\u666e\u901a\u7a0b\u5e8f \"\u90e8\u5206\u627e\u5230\uff09\u3002\n\n//  @cond  \u8df3\u8fc7\n\n#include <deal.II/base/conditional_ostream.h> \n\n#include <deal.II/distributed/grid_refinement.h> \n\n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/affine_constraints.h> \n\n#include <deal.II/lac/trilinos_solver.h> \n#include <deal.II/lac/trilinos_precondition.h> \n#include <deal.II/lac/trilinos_block_sparse_matrix.h> \n#include <deal.II/lac/trilinos_parallel_block_vector.h> \n#include <deal.II/lac/block_sparsity_pattern.h> \n\n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_tools.h> \n\n#include <deal.II/dofs/dof_renumbering.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/mapping_q.h> \n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n\nnamespace Step45 \n{ \n  using namespace dealii; \n\n  template <int dim> \n  class StokesProblem \n  { \n  public: \n    StokesProblem(const unsigned int degree); \n    void run(); \n\n  private: \n    void create_mesh(); \n    void setup_dofs(); \n    void assemble_system(); \n    void solve(); \n    void output_results(const unsigned int refinement_cycle) const; \n    void refine_mesh(); \n\n    const unsigned int degree; \n\n    MPI_Comm mpi_communicator; \n\n    parallel::distributed::Triangulation<dim> triangulation; \n    FESystem<dim>                             fe; \n    DoFHandler<dim>                           dof_handler; \n\n    AffineConstraints<double> constraints; \n    std::vector<IndexSet>     owned_partitioning; \n    std::vector<IndexSet>     relevant_partitioning; \n\n    TrilinosWrappers::BlockSparseMatrix system_matrix; \n\n    TrilinosWrappers::BlockSparseMatrix preconditioner_matrix; \n\n    TrilinosWrappers::MPI::BlockVector solution; \n    TrilinosWrappers::MPI::BlockVector system_rhs; \n\n    ConditionalOStream pcout; \n\n    MappingQ<dim> mapping; \n  }; \n\n  template <int dim> \n  class BoundaryValues : public Function<dim> \n  { \n  public: \n    BoundaryValues() \n      : Function<dim>(dim + 1) \n    {} \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n\n    virtual void vector_value(const Point<dim> &p, \n                              Vector<double> &  value) const override; \n  }; \n\n  template <int dim> \n  double BoundaryValues<dim>::value(const Point<dim> & /*p*/, \n                                    const unsigned int component) const \n  { \n    (void)component; \n    Assert(component < this->n_components, \n           ExcIndexRange(component, 0, this->n_components)); \n\n    return 0; \n  } \n\n  template <int dim> \n  void BoundaryValues<dim>::vector_value(const Point<dim> &p, \n                                         Vector<double> &  values) const \n  { \n    for (unsigned int c = 0; c < this->n_components; ++c) \n      values(c) = BoundaryValues<dim>::value(p, c); \n  } \n\n  template <int dim> \n  class RightHandSide : public Function<dim> \n  { \n  public: \n    RightHandSide() \n      : Function<dim>(dim + 1) \n    {} \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n\n    virtual void vector_value(const Point<dim> &p, \n                              Vector<double> &  value) const override; \n  }; \n\n  template <int dim> \n  double RightHandSide<dim>::value(const Point<dim> & p, \n                                   const unsigned int component) const \n  { \n    const Point<dim> center(0.75, 0.1); \n    const double     r = (p - center).norm(); \n\n    if (component == 0) \n      return std::exp(-100. * r * r); \n    return 0; \n  } \n\n  template <int dim> \n  void RightHandSide<dim>::vector_value(const Point<dim> &p, \n                                        Vector<double> &  values) const \n  { \n    for (unsigned int c = 0; c < this->n_components; ++c) \n      values(c) = RightHandSide<dim>::value(p, c); \n  } \n\n  template <class MatrixType, class PreconditionerType> \n  class InverseMatrix : public Subscriptor \n  { \n  public: \n    InverseMatrix(const MatrixType &        m, \n                  const PreconditionerType &preconditioner, \n                  const IndexSet &          locally_owned, \n                  const MPI_Comm &          mpi_communicator); \n\n    void vmult(TrilinosWrappers::MPI::Vector &      dst, \n               const TrilinosWrappers::MPI::Vector &src) const; \n\n  private: \n    const SmartPointer<const MatrixType>         matrix; \n    const SmartPointer<const PreconditionerType> preconditioner; \n\n    const MPI_Comm *                      mpi_communicator; \n    mutable TrilinosWrappers::MPI::Vector tmp; \n  }; \n\n  template <class MatrixType, class PreconditionerType> \n  InverseMatrix<MatrixType, PreconditionerType>::InverseMatrix( \n    const MatrixType &        m, \n    const PreconditionerType &preconditioner, \n    const IndexSet &          locally_owned, \n    const MPI_Comm &          mpi_communicator) \n    : matrix(&m) \n    , preconditioner(&preconditioner) \n    , mpi_communicator(&mpi_communicator) \n    , tmp(locally_owned, mpi_communicator) \n  {} \n\n  template <class MatrixType, class PreconditionerType> \n  void InverseMatrix<MatrixType, PreconditionerType>::vmult( \n    TrilinosWrappers::MPI::Vector &      dst, \n    const TrilinosWrappers::MPI::Vector &src) const \n  { \n    SolverControl              solver_control(src.size(), 1e-6 * src.l2_norm()); \n    TrilinosWrappers::SolverCG cg(solver_control, \n                                  TrilinosWrappers::SolverCG::AdditionalData()); \n\n    tmp = 0.; \n    cg.solve(*matrix, tmp, src, *preconditioner); \n    dst = tmp; \n  } \n\n  template <class PreconditionerType> \n  class SchurComplement : public TrilinosWrappers::SparseMatrix \n  { \n  public: \n    SchurComplement(const TrilinosWrappers::BlockSparseMatrix &system_matrix, \n                    const InverseMatrix<TrilinosWrappers::SparseMatrix, \n                                        PreconditionerType> &  A_inverse, \n                    const IndexSet &                           owned_pres, \n                    const MPI_Comm &mpi_communicator); \n\n    void vmult(TrilinosWrappers::MPI::Vector &      dst, \n               const TrilinosWrappers::MPI::Vector &src) const; \n\n  private: \n    const SmartPointer<const TrilinosWrappers::BlockSparseMatrix> system_matrix; \n    const SmartPointer< \n      const InverseMatrix<TrilinosWrappers::SparseMatrix, PreconditionerType>> \n                                          A_inverse; \n    mutable TrilinosWrappers::MPI::Vector tmp1, tmp2; \n  }; \n\n  template <class PreconditionerType> \n  SchurComplement<PreconditionerType>::SchurComplement( \n    const TrilinosWrappers::BlockSparseMatrix &system_matrix, \n    const InverseMatrix<TrilinosWrappers::SparseMatrix, PreconditionerType> \n      &             A_inverse, \n    const IndexSet &owned_vel, \n    const MPI_Comm &mpi_communicator) \n    : system_matrix(&system_matrix) \n    , A_inverse(&A_inverse) \n    , tmp1(owned_vel, mpi_communicator) \n    , tmp2(tmp1) \n  {} \n\n  template <class PreconditionerType> \n  void SchurComplement<PreconditionerType>::vmult( \n    TrilinosWrappers::MPI::Vector &      dst, \n    const TrilinosWrappers::MPI::Vector &src) const \n  { \n    system_matrix->block(0, 1).vmult(tmp1, src); \n    A_inverse->vmult(tmp2, tmp1); \n    system_matrix->block(1, 0).vmult(dst, tmp2); \n  } \n\n  template <int dim> \n  StokesProblem<dim>::StokesProblem(const unsigned int degree) \n    : degree(degree) \n    , mpi_communicator(MPI_COMM_WORLD) \n    , triangulation(mpi_communicator) \n    , fe(FE_Q<dim>(degree + 1), dim, FE_Q<dim>(degree), 1) \n    , dof_handler(triangulation) \n    , pcout(std::cout, Utilities::MPI::this_mpi_process(mpi_communicator) == 0) \n    , mapping(degree + 1) \n  {} \n// @endcond  \n// @sect3{Setting up periodicity constraints on distributed triangulations}  \n  template <int dim> \n  void StokesProblem<dim>::create_mesh() \n  { \n    Point<dim>   center; \n    const double inner_radius = .5; \n    const double outer_radius = 1.; \n\n    GridGenerator::quarter_hyper_shell( \n      triangulation, center, inner_radius, outer_radius, 0, true); \n\n// \u5728\u6211\u4eec\u53ef\u4ee5\u89c4\u5b9a\u5468\u671f\u6027\u7ea6\u675f\u4e4b\u524d\uff0c\u6211\u4eec\u9700\u8981\u786e\u4fdd\u4f4d\u4e8e\u57df\u7684\u5bf9\u9762\u4f46\u7531\u5468\u671f\u6027\u9762\u8fde\u63a5\u7684\u5355\u5143\u662f\u5e7d\u7075\u5c42\u7684\u4e00\u90e8\u5206\uff0c\u5982\u679c\u5176\u4e2d\u4e00\u4e2a\u5355\u5143\u5b58\u50a8\u5728\u672c\u5730\u5904\u7406\u5668\u4e0a\u3002\u5728\u8fd9\u4e00\u70b9\u4e0a\uff0c\u6211\u4eec\u9700\u8981\u8003\u8651\u6211\u4eec\u8981\u5982\u4f55\u89c4\u5b9a\u5468\u671f\u6027\u3002\u5de6\u8fb9\u8fb9\u754c\u4e0a\u7684\u9762\u7684\u9876\u70b9 $\\text{vertices}_2$ \u5e94\u8be5\u4e0e\u4e0b\u9762\u8fb9\u754c\u4e0a\u7684\u9762\u7684\u9876\u70b9 $\\text{vertices}_1$ \u76f8\u5339\u914d\uff0c\u7531 $\\text{vertices}_2=R\\cdot \\text{vertices}_1+b$ \u7ed9\u51fa\uff0c\u5176\u4e2d\u65cb\u8f6c\u77e9\u9635 $R$ \u548c\u504f\u79fb\u91cf $b$ \u7531\n//  @f{align*}\n//  R=\\begin{pmatrix}\n//  0&1\\\\-1&0\n//  \\end{pmatrix},\n//  \\quad\n//  b=\\begin{pmatrix}0&0\\end{pmatrix}.\n//  @f}\n//  \u7ed9\u51fa\u3002 \u6211\u4eec\u5c06\u6240\u5f97\u4fe1\u606f\u4fdd\u5b58\u5230\u8fd9\u91cc\u7684\u6570\u636e\u7ed3\u6784\u662f\u57fa\u4e8e\u4e09\u89d2\u7ed3\u6784\u7684\u3002\n\n    std::vector<GridTools::PeriodicFacePair< \n      typename parallel::distributed::Triangulation<dim>::cell_iterator>> \n      periodicity_vector; \n\n    FullMatrix<double> rotation_matrix(dim); \n    rotation_matrix[0][1] = 1.; \n    rotation_matrix[1][0] = -1.; \n\n    GridTools::collect_periodic_faces(triangulation, \n                                      2, \n                                      3, \n                                      1, \n                                      periodicity_vector, \n                                      Tensor<1, dim>(), \n                                      rotation_matrix); \n\n// \u73b0\u5728\uff0c\u53ea\u8981\u8c03\u7528 parallel::distributed::Triangulation::add_periodicity. \u5c31\u53ef\u4ee5\u544a\u8bc9\u4e09\u89d2\u51fd\u6570\u6240\u9700\u7684\u5468\u671f\u6027\uff0c\u7279\u522b\u5bb9\u6613\u3002\n    triangulation.add_periodicity(periodicity_vector); \n\n    triangulation.refine_global(4 - dim); \n  } \n\n  template <int dim> \n  void StokesProblem<dim>::setup_dofs() \n  { \n    dof_handler.distribute_dofs(fe); \n\n    std::vector<unsigned int> block_component(dim + 1, 0); \n    block_component[dim] = 1; \n    DoFRenumbering::component_wise(dof_handler, block_component); \n\n    const std::vector<types::global_dof_index> dofs_per_block = \n      DoFTools::count_dofs_per_fe_block(dof_handler, block_component); \n    const unsigned int n_u = dofs_per_block[0], n_p = dofs_per_block[1]; \n\n    { \n      owned_partitioning.clear(); \n      IndexSet locally_owned_dofs = dof_handler.locally_owned_dofs(); \n      owned_partitioning.push_back(locally_owned_dofs.get_view(0, n_u)); \n      owned_partitioning.push_back(locally_owned_dofs.get_view(n_u, n_u + n_p)); \n\n      relevant_partitioning.clear(); \n      IndexSet locally_relevant_dofs; \n      DoFTools::extract_locally_relevant_dofs(dof_handler, \n                                              locally_relevant_dofs); \n      relevant_partitioning.push_back(locally_relevant_dofs.get_view(0, n_u)); \n      relevant_partitioning.push_back( \n        locally_relevant_dofs.get_view(n_u, n_u + n_p)); \n\n      constraints.clear(); \n      constraints.reinit(locally_relevant_dofs); \n\n      FEValuesExtractors::Vector velocities(0); \n\n      DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n      VectorTools::interpolate_boundary_values(mapping, \n                                               dof_handler, \n                                               0, \n                                               BoundaryValues<dim>(), \n                                               constraints, \n                                               fe.component_mask(velocities)); \n      VectorTools::interpolate_boundary_values(mapping, \n                                               dof_handler, \n                                               1, \n                                               BoundaryValues<dim>(), \n                                               constraints, \n                                               fe.component_mask(velocities)); \n\n// \u5728\u6211\u4eec\u4e3a\u7f51\u683c\u63d0\u4f9b\u4e86\u5468\u671f\u6027\u7ea6\u675f\u7684\u5fc5\u8981\u4fe1\u606f\u540e\uff0c\u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u5b9e\u9645\u521b\u5efa\u5b83\u4eec\u3002\u5bf9\u4e8e\u63cf\u8ff0\u5339\u914d\uff0c\u6211\u4eec\u4f7f\u7528\u4e0e\u4e4b\u524d\u76f8\u540c\u7684\u65b9\u6cd5\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5de6\u8fb9\u8fb9\u754c\u4e0a\u7684\u4e00\u4e2a\u9762\u7684 $\\text{vertices}_2$ \u5e94\u8be5\u4e0e\u4e0b\u9762\u8fb9\u754c\u4e0a\u7684\u4e00\u4e2a\u9762\u7684\u9876\u70b9 $\\text{vertices}_1$ \u5339\u914d\uff0c\u7531 $\\text{vertices}_2=R\\cdot \\text{vertices}_1+b$  ]\uff0c\u5176\u4e2d\u65cb\u8f6c\u77e9\u9635 $R$ \u548c\u504f\u79fb\u91cf $b$ \u7531\n// @f{align*}\n//  R=\\begin{pmatrix}\n//  0&1\\\\-1&0\n//  \\end{pmatrix},\n//  \\quad\n//  b=\\begin{pmatrix}0&0\\end{pmatrix}.\n//  @f}\n//  \u7ed9\u51fa\u3002 \u8fd9\u4e24\u4e2a\u5bf9\u8c61\u4e0d\u4ec5\u63cf\u8ff0\u4e86\u5e94\u8be5\u5982\u4f55\u5339\u914d\u9762\uff0c\u800c\u4e14\u8fd8\u63cf\u8ff0\u4e86\u89e3\u51b3\u65b9\u6848\u5e94\u8be5\u4ece $\\text{face}_2$ \u8f6c\u6362\u5230 $\\text{face}_1$ \u7684\u610f\u4e49\u3002\n\n      FullMatrix<double> rotation_matrix(dim); \n      rotation_matrix[0][1] = 1.; \n      rotation_matrix[1][0] = -1.; \n\n      Tensor<1, dim> offset; \n\n// \u4e3a\u4e86\u8bbe\u7f6e\u7ea6\u675f\uff0c\u6211\u4eec\u9996\u5148\u5c06\u5468\u671f\u6027\u4fe1\u606f\u5b58\u50a8\u5728\u4e00\u4e2a\u7c7b\u578b\u4e3a <code>std::vector@<GridTools::PeriodicFacePair<typename \u7684\u8f85\u52a9\u5bf9\u8c61\u4e2d\u3002\n// DoFHandler@<dim@>::%cell_iterator@>  </code>\u3002\u5468\u671f\u6027\u8fb9\u754c\u7684\u8fb9\u754c\u6307\u6807\u4e3a2\uff08x=0\uff09\u548c3\uff08y=0\uff09\u3002\u6240\u6709\u5176\u4ed6\u7684\u53c2\u6570\u6211\u4eec\u4e4b\u524d\u5df2\u7ecf\u8bbe\u7f6e\u597d\u4e86\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u65b9\u5411\u5e76\u4e0d\u91cd\u8981\u3002\u7531\u4e8e $\\text{vertices}_2=R\\cdot \\text{vertices}_1+b$ \u8fd9\u6b63\u662f\u6211\u4eec\u60f3\u8981\u7684\u3002\n\n      std::vector< \n        GridTools::PeriodicFacePair<typename DoFHandler<dim>::cell_iterator>> \n        periodicity_vector; \n\n      const unsigned int direction = 1; \n\n      GridTools::collect_periodic_faces(dof_handler, \n                                        2, \n                                        3, \n                                        direction, \n                                        periodicity_vector, \n                                        offset, \n                                        rotation_matrix); \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u9700\u8981\u63d0\u4f9b\u5173\u4e8e\u89e3\u51b3\u65b9\u6848\u4e2d\u54ea\u4e9b\u77e2\u91cf\u503c\u5206\u91cf\u5e94\u8be5\u88ab\u65cb\u8f6c\u7684\u4fe1\u606f\u3002\u7531\u4e8e\u6211\u4eec\u5728\u8fd9\u91cc\u9009\u62e9\u53ea\u7ea6\u675f\u901f\u5ea6\uff0c\u5e76\u4e14\u4ece\u89e3\u51b3\u65b9\u6848\u77e2\u91cf\u7684\u7b2c\u4e00\u4e2a\u5206\u91cf\u5f00\u59cb\uff0c\u6211\u4eec\u53ea\u9700\u63d2\u5165\u4e00\u4e2a0\u3002\n\n      std::vector<unsigned int> first_vector_components; \n      first_vector_components.push_back(0); \n\n// \u5728\u8bbe\u7f6e\u4e86\u5468\u671f\u6027_vector\u4e2d\u7684\u6240\u6709\u4fe1\u606f\u4e4b\u540e\uff0c\u6211\u4eec\u8981\u505a\u7684\u5c31\u662f\u544a\u8bc9make_periodicity_constraints\u6765\u521b\u5efa\u6240\u9700\u7684\u7ea6\u675f\u3002\n\n      DoFTools::make_periodicity_constraints<dim, dim>(periodicity_vector, \n                                                       constraints, \n                                                       fe.component_mask( \n                                                         velocities), \n                                                       first_vector_components); \n\n      VectorTools::interpolate_boundary_values(mapping, \n                                               dof_handler, \n                                               0, \n                                               BoundaryValues<dim>(), \n                                               constraints, \n                                               fe.component_mask(velocities)); \n      VectorTools::interpolate_boundary_values(mapping, \n                                               dof_handler, \n                                               1, \n                                               BoundaryValues<dim>(), \n                                               constraints, \n                                               fe.component_mask(velocities)); \n    } \n\n    constraints.close(); \n\n    { \n      TrilinosWrappers::BlockSparsityPattern bsp(owned_partitioning, \n                                                 owned_partitioning, \n                                                 relevant_partitioning, \n                                                 mpi_communicator); \n\n      Table<2, DoFTools::Coupling> coupling(dim + 1, dim + 1); \n      for (unsigned int c = 0; c < dim + 1; ++c) \n        for (unsigned int d = 0; d < dim + 1; ++d) \n          if (!((c == dim) && (d == dim))) \n            coupling[c][d] = DoFTools::always; \n          else \n            coupling[c][d] = DoFTools::none; \n\n      DoFTools::make_sparsity_pattern(dof_handler, \n                                      coupling, \n                                      bsp, \n                                      constraints, \n                                      false, \n                                      Utilities::MPI::this_mpi_process( \n                                        mpi_communicator)); \n\n      bsp.compress(); \n\n      system_matrix.reinit(bsp); \n    } \n\n    { \n      TrilinosWrappers::BlockSparsityPattern preconditioner_bsp( \n        owned_partitioning, \n        owned_partitioning, \n        relevant_partitioning, \n        mpi_communicator); \n\n      Table<2, DoFTools::Coupling> preconditioner_coupling(dim + 1, dim + 1); \n      for (unsigned int c = 0; c < dim + 1; ++c) \n        for (unsigned int d = 0; d < dim + 1; ++d) \n          if ((c == dim) && (d == dim)) \n            preconditioner_coupling[c][d] = DoFTools::always; \n          else \n            preconditioner_coupling[c][d] = DoFTools::none; \n\n      DoFTools::make_sparsity_pattern(dof_handler, \n                                      preconditioner_coupling, \n                                      preconditioner_bsp, \n                                      constraints, \n                                      false, \n                                      Utilities::MPI::this_mpi_process( \n                                        mpi_communicator)); \n\n      preconditioner_bsp.compress(); \n\n      preconditioner_matrix.reinit(preconditioner_bsp); \n    } \n\n    system_rhs.reinit(owned_partitioning, mpi_communicator); \n    solution.reinit(owned_partitioning, \n                    relevant_partitioning, \n                    mpi_communicator); \n  } \n\n// \u7136\u540e\u7a0b\u5e8f\u7684\u5176\u4f59\u90e8\u5206\u53c8\u4e0e  step-22  \u76f8\u540c\u3002\u6211\u4eec\u73b0\u5728\u7701\u7565\u5b83\uff0c\u4f46\u548c\u4ee5\u524d\u4e00\u6837\uff0c\u4f60\u53ef\u4ee5\u5728\u4e0b\u9762\u7684 \"\u666e\u901a\u7a0b\u5e8f \"\u90e8\u5206\u627e\u5230\u8fd9\u4e9b\u90e8\u5206\u3002\n\n//  @cond  SKIP\n\n  template <int dim> \n  void StokesProblem<dim>::assemble_system() \n  { \n    system_matrix         = 0.; \n    system_rhs            = 0.; \n    preconditioner_matrix = 0.; \n\n    QGauss<dim> quadrature_formula(degree + 2); \n\n    FEValues<dim> fe_values(mapping, \n                            fe, \n                            quadrature_formula, \n                            update_values | update_quadrature_points | \n                              update_JxW_values | update_gradients); \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n\n    const unsigned int n_q_points = quadrature_formula.size(); \n\n    FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell); \n    FullMatrix<double> local_preconditioner_matrix(dofs_per_cell, \n                                                   dofs_per_cell); \n    Vector<double>     local_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    const RightHandSide<dim>    right_hand_side; \n    std::vector<Vector<double>> rhs_values(n_q_points, Vector<double>(dim + 1)); \n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure(dim); \n\n    std::vector<SymmetricTensor<2, dim>> symgrad_phi_u(dofs_per_cell); \n    std::vector<double>                  div_phi_u(dofs_per_cell); \n    std::vector<double>                  phi_p(dofs_per_cell); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        { \n          fe_values.reinit(cell); \n          local_matrix                = 0; \n          local_preconditioner_matrix = 0; \n          local_rhs                   = 0; \n\n          right_hand_side.vector_value_list(fe_values.get_quadrature_points(), \n                                            rhs_values); \n\n          for (unsigned int q = 0; q < n_q_points; ++q) \n            { \n              for (unsigned int k = 0; k < dofs_per_cell; ++k) \n                { \n                  symgrad_phi_u[k] = \n                    fe_values[velocities].symmetric_gradient(k, q); \n                  div_phi_u[k] = fe_values[velocities].divergence(k, q); \n                  phi_p[k]     = fe_values[pressure].value(k, q); \n                } \n\n              for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                { \n                  for (unsigned int j = 0; j <= i; ++j) \n                    { \n                      local_matrix(i, j) += \n                        (symgrad_phi_u[i] * symgrad_phi_u[j] // diffusion \n                         - div_phi_u[i] * phi_p[j]           // pressure force \n                         - phi_p[i] * div_phi_u[j])          // divergence \n                        * fe_values.JxW(q); \n\n                      local_preconditioner_matrix(i, j) += \n                        (phi_p[i] * phi_p[j]) * fe_values.JxW(q); \n                    } \n\n                  const unsigned int component_i = \n                    fe.system_to_component_index(i).first; \n                  local_rhs(i) += fe_values.shape_value(i, q)  // \n                                  * rhs_values[q](component_i) // \n                                  * fe_values.JxW(q); \n                } \n            } \n\n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            for (unsigned int j = i + 1; j < dofs_per_cell; ++j) \n              { \n                local_matrix(i, j) = local_matrix(j, i); \n                local_preconditioner_matrix(i, j) = \n                  local_preconditioner_matrix(j, i); \n              } \n\n          cell->get_dof_indices(local_dof_indices); \n          constraints.distribute_local_to_global(local_matrix, \n                                                 local_rhs, \n                                                 local_dof_indices, \n                                                 system_matrix, \n                                                 system_rhs); \n          constraints.distribute_local_to_global(local_preconditioner_matrix, \n                                                 local_dof_indices, \n                                                 preconditioner_matrix); \n        } \n\n    system_matrix.compress(VectorOperation::add); \n    system_rhs.compress(VectorOperation::add); \n\n    pcout << \"   Computing preconditioner...\" << std::endl << std::flush; \n  } \n\n  template <int dim> \n  void StokesProblem<dim>::solve() \n  { \n    TrilinosWrappers::PreconditionJacobi A_preconditioner; \n    A_preconditioner.initialize(system_matrix.block(0, 0)); \n\n    const InverseMatrix<TrilinosWrappers::SparseMatrix, \n                        TrilinosWrappers::PreconditionJacobi> \n      A_inverse(system_matrix.block(0, 0), \n                A_preconditioner, \n                owned_partitioning[0], \n                mpi_communicator); \n\n    TrilinosWrappers::MPI::BlockVector tmp(owned_partitioning, \n                                           mpi_communicator); \n\n \n      TrilinosWrappers::MPI::Vector schur_rhs(owned_partitioning[1], \n                                              mpi_communicator); \n      A_inverse.vmult(tmp.block(0), system_rhs.block(0)); \n      system_matrix.block(1, 0).vmult(schur_rhs, tmp.block(0)); \n      schur_rhs -= system_rhs.block(1); \n\n      SchurComplement<TrilinosWrappers::PreconditionJacobi> schur_complement( \n        system_matrix, A_inverse, owned_partitioning[0], mpi_communicator); \n\n      SolverControl solver_control(solution.block(1).size(), \n                                   1e-6 * schur_rhs.l2_norm()); \n      SolverCG<TrilinosWrappers::MPI::Vector> cg(solver_control); \n\n      TrilinosWrappers::PreconditionAMG preconditioner; \n      preconditioner.initialize(preconditioner_matrix.block(1, 1)); \n\n      InverseMatrix<TrilinosWrappers::SparseMatrix, \n                    TrilinosWrappers::PreconditionAMG> \n        m_inverse(preconditioner_matrix.block(1, 1), \n                  preconditioner, \n                  owned_partitioning[1], \n                  mpi_communicator); \n\n      cg.solve(schur_complement, tmp.block(1), schur_rhs, preconditioner); \n\n      constraints.distribute(tmp); \n      solution.block(1) = tmp.block(1); \n    } \n\n    { \n      system_matrix.block(0, 1).vmult(tmp.block(0), tmp.block(1)); \n      tmp.block(0) *= -1; \n      tmp.block(0) += system_rhs.block(0); \n\n      A_inverse.vmult(tmp.block(0), tmp.block(0)); \n\n      constraints.distribute(tmp); \n      solution.block(0) = tmp.block(0); \n    } \n  } \n\n  template <int dim> \n  void \n  StokesProblem<dim>::output_results(const unsigned int refinement_cycle) const \n  { \n    std::vector<std::string> solution_names(dim, \"velocity\"); \n    solution_names.emplace_back(\"pressure\"); \n\n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      data_component_interpretation( \n        dim, DataComponentInterpretation::component_is_part_of_vector); \n    data_component_interpretation.push_back( \n      DataComponentInterpretation::component_is_scalar); \n\n    DataOut<dim> data_out; \n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \n                             solution_names, \n                             DataOut<dim>::type_dof_data, \n                             data_component_interpretation); \n    Vector<float> subdomain(triangulation.n_active_cells()); \n    for (unsigned int i = 0; i < subdomain.size(); ++i) \n      subdomain(i) = triangulation.locally_owned_subdomain(); \n    data_out.add_data_vector(subdomain, \"subdomain\"); \n    data_out.build_patches(mapping, degree + 1); \n\n    data_out.write_vtu_with_pvtu_record( \n      \"./\", \"solution\", refinement_cycle, MPI_COMM_WORLD, 2); \n  } \n\n  template <int dim> \n  void StokesProblem<dim>::refine_mesh() \n  { \n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n\n    FEValuesExtractors::Scalar pressure(dim); \n    KellyErrorEstimator<dim>::estimate( \n      dof_handler, \n      QGauss<dim - 1>(degree + 1), \n      std::map<types::boundary_id, const Function<dim> *>(), \n      solution, \n      estimated_error_per_cell, \n      fe.component_mask(pressure)); \n\n    parallel::distributed::GridRefinement::refine_and_coarsen_fixed_number( \n      triangulation, estimated_error_per_cell, 0.3, 0.0); \n    triangulation.execute_coarsening_and_refinement(); \n  } \n\n  template <int dim> \n  void StokesProblem<dim>::run() \n  { \n    create_mesh(); \n\n    for (unsigned int refinement_cycle = 0; refinement_cycle < 9; \n         ++refinement_cycle) \n      { \n        pcout << \"Refinement cycle \" << refinement_cycle << std::endl; \n\n        if (refinement_cycle > 0) \n          refine_mesh(); \n\n        setup_dofs(); \n\n        pcout << \"   Assembling...\" << std::endl << std::flush; \n        assemble_system(); \n\n        pcout << \"   Solving...\" << std::flush; \n        solve(); \n\n        output_results(refinement_cycle); \n\n        pcout << std::endl; \n      } \n  } \n} // namespace Step45 \n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      using namespace dealii; \n      using namespace Step45; \n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); \n      StokesProblem<2>                 flow_problem(1); \n      flow_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\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// @endcond  \n\n\n", "meta": {"hexsha": "bcdddbf8cf71b685e19b666d23f39c538a5ca3c7", "size": 27875, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-45/step-45.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-45/step-45.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-45/step-45.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.0142118863, "max_line_length": 233, "alphanum_fraction": 0.557955157, "num_tokens": 7219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5109387766914417}}
{"text": "// CANONICALSTRUCTURE class for General DMPs\r\n//   Let x spread in time\r\n//   D.E Argiropoulos - General DMP - June 2020\r\n\r\n#include <iostream>\r\n#include <string>\r\n#include <armadillo>\r\n\r\nusing namespace std;\r\nusing namespace arma;\r\n\r\nclass CanonicalStructure\r\n{\r\npublic:\r\n    double ax , x0, Rx0;\r\n    vec x, dx;\r\n    vec Fx, fx;\r\n    vec Rdx, Rx;\r\n    double t0, tf, T;\r\n    double taf , dtaf ;\r\n\r\n    CanonicalStructure(int len);\r\n    ~CanonicalStructure();\r\n    void generateFx(std::string kind, vec timed);\r\n    double getFx(double t);\r\n    void generateRfx(string kind, vec timed);\r\n\r\n};\r\n\r\nCanonicalStructure::CanonicalStructure(int len)\r\n{\r\n\r\n  x.set_size(len);\r\n  dx.set_size(len);\r\n  Fx.set_size(len);\r\n  fx.set_size(len);\r\n  Rx.set_size(len);\r\n  Rdx.set_size(len);\r\n\r\n  std::cout << \"/* Constructor of CanonicalStructure */\" << '\\n';\r\n}\r\nCanonicalStructure::~CanonicalStructure()\r\n{\r\n}\r\n\r\nvoid CanonicalStructure::generateFx(string kind, vec timed)\r\n{\r\n  int len = timed.n_rows;\r\n  x0 = 0.01;\r\n  t0 = 0;\r\n  ax = 1/2;\r\n  T = timed[len-1]; // starts from 0sec - (len-1)*ts\r\n  tf = T + t0;\r\n  taf = 1;\r\n  dtaf = 0;\r\n  if ( kind == \"discrete\")\r\n  {\r\n    //CS for discrete\r\n    for (int i = 0; i<len; i++)\r\n    {\r\n      Fx[i] =  ax*timed[i];\r\n      fx[i] = ax;\r\n      x[i] = x0 + Fx[i]/taf ;\r\n      dx[i] = fx[i]/taf;\r\n    }\r\n  }\r\n}\r\n\r\ndouble CanonicalStructure::getFx(double t)\r\n{\r\n  return ax*t;\r\n}\r\n\r\nvoid CanonicalStructure::generateRfx(string kind, vec timed)\r\n{\r\n  int len = timed.n_rows;\r\n  Rx0 = x[len-1] ;\r\n  if ( kind == \"discrete\")\r\n  {\r\n    for (int i = 0;i<len;i++)\r\n    {\r\n      Rx[i] = Rx0 - Fx[i]/taf ;\r\n      Rdx[i] = -fx[i]/taf;\r\n    }\r\n\r\n  }\r\n}\r\n", "meta": {"hexsha": "7d975bb45c644ac1c2a70483173e0f9ddf3ea3c7", "size": 1671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CanonicalStructure.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/CanonicalStructure.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/CanonicalStructure.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": 18.9886363636, "max_line_length": 66, "alphanum_fraction": 0.5637342908, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5109387658565581}}
{"text": "#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <vector>\n#include <Eigen/Dense>\n#include \"tinyply.h\"\n#include \"pca.h\"\n#include <regex>\n#include <experimental/filesystem>\nnamespace fs = std::experimental::filesystem;\n\n\n\n// list of paths of all files under the directory 'dir' when the extension matches the regex\n// file_list<true> searches recursively into sub-directories; \n// file_list<false> searches only the specified directory\ntemplate <bool RECURSIVE> std::vector<fs::path> file_list(fs::path dir, std::regex ext_pattern)\n{\n\tstd::vector<fs::path> result;\n\tusing iterator = std::conditional<RECURSIVE, fs::recursive_directory_iterator, fs::directory_iterator>::type;\n\tconst iterator end;\n\tfor (iterator iter{ dir }; iter != end; ++iter)\n\t{\n\t\tconst std::string extension = iter->path().extension().string();\n\t\tif (fs::is_regular_file(*iter) && std::regex_match(extension, ext_pattern)) result.push_back(*iter);\n\t}\n\treturn result;\n}\n\n\nint main(int argc, char* argv[])\n{\n\n\tstd::cout\n\t\t<< std::fixed << std::endl\n\t\t<< \"Usage            : ./<app.exe> <dir>\" << std::endl\n\t\t<< \"Default          : ./pca_mesh.exe ../../data/\" << std::endl\n\t\t<< std::endl;\n\n\t//\n\t// Initial parameters\n\t//\n\tconst fs::path input_dir = (argc > 1) ? argv[1] : \"../../data/\";\n\tconst std::string output_filename = \"output_pca.ply\";\n\tconst std::vector<fs::path>& input_files = file_list<false>(input_dir, std::regex(\"\\\\.(?:ply)\"));\n\n\n\t// \n\t// Compose output filename\n\t//\n\tstd::stringstream output_abs_filename;\n\toutput_abs_filename << input_dir << \"/Output/\";\n\tfs::create_directory(output_abs_filename.str());\n\toutput_abs_filename << output_filename;\n\t\n\t//\n\t// Verify the first file and check the number of vertices\n\t//\n\tstd::ifstream ss(input_files.at(0).string(), std::ios::binary);\n\ttinyply::PlyFile file(ss);\n\tstd::vector<float> verts_first_file;\n\tfile.request_properties_from_element(\"vertex\", { \"x\", \"y\", \"z\" }, verts_first_file);\n\n\t//\n\t// Create matrix for PCA\n\t// \n\tEigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> pca_input_matrix(verts_first_file.size(), input_files.size());\n\n\tstd::cout << \"Matrix size: \" << pca_input_matrix.rows() << ' ' << pca_input_matrix.cols() << std::endl << std::endl;\n\n\n\tstd::vector<float> verts;\n\tstd::vector<float> norms;\n\tstd::vector<uint8_t> colors;\n\tstd::vector<uint32_t> faces;\n\tstd::vector<float> uvCoords;\n\tuint32_t file_count = 0;\n\n\tfor (const auto& filename : input_files)\n\t{\n\t\ttry\n\t\t{\n\t\t\tstd::cout << \"Reading file <\" << filename.string() << \"> ... \";\n\t\t\t// \n\t\t\t// Read source ply file\n\t\t\t//\n\t\t\tstd::ifstream ss(filename.string(), std::ios::binary);\n\t\t\ttinyply::PlyFile file(ss);\n\n\n\t\t\tuint32_t vertexCount, normalCount, colorCount, faceCount, faceTexcoordCount, faceColorCount;\n\t\t\tvertexCount = normalCount = colorCount = faceCount = faceTexcoordCount = faceColorCount = 0;\n\n\t\t\tvertexCount = file.request_properties_from_element(\"vertex\", { \"x\", \"y\", \"z\" }, verts);\n\n\t\t\tif (verts.size() != verts_first_file.size())\n\t\t\t\tthrow(\"[FAIL] The number of vertices does not match\");\n\n\t\t\tnormalCount = file.request_properties_from_element(\"vertex\", { \"nx\", \"ny\", \"nz\" }, norms);\n\t\t\tcolorCount = file.request_properties_from_element(\"vertex\", { \"red\", \"green\", \"blue\", \"alpha\" }, colors);\n\n\t\t\tfaceCount = file.request_properties_from_element(\"face\", { \"vertex_indices\" }, faces, 3);\n\t\t\tfaceTexcoordCount = file.request_properties_from_element(\"face\", { \"texcoord\" }, uvCoords, 6);\n\n\t\t\tfile.read(ss);\n\n\t\t\tfor (int i = 0; i < verts.size(); ++i)\n\t\t\t{\n\t\t\t\tpca_input_matrix(i, file_count) = verts[i];\n\t\t\t}\n\t\t\t\n\t\t\t++file_count;\n\n\t\t\tstd::cout << \"verts: \" << vertexCount << \" [OK]\" << std::endl;\n\t\t}\n\t\tcatch (const std::exception & e)\n\t\t{\n\t\t\tstd::cerr << \"Caught exception: \" << e.what() << std::endl;\n\t\t}\n\t}\n\t\n\n\n\tpca_t<float> pca;\n\tpca.set_input(pca_input_matrix);\n\tpca.compute();\n\n\tstd::cout\n\t\t<< \"Values: \\n\" << pca.get_eigen_values() << std::endl << std::endl\n\t\t<< \"Vectors: \\n\" << pca.get_eigen_vectors() << std::endl << std::endl;\n\n\tconst auto& result = pca.reprojection();\n\n\tfor (int i = 0; i < verts.size(); ++i)\n\t{\n\t\tverts[i] = result(i, 0);\n\t}\n\n\ttry\n\t{\n\t\t\n\t\t//\n\t\t// Write ply file\n\t\t//\n\t\tstd::filebuf fb;\n\t\tfb.open(output_abs_filename.str(), std::ios::out | std::ios::binary);\n\t\tstd::ostream outputStream(&fb);\n\n\t\ttinyply::PlyFile ply_out_file;\n\n\t\tif (!verts.empty())\n\t\t\tply_out_file.add_properties_to_element(\"vertex\", { \"x\", \"y\", \"z\" }, verts);\n\t\tif (!norms.empty())\n\t\t\tply_out_file.add_properties_to_element(\"vertex\", { \"nx\", \"ny\", \"nz\" }, norms);\n\t\tif (!colors.empty())\n\t\t\tply_out_file.add_properties_to_element(\"vertex\", { \"red\", \"green\", \"blue\", \"alpha\" }, colors);\n\t\tif (!faces.empty())\n\t\t\tply_out_file.add_properties_to_element(\"face\", { \"vertex_indices\" }, faces, 3, tinyply::PlyProperty::Type::UINT8);\n\t\tif (!uvCoords.empty())\n\t\t\tply_out_file.add_properties_to_element(\"face\", { \"texcoord\" }, uvCoords, 6, tinyply::PlyProperty::Type::UINT8);\n\n\t\tply_out_file.write(outputStream, true);\n\n\t\tfb.close();\n\t}\n\tcatch (const std::exception & e)\n\t{\n\t\tstd::cerr << \"Caught exception: \" << e.what() << std::endl;\n\t}\n\n}", "meta": {"hexsha": "d2719d8354525a9b82bcbdbf5028b66d4762f628", "size": 5056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pca_mesh.cpp", "max_stars_repo_name": "diegomazala/pca", "max_stars_repo_head_hexsha": "86b7688a5ebca97e3e596806038ead5a29d2855c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-29T12:23:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T12:23:02.000Z", "max_issues_repo_path": "src/pca_mesh.cpp", "max_issues_repo_name": "diegomazala/pca", "max_issues_repo_head_hexsha": "86b7688a5ebca97e3e596806038ead5a29d2855c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pca_mesh.cpp", "max_forks_repo_name": "diegomazala/pca", "max_forks_repo_head_hexsha": "86b7688a5ebca97e3e596806038ead5a29d2855c", "max_forks_repo_licenses": ["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.567251462, "max_line_length": 117, "alphanum_fraction": 0.659414557, "num_tokens": 1435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.510938765856558}}
{"text": "/**\n * \\ file OneMinusFilter.cpp\n */\n\n#include <ATK/Tools/OneMinusFilter.h>\n\n#include <ATK/Core/InPointerFilter.h>\n#include <ATK/Core/OutPointerFilter.h>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/scoped_array.hpp>\n\n#define PROCESSSIZE (1024*64)\n\nBOOST_AUTO_TEST_CASE( OneMinusFilter_sinus_test )\n{\n  boost::scoped_array<float> data(new float[PROCESSSIZE]);\n  for(int64_t i = 0; i < PROCESSSIZE; ++i)\n  {\n    data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000);\n  }\n  \n  ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);\n  generator.set_output_sampling_rate(48000);\n\n  boost::scoped_array<float> outdata(new float[PROCESSSIZE]);\n\n  ATK::OneMinusFilter<float> filter(1);\n  filter.set_input_sampling_rate(48000);\n  filter.set_input_port(0, &generator, 0);\n\n  ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);\n  output.set_input_sampling_rate(48000);\n  output.set_input_port(0, &filter, 0);\n\n  output.process(PROCESSSIZE);\n  \n  for(int64_t i = 0; i < PROCESSSIZE; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(data[i] + outdata[i], 1., 0.0001);\n  }\n}\n", "meta": {"hexsha": "d9678af324ab31f7a5d909a9fdab3a91806f57a7", "size": 1226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Tools/OneMinusFilter.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": "tests/Tools/OneMinusFilter.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": "tests/Tools/OneMinusFilter.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": 26.085106383, "max_line_length": 86, "alphanum_fraction": 0.7185970636, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5109387604391161}}
{"text": "#ifndef ALM_CONVEX_HULL_H\n#define ALM_CONVEX_HULL_H\n\n#include <vector>\n\n#include <Eigen/Dense>\n\nnamespace math_utils{\n\ntypedef double coord_t;   // coordinate type\ntypedef double coord2_t;  // must be big enough to hold 2*max(|coordinate|)^2\n\n// struct Point {\nclass Point{\npublic:\n  coord_t x, y;\n\n  Point(){}\n  Point(const coord_t x_in, const coord_t y_in){\n  \tx = x_in;\n  \ty = y_in;\n  }\n\n  bool operator<(const Point &p) const {\n    return x < p.x || (x == p.x && y < p.y);\n  }\n};\n\nstd::vector<Point> eigenToPoints(const Eigen::Ref<const Eigen::Matrix<double, 2, Eigen::Dynamic>>& P);\n\nstd::vector<Point> convexHull(std::vector<Point> P);\nbool inConvexHull(\n    const Eigen::Ref<const Eigen::Matrix<double, 2, Eigen::Dynamic>> &P,\n    const Eigen::Ref<const Eigen::Vector2d> &q, double tolerance = 1e-16);\n\n// Returns the perpendicular distance from point q to the convex hull of pts.\n// Specifically, if pts form a polytope defined by a_i'x <= b_i where each a_i\n// is a unit vector, then this returns:\n//\n// d* = min [b_i - a_i'q]\n//       i\n//\n// If q is inside the convex hull of pts, then d* will be positive, else it will\n// be negative.\ndouble signedDistanceInsideConvexHull(\n    const Eigen::Ref<const Eigen::Matrix<double, 2, Eigen::Dynamic>> &pts,\n    const Eigen::Ref<const Eigen::Vector2d> &q);\n\n}\n\n#endif\n", "meta": {"hexsha": "a3b7a2b3f91dc02e7616022027604558c9778918", "size": 1321, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/avatar_locomanipulation/helpers/convex_hull.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/convex_hull.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/convex_hull.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": 25.4038461538, "max_line_length": 102, "alphanum_fraction": 0.6805450416, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5109165882189433}}
{"text": "/*\n * testScheduler.cpp\n * @date March 25, 2011\n * @author Frank Dellaert\n */\n\n//#define ENABLE_TIMING\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/base/Testable.h>\n#include <gtsam/base/timing.h>\n#include <gtsam_unstable/discrete/Scheduler.h>\n\n#include <boost/assign/std/map.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/optional.hpp>\n\nusing namespace boost::assign;\nusing namespace std;\nusing namespace gtsam;\n\n/* ************************************************************************* */\n// Create the expected graph of constraints\nDiscreteFactorGraph createExpected() {\n  // Start building\n  size_t nrFaculty = 4, nrTimeSlots = 3;\n\n  // variables assigning a time to a student:\n  // Akansel and Jake\n  DiscreteKey A(6, nrTimeSlots), J(7, nrTimeSlots);\n\n  // variables assigning a faculty member to a student area\n  // Akansel:AI,ME,PC and Jake:HR,CT,AI\n  DiscreteKey A1(0, nrFaculty), J1(3, nrFaculty);\n  DiscreteKey A2(1, nrFaculty), J2(4, nrFaculty);\n  DiscreteKey A3(2, nrFaculty), J3(5, nrFaculty);\n\n  CSP expected;\n\n  // Area constraints\n  string faculty_in_A = \"1 0 0 1\";\n  string faculty_in_C = \"0 0 1 0\";\n  string faculty_in_H = \"0 0 0 1\";\n  string faculty_in_M = \"0 1 0 0\";\n  string faculty_in_P = \"1 0 1 0\";\n  string available = \"1 1 1 0   1 1 1 1   0 1 1 1\";\n\n  // Akansel\n  expected.add(A1, faculty_in_A);  // Area 1\n  expected.add(A1, \"1 1 1 0\");     // Advisor\n  expected.add(A & A1, available);\n  expected.add(A2, faculty_in_M);  // Area 2\n  expected.add(A2, \"1 1 1 0\");     // Advisor\n  expected.add(A & A2, available);\n  expected.add(A3, faculty_in_P);  // Area 3\n  expected.add(A3, \"1 1 1 0\");     // Advisor\n  expected.add(A & A3, available);\n  // Mutual exclusion for faculty\n  expected.addAllDiff(A1 & A2 & A3);\n\n  // Jake\n  expected.add(J1, faculty_in_H);  // Area 1\n  expected.add(J1, \"1 0 1 1\");     // Advisor\n  expected.add(J & J1, available);\n  expected.add(J2, faculty_in_C);  // Area 2\n  expected.add(J2, \"1 0 1 1\");     // Advisor\n  expected.add(J & J2, available);\n  expected.add(J3, faculty_in_A);  // Area 3\n  expected.add(J3, \"1 0 1 1\");     // Advisor\n  expected.add(J & J3, available);\n  // Mutual exclusion for faculty\n  expected.addAllDiff(J1 & J2 & J3);\n\n  // Mutual exclusion for students\n  expected.addAllDiff(A, J);\n\n  return std::move(expected);\n}\n\n/* ************************************************************************* */\nTEST(schedulingExample, test) {\n  Scheduler s(2);\n\n  // add faculty\n  s.addFaculty(\"Frank\");\n  s.addFaculty(\"Harvey\");\n  s.addFaculty(\"Magnus\");\n  s.addFaculty(\"Andrea\");\n\n  // add time slots\n  s.addSlot(\"Mon\");\n  s.addSlot(\"Wed\");\n  s.addSlot(\"Fri\");\n\n  // add areas\n  s.addArea(\"Frank\", \"AI\");\n  s.addArea(\"Frank\", \"PC\");\n  s.addArea(\"Harvey\", \"ME\");\n  s.addArea(\"Magnus\", \"CT\");\n  s.addArea(\"Magnus\", \"PC\");\n  s.addArea(\"Andrea\", \"AI\");\n  s.addArea(\"Andrea\", \"HR\");\n\n  // add availability, nrTimeSlots * nrFaculty\n  string available = \"1 1 1 0  1 1 1 1  0 1 1 1\";\n  s.setAvailability(available);\n\n  // add students\n  s.addStudent(\"Akansel\", \"AI\", \"ME\", \"PC\", \"Andrea\");\n  s.addStudent(\"Jake\", \"HR\", \"CT\", \"AI\", \"Harvey\");\n\n  // BUILD THE GRAPH !\n  s.buildGraph();\n  //  s.print();\n\n  // Check graph\n  DiscreteFactorGraph expected = createExpected();\n  EXPECT(assert_equal(expected, (DiscreteFactorGraph)s));\n\n  // Do brute force product and output that to file\n  DecisionTreeFactor product = s.product();\n  // product.dot(\"scheduling\", false);\n\n  // Do exact inference\n  gttic(small);\n  auto MPE = s.optimalAssignment();\n  gttoc(small);\n\n  // print MPE, commented out as unit tests don't print\n  //  s.printAssignment(MPE);\n\n  // Commented out as does not work yet\n  // s.runArcConsistency(8,10,true);\n\n  // find the assignment of students to slots with most possible committees\n  // Commented out as not implemented yet\n  //  auto bestSchedule = s.bestSchedule();\n  //  GTSAM_PRINT(bestSchedule);\n\n  //  find the corresponding most desirable committee assignment\n  // Commented out as not implemented yet\n  //  auto bestAssignment = s.bestAssignment(bestSchedule);\n  //  GTSAM_PRINT(bestAssignment);\n}\n\n/* ************************************************************************* */\nTEST(schedulingExample, smallFromFile) {\n  string path(TOPSRCDIR \"/gtsam_unstable/discrete/examples/\");\n  Scheduler s(2, path + \"small.csv\");\n\n  // add areas\n  s.addArea(\"Frank\", \"AI\");\n  s.addArea(\"Frank\", \"PC\");\n  s.addArea(\"Harvey\", \"ME\");\n  s.addArea(\"Magnus\", \"CT\");\n  s.addArea(\"Magnus\", \"PC\");\n  s.addArea(\"Andrea\", \"AI\");\n  s.addArea(\"Andrea\", \"HR\");\n\n  //   add students\n  s.addStudent(\"Akansel\", \"AI\", \"ME\", \"PC\", \"Andrea\");\n  s.addStudent(\"Jake\", \"HR\", \"CT\", \"AI\", \"Harvey\");\n  //  s.print();\n\n  // BUILD THE GRAPH !\n  s.buildGraph();\n\n  // Check graph\n  DiscreteFactorGraph expected = createExpected();\n  EXPECT(assert_equal(expected, (DiscreteFactorGraph)s));\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "7822cbd38ba639b93f9c42e208ac3b91002b18bb", "size": 5094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam_unstable/discrete/tests/testScheduler.cpp", "max_stars_repo_name": "cdb0y511/gtsam", "max_stars_repo_head_hexsha": "e5b928c61032cb3aaa9b88a44fbe2ed4ba08b7ca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-01T04:57:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T04:57:43.000Z", "max_issues_repo_path": "gtsam_unstable/discrete/tests/testScheduler.cpp", "max_issues_repo_name": "Mouri-Yasuhiro/gtsam", "max_issues_repo_head_hexsha": "deca3df7671640b4fbcc88fe45a3bea62e3c8b0a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2022-02-08T18:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:14:32.000Z", "max_forks_repo_path": "gtsam_unstable/discrete/tests/testScheduler.cpp", "max_forks_repo_name": "Mouri-Yasuhiro/gtsam", "max_forks_repo_head_hexsha": "deca3df7671640b4fbcc88fe45a3bea62e3c8b0a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-14T10:10:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T10:10:40.000Z", "avg_line_length": 28.6179775281, "max_line_length": 79, "alphanum_fraction": 0.6065959953, "num_tokens": 1491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5109165830083908}}
{"text": "// Ceres Solver - A fast non-linear least squares minimizer\n// Copyright 2015 Google Inc. All rights reserved.\n// http://ceres-solver.org/\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,\n//   this 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 Google Inc. nor the names of its contributors may be\n//   used to endorse or promote products derived from this software without\n//   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\n// BE  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// Author: keir@google.com (Keir Mierle)\n//\n// A  simple implementation  of N-dimensional  dual numbers,  for automatically\n// computing exact derivatives of functions.\n//\n// While    a   complete    treatment   of    the   mechanics    of   automatic\n// differentation    is    beyond   the    scope    of    this   header    (see\n// http://en.wikipedia.org/wiki/Automatic_differentiation  for   details),  the\n// basic idea is to extend normal  arithmetic with an extra element, \"e,\" often\n// denoted with the  greek symbol epsilon, such that  e != 0 but e^2  = 0. Dual\n// numbers are  extensions of  the real numbers  analogous to  complex numbers:\n// whereas complex numbers augment the reals by introducing an imaginary unit i\n// such that  i^2 = -1, dual  numbers introduce an \"infinitesimal\"  unit e such\n// that e^2 = 0. Dual numbers have two components: the \"real\" component and the\n// \"infinitesimal\" component, generally written as  x + y*e. Surprisingly, this\n// leads to a convenient method for computing exact derivatives without needing\n// to manipulate complicated symbolic expressions.\n//\n// For example, consider the function\n//\n//   f(x) = x^2 ,\n//\n// evaluated at 10. Using normal arithmetic, f(10) = 100, and df/dx(10) = 20.\n// Next, augument 10 with an infinitesimal to get:\n//\n//   f(10 + e) = (10 + e)^2\n//             = 100 + 2 * 10 * e + e^2\n//             = 100 + 20 * e       -+-\n//                     --            |\n//                     |             +--- This is zero, since e^2 = 0\n//                     |\n//                     +----------------- This is df/dx!\n//\n// Note that the derivative of f with  respect to x is simply the infinitesimal\n// component of the value  of f(x + e). So, in order to  take the derivative of\n// any function, it  is only necessary to replace the  numeric \"object\" used in\n// the function with  one extended with infinitesimals. The  class Jet, defined\n// in this header, is one such example of this, where substitution is done with\n// templates.\n//\n// To  handle derivatives  of  functions taking  multiple arguments,  different\n// infinitesimals are  used, one for each  variable to take the  derivative of.\n// For example, consider a scalar function of two scalar parameters x and y:\n//\n//   f(x, y) = x^2 + x * y\n//\n// Following the  technique above, to  compute the derivatives df/dx  and df/dy\n// for f(1, 3) involves doing two evaluations  of f, the first time replacing x\n// with x + e, the second time replacing y with y + e.\n//\n// For df/dx:\n//\n//   f(1 + e, y) = (1 + e)^2 + (1 + e) * 3\n//               = 1 + 2 * e + 3 + 3 * e\n//               = 4 + 5 * e\n//\n//               --> df/dx = 5\n//\n// For df/dy:\n//\n//   f(1, 3 + e) = 1^2 + 1 * (3 + e)\n//               = 1 + 3 + e\n//               = 4 + e\n//\n//               --> df/dy = 1\n//\n// To take the  gradient of f with the implementation  of dual numbers (\"jets\")\n// in  this file,  it  is necessary  to  create  a single  jet  type which  has\n// components for the  derivative in x and  y, and passing them  to a templated\n// version of f:\n//\n//   template<typename T>\n//   T f(const T &x, const T &y) {\n//     return x * x + x * y;\n//   }\n//\n//   // The \"2\" means there should be 2 dual number components.\n//   Jet<double, 2> x(1, 0);  // Pick the 0th dual number for x.\n//   Jet<double, 2> y(3, 1);  // Pick the 1st dual number for y.\n//   Jet<double, 2> z = f(x, y);\n//\n//   std::cout << z << std::endl;\n//\n// For  the  more mathematically  inclined,  this  file implements  first-order\n// \"jets\". A 1st order jet is an element of the ring\n//\n//   T[N] = T[t_1, ..., t_N] / (t_1, ..., t_N)^2\n//\n// which essentially means that each jet  consists of a \"scalar\" value 'a' from\n// T and a 1st order perturbation vector 'v' of length N:\n//\n//   x = a + \\sum_i v[i] t_i\n//\n// A shorthand is to write an element as x = a + u, where u is the pertubation.\n// Then, the  main point about  the arithmetic of jets  is that the  product of\n// perturbations is zero:\n//\n//   (a + u) * (b + v) = ab + av + bu + uv\n//                     = ab + (av + bu) + 0\n//\n// which is what operator* implements below. Addition is simpler:\n//\n//   (a + u) + (b + v) = (a + b) + (u + v).\n//\n// The only remaining  question is how to  evaluate the function of  a jet, for\n// which we use the chain rule:\n//\n//   f(a + u) = f(a) + f'(a) u\n//\n// where f'(a) is the (scalar) derivative of f at a.\n\n#ifndef PUBLIC_JET_HPP_\n#define PUBLIC_JET_HPP_\n\n#include <Eigen/Core>\n#include <cmath>\n\ntemplate <typename Tp, int N>\nstruct Jet {\n  // Default-construct \"a\"  because otherwise  this can lead  to false\n  // errors  about uninitialized  uses when  other classes  relying on\n  // default constructed Tp  (where Tp is a Jet<Tp,  N>). This usually\n  // only happens  in opt  mode. Note that  the C++  standard mandates\n  // that e.g. default constructed doubles are initialized to 0.0; see\n  // sections 8.5 of the C++03 standard.\n  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Jet() : a() { v.setZero(); }\n\n  // Constructor from scalar: a + [0, ...].\n  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit\n    Jet(const Tp& value) { a = value; v.setZero(); }\n\n  // Constructor from scalar plus variable: a + [0, ..., 1, ... 0].\n  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\n  Jet(const Tp& value, int k) { a = value; v.setZero(); v[k] = Tp(1.0); }\n\n  // Constructor from scalar and vector part\n  // ---------------------------------------\n  // The use of Eigen::DenseBase allows Eigen expressions to be passed\n  // in  without being  fully evaluated until  they are assigned  to v\n  template<typename Derived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\n  Jet(const Tp& a, const Eigen::DenseBase<Derived> &v) : a(a), v(v) {}\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\n  Jet<Tp, N>& operator+=(const Jet<Tp, N> &y)\n    { *this = *this + y; return *this; }\n\n  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\n  Jet<Tp, N>& operator-=(const Jet<Tp, N> &y)\n    { *this = *this - y; return *this; }\n\n  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\n  Jet<Tp, N>& operator*=(const Jet<Tp, N> &y)\n    { *this = *this * y; return *this; }\n\n  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\n  Jet<Tp, N>& operator/=(const Jet<Tp, N> &y)\n    { *this = *this / y; return *this; }\n\n#ifdef CEREAL_SERIALIZE_FUNCTION_NAME\n\n  friend class cereal::access;\n\n  template<class Archive>\n  void serialize(Archive& archive) {\n    archive(cereal::make_nvp(\"[real]\", a));\n    archive(cereal::make_nvp(\"[dual]\", v));\n  }\n\n#endif  // CEREAL_SERIALIZE_FUNCTION_NAME\n\n  // Jet dimensionality.\n  enum { kDimensions = N };\n\n  // The scalar part.\n  Tp a;\n\n  // The infinitesimal part.\n  Eigen::Matrix<Tp, N, 1, Eigen::AutoAlign> v;\n};\n\n// Unary +\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> const& operator+(const Jet<Tp, N>& f) { return f; }\n\n// Unary -\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> operator-(const Jet<Tp, N>&f) { return Jet<Tp, N>(-f.a, -f.v); }\n\n// Binary +\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> operator+(const Jet<Tp, N>& f, const Jet<Tp, N>& g)\n { return Jet<Tp, N>(f.a + g.a, f.v + g.v); }\n\n// Binary + with a scalar: x + s\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> operator+(const Jet<Tp, N>& f, Tp s)\n  { return Jet<Tp, N>(f.a + s, f.v); }\n\n// Binary + with a scalar: s + x\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> operator+(Tp s, const Jet<Tp, N>& f)\n  { return Jet<Tp, N>(f.a + s, f.v); }\n\n// Binary -\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> operator-(const Jet<Tp, N>& f, const Jet<Tp, N>& g)\n  { return Jet<Tp, N>(f.a - g.a, f.v - g.v); }\n\n// Binary - with a scalar: x - s\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> operator-(const Jet<Tp, N>& f, Tp s)\n  { return Jet<Tp, N>(f.a - s, f.v); }\n\n// Binary - with a scalar: s - x\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> operator-(Tp s, const Jet<Tp, N>& f)\n  { return Jet<Tp, N>(s - f.a, -f.v); }\n\n// Binary *\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> operator*(const Jet<Tp, N>& f, const Jet<Tp, N>& g)\n { return Jet<Tp, N>(f.a * g.a, f.a * g.v + f.v * g.a); }\n\n// Binary * with a scalar: x * s\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> operator*(const Jet<Tp, N>& f, Tp s)\n  { return Jet<Tp, N>(f.a * s, f.v * s); }\n\n// Binary * with a scalar: s * x\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> operator*(Tp s, const Jet<Tp, N>& f)\n  { return Jet<Tp, N>(f.a * s, f.v * s); }\n\n// Binary /\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> operator/(const Jet<Tp, N>& f, const Jet<Tp, N>& g) {\n  //   a + u   (a + u)(b - v)   (a + u)(b - v)\n  //   ----- = -------------- = --------------\n  //   b + v   (b + v)(b - v)        b^2\n  return Jet<Tp, N>(f.a / g.a, (f.v - f.a / g.a * g.v) / g.a);\n}\n\n// Binary / with a scalar: s / x\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> operator/(Tp s, const Jet<Tp, N>& g)\n  { return Jet<Tp, N>(s / g.a, -s * g.v / (g.a * g.a)); }\n\n// Binary / with a scalar: x / s\ntemplate<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> operator/(const Jet<Tp, N>& f, Tp s)\n  { return Jet<Tp, N>(f.a / s, f.v / s); }\n\n// Binary comparison operators for both scalars and jets.\n#define CERES_DEFINE_JET_COMPARISON_OPERATOR(op)                                    \\\n  template<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE                \\\n  bool operator op(const Tp& s, const Jet<Tp, N>& g) { return s op g.a; }           \\\n                                                                                    \\\n  template<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE                \\\n  bool operator op(const Jet<Tp, N>& f, const Tp& s) { return f.a op s; }           \\\n                                                                                    \\\n  template<typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE                \\\n  bool operator op(const Jet<Tp, N>& f, const Jet<Tp, N>& g) { return f.a op g.a; } \\\n\nCERES_DEFINE_JET_COMPARISON_OPERATOR(< )\nCERES_DEFINE_JET_COMPARISON_OPERATOR(<=)\nCERES_DEFINE_JET_COMPARISON_OPERATOR(> )\nCERES_DEFINE_JET_COMPARISON_OPERATOR(>=)\nCERES_DEFINE_JET_COMPARISON_OPERATOR(==)\nCERES_DEFINE_JET_COMPARISON_OPERATOR(!=)\n\n#undef CERES_DEFINE_JET_COMPARISON_OPERATOR\n\n// In general, f(a + h) ~= f(a) + f'(a) h, via the chain rule.\n\nusing std::abs;  // abs(x + h) ~= x + h or -(x + h)\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> abs(const Jet<Tp, N>& f) { return f.a < Tp(0.0) ? -f : f; }\n\nusing std::log;  // log(a + h) ~= log(a) + h / a\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> log(const Jet<Tp, N>& f) { return Jet<Tp, N>(log(f.a), f.v / f.a); }\n\nusing std::exp;  // exp(a + h) ~= exp(a) + exp(a) h\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> exp(const Jet<Tp, N>& f) { return Jet<Tp, N>(exp(f.a), exp(f.a) * f.v); }\n\nusing std::sqrt;  // sqrt(a + h) ~= sqrt(a) + h / (2 sqrt(a))\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> sqrt(const Jet<Tp, N>& f)\n  { return Jet<Tp, N>(sqrt(f.a), f.v / (Tp(2.0) * sqrt(f.a))); }\n\nusing std::cos;  // cos(a + h) ~= cos(a) - sin(a) h\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> cos(const Jet<Tp, N>& f)\n  { return Jet<Tp, N>(cos(f.a), - sin(f.a) * f.v); }\n\nusing std::acos;  // acos(a + h) ~= acos(a) - 1 / sqrt(1 - a^2) h\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> acos(const Jet<Tp, N>& f)\n  { return Jet<Tp, N>(acos(f.a), f.v / sqrt(Tp(1.0) - f.a * f.a)); }\n\nusing std::sin;  // sin(a + h) ~= sin(a) + cos(a) h\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> sin(const Jet<Tp, N>& f) { return Jet<Tp, N>(sin(f.a), cos(f.a) * f.v); }\n\nusing std::asin;  // asin(a + h) ~= asin(a) + 1 / sqrt(1 - a^2) h\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> asin(const Jet<Tp, N>& f)\n  { return Jet<Tp, N>(asin(f.a), f.v / sqrt(Tp(1.0) - f.a * f.a)); }\n\nusing std::tan;  // tan(a + h) ~= tan(a) + (1 + tan(a)^2) h\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> tan(const Jet<Tp, N>& f)\n  { return Jet<Tp, N>(tan(f.a), Tp(1.0) + tan(f.a) * tan(f.a) * f.v); }\n\nusing std::atan;  // atan(a + h) ~= atan(a) + 1 / (1 + a^2) h\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> atan(const Jet<Tp, N>& f)\n  { return Jet<Tp, N>(atan(f.a), f.v / (Tp(1.0) + f.a * f.a)); }\n\nusing std::sinh;  // sinh(a + h) ~= sinh(a) + cosh(a) h\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> sinh(const Jet<Tp, N>& f)\n  { return Jet<Tp, N>(sinh(f.a), cosh(f.a) * f.v); }\n\nusing std::cosh;  // cosh(a + h) ~= cosh(a) + sinh(a) h\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> cosh(const Jet<Tp, N>& f)\n  { return Jet<Tp, N>(cosh(f.a), sinh(f.a) * f.v); }\n\nusing std::tanh;  // tanh(a + h) ~= tanh(a) + (1 - tanh(a)^2) h\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> tanh(const Jet<Tp, N>& f)\n  { return Jet<Tp, N>(tan(f.a), (Tp(1.0) - tan(f.a) * tan(f.a)) * f.v); }\n\nusing std::atan2;\n\n// atan2(b + db, a + da) ~= atan2(b, a) + (- b da + a db) / (a^2 + b^2)\n//\n// In words: the rate of change of theta is 1/r times the rate of\n// change of (x, y) in the positive angular direction.\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> atan2(const Jet<Tp, N>& g, const Jet<Tp, N>& f) {\n  // Note order of arguments:\n  //\n  //   f = a + da\n  //   g = b + db\n\n  Tp const tmp = Tp(1.0) / (f.a * f.a + g.a * g.a);\n  return Jet<Tp, N>(atan2(g.a, f.a), tmp * (- g.a * f.v + f.a * g.v));\n}\n\nusing std::pow;\n\n// pow -- base is a differentiable function, exponent is a constant.\n// (a+da)^p ~= a^p + p*a^(p-1) da\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> pow(const Jet<Tp, N>& f, double g) {\n  Tp const tmp = g * pow(f.a, g - Tp(1.0));\n  return Jet<Tp, N>(pow(f.a, g), tmp * f.v);\n}\n\n// pow -- base is a constant, exponent is a differentiable function.\n// We have various special cases, see the comment for pow(Jet, Jet) for\n// analysis:\n//\n// 1. For f > 0 we have: (f)^(g + dg) ~= f^g + f^g log(f) dg\n//\n// 2. For f == 0 and g > 0 we have: (f)^(g + dg) ~= f^g\n//\n// 3. For f < 0 and integer g we have: (f)^(g + dg) ~= f^g but if dg\n// != 0, the derivatives are not defined and we return NaN.\n\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> pow(double f, const Jet<Tp, N>& g) {\n  if (f == 0 && g.a > 0) {\n    // Handle case 2.\n    return Jet<Tp, N>(Tp(0.0));\n  }\n  if (f < 0 && g.a == floor(g.a)) {\n    // Handle case 3.\n    Jet<Tp, N> ret(pow(f, g.a));\n    for (int i = 0; i < N; i++) {\n      if (g.v[i] != Tp(0.0)) {\n        // Return a NaN when g.v != 0.\n        ret.v[i] = std::numeric_limits<Tp>::quiet_NaN();\n      }\n    }\n    return ret;\n  }\n  // Handle case 1.\n  Tp const tmp = pow(f, g.a);\n  return Jet<Tp, N>(tmp, log(f) * tmp * g.v);\n}\n\n// pow -- both base and exponent are differentiable functions. This has a\n// variety of special cases that require careful handling.\n//\n// 1. For f > 0:\n//    (f + df)^(g + dg) ~= f^g + f^(g - 1) * (g * df + f * log(f) * dg)\n//    The numerical evaluation of f * log(f) for f > 0 is well behaved, even for\n//    extremely small values (e.g. 1e-99).\n//\n// 2. For f == 0 and g > 1: (f + df)^(g + dg) ~= 0\n//    This cases is needed because log(0) can not be evaluated in the f > 0\n//    expression. However the function f*log(f) is well behaved around f == 0\n//    and its limit as f-->0 is zero.\n//\n// 3. For f == 0 and g == 1: (f + df)^(g + dg) ~= 0 + df\n//\n// 4. For f == 0 and 0 < g < 1: The value is finite but the derivatives are not.\n//\n// 5. For f == 0 and g < 0: The value and derivatives of f^g are not finite.\n//\n// 6. For f == 0 and g == 0: The C standard incorrectly defines 0^0 to be 1\n//    \"because there are applications that can exploit this definition\". We\n//    (arbitrarily) decree that derivatives here will be nonfinite, since that\n//    is consistent with the behavior for f == 0, g < 0 and 0 < g < 1.\n//    Practically any definition could have been justified because mathematical\n//    consistency has been lost at this point.\n//\n// 7. For f < 0, g integer, dg == 0: (f + df)^(g + dg) ~= f^g + g * f^(g - 1) df\n//    This is equivalent to the case where f is a differentiable function and g\n//    is a constant (to first order).\n//\n// 8. For f < 0, g integer, dg != 0: The value is finite but the derivatives are\n//    not, because any change in the value of g moves us away from the point\n//    with a real-valued answer into the region with complex-valued answers.\n//\n// 9. For f < 0, g noninteger: The value and derivatives of f^g are not finite.\n\ntemplate <typename Tp, int N> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\nJet<Tp, N> pow(const Jet<Tp, N>& f, const Jet<Tp, N>& g) {\n  if (f.a == 0 && g.a >= 1) {\n    // Handle cases 2 and 3.\n    if (g.a > 1) {\n      return Jet<Tp, N>(Tp(0.0));\n    }\n    return f;\n  }\n  if (f.a < 0 && g.a == floor(g.a)) {\n    // Handle cases 7 and 8.\n    Tp const tmp = g.a * pow(f.a, g.a - Tp(1.0));\n    Jet<Tp, N> ret(pow(f.a, g.a), tmp * f.v);\n    for (int i = 0; i < N; i++) {\n      if (g.v[i] != Tp(0.0)) {\n        // Return a NaN when g.v != 0.\n        ret.v[i] = std::numeric_limits<Tp>::quiet_NaN();\n      }\n    }\n    return ret;\n  }\n  // Handle the remaining cases. For cases 4,5,6,9 we allow the log() function\n  // to generate -HUGE_VAL or NaN, since those cases result in a nonfinite\n  // derivative.\n  Tp const tmp1 = pow(f.a, g.a);\n  Tp const tmp2 = g.a * pow(f.a, g.a - Tp(1.0));\n  Tp const tmp3 = tmp1 * log(f.a);\n  return Jet<Tp, N>(tmp1, tmp2 * f.v + tmp3 * g.v);\n}\n\ntemplate <typename Tp, int N>\nstd::ostream &operator<<(std::ostream &s, const Jet<Tp, N>& z)\n  { return s << \"[\" << z.a << \"; \" << z.v.transpose() << \"]\"; }\n\nnamespace Eigen {\n\n// Creating  a  specialization of  NumTraits  enables\n// placing Jet  objects inside Eigen  arrays, getting\n// all the goodness of Eigen combined with autodiff.\ntemplate<typename Tp, int N>\nstruct NumTraits<Jet<Tp, N> > {\n  typedef Jet<Tp, N> Real;\n  typedef Jet<Tp, N> NonInteger;\n  typedef Jet<Tp, N> Nested;\n  typedef Jet<Tp, N> Literal;\n\n  // For Jet types, multiplication is more expensive than addition.\n  enum { IsComplex = 0, IsInteger = 0, IsSigned, ReadCost = 1, AddCost = 1,\n         MulCost = 3, HasFloatingPoint = 1, RequireInitialization = 1 };\n\n  // Assuming that for Jets, division is as expensive as multiplication.\n  template<bool Vectorized> struct Div { enum { Cost = 3 }; };\n\n  static Jet<Tp, N> dummy_precision()\n    { return Jet<Tp, N>(1e-12); }\n\n  static inline Real epsilon()\n    { return Real(std::numeric_limits<Tp>::epsilon()); }\n\n  static inline int digits10() { return 0; }\n};\n\n}  // namespace Eigen\n\n#endif  // PUBLIC_JET_HPP_\n", "meta": {"hexsha": "d863c1ffd69ae43463cb33c95efbcee0a6c12c00", "size": 20938, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/.local/include/jet.hpp", "max_stars_repo_name": "Bellaktris/.files", "max_stars_repo_head_hexsha": "e1ec6964964ee8a901ee3c30d3764d8e342f1f48", "max_stars_repo_licenses": ["MIT"], "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++/.local/include/jet.hpp", "max_issues_repo_name": "Bellaktris/.files", "max_issues_repo_head_hexsha": "e1ec6964964ee8a901ee3c30d3764d8e342f1f48", "max_issues_repo_licenses": ["MIT"], "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++/.local/include/jet.hpp", "max_forks_repo_name": "Bellaktris/.files", "max_forks_repo_head_hexsha": "e1ec6964964ee8a901ee3c30d3764d8e342f1f48", "max_forks_repo_licenses": ["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.5803402647, "max_line_length": 85, "alphanum_fraction": 0.6176330117, "num_tokens": 6850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5109008780909055}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   tstNormalDistribution.cpp\n//! \\author Alex Robinson\n//! \\brief  Normal distribution unit tests.\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <iostream>\n\n// Boost Includes\n#include <boost/units/systems/si.hpp>\n#include <boost/units/systems/cgs.hpp>\n#include <boost/units/io.hpp>\n\n// Trilinos Includes\n#include <Teuchos_UnitTestHarness.hpp>\n#include <Teuchos_RCP.hpp>\n#include <Teuchos_Array.hpp>\n#include <Teuchos_ParameterList.hpp>\n#include <Teuchos_XMLParameterListCoreHelpers.hpp>\n#include <Teuchos_VerboseObject.hpp>\n\n// FRENSIE Includes\n#include \"Utility_UnitTestHarnessExtensions.hpp\"\n#include \"Utility_OneDDistribution.hpp\"\n#include \"Utility_NormalDistribution.hpp\"\n#include \"Utility_PhysicalConstants.hpp\"\n#include \"Utility_RandomNumberGenerator.hpp\"\n#include \"Utility_QuantityTraits.hpp\"\n#include \"Utility_ElectronVoltUnit.hpp\"\n\nusing boost::units::quantity;\nusing namespace Utility::Units;\nnamespace si = boost::units::si;\nnamespace cgs = boost::units::cgs;\n\n//---------------------------------------------------------------------------//\n// Testing Variables\n//---------------------------------------------------------------------------//\n\nTeuchos::RCP<Teuchos::ParameterList> test_dists_list;\n\nTeuchos::RCP<Utility::OneDDistribution> distribution(\n\t\t\t\t new Utility::NormalDistribution( 0.0, 1.0 ) );\n\nTeuchos::RCP<Utility::UnitAwareOneDDistribution<cgs::length,si::amount> > unit_aware_distribution( new Utility::UnitAwareNormalDistribution<cgs::length,si::amount>( 0.5*si::mole, 0.0*si::meter, 0.01*si::meter, -Utility::QuantityTraits<quantity<si::length> >::inf() ) );\n\n//---------------------------------------------------------------------------//\n// Tests.\n//---------------------------------------------------------------------------//\n// Check that the distribution can be evaluated\nTEUCHOS_UNIT_TEST( NormalDistribution, evaluate )\n{\n  TEST_EQUALITY_CONST( distribution->evaluate( 0.0 ), 1.0 );\n  TEST_EQUALITY( distribution->evaluate( 2.0 ), exp( -4.0/2.0 ) );\n  TEST_EQUALITY( distribution->evaluate( -2.0 ), exp( -4.0/2.0 ) );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be evaluated\nTEUCHOS_UNIT_TEST( UnitAwareNormalDistribution, evaluate )\n{\n  TEST_EQUALITY_CONST( unit_aware_distribution->evaluate( 0.0*cgs::centimeter ), \n\t\t       0.5*si::mole );\n  TEST_EQUALITY_CONST( unit_aware_distribution->evaluate( 2.0*cgs::centimeter ),\n\t\t       0.5*exp( -4.0/2.0 )*si::mole );\n  TEST_EQUALITY_CONST( unit_aware_distribution->evaluate( -2.0*cgs::centimeter ),\n\t\t       0.5*exp( -4.0/2.0 )*si::mole );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the PDF can be evaluated\nTEUCHOS_UNIT_TEST( NormalDistribution, evaluatePDF )\n{\n  double center_value = 1.0/sqrt( 2.0*Utility::PhysicalConstants::pi );\n  double off_center_value = center_value*exp( -4.0/2.0 );\n  \n  TEST_EQUALITY_CONST( distribution->evaluatePDF( 0.0 ), center_value);\n  TEST_EQUALITY_CONST( distribution->evaluatePDF( 2.0 ), off_center_value );\n  TEST_EQUALITY_CONST( distribution->evaluatePDF( -2.0 ), off_center_value );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware PDF can be evaluated\nTEUCHOS_UNIT_TEST( UnitAwareNormalDistribution, evaluatePDF )\n{\n  double center_value = 1.0/sqrt( 2.0*Utility::PhysicalConstants::pi );\n\n  TEST_EQUALITY_CONST( unit_aware_distribution->evaluatePDF( 0.0*cgs::centimeter ),\n\t\t       center_value/cgs::centimeter );\n  TEST_EQUALITY_CONST( unit_aware_distribution->evaluatePDF( 2.0*cgs::centimeter ),\n\t\t       center_value*exp( -4.0/2.0 )/cgs::centimeter );\n  TEST_EQUALITY_CONST( unit_aware_distribution->evaluatePDF( -2.0*cgs::centimeter ),\n\t\t       center_value*exp( -4.0/2.0 )/cgs::centimeter );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled\nTEUCHOS_UNIT_TEST( NormalDistribution, sample_static )\n{\n  std::vector<double> fake_stream( 11 );\n  fake_stream[0] = 0.5;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 0.9;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5;\n  fake_stream[5] = 0.2;\n  fake_stream[6] = 0.049787;\n  fake_stream[7] = 0.449329;\n  fake_stream[8] = 0.5;\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.4;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  double sample = Utility::NormalDistribution::sample( 0.0, 1.0 );\n  TEST_FLOATING_EQUALITY( sample, 0.69314718055995, 1e-14 );\n\n  sample = Utility::NormalDistribution::sample( 0.0, 1.0 );\n  TEST_FLOATING_EQUALITY( sample, -0.69314718055995, 1e-14 );\n\n  sample = Utility::NormalDistribution::sample( 0.0, 1.0 );\n  TEST_FLOATING_EQUALITY( sample, -0.69314718055995, 1e-14 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled\nTEUCHOS_UNIT_TEST( UnitAwareNormalDistribution, sample_static )\n{\n  std::vector<double> fake_stream( 11 );\n  fake_stream[0] = 0.5;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 0.9;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5;\n  fake_stream[5] = 0.2;\n  fake_stream[6] = 0.049787;\n  fake_stream[7] = 0.449329;\n  fake_stream[8] = 0.5;\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.4;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  quantity<cgs::length> sample = \n    Utility::UnitAwareNormalDistribution<cgs::length>::sample( \n\t\t\t\t    0.0*cgs::centimeter, 1.0*cgs::centimeter );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  0.69314718055995*cgs::centimeter, \n\t\t\t\t  1e-14 );\n\n  sample = Utility::UnitAwareNormalDistribution<cgs::length>::sample( \n\t\t\t\t    0.0*cgs::centimeter, 1.0*cgs::centimeter );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  -0.69314718055995*cgs::centimeter, \n\t\t\t\t  1e-14 );\n\n  sample = Utility::UnitAwareNormalDistribution<cgs::length>::sample( \n\t\t\t\t    0.0*cgs::centimeter, 1.0*cgs::centimeter );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  -0.69314718055995*cgs::centimeter, \n\t\t\t\t  1e-14 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled\nTEUCHOS_UNIT_TEST( NormalDistribution, sampleAndRecordTrials_static )\n{\n  std::vector<double> fake_stream( 11 );\n  fake_stream[0] = 0.5;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 0.9;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5;\n  fake_stream[5] = 0.2;\n  fake_stream[6] = 0.049787;\n  fake_stream[7] = 0.449329;\n  fake_stream[8] = 0.5;\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.4;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  unsigned trials = 0;\n\n  double sample = Utility::NormalDistribution::sampleAndRecordTrials( \n\t\t\t\t\t\t\t    trials, 0.0, 1.0 );\n  TEST_FLOATING_EQUALITY( sample, 0.69314718055995, 1e-14 );\n  TEST_EQUALITY_CONST( 1.0/trials, 1.0 );\n\n  sample = Utility::NormalDistribution::sampleAndRecordTrials( \n\t\t\t\t\t\t\t    trials, 0.0, 1.0 );\n  TEST_FLOATING_EQUALITY( sample, -0.69314718055995, 1e-14 );\n  TEST_EQUALITY_CONST( 2.0/trials, 1.0 );\n\n  sample = Utility::NormalDistribution::sampleAndRecordTrials( \n\t\t\t\t\t\t\t    trials, 0.0, 1.0 );\n  TEST_FLOATING_EQUALITY( sample, -0.69314718055995, 1e-14 );\n  TEST_EQUALITY_CONST( 3.0/trials, 0.75 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled\nTEUCHOS_UNIT_TEST( UnitAwareNormalDistribution, sampleAndRecordTrials_static )\n{\n  std::vector<double> fake_stream( 11 );\n  fake_stream[0] = 0.5;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 0.9;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5;\n  fake_stream[5] = 0.2;\n  fake_stream[6] = 0.049787;\n  fake_stream[7] = 0.449329;\n  fake_stream[8] = 0.5;\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.4;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  unsigned trials = 0;\n\n  quantity<cgs::length> sample = \n    Utility::UnitAwareNormalDistribution<cgs::length>::sampleAndRecordTrials( \n\t\t\t    trials, 0.0*cgs::centimeter, 1.0*cgs::centimeter );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  0.69314718055995*cgs::centimeter, \n\t\t\t\t  1e-14 );\n  TEST_EQUALITY_CONST( 1.0/trials, 1.0 );\n\n  sample = Utility::UnitAwareNormalDistribution<cgs::length>::sampleAndRecordTrials( \n\t\t\t    trials, 0.0*cgs::centimeter, 1.0*cgs::centimeter );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  -0.69314718055995*cgs::centimeter, \n\t\t\t\t  1e-14 );\n  TEST_EQUALITY_CONST( 2.0/trials, 1.0 );\n\n  sample = Utility::UnitAwareNormalDistribution<cgs::length>::sampleAndRecordTrials( \n\t\t\t    trials, 0.0*cgs::centimeter, 1.0*cgs::centimeter );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  -0.69314718055995*cgs::centimeter, \n\t\t\t\t  1e-14 );\n  TEST_EQUALITY_CONST( 3.0/trials, 0.75 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled\nTEUCHOS_UNIT_TEST( NormalDistribution, sample )\n{\n  std::vector<double> fake_stream( 11 );\n  fake_stream[0] = 0.5;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 0.9;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5;\n  fake_stream[5] = 0.2;\n  fake_stream[6] = 0.049787;\n  fake_stream[7] = 0.449329;\n  fake_stream[8] = 0.5;\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.4;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  double sample = distribution->sample();\n  TEST_FLOATING_EQUALITY( sample, 0.69314718055995, 1e-14 );\n\n  sample = distribution->sample();\n  TEST_FLOATING_EQUALITY( sample, -0.69314718055995, 1e-14 );\n\n  sample = distribution->sample();\n  TEST_FLOATING_EQUALITY( sample, -0.69314718055995, 1e-14 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled\nTEUCHOS_UNIT_TEST( UnitAwareNormalDistribution, sample )\n{\n  std::vector<double> fake_stream( 11 );\n  fake_stream[0] = 0.5;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 0.9;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5;\n  fake_stream[5] = 0.2;\n  fake_stream[6] = 0.049787;\n  fake_stream[7] = 0.449329;\n  fake_stream[8] = 0.5;\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.4;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  quantity<cgs::length> sample = unit_aware_distribution->sample();\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  0.69314718055995*cgs::centimeter, \n\t\t\t\t  1e-14 );\n\n  sample = unit_aware_distribution->sample();\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  -0.69314718055995*cgs::centimeter, \n\t\t\t\t  1e-14 );\n\n  sample = unit_aware_distribution->sample();\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  -0.69314718055995*cgs::centimeter, \n\t\t\t\t  1e-14 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled\nTEUCHOS_UNIT_TEST( NormalDistribution, sampleAndRecordTrials )\n{\n  std::vector<double> fake_stream( 11 );\n  fake_stream[0] = 0.5;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 0.9;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5;\n  fake_stream[5] = 0.2;\n  fake_stream[6] = 0.049787;\n  fake_stream[7] = 0.449329;\n  fake_stream[8] = 0.5;\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.4;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  unsigned trials = 0;\n\n  double sample = distribution->sampleAndRecordTrials( trials );\n  TEST_FLOATING_EQUALITY( sample, 0.69314718055995, 1e-14 );\n  TEST_EQUALITY_CONST( 1.0/trials, 1.0 );\n\n  sample = distribution->sampleAndRecordTrials( trials );\n  TEST_FLOATING_EQUALITY( sample, -0.69314718055995, 1e-14 );\n  TEST_EQUALITY_CONST( 2.0/trials, 1.0 );\n\n  sample = distribution->sampleAndRecordTrials( trials );\n  TEST_FLOATING_EQUALITY( sample, -0.69314718055995, 1e-14 );\n  TEST_EQUALITY_CONST( 3.0/trials, 0.75 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled\nTEUCHOS_UNIT_TEST( UnitAwareNormalDistribution, sampleAndRecordTrials )\n{\n  std::vector<double> fake_stream( 11 );\n  fake_stream[0] = 0.5;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 0.9;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5;\n  fake_stream[5] = 0.2;\n  fake_stream[6] = 0.049787;\n  fake_stream[7] = 0.449329;\n  fake_stream[8] = 0.5;\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.4;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  unsigned trials = 0;\n\n  quantity<cgs::length> sample = \n    unit_aware_distribution->sampleAndRecordTrials( trials );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  0.69314718055995*cgs::centimeter, \n\t\t\t\t  1e-14 );\n  TEST_EQUALITY_CONST( 1.0/trials, 1.0 );\n\n  sample = unit_aware_distribution->sampleAndRecordTrials( trials );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  -0.69314718055995*cgs::centimeter, \n\t\t\t\t  1e-14 );\n  TEST_EQUALITY_CONST( 2.0/trials, 1.0 );\n\n  sample = unit_aware_distribution->sampleAndRecordTrials( trials );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, \n\t\t\t\t  -0.69314718055995*cgs::centimeter, \n\t\t\t\t  1e-14 );\n  TEST_EQUALITY_CONST( 3.0/trials, 0.75 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the distribution independent variable can be\n// returned\nTEUCHOS_UNIT_TEST( NormalDistribution, getUpperBoundOfIndepVar )\n{\n  TEST_EQUALITY_CONST( distribution->getUpperBoundOfIndepVar(),\n\t\t       std::numeric_limits<double>::infinity() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the unit-aware distribution independent \n// variable can be returned\nTEUCHOS_UNIT_TEST( UnitAwareNormalDistribution, getUpperBoundOfIndepVar )\n{\n  TEST_EQUALITY_CONST( unit_aware_distribution->getUpperBoundOfIndepVar(),\n\t\t       Utility::QuantityTraits<quantity<cgs::length> >::inf());\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the distribution independent variable can be\n// returned\nTEUCHOS_UNIT_TEST( NormalDistribution, getLowerBoundOfIndepVar )\n{\n  TEST_EQUALITY_CONST( distribution->getLowerBoundOfIndepVar(),\n\t\t       -std::numeric_limits<double>::infinity() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the unit-aware distribution independent \n// variable can be returned\nTEUCHOS_UNIT_TEST( UnitAwareNormalDistribution, getLowerBoundOfIndepVar )\n{\n  TEST_EQUALITY_CONST( unit_aware_distribution->getLowerBoundOfIndepVar(),\n\t\t       -Utility::QuantityTraits<quantity<cgs::length> >::inf());\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution type can be returned\nTEUCHOS_UNIT_TEST( NormalDistribution, getDistributionType )\n{\n  TEST_EQUALITY_CONST( distribution->getDistributionType(),\n\t\t       Utility::NORMAL_DISTRIBUTION );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution type can be returned\nTEUCHOS_UNIT_TEST( UnitAwareNormalDistribution, getDistributionType )\n{\n  TEST_EQUALITY_CONST( unit_aware_distribution->getDistributionType(),\n\t\t       Utility::NORMAL_DISTRIBUTION );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the distribution is tabular\nTEUCHOS_UNIT_TEST( NormalDistribution, isTabular )\n{\n  TEST_ASSERT( !distribution->isTabular() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the unit-aware distribution is tabular\nTEUCHOS_UNIT_TEST( UnitAwareNormalDistribution, isTabular )\n{\n  TEST_ASSERT( !unit_aware_distribution->isTabular() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the distribution is continuous\nTEUCHOS_UNIT_TEST( NormalDistribution, isContinuous )\n{\n  TEST_ASSERT( distribution->isContinuous() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the unit-aware distribution is continuous\nTEUCHOS_UNIT_TEST( UnitAwareNormalDistribution, isContinuous )\n{\n  TEST_ASSERT( unit_aware_distribution->isContinuous() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be written to an xml file\nTEUCHOS_UNIT_TEST( NormalDistribution, toParameterList )\n{\n  Teuchos::RCP<Utility::NormalDistribution> true_distribution =\n    Teuchos::rcp_dynamic_cast<Utility::NormalDistribution>( distribution );\n  \n  Teuchos::ParameterList parameter_list;\n  \n  parameter_list.set<Utility::NormalDistribution>( \"test distribution\", \n\t\t\t\t\t\t     *true_distribution );\n\n  Teuchos::writeParameterListToXmlFile( parameter_list,\n\t\t\t\t\t\"normal_dist_test_list.xml\" );\n  \n  Teuchos::RCP<Teuchos::ParameterList> read_parameter_list = \n    Teuchos::getParametersFromXmlFile( \"normal_dist_test_list.xml\" );\n  \n  TEST_EQUALITY( parameter_list, *read_parameter_list );\n\n  Teuchos::RCP<Utility::NormalDistribution> \n    copy_distribution( new Utility::NormalDistribution );\n\n  *copy_distribution = read_parameter_list->get<Utility::NormalDistribution>(\n\t\t\t\t\t\t\t  \"test distribution\");\n\n  TEST_EQUALITY( *copy_distribution, *true_distribution );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be written to an xml file\nTEUCHOS_UNIT_TEST( UnitAwareNormalDistribution, toParameterList )\n{\n  typedef Utility::UnitAwareNormalDistribution<cgs::length,si::amount>\n    UnitAwareNormalDistribution;\n  \n  Teuchos::RCP<UnitAwareNormalDistribution> true_distribution =\n    Teuchos::rcp_dynamic_cast<UnitAwareNormalDistribution>( unit_aware_distribution );\n  \n  Teuchos::ParameterList parameter_list;\n  \n  parameter_list.set<UnitAwareNormalDistribution>( \"test distribution\", \n\t\t\t\t\t\t   *true_distribution );\n\n  Teuchos::writeParameterListToXmlFile( parameter_list,\n\t\t\t\t       \"unit_aware_normal_dist_test_list.xml\" );\n  \n  Teuchos::RCP<Teuchos::ParameterList> read_parameter_list = \n    Teuchos::getParametersFromXmlFile( \"unit_aware_normal_dist_test_list.xml\" );\n  \n  TEST_EQUALITY( parameter_list, *read_parameter_list );\n\n  Teuchos::RCP<UnitAwareNormalDistribution> \n    copy_distribution( new UnitAwareNormalDistribution );\n\n  *copy_distribution = read_parameter_list->get<UnitAwareNormalDistribution>(\n\t\t\t\t\t\t\t  \"test distribution\");\n\n  TEST_EQUALITY( *copy_distribution, *true_distribution );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be read from an xml file\nTEUCHOS_UNIT_TEST( NormalDistribution, fromParameterList )\n{\n  Utility::NormalDistribution read_distribution = \n    test_dists_list->get<Utility::NormalDistribution>( \"Normal Distribution A\" );\n\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(),\n\t\t       -std::numeric_limits<double>::infinity() );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n\t\t       std::numeric_limits<double>::infinity() );\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0 ), 1.0 );\n\n  read_distribution = \n    test_dists_list->get<Utility::NormalDistribution>( \"Normal Distribution B\" );\n  \n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(),\n\t\t       -Utility::PhysicalConstants::pi );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n\t\t       Utility::PhysicalConstants::pi );\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0 ), 1.0 );\n\n  read_distribution = \n    test_dists_list->get<Utility::NormalDistribution>( \"Normal Distribution C\" );\n\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(), 0.0 );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(), 2.0 );\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 1.0 ), 0.5 );\n\n  read_distribution = \n    test_dists_list->get<Utility::NormalDistribution>( \"Normal Distribution D\" );\n\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(),\n\t\t       -std::numeric_limits<double>::infinity() );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n\t\t       std::numeric_limits<double>::infinity() );\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 1.0 ), 1.0 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be read from an xml file\nTEUCHOS_UNIT_TEST( UnitAwareNormalDistribution, fromParameterList )\n{\n  typedef Utility::UnitAwareNormalDistribution<cgs::length,si::amount>\n    UnitAwareNormalDistribution;\n  \n  UnitAwareNormalDistribution read_distribution = \n    test_dists_list->get<UnitAwareNormalDistribution>( \"Unit-Aware Normal Distribution A\" );\n\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(),\n\t\t       -Utility::QuantityTraits<quantity<cgs::length> >::inf());\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n\t\t       Utility::QuantityTraits<quantity<cgs::length> >::inf() );\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0*cgs::centimeter ), \n\t\t       1.0*si::mole );\n\n  read_distribution = \n    test_dists_list->get<UnitAwareNormalDistribution>( \"Unit-Aware Normal Distribution B\" );\n  \n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(),\n  \t\t       -Utility::PhysicalConstants::pi*cgs::centimeter );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n  \t\t       Utility::PhysicalConstants::pi*cgs::centimeter );\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0*cgs::centimeter ), \n\t\t       1.0*si::mole );\n\n  read_distribution = \n    test_dists_list->get<UnitAwareNormalDistribution>( \"Unit-Aware Normal Distribution C\" );\n\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(), \n\t\t       0.0*cgs::centimeter );\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(), \n\t\t       2.0*cgs::centimeter );\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 1.0*cgs::centimeter ), \n\t\t       0.5*si::mole );\n\n  read_distribution = \n    test_dists_list->get<UnitAwareNormalDistribution>( \"Unit-Aware Normal Distribution D\" );\n\n  TEST_EQUALITY_CONST( read_distribution.getLowerBoundOfIndepVar(),\n  \t\t       -Utility::QuantityTraits<quantity<cgs::length> >::inf());\n  TEST_EQUALITY_CONST( read_distribution.getUpperBoundOfIndepVar(),\n  \t\t       Utility::QuantityTraits<quantity<cgs::length> >::inf());\n  TEST_EQUALITY_CONST( read_distribution.evaluate( 1.0*cgs::centimeter ), \n\t\t       1.0*si::mole );\n}\n\n//---------------------------------------------------------------------------//\n// Check that distributions can be scaled\nTEUCHOS_UNIT_TEST_TEMPLATE_4_DECL( UnitAwareNormalDistribution,\n\t\t\t\t   explicit_conversion,\n\t\t\t\t   IndepUnitA,\n\t\t\t\t   DepUnitA,\n\t\t\t\t   IndepUnitB,\n\t\t\t\t   DepUnitB )\n{\n  typedef typename Utility::UnitTraits<IndepUnitA>::template GetQuantityType<double>::type IndepQuantityA;\n  typedef typename Utility::UnitTraits<typename Utility::UnitTraits<IndepUnitA>::InverseUnit>::template GetQuantityType<double>::type InverseIndepQuantityA;\n  \n  typedef typename Utility::UnitTraits<IndepUnitB>::template GetQuantityType<double>::type IndepQuantityB;\n  typedef typename Utility::UnitTraits<typename Utility::UnitTraits<IndepUnitB>::InverseUnit>::template GetQuantityType<double>::type InverseIndepQuantityB;\n  \n  typedef typename Utility::UnitTraits<DepUnitA>::template GetQuantityType<double>::type DepQuantityA;\n  typedef typename Utility::UnitTraits<DepUnitB>::template GetQuantityType<double>::type DepQuantityB;\n  \n  // Copy from unitless distribution to distribution type A (static method)\n  Utility::UnitAwareNormalDistribution<IndepUnitA,DepUnitA>\n    unit_aware_dist_a_copy = Utility::UnitAwareNormalDistribution<IndepUnitA,DepUnitA>::fromUnitlessDistribution( *Teuchos::rcp_dynamic_cast<Utility::NormalDistribution>( distribution ) );\n\n  // Copy from distribution type A to distribution type B (explicit cast)\n  Utility::UnitAwareNormalDistribution<IndepUnitB,DepUnitB>\n    unit_aware_dist_b_copy( unit_aware_dist_a_copy );\n\n  IndepQuantityA indep_quantity_a = \n    Utility::QuantityTraits<IndepQuantityA>::initializeQuantity( 0.0 );\n  InverseIndepQuantityA inv_indep_quantity_a = \n    Utility::QuantityTraits<InverseIndepQuantityA>::initializeQuantity( 1.0/sqrt( 2.0*Utility::PhysicalConstants::pi ) );\n  DepQuantityA dep_quantity_a = \n    Utility::QuantityTraits<DepQuantityA>::initializeQuantity( 1.0 );\n\n  IndepQuantityB indep_quantity_b( indep_quantity_a );\n  InverseIndepQuantityB inv_indep_quantity_b( inv_indep_quantity_a );\n  DepQuantityB dep_quantity_b( dep_quantity_a );\n\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   unit_aware_dist_a_copy.evaluate( indep_quantity_a ),\n\t\t\t   dep_quantity_a,\n\t\t\t   1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\tunit_aware_dist_a_copy.evaluatePDF( indep_quantity_a ),\n\t\t\tinv_indep_quantity_a,\n\t\t\t1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   unit_aware_dist_b_copy.evaluate( indep_quantity_b ),\n\t\t\t   dep_quantity_b,\n\t\t\t   1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\tunit_aware_dist_b_copy.evaluatePDF( indep_quantity_b ),\n\t\t\tinv_indep_quantity_b,\n\t\t\t1e-15 );\n  \n  Utility::setQuantity( indep_quantity_a, 2.0 );\n  Utility::setQuantity( inv_indep_quantity_a, exp( -4.0/2.0 )/sqrt( 2.0*Utility::PhysicalConstants::pi ) );\n  Utility::setQuantity( dep_quantity_a, exp( -4.0/2.0 ) );\n\n  indep_quantity_b = IndepQuantityB( indep_quantity_a );\n  inv_indep_quantity_b = InverseIndepQuantityB( inv_indep_quantity_a );\n  dep_quantity_b = DepQuantityB( dep_quantity_a );\n\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   unit_aware_dist_a_copy.evaluate( indep_quantity_a ),\n\t\t\t   dep_quantity_a,\n\t\t\t   1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\tunit_aware_dist_a_copy.evaluatePDF( indep_quantity_a ),\n\t\t\tinv_indep_quantity_a,\n\t\t\t1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   unit_aware_dist_b_copy.evaluate( indep_quantity_b ),\n\t\t\t   dep_quantity_b,\n\t\t\t   1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\tunit_aware_dist_b_copy.evaluatePDF( indep_quantity_b ),\n\t\t\tinv_indep_quantity_b,\n\t\t\t1e-15 );\n}\n\ntypedef si::energy si_energy;\ntypedef cgs::energy cgs_energy;\ntypedef si::amount si_amount;\ntypedef si::length si_length;\ntypedef cgs::length cgs_length;\ntypedef si::mass si_mass;\ntypedef cgs::mass cgs_mass;\ntypedef si::dimensionless si_dimensionless;\ntypedef cgs::dimensionless cgs_dimensionless;\n\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_length,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_length );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_length,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_length );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_mass,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_mass );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_mass,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_mass );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_dimensionless,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_dimensionless );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_dimensionless,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_dimensionless );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      void,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      void );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      void,\n\t\t\t\t      si_energy,\n\t\t\t\t      void );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareNormalDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      void,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      void,\n\t\t\t\t      KiloElectronVolt );\n\n//---------------------------------------------------------------------------//\n// Custom main function\n//---------------------------------------------------------------------------//\nint main( int argc, char** argv )\n{\n  std::string test_dists_xml_file;\n  \n  Teuchos::CommandLineProcessor& clp = Teuchos::UnitTestRepository::getCLP();\n  \n  clp.setOption( \"test_dists_xml_file\",\n\t\t &test_dists_xml_file,\n\t\t \"Test distributions xml file name\" );\n  \n  const Teuchos::RCP<Teuchos::FancyOStream> out = \n    Teuchos::VerboseObjectBase::getDefaultOStream();\n\n  Teuchos::CommandLineProcessor::EParseCommandLineReturn parse_return = \n    clp.parse(argc,argv);\n\n  if ( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL ) {\n    *out << \"\\nEnd Result: TEST FAILED\" << std::endl;\n    return parse_return;\n  }\n\n  TEUCHOS_ADD_TYPE_CONVERTER( Utility::NormalDistribution );\n  typedef Utility::UnitAwareNormalDistribution<cgs::length,si::amount> UnitAwareNormalDistribution;\n  TEUCHOS_ADD_TYPE_CONVERTER( UnitAwareNormalDistribution );\n  test_dists_list = Teuchos::getParametersFromXmlFile( test_dists_xml_file );\n  \n  // Initialize the random number generator\n  Utility::RandomNumberGenerator::createStreams();\n  \n  // Run the unit tests\n  Teuchos::GlobalMPISession mpiSession( &argc, &argv );\n\n  const bool success = Teuchos::UnitTestRepository::runUnitTests(*out);\n\n  if (success)\n    *out << \"\\nEnd Result: TEST PASSED\" << std::endl;\n  else\n    *out << \"\\nEnd Result: TEST FAILED\" << std::endl;\n\n  clp.printFinalTimerSummary(out.ptr());\n\n  return (success ? 0 : 1);\n}\n\n//---------------------------------------------------------------------------//\n// end tstNormalDistribution.cpp\n//---------------------------------------------------------------------------//\n\n", "meta": {"hexsha": "2f46b911f9698e006f080565ab3f334649e81be9", "size": 33035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/distribution/test/tstNormalDistribution.cpp", "max_stars_repo_name": "lkersting/SCR-2123", "max_stars_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "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": "packages/utility/distribution/test/tstNormalDistribution.cpp", "max_issues_repo_name": "lkersting/SCR-2123", "max_issues_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/utility/distribution/test/tstNormalDistribution.cpp", "max_forks_repo_name": "lkersting/SCR-2123", "max_forks_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "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.262349067, "max_line_length": 269, "alphanum_fraction": 0.6643257152, "num_tokens": 8299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.5109008780909055}}
{"text": "/**\n * cartan_iterator.cc\n * Copyright 2016 John Lawson\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 \"cartan_iterator.h\"\n\n#include \"util.h\"\n\n#include <boost/dynamic_bitset.hpp>\n\nnamespace refl {\nnamespace {\narma::Mat<int>\nconvert(cluster::QuiverMatrix const& q) {\n\tarma::Mat<int> res(util::to_arma(q));\n\tfor(uint_fast16_t i = 0; i < res.n_elem; ++i) {\n\t\tres(i) = std::abs(res(i));\n\t}\n\tfor(uint_fast16_t i = 0; i < res.n_cols; ++i) {\n\t\tres(i, i) = 2;\n\t}\n\treturn res;\n}\n/**\n * Make a bitset which has a 1 at each non-zero value in the off diagonal\n * matrix and a 0 at each zero.\n *\n * Then result.count() gives the number of non-zero entries, which is the number\n * of places the iterator needs to consider changing the signs of.\n *\n * @param a Initial quasi-Cartan matrix\n * @param vals The number of off diagonal upper triangle values in a\n */\nboost::dynamic_bitset<>\nzeros(arma::Mat<int> const& a, uint_fast16_t vals) {\n\tboost::dynamic_bitset<> result{ vals, 0 };\n\tuint_fast16_t row = 0;\n\tuint_fast16_t col = 1;\n\tfor(uint_fast16_t i = 0; i < vals; ++i) {\n\t\tresult[i] = a(row, col) != 0;\n\t\tif(++col >= a.n_cols) {\n\t\t\tcol = ++row + 1;\n\t\t}\n\t}\n\treturn result;\n}\n}\nCartanIterator::CartanIterator(cluster::QuiverMatrix const& q) \n\t: _number_vars( (q.num_rows() * (q.num_rows() - 1) ) / 2 ),\n\t\t_initial(convert(q)),\n\t\t_result(_initial.n_rows, _initial.n_cols),\n\t\t_zero_mask(zeros(_initial, _number_vars)),\n\t\t_non_zero_vars { _zero_mask.count() },\n\t\t_current_val {0},\n\t\t_max_val(std::pow(2, _non_zero_vars)) {}\nbool\nCartanIterator::has_next() {\n\treturn _current_val < _max_val;\n}\n/*\n * Convert int _current_val into its binary representation, then insert this\n * into the non-zero values of _zero_mask. This ensures that we are never\n * pointlessly mutliplying 0 by -1 and creating many quasi-Cartans which are\n * actually the same.\n *\n * Use the bitset to multiply the vlues corresponding to 1s by -1 in the cartan\n * matrix.\n */\narma::Mat<int>&\nCartanIterator::next(){\n\tboost::dynamic_bitset<> val_bits{_non_zero_vars, _current_val};\n\tboost::dynamic_bitset<> bits_with_zeros { _zero_mask };\n\tuint_fast16_t val_pos = 0;\n\tfor(uint_fast16_t i = 0; i < bits_with_zeros.size(); ++i) {\n\t\tif(bits_with_zeros[i]) {\n\t\t\tbits_with_zeros[i] = val_bits[val_pos];\n\t\t\t++val_pos;\n\t\t}\n\t}\n\n\t_result = _initial;\n\tuint_fast16_t row = 0;\n\tuint_fast16_t col = 1;\n\tfor(uint_fast16_t i = 0; i < _number_vars; ++i) {\n\t\tif(bits_with_zeros[i]) {\n\t\t\t_result(row, col) = -1 * _result(row, col);\n\t\t\t_result(col, row) = -1 * _result(col, row);\n\t\t}\n\t\tif(++col >= _result.n_cols) {\n\t\t\tcol = ++row + 1;\n\t\t}\n\t}\n\t++_current_val;\n\treturn _result;\n}\n}\n\n", "meta": {"hexsha": "2499d487a546426c56c577313ffa90ff51520444", "size": 3139, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/cartan_iterator.cc", "max_stars_repo_name": "jwlawson/qvrefl", "max_stars_repo_head_hexsha": "e843c48837949c5bb76d66959530e7cd55fec0ec", "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/cartan_iterator.cc", "max_issues_repo_name": "jwlawson/qvrefl", "max_issues_repo_head_hexsha": "e843c48837949c5bb76d66959530e7cd55fec0ec", "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/cartan_iterator.cc", "max_forks_repo_name": "jwlawson/qvrefl", "max_forks_repo_head_hexsha": "e843c48837949c5bb76d66959530e7cd55fec0ec", "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.5363636364, "max_line_length": 80, "alphanum_fraction": 0.6881172348, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5109008729433322}}
{"text": "#include <iostream>\n#include <string>\t// for stoi (argv)\n#include <armadillo>\n#include <algorithm> \t// shuffle\n#include <stdlib.h>     // srand, rand\n#include <time.h>     \t// time\n#include <vector>\n\n#include \"Functions.h\"\n\nusing namespace arma;\nusing namespace std;\n\nint main(int argc, char* argv[]){\n\t// argv[1]  : seed for random generator  (set to -1 for random seed)\n\t// argv[2]  : maximum number of MC trials\n\n\t// disable the dynamic adjustment of the number of threads within a team. \n\tomp_set_dynamic(false);\t\t\n\t// disable nested parallel regions, i.e., whether team members are allowed to create new teams.\n\tomp_set_nested(false);\n\tomp_set_num_threads(1);\n\n\tcout << endl;\n\t// initializing random number generator\n\tsimulation_parameters simulation_params;\n\tcout << \"# of Processors Available: \\t\" << omp_get_num_procs() << endl << endl;\n\n\tconst int num_mc_runs = stoi(argv[2],nullptr,10);// number of MC trials\n\tcout << \"# of MC trials: \\t\" << num_mc_runs << endl << endl;\n\tconst int SEED = stoi(argv[1],nullptr,10);\t\t\n\t\n\t// signal Parameters\n\tunsigned int sig_dim \t= 1e4;\t\t\t// signal dimension\n\tcout << \"Signal Dimension: \\t\" << sig_dim << endl<<endl;\n\tunsigned int sparsity\t= 2*sig_dim/100;\t// sparsity level of signal\n\tcout << \"Sparsity: \\t\\t\" << sparsity << endl<<endl;\n\tunsigned int meas_num\t= 30*sig_dim/100;\t// number of measurements\n\tcout << \"# of Measurements: \\t\" << meas_num << endl<<endl;\n\n\t// algorithm parameters\n\tconst unsigned int max_iter = 1.5e3;\n\tconst double gamma = 1e0;\n\tconst double tol = 1e-7;\n\tconst int unsigned block_size = fmin(meas_num,sparsity);\t\n\tconst vec prob_vec = normalise(ones(meas_num / block_size),1);\t\t// set probabilities of selecting each block\n\n    simulation_params.slow_cores_ratio = 0.2;\n\tsimulation_params.sleep_slow_cores = 15e5;   // microseconds to sleep\n\tcout << \"Percentage of Slow Cores: \\t\" << simulation_params.slow_cores_ratio * 100;\n\tcout << \" (each sleeping for \" << simulation_params.sleep_slow_cores/1000 << \" ms )\" << endl<<endl;\n\n\tvector<string> alg_names;\n    // Algorithms to test, comment out each line to skip running its corresponding algorithm \n\talg_names.push_back(\"Bayesian Sto_IHT\");\n\talg_names.push_back(\"Sto_IHT\");\n\talg_names.push_back(\"Parallel Sto_IHT\");\n\talg_names.push_back(\"Tally Sto_IHT\");\n\talg_names.push_back(\"AMP\");\n\talg_names.push_back(\"Parallel AMP\");\t\n\t\n\trun_experiments(alg_names, sig_dim, sparsity, meas_num, max_iter, gamma, tol ,\n\t\tprob_vec, simulation_params, num_mc_runs, SEED);\n\n\treturn 1;\n}\n\n\n", "meta": {"hexsha": "4fe2f4e8f7eca56e9ed45cab3f30ad779d7430e3", "size": 2494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "LCWN-Lab/Parallel-Sparse-Recovery", "max_stars_repo_head_hexsha": "b5dd6b98977bcb437164f1c0109bc892f1d7141d", "max_stars_repo_licenses": ["MIT"], "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": "LCWN-Lab/Parallel-Sparse-Recovery", "max_issues_repo_head_hexsha": "b5dd6b98977bcb437164f1c0109bc892f1d7141d", "max_issues_repo_licenses": ["MIT"], "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": "LCWN-Lab/Parallel-Sparse-Recovery", "max_forks_repo_head_hexsha": "b5dd6b98977bcb437164f1c0109bc892f1d7141d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-24T04:15:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T17:25:19.000Z", "avg_line_length": 36.1449275362, "max_line_length": 109, "alphanum_fraction": 0.7121090617, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5109008659954956}}
{"text": "#include \"stdafx.h\"\n\n#include \"problem.hpp\"\n\n#include <fstream>\n#include <set>\n\n#include <boost/algorithm/string.hpp>\n\nstruct advent_2016_1 : problem\n{\n\tadvent_2016_1() noexcept : problem(2016, 1) {\n\t}\n\nprotected:\n\tenum struct direction\n\t{\n\t\tnorth, east, south, west\n\t};\n\n\tdirection turn_left(direction d) noexcept {\n\t\tswitch(d) {\n\t\tcase direction::north:\n\t\t\treturn direction::west;\n\t\tcase direction::east:\n\t\t\treturn direction::north;\n\t\tcase direction::south:\n\t\t\treturn direction::east;\n\t\tcase direction::west:\n\t\t\treturn direction::south;\n\t\t}\n\t\t__assume(0);\n\t}\n\n\tdirection turn_right(direction d) noexcept {\n\t\tswitch(d) {\n\t\tcase direction::north:\n\t\t\treturn direction::east;\n\t\tcase direction::east:\n\t\t\treturn direction::south;\n\t\tcase direction::south:\n\t\t\treturn direction::west;\n\t\tcase direction::west:\n\t\t\treturn direction::north;\n\t\t}\n\t\t__assume(0);\n\t}\n\n\tenum struct turn\n\t{\n\t\tleft,\n\t\tright\n\t};\n\n\tdirection make_turn(direction d, turn t) noexcept {\n\t\tswitch(t) {\n\t\tcase turn::left:\n\t\t\treturn turn_left(d);\n\t\t\tbreak;\n\t\tcase turn::right:\n\t\t\treturn turn_right(d);\n\t\t\tbreak;\n\t\t}\n\t\t__assume(0);\n\t}\n\n\tstruct instruction\n\t{\n\t\tturn trn;\n\t\tstd::ptrdiff_t distance;\n\t};\n\n\tstd::vector<instruction> instructions;\n\n\tvoid prepare_input(std::ifstream& fin) override {\n\t\tstd::string line;\n\t\tstd::getline(fin, line);\n\t\tstd::vector<std::string> raw_instructions;\n\t\tboost::split(raw_instructions, line, [](char c) {\n\t\t\treturn c == ' ';\n\t\t});\n\t\tfor(const std::string& s : raw_instructions) {\n\t\t\tinstructions.push_back(instruction{ s[0] == 'L' ? turn::left : turn::right, std::stoll(s.substr(1, s.find(','))) });\n\t\t}\n\t}\n\n\tusing coordinate = std::pair<std::ptrdiff_t, std::ptrdiff_t>;\n\n\tcoordinate forward(coordinate pos, direction dir, std::ptrdiff_t dist) noexcept {\n\t\tswitch(dir) {\n\t\tcase direction::north:\n\t\t\tpos.second += dist;\n\t\t\tbreak;\n\t\tcase direction::east:\n\t\t\tpos.first += dist;\n\t\t\tbreak;\n\t\tcase direction::south:\n\t\t\tpos.second -= dist;\n\t\t\tbreak;\n\t\tcase direction::west:\n\t\t\tpos.first -= dist;\n\t\t\tbreak;\n\t\t}\n\t\treturn pos;\n\t}\n\n\tstd::string part_1() override {\n\t\tcoordinate position = { 0, 0 };\n\t\tdirection dir = direction::north;\n\t\tfor(const instruction& i : instructions) {\n\t\t\tdir = make_turn(dir, i.trn);\n\t\t\tposition = forward(position, dir, i.distance);\n\t\t}\n\t\tconst std::ptrdiff_t manhattan_distance = std::abs(position.first) + std::abs(position.second);\n\t\treturn std::to_string(manhattan_distance);\n\t}\n\n\tstd::string part_2() override {\n\t\tstd::set<coordinate> past_locations;\n\t\tcoordinate position = { 0, 0 };\n\t\tpast_locations.insert(position);\n\t\tdirection dir = direction::north;\n\t\tfor(const instruction& i : instructions) {\n\t\t\tdir = make_turn(dir, i.trn);\n\t\t\tfor(std::ptrdiff_t j = 0; j < i.distance; ++j) {\n\t\t\t\tswitch(dir) {\n\t\t\t\tcase direction::north:\n\t\t\t\t\tposition.second += 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase direction::east:\n\t\t\t\t\tposition.first += 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase direction::south:\n\t\t\t\t\tposition.second -= 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase direction::west:\n\t\t\t\t\tposition.first -= 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif(past_locations.insert(position).second == false) {\n\t\t\t\t\tconst std::ptrdiff_t manhattan_distance = std::abs(position.first) + std::abs(position.second);\n\t\t\t\t\treturn std::to_string(manhattan_distance);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t__assume(0);\n\t}\n};\n\nREGISTER_SOLVER(2016, 1);\n", "meta": {"hexsha": "073d29f3a23e30f1b3b2cfabd0f5d193b517e3b9", "size": 3254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc/src/2016/day-1.cpp", "max_stars_repo_name": "DrPizza/advent-of-code-2017", "max_stars_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-09T06:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-18T12:15:08.000Z", "max_issues_repo_path": "aoc/src/2016/day-1.cpp", "max_issues_repo_name": "DrPizza/advent-of-code-2017", "max_issues_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-03T17:46:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-03T17:46:56.000Z", "max_forks_repo_path": "aoc/src/2016/day-1.cpp", "max_forks_repo_name": "DrPizza/advent-of-code", "max_forks_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "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": 21.4078947368, "max_line_length": 119, "alphanum_fraction": 0.6591886908, "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5109008626481858}}
{"text": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/time.h>\n#include <stdlib.h>\n#include <math.h>\n#include <inttypes.h>\n#include <string.h>\n\nextern int enzyme_const;\ntemplate<typename Return, typename... T>\nReturn __enzyme_autodiff(T...);\n\nfloat tdiff(struct timeval *start, struct timeval *end) {\n  return (end->tv_sec-start->tv_sec) + 1e-6*(end->tv_usec-start->tv_usec);\n}\n\n#include <adept_arrays.h>\nusing adept::adouble;\nusing adept::aMatrix;\nusing adept::aVector;\n\nusing adept::Vector;\n\n#define N 2000\n#define M 2000\n#define ITERS 1000\n#define RATE 0.00000001\n\ndouble matvec_real(double* mat, double* vec) {\n  double *out = (double*)malloc(sizeof(double)*N);\n  //double *out = new double[N];\n  for(int i=0; i<N; i++) {\n    out[i] = 0;\n    for(int j=0; j<M; j++) {\n        out[i] += mat[i*M+j] * vec[j];\n    }\n  }\n  double sum = 0;\n  for(int i=0; i<N; i++) {\n    sum += out[i] * out[i];\n  }\n  free(out);\n  //delete[] out;\n  return sum;\n}\n\n/*\n  Differentiation of matvec_real in reverse (adjoint) mode:\n   gradient     of useful results: alloc(*out) matvec_real *mat\n   with respect to varying inputs: alloc(*out) *mat\n   RW status of diff variables: alloc(*out):in-out matvec_real:in-killed\n                *mat:incr\n   Plus diff mem management of: mat:in\n*/\nvoid matvec_real_b(double *mat, double *matb, double *vec, double matvec_realb) {\n    double *out;\n    double *outb;\n    int ii1;\n    double matvec_real;\n    outb = (double *)malloc(sizeof(double)*N);\n    for (ii1 = 0; ii1 < N; ++ii1)\n        outb[ii1] = 0.0;\n    out = (double *)malloc(sizeof(double)*N);\n    //double *out = new double[N];\n    for (int i = 0; i < N; ++i) {\n        out[i] = 0;\n        for (int j = 0; j < M; ++j)\n            out[i] = out[i] + mat[i*M+j]*vec[j];\n    }\n    double sum = 0;\n    double sumb = 0.0;\n    sumb = matvec_realb;\n    for (int i = N; i > -1; --i)\n        outb[i] = outb[i] + 2*out[i]*sumb;\n    for (int i = N; i > -1; --i) {\n        for (int j = M; j > -1; --j)\n            matb[i*M + j] = matb[i*M + j] + vec[j]*outb[i];\n        outb[i] = 0.0;\n    }\n    free(out);\n    free(outb);\n}\n\n#if 1\n#include <vector>\n\nstatic\nadouble matvec(aMatrix& mat, Vector& vec) {\n  //std::vector<adouble> out(N);\n\n  aVector out = mat**vec;\n\n#if 0\n  for(int i=0; i<N; i++) {\n    out[i] = 0;\n    for(int j=0; j<M; j++) {\n        out[i] +=\n//        out[i] += mat[i*M+j] * vec[j];\n    }\n  }\n#endif\n  adouble sum = 0;\n  for(int i=0; i<N; i++) {\n    sum += out(i) * out(i);\n  }\n  //delete[] out;\n  return sum;\n}\n\n#if 0\nstatic\nvoid sincos_and_gradient(double *Min, double *Mout, double *vecin, double *vecout) {\n    //adouble *mat = new adouble[N*M];\n    //std::vector<adouble> mat(N*M);// = new adouble[N*M];\n    //adept::set_values(&mat[0], N*M, Min);\n    //for(int i=0; i<N*M; i++) mat[i] = Min[i];\n    //adouble *vec = new adouble[M];\n    //std::vector<adouble> vec(M);// = new adouble[M];\n    //adept::set_values(&vec[0], M, vecin);\n    //for(int i=0; i<M; i++) vec[i] = vecin[i];\n\n    //aMatrix M = aMatrix(N,M);\n    //for (int i = 0; i < N; i++) {\n    //  for (int j = 0; j < M; j++) {\n    //    M.\n    //  }\n    //}\n\n    adept::Stack stack;\n    stack.new_recording();\n    adouble loss = matvec(&mat[0], &vec[0]);\n    loss.set_gradient(1.0);\n    stack.compute_adjoint();\n\n    adept::get_gradients(&mat[0], N*M, Mout);\n    adept::get_gradients(&vec[0], M, vecout);\n    //for(int i=0; i<N*M; i++) Mout[i] = mat[i].get_gradient();\n    //for(int i=0; i<M; i++) vecout[i] = vec[i].get_gradient();\n\n    //delete[] mat;\n    //delete[] vec;\n    //xgrad = x.get_gradient();\n    //return y.value();\n}\n#endif\n\nstatic void adept_sincos(double *Min, double *Mout, double *Vin, double *Vout) {\n\n  {\n  struct timeval start, end;\n\n  double res2 = 0;\n  adept::Stack stack;\n\n    aMatrix mat(N,M);\n    for(int i=0; i<N; i++) {\n    for(int j=0; j<M; j++) {\n        mat(i, j) = Min[i*M+j];\n    }\n    }\n    Vector vec(M);\n    for(int i=0; i<M; i++) vec(i) = Vin[i];\n\n\n  gettimeofday(&start, NULL);\n  for (int iter = 0; iter < ITERS; iter++) {\n    stack.new_recording();\n    adouble resa = matvec(mat, vec);\n    resa.set_gradient(1.0);\n    stack.continue_recording();\n  }\n    //stack.reverse();\n    //stack.pause_recording();\n    /*\n    for (int i = 0; i < N; i++) {\n      for (int j = 0; j < M; j++) {\n        mat(i,j) -= mat(i,j).get_gradient()*RATE;\n      }\n    }*/\n  gettimeofday(&end, NULL);\n  //gettimeofday(&end, NULL);\n  printf(\"%0.6f res'=%f %f %f\\n\", tdiff(&start, &end), Mout[1], Mout[2], Mout[3]);\n\n  }\n\n\n\n  {\n  struct timeval start, end;\n  //gettimeofday(&start, NULL);\n\n  double res2 = 0;\n  {\n  adept::Stack stack;\n\n    aMatrix mat(N,M);\n    for(int i=0; i<N; i++) {\n    for(int j=0; j<M; j++) {\n        mat(i, j) = Min[i*M+j];\n    }\n    }\n    Vector vec(M);\n    for(int i=0; i<M; i++) vec(i) = Vin[i];\n\n\n  gettimeofday(&start, NULL);\n  for (int iter = 0; iter < ITERS; iter++) {\n    stack.new_recording();\n    adouble resa = matvec(mat, vec);\n    resa.set_gradient(1.0);\n    stack.reverse();\n    stack.pause_recording();\n    for (int i = 0; i < N; i++) {\n      for (int j = 0; j < M; j++) {\n        mat(i,j) -= mat(i,j).get_gradient()*RATE;\n      }\n    }\n    stack.continue_recording();\n  }\n  gettimeofday(&end, NULL);\n#if 0\n    stack.new_recording();\n     gettimeofday(&start, NULL);\n  adouble resa = matvec(mat, vec);\n  res2 = resa.value();\n\n    resa.set_gradient(1.0);\n    stack.reverse();\n    gettimeofday(&end, NULL);\n    stack.pause_recording();\n    for (int i = 0; i < N; i++) {\n      for (int j = 0; j < M; j++) {\n        Mout[i*M+j] = mat(i,j).get_gradient();\n      }\n    }\n#endif\n    //for(int i=0; i<M; i++) Vout[i] = vec(i).get_gradient();\n\n    stack.pause_recording();\n    for (int i = 0; i < N; i++) {\n      for (int j = 0; j < M; j++) {\n        Mout[i*M+j] = mat(i,j).get_gradient();\n      }\n    }\n\n  }\n  //gettimeofday(&end, NULL);\n  printf(\"%0.6f res'=%f %f %f\\n\", tdiff(&start, &end), Mout[1], Mout[2], Mout[3]);\n  }\n}\n#endif\n\nstatic void tapenade_sincos(double *Min, double *Mout, double *Vin, double *Vout) {\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res = matvec_real(Min, Vin);\n\n  gettimeofday(&end, NULL);\n  printf(\"tapenade %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n\n  {\n  struct timeval start, end;\n  double tmp = Min[0];\n  gettimeofday(&start, NULL);\n\n  double sum = 0;\n  for(int i=0; i<ITERS; i++) {\n      Min[0] = tmp + i/100000000.;\n        sum += matvec_real(Min, Vin);\n  }\n\n  gettimeofday(&end, NULL);\n  printf(\"tapenade mv %0.6f res=%f\\n\", tdiff(&start, &end), sum);\n  Min[0] = tmp;\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n  double res2;\n\n  for(int i=0; i<ITERS; i++) {\n  for(int i=0; i<N*M; i++) { Mout[i] = 0; }\n  //for(int i=0; i<M; i++) { Vout[i] = 0; }\n    matvec_real_b(Min, Mout, Vin, 1.0);\n  //res2 = __builtin_autodiff(matvec_real, Min, Mout, Vin, Vout);\n  for(int i=0; i<N*M; i++) { Min[i] -= Mout[i] * RATE; }\n  }\n\n  gettimeofday(&end, NULL);\n  printf(\"tapenade %0.6f res'=%f %f %f\\n\", tdiff(&start, &end), Mout[1], Mout[2], Mout[3]);\n  }\n}\nstatic void enzyme_sincos(double *Min, double *Mout, double *Vin, double *Vout) {\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res = matvec_real(Min, Vin);\n\n  gettimeofday(&end, NULL);\n  printf(\"%0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n\n  {\n  struct timeval start, end;\n  double tmp = Min[0];\n  gettimeofday(&start, NULL);\n\n  double sum = 0;\n  for(int i=0; i<ITERS; i++) {\n      Min[0] = tmp + i/100000000.;\n        sum += matvec_real(Min, Vin);\n  }\n\n  gettimeofday(&end, NULL);\n  printf(\"mv %0.6f res=%f\\n\", tdiff(&start, &end), sum);\n  Min[0] = tmp;\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n  double res2;\n\n  for(int i=0; i<ITERS; i++) {\n  for(int i=0; i<N*M; i++) { Mout[i] = 0; }\n  //for(int i=0; i<M; i++) { Vout[i] = 0; }\n  res2 = __enzyme_autodiff<double>(matvec_real, Min, Mout, enzyme_const, Vin);\n  //res2 = __builtin_autodiff(matvec_real, Min, Mout, Vin, Vout);\n  for(int i=0; i<N*M; i++) { Min[i] -= Mout[i] * RATE; }\n  }\n\n  gettimeofday(&end, NULL);\n  printf(\"%0.6f res'=%f %f %f\\n\", tdiff(&start, &end), Mout[1], Mout[2], Mout[3]);\n  }\n}\n\nint main(int argc, char** argv) {\n\n  double *Min = new double[N*M];\n  double *Mout = new double[N*M];\n  double *Vin = new double[M];\n  double *Vout = new double[M];\n\n  for(int i=0; i<N*M; i++) Min[i] = 3*i;\n  for(int i=0; i<M; i++) Vin[i] = 1*i;\n\n  memset(Mout, 0, sizeof(double)*N*M);\n  memset(Vout, 0, sizeof(double)*M);\n  adept_sincos(Min, Mout, Vin, Vout);\n\n  memset(Mout, 0, sizeof(double)*N*M);\n  memset(Vout, 0, sizeof(double)*M);\n  tapenade_sincos(Min, Mout, Vin, Vout);\n\n  memset(Mout, 0, sizeof(double)*N*M);\n  memset(Vout, 0, sizeof(double)*M);\n  enzyme_sincos(Min, Mout, Vin, Vout);\n}\n\n", "meta": {"hexsha": "5446bf2f020752ef9e24dd083599acdbddee7b3e", "size": 8759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enzyme/benchmarks/matdescent/matdescent.cpp", "max_stars_repo_name": "anandijain/Enzyme", "max_stars_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 674.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T17:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T11:18:11.000Z", "max_issues_repo_path": "enzyme/benchmarks/matdescent/matdescent.cpp", "max_issues_repo_name": "anandijain/Enzyme", "max_issues_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2020-10-07T00:47:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T16:46:58.000Z", "max_forks_repo_path": "enzyme/benchmarks/matdescent/matdescent.cpp", "max_forks_repo_name": "anandijain/Enzyme", "max_forks_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T14:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:51:07.000Z", "avg_line_length": 23.8016304348, "max_line_length": 91, "alphanum_fraction": 0.5538303459, "num_tokens": 3067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5109008557003493}}
{"text": "#include <boost/math/distributions/geometric.hpp>\n", "meta": {"hexsha": "8d16f8f5a59ca5b0c5d5d07450c67979264ac519", "size": 50, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_geometric.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_geometric.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_geometric.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.0, "max_line_length": 49, "alphanum_fraction": 0.82, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5108915720816231}}
{"text": "/*\n * nr_rk4_phase_lattice.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#include <boost/array.hpp>\n\n#include \"rk_performance_test_case.hpp\"\n\n#include \"phase_lattice.hpp\"\n\nconst size_t dim = 1024;\n\ntypedef boost::array< double , dim > state_type;\n\n\ntemplate< class System , typename T , size_t dim >\nvoid rk4_step( const System sys , boost::array< T , dim > &x , const double t , const double dt )\n{   // fast rk4 implementation adapted from the book 'Numerical Recipes'\n    size_t i;\n    const double hh = dt*0.5;\n    const double h6 = dt/6.0;\n    const double th = t+hh;\n    boost::array< T , dim > dydx , dym , dyt , yt;\n\n    sys( x , dydx , t );\n\n    for( i=0 ; i<dim ; i++ )\n        yt[i] = x[i] + hh*dydx[i];\n\n    sys( yt , dyt , th );\n    for( i=0 ; i<dim ; i++ )\n        yt[i] = x[i] + hh*dyt[i];\n\n    sys( yt , dym , th );\n    for( i=0 ; i<dim ; i++ ) {\n        yt[i] = x[i] + dt*dym[i];\n        dym[i] += dyt[i];\n    }\n    sys( yt , dyt , t+dt );\n    for( i=0 ; i<dim ; i++ )\n        x[i] += h6*( dydx[i] + dyt[i] + 2.0*dym[i] );\n}\n\n\nclass nr_wrapper\n{\npublic:\n    void reset_init_cond()\n    {\n        for( size_t i = 0 ; i<dim ; ++i )\n            m_x[i] = 2.0*3.1415927*rand() / RAND_MAX;\n        m_t = 0.0;\n    }\n\n    inline void do_step( const double dt )\n    {\n        rk4_step( phase_lattice<dim>() , m_x , m_t , dt );\n    }\n\n    double state( const size_t i ) const\n    { return m_x[i]; }\n\nprivate:\n    state_type m_x;\n    double m_t;\n};\n\n\n\nint main()\n{\n    srand( 12312354 );\n\n    nr_wrapper stepper;\n\n    run( stepper , 10000 , 1E-6 );\n}\n", "meta": {"hexsha": "a7ee1da6e19f10cf639caa59f03ec441d19dac8e", "size": 1758, "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/performance/nr_rk4_phase_lattice.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/performance/nr_rk4_phase_lattice.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/performance/nr_rk4_phase_lattice.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": 20.4418604651, "max_line_length": 97, "alphanum_fraction": 0.5602957907, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5108915673903378}}
{"text": "#ifndef UPDATE_HPP\n# define UPDATE_HPP\n\n#include <iostream>\n\n#include <Eigen/Dense>\n\nusing Eigen::Matrix;\nusing Eigen::DiagonalMatrix;\n\n#include \"filter.hpp\"\n\n\ntemplate <size_t MM>\nclass Update {\npublic:\n  Update(Filter& kf, const Matrix<double,MM,1>& y)\n    : z2(0.0)\n    , pass(true)\n  {}\n\n  virtual void apply(Filter& kf, const Matrix<double,MM,1>& y,\n\t\t     float z2_max = 16.0) = 0;\n\n  float z2;  /* (--) square of z-score, which is Mahalanobis distance\n\t      *      of measurement from expectation */\n  bool pass; /* (--) did residual edit check pass? */\n};\n\n\ntemplate <size_t MM>\nclass ScalarUpdate : public Update<MM> {\npublic:\n  typedef Matrix<double,MM,1> Meas;\n  typedef Matrix<double,1,MM> MeasT;\n  typedef DiagonalMatrix<double,MM> MeasCov;\n  typedef Matrix<double,MM,NN> MeasSens;\n  typedef Matrix<double,NN,MM> MeasSensT;\n  \n  ScalarUpdate(Filter& kf, const Matrix<double,MM,1>& y)\n    : Update<MM>::Update(kf, y)\n  {}\n\n  void apply(Filter& kf, const Matrix<double,MM,1>& y,\n\t\t     float z2_max = 16.0)\n  {\n    MeasSensT PHt;\n    // 3. Perform residual edit check. Perform underweighting if\n    //    needed.\n    for (size_t kk = 0; Update<MM>::pass && kk < MM; ++kk) {\n      StateT Hk = H.row(kk);\n      PHt.col(kk) = kf.P * Hk.transpose();\n      W.diagonal()(kk) = Hk * PHt.col(kk);\n\n      // Should we do anything here about dX from other updates during\n      // this cycle, to account for it in the residual edit check?\n\n      W.diagonal()(kk) += R.diagonal()(kk);\n\n      // FIXME: Needs measurement underweighting\n\n      // Residual edit check\n      if (W.diagonal()[kk] < FILTER_SMALL) {\n        Update<MM>::z2 += (dy[kk] * dy[kk]) / W.diagonal()[kk];\n      } else {\n\tUpdate<MM>::z2 = std::numeric_limits<float>::infinity();\n      }\n\n      if (Update<MM>::z2 > z2_max) Update<MM>::pass = false;\n    }\n\n    if (Update<MM>::pass) {\n      for (size_t kk = 0; kk < MM; ++kk) {\n\tdouble w = W.diagonal()[kk];\n\t\n\t// Compute Kalman gain column kk\n\tState K = PHt.col(kk) / w;\n\t\n\tkf.dX += K * dy[kk];\n\tdx    += K * dy[kk]; // local copy just from this update\n\t\n\tfor (size_t ii = 0; ii < NN; ++ii) {\n\t  for (size_t jj = ii; jj < NN; ++jj) {\n\t    kf.P(ii,jj) = kf.P(ii,jj) - K[ii] * PHt(jj,kk)\n\t                              - K[jj] * PHt(ii,kk)\n\t                              + K[ii] * K[jj] * w;\n\t    if (ii != jj)\n\t      kf.P(jj,ii) = kf.P(ii,jj);\n\t  }\n\t}\n      }\n    }\n  }\n  \n  MeasCov W; /* (--) diagonal innovation covariance */\n  Meas dy;   /* (--) measurement residual */\n  MeasSens H;/* (--) measurement sensitivity matrix */\n  MeasCov R; /* (--) diagonal measurement covariance */\n\n  /* Debugging variables */\n  State dx;   /* (--) state update vector, for debugging */\n\n};\n\n#endif\n", "meta": {"hexsha": "7f1e4e7ead4a19e8fe4007780c8455babffd5853", "size": 2702, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/update.hpp", "max_stars_repo_name": "openlunar/nav", "max_stars_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/update.hpp", "max_issues_repo_name": "openlunar/nav", "max_issues_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/update.hpp", "max_forks_repo_name": "openlunar/nav", "max_forks_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4905660377, "max_line_length": 70, "alphanum_fraction": 0.5784603997, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5108915626990522}}
{"text": "\ufeff//*****************************************************************************\r\n//*****************************************************************************\r\n// Class: CAprocerosLeucopoda\r\n//          \r\n//\r\n// Description: the CAprocerosLeucopoda represents a group of TZZ insect. scale by m_ScaleFactor\r\n//*****************************************************************************\r\n// 17/10/2020   R\u00e9mi Saint-Amant    Creation\r\n//*****************************************************************************\r\n\r\n#include \"ALeucopodaEquations.h\"\r\n#include \"ALeucopoda.h\"\r\n#include <boost/math/distributions/weibull.hpp>\r\n#include <boost/math/distributions/logistic.hpp>\r\n\r\nusing namespace std;\r\nusing namespace WBSF::HOURLY_DATA;\r\nusing namespace WBSF::TZZ;\r\n\r\n\r\nnamespace WBSF\r\n{\r\n\r\n\t//*********************************************************************************\r\n\t//CAprocerosLeucopoda class\r\n\r\n\r\n\t//*****************************************************************************\r\n\t// Object creator\r\n\t//\r\n\t// Input: See CIndividual creator\r\n\t//\r\n\t// Note: m_RDR (relative Development Rate)  member is init with random values.\r\n\t//*****************************************************************************\r\n\tCAprocerosLeucopoda::CAprocerosLeucopoda(CHost* pHost, CTRef creationDate, double age, TSex sex, bool bFertil, size_t generation, double scaleFactor) :\r\n\t\tCIndividual(pHost, creationDate, age, sex, bFertil, generation, scaleFactor)\r\n\t{\r\n\t\t//reset creation date\r\n\t\tint year = creationDate.GetYear();\r\n\t\t//m_creationDate = GetCreationDate(year);\r\n\t\tm_adult_emergence = GetAdultEmergence(year);\r\n\t\tm_bDiapause = age==PUPA;\r\n\r\n\t\tfor (size_t s = 0; s < NB_STAGES; s++)\r\n\t\t\tm_RDR[s] = Equations().GetRelativeDevRate(s);\r\n\r\n\t\t//m_adult_longevity = Equations().GetAdultLongevity(m_sex);\r\n\t\tm_Fi = Equations().GetFecondity();\r\n\t\tm_bDeadByAttrition = false;\r\n\t}\r\n\r\n\tCTRef CAprocerosLeucopoda::GetCreationDate(int year)const\r\n\t{\r\n\t\tCTRef creationDate = CTRef(year, JANUARY, DAY_01);\r\n\t\treturn creationDate;\r\n\r\n\r\n\t\t//double creationCDD = Equations().GetCreationCDD();\r\n\r\n\t\t//const CWeatherStation& weather_station = GetStand()->GetModel()->m_weather;\r\n\t\t/*CTRef begin = CTRef(year, JANUARY, DAY_01);\r\n\r\n\r\n\r\n\r\n\r\n\t\tCTRef end = CTRef(year, JUNE, DAY_30);\r\n\r\n\t\tdouble CDD = 0;\r\n\t\tfor (CTRef TRef = begin; TRef <= end && !creationDate.IsInit(); TRef++)\r\n\t\t{\r\n\t\t\tconst CWeatherDay& wDay = weather_station.GetDay(TRef);\r\n\t\t\tdouble DD = GetStand()->m_DD.GetDD(wDay);\r\n\t\t\tCDD += DD;\r\n\t\t\tif (CDD >= creationCDD)\r\n\t\t\t{\r\n\t\t\t\tcreationDate = wDay.GetTRef();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tASSERT(creationDate.IsInit());\r\n\r\n\t\treturn creationDate;*/\r\n\t}\r\n\r\n\tCTRef CAprocerosLeucopoda::GetAdultEmergence(int year)const\r\n\t{\r\n\t\tconst CWeatherStation& weather_station = GetStand()->GetModel()->m_weather;\r\n\t\tCTPeriod p = weather_station[year].GetEntireTPeriod(CTM::DAILY);\r\n\r\n\t\tCTRef adult_emergence;\r\n\t\tdouble adult_emerging_CDD = Equations().GetAdultEmergingCDD();\r\n\r\n\t\tCTRef begin = p.Begin();\r\n\t\t//CTRef begin = GetStand()->m_diapause_end;\r\n\t\tCTRef end = p.End();\r\n\t\t//if (weather_station[year].HaveNext())\r\n\t\t\t//end = min(p.End(), CTRef(begin.GetYear() + 1, JUNE, DAY_30));\r\n\r\n\t\t//double CDD = 0;\r\n\t\t\r\n\t\tstatic const CDegreeDays::TDailyMethod DD_METHOD = CDegreeDays::ALLEN_WAVE;\r\n\t\tCDegreeDays DDmodel(DD_METHOD, GetStand()->m_equations.m_EAS[\u03a4\u1d34\u00b9], GetStand()->m_equations.m_EAS[\u03a4\u1d34\u00b2]);\r\n\t\tCModelStatVector GDD;\r\n\t\tDDmodel.Execute(weather_station[year], GDD);\r\n\r\n\t\tdouble CDD = 0;\r\n\t\tfor (CTRef TRef = begin; TRef <= end && !adult_emergence.IsInit(); TRef++)\r\n\t\t{\r\n\t\t\t//const CWeatherDay& wday = weather_station.GetDay(TRef);\r\n\t\t\t//double T = wday[H_TNTX][MEAN];\r\n\t\t\t//T = CAprocerosLeucopoda::AdjustTLab(wday.GetWeatherStation()->m_name, NOT_INIT, wday.GetTRef(), T);\r\n\r\n\t\t\t//double DD = max(0.0, T - Equations().m_EAS[\u03a4\u1d34]);\r\n\t\t\tdouble DD = GDD[TRef][CDegreeDays::S_DD];\r\n\t\t\tCDD += DD;\r\n\t\t\tif (CDD >= adult_emerging_CDD)\r\n\t\t\t{\r\n\t\t\t\tadult_emergence = TRef;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn adult_emergence;\r\n\t}\r\n\r\n\tCAprocerosLeucopoda& CAprocerosLeucopoda::operator=(const CAprocerosLeucopoda& in)\r\n\t{\r\n\t\tif (&in != this)\r\n\t\t{\r\n\t\t\tCIndividual::operator=(in);\r\n\r\n\t\t\tm_adult_emergence = in.m_adult_emergence;\r\n\t\t\tm_bDiapause = in.m_bDiapause;\r\n\t\t\tm_bDeadByAttrition = in.m_bDeadByAttrition;\r\n\r\n\t\t\tfor (size_t s = 0; s < NB_STAGES; s++)\r\n\t\t\t\tm_RDR[s] = Equations().GetRelativeDevRate(s);\r\n\t\t\t\r\n\t\t\tm_Fi = Equations().GetFecondity();;\r\n\t\t}\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\t//destructor\r\n\tCAprocerosLeucopoda::~CAprocerosLeucopoda(void)\r\n\t{}\r\n\r\n\r\n\r\n\r\n\tvoid CAprocerosLeucopoda::OnNewDay(const CWeatherDay& weather)\r\n\t{\r\n\t\tCIndividual::OnNewDay(weather);\r\n\r\n\t\t/*if (weather.GetTRef() == m_creationDate)\r\n\t\t{\r\n\t\t\tm_age = EGG;\r\n\t\t}*/\r\n\t}\r\n\r\n\t//*****************************************************************************\r\n\t// Develops all stages for one time step\r\n\t// Input:\tweather: weather of the hour\r\n\t//\t\t\ttimeStep: timeStep [h]\r\n\t//*****************************************************************************\r\n\tvoid CAprocerosLeucopoda::Live(const CHourlyData& weather, size_t timeStep)\r\n\t{\r\n\t\tassert(IsAlive());\r\n\t\tassert(m_status == HEALTHY);\r\n\r\n//\t\tif (m_dropToGroundDate.IsInit())\r\n\t//\t\treturn;\r\n\r\n\r\n\t\tCTZZHost* pHost = GetHost();\r\n\t\tCTZZStand* pStand = GetStand();\r\n\r\n\t\tdouble nb_steps = (24.0 / timeStep);\r\n\t\tsize_t h = weather.GetTRef().GetHour();\r\n\t\tsize_t s = GetStage();\r\n\r\n\t\tdouble T = weather[H_TAIR];\r\n\t\t//T = AdjustTLab(weather.GetWeatherStation()->m_name, s, weather.GetTRef(), T);\r\n\r\n\t\tdouble day_length = weather.GetLocation().GetDayLength(weather.GetTRef()) / 3600.0;//[h]\r\n\r\n\r\n\t\t\t//Time step development rate\r\n\t\tdouble r = Equations().GetRate(s, T) / nb_steps;\r\n\r\n\t\t//double corr_r = (s == EGG || s == LARVAE) ? : 1;\r\n\r\n\t\t//Relative development rate for this individual\r\n\t\tdouble rr = m_RDR[s];\r\n\r\n\t\t//Time step development rate for this individual\r\n\t\tr *= rr;\r\n\t\tASSERT(r >= 0 && r < 1);\r\n\r\n\t\t//Adjust age\r\n\t\tm_age += r;\r\n\r\n\r\n\t\t//if (!m_dropToGroundDate.IsInit() && m_age > LARVAE4 + 0.9)//drop to the soil when 90% competed (guess)\r\n\t\t\t//m_dropToGroundDate = weather.GetTRef().as(CTM::DAILY);\r\n\r\n\t\t//evaluate attrition once a day\r\n\t\tif (GetStand()->m_bApplyAttrition)\r\n\t\t{\r\n\t\t\tif (IsDeadByAttrition(s, T, r))\r\n\t\t\t\tm_bDeadByAttrition = true;\r\n\t\t}\r\n\r\n\t\t\r\n\r\n\t\tif (!m_adult_emergence.IsInit() && m_age >= ADULT)\r\n\t\t\tm_adult_emergence = weather.GetTRef().as(CTM::DAILY);\r\n\r\n\t\t/*else if (s == AESTIVAL_DIAPAUSE_ADULT)\r\n\t\t{\r\n\t\t\tCTRef TRef = weather.GetTRef().as(CTM::DAILY);\r\n\t\t\tif (TRef == m_adult_emergence)\r\n\t\t\t\tm_age = ACTIVE_ADULT;\r\n\t\t}*/\r\n\t\t//else//ACTIVE_ADULT\r\n\t\t//{\r\n\t\t\t//double r = (1.0 / m_adult_longevity) / nb_steps;\r\n\t\t\t//ASSERT(r >= 0 && r < 1);\r\n\r\n\t\t//\tm_age += r;\r\n\t\t//}/\r\n\t}\r\n\r\n\r\n\r\n\r\n\t//*****************************************************************************\r\n\t// Develops all stages, including adults\r\n\t// Input:\tweather: the weather of the day\r\n\t//*****************************************************************************\r\n\tvoid CAprocerosLeucopoda::Live(const CWeatherDay& weather)\r\n\t{\r\n\t\tCIndividual::Live(weather);\r\n\r\n\t\tASSERT(IsCreated(weather.GetTRef()));\r\n\r\n\t\t//if (!IsCreated(weather.GetTRef()))\r\n\t\t\t//return;\r\n\r\n\t\tif (m_bDiapause && !m_dropToGroundDate.IsInit() && weather.GetTRef() >= m_adult_emergence)\r\n\t\t{\r\n\t\t\tm_bDiapause = false;\r\n\t\t\tm_age = ADULT;\r\n\t\t}\r\n\r\n\t\tsize_t nbSteps = GetTimeStep().NbSteps();\r\n\t\tfor (size_t step = 0; step < nbSteps&&IsAlive() && m_age < DEAD_ADULT && !m_bDiapause; step++)\r\n\t\t{\r\n\t\t\tsize_t h = step * GetTimeStep();\r\n\t\t\tLive(weather[h], GetTimeStep());\r\n\r\n\t\t\tif (GetStage() == PUPA && HasChangedStage() && weather.GetTRef().GetJDay() >= 260)\r\n\t\t\t{\r\n\t\t\t\tm_dropToGroundDate = weather.GetTRef();\r\n\t\t\t\tm_bDiapause = true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (HasChangedStage())\r\n\t\t\tm_reachDate[GetStage()] = weather.GetTRef();\r\n\r\n\t}\r\n\r\n\r\n\tvoid CAprocerosLeucopoda::Brood(const CWeatherDay& weather)\r\n\t{\r\n\t\tassert(/*IsAlive() &&*/ m_sex == FEMALE);\r\n\r\n\r\n\t\tif (GetStage() == ADULT)\r\n\t\t{\r\n\t\t\t//no brood process done\r\n\r\n\t\t\tsize_t nb_days = weather.GetTRef() - m_reachDate[ADULT];\r\n\t\t\tdouble brood = Equations().GetBrood(m_Fi, weather[H_TNTX], nb_days, 1);\r\n\t\t\t//brooding\r\n\t\t\tm_broods = brood;\r\n\t\t\tm_totalBroods += brood;\r\n\t\t\t//m_F = 0;\r\n\t\t//}\r\n\r\n\t\t\tif (m_bFertil && m_broods > 0)\r\n\t\t\t{\r\n\t\t\t\tASSERT(m_age >= ADULT);\r\n\t\t\t\tCTZZStand* pStand = GetStand(); ASSERT(pStand);\r\n\r\n\t\t\t\tdouble gSurvival = 1;// GetStand()->m_bApplyAttrition ? pStand->m_generationSurvival : 1;//100% of survival by default\r\n\t\t\t\tdouble scaleFactor = m_broods * m_scaleFactor*gSurvival;\r\n\t\t\t\tCIndividualPtr object = make_shared<CAprocerosLeucopoda>(m_pHost, weather.GetTRef(), EGG, FEMALE, true, m_generation + 1, scaleFactor);\r\n\t\t\t\tm_pHost->push_front(object);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// kills by old age and frost\r\n\t// Output:  Individual's state is updated to follow update\r\n\tvoid CAprocerosLeucopoda::Die(const CWeatherDay& weather)\r\n\t{\r\n\t\t//attrition mortality. Killed at the end of time step \r\n\r\n\t\tif (m_bDeadByAttrition)\r\n\t\t{\r\n\t\t\tm_status = DEAD;\r\n\t\t\tm_death = ATTRITION;\r\n\t\t}\r\n\t\telse if (GetStage() == DEAD_ADULT)\r\n\t\t{\r\n\t\t\t//Old age\r\n\t\t\tm_status = DEAD;\r\n\t\t\tm_death = OLD_AGE;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsize_t s = GetStage();\r\n\r\n\t\t\t//Preliminary assessment of the cold tolerance of Laricobius Osakensis, a winter - active predator of the hemlock woolly adelgid from western canada\r\n\t\t\t//Leland M.Humble\r\n\t\t\tstatic const double COLD_TOLERENCE_T[NB_STAGES] = { -99, -99, -99, -99.0, -99.0 };\r\n\t\t\t//Toland:L. Osakensis was -13.6 oC (\u00b1 0.5) with temperatures that ranged from -6 oC to -21 oC.\r\n\t\t\tif (weather[H_TMIN][MEAN] < COLD_TOLERENCE_T[s])\r\n\t\t\t{\r\n\t\t\t\tm_status = DEAD;\r\n\t\t\t\tm_death = FROZEN;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t//s: stage\r\n\t//T: temperature for this time step\r\n\t//r: devlopement rate for this time step\r\n\tbool CAprocerosLeucopoda::IsDeadByAttrition(size_t s, double T, double r)const\r\n\t{\r\n\t\tbool bDeath = false;\r\n\r\n\t\t//daily survival\r\n\t\tdouble ds = GetStand()->m_equations.GetDailySurvivalRate(s, T);\r\n\r\n\t\t//time step survival\r\n\t\tdouble S = pow(ds, r);\r\n\r\n\t\t//Computes attrition (probability of survival in a given time step, based on development rate)\r\n\t\tif (RandomGenerator().RandUniform() > S)\r\n\t\t\tbDeath = true;\r\n\r\n\t\treturn bDeath;\r\n\t}\r\n\r\n\r\n\r\n\t//*****************************************************************************\r\n\t// GetStat gather information of this object\r\n\t//\r\n\t// Input: stat: the statistic object\r\n\t// Output: The stat is modified\r\n\t//*****************************************************************************\r\n\tvoid CAprocerosLeucopoda::GetStat(CTRef d, CModelStat& stat)\r\n\t{\r\n\t\tif (IsCreated(d))\r\n\t\t{\r\n\t\t\tsize_t s = GetStage();\r\n\t\t\tASSERT(s <= DEAD_ADULT);\r\n\r\n\t\t\tif (IsAlive() || (s == DEAD_ADULT))\r\n\t\t\t\tstat[S_EGG + s] += m_scaleFactor;\r\n\r\n\r\n\t\t\tif (m_status == DEAD && m_death == ATTRITION)\r\n\t\t\t\tstat[S_DEAD_ATTRITION] += m_scaleFactor;\r\n\r\n\t\t\tif (HasChangedStage())\r\n\t\t\t\tstat[S_M_EGG + s] += m_scaleFactor;\r\n\r\n\t\t\t//if (s == ADULT)\r\n\t\t\t//{\r\n\t\t\tstat[S_BROOD] += m_scaleFactor * m_broods;\r\n\t\t\t//}\r\n\r\n\t\t\tif(m_bDiapause)\r\n\t\t\t\tstat[S_DIAPAUSE] += m_scaleFactor;\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tvoid CAprocerosLeucopoda::Pack(const CIndividualPtr& pBug)\r\n\t{\r\n\t\tassert(m_sex == pBug->GetSex());\r\n\r\n\t\tCAprocerosLeucopoda* in = (CAprocerosLeucopoda*)(pBug.get());\r\n\t\tCIndividual::Pack(pBug);\r\n\t}\r\n\r\n\tdouble CAprocerosLeucopoda::GetInstar(bool includeLast)const\r\n\t{\r\n\t\treturn (IsAlive() || m_death == OLD_AGE) ? GetStage() : CBioSIMModelBase::VMISS;\r\n\t}\r\n\r\n\t//*********************************************************************************************************************\r\n\r\n\t//*********************************************************************************\r\n\t//CTZZHost\r\n\r\n\tCTZZHost::CTZZHost(CStand* pStand) :\r\n\t\tCHost(pStand)\r\n\t{\r\n\t}\r\n\r\n\r\n\tvoid CTZZHost::Live(const CWeatherDay& weather)\r\n\t{\r\n\t\tCHost::Live(weather);\r\n\t}\r\n\r\n\tvoid CTZZHost::GetStat(CTRef d, CModelStat& stat, size_t generation)\r\n\t{\r\n\t\tCHost::GetStat(d, stat, generation);\r\n\t}\r\n\r\n\t//*************************************************\r\n\t//CTZZStand\r\n\r\n\tvoid CTZZStand::init(int year, const CWeatherYears& weather)\r\n\t{\r\n//\t\tm_diapause_end = ComputeDiapauseEnd(weather[year]);\r\n\t}\r\n\r\n\tCTRef CTZZStand::ComputeDiapauseEnd(const CWeatherYear& weather)const\r\n\t{\r\n\t\tCTPeriod p = weather.GetEntireTPeriod(CTM::DAILY);\r\n\r\n\r\n\t\tdouble sumDD = 0;\r\n\r\n\t\tfor (size_t ii = (172 - 1); ii <= (m_equations.m_EWD[\u028e0] - 1); ii++)\r\n\t\t{\r\n\t\t\tCTRef TRef = p.Begin() + ii;\r\n\t\t\tconst CWeatherDay& wday = weather.GetDay(TRef);\r\n\t\t\tdouble T = wday[H_TNTX][MEAN];\r\n\t\t\tT = max(m_equations.m_EWD[\u028ea], T);\r\n\r\n\t\t\tdouble DD = min(0.0, T - m_equations.m_EWD[\u028eb]);//DD is negative\r\n\t\t\tsumDD += DD;\r\n\t\t}\r\n\r\n\t\tboost::math::logistic_distribution<double> begin_dist(m_equations.m_EWD[\u028e2], m_equations.m_EWD[\u028e3]);\r\n\t\tint begin = (int)Round((m_equations.m_EWD[\u028e0] - 1) + m_equations.m_EWD[\u028e1] * cdf(begin_dist, sumDD), 0);\r\n\r\n\r\n\t\treturn p.Begin() + begin;\r\n\t}\r\n\r\n\r\n\r\n\tvoid CTZZStand::GetStat(CTRef d, CModelStat& stat, size_t generation)\r\n\t{\r\n\t\tCStand::GetStat(d, stat, generation);\r\n\r\n//\t\tconst CWeatherStation& weather_station = GetModel()->m_weather;\r\n//\t\tconst CWeatherDay& wday = weather_station.GetDay(d);\r\n//\r\n//\t\t//use year of diapause to compute correctly the adult emergence cdd\r\n//\t\tint year = m_diapause_end.GetYear();\r\n//\t\tCTRef begin = CTRef(year, JANUARY, DAY_01);\r\n//\t\tCTRef end = CTRef(year, DECEMBER, DAY_31);\r\n//\r\n//\t\tif (d >= begin && d <= end)\r\n//\t\t{\r\n//\t\t\t//Egg creation DD (allen 1976)\r\n//\t\t\t//m_egg_creation_CDD += m_DD.GetDD(wday);\r\n////\t\t\tstat[S_EGG_CREATION_CDD] = m_egg_creation_CDD;\r\n//\r\n//\t\t\t//diapause end negative DD\r\n//\t\t\tdouble T = wday[H_TNTX][MEAN];\r\n//\t\t\tT = max(m_equations.m_EWD[\u028ea], T);\r\n//\t\t\tdouble NDD = min(0.0, T - m_equations.m_EWD[\u028eb]);//DD is negative\r\n//\r\n//\t\t\tint ii = d - begin;\r\n//\t\t\tif (ii >= (172 - 1) && ii <= int(m_equations.m_EWD[\u028e0] - 1))\r\n//\t\t\t\tm_diapause_end_NCDD += NDD;\r\n//\r\n//\t\t\t//stat[S_DIAPAUSE_END_NCDD] = m_diapause_end_NCDD;\r\n//\t\t}\r\n//\r\n\r\n\t\t//begin = m_diapause_end;\r\n\t\t//end = CTRef(m_diapause_end.GetYear() + 1, MARCH, DAY_01);\r\n\t\t//if (d >= begin && d <= end)\r\n\t\t//{\r\n\t\t//\t//adult emergence (growing DD)\r\n\t\t//\tdouble T = wday[H_TNTX][MEAN];\r\n\t\t//\tdouble GDD = max(0.0, T - m_equations.m_EAS[\u03a4\u1d34]);\r\n\t\t//\tm_adult_emergence_CDD += GDD;\r\n\t\t//\tstat[S_ADULT_EMERGENCE_CDD] = m_adult_emergence_CDD;\r\n\t\t//}\r\n\t}\r\n\r\n\r\n}", "meta": {"hexsha": "dfadd4e12956b989b555838cfef9c0c9ec592d52", "size": 14209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wbsModels/AprocerosLeucopoda/ALeucopoda.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": "wbsModels/AprocerosLeucopoda/ALeucopoda.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": "wbsModels/AprocerosLeucopoda/ALeucopoda.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": 27.8607843137, "max_line_length": 153, "alphanum_fraction": 0.5836441692, "num_tokens": 4288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5108915626990521}}
{"text": "\n#include <cmath>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\n#include \"distributions.hpp\"\n#include \"fastmath.hpp\"\n\n\nstatic float sq(float x)\n{\n    return x * x;\n}\n\n\n#if 0\nstatic double cb(double x)\n{\n    return x * x * x;\n}\n#endif\n\n\nvoid GammaLogPdf::set_alpha(float alpha)\n{\n    _alpha = alpha;\n    lgamma_alpha = lgammaf(alpha);\n}\n\n\nvoid GammaLogPdf::set_beta(float beta)\n{\n    _beta = beta;\n    log_beta = fastlog(beta);\n}\n\n\nfloat GammaLogPdf::f() const\n{\n    return _alpha * log_beta - lgamma_alpha - _beta * _x + (_alpha - 1.0f) * log_x;\n}\n\n\nfloat GammaLogPdf::x(float x)\n{\n    _x = x;\n    log_x = fastlog(x);\n    return f();\n}\n\n\nvoid GammaLogPdfDx::set_alpha(float alpha)\n{\n    _alpha = alpha;\n}\n\n\nvoid GammaLogPdfDx::set_beta(float beta)\n{\n    _beta = beta;\n}\n\n\nfloat GammaLogPdfDx::f() const\n{\n    return (_alpha - 1.0f) / _x - _beta;\n}\n\n\nfloat GammaLogPdfDx::x(float x)\n{\n    _x = x;\n    return f();\n}\n\n\nvoid GammaLogPdfDBeta::set_alpha(float alpha)\n{\n    _alpha = alpha;\n}\n\n\nvoid GammaLogPdfDBeta::set_beta(float beta)\n{\n    _beta = beta;\n}\n\n\nfloat GammaLogPdfDBeta::f() const\n{\n    return _alpha / _beta - _x;\n}\n\n\nfloat GammaLogPdfDBeta::x(float x)\n{\n    _x = x;\n    return f();\n}\n\n\nfloat AltGammaLogPdf::f() const\n{\n    return -(lgamma_shape + _shape * log_scale) + (_shape - 1.0f) * logx - _x / scale;\n}\n\n\nfloat AltGammaLogPdf::x(float x)\n{\n    _x = x;\n    logx = fastlog(x);\n    return f();\n}\n\n\nfloat AltGammaLogPdf::mean(float mean)\n{\n    _mean = mean;\n    scale = _mean / _shape;\n    log_scale = fastlog(scale);\n    return f();\n}\n\n\nvoid AltGammaLogPdf::set_mean(float mean)\n{\n    _mean = mean;\n    scale = _mean / _shape;\n    log_scale = fastlog(scale);\n}\n\n\nfloat AltGammaLogPdf::mean_x(float mean, float x)\n{\n    _mean = mean;\n    _x = x;\n    logx = fastlog(x);\n    scale = _mean / _shape;\n    log_scale = fastlog(scale);\n    return f();\n}\n\n\nfloat AltGammaLogPdf::shape(float shape)\n{\n    _shape = shape;\n    scale = _mean / _shape;\n    lgamma_shape = lgammaf(shape);\n    log_scale = fastlog(scale);\n    return f();\n}\n\n\nvoid AltGammaLogPdf::set_shape(float shape)\n{\n    _shape = shape;\n    scale = _mean / _shape;\n    lgamma_shape = lgammaf(shape);\n    log_scale = fastlog(scale);\n}\n\n\nfloat AltGammaLogPdfDx::f() const\n{\n    return (_shape - 1.0f) / _x - 1.0f / scale;\n}\n\n\nfloat AltGammaLogPdfDx::x(float x)\n{\n    _x = x;\n    return f();\n}\n\n\nfloat AltGammaLogPdfDx::mean(float mean)\n{\n    _mean = mean;\n    scale = _mean / _shape;\n    return f();\n}\n\n\nvoid AltGammaLogPdfDx::set_mean(float mean)\n{\n    _mean = mean;\n    scale = _mean / _shape;\n}\n\n\nfloat AltGammaLogPdfDx::shape(float shape)\n{\n    _shape = shape;\n    scale = _mean / _shape;\n    return f();\n}\n\n\nvoid AltGammaLogPdfDx::set_shape(float shape)\n{\n    _shape = shape;\n    scale = _mean / _shape;\n}\n\n\nfloat AltGammaLogPdfDMean::f() const\n{\n    return _x * _shape / sq(_mean) - _shape / _mean;\n}\n\n\nfloat AltGammaLogPdfDMean::x(float x)\n{\n    _x = x;\n    return f();\n}\n\n\nfloat AltGammaLogPdfDMean::mean(float mean)\n{\n    _mean = mean;\n    scale = _mean / _shape;\n    return f();\n}\n\n\nfloat AltGammaLogPdfDMean::shape(float shape)\n{\n    _shape = shape;\n    scale = _mean / _shape;\n    return f();\n}\n\n\nfloat AltGammaLogPdfDShape::f() const\n{\n    return logx - _x / _mean - digamma_shape + log_scale * (_mean/sq(_shape));\n}\n\n\nfloat AltGammaLogPdfDShape::x(float x)\n{\n    _x = x;\n    logx = fastlog(x);\n    return f();\n}\n\n\nfloat AltGammaLogPdfDShape::mean(float mean)\n{\n    _mean = mean;\n    scale = _mean / _shape;\n    log_scale = fastlog(scale);\n    return f();\n}\n\n\nfloat AltGammaLogPdfDShape::mean_x(float mean, float x)\n{\n    _x = x;\n    logx = fastlog(x);\n    _mean = mean;\n    scale = _mean / _shape;\n    log_scale = fastlog(scale);\n    return f();\n}\n\n\nfloat AltGammaLogPdfDShape::shape(float shape)\n{\n    _shape = shape;\n    scale = _mean / _shape;\n    log_scale = fastlog(scale);\n    digamma_shape = boost::math::digamma(shape);\n    return f();\n}\n\n\nvoid AltGammaLogPdfDShape::set_shape(float shape)\n{\n    _shape = shape;\n    scale = _mean / _shape;\n    log_scale = fastlog(scale);\n    digamma_shape = boost::math::digamma(shape);\n}\n\n\nfloat PoissonLogPdf::f() const\n{\n    return _k * log_lambda - log_factorial_k - _lambda;\n}\n\n\nfloat PoissonLogPdf::k(unsigned int k)\n{\n    _k = k;\n    log_factorial_k = lgammaf(k + 1);\n    return f();\n}\n\n\nvoid PoissonLogPdf::set_k(unsigned int k)\n{\n    _k = k;\n    log_factorial_k = lgammaf(k + 1);\n}\n\n\nfloat PoissonLogPdf::lambda(float lambda)\n{\n    _lambda = lambda;\n    log_lambda = fastlog(lambda);\n    return f();\n}\n\n\nfloat PoissonLogPdfDLambda::k(unsigned int k)\n{\n    _k = k;\n    return _k / _lambda - 1.0f;\n}\n\n\nvoid PoissonLogPdfDLambda::set_k(unsigned int k)\n{\n    _k = k;\n}\n\n\nfloat PoissonLogPdfDLambda::lambda(float lambda)\n{\n    _lambda = lambda;\n    return _k / _lambda - 1.0f;\n}\n\n\nvoid StudentsTLogPdf::set_nu(float nu)\n{\n    _nu = nu;\n    nu_term = lgammaf((nu + 1.0f) / 2.0f) - lgammaf(nu / 2.0f);\n    nu_sigma_term = - fastlog(sqrtf(nu * M_PI) * _sigma);\n}\n\n\nvoid StudentsTLogPdf::set_mu(float mu)\n{\n    _mu = mu;\n}\n\n\nvoid StudentsTLogPdf::set_sigma(float sigma)\n{\n    _sigma = sigma;\n    nu_sigma_term = -fastlog(sqrtf(_nu * M_PI) * _sigma);\n}\n\n\nfloat StudentsTLogPdf::f() const\n{\n    return nu_term + nu_sigma_term -\n        ((_nu + 1.0f) / 2.0f) * log1pf(sq((_x - _mu) / _sigma) / _nu);\n}\n\n\nfloat StudentsTLogPdf::x(float x)\n{\n    _x = x;\n    return f();\n}\n\n\nvoid StudentsTLogPdfDx::set_nu(float nu)\n{\n    _nu = nu;\n}\n\n\nvoid StudentsTLogPdfDx::set_mu(float mu)\n{\n    _mu = mu;\n}\n\n\nvoid StudentsTLogPdfDx::set_sigma(float sigma)\n{\n    _sigma = sigma;\n}\n\n\nfloat StudentsTLogPdfDx::f() const\n{\n    float part = (2.0f * (_x - _mu) / sq(_sigma) / _nu) /\n        (1.0f + sq((_x - _mu) / _sigma) / _nu);\n    return -((_nu + 1.0f) / 2.0f) * part;\n}\n\n\nfloat StudentsTLogPdfDx::x(float x)\n{\n    _x = x;\n    return f();\n}\n\n\nvoid StudentsTLogPdfDMu::set_nu(float nu)\n{\n    _nu = nu;\n}\n\n\nvoid StudentsTLogPdfDMu::set_mu(float mu)\n{\n    _mu = mu;\n}\n\n\nvoid StudentsTLogPdfDMu::set_sigma(float sigma)\n{\n    _sigma = sigma;\n}\n\n\nfloat StudentsTLogPdfDMu::f() const\n{\n    float part = (2.0f * (_x - _mu) / sq(_sigma) / _nu) /\n        (1.0f + sq((_x - _mu) / _sigma) / _nu);\n    return ((_nu + 1.0f) / 2.0f) * part;\n}\n\n\nfloat StudentsTLogPdfDMu::x(float x)\n{\n    _x = x;\n    return f();\n}\n", "meta": {"hexsha": "ef72e5adb6744b5ff387259b342090c345e776a4", "size": 6419, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/distributions.cpp", "max_stars_repo_name": "dcjones/isolator", "max_stars_repo_head_hexsha": "24bafc0a102dce213bfc2b5b9744136ceadaba03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-07-13T03:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T08:49:07.000Z", "max_issues_repo_path": "src/distributions.cpp", "max_issues_repo_name": "dcjones/isolator", "max_issues_repo_head_hexsha": "24bafc0a102dce213bfc2b5b9744136ceadaba03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-11-29T00:04:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-10T17:46:01.000Z", "max_forks_repo_path": "src/distributions.cpp", "max_forks_repo_name": "dcjones/isolator", "max_forks_repo_head_hexsha": "24bafc0a102dce213bfc2b5b9744136ceadaba03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T15:49:34.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-09T05:14:06.000Z", "avg_line_length": 14.6887871854, "max_line_length": 86, "alphanum_fraction": 0.6225268733, "num_tokens": 2058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5108915626990521}}
{"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#ifndef METRO_LIKELIHOOD_MULTIVARIATE_T_HPP\n#define METRO_LIKELIHOOD_MULTIVARIATE_T_HPP\n\n#include <cmath>\n#include <boost/math/special_functions/gamma.hpp>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Cholesky>\n#include \"metro/IndependentObservationLogLikelihood.hpp\"\n#include \"metro/DataRange.hpp\"\n#include \"metro/DataSubset.hpp\"\n\n// #define DEBUG_MULTIVARIATE_T 1\n\nnamespace metro {\n\tnamespace likelihood {\n\t\ttemplate< typename Scalar, typename Vector, typename Matrix >\n\t\tstruct MultivariateT: public metro::IndependentObservationLogLikelihood< Scalar, Vector, Matrix > {\n\t\tpublic:\n\t\t\ttypedef std::auto_ptr< MultivariateT > UniquePtr ;\n\t\t\ttypedef typename Vector::SegmentReturnType Segment ;\n\t\t\ttypedef typename Vector::ConstSegmentReturnType ConstSegment ;\n\t\t\ttypedef typename Eigen::Ref< Matrix > MatrixRef ;\n\t\t\ttypedef typename Eigen::Block< Matrix > Block ;\n\t\tpublic:\n\t\t\tMultivariateT( double const degrees_of_freedom ):\n\t\t\t\tm_pi( 3.141592653589793238462643383279502884 ),\n\t\t\t\tm_nu( degrees_of_freedom ),\n\t\t\t\tm_data( 0 ),\n\t\t\t\tm_kappa( 0 )\n\t\t\t{\n\t\t\t}\n\t\t\t\n\t\t\tMultivariateT( Matrix const& data, double const degrees_of_freedom ):\n\t\t\t\tm_pi( 3.141592653589793238462643383279502884 ),\n\t\t\t\tm_nu( degrees_of_freedom ),\n\t\t\t\tm_data( 0 ),\n\t\t\t\tm_kappa( 0 )\n\t\t\t{\n\t\t\t\tset_data( data ) ;\n\t\t\t}\n\n\t\t\tMultivariateT( Matrix const& data, Vector const& weights, double const degrees_of_freedom ):\n\t\t\t\tm_pi( 3.141592653589793238462643383279502884 ),\n\t\t\t\tm_nu( degrees_of_freedom ),\n\t\t\t\tm_data( 0 ),\n\t\t\t\tm_kappa( 0 )\n\t\t\t{\n\t\t\t\tset_data( data, weights ) ;\n\t\t\t}\n\n\t\t\tint p() const { return m_p ; }\n\t\t\tdouble nu() const { return m_nu ; }\n\t\t\tdouble degrees_of_freedom() const { return m_nu ; }\n\t\t\tVector parameters() const { return m_parameters ; }\n\t\t\tVector const& mean() const { return m_mean ; }\n\t\t\tMatrix const& sigma() const { return m_sigma ; }\n\t\t\tMatrix const& data() const { return m_data ; }\n\t\t\t\n\t\t\tstd::string get_spec() const { return \"MultivariateT\" ; }\n\n\n\t\t\t// Behaves as if calling set_data() (below) with unit weights.\n\t\t\tvoid set_data(\n\t\t\t\tMatrix const& data\n\t\t\t) {\n\t\t\t\tset_data( data, Vector::Constant( data.rows(), 1 )) ;\n\t\t\t}\n\n\t\t\t// Set data to a give matrix with specified weights.\n\t\t\t// If data.cols() == p() then parameters are left unchanged\n\t\t\t// and the likelihood will be re-evaluated.\n\t\t\t// Otherwise, if data.cols() != p() then parameters will be left undefined.\n\t\t\t// In both cases, you must call evaluate_at() before evaluating the likelihood.\n\t\t\tvoid set_data(\n\t\t\t\tMatrix const& data,\n\t\t\t\tVector const& weights\n\t\t\t) {\n\t\t\t\tm_data = &data ;\n\t\t\t\tassert( weights.size() == m_data->rows() ) ;\n\t\t\t\tm_weights = weights ;\n\t\t\t\tif( m_p != m_data->cols() ) {\n\t\t\t\t\tm_p = m_data->cols() ;\n\t\t\t\t\tm_kappa = compute_constant_terms( m_nu, m_p ) ;\n\t\t\t\t\tm_parameters = Vector::Zero( m_p + ( m_p * ( m_p + 1 ) / 2 ) ) ;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Evaluate at a given set of parameters, specified as a single vector.\n\t\t\t// Parameters are taken in order as the p entries of the mean vector,\n\t\t\t// followed by the p(p+1)/2 entries of the lower triangle of the\n\t\t\t// variance-covariance matrix taken in column-major order.\n\t\t\tvoid evaluate_at( Vector const& parameters ) {\n\t\t\t\tevaluate_at( parameters, DataRange( 0, m_data->rows() )) ;\n\t\t\t}\n\n\t\t\t// Evaluate at a given set of parameters on a specified subset of the data.\n\t\t\t// Parameters are taken in order as the p entries of the mean vector,\n\t\t\t// followed by the p(p+1)/2 entries of the lower triangle of the\n\t\t\t// variance-covariance matrix taken in column-major order.\n\t\t\tvoid evaluate_at( Vector const& parameters, DataSubset const& data_subset ) {\n\t\t\t\tassert( parameters.size() == m_parameters.size() ) ;\n\t\t\t\tassert( m_data ) ;\n\t\t\t\tunpack_parameters( parameters, &m_mean, &m_sigma ) ;\n\t\t\t\tevaluate_at( m_mean, m_sigma, data_subset ) ;\n\t\t\t}\n\n\t\t\t// Evaluate at a given set of parameters, specified as a mean vector\n\t\t\t// and variance-covariance matrix.  Only the lower triangle of the\n\t\t\t// variance-covariance matrix is used by this class.\n\t\t\tvoid evaluate_at( Vector const& mean, Matrix const& sigma ) {\n\t\t\t\tevaluate_at( mean, sigma, DataRange( 0, m_data->rows() )) ;\n\t\t\t}\n\n\t\t\t// Evaluate at a given set of parameters, on a subset of data.\n\t\t\t// Parameters are specified as a mean vector\n\t\t\t// and variance-covariance matrix.  Only the lower triangle of the\n\t\t\t// variance-covariance matrix is used by this class.\n\t\t\tvoid evaluate_at( Vector const& mean, Matrix const& sigma, DataSubset const& data_subset ) {\n\t\t\t\tassert( mean.size() == m_data->cols() ) ;\n\t\t\t\tassert( sigma.rows() == sigma.cols() ) ;\n\t\t\t\tassert( sigma.rows() == m_data->cols() ) ;\n\n\t\t\t\tm_mean = mean ;\n\t\t\t\tm_sigma = sigma ;\n\t\t\t\tm_data_subset = data_subset ;\n\n\t\t\t\t// Pack parameters into the parameter vector\n\t\t\t\tpack_parameters( mean, m_sigma, &m_parameters ) ;\n\n\t\t\t\t// We compute up-front some quantities that are useful\n\t\t\t\t// when computing the log-likelihood.\n\t\t\t\tm_ldlt.compute( m_sigma ) ;\n\t\t\t\tm_log_determinant = m_ldlt.vectorD().array().log().sum() ;\n\t\t\t\tm_mean_centred_data = m_data->rowwise() - m_mean.transpose() ;\n\t\t\t\t// Z is a vector of the terms ( x_i - mu )^t Sigma^-1 ( x_i - mu ).\n\t\t\t\tm_A = m_ldlt.solve( m_mean_centred_data.transpose() ) ;\n\t\t\t\tm_Z = (\n\t\t\t\t\tm_mean_centred_data.array() * m_A.transpose().array()\n\t\t\t\t).rowwise().sum() ;\n\n#if DEBUG_MULTIVARIATE_T\n\t\t\t\t\tstd::cerr << \"metro::likelihood::MultivariateT::evaluate_at():\\n\"\n\t\t\t\t\t\t<< \" m_mean \" << m_mean.transpose() << \"\\n\"\n\t\t\t\t\t\t<< \" m_sigma = \\n\" << m_sigma << \"\\n\" \n\t\t\t\t\t\t<< \" m_log_determinant = \" << m_log_determinant << \"\\n\" ;\n#endif\t\t\t\t\n\t\t\t}\n\n\t\t\t// Get the value of the log-likelihood for the given data,\n\t\t\t// and parameters and data subset passed to evaluate_at().\n\t\t\t// You must call evaluate_at() before using this function.\n\t\t\tdouble get_value_of_function() const {\n\t\t\t\tVector terms = Vector::Constant( m_data->rows(), 0 ) ;\n\t\t\t\tget_terms_of_function( terms ) ;\n\t\t\t\treturn terms.sum() ;\n\t\t\t}\n\n\t\t\t// Get terms of the log-likelihood corresponding to each\n\t\t\t// weighted data point.\n\t\t\tvoid get_terms_of_function( MatrixRef result ) const {\n\t\t\t\tassert( result.rows() == m_data->rows() ) ;\n\t\t\t\tassert( result.cols() == 1 ) ;\n\t\t\t\tbool const mvn = m_nu == std::numeric_limits< double >::infinity() ;\n\t\t\t\tfor( std::size_t i = 0; i < m_data_subset.number_of_subranges(); ++i ) {\n\t\t\t\t\tDataRange const& range = m_data_subset[i] ;\n\t\t\t\t\tConstSegment const segmentZ = m_Z.segment( range.begin(), range.size() ) ;\n\t\t\t\t\tConstSegment const segmentWeights = m_weights.segment( range.begin(), range.size() ) ;\n\t\t\t\t\tEigen::Block< MatrixRef > resultSegment = result.block( range.begin(), 0, range.size(), 1 ) ;\n\n\t\t\t\t\tif( mvn ) {\n\t\t\t\t\t\tresultSegment = segmentWeights.array() * (\n\t\t\t\t\t\t\tVector::Constant( range.size(), m_kappa - 0.5 * m_log_determinant )\n\t\t\t\t\t\t\t- 0.5 * segmentZ\n\t\t\t\t\t\t).array() ;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresultSegment = segmentWeights.array() * (\n\t\t\t\t\t\t\tVector::Constant( range.size(), m_kappa - 0.5 * m_log_determinant ).array()\n\t\t\t\t\t\t\t-( 0.5 * ( m_nu + m_p ) * (( segmentZ + Vector::Constant( range.size(), m_nu ) ).array().log() ) )\n\t\t\t\t\t\t) ;\n\t\t\t\t\t}\n#if DEBUG_MULTIVARIATE_T\n\t\t\t\t\tstd::cerr << \"metro::likelihood::MultivariateT::get_terms_of_function():\\n\"\n\t\t\t\t\t\t<< \" Adding \" << range << \"\\n\"\n\t\t\t\t\t\t<< \" segmentZ = \" << segmentZ.transpose() << \"\\n\"\n\t\t\t\t\t\t<< \" segmentWeights = \" << segmentWeights.transpose() << \"\\n\"\n\t\t\t\t\t\t<< \" m_kappa = \" << m_kappa << \"\\n\"\n\t\t\t\t\t\t<< \" m_log_determinant = \" << m_log_determinant << \"\\n\"\n\t\t\t\t\t\t<< \" term = \" << (( segmentZ + Vector::Constant( range.size(), m_nu ) ).array().log() )\n\t\t\t\t\t\t<< \" result = \" << result << \".\\n\" ;\n#endif\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Compute the first derivative of the log-likelihood\n\t\t\t// You must call evaluate_at() before using this method.\n\t\t\tVector get_value_of_first_derivative() const {\n\t\t\t\tassert(0) ;\n\t\t\t}\n\n\t\t\t// Compute the second derivative of the log-likelihood\n\t\t\t// You must call evaluate_at() before using this method.\n\t\t\tMatrix get_value_of_second_derivative() const {\n\t\t\t\tassert(0) ;\n\t\t\t}\n\n\t\t\t// Fit multivariate T on the full data using an EM algorithm\n\t\t\t// until the stopping condition becomes satisfied.\n\t\t\t// Algorithm details are from Nadarajah & Kotz, \"Estimation methods for the Multivariate t Distribution.\", p.103\n\t\t\t// stopping_condition must be callable as stopping_condition( current loglikelihood ),\n\t\t\t// where a return value of true indicates that iteration should stop.\n\t\t\t// This function iterates until stopping_condition() == true, at which point\n\t\t\t// it returns stopping_condition.converged().\n\t\t\t// The postcondition of this function is as though evaluate_at() has been called\n\t\t\t// for the last parameter value visited by the EM iteration (whether converged or not).\n\t\t\ttemplate< typename StoppingCondition >\n\t\t\tbool estimate_by_em(\n\t\t\t\tStoppingCondition& stopping_condition\n\t\t\t) {\n\t\t\t\tMatrix regularising_sigma = Matrix::Constant( m_p, m_p, 0 ) ;\n\t\t\t\tdouble regularising_weight = 0 ;\n\t\t\t\treturn estimate_by_em(\n\t\t\t\t\tDataRange( 0, m_data->rows() ),\n\t\t\t\t\tstopping_condition,\n\t\t\t\t\tregularising_sigma,\n\t\t\t\t\tregularising_weight\n\t\t\t\t) ;\n\t\t\t}\n\n\t\t\t// Fit multivariate T on a subset of data using an EM algorithm\n\t\t\t// until the stopping condition becomes satisfied.\n\t\t\t// Algorithm details are from Nadarajah & Kotz, \"Estimation methods for the Multivariate t Distribution.\", p.103\n\t\t\t// stopping_condition must be callable as stopping_condition( current loglikelihood ),\n\t\t\t// where a return value of true indicates that iteration should stop.\n\t\t\t// This function iterates until stopping_condition() == true, at which point\n\t\t\t// it returns stopping_condition.converged().\n\t\t\t// The postcondition of this function is as though evaluate_at() has been called\n\t\t\t// for the last parameter value visited by the EM iteration (whether converged or not).\n\t\t\ttemplate< typename StoppingCondition >\n\t\t\tbool estimate_by_em(\n\t\t\t\tDataSubset const& data_subset,\n\t\t\t\tStoppingCondition& stopping_condition\n\t\t\t) {\n\t\t\t\tMatrix regularising_sigma = Matrix::Constant( m_p, m_p, 0 ) ;\n\t\t\t\tdouble regularising_weight = 0 ;\n\t\t\t\treturn estimate_by_em(\n\t\t\t\t\tdata_subset,\n\t\t\t\t\tstopping_condition,\n\t\t\t\t\tregularising_sigma,\n\t\t\t\t\tregularising_weight\n\t\t\t\t) ;\n\t\t\t}\n\n\t\t\t// Fit multivariate T on the full data using an EM algorithm\n\t\t\t// until the stopping condition becomes satisfied.\n\t\t\t// Algorithm details are from Nadarajah & Kotz, \"Estimation methods for the Multivariate t Distribution.\", p.103\n\t\t\t// This function includes a regularising variance-covariance matrix, and weight\n\t\t\t// to prevent the fit from becoming degenerate.\n\t\t\t// stopping_condition must be callable as stopping_condition( current loglikelihood ),\n\t\t\t// where a return value of true indicates that iteration should stop.\n\t\t\t// This function iterates until stopping_condition() == true, at which point\n\t\t\t// it returns stopping_condition.converged().\n\t\t\t// The postcondition of this function is as though evaluate_at() has been called\n\t\t\t// for the last parameter value visited by the EM iteration (whether converged or not).\n\t\t\ttemplate< typename StoppingCondition >\n\t\t\tbool estimate_by_em(\n\t\t\t\tStoppingCondition& stopping_condition,\n\t\t\t\tMatrix const& regularising_sigma,\n\t\t\t\tdouble regularising_weight\n\t\t\t) {\n\t\t\t\treturn estimate_by_em(\n\t\t\t\t\tDataRange( 0, m_data->rows() ),\n\t\t\t\t\tstopping_condition,\n\t\t\t\t\tregularising_sigma,\n\t\t\t\t\tregularising_weight\n\t\t\t\t) ;\n\t\t\t}\n\n\n\t\t\t// Fit multivariate T on a subset of data using an EM algorithm\n\t\t\t// until the stopping condition becomes satisfied.\n\t\t\t// Algorithm details are from Nadarajah & Kotz, \"Estimation methods for the Multivariate t Distribution.\", p.103\n\t\t\t// This function includes a regularising variance-covariance matrix, and weight\n\t\t\t// to prevent the fit from becoming degenerate.\n\t\t\t// stopping_condition must be callable as stopping_condition( current loglikelihood ),\n\t\t\t// where a return value of true indicates that iteration should stop.\n\t\t\t// This function iterates until stopping_condition() == true, at which point\n\t\t\t// it returns stopping_condition.converged().\n\t\t\t// The postcondition of this function is as though evaluate_at() has been called\n\t\t\t// for the last parameter value visited by the EM iteration (whether converged or not).\n\t\t\ttemplate< typename StoppingCondition >\n\t\t\tbool estimate_by_em(\n\t\t\t\tDataSubset const& data_subset,\n\t\t\t\tStoppingCondition& stopping_condition,\n\t\t\t\tMatrix const& regularising_sigma,\n\t\t\t\tdouble regularising_weight\n\t\t\t) {\n\t\t\t\tassert( regularising_sigma.rows() == m_p ) ;\n\t\t\t\tassert( regularising_sigma.cols() == m_p ) ;\n\t\t\t\tassert( regularising_weight >= 0.0 ) ;\n\n\t\t\t\tif( data_subset.size() == 0 ) {\n\t\t\t\t\t// No data.  Do nothing and return false.\n\t\t\t\t\treturn false ;\n\t\t\t\t}\n\n\t\t\t\t// Start with unit weights, giving MVN estimate\n\t\t\t\tVector iterationWeights = Vector::Constant( m_data->rows(), 1 ) ;\n\t\t\t\tVector mean = compute_weighted_mean( iterationWeights, m_weights, data_subset ) ;\n\t\t\t\tMatrix sigma = compute_weighted_regularised_sigma( iterationWeights, m_weights, mean, regularising_sigma, regularising_weight, data_subset ) ;\n\n\t\t\t\tevaluate_at( mean, sigma, data_subset ) ;\n\t\t\t\tdouble loglikelihood = get_value_of_function() ;\n\t\t\t\t\n#if DEBUG_MULTIVARIATE_T\n\t\t\t\tstd::cerr << \"metro::likelihood::MultivariateT::estimate_by_em(): start: params = \"\n\t\t\t\t\t<< get_parameters().transpose() << \", ll = \" << get_value_of_function() << \".\\n\" ;\n#endif\t\t\t\t\n\n\t\t\t\t// If nu = \u221e we are at the MLE already, so bail out...\n\t\t\t\tif( m_nu == std::numeric_limits< double >::infinity() ) {\n\t\t\t\t\t// Multivariate normal.  Quit right now.\n\t\t\t\t\treturn true ;\n\t\t\t\t}\n\n\t\t\t\t// ..otherwise let's EM it.\n\t\t\t\tstd::size_t iteration = 0 ;\n\t\t\t\twhile( !stopping_condition( loglikelihood ) ) {\n\t\t\t\t\t// compute weights\n\t\t\t\t\t// Vector of weights is given as\n\t\t\t\t\t// (nu+p) / nu + (x_i-mean)^t R^-1 ( x_i - mean ).\n\t\t\t\t\t// Our x_i - mean_i is stored in a single row of m_mean_centred_data.\n\t\t\t\t\tm_A = m_ldlt.solve( m_mean_centred_data.transpose() ) ;\n\t\t\t\t\titerationWeights = (\n\t\t\t\t\t\tm_mean_centred_data.array() * m_A.transpose().array()\n\t\t\t\t\t).rowwise().sum() ;\n\t\t\t\t\titerationWeights += Vector::Constant( m_data->rows(), m_nu ) ;\n\t\t\t\t\titerationWeights.array() = iterationWeights.array().inverse() * ( m_nu + m_p ) ;\n\n\t\t\t\t\t// compute new parameter estimates\n\t\t\t\t\t// these are\n\t\t\t\t\t// mean = sum( w_i x_i ) / sum( w_i )\n\t\t\t\t\tmean = compute_weighted_mean( iterationWeights, m_weights, data_subset ) ;\n\t\t\t\t\tsigma = compute_weighted_regularised_sigma( iterationWeights, m_weights, mean, regularising_sigma, regularising_weight, data_subset ) ;\n\t\t\t\t\tevaluate_at( mean, sigma, data_subset ) ;\n\t\t\t\t\tloglikelihood = get_value_of_function() ;\n\n#if DEBUG_MULTIVARIATE_T\n\t\t\t\t\tstd::cerr << \"metro::likelihood::MultivariateT::estimate_by_em(): after iteration \"\n\t\t\t\t\t\t<< iteration << \": params = \" << get_parameters().transpose()\n\t\t\t\t\t\t<< \", ll = \" << loglikelihood\n\t\t\t\t\t\t<< \", iterationWeights = \" << iterationWeights.head( std::min( iterationWeights.size(), 10l )).transpose() << \".\\n\" ;\n#endif\t\t\t\t\n\t\t\t\t\t++iteration ;\n\t\t\t\t}\n\t\t\t\treturn stopping_condition.converged() ;\n\t\t\t}\n\n\t\tprivate:\n\t\t\tdouble const m_pi ;\n\t\t\tdouble const m_nu ;\n\t\t\tMatrix const* m_data ;\n\t\t\tDataSubset m_data_subset ;\n\t\t\tVector m_weights ;\n\t\t\tdouble m_p ;\n\t\t\tdouble m_kappa ;\n\t\t\tVector m_parameters ;\n\t\t\tMatrix m_sigma ;\n\t\t\tVector m_mean ;\n\n\t\t\tEigen::LDLT< Matrix > m_ldlt ;\n\t\t\tdouble m_log_determinant ;\n\t\t\tMatrix m_mean_centred_data ;\n\t\t\tMatrix m_A ;\n\t\t\tVector m_Z ;\n\t\t\t\n\t\tprivate:\n\t\t\t\n\t\t\tdouble compute_constant_terms( double const nu, double const p ) const {\n\t\t\t\treturn ( nu == std::numeric_limits< double >::infinity() )\n\t\t\t\t\t? (\n\t\t\t\t\t\t-0.5 * p * std::log( 2 * m_pi )\n\t\t\t\t\t) : (\n\t\t\t\t\t\tlgamma( ( nu + p ) / 2.0 )\n\t\t\t\t\t\t- ( p / 2 ) * std::log( m_pi * nu )\n\t\t\t\t\t\t- lgamma( nu / 2.0 )\n\t\t\t\t\t\t+ (( nu + p ) * std::log( nu ) / 2.0 )\n\t\t\t\t\t)\n\t\t\t\t;\n\t\t\t}\n\n\t\t\tvoid pack_parameters( Vector const& mean, Matrix const& sigma, Vector* result ) const {\n\t\t\t\tresult->resize( mean.size() + ( sigma.rows() * ( sigma.rows() + 1 ) / 2 )) ;\n\t\t\t\tresult->segment( 0, mean.size() ) = mean ;\n\t\t\t\tint parameter_i = mean.size() ;\n\t\t\t\tfor( int col = 0; col < m_p; ++col ) {\n\t\t\t\t\tresult->segment( parameter_i, m_p - col ) = sigma.col( col ).segment( col, m_p - col ) ;\n\t\t\t\t\tparameter_i += m_p - col ;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvoid unpack_parameters( Vector const& parameters, Vector* mean, Matrix* sigma ) const {\n\t\t\t\t*mean = parameters.head( m_p ) ;\n\t\t\t\tsigma->resize( m_p, m_p ) ;\n\t\t\t\tint parameter_i = m_p ;\n\t\t\t\tfor( int col = 0; col < m_data->cols(); ++col ) {\n\t\t\t\t\tsigma->col( col ).segment( col, m_p - col ) = parameters.segment( parameter_i, m_p - col ) ;\n\t\t\t\t\tparameter_i += m_p - col ;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tVector compute_weighted_mean(\n\t\t\t\tVector const& iterationWeights,\n\t\t\t\tVector const& dataWeights,\n\t\t\t\tDataSubset const& subset\n\t\t\t) const {\n\t\t\t\tVector result = Vector::Zero( m_p ) ;\n\t\t\t\tdouble total_weight = 0 ;\n\t\t\t\tfor( std::size_t i = 0; i < subset.number_of_subranges(); ++i ) {\n\t\t\t\t\tDataRange const& range = subset[i] ;\n\t\t\t\t\tConstSegment segmentIW = iterationWeights.segment( range.begin(), range.size() ) ;\n\t\t\t\t\tConstSegment segmentDW = dataWeights.segment( range.begin(), range.size() ) ;\n\t\t\t\t\t\n\t\t\t\t\tresult += (\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\t( segmentIW.array() * segmentDW.array() ).matrix().asDiagonal()\n\t\t\t\t\t\t\t* m_data->block( range.begin(), 0, range.size(), m_p )\n\t\t\t\t\t\t).colwise().sum()\n\t\t\t\t\t).transpose() ;\n\n\t\t\t\t\ttotal_weight += ( segmentDW.array() * segmentIW.array() ).sum() ;\n\t\t\t\t}\n\t\t\t\tresult /= total_weight ;\n\t\t\t\treturn result ;\n\t\t\t}\n\t\t\t\n\t\t\tMatrix compute_weighted_regularised_sigma(\n\t\t\t\tVector const& iterationWeights,\n\t\t\t\tVector const& dataWeights,\n\t\t\t\tVector const& mean,\n\t\t\t\tMatrix const& regularising_sigma,\n\t\t\t\tdouble const regularising_weight,\n\t\t\t\tDataSubset const& subset\n\t\t\t) const {\n\t\t\t\tMatrix mean_centred_data = m_data->rowwise() - mean.transpose() ;\n\t\t\t\t// sigma = 1/N sum ( w_i (x_i-mean)(x_i-mean)^t)\n\t\t\t\t// we store x_i as a row not a column, so transposes go the opposite way.\n\t\t\t\tMatrix result = Matrix::Zero( m_p, m_p ) ;\n\t\t\t\tdouble n = 0 ;\n\t\t\t\tfor( std::size_t i = 0; i < subset.number_of_subranges(); ++i ) {\n\t\t\t\t\tDataRange const& range = subset[i] ;\n\t\t\t\t\tConstSegment segmentIW = iterationWeights.segment( range.begin(), range.size() ) ;\n\t\t\t\t\tConstSegment segmentDW = dataWeights.segment( range.begin(), range.size() ) ;\n\n\t\t\t\t\tresult += (\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tmean_centred_data.block( range.begin(), 0, range.size(), m_p ).transpose()\n\t\t\t\t\t\t\t* segmentIW.asDiagonal()\n\t\t\t\t\t\t\t* segmentDW.asDiagonal()\n\t\t\t\t\t\t\t* mean_centred_data.block( range.begin(), 0, range.size(), m_p )\n\t\t\t\t\t\t)\n\t\t\t\t\t) ;\n\t\t\t\t\tn += segmentDW.sum() ;\n\t\t\t\t}\n\t\t\t\tresult += regularising_weight * regularising_sigma ;\n\t\t\t\tresult /= ( n + regularising_weight ) ;\n\t\t\t\treturn result ;\n\t\t\t}\n\t\t} ;\n\t}\n}\n\n#endif\n", "meta": {"hexsha": "d67e26bb1e9db79bcb7dc525463451077768505f", "size": 18816, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "metro/include/metro/likelihood/MultivariateT.hpp", "max_stars_repo_name": "gavinband/bingwa", "max_stars_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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": "metro/include/metro/likelihood/MultivariateT.hpp", "max_issues_repo_name": "gavinband/bingwa", "max_issues_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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": "metro/include/metro/likelihood/MultivariateT.hpp", "max_forks_repo_name": "gavinband/bingwa", "max_forks_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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.2, "max_line_length": 146, "alphanum_fraction": 0.6632653061, "num_tokens": 5014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5108915580077664}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2009 - 2021 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: Luca Heltai, Cataldo Manigrasso, 2009 \n */ \n\n\n// @sect3{Include files}  \n\n// \u7a0b\u5e8f\u4e00\u5f00\u59cb\u5c31\u5305\u62ec\u4e86\u4e00\u5806include\u6587\u4ef6\uff0c\u6211\u4eec\u5c06\u5728\u7a0b\u5e8f\u7684\u5404\u4e2a\u90e8\u5206\u4f7f\u7528\u8fd9\u4e9b\u6587\u4ef6\u3002\u5176\u4e2d\u5927\u90e8\u5206\u5728\u4ee5\u524d\u7684\u6559\u7a0b\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u4e86\u3002\n\n#include <deal.II/base/smartpointer.h> \n#include <deal.II/base/convergence_table.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/quadrature_selector.h> \n#include <deal.II/base/parsed_function.h> \n#include <deal.II/base/utilities.h> \n\n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/solver_control.h> \n#include <deal.II/lac/solver_gmres.h> \n#include <deal.II/lac/precondition.h> \n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_in.h> \n#include <deal.II/grid/grid_out.h> \n#include <deal.II/grid/manifold_lib.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/fe/mapping_q.h> \n\n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/vector_tools.h> \n\n// \u8fd9\u91cc\u6709\u4e00\u4e9b\u6211\u4eec\u9700\u8981\u7684C++\u6807\u51c6\u5934\u6587\u4ef6\u3002\n\n#include <cmath> \n#include <iostream> \n#include <fstream> \n#include <string> \n\n// \u8fd9\u4e2a\u5e8f\u8a00\u7684\u6700\u540e\u90e8\u5206\u662f\u5c06dealii\u547d\u540d\u7a7a\u95f4\u4e2d\u7684\u6240\u6709\u5185\u5bb9\u5bfc\u5165\u5230\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u7684\u6240\u6709\u5185\u5bb9\u4e2d\u3002\n\nnamespace Step34 \n{ \n  using namespace dealii; \n// @sect3{Single and double layer operator kernels}  \n\n// \u9996\u5148\uff0c\u8ba9\u6211\u4eec\u5b9a\u4e49\u4e00\u4e0b\u8fb9\u754c\u79ef\u5206\u65b9\u7a0b\u7684\u673a\u5236\u3002\n\n// \u4ee5\u4e0b\u4e24\u4e2a\u51fd\u6570\u662f\u5355\u5c42\u548c\u53cc\u5c42\u52bf\u80fd\u6838\u7684\u5b9e\u9645\u8ba1\u7b97\uff0c\u5373  $G$  \u548c  $\\nabla G$  \u3002\u53ea\u6709\u5f53\u77e2\u91cf $R = \\mathbf{y}-\\mathbf{x}$ \u4e0d\u540c\u4e8e\u96f6\u65f6\uff0c\u5b83\u4eec\u624d\u662f\u5b9a\u4e49\u826f\u597d\u7684\u3002\n\n  namespace LaplaceKernel \n  { \n    template <int dim> \n    double single_layer(const Tensor<1, dim> &R) \n    { \n      switch (dim) \n        { \n          case 2: \n            return (-std::log(R.norm()) / (2 * numbers::PI)); \n\n          case 3: \n            return (1. / (R.norm() * 4 * numbers::PI)); \n\n          default: \n            Assert(false, ExcInternalError()); \n            return 0.; \n        } \n    } \n\n    template <int dim> \n    Tensor<1, dim> double_layer(const Tensor<1, dim> &R) \n    { \n      switch (dim) \n        { \n          case 2: \n            return R / (-2 * numbers::PI * R.norm_square()); \n          case 3: \n            return R / (-4 * numbers::PI * R.norm_square() * R.norm()); \n\n          default: \n            Assert(false, ExcInternalError()); \n            return Tensor<1, dim>(); \n        } \n    } \n  } // namespace LaplaceKernel \n// @sect3{The BEMProblem class}  \n\n// \u8fb9\u754c\u5143\u7d20\u65b9\u6cd5\u4ee3\u7801\u7684\u7ed3\u6784\u4e0e\u6709\u9650\u5143\u7d20\u4ee3\u7801\u7684\u7ed3\u6784\u975e\u5e38\u76f8\u4f3c\uff0c\u6240\u4ee5\u8fd9\u4e2a\u7c7b\u7684\u6210\u5458\u51fd\u6570\u4e0e\u5176\u4ed6\u5927\u591a\u6570\u6559\u7a0b\u7a0b\u5e8f\u7684\u6210\u5458\u51fd\u6570\u4e00\u6837\u3002\u7279\u522b\u662f\uff0c\u73b0\u5728\u4f60\u5e94\u8be5\u719f\u6089\u4ece\u5916\u90e8\u6587\u4ef6\u4e2d\u8bfb\u53d6\u53c2\u6570\uff0c\u4ee5\u53ca\u5c06\u4e0d\u540c\u7684\u4efb\u52a1\u5206\u5272\u6210\u4e0d\u540c\u7684\u6a21\u5757\u3002\u8fd9\u540c\u6837\u9002\u7528\u4e8e\u8fb9\u754c\u5143\u7d20\u65b9\u6cd5\uff0c\u6211\u4eec\u4e0d\u4f1a\u5bf9\u5176\u8fdb\u884c\u8fc7\u591a\u7684\u8bc4\u8bba\uff0c\u53ea\u662f\u5bf9\u5176\u4e2d\u7684\u5dee\u5f02\u8fdb\u884c\u8bc4\u8bba\u3002\n\n  template <int dim> \n  class BEMProblem \n  { \n  public: \n    BEMProblem(const unsigned int fe_degree      = 1, \n               const unsigned int mapping_degree = 1); \n\n    void run(); \n\n  private: \n    void read_parameters(const std::string &filename); \n\n    void read_domain(); \n\n    void refine_and_resize(); \n\n// \u6211\u4eec\u5728\u8fd9\u91cc\u53d1\u73b0\u7684\u552f\u4e00\u771f\u6b63\u4e0d\u540c\u7684\u51fd\u6570\u662f\u88c5\u914d\u7a0b\u5e8f\u3002\u6211\u4eec\u4ee5\u6700\u901a\u7528\u7684\u65b9\u5f0f\u7f16\u5199\u4e86\u8fd9\u4e2a\u51fd\u6570\uff0c\u4ee5\u4fbf\u80fd\u591f\u65b9\u4fbf\u5730\u63a8\u5e7f\u5230\u9ad8\u9636\u65b9\u6cd5\u548c\u4e0d\u540c\u7684\u57fa\u672c\u89e3\uff08\u4f8b\u5982\u65af\u6258\u514b\u65af\u6216\u9ea6\u514b\u65af\u97e6\uff09\u3002\n\n// \u6700\u660e\u663e\u7684\u533a\u522b\u662f\uff0c\u6700\u7ec8\u7684\u77e9\u9635\u662f\u5b8c\u6574\u7684\uff0c\u800c\u4e14\u6211\u4eec\u5728\u901a\u5e38\u7684\u5355\u5143\u683c\u5faa\u73af\u5185\u6709\u4e00\u4e2a\u5d4c\u5957\u7684\u5faa\u73af\uff0c\u8bbf\u95ee\u6240\u6709\u81ea\u7531\u5ea6\u7684\u652f\u6301\u70b9\u3002 \u6b64\u5916\uff0c\u5f53\u652f\u6301\u70b9\u4f4d\u4e8e\u6211\u4eec\u6240\u8bbf\u95ee\u7684\u5355\u5143\u5185\u65f6\uff0c\u6211\u4eec\u6240\u6267\u884c\u7684\u79ef\u5206\u5c31\u4f1a\u53d8\u6210\u5355\u6570\u3002\n\n// \u5b9e\u9645\u7684\u7ed3\u679c\u662f\uff0c\u6211\u4eec\u6709\u4e24\u5957\u6b63\u4ea4\u516c\u5f0f\u3001\u6709\u9650\u5143\u503c\u548c\u4e34\u65f6\u5b58\u50a8\uff0c\u4e00\u5957\u7528\u4e8e\u6807\u51c6\u79ef\u5206\uff0c\u53e6\u4e00\u5957\u7528\u4e8e\u5947\u5f02\u79ef\u5206\uff0c\u5728\u5fc5\u8981\u65f6\u4f7f\u7528\u3002\n\n    void assemble_system(); \n\n// \u5bf9\u4e8e\u8fd9\u4e2a\u95ee\u9898\u7684\u89e3\u51b3\u6709\u4e24\u79cd\u9009\u62e9\u3002\u7b2c\u4e00\u4e2a\u662f\u4f7f\u7528\u76f4\u63a5\u6c42\u89e3\u5668\uff0c\u7b2c\u4e8c\u4e2a\u662f\u4f7f\u7528\u8fed\u4ee3\u6c42\u89e3\u5668\u3002\u6211\u4eec\u9009\u62e9\u4e86\u7b2c\u4e8c\u79cd\u65b9\u6848\u3002\n\n// \u6211\u4eec\u7ec4\u88c5\u7684\u77e9\u9635\u4e0d\u662f\u5bf9\u79f0\u7684\uff0c\u6211\u4eec\u9009\u62e9\u4f7f\u7528GMRES\u65b9\u6cd5\uff1b\u7136\u800c\u4e3a\u8fb9\u754c\u5143\u7d20\u65b9\u6cd5\u6784\u5efa\u4e00\u4e2a\u6709\u6548\u7684\u9884\u5904\u7406\u7a0b\u5e8f\u5e76\u4e0d\u662f\u4e00\u4e2a\u7b80\u5355\u7684\u95ee\u9898\u3002\u8fd9\u91cc\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u975e\u9884\u5904\u7406\u7684GMRES\u6c42\u89e3\u5668\u3002\u8fed\u4ee3\u6c42\u89e3\u5668\u7684\u9009\u9879\uff0c\u5982\u516c\u5dee\u3001\u6700\u5927\u8fed\u4ee3\u6b21\u6570\u7b49\uff0c\u90fd\u662f\u901a\u8fc7\u53c2\u6570\u6587\u4ef6\u9009\u62e9\u7684\u3002\n\n    void solve_system(); \n\n// \u4e00\u65e6\u6211\u4eec\u5f97\u5230\u4e86\u89e3\u51b3\u65b9\u6848\uff0c\u6211\u4eec\u5c06\u8ba1\u7b97\u8ba1\u7b97\u51fa\u7684\u52bf\u7684 $L^2$ \u8bef\u5dee\uff0c\u4ee5\u53ca\u5b9e\u4f53\u89d2\u7684\u8fd1\u4f3c\u503c\u7684 $L^\\infty$ \u8bef\u5dee\u3002\u6211\u4eec\u4f7f\u7528\u7684\u7f51\u683c\u662f\u5e73\u6ed1\u66f2\u7ebf\u7684\u8fd1\u4f3c\u503c\uff0c\u56e0\u6b64\u8ba1\u7b97\u51fa\u7684\u89d2\u7684\u5206\u91cf\u6216\u5b9e\u4f53\u89d2\u7684\u5bf9\u89d2\u7ebf\u77e9\u9635  $\\alpha(\\mathbf{x})$  \u5e94\u8be5\u4e00\u76f4\u7b49\u4e8e  $\\frac 12$  \u3002\u5728\u8fd9\u4e2a\u4f8b\u7a0b\u4e2d\uff0c\u6211\u4eec\u8f93\u51fa\u52bf\u7684\u8bef\u5dee\u548c\u8ba1\u7b97\u89d2\u5ea6\u7684\u8fd1\u4f3c\u503c\u7684\u8bef\u5dee\u3002\u6ce8\u610f\uff0c\u540e\u8005\u7684\u8bef\u5dee\u5b9e\u9645\u4e0a\u4e0d\u662f\u8ba1\u7b97\u89d2\u5ea6\u7684\u8bef\u5dee\uff0c\u800c\u662f\u8861\u91cf\u6211\u4eec\u5bf9\u7403\u4f53\u548c\u5706\u7684\u8fd1\u4f3c\u7a0b\u5ea6\u3002\n\n// \u5bf9\u89d2\u5ea6\u7684\u8ba1\u7b97\u505a\u4e00\u4e9b\u5b9e\u9a8c\uff0c\u5bf9\u4e8e\u8f83\u7b80\u5355\u7684\u51e0\u4f55\u5f62\u72b6\uff0c\u53ef\u4ee5\u5f97\u5230\u975e\u5e38\u51c6\u786e\u7684\u7ed3\u679c\u3002\u4e3a\u4e86\u9a8c\u8bc1\u8fd9\u4e00\u70b9\uff0c\u4f60\u53ef\u4ee5\u5728read_domain()\u65b9\u6cd5\u4e2d\u6ce8\u91ca\u6389tria.set_manifold(1, manifold)\u4e00\u884c\uff0c\u5e76\u68c0\u67e5\u7a0b\u5e8f\u751f\u6210\u7684alpha\u3002\u901a\u8fc7\u5220\u9664\u8fd9\u4e2a\u8c03\u7528\uff0c\u6bcf\u5f53\u7ec6\u5316\u7f51\u683c\u65f6\uff0c\u65b0\u7684\u8282\u70b9\u5c06\u6cbf\u7740\u6784\u6210\u7c97\u7565\u7f51\u683c\u7684\u76f4\u7ebf\u653e\u7f6e\uff0c\u800c\u4e0d\u662f\u88ab\u62c9\u5230\u6211\u4eec\u771f\u6b63\u60f3\u8981\u8fd1\u4f3c\u7684\u8868\u9762\u3002\u5728\u4e09\u7ef4\u6848\u4f8b\u4e2d\uff0c\u7403\u4f53\u7684\u7c97\u7f51\u683c\u662f\u4ece\u4e00\u4e2a\u7acb\u65b9\u4f53\u5f00\u59cb\u5f97\u5230\u7684\uff0c\u5f97\u5230\u7684\u5b57\u6bcd\u503c\u6b63\u597d\u662f\u9762\u7684\u8282\u70b9\u4e0a\u7684 $\\frac 12$ \uff0c\u8fb9\u7684\u8282\u70b9\u4e0a\u7684 $\\frac 34$ \u548c\u9876\u70b9\u76848\u4e2a\u8282\u70b9\u4e0a\u7684 $\\frac 78$ \u3002\n\n    void compute_errors(const unsigned int cycle); \n\n// \u4e00\u65e6\u6211\u4eec\u5728\u4e00\u7ef4\u9886\u57df\u5f97\u5230\u4e86\u4e00\u4e2a\u89e3\u51b3\u65b9\u6848\uff0c\u6211\u4eec\u5c31\u60f3\u628a\u5b83\u63d2\u503c\u5230\u7a7a\u95f4\u7684\u5176\u4ed6\u90e8\u5206\u3002\u8fd9\u53ef\u4ee5\u901a\u8fc7\u5728compute_exterior_solution()\u51fd\u6570\u4e2d\u518d\u6b21\u8fdb\u884c\u89e3\u4e0e\u6838\u7684\u5377\u79ef\u6765\u5b9e\u73b0\u3002\n\n// \u6211\u4eec\u60f3\u7ed8\u5236\u901f\u5ea6\u53d8\u91cf\uff0c\u4e5f\u5c31\u662f\u52bf\u89e3\u7684\u68af\u5ea6\u3002\u52bf\u89e3\u53ea\u5728\u8fb9\u754c\u4e0a\u662f\u5df2\u77e5\u7684\uff0c\u4f46\u6211\u4eec\u4f7f\u7528\u4e0e\u57fa\u672c\u89e3\u7684\u5377\u79ef\u5728\u6807\u51c6\u7684\u4e8c\u7ef4\u8fde\u7eed\u6709\u9650\u5143\u7a7a\u95f4\u4e0a\u8fdb\u884c\u63d2\u503c\u3002\u5916\u63a8\u89e3\u7684\u68af\u5ea6\u56fe\u5c06\u7ed9\u6211\u4eec\u63d0\u4f9b\u6211\u4eec\u60f3\u8981\u7684\u901f\u5ea6\u3002\n\n// \u9664\u4e86\u5916\u57df\u4e0a\u7684\u89e3\uff0c\u6211\u4eec\u8fd8\u5728output_results()\u51fd\u6570\u4e2d\u8f93\u51fa\u57df\u7684\u8fb9\u754c\u4e0a\u7684\u89e3\uff0c\u5f53\u7136\u4e86\u3002\n\n    void compute_exterior_solution(); \n\n    void output_results(const unsigned int cycle); \n\n// \u4e3a\u4e86\u5b9e\u73b0\u4e0d\u53d7\u7ef4\u5ea6\u9650\u5236\u7684\u7f16\u7a0b\uff0c\u6211\u4eec\u5bf9\u8fd9\u4e2a\u5355\u4e00\u7684\u51fd\u6570\u8fdb\u884c\u4e86\u4e13\u4e1a\u5316\u5904\u7406\uff0c\u4ee5\u63d0\u53d6\u6574\u5408\u5355\u5143\u5185\u90e8\u7684\u5947\u5f02\u6838\u6240\u9700\u7684\u5947\u5f02\u6b63\u4ea4\u516c\u5f0f\u3002\n\n    const Quadrature<dim - 1> &get_singular_quadrature( \n      const typename DoFHandler<dim - 1, dim>::active_cell_iterator &cell, \n      const unsigned int index) const; \n\n// \u901a\u5e38\u7684deal.II\u7c7b\u53ef\u4ee5\u901a\u8fc7\u6307\u5b9a\u95ee\u9898\u7684 \"\u4e8c\u7ef4 \"\u6765\u7528\u4e8e\u8fb9\u754c\u5143\u7d20\u65b9\u6cd5\u3002\u8fd9\u662f\u901a\u8fc7\u5c06Triangulation, FiniteElement\u548cDoFHandler\u7684\u53ef\u9009\u7b2c\u4e8c\u6a21\u677f\u53c2\u6570\u8bbe\u7f6e\u4e3a\u5d4c\u5165\u7a7a\u95f4\u7684\u7ef4\u5ea6\u6765\u5b9e\u73b0\u7684\u3002\u5728\u6211\u4eec\u7684\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u751f\u6210\u4e86\u5d4c\u5165\u5728\u4e8c\u7ef4\u6216\u4e09\u7ef4\u7a7a\u95f4\u7684\u4e00\u7ef4\u6216\u4e8c\u7ef4\u7f51\u683c\u3002\n\n// \u53ef\u9009\u53c2\u6570\u9ed8\u8ba4\u7b49\u4e8e\u7b2c\u4e00\u4e2a\u53c2\u6570\uff0c\u5e76\u4ea7\u751f\u6211\u4eec\u5728\u4e4b\u524d\u6240\u6709\u4f8b\u5b50\u4e2d\u770b\u5230\u7684\u901a\u5e38\u7684\u6709\u9650\u5143\u7c7b\u3002\n\n// \u8be5\u7c7b\u7684\u6784\u9020\u65b9\u5f0f\u662f\u5141\u8bb8\u4efb\u610f\u7684\u57df\uff08\u901a\u8fc7\u9ad8\u9636\u6620\u5c04\uff09\u548c\u6709\u9650\u5143\u7a7a\u95f4\u7684\u903c\u8fd1\u987a\u5e8f\u3002\u6709\u9650\u5143\u7a7a\u95f4\u548c\u6620\u5c04\u7684\u987a\u5e8f\u53ef\u4ee5\u5728\u8be5\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4e2d\u9009\u62e9\u3002\n\n    Triangulation<dim - 1, dim> tria; \n    FE_Q<dim - 1, dim>          fe; \n    DoFHandler<dim - 1, dim>    dof_handler; \n    MappingQ<dim - 1, dim>      mapping; \n\n// \u5728BEM\u65b9\u6cd5\u4e2d\uff0c\u751f\u6210\u7684\u77e9\u9635\u662f\u5bc6\u96c6\u7684\u3002\u6839\u636e\u95ee\u9898\u7684\u5927\u5c0f\uff0c\u6700\u7ec8\u7684\u7cfb\u7edf\u53ef\u80fd\u901a\u8fc7\u76f4\u63a5\u7684LU\u5206\u89e3\u6765\u89e3\u51b3\uff0c\u6216\u8005\u901a\u8fc7\u8fed\u4ee3\u65b9\u6cd5\u6765\u89e3\u51b3\u3002\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u4f7f\u7528\u4e86\u4e00\u4e2a\u65e0\u6761\u4ef6\u7684GMRES\u65b9\u6cd5\u3002\u4e3aBEM\u65b9\u6cd5\u5efa\u7acb\u4e00\u4e2a\u9884\u5904\u7406\u7a0b\u5e8f\u662f\u4e0d\u5bb9\u6613\u7684\uff0c\u6211\u4eec\u5728\u6b64\u4e0d\u505a\u5904\u7406\u3002\n\n    FullMatrix<double> system_matrix; \n    Vector<double>     system_rhs; \n\n// \u63a5\u4e0b\u6765\u7684\u4e24\u4e2a\u53d8\u91cf\u5c06\u8868\u793a\u89e3\u51b3\u65b9\u6848 $\\phi$ \u4ee5\u53ca\u4e00\u4e2a\u5411\u91cf\uff0c\u5b83\u5c06\u4fdd\u5b58 $\\alpha(\\mathbf x)$ \u7684\u503c\uff08\u4ece\u4e00\u4e2a\u70b9 $\\mathbf x$ \u53ef\u89c1\u7684 $\\Omega$ \u7684\u90e8\u5206\uff09\u5728\u6211\u4eec\u5f62\u72b6\u51fd\u6570\u7684\u652f\u6301\u70b9\u3002\n\n    Vector<double> phi; \n    Vector<double> alpha; \n\n// \u6536\u655b\u8868\u662f\u7528\u6765\u8f93\u51fa\u7cbe\u786e\u89e3\u548c\u8ba1\u7b97\u51fa\u7684\u5b57\u6bcd\u7684\u8bef\u5dee\u7684\u3002\n\n    ConvergenceTable convergence_table; \n\n// \u4e0b\u9762\u7684\u53d8\u91cf\u662f\u6211\u4eec\u901a\u8fc7\u53c2\u6570\u6587\u4ef6\u6765\u586b\u5145\u7684\u3002 \u672c\u4f8b\u4e2d\u6211\u4eec\u4f7f\u7528\u7684\u65b0\u5bf9\u8c61\u662f Functions::ParsedFunction \u5bf9\u8c61\u548cQuadratureSelector\u5bf9\u8c61\u3002\n\n//  Functions::ParsedFunction \u7c7b\u5141\u8bb8\u6211\u4eec\u901a\u8fc7\u53c2\u6570\u6587\u4ef6\u65b9\u4fbf\u5feb\u6377\u5730\u5b9a\u4e49\u65b0\u7684\u51fd\u6570\u5bf9\u8c61\uff0c\u81ea\u5b9a\u4e49\u7684\u5b9a\u4e49\u53ef\u4ee5\u975e\u5e38\u590d\u6742\uff08\u5173\u4e8e\u6240\u6709\u53ef\u7528\u7684\u9009\u9879\uff0c\u89c1\u8be5\u7c7b\u7684\u6587\u6863\uff09\u3002\n\n// \u6211\u4eec\u5c06\u4f7f\u7528QuadratureSelector\u7c7b\u6765\u5206\u914d\u6b63\u4ea4\u5bf9\u8c61\uff0c\u8be5\u7c7b\u5141\u8bb8\u6211\u4eec\u6839\u636e\u4e00\u4e2a\u8bc6\u522b\u5b57\u7b26\u4e32\u548c\u516c\u5f0f\u672c\u8eab\u7684\u53ef\u80fd\u7a0b\u5ea6\u6765\u751f\u6210\u6b63\u4ea4\u516c\u5f0f\u3002\u6211\u4eec\u7528\u5b83\u6765\u5141\u8bb8\u81ea\u5b9a\u4e49\u9009\u62e9\u6807\u51c6\u79ef\u5206\u7684\u6b63\u4ea4\u516c\u5f0f\uff0c\u5e76\u5b9a\u4e49\u5947\u5f02\u6b63\u4ea4\u89c4\u5219\u7684\u987a\u5e8f\u3002\n\n// \u6211\u4eec\u8fd8\u5b9a\u4e49\u4e86\u51e0\u4e2a\u53c2\u6570\uff0c\u8fd9\u4e9b\u53c2\u6570\u662f\u5728\u6211\u4eec\u60f3\u628a\u89e3\u51b3\u65b9\u6848\u6269\u5c55\u5230\u6574\u4e2a\u9886\u57df\u7684\u60c5\u51b5\u4e0b\u4f7f\u7528\u7684\u3002\n\n    Functions::ParsedFunction<dim> wind; \n    Functions::ParsedFunction<dim> exact_solution; \n\n    unsigned int                         singular_quadrature_order; \n    std::shared_ptr<Quadrature<dim - 1>> quadrature; \n\n    SolverControl solver_control; \n\n    unsigned int n_cycles; \n    unsigned int external_refinement; \n\n    bool run_in_this_dimension; \n    bool extend_solution; \n  }; \n// @sect4{BEMProblem::BEMProblem and BEMProblem::read_parameters}  \n\n//\u6784\u9020\u51fd\u6570\u521d\u59cb\u5316\u5404\u79cd\u5bf9\u8c61\u7684\u65b9\u5f0f\u4e0e\u6709\u9650\u5143\u7a0b\u5e8f\uff08\u5982  step-4  \u6216  step-6  \uff09\u4e2d\u7684\u65b9\u5f0f\u57fa\u672c\u76f8\u540c\u3002\u8fd9\u91cc\u552f\u4e00\u7684\u65b0\u6210\u5206\u662fParsedFunction\u5bf9\u8c61\uff0c\u5b83\u5728\u6784\u9020\u65f6\u9700\u8981\u8bf4\u660e\u7ec4\u4ef6\u7684\u6570\u91cf\u3002\n\n// \u5bf9\u4e8e\u7cbe\u786e\u89e3\u6765\u8bf4\uff0c\u5411\u91cf\u5206\u91cf\u7684\u6570\u91cf\u662f1\uff0c\u800c\u4e14\u4e0d\u9700\u8981\u4efb\u4f55\u64cd\u4f5c\uff0c\u56e0\u4e3a1\u662fParsedFunction\u5bf9\u8c61\u7684\u9ed8\u8ba4\u503c\u3002\u7136\u800c\uff0c\u98ce\u9700\u8981\u6307\u5b9adim\u7ec4\u4ef6\u3002\u6ce8\u610f\uff0c\u5728\u4e3a Functions::ParsedFunction, \u7684\u8868\u8fbe\u5f0f\u58f0\u660e\u53c2\u6570\u6587\u4ef6\u4e2d\u7684\u6761\u76ee\u65f6\uff0c\u6211\u4eec\u9700\u8981\u660e\u786e\u6307\u5b9a\u5206\u91cf\u7684\u6570\u91cf\uff0c\u56e0\u4e3a\u51fd\u6570 Functions::ParsedFunction::declare_parameters \u662f\u9759\u6001\u7684\uff0c\u5bf9\u5206\u91cf\u7684\u6570\u91cf\u6ca1\u6709\u4e86\u89e3\u3002\n\n  template <int dim> \n  BEMProblem<dim>::BEMProblem(const unsigned int fe_degree, \n                              const unsigned int mapping_degree) \n    : fe(fe_degree) \n    , dof_handler(tria) \n    , mapping(mapping_degree, true) \n    , wind(dim) \n    , singular_quadrature_order(5) \n    , n_cycles(4) \n    , external_refinement(5) \n    , run_in_this_dimension(true) \n    , extend_solution(true) \n  {} \n\n  template <int dim> \n  void BEMProblem<dim>::read_parameters(const std::string &filename) \n  { \n    deallog << std::endl \n            << \"Parsing parameter file \" << filename << std::endl \n            << \"for a \" << dim << \" dimensional simulation. \" << std::endl; \n\n    ParameterHandler prm; \n\n    prm.declare_entry(\"Number of cycles\", \"4\", Patterns::Integer()); \n    prm.declare_entry(\"External refinement\", \"5\", Patterns::Integer()); \n    prm.declare_entry(\"Extend solution on the -2,2 box\", \n                      \"true\", \n                      Patterns::Bool()); \n    prm.declare_entry(\"Run 2d simulation\", \"true\", Patterns::Bool()); \n    prm.declare_entry(\"Run 3d simulation\", \"true\", Patterns::Bool()); \n\n    prm.enter_subsection(\"Quadrature rules\"); \n    { \n      prm.declare_entry( \n        \"Quadrature type\", \n        \"gauss\", \n        Patterns::Selection( \n          QuadratureSelector<(dim - 1)>::get_quadrature_names())); \n      prm.declare_entry(\"Quadrature order\", \"4\", Patterns::Integer()); \n      prm.declare_entry(\"Singular quadrature order\", \"5\", Patterns::Integer()); \n    } \n    prm.leave_subsection(); \n\n// \u5bf9\u4e8e\u4e8c\u7ef4\u548c\u4e09\u7ef4\uff0c\u6211\u4eec\u5c06\u9ed8\u8ba4\u7684\u8f93\u5165\u6570\u636e\u8bbe\u7f6e\u4e3a\uff1a\u89e3\u4e3a  $x+y$  \u6216  $x+y+z$  \u3002\u5b9e\u9645\u8ba1\u7b97\u51fa\u7684\u89e3\u5728\u65e0\u7a77\u5927\u65f6\u7684\u6570\u503c\u4e3a\u96f6\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u8fd9\u4e0e\u7cbe\u786e\u89e3\u76f8\u543b\u5408\uff0c\u4e0d\u9700\u8981\u989d\u5916\u7684\u4fee\u6b63\uff0c\u4f46\u662f\u4f60\u5e94\u8be5\u6ce8\u610f\uff0c\u6211\u4eec\u4efb\u610f\u8bbe\u7f6e\u4e86 $\\phi_\\infty$ \uff0c\u800c\u6211\u4eec\u4f20\u9012\u7ed9\u7a0b\u5e8f\u7684\u7cbe\u786e\u89e3\u9700\u8981\u5728\u65e0\u7a77\u8fdc\u5904\u6709\u76f8\u540c\u7684\u503c\uff0c\u624d\u80fd\u6b63\u786e\u8ba1\u7b97\u51fa\u8bef\u5dee\u3002\n\n//  Functions::ParsedFunction \u5bf9\u8c61\u7684\u4f7f\u7528\u662f\u975e\u5e38\u76f4\u63a5\u7684\u3002 Functions::ParsedFunction::declare_parameters \u51fd\u6570\u9700\u8981\u4e00\u4e2a\u989d\u5916\u7684\u6574\u6570\u53c2\u6570\uff0c\u6307\u5b9a\u7ed9\u5b9a\u51fd\u6570\u7684\u5206\u91cf\u6570\u91cf\u3002\u5b83\u7684\u9ed8\u8ba4\u503c\u662f1\u3002\u5f53\u76f8\u5e94\u7684 Functions::ParsedFunction::parse_parameters \u65b9\u6cd5\u88ab\u8c03\u7528\u65f6\uff0c\u8c03\u7528\u5bf9\u8c61\u5fc5\u987b\u6709\u4e0e\u8fd9\u91cc\u5b9a\u4e49\u7684\u76f8\u540c\u6570\u91cf\u7684\u7ec4\u4ef6\uff0c\u5426\u5219\u4f1a\u4ea7\u751f\u5f02\u5e38\u3002\n\n// \u5728\u58f0\u660e\u6761\u76ee\u65f6\uff0c\u6211\u4eec\u540c\u65f6\u58f0\u660e\u4e86\u4e8c\u7ef4\u548c\u4e09\u7ef4\u7684\u51fd\u6570\u3002\u7136\u800c\u53ea\u6709\u4e8c\u7ef4\u7684\u6700\u7ec8\u88ab\u89e3\u6790\u3002\u8fd9\u4f7f\u5f97\u6211\u4eec\u5bf9\u4e8c\u7ef4\u548c\u4e09\u7ef4\u95ee\u9898\u90fd\u53ea\u9700\u8981\u4e00\u4e2a\u53c2\u6570\u6587\u4ef6\u3002\n\n// \u6ce8\u610f\uff0c\u4ece\u6570\u5b66\u7684\u89d2\u5ea6\u6765\u770b\uff0c\u8fb9\u754c\u4e0a\u7684\u98ce\u51fd\u6570\u5e94\u8be5\u6ee1\u8db3\u6761\u4ef6 $\\int_{\\partial\\Omega} \\mathbf{v}\\cdot \\mathbf{n} d \\Gamma = 0$  \uff0c\u8fd9\u6837\u95ee\u9898\u624d\u4f1a\u6709\u89e3\u3002\u5982\u679c\u4e0d\u6ee1\u8db3\u8fd9\u4e2a\u6761\u4ef6\uff0c\u90a3\u4e48\u5c31\u627e\u4e0d\u5230\u89e3\uff0c\u6c42\u89e3\u5668\u4e5f\u5c31\u4e0d\u4f1a\u6536\u655b\u3002\n\n    prm.enter_subsection(\"Wind function 2d\"); \n    { \n      Functions::ParsedFunction<2>::declare_parameters(prm, 2); \n      prm.set(\"Function expression\", \"1; 1\"); \n    } \n    prm.leave_subsection(); \n\n    prm.enter_subsection(\"Wind function 3d\"); \n    { \n      Functions::ParsedFunction<3>::declare_parameters(prm, 3); \n      prm.set(\"Function expression\", \"1; 1; 1\"); \n    } \n    prm.leave_subsection(); \n\n    prm.enter_subsection(\"Exact solution 2d\"); \n    { \n      Functions::ParsedFunction<2>::declare_parameters(prm); \n      prm.set(\"Function expression\", \"x+y\"); \n    } \n    prm.leave_subsection(); \n\n    prm.enter_subsection(\"Exact solution 3d\"); \n    { \n      Functions::ParsedFunction<3>::declare_parameters(prm); \n      prm.set(\"Function expression\", \"x+y+z\"); \n    } \n    prm.leave_subsection(); \n\n// \u5728\u6c42\u89e3\u5668\u90e8\u5206\uff0c\u6211\u4eec\u8bbe\u7f6e\u6240\u6709\u7684SolverControl\u53c2\u6570\u3002\u7136\u540e\uff0c\u8be5\u5bf9\u8c61\u5c06\u5728solve_system()\u51fd\u6570\u4e2d\u88ab\u9001\u5165GMRES\u6c42\u89e3\u5668\u3002\n\n    prm.enter_subsection(\"Solver\"); \n    SolverControl::declare_parameters(prm); \n    prm.leave_subsection(); \n\n// \u5728\u5411ParameterHandler\u5bf9\u8c61\u58f0\u660e\u4e86\u6240\u6709\u8fd9\u4e9b\u53c2\u6570\u540e\uff0c\u8ba9\u6211\u4eec\u8bfb\u53d6\u4e00\u4e2a\u8f93\u5165\u6587\u4ef6\uff0c\u8be5\u6587\u4ef6\u5c06\u4e3a\u8fd9\u4e9b\u53c2\u6570\u63d0\u4f9b\u5176\u503c\u3002\u7136\u540e\u6211\u4eec\u7ee7\u7eed\u4eceParameterHandler\u5bf9\u8c61\u4e2d\u63d0\u53d6\u8fd9\u4e9b\u503c\u3002\n\n    prm.parse_input(filename); \n\n    n_cycles            = prm.get_integer(\"Number of cycles\"); \n    external_refinement = prm.get_integer(\"External refinement\"); \n    extend_solution     = prm.get_bool(\"Extend solution on the -2,2 box\"); \n\n    prm.enter_subsection(\"Quadrature rules\"); \n    { \n      quadrature = std::shared_ptr<Quadrature<dim - 1>>( \n        new QuadratureSelector<dim - 1>(prm.get(\"Quadrature type\"), \n                                        prm.get_integer(\"Quadrature order\"))); \n      singular_quadrature_order = prm.get_integer(\"Singular quadrature order\"); \n    } \n    prm.leave_subsection(); \n\n    prm.enter_subsection(\"Wind function \" + std::to_string(dim) + \"d\"); \n    { \n      wind.parse_parameters(prm); \n    } \n    prm.leave_subsection(); \n\n    prm.enter_subsection(\"Exact solution \" + std::to_string(dim) + \"d\"); \n    { \n      exact_solution.parse_parameters(prm); \n    } \n    prm.leave_subsection(); \n\n    prm.enter_subsection(\"Solver\"); \n    solver_control.parse_parameters(prm); \n    prm.leave_subsection(); \n\n// \u6700\u540e\uff0c\u8fd9\u91cc\u662f\u53e6\u4e00\u4e2a\u5982\u4f55\u5728\u72ec\u7acb\u7ef4\u5ea6\u7f16\u7a0b\u4e2d\u4f7f\u7528\u53c2\u6570\u6587\u4ef6\u7684\u4f8b\u5b50\u3002 \u5982\u679c\u6211\u4eec\u60f3\u5173\u95ed\u4e24\u4e2a\u6a21\u62df\u4e2d\u7684\u4e00\u4e2a\uff0c\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u8bbe\u7f6e\u76f8\u5e94\u7684 \"\u8fd0\u884c2D\u6a21\u62df \"\u6216 \"\u8fd0\u884c3D\u6a21\u62df \"\u6807\u5fd7\u4e3a\u5047\u6765\u5b9e\u73b0\u3002\n\n    run_in_this_dimension = \n      prm.get_bool(\"Run \" + std::to_string(dim) + \"d simulation\"); \n  } \n// @sect4{BEMProblem::read_domain}  \n\n// \u8fb9\u754c\u5143\u7d20\u6cd5\u4e09\u89d2\u5256\u5206\u4e0e\uff08dim-1\uff09\u7ef4\u4e09\u89d2\u5256\u5206\u57fa\u672c\u76f8\u540c\uff0c\u4e0d\u540c\u4e4b\u5904\u5728\u4e8e\u9876\u70b9\u5c5e\u4e8e\uff08dim\uff09\u7ef4\u7a7a\u95f4\u3002\n\n// deal.II\u4e2d\u652f\u6301\u7684\u4e00\u4e9b\u7f51\u683c\u683c\u5f0f\u9ed8\u8ba4\u4f7f\u7528\u4e09\u7ef4\u70b9\u6765\u63cf\u8ff0\u7f51\u683c\u3002\u8fd9\u4e9b\u683c\u5f0f\u4e0edeal.II\u7684\u8fb9\u754c\u5143\u7d20\u65b9\u6cd5\u529f\u80fd\u517c\u5bb9\u3002\u7279\u522b\u662f\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528UCD\u6216GMSH\u683c\u5f0f\u3002\u5728\u8fd9\u4e24\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u5fc5\u987b\u7279\u522b\u6ce8\u610f\u7f51\u683c\u7684\u65b9\u5411\uff0c\u56e0\u4e3a\u4e0e\u6807\u51c6\u6709\u9650\u5143\u7684\u60c5\u51b5\u4e0d\u540c\uff0c\u8fd9\u91cc\u6ca1\u6709\u8fdb\u884c\u91cd\u65b0\u6392\u5e8f\u6216\u517c\u5bb9\u6027\u68c0\u67e5\u3002 \u6240\u6709\u7684\u7f51\u683c\u90fd\u88ab\u8ba4\u4e3a\u662f\u6709\u65b9\u5411\u6027\u7684\uff0c\u56e0\u4e3a\u5b83\u4eec\u88ab\u5d4c\u5165\u5230\u4e00\u4e2a\u9ad8\u7ef4\u7a7a\u95f4\u4e2d\u3002\u53c2\u89c1GridIn\u548cTriangulation\u7684\u6587\u6863\uff0c\u4ee5\u8fdb\u4e00\u6b65\u4e86\u89e3\u4e09\u89d2\u7ed3\u6784\u4e2d\u5355\u5143\u7684\u65b9\u5411\u3002\u5728\u6211\u4eec\u7684\u4f8b\u5b50\u4e2d\uff0c\u7f51\u683c\u7684\u6cd5\u7ebf\u662f\u5916\u5728\u4e8e2D\u7684\u5706\u62163D\u7684\u7403\u4f53\u3002\n\n// \u5bf9\u8fb9\u754c\u5143\u7d20\u7f51\u683c\u8fdb\u884c\u9002\u5f53\u7ec6\u5316\u6240\u9700\u8981\u7684\u53e6\u4e00\u4e2a\u7ec6\u8282\u662f\u5bf9\u7f51\u683c\u6240\u903c\u8fd1\u7684\u6d41\u5f62\u7684\u51c6\u786e\u63cf\u8ff0\u3002\u5bf9\u4e8e\u6807\u51c6\u6709\u9650\u5143\u7f51\u683c\u7684\u8fb9\u754c\uff0c\u6211\u4eec\u5df2\u7ecf\u591a\u6b21\u770b\u5230\u4e86\u8fd9\u4e00\u70b9\uff08\u4f8b\u5982\u5728 step-5 \u548c step-6 \u4e2d\uff09\uff0c\u8fd9\u91cc\u7684\u539f\u7406\u548c\u7528\u6cd5\u662f\u4e00\u6837\u7684\uff0c\u53ea\u662fSphericalManifold\u7c7b\u9700\u8981\u4e00\u4e2a\u989d\u5916\u7684\u6a21\u677f\u53c2\u6570\u6765\u6307\u5b9a\u5d4c\u5165\u7a7a\u95f4\u7ef4\u5ea6\u3002\n\n  template <int dim> \n  void BEMProblem<dim>::read_domain() \n  { \n    const Point<dim>                      center = Point<dim>(); \n    const SphericalManifold<dim - 1, dim> manifold(center); \n\n    std::ifstream in; \n    switch (dim) \n      { \n        case 2: \n          in.open(\"coarse_circle.inp\"); \n          break; \n\n        case 3: \n          in.open(\"coarse_sphere.inp\"); \n          break; \n\n        default: \n          Assert(false, ExcNotImplemented()); \n      } \n\n    GridIn<dim - 1, dim> gi; \n    gi.attach_triangulation(tria); \n    gi.read_ucd(in); \n\n    tria.set_all_manifold_ids(1); \n\n// \u5bf9  Triangulation::set_manifold  \u7684\u8c03\u7528\u590d\u5236\u4e86\u6d41\u5f62\uff08\u901a\u8fc7  Manifold::clone()),  \u6240\u4ee5\u6211\u4eec\u4e0d\u9700\u8981\u62c5\u5fc3\u5bf9  <code>manifold</code>  \u7684\u65e0\u6548\u6307\u9488\u3002\n\n    tria.set_manifold(1, manifold); \n  } \n// @sect4{BEMProblem::refine_and_resize}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u5bf9\u7f51\u683c\u8fdb\u884c\u5168\u5c40\u7ec6\u5316\uff0c\u5206\u914d\u81ea\u7531\u5ea6\uff0c\u5e76\u8c03\u6574\u77e9\u9635\u548c\u5411\u91cf\u7684\u5927\u5c0f\u3002\n\n  template <int dim> \n  void BEMProblem<dim>::refine_and_resize() \n  { \n    tria.refine_global(1); \n\n    dof_handler.distribute_dofs(fe); \n\n    const unsigned int n_dofs = dof_handler.n_dofs(); \n\n    system_matrix.reinit(n_dofs, n_dofs); \n\n    system_rhs.reinit(n_dofs); \n    phi.reinit(n_dofs); \n    alpha.reinit(n_dofs); \n  } \n// @sect4{BEMProblem::assemble_system}  \n\n// \u4e0b\u9762\u662f\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u8981\u529f\u80fd\uff0c\u7ec4\u88c5\u4e0e\u8fb9\u754c\u79ef\u5206\u65b9\u7a0b\u76f8\u5bf9\u5e94\u7684\u77e9\u9635\u3002\n\n  template <int dim> \n  void BEMProblem<dim>::assemble_system() \n  { \n\n// \u9996\u5148\u6211\u4eec\u7528\u6b63\u4ea4\u516c\u5f0f\u521d\u59cb\u5316\u4e00\u4e2aFEValues\u5bf9\u8c61\uff0c\u7528\u4e8e\u5728\u975e\u5947\u5f02\u5355\u5143\u4e2d\u8fdb\u884c\u5185\u6838\u79ef\u5206\u3002\u8fd9\u4e2a\u6b63\u4ea4\u516c\u5f0f\u662f\u901a\u8fc7\u53c2\u6570\u6587\u4ef6\u9009\u62e9\u7684\uff0c\u5e76\u4e14\u9700\u8981\u76f8\u5f53\u7cbe\u786e\uff0c\u56e0\u4e3a\u6211\u4eec\u8981\u79ef\u5206\u7684\u51fd\u6570\u4e0d\u662f\u591a\u9879\u5f0f\u51fd\u6570\u3002\n\n    FEValues<dim - 1, dim> fe_v(mapping, \n                                fe, \n                                *quadrature, \n                                update_values | update_normal_vectors | \n                                  update_quadrature_points | update_JxW_values); \n\n    const unsigned int n_q_points = fe_v.n_quadrature_points; \n\n    std::vector<types::global_dof_index> local_dof_indices( \n      fe.n_dofs_per_cell()); \n\n    std::vector<Vector<double>> cell_wind(n_q_points, Vector<double>(dim)); \n    double                      normal_wind; \n\n// \u4e0e\u6709\u9650\u5143\u65b9\u6cd5\u4e0d\u540c\u7684\u662f\uff0c\u5982\u679c\u6211\u4eec\u4f7f\u7528\u62fc\u5408\u8fb9\u754c\u5143\u65b9\u6cd5\uff0c\u90a3\u4e48\u5728\u6bcf\u4e2a\u88c5\u914d\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u53ea\u88c5\u914d\u4e0e\u4e00\u4e2a\u81ea\u7531\u5ea6\uff08\u4e0e\u652f\u6491\u70b9 $i$ \u76f8\u5173\u7684\u81ea\u7531\u5ea6\uff09\u548c\u5f53\u524d\u5355\u5143\u4e4b\u95f4\u7684\u8026\u5408\u4fe1\u606f\u3002\u8fd9\u662f\u7528fe.dofs_per_cell\u5143\u7d20\u7684\u5411\u91cf\u5b8c\u6210\u7684\uff0c\u7136\u540e\u5c06\u5176\u5206\u914d\u5230\u5168\u5c40\u884c\u7684\u77e9\u9635\u4e2d  $i$  \u3002\u4ee5\u4e0b\u5bf9\u8c61\u5c06\u6301\u6709\u8fd9\u4e9b\u4fe1\u606f\u3002\n\n    Vector<double> local_matrix_row_i(fe.n_dofs_per_cell()); \n\n// \u7d22\u5f15  $i$  \u8fd0\u884c\u5728\u62fc\u5408\u70b9\u4e0a\uff0c\u8fd9\u662f  $i$  \u7b2c\u4e09\u4e2a\u57fa\u51fd\u6570\u7684\u652f\u6301\u70b9\uff0c\u800c  $j$  \u8fd0\u884c\u5728\u5185\u90e8\u79ef\u5206\u70b9\u4e0a\u3002\n\n// \u6211\u4eec\u6784\u5efa\u4e00\u4e2a\u652f\u6301\u70b9\u7684\u5411\u91cf\uff0c\u5b83\u5c06\u7528\u4e8e\u5c40\u90e8\u79ef\u5206\u3002\n\n    std::vector<Point<dim>> support_points(dof_handler.n_dofs()); \n    DoFTools::map_dofs_to_support_points<dim - 1, dim>(mapping, \n                                                       dof_handler, \n                                                       support_points); \n\n// \u8fd9\u6837\u505a\u4e4b\u540e\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5f00\u59cb\u5bf9\u6240\u6709\u5355\u5143\u8fdb\u884c\u79ef\u5206\u5faa\u73af\uff0c\u9996\u5148\u521d\u59cb\u5316FEValues\u5bf9\u8c61\uff0c\u5f97\u5230\u6b63\u4ea4\u70b9\u7684 $\\mathbf{\\tilde v}$ \u7684\u503c\uff08\u8fd9\u4e2a\u5411\u91cf\u573a\u5e94\u8be5\u662f\u5e38\u6570\uff0c\u4f46\u66f4\u901a\u7528\u4e5f\u65e0\u59a8\uff09\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        fe_v.reinit(cell); \n        cell->get_dof_indices(local_dof_indices); \n\n        const std::vector<Point<dim>> &q_points = fe_v.get_quadrature_points(); \n        const std::vector<Tensor<1, dim>> &normals = fe_v.get_normal_vectors(); \n        wind.vector_value_list(q_points, cell_wind); \n\n// \u7136\u540e\u6211\u4eec\u5728\u5f53\u524d\u5355\u5143\u4e0a\u5f62\u6210\u6240\u6709\u81ea\u7531\u5ea6\u7684\u79ef\u5206\uff08\u6ce8\u610f\uff0c\u8fd9\u5305\u62ec\u4e0d\u5728\u5f53\u524d\u5355\u5143\u4e0a\u7684\u81ea\u7531\u5ea6\uff0c\u8fd9\u4e0e\u901a\u5e38\u7684\u6709\u9650\u5143\u79ef\u5206\u6709\u504f\u5dee\uff09\u3002\u5982\u679c\u5176\u4e2d\u4e00\u4e2a\u5c40\u90e8\u81ea\u7531\u5ea6\u4e0e\u652f\u6301\u70b9 $i$ \u76f8\u540c\uff0c\u6211\u4eec\u9700\u8981\u6267\u884c\u7684\u79ef\u5206\u662f\u5355\u6570\u3002\u56e0\u6b64\uff0c\u5728\u5faa\u73af\u7684\u5f00\u59cb\uff0c\u6211\u4eec\u68c0\u67e5\u662f\u5426\u662f\u8fd9\u79cd\u60c5\u51b5\uff0c\u5e76\u5b58\u50a8\u54ea\u4e00\u4e2a\u662f\u5947\u5f02\u6307\u6570\u3002\n\n        for (unsigned int i = 0; i < dof_handler.n_dofs(); ++i) \n          { \n            local_matrix_row_i = 0; \n\n            bool         is_singular    = false; \n            unsigned int singular_index = numbers::invalid_unsigned_int; \n\n            for (unsigned int j = 0; j < fe.n_dofs_per_cell(); ++j) \n              if (local_dof_indices[j] == i) \n                { \n                  singular_index = j; \n                  is_singular    = true; \n                  break; \n                } \n\n// \u7136\u540e\u6211\u4eec\u8fdb\u884c\u79ef\u5206\u3002\u5982\u679c\u6307\u6570 $i$ \u4e0d\u662f\u5c40\u90e8\u81ea\u7531\u5ea6\u4e4b\u4e00\uff0c\u6211\u4eec\u53ea\u9700\u5c06\u5355\u5c42\u9879\u52a0\u5230\u53f3\u8fb9\uff0c\u5c06\u53cc\u5c42\u9879\u52a0\u5230\u77e9\u9635\u4e2d\u3002\n\n            if (is_singular == false) \n              { \n                for (unsigned int q = 0; q < n_q_points; ++q) \n                  { \n                    normal_wind = 0; \n                    for (unsigned int d = 0; d < dim; ++d) \n                      normal_wind += normals[q][d] * cell_wind[q](d); \n\n                    const Tensor<1, dim> R = q_points[q] - support_points[i]; \n\n                    system_rhs(i) += (LaplaceKernel::single_layer(R) * \n                                      normal_wind * fe_v.JxW(q)); \n\n                    for (unsigned int j = 0; j < fe.n_dofs_per_cell(); ++j) \n\n                      local_matrix_row_i(j) -= \n                        ((LaplaceKernel::double_layer(R) * normals[q]) * \n                         fe_v.shape_value(j, q) * fe_v.JxW(q)); \n                  } \n              } \n            else \n              { \n\n// \u73b0\u5728\u6211\u4eec\u5904\u7406\u66f4\u5fae\u5999\u7684\u60c5\u51b5\u3002\u5982\u679c\u6211\u4eec\u5728\u8fd9\u91cc\uff0c\u8fd9\u610f\u5473\u7740\u5728 $j$ \u7d22\u5f15\u4e0a\u8fd0\u884c\u7684\u5355\u5143\u5305\u542bsupport_point[i]\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u5355\u5c42\u548c\u53cc\u5c42\u52bf\u90fd\u662f\u5355\u6570\uff0c\u5b83\u4eec\u9700\u8981\u7279\u6b8a\u5904\u7406\u3002            \n//\u6bcf\u5f53\u5728\u7ed9\u5b9a\u5355\u5143\u5185\u8fdb\u884c\u79ef\u5206\u65f6\uff0c\u5c31\u4f1a\u4f7f\u7528\u4e00\u4e2a\u7279\u6b8a\u7684\u6b63\u4ea4\u516c\u5f0f\uff0c\u5141\u8bb8\u4eba\u4eec\u5bf9\u53c2\u8003\u5355\u5143\u4e0a\u7684\u5947\u5f02\u6743\u91cd\u8fdb\u884c\u4efb\u610f\u51fd\u6570\u7684\u79ef\u5206\u3002            \n//\u6b63\u786e\u7684\u6b63\u4ea4\u516c\u5f0f\u7531get_singular_quadrature\u51fd\u6570\u9009\u62e9\uff0c\u4e0b\u9762\u5c06\u8be6\u7ec6\u8bf4\u660e\u3002\n\n                Assert(singular_index != numbers::invalid_unsigned_int, \n                       ExcInternalError()); \n\n                const Quadrature<dim - 1> &singular_quadrature = \n                  get_singular_quadrature(cell, singular_index); \n\n                FEValues<dim - 1, dim> fe_v_singular( \n                  mapping, \n                  fe, \n                  singular_quadrature, \n                  update_jacobians | update_values | update_normal_vectors | \n                    update_quadrature_points); \n\n                fe_v_singular.reinit(cell); \n\n                std::vector<Vector<double>> singular_cell_wind( \n                  singular_quadrature.size(), Vector<double>(dim)); \n\n                const std::vector<Tensor<1, dim>> &singular_normals = \n                  fe_v_singular.get_normal_vectors(); \n                const std::vector<Point<dim>> &singular_q_points = \n                  fe_v_singular.get_quadrature_points(); \n\n                wind.vector_value_list(singular_q_points, singular_cell_wind); \n\n                for (unsigned int q = 0; q < singular_quadrature.size(); ++q) \n                  { \n                    const Tensor<1, dim> R = \n                      singular_q_points[q] - support_points[i]; \n                    double normal_wind = 0; \n                    for (unsigned int d = 0; d < dim; ++d) \n                      normal_wind += \n                        (singular_cell_wind[q](d) * singular_normals[q][d]); \n\n                    system_rhs(i) += (LaplaceKernel::single_layer(R) * \n                                      normal_wind * fe_v_singular.JxW(q)); \n\n                    for (unsigned int j = 0; j < fe.n_dofs_per_cell(); ++j) \n                      { \n                        local_matrix_row_i(j) -= \n                          ((LaplaceKernel::double_layer(R) * \n                            singular_normals[q]) * \n                           fe_v_singular.shape_value(j, q) * \n                           fe_v_singular.JxW(q)); \n                      } \n                  } \n              } \n\n// \u6700\u540e\uff0c\u6211\u4eec\u9700\u8981\u5c06\u5f53\u524d\u5355\u5143\u683c\u7684\u8d21\u732e\u6dfb\u52a0\u5230\u5168\u5c40\u77e9\u9635\u4e2d\u3002\n\n            for (unsigned int j = 0; j < fe.n_dofs_per_cell(); ++j) \n              system_matrix(i, local_dof_indices[j]) += local_matrix_row_i(j); \n          } \n      } \n\n// \u79ef\u5206\u8fd0\u7b97\u7b26\u7684\u7b2c\u4e8c\u90e8\u5206\u662f\u672f\u8bed  $\\alpha(\\mathbf{x}_i) \\phi_j(\\mathbf{x}_i)$  \u3002\u7531\u4e8e\u6211\u4eec\u4f7f\u7528\u7684\u662f\u914d\u4f4d\u65b9\u6848\uff0c $\\phi_j(\\mathbf{x}_i)=\\delta_{ij}$  \u800c\u76f8\u5e94\u7684\u77e9\u9635\u662f\u4e00\u4e2a\u5bf9\u89d2\u7ebf\u7684\u77e9\u9635\uff0c\u5176\u6761\u76ee\u7b49\u4e8e $\\alpha(\\mathbf{x}_i)$  \u3002\n\n// \u8ba1\u7b97\u8fd9\u4e2a\u5b9e\u4f53\u89d2\u7684\u5bf9\u89d2\u77e9\u9635\u7684\u4e00\u4e2a\u5feb\u901f\u65b9\u6cd5\u662f\u4f7f\u7528\u8bfa\u4f0a\u66fc\u77e9\u9635\u672c\u8eab\u3002\u53ea\u9700\u5c06\u8be5\u77e9\u9635\u4e0e\u4e00\u4e2a\u5143\u7d20\u90fd\u7b49\u4e8e-1\u7684\u5411\u91cf\u76f8\u4e58\uff0c\u5c31\u53ef\u4ee5\u5f97\u5230\u963f\u5c14\u6cd5\u89d2\u6216\u5b9e\u4f53\u89d2\u7684\u5bf9\u89d2\u7ebf\u77e9\u9635\uff08\u89c1\u4ecb\u7ecd\u4e2d\u7684\u516c\u5f0f\uff09\u3002\u7136\u540e\u5c06\u8fd9\u4e2a\u7ed3\u679c\u52a0\u56de\u5230\u7cfb\u7edf\u77e9\u9635\u5bf9\u8c61\u4e0a\uff0c\u5f97\u5230\u77e9\u9635\u7684\u6700\u7ec8\u5f62\u5f0f\u3002\n\n    Vector<double> ones(dof_handler.n_dofs()); \n    ones.add(-1.); \n\n    system_matrix.vmult(alpha, ones); \n    alpha.add(1); \n    for (unsigned int i = 0; i < dof_handler.n_dofs(); ++i) \n      system_matrix(i, i) += alpha(i); \n  } \n// @sect4{BEMProblem::solve_system}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u7b80\u5355\u5730\u89e3\u51b3\u4e86\u7ebf\u6027\u7cfb\u7edf\u3002\n\n  template <int dim> \n  void BEMProblem<dim>::solve_system() \n  { \n    SolverGMRES<Vector<double>> solver(solver_control); \n    solver.solve(system_matrix, phi, system_rhs, PreconditionIdentity()); \n  } \n// @sect4{BEMProblem::compute_errors}  \n\n// \u8bef\u5dee\u7684\u8ba1\u7b97\u5728\u5176\u4ed6\u6240\u6709\u7684\u4f8b\u5b50\u7a0b\u5e8f\u4e2d\u90fd\u662f\u5b8c\u5168\u4e00\u6837\u7684\uff0c\u6211\u4eec\u5c31\u4e0d\u505a\u8fc7\u591a\u7684\u8bc4\u8bba\u3002\u8bf7\u6ce8\u610f\uff0c\u5728\u6709\u9650\u5143\u65b9\u6cd5\u4e2d\u4f7f\u7528\u7684\u65b9\u6cd5\u5728\u8fd9\u91cc\u4e5f\u53ef\u4ee5\u4f7f\u7528\u3002\n\n  template <int dim> \n  void BEMProblem<dim>::compute_errors(const unsigned int cycle) \n  { \n    Vector<float> difference_per_cell(tria.n_active_cells()); \n    VectorTools::integrate_difference(mapping, \n                                      dof_handler, \n                                      phi, \n                                      exact_solution, \n                                      difference_per_cell, \n                                      QGauss<(dim - 1)>(2 * fe.degree + 1), \n                                      VectorTools::L2_norm); \n    const double L2_error = \n      VectorTools::compute_global_error(tria, \n                                        difference_per_cell, \n                                        VectorTools::L2_norm); \n\n//\u53ef\u4ee5\u76f4\u63a5\u4f7f\u7528 Vector::linfty_norm() \u51fd\u6570\u6765\u8ba1\u7b97\u03b1\u5411\u91cf\u7684\u8bef\u5dee\uff0c\u56e0\u4e3a\u5728\u6bcf\u4e2a\u8282\u70b9\u4e0a\uff0c\u8be5\u503c\u5e94\u8be5\u662f $\\frac 12$  \u3002\u7136\u540e\uff0c\u6240\u6709\u7684\u8bef\u5dee\u90fd\u4f1a\u88ab\u8f93\u51fa\u5e76\u9644\u52a0\u5230\u6211\u4eec\u7684ConvergenceTable\u5bf9\u8c61\u4e2d\uff0c\u4ee5\u4fbf\u4ee5\u540e\u8ba1\u7b97\u6536\u655b\u7387\u3002\n\n    Vector<double> difference_per_node(alpha); \n    difference_per_node.add(-.5); \n\n    const double       alpha_error    = difference_per_node.linfty_norm(); \n    const unsigned int n_active_cells = tria.n_active_cells(); \n    const unsigned int n_dofs         = dof_handler.n_dofs(); \n\n    deallog << \"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(phi)\", L2_error); \n    convergence_table.add_value(\"Linfty(alpha)\", alpha_error); \n  } \n\n// \u5947\u5f02\u79ef\u5206\u9700\u8981\u4ed4\u7ec6\u9009\u62e9\u6b63\u4ea4\u89c4\u5219\u3002\u7279\u522b\u662fdeal.II\u5e93\u63d0\u4f9b\u4e86\u4e3a\u5bf9\u6570\u5947\u5f02\u6027\uff08QGaussLog, QGaussLogR\uff09\u4ee5\u53ca1/R\u5947\u5f02\u6027\uff08QGaussOneOverR\uff09\u91cf\u8eab\u5b9a\u5236\u7684\u6b63\u4ea4\u89c4\u5219\u3002\n\n// \u5947\u5f02\u79ef\u5206\u901a\u5e38\u662f\u901a\u8fc7\u6784\u5efa\u5177\u6709\u5947\u5f02\u6743\u91cd\u7684\u52a0\u6743\u6b63\u4ea4\u516c\u5f0f\u5f97\u5230\u7684\uff0c\u56e0\u6b64\u53ef\u4ee5\u5199\u6210\n\n// \\f[ \\int_K f(x) s(x) dx = \\sum_{i=1}^N w_i f(q_i) \\f]\n\n// \u5176\u4e2d $s(x)$ \u662f\u4e00\u4e2a\u7ed9\u5b9a\u7684\u5947\u70b9\uff0c\u6743\u91cd\u548c\u6b63\u4ea4\u70b9 $w_i,q_i$ \u662f\u7cbe\u5fc3\u9009\u62e9\u7684\uff0c\u4ee5\u4f7f\u4e0a\u8ff0\u516c\u5f0f\u5bf9\u67d0\u7c7b\u51fd\u6570 $f(x)$ \u662f\u4e00\u4e2a\u7b49\u5f0f\u3002\n\n// \u5728\u6211\u4eec\u76ee\u524d\u770b\u5230\u7684\u6240\u6709\u6709\u9650\u5143\u4f8b\u5b50\u4e2d\uff0c\u6b63\u4ea4\u70b9\u672c\u8eab\u7684\u6743\u91cd\uff08\u5373\u51fd\u6570  $s(x)$  \uff09\uff0c\u603b\u662f\u4e0d\u65ad\u5730\u7b49\u4e8e1\u3002 \u5bf9\u4e8e\u5947\u5f02\u79ef\u5206\uff0c\u6211\u4eec\u6709\u4e24\u4e2a\u9009\u62e9\uff1a\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528\u4e0a\u9762\u7684\u5b9a\u4e49\uff0c\u4ece\u79ef\u5206\u4e2d\u5254\u9664\u5947\u5f02\u6027\uff08\u5373\u7528\u7279\u6b8a\u7684\u6b63\u4ea4\u89c4\u5219\u5bf9 $f(x)$ \u8fdb\u884c\u79ef\u5206\uff09\uff0c\u6216\u8005\u6211\u4eec\u53ef\u4ee5\u8981\u6c42\u6b63\u4ea4\u89c4\u5219\u7528 $s(q_i)$ \u5bf9\u6743\u91cd $w_i$ \u8fdb\u884c \"\u6807\u51c6\u5316\"\u3002\n\n// \\f[ \\int_K f(x) s(x) dx = \\int_K g(x) dx = \\sum_{i=1}^N \\frac{w_i}{s(q_i)} g(q_i) \\f]\n\n// \u6211\u4eec\u901a\u8fc7QGaussLogR\u548cQGaussOneOverR\u7684 @p factor_out_singularity \u53c2\u6570\u6765\u4f7f\u7528\u8fd9\u7b2c\u4e8c\u79cd\u9009\u62e9\u3002\n\n// \u8fd9\u4e9b\u79ef\u5206\u6709\u4e9b\u5fae\u5999\uff0c\u7279\u522b\u662f\u5728\u4e8c\u7ef4\u7a7a\u95f4\uff0c\u7531\u4e8e\u4ece\u5b9e\u6570\u5230\u53c2\u8003\u5355\u5143\u7684\u8f6c\u6362\uff0c\u79ef\u5206\u7684\u53d8\u91cf\u662f\u4ee5\u8f6c\u6362\u7684\u884c\u5217\u5f0f\u4e3a\u5c3a\u5ea6\u7684\u3002\n\n// \u5728\u4e8c\u7ef4\u7a7a\u95f4\u4e2d\uff0c\u8fd9\u4e2a\u8fc7\u7a0b\u4e0d\u4ec5\u4f1a\u5bfc\u81f4\u4e00\u4e2a\u56e0\u5b50\u4f5c\u4e3a\u5e38\u6570\u51fa\u73b0\u5728\u6574\u4e2a\u79ef\u5206\u4e0a\uff0c\u800c\u4e14\u8fd8\u4f1a\u5bfc\u81f4\u4e00\u4e2a\u9700\u8981\u8bc4\u4f30\u7684\u989d\u5916\u79ef\u5206\u3002\n\n// \\f[ \\int_0^1 f(x)\\ln(x/\\alpha) dx = \\int_0^1 f(x)\\ln(x) dx - \\int_0^1  f(x) \\ln(\\alpha) dx.  \\f]\n\n// \u8fd9\u4e2a\u8fc7\u7a0b\u7531QGaussLogR\u7c7b\u7684\u6784\u9020\u51fd\u6570\u6765\u5904\u7406\uff0c\u5b83\u589e\u52a0\u4e86\u989d\u5916\u7684\u6b63\u4ea4\u70b9\u548c\u6743\u91cd\uff0c\u4ee5\u8003\u8651\u5230\u79ef\u5206\u7684\u7b2c\u4e8c\u90e8\u5206\u3002\n\n// \u7c7b\u4f3c\u7684\u63a8\u7406\u5e94\u8be5\u5728\u4e09\u7ef4\u60c5\u51b5\u4e0b\u8fdb\u884c\uff0c\u56e0\u4e3a\u5947\u5f02\u6b63\u4ea4\u662f\u5728\u53c2\u8003\u5355\u5143\u7684\u534a\u5f84 $r$ \u7684\u9006\u4e0a\u5b9a\u5236\u7684\uff0c\u800c\u6211\u4eec\u7684\u5947\u5f02\u51fd\u6570\u751f\u6d3b\u5728\u5b9e\u7a7a\u95f4\uff0c\u7136\u800c\u5728\u4e09\u7ef4\u60c5\u51b5\u4e0b\u4e00\u5207\u90fd\u66f4\u7b80\u5355\uff0c\u56e0\u4e3a\u5947\u5f02\u6027\u4e0e\u53d8\u6362\u7684\u884c\u5217\u5f0f\u6210\u7ebf\u6027\u6bd4\u4f8b\u3002\u8fd9\u4f7f\u6211\u4eec\u53ef\u4ee5\u53ea\u5efa\u7acb\u4e00\u6b21\u5947\u5f02\u7684\u4e8c\u7ef4\u6b63\u4ea4\u89c4\u5219\uff0c\u5e76\u5728\u6240\u6709\u5355\u5143\u683c\u4e2d\u91cd\u590d\u4f7f\u7528\u3002\n\n// \u5728\u4e00\u7ef4\u7684\u5947\u5f02\u79ef\u5206\u4e2d\uff0c\u8fd9\u662f\u4e0d\u53ef\u80fd\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u9700\u8981\u77e5\u9053\u6b63\u4ea4\u7684\u7f29\u653e\u53c2\u6570\uff0c\u800c\u8fd9\u4e2a\u53c2\u6570\u5e76\u4e0d\u662f\u5148\u9a8c\u7684\u3002\u8fd9\u91cc\uff0c\u6b63\u4ea4\u89c4\u5219\u672c\u8eab\u4e5f\u53d6\u51b3\u4e8e\u5f53\u524d\u5355\u5143\u683c\u7684\u5927\u5c0f\u3002\u51fa\u4e8e\u8fd9\u4e2a\u539f\u56e0\uff0c\u6709\u5fc5\u8981\u4e3a\u6bcf\u4e2a\u5355\u6570\u79ef\u5206\u521b\u5efa\u4e00\u4e2a\u65b0\u7684\u6b63\u4ea4\u3002\n\n// \u4e0d\u540c\u7684\u6b63\u4ea4\u89c4\u5219\u662f\u5728get_singular_quadrature\u4e2d\u5efa\u7acb\u7684\uff0c\u5b83\u4e13\u95e8\u7528\u4e8edim=2\u548cdim=3\uff0c\u5b83\u4eec\u5728assemble_system\u51fd\u6570\u4e2d\u88ab\u68c0\u7d22\u3002\u4f5c\u4e3a\u53c2\u6570\u7ed9\u51fa\u7684\u7d22\u5f15\u662f\u5947\u5f02\u70b9\u6240\u5728\u7684\u5355\u4f4d\u652f\u6301\u70b9\u7684\u7d22\u5f15\u3002\n\n  template <> \n  const Quadrature<2> &BEMProblem<3>::get_singular_quadrature( \n    const DoFHandler<2, 3>::active_cell_iterator &, \n    const unsigned int index) const \n  { \n    Assert(index < fe.n_dofs_per_cell(), \n           ExcIndexRange(0, fe.n_dofs_per_cell(), index)); \n\n    static std::vector<QGaussOneOverR<2>> quadratures; \n    if (quadratures.size() == 0) \n      for (unsigned int i = 0; i < fe.n_dofs_per_cell(); ++i) \n        quadratures.emplace_back(singular_quadrature_order, \n                                 fe.get_unit_support_points()[i], \n                                 true); \n    return quadratures[index]; \n  } \n\n  template <> \n  const Quadrature<1> &BEMProblem<2>::get_singular_quadrature( \n    const DoFHandler<1, 2>::active_cell_iterator &cell, \n    const unsigned int                            index) const \n  { \n    Assert(index < fe.n_dofs_per_cell(), \n           ExcIndexRange(0, fe.n_dofs_per_cell(), index)); \n\n    static Quadrature<1> *q_pointer = nullptr; \n    if (q_pointer) \n      delete q_pointer; \n\n    q_pointer = new QGaussLogR<1>(singular_quadrature_order, \n                                  fe.get_unit_support_points()[index], \n                                  1. / cell->measure(), \n                                  true); \n    return (*q_pointer); \n  } \n\n//  @sect4{BEMProblem::compute_exterior_solution}  \n\n// \u6211\u4eec\u8fd8\u60f3\u77e5\u9053\u4e00\u4e9b\u5173\u4e8e\u5916\u57df\u4e2d\u7535\u52bf $\\phi$ \u7684\u503c\uff1a\u6bd5\u7adf\u6211\u4eec\u8003\u8651\u8fb9\u754c\u79ef\u5206\u95ee\u9898\u7684\u52a8\u673a\u662f\u60f3\u77e5\u9053\u5916\u57df\u4e2d\u7684\u901f\u5ea6!\n\n// \u4e3a\u6b64\uff0c\u6211\u4eec\u5728\u6b64\u5047\u8bbe\u8fb9\u754c\u5143\u7d20\u57df\u5305\u542b\u5728\u76d2\u5b50 $[-2,2]^{\\text{dim}}$ \u4e2d\uff0c\u6211\u4eec\u7528\u4e0e\u57fa\u672c\u89e3\u7684\u5377\u79ef\u6765\u63a8\u7b97\u8fd9\u4e2a\u76d2\u5b50\u5185\u7684\u5b9e\u9645\u89e3\u3002\u8fd9\u65b9\u9762\u7684\u516c\u5f0f\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u7ed9\u51fa\u3002\n\n// \u6574\u4e2a\u7a7a\u95f4\u7684\u89e3\u7684\u91cd\u5efa\u662f\u5728\u4e00\u4e2a\u8fde\u7eed\u7684\u3001\u5c3a\u5bf8\u4e3adim\u7684\u6709\u9650\u5143\u7f51\u683c\u4e0a\u5b8c\u6210\u7684\u3002\u8fd9\u4e9b\u90fd\u662f\u5e38\u7528\u7684\uff0c\u6211\u4eec\u4e0d\u505a\u8fdb\u4e00\u6b65\u8bc4\u8bba\u3002\u5728\u51fd\u6570\u7684\u6700\u540e\uff0c\u6211\u4eec\u518d\u6b21\u4ee5\u901a\u5e38\u7684\u65b9\u5f0f\u8f93\u51fa\u8fd9\u4e2a\u5916\u90e8\u89e3\u3002\n\n  template <int dim> \n  void BEMProblem<dim>::compute_exterior_solution() \n  { \n    Triangulation<dim> external_tria; \n    GridGenerator::hyper_cube(external_tria, -2, 2); \n\n    FE_Q<dim>       external_fe(1); \n    DoFHandler<dim> external_dh(external_tria); \n    Vector<double>  external_phi; \n\n    external_tria.refine_global(external_refinement); \n    external_dh.distribute_dofs(external_fe); \n    external_phi.reinit(external_dh.n_dofs()); \n\n    FEValues<dim - 1, dim> fe_v(mapping, \n                                fe, \n                                *quadrature, \n                                update_values | update_normal_vectors | \n                                  update_quadrature_points | update_JxW_values); \n\n    const unsigned int n_q_points = fe_v.n_quadrature_points; \n\n    std::vector<types::global_dof_index> dofs(fe.n_dofs_per_cell()); \n\n    std::vector<double>         local_phi(n_q_points); \n    std::vector<double>         normal_wind(n_q_points); \n    std::vector<Vector<double>> local_wind(n_q_points, Vector<double>(dim)); \n\n    std::vector<Point<dim>> external_support_points(external_dh.n_dofs()); \n    DoFTools::map_dofs_to_support_points<dim>(StaticMappingQ1<dim>::mapping, \n                                              external_dh, \n                                              external_support_points); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        fe_v.reinit(cell); \n\n        const std::vector<Point<dim>> &q_points = fe_v.get_quadrature_points(); \n        const std::vector<Tensor<1, dim>> &normals = fe_v.get_normal_vectors(); \n\n        cell->get_dof_indices(dofs); \n        fe_v.get_function_values(phi, local_phi); \n\n        wind.vector_value_list(q_points, local_wind); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            normal_wind[q] = 0; \n            for (unsigned int d = 0; d < dim; ++d) \n              normal_wind[q] += normals[q][d] * local_wind[q](d); \n          } \n\n        for (unsigned int i = 0; i < external_dh.n_dofs(); ++i) \n          for (unsigned int q = 0; q < n_q_points; ++q) \n            { \n              const Tensor<1, dim> R = q_points[q] - external_support_points[i]; \n\n              external_phi(i) += \n                ((LaplaceKernel::single_layer(R) * normal_wind[q] + \n                  (LaplaceKernel::double_layer(R) * normals[q]) * \n                    local_phi[q]) * \n                 fe_v.JxW(q)); \n            } \n      } \n\n    DataOut<dim> data_out; \n\n    data_out.attach_dof_handler(external_dh); \n    data_out.add_data_vector(external_phi, \"external_phi\"); \n    data_out.build_patches(); \n\n    const std::string filename = std::to_string(dim) + \"d_external.vtk\"; \n    std::ofstream     file(filename); \n\n \n  } \n// @sect4{BEMProblem::output_results}  \n\n// \u8f93\u51fa\u6211\u4eec\u7684\u8ba1\u7b97\u7ed3\u679c\u662f\u4e00\u4e2a\u76f8\u5f53\u673a\u68b0\u7684\u4efb\u52a1\u3002\u8fd9\u4e2a\u51fd\u6570\u7684\u6240\u6709\u7ec4\u6210\u90e8\u5206\u4e4b\u524d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u4e86\u3002\n\n  template <int dim> \n  void BEMProblem<dim>::output_results(const unsigned int cycle) \n  { \n    DataOut<dim - 1, dim> dataout; \n\n    dataout.attach_dof_handler(dof_handler); \n    dataout.add_data_vector(phi, \"phi\", DataOut<dim - 1, dim>::type_dof_data); \n    dataout.add_data_vector(alpha, \n                            \"alpha\", \n                            DataOut<dim - 1, dim>::type_dof_data); \n    dataout.build_patches(mapping, \n                          mapping.get_degree(), \n                          DataOut<dim - 1, dim>::curved_inner_cells); \n\n    const std::string filename = std::to_string(dim) + \"d_boundary_solution_\" + \n                                 std::to_string(cycle) + \".vtk\"; \n    std::ofstream file(filename); \n\n    dataout.write_vtk(file); \n\n    if (cycle == n_cycles - 1) \n      { \n        convergence_table.set_precision(\"L2(phi)\", 3); \n        convergence_table.set_precision(\"Linfty(alpha)\", 3); \n\n        convergence_table.set_scientific(\"L2(phi)\", true); \n        convergence_table.set_scientific(\"Linfty(alpha)\", true); \n\n        convergence_table.evaluate_convergence_rates(\n          \"L2(phi)\", ConvergenceTable::reduction_rate_log2); \n        convergence_table.evaluate_convergence_rates( \n          \"Linfty(alpha)\", ConvergenceTable::reduction_rate_log2); \n        deallog << std::endl; \n        convergence_table.write_text(std::cout); \n      } \n  } \n// @sect4{BEMProblem::run}  \n\n// \u8fd9\u662f\u6700\u4e3b\u8981\u7684\u529f\u80fd\u3002\u5b83\u5e94\u8be5\u662f\u4e0d\u8a00\u81ea\u660e\u7684\u3002\n\n  template <int dim> \n  void BEMProblem<dim>::run() \n  { \n    read_parameters(\"parameters.prm\"); \n\n    if (run_in_this_dimension == false) \n      { \n        deallog << \"Run in dimension \" << dim \n                << \" explicitly disabled in parameter file. \" << std::endl; \n        return; \n      } \n\n    read_domain(); \n\n    for (unsigned int cycle = 0; cycle < n_cycles; ++cycle) \n      { \n        refine_and_resize(); \n        assemble_system(); \n        solve_system(); \n        compute_errors(cycle); \n        output_results(cycle); \n      } \n\n    if (extend_solution == true) \n      compute_exterior_solution(); \n  } \n} // namespace Step34 \n// @sect3{The main() function}  \n\n// \u8fd9\u662f\u672c\u7a0b\u5e8f\u7684\u4e3b\u8981\u529f\u80fd\u3002\u5b83\u4e0e\u4ee5\u524d\u6240\u6709\u7684\u6559\u7a0b\u7a0b\u5e8f\u5b8c\u5168\u4e00\u6837\u3002\n\nint main() \n{ \n  try \n    { \n      using namespace Step34; \n\n      const unsigned int degree         = 1; \n      const unsigned int mapping_degree = 1; \n\n      deallog.depth_console(3); \n      BEMProblem<2> laplace_problem_2d(degree, mapping_degree); \n      laplace_problem_2d.run(); \n\n      BEMProblem<3> laplace_problem_3d(degree, mapping_degree); \n      laplace_problem_3d.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\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\n\n", "meta": {"hexsha": "43640410f9135a4e270c8a3661c1782b047590bc", "size": 30503, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-34/step-34.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-34/step-34.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-34/step-34.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.6625, "max_line_length": 265, "alphanum_fraction": 0.6124315641, "num_tokens": 11427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5108132510189005}}
{"text": "#define BOOST_TEST_MODULE lue framework core domain_decomposition\n#include <hpx/config.hpp>\n#include <boost/test/unit_test.hpp>\n#include \"lue/framework/core/domain_decomposition.hpp\"\n#include \"lue/framework/test/stream.hpp\"\n\n\nBOOST_AUTO_TEST_CASE(nr_2d_partitions)\n{\n    using Index = std::uint64_t;\n    std::size_t const rank = 2;\n    using Shape = lue::Shape<Index, rank>;\n\n    Shape area_shape{6, 4};\n\n    {\n        Shape partition_shape{1, 1};\n        auto nr_partitions = lue::nr_partitions(area_shape, partition_shape);\n        BOOST_CHECK_EQUAL(nr_partitions, 24);\n    }\n\n    {\n        Shape partition_shape{2, 2};\n        auto nr_partitions = lue::nr_partitions(area_shape, partition_shape);\n        BOOST_CHECK_EQUAL(nr_partitions, 6);\n    }\n\n    {\n        Shape partition_shape{3, 3};\n        auto nr_partitions = lue::nr_partitions(area_shape, partition_shape);\n        BOOST_CHECK_EQUAL(nr_partitions, 4);\n    }\n\n    {\n        Shape partition_shape{4, 4};\n        auto nr_partitions = lue::nr_partitions(area_shape, partition_shape);\n        BOOST_CHECK_EQUAL(nr_partitions, 2);\n    }\n\n    {\n        Shape partition_shape{5, 5};\n        auto nr_partitions = lue::nr_partitions(area_shape, partition_shape);\n        BOOST_CHECK_EQUAL(nr_partitions, 2);\n    }\n\n    {\n        Shape partition_shape{10, 10};\n        auto nr_partitions = lue::nr_partitions(area_shape, partition_shape);\n        BOOST_CHECK_EQUAL(nr_partitions, 1);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(linear_to_1d_shape_index)\n{\n    using Index = std::uint64_t;\n    std::size_t const rank = 1;\n    using Shape = lue::Shape<Index, rank>;\n    using Indices = lue::Indices<Index, rank>;\n\n    Shape area_shape{10};\n    Index index;\n\n    {\n        index = 0;\n        auto indices = lue::linear_to_shape_index(area_shape, index);\n        BOOST_CHECK(indices == (Indices{0}));\n    }\n\n    {\n        index = 5;\n        auto indices = lue::linear_to_shape_index(area_shape, index);\n        BOOST_CHECK(indices == (Indices{5}));\n    }\n\n    {\n        index = 9;\n        auto indices = lue::linear_to_shape_index(area_shape, index);\n        BOOST_CHECK(indices == (Indices{9}));\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(linear_to_2d_shape_index)\n{\n    using Index = std::uint64_t;\n    std::size_t const rank = 2;\n    using Shape = lue::Shape<Index, rank>;\n    using Indices = lue::Indices<Index, rank>;\n\n    Shape area_shape{6, 4};\n    Index index;\n\n    {\n        index = 0;\n        auto indices = lue::linear_to_shape_index(area_shape, index);\n        BOOST_CHECK(indices == (Indices{0, 0}));\n    }\n\n    {\n        index = 3;\n        auto indices = lue::linear_to_shape_index(area_shape, index);\n        BOOST_CHECK(indices == (Indices{0, 3}));\n    }\n\n    {\n        index = 4;\n        auto indices = lue::linear_to_shape_index(area_shape, index);\n        BOOST_CHECK(indices == (Indices{1, 0}));\n    }\n\n    {\n        index = 23;\n        auto indices = lue::linear_to_shape_index(area_shape, index);\n        BOOST_CHECK(indices == (Indices{5, 3}));\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(linear_to_3d_shape_index)\n{\n    using Index = std::uint64_t;\n    std::size_t const rank = 3;\n    using Shape = lue::Shape<Index, rank>;\n    using Indices = lue::Indices<Index, rank>;\n\n    Shape area_shape{2, 6, 4};\n    Index index;\n\n    {\n        index = 0;\n        auto indices = lue::linear_to_shape_index(area_shape, index);\n        BOOST_CHECK(indices == (Indices{0, 0, 0}));\n    }\n\n    {\n        index = 47;\n        auto indices = lue::linear_to_shape_index(area_shape, index);\n        BOOST_CHECK(indices == (Indices{1, 5, 3}));\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(clamp_area_shape)\n{\n    using Index = std::uint64_t;\n    std::size_t const rank = 2;\n    using Shape = lue::Shape<Index, rank>;\n\n    Shape area_shape{6, 4};\n\n    {\n        Shape partition_shape{1, 1};\n        auto shape = lue::clamp_area_shape(area_shape, partition_shape);\n        BOOST_CHECK(shape == (Shape{6, 4}));\n    }\n\n    {\n        Shape partition_shape{2, 2};\n        auto shape = lue::clamp_area_shape(area_shape, partition_shape);\n        BOOST_CHECK(shape == (Shape{6, 4}));\n    }\n\n    {\n        Shape partition_shape{3, 3};\n        auto shape = lue::clamp_area_shape(area_shape, partition_shape);\n        BOOST_CHECK(shape == (Shape{6, 6}));\n    }\n\n    {\n        Shape partition_shape{4, 4};\n        auto shape = lue::clamp_area_shape(area_shape, partition_shape);\n        BOOST_CHECK(shape == (Shape{8, 4}));\n    }\n\n    {\n        Shape partition_shape{5, 5};\n        auto shape = lue::clamp_area_shape(area_shape, partition_shape);\n        BOOST_CHECK(shape == (Shape{10, 5}));\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(shape_in_partitions)\n{\n    using Index = std::uint64_t;\n    std::size_t const rank = 2;\n    using Shape = lue::Shape<Index, rank>;\n\n    Shape area_shape{6, 4};\n\n    {\n        Shape partition_shape{1, 1};\n        auto shape = lue::shape_in_partitions(area_shape, partition_shape);\n        BOOST_CHECK(shape == (Shape{6, 4}));\n    }\n\n    {\n        Shape partition_shape{2, 2};\n        auto shape = lue::shape_in_partitions(area_shape, partition_shape);\n        BOOST_CHECK(shape == (Shape{3, 2}));\n    }\n\n    {\n        Shape partition_shape{3, 3};\n        auto shape = lue::shape_in_partitions(area_shape, partition_shape);\n        BOOST_CHECK(shape == (Shape{2, 2}));\n    }\n\n    {\n        Shape partition_shape{4, 4};\n        auto shape = lue::shape_in_partitions(area_shape, partition_shape);\n        BOOST_CHECK(shape == (Shape{2, 1}));\n    }\n\n    {\n        Shape partition_shape{5, 5};\n        auto shape = lue::shape_in_partitions(area_shape, partition_shape);\n        BOOST_CHECK(shape == (Shape{2, 1}));\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(partitions)\n{\n    using Index = std::uint64_t;\n    std::size_t const rank = 2;\n    using Partition = lue::ArrayPartitionDefinition<Index, rank>;\n    using Start = typename Partition::Start;\n    using Shape = typename Partition::Shape;\n\n    {\n        Shape area_shape{6, 4};\n        Shape partition_shape{6, 4};\n\n        std::size_t nr_localities = 2;\n        std::uint32_t locality_id = 0;\n\n        auto partitions = lue::partitions(\n            area_shape, partition_shape, nr_localities, locality_id);\n\n        BOOST_REQUIRE_EQUAL(partitions.size(), 1);\n        BOOST_CHECK(partitions[0] == Partition{partition_shape});\n\n        locality_id = 1;\n        partitions = lue::partitions(\n            area_shape, partition_shape, nr_localities, locality_id);\n\n        BOOST_REQUIRE_EQUAL(partitions.size(), 0);\n    }\n\n    {\n        // Grains fit perfectly in area\n        Shape area_shape{60, 40};\n        Shape partition_shape{10, 10};\n\n        std::size_t nr_localities = 6;\n\n        std::uint32_t locality_id = 0;\n        auto partitions = lue::partitions(\n            area_shape, partition_shape, nr_localities, locality_id);\n\n        BOOST_REQUIRE_EQUAL(partitions.size(), 4);\n        BOOST_CHECK(partitions[0] == (Partition{Start{0,  0}, Shape{10, 10}}));\n        BOOST_CHECK(partitions[1] == (Partition{Start{0, 10}, Shape{10, 10}}));\n        BOOST_CHECK(partitions[2] == (Partition{Start{0, 20}, Shape{10, 10}}));\n        BOOST_CHECK(partitions[3] == (Partition{Start{0, 30}, Shape{10, 10}}));\n\n        locality_id = 5;\n        partitions = lue::partitions(\n            area_shape, partition_shape, nr_localities, locality_id);\n\n        BOOST_REQUIRE_EQUAL(partitions.size(), 4);\n        BOOST_CHECK(partitions[0] == (Partition{Start{50,  0}, Shape{10, 10}}));\n        BOOST_CHECK(partitions[1] == (Partition{Start{50, 10}, Shape{10, 10}}));\n        BOOST_CHECK(partitions[2] == (Partition{Start{50, 20}, Shape{10, 10}}));\n        BOOST_CHECK(partitions[3] == (Partition{Start{50, 30}, Shape{10, 10}}));\n    }\n\n    {\n        // Grains don't fit perfectly in area\n        Shape area_shape{60, 40};\n        Shape partition_shape{9, 9};\n\n        std::size_t nr_localities = 6;\n\n        std::uint32_t locality_id = 0;\n        auto partitions = lue::partitions(\n            area_shape, partition_shape, nr_localities, locality_id);\n\n        BOOST_REQUIRE_EQUAL(partitions.size(), 6);\n        BOOST_CHECK(partitions[0] == (Partition{Start{0,  0}, Shape{9, 9}}));\n        BOOST_CHECK(partitions[1] == (Partition{Start{0,  9}, Shape{9, 9}}));\n        BOOST_CHECK(partitions[2] == (Partition{Start{0, 18}, Shape{9, 9}}));\n        BOOST_CHECK(partitions[3] == (Partition{Start{0, 27}, Shape{9, 9}}));\n        BOOST_CHECK(partitions[4] == (Partition{Start{0, 36}, Shape{9, 4}}));\n        BOOST_CHECK(partitions[5] == (Partition{Start{9,  0}, Shape{9, 9}}));\n\n        locality_id = 4;\n        partitions = lue::partitions(\n            area_shape, partition_shape, nr_localities, locality_id);\n\n        BOOST_REQUIRE_EQUAL(partitions.size(), 6);\n        BOOST_CHECK(partitions[0] == (Partition{Start{36, 36}, Shape{9, 4}}));\n        BOOST_CHECK(partitions[1] == (Partition{Start{45,  0}, Shape{9, 9}}));\n        BOOST_CHECK(partitions[2] == (Partition{Start{45,  9}, Shape{9, 9}}));\n        BOOST_CHECK(partitions[3] == (Partition{Start{45, 18}, Shape{9, 9}}));\n        BOOST_CHECK(partitions[4] == (Partition{Start{45, 27}, Shape{9, 9}}));\n        BOOST_CHECK(partitions[5] == (Partition{Start{45, 36}, Shape{9, 4}}));\n\n        locality_id = 5;\n        partitions = lue::partitions(\n            area_shape, partition_shape, nr_localities, locality_id);\n\n        BOOST_REQUIRE_EQUAL(partitions.size(), 5);\n        BOOST_CHECK(partitions[0] == (Partition{Start{54,  0}, Shape{6, 9}}));\n        BOOST_CHECK(partitions[1] == (Partition{Start{54,  9}, Shape{6, 9}}));\n        BOOST_CHECK(partitions[2] == (Partition{Start{54, 18}, Shape{6, 9}}));\n        BOOST_CHECK(partitions[3] == (Partition{Start{54, 27}, Shape{6, 9}}));\n        BOOST_CHECK(partitions[4] == (Partition{Start{54, 36}, Shape{6, 4}}));\n    }\n\n    {\n        // Grains don't fit perfectly in area\n        Shape area_shape{60, 40};\n        Shape partition_shape{11, 11};\n\n        std::size_t nr_localities = 6;\n\n        std::uint32_t locality_id = 0;\n        auto partitions = lue::partitions(\n            area_shape, partition_shape, nr_localities, locality_id);\n\n        BOOST_REQUIRE_EQUAL(partitions.size(), 4);\n        BOOST_CHECK(partitions[0] == (Partition{Start{0,  0}, Shape{11, 11}}));\n        BOOST_CHECK(partitions[1] == (Partition{Start{0, 11}, Shape{11, 11}}));\n        BOOST_CHECK(partitions[2] == (Partition{Start{0, 22}, Shape{11, 11}}));\n        BOOST_CHECK(partitions[3] == (Partition{Start{0, 33}, Shape{11,  7}}));\n\n        locality_id = 5;\n        partitions = lue::partitions(\n            area_shape, partition_shape, nr_localities, locality_id);\n\n        BOOST_REQUIRE_EQUAL(partitions.size(), 4);\n        BOOST_CHECK(partitions[0] == (Partition{Start{55,  0}, Shape{5, 11}}));\n        BOOST_CHECK(partitions[1] == (Partition{Start{55, 11}, Shape{5, 11}}));\n        BOOST_CHECK(partitions[2] == (Partition{Start{55, 22}, Shape{5, 11}}));\n        BOOST_CHECK(partitions[3] == (Partition{Start{55, 33}, Shape{5,  7}}));\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(max_partition_shape_1d)\n{\n    using Shape = lue::Shape<std::uint32_t, 1>;\n\n    {\n        Shape const shape{10};\n        Shape const shape_we_got = lue::max_partition_shape(shape, 1u);\n        Shape const shape_we_want = Shape{10};\n\n        BOOST_CHECK_EQUAL(shape_we_got, shape_we_want);\n    }\n\n    {\n        Shape const shape{10};\n        Shape const shape_we_got = lue::max_partition_shape(shape, 2u);\n        Shape const shape_we_want = Shape{5};\n\n        BOOST_CHECK_EQUAL(shape_we_got, shape_we_want);\n    }\n\n    {\n        Shape const shape{10};\n        Shape const shape_we_got = lue::max_partition_shape(shape, 3u);\n        Shape const shape_we_want = Shape{3};\n\n        BOOST_CHECK_EQUAL(shape_we_got, shape_we_want);\n    }\n\n    {\n        Shape const shape{10};\n        Shape const shape_we_got = lue::max_partition_shape(shape, 4u);\n        Shape const shape_we_want = Shape{2};\n\n        BOOST_CHECK_EQUAL(shape_we_got, shape_we_want);\n    }\n\n    {\n        Shape const shape{10};\n        Shape const shape_we_got = lue::max_partition_shape(shape, 5u);\n        Shape const shape_we_want = Shape{2};\n\n        BOOST_CHECK_EQUAL(shape_we_got, shape_we_want);\n    }\n\n    {\n        Shape const shape{10};\n        Shape const shape_we_got = lue::max_partition_shape(shape, 6u);\n        Shape const shape_we_want = Shape{1};\n\n        BOOST_CHECK_EQUAL(shape_we_got, shape_we_want);\n    }\n\n    {\n        Shape const shape{10};\n        Shape const shape_we_got = lue::max_partition_shape(shape, 10u);\n        Shape const shape_we_want = Shape{1};\n\n        BOOST_CHECK_EQUAL(shape_we_got, shape_we_want);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(max_partition_shape_2d)\n{\n    using Shape = lue::Shape<std::uint32_t, 2>;\n\n    {\n        Shape const shape{10, 10};\n        Shape const shape_we_got = lue::max_partition_shape(shape, 1u);\n        Shape const shape_we_want = Shape{10, 10};\n\n        BOOST_CHECK_EQUAL(shape_we_got, shape_we_want);\n    }\n\n    {\n        Shape const shape{10, 10};\n        Shape const shape_we_got = lue::max_partition_shape(shape, 2u);\n        Shape const shape_we_want = Shape{5, 10};\n\n        BOOST_CHECK_EQUAL(shape_we_got, shape_we_want);\n    }\n\n    {\n        Shape const shape{10, 10};\n        Shape const shape_we_got = lue::max_partition_shape(shape, 3u);\n        Shape const shape_we_want = Shape{5, 5};\n\n        BOOST_CHECK_EQUAL(shape_we_got, shape_we_want);\n    }\n\n    {\n        Shape const shape{10, 10};\n        Shape const shape_we_got = lue::max_partition_shape(shape, 4u);\n        Shape const shape_we_want = Shape{5, 5};\n\n        BOOST_CHECK_EQUAL(shape_we_got, shape_we_want);\n    }\n\n    {\n        Shape const shape{10, 10};\n        Shape const shape_we_got = lue::max_partition_shape(shape, 25u);\n        Shape const shape_we_want = Shape{2, 2};\n\n        BOOST_CHECK_EQUAL(shape_we_got, shape_we_want);\n    }\n\n    {\n        Shape const shape{10, 10};\n        Shape const shape_we_got = lue::max_partition_shape(shape, 100u);\n        Shape const shape_we_want = Shape{1, 1};\n\n        BOOST_CHECK_EQUAL(shape_we_got, shape_we_want);\n    }\n}\n", "meta": {"hexsha": "1b28e9c1f9f92b39db14e05bd14abaf591ad9df9", "size": 14053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/framework/core/test/domain_decomposition_test.cpp", "max_stars_repo_name": "OliverSchmitz/lue", "max_stars_repo_head_hexsha": "da097e8c1de30724bfe7667cc04344b6535b40cd", "max_stars_repo_licenses": ["MIT"], "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/framework/core/test/domain_decomposition_test.cpp", "max_issues_repo_name": "OliverSchmitz/lue", "max_issues_repo_head_hexsha": "da097e8c1de30724bfe7667cc04344b6535b40cd", "max_issues_repo_licenses": ["MIT"], "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/framework/core/test/domain_decomposition_test.cpp", "max_forks_repo_name": "OliverSchmitz/lue", "max_forks_repo_head_hexsha": "da097e8c1de30724bfe7667cc04344b6535b40cd", "max_forks_repo_licenses": ["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.0920770878, "max_line_length": 80, "alphanum_fraction": 0.6181598235, "num_tokens": 3844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5108132495740619}}
{"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_TWOTO31_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_TWOTO31_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Twoto31 Twoto31 (function template)\n\n  Generates the constant \\f$2^{31}\\f$\n\n  @headerref{<boost/simd/constant/twoto31.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Twoto31();\n      @endcode\n\n  2.  @code\n      template<typename T> T Twoto31( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T that evaluates to (\\f$2^{31}\\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 <tt>T(2147483648)</tt>.\n\n  @par Requirements\n  - **T** models IEEEValue\n**/\n\n#include <boost/simd/constant/scalar/twoto31.hpp>\n#include <boost/simd/constant/simd/twoto31.hpp>\n\n#endif\n", "meta": {"hexsha": "aa1590af9f88d39043a859fcee448aa7d0a5ceff", "size": 1478, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/twoto31.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/twoto31.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/twoto31.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": 28.9803921569, "max_line_length": 100, "alphanum_fraction": 0.5223274696, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5108132443203792}}
{"text": "#ifndef EXPSUM_VANDERMONDE_HPP\n#define EXPSUM_VANDERMONDE_HPP\n\n#include <cassert>\n\n#include <armadillo>\n\n#include \"expsum/fitting/lsqr.hpp\"\n#include \"expsum/numeric.hpp\"\n\nnamespace expsum\n{\n//\n// Generalized Vandermonde matrix\n//\n// This class represents a ``$m \\times n$`` generalized Vandermonde matrix of\n// the form\n//\n// ``` math\n//   \\bm{V}(\\bm{t}) = \\left[ \\begin{array}{}\n//     1         & 1         & \\dots  & 1         \\\\\n//     t_{1}^{}  & t_{2}^{}  & \\dots  & t_{n}^{}  \\\\\n//     \\vdots    & \\vdots    & \\ddots & \\vdots    \\\\\n//     t_{1}^{m} & t_{2}^{m} & \\dots  & t_{n}^{m} \\\\\n//   \\end{array} \\right]\n// ```\ntemplate <typename T>\nclass vandermonde_matrix\n{\npublic:\n    using value_type  = T;\n    using real_type   = typename arma::get_pod_type<value_type>::result;\n    using size_type   = arma::uword;\n    using vector_type = arma::Col<value_type>;\n    using matrix_type = arma::Mat<value_type>;\n\nprivate:\n    size_type nrows_;\n    size_type ncols_;\n\n    vector_type coeffs_;\n    mutable vector_type work_;\n\npublic:\n    vandermonde_matrix()                          = default;\n    vandermonde_matrix(const vandermonde_matrix&) = default;\n    vandermonde_matrix(vandermonde_matrix&&)      = default;\n    ~vandermonde_matrix()                         = default;\n    vandermonde_matrix& operator=(const vandermonde_matrix&) = default;\n    vandermonde_matrix& operator=(vandermonde_matrix&&) = default;\n\n    vandermonde_matrix(size_type nrows, size_type ncols)\n        : nrows_(nrows), ncols_(ncols), coeffs_(ncols), work_(ncols)\n    {\n    }\n\n    template <typename T1>\n    vandermonde_matrix(\n        size_type nrows, const T1& coeffs,\n        typename std::enable_if<arma::is_arma_type<T1>::value>::type* = 0)\n        : nrows_(nrows), ncols_(coeffs.n_elem), coeffs_(coeffs), work_(ncols_)\n    {\n    }\n\n    size_type nrows() const\n    {\n        return nrows_;\n    }\n\n    size_type ncols() const\n    {\n        return ncols_;\n    }\n\n    // Returns size of vector that defines the Vandermonde matrix\n    size_type size() const\n    {\n        return ncols();\n    }\n\n    // Resize matrix\n    void resize(size_type nrows, size_type ncols)\n    {\n        nrows_ = nrows;\n        ncols_ = ncols;\n        coeffs_.resize(ncols);\n        work_.resize(ncols);\n    }\n\n    // Set elements of Vandermonde matrix\n    template <typename T1>\n    typename std::enable_if<arma::is_arma_type<T1>::value>::type\n    set_coeffs(const T1& coeffs)\n    {\n        ncols_ = coeffs.n_elem;\n        if (coeffs_.size() < ncols_)\n        {\n            coeffs_.resize(ncols_);\n            work_.resize(ncols_);\n        }\n        coeffs_.head(ncols_) = coeffs;\n    }\n\n    auto coeffs() const -> decltype(coeffs_.head(ncols_))\n    {\n        return coeffs_.head(ncols_);\n    }\n\n    matrix_type as_dense_matrix() const\n    {\n        matrix_type ret(nrows(), ncols());\n        for (size_type j = 0; j < ncols(); ++j)\n        {\n            auto x = coeffs_(j);\n            auto v = value_type(1);\n            ret(0, j) = v;\n            for (size_type i = 1; i < nrows(); ++i)\n            {\n                v *= x;\n                ret(i, j) = v;\n            }\n        }\n        return ret;\n    }\n    ///\n    /// Compute `y = A * x + beta * y`\n    ///\n    template <typename U1, typename U2>\n    typename std::enable_if<(arma::is_arma_type<U1>::value &&\n                             arma::is_arma_type<U2>::value),\n                            void>::type\n    apply(const U1& x, value_type beta, U2& y) const\n    {\n        assert(x.n_elem == ncols());\n        assert(y.n_elem == nrows());\n\n        auto w = work_.head(ncols_);\n        w      = x;\n\n        y(0) = arma::sum(w) + beta * y(0);\n        for (size_type i = 1; i < nrows(); ++i)\n        {\n            w %= coeffs();\n            y(i) = arma::sum(w) + beta * y(i);\n        }\n    }\n    ///\n    /// Compute `y = A.t() * x + beta * y`\n    ///\n    template <typename U1, typename U2>\n    typename std::enable_if<(arma::is_arma_type<U1>::value &&\n                             arma::is_arma_type<U2>::value),\n                            void>::type\n    apply_trans(const U1& x, value_type beta, U2& y) const\n    {\n        assert(x.n_elem == nrows());\n        assert(y.n_elem == ncols());\n\n        for (size_type i = 0; i < ncols(); ++i)\n        {\n            const auto zi = numeric::conj(coeffs_(i));\n            // Evaluate polynomial using Honer's method\n            auto s = value_type();\n            for (size_type j = 0; j < nrows(); ++j)\n            {\n                s = s * zi + x(nrows() - j - 1);\n            }\n\n            y(i) = s + beta * y(i);\n        }\n    }\n};\n\n//\n// Compute LDL^H factorization of the gramian matrix of column Vandermonde\n// matrix.\n//\ntemplate <typename T, typename MatrixT, typename MatrixWork>\nvoid ldlt_vandermonde_gramian(const vandermonde_matrix<T>& V, MatrixT& mat,\n                              MatrixWork& work)\n{\n    using value_type  = typename vandermonde_matrix<T>::value_type;\n    using vector_type = typename vandermonde_matrix<T>::vector_type;\n    using real_type   = typename arma::get_pod_type<value_type>::result;\n    using size_type   = arma::uword;\n\n    using std::abs;\n    using std::real;\n    using std::sqrt;\n\n    constexpr const auto one = value_type(1);\n    static const auto tiny   = sqrt(std::numeric_limits<real_type>::min());\n\n    const auto z      = V.coeffs();\n    const size_type m = V.nrows();\n    const size_type n = V.ncols();\n\n    assert(mat.n_rows == n && mat.n_cols == n);\n    assert(work.n_rows == n && work.n_cols >= 4);\n\n    // ----- Initialization\n    auto y1 = work.col(0);\n    auto y2 = work.col(1);\n    auto x1 = work.col(2);\n    auto x2 = work.col(3);\n\n    auto gramian = [&](size_type i, size_type j) {\n        const auto arg = numeric::conj(z(i)) * z(j);\n        return arg == one ? value_type(m)\n                          : (one - std::pow(arg, m)) / (one - arg);\n    };\n\n    auto sigma2 = gramian(0, 0);\n    auto b0     = mat.col(0);\n    b0(0)       = one;\n    for (size_type j = 1; j < n; ++j)\n    {\n        b0(j) = gramian(j, 0) / sigma2;\n    }\n\n    y1 = arma::ones<vector_type>(n) - b0;\n    y2 = arma::pow(arma::conj(z), m);\n    y2 -= y2(0) * b0;\n    x1 = value_type(1) / arma::conj(z);\n    x1 -= x1(0) * b0;\n    x2 = arma::pow(-arma::conj(z), m - 1);\n    x2 -= x2(0) * b0;\n\n    b0(0) = sigma2;\n\n    for (size_type k = 1; k < n; ++k)\n    {\n        auto bk = mat.col(k);\n\n        auto mu1 = x1(k);\n        auto mu2 = x2(k);\n        auto nu1 = numeric::conj(y1(k));\n        auto nu2 = numeric::conj(y2(k));\n\n        auto zk     = z(k);\n        auto zk_inv = one / zk;\n        auto denom  = numeric::conj(zk_inv) - zk;\n\n        if (abs(denom) < tiny)\n        {\n            sigma2         = real_type(m);\n            const auto bkk = real(mat(k, k));\n            for (size_type j = 0; j < k; ++j)\n            {\n                const auto bkj = mat(k, j);\n                sigma2 -= std::norm(bkj) * bkk;\n            }\n        }\n        else\n        {\n            sigma2 = (mu1 * nu1 + mu2 * nu2) / denom;\n        }\n\n        bk(k) = sigma2;\n\n        for (size_type i = k + 1; i < n; ++i)\n        {\n            const auto d1 =\n                (numeric::conj(mu1) * y1(i) + numeric::conj(mu2) * y2(i));\n            const auto d2 = sigma2 * (zk_inv - numeric::conj(z(i)));\n            bk(i)         = d1 / d2;\n        }\n\n        const size_type nt = n - k - 1;\n\n        x1.tail(nt) -= mu1 * bk.tail(nt);\n        x2.tail(nt) -= mu2 * bk.tail(nt);\n        y1.tail(nt) -= numeric::conj(nu1) * bk.tail(nt);\n        y2.tail(nt) -= numeric::conj(nu2) * bk.tail(nt);\n    }\n\n    // arma::Mat<T> tmp_V(V.as_dense_matrix());\n    // arma::Mat<T> tmp_H(V.t() * V);\n\n    // for (size_type k = 0; k < n; ++k)\n    // {\n    //     auto bk          = mat.col(k);\n    //     const auto sigma = sqrt(real(mat(k, k)));\n\n    //     bk(k) = sigma;\n    //     bk.tail(n - k - 1) *= sigma;\n    // }\n\n    return;\n}\n\n///\n/// Solve overdetermined Vandermonde system\n///\ntemplate <typename T>\nstruct vandermonde_least_squares\n{\n    using size_type  = arma::uword;\n    using value_type = T;\n    using real_type  = typename arma::get_pod_type<value_type>::result;\n\n    using matrix_type             = arma::Mat<value_type>;\n    using vector_type             = arma::Col<value_type>;\n    using vandermonde_matrix_type = vandermonde_matrix<value_type>;\n\nprivate:\n    struct matvec\n    {\n        matvec(const vandermonde_matrix_type& mat_V) : mat_V_(mat_V)\n        {\n        }\n\n        template <typename U1, typename U2>\n        void operator()(const U1& x, value_type beta, U2& y) const\n        {\n            mat_V_.apply(x, beta, y);\n        }\n\n        const vandermonde_matrix_type& mat_V_;\n    };\n\n    struct matvec_trans\n    {\n        matvec_trans(const vandermonde_matrix_type& mat_V) : mat_V_(mat_V)\n        {\n        }\n\n        template <typename U1, typename U2>\n        void operator()(const U1& x, value_type beta, U2& y) const\n        {\n            mat_V_.apply_trans(x, beta, y);\n        }\n\n        const vandermonde_matrix_type& mat_V_;\n    };\n\n    struct preconditioner\n    {\n        // ldlt -- Result of Cholesky (LDL^T) decomposition of V.t() * V\n        preconditioner(const matrix_type& ldlt) : ldlt_(ldlt){};\n\n        template <typename Rhs, typename Dest>\n        void operator()(const Rhs& rhs, Dest& dst) const\n        {\n            constexpr const real_type tol =\n                real_type(1) / std::numeric_limits<real_type>::max();\n            // auto mat_L = arma::trimatl(chol_VtV_);\n            // dst = arma::solve(mat_L, rhs);\n            // dst = arma::solve(mat_L.t(), dst);\n            char uplo           = 'L';\n            char trans1         = 'N';\n            char trans2         = 'C';\n            char diag           = 'U';\n            arma::blas_int n    = arma::blas_int(ldlt_.n_rows);\n            arma::blas_int nrhs = dst.n_cols;\n            arma::blas_int info = 0;\n            dst                 = rhs;\n\n            arma::lapack::trtrs(&uplo, &trans1, &diag, &n, &nrhs,\n                                ldlt_.memptr(), &n, &dst[0], &n, &info);\n\n            for (size_type i = 0; i < ldlt_.n_rows; ++i)\n            {\n                if (std::abs(ldlt_(i, i)) > tol)\n                {\n                    dst(i) /= ldlt_(i, i);\n                }\n                else\n                {\n                    dst(i) = value_type();\n                }\n            }\n\n            arma::lapack::trtrs(&uplo, &trans2, &diag, &n, &nrhs,\n                                ldlt_.memptr(), &n, &dst[0], &n, &info);\n\n            return;\n        }\n\n        const matrix_type& ldlt_;\n    };\n\npublic:\n    vandermonde_least_squares()\n        : max_iterations_(),\n          iterations_(),\n          tolerance_(arma::Datum<real_type>::eps),\n          error_()\n    {\n    }\n\n    static size_type\n    inquery_workspace_size(const vandermonde_matrix_type& mat_V)\n    {\n        return inquery_workspace_size(mat_V.nrows(), mat_V.ncols());\n    }\n\n    static size_type inquery_workspace_size(size_type nrows, size_type ncols)\n    {\n        return (ncols + 3) * ncols + std::max(nrows, ncols);\n    }\n\n    // Solve overdetermined Vandermonde problem.\n    template <typename Rhs, typename Dest>\n    void solve(const vandermonde_matrix_type& mat_V, const Rhs& b, Dest& x,\n               value_type* work)\n    {\n        const size_type m = mat_V.nrows();\n        const size_type n = mat_V.ncols();\n\n        assert(b.n_rows == m && x.n_rows == n);\n\n        //\n        // Compute Cholesky decomposition of `V.t() * V = L.t() * L`, where `V`\n        // is input Vandermonde matrix while `L` is a lower triangular matrix.\n        //\n        value_type* ptr_chol = work;\n        value_type* ptr_vec1 = ptr_chol + n * n;\n        value_type* ptr_vec2 = ptr_vec1 + m;\n        matrix_type chol_VtV(ptr_chol, n, n, /* copy_aux_mem */ false,\n                             /* strict */ true);\n        matrix_type vecs(ptr_vec1, n, 4, /* copy_aux_mem */ false,\n                         /* strict */ true);\n        ldlt_vandermonde_gramian(mat_V, chol_VtV, vecs);\n        //\n        // Solve `V * x = b` using preconditioned LSQR\n        //\n        matvec mv(mat_V);\n        matvec_trans mv_trans(mat_V);\n        preconditioner precond(chol_VtV);\n\n        vector_type u(ptr_vec1, m, /*copy_aux_mem*/ false, /*strict*/ true);\n        matrix_type tmp(ptr_vec2, n, 3, /*copy_aux_mem*/ false,\n                        /*strict*/ true);\n        u           = arma::conv_to<vector_type>::from(b);\n        iterations_ = max_iterations_ ? max_iterations_ : 2 * n;\n        error_      = tolerance_;\n        lsqr(mv, mv_trans, u, x, precond, tmp, iterations_, error_);\n\n        return;\n    }\n\n    /// Check the convergence\n    bool converged() const\n    {\n        return iterations_ <= max_iterations_;\n    }\n\n    real_type tolerance() const\n    {\n        return tolerance_;\n    }\n\n    void set_tolerance(real_type tol)\n    {\n        tolerance_ = tol;\n    }\n\n    size_type iterations() const\n    {\n        return iterations_;\n    }\n\n    void set_max_iterations(size_type max_iter)\n    {\n        max_iterations_ = max_iter;\n    }\n\n    /// @return An estimation of residual error\n    real_type error() const\n    {\n        return error_;\n    }\n\nprivate:\n    size_type max_iterations_;\n    size_type iterations_;\n    real_type tolerance_;\n    real_type error_;\n};\n\n} // namespace expsum\n\n#endif /* EXPSUM_VANDERMONDE_HPP */\n", "meta": {"hexsha": "390c714a10286becf3740303d2d8e43b48353ea2", "size": 13372, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/fitting/vandermonde_matrix.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/vandermonde_matrix.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/vandermonde_matrix.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.5711340206, "max_line_length": 79, "alphanum_fraction": 0.5205653605, "num_tokens": 3676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5108132405115348}}
{"text": "#include <stan/math/prim.hpp>\n#include <test/unit/math/prim/util.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <gtest/gtest.h>\n#include <stdexcept>\n#include <vector>\n\nTEST(ProbDistributionsWishart, rng) {\n  using Eigen::MatrixXd;\n  using stan::math::wishart_rng;\n\n  boost::random::mt19937 rng;\n\n  MatrixXd omega(3, 4);\n  EXPECT_THROW(wishart_rng(3.0, omega, rng), std::invalid_argument);\n\n  MatrixXd sigma(3, 3);\n  sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 1.0, 0.0, 1.0, 3.0;\n  EXPECT_NO_THROW(wishart_rng(3.0, sigma, rng));\n  EXPECT_THROW(wishart_rng(2, sigma, rng), std::domain_error);\n  EXPECT_THROW(wishart_rng(-1, sigma, rng), std::domain_error);\n  sigma(2, 1) = 100.0;\n  EXPECT_THROW(wishart_rng(3.0, sigma, rng), std::domain_error);\n}\n\nTEST(ProbDistributionsWishart, rng_pos_def) {\n  using Eigen::MatrixXd;\n  using stan::math::wishart_rng;\n\n  boost::random::mt19937 rng;\n\n  MatrixXd Sigma(2, 2);\n  MatrixXd Sigma_non_pos_def(2, 2);\n\n  Sigma << 1, 0, 0, 1;\n  Sigma_non_pos_def << -1, 0, 0, 1;\n\n  unsigned int dof = 5;\n\n  EXPECT_NO_THROW(wishart_rng(dof, Sigma, rng));\n  EXPECT_THROW(wishart_rng(dof, Sigma_non_pos_def, rng), std::domain_error);\n}\n\nTEST(ProbDistributionsWishart, rng_symmetry) {\n  using Eigen::MatrixXd;\n  using stan::math::wishart_rng;\n  using stan::test::unit::expect_symmetric;\n  using stan::test::unit::spd_rng;\n\n  boost::random::mt19937 rng;\n  for (int k = 1; k < 20; ++k)\n    for (double nu = k - 0.9; nu < k + 10; ++nu)\n      for (int n = 0; n < 10; ++n)\n        expect_symmetric(wishart_rng(nu, spd_rng(k, rng), rng));\n}\n\nTEST(ProbDistributionsWishart, marginalTwoChiSquareGoodnessFitTest) {\n  using boost::math::chi_squared;\n  using boost::math::digamma;\n  using Eigen::MatrixXd;\n  using stan::math::determinant;\n  using stan::math::wishart_rng;\n  using std::log;\n\n  boost::random::mt19937 rng;\n  MatrixXd sigma(3, 3);\n  sigma << 9.0, -3.0, 2.0, -3.0, 4.0, 0.0, 2.0, 0.0, 3.0;\n  int N = 10000;\n\n  double avg = 0;\n  double expect = sigma.rows() * log(2.0) + log(determinant(sigma))\n                  + digamma(5.0 / 2.0) + digamma(4.0 / 2.0)\n                  + digamma(3.0 / 2.0);\n\n  MatrixXd a(sigma.rows(), sigma.rows());\n  for (int count = 0; count < N; ++count) {\n    a = wishart_rng(5.0, sigma, rng);\n    avg += log(determinant(a));\n  }\n  avg /= N;\n  double chi = (expect - avg) * (expect - avg) / expect;\n  chi_squared mydist(1);\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsWishart, SpecialRNGTest) {\n  // For any vector C != 0\n  // (C' * W * C) / (C' * S * C)\n  // must be chi-square distributed with df = k\n  // which has mean = k and variance = 2k\n\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n  using stan::math::wishart_rng;\n\n  boost::random::mt19937 rng(1234);\n\n  MatrixXd sigma(3, 3);\n\n  sigma << 9.0, 2.0, 2.0, 2.0, 4.0, 1.0, 2.0, 1.0, 3.0;\n\n  VectorXd C(3);\n  C << 2, 1, 3;\n\n  size_t N = 1e4;\n  int k = 20;\n  // tolerance for variance\n  double tol = 0.2;\n  std::vector<double> acum;\n  acum.reserve(N);\n  for (size_t i = 0; i < N; i++)\n    acum.push_back((C.transpose() * wishart_rng(k, sigma, rng) * C)(0)\n                   / (C.transpose() * sigma * C)(0));\n\n  EXPECT_NEAR(1, stan::math::mean(acum) / k, tol * tol);\n  EXPECT_NEAR(1, stan::math::variance(acum) / (2 * k), tol);\n}\n", "meta": {"hexsha": "28da632500afcac064d7e7a3b604d63765307dd1", "size": 3330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/wishart_rng_test.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/math/prim/prob/wishart_rng_test.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": "test/unit/math/prim/prob/wishart_rng_test.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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.9831932773, "max_line_length": 76, "alphanum_fraction": 0.6348348348, "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.5108132376218578}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <stdexcept>\n#include <math.h>\n#include <set>\n#include <boost/multiprecision/gmp.hpp>\n#include <boost/multiprecision/number.hpp>\n\nusing namespace std;\nusing namespace boost::multiprecision;\n\nint target = 100;\n\nint main(int argc, char** argv) {\n  set<mpz_int> visited;\n\n  for (int a = 2; a <= target; a++) {\n    for (int b = 2; b <= target; b++) {\n      mpz_int val = 1;\n      for (int i = 0; i < b; i++) {\n        val *= a;\n      }\n      visited.insert(val);\n      cout << val << endl;\n    }\n  }\n\n  cout << \"Total unique elements: \" << visited.size() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "d0530bd585bcffa537a5673ef00590e556f78ac6", "size": 622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "29.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": "29.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": "29.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": 19.4375, "max_line_length": 62, "alphanum_fraction": 0.5868167203, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835534888481, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5107995835868214}}
{"text": "/**\n    Definitions of functions wrapping lapack.\n    Declarations depends on compilations options PROXTV_USE_LAPACK\n\n    @author Pablo Hernandez-Cerdan\n*/\n\n#include \"lapackFunctionsWrap.h\"\n\n#ifndef PROXTV_USE_LAPACK // USE_EIGEN\n#include <Eigen/Dense>\nvoid dpttrf_plus_dpttrs_eigen( lapack_int* n, double* d, double* e, double *b)\n{\n    using EigenMatrix = Eigen::MatrixXd;\n    using EigenVector = Eigen::VectorXd;\n    using EigenVectorMap = Eigen::Map<EigenVector>;\n    // Eigen has to create the full matrix from the diagonal d and subdiagonal e\n    int mSize = *n;\n    EigenMatrix eigenM(mSize,mSize);\n    EigenVectorMap diag(d, mSize);\n    EigenVectorMap subAndUpperDiag(e, mSize - 1);\n    EigenVectorMap inputB_outputX(b, mSize);\n    // Populate matrix\n    eigenM.diagonal() = diag;\n    eigenM.diagonal( 1) = subAndUpperDiag;\n    eigenM.diagonal(-1) = subAndUpperDiag;\n\n    // Factorize using ldlt (ldl is also possible, faster but less accurate)\n    // A = LDL'\n    Eigen::LDLT<EigenMatrix> factorization(eigenM);\n    // A*X = b\n    // This modifies the input/output pointer: b\n    inputB_outputX = factorization.solve(inputB_outputX);\n    // This modifies the input/output pointers: d and e\n    EigenMatrix factorized = factorization.matrixLDLT();\n    diag = factorized.diagonal();\n    subAndUpperDiag = factorized.diagonal(-1);\n}\n#endif\n", "meta": {"hexsha": "ec719a0f67be4a210b84fec3f8a9d2238524dd96", "size": 1346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lapackFunctionsWrap.cpp", "max_stars_repo_name": "dzenanz/proxTV", "max_stars_repo_head_hexsha": "4f7e2370a7134c871f0cb23aa6107d1d9fa775f0", "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/lapackFunctionsWrap.cpp", "max_issues_repo_name": "dzenanz/proxTV", "max_issues_repo_head_hexsha": "4f7e2370a7134c871f0cb23aa6107d1d9fa775f0", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-14T07:40:40.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-14T07:40:40.000Z", "max_forks_repo_path": "src/lapackFunctionsWrap.cpp", "max_forks_repo_name": "dzenanz/proxTV", "max_forks_repo_head_hexsha": "4f7e2370a7134c871f0cb23aa6107d1d9fa775f0", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-08-16T00:15:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T21:09:03.000Z", "avg_line_length": 33.65, "max_line_length": 80, "alphanum_fraction": 0.7124814264, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5107995785779489}}
{"text": "/**\n * @file velocity_filter.hpp\n * @author Fujii Naomichi\n * @copyright (c) 2021 Fujii Naomichi\n * SPDX-License-Identifier: MIT\n */\n\n#pragma once\n\n#include <Eigen/Core>\n\n/**\n * @brief IMU\u306e\u6e2c\u5b9a\u5024\u3068\u30aa\u30c9\u30e1\u30c8\u30ea\u304b\u3089\u8eca\u4f53\u901f\u5ea6\u3092\u63a8\u5b9a\u3059\u308b\n */\nclass VelocityFilter {\nprivate:\n    using Vector7f = Eigen::Matrix<float, 7, 1>;\n    using Matrix7f = Eigen::Matrix<float, 7, 7>;\n\npublic:\n    /**\n     * @brief \u5185\u90e8\u72b6\u614b\u3092\u30ea\u30bb\u30c3\u30c8\u3059\u308b\n     */\n    void reset(void);\n\n    /**\n     * @brief \u30d5\u30a3\u30eb\u30bf\u306b\u65b0\u305f\u306a\u5165\u529b\u3092\u4e0e\u3048\u3066\u51fa\u529b\u3092\u66f4\u65b0\u3059\u308b\n     * @param accel \u52a0\u901f\u5ea6\u30bb\u30f3\u30b5\u30fc\u306e\u6e2c\u5b9a\u5024\n     * @param gyro \u30b8\u30e3\u30a4\u30ed\u30b9\u30b3\u30fc\u30d7\u306e\u6e2c\u5b9a\u5024\n     * @param wheel_velocity \u8eca\u8f2a\u901f\u5ea6\n     * @param wheel_current \u30e2\u30fc\u30bf\u30fc\u96fb\u6d41\n     */\n    void update(const Eigen::Vector3f& accel, const Eigen::Vector3f& gyro, const Eigen::Vector4f& wheel_velocity, const Eigen::Vector4f& wheel_current);\n\n    /**\n     * @brief \u8eca\u4f53\u901f\u5ea6\u306e\u63a8\u5b9a\u5024\u3092\u53d6\u5f97\u3059\u308b\n     * @return \u8eca\u4f53\u901f\u5ea6 X [m/s], Y [m/s], \u03c9 [rad/s]\n     */\n    Eigen::Vector3f bodyVelocity(void) const {\n        return {_mu(0), _mu(1), _mu(2)};\n    }\n\n    /**\n     * @brief \u6469\u64e6\u4fc2\u6570\u306e\u63a8\u5b9a\u5024\u3092\u53d6\u5f97\u3059\u308b\n     * @return \u6469\u64e6\u4fc2\u6570 [Ns]\n     */\n    Eigen::Vector4f frictionCoefficients(void) const {\n        return {_mu(3), _mu(4), _mu(5), _mu(6)};\n    }\n\n    /// \u72b6\u614b\u5909\u6570\u306e\u6700\u5c24\u5024\n    Vector7f _mu;\n\n    /// \u5171\u5206\u6563\n    Matrix7f _sigma;\n\n    /// \u524d\u56de\u306e\u66f4\u65b0\u6642\u306e\u8eca\u8f2a\u901f\u5ea6\n    Eigen::Vector4f _last_wheel_velocity;\n\n    /// \u7dda\u5f62\u5316\u3055\u308c\u305f\u72b6\u614b\u65b9\u7a0b\u5f0f\n    Matrix7f G;\n\n    /// \u7dda\u5f62\u5316\u3055\u308c\u305f\u89b3\u6e2c\u65b9\u7a0b\u5f0f\n    Matrix7f H;\n\n    /// \u9006\u884c\u5217\u3092\u6c42\u3081\u308b\u969b\u306e\u9014\u4e2d\u8a08\u7b97\u7d50\u679c\n    Matrix7f L, invL;\n};\n", "meta": {"hexsha": "e573bab70805af2caa6c48294a4cec0775360008", "size": 1380, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "FPGA/App/software/controller/source/filter/velocity_filter.hpp", "max_stars_repo_name": "Nkyoku/phoenix-firmware", "max_stars_repo_head_hexsha": "42f17854099d3a1a4e1b50e314bbcd5648b83ac2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FPGA/App/software/controller/source/filter/velocity_filter.hpp", "max_issues_repo_name": "Nkyoku/phoenix-firmware", "max_issues_repo_head_hexsha": "42f17854099d3a1a4e1b50e314bbcd5648b83ac2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FPGA/App/software/controller/source/filter/velocity_filter.hpp", "max_forks_repo_name": "Nkyoku/phoenix-firmware", "max_forks_repo_head_hexsha": "42f17854099d3a1a4e1b50e314bbcd5648b83ac2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-27T09:24:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T02:11:26.000Z", "avg_line_length": 20.0, "max_line_length": 152, "alphanum_fraction": 0.6057971014, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5107995735690763}}
{"text": "#include <boost/math/distributions/fisher_f.hpp>\n", "meta": {"hexsha": "e6fea950a4af52da1cd4313b855034fd79ae2e29", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_fisher_f.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_fisher_f.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_fisher_f.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8163265306, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5107995735690763}}
{"text": "#include<boost/numeric/ublas/matrix.hpp>\n#include<boost/numeric/ublas/vector.hpp>\n#include<boost/numeric/ublas/io.hpp>\n#include<complex>\n\n#include <boost/numeric/linear_algebra/concepts.hpp>\n#include <boost/numeric/linear_algebra/vector_concepts.hpp>\n\ntypedef double Type;\n\nnamespace ublas = boost::numeric::ublas;\n\ntypedef ublas::vector<Type> Vector;\n\ntemplate <typename T>\nstruct dot \n{\n  T operator() (const T& v, const T& w)\n  {\n    using std::conj;\n    T tmp= 0;\n    for (int i= 0; i < v.size(); i++)\n      tmp+= conj(v[i]) * w[i];\n    return tmp;\n  }\n};\n\n\nnamespace math {\n  concept_map HilbertSpace< dot<double>, Vector>;\n}\n\n\nint main (int argc, char* argv[])  \n{\n  const int v_size= 10;\n\n  Vector v(v_size), w(v_size), x, y(v_size-1);\n  for (int i= 0; i < v_size; i++)\n    v[i]= 1.0, w[i]= 2.0;\n  for (int i= 0; i < v_size-1; i++) \n    y[i]= 3.0;\n\n  w+= v;\n  try {\n    x= v + y;\n  } catch (ublas::bad_argument) {\n    std::cout << \"caught bad argument \" << std::endl;\n  }\n\n\n  std::cout << \"v \" << v << std::endl;\n  std::cout << \"w \" << w << std::endl;\n  std::cout << \"x \" << x << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "ea3d6fc4946ee6d443918e201f08c2a1001b8a15", "size": 1113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/linear_algebra/test/vector_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/linear_algebra/test/vector_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/linear_algebra/test/vector_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": 19.1896551724, "max_line_length": 59, "alphanum_fraction": 0.5929919137, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5107995685602036}}
{"text": "/* Vehicle Vibration Analysis\r\n*\tVehicle dynamics can be modeled as a 2DoF spring-mass-damper system with two ouptuts:\r\n*\t\t1. Vehicle bounce (z motion felt by passengers)\r\n*\t\t2. Vehicle pitch (rotation felt be passengers along front to back)\r\n*\tThese ouputs are based on vehicle characteristics\r\n*/\r\n\r\n// Courtney Armstrong\r\n// Rev 2, 12/06/16\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <boost/numeric/odeint.hpp>\r\n#include <vector>\r\n#include <Eigen>\r\n#include <iomanip>\r\n#include <math.h>\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\n\r\ntypedef std::vector< double > state_type;\r\ndouble pi = acos(-1);\r\n\r\n// Define road class\r\nclass Road\r\n{\r\n\tfriend class coupledODE;\r\n\tprotected:\r\n\t\tdouble A;\t\t\t// 1/2 amplitude of road variation, m\r\n\t\tdouble L;\t\t\t// Wavelength of road variation, m\r\n\t\tdouble V;\t\t\t// Vehicle velocity, m/s\r\n\t\tdouble radFreq;\t\t// Radial frequency (rad/s)\r\n\r\n\tpublic:\r\n\t\tvoid getRoadValues()\r\n\t\t{\r\n\t\t\tcout << \"It is efficient to model road variation as a sinusoidal curve, using peak amplitude (bump height) and wavelength (roughness) as defining characteristics.\" << endl;\r\n\r\n\t\t\tcout << \"Enter the peak amplitude of the road variation, A (m): \"; cin >> A;\r\n\t\t\tcout << \"Enter the wavelength of the road variation, L (m): \"; cin >> L;\r\n\t\t\tcout << \"Enter the velocity of the vehicle, V (m/s): \"; cin >> V;\t\r\n\t\t\tcout << \"\\n\";\r\n\t\t\tradFreq = (2 * pi * V) / L;\r\n\t\t\tcout << setprecision(4) << \"The radial frequency is \" << radFreq << \" rad/s\\n\";\r\n\t\t}\r\n\r\n\r\n};\r\n\r\n// Define vehicle class\r\nclass Vehicle\r\n{\r\n\tfriend class coupledODE;\r\n\tprivate:\r\n\t\tdouble mass;\t\t\t// Vehicle mass, kg\r\n\t\tdouble inertia;\t\t\t// Mass moment of inertia, N*sec^2*m\r\n\t\tdouble stiffness_f;\t\t// Stiffness of front suspension, N/m\r\n\t\tdouble stiffness_r;\t\t// Stiffness of rear suspension, N/m\r\n\t\tdouble damping_f;\t\t// Damping of front suspension, N*s/m\r\n\t\tdouble damping_r;\t\t// Damping of rear suspension, N*s/m\r\n\t\tdouble frontLength;\t\t// Distance from CG to front suspension, m\r\n\t\tdouble rearLength;\t\t// Distance from CG to rear suspension, m\r\n\t\tdouble w1;\t\t\t\t// 1st natural frequency, rad/s\r\n\t\tdouble w2;\t\t\t\t// 2nd natural frequency, rad/s\r\n\t\tint classVal;\t\t\t// User defined class type\r\n\r\n\tpublic:\r\n\t\t// Output general information and get user choice (determines vehicle paramenters) \r\n\t\tint setUserChoice()\r\n\t\t{\r\n\t\t\tint selection;\r\n\t\t\tcout << \"Before the vibration analysis can be completed, modeling parameters for the vehicle need to be defined.\" << endl;\r\n\t\t\tcout << \"The pre-defined parameters are based on SAE passenger car classifications, or you can define your own parameters.\\n\" << endl;\r\n\t\t\tcout << \"The SAE classification are based on the wheelbase (length from front to back axle) of the vehicles. They are defined as follows:\" << endl;\r\n\t\t\tcout << \"\\tClass 1 - Wheelbase = 2.06-2.41 m (80.9-94.8\\\"); Includes sub-compact vehicles, like the Ford Fiesta and Kia Rio.\" << endl;\r\n\t\t\tcout << \"\\tClass 2 - Wheelbase = 2.41-2.58 m (94.8-101.6\\\"); Includes compact vehicles, like the Toyota Corolla and Mazda3\" << endl;\r\n\t\t\tcout << \"\\tClass 3 - Wheelbase = 2.58-2.80 m (101.6-110.4\\\"); Includes mid-size vehicles, like the Hyundai Sonata and Honda Accord\" << endl;\r\n\t\t\tcout << \"\\tClass 4 - Wheelbase = 2.80-2.98 m (110.4-117.5\\\"); Includes full-size vehicles, like the Infiniti Q70 and Jaguar XF\" << endl;\r\n\t\t\tcout << \"\\tClass 5 - Wheelbase = 2.98+ m (117.5\\\"+); Unusual for modern passenger cars to fit this class\\n\" << endl;\r\n\r\n\t\t\tcout << \"Enter a value from 1-5 to select one of the SAE classed (enter 1 to select Class 1, 2 to select Class 2, etc.)\\nOR\\nEnter 0 to define your own parameters: \";\r\n\t\t\tcin >> selection;\r\n\r\n\t\t\t// Check validity of selection and assign if data is correct\r\n\t\t\tif (selection >= 0 && selection <= 5)\r\n\t\t\t{\r\n\t\t\t\tclassVal = selection;\r\n\t\t\t\tif (classVal == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tcout << \"\\nYou have selected to input your own parameters.\\nNote that this may result in failed calculations if not properly defined.\\n\" << endl;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tcout << \"You have selected SAE Class \" << classVal << \"\\n\" << endl;\r\n\t\t\t\t}\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tcout << \"You have entered an invalid selection.\" << endl;\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Set modeling parameters for the vehicle based on user choice\r\n\t\tvoid setVehicleParameters()\r\n\t\t{\r\n\t\t\tif (classVal == 0)\r\n\t\t\t{\r\n\t\t\t\t// User defined parameters\r\n\t\t\t\tcout << \"Enter the mass, m (kg): \"; cin >> mass;\r\n\t\t\t\tcout << \"Enter the moment of inertia, J (N*s^2*m): \"; cin >> inertia;\r\n\t\t\t\tcout << \"Enter the front suspension stiffness, k_f (N/m): \"; cin >> stiffness_f;\r\n\t\t\t\tcout << \"Enter the rear suspension stiffness, k_r (N/m): \"; cin >> stiffness_r;\r\n\t\t\t\tcout << \"Enter the front damping coefficient, c_f (N*s/m): \"; cin >> damping_f;\r\n\t\t\t\tcout << \"Enter the rear damping coefficient, c_r (N*s/m): \"; cin >> damping_r;\r\n\t\t\t\tcout << \"Enter the length from the center of gravity to the front axle, L1 (m): \"; cin >> frontLength;\r\n\t\t\t\tcout << \"Enter the length from the center of gravity to the rear axle, L2 (m); \"; cin >> rearLength;\r\n\t\t\t\tcout << \"\\n\";\r\n\t\t\t}\r\n\t\t\telse if (classVal == 1)\r\n\t\t\t{\r\n\t\t\t\t// Parameters for SAE class 1\r\n\t\t\t\tmass = 998.8104;\t\t\r\n\t\t\t\tinertia = 1399.0933;\r\n\t\t\t\tstiffness_f = 16836.6944;\r\n\t\t\t\tstiffness_r = 17616.0088;\r\n\t\t\t\tdamping_f = 1733.7550;\r\n\t\t\t\tdamping_r = 1399.2629;\r\n\t\t\t\tfrontLength = 0.6998;\r\n\t\t\t\trearLength = 0.6934;\r\n\t\t\t}\r\n\t\t\telse if (classVal == 2)\r\n\t\t\t{\r\n\t\t\t\t// Parameters for SAE class 2\r\n\t\t\t\tmass = 1384.8175;\r\n\t\t\t\tinertia = 1790.2473;\r\n\t\t\t\tstiffness_f = 17931.2371;\r\n\t\t\t\tstiffness_r = 17048.5979;\r\n\t\t\t\tdamping_f = 1616.4201;\r\n\t\t\t\tdamping_r = 1227.6387;\r\n\t\t\t\tfrontLength = 0.7191;\r\n\t\t\t\trearLength = 0.7280;\r\n\t\t\t}\r\n\t\t\telse if (classVal == 3)\r\n\t\t\t{\r\n\t\t\t\t// Parameters for SAE class 3\r\n\t\t\t\tmass = 1608.8921;\r\n\t\t\t\tinertia = 2259.8130;\r\n\t\t\t\tstiffness_f = 19465.3483;\r\n\t\t\t\tstiffness_r = 20032.7592;\r\n\t\t\t\tdamping_f = 1521.8516;\r\n\t\t\t\tdamping_r = 1213.6285;\r\n\t\t\t\tfrontLength = 0.7457;\r\n\t\t\t\trearLength = 0.7346;\r\n\t\t\t}\r\n\t\t\telse if (classVal == 4)\r\n\t\t\t{\r\n\t\t\t\t// Parameters for SAE class 4\r\n\t\t\t\tmass = 1926.4068;\r\n\t\t\t\tinertia = 2822.3653;\r\n\t\t\t\tstiffness_f = 16680.8315;\r\n\t\t\t\tstiffness_r = 23204.3063;\r\n\t\t\t\tdamping_f = 1229.3899;\r\n\t\t\t\tdamping_r = 1218.8823;\r\n\t\t\t\tfrontLength = 0.7605;\r\n\t\t\t\trearLength = 0.7854;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t// Parameters for SAE class 5\r\n\t\t\t\tmass = 2206.7269;\r\n\t\t\t\tinertia = 2709.9452;\r\n\t\t\t\tstiffness_f = 16812.1766;\r\n\t\t\t\tstiffness_r = 30354.7352;\r\n\t\t\t\tdamping_f = 1201.3697;\r\n\t\t\t\tdamping_r = 1337.9685;\r\n\t\t\t\tfrontLength = 0.7623;\r\n\t\t\t\trearLength = 0.7620;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Calculate the two natural frequencies\r\n\t\tvoid calcNatFreq()\r\n\t\t{\r\n\r\n\t\t\tcout << \"-- Natural Frequencies --\" << endl;\r\n\t\t\t// Create a 2x2 matrix using Eigen\r\n\t\t\t// Mass matrix of the system, from eqtns of motion\r\n\t\t\tMatrix2d M;\r\n\t\t\tM(0, 0) = mass;\r\n\t\t\tM(1, 0) = 0;\r\n\t\t\tM(0, 1) = 0;\r\n\t\t\tM(1, 1) = inertia;\r\n\t\t\tcout << \"The mass matrix, M, of this system is: \\n\" << M << \"\\n\" << endl;\r\n\r\n\t\t\t// Create a 2x2 matrix using Eigen\r\n\t\t\t// Stiffness matrix of the system, from eqtns of motion\r\n\t\t\tMatrix2d K;\r\n\t\t\tK(0, 0) = stiffness_f + stiffness_r;\r\n\t\t\tK(1, 0) = (stiffness_r*rearLength) - (stiffness_f*frontLength);\r\n\t\t\tK(0, 1) = K(1, 0);\r\n\t\t\tK(1, 1) = (stiffness_f*pow(frontLength, 2)) + (stiffness_r*pow(rearLength, 2));\r\n\t\t\tcout << \"The stiffness matrix, K, is: \\n\" << K << \"\\n\" << endl;\r\n\r\n\t\t\t// Find eigenvalues of M,K\r\n\t\t\tGeneralizedSelfAdjointEigenSolver<MatrixXd> es(K, M);\r\n\t\t\tdouble lambda1 = es.eigenvalues()[0];\r\n\t\t\tdouble lambda2 = es.eigenvalues()[1];\r\n\r\n\t\t\t// Natural frequencies equal the sqrt of the eigenvalues\r\n\t\t\tw1 = sqrt(lambda1);\r\n\t\t\tw2 = sqrt(lambda2);\r\n\r\n\t\t\tcout << setprecision(4) << \"The undamped natural frequencies of the system are \" << w1 << \" rad/s and \" << w2 << \" rad/s.\\n\" << endl;\r\n\t\t}\r\n\r\n};\r\n\r\n\r\n// ODE integration parameters class used to solve equations (inherits data from Vehicle & Road class)\r\nclass analysisParam\r\n{\r\n\tpublic:\r\n\t\tdouble t0, tf, dt;\r\n\t\tdouble x_init1, x_init2, x_init3, x_init4;\r\n\r\n\t\tvoid getInterval()\r\n\t\t{\r\n\t\t\tcout << \"-- Forced Excitation --\" << endl;\r\n\t\t\tcout << \"Enter the starting time of the interval (s): \"; cin >> t0;\r\n\t\t\tcout << \"Enter the ending time of the interval (s): \"; cin >> tf;\r\n\t\t\tcout << \"Enter the desired time increment (s): \"; cin >> dt;\r\n\t\t}\r\n\r\n\t\tvoid getIntitialCond()\r\n\t\t{\r\n\t\t\tcout << \"\\nEnter the initial value of the bounce, (m): \"; cin >> x_init1;\r\n\t\t\tcout << \"Enter the initial value of the rate of change of the bounce (m/s): \"; cin >> x_init2;\r\n\t\t\tcout << \"Enter the initial value of the pitch (rad): \"; cin >> x_init3;\r\n\t\t\tcout << \"Enter the initial value of the rate of change of the pitch (rad/s): \"; cin >> x_init4;\r\n\t\t}\r\n};\r\n\r\nclass coupledODE\r\n{\r\n\t//double m_param, J_param, kf_param, kr_param, cf_param, cr_param, l1_param, l2_param, A_param, radF_param, L_param;\r\n\t//coupledODE(double m, double J, double kf, double kr, double cf, double cr, double l1, double l2, double Amp, double radialF, double waveL) : m_param(m), J_param(J), kf_param(kf), kr_param(kr), cf_param(cf), cr_param(cr), l1_param(l1), l2_param(l2), A_param(Amp), radF_param(radialF), L_param(waveL) {};\r\n\r\n\tpublic:\r\n\t\tVehicle car; Road road;\r\n\t\tcoupledODE(const Vehicle& car1, const Road& road1) : car(car1), road(road1) {};\r\n\r\n\r\n\t\tvoid operator()(state_type &x, state_type &dxdt, double t)\r\n\t\t{\r\n\t\t\tdouble wave_f = car.stiffness_f*road.A*sin((road.radFreq)*t);\r\n\t\t\tdouble wave_r = car.stiffness_r*road.A*sin((road.radFreq)*t - (2 * pi*(car.frontLength + car.rearLength)) / road.L);\r\n\r\n\t\t\tdouble term1f = car.stiffness_f*x[0] + car.damping_f*x[1];\r\n\t\t\tdouble term1r = car.stiffness_r*x[0] + car.damping_r*x[1];\r\n\t\t\tdouble term2f = car.stiffness_f*x[2] + car.damping_f*x[3];\r\n\t\t\tdouble term2r = car.stiffness_r*x[2] + car.damping_r*x[3];\r\n\t\t\tdouble term3f = -term1f + term2f*car.frontLength + wave_f;\r\n\t\t\tdouble term3r = -term1r - term2r*car.rearLength + wave_r;\r\n\r\n\t\t\tdxdt[0] = x[1];\r\n\t\t\tdxdt[1] = (1 / car.mass)*(term3f + term3r);\r\n\t\t\tdxdt[2] = x[3];\r\n\t\t\tdxdt[3] = (1 / car.inertia)*(-term3f*car.frontLength + term3r*car.rearLength);\r\n\t\t}\r\n};\r\n\r\n// Structure to write values generated by integration to vectors\r\nstruct writeVals\r\n{\r\n\tstd::vector< state_type >& m_states;\r\n\tstd::vector< double >& m_time;\r\n\r\n\twriteVals(std::vector< state_type > &states, std::vector< double > &time)\r\n\t\t: m_states(states), m_time(time) { }\r\n\r\n\tvoid operator()(const state_type &x, double t)\r\n\t{\r\n\t\tm_states.push_back(x);\r\n\t\tm_time.push_back(t);\r\n\t}\r\n};\r\n\r\nint main()\r\n{\r\n\tanalysisParam calcParams;\r\n\tVehicle car;\r\n\tRoad road;\r\n\r\n\tcout << \"2-DoF Vehicle Vibration Analysis\\n\" << endl;\r\n\tcout << \"\\n------ Vehicle Properties ------\\n\" << endl;\r\n\tif (car.setUserChoice() == 0)\r\n\t{\r\n\t\texit(0);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcar.setVehicleParameters();\r\n\t\tcout << \"\\n------ Driving Conditions ------\\n\" << endl;\r\n\t\troad.getRoadValues();\r\n\r\n\t\tcout << \"\\n------ System Analysis ------\\n\" << endl;\r\n\t\tcar.calcNatFreq();\r\n\t\tcalcParams.getInterval();\r\n\t\tcalcParams.getIntitialCond();\r\n\r\n\r\n\t\t// Redefine input from analysisParams to useable values for odeint evaluation\r\n\t\tstate_type x(4);\t\t// Define state vector to hold initial values\r\n\t\tx[0] = calcParams.x_init1;\t\t// value of x[0] (bounce)\r\n\t\tx[1] = calcParams.x_init2;\t\t// value of x[1] (rate of change of bounce, x')\r\n\t\tx[2] = calcParams.x_init3;\t\t// value of x[2] (pitch)\r\n\t\tx[3] = calcParams.x_init4;\t\t// value of x[3] (rate of change of pitch, theta')\r\n\t\tvector<state_type> x_vec;\r\n\t\tvector<double> times;\r\n\r\n\t\tconst double timeStep = calcParams.dt;\t\t// Time step as defined by user\r\n\t\tdouble tStart = calcParams.t0;\t\t\t\t// Start time as defined by user\r\n\t\tdouble tEnd = calcParams.tf;\t\t\t\t// End time as defined by user\r\n\r\n\r\n\t\t// Initialize odeint using standard rk5 integration (DOES NOT WORK)\r\n\t\t//typedef runge_kutta_dopri5<state_type> rk5;\r\n\t\t//ntegrate_const(make_dense_output(1E-3, 1E-6, rk5()), coupledODE(car,road), x, tStart, tEnd, timeStep, writeVals(x_vec, times));\r\n\r\n\t\t// Initialize odeint using Burlisch Stoer\r\n\t\tbulirsch_stoer_dense_out< state_type > stepper(1E-8, 0.0, 0.0, 0.0);\r\n\t\tintegrate_const(stepper, coupledODE(car, road), x, tStart, tEnd, timeStep, writeVals(x_vec, times));\r\n\r\n\t\tofstream out(\"results.txt\");\r\n\t\tif (out.is_open())\r\n\t\t{\r\n\t\t\tdouble n = (tEnd - tStart) / timeStep;\r\n\t\t\tout << \"System Analysis Results\\n\";\r\n\t\t\tout << \"Time\" << \"\\t\" << \"Bounce\" << \"\\t\" << \"Pitch\" << endl;\r\n\t\t\tfor (int i = 0; i <= n; i++)\r\n\t\t\t{\r\n\t\t\t\tout << setprecision(8) << times[i] << \"\\t\" << x_vec[i][0] << \"\\t\" << x_vec[i][2] << endl;\r\n\t\t\t}\r\n\t\t\tout.close();\r\n\t\t}\r\n\r\n\t\tcout << \"\\n------ System results written to file ------\\n\" << endl;\r\n\t\t\r\n\t\r\n\t\t\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "278082e5cc18a929a2540ce98188e188cd95cb33", "size": 12614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2dof_c.cpp", "max_stars_repo_name": "armstrongc93/2dof_vibration", "max_stars_repo_head_hexsha": "145402618157a40ea911578f0de6febd8e66d51d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2dof_c.cpp", "max_issues_repo_name": "armstrongc93/2dof_vibration", "max_issues_repo_head_hexsha": "145402618157a40ea911578f0de6febd8e66d51d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2dof_c.cpp", "max_forks_repo_name": "armstrongc93/2dof_vibration", "max_forks_repo_head_hexsha": "145402618157a40ea911578f0de6febd8e66d51d", "max_forks_repo_licenses": ["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.1364902507, "max_line_length": 306, "alphanum_fraction": 0.628825115, "num_tokens": 3933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5107509340426329}}
{"text": "/*\n * Bayes++ the Bayesian Filtering Library\n * Copyright (c) 2004 Michael Stevens\n * See accompanying Bayes++.htm for terms and conditions of use.\n *\n * $Id$\n */\n\n/*\n * Test the FastSLAM algorithm\n */\n\n\t\t// Bayes++ Bayesian filtering schemes\n#include \"BayesFilter/SIRFlt.hpp\"\n#include \"BayesFilter/covFlt.hpp\"\n#include \"BayesFilter/unsFlt.hpp\"\n#include \"BayesFilter/models.hpp\"\n\t\t// Types required for SLAM classes\n#include <vector>\n#include <map>\n\t\t// Bayes++ SLAM\n#include \"SLAM.hpp\"\n#include \"fastSLAM.hpp\"\n#include \"kalmanSLAM.hpp\"\n\n#include \"Test/random.hpp\"\n#include <iostream>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/lexical_cast.hpp> \n\nusing namespace SLAM_filter;\n\n\nclass SLAM_random : public Bayesian_filter_test::Boost_random, public BF::SIR_random\n/*\n * Random numbers for SLAM test\n */\n{\npublic:\n\tFM::Float normal (const FM::Float mean, const FM::Float sigma)\n\t{\n\t\treturn Boost_random::normal (mean, sigma);\n\t}\n\tvoid normal (FM::DenseVec& v)\n\t{\n\t\tBoost_random::normal (v);\n\t}\n\tvoid uniform_01 (FM::DenseVec& v)\n\t{\n\t\tBoost_random::uniform_01 (v);\n\t}\n\tvoid seed ()\n\t{\n\t\tBoost_random::seed();\n\t}\n};\n\n\n/*\n * Demonstrate a SLAM example\n */\nstruct SLAMDemo\n{\n\tconst unsigned nParticles;\n\t\n\tSLAMDemo (unsigned setnParticles) : nParticles(setnParticles)\n\t{}\n\tvoid OneDExperiment ();\n\tvoid InformationLossExperiment ();\n\t\n\tSLAM_random goodRandom;\n\n\t// Relative Observation with  Noise model\n\tstruct Simple_observe : BF::Linear_uncorrelated_observe_model\n\t{\n\t\tSimple_observe (Float i_Zv) : Linear_uncorrelated_observe_model(2,1)\n\t\t// Construct a linear model with const Hx\n\t\t{\n\t\t\tHx(0,0) = -1.;\t// Location\n\t\t\tHx(0,1) = 1.;\t// Map\n\t\t\tZv[0] = i_Zv;\n\t\t}\n\t};\n\tstruct Simple_observe_inverse : BF::Linear_uncorrelated_observe_model\n\t{\n\t\tSimple_observe_inverse (Float i_Zv) : Linear_uncorrelated_observe_model(2,1)\n\t\t{\n\t\t\tHx(0,0) = 1.;\t// location\n\t\t\tHx(0,1) = 1.;\t// observation\n\t\t\tZv[0] = i_Zv;\n\t\t}\n\t};\n\n\tstruct Kalman_statistics : public BF::Kalman_state_filter\n\t// Kalman_statistics without any filtering\n\t{\n\t\tKalman_statistics (std::size_t x_size) : Kalman_state_filter(x_size) {}\n\t\tvoid init() {}\n\t\tvoid update() {}\n\t};\n\n\ttemplate <class Filter>\n\tstruct Generic_kalman_generator : public Kalman_filter_generator\n\t// Generate and dispose of generic kalman filter type\n\t{\n\t\tFilter_type* generate( unsigned full_size )\n\t\t{\n\t\t\treturn new Filter(full_size);\n\t\t}\n\t\tvoid dispose( Filter_type* filter )\n\t\t{\n\t\t\tdelete filter;\n\t\t}\n\t};\n\n\n\tvoid display( const std::string label, const BF::Kalman_state_filter& stats)\n\t{\n\t\tstd::cout << label << stats.x << stats.X << std::endl;\n\t}\n};\n\n\nvoid SLAMDemo::OneDExperiment ()\n// Experiment with a one dimensional problem\n//  Use to look at implication of highly correlated features\n{\n\t// State size\n\tconst unsigned nL = 1;\t// Location\n\tconst unsigned nM = 2;\t// Map\n\n\t// Construct simple Prediction models\n\tBF::Sampled_LiAd_predict_model location_predict(nL,1, goodRandom);\n\t// Stationary Prediction model (Identity)\n\tFM::identity(location_predict.Fx);\n\t\t\t\t// Constant Noise model\n\tlocation_predict.q[0] = 1000.;\n\tlocation_predict.G.clear();\n\tlocation_predict.G(0,0) = 1.;\n\n\t// Relative Observation with  Noise model\n\tSimple_observe observe0(5.), observe1(3.);\n\tSimple_observe_inverse observe_new0(5.), observe_new1(3.);\n\n\t// Setup the initial state and covariance\n\t// Location with no uncertainty\n\tFM::Vec x_init(nL); FM::SymMatrix X_init(nL, nL);\n\tx_init[0] = 20.;\n\tX_init(0,0) = 0.;\n\n\t// Truth model : location plus one map feature\n\tFM::Vec true0(nL+1), true1(nL+1);\n\ttrue0.sub_range(0,nL) = x_init; true0[nL] = 50.;\n\ttrue1.sub_range(0,nL) = x_init; true1[nL] = 70.;\n\tFM::Vec z(1);\n\n\t// Filter statistics for display\n\tKalman_statistics stat(nL+nM);\n\n\t// Kalman_SLAM filter:\n\tGeneric_kalman_generator<BF::Covariance_scheme> full_gen;\n\tKalman_SLAM kalm (full_gen);\n\tkalm.init_kalman (x_init, X_init);\n\n\t// Fast_SLAM filter\n\tBF::SIR_kalman_scheme fast_location (nL, nParticles, goodRandom);\n\tfast_location.init_kalman (x_init, X_init);\n\tFast_SLAM_Kstatistics fast (fast_location);\n\n\t// Initial feature states\n\tz = observe0.h(true0);\t\t// Observe a relative position between location and map landmark\n\tz[0] += 0.5;\t\t\t\n\tkalm.observe_new (0, observe_new0, z);\n\tfast.observe_new (0, observe_new0, z);\n\n\tz = observe1.h(true1);\n\tz[0] += -1.0;\t\t\n\tkalm.observe_new (1, observe_new1, z);\n\tfast.observe_new (1, observe_new1, z);\n\n\tfast.update(); fast.statistics_sparse(stat); display(\"Feature Fast\", stat);\n\tkalm.update(); kalm.statistics_sparse(stat); display(\"Feature Kalm\", stat);\n\n\t// Predict the location state forward\n\tfast_location.predict (location_predict);\n\tkalm.predict (location_predict);\n\tfast.update(); fast.statistics_sparse(stat); display(\"Predict Fast\", stat);\n\tkalm.update(); kalm.statistics_sparse(stat); display(\"Predict Kalm\", stat);\n\n\t// Observation feature 0\n\tz = observe0.h(true0);\n\tz[0] += 0.5;\t\t\t// Observe a relative position between location and map landmark\n\tfast.observe( 0, observe0, z );\n\tkalm.observe( 0, observe0, z );\n\tfast.update(); fast.statistics_sparse(stat); display(\"ObserveA Fast\", stat);\n\tkalm.update(); kalm.statistics_sparse(stat); display(\"ObserveA Kalm\", stat);\n\n\t// Observation feature 1\n\tz = observe1.h(true1);\n\tz[0] += 1.0;\t\t\t// Observe a relative position between location and map landmark\n\tfast.observe( 1, observe1, z );\n\tkalm.observe( 1, observe1, z );\n\tfast.update(); fast.statistics_sparse(stat); display(\"ObserveB Fast\", stat);\n\tkalm.update(); kalm.statistics_sparse(stat); display(\"ObserveB Kalm\", stat);\n\n\t// Observation feature 0\n\tz = observe0.h(true0);\n\tz[0] += 0.5;\t\t\t// Observe a relative position between location and map landmark\n\tfast.observe( 0, observe0, z );\n\tkalm.observe( 0, observe0, z );\n\tfast.update(); fast.statistics_sparse(stat); display(\"ObserveC Fast\", stat);\n\tkalm.update(); kalm.statistics_sparse(stat); display(\"ObserveC Kalm\", stat);\n\n\t// Forget feature 0\n\tfast.forget(0);\n\tkalm.forget(0);\n\tfast.update(); fast.statistics_sparse(stat); display(\"Forget Fast\", stat);\n\tkalm.update(); kalm.statistics_sparse(stat); display(\"Forget Kalm\", stat);\n}\n\n\nvoid SLAMDemo::InformationLossExperiment ()\n// Experiment with information loss due to resampling\n{\n\t// State size\n\tconst unsigned nL = 1;\t// Location\n\tconst unsigned nM = 2;\t// Map\n\n\t// Construct simple Prediction models\n\tBF::Sampled_LiAd_predict_model location_predict(nL,1, goodRandom);\n\t// Stationary Prediction model (Identity)\n\tFM::identity(location_predict.Fx);\n\t\t\t\t// Constant Noise model\n\tlocation_predict.q[0] = 1000.;\n\tlocation_predict.G.clear();\n\tlocation_predict.G(0,0) = 1.;\n\n\t// Relative Observation with  Noise model\n\tSimple_observe observe0(5.), observe1(3.);\n\tSimple_observe_inverse observe_new0(5.), observe_new1(3.);\n\n\t// Setup the initial state and covariance\n\t// Location with no uncertainty\n\tFM::Vec x_init(nL); FM::SymMatrix X_init(nL, nL);\n\tx_init[0] = 20.;\n\tX_init(0,0) = 0.;\n\n\t// Truth model : location plus one map feature\n\tFM::Vec true0(nL+1), true1(nL+1);\n\ttrue0.sub_range(0,nL) = x_init; true0[nL] = 50.;\n\ttrue1.sub_range(0,nL) = x_init; true1[nL] = 70.;\n\tFM::Vec z(1);\n\n\t// Filter statistics for display\n\tKalman_statistics stat(nL+nM);\n\n\t// Kalman_SLAM filter\n\tGeneric_kalman_generator<BF::Unscented_scheme> full_gen;\n\tKalman_SLAM kalm (full_gen);\n\tkalm.init_kalman (x_init, X_init);\n\n\t// Fast_SLAM filter\n\tBF::SIR_kalman_scheme fast_location (nL, nParticles, goodRandom);\n\tfast_location.init_kalman (x_init, X_init);\n\tFast_SLAM_Kstatistics fast (fast_location);\n\n\t// Initial feature states\n\tz = observe0.h(true0);\t\t// Observe a relative position between location and map landmark\n\tz[0] += 0.5;\t\t\t\n\tkalm.observe_new (0, observe_new0, z);\n\tfast.observe_new (0, observe_new0, z);\n\n\tz = observe1.h(true1);\n\tz[0] += -1.0;\t\t\n\tkalm.observe_new (1, observe_new1, z);\n\tfast.observe_new (1, observe_new1, z);\n\n\tunsigned it = 0;\n\tfor (;;) {\n\t\t++it;\n\t\tstd::cout << it << std::endl;\n\t\t\n\t\t// Groups of observations without resampling\n\t\t{\n\t\t\t// Predict the filter forward\n\t\t\tkalm.predict (location_predict);\n\t\t\tfast_location.predict (location_predict);\n\n\t\t\t// Observation feature 0 with bias\n\t\t\tz = observe0.h(true0);\t\t// Observe a relative position between location and map landmark\n\t\t\tz[0] += 0.5;\n\t\t\tkalm.observe( 0, observe0, z );\n\t\t\tfast.observe( 0, observe0, z );\n\n\t\t\t// Predict the filter forward\n\t\t\tkalm.predict (location_predict);\n\t\t\tfast_location.predict (location_predict);\n\n\t\t\t// Observation feature 1 with bias\n\t\t\tz = observe1.h(true1);\t\t// Observe a relative position between location and map landmark\n\t\t\tz[0] += -1.0;\t\t\n\t\t\tkalm.observe( 1, observe1, z );\n\t\t\tfast.observe( 1, observe1, z );\n\t\t}\n\n\t\t// Update and resample\n\t\tkalm.update();\n\t\tfast.update();\n\t\t\n\t\tkalm.statistics_sparse(stat); display(\"Kalm\", stat);\n\t\tfast.statistics_sparse(stat); display(\"Fast\", stat);\n\t\tstd::cout << fast_location.stochastic_samples <<','<< fast_location.unique_samples()\n\t\t\t<<' '<< fast.feature_unique_samples(0) <<','<< fast.feature_unique_samples(1) <<std::endl;\n\t\tstd::cout.flush();\n\t}\n}\n\n\nint main (int argc, char* argv[])\n{\n\t// Global setup for test output\n\tstd::cout.flags(std::ios::fixed); std::cout.precision(4);\n\n\tunsigned nParticles = 1000;\n\tif (argv[1])\n\t{\n    \ttry {\n\t\t\tnParticles = boost::lexical_cast<unsigned>(argv[1]);\n\t\t}\n\t\tcatch (boost::bad_lexical_cast) {\n\t\t\t// ignore error and use default\n\t\t}\n\t}\n\tstd::cout << \"nParticles = \" << nParticles << std::endl;\n\n\t// Create test and run experiments\n\ttry {\n\t\tSLAMDemo test(nParticles);\n\t\ttest.OneDExperiment();\n\t\t//test.InformationLossExperiment();\n\t}\n\tcatch (const BF::Filter_exception& ne)\n\t{\n\t\tstd::cout << ne.what() << std::endl;\n\t}\n}\n", "meta": {"hexsha": "e83e5367504115f01dcc9b117bafbc78990e8e85", "size": 9583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SLAM/testFastSLAM.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": "SLAM/testFastSLAM.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": "SLAM/testFastSLAM.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": 27.6167146974, "max_line_length": 93, "alphanum_fraction": 0.7029114056, "num_tokens": 2805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5107509340426329}}
{"text": "#include <string>\n#include <NTL/ZZ.h>\n#include <sstream>\n\ninline std::string\nStringFromZZ(const NTL::ZZ &x)\n{\n    std::string s;\n    s.resize(NumBytes(x), 0);\n    NTL::BytesFromZZ((uint8_t*) &s[0], x, s.length());\n    return s;\n}\n\n// returns ZZ from a string representing the ZZ in base 256\ninline NTL::ZZ\nZZFromString(const std::string &s)\n{\n    return NTL::ZZFromBytes((const uint8_t *) s.data(), s.length());\n}\n\n\n// converts ZZ to and from a string representing the number in decimal\n\ninline std::string\nDecStringFromZZ(const NTL::ZZ & x) {\n    std::stringstream ss;\n    ss << x;\n    return ss.str();\n}\n\ninline NTL::ZZ\nZZFromDecString(const std::string &s) {\n    NTL::ZZ v;\n    std::stringstream ss(s);\n    ss >> v;\n    return v;\n}\n", "meta": {"hexsha": "e340599c8f1c84a8bccac9035582a43c1b81d64e", "size": 735, "ext": "hh", "lang": "C++", "max_stars_repo_path": "ope-from-cryptodb/lib/zz.hh", "max_stars_repo_name": "xietian1/mpkix-judgement", "max_stars_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "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": "ope-from-cryptodb/lib/zz.hh", "max_issues_repo_name": "xietian1/mpkix-judgement", "max_issues_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "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": "ope-from-cryptodb/lib/zz.hh", "max_forks_repo_name": "xietian1/mpkix-judgement", "max_forks_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3421052632, "max_line_length": 70, "alphanum_fraction": 0.6448979592, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5107509167263166}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2014 by Synge Todo <wistaria@comp-phys.org>\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// C++ version of TITPACK Ver.2 by H. Nishimori\n\n#ifndef TITPACK_COMMON_HPP\n#define TITPACK_COMMON_HPP\n\n#include \"subspace.hpp\"\n#include <vector>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/tuple/tuple.hpp>\n\ntypedef boost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> matrix_type;\ntypedef boost::numeric::ublas::matrix<int, boost::numeric::ublas::column_major> i_matrix_type;\n\n//\n// eigenvalues by the bisection method\n//\n// return value # m and nsplit\n// alpha  @ diagonal element\n// beta   @ subdiagonal element\n// ndim   @ matrix dimension\n// E      # eigenvalues\n// ne     @ number of eigenvalues to calculate\n// eps    @ limit of error\n\nboost::tuple<int, int>\nbisec(std::vector<double> const& alpha, std::vector<double> const& beta, int ndim,\n      std::vector<double>& E, int ne, double eps, std::vector<int>& iblock,\n      std::vector<int>& isplit, double *w);\n\n//\n// eigenvector of a tridiagonal matrix by inverse iteration for the large/medium routines\n// \n// E(4)       @  4 lowest eigenvalues\n// ndim       @  matrix dimension\n// nvec       @  number of vectors to calculate\n\nvoid vec12(std::vector<double> const& alpha, std::vector<double> const& beta, int ndim,\n           std::vector<double> const& E, int nvec, matrix_type& z,\n           std::vector<int>& iblock, std::vector<int>& isplit, double *w);\n\n//\n// xx correlation function\n//\n// n           @ lattice size\n// npair       @ pair of sites (k,l) <Sx(k)Sx(l)>\n// x           @ eigenvetor\n// sxx         # xx correlation function\n// list1,list2 @ spin configurations generated in 'sz'\n\nvoid xcorr(subspace const& ss, std::vector<int> const& npair, const double *x,\n           std::vector<double>& sxx);\n\nvoid xcorr(subspace const& ss, std::vector<int> const& npair,\n           std::vector<double> const& x, std::vector<double>& sxx);\n\nvoid xcorr(subspace const& ss, std::vector<int> const& npair,\n           matrix_type const& x, int xindex, std::vector<double>& sxx);\n\n//\n// ************* zz correlation function **************\n//\n// n           @ lattice size\n// npair       @ pair of sites (k,l) <Sz(k)Sz(l)>\n// x           @ eigenvetor\n// szz         # zz correlation function\n// list1,list2 @ spin configurations generated in 'sz'\n\nvoid zcorr(subspace const& ss, std::vector<int> const& npair, const double *x,\n           std::vector<double>& szz);\n\nvoid zcorr(subspace const& ss, std::vector<int> const& npair,\n           matrix_type const& x, int xindex, std::vector<double>& szz);\n\nvoid zcorr(subspace const& ss, std::vector<int> const& npair,\n           std::vector<double> const& x, std::vector<double>& szz);\n\n//\n// Orthogonalization of the eigenvectors\n//\n// return value #  degree of degenearcy\n// ev      @# vectors to be orthogonalized / orthogonalized vectors\n// norm(j) #  norm of the j-th vector returned\n// numvec  @  number of vectors to be checked\n\nint orthg(matrix_type& ev, std::vector<double>& norm, int numvec);\n\n//\n// configurations with the specified sz\n//\n// n          @  lattice size\n// idim       @  dimension of the matrix\n// szval      @  total sz\n// list1(i)   #  i-th spin configuration\n// list2      #  inverse list of list1 expressed by the\n//               2-dim search method of M. Ogata and H.Q. Lin.\n// ==============================================================\n//      This routine is equivalent to sz but is faster than sz.\n//      This routine has been developed by Daijiro Yoshioka,\n//      University of Tokyo.  The copyright of szdy belongs to him.\n//                                              1993/5/10\n// ==============================================================\n\nvoid szdy(int n, int idim, double szval, std::vector<int>& list1,\n          std::vector<std::vector<int> >& list2);\n\n#endif\n", "meta": {"hexsha": "c6f6a5e73949631d0ae126460ef99258adbf43df", "size": 4244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tutorial/titpack/02_refactored_cxx/common.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": "tutorial/titpack/02_refactored_cxx/common.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": "tutorial/titpack/02_refactored_cxx/common.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": 35.6638655462, "max_line_length": 95, "alphanum_fraction": 0.6060320452, "num_tokens": 1083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5107509167263166}}
{"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, lbeta) {\n  using stan::math::lbeta;\n\n  EXPECT_FLOAT_EQ(0.0, lbeta(1.0, 1.0));\n  EXPECT_FLOAT_EQ(2.981361, lbeta(0.1, 0.1));\n  EXPECT_FLOAT_EQ(-4.094345, lbeta(3.0, 4.0));\n  EXPECT_FLOAT_EQ(-4.094345, lbeta(4.0, 3.0));\n}\n\nTEST(MathFunctions, lbeta_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::lbeta(nan, 1.0));\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::lbeta(1.0, nan));\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::lbeta(nan, nan));\n}\n", "meta": {"hexsha": "ca2685aee0445a79ab41a69e46770279d98a2ed8", "size": 689, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/lbeta_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/lbeta_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/lbeta_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": 28.7083333333, "max_line_length": 72, "alphanum_fraction": 0.6966618287, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.5107509042934019}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <Windows.h>\n\n\n#ifdef min\n#undef min\n#endif\n\n#ifdef max\n#undef max\n#endif\n\n#include <Eigen\\Dense>\n#include <Image.h>\n\n\n#include \"CorrelationMat.h\"\n\n#include \"GDMPCA.h\"\n#include \"SPLH.h\"\n\nint main(int argc, char **argv)\n{\n\tEigen::setNbThreads(4);\n\tstd::clog << \"Eigen::nbThreads() = \" << Eigen::nbThreads() << std::endl;\n\n\n\tstd::clog << \"Eigen::nbThreads() = \" << Eigen::nbThreads() << std::endl;\n\n\tstd::vector<Image> images;\n\n\tstd::clog << \"Loading data... \" << std::endl;\n\n\tint M = 32 * 32 * 3;\n\n\t//M = 1024;\n\n\tfor (int i = 1; i < argc; ++i)\n\t{\n\t\tstd::clog << \"\\t\" << argv[i] << std::endl;\n\t\tstd::ifstream input(argv[i], std::ios::binary);\n\t\tauto imgs = LoadBatch(input);\n\t\timages.insert(images.end(), imgs.begin(), imgs.end());\n\n\t\t//LoadBatch(input, subCorrMat);\n\t}\n\n\t//while (images.size() > 100)\n\t//\timages.pop_back();\n\n\tstd::clog << \"DONE\" << std::endl;\n\n\tint N = images.size();\n\n\tstd::clog << \"Creating matrix X(\" << M << \"x\" << N << \")... \";\n\n\tint L = 0;\n\tfor (auto img : images)\n\t\tif (img.label != 255)\n\t\t\t++L;\n\n\tEigen::MatrixXf X(M, N);\n\tEigen::MatrixXf Xl(M, L);\n\n\t//Eigen::MatrixXf mi = subCorrMat.Mean();\n\tEigen::MatrixXf mi = Eigen::MatrixXf::Zero(M, 1);\n\t\n\tfor (int i = 0; i < M; ++i)\n\t\tfor (int j = 0; j < N; ++j)\n\t\t{\n\t\t\tdouble v = images[j].v[i] / 255.0f;\n\t\t\tX(i, j) = v;\n\t\t\tmi(i, 0) += v;\n\t\t}\n\n\tint tl = 0;\n\tfor (auto img : images)\n\t\tif (img.label != 255)\n\t\t{\n\t\t\tfor (int i = 0; i < M; ++i)\n\t\t\t\tXl(i, tl) = img.v[i] / 255.0f;\n\t\t\t++tl;\n\t\t}\n\n\tfor (int i = 0; i < M; ++i)\n\t\tmi(i, 0) /= N;\n\n\tfor (int i = 0; i < M; ++i)\n\t\tfor (int j = 0; j < N; ++j)\n\t\t{\n\t\t\tX(i, j) -= mi(i,0);\n\t\t}\n\t\n\n\tstd::clog << \"DONE\" << std::endl;\n\n\tstd::clog << \"Creating matrix S(\"<<L<<\"x\"<<L<<\")... \";\n\n\tEigen::MatrixXf S(L, L);\n\tfor (int i = 0; i < L; ++i)\n\t\tfor (int j = 0; j < L; ++j)\n\t\t\tS(i, j) = images[i].label == images[j].label ? 1 : -1;\n\n\tstd::clog << \"DONE\" << std::endl;\n\t\n\t/*\n\tstd::clog << \"Creating matrix M... \";\n\n\tEigen::MatrixXf Me(M, M);\n\t//Eigen::MatrixXf Me = subCorrMat.CorrelationMatrix();\n\tdouble beta = 0.3;\n\n\tMe = Xl * S * Xl.transpose();\n\tMe += beta * (X * X.transpose());\n\n\tstd::clog << \"DONE\" << std::endl;\n\t*/\n\tstd::clog << \"Matrix deflation... \" << std::endl;\n\n\tint H = 64;\n\n\t//auto x = OrtogonalDeflation(Me, H);\n\t//auto x = GDMPCA(Me, 10);\n\tauto x = SPLH(X, Xl, S, H, 1.0 / M, 0.3);\n\n\tstd::clog << \"DONE\" << std::endl;\n\n\tstd::cout << H << \" \" << M << std::endl;\n\tfor (auto &v : x)\n\t\tstd::cout << -mi.transpose() * v << \"\\t\" << v.transpose() << std::endl;\n\n\treturn 0;\n}", "meta": {"hexsha": "4e3d557dece5b460a2cc5fe5aa6a573ceb5daca1", "size": 2551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "learning/SPLH/main.cpp", "max_stars_repo_name": "HAL90000/tirt", "max_stars_repo_head_hexsha": "60eea9bde89b579eabfd11e5ee0ba3910d24f4a0", "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": "learning/SPLH/main.cpp", "max_issues_repo_name": "HAL90000/tirt", "max_issues_repo_head_hexsha": "60eea9bde89b579eabfd11e5ee0ba3910d24f4a0", "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": "learning/SPLH/main.cpp", "max_forks_repo_name": "HAL90000/tirt", "max_forks_repo_head_hexsha": "60eea9bde89b579eabfd11e5ee0ba3910d24f4a0", "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": 18.8962962963, "max_line_length": 73, "alphanum_fraction": 0.5268522148, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.5107425738058502}}
{"text": "#include \"Scheme.h\"\n\n#include <NTL/BasicThreadPool.h>\n#include <NTL/RR.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n\n#include \"EvaluatorUtils.h\"\n#include \"NumUtils.h\"\n#include \"Ring2Utils.h\"\n#include \"StringUtils.h\"\n\n//-----------------------------------------\n\nScheme::Scheme(Context& context) : context(context) {\n}\n\nScheme::Scheme(SecretKey& secretKey, Context& context) : context(context) {\n\taddEncKey(secretKey);\n\taddMultKey(secretKey);\n};\n\n//----------------------------------------------------------------------------------\n//   KEYS GENERATION\n//----------------------------------------------------------------------------------\n\n\nvoid Scheme::addEncKey(SecretKey& secretKey) {\n\tZZX ex, ax, bx;\n\n\tNumUtils::sampleUniform2(ax, context.N, context.logQQ);\n\tNumUtils::sampleGauss(ex, context.N, context.sigma);\n\tRing2Utils::mult(bx, secretKey.sx, ax, context.QQ, context.N);\n\tRing2Utils::sub(bx, ex, bx, context.QQ, context.N);\n\n\tkeyMap.insert(pair<long, Key>(ENCRYPTION, Key(ax, bx)));\n}\n\nvoid Scheme::addMultKey(SecretKey& secretKey) {\n\tZZX ex, ax, bx, sxsx;\n\n\tRing2Utils::mult(sxsx, secretKey.sx, secretKey.sx, context.Q, context.N);\n\tRing2Utils::leftShiftAndEqual(sxsx, context.logQ, context.QQ, context.N);\n\tNumUtils::sampleUniform2(ax, context.N, context.logQQ);\n\tNumUtils::sampleGauss(ex, context.N, context.sigma);\n\tRing2Utils::addAndEqual(ex, sxsx, context.QQ, context.N);\n\tRing2Utils::mult(bx, secretKey.sx, ax, context.QQ, context.N);\n\tRing2Utils::sub(bx, ex, bx, context.QQ, context.N);\n\n\tkeyMap.insert(pair<long, Key>(MULTIPLICATION, Key(ax, bx)));\n}\n\nvoid Scheme::addConjKey(SecretKey& secretKey) {\n\tZZX ex, ax, bx, sxconj;\n\n\tRing2Utils::conjugate(sxconj, secretKey.sx, context.N);\n\tRing2Utils::leftShiftAndEqual(sxconj, context.logQ, context.QQ, context.N);\n\tNumUtils::sampleUniform2(ax, context.N, context.logQQ);\n\tNumUtils::sampleGauss(ex, context.N, context.sigma);\n\tRing2Utils::addAndEqual(ex, sxconj, context.QQ, context.N);\n\tRing2Utils::mult(bx, secretKey.sx, ax, context.QQ, context.N);\n\tRing2Utils::sub(bx, ex, bx, context.QQ, context.N);\n\n\tkeyMap.insert(pair<long, Key>(CONJUGATION, Key(ax, bx)));\n}\n\nvoid Scheme::addLeftRotKey(SecretKey& secretKey, long rot) {\n\tZZX ex, ax, bx, sxrot;\n\n\tRing2Utils::inpower(sxrot, secretKey.sx, context.rotGroup[rot], context.Q, context.N);\n\tRing2Utils::leftShiftAndEqual(sxrot, context.logQ, context.QQ, context.N);\n\tNumUtils::sampleUniform2(ax, context.N, context.logQQ);\n\tNumUtils::sampleGauss(ex, context.N, context.sigma);\n\tRing2Utils::addAndEqual(ex, sxrot, context.QQ, context.N);\n\tRing2Utils::mult(bx, secretKey.sx, ax, context.QQ, context.N);\n\tRing2Utils::sub(bx, ex, bx, context.QQ, context.N);\n\n\tleftRotKeyMap.insert(pair<long, Key>(rot, Key(ax, bx)));\n}\n\nvoid Scheme::addLeftRotKeys(SecretKey& secretKey) {\n\tfor (long i = 0; i < context.logNh; ++i) {\n\t\tlong idx = 1 << i;\n\t\tif(leftRotKeyMap.find(idx) == leftRotKeyMap.end()) {\n\t\t\taddLeftRotKey(secretKey, idx);\n\t\t}\n\t}\n}\n\nvoid Scheme::addRightRotKeys(SecretKey& secretKey) {\n\tfor (long i = 0; i < context.logNh; ++i) {\n\t\tlong idx = context.N/2 - (1 << i);\n\t\tif(leftRotKeyMap.find(idx) == leftRotKeyMap.end()) {\n\t\t\taddLeftRotKey(secretKey, idx);\n\t\t}\n\t}\n}\n\nvoid Scheme::addSortKeys(SecretKey& secretKey, long size) {\n\tfor (long i = 1; i < size; ++i) {\n\t\tif(leftRotKeyMap.find(i) == leftRotKeyMap.end()) {\n\t\t\taddLeftRotKey(secretKey, i);\n\t\t}\n\t}\n}\n\n\n//----------------------------------------------------------------------------------\n//   ENCODING & DECODING\n//----------------------------------------------------------------------------------\n\n\nPlaintext Scheme::encode(double* vals, long slots, long logp, long logq) {\n\tZZX mx = context.encode(vals, slots, logp + context.logQ);\n\treturn Plaintext(mx, logp, logq, slots, false);\n}\n\nPlaintext Scheme::encode(complex<double>* vals, long slots, long logp, long logq) {\n\tZZX mx = context.encode(vals, slots, logp + context.logQ);\n\treturn Plaintext(mx, logp, logq, slots, true);\n}\n\ncomplex<double>* Scheme::decode(Plaintext& msg) {\n\tZZ q = context.qpowvec[msg.logq];\n\tlong slots = msg.slots;\n\tlong gap = context.Nh / slots;\n\tcomplex<double>* res = new complex<double>[slots];\n\tZZ tmp;\n\n\tfor (long i = 0, idx = 0; i < slots; ++i, idx += gap) {\n\t\trem(tmp, msg.mx[idx], q);\n\t\tif(NumBits(tmp) == msg.logq) tmp -= q;\n\t\tres[i].real(EvaluatorUtils::scaleDownToReal(tmp, msg.logp));\n\n\t\trem(tmp, msg.mx[idx + context.Nh], q);\n\t\tif(NumBits(tmp) == msg.logq) tmp -= q;\n\t\tres[i].imag(EvaluatorUtils::scaleDownToReal(tmp, msg.logp));\n\t}\n\tcontext.fftSpecial(res, slots);\n\treturn res;\n}\n\nPlaintext Scheme::encodeSingle(complex<double> val, long logp, long logq) {\n\tZZX mx;\n\tmx.SetLength(context.N);\n\tmx.rep[0] = EvaluatorUtils::scaleUpToZZ(val.real(), logp + context.logQ);\n\tmx.rep[context.Nh] = EvaluatorUtils::scaleUpToZZ(val.imag(), logp + context.logQ);\n\treturn Plaintext(mx, logp, logq, 1, true);\n}\n\nPlaintext Scheme::encodeSingle(double val, long logp, long logq) {\n\tZZX mx;\n\tmx.SetLength(context.N);\n\tmx.rep[0] = EvaluatorUtils::scaleUpToZZ(val, logp + context.logQ);\n\treturn Plaintext(mx, logp, logq, 1, false);\n}\n\ncomplex<double> Scheme::decodeSingle(Plaintext& msg) {\n\tZZ q = context.qpowvec[msg.logq];\n\n\tcomplex<double> res;\n\tZZ tmp = msg.mx.rep[0] % q;\n\tif(NumBits(tmp) == msg.logq) tmp -= q;\n\tres.real(EvaluatorUtils::scaleDownToReal(tmp, msg.logp));\n\n\tif(msg.isComplex) {\n\t\ttmp = msg.mx.rep[context.Nh] % q;\n\t\tif(NumBits(tmp) == msg.logq) tmp -= q;\n\t\tres.imag(EvaluatorUtils::scaleDownToReal(tmp, msg.logp));\n\t}\n\n\treturn res;\n}\n\n\n//----------------------------------------------------------------------------------\n//   ENCRYPTION & DECRYPTION\n//----------------------------------------------------------------------------------\n\n\nCiphertext Scheme::encryptMsg(Plaintext& msg) {\n\tZZX ax, bx, vx, ex;\n\tKey key = keyMap.at(ENCRYPTION);\n\tZZ qQ = context.qpowvec[msg.logq + context.logQ];\n\n\tNumUtils::sampleZO(vx, context.N);\n\tRing2Utils::mult(ax, vx, key.ax, qQ, context.N);\n\tNumUtils::sampleGauss(ex, context.N, context.sigma);\n\tRing2Utils::addAndEqual(ax, ex, qQ, context.N);\n\n\tRing2Utils::mult(bx, vx, key.bx, qQ, context.N);\n\tNumUtils::sampleGauss(ex, context.N, context.sigma);\n\tRing2Utils::addAndEqual(bx, ex, qQ, context.N);\n\n\tRing2Utils::addAndEqual(bx, msg.mx, qQ, context.N);\n\n\tRing2Utils::rightShiftAndEqual(ax, context.logQ, context.N);\n\tRing2Utils::rightShiftAndEqual(bx, context.logQ, context.N);\n\n\treturn Ciphertext(ax, bx, msg.logp, msg.logq, msg.slots, msg.isComplex);\n}\n\nPlaintext Scheme::decryptMsg(SecretKey& secretKey, Ciphertext& cipher) {\n\tZZ q = context.qpowvec[cipher.logq];\n\n\tZZX mx;\n\tRing2Utils::mult(mx, cipher.ax, secretKey.sx, q, context.N);\n\tRing2Utils::addAndEqual(mx, cipher.bx, q, context.N);\n\n\treturn Plaintext(mx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nCiphertext Scheme::encrypt(double* vals, long slots, long logp, long logq) {\n\tPlaintext msg = encode(vals, slots, logp, logq);\n\treturn encryptMsg(msg);\n}\n\nCiphertext Scheme::encrypt(complex<double>* vals, long slots, long logp, long logq) {\n\tPlaintext msg = encode(vals, slots, logp, logq);\n\treturn encryptMsg(msg);\n}\n\nCiphertext Scheme::encryptZeros(long slots, long logp, long logq) {\n\tCiphertext czeros = encryptSingle(0.0, logp, logq);\n\tczeros.isComplex = true;\n\tczeros.slots = slots;\n\treturn czeros;\n}\ncomplex<double>* Scheme::decrypt(SecretKey& secretKey, Ciphertext& cipher) {\n\tPlaintext msg = decryptMsg(secretKey, cipher);\n\treturn decode(msg);\n}\n\nCiphertext Scheme::encryptSingle(double val, long logp, long logq) {\n\tPlaintext msg = encodeSingle(val, logp,  logq);\n\treturn encryptMsg(msg);\n}\n\nCiphertext Scheme::encryptSingle(complex<double> val, long logp, long logq) {\n\tPlaintext msg = encodeSingle(val, logp,  logq);\n\treturn encryptMsg(msg);\n}\n\ncomplex<double> Scheme::decryptSingle(SecretKey& secretKey, Ciphertext& cipher) {\n\tPlaintext msg = decryptMsg(secretKey, cipher);\n\treturn decodeSingle(msg);\n}\n\n\n//----------------------------------------------------------------------------------\n//   HOMOMORPHIC OPERATIONS\n//----------------------------------------------------------------------------------\n\n\nCiphertext Scheme::negate(Ciphertext& cipher) {\n\treturn Ciphertext(-cipher.ax, -cipher.bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nvoid Scheme::negateAndEqual(Ciphertext& cipher) {\n\tcipher.ax = -cipher.ax;\n\tcipher.bx = -cipher.bx;\n}\n\nCiphertext Scheme::add(Ciphertext& cipher1, Ciphertext& cipher2) {\n\tZZ q = context.qpowvec[cipher1.logq];\n\tZZX ax, bx;\n\n\tRing2Utils::add(ax, cipher1.ax, cipher2.ax, q, context.N);\n\tRing2Utils::add(bx, cipher1.bx, cipher2.bx, q, context.N);\n\n\treturn Ciphertext(ax, bx, cipher1.logp, cipher1.logq, cipher1.slots, cipher1.isComplex);\n}\n\nvoid Scheme::addAndEqual(Ciphertext& cipher1, Ciphertext& cipher2) {\n\tZZ q = context.qpowvec[cipher1.logq];\n\n\tRing2Utils::addAndEqual(cipher1.ax, cipher2.ax, q, context.N);\n\tRing2Utils::addAndEqual(cipher1.bx, cipher2.bx, q, context.N);\n}\n\nCiphertext Scheme::addConst(Ciphertext& cipher, double cnst, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\n\tZZX ax = cipher.ax;\n\tZZX bx = cipher.bx;\n\n\tZZ cnstZZ = logp < 0 ? EvaluatorUtils::scaleUpToZZ(cnst, cipher.logp) : EvaluatorUtils::scaleUpToZZ(cnst, logp);\n\n\tAddMod(bx.rep[0], cipher.bx.rep[0], cnstZZ, q);\n\treturn Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nCiphertext Scheme::addConst(Ciphertext& cipher, RR& cnst, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\n\tZZX ax = cipher.ax;\n\tZZX bx = cipher.bx;\n\n\tZZ cnstZZ = logp < 0 ? EvaluatorUtils::scaleUpToZZ(cnst, cipher.logp) : EvaluatorUtils::scaleUpToZZ(cnst, logp);\n\n\tAddMod(bx.rep[0], cipher.bx.rep[0], cnstZZ, q);\n\treturn Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nCiphertext Scheme::addConst(Ciphertext& cipher, complex<double> cnst, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZX ax = cipher.ax;\n\tZZX bx = cipher.bx;\n\n\tZZ cnstrZZ = logp < 0 ? EvaluatorUtils::scaleUpToZZ(cnst.real(), cipher.logp) : EvaluatorUtils::scaleUpToZZ(cnst.real(), logp);\n\tZZ cnstiZZ = logp < 0 ? EvaluatorUtils::scaleUpToZZ(cnst.imag(), cipher.logp) : EvaluatorUtils::scaleUpToZZ(cnst.imag(), logp);\n\n\tAddMod(bx.rep[0], cipher.bx.rep[0], cnstrZZ, q);\n\tAddMod(bx.rep[context.Nh], cipher.bx.rep[context.Nh], cnstiZZ, q);\n\n\treturn Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nCiphertext Scheme::addConst(Ciphertext& cipher, ZZX& poly, long logp) {\n    ZZ q = context.qpowvec[cipher.logq];\n    ZZX ax = cipher.ax;\n    ZZX bx = cipher.bx;\n    \n    Ring2Utils::add(bx, cipher.bx, poly, q, context.N);\n    \n    return Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\n\nvoid Scheme::addConstAndEqual(Ciphertext& cipher, double cnst, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZ cnstZZ = logp < 0 ? EvaluatorUtils::scaleUpToZZ(cnst, cipher.logp) : EvaluatorUtils::scaleUpToZZ(cnst, logp);\n\tAddMod(cipher.bx.rep[0], cipher.bx.rep[0], cnstZZ, q);\n}\n\nvoid Scheme::addConstAndEqual(Ciphertext& cipher, RR& cnst, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZ cnstZZ = logp < 0 ? EvaluatorUtils::scaleUpToZZ(cnst, cipher.logp) : EvaluatorUtils::scaleUpToZZ(cnst, logp);\n\tAddMod(cipher.bx.rep[0], cipher.bx.rep[0], cnstZZ, q);\n}\n\nvoid Scheme::addConstAndEqual(Ciphertext& cipher, complex<double> cnst, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\n\tZZ cnstrZZ = logp < 0 ? EvaluatorUtils::scaleUpToZZ(cnst.real(), cipher.logp) : EvaluatorUtils::scaleUpToZZ(cnst.real(), logp);\n\tZZ cnstiZZ = logp < 0 ? EvaluatorUtils::scaleUpToZZ(cnst.imag(), cipher.logp) : EvaluatorUtils::scaleUpToZZ(cnst.imag(), logp);\n\n\tAddMod(cipher.bx.rep[0], cipher.bx.rep[0], cnstrZZ, q);\n\tAddMod(cipher.bx.rep[context.Nh], cipher.bx.rep[context.Nh], cnstiZZ, q);\n}\n\nvoid Scheme::addConstAndEqual(Ciphertext& cipher, ZZX& poly, long logp) {\n    ZZ q = context.qpowvec[cipher.logq];\n    \n    Ring2Utils::add(cipher.bx, cipher.bx, poly, q, context.N);\n}\n\n\n//-----------------------------------------\n\nCiphertext Scheme::sub(Ciphertext& cipher1, Ciphertext& cipher2) {\n\tZZ q = context.qpowvec[cipher1.logq];\n\tZZX ax, bx;\n\n\tRing2Utils::sub(ax, cipher1.ax, cipher2.ax, q, context.N);\n\tRing2Utils::sub(bx, cipher1.bx, cipher2.bx, q, context.N);\n\n\treturn Ciphertext(ax, bx, cipher1.logp, cipher1.logq, cipher1.slots, cipher1.isComplex);\n}\n\nvoid Scheme::subAndEqual(Ciphertext& cipher1, Ciphertext& cipher2) {\n\tZZ q = context.qpowvec[cipher1.logq];\n\n\tRing2Utils::subAndEqual(cipher1.ax, cipher2.ax, q, context.N);\n\tRing2Utils::subAndEqual(cipher1.bx, cipher2.bx, q, context.N);\n}\n\nvoid Scheme::subAndEqual2(Ciphertext& cipher1, Ciphertext& cipher2) {\n\tZZ q = context.qpowvec[cipher1.logq];\n\n\tRing2Utils::subAndEqual2(cipher1.ax, cipher2.ax, q, context.N);\n\tRing2Utils::subAndEqual2(cipher1.bx, cipher2.bx, q, context.N);\n}\n\n\n\nCiphertext Scheme::subConst2(Ciphertext& cipher, ZZX& poly, long logp) {\n    ZZ q = context.qpowvec[cipher.logq];\n    \n    ZZX ax = - cipher.ax;\n    \n    ZZX bx = cipher.bx;\n    Ring2Utils::sub(bx, poly, cipher.bx, q, context.N);\n    \n    return Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\n\nvoid Scheme::subConstAndEqual2(Ciphertext& cipher, ZZX& poly, long logp) {\n    ZZ q = context.qpowvec[cipher.logq];\n    \n    cipher.ax -= cipher.ax;   // -ax\n    Ring2Utils::subAndEqual(cipher.bx, poly, q, context.N);   // poly - bx\n}\n\n//-----------------------------------------\n\nCiphertext Scheme::imult(Ciphertext& cipher) {\n\tZZX ax, bx;\n\n\tRing2Utils::multByMonomial(ax, cipher.ax, context.Nh, context.N);\n\tRing2Utils::multByMonomial(bx, cipher.bx, context.Nh, context.N);\n\n\treturn Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nCiphertext Scheme::idiv(Ciphertext& cipher) {\n\tZZX ax, bx;\n\n\tRing2Utils::multByMonomial(ax, cipher.ax, 3 * context.Nh, context.N);\n\tRing2Utils::multByMonomial(bx, cipher.bx, 3 * context.Nh, context.N);\n\n\treturn Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nvoid Scheme::imultAndEqual(Ciphertext& cipher) {\n\tRing2Utils::multByMonomialAndEqual(cipher.ax, context.Nh, context.N);\n\tRing2Utils::multByMonomialAndEqual(cipher.bx, context.Nh, context.N);\n}\n\nvoid Scheme::idivAndEqual(Ciphertext& cipher) {\n\tRing2Utils::multByMonomialAndEqual(cipher.ax, 3 * context.Nh, context.N);\n\tRing2Utils::multByMonomialAndEqual(cipher.bx, 3 * context.Nh, context.N);\n}\n\nCiphertext Scheme::mult(Ciphertext& cipher1, Ciphertext& cipher2) {\n\tZZ q = context.qpowvec[cipher1.logq];\n\tZZ qQ = context.qpowvec[cipher1.logq + context.logQ];\n\n\tZZX axbx1, axbx2, axax, bxbx, axmult, bxmult;\n\tKey key = keyMap.at(MULTIPLICATION);\n\n\tRing2Utils::add(axbx1, cipher1.ax, cipher1.bx, q, context.N);\n\tRing2Utils::add(axbx2, cipher2.ax, cipher2.bx, q, context.N);\n\tRing2Utils::multAndEqual(axbx1, axbx2, q, context.N);\n\n\tRing2Utils::mult(axax, cipher1.ax, cipher2.ax, q, context.N);\n\tRing2Utils::mult(bxbx, cipher1.bx, cipher2.bx, q, context.N);\n\n\tRing2Utils::mult(axmult, axax, key.ax, qQ, context.N);\n\tRing2Utils::mult(bxmult, axax, key.bx, qQ, context.N);\n\n\tRing2Utils::rightShiftAndEqual(axmult, context.logQ, context.N);\n\tRing2Utils::rightShiftAndEqual(bxmult, context.logQ, context.N);\n\n\tRing2Utils::addAndEqual(axmult, axbx1, q, context.N);\n\tRing2Utils::subAndEqual(axmult, bxbx, q, context.N);\n\tRing2Utils::subAndEqual(axmult, axax, q, context.N);\n\tRing2Utils::addAndEqual(bxmult, bxbx, q, context.N);\n\n    return Ciphertext(axmult, bxmult, cipher1.logp, cipher1.logq, cipher1.slots, cipher1.isComplex);\n\t//return Ciphertext(axmult, bxmult, cipher1.logp + cipher2.logp, cipher1.logq, cipher1.slots, cipher1.isComplex);\n}\n\nvoid Scheme::multAndEqual(Ciphertext& cipher1, Ciphertext& cipher2) {\n\tZZ q = context.qpowvec[cipher1.logq];\n\tZZ qQ = context.qpowvec[cipher1.logq + context.logQ];\n\tZZX axbx1, axbx2, axax, bxbx;\n\tKey key = keyMap.at(MULTIPLICATION);\n\n\tRing2Utils::add(axbx1, cipher1.ax, cipher1.bx, q, context.N);\n\tRing2Utils::add(axbx2, cipher2.ax, cipher2.bx, q, context.N);\n\tRing2Utils::multAndEqual(axbx1, axbx2, q, context.N);\n\n\tRing2Utils::mult(axax, cipher1.ax, cipher2.ax, q, context.N);\n\tRing2Utils::mult(bxbx, cipher1.bx, cipher2.bx, q, context.N);\n\n\tRing2Utils::mult(cipher1.ax, axax, key.ax, qQ, context.N);\n\tRing2Utils::mult(cipher1.bx, axax, key.bx, qQ, context.N);\n\n\tRing2Utils::rightShiftAndEqual(cipher1.ax, context.logQ, context.N);\n\tRing2Utils::rightShiftAndEqual(cipher1.bx, context.logQ, context.N);\n\n\tRing2Utils::addAndEqual(cipher1.ax, axbx1, q, context.N);\n\tRing2Utils::subAndEqual(cipher1.ax, bxbx, q, context.N);\n\tRing2Utils::subAndEqual(cipher1.ax, axax, q, context.N);\n\tRing2Utils::addAndEqual(cipher1.bx, bxbx, q, context.N);\n\n\t//cipher1.logp += cipher2.logp;\n}\n\nCiphertext Scheme::square(Ciphertext& cipher) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZ qQ = context.qpowvec[cipher.logq + context.logQ];\n\tZZX axax, axbx, bxbx, bxmult, axmult;\n\tKey key = keyMap.at(MULTIPLICATION);\n\n\tRing2Utils::square(bxbx, cipher.bx, q, context.N);\n\tRing2Utils::mult(axbx, cipher.ax, cipher.bx, q, context.N);\n\tRing2Utils::addAndEqual(axbx, axbx, q, context.N);\n\tRing2Utils::square(axax, cipher.ax, q, context.N);\n\n\tRing2Utils::mult(axmult, axax, key.ax, qQ, context.N);\n\tRing2Utils::mult(bxmult, axax, key.bx, qQ, context.N);\n\n\tRing2Utils::rightShiftAndEqual(axmult, context.logQ, context.N);\n\tRing2Utils::rightShiftAndEqual(bxmult, context.logQ, context.N);\n\n\tRing2Utils::addAndEqual(axmult, axbx, q, context.N);\n\tRing2Utils::addAndEqual(bxmult, bxbx, q, context.N);\n\n    return Ciphertext(axmult, bxmult, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n\t//return Ciphertext(axmult, bxmult, cipher.logp * 2, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nvoid Scheme::squareAndEqual(Ciphertext& cipher) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZ qQ = context.qpowvec[cipher.logq + context.logQ];\n\tZZX bxbx, axbx, axax;\n\tKey key = keyMap.at(MULTIPLICATION);\n\n\tRing2Utils::square(bxbx, cipher.bx, q, context.N);\n\tRing2Utils::mult(axbx, cipher.bx, cipher.ax, q, context.N);\n\tRing2Utils::addAndEqual(axbx, axbx, q, context.N);\n\tRing2Utils::square(axax, cipher.ax, q, context.N);\n\n\tRing2Utils::mult(cipher.ax, axax, key.ax, qQ, context.N);\n\tRing2Utils::mult(cipher.bx, axax, key.bx, qQ, context.N);\n\n\tRing2Utils::rightShiftAndEqual(cipher.ax, context.logQ, context.N);\n\tRing2Utils::rightShiftAndEqual(cipher.bx, context.logQ, context.N);\n\n\tRing2Utils::addAndEqual(cipher.ax, axbx, q, context.N);\n\tRing2Utils::addAndEqual(cipher.bx, bxbx, q, context.N);\n\t//cipher.logp *= 2;\n}\n\nCiphertext Scheme::multByConst(Ciphertext& cipher, double cnst, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZX ax, bx;\n\n\tZZ cnstZZ = EvaluatorUtils::scaleUpToZZ(cnst, logp);\n\n\tRing2Utils::multByConst(ax, cipher.ax, cnstZZ, q, context.N);\n\tRing2Utils::multByConst(bx, cipher.bx, cnstZZ, q, context.N);\n\n    return Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n\t//return Ciphertext(ax, bx, cipher.logp + logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nCiphertext Scheme::multByConst(Ciphertext& cipher, RR& cnst, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZX ax, bx;\n\n\tZZ cnstZZ = EvaluatorUtils::scaleUpToZZ(cnst, logp);\n\n\tRing2Utils::multByConst(ax, cipher.ax, cnstZZ, q, context.N);\n\tRing2Utils::multByConst(bx, cipher.bx, cnstZZ, q, context.N);\n\n    return Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n\t//return Ciphertext(ax, bx, cipher.logp + logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nCiphertext Scheme::multByConst(Ciphertext& cipher, complex<double> cnst, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\n\tZZX axr, bxr, axi, bxi;\n\n\tZZ cnstrZZ = EvaluatorUtils::scaleUpToZZ(cnst.real(), logp);\n\tZZ cnstiZZ = EvaluatorUtils::scaleUpToZZ(cnst.imag(), logp);\n\n\tRing2Utils::multByMonomial(axi, cipher.ax, context.Nh, context.N);\n\tRing2Utils::multByMonomial(bxi, cipher.bx, context.Nh, context.N);\n\n\tRing2Utils::multByConst(axr, cipher.ax, cnstrZZ, q, context.N);\n\tRing2Utils::multByConst(bxr, cipher.bx, cnstrZZ, q, context.N);\n\n\tRing2Utils::multByConstAndEqual(axi, cnstiZZ, q, context.N);\n\tRing2Utils::multByConstAndEqual(bxi, cnstiZZ, q, context.N);\n\n\tRing2Utils::addAndEqual(axr, axi, q, context.N);\n\tRing2Utils::addAndEqual(bxr, bxi, q, context.N);\n\n    return Ciphertext(axr, bxr, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n\t//return Ciphertext(axr, bxr, cipher.logp + logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nvoid Scheme::multByConstAndEqual(Ciphertext& cipher, double cnst, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZ cnstZZ = EvaluatorUtils::scaleUpToZZ(cnst, logp);\n\n\tRing2Utils::multByConstAndEqual(cipher.ax, cnstZZ, q, context.N);\n\tRing2Utils::multByConstAndEqual(cipher.bx, cnstZZ, q, context.N);\n\t//cipher.logp += logp;\n}\n\nvoid Scheme::multByConstAndEqual(Ciphertext& cipher, RR& cnst, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZ cnstZZ = EvaluatorUtils::scaleUpToZZ(cnst, logp);\n\n\tRing2Utils::multByConstAndEqual(cipher.ax, cnstZZ, q, context.N);\n\tRing2Utils::multByConstAndEqual(cipher.bx, cnstZZ, q, context.N);\n\t//cipher.logp += logp;\n}\n\nvoid Scheme::multByConstAndEqual(Ciphertext& cipher, complex<double> cnst, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZX axi, bxi;\n\n\tZZ cnstrZZ = EvaluatorUtils::scaleUpToZZ(cnst.real(), logp);\n\tZZ cnstiZZ = EvaluatorUtils::scaleUpToZZ(cnst.imag(), logp);\n\n\tRing2Utils::multByMonomial(axi, cipher.ax, context.Nh, context.N);\n\tRing2Utils::multByMonomial(bxi, cipher.bx, context.Nh, context.N);\n\n\tRing2Utils::multByConstAndEqual(cipher.ax, cnstrZZ, q, context.N);\n\tRing2Utils::multByConstAndEqual(cipher.bx, cnstrZZ, q, context.N);\n\n\tRing2Utils::multByConstAndEqual(axi, cnstiZZ, q, context.N);\n\tRing2Utils::multByConstAndEqual(bxi, cnstiZZ, q, context.N);\n\n\tRing2Utils::addAndEqual(cipher.ax, axi, q, context.N);\n\tRing2Utils::addAndEqual(cipher.bx, bxi, q, context.N);\n\t//cipher.logp += logp;\n}\n\nCiphertext Scheme::multByPoly(Ciphertext& cipher, ZZX& poly, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZX ax, bx;\n\n\tRing2Utils::mult(ax, cipher.ax, poly, q, context.N);\n\tRing2Utils::mult(bx, cipher.bx, poly, q, context.N);\n\n    return Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n\t//return Ciphertext(ax, bx, cipher.logp + logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nvoid Scheme::multByPolyAndEqual(Ciphertext& cipher, ZZX& poly, long logp) {\n\tZZ q = context.qpowvec[cipher.logq];\n\n\tRing2Utils::multAndEqual(cipher.ax, poly, q, context.N);\n\tRing2Utils::multAndEqual(cipher.bx, poly, q, context.N);\n\t//cipher.logp += logp;\n}\n\nCiphertext Scheme::multByMonomial(Ciphertext& cipher, const long degree) {\n\tZZX ax, bx;\n\n\tRing2Utils::multByMonomial(ax, cipher.ax, degree, context.N);\n\tRing2Utils::multByMonomial(bx, cipher.bx, degree, context.N);\n\n\treturn Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nvoid Scheme::multByMonomialAndEqual(Ciphertext& cipher, const long degree) {\n\tRing2Utils::multByMonomialAndEqual(cipher.ax, degree, context.N);\n\tRing2Utils::multByMonomialAndEqual(cipher.bx, degree, context.N);\n}\n\nCiphertext Scheme::multByPo2(Ciphertext& cipher, long deg) {\n\tZZ q = context.qpowvec[cipher.logq];\n\n\tZZX ax, bx;\n\n\tRing2Utils::leftShift(ax, cipher.ax, deg, q, context.N);\n\tRing2Utils::leftShift(bx, cipher.bx, deg, q, context.N);\n\n\treturn Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nvoid Scheme::multByPo2AndEqual(Ciphertext& cipher, long deg) {\n\tZZ q = context.qpowvec[cipher.logq];\n\n\tRing2Utils::leftShiftAndEqual(cipher.ax, deg, q, context.N);\n\tRing2Utils::leftShiftAndEqual(cipher.bx, deg, q, context.N);\n}\n\nvoid Scheme::multBy2AndEqual(Ciphertext& cipher) {\n\tZZ q = context.qpowvec[cipher.logq];\n\n\tRing2Utils::doubleAndEqual(cipher.ax, q, context.N);\n\tRing2Utils::doubleAndEqual(cipher.bx, q, context.N);\n}\n\nCiphertext Scheme::divByPo2(Ciphertext& cipher, long degree) {\n\tZZX ax, bx;\n\n\tRing2Utils::rightShift(ax, cipher.ax, degree, context.N);\n\tRing2Utils::rightShift(bx, cipher.bx, degree, context.N);\n\n\treturn Ciphertext(ax, bx, cipher.logp, cipher.logq - degree, cipher.slots, cipher.isComplex);\n}\n\nvoid Scheme::divByPo2AndEqual(Ciphertext& cipher, long degree) {\n\tRing2Utils::rightShiftAndEqual(cipher.ax, degree, context.N);\n\tRing2Utils::rightShiftAndEqual(cipher.bx, degree, context.N);\n\n\tcipher.logq -= degree;\n}\n\n\n//----------------------------------------------------------------------------------\n//   RESCALING & MODULUS DOWN\n//----------------------------------------------------------------------------------\n\n\nCiphertext Scheme::reScaleBy(Ciphertext& cipher, long bitsDown) {\n\tZZX ax, bx;\n\n\tRing2Utils::rightShift(ax, cipher.ax, bitsDown, context.N);\n\tRing2Utils::rightShift(bx, cipher.bx, bitsDown, context.N);\n\n    return Ciphertext(ax, bx, cipher.logp, cipher.logq - bitsDown, cipher.slots, cipher.isComplex);\n\t//return Ciphertext(ax, bx, cipher.logp - bitsDown, cipher.logq - bitsDown, cipher.slots, cipher.isComplex);\n}\n\nCiphertext Scheme::reScaleTo(Ciphertext& cipher, long newlogq) {\n\tZZX ax, bx;\n\tlong bitsDown = cipher.logq - newlogq;\n\n\tRing2Utils::rightShift(ax, cipher.ax, bitsDown, context.N);\n\tRing2Utils::rightShift(bx, cipher.bx, bitsDown, context.N);\n\n    return Ciphertext(ax, bx, cipher.logp, newlogq, cipher.slots, cipher.isComplex);\n\t//return Ciphertext(ax, bx, cipher.logp - bitsDown, newlogq, cipher.slots, cipher.isComplex);\n}\n\nvoid Scheme::reScaleByAndEqual(Ciphertext& cipher, long bitsDown) {\n\tRing2Utils::rightShiftAndEqual(cipher.ax, bitsDown, context.N);\n\tRing2Utils::rightShiftAndEqual(cipher.bx, bitsDown, context.N);\n\n\tcipher.logq -= bitsDown;\n\t//cipher.logp -= bitsDown;\n}\n\nvoid Scheme::reScaleToAndEqual(Ciphertext& cipher, long logq) {\n\tlong bitsDown = cipher.logq - logq;\n\tcipher.logq = logq;\n\t//cipher.logp -= bitsDown;\n\n\tRing2Utils::rightShiftAndEqual(cipher.ax, bitsDown, context.N);\n\tRing2Utils::rightShiftAndEqual(cipher.bx, bitsDown, context.N);\n}\n\nCiphertext Scheme::modDownBy(Ciphertext& cipher, long bitsDown) {\n\tZZX bx, ax;\n\tlong newlogq = cipher.logq - bitsDown;\n\tZZ q = context.qpowvec[newlogq];\n\n\tRing2Utils::mod(ax, cipher.ax, q, context.N);\n\tRing2Utils::mod(bx, cipher.bx, q, context.N);\n\n\treturn Ciphertext(ax, bx, cipher.logp, newlogq, cipher.slots, cipher.isComplex);\n}\n\nvoid Scheme::modDownByAndEqual(Ciphertext& cipher, long bitsDown) {\n\tcipher.logq -= bitsDown;\n\tZZ q = context.qpowvec[cipher.logq];\n\n\tRing2Utils::modAndEqual(cipher.ax, q, context.N);\n\tRing2Utils::modAndEqual(cipher.bx, q, context.N);\n}\n\nCiphertext Scheme::modDownTo(Ciphertext& cipher, long logq) {\n\tZZX bx, ax;\n\tZZ q = context.qpowvec[logq];\n\n\tRing2Utils::mod(ax, cipher.ax, q, context.N);\n\tRing2Utils::mod(bx, cipher.bx, q, context.N);\n\treturn Ciphertext(ax, bx, cipher.logp, logq, cipher.slots);\n}\n\nvoid Scheme::modDownToAndEqual(Ciphertext& cipher, long logq) {\n\tcipher.logq = logq;\n\tZZ q = context.qpowvec[logq];\n\n\tRing2Utils::modAndEqual(cipher.ax, q, context.N);\n\tRing2Utils::modAndEqual(cipher.bx, q, context.N);\n}\n\n\n//----------------------------------------------------------------------------------\n//   ROTATIONS & CONJUGATIONS\n//----------------------------------------------------------------------------------\n\n\nCiphertext Scheme::leftRotateFast(Ciphertext& cipher, long rotSlots) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZ qQ = context.qpowvec[cipher.logq + context.logQ];\n\n\tZZX bxrot, ax, bx;\n\tKey key = leftRotKeyMap.at(rotSlots);\n\n\tRing2Utils::inpower(bxrot, cipher.bx, context.rotGroup[rotSlots], context.Q, context.N);\n\tRing2Utils::inpower(bx, cipher.ax, context.rotGroup[rotSlots], context.Q, context.N);\n\n\tRing2Utils::mult(ax, bx, key.ax, qQ, context.N);\n\tRing2Utils::multAndEqual(bx, key.bx, qQ, context.N);\n\n\tRing2Utils::rightShiftAndEqual(ax, context.logQ, context.N);\n\tRing2Utils::rightShiftAndEqual(bx, context.logQ, context.N);\n\n\tRing2Utils::addAndEqual(bx, bxrot, q, context.N);\n\n\treturn Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nvoid Scheme::leftRotateAndEqualFast(Ciphertext& cipher, long rotSlots) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZ qQ = context.qpowvec[cipher.logq + context.logQ];\n\tZZX bxrot;\n\tKey key = leftRotKeyMap.at(rotSlots);\n\n\tRing2Utils::inpower(bxrot, cipher.bx, context.rotGroup[rotSlots], context.Q, context.N);\n\tRing2Utils::inpower(cipher.bx, cipher.ax, context.rotGroup[rotSlots], context.Q, context.N);\n\n\tRing2Utils::mult(cipher.ax, cipher.bx, key.ax, qQ, context.N);\n\tRing2Utils::multAndEqual(cipher.bx, key.bx, qQ, context.N);\n\n\tRing2Utils::rightShiftAndEqual(cipher.ax, context.logQ, context.N);\n\tRing2Utils::rightShiftAndEqual(cipher.bx, context.logQ, context.N);\n\n\tRing2Utils::addAndEqual(cipher.bx, bxrot, q, context.N);\n}\n\nCiphertext Scheme::leftRotateByPo2(Ciphertext& cipher, long logrotSlots) {\n\tlong rotSlots = (1 << logrotSlots);\n\treturn leftRotateFast(cipher, rotSlots);\n}\n\nvoid Scheme::leftRotateByPo2AndEqual(Ciphertext& cipher, long logrotSlots) {\n\tlong rotSlots = (1 << logrotSlots);\n\tleftRotateAndEqualFast(cipher, rotSlots);\n}\n\nCiphertext Scheme::rightRotateByPo2(Ciphertext& cipher, long logrotSlots) {\n\tlong rotSlots = context.Nh - (1 << logrotSlots);\n\treturn leftRotateFast(cipher, rotSlots);\n}\n\nvoid Scheme::rightRotateByPo2AndEqual(Ciphertext& cipher, long logrotSlots) {\n\tlong rotSlots = context.Nh - (1 << logrotSlots);\n\tleftRotateAndEqualFast(cipher, rotSlots);\n}\n\nCiphertext Scheme::leftRotate(Ciphertext& cipher, long rotSlots) {\n\tCiphertext res = cipher;\n\tleftRotateAndEqual(res, rotSlots);\n\treturn res;\n}\n\nvoid Scheme::leftRotateAndEqual(Ciphertext& cipher, long rotSlots) {\n\tlong remrotSlots = rotSlots % cipher.slots;\n\tlong logrotSlots = log2((double)remrotSlots) + 1;\n\tfor (long i = 0; i < logrotSlots; ++i) {\n\t\tif(bit(remrotSlots, i)) {\n\t\t\tleftRotateByPo2AndEqual(cipher, i);\n\t\t}\n\t}\n}\n\nCiphertext Scheme::rightRotate(Ciphertext& cipher, long rotSlots) {\n\tCiphertext res = cipher;\n\trightRotateAndEqual(res, rotSlots);\n\treturn res;\n}\n\nvoid Scheme::rightRotateAndEqual(Ciphertext& cipher, long rotSlots) {\n\tlong remrotSlots = rotSlots % cipher.slots;\n\tlong logrotSlots = log2((double)remrotSlots) + 1;\n\tfor (long i = 0; i < logrotSlots; ++i) {\n\t\tif(bit(remrotSlots, i)) {\n\t\t\trightRotateByPo2AndEqual(cipher, i);\n\t\t}\n\t}\n}\n\nCiphertext Scheme::conjugate(Ciphertext& cipher) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZ qQ = context.qpowvec[cipher.logq + context.logQ];\n\n\tZZX bxconj, ax, bx;\n\tKey key = keyMap.at(CONJUGATION);\n\n\tRing2Utils::conjugate(bxconj, cipher.bx, context.N);\n\tRing2Utils::conjugate(bx, cipher.ax, context.N);\n\n\tRing2Utils::mult(ax, bx, key.ax, qQ, context.N);\n\tRing2Utils::multAndEqual(bx, key.bx, qQ, context.N);\n\n\tRing2Utils::rightShiftAndEqual(ax, context.logQ, context.N);\n\tRing2Utils::rightShiftAndEqual(bx, context.logQ, context.N);\n\n\tRing2Utils::addAndEqual(bx, bxconj, q, context.N);\n\n\treturn Ciphertext(ax, bx, cipher.logp, cipher.logq, cipher.slots, cipher.isComplex);\n}\n\nvoid Scheme::conjugateAndEqual(Ciphertext& cipher) {\n\tZZ q = context.qpowvec[cipher.logq];\n\tZZ qQ = context.qpowvec[cipher.logq + context.logQ];\n\tZZX bxconj;\n\tKey key = keyMap.at(CONJUGATION);\n\n\tRing2Utils::conjugate(bxconj, cipher.bx, context.N);\n\tRing2Utils::conjugate(cipher.bx, cipher.ax, context.N);\n\n\tRing2Utils::mult(cipher.ax, cipher.bx, key.ax, qQ, context.N);\n\tRing2Utils::multAndEqual(cipher.bx, key.bx, qQ, context.N);\n\n\tRing2Utils::rightShiftAndEqual(cipher.ax, context.logQ, context.N);\n\tRing2Utils::rightShiftAndEqual(cipher.bx, context.logQ, context.N);\n\n\tRing2Utils::addAndEqual(cipher.bx, bxconj, q, context.N);\n}\n", "meta": {"hexsha": "822bd84f4d975f0373c24ce61058cf199027a239", "size": 31598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Scheme.cpp", "max_stars_repo_name": "pwnmelife/HEMat", "max_stars_repo_head_hexsha": "1ce4fdfa0ed83ebf59709ddc3e2e7cd6215666d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-03-20T03:49:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:30:51.000Z", "max_issues_repo_path": "src/Scheme.cpp", "max_issues_repo_name": "pwnmelife/HEMat", "max_issues_repo_head_hexsha": "1ce4fdfa0ed83ebf59709ddc3e2e7cd6215666d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-08-29T13:21:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T12:16:09.000Z", "max_forks_repo_path": "src/Scheme.cpp", "max_forks_repo_name": "pwnmelife/HEMat", "max_forks_repo_head_hexsha": "1ce4fdfa0ed83ebf59709ddc3e2e7cd6215666d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-21T10:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T08:47:07.000Z", "avg_line_length": 34.4956331878, "max_line_length": 128, "alphanum_fraction": 0.6994746503, "num_tokens": 9851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.5107312260512387}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <vector>\n\n#include \"stiffness_matrix.hpp\"\n\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix<double> SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet<double> Triplet;\n\n//----------------AssembleMatrixBegin----------------\n//! Assemble the stiffness matrix\n//! for the linear system\n//!\n//! @param[out] A will at the end contain the Galerkin matrix\n//! @param[in] vertices a list of triangle vertices\n//! @param[in] triangles a list of triangles\ntemplate<class Matrix>\nvoid assembleStiffnessMatrix(Matrix& A, const Eigen::MatrixXd& vertices,\n                            const Eigen::MatrixXi& triangles)\n{\n    \n    const int numberOfElements = triangles.rows();\n    A.resize(vertices.rows(), vertices.rows());\n    \n    std::vector<Triplet> triplets;\n\n    triplets.reserve(numberOfElements * 3 * 3);\n// (write your solution here)\n    A.setFromTriplets(triplets.begin(), triplets.end());\n}\n//----------------AssembleMatrixEnd----------------\n", "meta": {"hexsha": "d1d3298a1ec00ec73e670299406737309f132d1d", "size": 1068, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series0_handout/2d-poissonlFEM/stiffness_matrix_assembly.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series0_handout/2d-poissonlFEM/stiffness_matrix_assembly.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series0_handout/2d-poissonlFEM/stiffness_matrix_assembly.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 29.6666666667, "max_line_length": 72, "alphanum_fraction": 0.6676029963, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5106792307939683}}
{"text": "/*! @file gridsearch.cpp\n    @brief Implementation of GridSearch class\n*/\n#include \"gridsearch.hpp\"\n#include \"util.hpp\"\n\n#include <wtl/exception.hpp>\n#include <wtl/debug.hpp>\n#include <wtl/iostr.hpp>\n#include <wtl/zlib.hpp>\n#include <wtl/numeric.hpp>\n#include <wtl/math.hpp>\n#include <wtl/concurrent.hpp>\n#include <wtl/itertools.hpp>\n\n#include <boost/math/distributions/chi_squared.hpp>\n\n#include <chrono>\n\nnamespace likeligrid {\n\nvoid GridSearch::init(const std::pair<size_t, size_t>& epistasis_pair, const bool pleiotropy) {HERE;\n    model_.set_epistasis(epistasis_pair, pleiotropy);\n    mle_params_.resize(model_.names().size());\n    mle_params_ = 1.0;\n}\n\nvoid GridSearch::run(const bool writing) {HERE;\n    while (stage_ < STEPS.size()) {\n        if (writing) {run_fout();} else {run_cout();}\n    }\n    --stage_;\n    search_limits();\n}\n\nvoid GridSearch::run_fout() {HERE;\n    const std::string outfile = init_meta();\n    std::cerr << \"mle_params_: \" << mle_params_ << std::endl;\n    if (outfile.empty()) return;\n    const auto axes = make_vicinity(mle_params_, BREAKS.at(stage_), radius(stage_));\n    for (size_t j=0u; j<model_.names().size(); ++j) {\n        std::cerr << model_.names()[j] << \": \" << axes[j] << std::endl;\n    }\n    {\n        wtl::zlib::ofstream fout(outfile, std::ios_base::out | std::ios_base::app);\n        std::cerr << \"Writing: \" << outfile << std::endl;\n        run_impl(fout, wtl::itertools::product(axes));\n    }\n}\n\nvoid GridSearch::run_cout() {HERE;\n    const auto axes = make_vicinity(mle_params_, BREAKS.at(stage_), radius(stage_));\n    for (size_t j=0u; j<model_.names().size(); ++j) {\n        std::cerr << model_.names()[j] << \": \" << axes[j] << std::endl;\n    }\n    {\n        std::stringstream sst;\n        run_impl(sst, wtl::itertools::product(axes));\n        std::cout << sst.str();\n        read_results(sst);\n    }\n    std::cerr << \"mle_params_: \" << mle_params_ << std::endl;\n    ++stage_;\n}\n\nvoid GridSearch::search_limits() {HERE;\n    namespace bmath = boost::math;\n    bmath::chi_squared_distribution<> chisq(1.0);\n    const double diff95 = 0.5 * bmath::quantile(bmath::complement(chisq, 0.05));\n    auto axis = wtl::round(wtl::lin_spaced(200, 2.0, 0.01), 100);\n    axis = (axis * 100.0).apply(std::round) / 100.0;\n    std::map<std::string, std::valarray<double>> intersections;\n    for (size_t i=0u; i<model_.names().size(); ++i) {\n        const std::string outfile = \"uniaxis-\" + model_.names()[i] + \".tsv.gz\";\n        std::cerr << outfile << std::endl;\n        std::stringstream sst;\n        run_impl(sst, wtl::itertools::uniaxis(axis, mle_params_, i));\n        wtl::zlib::ofstream(outfile) << sst.str();\n        const auto logliks = read_loglik(sst, axis.size());\n        const double threshold = logliks.max() - diff95;\n        const std::valarray<double> range = axis[logliks > threshold];\n        auto bound_params = mle_params_;\n        bound_params[i] = std::max(range.min() - 0.01, 0.01);\n        intersections.emplace(model_.names()[i] + \"_L\", bound_params);\n        bound_params[i] = std::min(range.max() + 0.01, 2.00);\n        intersections.emplace(model_.names()[i] + \"_U\", bound_params);\n    }\n    for (const auto& p: intersections) {\n        const std::string outfile = \"limit-\" + p.first + \".tsv.gz\";\n        std::cerr << outfile << \": \" << p.second << std::endl;\n        const auto axes = make_vicinity(p.second, 5u, 0.02);\n        wtl::zlib::ofstream fout(outfile);\n        //TODO: if exists\n        run_impl(fout, wtl::itertools::product(axes));\n    }\n}\n\nvoid GridSearch::run_impl(std::ostream& ost, wtl::itertools::Generator<std::valarray<double>>&& gen) {HERE;\n    std::cerr << skip_ << \" to \" << gen.max_count() << std::endl;\n    if (skip_ == 0u) {\n        write_header(ost, gen.max_count());\n    }\n\n    auto task = [this](const std::valarray<double> th_path) {\n        // argument and model are copied for each thread\n        auto buffer = wtl::make_oss();\n        auto model_copy = this->model_;\n        buffer << model_copy.calc_loglik(th_path) << \"\\t\";\n        wtl::join(th_path, buffer, \"\\t\") << \"\\n\";\n        return buffer.str();\n    };\n\n    static wtl::ThreadPool pool(concurrency_);\n    std::vector<std::future<std::string>> futures;\n    futures.reserve(gen.max_count() - skip_);\n    for (const auto& th_path: gen(skip_)) {\n        futures.push_back(pool.submit(task, th_path));\n    }\n\n    auto buffer = wtl::make_oss();\n    size_t stars = 0u;\n    size_t i = skip_;\n    const auto min_interval = std::chrono::seconds(1);\n    auto next_time = std::chrono::system_clock::now();\n    for (auto& ftr: futures) {\n        buffer << ftr.get();\n        ++i;\n        auto now = std::chrono::system_clock::now();\n        if (now > next_time || &ftr == &futures.back()) {\n            next_time = now + min_interval;\n            ost << buffer.str();\n            buffer.str(\"\");\n            buffer.clear();\n            for (size_t n= static_cast<size_t>(20.0 * i / gen.max_count()); stars<n; ++stars) {\n                std::cerr << \"*\";\n            }\n        }\n        if (wtl::SIGINT_RAISED()) {throw wtl::KeyboardInterrupt();}\n    }\n    std::cerr << \"\\n\";\n}\n\nstd::string GridSearch::init_meta() {HERE;\n    if (stage_ >= STEPS.size()) return \"\";\n    auto oss = wtl::make_oss(2u, std::ios_base::fixed);\n    oss << \"grid-\" << STEPS.at(stage_) << \".tsv.gz\";\n    std::string outfile = oss.str();\n    try {\n        wtl::zlib::ifstream ist(outfile);\n        std::cerr << \"Reading: \" << outfile << std::endl;\n        read_results(ist);\n        if (skip_ == 0u) {\n            ++stage_;\n            outfile = init_meta();\n        }\n    } catch (std::ios_base::failure& e) {\n        if (errno != ENOENT) throw e;\n    }\n    return outfile;\n}\n\nvoid GridSearch::read_results(std::istream& ist) {HERE;\n    size_t max_count;\n    double step;\n    std::tie(std::ignore, std::ignore, max_count, step) = read_metadata(ist);\n    stage_ = guess_stage(step);\n    std::vector<std::string> colnames;\n    std::valarray<double> mle_params;\n    std::tie(skip_, colnames, mle_params) = read_body(ist);\n    if (skip_ == max_count) {  // is complete file\n        skip_ = 0u;\n        mle_params_.swap(mle_params);\n    }\n}\n\nvoid GridSearch::read_results(const std::string& infile) {\n    wtl::zlib::ifstream ist(infile);\n    read_results(ist);\n}\n\nvoid GridSearch::write_header(std::ostream& ost, const size_t max_count) const {\n    ost << \"##genotype_file=\" << model_.filename() << \"\\n\";\n    ost << \"##max_sites=\" << model_.max_sites() << \"\\n\";\n    ost << \"##max_count=\" << max_count << \"\\n\";\n    ost << \"##step=\" << STEPS.at(stage_) << \"\\n\";\n    ost << \"loglik\\t\";\n    wtl::join(model_.names(), ost, \"\\t\") << \"\\n\";\n}\n\n} // namespace likeligrid\n", "meta": {"hexsha": "10f6f1e149152795ae1ae99f3dc644ca6d359327", "size": 6672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gridsearch.cpp", "max_stars_repo_name": "heavywatal/likeligrid", "max_stars_repo_head_hexsha": "763e72ecaf58a7bc095ea82f4b1553790e9ebf7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gridsearch.cpp", "max_issues_repo_name": "heavywatal/likeligrid", "max_issues_repo_head_hexsha": "763e72ecaf58a7bc095ea82f4b1553790e9ebf7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2016-11-17T15:33:12.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-15T04:59:23.000Z", "max_forks_repo_path": "src/gridsearch.cpp", "max_forks_repo_name": "heavywatal/lmpp", "max_forks_repo_head_hexsha": "763e72ecaf58a7bc095ea82f4b1553790e9ebf7f", "max_forks_repo_licenses": ["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.9319371728, "max_line_length": 107, "alphanum_fraction": 0.5923261391, "num_tokens": 1910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5106792207150629}}
{"text": "#include <ros/ros.h>\n#include <iostream>\n#include <Eigen/Dense>\n\n#include \"sensor_msgs/Imu.h\"\n\nnamespace ImuTransform {\n\n\nstatic inline Eigen::Matrix<double, 3, 3> CrossOperator(Eigen::Matrix<double, 3, 1> u)\n{\n\tEigen::Matrix<double, 3, 3> m;\n\n\tm << 0, -u[2], u[1], u[2], 0, -u[0], -u[1], u[0], 0;\n\n\treturn m;\n}\n\nclass ImuMeasurementModel {\n\npublic:\n\n    //! Measurement type shortcut definition\n    typedef Eigen::Matrix<double, 3, 1> Vector3;\n    typedef Eigen::Matrix<double, 3, 3> Matrix3;\n    typedef Eigen::Matrix<double, 4, 4> Matrix4;\n\n    ImuMeasurementModel(ros::NodeHandle& nh) : _nh(nh) {\n\n    \t_sub = _nh.subscribe(\"/imu/data\", 100, &ImuMeasurementModel::ImuCallback, this);\n    \t_pub = _nh.advertise<sensor_msgs::Imu>(\"/imu/transformed_data\", 1000);\n\n    \tMatrix4 tf_base_to_imu;\n    \ttf_base_to_imu << 0.7067584,  0.7074550,  0.0000000, 0.192,\n    \t                 -0.7074550,  0.7067584,  0.0000000, -0.086,\n    \t                  0.0000000,  0.0000000,  1.0000000, 0.185,\n    \t                  0.0, 0.0, 0.0, 1.0;\n\n    \t_tf_imu_to_base = tf_base_to_imu.inverse();\n    \t_rot_imu_to_base = tf_base_to_imu.block<3,3>(0,0);\n    \t_t_imu_to_base = _tf_imu_to_base.block<3,1>(0,3);\n\n    \tstd::cout << \"_tf_base_to_imu: \" << std::endl << tf_base_to_imu << std::endl;\n    \tstd::cout << \"_tf_imu_to_base: \" << std::endl << _tf_imu_to_base << std::endl;\n    \tstd::cout << \"_rot_imu_to_base: \" << std::endl << _rot_imu_to_base << std::endl;\n    \tstd::cout << \"_t_imu_to_base: \" << std::endl << _t_imu_to_base << std::endl;\n\n\t// _tf_mast_imu_to_base_imu = tf_mast_imu_to_link + tf_link_to_base_imu;\n\t// _rot_mast_imu_to_base_imu = _tf_mast_imu_to_base_imu.getRotationMatrix().cast<T>().transpose();\n\t// _t_mast_imu_to_base_imu = _tf_mast_imu_to_base_imu.translation_src().cast<T>();\n    }\n\n    sensor_msgs::Imu transform(const sensor_msgs::Imu::ConstPtr& msg) const\n    {\n    \tsensor_msgs::Imu transformed;\n    \ttransformed.header = msg->header;\n    \ttransformed.orientation = msg->orientation;\n    \ttransformed.orientation_covariance = msg->orientation_covariance;\n    \ttransformed.angular_velocity = msg->angular_velocity;\n        transformed.angular_velocity_covariance = msg->angular_velocity_covariance;\n    \ttransformed.linear_acceleration = msg->linear_acceleration;\n    \ttransformed.linear_acceleration_covariance = msg->linear_acceleration_covariance;\n\n\n        Vector3 a_imu = {msg->linear_acceleration.x, msg->linear_acceleration.y, msg->linear_acceleration.z};\n        Vector3 w_imu = {msg->angular_velocity.x, msg->angular_velocity.y, msg->angular_velocity.z};\n\n        Matrix3 wx = CrossOperator(w_imu);\n\n        Vector3 a_base = _rot_imu_to_base * (a_imu) + _rot_imu_to_base * wx * wx * _t_imu_to_base;\n        Vector3 w_base = _rot_imu_to_base * w_imu;\n\n        transformed.header.frame_id = \"base_link\";\n\n        transformed.angular_velocity.x = w_base[0];\n        transformed.angular_velocity.y = w_base[1];\n        transformed.angular_velocity.z = w_base[2];\n\n        transformed.linear_acceleration.x = a_base[0];\n        transformed.linear_acceleration.y = a_base[1];\n        transformed.linear_acceleration.z = a_base[2];\n\n        return transformed;\n    }\n\n    void spin() {\n    \twhile (ros::ok()) {\n    \t\tros::spinOnce();\n    \t}\n    }\n\n    void test() {\n    \tsensor_msgs::Imu::Ptr msg_ptr(new sensor_msgs::Imu);\n    \tmsg_ptr->linear_acceleration.x = 0.5;\n    \tmsg_ptr->linear_acceleration.y = 0.5;\n    \tstd::cout << \"old ax: \" << msg_ptr->linear_acceleration.x << std::endl;\n    \tstd::cout << \"old ay: \" << msg_ptr->linear_acceleration.y << std::endl;\n\n    \tsensor_msgs::Imu ret = transform(msg_ptr);\n    \tstd::cout << \"new ax: \" << ret.linear_acceleration.x << std::endl;\n    \tstd::cout << \"new ay: \" << ret.linear_acceleration.y << std::endl;\n\n    \tmsg_ptr->linear_acceleration.x = 1;\n    \tmsg_ptr->linear_acceleration.y = 0;\n    \tstd::cout << \"old ax: \" << msg_ptr->linear_acceleration.x << std::endl;\n    \tstd::cout << \"old ay: \" << msg_ptr->linear_acceleration.y << std::endl;\n\n    \tret = transform(msg_ptr);\n    \tstd::cout << \"new ax: \" << ret.linear_acceleration.x << std::endl;\n    \tstd::cout << \"new ay: \" << ret.linear_acceleration.y << std::endl;\n\n    \tmsg_ptr->linear_acceleration.x = 0;\n    \tmsg_ptr->linear_acceleration.y = 1;\n    \tstd::cout << \"old ax: \" << msg_ptr->linear_acceleration.x << std::endl;\n    \tstd::cout << \"old ay: \" << msg_ptr->linear_acceleration.y << std::endl;\n\n    \tret = transform(msg_ptr);\n    \tstd::cout << \"new ax: \" << ret.linear_acceleration.x << std::endl;\n    \tstd::cout << \"new ay: \" << ret.linear_acceleration.y << std::endl;\n\n    \tmsg_ptr->linear_acceleration.x = -0.2;\n    \tmsg_ptr->linear_acceleration.y = 0;\n    \tmsg_ptr->angular_velocity.z = 1;\n    \tstd::cout << \"old ax: \" << msg_ptr->linear_acceleration.x << std::endl;\n    \tstd::cout << \"old ay: \" << msg_ptr->linear_acceleration.y << std::endl;\n\n    \tret = transform(msg_ptr);\n    \tstd::cout << \"new ax: \" << ret.linear_acceleration.x << std::endl;\n    \tstd::cout << \"new ay: \" << ret.linear_acceleration.y << std::endl;\n    }\n\nprivate:\n    void ImuCallback(const sensor_msgs::Imu::ConstPtr& msg) {\n    \tsensor_msgs::Imu new_msg = transform(msg);\n    \t_pub.publish(new_msg);\n    }\n\n    Matrix4 _tf_imu_to_base;\n    Matrix3 _rot_imu_to_base;\n    Vector3 _t_imu_to_base;\n\n    ros::NodeHandle _nh;\n    ros::Publisher _pub;\n    ros::Subscriber _sub;\n};\n\n}\n\nint main(int argc, char* argv[]) {\n\tros::init(argc, argv, \"imu_transform\");\n\tros::NodeHandle n;\n\tImuTransform::ImuMeasurementModel transformer(n);\n\n\t//transformer.test();\n\n\ttransformer.spin();\n\n\treturn 0;\n}\n\n\n", "meta": {"hexsha": "699bb7b9e012fc8764f6d916bca67697f06f6b50", "size": 5596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ImuTransformer.cpp", "max_stars_repo_name": "Viky397/Kimera-VIO-ROS", "max_stars_repo_head_hexsha": "c23a5b976bbe527016d04b01827e8cfc36ce3e14", "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/ImuTransformer.cpp", "max_issues_repo_name": "Viky397/Kimera-VIO-ROS", "max_issues_repo_head_hexsha": "c23a5b976bbe527016d04b01827e8cfc36ce3e14", "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/ImuTransformer.cpp", "max_forks_repo_name": "Viky397/Kimera-VIO-ROS", "max_forks_repo_head_hexsha": "c23a5b976bbe527016d04b01827e8cfc36ce3e14", "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": 34.5432098765, "max_line_length": 109, "alphanum_fraction": 0.6510007148, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5105879349345271}}
{"text": "#include <ctime>\n#include <string>\n#include <fstream>\n#include <iostream>\n#include <boost/program_options.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include \"keys.hpp\"\n#include \"utils.hpp\"\n#include \"cipher.hpp\"\n#include \"stream_handler.hpp\"\n\nnamespace mp = boost::multiprecision;\nnamespace po = boost::program_options;\n\ntemplate<size_t E, size_t D>\nvoid encrypt_file(const std::string& in_file, const std::string& out_file, const rsa::keys<D * 8> keys) {\n    std::ifstream inp(in_file, std::ios::binary);\n    rsa::ifstream_handler<rsa::read_number_padding_operation, rsa::eof_operation> read_handler(inp);\n    std::ofstream out(out_file, std::ios::binary);\n    rsa::ofstream_handler<rsa::write_number_operation, rsa::write_bytes_operation> write_handler(out);\n    write_handler.write_number<D * 8>(keys.get_d());\n    write_handler.write_number<D * 8>(keys.get_n());\n    unsigned int n = 0;\n    for (const auto& it : rsa::cipher<E, D>::encrypt(read_handler, keys, n)) {\n        write_handler.write_number<D * 8>(it);\n    }\n    if (n == E) {\n        std::array<char, E> padding{};\n        padding.fill(static_cast<const char&>(E));\n        write_handler.write_number<D * 8>(mp::powm(\n                static_cast<typename rsa::num_utils<D * 8>::number>(\n                        rsa::num_utils<E * 8>::bytes_to_number(padding.begin(), padding.end())),\n                keys.get_e(), keys.get_n()));\n    }\n}\n\ntemplate<size_t E, size_t D>\nvoid decrypt_file(const std::string& in_file, const std::string& out_file, const bool print_keys) {\n    std::ifstream inp(in_file, std::ios::binary);\n    rsa::ifstream_handler<rsa::read_number_operation, rsa::eof_operation> read_handler(inp);\n    std::ofstream out(out_file, std::ios::binary);\n    rsa::ofstream_handler<rsa::write_number_operation> write_handler(out);\n    const auto d = read_handler.read_number<D * 8>();\n    const auto n = read_handler.read_number<D * 8>();\n    if (print_keys)\n        std::cout << \"Decrypt keys:\\n    d  : \" << d << \"\\n    n  : \" << n << std::endl;\n    const auto numbers = rsa::cipher<E, D>::decrypt(read_handler, rsa::keys<D * 8>(n, 0, d, 0));\n    for (size_t i = 0; i < numbers.size() - 1; ++i)\n        write_handler.write_number<E * 8>(numbers[i]);\n    const auto bytes = rsa::num_utils<E * 8>::number_to_bytes(numbers.back());\n    const auto p = bytes.back();\n    bool ok = true;\n    for (size_t i = 1; i < p; ++i)\n        ok &= bytes[E - i - 1] == p;\n    if (!ok)\n        throw std::runtime_error(\"Could not decrypt file\");\n    out.write(bytes.data(), E - p);\n}\n\nusing number = rsa::num_utils<256>::number;\n\nint main(int argc, char* argv[]) {\n    rsa::random::default_random().init_generator(static_cast<const uint64_t>(std::time(nullptr)));\n    std::string in_file, out_file, enc_file;\n    number n, e, d;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n            (\"help,h\", \"Print this message\")\n            (\"n\", po::value(&n), \"n key\")\n            (\"e\", po::value(&e), \"e key\")\n            (\"d\", po::value(&d), \"d key\")\n            (\"input_file,i\", po::value(&in_file)->default_value(\"input.txt\"), \"input filename\")\n            (\"output_file,o\", po::value(&out_file)->default_value(\"output.txt\"), \"output filename\")\n            (\"encfile,c\", po::value(&enc_file)->default_value(\"encrypted.txt\"), \"encrypted filename\")\n            (\"random_keys\", \"use random keys\")\n            (\"print_keys\", \"print keys\")\n            (\"encrypt\", \"encrypt file\")\n            (\"decrypt\", \"decrypt file\");\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\")) {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n    if (vm.count(\"encrypt\")) {\n        const auto keys = vm.count(\"random_keys\") ? rsa::keys<256>() : rsa::keys<256>(n, e, d, 0);\n        if (vm.count(\"print_keys\")) {\n            std::cout << \"Encrypt keys:\\n\";\n            std::cout << \"    n  : \" << keys.get_n() << '\\n';\n            std::cout << \"    e  : \" << keys.get_e() << '\\n';\n            std::cout << \"    d  : \" << keys.get_d() << '\\n';\n            std::cout << \"    phi: \" << keys.get_phi() << std::endl;\n        }\n        encrypt_file<8, 32>(in_file, enc_file, keys);\n    }\n    if (vm.count(\"decrypt\"))\n        decrypt_file<8, 32>(enc_file, out_file, vm.count(\"print_keys\"));\n}", "meta": {"hexsha": "7c0fe770bcae0eae3dd1b9e47c3faa260cbc2ce4", "size": 4342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "GoldFeniks/RSA", "max_stars_repo_head_hexsha": "0e5020202d03a84a217bd2cfd416a09590a71b37", "max_stars_repo_licenses": ["MIT"], "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": "GoldFeniks/RSA", "max_issues_repo_head_hexsha": "0e5020202d03a84a217bd2cfd416a09590a71b37", "max_issues_repo_licenses": ["MIT"], "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": "GoldFeniks/RSA", "max_forks_repo_head_hexsha": "0e5020202d03a84a217bd2cfd416a09590a71b37", "max_forks_repo_licenses": ["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.8585858586, "max_line_length": 105, "alphanum_fraction": 0.5967296177, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5105879308879714}}
{"text": "/////////////////////////////////////////////////////////////////////////////////////////////\n// Copyright (c) 2021 Andreas Milton Maniotis.\n//\n// Email: andreas.maniotis@gmail.com\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n/////////////////////////////////////////////////////////////////////////////////////////////\n\n\n#include \"aml/set.hpp\"\n\n#include <type_traits>\n\n#include <iostream>\n#include <boost/core/demangle.hpp>\n\nnamespace aml\n{\n    template< typename... X>\n    struct list\n    {\n        template<template<typename...> class F>\n        using apply  =  F<X...>;\n    };\n}\n\n\nnamespace test::set\n{\n    using aml::_;\n\n    using s0   =  aml::set<>;\n    using s1   =  aml::set< _<2> >;\n    using s2a  =  aml::set< _<1>, _<2> >;\n    using s2b  =  aml::set<_<2>, _<1> >;\n    using s3   =  aml::set< _<1>, _<3>, _<2> >;\n    using s5   =  aml::set< _<1>, _<2>, _<3>, _<4>, _<5> >;\n\n\n    void test_empty_set()\n    {\n        static_assert( s0() == s0() );\n        static_assert( s0()  <= s0() );\n        static_assert( s0() >= s0() );\n        static_assert( ! (s0() != s0()) );\n        static_assert( ! (s0() < s0())  );\n        static_assert( ! (s0() > s0() ) );\n\n        static_assert( std::is_same< s0::add_elements<>, s0 >::value );\n        static_assert( std::is_same< s0::add_elements< _<2>, _<3> >, aml::set< _<2>, _<3> > >::value );\n    }\n\n\n    void test_size()\n    {\n        static_assert( s0::size() == 0 );\n        static_assert( s1::size() == 1 );\n        static_assert( s2a::size() == 2 );\n        static_assert( s3::size() == 3 );\n        static_assert( s5::size() == 5 );\n    }\n\n\n    void test_add_elements()\n    {\n        static_assert( std::is_same<s0,  s0::add_elements<> >::value );\n        static_assert( std::is_same<s1,  s0::add_elements<_<2> > >::value );\n        static_assert( std::is_same<s2a, s0::add_elements< _<1>, _<2> > >::value );\n        static_assert( std::is_same<s5,  aml::set< _<1>, _<2> >::add_elements< _<3> >::add_elements< _<4>, _<5> > >::value );\n\n        static_assert( std::is_same< aml::set<_<2> >::add_elements< _<2>, _<2> >, aml::set<_<2> > >::value );\n    }\n\n\n    void test_remove_elements()\n    {\n        static_assert( std::is_same< s0::remove_elements<>, s0 >::value );\n        static_assert( std::is_same< s1::remove_elements< _<2>, _<3>, _<2> >, s0 >::value );\n        static_assert( std::is_same< s3::remove_elements< _<2>, _<1>, _<4> >, aml::set< _<3> > >::value );\n    }\n\n\n    void test_contains()\n    {\n        static_assert( s0::contains<>::eval() );\n        static_assert( s0::contains<_<1> >::eval() == false );\n        static_assert( s3::contains< _<2>, _<1> >::eval() );\n        static_assert( s3::contains_any_of< _<2>, _<8> >::eval() );\n        static_assert( s3::contains_any_of< _<8>, _<2> >::eval() );\n        static_assert( s3::contains_none_of< _<8>, _<5>, _<-1> >::eval() );\n        static_assert( s3::contains_none_of< _<1>, _<8> >::eval() == false );\n    }\n\n    template<typename X>\n    using is_even = aml::bool_< X::eval() % 2 == 0 >;\n\n    void test_subset_by_predicate()\n    {\n        using p0  =  s0::subset_by_predicate< is_even >;\n        using p1  =  s1::subset_by_predicate< is_even >;\n        using p2a =  s2a::subset_by_predicate< is_even >;\n        using p2b =  s2b::subset_by_predicate< is_even >;\n        using p3  =  s3::subset_by_predicate< is_even >;\n        using p5  =  s5::subset_by_predicate< is_even >;\n\n        static_assert( std::is_same < p0, aml::set<> >::value );\n        static_assert( std::is_same < p1, aml::set< _<2> > >::value );\n        static_assert( std::is_same < p2a, aml::set<_<2> > >::value );\n        static_assert( std::is_same < p2b, aml::set< _<2> > >::value );\n        static_assert( std::is_same < p3, aml::set< _<2> > >::value );\n        static_assert( std::is_same < p5, aml::set< _<2>, _<4> > >::value );\n    }\n\n    void test_set_operations_and_relations()\n    {\n        using s1  =  aml::set< _<1>, _<2>, _<3>             >;\n        using s2  =  aml::set<       _<2>, _<3>, _<4>       >;\n        using s3  =  aml::set<             _<3>, _<4>, _<5> >;\n        using s4  =  aml::set< _<1>, _<2>, _<3>, _<4>       >;\n\n        using s2a = aml::set< _<3>, _<2>, _<4> >;\n\n        static_assert( std::is_same< decltype(s1() & s2() & s3()), aml::set<_<3>> >::value );\n\n        using s_13 = decltype(s1() | s3());\n\n        static_assert( std::is_same< s_13, aml::set< _<1>, _<2>, _<3>, _<4>, _<5> > >::value );\n\n        static_assert( std::is_same< decltype( s1() - s2() ), aml::set< _<1> > >::value );\n        static_assert( std::is_same< decltype( aml::set<>() - aml::set<>() ), aml::set<> >::value );\n\n        static_assert(  s2a() == s2()  );\n        static_assert(   s1() < s4()   );\n        static_assert(   s4() > s1()   );\n        static_assert(   s1()  <= s4() );\n        static_assert(   s4() >= s1()  );\n        static_assert(   s3() != s4()  );\n\n        static_assert( !( s3() < s3() ) );\n        static_assert( !( s3() > s3() ) );\n        static_assert( s3() <= s3() );\n        static_assert( s3() >= s3() );\n        static_assert( s3() == s3() );\n        static_assert( ! (s3() != s3() ) );\n    }\n}\n\n\n#include <iostream>\n#include <string>\n\n\nint main()\n{\n    void (*test_set[])() =\n    {\n        test::set::test_empty_set,\n        test::set::test_size,\n        test::set::test_add_elements,\n        test::set::test_remove_elements,\n        test::set::test_contains,\n        test::set::test_subset_by_predicate,\n        test::set::test_set_operations_and_relations,\n    };\n\n\n    for ( auto test : test_set )\n        test();\n\n    std::cout << __FILE__ << \": \" << sizeof(test_set)/sizeof(test_set[0])  << \" tests passed.\" << std::endl;\n\n}\n", "meta": {"hexsha": "b8aa4198590ee20cff0f784a7d82769f7ba8e953", "size": 5771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_set.cpp", "max_stars_repo_name": "aandriko/libaml", "max_stars_repo_head_hexsha": "9db1a3ac13ef8160a33ed03e861be5d8cc8ea311", "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_set.cpp", "max_issues_repo_name": "aandriko/libaml", "max_issues_repo_head_hexsha": "9db1a3ac13ef8160a33ed03e861be5d8cc8ea311", "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_set.cpp", "max_forks_repo_name": "aandriko/libaml", "max_forks_repo_head_hexsha": "9db1a3ac13ef8160a33ed03e861be5d8cc8ea311", "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.1666666667, "max_line_length": 125, "alphanum_fraction": 0.5084040894, "num_tokens": 1860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5105866996462439}}
{"text": "//==============================================================================\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/exponential/include/functions/nthroot.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <nt2/sdk/meta/as_floating.hpp>\n\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/half.hpp>\n\nNT2_TEST_CASE_TPL ( nthroot,  NT2_REAL_TYPES)\n{\n  using nt2::nthroot;\n  using nt2::tag::nthroot_;\n  typedef typename nt2::meta::as_integer<T>::type          iT;\n  typedef typename nt2::meta::call<nthroot_(T,iT)>::type r_t;\n  typedef T wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Inf<T>(),iT(3)), nt2::Inf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Inf<T>(),iT(4)), nt2::Inf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Minf<T>(),iT(3)), nt2::Minf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Minf<T>(),iT(4)), nt2::Nan<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Nan<T>(),iT(3)), nt2::Nan<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Nan<T>(),iT(4)), nt2::Nan<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Mone<T>(),iT(4)), nt2::Nan<r_t>(), 0.5);\n#endif\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Mone<T>(),iT(0)), nt2::Nan<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::One <T>(),iT(0)), nt2::One<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Half<T>(),iT(0)), nt2::Zero<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Two <T>(),iT(0)), nt2::Inf <r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Zero<T>(),iT(0)), nt2::Zero<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Two <T>(),iT(0)), nt2::Inf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Half<T>(),iT(0)), nt2::Zero<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Mone<T>(),iT(3)), nt2::Mone<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::One<T>(),iT(3)), nt2::One<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::One<T>(),iT(4)), nt2::One<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Zero<T>(),iT(3)), nt2::Zero<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Zero<T>(),iT(4)), nt2::Zero<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(T(-8),iT(3)), r_t(-2), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(T(256),iT(4)), r_t(4), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(T(8),iT(3)), r_t(2), 0.5);\n}\n", "meta": {"hexsha": "f0a59b20d59e4d7cebe8eeb238ebc59412adbe5d", "size": 3122, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/unit/scalar/nthroot.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/exponential/unit/scalar/nthroot.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/exponential/unit/scalar/nthroot.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 48.0307692308, "max_line_length": 80, "alphanum_fraction": 0.6342088405, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5105866970014425}}
{"text": "#pragma once\n\n#include <cstddef>\n#include <cstdint>\n#include <type_traits>\n#include <array>\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace cryptb\n{\n\tclass sha512\n\t{\n\t\t// The hash size in bits\n\t\tstatic constexpr int hash_digest_size_in_bits{ 512 };\n\t\t// The hash size in bytes\n\t\tstatic constexpr int hash_digest_size_in_bytes{ hash_digest_size_in_bits / 8 };\n\n\t\t// The size of each message block in bits\n\t\tstatic constexpr int message_block_size_bits{ sha512::hash_digest_size_in_bits * 2 };\n\n\t\t// The size of each message block in bytes\n\t\tstatic constexpr int message_block_size_bytes{ message_block_size_bits / 8 };\n\n\t\t// Current hash values, of the concatenation of all of the message\n\t\t// blocks that we went through until now not including the current message block.\n\t\tstd::array<std::uint64_t, 8> m_hash_values{ {\n\t\t0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,\n\t\t0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL } };\n\n\t\tusing message_block_t = std::array<std::uint64_t, message_block_size_bits / 64>;\n\n\t\t// The partial message block that hasn't yet been accounted for in\n\t\t// the summation m_hash_values.\n\t\t// The assumption is that m_message_block will be \"emptied\" when full\n\t\t// The variable \"m_num_bytes_filled\" keeps track of how full m_message_block is.\n\t\tmessage_block_t m_message_block{ {0} };\n\n\t\t// The message block contains 64-bit integers but we're measuring the fullness level in\n\t\t// bytes. The message block is filled in big endian order inside of each 64-bit integer.\n\t\t// Meaning if \"m_num_bytes_filled\" is set to 3 then the 3 most significant bytes are set\n\t\t// in the first element of \"current_message_block\".\n\t\tint m_num_bytes_filled = 0;\n\n\t\t// Entire message length in bits counter\n\t\tboost::multiprecision::uint128_t m_bits_counter{ 0 };\n\n\tpublic:\n\t\tsha512() = default;\n\t\tsha512(const sha512&) = default;\n\t\tsha512(sha512&&) = default;\n\t\tsha512& operator=(const sha512&) = default;\n\t\tsha512& operator=(sha512&&) = default;\n\n\t\tsha512(const std::uint8_t* const data, const std::size_t len) { this->update(data, len); }\n\n\t\t// Appends another part of the message to be concatenated.\n\t\t// Even though that sounds expensive, the memory usage is constant.\n\t\tvoid update(const std::uint8_t* const data, const std::size_t len);\n\n\t\tusing digest_t = std::array<std::uint8_t, hash_digest_size_in_bytes>;\n\n\t\t// At any point you can ask for the hash of the concatenated data so far\n\t\tdigest_t digest() const;\n\n\t\t~sha512() = default;\n\tprivate:\n\t\ttemplate <typename x_T, int amount>\n\t\tstatic x_T rotater(const x_T& x)\n\t\t{\n\t\t\tstatic_assert(std::is_unsigned<x_T>::value, \"Rotates unsigned integer by a specific number of bits\");\n\t\t\tstatic_assert(std::numeric_limits<x_T>::digits > amount, \"Amount to shift needs to be smaller than number of bits in unsigned integer.\"\n\t\t\t\t\" Otherwise it\\'s undefined behavior.\");\n\t\t\treturn (x >> amount) | (x << (64 - amount));\n\t\t}\n\n\t\ttemplate <typename x_T>\n\t\tstatic x_T lowercase_sigma0(const x_T& x)\n\t\t{\n\t\t\tstatic_assert(std::is_unsigned<x_T>::value, \"Must be unsigned integer\");\n\t\t\treturn sha512::rotater<x_T, 1>(x) ^ sha512::rotater<x_T, 8>(x) ^ (x >> 7);\n\t\t}\n\n\t\ttemplate <typename x_T>\n\t\tstatic x_T lowercase_sigma1(const x_T& x)\n\t\t{\n\t\t\tstatic_assert(std::is_unsigned<x_T>::value, \"Must be unsigned integer\");\n\t\t\treturn sha512::rotater<x_T, 19>(x) ^ sha512::rotater<x_T, 61>(x) ^ (x >> 6);\n\t\t}\n\n\t\ttemplate <typename x_T>\n\t\tstatic x_T uppercase_sigma0(const x_T& x)\n\t\t{\n\t\t\tstatic_assert(std::is_unsigned<x_T>::value, \"Must be unsigned integer\");\n\t\t\treturn sha512::rotater<x_T, 28>(x) ^ sha512::rotater<x_T, 34>(x) ^ sha512::rotater<x_T, 39>(x);\n\t\t}\n\n\t\ttemplate <typename x_T>\n\t\tstatic x_T uppercase_sigma1(const x_T& x)\n\t\t{\n\t\t\tstatic_assert(std::is_unsigned<x_T>::value, \"Must be unsigned integer\");\n\t\t\treturn sha512::rotater<x_T, 14>(x) ^ sha512::rotater<x_T, 18>(x) ^ sha512::rotater<x_T, 41>(x);\n\t\t}\n\n\t\ttemplate <typename xyz_T>\n\t\tstatic xyz_T choice(const xyz_T& x, const xyz_T& y, const xyz_T& z)\n\t\t{\n\t\t\tstatic_assert(std::is_unsigned<xyz_T>::value, \"Must be unsigned integer\");\n\t\t\treturn (x & y) ^ ((~x) & z);\n\t\t}\n\n\t\ttemplate <typename xyz_T>\n\t\tstatic xyz_T majority(const xyz_T& x, const xyz_T& y, const xyz_T& z)\n\t\t{\n\t\t\tstatic_assert(std::is_unsigned<xyz_T>::value, \"Must be unsigned integer\");\n\t\t\treturn (x & y) ^ (x & z) ^ (y & z);\n\t\t}\n\n\t\t// Helper function to copy elements from an array of bytes\n\t\t// into an array of 64 bit unsigned integers in big-endian byte loading.\n\t\t// That means that the first byte copies into the most significant\n\t\t// byte of the first element of the 64 bit integer array etc.\n\t\t//\n\t\t// All of the bytes in the 64-bit integer array that aren't direct\n\t\t// targets to be overridden, are unaffected by this function's operation.\n\t\tstatic void copy_arr_bytes_into_message_block(\n\t\t\t// Source array of bytes\n\t\t\tconst std::uint8_t* const bytes,\n\t\t\t// Length of \"bytes\" array\n\t\t\tconst int num_bytes,\n\t\t\t// Destination\n\t\t\tmessage_block_t& messsage_block,\n\t\t\t// How many bytes are already used inside of the entire message block\n\t\t\t// The first used byte is the most significant one byte of the first\n\t\t\t// element in the array, in big-endian style.\n\t\t\tconst int num_bytes_already_used_in_message_block);\n\n\t\tstatic void compress(const message_block_t& message_block, std::array<std::uint64_t, 8>& hash_values);\n\n\t\t// Index of byte in array of uint64_t based on big-endian byte order.\n\t\tstatic void zero_bytes(message_block_t& messsage_block, int index_byte_to_start_zeroing);\n\t};\n}\n", "meta": {"hexsha": "6058d6205a16dc51825f5c55d5a20a6e4f4a006d", "size": 5555, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rsa_cpp/sha512.hpp", "max_stars_repo_name": "NatanFreeman/rsa_cpp", "max_stars_repo_head_hexsha": "c703be3860d172201eab150826427467e6d0ee7f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-08T18:16:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:16:06.000Z", "max_issues_repo_path": "rsa_cpp/sha512.hpp", "max_issues_repo_name": "NatanFreeman/rsa_cpp", "max_issues_repo_head_hexsha": "c703be3860d172201eab150826427467e6d0ee7f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-12-29T18:07:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-08T18:15:42.000Z", "max_forks_repo_path": "rsa_cpp/sha512.hpp", "max_forks_repo_name": "NatanFreeman/rsa_cpp", "max_forks_repo_head_hexsha": "c703be3860d172201eab150826427467e6d0ee7f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-29T10:42:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T13:46:46.000Z", "avg_line_length": 38.8461538462, "max_line_length": 138, "alphanum_fraction": 0.7227722772, "num_tokens": 1622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5105866963240548}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// random::poisson::devroye::q::lemma2.hpp                        \t        //\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#ifndef BOOST_RANDOM_POISSON_EXT_DEVROYE_Q_LEMMA2_HPP_ER_2010\n#define BOOST_RANDOM_POISSON_EXT_DEVROYE_Q_LEMMA2_HPP_ER_2010\n#include <string>\n#include <boost/mpl/bool.hpp>\n#include <boost/format.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace poisson{\nnamespace devroye{            \nnamespace q{\nnamespace lemma2{\n\n    template<typename T,typename Int,typename IntT>\n    inline \n    T lhs(const T& q, const Int& i_mean,const Int& i_y, const IntT& converter){\n        return q + IntT::convert( i_y * ( i_y + 1 ) ) \n            / IntT::convert( 2 * i_mean );\n    }\n\n    template<typename T,typename Int,typename IntT>\n    inline\n    T upper_bound(const Int& i_mean,const Int& i_y, const IntT& converter){\n        return IntT::convert( i_y * ( i_y + 1 ) * (2 * i_y + 1) )\n         / IntT::convert( 12 * i_mean * i_mean );\n    }\n\nnamespace impl{\n\n    template<typename T,typename Int,typename IntT>\n    inline \n    T lower_bound_common(\n        const Int& i_mean,const Int& i_y,\n        const IntT& converter, const T& den\n    ){\n        T ub = upper_bound<T>(i_mean,i_y,converter);\n        T num = IntT::convert( (i_y * i_y) * ( (i_y + 1) * (i_y + 1) ) ); \n        return ub - num / den;\n    }\n\n    template<typename T,typename Int,typename IntT>\n    inline \n    T lower_bound(\n        const Int& i_mean,const Int& i_y,\n        const IntT& converter, boost::mpl::bool_<true>/*y>=0*/\n    ){\n        T den = IntT::convert(12 * i_mean * i_mean * i_mean);\n        return lower_bound_common<T>(i_mean,i_y,converter,den);\n    }\n\n    template<typename T,typename Int,typename IntT>\n    inline\n    T lower_bound(\n        const Int& i_mean,const Int& i_y,\n        const IntT& converter, boost::mpl::bool_<false>/*y<0*/\n    ){\n        T den = IntT::convert(12 * i_mean * i_mean * (i_mean + i_y + 1) );\n        return lower_bound_common<T>(i_mean,i_y,converter,den);\n    }\n\n}//impl\n\n    template<typename T,typename Int,typename IntT>\n    inline \n    T lower_bound(const Int& i_mean,const Int& i_y,const IntT& converter){\n        if(i_y >= 0){\n           typedef boost::mpl::bool_<true> true_;\n           return lemma2::impl::lower_bound<T>(i_mean,i_y,converter,true_());\n        }else{\n           typedef boost::mpl::bool_<false> false_;\n           return lemma2::impl::lower_bound<T>(i_mean,i_y,converter,false_());\n        }\n    }\n\nnamespace impl{\n\n    template<typename T,typename Int,typename IntT>\n    bool do_raise_error1(\n        const T& lhs,\n        const T& tol,\n        std::string& str,\n        const Int& i_mean,\n        const Int& i_y,\n        const IntT& converter,\n        boost::mpl::bool_<true> /*y>=0*/\n    ){\n        BOOST_ASSERT(i_y>=0);\n        if(lhs <= -tol){\n            const std::string msg = \" [ lemma2 : lhs = %1% >=0 has failed ]\";\n            typedef boost::format f_;\n            f_ f( msg ); \n            f % lhs; \n            str += f.str();\n            return true;        \n        }\n        return false;\n    }\n\n    template<typename T,typename Int,typename IntT>\n    bool do_raise_error1(\n        const T& lhs,\n        const T& tol,\n        std::string& str,\n        const Int& i_mean,\n        const Int& i_y,\n        const IntT& converter,\n        boost::mpl::bool_<false> /*y>=0*/\n    ){\n        BOOST_ASSERT(i_y<0);\n        if(lhs >= tol){\n            const std::string msg = \" [ lemma2.1 : lhs = %1% <=0 has failed ]\";\n            typedef boost::format f_;\n            f_ f( msg ); f % lhs; \n            str += f.str();\n            return true;        \n        }\n        return false;\n    }\n\n}\n\n    template<typename T,typename Int,typename IntT>\n    bool do_raise_error1(\n        const T& q,\n        const T& tol,\n        std::string& str,\n        const Int& i_mean,\n        const Int& i_y,\n        const IntT& converter\n    ){\n        T lhs = lemma2::lhs(q, i_mean, i_y, converter);\n        if(i_y >= 0){\n           typedef boost::mpl::bool_<true> true_;\n           return lemma2::impl::do_raise_error1(\n               lhs,tol,str,i_mean,i_y,converter,true_());\n        }else{\n           typedef boost::mpl::bool_<false> false_;\n           return lemma2::impl::do_raise_error1(\n               lhs,tol,str,i_mean,i_y,converter,false_());\n        }\n    }\n\n    template<typename T,typename Int,typename IntT>\n    bool do_raise_error2(\n        const T& q,\n        const T& tol,\n        std::string& str,\n        const Int& i_mean,\n        const Int& i_y,\n        const IntT& converter\n    ){\n        T lhs = lemma2::lhs(q, i_mean, i_y, converter);\n        T ub = lemma2::upper_bound<T>(i_mean,i_y, converter);\n        if(lhs > ub + tol){\n            const std::string msg \n                = \" [ lemma2.2 : lhs = %1% < %2% has failed ]\";\n            typedef boost::format f_;\n            f_ f( msg ); f % lhs % ub; \n            str += f.str();\n            return true;\n        }\n        return false;\n    }\n\n    template<typename T,typename Int,typename IntT>\n    bool do_raise_error3(\n        const T& q,\n        const T& tol,\n        std::string& str,\n        const Int& i_mean,\n        const Int& i_y,\n        const IntT& converter\n    ){\n        T lhs = lemma2::lhs(q, i_mean, i_y, converter);\n        T lb = lemma2::lower_bound<T>(i_mean,i_y,converter);\n        if(lhs + tol < lb){\n            const std::string msg \n               = \" [ lemma2.3 : lhs = %1% > %2% has failed ]\";\n            typedef boost::format f_;\n            f_ f( msg ); f % lhs % lb; \n            str += f.str();\n            return true;\n        }\n        return false;\n    }\n\n}// lemma2\n}// q\n}// devroye\n}// poisson\n}// random\n}// boost\n\n#endif\n", "meta": {"hexsha": "24852594f42fe628c332a2a315f67637fb384ad8", "size": 6184, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/poisson_ext/devroye/q_function/lemma2.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": "random/boost/random/poisson_ext/devroye/q_function/lemma2.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": "random/boost/random/poisson_ext/devroye/q_function/lemma2.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.4630541872, "max_line_length": 79, "alphanum_fraction": 0.5203751617, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5105866963240548}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/20/problem20.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem20 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem20::solve(10);\n        BOOST_CHECK_EQUAL(res, 27);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem20::solve();\n        BOOST_CHECK_EQUAL(res, 648);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "f6b78e2dc1fb4fdcc6b9aa55dab41a54ff260ff1", "size": 491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem20.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": "tests/1-50/test_problem20.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": "tests/1-50/test_problem20.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.380952381, "max_line_length": 51, "alphanum_fraction": 0.6741344196, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5105866862927361}}
{"text": "//\n// Created by devi on 1/9/20.\n//\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/property_map/transform_value_property_map.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <iostream>\n#include <fstream>\n#include \"Node.h\"\n#include <boost/graph/astar_search.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/random.hpp>\n\nnamespace boost {\n    enum vertex_Node_t { vertex_Node = 0 };\n    BOOST_INSTALL_PROPERTY(vertex, Node);\n}\n\nint main() {\n    typedef boost::adjacency_list< boost::vecS, boost::vecS, boost::undirectedS,\n            boost::property<boost::vertex_Node_t, std::shared_ptr<Node> > > Graph;\n\n\n    typedef boost::graph_traits <Graph>::edge_descriptor Edge;\n    typedef boost::graph_traits <Graph>::vertex_descriptor Vertex;\n    typedef std::pair<int, int> E;\n\n\n    std::shared_ptr<Node> object_one = std::make_shared<Node>(123, \"obj1\");\n    std::shared_ptr<Node> object_two = std::make_shared<Node>(456, \"obj2\");\n    std::shared_ptr<Node> object_three = std::make_shared<Node>(789, \"obj3\");\n\n    std::shared_ptr<Node> object_four = std::make_shared<Node>(101, \"obj4\");\n    std::shared_ptr<Node> object_five = std::make_shared<Node>(121, \"obj5\");\n    std::shared_ptr<Node> object_six = std::make_shared<Node>(145, \"obj6\");\n\n    const int num_nodes = 5;\n    E edge_array[] = { E(0, 2), E(1, 3), E(1, 4), E(2, 1), E(2, 3),\n                       E(3, 4), E(4, 0), E(4, 1)\n    };\n    int weights[] = { 1, 1, 2, 7, 3, 1, 1, 1 };\n    std::size_t num_edges = sizeof(edge_array) / sizeof(E);\n\n    Graph g;\n\n    Vertex vertex_one = boost::add_vertex(object_one, g);\n    Vertex vertex_two = boost::add_vertex(object_two, g);\n    Vertex vertex_three = boost::add_vertex(object_three, g);\n    Vertex vertex_four = boost::add_vertex(object_four, g);\n    Vertex vertex_five = boost::add_vertex(object_five, g);\n    Vertex vertex_six = boost::add_vertex(object_six, g);\n\n    boost::add_edge(vertex_one, vertex_two, g);\n    boost::add_edge(vertex_one, vertex_three, g);\n    boost::add_edge(vertex_two, vertex_six, g);\n    boost::add_edge(vertex_three, vertex_five, g);\n    boost::add_edge(vertex_five, vertex_two, g);\n    boost::add_edge(vertex_six, vertex_one, g);\n/*\n    boost::property_map<Graph, boost::edge_weight_t >::type weight = get(boost::edge_weight, g);\n    std::vector < Edge > spanning_tree;\n\n    boost::kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n\n    std::cout << \"Print the edges in the MST:\" << std::endl;\n\n    for (std::vector < Edge >::iterator ei = spanning_tree.begin();\n         ei != spanning_tree.end(); ++ei)\n    {\n        std::cout << source(*ei, g)\n                  << \" <--> \"\n                  << target(*ei, g)\n                  << \" with weight of \"\n                  << weight[*ei]\n                  << std::endl;\n    }*/\n\n    {\n        boost::dynamic_properties dp;\n        boost::property_map<Graph , boost::vertex_Node_t>::type custom = get(boost::vertex_Node, g);\n        dp.property(\"node_id\", boost::make_transform_value_property_map(std::mem_fn(&Node::get_id), custom));\n        dp.property(\"label\", boost::make_transform_value_property_map(std::mem_fn(&Node::get_name), custom));\n        boost::write_graphviz_dp(std::cout, g, dp);\n    }\n\n    std::vector < Edge > spanning_tree;\n    boost::kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n    std::cout << \"Print the edges in the MST:\" << std::endl;\n\n    for (std::vector < Edge >::iterator ei = spanning_tree.begin();\n         ei != spanning_tree.end(); ++ei)\n    {\n        std::cout << source(*ei, g)\n                  << \" <--> \"\n                  << target(*ei, g)\n                  << std::endl;\n    }\n\n    return 0;\n}", "meta": {"hexsha": "e3e35a6ae3c4ee1f5ce20d1691ab67f60bd167d0", "size": 3726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boostGraphRef/OwnClassExample.cpp", "max_stars_repo_name": "fossabot/redisgraph-cplusplus", "max_stars_repo_head_hexsha": "18a61e7521d42cc13a25d61cb61dae8a3dc5a057", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-06T06:51:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T06:51:53.000Z", "max_issues_repo_path": "boostGraphRef/OwnClassExample.cpp", "max_issues_repo_name": "fossabot/redisgraph-cplusplus", "max_issues_repo_head_hexsha": "18a61e7521d42cc13a25d61cb61dae8a3dc5a057", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-17T03:01:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-17T03:01:59.000Z", "max_forks_repo_path": "boostGraphRef/OwnClassExample.cpp", "max_forks_repo_name": "fossabot/redisgraph-cplusplus", "max_forks_repo_head_hexsha": "18a61e7521d42cc13a25d61cb61dae8a3dc5a057", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-17T02:59:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-17T02:59:11.000Z", "avg_line_length": 36.8910891089, "max_line_length": 109, "alphanum_fraction": 0.629898014, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.510586682293159}}
{"text": "#include \"stiffness_checker/SharedConst.h\"\n#include \"stiffness_checker/StiffnessSolver.h\"\n#include <Eigen/LU>\n#include <Eigen/SparseCholesky>\n#include <iostream>\n\nnamespace conmech\n{\nnamespace stiffness_checker\n{\n\nbool StiffnessSolver::solveSparseSimplicialLDLT(\n    const Eigen::SparseMatrix<double>& A, const Eigen::VectorXd& b, Eigen::VectorXd& x, const bool& verbose)\n{\n  if(timing_)\n  {\n    solve_timer_.Start();\n  }\n\n  Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;\n  solver.compute(A);\n\n  if (solver.info() == Eigen::NumericalIssue)\n  {\n    if (verbose)\n    {\n      std::cerr << \"SolverSystem(LDLT): Error in Decomposition!: \" << solver.info() << std::endl;\n    }\n    int info = 0;\n    auto Diag = solver.vectorD();\n    for (int i = 0; i < Diag.size(); i++)\n    {\n      if (std::abs(Diag[i]) < conmech::DOUBLE_EPS)\n      {\n        if (verbose)\n        {\n          std::cerr << \" SolveSystem(LDLT): zero found on diagonal ...\" << std::endl;\n          std::cerr << \" d[\" << i << \"] = \" << Diag[i] << std::endl;\n        }\n      }\n      if (Diag[i] < - conmech::DOUBLE_EPS)\n      {\n        if (verbose)\n        {\n          std::cerr << \" SolveSystem(LDLT): negative number found on diagonal ...\" << std::endl;\n          std::cerr << \" d[\" << i << \"] = \" << Diag[i] << std::endl;\n        }\n        info--;\n      }\n    }\n    if (info < 0)\n    {\n      if (verbose)\n      {\n        std::cerr << \"Stiffness Matrix is not positive definite: \" << info \n          << \" negative elements found on decomp diagonal of K.\" << std::endl;\n        std::cerr << \"Matrix size:\" << A.rows() << \", \" << A.cols() << std::endl;\n        std::cerr << \"The stucture may have mechanism and thus not stable in general,\" << std::endl;\n        std::cerr << \"please Make sure that all six rigid body translations are restrained!\" << std::endl;\n      }\n    }\n    return false;\n  }\n\n  x = solver.solve(b);\n  if (solver.info() != Eigen::Success)\n  {\n    if (verbose)\n    {\n      std::cerr << \"SolverSystem(LDLT): Error in Solving!\" << std::endl;\n    }\n    return false;\n  }\n\n  if(timing_)\n  {\n    solve_timer_.Stop();\n  }\n  return true;\n}\n\nbool StiffnessSolver::solveSystemLU(\n    const Eigen::MatrixXd& A, const Eigen::VectorXd& b, Eigen::VectorXd& x)\n{\n  if(timing_)\n  {\n    solve_timer_.Start();\n  }\n\n  x = A.fullPivLu().solve(b);\n\n  if(timing_)\n  {\n    solve_timer_.Stop();\n  }\n\n  if ((A*x).isApprox(b))\n  {\n    return true;\n  }\n  else\n  {\n//    std::cout << \"A is invertible? - \" << A.fullPivLu().isInvertible() << std::endl;\n    return false;\n  }\n}\n\n} // namespace stiffness_checker\n} // namespace conmech", "meta": {"hexsha": "0df685bc2bba1c6fba9ffda2bd19bf92f70a6593", "size": 2594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/stiffness_checker/StiffnessSolver.cpp", "max_stars_repo_name": "yijiangh/conmech", "max_stars_repo_head_hexsha": "9f24230f08587c5e62e3b482f8829f5ea449a169", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-12-10T17:52:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-12T05:49:34.000Z", "max_issues_repo_path": "src/stiffness_checker/StiffnessSolver.cpp", "max_issues_repo_name": "yijiangh/conmech", "max_issues_repo_head_hexsha": "9f24230f08587c5e62e3b482f8829f5ea449a169", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-11-28T04:00:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-14T21:20:38.000Z", "max_forks_repo_path": "src/stiffness_checker/StiffnessSolver.cpp", "max_forks_repo_name": "yijiangh/conmech", "max_forks_repo_head_hexsha": "9f24230f08587c5e62e3b482f8829f5ea449a169", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-23T01:19:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-23T01:19:00.000Z", "avg_line_length": 23.7981651376, "max_line_length": 108, "alphanum_fraction": 0.5643793369, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5104579967056959}}
{"text": "#include <iostream>\n#include <fstream>\n#include <utility>\n#include <sstream>\n\n#include <boost/numeric/mtl/mtl.hpp>\n\ntypedef double value_type;\ntypedef std::size_t size_type;\ntypedef mtl::dense_vector<value_type>  vector_type;\ntypedef mtl::compressed2D<value_type>  matrix_type;\nconst double pi(3.14159265358979323846);\n\ntemplate <typename Vector, typename Matrix>\nclass grad_f_ftor\n{\n  public:\n    grad_f_ftor(const Matrix& M, const Matrix& K, const Matrix& G, const value_type& beta, const value_type& w) \n      : M(M), K(K), G(G), beta(beta), w(w)\n      {\n\tq.change_dim(num_cols(G));\n\tx.change_dim(num_cols(G));\n\tx=0.0; q=0.0;\n\tfor(size_type i=1; i< size(x); i++)\n\t  x(i)= x(i-1) + 0.01;\n      }\n      \n    //get timedependent input q for the heating\n    Vector get_input(const value_type& time) \n    {\n      value_type center(0.5*sin(2*pi*time)+0.5);\n      for(size_type i=0; i< size(x); i++)\n\t  q(i)=beta*cos(std::min(std::abs(pi*(x(i)-center)/(2*w)),pi/2));\n      return q;\n    }\n    template <typename VectorIn>\n    Vector operator()(const VectorIn& u, const value_type& time) \n    {\n\tq=get_input(time);\n\tVector x(K*u + G*q);\n\treturn x;\n    }\n \n  private:\n    Vector      q, x;\n    Matrix      M, K, G;\n    value_type  beta, w;\n   \n};\n\n\ntemplate <typename grad_f_ftor, typename Vector, typename Matrix>\nVector ode23s(grad_f_ftor func, value_type start_time, value_type end_time, Vector start_value, Matrix M, Matrix K){\n\n  value_type time(start_time), time_step(0.005), h= 0.005, gamma(1-1/sqrt(2));\n  mtl::dense2D<value_type> LU(M-h*gamma*K);\n  lu(LU);\n  Vector x(start_value);\n  size_type time_counter(0);\n  Vector k1, k2, step1, step2;\n  while (time < end_time){\n      k1= lu_solve_apply(LU, func(x,time));\n      step1= x + h * k1;\n      step2= func(step1, time + time_step) - 2*M*k1;\n      k2= lu_solve_apply(LU, step2);\n      save_data(x, time_counter);\n      x+= 3/2*h*k1 + 1/2*h*k2; \n      time_counter++;\n      time+= time_step;\n  }\n  return x;\n}\n\n//save current state of solution x(time)\ntemplate<typename Vector>\nvoid save_data(const Vector& x, const size_type& time) \n{\n    std::stringstream name;\n    name  <<\"plot_data_\" << time <<\".dat\";\n#if 1\n    std::cout<< \"#!/usr/bin/gnuplot\\n\";\n    std::cout<< \"set term png\\n\";\n   // std::cout<< \"set zrange[-4:14]\\n\";\n    std::cout<< \"set output \\\"\"<<time<<\".png\\\"\\n\";\n    std::cout<< \"splot './plot_data_\"<< time<<\".dat' using 1:2:3 with pm3d\\n\";\n#endif\n    std::fstream f;\n    f.open(name.str().c_str(), std::ios::out);\n    size_type n(1111), n1(101);\n \n    size_type row(0), col(0);\n    for(size_type i=0; i < n; i++){\n      if(i%(n/n1)==0){\n\trow=0;col+=1;\n\tf << \"\\n\";\n      }\n      f <<  col << \" \" << row << \" \" << x(i) << \"\\n\";\n      row+=1;\n    }\n    f.close();   \n}\n\n \nint main( int  , char ** )\n{\n     //read j\u00f6rgs matrices\n    matrix_type M(mtl::io::matrix_market( \"M.mtx\")),\n\t\tK(mtl::io::matrix_market( \"K.mtx\")),\n\t\tG(mtl::io::matrix_market( \"G.mtx\"));\n   \n    size_type n(num_rows(K));\n    value_type  start_time(0.0), end_time(1.0);\n    vector_type  x(n,0.0), x0(n,0.0);\n  \n    grad_f_ftor< vector_type, matrix_type >  grad_f(M, K, G, 0.2, 0.1);\n    \n    x= ode23s(grad_f, start_time, end_time, x0, M, K);\n    \n    return 0;\n}", "meta": {"hexsha": "d0d4596569b7dd607247672e7664392963a32d1e", "size": 3200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/ode_solver.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/ode_solver.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/ode_solver.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.6666666667, "max_line_length": 116, "alphanum_fraction": 0.603125, "num_tokens": 1053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.510436794263133}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::map_pdf::distributions::gamma::include.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_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_GAMMA_INCLUDE_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_GAMMA_INCLUDE_HPP_ER_2009\n\n#include <boost/math/distributions/gamma.hpp>\n\n#include <boost/statistics/detail/distribution_toolkit/distributions/gamma/derivative_log_unnormalized_pdf.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/gamma/description.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/gamma/is_log_concave.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/gamma/is_math_distribution.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/gamma/log_unnormalized_pdf.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/gamma/random.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/gamma/os.hpp>\n\n#endif\n", "meta": {"hexsha": "2520c2e6bf7fa3969ea7a7eac6d21eb48ddf1b42", "size": 1518, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/gamma/include.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/include.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/include.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": 66.0, "max_line_length": 111, "alphanum_fraction": 0.662055336, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.5104367773327768}}
{"text": "#include \"Generic/common/leak_detection.h\"\r\n\r\n#include \"PriorLoss.h\"\r\n#include <iostream>\r\n#include <boost/lexical_cast.hpp>\r\n#include \"Generic/common/SessionLogger.h\"\r\n#include \"Generic/common/UnrecoverableException.h\"\r\n#include \"ActiveLearning/DataView.h\"\r\n#include \"ActiveLearning/SmoothedL1.h\"\r\n\r\n\r\nusing Eigen::VectorXd;\r\nusing Eigen::SparseVector;\r\n\r\nPriorLoss::PriorLoss(InferenceDataView_ptr data, double prior, double lossWeight,\r\n\t\t\t\t\t Loss loss) \r\n: _data(data), _prior(prior), _lossWeight(lossWeight), _lossFunc(loss) {}\r\n\r\ndouble PriorLoss::operator()(VectorXd& gradient, size_t thread_idx,\r\n\t\tsize_t n_threads) const \r\n{\r\n\tdouble loss = 0.0;\r\n\r\n\tfor (int i=static_cast<int>(thread_idx); i<static_cast<int>(_data->nInstances()); i+=static_cast<int>(n_threads)) {\r\n\t\tdouble pos = _data->prediction(i);\r\n\r\n\t\tif (_lossFunc == KL) {\r\n\t\t\tdouble neg = 1.0 - pos;\r\n\r\n\t\t\tloss -= _lossWeight * (_prior * log (_prior/pos) +\r\n\t\t\t\t(1.0-_prior)*log((1.0-_prior)/neg));\r\n\r\n\t\t\tdouble factor = _lossWeight * (pos - _prior);\r\n\r\n\t\t\tSparseVector<double>::InnerIterator it(_data->features(i));\r\n\t\t\tfor (; it; ++it) {\r\n\t\t\t\tint inst = it.index();\r\n\t\t\t\tgradient(it.index()) -= factor * it.value();\r\n\t\t\t}\r\n\t\t} else { // _lossFunc == L1\r\n\t\t\tloss += SmoothedL1::SmoothedL1ProbConstant(pos, _prior, \r\n\t\t\t\t_data->features(i), gradient, _lossWeight);\r\n\t\t}\r\n\t} \r\n\t_debug_loss = loss;\r\n\treturn loss;\r\n}\r\n\r\ndouble PriorLoss::forInstance(int inst, SparseVector<double>& gradient) const {\r\n\tdouble ret = 0.0;\r\n\r\n\tdouble pos = _data->prediction(inst);\r\n\r\n\tif (_lossFunc == KL) {\r\n\t\tdouble neg = 1.0 - pos;\r\n\r\n\t\tret -= _lossWeight * (_prior * log (_prior/pos) +\r\n\t\t\t(1.0-_prior)*log((1.0-_prior)/neg));\r\n\r\n\t\tdouble factor = _lossWeight * (pos - _prior);\r\n\r\n\t\tSparseVector<double>::InnerIterator it(_data->features(inst));\r\n\t\tfor (; it; ++it) {\r\n\t\t\tint inst = it.index();\r\n\t\t\tgradient.coeffRef(it.index()) -= factor * it.value();\r\n\t\t}\r\n\t} else { // _lossFunc == L1\r\n\t\tthrow UnrecoverableException(\"PriorLoss::forInstance\",\r\n\t\t\t\"Instance-wise loss not yet implemented for L1 (but it's not \"\r\n\t\t\t\"hard to do)\");\r\n/*\t\tret += SmoothedL1::SmoothedL1ProbConstant(pos, _prior,\r\n\t\t\t_data->features(inst), gradient, _lossWeight);*/\r\n\t}\r\n\r\n\treturn ret;\r\n}\r\n\r\nstd::wstring PriorLoss::status() const {\r\n\treturn L\"prior_loss = \" + boost::lexical_cast<std::wstring>(_debug_loss);\r\n}\r\n\r\nvoid PriorLoss::snapshot() {\r\n}\r\n", "meta": {"hexsha": "2297d14c16c913edf22f9493744a899312659ede", "size": 2381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ActiveLearning/objectives/PriorLoss.cpp", "max_stars_repo_name": "BBN-E/serif", "max_stars_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T19:57:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T19:57:00.000Z", "max_issues_repo_path": "src/ActiveLearning/objectives/PriorLoss.cpp", "max_issues_repo_name": "BBN-E/serif", "max_issues_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "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/ActiveLearning/objectives/PriorLoss.cpp", "max_forks_repo_name": "BBN-E/serif", "max_forks_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "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.3452380952, "max_line_length": 117, "alphanum_fraction": 0.6572868543, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893520001, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5104367716453027}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2017-2018, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_DENSIFY_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_DENSIFY_HPP\n\n\n#include <boost/geometry/algorithms/detail/convert_point_to_point.hpp>\n#include <boost/geometry/algorithms/detail/signed_size_type.hpp>\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/srs/spheroid.hpp>\n#include <boost/geometry/strategies/densify.hpp>\n#include <boost/geometry/strategies/geographic/parameters.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace densify\n{\n\n\n/*!\n\\brief Densification of geographic segment.\n\\ingroup strategies\n\\tparam FormulaPolicy The geodesic formulas used internally.\n\\tparam Spheroid The spheroid model.\n\\tparam CalculationType \\tparam_calculation\n\n\\qbk{\n[heading See also]\n\\* [link geometry.reference.algorithms.densify.densify_4_with_strategy densify (with strategy)]\n\\* [link geometry.reference.srs.srs_spheroid srs::spheroid]\n}\n */\ntemplate\n<\n    typename FormulaPolicy = strategy::andoyer,\n    typename Spheroid = srs::spheroid<double>,\n    typename CalculationType = void\n>\nclass geographic\n{\npublic:\n    geographic()\n        : m_spheroid()\n    {}\n\n    explicit geographic(Spheroid const& spheroid)\n        : m_spheroid(spheroid)\n    {}\n\n    template <typename Point, typename AssignPolicy, typename T>\n    inline void apply(Point const& p0, Point const& p1, AssignPolicy & policy, T const& length_threshold) const\n    {\n        typedef typename AssignPolicy::point_type out_point_t;\n        typedef typename select_most_precise\n            <\n                typename coordinate_type<Point>::type,\n                typename coordinate_type<out_point_t>::type,\n                CalculationType\n            >::type calc_t;\n\n        typedef typename FormulaPolicy::template direct<calc_t, true, false, false, false> direct_t;\n        typedef typename FormulaPolicy::template inverse<calc_t, true, true, false, false, false> inverse_t;\n\n        typename inverse_t::result_type\n            inv_r = inverse_t::apply(get_as_radian<0>(p0), get_as_radian<1>(p0),\n                                     get_as_radian<0>(p1), get_as_radian<1>(p1),\n                                     m_spheroid);\n\n        BOOST_GEOMETRY_ASSERT(length_threshold > T(0));\n\n        signed_size_type n = signed_size_type(inv_r.distance / length_threshold);\n        if (n <= 0)\n            return;\n\n        calc_t step = inv_r.distance / (n + 1);\n\n        calc_t current = step;\n        for (signed_size_type i = 0 ; i < n ; ++i, current += step)\n        {\n            typename direct_t::result_type\n                dir_r = direct_t::apply(get_as_radian<0>(p0), get_as_radian<1>(p0),\n                                        current, inv_r.azimuth,\n                                        m_spheroid);\n\n            out_point_t p;\n            set_from_radian<0>(p, dir_r.lon2);\n            set_from_radian<1>(p, dir_r.lat2);\n            geometry::detail::conversion::point_to_point\n                <\n                    Point, out_point_t,\n                    2, dimension<out_point_t>::value\n                >::apply(p0, p);\n\n            policy.apply(p);\n        }\n    }\n\nprivate:\n    Spheroid m_spheroid;\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <>\nstruct default_strategy<geographic_tag>\n{\n    typedef strategy::densify::geographic<> type;\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::densify\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DENSIFY_HPP\n", "meta": {"hexsha": "a31ba72200e271ce2fefbb6523c51b7b18f3503c", "size": 4004, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/geographic/densify.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/geographic/densify.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/geographic/densify.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": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 29.2262773723, "max_line_length": 111, "alphanum_fraction": 0.6705794206, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5104367660238613}}
{"text": "/*\n * Copyright 2016-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n#include \"LMPC.h\"\n#include \"PreviewSystem.h\"\n#include \"QuadProgSolver.h\"\n#include \"constraints.h\"\n#include \"costFunctions.h\"\n#include \"doctest.h\"\n#include \"systems.h\"\n#include \"tools.h\"\n#ifdef EIGEN_QLD_FOUND\n#include \"QLDSolver.h\"\n#endif\n#ifdef EIGEN_LSSOL_FOUND\n#include \"LSSOLSolver.h\"\n#endif\n#ifdef EIGEN_GUROBI_FOUND\n#include \"GUROBISolver.h\"\n#endif\n#ifdef EIGEN_OSQP_FOUND\n#include \"OSQPSolver.h\"\n#endif\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <memory>\n#include <numeric>\n#include <vector>\n\n/********************************************************************************************************\n *                               Check Bound constraint                                                 *\n ********************************************************************************************************/\n\nTEST_CASE_FIXTURE(BoundedSystem, \"MPC_TARGET_COST_WITH_BOUND_CONSTRAINTS\")\n{\n    tools::SolverTimers sTimers;\n\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    auto xCost = std::make_shared<copra::TargetCost>(M, xd);\n    auto uCost = std::make_shared<copra::ControlCost>(N, ud);\n    auto trajConstr = std::make_shared<copra::TrajectoryBoundConstraint>(xLower, xUpper);\n    auto contConstr = std::make_shared<copra::ControlBoundConstraint>(uLower, uUpper);\n    xCost->weights(wx);\n    uCost->weights(wu);\n\n    controller.addCost(xCost);\n    controller.addCost(uCost);\n    controller.addConstraint(trajConstr);\n    controller.addConstraint(contConstr);\n\n    auto pcCheck = [&](const std::string& solverName, copra::SolverFlag sFlag, std::unique_ptr<copra::SolverInterface>&& solver = nullptr) {\n        if (solver) {\n            controller.useSolver(std::move(solver));\n        } else {\n            controller.selectQPSolver(sFlag);\n        }\n\n        REQUIRE(controller.solve());\n        sTimers.st.emplace_back(solverName, controller.solveTime() * 1e3);\n        sTimers.ct.emplace_back(solverName, controller.solveAndBuildTime() * 1e3);\n        sTimers.bt.emplace_back(solverName, (controller.solveAndBuildTime() - controller.solveTime()) * 1e3);\n\n        Eigen::VectorXd fullTraj = controller.trajectory();\n        auto trajLen = fullTraj.rows() / 2;\n        Eigen::VectorXd posTraj(trajLen);\n        Eigen::VectorXd velTraj(trajLen);\n        for (auto i = 0; i < trajLen; ++i) {\n            posTraj(i) = fullTraj(2 * i);\n            velTraj(i) = fullTraj(2 * i + 1);\n        }\n        Eigen::VectorXd control = controller.control();\n\n        // Check result\n        CHECK_LE(std::abs(xd(1) - velTraj.tail(1)(0)), 0.001);\n\n        // Check constrains\n        REQUIRE_LE(posTraj.maxCoeff(), x0(0));\n        REQUIRE_LE(velTraj.maxCoeff(), xUpper(1) + 1e-6);\n        REQUIRE_LE(control.maxCoeff(), uUpper(0) + 1e-6);\n    };\n\n    for (auto s : tools::Solvers) {\n        std::unique_ptr<copra::SolverInterface> solver(nullptr);\n#ifdef EIGEN_LSSOL_FOUND\n        if (s.second == copra::SolverFlag::LSSOL) {\n            solver = copra::solverFactory(copra::SolverFlag::LSSOL);\n            solver->SI_maxIter(200);\n        }\n#endif\n        pcCheck(s.first, s.second, std::move(solver));\n    }\n\n    MESSAGE(tools::getSortedTimers(sTimers));\n}\n\nTEST_CASE_FIXTURE(BoundedSystem, \"MPC_TRAJECTORY_COST_WITH_BOUND_CONSTRAINTS\")\n{\n    tools::SolverTimers sTimers;\n\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    auto xCost = std::make_shared<copra::TrajectoryCost>(M, xd);\n    auto uCost = std::make_shared<copra::ControlCost>(N, ud);\n    auto trajConstr = std::make_shared<copra::TrajectoryBoundConstraint>(xLower, xUpper);\n    auto contConstr = std::make_shared<copra::ControlBoundConstraint>(uLower, uUpper);\n    xCost->weights(wx);\n    uCost->weights(wu);\n\n    controller.addCost(xCost);\n    controller.addCost(uCost);\n    controller.addConstraint(trajConstr);\n    controller.addConstraint(contConstr);\n\n    auto pcCheck = [&](const std::string& solverName, copra::SolverFlag sFlag, std::unique_ptr<copra::SolverInterface>&& solver = nullptr) {\n        std::unique_ptr<copra::SolverInterface> newSolver;\n        if (solver) {\n            newSolver = std::move(solver);\n        } else {\n            newSolver = solverFactory(sFlag);\n        }\n#ifdef EIGEN_OSQP_FOUND\n        // Increase precision\n        if (sFlag == copra::SolverFlag::OSQP) {\n            auto& bs = static_cast<copra::OSQPSolver&>(*newSolver).baseSolver();\n            bs.scalingIter(0);\n            bs.absConvergenceTol(1e-6);\n            bs.relConvergenceTol(1e-6);\n            bs.primalInfeasibilityTol(1e-7);\n            bs.dualInfeasibilityTol(1e-7);\n        }\n#endif\n        controller.useSolver(std::move(newSolver));\n\n        REQUIRE(controller.solve());\n        sTimers.st.emplace_back(solverName, controller.solveTime() * 1e3);\n        sTimers.ct.emplace_back(solverName, controller.solveAndBuildTime() * 1e3);\n        sTimers.bt.emplace_back(solverName, (controller.solveAndBuildTime() - controller.solveTime()) * 1e3);\n\n        Eigen::VectorXd fullTraj = controller.trajectory();\n        auto trajLen = fullTraj.rows() / 2;\n        Eigen::VectorXd posTraj(trajLen);\n        Eigen::VectorXd velTraj(trajLen);\n        for (auto i = 0; i < trajLen; ++i) {\n            posTraj(i) = fullTraj(2 * i);\n            velTraj(i) = fullTraj(2 * i + 1);\n        }\n        Eigen::VectorXd control = controller.control();\n\n        // Check result\n        CHECK_LE(std::abs(xd(1) - velTraj.tail(1)(0)), 0.001);\n\n        // Check constrains\n        REQUIRE_LE(posTraj.maxCoeff(), x0(0));\n        REQUIRE_LE(velTraj.maxCoeff(), xUpper(1) + 1e-6);\n        REQUIRE_LE(control.maxCoeff(), uUpper(0) + 1e-6); // QuadProg allows to exceeds the constrain of a small amount.\n    };\n\n    for (auto s : tools::Solvers) {\n        std::unique_ptr<copra::SolverInterface> solver(nullptr);\n#ifdef EIGEN_LSSOL_FOUND\n        if (s.second == copra::SolverFlag::LSSOL) {\n            solver = copra::solverFactory(copra::SolverFlag::LSSOL);\n            solver->SI_maxIter(200);\n        }\n#endif\n        pcCheck(s.first, s.second, std::move(solver));\n    }\n\n    MESSAGE(tools::getSortedTimers(sTimers));\n}\n\nTEST_CASE_FIXTURE(BoundedSystem, \"MPC_MIXED_COST_WITH_BOUND_CONSTRAINTS\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    auto xCost = std::make_shared<copra::MixedCost>(M, Eigen::MatrixXd::Zero(2, 1), xd); // min(||X - Xt||^2)\n    auto uCost = std::make_shared<copra::MixedCost>(Eigen::MatrixXd::Zero(1, 2), N, ud); // min(||U - Ut||^2)\n    auto trajConstr = std::make_shared<copra::TrajectoryBoundConstraint>(xLower, xUpper);\n    auto contConstr = std::make_shared<copra::ControlBoundConstraint>(uLower, uUpper);\n    xCost->weights(wx);\n    uCost->weights(wu);\n\n    controller.addCost(xCost);\n    controller.addCost(uCost);\n    controller.addConstraint(trajConstr);\n    controller.addConstraint(contConstr);\n\n    REQUIRE(controller.solve());\n\n    Eigen::VectorXd fullTraj = controller.trajectory();\n    auto trajLen = fullTraj.rows() / 2;\n    Eigen::VectorXd posTraj(trajLen);\n    Eigen::VectorXd velTraj(trajLen);\n    for (auto i = 0; i < trajLen; ++i) {\n        posTraj(i) = fullTraj(2 * i);\n        velTraj(i) = fullTraj(2 * i + 1);\n    }\n    Eigen::VectorXd control = controller.control();\n\n    // Check result\n    CHECK_LE(std::abs(xd(1) - velTraj.tail(3)(0)), 0.001); // Check X_{N-1} for mixed cost because X_N is not evaluated.\n\n    // Check constrains\n    REQUIRE_LE(posTraj.maxCoeff(), x0(0));\n    REQUIRE_LE(velTraj.maxCoeff(), xUpper(1) + 1e-6);\n    REQUIRE_LE(control.maxCoeff(), uUpper(0) + 1e-6); // QuadProg allows to exceeds the constrain of a small amount.\n}\n\n/********************************************************************************************************\n *                            Check inequality constraint                                               *\n ********************************************************************************************************/\n\nTEST_CASE_FIXTURE(IneqSystem, \"MPC_TARGET_COST_WITH_INEQUALITY_CONSTRAINTS\")\n{\n    tools::SolverTimers sTimers;\n\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    auto xCost = std::make_shared<copra::TargetCost>(M, xd);\n    auto uCost = std::make_shared<copra::ControlCost>(N, ud);\n    auto trajConstr = std::make_shared<copra::TrajectoryConstraint>(E, p);\n    auto contConstr = std::make_shared<copra::ControlConstraint>(G, h);\n    xCost->weights(wx);\n    uCost->weights(wu);\n\n    controller.addCost(xCost);\n    controller.addCost(uCost);\n    controller.addConstraint(trajConstr);\n    controller.addConstraint(contConstr);\n\n    auto pcCheck = [&](const std::string& solverName, copra::SolverFlag sFlag, std::unique_ptr<copra::SolverInterface>&& solver = nullptr) {\n        std::unique_ptr<copra::SolverInterface> newSolver;\n        if (solver) {\n            newSolver = std::move(solver);\n        } else {\n            newSolver = solverFactory(sFlag);\n        }\n#ifdef EIGEN_OSQP_FOUND\n        // Increase precision\n        if (sFlag == copra::SolverFlag::OSQP) {\n            auto& bs = static_cast<copra::OSQPSolver&>(*newSolver).baseSolver();\n            bs.scalingIter(0);\n            bs.absConvergenceTol(1e-6);\n            bs.relConvergenceTol(1e-6);\n            bs.primalInfeasibilityTol(1e-7);\n            bs.dualInfeasibilityTol(1e-7);\n        }\n#endif\n        controller.useSolver(std::move(newSolver));\n\n        REQUIRE(controller.solve());\n        sTimers.st.emplace_back(solverName, controller.solveTime() * 1e3);\n        sTimers.ct.emplace_back(solverName, controller.solveAndBuildTime() * 1e3);\n        sTimers.bt.emplace_back(solverName, (controller.solveAndBuildTime() - controller.solveTime()) * 1e3);\n\n        Eigen::VectorXd fullTraj = controller.trajectory();\n        auto trajLen = fullTraj.rows() / 2;\n        Eigen::VectorXd posTraj(trajLen);\n        Eigen::VectorXd velTraj(trajLen);\n        for (auto i = 0; i < trajLen; ++i) {\n            posTraj(i) = fullTraj(2 * i);\n            velTraj(i) = fullTraj(2 * i + 1);\n        }\n        Eigen::VectorXd control = controller.control();\n\n        // Check result\n        CHECK_LE(std::abs(xd(1) - velTraj.tail(1)(0)), 0.001);\n\n        // Check constrains\n        REQUIRE_LE(posTraj.maxCoeff(), x0(0));\n        REQUIRE_LE(velTraj.maxCoeff(), p(0) + 1e-6);\n        REQUIRE_LE(control.maxCoeff(), h(0) + 1e-6);\n    };\n\n    for (auto s : tools::Solvers) {\n        std::unique_ptr<copra::SolverInterface> solver(nullptr);\n#ifdef EIGEN_LSSOL_FOUND\n        if (s.second == copra::SolverFlag::LSSOL) {\n            solver = copra::solverFactory(copra::SolverFlag::LSSOL);\n            solver->SI_maxIter(200);\n        }\n#endif\n        pcCheck(s.first, s.second, std::move(solver));\n    }\n\n    MESSAGE(tools::getSortedTimers(sTimers));\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"MPC_TRAJECTORY_COST_WITH_INEQUALITY_CONSTRAINTS\")\n{\n    tools::SolverTimers sTimers;\n\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    auto xCost = std::make_shared<copra::TrajectoryCost>(M, xd);\n    auto uCost = std::make_shared<copra::ControlCost>(N, ud);\n    auto trajConstr = std::make_shared<copra::TrajectoryConstraint>(E, p);\n    auto contConstr = std::make_shared<copra::ControlConstraint>(G, h);\n    xCost->weights(wx);\n    uCost->weights(wu);\n\n    controller.addCost(xCost);\n    controller.addCost(uCost);\n    controller.addConstraint(trajConstr);\n    controller.addConstraint(contConstr);\n\n    auto pcCheck = [&](const std::string& solverName, copra::SolverFlag sFlag, std::unique_ptr<copra::SolverInterface>&& solver = nullptr) {\n        std::unique_ptr<copra::SolverInterface> newSolver;\n        if (solver) {\n            newSolver = std::move(solver);\n        } else {\n            newSolver = solverFactory(sFlag);\n        }\n#ifdef EIGEN_OSQP_FOUND\n        // Increase precision\n        if (sFlag == copra::SolverFlag::OSQP) {\n            auto& bs = static_cast<copra::OSQPSolver&>(*newSolver).baseSolver();\n            bs.scalingIter(0);\n            bs.absConvergenceTol(1e-6);\n            bs.relConvergenceTol(1e-6);\n            bs.primalInfeasibilityTol(1e-7);\n            bs.dualInfeasibilityTol(1e-7);\n        }\n#endif\n        controller.useSolver(std::move(newSolver));\n\n        REQUIRE(controller.solve());\n        sTimers.st.emplace_back(solverName, controller.solveTime() * 1e3);\n        sTimers.ct.emplace_back(solverName, controller.solveAndBuildTime() * 1e3);\n        sTimers.bt.emplace_back(solverName, (controller.solveAndBuildTime() - controller.solveTime()) * 1e3);\n\n        Eigen::VectorXd fullTraj = controller.trajectory();\n        auto trajLen = fullTraj.rows() / 2;\n        Eigen::VectorXd posTraj(trajLen);\n        Eigen::VectorXd velTraj(trajLen);\n        for (auto i = 0; i < trajLen; ++i) {\n            posTraj(i) = fullTraj(2 * i);\n            velTraj(i) = fullTraj(2 * i + 1);\n        }\n        Eigen::VectorXd control = controller.control();\n\n        // Check result\n        CHECK_LE(std::abs(xd(1) - velTraj.tail(1)(0)), 0.001);\n\n        // Check constrains\n        REQUIRE_LE(posTraj.maxCoeff(), x0(0));\n        REQUIRE_LE(velTraj.maxCoeff(), p(0) + 1e-6);\n        REQUIRE_LE(control.maxCoeff(), h(0) + 1e-6); // QuadProg allows to exceeds the constrain of a small amount.\n    };\n\n    for (auto s : tools::Solvers) {\n        std::unique_ptr<copra::SolverInterface> solver(nullptr);\n#ifdef EIGEN_LSSOL_FOUND\n        if (s.second == copra::SolverFlag::LSSOL) {\n            solver = copra::solverFactory(copra::SolverFlag::LSSOL);\n            solver->SI_maxIter(200);\n        }\n#endif\n        pcCheck(s.first, s.second, std::move(solver));\n    }\n\n    MESSAGE(tools::getSortedTimers(sTimers));\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"MPC_MIXED_COST_WITH_INEQUALITY_CONSTRAINTS\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    auto xCost = std::make_shared<copra::MixedCost>(M, Eigen::MatrixXd::Zero(2, 1), xd);\n    auto uCost = std::make_shared<copra::MixedCost>(Eigen::MatrixXd::Zero(1, 2), N, ud);\n    auto trajConstr = std::make_shared<copra::TrajectoryConstraint>(E, p);\n    auto contConstr = std::make_shared<copra::ControlConstraint>(G, h);\n    xCost->weights(wx);\n    uCost->weights(wu);\n\n    controller.addCost(xCost);\n    controller.addCost(uCost);\n    controller.addConstraint(trajConstr);\n    controller.addConstraint(contConstr);\n\n    REQUIRE(controller.solve());\n\n    Eigen::VectorXd fullTraj = controller.trajectory();\n    auto trajLen = fullTraj.rows() / 2;\n    Eigen::VectorXd posTraj(trajLen);\n    Eigen::VectorXd velTraj(trajLen);\n    for (auto i = 0; i < trajLen; ++i) {\n        posTraj(i) = fullTraj(2 * i);\n        velTraj(i) = fullTraj(2 * i + 1);\n    }\n    Eigen::VectorXd control = controller.control();\n\n    // Check result\n    CHECK_LE(std::abs(xd(1) - velTraj.tail(3)(0)), 0.001); // Check X_{N-1} for mixed cost because X_N is not evaluated.\n\n    // Check constrains\n    REQUIRE_LE(posTraj.maxCoeff(), x0(0));\n    REQUIRE_LE(velTraj.maxCoeff(), p(0) + 1e-6);\n    REQUIRE_LE(control.maxCoeff(), h(0) + 1e-6); // QuadProg allows to exceeds the constrain of a small amount.\n}\n\n/********************************************************************************************************\n *                               Check Mixed constraint                                                 *\n ********************************************************************************************************/\n\nTEST_CASE_FIXTURE(MixedSystem, \"MPC_TARGET_COST_WITH_MIXED_CONSTRAINTS\")\n{\n    tools::SolverTimers sTimers;\n\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    auto xCost = std::make_shared<copra::TargetCost>(M, xd);\n    auto uCost = std::make_shared<copra::ControlCost>(N, ud);\n    auto mixedConstr = std::make_shared<copra::MixedConstraint>(E, G, p);\n    xCost->weights(wx);\n    uCost->weights(wu);\n\n    controller.addCost(xCost);\n    controller.addCost(uCost);\n    controller.addConstraint(mixedConstr);\n\n    auto pcCheck = [&](const std::string& solverName, copra::SolverFlag sFlag, std::unique_ptr<copra::SolverInterface>&& solver = nullptr) {\n        if (solver) {\n            controller.useSolver(std::move(solver));\n        } else {\n            controller.selectQPSolver(sFlag);\n        }\n\n        REQUIRE(controller.solve());\n        sTimers.st.emplace_back(solverName, controller.solveTime() * 1e3);\n        sTimers.ct.emplace_back(solverName, controller.solveAndBuildTime() * 1e3);\n        sTimers.bt.emplace_back(solverName, (controller.solveAndBuildTime() - controller.solveTime()) * 1e3);\n\n        Eigen::VectorXd fullTraj = controller.trajectory();\n        auto trajLen = fullTraj.rows() / 2;\n        Eigen::VectorXd posTraj(trajLen);\n        Eigen::VectorXd velTraj(trajLen);\n        for (auto i = 0; i < trajLen; ++i) {\n            posTraj(i) = fullTraj(2 * i);\n            velTraj(i) = fullTraj(2 * i + 1);\n        }\n        Eigen::VectorXd control = controller.control();\n\n        // Check result\n        CHECK_LE(std::abs(xd(1) - velTraj.tail(1)(0)), 0.001);\n\n        // Check constrains\n        REQUIRE_LE(posTraj.maxCoeff(), x0(0));\n        for (int i = 0; i < nbStep; ++i) {\n            auto res = E * fullTraj.segment(i * E.cols(), E.cols()) + G * control.segment(i * G.cols(), G.cols());\n            if (!(res(0) <= p(0) + 1e-6)) {\n                FAIL(\"Mixed constraint violated!\");\n            }\n        }\n    };\n\n    for (auto s : tools::Solvers) {\n        std::unique_ptr<copra::SolverInterface> solver(nullptr);\n#ifdef EIGEN_LSSOL_FOUND\n        if (s.second == copra::SolverFlag::LSSOL) {\n            solver = copra::solverFactory(copra::SolverFlag::LSSOL);\n            solver->SI_maxIter(200);\n        }\n#endif\n        pcCheck(s.first, s.second, std::move(solver));\n    }\n\n    MESSAGE(tools::getSortedTimers(sTimers));\n}\n\nTEST_CASE_FIXTURE(MixedSystem, \"MPC_TRAJECTORY_COST_WITH_MIXED_CONSTRAINTS\")\n{\n    tools::SolverTimers sTimers;\n\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    auto xCost = std::make_shared<copra::TrajectoryCost>(M, xd);\n    auto uCost = std::make_shared<copra::ControlCost>(N, ud);\n    auto mixedConstr = std::make_shared<copra::MixedConstraint>(E, G, p);\n    xCost->weights(wx);\n    uCost->weights(wu);\n\n    controller.addCost(xCost);\n    controller.addCost(uCost);\n    controller.addConstraint(mixedConstr);\n\n    auto pcCheck = [&](const std::string& solverName, copra::SolverFlag sFlag, std::unique_ptr<copra::SolverInterface>&& solver = nullptr) {\n        if (solver) {\n            controller.useSolver(std::move(solver));\n        } else {\n            controller.selectQPSolver(sFlag);\n        }\n\n        REQUIRE(controller.solve());\n        sTimers.st.emplace_back(solverName, controller.solveTime() * 1e3);\n        sTimers.ct.emplace_back(solverName, controller.solveAndBuildTime() * 1e3);\n        sTimers.bt.emplace_back(solverName, (controller.solveAndBuildTime() - controller.solveTime()) * 1e3);\n\n        Eigen::VectorXd fullTraj = controller.trajectory();\n        auto trajLen = fullTraj.rows() / 2;\n        Eigen::VectorXd posTraj(trajLen);\n        Eigen::VectorXd velTraj(trajLen);\n        for (auto i = 0; i < trajLen; ++i) {\n            posTraj(i) = fullTraj(2 * i);\n            velTraj(i) = fullTraj(2 * i + 1);\n        }\n        Eigen::VectorXd control = controller.control();\n\n        // Check result\n        CHECK_LE(std::abs(xd(1) - velTraj.tail(1)(0)), 0.001);\n\n        // Check constrains\n        REQUIRE_LE(posTraj.maxCoeff(), x0(0));\n        for (int i = 0; i < nbStep; ++i) {\n            auto res = E * fullTraj.segment(i * E.cols(), E.cols()) + G * control.segment(i * G.cols(), G.cols());\n            if (!(res(0) <= p(0) + 1e-6)) {\n                FAIL(\"Mixed constraint violated!\");\n            }\n        }\n    };\n\n    for (auto s : tools::Solvers) {\n        std::unique_ptr<copra::SolverInterface> solver(nullptr);\n#ifdef EIGEN_LSSOL_FOUND\n        if (s.second == copra::SolverFlag::LSSOL) {\n            solver = copra::solverFactory(copra::SolverFlag::LSSOL);\n            solver->SI_maxIter(200);\n        }\n#endif\n        pcCheck(s.first, s.second, std::move(solver));\n    }\n\n    MESSAGE(tools::getSortedTimers(sTimers));\n}\n\nTEST_CASE_FIXTURE(MixedSystem, \"MPC_MIXED_COST_WITH_MIXED_CONSTRAINTS\")\n{\n    tools::SolverTimers sTimers;\n\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    auto xCost = std::make_shared<copra::MixedCost>(M, Eigen::MatrixXd::Zero(2, 1), xd);\n    auto uCost = std::make_shared<copra::MixedCost>(Eigen::MatrixXd::Zero(1, 2), N, ud);\n    auto mixedConstr = std::make_shared<copra::MixedConstraint>(E, G, p);\n    xCost->weights(wx);\n    uCost->weights(wu);\n\n    controller.addCost(xCost);\n    controller.addCost(uCost);\n    controller.addConstraint(mixedConstr);\n\n    REQUIRE(controller.solve());\n\n    Eigen::VectorXd fullTraj = controller.trajectory();\n    auto trajLen = fullTraj.rows() / 2;\n    Eigen::VectorXd posTraj(trajLen);\n    Eigen::VectorXd velTraj(trajLen);\n    for (auto i = 0; i < trajLen; ++i) {\n        posTraj(i) = fullTraj(2 * i);\n        velTraj(i) = fullTraj(2 * i + 1);\n    }\n    Eigen::VectorXd control = controller.control();\n\n    // Check result\n    CHECK_LE(std::abs(xd(1) - velTraj.tail(3)(0)), 0.001); // Check X_{N-1} for mixed cost because X_N is not evaluated.\n\n    // Check constrains\n    REQUIRE_LE(posTraj.maxCoeff(), x0(0));\n    for (int i = 0; i < nbStep; ++i) {\n        auto res = E * fullTraj.segment(i * E.cols(), E.cols()) + G * control.segment(i * G.cols(), G.cols());\n        if (!(res(0) <= p(0) + 1e-6)) {\n            FAIL(\"Mixed constraint violated!\");\n        }\n    }\n}\n\n/********************************************************************************************************\n *                              Check Equality constraint                                               *\n ********************************************************************************************************/\n\nTEST_CASE_FIXTURE(EqSystem, \"MPC_TARGET_COST_WITH_EQUALITY_CONSTRAINTS\")\n{\n    tools::SolverTimers sTimers;\n\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    auto xCost = std::make_shared<copra::TargetCost>(M, xd);\n    auto uCost = std::make_shared<copra::ControlCost>(N, ud);\n    auto trajConstr = std::make_shared<copra::TrajectoryConstraint>(E, p, false);\n    xCost->weights(wx);\n    uCost->weights(wu);\n\n    controller.addCost(xCost);\n    controller.addCost(uCost);\n    controller.addConstraint(trajConstr);\n\n    auto pcCheck = [&](const std::string& solverName, copra::SolverFlag sFlag, std::unique_ptr<copra::SolverInterface>&& solver = nullptr) {\n        std::unique_ptr<copra::SolverInterface> newSolver;\n        if (solver) {\n            newSolver = std::move(solver);\n        } else {\n            newSolver = solverFactory(sFlag);\n        }\n#ifdef EIGEN_OSQP_FOUND\n        // Increase precision\n        if (sFlag == copra::SolverFlag::OSQP) {\n            auto& bs = static_cast<copra::OSQPSolver&>(*newSolver).baseSolver();\n            bs.scalingIter(0);\n            bs.absConvergenceTol(1e-6);\n            bs.relConvergenceTol(1e-6);\n            bs.primalInfeasibilityTol(1e-7);\n            bs.dualInfeasibilityTol(1e-7);\n        }\n#endif\n        controller.useSolver(std::move(newSolver));\n\n        REQUIRE(controller.solve());\n        sTimers.st.emplace_back(solverName, controller.solveTime() * 1e3);\n        sTimers.ct.emplace_back(solverName, controller.solveAndBuildTime() * 1e3);\n        sTimers.bt.emplace_back(solverName, (controller.solveAndBuildTime() - controller.solveTime()) * 1e3);\n\n        Eigen::VectorXd fullTraj = controller.trajectory();\n        auto trajLen = fullTraj.rows() / 2;\n        Eigen::VectorXd posTraj(trajLen);\n        Eigen::VectorXd velTraj(trajLen);\n        for (auto i = 0; i < trajLen; ++i) {\n            posTraj(i) = fullTraj(2 * i);\n            velTraj(i) = fullTraj(2 * i + 1);\n        }\n        Eigen::VectorXd control = controller.control();\n\n        // Check result\n        CHECK_LE(std::abs(xd(1) - velTraj.tail(1)(0)), 0.001);\n\n        // Check constrains\n        REQUIRE_LE(posTraj.maxCoeff(), x0(0) + 1e-6);\n#ifdef EIGEN_OSQP_FOUND\n        if (sFlag == copra::SolverFlag::OSQP)\n            REQUIRE_LE(velTraj.maxCoeff(), p(0) + 1e-4); // I could not get a better precision...\n        else\n#endif\n            REQUIRE_LE(velTraj.maxCoeff(), p(0) + 1e-6);\n    };\n\n    for (auto s : tools::Solvers) {\n        std::unique_ptr<copra::SolverInterface> solver(nullptr);\n#ifdef EIGEN_LSSOL_FOUND\n        if (s.second == copra::SolverFlag::LSSOL) {\n            solver = copra::solverFactory(copra::SolverFlag::LSSOL);\n            solver->SI_maxIter(200);\n        }\n#endif\n        pcCheck(s.first, s.second, std::move(solver));\n    }\n\n    MESSAGE(tools::getSortedTimers(sTimers));\n}\n\nTEST_CASE_FIXTURE(EqSystem, \"MPC_TRAJECTORY_COST_WITH_EQUALITY_CONSTRAINTS\")\n{\n    tools::SolverTimers sTimers;\n\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    auto xCost = std::make_shared<copra::TrajectoryCost>(M, xd);\n    auto uCost = std::make_shared<copra::ControlCost>(N, ud);\n    auto trajConstr = std::make_shared<copra::TrajectoryConstraint>(E, p, false);\n    xCost->weights(wx);\n    uCost->weights(wu);\n\n    controller.addCost(xCost);\n    controller.addCost(uCost);\n    controller.addConstraint(trajConstr);\n\n    auto pcCheck = [&](const std::string& solverName, copra::SolverFlag sFlag, std::unique_ptr<copra::SolverInterface>&& solver = nullptr) {\n        if (solver) {\n            controller.useSolver(std::move(solver));\n        } else {\n            controller.selectQPSolver(sFlag);\n        }\n\n        REQUIRE(controller.solve());\n        sTimers.st.emplace_back(solverName, controller.solveTime() * 1e3);\n        sTimers.ct.emplace_back(solverName, controller.solveAndBuildTime() * 1e3);\n        sTimers.bt.emplace_back(solverName, (controller.solveAndBuildTime() - controller.solveTime()) * 1e3);\n\n        Eigen::VectorXd fullTraj = controller.trajectory();\n        auto trajLen = fullTraj.rows() / 2;\n        Eigen::VectorXd posTraj(trajLen);\n        Eigen::VectorXd velTraj(trajLen);\n        for (auto i = 0; i < trajLen; ++i) {\n            posTraj(i) = fullTraj(2 * i);\n            velTraj(i) = fullTraj(2 * i + 1);\n        }\n        Eigen::VectorXd control = controller.control();\n\n        // Check result\n        CHECK_LE(std::abs(xd(1) - velTraj.tail(1)(0)), 0.001);\n\n        // Check constrains\n        REQUIRE_LE(posTraj.maxCoeff(), x0(0) + 1e-6);\n#ifdef EIGEN_OSQP_FOUND\n        if (sFlag == copra::SolverFlag::OSQP)\n            REQUIRE_LE(velTraj.maxCoeff(), p(0) + 1e-4); // I could not get a better precision...\n        else\n#endif\n            REQUIRE_LE(velTraj.maxCoeff(), p(0) + 1e-6);\n    };\n\n    for (auto s : tools::Solvers) {\n        std::unique_ptr<copra::SolverInterface> solver(nullptr);\n#ifdef EIGEN_LSSOL_FOUND\n        if (s.second == copra::SolverFlag::LSSOL) {\n            solver = copra::solverFactory(copra::SolverFlag::LSSOL);\n            solver->SI_maxIter(200);\n        }\n#endif\n        pcCheck(s.first, s.second, std::move(solver));\n    }\n\n    MESSAGE(tools::getSortedTimers(sTimers));\n}\n\nTEST_CASE_FIXTURE(EqSystem, \"MPC_MIXED_COST_WITH_EQUALITY_CONSTRAINTS\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    auto xCost = std::make_shared<copra::MixedCost>(M, Eigen::MatrixXd::Zero(2, 1), xd);\n    auto uCost = std::make_shared<copra::MixedCost>(Eigen::MatrixXd::Zero(1, 2), N, ud);\n    auto trajConstr = std::make_shared<copra::TrajectoryConstraint>(E, p, false);\n    xCost->weights(wx);\n    uCost->weights(wu);\n\n    controller.addCost(xCost);\n    controller.addCost(uCost);\n    controller.addConstraint(trajConstr);\n\n    REQUIRE(controller.solve());\n\n    Eigen::VectorXd fullTraj = controller.trajectory();\n    auto trajLen = fullTraj.rows() / 2;\n    Eigen::VectorXd posTraj(trajLen);\n    Eigen::VectorXd velTraj(trajLen);\n    for (auto i = 0; i < trajLen; ++i) {\n        posTraj(i) = fullTraj(2 * i);\n        velTraj(i) = fullTraj(2 * i + 1);\n    }\n    Eigen::VectorXd control = controller.control();\n\n    // Check result\n    CHECK_LE(std::abs(xd(1) - velTraj.tail(3)(0)), 0.001); // Check X_{N-1} for mixed cost because X_N is not evaluated.\n\n    // Check constrains\n    REQUIRE_LE(posTraj.maxCoeff(), x0(0) + 1e-6);\n    REQUIRE_LE(velTraj.maxCoeff(), p(0) + 1e-6);\n}\n\n/********************************************************************************************************\n *                                   Check Autospan                                                     *\n ********************************************************************************************************/\n\nTEST_CASE_FIXTURE(BoundedSystem, \"CHECK_AUTOSPAN_AND_WHOLE_MATRIX_ON_BOUND_CONSTRAINT\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    int nbXStep = nbStep + 1;\n\n    auto checkSpan = [&](const Eigen::VectorXd& xLower, const Eigen::VectorXd& xUpper, const Eigen::VectorXd& uLower, const Eigen::VectorXd& uUpper) {\n        auto trajConstr = std::make_shared<copra::TrajectoryBoundConstraint>(xLower, xUpper);\n        trajConstr->autoSpan();\n\n        auto contConstr = std::make_shared<copra::ControlBoundConstraint>(uLower, uUpper);\n        contConstr->autoSpan();\n\n        REQUIRE_NOTHROW(controller.addConstraint(trajConstr));\n        REQUIRE_NOTHROW(controller.addConstraint(contConstr));\n    };\n\n    auto fullxLower = tools::spanVector(xLower, nbXStep);\n    auto fullxUpper = tools::spanVector(xUpper, nbXStep);\n    auto fulluLower = tools::spanVector(uLower, nbStep);\n    auto fulluUpper = tools::spanVector(uUpper, nbStep);\n\n    checkSpan(xLower, xUpper, uLower, uUpper);\n    checkSpan(fullxLower, xUpper, fulluLower, uUpper);\n    checkSpan(xLower, fullxUpper, uLower, fulluUpper);\n    checkSpan(fullxLower, fullxUpper, fulluLower, fulluUpper);\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"CHECK_AUTOSPAN_AND_WHOLE_MATRIX_ON_INEQUALITY_CONSTRAINT\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    int nbXStep = nbStep + 1;\n\n    auto checkSpan = [&](const Eigen::MatrixXd& E, const Eigen::VectorXd& p, const Eigen::MatrixXd& G, const Eigen::VectorXd& h) {\n        auto trajConstr = std::make_shared<copra::TrajectoryConstraint>(E, p);\n        trajConstr->autoSpan();\n\n        auto contConstr = std::make_shared<copra::ControlConstraint>(G, h);\n        contConstr->autoSpan();\n\n        REQUIRE_NOTHROW(controller.addConstraint(trajConstr));\n        REQUIRE_NOTHROW(controller.addConstraint(contConstr));\n    };\n\n    auto fullE = tools::spanMatrix(E, nbXStep);\n    auto fullf = tools::spanVector(p, nbXStep);\n    auto fullG = tools::spanMatrix(G, nbStep);\n    auto fullh = tools::spanVector(h, nbStep);\n\n    checkSpan(E, p, G, h);\n    checkSpan(fullE, p, fullG, h);\n    checkSpan(E, fullf, G, fullh);\n    checkSpan(fullE, fullf, fullG, fullh);\n}\n\nTEST_CASE_FIXTURE(MixedSystem, \"CHECK_AUTOSPAN_AND_WHOLE_MATRIX_ON_MIXED_CONSTRAINT\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n\n    auto checkSpan = [&](const Eigen::MatrixXd& E, const Eigen::MatrixXd& G, const Eigen::VectorXd& p) {\n        auto mixedConstr = std::make_shared<copra::MixedConstraint>(E, G, p);\n        mixedConstr->autoSpan();\n\n        REQUIRE_NOTHROW(controller.addConstraint(mixedConstr));\n    };\n\n    auto fullE = tools::spanMatrix(E, nbStep, 1);\n    auto fullG = tools::spanMatrix(G, nbStep);\n    auto fullf = tools::spanVector(p, nbStep);\n\n    checkSpan(E, G, p);\n    checkSpan(fullE, G, p);\n    checkSpan(fullE, fullG, p);\n    checkSpan(fullE, G, fullf);\n    checkSpan(E, fullG, p);\n    checkSpan(fullE, fullG, p);\n    checkSpan(E, fullG, fullf);\n    checkSpan(E, G, fullf);\n    checkSpan(fullE, G, fullf);\n    checkSpan(E, fullG, fullf);\n    checkSpan(fullE, fullG, fullf);\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"CHECK_AUTOSPAN_AND_WHOLE_MATRIX_ON_TRAJECTORY_COST\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    int nbXStep = nbStep + 1;\n\n    auto checkSpan = [&](const Eigen::MatrixXd& M, const Eigen::VectorXd& p, const Eigen::VectorXd& weights) {\n        auto cost = std::make_shared<copra::TrajectoryCost>(M, p);\n        cost->weights(weights);\n        cost->autoSpan();\n\n        REQUIRE_NOTHROW(controller.addCost(cost));\n    };\n\n    auto fullM = tools::spanMatrix(M, nbXStep);\n    auto fullxd = tools::spanVector(xd, nbXStep);\n\n    checkSpan(M, xd, wx);\n    checkSpan(M, fullxd, wx);\n    checkSpan(fullM, xd, wx);\n    checkSpan(fullM, fullxd, wx);\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"CHECK_AUTOSPAN_AND_WHOLE_MATRIX_ON_CONTROL_COST\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n\n    auto checkSpan = [&](const Eigen::MatrixXd& M, const Eigen::VectorXd& p, const Eigen::VectorXd& weights) {\n        auto cost = std::make_shared<copra::ControlCost>(M, p);\n        cost->weights(weights);\n        cost->autoSpan();\n\n        REQUIRE_NOTHROW(controller.addCost(cost));\n    };\n\n    auto fullN = tools::spanMatrix(N, nbStep);\n    auto fullud = tools::spanVector(ud, nbStep);\n\n    checkSpan(N, ud, wu);\n    checkSpan(N, fullud, wu);\n    checkSpan(fullN, ud, wu);\n    checkSpan(fullN, fullud, wu);\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"CHECK_AUTOSPAN_AND_WHOLE_MATRIX_ON_MIXED_COST\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n\n    auto checkSpan = [&](const Eigen::MatrixXd& M, const Eigen::MatrixXd& N, const Eigen::VectorXd& p, const Eigen::VectorXd& weights) {\n        auto cost = std::make_shared<copra::MixedCost>(M, N, p);\n        cost->weights(weights);\n        cost->autoSpan();\n\n        REQUIRE_NOTHROW(controller.addCost(cost));\n    };\n\n    auto MVec = std::vector<Eigen::MatrixXd>();\n    MVec.push_back(M);\n    MVec.push_back(tools::spanMatrix(M, nbStep, 1));\n    auto nnVec = std::vector<Eigen::MatrixXd>();\n    nnVec.push_back(Eigen::MatrixXd::Ones(2, 1));\n    nnVec.push_back(tools::spanMatrix(Eigen::MatrixXd::Ones(2, 1), nbStep));\n    auto xdVec = std::vector<Eigen::VectorXd>();\n    xdVec.push_back(xd);\n    xdVec.push_back(tools::spanVector(xd, nbStep));\n\n    for (auto& i : MVec) {\n        for (auto& j : nnVec) {\n            for (auto& k : xdVec) {\n                checkSpan(i, j, k, wx);\n            }\n        }\n    }\n}\n\n/********************************************************************************************************\n *                                Check Error Messages                                                  *\n ********************************************************************************************************/\n\nTEST_CASE_FIXTURE(IneqSystem, \"ERROR_HANDLER_FOR_PREVIEW_SYSTEM\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    REQUIRE_THROWS_AS(ps->system(Eigen::MatrixXd::Ones(5, 2), B, c, x0, nbStep), std::domain_error);\n    REQUIRE_THROWS_AS(ps->system(Eigen::MatrixXd::Ones(2, 5), B, c, x0, nbStep), std::domain_error);\n    REQUIRE_THROWS_AS(ps->system(A, Eigen::MatrixXd::Ones(5, 1), c, x0, nbStep), std::domain_error);\n    REQUIRE_THROWS_AS(ps->system(A, B, Eigen::VectorXd::Ones(5), x0, nbStep), std::domain_error);\n    REQUIRE_THROWS_AS(ps->system(A, B, c, x0, -1), std::domain_error);\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"ERROR_HANDLER_FOR_WEIGTHS\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n    auto cost = std::make_shared<copra::TrajectoryCost>(M, xd);\n\n    REQUIRE_NOTHROW(cost->weight(2));\n    REQUIRE_THROWS_AS(cost->weights(Eigen::VectorXd::Ones(5)), std::domain_error);\n    REQUIRE_NOTHROW(cost->weights(wx));\n    REQUIRE_NOTHROW(controller.addCost(cost));\n    REQUIRE_NOTHROW(cost->weights(Eigen::VectorXd::Ones(2)));\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"ERROR_HANDLER_FOR_TRAJECTORY_COST\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n\n    auto badCost1 = std::make_shared<copra::TrajectoryCost>(Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(2));\n    REQUIRE_THROWS_AS(controller.addCost(badCost1), std::domain_error);\n    auto badCost2 = std::make_shared<copra::TrajectoryCost>(Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(5));\n    REQUIRE_THROWS_AS(controller.addCost(badCost2), std::domain_error);\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"ERROR_HANDLER_FOR_TARGET_COST\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n\n    auto badCost1 = std::make_shared<copra::TargetCost>(Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(2));\n    REQUIRE_THROWS_AS(controller.addCost(badCost1), std::domain_error);\n    auto badCost2 = std::make_shared<copra::TargetCost>(Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(5));\n    REQUIRE_THROWS_AS(controller.addCost(badCost2), std::domain_error);\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"ERROR_HANDLER_FOR_CONTROL_COST\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n\n    auto badCost1 = std::make_shared<copra::ControlCost>(Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(2));\n    REQUIRE_THROWS_AS(controller.addCost(badCost1), std::domain_error);\n    auto badCost2 = std::make_shared<copra::ControlCost>(Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(5));\n    REQUIRE_THROWS_AS(controller.addCost(badCost2), std::domain_error);\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"ERROR_HANDLER_FOR_MIXED_COST\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n\n    auto badCost1 = std::make_shared<copra::MixedCost>(Eigen::MatrixXd::Identity(5, 5), Eigen::MatrixXd::Identity(2, 1), Eigen::VectorXd::Ones(2));\n    REQUIRE_THROWS_AS(controller.addCost(badCost1), std::domain_error);\n    auto badCost2 = std::make_shared<copra::MixedCost>(Eigen::MatrixXd::Identity(2, 1), Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(2));\n    REQUIRE_THROWS_AS(controller.addCost(badCost2), std::domain_error);\n    auto badCost3 = std::make_shared<copra::MixedCost>(Eigen::MatrixXd::Identity(5, 5), Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(5));\n    REQUIRE_THROWS_AS(controller.addCost(badCost3), std::domain_error);\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"ERROR_HANDLER_FOR_TRAJECTORY_CONSTRAINT\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n\n    auto badConstr = std::make_shared<copra::TrajectoryConstraint>(Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(2));\n    REQUIRE_THROWS_AS(controller.addConstraint(badConstr), std::domain_error);\n    auto trajConstr = std::make_shared<copra::TrajectoryConstraint>(Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(5));\n    REQUIRE_THROWS_AS(controller.addConstraint(trajConstr), std::domain_error);\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"ERROR_HANDLER_FOR_CONTROL_CONSTRAINT\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n\n    auto badConstr1 = std::make_shared<copra::ControlConstraint>(Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(2));\n    REQUIRE_THROWS_AS(controller.addConstraint(badConstr1), std::domain_error);\n    auto badConstr2 = std::make_shared<copra::ControlConstraint>(Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(5));\n    REQUIRE_THROWS_AS(controller.addConstraint(badConstr2), std::domain_error);\n\n    auto goodConstr = std::make_shared<copra::ControlConstraint>(G, h);\n    controller.addConstraint(goodConstr);\n    REQUIRE_THROWS_AS(controller.addConstraint(goodConstr), std::runtime_error);\n}\n\nTEST_CASE_FIXTURE(IneqSystem, \"ERROR_HANDLER_FOR_MIXED_CONSTRAINT\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n\n    auto badConstr1 = std::make_shared<copra::MixedConstraint>(Eigen::MatrixXd::Identity(5, 5), Eigen::MatrixXd::Identity(2, 1), Eigen::VectorXd::Ones(2));\n    REQUIRE_THROWS_AS(controller.addConstraint(badConstr1), std::domain_error);\n    auto badConstr2 = std::make_shared<copra::MixedConstraint>(Eigen::MatrixXd::Identity(2, 1), Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(2));\n    REQUIRE_THROWS_AS(controller.addConstraint(badConstr2), std::domain_error);\n    auto badConstr3 = std::make_shared<copra::MixedConstraint>(Eigen::MatrixXd::Identity(5, 5), Eigen::MatrixXd::Identity(5, 5), Eigen::VectorXd::Ones(5));\n    REQUIRE_THROWS_AS(controller.addConstraint(badConstr3), std::domain_error);\n}\n\nTEST_CASE_FIXTURE(BoundedSystem, \"ERROR_HANDLER_FOR_TRAJECTORY_BOUND_CONSTRAINT\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n\n    auto badConstr = std::make_shared<copra::TrajectoryBoundConstraint>(Eigen::VectorXd::Ones(3), Eigen::VectorXd::Ones(2));\n    REQUIRE_THROWS_AS(controller.addConstraint(badConstr), std::domain_error);\n    auto tbConstr = std::make_shared<copra::TrajectoryBoundConstraint>(Eigen::VectorXd::Ones(3), Eigen::VectorXd::Ones(3));\n    REQUIRE_THROWS_AS(controller.addConstraint(tbConstr), std::domain_error);\n}\n\nTEST_CASE_FIXTURE(BoundedSystem, \"ERROR_HANDLER_FOR_CONTROL_BOUND_CONSTRAINT\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>();\n    ps->system(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n\n    auto badConstr1 = std::make_shared<copra::ControlBoundConstraint>(Eigen::VectorXd::Ones(3), Eigen::VectorXd::Ones(2));\n    REQUIRE_THROWS_AS(controller.addConstraint(badConstr1), std::domain_error);\n    auto badConstr2 = std::make_shared<copra::ControlBoundConstraint>(Eigen::VectorXd::Ones(3), Eigen::VectorXd::Ones(3));\n    REQUIRE_THROWS_AS(controller.addConstraint(badConstr2), std::domain_error);\n\n    auto goodConstr = std::make_shared<copra::ControlBoundConstraint>(uLower, uUpper);\n    controller.addConstraint(goodConstr);\n    REQUIRE_THROWS_AS(controller.addConstraint(goodConstr), std::runtime_error);\n}\n\n/********************************************************************************************************\n *                               Check remove functions                                                 *\n ********************************************************************************************************/\n\nTEST_CASE_FIXTURE(IneqSystem, \"REMOVE_COST_AND_CONSTRAINT\")\n{\n    auto ps = std::make_shared<copra::PreviewSystem>(A, B, c, x0, nbStep);\n    auto controller = copra::LMPC(ps);\n\n    {\n        auto xCost = std::make_shared<copra::TargetCost>(M, xd);\n        auto uCost = std::make_shared<copra::ControlCost>(N, ud);\n        auto trajConstr = std::make_shared<copra::TrajectoryConstraint>(E, p);\n        auto contConstr = std::make_shared<copra::ControlConstraint>(G, h);\n\n        controller.addCost(xCost);\n        controller.addCost(uCost);\n        controller.addConstraint(trajConstr);\n        controller.addConstraint(contConstr);\n\n        controller.removeCost(xCost);\n        controller.removeCost(uCost);\n        controller.removeConstraint(trajConstr);\n        controller.removeConstraint(contConstr);\n    }\n\n    MESSAGE(\"\\nIn DEBUG mode, if a message appears between this line\\n*******\");\n    controller.solve();\n    MESSAGE(\"*******\\nand this line, the remove methods have failed!\");\n}\n", "meta": {"hexsha": "435a33579eed6bfc38843a81ea902f54eb34915a", "size": 44534, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestLMPC.cpp", "max_stars_repo_name": "ndehio/copra", "max_stars_repo_head_hexsha": "81ffa423b95d16140c64f19785ac1836af3ef9bf", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-12-31T07:51:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T16:24:51.000Z", "max_issues_repo_path": "tests/TestLMPC.cpp", "max_issues_repo_name": "vsamy/Copra", "max_issues_repo_head_hexsha": "2662c567491690f145834aa8b95339cec3a8bb11", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-21T15:06:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T07:17:57.000Z", "max_forks_repo_path": "tests/TestLMPC.cpp", "max_forks_repo_name": "vsamy/Copra", "max_forks_repo_head_hexsha": "2662c567491690f145834aa8b95339cec3a8bb11", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-03-09T14:21:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T07:35:01.000Z", "avg_line_length": 39.7980339589, "max_line_length": 155, "alphanum_fraction": 0.623793057, "num_tokens": 12214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629214, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5104367574596335}}
{"text": "#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <boost/range/algorithm.hpp>\n#include <boost/integer/common_factor_rt.hpp>\n\nusing namespace std;\n\nint N, M;\n\nint main() {\n\n    while (cin >> N >> M) {\n        int k[M];\n        vector<vector<int>> s_v;\n        for (int i = 0; i < M; i++) {\n            cin >> k[i];\n            int s[k[i]];\n            for (int j = 0; j < k[i]; j++) {\n                cin >> s[j];\n            }\n            s_v.push_back(vector<int> (s, s + k[i]));\n        }\n        int p[M];\n        for (int i = 0; i < M; i++) {\n            cin >> p[i];\n        }\n\n        int ret = 0;\n        for (int i = 0; i < (1 << N); i++) {\n            bool n[N];\n            for (int j = 0; j < N; j++) {\n                n[j] = i & (1 << j);               \n            }\n            int j;\n            for (j = 0; j < M; j++) {\n                int tmp = 0;\n                for (int l = 0; l < k[j]; l++) {\n                    if (n[s_v.at(j).at(l) - 1]) {\n                        tmp++;\n                    }\n                }\n                if (p[j] != tmp % 2) {\n                    break;\n                }\n            }\n            if (j == M) {\n                ret++;\n            }\n        }\n        cout << ret << endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "c0a0760cb8746332e568a7dd1ddf5ee63bbc16ea", "size": 1331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc128_c/Main.cpp", "max_stars_repo_name": "mizo0203/atcoder", "max_stars_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "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": "abc128_c/Main.cpp", "max_issues_repo_name": "mizo0203/atcoder", "max_issues_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "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": "abc128_c/Main.cpp", "max_forks_repo_name": "mizo0203/atcoder", "max_forks_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "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.5593220339, "max_line_length": 53, "alphanum_fraction": 0.3178061608, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5104204179544827}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#define NT2_UNIT_MODULE \"nt2 optimize toolbox - rosenbrock\"\n\n#include <iostream>\n#include <nt2/include/functions/rosenbrock.hpp>\n\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/bind.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/exp.hpp>\n#include <nt2/include/functions/norm.hpp>\n#include <nt2/include/functions/globalsum.hpp>\n#include <nt2/include/functions/globalasum2.hpp>\n#include <nt2/include/functions/sqrt.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/include/functions/globalsum.hpp>\n#include <nt2/include/functions/globalmax.hpp>\n#include <nt2/include/functions/ones.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/constants/sqrteps.hpp>\n#include <nt2/include/constants/four.hpp>\n#include <nt2/table.hpp>\n\ntemplate < class Tabout >\nstruct fpp\n{\n  template < class Tabin> inline\n  Tabout operator()(const Tabin & x ) const\n  {\n    typedef typename Tabin::value_type value_type;\n    Tabout r = globalsum(nt2::sqr((x-nt2::_(value_type(1), value_type(numel(x))))));\n    return r;\n  }\n};\ntemplate < class Tabout >\nstruct gpp\n{\n  template < class Tabin> inline\n  Tabout operator()(const Tabin & x ) const\n  {\n    typedef typename Tabin::value_type value_type;\n    Tabout r=Tabout(100)*nt2::sqr(x(2)-nt2::sqr(x(1)))+nt2::sqr(1-x(1));\n    return r;\n  }\n};\n\n// template<class Tabout, class Tabin >  Tabout f1(const Tabin & x )\n// {\n//     typedef typename Tabin::value_type value_type;\n//     Tabout r =  globalasum2(nt2::sqr(x)-value_type(3));\n//     return r;\n// }\n\n\n// NT2_TEST_CASE_TPL( rosenbrock_function_ptr, NT2_REAL_TYPES )\n// {\n//   using nt2::rosenbrock;\n//   using nt2::optimization::output;\n//   typedef nt2::table<T> tab_t;\n//   typedef typename nt2::meta::as_logical<T>::type lT;\n//   typedef nt2::table<T> ltab_t;\n//   tab_t x0 = nt2::ones(nt2::of_size(1, 3), nt2::meta::as_<T>());\n//   NT2_DISPLAY(x0);\n//   tab_t r = nt2::sqrt(T(3))*nt2::ones (nt2::of_size(1, 3), nt2::meta::as_<T>());\n//   NT2_DISPLAY(r);\n//   output<tab_t,T> res = rosenbrock(&f1<T, tab_t>, x0);\n\n//   std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n//             << \" after \" << res.iterations_count <<  \" iterations\\n\";\n\n//   NT2_TEST(res.successful);\n//   NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::abs(res.minimum()-r)), nt2::Sqrteps<T>());\n// }\n\n// NT2_TEST_CASE_TPL( rosenbrock_functor, NT2_REAL_TYPES )\n// {\n//   using nt2::rosenbrock;\n//   using nt2::options;\n//   using nt2::optimization::output;\n//   typedef nt2::table<T> tab_t;\n//   typedef typename nt2::meta::as_logical<T>::type lT;\n//   typedef nt2::table<T> ltab_t;\n//   tab_t x0 = nt2::zeros(nt2::of_size(1, 3), nt2::meta::as_<T>());\n//   tab_t r = nt2::_(T(1), T(3));\n//   output<tab_t,T> res = rosenbrock(fpp<tab_t>(), x0,\n//                                   options [ nt2::iterations_ = 100,\n//                                             nt2::tolerance::absolute_ = nt2::Eps<T>()\n//                                     ]);\n\n//   std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n//             << \" after \" << res.iterations_count <<  \" iterations\\n\";\n\n//   NT2_TEST(res.successful);\n//   NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::abs(res.minimum()-r)), nt2::Four<T>()*nt2::Sqrteps<T>());\n// }\n\nNT2_TEST_CASE_TPL( rosenbrock_functor2, NT2_REAL_TYPES )\n{\n  using nt2::rosenbrock;\n  using nt2::options;\n  using nt2::optimization::output;\n  typedef nt2::table<T> tab_t;\n  typedef typename nt2::meta::as_logical<T>::type lT;\n  typedef nt2::table<T> ltab_t;\n  tab_t x0 = T(5)*nt2::ones(nt2::of_size(1, 2), nt2::meta::as_<T>());\n  tab_t r = nt2::cons(nt2::of_size(1, 2), T(1),T(1));\n  output<tab_t,T> res = rosenbrock(gpp<tab_t>(), x0,\n                                  options [ nt2::iterations_ = 10000,\n                                            nt2::tolerance::absolute_ = T(100)*nt2::Eps<T>()\n                                    ]);\n\n  std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n            << \" after \" << res.iterations_count <<  \" iterations\\n\";\n\n  NT2_TEST(res.successful);\n}\n\nNT2_TEST_CASE_TPL( rosenbrock_functor3, (float) )\n{\n  using nt2::rosenbrock;\n  using nt2::options;\n  using nt2::optimization::output;\n  typedef nt2::table<T> tab_t;\n  tab_t x0 = T(5)*nt2::ones(nt2::of_size(1, 2), nt2::meta::as_<T>());\n  tab_t r = nt2::cons(nt2::of_size(1, 2), T(1),T(1));\n  output<tab_t,T> res = rosenbrock(gpp<tab_t>(), x0,\n                                  options [ nt2::iterations_ = 10000,\n                                            nt2::tolerance::absolute_ = 1.0e-5\n                                    ]);\n\n  std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n            << \" after \" << res.iterations_count <<  \" iterations\\n\";\n\n  NT2_TEST(res.successful);\n  typedef nt2::table<double> tab_d;\n  tab_d x0d = nt2::cast<double>(res.minimum);\n  output<tab_d,double> resd = rosenbrock(gpp<tab_d>(), x0d,\n                                  options [ nt2::iterations_ = 10000,\n                                            nt2::tolerance::absolute_ = 1.0e-8\n                                    ]);\n   std::cout << \"Minimum : f(\" << resd.minimum << \") = \" << resd.value\n            << \" after \" << resd.iterations_count <<  \" iterations\\n\";\n\n}\n", "meta": {"hexsha": "03e5e8a81b13a9fd911de91c92c0e5d99be6e848", "size": 5896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/optimization/unit/scalar/rosenbrock.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/core/optimization/unit/scalar/rosenbrock.cpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/core/optimization/unit/scalar/rosenbrock.cpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": 37.7948717949, "max_line_length": 104, "alphanum_fraction": 0.5775101764, "num_tokens": 1736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5104204179544826}}
{"text": "/*\n Copyright (C) 2017 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/*! \\file fxvolsmile.cpp\n    \\brief fx vol smile\n*/\n\n#include \"toplevelfixture.hpp\"\n#include <boost/make_shared.hpp>\n#include <boost/test/unit_test.hpp>\n#include <ql/math/matrix.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvariancesurface.hpp>\n#include <ql/termstructures/yield/discountcurve.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/utilities/dataparsers.hpp>\n#include <qle/termstructures/blackinvertedvoltermstructure.hpp>\n#include <qle/termstructures/fxblackvolsurface.hpp>\n#include <qle/termstructures/fxvannavolgasmilesection.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace boost::unit_test_framework;\nusing namespace std;\n\nnamespace {\n\nstruct CommonVars {\n\n    /* ------ GLOBAL VARIABLES ------ */\n    Date today;\n    DayCounter dc;\n    vector<Date> dates;\n    vector<Real> strikes;\n    Matrix vols;\n    vector<Real> atmVols;\n\n    vector<Volatility> rrs;\n    vector<Volatility> bfs;\n\n    Handle<Quote> baseSpot;\n    Handle<YieldTermStructure> baseDomesticYield;\n    Handle<YieldTermStructure> baseForeignYield;\n\n    CommonVars() {\n\n        today = Date(1, Jan, 2014);\n        dc = ActualActual();\n\n        Settings::instance().evaluationDate() = today;\n\n        dates.push_back(Date(1, Feb, 2014));\n        dates.push_back(Date(1, Mar, 2014));\n        dates.push_back(Date(1, Apr, 2014));\n        dates.push_back(Date(1, Jan, 2015));\n\n        strikes.push_back(90);\n        strikes.push_back(100);\n        strikes.push_back(110);\n\n        vols = Matrix(3, 4);\n        vols[0][0] = 0.12;\n        vols[1][0] = 0.10;\n        vols[2][0] = 0.13;\n        vols[0][1] = 0.22;\n        vols[1][1] = 0.20;\n        vols[2][1] = 0.23;\n        vols[0][2] = 0.32;\n        vols[1][2] = 0.30;\n        vols[2][2] = 0.33;\n        vols[0][3] = 0.42;\n        vols[1][3] = 0.40;\n        vols[2][3] = 0.43;\n\n        atmVols.push_back(0.1);\n        atmVols.push_back(0.2);\n        atmVols.push_back(0.3);\n        atmVols.push_back(0.4);\n\n        rrs = vector<Volatility>(atmVols.size(), 0.01);\n        bfs = vector<Volatility>(atmVols.size(), 0.001);\n\n        baseSpot = Handle<Quote>(boost::shared_ptr<Quote>(new SimpleQuote(100)));\n\n        baseDomesticYield = Handle<YieldTermStructure>(\n            boost::make_shared<FlatForward>(today, Handle<Quote>(boost::make_shared<SimpleQuote>(0.03)), dc));\n        baseForeignYield = Handle<YieldTermStructure>(\n            boost::make_shared<FlatForward>(today, Handle<Quote>(boost::make_shared<SimpleQuote>(0.01)), dc));\n    }\n};\n\nstruct VolData {\n    const char* tenor;\n    Volatility atm;\n    Volatility rr;\n    Volatility bf;\n    Time time;\n    Real df_d;\n    Real df_f;\n};\n\n} // namespace\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(FxVolSmileTest)\n\nBOOST_AUTO_TEST_CASE(testVannaVolgaFxSmileSection) {\n\n    BOOST_TEST_MESSAGE(\"Testing fx vanna volga smile\");\n\n    SavedSettings backup;\n\n    // test numbers from Castagna & Mercurio (2006)\n    // http://papers.ssrn.com/sol3/papers.cfm?abstract_id=873788\n    // page 5\n    Settings::instance().evaluationDate() = Date(1, July, 2005);\n    Time t = 94 / (double)365;\n    Real S0 = 1.205;\n    Volatility sig_atm = 0.0905;\n    Volatility sig_rr = -0.005;\n    Volatility sig_bf = 0.0013;\n    // page 11\n    DiscountFactor df_usd = 0.9902752;\n    DiscountFactor df_eur = 0.9945049;\n\n    // Rates\n    Real rd = -::log(df_usd) / t;\n    Real rf = -::log(df_eur) / t;\n\n    VannaVolgaSmileSection vvss(S0, rd, rf, t, sig_atm, sig_rr, sig_bf);\n\n    // Check the Strike and Vol values from the paper\n    Real tolerance = 0.0001; // 4 decimal places\n    if (fabs(vvss.k_atm() - 1.2114) > tolerance)\n        BOOST_FAIL(\"VannaVolgaSmileSection failed to calculte ATM strike, got \" << vvss.k_atm());\n    if (fabs(vvss.k_25p() - 1.1733) > tolerance)\n        BOOST_FAIL(\"VannaVolgaSmileSection failed to calculate 25P strike, got \" << vvss.k_25p());\n    if (fabs(vvss.k_25c() - 1.2487) > tolerance)\n        BOOST_FAIL(\"VannaVolgaSmileSection failed to calculate 25C strike, got \" << vvss.k_25c());\n    if (fabs(vvss.vol_atm() - 0.0905) > tolerance)\n        BOOST_FAIL(\"VannaVolgaSmileSection failed to calculate ATM vol, got \" << vvss.vol_atm());\n    if (fabs(vvss.vol_25p() - 0.0943) > tolerance)\n        BOOST_FAIL(\"VannaVolgaSmileSection failed to calculate 25P vol, got \" << vvss.vol_25p());\n    if (fabs(vvss.vol_25c() - 0.0893) > tolerance)\n        BOOST_FAIL(\"VannaVolgaSmileSection failed to calculate 25C vol, got \" << vvss.vol_25c());\n\n    // Now check that our smile returns these\n    if (fabs(vvss.volatility(vvss.k_atm()) - vvss.vol_atm()) > tolerance)\n        BOOST_FAIL(\"VannaVolgaSmileSection failed to recover ATM vol, got \" << vvss.volatility(vvss.k_atm()));\n    if (fabs(vvss.volatility(vvss.k_25p()) - vvss.vol_25p()) > tolerance)\n        BOOST_FAIL(\"VannaVolgaSmileSection failed to recover 25P vol, got \" << vvss.volatility(vvss.k_25p()));\n    if (fabs(vvss.volatility(vvss.k_25c()) - vvss.vol_25c()) > tolerance)\n        BOOST_FAIL(\"VannaVolgaSmileSection failed to recover 25C vol, got \" << vvss.volatility(vvss.k_25c()));\n\n    // To graph the smile, uncomment this code\n    /*\n    cout << \"strike,vol\" << endl;\n    //for (Real k = 1.1; k < 1.35; k += 0.002) // normal (as per paper)\n    //for (Real k = 0.9; k < 1.5; k += 0.01) // large\n    for (Real k = 0.1; k < 3; k += 0.05) // extreme\n        cout << k << \",\" << vvss.volatility(k) << endl;\n    */\n}\n\nBOOST_AUTO_TEST_CASE(testVannaVolgaFxVolSurface) {\n\n    BOOST_TEST_MESSAGE(\"Testing fx vanna volga surface\");\n\n    SavedSettings backup;\n\n    // Data from\n    // \"Consistent pricing and hedging of an FX options book\" (2005)\n    // L. Bisesti, A. Castagna and F. Mercurio\n    // http://www.fabiomercurio.it/fxbook.pdf\n    Date asof(12, Feb, 2004);\n    Settings::instance().evaluationDate() = asof;\n\n    Handle<Quote> fxSpot(boost::shared_ptr<Quote>(new SimpleQuote(1.2832)));\n\n    // vols are % here\n    // tenor, atm, rr, bf, T, p_d, p_f\n    VolData volData[] = { { \"1W\", 11.75, 0.50, 0.190, 0.0192, 0.999804, 0.999606 },\n                          { \"2W\", 11.60, 0.50, 0.190, 0.0384, 0.999595, 0.999208 },\n                          { \"1M\", 11.50, 0.60, 0.190, 0.0877, 0.999044, 0.998179 },\n                          { \"2M\", 11.25, 0.60, 0.210, 0.1726, 0.998083, 0.996404 },\n                          { \"3M\", 11.00, 0.60, 0.220, 0.2493, 0.997187, 0.994803 },\n                          { \"6M\", 10.87, 0.65, 0.235, 0.5014, 0.993959, 0.989548 },\n                          { \"9M\", 10.83, 0.69, 0.235, 0.7589, 0.990101, 0.984040 },\n                          { \"1Y\", 10.80, 0.70, 0.240, 1.0110, 0.985469, 0.978479 },\n                          { \"2Y\", 10.70, 0.65, 0.255, 2.0110, 0.960102, 0.951092 } };\n\n    // Assume act/act\n    DayCounter dc = ActualActual();\n    Calendar cal = TARGET();\n\n    // set up vectors\n    Size len = sizeof(volData) / sizeof(volData[0]);\n    vector<Date> dates(len);\n    vector<Volatility> atm(len);\n    vector<Volatility> rr(len);\n    vector<Volatility> bf(len);\n    // For DiscountCurve we need the T=0 points.\n    vector<Date> discountDates(len + 1);\n    vector<DiscountFactor> dfDom(len + 1);\n    vector<DiscountFactor> dfFor(len + 1);\n    discountDates[0] = asof;\n    dfDom[0] = 1.0;\n    dfFor[0] = 1.0;\n\n    for (Size i = 0; i < sizeof(volData) / sizeof(volData[0]); i++) {\n        dates[i] = asof + PeriodParser::parse(volData[i].tenor);\n        // check time == volData[i].time\n        /*\n        if (fabs(dc.yearFraction(asof, dates[i]) - volData[i].time) > 0.001)\n            BOOST_FAIL(\"Did not match vol data time (\" << volData[i].time <<\n                       \") with aosf \" << asof << \" and maturity \" << dates[i] <<\n                       \" got year fraction of \" << dc.yearFraction(asof, dates[i]));\n         */\n\n        atm[i] = volData[i].atm / 100;\n        rr[i] = volData[i].rr / 100;\n        bf[i] = volData[i].bf / 100;\n\n        discountDates[i + 1] = dates[i];\n        dfDom[i + 1] = volData[i].df_d;\n        dfFor[i + 1] = volData[i].df_f;\n    }\n\n    // Now build discount curves\n    Handle<YieldTermStructure> domYTS(\n        boost::shared_ptr<YieldTermStructure>(new DiscountCurve(discountDates, dfDom, dc)));\n    Handle<YieldTermStructure> forYTS(\n        boost::shared_ptr<YieldTermStructure>(new DiscountCurve(discountDates, dfFor, dc)));\n\n    // build surface\n    FxBlackVannaVolgaVolatilitySurface volSurface(asof, dates, atm, rr, bf, dc, cal, fxSpot, domYTS, forYTS);\n\n    // 1.55,1.75,0.121507\n    Real vol = volSurface.blackVol(1.75, 1.55);\n    Real expected = 0.121507;\n    if (fabs(vol - expected) > 0.00001)\n        BOOST_FAIL(\"Failed to get expected vol from surface\");\n    /*\n    cout << \"strike,time,vol\" << endl;\n    for (Real k = 1.0; k < 1.6; k += 0.01) // extreme\n        for (Time tt = 0.1; tt < 2; tt+= 0.05)\n            cout << k << \",\" << tt << \",\" << volSurface.blackVol(tt, k) << endl;\n     */\n}\n\nBOOST_AUTO_TEST_CASE(testInvertedVolTermStructure) {\n\n    BOOST_TEST_MESSAGE(\"Testing inverted vol term structure\");\n\n    SavedSettings backup;\n\n    CommonVars vars;\n\n    Handle<BlackVolTermStructure> surface(boost::shared_ptr<BlackVolTermStructure>(\n        new BlackVarianceSurface(vars.today, TARGET(), vars.dates, vars.strikes, vars.vols, vars.dc)));\n\n    BlackInvertedVolTermStructure bivt(surface);\n\n    if (surface->maxDate() != bivt.maxDate())\n        BOOST_FAIL(\"inverted maxDate() vol surface does not match base\");\n\n    if (surface->referenceDate() != bivt.referenceDate())\n        BOOST_FAIL(\"inverted referenceDate() vol surface does not match base\");\n\n    // base spot is 100\n    // test cases <Time, Strike>\n    double testCases[][2] = { { 0.1, 104 }, { 0.5, 90 },  { 0.6, 110 }, { 0.9, 90 },\n                              { 0.9, 95 },  { 0.9, 100 }, { 0.9, 105 }, { 0.9, 110 } };\n\n    for (Size i = 0; i < sizeof(testCases) / sizeof(testCases[0]); i++) {\n        Time t = testCases[i][0];\n        Real k = testCases[i][1];\n\n        Real vol1 = surface->blackVol(t, k);\n\n        Real invertedStrike = 1.0 / k;\n        Real vol2 = bivt.blackVol(t, invertedStrike);\n        if (fabs(vol1 - vol2) > 0.00001)\n            BOOST_FAIL(\"Failed to get expected vol (\" << vol1 << \") from inverted vol surface, got (\" << vol2 << \")\");\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0245a270833199bfc2d0c145cb6c851a0107fa3b", "size": 11212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/fxvolsmile.cpp", "max_stars_repo_name": "PiotrSiejda/Engine", "max_stars_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "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": "QuantExt/test/fxvolsmile.cpp", "max_issues_repo_name": "PiotrSiejda/Engine", "max_issues_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/test/fxvolsmile.cpp", "max_forks_repo_name": "PiotrSiejda/Engine", "max_forks_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T02:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T02:04:10.000Z", "avg_line_length": 36.284789644, "max_line_length": 118, "alphanum_fraction": 0.6216553692, "num_tokens": 3512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311757235431, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5104204115026223}}
{"text": "/*\n * Filename: damm.cpp\n *\n * Copyright 2020 Tecnalia\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 <manipulability_metrics/metrics/damm.h>\n#include <manipulability_metrics/util/ellipsoid.h>\n#include <manipulability_metrics/util/similarity.h>\n\n#include <Eigen/SVD>\n\n#include <numeric>\n\nnamespace manipulability_metrics\n{\ndouble damm(const DualChain& dual_chain, const DualTcp& tcp, const KDL::JntArray& left_joint_positions,\n            const KDL::JntArray& right_joint_positions)\n{\n  auto left_jac = KDL::Jacobian{ static_cast<unsigned int>(dual_chain.leftChain().n_joints) };\n  dual_chain.leftChain().jacobian(left_joint_positions, tcp.leftTcp().p, left_jac);\n  auto right_jac = KDL::Jacobian{ static_cast<unsigned int>(dual_chain.rightChain().n_joints) };\n  dual_chain.rightChain().jacobian(right_joint_positions, tcp.rightTcp().p, right_jac);\n\n  auto left_ellipsoid = ellipsoidFromJacobian(left_jac.data);\n  auto right_ellipsoid = ellipsoidFromJacobian(right_jac.data);\n\n  return std::max(volumeIntersection(left_ellipsoid, right_jac.data),\n                  volumeIntersection(right_ellipsoid, left_jac.data));\n}\n}  // namespace manipulability_metrics\n", "meta": {"hexsha": "0e47380f6d2bdaf64816e4ba2fe2e0c22ccf3073", "size": 1684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "manipulability_metrics/src/damm.cpp", "max_stars_repo_name": "tecnalia-medical-robotics/manipulability_metrics", "max_stars_repo_head_hexsha": "0e1360376a49fdc623e761fc8ca769e99fa11ac9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-02-15T16:15:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T03:01:22.000Z", "max_issues_repo_path": "manipulability_metrics/src/damm.cpp", "max_issues_repo_name": "iLoveVenki/manipulability_metrics", "max_issues_repo_head_hexsha": "0e1360376a49fdc623e761fc8ca769e99fa11ac9", "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": "manipulability_metrics/src/damm.cpp", "max_forks_repo_name": "iLoveVenki/manipulability_metrics", "max_forks_repo_head_hexsha": "0e1360376a49fdc623e761fc8ca769e99fa11ac9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-04-06T08:18:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T12:43:57.000Z", "avg_line_length": 38.2727272727, "max_line_length": 103, "alphanum_fraction": 0.7606888361, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5104190480491405}}
{"text": "//==================================================================================================\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_ARCH_COMMON_SIMD_FUNCTION_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_RSQRT_HPP_INCLUDED\n\n#include <boost/simd/function/raw.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/sqrt.hpp>\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/detail/traits.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD_IF( rsqrt_\n                            , (typename A0, typename X)\n                            , (detail::is_native<X>)\n                            , bd::cpu_\n                            , bs::pack_< bd::floating_<A0>, X >\n                            )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      return bs::rec(bs::sqrt(a0));\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF( rsqrt_\n                            , (typename A0, typename X)\n                            , (detail::is_native<X>)\n                            , bd::cpu_\n                            , boost::simd::raw_tag\n                            , bs::pack_< bd::floating_<A0>, X >\n                            )\n  {\n    BOOST_FORCEINLINE A0 operator() (const raw_tag &,  A0 const& a0) const BOOST_NOEXCEPT\n    {\n      return bs::rec(bs::raw_(bs::sqrt)(a0));\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "e7bc2f2df98c0870ff3a6028d3f3b7b58569cc99", "size": 1740, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/rsqrt.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/arch/common/simd/function/rsqrt.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/arch/common/simd/function/rsqrt.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": 33.4615384615, "max_line_length": 100, "alphanum_fraction": 0.4994252874, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789269812079, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5104190480491404}}
{"text": "/** lexical_cast_nonfinite_facets.cpp\n*\n* Copyright (c) 2011 Paul A. Bristow\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* This very simple program illustrates how to use the\n* `boost/math/nonfinite_num_facets.hpp' with lexical cast\n* to obtain C99 representation of infinity and NaN.\n* This example is from the original Floating Point  Utilities contribution by Johan Rade.\n* Floating Point Utility library has been accepted into Boost,\n* but the utilities are incorporated into Boost.Math library.\n*\n\\file\n\n\\brief A very simple example of using lexical cast with\nnon_finite_num facet for C99 standard output of infinity and NaN.\n\n\\detail This example shows how to create a C99 non-finite locale,\nand imbue input and output streams with the non_finite_num put and get facets.\nThis allows lexical_cast output and input of infinity and NaN in a Standard portable way,\nThis permits 'loop-back' of output back into input (and portably across different system too).\n\nSee also lexical_cast_native.cpp which is expected to fail on many systems,\nbut might succeed if the default locale num_put and num_get facets\ncomply with C99 nonfinite input and output specification.\n\n*/\n\n#include <boost/math/special_functions/nonfinite_num_facets.hpp>\nusing boost::math::nonfinite_num_get;\nusing boost::math::nonfinite_num_put;\n\n#include <boost/lexical_cast.hpp>\nusing boost::lexical_cast;\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\nusing std::cerr;\n\n#include <iomanip>\nusing std::setw;\nusing std::left;\nusing std::right;\nusing std::internal;\n\n#include <string>\nusing std::string;\n\n#include <sstream>\nusing std::istringstream;\n\n#include <limits>\nusing std::numeric_limits;\n\n#include <locale>\nusing std::locale;\n\n#include <boost/assert.hpp>\n\nint main ()\n{\n  std::cout << \"finite_num_facet with lexical_cast example.\" << std::endl;\n\n  // Example of using non_finite num_put and num_get facets with lexical_cast.\n  //locale old_locale;\n  //locale tmp_locale(old_locale, new nonfinite_num_put<char>);\n  //// Create a new temporary output locale, and add the output nonfinite_num_put facet.\n\n  //locale new_locale(tmp_locale, new nonfinite_num_get<char>);\n  // Create a new output locale (from the tmp locale), and add the input nonfinite_num_get facet.\n\n  // Note that you can only add facets one at a time,\n  // unless you chain thus:\n\n  std::locale new_locale(std::locale(std::locale(),\n    new boost::math::nonfinite_num_put<char>),\n    new boost::math::nonfinite_num_get<char>);\n\n  locale::global(new_locale); // Newly constructed streams\n  // (including those streams inside lexical_cast)\n  // now use new_locale with nonfinite facets.\n\n  // Output using the new locale.\n  cout << \"Using C99_out_locale \" << endl;\n  cout.imbue(new_locale);\n  // Necessary because cout already constructed using default C locale,\n  // and default facets for nonfinites.\n\n    // Create plus and minus infinity.\n  double plus_infinity = +std::numeric_limits<double>::infinity();\n  double minus_infinity = -std::numeric_limits<double>::infinity();\n\n  // and create a NaN (NotANumber)\n  double NaN = +std::numeric_limits<double>::quiet_NaN ();\n  cout << \"+std::numeric_limits<double>::infinity() = \" << plus_infinity << endl;\n  cout << \"-std::numeric_limits<double>::infinity() = \" << minus_infinity << endl;\n  cout << \"+std::numeric_limits<double>::quiet_NaN () = \" << NaN << endl;\n\n  // Now try some 'round-tripping', 'reading' \"inf\".\n  double x = boost::lexical_cast<double>(\"inf\");\n  // and check we get a floating-point infinity.\n  BOOST_ASSERT(x == std::numeric_limits<double>::infinity());\n  cout << \"boost::lexical_cast<double>(\\\"inf\\\") = \" << x << endl;\n\n  // Check we can convert the other way from floating-point infinity,\n  string s = boost::lexical_cast<string>(numeric_limits<double>::infinity());\n  // to a C99 string representation as \"inf\".\n  BOOST_ASSERT(s == \"inf\");\n\n  // Finally try full 'round-tripping' (in both directions):\n  BOOST_ASSERT(lexical_cast<double>(lexical_cast<string>(numeric_limits<double>::infinity()))\n    == numeric_limits<double>::infinity());\n  BOOST_ASSERT(lexical_cast<string>(lexical_cast<double>(\"inf\")) == \"inf\");\n\n    return 0;\n} // int main()\n\n/*\n\nOutput:\n  finite_num_facet with lexical_cast example.\n  Using C99_out_locale\n  +std::numeric_limits<double>::infinity() = inf\n  -std::numeric_limits<double>::infinity() = -inf\n  +std::numeric_limits<double>::quiet_NaN () = nan\n  boost::lexical_cast<double>(\"inf\") = inf\n\n\n*/\n", "meta": {"hexsha": "2874db1c7d355987124e0bce7570e2b21f9f0792", "size": 4559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/lexical_cast_nonfinite_facets.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/lexical_cast_nonfinite_facets.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/lexical_cast_nonfinite_facets.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": 34.0223880597, "max_line_length": 97, "alphanum_fraction": 0.7348102654, "num_tokens": 1080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.5104190463394381}}
{"text": "/**\n * @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>\n * @date Sat Jun 4 21:38:59 2011 +0200\n *\n * @brief Implements a multi-class Fisher/LDA linear machine Training using\n * Singular Value Decomposition (SVD). For more information on Linear Machines\n * and associated methods, please consult Bishop, Machine Learning and Pattern\n * Recognition chapter 4.\n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <boost/format.hpp>\n#include <bob.math/pinv.h>\n#include <bob.math/eig.h>\n#include <bob.math/linear.h>\n#include <bob.math/stats.h>\n\n#include <bob.learn.linear/lda.h>\n\nnamespace bob { namespace learn { namespace linear {\n\n  FisherLDATrainer::FisherLDATrainer\n    (bool use_pinv, bool strip_to_rank)\n    : m_use_pinv(use_pinv),\n      m_strip_to_rank(strip_to_rank)\n  {\n  }\n\n  FisherLDATrainer::FisherLDATrainer\n    (const FisherLDATrainer& other)\n    : m_use_pinv(other.m_use_pinv),\n      m_strip_to_rank(other.m_strip_to_rank)\n  {\n  }\n\n  FisherLDATrainer::~FisherLDATrainer()\n  {\n  }\n\n  FisherLDATrainer& FisherLDATrainer::operator=\n    (const FisherLDATrainer& other)\n    {\n      if (this != &other) // avoid auto assignment\n      {\n        m_use_pinv = other.m_use_pinv;\n        m_strip_to_rank = other.m_strip_to_rank;\n      }\n      return *this;\n    }\n\n  bool FisherLDATrainer::operator==\n    (const FisherLDATrainer& other) const\n    {\n      return m_use_pinv == other.m_use_pinv && \\\n                         m_strip_to_rank == other.m_strip_to_rank;\n    }\n\n  bool FisherLDATrainer::operator!=\n    (const FisherLDATrainer& other) const\n    {\n      return !(this->operator==(other));\n    }\n\n  /**\n   * Returns the indexes for sorting a given blitz::Array<double,1>\n   */\n  struct compare_1d_blitz {\n    const blitz::Array<double,1>& v_;\n    compare_1d_blitz(const blitz::Array<double,1>& v): v_(v) { }\n    bool operator() (size_t i, size_t j) { return v_(i) < v_(j); }\n  };\n\n  static std::vector<size_t> sort_indexes(const blitz::Array<double,1>& v) {\n\n    // initialize original index locations\n    std::vector<size_t> idx(v.size());\n    for (size_t i = 0; i != idx.size(); ++i) idx[i] = i;\n\n    // sort indexes based on comparing values in v\n    std::sort(idx.begin(), idx.end(), compare_1d_blitz(v));\n\n    return idx;\n  }\n\n  void FisherLDATrainer::train\n    (Machine& machine, blitz::Array<double,1>& eigen_values,\n     const std::vector<blitz::Array<double, 2> >& data) const\n    {\n      // if #classes < 2, then throw\n      if (data.size() < 2) {\n        boost::format m(\"The number of arrays in the input data == %d whereas for LDA you should provide at least 2\");\n        m % data.size();\n        throw std::runtime_error(m.str());\n      }\n\n      // checks for arrayset data type and shape once\n      int n_features = data[0].extent(1);\n\n      for (size_t cl=0; cl<data.size(); ++cl) {\n        if (data[cl].extent(1) != n_features) {\n          boost::format m(\"The number of features/columns (%d) in array at position %d of your input differs from that of array at position 0 (%d)\");\n          m % data[cl].extent(1) % n_features;\n          throw std::runtime_error(m.str());\n        }\n      }\n\n      int osize = output_size(data);\n\n      // Checks that the dimensions are matching\n      if (machine.inputSize() != (size_t)data[0].extent(1)) {\n        boost::format m(\"Number of features at input data set (%d columns) does not match machine input size (%d)\");\n        m % data[0].extent(1) % machine.inputSize();\n        throw std::runtime_error(m.str());\n      }\n      if (machine.outputSize() != (size_t)osize) {\n        boost::format m(\"Number of outputs of the given machine (%d) does not match the expected number of outputs calculated by this trainer = %d\");\n        m % machine.outputSize() % osize;\n        throw std::runtime_error(m.str());\n      }\n      if (eigen_values.extent(0) != osize) {\n        boost::format m(\"Number of eigenvalues on the given 1D array (%d) does not match the expected number of outputs calculated by this trainer = %d\");\n        m % eigen_values.extent(0) % osize;\n        throw std::runtime_error(m.str());\n      }\n\n      blitz::Array<double,1> preMean(n_features);\n      blitz::Array<double,2> Sw(n_features, n_features);\n      blitz::Array<double,2> Sb(n_features, n_features);\n      bob::math::scatters_(data, Sw, Sb, preMean);\n\n      // computes the generalized eigenvalue decomposition\n      // so to find the eigen vectors/values of Sw^(-1) * Sb\n      blitz::Array<double,2> V(Sw.shape());\n      blitz::Array<double,1> eigen_values_(n_features);\n\n      if (m_use_pinv) {\n\n        //note: misuse V and Sw as temporary place holders for data\n        bob::math::pinv_(Sw, V); //V now contains Sw^-1\n        bob::math::prod_(V, Sb, Sw); //Sw now contains Sw^-1*Sb\n        blitz::Array<std::complex<double>,1> Dtemp(eigen_values_.shape());\n        blitz::Array<std::complex<double>,2> Vtemp(V.shape());\n        bob::math::eig_(Sw, Vtemp, Dtemp); //V now contains eigen-vectors\n\n        //sorting: we know this problem on has real eigen-values\n        blitz::Range a = blitz::Range::all();\n        blitz::Array<double,1> Dunordered(blitz::real(Dtemp));\n        std::vector<size_t> order = sort_indexes(Dunordered);\n        for (int i=0; i<n_features; ++i) {\n          eigen_values_(i) = Dunordered(order[i]);\n          V(a,i) = blitz::real(Vtemp(a,order[i]));\n        }\n      }\n      else {\n        bob::math::eigSym_(Sb, Sw, V, eigen_values_);\n      }\n\n      // Convert ascending order to descending order\n      eigen_values_.reverseSelf(0);\n      V.reverseSelf(1);\n\n      // limit the dimensions of the resulting projection matrix and eigen values\n      eigen_values = eigen_values_(blitz::Range(0,osize-1));\n      V.resizeAndPreserve(V.extent(0), osize);\n\n      // normalizes the eigen vectors so they have unit length\n      blitz::Range a = blitz::Range::all();\n      for (int column=0; column<V.extent(1); ++column) {\n        math::normalizeSelf(V(a,column));\n      }\n\n      // updates the machine\n      machine.setWeights(V);\n      machine.setInputSubtraction(preMean);\n\n      // also set input_div and biases to neutral values...\n      machine.setInputDivision(1.0);\n      machine.setBiases(0.0);\n    }\n\n  void FisherLDATrainer::train(Machine& machine,\n      const std::vector<blitz::Array<double,2> >& data) const {\n    blitz::Array<double,1> throw_away(output_size(data));\n    train(machine, throw_away, data);\n  }\n\n  size_t FisherLDATrainer::output_size(const std::vector<blitz::Array<double,2> >& data) const {\n    return m_strip_to_rank ? std::min(data.size()-1, (size_t)data[0].extent(1)) : data[0].extent(1);\n  }\n\n}}}\n", "meta": {"hexsha": "dee634ed8e7acdde6b9bb06fabdaa1d04b877024", "size": 6626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/learn/linear/cpp/lda.cpp", "max_stars_repo_name": "bioidiap/bob.learn.linear", "max_stars_repo_head_hexsha": "111323c3d0a7d1f0f2249ef95c18a3c0dd52be89", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-10-14T08:06:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:02:13.000Z", "max_issues_repo_path": "bob/learn/linear/cpp/lda.cpp", "max_issues_repo_name": "bioidiap/bob.learn.linear", "max_issues_repo_head_hexsha": "111323c3d0a7d1f0f2249ef95c18a3c0dd52be89", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-18T05:27:50.000Z", "max_issues_repo_issues_event_max_datetime": "2015-11-25T15:30:27.000Z", "max_forks_repo_path": "bob/learn/linear/cpp/lda.cpp", "max_forks_repo_name": "bioidiap/bob.learn.linear", "max_forks_repo_head_hexsha": "111323c3d0a7d1f0f2249ef95c18a3c0dd52be89", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-17T12:58:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-09T14:30:27.000Z", "avg_line_length": 34.3316062176, "max_line_length": 154, "alphanum_fraction": 0.6356776336, "num_tokens": 1794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5104190422832753}}
{"text": "#pragma once\n\n#include <array>\n#include <base/polyval.hpp>\n#include <boost/math/constants/constants.hpp>\n\n\nclass TransitionFunction\n{\n public:\n  template <typename NUMERIC>\n  NUMERIC operator()(const NUMERIC &x) const;\n};\n\ntemplate <typename NUMERIC>\ninline NUMERIC\nTransitionFunction::operator()(const NUMERIC &x) const\n{\n  constexpr static std::array<int, 8> coeffs_ = {0, 0, 0, 0, 35, -84, 70, -20};\n\n  if (x >= 1)\n    return 1;\n  else if (x <= 0)\n    return 0;\n  else {\n    double v = polyval(coeffs_.begin(), x, coeffs_.size());\n    assert(v >= 0 && v <= 1);\n    return v;\n  }\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename TF = TransitionFunction>\nclass PsiRadial1\n{\n public:\n  template <typename NUMERIC>\n  NUMERIC operator()(const NUMERIC &x) const;\n\n private:\n  TF t_;\n};\n\ntemplate <typename TF>\ntemplate <typename NUMERIC>\ninline NUMERIC\nPsiRadial1<TF>::operator()(const NUMERIC &x) const\n{\n  using namespace boost::math::constants;\n\n  if (std::abs(x) >= 1 && std::abs(x) <= 2) {\n    return std::sin(pi<NUMERIC>() / 2 * t_(std::abs(x) - 1));\n  } else if (2 < std::abs(x) && std::abs(x) < 4) {\n    return std::cos(pi<NUMERIC>() / 2 * t_(0.5 * std::abs(x) - 1));\n  } else {\n    return 0;\n  }\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename TF = TransitionFunction>\nclass PsiSpherical1\n{\n public:\n  template <typename NUMERIC>\n  NUMERIC operator()(const NUMERIC &x) const;\n\n private:\n  TF t_;\n};\n\ntemplate <typename TF>\ntemplate <typename NUMERIC>\ninline NUMERIC\nPsiSpherical1<TF>::operator()(const NUMERIC &x) const\n{\n  if (x <= 0)\n    return std::sqrt(t_(1 + x));\n  else\n    return std::sqrt(t_(1 - x));\n}\n\n// --------------------------------------------------------------------------------\n/**\n * @brief \\f$ \\Psi_{0,s,0} \\f$\n *\n */\ntemplate <typename TF = TransitionFunction>\nclass PsiScaling1\n{\n public:\n  template <typename NUMERIC>\n  NUMERIC operator()(const NUMERIC &x, const NUMERIC &y) const;\n\n  template <typename NUMERIC>\n  NUMERIC operator()(const NUMERIC &z) const;\n\n private:\n  TF t_;\n};\n\n// --------------------------------------------------------------------------------\ntemplate <typename TF>\ntemplate <typename NUMERIC>\ninline NUMERIC\nPsiScaling1<TF>::operator()(const NUMERIC &x, const NUMERIC &y) const\n{\n  using namespace boost::math::constants;\n  NUMERIC z = std::max(std::abs(x), std::abs(y));\n  if (z < 1)\n    return 1;\n  else if (z >= 1 && z <= 2)\n    return std::cos(pi<NUMERIC>() / 2 * t(z - 1));\n  else\n    return 0;\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename TF>\ntemplate <typename NUMERIC>\ninline NUMERIC\nPsiScaling1<TF>::operator()(const NUMERIC &z) const\n{\n  using namespace boost::math::constants;\n  if (z < 1)\n    return 1;\n  else if (z >= 1 && z <= 2)\n    return std::cos(pi<NUMERIC>() / 2 * t_(z - 1));\n  else\n    return 0;\n}\n", "meta": {"hexsha": "83402f0675a3e089bf07a7155b6d32bd70f159e2", "size": 2949, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ridgelet/construction/ridgelet_functions.hpp", "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": "ridgelet/construction/ridgelet_functions.hpp", "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": "ridgelet/construction/ridgelet_functions.hpp", "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.3409090909, "max_line_length": 83, "alphanum_fraction": 0.5489996609, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5104190422832753}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <ros/ros.h>\n\nnamespace nav{\n\ntemplate<typename T = float>\nclass CameraModel{\npublic:\n\n    ///////////////////////////////////////////////////////////////////////////////////////////////\n    // Constructors and Destructors ///////////////////////////////////////////////////////////////\n    ///////////////////////////////////////////////////////////////////////////////////////////////\n\n    CameraModel()\n    {\n    }\n\n    ~CameraModel()\n    {\n    }\n\nprivate:\n\n    ///////////////////////////////////////////////////////////////////////////////////////////////\n    // Private Methods ////////////////////////////////////////////////////////////////////////////\n    ///////////////////////////////////////////////////////////////////////////////////////////////\n    Eigen::Matrix<T, 3, 4> get_projection_matrix();\n\n\n    ///////////////////////////////////////////////////////////////////////////////////////////////\n    // Private Members ////////////////////////////////////////////////////////////////////////////\n    ///////////////////////////////////////////////////////////////////////////////////////////////\n\n    int ROWS = 0;\n    int COLS = 0;\n\n    // Distortion model (only the plum-bob model is currently supported)\n    T D[5] = {0, 0, 0, 0, 0};\n\n    // Camera Geometry\n    Eigen::Matrix<T, 3, 3> K;  // Camera intrinsics\n    Eigen::Matrix<T, 3, 3> C;  // Center of projection in world frame\n    Eigen::Matrix<T, 3, 3> R;  // Orientation of camera frame relative to world frame\n\n\n};\n\n\ntemplate<typename T>\nEigen::Matrix<T, 3, 4> CameraModel<T>::get_projection_matrix()\n{\n    Eigen::Matrix<T, 3, 1> v;\n    Eigen::DiagonalMatrix<T, 3> I = v.asDiagonal();\n    Eigen::Matrix<T, 3, 4> aug;\n    aug.block(0, 0, 2, 2) = I;\n    aug. col(2) = C;\n    return K * R * aug; \n}\n\n} // namespace nav", "meta": {"hexsha": "477b5497a7e19e268157df6c7bba3fbc8cc79b6e", "size": 1837, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "perception/navigator_vision/include/navigator_vision_lib/image_acquisition/camera_model.hpp", "max_stars_repo_name": "saltyan007/kill_test", "max_stars_repo_head_hexsha": "a641dd74bae38122c3a044ef11cd445042d85e2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "perception/navigator_vision/include/navigator_vision_lib/image_acquisition/camera_model.hpp", "max_issues_repo_name": "saltyan007/kill_test", "max_issues_repo_head_hexsha": "a641dd74bae38122c3a044ef11cd445042d85e2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perception/navigator_vision/include/navigator_vision_lib/image_acquisition/camera_model.hpp", "max_forks_repo_name": "saltyan007/kill_test", "max_forks_repo_head_hexsha": "a641dd74bae38122c3a044ef11cd445042d85e2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-29T12:24:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T12:24:15.000Z", "avg_line_length": 29.6290322581, "max_line_length": 99, "alphanum_fraction": 0.3342406097, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.510419030751544}}
{"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_ACSCD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACSCD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing acscd capabilities\n\n    inverse cosecant in degree.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = acscd(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r =  asind(rec(x));;\n    @endcode\n\n    @see acsc\n\n  **/\n  const boost::dispatch::functor<tag::acscd_> acscd = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/acscd.hpp>\n#include <boost/simd/function/simd/acscd.hpp>\n\n#endif\n", "meta": {"hexsha": "0b54d59c55c1983e4e42799b9796589002bbc7a3", "size": 1078, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/acscd.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/acscd.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/acscd.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": 21.137254902, "max_line_length": 100, "alphanum_fraction": 0.5686456401, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.5104190252539148}}
{"text": "#ifndef CANNON_PHYSICS_SYSTEMS_INVERTED_PENDULUM_H\n#define CANNON_PHYSICS_SYSTEMS_INVERTED_PENDULUM_H \n\n#include <Eigen/Dense>\n\n#include <ompl/control/ODESolver.h>\n#include <ompl/control/spaces/RealVectorControlSpace.h>\n\n#include <cannon/physics/systems/system.hpp>\n#include <cannon/physics/rk4_integrator.hpp>\n\nnamespace oc = ompl::control;\nnamespace ob = ompl::base;\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace physics {\n    namespace systems {\n\n      struct Hol2DSystem : System {\n        Hol2DSystem() {}\n\n        virtual void operator()(const VectorXd& s, VectorXd& dsdt, const double /*t*/) override {\n          double ux = s[2];\n          double uy = s[3];\n\n          dsdt.resize(4);\n          dsdt[0] = ux;\n          dsdt[1] = uy;\n          dsdt[2] = 0.0;\n          dsdt[3] = 0.0;\n        }\n\n        virtual void ompl_ode_adaptor(const oc::ODESolver::StateType& q, \n            const oc::Control* control, oc::ODESolver::StateType& qdot) override {\n\n          const double ux = control->as<oc::RealVectorControlSpace::ControlType>()->values[0];\n          const double uy = control->as<oc::RealVectorControlSpace::ControlType>()->values[1];\n\n          VectorXd s(4);\n          s[0] = q[0];\n          s[1] = q[1];\n          s[2] = ux;\n          s[3] = uy;\n          VectorXd dsdt(4);\n\n          (*this)(s, dsdt, 0.0);\n\n          qdot.resize(q.size(), 0);\n          for (unsigned int i = 0; i < q.size(); i++) {\n            qdot[i] = dsdt[i];\n          }\n        }\n\n        virtual std::tuple<MatrixXd, MatrixXd, VectorXd> get_linearization(const VectorXd& x) override {\n          MatrixXd A = MatrixXd::Zero(2, 2);\n          MatrixXd B = MatrixXd::Zero(2, 2);\n          VectorXd c = VectorXd::Zero(2);\n\n          // TODO \n          throw std::runtime_error(\"Not implemented yet\");\n          \n          return std::make_tuple(A, B, c);\n        }\n\n        virtual void\n        get_continuous_time_linearization(const oc::ODESolver::StateType &q,\n                                          Ref<MatrixXd> A,\n                                          Ref<MatrixXd> B) override {\n          // TODO\n          throw std::runtime_error(\"Not implemented yet\");\n        }\n\n        static void ompl_post_integration(const ob::State* /*state*/, const\n            oc::Control* /*control*/, const double /*duration*/, ob::State *result) {\n          // Nothing necessary\n        }\n\n        // Parameters?\n        \n      };\n\n      class Holonomic2D {\n        public:\n          Holonomic2D() = delete;\n\n          Holonomic2D(Vector2d s, Vector2d g) : e_(s_, 4, 0.01), start_(s), goal_(g) {\n            state_ = Vector4d::Zero(); \n            reset();\n          }\n\n          std::pair<VectorXd, double> step(double ux, double uy) {\n            double clipped_ux = std::max(-1.0, std::min(ux, 1.0));\n            double clipped_uy = std::max(-1.0, std::min(uy, 1.0));\n\n            state_[2] = clipped_ux;\n            state_[3] = clipped_uy;\n\n            double goal_r = -(state_.head(2) - goal_).norm();\n            double control_r = -(std::abs(clipped_ux), + std::abs(clipped_uy));\n\n            double reward = goal_r + 0.1*control_r;\n\n            e_.set_state(state_);\n            state_ = e_.step();\n\n            return std::make_pair(state_.head(2), reward);\n          }\n\n          VectorXd reset() {\n            state_.head(2) = start_ + Vector2d::Random() * 0.1;\n            state_[2] = 0.0;\n            state_[3] = 0.0;\n\n            return state_.head(2);\n          }\n\n          Hol2DSystem s_;\n\n        private:\n          RK4Integrator e_;\n\n          Vector4d state_;\n\n          Vector2d start_;\n          Vector2d goal_;\n\n      };\n\n    } // namespace systems\n  } // namespace physics\n} // namespace cannon\n\n#endif /* ifndef CANNON_PHYSICS_SYSTEMS_INVERTED_PENDULUM_H */\n", "meta": {"hexsha": "0f7bd3674056c8de0a7e4291342961c601629bb7", "size": 3776, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/physics/systems/holonomic_2d.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/physics/systems/holonomic_2d.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/physics/systems/holonomic_2d.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": 27.7647058824, "max_line_length": 104, "alphanum_fraction": 0.5360169492, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.5104190252539148}}
{"text": "/***********************************************************************************************************************\n *  OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n *  following conditions are met:\n *\n *  (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n *  disclaimer.\n *\n *  (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n *  following disclaimer in the documentation and/or other materials provided with the distribution.\n *\n *  (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote\n *  products derived from this software without specific prior written permission from the respective party.\n *\n *  (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative\n *  works may not use the \"OpenStudio\" trademark, \"OS\", \"os\", or any other confusingly similar designation without\n *  specific prior written permission from Alliance for Sustainable Energy, LLC.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR\n *  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n *  PROCUREMENT OF SUBSTITUTE 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 NEGLIGENCE OR OTHERWISE)\n *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **********************************************************************************************************************/\n\n#include \"Geometry.hpp\"\n#include \"Vector3d.hpp\"\n#include \"Point3d.hpp\"\n#include \"../core/Logger.hpp\"\n\n#include <boost/optional.hpp>\n#include <boost/math/constants/constants.hpp>\n\nnamespace openstudio {\nconstexpr double EPSILON = 1E-10;\n\nclass LineLinear2d  // Geometry line in linear form. General form: Ax + By + C = 0;\n{\n public:\n  double A = 0.0;\n  double B = 0.0;\n  double C = 0.0;\n\n  LineLinear2d(double a, double b, double c) : A{a}, B{b}, C{c} {}\n\n  LineLinear2d(const Point3d& p1, const Point3d& p2) : A{p1.y() - p2.y()}, B{p2.x() - p1.x()}, C{p1.x() * p2.y() - p2.x() * p1.y()} {}\n\n  boost::optional<Point3d> collide(const LineLinear2d& line2) const {\n    double WAB = A * line2.B - line2.A * B;\n    double WBC = B * line2.C - line2.B * C;\n    double WCA = C * line2.A - line2.C * A;\n\n    if (WAB == 0) {\n      return boost::none;\n    }\n\n    return Point3d(WBC / WAB, WCA / WAB, 0);\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const LineLinear2d& l) {\n    os << \"LineLinear2d [A=\" << l.A << \", B=\" << l.B << \", C=\" << l.C << \"]\";\n    return os;\n  }\n\n private:\n  REGISTER_LOGGER(\"utilities.LineLinear2d\");\n};\n\nclass Ray2d\n{\n public:\n  Ray2d() {\n    // nop\n  }\n\n  Point3d point;\n  Vector3d vector;\n\n  Ray2d(const Point3d& t_point, const Vector3d& t_vector) : point{t_point}, vector{t_vector} {}\n\n  boost::optional<Point3d> collide(const LineLinear2d& line, double epsilon) const {\n    LineLinear2d ll2d = getLinearForm();\n\n    // rewrite?\n    boost::optional<Point3d> collide = ll2d.collide(line);\n    if (!collide) {\n      return boost::none;\n    }\n\n    /*\n    * Portably there is better way to do this. this is from graphical.\n    */\n    Vector3d collideVector = collide.get() - point;\n\n    double d = vector.dot(collideVector);\n\n    if (d < epsilon) {\n      return boost::none;\n    }\n\n    return collide;\n  }\n\n  LineLinear2d getLinearForm() const {\n    double x = point.x();\n    double y = point.y();\n\n    double B = -vector.x();\n    double A = vector.y();\n\n    double C = -1 * (A * x + B * y);\n    return LineLinear2d(A, B, C);\n  }\n\n  bool isOnLeftSide(const Point3d& p, double epsilon) const {\n    Vector3d direction = p - point;\n    Vector3d orthRight = vector.orthogonalRight();\n    return (orthRight.dot(direction) < epsilon);\n  }\n\n  bool isOnRightSide(const Point3d& p, double epsilon) const {\n    Vector3d direction = p - point;\n    Vector3d orthRight = vector.orthogonalRight();\n    return (orthRight.dot(direction) > -epsilon);\n  }\n\n  boost::optional<Point3d> intersectRay2d(std::shared_ptr<Ray2d> other) const {\n    /*\n    * Calculate intersection points for rays. It can return more then one\n    * intersection point when rays overlaps.\n    *\n    * see http://geomalgorithms.com/a05-_intersect-1.html\n    * see http://softsurfer.com/Archive/algorithm_0102/algorithm_0102.htm\n    */\n\n    Point3d s1p0 = point;\n    Point3d s1p1 = Point3d(point) + vector;\n\n    Point3d s2p0 = other->point;\n    // TODO: this is unread!\n    // cppcheck-suppress unreadVariable\n    Point3d s2p1 = Point3d(other->point) + other->vector;\n\n    Vector3d u = vector;\n    Vector3d v = other->vector;\n\n    Vector3d w = s1p0 - s2p0;\n\n    double d = perpDot(u, v);\n\n    // test if they are parallel (includes either being a point)\n    if (std::abs(d) < EPSILON) {  // S1 and S2 are parallel\n\n      if (perpDot(u, w) != 0 || perpDot(v, w) != 0) {\n        // they are NOT collinear\n        return boost::none;\n      }\n\n      // they are collinear or degenerate\n      // check if they are degenerate points\n      double du = u.dot(u);\n      double dv = v.dot(v);\n\n      if (du == 0 && dv == 0) {\n        // both segments are points\n        if (s1p0 != s2p0) {\n          return boost::none;\n        }\n        // they are the same point\n        return s1p0;\n      }\n\n      if (du == 0) {\n        // S1 is a single point\n        Ray2d r = Ray2d(s2p0, v);\n        if (!r.inCollinearRay(s1p0)) {\n          return boost::none;\n        }\n        return s1p0;\n      }\n\n      if (dv == 0) {\n        // S2 is a single point\n        Ray2d r = Ray2d(s1p0, u);\n        if (!r.inCollinearRay(s2p0)) {\n          return boost::none;\n        }\n        return s2p0;\n      }\n\n      //they are collinear segments - get overlap (or not)\n      double t0, t1;\n      // endpoints of S1 in eqn for S2\n      Vector3d w2 = s1p1 - s2p0;\n\n      if (v.x() != 0) {\n        t0 = w.x() / v.x();\n        t1 = w2.x() / v.x();\n      } else {\n        t0 = w.y() / v.y();\n        t1 = w2.y() / v.y();\n      }\n\n      if (t0 > t1) {\n        // must have t0 smaller than t1\n        double t = t0;\n        t0 = t1;\n        t1 = t;  // swap if not\n      }\n\n      if (t1 < 0) {\n        return boost::none;\n      }\n\n      // clip to min 0\n      if (t0 < 0) {\n        t0 = 0;\n      }\n\n      // they overlap in a valid subsegment\n\n      // I0 = S2_P0 + t0 * v;\n      // I1 = S2_P0 + t1 * v;\n      Point3d I0 = s2p0 + t0 * v;\n      // TODO: this is unread!\n      // cppcheck-suppress unreadVariable\n      Point3d I1 = s2p0 + t1 * v;\n\n      if (t0 == t1) {\n        // intersect is a point\n        return I0;\n      }\n\n      return I0;  // only need first intersection point\n    }\n\n    // the segments are skewed and may intersect in a point\n\n    // get the intersect parameter for S1\n    double sI = perpDot(v, w) / d;\n    if (sI < 0) {\n      return boost::none;\n    }\n\n    // get the intersect parameter for S2\n    double tI = perpDot(u, w) / d;\n    if (tI < 0) {\n      return boost::none;\n    }\n\n    // I0 = S1_P0 + sI * u;\n    // compute S1 intersect point\n    Point3d I0 = s1p0 + sI * u;\n    return I0;\n  }\n\n  /// perp dot product between two vectors\n  static double perpDot(const Vector3d& p1, const Vector3d& p2) {\n    return (p1.x() * p2.y() - p1.y() * p2.x());\n  }\n\n  bool inCollinearRay(const Point3d& p) const {\n    // test if p is on ray\n    Vector3d collideVector = p - point;\n\n    double d = vector.dot(collideVector);\n    if (d < 0) {\n      return false;\n    }\n    return true;\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const Ray2d& r) {\n    os << \"Ray2d [A=\" << r.point << \", U=\" << r.vector << \"]\";\n    return os;\n  }\n\n  // Returns true if this ray2d is equal to other\n  bool operator==(const Ray2d& other) const {\n    if (point == other.point && vector == other.vector) {\n      return true;\n    }\n    return false;\n  }\n\n private:\n  REGISTER_LOGGER(\"utilities.Ray2d\");\n};\n\nclass Edge\n{\n public:\n  Point3d begin;\n  Point3d end;\n  std::shared_ptr<Ray2d> bisectorPrevious;\n  std::shared_ptr<Ray2d> bisectorNext;\n  std::shared_ptr<Edge> next;\n  std::shared_ptr<Edge> previous;\n\n  Edge() {\n    // nop\n  }\n\n  Edge(const Point3d& t_begin, const Point3d& t_end) : begin{t_begin}, end{t_end} {}\n\n  Vector3d normalize() const {\n    Vector3d v = Vector3d(end.x(), end.y(), end.z()) - Vector3d(begin.x(), begin.y(), begin.z());\n    v.normalize();\n    return v;\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const Edge& e) {\n    os << \"EdgeEntry [p1=\" << e.begin << \", p2=\" << e.end << \", bp=\" << *e.bisectorPrevious << \", bn=\" << *e.bisectorNext << \"]\";\n    return os;\n  }\n\n  // Returns true if this edge is equal to other\n  bool operator==(const Edge& other) const {\n    if (begin == other.begin && end == other.end) {\n      return true;\n    }\n    return false;\n  }\n\n  // Returns true if this edge is not equal to other\n  bool operator!=(const Edge& other) const {\n    if (begin != other.begin || end != other.end) {\n      return true;\n    }\n    return false;\n  }\n\n private:\n  REGISTER_LOGGER(\"utilities.Edge\");\n};\n\nclass Face;  // forward declaration\n\nclass FaceNode\n{\n public:\n  Point3d point;\n  double distance = 0.0;\n  std::shared_ptr<Face> face;\n\n  FaceNode() {\n    // nop\n  }\n\n  FaceNode(const Point3d& t_point, double t_distance, std::shared_ptr<Face> t_face) : point{t_point}, distance{t_distance}, face{t_face} {}\n\n  // Returns true if this vertex is equal to other\n  bool operator==(const FaceNode& other) const {\n    if (point == other.point && distance == other.distance) {\n      return true;\n    }\n    return false;\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const FaceNode& fn) {\n    os << \"FaceNode [point=\" << fn.point << \", distance=\" << fn.distance << \"]\";\n    return os;\n  }\n\n private:\n  REGISTER_LOGGER(\"utilities.FaceNode\");\n};\n\nclass Vertex\n{\n public:\n  Point3d point;\n  double distance = 0.0;\n  std::shared_ptr<Ray2d> bisector;\n  std::shared_ptr<Edge> previousEdge;\n  std::shared_ptr<Edge> nextEdge;\n  std::shared_ptr<FaceNode> leftFaceNode;\n  std::shared_ptr<FaceNode> rightFaceNode;\n  bool processed = false;\n\n  Vertex() {\n    // nop\n  }\n\n  Vertex(const Point3d& t_point, double t_distance, std::shared_ptr<Ray2d> t_bisector, std::shared_ptr<Edge> t_previousEdge,\n         std::shared_ptr<Edge> t_nextEdge)\n    : point{t_point}, distance{t_distance}, bisector{t_bisector}, previousEdge{t_previousEdge}, nextEdge{t_nextEdge} {}\n\n  Vertex(const std::shared_ptr<Edge> t_previousEdge, const std::shared_ptr<Edge> t_nextEdge) : previousEdge{t_previousEdge}, nextEdge{t_nextEdge} {}\n\n  static std::shared_ptr<Vertex> previous(std::shared_ptr<Vertex> vertex, std::vector<std::shared_ptr<Vertex>>& vertices) {\n    int index = getOffsetVertexIndex(vertex, vertices, -1);\n    return vertices[index];\n  }\n\n  static std::shared_ptr<Vertex> next(std::shared_ptr<Vertex> vertex, std::vector<std::shared_ptr<Vertex>>& vertices) {\n    int index = getOffsetVertexIndex(vertex, vertices, 1);\n    return vertices[index];\n  }\n\n  static std::shared_ptr<Vertex> previous(std::shared_ptr<Vertex> vertex, std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) {\n    int index = Vertex::getLavIndex(vertex, sLav);\n    return Vertex::previous(vertex, sLav[index]);\n  }\n\n  static std::shared_ptr<Vertex> next(std::shared_ptr<Vertex> vertex, std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) {\n    int index = Vertex::getLavIndex(vertex, sLav);\n    return Vertex::next(vertex, sLav[index]);\n  }\n\n  static int getLavIndex(std::shared_ptr<Vertex> vertex, std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) {\n    for (unsigned i = 0; i < sLav.size(); i++) {\n      if (std::find(sLav[i].begin(), sLav[i].end(), vertex) != sLav[i].end()) {\n        return i;\n      }\n    }\n    return -1;\n  }\n\n  static void removeFromLav(std::shared_ptr<Vertex> vertex, std::vector<std::shared_ptr<Vertex>>& lav) {\n    auto it = std::find(lav.begin(), lav.end(), vertex);\n    if (it != lav.end()) {\n      lav.erase(it);\n    }\n  }\n\n  static void removeFromLav(std::shared_ptr<Vertex> vertex, std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) {\n    int i = Vertex::getLavIndex(vertex, sLav);\n    if (i != -1) {\n      Vertex::removeFromLav(vertex, sLav[i]);\n    }\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const Vertex& v) {\n    std::string processed_str = \"false\";\n    if (v.processed) {\n      processed_str = \"true\";\n    }\n\n    os << \"VertexEntry [v=\" << v.point << \", processed=\" << processed_str << \", bisector=\";\n\n    if (v.bisector) {\n      os << *v.bisector;\n    } else {\n      os << \"null\";\n    }\n\n    os << \", previousEdge=\";\n\n    if (v.previousEdge) {\n      os << *v.previousEdge;\n    } else {\n      os << \"null\";\n    }\n\n    os << \", nextEdge=\";\n\n    if (v.nextEdge) {\n      os << *v.nextEdge;\n    } else {\n      os << \"null\";\n    }\n\n    os << \"]\";\n    return os;\n  }\n\n  // Returns true if this vertex is equal to other\n  bool operator==(const Vertex& other) const {\n    if (point == other.point && distance == other.distance && bisector == other.bisector && previousEdge == other.previousEdge\n        && nextEdge == other.nextEdge) {\n      return true;\n    }\n    return false;\n  }\n\n  // Returns true if this vertex is not equal to other\n  bool operator!=(const Vertex& other) const {\n    if (point != other.point || distance != other.distance || bisector != other.bisector || previousEdge != other.previousEdge\n        || nextEdge != other.nextEdge) {\n      return true;\n    }\n    return false;\n  }\n\n private:\n  REGISTER_LOGGER(\"utilities.Vertex\");\n\n  friend int getOffsetVertexIndex(std::shared_ptr<Vertex> vertex, std::vector<std::shared_ptr<Vertex>>& vertices, int offset) {\n    auto it = std::find(vertices.begin(), vertices.end(), vertex);\n    if (it == vertices.end()) {\n      LOG_AND_THROW(\"Could not find vertex.\");\n    }\n    int vsize = vertices.size();\n    auto pos = std::distance(vertices.begin(), it);\n    pos += offset;\n    if (pos < 0) {\n      pos += vertices.size();\n    } else if (pos >= vsize) {\n      pos -= vertices.size();\n    }\n    return static_cast<int>(pos);\n  }\n};\n\nclass Face\n{\n public:\n  std::vector<std::shared_ptr<FaceNode>> nodes;\n  std::shared_ptr<Edge> edge;\n  bool closed = false;\n\n  unsigned getNodeIndex(std::shared_ptr<FaceNode> node) const {\n    auto it = std::find(nodes.begin(), nodes.end(), node);\n    if (it == nodes.end()) {\n      LOG_AND_THROW(\"Could not find node in nodes.\")\n    }\n    return static_cast<unsigned>(it - nodes.begin());\n  }\n\n  bool isEnd(std::shared_ptr<FaceNode> vertex) const {\n    unsigned nodeIndex = getNodeIndex(vertex);\n    return (nodeIndex == 0 || nodeIndex == nodes.size() - 1);\n  }\n\n  bool isUnconnected() const {\n    if (edge) {\n      return false;\n    }\n    return true;\n  }\n\n  std::shared_ptr<FaceNode> popNode(std::shared_ptr<FaceNode> node) {\n    if (node->face->nodes != this->nodes) {\n      LOG_AND_THROW(\"Node is not assigned to this list!\");\n    }\n    if (nodes.empty()) {\n      LOG_AND_THROW(\"List is empty, can't remove.\");\n    }\n    if (!isEnd(node)) {\n      LOG_AND_THROW(\"Can pop only from end of queue.\");\n    }\n\n    node->face = nullptr;\n\n    unsigned nodeIndex = getNodeIndex(node);\n    nodes.erase(nodes.begin() + nodeIndex);\n\n    if (nodes.size() == 0) {\n      return nullptr;\n    } else if (nodeIndex > 0) {\n      return nodes[nodes.size() - 1];\n    } else {\n      return nodes[0];\n    }\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const Face& f) {\n    os << \"Face [size=\" << f.nodes.size() << \", edge=\";\n\n    if (f.edge) {\n      os << *f.edge;\n    } else {\n      os << \"null\";\n    }\n\n    os << \", closed=\" << f.closed << \"]\";\n\n    return os;\n  }\n\n private:\n  REGISTER_LOGGER(\"utilities.Face\");\n};\n\nclass QueueEvent\n{\n public:\n  enum QueueEventType\n  {\n    TYPE_EDGE = 0,\n    TYPE_SPLIT = 1,\n    TYPE_SPLIT_VERTEX = 2,\n  };\n\n  QueueEventType eventType;\n  Point3d point;\n  double distance = 0.0;\n  std::shared_ptr<Vertex> previousVertex;\n  std::shared_ptr<Vertex> nextVertex;\n  std::shared_ptr<Vertex> parent;\n  std::shared_ptr<Edge> oppositeEdge;\n\n  QueueEvent() : eventType{TYPE_EDGE} {\n    // nop\n  }\n\n  QueueEvent(const Point3d& t_point, double t_distance, std::shared_ptr<Vertex> t_previousVertex, std::shared_ptr<Vertex> t_nextVertex)\n    : eventType{TYPE_EDGE}, point{t_point}, distance{t_distance}, previousVertex{t_previousVertex}, nextVertex{t_nextVertex} {}\n\n  QueueEvent(const Point3d& t_point, double t_distance, std::shared_ptr<Vertex> t_parent)\n    : eventType{TYPE_SPLIT_VERTEX}, point{t_point}, distance{t_distance}, parent{t_parent} {}\n\n  QueueEvent(const Point3d& t_point, double t_distance, std::shared_ptr<Vertex> t_parent, std::shared_ptr<Edge> t_oppositeEdge)\n    : eventType{TYPE_SPLIT}, point{t_point}, distance{t_distance}, parent{t_parent}, oppositeEdge{t_oppositeEdge} {}\n\n  friend std::ostream& operator<<(std::ostream& os, const QueueEvent& e) {\n    if (e.eventType == TYPE_EDGE) {\n      os << \"EdgeEvent [v=\" << e.point << \", previousVertex=\" << e.previousVertex->point << \", nextVertex=\" << e.nextVertex->point\n         << \", distance=\" << e.distance << \"]\";\n    } else if (e.eventType == TYPE_SPLIT) {\n      os << \"SplitEvent [v=\" << e.point << \", parent=\" << e.parent->point << \", distance=\" << e.distance << \"]\";\n    } else if (e.eventType == TYPE_SPLIT_VERTEX) {\n      os << \"VertexSplitEvent [v=\" << e.point << \", parent=\" << e.parent->point << \", distance=\" << e.distance << \"]\";\n    }\n    return os;\n  }\n\n  bool operator<(const QueueEvent& other) const {\n    return distance < other.distance;\n  }\n\n  // Returns true if this queue event is equal to other\n  bool operator==(const QueueEvent& other) const {\n    if (eventType == other.eventType && point == other.point && distance == other.distance && parent == other.parent\n        && oppositeEdge == other.oppositeEdge && previousVertex == other.previousVertex && nextVertex == other.nextVertex) {\n      return true;\n    }\n    return false;\n  }\n\n  void addEventToGroup(std::vector<std::shared_ptr<Vertex>>& parentGroup) const {\n    if (eventType == TYPE_SPLIT || eventType == TYPE_SPLIT_VERTEX) {\n      parentGroup.push_back(parent);\n    } else if (eventType == TYPE_EDGE) {\n      parentGroup.push_back(previousVertex);\n      parentGroup.push_back(nextVertex);\n    }\n  }\n\n  bool isEventInGroup(std::vector<std::shared_ptr<Vertex>>& parentGroup) {\n    if (eventType == TYPE_SPLIT || eventType == TYPE_SPLIT_VERTEX) {\n      bool foundParent = std::find(parentGroup.begin(), parentGroup.end(), parent) != parentGroup.end();\n      return foundParent;\n    } else if (eventType == TYPE_EDGE) {\n      bool foundPreviousVertex = std::find(parentGroup.begin(), parentGroup.end(), previousVertex) != parentGroup.end();\n      bool foundNextVertex = std::find(parentGroup.begin(), parentGroup.end(), nextVertex) != parentGroup.end();\n      return (foundPreviousVertex || foundNextVertex);\n    }\n    return false;\n  }\n\n  std::shared_ptr<Edge> getOppositeEdgePrevious() const {\n    return oppositeEdge;\n  }\n\n  bool isObsolete() const {\n    if (eventType == TYPE_EDGE) {\n      return (previousVertex->processed || nextVertex->processed);\n    } else {\n      return parent->processed;\n    }\n  }\n\n  struct Comparer\n  {\n    bool operator()(std::shared_ptr<QueueEvent> q1, std::shared_ptr<QueueEvent> q2) const {\n      return *q1 < *q2;\n    }\n  };\n\n  static void insert_sorted(std::vector<std::shared_ptr<QueueEvent>>& queue, std::shared_ptr<QueueEvent> item) {\n    queue.insert(std::upper_bound(queue.begin(), queue.end(), item, QueueEvent::Comparer()), item);\n  }\n\n private:\n  REGISTER_LOGGER(\"utilities.QueueEvent\");\n};\n\nclass Chain  // Chains of queue events\n{\n public:\n  enum ChainType\n  {\n    TYPE_EDGE = 0,\n    TYPE_SPLIT = 1,\n    TYPE_SINGLE_EDGE = 2\n  };\n\n  enum ChainMode\n  {\n    MODE_EDGE = 0,\n    MODE_SPLIT = 1,\n    MODE_CLOSED_EDGE = 2\n  };\n\n  ChainType chainType;\n  std::vector<std::shared_ptr<QueueEvent>> edgeList;\n  std::shared_ptr<QueueEvent> splitEvent;\n\n  bool closed = false;\n  bool split = false;\n\n  Chain() : chainType{TYPE_EDGE} {\n    // nop\n  }\n\n  Chain(std::shared_ptr<QueueEvent> t_splitEvent) : chainType{TYPE_SPLIT}, splitEvent{t_splitEvent} {}\n\n  Chain(std::vector<std::shared_ptr<QueueEvent>>& t_edgeList, std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav)\n    : chainType{TYPE_EDGE}, edgeList{t_edgeList}, closed{(getPreviousVertex(sLav) == getNextVertex(sLav))} {}\n\n  Chain(std::shared_ptr<Edge> t_oppositeEdge, std::shared_ptr<Vertex> t_nextVertex, std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav)\n    : chainType{TYPE_SINGLE_EDGE}, nextVertex{t_nextVertex}, oppositeEdge{t_oppositeEdge} {\n    /*\n     * previous vertex for opposite edge event is valid only before\n     * processing of multi split event start .We need to store vertex before\n     * processing starts.\n    */\n    this->previousVertex = Vertex::previous(nextVertex, sLav);\n  }\n\n  ChainMode getChainMode() const {\n    if (chainType == TYPE_EDGE) {\n      if (closed && split) {\n        LOG_AND_THROW(\"Chain can't be closed and split\");\n      } else if (closed) {\n        return MODE_CLOSED_EDGE;\n      } else if (split) {\n        return MODE_SPLIT;\n      }\n      return MODE_EDGE;\n    } else if (chainType == TYPE_SPLIT) {\n      return MODE_SPLIT;\n    }\n    return MODE_SPLIT;\n  }\n\n  std::shared_ptr<Edge> getPreviousEdge() const {\n    if (chainType == TYPE_EDGE) {\n      return edgeList[0]->previousVertex->previousEdge;\n    } else if (chainType == TYPE_SINGLE_EDGE) {\n      return oppositeEdge;\n    } else {\n      return splitEvent->parent->previousEdge;\n    }\n  }\n\n  std::shared_ptr<Edge> getNextEdge() const {\n    if (chainType == TYPE_EDGE) {\n      return edgeList[edgeList.size() - 1]->nextVertex->nextEdge;\n    } else if (chainType == TYPE_SINGLE_EDGE) {\n      return oppositeEdge;\n    } else {\n      return splitEvent->parent->nextEdge;\n    }\n  }\n\n  std::shared_ptr<Vertex> getPreviousVertex(std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) const {\n    if (chainType == TYPE_EDGE) {\n      return edgeList[0]->previousVertex;\n    } else if (chainType == TYPE_SINGLE_EDGE) {\n      return previousVertex;\n    } else {\n      return Vertex::previous(splitEvent->parent, sLav);\n    }\n  }\n\n  std::shared_ptr<Vertex> getNextVertex(std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) const {\n    if (chainType == TYPE_EDGE) {\n      return edgeList[edgeList.size() - 1]->nextVertex;\n    } else if (chainType == TYPE_SINGLE_EDGE) {\n      return nextVertex;\n    } else {\n      return Vertex::next(splitEvent->parent, sLav);\n    }\n  }\n\n  std::shared_ptr<Vertex> getCurrentVertex() const {\n    std::shared_ptr<Vertex> ret;\n    if (chainType == TYPE_SPLIT) {\n      return splitEvent->parent;\n    }\n    return ret;\n  }\n\n  std::shared_ptr<Edge> getOppositeEdge() const {\n    if (chainType == TYPE_SPLIT) {\n      if (splitEvent->eventType != QueueEvent::TYPE_SPLIT_VERTEX) {\n        return splitEvent->oppositeEdge;\n      }\n    }\n    return oppositeEdge;\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const Chain& c) {\n    std::string type_s;\n    if (c.chainType == TYPE_EDGE) {\n      type_s = \"Edge\";\n    } else if (c.chainType == TYPE_SPLIT) {\n      type_s = \"Split\";\n    } else {\n      type_s = \"SingleEdge\";\n    }\n\n    std::string mode_s;\n    if (c.getChainMode() == MODE_EDGE) {\n      mode_s = \"EDGE\";\n    } else if (c.getChainMode() == MODE_SPLIT) {\n      mode_s = \"SPLIT\";\n    } else {\n      mode_s = \"CLOSED_EDGE\";\n    }\n\n    os << \"Chain [type=\" << type_s << \", mode=\" << mode_s << \", pe=\";\n\n    if (c.getPreviousEdge()) {\n      os << *c.getPreviousEdge();\n    } else {\n      os << \"null\";\n    }\n\n    os << \", ne=\";\n\n    if (c.getNextEdge()) {\n      os << *c.getNextEdge();\n    } else {\n      os << \"null\";\n    }\n\n    os << \", oe=\";\n\n    if (c.getOppositeEdge()) {\n      os << *c.getOppositeEdge();\n    } else {\n      os << \"null\";\n    }\n\n    os << \", cv=\";\n\n    if (c.getCurrentVertex()) {\n      os << *c.getCurrentVertex();\n    } else {\n      os << \"null\";\n    }\n\n    os << \"]\";\n\n    return os;\n  }\n\n  // Returns true if this chain is equal to other\n  bool operator==(const Chain& other) const {\n    if (chainType == other.chainType && splitEvent == other.splitEvent && edgeList == other.edgeList) {\n      return true;\n    }\n    return false;\n  }\n\n  struct Comparer\n  {\n    Point3d center;\n\n    Comparer(Point3d center) {\n      this->center = center;\n    }\n\n    static double angle(const Point3d& p1, const Point3d& p2) {\n      double dx = p2.x() - p1.x();\n      double dy = p2.y() - p1.y();\n      return atan2(dy, dx);\n    }\n\n    bool operator()(const Chain& c1, const Chain& c2) const {\n      double angle1 = angle(center, c1.getPreviousEdge()->begin);\n      double angle2 = angle(center, c2.getPreviousEdge()->begin);\n      return (angle1 < angle2);\n    }\n  };\n\n private:\n  REGISTER_LOGGER(\"utilities.Chain\");\n  std::shared_ptr<Edge> previousEdge;\n  std::shared_ptr<Edge> nextEdge;\n  std::shared_ptr<Vertex> previousVertex;\n  std::shared_ptr<Vertex> nextVertex;\n  std::shared_ptr<Vertex> currentVertex;\n  std::shared_ptr<Edge> oppositeEdge;\n};\n\nclass LevelEvent\n{\n public:\n  enum LevelEventType\n  {\n    TYPE_PICK = 0,\n    TYPE_MULTI_EDGE = 1,\n    TYPE_MULTI_SPLIT = 2\n  };\n\n  LevelEventType eventType;\n  Point3d point;\n  double distance = 0.0;\n  Chain chain;\n  std::vector<Chain> chains;\n  bool obsolete = false;\n\n  LevelEvent() : eventType{TYPE_PICK} {\n    // nop\n  }\n\n  LevelEvent(const Point3d& t_point, double t_distance, const Chain& t_chain, bool isPickEvent)\n    : point{t_point}, distance{t_distance}, chain{t_chain} {\n    if (isPickEvent) {\n      this->eventType = TYPE_PICK;\n    } else {\n      this->eventType = TYPE_MULTI_EDGE;\n    }\n  }\n\n  LevelEvent(const Point3d& t_point, double t_distance, const std::vector<Chain>& t_chains)\n    : eventType{TYPE_MULTI_SPLIT}, point{t_point}, distance{t_distance}, chains{t_chains} {}\n\n  friend std::ostream& operator<<(std::ostream& os, const LevelEvent& e) {\n    os << \"IntersectEntry [v=\" << e.point << \", distance=\" << e.distance << \"]\";\n    return os;\n  }\n\n  bool operator<(const LevelEvent& other) const {\n    return distance < other.distance;\n  }\n\n private:\n  REGISTER_LOGGER(\"utilities.LevelEvent\");\n};\n\nclass SplitCandidate\n{\n public:\n  Point3d point;\n  double distance = 0.0;\n  std::shared_ptr<Edge> oppositeEdge;\n  boost::optional<Point3d> oppositePoint;\n\n  SplitCandidate(const Point3d& t_point, double t_distance, std::shared_ptr<Edge> t_oppositeEdge, boost::optional<Point3d&> t_oppositePoint)\n    : point{t_point}, distance{t_distance}, oppositeEdge{t_oppositeEdge}, oppositePoint{t_oppositePoint} {}\n\n  // Returns true if this SplitCandidate is less than other\n  bool operator<(const SplitCandidate& other) const {\n    return (distance < other.distance);\n  }\n\n  // Returns true if this SplitCandidate is equal to other\n  bool operator==(const SplitCandidate& other) const {\n    return (point == other.point && distance == other.distance);\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const SplitCandidate& s) {\n    os << \"SplitCandidate [point=\" << s.point << \", distance=\" << s.distance << \"]\";\n    return os;\n  }\n\n private:\n  REGISTER_LOGGER(\"utilities.SplitCandidate\");\n};\n\nstatic std::vector<std::vector<Point3d>> facesToPoint3d(const std::vector<std::shared_ptr<Face>>& faces, double roofPitchDegrees, double zcoord) {\n  std::vector<std::vector<Point3d>> roofsPoint3d;\n  double roofSlope = tan(degToRad(roofPitchDegrees));\n  for (std::shared_ptr<Face> face : faces) {\n    if (face->nodes.size() == 0) {\n      continue;\n    }\n    std::vector<Point3d> roofPoint3d;\n    for (std::shared_ptr<FaceNode> v : face->nodes) {\n      Point3d p = Point3d(v->point.x(), v->point.y(), zcoord + v->distance * roofSlope);\n      roofPoint3d.push_back(p);\n    }\n    roofsPoint3d.push_back(roofPoint3d);\n  }\n  return roofsPoint3d;\n}\n\nstatic Vector3d calcVectorBisector(const Vector3d& norm1, const Vector3d& norm2) {\n  Vector3d e1v = norm1.orthogonalLeft();\n  Vector3d e2v = norm2.orthogonalLeft();\n\n  // 90 - 180 || 180 - 270\n  if (norm1.dot(norm2) > 0) {\n    e1v += e2v;\n    return e1v;\n  }\n\n  // 0 - 180\n  Vector3d ret = Vector3d(norm1);\n  ret = ret.reverseVector();\n  ret += norm2;\n\n  if (e1v.dot(norm2) < 0) {\n    // 270 - 360\n    ret = ret.reverseVector();\n  }\n\n  return ret;\n}\n\nstatic Ray2d calcBisector(const Point3d& p, std::shared_ptr<Edge> e1, std::shared_ptr<Edge> e2) {\n\n  Vector3d norm1 = e1->normalize();\n  Vector3d norm2 = e2->normalize();\n  Vector3d bisector = calcVectorBisector(norm1, norm2);\n  return Ray2d(p, bisector);\n}\n\nstatic void addPush(std::shared_ptr<FaceNode> node, std::shared_ptr<FaceNode> newNode) {\n  std::shared_ptr<Face> face = node->face;\n  if (face->closed) {\n    LOG_AND_THROW(\"Can't add node to closed Face\");\n  }\n\n  unsigned nodeIndex = face->getNodeIndex(node);\n  if (nodeIndex == face->nodes.size() - 1) {\n    // if vertex is end of list, add newVertex to end\n    face->nodes.push_back(newNode);\n  } else if (nodeIndex == 0) {\n    // if vertex is beginning of list, add newVertex to beginning\n    face->nodes.insert(face->nodes.begin(), newNode);\n  } else {\n    LOG_AND_THROW(\"Can't push new node. Node is inside a queue. New node can only be added at the ends of the queue.\");\n  }\n\n  if (face != newNode->face) {\n    newNode->face = face;\n  }\n}\n\nstatic void moveNodes(std::shared_ptr<FaceNode> firstNode, std::shared_ptr<FaceNode> secondNode) {\n  if (firstNode->face == secondNode->face) {\n    return;\n  }\n  std::shared_ptr<FaceNode> currentQueue = firstNode;\n  std::shared_ptr<FaceNode> current = secondNode;\n  std::shared_ptr<FaceNode> next = nullptr;\n  while (current) {\n    next = current->face->popNode(current);\n    addPush(currentQueue, current);\n    currentQueue = current;\n    current = next;\n  }\n}\n\nstatic void connectFaces(std::shared_ptr<FaceNode> firstFaceNode, std::shared_ptr<FaceNode> secondFaceNode) {\n  std::shared_ptr<Face> firstFace = firstFaceNode->face;\n  std::shared_ptr<Face> secondFace = secondFaceNode->face;\n  if (firstFace == secondFace) {\n    if (!firstFace->isEnd(firstFaceNode) || !secondFace->isEnd(secondFaceNode)) {\n      LOG_AND_THROW(\"Tried to connect the same list not on end nodes.\");\n    }\n    if (firstFace->isUnconnected() || secondFace->isUnconnected()) {\n      LOG_AND_THROW(\"Can't close node queue not conected with edges.\");\n    }\n\n    firstFace->closed = true;\n    return;\n  }\n\n  if (!firstFace->isUnconnected() && !secondFace->isUnconnected()) {\n    LOG_AND_THROW(\"Can't connect two different queues if each of them is connected to an edge.\");\n  }\n\n  if (!firstFace->isUnconnected()) {\n    moveNodes(firstFaceNode, secondFaceNode);\n    secondFace->closed = true;\n  } else {\n    moveNodes(secondFaceNode, firstFaceNode);\n    firstFace->closed = true;\n  }\n}\n\nstatic void initSlav(const std::vector<Point3d>& polygon, std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav,\n                     std::vector<std::shared_ptr<Edge>>& edges, std::vector<std::shared_ptr<Face>>& faces) {\n  int size = polygon.size();\n  for (int i = 0; i < size; i++) {\n    int j = (i + 1) % size;\n    std::shared_ptr<Edge> e(new Edge(polygon[i], polygon[j]));\n    edges.push_back(e);\n  }\n\n  for (int i = 0; i < size; i++) {\n    int h = (i - 1 + size) % size;\n    int j = (i + 1) % size;\n    edges[i]->previous = edges[h];\n    edges[i]->next = edges[j];\n  }\n\n  for (std::shared_ptr<Edge> edge : edges) {\n    std::shared_ptr<Edge> nextEdge = edge->next;\n\n    std::shared_ptr<Ray2d> bisector(new Ray2d(calcBisector(edge->end, edge, nextEdge)));\n\n    edge->bisectorNext = bisector;\n\n    nextEdge->bisectorPrevious = bisector;\n  }\n\n  std::vector<std::shared_ptr<Vertex>> lav;\n\n  for (std::shared_ptr<Edge> edge : edges) {\n    std::shared_ptr<Edge> nextEdge = edge->next;\n\n    std::shared_ptr<Vertex> vertex(new Vertex(edge->end, 0, edge->bisectorNext, edge, nextEdge));\n\n    lav.push_back(vertex);\n  }\n  sLav.push_back(lav);\n\n  for (std::shared_ptr<Vertex> vertex : lav) {\n    std::shared_ptr<Vertex> next = Vertex::next(vertex, lav);\n\n    // create face on right site of vertex\n    std::shared_ptr<Face> face(new Face());\n    face->edge = vertex->nextEdge;\n    std::shared_ptr<FaceNode> rightFaceNode(new FaceNode(vertex->point, vertex->distance, face));\n    face->nodes.push_back(rightFaceNode);\n    vertex->rightFaceNode = rightFaceNode;\n\n    // create face on left site of next vertex\n    std::shared_ptr<FaceNode> leftFaceNode(new FaceNode(next->point, next->distance, face));\n    addPush(rightFaceNode, leftFaceNode);\n    next->leftFaceNode = leftFaceNode;\n\n    faces.push_back(face);\n  }\n}\n\nstatic bool edgeBehindBisector(std::shared_ptr<Ray2d> bisector, const LineLinear2d& edge) {\n  /*\n  * Simple intersection test between the bisector starting at V and the\n  * whole line containing the currently tested line segment ei rejects\n  * the line segments laying \"behind\" the vertex V\n  */\n  return (!bisector->collide(edge, EPSILON));\n}\n\nstatic std::shared_ptr<Edge> chooseLessParallelVertexEdge(std::shared_ptr<Vertex> vertex, std::shared_ptr<Edge> edge) {\n  std::shared_ptr<Edge> edgeA = vertex->previousEdge;\n  std::shared_ptr<Edge> edgeB = vertex->nextEdge;\n\n  std::shared_ptr<Edge> vertexEdge = edgeA;\n\n  double edgeADot = std::abs(edge->normalize().dot(edgeA->normalize()));\n  double edgeBDot = std::abs(edge->normalize().dot(edgeB->normalize()));\n\n  if (edgeADot + edgeBDot >= 2 - EPSILON) {\n    // both lines are parallel to given edge\n    return nullptr;\n  }\n\n  if (edgeADot > edgeBDot) {\n    /*\n    * Simple check should be performed to exclude the case when one of\n    * the line segments starting at V (vertex) is parallel to e_i\n    * (edge) we always chose edge which is less parallel.\n    */\n    vertexEdge = edgeB;\n  }\n\n  return vertexEdge;\n}\n\n// see http://en.wikipedia.org/wiki/Vector_projection\nstatic Vector3d orthogonalProjection(const Vector3d& unitVector, const Vector3d& vectorToProject) {\n  Vector3d n = Vector3d(unitVector);\n  n.normalize();\n\n  double px = vectorToProject.x();\n  double py = vectorToProject.y();\n  double pz = vectorToProject.z();\n\n  double ax = n.x();\n  double ay = n.y();\n  double az = n.z();\n\n  double vx = px * ax * ax + py * ax * ay + pz * ax * az;\n  double vy = px * ax * ay + py * ay * ay + pz * ay * az;\n  double vz = px * ax * az + py * ay * az + pz * az * az;\n\n  return Vector3d(vx, vy, vz);\n}\n\nstatic double calcDistance(const Point3d& intersect, std::shared_ptr<Edge> currentEdge) {\n  // TODO: Can be replaced by getDistancePointToLineSegment() ?\n  Vector3d edge = currentEdge->end - currentEdge->begin;\n  Vector3d vector = intersect - currentEdge->begin;\n\n  Vector3d pointOnVector = orthogonalProjection(edge, vector);\n\n  return getDistance(Point3d(vector.x(), vector.y(), vector.z()), Point3d(pointOnVector.x(), pointOnVector.y(), pointOnVector.z()));\n}\n\nstatic boost::optional<SplitCandidate> calcCandidatePointForSplit(std::shared_ptr<Vertex> vertex, std::shared_ptr<Edge> edge) {\n\n  std::shared_ptr<Edge> vertexEdge = chooseLessParallelVertexEdge(vertex, edge);\n  if (!vertexEdge) {\n    return boost::none;\n  }\n\n  Vector3d vertexEdgeNormNegate = vertexEdge->normalize();\n  Vector3d edgeNorm = edge->normalize();\n  Vector3d edgesBisector = calcVectorBisector(vertexEdgeNormNegate, edgeNorm);\n\n  LineLinear2d llv = LineLinear2d(vertexEdge->begin, vertexEdge->end);\n  LineLinear2d lle = LineLinear2d(edge->begin, edge->end);\n\n  boost::optional<Point3d> edgesCollide = llv.collide(lle);\n\n  if (!edgesCollide) {\n    /*\n    * Check should be performed to exclude the case when one of the\n    * line segments starting at V is parallel to ei.\n    */\n    return boost::none;\n  }\n\n  LineLinear2d edgesBisectorLine = Ray2d(edgesCollide.get(), edgesBisector).getLinearForm();\n\n  /*\n  * Compute the coordinates of the candidate point Bi as the intersection\n  * between the bisector at V and the axis of the angle between one of\n  * the edges starting at V and the tested line segment ei\n  */\n  boost::optional<Point3d> candidatePoint = vertex->bisector->collide(edgesBisectorLine, EPSILON);\n\n  if (!candidatePoint) {\n    return boost::none;\n  }\n\n  if (edge->bisectorPrevious->isOnRightSide(candidatePoint.get(), EPSILON) && edge->bisectorNext->isOnLeftSide(candidatePoint.get(), EPSILON)) {\n\n    double distance = calcDistance(candidatePoint.get(), edge);\n\n    if (edge->bisectorPrevious->isOnLeftSide(candidatePoint.get(), EPSILON) || edge->bisectorNext->isOnRightSide(candidatePoint.get(), EPSILON)) {\n\n      Point3d oppositePoint = edge->begin;\n      return SplitCandidate(candidatePoint.get(), distance, nullptr, oppositePoint);\n    }\n\n    return SplitCandidate(candidatePoint.get(), distance, edge, boost::none);\n  }\n\n  return boost::none;\n}\n\nstatic std::vector<SplitCandidate> calcOppositeEdges(std::shared_ptr<Vertex> vertex, const std::vector<std::shared_ptr<Edge>>& edges) {\n\n  std::vector<SplitCandidate> ret;\n\n  for (std::shared_ptr<Edge> edgeEntry : edges) {\n\n    LineLinear2d edge = LineLinear2d(edgeEntry->begin, edgeEntry->end);\n\n    // check if edge is behind bisector\n    if (edgeBehindBisector(vertex->bisector, edge)) {\n      continue;\n    }\n    // compute the coordinates of the candidate point Bi\n    boost::optional<SplitCandidate> candidatePoint = calcCandidatePointForSplit(vertex, edgeEntry);\n\n    if (candidatePoint) {\n      ret.push_back(candidatePoint.get());\n    }\n  }\n\n  if (ret.size() > 1) {\n    std::sort(ret.begin(), ret.end());\n  }\n\n  return ret;\n}\n\nstatic void computeSplitEvents(std::shared_ptr<Vertex> vertex, const std::vector<std::shared_ptr<Edge>>& edges,\n                               std::vector<std::shared_ptr<QueueEvent>>& queue, boost::optional<double> distanceSquared) {\n  Point3d source = vertex->point;\n\n  std::vector<SplitCandidate> oppositeEdges = calcOppositeEdges(vertex, edges);\n\n  // check if it is vertex split event\n  for (SplitCandidate oppositeEdge : oppositeEdges) {\n\n    if (distanceSquared) {\n      if (getDistanceSquared(source, oppositeEdge.point) > distanceSquared.get() + EPSILON) {\n        /*\n        * Current split event distance from source of event is\n        * greater then for edge event. Split event can be reject.\n        * Distance from source is not the same as distance for\n        * edge. Two events can have the same distance to edge but\n        * they will be in different distance form its source.\n        * Unnecessary events should be reject otherwise they cause\n        * problems for degenerate cases.\n        */\n        continue;\n      }\n    }\n\n    // check if it is vertex split event\n    if (oppositeEdge.oppositePoint) {\n      // some of vertex event can share the same opposite\n      // point\n      std::shared_ptr<QueueEvent> e1(new QueueEvent(oppositeEdge.point, oppositeEdge.distance, vertex));  // SplitEvent\n      QueueEvent::insert_sorted(queue, e1);\n      continue;\n    }\n\n    std::shared_ptr<QueueEvent> e2(new QueueEvent(oppositeEdge.point, oppositeEdge.distance, vertex, oppositeEdge.oppositeEdge));  // SplitVertexEvent\n    QueueEvent::insert_sorted(queue, e2);\n    continue;\n  }\n}\n\nstatic boost::optional<Point3d> computeIntersectionBisectors(std::shared_ptr<Vertex> vertexPrevious, std::shared_ptr<Vertex> vertexNext) {\n  boost::optional<Point3d> ret;\n\n  std::shared_ptr<Ray2d> bisectorPrevious = vertexPrevious->bisector;\n  std::shared_ptr<Ray2d> bisectorNext = vertexNext->bisector;\n\n  boost::optional<Point3d> thisIntersect = bisectorPrevious->intersectRay2d(bisectorNext);\n\n  if (!thisIntersect) {\n    return ret;\n  }\n\n  if (vertexPrevious->point == thisIntersect.get() || vertexNext->point == thisIntersect.get()) {\n    // skip the same points\n    return ret;\n  }\n\n  ret = thisIntersect.get();\n  return ret;\n}\n\nstatic std::shared_ptr<QueueEvent> createEdgeEvent(const Point3d& point, std::shared_ptr<Vertex> previousVertex, std::shared_ptr<Vertex> nextVertex) {\n  std::shared_ptr<QueueEvent> e(new QueueEvent(point, calcDistance(point, previousVertex->nextEdge), previousVertex, nextVertex));  // EdgeEvent\n  return e;\n}\n\nstatic void computeEdgeEvents(std::shared_ptr<Vertex> previousVertex, std::shared_ptr<Vertex> nextVertex,\n                              std::vector<std::shared_ptr<QueueEvent>>& queue) {\n  boost::optional<Point3d> point = computeIntersectionBisectors(previousVertex, nextVertex);\n  if (point) {\n    std::shared_ptr<QueueEvent> e(createEdgeEvent(point.get(), previousVertex, nextVertex));\n    QueueEvent::insert_sorted(queue, e);\n  }\n}\n\nstatic void initEvents(std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav, std::vector<std::shared_ptr<QueueEvent>>& queue,\n                       const std::vector<std::shared_ptr<Edge>>& edges) {\n  for (std::vector<std::shared_ptr<Vertex>>& lav : sLav) {\n    for (std::shared_ptr<Vertex> vertex : lav) {\n      computeSplitEvents(vertex, edges, queue, boost::none);\n    }\n  }\n\n  for (std::vector<std::shared_ptr<Vertex>>& lav : sLav) {\n    for (std::shared_ptr<Vertex> vertex : lav) {\n      std::shared_ptr<Vertex> next = Vertex::next(vertex, lav);\n      computeEdgeEvents(vertex, next, queue);\n    }\n  }\n}\n\n// Calculate area of polygon outline. For clockwise area will be less than\n// zero, for counter-clockwise polygon area will be greater than zero.\nstatic double area(const std::vector<Point3d>& polygon) {\n  int n = polygon.size();\n  double a = 0.0;\n  for (int p = n - 1, q = 0; q < n; p = q++) {\n    Point3d pp = polygon[p];\n    Point3d pq = polygon[q];\n    a += pp.x() * pq.y() - pq.x() * pp.y();\n  }\n  return a * 0.5;\n}\n\n// Check if polygon is clockwise.\nstatic bool isClockwisePolygon(const std::vector<Point3d>& polygon) {\n  return (area(polygon) < 0);\n}\n\n// Updates points ordered as counter clockwise.\nstatic void makeCounterClockwise(std::vector<Point3d>& polygon) {\n  if (isClockwisePolygon(polygon)) {\n    polygon = reverse(polygon);\n  }\n}\n\nstatic void setZcoordsToZero(std::vector<Point3d>& polygon) {\n  for (Point3d& p : polygon) {\n    p += Vector3d(0, 0, -p.z());\n  }\n}\n\nstatic double initPolygon(std::vector<Point3d>& polygon) {\n  if (polygon.size() < 3) {\n    LOG_AND_THROW(\"Polygon must have at least 3 points.\");\n  } else if (polygon[0] == polygon[polygon.size() - 1]) {\n    LOG_AND_THROW(\"Polygon can't start and end with the same point.\");\n  }\n\n  for (unsigned i = 1; i < polygon.size(); i++) {\n    if (polygon[i].z() != polygon[0].z()) {\n      LOG_AND_THROW(\"All polygon z coordinates must be the same.\");\n    }\n  }\n\n  double zcoord = polygon[0].z();\n  setZcoordsToZero(polygon);\n\n  return zcoord;\n}\n\nstatic int assertMaxNumberOfIterations(int count) {\n  count++;\n  if (count > 10000) {\n    LOG_AND_THROW(\"Maximum number of iterations reached. Bug?\");\n  }\n  return count;\n}\n\nstatic std::vector<std::shared_ptr<QueueEvent>> loadLevelEvents(std::vector<std::shared_ptr<QueueEvent>>& queue) {\n  /*\n  * Loads all non obsolete events which are on one level.\n  */\n\n  std::vector<std::shared_ptr<QueueEvent>> level;\n\n  std::shared_ptr<QueueEvent> levelStart = nullptr;\n  while (queue.size() > 0) {\n    levelStart = queue[0];\n    queue.erase(queue.begin());\n    // skip all obsolete events in level\n    if (!levelStart->isObsolete()) {\n      break;\n    }\n  }\n\n  if (!levelStart || levelStart->isObsolete()) {\n    // all events obsolete\n    return level;\n  }\n\n  double levelStartHeight = levelStart->distance;\n\n  level.push_back(levelStart);\n\n  std::shared_ptr<QueueEvent> event = nullptr;\n\n  while (queue.size() > 0) {\n    event = queue[0];\n    if (event->distance - levelStartHeight >= EPSILON) {\n      break;\n    }\n    queue.erase(queue.begin());\n    if (!event->isObsolete()) {\n      level.push_back(event);\n    }\n  }\n\n  return level;\n}\n\nstatic std::vector<std::shared_ptr<QueueEvent>> createEdgeChain(std::vector<std::shared_ptr<QueueEvent>>& edgeCluster) {\n  std::vector<std::shared_ptr<QueueEvent>> edgeList;\n\n  edgeList.push_back(edgeCluster[0]);\n  edgeCluster.erase(edgeCluster.begin());\n\n  // find all successors of edge event\n  // find all predecessors of edge event\n\n  do {\n    std::shared_ptr<Vertex> beginVertex = edgeList[0]->previousVertex;\n    std::shared_ptr<Vertex> endVertex = edgeList[edgeList.size() - 1]->nextVertex;\n\n    bool do_continue = false;\n    for (unsigned i = 0; i < edgeCluster.size(); i++) {\n      if (edgeCluster[i]->previousVertex == endVertex) {\n        // edge should be added as last in chain\n        edgeList.push_back(edgeCluster[i]);\n        edgeCluster.erase(edgeCluster.begin() + i);\n        do_continue = true;\n        break;\n      } else if (edgeCluster[i]->nextVertex == beginVertex) {\n        // edge should be added as first in chain\n        edgeList.insert(edgeList.begin(), edgeCluster[i]);\n        edgeCluster.erase(edgeCluster.begin() + i);\n        do_continue = true;\n        break;\n      }\n    }\n\n    if (do_continue) {\n      continue;\n    }\n\n    break;\n\n  } while (true);\n\n  return edgeList;\n}\n\nstatic bool isInEdgeChain(std::shared_ptr<QueueEvent> split, const Chain& chain) {\n  for (std::shared_ptr<QueueEvent> edgeEvent : chain.edgeList) {\n    if (edgeEvent->previousVertex == split->parent || edgeEvent->nextVertex == split->parent) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nstatic std::vector<Chain> createChains(const std::vector<std::shared_ptr<QueueEvent>>& cluster,\n                                       std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) {\n  /*\n  * Create chains of events from cluster. Cluster is set of events which meet\n  * in the same result point. Try to connect all events which share the same\n  * vertex into chain. Events in a chain are sorted. If events don't share a\n  * vertex, returned chains contains only one event.\n  */\n\n  std::vector<std::shared_ptr<QueueEvent>> edgeCluster;\n  std::vector<std::shared_ptr<QueueEvent>> splitCluster;\n  std::vector<std::shared_ptr<Vertex>> vertexEventsParents;\n\n  for (std::shared_ptr<QueueEvent> event : cluster) {\n    if (event->eventType == QueueEvent::TYPE_EDGE) {\n      edgeCluster.push_back(event);\n    } else {\n      if (event->eventType == QueueEvent::TYPE_SPLIT_VERTEX) {\n        /*\n        * It will be processed in the next loop to find unique split\n        * events for one parent.\n        */\n        continue;\n      } else if (event->eventType == QueueEvent::TYPE_SPLIT) {\n        vertexEventsParents.push_back(event->parent);\n        splitCluster.push_back(event);\n      }\n    }\n  }\n\n  for (std::shared_ptr<QueueEvent> event : cluster) {\n    if (event->eventType == QueueEvent::TYPE_SPLIT_VERTEX) {\n      bool found = std::find(vertexEventsParents.begin(), vertexEventsParents.end(), event->parent) != vertexEventsParents.end();\n      if (!found) {\n        /*\n        * Multiple vertex events can be created for one parent.\n        * It is caused by two edges that share one vertex and new\n        * event will be added for both of them. When processing we\n        * always need to group them into one per vertex. Always prefer\n        * split events over vertex events.\n        */\n        vertexEventsParents.push_back(event->parent);\n        splitCluster.push_back(event);\n      }\n    }\n  }\n\n  std::vector<Chain> edgeChains;\n\n  while (edgeCluster.size() > 0) {\n    /*\n    * We need to find all connected edge events, and create chains from\n    * them. Two events are assumed to be connected if next parent of one\n    * event is equal to previous parent of second event.\n    */\n    std::vector<std::shared_ptr<QueueEvent>> edgeList = createEdgeChain(edgeCluster);\n    Chain edgeChain = Chain(edgeList, sLav);\n    edgeChains.push_back(edgeChain);  // EdgeChain\n  }\n\n  std::vector<Chain> chains;\n  for (Chain& edgeChain : edgeChains) {\n    chains.push_back(edgeChain);\n  }\n\n  while (splitCluster.size() > 0) {\n    std::shared_ptr<QueueEvent> split = splitCluster[0];\n    splitCluster.erase(splitCluster.begin());\n\n    bool inEdgeChain = false;\n    for (Chain& chain : edgeChains) {\n      // check if chain is split type\n      if (isInEdgeChain(split, chain)) {\n        // if we have edge chain it can't share split event\n        inEdgeChain = true;\n        break;\n      }\n    }\n\n    if (inEdgeChain) {\n      continue;\n    }\n\n    /*\n    * split event is not part of any edge chain, it should be added as\n    * new single element chain;\n    */\n    chains.push_back(Chain(split));  // SplitChain\n  }\n\n  /*\n  * Return list of chains with type. Possible types are edge chain,\n  * closed edge chain, split chain. Closed edge chain will produce pick\n  * event. Always it can exist only one closed edge chain for point\n  * cluster.\n  */\n\n  return chains;\n}\n\nstatic LevelEvent createLevelEvent(Point3d& eventCenter, double distance, const std::vector<std::shared_ptr<QueueEvent>>& eventCluster,\n                                   std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) {\n\n  std::vector<Chain> chains = createChains(eventCluster, sLav);\n\n  if (chains.size() == 1) {\n    if (chains[0].getChainMode() == Chain::MODE_CLOSED_EDGE) {\n      return LevelEvent(eventCenter, distance, chains[0], true);  // PickEvent\n    } else if (chains[0].getChainMode() == Chain::MODE_EDGE) {\n      return LevelEvent(eventCenter, distance, chains[0], false);  // MultiEdgeEvent\n    } else if (chains[0].getChainMode() == Chain::MODE_SPLIT) {\n      return LevelEvent(eventCenter, distance, chains);  // MultiSplitEvent\n    }\n  }\n\n  for (Chain chain : chains) {\n    if (chain.getChainMode() == Chain::MODE_CLOSED_EDGE) {\n      LOG_AND_THROW(\"found closed chain of events for single point, but found more then one chain\");\n    }\n  }\n\n  return LevelEvent(eventCenter, distance, chains);  // MultiSplitEvent\n}\n\nstatic std::vector<LevelEvent> groupLevelEvents(std::vector<std::shared_ptr<QueueEvent>>& levelEvents,\n                                                std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) {\n  std::vector<LevelEvent> ret;\n  std::vector<std::shared_ptr<Vertex>> parentGroup;\n\n  while (levelEvents.size() > 0) {\n    parentGroup.clear();\n\n    Point3d eventCenter = levelEvents[0]->point;\n    double distance = levelEvents[0]->distance;\n\n    levelEvents[0]->addEventToGroup(parentGroup);\n\n    std::vector<std::shared_ptr<QueueEvent>> cluster;\n    cluster.push_back(levelEvents[0]);\n\n    levelEvents.erase(levelEvents.begin());\n\n    for (unsigned j = 0; j < levelEvents.size(); j++) {\n\n      if (levelEvents[j]->isEventInGroup(parentGroup)) {\n        /* Because of numerical errors, split event and edge event\n        * can appear in slight different points. Epsilon can be\n        * applied to level but event point can move rapidly even for\n        * little changes in level. If two events for the same level\n        * share the same parent, they should be merge together.\n        */\n        cluster.push_back(levelEvents[j]);\n        levelEvents[j]->addEventToGroup(parentGroup);\n        levelEvents.erase(levelEvents.begin() + j);\n        j--;\n      } else if (getDistance(eventCenter, levelEvents[j]->point) < EPSILON) {\n        // group all events when the result points are near each other\n        cluster.push_back(levelEvents[j]);\n        levelEvents[j]->addEventToGroup(parentGroup);\n        levelEvents.erase(levelEvents.begin() + j);\n        j--;\n      }\n    }\n\n    // More than one event can share the same result point, we need to\n    // create new level event.\n    ret.push_back(createLevelEvent(eventCenter, distance, cluster, sLav));\n  }\n\n  return ret;\n}\n\nstatic std::vector<LevelEvent> loadAndGroupLevelEvents(std::vector<std::shared_ptr<QueueEvent>>& queue,\n                                                       std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) {\n  std::vector<std::shared_ptr<QueueEvent>> levelEvents = loadLevelEvents(queue);\n  return groupLevelEvents(levelEvents, sLav);\n}\n\nstatic std::shared_ptr<Vertex> getEdgeInLav(std::vector<std::shared_ptr<Vertex>>& lav, std::shared_ptr<Edge> oppositeEdge) {\n  for (std::shared_ptr<Vertex> vertex : lav) {\n    if (vertex->previousEdge && oppositeEdge == vertex->previousEdge) {\n      return vertex;\n    } else {\n      std::shared_ptr<Vertex> previous = Vertex::previous(vertex, lav);\n      if (previous->nextEdge && oppositeEdge == previous->nextEdge) {\n        return vertex;\n      }\n    }\n  }\n  return nullptr;\n}\n\n/// Test if point is inside polygon\nstatic bool isInsidePolygon(const Point3d& point, const std::vector<Point3d>& points) {\n  /*\n  * see http://en.wikipedia.org/wiki/Point_in_polygon\n  * see http://en.wikipedia.org/wiki/Even-odd_rule\n  * see http://paulbourke.net/geometry/insidepoly/\n  */\n\n  int numpoints = points.size();\n\n  if (numpoints < 3) {\n    return false;\n  }\n\n  int it = 0;\n\n  Point3d first = points[it];\n\n  bool oddNodes = false;\n\n  Point3d node1;\n  Point3d node2;\n\n  for (int i = 0; i < numpoints; i++) {\n    node1 = points[it];\n    it++;\n    if (i == numpoints - 1) {\n      node2 = first;\n    } else {\n      node2 = points[it];\n    }\n\n    double x = point.x();\n    double y = point.y();\n\n    if ((node1.y() < y && node2.y() >= y) || (node2.y() < y && node1.y() >= y)) {\n      if (node1.x() + (y - node1.y()) / (node2.y() - node1.y()) * (node2.x() - node1.x()) < x) {\n        oddNodes = !oddNodes;\n      }\n    }\n  }\n\n  return oddNodes;\n}\n\nstatic int chooseOppositeEdgeLavIndex(std::vector<std::shared_ptr<Vertex>>& edgeLavs, std::shared_ptr<Edge> oppositeEdge, const Point3d& center,\n                                      std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) {\n  if (edgeLavs.size() == 0) {\n    return -1;\n  } else if (edgeLavs.size() == 1) {\n    return 0;\n  }\n\n  const Point3d& edgeStart = oppositeEdge->begin;\n  Vector3d edgeNorm = oppositeEdge->normalize();\n  Vector3d centerVector = center - edgeStart;\n  double centerDot = edgeNorm.dot(centerVector);\n\n  for (unsigned i = 0; i < edgeLavs.size(); i++) {\n    std::shared_ptr<Vertex> end = edgeLavs[i];\n    std::shared_ptr<Vertex> begin = Vertex::previous(end, sLav);\n    Vector3d beginVector = begin->point - edgeStart;\n    Vector3d endVector = end->point - edgeStart;\n\n    double beginDot = edgeNorm.dot(beginVector);\n    double endDot = edgeNorm.dot(endVector);\n\n    /*\n    * Make projection of center, begin and end into edge. Begin and end\n    * are vertices chosen by opposite edge (then point to opposite edge).\n    * Chose lav only when center is between begin and end. Only one lav\n    * should meet criteria.\n    */\n\n    if ((beginDot < centerDot && centerDot < endDot) || (beginDot > centerDot && centerDot > endDot)) {\n      return i;\n    }\n  }\n\n  // Additional check if center is inside lav\n  for (unsigned i = 0; i < edgeLavs.size(); i++) {\n    std::shared_ptr<Vertex> end = edgeLavs[i];\n    int index = Vertex::getLavIndex(end, sLav);\n    unsigned size = sLav[index].size();\n    std::vector<Point3d> points;\n    std::shared_ptr<Vertex> next = end;\n    for (unsigned j = 0; j < size; j++) {\n      points.push_back(next->point);\n      next = Vertex::next(next, sLav[index]);\n    }\n    if (isInsidePolygon(center, points)) {\n      return i;\n    }\n  }\n\n  LOG_AND_THROW(\"could not find lav for opposite edge, it could be correct but need some test data to check.\")\n}\n\nstatic std::shared_ptr<Vertex> findOppositeEdgeLav(std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav, std::shared_ptr<Edge> oppositeEdge,\n                                                   const Point3d& center) {\n  std::vector<std::shared_ptr<Vertex>> edgeLavs;\n  for (std::vector<std::shared_ptr<Vertex>>& lav : sLav) {\n    std::shared_ptr<Vertex> vertexInLav = getEdgeInLav(lav, oppositeEdge);\n    if (vertexInLav) {\n      edgeLavs.push_back(vertexInLav);\n    }\n  }\n  int lavIndex = chooseOppositeEdgeLavIndex(edgeLavs, oppositeEdge, center, sLav);\n  if (lavIndex > -1) {\n    return edgeLavs[lavIndex];\n  }\n  return nullptr;\n}\n\nstatic void createOppositeEdgeChains(std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav, std::vector<Chain>& chains, Point3d& center) {\n  /*\n  * Add chain created from opposite edge, this chain have to be\n  * calculated during processing event because lav could change during\n  * processing another events on the same level\n  */\n  std::vector<std::shared_ptr<Edge>> oppositeEdges;\n\n  std::vector<Chain> oppositeEdgeChains;\n  std::vector<Chain> chainsForRemoval;\n\n  for (Chain& chain : chains) {\n    // add opposite edges as chain parts\n    if (chain.chainType == Chain::TYPE_SPLIT) {\n      std::shared_ptr<Edge> oppositeEdge = chain.getOppositeEdge();\n\n      bool hasOppositeEdge = false;\n      if (oppositeEdge) {\n        hasOppositeEdge = std::find(oppositeEdges.begin(), oppositeEdges.end(), oppositeEdge) != oppositeEdges.end();\n      }\n      if (oppositeEdge && !hasOppositeEdge) {\n        // find lav vertex for opposite edge\n\n        Point3d c = Point3d(center);\n        std::shared_ptr<Vertex> nextVertex = findOppositeEdgeLav(sLav, oppositeEdge, c);\n        if (nextVertex) {\n          oppositeEdgeChains.push_back(Chain(oppositeEdge, nextVertex, sLav));  // SingleEdgeChain\n        } else {\n          findOppositeEdgeLav(sLav, oppositeEdge, center);\n          chainsForRemoval.push_back(chain);\n        }\n        oppositeEdges.push_back(oppositeEdge);\n      }\n\n    } else if (chain.chainType == Chain::TYPE_EDGE) {\n      if (chain.getChainMode() == Chain::MODE_SPLIT) {\n        std::shared_ptr<Edge> oppositeEdge = chain.getOppositeEdge();\n        if (oppositeEdge) {\n          // never happen?\n          // find lav vertex for opposite edge\n          oppositeEdges.push_back(oppositeEdge);\n        }\n      }\n    }\n  }\n\n  /*\n  * if opposite edge can't be found in active lavs then split chain with\n  * that edge should be removed\n  */\n  for (Chain& chain : chainsForRemoval) {\n    auto it = std::find(chains.begin(), chains.end(), chain);\n    if (it == chains.end()) {\n      LOG_AND_THROW(\"Could not find chain for removal.\");\n    }\n    chains.erase(it);\n  }\n\n  for (Chain& chain : oppositeEdgeChains) {\n    chains.push_back(chain);\n  }\n}\n\nstatic std::shared_ptr<Vertex> createMultiSplitVertex(std::shared_ptr<Edge> nextEdge, std::shared_ptr<Edge> previousEdge, Point3d& center,\n                                                      double distance) {\n  std::shared_ptr<Ray2d> bisector(new Ray2d(calcBisector(center, previousEdge, nextEdge)));\n\n  // edges are mirrored for event\n  std::shared_ptr<Vertex> vertex(new Vertex(center, distance, bisector, previousEdge, nextEdge));\n  return vertex;\n}\n\nstatic void correctBisectorDirection(std::shared_ptr<Ray2d> bisector, std::shared_ptr<Vertex> beginNextVertex,\n                                     std::shared_ptr<Vertex> endPreviousVertex, std::shared_ptr<Edge> beginEdge, std::shared_ptr<Edge> endEdge) {\n  /*\n  * New bisector for vertex is created using connected edges. For\n  * parallel edges numerical error may appear and direction of created\n  * bisector is wrong. For parallel edges direction of edge need to be\n  * corrected using location of vertex.\n  */\n\n  std::shared_ptr<Edge> beginEdge2 = beginNextVertex->previousEdge;\n  std::shared_ptr<Edge> endEdge2 = endPreviousVertex->nextEdge;\n\n  if (beginEdge != beginEdge2 || endEdge != endEdge2) {\n    LOG_AND_THROW(\"Unexpected situation\");\n  }\n\n  /*\n  * Check if edges are parallel and in opposite direction to each other.\n  */\n  if (beginEdge->normalize().dot(endEdge->normalize()) < -0.97) {\n    Point3d epvp = endPreviousVertex->point;\n    Point3d bp = bisector->point;\n    Point3d bnvp = beginNextVertex->point;\n    Vector3d n1 = Vector3d(bp.x(), bp.y(), bp.z()) - Vector3d(epvp.x(), epvp.y(), epvp.z());\n    Vector3d n2 = Vector3d(bnvp.x(), bnvp.y(), bnvp.z()) - Vector3d(bp.x(), bp.y(), bp.z());\n    n1.normalize();\n    n2.normalize();\n    Vector3d bisectorPrediction = calcVectorBisector(n1, n2);\n\n    if (bisector->vector.dot(bisectorPrediction) < 0) {\n      /*\n      * Bisector is calculated in opposite direction to edges and\n      * center.\n      */\n      bisector->vector = bisector->vector.reverseVector();\n    }\n  }\n}\n\nstatic bool areSameLav(std::vector<std::shared_ptr<Vertex>>& lav1, std::vector<std::shared_ptr<Vertex>>& lav2) {\n  if (lav1.size() != lav2.size()) {\n    return false;\n  }\n  for (unsigned i = 0; i < lav1.size(); i++) {\n    if (lav1[i] != lav2[i]) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/// Add all vertex from \"merged\" lav into \"base\" lav. Vertex are added before\n/// base vertex. Merged vertex order is reversed.\nstatic void mergeBeforeBaseVertex(std::shared_ptr<Vertex> base, std::vector<std::shared_ptr<Vertex>>& baseList, std::shared_ptr<Vertex> merged,\n                                  std::vector<std::shared_ptr<Vertex>>& mergedList) {\n  int size = mergedList.size();\n\n  for (int i = 0; i < size; i++) {\n    std::shared_ptr<Vertex> nextMerged = Vertex::next(merged, mergedList);\n    auto it = std::find(baseList.begin(), baseList.end(), base);\n    baseList.insert(it, nextMerged);\n  }\n\n  mergedList.erase(mergedList.begin(), mergedList.end());\n}\n\nstatic boost::optional<double> computeCloserEdgeEvent(std::shared_ptr<Vertex> vertex, std::vector<std::shared_ptr<QueueEvent>>& queue,\n                                                      std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) {\n  /*\n  * Calculate two new edge events for given vertex. Events are generated\n  * using current, previous and next vertex in current lav. When two edge\n  * events are generated distance from source is check. To queue is added\n  * only closer event or both if they have the same distance.\n  */\n\n  std::shared_ptr<Vertex> nextVertex = Vertex::next(vertex, sLav);\n  std::shared_ptr<Vertex> previousVertex = Vertex::previous(vertex, sLav);\n\n  /*\n  * We need to chose closer edge event. When two evens appear in epsilon\n  * we take both. They will create single MultiEdgeEvent.\n  */\n\n  boost::optional<Point3d> point1 = computeIntersectionBisectors(vertex, nextVertex);\n  boost::optional<Point3d> point2 = computeIntersectionBisectors(previousVertex, vertex);\n\n  if (!point1 && !point2) {\n    return boost::none;\n  }\n\n  double distance1 = std::numeric_limits<double>::max();\n  double distance2 = std::numeric_limits<double>::max();\n\n  if (point1) {\n    distance1 = getDistanceSquared(vertex->point, point1.get());\n  }\n  if (point2) {\n    distance2 = getDistanceSquared(vertex->point, point2.get());\n  }\n\n  if (distance1 - EPSILON < distance2) {\n    std::shared_ptr<QueueEvent> e(createEdgeEvent(point1.get(), vertex, nextVertex));\n    QueueEvent::insert_sorted(queue, e);\n  }\n  if (distance2 - EPSILON < distance1) {\n    std::shared_ptr<QueueEvent> e(createEdgeEvent(point2.get(), previousVertex, vertex));\n    QueueEvent::insert_sorted(queue, e);\n  }\n\n  if (distance1 < distance2) {\n    return distance1;\n  }\n  return distance2;\n}\n\nstatic void computeEvents(std::shared_ptr<Vertex> vertex, std::vector<std::shared_ptr<QueueEvent>>& queue,\n                          const std::vector<std::shared_ptr<Edge>>& edges, std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) {\n  boost::optional<double> distanceSquared = computeCloserEdgeEvent(vertex, queue, sLav);\n  computeSplitEvents(vertex, edges, queue, distanceSquared);\n}\n\nstatic std::shared_ptr<Vertex> createOppositeEdgeVertex(std::shared_ptr<Vertex> newVertex) {\n  /*\n  * When opposite edge is processed we need to create copy of vertex to\n  * use in opposite face. When opposite edge chain occur vertex is shared\n  * by additional output face.\n  */\n\n  std::shared_ptr<Vertex> vertex(\n    new Vertex(newVertex->point, newVertex->distance, newVertex->bisector, newVertex->previousEdge, newVertex->nextEdge));\n\n  std::shared_ptr<Face> oppFace(new Face());\n\n  // create new empty node queue\n  std::shared_ptr<FaceNode> fn(new FaceNode(vertex->point, vertex->distance, oppFace));\n  vertex->leftFaceNode = fn;\n  vertex->rightFaceNode = fn;\n\n  // add one node for queue to present opposite side of edge split event\n  oppFace->nodes.push_back(fn);\n\n  return vertex;\n}\n\nstatic void addFaceLeft(std::shared_ptr<Vertex> newVertex, std::shared_ptr<Vertex> va, std::vector<std::shared_ptr<Face>>& faces) {\n  std::shared_ptr<Face> face = va->leftFaceNode->face;\n  std::shared_ptr<FaceNode> fn(new FaceNode(newVertex->point, newVertex->distance, face));\n  addPush(va->leftFaceNode, fn);\n  newVertex->leftFaceNode = fn;\n}\n\nstatic void addFaceRight(std::shared_ptr<Vertex> newVertex, std::shared_ptr<Vertex> vb, std::vector<std::shared_ptr<Face>>& faces) {\n  std::shared_ptr<Face> face = vb->rightFaceNode->face;\n  std::shared_ptr<FaceNode> fn(new FaceNode(newVertex->point, newVertex->distance, face));\n  addPush(vb->rightFaceNode, fn);\n  newVertex->rightFaceNode = fn;\n}\n\nstatic std::shared_ptr<FaceNode> addSplitFaces(std::shared_ptr<FaceNode> lastFaceNode, const Chain& chainBegin, const Chain& chainEnd,\n                                               std::shared_ptr<Vertex> newVertex, std::vector<std::shared_ptr<Face>>& faces,\n                                               std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) {\n  if (chainBegin.chainType == Chain::TYPE_SINGLE_EDGE) {\n    /*\n    * When chain is generated by opposite edge we need to share face\n    * between two chains. Number of that chains shares is always odd.\n    */\n    // TODO: Unread variable!\n    // cppcheck-suppress unreadVariable\n    std::shared_ptr<Vertex> beginVertex = chainBegin.getNextVertex(sLav);\n\n    // right face\n    if (lastFaceNode) {\n      // face queue exist simply assign it to new node\n      newVertex->rightFaceNode = lastFaceNode;\n      lastFaceNode = nullptr;\n    } else {\n      /*\n      * Vertex generated by opposite edge share three faces, but\n      * vertex can store only left and right face. So we need to\n      * create vertex clone to store additional back face.\n      */\n      beginVertex = createOppositeEdgeVertex(newVertex);\n\n      /* same face in two vertex, original and in opposite edge clone */\n      newVertex->rightFaceNode = beginVertex->rightFaceNode;\n      lastFaceNode = beginVertex->leftFaceNode;\n    }\n\n  } else {\n    std::shared_ptr<Vertex> beginVertex = chainBegin.getCurrentVertex();\n\n    // right face\n    addFaceRight(newVertex, beginVertex, faces);\n  }\n\n  if (chainEnd.chainType == Chain::TYPE_SINGLE_EDGE) {\n    // TODO: Unread variable!\n    // cppcheck-suppress unreadVariable\n    std::shared_ptr<Vertex> endVertex = chainEnd.getPreviousVertex(sLav);\n\n    // left face\n    if (lastFaceNode) {\n      // face queue exist simply assign it to new node\n      newVertex->leftFaceNode = lastFaceNode;\n      lastFaceNode = nullptr;\n    } else {\n      /*\n      * Vertex generated by opposite edge share three faces, but\n      * vertex can store only left and right face. So we need to\n      * create vertex clone to store additional back face.\n      */\n      endVertex = createOppositeEdgeVertex(newVertex);\n\n      /* same face in two vertex, original and in opposite edge clone */\n      newVertex->leftFaceNode = endVertex->leftFaceNode;\n      lastFaceNode = endVertex->leftFaceNode;\n    }\n\n  } else {\n    std::shared_ptr<Vertex> endVertex = chainEnd.getCurrentVertex();\n\n    // left face\n    addFaceLeft(newVertex, endVertex, faces);\n  }\n\n  return lastFaceNode;\n}\n\n// Returns cut portion of lav from startVertex to endVertex, including both\nstatic std::vector<std::shared_ptr<Vertex>> cutLavPart(std::vector<std::shared_ptr<Vertex>>& lav, std::shared_ptr<Vertex> startVertex,\n                                                       std::shared_ptr<Vertex> endVertex) {\n  std::vector<std::shared_ptr<Vertex>> ret;\n\n  std::shared_ptr<Vertex> current = startVertex;\n  ret.push_back(current);\n\n  if (startVertex == endVertex) {\n    return ret;\n  }\n\n  while (true) {\n    current = Vertex::next(current, lav);\n    ret.push_back(current);\n    if (current == endVertex) {\n      break;\n    }\n    if (ret.size() > lav.size()) {\n      LOG_AND_THROW(\"End vertex not found in start vertex lav.\");\n    }\n  }\n\n  for (std::shared_ptr<Vertex> v : ret) {\n    Vertex::removeFromLav(v, lav);\n  }\n\n  return ret;\n}\n\nstatic void multiSplitEvent(LevelEvent& event, std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav,\n                            std::vector<std::shared_ptr<QueueEvent>>& queue, const std::vector<std::shared_ptr<Edge>>& edges,\n                            std::vector<std::shared_ptr<Face>>& faces) {\n\n  createOppositeEdgeChains(sLav, event.chains, event.point);\n\n  // sort list of chains clock wise\n  std::sort(event.chains.begin(), event.chains.end(), Chain::Comparer(event.point));\n\n  // face vertex for split event is shared between two chains\n  std::shared_ptr<FaceNode> lastFaceNode;\n\n  // connect all edges into new bisectors and lavs\n  int edgeListSize = event.chains.size();\n  for (int i = 0; i < edgeListSize; i++) {\n    Chain& chainBegin = event.chains[i];\n    Chain& chainEnd = event.chains[(i + 1) % edgeListSize];\n\n    Point3d p = Point3d(event.point);\n    std::shared_ptr<Vertex> newVertex(createMultiSplitVertex(chainBegin.getNextEdge(), chainEnd.getPreviousEdge(), p, event.distance));\n\n    // Split and merge lavs...\n    std::shared_ptr<Vertex> beginNextVertex = chainBegin.getNextVertex(sLav);\n    std::shared_ptr<Vertex> endPreviousVertex = chainEnd.getPreviousVertex(sLav);\n\n    correctBisectorDirection(newVertex->bisector, beginNextVertex, endPreviousVertex, chainBegin.getNextEdge(), chainEnd.getPreviousEdge());\n\n    std::vector<std::shared_ptr<Vertex>>& beginNextVertexLav = sLav[Vertex::getLavIndex(beginNextVertex, sLav)];\n    std::vector<std::shared_ptr<Vertex>>& endPreviousVertexLav = sLav[Vertex::getLavIndex(endPreviousVertex, sLav)];\n\n    if (areSameLav(beginNextVertexLav, endPreviousVertexLav)) {\n      /*\n      * if vertices are in same lav we need to cut part of lav in the\n      * middle of vertex and create new lav from that points\n      */\n\n      std::vector<std::shared_ptr<Vertex>> lavPart = cutLavPart(beginNextVertexLav, beginNextVertex, endPreviousVertex);\n\n      std::vector<std::shared_ptr<Vertex>> lav;\n      lav.push_back(newVertex);\n      for (std::shared_ptr<Vertex> vertex : lavPart) {\n        lav.push_back(vertex);\n      }\n      sLav.push_back(lav);\n\n    } else {\n      /*\n      * if vertices are in different lavs we need to merge them into\n      * one.\n      */\n      mergeBeforeBaseVertex(beginNextVertex, beginNextVertexLav, endPreviousVertex, endPreviousVertexLav);\n\n      int lavIndex = Vertex::getLavIndex(endPreviousVertex, sLav);\n      if (lavIndex == -1) {\n        LOG_AND_THROW(\"Could not find vertex in sLav.\")\n      }\n      auto it = std::find(sLav[lavIndex].begin(), sLav[lavIndex].end(), endPreviousVertex);\n      sLav[lavIndex].insert(it + 1, newVertex);\n    }\n\n    computeEvents(newVertex, queue, edges, sLav);\n\n    lastFaceNode = addSplitFaces(lastFaceNode, chainBegin, chainEnd, newVertex, faces, sLav);\n  }\n\n  // remove all centers of events from lav\n  edgeListSize = event.chains.size();\n  for (int i = 0; i < edgeListSize; i++) {\n    Chain& chainBegin = event.chains[i];\n    Chain& chainEnd = event.chains[(i + 1) % edgeListSize];\n\n    if (chainBegin.getCurrentVertex()) {\n      chainBegin.getCurrentVertex()->processed = true;\n      Vertex::removeFromLav(chainBegin.getCurrentVertex(), sLav);\n    }\n    if (chainEnd.getCurrentVertex()) {\n      chainEnd.getCurrentVertex()->processed = true;\n      Vertex::removeFromLav(chainEnd.getCurrentVertex(), sLav);\n    }\n  }\n}\n\nstatic void addFaceBack(std::shared_ptr<Vertex> newVertex, std::shared_ptr<Vertex> va, std::shared_ptr<Vertex> vb,\n                        std::vector<std::shared_ptr<Face>>& faces) {\n  std::shared_ptr<Face> face = va->rightFaceNode->face;\n  std::shared_ptr<FaceNode> fn(new FaceNode(newVertex->point, newVertex->distance, face));\n  addPush(va->rightFaceNode, fn);\n  connectFaces(fn, vb->leftFaceNode);\n}\n\nstatic void addMultiBackFaces(const std::vector<std::shared_ptr<QueueEvent>>& edgeList, std::shared_ptr<Vertex> edgeVertex,\n                              std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav, std::vector<std::shared_ptr<QueueEvent>>& queue,\n                              std::vector<std::shared_ptr<Face>>& faces) {\n  for (std::shared_ptr<QueueEvent> edgeEvent : edgeList) {\n\n    edgeEvent->previousVertex->processed = true;\n    Vertex::removeFromLav(edgeEvent->previousVertex, sLav);\n\n    edgeEvent->nextVertex->processed = true;\n    Vertex::removeFromLav(edgeEvent->nextVertex, sLav);\n\n    addFaceBack(edgeVertex, edgeEvent->previousVertex, edgeEvent->nextVertex, faces);\n  }\n}\n\nstatic void pickEvent(LevelEvent& event, std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav, std::vector<std::shared_ptr<QueueEvent>>& queue,\n                      std::vector<std::shared_ptr<Edge>>& edges, std::vector<std::shared_ptr<Face>>& faces) {\n  // lav will be removed so it is final vertex.\n  std::shared_ptr<Vertex> pickVertex(new Vertex(event.point, event.distance, nullptr, nullptr, nullptr));\n  pickVertex->processed = true;\n\n  addMultiBackFaces(event.chain.edgeList, pickVertex, sLav, queue, faces);\n}\n\nstatic void multiEdgeEvent(LevelEvent& event, std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav,\n                           std::vector<std::shared_ptr<QueueEvent>>& queue, const std::vector<std::shared_ptr<Edge>>& edges,\n                           std::vector<std::shared_ptr<Face>>& faces) {\n\n  std::shared_ptr<Vertex> prevVertex = event.chain.getPreviousVertex(sLav);\n  std::shared_ptr<Vertex> nextVertex = event.chain.getNextVertex(sLav);\n\n  prevVertex->processed = true;\n  nextVertex->processed = true;\n\n  std::shared_ptr<Ray2d> bisector(new Ray2d(calcBisector(event.point, prevVertex->previousEdge, nextVertex->nextEdge)));\n  Point3d p = Point3d(event.point);\n  std::shared_ptr<Vertex> edgeVertex(new Vertex(p, event.distance, bisector, prevVertex->previousEdge, nextVertex->nextEdge));\n\n  // left face\n  addFaceLeft(edgeVertex, event.chain.getPreviousVertex(sLav), faces);\n\n  // right face\n  addFaceRight(edgeVertex, event.chain.getNextVertex(sLav), faces);\n\n  int lavIndex = Vertex::getLavIndex(prevVertex, sLav);\n  auto it = std::find(sLav[lavIndex].begin(), sLav[lavIndex].end(), prevVertex);\n  auto pos = std::distance(sLav[lavIndex].begin(), it);\n  if (pos == 0) {\n    sLav[lavIndex].push_back(edgeVertex);\n  } else {\n    sLav[lavIndex].insert(it, edgeVertex);\n  }\n\n  // back faces\n  addMultiBackFaces(event.chain.edgeList, edgeVertex, sLav, queue, faces);\n\n  computeEvents(edgeVertex, queue, edges, sLav);\n}\n\nstatic void processTwoNodeLavs(std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav, std::vector<std::shared_ptr<QueueEvent>>& queue,\n                               std::vector<std::shared_ptr<Face>>& faces) {\n  for (std::vector<std::shared_ptr<Vertex>>& lav : sLav) {\n    if (lav.size() == 2) {\n      std::shared_ptr<Vertex> first = lav[0];\n      std::shared_ptr<Vertex> last = Vertex::next(first, lav);\n\n      connectFaces(first->leftFaceNode, last->rightFaceNode);\n      connectFaces(first->rightFaceNode, last->leftFaceNode);\n\n      first->processed = true;\n      last->processed = true;\n\n      Vertex::removeFromLav(first, lav);\n      Vertex::removeFromLav(last, lav);\n    }\n  }\n}\n\nstatic void removeEventsUnderHeight(std::vector<std::shared_ptr<QueueEvent>>& queue, double levelHeight) {\n  while (!queue.empty()) {\n    if (queue[0]->distance > levelHeight + EPSILON) {\n      break;\n    }\n    queue.erase(queue.begin());\n  }\n}\n\nstatic void removeEmptyLav(std::vector<std::vector<std::shared_ptr<Vertex>>>& sLav) {\n  for (unsigned i = 0; i < sLav.size(); i++) {\n    if (sLav[i].size() == 0) {\n      sLav.erase(sLav.begin() + i);\n      i--;\n    }\n  }\n}\n\n[[maybe_unused]] static std::vector<std::vector<Point3d>> doStraightSkeleton(std::vector<Point3d>& polygon, double roofPitchDegrees) {\n\n  /* Straight skeleton algorithm implementation. Based on highly modified Petr\n  * Felkel and Stepan Obdrzalek algorithm.\n  * Translated from https://github.com/kendzi/kendzi-math\n  */\n\n  std::vector<std::shared_ptr<QueueEvent>> queue;\n  std::vector<std::shared_ptr<Face>> faces;\n  std::vector<std::shared_ptr<Edge>> edges;\n  std::vector<std::vector<std::shared_ptr<Vertex>>> sLav;\n\n  double zcoord = initPolygon(polygon);\n  makeCounterClockwise(polygon);\n  initSlav(polygon, sLav, edges, faces);\n  initEvents(sLav, queue, edges);\n\n  int count = 0;\n\n  while (!queue.empty()) {\n    // start processing skeleton level\n    count = assertMaxNumberOfIterations(count);\n\n    std::sort(queue.begin(), queue.end(), QueueEvent::Comparer());\n\n    double levelHeight = queue[0]->distance;\n\n    std::vector<LevelEvent> levelEvents = loadAndGroupLevelEvents(queue, sLav);\n\n    for (LevelEvent& event : levelEvents) {\n\n      if (event.obsolete) {\n        /*\n        * Event is outdated some of parent vertex was processed\n        * before\n        */\n        continue;\n      }\n\n      if (event.eventType == LevelEvent::TYPE_MULTI_SPLIT) {\n        multiSplitEvent(event, sLav, queue, edges, faces);\n        continue;\n      } else if (event.eventType == LevelEvent::TYPE_PICK) {\n        pickEvent(event, sLav, queue, edges, faces);\n        continue;\n      } else if (event.eventType == LevelEvent::TYPE_MULTI_EDGE) {\n        multiEdgeEvent(event, sLav, queue, edges, faces);\n        continue;\n      } else {\n        LOG_AND_THROW(\"Unexpected event type\");\n      }\n    }\n\n    processTwoNodeLavs(sLav, queue, faces);\n    removeEventsUnderHeight(queue, levelHeight);\n    removeEmptyLav(sLav);\n  }\n\n  return facesToPoint3d(faces, roofPitchDegrees, zcoord);\n}\n\nstatic std::vector<Point3d> getGableTopAndBottomVertices(std::vector<Point3d>& surface) {\n  std::vector<Point3d> ret;\n  if (surface.size() != 3) {\n    // gable must have 3 vertices\n    return ret;\n  }\n  if (surface[0].z() > surface[1].z() && surface[0].z() > surface[2].z() && surface[1].z() == surface[2].z()) {\n    ret.push_back(surface[0]);  // top\n    ret.push_back(surface[1]);  // bottom\n    ret.push_back(surface[2]);  // bottom\n  } else if (surface[1].z() > surface[0].z() && surface[1].z() > surface[2].z() && surface[0].z() == surface[2].z()) {\n    ret.push_back(surface[1]);  // top\n    ret.push_back(surface[0]);  // bottom\n    ret.push_back(surface[2]);  // bottom\n  } else if (surface[2].z() > surface[0].z() && surface[2].z() > surface[1].z() && surface[0].z() == surface[1].z()) {\n    ret.push_back(surface[2]);  // top\n    ret.push_back(surface[0]);  // bottom\n    ret.push_back(surface[1]);  // bottom\n  }\n  return ret;\n}\n\nstatic int getOppositeGableIndex(std::vector<std::vector<Point3d>>& surfaces, std::vector<unsigned> connectedSurfaces, unsigned gableIndexNum) {\n  // Obtain opposite gable index relative to gableIndexNum\n  if (connectedSurfaces.size() < 4) {\n    // There must be at least 4 connected surfaces (including gableIndexNum) for\n    // there to be an opposite gable.\n    return -1;\n  }\n  std::vector<Point3d> baseVertices = getGableTopAndBottomVertices(surfaces[gableIndexNum]);\n  Edge base1 = Edge(baseVertices[0], baseVertices[1]);\n  Edge base2 = Edge(baseVertices[0], baseVertices[2]);\n  for (unsigned i = 0; i < connectedSurfaces.size(); i++) {\n    if (connectedSurfaces[i] == gableIndexNum) {\n      continue;\n    }\n    std::vector<Point3d> tryVertices = getGableTopAndBottomVertices(surfaces[connectedSurfaces[i]]);\n    if (tryVertices.size() == 0) {\n      continue;\n    }\n    Edge try1 = Edge(tryVertices[0], tryVertices[1]);\n    Edge try2 = Edge(tryVertices[0], tryVertices[2]);\n    if (base1 != try1 && base1 != try2 && base2 != try1 && base2 != try2) {\n      return i;\n    }\n  }\n  return -1;\n}\n\nstatic void applyGableLogicTriangles(std::vector<std::vector<Point3d>>& surfaces) {\n  // For any roof surface that has 3 vertices, convert from an angled\n  // surface to a gable surface.\n\n  std::set<int> processedSurfaces;\n\n  for (unsigned i = 0; i < surfaces.size(); i++) {\n    if (std::find(processedSurfaces.begin(), processedSurfaces.end(), i) != processedSurfaces.end()) {\n      continue;  // already processed\n    }\n\n    std::vector<Point3d>& gable = surfaces[i];\n    std::vector<Point3d> gableVertices = getGableTopAndBottomVertices(gable);\n    if (gableVertices.size() == 0) {\n      continue;\n    }\n\n    processedSurfaces.insert(i);\n    Point3d gableTop = gableVertices[0];\n\n    std::vector<unsigned> connectedSurfaces;\n    for (unsigned j = 0; j < surfaces.size(); j++) {\n      for (Point3d& vertex : surfaces[j]) {\n        if (vertex != gableTop) {\n          continue;\n        }\n        connectedSurfaces.push_back(j);\n        processedSurfaces.insert(j);  // will be processed below\n      }\n    }\n\n    int oppositeGableIndex = getOppositeGableIndex(surfaces, connectedSurfaces, i);\n\n    if (oppositeGableIndex != -1) {\n      // Two gables opposite each other meet, we'll need to create a (arbitrary) ridge line.\n\n      /*                  ___________          ___________\n      *                  |\\         /|        |     |     |\n      *                  |  \\     /  |        |     |     |\n      *                  |    \\ /    |        |     |     |\n      *                  |    / \\    |   =>   |     |     |\n      *                  |  /     \\  |        |     |     |\n      *                  |/_________\\|        |_____|_____|\n      */\n\n      // Shift gable top vertex for opposite surfaces\n      std::vector<Point3d> newVertices;\n\n      std::vector<unsigned> gableSurfaceIndices = {i, connectedSurfaces[oppositeGableIndex]};\n      for (unsigned j = 0; j < gableSurfaceIndices.size(); j++) {\n        std::vector<Point3d>& surface = surfaces[gableSurfaceIndices[j]];\n        for (Point3d& vertex : surface) {\n          if (vertex != gableTop) {\n            continue;\n          }\n          std::vector<Point3d> surfVertices = getGableTopAndBottomVertices(surface);\n          Point3d newVertex =\n            Point3d((surfVertices[1].x() + surfVertices[2].x()) / 2.0, (surfVertices[1].y() + surfVertices[2].y()) / 2.0, surfVertices[0].z());\n          newVertices.push_back(newVertex);\n          vertex = newVertex;\n        }\n      }\n\n      // Split gable top vertex (create ridge) for other surfaces\n      for (unsigned j = 0; j < connectedSurfaces.size(); j++) {\n        if (std::find(gableSurfaceIndices.begin(), gableSurfaceIndices.end(), connectedSurfaces[j]) != gableSurfaceIndices.end()) {\n          continue;  // already processed these surfaces\n        }\n        std::vector<Point3d>& surface = surfaces[connectedSurfaces[j]];\n        std::vector<Point3d> trySurface1;\n        std::vector<Point3d> trySurface2;\n        std::vector<Edge> tryEdges1;\n        std::vector<Edge> tryEdges2;\n        for (unsigned k = 0; k < surface.size(); k++) {\n          Point3d vertex = surface[k];\n          if (vertex != gableTop) {\n            trySurface1.push_back(vertex);\n            trySurface2.push_back(vertex);\n            continue;\n          }\n          int prevk = k - 1 + surface.size();\n          int nextk = k + 1;\n          Point3d previousVertex = surface[prevk % surface.size()];\n          Point3d nextVertex = surface[nextk % surface.size()];\n\n          trySurface1.push_back(newVertices[0]);\n          trySurface1.push_back(newVertices[1]);\n          tryEdges1.push_back(Edge(newVertices[0], previousVertex));\n          tryEdges1.push_back(Edge(newVertices[1], nextVertex));\n\n          trySurface2.push_back(newVertices[1]);\n          trySurface2.push_back(newVertices[0]);\n          tryEdges2.push_back(Edge(newVertices[1], previousVertex));\n          tryEdges2.push_back(Edge(newVertices[0], nextVertex));\n        }\n\n        // Correct surface will have no edge intersections\n        LineLinear2d l1a = LineLinear2d(tryEdges1[0].begin, tryEdges1[0].end);\n        LineLinear2d l1b = LineLinear2d(tryEdges1[1].begin, tryEdges1[1].end);\n        LineLinear2d l2a = LineLinear2d(tryEdges2[0].begin, tryEdges2[0].end);\n        LineLinear2d l2b = LineLinear2d(tryEdges2[1].begin, tryEdges2[1].end);\n\n        if (l1a.collide(l1b) && !l2a.collide(l2b)) {\n          surface = trySurface2;  // trySurface1 has self intersection\n        } else if (l2a.collide(l2b) && !l1a.collide(l1b)) {\n          surface = trySurface1;  // trySurface2 has self intersection\n        } else {\n          LOG_AND_THROW(\"Could not create gable ridge.\");\n        }\n      }\n\n    } else {\n\n      // Shift gable top vertex for all connected surfaces.\n\n      /*                  ___________          ___________\n      *                  |\\         /|        |     |     |\n      *                  |  \\     /  |        |     |     |\n      *                  |    \\ /    |        |     |     |\n      *                  |     |     |        |     |     |\n      *                  |     |     |   =>   |     |     |\n      *                  |    / \\    |        |     |     |\n      *                  |  /     \\  |        |     |     |\n      *                  |/_________\\|        |_____|_____|\n      */\n\n      Point3d newVertex =\n        Point3d((gableVertices[1].x() + gableVertices[2].x()) / 2.0, (gableVertices[1].y() + gableVertices[2].y()) / 2.0, gableVertices[0].z());\n      for (unsigned j = 0; j < connectedSurfaces.size(); j++) {\n        std::vector<Point3d>& surface = surfaces[connectedSurfaces[j]];\n        for (Point3d& vertex : surface) {\n          if (vertex != gableTop) {\n            continue;\n          }\n          vertex = newVertex;\n        }\n      }\n    }\n  }\n}\n\nstatic void applyGableLogicRidgeTwoAnglesForward(std::vector<std::vector<Point3d>>& surfaces) {\n  // TODO\n\n  /*                  ___________          ___________\n  *                  |     |     |        |     |     |\n  *                  |     |     |        |     |     |\n  *                  |     |     |        |     |     |\n  *                  |     |     |        |     |     |\n  *                  |    / \\    |   =>   |     |     |\n  *                  |   /   \\   |        |     |     |\n  *                  |  /     |  |        |     |     |\n  *                  | /     /|  |        |     |     |\n  *                  |/_____/ |  |        |_____|_____|\n  *                        |  |  |              |  |  |\n  *                        |__|__|              |__|__|\n  */\n}\n\nstatic void applyGableLogicRidgeTwoAnglesInside(std::vector<std::vector<Point3d>>& surfaces) {\n  // TODO\n\n  /*                  ___________          ___________\n  *                  |     |     |        |     |     |\n  *                  |     |     |        |     |     |\n  *                  |     |     |        |     |     |\n  *                  |     |     |        |     |     |\n  *                  |    / \\    |   =>   |     |     |\n  *                  |   /   \\   |        |     |     |\n  *                  |  /     \\  |        |     |     |\n  *                  | /   /|\\ \\ |        |     |     |\n  *                  |/___/ | \\_\\|        |_____|_____|\n  *                       | | |                | | |\n  *                       |_|_|                |_|_|\n  */\n}\n\nstatic void applyGableLogicRidgeTwoAnglesBackward(std::vector<std::vector<Point3d>>& surfaces) {\n  // TODO\n\n  /*    _______________________          _______________________\n  *    |                      /|        |                       |\n  *    |                     / |        |                       |\n  *    |                    /  |        |                       |\n  *    |                   /   |        |                       |\n  *    |-------------------    |        |-----------------------|\n  *    |                   \\   |   =>   |                       |\n  *    |                    \\  |        |                       |\n  *    |                    |  |        |                       |\n  *    |                   /|  |        |                   /|\\ |\n  *    |__________________/ |  |        |__________________/ | \\|\n  *                      |  |  |                          |  |  |\n  *                      |  |  |                          |  |  |\n  *                      |__|__|                          |__|__|\n  */\n}\n\nstatic void applyGableLogicTwoRidgesTwoOppositeAngles(std::vector<std::vector<Point3d>>& surfaces) {\n  // TODO\n\n  /*    _______________________          _______________________\n  *    |                      /|        |                       |\n  *    |                     / |        |                       |\n  *    |                    /  |        |                       |\n  *    |                   /   |        |                       |\n  *    |-------------------    |        |-----------------------|\n  *    |                  /|   |   =>   |                 /|\\   |\n  *    |                 / |   |        |                / | \\  |\n  *    |                /  |   |        |               /  |  \\ |\n  *    |               /   |   |        |              /   |   \\|\n  *    |______________/    |   |        |_____________/    |    |\n  *                   |    |   |                      |    |    |\n  *                   |    |   |                      |    |    |\n  *                   |____|___|                      |____|____|\n  */\n}\n\n[[maybe_unused]] static void applyGables(std::vector<std::vector<Point3d>>& surfaces) {\n  // Convert hip roof to gable roof\n\n  // Simple logic\n  applyGableLogicTriangles(surfaces);\n\n  // Complex logic\n  applyGableLogicRidgeTwoAnglesForward(surfaces);\n  applyGableLogicRidgeTwoAnglesInside(surfaces);\n  applyGableLogicRidgeTwoAnglesBackward(surfaces);\n  applyGableLogicTwoRidgesTwoOppositeAngles(surfaces);\n}\n\nstruct Point3dComparer  // needed to use std::map<Point3d, foo>\n{\n  bool operator()(Point3d p1, Point3d p2) const {\n    if (p1.x() < p2.x()) {\n      return true;\n    } else if (p1.x() == p2.x()) {\n      return (p1.y() < p2.y());\n    }\n    return false;\n  }\n};\n\nstatic std::vector<Point3d> getShedLine(const std::vector<Point3d>& polygon, double directionDegrees) {\n  boost::optional<Point3d> centroid = getCentroid(polygon);\n  if (!centroid) {\n    LOG_AND_THROW(\"Could not obtain centroid for polygon.\");\n  }\n\n  // Get max distance of any polygon vertex from centroid\n  double maxDistance = 0.0;\n  for (const Point3d& vertex : polygon) {\n    double distance = getDistance(vertex, centroid.get());\n    if (distance > maxDistance) {\n      maxDistance = distance;\n    }\n  }\n  maxDistance *= 2.0;  // add buffer\n\n  double angleStandard = 90 - directionDegrees;\n\n  // Construct line segment through centroid perpendicular to directionDegrees\n  double angleRad1 = degToRad(angleStandard - 90.0);\n  double angleRad2 = degToRad(angleStandard + 90.0);\n  Point3d start = Point3d(centroid.get().x() + maxDistance * cos(angleRad1), centroid.get().y() + maxDistance * sin(angleRad1), 0.0);\n  Point3d end = Point3d(centroid.get().x() + maxDistance * cos(angleRad2), centroid.get().y() + maxDistance * sin(angleRad2), 0.0);\n\n  // Shift line segment in opposite direction of directionDegrees\n  double angle = atan2(end.x() - start.x(), end.y() - start.y());\n  double dx = -maxDistance * cos(angle);\n  double dy = maxDistance * sin(angle);\n  start += Vector3d(dx, dy, 0.0);\n  end += Vector3d(dx, dy, 0.0);\n\n  std::vector<Point3d> line = {start, end};\n  return line;\n}\n\n[[maybe_unused]] static std::vector<std::vector<Point3d>> doShedRoof(std::vector<Point3d>& polygon, double roofPitchDegrees,\n                                                                     double directionDegrees) {\n  std::vector<std::vector<Point3d>> surfaces;\n\n  double zcoord = initPolygon(polygon);\n\n  // Define arbitrary line outside of the polygon based on directionDegrees. The\n  // closest point to the line defines the start (height = 0) of the shed roof.\n  std::vector<Point3d> line = getShedLine(polygon, directionDegrees);\n\n  // Calculate distance from each polygon vertex to the line.\n  std::map<Point3d, double, Point3dComparer> distances;\n  double minDistance = std::numeric_limits<double>::max();\n  for (Point3d& vertex : polygon) {\n    distances[vertex] = getDistancePointToLineSegment(vertex, line);\n    if (distances[vertex] < minDistance) {\n      minDistance = distances[vertex];\n    }\n  }\n\n  // Reduce all vertex distances by minimum vertex distance. Combined with\n  // roofPitchDegrees, this defines the height of the shed roof vertex.\n  double roofSlope = tan(degToRad(roofPitchDegrees));\n  for (auto element : distances) {\n    distances[element.first] = element.second - minDistance;\n  }\n  for (Point3d& vertex : polygon) {\n    vertex += Vector3d(0.0, 0.0, zcoord + distances[vertex] * roofSlope);\n  }\n\n  // Construct vertical walls for each polygon edge up to the shed roof.\n  for (unsigned i = 0; i < polygon.size(); i++) {\n    Point3d vertex = polygon[i];\n    Point3d nextVertex = polygon[(i + 1) % polygon.size()];\n    std::vector<Point3d> wall = {vertex, nextVertex};\n    if (nextVertex.z() - zcoord > EPSILON) {\n      Point3d nextVertexFloor = Point3d(nextVertex.x(), nextVertex.y(), zcoord);\n      wall.push_back(nextVertexFloor);\n    }\n    if (vertex.z() - zcoord > EPSILON) {\n      Point3d vertexFloor = Point3d(vertex.x(), vertex.y(), zcoord);\n      wall.push_back(vertexFloor);\n    }\n    if (wall.size() > 2) {\n      surfaces.push_back(wall);\n    }\n  }\n  surfaces.push_back(reverse(polygon));\n\n  return surfaces;\n}\n}  // namespace openstudio\n", "meta": {"hexsha": "11c146dd6fa076928548da0d646dff54ba425395", "size": 93357, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utilities/geometry/RoofGeometry_Details.hpp", "max_stars_repo_name": "muehleisen/OpenStudio", "max_stars_repo_head_hexsha": "3bfe89f6c441d1e61e50b8e94e92e7218b4555a0", "max_stars_repo_licenses": ["blessing"], "max_stars_count": 354.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T17:46:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:00:00.000Z", "max_issues_repo_path": "src/utilities/geometry/RoofGeometry_Details.hpp", "max_issues_repo_name": "muehleisen/OpenStudio", "max_issues_repo_head_hexsha": "3bfe89f6c441d1e61e50b8e94e92e7218b4555a0", "max_issues_repo_licenses": ["blessing"], "max_issues_count": 3243.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T04:54:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:22:22.000Z", "max_forks_repo_path": "src/utilities/geometry/RoofGeometry_Details.hpp", "max_forks_repo_name": "jmarrec/OpenStudio", "max_forks_repo_head_hexsha": "5276feff0d8dbd6c8ef4e87eed626bc270a19b14", "max_forks_repo_licenses": ["blessing"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T15:59:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:46:09.000Z", "avg_line_length": 33.5093323762, "max_line_length": 150, "alphanum_fraction": 0.6262733378, "num_tokens": 24713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5104190251197965}}
{"text": "#include <Eigen/Dense>\n#include <algorithm>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/program_options.hpp>\n#include <chrono>\n#include <cmath>\n#include <cstdio>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include \"bte_config.h\"\n#include \"aux/rdtsc_timer.hpp\"\n#include \"aux/timer.hpp\"\n#include \"collision_tensor/collision_tensor_galerkin.hpp\"\n#include \"collision_tensor/dense/collision_tensor_zlastAM.hpp\"\n#include \"collision_tensor/dense/storage/vbcrs_sparsity.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n\n\n#ifdef LIKWID\n#include <likwid.h>\n#endif\n\n\nnamespace po = boost::program_options;\nnamespace bf = boost::filesystem;\n\n#include <yaml-cpp/yaml.h>\n\nusing namespace std;\nusing namespace boltzmann;\n\ntypedef ct_dense::CollisionTensorZLastAM ct_dense_t;\ntypedef SpectralBasisFactoryKS basis_factory_t;\ntypedef SpectralBasisFactoryKS::basis_type basis_type;\n\n\nint\nmain(int argc, char* argv[])\n{\n  // dummy call, internal storage of ct_dense is using MPI shmem, therefore:\n  MPI_Init(&argc, &argv);\n\n  std::string version_id = GIT_SHA1;\n  cout << \"VersionID: \" << version_id << \"@\" << GIT_BNAME << std::endl;\n\n  int nin, nrep, vblksize;\n  if (argc < 4) {\n    cerr << \"usage: \" << argv[0] << \" nin nrep\"\n         << \"\\nnin: number of input vectors\"\n         << \"\\nnrep: repeat timings this many times\"\n         << \"\\nvblksize: vblksize (VBCRS sparsity)\"\n         << \"\\n\";\n    return 1;\n  } else {\n    nin = atoi(argv[1]);\n    nrep = atoi(argv[2]);\n    vblksize = atoi(argv[3]);\n    cerr << \"nin: \" << nin << \"\\n\";\n    cerr << \"nrep: \" << nrep << \"\\n\";\n    cerr << \"vblksize: \" << vblksize << \"\\n\";\n  }\n\n  // Load config\n  if (!boost::filesystem::is_regular_file(\"config.yaml\")) {\n    cout << \"config file not found\\n\";\n    return 1;\n  }\n  YAML::Node config = YAML::LoadFile(\"config.yaml\");\n  const size_t K = config[\"SpectralBasis\"][\"deg\"].as<size_t>();\n\n  // create basis\n  basis_type basis;\n  SpectralBasisFactoryKS::create(basis, K);\n  unsigned int N = basis.n_dofs();\n\n  typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> array_t;\n\n  Timer<> stimer;\n  stimer.start();\n  ct_dense_t ct_dense(basis, nin);\n  stimer.print(std::cout, stimer.stop(), \"tensor constructor\");\n\n  stimer.start();\n  ct_dense.import_entries_mpishmem(config[\"Scattering\"][\"file\"].as<std::string>(),\n                                   vblksize);\n  stimer.print(std::cout, stimer.stop(), \"loading tensor\");\n\n  int npadded = ct_dense.padded_vector_length();\n  array_t xb(npadded, nin);\n  xb.setOnes();\n  array_t yb(N, nin);\n\n  cout << \"doing timings...\" << \"\\n\";\n#ifdef LIKWID\n  LIKWID_MARKER_INIT;\n  LIKWID_MARKER_REGISTER(\"CT\");\n  LIKWID_MARKER_START(\"CT\");\n#else\n  RDTSCTimer timer;\n#endif\n  MPI_Barrier(MPI_COMM_WORLD);\n  for (int i = 0; i < nrep; ++i) {\n#ifndef LIKWID\n    timer.start();\n#endif\n    ct_dense.apply(yb, xb);\n#ifndef LIKWID\n    auto clap = timer.stop();\n    timer.print(cout, clap, \"dense\");\n#endif\n  }\n\n#ifdef LIKWID\n  LIKWID_MARKER_STOP(\"CT\");\n  LIKWID_MARKER_CLOSE;\n#endif\n\n  MPI_Finalize();\n  return 0;\n}\n", "meta": {"hexsha": "4b2ee4e32f6ce553b64b6cb168118be6f14abbf7", "size": 3227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/collision_tensor_dense/main_timing_zlastAM.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/collision_tensor_dense/main_timing_zlastAM.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/collision_tensor_dense/main_timing_zlastAM.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": 25.6111111111, "max_line_length": 88, "alphanum_fraction": 0.6761698172, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5104190137221832}}
{"text": "#include \"InverseProblem_Adjoint_InitialConfiguration.h\"\n\n#include <Eigen/Dense>\n#include <tinyformat.h>\n#include <cinder/Log.h>\n#include <numeric>\n#include <LBFGS.h>\n#include <cinder/app/App.h>\n\n#include \"GradientDescent.h\"\n#include \"Integration.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n#define DEBUG_SAVE_MATRICES 0\n\n\nnamespace ar {\n\n    InverseProblem_Adjoint_InitialConfiguration::InverseProblem_Adjoint_InitialConfiguration()\n        : meshPositionPrior(0)\n\t\t, gridPriors({0.01, 0.01, 5})\n\t\t, gridHyperEpsilon(0.5)\n        , numIterations(10)\n    {\n    }\n\n    InverseProblemOutput InverseProblem_Adjoint_InitialConfiguration::solveGrid(int deformedTimestep,\n        BackgroundWorker* worker, IntermediateResultCallback_t callback)\n    {\n        CI_LOG_I(\"Solve for Initial Configuration at timestep \" << deformedTimestep);\n        // Create simulation\n        worker->setStatus(\"Adjoint - Initial Configuration Grid: create simulation\");\n        SoftBodyGrid2D simulation;\n        simulation.setGridResolution(input->gridResolution_);\n        simulation.setSDF(input->gridReferenceSdf_);\n        simulation.setExplicitDiffusion(true);\n        simulation.setHardDirichletBoundaries(true);\n        simulation.setAdvectionMode(SoftBodyGrid2D::AdvectionMode::DIRECT_FORWARD);\n        simulation.resetBoundaries();\n        for (const auto& b : input->gridDirichletBoundaries_)\n            simulation.addDirichletBoundary(b.first.first, b.first.second, b.second);\n        for (const auto& b : input->gridNeumannBoundaries_)\n            simulation.addNeumannBoundary(b.first.first, b.first.second, b.second);\n        if (worker->isInterrupted()) return InverseProblemOutput();\n\n        // Set parameters with everything that can't be reconstructed here\n        simulation.setGravity(input->settings_.gravity_);\n        simulation.setMass(input->settings_.mass_);\n        simulation.setDamping(input->settings_.dampingAlpha_, input->settings_.dampingBeta_);\n        simulation.setMaterialParameters(input->settings_.youngsModulus_, input->settings_.poissonsRatio_);\n        simulation.setRotationCorrection(SoftBodySimulation::RotationCorrection::None);\n        if (worker->isInterrupted()) return InverseProblemOutput();\n\n        GridUtils2D::grid_t targetSdf = input->gridResultsSdf_[deformedTimestep];\n\n#if 1\n\t\t//Gradient Descent\n\t\t//define gradient of the cost function\n        real finalCost = 0;\n        const auto gradient = \n            [&simulation, this, worker, targetSdf, &finalCost](const VectorX& x)\n        {\n            real cost;\n\t\t\tgrid_t currentSdf = GridUtils2D::delinearize(x, simulation.getGridResolution(), simulation.getGridResolution());\n\t\t\tauto gradientGrid = gradientGrid_AdjointMethod(targetSdf, simulation,\n\t\t\t\tcurrentSdf, gridPriors, cost, worker);\n\t\t\tVectorX gradient = GridUtils2D::linearize(gradientGrid);\n            finalCost = cost;\n            return gradient;\n        };\n\t\t//Optimize\n        VectorX start = GridUtils2D::linearize(targetSdf);\n        GradientDescent<VectorX> gd(start, gradient, 1e-10, 0.5);\n\t\tgd.setMinStepsize(0.0001);\n        gd.setMaxStepsize(0.4);\n        int oi;\n        for (oi = 0; oi < numIterations; ++oi) {\n            worker->setStatus(tfm::format(\"Adjoint - Initial Configuration Grid: optimization %d/%d\", (oi + 1), numIterations));\n            if (gd.step()) break;\n\t\t\tCI_LOG_I(\"Gradient descent, step size is \" << gd.getLastStepSize());\n            if (worker->isInterrupted()) return InverseProblemOutput();\n\n            InverseProblemOutput output;\n            output.initialGridSdf_ = GridUtils2D::delinearize(gd.getCurrentSolution(), input->gridResolution_, input->gridResolution_);\n            output.finalCost_ = finalCost;\n            callback(output);\n        }\n        VectorX finalValueV = gd.getCurrentSolution();\n#else\n        //LBFGS with Hyper-Optimization over the Gravity\n        LBFGSpp::LBFGSParam<real> params;\n        params.epsilon = 1e-10;\n        params.max_iterations = numIterations;\n        LBFGSpp::LBFGSSolver<real> lbfgs(params);\n        //define gradient\n        LBFGSpp::LBFGSSolver<real>::ObjectiveFunction_t fun([&simulation, this, worker, targetSdf](const VectorX& x, VectorX& gradient) -> real {\n            real cost;\n            grid_t currentSdf = GridUtils2D::delinearize(x, simulation.getGridResolution(), simulation.getGridResolution());\n            auto gradientGrid = gradientGrid_AdjointMethod(targetSdf, simulation,\n                currentSdf, gridPriors, cost, worker);\n            gradient = GridUtils2D::linearize(gradientGrid);\n            return cost;\n        });\n        LBFGSpp::LBFGSSolver<real>::CallbackFunction_t lbfgsCallback([worker, callback, this](const VectorX& x, const real& v, int k) -> bool {\n            worker->setStatus(tfm::format(\"Adjoint - Initial Configuration Grid: optimization %d/%d\", k, numIterations));\n\n\t\t\tInverseProblemOutput output;\n\t\t\toutput.initialGridSdf_ = GridUtils2D::delinearize(x, input->gridResolution_, input->gridResolution_);\n\t\t\toutput.finalCost_ = v;\n\t\t\tcallback(output);\n\n            return !worker->isInterrupted();\n        });\n        //optimize\n        Vector2 gravity = input->settings_.gravity_;\n        real hyperStepsize = 1;\n        real hyperStep = 0;\n        real finalCost = 0;\n        VectorX finalValueV = GridUtils2D::linearize(targetSdf);\n        int totalOI = 0;\n        while (true)\n        {\n            CI_LOG_I(\"Try optimization with \" << (hyperStep + hyperStepsize) * 100 << \"% of the final gravity\");\n            simulation.setGravity((hyperStep + hyperStepsize) * gravity);\n            VectorX currentValue = finalValueV;\n            int oi = lbfgs.minimize(fun, currentValue, finalCost, lbfgsCallback);\n            totalOI += oi;\n            if (worker->isInterrupted()) break;\n            if (finalCost > gridHyperEpsilon)\n            {\n                //not converged to global minimum, try smaller step\n                hyperStepsize /= 2;\n                CI_LOG_I(\"Not converged (cost \" << finalCost << \"), decrease hyper-stepsize to \" << hyperStepsize);\n            }\n            else\n            {\n                //converged, increase gravity\n                finalValueV = currentValue;\n                hyperStep += hyperStepsize;\n                hyperStepsize *= 1.2;\n                CI_LOG_I(\"Converged, take \" << hyperStep * 100 << \"% of the final gravity as input to the next step and increase the step size to \" << hyperStepsize);\n                if (hyperStep >= 1 - 1e-5)\n                    break; //finished\n                if (hyperStep + hyperStepsize > 1)\n                    hyperStepsize = 1 - hyperStep;\n            }\n        }\n#endif\n\n        InverseProblemOutput output;\n        output.initialGridSdf_ = GridUtils2D::delinearize(finalValueV, input->gridResolution_, input->gridResolution_);\n        output.finalCost_ = finalCost;\n\n\t\tCI_LOG_D(\"Ground truth sdf:\\n\" << input->gridReferenceSdf_);\n\t\tCI_LOG_D(\"Target sdf:\\n\" << targetSdf);\n\t\tCI_LOG_D(\"Reconstructed input sdf:\\n\" << output.initialGridSdf_.value());\n\t\tCI_LOG_D(\"Final cost: \" << output.finalCost_);\n\n        return output;\n    }\n\n    InverseProblemOutput InverseProblem_Adjoint_InitialConfiguration::solveMesh(int deformedTimestep,\n        BackgroundWorker* worker, IntermediateResultCallback_t callback)\n    {\n        CI_LOG_I(\"Solve for Initial Configuration at timestep \" << deformedTimestep);\n        // Create simulation\n        worker->setStatus(\"Adjoint - Initial Configuration Mesh: create simulation\");\n        SoftBodyMesh2D simulation;\n        simulation.setMesh(input->meshReferencePositions_, input->meshReferenceIndices_);\n        simulation.resetBoundaries();\n        for (const auto& b : input->meshDirichletBoundaries_)\n            simulation.addDirichletBoundary(b.first, b.second);\n        for (const auto& b : input->meshNeumannBoundaries_)\n            simulation.addNeumannBoundary(b.first, b.second);\n        simulation.reorderNodes();\n        if (worker->isInterrupted()) return InverseProblemOutput();\n\n        // Set parameters with everything that can't be reconstructed here\n        simulation.setGravity(input->settings_.gravity_);\n        simulation.setMass(input->settings_.mass_);\n        simulation.setDamping(input->settings_.dampingAlpha_, input->settings_.dampingBeta_);\n\t\tsimulation.setMaterialParameters(input->settings_.youngsModulus_, input->settings_.poissonsRatio_);\n        simulation.setRotationCorrection(SoftBodySimulation::RotationCorrection::None);\n        if (worker->isInterrupted()) return InverseProblemOutput();\n\n        \n\t\tSoftBodyMesh2D::Vector2List targetPositions = input->meshReferencePositions_;\n\t\tfor (size_t i = 0; i < input->meshReferencePositions_.size(); ++i) targetPositions[i] += input->meshResultsDisplacement_[deformedTimestep][i];\n#if 0\n\t\t//Gradient Descent\n        //define gradient of the cost function\n\t\treal finalCost = 0;\n        const auto gradient = [&simulation, &outputU, &finalCost, this, worker, deformedTimestep](const VectorX& x)\n        {\n            real cost;\n\t\t\tVectorX gradient = gradientMesh(deformedTimestep, simulation, x, outputU, cost, worker);\n\t\t\tfinalCost = cost;\n\t\t\treturn gradient;\n        };\n\n        //run optimization\n\t\tVectorX initialPositions = linearizePositions(input->meshReferencePositions_) + linearizePositions(input->meshResultsDisplacement_[deformedTimestep]);\n        GradientDescent<VectorX> gd(initialPositions, gradient, 1e-10, 0.0001);\n        int oi;\n        for (oi = 0; oi < numIterations; ++oi) {\n            worker->setStatus(tfm::format(\"Adjoint - Initial Configuration Mesh: optimization %d/%d\", (oi + 1), numIterations));\n            if (gd.step()) break;\n            if (worker->isInterrupted()) return InverseProblemOutput();\n        }\n        VectorX finalValueV = gd.getCurrentSolution();\n#else\n\t\t//LBFGS with Hyper-Optimization over the Gravity\n\t\tLBFGSpp::LBFGSParam<real> params;\n\t\tparams.epsilon = 1e-10;\n\t\tparams.max_iterations = numIterations;\n\t\tLBFGSpp::LBFGSSolver<real> lbfgs(params);\n\t\t//define gradient\n\t\tLBFGSpp::LBFGSSolver<real>::ObjectiveFunction_t fun([&targetPositions, &simulation, this, worker](const VectorX& x, VectorX& gradient) -> real {\n\t\t\treal cost;\n\t\t\tgradient = gradientMesh_AdjointMethod(targetPositions, simulation, x, meshPositionPrior, cost, worker);\n\t\t\treturn cost;\n\t\t});\n\t\tLBFGSpp::LBFGSSolver<real>::CallbackFunction_t lbfgsCallback([worker, callback, this](const VectorX& x, const VectorX& g, const real& v, int k) -> bool {\n\t\t\tworker->setStatus(tfm::format(\"Adjoint - Initial Configuration Mesh: optimization %d/%d\", k, numIterations));\n\n\t\t\tInverseProblemOutput output;\n\t\t\toutput.initialMeshPositions_ = delinearizePositions(x);\n\t\t\toutput.finalCost_ = v;\n\t\t\tcallback(output);\n\n\t\t\treturn !worker->isInterrupted();\n\t\t});\n\t\t//optimize\n\t\tVector2 gravity = input->settings_.gravity_;\n\t\treal hyperStepsize = 1;\n\t\treal hyperStep = 0;\n\t\treal finalCost = 0;\n\t\tstatic const real hyperEpsilon = 1e-4;\n        VectorX finalValueV = linearizePositions(input->meshReferencePositions_) + linearizePositions(input->meshResultsDisplacement_[deformedTimestep]);\n\t\tint totalOI = 0;\n\t\twhile (true)\n\t\t{\n\t\t\tCI_LOG_I(\"Try optimization with \" << (hyperStep + hyperStepsize) * 100 << \"% of the final gravity\");\n\t\t\tsimulation.setGravity((hyperStep + hyperStepsize) * gravity);\n\t\t\tVectorX currentValue = finalValueV;\n\t\t\tint oi = lbfgs.minimize(fun, currentValue, finalCost, lbfgsCallback);\n\t\t\ttotalOI += oi;\n\t\t\tif (worker->isInterrupted()) break;\n\t\t\tif (finalCost > hyperEpsilon)\n\t\t\t{\n\t\t\t\t//not converged to global minimum, try smaller step\n\t\t\t\thyperStepsize /= 2;\n\t\t\t\tCI_LOG_I(\"Not converged (cost \" << finalCost << \"), decrease hyper-stepsize to \" << hyperStepsize);\n\t\t\t} else\n\t\t\t{\n\t\t\t\t//converged, increase gravity\n\t\t\t\tfinalValueV = currentValue;\n\t\t\t\thyperStep += hyperStepsize;\n\t\t\t\thyperStepsize *= 1.2;\n\t\t\t\tCI_LOG_I(\"Converged, take \" << hyperStep * 100 << \"% of the final gravity as input to the next step and increase the step size to \" << hyperStepsize);\n\t\t\t\tif (hyperStep >= 1 - 1e-5)\n\t\t\t\t\tbreak; //finished\n\t\t\t\tif (hyperStep + hyperStepsize > 1)\n\t\t\t\t\thyperStepsize = 1 - hyperStep;\n\t\t\t}\n\t\t}\n#endif\n\n\t\tMatrixX positionLog(2, input->meshReferencePositions_.size() * 2);\n\t\tpositionLog << finalValueV.transpose(), linearizePositions(input->meshReferencePositions_).transpose();\n        CI_LOG_I(\"Optimization done after \" << totalOI << \" optimization steps.  Final positions | Reference positions:\\n\" << positionLog);\n\n        InverseProblemOutput output;\n        output.initialMeshPositions_ = delinearizePositions(finalValueV);\n\t\toutput.finalCost_ = finalCost;\n\n\t\tsimulation.setGravity(gravity);\n\n        return output;\n    }\n\n    VectorX InverseProblem_Adjoint_InitialConfiguration::gradientMesh_AdjointMethod(\n\t\tconst SoftBodyMesh2D::Vector2List& targetPositions, SoftBodyMesh2D& simulation,\n        const VectorX& currentInitialPositions, real positionPrior, real& outputCost, BackgroundWorker* worker)\n    {\n        real poissonsRatio = simulation.getPoissonsRatio();\n        real youngsModulus = simulation.getYoungsModulus();\n\t\tVector2 gravity = simulation.getGravity();\n\n        int n = static_cast<int>(currentInitialPositions.size() / 2);\n\t\tassert(n == simulation.getReferencePositions().size());\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tsimulation.getReferencePositions()[i] = currentInitialPositions.segment<2>(2 * i);\n\t\t}\n\n        //get winding order\n        triangle_t referenceTriangle = {\n\t\t\ttargetPositions[simulation.getTriangles()[0].x()],\n\t\t\ttargetPositions[simulation.getTriangles()[0].y()],\n\t\t\ttargetPositions[simulation.getTriangles()[0].z()]\n        };\n        int windingOrder = meshTriangleWindingOrder(referenceTriangle);\n\n        //FORWARD\n\n        MatrixX K = MatrixX::Zero(2 * simulation.getNumFreeNodes(), 2 * simulation.getNumFreeNodes());\n        VectorX f = VectorX::Zero(2 * simulation.getNumFreeNodes());\n\n        //assemble force vector f and stiffness matrix K\n        simulation.assembleForceVector(f);\n        if (worker->isInterrupted()) return VectorX::Zero(2*n);\n        real materialMu, materialLambda;\n        SoftBodySimulation::computeMaterialParameters(youngsModulus, poissonsRatio, materialMu, materialLambda);\n        Matrix3 C = SoftBodySimulation::computeMaterialMatrix(materialMu, materialLambda);\n        simulation.assembleStiffnessMatrix(C, K, &f, SoftBodyMesh2D::Vector2List(simulation.getNumNodes(), Vector2::Zero()));\n        if (worker->isInterrupted()) return VectorX::Zero(2 * n);\n\n        //solve for the current displacement\n\t\tassert(K.isApprox(K.transpose())); //Test if K is indeed symmetric\n        PartialPivLU<MatrixX> Klu = K.partialPivLu();\n        VectorX u = Klu.solve(f);\n\n        // BACKWARD\n\t\tint p = simulation.getNumFreeNodes();\n\n        //compute derivate of the cost function with respect to the output u (displacement)\n        VectorX costDu(2 * p);\n        for (int i = 0; i < simulation.getNumNodes(); ++i)\n        {\n\t\t\tif (simulation.getNodeToFreeMap()[i] < 0) continue;\n\t\t\tcostDu.segment<2>(2 * simulation.getNodeToFreeMap()[i])\n\t\t\t\t= currentInitialPositions.segment<2>(2 * i) + u.segment<2>(2 * simulation.getNodeToFreeMap()[i])\n\t\t\t\t- targetPositions[i];\n        }\n#if DEBUG_SAVE_MATRICES==1\n        saveAsCSV(costDu, tfm::format(\"AdjointYoung-GradientMesh-costDu-k%f.csv\", youngsModulus));\n#endif\n\n        //solve for the dual\n        //In theory, I have to use K', but because I know that K is symmetric,\n        //I can use K directly and not the transpose.\n        VectorX lambda = Klu.solve(costDu); //rhs is called 'g'\n\n\t\t//compute yF, the dual of gX\n\t\tVectorX yF = VectorX::Zero(2 * p);\n\t\tfor (int e = 0; e < simulation.getNumElements(); ++e)\n\t\t{\n\t\t\tconst Vector3i& tri = simulation.getTriangles()[e];\n\t\t\tVector6 ue = Vector6::Zero();\n\t\t\tfor (int i2 = 0; i2 < 3; ++i2)\n\t\t\t\tif (simulation.getNodeStates()[tri[i2]] != SoftBodyMesh2D::DIRICHLET)\n\t\t\t\t\tue.segment<2>(2 * i2) = u.segment<2>(2 * simulation.getNodeToFreeMap()[tri[i2]]);\n\t\t\tfor (int i = 0; i < 3; ++i)\n\t\t\t{\n\t\t\t\tif (simulation.getNodeStates()[tri[i]] == SoftBodyMesh2D::DIRICHLET) continue;\n\t\t\t\tint col = simulation.getNodeToFreeMap()[tri[i]];\n\t\t\t\tfor (int coord = 0; coord < 2; ++coord)\n\t\t\t\t{\n\t\t\t\t\t//current parameter: vertex 'col' with coordinate 'coord'\n\t\t\t\t\t//F(:,j) = -dK/dp*u + df/dp\n\t\t\t\t\tint j = 2 * col + coord;\n\t\t\t\t\ttriangle_t triangle{\n\t\t\t\t\t\tcurrentInitialPositions.segment<2>(2 * tri[0]),\n\t\t\t\t\t\tcurrentInitialPositions.segment<2>(2 * tri[1]),\n\t\t\t\t\t\tcurrentInitialPositions.segment<2>(2 * tri[2])\n\t\t\t\t\t};\n\t\t\t\t\tMatrix6 KeDpos = meshStiffnessMatrixDerivative(triangle, 2 * i + coord, C, windingOrder);\n\t\t\t\t\t// dK/dp * u\n\t\t\t\t\tVector6 y = KeDpos * ue;\n\t\t\t\t\t//F(:,j) -= dK/dp*u per triangle\n\t\t\t\t\t//F(:,j) += Df/dp per triangle\n\t\t\t\t\tVector6 feDpos = meshForceDerivative(triangle, 2 * i + coord, gravity, windingOrder);\n\t\t\t\t\t// -dE/dp per triangle\n\t\t\t\t\tVector6 Fe = -(y - feDpos);\n\n\t\t\t\t\tfor (int i2 = 0; i2 < 3; ++i2)\n\t\t\t\t\t\tif (simulation.getNodeStates()[tri[i2]] != SoftBodyMesh2D::DIRICHLET)\n\t\t\t\t\t\t\tyF[j] += Fe.segment<2>(2 * i2).dot(lambda.segment<2>(2 * simulation.getNodeToFreeMap()[tri[i2]]));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//assemble gradient\n\t\tVectorX priorGradient = VectorX::Zero(2 * p); //TODO\n\t\tVectorX r = costDu; // dJ / dp\n\t\tVectorX gradient = yF + r + positionPrior * priorGradient;\n\n\t\t//map gradients back to the whole grid\n\t\tVectorX fullGradient = VectorX::Zero(2 * simulation.getNumNodes());\n\t\tfor (int i = 0; i<p; ++i)\n\t\t{\n\t\t\tfullGradient.segment<2>(2 * simulation.getFreeToNodeMap()[i]) = gradient.segment<2>(2 * i);\n\t\t}\n\n        //evaluate cost\n        //cost on position difference\n        real costMain = 0;\n        for (int i = 0; i < simulation.getNumNodes(); ++i)\n        {\n            if (simulation.getNodeToFreeMap()[i] < 0) continue;\n            costMain += (currentInitialPositions.segment<2>(2*i) + u.segment<2>(2 * simulation.getNodeToFreeMap()[i])\n                - targetPositions[i]).squaredNorm() / 2;\n        }\n        //cost by the prior\n        real costPrior = 0;\n        for (int tri = 0; tri<simulation.getNumElements(); ++tri)\n        {\n            triangle_t triangle{\n                currentInitialPositions.segment<2>(2 * simulation.getTriangles()[tri][0]),\n                currentInitialPositions.segment<2>(2 * simulation.getTriangles()[tri][1]),\n                currentInitialPositions.segment<2>(2 * simulation.getTriangles()[tri][2])\n            };\n            costPrior += windingOrder * meshTriangleArea(triangle) / (\n                (triangle[0] - triangle[1]).squaredNorm() + (triangle[0] - triangle[2]).squaredNorm() + (triangle[2] - triangle[1]).squaredNorm()\n                );\n        }\n        //final cost\n        outputCost = costMain + positionPrior * costPrior;\n        //CI_LOG_I(\"Optimization: cost \" << outputCost << \", gradient \" << gradient.transpose());\n\n        return fullGradient;\n    }\n\n    VectorX InverseProblem_Adjoint_InitialConfiguration::gradientMesh_Forward(\n        const SoftBodyMesh2D::Vector2List & targetPositions, SoftBodyMesh2D & simulation, \n        const VectorX & currentInitialPositions, real positionPrior, real & outputCost, BackgroundWorker * worker)\n    {\n        real poissonsRatio = simulation.getPoissonsRatio();\n        real youngsModulus = simulation.getYoungsModulus();\n\t\tVector2 gravity = simulation.getGravity();\n\n        int n = static_cast<int>(currentInitialPositions.size() / 2);\n        assert(n == simulation.getReferencePositions().size());\n        for (int i = 0; i < n; ++i) {\n            simulation.getReferencePositions()[i] = currentInitialPositions.segment<2>(2 * i);\n        }\n\n        //get winding order\n        triangle_t referenceTriangle = {\n            targetPositions[simulation.getTriangles()[0].x()],\n            targetPositions[simulation.getTriangles()[0].y()],\n            targetPositions[simulation.getTriangles()[0].z()]\n        };\n        int windingOrder = meshTriangleWindingOrder(referenceTriangle);\n\n        //FORWARD\n\n        MatrixX K = MatrixX::Zero(2 * simulation.getNumFreeNodes(), 2 * simulation.getNumFreeNodes());\n        VectorX f = VectorX::Zero(2 * simulation.getNumFreeNodes());\n\n        //assemble force vector F and stiffness matrix K\n        simulation.assembleForceVector(f);\n        if (worker->isInterrupted()) return VectorX::Zero(2 * n);\n        real materialMu, materialLambda;\n        SoftBodySimulation::computeMaterialParameters(youngsModulus, poissonsRatio, materialMu, materialLambda);\n        Matrix3 C = SoftBodySimulation::computeMaterialMatrix(materialMu, materialLambda);\n        simulation.assembleStiffnessMatrix(C, K, &f, SoftBodyMesh2D::Vector2List(simulation.getNumNodes(), Vector2::Zero()));\n        if (worker->isInterrupted()) return VectorX::Zero(2 * n);\n\n        //solve for the current displacement\n        PartialPivLU<MatrixX> Klu = K.partialPivLu();\n        VectorX u = Klu.solve(f);\n\n        // DERIVATIVES\n        int p = simulation.getNumFreeNodes();\n\n        //compute derivate of the cost function with respect to the output u (displacement)\n        VectorX costDu(2 * p);\n        for (int i = 0; i < simulation.getNumNodes(); ++i)\n        {\n            if (simulation.getNodeToFreeMap()[i] < 0) continue;\n            costDu.segment<2>(2 * simulation.getNodeToFreeMap()[i])\n                = currentInitialPositions.segment<2>(2 * i) + u.segment<2>(2 * simulation.getNodeToFreeMap()[i])\n                - targetPositions[i];\n        }\n\n        MatrixX F = MatrixX::Zero(2 * p, 2 * p);\n\n        //current parameter: vertex 'col' with coordinate 'coord' -> j=2*col+coord\n        //F(:,j) = -dK/dp*u + df/dp\n\n        for (int e=0; e<simulation.getNumElements(); ++e)\n        {\n            const Vector3i& tri = simulation.getTriangles()[e];\n            for (int i=0; i<3; ++i)\n            {\n                if (simulation.getNodeStates()[tri[i]] == SoftBodyMesh2D::DIRICHLET) continue;\n                int col = simulation.getNodeToFreeMap()[tri[i]];\n                for (int coord = 0; coord < 2; ++coord)\n                {\n                    //current parameter: vertex 'col' with coordinate 'coord'\n                    //F(:,j) = -dK/dp*u + df/dp\n                    int j = 2 * col + coord;\n                    triangle_t triangle{\n                        currentInitialPositions.segment<2>(2 * tri[0]),\n                        currentInitialPositions.segment<2>(2 * tri[1]),\n                        currentInitialPositions.segment<2>(2 * tri[2])\n                    };\n                    Matrix6 KeDpos = meshStiffnessMatrixDerivative(triangle, 2 * i + coord, C, windingOrder);\n                    Vector6 ue = Vector6::Zero();\n                    for (int i2 = 0; i2 < 3; ++i2)\n                        if (simulation.getNodeStates()[tri[i2]] != SoftBodyMesh2D::DIRICHLET)\n                            ue.segment<2>(2 * i2) = u.segment<2>(2 * simulation.getNodeToFreeMap()[tri[i2]]);\n                    Vector6 y = KeDpos * ue;\n                    //F(:,j) -= dK/dp*u per triangle\n                    for (int i2 = 0; i2 < 3; ++i2)\n                        if (simulation.getNodeStates()[tri[i2]] != SoftBodyMesh2D::DIRICHLET)\n                            F.block<2, 1>(2 * simulation.getNodeToFreeMap()[tri[i2]], j) -= y.segment<2>(2 * i2);\n\t\t\t\t\t//F(:,j) += Df/dp per triangle\n\t\t\t\t\tVector6 FeDpos = meshForceDerivative(triangle, 2 * i + coord, gravity, windingOrder);\n\t\t\t\t\tfor (int i2 = 0; i2 < 3; ++i2)\n\t\t\t\t\t\tif (simulation.getNodeStates()[tri[i2]] != SoftBodyMesh2D::DIRICHLET)\n\t\t\t\t\t\t\tF.block<2, 1>(2 * simulation.getNodeToFreeMap()[tri[i2]], j) += FeDpos.segment<2>(2 * i2);\n                }\n            }\n        }\n\n        //assemble final gradient\n        VectorX priorGradient = VectorX::Zero(2 * p); //TODO\n        MatrixX X = Klu.solve(F);\n        VectorX g = costDu; // dJ / du\n        VectorX gX = g.transpose() * X;\n\t\tVectorX r = costDu; // dJ / dp\n        VectorX gradient = gX + r + positionPrior * priorGradient;\n\n        //map gradients back to the whole grid\n        VectorX fullGradient = VectorX::Zero(2 * simulation.getNumNodes());\n        for (int i=0; i<p; ++i)\n        {\n            fullGradient.segment<2>(2 * simulation.getFreeToNodeMap()[i]) = gradient.segment<2>(2 * i);\n        }\n\n        //evaluate cost\n        //cost on position difference\n        real costMain = 0;\n        for (int i = 0; i < simulation.getNumNodes(); ++i)\n        {\n            if (simulation.getNodeToFreeMap()[i] < 0) continue;\n            costMain += (currentInitialPositions.segment<2>(2 * i) + u.segment<2>(2 * simulation.getNodeToFreeMap()[i])\n                - targetPositions[i]).squaredNorm() / 2;\n        }\n        //cost by the prior\n        real costPrior = 0;\n        for (int tri = 0; tri<simulation.getNumElements(); ++tri)\n        {\n            triangle_t triangle{\n                currentInitialPositions.segment<2>(2 * simulation.getTriangles()[tri][0]),\n                currentInitialPositions.segment<2>(2 * simulation.getTriangles()[tri][1]),\n                currentInitialPositions.segment<2>(2 * simulation.getTriangles()[tri][2])\n            };\n            costPrior += windingOrder * meshTriangleArea(triangle) / (\n                (triangle[0] - triangle[1]).squaredNorm() + (triangle[0] - triangle[2]).squaredNorm() + (triangle[2] - triangle[1]).squaredNorm()\n                );\n        }\n        //final cost\n        outputCost = costMain + positionPrior * costPrior;\n        //CI_LOG_I(\"Optimization: cost \" << outputCost << \", gradient \" << gradient.transpose());\n\n        return fullGradient;\n    }\n\n    VectorX InverseProblem_Adjoint_InitialConfiguration::gradientMesh_Numerical(\n        const SoftBodyMesh2D::Vector2List & targetPositions, SoftBodyMesh2D & simulation, \n        const VectorX & currentInitialPositions, real positionPrior, real & outputCost, BackgroundWorker * worker)\n    {\n        real poissonsRatio = simulation.getPoissonsRatio();\n        real youngsModulus = simulation.getYoungsModulus();\n        int n = simulation.getNumNodes();\n        for (int i = 0; i < n; ++i) {\n            simulation.getReferencePositions()[i] = currentInitialPositions.segment<2>(2 * i);\n        }\n\n        int p = simulation.getNumFreeNodes();\n        VectorX gradient = VectorX::Zero(2 * n);\n\n        // Reference forward problem\n        real materialMu, materialLambda;\n        SoftBodySimulation::computeMaterialParameters(youngsModulus, poissonsRatio, materialMu, materialLambda);\n        Matrix3 C = SoftBodySimulation::computeMaterialMatrix(materialMu, materialLambda);\n\n        MatrixX K = MatrixX::Zero(2 * p, 2 * p);\n        VectorX F = VectorX::Zero(2 * p);\n        simulation.assembleForceVector(F);\n        simulation.assembleStiffnessMatrix(C, K, &F, SoftBodyMesh2D::Vector2List(simulation.getNumNodes(), Vector2::Zero()));\n        VectorX u = K.partialPivLu().solve(F);\n        if (worker->isInterrupted()) return gradient;\n\n        real costReference = 0;\n        for (int i=0; i<p; ++i)\n        {\n            costReference += (currentInitialPositions.segment<2>(2 * simulation.getFreeToNodeMap()[i])\n                + u.segment<2>(2 * i)\n                - targetPositions[simulation.getFreeToNodeMap()[i]])\n                .squaredNorm() / 2;\n        }\n\n        //numerical differentiation\n        real epsilon = 1e-7;\n        for (int j=0; j<p; ++j)\n        {\n            for (int c=0; c<2; ++c)\n            {\n                VectorX positions = currentInitialPositions;\n                positions[2 * simulation.getFreeToNodeMap()[j] + c] += epsilon;\n                for (int i = 0; i < n; ++i) {\n                    simulation.getReferencePositions()[i] = positions.segment<2>(2 * i);\n                }\n                K.setZero();\n                F.setZero();\n                simulation.assembleForceVector(F);\n                simulation.assembleStiffnessMatrix(C, K, &F, SoftBodyMesh2D::Vector2List(simulation.getNumNodes(), Vector2::Zero()));\n                VectorX u = K.partialPivLu().solve(F);\n\t\t\t\tif (worker->isInterrupted()) return gradient;\n\n                real cost = 0;\n                for (int i = 0; i<p; ++i)\n                {\n                    cost += (positions.segment<2>(2 * simulation.getFreeToNodeMap()[i])\n                        + u.segment<2>(2 * i)\n                        - targetPositions[simulation.getFreeToNodeMap()[i]])\n                        .squaredNorm() / 2;\n                }\n                gradient[2 * simulation.getFreeToNodeMap()[j] + c] = (cost - costReference) / epsilon;\n            }\n        }\n\n        outputCost = costReference;\n        return gradient;\n    }\n\n\tInverseProblem_Adjoint_InitialConfiguration::grid_t InverseProblem_Adjoint_InitialConfiguration::gradientGrid_AdjointMethod(\n\t\tconst grid_t & targetSdf, SoftBodyGrid2D & simulation,\n\t\tconst grid_t & initialSdf, const GridPriors& priors,\n\t\treal & outputCost, BackgroundWorker * worker, bool onlyCost)\n\t{\n\t\t//only these modes are supported\n\t\tassert(simulation.isExplicitDiffusion());\n\t\tassert(simulation.isHardDirichletBoundaries());\n\t\tassert(simulation.getRotationCorrection() == SoftBodySimulation::RotationCorrection::None);\n        assert(simulation.getAdvectionMode() == SoftBodyGrid2D::AdvectionMode::DIRECT_FORWARD);\n\n\t\t//get settings from the simulation\n\t\treal poissonsRatio = simulation.getPoissonsRatio();\n\t\treal youngsModulus = simulation.getYoungsModulus();\n\t\tVector2 gravity = simulation.getGravity();\n\t\tint resolution = simulation.getGridResolution();\n\t\tVector2 size = simulation.getCellSize();\n\t\treal h = size.x();\n\n\t\t// allocate output\n\t\toutputCost = 0;\n\t\tgrid_t outputGradient = grid_t::Zero(resolution, resolution);\n\n\t\t//FORWARD\n\n\t\t//set initial / current SDF as the reference SDF in the simulation\n\t\t//and the degrees of freedom are computed as well\n\t\tsimulation.setSDF(initialSdf);\n\t\t//collect degrees of freedom in the stifness solve\n\t\tconst Eigen::MatrixXi& posToIndex = simulation.getPosToIndex();\n\t\tconst SoftBodyGrid2D::indexToPos_t& indexToPos = simulation.getIndexToPos();\n\t\tconst int dof = simulation.getDoF();\n\n\t\tMatrixX K = MatrixX::Zero(dof * 2, dof * 2);\n\t\tVectorX f = VectorX::Zero(dof * 2);\n\t\tconst VectorX prevU = VectorX::Zero(dof * 2); //previous displacements for rotation correction. Not needed here\n\n\t\t//assemble force vector f and stiffness matrix K\n\t\tVectorX collisionForces = VectorX::Zero(2 * dof);\n\t\tsimulation.assembleForceVector(f, posToIndex, collisionForces);\n\t\tif (worker->isInterrupted()) return outputGradient;\n\t\treal materialMu, materialLambda;\n\t\tSoftBodySimulation::computeMaterialParameters(youngsModulus, poissonsRatio, materialMu, materialLambda);\n\t\tMatrix3 C = SoftBodySimulation::computeMaterialMatrix(materialMu, materialLambda);\n\t\tsimulation.assembleStiffnessMatrix(C, materialMu, materialLambda, K, &f, posToIndex, prevU);\n\t\tif (worker->isInterrupted()) return outputGradient;\n\n\t\t//solve for the current displacement\n\t\tPartialPivLU<MatrixX> Klu = K.partialPivLu();\n\t\tVectorX u = Klu.solve(f);\n\t\tif (worker->isInterrupted()) return outputGradient;\n\n\t\t//map back to a grid\n\t\tgrid_t uGridX = grid_t::Zero(resolution, resolution);\n\t\tgrid_t uGridY = grid_t::Zero(resolution, resolution);\n\t\tfor (int i = 0; i < dof; ++i) {\n\t\t\tVector2i p = indexToPos.at(i);\n\t\t\tuGridX(p.x(), p.y()) = u[2 * i];\n\t\t\tuGridY(p.x(), p.y()) = u[2 * i + 1];\n\t\t}\n\t\tif (worker->isInterrupted()) return outputGradient;\n\n\t\t//perform diffusion step\n\t\tGridUtils2D::bgrid_t validCells = simulation.computeValidCells(uGridX, uGridY, posToIndex);\n\t\tuGridX = GridUtils2D::fillGridDiffusion(uGridX, validCells);\n\t\tuGridY = GridUtils2D::fillGridDiffusion(uGridY, validCells);\n\t\tif (worker->isInterrupted()) return outputGradient;\n\n\t\t//advect levelset\n\t\tgrid_t advectionWeights;\n\t\tgrid_t forwardSdf = GridUtils2D::advectGridDirectForward(initialSdf, uGridX, uGridY, -1 / h, &advectionWeights);\n\t\tif (worker->isInterrupted()) return outputGradient;\n\n\t\t//reconstruct SDF\n        GridUtils2D::RecoverSDFSussmannAdjointStorage recoveryStorage;\n        grid_t forwardSdf2 = simulation.getSdfRecoveryIterations() > 0\n            ? GridUtils2D::recoverSDFSussmann(forwardSdf, real(0.01), simulation.getSdfRecoveryIterations(), &recoveryStorage)\n\t\t\t: forwardSdf;\n\n\t\t// COST\n\t\tgrid_t costWeighting = advectionWeights.min(1);\n\t\toutputCost += gridCostSimilarity(forwardSdf, targetSdf, &costWeighting);\n\t\t// prior on the SDF\n\t\treal costPriorSdf = 0;\n\t\tgrid_t priorSdfGrad = GridUtils2D::recoverSDFSussmannGradient(initialSdf, initialSdf, GridUtils2D::bgrid_t::Constant(resolution, resolution, true), costPriorSdf, priors.sdfEpsilon);\n\t\toutputCost += priors.sdfPrior * costPriorSdf;\n\n        if (onlyCost)\n            return outputGradient;\n\n\t\t// BACKWARD\n\n\t\t//The derivative of the cost with respect to the forward (output) SDF\n\t\tgrid_t costDforwardSdf1 = gridCostSimilarityDerivative(forwardSdf2, targetSdf, &costWeighting);\n\n\t\t// propagate back, get the adjoint solutions\n\n        // Adjoint: recover SDF\n        grid_t adjOutputSdf = grid_t::Zero(resolution, resolution);\n        GridUtils2D::recoverSDFSussmannAdjoint(forwardSdf, forwardSdf2, costDforwardSdf1, adjOutputSdf, recoveryStorage);\n\n\t\t//Adjoint: advect levelset\n\t\tgrid_t adjInputSdf = grid_t::Zero(resolution, resolution);\n\t\tgrid_t adjUGridX = grid_t::Zero(resolution, resolution);\n\t\tgrid_t adjUGridY = grid_t::Zero(resolution, resolution);\n\t\tGridUtils2D::advectGridDirectForwardAdjoint(\n\t\t\tadjInputSdf, adjUGridX, adjUGridY, adjOutputSdf,\n\t\t\tuGridX, uGridY, initialSdf, forwardSdf, -1 / h, advectionWeights);\n\t\tif (worker->isInterrupted()) return outputGradient;\n\n\t\t//Adjoint: perform diffusion step\n\t\tGridUtils2D::fillGridDiffusionAdjoint(adjUGridX, adjUGridX, uGridX, validCells); //note that the adjoint is both input and output\n\t\tGridUtils2D::fillGridDiffusionAdjoint(adjUGridY, adjUGridY, uGridY, validCells); //it is modified in-place\n\t\tif (worker->isInterrupted()) return outputGradient;\n\n\t\t//Adjoint: map back to a grid\n\t\tVectorX adjU(2 * dof);\n\t\tfor (int i = 0; i < dof; ++i) {\n\t\t\tVector2i p = indexToPos.at(i);\n\t\t\tadjU[2 * i] = adjUGridX(p.x(), p.y());\n\t\t\tadjU[2 * i + 1] = adjUGridY(p.x(), p.y());\n\t\t}\n\t\tif (worker->isInterrupted()) return outputGradient;\n\n\t\t//Adjoint: solve for the current displacement\n\t\t//since K is symmetric, I can use K directly instead of K' as normally required by the Adjoint Method.\n\t\tVectorX lambdaU = Klu.solve(adjU);\n\t\tif (worker->isInterrupted()) return outputGradient;\n\n\t\t// DERIVATIVES OF THE UNKNOWNS\n\t\t// Matrix-Free assembly of y'F, y = (lambdaU, adjInputSdf)\n\n\t\t// advection / currentSdf\n\t\tgrid_t gradientAdvection \n    \t\t= GridUtils2D::advectGridDirectForwardAdjOpMult(adjInputSdf, uGridX, uGridY, -1 / h, advectionWeights);\n\n\t\t// elasticity / lambdaU -> compute element-wise\n        grid_t gradientElasticity =\n            gridElasticityAdjOpMult(lambdaU, u, initialSdf,\n                gravity, C, simulation, posToIndex);\n\n\t\t// ASSEMBLE FINAL GRADIENT\n\t\tgrid_t gradientPriors = grid_t::Zero(resolution, resolution); //(r in the notes)\n\t\tgradientPriors += priorSdfGrad.unaryExpr([&priors](real v)\n\t\t{\n\t\t\treturn priors.sdfPrior * std::clamp(v, -priors.sdfMaxDistance, priors.sdfMaxDistance);\n\t\t});\n\t\toutputGradient = gradientAdvection + gradientElasticity + gradientPriors;\n\n        CI_LOG_I(\"Optimize: cost \" << outputCost);\n\n\t\treturn outputGradient;\n\t}\n\n\tvoid InverseProblem_Adjoint_InitialConfiguration::setupParams(cinder::params::InterfaceGlRef params,\n\t\tconst std::string& group)\n\t{\n\t\tparams->addParam(\"InverseProblem_Adjoint_InitialConfiguration_PositionPrior\", &meshPositionPrior)\n\t\t\t.group(group).label(\"Mesh Prior - Initial Positions\").min(0).step(0.01);\n        params->addParam(\"InverseProblem_Adjoint_InitialConfiguration_SDFPrior1\", &gridPriors.sdfPrior)\n            .group(group).label(\"Grid Prior - Weight on SDF\").min(0).step(0.01);\n\t\tparams->addParam(\"InverseProblem_Adjoint_InitialConfiguration_SDFPrior2\", &gridPriors.sdfEpsilon)\n\t\t\t.group(group).label(\"Grid Prior - SDF Epsilon\").min(0).step(0.01);\n\t\tparams->addParam(\"InverseProblem_Adjoint_InitialConfiguration_SDFPrior3\", &gridPriors.sdfMaxDistance)\n\t\t\t.group(group).label(\"Grid Prior - SDF Max distance\").min(0).step(0.1);\n\t\tparams->addParam(\"InverseProblem_Adjoint_InitialConfiguration_GridHyperEpsilon\", &gridHyperEpsilon)\n\t\t\t.group(group).label(\"Grid Hyper Epsilon\").min(0).step(0.01);\n\t\tparams->addParam(\"InverseProblem_Adjoint_InitialConfiguration_NumIterations\", &numIterations)\n\t\t\t.group(group).label(\"Iterations\").min(1);\n\t}\n\n\tvoid InverseProblem_Adjoint_InitialConfiguration::setParamsVisibility(cinder::params::InterfaceGlRef params,\n\t\tbool visible) const\n\t{\n\t\tstd::string option = visible ? \"visible=true\" : \"visible=false\";\n\t\tparams->setOptions(\"InverseProblem_Adjoint_InitialConfiguration_PositionPrior\", option);\n        params->setOptions(\"InverseProblem_Adjoint_InitialConfiguration_SDFPrior1\", option);\n\t\tparams->setOptions(\"InverseProblem_Adjoint_InitialConfiguration_SDFPrior2\", option);\n\t\tparams->setOptions(\"InverseProblem_Adjoint_InitialConfiguration_SDFPrior3\", option);\n\t\tparams->setOptions(\"InverseProblem_Adjoint_InitialConfiguration_GridHyperEpsilon\", option);\n\t\tparams->setOptions(\"InverseProblem_Adjoint_InitialConfiguration_NumIterations\", option);\n\t}\n\n\tVectorX InverseProblem_Adjoint_InitialConfiguration::linearizePositions(const SoftBodyMesh2D::Vector2List & positions)\n    {\n        size_t n = positions.size();\n        VectorX x(n*2);\n        for (size_t i=0; i<n; ++i)\n        {\n            x.segment<2>(2 * i) = positions[i];\n        }\n        return x;\n    }\n\n    SoftBodyMesh2D::Vector2List InverseProblem_Adjoint_InitialConfiguration::delinearizePositions(const VectorX & linearizedPositions)\n    {\n        size_t n = linearizedPositions.size() / 2;\n        SoftBodyMesh2D::Vector2List l(n);\n        for (size_t i=0; i<n; ++i)\n        {\n            l[i] = linearizedPositions.segment<2>(2 * i);\n        }\n        return l;\n    }\n\n    real InverseProblem_Adjoint_InitialConfiguration::meshTriangleArea(const triangle_t & triangle)\n    {\n        return ((triangle[1].x() - triangle[0].x())*(triangle[2].y() - triangle[0].y()) - (triangle[2].x() - triangle[0].x())*(triangle[1].y() - triangle[0].y())) / 2;\n    }\n\n\tint InverseProblem_Adjoint_InitialConfiguration::meshTriangleWindingOrder(const triangle_t & triangle)\n\t{\n\t\treturn meshTriangleArea(triangle) > 0 ? 1 : -1;\n\t}\n\n    std::array<real, 6> InverseProblem_Adjoint_InitialConfiguration::meshTriangleAreaDerivative(const triangle_t & triangle)\n    {\n        return std::array<real, 6>({\n            (triangle[1].y() - triangle[2].y()) / 2,\n            (triangle[2].x() - triangle[1].x()) / 2,\n            (triangle[2].y() - triangle[0].y()) / 2,\n            (triangle[0].x() - triangle[2].x()) / 2,\n            (triangle[0].y() - triangle[1].y()) / 2,\n            (triangle[1].x() - triangle[0].x()) / 2\n        });\n    }\n\n    Matrix36 InverseProblem_Adjoint_InitialConfiguration::meshDerivativeMatrix(const triangle_t & triangle)\n    {\n        Matrix36 Be;\n        Be << (triangle[1].y() - triangle[2].y()), 0, (triangle[2].y() - triangle[0].y()), 0, (triangle[0].y() - triangle[1].y()), 0,\n            0, (triangle[2].x() - triangle[1].x()), 0, (triangle[0].x() - triangle[2].x()), 0, (triangle[1].x() - triangle[0].x()),\n            (triangle[2].x() - triangle[1].x()), (triangle[1].y() - triangle[2].y()), (triangle[0].x() - triangle[2].x()), (triangle[2].y() - triangle[0].y()), (triangle[1].x() - triangle[0].x()), (triangle[0].y() - triangle[1].y());\n        Be *= (1 / meshTriangleArea(triangle));\n        return Be;\n    }\n\n    Matrix36 InverseProblem_Adjoint_InitialConfiguration::meshDerivativeMatrixDerivative(const triangle_t & triangle, int i)\n    {\n        static const std::array<Matrix36, 6> Bprime = {\n            (Matrix36() << 0,0,0,0,0,0, 0,0,0,1,0,-1, 0,0,1,0,-1,0).finished(), //d x1\n            (Matrix36() << 0,0,-1,0,1,0, 0,0,0,0,0,0, 0,0,0,-1,0,1).finished(), //d y1\n            (Matrix36() << 0,0,0,0,0,0, 0,-1,0,0,0,1, -1,0,0,0,1,0).finished(), //d x2\n            (Matrix36() << 1,0,0,0,-1,0, 0,0,0,0,0,0, 0,1,0,0,0,-1).finished(), //d y2\n            (Matrix36() << 0,0,0,0,0,0, 0,1,0,-1,0,0, 1,0,-1,0,0,0).finished(), //d x3\n            (Matrix36() << -1,0,1,0,0,0, 0,0,0,0,0,0, 0,-1,0,1,0,0).finished()  //d y3\n        };\n        //return (1 / meshTriangleArea(triangle)) * (Bprime[i] - meshDerivativeMatrix(triangle) * meshTriangleAreaDerivative(triangle)[i]);\n        real area = meshTriangleArea(triangle);\n        return (Bprime[i] / area - meshDerivativeMatrix(triangle)*meshTriangleAreaDerivative(triangle)[i] / area);\n    }\n\n    Matrix6 InverseProblem_Adjoint_InitialConfiguration::meshStiffnessMatrix(const triangle_t & triangle, const Matrix3 & C)\n    {\n        Matrix36 Be = meshDerivativeMatrix(triangle);\n        return abs(meshTriangleArea(triangle)) * Be.transpose() * C * Be;\n    }\n\n    Matrix6 InverseProblem_Adjoint_InitialConfiguration::meshStiffnessMatrixDerivative(const triangle_t & triangle, int i, const Matrix3& C, int windingOrder)\n    {\n        Matrix36 Be = meshDerivativeMatrix(triangle);\n        Matrix36 BePrime = meshDerivativeMatrixDerivative(triangle, i);\n        return windingOrder * (meshTriangleAreaDerivative(triangle)[i] * (Be.transpose() * C * Be)\n             + meshTriangleArea(triangle) * (BePrime.transpose() * C * Be + Be.transpose() * C * BePrime));\n    }\n\n\tVector6 InverseProblem_Adjoint_InitialConfiguration::meshForce(const triangle_t & triangle, const Vector2 & gravity)\n\t{\n\t\treturn abs(meshTriangleArea(triangle)) * (Vector6() << gravity, gravity, gravity).finished();\n\t}\n\n\tVector6 InverseProblem_Adjoint_InitialConfiguration::meshForceDerivative(const triangle_t & triangle, int i, const Vector2 & gravity, int windingOrder)\n\t{\n\t\treturn meshTriangleAreaDerivative(triangle)[i] * windingOrder * (Vector6() << gravity, gravity, gravity).finished();\n\t}\n\n\treal InverseProblem_Adjoint_InitialConfiguration::gridCostSimilarity(\n\t\tconst grid_t & currentPhi, const grid_t & targetPhi, \n\t\tconst grid_t * weighting)\n\t{\n\t\tif (weighting)\n\t\t\treturn ((*weighting) * (currentPhi.unaryExpr(&sdfTransformFun) - targetPhi.unaryExpr(&sdfTransformFun))).matrix().squaredNorm() / 2;\n\t\telse\n\t\t\treturn (currentPhi.unaryExpr(&sdfTransformFun) - targetPhi.unaryExpr(&sdfTransformFun)).matrix().squaredNorm() / 2;\n\t}\n\n\tInverseProblem_Adjoint_InitialConfiguration::grid_t InverseProblem_Adjoint_InitialConfiguration::gridCostSimilarityDerivative(\n\t\tconst grid_t& currentPhi, const grid_t& targetPhi,\n\t\tconst grid_t* weighting)\n\t{\n\t\tif (weighting)\n\t\t\treturn currentPhi.unaryExpr(&sdfTransformFunDerivative) * (*weighting) * (*weighting) * (currentPhi.unaryExpr(&sdfTransformFun) - targetPhi.unaryExpr(&sdfTransformFun));\n\t\telse\n\t\t\treturn currentPhi.unaryExpr(&sdfTransformFunDerivative) * (currentPhi.unaryExpr(&sdfTransformFun) - targetPhi.unaryExpr(&sdfTransformFun));\n\t}\n\n\tstd::array<Vector8, 4> InverseProblem_Adjoint_InitialConfiguration::gridGravityForceDerivative(\n\t\tconst std::array<real, 4>& sdfs, const Vector2& gravity, const SoftBodyGrid2D& simulation)\n\t{\n\t\tVector8 bodyForces;\n\t\tbodyForces << gravity, gravity, gravity, gravity;\n\t\tstd::array<real, 4> derivatives = Integration2D<real>::integrateQuadDsdf<real>(simulation.getCellSize(), sdfs, { 1,1,1,1 });\n\t\treturn {\n\t\t\tbodyForces * derivatives[0],\n\t\t\tbodyForces * derivatives[1],\n\t\t\tbodyForces * derivatives[2],\n\t\t\tbodyForces * derivatives[3]\n\t\t};\n\t}\n\n\tVector8 InverseProblem_Adjoint_InitialConfiguration::gridGravityForce(const std::array<real, 4>& sdfs,\n\t\tconst Vector2& gravity, const SoftBodyGrid2D& simulation)\n\t{\n\t\tVector8 bodyForces;\n\t\tbodyForces << gravity, gravity, gravity, gravity;\n\t\treturn bodyForces * Integration2D<real>::integrateQuad<real>(simulation.getCellSize(), sdfs, { 1,1,1,1 });\n\t}\n\n\tstd::array<Matrix8, 4> InverseProblem_Adjoint_InitialConfiguration::gridStiffnessMatrixDerivative(\n\t\tconst std::array<real, 4>& sdfs, const Matrix3& C, const SoftBodyGrid2D& simulation)\n\t{\n\t\tarray<Matrix8, 4> Kex = {\n\t\t\tsimulation.getB1().transpose() * C * simulation.getB1(),\n\t\t\tsimulation.getB2().transpose() * C * simulation.getB2(),\n\t\t\tsimulation.getB3().transpose() * C * simulation.getB3(),\n\t\t\tsimulation.getB4().transpose() * C * simulation.getB4(),\n\t\t};\n\t\treturn Integration2D<real>::integrateQuadDsdf(simulation.getCellSize(), sdfs, Kex);\n\t}\n\n\tMatrix8 InverseProblem_Adjoint_InitialConfiguration::gridStiffnessMatrix(const std::array<real, 4>& sdfs,\n\t\tconst Matrix3& C, const SoftBodyGrid2D& simulation)\n\t{\n\t\tarray<Matrix8, 4> Kex = {\n\t\t\tsimulation.getB1().transpose() * C * simulation.getB1(),\n\t\t\tsimulation.getB2().transpose() * C * simulation.getB2(),\n\t\t\tsimulation.getB3().transpose() * C * simulation.getB3(),\n\t\t\tsimulation.getB4().transpose() * C * simulation.getB4(),\n\t\t};\n\t\treturn Integration2D<real>::integrateQuad(simulation.getCellSize(), sdfs, Kex);\n\t}\n\n\tInverseProblem_Adjoint_InitialConfiguration::grid_t InverseProblem_Adjoint_InitialConfiguration::gridElasticityAdjOpMult(\n        const VectorX & lambdaU, const VectorX& u, const grid_t & sdf,\n        const Vector2 & gravity, const Matrix3 & C, const SoftBodyGrid2D & simulation,\n        const Eigen::MatrixXi & posToIndex)\n    {\n\t\t////Test: not matrix-free\n\t\t//int dof = lambdaU.size() / 2;\n\t\t//MatrixX F = MatrixX::Zero(2 * dof, dof);\n\n        int resolution = simulation.getGridResolution();\n        grid_t gradientElasticity = grid_t::Zero(resolution, resolution);\n        for (int xy = 0; xy < (resolution - 1)*(resolution - 1); ++xy) {\n            int x = xy / (resolution - 1);\n            int y = xy % (resolution - 1);\n\n            array<real, 4> sdfs = { sdf(x, y), sdf(x + 1,y), sdf(x, y + 1), sdf(x + 1, y + 1) };\n            if (utils::outside(sdfs[0]) && utils::outside(sdfs[1]) && utils::outside(sdfs[2]) && utils::outside(sdfs[3])) continue;\n\n            std::array<Vector8, 4> FeDphi = gridGravityForceDerivative(sdfs, gravity, simulation);\n            std::array<Matrix8, 4> KeDphi = gridStiffnessMatrixDerivative(sdfs, C, simulation);\n\n            int mapping[4] = {\n                posToIndex(x, y),\n                posToIndex(x + 1, y),\n                posToIndex(x, y + 1),\n                posToIndex(x + 1, y + 1)\n            };\n            bool dirichlet[4] = {\n                simulation.getGridDirichlet()(x, y),\n                simulation.getGridDirichlet()(x + 1, y),\n                simulation.getGridDirichlet()(x, y + 1),\n                simulation.getGridDirichlet()(x + 1, y + 1)\n            };\n            Vector8 ue;\n            Vector8 lambdaUE;\n            for (int i = 0; i < 4; ++i) {\n                ue.segment<2>(2 * i) = u.segment<2>(2 * mapping[i]);\n                lambdaUE.segment<2>(2 * i) = lambdaU.segment<2>(2 * mapping[i]);\n            }\n            for (int i = 0; i < 4; ++i) {\n                if (dirichlet[i]) continue;\n                Vector8 EeDphi = -(KeDphi[i] * ue - FeDphi[i]);\n                gradientElasticity(x + (i % 2), y + (i / 2)) += lambdaUE.dot(EeDphi);\n\t\t\t\t//for (int j=0; j<4; ++j)\n\t\t\t\t//{\n\t\t\t\t//\tF.block<2, 1>(2 * mapping[j], mapping[i]) += EeDphi.segment<2>(2 * j);\n\t\t\t\t//}\n            }\n        }\n\n\t\t//VectorX result = lambdaU.transpose() * F;\n\t\t//for (int x=0; x<resolution; ++x) for (int y=0; y<resolution; ++y)\n\t\t//{\n\t\t//\tint i = posToIndex(x, y);\n\t\t//\tif (i >= 0)\n\t\t//\t\tgradientElasticity(x, y) = result[i];\n\t\t//}\n\n        return gradientElasticity;\n    }\n}\n", "meta": {"hexsha": "6037c5e7c5c1423d76d8f4d34c84f661ed78b868", "size": 47237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ActionReconstructionLib/InverseProblem_Adjoint_InitialConfiguration.cpp", "max_stars_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_stars_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-03-08T18:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T20:32:56.000Z", "max_issues_repo_path": "ActionReconstructionLib/InverseProblem_Adjoint_InitialConfiguration.cpp", "max_issues_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_issues_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ActionReconstructionLib/InverseProblem_Adjoint_InitialConfiguration.cpp", "max_forks_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_forks_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-26T01:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T13:32:46.000Z", "avg_line_length": 45.5955598456, "max_line_length": 233, "alphanum_fraction": 0.6542117408, "num_tokens": 12664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.510350279971517}}
{"text": "/**\n * \\file TimeVaryingSecondOrderSVFFilter.cpp\n */\n\n#include \"TimeVaryingSecondOrderSVFFilter.h\"\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cassert>\n\nnamespace ATK\n{\n  template<typename SVFCoefficients>\n  class TimeVaryingSecondOrderSVFFilter<SVFCoefficients>::SVFState\n  {\n  public:\n    typename SVFCoefficients::DataType iceq1{0};\n    typename SVFCoefficients::DataType iceq2{0};\n  };\n  \n  template<typename SVFCoefficients>\n  TimeVaryingSecondOrderSVFFilter<SVFCoefficients>::TimeVaryingSecondOrderSVFFilter(gsl::index nb_channels)\n  :SVFCoefficients(nb_channels), state(std::make_unique<SVFState[]>(nb_channels))\n  {\n  }\n\n  template<typename SVFCoefficients>\n  TimeVaryingSecondOrderSVFFilter<SVFCoefficients>::~TimeVaryingSecondOrderSVFFilter()\n  {\n  }\n\n  template<typename SVFCoefficients>\n  void TimeVaryingSecondOrderSVFFilter<SVFCoefficients>::full_setup()\n  {\n    state = std::make_unique<SVFState[]>(nb_input_ports - 1);\n  }\n\n  template<typename DataType>\n  void TimeVaryingSecondOrderSVFFilter<DataType>::process_impl(gsl::index size) const\n  {\n    assert(nb_input_ports - 1 == nb_output_ports);\n\n    for(gsl::index i = 0; i < size; ++i)\n    {\n      update_coeffs(converted_inputs[0][i]);\n      \n      for(gsl::index j = 0; j < nb_input_ports - 1; ++j)\n      {\n        const DataType* ATK_RESTRICT input = converted_inputs[j+1];\n        DataType* ATK_RESTRICT output = outputs[j];\n\n        DataType v3 = input[i] - state[j].iceq2;\n        DataType v1 = a1 * state[j].iceq1 + a2 * v3;\n        DataType v2 = state[j].iceq2 + a2 * state[j].iceq1 + a3 * v3;\n        state[j].iceq1 = 2 * v1 - state[j].iceq1;\n        state[j].iceq2 = 2 * v2 - state[j].iceq2;\n        \n        output[i] = m0 * input[i] + m1 * v1 + m2 * v2;\n      }\n    }\n  }\n  \n  template<typename DataType>\n  TimeVaryingSecondOrderSVFBaseCoefficients<DataType>::TimeVaryingSecondOrderSVFBaseCoefficients(gsl::index nb_channels)\n  :TypedBaseFilter<DataType>(1 + nb_channels, nb_channels)\n  {\n  }\n\n  template<typename DataType_>\n  void TimeVaryingSecondOrderSVFBaseCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    if(Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be strictly positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template<typename DataType>\n  DataType TimeVaryingSecondOrderSVFBaseCoefficients<DataType>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType_>\n  TimeVaryingSecondOrderSVFLowPassCoefficients<DataType_>::TimeVaryingSecondOrderSVFLowPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void TimeVaryingSecondOrderSVFLowPassCoefficients<DataType>::update_coeffs(DataType g) const\n  {\n    auto k = 1/Q;\n    a1 = 1 / (1 + g * (g + k));\n    a2 = g * a1;\n    a3 = g * a2;\n    m0 = 0;\n    m1 = 0;\n    m2 = 1;\n  }\n\n  template<typename DataType_>\n  TimeVaryingSecondOrderSVFBandPassCoefficients<DataType_>::TimeVaryingSecondOrderSVFBandPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void TimeVaryingSecondOrderSVFBandPassCoefficients<DataType>::update_coeffs(DataType g) const\n  {\n    auto k = 1 / Q;\n    a1 = 1 / (1 + g * (g + k));\n    a2 = g * a1;\n    a3 = g * a2;\n    m0 = 0;\n    m1 = 1;\n    m2 = 0;\n  }\n\n  template<typename DataType_>\n  TimeVaryingSecondOrderSVFHighPassCoefficients<DataType_>::TimeVaryingSecondOrderSVFHighPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void TimeVaryingSecondOrderSVFHighPassCoefficients<DataType>::update_coeffs(DataType g) const\n  {\n    auto k = 1 / Q;\n    a1 = 1 / (1 + g * (g + k));\n    a2 = g * a1;\n    a3 = g * a2;\n    m0 = 1;\n    m1 = -k;\n    m2 = -1;\n  }\n\n  template<typename DataType_>\n  TimeVaryingSecondOrderSVFNotchCoefficients<DataType_>::TimeVaryingSecondOrderSVFNotchCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void TimeVaryingSecondOrderSVFNotchCoefficients<DataType>::update_coeffs(DataType g) const\n  {\n    auto k = 1 / Q;\n    a1 = 1 / (1 + g * (g + k));\n    a2 = g * a1;\n    a3 = g * a2;\n    m0 = 1;\n    m1 = -k;\n    m2 = 0;\n  }\n\n  template<typename DataType_>\n  TimeVaryingSecondOrderSVFPeakCoefficients<DataType_>::TimeVaryingSecondOrderSVFPeakCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void TimeVaryingSecondOrderSVFPeakCoefficients<DataType>::update_coeffs(DataType g) const\n  {\n    auto k = 1 / Q;\n    a1 = 1 / (1 + g * (g + k));\n    a2 = g * a1;\n    a3 = g * a2;\n    m0 = 1;\n    m1 = -k;\n    m2 = 2;\n  }\n\n  template<typename DataType_>\n  TimeVaryingSecondOrderSVFBellCoefficients<DataType_>::TimeVaryingSecondOrderSVFBellCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n    \n  }\n  \n  template<typename DataType_>\n  void TimeVaryingSecondOrderSVFBellCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    if(gain <= 0)\n    {\n      throw std::out_of_range(\"Gain must be strictly positive\");\n    }\n    this->gain = gain;\n    setup();\n  }\n\n  template<typename DataType>\n  DataType TimeVaryingSecondOrderSVFBellCoefficients<DataType>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType>\n  void TimeVaryingSecondOrderSVFBellCoefficients<DataType>::update_coeffs(DataType g) const\n  {\n    auto k = 1 / (Q * gain);\n    a1 = 1 / (1 + g * (g + k));\n    a2 = g * a1;\n    a3 = g * a2;\n    m0 = 1;\n    m1 = k * (gain * gain - 1);\n    m2 = 0;\n  }\n\n  template<typename DataType_>\n  TimeVaryingSecondOrderSVFLowShelfCoefficients<DataType_>::TimeVaryingSecondOrderSVFLowShelfCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n    \n  }\n\n  template<typename DataType_>\n  void TimeVaryingSecondOrderSVFLowShelfCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    this->gain = gain;\n    setup();\n  }\n\n  template<typename DataType>\n  DataType TimeVaryingSecondOrderSVFLowShelfCoefficients<DataType>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType>\n  void TimeVaryingSecondOrderSVFLowShelfCoefficients<DataType>::update_coeffs(DataType g) const\n  {\n    auto k = 1 / Q;\n    a1 = 1 / (1 + g * (g + k));\n    a2 = g * a1;\n    a3 = g * a2;\n    m0 = 1;\n    m1 = k * (gain - 1);\n    m2 = gain * gain - 1;\n  }\n\n  template<typename DataType_>\n  TimeVaryingSecondOrderSVFHighShelfCoefficients<DataType_>::TimeVaryingSecondOrderSVFHighShelfCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType_>\n  void TimeVaryingSecondOrderSVFHighShelfCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    this->gain = gain;\n    setup();\n  }\n\n  template<typename DataType>\n  DataType TimeVaryingSecondOrderSVFHighShelfCoefficients<DataType>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType>\n  void TimeVaryingSecondOrderSVFHighShelfCoefficients<DataType>::update_coeffs(DataType g) const\n  {\n    auto k = 1 / (Q* gain);\n    a1 = 1 / (1 + g * (g + k));\n    a2 = g * a1;\n    a3 = g * a2;\n    m0 = gain * gain;\n    m1 = k * (1 - gain) * gain;\n    m2 = 1 - gain * gain;\n  }\n\n#if ATK_ENABLE_INSTANTIATION\n  template class TimeVaryingSecondOrderSVFBaseCoefficients<float>;\n\n  template class TimeVaryingSecondOrderSVFLowPassCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFBandPassCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFHighPassCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFNotchCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFPeakCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFBellCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFLowShelfCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFHighShelfCoefficients<float>;\n\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFLowPassCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFBandPassCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFHighPassCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFNotchCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFPeakCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFBellCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFLowShelfCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFHighShelfCoefficients<float> >;\n#endif\n  template class TimeVaryingSecondOrderSVFBaseCoefficients<double>;\n\n  template class TimeVaryingSecondOrderSVFLowPassCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFBandPassCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFHighPassCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFNotchCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFPeakCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFBellCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFLowShelfCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFHighShelfCoefficients<double>;\n\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFLowPassCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFBandPassCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFHighPassCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFNotchCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFPeakCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFBellCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFLowShelfCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFHighShelfCoefficients<double> >;\n}\n", "meta": {"hexsha": "edb7f72d879d9be4950ff70be565219285628d35", "size": 10021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/TimeVaryingSecondOrderSVFFilter.cpp", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "ATK/EQ/TimeVaryingSecondOrderSVFFilter.cpp", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "ATK/EQ/TimeVaryingSecondOrderSVFFilter.cpp", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 31.7120253165, "max_line_length": 131, "alphanum_fraction": 0.7411435984, "num_tokens": 2971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5103502744928085}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2012-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#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_BUFFER_JOIN_ROUND_BY_DIVIDE_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_BUFFER_JOIN_ROUND_BY_DIVIDE_HPP\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/policies/compare.hpp>\n#include <boost/geometry/strategies/buffer.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n#ifdef BOOST_GEOMETRY_DEBUG_BUFFER_WARN\n#include <boost/geometry/io/wkt/wkt.hpp>\n#endif\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\n\nnamespace strategy { namespace buffer\n{\n\n\nclass join_round_by_divide\n{\npublic :\n\n    inline join_round_by_divide(std::size_t max_level = 4)\n        : m_max_level(max_level)\n    {}\n\n    template\n    <\n        typename PromotedType,\n        typename Point,\n        typename DistanceType,\n        typename RangeOut\n    >\n    inline void mid_points(Point const& vertex,\n                Point const& p1, Point const& p2,\n                DistanceType const& buffer_distance,\n                RangeOut& range_out,\n                std::size_t level = 1) const\n    {\n        typedef typename coordinate_type<Point>::type coordinate_type;\n\n        // Generate 'vectors'\n        coordinate_type const vp1_x = get<0>(p1) - get<0>(vertex);\n        coordinate_type const vp1_y = get<1>(p1) - get<1>(vertex);\n\n        coordinate_type const vp2_x = (get<0>(p2) - get<0>(vertex));\n        coordinate_type const vp2_y = (get<1>(p2) - get<1>(vertex));\n\n        // Average them to generate vector in between\n        coordinate_type const two = 2;\n        coordinate_type const v_x = (vp1_x + vp2_x) / two;\n        coordinate_type const v_y = (vp1_y + vp2_y) / two;\n\n        PromotedType const length2 = geometry::math::sqrt(v_x * v_x + v_y * v_y);\n\n        PromotedType prop = buffer_distance / length2;\n\n        Point mid_point;\n        set<0>(mid_point, get<0>(vertex) + v_x * prop);\n        set<1>(mid_point, get<1>(vertex) + v_y * prop);\n\n        if (level < m_max_level)\n        {\n            mid_points<PromotedType>(vertex, p1, mid_point, buffer_distance, range_out, level + 1);\n        }\n        range_out.push_back(mid_point);\n        if (level < m_max_level)\n        {\n            mid_points<PromotedType>(vertex, mid_point, p2, buffer_distance, range_out, level + 1);\n        }\n    }\n\n    template <typename Point, typename DistanceType, typename RangeOut>\n    inline bool apply(Point const& ip, Point const& vertex,\n                Point const& perp1, Point const& perp2,\n                DistanceType const& buffer_distance,\n                RangeOut& range_out) const\n    {\n        typedef typename coordinate_type<Point>::type coordinate_type;\n\n        typedef typename geometry::select_most_precise\n            <\n                coordinate_type,\n                double\n            >::type promoted_type;\n\n        geometry::equal_to<Point> equals;\n\n        if (equals(perp1, perp2))\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_BUFFER_WARN\n            std::cout << \"Corner for equal points \" << geometry::wkt(ip) << \" \" << geometry::wkt(perp1) << std::endl;\n#endif\n            return false;\n        }\n\n        // Generate 'vectors'\n        coordinate_type const vix = (get<0>(ip) - get<0>(vertex));\n        coordinate_type const viy = (get<1>(ip) - get<1>(vertex));\n\n        promoted_type const length_i = geometry::math::sqrt(vix * vix + viy * viy);\n\n        promoted_type const bd = geometry::math::abs(buffer_distance);\n        promoted_type prop = bd / length_i;\n\n        Point bp;\n        set<0>(bp, get<0>(vertex) + vix * prop);\n        set<1>(bp, get<1>(vertex) + viy * prop);\n\n        range_out.push_back(perp1);\n\n        if (m_max_level > 1)\n        {\n            mid_points<promoted_type>(vertex, perp1, bp, bd, range_out);\n            range_out.push_back(bp);\n            mid_points<promoted_type>(vertex, bp, perp2, bd, range_out);\n        }\n        else if (m_max_level == 1)\n        {\n            range_out.push_back(bp);\n        }\n\n        range_out.push_back(perp2);\n        return true;\n    }\n\n    template <typename NumericType>\n    static inline NumericType max_distance(NumericType const& distance)\n    {\n        return distance;\n    }\n\nprivate :\n    std::size_t m_max_level;\n};\n\n\n}} // namespace strategy::buffer\n\n\n}} // namespace geofeatures_boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_BUFFER_JOIN_ROUND_BY_DIVIDE_HPP\n", "meta": {"hexsha": "411a595f288a778d3fb9a1179f634c32f7531d6e", "size": 4751, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/strategies/cartesian/buffer_join_round_by_divide.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T05:35:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-24T14:21:59.000Z", "max_issues_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/strategies/cartesian/buffer_join_round_by_divide.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T16:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-17T00:54:32.000Z", "max_forks_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/strategies/cartesian/buffer_join_round_by_divide.hpp", "max_forks_repo_name": "xarvey/Yuuuuuge", "max_forks_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T03:11:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-21T07:16:29.000Z", "avg_line_length": 30.6516129032, "max_line_length": 117, "alphanum_fraction": 0.6394443275, "num_tokens": 1173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5103502744928083}}
{"text": "#include <memory>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <ceres/ceres.h>\n#include <ceres/gradient_checker.h>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n#include <maplab-common/gravity-provider.h>\n#include <maplab-common/pose_types.h>\n#include <maplab-common/test/testing-entrypoint.h>\n#include <maplab-common/test/testing-predicates.h>\n\n#include \"ceres-error-terms/inertial-error-term-eigen.h\"\n#include \"ceres-error-terms/parameterization/quaternion-param-eigen.h\"\n\nusing ceres_error_terms::InertialErrorTermEigen;\n\nclass PosegraphErrorTermsEigen : public ::testing::Test {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n protected:\n  virtual void SetUp() {\n    rot0_.coeffs() << 0, 0, 0, 1;\n    rot1_.coeffs() << 0, 0, 0, 1;\n    pos0_ << 0, 0, 0;\n    pos1_ << 1.5, 0, 0;\n\n    accel_bias0_ << 0, 0, 0;\n    accel_bias1_ << 0, 0, 0;\n    gyro_bias0_ << 0, 0, 0;\n    gyro_bias1_ << 0, 0, 0;\n\n    velocity0_ << 1, 0, 0;\n    velocity1_ << 2, 0, 0;\n\n    common::GravityProvider gravity_provider(\n        common::locations::kAltitudeZurichMeters,\n        common::locations::kLatitudeZurichDegrees);\n    gravity_magnitude_ = gravity_provider.getGravityMagnitude();\n\n    imu_timestamps_ns_ << 0, 0.5 * 1e9, 1.0 * 1e9;\n    imu_data_ << 1, 1, 1, 0, 0, 0, gravity_magnitude_, gravity_magnitude_,\n        gravity_magnitude_, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n  }\n\n  void addResidual();\n  void solve();\n  void checkGradient();\n\n  ceres::Problem problem_;\n  ceres::Solver::Summary summary_;\n\n  Eigen::Matrix<int64_t, 1, 3> imu_timestamps_ns_;\n  Eigen::Matrix<double, 6, 3> imu_data_;\n\n  Eigen::Quaterniond rot0_;\n  Eigen::Quaterniond rot1_;\n  Eigen::Vector3d pos0_;\n  Eigen::Vector3d pos1_;\n\n  Eigen::Vector3d accel_bias0_;\n  Eigen::Vector3d accel_bias1_;\n  Eigen::Vector3d gyro_bias0_;\n  Eigen::Vector3d gyro_bias1_;\n\n  Eigen::Vector3d velocity0_;\n  Eigen::Vector3d velocity1_;\n\n  Eigen::Matrix<double, 6, 1> imu_bias0_;\n  Eigen::Matrix<double, 6, 1> imu_bias1_;\n\n  double gravity_magnitude_;\n};\n\nvoid PosegraphErrorTermsEigen::addResidual() {\n  rot0_.normalize();\n  rot1_.normalize();\n  imu_bias0_ << gyro_bias0_, accel_bias0_;\n  imu_bias1_ << gyro_bias1_, accel_bias1_;\n\n  ceres::CostFunction* inertial_term_cost =\n      new ceres_error_terms::InertialErrorTermEigen(\n          imu_data_, imu_timestamps_ns_, 1, 1, 1, 1, gravity_magnitude_);\n\n  problem_.AddResidualBlock(\n      inertial_term_cost, NULL, rot0_.coeffs().data(), pos0_.data(),\n      velocity0_.data(), imu_bias0_.data(), rot1_.coeffs().data(), pos1_.data(),\n      velocity1_.data(), imu_bias1_.data());\n\n  ceres::LocalParameterization* quaternion_parameterization =\n      new ceres_error_terms::EigenQuaternionParameterization;\n  problem_.SetParameterization(\n      rot0_.coeffs().data(), quaternion_parameterization);\n  problem_.SetParameterization(\n      rot1_.coeffs().data(), quaternion_parameterization);\n}\n\nvoid PosegraphErrorTermsEigen::checkGradient() {\n  rot0_.normalize();\n  rot1_.normalize();\n  imu_bias0_ << gyro_bias0_, accel_bias0_;\n  imu_bias1_ << gyro_bias1_, accel_bias1_;\n\n  ceres::CostFunction* inertial_term_cost =\n      new ceres_error_terms::InertialErrorTermEigen(\n          imu_data_, imu_timestamps_ns_, 1, 1, 1, 1, gravity_magnitude_);\n\n  std::vector<double*> parameter_blocks;\n  parameter_blocks.push_back(rot0_.coeffs().data());\n  parameter_blocks.push_back(pos0_.data());\n  parameter_blocks.push_back(velocity0_.data());\n  parameter_blocks.push_back(imu_bias0_.data());\n  parameter_blocks.push_back(rot1_.coeffs().data());\n  parameter_blocks.push_back(pos1_.data());\n  parameter_blocks.push_back(velocity1_.data());\n  parameter_blocks.push_back(imu_bias1_.data());\n\n  ceres::LocalParameterization* orientation_parameterization =\n      new ceres_error_terms::EigenQuaternionParameterization;\n\n  ceres::NumericDiffOptions numeric_diff_options;\n  numeric_diff_options.ridders_relative_initial_step_size = 1e-3;\n\n  std::vector<const ceres::LocalParameterization*> local_parameterizations;\n  local_parameterizations.push_back(orientation_parameterization);\n  local_parameterizations.push_back(NULL);\n  local_parameterizations.push_back(NULL);\n  local_parameterizations.push_back(NULL);\n  local_parameterizations.push_back(orientation_parameterization);\n  local_parameterizations.push_back(NULL);\n  local_parameterizations.push_back(NULL);\n  local_parameterizations.push_back(NULL);\n\n  ceres::GradientChecker gradient_checker(\n      inertial_term_cost, &local_parameterizations, numeric_diff_options);\n  ceres::GradientChecker::ProbeResults results;\n\n  if (!gradient_checker.Probe(parameter_blocks.data(), 1e-9, &results)) {\n    std::cout << \"An error has occurred:\\n\" << results.error_log;\n  }\n}\n\nvoid PosegraphErrorTermsEigen::solve() {\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::DENSE_SCHUR;\n  options.minimizer_progress_to_stdout = false;\n  options.max_num_iterations = 500;\n  options.gradient_tolerance = 1e-50;\n  options.function_tolerance = 1e-50;\n  options.parameter_tolerance = 1e-50;\n  options.num_threads = 8;\n  options.num_linear_solver_threads = 8;\n\n  ceres::Solve(options, &problem_, &summary_);\n\n  LOG(INFO) << summary_.message;\n  LOG(INFO) << summary_.BriefReport();\n}\n\nTEST_F(PosegraphErrorTermsEigen, InertialTermZeroCost) {\n  addResidual();\n  solve();\n\n  EXPECT_LT(summary_.final_cost, 1e-15);\n}\n\nTEST_F(PosegraphErrorTermsEigen, InertialTermFinalPositionOptimization) {\n  pos1_ << 1.43, -0.2, 0.175;\n  addResidual();\n\n  problem_.SetParameterBlockConstant(imu_bias0_.data());\n  problem_.SetParameterBlockConstant(imu_bias1_.data());\n  problem_.SetParameterBlockConstant(velocity0_.data());\n  problem_.SetParameterBlockConstant(velocity1_.data());\n  problem_.SetParameterBlockConstant(pos0_.data());\n  problem_.SetParameterBlockConstant(rot0_.coeffs().data());\n\n  solve();\n\n  EXPECT_NEAR_EIGEN(pos1_, Eigen::Vector3d(1.5, 0, 0), 1e-15);\n  EXPECT_NEAR_EIGEN(rot1_.coeffs(), Eigen::Vector4d(0, 0, 0, 1), 1e-15);\n  EXPECT_LT(summary_.final_cost, 1e-15);\n}\n\nTEST_F(\n    PosegraphErrorTermsEigen, InertialTermFinalPositionVelocityOptimization) {\n  pos1_ << 1.43, -0.2, 0.175;\n  velocity1_ << 2.1, -0.2, 0.1;\n  addResidual();\n\n  problem_.SetParameterBlockConstant(imu_bias0_.data());\n  problem_.SetParameterBlockConstant(imu_bias1_.data());\n  problem_.SetParameterBlockConstant(velocity0_.data());\n  problem_.SetParameterBlockConstant(pos0_.data());\n  problem_.SetParameterBlockConstant(rot0_.coeffs().data());\n  solve();\n  EXPECT_NEAR_EIGEN(pos1_, Eigen::Vector3d(1.5, 0, 0), 1e-15);\n  EXPECT_NEAR_EIGEN(rot1_.coeffs(), Eigen::Vector4d(0, 0, 0, 1), 1e-15);\n  EXPECT_NEAR_EIGEN(velocity1_, Eigen::Vector3d(2, 0, 0), 1e-15);\n  EXPECT_LT(summary_.final_cost, 1e-15);\n}\n\nTEST_F(PosegraphErrorTermsEigen, InertialTermFinalRotationOptimization) {\n  rot1_.coeffs() << 0.024225143749034013, 0.04470367401201076,\n      0.04242220263937102, 0.9978051316080664;\n  addResidual();\n\n  problem_.SetParameterBlockConstant(imu_bias0_.data());\n  problem_.SetParameterBlockConstant(imu_bias1_.data());\n  problem_.SetParameterBlockConstant(velocity0_.data());\n  problem_.SetParameterBlockConstant(velocity1_.data());\n  problem_.SetParameterBlockConstant(pos0_.data());\n  problem_.SetParameterBlockConstant(rot0_.coeffs().data());\n\n  solve();\n  //  EXPECT_NEAR_EIGEN(pos1_, pos1_, 1e-15);\n  EXPECT_NEAR_EIGEN(rot1_.coeffs(), Eigen::Vector4d(0, 0, 0, 1), 1e-15);\n  EXPECT_LT(summary_.final_cost, 1e-15);\n}\n\nTEST_F(PosegraphErrorTermsEigen, InertialTermFinalVelocityOptimization) {\n  velocity1_ << 2.1, 0, 0;\n  addResidual();\n\n  problem_.SetParameterBlockConstant(imu_bias0_.data());\n  problem_.SetParameterBlockConstant(imu_bias1_.data());\n  problem_.SetParameterBlockConstant(velocity0_.data());\n  problem_.SetParameterBlockConstant(pos0_.data());\n  problem_.SetParameterBlockConstant(rot0_.coeffs().data());\n  problem_.SetParameterBlockConstant(pos1_.data());\n  problem_.SetParameterBlockConstant(rot1_.coeffs().data());\n\n  solve();\n  EXPECT_NEAR_EIGEN(velocity1_, Eigen::Vector3d(2, 0, 0), 1e-15);\n  EXPECT_LT(summary_.final_cost, 1e-15);\n}\n\nTEST_F(PosegraphErrorTermsEigen, InertialTermStartPositionOptimization) {\n  pos0_ << 0.13, -0.2, 0.175;\n  addResidual();\n\n  problem_.SetParameterBlockConstant(imu_bias0_.data());\n  problem_.SetParameterBlockConstant(imu_bias1_.data());\n  problem_.SetParameterBlockConstant(velocity0_.data());\n  problem_.SetParameterBlockConstant(velocity1_.data());\n  problem_.SetParameterBlockConstant(pos1_.data());\n  problem_.SetParameterBlockConstant(rot1_.coeffs().data());\n  solve();\n\n  //  checkGradient();\n\n  EXPECT_ZERO_EIGEN(pos0_, 1e-15);\n  EXPECT_NEAR_EIGEN(rot0_.coeffs(), Eigen::Vector4d(0, 0, 0, 1), 1e-15);\n  EXPECT_LT(summary_.final_cost, 1e-15);\n}\n\nTEST_F(PosegraphErrorTermsEigen, InertialTermStartRotationOptimization) {\n  rot0_.coeffs() << 0.024225143749034013, 0.04470367401201076,\n      0.04242220263937102, 0.9978051316080664;\n  addResidual();\n\n  problem_.SetParameterBlockConstant(imu_bias0_.data());\n  problem_.SetParameterBlockConstant(imu_bias1_.data());\n  problem_.SetParameterBlockConstant(velocity0_.data());\n  problem_.SetParameterBlockConstant(pos1_.data());\n  problem_.SetParameterBlockConstant(rot1_.coeffs().data());\n  solve();\n  EXPECT_ZERO_EIGEN(pos0_, 1e-15);\n  EXPECT_NEAR_EIGEN(rot0_.coeffs(), Eigen::Vector4d(0, 0, 0, 1), 1e-15);\n  EXPECT_NEAR_EIGEN(velocity1_, Eigen::Vector3d(2, 0, 0), 1e-15);\n  EXPECT_LT(summary_.final_cost, 1e-15);\n}\n\nTEST_F(PosegraphErrorTermsEigen, InertialTermStartVelocityOptimization) {\n  velocity0_ << 2.1, -0.2, 0.1;\n  addResidual();\n\n  problem_.SetParameterBlockConstant(imu_bias0_.data());\n  problem_.SetParameterBlockConstant(imu_bias1_.data());\n  problem_.SetParameterBlockConstant(velocity1_.data());\n  problem_.SetParameterBlockConstant(pos0_.data());\n  problem_.SetParameterBlockConstant(rot0_.coeffs().data());\n  problem_.SetParameterBlockConstant(pos1_.data());\n  problem_.SetParameterBlockConstant(rot1_.coeffs().data());\n\n  solve();\n  EXPECT_NEAR_EIGEN(velocity0_, Eigen::Vector3d(1, 0, 0), 1e-15);\n  EXPECT_LT(summary_.final_cost, 1e-15);\n}\n\nTEST_F(PosegraphErrorTermsEigen, InertialTermStartImuBiasOptimization) {\n  gyro_bias0_ << 0.3, -0.2, 0.1;\n  accel_bias0_ << 0.1, -0.2, 0.1;\n\n  addResidual();\n\n  problem_.SetParameterBlockConstant(imu_bias1_.data());\n  problem_.SetParameterBlockConstant(velocity0_.data());\n  problem_.SetParameterBlockConstant(velocity1_.data());\n  problem_.SetParameterBlockConstant(pos0_.data());\n  problem_.SetParameterBlockConstant(rot0_.coeffs().data());\n  problem_.SetParameterBlockConstant(pos1_.data());\n  problem_.SetParameterBlockConstant(rot1_.coeffs().data());\n\n  solve();\n  EXPECT_ZERO_EIGEN(imu_bias0_, 1e-15);\n  EXPECT_LT(summary_.final_cost, 1e-15);\n}\n\nTEST_F(PosegraphErrorTermsEigen, InertialTermFinalImuBiasOptimization) {\n  gyro_bias1_ << 0.3, -0.2, 0.1;\n  accel_bias1_ << -0.3, -0.2, 0.1;\n\n  addResidual();\n\n  problem_.SetParameterBlockConstant(imu_bias0_.data());\n  problem_.SetParameterBlockConstant(velocity0_.data());\n  problem_.SetParameterBlockConstant(pos0_.data());\n  problem_.SetParameterBlockConstant(rot0_.coeffs().data());\n  problem_.SetParameterBlockConstant(pos1_.data());\n  problem_.SetParameterBlockConstant(rot1_.coeffs().data());\n\n  solve();\n  EXPECT_ZERO_EIGEN(imu_bias1_, 1e-15);\n  EXPECT_NEAR_EIGEN(velocity1_, Eigen::Vector3d(2, 0, 0), 1e-15);\n  EXPECT_LT(summary_.final_cost, 1e-15);\n}\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "3a12f68c8aeacd1dd931e795cd82eb8193759ba7", "size": 11403, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/ceres-error-terms/test/test_inertial_term_test_eigen.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": "algorithms/ceres-error-terms/test/test_inertial_term_test_eigen.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": "algorithms/ceres-error-terms/test/test_inertial_term_test_eigen.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": 34.3463855422, "max_line_length": 80, "alphanum_fraction": 0.7539244059, "num_tokens": 3401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5103502575295972}}
{"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\nnamespace votca { namespace tools {\n\nusing namespace std;\n\n/**\n * ublas binding to MKL  Singular Value Decomposition\n * \n * A = U S V^T\n * \n * @param A MxN matrix do decompose. Becomes an MxN orthogonal matrix U\n * @param V NxN orthogonal square matrix\n * @param S N vector of non-negative numbers forming a non-increasing sequence\n * @return succeeded or not \n */\n\n\nbool linalg_singular_value_decomposition(ub::matrix<double> &A, ub::matrix<double> &VT, ub::vector<double> &S ){\n        // matrix inversion using MKL\n    \n    \n    \n    // define LAPACK variables\n    MKL_INT m = A.size1();\n    MKL_INT n = A.size2();\n    \n    if (m>n){\n        throw runtime_error(\"Matrix for svd has the wrong shape first dimension must be equal or larger than second.\");\n    }\n    //MKL_INT info;\n    //MKL_INT ipiv[n];\n    ub::matrix<double>work=ub::zero_matrix<double>(m,n);\n    // initialize V\n    S.resize(n, false);\n    VT.resize(n, n, false);\n    \n    // pointers for LAPACK\n    double * a = const_cast<double*>(&A.data().begin()[0]);\n    double * s = const_cast<double*>(&S.data().begin()[0]);\n    double * vt = const_cast<double*>(&VT.data().begin()[0]);   \n    double * superb = const_cast<double*>(&work.data().begin()[0]);\n    // solve\n    int status= LAPACKE_dgesvd( LAPACK_ROW_MAJOR, 'O', 'A',  m,  n,  a, n,  s,  NULL,m,  vt, n, superb );\n    return (status != 0);\n    \n}\n\n}}\n", "meta": {"hexsha": "604adfb6646cc0414e6219b01fb9639fa4a1008f", "size": 2143, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libtools/linalg/mkl/svd.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/svd.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/svd.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": 30.1830985915, "max_line_length": 119, "alphanum_fraction": 0.6612225852, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5103502575295972}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_HYPERBOLIC_FUNCTIONS_SIMD_COMMON_ASINH_HPP_INCLUDED\n#define NT2_HYPERBOLIC_FUNCTIONS_SIMD_COMMON_ASINH_HPP_INCLUDED\n#include <nt2/hyperbolic/functions/asinh.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/log_2.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/oneosqrteps.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/functions/simd/abs.hpp>\n#include <nt2/include/functions/simd/average.hpp>\n#include <nt2/include/functions/simd/bitofsign.hpp>\n#include <nt2/include/functions/simd/bitwise_xor.hpp>\n#include <nt2/include/functions/simd/bitwise_xor.hpp>\n#include <nt2/include/functions/simd/divides.hpp>\n#include <nt2/include/functions/simd/hypot.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/inbtrue.hpp>\n#include <nt2/include/functions/simd/is_greater.hpp>\n#include <nt2/include/functions/simd/is_less.hpp>\n#include <nt2/include/functions/simd/log.hpp>\n#include <nt2/include/functions/simd/minusone.hpp>\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/functions/simd/oneplus.hpp>\n#include <nt2/include/functions/simd/plus.hpp>\n#include <nt2/include/functions/simd/sqr.hpp>\n#include <nt2/polynomials/functions/scalar/impl/horner.hpp>\n#include <nt2/sdk/meta/as_logical.hpp>\n#include <nt2/sdk/meta/cardinal_of.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/functions/simd/is_equal.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( asinh_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<double_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename meta::as_logical<A0>::type bA0;\n      A0 x =  nt2::abs(a0);\n      bA0 test = gt(x,Oneosqrteps<A0>());\n      A0 z = if_else(test,minusone(x), x+sqr(x)/nt2::oneplus(hypot(One<A0>(), x)));\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      z = if_else(is_equal(x, Inf<A0>()),x, z);\n      #endif\n      z =  seladd(test, log1p(z), Log_2<A0>());\n      return bitwise_xor(bitofsign(a0), z);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( asinh_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<single_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      // Exhaustive test for: boost::dispatch::functor<nt2::tag::asinh_, boost::simd::tag::sse4_2_>\n      //              versus: float(boost::math::asinh(double)\n      //              With T: boost::simd::native<float, boost::simd::tag::sse_, void>\n      //            in range: [-3.40282e+38, 3.40282e+38]\n      // 4278190076 values computed.\n      // 3619320676 values (84.60%)  within 0.0 ULPs\n      //  658843138 values (15.40%)  within 0.5 ULPs\n      //      26262 values ( 0.00%)  within 1.0 ULPs\n      typedef typename meta::as_logical<A0>::type bA0;\n      typedef typename meta::scalar_of<A0>::type sA0;\n      A0 x = nt2::abs(a0);\n      bA0 lthalf = lt(x,Half<A0>());\n      A0 x2 = nt2::sqr(x);\n      A0 z = Zero<A0>();\n      std::size_t nb = inbtrue(lthalf);\n      A0 bts = bitofsign(a0);\n      if(nb > 0)\n      {\n        z = horner < NT2_HORNER_COEFF_T(sA0, 5,\n                                        ( 0x3ca4d6e6\n                                        , 0xbd2ee581\n                                        , 0x3d9949b1\n                                        , 0xbe2aa9ad\n                                        , 0x3f800000\n                                        )\n                                       )> (x2)*x;\n        if(nb >= meta::cardinal_of<A0>::value) return  b_xor(z, bts);\n      }\n      A0 tmp =  if_else(gt(x, Oneosqrteps<A0>()),\n                       x, average(x, hypot(One<A0>(), x)));\n     return b_xor(if_else(lthalf, z, log(tmp)+Log_2<A0>()), bts);\n    }\n  };\n} }\n#endif\n", "meta": {"hexsha": "4fcb87c59597d576b034892492ad62b5c747aa08", "size": 4471, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/hyperbolic/include/nt2/hyperbolic/functions/simd/common/asinh.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/hyperbolic/include/nt2/hyperbolic/functions/simd/common/asinh.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/hyperbolic/include/nt2/hyperbolic/functions/simd/common/asinh.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 41.0183486239, "max_line_length": 99, "alphanum_fraction": 0.5754864684, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5103502575295972}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::model::functional::log_likelihood_evaluator.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_MODEL_FUNCTIONAL_LOG_LIKELIHOOD_EVALUATOR_HPP_ER_2009\n#define BOOST_STATISTICS_MODEL_FUNCTIONAL_LOG_LIKELIHOOD_EVALUATOR_HPP_ER_2009\n#include <boost/range.hpp>\n#include <boost/statistics/model/wrap/aggregate/model_parameter.hpp>\n#include <boost/statistics/model/wrap/aggregate/model_dataset.hpp>\n#include <boost/statistics/model/algorithm/log_likelihood.hpp>\n\nnamespace boost{ \nnamespace statistics{\nnamespace model{  \n\n    // Evaluates the log-likelihood at a parameter values given a model and\n    // a dataset.\n    //\n    // T is the result_type\n    template<typename T,typename M,typename Rx,typename Ry>\n    class log_likelihood_evaluator{\n        public:\n        typedef T result_type;\n        typedef model_dataset_<M,Rx,Ry> model_dataset_type;\n        \n        // Constructor\n        log_likelihood_evaluator();\n        log_likelihood_evaluator(const model_dataset_type&);\n        log_likelihood_evaluator(const log_likelihood_evaluator&);\n        log_likelihood_evaluator& operator=(const log_likelihood_evaluator&);\n\n        // Evaluate\n        template<typename P> result_type operator()(const P& p)const;\n\n        // Access\n        const model_dataset_type& model_dataset()const;\n        \n        private:\n        model_dataset_type md_;\n    };\n\n    // Implementation //\n    \n    // Construction\n    template<typename T,typename M,typename Rx,typename Ry>\n    log_likelihood_evaluator<T,M,Rx,Ry>::log_likelihood_evaluator(){}\n    \n    template<typename T,typename M,typename Rx,typename Ry>\n    log_likelihood_evaluator<T,M,Rx,Ry>::log_likelihood_evaluator(\n        const model_dataset_type& md\n    ):md_(md){}\n\n    template<typename T,typename M,typename Rx,typename Ry>\n    log_likelihood_evaluator<T,M,Rx,Ry>::log_likelihood_evaluator(\n        const log_likelihood_evaluator& that\n    ):md_(that.md_){}\n\n    template<typename T,typename M,typename Rx,typename Ry>\n    log_likelihood_evaluator<T,M,Rx,Ry>&\n    log_likelihood_evaluator<T,M,Rx,Ry>::operator=(\n        const log_likelihood_evaluator& that\n    ){\n        if(&that!=this){\n            md_ = (that.md_);\n        }\n        return (*this);\n    }\n    \n    // Evaluate\n    template<typename T,typename M,typename Rx,typename Ry>\n    template<typename P>\n    typename log_likelihood_evaluator<T,M,Rx,Ry>::result_type \n    log_likelihood_evaluator<T,M,Rx,Ry>::operator()(const P& p)const{\n        return log_likelihood<T>(\n            make_model_parameter(\n                model_dataset().model(),\n                p\n            ),\n            boost::begin( model_dataset().covariates() ),\n            boost::end( model_dataset().covariates() ),\n            boost::begin( model_dataset().responses() )\n        );\n    }\n\n    // Access\n    template<typename T,typename M,typename Rx,typename Ry>\n    const typename log_likelihood_evaluator<T,M,Rx,Ry>::model_dataset_type& \n    log_likelihood_evaluator<T,M,Rx,Ry>::model_dataset()const{\n        return (this->md_);\n    }\n\n}// model\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "45e9bb8f80c86417f47cadc812a8f337a68e4a13", "size": 3564, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "model copy/boost/statistics/model/functional/log_likelihood_evaluator.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": "model copy/boost/statistics/model/functional/log_likelihood_evaluator.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": "model copy/boost/statistics/model/functional/log_likelihood_evaluator.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": 36.0, "max_line_length": 79, "alphanum_fraction": 0.6271043771, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5103502465721789}}
{"text": "/*\n    Boost Competency Test - GSoC 2020\n    digu_J - Digvijay Janartha\n    NIT Hamirpur - INDIA\n*/\n\n#include <bits/stdc++.h>\n#include <boost/geometry.hpp>\n\nusing namespace std;\nnamespace bg = boost::geometry;\n\ntypedef bg::model::point<double, 2, bg::cs::cartesian> point_t;\ntypedef bg::model::polygon<point_t> poly_t;\n\nconst double EPS = 1e-9; // used in various places to solve precision issues\n\n// This program takes input integer n and k, followed by n points and outputs concave hull using KNN algorithm.\n// The concave hull of a geometry represents a possibly concave geometry that encloses all geometries within the set.\n\nstruct pnt{\n    double x, y;\n\n    bool operator<(pnt const& oth) {\n        if (x == oth.x) {\n            return y < oth.y;\n        }\n        return x < oth.x;\n    }\n\n    bool operator==(const pnt& a) const {return a.x == x && a.y == y;}\n};\n\nstruct line{\n    double a, b, c;\n};\n\ndouble dist(pnt a, pnt b) {\n    // returns distance square between two points\n    return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);\n}\n\nint cross_product(pnt a, pnt b, pnt c) {\n    // returns 1 if points are oriented in counter-clockwise manner\n    // returns 0 if points are oriented in clockwise manner\n    double ans = (b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y);\n    if (!ans) {\n        // returns -1 if collinear\n        return -1;\n    }\n    return (ans < 0 ? 1 : 0);\n}\n\nvoid CleanList(vector<pnt> &pt) {\n    // this function removes duplicates from input vector\n    // and then sorts the vector with increasing x value\n    int n = pt.size();\n    set<pair<double,double>> st;\n    for (int i = 0; i < n; ++i) {\n        st.insert({pt[i].x, pt[i].y});\n    }\n    for (int i = 0; i < n; ++i) {\n        pt.pop_back();\n    }\n    for (auto &p: st) {\n        pt.push_back({p.first, p.second});\n    }\n    sort(pt.begin(), pt.end());\n}\n\nvoid RemovePoint(vector<pnt> &pt, pnt cur) {\n    // removes the cur point from vector pt\n    int n = pt.size();\n    bool active = false;\n    for (int i = 0; i < n; ++i) {\n        if (pt[i].x == cur.x and pt[i].y == cur.y) {\n            for (int j = i; j < n - 1; ++j) {\n                pt[j] = pt[j + 1];\n            }\n            break;\n        }\n    }\n    pt.pop_back();\n}\n\nvector<pnt> NearestPoints(vector<pnt> pt, pnt cur, int cur_k) {\n    // this function returns vector with cur_k nearest points to point cur\n    sort(pt.begin(), pt.end(), [&](pnt a, pnt b) {\n        return (dist(a, cur) < dist(b, cur));\n    });\n    vector<pnt> ans;\n    for (int i = 0; i < min(cur_k, int(pt.size())); ++i) {\n        ans.push_back(pt[i]);\n    }\n    sort(ans.begin(), ans.end());\n    return ans;\n}\n\nbool IsInside(vector<pnt> pt, pnt cur) {\n    // returns true if cur is inside or in the border of the polygon formed by points in vector pt\n    poly_t poly;\n    for (int i = 0; i < int(pt.size()); ++i) {\n        bg::append(poly, point_t(pt[i].x, pt[i].y));\n    }\n    point_t now = point_t(cur.x, cur.y);\n    return bg::covered_by(now, poly);\n}\n\nbool PointOnSegment(pnt a, pnt b, pnt p) {\n    // returns true if point p lies on the line segment formed by point a and b (exclusive)\n    if (p == a or p == b) {\n        return false;\n    }\n    double len = sqrt(dist(a, b));\n    double tot = sqrt(dist(a, p)) + sqrt(dist(b, p));\n    return (len + EPS > tot);\n}\n\nbool Intersect(pnt a, pnt b, pnt c, pnt d) {\n    // returns true if line formed by point a and b intersects line formed by point c and d\n    // if segments only touches each other than return false\n    line l1 = {a.y - b.y, b.x - a.x, a.x * (b.y - a.y) + a.y * (a.x - b.x)};\n    line l2 = {c.y - d.y, d.x - c.x, c.x * (d.y - c.y) + c.y * (c.x - d.x)};\n    double D = l1.a * l2.b - l1.b * l2.a;\n    double Ny = l1.c * l2.a - l1.a * l2.c;\n    double Nx = l1.b * l2.c - l1.c * l2.b;\n    if (abs(D) < EPS) {\n        if (abs(Nx) < EPS and abs(Ny) < EPS) {\n            double Sum = sqrt(dist(a, b)) + sqrt(dist(c, d));\n            double Max = sqrt(max({dist(a, c), dist(a, d), dist(b, c), dist(b, d)}));\n            if (Sum > Max) {\n                return true;\n            }\n            return false;\n        }\n        return false;\n    }\n    pnt Mid = {Nx / D, Ny / D};\n    if (PointOnSegment(a, b, Mid) and PointOnSegment(c, d, Mid)) {\n        return true;\n    }\n    return false;\n}\n\nvector<pnt> KNN(vector<pnt> input, int k) {\n    vector<pnt> pt = input;\n\n    // k must be atleast 2\n    k = max(k, 2);\n    if (pt.size() < 3 or k > int(pt.size())) {\n        return {};\n    }\n    if (pt.size() == 3) {\n        return pt;\n    }\n\n    int cur_k = min(k, int(pt.size()) - 1);\n    vector<pnt> hull = {pt[0]};\n    pnt cur_pt = pt[0];\n    int step = 0;\n    RemovePoint(pt, cur_pt);\n\n    while (pt.size()) {\n        if (step == 3) {\n            // once a polygon with more than 3 edges is formed add the first point to the pt vector again\n            pt.push_back(hull[0]);\n        }\n        vector<pnt> nearest = NearestPoints(pt, cur_pt, cur_k);\n        vector<pnt> good;\n        for (int i = 0; i < int(nearest.size()); ++i) {\n            bool ok = true;\n            for (int j = int(hull.size()) - 1; j > 0; --j) {\n                if (Intersect(hull[j], hull[j - 1], nearest[i], cur_pt)) {\n                    ok = false;\n                    break;\n                }\n            }\n            if (ok) {\n                // non intersecting edge is good\n                good.push_back(nearest[i]);\n            }\n        }\n        if (good.empty()) {\n            // if no good points remaining, increase k\n            return KNN(input, k + 1);\n        }\n\n        pnt best = good[0];\n        for (int i = 0; i < int(good.size()); ++i) {\n            int val = cross_product(cur_pt, good[i], best);\n            if (val) {\n                // update best if we have counter-clockwise orientation\n                if (val == -1) {\n                    // in case of collinear points take the nearest one as best\n                    if (dist(good[i], cur_pt) < dist(best, cur_pt)) {\n                        best = good[i];\n                    }\n                } else {\n                    best = good[i];\n                }\n            }\n        }\n        cur_pt = best;\n        hull.push_back(cur_pt);\n        RemovePoint(pt, cur_pt);\n\n        if (cur_pt == hull[0]) {\n            // cycle completed\n            break;\n        }\n        cur_k = min(cur_k, int(pt.size()));\n        ++step;\n    }\n    for (auto &p: pt) {\n        if (!IsInside(hull, p)) {\n            // if any point is outside the concave hull, increase k\n            return KNN(input, k + 1);\n        }\n    }\n    cout << \"k => \" << k << \"\\n\";\n    return hull;\n}\n\nint main() {\n    cout << fixed << setprecision(0);\n    // take user input\n    int n, k;\n    cin >> n >> k;\n    vector<pnt> pt;\n    for (int i = 0; i < n; ++i) {\n        double a, b;\n        cin >> a >> b;\n        pt.push_back({a, b});\n    }\n\n    CleanList(pt);\n    vector<pnt> hull = KNN(pt, k);\n\n    if (hull.empty()) {\n        cout << \"Invalid input\\n\";\n    } else {\n        cout << \"Hull size: \" << int(hull.size()) << \"\\n\";\n        for (int i = 0; i < int(hull.size()); ++i) {\n            cout << hull[i].x << \" \" << hull[i].y << \"\\n\";\n        }\n    }\n\n    // To calculate the time taken in executing the code\n    cout << \"Time: \" << (int)(clock() * 1000. / CLOCKS_PER_SEC) << \"ms\";\n    return 0;\n}\n", "meta": {"hexsha": "4437b5e7d0234113f789958bc72b50fdcbd5261f", "size": 7320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_implementation/concave_hull_k_nearest_neighbours.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": "cpp_implementation/concave_hull_k_nearest_neighbours.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": "cpp_implementation/concave_hull_k_nearest_neighbours.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": 29.0476190476, "max_line_length": 117, "alphanum_fraction": 0.4964480874, "num_tokens": 2174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5102957202239436}}
{"text": "//=======================================================================\n// Copyright (c)\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 fast_exp_test.cpp\n * @brief\n * @author Piotr Wygocki\n * @version 1.0\n * @date 2013-06-20\n */\n#include \"test_utils/logger.hpp\"\n\n#include \"paal/utils/fast_exp.hpp\"\n#include \"paal/utils/irange.hpp\"\n#include \"paal/utils/assign_updates.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(FastExpTest) {\n    double biggestErr = 0;\n    for (int i : paal::irange(-80, 80)) {\n        paal::assign_max(biggestErr, std::abs(exp(i) - paal::fast_exp(i)) / exp(i));\n    }\n    LOGLN(\"biggest error \" << biggestErr);\n    BOOST_CHECK(biggestErr < 0.04);\n}\n", "meta": {"hexsha": "85c4101f84990fc0cbf8c81c7d938cf0601b2a29", "size": 888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fast_exp_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/fast_exp_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/fast_exp_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.6451612903, "max_line_length": 84, "alphanum_fraction": 0.5653153153, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481138, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5102957090737522}}
{"text": "// Copyright \u00a9 2016-2021 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#include <vinecopulib/misc/tools_stats.hpp>\n#include <vinecopulib/misc/tools_stl.hpp>\n\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include <cmath>\n#include <iostream>\n#include <wdm/eigen.hpp>\n\nnamespace vinecopulib {\n\nnamespace tools_select {\n\nusing namespace tools_stl;\n\n//! @brief Calculates criterion for tree selection.\n//! @param data Observations.\n//! @param tree_criterion The criterion.\n//! @param weights Vector of weights for each observation (can be empty).\ninline double\ncalculate_criterion(const Eigen::MatrixXd& data,\n                    std::string tree_criterion,\n                    Eigen::VectorXd weights)\n{\n  double w = 0.0;\n  Eigen::MatrixXd data_no_nan = data;\n  tools_eigen::remove_nans(data_no_nan, weights);\n  double freq =\n    static_cast<double>(data_no_nan.rows()) / static_cast<double>(data.rows());\n  if (data_no_nan.rows() > 10) {\n    if (tree_criterion == \"mcor\") {\n      w = tools_stats::pairwise_mcor(data_no_nan, weights);\n    } else if (tree_criterion == \"joe\") {\n      // mutual information for Gaussian copula\n      w = wdm::wdm(tools_stats::qnorm(data_no_nan), \"pearson\", weights)(0, 1);\n      w = -0.5 * std::log(1 - w * w);\n    } else {\n      w = wdm::wdm(data_no_nan, tree_criterion, weights)(0, 1);\n    }\n\n    if (std::isnan(w)) {\n      w = 0.0;\n    }\n  }\n  return std::fabs(w) * std::sqrt(freq);\n}\n\n//! @brief Evaluates maximal criterion for tree selection.\n//! @param data Observations.\n//! @param tree_criterion The criterion.\n//! @param weights Vector of weights for each observation (can be empty).\ninline Eigen::MatrixXd\ncalculate_criterion_matrix(const Eigen::MatrixXd& data,\n                           const std::string& tree_criterion,\n                           const Eigen::VectorXd& weights)\n{\n  size_t n = data.rows();\n  size_t d = data.cols();\n  Eigen::MatrixXd mat(d, d);\n  mat.diagonal() = Eigen::VectorXd::Constant(d, 1.0);\n  Eigen::MatrixXd pair_data(n, 2);\n  for (size_t i = 1; i < d; ++i) {\n    for (size_t j = 0; j < i; ++j) {\n      pair_data.col(0) = data.col(i);\n      pair_data.col(1) = data.col(j);\n      Eigen::VectorXd pair_w = weights;\n      mat(i, j) = calculate_criterion(pair_data, tree_criterion, pair_w);\n      mat(j, i) = mat(i, j);\n    }\n  }\n  return mat;\n}\n\n//! computes\ninline std::vector<size_t>\nget_disc_cols(std::vector<std::string> var_types)\n{\n  size_t d = var_types.size();\n  std::vector<size_t> disc_cols(d);\n  size_t disc_count = 0;\n  for (size_t i = 0; i < d; ++i) {\n    if (var_types[i] == \"d\") {\n      disc_cols[i] = disc_count++;\n    } else {\n      disc_cols[i] = 0;\n    }\n  }\n  return disc_cols;\n}\n\ninline VinecopSelector::VinecopSelector(const Eigen::MatrixXd& data,\n                                        const FitControlsVinecop& controls,\n                                        std::vector<std::string> var_types)\n  : n_(data.rows())\n  , d_(var_types.size())\n  , var_types_(var_types)\n  , controls_(controls)\n  , pool_(controls_.get_num_threads())\n  , trees_(std::vector<VineTree>(1))\n  , threshold_(controls.get_threshold())\n  , psi0_(controls.get_psi0())\n{\n  vine_struct_ = RVineStructure(tools_stl::seq_int(1, d_), 1, false);\n}\n\ninline VinecopSelector::VinecopSelector(const Eigen::MatrixXd& data,\n                                        const RVineStructure& vine_struct,\n                                        const FitControlsVinecop& controls,\n                                        std::vector<std::string> var_types)\n  : VinecopSelector(data, controls, var_types)\n{\n  vine_struct_ = vine_struct;\n  structure_known_ = false;\n}\n\ninline std::vector<std::vector<Bicop>>\nVinecopSelector::get_pair_copulas() const\n{\n  return pair_copulas_;\n}\n\ninline RVineStructure\nVinecopSelector::get_rvine_structure() const\n{\n  return vine_struct_;\n}\n\n//! @brief Instantiates the object for storing pair copulas.\n//! @param d Dimension of the vine copula.\n//! @param trunc_lvl A truncation level (optional).\n//! @return A nested vector such that `pc_store[t][e]` contains a Bicop.\n//!     object for the pair copula corresponding to tree `t` and edge `e`.\ninline std::vector<std::vector<Bicop>>\nVinecopSelector::make_pair_copula_store(size_t d, size_t trunc_lvl)\n{\n  if (d < 1) {\n    throw std::runtime_error(\"dimension must be be > 0.\");\n  }\n\n  size_t n_trees = std::min(d - 1, trunc_lvl);\n  std::vector<std::vector<Bicop>> pc_store(n_trees);\n  for (size_t t = 0; t < n_trees; ++t) {\n    pc_store[t].resize(d - 1 - t);\n  }\n\n  return pc_store;\n}\n\ninline void\nVinecopSelector::select_all_trees(const Eigen::MatrixXd& data)\n{\n  loglik_ = 0.0;\n  initialize_new_fit(data);\n  for (size_t t = 0; t < d_ - 1; ++t) {\n    select_tree(t); // select pair copulas (+ structure) of tree t\n    loglik_ += get_loglik_of_tree(t);\n\n    if (controls_.get_show_trace()) {\n      std::stringstream tree_heading;\n      std::cout << \"** Tree: \" << t << std::endl;\n      print_pair_copulas_of_tree(t);\n    }\n\n    if (controls_.get_trunc_lvl() == t + 1) {\n      // don't need to fit the remaining trees\n      break;\n    }\n  }\n  finalize(controls_.get_trunc_lvl());\n}\n\ninline void\nVinecopSelector::sparse_select_all_trees(const Eigen::MatrixXd& data)\n{\n  // family set must be reset after each iteration of the threshold search\n  auto family_set = controls_.get_family_set();\n  double d = static_cast<double>(d_);\n\n  std::vector<double> thresholded_crits;\n  double mbicv_opt = std::numeric_limits<double>::max();\n  bool needs_break = false;\n  while (!needs_break) {\n    // restore family set in case previous threshold iteration also\n    // truncated the model\n    controls_.set_family_set(family_set);\n    controls_.set_trunc_lvl(std::numeric_limits<size_t>::max());\n    initialize_new_fit(data);\n\n    // decrease the threshold\n    // (in the first iteration thresholded_crits is empty and the threshold is\n    // set to 1.0, which fits an independence model)\n    if (controls_.get_select_threshold()) {\n      controls_.set_threshold(get_next_threshold(thresholded_crits));\n      if (controls_.get_show_trace()) {\n        std::cout << \"***** threshold: \" << controls_.get_threshold()\n                  << std::endl;\n      }\n    }\n\n    // helper variables for checking whether an optimum was found\n    double mbicv = 0.0;\n    double mbicv_trunc = 0.0;\n    double loglik = 0.0;\n    bool select_trunc_lvl = controls_.get_select_trunc_lvl();\n    bool select_threshold = controls_.get_select_threshold();\n    double num_changed = 0.0;\n    double num_total = d * (d - 1.0) / 2.0;\n\n    for (size_t t = 0; t < d_ - 1; ++t) {\n      if (controls_.get_trunc_lvl() < t) {\n        break; // don't need to fit the remaining trees\n      }\n\n      // select pair copulas (and possibly tree structure)\n      select_tree(t);\n      num_changed += d - 1 - static_cast<double>(t);\n\n      // update fit statistic\n      double loglik_tree = get_loglik_of_tree(t);\n      loglik += loglik_tree;\n      double mbicv_tree = get_mbicv_of_tree(t, loglik_tree);\n      mbicv_trunc += mbicv_tree;\n\n      // print trace for this tree level\n      if (controls_.get_show_trace()) {\n        std::cout << \"** Tree: \" << t;\n        if (select_trunc_lvl) {\n          std::cout << \", mbicv: \" << mbicv_tree << \", loglik: \" << loglik_tree;\n        }\n        std::cout << std::endl;\n        print_pair_copulas_of_tree(t);\n      }\n\n      // mbicv comparison for truncation level (check only after 10% of\n      // copulas change to avoid getting stuck in local minimum)\n      if (num_changed / num_total > 0.1) {\n        num_changed = 0.0;\n        if (select_trunc_lvl & (mbicv_trunc >= mbicv) & (t > 0)) {\n          // mbicv did not improve\n          // check if it can be improved by removing trees\n          loglik -= loglik_tree;\n          mbicv_trunc -= mbicv_tree;\n          while (t > 1) {\n            loglik_tree = get_loglik_of_tree(t - 1);\n            mbicv_tree = get_mbicv_of_tree(t - 1, loglik_tree);\n            if (mbicv_tree <= 0)\n              break;\n            loglik -= loglik_tree;\n            mbicv_trunc -= mbicv_tree;\n            t--;\n          }\n          set_current_fit_as_opt(loglik);\n          controls_.set_trunc_lvl(t);\n          if (!select_threshold) {\n            // fixed threshold, no need to continue\n            needs_break = true;\n          }\n        } else {\n          mbicv = mbicv_trunc;\n        }\n      }\n    }\n\n    if (controls_.get_show_trace()) {\n      std::cout << \"--> mbicv = \" << mbicv << \", loglik = \" << loglik\n                << std::endl\n                << std::endl;\n    }\n\n    // check whether mbicv-optimal model has been found\n    if (mbicv == 0.0) {\n      //// CASE: 0-truncated model is best for this threshold\n      set_current_fit_as_opt(loglik);\n      if (!select_threshold) {\n        // threshold is fixed and trunc_lvl has been found -> stop\n        needs_break = true;\n      }\n    } else if (mbicv >= mbicv_opt) {\n      //// CASE: old model is optimal\n      needs_break = true;\n    } else {\n      //// CASE: optimum hasn't been found\n      set_current_fit_as_opt(loglik);\n      mbicv_opt = mbicv;\n      // while loop is only for threshold selection\n      needs_break = needs_break || !select_threshold;\n      // threshold is too close to 0\n      needs_break = needs_break || (controls_.get_threshold() < 0.01);\n      // prepare for possible next iteration\n      thresholded_crits = get_thresholded_crits();\n    }\n  }\n\n  // set final model\n  trees_ = trees_opt_;\n  finalize(controls_.get_trunc_lvl());\n}\n\ninline void\nVinecopSelector::set_tree_to_indep(size_t t)\n{\n  // trees_[0] is base tree, see make_base_tree()\n  for (auto e : boost::edges(trees_[t + 1])) {\n    trees_[t + 1][e].pair_copula = Bicop();\n  }\n}\n\n// extracts the current loglik value\ninline double\nVinecopSelector::get_loglik() const\n{\n  return loglik_;\n}\n\n// extracts the current threshold value\ninline double\nVinecopSelector::get_threshold() const\n{\n  return threshold_;\n}\n\n// extracts the number of observations\ninline size_t\nVinecopSelector::get_nobs() const\n{\n  return n_;\n}\n\n//! chooses threshold for next iteration such that at a proportion of at\n//! least 2.5% of the previously thresholded pairs become non-thresholded.\ninline double\nVinecopSelector::get_next_threshold(std::vector<double>& thresholded_crits)\n{\n  if (thresholded_crits.size() == 0) {\n    return 1.0;\n  }\n  // sort in descending order\n  std::sort(thresholded_crits.begin(), thresholded_crits.end());\n  std::reverse(thresholded_crits.begin(), thresholded_crits.end());\n  // pick threshold that changes at least alpha*100 % of the pair-copulas\n  double alpha = 0.05;\n  size_t m = thresholded_crits.size();\n  double new_index = std::ceil(static_cast<double>(m) * alpha) - 1;\n  return thresholded_crits[static_cast<size_t>(new_index)];\n}\n\n//! @brief Adds edges allowed by either the proximity condition or the vine\n//  structure.\n//!\n//! If all the edges allowed by the proximity condition are included, then\n//! the function also calculates the edge weight\n//! (e.g., 1-|tau| for tree_criterion = \"itau\").\n//!\n//! @param vine_tree Tree of a vine.\ninline void\nVinecopSelector::add_allowed_edges(VineTree& vine_tree)\n{\n  std::string tree_criterion = controls_.get_tree_criterion();\n  if (structure_known_) {\n    double threshold = controls_.get_threshold();\n    std::mutex m;\n    auto add_edge = [&](size_t v0) {\n      tools_interface::check_user_interrupt(v0 % 50 == 0);\n      for (size_t v1 = 0; v1 < v0; ++v1) {\n        // check proximity condition: common neighbor in previous tree\n        // (-1 means 'no common neighbor')\n        if (find_common_neighbor(v0, v1, vine_tree) > -1) {\n          auto pc_data = get_pc_data(v0, v1, vine_tree);\n          double crit = calculate_criterion(\n            pc_data, tree_criterion, controls_.get_weights());\n          double w = 1.0 - static_cast<double>(crit >= threshold) * crit;\n          {\n            std::lock_guard<std::mutex> lk(m);\n            auto e = boost::add_edge(v0, v1, w, vine_tree).first;\n            vine_tree[e].weight = w;\n            vine_tree[e].crit = crit;\n          }\n        }\n      }\n    };\n\n    pool_.map(add_edge, boost::vertices(vine_tree));\n    pool_.wait();\n  } else {\n    size_t tree = d_ - boost::num_vertices(vine_tree);\n    size_t edges = boost::num_vertices(vine_tree) - 1;\n    size_t trunc_lvl = vine_struct_.get_trunc_lvl();\n    if (tree < trunc_lvl) {\n      for (size_t v0 = 0; v0 < edges; ++v0) {\n        tools_interface::check_user_interrupt(v0 % 10000 == 0);\n        size_t v1 = vine_struct_.min_array(tree, v0) - 1;\n        Eigen::MatrixXd pc_data = get_pc_data(v0, v1, vine_tree);\n        EdgeIterator e = boost::add_edge(v0, v1, 1.0, vine_tree).first;\n        double crit = calculate_criterion(\n          pc_data.leftCols(2), tree_criterion, controls_.get_weights());\n        vine_tree[e].weight = 1.0;\n        vine_tree[e].crit = crit;\n      }\n    }\n  }\n}\n\n//! @brief Selects the edges using the minimum spanning tree.\n//!\n//! See, e.g., Czado (2010), \"Pair-copula constructions of multivariate\n//! copulas\", url: https://mediatum.ub.tum.de/doc/1079253/file.pdf\n//! @param vine_tree Tree of a vine.\ninline void\nVinecopSelector::select_edges(VineTree& vine_tree)\n{\n  // has no effect if the input is already a tree\n  min_spanning_tree(vine_tree);\n}\n\ninline void\nVinecopSelector::finalize(size_t trunc_lvl)\n{\n  pair_copulas_ = make_pair_copula_store(d_, trunc_lvl);\n  trunc_lvl = pair_copulas_.size(); // trunc_lvl may be <size_t>::max()\n\n  if (structure_known_) {\n    using namespace tools_stl;\n    trees_opt_ = trees_;\n    TriangularArray<size_t> mat(d_, trunc_lvl);\n    std::vector<size_t> order(d_);\n\n    if (trunc_lvl > 0) {\n      std::vector<size_t> ning_set;\n\n      // fill matrix column by column\n      for (size_t col = 0; col < d_ - 1; ++col) {\n        tools_interface::check_user_interrupt();\n        // matrix above trunc_lvl is left empty\n        size_t t =\n          std::max(std::min(trunc_lvl, d_ - 1 - col), static_cast<size_t>(1));\n        // start with highest tree in this column\n        for (auto e : boost::edges(trees_[t])) {\n\n          // find an edge that contains a leaf\n          size_t v0 = boost::source(e, trees_[t]);\n          size_t v1 = boost::target(e, trees_[t]);\n          size_t min_deg = std::min(boost::out_degree(v0, trees_[t]),\n                                    boost::out_degree(v1, trees_[t]));\n          if (min_deg > 1) {\n            continue; // not a leaf\n          }\n          // find position of leaf in the edge\n          ptrdiff_t pos = (boost::out_degree(v1, trees_[t]) == 1);\n          if (pos == 1) {\n            trees_[t][e].pair_copula.flip();\n          }\n\n          // fill diagonal entry with leaf index\n          order[col] = trees_[t][e].conditioned[pos];\n\n          // entry in row t-1 is other index of the edge\n          mat(t - 1, col) = trees_[t][e].conditioned[std::abs(1 - pos)];\n\n          // assign fitted pair copula to appropriate entry, see\n          // `Vinecop::get_pair_copula()`.\n          if (trunc_lvl > 0) {\n            pair_copulas_[t - 1][col] = trees_[t][e].pair_copula;\n          }\n\n          // initialize running set with full conditioning set of this edge\n          ning_set = trees_[t][e].conditioning;\n\n          // remove edge (must not be reused in another column!)\n          boost::remove_edge(v0, v1, trees_[t]);\n          break;\n        }\n\n        // fill column bottom to top\n        for (size_t k = 1; k < t; ++k) {\n          auto check_set = cat(order[col], ning_set);\n          for (auto e : boost::edges(trees_[t - k])) {\n            // search for an edge in lower tree that shares all\n            // indices in the conditioning set + diagonal entry\n            if (!is_same_set(trees_[t - k][e].all_indices, check_set)) {\n              continue;\n            }\n            // found suitable edge ->\n            // next matrix entry is conditioned variable of new edge\n            // that's not equal to the diagonal entry of this column\n            auto e_new = trees_[t - k][e];\n            ptrdiff_t pos = (order[col] == e_new.conditioned[1]);\n            if (pos == 1) {\n              e_new.pair_copula.flip();\n            }\n            mat(t - k - 1, col) = e_new.conditioned[std::abs(1 - pos)];\n\n            // assign fitted pair copula to appropriate entry, see\n            // Vinecop::get_pair_copula().\n            pair_copulas_[t - 1 - k][col] = e_new.pair_copula;\n\n            // start over with conditioned set of next edge\n            ning_set = e_new.conditioning;\n\n            // remove edge (must not be reused in another column!)\n            size_t v0 = boost::source(e, trees_[t - k]);\n            size_t v1 = boost::target(e, trees_[t - k]);\n            boost::remove_edge(v0, v1, trees_[t - k]);\n            break;\n          }\n        }\n      }\n\n      // The last column contains a single element which must be different\n      // from all other diagonal elements. Based on the properties of an\n      // R-vine matrix, this must be the element next to it.\n      order[d_ - 1] = mat(0, d_ - 2);\n\n      // change to user-facing format\n      // (variable index starting at 1 instead of 0)\n      for (size_t i = 0; i < std::min(d_ - 1, trunc_lvl); ++i) {\n        for (size_t j = 0; j < d_ - i - 1; ++j) {\n          mat(i, j) += 1;\n        }\n      }\n      for (size_t i = 0; i < d_; i++)\n        order[i] += 1;\n    } else {\n      // order doesn't matter for truncated\n      order = tools_stl::seq_int(1, d_);\n    }\n\n    // return as RVineStructure\n    vine_struct_ = RVineStructure(order, mat);\n  } else {\n\n    for (size_t tree = 0; tree < pair_copulas_.size(); tree++) {\n      size_t edge = 0;\n      for (auto e : boost::edges(trees_[tree + 1])) {\n        // trees_[0] is base tree, vine copula starts at trees_[1]\n        pair_copulas_[tree][edge] = trees_[tree + 1][e].pair_copula;\n        edge++;\n      }\n    }\n\n    vine_struct_.truncate(trunc_lvl);\n  }\n}\n\n//! @brief Gets pair copula pseudo-observations from h-functions.\n//! @param v0,v1 vertex indices.\n//! @param tree A vine tree.\n//! @return The pseudo-observations for the pair coula, extracted from\n//!     the h-functions calculated in the previous tree.\ninline void\nVinecopSelector::add_pc_info(const EdgeIterator& e, VineTree& tree)\n{\n  auto v0 = boost::source(e, tree);\n  auto v1 = boost::target(e, tree);\n  size_t n = tree[v0].hfunc1.size();\n  tree[e].pc_data = Eigen::MatrixXd(n, 2);\n\n  // find positions of common vertex in pair indices\n  size_t ei_common = find_common_neighbor(v0, v1, tree);\n  ptrdiff_t pos0 = find_position(ei_common, tree[v0].prev_edge_indices);\n  ptrdiff_t pos1 = find_position(ei_common, tree[v1].prev_edge_indices);\n\n  tree[e].var_types[0] = tree[v0].var_types[std::abs(1 - pos0)];\n  tree[e].var_types[1] = tree[v1].var_types[std::abs(1 - pos1)];\n\n  // collect pseudo observations for next tree\n  tree[e].pc_data.col(0) = get_hfunc(tree[v0], pos0 == 0);\n  tree[e].pc_data.col(1) = get_hfunc(tree[v1], pos1 == 0);\n  if ((tree[e].var_types[0] == \"d\") | (tree[e].var_types[1] == \"d\")) {\n    tree[e].pc_data.conservativeResize(n, 4);\n    tree[e].pc_data.col(2) = get_hfunc_sub(tree[v0], pos0 == 0);\n    tree[e].pc_data.col(3) = get_hfunc_sub(tree[v1], pos1 == 0);\n  }\n\n  tree[e].conditioned =\n    set_sym_diff(tree[v0].all_indices, tree[v1].all_indices);\n  tree[e].conditioning = intersect(tree[v0].all_indices, tree[v1].all_indices);\n  tree[e].all_indices = cat(tree[e].conditioned, tree[e].conditioning);\n}\n\ninline Eigen::VectorXd\nVinecopSelector::get_hfunc(const VertexProperties& vertex_data, bool is_first)\n{\n  if (is_first) {\n    return vertex_data.hfunc1;\n  } else {\n    return vertex_data.hfunc2;\n  }\n}\n\ninline Eigen::VectorXd\nVinecopSelector::get_hfunc_sub(const VertexProperties& vertex_data,\n                               bool is_first)\n{\n  if (is_first) {\n    if (vertex_data.hfunc1_sub.size()) {\n      return vertex_data.hfunc1_sub;\n    } else {\n      return vertex_data.hfunc1;\n    }\n  } else {\n    if (vertex_data.hfunc2_sub.size()) {\n      return vertex_data.hfunc2_sub;\n    } else {\n      return vertex_data.hfunc2;\n    }\n  }\n}\n\ninline Eigen::MatrixXd\nVinecopSelector::get_pc_data(size_t v0, size_t v1, const VineTree& tree)\n{\n  size_t ei_common = find_common_neighbor(v0, v1, tree);\n  auto pos0 = find_position(ei_common, tree[v0].prev_edge_indices);\n  auto pos1 = find_position(ei_common, tree[v1].prev_edge_indices);\n\n  Eigen::MatrixXd pc_data(tree[v0].hfunc1.size(), 2);\n  pc_data.col(0) = get_hfunc(tree[v0], pos0 == 0);\n  pc_data.col(1) = get_hfunc(tree[v1], pos1 == 0);\n  return pc_data;\n}\n\n//! @brief Selects and fits next tree of the vine.\n//!\n//! The next tree is found the following way:\n//!     1. Edges of the previous tree become edges in the new tree.\n//!     2. All edges allowed by the proximity condition are added to the\n//!        new graph.\n//!     3. Collapse the new graph to a maximum spanning tree for edge\n//!        weight.\n//!     4. Populate edges with conditioned/conditioning sets and pseudo-\n//!        observations.\n//!     5. Fit and select a copula model for each edge.\n//!\n//! @param prev_tree Tree T_{k}.\n//! @param controls The controls for fitting a vine copula\n//!     (see FitControlsVinecop).\n//! @param tree_opt The current optimal tree (used only for sparse\n//!     selection).\ninline void\nVinecopSelector::select_tree(size_t t)\n{\n  auto new_tree = edges_as_vertices(trees_[t]);\n  remove_edge_data(trees_[t]); // no longer needed\n\n  if (t >= vine_struct_.get_trunc_lvl()) {\n    // only important if proximity_ was previously false (partial selection)\n    structure_known_ = true;\n  }\n  add_allowed_edges(new_tree);\n  if (boost::num_vertices(new_tree) > 2) {\n    select_edges(new_tree);\n  }\n  if (boost::num_vertices(new_tree) > 0) {\n    add_edge_info(new_tree);      // for pc estimation and next tree\n    remove_vertex_data(new_tree); // no longer needed\n    if (controls_.get_selection_criterion() == \"mbicv\") {\n      // adjust prior probability to tree level\n      controls_.set_psi0(std::pow(psi0_, t + 1));\n    }\n    if (trees_opt_.size() > t + 1) {\n      select_pair_copulas(new_tree, trees_opt_[t + 1]);\n    } else {\n      select_pair_copulas(new_tree);\n    }\n  }\n  // make sure there is space for new tree\n  trees_.resize(t + 2);\n  trees_[t + 1] = new_tree;\n}\n\ninline double\nVinecopSelector::get_mbicv_of_tree(size_t t, double loglik)\n{\n  double npars = get_npars_of_tree(t);\n  size_t non_indeps = get_num_non_indeps_of_tree(t);\n  size_t indeps = d_ - t - 1 - non_indeps;\n  double psi0 = std::pow(psi0_, t + 1);\n  double log_prior = static_cast<double>(non_indeps) * std::log(psi0) +\n                     static_cast<double>(indeps) * std::log(1.0 - psi0);\n  double n_eff = static_cast<double>(n_);\n  if (controls_.get_weights().size() > 0) {\n    n_eff = std::pow(controls_.get_weights().sum(), 2);\n    n_eff /= controls_.get_weights().array().pow(2).sum();\n  }\n\n  return -2 * loglik + std::log(n_eff) * npars - 2 * log_prior;\n}\n\n//! @brief Calculates the log-likelihood of a tree.\ninline double\nVinecopSelector::get_loglik_of_tree(size_t t)\n{\n  double ll = 0.0;\n  // trees_[0] is base tree, see make_base_tree()\n  for (const auto& e : boost::edges(trees_[t + 1])) {\n    ll += trees_[t + 1][e].pair_copula.get_loglik();\n  }\n  return ll;\n}\n\n//! @brief Calculates the numbers of parameters of a tree.\ninline double\nVinecopSelector::get_npars_of_tree(size_t t)\n{\n  double npars = 0.0;\n  // trees_[0] is base tree, see make_base_tree()\n  for (const auto& e : boost::edges(trees_[t + 1])) {\n    npars += trees_[t + 1][e].pair_copula.get_npars();\n  }\n  return npars;\n}\n\n//! @brief Calculates the numbers of independence copulas in a tree.\ninline size_t\nVinecopSelector::get_num_non_indeps_of_tree(size_t t)\n{\n  size_t num_non_indeps = 0;\n  // trees_[0] is base tree, see make_base_tree()\n  for (const auto& e : boost::edges(trees_[t + 1])) {\n    num_non_indeps += static_cast<size_t>(\n      trees_[t + 1][e].pair_copula.get_family() == BicopFamily::indep);\n  }\n  return num_non_indeps;\n}\n\n//! @brief Prints indices, family, and parameters for each pair-copula\n//! @param tree A vine tree.\ninline void\nVinecopSelector::print_pair_copulas_of_tree(size_t t)\n{\n  // trees_[0] is the base tree, see make_base_tree()\n  for (auto e : boost::edges(trees_[t + 1])) {\n    std::cout << get_pc_index(e, trees_[t + 1]) << \" <-> \"\n              << trees_[t + 1][e].pair_copula.str() << std::endl;\n  }\n}\n\n//! @brief Gets all criterion values that got thresholded to zero.\ninline std::vector<double>\nVinecopSelector::get_thresholded_crits()\n{\n  std::vector<double> crits;\n  for (size_t t = 1; t < trees_.size(); ++t) {\n    for (auto e : boost::edges(trees_[t])) {\n      if (trees_[t][e].crit < controls_.get_threshold()) {\n        crits.push_back(trees_[t][e].crit);\n      }\n    }\n  }\n\n  return crits;\n}\n\ninline void\nVinecopSelector::initialize_new_fit(const Eigen::MatrixXd& data)\n{\n  trees_[0] = make_base_tree(data);\n}\n\ninline void\nVinecopSelector::set_current_fit_as_opt(const double& loglik)\n{\n  threshold_ = controls_.get_threshold();\n  trees_opt_ = trees_;\n  loglik_ = loglik;\n}\n\n//! @brief Instantiates base tree of the vine.\n//!\n//! The base tree is a star on d + 1 variables, where the conditioned\n//! set of each edge consists of a single number. When building the next\n//! tree, the edges become vertices. Because the base graph was a star\n//! all edges are allowed by the proximity condition, and the edges will\n//! have a conditioned set consisting of the two vertex indices. This\n//! will be the first actual tree of the vine.\n//!\n//! @param data nxd matrix of copula data.\n//! @return A VineTree object containing the base graph.\ninline VineTree\nVinecopSelector::make_base_tree(const Eigen::MatrixXd& data)\n{\n  VineTree base_tree(d_);\n  auto order = vine_struct_.get_order();\n  auto disc_cols = get_disc_cols(var_types_);\n\n  // a star connects the root node (d) with all other nodes\n  for (size_t target = 0; target < d_; ++target) {\n    tools_interface::check_user_interrupt(target % 10000 == 0);\n    // add edge and extract edge iterator\n    auto e = add_edge(d_, target, base_tree).first;\n    // inititialize hfunc1 with actual data for variable \"target\"\n    // data need are reordered to correspond to natural order (neccessary\n    // when structure is fixed)\n    base_tree[e].hfunc1 = data.col(order[target] - 1);\n    if (var_types_[order[target] - 1] == \"d\") {\n      base_tree[e].hfunc1_sub = data.col(d_ + disc_cols[order[target] - 1]);\n      base_tree[e].var_types = { \"d\", \"d\" };\n    }\n\n    // identify edge with variable \"target\" and initialize sets\n    base_tree[e].conditioned.reserve(2);\n    base_tree[e].conditioned.push_back(order[target] - 1);\n    base_tree[e].conditioning.reserve(d_ - 2);\n    base_tree[e].all_indices = base_tree[e].conditioned;\n  }\n\n  return base_tree;\n}\n\n//! @brief Converts the edge set into vertex set of a new graph.\n//!\n//! Further information about the structure is passed along:\n//!     - conditioned/conditioning set,\n//!     - indices of vertices connected by the edge in the previous tree.\n//!\n//! @param tree T_{k}.\n//! @return A edge-less graph of vertices, each representing one edge of the\n//!     previous tree.\ninline VineTree\nVinecopSelector::edges_as_vertices(const VineTree& prev_tree)\n{\n  // start with full graph\n  size_t d = num_edges(prev_tree);\n  VineTree new_tree(d);\n\n  // copy & paste information from previous tree\n  int i = 0;\n  for (auto e : boost::edges(prev_tree)) {\n    new_tree[i].hfunc1 = prev_tree[e].hfunc1;\n    new_tree[i].hfunc2 = prev_tree[e].hfunc2;\n    new_tree[i].hfunc1_sub = prev_tree[e].hfunc1_sub;\n    new_tree[i].hfunc2_sub = prev_tree[e].hfunc2_sub;\n    new_tree[i].conditioned = prev_tree[e].conditioned;\n    new_tree[i].conditioning = prev_tree[e].conditioning;\n    new_tree[i].all_indices = prev_tree[e].all_indices;\n    new_tree[i].prev_edge_indices.reserve(2);\n    new_tree[i].prev_edge_indices.push_back(boost::source(e, prev_tree));\n    new_tree[i].prev_edge_indices.push_back(boost::target(e, prev_tree));\n    new_tree[i].var_types = prev_tree[e].var_types;\n    ++i;\n  }\n\n  return new_tree;\n}\n\n//! @brief Finds common neighbor in previous tree.\n//! @param v0,v1 vertices in the tree.\n//! @param tree the current tree.\n//! @return Gives the index of the vertex in the previous tree that was\n//!     shared by e0, e1, the edge representations of v0, v1.\ninline ptrdiff_t\nVinecopSelector::find_common_neighbor(size_t v0,\n                                      size_t v1,\n                                      const VineTree& tree)\n{\n  auto ei0 = tree[v0].prev_edge_indices;\n  auto ei1 = tree[v1].prev_edge_indices;\n  auto ei_common = intersect(ei0, ei1);\n\n  if (ei_common.size() == 0) {\n    return -1;\n  } else {\n    return ei_common[0];\n  }\n}\n\n//! @brief Computes a fit id; can be used to re-use already fitted pair-copulas.\n//! @param edge.\ninline double\nVinecopSelector::compute_fit_id(const EdgeProperties& e)\n{\n  double id = 0.0;\n  if (controls_.needs_sparse_select()) {\n    // the formula is quite arbitrary, but sufficient for\n    // identifying situations where fits can be re-used\n    id = (e.pc_data.col(0) - 2 * e.pc_data.col(1)).sum();\n    id += 5.0 * static_cast<double>(e.crit < controls_.get_threshold());\n  }\n\n  return id;\n}\n\n//! @brief Collapses a graph to the minimum spanning tree.\n//! @param graph The input graph.\n//! @return the input graph with all non-MST edges removed.\ninline void\nVinecopSelector::min_spanning_tree(VineTree& graph)\n{\n  size_t d = num_vertices(graph);\n  std::vector<size_t> targets(d);\n  prim_minimum_spanning_tree(graph, targets.data());\n  for (size_t v1 = 0; v1 < d; ++v1) {\n    for (size_t v2 = 0; v2 < v1; ++v2) {\n      if ((v2 != targets[v1]) & (v1 != targets[v2])) {\n        boost::remove_edge(v1, v2, graph);\n      }\n    }\n  }\n}\n\n//! @brief Adds conditioned info and data for each edge.\n//!\n//! See, e.g., Czado (2010), \"Pair-copula constructions of multivariate\n//! copulas\", url: https://mediatum.ub.tum.de/doc/1079253/file.pdf\n//! @param tree A vine tree.\ninline void\nVinecopSelector::add_edge_info(VineTree& tree)\n{\n  for (auto e : boost::edges(tree)) {\n    add_pc_info(e, tree);\n  }\n}\n\n//! @brief Removes data (hfunc1/hfunc2/pc_data) from all edges of a vine tree.\n//! @param tree A vine tree.\ninline void\nVinecopSelector::remove_edge_data(VineTree& tree)\n{\n  for (auto e : boost::edges(tree)) {\n    tree[e].hfunc1 = Eigen::VectorXd();\n    tree[e].hfunc2 = Eigen::VectorXd();\n    tree[e].hfunc1_sub = Eigen::VectorXd();\n    tree[e].hfunc2_sub = Eigen::VectorXd();\n    tree[e].pc_data = Eigen::MatrixXd(0, 2);\n  }\n}\n\n//! @brief Removes data (hfunc1/hfunc2/pc_data) from all vertices of a vine\n//! tree.\n//! @param tree A vine tree.\ninline void\nVinecopSelector::remove_vertex_data(VineTree& tree)\n{\n  for (auto v : boost::vertices(tree)) {\n    tree[v].hfunc1 = Eigen::VectorXd();\n    tree[v].hfunc2 = Eigen::VectorXd();\n    tree[v].hfunc1_sub = Eigen::VectorXd();\n    tree[v].hfunc2_sub = Eigen::VectorXd();\n  }\n}\n\n//! @brief Fits and selects a pair copula for each edges.\n//! @param tree A vine tree preprocessed with `add_edge_info()`.\n//! @param tree_opt The current optimal tree (used only for sparse\n//!     selection).\ninline void\nVinecopSelector::select_pair_copulas(VineTree& tree, const VineTree& tree_opt)\n{\n  auto select_pc = [&](EdgeIterator e) -> void {\n    tools_interface::check_user_interrupt();\n    bool is_thresholded = (tree[e].crit < controls_.get_threshold());\n    bool used_old_fit = false;\n\n    tree[e].fit_id = compute_fit_id(tree[e]);\n    if (boost::num_edges(tree_opt) > 0) {\n      auto old_fit = find_old_fit(tree[e].fit_id, tree_opt);\n      if (old_fit.second) { // indicates if match was found\n        // data and thresholding status haven't changed,\n        // we can use old fit\n        used_old_fit = true;\n        tree[e].pair_copula = tree_opt[old_fit.first].pair_copula;\n      }\n    }\n\n    if (!used_old_fit) {\n      tree[e].pair_copula = vinecopulib::Bicop();\n      tree[e].pair_copula.set_var_types(tree[e].var_types);\n      if (!is_thresholded) {\n        tree[e].pair_copula.select(tree[e].pc_data, controls_);\n      }\n    }\n\n    tree[e].hfunc1 = tree[e].pair_copula.hfunc1(tree[e].pc_data);\n    tree[e].hfunc2 = tree[e].pair_copula.hfunc2(tree[e].pc_data);\n    if (tree[e].var_types[1] == \"d\") {\n      auto sub_data = tree[e].pc_data;\n      sub_data.col(1) = sub_data.col(3);\n      tree[e].hfunc1_sub = tree[e].pair_copula.hfunc1(sub_data);\n    }\n    if (tree[e].var_types[0] == \"d\") {\n      auto sub_data = tree[e].pc_data;\n      sub_data.col(0) = sub_data.col(2);\n      tree[e].hfunc2_sub = tree[e].pair_copula.hfunc2(sub_data);\n    }\n  };\n\n  // make sure that Bicop.select() doesn't spawn new threads\n  size_t num_threads = controls_.get_num_threads();\n  controls_.set_num_threads(0);\n  pool_.map(select_pc, boost::edges(tree));\n  pool_.wait();\n  controls_.set_num_threads(num_threads);\n}\n\n//! @brief Finds the fitted pair-copula from the previous iteration.\ninline FoundEdge\nVinecopSelector::find_old_fit(double fit_id, const VineTree& old_graph)\n{\n  auto edge = boost::edge(0, 1, old_graph).first;\n  bool fit_with_same_id = false;\n  for (auto e : boost::edges(old_graph)) {\n    if (fit_id == old_graph[e].fit_id) {\n      fit_with_same_id = true;\n      edge = e;\n    }\n  }\n  return std::make_pair(edge, fit_with_same_id);\n}\n\n//! @brief Gets edge index for the vine (like 1, 2; 3).\n//! @param e A descriptor for the edge.\n//! @param tree A vine tree.\ninline std::string\nVinecopSelector::get_pc_index(const EdgeIterator& e, const VineTree& tree)\n{\n  std::stringstream index;\n  // add 1 everywhere for user-facing representation (boost::graph\n  // starts at 0)\n  index << tree[e].conditioned[0] + 1 << \",\" << tree[e].conditioned[1] + 1;\n  if (tree[e].conditioning.size() > 0) {\n    index << \" | \";\n    for (unsigned int i = 0; i < tree[e].conditioning.size(); ++i) {\n      index << tree[e].conditioning[i] + 1;\n      if (i < tree[e].conditioning.size() - 1)\n        index << \",\";\n    }\n  }\n\n  return index.str().c_str();\n}\n}\n}\n", "meta": {"hexsha": "cf9c4d0c3cb268af1a98b8127c84ed3ae0f2dc8a", "size": 34179, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "include/vinecopulib/vinecop/implementation/tools_select.ipp", "max_stars_repo_name": "tvatter/vinecoplib", "max_stars_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-05-05T13:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T23:40:01.000Z", "max_issues_repo_path": "include/vinecopulib/vinecop/implementation/tools_select.ipp", "max_issues_repo_name": "vinecopulib/vinecopulib", "max_issues_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 264.0, "max_issues_repo_issues_event_min_datetime": "2017-03-28T10:07:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T10:04:39.000Z", "max_forks_repo_path": "include/vinecopulib/vinecop/implementation/tools_select.ipp", "max_forks_repo_name": "tvatter/vinecoplib", "max_forks_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-04-24T13:54:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T16:56:17.000Z", "avg_line_length": 32.9277456647, "max_line_length": 80, "alphanum_fraction": 0.6400421311, "num_tokens": 9514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5102956913380823}}
{"text": "/***************************************************************************\n *  @file       longest_common_subsequence.hpp\n *  @author     alan.w\n *  @date       09  August 2014\n *  @remark     CLRS Algorithms implementation, using C++ templates.\n ***************************************************************************/\n\n#ifndef LONGEST_COMMON_SUBSEQUENCE_HPP\n#define LONGEST_COMMON_SUBSEQUENCE_HPP\n\n#include <functional>\n#include \"matrix.hpp\"\n#include \"color.hpp\"\n\nnamespace ch15 {\n/**\n * @brief  as a part of an entry\n */\nenum class Arrow\n{\n    NA, LEFT, UP, DIAGONAL\n};\n\n/**\n * @brief The Entry struct\n *\n * as an entry of Table\n */\ntemplate<typename T, typename A>\nstruct Entry\n{\n    //! Ctors\n    Entry() = default;\n    Entry(const T& len, const A& arw = Arrow::NA):\n        length(len), arrow(arw)\n    {}\n\n    //! update this entry\n    Entry operator ()(const T& len, const A& arw = Arrow::NA)\n    {\n        length  =   len;\n        arrow   =   arw;\n\n        return *this;\n    }\n\n    T length = 0;\n    A arrow = Arrow::NA;\n};\n\n/**\n * @brief operator <<\n *\n * called when printing a boost matrix\n */\ntemplate<typename T, typename A>\ninline std::ostream&\noperator <<(std::ostream& os , const Entry<T,A>& etr)\n{\n    os << color::green(\"[\")\n       << etr.length << \",\";\n\n    switch (etr.arrow)\n    {\n    case Arrow::NA      :   os << \" \";      break;\n    case Arrow::LEFT    :   os << \"<\";      break;\n    case Arrow::DIAGONAL:   os << \"\\\\\";     break;\n    case Arrow::UP      :   os << \"^\";      break;\n    }\n\n    os << color::green(\"]\");\n\n    return os;\n}\n\n/**\n * @brief operator >=\n *\n * overloaded for comparison in build_lcs_table\n */\ntemplate<typename T, typename A>\ninline bool\noperator >=(const Entry<T,A>& lhs, const Entry<T,A>& rhs)\n{\n    return lhs.length >= rhs.length;\n}\n\n//! @alias for Table\ntemplate<typename T, typename A>\nusing Table = ch15::Matrix<Entry<T,A>>;\n\n/**\n * @brief build lcs table\n * @param lhs   X\n * @param rhs   Y\n *\n * @pseudocode  LCS-LENGTH\n * @page    394, CLRS\n * @complx  O(mn)\n *\n * @note    the tables b and c in the peudocode have been merged in to one.\n *          so only one table is returned\n */\ntemplate<typename Range, typename A = Arrow>\nTable<typename Range::size_type, A>\nbuild_lcs_table(const Range& lhs, const Range& rhs)\n{\n    //! types def\n    using SizeType  =   typename Range::size_type;\n    using TableType =   Table<SizeType, A>;\n\n    //! init\n    SizeType rows = lhs.size() + 1;\n    SizeType cols = rhs.size() + 1;\n    TableType lcs(rows, cols);\n    //! ^^^^^^^^^^^^^^^^^^^^^^@attention  :\n    //!     the Entry's default ctor grantee that its member length has\n    //!     default value 0.so no need to implementlines 4 - 7 explicitly.\n\n    //! build lcs table\n    for(SizeType r = 1; r != rows; ++r)\n        for(SizeType c = 1; c != cols; ++c)\n        {\n            if(lhs[r - 1]   ==  rhs[c - 1])\n                lcs(r,c) (lcs(r - 1, c - 1).length + 1   ,  Arrow::DIAGONAL);\n            else if(lcs(r - 1, c) >= lcs(r, c - 1))\n                lcs(r,c) (lcs(r - 1, c).length           ,  Arrow::UP);\n            else\n                lcs(r,c) (lcs(r, c - 1).length           ,  Arrow::LEFT);\n        }\n\n    return lcs;\n}\n\n/**\n * @brief The LongestCommonSubsequence class\n */\ntemplate<typename Range, typename A = ch15::Arrow>\nclass LongestCommonSubsequence\n{\npublic:\n    //! types def\n    using SizeType  =   typename Range::size_type;\n    using TableType =   ch15::Table<SizeType, A>;\n    using Pointer   =   const Range*;\n\n    //! Ctor\n    LongestCommonSubsequence(const Range& l, const Range& r):\n        lhs(&l),\n        rhs(&r),\n        maze(ch15::build_lcs_table(l,r))\n    {}\n\n    /**\n     * @brief print_maze\n     *\n     * print the maze built by build_lcs_table\n     */\n    void print_maze()const\n    {\n        ch15::print(maze);\n    }\n\n    /**\n     * @brief return the generated longest common sequence\n     *\n     * @pseudocode PRINT-LCS\n     * @page    395, CLRS\n     * @complx  O(m + n)\n     */\n    Range generate() const\n    {\n        assert(lhs && rhs);\n        using Lambda = std::function<void(SizeType, SizeType)>;\n        Range lcs;\n\n        //! a recursive lamda that performs the real work\n        Lambda build_lcs = [&lcs, &build_lcs, this](SizeType row, SizeType col)\n        {\n            //! stop condition\n            if(row == 0 || col == 0)    return;\n\n            //! build the longest common sequence\n            if(maze(row, col).arrow ==  Arrow::DIAGONAL)\n            {\n                build_lcs(row - 1, col - 1);\n                lcs.push_back((*lhs)[row - 1]);\n            }\n            else if(maze(row, col).arrow ==  Arrow::UP)\n                build_lcs(row - 1, col);\n            else\n                build_lcs(row, col - 1);\n        };\n\n        //! call the lambda\n        build_lcs(lhs->size(), rhs->size());\n        return lcs;\n    }\n\nprivate:\n    Pointer lhs;\n    Pointer rhs;\n    TableType maze;\n};\n\n}//namespace\n#endif // LONGEST_COMMON_SUBSEQUENCE_HPP\n\n//! @test   print ch15::table\n//#include <iostream>\n//#include <boost/numeric/ublas/io.hpp>\n//#include \"longest_common_subsequence.hpp\"\n//#include \"color.hpp\"\n\n//int main()\n//{\n//    using TableType = ch15::Table<int, ch15::Arrow>;\n\n//    TableType tbl(3,3, ch15::Entry<int, ch15::Arrow>());\n//    std::cout << tbl << std::endl;\n\n//    std::cout << color::red(\"\\nend\\n\");\n//    return 0;\n//}\n\n//! @test   build_lcs_table\n//!         i.e. LCS-LENGTH\n//!\n//#include <iostream>\n//#include <boost/numeric/ublas/io.hpp>\n//#include \"longest_common_subsequence.hpp\"\n//#include \"color.hpp\"\n\n//int main()\n//{\n//    //! the same strings as that on page 394, CLRS.\n//    std::vector<std::string> lhs = {\"A\", \"B\", \"C\", \"B\", \"D\", \"A\", \"B\"};\n//    std::vector<std::string> rhs = {\"B\", \"D\", \"C\", \"A\", \"B\", \"A\"};\n\n//    auto ret = ch15::build_lcs_table(lhs, rhs);\n//    ch15::print(ret);\n\n//    std::cout << color::red(\"\\nend\\n\");\n//    return 0;\n//}\n\n\n//! @test   The LongestCommonSubsequence class\n//!         i.e. LCS-LENGTH and PRINT-LCS\n//!\n//#include <iostream>\n//#include <boost/numeric/ublas/io.hpp>\n//#include \"longest_common_subsequence.hpp\"\n//#include \"color.hpp\"\n\n//int main()\n//{\n//    //! strings used on page 394, CLRS.\n//    std::string lhs = \"ABCBDAB\";\n//    std::string rhs = \"BDCABA\";\n\n//    using LCS   =   ch15::LongestCommonSubsequence<std::string>;\n//    LCS lcs(lhs, rhs);\n//    lcs.print_maze();\n\n//    auto sequence = lcs.generate();\n//    std::cout << \"The longest common sequence = \";\n//    std::cout << color::yellow(sequence) << std::endl;\n\n//    std::cout << color::red(\"\\nend\\n\");\n//    return 0;\n//}\n//! @output:\n//[0, ] [0, ] [0, ] [0, ] [0, ] [0, ] [0, ]\n\n//[0, ] [0,^] [0,^] [0,^] [1,\\] [1,<] [1,\\]\n\n//[0, ] [1,\\] [1,<] [1,<] [1,^] [2,\\] [2,<]\n\n//[0, ] [1,^] [1,^] [2,\\] [2,<] [2,^] [2,^]\n\n//[0, ] [1,\\] [1,^] [2,^] [2,^] [3,\\] [3,<]\n\n//[0, ] [1,^] [2,\\] [2,^] [2,^] [3,^] [3,^]\n\n//[0, ] [1,^] [2,^] [2,^] [3,\\] [3,^] [4,\\]\n\n//[0, ] [1,\\] [2,^] [2,^] [3,^] [4,\\] [4,^]\n\n//The longest common sequence = BCBA\n\n//end\n\n\n\n\n\n", "meta": {"hexsha": "343cc4de421aa6fe49c83fee6cd7ddd76635d5c6", "size": 7005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ch15/longest_common_subsequence.hpp", "max_stars_repo_name": "klong13579/cppL", "max_stars_repo_head_hexsha": "7aa8afaf2d2e17578c7fd91654bedcccf0a6baab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 261.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T20:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T01:33:39.000Z", "max_issues_repo_path": "ch15/longest_common_subsequence.hpp", "max_issues_repo_name": "LeungGeorge/CLRS", "max_issues_repo_head_hexsha": "7aa8afaf2d2e17578c7fd91654bedcccf0a6baab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-04-05T11:49:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-19T08:29:52.000Z", "max_forks_repo_path": "ch15/longest_common_subsequence.hpp", "max_forks_repo_name": "LeungGeorge/CLRS", "max_forks_repo_head_hexsha": "7aa8afaf2d2e17578c7fd91654bedcccf0a6baab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 98.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T12:58:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T07:29:31.000Z", "avg_line_length": 23.5067114094, "max_line_length": 79, "alphanum_fraction": 0.5197715917, "num_tokens": 2106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.5102956890557263}}
{"text": "// CodigoCFD.cpp : Este archivo contiene la funci\u00f3n \"main\". La ejecuci\u00f3n del programa comienza y termina ah\u00ed.\n//\n\n\n#include <Eigen/Eigen>\n\n#include <mesh/mesh.h>\n#include <mesh/reader/luismi_format_mesh_reader.h>\n\n#include <math/interpolation.h>\n#include <material/material.h>\n#include <material/properties/constant_properties.h>\n#include <material/properties/ideal_gas.h>\n#include <material/material_factory.h>\n\n#include <field/state_vector.h>\n#include <field/field.h>\n\n#include <core/environment.h>\nint main()\n{\n    core::Environment simulation;\n    simulation.loadMesh();\n    simulation.buildMaterials();\n    simulation.createBoundary();\n    simulation.initializeFields();\n    simulation.solve();\n\n    return 0;\n}\n\n// Ejecutar programa: Ctrl + F5 o men\u00fa Depurar > Iniciar sin depurar\n// Depurar programa: F5 o men\u00fa Depurar > Iniciar depuraci\u00f3n\n\n// Sugerencias para primeros pasos: 1. Use la ventana del Explorador de soluciones para agregar y administrar archivos\n//   2. Use la ventana de Team Explorer para conectar con el control de c\u00f3digo fuente\n//   3. Use la ventana de salida para ver la salida de compilaci\u00f3n y otros mensajes\n//   4. Use la ventana Lista de errores para ver los errores\n//   5. Vaya a Proyecto > Agregar nuevo elemento para crear nuevos archivos de c\u00f3digo, o a Proyecto > Agregar elemento existente para agregar archivos de c\u00f3digo existentes al proyecto\n//   6. En el futuro, para volver a abrir este proyecto, vaya a Archivo > Abrir > Proyecto y seleccione el archivo .sln\n", "meta": {"hexsha": "94e61c38a4e29bb673297e7c0ffe62846f1157c9", "size": 1502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CodigoCFD.cpp", "max_stars_repo_name": "FredyTP/CFDcode", "max_stars_repo_head_hexsha": "3c11671a25dc2b84626484bf30b63089166078df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CodigoCFD.cpp", "max_issues_repo_name": "FredyTP/CFDcode", "max_issues_repo_head_hexsha": "3c11671a25dc2b84626484bf30b63089166078df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CodigoCFD.cpp", "max_forks_repo_name": "FredyTP/CFDcode", "max_forks_repo_head_hexsha": "3c11671a25dc2b84626484bf30b63089166078df", "max_forks_repo_licenses": ["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.6341463415, "max_line_length": 183, "alphanum_fraction": 0.7543275632, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.5102956860997812}}
{"text": "#define BOOST_TEST_MODULE \"test_small_inverse_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 \"../src/InverseMatrix.hpp\"\n\n#include \"test_Defs.hpp\"\nusing ax::test::tolerance;\nusing ax::test::seed;\n\n#include <random>\n\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        std::array<std::array<double, msize>, msize> rand1;\n        for(std::size_t i=0; i<msize; ++i)\n            for(std::size_t j=0; j<msize; ++j)\n                mat(i,j) = rand1[i][j] = randreal(mt);\n\n        det = ax::determinant(mat);\n    }\n\n    const ax::Matrix<double, msize,msize> inv = inverse(mat);\n    const ax::Matrix<double, msize,msize> E   = inv * mat;\n\n    for(std::size_t i=0; i<msize; ++i)\n        for(std::size_t j=0; j<msize; ++j)\n            if(i==j)\n                BOOST_CHECK_CLOSE(E(i,j), 1e0, tolerance);\n            else\n                BOOST_CHECK_SMALL(E(i,j), tolerance);\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        std::array<std::array<double, msize>, msize> rand1;\n        for(std::size_t i=0; i<msize; ++i)\n            for(std::size_t j=0; j<msize; ++j)\n                mat(i,j) = rand1[i][j] = randreal(mt);\n\n        det = ax::determinant(mat);\n    }\n\n    const ax::Matrix<double, msize,msize> inv = inverse(mat);\n    const ax::Matrix<double, msize,msize> E   = inv * mat;\n\n    for(std::size_t i=0; i<msize; ++i)\n        for(std::size_t j=0; j<msize; ++j)\n            if(i==j)\n                BOOST_CHECK_CLOSE(E(i,j), 1e0, tolerance);\n            else\n                BOOST_CHECK_SMALL(E(i,j), tolerance);\n}\n", "meta": {"hexsha": "585c7fd48ae7084c243819c7b1a747d52e1a2d5a", "size": 2073, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_2or3_inverse_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_2or3_inverse_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_2or3_inverse_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": 25.9125, "max_line_length": 62, "alphanum_fraction": 0.5923781959, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5102956801878912}}
{"text": "//#include <dlib/rand.h>\n#include <dlib/svm_threaded.h>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <random>\nusing namespace std;\n//using namespace dlib;\n\n//typedef matrix<double,2,1> sample_type;\n\n\nint main(void){\n    ofstream datafile;\n    datafile.open (\"svm_data_test.txt\");\n    \n   // dlib::rand rnd;\n    double x;\n    double y; \n    double r;\n    double theta;\n    \n    for(int i=0; i < 50; i++){\n       r = ((double)rand() / RAND_MAX)*10.0;\n       while (r > 10){\n         r = ((double)rand() / RAND_MAX)*10.0;\n       }\n       if (r < 0){r*=-1;}\n       theta = (double)rand();\n       x = r*cos(theta);\n       if (x < 0){x*=-1;}\n       y = r*sin(theta);\n       if (y<0){y*=-1;}\n       datafile << x << \" \" << y << \" \" << \"+1\\n\";\n    }  \n    \n    for(int i=0; i < 50; i++){\n       r = ((double)rand() / RAND_MAX)*10.0 + 10.0;\n       while (r < 10){\n         r = ((double)rand() / RAND_MAX)*10.0 + 10.0;\n       }\n       theta = (double)rand();\n       x = r*cos(theta);\n       y = r*sin(theta);\n       datafile << x << \" \" << y << \" \" << \"-1\\n\";\n    }  \n    datafile.close();\n\n} \n", "meta": {"hexsha": "82af30bd1c06a8333cf19968cfed17be032d9dae", "size": 1122, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/gendata_svm.cpp", "max_stars_repo_name": "ytobah/dlib-mod", "max_stars_repo_head_hexsha": "f1ddeb506b59c8b49f744323301b7f22fd3a25e0", "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/gendata_svm.cpp", "max_issues_repo_name": "ytobah/dlib-mod", "max_issues_repo_head_hexsha": "f1ddeb506b59c8b49f744323301b7f22fd3a25e0", "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/gendata_svm.cpp", "max_forks_repo_name": "ytobah/dlib-mod", "max_forks_repo_head_hexsha": "f1ddeb506b59c8b49f744323301b7f22fd3a25e0", "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.0, "max_line_length": 53, "alphanum_fraction": 0.4732620321, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5102956742760009}}
{"text": "/******************************************************************************\n * Author:   Laurent Kneip                                                    *\n * Contact:  kneip.laurent@gmail.com                                          *\n * License:  Copyright (c) 2013 Laurent Kneip, ANU. 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 * * 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 ANU nor the names of its contributors may be         *\n *   used to endorse or promote products derived from this software without   *\n *   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 ANU OR THE 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         *\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// Note: this code has been downloaded from the homepage of the \"Computer \n// Vision Laboratory\" at EPFL Lausanne, and was originally developped by the \n// authors of [4]. I only adapted it to Eigen.\n\n\n#ifndef OPENGV_ABSOLUTE_POSE_MODULES_EPNP_HPP_\n#define OPENGV_ABSOLUTE_POSE_MODULES_EPNP_HPP_\n\n#include <stdlib.h>\n#include <Eigen/Eigen>\n\nnamespace opengv\n{\nnamespace absolute_pose\n{\nnamespace modules\n{\n\nclass Epnp\n{\npublic:\n  Epnp(void);\n  ~Epnp();\n\n  void set_maximum_number_of_correspondences(const int n);\n  void reset_correspondences(void);\n  void add_correspondence(\n      const double X,\n      const double Y,\n      const double Z,\n      const double x,\n      const double y,\n      const double z);\n\n  double compute_pose(double R[3][3], double T[3]);\n\n  void relative_error(\n      double & rot_err,\n      double & transl_err,\n      const double Rtrue[3][3],\n      const double ttrue[3],\n      const double Rest[3][3],\n      const double test[3]);\n\n  void print_pose(const double R[3][3], const double t[3]);\n  double reprojection_error(const double R[3][3], const double t[3]);\n\nprivate:\n  void choose_control_points(void);\n  void compute_barycentric_coordinates(void);\n  void fill_M(\n      Eigen::MatrixXd & M,\n      const int row,\n      const double * alphas,\n      const double u,\n      const double v);\n  void compute_ccs(const double * betas, const Eigen::MatrixXd & ut);\n  void compute_pcs(void);\n\n  void solve_for_sign(void);\n\n  void find_betas_approx_1(\n      const Eigen::Matrix<double,6,10> & L_6x10,\n      const Eigen::Matrix<double,6,1> & Rho,\n      double * betas);\n  void find_betas_approx_2(\n      const Eigen::Matrix<double,6,10> & L_6x10,\n      const Eigen::Matrix<double,6,1> & Rho,\n      double * betas);\n  void find_betas_approx_3(\n      const Eigen::Matrix<double,6,10> & L_6x10,\n      const Eigen::Matrix<double,6,1> & Rho,\n      double * betas);\n  void qr_solve(\n      Eigen::Matrix<double,6,4> & A,\n      Eigen::Matrix<double,6,1> & b,\n      Eigen::Matrix<double,4,1> & X);\n\n  double dot(const double * v1, const double * v2);\n  double dist2(const double * p1, const double * p2);\n\n  void compute_rho(Eigen::Matrix<double,6,1> & Rho);\n  void compute_L_6x10(\n      const Eigen::MatrixXd & Ut,\n      Eigen::Matrix<double,6,10> & L_6x10 );\n\n  void gauss_newton(\n      const Eigen::Matrix<double,6,10> & L_6x10,\n      const Eigen::Matrix<double,6,1> & Rho,\n      double current_betas[4]);\n  void compute_A_and_b_gauss_newton(\n      const Eigen::Matrix<double,6,10> & L_6x10,\n      const Eigen::Matrix<double,6,1> & Rho,\n      double cb[4],\n      Eigen::Matrix<double,6,4> & A,\n      Eigen::Matrix<double,6,1> & b);\n\n  double compute_R_and_t(\n      const Eigen::MatrixXd & Ut,\n      const double * betas,\n      double R[3][3],\n      double t[3]);\n\n  void estimate_R_and_t(double R[3][3], double t[3]);\n\n  void copy_R_and_t(\n      const double R_dst[3][3],\n      const double t_dst[3],\n      double R_src[3][3],\n      double t_src[3]);\n\n  void mat_to_quat(const double R[3][3], double q[4]);\n\n\n  double uc, vc, fu, fv;\n\n  double * pws, * us, * alphas, * pcs;\n  int * signs; //added!\n  int maximum_number_of_correspondences;\n  int number_of_correspondences;\n\n  double cws[4][3], ccs[4][3];\n  double cws_determinant;\n};\n\n}\n}\n}\n\n#endif /* OPENGV_ABSOLUTE_POSE_MODULES_EPNP_HPP_ */\n", "meta": {"hexsha": "a46d8d2c231e1051c293f0be67af2890c51d33c2", "size": 5629, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/opengv/absolute_pose/modules/Epnp.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "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/opengv/absolute_pose/modules/Epnp.hpp", "max_issues_repo_name": "PXLVision/opengv", "max_issues_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/opengv/absolute_pose/modules/Epnp.hpp", "max_forks_repo_name": "PXLVision/opengv", "max_forks_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "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.9627329193, "max_line_length": 80, "alphanum_fraction": 0.6063243915, "num_tokens": 1339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5102753997376069}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/ext/std/ratio.hpp>\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <laws/ring.hpp>\n\n#include <ratio>\nusing namespace boost::hana;\n\n\nint main() {\n    auto ratios = make<Tuple>(\n          std::ratio<0>{}\n        , std::ratio<1, 3>{}\n        , std::ratio<1, 2>{}\n        , std::ratio<2, 6>{}\n        , std::ratio<3, 1>{}\n        , std::ratio<7, 8>{}\n        , std::ratio<3, 5>{}\n        , std::ratio<2, 1>{}\n    );\n\n    //////////////////////////////////////////////////////////////////////////\n    // Ring\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // mult\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                mult(std::ratio<3, 4>{}, std::ratio<5, 10>{}),\n                std::ratio<3*5, 4*10>{}\n            ));\n        }\n\n        // one\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                one<ext::std::Ratio>(),\n                std::ratio<1, 1>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                one<ext::std::Ratio>(),\n                std::ratio<2, 2>{}\n            ));\n        }\n\n        // laws\n        test::TestRing<ext::std::Ratio>{ratios};\n    }\n}\n", "meta": {"hexsha": "f670cae62b8d8d1cef6816d0b2a2749704d6ebc9", "size": 1396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ext/std/ratio/ring.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/ext/std/ratio/ring.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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/ext/std/ratio/ring.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "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.6610169492, "max_line_length": 78, "alphanum_fraction": 0.4233524355, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5102753948631499}}
{"text": "#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\n#include \"Grid.hpp\"\n#include \"SketchUtils.hpp\"\n#include \"CountMinSketch.hpp\"\n\nBOOST_AUTO_TEST_CASE( GridTest_PositiveDimRanges ) {\n\tfloat gridSize = 0.2;\n\n\tGrid* grid = new Grid(gridSize);\n\n\tstd::vector<double> point = { 0.1, 0.1 };\n\tstd::vector<int> coordsValues = grid->getGridCoords(point);\n\n\tstd::vector<int> coordsExpected = { 0, 0 };\n\n\n\tBOOST_CHECK_EQUAL_COLLECTIONS(coordsValues.begin(), coordsValues.end(),\n\t\t\tcoordsExpected.begin(), coordsExpected.end());\n\n\n\tstd::vector<std::vector<int>> nearCoordsValues = grid->getNearCoords(\n\t\t\tcoordsExpected);\n\tBOOST_CHECK_EQUAL(5, nearCoordsValues.size());\n}\n\n\n\nBOOST_AUTO_TEST_CASE( GridTest_MixedDimRanges ) {\n\tfloat gridSize = 0.2;\n\n\tGrid* grid = new Grid(gridSize);\n\n\tstd::vector<double> point = { -0.5, -0.5 };\n\tstd::vector<int> coordsValues = grid->getGridCoords(point);\n\tstd::vector<int> coordsExpected = { -2, -2 };\n\n\tBOOST_CHECK_EQUAL_COLLECTIONS(coordsValues.begin(), coordsValues.end(),\n\t\t\tcoordsExpected.begin(), coordsExpected.end());\n\n\tstd::vector<std::vector<int>> nearCoordsValues = grid->getNearCoords(\n\t\t\tcoordsExpected);\n\tBOOST_CHECK_EQUAL(5, nearCoordsValues.size());\n\n\n\tpoint =\t{\t0.9, 0.9};\n\tcoordsValues = grid->getGridCoords(point);\n\tcoordsExpected = {\t4, 4};\n\n\tBOOST_CHECK_EQUAL_COLLECTIONS(coordsValues.begin(), coordsValues.end(),\n\t\t\tcoordsExpected.begin(), coordsExpected.end());\n\n}\n\n\nBOOST_AUTO_TEST_CASE( SketchUtilsTest ) {\n\tfloat cmDelta = 0.01;\n\tfloat cmEpsilon = 0.05;\n\tSketchUtils* utils = new SketchUtils(cmDelta, cmEpsilon);\n\n\tBOOST_CHECK_EQUAL(utils->getBitNo(), 275);\n\tBOOST_CHECK_EQUAL(utils->getHashNo(), 5);\n}\n\nBOOST_AUTO_TEST_CASE( CountMinSketchTest_SingleWindow ) {\n\tint thld = 2;\n\tint bitNo = 20;\n\tint wSize = 10;\n\tint hashNo = 10;\n\n\tCountMinSketch* countMin = new CountMinSketch(wSize, bitNo, thld);\n\n\tBOOST_CHECK_EQUAL(false, countMin->update(0, std::vector<int> { 0, hashNo + 0 }));\n\tBOOST_CHECK_EQUAL(true, countMin->update(1, std::vector<int> { 0, hashNo + 0 }));\n\tBOOST_CHECK_EQUAL(false, countMin->update(2, std::vector<int> { 0, hashNo + 0 }));\n\n\tBOOST_CHECK_EQUAL(false, countMin->update(3, std::vector<int> { 1, hashNo + 0 }));\n\tBOOST_CHECK_EQUAL(true, countMin->update(4, std::vector<int> { 1, hashNo + 0 }));\n\tBOOST_CHECK_EQUAL(false, countMin->update(5, std::vector<int> { 1, hashNo + 0 }));\n}\n\nBOOST_AUTO_TEST_CASE( CountMinSketchTest_MultipleWindows ) {\n\tint thld = 2;\n\tint bitNo = 20;\n\tint wSize = 4;\n\tint hashNo = 10;\n\n\tCountMinSketch* countMin = new CountMinSketch(wSize, bitNo, thld);\n\n\t// win 1\n\t//std::cout << \"win1\" << std::endl;\n\tBOOST_CHECK_EQUAL(false, countMin->update(0, std::vector<int> { 0, hashNo + 0 }));\n\tBOOST_CHECK_EQUAL(true, countMin->update(1, std::vector<int> { 0, hashNo + 0 }));\n\tBOOST_CHECK_EQUAL(false, countMin->update(2, std::vector<int> { 0, hashNo + 0 }));\n\tBOOST_CHECK_EQUAL(false, countMin->update(3, std::vector<int> { 0, hashNo + 0 }));\n\n\t// win 2\n\t//std::cout << \"win2\" << std::endl;\n\tBOOST_CHECK_EQUAL(true, countMin->update(4, std::vector<int> { 0, hashNo + 0 }));\n\tBOOST_CHECK_EQUAL(false, countMin->update(5, std::vector<int> { 0, hashNo + 1 }));\n\tBOOST_CHECK_EQUAL(false, countMin->update(6, std::vector<int> { 1, hashNo + 3 }));\n\tBOOST_CHECK_EQUAL(false, countMin->update(7, std::vector<int> { 1, hashNo + 2 }));\n\n\t// win 3\n\t//std::cout << \"win3\" << std::endl;\n\tBOOST_CHECK_EQUAL(false, countMin->update(8, std::vector<int> { 0, hashNo + 0 }));\n\tBOOST_CHECK_EQUAL(false, countMin->update(9, std::vector<int> { 1, hashNo + 3 }));\n\tBOOST_CHECK_EQUAL(false, countMin->update(10, std::vector<int> { 0, hashNo + 1 }));\n\tBOOST_CHECK_EQUAL(false, countMin->update(11, std::vector<int> { 0, hashNo + 0 }));\n\n\t// win 4\n\t//std::cout << \"win4\" << std::endl;\n\tBOOST_CHECK_EQUAL(true, countMin->update(12, std::vector<int> { 0, hashNo + 0 }));\n\tBOOST_CHECK_EQUAL(false, countMin->update(13, std::vector<int> { 1, hashNo + 0 }));\n\tBOOST_CHECK_EQUAL(false, countMin->update(14, std::vector<int> { 0, hashNo + 0 }));\n\tBOOST_CHECK_EQUAL(false, countMin->update(15, std::vector<int> { 0, hashNo + 0 }));\n}\n", "meta": {"hexsha": "c062ae66dc0a96f851943ceb0731f06b602885a0", "size": 4104, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestBasics.cpp", "max_stars_repo_name": "a1sabau/bloomstream", "max_stars_repo_head_hexsha": "9195e3dea4bc7321a9dbf7a968d9c66285e38f7a", "max_stars_repo_licenses": ["MIT"], "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/TestBasics.cpp", "max_issues_repo_name": "a1sabau/bloomstream", "max_issues_repo_head_hexsha": "9195e3dea4bc7321a9dbf7a968d9c66285e38f7a", "max_issues_repo_licenses": ["MIT"], "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/TestBasics.cpp", "max_forks_repo_name": "a1sabau/bloomstream", "max_forks_repo_head_hexsha": "9195e3dea4bc7321a9dbf7a968d9c66285e38f7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-08T00:38:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-08T00:38:28.000Z", "avg_line_length": 34.487394958, "max_line_length": 84, "alphanum_fraction": 0.6929824561, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.5102063546025017}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file DcsLossFunc.hpp\n///\n/// \\author Sean Anderson, ASRL\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef STEAM_DCS_LOSS_FUNCTION_HPP\n#define STEAM_DCS_LOSS_FUNCTION_HPP\n\n#include <Eigen/Core>\n\n#include <steam/problem/lossfunc/LossFunctionBase.hpp>\n\nnamespace steam {\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Huber loss function class\n//////////////////////////////////////////////////////////////////////////////////////////////\nclass DcsLossFunc : public LossFunctionBase\n{\n public:\n\n  /// Convenience typedefs\n  typedef std::shared_ptr<DcsLossFunc> Ptr;\n  typedef std::shared_ptr<const DcsLossFunc> ConstPtr;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor -- k is the `threshold' based on number of std devs (1-3 is typical)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  DcsLossFunc(double k) : k2_(k*k) {}\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Cost function (basic evaluation of the loss function)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual double cost(double whitened_error_norm) const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Weight for iteratively reweighted least-squares (influence function div. by error)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual double weight(double whitened_error_norm) const;\n\n private:\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Huber constant\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  double k2_;\n};\n\n} // steam\n\n#endif // STEAM_DCS_LOSS_FUNCTION_HPP\n", "meta": {"hexsha": "f4acc700a17103bbc7e67d49381fe541e493bac6", "size": 2131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/steam/problem/lossfunc/DcsLossFunc.hpp", "max_stars_repo_name": "utiasASRL/steam", "max_stars_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-10-17T01:37:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:55:47.000Z", "max_issues_repo_path": "include/steam/problem/lossfunc/DcsLossFunc.hpp", "max_issues_repo_name": "utiasASRL/steam", "max_issues_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-21T21:25:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-01T23:08:57.000Z", "max_forks_repo_path": "include/steam/problem/lossfunc/DcsLossFunc.hpp", "max_forks_repo_name": "utiasASRL/steam", "max_forks_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-12-21T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T23:42:14.000Z", "avg_line_length": 40.2075471698, "max_line_length": 96, "alphanum_fraction": 0.3411543876, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5102063419768186}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/assert.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/ext/std/integral_constant.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/mod.hpp>\n#include <boost/hana/not_equal.hpp>\n#include <boost/hana/pair.hpp>\n#include <boost/hana/partition.hpp>\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/type.hpp>\n\n#include <type_traits>\nnamespace hana = boost::hana;\n\n\nBOOST_HANA_CONSTANT_CHECK(\n    hana::partition(hana::tuple_c<int, 1, 2, 3, 4, 5, 6, 7>, [](auto x) {\n        return x % hana::int_c<2> != hana::int_c<0>;\n    })\n    ==\n    hana::make_pair(\n        hana::tuple_c<int, 1, 3, 5, 7>,\n        hana::tuple_c<int, 2, 4, 6>\n    )\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    hana::partition(hana::tuple_t<void, int, float, char, double>, hana::trait<std::is_floating_point>)\n    ==\n    hana::make_pair(\n        hana::tuple_t<float, double>,\n        hana::tuple_t<void, int, char>\n    )\n);\n\n\n// partition.by is syntactic sugar\nBOOST_HANA_CONSTANT_CHECK(\n    hana::partition.by(hana::trait<std::is_floating_point>,\n                       hana::tuple_t<void, int, float, char, double>)\n    ==\n    hana::make_pair(\n        hana::tuple_t<float, double>,\n        hana::tuple_t<void, int, char>\n    )\n);\n\nint main() { }\n", "meta": {"hexsha": "33ff14dc6351ff8829617a9388714fad08a42e05", "size": 1432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/partition.cpp", "max_stars_repo_name": "qicosmos/hana", "max_stars_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-06T05:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T21:48:27.000Z", "max_issues_repo_path": "example/partition.cpp", "max_issues_repo_name": "qicosmos/hana", "max_issues_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "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/partition.cpp", "max_forks_repo_name": "qicosmos/hana", "max_forks_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-06T10:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-06T10:50:17.000Z", "avg_line_length": 26.0363636364, "max_line_length": 103, "alphanum_fraction": 0.655027933, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5102063404298663}}
{"text": "#define BOOST_TEST_MODULE matrix\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/matrix/all.h++>\n#include <mla/matrix/convert.h++>\n#include <mla/operations/cuthill_mckee.h++>\n\n\ntypedef boost::mpl::list<\n//\tmla::matrix::DenseRowMajor<float>,\n//\tmla::matrix::DenseRowMajor<double>,\n//\tmla::matrix::SparseCRS<float>,\n//\tmla::matrix::SparseCRS<double>,\n\tmla::matrix::SparseDOK<float>,\n\tmla::matrix::SparseDOK<double>\n> matrix_type_list;\n\n\nBOOST_AUTO_TEST_SUITE(test_operations)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( matrix_cuthill_mckee_arrowhead, MatrixType, matrix_type_list )\n{\n\tsize_t matrix_size = 6;\n\n\ttypedef typename MatrixType::scalar_type Scalar;\n\n\tMatrixType A(matrix_size, matrix_size);\n\n\t// sets an arrowhead matrix\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tA.setValue( i, i, (Scalar)1.0f );\n\t\tA.setValue( 0, i, (Scalar)1.0f );\n\t\tA.setValue( i, 0, (Scalar)1.0f );\n\t}\n\n\tstd::vector<size_t> indices = mla::cuthill_mckee(A);\n\n\n\t// the indices should be the same size as the matrix\n\tBOOST_CHECK_EQUAL( indices.size(), matrix_size );\n\n\t// Cuthill-McKee reorders matrices as arrowhead matrices\n\tfor(size_t i = 0; i < matrix_size; i++)\n\t{\n\t\tBOOST_CHECK_EQUAL( indices[i], i );\n\t}\n\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "0b63a78e4aa8f31cc352cb4fa4df22519ca6b2c1", "size": 1301, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_cuthill_mckee.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "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": "unit_tests/test_cuthill_mckee.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/test_cuthill_mckee.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "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.0508474576, "max_line_length": 93, "alphanum_fraction": 0.7240584166, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5102063404298661}}
{"text": "/*\n * Copyright 2020 TierIV. 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\n#include <gtest/gtest.h>\n\n#include <autoware_utils/geometry/boost_geometry.h>\n\n#include <boost/geometry/geometry.hpp>\n\nnamespace bg = boost::geometry;\n\nusing autoware_utils::Point2d;\nusing autoware_utils::Point3d;\n\nTEST(boost_geometry, boost_geometry_distance)\n{\n  {\n    const Point2d p1(1.0, 2.0);\n    const Point2d p2(2.0, 4.0);\n    EXPECT_DOUBLE_EQ(bg::distance(p1, p2), std::sqrt(5));\n  }\n\n  {\n    const Point3d p1(1.0, 2.0, 3.0);\n    const Point3d p2(2.0, 4.0, 6.0);\n    EXPECT_DOUBLE_EQ(bg::distance(p1, p2), std::sqrt(14));\n  }\n}\n\nTEST(boost_geometry, to_3d)\n{\n  const Point2d p_2d(1.0, 2.0);\n  const Point3d p_3d(1.0, 2.0, 3.0);\n  EXPECT_TRUE(p_2d.to_3d(3.0) == p_3d);\n}\n\nTEST(boost_geometry, to_2d)\n{\n  const Point2d p_2d(1.0, 2.0);\n  const Point3d p_3d(1.0, 2.0, 3.0);\n  EXPECT_TRUE(p_3d.to_2d() == p_2d);\n}\n\nTEST(boost_geometry, toMsg)\n{\n  using autoware_utils::toMsg;\n\n  {\n    const Point3d p(1.0, 2.0, 3.0);\n    const geometry_msgs::Point p_msg = toMsg(p);\n\n    EXPECT_DOUBLE_EQ(p_msg.x, 1.0);\n    EXPECT_DOUBLE_EQ(p_msg.y, 2.0);\n    EXPECT_DOUBLE_EQ(p_msg.z, 3.0);\n  }\n}\n\nTEST(boost_geometry, fromMsg)\n{\n  using autoware_utils::fromMsg;\n\n  geometry_msgs::Point p_msg;\n  p_msg.x = 1.0;\n  p_msg.y = 2.0;\n  p_msg.z = 3.0;\n\n  const Point3d p = fromMsg(p_msg);\n\n  EXPECT_DOUBLE_EQ(p.x(), 1.0);\n  EXPECT_DOUBLE_EQ(p.y(), 2.0);\n  EXPECT_DOUBLE_EQ(p.z(), 3.0);\n}\n", "meta": {"hexsha": "29b6f596770f22763e8efe7c35b57d457b406d83", "size": 1982, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common/util/autoware_utils/test/src/geometry/test_boost_geometry.cpp", "max_stars_repo_name": "hamlinzheng/AutowareArchitectureProposal.iv", "max_stars_repo_head_hexsha": "8a1343019aca3a648754fa50e6cab72b98db2df5", "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": "common/util/autoware_utils/test/src/geometry/test_boost_geometry.cpp", "max_issues_repo_name": "hamlinzheng/AutowareArchitectureProposal.iv", "max_issues_repo_head_hexsha": "8a1343019aca3a648754fa50e6cab72b98db2df5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-08-09T14:15:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T07:56:14.000Z", "max_forks_repo_path": "common/util/autoware_utils/test/src/geometry/test_boost_geometry.cpp", "max_forks_repo_name": "hamlinzheng/AutowareArchitectureProposal.iv", "max_forks_repo_head_hexsha": "8a1343019aca3a648754fa50e6cab72b98db2df5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-09T01:24:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-09T01:24:13.000Z", "avg_line_length": 23.0465116279, "max_line_length": 75, "alphanum_fraction": 0.6811301715, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5102063372526068}}
{"text": "// This file is a part of the OpenSurgSim project.\n// Copyright 2013-2017, SimQuest Solutions Inc.\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/// \\file\n/// Tests for the Geometry.cpp functions.\n///\n\n\n#include <gtest/gtest.h>\n#include <array>\n#include <numeric>\n#include <cmath>\n\n#include \"SurgSim/Math/Geometry.h\"\n#include \"SurgSim/Math/RigidTransform.h\"\n#include \"SurgSim/Math/UnitTests/MockTriangle.h\"\n#include <boost/math/special_functions/fpclassify.hpp>\n\nnamespace SurgSim\n{\nnamespace Math\n{\n\ntypedef double SizeType;\ntypedef Eigen::Matrix<SizeType, 3, 1> VectorType;\n\n::std::ostream& operator <<(std::ostream& stream, const VectorType& vector)\n{\n\tstream << \"(\" << vector[0] << \", \" << vector[1] << \", \" << vector[2] << \")\";\n\treturn stream;\n}\n\nbool near(double val1, double val2, double abs_error)\n{\n\tconst double diff = std::abs(val1 - val2);\n\tif (diff <= abs_error)\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n}\n\n::testing::AssertionResult eigenEqual(const VectorType& expected, const VectorType& actual)\n{\n\tdouble precision = 1e-4;\n\tif (expected.isApprox(actual, precision))\n\t{\n\t\treturn ::testing::AssertionSuccess();\n\t}\n\telse\n\t{\n\t\treturn ::testing::AssertionFailure() << \"Eigen Matrices not the same \" << std::endl <<\n\t\t\t   \"expected: \" << expected << std::endl << \"actual: \" << actual << std::endl;\n\t}\n}\n\n::testing::AssertionResult eigenAllNan(const VectorType& actual)\n{\n\tif (boost::math::isnan(actual[0]) && boost::math::isnan(actual[1]) && boost::math::isnan(actual[2]))\n\t{\n\t\treturn ::testing::AssertionSuccess();\n\t}\n\telse\n\t{\n\t\treturn ::testing::AssertionFailure() << \"Not all elements are NAN\";\n\t}\n}\n\nclass Segment\n{\npublic:\n\tVectorType a;\n\tVectorType b;\n\tVectorType ab;\n\n\tSegment() {}\n\tSegment(const VectorType& pointA, const VectorType& pointB) :\n\t\ta(pointA), b(pointB), ab(pointB - pointA) {}\n\t~Segment() {}\n\t/// Point on the line that the segment is on, s =< 1 and s >= 0 will give you a point on the segment\n\tVectorType pointOnLine(double s) const\n\t{\n\t\treturn a + ab * s;\n\t}\n};\n\n\nnamespace\n{\nSizeType epsilon = 1e-10;\n}\n\nclass GeometryTest : public ::testing::Test\n{\nprotected:\n\tvirtual void SetUp()\n\t{\n\t\tplainPoint = VectorType(45, 20, 10);\n\t\tplainSegment = Segment(VectorType(1.1, 2.2, 3.3), VectorType(6.6, 5.5, 4.4));\n\t\tplainNormal = plainSegment.ab.cross(plainPoint); // Normal to segment\n\t\tplainNormal.normalize();\n\n\t\tdegenerateSegment.a = plainSegment.a;\n\t\tdegenerateSegment.b = degenerateSegment.a + (plainSegment.ab) * 1e-9;\n\t\tdegenerateSegment.ab = degenerateSegment.b - degenerateSegment.a;\n\n\t\tplainLine = Segment(VectorType(-10.0, 10, 10), VectorType(10.0, 10.0, 10.0));\n\t\tparallelLine = Segment(VectorType(-100.0, 5.0, 5.0), VectorType(-90.0, 5.0, 5.0));\n\t\tintersectingLine = Segment(VectorType(0, 0, 0), VectorType(20, 20, 20));\n\t\tnonIntersectingLine = Segment(VectorType(5, 5, -5), VectorType(5, 5, 5));\n\n\t\ttri = MockTriangle(VectorType(5, 0, 0), VectorType(0, -5, -5), VectorType(0, 5, 5));\n\t}\n\n\tvirtual void TearDown()\n\t{\n\t}\n\tVectorType plainPoint;\n\tVector3d plainNormal;\n\tSegment plainSegment;\n\tSegment degenerateSegment;\n\n\tSegment plainLine;\n\tSegment parallelLine;\n\tSegment intersectingLine;\n\tSegment nonIntersectingLine;\n\n\tMockTriangle tri;\n};\n\nTEST_F(GeometryTest, IntersectSegmentSegment2D)\n{\n\ttypedef Eigen::Matrix<SizeType, 2, 1> Vector2;\n\tdouble s, t;\n\n\tEXPECT_TRUE(doesIntersectSegmentSegment(\n\t\tVector2(0.0, 0.0), Vector2(3.0, 0.0),\n\t\tVector2(0.0, -1.0), Vector2(1.0, 1.0), &s, &t));\n\tEXPECT_NEAR(1.0 / 6.0, s, epsilon);\n\tEXPECT_NEAR(0.5, t, epsilon);\n\n\tEXPECT_TRUE(doesIntersectSegmentSegment(\n\t\tVector2(0.0, 0.0), Vector2(2.0, 2.0),\n\t\tVector2(1.0, -1.0), Vector2(1.0, 3.0), &s, &t));\n\tEXPECT_NEAR(0.5, s, epsilon);\n\tEXPECT_NEAR(0.5, t, epsilon);\n\n\tEXPECT_TRUE(doesIntersectSegmentSegment(\n\t\tVector2(0.0, 0.0), Vector2(5.0, 5.0),\n\t\tVector2(1.0, -1.0), Vector2(1.0, 1.0), &s, &t));\n\tEXPECT_NEAR(0.2, s, epsilon);\n\tEXPECT_NEAR(1.0, t, epsilon);\n\n\tEXPECT_FALSE(doesIntersectSegmentSegment(\n\t\tVector2(0.0, 0.0), Vector2(5.0, 5.0),\n\t\tVector2(1.0, -1.0), Vector2(1.0, -1.0), &s, &t));\n\n\tEXPECT_FALSE(doesIntersectSegmentSegment(\n\t\tVector2(0.0, 0.0), Vector2(1.0, 1.0),\n\t\tVector2(1.0, -1.0), Vector2(2.0, 0.0), &s, &t));\n}\n\nTEST_F(GeometryTest, BaryCentricOfSegment)\n{\n\ttypedef Eigen::Matrix<SizeType, 2, 1> Vector2;\n\n\tVector2 outputPoint;\n\tEXPECT_TRUE(barycentricCoordinates(plainSegment.a, plainSegment.a, plainSegment.b, &outputPoint));\n\tEXPECT_TRUE(Vector2(1.0, 0.0).isApprox(outputPoint));\n\n\tEXPECT_TRUE(barycentricCoordinates(plainSegment.b, plainSegment.a, plainSegment.b, &outputPoint));\n\tEXPECT_TRUE(Vector2(0.0, 1.0).isApprox(outputPoint));\n\n\t// Halfway points\n\tEXPECT_TRUE(barycentricCoordinates(plainSegment.pointOnLine(0.5), plainSegment.a, plainSegment.b, &outputPoint));\n\tEXPECT_TRUE(Vector2(0.5, 0.5).isApprox(outputPoint));\n\n\t// Random point\n\tEXPECT_TRUE(barycentricCoordinates(plainSegment.pointOnLine(0.327), plainSegment.a, plainSegment.b, &outputPoint));\n\tEXPECT_TRUE(Vector2(1.0 - 0.327, 0.327).isApprox(outputPoint));\n\n\t// Point not on line\n\tVectorType orthogonal =\n\t\tplainSegment.ab.cross(VectorType(plainSegment.ab[0] * 0.5, plainSegment.ab[1] * 0.6, plainSegment.ab[2] * 0.7));\n\tVectorType point = plainSegment.pointOnLine(0.486) + orthogonal;\n\tEXPECT_TRUE(barycentricCoordinates(point, plainSegment.a, plainSegment.b, &outputPoint));\n\tEXPECT_TRUE(Vector2(1.0 - 0.486, 0.486).isApprox(outputPoint));\n\n\t// Degenerate\n\tEXPECT_FALSE(barycentricCoordinates(degenerateSegment.a, degenerateSegment.a, degenerateSegment.b, &outputPoint));\n\tEXPECT_TRUE(boost::math::isnan(outputPoint[0]) && boost::math::isnan(outputPoint[1]));\n}\n\n\nTEST_F(GeometryTest, BaryCentricWithNormal)\n{\n\t// Order of Points is v0,v1,v2\n\t//Check Edges first\n\tVectorType outputPoint;\n\tEXPECT_TRUE(barycentricCoordinates(tri.v0, tri.v0, tri.v1, tri.v2, tri.n, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(1, 0, 0), outputPoint));\n\n\tEXPECT_TRUE(barycentricCoordinates(tri.v1, tri.v0, tri.v1, tri.v2, tri.n, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(0, 1, 0), outputPoint));\n\n\tEXPECT_TRUE(barycentricCoordinates(tri.v2, tri.v0, tri.v1, tri.v2, tri.n, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(0, 0, 1), outputPoint));\n\n\t// Halfway points\n\tEXPECT_TRUE(barycentricCoordinates<double>(tri.pointInTriangle(0.5, 0),\n\t\t\t\ttri.v0, tri.v1, tri.v2, tri.n, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(0.5, 0.5, 0), outputPoint));\n\n\tEXPECT_TRUE(barycentricCoordinates<double>(tri.pointInTriangle(0, 0.5),\n\t\t\t\ttri.v0, tri.v1, tri.v2, tri.n, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(0.5, 0.0, 0.5), outputPoint));\n\n\t// Center Point\n\tVectorType inputPoint;\n\tinputPoint = (tri.v0 + tri.v1 + tri.v2) / 3;\n\tEXPECT_TRUE(barycentricCoordinates(inputPoint, tri.v0, tri.v1, tri.v2, tri.n, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0), outputPoint));\n\n\t// random Point\n\tinputPoint = tri.v0 * 0.2 + tri.v1 * 0.25 + tri.v2 * 0.55;\n\tEXPECT_TRUE(barycentricCoordinates(inputPoint, tri.v0, tri.v1, tri.v2, tri.n, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(0.2, 0.25, 0.55), outputPoint));\n\n\t// Degenerate\n\tEXPECT_FALSE(barycentricCoordinates(inputPoint, tri.v1, tri.v1, tri.v2, tri.n, &outputPoint));\n\tEXPECT_TRUE(eigenAllNan(outputPoint));\n\n\tEXPECT_FALSE(barycentricCoordinates(inputPoint, tri.v0, tri.v0, tri.v2, tri.n, &outputPoint));\n\tEXPECT_TRUE(eigenAllNan(outputPoint));\n\n\tEXPECT_FALSE(barycentricCoordinates(inputPoint, tri.v2, tri.v1, tri.v2, tri.n, &outputPoint));\n\tEXPECT_TRUE(eigenAllNan(outputPoint));\n}\n\nTEST_F(GeometryTest, BaryCentricWithoutNormal)\n{\n\t// Order of Points is v0,v1,v2\n\t//Check Edges first\n\tVectorType outputPoint;\n\tEXPECT_TRUE(barycentricCoordinates(tri.v0, tri.v0, tri.v1, tri.v2, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(1, 0, 0), outputPoint));\n\n\tEXPECT_TRUE(barycentricCoordinates(tri.v1, tri.v0, tri.v1, tri.v2, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(0, 1, 0), outputPoint));\n\n\tEXPECT_TRUE(barycentricCoordinates(tri.v2, tri.v0, tri.v1, tri.v2, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(0, 0, 1), outputPoint));\n\n\t// Halfway points\n\tEXPECT_TRUE(barycentricCoordinates<double>(tri.pointInTriangle(0.5, 0),\n\t\t\t\ttri.v0, tri.v1, tri.v2, tri.n, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(0.5, 0.5, 0), outputPoint));\n\n\tEXPECT_TRUE(barycentricCoordinates<double>(tri.pointInTriangle(0, 0.5),\n\t\t\t\ttri.v0, tri.v1, tri.v2, tri.n, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(0.5, 0.0, 0.5), outputPoint));\n\n\t// Center Point\n\tVectorType inputPoint;\n\tinputPoint = (tri.v0 + tri.v1 + tri.v2) / 3;\n\tEXPECT_TRUE(barycentricCoordinates(inputPoint, tri.v0, tri.v1, tri.v2, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0), outputPoint));\n\n\t// random Point\n\tinputPoint = tri.v0 * 0.2 + tri.v1 * 0.25 + tri.v2 * 0.55;\n\tEXPECT_TRUE(barycentricCoordinates(inputPoint, tri.v0, tri.v1, tri.v2, &outputPoint));\n\tEXPECT_TRUE(eigenEqual(VectorType(0.2, 0.25, 0.55), outputPoint));\n\n\t// Degenerate\n\tEXPECT_FALSE(barycentricCoordinates(inputPoint, tri.v0, tri.v0, tri.v2, &outputPoint));\n\tEXPECT_TRUE(eigenAllNan(outputPoint));\n\n\tEXPECT_FALSE(barycentricCoordinates(inputPoint, tri.v0, tri.v1, tri.v1, &outputPoint));\n\tEXPECT_TRUE(eigenAllNan(outputPoint));\n\n\tEXPECT_FALSE(barycentricCoordinates(inputPoint, tri.v2, tri.v1, tri.v2, &outputPoint));\n\tEXPECT_TRUE(eigenAllNan(outputPoint));\n}\n\nTEST_F(GeometryTest, DistancePointLine)\n{\n\tSizeType distance;\n\tVector3d result;\n\n\t// Trivial point lies on the line\n\tdistance = distancePointLine<SizeType>(plainSegment.pointOnLine(0.5), plainSegment.a, plainSegment.b, &result);\n\tEXPECT_NEAR(0.0, distance, epsilon);\n\tEXPECT_EQ(plainSegment.pointOnLine(0.5), result);\n\n\t// Point is away from the line\n\tVector3d offLinePoint = plainSegment.a + (plainNormal * 1.5);\n\tdistance = distancePointLine(offLinePoint, plainSegment.a, plainSegment.b, &result);\n\tEXPECT_NEAR(1.5, distance, epsilon);\n\tEXPECT_EQ(plainSegment.a, result);\n\n\t// Degenerate line, just do plain distance\n\toffLinePoint = plainSegment.a + plainNormal * 1.5;\n\tdistance = distancePointLine(offLinePoint, plainSegment.a, plainSegment.a, &result);\n\tEXPECT_NEAR(1.5, distance, epsilon);\n\tEXPECT_EQ(plainSegment.a, result);\n}\n\nTEST_F(GeometryTest, DistancePointSegment)\n{\n\tSizeType distance;\n\tVector3d result;\n\n\t// Trivial point lies on the line\n\tdistance = distancePointSegment(plainSegment.pointOnLine(0.5), plainSegment.a, plainSegment.b, &result);\n\tEXPECT_NEAR(0.0, distance, epsilon);\n\tEXPECT_EQ(plainSegment.pointOnLine(0.5), result);\n\n\t// Point On the line but outside the segment\n\tVectorType point = plainSegment.pointOnLine(1.5);\n\tdistance = distancePointSegment(point, plainSegment.a, plainSegment.b, &result);\n\tEXPECT_NEAR((plainSegment.ab.norm() * 0.5), distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(plainSegment.b, result));\n\n\t// Point projection is on the segment\n\tVectorType resultPoint = plainSegment.a + plainSegment.ab * 0.25;\n\tVectorType offLinePoint = resultPoint + (plainNormal * 1.5);\n\tdistance = distancePointSegment(offLinePoint, plainSegment.a, plainSegment.b, &result);\n\tEXPECT_NEAR(1.5, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(resultPoint, result));\n\n\t// Point projection is away from the segment, distance is to the closest segment point\n\tresultPoint = plainSegment.a;\n\toffLinePoint = plainSegment.a - plainSegment.ab + (plainNormal * 1.5);\n\tdistance = distancePointSegment(offLinePoint, plainSegment.a, plainSegment.b, &result);\n\tEXPECT_NEAR((offLinePoint - resultPoint).norm(), distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(resultPoint, result));\n\n\t// Other Side of the above case\n\tresultPoint = plainSegment.b;\n\toffLinePoint = plainSegment.b + plainSegment.ab * 0.01 + plainNormal * 0.1;\n\tdistance = distancePointSegment(offLinePoint, plainSegment.a, plainSegment.b, &result);\n\tEXPECT_NEAR((offLinePoint - resultPoint).norm(), distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(resultPoint, result));\n\n\n\t// Degenerated Segment\n\tdistance = distancePointSegment(offLinePoint, plainSegment.a, plainSegment.a, &result);\n\tEXPECT_NEAR((offLinePoint - plainSegment.a).norm(), distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(plainSegment.a, result));\n}\n\ntypedef std::tuple<Segment, Segment, VectorType, VectorType> LineLineCheckData;\nvoid checkLineLineDistance(const LineLineCheckData& data)\n{\n\tSegment line0 = std::get<0>(data);\n\tSegment line1 = std::get<1>(data);\n\tVectorType expectedResult0 = std::get<2>(data);\n\tVectorType expectedResult1 = std::get<3>(data);\n\tVectorType result0, result1;\n\tdouble distance;\n\n\t{\n\t\tSCOPED_TRACE(\"Forward Case\");\n\t\tdistance = distanceLineLine(line0.a, line0.b, line1.a, line1.b, &result0, &result1);\n\t\tEXPECT_NEAR((expectedResult1 - expectedResult0).norm(), distance, epsilon);\n\t\tEXPECT_TRUE(expectedResult0.isApprox(result0));\n\t\tEXPECT_TRUE(expectedResult1.isApprox(result1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Backward Case\");\n\t\tdistance = distanceLineLine(line1.a, line1.b, line0.a, line0.b, &result1, &result0);\n\t\tEXPECT_NEAR((expectedResult1 - expectedResult0).norm(), distance, epsilon);\n\t\tEXPECT_TRUE(expectedResult0.isApprox(result0));\n\t\tEXPECT_TRUE(expectedResult1.isApprox(result1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Turn around the first line\");\n\t\tdistance = distanceLineLine(line0.b, line0.a, line1.a, line1.b, &result0, &result1);\n\t\tEXPECT_NEAR((expectedResult1 - expectedResult0).norm(), distance, epsilon);\n\t\tEXPECT_TRUE(expectedResult0.isApprox(result0));\n\t\tEXPECT_TRUE(expectedResult1.isApprox(result1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"And switch lines again\");\n\t\tdistance = distanceLineLine(line0.b, line0.a, line1.a, line1.b, &result0, &result1);\n\t\tEXPECT_NEAR((expectedResult1 - expectedResult0).norm(), distance, epsilon);\n\t\tEXPECT_TRUE(expectedResult0.isApprox(result0));\n\t\tEXPECT_TRUE(expectedResult1.isApprox(result1));\n\t}\n\n\n\n}\n\nTEST_F(GeometryTest, DistanceLineLine)\n{\n\tSizeType distance;\n\tVectorType p0, p1;\n\n\t// Trivial the same line compared against itself\n\tdistance = distanceLineLine(plainSegment.a, plainSegment.b, plainSegment.a, plainSegment.b, &p0, &p1);\n\tEXPECT_NEAR(0.0, distance, epsilon);\n\n\t// Parallel Line\n\tSegment parallel = Segment(plainSegment.a + plainNormal * 2, plainSegment.b + plainNormal * 2);\n\tdistance = distanceLineLine(plainSegment.a, plainSegment.b, parallel.a, parallel.b, &p0, &p1);\n\tEXPECT_NEAR(2.0, distance, epsilon);\n\n\t// Not quite parallel, trying to get below epsilon\n\tparallel = Segment(plainSegment.a + plainNormal * 2, plainSegment.b + plainNormal * 2 - plainNormal * 1.0e-10);\n\tdistance = distanceLineLine(plainSegment.a, plainSegment.b, parallel.a, parallel.b, &p0, &p1);\n\tEXPECT_NEAR(2.0, distance, epsilon);\n\n\t{\n\t\tSCOPED_TRACE(\"Intersecting Lines\");\n\t\tLineLineCheckData data(plainLine, intersectingLine, plainLine.b, plainLine.b);\n\t\tcheckLineLineDistance(data);\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Non-intersecting Lines\");\n\t\t// Non Intersecting Line, don't know a better way to design this case besides reimplementing line/line distance\n\t\tSegment line0(VectorType(0, -5, 0), VectorType(0, 5, 0));\n\t\tSegment line1(VectorType(-5, 5, 5), VectorType(5, 5, 5));\n\t\tcheckLineLineDistance(LineLineCheckData(line0, line1, VectorType(0, 5, 0), VectorType(0, 5, 5)));\n\t}\n\n\n\t// Degenerate Cases\n\t{\n\t\tSCOPED_TRACE(\"Both lines degenerate\");\n\t\tSegment line0(VectorType(0, -5, 0), VectorType(0, -5, 0));\n\t\tSegment line1(VectorType(5, 5, 5), VectorType(5, 5, 5));\n\t\tcheckLineLineDistance(LineLineCheckData(line0, line1, line0.a, line1.a));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Only one line degenerate\");\n\t\tVectorType offLinePoint = plainSegment.a + plainSegment.ab * 0.5 + plainNormal * 1.5;\n\t\tLineLineCheckData data(plainSegment, Segment(offLinePoint, offLinePoint),\n\t\t\t\t\t\t\t   plainSegment.pointOnLine(0.5), offLinePoint);\n\t\tcheckLineLineDistance(data);\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Orthogonal Lines intersecting\");\n\t\tSegment line0(VectorType(0, -5, 0), VectorType(0, 5, 0));\n\t\tVectorType v(3, 4, 5);\n\t\tVectorType n = line0.ab.cross(v);\n\t\tn.normalize();\n\t\tSegment line1(line0.a + n, line0.a - n);\n\t\tcheckLineLineDistance(LineLineCheckData(line0, line1, line0.a, line0.a));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Orthogonal Lines non intersecting\");\n\t\tSegment line0(VectorType(0, -5, 0), VectorType(0, 5, 0));\n\t\tVectorType v(3, 4, 5);\n\t\tVectorType n = line0.ab.cross(v);\n\t\tn.normalize();\n\t\tVectorType n2 = line0.ab.cross(n);\n\t\tn2.normalize();\n\t\tSegment line1(line0.a + n + n2, line0.a - n + n2);\n\t\tcheckLineLineDistance(LineLineCheckData(line0, line1, line0.a, line0.a + n2));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"not quite orthogonal Lines non intersecting \");\n\t\tSegment line0(VectorType(0, -5, 0), VectorType(0, 5, 0));\n\t\tVectorType v(3, 4, 5);\n\t\tVectorType n = line0.ab.cross(v);\n\t\tn.normalize();\n\t\tVectorType n2 = line0.ab.cross(n);\n\t\tn2.normalize();\n\t\tSegment line1(line0.a + n + n2 + line0.ab * 0.01, line0.a - n + n2 - line0.ab * 0.01);\n\t\tcheckLineLineDistance(LineLineCheckData(line0, line1, line0.a, line0.a + n2));\n\t}\n\n}\n\n\n\nstruct SegmentData\n{\n\tSegment segment0;\n\tSegment segment1;\n\tVectorType p0;\n\tVectorType p1;\n\tSegmentData() {}\n\tSegmentData(Segment seg0, Segment seg1, VectorType vec0, VectorType vec1) :\n\t\tsegment0(seg0), segment1(seg1), p0(vec0), p1(vec1) {}\n};\n\n\nvoid testSegmentDistance(const SegmentData& segmentData, const std::string& info, size_t i)\n{\n\tSizeType distance;\n\tVectorType p0, p1;\n\n\t// The expected distance should be the distance between the two points that were\n\t// reported as being the closes ones\n\tSizeType expectedDistance = (segmentData.p1 - segmentData.p0).norm();\n\n\tdistance = distanceSegmentSegment(segmentData.segment0.a, segmentData.segment0.b,\n\t\t\t\t\t\t\t\t\t  segmentData.segment1.a, segmentData.segment1.b, &p0, &p1);\n\tEXPECT_NEAR(expectedDistance, distance, 1e-8) << \"for \" << info << \" at index \" << i;\n\tEXPECT_TRUE(eigenEqual(segmentData.p0, p0)) << \"for \" << info << \" at index \" << i;\n\tEXPECT_TRUE(eigenEqual(segmentData.p1, p1)) << \"for \" << info << \" at index \" << i;\n\n\tdistance = distanceSegmentSegment(segmentData.segment1.a, segmentData.segment1.b,\n\t\t\t\t\t\t\t\t\t  segmentData.segment0.a, segmentData.segment0.b, &p0, &p1);\n\tEXPECT_NEAR(expectedDistance, distance, 1e-8) << \"for \" << info << \" at index \" << i;\n\tEXPECT_TRUE(eigenEqual(segmentData.p1, p0)) << \"for \" << info << \" at index \" << i;\n\tEXPECT_TRUE(eigenEqual(segmentData.p0, p1)) << \"for \" << info << \" at index \" << i;\n}\n\n\n\nTEST_F(GeometryTest, DistanceSegmentSegment)\n{\n\tSizeType distance;\n\tVectorType p0, p1;\n\n\t// Intersecting segments\n\t// Intersecting inside\n\tVectorType closestPoint = plainSegment.pointOnLine(0.5);\n\tSegment otherSegment(closestPoint + plainNormal, closestPoint - plainNormal);\n\n\tdistance = distanceSegmentSegment(plainSegment.a, plainSegment.b, otherSegment.a, otherSegment.b, &p0, &p1);\n\tEXPECT_NEAR(0.0, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(closestPoint, p0));\n\tEXPECT_TRUE(eigenEqual(closestPoint, p1));\n\n\t// Explode the cases\n\tstd::vector<SegmentData> segments;\n\n\t// The following series test the segment to segment distance for\n\t// a) coplanar segments\n\t// b) non coplanar segments\n\t// for each of the groups multiple pairs of segments are testes in various configurations, where the\n\t// projections either intersect or don't, this should cover all the segments that are used in the\n\t// algorithm, inside testSegmentDistance the segments are also swapped around and tested against each other\n\n\t// <0> Intersecting outside past b with segment straddling the line\n\tclosestPoint = plainSegment.pointOnLine(1.5);\n\totherSegment = Segment(closestPoint + plainNormal, closestPoint - plainNormal);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.b, closestPoint));\n\n\t// <1> segment not straddling, the correct points on the edges of the segments should get picked\n\totherSegment = Segment(closestPoint + plainNormal, closestPoint + plainNormal * 2);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.b, otherSegment.a));\n\n\t// <2> segment not straddling, reverse the order of the points, reverse the side where the other segments falls\n\totherSegment = Segment(closestPoint - plainNormal * 2, closestPoint - plainNormal);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.b, otherSegment.b));\n\n\t// Go to the other side of the segment\n\tclosestPoint = plainSegment.pointOnLine(-0.5);\n\t// <3> Straddling, there is actual an intersection\n\totherSegment = Segment(closestPoint + plainNormal, closestPoint - plainNormal);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.a, closestPoint));\n\n\t// <4> segment not straddling, the correct points on the edges of the segments should get picked\n\totherSegment = Segment(closestPoint + plainNormal, closestPoint + plainNormal * 2);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.a, otherSegment.a));\n\n\n\t// <5> segment not straddling, reverse the order of the points, reverse the side where the other segments falls\n\totherSegment = Segment(closestPoint - plainNormal * 2, closestPoint - plainNormal);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.a, otherSegment.b));\n\n\n\t// Repeat the same sequence for the segments as they are not touching\n\tVectorType otherNormal = plainSegment.ab.cross(plainNormal);\n\n\t// <6> segment projections intersect\n\tclosestPoint = plainSegment.pointOnLine(0.5) + plainNormal * 3;\n\totherSegment = Segment(closestPoint + otherNormal, closestPoint - otherNormal);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.pointOnLine(0.5), closestPoint));\n\n\t// <7> go past the end of the segment but straddle the line (T intersection)\n\tclosestPoint = plainSegment.pointOnLine(1.5) + plainNormal * 3;\n\totherSegment = Segment(closestPoint + otherNormal, closestPoint - otherNormal);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.b, closestPoint));\n\n\t// <8> go past the end of the segment not straddling the line anymore\n\totherSegment = Segment(closestPoint + otherNormal, closestPoint + otherNormal * 2);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.b, otherSegment.a));\n\n\t// <9> go past the end of the on the other side, switching up endpoints\n\totherSegment = Segment(closestPoint - otherNormal * 2, closestPoint - otherNormal);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.b, otherSegment.b));\n\n\t// Repeat for the other end of the base segment\n\t// <10> go past the end of the segment but straddle the line (T intersection)\n\tclosestPoint = plainSegment.pointOnLine(-2.0) + plainNormal * 3;\n\totherSegment = Segment(closestPoint + otherNormal, closestPoint - otherNormal);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.a, closestPoint));\n\n\t// <11> go past the end of the segment not straddling the line anymore\n\totherSegment = Segment(closestPoint + otherNormal, closestPoint + otherNormal * 2);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.a, otherSegment.a));\n\n\t// <12> go past the end of the on the other side, switching up endpoints\n\totherSegment = Segment(closestPoint - otherNormal * 2, closestPoint - otherNormal);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.a, otherSegment.b));\n\n\t// <13> projections intersect, short segments\n\tconst VectorType aPoint = VectorType(1, 0, 0);\n\tconst SizeType shortLength = 0.0001;\n\tconst Segment shortSegment = Segment(VectorType(0, -shortLength / 2, 0), VectorType(0, shortLength / 2, 0));\n\tconst VectorType shortSegmentNormal = shortSegment.ab.cross(aPoint).normalized();\n\tconst Segment otherShortSegment = Segment(aPoint, aPoint + shortLength * shortSegmentNormal);\n\tsegments.push_back(SegmentData(shortSegment, otherShortSegment,\n\t\t\t\t\t\t\t\t   shortSegment.pointOnLine(0.5), otherShortSegment.a));\n\n\tfor (size_t i = 0; i < segments.size(); ++i)\n\t{\n\t\ttestSegmentDistance(segments[i], \"basic cases\", i);\n\t}\n\n\t// Parallel Segments\n\totherSegment = Segment(plainSegment.a + plainNormal * 4, plainSegment.b + plainNormal * 4);\n\tdistance = distanceSegmentSegment(plainSegment.a, plainSegment.b, otherSegment.a, otherSegment.b, &p0, &p1);\n\tEXPECT_NEAR(4.0, distance, epsilon);\n\t// What should the points be here ?\n\n\tsegments.clear();\n\n\t// <0> parallel, non-overlapping\n\tclosestPoint = plainSegment.a;\n\tconst Vector3d segmentDirection = plainSegment.a - plainSegment.b;\n\totherSegment = Segment(closestPoint + plainNormal * 4 + 2 * segmentDirection,\n\t\t\t\t\t\t   closestPoint + plainNormal * 4 + 4 * segmentDirection);\n\tdistance = distanceSegmentSegment(plainSegment.a, plainSegment.b, otherSegment.a, otherSegment.b, &p0, &p1);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, closestPoint, otherSegment.a));\n\n\t// Anti-parallel Segments\n\totherSegment = Segment(plainSegment.b + plainNormal * 4, plainSegment.a + plainNormal * 4);\n\tdistance = distanceSegmentSegment(plainSegment.a, plainSegment.b, otherSegment.a, otherSegment.b, &p0, &p1);\n\tEXPECT_NEAR(4.0, distance, epsilon);\n\n\t// <1> anti-parallel, non-overlapping\n\tclosestPoint = plainSegment.a;\n\totherSegment = Segment(closestPoint + plainNormal * 4 + 4 * segmentDirection,\n\t\t\t\t\t\t   closestPoint + plainNormal * 4 + 2 * segmentDirection);\n\tdistance = distanceSegmentSegment(plainSegment.a, plainSegment.b, otherSegment.a, otherSegment.b, &p0, &p1);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, closestPoint, otherSegment.b));\n\n\tfor (size_t i = 0; i < segments.size(); ++i)\n\t{\n\t\ttestSegmentDistance(segments[i], \"parallel cases\", i);\n\t}\n\n\tsegments.clear();\n\n\t// The closest points are some assumptions, it looks like the algorithm is slanted towards\n\t// <0> the beginning points of the segments for this\n\tclosestPoint = plainSegment.pointOnLine(0.5);\n\totherSegment = Segment(closestPoint + plainNormal * 4, closestPoint + plainNormal * 8);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.pointOnLine(0.5), otherSegment.a));\n\n\t// <1> Move past the end of the segment on the far end\n\tclosestPoint = plainSegment.pointOnLine(1.5);\n\totherSegment = Segment(closestPoint + plainNormal * 4, closestPoint + plainNormal * 8);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.b, otherSegment.a));\n\n\t// <2> Move past the end of the segment on the near end\n\tclosestPoint = plainSegment.pointOnLine(-2.0);\n\totherSegment = Segment(closestPoint - plainNormal * 8, closestPoint - plainNormal * 4);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.a, otherSegment.b));\n\n\n\t// Degenerate cases delegate to PointSegDistance, just some spotChecks\n\t// <3> On the segment\n\tclosestPoint = plainSegment.pointOnLine(0.5);\n\totherSegment = Segment(closestPoint, closestPoint);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, closestPoint, closestPoint));\n\n\t// <4> off the segment\n\tclosestPoint = plainSegment.pointOnLine(1.5) + plainNormal * 4 + otherNormal * 10;\n\totherSegment = Segment(closestPoint, closestPoint);\n\tsegments.push_back(SegmentData(plainSegment, otherSegment, plainSegment.b, closestPoint));\n\n\n\tfor (size_t i = 0; i < segments.size(); ++i)\n\t{\n\t\ttestSegmentDistance(segments[i], \"other cases\", i);\n\t}\n}\n\nTEST_F(GeometryTest, DistancePointTriangle)\n{\n\tdouble distance;\n\tVectorType closestPoint;\n\tVectorType result;\n\tVectorType inputPoint;\n\n\t// Trivial, point on triangle\n\tinputPoint = VectorType(0, 0, 0);\n\tdistance = distancePointTriangle(inputPoint, tri.v0, tri.v1, tri.v2, &result);\n\tEXPECT_NEAR(0.0, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(inputPoint, result));\n\n\tdistance = distancePointTriangle(tri.v1, tri.v0, tri.v1, tri.v2, &result);\n\tEXPECT_NEAR(0.0, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(tri.v1, result));\n\n\t// Closest Point is inside Triangle\n\tclosestPoint = tri.v0 + tri.v0v1 * 0.3 + tri.v0v2 * 0.7;\n\tinputPoint = closestPoint + tri.n * 2.5;\n\tdistance = distancePointTriangle(inputPoint, tri.v0, tri.v1, tri.v2, &result);\n\tEXPECT_NEAR(2.5, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(closestPoint, result));\n\n\t// other side\n\tinputPoint = closestPoint - tri.n * 3.5;\n\tdistance = distancePointTriangle(inputPoint, tri.v0, tri.v1, tri.v2, &result);\n\tEXPECT_NEAR(3.5, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(closestPoint, result));\n\n\t// Test the Point close to a triangle Edge cases\n\t// Point closest to edge v0v1\n\tdouble expectedDistance;\n\tinputPoint = tri.v0 +  tri.v0v1 * 0.5 - tri.v0v2 + tri.n;\n\tdistance = distancePointTriangle(inputPoint, tri.v0, tri.v1, tri.v2, &result);\n\texpectedDistance = distancePointSegment(inputPoint, tri.v0, tri.v1, &closestPoint);\n\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(closestPoint, result));\n\n\t// Point closest to edge v0v2\n\tinputPoint = tri.v0 + tri.v0v2 * 0.3 - tri.v0v1 + tri.n * 2;\n\tdistance = distancePointTriangle(inputPoint, tri.v0, tri.v1, tri.v2, &result);\n\texpectedDistance = distancePointSegment(inputPoint, tri.v0, tri.v2, &closestPoint);\n\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(closestPoint, result));\n\n\t// Point closest to edge v1v2\n\tinputPoint = tri.v1 + (tri.v2 - tri.v1) * .75 + tri.v0v1 * 0.2 + tri.n;\n\tdistance = distancePointTriangle(inputPoint, tri.v0, tri.v1, tri.v2, &result);\n\texpectedDistance = distancePointSegment(inputPoint, tri.v1, tri.v2, &closestPoint);\n\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(closestPoint, result));\n\n\t// Point closest to point v0\n\tinputPoint = tri.v0 - tri.v0v1 - tri.v0v2 * 0.5 - tri.n;\n\tdistance = distancePointTriangle(inputPoint, tri.v0, tri.v1, tri.v2, &result);\n\texpectedDistance = (tri.v0 - inputPoint).norm();\n\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(tri.v0, result));\n\n\t// Point closest to point v1\n\tinputPoint = tri.v1 + tri.v0v1 + (tri.v1 - tri.v2) * 2.0 - tri.n * 2.0;\n\tdistance = distancePointTriangle(inputPoint, tri.v0, tri.v1, tri.v2, &result);\n\texpectedDistance = (tri.v1 - inputPoint).norm();\n\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(tri.v1, result));\n\n\t// Point closest to point v2\n\tinputPoint = tri.v2 + tri.v0v2 + (tri.v2 - tri.v1) * 3.0 - tri.n * 1.5;\n\tdistance = distancePointTriangle(inputPoint, tri.v0, tri.v1, tri.v2, &result);\n\texpectedDistance = (tri.v2 - inputPoint).norm();\n\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(tri.v2, result));\n\n\t// Degenerate Edges\n\t// Edge v0v1\n\tdistance = distancePointTriangle(inputPoint,\n\t\t\t\t\t\t\t\t\t tri.v0, (tri.v0 + tri.v0v1 * epsilon * 0.01).eval(), tri.v2,\n\t\t\t\t\t\t\t\t\t &result);\n\texpectedDistance = distancePointSegment(inputPoint, tri.v0, tri.v2, &closestPoint);\n\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(closestPoint, result));\n\n\t// Edge v0v2\n\tdistance = distancePointTriangle(inputPoint,\n\t\t\t\t\t\t\t\t\t (tri.v2 - tri.v0v2 * epsilon * 0.01).eval(), tri.v1, tri.v2,\n\t\t\t\t\t\t\t\t\t &result);\n\texpectedDistance = distancePointSegment(inputPoint, tri.v1, tri.v2, &closestPoint);\n\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(closestPoint, result));\n\n\t// Edge v1v2\n\tdistance = distancePointTriangle(inputPoint, tri.v0, tri.v1, tri.v1, &result);\n\texpectedDistance = distancePointSegment(inputPoint, tri.v1, tri.v0, &closestPoint);\n\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\tEXPECT_TRUE(eigenEqual(closestPoint, result));\n}\n\nTEST_F(GeometryTest, PointInsideTriangleWithNormal)\n{\n\tEXPECT_TRUE(isPointInsideTriangle(tri.v0, tri.v0, tri.v1, tri.v2, tri.n));\n\tEXPECT_TRUE(isPointInsideTriangle(tri.v1, tri.v0, tri.v1, tri.v2, tri.n));\n\tEXPECT_TRUE(isPointInsideTriangle(tri.v2, tri.v0, tri.v1, tri.v2, tri.n));\n\n\tVectorType inputPoint = tri.v0 + tri.v0v1 * 0.2;\n\tEXPECT_TRUE(isPointInsideTriangle(inputPoint, tri.v0, tri.v1, tri.v2, tri.n));\n\tinputPoint += tri.v0v2 * 0.5;\n\tEXPECT_TRUE(isPointInsideTriangle(inputPoint, tri.v0, tri.v1, tri.v2, tri.n));\n\n\tinputPoint = tri.v0 + tri.v0v1 * 1.5;\n\tEXPECT_FALSE(isPointInsideTriangle(inputPoint, tri.v0, tri.v1, tri.v2, tri.n));\n\tEXPECT_FALSE(isPointInsideTriangle(inputPoint, tri.v1, tri.v1, tri.v2, tri.n));\n\n\tinputPoint = tri.v0 + tri.v0v2 * 2 + tri.v0v1 * 2;\n\tEXPECT_FALSE(isPointInsideTriangle(inputPoint, tri.v0, tri.v1, tri.v2, tri.n));\n\n}\n\nTEST_F(GeometryTest, PointInsideTriangleWithoutNormal)\n{\n\tEXPECT_TRUE(isPointInsideTriangle(tri.v0, tri.v0, tri.v1, tri.v2));\n\tEXPECT_TRUE(isPointInsideTriangle(tri.v1, tri.v0, tri.v1, tri.v2));\n\tEXPECT_TRUE(isPointInsideTriangle(tri.v2, tri.v0, tri.v1, tri.v2));\n\n\tVectorType inputPoint = tri.v0 + tri.v0v1 * 0.2;\n\tEXPECT_TRUE(isPointInsideTriangle(inputPoint, tri.v0, tri.v1, tri.v2));\n\tinputPoint += tri.v0v2 * 0.5;\n\tEXPECT_TRUE(isPointInsideTriangle(inputPoint, tri.v0, tri.v1, tri.v2));\n\n\tinputPoint = tri.v0 + tri.v0v1 * 1.5;\n\tEXPECT_FALSE(isPointInsideTriangle(inputPoint, tri.v0, tri.v1, tri.v2));\n\tEXPECT_FALSE(isPointInsideTriangle(inputPoint, tri.v1, tri.v1, tri.v2));\n\n\tinputPoint = tri.v0 + tri.v0v2 * 2 + tri.v0v1 * 2;\n\tEXPECT_FALSE(isPointInsideTriangle(inputPoint, tri.v0, tri.v1, tri.v2));\n}\n\nTEST_F(GeometryTest, PointOnTriangleEdgeWithoutNormal)\n{\n\tEXPECT_TRUE(isPointOnTriangleEdge(tri.v0, tri.v0, tri.v1, tri.v2));\n\tEXPECT_TRUE(isPointOnTriangleEdge(tri.v1, tri.v0, tri.v1, tri.v2));\n\tEXPECT_TRUE(isPointOnTriangleEdge(tri.v2, tri.v0, tri.v1, tri.v2));\n\n\tVectorType inputPoint = tri.v0 + tri.v0v1 * 0.2;\n\tEXPECT_TRUE(isPointOnTriangleEdge(inputPoint, tri.v0, tri.v1, tri.v2));\n\tinputPoint = tri.v0 + tri.v0v2 * 0.2;\n\tEXPECT_TRUE(isPointOnTriangleEdge(inputPoint, tri.v0, tri.v1, tri.v2));\n\tinputPoint = tri.v1 + tri.v1v2 * 0.2;\n\tEXPECT_TRUE(isPointOnTriangleEdge(inputPoint, tri.v0, tri.v1, tri.v2));\n\n\tinputPoint = tri.v0 + tri.v0v1 * 1.5;\n\tEXPECT_FALSE(isPointOnTriangleEdge(inputPoint, tri.v0, tri.v1, tri.v2));\n\tEXPECT_FALSE(isPointOnTriangleEdge(inputPoint, tri.v1, tri.v1, tri.v2));\n\n\tinputPoint = tri.v0 + tri.v0v2 * 2 + tri.v0v1 * 2;\n\tEXPECT_FALSE(isPointOnTriangleEdge(inputPoint, tri.v0, tri.v1, tri.v2));\n}\n\nTEST_F(GeometryTest, Coplanarity)\n{\n\tstruct CoplanarityTestCandidate\n\t{\n\t\tbool expected;\n\t\tstd::array<Vector3d, 4> points;\n\t};\n\n\tCoplanarityTestCandidate candidates[] =\n\t{\n\t\t{true, Vector3d(0.0, 0.0, 0.0), Vector3d(0.0, 0.0, 0.0), Vector3d(0.0, 0.0, 0.0), Vector3d(0.0, 0.0, 0.0)},\n\t\t{true, Vector3d(0.0, 0.0, 0.0), Vector3d(0.0, 0.0, 0.0), Vector3d(0.0, 0.0, 0.0), Vector3d(3.7, 0.0, 0.0)},\n\t\t{true, Vector3d(0.0, 0.0, 0.0), Vector3d(0.0, 0.0, 0.0), Vector3d(2.3, 0.0, 0.0), Vector3d(3.7, 0.0, 0.0)},\n\t\t{true, Vector3d(0.0, 0.0, 0.0), Vector3d(1.1, 0.0, 0.0), Vector3d(2.3, 0.0, 0.0), Vector3d(3.7, 0.0, 0.0)},\n\t\t{true, Vector3d(0.0, 0.0, 0.0), Vector3d(1.1, 1.5, 0.0), Vector3d(2.3, 0.0, 0.0), Vector3d(3.7, 0.0, 0.0)},\n\t\t{true, Vector3d(0.0, 0.0, 0.0), Vector3d(1.1, 1.5, 0.0), Vector3d(2.3, 0.0, 0.0), Vector3d(3.7, 3.0, 0.0)},\n\t\t{false, Vector3d(0.0, 0.0, 1.0), Vector3d(1.1, 1.5, 0.0), Vector3d(2.3, 0.0, 0.0), Vector3d(3.7, 3.0, 0.0)},\n\t\t{false, Vector3d(0.0, 0.0, 0.0), Vector3d(1.1, 1.5, 1.1), Vector3d(2.3, 0.0, 0.0), Vector3d(3.7, 3.0, 0.0)},\n\t\t{false, Vector3d(0.0, 0.0, 0.0), Vector3d(1.1, 1.5, 0.0), Vector3d(2.3, 0.0, 7.7), Vector3d(3.7, 3.0, 0.0)},\n\t\t{false, Vector3d(0.0, 0.0, 0.0), Vector3d(1.1, 1.5, 0.0), Vector3d(2.3, 0.0, 0.0), Vector3d(3.7, 3.0, -9.6)},\n\n\t\t{true, Vector3d(0.0, 0.0, 0.0), Vector3d(1.0, 0.0, 0.0), Vector3d(0.0, 1.0, 0.0), Vector3d(12.3, -41.3, 0.0)},\n\t\t{false, Vector3d(0.0, 0.0, 0.0), Vector3d(1.0, 0.0, 0.0), Vector3d(0.0, 1.0, 0.0), Vector3d(12.3, -41.3, 4.0)},\n\n\t\t{\n\t\t\tfalse, Vector3d(10932.645, 43.1987, -0.009874245),\n\t\t\tVector3d(53432.4, -9.87243, 654.31),\n\t\t\tVector3d(28.71, 0.005483927, 2.34515),\n\t\t\tVector3d(5897.1, -5.432, 512152.7654)\n\t\t}\n\t};\n\n\tfor (auto candidate = std::begin(candidates); candidate != std::end(candidates); ++candidate)\n\t{\n\t\tEXPECT_EQ(candidate->expected, isCoplanar(candidate->points[0],\n\t\t\t\t  candidate->points[1],\n\t\t\t\t  candidate->points[2],\n\t\t\t\t  candidate->points[3]))\n\t\t\t\t<< \"Candidate points were [\" << candidate->points[0].transpose() << \"], [\"\n\t\t\t\t<< candidate->points[1].transpose() << \"], [\"\n\t\t\t\t<< candidate->points[2].transpose() << \"], [\"\n\t\t\t\t<< candidate->points[3].transpose() << \"]\";\n\t}\n}\n\ntypedef std::tuple<Segment, MockTriangle, VectorType, bool> SegTriIntersectionData;\n::testing::AssertionResult checkSegTriIntersection(const SegTriIntersectionData& data)\n{\n\tstd::stringstream errorMessage;\n\tSegment segment = std::get<0>(data);\n\tMockTriangle tri = std::get<1>(data);\n\tVectorType expectedClosestPoint = std::get<2>(data);\n\tbool expectedResult = std::get<3>(data);\n\tVectorType closestPoint;\n\n\tbool result = doesCollideSegmentTriangle(segment.a, segment.b, tri.v0, tri.v1, tri.v2, tri.n, &closestPoint);\n\tif (result != expectedResult)\n\t{\n\t\terrorMessage << \"Intersection result does not match should be: \" << expectedResult << \" but got \" <<\n\t\t\t\t\t result << std::endl;\n\t};\n\tif (expectedResult)\n\t{\n\t\tif (! expectedClosestPoint.isApprox(closestPoint))\n\t\t{\n\t\t\terrorMessage << \"Closest Point was expected to be \" << expectedClosestPoint << \" but is \" <<\n\t\t\t\t\t\t closestPoint << std::endl;\n\t\t}\n\t}\n\telse\n\t{\n\t\terrorMessage << eigenAllNan(closestPoint).message();\n\t}\n\n\tif (errorMessage.str() == \"\")\n\t{\n\t\treturn ::testing::AssertionSuccess();\n\t}\n\telse\n\t{\n\t\treturn ::testing::AssertionFailure() << errorMessage.str();\n\t}\n}\n\nTEST_F(GeometryTest, SegmentTriangleIntersection)\n{\n\tVectorType closestPoint;\n\tVectorType intersectionPoint = tri.pointInTriangle(0.2, 0.7);\n\tSegment intersecting(intersectionPoint - tri.n * 2, intersectionPoint + tri.n * 2);\n\n\tSegTriIntersectionData data;\n\n\tdata = SegTriIntersectionData(intersecting, tri, intersectionPoint, true);\n\tEXPECT_TRUE(checkSegTriIntersection(data));\n\n\tintersecting.a = intersectionPoint + tri.n * 4;\n\tdata = SegTriIntersectionData(intersecting, tri, intersectionPoint, false);\n\tEXPECT_TRUE(checkSegTriIntersection(data));\n\n\t// in the plane of the triangle\n\tintersecting = Segment(intersectionPoint, intersectionPoint + tri.v0v1 + tri.v1v2);\n\tdata = SegTriIntersectionData(intersecting, tri, intersectionPoint, true);\n\tEXPECT_TRUE(checkSegTriIntersection(data));\n\n\tintersecting = Segment(intersectionPoint + tri.v0v1 + tri.v1v2, intersectionPoint);\n\tdata = SegTriIntersectionData(intersecting, tri, intersectionPoint, true);\n\tEXPECT_TRUE(checkSegTriIntersection(data));\n\n\tintersecting = Segment(intersectionPoint + tri.v0v1 + tri.v1v2, intersectionPoint + 2 * tri.v0v1 + tri.v1v2);\n\tdata = SegTriIntersectionData(intersecting, tri, intersectionPoint, false);\n\tEXPECT_TRUE(checkSegTriIntersection(data));\n\n\t// Slanting but intersecting\n\t// Point On triangle\n\tintersecting = Segment(intersectionPoint, intersectionPoint + tri.n * 2 + tri.v0v1 * 2);\n\tdata = SegTriIntersectionData(intersecting, tri, intersectionPoint, true);\n\tEXPECT_TRUE(checkSegTriIntersection(data));\n\n\t// Intersection in Triangle\n\tintersecting = Segment(intersectionPoint - tri.n * 2 - tri.v1v2 * 2, intersectionPoint + 2 * tri.n + tri.v1v2 * 2);\n\tdata = SegTriIntersectionData(intersecting, tri, intersectionPoint, true);\n\tEXPECT_TRUE(checkSegTriIntersection(data));\n\n\t// Intersection not on Segment\n\tintersecting = Segment(intersectionPoint + tri.n * 4 + tri.v1v2 * 4, intersectionPoint + 2 * tri.n + tri.v1v2 * 2);\n\tdata = SegTriIntersectionData(intersecting, tri, intersectionPoint, false);\n\tEXPECT_TRUE(checkSegTriIntersection(data));\n\n\t// Normal segment through one edge\n\tVectorType pointOnEdge = tri.v0 + tri.v0v1 * 0.5;\n\tintersecting = Segment(pointOnEdge + tri.n, pointOnEdge - tri.n);\n\tdata = SegTriIntersectionData(intersecting, tri, pointOnEdge, true);\n\tEXPECT_TRUE(checkSegTriIntersection(data));\n\n\tintersecting = Segment(pointOnEdge + tri.n, pointOnEdge);\n\tdata = SegTriIntersectionData(intersecting, tri, pointOnEdge, true);\n\tEXPECT_TRUE(checkSegTriIntersection(data));\n\n\tintersecting = Segment(pointOnEdge + tri.n * 3, pointOnEdge + tri.n * 4);\n\tdata = SegTriIntersectionData(intersecting, tri, pointOnEdge, false);\n\tEXPECT_TRUE(checkSegTriIntersection(data));\n\n\tintersecting = Segment(pointOnEdge + tri.n + tri.v0v1 * 0.5, pointOnEdge);\n\tdata = SegTriIntersectionData(intersecting, tri, pointOnEdge, true);\n\tEXPECT_TRUE(checkSegTriIntersection(data));\n\n\t// Segment away from the triangle\n\tintersecting = Segment(tri.v0 - tri.v0v1 - tri.v1v2, tri.v0 - tri.n * 3.0 - tri.v0v1 - tri.v1v2);\n\tdata = SegTriIntersectionData(intersecting, tri, pointOnEdge, false);\n\tEXPECT_TRUE(checkSegTriIntersection(data));\n}\n\nTEST_F(GeometryTest, distancePointPlane)\n{\n\tMockTriangle triangle(VectorType(3, 4, 5), VectorType(5, 5, 5), VectorType(10, 5, 2));\n\tVectorType pointInTriangle = triangle.v0 + triangle.v0v1 * 0.4;\n\tdouble d = -triangle.n.dot(triangle.v0);\n\tVectorType point = pointInTriangle;\n\tVectorType projectionPoint;\n\tdouble distance = distancePointPlane(point, triangle.n, d, &projectionPoint);\n\tEXPECT_NEAR(0.0, distance, epsilon);\n\tEXPECT_TRUE(pointInTriangle.isApprox(projectionPoint));\n\n\tpoint = pointInTriangle + triangle.n * 2;\n\tdistance = distancePointPlane(point, triangle.n, d, &projectionPoint);\n\tEXPECT_NEAR(2.0, distance, epsilon);\n\tEXPECT_TRUE(pointInTriangle.isApprox(projectionPoint));\n\n\tpoint = pointInTriangle - triangle.n * 3;\n\tdistance = distancePointPlane(point, triangle.n, d, &projectionPoint);\n\tEXPECT_NEAR(-3.0, distance, epsilon);\n\tEXPECT_TRUE(pointInTriangle.isApprox(projectionPoint));\n}\n\ntypedef std::tuple<Segment, VectorType, double, VectorType, VectorType, int> SegmentPlaneData;\nvoid checkSegmentPlanDistance(const SegmentPlaneData& data)\n{\n\tSegment seg = std::get<0>(data);\n\tVectorType n = std::get<1>(data);\n\tdouble d = std::get<2>(data);\n\tVectorType expectedSegmentPoint = std::get<3>(data);\n\tVectorType expectedPlanePoint = std::get<4>(data);\n\t// The sign of the expected distance [1|-1|0], you must use 0 for expected 0\n\tint sign = std::get<5>(data);\n\tdouble distance;\n\tVectorType segResultPoint, planeResultPoint;\n\tdistance = distanceSegmentPlane(seg. a, seg.b, n, d, &segResultPoint, &planeResultPoint);\n\tEXPECT_NEAR((planeResultPoint - segResultPoint).norm(), std::abs(distance), epsilon);\n\tEXPECT_TRUE(distance * sign > 0 || distance == static_cast<double>(sign));\n\tEXPECT_TRUE(expectedSegmentPoint.isApprox(segResultPoint));\n\tEXPECT_TRUE(expectedPlanePoint.isApprox(planeResultPoint));\n}\n\nTEST_F(GeometryTest, SegmentPlaneDistance)\n{\n\tMockTriangle triangle(VectorType(3, 4, 5), VectorType(5, 5, 5), VectorType(10, 5, 2));\n\tdouble d = -triangle.n.dot(triangle.v0);\n\tVectorType intersectionPoint = triangle.pointInTriangle(0.2, 0.7);\n\tSegment seg(intersectionPoint - triangle.n * 2, intersectionPoint + triangle.n * 2);\n\n\tVectorType segResultPoint, planeResultPoint;\n\n\t{\n\t\tSCOPED_TRACE(\"Segment intersects Plane\");\n\t\tcheckSegmentPlanDistance(SegmentPlaneData(seg, triangle.n, d, intersectionPoint, intersectionPoint, 0));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Segment above plane, segment intersection should be point a\");\n\t\tseg = Segment(intersectionPoint + triangle.n * 2, intersectionPoint + triangle.n * 3);\n\t\tdistanceSegmentPlane(seg.a, seg.b, triangle.n, d, &segResultPoint, &planeResultPoint);\n\t\tcheckSegmentPlanDistance(SegmentPlaneData(seg, triangle.n, d, seg.a, intersectionPoint, 1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Segment below plane, segment intersection should be point a\");\n\t\tseg = Segment(intersectionPoint - triangle.n * 3, intersectionPoint - triangle.n * 2);\n\t\tdistanceSegmentPlane(seg.a, seg.b, triangle.n, d, &segResultPoint, &planeResultPoint);\n\t\tcheckSegmentPlanDistance(SegmentPlaneData(seg, triangle.n, d, seg.b, intersectionPoint, -1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Segment below plane, segment intersection should be point a, reverse case from above\");\n\t\tseg = Segment(intersectionPoint - triangle.n * 2, intersectionPoint - triangle.n * 3);\n\t\tcheckSegmentPlanDistance(SegmentPlaneData(seg, triangle.n, d, seg.a, intersectionPoint, -1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Segment coplanar with plane\");\n\t\tseg = Segment(intersectionPoint - triangle.v0v1, intersectionPoint + triangle.v0v1);\n\t\tcheckSegmentPlanDistance(SegmentPlaneData(seg, triangle.n, d, intersectionPoint, intersectionPoint, 0));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Segment parallel with plane\");\n\t\tseg = Segment(intersectionPoint - triangle.v0v1 + triangle.n * 2.0,\n\t\t\t\t\t  intersectionPoint + triangle.v0v1 + triangle.n * 2.0);\n\t\tcheckSegmentPlanDistance(SegmentPlaneData(seg, triangle.n, d, seg.pointOnLine(0.5), intersectionPoint, 1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Segment parallel with plane but on the other side\");\n\t\tseg = Segment(intersectionPoint - triangle.v0v1 - triangle.n * 2.0,\n\t\t\t\t\t  intersectionPoint + triangle.v0v1 - triangle.n * 2.0);\n\t\tcheckSegmentPlanDistance(SegmentPlaneData(seg, triangle.n, d, seg.pointOnLine(0.5), intersectionPoint, -1));\n\t}\n}\n\ntemplate <class T>\nclass GeometryVectorTestBase : public testing::Test\n{\npublic:\n\ttypedef T Scalar;\n};\n\ntemplate <class T>\nclass GeometryVector3Tests : public GeometryVectorTestBase<typename T::Scalar>\n{\npublic:\n\ttypedef T Vector3;\n};\n\ntypedef ::testing::Types<SurgSim::Math::Vector3d,\n\t\tSurgSim::Math::Vector3f> GeometryVector3Variants;\nTYPED_TEST_CASE(GeometryVector3Tests, GeometryVector3Variants);\n\nTYPED_TEST(GeometryVector3Tests, nearestPointOnLine)\n{\n\ttypedef typename TestFixture::Vector3 Vector3;\n\ttypedef typename Vector3::Scalar T;\n\tconst int VOpt = Vector3::Options;\n\n\tVector3 point(static_cast<T>(2.0), static_cast<T>(-4.0), static_cast<T>(3.0));\n\tVector3 segmentEnd1(static_cast<T>(-2.0), static_cast<T>(2.0), static_cast<T>(4.0));\n\tVector3 segmentEnd2(static_cast<T>(-1.0), static_cast<T>(1.0), static_cast<T>(2.0));\n\tT precision = Eigen::NumTraits<T>::dummy_precision();\n\n\t// Assert if segment is degenerate\n\tASSERT_ANY_THROW((SurgSim::Math::nearestPointOnLine<T, VOpt>(point, segmentEnd1, segmentEnd1)));\n\n\t// Otherwise, calculate the correct value\n\tASSERT_NO_THROW((SurgSim::Math::nearestPointOnLine<T, VOpt>(point, segmentEnd1, segmentEnd2)));\n\n\tauto result = SurgSim::Math::nearestPointOnLine<T, VOpt>(point, segmentEnd1, segmentEnd2);\n\tEXPECT_GT(precision, (std::abs((segmentEnd2 - segmentEnd1).dot(result - point))));\n}\n\ntypedef std::tuple<MockTriangle, VectorType, double, VectorType, VectorType, int> TriPlaneData;\nvoid checkTriPlaneDistance(const TriPlaneData& data)\n{\n\tMockTriangle tri = std::get<0>(data);\n\tVectorType n = std::get<1>(data);\n\tdouble d = std::get<2>(data);\n\tVectorType expectedTrianglePoint = std::get<3>(data);\n\tVectorType expectedPlanePoint = std::get<4>(data);\n\tint sign = std::get<5>(data);\n\tVectorType triangleResultPoint, planeResultPoint;\n\tdouble distance;\n\n\tdistance = distanceTrianglePlane(tri.v0, tri.v1, tri.v2, n, d, &triangleResultPoint, &planeResultPoint);\n\tEXPECT_NEAR((planeResultPoint - triangleResultPoint).norm(), std::abs(distance), epsilon);\n\tEXPECT_TRUE((sign == 0 && std::abs(distance) <= epsilon) || (distance * sign > 0));\n\tEXPECT_TRUE(expectedTrianglePoint.isApprox(triangleResultPoint));\n\tEXPECT_TRUE(expectedPlanePoint.isApprox(planeResultPoint));\n}\n\nTEST_F(GeometryTest, TrianglePlaneTest)\n{\n\tMockTriangle triangle(VectorType(3, 4, 5), VectorType(5, 5, 5), VectorType(10, 5, 2));\n\t// Start with the coplanar case\n\tdouble d = -triangle.n.dot(triangle.v0);\n\tdouble distance;\n\tVectorType intersectionPoint0;\n\tVectorType intersectionPoint1;\n\n\t// Coplanar\n\tVectorType third = (triangle.v0 + triangle.v1 + triangle.v2) / 3.0;\n\tdistance = distanceTrianglePlane(triangle.v0, triangle.v1, triangle.v2, triangle.n, d,\n\t\t\t\t\t\t\t\t\t &intersectionPoint0, &intersectionPoint1);\n\tEXPECT_NEAR(0.0, distance, epsilon);\n\tEXPECT_TRUE(third.isApprox(intersectionPoint0));\n\tEXPECT_TRUE(third.isApprox(intersectionPoint1));\n\n\tVectorType pointOnPlane = (triangle.v0 + triangle.v1 + triangle.v2) / 3.0;\n\n\t{\n\t\tSCOPED_TRACE(\"Coplanar Case\");\n\t\tMockTriangle target(triangle.v0, triangle.v1, triangle.v2);\n\t\tcheckTriPlaneDistance(TriPlaneData(target, triangle.n, d, pointOnPlane, pointOnPlane, 0));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Parallel, below the plane\");\n\t\tMockTriangle target(triangle.v0 - triangle.n * 3, triangle.v1 - triangle.n * 3, triangle.v2 - triangle.n * 3);\n\t\tcheckTriPlaneDistance(TriPlaneData(target, triangle.n, d, pointOnPlane - triangle.n * 3, pointOnPlane, -1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Parallel, above the plane\");\n\t\tMockTriangle target(triangle.v0 + triangle.n, triangle.v1 + triangle.n, triangle.v2 + triangle.n);\n\t\tcheckTriPlaneDistance(TriPlaneData(target, triangle.n, d, pointOnPlane + triangle.n, pointOnPlane, 1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Not Intersecting, triangle.v0 is closest above the plane\");\n\t\tMockTriangle target(triangle.v0 + triangle.n * 2, triangle.v1 + triangle.n * 3, triangle.v2 + triangle.n * 3);\n\t\tcheckTriPlaneDistance(TriPlaneData(target, triangle.n, d, target.v0, triangle.v0, 1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Not Intersecting, triangle.v1 is closest above the plane\");\n\t\tMockTriangle target(triangle.v0 + triangle.n * 3, triangle.v1 + triangle.n * 2, triangle.v2 + triangle.n * 3);\n\t\tcheckTriPlaneDistance(TriPlaneData(target, triangle.n, d, target.v1, triangle.v1, 1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Not Intersecting, triangle.v2 is closest above the plane\");\n\t\tMockTriangle target(triangle.v0 + triangle.n * 4, triangle.v1 + triangle.n * 3, triangle.v2 + triangle.n * 2);\n\t\tcheckTriPlaneDistance(TriPlaneData(target, triangle.n, d, target.v2, triangle.v2, 1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Not Intersecting, triangle.v0 is closest below the plane\");\n\t\tMockTriangle target(triangle.v0 - triangle.n * 2, triangle.v1 - triangle.n * 3, triangle.v2 - triangle.n * 3);\n\t\tcheckTriPlaneDistance(TriPlaneData(target, triangle.n, d, target.v0, triangle.v0, -1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Not Intersecting, triangle.v1 is closest below the plane\");\n\t\tMockTriangle target(triangle.v0 - triangle.n * 4, triangle.v1 - triangle.n * 2, triangle.v2 - triangle.n * 3);\n\t\tcheckTriPlaneDistance(TriPlaneData(target, triangle.n, d, target.v1, triangle.v1, -1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Not Intersecting, triangle.v2 is closest below the plane\");\n\t\tMockTriangle target(triangle.v0 - triangle.n * 4, triangle.v1 - triangle.n * 3, triangle.v2 - triangle.n * 2);\n\t\tcheckTriPlaneDistance(TriPlaneData(target, triangle.n, d, target.v2, triangle.v2, -1));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Triangle point on the plane\");\n\t\t// Need to change the order of points for this to work ... strange ...\n\t\tMockTriangle target(triangle.v0 + triangle.n * 3, triangle.v2 + triangle.n * 3, triangle.v1);\n\t\tcheckTriPlaneDistance(TriPlaneData(target, triangle.n, d, target.v2, target.v2, 0));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Triangle plane intersection with v0 being under the plane\");\n\t\tMockTriangle target(triangle.v0 - triangle.n * 2, triangle.v1 + triangle.n * 2, triangle.v2 + triangle.n * 2);\n\t\tdistance = distanceTrianglePlane(target.v0, target.v1, target.v2, triangle.n, d,\n\t\t\t\t\t\t\t\t\t\t &intersectionPoint0, &intersectionPoint1);\n\t\tEXPECT_NEAR(0.0, distance, epsilon);\n\t\tEXPECT_TRUE(intersectionPoint0.isApprox(intersectionPoint1));\n\t\tEXPECT_TRUE(isPointInsideTriangle(intersectionPoint0, target.v0, target.v1, target.v2, target.n));\n\t\tEXPECT_TRUE(isPointInsideTriangle(intersectionPoint0, triangle.v0, triangle.v1, triangle.v2, triangle.n));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Triangle plane intersection with v0 and v1 being under the plane\");\n\t\tMockTriangle target(triangle.v0 - triangle.n * 2, triangle.v1 - triangle.n * 2, triangle.v2 + triangle.n * 2);\n\t\tdistance = distanceTrianglePlane(target.v0, target.v1, target.v2, triangle.n, d,\n\t\t\t\t\t\t\t\t\t\t &intersectionPoint0, &intersectionPoint1);\n\t\tEXPECT_NEAR(0.0, distance, epsilon);\n\t\tEXPECT_TRUE(intersectionPoint0.isApprox(intersectionPoint1));\n\t\tEXPECT_TRUE(isPointInsideTriangle(intersectionPoint0, target.v0, target.v1, target.v2, target.n));\n\t\tEXPECT_TRUE(isPointInsideTriangle(intersectionPoint0, triangle.v0, triangle.v1, triangle.v2, triangle.n));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Triangle plane intersection with v2 being under the plane\");\n\t\tMockTriangle target(triangle.v0 + triangle.n * 2, triangle.v1 + triangle.n * 2, triangle.v2 - triangle.n * 2);\n\t\tdistance = distanceTrianglePlane(target.v0, target.v1, target.v2, triangle.n, d,\n\t\t\t\t\t\t\t\t\t\t &intersectionPoint0, &intersectionPoint1);\n\t\tEXPECT_NEAR(0.0, distance, epsilon);\n\t\tEXPECT_TRUE(intersectionPoint0.isApprox(intersectionPoint1));\n\t\tEXPECT_TRUE(isPointInsideTriangle(intersectionPoint0, target.v0, target.v1, target.v2, target.n));\n\t\tEXPECT_TRUE(isPointInsideTriangle(intersectionPoint0, triangle.v0, triangle.v1, triangle.v2, triangle.n));\n\t}\n}\n\nTEST_F(GeometryTest, PlanePlaneDistance)\n{\n\t// Simple test against same\n\tdouble d1 = -tri.n.dot(tri.v0);\n\tVectorType point0, point1;\n\n\tbool result = doesIntersectPlanePlane(tri.n, d1, tri.n, d1, &point0, &point1);\n\tEXPECT_FALSE(result);\n\tEXPECT_TRUE(eigenAllNan(point0));\n\tEXPECT_TRUE(eigenAllNan(point1));\n\tresult = doesIntersectPlanePlane(tri.n, -2.0, tri.n, 8.8, &point0, &point1);\n\tEXPECT_FALSE(result);\n\tEXPECT_TRUE(eigenAllNan(point0));\n\tEXPECT_TRUE(eigenAllNan(point1));\n\n\tVectorType n2 = VectorType(5, 6, 7);\n\tn2.normalize();\n\tdouble d2 = -2;\n\tresult = doesIntersectPlanePlane(tri.n, d1, n2, d2, &point0, &point1);\n\tVectorType output;\n\tEXPECT_TRUE(result);\n\tEXPECT_FALSE(eigenAllNan(point0));\n\tEXPECT_NEAR(0, distancePointPlane(point0, tri.n, d1, &output), epsilon);\n\tEXPECT_NEAR(0, distancePointPlane(point1, tri.n, d1, &output), epsilon);\n\tEXPECT_FALSE(eigenAllNan(point1));\n\tEXPECT_NEAR(0, distancePointPlane(point0, n2, d2, &output), epsilon);\n\tEXPECT_NEAR(0, distancePointPlane(point1, n2, d2, &output), epsilon);\n}\n\ntypedef std::tuple<Segment, MockTriangle, VectorType, VectorType> SegTriDistanceData;\nvoid checkSegTriDistance(const SegTriDistanceData& data)\n{\n\tstd::stringstream errorMessage;\n\tSegment segment = std::get<0>(data);\n\tMockTriangle tri = std::get<1>(data);\n\tVectorType expectedSegmentPoint = std::get<2>(data);\n\tVectorType expectedTrianglePoint = std::get<3>(data);\n\tdouble expectedDistance = (expectedSegmentPoint - expectedTrianglePoint).norm();\n\tdouble distance;\n\tVectorType segmentPoint, trianglePoint;\n\n\tdistance = distanceSegmentTriangle(segment.a, segment.b, tri.v0, tri.v1, tri.v2, tri.n,\n\t\t\t\t\t\t\t\t\t   &segmentPoint, &trianglePoint);\n\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\tEXPECT_TRUE(expectedSegmentPoint.isApprox(segmentPoint));\n\tEXPECT_TRUE(expectedTrianglePoint.isApprox(trianglePoint));\n\n\t// Check call without n;\n\tdistance = distanceSegmentTriangle(segment.a, segment.b, tri.v0, tri.v1, tri.v2,\n\t\t\t\t\t\t\t\t\t   &segmentPoint, &trianglePoint);\n\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\tEXPECT_TRUE(expectedSegmentPoint.isApprox(segmentPoint));\n\tEXPECT_TRUE(expectedTrianglePoint.isApprox(trianglePoint));\n\n\n\t// Repeat above with segment reversed\n\tdistance = distanceSegmentTriangle(segment.b, segment.a, tri.v0, tri.v1, tri.v2, tri.n,\n\t\t\t\t\t\t\t\t\t   &segmentPoint, &trianglePoint);\n\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\tEXPECT_TRUE(expectedSegmentPoint.isApprox(segmentPoint));\n\tEXPECT_TRUE(expectedTrianglePoint.isApprox(trianglePoint));\n\n}\nTEST_F(GeometryTest, SegmentTriangleDistance)\n{\n\tSegment segment;\n\tVectorType intersection;\n\t{\n\t\tSCOPED_TRACE(\"Segment endpoint equivalent to triangle point\");\n\t\tsegment = Segment(tri.v0, tri.v1 + tri.n * 3);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, segment.a, tri.v0));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"Segment endpoint inside triangle on triangle plane\");\n\t\tsegment = Segment(tri.pointInTriangle(0.5, 0.2), tri.pointInTriangle(2, 2) + tri.n * 4);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, segment.a, segment.a));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"Intersection inside triangle\");\n\t\tintersection = tri.pointInTriangle(0.5, 0.2);\n\t\tsegment = Segment(intersection - tri.n * 4 - tri.v0v1, intersection + tri.n * 4 + tri.v0v1);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, intersection, intersection));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"Segment endpoint on triangle edge\");\n\t\tsegment = Segment(tri.pointInTriangle(0.0, 0.2), tri.pointInTriangle(2, 2) + tri.n * 4);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, segment.a, segment.a));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"intersection on triangle edge\");\n\t\tintersection = tri.pointInTriangle(0, 0.2);\n\t\tsegment = Segment(intersection - tri.n * 3 - tri.v1v2 * .5, intersection + tri.n * 3 + tri.v1v2 * .5);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, intersection, intersection));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"segment endpoint is close to point inside of triangle\");\n\t\tintersection = tri.pointInTriangle(0.5, 0.2);\n\t\tSegment seg(intersection, intersection + tri.n * 2 + tri.v0v1 * 3);\n\t\tsegment = Segment(seg.a + tri.n * 0.1, seg.b + tri.n * 0.1);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, segment.a, intersection));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"segment endpoint is close to triangle point v0\");\n\t\tSegment seg(tri.v0, tri.v0 - tri.n * 2 - tri.v0v1 * 2);\n\t\tsegment = Segment(seg.a - tri.n * 0.1, seg.b - tri.n * 0.1);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, segment.a, tri.v0));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"segment endpoint is close to triangle point v1\");\n\t\tSegment seg(tri.v1, tri.v1 - tri.n * 2 - tri.v0v1 * 2);\n\t\tsegment = Segment(seg.a - tri.n * 0.1, seg.b - tri.n * 0.1);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, segment.a, tri.v1));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"segment endpoint is close to triangle point v2\");\n\t\tSegment seg(tri.v2, tri.v2 - tri.n * 2 - tri.v1v2 * 2);\n\t\tsegment = Segment(seg.a - tri.n * 0.1, seg.b - tri.n * 0.1);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, segment.a, tri.v2));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"segment endpoint is close to edge v0v1\");\n\t\tintersection = tri.v0 + tri.v0v1 * 0.2;\n\t\tSegment seg(intersection, intersection + tri.n * 2);\n\t\tsegment = Segment(seg.a + seg.ab * 0.01, seg.b + seg.ab * 0.01);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, segment.a, intersection));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"segment endpoint is close to edge v0v2\");\n\t\tintersection = tri.v0 + tri.v0v2 * 0.4;\n\t\tSegment seg(intersection, intersection + tri.n * 2);\n\t\tsegment = Segment(seg.a + seg.ab * 0.01, seg.b + seg.ab * 0.01);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, segment.a, intersection));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"segment endpoint is close to edge v1v2\");\n\t\tintersection = tri.v1 + tri.v1v2 * 0.2;\n\t\tSegment seg(intersection, intersection + tri.n * 2);\n\t\tsegment = Segment(seg.a + seg.ab * 0.01, seg.b + seg.ab * 0.01);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, segment.a, intersection));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"point on segment is close to triangle vertex v0\");\n\t\tsegment = Segment(tri.v0 - tri.n * 3, tri.v0 + tri.n * 3);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, tri.v0, tri.v0));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"point on segment is close to triangle vertex v1\");\n\t\tsegment = Segment(tri.v1 - tri.n * 3, tri.v1 + tri.n * 3);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, tri.v1, tri.v1));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"point on segment is close to triangle vertex v2\");\n\t\tsegment = Segment(tri.v2 - tri.n * 3, tri.v2 + tri.n * 3);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, tri.v2, tri.v2));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"point on segment is close to edge v0v1\");\n\t\tintersection = tri.v0 + tri.v0v1 * 0.2;\n\t\tSegment seg(intersection - tri.n * 3, intersection + tri.n * 2);\n\t\tVectorType cross = tri.n.cross(tri.v0v1);\n\t\tsegment = Segment(seg.a - cross * 0.01, seg.b - cross * 0.01);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, intersection - cross * 0.01, intersection));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"point on segment is close to edge v0v2\");\n\t\tintersection = tri.v0 + tri.v0v2 * 0.2;\n\t\tSegment seg(intersection - tri.n * 3, intersection + tri.n * 2);\n\t\tVectorType cross = tri.n.cross(tri.v0v2);\n\t\tsegment = Segment(seg.a + cross * 0.01, seg.b + cross * 0.01);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, intersection + cross * 0.01, intersection));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"point on segment is close to edge v1v2\");\n\t\tintersection = tri.v1 + tri.v1v2 * 0.2;\n\t\tSegment seg(intersection - tri.n * 3, intersection + tri.n * 2);\n\t\tVectorType cross = tri.n.cross(tri.v1v2);\n\t\tsegment = Segment(seg.a - cross * 0.01, seg.b - cross * 0.01);\n\t\tcheckSegTriDistance(SegTriDistanceData(segment, tri, intersection - cross * 0.01, intersection));\n\t}\n}\n\ntypedef std::tuple<MockTriangle, MockTriangle, VectorType, VectorType> TriTriDistanceData;\nvoid checkTriTriDistance(const TriTriDistanceData& data)\n{\n\tMockTriangle t0 = std::get<0>(data);\n\tMockTriangle t1 = std::get<1>(data);\n\tVectorType expectedT0Point = std::get<2>(data);\n\tVectorType expectedT1Point = std::get<3>(data);\n\tdouble expectedDistance = (expectedT1Point - expectedT0Point).norm();\n\tdouble distance;\n\tVectorType t0Point, t1Point;\n\n\t{\n\t\tSCOPED_TRACE(\"Normal Test\");\n\t\tdistance = distanceTriangleTriangle(t0.v0, t0.v1, t0.v2, t1.v0, t1.v1, t1.v2, &t0Point, &t1Point);\n\t\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\t\tEXPECT_TRUE(expectedT0Point.isApprox(t0Point));\n\t\tEXPECT_TRUE(expectedT1Point.isApprox(t1Point));\n\t}\n\n// \t{\n// \t\tSCOPED_TRACE(\"Reversed Triangles\");\n// \t\tdistance = TriangleTriangleDistance(t1.v0, t1.v1, t1.v2, t0.v0, t0.v1, t0.v2, &t1Point, &t0Point);\n// \t\tEXPECT_NEAR(expectedDistance, distance,epsilon);\n// \t\tEXPECT_TRUE(expectedT0Point.isApprox(t0Point));\n// \t\tEXPECT_TRUE(expectedT1Point.isApprox(t1Point));\n// \t}\n\n\t{\n\t\tSCOPED_TRACE(\"Shift t0 edges once\");\n\t\tdistance = distanceTriangleTriangle(t0.v1, t0.v2, t0.v0, t1.v0, t1.v1, t1.v2, &t0Point, &t1Point);\n\t\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\t\tEXPECT_TRUE(expectedT0Point.isApprox(t0Point));\n\t\tEXPECT_TRUE(expectedT1Point.isApprox(t1Point));\n\t}\n\n\n\t{\n\t\tSCOPED_TRACE(\"Shift t0 edges twice\");\n\t\tdistance = distanceTriangleTriangle(t0.v2, t0.v0, t0.v1, t1.v0, t1.v1, t1.v2, &t0Point, &t1Point);\n\t\tEXPECT_NEAR(expectedDistance, distance, epsilon);\n\t\tEXPECT_TRUE(expectedT0Point.isApprox(t0Point));\n\t\tEXPECT_TRUE(expectedT1Point.isApprox(t1Point));\n\t}\n}\n\nTEST_F(GeometryTest, distanceTriangleTriangle)\n{\n\tMockTriangle t0(VectorType(5, 0, 0), VectorType(0, 2, 2), VectorType(0, -2, -2));\n\tMockTriangle t1;\n\t{\n\t\tSCOPED_TRACE(\"vertex t1v0 equal to t0v0\");\n\t\tt1 = MockTriangle(t0.v0, t0.v1 + t0.n * 2, t0.v2 + t0.n * 2);\n\t\tcheckTriTriDistance(TriTriDistanceData(t1, t0, t0.v0, t0.v0));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"vertex t1v0 inside of triangle t0\");\n\t\tVectorType intersection = t0.pointInTriangle(0.2, 0.2);\n\t\tt1 = MockTriangle(intersection, t0.v1 + t0.n * 2, t0.v2 + t0.n * 2);\n\t\tcheckTriTriDistance(TriTriDistanceData(t1, t0, t1.v0, intersection));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"vertex t1v0 close to t0v0\");\n\t\tt1 = MockTriangle(t0.v0 + t0.n, t0.v1 + t0.n * 2, t0.v2 + t0.n * 2);\n\t\tcheckTriTriDistance(TriTriDistanceData(t1, t0, t1.v0, t0.v0));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"vertex t1v0 close to the inside of triangle t0\");\n\t\tVectorType intersection = t0.pointInTriangle(0.2, 0.2);\n\t\tt1 = MockTriangle(intersection + t0.n, t0.v1 + t0.n * 2, t0.v2 + t0.n * 2);\n\t\tcheckTriTriDistance(TriTriDistanceData(t1, t0, t1.v0, intersection));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"edge t1v0v1 through triangle t0\");\n\t\tVectorType intersection = t0.pointInTriangle(0.2, 0.2);\n\t\tt1 = MockTriangle(intersection + t0.n * 3, t0.v0 - t0.v0v2 * 4 + t0.n, intersection - t0.n * 4);\n\t\tcheckTriTriDistance(TriTriDistanceData(t1, t0, intersection, intersection));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"Triangles parallel\");\n\t\tt1 = MockTriangle(t0.v0 + tri.n * 3, t0.v1 + tri.n * 3, t0.v2 + tri.n * 3);\n\t\tVectorType closest0, closest1;\n\t\tdouble distance = distanceTriangleTriangle(t0.v0, t0.v1, t0.v2, t1.v0, t1.v1, t1.v2, &closest0, &closest1);\n\t\tEXPECT_NEAR(3.0, distance, epsilon);\n\t}\n\t{\n\t\tSCOPED_TRACE(\"edge t0v0v1 close to t1v0v1\");\n\t\tVectorType closest0 = t0.v0 + t0.v0v1 * 0.2;\n\t\tVectorType shift = t0.n.cross(t0.v0v1.normalized());\n\t\tshift.normalize();\n\t\tVectorType closest1 = closest0 - shift * 2;\n\t\tt1 = MockTriangle(closest1 - tri.n * 2, closest1 + tri.n * 2, closest1 + tri.n - shift * 10);\n\t\tcheckTriTriDistance(TriTriDistanceData(t1, t0, closest1, closest0));\n\t}\n}\n\nTEST_F(GeometryTest, IntersectionsSegmentBox)\n{\n\tEigen::AlignedBox<SizeType, 3> box;\n\t{\n\t\tSCOPED_TRACE(\"No intersection, zero length segment\");\n\t\tVectorType point1(0.0, 0.0, 0.0);\n\t\tVectorType point2(0.0, 0.0, 0.0);\n\t\tbox.min() = VectorType(1.0, 1.0, 1.0);\n\t\tbox.max() = VectorType(5.0, 5.0, 5.0);\n\t\tstd::vector<VectorType> intersections;\n\t\tintersectionsSegmentBox(point1, point2, box, &intersections);\n\t\tEXPECT_EQ(0u, intersections.size());\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"No intersection, zero size box\");\n\t\tVectorType point1(0.0, 0.0, 0.0);\n\t\tVectorType point2(0.0, 5.0, 0.0);\n\t\tbox.min() = VectorType(1.0, 1.0, 1.0);\n\t\tbox.max() = VectorType(1.0, 1.0, 1.0);\n\t\tstd::vector<VectorType> intersections;\n\t\tintersectionsSegmentBox(point1, point2, box, &intersections);\n\t\tEXPECT_EQ(0u, intersections.size());\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"No Intersection, parallel and beyond corners\");\n\t\tVectorType point1(-0.0, 0.0, -0.0);\n\t\tVectorType point2(0.0, 5.0, -0.0);\n\t\tbox.min() = VectorType(1.0, 1.0, 1.0);\n\t\tbox.max() = VectorType(5.0, 5.0, 5.0);\n\t\tstd::vector<VectorType> intersections;\n\t\tintersectionsSegmentBox(point1, point2, box, &intersections);\n\t\tEXPECT_EQ(0u, intersections.size());\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Entering box, but not leaving\");\n\t\tVectorType point1(2.0, 2.0, 0.0);\n\t\tVectorType point2(3.0, 3.0, 2.0);\n\t\tbox.min() = VectorType(1.0, 1.0, 1.0);\n\t\tbox.max() = VectorType(5.0, 5.0, 5.0);\n\t\tstd::vector<VectorType> intersections;\n\t\tintersectionsSegmentBox(point1, point2, box, &intersections);\n\t\tEXPECT_EQ(1u, intersections.size());\n\t\tEXPECT_TRUE(intersections[0].isApprox(VectorType(2.5, 2.5, 1.0)));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Entering and exiting box, through box corners\");\n\t\tVectorType point1(0.0, 0.0, 0.0);\n\t\tVectorType point2(6.0, 6.0, 6.0);\n\t\tbox.min() = VectorType(1.0, 1.0, 1.0);\n\t\tbox.max() = VectorType(5.0, 5.0, 5.0);\n\t\tstd::vector<VectorType> intersections;\n\t\tintersectionsSegmentBox(point1, point2, box, &intersections);\n\t\tEXPECT_EQ(2u, intersections.size());\n\t\tEXPECT_TRUE(intersections[0].isApprox(box.min()) || intersections[0].isApprox(box.max()));\n\t\tEXPECT_TRUE(intersections[1].isApprox(box.min()) || intersections[1].isApprox(box.max()));\n\t}\n}\n\nTEST_F(GeometryTest, DoesIntersectBoxCapsule)\n{\n\ttypedef Eigen::AlignedBox<SizeType, 3> BoxType;\n\t{\n\t\tSCOPED_TRACE(\"No intersection\");\n\t\tVectorType bottom(-5.0, 5.0, 0.0);\n\t\tVectorType top(5.0, 5.0, 0.0);\n\t\tdouble radius = 1.0;\n\t\tBoxType box(VectorType(-1.0, -1.0, -1.0), VectorType(1.0, 1.0, 1.0));\n\t\tEXPECT_FALSE(doesIntersectBoxCapsule(bottom, top, radius, box));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"Intersection, capsule in middle of box\");\n\t\tVectorType bottom(-5.0, -5.0, -5.0);\n\t\tVectorType top(5.0, 5.0, 5.0);\n\t\tdouble radius = 10.0;\n\t\tBoxType box(VectorType(-1.0, -1.0, -1.0), VectorType(1.0, 1.0, 1.0));\n\t\tEXPECT_TRUE(doesIntersectBoxCapsule(bottom, top, radius, box));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"No Intersection, box not centered\");\n\t\tVectorType bottom(-5.0, -5.0, -5.0);\n\t\tVectorType top(5.0, 5.0, 5.0);\n\t\tdouble radius = 1.0;\n\t\tBoxType box(VectorType(1.0, 1.0, -1.0), VectorType(2.0, 2.0, -2.0));\n\t\tEXPECT_FALSE(doesIntersectBoxCapsule(bottom, top, radius, box));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"Intersection, box not centered\");\n\t\tVectorType bottom(-5.0, -5.0, -5.0);\n\t\tVectorType top(5.0, 5.0, 5.0);\n\t\tdouble radius = 1.0;\n\t\tBoxType box(VectorType(0.0, 0.0, 0.0), VectorType(1.0, 1.0, 1.0));\n\t\tEXPECT_TRUE(doesIntersectBoxCapsule(bottom, top, radius, box));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"No intersection, capsule along edge\");\n\t\tVectorType bottom(2.0, -2.0, 2.0);\n\t\tVectorType top(2.0, 2.0, 2.0);\n\t\tdouble radius = sqrt(2.0) - 1.0;\n\t\tBoxType box(VectorType(-1.0, -1.0, -1.0), VectorType(1.0, 1.0, 1.0));\n\t\tEXPECT_FALSE(doesIntersectBoxCapsule(bottom, top, radius, box));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"Intersection, capsule along edge\");\n\t\tVectorType bottom(2.0, -2.0, 2.0);\n\t\tVectorType top(2.0, 2.0, 2.0);\n\t\tdouble radius = sqrt(2.0) + 0.1;\n\t\tBoxType box(VectorType(-1.0, -1.0, -1.0), VectorType(1.0, 1.0, 1.0));\n\t\tEXPECT_TRUE(doesIntersectBoxCapsule(bottom, top, radius, box));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"No Intersection, capsule at corner\");\n\t\tVectorType bottom(2.0, 3.0, 1.0);\n\t\tVectorType top(2.0, 1.0, 3.0);\n\t\tdouble radius = sqrt(3.0) - 0.1;\n\t\tBoxType box(VectorType(-1.0, -1.0, -1.0), VectorType(1.0, 1.0, 1.0));\n\t\tEXPECT_FALSE(doesIntersectBoxCapsule(bottom, top, radius, box));\n\t}\n\t{\n\t\tSCOPED_TRACE(\"Intersection, capsule at corner\");\n\t\tVectorType bottom(2.0, 3.0, 1.0);\n\t\tVectorType top(2.0, 1.0, 3.0);\n\t\tdouble radius = sqrt(3.0) + 0.1;\n\t\tBoxType box(VectorType(-1.0, -1.0, -1.0), VectorType(1.0, 1.0, 1.0));\n\t\tEXPECT_TRUE(doesIntersectBoxCapsule(bottom, top, radius, box));\n\t}\n}\n\nTEST_F(GeometryTest, TimesOfCoplanarity)\n{\n\tstd::array<SizeType, 3> times;\n\n\t{\n\t\tSCOPED_TRACE(\"No coplanarity case in [0..1]\");\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(0.0, 0.0, 0.0), VectorType(1.0, 0.0, 1.0));\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(1.0, 0.0, 2.0), VectorType(2.0, 0.0, 4.0));\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(0.0, 0.1, 10.0), VectorType(0.0, 1.1, 10.0));\n\t\tstd::pair<VectorType, VectorType> D = std::make_pair(VectorType(0.0, 1.1, 10.0), VectorType(0.0, 2.1, 10.0));\n\t\tEXPECT_EQ(0, (timesOfCoplanarityInRange01<double, Vector3d::Options>(A, B, C, D, &times)));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"1 case of coplanarity at time 0\");\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(0.0, 0.0, 0.0), VectorType(1.0, 0.0, 1.0));\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(1.0, 0.0, 2.0), VectorType(2.0, 0.0, 4.0));\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(0.0, 1.0, -2.0), VectorType(0.0, 2.0, -3.5));\n\t\tstd::pair<VectorType, VectorType> D = std::make_pair(VectorType(0.0, 0.0, 0.0), VectorType(0.0, 1.0, -10.0));\n\t\tEXPECT_EQ(1, (timesOfCoplanarityInRange01<double, Vector3d::Options>(A, B, C, D, &times)));\n\t\tEXPECT_DOUBLE_EQ(0.0, times[0]);\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"1 case of coplanarity at time 0.5\");\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(0.1, 0.0, 1.0), VectorType(-0.1, 0.0, -1.0));\n\t\t// A(0.5) = 0.0 0.0 0.0\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(1.0, 0.0, 2.0), VectorType(2.0, 3.0, -2.0));\n\t\t// B(0.5) = 1.5 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(-0.3, 2.0, -2.0), VectorType(0.3, 1.0, 2.0));\n\t\t// C(0.5) = 0.0 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> D = std::make_pair(VectorType(1.7, 1.0, -1.0), VectorType(1.3, -1.0, 1.0));\n\t\t// D(0.5) = 1.5 0.0 0.0\n\t\tEXPECT_EQ(1, (timesOfCoplanarityInRange01<double, Vector3d::Options>(A, B, C, D, &times)));\n\t\tEXPECT_NEAR(0.5, times[0], Math::Geometry::ScalarEpsilon);\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"2 cases of coplanarity at times 0.089971778657590915 and 0.5\");\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(0.4, 0.8, 1.0), VectorType(0.8, 1.0, -1.0));\n\t\t// A(0.5) = 0.6 0.9 0.0\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(1.0, 0.0, 2.0), VectorType(2.0, 3.0, -2.0));\n\t\t// B(0.5) = 1.5 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(-0.3, 2.0, -2.0), VectorType(0.3, 1.0, 2.0));\n\t\t// C(0.5) = 0.0 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> D = std::make_pair(VectorType(1.7, 1.0, -1.0), VectorType(1.3, -1.0, 1.0));\n\t\t// D(0.5) = 1.5 0.0 0.0\n\t\tEXPECT_EQ(2, (timesOfCoplanarityInRange01<double, Vector3d::Options>(A, B, C, D, &times)));\n\t\tEXPECT_NEAR(0.089971778657590915, times[0], Math::Geometry::ScalarEpsilon);\n\t\tEXPECT_NEAR(0.5, times[1], Math::Geometry::ScalarEpsilon);\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"1 case of coplanarity at time 1\");\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(0.0, 0.0, 0.0), VectorType(1.0, 0.0, 1.0));\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(1.0, 0.0, 1.24), VectorType(2.0, 0.0, 3.0));\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(0.0, 1.0, -2.0), VectorType(2.0, 0.0, 3.0));\n\t\tstd::pair<VectorType, VectorType> D = std::make_pair(VectorType(0.1, 1.0, 1.1), VectorType(0.0, 1.0, -1.54));\n\t\tEXPECT_EQ(1, (timesOfCoplanarityInRange01<double, Vector3d::Options>(A, B, C, D, &times)));\n\t\tEXPECT_NEAR(1.0, times[0], Math::Geometry::ScalarEpsilon);\n\t}\n}\n\nTEST_F(GeometryTest, CcdIntersectionsSegmentSegment)\n{\n\tSizeType time, s0p1Factor, s1p1Factor;\n\n\t{\n\t\tSCOPED_TRACE(\"No intersection\");\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(0.0, 0.0, 0.0), VectorType(1.0, 0.0, 1.0));\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(1.0, 0.0, 2.0), VectorType(2.0, 0.0, 4.0));\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(0.0, 0.1, 4.0), VectorType(0.0, 1.1, 8.0));\n\t\tstd::pair<VectorType, VectorType> D = std::make_pair(VectorType(0.0, 1.1, 6.0), VectorType(0.0, 2.1, 54.0));\n\t\tEXPECT_FALSE(calculateCcdContactSegmentSegment(A, B, C, D, &time, &s0p1Factor, &s1p1Factor));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Intersection at t=0\");\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(0.0, 0.0, 0.0), VectorType(1.0, 0.0, 1.0));\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(1.0, 0.0, 2.0), VectorType(2.0, 0.0, 4.0));\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(0.0, 1.0, -2.0), VectorType(0.0, 2.0, -3.5));\n\t\tstd::pair<VectorType, VectorType> D = std::make_pair(VectorType(0.0, 0.0, 0.0), VectorType(0.0, 1.0, -10.0));\n\t\tEXPECT_TRUE(calculateCcdContactSegmentSegment(A, B, C, D, &time, &s0p1Factor, &s1p1Factor));\n\t\tEXPECT_DOUBLE_EQ(0.0, time);\n\t\tEXPECT_DOUBLE_EQ(0.0, s0p1Factor);\n\t\tEXPECT_DOUBLE_EQ(1.0, s1p1Factor);\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Intersection at t=0.5\");\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(0.1, 0.0, 1.0), VectorType(-0.1, 0.0, -1.0));\n\t\t// A(0.5) = 0.0 0.0 0.0\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(1.0, 0.0, 2.0), VectorType(2.0, 3.0, -2.0));\n\t\t// B(0.5) = 1.5 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(-0.3, 2.0, -2.0), VectorType(0.3, 1.0, 2.0));\n\t\t// C(0.5) = 0.0 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> D = std::make_pair(VectorType(1.7, 1.0, -1.0), VectorType(1.3, -1.0, 1.0));\n\t\t// D(0.5) = 1.5 0.0 0.0\n\t\t// At time 0.5, the segments AB and CD are coplanar and intersect exactly in their middle\n\t\tEXPECT_TRUE(calculateCcdContactSegmentSegment(A, B, C, D, &time, &s0p1Factor, &s1p1Factor));\n\t\tEXPECT_NEAR(0.5, time, Math::Geometry::ScalarEpsilon);\n\t\tEXPECT_NEAR(0.5, s0p1Factor, Math::Geometry::ScalarEpsilon);\n\t\tEXPECT_NEAR(0.5, s1p1Factor, Math::Geometry::ScalarEpsilon);\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Intersection at t=0.5\");\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(0.4, 0.0, 1.0), VectorType(0.6, 0.0, -1.0));\n\t\t// A(0.5) = 0.5 0.0 0.0\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(1.0, 0.0, 2.0), VectorType(2.0, 3.0, -2.0));\n\t\t// B(0.5) = 1.5 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(-0.3, 2.0, -2.0), VectorType(0.3, 1.0, 2.0));\n\t\t// C(0.5) = 0.0 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> D = std::make_pair(VectorType(1.7, 1.0, -1.0), VectorType(1.3, -1.0, 1.0));\n\t\t// D(0.5) = 1.5 0.0 0.0\n\t\t// At time 0.5, the segments AB and CD are coplanar and intersect at P:\n\t\t// P = A + 0.4 AB = (0.5 0.0 0.0) + 0.4 (1.0 1.5 0.0)  = (0.9 0.6 0.0)\n\t\t// P = C + 0.6 CD = (0.0 1.5 0.0) + 0.6 (1.5 -1.5 0.0) = (0.9 0.6 0.0)\n\t\tEXPECT_TRUE(calculateCcdContactSegmentSegment(A, B, C, D, &time, &s0p1Factor, &s1p1Factor));\n\t\tEXPECT_NEAR(0.5, time, Math::Geometry::ScalarEpsilon);\n\t\tEXPECT_NEAR(0.4, s0p1Factor, Math::Geometry::ScalarEpsilon);\n\t\tEXPECT_NEAR(0.6, s1p1Factor, Math::Geometry::ScalarEpsilon);\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Intersection at t=0.5 (2 cubic roots in [0..1]: 0.0899 (no collision) and 0.5 (collision))\");\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(0.4, 0.8, 1.0), VectorType(0.8, 1.0, -1.0));\n\t\t// A(0.5) = 0.6 0.9 0.0\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(1.0, 0.0, 2.0), VectorType(2.0, 3.0, -2.0));\n\t\t// B(0.5) = 1.5 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(-0.3, 2.0, -2.0), VectorType(0.3, 1.0, 2.0));\n\t\t// C(0.5) = 0.0 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> D = std::make_pair(VectorType(1.7, 1.0, -1.0), VectorType(1.3, -1.0, 1.0));\n\t\t// D(0.5) = 1.5 0.0 0.0\n\t\t// At time 0.5, all 4 points are coplanar and AB/CD intersect:\n\t\t// P = A +   0*AB = (0.6 0.9 0.0)\n\t\t// P = C + 0.4*CD = (0.0 1.5 0.0) + 0.4 (1.5 -1.5 0.0) = (0.6 0.9 0.0)\n\t\tEXPECT_TRUE(calculateCcdContactSegmentSegment(A, B, C, D, &time, &s0p1Factor, &s1p1Factor));\n\t\tEXPECT_NEAR(0.5, time, Math::Geometry::ScalarEpsilon);\n\t\tEXPECT_NEAR(0.0, s0p1Factor, Math::Geometry::ScalarEpsilon);\n\t\tEXPECT_NEAR(0.4, s1p1Factor, Math::Geometry::ScalarEpsilon);\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Intersection at t=1\");\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(0.0, 0.0, 0.0), VectorType(1.0, 0.0, 1.0));\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(1.0, 0.0, 1.24), VectorType(2.0, 0.0, 3.0));\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(0.0, 1.0, -2.0), VectorType(2.0, 0.0, 3.0));\n\t\tstd::pair<VectorType, VectorType> D = std::make_pair(VectorType(0.1, 1.0, 1.1), VectorType(0.0, 1.0, -1.54));\n\t\tEXPECT_TRUE(calculateCcdContactSegmentSegment(A, B, C, D, &time, &s0p1Factor, &s1p1Factor));\n\t\tEXPECT_DOUBLE_EQ(1.0, time);\n\t\tEXPECT_DOUBLE_EQ(1.0, s0p1Factor);\n\t\tEXPECT_DOUBLE_EQ(0.0, s1p1Factor);\n\t}\n}\n\nTEST_F(GeometryTest, CcdIntersectionsPointTriangle)\n{\n\tSizeType time, tv01Factor, tv02Factor;\n\n\t{\n\t\tSCOPED_TRACE(\"No intersection\");\n\t\tstd::pair<VectorType, VectorType> P = std::make_pair(VectorType(0.0, 0.0, 0.0), VectorType(1.0, 0.0, 1.0));\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(1.0, 0.0, 2.0), VectorType(2.0, 0.0, 4.0));\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(0.0, 0.1, 4.0), VectorType(0.0, 1.1, 8.0));\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(0.0, 1.1, 6.0), VectorType(0.0, 2.1, 54.0));\n\t\tEXPECT_FALSE(calculateCcdContactPointTriangle(P, A, B, C, &time, &tv01Factor, &tv02Factor));\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Intersection at t=0\");\n\t\tstd::pair<VectorType, VectorType> P = std::make_pair(VectorType(0.0, 0.0, 0.0), VectorType(1.0, 0.0, 1.0));\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(1.0, 0.0, 2.0), VectorType(2.0, 0.0, 4.0));\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(0.0, 1.0, -2.0), VectorType(0.0, 2.0, -3.5));\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(0.0, 0.0, 0.0), VectorType(0.0, 1.0, -10.0));\n\t\tEXPECT_TRUE(calculateCcdContactPointTriangle(P, A, B, C, &time, &tv01Factor, &tv02Factor));\n\t\tEXPECT_DOUBLE_EQ(0.0, time);\n\t\tEXPECT_DOUBLE_EQ(0.0, tv01Factor);\n\t\tEXPECT_DOUBLE_EQ(1.0, tv02Factor);\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Intersection at t=0.5\");\n\t\tstd::pair<VectorType, VectorType> P = std::make_pair(VectorType(1.1, 0.0, 1.0), VectorType(0.9, 2.0, -1.0));\n\t\t// P(0.5) = 1.0 1.0 0.0\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(1.0, 0.0, 2.0), VectorType(2.0, 3.0, -2.0));\n\t\t// A(0.5) = 1.5 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(-0.3, 2.0, -2.0), VectorType(0.3, 1.0, 2.0));\n\t\t// B(0.5) = 0.0 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(1.7, 1.0, -1.0), VectorType(1.3, -1.0, 1.0));\n\t\t// C(0.5) = 1.5 0.0 0.0\n\t\t// At time 0.5, all 4 points are coplanar and P is inside ABC with the barycentric coordinates (1/3 1/3 1/3)\n\t\tEXPECT_TRUE(calculateCcdContactPointTriangle(P, A, B, C, &time, &tv01Factor, &tv02Factor));\n\t\tEXPECT_NEAR(0.5, time, Math::Geometry::ScalarEpsilon);\n\t\tEXPECT_NEAR(1.0 / 3.0, tv01Factor, Math::Geometry::ScalarEpsilon);\n\t\tEXPECT_NEAR(1.0 / 3.0, tv01Factor, Math::Geometry::ScalarEpsilon);\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Intersection at t=0.5 (2 cubic roots in [0..1]: 0.0899 (no collision) and 0.5 (collision))\");\n\t\tstd::pair<VectorType, VectorType> P = std::make_pair(VectorType(0.4, 0.8, 1.0), VectorType(0.8, 1.0, -1.0));\n\t\t// P(0.5) = 0.6 0.9 0.0\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(1.0, 0.0, 2.0), VectorType(2.0, 3.0, -2.0));\n\t\t// A(0.5) = 1.5 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(-0.3, 2.0, -2.0), VectorType(0.3, 1.0, 2.0));\n\t\t// B(0.5) = 0.0 1.5 0.0\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(1.7, 1.0, -1.0), VectorType(1.3, -1.0, 1.0));\n\t\t// C(0.5) = 1.5 0.0 0.0\n\t\t// At time 0.5, all 4 points are coplanar and P is inside ABC with the barycentric coordinates (0 0.6 0.4)\n\t\t// P = A + 0.6 AB + 0.4 AC = (1.5 1.5 0.0) + 0.6 (-1.5 0.0 0.0) + 0.4 (0.0 -1.5 0.0) = (0.6 0.9 0.0)\n\t\tEXPECT_TRUE(calculateCcdContactPointTriangle(P, A, B, C, &time, &tv01Factor, &tv02Factor));\n\t\tEXPECT_NEAR(0.5, time, Math::Geometry::ScalarEpsilon);\n\t\tEXPECT_NEAR(0.6, tv01Factor, Math::Geometry::ScalarEpsilon);\n\t\tEXPECT_NEAR(0.4, tv02Factor, Math::Geometry::ScalarEpsilon);\n\t}\n\n\t{\n\t\tSCOPED_TRACE(\"Intersection at t=1\");\n\t\tstd::pair<VectorType, VectorType> P = std::make_pair(VectorType(1.0, 0.0, 1.24), VectorType(2.0, 0.0, 3.0));\n\t\tstd::pair<VectorType, VectorType> A = std::make_pair(VectorType(0.0, 0.0, 0.0), VectorType(1.0, 0.0, 1.0));\n\t\tstd::pair<VectorType, VectorType> B = std::make_pair(VectorType(0.0, 1.0, -2.0), VectorType(2.0, 0.0, 3.0));\n\t\tstd::pair<VectorType, VectorType> C = std::make_pair(VectorType(0.1, 1.0, 1.1), VectorType(0.0, 1.0, -1.54));\n\t\tEXPECT_TRUE(calculateCcdContactPointTriangle(P, A, B, C, &time, &tv01Factor, &tv02Factor));\n\t\tEXPECT_DOUBLE_EQ(1.0, time);\n\t\tEXPECT_DOUBLE_EQ(1.0, tv01Factor);\n\t\tEXPECT_DOUBLE_EQ(0.0, tv02Factor);\n\t}\n}\n\n}; // namespace Math\n}; // namespace SurgSim\n", "meta": {"hexsha": "bd32f5e4d35c015cbce22cd352440ef3f2aec9ec", "size": 81665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SurgSim/Math/UnitTests/GeometryTests.cpp", "max_stars_repo_name": "dbungert/opensurgsim", "max_stars_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T16:18:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T03:29:11.000Z", "max_issues_repo_path": "SurgSim/Math/UnitTests/GeometryTests.cpp", "max_issues_repo_name": "dbungert/opensurgsim", "max_issues_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-12-21T14:54:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T12:38:07.000Z", "max_forks_repo_path": "SurgSim/Math/UnitTests/GeometryTests.cpp", "max_forks_repo_name": "dbungert/opensurgsim", "max_forks_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-04-10T19:45:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T17:00:59.000Z", "avg_line_length": 42.4013499481, "max_line_length": 116, "alphanum_fraction": 0.7140513072, "num_tokens": 26896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5102063278041832}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::survival::model::models::exponential::log_likelihood.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_MODEL_MODELS_EXPONENTIAL_LOG_LIKELIHOOD_HPP_ER_2009\n#define BOOST_STATISTICS_SURVIVAL_MODEL_MODELS_EXPONENTIAL_LOG_LIKELIHOOD_HPP_ER_2009\n#include <boost/statistics/survival/model/meta/model_data.hpp>\n#include <boost/statistics/survival/model/models/exponential/model.hpp>\n#include <boost/statistics/survival/model/models/exponential/detail/log_likelihood.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace model{\n    \n    // Models HasLogLikelihood (sandbox/statistics/model/concept).\n    //\n    // Intentionally not in namespace survival\n    template<typename T,typename X,typename P>\n    T log_likelihood(\n        typename survival::model::meta::model_data<\n            T,\n            survival::model::exponential::model<T>,\n            X\n        >::type md,\n        const P& beta\n    ){\n        // TODO check\n        // Models:\n        //HasLogLikelihood<\n        //    T,\n        //    survival::model::exponential::model<T>,\n        //    X,\n        //    typename meta::response<T>::type,\n        //    P\n        //>\n\n        typedef survival::model::exponential::model<T> model_;\n    \n        T lr = model_::log_rate(\n            md.covariate(),\n            beta\n        );\n        return survival::model::exponential::detail::log_likelihood( \n            lr, \n            md.response() \n        );\n    }\n\n    // If P == X we need this overload, or else the compiler cannot find\n    // the above definition\n    template<typename T,typename X>\n    T log_likelihood(\n        typename survival::model::meta::model_data<\n            T,\n            survival::model::exponential::model<T>,\n            X\n        >::type md,\n        const X& beta\n    ){\n        return log_likelihood<T,X,X>(\n            md,\n            beta\n        );\n    }\n\n}// model\n}// statistics\n}// boost\n\n#endif ", "meta": {"hexsha": "bcb145ae908a3695df8fac6e0ebb925e87da2c68", "size": 2385, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "survival_model copy/boost/statistics/survival/model/models/exponential/log_likelihood.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_model copy/boost/statistics/survival/model/models/exponential/log_likelihood.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_model copy/boost/statistics/survival/model/models/exponential/log_likelihood.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": 32.6712328767, "max_line_length": 87, "alphanum_fraction": 0.5408805031, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5101609190840936}}
{"text": "#ifndef JHMI_UTILITY_MAKE_BALANCED_SAMPLER_HPP_NRC_20160805\n#define JHMI_UTILITY_MAKE_BALANCED_SAMPLER_HPP_NRC_20160805\n\n#include <boost/container/flat_map.hpp>\n#include <range/v3/algorithm.hpp>\n#include <range/v3/view.hpp>\n\nnamespace jhmi {\n\n  auto make_balanced_sampler(std::vector<int> const& values) {\n    auto hist = boost::container::flat_map<int,int>{};\n    for (auto&& v : values)\n      ++hist[v];\n    auto desired_pct = 1. / hist.size();\n    auto all_sum = ranges::accumulate(hist | ranges::view::values, 0);\n    auto weight_table = boost::container::flat_map<int, double>{};\n    for (auto&& h : hist)\n      weight_table.insert(std::make_pair(h.first, desired_pct * all_sum / h.second));\n    auto weights = values | ranges::view::transform([&](int i) { return weight_table[i]; });\n\n    return std::discrete_distribution<>(weights.begin(), weights.end());\n    //auto ones = std::vector<double>(hist.size(), 1.);\n    //return std::discrete_distribution<>(ones.begin(), ones.end());\n  }\n}\n\n#endif\n", "meta": {"hexsha": "a614a48525966f6e9e286202493cc2b28850ceac", "size": 1003, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utility/make_balanced_sampler.hpp", "max_stars_repo_name": "ncrookston/liver_source", "max_stars_repo_head_hexsha": "9876ac4e9ea57d8e23767af9be061a9b10c6f1e5", "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": "utility/make_balanced_sampler.hpp", "max_issues_repo_name": "ncrookston/liver_source", "max_issues_repo_head_hexsha": "9876ac4e9ea57d8e23767af9be061a9b10c6f1e5", "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": "utility/make_balanced_sampler.hpp", "max_forks_repo_name": "ncrookston/liver_source", "max_forks_repo_head_hexsha": "9876ac4e9ea57d8e23767af9be061a9b10c6f1e5", "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.8214285714, "max_line_length": 92, "alphanum_fraction": 0.6929212363, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5101609190840936}}
{"text": "\r\n#pragma once\r\n\r\n#define EIGEN_NO_AUTOMATIC_RESIZING \r\n\r\n#include \"Tableau.hpp\"\r\n#include \"SM_utils.hpp\"\r\n#include \"Solids.hpp\"\r\n#include \"ReplacementDictionary.hpp\"\r\n#include \"Equilibrium.hpp\"\r\n\r\n#include <Eigen/Dense>\r\n\r\n#include <stdexcept>\r\n#include <algorithm>\r\n#include <cstddef>\r\n#include <tuple>\r\n#include <utility>\r\n\r\nnamespace AQSystemSolver {\r\n    [[nodiscard]] inline auto possiblyAddSolid(const Eigen::VectorXd& solubilityProducts, ReplacementDict& replacementDict, SolidSystem& solidSystem){\r\n        const auto addAttempt=solidSystem.getSolidToAdd(solubilityProducts);\r\n        if(addAttempt.success) [[likely]] {\r\n            replacementDict.addSolid(addAttempt.solid);\r\n        }\r\n        return addAttempt;\r\n    }\r\n    [[nodiscard]] inline auto possiblyRemoveSolid(const Eigen::VectorXd& solidAmts, ReplacementDict& replacementDict, SolidSystem& solidSystem){\r\n        const auto removeAttempt=solidSystem.getSolidToRemove(solidAmts);\r\n        if(removeAttempt.success) [[unlikely]] {\r\n            replacementDict.removeSolid(removeAttempt.solid);\r\n        }\r\n        return removeAttempt;\r\n    }\r\n\r\n    inline constexpr double GUESS_TOTALS_FACTOR=1e-5;\r\n\r\n    inline constexpr double MAX_PERCENT_ERROR_ADDEND=1e-5;\r\n\r\n    inline constexpr std::size_t MAX_ITER=30;\r\n\r\n    inline constexpr double STEP_WHEN_NEGATIVE=0.9;\r\n\r\n    [[nodiscard]] std::pair<Eigen::RowVectorXd, Eigen::VectorXd> inline solveWithReplacement(const TableauWithTotals<>& replacedTableau) {\r\n        \r\n        Eigen::RowVectorXd currentSolution=Eigen::RowVectorXd::Constant(replacedTableau.cols(), GUESS_TOTALS_FACTOR);\r\n        for(std::size_t iter=0; iter<MAX_ITER; ++iter){\r\n            Eigen::VectorXd speciesConcentrations=replacedTableau.evalTerms(currentSolution);\r\n\r\n            const Eigen::MatrixXd addends=replacedTableau.evalAddends(speciesConcentrations);\r\n\r\n            const Eigen::RowVectorXd maxAddend=abs(addends.array()).colwise().maxCoeff();\r\n\r\n            //x^c*c/x=(x^c)'\r\n            const Eigen::MatrixXd jacobian=addends.transpose()*(replacedTableau.getCoefficients().array().rowwise()/currentSolution.array()).matrix();\r\n\r\n            const Eigen::RowVectorXd yResult=replacedTableau.eval(addends);\r\n\r\n            if(abs(yResult.array()/maxAddend.array()).maxCoeff()<MAX_PERCENT_ERROR_ADDEND) [[unlikely]] {\r\n                return std::make_pair(std::move(currentSolution), std::move(speciesConcentrations));\r\n            }\r\n\r\n            Eigen::RowVectorXd delta=jacobian.partialPivLu().solve(yResult.transpose()).transpose();\r\n\r\n            //don't go into the negatives, instead divide by 10\r\n            delta=(delta.array()<currentSolution.array()).select(delta, currentSolution*STEP_WHEN_NEGATIVE);\r\n            \r\n\r\n            currentSolution-=delta;\r\n        }\r\n        throw std::runtime_error(\"Failed to converge\");\r\n    }\r\n\r\n    inline auto solveForEquilibrium(const TableauWithTotals<>& tableau, const SolidSystem& initialSolidSystem, const ReplacementDict& origReplacementDict){\r\n        Eigen::RowVectorXd currentSolution;\r\n        Eigen::VectorXd speciesConcentrations;\r\n        Eigen::VectorXd solubilityProducts;\r\n        Eigen::VectorXd solidAmts;\r\n\r\n        ReplacementDict replacementDict{origReplacementDict};\r\n        SolidSystem solidSystem=initialSolidSystem.createNewWithInitialConditions();\r\n        replacementDict.addSolidSystem(solidSystem);\r\n\r\n\r\n        for(;;){\r\n            const auto currentReplacedTableau=replacementDict.createReplacedTableau(tableau);\r\n            if(currentReplacedTableau.cols()!=0){\r\n                std::tie(currentSolution, speciesConcentrations)=solveWithReplacement(currentReplacedTableau);\r\n            } else {\r\n                currentSolution=Eigen::RowVectorXd(0);\r\n                speciesConcentrations=currentReplacedTableau.getConstants();\r\n            }\r\n            solubilityProducts=solidSystem.calculateSolubilityProducts(currentSolution, replacementDict);\r\n\r\n            solidAmts=solidSystem.calculateSolidAmts(-tableau.eval(speciesConcentrations)); \r\n\r\n            SolidSystem::SolidChangeAttempt removalAttempt=possiblyRemoveSolid(solidAmts, replacementDict, solidSystem);\r\n            if(removalAttempt.success) {\r\n                continue;\r\n            }\r\n            SolidSystem::SolidChangeAttempt addAttempt=possiblyAddSolid(solubilityProducts, replacementDict, solidSystem);\r\n            if(addAttempt.success) {\r\n                continue;\r\n            }\r\n\r\n            \r\n            //there used to be a huge piece of code to try and switch two solids (remove one and add another within a single iteration). It was a mess, huge, and didn't really help recovery        \r\n            if(removalAttempt.solid!=nullptr){\r\n                //we've looped, and the adding didn't help\r\n                throw std::runtime_error(\"failed to recover from loop. You may have to provide an initial guess for which solids are present.\");\r\n            }\r\n            if(addAttempt.solid!=nullptr){\r\n                //we've looped while trying to add.\r\n                throw std::runtime_error(\"failed to recover from loop. You may have to provide an initial guess for which solids are present.\");\r\n            }\r\n            break;\r\n        }\r\n        return Equilibrium{\r\n            tableau,\r\n            std::move(replacementDict), std::move(currentSolution), std::move(speciesConcentrations),\r\n            std::move(solidSystem), solidAmts, solubilityProducts\r\n        };\r\n    }\r\n} // namespace AQSystemSolver", "meta": {"hexsha": "46d803e13131df85eabef48080a172ecb5196807", "size": 5497, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AQSystemSolver.hpp", "max_stars_repo_name": "FreeQL/AQSystemSolver", "max_stars_repo_head_hexsha": "3d98837d7cac9c5c0da57ed896a3145ed0c49a97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AQSystemSolver.hpp", "max_issues_repo_name": "FreeQL/AQSystemSolver", "max_issues_repo_head_hexsha": "3d98837d7cac9c5c0da57ed896a3145ed0c49a97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AQSystemSolver.hpp", "max_forks_repo_name": "FreeQL/AQSystemSolver", "max_forks_repo_head_hexsha": "3d98837d7cac9c5c0da57ed896a3145ed0c49a97", "max_forks_repo_licenses": ["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.3306451613, "max_line_length": 198, "alphanum_fraction": 0.6665453884, "num_tokens": 1130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5101609084085845}}
{"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_ATAND_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ATAND_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing atand capabilities\n\n    inverse tangent in degree.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = atand(x);\n    @endcode\n\n    Returns the arc @c r in the interval\n    \\f$[-90, 90[\\f$ such that <tt>tand(r) == x</tt>.\n\n    @see atan2d, atan2, atan, atanpi, tand\n\n  **/\n  Value atand(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/atand.hpp>\n#include <boost/simd/function/simd/atand.hpp>\n\n#endif\n", "meta": {"hexsha": "627d71494429a154343133c3af26554a3dbe5992", "size": 1074, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/atand.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/atand.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/atand.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": 22.8510638298, "max_line_length": 100, "alphanum_fraction": 0.5716945996, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5101609084085845}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\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__FEEDBACK__MPC_FUNC_HPP_\n#define SMOOTH__FEEDBACK__MPC_FUNC_HPP_\n\n/**\n * @file\n * @brief Functions for Model-Predictive Control (MPC) on Lie groups.\n */\n\n#include <Eigen/Core>\n\n#include <cassert>\n#include <chrono>\n#include <smooth/diff.hpp>\n#include <smooth/lie_group.hpp>\n\n#include \"common.hpp\"\n#include \"qp.hpp\"\n\nnamespace smooth::feedback {\n\n/**\n * @brief Optimal control problem defintiion.\n *\n * @tparam G State space Lie group.\n * @tparam U Input space Lie group.\n *\n * The optimal control problem is\n * \\f[\n *   \\begin{cases}\n *    \\min_{u(\\cdot)} & \\int_{0}^T \\left( (g(t) \\ominus g_{des}(t))^T Q (g(t) \\ominus g_{des}(t))^T\n *     + (u(t) \\ominus u_{des}(t))^T R (u(t) \\ominus u_{des}(t))^T \\right)\n *     + (g(T) \\ominus g_{des}(T))^T Q_T (g(T) \\ominus g_{des}(T))               \\\\\n *    \\text{s.t.}    & g(0) = x_0,                                               \\\\\n *                    & l_G \\leq A_G (g(t) \\ominus c_G) \\leq u_G,                \\\\\n *                    & l_U \\leq A_U (u(t) \\ominus c_U) \\leq u_U,\n *   \\end{cases}\n * \\f]\n * where the cost matrices must be positive semi-definite.\n */\ntemplate<LieGroup G, Manifold U>\nstruct OptimalControlProblem\n{\n  /// State tangent dimension\n  static constexpr Eigen::Index Nx = Dof<G>;\n  /// Input tangent dimension\n  static constexpr Eigen::Index Nu = Dof<U>;\n\n  /// Time horizon\n  double T{1};\n  /// Initial state\n  G x0{Default<G>()};\n\n  /// Desired input trajectory\n  std::function<U(double)> udes = [](double) -> U { return Default<U>(); };\n  /// Desired state trajectory\n  std::function<G(double)> gdes = [](double) -> G { return Default<G>(); };\n\n  /// Input bounds\n  ManifoldBounds<U> ulim{};\n  /// State bounds\n  ManifoldBounds<G> glim{};\n\n  /// MPC weights struct\n  struct Weights\n  {\n    /// Running state cost\n    Eigen::Matrix<double, Nx, Nx> Q = Eigen::Matrix<double, Nx, Nx>::Identity();\n    /// Final state cost\n    Eigen::Matrix<double, Nx, Nx> QT = Eigen::Matrix<double, Nx, Nx>::Identity();\n    /// Running input cost\n    Eigen::Matrix<double, Nu, Nu> R = Eigen::Matrix<double, Nu, Nu>::Identity();\n  };\n\n  /// MPC weights values\n  Weights weights{};\n};\n\n/**\n * @brief Struct to define a linearization point.\n */\ntemplate<LieGroup G, Manifold U>\nstruct LinearizationInfo\n{\n  /**\n   * @brief state linearization trajectory with first derivative\n   * \\f$ g_{lin}: \\mathbb{R} \\rightarrow (G, \\mathbb{R}^{\\dim \\mathfrak{g}}) \\f$\n   */\n  std::function<std::pair<G, Tangent<G>>(double)> g = [](double) -> std::pair<G, Tangent<G>> {\n    return {Default<G>(), Tangent<G>::Zero()};\n  };\n\n  /**\n   * @brief input linearization trajectory \\f$ u_{lin}(t) :  \\mathbb{R} \\rightarrow U \\f$\n   */\n  std::function<U(double)> u = [](double) -> U { return Default<U>(); };\n\n  /**\n   * @brief Domain of validity of state linearization\n   *\n   *  Defines an upper bound \\f$ \\bar a \\f$ s.t. the linearization is valid for \\f$ g \\f$ s.t.\n   * \\f[\n   *   -\\bar a \\leq g \\ominus_r g_{lin} \\leq \\bar a\n   * \\f]\n   * holds component-wise.\n   */\n  Eigen::Matrix<double, Dof<G>, 1> g_domain =\n    Eigen::Matrix<double, Dof<G>, 1>::Constant(std::numeric_limits<double>::infinity());\n};\n\n/**\n * @brief Allocate QP sparsity pattern (part 1 of ocp_to_qp()).\n *\n * Variables: [x_1, ..., x_K, u_0, ..., u_{K-1}]\n *\n * Constraints:\n *  - Dynamics constraints            (K * Nx)\n *  - Input constraints               (Nu_ineq * Nu)\n *  - State constraints               (Nx_ineq * Nx)\n *  - State linearization constraints (K * Nu)        [optional]\n *\n * @param[in] pbm OptimalControlProblem definition.\n * @param[in] K number of time discretization steps\n * @param[out] qp quadratic program definition with allocated matrices.\n * @param[in] lin_con set to true to allocate K * Nu state linearization constraints\n */\ntemplate<LieGroup G, Manifold U>\n  requires(Dof<G> > 0 && Dof<U> > 0)\nvoid ocp_to_qp_allocate(\n  const OptimalControlProblem<G, U> & pbm,\n  std::size_t K,\n  QuadraticProgramSparse<double> & qp,\n  bool lin_con = false)\n{\n  // problem info\n  static constexpr int Nx = Dof<G>;\n  static constexpr int Nu = Dof<U>;\n\n  static_assert(Nx > 0, \"State space dimension must be static\");\n  static_assert(Nu > 0, \"Input space dimension must be static\");\n\n  const uint32_t n_eq     = K * Nx;\n  const uint32_t NU_iq    = K * pbm.ulim.A.rows();\n  const uint32_t NX_iq    = K * pbm.glim.A.rows();\n  const uint32_t NXLIN_iq = lin_con ? K * Nu : 0;\n\n  const uint32_t nvar = K * Nx + K * Nu;\n  const uint32_t ncon = n_eq + NU_iq + NX_iq + NXLIN_iq;\n\n  // Matrix sizes\n  qp.P.resize(nvar, nvar);\n  qp.q.resize(nvar);\n\n  qp.A.resize(ncon, nvar);\n  qp.l.resize(ncon);\n  qp.u.resize(ncon);\n\n  // SPARSITY PATTERN FOR P\n\n  Eigen::Matrix<int, -1, 1> Pp(nvar);\n  for (auto k = 0u; k != K; ++k) {\n    for (auto i = 0u; i != Nu; ++i) { Pp[k * Nu + i] = 1 + i; }\n  }\n\n  for (auto k = 0u; k != K; ++k) {\n    for (auto i = 0u; i != Nx; ++i) { Pp[K * Nu + k * Nx + i] = 1 + i; }\n  }\n\n  // SPARSITY PATTERN FOR A\n\n  Eigen::Matrix<int, -1, 1> Ap(ncon);\n  int Arow = 0;\n\n  // state constraint k = 0\n  Ap.segment(Arow, Nx).setConstant(1 + Nu);\n  Arow += Nx;\n\n  // state constraints k = 1, ... K\n  Ap.segment(Arow, (K - 1) * Nx).setConstant(1 + Nu + Nx);\n  Arow += (K - 1) * Nx;\n\n  // input constraints\n  if (NU_iq > 0) { Ap.segment(Arow, NU_iq).setConstant(Nu); }\n  Arow += NU_iq;\n\n  // state constraints\n  if (NX_iq > 0) { Ap.segment(Arow, NX_iq).setConstant(Nx); }\n  Arow += NX_iq;\n\n  // state linearization constraints\n  if (NXLIN_iq > 0) { Ap.segment(Arow, NXLIN_iq).setConstant(1); }\n\n  qp.P.reserve(Pp);\n  qp.A.reserve(Ap);\n}\n\n/**\n * @brief Fill QP matrices (part 2 of ocp_to_qp()).\n */\ntemplate<LieGroup G, Manifold U, typename Dyn, diff::Type DT = diff::Type::Default>\n  requires(Dof<G> > 0 && Dof<U> > 0)\nvoid ocp_to_qp_fill(\n  const OptimalControlProblem<G, U> & pbm,\n  std::size_t K,\n  const Dyn & f,\n  const LinearizationInfo<G, U> & lin,\n  QuadraticProgramSparse<double> & qp)\n{\n  using std::placeholders::_1;\n\n  static constexpr int Nx = Dof<G>;\n  static constexpr int Nu = Dof<U>;\n  const int NU            = K * Nu;\n\n  static_assert(Nx > 0, \"State space dimension must be static\");\n  static_assert(Nu > 0, \"Input space dimension must be static\");\n\n  const bool lin_con = lin.g_domain.minCoeff() < std::numeric_limits<double>::infinity();\n\n  const uint32_t Nu_iq    = pbm.ulim.A.rows();\n  const uint32_t Nx_iq    = pbm.glim.A.rows();\n  const uint32_t Nxlin_iq = lin_con ? Nx : 0;\n\n  const double dt = pbm.T / static_cast<double>(K);\n\n  ////////////////////\n  /// FILL A, l, u ///\n  ////////////////////\n\n  assert(static_cast<uint32_t>(qp.A.rows()) == K * (Nx + Nu_iq + Nx_iq + Nxlin_iq));\n  assert(static_cast<uint32_t>(qp.A.cols()) == K * (Nx + Nu));\n  assert(static_cast<uint32_t>(qp.l.rows()) == K * (Nx + Nu_iq + Nx_iq + Nxlin_iq));\n  assert(static_cast<uint32_t>(qp.u.rows()) == K * (Nx + Nu_iq + Nx_iq + Nxlin_iq));\n\n  int Arow = 0;\n\n  for (auto k = 0u; k != K; ++k) {\n    using AT = Eigen::Matrix<double, Nx, Nx>;\n    using BT = Eigen::Matrix<double, Nx, Nu>;\n    using ET = Eigen::Matrix<double, Nx, 1>;\n\n    const double t = k * dt;\n\n    // LINEARIZATION\n\n    const auto [xl, dxl] = lin.g(t);\n    const auto ul        = lin.u(t);\n\n    // clang-format off\n    const auto [flin, df_xu] = diff::dr<1, DT>(\n      [&f, &t]<typename T>(const CastT<T, G> & vx, const CastT<T, U> & vu) -> Tangent<CastT<T, G>> {\n        return f(t, vx, vu);\n      },\n      wrt(xl, ul)\n    );\n    // clang-format on\n\n    // cltv system \\dot x = At x(t) + Bt u(t) + Et\n    const AT At = -0.5 * ad<G>(flin) - 0.5 * ad<G>(dxl) + df_xu.template leftCols<Nx>();\n    const BT Bt = df_xu.template rightCols<Nu>();\n    const ET Et = flin - dxl;\n\n    // TIME DISCRETIZATION\n\n    const AT At2     = At * At;\n    const double dt2 = dt * dt;\n    const double dt3 = dt2 * dt;\n\n    // dltv system x^+ = Ak x + Bk u + Ek by truncated taylor expansion of the matrix exponential\n    const AT Ak = AT::Identity() + At * dt + At2 * dt2 / 2. + At2 * At * dt3 / 6.;\n    const BT Bk = Bt * dt + At * Bt * dt2 / 2. + At2 * Bt * dt3 / 6.;\n    const ET Ek = Et * dt + At * Et * dt2 / 2. + At2 * Et * dt3 / 6.;\n\n    // DYNAMICS CONSTRANTS\n\n    if (k == 0) {\n      // x(1) - B u(0) = A x0 + E\n\n      // identity matrix on x(1)\n      for (auto i = 0u; i != Nx; ++i) {\n        const Eigen::Index Ari = Nx * k + i;\n        assert(qp.A.outerIndexPtr()[Ari + 1] - qp.A.outerIndexPtr()[Ari] == Nu + 1);\n\n        // B matrix on u0\n        for (auto j = 0u; j != Nu; ++j) { qp.A.coeffRef(Ari, Nu * k + j) = -Bk(i, j); }\n\n        // Identity matrix on x1\n        qp.A.coeffRef(Ari, NU + Nx * k + i) = 1;\n      }\n\n      // B matrix on u(0)\n      for (auto i = 0u; i != Nx; ++i) {}\n\n      qp.u.template segment<Nx>(Nx * k) = Ak * rminus(pbm.x0, xl) + Ek;\n      qp.l.template segment<Nx>(Nx * k) = qp.u.template segment<Nx>(Nx * k);\n    } else {\n      // x(k+1) - A x(k) - B u(k) = E\n      for (auto i = 0u; i != Nx; ++i) {\n        const Eigen::Index Ari = Nx * k + i;\n        assert(qp.A.outerIndexPtr()[Ari + 1] - qp.A.outerIndexPtr()[Ari] == Nu + Nx + 1);\n\n        // B matrix on u(k)\n        for (auto j = 0u; j != Nu; ++j) { qp.A.coeffRef(Ari, Nu * k + j) = -Bk(i, j); }\n\n        // A matrix on x(k)\n        for (auto j = 0u; j != Nx; ++j) { qp.A.coeffRef(Ari, NU + Nx * (k - 1) + j) = -Ak(i, j); }\n\n        // identity matrix on x(k+1)\n        qp.A.coeffRef(Ari, NU + Nx * k + i) = 1;\n      }\n\n      qp.u.template segment<Nx>(Nx * k) = Ek;\n      qp.l.template segment<Nx>(Nx * k) = Ek;\n    }\n  }\n  Arow += K * Nx;\n\n  // INPUT CONSTRAINTS\n\n  if (Nu_iq > 0) {\n    for (auto k = 0u; k < K; ++k) {\n      for (auto i = 0u; i != Nu_iq; ++i) {\n        const Eigen::Index Ari = Arow + k * Nu_iq + i;\n        assert(qp.A.outerIndexPtr()[Ari + 1] - qp.A.outerIndexPtr()[Ari] == Nu);\n\n        for (auto j = 0u; j != Nu; ++j) { qp.A.coeffRef(Ari, k * Nu + j) = pbm.ulim.A(i, j); }\n      }\n      // clang-format off\n      qp.l.segment(Arow + k * Nu_iq, Nu_iq) = pbm.ulim.l - pbm.ulim.A * rminus(lin.u(k * dt), pbm.ulim.c);\n      qp.u.segment(Arow + k * Nu_iq, Nu_iq) = pbm.ulim.u - pbm.ulim.A * rminus(lin.u(k * dt), pbm.ulim.c);\n      // clang-format on\n    }\n  }\n  Arow += K * Nu_iq;\n\n  // STATE CONSTRAINTS\n\n  if (Nx_iq > 0) {\n    for (auto k = 1u; k != K + 1; ++k) {\n      for (auto i = 0u; i != Nx_iq; ++i) {\n        const Eigen::Index Ari = Arow + (k - 1) * Nx_iq + i;\n        assert(qp.A.outerIndexPtr()[Ari + 1] - qp.A.outerIndexPtr()[Ari] == Nx);\n\n        for (auto j = 0u; j != Nx; ++j) {\n          qp.A.coeffRef(Ari, NU + (k - 1) * Nx + j) = pbm.glim.A(i, j);\n        }\n      }\n      // clang-format off\n      qp.l.segment(Arow + (k - 1) * Nx_iq, Nx_iq) = pbm.glim.l - pbm.glim.A * rminus(lin.g(k * dt).first, pbm.glim.c);\n      qp.u.segment(Arow + (k - 1) * Nx_iq, Nx_iq) = pbm.glim.u - pbm.glim.A * rminus(lin.g(k * dt).first, pbm.glim.c);\n      // clang-format on\n    }\n  }\n  Arow += K * Nx_iq;\n\n  // STATE LINEARIZATION BOUNDS\n\n  if (Nxlin_iq > 0) {\n    for (auto k = 1u; k < K + 1; ++k) {\n      for (auto i = 0u; i != Nxlin_iq; ++i) {\n        const Eigen::Index Ari = Arow + (k - 1) * Nxlin_iq + i;\n        assert(qp.A.outerIndexPtr()[Ari + 1] - qp.A.outerIndexPtr()[Ari] == 1);\n\n        qp.A.coeffRef(Ari, NU + (k - 1) * Nx + i) = 1.;\n      }\n      qp.l.segment(Arow + (k - 1) * Nxlin_iq, Nxlin_iq) = -lin.g_domain;\n      qp.u.segment(Arow + (k - 1) * Nxlin_iq, Nxlin_iq) = lin.g_domain;\n    }\n  }\n  Arow += K * Nxlin_iq;\n\n  ////////////////\n  /// FILL P,q ///\n  ////////////////\n\n  assert(static_cast<uint32_t>(qp.P.cols()) == K * (Nx + Nu));\n  assert(static_cast<uint32_t>(qp.P.cols()) == K * (Nx + Nu));\n  assert(static_cast<uint32_t>(qp.q.rows()) == K * (Nx + Nu));\n\n  // INPUT COSTS\n\n  for (auto k = 0u; k < K; ++k) {\n    for (auto i = 0u; i != Nu; ++i) {\n      const Eigen::Index Pci = k * Nu + i;\n      assert(\n        qp.P.outerIndexPtr()[Pci + 1] - qp.P.outerIndexPtr()[Pci]\n        == static_cast<decltype(qp.P)::StorageIndex>(i) + 1);\n\n      for (auto j = 0u; j != i + 1; ++j) {\n        qp.P.coeffRef(k * Nu + j, Pci) = pbm.weights.R(j, i) * dt;\n      }\n    }\n    qp.q.segment(k * Nu, Nu) = pbm.weights.R * rminus(lin.u(k * dt), pbm.udes(k * dt)) * dt;\n  }\n\n  // STATE COSTS\n\n  // intermediate states x(1) ... x(K-1)\n  for (auto k = 1u; k < K; ++k) {\n    for (auto i = 0u; i != Nx; ++i) {\n      const Eigen::Index Pci = NU + (k - 1) * Nx + i;\n      assert(\n        qp.P.outerIndexPtr()[Pci + 1] - qp.P.outerIndexPtr()[Pci]\n        == static_cast<decltype(qp.P)::StorageIndex>(i) + 1);\n\n      for (auto j = 0u; j != i + 1; ++j) {\n        qp.P.coeffRef(NU + (k - 1) * Nx + j, Pci) = pbm.weights.Q(j, i) * dt;\n      }\n    }\n    qp.q.segment(NU + (k - 1) * Nx, Nx) =\n      pbm.weights.Q * rminus(lin.g(k * dt).first, pbm.gdes(k * dt)) * dt;\n  }\n\n  // last state x(K) ~ x(T)\n  for (auto i = 0u; i != Nx; ++i) {\n    const Eigen::Index Pci = NU + (K - 1) * Nx + i;\n    assert(\n      qp.P.outerIndexPtr()[Pci + 1] - qp.P.outerIndexPtr()[Pci]\n      == static_cast<decltype(qp.P)::StorageIndex>(i) + 1);\n\n    for (auto j = 0u; j != i + 1; ++j) {\n      qp.P.coeffRef(NU + (K - 1) * Nx + j, Pci) = pbm.weights.QT(j, i);\n    }\n  }\n  qp.q.segment(NU + (K - 1) * Nx, Nx) =\n    pbm.weights.QT * rminus(lin.g(pbm.T).first, pbm.gdes(pbm.T));\n\n  qp.A.makeCompressed();\n  qp.P.makeCompressed();\n}\n\n/**\n * @brief Convert OptimalControlProblem on \\f$ (\\mathbb{G}, \\mathbb{U}) \\f$ into a tangent space\n * QuadraticProgramSparse on \\f$ (\\mathbb{R}^{\\dim \\mathfrak{g}}, \\mathbb{R}^{\\dim \\mathfrak{u}})\n * \\f$.\n *\n * The OptimalControlProblem is encoded into a QuadraticProgram via linearization around\n * \\f$(g_{lin}(t), u_{lin}(t))\\f$ followed by time discretization. The variables of the QP are \\f[\n * \\begin{bmatrix} \\mu_0 & \\mu_1 & \\ldots & \\mu_{K - 1} & x_1 & x_2 & \\ldots & x_K\n * \\end{bmatrix}, \\f] where the discrete time index \\f$k\\f$ corresponds to time \\f$t_k = k\n * \\frac{T}{K} \\f$ for \\f$ k = 0, 1, \\ldots, K \\f$.\n *\n * performance.\n * @tparam G problem state group type \\f$ \\mathbb{G} \\f$\n * @tparam U problem input group type \\f$ \\mathbb{U} \\f$\n * @tparam Dyn dynamics functor type\n * @tparam DT differentiation method to utilize\n *\n * @param pbm optimal control problem\n * @param K number of discretization points. More points create a larger QP, but the distance \\f$\n * T / K \\f$ between points should be smaller than the smallest system time constant for adequate\n * @param f dynamics \\f$ f : \\mathbb{R} \\times \\mathbb{G} \\times \\mathbb{U} \\rightarrow\n * \\mathbb{R}^{\\dim \\mathfrak g}\\f$ s.t. \\f$ \\mathrm{d}^r g_t = f(t, g, u) \\f$\n * @param lin linearization point\n *\n * @return QuadraticProgramSparse modeling the input optimal control problem.\n *\n * @note Given a solution \\f$(x^*, \\mu^*)\\f$ to the QuadraticProgramSparse, the corresponding\n * solution to the OptimalControlProblem is \\f$ u^*(t) = u_{lin}(t) \\oplus \\mu^*(t) \\f$ and the\n * optimal trajectory is \\f$ g^*(t) = g_{lin}(t) \\oplus x^*(t) \\f$.\n *\n * @note Constraints are added as \\f$ A x \\leq b - A (g_{lin} - c) \\f$ and similarly for the\n * input. Beware of using constraints on non-Euclidean spaces.\n *\n * @note \\p f must be differentiable w.r.t. \\f$ g \\f$ and \\f$ u \\f$  with the default \\p\n * smooth::diff method (check \\p smooth::diff::DefaultType). If using an automatic differentiation\n * method this means that it must be templated on the scalar type.\n */\ntemplate<LieGroup G, Manifold U, typename Dyn, diff::Type DT = diff::Type::Default>\nQuadraticProgramSparse<double> ocp_to_qp(\n  const OptimalControlProblem<G, U> & pbm,\n  std::size_t K,\n  const Dyn & f,\n  const LinearizationInfo<G, U> & lin)\n{\n  bool lin_con = lin.g_domain.minCoeff() < std::numeric_limits<double>::infinity();\n\n  QuadraticProgramSparse<double> qp;\n\n  ocp_to_qp_allocate<G, U>(pbm, K, qp, lin_con);\n  ocp_to_qp_fill<G, U>(pbm, K, f, lin, qp);\n\n  return qp;\n}\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__MPC_FUNC_HPP_\n", "meta": {"hexsha": "ee8ae2bb796a5920ddb081b1270a50aadab9e3c5", "size": 17185, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/mpc_func.hpp", "max_stars_repo_name": "pettni/smooth_feedback", "max_stars_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "include/smooth/feedback/mpc_func.hpp", "max_issues_repo_name": "pettni/smooth_feedback", "max_issues_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "include/smooth/feedback/mpc_func.hpp", "max_forks_repo_name": "pettni/smooth_feedback", "max_forks_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T15:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:23:18.000Z", "avg_line_length": 33.4990253411, "max_line_length": 118, "alphanum_fraction": 0.5830666279, "num_tokens": 5784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5101609030708298}}
{"text": "#include \"FloatingObject.hpp\"\n#include <algorithm>\n#include <vector>\n#include <mutex>\n#include <shared_mutex>\n#include <Eigen\\Geometry>\n\n#define NOMINMAX\n#include <Windows.h>\n\nnamespace {\n\tconst float pi = 3.14159265359;\n\tconstexpr float AIR_DENSITY = 1.293e-9; // [kg/mm3]\n}\n\nnamespace dynaman {\n\tFloatingObject::FloatingObject(\n\t\tconst Eigen::Vector3f& positionTarget,\n\t\tconst Eigen::Vector3f& lowerbound,\n\t\tconst Eigen::Vector3f& upperbound,\n\t\tfloat radius,\n\t\tfloat weight\n\t):\n\t\tm_position(positionTarget),\n\t\tm_velocity(Eigen::Vector3f::Zero()),\n\t\tm_integral(Eigen::Vector3f::Zero()),\n\t\tm_lowerbound(lowerbound),\n\t\tm_upperbound(upperbound),\n\t\tm_weight(weight),\n\t\tm_radius(radius),\n\t\tm_is_tracked(false),\n\t\tm_lastDeterminationTime(0),\n\t\tvelocityBufferSize(3),\n\t\tpositionBuffer(velocityBufferSize, positionTarget),\n\t\tvelocityBuffer(velocityBufferSize, Eigen::Vector3f::Zero()),\n\t\tdTBuffer(velocityBufferSize, 1),\n\t\tm_pTrajectory(std::make_shared<TrajectoryConstantState>(positionTarget)\n\t\t)\n\t{}\n\n\tFloatingObjectPtr FloatingObject::Create(\n\t\tconst Eigen::Vector3f& posTgt,\n\t\tconst Eigen::Vector3f& lowerbound,\n\t\tconst Eigen::Vector3f& upperbound,\n\t\tfloat radius,\n\t\tfloat weight\n\t){\n\t\treturn std::make_shared<FloatingObject>(posTgt, lowerbound, upperbound, radius, weight);\n\t}\n\n\tfloat FloatingObject::sphereMass()\n\t{\n\t\treturn AIR_DENSITY * 4.0f * pi * m_radius * m_radius * m_radius / 3.0f;\n\t}\n\n\tfloat FloatingObject::radius() {\n\t\treturn m_radius;\n\t}\n\n\tfloat FloatingObject::weight()\n\t{\n\t\treturn m_weight;\n\t}\n\n\tfloat FloatingObject::totalMass()\n\t{\n\t\treturn sphereMass() + weight();\n\t}\n\n\tDWORD FloatingObject::lastDeterminationTime() {\n\t\tstd::lock_guard<std::mutex> lock(mtxState);\n\t\treturn m_lastDeterminationTime;\n\t}\n\n\tEigen::Vector3f FloatingObject::position()\n\t{\n\t\tstd::lock_guard<std::mutex> lock(mtxState);\n\t\treturn m_position;\n\t}\n\n\tEigen::Vector3f FloatingObject::velocity()\n\t{\n\t\tstd::lock_guard<std::mutex> lock(mtxState);\n\t\treturn averageVelocity(this->velocityBuffer, this->dTBuffer);\n\t}\n\n\tEigen::Vector3f FloatingObject::integral()\n\t{\n\t\tstd::lock_guard<std::mutex> lock(mtxState);\n\t\treturn m_integral;\n\t}\n\n\tEigen::Vector3f FloatingObject::positionTarget(DWORD systime_ms)\n\t{\n\t\tstd::shared_lock<std::shared_mutex> lock(mtxTrajectory);\n\t\treturn m_pTrajectory->pos(systime_ms);\n\t}\n\n\tEigen::Vector3f FloatingObject::velocityTarget(DWORD systime_ms)\n\t{\n\t\tstd::shared_lock<std::shared_mutex> lock(mtxTrajectory);\n\t\treturn m_pTrajectory->vel(systime_ms);\n\t}\n\n\tEigen::Vector3f FloatingObject::accelTarget(DWORD systime_ms)\n\t{\n\t\tstd::shared_lock<std::shared_mutex> lock(mtxTrajectory);\n\t\treturn m_pTrajectory->accel(systime_ms);\n\t}\n\n\tvoid FloatingObject::getStates(\n\t\tEigen::Vector3f& pos,\n\t\tEigen::Vector3f& vel,\n\t\tEigen::Vector3f& integ\n\t) {\n\t\tstd::lock_guard<std::mutex> lock(mtxState);\n\t\tpos = m_position;\n\t\tvel = averageVelocity(this->velocityBuffer, this->dTBuffer);\n\t\tinteg = m_integral;\n\t}\n\n\tvoid FloatingObject::updateStates(DWORD determinationTime, const Eigen::Vector3f& positionNew)\n\t{\n\t\tstd::lock_guard<std::mutex> lock(mtxState);\n\t\tfloat dt = (float)(determinationTime - m_lastDeterminationTime) / 1000.f; // [sec]\n\t\tm_velocity = (positionNew - m_position) / dt;\n\t\tdTBuffer.push_back(dt);\n\t\tdTBuffer.pop_front();\n\t\tpositionBuffer.push_back(positionNew);\n\t\tpositionBuffer.pop_front();\n\t\tvelocityBuffer.push_back(m_velocity);\n\t\tvelocityBuffer.pop_front();\n\t\tif (isTracked())\n\t\t{\n\t\t\tm_integral += (0.5f * (positionNew + m_position) - positionTarget()) * dt;\n\t\t}\n\t\tm_position = positionNew;\n\t\tm_lastDeterminationTime = determinationTime;\n\t}\n\n\tvoid FloatingObject::resetIntegral() {\n\t\tstd::lock_guard<std::mutex> lock(mtxState);\n\t\tm_integral.setZero();\n\t}\n\n\tvoid FloatingObject::getStatesTarget(\n\t\tEigen::Vector3f& posTgt,\n\t\tEigen::Vector3f& velTgt,\n\t\tEigen::Vector3f& accelTgt,\n\t\tDWORD time\n\t) {\n\t\tstd::lock_guard<std::shared_mutex> lock(mtxTrajectory);\n\t\tposTgt = m_pTrajectory->pos(time);\n\t\tvelTgt = m_pTrajectory->vel(time);\n\t\taccelTgt = m_pTrajectory->accel(time);\n\t}\n\n\tvoid FloatingObject::updateStatesTarget(\n\t\tconst Eigen::Vector3f& _positionTarget,\n\t\tconst Eigen::Vector3f& _velocityTarget,\n\t\tconst Eigen::Vector3f& _accelTarget)\n\t{\n\t\tauto constTrajPtr = TrajectoryConstantState::Create(_positionTarget, _velocityTarget, _accelTarget);\n\t\tsetTrajectory(constTrajPtr);\n\t}\n\n\tbool FloatingObject::isTracked() {\n\t\tstd::lock_guard<std::mutex> lock(mtxTrack);\n\t\treturn m_is_tracked;\n\t}\n\n\tvoid FloatingObject::setTrackingStatus(bool is_tracked) {\n\t\tstd::lock_guard<std::mutex> lock(mtxTrack);\n\t\tthis->m_is_tracked = is_tracked;\n\t}\n\n\tEigen::Vector3f FloatingObject::averageVelocity(\n\t\tstd::deque<Eigen::Vector3f> velocityBuffer,\n\t\tstd::deque<float> intervalBuffer\n\t) {\n\t\tauto itrVel = velocityBuffer.begin();\n\t\tauto itrDT = intervalBuffer.begin();\n\t\tEigen::Vector3f distSum(0.f, 0.f, 0.f);\n\t\tfloat period = 0;\n\t\twhile (itrVel != velocityBuffer.end())\n\t\t{\n\t\t\tdistSum += (*itrDT) * (*itrVel);\n\t\t\tperiod += *itrDT;\n\t\t\titrDT++;\n\t\t\titrVel++;\n\t\t}\n\t\treturn distSum /= period;\n\t}\n\n\tEigen::Vector3f FloatingObject::averagePosition() {\n\t\tEigen::Vector3f posAverage(0, 0, 0);\n\t\tstd::lock_guard<std::mutex> lock(mtxState);\n\t\tfor (auto itr = positionBuffer.begin(); itr != positionBuffer.end(); itr++) {\n\t\t\tposAverage += *itr;\n\t\t}\n\t\treturn posAverage / positionBuffer.size();\n\t}\n\n\n\tbool FloatingObject::isInsideWorkspace()\n\t{\n\t\tauto pos = position();\n\t\tEigen::Vector3f v0 = pos - lowerbound();\n\t\tEigen::Vector3f v1 = pos - upperbound();\n\t\treturn (v0.x() * v1.x() <= 0) && (v0.y() * v1.y() <= 0) && (v0.z() * v1.z() <= 0);\n\t}\n\n\tvoid FloatingObject::setTrajectory(std::shared_ptr<Trajectory> newTrajectoryPtr)\n\t{\n\t\tstd::lock_guard<std::shared_mutex> lock(mtxTrajectory);\n\t\tm_pTrajectory = newTrajectoryPtr;\n\t}\n\n\tEigen::Vector3f FloatingObject::lowerbound() {\n\t\treturn m_lowerbound;\n\t}\n\n\tEigen::Vector3f FloatingObject::upperbound() {\n\t\treturn m_upperbound;\n\t}\n\n\tstd::string FloatingObject::logCtrlHeader() const {\n\t\treturn \"sys_time,x,y,z,vx,vy,vz,ix,iy,iz,xTgt,yTgt,zTgt,vxTgt,vyTgt,vzTgt,axTgt,ayTgt,azTgt\";\n\t}\n\n\tstd::ofstream& operator<<(std::ostream& ofs, FloatingObjectPtr pObject) {\n\t\tDWORD time = pObject->lastDeterminationTime();\n\t\tEigen::Vector3f pos, vel, integ, posTgt, velTgt, accelTgt;\n\t\tpObject->getStates(pos, vel, integ);\n\t\tpObject->getStatesTarget(posTgt, velTgt, accelTgt, time);\n\t\tofs\n\t\t\t<< time << \",\"\n\t\t\t<< pos.x() << \",\" << pos.y() << \",\" << pos.z() << \",\"\n\t\t\t<< vel.x() << \",\" << vel.y() << \",\" << vel.z() << \",\"\n\t\t\t<< integ.x() << \",\" << integ.y() << \",\" << integ.z() << \",\"\n\t\t\t<< posTgt.x() << \",\" << posTgt.y() << \",\" << posTgt.z() << \",\"\n\t\t\t<< velTgt.x() << \",\" << velTgt.y() << \",\" << velTgt.z() << \",\"\n\t\t\t<< accelTgt.x() << \",\" << accelTgt.y() << \",\" << accelTgt.z();\n\t}\n}", "meta": {"hexsha": "862727228af4b9cd32fc0e6d10ce810618e043bb", "size": 6695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/FloatingObject.cpp", "max_stars_repo_name": "shinolab/dynamic-manipulation", "max_stars_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_stars_repo_licenses": ["MIT"], "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/FloatingObject.cpp", "max_issues_repo_name": "shinolab/dynamic-manipulation", "max_issues_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_issues_repo_licenses": ["MIT"], "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/FloatingObject.cpp", "max_forks_repo_name": "shinolab/dynamic-manipulation", "max_forks_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_forks_repo_licenses": ["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.3265306122, "max_line_length": 102, "alphanum_fraction": 0.6982823002, "num_tokens": 2001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5101608977330748}}
{"text": "#ifndef _CHEBSPEC_CPP_\n#define _CHEBSPEC_CPP_\n\n#include <armadillo>\n\n#include \"solvspec.cpp\"\n#include \"../include/chebspec.h\"\n\nusing namespace std;\nusing namespace arma;\n\nconst double PI = 3.141592653589793;\n\nint ChebSpec::N = -1;\nint ChebSpec::L = 0;\nvector<double> ChebSpec::x = vector<double>();\nvector<vector<double> > ChebSpec::Tm = vector<vector<double> >();\nvector<vector<double> > ChebSpec::TmInt = vector<vector<double> >();\nvector<vector<double> > ChebSpec::D = vector<vector<double> >();\nvector<vector<double> > ChebSpec::D2 = vector<vector<double> >();\n\nChebSpec::ChebSpec(){}\n\nvoid ChebSpec::setPotential(const vector<double> &XX, const vector<double> &VV) \n{\n  SolvSpec::setPotential(XX, VV);\n  a = XX[0];\n  b = XX[XX.size() - 1];\n  scal = pow((b - a) / 2, 2.0);\n}\n\nvoid ChebSpec::findSpectrum(int nEigen)\n{\n  if(PotVals.size() < 2) \n  {\n    cout << \"Please use the setPotential() function before using this one.\" << endl;\n    return;\n  }\n  // compute V\n  V.resize(L);\n  for(int i = 0; i < L; i++)\n  {\n    V[i] = scal * potFunc.interp(0.5 * ((b - a) * x[i] + b + a));\n  }\n  // compute Ehat\n  Ehat.resize(L);\n  for(int i = 0; i < L; i++) \n  {\n    Ehat[i].resize(L);\n    for(int j = 0; j < L; j++) \n    {\n      Ehat[i][j] = D2[i][j] * V[j];\n    }\n  }\n  // compute UE and US\n  UE.resize(L);\n  US.resize(L);\n  for(int i = 0; i < L; i++) \n  {\n    UE[i].resize(L);\n    US[i].resize(L);\n    for(int j = 0; j < L; j++)\n    {\n      UE[i][j] = 0.5 * (x[i] + 1) * D2[N][j];\n      US[i][j] = 0.5 * (x[i] + 1) * Ehat[N][j];\n    }\n  }\n  // compute the A and B matrices, remove the first/last row/column\n  int Nr = N - 1;\n  mat A(Nr, Nr);\n  mat B(Nr, Nr);\n\n  //lapack routines use the column-major order!\n  for(int i = 0; i < Nr; i++) \n  {\n    for(int j = 0; j < Nr; j++)\n    {\n      // define A\n      A(i, j) = -US[i + 1][j + 1] + Ehat[i + 1][j + 1];\n      if(i == j)   // add the identity matrix\n      {\n        A(i, j) = A[i + j * Nr] - 1;\n      }\n      // now B\n      B(i, j) = D2[i + 1][j + 1] - UE[i + 1][j + 1];\n    }\n  }\n\n  mat B1A = inv(B) * A;\n  cx_vec cxeigval;\n  cx_mat cxeigvec;\n\n  // diagonalize\n  eig_gen(cxeigval, cxeigvec, B1A);\n  mat eigvec = real(cxeigvec);\n  vec eigval = real(cxeigval);\n  // we need to sort this\n  for(int i = 0; i < Nr; i++)\n  {\n    for(int j = 0; j < Nr; j++)\n    {\n      if(eigval(i) < eigval(j)) \n      {\n        double temp = eigval(i);\n        eigval(i) = eigval(j);\n        eigval(j) = temp;\n        eigvec.swap_cols(i, j);\n      }\n    }\n  }\n  // now we just need to put everything in our internal format\n  // finally safelly add all the modes found to the spectrum (already in a nice way)\n  spectrum.clear();\n  spectrum.potential.push_back(X); spectrum.potential.push_back(PotVals);\n  for (int i = 0; i < nEigen; i++) \n  {\n    // build the wavefunction\n    vector<Point> wf;\n    for(int j = 0; j < Nr; j++)\n    {\n      wf.push_back(Point(0.5 * ((b - a) * x[j] + b + a), eigvec(j,i)));\n    }\n    // normalization loop\n    double c = 0;\n    for(int j = 0; j < Nr; j++)\n    {\n      c += D[N][j + 1] * wf[j].y * wf[j].y * 0.5 * (b - a);\n    }\n    // set all the wavefunctions start growing positive from the left\n    double s = 1;\n    // get the sign of the derivative, this is important since it may be the case\n    // that the routine return the same eigenvector with a different sign, in that case\n    // the overall coefficient we would like to fit would have change the sign\n    for(int j = 4; j < Nr; j++)\n    {\n      // filter the data and compute the derivative\n      double der = (25/12)*int(1e3 * wf[j].y)-4*int(1e3 * wf[j-1].y)+3*int(1e3 * wf[j-2].y)-(4/3) * int(1e3 * wf[j-3].y)+(1/4)* int(1e3 * wf[j-4].y);\n      der /= 1e3;\n      if(abs(der) > 1e-2) \n      {\n        s = der / abs(der);\n        break;\n      }\n    }\n    for(int j = 0; j < Nr; j++)\n    {\n      wf[j].y = s * wf[j].y / sqrt(c);\n    }\n    Mode m(eigval(i) / scal, wf);\n    spectrum.addMode(m);\n  }\n}\n\nvoid ChebSpec::showMatrix(double* A, int Nr)\n{\n  cout << endl;\n  for(int i = 0; i < Nr; i++) \n  {\n    for(int j = 0; j < Nr; j++) \n    {\n      cout << A[i + j * Nr] << \" \";\n    }\n    cout << endl;\n  }\n}\n\nChebSpec::~ChebSpec(){}\n\n// [[Rcpp::export]]\nvoid chebSetN(int n) \n{\n  if(ChebSpec::N == n)\n    return;\n  ChebSpec::N = n;\n  ChebSpec::L = n + 1;\n  cout << \"computing chebyshev matrices, N = \" << ChebSpec::N << endl;\n  // initialize x\n  ChebSpec::x.clear();\n  ChebSpec::x.resize(ChebSpec::L);\n  for(int i = 0; i < ChebSpec::L; i++)\n  {\n    ChebSpec::x[i] = -cos(PI * i / ChebSpec::N);\n  }\n  // Tm, the matrix of the Chebyshev polynomial values in the grid. Checked.\n  ChebSpec::Tm.clear();\n  ChebSpec::Tm.resize(ChebSpec::L);\n  for(int i = 0; i < ChebSpec::L; i++) \n  {\n    ChebSpec::Tm[i].resize(ChebSpec::L);\n    for(int j = 0; j < ChebSpec::L; j++) \n    {\n      if(i == 0)      // first\n      {  \n        ChebSpec::Tm[i][j] = 1;\n      }\n      else if(i == 1) // second\n      {\n        ChebSpec::Tm[i][j] = ChebSpec::x[j];\n      }\n      else\n      {\n        ChebSpec::Tm[i][j] = 2 * ChebSpec::x[j] * ChebSpec::Tm[i - 1][j] - ChebSpec::Tm[i - 2][j];\n      }\n    }\n  }\n\n  // TmIntInt, the matrix of the integrated from -1 Chebyshev polynomial values in the grid. Checked.\n  ChebSpec::TmInt.clear();\n  ChebSpec::TmInt.resize(ChebSpec::L);\n  for(int i = 0; i < ChebSpec::L; i++) \n  {\n    ChebSpec::TmInt[i].resize(ChebSpec::L);\n    for(int j = 0; j < ChebSpec::L; j++)\n    {\n      if(i == 0)      // first\n      {\n        ChebSpec::TmInt[i][j] = ChebSpec::x[j] + 1;\n      }\n      else if(i == 1) // second\n      {\n        ChebSpec::TmInt[i][j] =  0.5 * (ChebSpec::x[j] * ChebSpec::x[j] - 1);\n      }\n      else if(i < ChebSpec::L - 1)\n      {\n        ChebSpec::TmInt[i][j] = ChebSpec::Tm[i + 1][j] / (2. * (i + 1)) - ChebSpec::Tm[i - 1][j] / (2. * (i - 1)) + pow(-1, i + 1.) / (pow(i, 2.) - 1);\n      }\n      else   // case i = L - 1, right extreme\n      {\n        ChebSpec::TmInt[i][j] = (2 * ChebSpec::x[j] * ChebSpec::Tm[i][j] - ChebSpec::Tm[i - 1][j]) / (2.0 * (i + 1)) - ChebSpec::Tm[i - 1][j] / (2.0 * (i - 1)) + pow(-1, i + 1) / (pow(i, 2) - 1);\n      }\n    }\n  }\n\n  // D matrix: the integral from -1 to x. Checked.\n  ChebSpec::D.clear();\n  ChebSpec::D.resize(ChebSpec::L);\n  for(int i = 0; i < ChebSpec::L; i++) \n  {\n    ChebSpec::D[i].resize(ChebSpec::L);\n    for(int j = 0; j < ChebSpec::L; j++) \n    {\n      double s = 0;\n      for(int k = 0; k < ChebSpec::L; k++) \n      {\n        double f = 1;\n        if(k == 0 || k == ChebSpec::L - 1) // prime '' sum\n        {\n          f = 0.5;\n        }\n        s += f * ChebSpec::Tm[k][j] * ChebSpec::TmInt[k][i];\n      }\n\n      ChebSpec::D[i][j] = (2. / ChebSpec::N) * s;\n      // prime '' sum\n      if(j == 0 || j == ChebSpec::L - 1)\n        ChebSpec::D[i][j] = 0.5 * ChebSpec::D[i][j];\n    }\n  }\n  // finally the D2 = D*D matrix\n  // check, the sum of the last row has to be 2 and 0 the sum of the first\n  ChebSpec::D2.clear();\n  ChebSpec::D2.resize(ChebSpec::L);\n  for(int i = 0; i < ChebSpec::L; i++)\n  {\n    ChebSpec::D2[i].resize(ChebSpec::L);\n    for(int j = 0; j < ChebSpec::L; j++)\n    {\n      double s = 0;\n      for(int k = 0; k < ChebSpec::L; k++)\n      {\n        s += ChebSpec::D[i][k] * ChebSpec::D[k][j];\n      }\n      ChebSpec::D2[i][j] = s;\n    }\n  }\n\n  // check, the sum of the last row has to be 2\n  double s = 0;\n  for(int k = 0; k < ChebSpec::L; k++)\n  {\n    s += ChebSpec::D2[0][k];\n  }\n}\n\n;\n#endif", "meta": {"hexsha": "0c0024e28156af6672a9b59da4942e312f8717be", "size": 7395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/chebspec.cpp", "max_stars_repo_name": "artur-amorim/schrodinger", "max_stars_repo_head_hexsha": "a22b25e37a85d93e865d7d9c0d63f3b77bd78a0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chebspec.cpp", "max_issues_repo_name": "artur-amorim/schrodinger", "max_issues_repo_head_hexsha": "a22b25e37a85d93e865d7d9c0d63f3b77bd78a0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chebspec.cpp", "max_forks_repo_name": "artur-amorim/schrodinger", "max_forks_repo_head_hexsha": "a22b25e37a85d93e865d7d9c0d63f3b77bd78a0e", "max_forks_repo_licenses": ["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.8566433566, "max_line_length": 195, "alphanum_fraction": 0.5057471264, "num_tokens": 2815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82446190912407, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5101608977330747}}
{"text": "/** \n * @example ublas/test/vector_test.cc\n */\n#include <boost/test/unit_test.hpp>\n#include <usml/ublas/vector_math.h>\n#include <usml/ublas/test/vector_test_support.h>\n\nusing namespace usml::ublas;\nusing namespace vector_test;\n\nBOOST_AUTO_TEST_SUITE(vector_test)\n\n/**\n * @ingroup ublas_test\n * @{\n */\n\n/**\n * Run a real valued vector through the standard math routines.  Tests include:\n *\n *  - addition of vector to itself\n *  - add scalar to vector\n *  - subtract vector from scalar\n *  - divide scalar by vector\n *  - limiting functions: min, max, floor, and ceil\n *  - conversion routines for degrees/radians and latitude/colatitude\n *  - algebraic functions: abs(), abs2(), arg(), sqrt()\n *  - trig functions: cos(), cosh(), sin(), sinh(), tan(), tanh()\n *  - exponential functions: exp(), log(), log10()\n *\n * Warning: Some compilers, at low optimization levels, fail to properly \n * chain multiple ublas operations into a single evaluation.  \n * When this happens, the result is equal to the first operation.\n * These tests have been designed to catch this flaw.\n */\nBOOST_AUTO_TEST_CASE( real_vector_test ) {\n\n    vector<double> rvect(7);\n    for ( size_t n=0; n < rvect.size(); ++n ) {\n        rvect(n) = (double) (n+1);\n    }\n\n    cout << \"=== vector_test: real_vector_test ===\" << endl;\n    cout << \"a:         \" << rvect << endl;\n    cout << \"a+a:       \" << rvect + rvect << endl;\n    USML_VECTOR_REAL_TESTER( rvect+rvect, rvect, add_helper<double> ) ;\n    cout << \"a*2.1:     \" << rvect*2.1 << endl;\n    USML_VECTOR_REAL_TESTER( rvect*2.1, rvect, scalar2_multiply_helper<double> ) ;\n    cout << \"a+2.1:     \" << rvect+2.1 << endl;\n    USML_VECTOR_REAL_TESTER( rvect+2.1, rvect, scalar2_add_helper<double> ) ;\n    cout << \"2.1-a:     \" << 2.1-rvect << endl;\n    USML_VECTOR_REAL_TESTER( 2.1-rvect, rvect, scalar1_minus_helper<double> ) ;\n    cout << \"2.1/a:     \" << 2.1/rvect << endl;\n    USML_VECTOR_REAL_TESTER( 2.1/rvect, rvect, scalar1_divide_helper<double> ) ;\n    cout << \"a*a:       \" << rvect * rvect << endl;\n    USML_VECTOR_REAL_TESTER( rvect*rvect, rvect, multiply_helper<double> ) ;\n    cout << \"a/a:       \" << rvect / rvect << endl;\n    USML_VECTOR_REAL_TESTER( rvect/rvect, rvect, divide_helper<double> ) ;\n    cout << \"max(a,3.0):   \" << max(rvect,3.0) << endl;\n    USML_VECTOR_REAL_TESTER( max(rvect,3.0), rvect, max_helper<double> ) ;\n    cout << \"min(a,3.0):   \" << min(rvect,3.0) << endl;\n    USML_VECTOR_REAL_TESTER( min(rvect,3.0), rvect, min_helper<double> ) ;\n    cout << \"floor(a+2.1): \" << floor( rvect+2.1 ) << endl;\n    USML_VECTOR_REAL_TESTER( floor( rvect+2.1 ), rvect, floor_helper<double> ) ;\n    cout << \"ceil(a+2.1):  \" << ceil( rvect+2.1 ) << endl;\n    USML_VECTOR_REAL_TESTER( ceil( rvect+2.1 ), rvect, ceil_helper<double> ) ;\n    cout << \"to_degrees(to_radians(a+2.1)):     \" << to_degrees(to_radians(rvect+2.1)) << endl;\n    USML_VECTOR_REAL_TESTER( to_degrees(to_radians(rvect+2.1)), rvect, scalar2_add_helper<double> ) ;\n    cout << \"to_latitude(to_colatitude(a+2.1)): \" << to_latitude(to_colatitude(rvect+2.1)) << endl;\n    USML_VECTOR_REAL_TESTER( to_latitude(to_colatitude(rvect+2.1)), rvect, scalar2_add_helper<double> ) ;\n\n    cout << \"abs(a):    \" << abs(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( abs(rvect), rvect, std::abs<double> ) ;\n    cout << \"abs2(a):   \" << abs2(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( abs2(rvect), rvect, abs2_helper<double> ) ;\n    cout << \"arg(a):    \" << arg(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( arg(rvect), rvect, zero_helper<double> ) ;\n    cout << \"sqrt(a):   \" << sqrt(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( sqrt(rvect), rvect, std::sqrt<double> ) ;\n\n    cout << \"cos(a):    \" << cos(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( cos(rvect), rvect, std::cos<double> ) ;\n    cout << \"cosh(a):   \" << cosh(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( cosh(rvect), rvect, std::cosh<double> ) ;\n    cout << \"sin(a):    \" << sin(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( sin(rvect), rvect, std::sin<double> ) ;\n    cout << \"sinh(a):   \" << sinh(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( sinh(rvect), rvect, std::sinh<double> ) ;\n    cout << \"tan(a):    \" << tan(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( tan(rvect), rvect, std::tan<double> ) ;\n    cout << \"tanh(a):   \" << tanh(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( tanh(rvect), rvect, std::tanh<double> ) ;\n\n    cout << \"exp(a):    \" << exp(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( exp(rvect), rvect, std::exp<double> ) ;\n    cout << \"log(a):    \" << log(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( log(rvect), rvect, std::log<double> ) ;\n    cout << \"log10(a):  \" << log10(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( log10(rvect), rvect, std::log10<double> ) ;\n}\n\n/**\n * Run a complex valued vector through the standard math routines.  Tests include:\n *\n *  - addition of vector to itself\n *  - add scalar to vector\n *  - subtract vector from scalar\n *  - divide scalar by vector\n *  - min, max, floor, and ceil clipping using a scalar \n *  - conversion routines for degrees/radians and latitude/colatitude\n *  - algebraic functions: abs(), abs2(), arg(), sqrt()\n *  - trig functions: cos(), cosh(), sin(), sinh(), tan(), tanh()\n *  - exponential functions: exp(), log(), log10()\n *\n * Warning: Some compilers, at low optimization levels, fail to properly \n * chain multiple ublas operations into a single evaluation.  \n * When this happens, the result is equal to the first operation.\n * These tests have been designed to catch this flaw.\n */\nBOOST_AUTO_TEST_CASE( complex_vector_test ) {\n\n    vector< std::complex<double> > cvect(7);\n    for ( size_t n=0; n < cvect.size(); ++n ) {\n        cvect(n) = std::complex<double>(n+1,1.0);\n    }\n\n    cout << \"=== vector_test: complex_vector_test ===\" << endl;\n    cout << \"a:         \" << cvect << endl;\n    cout << \"a+a:       \" << cvect + cvect << endl;\n    USML_VECTOR_COMPLEX_TESTER( cvect+cvect, cvect, add_helper<complex<double> > ) ;\n    cout << \"a+2.1:     \" << cvect+2.1 << endl;\n    USML_VECTOR_COMPLEX_TESTER( cvect+2.1, cvect, scalar2_add_helper<complex<double> > ) ;\n    cout << \"2.1-a:     \" << 2.1-cvect << endl;\n    USML_VECTOR_COMPLEX_TESTER( 2.1-cvect, cvect, scalar1_minus_helper<complex<double> > ) ;\n\n    cout << \"abs(a):    \" << abs(cvect) << endl;\n    USML_VECTOR_COMPLEX_TESTER( abs(cvect), cvect, abs_helper<complex<double> > ) ;\n    cout << \"abs2(a):   \" << abs2(cvect) << endl;\n    USML_VECTOR_COMPLEX_TESTER( abs2(cvect), cvect, abs2_helper<complex<double> > ) ;\n    cout << \"arg(a):    \" << arg(cvect) << endl;\n    USML_VECTOR_COMPLEX_TESTER( arg(cvect), cvect, arg_helper<double> ) ;\n    cout << \"sqrt(a):   \" << sqrt(cvect) << endl;\n    USML_VECTOR_COMPLEX_TESTER( sqrt(cvect), cvect, std::sqrt<double> ) ;\n\n    cout << \"cos(a):    \" << cos(cvect) << endl;\n    USML_VECTOR_COMPLEX_TESTER( cos(cvect), cvect, std::cos<double> ) ;\n    cout << \"cosh(a):   \" << cosh(cvect) << endl;\n    USML_VECTOR_COMPLEX_TESTER( cosh(cvect), cvect, std::cosh<double> ) ;\n    cout << \"sin(a):    \" << sin(cvect) << endl;\n    USML_VECTOR_COMPLEX_TESTER( sin(cvect), cvect, std::sin<double> ) ;\n    cout << \"sinh(a):   \" << sinh(cvect) << endl;\n    USML_VECTOR_COMPLEX_TESTER( sinh(cvect), cvect, std::sinh<double> ) ;\n    cout << \"tan(a):    \" << tan(cvect) << endl;\n    USML_VECTOR_COMPLEX_TESTER( tan(cvect), cvect, std::tan<double> ) ;\n    cout << \"tanh(a):   \" << tanh(cvect) << endl;\n    USML_VECTOR_COMPLEX_TESTER( tanh(cvect), cvect, std::tanh<double> ) ;\n\n    cout << \"exp(a):    \" << exp(cvect) << endl;\n    USML_VECTOR_COMPLEX_TESTER( exp(cvect), cvect, std::exp<double> ) ;\n    cout << \"log(a):    \" << log(cvect) << endl;\n    USML_VECTOR_COMPLEX_TESTER( log(cvect), cvect, std::log<double> ) ;\n    cout << \"log10(a):  \" << log10(cvect) << endl;\n    USML_VECTOR_COMPLEX_TESTER( log10(cvect), cvect, std::log10<double> ) ;\n}\n\n/**\n * Test all of the real and complex combinations of the pow() function.\n */\nBOOST_AUTO_TEST_CASE( pow_vector_test ) {\n\n    vector<double> rvect(3);\n    vector< std::complex<double> > cvect(3);\n    std::complex<double> cmplx(2.5,3.5);\n\n    for ( size_t n=0; n < cvect.size(); ++n ) {\n        rvect(n) = (double) (n+1);\n        cvect(n) = std::complex<double>(n+1,1.0);\n    }\n\n    cout << \"=== vector_test: pow_vector_test ===\" << endl;\n    cout << \"N:      \" << rvect << endl;\n    cout << \"M:      \" << cvect << endl;\n    cout << \"C:      \" << cmplx << endl;\n\n    cout << \"N^3:    \" << pow(rvect,3) << endl;\n    USML_VECTOR_POW_SCALAR2_TESTER( pow(rvect,3), rvect, 3 ) ;\n    cout << \"N^2.5:  \" << pow(rvect,2.5) << endl;\n    USML_VECTOR_POW_SCALAR2_TESTER( pow(rvect,2.5), rvect, 2.5 ) ;\n    cout << \"2^N:    \" << pow( 2.0, rvect ) << endl;\n    USML_VECTOR_POW_SCALAR1_TESTER( pow(2.0,rvect), 2.0, rvect ) ;\n\n//    cout << \"M^3:    \" << pow(cvect,3.0) << endl;\n//    USML_VECTOR_POW_SCALAR2_TESTER( pow(cvect,3), cvect, 3 ) ;\n    cout << \"M^2.5:  \" << pow(cvect,2.5) << endl;\n    USML_VECTOR_POW_SCALAR2_TESTER( pow(cvect,2.5), cvect, 2.5 ) ;\n    cout << \"2^M:    \" << pow(2.0,cvect) << endl;\n    USML_VECTOR_POW_SCALAR1_TESTER( pow(2.0,cvect), 2.0, cvect ) ;\n\n    cout << \"N^N:    \" << pow(rvect,rvect) << endl;\n    USML_VECTOR_POW_TESTER( pow(rvect,rvect), rvect, rvect ) ;\n    cout << \"M^M:    \" << pow(cvect,cvect) << endl;\n    USML_VECTOR_POW_TESTER( pow(cvect,cvect), cvect, cvect ) ;\n    cout << \"N^M:    \" << pow(rvect,cvect) << endl;\n    USML_VECTOR_POW_TESTER( pow(rvect,cvect), rvect, cvect ) ;\n    cout << \"M^N:    \" << pow(cvect,rvect) << endl;\n    USML_VECTOR_POW_TESTER( pow(cvect,rvect), cvect, rvect ) ;\n}\n\n/**\n * Test the generation of real valued and analytic signals from\n * a vector of arguments.\n *\n * Assume that testers will visually inspect the results.\n */\nBOOST_AUTO_TEST_CASE( signal_vector_test ) {\n\n    vector<double> rvect(3);\n    for ( size_t n=0; n < rvect.size(); ++n ) {\n        rvect(n) = (double) (n+1);\n    }\n\n    cout << \"=== vector_test: signal_vector_test ===\" << endl;\n    cout << \"input:  \" << rvect << endl;\n    cout << \"signal: \" << signal(rvect) << endl;\n    USML_VECTOR_REAL_TESTER( signal(rvect), rvect, signal_helper<double> ) ;\n    cout << \"signal: \" << asignal(rvect) << endl;\n    USML_VECTOR_CR_TESTER( asignal(rvect), rvect, asignal_helper<double> ) ;\n}\n\n/**\n * Run trig routines forward and backward to check algorithms.\n */\nBOOST_AUTO_TEST_CASE( realInverse_vector_test ) {\n\n    vector<double> rvect(3);\n    for ( size_t n=0; n < rvect.size(); ++n ) {\n        rvect(n) = 0.1 * (double) (n+1);\n    }\n\n    cout << \"=== vector_test: realInverse_vector_test ===\" << endl;\n    cout << \"acos(cos(t)):    \" << acos(cos(rvect)) << endl;\n    USML_VECTOR_REAL_TESTER( acos(cos(rvect)), rvect, identity<double> ) ;\n    cout << \"acosh(cosh(t)):  \" << acosh(cosh(rvect)) << endl;\n    USML_VECTOR_REAL_TESTER( acosh(cosh(rvect)), rvect, identity<double> ) ;\n    cout << \"asin(sin(t)):    \" << asin(sin(rvect)) << endl;\n    USML_VECTOR_REAL_TESTER( asin(sin(rvect)), rvect, identity<double> ) ;\n    cout << \"asinh(sinh(t)):  \" << asinh(sinh(rvect)) << endl;\n    USML_VECTOR_REAL_TESTER( asinh(sinh(rvect)), rvect, identity<double> ) ;\n    cout << \"atan(tan(t)):    \" << atan(tan(rvect)) << endl;\n    USML_VECTOR_REAL_TESTER( atan(tan(rvect)), rvect, identity<double> ) ;\n    cout << \"atanh(tanh(t)):  \" << atanh(tanh(rvect)) << endl;\n    USML_VECTOR_REAL_TESTER( atanh(tanh(rvect)), rvect, identity<double> ) ;\n}\n\n/**\n * Run complex trig routines forward and backward to check algorithms.\n */\nBOOST_AUTO_TEST_CASE( complexInverse_vector_test ) {\n\n    vector< std::complex<double> > cvect(3);\n    for ( size_t n=0; n < cvect.size(); ++n ) {\n        cvect(n) = 0.1 * std::complex<double>(n+1,1.0);\n    }\n\n    cout << \"=== vector_test: complexInverse_vector_test ===\" << endl;\n    cout << \"acos(cos(t)):    \" << acos(cos(cvect)) << endl;\n    USML_VECTOR_COMPLEX_TESTER( acos(cos(cvect)), cvect, identity<complex<double> > ) ;\n    cout << \"acosh(cosh(t)):  \" << acosh(cosh(cvect)) << endl;\n    USML_VECTOR_COMPLEX_TESTER( acosh(cosh(cvect)), cvect, identity<complex<double> > ) ;\n    cout << \"asin(sin(t)):    \" << asin(sin(cvect)) << endl;\n    USML_VECTOR_COMPLEX_TESTER( asin(sin(cvect)), cvect, identity<complex<double> > ) ;\n    cout << \"asinh(sinh(t)):  \" << asinh(sinh(cvect)) << endl;\n    USML_VECTOR_COMPLEX_TESTER( asinh(sinh(cvect)), cvect, identity<complex<double> > ) ;\n    cout << \"atan(tan(t)):    \" << atan(tan(cvect)) << endl;\n    USML_VECTOR_COMPLEX_TESTER( atan(tan(cvect)), cvect, identity<complex<double> > ) ;\n    cout << \"atanh(tanh(t)):  \" << atanh(tanh(cvect)) << endl;\n    USML_VECTOR_COMPLEX_TESTER( atanh(tanh(cvect)), cvect, identity<complex<double> > ) ;\n}\n\n/// @}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "b1300f0c4a6f8a0b93aab767cb5785ddcc9268e3", "size": 12737, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ublas/test/vector_test.cc", "max_stars_repo_name": "fraclipe/UnderSeaModelingLibrary", "max_stars_repo_head_hexsha": "52ef9dd03c7cbe548749e4527190afe7668ff4e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-07T14:48:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T14:48:22.000Z", "max_issues_repo_path": "ublas/test/vector_test.cc", "max_issues_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_issues_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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": "ublas/test/vector_test.cc", "max_forks_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_forks_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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": 45.0070671378, "max_line_length": 105, "alphanum_fraction": 0.615058491, "num_tokens": 4061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5101448347629284}}
{"text": "/******************************************************************************\n *\n * AMDiS - Adaptive multidimensional simulations\n *\n * Copyright (C) 2013 Dresden University of Technology. All Rights Reserved.\n * Web: https://fusionforge.zih.tu-dresden.de/projects/amdis\n *\n * Authors:\n * Simon Vey, Thomas Witkowski, Andreas Naumann, Simon Praetorius, et al.\n *\n * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\n *\n * This file is part of AMDiS\n *\n * See also license.opensource.txt in the distribution.\n *\n ******************************************************************************/\n\n// Written by Simon Praetorius\n\n\n#ifndef ITL_PREONLY_INCLUDE\n#define ITL_PREONLY_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n\nnamespace itl\n{\n\n  /// Solver that simply applies a preconditioner to the rhs vector\n  template <typename Matrix, typename Vector, typename Preconditioner, typename Iteration>\n  int preonly(const Matrix& A, Vector& x, const Vector& b, const Preconditioner& P, Iteration& iter)\n  {\n    if (size(b) == 0)\n      throw mtl::logic_error(\"empty rhs vector\");\n\n    typedef typename mtl::Collection<Vector>::value_type Scalar;\n\n    // simple richardson iteration\n    Vector r(b - A*x);\n    Scalar res = two_norm(r);\n    for (; !iter.finished(res); ++iter)\n    {\n      x += Vector(solve(P, r));\n      r = b - A*x;\n      res = two_norm(r);\n    }\n    return iter;\n  }\n\n} // namespace itl\n\n#endif // ITL_PREONLY_INCLUDE\n\n", "meta": {"hexsha": "98f1b6c56d9ac113c3b74598e7e0b5305eb3c2f0", "size": 1549, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/itl/preonly.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": "src/solver/itl/preonly.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": "src/solver/itl/preonly.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": 27.1754385965, "max_line_length": 100, "alphanum_fraction": 0.6223369916, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5101448274266894}}
{"text": "#define BOOST_TEST_MODULE unary\n#include <boost/test/included/unit_test.hpp>\n#include \"exprtest.hpp\"\n\nEXPRTEST(unary1, \"-(2)\",  -2)\nEXPRTEST(unary2, \"-(-2)\",  2)\nEXPRTEST(unary3, \"+(-2)\", -2)\nEXPRTEST(unary4, \"+(+2)\",  2)\nEXPRTEST(unary5, \"!(1)\",   0)\nEXPRTEST(unary6, \"!(0)\",   1)\n", "meta": {"hexsha": "380a689f2ee090849a6209988bfe4118b1684083", "size": 282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unary.cpp", "max_stars_repo_name": "hmenke/boost_matheval", "max_stars_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-01-26T01:58:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:49:05.000Z", "max_issues_repo_path": "tests/unary.cpp", "max_issues_repo_name": "hmenke/boost_matheval", "max_issues_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T04:32:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-31T06:53:42.000Z", "max_forks_repo_path": "tests/unary.cpp", "max_forks_repo_name": "hmenke/boost_matheval", "max_forks_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-11-07T07:09:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T03:03:03.000Z", "avg_line_length": 25.6363636364, "max_line_length": 44, "alphanum_fraction": 0.6312056738, "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5101448249039024}}
{"text": "#pragma once\n\n// Armadillo\n#include <armadillo>\n\n// C++ standard library\n#include <functional>\n\nnamespace mant {\n  double brent(\n      std::function<double(\n          double)> objectiveFunction,\n      double lowerBound,\n      double upperBound,\n      arma::uword maximalNumberOfIterations);\n}\n", "meta": {"hexsha": "486b2fcc8bf9a2aa147b95e2e7621a4f42cf0060", "size": 293, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mantella_bits/numericalAnalysis.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/numericalAnalysis.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/numericalAnalysis.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": 17.2352941176, "max_line_length": 45, "alphanum_fraction": 0.6757679181, "num_tokens": 64, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5101448249039024}}
{"text": "#ifndef EXPONENTIAL_HISTOGRAM_HPP\n#define EXPONENTIAL_HISTOGRAM_HPP\n\n#include <stdexcept>\n#include <string>\n#include <boost/lexical_cast.hpp>\n#include <iostream>\n\n#include <sam/BaseSlidingWindow.hpp>\n\nnamespace sam {\n\ntemplate <typename T>\nclass ExponentialHistogram: public BaseSlidingWindow<T>\n{\npublic:\n  static size_t const MAX_SIZE;\n\nprivate:\n  \n  // Determines number of buckets.  If there are k/2 + 2 buckets\n  // of the same size (k + 2 buckets if the bucket size equals 1), \n  // the oldest two buckets are combined. \n  size_t k;\n\n  // The number of levels.  The first level has k+2 slots.\n  // All other levels have k/2 + 2 slots.  The ith level (starting at 0)\n  // has slots that represent 2^i numbers.  \n  size_t numLevels;\n\n  // The data structure that holds the data of the sliding window.\n  T** data;\n\n  // Points to where data should be added\n  size_t* ends;\n\n  // An array of booleans that keeps track of which levels need to be merged\n  bool* needToMerge;\n\n  // If all the storage in one level has been used, this is set to true.\n  // There is different processing depending on if we have seen the entire level\n  // or not.\n  bool* onePass;\n\n  T total = 0;\n\n  int numItems = 0;\n\npublic:\n  ExponentialHistogram(size_t N, size_t k) : BaseSlidingWindow<T>(N)\n  {\n    if (N == 0) {\n      throw std::out_of_range(\"Cannot specify 0 as the size of window\");\n    }\n\n    if (N >= MAX_SIZE) {\n      throw std::out_of_range(\"Specified N > MAX_SIZE which is \" +\n                              boost::lexical_cast<std::string>(MAX_SIZE));\n    }\n\n    this->k = k;\n\n    // Sets numLevels\n    determineNumLevels();  \n\n    data = new T*[numLevels];\n    \n    // The first level has k + 2 elements\n    data[0] = new T[k + 2];\n    for (int i = 1; i < numLevels; i++) {\n      data[i] = new T[k/2 + 2];  \n    }\n\n    onePass = new bool[numLevels];\n    for (int i = 0; i < numLevels; i++) onePass[i] = false;\n\n    needToMerge = new bool[numLevels];\n    for (int i = 0; i < numLevels; i++) needToMerge[i] = false;\n\n    ends = new size_t[numLevels];\n    for (int i = 0; i < numLevels; i++) ends[i] = 0;\n\n  }\n\n  virtual ~ExponentialHistogram() {\n    for(int i = 0; i < numLevels; i++) {\n      delete[] data[i];\n    }\n    delete[] data;\n    delete[] onePass;\n    delete[] ends;\n  }\n\n  /**\n   * Add the specified item to the window.  If the window is full,\n   * the item at the end is dropped.\n   */\n  void add(T item) {\n    //update the global total\n    total = total + item;\n\n    //update the number of items represented\n    numItems++;\n\n    // Add the item to the data structure.\n    add(item, 0);\n\n    /*for (int i = 0; i < k + 2; i++) {\n      std::cout << data[0][i] << \" \";\n    }\n    std::cout << std::endl;\n    for (int i = 1; i < numLevels; i++) {\n      for (int j = 0; j < k/2 + 2; j++) {\n        std::cout << data[i][j] << \" \";\n      }\n      std::cout << std::endl;\n    }*/\n\n  } \n\n  /**\n   * Returns the number of levels.  The ith level represents\n   * 2^i items aggregated together.  There are k+2 values in the\n   * 0th level, and k/2 + 1 values for levels > 0.\n   */\n  size_t getNumLevels() {\n    return numLevels;\n  }\n\n  T getTotal() {\n    return total;\n  }\n\n  /**\n   * Returns the total number of numbers that can be represented by\n   * the histogram.\n   */\n  size_t getNumSlots() {\n    return getNumSlots(numLevels, k);\n  }\n\n  /**\n   * Returns the number of items currently being represented by the\n   * exponential histogram.\n   */\n  size_t getNumItems() {\n    return numItems;\n  }\n\n  static size_t getNumSlots(long N, int k) \n  {\n    int size = 1;\n    int total = 0;\n    total = size * (k + 2);\n    for (int i = 1; i < N; i++) {\n      size = size * 2;\n      total = total + size * (k/2 + 2); \n    }\n    return total;\n\n  }\n  \nprivate:\n\n  void add(T item, size_t level) {\n    //std::cout << \"Adding item \" << item << \" to level \" << level << std::endl;\n    if (level < numLevels) {\n      // Going through the level for the first time.  \n      // We can just add items without worrying about overwriting values \n      // or the need to merge. \n      if (!onePass[level]) \n      { \n        data[level][ends[level]] = item;\n        incrementEnd(level);\n        // we passed through the level once\n        if (ends[level] == 0) {\n          onePass[level] = true;\n          needToMerge[level] = true;\n        }\n      } \n      // We have gone through the level at least once.  We have to worry about\n      // writing over values and the need to merge values to send to the level\n      // above.\n      else {\n\n        // Adding an item will force a merger\n        if (needToMerge[level]) { \n          // index of the first item to merge.\n          //std::cout << ends[level] << \" \" << endPlusOne(level) << std::endl;\n          size_t first = data[level][ends[level]]; \n          \n          // index of the second item to merge.\n          size_t second = data[level][endPlusOne(level)]; \n          \n          // Adding merged item to the next level\n          add(first + second, level + 1); \n          \n          // Adding the new item to the now open space\n          data[level][ends[level]] = item; \n          data[level][endPlusOne(level)] = -1;\n          \n          // The next addition won't require a merger since we cleared out\n          // two spaces.\n          needToMerge[level] = false; \n\n          incrementEnd(level);\n        } \n        // Still have space; no merger needed.\n        else { \n          data[level][ends[level]] = item;\n          incrementEnd(level);\n          needToMerge[level] = true;\n        }\n      }\n    }\n    // If there isn't another level, we update the total and drop the item.\n    else \n    {\n      numItems -= pow(2, level);\n      total = total - item;\n    }\n  }\n\n  /**\n   * Returns the index of the end incremented by 1 for the\n   * specified level.\n   */\n  size_t endPlusOne(size_t level) {\n    size_t tempEnd = ends[level] + 1;\n    if (((level == 0) && (tempEnd >= (k + 2))) ||\n        ((level > 0) && (tempEnd >= (k/2 + 2))))\n    {\n      return 0;\n    }\n    return tempEnd;\n  }\n\n  /**\n   * Increments the end index for the specified level.\n   */\n  void incrementEnd(size_t level) {\n    ends[level]++;\n    if (((level == 0) && (ends[level] >= (k + 2))) ||\n        ((level > 0) && (ends[level] >= (k/2 + 2))))\n    {\n      ends[level] = 0;\n    }\n  }\n\n  // Determines the number of bins necessary for the sliding window\n  // of size N.\n  void determineNumLevels() {\n    size_t total = 0;\n    numLevels = 1;\n\n    // first level has k + 2 slots, each representing one number\n    total = k + 2;\n    \n    while (total <= this->N) {\n      total = total + (k/2 + 2) * pow(2, numLevels);   \n      numLevels++;\n    }\n  }\n\n};\n\ntemplate <typename T>\nsize_t const ExponentialHistogram<T>::MAX_SIZE = 10000000;\n\n}\n#endif\n", "meta": {"hexsha": "be804bc8a22872c4a7f2443e36c37d319b7fed87", "size": 6746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SamSrc/sam/ExponentialHistogram.hpp", "max_stars_repo_name": "dirkcgrunwald/SAM", "max_stars_repo_head_hexsha": "0478925c506ad38fd405954cc4415a3e96e77d90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T07:13:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-08T21:15:52.000Z", "max_issues_repo_path": "SamSrc/sam/ExponentialHistogram.hpp", "max_issues_repo_name": "dirkcgrunwald/SAM", "max_issues_repo_head_hexsha": "0478925c506ad38fd405954cc4415a3e96e77d90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-30T20:35:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-30T20:35:18.000Z", "max_forks_repo_path": "SamSrc/sam/ExponentialHistogram.hpp", "max_forks_repo_name": "dirkcgrunwald/SAM", "max_forks_repo_head_hexsha": "0478925c506ad38fd405954cc4415a3e96e77d90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-17T18:38:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-28T02:47:57.000Z", "avg_line_length": 24.8014705882, "max_line_length": 80, "alphanum_fraction": 0.5674473762, "num_tokens": 1890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396753, "lm_q2_score": 0.6757646010190477, "lm_q1q2_score": 0.5101448174516021}}
{"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_MODF_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MODF_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing modf capabilities\n\n    Computes the integer and  fractional parts of the input\n\n    @par Semantic:\n\n    @code\n    std::pair<T,T> p = modf(x);\n    @endcode\n\n     is similar to:\n\n    @code\n    T t = trunc(x);\n    T f = frac(x);\n    @endcode\n\n    @see frac,  trunc\n\n  **/\n  Value modf(Value const & x, Value & y);\n\n  //@overload\n  std::pair<Value, Value> modf(Value const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/modf.hpp>\n#include <boost/simd/function/simd/modf.hpp>\n\n#endif\n", "meta": {"hexsha": "9816e8fe4911177aa6748453b6ebaf7c0e6beb57", "size": 1097, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/modf.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/modf.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/modf.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": 21.0961538462, "max_line_length": 100, "alphanum_fraction": 0.5560619872, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5101448150448762}}
{"text": "/* Copyright (c) 2016 - 2019, the adamantine authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#ifndef MATERIAL_PROPERTY_HH\n#define MATERIAL_PROPERTY_HH\n\n#include <types.hh>\n#include <utils.hh>\n\n#include <deal.II/base/function_parser.h>\n#include <deal.II/distributed/tria.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/fe/fe_dgq.h>\n#include <deal.II/grid/filtered_iterator.h>\n#include <deal.II/lac/la_parallel_vector.h>\n#include <deal.II/lac/la_vector.h>\n\n#include <boost/property_tree/ptree.hpp>\n\n#include <array>\n#include <limits>\n#include <unordered_map>\n\nnamespace adamantine\n{\n/**\n * This class stores the material properties for all the materials\n */\ntemplate <int dim>\nclass MaterialProperty\n{\npublic:\n  /**\n   * Constructor.\n   * \\param[in] database requires the following entries:\n   *   - <B>n_materials</B>: unsigned int in \\f$(0,\\infty)\\f$\n   *   - <B>material_X</B>: property tree associated with material_X\n   *   where X is a number\n   *   - <B>material_X.Y</B>: property_tree where Y is either liquid, powder, or\n   *   solid [optional]\n   *   - <B>material_X.Y.Z</B>: string where Z is either density, specific_heat,\n   *   or thermal_conductivity, describe the behavior of the property as a\n   *   function of the temperatur (e.g. \"2.*T\") [optional]\n   *   - <B>material.X.A</B>: A is either solidus, liquidus, or latent_heat\n   *   [optional]\n   */\n  MaterialProperty(\n      MPI_Comm const &communicator,\n      dealii::parallel::distributed::Triangulation<dim> const &tria,\n      boost::property_tree::ptree const &database);\n\n  /**\n   * Return the value of the given property, for a given cell and a given field\n   * state.\n   */\n  template <typename NumberType>\n  double\n  get(typename dealii::Triangulation<dim>::active_cell_iterator const &cell,\n      Property prop,\n      dealii::LA::distributed::Vector<NumberType> const &field_state) const;\n\n  /**\n   * Return the average temperature on every cell given the enthalpy.\n   */\n  template <typename NumberType>\n  dealii::LA::distributed::Vector<NumberType> enthalpy_to_temperature(\n      dealii::DoFHandler<dim> const &enthalpy_dof_handler,\n      dealii::LA::distributed::Vector<NumberType> const &enthalpy);\n\n  /**\n   * Reinitialize the DoFHandler associated with MaterialProperty and resize the\n   * state vectors.\n   */\n  void reinit_dofs();\n\n  /**\n   * Update the material state, i.e, the ratio of liquid, powder, and solid.\n   */\n  template <typename NumberType>\n  void\n  update_state(dealii::DoFHandler<dim> const &enthalpy_dof_handler,\n               dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> const &enthalpy);\n\n  /**\n   * Get the array of material state vectors. The order of the different state\n   * vectos is given by the MaterialState enum. Each entry in the vector\n   * correspond to a cell in the mesh and has a value between 0 and 1. The sum\n   * of the states for a given cell is equal to 1.\n   */\n  std::array<dealii::LA::distributed::Vector<double>,\n             static_cast<unsigned int>(MaterialState::SIZE)> &\n  get_state();\n\n  double get_state_ratio(\n      typename dealii::Triangulation<dim>::active_cell_iterator const &cell,\n      MaterialState material_state) const;\n\n  /**\n   * Return \\f$ -\\frac{H_{liquidus}}{\\rho C_P} + T_{liquidus} \\f$\n   */\n  double get_liquid_beta(\n      typename dealii::Triangulation<dim>::active_cell_iterator const &cell)\n      const;\n\n  /**\n   * Return \\f$ \\frac{T_{liquidus}-T_{solidus}}{\\mathcal{L}} \\f$\n   */\n  double get_mushy_alpha(\n      typename dealii::Triangulation<dim>::active_cell_iterator const &cell)\n      const;\n\n  /**\n   * Return \\f$ -H_{solidus} \\frac{T_{liquidus}-T_{solidus}}{\\mathcal{L}} +\n   * T_{solidus} \\f$\n   */\n  double get_mushy_beta(\n      typename dealii::Triangulation<dim>::active_cell_iterator const &cell)\n      const;\n\n  /**\n   * Return the underlying the DoFHandler.\n   */\n  dealii::DoFHandler<dim> const &get_dof_handler() const;\n\nprivate:\n  /**\n   * Maximum different number of states a given material can be.\n   */\n  static unsigned int constexpr _n_material_states =\n      static_cast<unsigned int>(MaterialState::SIZE);\n\n  /**\n   * Number of properties defined.\n   */\n  static unsigned int constexpr _n_properties =\n      static_cast<unsigned int>(Property::SIZE);\n\n  /**\n   * Set the values in _state from the values of the user index of the\n   * Triangulation.\n   */\n  void set_state();\n\n  /**\n   * Fill the _properties map.\n   */\n  void fill_properties(boost::property_tree::ptree const &database);\n\n  /**\n   * If the density and the specific heat do not depend on the temperature, the\n   * relationship between the temperature and the enthalpy can be written by\n   * piecewise function \\f$ T = \\alpha H + \\beta \\f$. This function computes the\n   * constants \\f$ \\alpha \\f$ and \\f$ \\beta \\f$.\n   */\n  void compute_constants();\n\n  /**\n   * Return the index of the dof associated to the cell.\n   */\n  double get_dof_index(\n      typename dealii::Triangulation<dim>::active_cell_iterator const &cell)\n      const;\n\n  /**\n   * Compute the average of the enthalpy on every cell.\n   */\n  template <typename NumberType>\n  dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> compute_average_enthalpy(\n      dealii::DoFHandler<dim> const &enthalpy_dof_handler,\n      dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> const &enthalpy) const;\n\n  /**\n   * MPI communicator.\n   */\n  MPI_Comm _communicator;\n  /**\n   * Map of \\f$ -\\frac{H_{liquidus}}{\\rho C_P} + T_{liquidus} \\f$ for each\n   * material.\n   */\n  std::unordered_map<dealii::types::material_id, double> _liquid_beta;\n  /**\n   * Map of \\f$ \\frac{T_{liquidus}-T_{solidus}}{\\mathcal{L}} \\f$ for each\n   * material.\n   */\n  std::unordered_map<dealii::types::material_id, double> _mushy_alpha;\n  /**\n   * Map of \\f$ -H_{solidus} \\frac{T_{liquidus}-T_{solidus}}{\\mathcal{L}} +\n   * T_{solidus} \\f$ for each material.\n   */\n  std::unordered_map<dealii::types::material_id, double> _mushy_beta;\n  /**\n   * Map that stores functions describing the properties of the material.\n   */\n  std::unordered_map<\n      dealii::types::material_id,\n      std::array<\n          std::array<std::unique_ptr<dealii::FunctionParser<1>>, _n_properties>,\n          _n_material_states>>\n      _properties;\n  /**\n   * Array of vector describing the ratio of each state in each cell. Each\n   * vector corresponds to a state defined in the MaterialState enum.\n   */\n  std::array<dealii::LA::distributed::Vector<double>, _n_material_states>\n      _state;\n  /**\n   * Discontinuous piecewise constant finite element.\n   */\n  dealii::FE_DGQ<dim> _fe;\n  /**\n   * DoFHandler associated to the _state array.\n   */\n  dealii::DoFHandler<dim> _mp_dof_handler;\n};\n\ntemplate <int dim>\ninline std::array<dealii::LA::distributed::Vector<double>,\n                  static_cast<unsigned int>(MaterialState::SIZE)> &\nMaterialProperty<dim>::get_state()\n{\n  return _state;\n}\n\ntemplate <int dim>\ninline double MaterialProperty<dim>::get_state_ratio(\n    typename dealii::Triangulation<dim>::active_cell_iterator const &cell,\n    MaterialState material_state) const\n{\n  double const mp_dof_index = get_dof_index(cell);\n  unsigned int const mat_state = static_cast<unsigned int>(material_state);\n\n  return _state[mat_state][mp_dof_index];\n}\n\ntemplate <int dim>\ninline double MaterialProperty<dim>::get_liquid_beta(\n    typename dealii::Triangulation<dim>::active_cell_iterator const &cell) const\n{\n  dealii::types::material_id material_id = cell->material_id();\n  auto const liquid_beta = _liquid_beta.find(material_id);\n  ASSERT(liquid_beta != _liquid_beta.end(), \"Material not found.\");\n\n  return liquid_beta->second;\n}\n\ntemplate <int dim>\ninline double MaterialProperty<dim>::get_mushy_alpha(\n    typename dealii::Triangulation<dim>::active_cell_iterator const &cell) const\n{\n  dealii::types::material_id material_id = cell->material_id();\n  auto const mushy_alpha = _mushy_alpha.find(material_id);\n  ASSERT(mushy_alpha != _mushy_alpha.end(), \"Material not found.\");\n\n  return mushy_alpha->second;\n}\n\ntemplate <int dim>\ninline double MaterialProperty<dim>::get_mushy_beta(\n    typename dealii::Triangulation<dim>::active_cell_iterator const &cell) const\n{\n  dealii::types::material_id material_id = cell->material_id();\n  auto const mushy_beta = _mushy_beta.find(material_id);\n  ASSERT(mushy_beta != _mushy_beta.end(), \"Material not found.\");\n\n  return mushy_beta->second;\n}\n\ntemplate <int dim>\ninline double MaterialProperty<dim>::get_dof_index(\n    typename dealii::Triangulation<dim>::active_cell_iterator const &cell) const\n{\n  // Get a DoFCellAccessor from a Triangulation::active_cell_iterator.\n  dealii::DoFAccessor<dim, dealii::DoFHandler<dim>, false> dof_accessor(\n      &_mp_dof_handler.get_triangulation(), cell->level(), cell->index(),\n      &_mp_dof_handler);\n  std::vector<dealii::types::global_dof_index> mp_dof(1.);\n  dof_accessor.get_dof_indices(mp_dof);\n\n  return mp_dof[0];\n}\n\ntemplate <int dim>\ninline dealii::DoFHandler<dim> const &\nMaterialProperty<dim>::get_dof_handler() const\n{\n  return _mp_dof_handler;\n}\n} // namespace adamantine\n\n#endif\n", "meta": {"hexsha": "571a40410948d088995b11ceb9c0d2b66e1f6844", "size": 9336, "ext": "hh", "lang": "C++", "max_stars_repo_path": "source/MaterialProperty.hh", "max_stars_repo_name": "masterleinad/adamantine", "max_stars_repo_head_hexsha": "f5de64d869bf419273946d4f25fb0a8ddc016eaf", "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": "source/MaterialProperty.hh", "max_issues_repo_name": "masterleinad/adamantine", "max_issues_repo_head_hexsha": "f5de64d869bf419273946d4f25fb0a8ddc016eaf", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/MaterialProperty.hh", "max_forks_repo_name": "masterleinad/adamantine", "max_forks_repo_head_hexsha": "f5de64d869bf419273946d4f25fb0a8ddc016eaf", "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.5405405405, "max_line_length": 103, "alphanum_fraction": 0.7035132819, "num_tokens": 2466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.5101428098982957}}
{"text": "#include \"ViewerInh.h\"\n#include <igl/collapse_edge.h>\n#include <igl/edge_flaps.h>\n#include <igl/vertex_triangle_adjacency.h>\n#include <igl/adjacency_list.h>\n#include <Eigen/Core>\n#include <set>\n#include <math.h>\n#include \"igl/circulation.h\"\n\n\nvoid ViewerInh::init_ds_for_data() {\n    int num_of_meshes = static_cast<int>(data_list.size());\n    data_edges.resize(static_cast<unsigned long>(num_of_meshes));\n    for (int i = 0; i < num_of_meshes; i++) {\n        auto ds = new edges;                                            // Create new data structure\n        data_edges[i] = reset(data_list[i], ds);\n    }\n}\n\n\nedges *ViewerInh::reset(igl::opengl::ViewerData obj, edges* ds){\n    Eigen::MatrixXd V = obj.V;                                                         // Get mesh's vertexes\n    Eigen::MatrixXi F = obj.F;                                                         // Get mesh's faces\n    igl::edge_flaps(F,ds->E,ds->EMAP,ds->EF,ds->EI);                                   // Init the edge related field in the data structure\n    ds->Qit.resize(static_cast<unsigned long>(ds->E.rows()));\n    ds->C.resize(ds->E.rows(),V.cols());\n    ds->Q.clear();\n    ds->EQ = get_Q(V,F,obj.F_normals);\n\n    for(int e = 0; e < ds->E.rows(); e++){\n        double cost;\n        Eigen::RowVectorXd p(1,3);\n        calc_edges_cost(e,V,F,ds->E,ds->EMAP,ds->EF, ds->EI, cost, p, ds->EQ);         // Calculate cost for each edge\n        ds->Qit[e] = ds->Q.insert(std::pair<double,int>(cost,e)).first;                // Save the edge cost in Q and in Q's iterator- Qit\n        ds->C.row(e)   = p;                                                            // Save the optimal vertex p in C at index e\n    }\n    ds->num_collapsed = 0;\n    return ds;\n}\n\n std::vector<Eigen::Matrix4d> ViewerInh::get_Q(Eigen::MatrixXd &V, Eigen::MatrixXi &F, Eigen::MatrixXd &F_normals){\n    std::vector<std::vector<int> > vertex_to_vertices;\n    std::vector<std::vector<int> > vertex_to_faces_index;\n    igl::adjacency_list(F, vertex_to_vertices);\n    igl::vertex_triangle_adjacency(V,F,vertex_to_vertices, vertex_to_faces_index);     // Get the faces connected to each vertex\n\n    std::vector<Eigen::Matrix4d> Q;                                                    // Create vector Q of error quadrics\n    Q.resize(V.rows());                                                                // Set the size of Q to be as the numbers of vertecies\n\n    for(int v = 0; v < V.rows(); v++) {                                                // For each vertex v in V\n        std::vector<int> faces_index_of_vector = vertex_to_vertices[v];                // Get the faces connected to v\n        Eigen::Vector4d vertex(V.row(v)(0), V.row(v)(1), V.row(v)(2), 1);              // Get v in vector of size 4\n        Eigen::Matrix4d sum_of_Kp;\n        sum_of_Kp << 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;                                  // Init 4X4 matrix to insert to Q\n\n        for(int f: faces_index_of_vector) {                                            // For each face connected to v\n            Eigen::RowVectorXd p = F_normals.row(f).normalized();                      // p = (a, b, c) -> a^2 + b^2 + c^2 = 1\n            double d = (-vertex(0) * p(0))+ (-vertex(1) * p(1)) + (-vertex(2) * p(2)); // d = -ax - by - cz\n            Eigen::Vector4d p_with_d(p(0), p(1), p(2), d);                             // p_with_d = (a, b, c, d)\n            Eigen::Matrix4d Kp = p_with_d * p_with_d.transpose();                      // Kp\n            sum_of_Kp += Kp;                                                           // Add Kp to sum_of_KP\n        }\n        Q[v] = sum_of_Kp;                                                              // Push sum_of_KP to Q in index v\n    }\n     return Q;\n}\n\n void ViewerInh::calc_edges_cost(const int e,\n                                 const Eigen::MatrixXd & V,\n                                 const Eigen::MatrixXi & F,\n                                 const Eigen::MatrixXi & E,\n                                 const Eigen::VectorXi & EMAP,\n                                 const Eigen::MatrixXi & EF,\n                                 const Eigen::MatrixXi & EI,\n                                 double & cost,\n                                 Eigen::RowVectorXd & p,\n                                 std::vector<Eigen::Matrix4d> & Q){\n        Eigen::RowVectorXd p_(1,3);\n        int v1 = E(e,0);                    // Index (in V) of the first vertex in edge e\n        int v2 = E(e,1);                    // Index (in V) of the second vertex in edge e\n        Eigen::Matrix4d Q1 = Q[v1];         // Error-quadric of v1\n        Eigen::Matrix4d Q2 = Q[v2];         // Error-quadric of v2\n        Eigen::Matrix4d Q_tag = (Q1 + Q2);  // Error-quadric Q\n\n        Eigen::Vector4d vertex1(V.row(v1)(0), V.row(v1)(1), V.row(v1)(2), 1); // V.row(v1) as vector of size 4\n        Eigen::Vector4d vertex2(V.row(v2)(0), V.row(v2)(1), V.row(v2)(2), 1); // V.row(v2) as vector of size 4\n\n        double lowest_cost;          // Init the lowest cost of the edge\n\n        // Create matrix of Q(1,1)-Q(3,4) and (0,0,0,1) at the bottom\n        Eigen::Matrix4d v_tag_1;\n        v_tag_1 <<\n                Q_tag(0,0),Q_tag(0,1),Q_tag(0,2),Q_tag(0,3),\n                Q_tag(1,0),Q_tag(1,1),Q_tag(1,2),Q_tag(1,3),\n                Q_tag(2,0),Q_tag(2,1),Q_tag(2,2),Q_tag(2,3),\n                0,           0,           0,        1;\n\n\n        if(v_tag_1.determinant() != 0) {                            // Check if v_tag_1 is inversable\n            Eigen::Vector4d v_tag_2(0, 0, 0, 1);\n            Eigen::Vector4d v_tag = v_tag_1.inverse() * v_tag_2;    // Get new vertex v_tag to collapse e into\n            lowest_cost = v_tag.transpose() * Q_tag * v_tag;        // Get the cost of e\n            p_ << v_tag(0), v_tag(1), v_tag(2);                      // Set the optimal vertex p to be v_tag\n        }\n\n        else{                                                       // If v_tag_1 is not inverse\n            Eigen::Vector4d midpoint = (vertex1 + vertex2) * 0.5;   // Calculate mitdpoint of e\n            double cost1 = vertex1.transpose()  * Q_tag * vertex1;  // Calculate cost of v1\n            double cost2 = vertex2.transpose()  * Q_tag * vertex2;  // Calculate cost of v2\n            double cost3 = midpoint.transpose() * Q_tag * midpoint; // Calculate cost of mitdpoint\n\n\n            lowest_cost = std::min(cost1, cost2);                   // Set cost of e as min(cost1,cost2,cost3)\n            lowest_cost = std::min(lowest_cost, cost3);             //\n\n            if (lowest_cost == cost1)                               //\n                p_ << vertex1(0), vertex1(1), vertex1(2);           //\n            else if (lowest_cost == cost2)                          // Set the optimal vertex p to the vertex with lowest cost\n                p_ << vertex2(0), vertex2(1), vertex2(2);           //\n            else                                                    //\n                p_ << midpoint(0), midpoint(1), midpoint(2);        //\n        }\n     p = p_;\n     cost = lowest_cost;\n//     std::cout << e << \") cost \" << cost << \" at point \" << p(0) << \", \"<< p(1) << \", \"<< p(2) << \"\\n\"<< std::endl;\n}\n\nbool ViewerInh::my_collapse(Eigen::MatrixXd & V,\n                             Eigen::MatrixXi & F,\n                             Eigen::MatrixXd &F_normals,\n                             edges *ds){\n    //a. Takes out the lowest cost edge from queue.\n    if(ds->Q.empty())\n    {\n        return false;\n    }\n    std::pair<double,int> q = *(ds->Q.begin());\n    ds->Q.erase(ds->Q.begin());\n    int e = q.second;\n    double cost = q.first;\n    ds->Qit[e] = ds->Q.end();\n    std::vector<int> N  = igl::circulation(e, true,ds->EMAP,ds->EF,ds->EI);\n    std::vector<int> Nd = igl::circulation(e,false,ds->EMAP,ds->EF,ds->EI);\n    N.insert(N.begin(),Nd.begin(),Nd.end());\n\n    //b. Deletes edge\n    const auto & kill_edge = [&ds](const int e)\n    {\n        ds->E(e,0) = 0;\n        ds->E(e,1) = 0;\n        ds->EF(e,0) = 0;\n        ds->EF(e,1) = 0;\n        ds->EI(e,0) = 0;\n        ds->EI(e,1) = 0;\n    };\n\n    const int eflip = ds->E(e,0)>ds->E(e,1);\n    // source and destination\n    const int s = eflip?ds->E(e,1):ds->E(e,0);\n    const int d = eflip?ds->E(e,0):ds->E(e,1);\n    const std::vector<int> nV2Fd = igl::circulation(e,!eflip,ds->EMAP,ds->EF,ds->EI);\n    int e1,f1,e2,f2;\n\n    const int m = F.rows();\n    for(int side = 0;side<2;side++)\n    {\n        const int f = ds->EF(e,side);\n        const int v = ds->EI(e,side);\n        const int sign = (eflip==0?1:-1)*(1-2*side);\n        // next edge emanating from d\n        const int e1_ = ds->EMAP(f+m*((v+sign*1+3)%3));\n        // prev edge pointing to s\n        const int e2_ = ds->EMAP(f+m*((v+sign*2+3)%3));\n        if(! (ds->E(e1_,0) == d || ds->E(e1_,1) == d))return false;\n        if(! (ds->E(e2_,0) == s || ds->E(e2_,1) == s))return false;\n        // face adjacent to f on e1, also incident on d\n        const bool flip1 = ds->EF(e1_,1)==f;\n        const int f1_ = flip1 ? ds->EF(e1_,0) : ds->EF(e1_,1);\n        if(! (f1_!=f))return false;\n        if(! (F(f1_,0)==d || F(f1_,1)==d || F(f1_,2) == d))return false;\n        // across from which vertex of f1_ does e1 appear?\n        const int v1 = flip1 ? ds->EI(e1_,0) : ds->EI(e1_,1);\n        // Kill e1_\n        kill_edge(e1_);\n        // Kill f\n        F(f,0) = 0;\n        F(f,1) = 0;\n        F(f,2) = 0;\n        // map f1_'s edge on e1 to e2_\n        if(! (ds->EMAP(f1_+m*v1) == e1_))return false;\n        ds->EMAP(f1_+m*v1) = e2_;\n        // side opposite f2, the face adjacent to f on e2_, also incident on s\n        const int opp2 = (ds->EF(e2_,0)==f?0:1);\n        if(! (ds->EF(e2_,opp2) == f))return false;\n        ds->EF(e2_,opp2) =  f1_;\n        ds->EI(e2_,opp2) = v1;\n        // remap e2 from d to s\n        ds->E(e2_,0) = ds->E(e2_,0)==d ? s : ds->E(e2_,0);\n        ds->E(e2_,1) = ds->E(e2_,1)==d ? s : ds->E(e2_,1);\n        if(side==0)\n        {\n            e1 = e1_;\n            f1 = f;\n        }else\n        {\n            e2 = e1_;\n            f2 = f;\n        }\n    }\n\n    //c. Deletes faces\n    for(auto f : nV2Fd)\n    {\n        for(int v = 0;v<3;v++)\n        {\n            if(F(f,v) == d)\n            {\n                const int flip1 = (ds->EF(ds->EMAP(f+m*((v+1)%3)),0)==f)?1:0;\n                const int flip2 = (ds->EF(ds->EMAP(f+m*((v+2)%3)),0)==f)?0:1;\n                if(! (ds->E(ds->EMAP(f+m*((v+1)%3)),flip1) == d ||\n                                ds->E(ds->EMAP(f+m*((v+1)%3)),flip1) == s)) return false;\n                ds->E(ds->EMAP(f+m*((v+1)%3)),flip1) = s;\n                if(! (ds->E(ds->EMAP(f+m*((v+2)%3)),flip2) == d ||\n                                ds->E(ds->EMAP(f+m*((v+2)%3)),flip2) == s)) return false;\n                ds->E(ds->EMAP(f+m*((v+2)%3)),flip2) = s;\n                F(f,v) = s;\n                break;\n            }\n        }\n    }\n    // Finally, \"remove\" this edge and its information\n    kill_edge(e);\n\n    //d. Merges vertices to a new vertex v\u0305\n    Eigen::RowVectorXd v = ds->C.row(e);\n    V.row(s) = v;\n    V.row(d) = v;\n//    ds->EQ = get_Q(V,F,F_normals);\n\n    // Erase the two, other collapsed edges\n    ds->Q.erase(ds->Qit[e1]);\n    ds->Qit[e1] = ds->Q.end();\n    ds->Q.erase(ds->Qit[e2]);\n    ds->Qit[e2] = ds->Q.end();\n    // update local neighbors\n    // loop over original face neighbors\n    for(auto n : N)\n    {\n        if(F(n,0) != 0 ||\n           F(n,1) != 0 ||\n           F(n,2) != 0)\n        {\n            for(int v = 0;v<3;v++)\n            {\n                // get edge id\n                const int ei = ds->EMAP(v*F.rows()+n);\n                // erase old entry\n                ds->Q.erase(ds->Qit[ei]);\n                // compute cost and potential placement\n                double cost;\n                Eigen::RowVectorXd place;\n                calc_edges_cost(ei,V,F,ds->E,ds->EMAP,ds->EF,ds->EI,cost,place,ds->EQ);\n                // Replace in queue\n                ds->Qit[ei] = ds->Q.insert(std::pair<double,int>(cost,ei)).first;\n                ds->C.row(ei) = place;\n            }\n        }\n    }\n\n    std::cout << \"edge \" << e << \", cost = \" << cost << \"  new v position (\" << v(0) << \",\"<< v(1) << \",\"<< v(2) << \")\\n\"<< std::endl;\nreturn true;\n}\n\nvoid ViewerInh::simplify(int num_to_collapse){\n    edges *ds = data_edges[selected_data_index];\n    Eigen::MatrixXd V = data_list[selected_data_index].V;\n    Eigen::MatrixXi F = data_list[selected_data_index].F;\n    Eigen::MatrixXd F_normals = data_list[selected_data_index].F_normals;\n    int curr_collapsed = 0;\n\n    const auto & collapse = [&ds, &V,  &F, &F_normals](){\n            return my_collapse(V, F, F_normals,ds);\n    };\n\n    bool something_collapsed = false;\n    while(curr_collapsed < num_to_collapse)\n    {\n        if(collapse()){\n            ds->num_collapsed++;\n            curr_collapsed++;\n            something_collapsed = true;\n        }else{\n           break;\n        }\n    }\n\n    if(something_collapsed){\n        data_list[selected_data_index].clear();\n        data_list[selected_data_index].set_mesh(V, F);\n        data_list[selected_data_index].set_face_based(true);\n    }\n\n    data_edges[selected_data_index] = ds;\n}\n\n\nvoid ViewerInh::simplification(){\n    long num_of_edges = data_edges[selected_data_index]->E.rows() - data_edges[selected_data_index]->num_collapsed;\n    if (num_of_edges < 8)\n        return;\n    const int max_iter = std::ceil(num_of_edges * 0.05);\n    simplify(max_iter);\n}\n\n\n\n", "meta": {"hexsha": "3cfbcb60548d44c80c1af566d1a8c9be74128661", "size": 13438, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tutorial/sandBox/ViewerInh.cpp", "max_stars_repo_name": "urield94/3D_Engine", "max_stars_repo_head_hexsha": "a1d3de20f24026d7443216c5220a9fd4109bf488", "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": "tutorial/sandBox/ViewerInh.cpp", "max_issues_repo_name": "urield94/3D_Engine", "max_issues_repo_head_hexsha": "a1d3de20f24026d7443216c5220a9fd4109bf488", "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": "tutorial/sandBox/ViewerInh.cpp", "max_forks_repo_name": "urield94/3D_Engine", "max_forks_repo_head_hexsha": "a1d3de20f24026d7443216c5220a9fd4109bf488", "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.2578616352, "max_line_length": 141, "alphanum_fraction": 0.4767078434, "num_tokens": 3942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5101428098982957}}
{"text": "#include<iostream>\n#include<cstdlib>\n#include<complex>\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/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/lapack/geev.hpp>\n#include \"utils.h\"\n\nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::complex;\n\nnamespace ublas =  boost::numeric::ublas;\nnamespace lapack =  boost::numeric::bindings::lapack;\n\nvoid geev(int);\ntemplate <typename T>\nvoid Hessenberg(ublas::matrix<T, ublas::column_major>& );\n\nint main(){\n    cout << \"I'm testing uBlas.\" << endl;\n\n    int n = 5;\n    geev(n);\n\n}\nvoid geev(int n){\n    cout << \"\\nCalculating eigenvalues using LAPACK's geev.\" << endl;\n    ublas::matrix<double, ublas::column_major> A(n,n);\n    Hessenberg(A);\n    print_m(A);\n\n    ublas::vector<complex<double> > values(n);\n    ublas::matrix<complex<double>, ublas::column_major>* Vectors_left = 0;\n    ublas::matrix<complex<double>, ublas::column_major> Vectors_right(n,n);\n\n    lapack::geev(A, values, Vectors_left, &Vectors_right, lapack::optimal_workspace());\n    print_v(values, \"values\"); cout << endl;\n    print_m(Vectors_right, \"Vectors_right\"); cout << endl;\n\n    Hessenberg(A);\n    cout << \"A*x = l*x.\" << endl;\n    for( int i = 0; i < Vectors_right.size2(); ++i ){\n        ublas::vector<complex<double> > tmp(n);\n        tmp = ublas::prod( A, column(Vectors_right, i) );\n        cout << tmp - values(i)*column(Vectors_right,i) << endl;\n    }\n\n}\ntemplate <typename T>\nvoid Hessenberg(ublas::matrix<T, ublas::column_major>& H){\n    T k = 1;\n    for( unsigned int i = 0; i < H.size1(); ++i ){\n        for( unsigned int j = i; j <= H.size2(); ++j ){\n            if( j > 0 ){\n                H(i,j-1) = k;\n                k += 1;\n            }\n        }\n    }\n}\n\n", "meta": {"hexsha": "29cb8a1ee1cbe428624132454ebd1e630fe40837", "size": 1894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_geev.cpp", "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/lapack/test/ublas_geev.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_geev.cpp", "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": 28.2686567164, "max_line_length": 87, "alphanum_fraction": 0.6282998944, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5101428076173417}}
{"text": "#include \"vmcsolver.h\"\n#include \"lib.h\"\n\n#include <armadillo>\n#include <iostream>\n\nusing namespace arma;\nusing namespace std;\n\nVMCSolver::VMCSolver() :\n    nDimensions(3),\n    charge(2),\n    nParticles(2),\n    h(0.001),\n    h2(1000000),\n    idum(-1),\n    alpha(0.5*charge),\n    nCycles(1000000),\n    timestep(0.05),\n    D(0.5)\n{\n}\n\nvoid VMCSolver::runMonteCarloIntegration()\n{\n  rOld = zeros<mat>(nParticles, nDimensions);\n  rNew = zeros<mat>(nParticles, nDimensions);\n  QForceOld = zeros<mat>(nParticles, nDimensions);\n  QForceNew = zeros<mat>(nParticles, nDimensions);\n\n  double waveFunctionOld = 0;\n  double waveFunctionNew = 0;\n\n  double energySum = 0;\n  double energySquaredSum = 0;\n\n  double deltaE;\n\n  // initial trial positions\n  for(int i = 0; i < nParticles; i++) {\n    for(int j = 0; j < nDimensions; j++) {\n      rOld(i,j) = GaussianDeviate(&idum)*sqrt(timestep);\n    }\n  }\n  rNew = rOld;\n\n  // loop over Monte Carlo cycles\n  for(int cycle = 0; cycle < nCycles; cycle++) {\n\n    // Store the current value of the wave function\n    waveFunctionOld = waveFunction(rOld);\n    QuantumForce(rOld, QForceOld); QForceOld = QForceOld*h/waveFunctionOld;\n    // New position to test\n    for(int i = 0; i < nParticles; i++) {\n      for(int j = 0; j < nDimensions; j++) {\n\trNew(i,j) = rOld(i,j) + GaussianDeviate(&idum)*sqrt(timestep)+QForceOld(i,j)*timestep*D;\n      }\n      //  for the other particles we need to set the position to the old position since\n      //  we move only one particle at the time\n      for (int k = 0; k < nParticles; k++) {\n\tif ( k != i) {\n\t  for (int j=0; j < nDimensions; j++) {\n\t    rNew(k,j) = rOld(k,j);\n\t  }\n\t} \n      }\n      // Recalculate the value of the wave function and the quantum force\n      waveFunctionNew = waveFunction(rNew);\n      QuantumForce(rNew,QForceNew) = QForceNew*h/waveFunctionNew;\n      //  we compute the log of the ratio of the greens functions to be used in the \n      //  Metropolis-Hastings algorithm\n      GreensFunction = 0.0;            \n      for (int j=0; j < nDimensions; j++) {\n\tGreensFunction += 0.5*(QForceOld(i,j)+QForceNew(i,j))*\n\t  (D*timestep*0.5*(QForceOld(i,j)-QForceNew(i,j))-rNew(i,j)+rOld(i,j));\n      }\n      GreensFunction = exp(GreensFunction);\n\n      // The Metropolis test is performed by moving one particle at the time\n      if(ran2(&idum) <= GreensFunction*(waveFunctionNew*waveFunctionNew) / (waveFunctionOld*waveFunctionOld)) {\n\tfor(int j = 0; j < nDimensions; j++) {\n\t  rOld(i,j) = rNew(i,j);\n\t  QForceOld(i,j) = QForceNew(i,j);\n\t  waveFunctionOld = waveFunctionNew;\n\t}\n      } else {\n\tfor(int j = 0; j < nDimensions; j++) {\n\t  rNew(i,j) = rOld(i,j);\n\t  QForceNew(i,j) = QForceOld(i,j);\n\t}\n      }\n      // update energies\n      deltaE = localEnergy(rNew);\n      energySum += deltaE;\n      energySquaredSum += deltaE*deltaE;\n    }\n  }\n  double energy = energySum/(nCycles * nParticles);\n  double energySquared = energySquaredSum/(nCycles * nParticles);\n  cout << \"Energy: \" << energy << \" Energy (squared sum): \" << energySquared << endl;\n}\n\ndouble VMCSolver::localEnergy(const mat &r)\n{\n    mat rPlus = zeros<mat>(nParticles, nDimensions);\n    mat rMinus = zeros<mat>(nParticles, nDimensions);\n\n    rPlus = rMinus = r;\n\n    double waveFunctionMinus = 0;\n    double waveFunctionPlus = 0;\n\n    double waveFunctionCurrent = waveFunction(r);\n\n    // Kinetic energy\n\n    double kineticEnergy = 0;\n    for(int i = 0; i < nParticles; i++) {\n        for(int j = 0; j < nDimensions; j++) {\n            rPlus(i,j) += h;\n            rMinus(i,j) -= h;\n            waveFunctionMinus = waveFunction(rMinus);\n            waveFunctionPlus = waveFunction(rPlus);\n            kineticEnergy -= (waveFunctionMinus + waveFunctionPlus - 2 * waveFunctionCurrent);\n            rPlus(i,j) = r(i,j);\n            rMinus(i,j) = r(i,j);\n        }\n    }\n    kineticEnergy = 0.5 * h2 * kineticEnergy / waveFunctionCurrent;\n\n    // Potential energy\n    double potentialEnergy = 0;\n    double rSingleParticle = 0;\n    for(int i = 0; i < nParticles; i++) {\n        rSingleParticle = 0;\n        for(int j = 0; j < nDimensions; j++) {\n            rSingleParticle += r(i,j)*r(i,j);\n        }\n        potentialEnergy -= charge / sqrt(rSingleParticle);\n    }\n    // Contribution from electron-electron potential\n    double r12 = 0;\n    for(int i = 0; i < nParticles; i++) {\n        for(int j = i + 1; j < nParticles; j++) {\n            r12 = 0;\n            for(int k = 0; k < nDimensions; k++) {\n                r12 += (r(i,k) - r(j,k)) * (r(i,k) - r(j,k));\n            }\n            potentialEnergy += 1 / sqrt(r12);\n        }\n    }\n\n    return kineticEnergy + potentialEnergy;\n}\n\ndouble VMCSolver::waveFunction(const mat &r)\n{\n    double argument = 0;\n    for(int i = 0; i < nParticles; i++) {\n        double rSingleParticle = 0;\n        for(int j = 0; j < nDimensions; j++) {\n            rSingleParticle += r(i,j) * r(i,j);\n        }\n        argument += sqrt(rSingleParticle);\n    }\n    return exp(-argument * alpha);\n}\n\n\n\ndouble VMCSolver::QuantumForce(const mat &r, mat &QForce)\n{\n    mat rPlus = zeros<mat>(nParticles, nDimensions);\n    mat rMinus = zeros<mat>(nParticles, nDimensions);\n\n    rPlus = rMinus = r;\n\n    double waveFunctionMinus = 0;\n    double waveFunctionPlus = 0;\n\n    double waveFunctionCurrent = waveFunction(r);\n\n    // Kinetic energy\n\n    double kineticEnergy = 0;\n    for(int i = 0; i < nParticles; i++) {\n        for(int j = 0; j < nDimensions; j++) {\n            rPlus(i,j) += h;\n            rMinus(i,j) -= h;\n            waveFunctionMinus = waveFunction(rMinus);\n            waveFunctionPlus = waveFunction(rPlus);\n            QForce(i,j) =  (waveFunctionPlus-waveFunctionMinus);\n            rPlus(i,j) = r(i,j);\n            rMinus(i,j) = r(i,j);\n        }\n    }\n}\n", "meta": {"hexsha": "3a9651c5b687e2463f3ce30b12d31498b6849f89", "size": 5746, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/pub/vmc/programs/c++/vmcsolver.cpp", "max_stars_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_stars_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 87.0, "max_stars_repo_stars_event_min_datetime": "2015-01-21T08:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T07:11:53.000Z", "max_issues_repo_path": "doc/pub/vmc/programs/c++/vmcsolver.cpp", "max_issues_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_issues_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-01-18T10:43:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T13:15:42.000Z", "max_forks_repo_path": "doc/pub/vmc/programs/c++/vmcsolver.cpp", "max_forks_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_forks_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2015-02-09T10:02:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T10:44:14.000Z", "avg_line_length": 29.0202020202, "max_line_length": 111, "alphanum_fraction": 0.5910198399, "num_tokens": 1682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5101428053363873}}
{"text": "#ifndef TRIUMF_SUPERCONDUCTIVITY_NONLOCAL_HPP\n#define TRIUMF_SUPERCONDUCTIVITY_NONLOCAL_HPP\n\n#include <cmath>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/quadrature/ooura_fourier_integrals.hpp>\n\n#include <triumf/superconductivity/bcs.hpp>\n#include <triumf/superconductivity/london.hpp>\n#include <triumf/superconductivity/pippard.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n//\nnamespace superconductivity {\n\n// nonlocal effects on superconductivity in the Meissner-Ochsenfeld state\nnamespace nonlocal {\n\n//\ntemplate <typename T = double>\nT B_z_pippard(const T z, const T B_0, const T K) {\n\n  // return the applied field if z isn't below the surface\n  if (z <= 0.0) {\n    return B_0;\n  }\n\n  // integrand for the sine transform\n  // using the Kernel for Pippard's model\n  auto integrand = [&, K](T q) {\n    // need to check if this is a reasaonble cutoff...\n    auto kappa = q > 1e-5 ? 1.0\n                          : (3.0 / 2.0) * ((1.0 + q * q) * std::atan(q) - q) /\n                                (q * q * q);\n    return q / (q * q + K * kappa);\n  };\n\n  // create the integrator w/ default tolerance and evaluation levels\n  // (root_epsilon and eight levels for type double).\n  static boost::math::quadrature::ooura_fourier_sin<T> integrator =\n      boost::math::quadrature::ooura_fourier_sin<T>();\n\n  // evaluate the integral, which returns a pair\n  // (first = integral, second = relative error)\n  std::pair<T, T> result = integrator.integrate(integrand, z);\n\n  // return the integral multiplied by the prefactors to get B vs. z\n  return boost::math::constants::two_div_pi<T>() * B_0 * result.first;\n}\n\n// \"extreme anomalous limit\"\ntemplate <typename T = double>\nauto B_z_extreme_anomalous_limit(const T z, const T B_0, const T K) {\n\n  // return the applied field if z isn't below the surface\n  if (z <= 0.0) {\n    return B_0;\n  }\n\n  // integrand for the sine transform\n  // using the Kernel for the \"extreme anomalous limit\"\n  auto integrand = [&, K](T q) { return q / (q * q + K / q); };\n\n  // create the integrator w/ default tolerance and evaluation levels\n  // (root_epsilon and eight levels for type double).\n  static boost::math::quadrature::ooura_fourier_sin<T> integrator =\n      boost::math::quadrature::ooura_fourier_sin<T>();\n\n  // evaluate the integral, which returns a pair\n  // (first = integral, second = relative error)\n  std::pair<T, T> result = integrator.integrate(integrand, z);\n\n  // return the integral multiplied by the prefactors to get B vs. z\n  return boost::math::constants::two_div_pi<T>() * B_0 * result.first;\n}\n\n// london\ntemplate <typename T = double>\nauto B_z_london(const T z, const T B_0, const T K) {\n\n  // return the applied field if z isn't below the surface\n  if (z <= 0.0) {\n    return B_0;\n  }\n\n  // integrand for the sine transform\n  // using the Kernel for the \"extreme anomalous limit\"\n  auto integrand = [&, K](T q) { return q / (q * q + K); };\n\n  // create the integrator w/ default tolerance and evaluation levels\n  // (root_epsilon and eight levels for type double).\n  static boost::math::quadrature::ooura_fourier_sin<T> integrator =\n      boost::math::quadrature::ooura_fourier_sin<T>();\n\n  // evaluate the integral, which returns a pair\n  // (first = integral, second = relative error)\n  std::pair<T, T> result = integrator.integrate(integrand, z);\n\n  // return the integral multiplied by the prefactors to get B vs. z\n  return boost::math::constants::two_div_pi<T>() * B_0 * result.first;\n}\n\n} // namespace nonlocal\n\n} // namespace superconductivity\n\n} // namespace triumf\n\n#endif // TRIUMF_SUPERCONDUCTIVITY_NONLOCAL_HPP\n", "meta": {"hexsha": "63804ad51b044389bbf97f748d248eb4bfcd5ad9", "size": 3632, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tmp/nonlocal.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": "tmp/nonlocal.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": "tmp/nonlocal.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": 32.1415929204, "max_line_length": 78, "alphanum_fraction": 0.686123348, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5101427962125699}}
{"text": "#include <cmath>\n#include <cstdio>\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n\tint fib = 42;\n\n    MatrixXd m(2, 2);\n    m << 0, 0, 0, 0;\n    EigenSolver<MatrixXd> mSolver(m);\n    cout << mSolver.eigenvectors() << \"\\n\";\n\n\tMatrixXcd T;\n\n\tT = MatrixXcd(3, 3);\n\n\tMatrixXd F(2, 2);\n\tF(0, 0) = 0;\n\tF(0, 1) = 1;\n\tF(1, 0) = 1;\n\tF(1, 1) = 1;\n\tEigenSolver<MatrixXd> eigensolver(F);\n\n\tMatrixXcd D = eigensolver.eigenvalues().asDiagonal();\n\tD(0, 0) = pow(D(0, 0), fib);\n\tD(1, 1) = pow(D(1, 1), fib);\n\n\tMatrixXcd P = eigensolver.eigenvectors();\n\tMatrixXcd Pinv = P.inverse();\n\tMatrixXcd S = (P * D * Pinv);\n\n\tcout << F << endl\n\t\t<< P << endl\n\t\t<< Pinv << endl\n\t\t<< D << endl\n\t\t<< S << endl;\n\n\tcout << \"fib(\" << fib << \"):\\n\";\n\tcout << S << endl;\n\tprintf(\"%.0f\\n\", round(real(S(1, 1))));\n\n\treturn 0;\n}\n", "meta": {"hexsha": "4d9d05dcdfdb0fc2d4320bd21dfad762b8d4fad6", "size": 918, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/eigen.cc", "max_stars_repo_name": "vedantk/auto-diagonalize", "max_stars_repo_head_hexsha": "ca8917ac13afc507c86e0ab2f62c2aa35030523c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-05-06T01:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-06T02:56:44.000Z", "max_issues_repo_path": "test/eigen.cc", "max_issues_repo_name": "vedantk/auto-diagonalize", "max_issues_repo_head_hexsha": "ca8917ac13afc507c86e0ab2f62c2aa35030523c", "max_issues_repo_licenses": ["MIT"], "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/eigen.cc", "max_forks_repo_name": "vedantk/auto-diagonalize", "max_forks_repo_head_hexsha": "ca8917ac13afc507c86e0ab2f62c2aa35030523c", "max_forks_repo_licenses": ["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": 54, "alphanum_fraction": 0.5708061002, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5100799722569271}}
{"text": "//////////////////////////////////////////////////////////////////////////////////\n// statistics::survival::response::right_truncated::detail::logit_log.hpp \t\t//\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_DISTRIBUTION_SURVIVAL_RESPONSE_RIGHT_TRUNCATED_LOGIT_LOG_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_RESPONSE_RIGHT_TRUNCATED_LOGIT_LOG_HPP_ER_2009\n#include <boost/statistics/detail/math/function/log_shift.hpp>\n#include <boost/statistics/detail/math/function/logit_shift.hpp>\n#include <boost/statistics/detail/survival/response/right_truncated/mean.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace survival{\nnamespace response{\n\ntemplate<typename T0,typename T1,typename T,typename B,typename ItO>\nItO logit_log_shift(\n    const T0& c0,\n    const T1& c1,\n    const mean_event<T,B>& m, \n    ItO o\n)\n{\n    (*o++) = statistics::detail::math::logit_shift(m.failure_time(),c0);\n    (*o++) = statistics::detail::math::log_shift(m.entry_time(),c1);\n    return o;\n}\n\ntemplate<typename T0,typename T,typename B,typename ItO>\nItO logit_log_shift(\n    const T0& c0,\n    const mean_event<T,B>& m, \n    ItO o\n)\n{\n    return logit_log(c0,c0,m,o);\n}\n\n}// response\n}// survival\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "336fe1c5bae7f2f490fbaee3f75f176053a62974", "size": 1649, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_survival/boost/statistics/detail/distribution/survival/response/types/right_truncated/detail/logit_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": "distribution_survival/boost/statistics/detail/distribution/survival/response/types/right_truncated/detail/logit_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": "distribution_survival/boost/statistics/detail/distribution/survival/response/types/right_truncated/detail/logit_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": 34.3541666667, "max_line_length": 100, "alphanum_fraction": 0.6167374166, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5100799610816574}}
{"text": "#include <iostream>\n#include <bitset>\n#include <boost/dynamic_bitset.hpp>\n\nusing namespace std;\n\nint bulbSwitch(int num){\n    if(num<=0) return 0;\n    boost::dynamic_bitset<> map(num);\n    int i,j;\n    for(j=1;j<=num;++j){\n        for(i=j;i<=num;++i){\n            if(i%j==0) map.flip(i-1);\n        }\n        //flag=!flag;\n    }\n    cout<<map.count()<<endl;\n}\n\nint main(int argc,char *argv[])\n{\n    //const int num = 3;\n    //bitset<num> map;\n    //vector<bool> map(false,num);\n    int num;\n    cin>>num;\n    boost::dynamic_bitset<> map(num);\n\n    int i,j;\n    for(j=1;j<=num;++j){\n        for(i=j;i<=num;++i){\n            if(i%j==0) map.flip(i-1);\n        }\n        //flag=!flag;\n        //cout<<map<<endl;\n    }\n    cout<<map.count()<<endl;\n    return 0;\n}\n", "meta": {"hexsha": "ce53a803d0a31a9da745eb41c4f79fe4a5108475", "size": 758, "ext": "cc", "lang": "C++", "max_stars_repo_path": "array/light-buln.cc", "max_stars_repo_name": "linghutf/leetcode", "max_stars_repo_head_hexsha": "641c87f7c1fc696e296323138c112a8f91c4761d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "array/light-buln.cc", "max_issues_repo_name": "linghutf/leetcode", "max_issues_repo_head_hexsha": "641c87f7c1fc696e296323138c112a8f91c4761d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "array/light-buln.cc", "max_forks_repo_name": "linghutf/leetcode", "max_forks_repo_head_hexsha": "641c87f7c1fc696e296323138c112a8f91c4761d", "max_forks_repo_licenses": ["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.95, "max_line_length": 37, "alphanum_fraction": 0.5, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959545, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5100654622292745}}
{"text": "/**\n * @file stabrk3_main.cc\n * @brief NPDE homework StabRK3 code\n * @author Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include \"stabrk3.h\"\n\nconst static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n                                       Eigen::DontAlignCols, \", \", \"\\n\");\n\nint main() {\n  double T = 1.0;\n  Eigen::Vector2d y0(100.0, 1.0);\n  Eigen::Vector2d yT_reference = StabRK3::predPrey(y0, T, 16384);\n  std::cout << \"Solution Computed by predPrey(): \"\n            << yT_reference.transpose().format(CSVFormat) << std::endl;\n\n  // Vector of number of steps (for convergence study)\n  std::vector<unsigned int> N_list = {4,   8,   16,   32,   64,   128,\n                                      256, 512, 1024, 2048, 4096, 8192};\n\n  // Compute approximations and take last one as reference\n  std::vector<Eigen::Vector2d> yT_list = StabRK3::simulatePredPrey(N_list);\n\n  // Compute the error table\n  std::cout << std::setw(15) << \"N\" << std::setw(15) << \"error\" << std::setw(15)\n            << \"rate\" << std::endl;\n  double error_old;\n  for (unsigned int j = 0; j < N_list.size(); ++j) {\n    double error = (yT_list[j] - yT_reference).norm();\n    std::cout << std::setw(15) << N_list[j] << std::setw(15) << error;\n    if (j > 0) {\n      std::cout << std::setw(15) << log2(error_old / error);\n    }\n    error_old = error;\n    std::cout << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "7db81a8672faa0bdcc437ec4aa15da59993a1851", "size": 1484, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/StabRK3/templates/stabrk3_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": "homeworks/StabRK3/templates/stabrk3_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": "homeworks/StabRK3/templates/stabrk3_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": 30.2857142857, "max_line_length": 80, "alphanum_fraction": 0.5882749326, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.5100654576847126}}
{"text": "/* Author: Xing Jin, Wolfgang Bangerth, Texas A&M University, 2006 */\n\n/*    $Id: step-24.cc 27657 2012-11-21 13:19:08Z bangerth $ */\n/*    Copyright (C) 2006-2009, 2011-2012 by the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n\n// @sect3{Include files}\n\n// The following have all been covered previously:\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\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/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/constraint_matrix.h>\n\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/grid/tria_boundary_lib.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <fstream>\n#include <iostream>\n\n// This is the only new one: We will need a library function defined in a\n// class GridTools that computes the minimal cell diameter.\n#include <deal.II/grid/grid_tools.h>\n\n// The last step is as in all previous programs:\nnamespace Step24\n{\n  using namespace dealii;\n\n  // @sect3{The \"forward problem\" class template}\n\n  // The first part of the main class is exactly as in step-23 (except for the\n  // name):\n  template <int dim>\n  class TATForwardProblem\n  {\n  public:\n    TATForwardProblem ();\n    void run ();\n\n  private:\n    void setup_system ();\n    void solve_p ();\n    void solve_v ();\n    void output_results () const;\n\n    Triangulation<dim>   triangulation;\n    FE_Q<dim>            fe;\n    DoFHandler<dim>      dof_handler;\n\n    ConstraintMatrix constraints;\n\n    SparsityPattern      sparsity_pattern;\n    SparseMatrix<double> system_matrix;\n    SparseMatrix<double> mass_matrix;\n    SparseMatrix<double> laplace_matrix;\n\n    Vector<double>       solution_p, solution_v;\n    Vector<double>       old_solution_p, old_solution_v;\n    Vector<double>       system_rhs_p, system_rhs_v;\n\n    double time, time_step;\n    unsigned int timestep_number;\n    const double theta;\n\n    //  Here's what's new: first, we need that boundary mass matrix $B$ that\n    //  came out of the absorbing boundary condition. Likewise, since this\n    //  time we consider a realistic medium, we must have a measure of the\n    //  wave speed $c_0$ that will enter all the formulas with the Laplace\n    //  matrix (which we still define as $(\\nabla \\phi_i,\\nabla \\phi_j)$):\n    SparseMatrix<double> boundary_matrix;\n    const double wave_speed;\n\n    // The last thing we have to take care of is that we wanted to evaluate\n    // the solution at a certain number of detector locations. We need an\n    // array to hold these locations, declared here and filled in the\n    // constructor:\n    std::vector<Point<dim> > detector_locations;\n  };\n\n\n  // @sect3{Equation data}\n\n  // As usual, we have to define our initial values, boundary conditions, and\n  // right hand side functions. Except things are a bit simpler this time: we\n  // are to consider a problem that is driven by initial conditions, so there\n  // is no right hand side function (though you could look up in step-23 to\n  // see how this can be done. Secondly, there are no boundary conditions: the\n  // entire boundary of the domain consists of absorbing boundary\n  // conditions. That only leaves initial conditions, and there things are\n  // simple too since for this particular application only nonzero initial\n  // conditions for the pressure are prescribed, not for the velocity (which\n  // is zero at the initial time).\n  //\n  // So this is all we need: a class that specifies initial conditions for the\n  // pressure. In the physical setting considered in this program, these are\n  // small absorbers, which we model as a series of little circles where we\n  // assume that the pressure surplus is one, whereas no absorption and\n  // therefore no pressure surplus is anywhere else. This is how we do things\n  // (note that if we wanted to expand this program to not only compile but\n  // also to run, we would have to initialize the sources with\n  // three-dimensional source locations):\n  template <int dim>\n  class InitialValuesP : public Function<dim>\n  {\n  public:\n    InitialValuesP ()\n      :\n      Function<dim>()\n    {}\n\n    virtual double value (const Point<dim> &p,\n                          const unsigned int  component = 0) const;\n\n  private:\n    struct Source\n    {\n      Source (const Point<dim> &l,\n              const double      r)\n        :\n        location (l),\n        radius (r)\n      {}\n\n      const Point<dim> location;\n      const double     radius;\n    };\n  };\n\n\n  template <int dim>\n  double InitialValuesP<dim>::value (const Point<dim> &p,\n                                     const unsigned int /*component*/) const\n  {\n    static const Source sources[] = {Source (Point<dim> (0, 0),         0.025),\n                                     Source (Point<dim> (-0.135, 0),    0.05),\n                                     Source (Point<dim> (0.17, 0),      0.03),\n                                     Source (Point<dim> (-0.25, 0),     0.02),\n                                     Source (Point<dim> (-0.05, -0.15), 0.015)\n                                    };\n    static const unsigned int n_sources = sizeof(sources)/sizeof(sources[0]);\n\n    for (unsigned int i=0; i<n_sources; ++i)\n      if (p.distance(sources[i].location) < sources[i].radius)\n        return 1;\n\n    return 0;\n  }\n\n\n  // @sect3{Implementation of the <code>TATForwardProblem</code> class}\n\n  // Let's start again with the constructor. Setting the member variables is\n  // straightforward. We use the acoustic wave speed of mineral oil (in\n  // millimeters per microsecond, a common unit in experimental biomedical\n  // imaging) since this is where many of the experiments we want to compare\n  // the output with are made in. The Crank-Nicolson scheme is used again,\n  // i.e. theta is set to 0.5. The time step is later selected to satisfy $k =\n  // \\frac hc$\n  template <int dim>\n  TATForwardProblem<dim>::TATForwardProblem ()\n    :\n    fe (1),\n    dof_handler (triangulation),\n    theta (0.5),\n    wave_speed (1.437)\n  {\n    // The second task in the constructor is to initialize the array that\n    // holds the detector locations. The results of this program were compared\n    // with experiments in which the step size of the detector spacing is 2.25\n    // degree, corresponding to 160 detector locations. The radius of the\n    // scanning circle is selected to be half way between the center and the\n    // boundary to avoid that the remaining reflections from the imperfect\n    // boundary condition spoils our numerical results.\n    //\n    // The locations of the detectors are then calculated in clockwise\n    // order. Note that the following of course only works if we are computing\n    // in 2d, a condition that we guard with an assertion. If we later wanted\n    // to run the same program in 3d, we would have to add code here for the\n    // initialization of detector locations in 3d. Due to the assertion, there\n    // is no way we can forget to do this.\n    Assert (dim == 2, ExcNotImplemented());\n\n    const double detector_step_angle = 2.25;\n    const double detector_radius = 0.5;\n\n    for (double detector_angle = 2*numbers::PI;\n         detector_angle >= 0;\n         detector_angle -= detector_step_angle/360*2*numbers::PI)\n      detector_locations.push_back (Point<dim> (std::cos(detector_angle),\n                                                std::sin(detector_angle)) *\n                                    detector_radius);\n  }\n\n\n\n  // @sect4{TATForwardProblem::setup_system}\n\n  // The following system is pretty much what we've already done in step-23,\n  // but with two important differences. First, we have to create a circular\n  // (or spherical) mesh around the origin, with a radius of 1. This nothing\n  // new: we've done so before in step-6, step-10, and step-11, where we also\n  // explain how to attach a boundary object to a triangulation to be used\n  // whenever the triangulation needs to know where new boundary points lie\n  // when a cell is refined. Following this, the mesh is refined a number of\n  // times.\n  //\n  // One thing we had to make sure is that the time step satisfies the CFL\n  // condition discussed in the introduction of step-23. Back in that program,\n  // we ensured this by hand by setting a timestep that matches the mesh\n  // width, but that was error prone because if we refined the mesh once more\n  // we would also have to make sure the time step is changed. Here, we do\n  // that automatically: we ask a library function for the minimal diameter of\n  // any cell. Then we set $k=\\frac h{c_0}$. The only problem is: what exactly\n  // is $h$? The point is that there is really no good theory on this question\n  // for the wave equation. It is known that for uniformly refined meshes\n  // consisting of rectangles, $h$ is the minimal edge length. But for meshes\n  // on general quadrilaterals, the exact relationship appears to be unknown,\n  // i.e. it is unknown what properties of cells are relevant for the CFL\n  // condition. The problem is that the CFL condition follows from knowledge\n  // of the smallest eigenvalue of the Laplace matrix, and that can only be\n  // computed analytically for simply structured meshes.\n  //\n  // The upshot of all this is that we're not quite sure what exactly we\n  // should take for $h$. The function GridTools::minimal_cell_diameter\n  // computes the minimal diameter of all cells. If the cells were all squares\n  // or cubes, then the minimal edge length would be the minimal diameter\n  // divided by <code>std::sqrt(dim)</code>. We simply generalize this,\n  // without theoretical justification, to the case of non-uniform meshes.\n  //\n  // The only other significant change is that we need to build the boundary\n  // mass matrix. We will comment on this further down below.\n  template <int dim>\n  void TATForwardProblem<dim>::setup_system ()\n  {\n    const Point<dim> center;\n    GridGenerator::hyper_ball (triangulation, center, 1.);\n    static const HyperBallBoundary<dim> boundary_description (center, 1.);\n    triangulation.set_boundary (0,boundary_description);\n    triangulation.refine_global (7);\n\n    time_step = GridTools::minimal_cell_diameter(triangulation) /\n                wave_speed /\n                std::sqrt (1.*dim);\n\n    std::cout << \"Number of active cells: \"\n              << triangulation.n_active_cells()\n              << std::endl;\n\n    dof_handler.distribute_dofs (fe);\n\n    std::cout << \"Number of degrees of freedom: \"\n              << dof_handler.n_dofs()\n              << std::endl\n              << std::endl;\n\n    sparsity_pattern.reinit (dof_handler.n_dofs(),\n                             dof_handler.n_dofs(),\n                             dof_handler.max_couplings_between_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);\n    sparsity_pattern.compress();\n\n    system_matrix.reinit (sparsity_pattern);\n    mass_matrix.reinit (sparsity_pattern);\n    laplace_matrix.reinit (sparsity_pattern);\n\n    MatrixCreator::create_mass_matrix (dof_handler, QGauss<dim>(3),\n                                       mass_matrix);\n    MatrixCreator::create_laplace_matrix (dof_handler, QGauss<dim>(3),\n                                          laplace_matrix);\n\n    // The second difference, as mentioned, to step-23 is that we need to\n    // build the boundary mass matrix that grew out of the absorbing boundary\n    // conditions.\n    //\n    // A first observation would be that this matrix is much sparser than the\n    // regular mass matrix, since none of the shape functions with purely\n    // interior support contributes to this matrix. We could therefore\n    // optimize the storage pattern to this situation and build up a second\n    // sparsity pattern that only contains the nonzero entries that we\n    // need. There is a trade-off to make here: first, we would have to have a\n    // second sparsity pattern object, so that costs memory. Secondly, the\n    // matrix attached to this sparsity pattern is going to be smaller and\n    // therefore requires less memory; it would also be faster to perform\n    // matrix-vector multiplications with it. The final argument, however, is\n    // the one that tips the scale: we are not primarily interested in\n    // performing matrix-vector with the boundary matrix alone (though we need\n    // to do that for the right hand side vector once per time step), but\n    // mostly wish to add it up to the other matrices used in the first of the\n    // two equations since this is the one that is going to be multiplied with\n    // once per iteration of the CG method, i.e. significantly more often. It\n    // is now the case that the SparseMatrix::add class allows to add one\n    // matrix to another, but only if they use the same sparsity pattern (the\n    // reason being that we can't add nonzero entries to a matrix after the\n    // sparsity pattern has been created, so we simply require that the two\n    // matrices have the same sparsity pattern).\n    //\n    // So let's go with that:\n    boundary_matrix.reinit (sparsity_pattern);\n\n    // The second thing to do is to actually build the matrix. Here, we need\n    // to integrate over faces of cells, so first we need a quadrature object\n    // that works on <code>dim-1</code> dimensional objects. Secondly, the\n    // FEFaceValues variant of FEValues that works on faces, as its name\n    // suggest. And finally, the other variables that are part of the assembly\n    // machinery. All of this we put between curly braces to limit the scope\n    // of these variables to where we actually need them.\n    //\n    // The actual act of assembling the matrix is then fairly straightforward:\n    // we loop over all cells, over all faces of each of these cells, and then\n    // do something only if that particular face is at the boundary of the\n    // domain. Like this:\n    {\n      const QGauss<dim-1>  quadrature_formula(3);\n      FEFaceValues<dim> fe_values (fe, quadrature_formula,\n                                   update_values  |  update_JxW_values);\n\n      const unsigned int   dofs_per_cell = fe.dofs_per_cell;\n      const unsigned int   n_q_points    = quadrature_formula.size();\n\n      FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n\n      std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n\n\n      typename DoFHandler<dim>::active_cell_iterator\n      cell = dof_handler.begin_active(),\n      endc = dof_handler.end();\n      for (; cell!=endc; ++cell)\n        for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)\n          if (cell->at_boundary(f))\n            {\n              cell_matrix = 0;\n\n              fe_values.reinit (cell, f);\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                  for (unsigned int j=0; j<dofs_per_cell; ++j)\n                    cell_matrix(i,j) += (fe_values.shape_value(i,q_point) *\n                                         fe_values.shape_value(j,q_point) *\n                                         fe_values.JxW(q_point));\n\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                  boundary_matrix.add (local_dof_indices[i],\n                                       local_dof_indices[j],\n                                       cell_matrix(i,j));\n            }\n\n    }\n\n    system_matrix.copy_from (mass_matrix);\n    system_matrix.add (time_step * time_step * theta * theta *\n                       wave_speed * wave_speed,\n                       laplace_matrix);\n    system_matrix.add (wave_speed * theta * time_step, boundary_matrix);\n\n\n    solution_p.reinit (dof_handler.n_dofs());\n    old_solution_p.reinit (dof_handler.n_dofs());\n    system_rhs_p.reinit (dof_handler.n_dofs());\n\n    solution_v.reinit (dof_handler.n_dofs());\n    old_solution_v.reinit (dof_handler.n_dofs());\n    system_rhs_v.reinit (dof_handler.n_dofs());\n\n    constraints.close ();\n  }\n\n\n  // @sect4{TATForwardProblem::solve_p and TATForwardProblem::solve_v}\n\n  // The following two functions, solving the linear systems for the pressure\n  // and the velocity variable, are taken pretty much verbatim (with the\n  // exception of the change of name from $u$ to $p$ of the primary variable)\n  // from step-23:\n  template <int dim>\n  void TATForwardProblem<dim>::solve_p ()\n  {\n    SolverControl           solver_control (1000, 1e-8*system_rhs_p.l2_norm());\n    SolverCG<>              cg (solver_control);\n\n    cg.solve (system_matrix, solution_p, system_rhs_p,\n              PreconditionIdentity());\n\n    std::cout << \"   p-equation: \" << solver_control.last_step()\n              << \" CG iterations.\"\n              << std::endl;\n  }\n\n\n  template <int dim>\n  void TATForwardProblem<dim>::solve_v ()\n  {\n    SolverControl           solver_control (1000, 1e-8*system_rhs_v.l2_norm());\n    SolverCG<>              cg (solver_control);\n\n    cg.solve (mass_matrix, solution_v, system_rhs_v,\n              PreconditionIdentity());\n\n    std::cout << \"   v-equation: \" << solver_control.last_step()\n              << \" CG iterations.\"\n              << std::endl;\n  }\n\n\n\n  // @sect4{TATForwardProblem::output_results}\n\n  // The same holds here: the function is from step-23.\n  template <int dim>\n  void TATForwardProblem<dim>::output_results () const\n  {\n    DataOut<dim> data_out;\n\n    data_out.attach_dof_handler (dof_handler);\n    data_out.add_data_vector (solution_p, \"P\");\n    data_out.add_data_vector (solution_v, \"V\");\n\n    data_out.build_patches ();\n\n    const std::string filename =  \"solution-\" +\n                                  Utilities::int_to_string (timestep_number, 3) +\n                                  \".gnuplot\";\n    std::ofstream output (filename.c_str());\n    data_out.write_gnuplot (output);\n  }\n\n\n\n  // @sect4{TATForwardProblem::run}\n\n  // This function that does most of the work is pretty much again like in\n  // step-23, though we make things a bit clearer by using the vectors G1 and\n  // G2 mentioned in the introduction. Compared to the overall memory\n  // consumption of the program, the introduction of a few temporary vectors\n  // isn't doing much harm.\n  //\n  // The only changes to this function are: First, that we do not have to\n  // project initial values for the velocity $v$, since we know that it is\n  // zero. And second that we evaluate the solution at the detector locations\n  // computed in the constructor. This is done using the\n  // VectorTools::point_value function. These values are then written to a\n  // file that we open at the beginning of the function.\n  template <int dim>\n  void TATForwardProblem<dim>::run ()\n  {\n    setup_system();\n\n    VectorTools::project (dof_handler, constraints,\n                          QGauss<dim>(3), InitialValuesP<dim>(),\n                          old_solution_p);\n    old_solution_v = 0;\n\n\n    std::ofstream detector_data(\"detectors.dat\");\n\n    Vector<double> tmp (solution_p.size());\n    Vector<double> G1 (solution_p.size());\n    Vector<double> G2 (solution_v.size());\n\n    const double end_time = 0.7;\n    for (timestep_number=1, time=time_step;\n         time<=end_time;\n         time+=time_step, ++timestep_number)\n      {\n        std::cout << std::endl;\n        std::cout<< \"time_step \" << timestep_number << \" @ t=\" << time << std::endl;\n\n        mass_matrix.vmult (G1, old_solution_p);\n        mass_matrix.vmult (tmp, old_solution_v);\n        G1.add(time_step * (1-theta), tmp);\n\n        mass_matrix.vmult (G2, old_solution_v);\n        laplace_matrix.vmult (tmp, old_solution_p);\n        G2.add (-wave_speed * wave_speed * time_step * (1-theta), tmp);\n\n        boundary_matrix.vmult (tmp, old_solution_p);\n        G2.add (wave_speed, tmp);\n\n        system_rhs_p = G1;\n        system_rhs_p.add(time_step * theta , G2);\n\n        solve_p ();\n\n\n        system_rhs_v = G2;\n        laplace_matrix.vmult (tmp, solution_p);\n        system_rhs_v.add (-time_step * theta * wave_speed * wave_speed, tmp);\n\n        boundary_matrix.vmult (tmp, solution_p);\n        system_rhs_v.add (-wave_speed, tmp);\n\n        solve_v ();\n\n        output_results ();\n\n\n        detector_data << time;\n        for (unsigned int i=0 ; i<detector_locations.size(); ++i)\n          detector_data << \" \"\n                        << VectorTools::point_value (dof_handler,\n                                                     solution_p,\n                                                     detector_locations[i])\n                        << \" \";\n        detector_data << std::endl;\n\n\n        old_solution_p = solution_p;\n        old_solution_v = solution_v;\n      }\n  }\n}\n\n\n\n// @sect3{The <code>main</code> function}\n\n// What remains is the main function of the program. There is nothing here\n// that hasn't been shown in several of the previous programs:\nint main ()\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step24;\n\n      deallog.depth_console (0);\n\n      TATForwardProblem<2> forward_problem_solver;\n      forward_problem_solver.run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << 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\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << 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": "dcccf3d8dcadf85c3eb5ba6bfc2f870d184957af", "size": 22702, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-24/step-24.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/step-24/step-24.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/step-24/step-24.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 38.5432937182, "max_line_length": 84, "alphanum_fraction": 0.635670866, "num_tokens": 5323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.5099992609702466}}
{"text": "/***************************************************************************\n                          prim_ottc.cc  -  description\n                             -------------------\n    begin                : Wed May 30 2007\n    copyright            : (C) 2005 by Knut-Helge Vik\n    email                : knuthelv@ifi.uio.no\n ***************************************************************************/\n\n#include \"prim_ottc.h\"\n#include \"treealgs.h\"\n#include \"fheap.h\"\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace boost;\nusing namespace std;\t\n\nnamespace TreeAlgorithms\n{\n\nbool OTTC(double D, const TreeStructure &Tin, TreeStructure &T, vertex_descriptorN src, const VertexSet &treeNodes)\n{\n\tconst GraphN &g = Tin.g;\n\t//cerr << WRITE_FUNCTION << \" src \" << src  << \" num_vertices \" << treeNodes.size() << endl;\n\t\n\tdEdgeMapConst wmap = get(&EdgeProp::weight, g);\n\tout_edge_iteratorN oit, oit_end;\n\tVertexSet::iterator vit, vit_end, vit_in, vit_in_end;\n\t\n\tvector<int> near(num_vertices(g));\n\tDistanceVector ecc(num_vertices(g));\n\tDistanceVector\t\tdiameter_bound(num_vertices(g));\n\tusing namespace boost::numeric::ublas;\n\tmatrix<double> dist(num_vertices(g), num_vertices(g));\n\t\n\tpair<int, double> nearest_vert(-1,(std::numeric_limits<double>::max)());\n\t\n\tfor(vit = treeNodes.begin(), vit_end = treeNodes.end(); vit != vit_end; ++vit)\n\t{\t\n\t\tdiameter_bound[*vit] = D;\n\t\tecc[*vit] = 0;\t\t\n\t\tif(*vit != src) \n\t\t{\n\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, src, g);\n\t\t\tif(ep.second) \n\t\t\t{\n\t\t\t\tnear[*vit] = src;\n\t\t\t\tif(nearest_vert.second > wmap[ep.first])\n\t\t\t\t{\n\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\tnearest_vert.second = wmap[ep.first];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse near[*vit] = -1;\n\t\t}\n\t\telse \n\t\t{\n\t\t\tnear[*vit] = 0;\n\t\t}\n\t\tfor(vit_in = treeNodes.begin(), vit_in_end = treeNodes.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\tdist(*vit,*vit_in) = 0;\n\t}\n\n\t// -- begin --\n\tT.insertVertex(src, g[src]);\n\tecc[src] = 0;\n\tdist(src,src) = 0;\n\tVertexSet notInTree = treeNodes - src;\n\t\n\twhile(1) //T.V.size() < treeNodes.size())\n\t{\n\t\tint z = nearest_vert.first;\n\t\t\n\t\tASSERTING(z > -1);\n\t\t//cerr << WRITE_FUNCTION << \" z \" << z << \" near[z] \" << near[z] << endl; \n\t\t//cerr << WRITE_FUNCTION << \" inserting edge (\" << z << \",\" << near[z] << \")\" << endl;\n\t\t\n\t\tT.insertVertex(z, g[z]);\n\t\tT.insertEdge(z, near[z], g);\n\t\tnotInTree = notInTree - z;\n\t\tif(notInTree.empty()) break;\n\n\t\t//cerr << WRITE_FUNCTION << \" not in tree \" << notInTree << endl;\n\t\t\n\t\tpair<edge_descriptorN, bool> edge_z_near = edge(z, near[z], g);\n\t\tASSERTING(edge_z_near.second);\n\t\t\n\t\t// set dist(z,u) and ecc(z)\n\t\tfor(vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tif(dist(near[z],*vit) > 0) dist(z,*vit) = dist(near[z],*vit) + wmap[edge_z_near.first];\n\t\t}\n\t\t\n\t\tdist(z,z) = 0;\n\t\tecc[z] = ecc[near[z]] + wmap[edge_z_near.first];\n\n\t\t// update dist(near(z), u) and ecc(near(z))\n\t\tdist(near[z],z) = wmap[edge_z_near.first];\n\t\tif(ecc[near[z]] <= 0) ecc[near[z]] = wmap[edge_z_near.first];\n\t\t\t\n\t\t// update other nodes' values of dist and ecc\n\t\tfor(vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tASSERTING(dist(*vit, near[z]) >= 0);\n\t\t\tASSERTING(dist(*vit, z) >= 0);\n\t\t\tASSERTING(ecc[*vit] >= 0);\n\n\t\t\tdist(*vit,z) = dist(*vit, near[z]) + wmap[edge_z_near.first];\n\t\t\tecc[*vit] = std::max(ecc[*vit], dist(*vit,z));\t\n\t\t}\n\t\t\n\t\t//cerr << \" update the near values for other nodes in G \" << endl;\n\t\tfor(vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tdouble weight_ep = (std::numeric_limits<double>::max)();\n\t\t\tdouble curr_ecc = (std::numeric_limits<double>::max)(); \n\t\t\tif(near[*vit] > -1) \n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, near[*vit], g);\n\t\t\t\tASSERTING(ep.second);\n\n\t\t\t\tcurr_ecc = ecc[near[*vit]] + wmap[ep.first];\n\t\t\t\tweight_ep = wmap[ep.first];\n\t\t\t}\n\n\t\t\tif(curr_ecc > diameter_bound[*vit])\n\t\t\t{\n\t\t\t\t//cerr << \" examine all nodes in T to determine near(\" << *vit << \")\t\" << endl;\n\t\t\t\tfor(vit_in = T.V.begin(), vit_in_end = T.V.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\t\t{\n\t\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, *vit_in, g);\n\t\t\t\t\tif(!ep.second) continue;\n\t\t\t\t\t\n\t\t\t\t\tdouble new_ecc = ecc[*vit_in] + wmap[ep.first]; \n\t\t\t\t\t//cerr << \" curr ecc \" << curr_ecc << \" new ecc \" << new_ecc << endl;\n\t\t\t\t\t\n\t\t\t\t\tif(new_ecc < curr_ecc)\n\t\t\t\t\t{ \n\t\t\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << *vit_in << endl;\n\t\t\t\t\t\tnear[*vit] = *vit_in;\n\t\t\t\t\t\tcurr_ecc = new_ecc;\n\t\t\t\t\t}\t\n\t\t\t\t}\n\t\t\t}\t\n\t\t\telse\n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> epz = edge(*vit, z, g);\n\t\t\t\tif(epz.second)\n\t\t\t\t{\n\t\t\t\t\t//cerr << \"Compare w(\" << *vit << \",\" << near[*vit] << \") = \" << weight_ep << \" to w(\" << *vit << \",\" <<  z << \")= \" << wmap[epz.first] << endl;\n\t\t\t\t\tif(wmap[epz.first] <= weight_ep)\n\t\t\t\t\t{\n\t\t\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << z << endl;\n\t\t\t\t\t\tnear[*vit] = z;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// -- fail safe --\n\t\tdouble failsafe = 0;\n\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\n\t\twhile(nearest_vert.first == -1)\n\t\t{\t\n\t\t\tVertexSet diameterBroken;\n\t\t\t// find new z\n\t\t\tfor(vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t\t{\n\t\t\t\tif(near[*vit] > -1) \n\t\t\t\t{\n\t\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, near[*vit], g);\n\t\t\t\t\tASSERTING(ep.second);\n\t\t\t\t\n\t\t\t\t\tif(ecc[near[*vit]] + wmap[ep.first] <= diameter_bound[*vit] && nearest_vert.second > wmap[ep.first])\n\t\t\t\t\t{\n\t\t\t\t\t\t//cerr << \" new z \" << *vit << endl;\n\t\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\t\tnearest_vert.second = wmap[ep.first]; \n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif(ecc[near[*vit]] + wmap[ep.first] > diameter_bound[*vit]) diameterBroken.insert(*vit);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(nearest_vert.first > -1) break;\n\t\t\t\n\t\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\t\t\t\n\t\t\tif(diameterBroken.empty()) return false;\n\t\t\tif(TreeAlgorithms::relaxDiameter(diameterBroken, diameter_bound) == false) return false;\n\t\t\t\n\t\t\t//ASSERTING(!diameterBroken.empty());\n\t\t\t// try to increase broken limits\n\t\t\t//for(VertexSet::iterator vit = diameterBroken.begin(), vit_end = diameterBroken.end(); vit != vit_end; ++vit)\n\t\t\t//{\n\t\t\t//\tdiameter_bound[*vit] = diameter_bound[*vit] + 0.1;\n\t\t\t\t//cerr << *vit << \" increased diameter bound \" <<  diameter_bound[*vit] << endl; \n\t\t\t//}\n\n\t\t\t// -- fail safe --\n\t\t\tif(failsafe++ >= ((std::numeric_limits<double>::max)() - 1)) break;\n\t\t}\t\n\t}\n\t//cerr << WRITE_PRETTY_FUNCTION << \" tree \" << T << endl;\n\n\treturn true;\n}\n\n\nbool dlOTTC(double D, const TreeStructure &Tin, TreeStructure &T, vertex_descriptorN src, const VertexSet &treeNodes)\n{\n\tconst GraphN &g = Tin.g;\n\t//cerr << WRITE_FUNCTION << \" src \" << src  << \" num_vertices \" << treeNodes.size() << endl;\n\t\n\tdEdgeMapConst \t\twmap = get(&EdgeProp::weight, g);\n\tout_edge_iteratorN \toit, oit_end;\n\t\n\tvector<int> \t\tnear(num_vertices(g));\n\tDistanceVector \t\tecc(num_vertices(g));\n\tDistanceVector\t\tdiameter_bound(num_vertices(g));\n\tDistanceVector\t\tdegree_bound(num_vertices(g));\n\tusing namespace \tboost::numeric::ublas;\n\tmatrix<double> \t\tdist(num_vertices(g), num_vertices(g));\n\tpair<int, double> \tnearest_vert(-1,(std::numeric_limits<double>::max)());\n\tint \t\t\t\tdegreeLeverage = 0;\n\t\n\tfor(VertexSet::iterator vit = treeNodes.begin(), vit_end = treeNodes.end(); vit != vit_end; ++vit)\n\t{\n\t\tdegree_bound[*vit] = getDegreeConstraint(g, *vit);\n\t\tdiameter_bound[*vit] = D;\n\t\tecc[*vit] = 0;\t\t\n\t\tif(*vit != src) \n\t\t{\n\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, src, g);\n\t\t\tif(ep.second) \n\t\t\t{\n\t\t\t\tnear[*vit] = src;\n\t\t\t\tif(nearest_vert.second > wmap[ep.first])\n\t\t\t\t{\n\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\tnearest_vert.second = wmap[ep.first];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse near[*vit] = -1;\n\t\t}\n\t\telse \n\t\t{\n\t\t\tnear[*vit] = 0;\n\t\t}\n\t\tfor(VertexSet::iterator vit_in = treeNodes.begin(), vit_in_end = treeNodes.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\tdist(*vit,*vit_in) = 0;\n\t}\n\n\t// -- begin --\n\tT.insertVertex(src, g[src]);\n\tecc[src] = 0;\n\tdist(src,src) = 0;\n\tVertexSet notInTree = treeNodes - src;\n\t\n\twhile(1) \n\t{\n\t\tint z = nearest_vert.first;\n\t\n\t\t//cerr << WRITE_FUNCTION << \" z \" << z << \" near[z] \" << near[z] << endl; \n\t\t//cerr << WRITE_FUNCTION << \" inserting edge (\" << z << \",\" << near[z] << \")\" << endl;\n\n\t\tASSERTING(z > -1);\n\t\tASSERTING(notInTree.contains(z));\n\t\tASSERTING(T.V.contains(near[z]));\n\t\t\n\t\tT.insertVertex(z, g[z]);\n\t\tT.insertEdge(z, near[z], g);\n\t\tASSERTING(degree_bound[near[z]] >= getOutDegree(T.g, near[z]));\n\t\tnotInTree = notInTree - z;\n\t\tif(notInTree.empty()) break;\n\t\t\n\t\t//cerr << WRITE_FUNCTION << \" not in tree \" << notInTree << endl;\n\t\t\n\t\tpair<edge_descriptorN, bool> edge_z_near = edge(z, near[z], g);\n\t\tASSERTING(edge_z_near.second);\n\t\t\n\t\t// set dist(z,u) and ecc(z)\n\t\tfor(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tif(dist(near[z],*vit) > 0) dist(z,*vit) = dist(near[z],*vit) + wmap[edge_z_near.first];\n\t\t}\n\t\t\n\t\tdist(z,z) = 0;\n\t\tecc[z] = ecc[near[z]] + wmap[edge_z_near.first];\n\n\t\t// update dist(near(z), u) and ecc(near(z))\n\t\tdist(near[z],z) = wmap[edge_z_near.first];\n\t\tif(ecc[near[z]] <= 0) ecc[near[z]] = wmap[edge_z_near.first];\n\t\t\t\n\t\t// update other nodes' values of dist and ecc\n\t\tfor(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tASSERTING(dist(*vit, near[z]) >= 0);\n\t\t\tASSERTING(dist(*vit, z) >= 0);\n\t\t\tASSERTING(ecc[*vit] >= 0);\n\n\t\t\tdist(*vit,z) = dist(*vit, near[z]) + wmap[edge_z_near.first];\n\t\t\tecc[*vit] = std::max(ecc[*vit], dist(*vit,z));\t\n\t\t}\n\t\t\n\t\t//cerr << \" update the near values for other nodes in G \" << endl;\n\t\tfor(VertexSet::iterator vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tdouble dc_near_vit = (numeric_limits<double>::max)(), od_near_vit = 0; \n\t\t\tif(near[*vit] > -1) \n\t\t\t{\n\t\t\t\tdc_near_vit = degree_bound[near[*vit]]; \n\t\t\t\tod_near_vit = getOutDegree(T.g, near[*vit]);\n\t\t\t}\n\n\t\t\tdouble weight_ep = (std::numeric_limits<double>::max)();\n\t\t\tdouble curr_ecc = (std::numeric_limits<double>::max)(); \n\t\t\tif(near[*vit] > -1 && od_near_vit < dc_near_vit) \n\t\t\t{\n\t\t\t\t//cerr << \" edge (\" << *vit << \",\" << near[*vit] << \")\" << endl;\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, near[*vit], g);\n\t\t\t\tASSERTING(ep.second);\n\n\t\t\t\tcurr_ecc = ecc[near[*vit]] + wmap[ep.first];\n\t\t\t\tweight_ep = wmap[ep.first];\n\t\t\t}\n\t\t\n\t\t\t//if(curr_ecc > diameter_bound[*vit] || (od_near_vit >= dc_near_vit && getOutDegree(T.g, z) >= degree_bound[z]) )  \n\t\t\tif(curr_ecc > diameter_bound[*vit] || getOutDegree(T.g, z) >= degree_bound[z])\n\t\t\t{\n\t\t\t\t//cerr << \" examine all nodes in T to determine near(\" << *vit << \")\t\" << endl;\n\t\t\t\tfor(VertexSet::iterator vit_in = T.V.begin(), vit_in_end = T.V.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\t\t{\n\t\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, *vit_in, g);\n\t\t\t\t\tif(!ep.second) continue;\n\t\t\t\t\t\n\t\t\t\t\tdouble new_ecc = ecc[*vit_in] + wmap[ep.first]; //1;\n\t\t\t\t\t//cerr << \" curr ecc \" << curr_ecc << \" new ecc \" << new_ecc << endl;\n\t\t\t\t\n\t\t\t\t\tif(new_ecc < curr_ecc && getOutDegree(T.g, *vit_in) < degree_bound[*vit_in] )  \n\t\t\t\t\t{ \n\t\t\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << *vit_in << endl;\n\t\t\t\t\t\tnear[*vit] = *vit_in;\n\t\t\t\t\t\tcurr_ecc = new_ecc;\n\t\t\t\t\t}\t\n\t\t\t\t}\n\t\t\t}\t\n\t\t\telse\n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> epz = edge(*vit, z, g);\n\t\t\t\tif(epz.second)\n\t\t\t\t{\t\t\t\t\n\t\t\t\t\t//cerr << \"Compare w(\" << *vit << \",\" << near[*vit] << \") = \" << weight_ep << \" to w(\" << *vit << \",\" <<  z << \")= \" << wmap[epz.first] << endl;\n\t\t\t\t\tif(wmap[epz.first] <= weight_ep && getOutDegree(T.g, z) < degree_bound[z])\n\t\t\t\t\t{\n\t\t\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << z << endl;\n\t\t\t\t\t\tnear[*vit] = z;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// -- fail safe --\n\t\tdouble failsafe = 0;\n\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\t\t\n\t\twhile(nearest_vert.first == -1)\n\t\t{\t\n\t\t\tVertexSet diameterBroken, degreeBroken;\t\n\t\t\t// find new z\n\t\t\tfor(VertexSet::iterator vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t\t{\n\t\t\t\tif(near[*vit] > -1) \n\t\t\t\t{\n\t\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, near[*vit], g);\n\t\t\t\t\tASSERTING(ep.second);\n\n\t\t\t\t\tdouble dc_near_vit = degree_bound[near[*vit]];\n\t\t\t\t\tdouble od_near_vit = getOutDegree(T.g, near[*vit]);\n\n\t\t\t\t\tif(ecc[near[*vit]] + wmap[ep.first] <= diameter_bound[*vit] && nearest_vert.second > wmap[ep.first] && od_near_vit < dc_near_vit)\n\t\t\t\t\t{\n\t\t\t\t\t\t//cerr << \" new z \" << *vit << endl;\n\t\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\t\tnearest_vert.second = wmap[ep.first]; \n\t\t\t\t\t}\n\n\t\t\t\t\tif(ecc[near[*vit]] + wmap[ep.first] > diameter_bound[*vit]) diameterBroken.insert(*vit);\n\t\t\t\t\tif(od_near_vit >= dc_near_vit) degreeBroken.insert(near[*vit]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(nearest_vert.first > -1) break;\n\t\t\n\t\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\n\t\t\tif(!TreeAlgorithms::relaxDegreeAndDiameter(degreeBroken, degree_bound, diameterBroken, diameter_bound)) return false; \n\t\t\tif(!TreeAlgorithms::isRelaxWorking(degreeBroken, diameterBroken)) return false;\n\t\t\t\n\t\t\t// -- fail safe --\n\t\t\tif(failsafe++ >= ((std::numeric_limits<double>::max)() - 1)) break;\n\t\t}\t\n\t}\n\t\n\t//cerr << WRITE_PRETTY_FUNCTION << \" tree \" << T << endl;\n\treturn true;\n}\n\n\nbool mdOTTC(const TreeStructure &Tin, TreeStructure &T, vertex_descriptorN src, const VertexSet &treeNodes)\n{\n\tconst GraphN &g = Tin.g;\n\t//cerr << WRITE_FUNCTION << \" src \" << src  << \" num_vertices \" << treeNodes.size() << endl;\n\t\n\tdEdgeMapConst wmap = get(&EdgeProp::weight, g);\n\tout_edge_iteratorN oit, oit_end;\n\tVertexSet::iterator vit, vit_end, vit_in, vit_in_end;\n\t\n\tvector<int> near(num_vertices(g));\n\tDistanceVector ecc(num_vertices(g));\n\tusing namespace boost::numeric::ublas;\n\tmatrix<double> dist(num_vertices(g), num_vertices(g));\n\t\n\tpair<int, double> nearest_vert(-1,(std::numeric_limits<double>::max)());\n\t\n\tfor(vit = treeNodes.begin(), vit_end = treeNodes.end(); vit != vit_end; ++vit)\n\t{\t\n\t\tecc[*vit] = 0;\t\t\n\t\tif(*vit != src) \n\t\t{\n\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, src, g);\n\t\t\tif(ep.second) \n\t\t\t{\n\t\t\t\tnear[*vit] = src;\n\t\t\t\tif(nearest_vert.second > wmap[ep.first])\n\t\t\t\t{\n\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\tnearest_vert.second = wmap[ep.first];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse near[*vit] = -1;\n\t\t}\n\t\telse \n\t\t{\n\t\t\tnear[*vit] = 0;\n\t\t}\n\t\tfor(vit_in = treeNodes.begin(), vit_in_end = treeNodes.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\tdist(*vit,*vit_in) = 0;\n\t}\n\n\t// -- begin --\n\tT.insertVertex(src, g[src]);\n\tecc[src] = 0;\n\tdist(src,src) = 0;\n\tVertexSet notInTree = treeNodes - src;\n\t\n\twhile(1) \t\n\t{\n\t\tint z = nearest_vert.first;\n\t\tASSERTING(z > -1);\n\t\t\n\t\t//cerr << WRITE_FUNCTION << \" z \" << z << \" near[z] \" << near[z] << endl; \n\t\t//cerr << WRITE_FUNCTION << \" inserting edge (\" << z << \",\" << near[z] << \")\" << endl;\n\t\t\n\t\tT.insertVertex(z, g[z]);\n\t\tT.insertEdge(z, near[z], g);\n\t\tnotInTree = notInTree - z;\n\t\tif(notInTree.empty()) break;\n\n\t\t//cerr << WRITE_FUNCTION << \" not in tree \" << notInTree << endl;\n\t\t\n\t\tpair<edge_descriptorN, bool> edge_z_near = edge(z, near[z], g);\n\t\tASSERTING(edge_z_near.second);\n\t\t\n\t\t// set dist(z,u) and ecc(z)\n\t\tfor(vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tif(dist(near[z],*vit) > 0) dist(z,*vit) = dist(near[z],*vit) + wmap[edge_z_near.first];\n\t\t}\n\t\t\n\t\tdist(z,z) = 0;\n\t\tecc[z] = ecc[near[z]] + wmap[edge_z_near.first];\n\n\t\t// update dist(near(z), u) and ecc(near(z))\n\t\tdist(near[z],z) = wmap[edge_z_near.first];\n\t\tif(ecc[near[z]] <= 0) ecc[near[z]] = wmap[edge_z_near.first];\n\t\t\t\n\t\t// update other nodes' values of dist and ecc\n\t\tfor(vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tASSERTING(dist(*vit, near[z]) >= 0);\n\t\t\tASSERTING(dist(*vit, z) >= 0);\n\t\t\tASSERTING(ecc[*vit] >= 0);\n\n\t\t\tdist(*vit,z) = dist(*vit, near[z]) + wmap[edge_z_near.first];\n\t\t\tecc[*vit] = std::max(ecc[*vit], dist(*vit,z));\t\n\t\t}\n\t\t\n\t\t//cerr << \" update the near values for other nodes in G \" << endl;\n\t\tfor(vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tdouble curr_ecc = (std::numeric_limits<double>::max)(); \n\t\t\t//cerr << \" examine all nodes in T to determine near(\" << *vit << \")\t\" << endl;\n\t\t\tfor(vit_in = T.V.begin(), vit_in_end = T.V.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, *vit_in, g);\n\t\t\t\tif(!ep.second) continue;\n\t\t\t\t\t\n\t\t\t\tdouble new_ecc = ecc[*vit_in] + wmap[ep.first]; \n\t\t\t\t//cerr << \" curr ecc \" << curr_ecc << \" new ecc \" << new_ecc << endl;\n\t\t\t\t\t\n\t\t\t\tif(new_ecc < curr_ecc)\n\t\t\t\t{ \n\t\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << *vit_in << endl;\n\t\t\t\t\tnear[*vit] = *vit_in;\n\t\t\t\t\tcurr_ecc = new_ecc;\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\n\t\t// find new z\n\t\tfor(vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tif(near[*vit] > -1) \n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, near[*vit], g);\n\t\t\t\tASSERTING(ep.second);\n\t\t\t\t\t\n\t\t\t\tdouble new_ecc = ecc[near[*vit]] + wmap[ep.first];\n\t\t\t\tif(nearest_vert.second > new_ecc) \n\t\t\t\t{\n\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\tnearest_vert.second = new_ecc; \n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(nearest_vert.first < 0) break;\n\t\tASSERTING(nearest_vert.first > -1);\n\t}\n\n\tif(!notInTree.empty()) return false;\n\n\treturn true;\n}\n\nbool mddlOTTC(const TreeStructure &Tin, TreeStructure &T, vertex_descriptorN src, const VertexSet &treeNodes)\n{\n\tconst GraphN &g = Tin.g;\n\t//cerr << WRITE_FUNCTION << \" src \" << src  << \" num_vertices \" << treeNodes.size() << \" treeNodes \" << treeNodes << endl;\n\t\n\tdEdgeMapConst \t\twmap = get(&EdgeProp::weight, g);\n\tout_edge_iteratorN \toit, oit_end;\n\t\n\tvector<int> \t\tnear(num_vertices(g));\n\tDistanceVector \t\tecc(num_vertices(g));\n\tDistanceVector\t\tdegree_bound(num_vertices(g));\n\tusing namespace \tboost::numeric::ublas;\n\tmatrix<double> \t\tdist(num_vertices(g), num_vertices(g));\n\tpair<int, double> \tnearest_vert(-1,(std::numeric_limits<double>::max)());\n\tint \t\t\t\tdegreeLeverage = 0;\n\t\n\tfor(VertexSet::iterator vit = treeNodes.begin(), vit_end = treeNodes.end(); vit != vit_end; ++vit)\n\t{\n\t\tdegree_bound[*vit] = getDegreeConstraint(g, *vit);\n\t\tecc[*vit] = 0;\t\t\n\t\tif(*vit != src) \n\t\t{\n\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, src, g);\n\t\t\tif(ep.second) \n\t\t\t{\n\t\t\t\tnear[*vit] = src;\n\t\t\t\tif(nearest_vert.second > wmap[ep.first])\n\t\t\t\t{\n\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\tnearest_vert.second = wmap[ep.first];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse near[*vit] = -1;\n\t\t}\n\t\telse \n\t\t{\n\t\t\tnear[*vit] = 0;\n\t\t}\n\t\tfor(VertexSet::iterator vit_in = treeNodes.begin(), vit_in_end = treeNodes.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\tdist(*vit,*vit_in) = 0;\n\t}\n\t\n\tASSERTING(nearest_vert.first > -1);\n\n\t// -- begin --\n\tT.insertVertex(src, g[src]);\n\tecc[src] = 0;\n\tdist(src,src) = 0;\n\tVertexSet notInTree = treeNodes - src;\n\n\twhile(1) \n\t{\n\t\tint z = nearest_vert.first;\n\t\n\t\t//cerr << WRITE_FUNCTION << \" z \" << z << \" near[z] \" << near[z] << endl; \n\t\t//cerr << WRITE_FUNCTION << \" inserting edge (\" << z << \",\" << near[z] << \")\" << \" out degree : \" << getOutDegree(T.g, near[z]) << endl;\n\n\t\tASSERTING(z > -1);\n\t\tASSERTING(notInTree.contains(z));\n\t\tASSERTING(T.V.contains(near[z]));\n\t\t\n\t\tT.insertVertex(z, g[z]);\n\t\tT.insertEdge(z, near[z], g);\n\t\tASSERTING(degree_bound[near[z]] >= getOutDegree(T.g, near[z]));\n\n\t\tnotInTree = notInTree - z;\n\t\tif(notInTree.empty()) break;\n\t\t\n\t\t//cerr << WRITE_FUNCTION << \" not in tree \" << notInTree << endl;\n\t\t\n\t\tpair<edge_descriptorN, bool> edge_z_near = edge(z, near[z], g);\n\t\tASSERTING(edge_z_near.second);\n\t\t\n\t\t// set dist(z,u) and ecc(z)\n\t\tfor(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tif(dist(near[z],*vit) > 0) dist(z,*vit) = dist(near[z],*vit) + wmap[edge_z_near.first];\n\t\t}\n\t\t\n\t\tdist(z,z) = 0;\n\t\tecc[z] = ecc[near[z]] + wmap[edge_z_near.first];\n\n\t\t// update dist(near(z), u) and ecc(near(z))\n\t\tdist(near[z],z) = wmap[edge_z_near.first];\n\t\tif(ecc[near[z]] <= 0) ecc[near[z]] = wmap[edge_z_near.first];\n\t\t\t\n\t\t// update other nodes' values of dist and ecc\n\t\tfor(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tASSERTING(dist(*vit, near[z]) >= 0);\n\t\t\tASSERTING(dist(*vit, z) >= 0);\n\t\t\tASSERTING(ecc[*vit] >= 0);\n\n\t\t\tdist(*vit,z) = dist(*vit, near[z]) + wmap[edge_z_near.first];\n\t\t\tecc[*vit] = std::max(ecc[*vit], dist(*vit,z));\t\n\t\t}\n\t\t\n\t\t//cerr << \" update the near values for other nodes in G \" << endl;\n\t\tfor(VertexSet::iterator vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tdouble curr_ecc = (std::numeric_limits<double>::max)(); \n\t\t\t//cerr << \" examine all nodes in T to determine near(\" << *vit << \")\t\" << endl;\n\t\t\tfor(VertexSet::iterator vit_in = T.V.begin(), vit_in_end = T.V.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, *vit_in, g);\n\t\t\t\tif(!ep.second) continue;\n\t\t\t\t\t\n\t\t\t\tdouble new_ecc = ecc[*vit_in] + wmap[ep.first]; \n\t\t\t\tif(T.V.size() > 1) ASSERTING(ecc[*vit_in] > 0);\n\t\t\t\t\n\t\t\t\t//cerr << \" curr ecc \" << curr_ecc << \" new ecc \" << new_ecc << endl;\n\t\t\t\t\n\t\t\t\tif(new_ecc < curr_ecc && getOutDegree(T.g, *vit_in) < degree_bound[*vit_in] ) \n\t\t\t\t{ \n\t\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << *vit_in << endl;\n\t\t\t\t\tnear[*vit] = *vit_in;\n\t\t\t\t\tcurr_ecc = new_ecc;\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t\t\n\t\t// -- fail safe --\n\t\tdouble failsafe = 0;\n\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\t\t\n\t\twhile(nearest_vert.first < 0)\n\t\t{\t\n\t\t\tVertexSet degreeBroken;\t\n\t\t\t// find new z\n\t\t\tfor(VertexSet::iterator vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t\t{\n\t\t\t\tif(near[*vit] > -1) \n\t\t\t\t{\n\t\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, near[*vit], g);\n\t\t\t\t\tASSERTING(ep.second);\n\n\t\t\t\t\tdouble dc_near_vit = degree_bound[near[*vit]];\n\t\t\t\t\tdouble od_near_vit = getOutDegree(T.g, near[*vit]);\n\t\t\t\t\n\t\t\t\t\tif(T.V.size() > 1) ASSERTING(od_near_vit > 0);\n\t\t\t\t\t\n\t\t\t\t\tdouble new_ecc = ecc[near[*vit]] + wmap[ep.first];\n\t\t\t\t\tif(nearest_vert.second > new_ecc && od_near_vit < dc_near_vit) \n\t\t\t\t\t{\n\t\t\t\t\t\t//cerr << \" new z \" << *vit << endl;\n\t\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\t\tnearest_vert.second = new_ecc; \n\t\t\t\t\t}\n\n\t\t\t\t\tif(od_near_vit >= dc_near_vit) degreeBroken.insert(near[*vit]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(nearest_vert.first > -1) break;\n\t\t\n\t\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\t\n\t\t\t//ASSERTING(!degreeBroken.empty());\n\t\t\tif(degreeBroken.empty()) return false;\n\t\t\tif(TreeAlgorithms::relaxDegree(degreeBroken, degree_bound) == false)\n\t\t\t\treturn false;\n\n\t\t\t// -- fail safe --\n\t\t\tif(failsafe++ >= ((std::numeric_limits<double>::max)() - 1)) break;\n\t\t}\t\n\t}\n\n\tif(!notInTree.empty()) return false;\n\n\treturn true;\n}\n\n\n/* -------------------------------------------------------------------------\n\t\n\t\t\t\tOTTC(): distance and parent\n\n------------------------------------------------------------------------- */\n\nbool OTTC(double D, const GraphN &g, vertex_descriptorN src, DistanceVector &distance, ParentVector &parent, const VertexSet &treeNodes)\n{\n\t//cerr << WRITE_FUNCTION << \" src \" << src  << \" num_vertices \" << treeNodes.size() << \" \"  << num_vertices(g) << endl;\n\t\n\tVertexSet inTree;\n\tdEdgeMapConst wmap = get(&EdgeProp::weight, g);\n\tout_edge_iteratorN oit, oit_end;\n\tVertexSet::iterator vit, vit_end, vit_in, vit_in_end;\n\t\n\tvector<int> \tnear(num_vertices(g));\n\tDistanceVector \tecc(num_vertices(g));\n\tDistanceVector\tdiameter_bound(num_vertices(g));\n\tusing namespace boost::numeric::ublas;\n\tmatrix<double> \tdist(num_vertices(g), num_vertices(g));\n\t\n\tpair<int, double> nearest_vert(-1,(std::numeric_limits<double>::max)());\n\t\n\tfor(vit = treeNodes.begin(), vit_end = treeNodes.end(); vit != vit_end; ++vit)\n\t{\n\t\tdistance[*vit] = (std::numeric_limits<double>::max)();\n\t\tparent[*vit] = *vit;\t\n\t\t\n\t\tdiameter_bound[*vit] = D;\n\t\tecc[*vit] = 0;\t\t\n\t\tif(*vit != src) \n\t\t{\n\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, src, g);\n\t\t\tif(ep.second) \n\t\t\t{\n\t\t\t\tnear[*vit] = src;\n\t\t\t\tif(nearest_vert.second > wmap[ep.first])\n\t\t\t\t{\n\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\tnearest_vert.second = wmap[ep.first];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse near[*vit] = -1;\n\t\t}\n\t\telse \n\t\t{\n\t\t\tnear[*vit] = 0;\n\t\t}\n\t\tfor(vit_in = treeNodes.begin(), vit_in_end = treeNodes.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\tdist(*vit,*vit_in) = 0;\n\t}\n\n\t// -- begin --\n\tinTree.insert(src);\n\tecc[src] = 0;\n\tdist(src,src) = 0;\n\tdistance[src] = 0;\n\tVertexSet notInTree = treeNodes - src;\n\t\n\twhile(1) //T.V.size() < treeNodes.size())\n\t{\n\t\tint z = nearest_vert.first;\n\t\t\n\t\tASSERTING(z > -1);\n\t\t//cerr << WRITE_FUNCTION << \" z \" << z << \" near[z] \" << near[z] << endl; \n\t\t//cerr << WRITE_FUNCTION << \" inserting edge (\" << z << \",\" << near[z] << \")\" << endl;\n\t\t\n\t\tinTree.insert(z);\n\t\t\t\t\n\t\tpair<edge_descriptorN, bool> edge_z_near = edge(z, near[z], g);\n\t\tASSERTING(edge_z_near.second);\t\t\n\t\t\n\t\t// distance/parent\n\t\tdistance[z] = g[edge_z_near.first].weight;\n\t\tparent[z] = near[z];\n\t\t\n\t\tnotInTree = notInTree - z;\n\t\tif(notInTree.empty()) break;\n\n\t\t//cerr << WRITE_FUNCTION << \" not in tree \" << notInTree << endl;\n\t\t//cerr << WRITE_FUNCTION << \" in tree \" << T.V << endl;\n\t\t\n\t\t// set dist(z,u) and ecc(z)\n\t\tfor(vit = inTree.begin(), vit_end = inTree.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tif(dist(near[z],*vit) > 0) dist(z,*vit) = dist(near[z],*vit) + wmap[edge_z_near.first];\n\t\t}\n\t\t\n\t\tdist(z,z) = 0;\n\t\tecc[z] = ecc[near[z]] + wmap[edge_z_near.first];\n\n\t\t// update dist(near(z), u) and ecc(near(z))\n\t\tdist(near[z],z) = wmap[edge_z_near.first];\n\t\tif(ecc[near[z]] <= 0) ecc[near[z]] = wmap[edge_z_near.first];\n\t\t\t\n\t\t// update other nodes' values of dist and ecc\n\t\tfor(vit = inTree.begin(), vit_end = inTree.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tASSERTING(dist(*vit, near[z]) >= 0);\n\t\t\tASSERTING(dist(*vit, z) >= 0);\n\t\t\tASSERTING(ecc[*vit] >= 0);\n\n\t\t\tdist(*vit,z) = dist(*vit, near[z]) + wmap[edge_z_near.first];\n\t\t\tecc[*vit] = std::max(ecc[*vit], dist(*vit,z));\t\n\t\t}\n\t\t\n\t\t//cerr << \" update the near values for other nodes in G \" << endl;\n\t\tfor(vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tdouble weight_ep = (std::numeric_limits<double>::max)();\n\t\t\tdouble curr_ecc = (std::numeric_limits<double>::max)(); \n\t\t\tif(near[*vit] > -1) \n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, near[*vit], g);\n\t\t\t\tASSERTING(ep.second);\n\n\t\t\t\tcurr_ecc = ecc[near[*vit]] + wmap[ep.first];\n\t\t\t\tweight_ep = wmap[ep.first];\n\t\t\t}\n\n\t\t\tif(curr_ecc > diameter_bound[*vit])\n\t\t\t{\n\t\t\t\t//cerr << \" examine all nodes in T to determine near(\" << *vit << \")\t\" << endl;\n\t\t\t\tfor(vit_in = inTree.begin(), vit_in_end = inTree.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\t\t{\n\t\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, *vit_in, g);\n\t\t\t\t\tif(!ep.second) continue;\n\t\t\t\t\t\n\t\t\t\t\tdouble new_ecc = ecc[*vit_in] + wmap[ep.first]; \n\t\t\t\t\t//cerr << \" curr ecc \" << curr_ecc << \" new ecc \" << new_ecc << endl;\n\t\t\t\t\t\n\t\t\t\t\tif(new_ecc < curr_ecc)\n\t\t\t\t\t{ \n\t\t\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << *vit_in << endl;\n\t\t\t\t\t\tnear[*vit] = *vit_in;\n\t\t\t\t\t\tcurr_ecc = new_ecc;\n\t\t\t\t\t}\t\n\t\t\t\t}\n\t\t\t}\t\n\t\t\telse\n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> epz = edge(*vit, z, g);\n\t\t\t\tif(epz.second)\n\t\t\t\t{\n\t\t\t\t\t//cerr << \"Compare w(\" << *vit << \",\" << near[*vit] << \") = \" << weight_ep << \" to w(\" << *vit << \",\" <<  z << \")= \" << wmap[epz.first] << endl;\n\t\t\t\t\tif(wmap[epz.first] <= weight_ep)\n\t\t\t\t\t{\n\t\t\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << z << endl;\n\t\t\t\t\t\tnear[*vit] = z;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// -- fail safe --\n\t\tdouble failsafe = 0;\n\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\t\t// -- end fail safe --\n\t\t\n\t\twhile(nearest_vert.first == -1)\n\t\t{\t\n\t\t\tbool hit = false;\n\t\t\tVertexSet diameterBroken;\n\t\t\t// find new z\n\t\t\tfor(vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t\t{\n\t\t\t\tif(near[*vit] > -1) \n\t\t\t\t{\n\t\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, near[*vit], g);\n\t\t\t\t\tASSERTING(ep.second);\n\t\t\t\t\n\t\t\t\t\tif(ecc[near[*vit]] + wmap[ep.first] <= diameter_bound[*vit] && nearest_vert.second > wmap[ep.first])\n\t\t\t\t\t{\n\t\t\t\t\t\t//cerr << \" new z \" << *vit << endl;\n\t\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\t\tnearest_vert.second = wmap[ep.first]; \n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif(ecc[near[*vit]] + wmap[ep.first] > diameter_bound[*vit]) diameterBroken.insert(*vit);\n\t\t\t\t\t\t\n\t\t\t\t\thit = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(nearest_vert.first > -1) break;\n\t\t\t\n\t\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\t\t\t\n\t\t\tASSERTING(hit);\n\t\t\tASSERTING(!diameterBroken.empty());\n\t\t\tif(diameterBroken.empty()) return false;\n\t\t\tif(TreeAlgorithms::relaxDiameter(diameterBroken, diameter_bound) == false) return false;\n\t\t\t\n\t\t\t// try to increase broken limits\n\t\t\t//for(VertexSet::iterator vit = diameterBroken.begin(), vit_end = diameterBroken.end(); vit != vit_end; ++vit)\n\t\t\t//{\n\t\t\t//\tdiameter_bound[*vit] = diameter_bound[*vit] + 0.1;\n\t\t\t\t//cerr << *vit << \" increased diameter bound \" <<  diameter_bound[*vit] << endl; \n\t\t\t//}\n\n\t\t\t// -- fail safe --\n\t\t\tif(failsafe++ >= ((std::numeric_limits<double>::max)() - 1)) break;\n\t\t}\t\n\t}\n\t\n\t//cerr << WRITE_PRETTY_FUNCTION << \" tree \" << T << endl;\n\treturn true;\n}\n\nbool dlOTTC(double D, const GraphN &g, vertex_descriptorN src, DistanceVector &distance, ParentVector &parent, const VertexSet &treeNodes)\n{\n//\tcerr << WRITE_FUNCTION << \" src \" << src  << \" num_vertices \" << treeNodes.size() << endl;\n\t\n\tTreeStructure T;\n\tdEdgeMapConst \t\twmap = get(&EdgeProp::weight, g);\n\tout_edge_iteratorN \toit, oit_end;\n\t\n\tvector<int> \t\tnear(num_vertices(g));\n\tDistanceVector \t\tecc(num_vertices(g));\n\tDistanceVector\t\tdiameter_bound(num_vertices(g));\n\tDistanceVector\t\tdegree_bound(num_vertices(g));\n\tusing namespace \tboost::numeric::ublas;\n\tmatrix<double> \t\tdist(num_vertices(g), num_vertices(g));\n\tpair<int, double> \tnearest_vert(-1,(std::numeric_limits<double>::max)());\n\tint \t\t\t\tdegreeLeverage = 0;\n\t\n\tfor(VertexSet::iterator vit = treeNodes.begin(), vit_end = treeNodes.end(); vit != vit_end; ++vit)\n\t{\n\t\tdistance[*vit] = (std::numeric_limits<double>::max)();\n\t\tparent[*vit] = *vit;\t\n\t\t\n\t\tdegree_bound[*vit] = getDegreeConstraint(g, *vit);\n\t\tdiameter_bound[*vit] = D;\n\t\tecc[*vit] = 0;\t\t\n\t\tif(*vit != src) \n\t\t{\n\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, src, g);\n\t\t\tif(ep.second) \n\t\t\t{\n\t\t\t\tnear[*vit] = src;\n\t\t\t\tif(nearest_vert.second > wmap[ep.first])\n\t\t\t\t{\n\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\tnearest_vert.second = wmap[ep.first];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse near[*vit] = -1;\n\t\t}\n\t\telse \n\t\t{\n\t\t\tnear[*vit] = 0;\n\t\t}\n\t\tfor(VertexSet::iterator vit_in = treeNodes.begin(), vit_in_end = treeNodes.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\tdist(*vit,*vit_in) = 0;\n\t}\n\n\t// -- begin --\n\tT.insertVertex(src, g[src]);\n\tecc[src] = 0;\n\tdist(src,src) = 0;\n\tdistance[src] = 0;\n\tVertexSet notInTree = treeNodes - src;\n\t\n\twhile(1) \n\t{\n\t\tint z = nearest_vert.first;\n\t\n\t\t//cerr << WRITE_FUNCTION << \" z \" << z << \" near[z] \" << near[z] << endl; \n\t\t//cerr << WRITE_FUNCTION << \" inserting edge (\" << z << \",\" << near[z] << \")\" << endl;\n\n\t\tASSERTING(z > -1);\n\t\tASSERTING(notInTree.contains(z));\n\t\tASSERTING(T.V.contains(near[z]));\n\t\t\n\t\tT.insertVertex(z, g[z]);\n\t\tT.insertEdge(z, near[z], g);\n\t\tASSERTING(degree_bound[near[z]] >= getOutDegree(T.g, near[z]));\n\t\t\n\t\tpair<edge_descriptorN, bool> edge_z_near = edge(z, near[z], g);\n\t\tASSERTING(edge_z_near.second);\t\t\n\t\t\n\t\t// distance/parent\n\t\tdistance[z] = g[edge_z_near.first].weight;\n\t\tparent[z] = near[z];\n\t\t\n\t\tnotInTree = notInTree - z;\n\t\tif(notInTree.empty()) break;\n\t\t\n\t\t//cerr << WRITE_FUNCTION << \" not in tree \" << notInTree << endl;\n\t\t\n\t\t//pair<edge_descriptorN, bool> edge_z_near = edge(z, near[z], g);\n\t\t//ASSERTING(edge_z_near.second);\n\t\t\n\t\t// set dist(z,u) and ecc(z)\n\t\tfor(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tif(dist(near[z],*vit) > 0) dist(z,*vit) = dist(near[z],*vit) + wmap[edge_z_near.first];\n\t\t}\n\t\t\n\t\tdist(z,z) = 0;\n\t\tecc[z] = ecc[near[z]] + wmap[edge_z_near.first];\n\n\t\t// update dist(near(z), u) and ecc(near(z))\n\t\tdist(near[z],z) = wmap[edge_z_near.first];\n\t\tif(ecc[near[z]] <= 0) ecc[near[z]] = wmap[edge_z_near.first];\n\t\t\t\n\t\t// update other nodes' values of dist and ecc\n\t\tfor(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tASSERTING(dist(*vit, near[z]) >= 0);\n\t\t\tASSERTING(dist(*vit, z) >= 0);\n\t\t\tASSERTING(ecc[*vit] >= 0);\n\n\t\t\tdist(*vit,z) = dist(*vit, near[z]) + wmap[edge_z_near.first];\n\t\t\tecc[*vit] = std::max(ecc[*vit], dist(*vit,z));\t\n\t\t}\n\t\t\n\t\t//cerr << \" update the near values for other nodes in G \" << endl;\n\t\tfor(VertexSet::iterator vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tdouble dc_near_vit = (numeric_limits<double>::max)(), od_near_vit = 0; \n\t\t\tif(near[*vit] > -1) \n\t\t\t{\n\t\t\t\tdc_near_vit = degree_bound[near[*vit]]; \n\t\t\t\tod_near_vit = getOutDegree(T.g, near[*vit]);\n\t\t\t}\n\n\t\t\tdouble weight_ep = (std::numeric_limits<double>::max)();\n\t\t\tdouble curr_ecc = (std::numeric_limits<double>::max)(); \n\t\t\tif(near[*vit] > -1 && od_near_vit < dc_near_vit) \n\t\t\t{\n\t\t\t\t//cerr << \" edge (\" << *vit << \",\" << near[*vit] << \")\" << endl;\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, near[*vit], g);\n\t\t\t\tASSERTING(ep.second);\n\n\t\t\t\tcurr_ecc = ecc[near[*vit]] + wmap[ep.first];\n\t\t\t\tweight_ep = wmap[ep.first];\n\t\t\t}\n\t\t\n\t\t\t//if(curr_ecc > diameter_bound[*vit] || (od_near_vit >= dc_near_vit && getOutDegree(T.g, z) >= degree_bound[z]) )  \n\t\t\tif(curr_ecc > diameter_bound[*vit] || getOutDegree(T.g, z) >= degree_bound[z])\n\t\t\t{\n\t\t\t\t//cerr << \" examine all nodes in T to determine near(\" << *vit << \")\t\" << endl;\n\t\t\t\tfor(VertexSet::iterator vit_in = T.V.begin(), vit_in_end = T.V.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\t\t{\n\t\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, *vit_in, g);\n\t\t\t\t\tif(!ep.second) continue;\n\t\t\t\t\t\n\t\t\t\t\tdouble new_ecc = ecc[*vit_in] + wmap[ep.first]; //1;\n\t\t\t\t\t//cerr << \" curr ecc \" << curr_ecc << \" new ecc \" << new_ecc << endl;\n\t\t\t\t\n\t\t\t\t\tif(new_ecc < curr_ecc && getOutDegree(T.g, *vit_in) < degree_bound[*vit_in] )  \n\t\t\t\t\t{ \n\t\t\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << *vit_in << endl;\n\t\t\t\t\t\tnear[*vit] = *vit_in;\n\t\t\t\t\t\tcurr_ecc = new_ecc;\n\t\t\t\t\t}\t\n\t\t\t\t}\n\t\t\t}\t\n\t\t\telse\n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> epz = edge(*vit, z, g);\n\t\t\t\tif(epz.second)\n\t\t\t\t{\t\t\t\t\n\t\t\t\t\t//cerr << \"Compare w(\" << *vit << \",\" << near[*vit] << \") = \" << weight_ep << \" to w(\" << *vit << \",\" <<  z << \")= \" << wmap[epz.first] << endl;\n\t\t\t\t\tif(wmap[epz.first] <= weight_ep && getOutDegree(T.g, z) < degree_bound[z])\n\t\t\t\t\t{\n\t\t\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << z << endl;\n\t\t\t\t\t\tnear[*vit] = z;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// -- fail safe --\n\t\tdouble failsafe = 0;\n\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\t\t\n\t\twhile(nearest_vert.first == -1)\n\t\t{\t\n\t\t\tVertexSet diameterBroken, degreeBroken;\t\n\t\t\t// find new z\n\t\t\tfor(VertexSet::iterator vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t\t{\n\t\t\t\tif(near[*vit] > -1) \n\t\t\t\t{\n\t\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, near[*vit], g);\n\t\t\t\t\tASSERTING(ep.second);\n\n\t\t\t\t\tdouble dc_near_vit = degree_bound[near[*vit]];\n\t\t\t\t\tdouble od_near_vit = getOutDegree(T.g, near[*vit]);\n\n\t\t\t\t\tif(ecc[near[*vit]] + wmap[ep.first] <= diameter_bound[*vit] && nearest_vert.second > wmap[ep.first] && od_near_vit < dc_near_vit)\n\t\t\t\t\t{\n\t\t\t\t\t\t//cerr << \" new z \" << *vit << endl;\n\t\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\t\tnearest_vert.second = wmap[ep.first]; \n\t\t\t\t\t}\n\n\t\t\t\t\tif(ecc[near[*vit]] + wmap[ep.first] > diameter_bound[*vit]) diameterBroken.insert(*vit);\n\t\t\t\t\tif(od_near_vit >= dc_near_vit) degreeBroken.insert(near[*vit]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(nearest_vert.first > -1) break;\n\t\t\n\t\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\t\t\n\t\t\tif(!TreeAlgorithms::relaxDegreeAndDiameter(degreeBroken, degree_bound, diameterBroken, diameter_bound)) return false; \n\t\t\tif(!TreeAlgorithms::isRelaxWorking(degreeBroken, diameterBroken)) return false;\n\n\t\t\t// -- fail safe --\n\t\t\tif(failsafe++ >= ((std::numeric_limits<double>::max)() - 1)) break;\n\t\t}\t\n\t}\n\t\n\t//cerr << WRITE_PRETTY_FUNCTION << \" tree \" << T << endl;\n\treturn true;\n}\n\n\nbool mdOTTC(const GraphN &g, vertex_descriptorN src, DistanceVector &distance, ParentVector &parent, const VertexSet &treeNodes)\n{\n//\tcerr << WRITE_FUNCTION << \" src \" << src  << \" num_vertices \" << treeNodes.size() << endl;\n\n\tTreeStructure T;\t\n\tdEdgeMapConst wmap = get(&EdgeProp::weight, g);\n\tout_edge_iteratorN oit, oit_end;\n\tVertexSet::iterator vit, vit_end, vit_in, vit_in_end;\n\t\n\tvector<int> near(num_vertices(g));\n\tDistanceVector ecc(num_vertices(g));\n\tusing namespace boost::numeric::ublas;\n\tmatrix<double> dist(num_vertices(g), num_vertices(g));\n\t\n\tpair<int, double> nearest_vert(-1,(std::numeric_limits<double>::max)());\n\t\n\tfor(vit = treeNodes.begin(), vit_end = treeNodes.end(); vit != vit_end; ++vit)\n\t{\t\n\t\tdistance[*vit] = (std::numeric_limits<double>::max)();\n\t\tparent[*vit] = *vit;\t\n\t\t\n\t\tecc[*vit] = 0;\t\t\n\t\tif(*vit != src) \n\t\t{\n\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, src, g);\n\t\t\tif(ep.second) \n\t\t\t{\n\t\t\t\tnear[*vit] = src;\n\t\t\t\tif(nearest_vert.second > wmap[ep.first])\n\t\t\t\t{\n\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\tnearest_vert.second = wmap[ep.first];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse near[*vit] = -1;\n\t\t}\n\t\telse \n\t\t{\n\t\t\tnear[*vit] = 0;\n\t\t}\n\t\tfor(vit_in = treeNodes.begin(), vit_in_end = treeNodes.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\tdist(*vit,*vit_in) = 0;\n\t}\n\n\t// -- begin --\n\tT.insertVertex(src, g[src]);\n\tecc[src] = 0;\n\tdist(src,src) = 0;\n\tdistance[src] = 0;\n\tVertexSet notInTree = treeNodes - src;\n\t\n\twhile(1) \t\n\t{\n\t\tint z = nearest_vert.first;\n\t\tASSERTING(z > -1);\n\t\t\n\t\t//cerr << WRITE_FUNCTION << \" z \" << z << \" near[z] \" << near[z] << endl; \n\t\t//cerr << WRITE_FUNCTION << \" inserting edge (\" << z << \",\" << near[z] << \")\" << endl;\n\t\t\n\t\tT.insertVertex(z, g[z]);\n\t\tT.insertEdge(z, near[z], g);\n\t\t\n\t\tpair<edge_descriptorN, bool> edge_z_near = edge(z, near[z], g);\n\t\tASSERTING(edge_z_near.second);\t\t\n\t\t\n\t\t// distance/parent\n\t\tdistance[z] = g[edge_z_near.first].weight;\n\t\tparent[z] = near[z];\n\t\t\n\t\tnotInTree = notInTree - z;\n\t\tif(notInTree.empty()) break;\n\n\t\t//cerr << WRITE_FUNCTION << \" not in tree \" << notInTree << endl;\n\t\t\n\t\t//pair<edge_descriptorN, bool> edge_z_near = edge(z, near[z], g);\n\t\t//ASSERTING(edge_z_near.second);\n\t\t\n\t\t// set dist(z,u) and ecc(z)\n\t\tfor(vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tif(dist(near[z],*vit) > 0) dist(z,*vit) = dist(near[z],*vit) + wmap[edge_z_near.first];\n\t\t}\n\t\t\n\t\tdist(z,z) = 0;\n\t\tecc[z] = ecc[near[z]] + wmap[edge_z_near.first];\n\n\t\t// update dist(near(z), u) and ecc(near(z))\n\t\tdist(near[z],z) = wmap[edge_z_near.first];\n\t\tif(ecc[near[z]] <= 0) ecc[near[z]] = wmap[edge_z_near.first];\n\t\t\t\n\t\t// update other nodes' values of dist and ecc\n\t\tfor(vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tASSERTING(dist(*vit, near[z]) >= 0);\n\t\t\tASSERTING(dist(*vit, z) >= 0);\n\t\t\tASSERTING(ecc[*vit] >= 0);\n\n\t\t\tdist(*vit,z) = dist(*vit, near[z]) + wmap[edge_z_near.first];\n\t\t\tecc[*vit] = std::max(ecc[*vit], dist(*vit,z));\t\n\t\t}\n\t\t\n\t\t//cerr << \" update the near values for other nodes in G \" << endl;\n\t\tfor(vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tdouble curr_ecc = (std::numeric_limits<double>::max)(); \n\t\t\t//cerr << \" examine all nodes in T to determine near(\" << *vit << \")\t\" << endl;\n\t\t\tfor(vit_in = T.V.begin(), vit_in_end = T.V.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, *vit_in, g);\n\t\t\t\tif(!ep.second) continue;\n\t\t\t\t\t\n\t\t\t\tdouble new_ecc = ecc[*vit_in] + wmap[ep.first]; \n\t\t\t\t//cerr << \" curr ecc \" << curr_ecc << \" new ecc \" << new_ecc << endl;\n\t\t\t\t\t\n\t\t\t\tif(new_ecc < curr_ecc)\n\t\t\t\t{ \n\t\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << *vit_in << endl;\n\t\t\t\t\tnear[*vit] = *vit_in;\n\t\t\t\t\tcurr_ecc = new_ecc;\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\n\t\t// find new z\n\t\tfor(vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tif(near[*vit] > -1) \n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, near[*vit], g);\n\t\t\t\tASSERTING(ep.second);\n\t\t\t\t\t\n\t\t\t\tdouble new_ecc = ecc[near[*vit]] + wmap[ep.first];\n\t\t\t\tif(nearest_vert.second > new_ecc) \n\t\t\t\t{\n\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\tnearest_vert.second = new_ecc; \n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tASSERTING(nearest_vert.first > -1);\n\t}\n\treturn true;\n}\n\nbool mddlOTTC(const GraphN &g, vertex_descriptorN src, DistanceVector &distance, ParentVector &parent, const VertexSet &treeNodes)\n{\n//\tcerr << WRITE_FUNCTION << \" src \" << src  << \" num_vertices \" << treeNodes.size() << endl;\n\t\n\tTreeStructure T;\n\tdEdgeMapConst \t\twmap = get(&EdgeProp::weight, g);\n\tout_edge_iteratorN \toit, oit_end;\n\t\n\tvector<int> \t\tnear(num_vertices(g));\n\tDistanceVector \t\tecc(num_vertices(g));\n\tDistanceVector\t\tdegree_bound(num_vertices(g));\n\tusing namespace \tboost::numeric::ublas;\n\tmatrix<double> \t\tdist(num_vertices(g), num_vertices(g));\n\tpair<int, double> \tnearest_vert(-1,(std::numeric_limits<double>::max)());\n\tint \t\t\t\tdegreeLeverage = 0;\n\t\n\tfor(VertexSet::iterator vit = treeNodes.begin(), vit_end = treeNodes.end(); vit != vit_end; ++vit)\n\t{\n\t\tdistance[*vit] = (std::numeric_limits<double>::max)();\n\t\tparent[*vit] = *vit;\t\n\n\t\tdegree_bound[*vit] = getDegreeConstraint(g, *vit);\n\t\tecc[*vit] = 0;\t\t\n\t\tif(*vit != src) \n\t\t{\n\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, src, g);\n\t\t\tif(ep.second) \n\t\t\t{\n\t\t\t\tnear[*vit] = src;\n\t\t\t\tif(nearest_vert.second > wmap[ep.first])\n\t\t\t\t{\n\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\tnearest_vert.second = wmap[ep.first];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse near[*vit] = -1;\n\t\t}\n\t\telse \n\t\t{\n\t\t\tnear[*vit] = 0;\n\t\t}\n\t\tfor(VertexSet::iterator vit_in = treeNodes.begin(), vit_in_end = treeNodes.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\tdist(*vit,*vit_in) = 0;\n\t}\n\n\t// -- begin --\n\tT.insertVertex(src, g[src]);\n\tecc[src] = 0;\n\tdist(src,src) = 0;\n\tdistance[src] = 0;\n\tVertexSet notInTree = treeNodes - src;\n\t\n\twhile(1) \n\t{\n\t\tint z = nearest_vert.first;\n\t\n\t\t//cerr << WRITE_FUNCTION << \" z \" << z << \" near[z] \" << near[z] << endl; \n\t\t//cerr << WRITE_FUNCTION << \" inserting edge (\" << z << \",\" << near[z] << \")\" << \" out degree : \" << getOutDegree(T.g, near[z]) << endl;\n\n\t\tASSERTING(z > -1);\n\t\tASSERTING(notInTree.contains(z));\n\t\tASSERTING(T.V.contains(near[z]));\n\t\t\n\t\tT.insertVertex(z, g[z]);\n\t\tT.insertEdge(z, near[z], g);\n\t\tASSERTING(degree_bound[near[z]] >= getOutDegree(T.g, near[z]));\n\t\t\n\t\tpair<edge_descriptorN, bool> edge_z_near = edge(z, near[z], g);\n\t\tASSERTING(edge_z_near.second);\t\t\n\t\t\n\t\t// distance/parent\n\t\tdistance[z] = g[edge_z_near.first].weight;\n\t\tparent[z] = near[z];\n\n\t\tnotInTree = notInTree - z;\n\t\tif(notInTree.empty()) break;\n\t\t\n\t\t//cerr << WRITE_FUNCTION << \" not in tree \" << notInTree << endl;\n\t\t\n\t\t//pair<edge_descriptorN, bool> edge_z_near = edge(z, near[z], g);\n\t\t//ASSERTING(edge_z_near.second);\n\t\t\n\t\t// set dist(z,u) and ecc(z)\n\t\tfor(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tif(dist(near[z],*vit) > 0) dist(z,*vit) = dist(near[z],*vit) + wmap[edge_z_near.first];\n\t\t}\n\t\t\n\t\tdist(z,z) = 0;\n\t\tecc[z] = ecc[near[z]] + wmap[edge_z_near.first];\n\n\t\t// update dist(near(z), u) and ecc(near(z))\n\t\tdist(near[z],z) = wmap[edge_z_near.first];\n\t\tif(ecc[near[z]] <= 0) ecc[near[z]] = wmap[edge_z_near.first];\n\t\t\t\n\t\t// update other nodes' values of dist and ecc\n\t\tfor(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tASSERTING(dist(*vit, near[z]) >= 0);\n\t\t\tASSERTING(dist(*vit, z) >= 0);\n\t\t\tASSERTING(ecc[*vit] >= 0);\n\n\t\t\tdist(*vit,z) = dist(*vit, near[z]) + wmap[edge_z_near.first];\n\t\t\tecc[*vit] = std::max(ecc[*vit], dist(*vit,z));\t\n\t\t}\n\t\t\n\t\t//cerr << \" update the near values for other nodes in G \" << endl;\n\t\tfor(VertexSet::iterator vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t{\n\t\t\tdouble curr_ecc = (std::numeric_limits<double>::max)(); \n\t\t\t//cerr << \" examine all nodes in T to determine near(\" << *vit << \")\t\" << endl;\n\t\t\tfor(VertexSet::iterator vit_in = T.V.begin(), vit_in_end = T.V.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, *vit_in, g);\n\t\t\t\tif(!ep.second) continue;\n\t\t\t\t\t\n\t\t\t\tdouble new_ecc = ecc[*vit_in] + wmap[ep.first]; \n\t\t\t\tif(T.V.size() > 1) ASSERTING(ecc[*vit_in] > 0);\n\t\t\t\t\n\t\t\t\t//cerr << \" curr ecc \" << curr_ecc << \" new ecc \" << new_ecc << endl;\n\t\t\t\t\n\t\t\t\tif(new_ecc < curr_ecc && getOutDegree(T.g, *vit_in) < degree_bound[*vit_in] ) \n\t\t\t\t{ \n\t\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << *vit_in << endl;\n\t\t\t\t\tnear[*vit] = *vit_in;\n\t\t\t\t\tcurr_ecc = new_ecc;\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t\t\n\t\t// -- fail safe --\n\t\tdouble failsafe = 0;\n\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\t\t\n\t\twhile(nearest_vert.first == -1)\n\t\t{\t\n\t\t\tVertexSet degreeBroken;\t\n\t\t\t// find new z\n\t\t\tfor(VertexSet::iterator vit = notInTree.begin(), vit_end = notInTree.end(); vit != vit_end; ++vit)\n\t\t\t{\n\t\t\t\tif(near[*vit] > -1) \n\t\t\t\t{\n\t\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, near[*vit], g);\n\t\t\t\t\tASSERTING(ep.second);\n\n\t\t\t\t\tdouble dc_near_vit = degree_bound[near[*vit]];\n\t\t\t\t\tdouble od_near_vit = getOutDegree(T.g, near[*vit]);\n\t\t\t\t\n\t\t\t\t\tif(T.V.size() > 1) ASSERTING(od_near_vit > 0);\n\t\t\t\t\t\n\t\t\t\t\tdouble new_ecc = ecc[near[*vit]] + wmap[ep.first];\n\t\t\t\t\tif(nearest_vert.second > new_ecc && od_near_vit < dc_near_vit) \n\t\t\t\t\t{\n\t\t\t\t\t\t//cerr << \" new z \" << *vit << endl;\n\t\t\t\t\t\tnearest_vert.first = *vit;\n\t\t\t\t\t\tnearest_vert.second = new_ecc; \n\t\t\t\t\t}\n\n\t\t\t\t\tif(od_near_vit >= dc_near_vit) degreeBroken.insert(near[*vit]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(nearest_vert.first > -1) break;\n\t\t\n\t\t\tnearest_vert = pair<int,double>(-1,(std::numeric_limits<double>::max)());\n\t\t\n\t\t\tASSERTING(!degreeBroken.empty());\n\t\t\tif(degreeBroken.empty()) return false;\n\t\t\tif(TreeAlgorithms::relaxDegree(degreeBroken, degree_bound) == false) return false;\n\n\t\t\t// try to increase broken limits\n\t\t\t//for(VertexSet::iterator vit = degreeBroken.begin(), vit_end = degreeBroken.end(); vit != vit_end; ++vit)\n\t\t\t//{\n\t\t\t//\tdegree_bound[*vit] = degree_bound[*vit] + 1;\n\t\t\t\t//cerr << *vit << \" increased degree limit \" << degree_bound[*vit] << endl;\n\t\t\t//}\n\t\t\t// -- fail safe --\n\t\t\tif(failsafe++ >= ((std::numeric_limits<double>::max)() - 1)) break;\n\t\t}\t\n\t}\n\treturn true;\n}\n}; // namespace TreeAlgorithms\n\n\n\n", "meta": {"hexsha": "9fd943cacd552a1ce781ba78d499dcfc643fe2d0", "size": 45917, "ext": "cc", "lang": "C++", "max_stars_repo_path": "GraphLib/treealgs/prim_ottc.cc", "max_stars_repo_name": "intact-software-systems/cpp-software-patterns", "max_stars_repo_head_hexsha": "e463fc7eeba4946b365b5f0b2eecf3da0f4c895b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-03T07:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-03T07:23:11.000Z", "max_issues_repo_path": "GraphLib/treealgs/prim_ottc.cc", "max_issues_repo_name": "intact-software-systems/cpp-software-patterns", "max_issues_repo_head_hexsha": "e463fc7eeba4946b365b5f0b2eecf3da0f4c895b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GraphLib/treealgs/prim_ottc.cc", "max_forks_repo_name": "intact-software-systems/cpp-software-patterns", "max_forks_repo_head_hexsha": "e463fc7eeba4946b365b5f0b2eecf3da0f4c895b", "max_forks_repo_licenses": ["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.2360544218, "max_line_length": 149, "alphanum_fraction": 0.5876254982, "num_tokens": 14851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5099992609702465}}
{"text": "#pragma once\n#include <Eigen/Dense>\n\n#define VECLEN 10\n\ntypedef Eigen::Matrix<double, VECLEN, 1> MyVector;\n\nvoid add_vector_fixed(const MyVector &in1, const MyVector &in2, MyVector &out);\n\nvoid add_vector(const Eigen::VectorXd &in1, const Eigen::VectorXd &in2, Eigen::VectorXd &out);\n", "meta": {"hexsha": "7d8fffa87665c315d7fbf0b8bb99241b7537cb25", "size": 284, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cuda/vector_add_eigen/kernel.hpp", "max_stars_repo_name": "kamino410/edsdk-sample", "max_stars_repo_head_hexsha": "b08cd8b116a36e09f26358b04e385f32f0c82b4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2018-10-26T18:16:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T04:58:28.000Z", "max_issues_repo_path": "cuda/vector_add_eigen/kernel.hpp", "max_issues_repo_name": "kamino410/edsdk-sample", "max_issues_repo_head_hexsha": "b08cd8b116a36e09f26358b04e385f32f0c82b4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-24T08:05:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-24T08:05:20.000Z", "max_forks_repo_path": "cuda/vector_add_eigen/kernel.hpp", "max_forks_repo_name": "kamino410/edsdk-sample", "max_forks_repo_head_hexsha": "b08cd8b116a36e09f26358b04e385f32f0c82b4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2019-05-20T06:31:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T05:53:29.000Z", "avg_line_length": 25.8181818182, "max_line_length": 94, "alphanum_fraction": 0.7570422535, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5099992609702464}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"tests/Unit/TestingFramework.hpp\"\n\n#include <array>\n#include <boost/optional.hpp>\n#include <cmath>\n#include <cstddef>\n#include <memory>\n#include <pup.h>\n#include <vector>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Domain/CoordinateMaps/Affine.hpp\"\n#include \"Domain/CoordinateMaps/CoordinateMap.hpp\"\n#include \"Domain/CoordinateMaps/ProductMaps.hpp\"\n#include \"Domain/CoordinateMaps/Rotation.hpp\"\n#include \"Domain/CoordinateMaps/Wedge2D.hpp\"\n#include \"Domain/Direction.hpp\"\n#include \"Domain/OrientationMap.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeArray.hpp\"\n#include \"Utilities/MakeWithValue.hpp\"\n#include \"tests/Unit/TestHelpers.hpp\"\n\n// IWYU pragma: no_forward_declare Tensor\n\nnamespace {\ntemplate <typename Map1, typename Map2, typename DataType, size_t Dim>\nauto compose_jacobians(const Map1& map1, const Map2& map2,\n                       const std::array<DataType, Dim>& point) {\n  const auto jac1 = map1.jacobian(point);\n  const auto jac2 = map2.jacobian(map1(point));\n\n  auto result =\n      make_with_value<Jacobian<DataType, Dim, Frame::Logical, Frame::Grid>>(\n          point[0], 0.);\n  for (size_t target = 0; target < Dim; ++target) {\n    for (size_t source = 0; source < Dim; ++source) {\n      for (size_t dummy = 0; dummy < Dim; ++dummy) {\n        result.get(target, source) +=\n            jac2.get(target, dummy) * jac1.get(dummy, source);\n      }\n    }\n  }\n  return result;\n}\n\ntemplate <typename Map1, typename Map2, typename DataType, size_t Dim>\nauto compose_inv_jacobians(const Map1& map1, const Map2& map2,\n                           const std::array<DataType, Dim>& point) {\n  const auto inv_jac1 = map1.inv_jacobian(point);\n  const auto inv_jac2 = map2.inv_jacobian(map1(point));\n\n  auto result = make_with_value<\n      InverseJacobian<DataType, Dim, Frame::Logical, Frame::Grid>>(point[0],\n                                                                   0.);\n  for (size_t target = 0; target < Dim; ++target) {\n    for (size_t source = 0; source < Dim; ++source) {\n      for (size_t dummy = 0; dummy < Dim; ++dummy) {\n        result.get(source, target) +=\n            inv_jac1.get(source, dummy) * inv_jac2.get(dummy, target);\n      }\n    }\n  }\n  return result;\n}\n\nvoid test_single_coordinate_map() {\n  using affine_map1d = CoordinateMaps::Affine;\n\n  const auto affine1d = make_coordinate_map<Frame::Logical, Frame::Grid>(\n      affine_map1d{-1.0, 1.0, 2.0, 8.0});\n  const auto affine1d_base =\n      make_coordinate_map_base<Frame::Logical, Frame::Grid>(\n          affine_map1d{-1.0, 1.0, 2.0, 8.0});\n  const auto first_affine1d = affine_map1d{-1.0, 1.0, 2.0, 8.0};\n\n  CHECK(affine1d == *affine1d_base);\n  CHECK(*affine1d_base == affine1d);\n\n  std::array<std::array<double, 1>, 4> coords1d{\n      {{{0.1}}, {{-8.2}}, {{5.7}}, {{2.9}}}};\n\n  for (const auto& coord : coords1d) {\n    CHECK((make_array<double, 1>((*affine1d_base)(\n              tnsr::I<double, 1, Frame::Logical>{{{coord[0]}}}))) ==\n          first_affine1d(coord));\n    CHECK((make_array<double, 1>(\n              affine1d_base\n                  ->inverse(tnsr::I<double, 1, Frame::Grid>{{{coord[0]}}})\n                  .get())) == first_affine1d.inverse(coord).get());\n\n    CHECK((make_array<double, 1>(affine1d(tnsr::I<double, 1, Frame::Logical>{\n              {{coord[0]}}}))) == first_affine1d(coord));\n    CHECK((make_array<double, 1>(\n              affine1d.inverse(tnsr::I<double, 1, Frame::Grid>{{{coord[0]}}})\n                  .get())) == first_affine1d.inverse(coord).get());\n\n    const auto jac =\n        affine1d.jacobian(tnsr::I<double, 1, Frame::Logical>{{{coord[0]}}});\n    const auto expected_jac = first_affine1d.jacobian(coord);\n    CHECK(affine1d_base\n              ->jacobian(tnsr::I<double, 1, Frame::Logical>{{{coord[0]}}})\n              .get(0, 0) == expected_jac.get(0, 0));\n    CHECK(jac.get(0, 0) == expected_jac.get(0, 0));\n\n    const auto inv_jac =\n        affine1d.inv_jacobian(tnsr::I<double, 1, Frame::Logical>{{{coord[0]}}});\n    const auto expected_inv_jac = first_affine1d.inv_jacobian(coord);\n    CHECK(affine1d_base\n              ->inv_jacobian(tnsr::I<double, 1, Frame::Logical>{{{coord[0]}}})\n              .get(0, 0) == expected_inv_jac.get(0, 0));\n    CHECK(inv_jac.get(0, 0) == expected_inv_jac.get(0, 0));\n  }\n\n  using rotate2d = CoordinateMaps::Rotation<2>;\n\n  const auto first_rotated2d = rotate2d{M_PI_4};\n  const auto rotated2d =\n      make_coordinate_map<Frame::Logical, Frame::Grid>(first_rotated2d);\n  const auto rotated2d_base =\n      make_coordinate_map_base<Frame::Logical, Frame::Grid>(first_rotated2d);\n\n  CHECK(rotated2d == *rotated2d_base);\n  CHECK(*rotated2d_base == rotated2d);\n\n  std::array<std::array<double, 2>, 4> coords2d{\n      {{{0.1, 2.8}}, {{-8.2, 2.8}}, {{5.7, -4.9}}, {{2.9, 3.4}}}};\n\n  for (const auto& coord : coords2d) {\n    CHECK((make_array<double, 2>((*rotated2d_base)(\n              tnsr::I<double, 2, Frame::Logical>{{{coord[0], coord[1]}}}))) ==\n          first_rotated2d(coord));\n    CHECK((make_array<double, 2>(rotated2d_base\n                                     ->inverse(tnsr::I<double, 2, Frame::Grid>{\n                                         {{coord[0], coord[1]}}})\n                                     .get())) ==\n          first_rotated2d.inverse(coord).get());\n\n    CHECK((make_array<double, 2>(rotated2d(tnsr::I<double, 2, Frame::Logical>{\n              {{coord[0], coord[1]}}}))) == first_rotated2d(coord));\n    CHECK((make_array<double, 2>(rotated2d\n                                     .inverse(tnsr::I<double, 2, Frame::Grid>{\n                                         {{coord[0], coord[1]}}})\n                                     .get())) ==\n          first_rotated2d.inverse(coord).get());\n\n    const auto jac = rotated2d.jacobian(\n        tnsr::I<double, 2, Frame::Logical>{{{coord[0], coord[1]}}});\n    const auto jac2 = rotated2d_base->jacobian(\n        tnsr::I<double, 2, Frame::Logical>{{{coord[0], coord[1]}}});\n    const auto expected_jac = first_rotated2d.jacobian(coord);\n    for (size_t j = 0; j < 2; ++j) {\n      for (size_t k = 0; k < 2; ++k) {\n        CHECK(jac.get(j, k) == expected_jac.get(j, k));\n        CHECK(jac2.get(j, k) == expected_jac.get(j, k));\n      }\n    }\n\n    const auto inv_jac = rotated2d.inv_jacobian(\n        tnsr::I<double, 2, Frame::Logical>{{{coord[0], coord[1]}}});\n    const auto inv_jac2 = rotated2d_base->inv_jacobian(\n        tnsr::I<double, 2, Frame::Logical>{{{coord[0], coord[1]}}});\n    const auto expected_inv_jac = first_rotated2d.inv_jacobian(coord);\n    for (size_t j = 0; j < 2; ++j) {\n      for (size_t k = 0; k < 2; ++k) {\n        CHECK(inv_jac.get(j, k) == expected_inv_jac.get(j, k));\n        CHECK(inv_jac2.get(j, k) == expected_inv_jac.get(j, k));\n      }\n    }\n  }\n\n  using rotate3d = CoordinateMaps::Rotation<3>;\n\n  const auto first_rotated3d = rotate3d{M_PI_4, M_PI_4, M_PI_2};\n  const auto rotated3d =\n      make_coordinate_map<Frame::Logical, Frame::Grid>(first_rotated3d);\n  const auto rotated3d_base =\n      make_coordinate_map_base<Frame::Logical, Frame::Grid>(first_rotated3d);\n\n  CHECK(rotated3d == *rotated3d_base);\n  CHECK(*rotated3d_base == rotated3d);\n\n  std::array<std::array<double, 3>, 4> coords3d{{{{0.1, 2.8, 9.3}},\n                                                 {{-8.2, 2.8, -9.7}},\n                                                 {{5.7, -4.9, 8.1}},\n                                                 {{2.9, 3.4, -7.8}}}};\n\n  for (const auto& coord : coords3d) {\n    CHECK((make_array<double, 3>((\n              *rotated3d_base)(tnsr::I<double, 3, Frame::Logical>{\n              {{coord[0], coord[1], coord[2]}}}))) == first_rotated3d(coord));\n    CHECK((make_array<double, 3>(rotated3d_base\n                                     ->inverse(tnsr::I<double, 3, Frame::Grid>{\n                                         {{coord[0], coord[1], coord[2]}}})\n                                     .get())) ==\n          first_rotated3d.inverse(coord).get());\n\n    CHECK((make_array<double, 3>(rotated3d(tnsr::I<double, 3, Frame::Logical>{\n              {{coord[0], coord[1], coord[2]}}}))) == first_rotated3d(coord));\n    CHECK((make_array<double, 3>(rotated3d\n                                     .inverse(tnsr::I<double, 3, Frame::Grid>{\n                                         {{coord[0], coord[1], coord[2]}}})\n                                     .get())) ==\n          first_rotated3d.inverse(coord).get());\n\n    const auto jac = rotated3d.jacobian(\n        tnsr::I<double, 3, Frame::Logical>{{{coord[0], coord[1], coord[2]}}});\n    const auto jac2 = rotated3d_base->jacobian(\n        tnsr::I<double, 3, Frame::Logical>{{{coord[0], coord[1], coord[2]}}});\n    const auto expected_jac = first_rotated3d.jacobian(coord);\n    for (size_t j = 0; j < 3; ++j) {\n      for (size_t k = 0; k < 3; ++k) {\n        CHECK(jac.get(j, k) == expected_jac.get(j, k));\n        CHECK(jac2.get(j, k) == expected_jac.get(j, k));\n      }\n    }\n\n    const auto inv_jac = rotated3d.inv_jacobian(\n        tnsr::I<double, 3, Frame::Logical>{{{coord[0], coord[1], coord[2]}}});\n    const auto inv_jac2 = rotated3d_base->inv_jacobian(\n        tnsr::I<double, 3, Frame::Logical>{{{coord[0], coord[1], coord[2]}}});\n    const auto expected_inv_jac = first_rotated3d.inv_jacobian(coord);\n    for (size_t j = 0; j < 3; ++j) {\n      for (size_t k = 0; k < 3; ++k) {\n        CHECK(inv_jac.get(j, k) == expected_inv_jac.get(j, k));\n        CHECK(inv_jac2.get(j, k) == expected_inv_jac.get(j, k));\n      }\n    }\n  }\n}\n\nvoid test_coordinate_map_with_affine_map() {\n  using affine_map = CoordinateMaps::Affine;\n  using affine_map_2d = CoordinateMaps::ProductOf2Maps<affine_map, affine_map>;\n  using affine_map_3d =\n      CoordinateMaps::ProductOf3Maps<affine_map, affine_map, affine_map>;\n\n  constexpr size_t number_of_points_checked = 10;\n\n  // Test 1D\n  const auto map = make_coordinate_map<Frame::Logical, Frame::Grid>(\n      affine_map{-1.0, 1.0, 0.0, 2.3}, affine_map{0.0, 2.3, -0.5, 0.5});\n  for (size_t i = 1; i < number_of_points_checked + 1; ++i) {\n    CHECK((tnsr::I<double, 1, Frame::Grid>(1.0 / i + -0.5))[0] ==\n          approx(map(tnsr::I<double, 1, Frame::Logical>{2.0 / i + -1.0})[0]));\n    CHECK((tnsr::I<double, 1, Frame::Logical>(2.0 / i + -1.0))[0] ==\n          approx(map.inverse(tnsr::I<double, 1, Frame::Grid>{1.0 / i + -0.5})\n                     .get()[0]));\n\n    CHECK(approx(map.inv_jacobian(\n                        tnsr::I<double, 1, Frame::Logical>{2.0 / i + -1.0})\n                     .get(0, 0)) == 2.0);\n    CHECK(\n        approx(map.jacobian(tnsr::I<double, 1, Frame::Logical>{2.0 / i + -1.0})\n                   .get(0, 0)) == 0.5);\n  }\n\n  // Test 2D\n  const auto prod_map2d = make_coordinate_map<Frame::Logical, Frame::Grid>(\n      affine_map_2d{affine_map{-1.0, 1.0, 0.0, 2.0},\n                    affine_map{0.0, 2.0, -0.5, 0.5}},\n      affine_map_2d{affine_map{0.0, 2.0, 2.0, 6.0},\n                    affine_map{-0.5, 0.5, 0.0, 8.0}});\n  for (size_t i = 1; i < number_of_points_checked + 1; ++i) {\n    const auto mapped_point = prod_map2d(\n        tnsr::I<double, 2, Frame::Logical>{{{-1.0 + 2.0 / i, 0.0 + 2.0 / i}}});\n    const auto expected_mapped_point =\n        tnsr::I<double, 2, Frame::Grid>{{{4.0 / i + 2.0, 8.0 / i + 0.0}}};\n    CHECK(get<0>(expected_mapped_point) == approx(get<0>(mapped_point)));\n    CHECK(get<1>(expected_mapped_point) == approx(get<1>(mapped_point)));\n\n    const auto inv_mapped_point = prod_map2d\n                                      .inverse(tnsr::I<double, 2, Frame::Grid>{\n                                          {{4.0 / i + 2.0, 8.0 / i + 0.0}}})\n                                      .get();\n    const auto expected_inv_mapped_point =\n        tnsr::I<double, 2, Frame::Grid>{{{-1.0 + 2.0 / i, 0.0 + 2.0 / i}}};\n    CHECK(get<0>(expected_inv_mapped_point) ==\n          approx(get<0>(inv_mapped_point)));\n    CHECK(get<1>(expected_inv_mapped_point) ==\n          approx(get<1>(inv_mapped_point)));\n\n    const auto inv_jac = prod_map2d.inv_jacobian(\n        tnsr::I<double, 2, Frame::Logical>{{{-1.0 + 2.0 / i, 0.0 + 2.0 / i}}});\n    CHECK(0.5 == approx(get<0, 0>(inv_jac)));\n    CHECK(0.0 == approx(get<1, 0>(inv_jac)));\n    CHECK(0.0 == approx(get<0, 1>(inv_jac)));\n    CHECK(0.25 == approx(get<1, 1>(inv_jac)));\n\n    const auto jac = prod_map2d.jacobian(\n        tnsr::I<double, 2, Frame::Logical>{{{-1.0 + 2.0 / i, 0.0 + 2.0 / i}}});\n    CHECK(2.0 == approx(get<0, 0>(jac)));\n    CHECK(0.0 == approx(get<1, 0>(jac)));\n    CHECK(0.0 == approx(get<0, 1>(jac)));\n    CHECK(4.0 == approx(get<1, 1>(jac)));\n  }\n\n  // Test 3D\n  const auto prod_map3d = make_coordinate_map<Frame::Logical, Frame::Grid>(\n      affine_map_3d{affine_map{-1.0, 1.0, 0.0, 2.0},\n                    affine_map{0.0, 2.0, -0.5, 0.5},\n                    affine_map{5.0, 7.0, -7.0, 7.0}},\n      affine_map_3d{affine_map{0.0, 2.0, 2.0, 6.0},\n                    affine_map{-0.5, 0.5, 0.0, 8.0},\n                    affine_map{-7.0, 7.0, 3.0, 23.0}});\n\n  for (size_t i = 1; i < number_of_points_checked + 1; ++i) {\n    const auto mapped_point = prod_map3d(tnsr::I<double, 3, Frame::Logical>{\n        {{-1.0 + 2.0 / i, 0.0 + 2.0 / i, 5.0 + 2.0 / i}}});\n    const auto expected_mapped_point = tnsr::I<double, 3, Frame::Grid>{\n        {{4.0 / i + 2.0, 8.0 / i + 0.0, 3.0 + 20.0 / i}}};\n    CHECK(get<0>(expected_mapped_point) == approx(get<0>(mapped_point)));\n    CHECK(get<1>(expected_mapped_point) == approx(get<1>(mapped_point)));\n    CHECK(get<2>(expected_mapped_point) == approx(get<2>(mapped_point)));\n\n    const auto inv_mapped_point =\n        prod_map3d\n            .inverse(tnsr::I<double, 3, Frame::Grid>{\n                {{4.0 / i + 2.0, 8.0 / i + 0.0, 3.0 + 20.0 / i}}})\n            .get();\n    const auto expected_inv_mapped_point = tnsr::I<double, 3, Frame::Grid>{\n        {{-1.0 + 2.0 / i, 0.0 + 2.0 / i, 5.0 + 2.0 / i}}};\n    CHECK(get<0>(expected_inv_mapped_point) ==\n          approx(get<0>(inv_mapped_point)));\n    CHECK(get<1>(expected_inv_mapped_point) ==\n          approx(get<1>(inv_mapped_point)));\n    CHECK(get<2>(expected_inv_mapped_point) ==\n          approx(get<2>(inv_mapped_point)));\n\n    const auto inv_jac =\n        prod_map3d.inv_jacobian(tnsr::I<double, 3, Frame::Logical>{\n            {{-1.0 + 2.0 / i, 0.0 + 2.0 / i, 5.0 + 2.0 / i}}});\n    CHECK(0.5 == approx(get<0, 0>(inv_jac)));\n    CHECK(0.0 == approx(get<1, 0>(inv_jac)));\n    CHECK(0.0 == approx(get<0, 1>(inv_jac)));\n    CHECK(0.25 == approx(get<1, 1>(inv_jac)));\n    CHECK(0.0 == approx(get<0, 2>(inv_jac)));\n    CHECK(0.0 == approx(get<1, 2>(inv_jac)));\n    CHECK(0.0 == approx(get<2, 0>(inv_jac)));\n    CHECK(0.0 == approx(get<2, 1>(inv_jac)));\n    CHECK(0.1 == approx(get<2, 2>(inv_jac)));\n\n    const auto jac = prod_map3d.jacobian(tnsr::I<double, 3, Frame::Logical>{\n        {{-1.0 + 2.0 / i, 0.0 + 2.0 / i, 5.0 + 2.0 / i}}});\n    CHECK(2.0 == approx(get<0, 0>(jac)));\n    CHECK(0.0 == approx(get<1, 0>(jac)));\n    CHECK(0.0 == approx(get<0, 1>(jac)));\n    CHECK(4.0 == approx(get<1, 1>(jac)));\n    CHECK(0.0 == approx(get<0, 2>(jac)));\n    CHECK(0.0 == approx(get<1, 2>(jac)));\n    CHECK(0.0 == approx(get<2, 0>(jac)));\n    CHECK(0.0 == approx(get<2, 1>(jac)));\n    CHECK(10.0 == approx(get<2, 2>(jac)));\n  }\n}\n\nvoid test_coordinate_map_with_rotation_map() {\n  using rotate2d = CoordinateMaps::Rotation<2>;\n  using rotate3d = CoordinateMaps::Rotation<3>;\n\n  // No 1D test because it would just the be affine map test\n\n  // Test 2D\n  const auto double_rotated2d =\n      make_coordinate_map<Frame::Logical, Frame::Grid>(rotate2d{M_PI_4},\n                                                       rotate2d{M_PI_2});\n  const auto first_rotated2d = rotate2d{M_PI_4};\n  const auto second_rotated2d = rotate2d{M_PI_2};\n\n  std::array<std::array<double, 2>, 4> coords2d{\n      {{{0.1, 2.8}}, {{-8.2, 2.8}}, {{5.7, -4.9}}, {{2.9, 3.4}}}};\n\n  for (size_t i = 0; i < coords2d.size(); ++i) {\n    INFO(i);\n    const auto coord = gsl::at(coords2d, i);\n    CHECK((make_array<double, 2>(double_rotated2d(\n              tnsr::I<double, 2, Frame::Logical>{{{coord[0], coord[1]}}}))) ==\n          second_rotated2d(first_rotated2d(coord)));\n    CHECK((make_array<double, 2>(double_rotated2d\n                                     .inverse(tnsr::I<double, 2, Frame::Grid>{\n                                         {{coord[0], coord[1]}}})\n                                     .get())) ==\n          first_rotated2d.inverse(second_rotated2d.inverse(coord).get()).get());\n\n    const auto jac = double_rotated2d.jacobian(\n        tnsr::I<double, 2, Frame::Logical>{{{coord[0], coord[1]}}});\n    const auto expected_jac = compose_jacobians(\n        first_rotated2d, second_rotated2d, gsl::at(coords2d, i));\n    CHECK_ITERABLE_APPROX(jac, expected_jac);\n\n    const auto inv_jac = double_rotated2d.inv_jacobian(\n        tnsr::I<double, 2, Frame::Logical>{{{coord[0], coord[1]}}});\n    const auto expected_inv_jac = compose_inv_jacobians(\n        first_rotated2d, second_rotated2d, gsl::at(coords2d, i));\n    CHECK_ITERABLE_APPROX(inv_jac, expected_inv_jac);\n  }\n\n  // Test 3D\n  const auto double_rotated3d =\n      make_coordinate_map<Frame::Logical, Frame::Grid>(\n          rotate3d{M_PI_4, M_PI_4, M_PI_2}, rotate3d{M_PI_2, M_PI_4, M_PI_4});\n  const auto first_rotated3d = rotate3d{M_PI_4, M_PI_4, M_PI_2};\n  const auto second_rotated3d = rotate3d{M_PI_2, M_PI_4, M_PI_4};\n\n  std::array<std::array<double, 3>, 4> coords3d{{{{0.1, 2.8, 9.3}},\n                                                 {{-8.2, 2.8, -9.7}},\n                                                 {{5.7, -4.9, 8.1}},\n                                                 {{2.9, 3.4, -7.8}}}};\n\n  for (size_t i = 0; i < coords3d.size(); ++i) {\n    INFO(i);\n    const auto coord = gsl::at(coords3d, i);\n    CHECK((make_array<double, 3>(\n              double_rotated3d(tnsr::I<double, 3, Frame::Logical>{\n                  {{coord[0], coord[1], coord[2]}}}))) ==\n          second_rotated3d(first_rotated3d(coord)));\n    CHECK((make_array<double, 3>(double_rotated3d\n                                     .inverse(tnsr::I<double, 3, Frame::Grid>{\n                                         {{coord[0], coord[1], coord[2]}}})\n                                     .get())) ==\n          first_rotated3d.inverse(second_rotated3d.inverse(coord).get()).get());\n\n    const auto jac = double_rotated3d.jacobian(\n        tnsr::I<double, 3, Frame::Logical>{{{coord[0], coord[1], coord[2]}}});\n    const auto expected_jac = compose_jacobians(\n        first_rotated3d, second_rotated3d, gsl::at(coords3d, i));\n    CHECK_ITERABLE_APPROX(jac, expected_jac);\n\n    const auto inv_jac = double_rotated3d.inv_jacobian(\n        tnsr::I<double, 3, Frame::Logical>{{{coord[0], coord[1], coord[2]}}});\n    const auto expected_inv_jac = compose_inv_jacobians(\n        first_rotated3d, second_rotated3d, gsl::at(coords3d, i));\n    CHECK_ITERABLE_APPROX(inv_jac, expected_inv_jac);\n  }\n\n  // Check inequivalence operator\n  CHECK_FALSE(double_rotated3d != double_rotated3d);\n  test_serialization(double_rotated3d);\n}\n\nvoid test_coordinate_map_with_rotation_map_datavector() {\n  using rotate2d = CoordinateMaps::Rotation<2>;\n  using rotate3d = CoordinateMaps::Rotation<3>;\n\n  // No 1D test because it would just the be affine map test\n\n  // Test 2D\n  {\n    const auto double_rotated2d =\n        make_coordinate_map<Frame::Logical, Frame::Grid>(rotate2d{M_PI_4},\n                                                         rotate2d{M_PI_2});\n    const auto first_rotated2d = rotate2d{M_PI_4};\n    const auto second_rotated2d = rotate2d{M_PI_2};\n\n    const tnsr::I<DataVector, 2, Frame::Logical> coords2d{\n        {{DataVector{0.1, -8.2, 5.7, 2.9}, DataVector{2.8, 2.8, -4.9, 3.4}}}};\n    const tnsr::I<DataVector, 2, Frame::Grid> coords2d_grid{\n        {{DataVector{0.1, -8.2, 5.7, 2.9}, DataVector{2.8, 2.8, -4.9, 3.4}}}};\n    const auto coords2d_array = make_array<DataVector, 2>(coords2d);\n\n    CHECK((make_array<DataVector, 2>(double_rotated2d(coords2d))) ==\n          second_rotated2d(first_rotated2d(coords2d_array)));\n\n    const auto jac = double_rotated2d.jacobian(coords2d);\n    const auto expected_jac =\n        compose_jacobians(first_rotated2d, second_rotated2d, coords2d_array);\n    CHECK_ITERABLE_APPROX(jac, expected_jac);\n\n    const auto inv_jac = double_rotated2d.inv_jacobian(coords2d);\n    const auto expected_inv_jac = compose_inv_jacobians(\n        first_rotated2d, second_rotated2d, coords2d_array);\n    CHECK_ITERABLE_APPROX(inv_jac, expected_inv_jac);\n  }\n\n  // Test 3D\n  {\n    const auto first_rotated3d = rotate3d{M_PI_4, M_PI_4, M_PI_2};\n    const auto second_rotated3d = rotate3d{M_PI_2, M_PI_4, M_PI_4};\n    const auto double_rotated3d_full =\n        make_coordinate_map<Frame::Logical, Frame::Grid>(first_rotated3d,\n                                                         second_rotated3d);\n    const auto double_rotated3d_base =\n        make_coordinate_map_base<Frame::Logical, Frame::Grid>(first_rotated3d,\n                                                              second_rotated3d);\n    const auto& double_rotated3d = *double_rotated3d_base;\n\n    CHECK(double_rotated3d_full == double_rotated3d);\n\n    const auto different_rotated3d_base =\n        make_coordinate_map_base<Frame::Logical, Frame::Grid>(second_rotated3d,\n                                                              first_rotated3d);\n    CHECK(*different_rotated3d_base == *different_rotated3d_base);\n    CHECK(*different_rotated3d_base != double_rotated3d);\n\n    const tnsr::I<DataVector, 3, Frame::Logical> coords3d{\n        {{DataVector{0.1, -8.2, 5.7, 2.9}, DataVector{2.8, 2.8, -4.9, 3.4},\n          DataVector{9.3, -9.7, 8.1, -7.8}}}};\n    const tnsr::I<DataVector, 3, Frame::Grid> coords3d_grid{\n        {{DataVector{0.1, -8.2, 5.7, 2.9}, DataVector{2.8, 2.8, -4.9, 3.4},\n          DataVector{9.3, -9.7, 8.1, -7.8}}}};\n    const auto coords3d_array = make_array<DataVector, 3>(coords3d);\n\n    CHECK((make_array<DataVector, 3>(double_rotated3d(coords3d))) ==\n          second_rotated3d(first_rotated3d(coords3d_array)));\n\n    const auto jac = double_rotated3d.jacobian(coords3d);\n    const auto expected_jac =\n        compose_jacobians(first_rotated3d, second_rotated3d, coords3d_array);\n    CHECK_ITERABLE_APPROX(jac, expected_jac);\n\n    const auto inv_jac = double_rotated3d.inv_jacobian(coords3d);\n    const auto expected_inv_jac = compose_inv_jacobians(\n        first_rotated3d, second_rotated3d, coords3d_array);\n    CHECK_ITERABLE_APPROX(inv_jac, expected_inv_jac);\n\n    // Check inequivalence operator\n    CHECK_FALSE(double_rotated3d_full != double_rotated3d_full);\n    test_serialization(double_rotated3d_full);\n  }\n}\n\nvoid test_coordinate_map_with_rotation_wedge() {\n  using Rotate = CoordinateMaps::Rotation<2>;\n  using Wedge2D = CoordinateMaps::Wedge2D;\n\n  const auto first_map = Rotate(2.);\n  const auto second_map =\n      Wedge2D(3., 7., 0.0, 1.0,\n              OrientationMap<2>{std::array<Direction<2>, 2>{\n                  {Direction<2>::lower_eta(), Direction<2>::lower_xi()}}},\n              false);\n\n  const auto composed_map =\n      make_coordinate_map<Frame::Logical, Frame::Grid>(first_map, second_map);\n\n  const std::array<double, 2> test_point_array{{0.1, 0.8}};\n  const tnsr::I<double, 2, Frame::Logical> test_point_vector(test_point_array);\n\n  const auto mapped_point_array = second_map(first_map(test_point_array));\n  const auto mapped_point_vector = composed_map(test_point_vector);\n  CHECK((make_array<double, 2>(mapped_point_vector)) == mapped_point_array);\n\n  const auto jac = composed_map.jacobian(test_point_vector);\n  const auto expected_jac =\n      compose_jacobians(first_map, second_map, test_point_array);\n  CHECK_ITERABLE_APPROX(jac, expected_jac);\n\n  const auto inv_jac = composed_map.inv_jacobian(test_point_vector);\n  const auto expected_inv_jac =\n      compose_inv_jacobians(first_map, second_map, test_point_array);\n  CHECK_ITERABLE_APPROX(inv_jac, expected_inv_jac);\n}\n\nvoid test_make_vector_coordinate_map_base() {\n  using Affine = CoordinateMaps::Affine;\n  using Affine2D = CoordinateMaps::ProductOf2Maps<Affine, Affine>;\n\n  const auto affine1d = make_coordinate_map<Frame::Logical, Frame::Grid>(\n      Affine{-1.0, 1.0, 2.0, 8.0});\n  const auto affine1d_base =\n      make_coordinate_map_base<Frame::Logical, Frame::Grid>(\n          Affine{-1.0, 1.0, 2.0, 8.0});\n  const auto vector_of_affine1d =\n      make_vector_coordinate_map_base<Frame::Logical, Frame::Grid>(\n          Affine{-1.0, 1.0, 2.0, 8.0});\n\n  CHECK(affine1d == *affine1d_base);\n  CHECK(*affine1d_base == affine1d);\n  CHECK(affine1d == *(vector_of_affine1d[0]));\n  CHECK(*(vector_of_affine1d[0]) == affine1d);\n\n  using Wedge2DMap = CoordinateMaps::Wedge2D;\n  const auto upper_xi_wedge =\n      Wedge2DMap{1.0,\n                 2.0,\n                 0.0,\n                 1.0,\n                 OrientationMap<2>{std::array<Direction<2>, 2>{\n                     {Direction<2>::upper_xi(), Direction<2>::upper_eta()}}},\n                 true};\n  const auto upper_eta_wedge =\n      Wedge2DMap{1.0,\n                 2.0,\n                 0.0,\n                 1.0,\n                 OrientationMap<2>{std::array<Direction<2>, 2>{\n                     {Direction<2>::upper_eta(), Direction<2>::lower_xi()}}},\n                 true};\n  const auto lower_xi_wedge =\n      Wedge2DMap{1.0,\n                 2.0,\n                 0.0,\n                 1.0,\n                 OrientationMap<2>{std::array<Direction<2>, 2>{\n                     {Direction<2>::lower_xi(), Direction<2>::lower_eta()}}},\n                 true};\n  const auto lower_eta_wedge =\n      Wedge2DMap{1.0,\n                 2.0,\n                 0.0,\n                 1.0,\n                 OrientationMap<2>{std::array<Direction<2>, 2>{\n                     {Direction<2>::lower_eta(), Direction<2>::upper_xi()}}},\n                 true};\n  const auto vector_of_wedges =\n      make_vector_coordinate_map_base<Frame::Logical, Frame::Inertial>(\n          Wedge2DMap{\n              1.0, 2.0, 0.0, 1.0,\n              OrientationMap<2>{std::array<Direction<2>, 2>{\n                  {Direction<2>::upper_xi(), Direction<2>::upper_eta()}}},\n              true},\n          Wedge2DMap{\n              1.0, 2.0, 0.0, 1.0,\n              OrientationMap<2>{std::array<Direction<2>, 2>{\n                  {Direction<2>::upper_eta(), Direction<2>::lower_xi()}}},\n              true},\n          Wedge2DMap{\n              1.0, 2.0, 0.0, 1.0,\n              OrientationMap<2>{std::array<Direction<2>, 2>{\n                  {Direction<2>::lower_xi(), Direction<2>::lower_eta()}}},\n              true},\n          Wedge2DMap{\n              1.0, 2.0, 0.0, 1.0,\n              OrientationMap<2>{std::array<Direction<2>, 2>{\n                  {Direction<2>::lower_eta(), Direction<2>::upper_xi()}}},\n              true});\n\n  CHECK(make_coordinate_map<Frame::Logical, Frame::Inertial>(upper_xi_wedge) ==\n        *(vector_of_wedges[0]));\n  CHECK(make_coordinate_map<Frame::Logical, Frame::Inertial>(upper_eta_wedge) ==\n        *(vector_of_wedges[1]));\n  CHECK(make_coordinate_map<Frame::Logical, Frame::Inertial>(lower_xi_wedge) ==\n        *(vector_of_wedges[2]));\n  CHECK(make_coordinate_map<Frame::Logical, Frame::Inertial>(lower_eta_wedge) ==\n        *(vector_of_wedges[3]));\n  CHECK(*make_coordinate_map_base<Frame::Logical, Frame::Inertial>(\n            upper_xi_wedge) == *(vector_of_wedges[0]));\n  CHECK(*make_coordinate_map_base<Frame::Logical, Frame::Inertial>(\n            upper_eta_wedge) == *(vector_of_wedges[1]));\n  CHECK(*make_coordinate_map_base<Frame::Logical, Frame::Inertial>(\n            lower_xi_wedge) == *(vector_of_wedges[2]));\n  CHECK(*make_coordinate_map_base<Frame::Logical, Frame::Inertial>(\n            lower_eta_wedge) == *(vector_of_wedges[3]));\n\n  const auto wedges = std::vector<Wedge2DMap>{upper_xi_wedge, upper_eta_wedge,\n                                              lower_xi_wedge, lower_eta_wedge};\n  const auto vector_of_wedges2 =\n      make_vector_coordinate_map_base<Frame::Logical, Frame::Inertial, 2>(\n          wedges);\n  CHECK(make_coordinate_map<Frame::Logical, Frame::Inertial>(upper_xi_wedge) ==\n        *(vector_of_wedges2[0]));\n  CHECK(make_coordinate_map<Frame::Logical, Frame::Inertial>(upper_eta_wedge) ==\n        *(vector_of_wedges2[1]));\n  CHECK(make_coordinate_map<Frame::Logical, Frame::Inertial>(lower_xi_wedge) ==\n        *(vector_of_wedges2[2]));\n  CHECK(make_coordinate_map<Frame::Logical, Frame::Inertial>(lower_eta_wedge) ==\n        *(vector_of_wedges2[3]));\n  CHECK(*make_coordinate_map_base<Frame::Logical, Frame::Inertial>(\n            upper_xi_wedge) == *(vector_of_wedges2[0]));\n  CHECK(*make_coordinate_map_base<Frame::Logical, Frame::Inertial>(\n            upper_eta_wedge) == *(vector_of_wedges2[1]));\n  CHECK(*make_coordinate_map_base<Frame::Logical, Frame::Inertial>(\n            lower_xi_wedge) == *(vector_of_wedges2[2]));\n  CHECK(*make_coordinate_map_base<Frame::Logical, Frame::Inertial>(\n            lower_eta_wedge) == *(vector_of_wedges2[3]));\n\n  const auto translation =\n      Affine2D{Affine{-1.0, 1.0, -1.0, 1.0}, Affine{-1.0, 1.0, 0.0, 2.0}};\n  const auto vector_of_translated_wedges =\n      make_vector_coordinate_map_base<Frame::Logical, Frame::Inertial, 2>(\n          wedges, translation);\n\n  const auto translated_upper_xi_wedge =\n      make_coordinate_map<Frame::Logical, Frame::Inertial>(\n          Wedge2DMap{\n              1.0, 2.0, 0.0, 1.0,\n              OrientationMap<2>{std::array<Direction<2>, 2>{\n                  {Direction<2>::upper_xi(), Direction<2>::upper_eta()}}},\n              true},\n          translation);\n  const auto translated_upper_eta_wedge =\n      make_coordinate_map<Frame::Logical, Frame::Inertial>(\n          Wedge2DMap{\n              1.0, 2.0, 0.0, 1.0,\n              OrientationMap<2>{std::array<Direction<2>, 2>{\n                  {Direction<2>::upper_eta(), Direction<2>::lower_xi()}}},\n              true},\n          translation);\n  const auto translated_lower_xi_wedge =\n      make_coordinate_map<Frame::Logical, Frame::Inertial>(\n          Wedge2DMap{\n              1.0, 2.0, 0.0, 1.0,\n              OrientationMap<2>{std::array<Direction<2>, 2>{\n                  {Direction<2>::lower_xi(), Direction<2>::lower_eta()}}},\n              true},\n          translation);\n  const auto translated_lower_eta_wedge =\n      make_coordinate_map<Frame::Logical, Frame::Inertial>(\n          Wedge2DMap{\n              1.0, 2.0, 0.0, 1.0,\n              OrientationMap<2>{std::array<Direction<2>, 2>{\n                  {Direction<2>::lower_eta(), Direction<2>::upper_xi()}}},\n              true},\n          translation);\n  const auto translated_upper_xi_wedge_base =\n      make_coordinate_map_base<Frame::Logical, Frame::Inertial>(\n          Wedge2DMap{\n              1.0, 2.0, 0.0, 1.0,\n              OrientationMap<2>{std::array<Direction<2>, 2>{\n                  {Direction<2>::upper_xi(), Direction<2>::upper_eta()}}},\n              true},\n          translation);\n  const auto translated_upper_eta_wedge_base =\n      make_coordinate_map_base<Frame::Logical, Frame::Inertial>(\n          Wedge2DMap{\n              1.0, 2.0, 0.0, 1.0,\n              OrientationMap<2>{std::array<Direction<2>, 2>{\n                  {Direction<2>::upper_eta(), Direction<2>::lower_xi()}}},\n              true},\n          translation);\n  const auto translated_lower_xi_wedge_base =\n      make_coordinate_map_base<Frame::Logical, Frame::Inertial>(\n          Wedge2DMap{\n              1.0, 2.0, 0.0, 1.0,\n              OrientationMap<2>{std::array<Direction<2>, 2>{\n                  {Direction<2>::lower_xi(), Direction<2>::lower_eta()}}},\n              true},\n          translation);\n  const auto translated_lower_eta_wedge_base =\n      make_coordinate_map_base<Frame::Logical, Frame::Inertial>(\n          Wedge2DMap{\n              1.0, 2.0, 0.0, 1.0,\n              OrientationMap<2>{std::array<Direction<2>, 2>{\n                  {Direction<2>::lower_eta(), Direction<2>::upper_xi()}}},\n              true},\n          translation);\n\n  CHECK(translated_upper_xi_wedge == *(vector_of_translated_wedges[0]));\n  CHECK(translated_upper_eta_wedge == *(vector_of_translated_wedges[1]));\n  CHECK(translated_lower_xi_wedge == *(vector_of_translated_wedges[2]));\n  CHECK(translated_lower_eta_wedge == *(vector_of_translated_wedges[3]));\n  CHECK(*translated_upper_xi_wedge_base == *(vector_of_translated_wedges[0]));\n  CHECK(*translated_upper_eta_wedge_base == *(vector_of_translated_wedges[1]));\n  CHECK(*translated_lower_xi_wedge_base == *(vector_of_translated_wedges[2]));\n  CHECK(*translated_lower_eta_wedge_base == *(vector_of_translated_wedges[3]));\n}\n}  // namespace\n\nSPECTRE_TEST_CASE(\"Unit.Domain.CoordinateMap\", \"[Domain][Unit]\") {\n  test_single_coordinate_map();\n  test_coordinate_map_with_affine_map();\n  test_coordinate_map_with_rotation_map();\n  test_coordinate_map_with_rotation_map_datavector();\n  test_coordinate_map_with_rotation_wedge();\n  test_make_vector_coordinate_map_base();\n}\n", "meta": {"hexsha": "b32f3523e55aa2f66d0fae1e22d892ab7f3ea536", "size": 33033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/Domain/CoordinateMaps/Test_CoordinateMap.cpp", "max_stars_repo_name": "marissawalker/spectre", "max_stars_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_stars_repo_licenses": ["MIT"], "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/Domain/CoordinateMaps/Test_CoordinateMap.cpp", "max_issues_repo_name": "marissawalker/spectre", "max_issues_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_issues_repo_licenses": ["MIT"], "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/Domain/CoordinateMaps/Test_CoordinateMap.cpp", "max_forks_repo_name": "marissawalker/spectre", "max_forks_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_forks_repo_licenses": ["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.4073587385, "max_line_length": 80, "alphanum_fraction": 0.5922562286, "num_tokens": 10131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5099992557784787}}
{"text": "/**\n * To optimize over the set of a unit 2-sphere\n */\n\n#ifndef WAVE_SPHERICAL_PARAMETERIZATION_HPP\n#define WAVE_SPHERICAL_PARAMETERIZATION_HPP\n\n#include <Eigen/Core>\n#include <ceres/ceres.h>\n#include <ceres/local_parameterization.h>\n#include \"wave/utils/math.hpp\"\n\nnamespace wave {\n\nclass SphericalParameterization : public ceres::LocalParameterization {\n public:\n    virtual ~SphericalParameterization() {}\n    virtual bool Plus(const double* x, const double* delta, double* x_plus_delta) const;\n    virtual bool ComputeJacobian(const double* x, double* jacobian) const;\n    virtual int GlobalSize() const { return 3; }\n    virtual int LocalSize() const { return 2; }\n};\n\n}\n\n#endif //WAVE_SPHERICAL_PARAMETERIZATION_HPP\n", "meta": {"hexsha": "de831486941251aeb0eba9dfb2048dfafeb28f4a", "size": 722, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "wave_optimization/include/wave/optimization/ceres/local_params/spherical_parameterization.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_optimization/include/wave/optimization/ceres/local_params/spherical_parameterization.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_optimization/include/wave/optimization/ceres/local_params/spherical_parameterization.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": 26.7407407407, "max_line_length": 88, "alphanum_fraction": 0.7576177285, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5099992557784787}}
{"text": "/**\n * @file dense_inversion.cpp\n * @brief Benchmarks the inversion of 1 random square matrix of increasing size\n *\n * @author Matthew Powelson\n * @date April 1, 2020\n * @version TODO\n * @bug No known bugs\n *\n * @copyright Copyright (c) 2020, Southwest Research Institute\n *\n * @par License\n * Software License Agreement (Apache License)\n * @par\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 * @par\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 <benchmark/benchmark.h>\n\n#include <arrayfire.h>\n#include <Eigen/Eigen>\n#include <torch/torch.h>\n\nauto BM_PYTORCH_INV = [](benchmark::State& state, int size, torch::Device device) {\n  torch::TensorOptions options =\n      torch::TensorOptions().dtype(torch::kFloat64).layout(torch::kStrided).device(device).requires_grad(true);\n\n  torch::manual_seed(0);\n  torch::Tensor tensor0 = torch::rand({ size, size }, options);\n\n  torch::Tensor result = torch::rand({ size, size }, options);\n  for (auto _ : state)\n  {\n    benchmark::DoNotOptimize(result = tensor0.inverse());\n  }\n};\n\nauto BM_EIGEN_INV = [](benchmark::State& state, int size) {\n  Eigen::MatrixXd matrix0 = Eigen::MatrixXd::Random(size, size);\n  Eigen::MatrixXd result = Eigen::MatrixXd::Random(size, size);\n  for (auto _ : state)\n  {\n    benchmark::DoNotOptimize(result = matrix0.inverse());\n  }\n};\n\n// TODO: Make sure the ArrayFire benchmarks are actually executing since they normally use lazy execution\nauto BM_ARRAYFIRE_INV = [](benchmark::State& state, int size, auto device) {\n  af::setBackend(device);\n\n  af::setSeed(0);\n  af::array array0 = af::randu(size, size);\n\n  af::array result = af::randu(size, size);\n  for (auto _ : state)\n  {\n    benchmark::DoNotOptimize(result = af::inverse(array0));\n  }\n};\n\nint main(int argc, char** argv)\n{\n  for (auto& test_input : { 2, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1028, 2056})\n  {\n    std::string name = \"BM_PYTORCH_CPU_INV_Size_\" + std::to_string(test_input);\n    benchmark::RegisterBenchmark(name.c_str(), BM_PYTORCH_INV, test_input, torch::kCPU)\n        ->UseRealTime()\n        ->Unit(benchmark::TimeUnit::kMicrosecond);\n  }\n  for (auto& test_input : { 2, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1028, 2056})\n  {\n    std::string name = \"BM_PYTORCH_GPU_INV_Size_\" + std::to_string(test_input);\n    benchmark::RegisterBenchmark(name.c_str(), BM_PYTORCH_INV, test_input, torch::kCUDA)\n        ->UseRealTime()\n        ->Unit(benchmark::TimeUnit::kMicrosecond);\n  }\n  for (auto& test_input : { 2, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1028, 2056})\n  {\n    std::string name = \"BM_EIGEN_INV_Size_\" + std::to_string(test_input);\n    benchmark::RegisterBenchmark(name.c_str(), BM_EIGEN_INV, test_input)\n        ->UseRealTime()\n        ->Unit(benchmark::TimeUnit::kMicrosecond);\n  }\n  for (auto& test_input : { 2, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1028, 2056})\n  {\n    std::string name = \"BM_ARRAYFIRE_CPU_INV_Size_\" + std::to_string(test_input);\n    benchmark::RegisterBenchmark(name.c_str(), BM_ARRAYFIRE_INV, test_input, AF_BACKEND_CPU)\n        ->UseRealTime()\n        ->Unit(benchmark::TimeUnit::kMicrosecond);\n  }\n  for (auto& test_input : { 2, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1028, 2056})\n  {\n    std::string name = \"BM_ARRAYFIRE_CUDA_INV_Size_\" + std::to_string(test_input);\n    benchmark::RegisterBenchmark(name.c_str(), BM_ARRAYFIRE_INV, test_input, AF_BACKEND_CUDA)\n        ->UseRealTime()\n        ->Unit(benchmark::TimeUnit::kMicrosecond);\n  }\n  for (auto& test_input : { 2, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1028, 2056})\n  {\n    std::string name = \"BM_ARRAYFIRE_OPENCL_INV_Size_\" + std::to_string(test_input);\n    benchmark::RegisterBenchmark(name.c_str(), BM_ARRAYFIRE_INV, test_input, AF_BACKEND_OPENCL)\n        ->UseRealTime()\n        ->Unit(benchmark::TimeUnit::kMicrosecond);\n  }\n  benchmark::Initialize(&argc, argv);\n  benchmark::RunSpecifiedBenchmarks();\n}\n", "meta": {"hexsha": "741d89606aac2be2330a442da85e8ad43fa135bb", "size": 4288, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dense_inversion.cpp", "max_stars_repo_name": "mpowelson/matrix_math_benchmarks", "max_stars_repo_head_hexsha": "b1796c2c8e1eb1af2691129decc156f68ef3d07a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T18:25:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T02:08:27.000Z", "max_issues_repo_path": "src/dense_inversion.cpp", "max_issues_repo_name": "mpowelson/matrix_math_benchmarks", "max_issues_repo_head_hexsha": "b1796c2c8e1eb1af2691129decc156f68ef3d07a", "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/dense_inversion.cpp", "max_forks_repo_name": "mpowelson/matrix_math_benchmarks", "max_forks_repo_head_hexsha": "b1796c2c8e1eb1af2691129decc156f68ef3d07a", "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.6495726496, "max_line_length": 111, "alphanum_fraction": 0.6830690299, "num_tokens": 1268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5099992557784787}}
{"text": "/*\n * This file is part of the statismo library.\n *\n * Author: Marcel Luethi (marcel.luethi@unibas.ch)\n *\n * Copyright (c) 2011 University of Basel\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 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 *\n * Neither the name of the project's author 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\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 COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * 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\n#ifndef __STATIMO_CORE_PCA_MODEL_BUILDER_HXX_\n#define __STATIMO_CORE_PCA_MODEL_BUILDER_HXX_\n\n#include \"statismo/core/PCAModelBuilder.h\"\n#include \"statismo/core/CommonTypes.h\"\n#include \"statismo/core/Exceptions.h\"\n\n#include <Eigen/SVD>\n#include <Eigen/Eigenvalues>\n\nnamespace statismo\n{\n\ntemplate <typename T>\nUniquePtrType<typename PCAModelBuilder<T>::StatisticalModelType>\nPCAModelBuilder<T>::BuildNewModel(const DataItemListType & sampleDataList,\n                                  double                   noiseVariance,\n                                  bool                     computeScores,\n                                  EigenValueMethod         method) const\n{\n\n  STATISMO_LOG_INFO(\"Building new model\");\n  STATISMO_LOG_INFO(\"Noise variance: \" + std::to_string(noiseVariance));\n\n  auto n = sampleDataList.size();\n  STATISMO_LOG_INFO(\"Sample count: \" + std::to_string(n));\n\n  if (n <= 0)\n  {\n    throw StatisticalModelException(\"Provided empty sample set. Cannot build the sample matrix\",\n                                    Status::BAD_INPUT_ERROR);\n  }\n\n  unsigned     p = sampleDataList.front()->GetSampleVector().rows();\n  const auto * representer = sampleDataList.front()->GetRepresenter();\n\n  // Compute the mean vector mu\n  VectorType mu = VectorType::Zero(p);\n\n  for (const auto & item : sampleDataList)\n  {\n    assert(item->GetSampleVector().rows() == p);   // all samples must have same number of rows\n    assert(item->GetRepresenter() == representer); // all samples have the same representer\n    mu += item->GetSampleVector();\n  }\n\n  mu /= n;\n\n  // Build the mean free sample matrix X0\n  MatrixType matX0(n, p);\n  unsigned   i{ 0 };\n  for (const auto & item : sampleDataList)\n  {\n    matX0.row(i++) = item->GetSampleVector() - mu;\n  }\n\n  // build the model\n  auto model = BuildNewModelInternal(representer, matX0, mu, noiseVariance, method);\n\n  // compute the scores if requested\n  MatrixType scores;\n  if (computeScores)\n  {\n    scores = this->ComputeScores(sampleDataList, model.get());\n  }\n\n  typename BuilderInfo::ParameterInfoList bi;\n  bi.emplace_back(BuilderInfo::KeyValuePair(\"NoiseVariance \", std::to_string(noiseVariance)));\n\n  typename BuilderInfo::DataInfoList dataInfo;\n  i = 0;\n  for (const auto & item : sampleDataList)\n  {\n    STATISMO_LOG_INFO(\"Adding info about dataset with uri \" + item->GetDatasetURI());\n    std::ostringstream os;\n    os << \"URI_\" << i++;\n    dataInfo.emplace_back(os.str().c_str(), item->GetDatasetURI());\n  }\n\n  // finally add meta data to the model info\n  ModelInfo::BuilderInfoList biList;\n  biList.emplace_back(\"PCAModelBuilder\", dataInfo, bi);\n\n  model->SetModelInfo(ModelInfo{ scores, biList });\n\n  return model;\n}\n\n\ntemplate <typename T>\nUniquePtrType<typename PCAModelBuilder<T>::StatisticalModelType>\nPCAModelBuilder<T>::BuildNewModelInternal(const Representer<T> * representer,\n                                          const MatrixType &     matX0,\n                                          const VectorType &     mu,\n                                          double                 noiseVariance,\n                                          EigenValueMethod       method) const\n{\n  unsigned n = matX0.rows();\n  unsigned p = matX0.cols();\n\n  STATISMO_LOG_INFO(\"n: \" + std::to_string(n));\n  STATISMO_LOG_INFO(\"p: \" + std::to_string(p));\n\n  switch (method)\n  {\n    case EigenValueMethod::JACOBI_SVD:\n\n      STATISMO_LOG_INFO(\"Using JACOBI_SVD method\");\n\n      using SVDType = Eigen::JacobiSVD<MatrixType>;\n      using SVDDoublePrecisionType = Eigen::JacobiSVD<MatrixTypeDoublePrecision>;\n\n      // We destinguish the case where we have more variables than samples and\n      // the case where we have more samples than variable.\n      // In the first case we compute the (smaller) inner product matrix instead of the full covariance matrix.\n      // It is known that this has the same non-zero singular values as the covariance matrix.\n      // Furthermore, it is possible to compute the corresponding eigenvectors of the covariance matrix from the\n      // decomposition.\n\n      if (n < p)\n      {\n        // we compute the eigenvectors of the covariance matrix by computing an SVD of the\n        // n x n inner product matrix 1/(n-1) X0X0^T\n        MatrixType             cov = matX0 * matX0.transpose() * 1.0 / (n - 1);\n        SVDDoublePrecisionType svd(cov.cast<double>(), Eigen::ComputeThinV);\n        VectorType             singularValues = svd.singularValues().cast<ScalarType>();\n        MatrixType             matV = svd.matrixV().cast<ScalarType>();\n\n        unsigned numComponentsAboveTolerance =\n          ((singularValues.array() - noiseVariance - Superclass::sk_tolerance) > 0).count();\n\n        // there can be at most n-1 nonzero singular values in this case. Everything else must be due to numerical\n        // inaccuracies\n        unsigned numComponentsToKeep = std::min(numComponentsAboveTolerance, n - 1);\n        // compute the pseudo inverse of the square root of the singular values\n        // which is then needed to recompute the PCA basis\n        VectorType singSqrt = singularValues.array().sqrt();\n        VectorType singSqrtInv = VectorType::Zero(singSqrt.rows());\n        for (unsigned i = 0; i < numComponentsToKeep; i++)\n        {\n          assert(singSqrt(i) > Superclass::sk_tolerance);\n          singSqrtInv(i) = 1.0 / singSqrt(i);\n        }\n\n        if (numComponentsToKeep == 0)\n        {\n          STATISMO_LOG_ERROR(\"No component to keep\");\n          throw StatisticalModelException(\"All the eigenvalues are below the given tolerance. Model cannot be built.\");\n        }\n\n        // we recover the eigenvectors U of the full covariance matrix from the eigenvectors V of the inner product\n        // matrix. We use the fact that if we decompose X as X=UDV^T, then we get X^TX = UD^2U^T and XX^T = VD^2V^T\n        // (exploiting the orthogonormality of the matrix U and V from the SVD). The additional factor sqrt(n-1) is to\n        // compensate for the 1/sqrt(n-1) in the formula for the covariance matrix.\n\n        MatrixType pcaBasis = matX0.transpose() * matV * singSqrtInv.asDiagonal();\n        pcaBasis /= sqrt(n - 1.0);\n        pcaBasis.conservativeResize(Eigen::NoChange, numComponentsToKeep);\n\n\n        VectorType sampleVarianceVector = singularValues.topRows(numComponentsToKeep);\n        VectorType pcaVariance = (sampleVarianceVector - VectorType::Ones(numComponentsToKeep) * noiseVariance);\n\n        auto model = StatisticalModelType::SafeCreate(representer, mu, pcaBasis, pcaVariance, noiseVariance);\n\n        return model;\n      }\n      else // NOLINT\n      {\n        // we compute an SVD of the full p x p  covariance matrix 1/(n-1) X0^TX0 directly\n        SVDType    svd(matX0.transpose() * matX0, Eigen::ComputeThinU);\n        VectorType singularValues = svd.singularValues();\n        singularValues /= (n - 1.0);\n        unsigned numComponentsToKeep =\n          ((singularValues.array() - noiseVariance - Superclass::sk_tolerance) > 0).count();\n        MatrixType pcaBasis = svd.matrixU();\n\n        pcaBasis.conservativeResize(Eigen::NoChange, numComponentsToKeep);\n\n        if (numComponentsToKeep == 0)\n        {\n          STATISMO_LOG_ERROR(\"No component to keep\");\n          throw StatisticalModelException(\"All the eigenvalues are below the given tolerance. Model cannot be built.\");\n        }\n\n        VectorType sampleVarianceVector = singularValues.topRows(numComponentsToKeep);\n        VectorType pcaVariance = (sampleVarianceVector - VectorType::Ones(numComponentsToKeep) * noiseVariance);\n        auto       model = StatisticalModelType::SafeCreate(representer, mu, pcaBasis, pcaVariance, noiseVariance);\n        return model;\n      }\n      break;\n\n    case EigenValueMethod::SELF_ADJOINT_EIGEN_SOLVER:\n    {\n      STATISMO_LOG_INFO(\"Using SELF_ADJOINT_EIGEN_SOLVER method\");\n      // we compute the eigenvalues/eigenvectors of the full p x p  covariance matrix 1/(n-1) X0^TX0 directly\n\n      using SelfAdjointEigenSolver = Eigen::SelfAdjointEigenSolver<MatrixType>;\n      SelfAdjointEigenSolver es;\n      es.compute(matX0.transpose() * matX0);\n      VectorType eigenValues =\n        es.eigenvalues().reverse(); // SelfAdjointEigenSolver orders the eigenvalues in increasing order\n      eigenValues /= (n - 1.0);\n\n      unsigned   numComponentsToKeep = ((eigenValues.array() - noiseVariance - Superclass::sk_tolerance) > 0).count();\n      MatrixType pcaBasis = es.eigenvectors().rowwise().reverse();\n      pcaBasis.conservativeResize(Eigen::NoChange, numComponentsToKeep);\n\n      if (numComponentsToKeep == 0)\n      {\n        throw StatisticalModelException(\"All the eigenvalues are below the given tolerance. Model cannot be built.\");\n      }\n\n      VectorType sampleVarianceVector = eigenValues.topRows(numComponentsToKeep);\n      VectorType pcaVariance = (sampleVarianceVector - VectorType::Ones(numComponentsToKeep) * noiseVariance);\n      auto       model = StatisticalModelType::SafeCreate(representer, mu, pcaBasis, pcaVariance, noiseVariance);\n      return model;\n    }\n    break;\n\n    default:\n      throw StatisticalModelException(\"Unrecognized decomposition/eigenvalue solver method.\");\n  }\n  return nullptr;\n}\n\n\n} // namespace statismo\n\n#endif\n", "meta": {"hexsha": "e84213e6d24886cf7863436f9ff5a74ba5187bfa", "size": 10868, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "modules/core/include/statismo/core/PCAModelBuilder.hxx", "max_stars_repo_name": "skn123/statismo-1", "max_stars_repo_head_hexsha": "a380f33cf070d1c4ba624db8b0c6d946d2aecabf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T17:24:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T11:54:59.000Z", "max_issues_repo_path": "modules/core/include/statismo/core/PCAModelBuilder.hxx", "max_issues_repo_name": "latimagine/statismo", "max_issues_repo_head_hexsha": "a380f33cf070d1c4ba624db8b0c6d946d2aecabf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-01-22T09:05:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T10:10:24.000Z", "max_forks_repo_path": "modules/core/include/statismo/core/PCAModelBuilder.hxx", "max_forks_repo_name": "latimagine/statismo", "max_forks_repo_head_hexsha": "a380f33cf070d1c4ba624db8b0c6d946d2aecabf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-11T19:41:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T12:57:20.000Z", "avg_line_length": 40.552238806, "max_line_length": 119, "alphanum_fraction": 0.6818181818, "num_tokens": 2583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5099992541179589}}
{"text": "#include <iostream> //std::cout\n#include <chrono> //std::chrono::high_resolution_clock, std::chrono::duration_cast\n#include <fstream> // std::ofstream \n#include <filesystem> //fs::is_directory, fs::create_directory\n#include <boost/progress.hpp> //boost::progress_display, boost::progress_timer\n#include <numeric> //std::accumulate\n\n#include \"histogram.h\"\n#include \"init.h\"\n#include \"vars.h\"\n#include \"evolve.h\"\n\nnamespace fs = std::filesystem;\nvoid print_parameters();\n\n//three function declarations below are no longer in use\nstd::vector<std::vector<double>> evolve_and_hist(float time, std::vector <std::vector<double>> init_vel_matrix, std::vector <std::vector<double>> init_pos_matrix, std::list<double> bin_list);\nvoid sample_xv_in_csv(std::string folder, std::string file, float time, std::vector <std::vector<double>> init_vel_matrix, std::vector <std::vector<double>> init_pos_matrix, bool exporting_vel);\nvoid old_main();\n/*\n * Runs hard rod gas simulation a number of times given by no_samples for each sampling_time, up until max_time. Set ALL parameters in vars.h\n * Saves the averaged density and current distribution time_series of each simulation run in two csv files.\n */\nint main() {    \n\n    print_parameters();\n\n    //Create a directory if there isn't one       \n    if (fs::is_directory(folder_name)) { std::cout << \"N.B. Directory with this name already exists.\\n\\n\"; }\n    else { fs::create_directory(folder_name); }\n    \n    //Initialise csv files for exporting    \n    //Set file names\n    std::string file_name = \"T\" + std::to_string(int(max_time)) + \"_ST\" + std::to_string(int(sampling_time)) + \\\n        \"_V\" + std::to_string(float(V)) + \"_kickW\" + std::to_string(kick_width) + \"_temp\" + std::to_string(float(T)) + \\\n        \"_samples\" + std::to_string(no_samples) \\\n        + \"_rods\" + std::to_string(N) + \"_sys_length\" + std::to_string(int(L)) + \"_rodlength\" + std::to_string(float(rod_length));\n\n    std::ofstream rho_bar_csvfile;\n    rho_bar_csvfile.open(\".\\\\\" + folder_name + \"\\\\D_\" + file_name + \".csv\"); //Create csv file in which density data is stored\n\n    std::ofstream j_bar_csvfile;\n    j_bar_csvfile.open(\".\\\\\" + folder_name + \"\\\\J_\" + file_name + \".csv\"); //Create csv file in which current data is stored\n\n    if (fs::exists(\".\\\\\" + folder_name + \"\\\\\" + file_name)) {\n        std::cout << \"File name already exists - please rename. exiting\";\n        return 0;\n    }\n    else {        \n\n        //Initialise matrices of density + current data for reading to csv\n\n        int no_time_samples = std::round(max_time / sampling_time + 1); \n        int no_cells = std::round(L / cell_length);\n\n        std::vector<std::vector<double>> rho_accumulator(no_time_samples, std::vector<double>(no_cells)); //density matrix size no_time_samples x no_cells\n        std::vector<std::vector<double>> j_accumulator(no_time_samples, std::vector<double>(no_cells)); //current matrix size no_time_samples x no_cells\n\n        //Initialise histogram bins\n\n        std::list<double> bins_list = init_bins(std::round(L / cell_length));                    \n\n        //Initalise progress bar\n        std::cout << \"Running simulation:\" << \"\\n\";\n        unsigned int sample_size = no_samples;\n        boost::progress_display show_progress(sample_size);\n\n        //Start timing\n        \n        boost::progress_timer t;\n\n        for (unsigned int i = 0; i < sample_size; i++) {\n\n            //initialise sample positions + velocities from init.cpp\n\n            std::vector<double> x_0 = init_uniform_positions();\n\n            std::vector<double> v_0 = init_velocities();\n\n            if (implementing_v_kick) { v_0 = velocity_kick(kick_centre, V, kick_width, v_0, x_0); }\n\n            for (int j = 0; j < static_cast<int> (max_time / sampling_time) + 1; j++) {\n\n                std::vector<std::vector<double>> xv_evolved = evolve_to(sampling_time * j, x_0, v_0); // call evolve.cpp function\n\n                std::vector<std::vector<double>> rho_j_dist_matrix = rho_j_dist(xv_evolved[0], xv_evolved[1], bins_list); // call histogram.cpp function\n\n                //std::cout << std::accumulate(rho_j_dist_matrix[0].begin(), rho_j_dist_matrix[0].end(), 0); //print out sum of the bins\n\n                //add to density and current containers\n                std::transform(rho_accumulator[j].begin(), rho_accumulator[j].end(), rho_j_dist_matrix[0].begin(), rho_accumulator[j].begin(), std::plus<double>());\n                std::transform(j_accumulator[j].begin(), j_accumulator[j].end(), rho_j_dist_matrix[1].begin(), j_accumulator[j].begin(), std::plus<double>());\n\n            }\n\n            ++show_progress;\n\n        }\n        int sample_no = no_samples; //no_samples is a const so can't be used in a lambda\n\n        for (int i = 0; i < no_time_samples; i++) {\n            //normalise rho and j by sample_no\n            std::transform(rho_accumulator[i].begin(), rho_accumulator[i].end(), rho_accumulator[i].begin(), [&sample_no](auto& c) {return c / sample_no;});\n            std::transform(j_accumulator[i].begin(), j_accumulator[i].end(), j_accumulator[i].begin(), [&sample_no](auto& c) {return c / sample_no;});\n        }\n        //write rho_accumulator and j_accumulator matrices to csv files\n\n        if (rho_bar_csvfile.is_open()) {\n\n            for (unsigned i = 0; i < rho_accumulator.size(); i++) {\n                for (unsigned j = 0; j < rho_accumulator[i].size() - 1; j++) {\n                    rho_bar_csvfile << rho_accumulator[i][j] << \",\";\n                }\n                rho_bar_csvfile << rho_accumulator[i].back() << \"\\n\"; //last entry on row doesn't require a comma\n            }\n        }\n        else {\n            std::cout << \"\\nError opening file.\";\n        }\n\n        if (j_bar_csvfile.is_open()) {\n\n            for (unsigned i = 0; i < j_accumulator.size(); i++) {\n                for (unsigned j = 0; j < j_accumulator[i].size() - 1; j++) {\n                    j_bar_csvfile << j_accumulator[i][j] << \",\";\n                }\n                j_bar_csvfile << j_accumulator[i].back() << \"\\n\"; //last entry on row doesn't require a comma\n            }\n        }\n        else {\n            std::cout << \"\\nError opening file.\";\n        }\n        //End of simulation\n        std::cout << \"\\n\\nHard rod simulation has completed with runtime of \";\n    }    \n}\n\n/*\n * Prints parameters in vars.h\n */\nvoid print_parameters() {\n    std::cout << \"Parameters chosen:\\n\";\n    std::cout << \"Max_Time: \" << max_time << \" Sampling_Time: \" << sampling_time << \" No_Samples: \" << no_samples << \"\\n\";\n    std::cout << \"No_Rods: \" << N << \" Temp: \" << T << \" Sys_Length: \" << L << \" Rod_Length: \" << std::to_string(rod_length) << \" Cell_Length: \" << std::to_string(cell_length) << \"\\n\\n\";\n    std::cout << \"Position sampling method: \" << posn_init_method << \"\\n\";\n\n    if (posn_init_method == \"init_densityjump\") {\n        std::cout << \"Left_weight: \" << l_weight << \" Right_weight: \" << r_weight << \"\\n\";\n    }\n\n    if (implementing_v_kick) {\n        std::cout << \"Implementing_v_kick: Yes\" << \"\\n\";\n        std:: cout << \"Kick_Centre: \" << kick_centre << \" Kick_Width: \" << kick_width << \" Kick_Strength: \" << V << \"\\n\\n\";\n    }\n    else {\n        std::cout << \"Implementing_v_kick: No\" << \"\\n\";\n    }\n}\n\n/*\n* Calls evolve.cpp and hist.cpp functions - returns averaged density and current distributions for each time. \n*/\nstd::vector<std::vector<double>> evolve_and_hist(float time, std::vector <std::vector<double>> init_vel_matrix, std::vector <std::vector<double>> init_pos_matrix, std::list<double> bin_list) {\n\n    std::vector<double> rho_accumulator(std::round(L / cell_length)); //initialise vector which adds the density distributions for each sample\n    std::vector<double> j_accumulator(std::round(L / cell_length)); //initialise vector which adds the current distributions for each sample\n\n    for (size_t i = 0; i < init_vel_matrix.size(); i++) {\n\n        auto start = std::chrono::high_resolution_clock::now();\n\n        //std::cout << \"\\nRun \" << i << \" is in progress...\";\n        auto iter_start = std::chrono::high_resolution_clock::now();\n\n        //Call evolve.cpp function\n        auto xv_matrix = evolve_to(time, init_pos_matrix[i], init_vel_matrix[i]); // x_evolved = xv_matrix[0]; v_evolved = xv_matrix[1]        \n\n        //histogram call\n        auto rho_j_dist_matrix = rho_j_dist(xv_matrix[0], xv_matrix[1],bin_list);\n        \n\n        //add to density and current containers\n        std::transform(rho_accumulator.begin(), rho_accumulator.end(), rho_j_dist_matrix[0].begin(), rho_accumulator.begin(), std::plus<double>()); \n        std::transform(j_accumulator.begin(), j_accumulator.end(), rho_j_dist_matrix[1].begin(), j_accumulator.begin(), std::plus<double>());\n\n        // Print time data\n        auto iter_stop = std::chrono::high_resolution_clock::now();\n        auto iter_duration = std::chrono::duration_cast<std::chrono::microseconds>(iter_stop - iter_start);\n        auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(iter_stop - start);\n    }\n    //normalise density and current containers by no_samples\n    int sample_no = no_samples;\n    std::transform(rho_accumulator.begin(), rho_accumulator.end(), rho_accumulator.begin(), [&sample_no](auto& c) {return c / sample_no;});\n    std::transform(j_accumulator.begin(), j_accumulator.end(), j_accumulator.begin(), [& sample_no](auto& c) {return c / sample_no;});\n\n    return { rho_accumulator, j_accumulator };\n}\n\n/*\n * Creates a .csv file for both x[N] and v[N] after the system is evolved to a particular time. Both .csv files have 'no_rods' columns and 'no_samples' rows.\n * \n * @param std::string folder is the existing/new folder in which you want to store the .csv file\n * @param std::string file contains the simulation parameter data of the .csv file\n * @param float time is the duration for which evolve_to runs (evolve_to takes 'time' as an argument)\n * @param init_vel_matrix and init_pos_matrix are the matrices containing 'no_samples' intial velocity and position vectors respectively\n * @param bool export_vel exports velocities to a csv file, default value is False.\n */\nvoid sample_xv_in_csv(std::string folder, std::string file, float time, std::vector <std::vector<double>> init_vel_matrix, std::vector <std::vector<double>> init_pos_matrix, bool exporting_vel) {\n\n    std::ofstream positions_csv_file;\n    positions_csv_file.open(\".\\\\\" + folder + \"\\\\P_\" + file + \".csv\"); //Create csv file in which position data is stored\n\n    \n    std::ofstream velocities_csv_file;\n    velocities_csv_file.open(\".\\\\\" + folder + \"\\\\V_\" + file + \".csv\"); //Create csv file in which velocity data is stored\n    \n    //std::cout << \"Beginning sample_run:\" << \"\\n\";\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    //Call evolve functions 'sample_no' times\n    \n    for (size_t i = 0; i < init_vel_matrix.size(); i++) {\n\n        //std::cout << \"\\nRun \" << i << \" is in progress...\";\n        auto iter_start = std::chrono::high_resolution_clock::now();\n\n        //Call evolve.cpp function\n        auto xv_matrix = evolve_to(time, init_pos_matrix[i], init_vel_matrix[i]); // x_evolved = xv_matrix[0]; v_evolved = xv_matrix[1]        \n        \n        //HISTOGRAM CALL\n                \n        // Print time data\n        auto iter_stop = std::chrono::high_resolution_clock::now();\n        auto iter_duration = std::chrono::duration_cast<std::chrono::microseconds>(iter_stop - iter_start);\n        auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(iter_stop - start);\n\n        //std::cout << \" and has completed after \" << iter_duration.count() << \"mu_s. Total runtime is \" << time_elapsed.count() << \"ms.\";\n        \n        \n\n        //Entering position data to csv file\n        if (positions_csv_file.is_open()) {\n\n            for (int j = 0; j < N - 1; j++) {\n                //positions_csv_file << xv_matrix[0][j] << \",\";\n            }\n            //positions_csv_file << xv_matrix[0][N - 1] << \"\\n\"; //last entry on row doesn't require a comma\n        }\n        else {\n            std::cout << \"\\nError opening file.\";\n        }\n\n        if (exporting_vel) {\n            if (velocities_csv_file.is_open()) {\n\n                for (int j = 0; j < N - 1; j++) {\n                    //velocities_csv_file << xv_matrix[1][j] << \",\";\n                }\n                //velocities_csv_file << xv_matrix[1][N - 1] << \"\\n\"; //last entry on row doesn't require a comma\n            }\n            else {\n                std::cout << \"\\nError opening file.\";\n            }\n        }\n\n    }\n    //Close csv files\n    positions_csv_file.close();\n    if (exporting_vel) {\n        velocities_csv_file.close();\n    }\n    else {\n        velocities_csv_file.close();\n        fs::remove(\".\\\\\" + folder + \"\\\\V_\" + file + \".csv\");\n    }\n}\n\nvoid old_main() {\n    print_parameters();\n\n    //Run initialisation\n    //Create a directory if there isn't one       \n    if (fs::is_directory(folder_name)) { std::cout << \"N.B. Directory with this name already exists.\\n\\n\"; }\n    else { fs::create_directory(folder_name); }\n\n    //Start clock\n    std::cout << \"Beginning simulation:\" << \"\\n\";\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    //Call init.cpp functions\n    std::cout << \"Initialisation in progress...\";\n    std::vector <std::vector<double>> init_vel_matrix = init_velocities_matrix();\n    std::vector <std::vector<double>> init_posn_matrix = init_positions_matrix(posn_init_method);\n\n    if (implementing_v_kick) { init_vel_matrix = kick_velocity_matrix(init_vel_matrix, init_posn_matrix); }\n\n    auto init_stop = std::chrono::high_resolution_clock::now();\n    auto init_duration = std::chrono::duration_cast<std::chrono::milliseconds>(init_stop - start);\n    std::cout << \" and has completed after \" << init_duration.count() << \"ms. total runtime is \" << init_duration.count() / 1000 << \"s.\";\n\n    std::cout << \"\\nBegin evolving + sampling:\" << \"\\n\";\n\n    //set file_name\n    std::string file_name = \"T\" + std::to_string(std::round(max_time)) + \"ST\" + std::to_string(std::round(sampling_time)) + \\\n        \"_temp\" + std::to_string(std::round(T)) + \"_samples\" + std::to_string(no_samples) \\\n        + \"_rods\" + std::to_string(N) + \"_sys_length\" + std::to_string(std::round(L)) + \"_rodlength\" + std::to_string(rod_length);\n\n    //check if file_name doesn't already exist inside folder_name \n    if (fs::exists(\".\\\\\" + folder_name + \"\\\\\" + file_name)) {\n        std::cout << \"File name already exists - please rename. exiting\";\n        //return 0;\n    }\n    else {\n        std::ofstream rho_bar_csvfile;\n        rho_bar_csvfile.open(\".\\\\\" + folder_name + \"\\\\D_\" + file_name + \".csv\"); //Create csv file in which density data is stored\n\n        std::ofstream j_bar_csvfile;\n        j_bar_csvfile.open(\".\\\\\" + folder_name + \"\\\\J_\" + file_name + \".csv\"); //Create csv file in which current data is stored\n\n        int no_time_samples = std::round(max_time / sampling_time) + 1;\n\n        std::vector<std::vector<double>> rho_t_series(no_time_samples);\n        std::vector<std::vector<double>> j_t_series(no_time_samples);\n\n        std::list<double> bins_list = init_bins(std::round(L / cell_length));\n\n        //for loop to run evolve_and_hist every 'sampling_time' up until 'max_time'\n        for (int i = 0; i < static_cast<int> (max_time / sampling_time) + 1; i++) {\n\n            std::cout << \"\\nSampling at time t = \" << std::to_string(sampling_time * i) << \" is in progress...\";\n            auto iter_start = std::chrono::high_resolution_clock::now();\n\n            //call evolve_and_hist\n\n            std::vector<std::vector<double>> averaged_rho_j_dists = evolve_and_hist(sampling_time * i, init_vel_matrix, init_posn_matrix, bins_list);\n            rho_t_series[i] = averaged_rho_j_dists[0];\n            j_t_series[i] = averaged_rho_j_dists[1];\n\n            auto iter_stop = std::chrono::high_resolution_clock::now();\n            auto iter_duration = std::chrono::duration_cast<std::chrono::milliseconds>(iter_stop - iter_start);\n            auto time_elapsed = std::chrono::duration_cast<std::chrono::seconds>(iter_stop - start);\n            std::cout << \" and has completed after \" << iter_duration.count() << \"ms. Total runtime is \" << time_elapsed.count() << \"s.\";\n        }\n        //exporting to csv\n\n        if (rho_bar_csvfile.is_open()) {\n\n            for (unsigned i = 0; i < rho_t_series.size(); i++) {\n                for (unsigned j = 0; j < rho_t_series[i].size() - 1; j++) {\n                    rho_bar_csvfile << rho_t_series[i][j] << \",\";\n                }\n                rho_bar_csvfile << rho_t_series[i].back() << \"\\n\"; //last entry on row doesn't require a comma\n            }\n        }\n        else {\n            std::cout << \"\\nError opening file.\";\n        }\n\n        if (j_bar_csvfile.is_open()) {\n\n            for (unsigned i = 0; i < j_t_series.size(); i++) {\n                for (unsigned j = 0; j < j_t_series[i].size() - 1; j++) {\n                    j_bar_csvfile << j_t_series[i][j] << \",\";\n                }\n                j_bar_csvfile << j_t_series[i].back() << \"\\n\"; //last entry on row doesn't require a comma\n            }\n        }\n        else {\n            std::cout << \"\\nError opening file.\";\n        }\n\n    }\n}", "meta": {"hexsha": "8616543b6bdb21973fc5126bb8ea418995b5192a", "size": 17239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "IraPelidae/Classical-Nonlinear-Response", "max_stars_repo_head_hexsha": "e18c3c287100ddd5a5d389ca6e895a8100df1cfc", "max_stars_repo_licenses": ["MIT"], "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": "IraPelidae/Classical-Nonlinear-Response", "max_issues_repo_head_hexsha": "e18c3c287100ddd5a5d389ca6e895a8100df1cfc", "max_issues_repo_licenses": ["MIT"], "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": "IraPelidae/Classical-Nonlinear-Response", "max_forks_repo_head_hexsha": "e18c3c287100ddd5a5d389ca6e895a8100df1cfc", "max_forks_repo_licenses": ["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.9706666667, "max_line_length": 195, "alphanum_fraction": 0.6161610302, "num_tokens": 4284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5098998984818339}}
{"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_MAP_CONVEXIFIED_MAP_HPP_\n#define MIQP_COMMON_MAP_CONVEXIFIED_MAP_HPP_\n\n#include <vector>\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/polygon/voronoi.hpp>\n#include \"bark/commons/base_type.hpp\"\n#include \"bark/commons/util/util.hpp\"\n#include \"bark/geometry/polygon.hpp\"\n#include \"bark/models/dynamic/dynamic_model.hpp\"\n#include \"common/geometry/geometry.hpp\"\n\nnamespace miqp {\nnamespace common {\nnamespace map {\n\ntypedef boost::polygon::voronoi_diagram<double> boost_voronoi_diagram;\ntypedef boost::polygon::point_data<double> point_data_t;\n\nclass ConvexifiedMap : public bark::commons::BaseType {\n public:\n  explicit ConvexifiedMap(const bark::commons::ParamsPtr& params,\n                          const bark::geometry::Polygon& map_polygon,\n                          const double buffer_radius,\n                          const double max_simplify_dist,\n                          const double buffer_reference,\n                          const double buffer_for_merging_tolerance);\n\n  virtual ~ConvexifiedMap() {}\n\n  /**\n   * @brief shrinks and converts nonconvex polygon to multiple convex ones\n   *\n   * @return true ... if conversion was successfull\n   */\n  bool Convert();\n\n  /**\n   * @brief Get the Map Non Convex Polygon object\n   *\n   * @return bark::geometry::Polygon\n   */\n  bark::geometry::Polygon GetMapNonConvexPolygon() const {\n    return nonconvex_input_polygon_;\n  }\n\n  /**\n   * @brief Get the Map Convex Polygons object\n   *\n   * @return miqp::common::geometry::PolygonMap\n   */\n  miqp::common::geometry::PolygonMap GetMapConvexPolygons() const {\n    return convex_output_polygon_map_;\n  }\n\n  /**\n   * @brief returns convex polygons of street that intersect with reference.\n   * reference is bufferd to make sure that enough environment polygons are\n   * available for a maneuver.\n   *\n   * @param referenceTraj ... reference trajectory\n   * @return PolygonMap ... convex polygons\n   */\n  miqp::common::geometry::PolygonMap GetIntersectingConvexPolygons(\n      const bark::models::dynamic::Trajectory& referenceTraj) const;\n\n  /**\n   * @brief checks if input polygon is valid\n   *\n   * @return true if polygon is valid\n   * @return false if polygon is not valid\n   */\n  bool HasValidPolygon() { return nonconvex_input_polygon_.Valid(); }\n\n  /**\n   * @brief Set the Map Polygon object\n   *\n   * @param map_polygon\n   */\n  void SetMapPolygon(const bark::geometry::Polygon& map_polygon);\n\n private:\n  /**\n   * @brief function checks if decomposition of initial polygon was successfull\n   * or not\n   *\n   * @param shrinked_input_polygon ... shrinked nonconvex input polygon\n   * @param convex_output_polygons ... shrinked decomposed output polygons\n   * @return true ... if decomposition successfull\n   */\n  bool CheckDecomposition(const bark::geometry::Polygon& shrinked_input_polygon,\n                          const miqp::common::geometry::BoostMultiPolygon&\n                              convex_output_polygons) const;\n\n  /**\n   * @brief converts cells of voronoi diagram to multipolygon\n   *\n   * @param vd ... voronoi diagram\n   * @return BoostMultiPolygon ... cells from voronoi diagram\n   */\n  miqp::common::geometry::BoostMultiPolygon VoronoiCellsToBoostMultiPolygon(\n      const boost::polygon::voronoi_diagram<double>& vd);\n\n  /**\n   * @brief construct voronoi diagram from input polygon\n   *\n   * @param input_polygon ... input geometry as polygon\n   * @param input_points ... input geometry as points vector\n   * @param vd ... voronoi diagram\n   */\n  void ConstructVoronoiDiagram(\n      const bark::geometry::Polygon& buffered_simplified_input_polygon,\n      std::vector<point_data_t>& input_points, boost_voronoi_diagram& vd) const;\n\n  /**\n   * @brief converts possibly nonconvex cells to triangles\n   *\n   * @param input_points ... points vector of input geometry\n   * @param cells_inside_map ... possibly nonconvex cells\n   * @param boost_polygon_convex_out ... triangles\n   */\n  void TriangulateCells(\n      const std::vector<point_data_t>& input_points,\n      miqp::common::geometry::BoostMultiPolygon& cells_inside_map,\n      miqp::common::geometry::BoostMultiPolygon& boost_polygon_convex_out);\n\n  /**\n   * @brief create polygon from three points\n   *\n   * @param p1 ... input point\n   * @param p2 ... input point\n   * @param p3 ... input point\n   * @param triangle ... output polygon\n   * @return true ... if polygon could be constructed\n   */\n  bool CreateTriangle(const miqp::common::geometry::PointXY& p1,\n                      const miqp::common::geometry::PointXY& p2,\n                      const miqp::common::geometry::PointXY& p3,\n                      miqp::common::geometry::BoostPolygon& triangle) const;\n\n  /**\n   * @brief simplifying and buffering input polygon\n   *\n   * @return Polygon ... simplified and buffered polygon\n   */\n  bark::geometry::Polygon PreprocessPolygon() const;\n\n  /**\n   * @brief thakes the convex_output_polygon_map_ member and simplifies the\n   * linestrings in the polygons again to avoid too short segments. Afterwards\n   * inflate the polygons again to avoid holes in between.\n   */\n  void PostprocessPolygonVector();\n\n  bark::geometry::Polygon nonconvex_input_polygon_;\n  miqp::common::geometry::PolygonMap convex_output_polygon_map_;\n  const double envelope_offset_;\n  bool decomposed_;\n  double merging_tolerance_;\n  const double buffer_radius_;\n  const double buffer_reference_;\n  const double buffer_for_merging_tolerance_;\n  const double max_simplify_dist_;\n  const double postprocess_simplification_dist_;\n  const int num_merging_runs_;\n};\n\n}  // namespace map\n}  // namespace common\n}  // namespace miqp\n\n#endif  // MIQP_COMMON_MAP_CONVEXIFIED_MAP_HPP_\n", "meta": {"hexsha": "e8aa776d507868ae2e561de467e6ecd392c42464", "size": 5885, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "common/map/convexified_map.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/map/convexified_map.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/map/convexified_map.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": 32.5138121547, "max_line_length": 80, "alphanum_fraction": 0.7004248088, "num_tokens": 1378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.509899884276039}}
{"text": "//==================================================================================================\n/*\n  Copyright 2017 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//! [fnma]\n#include <boost/simd/arithmetic.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/enumerate.hpp>\n#include <iostream>\n\nnamespace bs = boost::simd;\nusing pack_ft = bs::pack <float, 4>;\n\nint main()\n{\n  pack_ft pf = bs::enumerate<pack_ft>(-1, 2);\n  pack_ft qf = bs::enumerate<pack_ft>( 0, 3);\n  pack_ft rf = bs::enumerate<pack_ft>( 2, 5);\n\n  std::cout\n    << \"---- simd\" << '\\n'\n    << \" <- pf =                   \" << pf << '\\n'\n    << \" <- qf =                   \" << qf << '\\n'\n    << \" <- rf =                   \" << rf << '\\n'\n    << \" -> bs::fnma(pf, qf, rf) = \" << bs::fnma(pf, qf, rf) << '\\n';\n\n  float xf = 3.0f, yf = -3.0f, zf = 2.0f;\n\n  std::cout\n    << \"---- scalar\" << '\\n'\n    << \" <- xf =                   \" << xf << '\\n'\n    << \" <- yf =                   \" << yf << '\\n'\n    << \" <- yf =                   \" << zf << '\\n'\n    << \" -> bs::fnma(xf, yf, rf) = \" << bs::fnma(xf, yf, zf) << '\\n';\n  return 0;\n}\n//! [fnma]\n", "meta": {"hexsha": "3eefdbce33493f24e3d8f9c31819c370146a0854", "size": 1339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/arithmetic/fnma.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/doc/arithmetic/fnma.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/doc/arithmetic/fnma.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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.880952381, "max_line_length": 100, "alphanum_fraction": 0.3853622106, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604181, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5098998832283691}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/qr.hpp\n *\n * \\brief The QR matrix decomposition.\n *\n * Given a matrix \\f$A\\f$, its QR-decomposition is a matrix decomposition of the\n * form:\n * \\f[\n *   A=QR\n * \\f]\n * where \\f$R\\f$ is an m-by-n upper trapezoidal (or, when \\f$m \\ge n\\f$,\n * triangular) matrix and \\f$Q\\f$ is an m-by-m orthogonal (or unitary) matrix,\n * that is one satisfying:\n * \\f[\n *   Q^{T}Q=I,\n * \\f]\n * where \\f$Q^{T}\\f$ is the transpose of \\f$Q\\f$ and \\f$I\\f$ is the identity\n * matrix.\n *\n * For the special case of \\f$m \\ge n\\f$, the factorization can be rewritten as:\n * \\f[\n *  A=\\begin{pmatrix}\n *     Q_1 & Q_2\n *     \\end{pmatrix}\n *     \\begin{pmatrix}\n *     R_1 \\\\\n *     R_2 \\\\\n *     \\end{pmatrix}\n *   =\\begin{pmatrix}\n *     Q_1 & Q_2\n *     \\end{pmatrix}\n *     \\begin{pmatrix}\n *     R_1 \\\\\n *     0 \\\\\n *     \\end{pmatrix}\n *   = Q_1 R_1\n * \\f] \n * where \\f$Q_1\\f$ is an m-by-n matrix, \\f$Q_2\\f$ is an m-by-(m-n) matrix,\n * \\f$R_1\\f$ is an n-by-n lower triangular matrix, and \\f$R_2\\f$ is an\n * (m-n)-by-n zero matrix.\n *\n * This matrix decomposition can be used to solve linear systems of equations,\n * especially the ones involved in the linear least squares problem.\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_QR_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_QR_HPP\n\n\n#include <algorithm>\n#include <boost/mpl/and.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/numeric/bindings/lapack/computational/geqrf.hpp>\n#include <boost/numeric/bindings/lapack/computational/orgqr.hpp>\n#include <boost/numeric/bindings/lapack/computational/ormqr.hpp>\n#include <boost/numeric/bindings/lapack/computational/ungqr.hpp>\n#include <boost/numeric/bindings/ublas.hpp>\n#include <boost/numeric/bindings/tag.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/fwd.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/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_same.hpp>\n#include <complex>\n#include <cstddef>\n#include <stdint.h>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\nnamespace detail {\n\n/**\n * \\brief Common operations for QR decomposition.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\nstruct qr_decomposition_impl_common;\n\n/**\n * \\brief Type-oriented operations for QR decomposition.\n *\n * \\tparam IsComplex Logical parameter telling if the we are doing either a real\n *  or a complex QR decomposition.\n *\n * This class makes distinction between the real and the complex case.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <bool IsComplex>\nstruct qr_decomposition_impl;\n\n\nstruct qr_decomposition_impl_common\n{\n    /// Performan QR decomposition of the given input matrix \\a A\n    /// (row-major case).\n    template <typename AMatrixT, typename TauVectorT>\n        static void decompose(AMatrixT& A, TauVectorT& tau, row_major_tag)\n    {\n        matrix<typename matrix_traits<AMatrixT>::value_type, column_major> tmp_A(A);\n\n        decompose(tmp_A, tau, column_major_tag());\n\n        A = tmp_A;\n    }\n\n\n    /// Performan QR decomposition of the given input matrix \\a A\n    /// (column-major case).\n    template <typename AMatrixT, typename TauVectorT>\n        static void decompose(AMatrixT& A, TauVectorT& tau, column_major_tag)\n    {\n        typedef typename matrix_traits<AMatrixT>::size_type size_type;\n\n        size_type m = num_rows(A);\n        size_type n = num_columns(A);\n        size_type k = ::std::min(m,n);\n\n        if (size(tau) != k)\n        {\n            tau.resize(k, false);\n        }\n\n        ::boost::numeric::bindings::lapack::geqrf(A, tau);\n    }\n\n\n    /**\n     * \\brief Extract the R matrix from a previously computing QR decomposition\n     * (row-major case).\n     *\n     * Let QR be an m-by-n matrix, then the R matrix is built by taking the\n     * min(m,n)-by-n upper trapezoidal (triangular, if m >= n) elements of QR.\n     */\n    template <typename QRMatrixT, typename RMatrixT>\n        static void extract_R(QRMatrixT const& QR, RMatrixT& R, bool full, row_major_tag)\n    {\n        matrix<typename matrix_traits<QRMatrixT>::value_type, column_major> tmp_QR(QR);\n        matrix<typename matrix_traits<RMatrixT>::value_type, column_major> tmp_R(R);\n\n        extract_R(tmp_QR, tmp_R, full, column_major_tag());\n\n        R = tmp_R;\n    }\n\n\n    /**\n     * \\brief Extract the R matrix from a previously computing QR decomposition\n     * (row-major case).\n     *\n     * Let QR be an m-by-n matrix, then the R matrix is built by taking the\n     * min(m,n)-by-n upper trapezoidal (triangular, if m >= n) elements of QR.\n     */\n    template <typename QRMatrixT, typename RMatrixT>\n        static void extract_R(QRMatrixT const& QR, RMatrixT& R, bool full, column_major_tag)\n    {\n        typedef typename matrix_traits<RMatrixT>::size_type size_type;\n        typedef typename matrix_traits<RMatrixT>::value_type value_type;\n\n        size_type m = num_rows(QR);\n        size_type n = num_columns(QR);\n        size_type nr = full ? m : ::std::min(m,n);\n\n        if (num_rows(R) != nr && num_columns(R) != n)\n        {\n            R.resize(nr, n, false);\n        }\n\n        if (m >= n)\n        {\n            // The upper triangle of the submatrix QR(1:n,1:n) contains the\n            // min(m,n)-by-n upper triangular matrix R.\n            for (size_type row = 0; row < n; ++row)\n            {\n                for (size_type col = 0; col < n; ++col)\n                {\n                    if (col >= row)\n                    {\n                        R(row,col) = QR(row,col);\n                    }\n                    else\n                    {\n                        R(row,col) = value_type/*zero*/();\n                    }\n                }\n            }\n\n            // Set to zero the last m-n rows\n            if (full)\n            {\n                subrange(R, n, m, 0, n) = scalar_matrix<value_type>(m-n, n, value_type/*zero*/());\n            }\n        }\n        else\n        {\n            // The elements on and upper the n-th subdiagonal contain the\n            // m-by-n upper trapezoidal matrix R.\n            for (size_type row = 0; row < m; ++row)\n            {\n                for (size_type col = 0; col < n; ++col)\n                {\n                    if (col >= row)\n                    {\n                        R(row,col) = QR(row,col);\n                    }\n                    else\n                    {\n                        R(row,col) = value_type/*zero*/();\n                    }\n                }\n            }\n        }\n    }\n\n\n    /**\n     * \\brief Multiply the given \\a C matrix by the \\c Q matrix obtained from\n     *  the QR decomposition.\n     *\n     * \\tparam QRMatrixT The type of the \\a QR matrix.\n     * \\tparam TAUMatrixT The type of the \\a tau vector.\n     * \\tparam CMatrixT The type of the \\a C matrix.\n     *\n     * \\param QR The matrix obtained by the QR decomposition such that the i-th\n     *  column contains the vector which defines the elementary reflector\n     *  \\f$H(i)\\f$, for \\f$i = 1,2,\\ldots,k\\f$.\n     * \\param tau The vector obtained by the QR decomposition containing the\n     *  scalar factors of the elementary reflectors \\f$H(i)\\f$, for\n     *  \\f$i=1,2,\\ldots,k\\f$.\n     * \\param left_Q A boolean value indicating which side of the product the\n     *  matrix \\c Q will occupy. A \\c true value indicates that \\c Q is the left\n     *  operand, while a \\c false value indicates that \\c Q is the right\n     *  operand.\n     * \\param trans_Q A boolean value indicating if the matrix \\c Q is to be\n     *  transposed. A \\c true value indicates that \\c Q is to be transposed,\n     *  while a \\c false value indicates that \\c Q is to be taken as-is.\n     * \\param orientation The matrix orientation fixed to row-major.\n     *\n     * Let \\c Q be the matrix obtained from the QR decomposition represented\n     * by the \\a QR matrix and the \\a tau vector parameters. \n     * Then this function computes the following matrix product:\n     * \\f{equation*}{\n     *   \\begin{cases}\n     *   Q C, & \\text{\\texttt{left\\_Q} = \\emph{true} and \\texttt{trans\\_Q} = \\emph{false}}, \\\\\n     *   Q^T C, & \\text{\\texttt{left\\_Q} = \\emph{true} and \\texttt{trans\\_Q} = \\emph{true}}, \\\\\n     *   C Q, & \\text{\\texttt{left\\_Q} = \\emph{false} and \\texttt{trans\\_Q} = \\emph{false}}, \\\\\n     *   C Q^T, & \\text{\\texttt{left\\_Q} = \\emph{false} and \\texttt{trans\\_Q} = \\emph{true}}.\n     *  \\end{cases}\n     * \\f}\n     */\n    template <typename QRMatrixT, typename TAUVectorT, typename CMatrixT>\n        static void prod(QRMatrixT& QR, TAUVectorT const& tau, CMatrixT& C, bool left_Q, bool trans_Q, row_major_tag)\n    {\n        //NOTE: QR cannot be const since LAPACK::ORMQR modified it, restoring\n        //      it at the end of the function.\n\n        matrix<typename matrix_traits<QRMatrixT>::value_type, column_major> tmp_QR(QR);\n        matrix<typename matrix_traits<CMatrixT>::value_type, column_major> tmp_C(C);\n\n        prod(tmp_QR, tau, tmp_C, left_Q, trans_Q, column_major_tag());\n\n        C = tmp_C;\n    }\n\n\n    /**\n     * \\brief Multiply the given \\a C matrix by the \\c Q matrix obtained from\n     *  the QR decomposition.\n     *\n     * \\tparam QRMatrixT The type of the \\a QR matrix.\n     * \\tparam TAUMatrixT The type of the \\a tau vector.\n     * \\tparam CMatrixT The type of the \\a C matrix.\n     *\n     * \\param QR The matrix obtained by the QR decomposition such that the i-th\n     *  column contains the vector which defines the elementary reflector\n     *  \\f$H(i)\\f$, for \\f$i = 1,2,\\ldots,k\\f$.\n     * \\param tau The vector obtained by the QR decomposition containing the\n     *  scalar factors of the elementary reflectors \\f$H(i)\\f$, for\n     *  \\f$i=1,2,\\ldots,k\\f$.\n     * \\param left_Q A boolean value indicating which side of the product the\n     *  matrix \\c Q will occupy. A \\c true value indicates that \\c Q is the left\n     *  operand, while a \\c false value indicates that \\c Q is the right\n     *  operand.\n     * \\param trans_Q A boolean value indicating if the matrix \\c Q is to be\n     *  transposed. A \\c true value indicates that \\c Q is to be transposed,\n     *  while a \\c false value indicates that \\c Q is to be taken as-is.\n     * \\param orientation The matrix orientation fixed to column-major.\n     *\n     * Let \\c Q be the matrix obtained from the QR decomposition represented\n     * by the \\a QR matrix and the \\a tau vector parameters. \n     * Then this function computes the following matrix product:\n     * \\f{equation*}{\n     *   \\begin{cases}\n     *   Q C, & \\text{\\texttt{left\\_Q} = \\emph{true} and \\texttt{trans\\_Q} = \\emph{false}}, \\\\\n     *   Q^T C, & \\text{\\texttt{left\\_Q} = \\emph{true} and \\texttt{trans\\_Q} = \\emph{true}}, \\\\\n     *   C Q, & \\text{\\texttt{left\\_Q} = \\emph{false} and \\texttt{trans\\_Q} = \\emph{false}}, \\\\\n     *   C Q^T, & \\text{\\texttt{left\\_Q} = \\emph{false} and \\texttt{trans\\_Q} = \\emph{true}}.\n     *  \\end{cases}\n     * \\f}\n     */\n    template <typename QRMatrixT, typename TAUVectorT, typename CMatrixT>\n        static void prod(QRMatrixT& QR, TAUVectorT const& tau, CMatrixT& C, bool left_Q, bool trans_Q, column_major_tag /*orientation*/)\n    {\n        //NOTE: QR cannot be const since LAPACK::ORMQR modified it, restoring\n        //      it at the end of the function.\n\n//      typedef typename matrix_traits<QRMatrixT>::value_type value_type;\n//      typedef typename matrix_traits<QRMatrixT>::size_type size_type;\n//      typedef typename type_traits<value_type>::real_type real_type;\n//\n//      const ::fortran_int_t m = num_rows(C);\n//      const ::fortran_int_t n = num_columns(C);\n//      const ::fortran_int_t k = size(tau);\n//      const ::fortran_int_t lda = num_rows(QR);\n//      const ::fortran_int_t ldc = m;\n//      real_type* work;\n//      real_type opt_work_size;\n//      ::fortran_int_t lwork;\n//      ::std::ptrdiff_t info;\n\n        if (left_Q)\n        {\n            if (trans_Q)\n            {\n//              //FIXME: actually (2010-08-13) bindinds::lapack::ormqr has problems\n//              info = ::boost::numeric::bindings::lapack::detail::ormqr(\n//                  ::boost::numeric::bindings::tag::left(),\n//                  ::boost::numeric::bindings::tag::transpose(),\n//                  m,\n//                  n,\n//                  k,\n//                  QR.data().begin(),\n//                  lda,\n//                  tau.data().begin(),\n//                  C.data().begin(),\n//                  ldc,\n//                  &opt_work_size,\n//                  -1\n//              );\n//              lwork = static_cast< ::fortran_int_t >(opt_work_size);\n//              work = new real_type[lwork];\n//              info = ::boost::numeric::bindings::lapack::detail::ormqr(\n//                  ::boost::numeric::bindings::tag::left(),\n//                  ::boost::numeric::bindings::tag::transpose(),\n//                  m,\n//                  n,\n//                  k,\n//                  QR.data().begin(),\n//                  lda,\n//                  tau.data().begin(),\n//                  C.data().begin(),\n//                  ldc,\n//                  work,\n//                  lwork\n//              );\n//              delete[] work;\n                ::boost::numeric::bindings::lapack::ormqr(\n                    ::boost::numeric::bindings::tag::left(),\n                    ::boost::numeric::bindings::trans(QR),\n                    tau,\n                    C\n                );\n            }\n            else\n            {\n//              //FIXME: actually (2010-08-13) bindinds::lapack::ormqr has problems\n//              info = ::boost::numeric::bindings::lapack::detail::ormqr(\n//                  ::boost::numeric::bindings::tag::left(),\n//                  ::boost::numeric::bindings::tag::no_transpose(),\n//                  m,\n//                  n,\n//                  k,\n//                  QR.data().begin(),\n//                  lda,\n//                  tau.data().begin(),\n//                  C.data().begin(),\n//                  ldc,\n//                  &opt_work_size,\n//                  -1\n//              );\n//              lwork = static_cast< ::fortran_int_t >(opt_work_size);\n//              work = new real_type[lwork];\n//              info = ::boost::numeric::bindings::lapack::detail::ormqr(\n//                  ::boost::numeric::bindings::tag::left(),\n//                  ::boost::numeric::bindings::tag::no_transpose(),\n//                  m,\n//                  n,\n//                  k,\n//                  QR.data().begin(),\n//                  lda,\n//                  tau.data().begin(),\n//                  C.data().begin(),\n//                  ldc,\n//                  work,\n//                  lwork\n//              );\n//              delete[] work;\n                ::boost::numeric::bindings::lapack::ormqr(\n                    ::boost::numeric::bindings::tag::left(),\n                    QR,\n                    tau,\n                    C\n                );\n            }\n        }\n        else\n        {\n            if (trans_Q)\n            {\n//              //FIXME: actually (2010-08-13) bindinds::lapack::ormqr has problems\n//              info = ::boost::numeric::bindings::lapack::detail::ormqr(\n//                  ::boost::numeric::bindings::tag::right(),\n//                  ::boost::numeric::bindings::tag::transpose(),\n//                  m,\n//                  n,\n//                  k,\n//                  QR.data().begin(),\n//                  lda,\n//                  tau.data().begin(),\n//                  C.data().begin(),\n//                  ldc,\n//                  &opt_work_size,\n//                  -1\n//              );\n//              lwork = static_cast< ::fortran_int_t >(opt_work_size);\n//              work = new real_type[lwork];\n//              info = ::boost::numeric::bindings::lapack::detail::ormqr(\n//                  ::boost::numeric::bindings::tag::right(),\n//                  ::boost::numeric::bindings::tag::transpose(),\n//                  m,\n//                  n,\n//                  k,\n//                  QR.data().begin(),\n//                  lda,\n//                  tau.data().begin(),\n//                  C.data().begin(),\n//                  ldc,\n//                  work,\n//                  lwork\n//              );\n//              delete[] work;\n                ::boost::numeric::bindings::lapack::ormqr(\n                    ::boost::numeric::bindings::tag::right(),\n                    ::boost::numeric::bindings::trans(QR),\n                    tau,\n                    C\n                );\n            }\n            else\n            {\n//              //FIXME: actually (2010-08-13) bindinds::lapack::ormqr has problems\n//              info = ::boost::numeric::bindings::lapack::detail::ormqr(\n//                  ::boost::numeric::bindings::tag::right(),\n//                  ::boost::numeric::bindings::tag::no_transpose(),\n//                  m,\n//                  n,\n//                  k,\n//                  QR.data().begin(),\n//                  lda,\n//                  tau.data().begin(),\n//                  C.data().begin(),\n//                  ldc,\n//                  &opt_work_size,\n//                  -1\n//              );\n//              lwork = static_cast< ::fortran_int_t >(opt_work_size);\n//              work = new real_type[lwork];\n//              info = ::boost::numeric::bindings::lapack::detail::ormqr(\n//                  ::boost::numeric::bindings::tag::right(),\n//                  ::boost::numeric::bindings::tag::no_transpose(),\n//                  m,\n//                  n,\n//                  k,\n//                  QR.data().begin(),\n//                  lda,\n//                  tau.data().begin(),\n//                  C.data().begin(),\n//                  ldc,\n//                  work,\n//                  lwork\n//              );\n//              delete[] work;\n                ::boost::numeric::bindings::lapack::ormqr(\n                    ::boost::numeric::bindings::tag::right(),\n                    QR,\n                    tau,\n                    C\n                );\n            }\n        }\n    }\n};\n\n\ntemplate <>\nstruct qr_decomposition_impl<false>: public qr_decomposition_impl_common\n{\n    /// Extract the Q matrix from a previously computing QR decomposition\n    /// (row-major case).\n    template <typename QRMatrixT, typename TauVectorT, typename QMatrixT>\n        static void extract_Q(QRMatrixT const& QR, TauVectorT const& tau, QMatrixT& Q, bool full, row_major_tag)\n    {\n        matrix<typename matrix_traits<QRMatrixT>::value_type, column_major> tmp_QR(QR);\n        matrix<typename matrix_traits<QMatrixT>::value_type, column_major> tmp_Q(Q);\n\n        extract_Q(tmp_QR, tau, tmp_Q, full, column_major_tag());\n\n        Q = tmp_Q;\n    }\n\n\n    /// Extract the Q matrix from a previously computing QR decomposition\n    /// (column-major case).\n    template <typename QRMatrixT, typename TauVectorT, typename QMatrixT>\n        static void extract_Q(QRMatrixT const& QR, TauVectorT& tau, QMatrixT& Q, bool full, column_major_tag)\n    {\n        typedef typename matrix_traits<QMatrixT>::size_type size_type;\n        typedef typename matrix_traits<QMatrixT>::value_type value_type;\n\n        size_type m = num_rows(QR);\n        size_type n = num_columns(QR);\n        size_type nc = full ? m : ::std::min(m,n);\n\n        if (num_rows(Q) != m || num_columns(Q) != nc)\n        {\n            Q.resize(m, nc, false);\n        }\n\n        if (m > n)\n        {\n            if (full)\n            {\n                subrange(Q, 0, m, 0, n) = QR;\n                subrange(Q, 0, m, n, m) = scalar_matrix<value_type>(m, m-n, value_type/*zero*/());\n            }\n            else\n            {\n                Q = QR;\n            }\n        }\n        else if (m < n)\n        {\n            Q = subrange(QR, 0, m, 0, nc);\n        }\n        else\n        {\n            Q = QR;\n        }\n\n       ::boost::numeric::bindings::lapack::orgqr(Q, tau);\n    }\n};\n\n\ntemplate <>\nstruct qr_decomposition_impl<true>: public qr_decomposition_impl_common\n{\n    /// Extract the Q matrix from a previously computing QR decomposition\n    /// (row-major case).\n    template <typename QRMatrixT, typename TauVectorT, typename QMatrixT>\n        static void extract_Q(QRMatrixT const& QR, TauVectorT const& tau, QMatrixT& Q, bool full, row_major_tag)\n    {\n        matrix<typename matrix_traits<QRMatrixT>::value_type, column_major> tmp_QR(QR);\n        matrix<typename matrix_traits<QMatrixT>::value_type, column_major> tmp_Q(Q);\n\n        extract_Q(tmp_QR, tau, tmp_Q, full, column_major_tag());\n\n        Q = tmp_Q;\n    }\n\n\n    /// Extract the Q matrix from a previously computing QR decomposition\n    /// (column-major case).\n    template <typename QRMatrixT, typename TauVectorT, typename QMatrixT>\n        static void extract_Q(QRMatrixT const& QR, TauVectorT const& tau, QMatrixT& Q, bool full, column_major_tag)\n    {\n        typedef typename matrix_traits<QMatrixT>::size_type size_type;\n        typedef typename matrix_traits<QMatrixT>::value_type value_type;\n\n        size_type m = num_rows(QR);\n        size_type n = num_columns(QR);\n        size_type nc = full ? m : ::std::min(m,n);\n\n        if (num_rows(Q) != m || num_columns(Q) != nc)\n        {\n            Q.resize(m, nc, false);\n        }\n\n        if (m > n)\n        {\n            if (full)\n            {\n                subrange(Q, 0, m, 0, n) = QR;\n                subrange(Q, 0, m, n, m) = scalar_matrix<value_type>(m, m-n, value_type/*zero*/());\n            }\n            else\n            {\n                Q = QR;\n            }\n        }\n        else if (m < n)\n        {\n            Q = subrange(QR, 0, m, 0, nc);\n        }\n        else\n        {\n            Q = QR;\n        }\n\n        ::boost::numeric::bindings::lapack::ungqr(Q, tau);\n    }\n};\n\n\n/// Free function performing the QR decomposition of the given matrix expression \\a A.\ntemplate<typename MatrixExprT, typename QMatrixT, typename RMatrixT, typename OrientationT>\nvoid qr_decompose_impl(matrix_expression<MatrixExprT> const& A, QMatrixT& Q, RMatrixT& R, bool full, OrientationT orientation)\n{\n    typedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\n    matrix<value_type, typename layout_type<MatrixExprT>::type> tmp_QR(A);\n    vector<value_type> tmp_tau;\n\n    qr_decomposition_impl<\n            ::boost::is_complex<value_type>::value\n        >::template decompose(tmp_QR, tmp_tau, orientation);\n\n\n    qr_decomposition_impl<\n            ::boost::is_complex<value_type>::value\n        >::template extract_Q(tmp_QR, tmp_tau, Q, full, orientation);\n\n\n    qr_decomposition_impl<\n            ::boost::is_complex<value_type>::value\n        >::template extract_R(tmp_QR, R, full, orientation);\n}\n\n} // Namespace detail\n\n\n/**\n * \\brief QR decomposition.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename ValueT>\nclass qr_decomposition\n{\n    public: typedef ValueT value_type;\n    private: typedef matrix<value_type, column_major> work_matrix_type;\n    public: typedef work_matrix_type QR_matrix_type;\n    public: typedef work_matrix_type Q_matrix_type;\n    public: typedef work_matrix_type R_matrix_type;\n    private: typedef vector<value_type> tau_vector_type;\n\n\n    public: qr_decomposition()\n    {\n        // empty\n    }\n\n\n    public: template <typename MatrixExprT>\n        qr_decomposition(matrix_expression<MatrixExprT> const& A)\n        : QR_(A)\n    {\n        decompose();\n    }\n\n\n    public: template <typename MatrixExprT>\n        void decompose(matrix_expression<MatrixExprT> const& A)\n    {\n        QR_ = A;\n\n        decompose();\n    }\n\n\n    public: Q_matrix_type Q(bool full = true) const\n    {\n        Q_matrix_type tmp_Q;\n\n        detail::qr_decomposition_impl<\n                ::boost::is_complex<value_type>::value\n            >::template extract_Q(QR_, tau_, tmp_Q, full, column_major_tag());\n\n        return tmp_Q;\n    }\n\n\n    public: R_matrix_type R(bool full = true) const\n    {\n        R_matrix_type tmp_R;\n\n        detail::qr_decomposition_impl<\n                ::boost::is_complex<value_type>::value\n            >::template extract_R(QR_, tmp_R, full, column_major_tag());\n\n        return tmp_R;\n    }\n\n\n    /// Perform the product \\f$Q C\\f$ and store the result in \\a C.\n    public: template <typename CMatrixT>\n        void lprod_inplace(CMatrixT& C) const\n    {\n        typedef typename matrix_traits<CMatrixT>::orientation_category orientation_category;\n\n        lprod_inplace(C, orientation_category());\n    }\n\n\n    /// Perform the product \\f$C Q\\f$ and store the result in \\a C.\n    public: template <typename CMatrixT>\n        void rprod_inplace(CMatrixT& C) const\n    {\n        typedef typename matrix_traits<CMatrixT>::orientation_category orientation_category;\n\n        rprod_inplace(C, orientation_category());\n    }\n\n\n    /// Perform the product \\f$Q^T C\\f$ and store the result in \\a C.\n    public: template <typename CMatrixT>\n        void tlprod_inplace(CMatrixT& C) const\n    {\n        typedef typename matrix_traits<CMatrixT>::orientation_category orientation_category;\n\n        tlprod_inplace(C, orientation_category());\n    }\n\n\n    /// Perform the product \\f$C Q^T\\f$ and store the result in \\a C.\n    public: template <typename CMatrixT>\n        void trprod_inplace(CMatrixT& C) const\n    {\n        typedef typename matrix_traits<CMatrixT>::orientation_category orientation_category;\n\n        trprod_inplace(C, orientation_category());\n    }\n\n\n    /// Perform the product \\f$Q C\\f$ and return the result.\n    public: template <typename CMatrixExprT>\n        typename matrix_temporary_traits<CMatrixExprT>::type lprod(matrix_expression<CMatrixExprT> const& C) const\n    {\n        typename matrix_temporary_traits<CMatrixExprT>::type tmp_C(C);\n\n        lprod_inplace(tmp_C);\n\n        return tmp_C;\n    }\n\n\n    /// Perform the product \\f$C Q\\f$ and return the result.\n    public: template <typename CMatrixExprT>\n        typename matrix_temporary_traits<CMatrixExprT>::type rprod(matrix_expression<CMatrixExprT> const& C) const\n    {\n        typename matrix_temporary_traits<CMatrixExprT>::type tmp_C(C);\n\n        rprod_inplace(tmp_C);\n\n        return tmp_C;\n    }\n\n\n    /// Perform the product \\f$Q^T C\\f$ and return the result.\n    public: template <typename CMatrixExprT>\n        typename matrix_temporary_traits<CMatrixExprT>::type tlprod(matrix_expression<CMatrixExprT> const& C) const\n    {\n        typename matrix_temporary_traits<CMatrixExprT>::type tmp_C(C);\n\n        tlprod_inplace(tmp_C);\n\n        return tmp_C;\n    }\n\n\n    /// Perform the product \\f$C Q^T\\f$ and return the result.\n    public: template <typename CMatrixExprT>\n        typename matrix_temporary_traits<CMatrixExprT>::type trprod(matrix_expression<CMatrixExprT> const& C) const\n    {\n        typename matrix_temporary_traits<CMatrixExprT>::type tmp_C(C);\n\n        trprod_inplace(tmp_C);\n\n        return tmp_C;\n    }\n\n\n    private: void decompose()\n    {\n        detail::qr_decomposition_impl<\n                ::boost::is_complex<value_type>::value\n            >::template decompose(QR_, tau_, column_major_tag());\n    }\n\n\n    /// Perform the product \\f$Q C\\f$ and store the result in \\a C (column-major\n    /// case).\n    private: template <typename CMatrixT>\n        void lprod_inplace(CMatrixT& C, column_major_tag) const\n    {\n        detail::qr_decomposition_impl<\n                ::boost::is_complex<value_type>::value\n            >::template prod(QR_, tau_, C, true, false, column_major_tag());\n    }\n\n\n    /// Perform the product \\f$Q C\\f$ and store the result in \\a C (row-major\n    /// case).\n    private: template <typename CMatrixT>\n        void lprod_inplace(CMatrixT& C, row_major_tag) const\n    {\n        work_matrix_type tmp_C(C);\n\n        detail::qr_decomposition_impl<\n                ::boost::is_complex<value_type>::value\n            >::template prod(QR_, tau_, tmp_C, true, false, column_major_tag());\n\n        C = tmp_C;\n    }\n\n\n    /// Perform the product \\f$C Q\\f$ and store the result in \\a C (column-major\n    /// case).\n    private: template <typename CMatrixT>\n        void rprod_inplace(CMatrixT& C, column_major_tag) const\n    {\n        detail::qr_decomposition_impl<\n            ::boost::is_complex<value_type>::value\n        >::template prod(QR_, tau_, C, false, false, column_major_tag());\n    }\n\n\n    /// Perform the product \\f$C Q\\f$ and store the result in \\a C (row-major\n    /// case).\n    private: template <typename CMatrixT>\n        void rprod_inplace(CMatrixT& C, row_major_tag) const\n    {\n        work_matrix_type tmp_C(C);\n\n        detail::qr_decomposition_impl<\n                ::boost::is_complex<value_type>::value\n            >::template prod(QR_, tau_, tmp_C, false, false, column_major_tag());\n\n        C = tmp_C;\n    }\n\n\n    /// Perform the product \\f$Q^T C\\f$ and store the result in \\a C\n    /// (column-major case).\n    private: template <typename CMatrixT>\n        void tlprod_inplace(CMatrixT& C, column_major_tag) const\n    {\n        detail::qr_decomposition_impl<\n            ::boost::is_complex<value_type>::value\n        >::template prod(QR_, tau_, C, true, true, column_major_tag());\n    }\n\n\n    /// Perform the product \\f$Q^T C\\f$ and store the result in \\a C\n    /// (row-major case).\n    private: template <typename CMatrixT>\n        void tlprod_inplace(CMatrixT& C, row_major_tag) const\n    {\n        work_matrix_type tmp_C(C);\n\n        detail::qr_decomposition_impl<\n                ::boost::is_complex<value_type>::value\n            >::template prod(QR_, tau_, tmp_C, true, true, column_major_tag());\n\n        C = tmp_C;\n    }\n\n\n    /// Perform the product \\f$C Q^T\\f$ and store the result in \\a C\n    /// (column-major case).\n    private: template <typename CMatrixT>\n        void trprod_inplace(CMatrixT& C, column_major_tag) const\n    {\n        detail::qr_decomposition_impl<\n                ::boost::is_complex<value_type>::value\n            >::template prod(QR_, tau_, C, false, true, column_major_tag());\n    }\n\n\n    /// Perform the product \\f$C Q^T\\f$ and store the result in \\a C\n    /// (row-major case).\n    private: template <typename CMatrixT>\n        void trprod_inplace(CMatrixT& C, row_major_tag) const\n    {\n        work_matrix_type tmp_C(C);\n\n        detail::qr_decomposition_impl<\n                ::boost::is_complex<value_type>::value\n            >::template prod(QR_, tau_, tmp_C, false, true, column_major_tag());\n\n        C = tmp_C;\n    }\n\n\n    // NOTE: the 'mutable' keyword is needed in order to make 'const' the\n    //       '?prod' methods ('lprod', 'tlprod', 'rprod', 'trprod').\n    //       Indeed, these methods call the respective '?prod_inplace' methods\n    //       which, in turns, call the LAPACK::ORMQR function which temporarily\n    //       changes the QR matrix (and restores it before returning).\n    private: mutable QR_matrix_type QR_;\n    private: tau_vector_type tau_;\n};\n\n\n/// Free function performing the QR decomposition of the given matrix expression \\a A.\ntemplate<typename MatrixExprT, typename OutMatrix1T, typename OutMatrix2T>\nBOOST_UBLAS_INLINE\nvoid qr_decompose(matrix_expression<MatrixExprT> const& A, OutMatrix1T& Q, OutMatrix2T& R, bool full = true)\n{\n    typedef typename matrix_traits<MatrixExprT>::orientation_category orientation_category1;\n    typedef typename matrix_traits<OutMatrix1T>::orientation_category orientation_category2;\n    typedef typename matrix_traits<OutMatrix2T>::orientation_category orientation_category3;\n\n    // precondition: same orientation category\n    BOOST_MPL_ASSERT(\n        (::boost::mpl::and_<\n            ::boost::is_same<orientation_category1,orientation_category2>,\n            ::boost::is_same<orientation_category1,orientation_category3>\n        >)\n    );\n\n    detail::qr_decompose_impl(A, Q, R, full, orientation_category1());\n}\n\n\n/// Free function performing the QR decomposition of the given matrix expression \\a A.\ntemplate<typename MatrixExprT>\nBOOST_UBLAS_INLINE\nqr_decomposition<typename matrix_traits<MatrixExprT>::value_type> qr_decompose(matrix_expression<MatrixExprT> const& A)\n{\n    typedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\n    return qr_decomposition<value_type>(A);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_QR_HPP\n", "meta": {"hexsha": "403bddc8011281763276b9f0bf67c89cecac0e8a", "size": 32950, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/qr.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/qr.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/qr.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": 33.7948717949, "max_line_length": 136, "alphanum_fraction": 0.5741122914, "num_tokens": 8230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.509899883228369}}
{"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 TestRotation3DX\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <cmath>\n#include \"minimath/rotation3d.hpp\"\n#include \"minimath/point3d.hpp\"\n\n#include \"Defines.h\"\n#include \"TestRotation3DUtils.h\"\n\nusing namespace minimath;\n\nBOOST_AUTO_TEST_SUITE(TestRotation3DX)\n\nBOOST_AUTO_TEST_CASE(testInstantiation)\n{\n  rotation3dx<double> rot1, rot2;\n}\n\nBOOST_AUTO_TEST_CASE(testDefaultEquality)\n{\n  BOOST_CHECK(rotation3dx<double>() == rotation3dx<double>());\n}\n\nBOOST_AUTO_TEST_CASE(testCopyConstruction)\n{\n  rotation3dx<double> rot1;\n  rotation3dx<double> rot2(rot1);\n  BOOST_CHECK(rot1 == rot2);\n}\n\nBOOST_AUTO_TEST_CASE(testAssignment)\n{\n  rotation3dx<double> rot1, rot2;\n  rot2 = rot1;\n  BOOST_CHECK(rot1 == rot2);\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint0)\n{\n  rotation3dx<double> rotx4(0);\n  pointxyzd pTest = rotx4*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rotx4*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = rotx4*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint45)\n{\n  rotation3dx<double> rotx6(PI/4.); // 45 degree rotation about X\n  pointxyzd pTest = rotx6*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rotx6*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., cos45, cos45));\n\n  pTest = rotx6*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., -cos45, cos45));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint90)\n{\n  rotation3dx<double> rotx4(PI/2.); // 90 degree rotation about X\n  pointxyzd pTest = rotx4*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rotx4*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n\n  pTest = rotx4*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., -1., 0.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint180)\n{\n  rotation3dx<double> rotx5(PI); // 180 degree rotation about X\n\n  pointxyzd pTest = rotx5*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rotx5*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., -1., 0.));\n\n  pTest = rotx5*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., -1.));\n}\n\nBOOST_AUTO_TEST_CASE(testInverse)\n{\n  BOOST_CHECK(TestUtils::testInverse<rotation3dx<double> >());\n}\n\nBOOST_AUTO_TEST_CASE(testInvert)\n{\n  BOOST_CHECK(TestUtils::testInvert<rotation3dx<double> >());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3e372f3d11b5408463ba0759549a6f29af5e98f0", "size": 2519, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestRotation3DX.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/TestRotation3DX.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/TestRotation3DX.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": 22.9, "max_line_length": 66, "alphanum_fraction": 0.7161572052, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604179, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5098998832283689}}
{"text": "#ifndef INCLUDE_MIMKL_MODELS_UMKL_KNN_HPP_\n#define INCLUDE_MIMKL_MODELS_UMKL_KNN_HPP_\n\n#include <dlib/optimization.h>\n#include <mimkl/definitions.hpp>\n#include <mimkl/linear_algebra.hpp>\n#include <mimkl/models/model.hpp>\n#include <queue>\n#include <spdlog/spdlog.h>\n#include <thread>\n#include <type_traits>\n#include <utility>\n\nusing dlib::mat;\nusing mimkl::definitions::Index;\nusing mimkl::kernels_handler::KernelsHandler;\nusing mimkl::utilities::sort_indices_decending;\n\nnamespace mimkl\n{\nnamespace models\n{\n\nstatic std::shared_ptr<spdlog::logger> logger_umkl_knn =\nspdlog::stdout_color_mt(\"UMKLKNN\");\n\ntemplate <typename Scalar, typename Kernel>\nvoid find_and_update_neighbours_using_kernels(\nKernelsHandler<Scalar, Kernel> &kernels_handler,\nconst Index number_of_kernels,\nconst Index number_of_support_vectors,\nconst Index k,\nMATRIX(Scalar) & W)\n{\n// for each kernel, get k-NN and add it to upper triangular part of W\n// TODO: consider allocation of W_local outside of the loop\n// currently not in place given SegFault in development\n#pragma omp parallel for shared(kernels_handler, W)\n    for (Index m = 0; m < number_of_kernels; ++m)\n    {\n        // set W_local copy\n        MATRIX(Scalar)\n        W_local = MATRIX(Scalar)::Zero(number_of_support_vectors,\n                                       number_of_support_vectors);\n        // TODO: think about how to avoid this copy\n        MATRIX(Scalar) kernel = kernels_handler[m];\n        for (Index c = 0; c < number_of_support_vectors; ++c)\n        {\n            // no self loops admitted in W we have to treat the handle the case\n            // i==c see original implementation\n            // https://github.com/cran/mixKernel/blob/master/R/combine.kernels.R\n            // starting by filling a neighbors heap\n            std::priority_queue<std::pair<Scalar, Index>,\n                                std::vector<std::pair<Scalar, Index>>,\n                                std::greater<std::pair<Scalar, Index>>>\n            nn_heap;\n            Index i = 0;\n            // initialize initial k elements\n            while (nn_heap.size() < k)\n            {\n                if (i != c)\n                {\n                    nn_heap.push(std::pair<Scalar, Index>(kernel(i, c), i));\n                }\n                // keep track of the index\n                ++i;\n            }\n            // compute k nearest neighbors for c\n            for (; i < number_of_support_vectors; ++i)\n            {\n                if (i != c && nn_heap.top().first < kernel(i, c))\n                {\n                    nn_heap.pop();\n                    nn_heap.push(std::pair<Scalar, Index>(kernel(i, c), i));\n                }\n            }\n            // consuming the neighbors heap and populating the knn graph\n            while (!nn_heap.empty())\n            {\n                Index neighbor = nn_heap.top().second;\n                neighbor > c ? W_local(c, neighbor) = 1 :\n                               W_local(neighbor, c) = 1;\n                nn_heap.pop();\n            }\n        }\n// update W with W_local\n#pragma omp critical\n        {\n            W.template triangularView<Eigen::Upper>() += W_local;\n        }\n    }\n}\n\n//! Unsupervised Multiple Kernel Learning (2017), notion of original topology\n//! from k-NN of kernels\n/*! (sparse version from paper)\n *\n */\ntemplate <typename Scalar, typename Kernel>\nclass UMKLKNN : public Model<Scalar, Kernel>\n{\n\n    private:\n    // inheritance of templatized base members\n    using Model<Scalar, Kernel>::_kernels_handler;\n    using Model<Scalar, Kernel>::_trained;\n    using Model<Scalar, Kernel>::_precompute;\n    using Model<Scalar, Kernel>::_trace_normalization;\n    using Model<Scalar, Kernel>::_number_of_support_vectors;\n    using Model<Scalar, Kernel>::_number_of_kernels;\n\n    std::shared_ptr<spdlog::logger> _logger = spdlog::get(\"UMKLKNN\");\n\n    typedef MATRIX(Scalar) Matrix;\n    typedef COLUMN(Scalar) Column;\n    typedef Eigen::Map<const Column> MapColumn;\n    typedef dlib::matrix<Scalar, 0, 1, dlib::default_memory_manager, dlib::column_major_layout>\n    DlibColumn;\n\n    Index _k = 5; // for k nearest neighbors (k-NN)\n    double _epsilon = 0.0001;\n    Index _maxiter_qp = 100000;\n\n    Matrix _W;\n    Matrix _S;\n\n    DlibColumn _beta_dlib;\n    Column _beta;\n\n    void compute_w_matrix();\n    void compute_s_matrix();\n    void optimize_beta();\n    void fit();\n\n    public:\n    UMKLKNN(const std::vector<Kernel> & = std::vector<Kernel>(),\n            const bool precompute = true,\n            const bool trace_normalization = true,\n            const Index k = 5,\n            const double epsilon = 0.0001,\n            const Index maxiter_qp = 100000);\n    UMKLKNN(const std::vector<Matrix> & = std::vector<Matrix>(),\n            const bool precompute = true,\n            const bool trace_normalization = true,\n            const Index k = 5,\n            const double epsilon = 0.0001,\n            const Index maxiter_qp = 100000);\n\n    void fit(const Matrix &);\n    void fit(const std::vector<Matrix> &);\n    Matrix predict(const Matrix &);\n    Matrix predict(const std::vector<Matrix> &);\n\n    Index get_k() const;\n    double get_epsilon() const;\n    Index get_maxiter_qp() const;\n    Column get_beta() const;\n    Matrix get_optimal_kernel();\n\n    void set_k(const Index);\n    void set_epsilon(const double);\n    void set_maxiter_qp(const Index);\n    void set_parameters(const Index,\n                        const double epsilon = 0.0001,\n                        const Index maxiter_qp = 100000);\n    void set_beta(const Column &);\n};\n\ntemplate <typename Scalar, typename Kernel>\nUMKLKNN<Scalar, Kernel>::UMKLKNN(const std::vector<Kernel> &kernel_functions,\n                                 const bool precompute,\n                                 const bool trace_normalization,\n                                 const Index k,\n                                 const double epsilon,\n                                 const Index maxiter_qp)\n: Model<Scalar, Kernel>(kernel_functions, precompute, trace_normalization)\n{\n    _beta = Column::Constant(_number_of_kernels, (double)1. / _number_of_kernels);\n    _beta_dlib = mat(_beta);\n    set_parameters(k, epsilon, maxiter_qp);\n}\n\ntemplate <typename Scalar, typename Kernel>\nUMKLKNN<Scalar, Kernel>::UMKLKNN(const std::vector<Matrix> &kernel_matrices,\n                                 const bool precompute,\n                                 const bool trace_normalization,\n                                 const Index k,\n                                 const double epsilon,\n                                 const Index maxiter_qp)\n: Model<Scalar, Kernel>(kernel_matrices, precompute, trace_normalization)\n{\n    _beta = Column::Constant(_number_of_kernels, (double)1. / _number_of_kernels);\n    _beta_dlib = mat(_beta);\n    set_parameters(k, epsilon, maxiter_qp);\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid UMKLKNN<Scalar, Kernel>::fit()\n{\n    _number_of_support_vectors = _kernels_handler.get_lhs_size();\n    _number_of_kernels = _kernels_handler.get_number_of_kernels();\n    compute_w_matrix();\n    compute_s_matrix();\n    optimize_beta();\n    _trained = true;\n    _logger->debug(\"all done\");\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid UMKLKNN<Scalar, Kernel>::fit(const std::vector<Matrix> &kernel_matrices)\n{\n    _kernels_handler.set_matrices(kernel_matrices, true);\n    fit();\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid UMKLKNN<Scalar, Kernel>::fit(const Matrix &X)\n{\n    _kernels_handler.set_lhs(X);\n    fit();\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename UMKLKNN<Scalar, Kernel>::Matrix\nUMKLKNN<Scalar, Kernel>::predict(const Matrix &X)\n{\n    if (!_trained)\n        throw std::logic_error(\"The model should be trained first (after \"\n                               \"instantiation or change in parameters)\");\n    _kernels_handler.set_rhs(X);\n    return get_optimal_kernel();\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename UMKLKNN<Scalar, Kernel>::Matrix\nUMKLKNN<Scalar, Kernel>::predict(const std::vector<Matrix> &kernel_matrices)\n{\n    if (!_trained)\n        throw std::logic_error(\"The model should be trained first (after \"\n                               \"instantiation or change in parameters)\");\n    if (kernel_matrices[0].rows() != _number_of_support_vectors)\n        throw std::length_error(\"Similarities must be provided for all support \"\n                                \"vectors; matrices have wrong number of rows.\");\n    if (kernel_matrices.size() != _number_of_kernels)\n        throw std::length_error(\n        \"Same number of kernels as on training is required\");\n    _kernels_handler.set_matrices(kernel_matrices);\n    return get_optimal_kernel();\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid UMKLKNN<Scalar, Kernel>::compute_w_matrix()\n{\n    // ensure a clean status\n    _W.resize(_number_of_support_vectors, _number_of_support_vectors);\n    _W.setZero();\n\n    // find k-nearest neighbors filling upper part of _W\n    find_and_update_neighbours_using_kernels(_kernels_handler, _number_of_kernels,\n                                             _number_of_support_vectors, _k, _W);\n\n    // symmetrize _W\n    _W.template triangularView<Eigen::Lower>() = _W.transpose();\n    // check if we handled properly the self loops\n    if (_W.diagonal().sum() > 0.0)\n    {\n        _logger->critical(\"W diagonal contains non zero elements\");\n    }\n    _logger->trace(\"Matrix W:\\n{}\", _W);\n    _logger->debug(\"W done\");\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid UMKLKNN<Scalar, Kernel>::compute_s_matrix()\n{\n    _S.resize(_number_of_kernels, _number_of_kernels);\n    _S.setZero();\n    Matrix K_st(_number_of_support_vectors, _number_of_support_vectors);\n    for (Index s = 0; s < _number_of_kernels; ++s)\n    {\n        for (Index t = s; t < _number_of_kernels; ++t)\n        { // compute\n            K_st = _kernels_handler[s] * _kernels_handler[t];\n            _S(s, t) =\n            ((_W * K_st.diagonal()).sum() - _W.cwiseProduct(K_st).sum());\n            if (t > s)\n            {\n                _S(t, s) = _S(s, t);\n            }\n        }\n    }\n    _logger->trace(\"Matrix S:\\n{}\", _S);\n    _logger->debug(\"S done\");\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid UMKLKNN<Scalar, Kernel>::optimize_beta()\n{\n    _beta = Column::Constant(_number_of_kernels, (double)1. / _number_of_kernels);\n    _beta_dlib = mat(_beta);\n    Index iterations = dlib::solve_qp_using_smo(\n    mat(_S), dlib::zeros_matrix<Scalar>(0, _number_of_kernels), _beta_dlib,\n    _epsilon, _maxiter_qp); // 2*mat(_S) would be correct, but not needed\n    if (iterations > _maxiter_qp)\n    {\n        _logger->critical(\"the qp-solver did not finish in {} iterations\",\n                          _maxiter_qp);\n    }\n    _logger->debug(\"{} qp iterations\", iterations);\n    _beta = mimkl::linear_algebra::dlib_to_eigen(_beta_dlib);\n}\n\ntemplate <typename Scalar, typename Kernel>\nIndex UMKLKNN<Scalar, Kernel>::get_k() const\n{\n    return _k;\n}\n\ntemplate <typename Scalar, typename Kernel>\ndouble UMKLKNN<Scalar, Kernel>::get_epsilon() const\n{\n    return _epsilon;\n}\n\ntemplate <typename Scalar, typename Kernel>\nIndex UMKLKNN<Scalar, Kernel>::get_maxiter_qp() const\n{\n    return _maxiter_qp;\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename UMKLKNN<Scalar, Kernel>::Column UMKLKNN<Scalar, Kernel>::get_beta() const\n{\n    _logger->debug(\n    \"The model has not been fit. Maybe the parameters were changed?\");\n    return _beta;\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename UMKLKNN<Scalar, Kernel>::Matrix\nUMKLKNN<Scalar, Kernel>::get_optimal_kernel()\n{\n    return _kernels_handler.sum(_beta);\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid UMKLKNN<Scalar, Kernel>::set_k(const Index k)\n{\n    _k = k;\n    _trained = false;\n    _logger->debug(\"changing parameters requires refitting before prediction\");\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid UMKLKNN<Scalar, Kernel>::set_epsilon(const double epsilon)\n{\n    _epsilon = epsilon;\n    _trained = false;\n    _logger->debug(\"changing parameters requires refitting before prediction\");\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid UMKLKNN<Scalar, Kernel>::set_maxiter_qp(const Index maxiter_qp)\n{\n    _maxiter_qp = maxiter_qp;\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid UMKLKNN<Scalar, Kernel>::set_parameters(const Index k,\n                                             const double epsilon,\n                                             const Index maxiter_qp)\n{\n    _k = k;\n    _epsilon = epsilon;\n    _maxiter_qp = maxiter_qp;\n    _trained = false;\n    _logger->debug(\"changing parameters requires refitting before prediction\");\n    _logger->debug(\"k: {}\", _k);\n    _logger->debug(\"epsilon: {}\", _epsilon);\n    _logger->debug(\"maxiter_qp: {}\", _maxiter_qp);\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid UMKLKNN<Scalar, Kernel>::set_beta(const Column &beta)\n{\n    if (beta.rows() != _number_of_kernels)\n        throw std::length_error(\n        \"passed beta does not have one weight for each kernel\");\n    _beta = beta;\n    _beta_dlib = mat(_beta);\n}\n\n} // namespace models\n} // namespace mimkl\n\n#endif /* INCLUDE_MIMKL_MODELS_UMKL_KNN_HPP_ */\n", "meta": {"hexsha": "43e2191486fd3c3f20de1f503ee723c21d20403a", "size": 13125, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mimkl/models/umkl_knn.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/models/umkl_knn.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/models/umkl_knn.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.0604534005, "max_line_length": 95, "alphanum_fraction": 0.6358857143, "num_tokens": 3088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604181, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5098998781438807}}
{"text": "/* sse_expf_test.cc\n   Jeremy Barnes, 18 January 2009\n   Copyright (c) 2009 Jeremy Barnes.  All rights reserved.\n   This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n   Test for the SSE2 expf function.\n*/\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#include \"mldb/arch/sse2_exp.h\"\n#include \"mldb/arch/sse2_log.h\"\n#include \"mldb/arch/demangle.h\"\n#include \"mldb/utils/vector_utils.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <vector>\n#include <set>\n#include <iostream>\n#include <cmath>\n#include \"mldb/arch/tick_counter.h\"\n#include \"mldb/utils/string_functions.h\"\n#include <sys/time.h>\n#include \"mldb/utils/floating_point.h\"\n\nusing namespace std;\nusing namespace MLDB;\nusing namespace MLDB::SIMD;\n\nusing boost::unit_test::test_suite;\n\nfloat extract_scalar(v4sf i)\n{\n    float vals[4];\n    *((v4sf *)vals) = i;\n    if (std::isnan(vals[0])) {\n        BOOST_CHECK(std::isnan(vals[1]));\n        BOOST_CHECK(std::isnan(vals[2]));\n        BOOST_CHECK(std::isnan(vals[3]));\n    }\n    else {\n        BOOST_CHECK_EQUAL(vals[0], vals[1]);\n        BOOST_CHECK_EQUAL(vals[0], vals[2]);\n        BOOST_CHECK_EQUAL(vals[0], vals[3]);\n    }\n    return vals[0];\n}\n\nint extract_scalar(v4si i)\n{\n    int vals[4];\n    *((v4si *)vals) = i;\n    BOOST_CHECK_EQUAL(vals[0], vals[1]);\n    BOOST_CHECK_EQUAL(vals[0], vals[2]);\n    BOOST_CHECK_EQUAL(vals[0], vals[3]);\n    return vals[0];\n}\n\ndouble extract_scalar(v2df i)\n{\n    double vals[2];\n    *((v2df *)vals) = i;\n    if (std::isnan(vals[0])) {\n        BOOST_CHECK(std::isnan(vals[1]));\n    }\n    else {\n        BOOST_CHECK_EQUAL(vals[0], vals[1]);\n    }\n    return vals[0];\n}\n\nBOOST_AUTO_TEST_CASE( ldexp_test )\n{\n    BOOST_CHECK_EQUAL(ldexp(1.0, 0), extract_scalar(ldexp(vec_splat(1.0), vec_splat(0))));\n    BOOST_CHECK_EQUAL(ldexp(1.0, 1), extract_scalar(ldexp(vec_splat(1.0), vec_splat(1))));\n}\n\nvoid test_functions(double val)\n{\n    cerr << format(\"%5.2f  %5.2f  %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\\n\",\n                   val,\n                   floor(val + 0.5),\n                   round(val),\n                   trunc(val),\n                   floor(val),\n                   ceil(val),\n                   rint(val),\n                   double(int(val)));\n}\n\nBOOST_AUTO_TEST_CASE( value_test )\n{\n    cerr << \"  val   func  round trunc floor  ceil  rint  conv\" << endl;\n    test_functions(0.0);\n    cerr << endl;\n    test_functions(0.1);\n    test_functions(0.49);\n    test_functions(0.50);\n    test_functions(0.51);\n    test_functions(0.99);\n    test_functions(1.00);\n    test_functions(1.01);\n    test_functions(1.50);\n    test_functions(1.51);\n    cerr << endl;\n    test_functions(-0.1);\n    test_functions(-0.49);\n    test_functions(-0.50);\n    test_functions(-0.51);\n    test_functions(-0.99);\n    test_functions(-1.00);\n    test_functions(-1.01);\n    test_functions(-1.50);\n    test_functions(-1.51);\n    cerr << endl;\n}\n\n#define test_floor_value(input) \\\n{ \\\n    float in2 = float(input); \\\n    float output1 = floorf(in2); \\\n    float output2 = extract_scalar(sse2_floor(vec_splat(in2))); \\\n    if (std::isnan(output1)) \\\n        BOOST_CHECK(std::isnan(output2));            \\\n    else BOOST_CHECK_EQUAL(floorf(float(input)), output2);      \\\n} \\\n{ \\\n    double in2 = double(input); \\\n    double output1 = floorf(in2); \\\n    double output2 = extract_scalar(sse2_floor(vec_splat(in2))); \\\n    if (std::isnan(output1)) \\\n        BOOST_CHECK(std::isnan(output2));            \\\n    else BOOST_CHECK_EQUAL(floorf(double(input)), output2);      \\\n}\n\nstatic const float NaN = std::numeric_limits<float>::quiet_NaN();\n\nBOOST_AUTO_TEST_CASE( floor_test )\n{\n    test_floor_value(0.0);\n    test_floor_value(-0.0);\n    test_floor_value(1.0);\n    test_floor_value(2.0);\n    test_floor_value(2.5);\n    test_floor_value(-0.49);\n    test_floor_value(-0.5);\n    test_floor_value(-0.51);\n    test_floor_value(-0.99);\n    test_floor_value(-1.0);\n    test_floor_value(-1.01);\n    test_floor_value(2.5);\n    test_floor_value(NaN);\n    test_floor_value(-NaN);\n    test_floor_value(INFINITY);\n    test_floor_value(-INFINITY);\n}\n\n#define test_trunc_value(input) \\\n{ \\\n    float in2 = float(input); \\\n    float output1 = truncf(in2); \\\n    float output2 = extract_scalar(sse2_trunc(vec_splat(in2))); \\\n    if (std::isnan(output1)) \\\n        BOOST_CHECK(std::isnan(output2));            \\\n    else BOOST_CHECK_EQUAL(truncf(float(input)), output2);      \\\n}\n\nBOOST_AUTO_TEST_CASE( trunc_test )\n{\n    test_trunc_value(0.0);\n    test_trunc_value(-0.0);\n    test_trunc_value(1.0);\n    test_trunc_value(2.0);\n    test_trunc_value(2.5);\n    test_trunc_value(-0.49);\n    test_trunc_value(-0.5);\n    test_trunc_value(-0.51);\n    test_trunc_value(-0.99);\n    test_trunc_value(-1.0);\n    test_trunc_value(-1.01);\n    test_trunc_value(2.5);\n    test_trunc_value(NaN);\n    test_trunc_value(-NaN);\n    test_trunc_value(INFINITY);\n    test_trunc_value(-INFINITY);\n}\n\n#define test_expf_value(input)                                          \\\n    {                                                                   \\\n        float in2 = float(input);                                       \\\n        float output1 = expf(in2);                                      \\\n        float output2 = extract_scalar(sse2_expf(vec_splat(in2)));      \\\n        if (std::isnan(output1)) {                                           \\\n            if (!std::isnan(output2)) {                                      \\\n                cerr << \"input = \" << in2 << \" output1 = \" << output1 << \" output2 = \" << output2 \\\n                 << endl;                                               \\\n            }                                                           \\\n            BOOST_CHECK(std::isnan(output2));                                \\\n        }                                                               \\\n        else if (output1 != output2) {                                  \\\n            int i1 = reinterpret_as_int(output1);                       \\\n            int i2 = reinterpret_as_int(output2);                       \\\n            if (abs(i1 - i2) > 1) {                                     \\\n                cerr << format(\"%12.8f: %14.9f != %14.9f: %08x != %08x (%4d ulps)\\n\", \\\n                               in2, output1, output2, i1, i2, (i1 - i2)); \\\n                BOOST_CHECK_EQUAL(expf(float(input)), output2);         \\\n            }                                                           \\\n        }                                                               \\\n    }\n\nBOOST_AUTO_TEST_CASE( test_expf )\n{\n    test_expf_value(0.0);\n    test_expf_value(1.0);\n    test_expf_value(2.0);\n    test_expf_value(3.0);\n    test_expf_value(-0.0);\n    test_expf_value(-1.0);\n    test_expf_value(-2.0);\n    test_expf_value(-3.0);\n\n    test_expf_value(-10.0);\n    test_expf_value(-20.0);\n    test_expf_value(-30.0);\n    test_expf_value(-50.0);\n    test_expf_value(-100.0);\n    test_expf_value(-1000.0);\n\n    test_expf_value(10.0);\n    test_expf_value(20.0);\n    test_expf_value(30.0);\n    test_expf_value(50.0);\n    test_expf_value(100.0);\n    test_expf_value(1000.0);\n\n    test_expf_value(NaN);\n    test_expf_value(-NaN);\n    test_expf_value(INFINITY);\n    test_expf_value(-INFINITY);\n\n    int nvals = 65536;\n    for (int i = 0;  i < nvals;  ++i) {\n        float f = 105.0 * (2 * i - nvals) / (1.0 * nvals);\n        test_expf_value(f);\n    }\n}\n\n#define test_exp_value(input)                                          \\\n    {                                                                   \\\n        double in2 = double(input);                                       \\\n        double output1 = exp(in2);                                      \\\n        double output2 = extract_scalar(sse2_exp(vec_splat(in2)));      \\\n        if (std::isnan(output1)) {                                           \\\n            if (!std::isnan(output2)) {                                      \\\n                cerr << \"input = \" << in2 << \" output1 = \" << output1 << \" output2 = \" << output2 \\\n                 << endl;                                               \\\n            }                                                           \\\n            BOOST_CHECK(std::isnan(output2));                                \\\n        }                                                               \\\n        else if (output1 != output2) {                                  \\\n            int i1 = reinterpret_as_int(output1);                       \\\n            int i2 = reinterpret_as_int(output2);                       \\\n            /* Allow 2 ulps as there are a very few values that */      \\\n            /* have this error */                                       \\\n            if (abs(i1 - i2) > 2) {                                     \\\n                cerr << format(\"%12.8f: %14.9f != %14.9f: %08x != %08x (%4d ulps)\\n\", \\\n                               in2, output1, output2, i1, i2, (i1 - i2)); \\\n                BOOST_CHECK_EQUAL(exp(double(input)), output2);         \\\n            }                                                           \\\n        }                                                               \\\n    }\n\nBOOST_AUTO_TEST_CASE( test_exp )\n{\n    test_exp_value(0.0);\n    test_exp_value(1.0);\n    test_exp_value(2.0);\n    test_exp_value(3.0);\n    test_exp_value(-0.0);\n    test_exp_value(-1.0);\n    test_exp_value(-2.0);\n    test_exp_value(-3.0);\n\n    test_exp_value(-10.0);\n    test_exp_value(-20.0);\n    test_exp_value(-30.0);\n    test_exp_value(-50.0);\n    test_exp_value(-100.0);\n    test_exp_value(-1000.0);\n\n    test_exp_value(10.0);\n    test_exp_value(20.0);\n    test_exp_value(30.0);\n    test_exp_value(50.0);\n    test_exp_value(100.0);\n    test_exp_value(1000.0);\n\n    test_exp_value(NaN);\n    test_exp_value(-NaN);\n    test_exp_value(INFINITY);\n    test_exp_value(-INFINITY);\n\n    // Test over the whole range\n    int nvals = 65536;\n    for (int i = 0;  i < nvals;  ++i) {\n        double f = 1000.0 * (2 * i - nvals) / (1.0 * nvals);\n        test_exp_value(f);\n    }\n\n    // Test more closely over (-10, 10)\n    for (int i = 0;  i < nvals;  ++i) {\n        double f = 10.0 * (2 * i - nvals) / (1.0 * nvals);\n        test_exp_value(f);\n    }\n}\n\ninline double pow2(int input)\n{\n    return pow(2.0, double(input));\n}\n\n#define test_pow2_value(input)                                         \\\n    {                                                                   \\\n        double output1 = pow2(input);                                      \\\n        double output2 = extract_scalar(sse2_pow2(vec_splat(input)));      \\\n        if (std::isnan(output1)) {                                           \\\n            if (!std::isnan(output2)) {                                      \\\n                cerr << \"input = \" << input << \" output1 = \" << output1 << \" output2 = \" << output2 \\\n                 << endl;                                               \\\n            }                                                           \\\n            BOOST_CHECK(std::isnan(output2));                                \\\n        }                                                               \\\n        else if (output1 != output2) {                                  \\\n            int i1 = reinterpret_as_int(output1);                       \\\n            int i2 = reinterpret_as_int(output2);                       \\\n            if (abs(i1 - i2) > 1) {                                     \\\n                cerr << format(\"%12.8f: %14.9f != %14.9f: %08x != %08x (%4d ulps)\\n\", \\\n                               (double)input, output1, output2, i1, i2, (i1 - i2)); \\\n                BOOST_CHECK_EQUAL(pow2(double(input)), output2);         \\\n            }                                                           \\\n        }                                                               \\\n    }\n\nBOOST_AUTO_TEST_CASE( test_pow2 )\n{\n    test_pow2_value(0);\n    test_pow2_value(1);\n    test_pow2_value(2);\n    test_pow2_value(3);\n    test_pow2_value(-0);\n    test_pow2_value(-1);\n    test_pow2_value(-2);\n    test_pow2_value(-3);\n\n    test_pow2_value(-10);\n    test_pow2_value(-20);\n    test_pow2_value(-30);\n    test_pow2_value(-50);\n    test_pow2_value(-100);\n    test_pow2_value(-1000);\n\n    test_pow2_value(10);\n    test_pow2_value(20);\n    test_pow2_value(30);\n    test_pow2_value(50);\n    test_pow2_value(100);\n    test_pow2_value(1000);\n\n#if 0\n    test_pow2_value(NaN);\n    test_pow2_value(-NaN);\n    test_pow2_value(INFINITY);\n    test_pow2_value(-INFINITY);\n\n    // Test over the whole range\n    int nvals = 65536;\n    for (int i = 0;  i < nvals;  ++i) {\n        double f = 1000.0 * (2 * i - nvals) / (1.0 * nvals);\n        test_pow2_value(f);\n    }\n\n    // Test more closely over (-10, 10)\n    for (int i = 0;  i < nvals;  ++i) {\n        double f = 10.0 * (2 * i - nvals) / (1.0 * nvals);\n        test_pow2_value(f);\n    }\n#endif\n}\n\nnamespace {\n\n// TODO: use clock_gettime\ndouble elapsed_since(const timeval & tv_start)\n{\n    struct timeval tv_end;\n    gettimeofday(&tv_end, 0);\n\n    double start_sec = tv_start.tv_sec + (tv_start.tv_usec / 1000000.0);\n    double end_sec = tv_end.tv_sec + (tv_end.tv_usec / 1000000.0);\n\n    return (end_sec - start_sec);\n}\n\n} // file scope\n\nvoid warm_up_cpu(double seconds = 1.0)\n{\n    // One second of activity to push up the CPU speed if boost is enabled\n    struct timeval tv;\n    gettimeofday(&tv, 0);\n    \n    while (elapsed_since(tv) < seconds);\n    \n}\n\ndouble builtin_expf_array(float * vals, int nvals)\n{\n    sched_yield();\n    size_t before = ticks();\n\n    for (unsigned i = 0;  i < nvals;  ++i)\n        vals[i] = expf(vals[i]);\n\n    size_t after = ticks();\n\n    return (after - before);\n}\n\ndouble builtin_exp_array(float * vals, int nvals)\n{\n    sched_yield();\n    size_t before = ticks();\n\n    for (unsigned i = 0;  i < nvals;  ++i)\n        vals[i] = exp(double(vals[i]));\n\n    size_t after = ticks();\n\n    return (after - before);\n}\n\ndouble sse2_expf_array(float * vals, int nvals)\n{\n    sched_yield();\n    size_t before = ticks();\n\n    int nvecs = nvals / 4;\n    v4sf * vvals = (v4sf *)vals;\n    \n    for (unsigned i = 0;  i < nvecs;  ++i)\n        vvals[i] = sse2_expf(vvals[i]);\n\n    size_t after = ticks();\n    return (after - before);\n}\n\ndouble sse2_exp_array(float * vals_, int nvals)\n{\n    double vals[nvals];\n    std::copy(vals_, vals_ + nvals, vals);\n\n    sched_yield();\n    size_t before = ticks();\n\n    int nvecs = nvals / 2;\n    v2df * vvals = (v2df *)vals;\n    \n    for (unsigned i = 0;  i < nvecs;  ++i)\n        vvals[i] = sse2_exp(vvals[i]);\n\n    size_t after = ticks();\n    return (after - before);\n}\n\ntypedef double (*profile_function) (float *, int);\n\nvoid profile_expf(int nvals, const std::string & desc,\n                  profile_function function)\n{\n    double overhead = calc_ticks_overhead();\n    double tps = calc_ticks_per_second();\n\n    // First, warm it up\n    float vals[nvals];\n    for (int i = 0;  i < nvals;  ++i)\n        vals[i] = 10.0 * (2 * i - nvals) / (1.0 * nvals);\n\n    function(vals, nvals);\n    \n    vector<double> timings(20);\n    for (unsigned trial = 0;  trial < 20;  ++trial) {\n        for (int i = 0;  i < nvals;  ++i)\n            vals[i] = 10.0 * (2 * i - nvals) / (1.0 * nvals);\n        timings[trial] = function(vals, nvals);\n    }\n\n    std::sort(timings.begin(), timings.end());\n\n    //cerr << \"timings = \" << timings << endl;\n\n    cerr << format(\"%-30s %8.2f %10.1f %8.5f\\n\", desc.c_str(),\n                   (timings[10] - overhead) / (1.0 * nvals),\n                   tps, overhead);\n}\n\nBOOST_AUTO_TEST_CASE( profile_expf_test )\n{\n    cerr << endl;\n    cerr << \"profiling expf\" << endl;\n\n    static const int NVALS = 131072;\n\n    warm_up_cpu();\n\n    profile_expf(NVALS, \"builtin\", &builtin_expf_array);\n    profile_expf(NVALS, \"builtin double\", &builtin_exp_array);\n    profile_expf(NVALS, \"sse2 discrete\", &sse2_expf_array);\n    profile_expf(NVALS, \"sse2 discrete double\", &sse2_exp_array);\n}\n\n#define test_frexpf_value(input)                                          \\\n    {                                                                   \\\n        float in2 = float(input);                                       \\\n        int exp1 = 0, exp2 = 0;                                         \\\n        float output1 = frexpf(in2, &exp1);                              \\\n        v4si eexp2;                                                     \\\n        float output2 = extract_scalar(sse2_frexpf(vec_splat(in2), eexp2)); \\\n        exp2 = extract_scalar(eexp2);                                   \\\n        if (std::isnan(output1)) {                                           \\\n            if (!std::isnan(output2)) {                                      \\\n                cerr << \"input = \" << in2 << \" output1 = \" << output1 << \" output2 = \" << output2 \\\n                 << endl;                                               \\\n            }                                                           \\\n            BOOST_CHECK(std::isnan(output2));                                \\\n        }                                                               \\\n        else if (output1 != output2) {                                  \\\n            int i1 = reinterpret_as_int(output1);                       \\\n            int i2 = reinterpret_as_int(output2);                       \\\n            if (abs(i1 - i2) > 1) {                                     \\\n                cerr << format(\"%12.8f: %14.9f != %14.9f: %08x != %08x (%4d ulps)\\n\", \\\n                               in2, output1, output2, i1, i2, (i1 - i2)); \\\n                BOOST_CHECK_EQUAL(frexpf(float(input), &exp1), output2); \\\n            }                                                           \\\n        }                                                               \\\n        if (exp1 != exp2 && isfinite(input)) {                          \\\n            BOOST_CHECK_EQUAL(make_pair(input, exp1).second, exp2);     \\\n        }                                                               \\\n    }\n\nBOOST_AUTO_TEST_CASE( test_frexpf )\n{\n    test_frexpf_value(0.0);\n    test_frexpf_value(1.0);\n    test_frexpf_value(2.0);\n    test_frexpf_value(3.0);\n    test_frexpf_value(-0.0);\n    test_frexpf_value(-1.0);\n    test_frexpf_value(-2.0);\n    test_frexpf_value(-3.0);\n\n    test_frexpf_value(-10.0);\n    test_frexpf_value(-20.0);\n    test_frexpf_value(-30.0);\n    test_frexpf_value(-50.0);\n    test_frexpf_value(-100.0);\n    test_frexpf_value(-1000.0);\n\n    test_frexpf_value(10.0);\n    test_frexpf_value(20.0);\n    test_frexpf_value(30.0);\n    test_frexpf_value(50.0);\n    test_frexpf_value(100.0);\n    test_frexpf_value(1000.0);\n\n    test_frexpf_value(-0.0);\n\n    test_frexpf_value(NaN);\n    test_frexpf_value(-NaN);\n    test_frexpf_value(INFINITY);\n    test_frexpf_value(-INFINITY);\n\n#if 0\n    int nvals = 65536;\n    for (int i = 0;  i < nvals;  ++i) {\n        float f = 105.0 * (2 * i - nvals) / (1.0 * nvals);\n        test_frexp_value(f);\n    }\n#endif\n}\n\n\n#define test_logf_value(input)                                          \\\n    {                                                                   \\\n        float in2 = float(input);                                       \\\n        float output1 = logf(in2);                                      \\\n        float output2 = extract_scalar(sse2_logf(vec_splat(in2)));      \\\n        if (std::isnan(output1)) {                                           \\\n            if (!std::isnan(output2)) {                                      \\\n                cerr << \"input = \" << in2 << \" output1 = \" << output1 << \" output2 = \" << output2 \\\n                 << endl;                                               \\\n            }                                                           \\\n            BOOST_CHECK(std::isnan(output2));                                \\\n        }                                                               \\\n        else if (output1 != output2) {                                  \\\n            int i1 = reinterpret_as_int(output1);                       \\\n            int i2 = reinterpret_as_int(output2);                       \\\n            if (abs(i1 - i2) > 1) {                                     \\\n                cerr << format(\"%12.8f: %14.9f != %14.9f: %08x != %08x (%4d ulps)\\n\", \\\n                               in2, output1, output2, i1, i2, (i1 - i2)); \\\n                BOOST_CHECK_EQUAL(logf(float(input)), output2);         \\\n            }                                                           \\\n        }                                                               \\\n    }\n\nBOOST_AUTO_TEST_CASE( test_logf )\n{\n    test_logf_value(0.0);\n    test_logf_value(1.0);\n    test_logf_value(2.0);\n    test_logf_value(3.0);\n    test_logf_value(-0.0);\n    test_logf_value(-1.0);\n    test_logf_value(-2.0);\n    test_logf_value(-3.0);\n\n    test_logf_value(-10.0);\n    test_logf_value(-20.0);\n    test_logf_value(-30.0);\n    test_logf_value(-50.0);\n    test_logf_value(-100.0);\n    test_logf_value(-1000.0);\n\n    test_logf_value(10.0);\n    test_logf_value(20.0);\n    test_logf_value(30.0);\n    test_logf_value(50.0);\n    test_logf_value(100.0);\n    test_logf_value(1000.0);\n\n    test_logf_value(-0.0);\n    test_logf_value(NaN);\n    test_logf_value(-NaN);\n    test_logf_value(INFINITY);\n    test_logf_value(-INFINITY);\n\n    int nvals = 65536;\n    for (int i = 0;  i < nvals;  ++i) {\n        float f = 105.0 * (2 * i - nvals) / (1.0 * nvals);\n        test_logf_value(f);\n    }\n}\n\ndouble builtin_logf_array(float * vals, int nvals)\n{\n    sched_yield();\n    size_t before = ticks();\n\n    for (unsigned i = 0;  i < nvals;  ++i)\n        vals[i] = logf(vals[i]);\n\n    size_t after = ticks();\n\n    return (after - before);\n}\n\ndouble builtin_log_array(float * vals, int nvals)\n{\n    sched_yield();\n    size_t before = ticks();\n\n    for (unsigned i = 0;  i < nvals;  ++i)\n        vals[i] = log(double(vals[i]));\n\n    size_t after = ticks();\n\n    return (after - before);\n}\n\ndouble sse2_logf_array(float * vals, int nvals)\n{\n    sched_yield();\n    size_t before = ticks();\n\n    int nvecs = nvals / 4;\n    v4sf * vvals = (v4sf *)vals;\n    \n    for (unsigned i = 0;  i < nvecs;  ++i)\n        vvals[i] = sse2_logf(vvals[i]);\n\n    size_t after = ticks();\n    return (after - before);\n}\n\ndouble sse2_log_array(float * vals_, int nvals)\n{\n    double vals[nvals];\n    std::copy(vals_, vals_ + nvals, vals);\n\n    sched_yield();\n    size_t before = ticks();\n\n    int nvecs = nvals / 2;\n    v2df * vvals = (v2df *)vals;\n    \n    for (unsigned i = 0;  i < nvecs;  ++i)\n        vvals[i] = sse2_log(vvals[i]);\n\n    size_t after = ticks();\n    return (after - before);\n}\n\ntypedef double (*profile_function) (float *, int);\n\nvoid profile_logf(int nvals, const std::string & desc,\n                  profile_function function)\n{\n    double overhead = calc_ticks_overhead();\n    double tps = calc_ticks_per_second();\n\n    // First, warm it up\n    float vals[nvals];\n    for (int i = 0;  i < nvals;  ++i)\n        vals[i] = 10.0 * (2 * i - nvals) / (1.0 * nvals);\n\n    function(vals, nvals);\n    \n    vector<double> timings(20);\n    for (unsigned trial = 0;  trial < 20;  ++trial) {\n        for (int i = 0;  i < nvals;  ++i)\n            vals[i] = 10.0 * (2 * i - nvals) / (1.0 * nvals);\n        timings[trial] = function(vals, nvals);\n    }\n\n    std::sort(timings.begin(), timings.end());\n\n    //cerr << \"timings = \" << timings << endl;\n\n    cerr << format(\"%-30s %8.2f %10.1f %8.5f\\n\", desc.c_str(),\n                   (timings[10] - overhead) / (1.0 * nvals),\n                   tps, overhead);\n}\n\nBOOST_AUTO_TEST_CASE( profile_logf_test )\n{\n    cerr << endl;\n    cerr << \"profiling logf\" << endl;\n\n    static const int NVALS = 131072;\n\n    warm_up_cpu();\n\n    profile_logf(NVALS, \"builtin\", &builtin_logf_array);\n    profile_logf(NVALS, \"builtin double\", &builtin_log_array);\n    profile_logf(NVALS, \"sse2 discrete\", &sse2_logf_array);\n    profile_logf(NVALS, \"sse2 discrete double\", &sse2_log_array);\n}\n\n", "meta": {"hexsha": "7301f9de3c2cc4490c9de37d446f20c5ccb9c800", "size": 24028, "ext": "cc", "lang": "C++", "max_stars_repo_path": "arch/testing/sse2_math_test.cc", "max_stars_repo_name": "mldbai/mldb", "max_stars_repo_head_hexsha": "0554aa390a563a6294ecc841f8026a88139c3041", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 665.0, "max_stars_repo_stars_event_min_datetime": "2015-12-09T17:00:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:46:46.000Z", "max_issues_repo_path": "arch/testing/sse2_math_test.cc", "max_issues_repo_name": "mldbai/mldb", "max_issues_repo_head_hexsha": "0554aa390a563a6294ecc841f8026a88139c3041", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 797.0, "max_issues_repo_issues_event_min_datetime": "2015-12-09T19:48:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T02:19:47.000Z", "max_forks_repo_path": "arch/testing/sse2_math_test.cc", "max_forks_repo_name": "mldbai/mldb", "max_forks_repo_head_hexsha": "0554aa390a563a6294ecc841f8026a88139c3041", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 103.0, "max_forks_repo_forks_event_min_datetime": "2015-12-25T04:39:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T02:55:22.000Z", "avg_line_length": 31.6157894737, "max_line_length": 101, "alphanum_fraction": 0.4798568337, "num_tokens": 6297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5098998761254718}}
{"text": "#include \"fbstab/components/dense_data.h\"\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <stdexcept>\n\nnamespace fbstab {\n\nusing MatrixXd = Eigen::MatrixXd;\nusing VectorXd = Eigen::VectorXd;\n\nvoid DenseData::gemvH(const Eigen::VectorXd &x, double a, double b,\n                      Eigen::VectorXd *y) const {\n  *y = a * H_ * x + b * (*y);\n}\n\nvoid DenseData::gemvG(const Eigen::VectorXd &x, double a, double b,\n                      Eigen::VectorXd *y) const {\n  *y = a * G_ * x + b * (*y);\n}\n\nvoid DenseData::gemvGT(const Eigen::VectorXd &x, double a, double b,\n                       Eigen::VectorXd *y) const {\n  *y = a * G_.transpose() * x + b * (*y);\n}\n\nvoid DenseData::gemvA(const Eigen::VectorXd &x, double a, double b,\n                      Eigen::VectorXd *y) const {\n  *y = a * A_ * x + b * (*y);\n}\n\nvoid DenseData::gemvAT(const Eigen::VectorXd &x, double a, double b,\n                       Eigen::VectorXd *y) const {\n  *y = a * A_.transpose() * x + b * (*y);\n}\n\nvoid DenseData::axpyf(double a, Eigen::VectorXd *y) const { *y += a * f_; }\n\nvoid DenseData::axpyh(double a, Eigen::VectorXd *y) const { *y += a * h_; }\n\nvoid DenseData::axpyb(double a, Eigen::VectorXd *y) const { *y += a * b_; }\n\n}  // namespace fbstab\n", "meta": {"hexsha": "4dd3a1cd09f0812fe436090c41b6f88e69478e24", "size": 1231, "ext": "cc", "lang": "C++", "max_stars_repo_path": "fbstab/components/dense_data.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/components/dense_data.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/components/dense_data.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": 27.9772727273, "max_line_length": 75, "alphanum_fraction": 0.5767668562, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5098702043617782}}
{"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    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    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(params);\n\n    prover.proof(commits, index, r, 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));\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(params);\n\n    prover.proof(commits, index, r, 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));\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(params);\n\n    prover.proof(commits, commits.size(), r, proof);\n\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n    BOOST_CHECK(!verifier.verify(commits,proof));\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(params);\n\n    prover.proof(commits, index, r, proof);\n\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n    BOOST_CHECK(!verifier.verify(commits,proof));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d0453ae9a85b42f21c3dd6537696848e6a52eb0e", "size": 5374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sigma/test/protocol_tests.cpp", "max_stars_repo_name": "braveheart12/Zcoin", "max_stars_repo_head_hexsha": "27020764b5a5856dff1f7f4b16f9be5991ba993b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sigma/test/protocol_tests.cpp", "max_issues_repo_name": "braveheart12/Zcoin", "max_issues_repo_head_hexsha": "27020764b5a5856dff1f7f4b16f9be5991ba993b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sigma/test/protocol_tests.cpp", "max_forks_repo_name": "braveheart12/Zcoin", "max_forks_repo_head_hexsha": "27020764b5a5856dff1f7f4b16f9be5991ba993b", "max_forks_repo_licenses": ["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.1796407186, "max_line_length": 125, "alphanum_fraction": 0.6617045032, "num_tokens": 1521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5098702043617782}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <opencv2/core.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/core/utility.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/video/tracking.hpp>\n#include <opencv2/plot.hpp>\n#include \"g2o/solvers/eigen/linear_solver_eigen.h\"\n\n#include \"data.hpp\"\n#include \"helper.hpp\"\n\n#include \"stereo_processor/pose_estimater.hpp\"\n#include \"stereo_processor/g2o_edges/edge_se3m.h\"\n\nclass LocalKFOptimizer{\nprivate:\n\tPoseEstimater pose_estimater;\n\n\tdouble getTransformBetweenKF(const KeyFrame& KF_from, const KeyFrame& KF_to, const CameraModel& cam0, Eigen::Isometry3d& T);\npublic:\n\tbool optimize(std::vector<KeyFrame>& keyframes, int KF_count, const CameraModel& cam0);\n\n};\n", "meta": {"hexsha": "cb27f1613953ab4ceb83fb334d7a210a923986f7", "size": 859, "ext": "hpp", "lang": "C++", "max_stars_repo_path": ".backup/local_KF_optimizer.hpp", "max_stars_repo_name": "jiawei-mo/dsvo", "max_stars_repo_head_hexsha": "a6d6f3a5377b472550fd3f48308adc701ed5c679", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-09-22T16:00:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:14:04.000Z", "max_issues_repo_path": ".backup/local_KF_optimizer.hpp", "max_issues_repo_name": "TianQi-777/dsvo", "max_issues_repo_head_hexsha": "60f4153bc970718b7ebb4be66fa1ebb0f1372a38", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-22T02:12:15.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-28T18:57:12.000Z", "max_forks_repo_path": ".backup/local_KF_optimizer.hpp", "max_forks_repo_name": "jiawei-mo/dsvo", "max_forks_repo_head_hexsha": "a6d6f3a5377b472550fd3f48308adc701ed5c679", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-01-02T02:05:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-16T08:00:28.000Z", "avg_line_length": 29.6206896552, "max_line_length": 125, "alphanum_fraction": 0.7881257276, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5098701939644632}}
{"text": "#ifndef _ITERATIVE_CLOSEST_POINT_HPP_\n#define _ITERATIVE_CLOSEST_POINT_HPP_\n\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/algorithms/distance.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/algorithms/correct.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\n\n#include <boost/geometry/index/rtree.hpp>\n\n#include <cmath>\n#include <vector>\n#include <iostream>\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\n\n\n#include \"hornRegistration.hpp\"\n#include \"TerminationCriteria.hpp\"\n\n/// Finds the nearest point on a line segment to a point in space.  Called by the function OutsideOfTriangle()\n/// to determine where the nearest point is to each side of the triangle.\n/// @param a is the point in space\n/// @param p is one end of the line segment represented by an Eigen::Vector3d\n/// @param q is the other end of the line segment represented by an Eigen::Vector3d\n/// @see page 8 of PointPairs.pdf from the notes\nEigen::Vector4d ProjectOnSegment(const Eigen::Vector3d& c, const Eigen::Vector3d& p, const Eigen::Vector3d& q)\n{\n    Eigen::Vector3d pMinusQ = q - p;\n    double lambda = (c-p).dot(pMinusQ)/(pMinusQ.dot(pMinusQ));\n    double zero = 0.0;\n    double one = 1.0;\n    double vertexlogic = one;\n    if (lambda <= 0 || lambda >= 1){\n        vertexlogic = zero;\n    }\n    lambda = std::max(zero,std::min(lambda,one));\n    Eigen::Vector4d cNew;\n    cNew.block<3,1>(0,0) = p+lambda*pMinusQ;\n    cNew(3) = vertexlogic;\n    return cNew;\n}\n\n/// Determines if two points are equal.  Used by the function OutsideOfTriangle to determine if the nearest\n/// point on the triangle lies on a vertice\n/// @param a is the point in space\n/// @param p is the first vertice of the triangle represented by an Eigen::Vector3d\nbool PointEqualityCheck(const Eigen::Vector3d& a, const Eigen::Vector3d& b){\n    bool tf = (a(0) == b(0) && a(1) == b(1) && a(2) == b(2));\n    return tf;\n}\n\n/// Finds the closest point on the triangle to a point in space if the closest point lies on an edge or vertice\n/// @param a is the point in space\n/// @param p is the first vertice of the triangle represented by an Eigen::Vector3d\n/// @param q is the second vertice of the triangle represented by an Eigen::Vector3d\n/// @param r is the third vertice of the triangle represented by an Eigen::Vector3d\n/// @see page 8 of PointPairs.pdf from the notes\nEigen::Vector3d OutsideOfTriangle(const Eigen::Vector3d& a, const Eigen::Vector3d& p, const Eigen::Vector3d& q, const Eigen::Vector3d& r)\n{\n    Eigen::MatrixXd c(3,4);\n    c.block<1,4>(0,0) = ProjectOnSegment(a,r,p).transpose();\n    c.block<1,4>(1,0) = ProjectOnSegment(a,p,q).transpose();\n    c.block<1,4>(2,0) = ProjectOnSegment(a,q,r).transpose();\n    Eigen::Vector3d cnew;\n    if (PointEqualityCheck(c.block<1,3>(0,0),c.block<1,3>(1,0))) cnew = c.block<1,3>(0,0);\n    else if (PointEqualityCheck(c.block<1,3>(0,0),c.block<1,3>(2,0))) cnew = c.block<1,3>(0,0);\n    else if (PointEqualityCheck(c.block<1,3>(1,0),c.block<1,3>(2,0))) cnew = c.block<1,3>(1,0);\n    else{\n        for (int i=0; i<3; i++){\n            if (c(i,3) == 1){\n                cnew = c.block<1,3>(i,0);\n            }\n        }\n    }\n    return cnew;\n}\n\n/// Finds the closest point on the triangle to a point in space.  If the closest point lies with in triangle,\n/// then the function finds the nearest point internally.  Else if the closest point lies on an edge or vertice,\n/// the function OutsideOfTriangle() is called to find the nearest point\n/// @param a is the point in space represented by an Eigen::Vector3d\n/// @param vertices are the three vertices of the triangle represented by standard vector of Eigen::Vector3d\n/// @see page 7 of PointPairs.pdf from the notes\nEigen::Vector3d FindClosestPoint(const Eigen::Vector3d& p, const Eigen::Vector3d& p1, const Eigen::Vector3d& p2, const Eigen::Vector3d& p3)\n{\n    Eigen::Vector3d u = p2-p1;\n    Eigen::Vector3d v = p3-p1;\n    Eigen::Vector3d w = p-p1;\n    Eigen::Vector3d n = u.cross(v);\n    double gamma = u.cross(w).dot(n)/(n.dot(n));\n    double beta = w.cross(v).dot(n)/(n.dot(n));\n    double alpha = 1-gamma-beta;\n    Eigen::Vector3d projectedPoint;\n    if ((alpha < 0 || alpha > 1) || (beta < 0 || beta > 1) || (gamma < 0 || gamma > 1)){\n        projectedPoint = OutsideOfTriangle(p,p1,p2,p3);\n    }\n    else projectedPoint = alpha*p1+beta*p2+gamma*p3;\n\n    return projectedPoint;\n}\n\nEigen::Vector3d FindClosestPoint(const Eigen::Vector3d& p, const std::vector<Eigen::Vector3d>& vertices, const Eigen::VectorXd& triangle) {\n    \n    Eigen::Vector3d p1 = vertices[triangle(0)];\n    Eigen::Vector3d p2 = vertices[triangle(1)];\n    Eigen::Vector3d p3 = vertices[triangle(2)];\n\n    return FindClosestPoint(p,p1,p2,p3);\n}\n\n\n\n\ntypedef Eigen::Vector3d EV3d;\ntypedef bg::cs::cartesian bgcscart;\n\n#define ZEROINDEX operator()(0)\n#define ONEINDEX operator()(1)\n#define TWOINDEX operator()(2)\n\nBOOST_GEOMETRY_REGISTER_POINT_3D(EV3d, double, bgcscart, ZEROINDEX, ONEINDEX, TWOINDEX)\n\n\nnamespace cis {\n    \n    //typedef bg::model::point<double, 3, bg::cs::cartesian> point;\n    typedef Eigen::Vector3d point;\n    typedef bg::model::box<point> box;\n    typedef bg::model::polygon<point, false, false> polygon; // ccw, open polygon\n    typedef std::pair<box, polygon> value;\n}\n\n\n/// perform ICPregistration on source data consisting of sensor data,\n/// prior known body data, and a triangle mesh.\n///\n/// @pre NA and NB vectors, rather than data, must be of equal length. Corresponding to the same quantity of measured sample time points.\n///\n/// @param[in]  NA list of sensor data point sets for pointer A\n/// @param[in]  NB list of sensor data point sets for fiducial B\n/// @param[in]  Atip location of tip of pointerA in pointer A body coordinates\n/// @param[in]  bodyAmarkerLEDs location of LED markers on pointer A in pointer A body coordinates\n/// @param[in]  bodyAmarkerLEDs location of LED markers on fiducial B in fiducial B body coordinatesnd 3 correspond to neighbors. -1 indicates not a neighbor. List of triangles on mesh, corresponding to bone surface.\n/// @return dkList location of Atip in fiducial B body coordinates, nx3 matrix of transposed vectors\nEigen::MatrixXd\ndkKnownMeshPointsBaseFrame(const std::vector<Eigen::MatrixXd>& NA,\n                                const std::vector<Eigen::MatrixXd>& NB,\n                                const Eigen::Vector3d& Atip,\n                                const Eigen::MatrixXd& bodyAmarkerLEDs,\n                                const Eigen::MatrixXd& bodyBmarkerLEDs){\n    \n    Eigen::MatrixXd dkList(NA.size(),3);\n    \n    for (int i=0; i<NA.size(); i++){\n        Eigen::Affine3d FaAffine(hornRegistration(bodyAmarkerLEDs,NA[i])); // a: PA3-A-Debug-SampleReadingsTest A: Problem3-BodyA\n        Eigen::Affine3d FbInverseAffine(hornRegistration(NB[i], bodyBmarkerLEDs)); // b: PA3-A-Debug-SampleReadingsTest B: Problem3-BodyB\n        \n        // Atip: Problem3-BodyA (last line)\n        Eigen::Vector3d dk_i(Eigen::Vector3d(FbInverseAffine*FaAffine*Atip));\n        dkList.block<1,3>(i,0) = dk_i.transpose();\n    }\n    \n    return dkList;\n}\n\n/// Perform one iteration of ICPregistration on source data consisting of sensor data,\n/// prior known body data, and a triangle mesh.\n///\n/// @param[out] dkList location of Atip in fiducial B body coordinates, nx3 matrix of transposed vectors\n/// @param[in]  vertices list of vertices on mesh, corresponding to bone surface\n/// @param[in]  vertexTriangleNeighborIndex list of 1x6 vectors. First 3 Elements are indices into vertices list, Second 3 correspond to neighbors. -1 indicates not a neighbor. List of triangles on mesh, corresponding to bone surface.\n/// @param[out] ck location of CT mesh closest to sample points, nx3 matrix of transposed vectors\n/// @param[out] errork norm between ck and dk\nvoid ICPwithSimpleSearchStep(\n                              const Eigen::MatrixXd& dkList,\n                              const std::vector<Eigen::Vector3d>& vertices,\n                              const std::vector<Eigen::VectorXd>& vertexTriangleNeighborIndex,\n                              Eigen::Affine3d& Freg,\n                              Eigen::MatrixXd& skList,\n                              Eigen::MatrixXd& ckList,\n                              std::vector<double>& errork){\n    \n    errork.clear();\n    ckList.resize(dkList.rows(),3);\n    skList.resize(dkList.rows(),3);\n    \n    for (int i=0; i<dkList.rows(); i++){\n        double errorMin=std::numeric_limits<double>::max();\n\t    Eigen::Vector3d ckMin;\n        Eigen::Vector3d dk_i(dkList.block<1,3>(i,0).transpose());\n        \n        Eigen::Vector3d sk(Freg*dk_i);\n        skList.block<1,3>(i,0) = sk.transpose();\n        \n        //if(i % NA.size() == 3) std::cout << \"\\n\\nsk[3]\\n\\n\" << sk << \"\\n\\n\";\n        for (auto&& triangle : vertexTriangleNeighborIndex){\n            Eigen::Vector3d ckTemp = FindClosestPoint(sk, vertices, triangle);\n            double errorTemp = (sk-ckTemp).norm();\n            if (errorTemp < errorMin){\n                ckMin = ckTemp;\n                errorMin = errorTemp;\n            }\n        }\n\t\tckList.block<1,3>(i,0) = ckMin.transpose();\n        errork.push_back(errorMin);\n    }\n\t\n\tFreg = hornRegistration(dkList,ckList);\n}\n\n/// perform ICPregistration on source data consisting of sensor data,\n/// prior known body data, and a triangle mesh. Uses brute force iteration.\n/// Runs many iterations and stops\n/// optimization based on the input terminationCriteria object, which also\n/// returns statistics of the execution by default.\n///\n/// @param[in] dkList location of Atip in fiducial B body coordinates, n x 3 matrix of transposed vectors\n/// @param[in]  vertices list of vertices on mesh, corresponding to bone surface\n/// @param[in]  vertexTriangleNeighborIndex list of 1x6 vectors. First 3 Elements are indices into vertices list, Second 3 correspond to neighbors. -1 indicates not a neighbor. List of triangles on mesh, corresponding to bone surface.\n/// @param[in,out] terminationCriteria  Collects statistics and determines when algorithm should stop. C++ concept matches TerminationCriteria class.\n/// @param[out] ck location of CT mesh closest to sample points, nx3 matrix of transposed vectors\n/// @param[out] errork norm between ck and dk\ntemplate<typename TerminationType = TerminationCriteria>\nvoid ICPwithSimpleSearch(\n                              const Eigen::MatrixXd& dkList,\n                              const std::vector<Eigen::Vector3d>& vertices,\n                              const std::vector<Eigen::VectorXd>& vertexTriangleNeighborIndex,\n                              TerminationType& terminationCriteria,\n                              Eigen::Affine3d& Freg,\n                              Eigen::MatrixXd& skList,\n                              Eigen::MatrixXd& ckList,\n                              std::vector<double>& errork,\n                              bool debug = false){\n\n    Freg.setIdentity();\n    \n    for(int i = 0; !terminationCriteria.shouldTerminate(); i++){\n        \n        if(debug) std::cout << \"\\n\\nFreg before iteration \" << i << \":\\n\\n\" << Freg.matrix() << \"\\n\\n\";\n        \n        if(i) terminationCriteria.nextIteration();\n\t\tICPwithSimpleSearchStep(dkList,vertices,vertexTriangleNeighborIndex,Freg,skList,ckList,errork);\n        \n        for(auto && err : errork){\n            terminationCriteria(err);\n        }\n        \n\t}\n}\n\n\n\n\n/// Perform one iteration of ICPregistration on source data consisting of sensor data,\n/// prior known body data, and a triangle mesh. Uses a spatial index to accelerate\n/// nearest neighbor lookup of triangles.\n///\n/// @tparam boost::geometry::rtree data structure type configured with the triangle set\n///\n/// @param[in] dkList location of Atip in fiducial B body coordinates, n x 3 matrix of transposed vectors\n/// @param[in] vertices list of vertices on mesh, corresponding to bone surface\n/// @param[in] rtree actual triangle data index\n/// @param[in,out] terminationCriteria  Collects statistics and determines when algorithm should stop. C++ concept matches TerminationCriteria class.\n/// @param[out] ck location of CT mesh closest to sample points, nx3 matrix of transposed vectors\n/// @param[out] errork norm between ck and dk\n/// @param[out] errork norm between ck and dk\n/// @param[in]  initialQuerySize is the number of boxes that will initially be selected in spatialIndex. Affects algorithm performance.\ntemplate<typename RTREE>\nvoid ICPwithSpatialIndexStep(\n                      const Eigen::MatrixXd& dkList,\n                      const RTREE& rtree,\n                      Eigen::Affine3d& Freg,\n                      Eigen::MatrixXd& skList,\n                      Eigen::MatrixXd& ckList,\n                      std::vector<double>& errork,\n                      const std::size_t initialQuerySize = 4){\n    \n    errork.clear();\n    ckList.resize(dkList.rows(),3);\n    skList.resize(dkList.rows(),3);\n    \n    for (int i=0; i<dkList.rows(); ++i){\n        double minErrorAKAdistanceToClosestTriangle=std::numeric_limits<double>::max();\n        Eigen::Vector3d ckClosestPointOnMesh;\n        Eigen::Vector3d dk_i(dkList.block<1,3>(i,0).transpose());\n        \n        Eigen::Vector3d sk(Freg*dk_i);\n        skList.block<1,3>(i,0) = sk.transpose();\n        \n        // starting query size will affect performance\n        /// @todo consider making querySize a parameter\n        \n        bool closestFound = false;\n        std::size_t querySize = initialQuerySize;\n        while(!closestFound){\n            // If the distance to the next box was greater than to the nearest triangle\n            // or the distance to the triangle was equal to 0\n            // break the loop.\n            \n            // find 2 nearest values to a point\n            std::vector<cis::value> result_n;\n            rtree.query(bgi::nearest(sk, querySize), std::back_inserter(result_n));\n            \n            // results should be listed in order from closest box to furthest box,\n            // but the boxes can overlap so untl the closest point on the nearest triangle\n            // is closer than boxes later in the list, there may be closer triangle points\n            // than the current one.\n            for(auto&& result : result_n){\n                /// @todo Eliminate redundantly checking first querySize boxes in result_n on subsequent iterations of while(!closestFound == false).\n                Eigen::Vector3d ckClosestPointOnCurrentTriangle = FindClosestPoint(sk, result.second.outer()[0], result.second.outer()[1], result.second.outer()[2]);\n                double distanceToCurrentBox = bg::distance(sk,result.first);\n                double distanceToCurrentTriangle = bg::distance(sk,ckClosestPointOnCurrentTriangle);\n                \n                \n                if (distanceToCurrentTriangle < minErrorAKAdistanceToClosestTriangle){\n                    // put dk (qk)  into A put ck into B\n                    ckClosestPointOnMesh = ckClosestPointOnCurrentTriangle;\n                    minErrorAKAdistanceToClosestTriangle = distanceToCurrentTriangle;\n                }\n                \n                // leave the loop if the distance to the box is larger than the distance to the polygon\n                if( minErrorAKAdistanceToClosestTriangle < distanceToCurrentBox || distanceToCurrentTriangle == 0) {\n                    closestFound = true;\n                    break;\n                }\n            }\n            \n            // increase the query size and rerun it if we didn't find the closest point for certain\n            querySize *=2;\n        }\n        \n        ckList.block<1,3>(i,0) = ckClosestPointOnMesh.transpose();\n        BOOST_VERIFY(!boost::math::isnan(minErrorAKAdistanceToClosestTriangle));\n        errork.push_back(minErrorAKAdistanceToClosestTriangle);\n    }\n    \n    Freg = hornRegistration(dkList,ckList);\n}\n\n\n/// perform ICPregistration on source data consisting of sensor data,\n/// prior known body data, and a triangle mesh.  Uses a spatial index to accelerate\n/// nearest neighbor lookup of triangles. Runs many iterations and stops\n/// optimization based on the input terminationCriteria object, which also\n/// returns statistics of the execution by default.\n///\n/// @param[in] dkList location of Atip in fiducial B body coordinates, n x 3 matrix of transposed vectors\n/// @param[in]  vertices list of vertices on mesh, corresponding to bone surface\n/// @param[in]  vertexTriangleNeighborIndex list of 1x6 vectors. First 3 Elements are indices into vertices list, Second 3 correspond to neighbors. -1 indicates not a neighbor. List of triangles on mesh, corresponding to bone surface.\n/// @param[in,out] terminationCriteria  Collects statistics and determines when algorithm should stop. C++ concept matches TerminationCriteria class.\n/// @param[out] ck location of CT mesh closest to sample points, nx3 matrix of transposed vectors\n/// @param[out] errork norm between ck and dk\ntemplate<typename TerminationType = TerminationCriteria>\nvoid ICPwithSpatialIndex(\n                  const Eigen::MatrixXd& dkList,\n                  const std::vector<Eigen::Vector3d>& vertices,\n                  const std::vector<Eigen::VectorXd>& vertexTriangleNeighborIndex,\n                  TerminationType& terminationCriteria,\n                  Eigen::Affine3d& Freg,\n                  Eigen::MatrixXd& skList,\n                  Eigen::MatrixXd& ckList,\n                  std::vector<double>& errork,\n                  bool debug = false){\n    \n    Freg.setIdentity();\n    \n    \n    // polygons\n    std::vector<cis::polygon> polygons;\n    \n    \n    // create some polygons\n    for ( auto&& triangle : vertexTriangleNeighborIndex )\n    {\n        // create a polygon\n        cis::polygon p;\n        \n        Eigen::Vector3d p1 = vertices[triangle(0)];\n        Eigen::Vector3d p2 = vertices[triangle(1)];\n        Eigen::Vector3d p3 = vertices[triangle(2)];\n        p.outer().push_back(p1);\n        p.outer().push_back(p2);\n        p.outer().push_back(p3);\n        \n        // add polygon\n        polygons.push_back(p);\n    }\n    \n    // create the rtree using default constructor\n    bgi::rtree< cis::value, bgi::rstar<16, 4> > rtree;\n    \n    // fill the spatial index\n    for ( auto && polygon : polygons )\n    {\n        \n        // calculate polygon bounding box\n        cis::box b = bg::return_envelope<cis::box>(polygon);\n        // insert new value\n        rtree.insert(std::make_pair(b, polygon));\n    }\n    \n    for(int i = 0; !terminationCriteria.shouldTerminate(); i++){\n        \n        if(debug) std::cout << \"\\n\\nFreg before iteration \" << i << \":\\n\\n\" << Freg.matrix() << \"\\n\\n\";\n        if(i) terminationCriteria.nextIteration();\n        ICPwithSpatialIndexStep(dkList,rtree,Freg,skList,ckList,errork);\n        \n        for(auto && err : errork){\n            terminationCriteria(err);\n        }\n    }\n}\n\n\n#endif // _ITERATIVE_CLOSEST_POINT_HPP_\n", "meta": {"hexsha": "7855dc8bd6ea785e56bb08eb4f59adf9bc2ad6cf", "size": 19042, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/IterativeClosestPoint.hpp", "max_stars_repo_name": "ahundt/cis", "max_stars_repo_head_hexsha": "bd55e8c77ec78994454247ffe7d67f537710a53f", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-17T03:13:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-17T03:13:01.000Z", "max_issues_repo_path": "include/IterativeClosestPoint.hpp", "max_issues_repo_name": "ahundt/cis", "max_issues_repo_head_hexsha": "bd55e8c77ec78994454247ffe7d67f537710a53f", "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": "include/IterativeClosestPoint.hpp", "max_forks_repo_name": "ahundt/cis", "max_forks_repo_head_hexsha": "bd55e8c77ec78994454247ffe7d67f537710a53f", "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": 44.8047058824, "max_line_length": 234, "alphanum_fraction": 0.6478836257, "num_tokens": 4681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5098701939644632}}
{"text": "#include <iostream>\n#include <utility>\n#include <algorithm>\n#include <vector>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/transform_value_property_map.hpp>\n#include <boost/property_map/function_property_map.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <future>\n#include <torch/extension.h>\n#define EPS 1e-20\n\nclass union_find{\npublic:\n    union_find(int n){\n        this->count = n;\n        for(auto i=0; i<n; i++){\n            parent[i] = i;\n        }\n    }\n\n    void make_set(int x){\n        this->parent[x] = x;\n        count++;\n    }\n    int find(int x){\n        int tmp = x;\n        while(parent[tmp] != tmp){\n            parent[tmp] = parent[parent[tmp]];\n            tmp = parent[tmp];\n        }\n        return tmp;\n    }\n    // For now set parent[y] = x. Union by rank may come later. In that case we need to make sure the root is\n    // always lower f value\n    void link(int x, int y){\n        parent[y] = x;\n        count--;\n    }\n    int num_connected_component() const{\n        return this->count;\n    }\nprivate:\n    std::map<int, int> parent;\n    int count;\n\n};\nusing std::vector;\nusing torch::Tensor;\ntypedef std::pair<long, long> Edge;\ntypedef std::pair<int, Edge> Pers;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int>> Graph;\ntypedef boost::graph_traits<Graph>::vertex_descriptor VertexDesc;\ntypedef boost::graph_traits<Graph>::edge_descriptor EdgeDesc;\ntypedef boost::graph_traits<Graph>::vertex_iterator VertexIter;\ntypedef boost::graph_traits<Graph>::edge_iterator EdgeIter;\nusing PathType = vector<vector<VertexDesc>>;\nusing namespace torch::indexing;\n\n\nPathType find_path(int start, VertexDesc goal, const Graph& _graph)  {\n    vector<VertexDesc> p(num_vertices(_graph));\n    vector<int> d(num_vertices(_graph));\n    VertexDesc s = vertex(start, _graph);\n\n    //auto idmap = boost::get(boost::vertex_index, _graph);\n\n    //vector<VertexDesc> predecessors(boost::num_vertices(_graph), Graph::null_vertex());\n    //vector<int> distances(boost::num_vertices(_graph));\n    //boost::property_map<Graph, boost::edge_weight_t>::type weightmap = boost::get(boost::edge_weight, _graph);\n    dijkstra_shortest_paths(_graph, s, boost::predecessor_map(&p[0]).distance_map(&d[0]));\n\n    // extract path\n    VertexDesc current = goal;\n    PathType path { };\n    //PathType edge_path;\n\n    do {\n        auto const pred = p.at(current);\n\n        //std::cout << \"extract path: \" << current << \" \" << _graph[current].coord << \" <- \" << pred << std::endl;\n\n        if(current == pred)\n            break;\n        path.push_back({current, pred});\n        current = pred;\n\n\n    } while(current != start);\n\n    //std::reverse(path.begin(), path.end());\n\n    return path;\n}\n\n\nbool mycmp(Edge a, Edge b){\n    float a_val = std::max(a.first, a.second);\n    float b_val = std::max(b.first, b.second);\n    if (a_val < b_val)\n        return true;\n    else if(std::abs(a_val - b_val) < EPS)\n        return a.second - b.second;\n    return false;\n}\n\nbool vcmp(const vector<VertexDesc>& a, const vector<VertexDesc>& b){\n    float a_val = std::max(a[0], a[1]);\n    float b_val = std::max(b[0], b[1]);\n    if (a_val < b_val)\n        return true;\n    else if(std::abs(a_val - b_val) < EPS)\n        return a[1] - b[1];\n    return false;\n}\n\nvoid print_pairs(vector<Pers> &ed) {\n    for (auto e: ed) {\n        std::cout << e.first << \" (\" << e.second.first << \",\" << e.second.second << \")\" << std::endl;\n    }\n}\n\nvoid print_path(const PathType& p){\n    for(auto v : p){\n        std::cout << \"(\" << v[0] << \",\" << v[1] << \")\" << std::endl;\n    }\n}\n\nstruct CustomEdgeCompare {\n    Tensor vert_fil;\n    CustomEdgeCompare(const Tensor &vertex_filtration){\n        this->vert_fil = vertex_filtration;\n    }\n\n    bool operator()(const vector<VertexDesc>& a, const vector<VertexDesc>& b) const {\n        double a_val = std::max(vert_fil[a[0]].item<double>(), vert_fil[a[1]].item<double>());\n        double b_val = std::max(vert_fil[b[0]].item<double>(), vert_fil[b[1]].item<double>());\n        if (a_val < b_val)\n            return true;\n        else if(std::abs(a_val - b_val) < EPS)\n            return (vert_fil[a[1]] - vert_fil[b[1]]).item<int>();\n        return false;\n    }\n};\nvector<Tensor> compute_pd0(const Tensor & vertex_filtration,\n                           const vector<Tensor> & boundary_info){\n    auto num_nodes = vertex_filtration.size(0);\n    union_find uf = union_find(num_nodes);\n    Tensor tensor_edges = boundary_info[0];\n    Tensor edge_val = std::get<0>(torch::max(vertex_filtration.index({tensor_edges}), 1));\n    Tensor sorted_edge_indices = edge_val.argsort(-1,false);\n    const Tensor sorted_edges = tensor_edges.index({sorted_edge_indices});\n    edge_val = edge_val.index({sorted_edge_indices});\n    auto num_edges = sorted_edges.size(0);\n    vector<Tensor> pd_0;\n\n    for(auto i = 0; i < num_edges; i++){\n        auto e = sorted_edges[i];\n        auto e_val = edge_val[i];\n        int u = e[0].item<int>();\n        int v = e[1].item<int>();\n        int root_u = uf.find(u);\n        int root_v = uf.find(v);\n        if(root_u == root_v){\n            continue;\n        }\n        int root = root_u;\n        int merged = root_v;\n        if (vertex_filtration[root].item<double>() > vertex_filtration[merged].item<double>())\n            std::swap(root, merged);\n        else if (std::abs(vertex_filtration[root].item<double>() - vertex_filtration[merged].item<double>()) < EPS) {\n            if (root > merged)\n                std::swap(root, merged);\n        }\n        auto merged_val = vertex_filtration[merged];\n        //std::cout << \"M: \" << merged_val.item<double>() << \" E: \" << e_val.item<double>()<< std::endl;\n        Tensor pd_pair = torch::stack({merged_val, e_val});\n        pd_0.emplace_back(pd_pair);\n        uf.link(root, merged);\n    }\n    return pd_0;\n\n}\n\nvector<vector<Tensor>> extended_filt_persistence_single(const Tensor & vertex_filtration,\n                                                        const vector<Tensor> & boundary_info){\n    vector<vector<Tensor>> pd;\n    auto num_nodes = vertex_filtration.size(0);\n    union_find uf = union_find(num_nodes);\n    Graph g;\n    vector<size_t> pos_edge_index;\n    vector<Tensor> pd_0_up = compute_pd0(vertex_filtration, boundary_info);\n    vector<Tensor> pd_0_down, pd_1_rel, pd_1_ext;\n    Tensor tensor_edges = boundary_info[0];\n    Tensor edge_val = std::get<0>(torch::min(vertex_filtration.index({tensor_edges}), 1));\n    Tensor sorted_edge_indices = edge_val.argsort(-1, true);\n    const Tensor sorted_edges = tensor_edges.index({sorted_edge_indices});\n    edge_val = edge_val.index({sorted_edge_indices});\n    auto num_edges = sorted_edges.size(0);\n    for(auto i = 0; i < num_edges; i++){\n        auto e = sorted_edges[i];\n        auto e_val = edge_val[i];\n        int u = e[0].item<int>();\n        int v = e[1].item<int>();\n        int root_u = uf.find(u);\n        int root_v = uf.find(v);\n        if(root_u == root_v){\n            pos_edge_index.push_back(i);\n            continue;\n        }\n        boost::add_edge(u, v, 1, g);\n        int root = root_u;\n        int merged = root_v;\n        if (vertex_filtration[root].item<double>() < vertex_filtration[merged].item<double>())\n            std::swap(root, merged);\n        else if (std::abs(vertex_filtration[root].item<double>() - vertex_filtration[merged].item<double>()) < EPS) {\n            if (root < merged)\n                std::swap(root, merged);\n        }\n        auto merged_val = vertex_filtration[merged];\n        Tensor pd_pair = torch::stack({merged_val, e_val});\n        pd_0_down.emplace_back(pd_pair);\n        uf.link(root, merged);\n    }\n    //pd.push_back(pd_0);\n    Tensor min_max = torch::stack({vertex_filtration.min(), vertex_filtration.max()});\n    pd_1_rel.push_back(min_max);\n    CustomEdgeCompare cmp = CustomEdgeCompare(vertex_filtration);\n    for(auto ii : pos_edge_index){\n        auto pos_edge = sorted_edges[ii];\n        auto pos_edge_val = edge_val[ii];\n        int u = pos_edge[0].item<int>();\n        int v = pos_edge[1].item<int>();\n        PathType p = find_path(u, v, g);\n        //std::cout << \"Edge: \" << u << \" \" << v << std::endl;\n        //print_path(p);\n        auto result = *std::max_element(p.begin(), p.end(), cmp);\n        boost::remove_edge(result[0], result[1], g);\n        //std::cout << \"Removed edge: \" << result[0] << \" \" << result[1] << std::endl;\n        boost::add_edge(u, v, 1, g);\n        auto cut_edge_tensor = torch::from_blob(result.data(), {2}, torch::TensorOptions().dtype(at::kLong));\n        auto cut_edge_val = vertex_filtration.index({cut_edge_tensor}).max();\n        //std::cout << \"CE \" << cut_edge_val.item<double>() << \" AE \" << pos_edge_val.item<double>() << std::endl;\n        auto pers_pair = torch::stack({cut_edge_val, pos_edge_val});\n        pd_1_ext.push_back(pers_pair);\n    }\n    //pd.push_back(pd_1);\n    pd.push_back(pd_0_up);\n    pd.push_back(pd_0_down);\n    pd.push_back(pd_1_rel);\n    pd.push_back(pd_1_ext);\n    return pd;\n\n}\nvector<vector<vector<Tensor>>> extended_filt_persistence_batch(const vector<std::tuple<Tensor, vector<Tensor>>> & batch){\nauto futures = vector<std::future<vector<vector<Tensor>>>>();\nfor (auto & arg: batch){\n\nfutures.push_back(\n        async(std::launch::async,[=]{\n                  return extended_filt_persistence_single(\n                          std::get<0>(arg),\n                          std::get<1>(arg)\n                  );\n              }\n)\n);\n}\nauto ret = vector<vector<vector<Tensor>>>();\nfor (auto & fut: futures){\nret.push_back(\n        fut.get()\n);\n}\n\nreturn ret;\n}\n\nPYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {\nm.def(\"extended_persistence_batch\", &extended_filt_persistence_batch, \"A function to compute extended_persistence in batches as C-hofer\");\nm.def(\"extended_persistence_single\", &extended_filt_persistence_single, \"A function to compute extended_persistence with (v, [e]) format\");\n}\n\n", "meta": {"hexsha": "29431bce0bfeef599fa3b5e58c71b7a035019c9c", "size": 10030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TopGraph/extendedpersistence/extended_pers_11-28-2021ORIGINAL.cpp", "max_stars_repo_name": "mityanony404/TopGraph", "max_stars_repo_head_hexsha": "23595ca5d3dfcd5bc5ebb771800e3fbe9a0d5eed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TopGraph/extendedpersistence/extended_pers_11-28-2021ORIGINAL.cpp", "max_issues_repo_name": "mityanony404/TopGraph", "max_issues_repo_head_hexsha": "23595ca5d3dfcd5bc5ebb771800e3fbe9a0d5eed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TopGraph/extendedpersistence/extended_pers_11-28-2021ORIGINAL.cpp", "max_forks_repo_name": "mityanony404/TopGraph", "max_forks_repo_head_hexsha": "23595ca5d3dfcd5bc5ebb771800e3fbe9a0d5eed", "max_forks_repo_licenses": ["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.1929824561, "max_line_length": 146, "alphanum_fraction": 0.6137587238, "num_tokens": 2564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954683, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5098701913651343}}
{"text": "//\n//! Copyright \u00a9 2021\n//! Brandon Kohn\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#ifndef GEOMETRIX_CONVEX_POLYGON_POLYGON_INTERSECTION_HPP\n#define GEOMETRIX_CONVEX_POLYGON_POLYGON_INTERSECTION_HPP\n#pragma once\n\n#include <geometrix/algorithm/intersection/segment_segment_intersection.hpp>\n#include <geometrix/algorithm/orientation/point_segment_orientation.hpp>\n#include <geometrix/primitive/point_sequence_traits.hpp>\n#include <geometrix/primitive/polygon.hpp>\n#include <geometrix/algorithm/point_in_polygon.hpp>\n#include <geometrix/primitive/point.hpp>\n#include <geometrix/arithmetic/arithmetic_promotion_policy.hpp>\n#include <geometrix/utility/utilities.hpp>\n\n#include <boost/container/flat_set.hpp>\n#include <boost/container/small_vector.hpp>\n#include <boost/container/new_allocator.hpp>\n#include <boost/concept_check.hpp>\n\n/////////////////////////////////////////////////////////////////////////////\n//\n// NAMESPACE\n//\n/////////////////////////////////////////////////////////////////////////////\nnamespace geometrix {\n    enum class polygon_intersection_type\n    {\n        none = 0,\n        face = 1,\n        vertex = 2,\n        overlapping = 3\n    };\n\n    //! From Computational Geometry in C, O'Rourke.\n    template <typename Polygon1, typename Polygon2, typename Visitor, typename NumberComparisonPolicy>\n    inline polygon_intersection_type convex_polygon_polygon_intersection(const Polygon1& pgon1, const Polygon2& pgon2, Visitor&& visitor, const NumberComparisonPolicy& cmp)\n    {\n        BOOST_CONCEPT_ASSERT((PointSequenceConcept<Polygon1>));\n        BOOST_CONCEPT_ASSERT((PointSequenceConcept<Polygon2>));\n        BOOST_CONCEPT_ASSERT((NumberComparisonPolicyConcept<NumberComparisonPolicy>));\n        using access1 = point_sequence_traits<Polygon1>;\n        using access2 = point_sequence_traits<Polygon2>;\n        using length_t = typename select_arithmetic_type_from_sequences<typename access1::point_type, typename access2::point_type>::type;\n        using area_t = decltype(std::declval<length_t>() * std::declval<length_t>());\n        using point_t = point<length_t, 2>;\n        using vector_t = vector<length_t, 2>;\n        enum in_out_state \n        { \n            pgon1_in,\n            pgon2_in,\n            unknown\n        };\n\t\tauto pointCmp = [&]( const point_t& lhs, const point_t& rhs )\n\t\t{\n\t\t\treturn lexicographically_less_than( lhs, rhs, cmp );\n\t\t};\n\t#if BOOST_VERSION >= 107000\n\t\tusing small_flat_set = boost::container::flat_set<point_t, decltype(pointCmp), boost::container::small_vector<point_t, 20, boost::container::new_allocator<point_t>>>;\n\t\tauto visited = small_flat_set(pointCmp);\n    #else\n\t\tauto visited = boost::container::flat_set<point_t, decltype( pointCmp )>( pointCmp );\n    #endif\n\t\tauto shouldVisit = [&]( const point_t& p )\n\t\t{\n\t\t\tauto it = visited.lower_bound( p );\n\t\t\tif( it != visited.end() && !( visited.key_comp()( p, *it ) ) )\n\t\t\t\treturn;\n\n\t\t\tvisited.insert( it, p );\n\t\t\tvisitor( p );\n\t\t};\n        auto get_point1 = [&](std::size_t i) { return access1::get_point(pgon1, i); };\n        auto get_point2 = [&](std::size_t i) { return access2::get_point(pgon2, i); };\n        auto advance = [](std::size_t& a, std::size_t& aa, std::size_t n) { ++aa; ++a %= n; };\n        auto a = std::size_t {};\n        auto b = std::size_t {};\n        auto aa = std::size_t {};\n        auto ba = std::size_t {};\n        auto inflag = unknown;\n\n        auto n = access1::size(pgon1);\n        auto n2 = n * 2;\n        auto m = access2::size(pgon2);\n        auto m2 = m * 2;\n\n        auto nVisited = 0;\n        do\n        {\n            auto a1 = (a + n - 1) % n;\n            auto b1 = (b + m - 1) % m;\n\n            vector_t A = get_point1(a) - get_point1(a1);\n            vector_t B = get_point2(b) - get_point2(b1);\n\n            auto ABOrientation = get_orientation(A, B, cmp);\n            auto aHB = get_orientation(get_point2(b1), get_point2(b), get_point1(a), cmp);\n            auto bHA = get_orientation(get_point1(a1), get_point1(a), get_point2(b), cmp);\n\n            point_t xpoints[2];\n            auto iType = segment_segment_intersection(get_point1(a1), get_point1(a), get_point2(b1), get_point2(b), xpoints, cmp);\n            if (iType == e_crossing || iType == e_endpoint)\n            {\n                shouldVisit(xpoints[0]);\n                ++nVisited;\n\n                if (inflag == unknown && nVisited == 1)\n                    aa = ba = 0;\n                if (aHB == oriented_left)\n                    inflag = pgon1_in;\n                else if (bHA == oriented_left)\n                    inflag = pgon2_in;\n            } \n            else if (iType == e_overlapping && dot_product(A, B) < area_t {})\n            {\n                //++nVisited;\n                shouldVisit(xpoints[0]);\n                shouldVisit(xpoints[1]);\n                return polygon_intersection_type::face;\n            }\n\n            if (ABOrientation == oriented_collinear && aHB == oriented_right && bHA == oriented_right)\n                return polygon_intersection_type::none;\n            else if (ABOrientation == oriented_collinear && aHB == oriented_collinear && bHA == oriented_collinear)\n            {\n                if (inflag == pgon1_in)\n                    advance(b, ba, m);\n                else\n                    advance(a, aa, n);\n            } \n            else if (ABOrientation != oriented_right)\n            {\n                if (bHA == oriented_left)\n                {\n                    if (inflag == pgon1_in)\n                    {\n                        ++nVisited;\n                        shouldVisit(get_point1(a));\n                    }\n                    advance(a, aa, n);\n                } \n                else\n                {\n                    if (inflag == pgon2_in)\n                    {\n                        ++nVisited;\n                        shouldVisit(get_point2(b));\n                    }\n                    advance(b, ba, m);\n                }\n            }\n            else\n            {\n                if (aHB == oriented_left)\n                {\n                    if (inflag == pgon2_in)\n                    {\n                        ++nVisited;\n                        shouldVisit(get_point2(b));\n                    }\n                    advance(b, ba, m);\n                }\n                else\n                {\n                    if (inflag == pgon1_in)\n                    {\n                        ++nVisited;\n                        shouldVisit(get_point1(a));\n                    }\n                    advance(a, aa, n);\n                }\n            }\n        } while((aa < n || ba < m) && aa < n2 && ba < m2);\n\n        if (inflag == unknown) \n        {\n            if (visited.size() == 1) {\n\t\t\t\treturn polygon_intersection_type::vertex;\n            }\n            //! Check if one vertex of either is inside.\n            if (point_in_polygon(get_point1(0), pgon2)) \n            {\n                for (auto i = 0ULL; i < m; ++i)\n                    shouldVisit(get_point1(i));\n                return polygon_intersection_type::overlapping;\n            }\n            if (point_in_polygon(get_point2(0), pgon1)) \n            {\n                for (auto i = 0ULL; i < m; ++i)\n                    shouldVisit(get_point2(i));\n                return polygon_intersection_type::overlapping;\n            }\n        }\n        \n        return nVisited == 0 ? polygon_intersection_type::none : polygon_intersection_type::overlapping;\n    }\n\n}//! namespace geometrix;\n\n#endif//! GEOMETRIX_CONVEX_POLYGON_POLYGON_INTERSECTION_HPP\n\n", "meta": {"hexsha": "36de18c3d3d477ca371974fcbf28c8e8e0176d4b", "size": 7640, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometrix/algorithm/intersection/convex_polygon_polygon_intersection.hpp", "max_stars_repo_name": "brandon-kohn/Geometrix", "max_stars_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometrix/algorithm/intersection/convex_polygon_polygon_intersection.hpp", "max_issues_repo_name": "brandon-kohn/Geometrix", "max_issues_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometrix/algorithm/intersection/convex_polygon_polygon_intersection.hpp", "max_forks_repo_name": "brandon-kohn/Geometrix", "max_forks_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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.7307692308, "max_line_length": 172, "alphanum_fraction": 0.5307591623, "num_tokens": 1748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5098701835671475}}
{"text": "#include \"segment.pb.h\"            // for ResizeArgs (generated file)\n#include \"scanner/api/kernel.h\"   // for VideoKernel and REGISTER_KERNEL\n#include \"scanner/api/op.h\"       // for REGISTER_OP\n#include \"scanner/util/memory.h\"  // for device-independent memory management\n#include \"scanner/util/opencv.h\"  // for using OpenCV\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/ximgproc.hpp>\n#include \"opencv2/highgui.hpp\"\n#include \"opencv2/core/utility.hpp\"\n\n#include <iostream>               // for std::cout\n\n#include <Eigen/Sparse>\ntypedef float var_t;\ntypedef Eigen::SparseMatrix<var_t> SpMat;\ntypedef Eigen::Triplet<var_t> T;\n\nvoid getPixelNeighbors(int height, int width, std::vector<std::vector<int>>& neighborId){\n\n    for(int i=0; i<height; i++){\n        for(int j=0; j<width; j++){\n\n            if(i == 0){\n                neighborId[i*width+j].push_back((i+1)*width+j);\n            }else if(i == height-1){\n                neighborId[i*width+j].push_back((i-1)*width+j);\n            }else{\n                neighborId[i*width+j].push_back((i+1)*width+j);\n                neighborId[i*width+j].push_back((i-1)*width+j);\n            }\n\n            if(j == 0){\n                neighborId[i*width+j].push_back(i*width+j+1);\n            }else if(j == width-1){\n                neighborId[i*width+j].push_back(i*width+j-1);\n            }else{\n                neighborId[i*width+j].push_back(i*width+j+1);\n                neighborId[i*width+j].push_back(i*width+j-1);\n            }\n\n        }\n    }\n\n}\n\n\nvoid getLabelPosition(var_t *img, int h, int w, std::map<int, std::vector<int>>& ht){\n    for(int i=0; i<h; i++) {\n        for (int j = 0; j < w; j++) {\n\n            if(img[i*w+j] >= 1.0){\n                int lbl = int(img[i*w+j]-1);\n                ht[lbl].push_back(i*w+j);\n            }\n\n        }\n    }\n}\n\n\nSpMat setU(int N, std::map<int, std::vector<int>>& ht, Eigen::VectorXf& y){\n    std::vector<T> tripletList;\n\n    for(std::map<int,std::vector<int>>::iterator it = ht.begin(); it != ht.end(); ++it) {\n        std::vector<int> pixLocation = it->second;\n        for(int i=0; i<pixLocation.size();i++){\n            tripletList.push_back(T(pixLocation[i], pixLocation[i], 1.));\n            y[pixLocation[i]] = float(it->first);\n        }\n    }\n\n    SpMat U(N,N);\n    U.setFromTriplets(tripletList.begin(), tripletList.end());\n    return U;\n}\n\nvoid setDW(var_t* image, var_t* edges, int h, int w, std::vector<SpMat>& out, float sigma1, float sigma2){\n\n    int N = h * w;\n    std::vector<std::vector<int>> neighborId(N);\n    getPixelNeighbors(h, w, neighborId);\n\n    std::vector<T> tripletListD;\n    std::vector<T> tripletListW;\n    int M = 0;\n\n    for(int i=0; i<neighborId.size(); i++){\n        int x, y;\n        y = i/w;\n        x = i%w;\n        var_t r1 = image[y*w*3+x*3+0];\n        var_t g1 = image[y*w*3+x*3+1];\n        var_t b1 = image[y*w*3+x*3+2];\n        var_t e1 = edges[y*w+x];\n\n        for(int j=0; j<neighborId[i].size(); j++){\n\n            y = neighborId[i][j]/w;\n            x = neighborId[i][j]%w;\n            var_t r2 = image[y*w*3+x*3+0];\n            var_t g2 = image[y*w*3+x*3+1];\n            var_t b2 = image[y*w*3+x*3+2];\n\n            var_t weight0 = exp(-((r1-r2)*(r1-r2) + (g1-g2)*(g1-g2)+ (b1-b2)*(b1-b2))/sigma1);\n            var_t weight1 = exp(-(e1*e1)/sigma2);\n\n            // std::cout<<weight0<<\" \"<<weight1<<std::endl;\n\n            tripletListD.push_back(T(M, i, 1.));\n            tripletListD.push_back(T(M, neighborId[i][j], -1.));\n            tripletListW.push_back(T(M, M, weight0*weight1));\n\n            M++;\n\n        }\n    }\n\n    SpMat D(M, N);\n    D.setFromTriplets(tripletListD.begin(), tripletListD.end());\n\n    SpMat W(M, M);\n    W.setFromTriplets(tripletListW.begin(), tripletListW.end());\n    out.push_back(D);\n    out.push_back(W);\n}\n\n\nvar_t* segmentFromPoses(var_t *img, var_t *edges, var_t *poseData, int height, int width, float sigma1, float sigma2){\n    std::map<int, std::vector<int>> ht;\n    getLabelPosition(poseData, height, width, ht);\n    Eigen::VectorXf y(height*width);\n    SpMat U = setU(height*width, ht, y);\n    std::vector<SpMat> DW;\n    setDW(img, edges, height, width, DW, sigma1, sigma2);\n    SpMat D = DW[0];\n    SpMat W = DW[1];\n\n    Eigen::VectorXf b = U*y;\n\n    SpMat A = U + D.transpose()*W*D;\n\n    Eigen::SimplicialCholesky <SpMat> solver(A);\n    Eigen::VectorXf x = solver.solve(b);\n\n    var_t *output = new var_t[height*width];\n    for(int i=0; i<height*width; i++)\n        output[i] = x[i];\n\n    return output;\n}\n\n\ncv::Ptr<cv::ximgproc::StructuredEdgeDetection> pDollar = cv::ximgproc::createStructuredEdgeDetection(\"/home/krematas/code/soccerontable/soccer3d/instancesegm/model.yml.gz\");\n\n/*\n * Ops in Scanner are abstract units of computation that are implemented by\n * kernels. Kernels are pinned to a specific device (CPU or GPU). Here, we\n * implement a custom op to resize an image. After reading this file, look\n * at CMakeLists.txt for how to build the op.\n */\n\n// Custom kernels must inherit the Kernel class or any subclass thereof,\n// e.g. the VideoKernel which provides support for processing video frames.\nclass MySegmentKernel : public scanner::Kernel, public scanner::VideoKernel {\n public:\n  // To allow ops to be customized by users at a runtime, e.g. to define the\n  // target width and height of the MyResizeKernel, Scanner uses Google's Protocol\n  // Buffers, or protobufs, to define serialzable types usable in C++ and\n  // Python (see resize_op/args.proto). By convention, ops that take\n  // arguments must define a protobuf called <OpName>Args, e.g. ResizeArgs,\n  // In Python, users will provide the argument fields to the op constructor,\n  // and these will get serialized into a string. This string is part of the\n  // general configuration each kernel receives from the runtime, config.args.\n  MySegmentKernel(const scanner::KernelConfig& config)\n      : scanner::Kernel(config) {\n    // The protobuf arguments must be decoded from the input string.\n    MySegmentArgs args;\n    args.ParseFromArray(config.args.data(), config.args.size());\n    width_ = args.w();\n    height_ = args.h();\n    sigma1 = args.sigma1();\n    sigma2 = args.sigma2();\n  }\n\n  // Execute is the core computation of the kernel. It maps a batch of rows\n  // from an input table to a batch of rows of the output table. Here, we map\n  // from one input column from the video, \"frame\", and return\n  // a single column, \"frame\".\n  void execute(const scanner::Elements& input_columns,\n               scanner::Elements& output_columns) override {\n    auto& frame_col = input_columns[0];\n    auto& mask_col = input_columns[1];\n\n    // This must be called at the top of the execute method in any VideoKernel.\n    // See the VideoKernel for the implementation check_frame_info.\n    check_frame(scanner::CPU_DEVICE, frame_col);\n    check_frame(scanner::CPU_DEVICE, mask_col);\n\n    auto& resized_frame_col = output_columns[0];\n    scanner::FrameInfo output_frame_info(height_, width_, 3, scanner::FrameType::U8);\n\n    const scanner::Frame* frame = frame_col.as_const_frame();\n    cv::Mat image = scanner::frame_to_mat(frame);\n\n    const scanner::Frame* mask = mask_col.as_const_frame();\n    cv::Mat poseImage = scanner::frame_to_mat(mask);\n\n    image.convertTo(image, cv::DataType<var_t>::type, 1.0/255.0);\n    var_t *imgData = (var_t*)(image.data);\n    std::cout<<image.channels()<<std::endl;\n\n\n    poseImage.convertTo(poseImage, cv::DataType<var_t>::type);\n    var_t *poseData = (var_t*)(poseImage.data);\n    std::cout<<poseImage.channels()<<std::endl;\n    //\n    cv::Mat img2;\n    image.copyTo(img2);\n    img2.convertTo(img2, cv::DataType<var_t>::type);\n    cv::Mat edges(img2.size(), img2.type());\n\n    pDollar->detectEdges(img2, edges);\n    std::cout<<edges.channels()<<std::endl;\n\n    std::cout<<\" -------------------------- \"<<std::endl<<std::endl;\n    int height = image.rows;\n    int width = image.cols;\n\n    var_t *edgesData = (var_t*)(edges.data);\n\n    var_t* segm_output = segmentFromPoses(imgData, edgesData, poseData, height, width, sigma1, sigma2);\n\n    // cv::Mat new_mask(height, width, cv::DataType<var_t>::type, segm_output);\n\n    //copy vector to mat\n    // std::cout<<edges.size()<<edges.type()<<std::endl;\n\n    cv::Mat new_mask(height, width, CV_8U);\n    for(int i=0; i<height; i++) {\n        for (int j = 0; j < width; j++) {\n          // std::cout<<segm_output[i*width+j]<<std::endl;\n            if(segm_output[i*width+j] > 1.5)\n                new_mask.at<uchar>(i,j) = 255;\n            else\n                new_mask.at<uchar>(i,j) = 0;\n        }\n    }\n\n\n    // new_mask.convertTo(new_mask, CV_8UC3, 255.0);\n    // cv::Mat output_img;\n    // edges.convertTo(output_img, cv::DataType<uint8>::type);\n    cv::cvtColor(new_mask, new_mask, cv::COLOR_GRAY2BGR);\n\n    // Allocate a frame for the resized output frame\n    scanner::Frame* resized_frame = scanner::new_frame(scanner::CPU_DEVICE, output_frame_info);\n    cv::Mat output = scanner::frame_to_mat(resized_frame);\n\n    cv::resize(new_mask, output, cv::Size(width_, height_));\n\n    scanner::insert_frame(resized_frame_col, resized_frame);\n  }\n\n private:\n  int width_;\n  int height_;\n  float sigma1;\n  float sigma2;\n};\n\n// These functions run statically when the shared library is loaded to tell the\n// Scanner runtime about your custom op.\n\nREGISTER_OP(MySegment).frame_input(\"frame\").frame_input(\"mask\").frame_output(\"frame\").protobuf_name(\"MySegmentArgs\");\n\nREGISTER_KERNEL(MySegment, MySegmentKernel)\n    .device(scanner::DeviceType::CPU)\n    .num_devices(1);\n", "meta": {"hexsha": "869dac8eea6361dbaab458cddbae5bdcb0850068", "size": 9509, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/apps/soccer/instance_segmentation/segment_op/segment_op.cpp", "max_stars_repo_name": "apoms/scanner", "max_stars_repo_head_hexsha": "106896fab29be429e428278d4fcefed1953a15c2", "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/apps/soccer/instance_segmentation/segment_op/segment_op.cpp", "max_issues_repo_name": "apoms/scanner", "max_issues_repo_head_hexsha": "106896fab29be429e428278d4fcefed1953a15c2", "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/apps/soccer/instance_segmentation/segment_op/segment_op.cpp", "max_forks_repo_name": "apoms/scanner", "max_forks_repo_head_hexsha": "106896fab29be429e428278d4fcefed1953a15c2", "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.9607142857, "max_line_length": 173, "alphanum_fraction": 0.6221474393, "num_tokens": 2620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.5098617224988975}}
{"text": "#include <array>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <unordered_map>\n\n#include <boost/range/irange.hpp>\n\nusing uint64 = std::uint64_t;\n\nstruct Arguments {\n\tstd::string strcmd;\n\tuint64 A, B;\n};\n\nauto& operator>>(std::istream& in, Arguments& args) {\n\treturn in >> args.strcmd >> args.A >> args.B;\n}\n\n// tmp_screen is unnecessary as we are not doing any\n// intermediate steps, thus we don't need to save any state\ntemplate<typename S, typename N>\nauto set_rectangle(S& screen, S&, N width, N height) {\n\n\tfor(const auto row : boost::irange(height)) {\n\n\t\tfor(const auto col : boost::irange(width)) {\n\n\t\t\tscreen[row][col] = true;\n\t\t}\n\t}\n}\n\ntemplate<typename S, typename N>\nauto shift_row(S& screen, S& tmp_screen, N row, N shift) {\n\n\ttmp_screen = screen;\n\n\t// on the temporary screen, the row is set to all-false\n\t// so that we can lay the original screen over it, and\n\t// based on the state of the original screen we can set\n\t// the columns on the temporary screen to true as if we\n\t// had shifted the row of the original screen\n\tfor(auto& col : tmp_screen[row]) {\n\t\tcol = false;\n\t}\n\n\tconst auto width = tmp_screen[row].size();\n\n\tfor(const auto col : boost::irange(width)) {\n\n\t\t// if the current column on the original screen is lit,\n\t\t// we can start doing the shifting and apply the result\n\t\t// to the corresponding column on the temporary screen\n\t\tif(screen[row][col]) {\n\n\t\t\tconst auto new_pos = ((col + shift) % width);\n\n\t\t\ttmp_screen[row][new_pos] = true;\n\t\t}\n\t}\n\n\tscreen = tmp_screen;\n}\n\n// works the same way as shift_row(), except the shift applies to columns instead of rows\ntemplate<typename S, typename N>\nauto shift_col(S& screen, S& tmp_screen, N col, N shift) {\n\n\ttmp_screen = screen;\n\n\tfor(auto& row : tmp_screen) {\n\t\trow[col] = false;\n\t};\n\n\tconst auto height = tmp_screen.size();\n\n\tfor(const auto row : boost::irange(height)) {\n\n\t\tif(screen[row][col]) {\n\n\t\t\tconst auto new_row = ((row + shift) % height);\n\n\t\t\ttmp_screen[new_row][col] = true;\n\t\t}\n\t}\n\n\tscreen = tmp_screen;\n}\n\ntemplate<typename S>\nauto print(const S& screen) {\n\n\tfor(const auto& row : screen) {\n\n\t\tfor(const auto col : row) {\n\t\t\tstd::cout << (col ? '#' : ' ');\n\t\t}\n\n\t\tstd::cout << \"\\n\";\n\t}\n\n\tstd::cout.flush();\n}\n\nint main() {\n\n\tconst auto filename = std::string{\"operations.txt\"};\n\tauto file = std::fstream{filename};\n\n\tif(file.is_open()) {\n\n\t\tconstexpr auto width = uint64{50};\n\t\tconstexpr auto height = uint64{6};\n\n\t\tusing Array2D = std::array<std::array<bool, width>, height>;\n\n\t\tauto screen = Array2D{};\n\t\tauto tmp_screen = screen;\n\n\t\tusing Command = void (*) (decltype(screen)&, decltype(tmp_screen)&, decltype(width), decltype(height));\n\n\t\tauto commands = std::unordered_map<std::string, Command>{\n\t\t\t{\"rect\", set_rectangle},\n\t\t\t{\"row\", shift_row},\n\t\t\t{\"col\", shift_col}\n\t\t};\n\n\t\tauto args = Arguments{};\n\n\t\twhile(file >> args) {\n\t\t\tcommands[args.strcmd](screen, tmp_screen, args.A, args.B);\n\t\t}\n\n\t\tprint(screen);\n\n\t} else {\n\t\tstd::cerr << \"Error! Could not open \\\"\" << filename << \"\\\"!\" << std::endl;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "51a11da53640fac57619359ad4ce9761372bf88c", "size": 3050, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 08 Part 2/main.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2016-cpp", "max_stars_repo_head_hexsha": "729bc5c2d7c054c98212b692ea45ae70ed35a24c", "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": "Day 08 Part 2/main.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2016-cpp", "max_issues_repo_head_hexsha": "729bc5c2d7c054c98212b692ea45ae70ed35a24c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 08 Part 2/main.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2016-cpp", "max_forks_repo_head_hexsha": "729bc5c2d7c054c98212b692ea45ae70ed35a24c", "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.1805555556, "max_line_length": 105, "alphanum_fraction": 0.6567213115, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5097910170474905}}
{"text": "/**\n * @file   tevol_source_gca.hpp\n * @brief  ODE system for group SIS with group selection mechanism for transmission rates\n *\n * Source code. All parameters passed as arguments, but specify and compile to change precision or output format.\n * g++ -std=c++11 -O3 -o tevol_source_gca ./tevol_source_gca.cpp $(gsl-config --cflags) $(gsl-config --libs)\n *\n * @author  LHD\n * @since   2021-02-06\n */\n\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <fstream>\n#include <sstream>\n\n#include <boost/multi_array.hpp>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_odeiv.h>\n\n#include \"dyn_gca.hpp\"\n\ndouble binomial(int n, int k, double p);\n\nusing namespace std;\n\nint main(int argc, const char *argv[]) {\n\t\t \n\t//Model parameters\t\n\tdouble beta = atof(argv[1]); //basic diffusion rate of innovation \n\tdouble gamma = atof(argv[2]); //recovery rate of innovation\n\tdouble rho = atof(argv[3]); //coupling between groups\n\tdouble b = atof(argv[4]); //collective benefit per adopter\n\tdouble c = atof(argv[5]); //cost per level of promotion\n\tdouble mu = atof(argv[6]); //mutation rate of adoption\n\tdouble epsilon = atof(argv[7]); //random initial condition\n\tint n = atoi(argv[8]); //group size\n\tint L = atoi(argv[9]); //number of levels\n    bool timeseries = atoi(argv[10]); //1 for time series, 0 for final state\n\n    if(argc<6) {cerr << \"Requires bunch of parameters: basic diffusion rate (beta),\\n recovery rate (gamma),\"\n                    << \"\\n group coupling (rho),\\n adaptation benefit (b),\\n promotion cost (c),\"\n                    << \"\\n initial adoption (epsilon),\\n group size (n),\\n number of levels (l_max), \\n 1 for time series, 0 for final state.\\n\" << endl; return 0;}\n\n    const int dim1 = L+1;\n    const int dim2 = n+1;\n    Sparam param = {beta, gamma, rho, b, c, mu, dim1, dim2};\n\n    // Integrator parameters\n    double t = 0;\n    double dt = 1e-4;\n    double t_step = 1.0;\n    const double eps_abs = 1e-8;\n    const double eps_rel = 1e-6;\n\n    // Setting initial conditions\n    typedef boost::multi_array<double,2> mat_type;\n    typedef mat_type::index index;\n    mat_type y(boost::extents[dim1][dim2]);\n    fill(y.data(),y.data()+y.num_elements(),0.0);\n\n    // Uniform initial conditions\n    double lastI = 0.0;\n    double lastIL = 0.0;\n\tfor(int l=0; l<dim1; ++l) {\n        for(int i=0; i<=n; ++i) {\n            y[l][i] = (1.0/(1.0*(L+1)))*binomial(n,i,epsilon); //C_n,i\n            lastI += 1.0*i*y[l][i];\n        }\n    }\n    double newI = 0.0;\n    double newIL = 0.0;\n    double newS = 1.0;\n\n    // Define GSL odeiv parameters\n    const gsl_odeiv_step_type * step_type = gsl_odeiv_step_rkf45;\n    gsl_odeiv_step * step = gsl_odeiv_step_alloc (step_type, dim1*dim2);\n    gsl_odeiv_control * control = gsl_odeiv_control_y_new (eps_abs,eps_rel);\n    gsl_odeiv_evolve * evolve = gsl_odeiv_evolve_alloc (dim1*dim2);\n    gsl_odeiv_system sys = {dydt, NULL, dim1*dim2, &param};\n\t\n\t//Integration\n    int status(GSL_SUCCESS);\n    double diff = 1.0;\n    double diffL = 1.0;\n    for (double t_target = t+t_step; t_target < 10000 || diff > 1e-10; t_target += t_step ) { //stop by time and difference\n        while (t < t_target) {\n            status = gsl_odeiv_evolve_apply (evolve,control,step,&sys,&t,t_target,&dt,y.data());\n            if (status != GSL_SUCCESS) {\n\t\t\t\tcout << \"SNAFU\" << endl;\n                break;\n\t\t\t}\n        } // end while\n\n        //measure adoption\n        vector<double> newIvec(dim1, 0.0); vector<double> popvec(dim1, 0.0); newI=0.0;\n        for(int l=0; l<dim1; ++l) for(int i=0; i<=n; ++i) {\n            newIvec[l] += 1.0*i*y[l][i]; popvec[l] += y[l][i]; newI += 1.0*i*y[l][i]; }\n        \n        //timeseries output\n        if(timeseries) {   \n          cout << t;\n\t\t  for(int l=0; l<dim1; ++l) cout << \" \" << newIvec[l]/popvec[l] << \" \" << popvec[l];\n          cout << \"\\n\";\n        }\n        diff = abs(newIvec[0]/popvec[0] - lastI);\n        diffL = abs(newIvec[dim1-1]/popvec[dim1-1] - lastIL);\n        lastI=newIvec[0]/popvec[0];\n        lastIL=newIvec[dim1-1]/popvec[dim1-1];\n\t} //end while\n\n    //calculate fitnesses\n    vector<double> Zvec_(dim1, 0.0); vector<double> popvec_(dim1, 0.0);\n    for(int l=0; l<dim1; ++l) {\n        for(int i=0; i<dim2; ++i) {\n            Zvec_[l] += exp(b*i-c*l)*y[l][i]; //should this really be proportional to C_i,l?\n            popvec_[l] += y[l][i];\n        }\n        Zvec_[l] /= popvec_[l];\n    }\n    double Z_ = accumulate(Zvec_.begin(), Zvec_.end(), 0.0);\n\n    //final state output\n    \n    if(!timeseries) {\n      vector<double> Ivec(dim1, 0.0); vector<double> pop(dim1, 0.0); newI=0.0;\n      for(int l=0; l<dim1; ++l) for(int i=0; i<=n; ++i) {\n        Ivec[l] += 1.0*i*y[l][i]; pop[l] += y[l][i]; newI += 1.0*i*y[l][i];\n      }\n      cout << beta << \" \" << b << \" \" << c << \" \" << rho;\n      for(int l=0; l<dim1; ++l) cout << \" \" << Ivec[l]/pop[l] << \" \" << pop[l];\n      for(int l=0; l<dim1; ++l) cout << \" \" << Zvec_[l]/Z_;\n      cout << \"\\n\";\n    }\n    \n\n    //output fitness distribution\n    /*for(int l=0; l<dim1; ++l) {\n        cout << beta << \" \" << b << \" \" << c << \" \" << rho << \" \" << l;\n        for(int i=0; i<dim2; ++i) {\n            int g = 0;\n            for(; g<int(1000*y[l][i]); ++g) cout << \" \" << exp(b*i-c*l);\n            for(; g<1000; ++g) cout << \" \" << \"nan\";\n        }\n        cout << \"\\n\";\n    }*/\n    \n\n    // localization in cliques\n    /*double xi = 0.0;\n    double It = 0.0;\n\tfor(int s=2; s<dim; ++s) for(int i=0; i<=s; ++i) It += 1.0*i*y[s][i];\n    for(int s=2; s<dim; ++s) {\n        double In = 0.0;\n        for(int i=0; i<=s; ++i) In += 1.0*i*y[s][i];\n        xi += (In/It)*(In/It);\n    }*/\n    \n    /*cout << beta << \" \" << lastI;\n    for(int n=dim-1; n>1; n-=10) {\n        lastI=0.0;\n        for(int i=0; i<=n; ++i) lastI += 1.0*norms*i*y[n][i]/(1.0*n*pow(1.0*n,-gammas));\n\t    cout << \" \" << lastI;\n    }\n    cout << \"\\n\";\n\t*/\n    cout.flush();\n\n    // Free memory\n    gsl_odeiv_evolve_free(evolve);\n    gsl_odeiv_control_free(control);\n    gsl_odeiv_step_free(step);\n    \n    return 0;\n}\n\ndouble binomial(int n, int k, double p)\n\t{\n\t//check\n\tif(k>n || k<0 || n<0) return 0.0;\n\t\t\n\tdouble result=0.L;\n\tdouble postfix = pow(p,k)*pow(1.L-p,n-k);\n\tif(n<2*k) k=n-k;\n\t\n\tif(k<=100&&n<=200)\n\t\t{\n\t\tdouble numerator=1;\n\t\tfor(int i=0; i<k; i++) numerator = numerator*((double)(n-i));\n\t\tdouble denominator=1;\n\t\tfor(int i=2; i<=k; i++) denominator = denominator*((double)i);\n\t\tresult = (double)(numerator/denominator)*postfix;\n\t\t}\n\telse\n\t\t{\n\t\tif(k<100||n<300)\n\t\t\t{\n\t\t\tresult=1.L;\n\t\t\tfor(int i=1; i<=k; i++) result = result*((double)(n-k+i))/((double)i);\n\t\t\tresult = result*postfix;\n\t\t\t}\n\t\telse if(n<1000)\n\t\t\t{\n\t\t\tdouble nd=(double)n, kd=(double)k, nkd=(double)(n-k);\n\t\t\tresult = nd*log(nd)-nd+0.5L*log(2.L*M_PI*nd)+1.L/(12.L*nd)-1.L/(360.L*pow(nd,3))+1.L/(1260.L*pow(nd,5));\n\t\t\tresult -= kd*log(kd)-kd + 0.5L*log(2.L*M_PI*kd) + 1.L/(12.L*kd) - 1.L/(360.L*pow(kd,3)) + 1.L/(1260.L*pow(kd,5));\n\t\t\tresult -= nkd*log(nkd)-nkd + 0.5L*log(2.L*M_PI*nkd) + 1.L/(12.L*nkd) - 1.L/(360.L*pow(nkd,3)) + 1.L/(1260.L*pow(nkd,5));\n\t\t\tresult = exp(result);\n\t\t\tresult = result*postfix;\n\t\t\t}\n\t\t\t\n\t\telse result = (1.L/sqrt(2.L*M_PI*(double)n*p*(1.L-p)))*exp(-pow(k-n*p,2)/(2.L*(double)n*p*(1.L-p)));\n\t\t}\n\tif(result!=result) result=0.L;\n\tif(isinf(result)) result=0.L;\n\treturn result;\n\t}\n", "meta": {"hexsha": "e7cee7083069e56ead5e217cce6138a425b6bfcb", "size": 7299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tevol_source_gca.cpp", "max_stars_repo_name": "LaurentHebert/group-cultural-adaptation", "max_stars_repo_head_hexsha": "806a7e3aea4d544e2d840ea517b8cbd19cd9e8bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tevol_source_gca.cpp", "max_issues_repo_name": "LaurentHebert/group-cultural-adaptation", "max_issues_repo_head_hexsha": "806a7e3aea4d544e2d840ea517b8cbd19cd9e8bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tevol_source_gca.cpp", "max_forks_repo_name": "LaurentHebert/group-cultural-adaptation", "max_forks_repo_head_hexsha": "806a7e3aea4d544e2d840ea517b8cbd19cd9e8bf", "max_forks_repo_licenses": ["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.1772727273, "max_line_length": 164, "alphanum_fraction": 0.556377586, "num_tokens": 2523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5097910143646376}}
{"text": "#include \"../include/streamcc_test.h\"\n#define BOOST_TEST_MODULE ClassTest\n#define BOOST_TEST_DYN_LINK\n\n#include <boost/test/unit_test.hpp>\n#include <random>\n#include <map>\n#include <iostream>\n\n\n\n\nstd::mt19937 gen;\n\n\nBOOST_AUTO_TEST_CASE(CountSketch_Test) {\n  Scc::CountSketch<int> cs(100, 20);\n  std::discrete_distribution<int> dist {100, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};\n  std::map<int, int> real; // to keep the actual frequencies\n\n  for (int i = 0; i < 100000; ++i) {\n    int p = dist(gen);\n    cs.processItem(p);\n    real[p] += 1;\n  }\n  \n  // now check the frequencies\n  for (int i = 0; i < 15 ; ++i) {\n    BOOST_CHECK(cs.estTotWeight(i) == real[i]);\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(CountMin_Test) {\n  Scc::CountMin<int> cm(100, 20);\n  std::discrete_distribution<int> dist {100, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};\n  std::map<int, int> real; // to keep the actual frequencies\n\n  for (int i = 0; i < 100000; ++i) {\n    int p = dist(gen);\n    cm.processItem(p);\n    real[p] += 1;\n  }\n  \n  // now check the frequencies\n  for (int i = 0; i < 15 ; ++i) {\n    BOOST_CHECK(cm.estTotWeight(i) == real[i]);\n  }\n}\n\n\n\nBOOST_AUTO_TEST_CASE(DistinctCounter_Test) {\n  Scc::DistinctCounter<int> f0(100);\n  for (int i = 0; i < 10000; ++i) {\n    for (int j = 0; j < 10; ++j)\n      f0.processItem(i);\n  }\n  int estF0 = f0.getEstDistinct();\n  BOOST_CHECK(estF0 < 10000 * 1.1);\n  BOOST_CHECK(estF0 > 10000 * 0.9);  \n}\n\n\nBOOST_AUTO_TEST_CASE(F2_Test) {\n  std::discrete_distribution<int> dist {100, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};\n  std::map<int, double> real; // to keep the actual frequencies\n\n  Scc::F2<int> f2(50);\n  for (int i = 0; i < 10000; ++i) {\n    int item = dist(gen);\n    double weight = utils::rand_double();\n    f2.processItem(item, weight);\n    real[item] += weight;\n  }\n\n  // calc the actual F2\n  double r = 0.;\n  for (auto p: real) {\n    r += p.second * p.second;\n  }\n  \n  auto est = f2.getEstF2();\n  BOOST_CHECK(est < 1.1 * r);\n  BOOST_CHECK(est > 0.9 * r);\n    \n}\n\nBOOST_AUTO_TEST_CASE(Zeros_Test) {\n  BOOST_CHECK(utils::zeros(1 << 30) == 1);\n  BOOST_CHECK(utils::zeros(1 << 10) == 21);\n  BOOST_CHECK(utils::zeros(101 << 29) == 0);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "65fdb2b4de2a9ae793e0b56620d40847ae9721d9", "size": 2179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/tests.cpp", "max_stars_repo_name": "jiecchen/StreamingCC", "max_stars_repo_head_hexsha": "34547a16239735771341a5bb202204b71c6d1fa2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-10-24T12:35:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T04:46:40.000Z", "max_issues_repo_path": "tests/tests.cpp", "max_issues_repo_name": "jiecchen/StreamingCC", "max_issues_repo_head_hexsha": "34547a16239735771341a5bb202204b71c6d1fa2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-18T13:46:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T13:46:35.000Z", "max_forks_repo_path": "tests/tests.cpp", "max_forks_repo_name": "jiecchen/StreamingCC", "max_forks_repo_head_hexsha": "34547a16239735771341a5bb202204b71c6d1fa2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-06-25T03:56:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-07T08:49:14.000Z", "avg_line_length": 19.4553571429, "max_line_length": 87, "alphanum_fraction": 0.5938503901, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5097910130575892}}
{"text": "#define BOOST_TEST_MODULE  physical_calc_Driver\n\n#include <physical/calc/Driver.h>\n#include <physical/calc/symbol.h>\n\n#include <boost/test/unit_test.hpp>\n\n#include <complex>\n#include <iostream>\n\nnamespace {\n  using runtime::physical::Quantity;\n  using runtime::physical::calc::Driver;\n  using runtime::physical::calc::symbol;\n\n  void prepareCalculator() {\n    /* prepare infix units calculator. */\n    Driver & calc = Driver::instance();\n  \n    /* clear the old symbols out */\n    calc.symbols.clear();\n    calc.addMathLib();\n    calc.addPhysicalUnits();\n\n    calc.exec(\"from physical::constant import *\");\n    calc.exec(\"from physical::unit import *\");\n    calc.exec(\"from physical import 'unit::pi'\");\n    calc.exec(\"from physical import 'element::.*'\");\n  }\n\n  void cleanCalculator() {\n    /* prepare infix units calculator. */\n    Driver & calc = Driver::instance();\n  \n    /* clear the old symbols out */\n    calc.symbols.clear();\n  }\n\n}\n\n\nBOOST_AUTO_TEST_SUITE( CalculatorDriver );//{\n\n  BOOST_AUTO_TEST_CASE( simple_parse ) {\n    prepareCalculator();\n\n    BOOST_CHECK_CLOSE(\n      Driver::instance().eval( \"pi*(0.417*nm)^2\").getCoeff<double>(),\n      5.4628840494007563e-19,\n      1e-10\n    );\n\n    cleanCalculator();\n  }\n\n  BOOST_AUTO_TEST_CASE( assignment ) {\n    Driver & calc = Driver::instance();\n    calc.symbols.clear();\n\n    double v0 = calc.eval( \"v0 = v1 = 10\" ).getCoeff<double>();\n    symbol::table::const_iterator it = calc.symbols.find(\"v0\");\n    if ( it == calc.symbols.end() )\n      BOOST_FAIL(\"symbol 'v0' was not assigned!\");\n    else\n      BOOST_CHECK_EQUAL( it->second.evaluate().getCoeff<double>(), v0);\n\n    it = calc.symbols.find(\"v1\");\n    if ( it == calc.symbols.end() )\n      BOOST_FAIL(\"symbol 'v1' was not assigned!\");\n    else\n      BOOST_CHECK_EQUAL( it->second.evaluate().getCoeff<double>(), v0);\n\n    calc.symbols.clear();\n  }\n\n  BOOST_AUTO_TEST_CASE( expressions ) {\n    Driver & calc = Driver::instance();\n    calc.symbols.clear();\n\n    BOOST_CHECK_CLOSE( calc.eval( \"1 + 1\" ).getCoeff<double>(), 2., 1e-10 );\n    BOOST_CHECK_CLOSE( calc.eval( \"1 - 1\" ).getCoeff<double>(), 0., 1e-10 );\n    BOOST_CHECK_CLOSE( calc.eval( \"1 + 1 - 1\" ).getCoeff<double>(), 1., 1e-10 );\n    BOOST_CHECK_CLOSE( calc.eval( \"1 - 1 + 1\" ).getCoeff<double>(), 1., 1e-10 );\n    BOOST_CHECK_CLOSE( calc.eval( \"1 - 2 + 1 + 1\" ).getCoeff<double>(), 1., 1e-10 );\n    BOOST_CHECK_CLOSE( calc.eval( \"2*3 + 2^3\" ).getCoeff<double>(), 14., 1e-10 );\n    BOOST_CHECK_CLOSE( calc.eval( \"9/3 + 5 % 2\" ).getCoeff<double>(), 4., 1e-10 );\n    BOOST_CHECK_CLOSE( calc.eval( \"-3 + 2^-1 + 2*3\" ).getCoeff<double>(), 3.5, 1e-10 );\n    BOOST_CHECK_CLOSE( calc.eval( \"2^3^2\" ).getCoeff<double>(), 512., 1e-10 );\n    BOOST_CHECK_CLOSE( calc.eval( \"+3 + 2^-1 + 2*3\" ).getCoeff<double>(), 9.5, 1e-10);\n    BOOST_CHECK_CLOSE( calc.eval( \"1 - (1 + 1)\" ).getCoeff<double>(), -1., 1e-10 );\n    BOOST_CHECK_CLOSE( calc.eval( \"(1 - 3)*2 + 1\" ).getCoeff<double>(), -3., 1e-10 );\n\n  }\n\n\nBOOST_AUTO_TEST_SUITE_END();//}\n\n", "meta": {"hexsha": "91be6bad87bd13b9fb1c5570691163af09d352ea", "size": 3004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cxx/physical/calc/test/Driver.cpp", "max_stars_repo_name": "afrl-quantum/physical", "max_stars_repo_head_hexsha": "71de3f7895b9bc1a1e9969701ad6980c5676b294", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-01T21:21:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-01T21:21:54.000Z", "max_issues_repo_path": "cxx/physical/calc/test/Driver.cpp", "max_issues_repo_name": "afrl-quantum/physical", "max_issues_repo_head_hexsha": "71de3f7895b9bc1a1e9969701ad6980c5676b294", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cxx/physical/calc/test/Driver.cpp", "max_forks_repo_name": "afrl-quantum/physical", "max_forks_repo_head_hexsha": "71de3f7895b9bc1a1e9969701ad6980c5676b294", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-03-21T15:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-26T09:29:37.000Z", "avg_line_length": 30.6530612245, "max_line_length": 87, "alphanum_fraction": 0.6235019973, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5097910090676873}}
{"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_FNMS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FNMS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-arithmetic\n    This function object computes the negated (fused) multiply substract of\n    its three parameters.\n\n\n    @par Header <boost/simd/function/fnms.hpp>\n\n    @par Notes\n    The call `fnms(x, y, z)` is similar to `-x*y+z`\n\n    But really conformant fused multiply/add also implies\n\n    - only one rounding\n\n    - no \"intermediate\" overflow\n\n    fnms provides this for all integral types and also each time it is reasonable\n    in terms of performance for floating ones (i.e. if the system has the hard\n    wired capability).\n\n    If you need pedantic fnms capabilities in all circumstances in your own\n    code you can use the pedantic_ decorator (can be very expensive).\n\n    @par Decorators\n    - pedantic_ ensures the fnms properties and allows SIMD acceleration if available.\n\n    @see fms, fma, fnma\n\n    @par Example:\n\n      @snippet fnms.cpp fnms\n\n    @par Possible output:\n\n      @snippet fnms.txt fnms\n\n  **/\n  Value fnms(Value const& x, Value const& y, Value const& z);\n} }\n#endif\n\n#include <boost/simd/function/scalar/fnms.hpp>\n#include <boost/simd/function/simd/fnms.hpp>\n\n#endif\n", "meta": {"hexsha": "3571138fe855a54581dd3285be5350cbc70a3e1f", "size": 1675, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/fnms.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/function/fnms.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/function/fnms.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": 25.7692307692, "max_line_length": 100, "alphanum_fraction": 0.6298507463, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5097910077606389}}
{"text": "/* This file is part of the Tomographer project, which is distributed under the\n * terms of the MIT license.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 ETH Zurich, Institute for Theoretical Physics, Philippe Faist\n * Copyright (c) 2017 Caltech, Institute for Quantum Information and Matter, Philippe Faist\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include <cmath>\n\n#include <string>\n#include <sstream>\n#include <random>\n\n#include <boost/math/constants/constants.hpp>\n\n// include before <Eigen/*> !\n#include \"test_tomographer.h\"\n\n#include <tomographer/densedm/distmeasures.h>\n#include <tomographer/densedm/dmtypes.h>\n\n\n\n\n// -----------------------------------------------------------------------------\n// fixture(s)\n\n#include \"test_densedm_distmeasures_common.h\"\n\n\n// -----------------------------------------------------------------------------\n// test suites\n\n\nBOOST_AUTO_TEST_SUITE(test_densedm_distmeasures)\n\nBOOST_FIXTURE_TEST_SUITE(qubit_d, distmeasures_qubit_fixture<double>)\n\nBOOST_AUTO_TEST_CASE(internal_test_fixture)\n{\n  internal_test_fixture();\n}\n\nBOOST_AUTO_TEST_CASE(traceDistance)\n{\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho1), trdist_with_1(1), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho2), trdist_with_1(2), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho3), trdist_with_1(3), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho4), trdist_with_1(4), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho5), trdist_with_1(5), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho6), trdist_with_1(6), tol);\n}\n\nBOOST_AUTO_TEST_CASE(fidelity)\n{\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho1), fid_with_1(1), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho2), fid_with_1(2), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho3), fid_with_1(3), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho4), fid_with_1(4), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho5), fid_with_1(5), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho6), fid_with_1(6), tol);\n}\n\nBOOST_AUTO_TEST_CASE(fidelityT)\n{\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T1), fid_with_1(1), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T2), fid_with_1(2), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T2b), fid_with_1(2), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T3), fid_with_1(3), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T4), fid_with_1(4), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T5), fid_with_1(5), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T6), fid_with_1(6), tol);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n// -----------------------------------------------\n\nBOOST_FIXTURE_TEST_SUITE(qubit_f, distmeasures_qubit_fixture<float>)\n\nBOOST_AUTO_TEST_CASE(internal_test_fixture)\n{\n  internal_test_fixture();\n}\n\nBOOST_AUTO_TEST_CASE(traceDistance)\n{\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho1), trdist_with_1(1), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho2), trdist_with_1(2), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho3), trdist_with_1(3), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho4), trdist_with_1(4), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho5), trdist_with_1(5), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho6), trdist_with_1(6), tol_f);\n}\n\nBOOST_AUTO_TEST_CASE(fidelity)\n{\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho1), fid_with_1(1), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho2), fid_with_1(2), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho3), fid_with_1(3), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho4), fid_with_1(4), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho5), fid_with_1(5), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho6), fid_with_1(6), tol_f);\n}\n\nBOOST_AUTO_TEST_CASE(fidelityT)\n{\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T1), fid_with_1(1), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T2), fid_with_1(2), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T2b), fid_with_1(2), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T3), fid_with_1(3), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T4), fid_with_1(4), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T5), fid_with_1(5), tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T6), fid_with_1(6), tol_f);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n// -----------------------------------------------\n\nBOOST_FIXTURE_TEST_SUITE(qudit4_d, distmeasures_qudit4_fixture<double>)\n\nBOOST_AUTO_TEST_CASE(traceDistance)\n{\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho1), trdist_with_1(1), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho2), trdist_with_1(2), tol);\n}\nBOOST_AUTO_TEST_CASE(fidelity)\n{\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho1), fid_with_1(1), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho2), fid_with_1(2), tol);\n}\nBOOST_AUTO_TEST_CASE(fidelityT)\n{\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T1), fid_with_1(1), tol);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T2), fid_with_1(2), tol);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_FIXTURE_TEST_SUITE(qudit4_f, distmeasures_qudit4_fixture<float>)\n\nBOOST_AUTO_TEST_CASE(traceDistance)\n{\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho1), trdist_with_1(1), 32*tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::traceDistance<RealScalar>(rho1, rho2), trdist_with_1(2), 32*tol_f);\n}\nBOOST_AUTO_TEST_CASE(fidelity)\n{\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho1), fid_with_1(1), 32*tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelity<RealScalar>(rho1, rho2), fid_with_1(2), 32*tol_f);\n}\nBOOST_AUTO_TEST_CASE(fidelityT)\n{\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T1), fid_with_1(1), 32*tol_f);\n  MY_BOOST_CHECK_FLOATS_EQUAL(Tomographer::DenseDM::fidelityT<RealScalar>(T1, T2), fid_with_1(2), 32*tol_f);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f55efc2da164ddb90507913451bb7bb45b096923", "size": 8593, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/test_densedm_distmeasures.cxx", "max_stars_repo_name": "Tomographer/tomographer", "max_stars_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T02:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T02:26:00.000Z", "max_issues_repo_path": "test/test_densedm_distmeasures.cxx", "max_issues_repo_name": "Tomographer/tomographer", "max_issues_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-12T15:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-21T15:14:59.000Z", "max_forks_repo_path": "test/test_densedm_distmeasures.cxx", "max_forks_repo_name": "Tomographer/tomographer", "max_forks_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-10-12T15:32:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-08T11:39:49.000Z", "avg_line_length": 47.2142857143, "max_line_length": 119, "alphanum_fraction": 0.7705108809, "num_tokens": 2532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5097910024636887}}
{"text": "/* Copyright (c) 2018, Skolkovo Institute of Science and Technology (Skoltech)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\n * optimizer.cpp\n *\n *  Created on: Jul 8, 2020\n *      Author: Gonzalo Ferrer\n *              g.ferrer@skoltech.ru\n *              Mobile Robotics Lab, Skoltech\n */\n\n#include \"mrob/optimizer.hpp\"\n#include <Eigen/LU> // for inverse and determinant\n#include <iostream>\n\nusing namespace mrob;\n\nOptimizer::Optimizer(matData_t solutionTolerance, matData_t lambda) :\n        solutionTolerance_(solutionTolerance), max_iters_(1e2), lambda_(lambda)\n{\n\n}\n\nOptimizer::~Optimizer()\n{\n\n}\n\n\n uint_t Optimizer::solve(optimMethod method, uint_t max_iters, double lambda)\n{\n    optimization_method_ = method;\n    max_iters_ = max_iters;\n    switch(method)\n    {\n      case NEWTON_RAPHSON:\n          return optimize_newton_raphson();\n      case LEVENBERG_MARQUARDT_SPHER:\n      case LEVENBERG_MARQUARDT_ELLIP:\n          lambda_ = lambda;\n          return optimize_levenberg_marquardt();\n    }\n    return 0;\n}\n\n\nuint_t OptimizerDense::optimize_newton_raphson_one_iteration(bool useLambda)\n{\n    // 1) build problem: Gradient and Hessian and re-evaluates\n    calculate_gradient_hessian();\n    if (useLambda)\n    {\n        if (optimization_method_ == LEVENBERG_MARQUARDT_SPHER)\n        {\n            for (Eigen::Index i = 0; i < hessian_.diagonalSize() ; ++i)\n                hessian_(i,i) += lambda_;\n        }\n        if (optimization_method_ == LEVENBERG_MARQUARDT_ELLIP)\n        {\n            for (Eigen::Index i = 0; i < hessian_.diagonalSize() ; ++i)\n                hessian_(i,i) *= 1.0 + lambda_;\n        }\n    }\n\n    // 2) dx = - h^-1 * grad XXX test for singularities?\n    dx_ = - hessian_.inverse() * gradient_;\n    // 3) update the solution\n    this->update_state();\n\n    return 1;\n}\n\nuint_t Optimizer::optimize_newton_raphson()\n{\n    uint_t iters = 0;\n    // Calculate error also estimates planes, which are necessary for gradients. XXX this can cause bugs on the first iteration\n    matData_t previous_error = this->calculate_error(), diff_error;\n    do\n    {\n        this->optimize_newton_raphson_one_iteration(false);\n        matData_t current_error = this->calculate_error();\n        //std::cout << \"iter \" << iters << \", error = \" << current_error <<std::endl;\n        diff_error = previous_error - current_error;\n        previous_error = current_error;\n        iters++;\n    }while(fabs(diff_error) > solutionTolerance_ && iters < max_iters_);\n\n\n    return iters;\n}\n\nuint_t Optimizer::optimize_levenberg_marquardt()\n{\n    // LM trust region as described in Bertsekas (p.105)\n    // sigma reference to the fidelity of the model at the proposed solution \\in [0,1]\n    matData_t sigma1(0.25), sigma2(0.8);// 0 < sigma1 < sigma2 < 1\n    matData_t beta1(2.0), beta2(0.25); // lambda updates multiplier values, beta1 > 1 > beta2 >0\n    uint_t iters = 0;\n    matData_t previous_error = calculate_error();\n    bool improvement; // variable for controlling when no update is done and number of iterations is exceeded.\n    do\n    {\n        iters++;\n        // 1) solve the current subproblem by Newton Raphson\n        this->bookkeep_state();\n        optimize_newton_raphson_one_iteration(true);\n        auto current_error = calculate_error();\n        //std::cout << \"iter \" << iters << \", error = \" << current_error << \", lambda = \"<< lambda_ << std::endl;\n        auto diff_error = previous_error - current_error;\n        improvement = true;\n\n        // 2) Check for convergence, hillclimb\n        if (diff_error < 0)\n        {\n            //std::cout << \"no improvement\\n\";\n            lambda_ *= beta1;\n            this->update_state_from_bookkeep();\n            improvement = false;\n            continue;\n        }\n        previous_error = current_error;\n\n        // 2.1) check for convergence, terminal\n        if (diff_error < solutionTolerance_)\n            return iters;\n\n        // 3 Fidelity of the quadratized model vs non-linear error evaluation.\n        // f = err(x_k) - err(x_k + dx)  ( >0 if upgrade)\n        //     err(x_k) - m_k(dx)\n        // where m_k is the quadratized model m_k(dx) = err(x_k) + dx'*Grad r + 0.5 dx'(Hessian + LM)dx\n        // => f = d err / (-dx'*Grad r - 0.5 dx'(Hessian + LM)dx)\n        //matData_t modelFidelity = diff_error / (-dx_.dot(gradient_) - 0.5*dx_.dot(hessian_* dx_));\n        matData_t modelFidelity = calculate_model_fidelity(diff_error);\n\n\n        // 4) update lambda\n        if (modelFidelity < sigma1)\n            lambda_ *= beta1;\n        if (modelFidelity > sigma2)\n            lambda_ *= beta2;\n\n    }while(iters < max_iters_);\n\n    if (!improvement)\n    {\n        this->update_state_from_bookkeep();//If no improvement shown, undo again\n    }\n\n\n    // output\n    std::cout << \"Optimizer::optimize_levenberg_marquardt: failed to converge after \"\n              << iters << \" iterations and error \" << calculate_error()\n              << std::endl;\n\n    return iters;\n}\n\nOptimizerDense::OptimizerDense(matData_t solutionTolerance, matData_t lambda):\n        Optimizer(solutionTolerance, lambda)\n{\n\n}\nOptimizerDense::~OptimizerDense()\n{\n\n}\n\nmatData_t OptimizerDense::calculate_model_fidelity(matData_t diff_error)\n{\n\n    return diff_error / (-dx_.dot(gradient_) - 0.5*dx_.dot(hessian_* dx_));\n}\n", "meta": {"hexsha": "8e681289503939e811b4e40ec5e095f02c7f42c3", "size": 5784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common/optimizer.cpp", "max_stars_repo_name": "miloserdova-l/mrob", "max_stars_repo_head_hexsha": "48bef772ba3158d2122991069196d6efd4a39f8c", "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/common/optimizer.cpp", "max_issues_repo_name": "MobileRoboticsSkoltech/mrob", "max_issues_repo_head_hexsha": "7668a3ee35345c4878aa86fff082cc017992d205", "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/common/optimizer.cpp", "max_forks_repo_name": "MobileRoboticsSkoltech/mrob", "max_forks_repo_head_hexsha": "7668a3ee35345c4878aa86fff082cc017992d205", "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": 31.2648648649, "max_line_length": 127, "alphanum_fraction": 0.640560166, "num_tokens": 1502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5097910024636887}}
{"text": "\n#include \"Frustum.hpp\"\n#include <Engine/ShaderManager.hpp>\n#include <boost/filesystem.hpp>\n#include <iostream>\n#include <Engine/Camera.hpp>\n#include <Engine/MainGraphic.hpp>\n#include <NTL.hpp>\n\nFrustum::Frustum(Camera &camera) :\ncamera_(camera) {\n    setDebug();\n}\n\nvoid Frustum::update()\n{\n    glm::mat4 mat = camera_.getProjectionMatrix() * camera_.getViewMatrix();\n\n    for (int i = 4; i--; )\n        planes_[FRUSTUM_PLANE_LEFT][i] = mat[i][3] + mat[i][0];\n    for (int i = 4; i--; )\n        planes_[FRUSTUM_PLANE_RIGHT][i] = mat[i][3] - mat[i][0];\n    for (int i = 4; i--; )\n        planes_[FRUSTUM_PLANE_DOWN][i] = mat[i][3] + mat[i][1];\n    for (int i = 4; i--; )\n        planes_[FRUSTUM_PLANE_UP][i] = mat[i][3] - mat[i][1];\n    for (int i = 4; i--; )\n        planes_[FRUSTUM_PLANE_NEAR][i] = mat[i][3] + mat[i][2];\n    for (int i = 4; i--; )\n        planes_[FRUSTUM_PLANE_FAR][i] = mat[i][3] - mat[i][2];\n\n    updateLines();\n}\n\nbool\t\tFrustum::pointIn(float x, float y, float z) {\n    for(auto plane : planes_) {\n        if (glm::dot(plane, glm::vec4(x, y, z, 1.0f)) < 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid Frustum::initDebug() {\n}\n\nvoid Frustum::updateLines() {\n\tfloat ar = 1024.f / 720.f;\n\tfloat halfHeight = tanf((3.1415926f / 180.f) * (camera_.fov_ / 2.f));\n\tfloat halfWidth = halfHeight * ar;\n\n\tfloat xn = halfWidth * camera_.near_;\n\tfloat xf = halfWidth * camera_.far_;\n\tfloat yn = halfHeight * camera_.near_;\n\tfloat yf = halfHeight * camera_.far_;\n\n/*\n    glm::mat4 inverse = glm::inverse(view);\n\n    glm::vec4 f[8u] =\n            {\n                    // near face\n                    {xn, yn, -camera_.near_, 1.f},\n                    {-xn, yn, -camera_.near_, 1.f},\n                    {xn, -yn, -camera_.near_, 1.f},\n                    {-xn, -yn, -camera_.near_ , 1.f},\n\n                    // far face\n                    {xf, yf, -camera_.far_, 1.f},\n                    {-xf, yf, -camera_.far_ , 1.f},\n                    {xf, -yf, -camera_.far_ , 1.f},\n                    {-xf, -yf, -camera_.far_, 1.f},\n            };\n\n    glm::vec3 v[8];\n    for (int i = 0; i < 8; i++)\n    {\n        glm::vec4 ff = inverse * f[i];\n        v[i].x = ff.x / ff.w;\n        v[i].y = ff.y / ff.w;\n        v[i].z = ff.z / ff.w;\n    }\n\n    glm::vec3 lines[] = {\n            v[0], v[1],\n            v[0], v[2],\n            v[3], v[1],\n            v[3], v[2],\n            v[4], v[5],\n            v[4], v[6],\n            v[7], v[5],\n            v[7], v[6],\n            v[0], v[4],\n            v[1], v[5],\n            v[3], v[7],\n            v[2], v[6]\n    };\n*/\n\n\t/// Converstion du Clip Space en World Space\n\t/// ClipSpace   - > View Space  = ClipSpace   *  INV(Projection Matrix)\n\t/// View Space  - > World Space = View Space  *  INV(View Matrix)\n\t///\n\tglm::mat4 inv = glm::inverse(camera_.getViewMatrix()) * glm::inverse(camera_.getProjectionMatrix());\n\tglm::vec4 ndc[8] =\n\t\t\t{\n\t\t\t\t\t// near face\n\t\t\t\t\t{ 1, 1, -1, 1.f },\n\t\t\t\t\t{ -1, 1, -1, 1.f },\n\t\t\t\t\t{ 1, -1, -1, 1.f },\n\t\t\t\t\t{ -1, -1, -1, 1.f },\n\n\t\t\t\t\t// far face\n\t\t\t\t\t{ 1, 1, 1, 1.f},\n\t\t\t\t\t{ -1, 1, 1, 1.f},\n\t\t\t\t\t{ 1, -1, 1, 1.f},\n\t\t\t\t\t{ -1, -1, 1, 1.f},\n\t\t\t};\n\n\tglm::vec3 v[8];\n\tfor (int i = 0; i < 8; i++)\n\t{\n\t\tglm::vec4 wc = inv * ndc[i];\n\n\t\t///Homogenous to cartesian conversion\n\t\tv[i].x = wc.x / wc.w;\n\t\tv[i].y = wc.y / wc.w;\n\t\tv[i].z = wc.z / wc.w;\n\t}\n\n    linesObject_.clear();\n    linesObject_.reserve(24);\n\tlinesObject_.emplace_back(v[0], color);\n\tlinesObject_.emplace_back(v[1], color);\n\tlinesObject_.emplace_back(v[0], color);\n\tlinesObject_.emplace_back(v[2], color);\n\tlinesObject_.emplace_back(v[3], color);\n\tlinesObject_.emplace_back(v[1], color);\n\tlinesObject_.emplace_back(v[3], color);\n\tlinesObject_.emplace_back(v[2], color);\n\tlinesObject_.emplace_back(v[4], color);\n\tlinesObject_.emplace_back(v[5], color);\n\tlinesObject_.emplace_back(v[4], color);\n\tlinesObject_.emplace_back(v[6], color);\n\tlinesObject_.emplace_back(v[7], color);\n\tlinesObject_.emplace_back(v[5], color);\n\tlinesObject_.emplace_back(v[7], color);\n\tlinesObject_.emplace_back(v[6], color);\n\tlinesObject_.emplace_back(v[0], color);\n\tlinesObject_.emplace_back(v[4], color);\n\tlinesObject_.emplace_back(v[1], color);\n\tlinesObject_.emplace_back(v[5], color);\n\tlinesObject_.emplace_back(v[3], color);\n\tlinesObject_.emplace_back(v[7], color);\n\tlinesObject_.emplace_back(v[2], color);\n\tlinesObject_.emplace_back(v[6], color);\n\n\n    updateDebug();\n}\n\n\n", "meta": {"hexsha": "b80c3f88561287ba06ec44239bdaaa6fe2af3550", "size": 4412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Engine/Frustum.cpp", "max_stars_repo_name": "Jino42/stf", "max_stars_repo_head_hexsha": "f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db", "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/Engine/Frustum.cpp", "max_issues_repo_name": "Jino42/stf", "max_issues_repo_head_hexsha": "f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db", "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/Engine/Frustum.cpp", "max_forks_repo_name": "Jino42/stf", "max_forks_repo_head_hexsha": "f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db", "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.0674846626, "max_line_length": 101, "alphanum_fraction": 0.5346781505, "num_tokens": 1458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5097910024636887}}
{"text": "#include <shark/Algorithms/Trainers/LinearRegression.h>\n#include <shark/Models/LinearModel.h>\n#include <boost/archive/polymorphic_binary_iarchive.hpp>\n#include <boost/archive/polymorphic_binary_oarchive.hpp>\nusing namespace shark;\n\ndouble func(double x) {\n  return 4. + 0.3 * x;  // line coeficients\n}\n\nstd::pair<Data<RealVector>, Data<RealVector>> GenerateData(size_t n) {\n  std::vector<RealVector> x_data(n);\n  std::vector<RealVector> y_data(n);\n\n  std::random_device rd;\n  std::mt19937 re(rd());\n  std::uniform_real_distribution<double> dist(-1.5, 1.5);\n\n  // generate data\n  RealVector x_v(1);  // it's a typdef to remora::vector<float>\n  RealVector y_v(1);\n  for (size_t i = 0; i < n; ++i) {\n    x_v(0) = i;\n    x_data[i] = x_v;\n\n    y_v(0) = func(i) + dist(re);  // add noise\n    y_data[i] = y_v;\n  }\n\n  return {createDataFromRange(x_data), createDataFromRange(y_data)};\n}\n\nint main() {\n  {\n    Data<RealVector> x;\n    Data<RealVector> y;\n    std::tie(x, y) = GenerateData(1000);\n    RegressionDataset data(x, y);\n    LinearModel<> model;\n    LinearRegression trainer;\n    trainer.train(model, data);\n\n    std::ofstream ofs(\"shark-linear.dat\");\n    // boost::archive::polymorphic_text_oarchive oa(ofs);\n    boost::archive::polymorphic_binary_oarchive oa(ofs);\n    model.write(oa);\n  }\n\n  std::ifstream ifs(\"shark-linear.dat\");\n  // boost::archive::polymorphic_text_iarchive ia(ifs);\n  boost::archive::polymorphic_binary_iarchive ia(ifs);\n  LinearModel<> model;\n  model.read(ia);\n\n  std::cout << \"Target values: \\n\";\n  std::vector<RealVector> new_x_data;\n  for (size_t i = 0; i < 5; ++i) {\n    new_x_data.push_back({static_cast<double>(i)});\n    std::cout << func(i) << std::endl;\n  }\n  auto prediction = model(createDataFromRange(new_x_data));\n  std::cout << \"Predictions: \\n\" << prediction << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "5d6865adcbc0d4d347774a82b0c975098d5baace", "size": 1826, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter12/sharkml/shark-save.cc", "max_stars_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_stars_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 201.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T12:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:56:11.000Z", "max_issues_repo_path": "Chapter12/sharkml/shark-save.cc", "max_issues_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_issues_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-12T10:01:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T19:35:05.000Z", "max_forks_repo_path": "Chapter12/sharkml/shark-save.cc", "max_forks_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_forks_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T15:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T02:07:09.000Z", "avg_line_length": 27.6666666667, "max_line_length": 70, "alphanum_fraction": 0.6703176342, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5097757000296805}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright Christopher Kormanyos 2019 - 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 <string>\n\n#if defined(__GNUC__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#endif\n\n#include <boost/lexical_cast.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/uintwide_t_backend.hpp>\n\n#include <math/wide_integer/uintwide_t.h>\n#include <math/wide_integer/uintwide_t_test.h>\n\nnamespace\n{\n  constexpr std::size_t local_digits2 = 16384U;\n}\n\nusing local_uint_type =\n  boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<local_digits2>,\n                                boost::multiprecision::et_off>;\n\nusing boost_uint_backend_type =\n  boost::multiprecision::cpp_int_backend<local_digits2,\n                                         local_digits2,\n                                         boost::multiprecision::unsigned_magnitude>;\n\nusing boost_uint_type =\n  boost::multiprecision::number<boost_uint_backend_type,\n                                boost::multiprecision::et_off>;\n\nbool math::wide_integer::test_uintwide_t_edge_cases()\n{\n  const local_uint_type u_max_local = (std::numeric_limits<local_uint_type>::max)();\n  const boost_uint_type u_max_boost = (std::numeric_limits<boost_uint_type>::max)();\n\n  local_uint_type result_local;\n  boost_uint_type result_boost;\n\n  result_local = u_max_local * u_max_local;\n  result_boost = u_max_boost * u_max_boost;\n\n  const bool result01_is_ok = ((result_local == 1U) && (result_boost == 1U));\n\n  result_local = (u_max_local - 1U) * u_max_local;\n  result_boost = (u_max_boost - 1U) * u_max_boost;\n\n  const bool result02_is_ok = ((result_local == 2U) && (result_boost == 2U));\n\n  const std::string str_seven_and_effs =\n    \"0x7\" + std::string(std::string::size_type((local_digits2 / 4) - 1U), char('F'));\n\n  const local_uint_type u_seven_and_effs_local(str_seven_and_effs.c_str());\n  const boost_uint_type u_seven_and_effs_boost(str_seven_and_effs.c_str());\n\n  result_local = u_seven_and_effs_local * u_seven_and_effs_local;\n  result_boost = u_seven_and_effs_boost * u_seven_and_effs_boost;\n\n  const bool result03_is_ok = (result_local.convert_to<std::string>() == result_boost.convert_to<std::string>());\n\n  const std::string str_three_quarter_effs_and_zeros =\n      \"0x\"\n    + std::string(std::string::size_type((local_digits2 / 4) * 3U), char('F'))\n    + std::string(std::string::size_type((local_digits2 / 4) * 1U), char('0'))\n    ;\n\n  const local_uint_type u_three_quarter_effs_and_zeros_local(str_three_quarter_effs_and_zeros.c_str());\n  const boost_uint_type u_three_quarter_effs_and_zeros_boost(str_three_quarter_effs_and_zeros.c_str());\n\n  result_local = u_three_quarter_effs_and_zeros_local * u_three_quarter_effs_and_zeros_local;\n  result_boost = u_three_quarter_effs_and_zeros_boost * u_three_quarter_effs_and_zeros_boost;\n\n  const bool result04_is_ok = (result_local.convert_to<std::string>() == result_boost.convert_to<std::string>());\n\n  const std::string str_one_quarter_effs_and_zeros =\n      \"0x\"\n    + std::string(std::string::size_type((local_digits2 / 4) * 1U), char('F'))\n    + std::string(std::string::size_type((local_digits2 / 4) * 3U), char('0'))\n    ;\n\n  const local_uint_type u_one_quarter_effs_and_zeros_local(str_one_quarter_effs_and_zeros.c_str());\n  const boost_uint_type u_one_quarter_effs_and_zeros_boost(str_one_quarter_effs_and_zeros.c_str());\n\n  result_local = u_one_quarter_effs_and_zeros_local * u_one_quarter_effs_and_zeros_local;\n  result_boost = u_one_quarter_effs_and_zeros_boost * u_one_quarter_effs_and_zeros_boost;\n\n  const bool result05_is_ok = (result_local.convert_to<std::string>() == result_boost.convert_to<std::string>());\n\n  const local_uint_type one_limb_effs_prior_to_half_and_zeros_local(local_uint_type(UINT32_C(0xFFFFFFFF)) << ((std::numeric_limits<local_uint_type>::digits / 2) - 32));\n  const boost_uint_type one_limb_effs_prior_to_half_and_zeros_boost(boost_uint_type(UINT32_C(0xFFFFFFFF)) << ((std::numeric_limits<boost_uint_type>::digits / 2) - 32));\n\n  result_local = one_limb_effs_prior_to_half_and_zeros_local * one_limb_effs_prior_to_half_and_zeros_local;\n  result_boost = one_limb_effs_prior_to_half_and_zeros_boost * one_limb_effs_prior_to_half_and_zeros_boost;\n\n  const bool result06_is_ok = (result_local.convert_to<std::string>() == result_boost.convert_to<std::string>());\n\n  const local_uint_type u_mid_local = u_three_quarter_effs_and_zeros_local / typename local_uint_type::backend_type::representation_type::limb_type(2U);\n  const boost_uint_type u_mid_boost = u_three_quarter_effs_and_zeros_boost / typename std::iterator_traits<boost_uint_type::backend_type::limb_pointer>::value_type(2U);\n\n  constexpr int signed_shift_amount =\n    -(std::numeric_limits<typename local_uint_type::backend_type::representation_type::limb_type>::digits + 7);\n\n  result_local = u_mid_local;\n  result_local.backend().representation() >>= signed_shift_amount;\n  result_boost = u_mid_boost * (boost_uint_type(1U) << (-signed_shift_amount));\n\n  const bool result07_is_ok = (result_local.convert_to<std::string>() == result_boost.convert_to<std::string>());\n\n  result_local = u_mid_local;\n  result_local.backend().representation() <<= signed_shift_amount;\n  result_boost = u_mid_boost / (boost_uint_type(1U) << (-signed_shift_amount));\n\n  const bool result08_is_ok = (result_local.convert_to<std::string>() == result_boost.convert_to<std::string>());\n\n  const bool result_is_ok = (   result01_is_ok\n                             && result02_is_ok\n                             && result03_is_ok\n                             && result04_is_ok\n                             && result05_is_ok\n                             && result06_is_ok\n                             && result07_is_ok\n                             && result08_is_ok);\n\n  return result_is_ok;\n}\n\n#if defined(__GNUC__)\n#pragma GCC diagnostic pop\n#endif\n", "meta": {"hexsha": "6602f4851eb0a76299b40762e2fe87cfefd700c3", "size": 6090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_uintwide_t_edge_cases.cpp", "max_stars_repo_name": "zeta1999/wide-integer", "max_stars_repo_head_hexsha": "22d819091f5b9d42e5f1bfad1b312028fc400b91", "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_uintwide_t_edge_cases.cpp", "max_issues_repo_name": "zeta1999/wide-integer", "max_issues_repo_head_hexsha": "22d819091f5b9d42e5f1bfad1b312028fc400b91", "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_uintwide_t_edge_cases.cpp", "max_forks_repo_name": "zeta1999/wide-integer", "max_forks_repo_head_hexsha": "22d819091f5b9d42e5f1bfad1b312028fc400b91", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T11:23:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-19T11:23:57.000Z", "avg_line_length": 44.1304347826, "max_line_length": 168, "alphanum_fraction": 0.7275862069, "num_tokens": 1495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5097271125533671}}
{"text": "//File: homography.cc\n//Author: Yuxin Wu <ppwwyyxx@gmail.com>\n\n#include \"homography.hh\"\n\n#include <Eigen/Dense>\n#include <vector>\n\n#include \"lib/matrix.hh\"\n#include \"lib/polygon.hh\"\n#include \"match_info.hh\"\n\nusing namespace std;\n\nnamespace {\ninline Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>>\n\tto_eigenmap(const pano::Homography& m) {\n\t\treturn Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>>(\n\t\t\t\t(double*)m.data, 3, 3);\n\t}\n}\n\nnamespace pano {\n\nHomography Homography::inverse(bool* succ) const {\n\tusing namespace Eigen;\n\tHomography ret;\n\tauto res = to_eigenmap(ret),\n\t\t\t input = to_eigenmap(*this);\n\tFullPivLU<Eigen::Matrix<double,3,3,RowMajor>> lu(input);\n\tif (succ == nullptr) {\n\t\tm_assert(lu.isInvertible());\n\t} else {\n\t\t*succ = lu.isInvertible();\n\t\tif (! *succ) return ret;\n\t}\n\tres = lu.inverse().eval();\n\treturn ret;\n}\n\nHomography Homography::operator * (const Homography& r) const {\n\tHomography ret;\n\tauto m1 = to_eigenmap(*this),\n\t\t\t m2 = to_eigenmap(r),\n\t\t\t res = to_eigenmap(ret);\n\tres = m1 * m2;\n\treturn ret;\n}\n\nstd::vector<Vec2D> overlap_region(\n\t\tconst Shape2D& shape1, const Shape2D& shape2,\n\t\tconst Matrix& homo, const Homography& inv) {\n\t// use sampled edge points, rather than 4 corner, to deal with distorted homography\n\t// for distorted homography, the range of projected z coordinate contains 0\n\t// or equivalently, some point is projected to infinity\n\tconst int NR_POINT_ON_EDGE = 100;\n\tMatrix edge_points(3, 4 * NR_POINT_ON_EDGE);\n\tfloat stepw = shape2.w * 1.0 / NR_POINT_ON_EDGE,\n\t\t\t\tsteph = shape2.h * 1.0 / NR_POINT_ON_EDGE;\n\tREP(i, NR_POINT_ON_EDGE) {\n\t\tVec2D p{-shape2.halfw() + i * stepw, -shape2.halfh()};\n\t\tedge_points.at(0, i * 4) = p.x, edge_points.at(1, i * 4) = p.y;\n\t\tp = Vec2D{-shape2.halfw() + i * stepw, shape2.halfh()};\n\t\tedge_points.at(0, i * 4 + 1) = p.x, edge_points.at(1, i * 4 + 1) = p.y;\n\t\tp = Vec2D{-shape2.halfw(), -shape2.halfh() + i * steph};\n\t\tedge_points.at(0, i * 4 + 2) = p.x, edge_points.at(1, i * 4 + 2) = p.y;\n\t\tp = Vec2D{shape2.halfw(), -shape2.halfh() + i * steph};\n\t\tedge_points.at(0, i * 4 + 3) = p.x, edge_points.at(1, i * 4 + 3) = p.y;\n\t}\n\tREP(i, 4 * NR_POINT_ON_EDGE)\n\t\tedge_points.at(2, i) = 1;\n\tauto transformed_pts = homo * edge_points;\t//3x4n\n\tvector<Vec2D> pts2in1;\n\tREP(i, 4 * NR_POINT_ON_EDGE) {\n\t\tfloat denom = 1.0 / transformed_pts.at(2, i);\n\t\tVec2D pin1{transformed_pts.at(0, i) * denom, transformed_pts.at(1, i) * denom};\n\t\tif (shape1.shifted_in(pin1))\n\t\t\tpts2in1.emplace_back(pin1);\n\t}\n\n\t// also add 4 corner of 1 to build convex hull, in case some are valid\n\tauto corners = shape1.shifted_corner();\n\tfor (auto& c : corners) {\n\t\tVec2D cin2 = inv.trans2d(c);\n\t\tif (shape2.shifted_in(cin2))\n\t\t\tpts2in1.emplace_back(c);\n\t}\n\tauto ret = convex_hull(pts2in1);\n\treturn ret;\n}\n\n}\n", "meta": {"hexsha": "8b13878ee761230273187fb3442f34fe686b9d71", "size": 2768, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/stitch/homography.cc", "max_stars_repo_name": "couetilj/OpenPano", "max_stars_repo_head_hexsha": "f2f9c02cbb82ffed5fceed172a9c458eee5aace3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1318.0, "max_stars_repo_stars_event_min_datetime": "2017-02-22T15:59:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:18:41.000Z", "max_issues_repo_path": "src/stitch/homography.cc", "max_issues_repo_name": "couetilj/OpenPano", "max_issues_repo_head_hexsha": "f2f9c02cbb82ffed5fceed172a9c458eee5aace3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 91.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T11:53:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T21:02:55.000Z", "max_forks_repo_path": "src/stitch/homography.cc", "max_forks_repo_name": "couetilj/OpenPano", "max_forks_repo_head_hexsha": "f2f9c02cbb82ffed5fceed172a9c458eee5aace3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 439.0, "max_forks_repo_forks_event_min_datetime": "2017-02-15T04:53:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T02:16:50.000Z", "avg_line_length": 29.7634408602, "max_line_length": 84, "alphanum_fraction": 0.6683526012, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.509727107094248}}
{"text": "#include \"ros/ros.h\"\n#include \"geometry_msgs/PoseStamped.h\"\n#include \"nav_msgs/Path.h\"\n#include <opencv2/opencv.hpp>\n#include <Eigen/Dense>\n#include <chrono>\n\n#include <vector>\nusing namespace std;\n/**\n *  \u8fd9\u4e2a\u662fnav_msgs::Path\u7248\u672c\u7684,\u7528\u7684\u662f\u6700\u539f\u59cb\u7684\u7b56\u7565:OpenCV\u4ece\u4e2d\u95f4\u5411\u4e24\u8fb9\u8fdb\u884c\u626b\u63cf\n *\n *  @author:panguoping\n *  @version:v3.0\n *\n *  @functions:\n *      - transTo3D\n *      - pubMiddleline\n *      - pubMiddleline\n *\n *  @tips: \u76f8\u6bd4v2.0\u6dfb\u52a0\u4e0a\u4e86\u4ee5\u4e0b\u53c2\u6570\uff0c\u540c\u65f6\u6539\u4e86main\u51fd\u6570\n *      int left_begin;\n *      int left_end;\n *      int right_begin;\n *      int right_end;\n *\n *\n *\n * */\n\n/** \u53c2\u6570\u5b9a\u4e49 **/\nconst float fx = 760.4862674784594; // \u76f8\u673a\u5185\u53c2\nconst float fy = 761.4971958529285;\nconst float cx = 631.6715834996345;\nconst float cy = 329.3054436037627;\n\nconst float y = 129.5585;   // \u56fa\u5b9a\u76f8\u673a\u79bb\u5730\u9762\u9ad8\u5ea6\uff0c\u5355\u4f4dmm\uff0c\u901a\u8fc7\u8ba1\u7b97\u5f97\u5230\uff0c\u4e0d\u4e00\u5b9a\u51c6\n\nfloat offset;\nfloat thetaX;\nfloat thetaY;\nfloat scale;\nint imgWidth;  // \u56fe\u7247\u5927\u5c0f\nint imgHeight;\nint left_begin;\nint left_end;\nint right_begin;\nint right_end;\n\nros::Publisher pathpub;\n\n/** \u5c06\u56fe\u7247\u4e2d\u7684 \u70b9uv \u8f6c\u5316\u4e3a \u73b0\u5b9e\u5750\u6807\u4e2d\u7684 \u70b9xy **/\ncv::Point3f getXYZ(cv::Point2f& point){\n    cv::Point3f point3d;\n    point3d.x = (fy * y/(point.y-cy))/scale;\n    point3d.y = (-(point.x-cx)*point3d.x/fx);   //todo shan chu /scale\n    point3d.z = 0.0;\n    return point3d;\n}\n\n/** \u5c06\u4e8c\u7ef4\u8fb9\u7ebf\u8f6c\u5316\u4e3a\u4e09\u7ef4\u8fb9\u7ebf **/\nvoid transTo3D(vector<cv::Point2f>& uv,vector<cv::Point3f>& posearray){\n    for(auto p:uv){\n        cv::Point3f pose = getXYZ(p);\n        posearray.push_back(pose);\n    }\n}\n\n/** \u753b\u51fa\u4e2d\u95f4\u7ebf **/\nvoid pubMiddleline(vector<cv::Point2f>& uvLeft,vector<cv::Point2f>& uvRight){\n    vector<cv::Point3f> xyLeft,xyRight;\n    nav_msgs::Path path;\n    transTo3D(uvLeft,xyLeft);\n    transTo3D(uvRight,xyRight);\n    ROS_INFO(\"int two middle\");\n    bool lbigthanr = xyLeft.size() > xyRight.size() ? true:false;\n    int ir = 0;\n    int il = 0;\n    if(lbigthanr){\n        while(il<xyLeft.size()&&abs(xyLeft[il].x-xyRight[ir].x)>thetaX){\n            ++il;\n        }\n    } else{\n        while(ir<xyRight.size()&&abs(xyLeft[il].x-uvRight[ir].x)>thetaX){\n            ++ir;\n        }\n    }\n    ROS_INFO(\"sizer:%d,sizel:%d\",xyRight.size(),xyLeft.size());\n//    ROS_INFO(\"ir:%d,il:%d\",ir,il);\n    ROS_INFO(\"sizer1:%d,sizel1:%d\",xyRight.size()-5,xyLeft.size()-5);\n    ROS_INFO(\"ir1:%d,il1:%d\",ir,il);\n\n    for(ir,il; il<int(xyLeft.size()-5)&&ir<int(uvRight.size()-5);++ir,++il){    //this qiang zhi zhuan huan yongyuande shen\n        ROS_INFO(\"ir:%d,il:%d\",ir,il);\n//        if(ir>100){\n//            while (1);\n//        }\n        if(abs(xyLeft[il].x-uvRight[ir].x)>thetaX\n           && abs(xyLeft[il+1].y-xyLeft[il].y)>thetaY   //todo cha zhi\n           && abs(xyRight[ir+1].y-xyRight[ir].y)>thetaY)\n            continue;\n        ROS_INFO(\"yes\");\n\n        geometry_msgs::PoseStamped pose;\n        pose.pose.position.x = (xyLeft[il].x+xyRight[ir].x)/2;\n        pose.pose.position.y = (xyLeft[il].y+xyRight[ir].y)/2;\n        pose.pose.position.z = 0.0;\n        path.poses.push_back(pose);\n    }\n    ROS_INFO(\"pathpose:%d\",path.poses.size());\n    path.header.stamp = ros::Time::now();\n    path.header.frame_id = \"camera\";\n\n    pathpub.publish(path);\n    ROS_INFO(\"publish successfully\");\n}\n/** \u753b\u51fa\u4e2d\u95f4\u7ebf **/\nvoid pubMiddleline(vector<cv::Point2f>& uv){\n    vector<cv::Point3f> xy;\n    nav_msgs::Path path;\n    transTo3D(uv,xy);\n    for(auto p:xy){\n        if(p.y>0.1){\n            geometry_msgs::PoseStamped pose;\n            pose.pose.position.x = p.x;\n            pose.pose.position.y = p.y-offset;\n            pose.pose.position.z = 0.0;\n            path.poses.push_back(pose);\n        }\n        else if(p.y<-0.1){\n            geometry_msgs::PoseStamped pose;\n            pose.pose.position.x = p.x;\n            pose.pose.position.y = p.y+offset;\n            pose.pose.position.z = 0.0;\n            path.poses.push_back(pose);\n        }\n        else{\n            continue;\n        }\n    }\n    ROS_INFO(\"pathpose:%d\",path.poses.size());\n    path.header.stamp = ros::Time::now();\n    path.header.frame_id = \"camera\";\n    pathpub.publish(path);\n    ROS_INFO(\"publish successfully\");\n}\n\nint main(int argc ,char **argv){\n    ros::init(argc,argv,\"linktracking\");\n    ros::NodeHandle nh(\"~\");\n    ros::Time t1 = ros::Time::now();\n\n    pathpub = nh.advertise<nav_msgs::Path>(\"path\",0);\n    string video;\n    nh.param<string>(\"video\",video,\"../dataset/test.mp4\");\n    nh.param<float>(\"offset\",offset,0.45);\n    nh.param<float>(\"thetaX\",thetaX,0.2);\n    nh.param<float>(\"thetaY\",thetaY,0.1);\n    nh.param<float>(\"scale\",scale,1000.0);\n    nh.param<int>(\"imgWidth\",imgWidth,1280);\n    nh.param<int>(\"imgHeight\",imgHeight,720);\n    nh.param<int>(\"left_begin\",left_begin,imgHeight/2);\n    nh.param<int>(\"left_end\",left_end,imgHeight);\n    nh.param<int>(\"right_begin\",right_begin,imgWidth/2);\n    nh.param<int>(\"right_end\",right_end,imgHeight);\n\n    /** 1.get the video **/\n    cv::VideoCapture cap = cv::VideoCapture(video);\n    cap.set(CV_CAP_PROP_FRAME_WIDTH, imgWidth);\n    cap.set(CV_CAP_PROP_FRAME_HEIGHT, imgHeight);\n    cap.set(cv::CAP_PROP_FPS,30);\n    // LineState flag;\n    ROS_INFO(\"get\");\n    ROS_INFO(\"%s\",video.c_str());\n    cv::Mat frame;\n\n    while (cap.isOpened()&&ros::ok()) {\n        /** 2.get frame and turn to binary **/\n        cap.read(frame);\n        cv::Mat gray;\n//            ROS_INFO(\"frame.channel: %d\",frame.channels());\n\n\n//            if(frame.channels()==1){\n//                ROS_INFO(\"use time : %f\",(ros::Time::now()-t1).toSec());\n//                cv::imshow(\"frame\",frame);\n//                cv::waitKey(0);\n//                continue;\n//            }\n        cv::cvtColor(frame, gray, CV_RGB2GRAY);\n        cv::Mat binary;\n        cv::threshold(gray, binary, 0, 255, CV_THRESH_OTSU);\n        cv::imshow(\"frame\",binary);\n        cv::waitKey(33);\n        // cv::erode(binary, binary, cv::Mat(), cv::Point(-1, -1), 2);\n//            cv::imshow(\"show\", binary);\n//            cv::waitKey(0);\n\n        /** 3.get point of two side **/\n        int vline = binary.cols / 2;    //todo verticalThres\n        int pline = binary.rows * 2 / 3 - 10; //todo parallelThres and bias\n        vector<cv::Point2f> uvRight;\n        vector<cv::Point2f> uvLeft;\n        // right side\n        for (int i = right_begin; i < right_end; ++i) {\n            uchar *data = binary.ptr<uchar>(i);\n            for (int j = vline; j < binary.cols - 5; ++j) {\n                if (data[j] == 0 \n                    && data[j + 1] == 255&&data[j+2]==255\n                    &&data[j+3]==255&&data[j+4]==255) {\n                    \n                    uvRight.push_back(cv::Point2f(j, i));\n                    break;\n                }\n            }\n        }\n        // left side\n        for (int i = left_begin; i < left_end; ++i) {\n            uchar *data = binary.ptr<uchar>(i);\n            for (int j = vline; j > 5; --j) {\n                if (data[j] == 0 \n                    && data[j - 1] == 255&& data[j - 2] == 255\n                    && data[j - 3] == 255&& data[j - 4] == 255) {\n                    uvLeft.push_back(cv::Point2f(j, i));\n                    break;\n                }\n            }\n        }\n        ROS_INFO(\"right.size = %d,left.size = %d\",uvRight.size(),uvLeft.size());\n        /** 4.transport **/\n        if(uvLeft.size()>10&&uvRight.size()>10){  //todo sizeThres\n            pubMiddleline(uvLeft,uvRight);\n        }\n        else if(uvLeft.size()>10){\n            pubMiddleline(uvLeft);\n        }\n        else if(uvRight.size()>10){\n            pubMiddleline(uvRight);\n        }\n    }\n    ROS_INFO(\"can't load the video!\");\n    return 0;\n}", "meta": {"hexsha": "447d99ec41a0b1240177359a27eace110a028643", "size": 7444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lineTrack-2/src/linTrack_nav_v3.0.cpp", "max_stars_repo_name": "GuoPingPan/LinearTracking_Huawei", "max_stars_repo_head_hexsha": "499e16448081421766df66614551750c1cb71a1d", "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": "lineTrack-2/src/linTrack_nav_v3.0.cpp", "max_issues_repo_name": "GuoPingPan/LinearTracking_Huawei", "max_issues_repo_head_hexsha": "499e16448081421766df66614551750c1cb71a1d", "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": "lineTrack-2/src/linTrack_nav_v3.0.cpp", "max_forks_repo_name": "GuoPingPan/LinearTracking_Huawei", "max_forks_repo_head_hexsha": "499e16448081421766df66614551750c1cb71a1d", "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.633744856, "max_line_length": 123, "alphanum_fraction": 0.5464803869, "num_tokens": 2290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.640635841117624, "lm_q1q2_score": 0.5097270961760094}}
{"text": "#include <CGAL/Cartesian.h>\n#include <CGAL/Point_2.h>\n#include <CGAL/Segment_2.h>\n#include <CGAL/intersections.h>\n#include <CGAL/tuple.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/Join_input_iterator.h>\n#include <CGAL/iterator.h>\n\n#include <vector>\n#include <functional>\n\n#include <boost/variant.hpp>\n#include <boost/optional.hpp>\n#include <boost/any.hpp>\n#include <boost/timer.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <tuple>\n#include <functional>\n#include <CGAL/Overload.h>\n\n// Intersection_traits\ntemplate<typename, typename, typename>\nstruct Intersection_traits;\n\ntemplate<typename K>\nstruct Intersection_traits<K, typename K::Segment_2, typename K::Segment_2> {\n  typedef typename boost::variant<typename K::Segment_2, typename K::Point_2 > variant_type;\n  typedef typename boost::optional< variant_type > result_type;\n};\n\n\ntemplate <class K, class OutputIterator>\nOutputIterator intersect_do_iterator(const typename K::Segment_2 &seg1,\n                           const typename K::Segment_2 &seg2,\n                           const K&, OutputIterator o) {\n  typedef CGAL::internal::Segment_2_Segment_2_pair<K> is_t;\n\n  is_t ispair(&seg1, &seg2);\n  switch (ispair.intersection_type()) {\n  case is_t::NO_INTERSECTION:\n  default:\n    return o;\n  case is_t::POINT:\n    *o++ = ispair.intersection_point();\n    return o;\n  case is_t::SEGMENT:\n    *o++ = ispair.intersection_segment();\n    return o;\n  }\n}\n\n\ntemplate <class K>\nboost::optional<\n  boost::variant<typename K::Segment_2, typename K::Point_2>\n  >\nintersection_variant(const typename K::Segment_2 &seg1,\n             const typename K::Segment_2 &seg2,\n             const K&)\n{\n  typedef CGAL::internal::Segment_2_Segment_2_pair<K> is_t;\n\n  typedef boost::variant<typename K::Segment_2, typename K::Point_2> Variant;\n  typedef boost::optional<Variant> OptVariant;\n\n  is_t ispair(&seg1, &seg2);\n  switch (ispair.intersection_type()) {\n  case is_t::NO_INTERSECTION:\n  default:\n    return OptVariant();\n  case is_t::POINT:\n    return OptVariant(ispair.intersection_point());\n  case is_t::SEGMENT:\n    return OptVariant(ispair.intersection_segment());\n  }\n}\n\ntemplate <class K>\nboost::any intersection_any(const typename K::Segment_2 &seg1,\n                            const typename K::Segment_2 &seg2,\n                            const K&)\n{\n  typedef CGAL::internal::Segment_2_Segment_2_pair<K> is_t;\n\n  is_t ispair(&seg1, &seg2);\n  switch (ispair.intersection_type()) {\n  case is_t::NO_INTERSECTION:\n  default:\n    return boost::any();\n  case is_t::POINT:\n    return boost::any(ispair.intersection_point());\n  case is_t::SEGMENT:\n    return boost::any(ispair.intersection_segment());\n  }\n}\n\n\nusing namespace CGAL;\n\ntypedef Cartesian<double>    K;\ntypedef K::Point_2           Point;\ntypedef Creator_uniform_2<double,Point>  Pt_creator;\ntypedef K::Segment_2         Segment;\ntypedef std::vector<Segment> Vector;\n\ntemplate<typename F>\nvoid intersect_each(F f, const Vector& segs) {\n  for(Vector::const_iterator it = segs.begin(); it != segs.end(); ++it) {\n      const Segment& seg_1 = *it;\n      for(Vector::const_iterator it2 = segs.begin(); it2 != segs.end(); ++it2) {\n        f(seg_1, *it2);\n      }\n  }\n}\n\nstruct Vec_holder {\n  Vec_holder(std::vector<Point>* p, std::vector<Segment>* s) : p(p), s(s) { }\nprotected:\n  std::vector<Point>* p;\n  std::vector<Segment>* s;\n};\n\nstruct Visitor : public boost::static_visitor<>, Vec_holder\n{\n  Visitor(std::vector<Point>* p, std::vector<Segment>* s) :\n    Vec_holder(p, s) { }\n\n  void operator()(const Point& point) { p->push_back(point);  }\n  void operator()(const Segment& segment) { s->push_back(segment);  }\n};\n\nstruct Variant_f {\n  Variant_f(std::vector<Point>* p, std::vector<Segment>* s) : v(p, s)\n    { }\n  typedef Intersection_traits<K, Segment, Segment> Traits;\n  typedef Traits::result_type result_type;\n\n  Visitor v;\n  void operator()(const Segment& s1, const Segment& s2) {\n    result_type obj = intersection_variant(s1, s2, K());\n    if(obj) {\n      boost::apply_visitor(v, *obj);\n    }\n  }\n};\n\nstruct Object_f : Vec_holder {\n  Object_f(std::vector<Point>* p, std::vector<Segment>* s) :\n    Vec_holder(p, s) { }\n\n  void operator()(const Segment& s1, const Segment& s2) {\n    Object obj = intersection(s1, s2);\n      if (const Point * point = object_cast<Point>(&obj)) {\n        p->push_back(*point);\n      } else if (const Segment * segment = object_cast<Segment>(&obj)) {\n        s->push_back(*segment);\n      }\n  }\n};\n\nstruct Any_f : Vec_holder {\n  Any_f(std::vector<Point>* p, std::vector<Segment>* s) :\n    Vec_holder(p, s) { }\n\n  void operator()(const Segment& s1, const Segment& s2) {\n    boost::any obj = intersection_any(s1, s2, K());\n    if (const Point * point = boost::any_cast<Point>(&obj)) {\n       p->push_back(*point);\n    } else if (const Segment * segment = boost::any_cast<Segment>(&obj)) {\n      s->push_back(*segment);\n    }\n  }\n};\n\n\nstruct Object_from_variant_f : Vec_holder {\n  Object_from_variant_f(std::vector<Point>* p, std::vector<Segment>* s) :\n    Vec_holder(p, s) { }\n\n  void operator()(const Segment& s1, const Segment& s2) {\n    Object obj = intersection_variant(s1, s2, K());\n      if (const Point * point = object_cast<Point>(&obj)) {\n        p->push_back(*point);\n      } else if (const Segment * segment = object_cast<Segment>(&obj)) {\n        s->push_back(*segment);\n      }\n  }\n};\n\nstruct Do_f : Vec_holder {\n  Do_f(std::vector<Point>* p, std::vector<Segment>* s) :\n    Vec_holder(p, s) { }\n\n  typedef typename std::back_insert_iterator< std::vector<Point> >   Iter1;\n  typedef typename std::back_insert_iterator< std::vector<Segment> > Iter2;\n\n  void operator()(const Segment& s1, const Segment& s2) {\n\n    CGAL::Dispatch_or_drop_output_iterator<std::tuple<Point,Segment>,\n                                           std::tuple<Iter1,Iter2>\n                                           > do_it(std::back_inserter(*p), std::back_inserter(*s));\n\n    intersect_do_iterator(s1, s2, K(), do_it);\n  }\n};\n\nstd::tuple<int, int, int> intersect_each_variant_overload(const Vector& segs) {\n  std::tuple<int, int, int> ret = std::make_tuple(0, 0, 0);\n  typedef Intersection_traits<K, Segment, Segment> Traits;\n  typedef Traits::result_type result_type;\n\n  // Calculate the intersections between each segment\n  for(Vector::const_iterator it = segs.begin(); it != segs.end(); ++it) {\n    const Segment& seg_1 = *it;\n    for(Vector::const_iterator it2 = segs.begin(); it2 != segs.end(); ++it2) {\n      result_type obj = intersection_variant(seg_1, *it2, K());\n      if(obj) {\n         // with c++0x\n        auto v = make_overload(\n          std::make_tuple(std::function<void(const Segment&)>(\n                            [&ret](const Segment& s) { (void)s; ++(std::get<1>(ret)); }),\n                          std::function<void(const Point&)>(\n                            [&ret](const Point& p) { (void)p; ++(std::get<0>(ret)); })));\n\n        boost::apply_visitor(v, *obj);\n      } else {\n        ++(std::get<2>(ret));\n      }\n    }\n  }\n\n  return ret;\n}\n\nint main(int argc, char* argv[]) {\n  int repeats = 100;\n  int seg_count = 200;\n\n  if(argc > 1)\n    repeats = boost::lexical_cast<int>(argv[1]);\n  if(argc > 2)\n    seg_count = boost::lexical_cast<int>(argv[2]);\n\n  // Create test segment set. Prepare a vector for 200 segments.\n  Vector segs;\n  segs.reserve(200);\n\n  // Prepare point generator for the horizontal segment, length 200.\n  typedef Random_points_on_segment_2<Point,Pt_creator> P1;\n  P1 p1( Point(-100,0), Point(100,0));\n\n  // Prepare point generator for random points on circle, radius 250.\n  typedef Random_points_on_circle_2<Point,Pt_creator> P2;\n  P2 p2( 250);\n\n  // Create segments.\n  typedef Creator_uniform_2< Point, Segment> Seg_creator;\n  typedef Join_input_iterator_2< P1, P2, Seg_creator> Seg_iterator;\n  Seg_iterator g( p1, p2);\n  CGAL::copy_n( g, seg_count, std::back_inserter(segs));\n\n  std::vector<Point> points;\n  std::vector<Segment> segments;\n  points.clear(); segments.clear(); points.reserve(0); segments.reserve(0);\n  //one run to get the size\n  intersect_each(Variant_f(&points, &segments), segs);\n\n  boost::timer timer;\n\n  // variant vs object vs any\n\n  points.clear(); segments.clear();\n  timer.restart();\n\n  for(int i = 0; i < repeats; ++i) {\n    intersect_each(Object_f(&points, &segments), segs);\n    points.clear(); segments.clear();\n  }\n  std::cout << \"Time for object: \" << timer.elapsed() << '\\n';\n\n  points.clear(); segments.clear();\n  timer.restart();\n\n  for(int i = 0; i < repeats; ++i) {\n    intersect_each(Variant_f(&points, &segments), segs);\n    points.clear(); segments.clear();\n  }\n  std::cout << \"Time for variant: \" << timer.elapsed() << '\\n';\n\n  points.clear(); segments.clear();\n  timer.restart();\n\n  for(int i = 0; i < repeats; ++i) {\n    intersect_each(Any_f(&points, &segments), segs);\n    points.clear(); segments.clear();\n  }\n  std::cout << \"Time for any: \" << timer.elapsed() << '\\n';\n\n  points.clear(); segments.clear();\n  timer.restart();\n\n  for(int i = 0; i < repeats; ++i) {\n    intersect_each(Object_from_variant_f(&points, &segments), segs);\n    points.clear(); segments.clear();\n  }\n  std::cout << \"Time for object_from_variant: \" << timer.elapsed() << '\\n';\n\n  points.clear(); segments.clear();\n  timer.restart();\n\n  for(int i = 0; i < repeats; ++i) {\n    intersect_each(Do_f(&points, &segments), segs);\n    points.clear(); segments.clear();\n  }\n  std::cout << \"Time for dispatch_output: \" << timer.elapsed() << '\\n';\n\n  std::cout << std::flush;\n}\n", "meta": {"hexsha": "11416d859b79b73fc9a98122b35fca774a4d1c00", "size": 9474, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Intersections_2/benchmark/Intersections_2/variant_any_object.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": "Intersections_2/benchmark/Intersections_2/variant_any_object.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": "Intersections_2/benchmark/Intersections_2/variant_any_object.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": 29.5140186916, "max_line_length": 99, "alphanum_fraction": 0.6427063542, "num_tokens": 2555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5096551262423707}}
{"text": "#include \"quadeigs.hpp\"\n#include \"soar.hpp\"\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <fmt/format.h>\n\nusing namespace Eigen;\n\nQuadEigs::QuadEigs(const Ref<const MatrixXd> &matM,\n                   const Ref<const MatrixXd> &matD,\n                   const Ref<const MatrixXd> &matK)\n    : ndim_(matM.cols()), matM_(matM), matD_(matD), matK_(matK),\n      matA_(ndim_, ndim_), matB_(ndim_, ndim_) {\n  MatrixXd matMi = matM.inverse();\n  matA_ = -matMi * matD_;\n  matB_ = -matMi * matK_;\n}\n\nVectorXcd QuadEigs::eigenvalues(int m) {\n  Soar soar(matA_, matB_);\n  MatrixXd matQm = soar.compute(m);\n  MatrixXd matMm = matQm.transpose() * matM_ * matQm;\n  MatrixXd matDm = matQm.transpose() * matD_ * matQm;\n  MatrixXd matKm = matQm.transpose() * matK_ * matQm;\n\n  MatrixXd matC(2 * m, 2 * m);\n  MatrixXd matG(2 * m, 2 * m);\n  MatrixXd mzero = MatrixXd::Zero(m, m);\n  MatrixXd mone = MatrixXd::Identity(m, m);\n  matC << -matDm, -matKm, mone, mzero;\n  matG << matMm, mzero, mzero, mone;\n\n  GeneralizedEigenSolver<MatrixXd> ges(matC, matG, false);\n  VectorXcd alphas = ges.alphas();\n  VectorXd betas = ges.betas();\n\n  fmt::print(\"{:>30s}, {:>15s}\\n\", \"alphas\", \"betas\");\n  for (int i = 0; i < m; ++i) {\n    if (std::abs(betas(i)) > 1.0e-8) {\n      fmt::print(\"{:14.5f}+{:14.5f}i\\n\", alphas(i).real() / betas(i),\n                 alphas(i).imag() / betas(i));\n    }\n  }\n\n  VectorXcd ret(m);\n  return ret;\n}", "meta": {"hexsha": "d0011fab1e40e817672a6644c3876a7e9271f4f3", "size": 1401, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/quadeigs.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": "src/quadeigs.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": "src/quadeigs.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.1875, "max_line_length": 69, "alphanum_fraction": 0.6088508208, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5096551262423707}}
{"text": "#define CATCH_CONFIG_MAIN\n#include <catch2/catch.hpp>\n\n#include \"../banquet.h\"\n#include \"utils.h\"\n#include <NTL/GF2E.h>\n#include <NTL/GF2EX.h>\n\nTEST_CASE(\"Precomputed Lagrange Interpolation\", \"[util]\") {\n  const banquet_instance_t &instance = banquet_instance_get(Banquet_L1_Param1);\n  utils::init_extension_field(instance);\n  size_t dimension = 20;\n  vec_GF2E x_values;\n  vec_GF2E y_values1;\n  vec_GF2E y_values2;\n  for (size_t i = 0; i < dimension; i++) {\n    x_values.append(random_GF2E());\n    y_values1.append(random_GF2E());\n    y_values2.append(random_GF2E());\n  }\n\n  // builtin interpolate\n  GF2EX poly1 = interpolate(x_values, y_values1);\n  GF2EX poly2 = interpolate(x_values, y_values2);\n  // precomputed interpolate\n  auto precomputation = utils::precompute_lagrange_polynomials(x_values);\n  GF2EX poly1_with_precom =\n      utils::interpolate_with_precomputation(precomputation, y_values1);\n  GF2EX poly2_with_precom =\n      utils::interpolate_with_precomputation(precomputation, y_values2);\n\n  REQUIRE(poly1 == poly1_with_precom);\n  REQUIRE(poly2 == poly2_with_precom);\n}\n\nTEST_CASE(\"Basic Lifting tests\", \"[util]\") {\n  const banquet_instance_t &instance = banquet_instance_get(Banquet_L1_Param1);\n  utils::init_extension_field(instance);\n  uint8_t a = 3;\n  uint8_t b = 246;\n\n  GF2E a_lifted, b_lifted;\n  GF2X tmp;\n  // a_lifted should be y^30 + y^23 + y^21 + y^18 + y^14 + y^13 + y^11 + y^9 +\n  // y^7 + y^6 + y^5 + y^4 + y^3 + y + 1\n  SetCoeff(tmp, 30);\n  SetCoeff(tmp, 23);\n  SetCoeff(tmp, 21);\n  SetCoeff(tmp, 18);\n  SetCoeff(tmp, 14);\n  SetCoeff(tmp, 13);\n  SetCoeff(tmp, 11);\n  SetCoeff(tmp, 9);\n  SetCoeff(tmp, 7);\n  SetCoeff(tmp, 6);\n  SetCoeff(tmp, 5);\n  SetCoeff(tmp, 4);\n  SetCoeff(tmp, 3);\n  SetCoeff(tmp, 1);\n  SetCoeff(tmp, 0);\n  a_lifted = conv<GF2E>(tmp);\n  clear(tmp);\n  // b_lifted should be y^30 + y^29 + y^27 + y^26 + y^25 + y^19 + y^18 + y^17 +\n  // y^14 + y^13 + y^12 + y^10 + y^8 + y^7 + y^4 + y^2 + y\n  SetCoeff(tmp, 30);\n  SetCoeff(tmp, 29);\n  SetCoeff(tmp, 27);\n  SetCoeff(tmp, 26);\n  SetCoeff(tmp, 25);\n  SetCoeff(tmp, 19);\n  SetCoeff(tmp, 18);\n  SetCoeff(tmp, 17);\n  SetCoeff(tmp, 14);\n  SetCoeff(tmp, 13);\n  SetCoeff(tmp, 12);\n  SetCoeff(tmp, 10);\n  SetCoeff(tmp, 8);\n  SetCoeff(tmp, 7);\n  SetCoeff(tmp, 4);\n  SetCoeff(tmp, 2);\n  SetCoeff(tmp, 1);\n  b_lifted = conv<GF2E>(tmp);\n  GF2E one;\n  set(one);\n\n  REQUIRE(utils::lift_uint8_t(a) == a_lifted);\n  REQUIRE(utils::lift_uint8_t(b) == b_lifted);\n  REQUIRE(a_lifted * b_lifted == one);\n}\n", "meta": {"hexsha": "a064354142b20e20ea06db75d022ce552a1ee551", "size": 2479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/util_test.cpp", "max_stars_repo_name": "dkales/banquet", "max_stars_repo_head_hexsha": "ec9920205713e09199e29ff439928d266e0d9a02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-08-16T23:15:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T12:18:08.000Z", "max_issues_repo_path": "tests/util_test.cpp", "max_issues_repo_name": "dkales/banquet", "max_issues_repo_head_hexsha": "ec9920205713e09199e29ff439928d266e0d9a02", "max_issues_repo_licenses": ["MIT"], "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/util_test.cpp", "max_forks_repo_name": "dkales/banquet", "max_forks_repo_head_hexsha": "ec9920205713e09199e29ff439928d266e0d9a02", "max_forks_repo_licenses": ["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.5444444444, "max_line_length": 79, "alphanum_fraction": 0.6684146833, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5096551262423707}}
{"text": "#include <mex.h> \n#include <math.h>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <vector>\n#include <time.h>\n\n\nusing namespace Eigen;\nusing namespace std;\n\n\ntypedef Triplet<double> eigen_entry;\ntypedef vector<eigen_entry> entry_list;\n\n\ndouble get_Fischer_Burmeister(VectorXd &x, VectorXd &pj, int num)\n{\n    \n    double fb = 0;\n    \n    for (int i = 0; i < num; i++)\n    {\n        double ent = x[i] + pj[i] - sqrt(x[i] * x[i] + pj[i] * pj[i]);\n        fb += ent * ent;\n    }\n    \n    return sqrt(fb);\n    \n}\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n    \n    mxArray *output_mex;\n\n    double *J_index, *JT_index, *J_value, *JT_value, *JTJ_info, *pu, *wu, *bu, *max_iter, *step_size;\n    double *output;\n    \n    J_index = mxGetPr(prhs[0]);\n    JT_index = mxGetPr(prhs[1]);\n    J_value = mxGetPr(prhs[2]);\n    JT_value = mxGetPr(prhs[3]);\n    JTJ_info = mxGetPr(prhs[4]); \n    pu = mxGetPr(prhs[5]);\n    wu = mxGetPr(prhs[6]);\n    bu = mxGetPr(prhs[7]);\n    max_iter = mxGetPr(prhs[8]);\n    step_size = mxGetPr(prhs[9]);\n    \n    // JTJ_info : dof_n, max_valence, tri_n, 3 * 2\n    \n    int J_row = JTJ_info[0];\n    int J_col = JTJ_info[2];\n    int max_it = max_iter[0];\n    double step = step_size[0];\n    \n    output_mex = plhs[0] = mxCreateDoubleMatrix(J_row, 1, mxREAL);\n    \n    output = mxGetPr(output_mex);\n\n    SparseMatrix<double> J_u = SparseMatrix<double>(J_row, J_col);\n    SparseMatrix<double> JT_u = SparseMatrix<double>(J_col, J_row);\n    VectorXd b_u = VectorXd::Zero(J_col);\n     \n    entry_list en_list;\n    \n    for(int i = 0; i < JTJ_info[0]; i++)\n    {\n        for(int j = 0; j < JTJ_info[1]; j++)\n        {\n            int index = i * JTJ_info[1] + j;\n            \n            if(J_index[index] >= 0)\n            {\n                en_list.push_back(eigen_entry(i, J_index[index], J_value[index]));\n            }\n        }\n    }\n    \n    J_u.setFromTriplets(en_list.begin(), en_list.end());\n    \n    \n    en_list.clear();\n    \n    for(int i = 0; i < JTJ_info[2]; i++)\n    {\n        for(int j = 0; j < JTJ_info[3]; j++)\n        {\n            int index = i * JTJ_info[3] + j;\n            \n            if(JT_index[index] >= 0)\n            {\n                en_list.push_back(eigen_entry(i, JT_index[index], JT_value[index]));\n            }\n        }\n    }\n    \n    JT_u.setFromTriplets(en_list.begin(), en_list.end());\n    \n    \n    VectorXd p_u = VectorXd::Zero(J_row);\n    \n    for(int i = 0; i < J_row; i++)\n    {\n        p_u[i] = pu[i];\n    }\n    \n    for(int i = 0; i < J_col; i++)\n    {\n        b_u[i] = bu[i];\n    }\n   \n    VectorXd b = b_u + JT_u * p_u;\n    \n    VectorXd lambda = VectorXd::Zero(J_col);\n    \n    VectorXd pi;\n    \n    double pre_FB, post_FB;\n    \n    int iteration = -1;\n    \n    ///////////////////////////////////////////////////////////////////////////////////////////////\n    \n    pi = JT_u * (J_u * lambda) + b;\n        \n    post_FB = get_Fischer_Burmeister(lambda, pi, J_col);\n    \n    for(int outer = 0; outer < max_it; outer++)\n    {\n        iteration = outer;\n        \n        \n        pre_FB = post_FB;\n        \n        for(int iter = 0; iter < J_col; iter++)\n        {\n            lambda[iter] = fmax(lambda[iter] - step * pi[iter] / wu[iter], 0.0);\n        }\n        \n        pi = JT_u * (J_u * lambda) + b;\n        \n        post_FB = get_Fischer_Burmeister(lambda, pi, J_col);\n\t\t\t\n\t\t\t\tif(abs(post_FB) < 1e-6)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\n        if(abs(pre_FB - post_FB) < 1e-3 * abs(pre_FB))\n        {\n            break;\n        }\t\t\t\n    }\n\t\n    VectorXd p_mod = J_u * lambda;\n    \n    for(int i = 0; i < J_row; i++)\n    {\n        output[i] = p_mod[i];\n    }\n   \n    return;\n    \n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "f46578578f87f49dd80089df12c19270ecdd3af7", "size": 3720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/2D/lib/mex/lcp_solve_eigen_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/lcp_solve_eigen_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/lcp_solve_eigen_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": 20.2173913043, "max_line_length": 101, "alphanum_fraction": 0.4913978495, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5096551167581206}}
{"text": "#include <numeric>\n#include <boost/geometry/algorithms/intersection.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include \"Polygon.hpp\"\n\nPolygon cat_reduce(std::vector<unsigned> ids, std::unordered_map<unsigned, std::vector<Polygon>> polys){\n  using BoostPoly = boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<float>>;\n  BoostPoly a, b;\n  std::vector<float> out;\n  for (const auto& id : ids){\n    const auto& poly_vec = polys[id];\n    for (const auto& poly : poly_vec) {\n      for (int i = 0; i < poly.size(); i += 2) {\n        boost::geometry::append(a.inners(), boost::geometry::model::d2::point_xy{poly[i], poly[i + 1]});\n      }\n    }\n    boost::geometry::intersection(a, b, out);\n  }\n  //std::accumulate(, , [](){boost::geometry::intersection(, , out);});\n}\n\nstd::unordered_map<std::string, Polygon> cats_reduce(std::unordered_map<std::string, std::vector<unsigned>> cats, std::unordered_map<unsigned, std::vector<Polygon>> polys){\n  std::unordered_map<std::string, Polygon> ret;\n  std::transform(cats.begin(), cats.end(), std::inserter(ret, ret.begin()), [](const auto& e){\n    const auto& [name, ids] = e;\n    return std::make_pair(name, cat_reduce(ids));\n  });\n  return ret;\n}", "meta": {"hexsha": "5481cc5746395f832c83e2e933725e8a9314e930", "size": 1264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cats_reduce.cpp", "max_stars_repo_name": "opensciencehack/Fork-of-Team-TimSort", "max_stars_repo_head_hexsha": "90c44752af9932ce2f4c6c617842fb75f4a60941", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cats_reduce.cpp", "max_issues_repo_name": "opensciencehack/Fork-of-Team-TimSort", "max_issues_repo_head_hexsha": "90c44752af9932ce2f4c6c617842fb75f4a60941", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cats_reduce.cpp", "max_forks_repo_name": "opensciencehack/Fork-of-Team-TimSort", "max_forks_repo_head_hexsha": "90c44752af9932ce2f4c6c617842fb75f4a60941", "max_forks_repo_licenses": ["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.1333333333, "max_line_length": 172, "alphanum_fraction": 0.6716772152, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.5095980101306408}}
{"text": "#include <Eigen/Core>\r\n#include <Eigen/Eigenvalues>\r\n\r\n    #include <iostream>\r\n\r\n    #include <iomanip>\r\n    #include \"riemann_filter.h\"\r\n\r\n    bool debug=0;\r\n    bool debug2=0;\r\n\r\n    #define halfpi 3.141593f/2.f\r\n    #define c_speed  299792458\r\n    #define max_nop 8\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\nnamespace {\r\n\r\nconstexpr float b = 1.f;\r\nconstexpr float d = 1.e4f;\r\nint nop;\r\n\r\ntypedef Matrix<float, Dynamic, Dynamic, 0, max_nop, max_nop> MatrixNf;\r\ntypedef Matrix<float, Dynamic, Dynamic, 0, 2*max_nop, 2*max_nop> Matrix2Nf;\r\ntypedef Matrix<float, Dynamic, Dynamic, 0, 3*max_nop, 3*max_nop> Matrix3Nf;\r\ntypedef Matrix<float, Dynamic, 1, 0, max_nop, 1> VectorNf;\r\ntypedef Matrix<float, Dynamic, 1, 0, 2*max_nop, 1> Vector2Nf;\r\ntypedef Matrix<float, Dynamic, 1, 0, 3*max_nop, 1> Vector3Nf;\r\ntypedef Matrix<float, 2, Dynamic, 0, 2, max_nop> Matrix2xNf;\r\ntypedef Matrix<float, 3, Dynamic, 0, 3, max_nop> Matrix3xNf;\r\ntypedef Matrix<float, 5, 5> Matrix5f;\r\ntypedef Matrix<float, 5, 1> Vector5f;\r\n\r\nstruct circle_fit{\r\nVector3f par;\r\nMatrix3f cov;\r\nint charge;\r\nfloat chi2;\r\n};\r\n\r\nstruct line_fit{\r\nVector2f par;\r\nMatrix2f cov;\r\nfloat chi2;\r\n};\r\n\r\nstruct helix_fit{\r\nVector5f par;\r\nMatrix5f cov;\r\nint charge;\r\nfloat chi2;\r\n};\r\n\r\nstruct scatter{\r\n    float p;\r\n    float theta;\r\n    float X;\r\n};\r\n\r\ninline float sqr(float a){\r\nreturn a*a;\r\n}\r\n\r\n//only barrel ! TO FIX\r\nMatrixNf Scatter_cov_rad (Matrix2xNf p2D, scatter MS){\r\n    VectorNf rad = (p2D.row(0).array().square() + p2D.row(1).array().square()).sqrt();\r\n    MatrixNf scatter_cov_rad = MatrixXf::Zero(nop,nop);\r\n    float sig2 = sqr(0.015/MS.p *sqr(MS.X/cos(MS.theta))*(1+0.038*log(MS.X/cos(MS.theta))));\r\n    for(int k=0; k<nop; k++){\r\n        for(int l=k; l<nop; l++){\r\n            for(int i=0; i<min(k,l); i++){\r\n                scatter_cov_rad(k,l) += (rad(k)-rad(i))*(rad(l)-rad(i))*sig2/sqr(sin(MS.theta));\r\n                scatter_cov_rad(l,k) = scatter_cov_rad(k,l);\r\n            }\r\n        }\r\n    }\r\n    return scatter_cov_rad;\r\n}\r\n\r\nMatrix2Nf cov_radtocart (Matrix2xNf p2D, MatrixNf cov_rad){\r\n    Matrix2Nf cov_cart=MatrixXf::Zero(2*nop,2*nop);\r\n    VectorNf rad = (p2D.row(0).array().square() + p2D.row(1).array().square()).sqrt();\r\n    for(int k=0; k<nop; k++){\r\n        for(int l=k; l<nop; l++){\r\n            cov_cart(k,l) = cov_rad(k,l)*p2D(1,k)/rad(k)*p2D(1,l)/rad(l);\r\n            cov_cart(k+nop,l+nop) = cov_rad(k,l)*p2D(0,k)/rad(k)*p2D(0,l)/rad(l);\r\n            cov_cart(k,l+nop) = -cov_rad(k,l)*p2D(1,k)/rad(k)*p2D(0,l)/rad(l);\r\n            cov_cart(k+nop,l) = -cov_rad(k,l)*p2D(0,k)/rad(k)*p2D(1,l)/rad(l);\r\n            cov_cart(l,k) = cov_cart(k,l);\r\n            cov_cart(l+nop,k+nop) = cov_cart(k+nop,l+nop);\r\n            cov_cart(l+nop,k) = cov_cart(k,l+nop);\r\n            cov_cart(l,k+nop) = cov_cart(k+nop,l);\r\n        }\r\n    }\r\n    return cov_cart;\r\n}\r\n\r\nMatrixNf cov_carttorad (Matrix2xNf p2D, Matrix2Nf cov_cart){ //only diagonal terms\r\n    MatrixNf cov_rad=MatrixXf::Zero(nop,nop);\r\n    VectorNf rad2 = p2D.row(0).array().square() + p2D.row(1).array().square();\r\n    for(int i=0; i<nop; i++){\r\n        cov_rad(i,i) = (cov_cart(i,i)*sqr(p2D(1,i)) + cov_cart(i+nop,i+nop)*sqr(p2D(0,i))\r\n            - 2.f*cov_cart(i,i+nop)*p2D(0,i)*p2D(1,i))/rad2(i);\r\n        if(rad2(i)<1e-4) cov_rad(i,i) = cov_cart(i,i); //TO FIX\r\n    }\r\n    return cov_rad;\r\n}\r\n\r\nVectorNf Weight(Matrix2xNf p2D, MatrixNf cov_rad_inv){\r\n    VectorNf weight(nop);\r\n    for(int i=0; i<nop; i++){\r\n        weight(i) = cov_rad_inv.col(i).sum();\r\n    }\r\n    return weight;\r\n}\r\n\r\nfloat chi2_circle(Matrix2xNf p2D, Matrix2Nf V, Vector3f par_uvr){\r\n    float chi2 = 0;\r\n    for(int i=0; i<nop; i++){\r\n        float x_ = p2D(0,i)-par_uvr(0);\r\n        float y_ = p2D(1,i)-par_uvr(1);\r\n        float x_2 = sqr(x_);\r\n        float y_2 = sqr(y_);\r\n        chi2 += sqr(sqrt(x_2+y_2)-par_uvr(2))/((V(i,i)*x_2+V(i+nop,i+nop)*y_2+2*V(i,i+nop)*x_*y_)/(x_2+y_2));\r\n    }\r\n    return chi2;\r\n}\r\n\r\nfloat chi2_line(Matrix2xNf p2D, VectorNf y_err2, Vector2f par_line){\r\n    float chi2 = 0;\r\n        for(int i=0; i<nop; i++){\r\n        chi2 += sqr(p2D(1,i)-p2D(0,i)*par_line(0)-par_line(1)) / (1+sqr(par_line(0)))\r\n                / (y_err2(i)*sqr(cos(atan(par_line(0)))) + y_err2(i)*sqr(sin(atan(par_line(0)))));\r\n    }\r\n    return chi2;\r\n}\r\n\r\ninline int Charge (Matrix2xNf p2D, Vector3f par_uvr) { //error to be computed TO FIX\r\n    float dir = (p2D(0,1)-p2D(0,0))*(par_uvr(1)-p2D(1,0))-(p2D(1,1)-p2D(1,0))*(par_uvr(0)-p2D(0,0));\r\n    return (dir > 0) ? -1 : 1;\r\n}\r\n\r\nVector3f par_transformation(Vector3f par_uvr, int charge, float B_field){\r\n    Vector3f par_pak;\r\n    float phi = (charge > 0) ? atan2(par_uvr(0), -par_uvr(1)) : atan2(-par_uvr(0), par_uvr(1));\r\n    par_pak <<  phi,\r\n                charge * (sqrt(sqr(par_uvr(0))+sqr(par_uvr(1)))-par_uvr(2)),\r\n                par_uvr(2)*B_field;\r\n    return par_pak;\r\n}\r\n\r\n// return the eigenvector associated to the minimum eigenvalue\r\nVector3f min_eigen3D(Matrix3f A){\r\n    EigenSolver<Matrix3f> solver(A); // evaluate eigenvalues and eigenvector\r\n    Vector3cf lambdac = solver.eigenvalues(); //why can't I cast here ??\r\n    Matrix3cf eigenvectc = solver.eigenvectors();\r\n    Vector3f lambda = lambdac.real().cast<float>(); //check if real ! TO FIX\r\n    Matrix3f eigenvect = eigenvectc.real().cast<float>();\r\n    int minindex =0;\r\n    lambda.minCoeff(&minindex);\r\n    Vector3f n = eigenvect.col(minindex);\r\n    return n;\r\n}\r\n\r\nVector2f min_eigen2D(Matrix2f A){\r\n    EigenSolver<Matrix2f> solver(A); // evaluate eigenvalues and eigenvector\r\n    Vector2cf lambdac = solver.eigenvalues(); //why can't I cast here ??\r\n    Matrix2cf eigenvectc = solver.eigenvectors();\r\n    Vector2f lambda = lambdac.real().cast<float>(); //check if real ! TO FIX\r\n    Matrix2f eigenvect = eigenvectc.real().cast<float>();\r\n    int minindex =0;\r\n    lambda.minCoeff(&minindex);\r\n    Vector2f n = eigenvect.col(minindex);\r\n    return n;\r\n}\r\n\r\n//     a       ||   0|   1|   2|   3|   4|   5\r\n// nu(a)=(i,j) || 0,0| 0,1| 0,2| 1,1| 1,2| 2,2\r\ninline int nu(int a, int* i, int* j){\r\n    *i = (a==0 || a==1 || a==2) ? 0 : (a==3 || a==4) ? 1 : (a==5) ? 2 : 3;\r\n    *j = (a==2 || a==4 || a==5) ? 2 : (a==1 || a==3) ? 1 : (a==0) ? 0 : 3;\r\n    if (*i == 3) return 1;\r\n    return 0;\r\n}\r\n\r\n\r\n\r\ncircle_fit Circle_fit(Matrix2xNf p2D, Matrix2Nf V, float B_field,\r\n                      bool return_err = true, bool scattering=true, scatter* MS=nullptr){\r\n\r\n    //INITIALIZATION\r\n\r\n    //SORTING !! TO FIX\r\n    Matrix2xNf p2D_ = p2D;\r\n    Matrix3xNf p3D(3,nop);\r\n\r\n    MatrixNf cov_rad = cov_carttorad(p2D_, V);\r\n    if(scattering && MS != nullptr){\r\n        MatrixNf scatter_cov_rad = Scatter_cov_rad(p2D_, *MS);\r\n        V += cov_radtocart(p2D_, scatter_cov_rad);\r\n        cov_rad += scatter_cov_rad;\r\n    }\r\n    MatrixNf G = cov_rad.inverse();\r\n    G /= G.sum();\r\n    VectorNf weight = Weight(p2D_, G);\r\n    if(debug){\r\n        cout << \"cov_rad:\\n\" << cov_rad << endl << endl;\r\n        cout << \"G:\\n\" << G << endl << endl;\r\n        cout << \"weight:\\n\" << weight.transpose() << endl;\r\n    }\r\n\r\n\r\n    //CENTER & SCALE 2D POINTS\r\n    float umean = p2D.row(0).mean();\r\n    float vmean = p2D.row(1).mean();\r\n    p2D.row(0) = p2D.row(0).array() - umean;\r\n    p2D.row(1) = p2D.row(1).array() - vmean;\r\n    Vector2Nf mc(2*nop);\r\n    mc << p2D.row(0).transpose(), p2D.row(1).transpose(); //useful for error propagation\r\n    float q = p2D.array().square().sum();\r\n    float s = b*sqrt(nop/q); //scaling factor (b is an arbitrary constant)\r\n    p2D *= s;\r\n\r\n    //CALCULATE TRASFORMED POINTS IN 3D\r\n    p3D.block(0,0,2,nop) = p2D;\r\n    p3D.row(2) = p2D.row(0).array().square() + p2D.row(1).array().square();\r\n\r\n    //CALCULATE & MINIMIZE COST FUNCTION\r\n    Matrix3f A = Matrix3f::Zero();\r\n    Vector3f r0 = p3D * weight;\r\n\r\n    Matrix3xNf temp = p3D - r0*RowVectorXf::Constant(nop,1.f);\r\n    A = temp*G*temp.transpose();\r\n\r\n    Vector3f n = min_eigen3D(A);\r\n    n *= (n(2)>0) ? 1 : -1;\r\n    float c = -n.transpose()*r0;\r\n\r\n    //CALCULATE CIRCUMFERENCE PARAMETER\r\n    Vector3f par_uvr_;\r\n        par_uvr_ << -n(0)/(2.f*n(2)),\r\n                    -n(1)/(2.f*n(2)),\r\n                    sqrt((1.f-sqr(n(2))-4.f*c*n(2))/(4.f*sqr(n(2))));\r\n    Vector3f par_uvr;\r\n        par_uvr <<  par_uvr_(0)/s + umean, par_uvr_(1)/s + vmean, par_uvr_(2)/s;\r\n\r\n    circle_fit circle;\r\n    circle.charge = Charge(p2D_, par_uvr);\r\n    circle.par = par_transformation(par_uvr, circle.charge, B_field);\r\n    if(!scattering || (scattering && MS!=nullptr))\r\n        circle.chi2 = chi2_circle(p2D_, V, par_uvr);\r\n\r\n\r\n\r\n    return circle;\r\n}\r\n\r\nline_fit Line_fit (Matrix3xNf p3D, Matrix3Nf V, circle_fit circle,\r\n                   float B_field, bool return_err=true){\r\n\r\n    //INITIALIZATION\r\n    Matrix2xNf p2D(2,nop);\r\n\r\n    //VectorNf x_err2 = X_err(p3D, V, circle);\r\n    VectorNf y_err2 = V.block(2*nop,2*nop,nop,nop).diagonal();\r\n    //float k = x_err2.array().sqrt().mean()/y_err2.array().sqrt().mean();\r\n    //if(debug) cout << \"k:  \" <<  k <<endl;\r\n\r\n    VectorNf weight = 1.f/(y_err2).array();\r\n    weight /= weight.sum();\r\n\r\n    //CALCULATE TRASFORMED POINTS IN 2D\r\n    p2D.row(1) = p3D.row(2);\r\n    //p2D.row(0) = p3D.row(1);\r\n    Matrix<float, 1, Dynamic> ciccio=((p3D.row(0).array() - cos(circle.par(0)-halfpi)*circle.par(1)).square()\r\n        + (p3D.row(1).array() - sin(circle.par(0)-halfpi)*circle.par(1)).square()).sqrt()\r\n        / (circle.par(2)/B_field*2.f);\r\n        for(int i=0; i<nop; i++){\r\n            if(ciccio(i) < -1) ciccio(i)=-1.f;\r\n            else if(ciccio(i) >1) ciccio(i)=1.f;\r\n        }\r\n\r\n    p2D.row(0) = 2.f*asin(ciccio.array())*(circle.par(2)/B_field);\r\n\r\n    //CALCULATE & MINIMIZE COST FUNCTION\r\n    Matrix2f A = Matrix2f::Zero();\r\n    Vector2f r0 = p2D * weight;\r\n\r\n    for (int i=0; i<nop; i++) A += weight(i)*((p2D.col(i)-r0)*(p2D.col(i)-r0).transpose());\r\n\r\n    Vector2f n = min_eigen2D(A);\r\n    float c = -n.transpose()*r0;\r\n\r\n    //CALCULATE LINE PARAMETER\r\n    line_fit line;\r\n    line.par << -n(0)/n(1), -c*sqrt(sqr(n(0))+sqr(n(1)))/n(1);\r\n    line.chi2 = chi2_line(p2D, y_err2, line.par);\r\n\r\n    //ERROR PROPAGATION\r\n    if(return_err){\r\n        //auxiliary quantities\r\n        float sig2 = y_err2.mean(); //TO FIX\r\n        float S = (A(0,0) + A(1,1))*nop;\r\n        float n0_2 = sqr(n(0));\r\n        float n1_2 = sqr(n(1));\r\n        float sqrt_ = sqrt(n1_2+n0_2);\r\n        float x_ =  p2D.row(0).sum()/nop;\r\n        float y_ =  p2D.row(1).sum()/nop;\r\n        float corr = sqr(1.131); //TO FIX\r\n        float C13 = sig2*n(1)*(n(0)*y_-n(1)*x_)/S;\r\n        float C23 =-sig2*n(0)*(n(0)*y_-n(1)*x_)/S;\r\n        float C33 = corr*sig2*sqr(1/nop + n(0)*y_-n(1)*x_)/S;\r\n        Matrix3f C;\r\n        C <<    sig2*n1_2/S, -sig2*n(0)*n(1)/S, C13,\r\n                -sig2*n(0)*n(1)/S, sig2*n0_2/S, C23,\r\n                C13, C23, C33;\r\n\r\n        Matrix<float, 2, 3> J;\r\n        J <<    -1.f/n(1), n(0)/n1_2, 0,\r\n                -c*n(0)/(n(1)*sqrt_), n0_2*c/(n1_2*sqrt_), -sqrt_/n(1);\r\n\r\n        line.cov = J * C * J.transpose();\r\n    }\r\n\r\n    return line;\r\n}\r\n\r\nhelix_fit Helix_fit(Matrix3xNf hits, Matrix3Nf hits_cov, float B_field,\r\n                    bool return_err=true, bool scattering=true){\r\n    nop = hits.cols();\r\n    circle_fit circle;\r\n    line_fit line;\r\n    scatter MS;\r\n    if(scattering){\r\n        circle = Circle_fit(hits.block(0,0,2,nop), hits_cov.block(0,0,2*nop,2*nop),\r\n                            B_field, false, true, nullptr);\r\n        line = Line_fit(hits, hits_cov, circle, B_field, false);\r\n        MS.theta = atan(1/line.par(0));\r\n        MS.p = circle.par(2)/cos(MS.theta);\r\n        MS.X = 0.04f;\r\n    }\r\n    circle = Circle_fit(hits.block(0,0,2,nop), hits_cov.block(0,0,2*nop,2*nop),\r\n                        B_field, return_err, scattering, &MS);\r\n    line = Line_fit(hits, hits_cov, circle, B_field, return_err);\r\n    helix_fit helix;\r\n    helix.par << circle.par, line.par;\r\n    helix.cov = MatrixXf::Zero(5,5);\r\n    if(return_err){\r\n        helix.cov.block(0,0,3,3) = circle.cov;\r\n        helix.cov.block(3,3,2,2) = line.cov;\r\n    }\r\n    helix.charge = circle.charge;\r\n    helix.chi2 = circle.chi2 + line.chi2;\r\n    return helix;\r\n}\r\n\r\n}\r\n\r\n\r\n\r\nbool havesamephi(Vector3f p1, Vector3f p2, float phiCut){\r\n    Vector2f p1_ = p1.block(0,0,2,1);\r\n    Vector2f p2_ = p2.block(0,0,2,1);\r\n    return (((p1_.transpose()*p2_)/(p1_.norm()*p2_.norm())).norm() > phiCut);\r\n}\r\n\r\nbool areAlignedRZ(const float r1, const float z1,const float r2,const float z2,const float r3,const float z3, float ptmin, float thetaCut)\r\n    {\r\n        float radius_diff = std::abs(r1 - r3);\r\n        float distance_13_squared = radius_diff*radius_diff + (z1 - z3)*(z1 - z3);\r\n\r\n        float pMin = ptmin*std::sqrt(distance_13_squared); //this needs to be divided by radius_diff later\r\n\r\n        float tan_12_13_half_mul_distance_13_squared = fabs(z1 * (r2 - r3) + z2 * (r3 - r1) + z3 * (r1 - r2)) ;\r\n        return tan_12_13_half_mul_distance_13_squared * pMin <= thetaCut * distance_13_squared * radius_diff;\r\n    }\r\n\r\nvoid findTps(const vector< event_t>& events, vector < vector <vector <array <int,4>>>>& tracking_particles){\r\n    for (int event_id=0; event_id <events.size(); event_id++){\r\n        for(unsigned int offset=0; offset<4; offset++){\r\n            int first_lid = offset;\r\n            for(unsigned int i=0; i<events[event_id][first_lid].size(); i++){\r\n                if(events[event_id][first_lid][i].inner_tp == events[event_id][first_lid][i].outer_tp){\r\n                    for(unsigned int j=0; j<events[event_id][first_lid+1].size(); j++){\r\n                        if( events[event_id][first_lid][i].outer_tp == events[event_id][first_lid+1][j].inner_tp &&\r\n                            events[event_id][first_lid+1][j].inner_tp == events[event_id][first_lid+1][j].outer_tp){\r\n                            for(unsigned int k=0; k<events[event_id][first_lid+2].size(); k++){\r\n                                if(events[event_id][first_lid+1][j].outer_tp == events[event_id][first_lid+2][k].inner_tp &&\r\n                                    events[event_id][first_lid+2][k].inner_tp == events[event_id][first_lid+2][k].outer_tp){\r\n                                        tracking_particles[event_id][first_lid].emplace_back(array<int, 4>{{events[event_id][first_lid][i].inner_tp, i, j, k}});\r\n                                    //cout << tracking_particles[event_id][first_lid].back()[0] << endl;\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nvoid track_part(const vector <event_t> &events,  vector <vector <vector <array<int,4>>>> &tracking_particles, ofstream & myfile){\r\n    findTps(events, tracking_particles);\r\n    for (int ev_id=0; ev_id<tracking_particles.size(); ev_id++){\r\n\r\n        for(unsigned int offset=0; offset<4; offset++){\r\n            int first_lid = offset;\r\n             sort(tracking_particles[ev_id][offset].begin(),tracking_particles[ev_id][offset].end(),[] (const array<int,4>& a, const array<int,4>& b ) { return a[0]< b[0]; } );\r\n             tracking_particles[ev_id][offset].erase(unique(tracking_particles[ev_id][offset].begin(),tracking_particles[ev_id][offset].end(),\r\n                                                            [] (const array<int,4>& a, const array<int,4>& b ) { return a[0]== b[0]; } ),\r\n                                                    tracking_particles[ev_id][offset].end());\r\n                    }\r\n                }\r\n\r\n    for (int ev_id=0; ev_id<tracking_particles.size(); ev_id++){\r\n        for(unsigned int offset=0; offset<4; offset++){\r\n            int first_lid = offset;\r\n            for(unsigned int tp=0; tp<tracking_particles[ev_id][offset].size(); tp++){\r\n             myfile << ev_id << \"  \" << first_lid << \" \" << tracking_particles[ev_id][offset][tp][0] << endl;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nint main(){\r\n    ofstream myfile(\"tracking_particles.txt\", ofstream::out);\r\n    ofstream comecazzovuoi(\"fileditesto.txt\", ofstream::out);\r\n    vector <event_t> events;\r\n    vector <vector <vector <array<int,4>>>> tracking_particles;\r\n    ciccio(\"data.csv\", events);\r\n    Matrix<float, 3, 7> hit;\r\n    Matrix<float, 21, 21> cov=MatrixXf::Zero(21,21);\r\n    Vector3f zero; zero << 0,0,0;\r\n    unsigned long long int counter=0;\r\n    tracking_particles.resize(events.size());\r\n    for(auto& tp:tracking_particles){\r\n        tp.resize(4);\r\n    }\r\n\r\n    track_part(events, tracking_particles, myfile);\r\n\r\n for (auto& ev: events){\r\n\r\n        for(unsigned int offset=0; offset<4; offset++){\r\n            int first_lid = offset;\r\n            //int first_lid=0;\r\n            //int i=3194; int j=1363; int k=576;\r\n            for(unsigned int i=0; i<ev[first_lid].size(); i++){\r\n                if(i%10==0){\r\n                unsigned long long int index = (unsigned long long int)i*ev[first_lid+1].size()*ev[first_lid+2].size();\r\n                cout << \"processed: \" << counter << \"    \" <<  index << endl;\r\n                }\r\n                float r1 = sqrt(sqr(ev[first_lid][i].point1(0))+sqr(ev[first_lid][i].point1(1)));\r\n                for(unsigned int j=0; j<ev[first_lid+1].size(); j++){\r\n                    if(havesamephi(ev[first_lid][i].point1,ev[first_lid+1][j].point1,0.9f)){\r\n                        float r2 = sqrt(sqr(ev[first_lid+1][j].point1(0))+sqr(ev[first_lid+1][j].point1(1)));\r\n\r\n                        for(unsigned int k=0; k<ev[first_lid+2].size(); k++){\r\n                            if(havesamephi(ev[first_lid+1][j].point1,ev[first_lid+2][k].point1,0.9f)){\r\n                                float r3 = sqrt(sqr(ev[first_lid+2][k].point1(0))+sqr(ev[first_lid+2][k].point1(1)));\r\n\r\n                                if(areAlignedRZ(r1, ev[first_lid][i].point1(2), r2, ev[first_lid+1][j].point1(2),r3, ev[first_lid+2][k].point1(2),0.5f, 0.01)){\r\n\r\n                                    counter++;\r\n                                    hit <<  zero, ev[first_lid][i].point1, ev[first_lid][i].point2, ev[first_lid+1][j].point1,\r\n                                            ev[first_lid+1][j].point2,ev[first_lid+2][k].point1, ev[first_lid+2][k].point2;\r\n\r\n                                    cov(0,0)=0.1;\r\n                                    cov(1,1)=0.1;\r\n                                    cov(2,2)=5;\r\n                                    for(int z=0; z < 3; z++){\r\n                                         cov(6*z+3,6*z+3) = ev[first_lid][i].err_point1(z);\r\n                                         cov(6*z+4,6*z+4) = ev[first_lid][i].err_point2(z);\r\n                                         cov(6*z+5,6*z+5) = ev[first_lid+1][j].err_point1(z);\r\n                                         cov(6*z+6,6*z+6) = ev[first_lid+1][j].err_point2(z);\r\n                                         cov(6*z+7,6*z+7) = ev[first_lid+2][k].err_point1(z);\r\n                                         cov(6*z+8,6*z+8) = ev[first_lid+2][k].err_point2(z);\r\n                                    }\r\n                                    cov.array().square();\r\n\r\n                                    helix_fit helix = Helix_fit(hit, cov, 3.8*c_speed/pow(10,9)/100, false, false);\r\n                                    //cout << i << \" \" << j << \"  \" << k << endl;\r\n                                    if(helix.chi2 < 100){\r\n                                        //cout << ev[first_lid][i].inner_tp   << \"   \" << helix.chi2 << endl;\r\n                                        comecazzovuoi  << ev[first_lid][i].inner_tp   << \"   \"\r\n                                                << ev[first_lid][i].outer_tp    << \"   \"\r\n                                                << ev[first_lid+1][j].inner_tp  << \"   \"\r\n                                                << ev[first_lid+1][j].outer_tp  << \"   \"\r\n                                                << ev[first_lid+2][k].inner_tp  << \"   \"\r\n                                                << ev[first_lid+2][k].outer_tp  << \"   \" << helix.chi2 << endl;\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\ncomecazzovuoi.close();\r\nmyfile.close();\r\n\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "64be65f94fb26489621a733bedd1c6a4c0cbdfdd", "size": 20248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "felicepantaleo/RiemannFit", "max_stars_repo_head_hexsha": "61fc23feb834dddabe4ad37e5352c8ff6d913fb9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T14:22:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-11T14:22:54.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "felicepantaleo/RiemannFit", "max_issues_repo_head_hexsha": "61fc23feb834dddabe4ad37e5352c8ff6d913fb9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "felicepantaleo/RiemannFit", "max_forks_repo_head_hexsha": "61fc23feb834dddabe4ad37e5352c8ff6d913fb9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7799607073, "max_line_length": 177, "alphanum_fraction": 0.527360727, "num_tokens": 6363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.5095980029882732}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\ntemplate <typename Matrix, typename Reorder>\nvoid test_rows(const Matrix& A, const Reorder& r)\n{\n    typedef typename mtl::Collection<Matrix>::value_type   value_type;\n    Matrix BB(reorder_matrix_rows(r, A));\n    cout << \"\\nreorder_matrix_rows(A) =\\n\" << BB;\n    MTL_THROW_IF(BB[1][0] != value_type(4.), mtl::runtime_error(\"Wrong value after row reordering!\"));\n}\n\ntemplate <typename Reorder, typename Value, typename Parameters>\nvoid test_rows(const mtl::compressed2D<Value, Parameters>&, const Reorder&) {}\n\n\ntemplate <typename Matrix>\nvoid test(Matrix& A, const char* name)\n{\n    typedef typename mtl::Collection<Matrix>::value_type   value_type;\n    \n    value_type array[][3]= {{1., 2., 3.}, {4., 5., 6.}, {7., 8., 9.}};\n    A= array;\n\n    cout << \"\\n\" << name << \"\\n\" << \"A =\\n\" << A;\n\n    int reordering[]= {2, 1};\n    mtl::mat::traits::reorder<>::type  R= mtl::mat::reorder(reordering);\n    cout << \"\\nR =\\n\" << R;    \n\n    Matrix B(R * A);\n    cout << \"\\nB= R * A =\\n\" << B;\n    \n    MTL_THROW_IF(B[1][0] != value_type(4.), mtl::runtime_error(\"Wrong value after row reordering!\"));\n\n    test_rows(A, reordering);\n    Matrix B2(B * trans(R));\n    cout << \"\\nB * trans(R) =\\n\" << B2;\n    \n    MTL_THROW_IF(B2[1][0] != value_type(6.), mtl::runtime_error(\"Wrong value after column reordering!\"));    \n}\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n    dense2D<double>                                      dr;\n    dense2D<double, mat::parameters<col_major> >      dc;\n    morton_dense<double, recursion::morton_z_mask>       mzd;\n    morton_dense<double, recursion::doppled_2_row_mask>  d2r;\n    compressed2D<double>                                 cr;\n    compressed2D<double, mat::parameters<col_major> > cc;\n\n    dense2D<complex<double> >                            drc;\n    compressed2D<complex<double> >                       crc;\n\n    test(dr, \"Dense row major\");\n    test(dc, \"Dense column major\");\n    test(mzd, \"Morton Z-order\");\n    test(d2r, \"Hybrid 2 row-major\");\n    test(cr, \"Compressed row major\");\n    test(cc, \"Compressed column major\");\n    test(drc, \"Dense row major complex\");\n    test(crc, \"Compressed row major complex\");\n\n\t\n    return 0;\n}\n", "meta": {"hexsha": "b9d341b12bcac392dd2f07c45781328df7fca03d", "size": 2699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/reorder_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/reorder_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/reorder_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": 32.130952381, "max_line_length": 109, "alphanum_fraction": 0.6150426084, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5095479864338989}}
{"text": "#include <tiny_functions.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\nBOOST_AUTO_TEST_SUITE(tiny_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 = tiny::clamp(1.5, min_val, max_val);\n    BOOST_CHECK( clamped_val == 1.5 );\n\n    clamped_val = tiny::clamp(-1.5, min_val, max_val);\n    BOOST_CHECK( clamped_val == min_val );\n\n    clamped_val = tiny::clamp(3.0, min_val, max_val);\n    BOOST_CHECK( clamped_val == max_val );\n\n\n    // clamp minimum tests\n    clamped_val = tiny::clamp_min(1.5, min_val);\n    BOOST_CHECK( clamped_val == 1.5 );\n\n    clamped_val = tiny::clamp_min(-1.5, min_val);\n    BOOST_CHECK( clamped_val == min_val );\n\n    clamped_val = tiny::clamp_min(3.0, min_val);\n    BOOST_CHECK( clamped_val == 3.0 );\n\n\n    // clamp maximum tests\n    clamped_val = tiny::clamp_max(1.5, max_val);\n    BOOST_CHECK( clamped_val == 1.5 );\n\n    clamped_val = tiny::clamp_max(-1.5, max_val);\n    BOOST_CHECK( clamped_val == -1.5 );\n\n    clamped_val = tiny::clamp_max(3.0, max_val);\n    BOOST_CHECK( clamped_val == max_val );\n\n\n    // clamp zero..one tests\n    clamped_val = tiny::clamp_zero_one(0.5);\n    BOOST_CHECK( clamped_val == 0.5 );\n\n    clamped_val = tiny::clamp_zero_one(-1.5);\n    BOOST_CHECK( clamped_val == 0.0 );\n\n    clamped_val = tiny::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 = tiny::clamp(1.5f, min_val, max_val);\n    BOOST_CHECK( clamped_val == 1.5f );\n\n    clamped_val = tiny::clamp(-1.5f, min_val, max_val);\n    BOOST_CHECK( clamped_val == min_val );\n\n    clamped_val = tiny::clamp(3.0f, min_val, max_val);\n    BOOST_CHECK( clamped_val == max_val );\n\n\n    // clamp minimum tests\n    clamped_val = tiny::clamp_min(1.5f, min_val);\n    BOOST_CHECK( clamped_val == 1.5f );\n\n    clamped_val = tiny::clamp_min(-1.5f, min_val);\n    BOOST_CHECK( clamped_val == min_val );\n\n    clamped_val = tiny::clamp_min(3.0f, min_val);\n    BOOST_CHECK( clamped_val == 3.0f );\n\n\n    // clamp maximum tests\n    clamped_val = tiny::clamp_max(1.5f, max_val);\n    BOOST_CHECK( clamped_val == 1.5f );\n\n    clamped_val = tiny::clamp_max(-1.5f, max_val);\n    BOOST_CHECK( clamped_val == -1.5f );\n\n    clamped_val = tiny::clamp_max(3.0f, max_val);\n    BOOST_CHECK( clamped_val == max_val );\n\n\n    // clamp zero..one tests\n    clamped_val = tiny::clamp_zero_one(0.5f);\n    BOOST_CHECK( clamped_val == 0.5f );\n\n    clamped_val = tiny::clamp_zero_one(-1.5f);\n    BOOST_CHECK( clamped_val == 0.0f );\n\n    clamped_val = tiny::clamp_zero_one(3.0f);\n    BOOST_CHECK( clamped_val == 1.0f );\n  }\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "7566db0c19d029603938742859098d85f8ce0d03", "size": 2996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_clamp/tiny_clamp.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_clamp/tiny_clamp.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_clamp/tiny_clamp.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2807017544, "max_line_length": 55, "alphanum_fraction": 0.6648865154, "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.5094971911458738}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//  What's in this header: \n//  The frontend of a plan-like FFT interface.\n\n#ifndef BOOST_MATH_DFTAPI_HPP\n  #define BOOST_MATH_DFTAPI_HPP\n\n#include <algorithm>\n#include <vector>\n#include <complex>\n\n// TODO: once this file is split as described inside it, then this include can be removed, because the user code will include the complex type of their choosing and along with the necessary traits.\n#include <boost/math/fft/multiprecision_complex.hpp>\n\n  namespace boost { namespace math { namespace fft { \n  namespace detail {\n\n  // fftw_plan-like Fourier Transform API\n  \n  /*\n    RingType axioms:\n    1. Abelian group addition (operator+)\n      -> closure\n      -> associativity\n      -> neutral element (0)\n      -> inverse (operator-)\n      -> commutativity\n    2. Monoid multiplication (operator*)\n      -> closure\n      -> associativity\n      -> neutral element (1)\n    3. addition and multiplication compatibility\n      -> left distributivity, ie. a*(b+c) == a*b + a*c\n      -> right distributivity, ie. (b+c)*a == b*a + c*a\n  */\n  \n  /*\n    Type A to type B execution API.\n  */\n  template<typename A_t, typename B_t, typename allocator_t>\n  class asymmetric_executor\n  {\n    public:\n    using value_type1 = A_t;\n    using value_type2 = B_t;\n    //using allocator_type1 = allocator_t;\n    //using allocator_type2 = allocator_t;\n    using allocator_type1 = typename std::allocator_traits<allocator_t>::template rebind_alloc<value_type1>;\n    using allocator_type2 = typename std::allocator_traits<allocator_t>::template rebind_alloc<value_type2>;\n    \n    private:\n    \n    using buffer_type1 = std::vector<value_type1,allocator_type1> ;\n    using buffer_type2 = std::vector<value_type2,allocator_type2> ;\n    buffer_type1 my_mem_1;\n    buffer_type2 my_mem_2;\n    \n    public:\n    constexpr asymmetric_executor(const allocator_t& in_alloc = allocator_t{})\n      : my_mem_1(in_alloc), my_mem_2(in_alloc) \n    { }\n    \n    template<typename InputIteratorType,\n             typename OutputIteratorType,\n             typename EngineType >\n    void execute(\n      InputIteratorType in_first, InputIteratorType /* in_last */,\n      OutputIteratorType out,\n      EngineType engine, \n      typename std::enable_if<(   (std::is_convertible<InputIteratorType,  const value_type1*>::value == true)\n                               && (std::is_convertible<OutputIteratorType,       value_type2*>::value == true))>::type* = nullptr)\n    {\n      engine(in_first,out);\n    }\n    \n    template<typename InputIteratorType,\n             typename OutputIteratorType,\n             typename EngineType>\n    void execute(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out,\n      EngineType engine,\n      typename std::enable_if<(   (std::is_convertible<InputIteratorType,  const value_type1*>::value == false)\n                               && (std::is_convertible<OutputIteratorType,       value_type2*>::value == true))>::type* = nullptr)\n    {\n      my_mem_1.resize(std::distance(in_first,in_last));\n      std::copy(in_first, in_last, std::begin(my_mem_1));\n      engine(my_mem_1.data(),out);\n    }\n\n    template<typename InputIteratorType,\n             typename OutputIteratorType,\n             typename EngineType>\n    void execute(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out,\n      EngineType engine,\n      typename std::enable_if<(   (std::is_convertible<InputIteratorType,  const value_type1*>::value == true)\n                               && (std::is_convertible<OutputIteratorType,       value_type2*>::value == false))>::type* = nullptr)\n    {\n      my_mem_2.resize(std::distance(in_first,in_last));\n      engine(in_first,my_mem_2.data());\n      std::copy(std::begin(my_mem_2), std::end(my_mem_2), out);\n    }\n\n    template<typename InputIteratorType,\n             typename OutputIteratorType,\n             typename EngineType>\n    void execute(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out,\n      EngineType engine,\n      typename std::enable_if<(   (std::is_convertible<InputIteratorType,  const value_type1*>::value == false)\n                               && (std::is_convertible<OutputIteratorType,       value_type2*>::value == false))>::type* = nullptr)\n    {\n      my_mem_1.resize(std::distance(in_first,in_last));\n      my_mem_2.resize(my_mem_1.size());\n      std::copy(in_first, in_last, std::begin(my_mem_1));\n      engine(my_mem_1.data(),my_mem_2.data());\n      std::copy(std::begin(my_mem_2),std::end(my_mem_2), out);\n    }\n    \n  };\n  \n  /*\n    Type T to type T execution API.\n  */\n  template<typename A_t, typename allocator_t>\n  class symmetric_executor\n  {\n    public:\n    using value_type = A_t;\n    using allocator_type = allocator_t;\n    \n    private:\n    using buffer_type = std::vector<value_type,allocator_type> ;\n    \n    protected:\n    buffer_type my_mem;\n    \n    public:\n    constexpr symmetric_executor(const allocator_type& in_alloc = allocator_type{})\n      : my_mem(in_alloc)\n    { }\n    \n    template<typename InputIteratorType,\n             typename OutputIteratorType,\n             typename EngineType >\n    void execute(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out,\n      EngineType engine, \n      typename std::enable_if<(   (std::is_convertible<InputIteratorType,  const value_type*>::value == true)\n                               && (std::is_convertible<OutputIteratorType,       value_type*>::value == true))>::type* = nullptr)\n    {\n      engine(in_first,out);\n    }\n    \n    template<typename InputIteratorType,\n             typename OutputIteratorType,\n             typename EngineType>\n    void execute(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out,\n      EngineType engine,\n      typename std::enable_if<(   (std::is_convertible<InputIteratorType,  const value_type*>::value == false)\n                               && (std::is_convertible<OutputIteratorType,       value_type*>::value == true))>::type* = nullptr)\n    {\n      std::copy(in_first, in_last, out);\n      engine(out,out);\n    }\n\n    template<typename InputIteratorType,\n             typename OutputIteratorType,\n             typename EngineType>\n    void execute(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out,\n      EngineType engine,\n      typename std::enable_if<(   (std::is_convertible<InputIteratorType,  const value_type*>::value == true)\n                               && (std::is_convertible<OutputIteratorType,       value_type*>::value == false))>::type* = nullptr)\n    {\n      my_mem.resize(std::distance(in_first,in_last));\n      engine(in_first,my_mem.data());\n      std::copy(std::begin(my_mem), std::end(my_mem), out);\n    }\n\n    template<typename InputIteratorType,\n             typename OutputIteratorType,\n             typename EngineType>\n    void execute(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out,\n      EngineType engine,\n      typename std::enable_if<(   (std::is_convertible<InputIteratorType,  const value_type*>::value == false)\n                               && (std::is_convertible<OutputIteratorType,       value_type*>::value == false))>::type* = nullptr)\n    {\n      my_mem.resize(std::distance(in_first,in_last));\n      std::copy(in_first, in_last, std::begin(my_mem));\n      engine(my_mem.data(),my_mem.data());\n      std::copy(std::begin(my_mem),std::end(my_mem), out);\n    }\n    \n  };\n  \n  template< template<class ... Args> class BackendType, class T, class allocator_t >\n  class algebraic_dft : \n        public BackendType<T,allocator_t> , \n        public symmetric_executor<T,allocator_t>\n  {\n    public:\n    using value_type      = T;\n    using allocator_type  = allocator_t;\n    \n    using backend         = BackendType<value_type,allocator_type>;\n    using executor        = symmetric_executor<value_type,allocator_type>;\n    \n    template<class U, class A>\n    using other = algebraic_dft<BackendType,U,A>;\n    \n    private:\n    allocator_type alloc;\n    value_type root,inverse_root;\n    \n  public:\n    using backend::size;\n    using backend::resize;\n    \n    // complex types ctor. n: the size of the dft\n    constexpr algebraic_dft(unsigned int n, value_type w, const allocator_type& in_alloc = allocator_type{} )\n      : backend(n,in_alloc), \n        executor(in_alloc), \n        alloc{in_alloc} ,\n        root{w},\n        inverse_root{ backend::inverse_root(w) }\n    { }\n\n    template<typename InputIteratorType,\n             typename OutputIteratorType>\n    void forward(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out)\n    {\n      resize(std::distance(in_first,in_last));\n      executor::execute(in_first,in_last,out,\n        [this](const value_type* i, value_type* o)\n        {\n          backend::dft(i,o,root);\n        });\n    }\n\n    template<typename InputIteratorType,\n             typename OutputIteratorType>\n    void backward(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out)\n    {\n      resize(std::distance(in_first,in_last));\n      executor::execute(in_first,in_last,out,\n        [this](const value_type* i, value_type* o)\n        {\n          backend::dft(i,o,inverse_root);\n        });\n    }\n  };\n  \n  template< template<class ... Args> class BackendType, class T, class allocator_t >\n  class complex_dft : \n        public BackendType<T,allocator_t> , \n        public symmetric_executor<T,allocator_t>\n  {\n    public:\n    using complex_type    = T;\n    using real_type       = typename T::value_type;\n    using allocator_type  = allocator_t;\n    \n    using value_type      = complex_type;\n    \n    using backend         = BackendType<complex_type,allocator_type>;\n    using executor_C2C    = symmetric_executor<complex_type,allocator_type>;\n    \n    template<class U, class A>\n    using other = complex_dft<BackendType,U,A>;\n    \n    private:\n    allocator_type alloc;\n    \n  public:\n    using backend::size;\n    using backend::resize;\n\n    // complex types ctor. n: the size of the dft\n    constexpr complex_dft(unsigned int n, const allocator_type& in_alloc = allocator_type{} )\n      : backend(n,in_alloc), \n        executor_C2C(in_alloc), \n        alloc{in_alloc} { }\n\n    template<typename InputIteratorType,\n             typename OutputIteratorType>\n    void forward(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out)\n    {\n      resize(std::distance(in_first,in_last));\n      executor_C2C::execute(in_first,in_last,out,\n        [this](const complex_type* i, complex_type* o)\n        {\n          backend::forward(i,o);\n        });\n    }\n\n    template<typename InputIteratorType,\n             typename OutputIteratorType>\n    void backward(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out)\n    {\n      resize(std::distance(in_first,in_last));\n      executor_C2C::execute(in_first,in_last,out,\n        [this](const complex_type* i, complex_type* o)\n        {\n          backend::backward(i,o);\n        });\n    }\n  };\n  \n  template< template<class ... Args> class BackendType, class T, class allocator_t >\n  class real_dft : \n        public BackendType<T,allocator_t> , \n        public symmetric_executor<T,allocator_t>\n  {\n    public:\n    using value_type      = T;\n    using real_type       = T;\n    using complex_type    = boost::multiprecision::complex<T>;\n    using allocator_type  = allocator_t;\n    \n    using backend         = BackendType<real_type,allocator_type>;\n    using executor_halfcomplex = symmetric_executor<real_type,allocator_type>;\n    \n    template<class U, class A>\n    using other = real_dft<BackendType,U,A>;\n    \n    private:\n    allocator_type alloc;\n    \n    template<typename InputIteratorType>\n    void encode_halfcomplex(\n      InputIteratorType in_first, InputIteratorType in_last,\n      real_type* out) const\n    {\n      unsigned int i=0,j=size();\n      {\n        *out = in_first->real();\n        ++in_first, ++out, ++i; --j;\n      }\n      while(i<=j)\n      {\n        *out = in_first->real();\n        ++in_first, ++out, ++i, --j;\n      }\n      while(j>0)\n      {\n        *out = in_first->imag();\n        ++in_first, ++out, ++i, --j;\n      }\n    }\n    template<typename OutputIteratorType>\n    void decode_halfcomplex(\n      const real_type *in_first, const real_type* in_last, \n      OutputIteratorType out) const\n    {\n      using complex_type = typename std::iterator_traits<OutputIteratorType>::value_type;\n      \n      real_type const * const zeroth = in_first;\n      \n      {\n        *out = *in_first;\n        ++out, ++in_first; --in_last;\n      }\n      while(in_first < in_last)\n      {\n        *out = complex_type{*in_first, - *in_last};\n        ++out, ++in_first; --in_last;\n      }\n      if(in_first == in_last)\n      {\n        *out = *in_first;\n        ++out, ++in_first; --in_last;\n      }\n      while(in_last>zeroth)\n      {\n        *out = complex_type{*in_last,*in_first};\n        ++out, ++in_first; --in_last;\n      }\n   } \n    using executor_halfcomplex::my_mem;\n    \n  public:\n    using backend::size;\n    \n    void resize(std::size_t n)\n    {\n        backend::resize(n);\n        my_mem.resize(n);\n    }\n    \n    // complex types ctor. n: the size of the dft\n    constexpr real_dft(unsigned int n, const allocator_type& in_alloc = allocator_type{} )\n      : backend(n,in_alloc), \n        executor_halfcomplex(in_alloc), \n        alloc{in_alloc} { }\n\n    template<typename InputIteratorType,\n             typename OutputIteratorType>\n    void real_to_halfcomplex(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out)\n    {\n      resize(std::distance(in_first,in_last));\n      executor_halfcomplex::execute(in_first,in_last,out,\n        [this](const real_type* i, real_type* o)\n        {\n          backend::real_to_halfcomplex(i,o);\n        });\n    }\n    template<typename InputIteratorType,\n             typename OutputIteratorType>\n    void halfcomplex_to_real(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out)\n    {\n      resize(std::distance(in_first,in_last));\n      executor_halfcomplex::execute(in_first,in_last,out,\n        [this](const real_type* i, real_type* o)\n        {\n          backend::halfcomplex_to_real(i,o);\n        });\n    }\n    \n    template<typename InputIteratorType,\n             typename OutputIteratorType>\n    void real_to_complex(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out)\n    {\n      resize(std::distance(in_first,in_last));\n      \n      executor_halfcomplex::execute(\n        in_first,in_last,\n        my_mem.data(),\n        [this](const real_type* i, real_type* o)\n        {\n          backend::real_to_halfcomplex(i,o);\n        });\n      \n      decode_halfcomplex(\n        my_mem.data(),\n        my_mem.data()+size(),\n        out);\n    }\n\n    template<typename InputIteratorType,\n             typename OutputIteratorType>\n    void complex_to_real(\n      InputIteratorType in_first, InputIteratorType in_last,\n      OutputIteratorType out)\n    {\n      resize(std::distance(in_first,in_last));\n      \n      encode_halfcomplex(\n        in_first,\n        in_last,\n        my_mem.data());\n      \n      executor_halfcomplex::execute(\n        my_mem.data(),\n        my_mem.data()+size(),\n        out,\n        [this](const real_type* i, real_type* o)\n        {\n          backend::halfcomplex_to_real(i,o);\n        });\n    }\n    \n  };\n  \n  } // namespace detail\n  \n  template< class dft_plan_t >\n  struct transform\n  {\n    \n    template<class RingType, class allocator_t = std::allocator<RingType> >\n    using plan_type = typename dft_plan_t::template other< RingType,allocator_t > ;\n    \n    \n    // std::transform-like Fourier Transform API\n    // for complex types\n    template<typename InputIterator,\n             typename OutputIterator>\n    static void forward(InputIterator  input_begin,\n                     InputIterator  input_end,\n                     OutputIterator output)\n    {\n      using input_value_type  = typename std::iterator_traits<InputIterator >::value_type;\n      plan_type<input_value_type> plan(static_cast<unsigned int>(std::distance(input_begin, input_end)));\n      plan.forward(input_begin, input_end, output);\n    }\n  \n    // std::transform-like Fourier Transform API\n    // for complex types\n    template<typename InputIterator,\n             typename OutputIterator>\n    static void backward(InputIterator  input_begin,\n                      InputIterator  input_end,\n                      OutputIterator output)\n    {\n      using input_value_type  = typename std::iterator_traits<InputIterator >::value_type;\n      plan_type<input_value_type> plan(static_cast<unsigned int>(std::distance(input_begin, input_end)));\n      plan.backward(input_begin, input_end, output);\n    }\n    \n    // std::transform-like Fourier Transform API\n    // for Ring types\n    template<typename InputIterator,\n             typename OutputIterator,\n             typename value_type>\n    static void forward(InputIterator  input_begin,\n                     InputIterator  input_end,\n                     OutputIterator output,\n                     value_type w)\n    {\n      using input_value_type  = typename std::iterator_traits<InputIterator >::value_type;\n      plan_type<input_value_type> plan(static_cast<unsigned int>(std::distance(input_begin, input_end)),w);\n      plan.forward(input_begin, input_end, output);\n    }\n  \n    // std::transform-like Fourier Transform API\n    // for Ring types\n    template<typename InputIterator,\n             typename OutputIterator,\n             typename value_type>\n    static void backward(InputIterator  input_begin,\n                      InputIterator  input_end,\n                      OutputIterator output,\n                      value_type w)\n    {\n      using input_value_type  = typename std::iterator_traits<InputIterator >::value_type;\n      plan_type<input_value_type> plan(static_cast<unsigned int>(std::distance(input_begin, input_end)),w);\n      plan.backward(input_begin, input_end, output);\n    }\n    \n    // std::transform-like Fourier Transform API\n    // for real types\n    template<typename InputIterator,\n             typename OutputIterator>\n    static void real_to_complex(\n                     InputIterator  input_begin,\n                     InputIterator  input_end,\n                     OutputIterator output)\n    {\n      using input_value_type  = typename std::iterator_traits<InputIterator >::value_type;\n      // using output_value_type = typename std::iterator_traits<OutputIterator>::value_type;\n      plan_type<input_value_type> plan(static_cast<unsigned int>(std::distance(input_begin, input_end)));\n      plan.real_to_complex(input_begin, input_end, output);\n    }\n  \n    // std::transform-like Fourier Transform API\n    // for real types\n    template<typename InputIterator,\n             typename OutputIterator>\n    static void complex_to_real(InputIterator  input_begin,\n                      InputIterator  input_end,\n                      OutputIterator output)\n    {\n      using input_value_type  = typename std::iterator_traits<InputIterator >::value_type;\n      // using output_value_type = typename std::iterator_traits<OutputIterator>::value_type;\n      plan_type<input_value_type> plan(static_cast<unsigned int>(std::distance(input_begin, input_end)));\n      plan.complex_to_real(input_begin, input_end, output);\n    }\n    \n    // std::transform-like Fourier Transform API\n    // for real types\n    template<typename InputIterator,\n             typename OutputIterator>\n    static void real_to_halfcomplex(\n                     InputIterator  input_begin,\n                     InputIterator  input_end,\n                     OutputIterator output)\n    {\n      using input_value_type  = typename std::iterator_traits<InputIterator >::value_type;\n      plan_type<input_value_type> plan(static_cast<unsigned int>(std::distance(input_begin, input_end)));\n      plan.real_to_halfcomplex(input_begin, input_end, output);\n    }\n  \n    // std::transform-like Fourier Transform API\n    // for real types\n    template<typename InputIterator,\n             typename OutputIterator>\n    static void halfcomplex_to_real(InputIterator  input_begin,\n                      InputIterator  input_end,\n                      OutputIterator output)\n    {\n      using input_value_type  = typename std::iterator_traits<InputIterator >::value_type;\n      plan_type<input_value_type> plan(static_cast<unsigned int>(std::distance(input_begin, input_end)));\n      plan.halfcomplex_to_real(input_begin, input_end, output);\n    }\n  \n    template<typename InputIterator1,\n             typename InputIterator2,\n             typename OutputIterator>\n    static void convolution(\n        InputIterator1 input1_begin,\n        InputIterator1 input1_end,\n        InputIterator2 input2_begin,\n        OutputIterator output)\n    {\n      using input_value_type  = typename std::iterator_traits<InputIterator1>::value_type;\n      using real_value_type  = typename input_value_type::value_type;\n      // using allocator_type    = std::allocator<input_value_type>;\n      const long N = std::distance(input1_begin,input1_end);\n      plan_type<input_value_type> plan(static_cast<unsigned int>(N));\n      \n      std::vector<input_value_type> In1(N),In2(N),Out(N);\n      \n      std::copy(input1_begin,input1_end,In1.begin());\n      \n      InputIterator2 input2_end{input2_begin};\n      std::advance(input2_end,N);\n      std::copy(input2_begin,input2_end,In2.begin());\n      \n      plan.forward(In1.begin(),In1.end(),In1.begin());\n      plan.forward(In2.begin(),In2.end(),In2.begin());\n      \n      // direct convolution\n      std::transform(In1.begin(),In1.end(),In2.begin(),Out.begin(),std::multiplies<input_value_type>()); \n      \n      plan.backward(Out.begin(),Out.end(),Out.begin());\n      \n      const real_value_type inv_N = real_value_type{1}/N;\n      for(auto & x : Out)\n          x *= inv_N;\n      \n      std::copy(Out.begin(),Out.end(),output);\n    }\n    \n  };\n  \n  } } } // namespace boost::math::fft\n\n\n#endif // BOOST_MATH_DFTAPI_HPP\n", "meta": {"hexsha": "0b9238c496a94b4994fcc7199079ca73d788159e", "size": 22576, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/fft/dft_api.hpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/math/fft/dft_api.hpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "include/boost/math/fft/dft_api.hpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 34.154311649, "max_line_length": 197, "alphanum_fraction": 0.6376683203, "num_tokens": 5028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5094971826000364}}
{"text": "#ifndef MATRIX\n#define MATRIX\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <iostream>\n\n#include \"MiniDnn/layer.h\"\n#include \"MiniDnn/layer/conv.h\"\n#include \"MiniDnn/layer/fully_connected.h\"\n#include \"MiniDnn/layer/ave_pooling.h\"\n#include \"MiniDnn/layer/max_pooling.h\"\n#include \"MiniDnn/layer/relu.h\"\n#include \"MiniDnn/layer/sigmoid.h\"\n#include \"MiniDnn/layer/softmax.h\"\n#include \"MiniDnn/loss.h\"\n#include \"MiniDnn/loss/mse_loss.h\"\n#include \"MiniDnn/loss/cross_entropy_loss.h\"\n#include \"MiniDnn/mnist.h\"\n#include \"MiniDnn/network.h\"\n#include \"MiniDnn/optimizer.h\"\n#include \"MiniDnn/optimizer/sgd.h\"\n#include \"Enclave.h\"\n#include \"Enclave_t.h\"  /* print_string */\n\nusing namespace Eigen;\nusing namespace std;\n\n//#define N 4\n\n\n\nvoid Multiply_directly(int N) {\n    // std::chrono::time_point<std::chrono::high_resolution_clock> start, end;\n    // std::chrono::duration<double> elapsed;\n    MatrixXf X = MatrixXf::Random(N, N);\n    MatrixXf Y = MatrixXf::Random(N, N);\n    MatrixXf Z = MatrixXf::Zero(N, N);\n    //start = std::chrono::high_resolution_clock::now();\n    ocall_start_clock();\n    for (int i = 0; i < 5; i++) {\n        Z = X * Y;\n    }\n    //end = std::chrono::high_resolution_clock::now();\n    ocall_end_clock(\"%f: \");\n    printf(\"Direct[%d*%d]\\n\", N, N);\n    // elapsed = end - start;\n    // std::cout << \"Direct[\" << N << '*' << N << \"]:\" << elapsed.count() << std::endl;\n\n}\n\nvoid Multiply_breakdown(int N) {\n    // std::chrono::time_point<std::chrono::high_resolution_clock> start, end;\n    // std::chrono::duration<double> elapsed;\n    MatrixXf Z = MatrixXf::Zero(N, N);\n\n    MatrixXf XA = MatrixXf::Random(N / 2, N / 2);\n    MatrixXf XC = MatrixXf::Random(N / 2, N / 2);\n    MatrixXf XB = MatrixXf::Random(N / 2, N / 2);\n    MatrixXf XD = MatrixXf::Random(N / 2, N / 2);\n\n    MatrixXf YA = MatrixXf::Random(N / 2, N / 2);\n    MatrixXf YC = MatrixXf::Random(N / 2, N / 2);\n    MatrixXf YB = MatrixXf::Random(N / 2, N / 2);\n    MatrixXf YD = MatrixXf::Random(N / 2, N / 2);\n\n    //start = std::chrono::high_resolution_clock::now();\n    ocall_start_clock();\n    for (int i = 0; i < 5; i++) {\n        Z.block(0, 0, N / 2, N / 2) = XA * YA + XB * YC;\n        Z.block(0, N / 2, N / 2, N / 2) = XA * YB + XB * YD;\n        Z.block(N / 2, 0, N / 2, N / 2) = XC * YA + XD * YC;\n        Z.block(N / 2, N / 2, N / 2, N / 2) = XC * YB + XD * YD;\n    }\n    ocall_end_clock(\"%f: \");\n    printf(\"Break[%d*%d]\\n\", N, N);\n    //end = std::chrono::high_resolution_clock::now();\n\n    // elapsed = end - start;\n    // std::cout << \"Break[\" << N << '*' << N << \"]:\" << elapsed.count() << std::endl;\n\n}\n\nvoid ecall_ml_matrix_breakdown() {\n\n\n    for (int i = 256; i <= 2048; i *= 2) {\n        Multiply_directly(i);\n        Multiply_breakdown(i);\n    }\n\n}\n\n#endif", "meta": {"hexsha": "5166515499cea13b2acd6b4833900a24c608006e", "size": 2760, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Enclave/matrix_breakdown.cpp", "max_stars_repo_name": "zeyu-zh/TrustFL", "max_stars_repo_head_hexsha": "9e05a7e160bbf4fa1e7a426767f69158ea89b22d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-09-11T18:06:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T11:16:59.000Z", "max_issues_repo_path": "Enclave/matrix_breakdown.cpp", "max_issues_repo_name": "zeyu-zh/TrustFL", "max_issues_repo_head_hexsha": "9e05a7e160bbf4fa1e7a426767f69158ea89b22d", "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": "Enclave/matrix_breakdown.cpp", "max_forks_repo_name": "zeyu-zh/TrustFL", "max_forks_repo_head_hexsha": "9e05a7e160bbf4fa1e7a426767f69158ea89b22d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-01-29T02:52:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T09:10:56.000Z", "avg_line_length": 29.3617021277, "max_line_length": 87, "alphanum_fraction": 0.5945652174, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5094939878567155}}
{"text": "#include <string>\n#include <iostream>\n#include <rsa.h>\n#include <osrng.h>\n#include <files.h>\n#include <string>\n#include <boost/program_options.hpp>\n\ntemplate <typename Key>\nconst Key loadKey(const std::string& filename)\n{\n  Key key;\n  CryptoPP::ByteQueue queue;\n  CryptoPP::FileSource file(filename.c_str(), true);\n  file.TransferTo(queue);\n  queue.MessageEnd();\n\n  key.Load(queue);\n  return key;\n}\n\n\nint main(int argc, char** argv) {\n  using namespace CryptoPP;\n  namespace po = boost::program_options;\n\n  std::string privateKeyName, publicKeyName, plainText;\n  \n    po::options_description desc(\"Allowed Options\");\n  desc.add_options()\n    (\"help\", \"produce help message\")\n    (\"plainText,l\", po::value<std::string>(&plainText)->default_value(\"test\"), \"set plain text\")\n    (\"pubKey,r\", po::value<std::string>(&publicKeyName)->default_value(\"key.pub\"), \"set public key name\")\n    (\"privKey,u\", po::value<std::string>(&privateKeyName)->default_value(\"key.pem\"), \"set private key name\")\n    ;\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);    \n  \n  if (vm.count(\"help\")) {\n    std::cout << desc << \"\\n\";\n    return 1;\n  }\n\n\n  privateKeyName = \"key.pem\";\n  publicKeyName = \"key.pub\";\n  AutoSeededRandomPool prng;\n\n  auto privateKey = loadKey<RSA::PrivateKey>(privateKeyName);\n  auto publicKey = loadKey<RSA::PublicKey>(publicKeyName);\n\n  std::string encrypted, decrypted;\n  RSAES_OAEP_SHA_Encryptor e(publicKey);\n\n  StringSource(plainText, true,\n\t       new PK_EncryptorFilter(prng, e,\n\t\t\t\t      new StringSink(encrypted)));\n\n  RSAES_OAEP_SHA_Decryptor d(privateKey);\n\n  StringSource(encrypted, true,\n\t       new PK_DecryptorFilter(prng, d,\n\t\t\t\t      new StringSink(decrypted)));\n\n  std::cout << plainText << \" ---> \" << encrypted << \" <--- \" << decrypted << std::endl;\n}\n", "meta": {"hexsha": "ad85c3259e2dc7ad232b059a8bb4a469afcdb3c9", "size": 1826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "dunkyp/crypto--rsa-example", "max_stars_repo_head_hexsha": "fef2fbb9ce9787546c7572ab3dc68f3714b09f0a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-11-26T19:20:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T07:07:42.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "dunkyp/crypto--rsa-example", "max_issues_repo_head_hexsha": "fef2fbb9ce9787546c7572ab3dc68f3714b09f0a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "dunkyp/crypto--rsa-example", "max_forks_repo_head_hexsha": "fef2fbb9ce9787546c7572ab3dc68f3714b09f0a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-11-26T19:20:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T04:29:15.000Z", "avg_line_length": 26.4637681159, "max_line_length": 108, "alphanum_fraction": 0.6736035049, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5094891872181829}}
{"text": "/*\n * $Revision: 565 $ $Date: 2011-02-15 16:00:43 -0800 (Tue, 15 Feb 2011) $\n *\n * Copyright by Astos Solutions GmbH, Germany\n *\n * this file is published under the Astos Solutions Free Public License\n * For details on copyright and terms of use see\n * http://www.astos.de/Astos_Solutions_Free_Public_License.html\n */\n\n#include \"AlignedEllipsoid.h\"\n#include <Eigen/LU>\n#include <Eigen/QR>\n#include <cmath>\n\nusing namespace vesta;\nusing namespace Eigen;\nusing namespace std;\n\n\n\nstatic void\nplaneToSpanningVectors(const Hyperplane<double, 3>& plane,\n                       Vector3d& origin, Vector3d& v0, Vector3d& v1)\n{\n    origin = plane.normal() * -plane.offset();\n    v0 = plane.normal().unitOrthogonal();\n    v1 = v0.cross(plane.normal());\n}\n\n\n/* Only required for alternate implementation of plane intersection method\n\nstatic Hyperplane<double, 3> spanningVectorsToPlane(const Vector3d& origin,\n                                                    const Vector3d& v0,\n                                                    const Vector3d& v1)\n{\n    Vector3d n = v0.normalized().cross(v1.normalized());\n    return Hyperplane<double, 3>(n, n.dot(origin));\n}\n\n*/\n\n#define USE_ALTERNATE_INTERSECTION_METHOD 0\n\n/** Compute the of this ellipsoid with a plane. The intersection--if it exists--will\n  * be either a point or an ellipse. This method treats the point case as if no\n  * intersection occurred.\n  *\n  * \\param p the plane to test for intersection\n  * \\param foundIntersect set to true if there was an intersection, false otherwise. OK if null.\n  */\nGeneralEllipse\nAlignedEllipsoid::intersection(const Hyperplane<double, 3>& p, bool* foundIntersection) const\n{\n    // We will reduce the problem to the simpler one of finding the intersection of\n    // a plane with a unit sphere:\n    //    1. Computing transformation M that maps the ellipsoid to a unit sphere\n    //    2. Apply this transformation to the plane\n    //    3. Find the intersection of the transformed plane and the unit sphere\n    //    4. Apply the inverse transformation to get the ellipse of intersection\n\n    // Compute the transformation that maps the ellipsoid to a unit sphere\n    Matrix3d M = m_semiAxes.cwise().inverse().asDiagonal();\n\n    Vector3d plane_origin, plane_v0, plane_v1;\n    planeToSpanningVectors(p, plane_origin, plane_v0, plane_v1);\n\n    // Transform the plane\n    plane_origin = M * plane_origin;\n    plane_v0     = M * plane_v0;\n    plane_v1     = M * plane_v1;\n\n#if USE_ALTERNATE_INTERSECTION_METHOD\n    Hyperplane<double, 3> p1 = spanningVectorsToPlane(plane_origin, plane_v0, plane_v1);\n    planeToSpanningVectors(p1, plane_origin, plane_v0, plane_v1);\n\n    double d = plane_origin.norm();\n    if (d < 1.0)\n    {\n        if (foundIntersection)\n        {\n            *foundIntersection = true;\n        }\n\n        // Compute the radius of the circle of intersection\n        double r = 1.0 - d * d;\n\n        // Transform the spanning vectors and center back to the original space\n        /*DiagonalMatrix<Vector3d>*/ Matrix3d invM = m_semiAxes.asDiagonal();\n        plane_origin = invM * plane_origin;\n        plane_v0     = invM * (plane_v0 * r);\n        plane_v1     = invM * (plane_v1 * r);\n\n        return GeneralEllipse(plane_origin, plane_v0, plane_v1);\n    }\n    else\n    {\n        if (foundIntersection)\n        {\n            *foundIntersection = false;\n        }\n\n        // Return an empty ellipse\n        return GeneralEllipse(Vector3d::Zero(), Vector3d::Zero(), Vector3d::Zero());\n    }\n#else\n    Hyperplane<double, 3> p1 = p;\n    p1.transform(M);\n\n    if (abs(p1.offset()) < 1.0)\n    {\n        if (foundIntersection)\n        {\n            *foundIntersection = true;\n        }\n\n        // Compute the radius of the circle of intersection\n        double r = 1.0 - p1.offset() * p1.offset();\n\n        // n is the plane normal, v0 and v1 are spanning vectors of the plane\n        Vector3d n  = p1.normal();\n        Vector3d v0 = n.unitOrthogonal();\n        Vector3d v1 = v0.cross(n);\n\n        // Transform the spanning vectors and center back to the original space\n        DiagonalMatrix<Vector3d> D = m_semiAxes.asDiagonal();\n        Vector3d center = D * (n * p1.offset());\n        v0              = D * (v0 * r);\n        v1              = D * (v1 * r);\n\n        return GeneralEllipse(center, v0, v1);\n    }\n    else\n    {\n        if (foundIntersection)\n        {\n            *foundIntersection = false;\n        }\n\n        // Return an empty ellipse\n        return GeneralEllipse(Vector3d::Zero(), Vector3d::Zero(), Vector3d::Zero());\n    }\n#endif\n}\n\n\n/** Compute the ellipse that is the limb of the ellipsoid when viewed from\n  * some point outside the ellipsoid.\n  */\nGeneralEllipse\nAlignedEllipsoid::limb(const Vector3d& p) const\n{\n    // For a point L on the limb, the surface normal N(L) is\n    // perpendicular to the view direction L - P, thus:\n    //    (L - P) dot N(L) = 0\n    //\n\n    Vector3d n = m_semiAxes.cwise().square().cwise().inverse().asDiagonal() * p;\n    double mag = n.norm();\n    Hyperplane<double, 3> limbPlane(n / mag, 1.0 / mag);\n\n    bool found = false;\n\n    return intersection(limbPlane, &found);\n}\n\n\nstatic Vector3d projectPoint(const Vector3d& point, const Vector3d& planeNormal)\n{\n    return point - planeNormal * (point.dot(planeNormal));\n}\n\n\n/** Calculate the projection of the ellipsoid onto plane with specified normal and\n  * containing the ellipsoid center.\n  */\nGeneralEllipse\nAlignedEllipsoid::orthogonalProjection(const Vector3d& planeNormal) const\n{\n    // Compute the transformation that maps the ellipsoid to a unit sphere\n    Matrix3d M = m_semiAxes.cwise().inverse().asDiagonal();\n\n    Hyperplane<double, 3> p(planeNormal, 0.0);\n    Hyperplane<double, 3> p1 = p;\n    p1.transform(M);\n    p1.normal().normalize();\n\n    Vector3d plane_origin, plane_v0, plane_v1;\n    planeToSpanningVectors(p1, plane_origin, plane_v0, plane_v1);\n\n    DiagonalMatrix<Vector3d> invM = m_semiAxes.asDiagonal();\n    plane_v0     = invM * (plane_v0);\n    plane_v1     = invM * (plane_v1);\n\n    return GeneralEllipse(Vector3d::Zero(), plane_v0, plane_v1);\n}\n", "meta": {"hexsha": "5540c9efda1ed854d5dda5bf3492d3f4b20ee64f", "size": 6084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/vesta/AlignedEllipsoid.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "thirdparty/vesta/AlignedEllipsoid.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "thirdparty/vesta/AlignedEllipsoid.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 30.7272727273, "max_line_length": 96, "alphanum_fraction": 0.6449704142, "num_tokens": 1579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5094891822428805}}
{"text": "// Copyright (c) 2012, 2020 Tel-Aviv University (Israel).\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org).\n// You can redistribute it and/or modify it under the terms of the GNU\n// General Public License as published by the Free Software Foundation,\n// either version 3 of the License, or (at your option) any later version.\n//\n// Licensees holding a valid commercial license may use this file in\n// accordance with the commercial license agreement provided with the software.\n//\n// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n//\n// SPDX-License-Identifier: GPL-3.0+\n//\n// Author(s): Saurabh Singh <ssingh@cs.iitr.ac.in>\n//            Ahmed Essam <theartful.ae@gmail.com>\n\n#include <CGAL/Polynomial_traits_d.h>\n#include <CGAL/polynomial_utils.h>\n\n#include <boost/phoenix.hpp>\n#include <boost/spirit/include/qi.hpp>\n\n#include \"AlgebraicCurveParser.h\"\n\nnamespace phx = boost::phoenix;\nnamespace qi = boost::spirit::qi;\nnamespace ascii = boost::spirit::ascii;\n\ntemplate <typename Polynomial_d, typename Iterator, typename Skipper>\nstruct PolynomialParser : qi::grammar<Iterator, Polynomial_d(), Skipper>\n{\n  using Self = PolynomialParser<Polynomial_d, Iterator, Skipper>;\n  using Traits = CGAL::Polynomial_traits_d<Polynomial_d>;\n  using Coefficient = typename Traits::Innermost_coefficient_type;\n  using Innermost_leading_coefficient =\n    typename Traits::Innermost_leading_coefficient;\n  using Total_degree = typename Traits::Total_degree;\n\n  PolynomialParser() : PolynomialParser::base_type(start)\n  {\n    using qi::_val;\n    using qi::eps;\n\n    for (int i = 0; i < Traits::d; i++)\n        vars[i] = CGAL::shift(Polynomial_d(1), 1, i);\n\n    // { expr = expr } or { expr }\n    start = (expr >> '=' >> expr)[_val = qi::_1 - qi::_2] | expr[_val = qi::_1];\n    // addition and subtraction\n    expr = term[_val = qi::_1] >>\n           *('+' >> term[_val += qi::_1] | '-' >> term[_val -= qi::_1]);\n    // multiplication using *, and implied multiplication as in (x+y)(x+y)\n    term = factor[_val = qi::_1] >>\n           *(('*' >> factor[_val *= qi::_1]) | pow_expr[_val *= qi::_1]);\n    // uniary - and + operators\n    factor = qi::char_('-') >> pow_expr[_val = -qi::_1] |\n             -qi::char_('+') >> pow_expr[_val = qi::_1];\n    // power\n    pow_expr =\n      factor2[_val = qi::_1] >>\n      (('^' >> factor2[_val = phx::bind(&Self::raise, this, _val, qi::_1)]) |\n       eps);\n    // ( expr )\n    factor2 = (('(' >> expr >> ')') | factor3)[_val = qi::_1];\n    // coefficients and variables\n    factor3 =\n      coeff[_val = phx::construct<Polynomial_d>(qi::_1)] | var[_val = qi::_1];\n    coeff = qi::as_string[qi::lexeme[+qi::digit]]\n                         [_val = phx::construct<Coefficient>(qi::_1)];\n    if (Traits::d == 1)\n      var = qi::char_('x')[_val = vars[0]];\n    else\n      var = qi::char_('x')[_val = vars[0]] | qi::char_('y')[_val = vars[1]];\n  }\n\n  Polynomial_d raise(const Polynomial_d& poly, const Polynomial_d& power)\n  {\n    if (total_degree(power) != 0)\n    {\n      this->error = true;\n      return {};\n    }\n\n    return CGAL::ipower(\n      poly, std::lround(CGAL::to_double(innermost_leading_coefficient(power))));\n  }\n\n  Innermost_leading_coefficient innermost_leading_coefficient;\n  Total_degree total_degree;\n\n  Polynomial_d vars[Traits::d];\n\n  qi::rule<Iterator, Polynomial_d(), Skipper> start;\n  qi::rule<Iterator, Polynomial_d(), Skipper> expr;\n  qi::rule<Iterator, Polynomial_d(), Skipper> term;\n  qi::rule<Iterator, Polynomial_d(), Skipper> pow_expr;\n  qi::rule<Iterator, Polynomial_d(), Skipper> factor;\n  qi::rule<Iterator, Polynomial_d(), Skipper> factor2;\n  qi::rule<Iterator, Polynomial_d(), Skipper> factor3;\n  qi::rule<Iterator, Polynomial_d(), Skipper> var;\n  qi::rule<Iterator, Coefficient(), Skipper> coeff;\n\n  bool error = false;\n};\n\nstatic bool hasValidChars2D(const std::string& expression)\n{\n  const char valid_chars[] = {'x', 'y', '+', '-', '*', '(', ')', '^', '='};\n  return std::all_of(expression.begin(), expression.end(), [&](char c) {\n    return std::isspace(c) || std::isdigit(c) ||\n           std::find(std::begin(valid_chars), std::end(valid_chars), c) !=\n             std::end(valid_chars);\n  });\n}\n\nstatic bool hasValidChars1D(const std::string& expression)\n{\n  const char valid_chars[] = {'x', '+', '-', '*', '(', ')', '^'};\n  return std::all_of(expression.begin(), expression.end(), [&](char c) {\n    return std::isspace(c) || std::isdigit(c) ||\n           std::find(std::begin(valid_chars), std::end(valid_chars), c) !=\n             std::end(valid_chars);\n  });\n}\n\nstatic inline bool hasValidChars(const std::string& expression, int dimension)\n{\n  if (dimension == 1)\n    return hasValidChars1D(expression);\n  else\n    return hasValidChars2D(expression);\n}\n\ntemplate <typename Polynomial_d>\nboost::optional<Polynomial_d>\nAlgebraicCurveParser<Polynomial_d>::operator()(const std::string& expression)\n{\n  using Traits = CGAL::Polynomial_traits_d<Polynomial_d>;\n  using iterator_type = std::string::const_iterator;\n\n  if (!hasValidChars(expression, Traits::d)) return {};\n\n  PolynomialParser<Polynomial_d, iterator_type, ascii::space_type> pparser;\n  std::string::const_iterator iter = expression.begin();\n  std::string::const_iterator end = expression.end();\n\n  // parsing goes on here\n  Polynomial_d poly;\n  bool r = qi::phrase_parse(iter, end, pparser, ascii::space, poly);\n\n  if (r && iter == end && !pparser.error)\n    return poly;\n  else\n    return {};\n}\n\n#ifdef CGAL_USE_CORE\n// don't want to include ArrangementTypes.h\n// makes compilation slower\n// template class\n// AlgebraicCurveParser<demo_types::Alg_seg_traits::Polynomial_2>;\n// AlgebraicCurveParser<demo_types::Rational_traits::Polynomial_1>;\n#include <CGAL/Algebraic_kernel_d_1.h>\n#include <CGAL/Arr_algebraic_segment_traits_2.h>\n\ntemplate struct AlgebraicCurveParser<\n  CGAL::Arr_algebraic_segment_traits_2<CORE::BigInt>::Polynomial_2>;\n\ntemplate struct AlgebraicCurveParser<\n  typename CGAL::Algebraic_kernel_d_1<CORE::BigInt>::Polynomial_1>;\n#endif\n", "meta": {"hexsha": "009eede6a798a370b5d25bfefe083669b42bbe9c", "size": 6100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Arrangement_on_surface_2/demo/Arrangement_on_surface_2/AlgebraicCurveParser.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-19T03:07:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T03:07:22.000Z", "max_issues_repo_path": "Arrangement_on_surface_2/demo/Arrangement_on_surface_2/AlgebraicCurveParser.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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": "Arrangement_on_surface_2/demo/Arrangement_on_surface_2/AlgebraicCurveParser.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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": 34.8571428571, "max_line_length": 80, "alphanum_fraction": 0.6659016393, "num_tokens": 1647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5094891822428805}}
{"text": "// This file is part of the pyMOR project (http://www.pymor.org).\n// Copyright 2013-2018 pyMOR developers and contributors. All rights reserved.\n// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\n#ifndef EXAMPLE_HH\n#define EXAMPLE_HH\n\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_system.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_bicgstab.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/solution_transfer.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <functional>\n\n#include \"rhs.hh\"\n\nusing namespace dealii;\n\nclass ElasticityExample {\n\npublic:\n  static constexpr size_t dim{2};\n\n  ElasticityExample(int refine_steps);\n  ~ElasticityExample();\n\n  typedef double Number;\n  typedef std::map<std::string, std::vector<Number>> Parameter;\n  typedef Vector<Number> VectorType;\n\n  void visualize(const VectorType& solution, std::string filename) const;\n  VectorType solve(const Parameter& param);\n\n  const SparseMatrix<Number>& lambda_mat() const;\n  const SparseMatrix<Number>& mu_mat() const;\n  const SparseMatrix<Number>& h1_mat() const;\n  const Vector<Number>& rhs() const;\n\n  Number h1_0_semi_norm(const Vector<Number>& v) const;\n  Number energy_norm(const Vector<Number>& v) const;\n\n  VectorType transfer_to(int refine_steps, const VectorType& v);\n\nprivate:\n  void setup_system();\n  void assemble_h1();\n  void assemble_system();\n  void _solve(Parameter param, VectorType& solution);\n\nprotected:\n  void refine_global(int refine_steps = 1);\n\n  Triangulation<dim> triangulation_;\n  DoFHandler<dim> dof_handler_;\n\n  FESystem<dim> fe_;\n\n  SparsityPattern sparsity_pattern_;\n  SparseMatrix<Number> lambda_system_matrix_, mu_system_matrix_, h1_matrix_;\n  Vector<Number> system_rhs_, tmp_data_;\n};\n\n#endif // EXAMPLE_HH\n", "meta": {"hexsha": "44d015ca7b4e325807d026778f137ee1c2fb7609", "size": 2531, "ext": "hh", "lang": "C++", "max_stars_repo_path": "lib/elasticity.hh", "max_stars_repo_name": "DavidSCN/pymor-deal.II", "max_stars_repo_head_hexsha": "e8817fbec023f317cadf231abb7f3ac6e5751611", "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": "lib/elasticity.hh", "max_issues_repo_name": "DavidSCN/pymor-deal.II", "max_issues_repo_head_hexsha": "e8817fbec023f317cadf231abb7f3ac6e5751611", "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": "lib/elasticity.hh", "max_forks_repo_name": "DavidSCN/pymor-deal.II", "max_forks_repo_head_hexsha": "e8817fbec023f317cadf231abb7f3ac6e5751611", "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.4302325581, "max_line_length": 78, "alphanum_fraction": 0.7605689451, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.5094891796475565}}
{"text": "// root_finding_example.cpp\n\n// Copyright Paul A. Bristow 2010, 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// Example of finding roots using Newton-Raphson, Halley.\n\n// Note that this file contains Quickbook mark-up as well as code\n// and comments, don't change any of the special comment mark-ups!\n\n//#define BOOST_MATH_INSTRUMENT\n\n/*\nThis example demonstrates how to use the various tools for root finding\ntaking the simple cube root function (`cbrt`) as an example.\n\nIt shows how use of derivatives can improve the speed.\n(But is only a demonstration and does not try to make the ultimate improvements of 'real-life'\nimplementation of `boost::math::cbrt`, mainly by using a better computed initial 'guess'\nat `<boost/math/special_functions/cbrt.hpp>`).\n\nThen we show how a higher root (fifth) can be computed,\nand in `root_finding_n_example.cpp` a generic method\nfor the ['n]th root that constructs the derivatives at compile-time,\n\nThese methods should be applicable to other functions that can be differentiated easily.\n\nFirst some `#includes` that will be needed.\n\n[tip For clarity, `using` statements are provided to list what functions are being used in this example:\nyou can of course partly or fully qualify the names in other ways.\n(For your application, you may wish to extract some parts into header files,\nbut you should never use `using` statements globally in header files).]\n*/\n\n//[root_finding_include_1\n\n#include <boost/math/tools/roots.hpp>\n//using boost::math::policies::policy;\n//using boost::math::tools::newton_raphson_iterate;\n//using boost::math::tools::halley_iterate; //\n//using boost::math::tools::eps_tolerance; // Binary functor for specified number of bits.\n//using boost::math::tools::bracket_and_solve_root;\n//using boost::math::tools::toms748_solve;\n\n#include <boost/math/special_functions/next.hpp> // For float_distance.\n#include <tuple> // for std::tuple and std::make_tuple.\n#include <boost/math/special_functions/cbrt.hpp> // For boost::math::cbrt.\n\n//] [/root_finding_include_1]\n\n// using boost::math::tuple;\n// using boost::math::make_tuple;\n// using boost::math::tie;\n// which provide convenient aliases for various implementations,\n// including std::tr1, depending on what is available.\n\n#include <iostream>\n//using std::cout; using std::endl;\n#include <iomanip>\n//using std::setw; using std::setprecision;\n#include <limits>\n//using std::numeric_limits;\n\n/*\n\nLet's suppose we want to find the root of a number ['a], and to start, compute the cube root.\n\nSo the equation we want to solve is:\n\n__spaces ['f](x) = x[cubed] - a\n\nWe will first solve this without using any information\nabout the slope or curvature of the cube root function.\n\nWe then show how adding what we can know about this function, first just the slope,\nthe 1st derivation /f'(x)/, will speed homing in on the solution.\n\nLastly we show how adding the curvature /f''(x)/ too will speed convergence even more.\n\n*/\n\n//[root_finding_noderiv_1\n\ntemplate <class T>\nstruct cbrt_functor_noderiv\n{ \n  //  cube root of x using only function - no derivatives.\n  cbrt_functor_noderiv(T const& to_find_root_of) : a(to_find_root_of)\n  { /* Constructor just stores value a to find root of. */ }\n  T operator()(T const& x)\n  {\n    T fx = x*x*x - a; // Difference (estimate x^3 - a).\n    return fx;\n  }\nprivate:\n  T a; // to be 'cube_rooted'.\n};\n//] [/root_finding_noderiv_1\n\n/*\nImplementing the cube root function itself is fairly trivial now:\nthe hardest part is finding a good approximation to begin with.\nIn this case we'll just divide the exponent by three.\n(There are better but more complex guess algorithms used in 'real-life'.)\n\nCube root function is 'Really Well Behaved' in that it is monotonic\nand has only one root (we leave negative values 'as an exercise for the student').\n*/\n\n//[root_finding_noderiv_2\n\ntemplate <class T>\nT cbrt_noderiv(T x)\n{ \n  // return cube root of x using bracket_and_solve (no derivatives).\n  using namespace std;                          // Help ADL of std functions.\n  using namespace boost::math::tools;           // For bracket_and_solve_root.\n\n  int exponent;\n  frexp(x, &exponent);                          // Get exponent of z (ignore mantissa).\n  T guess = ldexp(1., exponent/3);              // Rough guess is to divide the exponent by three.\n  T factor = 2;                                 // How big steps to take when searching.\n\n  const boost::uintmax_t maxit = 20;            // Limit to maximum iterations.\n  boost::uintmax_t it = maxit;                  // Initally our chosen max iterations, but updated with actual.\n  bool is_rising = true;                        // So if result if guess^3 is too low, then try increasing guess.\n  int digits = std::numeric_limits<T>::digits;  // Maximum possible binary digits accuracy for type T.\n  // Some fraction of digits is used to control how accurate to try to make the result.\n  int get_digits = 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  eps_tolerance<T> tol(get_digits);             // Set the tolerance.\n  std::pair<T, T> r = bracket_and_solve_root(cbrt_functor_noderiv<T>(x), guess, factor, is_rising, tol, it);\n  return r.first + (r.second - r.first)/2;      // Midway between brackets is our result, if necessary we could\n                                                // return the result as an interval here.\n}\n\n/*`\n\n[note The final parameter specifying a maximum number of iterations is optional.\nHowever, it defaults to `boost::uintmax_t maxit = (std::numeric_limits<boost::uintmax_t>::max)();`\nwhich is `18446744073709551615` and is more than anyone would wish to wait for!\n\nSo it may be wise to chose some reasonable estimate of how many iterations may be needed, \nIn this case the function is so well behaved that we can chose a low value of 20.\n\nInternally when Boost.Math uses these functions, it sets the maximum iterations to\n`policies::get_max_root_iterations<Policy>();`.]\n\nShould we have wished we can show how many iterations were used in `bracket_and_solve_root` \n(this information is lost outside `cbrt_noderiv`), for example with:\n\n  if (it >= maxit)\n  {\n    std::cout << \"Unable to locate solution in \" << maxit << \" iterations:\"\n      \" Current best guess is between \" << r.first << \" and \" << r.second << std::endl;\n  }\n  else\n  {\n    std::cout << \"Converged after \" << it << \" (from maximum of \" << maxit << \" iterations).\" << std::endl;\n  }\n\nfor output like\n\n  Converged after 11 (from maximum of 20 iterations).\n*/\n//] [/root_finding_noderiv_2]\n\n\n// Cube root with 1st derivative (slope)\n\n/*\nWe now solve the same problem, but using more information about the function,\nto show how this can speed up finding the best estimate of the root.\n\nFor the root function, the 1st differential (the slope of the tangent to a curve at any point) is known.\n\nIf you need some reminders then\n[@http://en.wikipedia.org/wiki/Derivative#Derivatives_of_elementary_functions Derivatives of elementary functions]\nmay help.\n\nUsing the rule that the derivative of ['x[super n]] for positive n (actually all nonzero n) is ['n x[super n-1]],\nallows us to get the 1st differential as ['3x[super 2]].\n\nTo see how this extra information is used to find a root, view\n[@http://en.wikipedia.org/wiki/Newton%27s_method Newton-Raphson iterations]\nand the [@http://en.wikipedia.org/wiki/Newton%27s_method#mediaviewer/File:NewtonIteration_Ani.gif animation].\n\nWe need to define a different functor `cbrt_functor_deriv` that returns\nboth the evaluation of the function to solve, along with its first derivative:\n\nTo \\'return\\' two values, we use a `std::pair` of floating-point values\n(though we could equally have used a std::tuple):\n*/\n\n//[root_finding_1_deriv_1\n\ntemplate <class T>\nstruct cbrt_functor_deriv\n{ // Functor also returning 1st derivative.\n  cbrt_functor_deriv(T const& to_find_root_of) : a(to_find_root_of)\n  { // Constructor stores value a to find root of,\n    // for example: calling cbrt_functor_deriv<T>(a) to use to get cube root of a.\n  }\n  std::pair<T, T> operator()(T const& x)\n  { \n    // Return both f(x) and f'(x).\n    T fx = x*x*x - a;                // Difference (estimate x^3 - value).\n    T dx =  3 * x*x;                 // 1st derivative = 3x^2.\n    return std::make_pair(fx, dx);   // 'return' both fx and dx.\n  }\nprivate:\n  T a;                               // Store value to be 'cube_rooted'.\n};\n\n/*`Our cube root function is now:*/\n\ntemplate <class T>\nT cbrt_deriv(T x)\n{ \n  // return cube root of x using 1st derivative and Newton_Raphson.\n  using namespace boost::math::tools;\n  int exponent;\n  frexp(x, &exponent);                                // Get exponent of z (ignore mantissa).\n  T guess = ldexp(1., exponent/3);                    // Rough guess is to divide the exponent by three.\n  T min = ldexp(0.5, exponent/3);                     // Minimum possible value is half our guess.\n  T max = ldexp(2., exponent/3);                      // Maximum possible value is twice our guess.\n  const int digits = std::numeric_limits<T>::digits;  // Maximum possible binary digits accuracy for type T.\n  int get_digits = static_cast<int>(digits * 0.6);    // Accuracy doubles with each step, so stop when we have\n                                                      // just over half the digits correct.\n  const boost::uintmax_t maxit = 20;\n  boost::uintmax_t it = maxit;\n  T result = newton_raphson_iterate(cbrt_functor_deriv<T>(x), guess, min, max, get_digits, it);\n  return result;\n}\n\n//] [/root_finding_1_deriv_1]\n\n\n/*\n[h3:cbrt_2_derivatives Cube root with 1st & 2nd derivative (slope & curvature)]\n\nFinally we define yet another functor `cbrt_functor_2deriv` that returns\nboth the evaluation of the function to solve,\nalong with its first *and second* derivatives:\n\n__spaces[''f](x) = 6x\n\nTo \\'return\\' three values, we use a `tuple` of three floating-point values:\n*/\n\n//[root_finding_2deriv_1\n\ntemplate <class T>\nstruct cbrt_functor_2deriv\n{ \n  // Functor returning both 1st and 2nd derivatives.\n  cbrt_functor_2deriv(T const& to_find_root_of) : a(to_find_root_of)\n  { // Constructor stores value a to find root of, for example:\n    // calling cbrt_functor_2deriv<T>(x) to get cube root of x,\n  }\n  std::tuple<T, T, T> operator()(T const& x)\n  { \n    // Return both f(x) and f'(x) and f''(x).\n    T fx = x*x*x - a;                     // Difference (estimate x^3 - value).\n    T dx = 3 * x*x;                       // 1st derivative = 3x^2.\n    T d2x = 6 * x;                        // 2nd derivative = 6x.\n    return std::make_tuple(fx, dx, d2x);  // 'return' fx, dx and d2x.\n  }\nprivate:\n  T a; // to be 'cube_rooted'.\n};\n\n/*`Our cube root function is now:*/\n\ntemplate <class T>\nT cbrt_2deriv(T x)\n{ \n  // return cube root of x using 1st and 2nd derivatives and Halley.\n  //using namespace std;  // Help ADL of std functions.\n  using namespace boost::math::tools;\n  int exponent;\n  frexp(x, &exponent);                                // Get exponent of z (ignore mantissa).\n  T guess = ldexp(1., exponent/3);                    // Rough guess is to divide the exponent by three.\n  T min = ldexp(0.5, exponent/3);                     // Minimum possible value is half our guess.\n  T max = ldexp(2., exponent/3);                      // Maximum possible value is twice our guess.\n  const int digits = std::numeric_limits<T>::digits;  // Maximum possible binary digits accuracy for type T.\n  // digits used to control how accurate to try to make the result.\n  int get_digits = static_cast<int>(digits * 0.4);    // Accuracy triples with each step, so stop when just\n                                                      // over one third of the digits are correct.\n  boost::uintmax_t maxit = 20;\n  T result = halley_iterate(cbrt_functor_2deriv<T>(x), guess, min, max, get_digits, maxit);\n  return result;\n}\n\n//] [/root_finding_2deriv_1]\n\n//[root_finding_2deriv_lambda\n\ntemplate <class T>\nT cbrt_2deriv_lambda(T x)\n{\n   // return cube root of x using 1st and 2nd derivatives and Halley.\n   //using namespace std;  // Help ADL of std functions.\n   using namespace boost::math::tools;\n   int exponent;\n   frexp(x, &exponent);                                // Get exponent of z (ignore mantissa).\n   T guess = ldexp(1., exponent / 3);                    // Rough guess is to divide the exponent by three.\n   T min = ldexp(0.5, exponent / 3);                     // Minimum possible value is half our guess.\n   T max = ldexp(2., exponent / 3);                      // Maximum possible value is twice our guess.\n   const int digits = std::numeric_limits<T>::digits;  // Maximum possible binary digits accuracy for type T.\n   // digits used to control how accurate to try to make the result.\n   int get_digits = static_cast<int>(digits * 0.4);    // Accuracy triples with each step, so stop when just\n   // over one third of the digits are correct.\n   boost::uintmax_t maxit = 20;\n   T result = halley_iterate(\n      // lambda function:\n      [x](const T& g){ return std::make_tuple(g * g * g - x, 3 * g * g, 6 * g); }, \n      guess, min, max, get_digits, maxit);\n   return result;\n}\n\n//] [/root_finding_2deriv_lambda]\n/*\n\n[h3 Fifth-root function]\nLet's now suppose we want to find the [*fifth root] of a number ['a].\n\nThe equation we want to solve is :\n\n__spaces['f](x) = x[super 5] - a\n\nIf your differentiation is a little rusty\n(or you are faced with an equation whose complexity is daunting),\nthen you can get help, for example from the invaluable\n[@http://www.wolframalpha.com/ WolframAlpha site.]\n\nFor example, entering the commmand: `differentiate x ^ 5`\n\nor the Wolfram Language command: ` D[x ^ 5, x]`\n\ngives the output: `d/dx(x ^ 5) = 5 x ^ 4`\n\nand to get the second differential, enter: `second differentiate x ^ 5`\n\nor the Wolfram Language command: `D[x ^ 5, { x, 2 }]`\n\nto get the output: `d ^ 2 / dx ^ 2(x ^ 5) = 20 x ^ 3`\n\nTo get a reference value, we can enter: [^fifth root 3126]\n\nor: `N[3126 ^ (1 / 5), 50]`\n\nto get a result with a precision of 50 decimal digits:\n\n5.0003199590478625588206333405631053401128722314376\n\n(We could also get a reference value using Boost.Multiprecision - see below).\n\nThe 1st and 2nd derivatives of x[super 5] are:\n\n__spaces['f]\\'(x) = 5x[super 4]\n\n__spaces['f]\\'\\'(x) = 20x[super 3]\n\n*/\n\n//[root_finding_fifth_1\n//] [/root_finding_fifth_1]\n\n\n//[root_finding_fifth_functor_2deriv\n\n/*`Using these expressions for the derivatives, the functor is:\n*/\n\ntemplate <class T>\nstruct fifth_functor_2deriv\n{ \n  // Functor returning both 1st and 2nd derivatives.\n  fifth_functor_2deriv(T const& to_find_root_of) : a(to_find_root_of)\n  { /* Constructor stores value a to find root of, for example: */ }\n\n  std::tuple<T, T, T> operator()(T const& x)\n  { \n    // Return both f(x) and f'(x) and f''(x).\n    T fx = boost::math::pow<5>(x) - a;    // Difference (estimate x^3 - value).\n    T dx = 5 * boost::math::pow<4>(x);    // 1st derivative = 5x^4.\n    T d2x = 20 * boost::math::pow<3>(x);  // 2nd derivative = 20 x^3\n    return std::make_tuple(fx, dx, d2x);  // 'return' fx, dx and d2x.\n  }\nprivate:\n  T a;                                    // to be 'fifth_rooted'.\n}; // struct fifth_functor_2deriv\n\n//] [/root_finding_fifth_functor_2deriv]\n\n//[root_finding_fifth_2deriv\n\n/*`Our fifth-root function is now:\n*/\n\ntemplate <class T>\nT fifth_2deriv(T x)\n{ \n  // return fifth root of x using 1st and 2nd derivatives and Halley.\n  using namespace std;                  // Help ADL of std functions.\n  using namespace boost::math::tools;   // for halley_iterate.\n\n  int exponent;\n  frexp(x, &exponent);                  // Get exponent of z (ignore mantissa).\n  T guess = ldexp(1., exponent / 5);    // Rough guess is to divide the exponent by five.\n  T min = ldexp(0.5, exponent / 5);     // Minimum possible value is half our guess.\n  T max = ldexp(2., exponent / 5);      // Maximum possible value is twice our guess.\n  // Stop when slightly more than one of the digits are correct:\n  const int digits = static_cast<int>(std::numeric_limits<T>::digits * 0.4); \n  const boost::uintmax_t maxit = 50;\n  boost::uintmax_t it = maxit;\n  T result = halley_iterate(fifth_functor_2deriv<T>(x), guess, min, max, digits, it);\n  return result;\n}\n\n//] [/root_finding_fifth_2deriv]\n\n\nint main()\n{\n  std::cout << \"Root finding  Examples.\" << std::endl;\n  std::cout.precision(std::numeric_limits<double>::max_digits10);\n  // Show all possibly significant decimal digits for double.\n  // std::cout.precision(std::numeric_limits<double>::digits10);\n  // Show all guaranteed significant decimal digits for double.\n\n\n//[root_finding_main_1\n  try\n  {\n    double threecubed = 27.;   // Value that has an *exactly representable* integer cube root.\n    double threecubedp1 = 28.; // Value whose cube root is *not* exactly representable.\n\n    std::cout << \"cbrt(28) \" << boost::math::cbrt(28.) << std::endl; // boost::math:: version of cbrt.\n    std::cout << \"std::cbrt(28) \" << std::cbrt(28.) << std::endl;    // std:: version of cbrt.\n    std::cout <<\" cast double \" << static_cast<double>(3.0365889718756625194208095785056696355814539772481111) << std::endl;\n\n    // Cube root using bracketing:\n    double r = cbrt_noderiv(threecubed);\n    std::cout << \"cbrt_noderiv(\" << threecubed << \") = \" << r << std::endl;\n    r = cbrt_noderiv(threecubedp1);\n    std::cout << \"cbrt_noderiv(\" << threecubedp1 << \") = \" << r << std::endl;\n//] [/root_finding_main_1]\n    //[root_finding_main_2\n\n    // Cube root using 1st differential Newton-Raphson:\n    r = cbrt_deriv(threecubed);\n    std::cout << \"cbrt_deriv(\" << threecubed << \") = \" << r << std::endl;\n    r = cbrt_deriv(threecubedp1);\n    std::cout << \"cbrt_deriv(\" << threecubedp1 << \") = \" << r << std::endl;\n\n    // Cube root using Halley with 1st and 2nd differentials.\n    r = cbrt_2deriv(threecubed);\n    std::cout << \"cbrt_2deriv(\" << threecubed << \") = \" << r << std::endl;\n    r = cbrt_2deriv(threecubedp1);\n    std::cout << \"cbrt_2deriv(\" << threecubedp1 << \") = \" << r << std::endl;\n\n    // Cube root using lambda's:\n    r = cbrt_2deriv_lambda(threecubed);\n    std::cout << \"cbrt_2deriv(\" << threecubed << \") = \" << r << std::endl;\n    r = cbrt_2deriv_lambda(threecubedp1);\n    std::cout << \"cbrt_2deriv(\" << threecubedp1 << \") = \" << r << std::endl;\n\n    // Fifth root.\n\n    double fivepowfive = 3125; // Example of a value that has an exact integer fifth root.\n    // Exact value of fifth root is exactly 5.\n    std::cout << \"Fifth root  of \" << fivepowfive << \" is \" << 5 << std::endl;\n\n    double fivepowfivep1 = fivepowfive + 1; // Example of a value whose fifth root is *not* exactly representable.\n    // Value of fifth root is 5.0003199590478625588206333405631053401128722314376 (50 decimal digits precision)\n    // and to std::numeric_limits<double>::max_digits10 double precision (usually 17) is\n\n    double root5v2 = static_cast<double>(5.0003199590478625588206333405631053401128722314376);\n        std::cout << \"Fifth root  of \" << fivepowfivep1 << \" is \" << root5v2 << std::endl;\n\n    // Using Halley with 1st and 2nd differentials.\n    r = fifth_2deriv(fivepowfive);\n    std::cout << \"fifth_2deriv(\" << fivepowfive << \") = \" << r << std::endl;\n    r = fifth_2deriv(fivepowfivep1);\n    std::cout << \"fifth_2deriv(\" << fivepowfivep1 << \") = \" << r << std::endl;\n//] [/root_finding_main_?]\n  }\n  catch(const std::exception& e)\n  { // Always useful to include try & catch blocks because default policies\n    // are to throw exceptions on arguments that cause errors like underflow, overflow.\n    // Lacking try & catch blocks, the program will abort without a message below,\n    // which may give some helpful clues as to the cause of the exception.\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << std::endl;\n  }\n  return 0;\n}  // int main()\n\n//[root_finding_example_output\n/*`\nNormal output is:\n\n[pre\n  root_finding_example.cpp\n  Generating code\n  Finished generating code\n  root_finding_example.vcxproj -> J:\\Cpp\\MathToolkit\\test\\Math_test\\Release\\root_finding_example.exe\n  Cube Root finding (cbrt) Example.\n  Iterations 10\n  cbrt_1(27) = 3\n  Iterations 10\n  Unable to locate solution in chosen iterations: Current best guess is between 3.0365889718756613 and 3.0365889718756627\n  cbrt_1(28) = 3.0365889718756618\n  cbrt_1(27) = 3\n  cbrt_2(28) = 3.0365889718756627\n  Iterations 4\n  cbrt_3(27) = 3\n  Iterations 5\n  cbrt_3(28) = 3.0365889718756627\n\n] [/pre]\n\nto get some (much!) diagnostic output we can add\n\n#define BOOST_MATH_INSTRUMENT\n\n[pre\n\n]\n*/\n//] [/root_finding_example_output]\n\n/*\n\ncbrt(28) 3.0365889718756622\nstd::cbrt(28) 3.0365889718756627\n\n*/\n", "meta": {"hexsha": "9cbfd237ed79d468bca9654e2651c76cf946e565", "size": 20987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/root_finding_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/root_finding_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/root_finding_example.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 38.2974452555, "max_line_length": 124, "alphanum_fraction": 0.6668890265, "num_tokens": 5868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5094891772675778}}
{"text": "\n\n//\n//=======================================================================\n// Copyright (c) 2004 Kristopher Beevers\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\n#include <boost/graph/astar_search.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/random.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <ctime>\n#include <vector>\n#include <list>\n#include <iostream>\n#include <fstream>\n#include <math.h> // for sqrt\n\nusing namespace boost;\nusing namespace std;\n\n// auxiliary types\nstruct location\n{\n    float y, x; // lat, long\n};\ntypedef float cost;\n\ntemplate < class Name, class LocMap > class city_writer\n{\npublic:\n    city_writer(Name n, LocMap l, float _minx, float _maxx, float _miny,\n        float _maxy, unsigned int _ptx, unsigned int _pty)\n    : name(n)\n    , loc(l)\n    , minx(_minx)\n    , maxx(_maxx)\n    , miny(_miny)\n    , maxy(_maxy)\n    , ptx(_ptx)\n    , pty(_pty)\n    {\n    }\n    template < class Vertex >\n    void operator()(ostream& out, const Vertex& v) const\n    {\n        float px = 1 - (loc[v].x - minx) / (maxx - minx);\n        float py = (loc[v].y - miny) / (maxy - miny);\n        out << \"[label=\\\"\" << name[v] << \"\\\", pos=\\\"\"\n            << static_cast< unsigned int >(ptx * px) << \",\"\n            << static_cast< unsigned int >(pty * py) << \"\\\", fontsize=\\\"11\\\"]\";\n    }\n\nprivate:\n    Name name;\n    LocMap loc;\n    float minx, maxx, miny, maxy;\n    unsigned int ptx, pty;\n};\n\ntemplate < class WeightMap > class time_writer\n{\npublic:\n    time_writer(WeightMap w) : wm(w) {}\n    template < class Edge > void operator()(ostream& out, const Edge& e) const\n    {\n        out << \"[label=\\\"\" << wm[e] << \"\\\", fontsize=\\\"11\\\"]\";\n    }\n\nprivate:\n    WeightMap wm;\n};\n\n// euclidean distance heuristic\ntemplate < class Graph, class CostType, class LocMap >\nclass distance_heuristic : public astar_heuristic< Graph, CostType >\n{\npublic:\n    typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\n    distance_heuristic(LocMap l, Vertex goal) : m_location(l), m_goal(goal) {}\n    CostType operator()(Vertex u)\n    {\n        CostType dx = m_location[m_goal].x - m_location[u].x;\n        CostType dy = m_location[m_goal].y - m_location[u].y;\n        return ::sqrt(dx * dx + dy * dy);\n    }\n\nprivate:\n    LocMap m_location;\n    Vertex m_goal;\n};\n\nstruct found_goal\n{\n}; // exception for termination\n\n// visitor that terminates when we find the goal\ntemplate < class Vertex >\nclass astar_goal_visitor : public boost::default_astar_visitor\n{\npublic:\n    astar_goal_visitor(Vertex goal) : m_goal(goal) {}\n    template < class Graph > void examine_vertex(Vertex u, Graph& g)\n    {\n        if (u == m_goal)\n            throw found_goal();\n    }\n\nprivate:\n    Vertex m_goal;\n};\n\nint main(int argc, char** argv)\n{\n\n    // specify some types\n    typedef adjacency_list< listS, vecS, undirectedS, no_property,\n        property< edge_weight_t, cost > >\n        mygraph_t;\n    typedef property_map< mygraph_t, edge_weight_t >::type WeightMap;\n    typedef mygraph_t::vertex_descriptor vertex;\n    typedef mygraph_t::edge_descriptor edge_descriptor;\n    typedef std::pair< int, int > edge;\n\n    // specify data\n    enum nodes\n    {\n        Troy,\n        LakePlacid,\n        Plattsburgh,\n        Massena,\n        Watertown,\n        Utica,\n        Syracuse,\n        Rochester,\n        Buffalo,\n        Ithaca,\n        Binghamton,\n        Woodstock,\n        NewYork,\n        N\n    };\n    const char* name[] = { \"Troy\", \"Lake Placid\", \"Plattsburgh\", \"Massena\",\n        \"Watertown\", \"Utica\", \"Syracuse\", \"Rochester\", \"Buffalo\", \"Ithaca\",\n        \"Binghamton\", \"Woodstock\", \"New York\" };\n    location locations[] = { // lat/long\n        { 42.73, 73.68 }, { 44.28, 73.99 }, { 44.70, 73.46 }, { 44.93, 74.89 },\n        { 43.97, 75.91 }, { 43.10, 75.23 }, { 43.04, 76.14 }, { 43.17, 77.61 },\n        { 42.89, 78.86 }, { 42.44, 76.50 }, { 42.10, 75.91 }, { 42.04, 74.11 },\n        { 40.67, 73.94 }\n    };\n    edge edge_array[]\n        = { edge(Troy, Utica), edge(Troy, LakePlacid), edge(Troy, Plattsburgh),\n              edge(LakePlacid, Plattsburgh), edge(Plattsburgh, Massena),\n              edge(LakePlacid, Massena), edge(Massena, Watertown),\n              edge(Watertown, Utica), edge(Watertown, Syracuse),\n              edge(Utica, Syracuse), edge(Syracuse, Rochester),\n              edge(Rochester, Buffalo), edge(Syracuse, Ithaca),\n              edge(Ithaca, Binghamton), edge(Ithaca, Rochester),\n              edge(Binghamton, Troy), edge(Binghamton, Woodstock),\n              edge(Binghamton, NewYork), edge(Syracuse, Binghamton),\n              edge(Woodstock, Troy), edge(Woodstock, NewYork) };\n    unsigned int num_edges = sizeof(edge_array) / sizeof(edge);\n    cost weights[] = { // estimated travel time (mins)\n        96, 134, 143, 65, 115, 133, 117, 116, 74, 56, 84, 73, 69, 70, 116, 147,\n        173, 183, 74, 71, 124\n    };\n\n    // create graph\n    mygraph_t g(N);\n    WeightMap weightmap = get(edge_weight, g);\n    for (std::size_t j = 0; j < num_edges; ++j)\n    {\n        edge_descriptor e;\n        bool inserted;\n        boost::tie(e, inserted)\n            = add_edge(edge_array[j].first, edge_array[j].second, g);\n        weightmap[e] = weights[j];\n    }\n\n    // pick random start/goal\n    boost::mt19937 gen(std::time(0));\n    vertex start = random_vertex(g, gen);\n    vertex goal = random_vertex(g, gen);\n\n    cout << \"Start vertex: \" << name[start] << endl;\n    cout << \"Goal vertex: \" << name[goal] << endl;\n\n    ofstream dotfile;\n    dotfile.open(\"test-astar-cities.dot\");\n    write_graphviz(dotfile, g,\n        city_writer< const char**, location* >(\n            name, locations, 73.46, 78.86, 40.67, 44.93, 480, 400),\n        time_writer< WeightMap >(weightmap));\n\n    vector< mygraph_t::vertex_descriptor > p(num_vertices(g));\n    vector< cost > d(num_vertices(g));\n    try\n    {\n        // call astar named parameter interface\n        astar_search_tree(g, start,\n            distance_heuristic< mygraph_t, cost, location* >(locations, goal),\n            predecessor_map(\n                make_iterator_property_map(p.begin(), get(vertex_index, g)))\n                .distance_map(\n                    make_iterator_property_map(d.begin(), get(vertex_index, g)))\n                .visitor(astar_goal_visitor< vertex >(goal)));\n    }\n    catch (found_goal fg)\n    { // found a path to the goal\n        list< vertex > shortest_path;\n        for (vertex v = goal;; v = p[v])\n        {\n            shortest_path.push_front(v);\n            if (p[v] == v)\n                break;\n        }\n        cout << \"Shortest path from \" << name[start] << \" to \" << name[goal]\n             << \": \";\n        list< vertex >::iterator spi = shortest_path.begin();\n        cout << name[start];\n        for (++spi; spi != shortest_path.end(); ++spi)\n            cout << \" -> \" << name[*spi];\n        cout << endl << \"Total travel time: \" << d[goal] << endl;\n        return 0;\n    }\n\n    cout << \"Didn't find a path from \" << name[start] << \"to\" << name[goal]\n         << \"!\" << endl;\n    return 0;\n}\n", "meta": {"hexsha": "3437e6abd75e90adafcd8750d09e56f0dad4a5bc", "size": 7246, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/astar-cities.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.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": "3rdparty/boost_1_73_0/libs/graph/example/astar-cities.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": "3rdparty/boost_1_73_0/libs/graph/example/astar-cities.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": 30.4453781513, "max_line_length": 80, "alphanum_fraction": 0.571211703, "num_tokens": 1992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5094891722922752}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/gamma.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/halfeps.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/five.hpp>\n#include <boost/simd/function/rsqrt.hpp>\n#include <boost/simd/function/std.hpp>\n#include <scalar_test.hpp>\n\nSTF_CASE_TPL (\" gamma\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::gamma;\n  using r_t = decltype(gamma(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(gamma(bs::Minf<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(gamma(bs::Inf<T>()), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(gamma(bs::Nan<T>()), bs::Nan<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(gamma(bs::Zero<T>()), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(gamma(bs::Mzero<T>()), bs::Minf<r_t>(), 0);\n  STF_ULP_EQUAL(gamma(T(1)), T(1), 0);\n  STF_ULP_EQUAL(gamma(T(2)), T(1), 0);\n  STF_ULP_EQUAL(gamma(T(3)), T(2), 0);\n  STF_ULP_EQUAL(gamma(T(5)), T(24), 0);\n }\n", "meta": {"hexsha": "5e9691a8178a72e467b5c929ced2e35c7795e0e8", "size": 1752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/gamma.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/scalar/gamma.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/gamma.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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": 35.04, "max_line_length": 100, "alphanum_fraction": 0.6210045662, "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5094891599616912}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/ml/glm/logistic_regression_with_lbfgs.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\ndouble to_double(std::string& line) {\n  return boost::lexical_cast<double>(line);\n}\n\nBOOST_AUTO_TEST_CASE( frovedis_test )\n{\n    int argc = 1;\n    char** argv = NULL;\n    use_frovedis use(argc, argv);\n\n    auto data = make_crs_matrix_load<double> (\"./data\");\n    auto label = make_dvector_loadline(\"./label\").map(to_double);\n\n    size_t num_iteration = 200;\n    double alpha = 1.0;\n    size_t hist_size = 10;\n    bool intercept = true;\n    RegType rt = L2;\n    double regParam = 0.01;\n\n    auto model = logistic_regression_with_lbfgs::train(std::move(data),label,\n                                   num_iteration, alpha, hist_size,\n                                   regParam, rt, intercept); \n\n    auto mat = make_crs_matrix_local_load<double>(\"./data\");    \n    auto out_p = model.predict(mat);\n    auto out_pb = model.predict_probability(mat);\n    for(auto i: out_p) cout << i << \" \"; cout << endl;\n    for(auto i: out_pb) cout << i << \" \"; cout << endl;\n\n    double tol = 0.01;\n    std::vector<double> expected_out_p = {1.0, -1.0, 1.0, 1.0};\n    std::vector<double> expected_out_pb = {1.0, 0.0, 1.0, 1.0};\n    BOOST_CHECK (calc_rms_err<double> (out_p,expected_out_p) < tol);\n    BOOST_CHECK (calc_rms_err<double> (out_pb,expected_out_pb) < tol);\n}\n\n", "meta": {"hexsha": "6b39b1a076e953868de3796accb04487e334e718", "size": 1490, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/ml/test2.1-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/ml/test2.1-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/ml/test2.1-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": 31.0416666667, "max_line_length": 77, "alphanum_fraction": 0.644295302, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5094796354764146}}
{"text": "#include <utils/LQR.hpp>\n\n#include <Eigen/Eigenvalues>\n#include <iostream>\n\n#include <utils/utilities.hpp>\n\nusing namespace std;\n\nnamespace sejong{\n    void LQR(const Matrix & A,\n             const Matrix & B,\n             const Matrix & Q,\n             const Matrix & R,\n             Matrix & S, bool descrete){\n        int n = A.rows();\n        \n\n        Matrix Z(2*n, 2*n);\n\n        if(!descrete){\n            // sejong::pretty_print(A, std::cout, \"A\",\"\");\n            // sejong::pretty_print(B, std::cout, \"B\",\"\");\n            // sejong::pretty_print(Q, std::cout, \"Q\",\"\");\n            // sejong::pretty_print(R, std::cout, \"R\",\"\");\n\n            Z.block(0, 0, n, n) = A;\n\n            Z.block(0, n, n, n) = -B * R.inverse() * B.transpose();\n\n            Z.block(n, 0, n, n) = -Q;\n\n            Z.block(n, n, n, n) = -A.transpose();\n\n        } else {\n\n            Matrix Ainv = A.inverse();\n            Z.block(0, 0, n, n) = A + B * R.inverse() * B.transpose() * Ainv.transpose() * Q;\n            Z.block(0, n, n, n) = -B * R.inverse() * B.transpose() * Ainv.transpose();\n            Z.block(n, 0, n, n) = -Ainv.transpose() * Q;\n            Z.block(n, n, n, n) = Ainv.transpose();\n\n        }\n\n        Eigen::EigenSolver<Matrix> es(Z);\n        Eigen::MatrixXcd V(2*n, n);\n        // cout << \"The eigenvalues of Z are:\" << endl << es.eigenvalues() << endl;\n\n        int col_num(0);\n        for (int i(0); i<2*n; ++i){\n            if(!descrete){\n                if( (es.eigenvalues()[i]).real() < 0.0){\n                    V.col(col_num) = es.eigenvectors().col(i);\n                    ++col_num;\n                }\n            } else {\n                if( ((es.eigenvalues()[i]).real())*( (es.eigenvalues()[i]).real()) < 1.0){\n                    V.col(col_num) = es.eigenvectors().col(i);\n                    ++col_num;\n                }\n            }\n        }\n        // cout << \"The eigenvalues of Z are:\" << endl << es.eigenvalues() << endl;\n        // cout << \"The matrix of eigenvectors, V, is:\" << endl << es.eigenvectors() << endl << endl;\n        // cout << \"Finally, S = \" << endl << S << endl;\n\n        Eigen::MatrixXcd Stmp = V.block(n, 0, n, n) * (V.block(0, 0, n, n)).inverse();\n        S = Stmp.real();\n    }\n}\n", "meta": {"hexsha": "e82b978b8b6f25c17a60f38e069501aef83eeffd", "size": 2225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/src/LQR.cpp", "max_stars_repo_name": "junhyeokahn/DracoNodelet", "max_stars_repo_head_hexsha": "0f87331ceaf4fe42f9bab164954c5e9cb9c010f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-31T13:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T12:42:09.000Z", "max_issues_repo_path": "utils/src/LQR.cpp", "max_issues_repo_name": "junhyeokahn/DracoNodelet", "max_issues_repo_head_hexsha": "0f87331ceaf4fe42f9bab164954c5e9cb9c010f4", "max_issues_repo_licenses": ["MIT"], "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/src/LQR.cpp", "max_forks_repo_name": "junhyeokahn/DracoNodelet", "max_forks_repo_head_hexsha": "0f87331ceaf4fe42f9bab164954c5e9cb9c010f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-05T04:11:49.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-05T04:11:49.000Z", "avg_line_length": 31.338028169, "max_line_length": 101, "alphanum_fraction": 0.4426966292, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5094796253534327}}
{"text": "/*\n * problem_adjointness.cpp\n *\n *  Created on: 06.03.2018\n *      Author: thies\n */\n\n#include <base/ConstantMesh.h>\n#include <base/DiscretizedFunction.h>\n#include <base/MacroFunctionParser.h>\n#include <base/Norm.h>\n#include <base/SpaceTimeMesh.h>\n#include <base/Transformation.h>\n#include <base/Tuple.h>\n#include <base/Util.h>\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/numbers.h>\n#include <deal.II/base/point.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria.h>\n#include <forward/WaveEquation.h>\n#include <forward/WaveEquationBase.h>\n#include <gtest/gtest.h>\n#include <measurements/FieldMeasure.h>\n#include <measurements/Measure.h>\n#include <norms/H1H1.h>\n#include <norms/H1L2.h>\n#include <norms/L2L2.h>\n#include <problems/RhoProblem.h>\n#include <problems/CProblem.h>\n#include <problems/NuProblem.h>\n#include <problems/QProblem.h>\n#include <stddef.h>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace {\n\nusing namespace dealii;\nusing namespace wavepi::forward;\nusing namespace wavepi::base;\nusing namespace wavepi::problems;\nusing namespace wavepi::measurements;\nusing namespace wavepi;\n\ntemplate<int dim>\nclass TestF: public LightFunction<dim> {\npublic:\n   double evaluate(const Point<dim> &p, const double t) const {\n       if (p.norm() < 0.5)\n         return std::sin(t * 2 * numbers::PI);\n      else\n         return 0.0;\n   }\n};\n\ntemplate<int dim>\nclass TestG: public LightFunction<dim> {\npublic:\n   double evaluate(const Point<dim> &p, const double t) const {\n      Point<dim> pc = Point<dim>::unit_vector(0);\n      pc *= 0.5;\n\n      return t * std::sin(p.distance(pc) * 2 * numbers::PI);\n   }\n};\n\ntemplate<int dim>\nclass TestH: public LightFunction<dim> {\npublic:\n   double evaluate(const Point<dim> &p, const double t) const {\n        return p.norm() * t;\n   }\n};\n\ntemplate<int dim>\ndouble rho(const Point<dim> &p, double t) {\n   return p.norm() + t + 1.0;\n}\n\ntemplate<int dim>\ndouble c_squared(const Point<dim> &p, double t) {\n   double tmp = p.norm() * t + 1.0;\n\n   return tmp * tmp;\n}\n\ntemplate<int dim>\nclass TestC: public LightFunction<dim> {\npublic:\n   double evaluate(const Point<dim> &p, const double t) const {\n     return 1.0 / (rho(p, t) * c_squared(p, t));\n   }\n};\n\ntemplate<int dim>\nclass TestRho: public LightFunction<dim> {\npublic:\n   double evaluate(const Point<dim> &p, const double t) const {\n     return rho(p, t);\n   }\n};\n\ntemplate<int dim>\nclass TestNu: public LightFunction<dim> {\npublic:\n   double evaluate(const Point<dim> &p, const double t) const {\n    if (t > 1.0) return 0.0;\n\n      return std::abs(p[0]) * t;\n   }\n};\n\ntemplate<int dim>\nclass TestQ: public LightFunction<dim> {\npublic:\n   double evaluate(const Point<dim> &p, const double t) const {\n    return p.norm() < 0.5 ? std::sin(t / 2 * 2 * numbers::PI) : 0.0;\n   }\n\n   static const Point<dim> q_position;\n};\n\ntemplate<int dim>\nclass TestEstimate: public LightFunction<dim> {\npublic:\n   double evaluate(const Point<dim> &p __attribute__((unused)), const double t __attribute__((unused))) const {\n           return 2;\n   }\n};\n\ntemplate<>\nconst Point<1> TestQ<1>::q_position = Point<1>(-1.0);\ntemplate<>\nconst Point<2> TestQ<2>::q_position = Point<2>(-1.0, 0.5);\ntemplate<>\nconst Point<3> TestQ<3>::q_position = Point<3>(-1.0, 0.5, 0.0);\n\ntemplate<int dim, typename ProblemType>\nvoid run_adjoint_test(int fe_order, int quad_order, int refines, int n_steps,\n      std::shared_ptr<Norm<DiscretizedFunction<dim>>> norm_domain,\n      std::shared_ptr<Norm<DiscretizedFunction<dim>>> norm_codomain, double tol) {\n   auto triangulation = std::make_shared<Triangulation<dim>>();\n   GridGenerator::hyper_cube(*triangulation, -1, 1);\n   Util::set_all_boundary_ids(*triangulation, 0);\n   triangulation->refine_global(refines);\n\n   double t_start = 0.0, t_end = 2.0, dt = t_end / n_steps;\n   std::vector<double> times;\n\n   for (size_t i = 0; t_start + i * dt <= t_end; i++)\n      times.push_back(t_start + i * dt);\n\n   std::shared_ptr<SpaceTimeMesh<dim>> mesh = std::make_shared<ConstantMesh<dim>>(times, FE_Q<dim>(fe_order),\n         QGauss<dim>(quad_order), triangulation);\n\n   deallog << std::endl << \"----------  n_dofs / timestep: \" << mesh->get_dof_handler(0)->n_dofs();\n   deallog << \", n_steps: \" << times.size() << \"  ----------\" << std::endl;\n\n   WaveEquation<dim> wave_eq(mesh);\n   wave_eq.set_param_rho(std::make_shared<TestRho<dim>>());\n   wave_eq.set_param_c(std::make_shared<TestC<dim>>());\n   wave_eq.set_param_q(std::make_shared<TestQ<dim>>());\n   wave_eq.set_param_nu(std::make_shared<TestNu<dim>>());\n\n   TestEstimate<dim> est_cont;\n   DiscretizedFunction<dim> estimate(mesh, est_cont);\n   estimate.set_norm(norm_domain);\n\n   std::vector<std::shared_ptr<Measure<DiscretizedFunction<dim>, DiscretizedFunction<dim>>>> measures;\n   measures.push_back(std::make_shared<FieldMeasure<dim>>(mesh, norm_codomain));\n\n   std::map<std::string, double> consts;\n   std::vector<std::shared_ptr<Function<dim>>> pulses;\n   pulses.push_back(std::make_shared<MacroFunctionParser<dim>>(\"if(norm{x|y|z} < 0.2, sin(t), 0.0)\", consts));\n\n   ProblemType problem(wave_eq, pulses, measures, std::make_shared<IdentityTransform<dim>>(), 0);\n   problem.set_adjoint_solver(WaveEquationBase<dim>::WaveEquationAdjoint);\n\n   problem.set_norm_domain(norm_domain);\n   problem.set_norm_codomain(norm_codomain);\n\n   auto data_current = problem.forward(estimate);  // have to run forward at least once\n   auto A = problem.derivative(estimate);\n\n   double err_avg = 0.0;\n   double err_simple;\n\n   for (size_t i = 0; i < 11; i++) {\n      std::shared_ptr<DiscretizedFunction<dim>> f, g;\n\n      if (i == 0) {\n         TestF<dim> f_cont;\n         f = std::make_shared<DiscretizedFunction<dim>>(mesh, f_cont);\n\n         TestG<dim> g_cont;\n         g = std::make_shared<DiscretizedFunction<dim>>(mesh, g_cont);\n      } else {\n         f = std::make_shared<DiscretizedFunction<dim>>(DiscretizedFunction<dim>::noise(mesh));\n\n         // make it a bit smoother, random noise might be a bit too harsh\n         f->set_norm(std::make_shared<norms::H1L2<dim>>(0.5));\n         f->dot_transform_inverse();\n\n         g = std::make_shared<DiscretizedFunction<dim>>(DiscretizedFunction<dim>::noise(mesh));\n\n         // make it a bit smoother, random noise might be a bit too harsh\n         g->set_norm(std::make_shared<norms::H1L2<dim>>(0.5));\n         g->dot_transform_inverse();\n      }\n\n      // normalize both f and g (not necessary)\n      f->set_norm(norm_domain);\n      *f *= 1.0 / f->norm();\n\n      g->set_norm(norm_codomain);\n      *g *= 1.0 / g->norm();\n      Tuple<DiscretizedFunction<dim>> Tg(*g);\n\n      auto Af = A->forward(*f);\n      EXPECT_GT(Af.norm(), 0.0);\n\n      auto Astarg = A->adjoint(Tg);\n      EXPECT_GT(Astarg.norm(), 0.0);\n\n      double dot_solf_g = Af * Tg;\n      double dot_f_adjg = (*f) * Astarg;\n      double fg_err = std::abs(dot_solf_g - dot_f_adjg) / (std::abs(dot_solf_g) + 1e-300);\n\n      if (i == 0) {\n         // deallog << \"simple f,g: \" << std::scientific << \"(Lf, g) = \" << dot_solf_g << \", (f, L*g) = \" << dot_f_adjg\n         //         << std::endl;\n         err_simple = fg_err;\n         deallog << std::scientific << \"        relative error for simple f,g = \" << fg_err << std::endl;\n      } else\n         err_avg = ((i - 1) * err_avg + fg_err) / i;\n\n      // deallog << std::scientific << \"(Lf, g) = \" << dot_solf_g << \", (f, L*g) = \" << dot_f_adjg\n      //        << \", rel. error = \" << fg_err << std::endl;\n\n      // EXPECT_LT(zz_err, tol);\n   }\n\n   deallog << std::scientific << \"average relative error for random f,g = \" << err_avg << std::endl;\n   EXPECT_LT(err_simple, tol);\n   EXPECT_LT(err_avg, tol);\n}\n}  // namespace\n\n/* Q */\n\nTEST(ProblemAdjointness, AdjointQ1DFE1) {\n   for (int i = 3; i < 10; i++)\n      run_adjoint_test<1, QProblem<1, DiscretizedFunction<1>>>(1, 3, 6, 1 << i, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n\n   for (int refine = 6; refine >= 1; refine--)\n      run_adjoint_test<1, QProblem<1, DiscretizedFunction<1>>>(1, 3, refine, 1 << 9, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointQ1DFE2) {\n   for (int i = 3; i < 10; i++)\n      run_adjoint_test<1, QProblem<1, DiscretizedFunction<1>>>(2, 6, 4, 1 << i, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n\n   for (int refine = 4; refine >= 1; refine--)\n      run_adjoint_test<1, QProblem<1, DiscretizedFunction<1>>>(1, 3, refine, 1 << 9, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointQ2DFE1) {\n   for (int i = 3; i < 9; i++)\n      run_adjoint_test<2, QProblem<2, DiscretizedFunction<2>>>(1, 3, 5, 1 << i, std::make_shared<norms::L2L2<2>>(),\n            std::make_shared<norms::L2L2<2>>(), 1e-1);\n\n   for (int refine = 4; refine >= 1; refine--)\n      run_adjoint_test<2, QProblem<2, DiscretizedFunction<2>>>(1, 3, refine, 1 << 8, std::make_shared<norms::L2L2<2>>(),\n            std::make_shared<norms::L2L2<2>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointQ2DFE1H1H1) {\n   for (int i = 3; i < 9; i++)\n      run_adjoint_test<2, QProblem<2, DiscretizedFunction<2>>>(1, 3, 5, 1 << i,\n            std::make_shared<norms::H1H1<2>>(0.5, 0.5), std::make_shared<norms::L2L2<2>>(), 1e-1);\n\n   for (int refine = 4; refine >= 1; refine--)\n      run_adjoint_test<2, QProblem<2, DiscretizedFunction<2>>>(1, 3, refine, 1 << 8,\n            std::make_shared<norms::H1H1<2>>(0.5, 0.5), std::make_shared<norms::L2L2<2>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointQ3DFE1) {\n   for (int i = 3; i < 5; i++)\n      run_adjoint_test<3, QProblem<3, DiscretizedFunction<3>>>(1, 3, 2, 1 << i, std::make_shared<norms::L2L2<3>>(),\n            std::make_shared<norms::L2L2<3>>(), 1e-1);\n}\n\n/* A */\n\nTEST(ProblemAdjointness, AdjointRho1DFE1) {\n   for (int i = 3; i < 10; i++)\n      run_adjoint_test<1, RhoProblem<1, DiscretizedFunction<1>>>(1, 3, 6, 1 << i, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n\n   for (int refine = 6; refine >= 1; refine--)\n      run_adjoint_test<1, RhoProblem<1, DiscretizedFunction<1>>>(1, 3, refine, 1 << 9, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointRho1DFE2) {\n   for (int i = 3; i < 10; i++)\n      run_adjoint_test<1, RhoProblem<1, DiscretizedFunction<1>>>(2, 6, 4, 1 << i, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n\n   for (int refine = 4; refine >= 1; refine--)\n      run_adjoint_test<1, RhoProblem<1, DiscretizedFunction<1>>>(1, 3, refine, 1 << 9, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointRho2DFE1) {\n   for (int i = 3; i < 9; i++)\n      run_adjoint_test<2, RhoProblem<2, DiscretizedFunction<2>>>(1, 3, 5, 1 << i, std::make_shared<norms::L2L2<2>>(),\n            std::make_shared<norms::L2L2<2>>(), 1e-1);\n\n   for (int refine = 4; refine >= 1; refine--)\n      run_adjoint_test<2, RhoProblem<2, DiscretizedFunction<2>>>(1, 3, refine, 1 << 8, std::make_shared<norms::L2L2<2>>(),\n            std::make_shared<norms::L2L2<2>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointRho2DFE1H1H1) {\n   for (int i = 3; i < 9; i++)\n      run_adjoint_test<2, RhoProblem<2, DiscretizedFunction<2>>>(1, 3, 5, 1 << i,\n            std::make_shared<norms::H1H1<2>>(0.5, 0.5), std::make_shared<norms::L2L2<2>>(), 1e-1);\n\n   for (int refine = 4; refine >= 1; refine--)\n      run_adjoint_test<2, RhoProblem<2, DiscretizedFunction<2>>>(1, 3, refine, 1 << 8,\n            std::make_shared<norms::H1H1<2>>(0.5, 0.5), std::make_shared<norms::L2L2<2>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointRho3DFE1) {\n   for (int i = 3; i < 5; i++)\n      run_adjoint_test<3, RhoProblem<3, DiscretizedFunction<3>>>(1, 3, 2, 1 << i, std::make_shared<norms::L2L2<3>>(),\n            std::make_shared<norms::L2L2<3>>(), 1e-1);\n}\n\n/* Nu */\n\nTEST(ProblemAdjointness, AdjointNu1DFE1) {\n   for (int i = 3; i < 10; i++)\n      run_adjoint_test<1, NuProblem<1, DiscretizedFunction<1>>>(1, 3, 6, 1 << i, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n\n   for (int refine = 6; refine >= 1; refine--)\n      run_adjoint_test<1, NuProblem<1, DiscretizedFunction<1>>>(1, 3, refine, 1 << 9,\n            std::make_shared<norms::L2L2<1>>(), std::make_shared<norms::L2L2<1>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointNu1DFE2) {\n   for (int i = 3; i < 10; i++)\n      run_adjoint_test<1, NuProblem<1, DiscretizedFunction<1>>>(2, 6, 4, 1 << i, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n\n   for (int refine = 4; refine >= 1; refine--)\n      run_adjoint_test<1, NuProblem<1, DiscretizedFunction<1>>>(1, 3, refine, 1 << 9,\n            std::make_shared<norms::L2L2<1>>(), std::make_shared<norms::L2L2<1>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointNu2DFE1) {\n   for (int i = 3; i < 9; i++)\n      run_adjoint_test<2, NuProblem<2, DiscretizedFunction<2>>>(1, 3, 5, 1 << i, std::make_shared<norms::L2L2<2>>(),\n            std::make_shared<norms::L2L2<2>>(), 1e-1);\n\n   for (int refine = 4; refine >= 1; refine--)\n      run_adjoint_test<2, NuProblem<2, DiscretizedFunction<2>>>(1, 3, refine, 1 << 8,\n            std::make_shared<norms::L2L2<2>>(), std::make_shared<norms::L2L2<2>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointNu2DFE1H1H1) {\n   for (int i = 3; i < 9; i++)\n      run_adjoint_test<2, NuProblem<2, DiscretizedFunction<2>>>(1, 3, 5, 1 << i,\n            std::make_shared<norms::H1H1<2>>(0.5, 0.5), std::make_shared<norms::L2L2<2>>(), 1e-1);\n\n   for (int refine = 4; refine >= 1; refine--)\n      run_adjoint_test<2, NuProblem<2, DiscretizedFunction<2>>>(1, 3, refine, 1 << 8,\n            std::make_shared<norms::H1H1<2>>(0.5, 0.5), std::make_shared<norms::L2L2<2>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointNu3DFE1) {\n   for (int i = 3; i < 5; i++)\n      run_adjoint_test<3, NuProblem<3, DiscretizedFunction<3>>>(1, 3, 2, 1 << i, std::make_shared<norms::L2L2<3>>(),\n            std::make_shared<norms::L2L2<3>>(), 1e-1);\n}\n\n/* C */\n\nTEST(ProblemAdjointness, AdjointC1DFE1) {\n   for (int i = 3; i < 10; i++)\n      run_adjoint_test<1, CProblem<1, DiscretizedFunction<1>>>(1, 3, 6, 1 << i, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n\n   for (int refine = 6; refine >= 1; refine--)\n      run_adjoint_test<1, CProblem<1, DiscretizedFunction<1>>>(1, 3, refine, 1 << 9, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointC1DFE2) {\n   for (int i = 3; i < 10; i++)\n      run_adjoint_test<1, CProblem<1, DiscretizedFunction<1>>>(2, 6, 4, 1 << i, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n\n   for (int refine = 4; refine >= 1; refine--)\n      run_adjoint_test<1, CProblem<1, DiscretizedFunction<1>>>(1, 3, refine, 1 << 9, std::make_shared<norms::L2L2<1>>(),\n            std::make_shared<norms::L2L2<1>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointC2DFE1) {\n   for (int i = 3; i < 9; i++)\n      run_adjoint_test<2, CProblem<2, DiscretizedFunction<2>>>(1, 3, 5, 1 << i, std::make_shared<norms::L2L2<2>>(),\n            std::make_shared<norms::L2L2<2>>(), 1e-1);\n\n   for (int refine = 4; refine >= 1; refine--)\n      run_adjoint_test<2, CProblem<2, DiscretizedFunction<2>>>(1, 3, refine, 1 << 8, std::make_shared<norms::L2L2<2>>(),\n            std::make_shared<norms::L2L2<2>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointC2DFE1H1H1) {\n   for (int i = 3; i < 9; i++)\n      run_adjoint_test<2, CProblem<2, DiscretizedFunction<2>>>(1, 3, 5, 1 << i,\n            std::make_shared<norms::H1H1<2>>(0.5, 0.5), std::make_shared<norms::L2L2<2>>(), 1e-1);\n\n   for (int refine = 4; refine >= 1; refine--)\n      run_adjoint_test<2, CProblem<2, DiscretizedFunction<2>>>(1, 3, refine, 1 << 8,\n            std::make_shared<norms::H1H1<2>>(0.5, 0.5), std::make_shared<norms::L2L2<2>>(), 1e-1);\n}\n\nTEST(ProblemAdjointness, AdjointC3DFE1) {\n   for (int i = 3; i < 5; i++)\n      run_adjoint_test<3, CProblem<3, DiscretizedFunction<3>>>(1, 3, 2, 1 << i, std::make_shared<norms::L2L2<3>>(),\n            std::make_shared<norms::L2L2<3>>(), 1e-1);\n}\n", "meta": {"hexsha": "68ba7eabbc6db78a0ee0c69ef69d445523d6f823", "size": 16539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/problem_adjointness.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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/problem_adjointness.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/problem_adjointness.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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.9174107143, "max_line_length": 122, "alphanum_fraction": 0.622589032, "num_tokens": 5861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5094796253534327}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_MATRIXIO_HPP\n#define MCL_MATRIXIO_HPP 1\n\n#include <Eigen/Dense>\n#include <fstream>\n\nnamespace mcl\n{\n\ntemplate <typename Derived>\nstatic inline void write_eigen_matrix(const std::string& fn, const Eigen::MatrixBase<Derived>& A)\n{\n\tstd::ofstream file(fn);\n\tif (file.is_open()) { file << A; }\n}\n\ntemplate<typename T, int dim = Eigen::Dynamic>\nstatic inline bool read_eigen_matrix(const std::string &fn, Eigen::Matrix<T,Eigen::Dynamic,dim> &A)\n{\n\t// dim most often -1 (Eigen::Dynamic)\n\n\tstd::vector<std::vector<T> > vals;\n\tstd::ifstream ifs;\n\tifs.open(fn.c_str());\n\tif (!ifs) { return false; }\n\tint cols = 0;\n\n\tstd::string line;\n\twhile(std::getline(ifs, line))\n\t{\n\t\tvals.emplace_back(std::vector<T>());\n\t\tstd::istringstream ss(line);\n\t\twhile (ss.good())\n\t\t{\n\t\t\tT val; ss >> val;\n\t\t\tvals.back().emplace_back(val);\n\t\t}\n\t\tcols = std::max(cols, int(vals.back().size()));\n\t}\n\tifs.close();\n\n\tint rows = vals.size();\n\tif(rows==0 || cols==0)\n\t{\n\t\t// File exists, it's just empty\n\t\tA = Eigen::Matrix<T,Eigen::Dynamic,dim>();\n\t\treturn true;\n\t}\n\tcols = dim > 0 ? std::min(cols, dim) : cols;\n\tA = Eigen::Matrix<T,Eigen::Dynamic,dim>::Zero(rows,cols);\n\tint nx = vals.size();\n\tfor(int i=0; i<nx; ++i)\n\t{\n\t\tfor(int j=0; j<cols; ++j)\n\t\t{\n\t\t\tA(i,j) = vals[i][j];\n\t\t}\n\t}\n\treturn true;\n\n}; // end read matrix\n\n} // end namespace mcl\n\n#endif", "meta": {"hexsha": "1e346d44bfadb9e7b4d5e47361a7c9721299224d", "size": 1399, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/EigenMatrixIO.hpp", "max_stars_repo_name": "mattoverby/mclgeom", "max_stars_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/MCL/EigenMatrixIO.hpp", "max_issues_repo_name": "mattoverby/mclgeom", "max_issues_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-26T22:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T02:54:23.000Z", "max_forks_repo_path": "include/MCL/EigenMatrixIO.hpp", "max_forks_repo_name": "mattoverby/mclgeom", "max_forks_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5735294118, "max_line_length": 99, "alphanum_fraction": 0.6390278771, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5093955489479239}}
{"text": "#include <gen/terrain.hpp>\n\n#include <boost/graph/astar_search.hpp>\n#include <gen/graphutils.hpp>\n\n#include <gen/poissonsampling.hpp>\n#include <math/mathtools.hpp>\n\n#include <armadillo>\n\nnamespace eXl\n{\n\n  class ArmaLaplaceMatrix : public LaplaceMatrix\n  {\n  public:\n    arma::sp_mat m_Matrix;\n  };\n\n  struct found_goal{};\n\n\n  template <class Vertex>\n  class astar_goal_visitor : public boost::default_astar_visitor\n  {\n  public:\n    inline astar_goal_visitor(Vertex goal) : m_goal(goal) {}\n    template <class Graph>\n    void examine_vertex(Vertex u, Graph& g) {\n      if(u == m_goal)\n        throw found_goal();\n    }\n  private:\n    Vertex m_goal;\n  };\n\n  template<typename PosMap>\n  class VoroDiagGraphDistance : public boost::astar_heuristic<VoronoiGraph::CellGraphImpl, float>\n  {\n  public:\n    typedef boost::graph_traits<VoronoiGraph::CellGraphImpl>::vertex_descriptor Vertex;\n    VoroDiagGraphDistance(PosMap const& iCenters, Vertex iGoal, TIndexMap<VoronoiGraph::CellGraphImpl> const& iIndex)\n      : m_CellCenter(iCenters), m_Goal(iGoal), m_Index(iIndex) {}\n    float operator()(Vertex u)\n    {\n      unsigned int goalIdx = boost::get(m_Index, m_Goal);\n      unsigned int idx = boost::get(m_Index, u);\n\n      Vector2f goalPos = m_CellCenter(goalIdx);\n      Vector2f curPos = m_CellCenter(idx);\n\n      return (curPos - goalPos).Length();\n    }\n  private:\n    PosMap const& m_CellCenter;\n    TIndexMap<VoronoiGraph::CellGraphImpl> const& m_Index;\n    Vertex m_Goal;\n  };\n\n  template<typename PosMap>\n  void FindPath(VoronoiGraph::CellGraph const& iGraph,\n    PosMap const& iCellCenters,\n    VoronoiGraph::CellGraphImpl::vertex_descriptor start,\n    VoronoiGraph::CellGraphImpl::vertex_descriptor goal,\n    Vector<VoronoiGraph::CellGraphImpl::vertex_descriptor>& oPath)\n  {\n    IndexMap<VoronoiGraph::CellGraphImpl> index(iGraph.m_CellGraph);\n    Vector<VoronoiGraph::CellGraphImpl::vertex_descriptor> p(boost::num_vertices(iGraph.m_CellGraph), start);\n    Vector<float> d(boost::num_vertices(iGraph.m_CellGraph));\n    bool found = false;\n    try \n    {\n      // call astar named parameter interface\n      boost::astar_search_tree\n      (iGraph.m_CellGraph, start,\n        VoroDiagGraphDistance<PosMap>(iCellCenters, goal, index),\n        //iFactory.Make<boost::filtered_graph<OutGraph, boost::keep_all, TagFilter> >(filteredGr, goal),\n        boost::predecessor_map(boost::make_iterator_property_map(p.begin(), index)).\n        distance_map(make_iterator_property_map(d.begin(), index)).\n        visitor(astar_goal_visitor<VoronoiGraph::CellGraphImpl::vertex_descriptor>(goal)));\n    } \n    catch(found_goal ) \n    { // found a path to the goal\n      Vector<VoronoiGraph::CellGraphImpl::vertex_descriptor> path;\n      for(auto v = goal;; v = p[v]) \n      {\n        path.push_back(v);\n\n        if(p[v] == v)\n          break;\n      }\n      oPath.swap(path);\n      found = true;\n    }\n  }\n\n  struct TerrainPosMap\n  {\n    TerrainPosMap(Vector<Terrain::CellProperties> const& iCells)\n      :m_Cells(iCells){}\n\n    Vector2f const& operator()(unsigned int i) const {return m_Cells[i].position;}\n\n    Vector<Terrain::CellProperties> const& m_Cells;\n  };\n\n  Terrain::Terrain()\n  {\n  }\n  \n  void Terrain::MakeGrid(Vector2f const& iSize, Vector2i const& iGridSize)\n  {\n    m_Size = iSize;\n    \n    Vector2f gridStep(iSize.X() / iGridSize.X(), iSize.Y() / iGridSize.Y());\n\n    m_QueryBox = AABB2Df(-gridStep * 0.51, gridStep * 1.02);\n\n    m_Cells.clear();\n    m_Graph.m_CellGraph.clear();\n    m_Graph.m_Edges.clear();\n    m_Graph.m_Vertices.clear();\n    m_Neigh.clear();\n    m_Index.clear();\n\n    uint32_t totNumCells = iGridSize.X() * iGridSize.Y();\n\n    m_Cells.reserve(totNumCells);\n    m_Neigh.reserve(totNumCells * 4);\n    for (uint32_t i = 0; i < totNumCells; ++i)\n    {\n      boost::add_vertex(m_Graph.m_CellGraph);\n    }\n    \n    for (int32_t y = 0; y < iGridSize.Y() + 1; ++y)\n    {\n      for (int32_t x = 0; x < iGridSize.X() + 1; ++x)\n      {\n        VoronoiGraph::Vertex gridVtx;\n        gridVtx.m_Position = Vector2f(gridStep.X() * x, gridStep.Y() * y);\n        m_Graph.m_Vertices.push_back(gridVtx);\n      }\n    }\n\n    uint32_t cellOffset = 0;\n    Vector<CellLoc> locs;\n    locs.reserve(totNumCells);\n    for (int32_t y = 0; y < iGridSize.Y(); ++y)\n    {\n      for (int32_t x = 0; x < iGridSize.X(); ++x)\n      {\n        uint32_t gridLowLeftCorner = y * (iGridSize.X() + 1) + x;\n\n        CellProperties cell;\n        cell.neighCount = 0;\n        cell.position = Vector2f(((float)x + 0.5) * gridStep.X(), ((float)y + 0.5) * gridStep.Y());\n        cell.neighStart = m_Neigh.size();\n\n        Vector2f const& cellPos = cell.position;\n        locs.push_back(std::make_pair(AABB2Df(cellPos - gridStep * 0.5, gridStep), cellOffset));\n\n        if (x > 0)\n        {\n          cell.neighCount++;\n          m_Neigh.push_back(cellOffset - 1);\n        //  auto edgeDesc = boost::add_edge(cellOffset, cellOffset - 1, m_Graph.m_CellGraph);\n        //  VoronoiGraph::Edge newEdge;\n        //  newEdge.m_Pt1 = gridLowLeftCorner;\n        //  newEdge.m_Pt2 = gridLowLeftCorner + iGridSize.X() + 1;\n        //  m_Graph.m_Edges.insert(std::make_pair(edgeDesc, newEdge));\n        }\n\n        if (x < iGridSize.X() - 1)\n        {\n          cell.neighCount++;\n          m_Neigh.push_back(cellOffset + 1);\n          auto edgeDesc = boost::add_edge(cellOffset, cellOffset + 1, m_Graph.m_CellGraph).first;\n          VoronoiGraph::Edge newEdge;\n          newEdge.m_Pt1 = gridLowLeftCorner + 1;\n          newEdge.m_Pt2 = gridLowLeftCorner + 1 + iGridSize.X() + 1;\n          m_Graph.m_Edges[edgeDesc] = newEdge;\n        }\n\n        if (y > 0)\n        {\n          cell.neighCount++;\n          m_Neigh.push_back(cellOffset - iGridSize.X());\n        //  auto edgeDesc = boost::add_edge(cellOffset, cellOffset - iGridSize.X(), m_Graph.m_CellGraph);\n        //  VoronoiGraph::Edge newEdge;\n        //  newEdge.m_Pt1 = gridLowLeftCorner;\n        //  newEdge.m_Pt2 = gridLowLeftCorner + 1;\n        //  m_Graph.m_Edges.insert(std::make_pair(edgeDesc, newEdge));\n        }\n\n        if (y < iGridSize.Y() - 1)\n        {\n          cell.neighCount++;\n          m_Neigh.push_back(cellOffset + iGridSize.X());\n\n          auto edgeDesc = boost::add_edge(cellOffset, cellOffset + iGridSize.X(), m_Graph.m_CellGraph).first;\n          VoronoiGraph::Edge newEdge;\n          newEdge.m_Pt1 = gridLowLeftCorner + iGridSize.X() + 1;\n          newEdge.m_Pt2 = gridLowLeftCorner + 1 + iGridSize.X() + 1;\n          m_Graph.m_Edges[edgeDesc] = newEdge;\n        }\n        m_Cells.push_back(cell);\n        ++cellOffset;\n      }\n    }\n\n    m_Index = CellIndex(locs);\n  }\n\n  void Terrain::MakeCirclePacking(Random& iRand, Vector2f const& iSize, float iCellSize)\n  {\n    m_Size = iSize;\n\n    m_QueryBox = AABB2Df(-iCellSize * 1.1, -iCellSize * 1.1, iCellSize * 1.1, iCellSize * 1.1);\n\n    m_Cells.clear();\n    m_Graph.m_CellGraph.clear();\n    m_Graph.m_Edges.clear();\n    m_Graph.m_Vertices.clear();\n    m_Neigh.clear();\n    m_Index.clear();\n\n    Polygoni poly(AABB2Di(Vector2i::ZERO, Vector2i(Mathf::Ceil(m_Size.X()), Mathf::Ceil(m_Size.Y()))));\n    PoissonDiskSampling sampler(poly, iRand);\n\n    sampler.Sample(iCellSize, iCellSize);\n\n    Vector<Vector2d> samples;\n    Vector<Vector2f> cellCenter;\n    sampler.GetLayer(0, samples);\n    //sampler.GetLayer(1, samples[1]);\n    //sampler.GetLayer(2, samples[2]);\n\n    unsigned int const totSamples = samples.size() /*+ samples[1].size() + samples[2].size()*/;\n\n    VoronoiGraph voroGr;\n\n    for(unsigned int j = 0; j<samples.size(); ++j)\n    {\n      voroGr.AddCircle(iCellSize, MathTools::ToFVec(samples[j]));\n      cellCenter.push_back(MathTools::ToFVec(samples[j]));\n\n      CellProperties props;\n      props.position = cellCenter.back();\n      m_Cells.push_back(props);\n    }\n\n    voroGr.BuildGraph(m_Graph, true);\n\n\n    {\n      Vector<CellLoc> locs(cellCenter.size());\n      for(unsigned int i = 0; i<cellCenter.size(); ++i)\n      {\n        Vector2f const& cellPos = cellCenter[i];\n        locs.push_back(std::make_pair(AABB2Df(cellPos - Vector2f::ONE * iCellSize, Vector2f::ONE * 2 * iCellSize), i));\n      }\n      m_Index = CellIndex(locs);\n    }\n\n    unsigned int const numCells = m_Cells.size();\n    Vector<unsigned int> sortedPoints;\n\n    for (unsigned int i = 0; i < numCells; ++i)\n    {\n      m_Cells[i].neighCount = 0;\n      sortedPoints.clear();\n      Vector2f center = m_Cells[i].position;\n\n      VoronoiGraph::CellGraphImpl::out_edge_iterator edgesBegin, edgesEnd;\n      boost::tie(edgesBegin, edgesEnd) = boost::out_edges(i, m_Graph.m_CellGraph);\n      unsigned int numNeigh = std::distance(edgesBegin, edgesEnd);\n      if(edgesBegin != edgesEnd)\n      {\n        unsigned int firstPoint = i == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n        VoronoiGraph::Edge firstEdge = m_Graph.m_Edges.find(*edgesBegin)->second;\n        ++edgesBegin;\n        while(firstPoint == numCells)\n        {\n          --numNeigh;\n          firstPoint = i == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n          firstEdge = m_Graph.m_Edges.find(*edgesBegin)->second;\n          ++edgesBegin;\n        }\n\n        Segmentf::SortByAngle sortMeth(m_Cells[firstPoint].position);\n        std::map<Vector2f, unsigned int, Segmentf::SortByAngle > sortedPointsMap(sortMeth);\n\n        for (; edgesBegin != edgesEnd; ++edgesBegin)\n        {\n          unsigned int target = i == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n          if(target == numCells)\n          {\n            --numNeigh;\n            continue;\n          }\n          sortedPointsMap.insert(std::make_pair(m_Cells[target].position, target));\n        }\n        sortedPoints.push_back(firstPoint);\n        for(auto pair : sortedPointsMap)\n        {\n          sortedPoints.push_back(pair.second);\n        }\n\n        m_Cells[i].neighStart = m_Neigh.size();\n\n        for(uint32_t curNeighIdx = 0; curNeighIdx < numNeigh; ++curNeighIdx)\n        {\n          unsigned int curNeigh = sortedPoints[curNeighIdx];\n          \n          m_Neigh.push_back(curNeigh);\n        }\n\n        m_Cells[i].neighCount = numNeigh;\n      }\n    }\n  }\n\n  bool Terrain::GetClosestCell(Vector2f const& iPos, uint32_t& oCellIdx)\n  {\n    AABB2Df queryBox = m_QueryBox;\n    queryBox.m_Data[0] += iPos;\n    queryBox.m_Data[1] += iPos;\n\n    Vector<CellLoc> results;\n    m_Index.query(boost::geometry::index::intersects(queryBox), std::back_inserter(results));\n\n    if (results.empty())\n    {\n      return false;\n    }\n\n    float minDist = FLT_MAX;\n    for (auto const& cellLoc : results)\n    {\n      CellProperties const& cell = m_Cells[cellLoc.second];\n      float const distSq = (cell.position - iPos).SquaredLength();\n      if (minDist > distSq)\n      {\n        oCellIdx = cellLoc.second;\n        minDist = distSq;\n      }\n    }\n\n    return true;\n  }\n\n  void Terrain::GetLineCells(Segmentf const& iSeg, float iRadius, Vector<unsigned int>& oCells)\n  {\n    oCells.clear();\n\n    AABB2Df queryBox;\n    queryBox.m_Data[0] = iSeg.m_Ext1;\n    queryBox.m_Data[1] = iSeg.m_Ext1;\n    queryBox.Absorb(iSeg.m_Ext2);\n    queryBox.m_Data[0] -= Vector2f::ONE * iRadius;\n    queryBox.m_Data[1] += Vector2f::ONE * iRadius;\n\n    Vector<CellLoc> results;\n    m_Index.query(boost::geometry::index::intersects(queryBox), std::back_inserter(results));\n\n    for (auto const& cellLoc : results)\n    {\n      CellProperties const& cell = m_Cells[cellLoc.second];\n\n      Vector2f dir;\n      float dist = iSeg.NearestPointSeg(cell.position, dir);\n      if (dist < iRadius)\n      {\n        oCells.push_back(cellLoc.second);\n      }\n    }\n  }\n\n  void Terrain::GetDiskCells(Vector2f const& iCenter, float iRadius, Vector<unsigned int>& oCells)\n  {\n    oCells.clear();\n\n    AABB2Df queryBox(iCenter - iRadius * Vector2f::ONE, Vector2f::ONE * 2 * iRadius);\n\n    Vector<CellLoc> results;\n    m_Index.query(boost::geometry::index::intersects(queryBox), std::back_inserter(results));\n\n    for(auto cell : results)\n    {\n      if((m_Cells[cell.second].position - iCenter).Length() < iRadius)\n      {\n        oCells.push_back(cell.second);\n      }\n    }\n  }\n\n  void Terrain::BuildLaplaceMatrix(ConductivityGetter& iConductivity, LaplaceMatrix*& oMat)\n  {\n    unsigned int const numCells = m_Cells.size();\n\n    if (oMat != nullptr)\n    {\n      delete oMat;\n    }\n\n    ArmaLaplaceMatrix* matrix = eXl_NEW(ArmaLaplaceMatrix);\n\n    oMat = matrix;\n\n    arma::sp_mat& mat = matrix->m_Matrix;\n\n    mat.set_size(numCells, numCells);\n\n    //Vector<unsigned int> sortedPoints;\n    //Vector<Vector2f> cellPoints;\n\n    for (unsigned int i = 0; i < numCells; ++i)\n    {\n      //cellPoints.clear();\n      //sortedPoints.clear();\n      float sum = 0.0;\n\n      Vector2f center = m_Cells[i].position;\n\n      VoronoiGraph::CellGraphImpl::out_edge_iterator edgesBegin, edgesEnd;\n      boost::tie(edgesBegin, edgesEnd) = boost::out_edges(i, m_Graph.m_CellGraph);\n      \n      for (; edgesBegin != edgesEnd; ++edgesBegin)\n      {\n        unsigned int target = i == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n        if (target == numCells)\n        {\n          continue;\n        }\n        VoronoiGraph::Edge const& curEdge = m_Graph.m_Edges.find(*edgesBegin)->second;\n        \n        float edgeLen = (m_Graph.m_Vertices[curEdge.m_Pt2].m_Position - m_Graph.m_Vertices[curEdge.m_Pt1].m_Position).Length();\n        float cellDist = (center - m_Cells[target].position).Length();\n\n        float curConnectionValue = iConductivity(i, target, edgeLen, cellDist);\n        sum -= curConnectionValue;\n\n        mat.at(i, target) = 0.5 * curConnectionValue;\n      }\n\n      mat.at(i, i) = 0.5 * sum;\n    }\n  }\n\n  void Terrain::BuildSmoothingMatrix(LaplaceMatrix*& oMat)\n  {\n    unsigned int const numCells = m_Cells.size();\n\n    if (oMat != nullptr)\n    {\n      delete oMat;\n    }\n\n    ArmaLaplaceMatrix* matrix = eXl_NEW(ArmaLaplaceMatrix);\n\n    oMat = matrix;\n\n    arma::sp_mat& mat = matrix->m_Matrix;\n\n    mat.set_size(numCells, numCells);\n\n    Vector<unsigned int> sortedPoints;\n    Vector<Vector2f> cellPoints;\n\n    for (unsigned int i = 0; i < numCells; ++i)\n    {\n      cellPoints.clear();\n      sortedPoints.clear();\n      Vector2f center = m_Cells[i].position;\n      \n      VoronoiGraph::CellGraphImpl::out_edge_iterator edgesBegin, edgesEnd;\n      boost::tie(edgesBegin, edgesEnd) = boost::out_edges(i, m_Graph.m_CellGraph);\n      unsigned int numNeigh = std::distance(edgesBegin, edgesEnd);\n      if(edgesBegin != edgesEnd)\n      {\n        unsigned int firstPoint = i == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n        VoronoiGraph::Edge firstEdge = m_Graph.m_Edges.find(*edgesBegin)->second;\n        ++edgesBegin;\n        while(firstPoint == numCells)\n        {\n          --numNeigh;\n          firstPoint = i == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n          firstEdge = m_Graph.m_Edges.find(*edgesBegin)->second;\n          ++edgesBegin;\n        }\n          \n        Segmentf::SortByAngle sortMeth(m_Cells[firstPoint].position);\n        std::map<Vector2f, unsigned int, Segmentf::SortByAngle > sortedPointsMap(sortMeth);\n\n        cellPoints.push_back(m_Graph.m_Vertices[firstEdge.m_Pt1].m_Position);\n        cellPoints.push_back(m_Graph.m_Vertices[firstEdge.m_Pt2].m_Position);\n\n        for (; edgesBegin != edgesEnd; ++edgesBegin)\n        {\n          unsigned int target = i == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n          if(target == numCells)\n          {\n            --numNeigh;\n            continue;\n          }\n          VoronoiGraph::Edge const& curEdge = m_Graph.m_Edges.find(*edgesBegin)->second;\n          cellPoints.push_back(m_Graph.m_Vertices[curEdge.m_Pt1].m_Position);\n          cellPoints.push_back(m_Graph.m_Vertices[curEdge.m_Pt2].m_Position);\n          sortedPointsMap.insert(std::make_pair(m_Cells[target].position, target));\n        }\n        sortedPoints.push_back(firstPoint);\n        for(auto pair : sortedPointsMap)\n        {\n          sortedPoints.push_back(pair.second);\n        }\n\n        Polygonf cellPoly;\n        Polygonf::ConvexHull(cellPoints, cellPoly);\n\n        float area = cellPoly.Area();\n        float sum = 0.0;\n\n        for(uint32_t curNeighIdx = 0; curNeighIdx < numNeigh; ++curNeighIdx)\n        {\n          float alphaI = 0.0;\n          float betaI = 0.0;\n\n          unsigned int curNeigh = sortedPoints[curNeighIdx];\n          unsigned int prevNeigh = sortedPoints[curNeighIdx == 0 ? numNeigh - 1 : curNeighIdx - 1];\n          unsigned int nextNeigh = sortedPoints[curNeighIdx == numNeigh - 1 ? 0 : curNeighIdx + 1];\n\n          Vector2f next1 = m_Cells[curNeigh].position - m_Cells[nextNeigh].position;\n          Vector2f next2 = center - m_Cells[nextNeigh].position;\n\n          float crossA = Segmentf::Cross(next1, next2);\n          if(Mathf::Abs(crossA) > Mathf::EPSILON)\n          {\n            alphaI = Mathf::Abs(next1.Dot(next2) / crossA);\n          }\n\n          Vector2f prev1 = center - m_Cells[prevNeigh].position;\n          Vector2f prev2 = m_Cells[curNeigh].position - m_Cells[prevNeigh].position;\n\n          float crossB = Segmentf::Cross(prev1, prev2);\n          if(Mathf::Abs(crossB) > Mathf::EPSILON)\n          {\n            betaI = Mathf::Abs(prev1.Dot(prev2) / crossB);\n          }\n          float curConnectionValue = (alphaI + betaI / area);\n          sum -= curConnectionValue;\n\n          mat.at(i, curNeigh) = 0.5 * curConnectionValue;\n        }\n         \n        mat.at(i, i) = 0.5 * sum;\n      }\n    }\n  }\n\n  void Terrain::Diffusion(LaplaceMatrix const* iMatrix, float iHeatCoefficient, Vector<float>& ioValues)\n  {\n    ArmaLaplaceMatrix const* matrixContainer = static_cast<ArmaLaplaceMatrix const*>(iMatrix);\n\n    unsigned int const numCells = m_Cells.size();\n\n    eXl_ASSERT(numCells == ioValues.size());\n\n    arma::colvec inputTemp(numCells);\n    for (unsigned int i = 0; i < numCells; ++i)\n    {\n      inputTemp.at(i) = ioValues[i];\n    }\n\n    arma::colvec tempRes(numCells, arma::fill::zeros);\n\n    arma::sp_mat resEqn(numCells, numCells);\n    arma::sp_mat idMat(numCells, numCells);\n    for (unsigned int i = 0; i < numCells; ++i)\n      idMat.at(i, i) = 1.0;\n\n    resEqn = idMat - matrixContainer->m_Matrix * iHeatCoefficient;\n\n    arma::spsolve(tempRes, resEqn, inputTemp);\n\n    for (unsigned int i = 0; i < numCells; ++i)\n    {\n      ioValues[i] = tempRes.at(i);\n    }\n  }\n\n  size_t Terrain::GetNumMeshVertices()\n  {\n    size_t numVtx = 2 * m_Graph.m_Edges.size();\n    for (auto const& cell : m_Cells)\n    {\n      numVtx += 1 + cell.neighCount;\n    }\n\n    return numVtx;\n  }\n\n  size_t Terrain::GetNumMeshIndices()\n  {\n    return GetNumSmoothMeshIndices() /*+ 6 * m_Graph.m_Edges.size()*/;\n  }\n\n  size_t Terrain::GetNumSmoothMeshVertices()\n  {\n    return m_Cells.size() + m_Graph.m_Vertices.size();\n  }\n\n  size_t Terrain::GetNumSmoothMeshIndices()\n  {\n    size_t numIndices = 0;\n    for (auto const& cell : m_Cells)\n    {\n      numIndices += 3 * cell.neighCount;\n    }\n\n    return numIndices;\n  }\n\n  void Terrain::BuildMesh(Vector3f const& iScale, const Vector<float>& iHeight, OutputBuffer oPositions, OutputBuffer oNormals, OutputBuffer oTexCoords, OutputBuffer oIdx)\n  {\n    uint32_t maxIndices = GetNumMeshIndices();\n    uint32_t counterCheck = 0;\n\n    Vector3f* positionsPtr = reinterpret_cast<Vector3f*>(oPositions.data);\n    float* texCoordPtr = reinterpret_cast<float*>(oTexCoords.data);\n    Vector3f* normalsPtr = reinterpret_cast<Vector3f*>(oNormals.data);\n    uint32_t* indicesPtr = reinterpret_cast<uint32_t*>(oIdx.data);\n    uint32_t addVtxCounter = 0;\n\n    UnorderedMap<uint32_t, uint32_t> vtxAlloc;\n\n    for (unsigned int i = 0; i < m_Cells.size(); ++i)\n    {\n      uint32_t cellCenterIdx = addVtxCounter;\n      vtxAlloc.clear();\n      Vector2f ptCenter = m_Cells[i].position;\n\n      float height = iHeight[i];\n\n      Vector3f pos(iScale.X() * ptCenter.X(), iScale.Y() * ptCenter.Y(), iScale.Z() * height);\n\n      *positionsPtr = pos;\n      texCoordPtr[0] = ptCenter.X() / m_Size.X();\n      texCoordPtr[1] = ptCenter.Y() / m_Size.Y();\n      *normalsPtr = Vector3f::UNIT_Z;\n\n      oPositions.NextItem(positionsPtr);\n      oTexCoords.NextItem(texCoordPtr);\n      oNormals.NextItem(normalsPtr);\n      ++addVtxCounter;\n\n      VoronoiGraph::CellGraphImpl::vertex_descriptor curCell = i;\n      VoronoiGraph::CellGraphImpl::out_edge_iterator edgesBegin, edgesEnd;\n      unsigned int numPts = 0;\n      for (boost::tie(edgesBegin, edgesEnd) = boost::out_edges(curCell, m_Graph.m_CellGraph); edgesBegin != edgesEnd; ++edgesBegin)\n      {\n        unsigned int target = curCell == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n        if (target >= m_Cells.size())\n        {\n          continue;\n        }\n\n        VoronoiGraph::Edge const& curEdge = m_Graph.m_Edges.find(*edgesBegin)->second;\n\n        auto insertRes = vtxAlloc.insert(std::make_pair(curEdge.m_Pt1, addVtxCounter));\n        if (insertRes.second)\n        {\n          *positionsPtr = Vector3f(iScale.X() * m_Graph.m_Vertices[curEdge.m_Pt1].m_Position.X(), \n            iScale.Y() * m_Graph.m_Vertices[curEdge.m_Pt1].m_Position.Y(), \n            iScale.Z() * height);\n          texCoordPtr[0] = m_Graph.m_Vertices[curEdge.m_Pt1].m_Position.X() / m_Size.X();\n          texCoordPtr[1] = m_Graph.m_Vertices[curEdge.m_Pt1].m_Position.Y() / m_Size.Y();\n          *normalsPtr = Vector3f::UNIT_Z;\n\n          oPositions.NextItem(positionsPtr);\n          oTexCoords.NextItem(texCoordPtr);\n          oNormals.NextItem(normalsPtr);\n          ++addVtxCounter;\n        }\n        insertRes = vtxAlloc.insert(std::make_pair(curEdge.m_Pt2, addVtxCounter));\n        if (insertRes.second)\n        {\n          *positionsPtr = Vector3f(iScale.X() * m_Graph.m_Vertices[curEdge.m_Pt2].m_Position.X(),\n            iScale.Y() * m_Graph.m_Vertices[curEdge.m_Pt2].m_Position.Y(), \n            iScale.Z() * height);\n          texCoordPtr[0] = m_Graph.m_Vertices[curEdge.m_Pt2].m_Position.X() / m_Size.X();\n          texCoordPtr[1] = m_Graph.m_Vertices[curEdge.m_Pt2].m_Position.Y() / m_Size.Y();\n          *normalsPtr = Vector3f::UNIT_Z;\n\n          oPositions.NextItem(positionsPtr);\n          oTexCoords.NextItem(texCoordPtr);\n          oNormals.NextItem(normalsPtr);\n          ++addVtxCounter;\n        }\n      }\n\n      for (boost::tie(edgesBegin, edgesEnd) = boost::out_edges(curCell, m_Graph.m_CellGraph); edgesBegin != edgesEnd; ++edgesBegin)\n      {\n        unsigned int target = curCell == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n        if (target >= m_Cells.size())\n        {\n          continue;\n        }\n\n        VoronoiGraph::Edge const& curEdge = m_Graph.m_Edges.find(*edgesBegin)->second;\n        \n        uint32_t pt1Idx = vtxAlloc[curEdge.m_Pt1];\n        uint32_t pt2Idx = vtxAlloc[curEdge.m_Pt2];\n\n        Vector3f const& otherPt1 = *oPositions.Item<Vector3f>(pt1Idx);\n        Vector3f const& otherPt2 = *oPositions.Item<Vector3f>(pt2Idx);\n\n        Vector3f locNormal = (pos - otherPt1).Cross(pos - otherPt2);\n\n        if (locNormal.Dot(Vector3f::UNIT_Z) < -Mathf::EPSILON)\n        {\n          std::swap(pt1Idx, pt2Idx);\n        }\n\n        eXl_ASSERT(counterCheck < maxIndices);\n\n        *indicesPtr = cellCenterIdx;\n        oIdx.NextItem(indicesPtr);\n        *indicesPtr = pt1Idx;\n        oIdx.NextItem(indicesPtr);\n        *indicesPtr = pt2Idx;\n        oIdx.NextItem(indicesPtr);\n\n        counterCheck += 3;\n      }\n    }\n\n    for (unsigned int i = 0; i < m_Graph.m_Edges.size(); ++i)\n    {\n      //unsigned int numRef = 0;\n      //float height = 0.0;\n      //for (auto ref : edgePtRef[i])\n      //{\n      //  height += oPositions.Item<float>(ref)[2];\n      //  ++numRef;\n      //}\n      //\n      //if (numRef > 0)\n      //  height /= numRef;\n      //\n      //\n      //positionsPtr[0] = iScale.X() * m_Graph.m_Vertices[i].m_Position.X();\n      //positionsPtr[1] = iScale.Y() * m_Graph.m_Vertices[i].m_Position.Y();\n      //positionsPtr[2] = height;\n      //texCoordPtr[0] = m_Graph.m_Vertices[i].m_Position.X() / m_Size.X();\n      //texCoordPtr[1] = m_Graph.m_Vertices[i].m_Position.Y() / m_Size.Y();\n      //*normalsPtr = Vector3f::ZERO;\n      //\n      //oPositions.NextItem(positionsPtr);\n      //oTexCoords.NextItem(texCoordPtr);\n      //oNormals.NextItem(normalsPtr);\n    }\n  }\n\n  void Terrain::BuildSmoothMesh(Vector3f const& iScale, const Vector<float>& iHeight, OutputBuffer oPositions, OutputBuffer oNormals, OutputBuffer oTexCoords, OutputBuffer oIdx)\n  {\n    unsigned int const numCells = m_Cells.size();\n\n    Vector<Set<unsigned int> > edgePtRef(m_Graph.m_Vertices.size());\n\n    float* positionsPtr = reinterpret_cast<float*>(oPositions.data);\n    float* texCoordPtr = reinterpret_cast<float*>(oTexCoords.data);\n    uint32_t* indicesPtr = reinterpret_cast<uint32_t*>(oIdx.data);\n    Vector3f* normalsPtr = reinterpret_cast<Vector3f*>(oNormals.data);\n\n    for (unsigned int i = 0; i < numCells; ++i)\n    {\n      Vector2f ptCenter = m_Cells[i].position;\n      \n      float height = iHeight[i];\n\n      positionsPtr[0] = iScale.X() * ptCenter.X();\n      positionsPtr[1] = iScale.Y() * ptCenter.Y();\n      positionsPtr[2] = iScale.Z() * height;\n      texCoordPtr[0] = ptCenter.X() / m_Size.X();\n      texCoordPtr[1] = ptCenter.Y() / m_Size.Y();\n\n      VoronoiGraph::CellGraphImpl::vertex_descriptor curCell = i;\n      VoronoiGraph::CellGraphImpl::out_edge_iterator edgesBegin, edgesEnd;\n      unsigned int numPts = 0;\n      for (boost::tie(edgesBegin, edgesEnd) = boost::out_edges(curCell, m_Graph.m_CellGraph); edgesBegin != edgesEnd; ++edgesBegin)\n      {\n        unsigned int target = curCell == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n        if (target >= m_Cells.size())\n        {\n          continue;\n        }\n\n        VoronoiGraph::Edge const& curEdge = m_Graph.m_Edges.find(*edgesBegin)->second;\n\n        uint32_t pt1Idx = numCells + curEdge.m_Pt1;\n        uint32_t pt2Idx = numCells + curEdge.m_Pt2;\n\n        *indicesPtr = i;\n        oIdx.NextItem(indicesPtr);\n        *indicesPtr = pt1Idx;\n        oIdx.NextItem(indicesPtr);\n        *indicesPtr = pt2Idx;\n        oIdx.NextItem(indicesPtr);\n\n        edgePtRef[curEdge.m_Pt1].insert(i);\n        edgePtRef[curEdge.m_Pt2].insert(i);\n      }  \n\n      *normalsPtr = Vector3f::ZERO;\n\n      oPositions.NextItem(positionsPtr);\n      oTexCoords.NextItem(texCoordPtr);\n      oNormals.NextItem(normalsPtr);\n    }\n\n    for(unsigned int i = 0; i<edgePtRef.size(); ++i)\n    {\n      unsigned int numRef = 0;\n      float height = 0.0;\n      for(auto ref : edgePtRef[i])\n      {\n        height += oPositions.Item<float>(ref)[2];\n        ++numRef;\n      }\n\n      if(numRef > 0)\n        height /= numRef;\n\n\n      positionsPtr[0] = iScale.X() * m_Graph.m_Vertices[i].m_Position.X();\n      positionsPtr[1] = iScale.Y() * m_Graph.m_Vertices[i].m_Position.Y();\n      positionsPtr[2] = height;\n      texCoordPtr[0] = m_Graph.m_Vertices[i].m_Position.X() / m_Size.X();\n      texCoordPtr[1] = m_Graph.m_Vertices[i].m_Position.Y() / m_Size.Y();\n      *normalsPtr = Vector3f::ZERO;\n\n      oPositions.NextItem(positionsPtr);\n      oTexCoords.NextItem(texCoordPtr);\n      oNormals.NextItem(normalsPtr);\n    }\n\n    indicesPtr = reinterpret_cast<uint32_t*>(oIdx.data);\n    for (unsigned int i = 0; i < numCells; ++i)\n    {\n      Vector3f const& pos = *oPositions.Item<Vector3f>(i);\n\n      VoronoiGraph::CellGraphImpl::vertex_descriptor curCell = i;\n      VoronoiGraph::CellGraphImpl::out_edge_iterator edgesBegin, edgesEnd;\n      unsigned int numPts = 0;\n      Vector3f normal;\n      Set<unsigned int> pts;\n      for (boost::tie(edgesBegin, edgesEnd) = boost::out_edges(curCell, m_Graph.m_CellGraph); edgesBegin != edgesEnd; ++edgesBegin)\n      {\n        unsigned int target = curCell == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n        if (target >= m_Cells.size())\n        {\n          continue;\n        }\n\n        VoronoiGraph::Edge const& curEdge = m_Graph.m_Edges.find(*edgesBegin)->second;\n\n        Vector3f const& otherPt1 = *oPositions.Item<Vector3f>(curEdge.m_Pt1 + numCells);\n        Vector3f const& otherPt2 = *oPositions.Item<Vector3f>(curEdge.m_Pt2 + numCells);\n\n        Vector3f locNormal = (pos - otherPt1).Cross(pos - otherPt2);\n\n        if (locNormal.Dot(Vector3f::UNIT_Z) < -Mathf::EPSILON)\n        {\n          locNormal *= -1.0;\n          std::swap(indicesPtr[1], indicesPtr[2]);\n        }\n\n        *oNormals.Item<Vector3f>(i) += locNormal;\n        *oNormals.Item<Vector3f>(curEdge.m_Pt1 + numCells) += locNormal;\n        *oNormals.Item<Vector3f>(curEdge.m_Pt2 + numCells) += locNormal;\n\n        oIdx.NextItem(indicesPtr);\n        oIdx.NextItem(indicesPtr);\n        oIdx.NextItem(indicesPtr);\n      }\n    }\n\n    normalsPtr = reinterpret_cast<Vector3f*>(oNormals.data);\n    for (unsigned int i = 0; i < numCells + m_Graph.m_Vertices.size(); ++i)\n    {\n      normalsPtr->Normalize();\n      oNormals.NextItem(normalsPtr);\n    }\n  }\n\n  void Terrain::ComputeFlowMap(const Vector<float>& iHeight, Vector<unsigned int>& oSummits, Vector<int>& oNext)\n  {\n    unsigned int const numCells = m_Cells.size();\n\n    oSummits.clear();\n    oNext.resize(numCells, -1);\n\n    \n    Vector<float> filledHeight(numCells, Mathf::MAX_REAL);\n\n    for (unsigned int i = 0; i < numCells; ++i)\n    {\n      VoronoiGraph::CellGraphImpl::out_edge_iterator edgesBegin, edgesEnd;\n      boost::tie(edgesBegin, edgesEnd) = boost::out_edges(i, m_Graph.m_CellGraph);\n      for(; edgesBegin != edgesEnd; ++edgesBegin)\n      {\n        unsigned int curNeigh = i == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n\n        if(curNeigh == numCells)\n        {\n          filledHeight[i] = iHeight[i];\n          break;\n        }\n      }\n    }\n\n    bool updated;\n    do\n    {\n      updated = false;\n\n      for (unsigned int i = 0; i < numCells; ++i)\n      {\n        if(iHeight[i] == filledHeight[i])\n          continue;\n\n        float curOrigH = iHeight[i];\n\n        VoronoiGraph::CellGraphImpl::out_edge_iterator edgesBegin, edgesEnd;\n        boost::tie(edgesBegin, edgesEnd) = boost::out_edges(i, m_Graph.m_CellGraph);\n        for(; edgesBegin != edgesEnd; ++edgesBegin)\n        {\n          unsigned int curNeigh = i == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n\n          eXl_ASSERT(curNeigh < numCells);\n\n          float neighH = filledHeight[curNeigh];\n          if(curOrigH >= neighH + Mathf::ZERO_TOLERANCE)\n          {\n            //C'est bon on a un voisin plus bas\n            filledHeight[i] = curOrigH;\n            updated = true;\n          }\n          else\n          {\n            float newH = neighH + Mathf::ZERO_TOLERANCE;\n            if(filledHeight[i] > newH && (newH > curOrigH))\n            {\n              filledHeight[i] = newH;\n              updated = true;\n            }\n          }\n        }\n      }\n    }while(updated);\n\n    for (unsigned int i = 0; i < numCells; ++i)\n    {\n      int lowerN = -1;\n      float curLowerH = Mathf::MAX_REAL;\n      float curH = filledHeight[i];\n      bool summit = true;\n\n      VoronoiGraph::CellGraphImpl::out_edge_iterator edgesBegin, edgesEnd;\n      boost::tie(edgesBegin, edgesEnd) = boost::out_edges(i, m_Graph.m_CellGraph);\n      for(; edgesBegin != edgesEnd; ++edgesBegin)\n      {\n        unsigned int curNeigh = i == edgesBegin->m_target ? edgesBegin->m_source : edgesBegin->m_target;\n        if(curNeigh == numCells)\n          continue;\n\n        float neighH = filledHeight[curNeigh];\n        if(curH > neighH)\n        {\n          if(neighH < curLowerH)\n          {\n            lowerN = curNeigh;\n            curLowerH = neighH;\n          }\n        }\n        else\n          summit = false;\n      }\n\n      if(summit)\n        oSummits.push_back(i);\n\n      oNext[i] = lowerN;\n    }\n  }\n\n  //void Terrain::ComputeNormals(Vector3f const& iScale, const Vector<float>& iHeight, Vector<Vector3f>& oNormals)\n  //{\n  //  unsigned int const numCells = m_Cells.size();\n  //  oNormals.resize(numCells);\n  //\n  //  for (unsigned int i = 0; i < numCells; ++i)\n  //  {\n  //    Vector3f pos(m_Cells[i].position.X() * iScale.X(), iHeight[i] * iScale.Y(), m_Cells[i].position.Y() * iScale.Z());\n  //\n  //    unsigned int neighStart = m_Cells[i].neighStart;\n  //    unsigned int neighEnd = m_Cells[i].neighCount + neighStart;\n  //\n  //    Vector3f normal;\n  //    if(neighEnd != neighStart)\n  //    {\n  //      unsigned int prevNeigh = m_Neigh[neighEnd - 1];\n  //      Vector3f prevPt(m_Cells[prevNeigh].position.X() * iScale.X(), iHeight[prevNeigh] * iScale.Y(), m_Cells[prevNeigh].position.Y() * iScale.Z());\n  //\n  //      for (unsigned int neighIdx = neighStart; neighIdx < neighEnd; ++neighIdx)\n  //      {\n  //        unsigned int curNeigh = m_Neigh[neighIdx];\n  //        Vector3f curPt(m_Cells[curNeigh].position.X() * iScale.X(), iHeight[curNeigh] * iScale.Y(), m_Cells[curNeigh].position.Y() * iScale.Z());\n  //        Vector3f locNormal = (pos - prevPt).Cross(pos - curPt);\n  //\n  //        if(locNormal.Dot(Vector3f::UNIT_Y) < -Mathf::EPSILON)\n  //          locNormal *= -1.0;\n  //\n  //        normal += locNormal;\n  //        prevPt = curPt;\n  //      }\n  //    }\n  //    normal.Normalize();\n  //    oNormals[i] = normal;\n  //  }\n  //}\n\n}", "meta": {"hexsha": "8aa9417ba4ec28ef070f5558b86a096d5690ae38", "size": 33230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gen/terrain.cpp", "max_stars_repo_name": "eXl-Nic/eXl", "max_stars_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gen/terrain.cpp", "max_issues_repo_name": "eXl-Nic/eXl", "max_issues_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gen/terrain.cpp", "max_forks_repo_name": "eXl-Nic/eXl", "max_forks_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1684414327, "max_line_length": 177, "alphanum_fraction": 0.6196208246, "num_tokens": 9347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5093874705208196}}
{"text": "\n// Copyright (C) 2018 Thanaphon Chavengsaksongkram <as12production@gmail.com>, He Sun <he.sun@ed.ac.uk>\n// This file is subject to the license terms in the LICENSE file\n// found in the top-level directory of this distribution.\n\n#ifndef GSPARSE_ER_POLICY_APROXERSLMJACOBICG_HPP\n#define GSPARSE_ER_POLICY_APROXERSLMJACOBICG_HPP\n\n#include \"../../Config.hpp\"\n#include \"../../Util/JL.hpp\"  // Building Random Projection\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\nnamespace gSparse \n{\n    namespace ER \n    {\n        namespace Policy\n        {\n            /// \\ingroup EffectiveResistance\n            ///\n            /// This class Approximate Effective Weight Resistance\n            /// Adaptation from http://ccom.uprrp.edu/~ikoutis/SpectralAlgorithms.htm.\n            /// The algorithm leverages Conjugated Graident with Jacobi preconditioner to solve linear system\n            ///\n            class AproxERSLMJacobiCG\n            {\n            protected:\n                /// This function calculates Effective Resistance and return computation status.\n                /// \\param er A row matrix to receive the EffectiveResistance value\n                /// \\param graph A std::shared_ptr<IGraph> object representing the graph to calculate resistance\n                /// \\param eps Error tolerance for conjugated gradient. Default is 1.0f.\n                /// \\param JLTol Tolerance for JL projection Matrix. Default is 0.5f. (See http://ccom.uprrp.edu/~ikoutis/SpectralAlgorithms.htm.)\n                /// \\param maxIter  Maximum iteration for conjugated gradient. Default is 300 iterations.\n                inline gSparse::COMPUTE_INFO _calculateER(\n                    gSparse::PrecisionRowMatrix & er,\n                    const gSparse::Graph & graph,\n                    double eps = 1.0f,\n                    double JLTol = 0.5,\n                    int maxIter = 300\n                    )\n                {\n                    er = gSparse::PrecisionRowMatrix::Zero(graph->GetEdgeCount(), 1);\n\n                    std::size_t scale = static_cast<size_t>(\n                                std::ceil(\n                                std::log2(\n                                static_cast<double>(graph->GetIncidentMatrix().cols()) / eps)));\n\n                    for (int i = 1; i != scale + 1; ++i)\n                    {\n                        Eigen::VectorXd x;\n                        gSparse::PrecisionMatrix Q =\n                        gSparse::Util::randomProjectionMatrix(1, \n                                                                graph->GetIncidentMatrix().rows(), \n                                                                static_cast<double>(scale), \n                                                                JLTol);\n\n                        gSparse::PrecisionMatrix Y = (Q * graph->GetWeightMatrix().cwiseSqrt() * graph->GetIncidentMatrix());\n\n                        // solve Linear system with 300 max iteration\n                        Eigen::ConjugateGradient<gSparse::SparsePrecisionMatrix, Eigen::Lower | Eigen::Upper  > cg;\n                        cg.setMaxIterations(maxIter);\n                        x = cg.compute(graph->GetLaplacianMatrix()).solve(Y.transpose());\n                                    \n                        if (cg.info() != Eigen::Success)\n                        {\n                            // Does not converge this iteration. Keeps going.\n                            continue;\n                        }\n                        for (std::size_t j = 0; j != graph->GetEdgeCount(); ++j)\n                        {\n                            er(j) += pow(std::abs(x(graph->GetEdgeList()(j, 0)) - x(graph->GetEdgeList()(j, 1))), 2.0f);\n                        }\n                    }\n                    // Non finite element goes to zero\n                    er = er.unaryExpr([](double v) { return std::isfinite(v)? v : 0.0; });\n                    if (er.rows() != graph->GetEdgeCount())\n                        return gSparse::NOT_CONVERGING;\n                    return gSparse::SUCCESSFUL;       \n                }\n            };\n        }\n    }\n}\n#endif\n\n", "meta": {"hexsha": "8186d71b296d1da4cf232627a5ee99d181abda10", "size": 4125, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gSparse/ER/Policy/AproxERSLMJacobiCG.hpp", "max_stars_repo_name": "As-12/gSparse", "max_stars_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-14T09:38:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:03:55.000Z", "max_issues_repo_path": "include/gSparse/ER/Policy/AproxERSLMJacobiCG.hpp", "max_issues_repo_name": "As-12/gSparse", "max_issues_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gSparse/ER/Policy/AproxERSLMJacobiCG.hpp", "max_forks_repo_name": "As-12/gSparse", "max_forks_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-11T13:03:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T13:03:58.000Z", "avg_line_length": 46.875, "max_line_length": 146, "alphanum_fraction": 0.4904242424, "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.5093261899152884}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n\nTEST(ProbNegBinomial2, ccdf_log_matches_lccdf) {\n  double y = 0.8;\n  double mu = 1.1;\n  double phi = 2.3;\n\n  EXPECT_FLOAT_EQ((stan::math::neg_binomial_2_lccdf(y, mu, phi)),\n                  (stan::math::neg_binomial_2_ccdf_log(y, mu, phi)));\n  EXPECT_FLOAT_EQ(\n      (stan::math::neg_binomial_2_lccdf<double, double, double>(y, mu, phi)),\n      (stan::math::neg_binomial_2_ccdf_log<double, double, double>(y, mu,\n                                                                   phi)));\n}\n", "meta": {"hexsha": "2e2a7e23e5ff24081b5444d240fa95305c867fab", "size": 637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/prob/neg_binomial_2_ccdf_log_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/prob/neg_binomial_2_ccdf_log_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/prob/neg_binomial_2_ccdf_log_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": 35.3888888889, "max_line_length": 77, "alphanum_fraction": 0.6169544741, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.509301874313208}}
{"text": "#include <ql/quantlib.hpp>\n\n#include <boost/make_shared.hpp>\n\n// example / tests for multicurrency lgm model\n\nusing namespace QuantLib;\n\nvoid nodelete() {}\n\nint main() {\n\n    try {\n\n        Date referenceDate(30, July, 2015);\n\n        Settings::instance().evaluationDate() = referenceDate;\n\n        // the single currency models\n        // they can be calibrated in the usual way\n\n        Handle<YieldTermStructure> eurYts(boost::make_shared<FlatForward>(\n            referenceDate, 0.02, Actual365Fixed()));\n\n        Handle<YieldTermStructure> usdYts(boost::make_shared<FlatForward>(\n            referenceDate, 0.05, Actual365Fixed()));\n\n        std::vector<Date> volstepdates;\n        std::vector<Real> volsteptimes;\n        Array volsteptimes_a(0);\n        std::vector<Real> eurVols(1, atof(getenv(\"EURVOL\")));\n        std::vector<Real> usdVols(1, atof(getenv(\"USDVOL\")));\n        std::vector<Real> fxSigmas(1, atof(getenv(\"FXVOL\")));\n        Array fxSigmas_a(fxSigmas.begin(), fxSigmas.end());\n\n        boost::shared_ptr<Lgm1> eurLgm = boost::make_shared<Lgm1>(\n            eurYts, volstepdates, eurVols, atof(getenv(\"EURMR\")));\n        boost::shared_ptr<Lgm1> usdLgm = boost::make_shared<Lgm1>(\n            usdYts, volstepdates, usdVols, atof(getenv(\"USDMR\")));\n\n        std::vector<boost::shared_ptr<Lgm1> > singleModels;\n        singleModels.push_back(eurLgm);\n        singleModels.push_back(usdLgm);\n\n        std::vector<Handle<YieldTermStructure> > curves;\n        curves.push_back(eurYts);\n        curves.push_back(usdYts);\n\n        // build cc parametrization from scratch\n\n        // lgm parametrizations\n\n        std::vector<boost::shared_ptr<detail::LgmParametrization<\n            detail::LgmPiecewiseAlphaConstantKappa> > > lgmParametrizations;\n\n        boost::shared_ptr<\n            detail::LgmParametrization<detail::LgmPiecewiseAlphaConstantKappa> >\n            eurParam = eurLgm->parametrization();\n        boost::shared_ptr<\n            detail::LgmParametrization<detail::LgmPiecewiseAlphaConstantKappa> >\n            usdParam = usdLgm->parametrization();\n\n        lgmParametrizations.push_back(eurParam);\n        lgmParametrizations.push_back(usdParam);\n\n        // fx parametrizations\n\n        std::vector<boost::shared_ptr<detail::LgmFxParametrization<\n            detail::LgmFxPiecewiseSigma> > > fxParametrizations;\n\n        boost::shared_ptr<detail::LgmFxParametrization<\n            detail::LgmFxPiecewiseSigma> > fxParam =\n            boost::make_shared<detail::LgmFxPiecewiseSigma>(volsteptimes_a,\n                                                            fxSigmas_a);\n\n        fxParametrizations.push_back(fxParam);\n\n        // the fx vols, correlations and the cclgmm parametrization / process /\n        // model\n\n        std::vector<Handle<Quote> > fxSpots;\n        fxSpots.push_back(Handle<Quote>(boost::make_shared<SimpleQuote>(\n            std::log(0.9090)))); // EUR-USD ~ 1.10\n\n        Matrix c(3, 3);\n        //  FX             EUR         USD\n        c[0][0] = 1.0; c[0][1] = 0.99; c[0][2] = 0.99; // FX\n        c[1][0] = 0.99; c[1][1] = 1.0; c[1][2] = 0.99; // EUR\n        c[2][0] = 0.99; c[2][1] = 0.99; c[2][2] = 1.0; // USD\n\n        boost::shared_ptr<detail::CcLgmPiecewise> ccParam =\n            boost::make_shared<detail::CcLgmPiecewise>(fxParametrizations,\n                                                       lgmParametrizations, c);\n\n        ccParam->update();\n\n        // test parametrization\n\n        std::clog.precision(12);\n        // std::clog << \"H0(0.0) = \" << ccParam->H_i(0,0.0) << std::endl;\n        // std::clog << \"H0(1.0) = \" << ccParam->H_i(0,1.0) << std::endl;\n        // std::clog << \"H0(2.0) = \" << ccParam->H_i(0,2.0) << std::endl;\n        // std::clog << \"H1(0.0) = \" << ccParam->H_i(1,0.0) << std::endl;\n        // std::clog << \"H1(1.0) = \" << ccParam->H_i(1,1.0) << std::endl;\n        // std::clog << \"H1(2.0) = \" << ccParam->H_i(1,2.0) << std::endl;\n        // std::clog << \"zeta0(0.0) = \" << ccParam->zeta_i(0,0.0) << std::endl;\n        // std::clog << \"zeta0(1.0) = \" << ccParam->zeta_i(0,1.0) << std::endl;\n        // std::clog << \"zeta0(2.0) = \" << ccParam->zeta_i(0,2.0) << std::endl;\n        // std::clog << \"zeta0(3.0) = \" << ccParam->zeta_i(0,3.0) << std::endl;\n        // std::clog << \"zeta1(0.0) = \" << ccParam->zeta_i(1,0.0) << std::endl;\n        // std::clog << \"zeta1(1.0) = \" << ccParam->zeta_i(1,1.0) << std::endl;\n        // std::clog << \"zeta1(2.0) = \" << ccParam->zeta_i(1,2.0) << std::endl;\n        // std::clog << \"zeta1(3.0) = \" << ccParam->zeta_i(1,3.0) << std::endl;\n        // std::clog << \"alphaialphaj(0.0) = \" <<\n        // ccParam->alpha_i_alpha_j(0,0,0.0) << std::endl;\n        // std::clog << \"alphaialphaj(1.0) = \" <<\n        // ccParam->alpha_i_alpha_j(0,0,1.0) << std::endl;\n        // std::clog << \"alphaialphaj(2.0) = \" <<\n        // ccParam->alpha_i_alpha_j(0,0,2.0) << std::endl;\n        // std::clog << \"alphaialphaj(0.0) = \" <<\n        // ccParam->alpha_i_alpha_j(1,1,0.0) << std::endl;\n        // std::clog << \"alphaialphaj(1.0) = \" <<\n        // ccParam->alpha_i_alpha_j(1,1,1.0) << std::endl;\n        // std::clog << \"alphaialphaj(2.0) = \" <<\n        // ccParam->alpha_i_alpha_j(1,1,2.0) << std::endl;\n        // std::clog << \"alphaialphaj(0.0) = \" <<\n        // ccParam->alpha_i_alpha_j(0,1,0.0) << std::endl;\n        // std::clog << \"alphaialphaj(1.0) = \" <<\n        // ccParam->alpha_i_alpha_j(0,1,1.0) << std::endl;\n        // std::clog << \"alphaialphaj(2.0) = \" <<\n        // ccParam->alpha_i_alpha_j(0,1,2.0) << std::endl;\n        // std::clog << \"alphaialphaj(0.0) = \" <<\n        // ccParam->alpha_i_alpha_j(1,0,0.0) << std::endl;\n        // std::clog << \"alphaialphaj(1.0) = \" <<\n        // ccParam->alpha_i_alpha_j(1,0,1.0) << std::endl;\n        // std::clog << \"alphaialphaj(2.0) = \" <<\n        // ccParam->alpha_i_alpha_j(1,0,2.0) << std::endl;\n        // std::clog << \"sigmaisigmaj(0.0) = \" <<\n        // ccParam->sigma_i_sigma_j(0,0,0.0) << std::endl;\n        // std::clog << \"sigmaisigmaj(1.0) = \" <<\n        // ccParam->sigma_i_sigma_j(0,0,1.0) << std::endl;\n        // std::clog << \"sigmaisigmaj(2.0) = \" <<\n        // ccParam->sigma_i_sigma_j(0,0,2.0) << std::endl;\n        // std::clog << \"alphaisigmaj(0.0) = \" <<\n        // ccParam->alpha_i_sigma_j(0,0,0.0) << std::endl;\n        // std::clog << \"alphaisigmaj(1.0) = \" <<\n        // ccParam->alpha_i_sigma_j(0,0,1.0) << std::endl;\n        // std::clog << \"alphaisigmaj(2.0) = \" <<\n        // ccParam->alpha_i_sigma_j(0,0,2.0) << std::endl;\n        // std::clog << \"alphaisigmaj(0.0) = \" <<\n        // ccParam->alpha_i_sigma_j(1,0,0.0) << std::endl;\n        // std::clog << \"alphaisigmaj(1.0) = \" <<\n        // ccParam->alpha_i_sigma_j(1,0,1.0) << std::endl;\n        // std::clog << \"alphaisigmaj(2.0) = \" <<\n        // ccParam->alpha_i_sigma_j(1,0,2.0) << std::endl;\n        // std::clog << \"HiAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_alpha_j(0,0,0.0) << std::endl;\n        // std::clog << \"HiAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_alpha_j(0,0,1.0) << std::endl;\n        // std::clog << \"HiAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_alpha_j(0,0,2.0) << std::endl;\n        // std::clog << \"HiAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_alpha_j(1,1,0.0) << std::endl;\n        // std::clog << \"HiAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_alpha_j(1,1,1.0) << std::endl;\n        // std::clog << \"HiAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_alpha_j(1,1,2.0) << std::endl;\n        // std::clog << \"HiAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_alpha_j(1,0,0.0) << std::endl;\n        // std::clog << \"HiAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_alpha_j(1,0,1.0) << std::endl;\n        // std::clog << \"HiAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_alpha_j(1,0,2.0) << std::endl;\n        // std::clog << \"HiHjAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_H_j_alpha_i_alpha_j(0,0,0.0) << std::endl;\n        // std::clog << \"HiHjAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_H_j_alpha_i_alpha_j(0,0,1.0) << std::endl;\n        // std::clog << \"HiHjAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_H_j_alpha_i_alpha_j(0,0,2.0) << std::endl;\n        // std::clog << \"HiHjAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_H_j_alpha_i_alpha_j(1,1,0.0) << std::endl;\n        // std::clog << \"HiHjAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_H_j_alpha_i_alpha_j(1,1,1.0) << std::endl;\n        // std::clog << \"HiHjAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_H_j_alpha_i_alpha_j(1,1,2.0) << std::endl;\n        // std::clog << \"HiHjAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_H_j_alpha_i_alpha_j(1,0,0.0) << std::endl;\n        // std::clog << \"HiHjAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_H_j_alpha_i_alpha_j(1,0,1.0) << std::endl;\n        // std::clog << \"HiHjAlphaIAlphaJ(0.0) = \" <<\n        // ccParam->H_i_H_j_alpha_i_alpha_j(1,0,2.0) << std::endl;\n        // std::clog << \"HiAlphaISigmaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_sigma_j(0,0,0.0) << std::endl;\n        // std::clog << \"HiAlphaISigmaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_sigma_j(0,0,1.0) << std::endl;\n        // std::clog << \"HiAlphaISigmaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_sigma_j(0,0,2.0) << std::endl;\n        // std::clog << \"HiAlphaISigmaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_sigma_j(1,0,0.0) << std::endl;\n        // std::clog << \"HiAlphaISigmaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_sigma_j(1,0,1.0) << std::endl;\n        // std::clog << \"HiAlphaISigmaJ(0.0) = \" <<\n        // ccParam->H_i_alpha_i_sigma_j(1,0,2.0) << std::endl;\n        // std::clog << \"int_alphaialphaj(0.0) = \" <<\n        // ccParam->int_alpha_i_alpha_j(0,0,0.0,0.0) << std::endl;\n        // std::clog << \"int_alphaialphaj(1.0) = \" <<\n        // ccParam->int_alpha_i_alpha_j(0,0,0.0,1.0) << std::endl;\n        // std::clog << \"int_alphaialphaj(2.0) = \" <<\n        // ccParam->int_alpha_i_alpha_j(0,0,0.0,2.0) << std::endl;\n        // std::clog << \"int_alphaialphaj(0.0) = \" <<\n        // ccParam->int_alpha_i_alpha_j(1,1,0.0,0.0) << std::endl;\n        // std::clog << \"int_alphaialphaj(1.0) = \" <<\n        // ccParam->int_alpha_i_alpha_j(1,1,0.0,1.0) << std::endl;\n        // std::clog << \"int_alphaialphaj(2.0) = \" <<\n        // ccParam->int_alpha_i_alpha_j(1,1,0.0,2.0) << std::endl;\n        // std::clog << \"int_alphaialphaj(0.0) = \" <<\n        // ccParam->int_alpha_i_alpha_j(0,1,0.0,0.0) << std::endl;\n        // std::clog << \"int_alphaialphaj(1.0) = \" <<\n        // ccParam->int_alpha_i_alpha_j(0,1,0.0,1.0) << std::endl;\n        // std::clog << \"int_alphaialphaj(2.0) = \" <<\n        // ccParam->int_alpha_i_alpha_j(0,1,0.0,2.0) << std::endl;\n        // std::clog << \"int_alphaialphaj(0.0) = \" <<\n        // ccParam->int_alpha_i_alpha_j(1,0,0.0,0.0) << std::endl;\n        // std::clog << \"int_alphaialphaj(1.0) = \" <<\n        // ccParam->int_alpha_i_alpha_j(1,0,0.0,1.0) << std::endl;\n        // std::clog << \"int_alphaialphaj(2.0) = \" <<\n        // ccParam->int_alpha_i_alpha_j(1,0,0.0,2.0) << std::endl;\n        // std::clog << \"int_sigmaisigmaj(0.0) = \" <<\n        // ccParam->int_sigma_i_sigma_j(0,0,0.0,0.0) << std::endl;\n        // std::clog << \"int_sigmaisigmaj(1.0) = \" <<\n        // ccParam->int_sigma_i_sigma_j(0,0,0.0,1.0) << std::endl;\n        // std::clog << \"int_sigmaisigmaj(2.0) = \" <<\n        // ccParam->int_sigma_i_sigma_j(0,0,0.0,2.0) << std::endl;\n        // std::clog << \"int_alphaisigmaj(0.0) = \" <<\n        // ccParam->int_alpha_i_sigma_j(0,0,0.0,0.0) << std::endl;\n        // std::clog << \"int_alphaisigmaj(1.0) = \" <<\n        // ccParam->int_alpha_i_sigma_j(0,0,0.0,1.0) << std::endl;\n        // std::clog << \"int_alphaisigmaj(2.0) = \" <<\n        // ccParam->int_alpha_i_sigma_j(0,0,0.0,2.0) << std::endl;\n        // std::clog << \"int_alphaisigmaj(0.0) = \" <<\n        // ccParam->int_alpha_i_sigma_j(1,0,0.0,0.0) << std::endl;\n        // std::clog << \"int_alphaisigmaj(1.0) = \" <<\n        // ccParam->int_alpha_i_sigma_j(1,0,0.0,1.0) << std::endl;\n        // std::clog << \"int_alphaisigmaj(2.0) = \" <<\n        // ccParam->int_alpha_i_sigma_j(1,0,0.0,2.0) << std::endl;\n        // std::clog << \"int_H_i_alphaialphaj(0.0) = \" <<\n        // ccParam->int_H_i_alpha_i_alpha_j(0,0,0.0,0.0) << std::endl;\n        // std::clog << \"int_H_i_alphaialphaj(1.0) = \" <<\n        // ccParam->int_H_i_alpha_i_alpha_j(0,0,0.0,1.0) << std::endl;\n        // std::clog << \"int_H_i_alphaialphaj(2.0) = \" <<\n        // ccParam->int_H_i_alpha_i_alpha_j(0,0,0.0,2.0) << std::endl;\n        // std::clog << \"int_H_i_alphaialphaj(0.0) = \" <<\n        // ccParam->int_H_i_alpha_i_alpha_j(1,1,0.0,0.0) << std::endl;\n        // std::clog << \"int_H_i_alphaialphaj(1.0) = \" <<\n        // ccParam->int_H_i_alpha_i_alpha_j(1,1,0.0,1.0) << std::endl;\n        // std::clog << \"int_H_i_alphaialphaj(2.0) = \" <<\n        // ccParam->int_H_i_alpha_i_alpha_j(1,1,0.0,2.0) << std::endl;\n        // std::clog << \"int_H_i_alphaialphaj(0.0) = \" <<\n        // ccParam->int_H_i_alpha_i_alpha_j(0,1,0.0,0.0) << std::endl;\n        // std::clog << \"int_H_i_alphaialphaj(1.0) = \" <<\n        // ccParam->int_H_i_alpha_i_alpha_j(0,1,0.0,1.0) << std::endl;\n        // std::clog << \"int_H_i_alphaialphaj(2.0) = \" <<\n        // ccParam->int_H_i_alpha_i_alpha_j(0,1,0.0,2.0) << std::endl;\n        // std::clog << \"int_H_i_alphaialphaj(0.0) = \" <<\n        // ccParam->int_H_i_alpha_i_alpha_j(1,0,0.0,0.0) << std::endl;\n        // std::clog << \"int_H_i_alphaialphaj(1.0) = \" <<\n        // ccParam->int_H_i_alpha_i_alpha_j(1,0,0.0,1.0) << std::endl;\n        // std::clog << \"int_H_i_alphaialphaj(2.0) = \" <<\n        // ccParam->int_H_i_alpha_i_alpha_j(1,0,0.0,2.0) << std::endl;\n        // std::clog << \"int_H_i_H_j_alphaialphaj(0.0) = \" <<\n        // ccParam->int_H_i_H_j_alpha_i_alpha_j(0,0,0.0,0.0) << std::endl;\n        // std::clog << \"int_H_i_H_j_alphaialphaj(1.0) = \" <<\n        // ccParam->int_H_i_H_j_alpha_i_alpha_j(0,0,0.0,1.0) << std::endl;\n        // std::clog << \"int_H_i_H_j_alphaialphaj(2.0) = \" <<\n        // ccParam->int_H_i_H_j_alpha_i_alpha_j(0,0,0.0,2.0) << std::endl;\n        // std::clog << \"int_H_i_H_j_alphaialphaj(0.0) = \" <<\n        // ccParam->int_H_i_H_j_alpha_i_alpha_j(1,1,0.0,0.0) << std::endl;\n        // std::clog << \"int_H_i_H_j_alphaialphaj(1.0) = \" <<\n        // ccParam->int_H_i_H_j_alpha_i_alpha_j(1,1,0.0,1.0) << std::endl;\n        // std::clog << \"int_H_i_H_j_alphaialphaj(2.0) = \" <<\n        // ccParam->int_H_i_H_j_alpha_i_alpha_j(1,1,0.0,2.0) << std::endl;\n        // std::clog << \"int_H_i_H_j_alphaialphaj(0.0) = \" <<\n        // ccParam->int_H_i_H_j_alpha_i_alpha_j(0,1,0.0,0.0) << std::endl;\n        // std::clog << \"int_H_i_H_j_alphaialphaj(1.0) = \" <<\n        // ccParam->int_H_i_H_j_alpha_i_alpha_j(0,1,0.0,1.0) << std::endl;\n        // std::clog << \"int_H_i_H_j_alphaialphaj(2.0) = \" <<\n        // ccParam->int_H_i_H_j_alpha_i_alpha_j(0,1,0.0,2.0) << std::endl;\n        // std::clog << \"int_H_i_H_j_alphaialphaj(0.0) = \" <<\n        // ccParam->int_H_i_H_j_alpha_i_alpha_j(1,0,0.0,0.0) << std::endl;\n        // std::clog << \"int_H_i_H_j_alphaialphaj(1.0) = \" <<\n        // ccParam->int_H_i_H_j_alpha_i_alpha_j(1,0,0.0,1.0) << std::endl;\n        // std::clog << \"int_H_i_H_j_alphaialphaj(2.0) = \" <<\n        // ccParam->int_H_i_H_j_alpha_i_alpha_j(1,0,0.0,2.0) << std::endl;\n        // std::clog << \"int_H_i_alphaisigmaj(0.0) = \" <<\n        // ccParam->int_H_i_alpha_i_sigma_j(0,0,0.0,0.0) << std::endl;\n        // std::clog << \"int_H_i_alphaisigmaj(1.0) = \" <<\n        // ccParam->int_H_i_alpha_i_sigma_j(0,0,0.0,1.0) << std::endl;\n        // std::clog << \"int_H_i_alphaisigmaj(2.0) = \" <<\n        // ccParam->int_H_i_alpha_i_sigma_j(0,0,0.0,2.0) << std::endl;\n        // std::clog << \"int_H_i_alphaisigmaj(0.0) = \" <<\n        // ccParam->int_H_i_alpha_i_sigma_j(1,0,0.0,0.0) << std::endl;\n        // std::clog << \"int_H_i_alphaisigmaj(1.0) = \" <<\n        // ccParam->int_H_i_alpha_i_sigma_j(1,0,0.0,1.0) << std::endl;\n        // std::clog << \"int_H_i_alphaisigmaj(2.0) = \" <<\n        // ccParam->int_H_i_alpha_i_sigma_j(1,0,0.0,2.0) << std::endl;\n\n        // std::clog << \"rho alpha-alpha 00\" << ccParam->rho_alpha_alpha(0,0) <<\n        // std::endl;\n        // std::clog << \"rho alpha-alpha 01\" << ccParam->rho_alpha_alpha(0,1) <<\n        // std::endl;\n        // std::clog << \"rho alpha-alpha 10\" << ccParam->rho_alpha_alpha(1,0) <<\n        // std::endl;\n        // std::clog << \"rho alpha-alpha 11\" << ccParam->rho_alpha_alpha(1,1) <<\n        // std::endl;\n        // std::clog << \"rho alpha-sigma 00\" << ccParam->rho_alpha_sigma(0,0) <<\n        // std::endl;\n        // std::clog << \"rho alpha-sigma 10\" << ccParam->rho_alpha_sigma(1,0) <<\n        // std::endl;\n        // std::clog << \"rho sigma-sigma 00\" << ccParam->rho_sigma_sigma(0,0) <<\n        // std::endl;\n\n        // end test parametrization\n\n        boost::shared_ptr<\n            CcLgmProcess<detail::CcLgmPiecewise, detail::LgmFxPiecewiseSigma,\n                         detail::LgmPiecewiseAlphaConstantKappa> > process =\n            boost::make_shared<CcLgmProcess<\n                detail::CcLgmPiecewise, detail::LgmFxPiecewiseSigma,\n                detail::LgmPiecewiseAlphaConstantKappa> >(ccParam, fxSpots,\n                                                          curves);\n\n        // generate paths\n\n        Size n = atoi(getenv(\"N\")); // N paths\n        Time T = atof(getenv(\"T\")); // cashflow time\n        Size steps = static_cast<Size>(\n            T * atof(getenv(\"STEPS\")));   // STEPS steps per year\n        Size seed = atoi(getenv(\"SEED\")); // rng seed\n        TimeGrid grid(T, steps);\n\n        PseudoRandom::rsg_type sg =\n            PseudoRandom::make_sequence_generator(steps * 3, seed);\n        MultiPathGenerator<PseudoRandom::rsg_type> pg(process, grid, sg, false);\n\n        PseudoRandom::rsg_type sg2 =\n            PseudoRandom::make_sequence_generator(steps, seed);\n        PathGenerator<PseudoRandom::rsg_type> pg2(usdLgm->stateProcess(), grid,\n                                                  sg2, false);\n\n        std::vector<Sample<MultiPath> > paths;\n        for (Size j = 0; j < n; ++j) {\n            paths.push_back(pg.next());\n        }\n\n        std::vector<Sample<Path> > paths2;\n        for (Size j = 0; j < n; ++j) {\n            paths2.push_back(pg2.next());\n        }\n\n        // output paths for visual inspection in gnuplot\n\n        if (atoi(getenv(\"OUTPUT\"))) {\n            // cc model paths\n            for (Size i = 0; i < paths[0].value[0].length(); ++i) {\n                std::cout << grid[i] << \" \";\n                for (Size j = 0; j < n; ++j) {\n                    std::cout << std::exp(paths[j].value[0][i]) << \" \"\n                              << paths[j].value[1][i] << \" \"\n                              << paths[j].value[2][i] << \" \"\n                              << paths2[j].value[i] << \" \";\n                }\n                std::cout << \"\\n\";\n            }\n        }\n\n        // test: 1 USD in 1y, priced in domestic measure\n\n        Size l = paths[0].value[0].length() - 1;\n        IncrementalStatistics stat, stat2;\n        for (Size j = 0; j < n; ++j) {\n            Real fx = std::exp(paths[j].value[0][l]);\n            Real zeur = paths[j].value[1][l];\n            Real zusd = paths[j].value[2][l];\n            Real zusd2 = paths2[j].value[l];\n            Real stddev = eurLgm->stateProcess()->stdDeviation(0.0, 0.0, T);\n            Real stddev2 = usdLgm->stateProcess()->stdDeviation(0.0, 0.0, T);\n            Real y = (zeur - eurLgm->stateProcess()->expectation(0.0, 0.0, T)) /\n                     (!close_enough(stddev, 0.0) ? stddev : 1.0);\n            Real y2 =\n                (zusd2 - usdLgm->stateProcess()->expectation(0.0, 0.0, T)) /\n                (!close_enough(stddev2, 0.0) ? stddev2 : 1.0);\n            stat.add(1.0 * fx / eurLgm->numeraire(T, y));\n            stat2.add(1.0 / usdLgm->numeraire(T, y2));\n        }\n        std::clog << \"1 USD @ 1y  = \" << stat.mean() << \" EUR +/- \"\n                  << stat.errorEstimate() << std::endl;\n        ;\n        std::clog << \"curve price = \" << usdYts->discount(T) << \" spot \"\n                  << std::exp(fxSpots[0]->value()) << \" EUR price \"\n                  << usdYts->discount(T) * std::exp(fxSpots[0]->value())\n                  << \"\\n\";\n\n        std::clog << \"1 USD @ 1y = \" << stat2.mean() << \" USD +/-\"\n                  << stat2.errorEstimate() << std::endl;\n\n        return 0;\n\n    } catch (QuantLib::Error e) {\n        std::clog << \"ql exception : \" << e.what() << \"\\n\";\n    } catch (std::exception e) {\n        std::clog << \"std exception: \" << e.what() << \"\\n\";\n    }\n}\n", "meta": {"hexsha": "f26bcb26cc4ff77c6d2d9b35e450db33172027db", "size": 20699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/crosscurrencylgm.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/crosscurrencylgm.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/crosscurrencylgm.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": 49.9975845411, "max_line_length": 80, "alphanum_fraction": 0.5299772936, "num_tokens": 7500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5093018698784729}}
{"text": "#include \"corner_detection.h\"\n#include <cslibs_boost_geometry/algorithms.h>\n#include <boost/geometry/algorithms/distance.hpp>\n\nusing namespace cslibs_vectormaps;\n\nCornerDetection::CornerDetection(const CornerDetectionParameter &parameter) :\n    parameter_(parameter)\n{\n}\n\nvoid CornerDetection::operator () (const Vectors &vectors,\n                                   Points &corners,\n                                   std::vector<double> &cornerness,\n                                   Points &loose_endpoints,\n                                   progress_callback progress)\n{\n    struct Corner {\n        Corner(const dxf::DXFMap::Point &point,\n               const double cornerness) :\n            point(point),\n            cornerness(cornerness)\n        {\n        }\n\n        dxf::DXFMap::Point  point;\n        double              cornerness;\n    };\n\n    auto capped_abs  = [] (const double x)\n    {return (fabs(M_PI - fabs(x))  < 1e-3) ? 0.0 : fabs(x);};\n    auto less_corner= [] (const Corner &c1,const Corner &c2)\n    {return c1.point.x() < c2.point.x() || c1.point.y() < c2.point.y();};\n    auto less_point = [] (const dxf::DXFMap::Point &p1,const dxf::DXFMap::Point &p2)\n    {return p1.x() < p2.x() || p1.y() < p2.y();};\n\n    const double mu = parameter_.pref_corner_angle;\n    const double sigma = parameter_.pref_corner_angle_std_dev;\n    auto cornerness_from_angle = [mu, sigma](const double x)\n    {\n        return std::exp(-0.5 * (x - mu) * (x - mu) / (sigma * sigma));\n    };\n\n    std::size_t count = 0;\n\n    std::set<Corner, decltype(less_corner)> corner_set(less_corner);\n    std::set<dxf::DXFMap::Point, decltype(less_point)> loose_endpoint_set(less_point);\n\n    for(const Vector &v1 : vectors) {\n        double min_distance_p1 = std::numeric_limits<double>::max();\n        double min_distance_p2 = std::numeric_limits<double>::max();\n        Vector  closest_p1;\n        Vector  closest_p2;\n\n        /// do a probabilistic approach, the wider the angle the more unintresting the point is\n        /// mix that with the distance\n\n        /// both ends of the line have to minimized not only one !!! that is the problem why it doesn't work\n\n        for(const Vector &v2 : vectors) {\n            double distance_p1 = cslibs_boost_geometry::algorithms::distance<double, Point>(v1.first,  v2);\n            double distance_p2 = cslibs_boost_geometry::algorithms::distance<double, Point>(v1.second, v2);\n\n            if(cslibs_boost_geometry::algorithms::equal<Point, double>(v1,v2, 1e-6))\n                continue;\n\n            if(distance_p1 <= min_distance_p1) {\n                closest_p1 = v2;\n                min_distance_p1 = distance_p1;\n            }\n            if(distance_p2 <= min_distance_p2) {\n                closest_p2 = v2;\n                min_distance_p2 = distance_p2;\n            }\n        }\n\n        double angle_p1 = cslibs_boost_geometry::algorithms::angle<double, Point>(v1,closest_p1, 1e-6);\n        double angle_p2 = cslibs_boost_geometry::algorithms::angle<double, Point>(v1,closest_p2, 1e-6);\n\n        if(capped_abs(angle_p1) >= parameter_.min_corner_angle &&\n                min_distance_p1 <= parameter_.max_corner_point_distance) {\n\n            double c = cornerness_from_angle(angle_p1);\n            corner_set.insert(Corner(v1.first, c));\n\n        } else if(min_distance_p1 >= parameter_.min_loose_endpoint_distance) {\n\n            loose_endpoint_set.insert(v1.first);\n\n        }\n        if(capped_abs(angle_p2) >= parameter_.min_corner_angle &&\n                min_distance_p2 <= parameter_.max_corner_point_distance) {\n\n            double c = cornerness_from_angle(angle_p2);\n            corner_set.insert(Corner(v1.second, c));\n\n        } else if(min_distance_p2 >= parameter_.min_loose_endpoint_distance) {\n\n            loose_endpoint_set.insert(v1.second);\n\n        }\n        progress(++count / (double) vectors.size() * 100);\n    }\n\n    auto it_last = corner_set.begin();\n    auto it = corner_set.begin();\n    ++it;\n    corners.emplace_back(it_last->point);\n    cornerness.emplace_back(it_last->cornerness);\n    while(it != corner_set.end()) {\n        if(!cslibs_boost_geometry::algorithms::equal<Point, double>(it->point,it_last->point, 1e-2)) {\n            corners.emplace_back(it->point);\n            cornerness.emplace_back(it->cornerness);\n        }\n        ++it;\n        ++it_last;\n    }\n\n    loose_endpoints.assign(loose_endpoint_set.begin(), loose_endpoint_set.end());\n    progress(100);\n}\n", "meta": {"hexsha": "67b763828f23d3818288091b22d0c36f11cb2dc3", "size": 4444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/map_viewer/algorithms/corner_detection.cpp", "max_stars_repo_name": "cogsys-tuebingen/cslibs_vectormaps", "max_stars_repo_head_hexsha": "bafdea3e25db51a1324634ded30c69322faa02bb", "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/map_viewer/algorithms/corner_detection.cpp", "max_issues_repo_name": "cogsys-tuebingen/cslibs_vectormaps", "max_issues_repo_head_hexsha": "bafdea3e25db51a1324634ded30c69322faa02bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-31T02:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-31T02:12:27.000Z", "max_forks_repo_path": "src/map_viewer/algorithms/corner_detection.cpp", "max_forks_repo_name": "cogsys-tuebingen/cslibs_vectormaps", "max_forks_repo_head_hexsha": "bafdea3e25db51a1324634ded30c69322faa02bb", "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.4262295082, "max_line_length": 108, "alphanum_fraction": 0.6109360936, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5093018698784729}}
{"text": "/* Boost libs/numeric/odeint/examples/point_type.hpp\n\n Copyright 2009-2012 Karsten Ahnert\n Copyright 2009-2012 Mario Mulansky\n\n solar system example for Hamiltonian stepper\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 POINT_TYPE_HPP_INCLUDED\n#define POINT_TYPE_HPP_INCLUDED\n\n\n#include <boost/operators.hpp>\n#include <ostream>\n\n\n//[ point_type\n/*the point type */\ntemplate< class T , size_t Dim >\nclass point :\n    boost::additive1< point< T , Dim > ,\n    boost::additive2< point< T , Dim  > , T ,\n    boost::multiplicative2< point< T , Dim > , T\n    > > >\n    {\n    public:\n\n        const static size_t dim = Dim;\n        typedef T value_type;\n        typedef point< value_type , dim > point_type;\n\n        // ...\n        // constructors\n        //<-\n        point( void )\n        {\n            for( size_t i=0 ; i<dim ; ++i ) m_val[i] = 0.0;\n        }\n\n        point( value_type val )\n        {\n            for( size_t i=0 ; i<dim ; ++i ) m_val[i] = val;\n        }\n\n        point( value_type x , value_type y , value_type z = 0.0 )\n        {\n            if( dim > 0 ) m_val[0] = x;\n            if( dim > 1 ) m_val[1] = y;\n            if( dim > 2 ) m_val[2] = z;\n        }\n        //->\n\n        // ...\n        // operators\n        //<-\n        T operator[]( size_t i ) const { return m_val[i]; }\n        T& operator[]( size_t i ) { return m_val[i]; }\n\n        point_type& operator+=( const point_type& p )\n        {\n            for( size_t i=0 ; i<dim ; ++i )\n                m_val[i] += p[i];\n            return *this;\n        }\n\n        point_type& operator-=( const point_type& p )\n        {\n            for( size_t i=0 ; i<dim ; ++i )\n                m_val[i] -= p[i];\n            return *this;\n        }\n\n        point_type& operator+=( const value_type& val )\n        {\n            for( size_t i=0 ; i<dim ; ++i )\n                m_val[i] += val;\n            return *this;\n        }\n\n        point_type& operator-=( const value_type& val )\n        {\n            for( size_t i=0 ; i<dim ; ++i )\n                m_val[i] -= val;\n            return *this;\n        }\n\n        point_type& operator*=( const value_type &val )\n        {\n            for( size_t i=0 ; i<dim ; ++i )\n                m_val[i] *= val;\n            return *this;\n        }\n\n        point_type& operator/=( const value_type &val )\n        {\n            for( size_t i=0 ; i<dim ; ++i )\n                m_val[i] /= val;\n            return *this;\n        }\n\n        //->\n\n    private:\n\n        T m_val[dim];\n    };\n\n    //...\n    // more operators\n    //]\n\n    //\n    // the - operator\n    //\n    template< class T , size_t Dim >\n    point< T , Dim > operator-( const point< T , Dim > &p )\n    {\n        point< T , Dim > tmp;\n        for( size_t i=0 ; i<Dim ; ++i ) tmp[i] = -p[i];\n        return tmp;\n    }\n\n    //\n    // scalar product\n    //\n    template< class T , size_t Dim >\n    T scalar_prod( const point< T , Dim > &p1 , const point< T , Dim > &p2 )\n    {\n        T tmp = 0.0;\n        for( size_t i=0 ; i<Dim ; ++i ) tmp += p1[i] * p2[i];\n        return tmp;\n    }\n\n\n\n    //\n    // norm\n    //\n    template< class T , size_t Dim >\n    T norm( const point< T , Dim > &p1 )\n    {\n        return scalar_prod( p1 , p1 );\n    }\n\n\n\n\n    //\n    // absolute value\n    //\n    template< class T , size_t Dim >\n    T abs( const point< T , Dim > &p1 )\n    {\n        return sqrt( norm( p1 ) );\n    }\n\n\n\n\n    //\n    // output operator\n    //\n    template< class T , size_t Dim >\n    std::ostream& operator<<( std::ostream &out , const point< T , Dim > &p )\n    {\n        if( Dim > 0 ) out << p[0];\n        for( size_t i=1 ; i<Dim ; ++i ) out << \" \" << p[i];\n        return out;\n    }\n\n\n\n#endif //POINT_TYPE_HPP_INCLUDED\n", "meta": {"hexsha": "f397dee4d1adf45db8040aff0adde7575f032650", "size": 3805, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/point_type.hpp", "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/point_type.hpp", "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/point_type.hpp", "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": 21.3764044944, "max_line_length": 77, "alphanum_fraction": 0.4672798949, "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5092948884995505}}
{"text": "//\n// Copyright 2005-2007 Adobe Systems Incorporated\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/extension/io/jpeg.hpp>\n\n// Demonstrates how to compute gradients along the x-axis\n// This example converts the input image to a greyscale view via color_converted_view,\n// and then relies on the function static_transform to apply the operation halfdiff_cast_channels.\n// The result is captured in a view, initially blacked out via a call to fill_pixels (defined in\n// include/boost/gil/algorithm.hpp)\n// static_transform is defined in include/boost/gil/color_based_algorithm.hpp and applies an operation\n// to either a single source or two sources and a destination (as is the case here).\n// In this example, the gradient is calculated as half the difference between the two pixels surrounding x\n// in the loop in x_gradient.\n\nusing namespace boost::gil;\n\ntemplate <typename Out>\nstruct halfdiff_cast_channels {\n    template <typename T> Out operator()(const T& in1, const T& in2) const {\n        return Out((in2-in1)/2);\n    }\n};\n\n\ntemplate <typename SrcView, typename DstView>\nvoid x_gradient(SrcView const& src, DstView const& dst)\n{\n    using dst_channel_t = typename channel_type<DstView>::type;\n\n    for (int y = 0; y < src.height(); ++y)\n    {\n        typename SrcView::x_iterator src_it = src.row_begin(y);\n        typename DstView::x_iterator dst_it = dst.row_begin(y);\n\n        for (int x = 1; x < src.width() - 1; ++x)\n        {\n            static_transform(src_it[x - 1], src_it[x + 1], dst_it[x],\n                halfdiff_cast_channels<dst_channel_t>());\n        }\n    }\n}\n\ntemplate <typename SrcView, typename DstView>\nvoid x_luminosity_gradient(SrcView const& src, DstView const& dst)\n{\n    using gray_pixel_t = pixel<typename channel_type<SrcView>::type, gray_layout_t>;\n    x_gradient(color_converted_view<gray_pixel_t>(src), dst);\n}\n\nint main()\n{\n    rgb8_image_t img;\n    read_image(\"test.jpg\",img, jpeg_tag{});\n\n    gray8s_image_t img_out(img.dimensions());\n    fill_pixels(view(img_out),int8_t(0));\n\n    x_luminosity_gradient(const_view(img), view(img_out));\n    write_view(\"out-x_gradient.jpg\",color_converted_view<gray8_pixel_t>(const_view(img_out)), jpeg_tag{});\n\n    return 0;\n}\n", "meta": {"hexsha": "8d24d3a11b718109cdf53c0b0f19f1dc14140895", "size": 2337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/x_gradient.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/x_gradient.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/x_gradient.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.8695652174, "max_line_length": 106, "alphanum_fraction": 0.7163029525, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5092948817519919}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2009 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#include <algorithm>\r\n\r\ntemplate<typename T> std::string type_name() { return \"other\"; }\r\ntemplate<> std::string type_name<float>() { return \"float\"; }\r\ntemplate<> std::string type_name<double>() { return \"double\"; }\r\ntemplate<> std::string type_name<int>() { return \"int\"; }\r\ntemplate<> std::string type_name<std::complex<float> >() { return \"complex<float>\"; }\r\ntemplate<> std::string type_name<std::complex<double> >() { return \"complex<double>\"; }\r\ntemplate<> std::string type_name<std::complex<int> >() { return \"complex<int>\"; }\r\n\r\n#define EIGEN_DEBUG_VAR(x) std::cerr << #x << \" = \" << x << std::endl;\r\n\r\ntemplate<typename T> inline typename NumTraits<T>::Real epsilon()\r\n{\r\n return std::numeric_limits<typename NumTraits<T>::Real>::epsilon();\r\n}\r\n\r\ntemplate<typename MatrixType> void inverse_permutation_4x4()\r\n{\r\n  typedef typename MatrixType::Scalar Scalar;\r\n  typedef typename MatrixType::RealScalar RealScalar;\r\n  Vector4i indices(0,1,2,3);\r\n  for(int i = 0; i < 24; ++i)\r\n  {\r\n    MatrixType m = MatrixType::Zero();\r\n    m(indices(0),0) = 1;\r\n    m(indices(1),1) = 1;\r\n    m(indices(2),2) = 1;\r\n    m(indices(3),3) = 1;\r\n    MatrixType inv = m.inverse();\r\n    double error = double( (m*inv-MatrixType::Identity()).norm() / epsilon<Scalar>() );\r\n    VERIFY(error == 0.0);\r\n    std::next_permutation(indices.data(),indices.data()+4);\r\n  }\r\n}\r\n\r\ntemplate<typename MatrixType> void inverse_general_4x4(int repeat)\r\n{\r\n  typedef typename MatrixType::Scalar Scalar;\r\n  typedef typename MatrixType::RealScalar RealScalar;\r\n  double error_sum = 0., error_max = 0.;\r\n  for(int i = 0; i < repeat; ++i)\r\n  {\r\n    MatrixType m;\r\n    RealScalar absdet;\r\n    do {\r\n      m = MatrixType::Random();\r\n      absdet = ei_abs(m.determinant());\r\n    } while(absdet < 10 * epsilon<Scalar>());\r\n    MatrixType inv = m.inverse();\r\n    double error = double( (m*inv-MatrixType::Identity()).norm() * absdet / epsilon<Scalar>() );\r\n    error_sum += error;\r\n    error_max = std::max(error_max, error);\r\n  }\r\n  std::cerr << \"inverse_general_4x4, Scalar = \" << type_name<Scalar>() << std::endl;\r\n  double error_avg = error_sum / repeat;\r\n  EIGEN_DEBUG_VAR(error_avg);\r\n  EIGEN_DEBUG_VAR(error_max);\r\n  VERIFY(error_avg < (NumTraits<Scalar>::IsComplex ? 8.0 : 1.25));\r\n  VERIFY(error_max < (NumTraits<Scalar>::IsComplex ? 64.0 : 20.0));\r\n}\r\n\r\nvoid test_eigen2_prec_inverse_4x4()\r\n{\r\n  CALL_SUBTEST_1((inverse_permutation_4x4<Matrix4f>()));\r\n  CALL_SUBTEST_1(( inverse_general_4x4<Matrix4f>(200000 * g_repeat) ));\r\n\r\n  CALL_SUBTEST_2((inverse_permutation_4x4<Matrix<double,4,4,RowMajor> >()));\r\n  CALL_SUBTEST_2(( inverse_general_4x4<Matrix<double,4,4,RowMajor> >(200000 * g_repeat) ));\r\n\r\n  CALL_SUBTEST_3((inverse_permutation_4x4<Matrix4cf>()));\r\n  CALL_SUBTEST_3((inverse_general_4x4<Matrix4cf>(50000 * g_repeat)));\r\n}\r\n", "meta": {"hexsha": "cb9beae29d2451c802fd227e1f41ebe5a89301a0", "size": 3212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/eigen3.2.10/test/eigen2/eigen2_prec_inverse_4x4.cpp", "max_stars_repo_name": "rgijsen/opengl_tmp_poc", "max_stars_repo_head_hexsha": "93e3a08e30ed100475034281208200ed724db5d9", "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": "thirdparty/eigen3.2.10/test/eigen2/eigen2_prec_inverse_4x4.cpp", "max_issues_repo_name": "rgijsen/opengl_tmp_poc", "max_issues_repo_head_hexsha": "93e3a08e30ed100475034281208200ed724db5d9", "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/eigen3.2.10/test/eigen2/eigen2_prec_inverse_4x4.cpp", "max_forks_repo_name": "rgijsen/opengl_tmp_poc", "max_forks_repo_head_hexsha": "93e3a08e30ed100475034281208200ed724db5d9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-31T01:49:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T01:49:42.000Z", "avg_line_length": 37.7882352941, "max_line_length": 97, "alphanum_fraction": 0.6653175592, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.509294874045701}}
{"text": "\r\n//          Copyright W.P. McNeill 2010.\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// This program uses the A-star search algorithm in the Boost Graph Library to\r\n// solve a maze.  It is an example of how to apply Boost Graph Library\r\n// algorithms to implicit graphs.\r\n//\r\n// This program generates a random maze and then tries to find the shortest\r\n// path from the lower left-hand corner to the upper right-hand corner.  Mazes\r\n// are represented by two-dimensional grids where a cell in the grid may\r\n// contain a barrier.  You may move up, down, right, or left to any adjacent\r\n// cell that does not contain a barrier.\r\n//\r\n// Once a maze solution has been attempted, the maze is printed.  If a\r\n// solution was found it will be shown in the maze printout and its length\r\n// will be returned.  Note that not all mazes have solutions.\r\n//\r\n// The default maze size is 20x10, though different dimensions may be\r\n// specified on the command line.\r\n\r\n\r\n#include <boost/graph/astar_search.hpp>\r\n#include <boost/graph/filtered_graph.hpp>\r\n#include <boost/graph/grid_graph.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/random/mersenne_twister.hpp>\r\n#include <boost/random/uniform_int.hpp>\r\n#include <boost/random/variate_generator.hpp>\r\n#include <boost/unordered_map.hpp>\r\n#include <boost/unordered_set.hpp>\r\n#include <ctime>\r\n#include <iostream>\r\n\r\nboost::mt19937 random_generator;\r\n\r\n// Distance traveled in the maze\r\ntypedef double distance;\r\n\r\n#define GRID_RANK 2\r\ntypedef boost::grid_graph<GRID_RANK> grid;\r\ntypedef boost::graph_traits<grid>::vertex_descriptor vertex_descriptor;\r\ntypedef boost::graph_traits<grid>::vertices_size_type vertices_size_type;\r\n\r\n// A hash function for vertices.\r\nstruct vertex_hash:std::unary_function<vertex_descriptor, std::size_t> {\r\n  std::size_t operator()(vertex_descriptor const& u) const {\r\n    std::size_t seed = 0;\r\n    boost::hash_combine(seed, u[0]);\r\n    boost::hash_combine(seed, u[1]);\r\n    return seed;\r\n  }\r\n};\r\n\r\ntypedef boost::unordered_set<vertex_descriptor, vertex_hash> vertex_set;\r\ntypedef boost::vertex_subset_complement_filter<grid, vertex_set>::type\r\n        filtered_grid;\r\n\r\n// A searchable maze\r\n//\r\n// The maze is grid of locations which can either be empty or contain a\r\n// barrier.  You can move to an adjacent location in the grid by going up,\r\n// down, left and right.  Moving onto a barrier is not allowed.  The maze can\r\n// be solved by finding a path from the lower-left-hand corner to the\r\n// upper-right-hand corner.  If no open path exists between these two\r\n// locations, the maze is unsolvable.\r\n//\r\n// The maze is implemented as a filtered grid graph where locations are\r\n// vertices.  Barrier vertices are filtered out of the graph.\r\n//\r\n// A-star search is used to find a path through the maze. Each edge has a\r\n// weight of one, so the total path length is equal to the number of edges\r\n// traversed.\r\nclass maze {\r\npublic:\r\n  friend std::ostream& operator<<(std::ostream&, const maze&);\r\n  friend maze random_maze(std::size_t, std::size_t);\r\n\r\n  maze():m_grid(create_grid(0, 0)),m_barrier_grid(create_barrier_grid()) {};\r\n  maze(std::size_t x, std::size_t y):m_grid(create_grid(x, y)),\r\n       m_barrier_grid(create_barrier_grid()) {};\r\n\r\n  // The length of the maze along the specified dimension.\r\n  vertices_size_type length(std::size_t d) const {return m_grid.length(d);}\r\n\r\n  bool has_barrier(vertex_descriptor u) const {\r\n    return m_barriers.find(u) != m_barriers.end();\r\n  }\r\n\r\n  // Try to find a path from the lower-left-hand corner source (0,0) to the\r\n  // upper-right-hand corner goal (x-1, y-1).\r\n  vertex_descriptor source() const {return vertex(0, m_grid);}\r\n  vertex_descriptor goal() const {\r\n    return vertex(num_vertices(m_grid)-1, m_grid);\r\n  }\r\n\r\n  bool solve();\r\n  bool solved() const {return !m_solution.empty();}\r\n  bool solution_contains(vertex_descriptor u) const {\r\n    return m_solution.find(u) != m_solution.end();\r\n  }\r\n\r\nprivate:\r\n  // Create the underlying rank-2 grid with the specified dimensions.\r\n  grid create_grid(std::size_t x, std::size_t y) {\r\n    boost::array<std::size_t, GRID_RANK> lengths = { {x, y} };\r\n    return grid(lengths);\r\n  }\r\n\r\n  // Filter the barrier vertices out of the underlying grid.\r\n  filtered_grid create_barrier_grid() {\r\n    return boost::make_vertex_subset_complement_filter(m_grid, m_barriers);\r\n  }\r\n\r\n  // The grid underlying the maze\r\n  grid m_grid;\r\n  // The underlying maze grid with barrier vertices filtered out\r\n  filtered_grid m_barrier_grid;\r\n  // The barriers in the maze\r\n  vertex_set m_barriers;\r\n  // The vertices on a solution path through the maze\r\n  vertex_set m_solution;\r\n  // The length of the solution path\r\n  distance m_solution_length;\r\n};\r\n\r\n\r\n// Euclidean heuristic for a grid\r\n//\r\n// This calculates the Euclidean distance between a vertex and a goal\r\n// vertex.\r\nclass euclidean_heuristic:\r\n      public boost::astar_heuristic<filtered_grid, double>\r\n{\r\npublic:\r\n  euclidean_heuristic(vertex_descriptor goal):m_goal(goal) {};\r\n\r\n  double operator()(vertex_descriptor v) {\r\n    return sqrt(pow(m_goal[0] - v[0], 2) + pow(m_goal[1] - v[1], 2));\r\n  }\r\n\r\nprivate:\r\n  vertex_descriptor m_goal;\r\n};\r\n\r\n// Exception thrown when the goal vertex is found\r\nstruct found_goal {};\r\n\r\n// Visitor that terminates when we find the goal vertex\r\nstruct astar_goal_visitor:public boost::default_astar_visitor {\r\n  astar_goal_visitor(vertex_descriptor goal):m_goal(goal) {};\r\n\r\n  void examine_vertex(vertex_descriptor u, const filtered_grid&) {\r\n    if (u == m_goal)\r\n      throw found_goal();\r\n  }\r\n\r\nprivate:\r\n  vertex_descriptor m_goal;\r\n};\r\n\r\n// Solve the maze using A-star search.  Return true if a solution was found.\r\nbool maze::solve() {\r\n  boost::static_property_map<distance> weight(1);\r\n  // The predecessor map is a vertex-to-vertex mapping.\r\n  typedef boost::unordered_map<vertex_descriptor,\r\n                               vertex_descriptor,\r\n                               vertex_hash> pred_map;\r\n  pred_map predecessor;\r\n  boost::associative_property_map<pred_map> pred_pmap(predecessor);\r\n  // The distance map is a vertex-to-distance mapping.\r\n  typedef boost::unordered_map<vertex_descriptor,\r\n                               distance,\r\n                               vertex_hash> dist_map;\r\n  dist_map distance;\r\n  boost::associative_property_map<dist_map> dist_pmap(distance);\r\n\r\n  vertex_descriptor s = source();\r\n  vertex_descriptor g = goal();\r\n  euclidean_heuristic heuristic(g);\r\n  astar_goal_visitor visitor(g);\r\n\r\n  try {\r\n    astar_search(m_barrier_grid, s, heuristic,\r\n                 boost::weight_map(weight).\r\n                 predecessor_map(pred_pmap).\r\n                 distance_map(dist_pmap).\r\n                 visitor(visitor) );\r\n  } catch(found_goal fg) {\r\n    // Walk backwards from the goal through the predecessor chain adding\r\n    // vertices to the solution path.\r\n    for (vertex_descriptor u = g; u != s; u = predecessor[u])\r\n      m_solution.insert(u);\r\n    m_solution.insert(s);\r\n    m_solution_length = distance[g];\r\n    return true;\r\n  }\r\n\r\n  return false;\r\n}\r\n\r\n\r\n#define BARRIER \"#\"\r\n// Print the maze as an ASCII map.\r\nstd::ostream& operator<<(std::ostream& output, const maze& m) {\r\n  // Header\r\n  for (vertices_size_type i = 0; i < m.length(0)+2; i++)\r\n    output << BARRIER;\r\n  output << std::endl;\r\n  // Body\r\n  for (int y = m.length(1)-1; y >= 0; y--) {\r\n    // Enumerate rows in reverse order and columns in regular order so that\r\n    // (0,0) appears in the lower left-hand corner.  This requires that y be\r\n    // int and not the unsigned vertices_size_type because the loop exit\r\n    // condition is y==-1.\r\n    for (vertices_size_type x = 0; x < m.length(0); x++) {\r\n      // Put a barrier on the left-hand side.\r\n      if (x == 0)\r\n        output << BARRIER;\r\n      // Put the character representing this point in the maze grid.\r\n      vertex_descriptor u = {{x, y}};\r\n      if (m.solution_contains(u))\r\n        output << \".\";\r\n      else if (m.has_barrier(u))\r\n        output << BARRIER;\r\n      else\r\n        output << \" \";\r\n      // Put a barrier on the right-hand side.\r\n      if (x == m.length(0)-1)\r\n        output << BARRIER;\r\n    }\r\n    // Put a newline after every row except the last one.\r\n    output << std::endl;\r\n  }\r\n  // Footer\r\n  for (vertices_size_type i = 0; i < m.length(0)+2; i++)\r\n    output << BARRIER;\r\n  if (m.solved())\r\n    output << std::endl << \"Solution length \" << m.m_solution_length;\r\n  return output;\r\n}\r\n\r\n// Return a random integer in the interval [a, b].\r\nstd::size_t random_int(std::size_t a, std::size_t b) {\r\n  if (b < a)\r\n    b = a;\r\n  boost::uniform_int<> dist(a, b);\r\n  boost::variate_generator<boost::mt19937&, boost::uniform_int<> >\r\n  generate(random_generator, dist);\r\n  return generate();\r\n}\r\n\r\n// Generate a maze with a random assignment of barriers.\r\nmaze random_maze(std::size_t x, std::size_t y) {\r\n  maze m(x, y);\r\n  vertices_size_type n = num_vertices(m.m_grid);\r\n  vertex_descriptor s = m.source();\r\n  vertex_descriptor g = m.goal();\r\n  // One quarter of the cells in the maze should be barriers.\r\n  int barriers = n/4;\r\n  while (barriers > 0) {\r\n    // Choose horizontal or vertical direction.\r\n    std::size_t direction = random_int(0, 1);\r\n    // Walls range up to one quarter the dimension length in this direction.\r\n    vertices_size_type wall = random_int(1, m.length(direction)/4);\r\n    // Create the wall while decrementing the total barrier count.\r\n    vertex_descriptor u = vertex(random_int(0, n-1), m.m_grid);\r\n    while (wall) {\r\n      // Start and goal spaces should never be barriers.\r\n      if (u != s && u != g) {\r\n        wall--;\r\n        if (!m.has_barrier(u)) {\r\n          m.m_barriers.insert(u);\r\n          barriers--;\r\n        }\r\n      }\r\n      vertex_descriptor v = m.m_grid.next(u, direction);\r\n      // Stop creating this wall if we reached the maze's edge.\r\n      if (u == v)\r\n        break;\r\n      u = v;\r\n    }\r\n  }\r\n  return m;\r\n}\r\n\r\n\r\nint main (int argc, char const *argv[]) {\r\n  // The default maze size is 20x10.  A different size may be specified on\r\n  // the command line.\r\n  std::size_t x = 20;\r\n  std::size_t y = 10;\r\n\r\n  if (argc == 3) {\r\n    x = boost::lexical_cast<std::size_t>(argv[1]);\r\n    y = boost::lexical_cast<std::size_t>(argv[2]);\r\n  }\r\n\r\n  random_generator.seed(std::time(0));\r\n  maze m = random_maze(x, y);\r\n\r\n  if (m.solve())\r\n    std::cout << \"Solved the maze.\" << std::endl;\r\n  else\r\n    std::cout << \"The maze is not solvable.\" << std::endl;\r\n  std::cout << m << std::endl;\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "0fc0a045f5827745e95eed9601074b205d845089", "size": 10665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/astar_maze.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/graph/example/astar_maze.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/graph/example/astar_maze.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": 34.1826923077, "max_line_length": 79, "alphanum_fraction": 0.6614158462, "num_tokens": 2579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5092948711573597}}
{"text": "#include <eve/function/heuman_lambda.hpp>\n#include <boost/math/special_functions/heuman_lambda.hpp>\n#include <eve/wide.hpp>\n#include <iostream>\n#include <eve/constant/pio_2.hpp>\n#include <iostream>\n\nusing wide_ft = eve::wide<float, eve::fixed<4>>;\n\nint main()\n{\n  wide_ft k    = {1.0e-3f, 0.1f, 0.75f, 0.5f};\n  wide_ft phi0 = {0.2f, 1.0e-5f, 0.5f, 0.0f};\n  wide_ft phi1 = phi0+eve::pio_2(as(phi0));\n\n  std::cout << \"---- simd\" << '\\n'\n             << \"<- phi0                   = \" << phi0 << '\\n'\n             << \"<- phi1                   = \" << phi1 << '\\n'\n             << \"<- k                      = \" << k << '\\n'\n             << \"-> heuman_lambda(phi0, k) = \" << eve::heuman_lambda(phi0, k) << '\\n'\n             << \"-> heuman_lambda(phi1, k) = \" << eve::heuman_lambda(phi1, k) << '\\n'       ;\n\n  float kf = 0.1f;\n  float phif = 1.1f;\n\n  std::cout << \"---- scalar\" << '\\n'\n            << \"<- xf                      = \" << kf << '\\n'\n            << \"<- phif                    = \" << phif<< '\\n'\n            << \"-> heuman_lambda(phif, kf) = \" << eve::heuman_lambda(phif, kf) << '\\n';\n\n  return 0;\n}\n", "meta": {"hexsha": "8a66d5b7183c8f24531bdf45ddbed7ea9dfd371a", "size": 1106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/core/heuman_lambda.cpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "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/doc/core/heuman_lambda.cpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "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/doc/core/heuman_lambda.cpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["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.5151515152, "max_line_length": 93, "alphanum_fraction": 0.438517179, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5092948663394098}}
{"text": "#ifndef BOOST_METAPARSE_GETTING_STARTED_5_2_2_HPP\r\n#define BOOST_METAPARSE_GETTING_STARTED_5_2_2_HPP\r\n\r\n// Automatically generated header file\r\n\r\n// Definitions before section 5.2.1\r\n#include \"5_2_1.hpp\"\r\n\r\n// Definitions of section 5.2.1\r\n#include <boost/mpl/fold.hpp>\r\n\r\nusing vector_of_numbers = \r\n boost::mpl::vector< \r\n   boost::mpl::int_<2>, \r\n   boost::mpl::int_<5>, \r\n   boost::mpl::int_<6> \r\n >;\r\n\r\ntemplate <class Vector> \r\n struct sum_vector : \r\n    boost::mpl::fold< \r\n      Vector, \r\n      boost::mpl::int_<0>, \r\n      boost::mpl::lambda< \r\n        boost::mpl::plus<boost::mpl::_1, boost::mpl::_2> \r\n      >::type \r\n    > \r\n  {};\r\n\r\n// query:\r\n//    sum_vector<vector_of_numbers>::type\r\n\r\ntemplate <class Sum, class Item> \r\n   struct sum_items : \r\n     boost::mpl::plus< \r\n       Sum, \r\n       typename boost::mpl::at_c<Item, 1>::type \r\n     > \r\n {};\r\n\r\n// query:\r\n//   sum_items< \r\n//      mpl_::integral_c<int, 1>, \r\n//      boost::mpl::vector<mpl_::char_<'+'>, mpl_::integral_c<int, 2>> \r\n//    >::type\r\n\r\n// query:\r\n//    boost::mpl::at_c<temp_result, 1>::type\r\n\r\n// query:\r\n//   boost::mpl::fold< \r\n//      boost::mpl::at_c<temp_result, 1>::type, /* The vector to summarise */ \r\n//      boost::mpl::int_<0>, /* The value to start the sum from */ \r\n//      boost::mpl::quote2<sum_items> /* The function to call in each iteration */ \r\n//    >::type\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "d21239db022a170768914330688f9a460a5c6655", "size": 1378, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/getting_started/5_2_2.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": 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/metaparse/example/getting_started/5_2_2.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": "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/metaparse/example/getting_started/5_2_2.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": 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": 23.3559322034, "max_line_length": 84, "alphanum_fraction": 0.5812772134, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.50929486152146}}
{"text": "#include \"Camera2D.h\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <iostream>\n#include <GL/glut.h>\nCamera2D::\nCamera2D()\n\t:mCx(0.0),mCy(0.5),mdx(2.0)\n{\n\n}\n\nvoid\nCamera2D::\nApply()\n{\n\tGLint w = glutGet(GLUT_WINDOW_WIDTH);\n\tGLint h = glutGet(GLUT_WINDOW_HEIGHT);\n\tdouble aspect_ratio_inv = (double)h/(double)w;\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tglOrtho(mCx - mdx*0.5,mCx + mdx*0.5,\n\t\t\tmCy - mdx*aspect_ratio_inv*0.5,mCy + mdx*aspect_ratio_inv*0.5,-1,1);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\nvoid\nCamera2D::\nPan(int x,int y,int prev_x,int prev_y)\n{\n\tfloat delta = (float)prev_y - (float)y;\n\tdelta*=0.01;\n\n\tmdx += delta;\n\tif(mdx<0.1)\n\t\tmdx=0.1;\n\telse if(mdx>100)\n\t\tmdx = 100.0;\n\t\n}\nvoid\nCamera2D::\nTranslate(int x,int y,int prev_x,int prev_y)\n{\n\tEigen::Vector2d delta = GetWorldPosition(prev_x,prev_y)-GetWorldPosition(x,y);\n\n\tmCx += delta[0];\n\tmCy += delta[1];\n}\nEigen::Vector2d\nCamera2D::\nGetWorldPosition(int x,int y)\n{\n\tGLint w = glutGet(GLUT_WINDOW_WIDTH);\n\tGLint h = glutGet(GLUT_WINDOW_HEIGHT);\n\n\tEigen::Vector2d screen_pos((double)x/(double)w-0.5,(1.0-(double)y/(double)h)-0.5);\n\tEigen::Vector2d pos = mdx*screen_pos+Eigen::Vector2d(mCx,mCy);\n\n\treturn pos;\n}", "meta": {"hexsha": "233cf623fa0574f92085e24fc0da978da5973dbf", "size": 1200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GUI/Camera2D.cpp", "max_stars_repo_name": "snumrl/volcon2D", "max_stars_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "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": "GUI/Camera2D.cpp", "max_issues_repo_name": "snumrl/volcon2D", "max_issues_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "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": "GUI/Camera2D.cpp", "max_forks_repo_name": "snumrl/volcon2D", "max_forks_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "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.6721311475, "max_line_length": 83, "alphanum_fraction": 0.6975, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5092794904840642}}
{"text": "#ifndef __DOUBLE_PENDULUM_H_\n#define __DOUBLE_PENDULUM_H_\n\n#include <SFML/Graphics.hpp>\n#include <armadillo>\n\n\nclass DoublePendulum {\n\n    private:\n\n        // Representation of the pendulums\n        sf::RectangleShape pend1;\n        sf::RectangleShape pend2;\n\n        // Representation of the pivots\n        sf::CircleShape pivot1;\n        sf::CircleShape pivot2;\n\n        double gravity;\n\n        // Pivot vector coordinates\n        arma::vec P1;\n        arma::vec P2;\n\n        // Center of mass vector coordinates\n        arma::vec X1;\n        arma::vec X2;\n\n        // Vector from pivot to center of mass\n        arma::vec R1;\n        arma::vec R2;\n        // Respective lengths\n        double R1Length;\n        double R2Length;\n\n        // Angle at pivot between R and the downward vertical position [rad]\n        double theta1;\n        double theta2;\n\n        // Vector from pivot 1 to pivot 2\n        arma::vec L1;\n        // Respective length\n        double L1Length;\n\n        // Angle from R1 to L1 [rad]\n        double phi;\n\n        // Mass of the pendulums [kg]\n        double m1;\n        double m2;\n\n        // Rotation interia about the center of mass of the pendulums\n        double I1;\n        double I2;\n\n\n    public:\n\n        // Default constructor\n        DoublePendulum();\n\n        // Draw figures\n        void draw(sf::RenderWindow *window);\n\n};\n\n#endif // __DOUBLE_PENDULUM_H_\n", "meta": {"hexsha": "be0615cc6e206aa80102a730775e9f8fe11cd87e", "size": 1398, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/double_pendulum.hpp", "max_stars_repo_name": "vcoutasso/Double-Pendulum", "max_stars_repo_head_hexsha": "cce43003eea9ceec3f36d522e00f12ecf0ef5ebc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T20:21:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T20:21:58.000Z", "max_issues_repo_path": "src/double_pendulum.hpp", "max_issues_repo_name": "vcoutasso/Double-Pendulum", "max_issues_repo_head_hexsha": "cce43003eea9ceec3f36d522e00f12ecf0ef5ebc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/double_pendulum.hpp", "max_forks_repo_name": "vcoutasso/Double-Pendulum", "max_forks_repo_head_hexsha": "cce43003eea9ceec3f36d522e00f12ecf0ef5ebc", "max_forks_repo_licenses": ["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.2608695652, "max_line_length": 76, "alphanum_fraction": 0.5801144492, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.509279489525372}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <stan/math/prim/mat.hpp>\n#include <test/unit/math/prim/mat/prob/vector_rng_test_helper.hpp>\n#include <limits>\n#include <vector>\n\nclass UniformTestRig : public VectorRealRNGTestRig {\n public:\n  UniformTestRig(std::vector<double> good_p1, std::vector<int> good_p1_int,\n                 std::vector<double> bad_p1, std::vector<int> bad_p1_int,\n                 std::vector<double> good_p2, std::vector<int> good_p2_int,\n                 std::vector<double> bad_p2, std::vector<int> bad_p2_int)\n      : VectorRealRNGTestRig(10000, 10, good_p1, good_p1_int, bad_p1,\n                             bad_p1_int, good_p2, good_p2_int, bad_p2,\n                             bad_p2_int) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& alpha, const T2& beta, const T3& unused,\n                        T_rng& rng) const {\n    return stan::math::uniform_rng(alpha, beta, rng);\n  }\n\n  std::vector<double> generate_quantiles(double alpha, double beta,\n                                         double unused) const {\n    std::vector<double> quantiles;\n    double K = stan::math::round(2 * std::pow(N_, 0.4));\n    boost::math::uniform_distribution<> dist(alpha, beta);\n\n    for (int i = 1; i < K; ++i) {\n      double frac = i / K;\n      quantiles.push_back(quantile(dist, frac));\n    }\n    quantiles.push_back(std::numeric_limits<double>::max());\n\n    return quantiles;\n  }\n};\n\nTEST(ProbDistributionsUniform, errorCheck) {\n  // beta must be greater than alpha, so we have to be careful about how the\n  // tests are initialized here (the VectorRNGTestRig class assumes no order)\n\n  check_dist_throws_all_types(\n      UniformTestRig({-2.5, -1.7, -0.1, 0.0, 0.5}, {-3, -2, -1, 0, 1}, {}, {},\n                     {1.1, 2.2, 3.8}, {2, 3, 6}, {}, {}));\n\n  check_dist_throws_all_types(\n      UniformTestRig({-7.5, -6.7, -5.1, -4.0}, {-7, -6, -5, -4}, {}, {},\n                     {-3.0, -2.2, 0.0, 1.0}, {-3, -2, 0, 1, 2}, {}, {}));\n}\n\nTEST(ProbDistributionsUniform, distributionTest) {\n  check_quantiles_real_real(UniformTestRig({-1.7, -0.1, 0.0, 0.5},\n                                           {-2, -1, 0, 1}, {}, {}, {1.1, 3.8},\n                                           {2, 6}, {}, {}));\n\n  check_quantiles_real_real(UniformTestRig({-7.5, -5.1, -4.0}, {-7, -6, -4}, {},\n                                           {}, {-2.2, 0.0, 1.0}, {-3, 0, 1, 2},\n                                           {}, {}));\n}\n", "meta": {"hexsha": "70cbb318f538b4d854efdbe8ea2f7502d984d7d8", "size": 2560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/mat/prob/uniform_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/mat/prob/uniform_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/mat/prob/uniform_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": 40.6349206349, "max_line_length": 80, "alphanum_fraction": 0.552734375, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5092794615674371}}
{"text": "/**\nCopyright (c) 2016 Theodore Gast, Chuyuan Fu, Chenfanfu Jiang, Joseph Teran\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, 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\nIf the code is used in an article, the following paper shall be cited:\n@techreport{qrsvd:2016,\n  title={Implicit-shifted Symmetric QR Singular Value Decomposition of 3x3 Matrices},\n  author={Gast, Theodore and Fu, Chuyuan and Jiang, Chenfanfu and Teran, Joseph},\n  year={2016},\n  institution={University of California Los Angeles}\n}\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 <cmath>\n#include \"Tools.h\"\n#include \"ImplicitQRSVD.h\"\n#include <Eigen/Jacobi>\n#include <math.h> \n\ntemplate <class T>\nvoid testAccuracy(const std::vector<Eigen::Matrix<T, 3, 3> >& AA,\n    const std::vector<Eigen::Matrix<T, 3, 3> >& UU,\n    const std::vector<Eigen::Matrix<T, 3, 1> >& SS,\n    const std::vector<Eigen::Matrix<T, 3, 3> >& VV)\n{\n    T max_UUt_error = 0, max_VVt_error = 0, max_detU_error = 0, max_detV_error = 0, max_reconstruction_error = 0;\n    T ave_UUt_error = 0, ave_VVt_error = 0, ave_detU_error = 0, ave_detV_error = 0, ave_reconstruction_error = 0;\n    for (size_t i = 0; i < AA.size(); i++) {\n        Eigen::Matrix<T, 3, 3> M = AA[i];\n        Eigen::Matrix<T, 3, 1> S = SS[i];\n        Eigen::Matrix<T, 3, 3> U = UU[i];\n        Eigen::Matrix<T, 3, 3> V = VV[i];\n        T error;\n        error = (U * U.transpose() - Eigen::Matrix<T, 3, 3>::Identity()).array().abs().maxCoeff();\n        max_UUt_error = (error > max_UUt_error) ? error : max_UUt_error;\n        ave_UUt_error += fabs(error);\n        error = (V * V.transpose() - Eigen::Matrix<T, 3, 3>::Identity()).array().abs().maxCoeff();\n        max_VVt_error = (error > max_VVt_error) ? error : max_VVt_error;\n        ave_VVt_error += fabs(error);\n        error = fabs(fabs(U.determinant()) - (T)1);\n        max_detU_error = (error > max_detU_error) ? error : max_detU_error;\n        ave_detU_error += fabs(error);\n        error = fabs(fabs(V.determinant()) - (T)1);\n        max_detV_error = (error > max_detV_error) ? error : max_detV_error;\n        ave_detV_error += fabs(error);\n        error = (U * S.asDiagonal() * V.transpose() - M).array().abs().maxCoeff();\n        max_reconstruction_error = (error > max_reconstruction_error) ? error : max_reconstruction_error;\n        ave_reconstruction_error += fabs(error);\n    }\n    ave_UUt_error /= (T)(AA.size());\n    ave_VVt_error /= (T)(AA.size());\n    ave_detU_error /= (T)(AA.size());\n    ave_detV_error /= (T)(AA.size());\n    ave_reconstruction_error /= (T)(AA.size());\n    std::cout << std::setprecision(10) << \" UUt max error: \" << max_UUt_error\n              << \" VVt max error: \" << max_VVt_error\n              << \" detU max error:\" << max_detU_error\n              << \" detV max error:\" << max_detV_error\n              << \" recons max error:\" << max_reconstruction_error << std::endl;\n    std::cout << std::setprecision(10) << \" UUt ave error: \" << ave_UUt_error\n              << \" VVt ave error: \" << ave_VVt_error\n              << \" detU ave error:\" << ave_detU_error\n              << \" detV ave error:\" << ave_detV_error\n              << \" recons ave error:\" << ave_reconstruction_error << std::endl;\n}\n\ntemplate <class T>\nvoid runImplicitQRSVD(const int repeat, const std::vector<Eigen::Matrix<T, 3, 3> >& tests, const bool accuracy_test)\n{\n    using namespace JIXIE;\n    std::vector<Eigen::Matrix<T, 3, 3> > UU, VV;\n    std::vector<Eigen::Matrix<T, 3, 1> > SS;\n    JIXIE::Timer timer;\n    timer.start();\n    double total_time = 0;\n    for (int test_iter = 0; test_iter < repeat; test_iter++) {\n        timer.click();\n        for (size_t i = 0; i < tests.size(); i++) {\n            Eigen::Matrix<T, 3, 3> M = tests[i];\n            Eigen::Matrix<T, 3, 1> S;\n            Eigen::Matrix<T, 3, 3> U;\n            Eigen::Matrix<T, 3, 3> V;\n            singularValueDecomposition(M, U, S, V);\n            if (accuracy_test && test_iter == 0) {\n                UU.push_back(U);\n                SS.push_back(S);\n                VV.push_back(V);\n            }\n        }\n        double this_time = timer.click();\n        total_time += this_time;\n        std::cout << std::setprecision(10) << \"impQR time: \" << this_time << std::endl;\n    }\n    std::cout << std::setprecision(10) << \"impQR Average time: \" << total_time / (double)(repeat) << std::endl;\n    if (accuracy_test)\n        testAccuracy(tests, UU, SS, VV);\n}\n\ntemplate <class T>\nvoid addRandomCases(std::vector<Eigen::Matrix<T, 3, 3> >& tests, const T random_range, const int N)\n{\n    using namespace JIXIE;\n    int old_count = tests.size();\n    std::cout << std::setprecision(10) << \"Adding random test cases with range \" << -random_range << \" to \" << random_range << std::endl;\n    RandomNumber<T> random_gen(123);\n    for (int t = 0; t < N; t++) {\n        Eigen::Matrix<T, 3, 3> Z;\n        random_gen.fill(Z, -random_range, random_range);\n        tests.push_back(Z);\n    }\n    std::cout << std::setprecision(10) << tests.size() - old_count << \" cases added.\" << std::endl;\n    std::cout << std::setprecision(10) << \"Total test cases: \" << tests.size() << std::endl;\n}\n\ntemplate <class T>\nvoid addIntegerCases(std::vector<Eigen::Matrix<T, 3, 3> >& tests, const int int_range)\n{\n    using namespace JIXIE;\n    int old_count = tests.size();\n    std::cout << std::setprecision(10) << \"Adding integer test cases with range \" << -int_range << \" to \" << int_range << std::endl;\n    Eigen::Matrix<T, 3, 3> Z;\n    Z.fill(-int_range);\n    typename Eigen::Matrix<T, 3, 3>::Index i = 0;\n    tests.push_back(Z);\n    while (i < Eigen::Matrix<T, 3, 3>::SizeAtCompileTime) {\n        if (Z(i) < int_range) {\n            Z(i)++;\n            tests.push_back(Z);\n            i = 0;\n        }\n        else {\n            Z(i) = -int_range;\n            i++;\n        }\n    }\n    std::cout << std::setprecision(10) << tests.size() - old_count << \" cases added.\" << std::endl;\n    std::cout << std::setprecision(10) << \"Total test cases: \" << tests.size() << std::endl;\n}\n\ntemplate <class T>\nvoid addPerturbationFromIdentityCases(std::vector<Eigen::Matrix<T, 3, 3> >& tests, const int num_perturbations, const T perturb)\n{\n    using namespace JIXIE;\n    int old_count = tests.size();\n    std::vector<Eigen::Matrix<T, 3, 3> > tests_tmp;\n    Eigen::Matrix<T, 3, 3> Z = Eigen::Matrix<T, 3, 3>::Identity();\n    tests_tmp.push_back(Z);\n    std::cout << std::setprecision(10) << \"Adding perturbed identity test cases with perturbation \" << perturb << std::endl;\n    RandomNumber<T> random_gen(123);\n    size_t special_cases = tests_tmp.size();\n    for (size_t t = 0; t < special_cases; t++) {\n        for (int i = 0; i < num_perturbations; i++) {\n            random_gen.fill(Z, -perturb, perturb);\n            tests.push_back(tests_tmp[t] + Z);\n        }\n    }\n    std::cout << std::setprecision(10) << tests.size() - old_count << \" cases added.\" << std::endl;\n    std::cout << std::setprecision(10) << \"Total test cases: \" << tests.size() << std::endl;\n}\n\ntemplate <class T>\nvoid addPerturbationCases(std::vector<Eigen::Matrix<T, 3, 3> >& tests, const int int_range, const int num_perturbations, const T perturb)\n{\n    using namespace JIXIE;\n    int old_count = tests.size();\n    std::vector<Eigen::Matrix<T, 3, 3> > tests_tmp;\n    Eigen::Matrix<T, 3, 3> Z;\n    Z.fill(-int_range);\n    typename Eigen::Matrix<T, 3, 3>::Index i = 0;\n    tests_tmp.push_back(Z);\n    while (i < Eigen::Matrix<T, 3, 3>::SizeAtCompileTime) {\n        if (Z(i) < int_range) {\n            Z(i)++;\n            tests_tmp.push_back(Z);\n            i = 0;\n        }\n        else {\n            Z(i) = -int_range;\n            i++;\n        }\n    }\n    std::cout << std::setprecision(10) << \"Adding perturbed integer test cases with perturbation \" << perturb << \" and range \" << -int_range << \" to \" << int_range << std::endl;\n    RandomNumber<T> random_gen(123);\n    size_t special_cases = tests_tmp.size();\n    for (size_t t = 0; t < special_cases; t++) {\n        for (int i = 0; i < num_perturbations; i++) {\n            random_gen.fill(Z, -perturb, perturb);\n            tests.push_back(tests_tmp[t] + Z);\n        }\n    }\n    std::cout << std::setprecision(10) << tests.size() - old_count << \" cases added.\" << std::endl;\n    std::cout << std::setprecision(10) << \"Total test cases: \" << tests.size() << std::endl;\n}\n\nvoid runBenchmark()\n{\n    using namespace JIXIE;\n    using std::fabs;\n\n    bool run_qr;\n\n    bool test_float;\n    bool test_double;\n    bool accuracy_test;\n    bool normalize_matrix;\n    int number_of_repeated_experiments;\n    bool test_random;\n    int random_range;\n    int number_of_random_cases;\n    bool test_integer;\n    int integer_range;\n    bool test_perturbation;\n    int perturbation_count;\n    float float_perturbation;\n    double double_perturbation;\n    bool test_perturbation_from_identity;\n    int perturbation_from_identity_count;\n    float float_perturbation_identity;\n    double double_perturbation_identity;\n    std::string title;\n\n    // Finalized options\n    run_qr = true;\n\n    test_float = true;\n    test_double = true;\n    normalize_matrix = false;\n    int number_of_repeated_experiments_for_timing = 2;\n\n    for (int test_number = 1; test_number <= 10; test_number++) {\n\n        if (test_number == 1) {\n            title = \"random timing test\";\n            number_of_repeated_experiments = number_of_repeated_experiments_for_timing;\n            accuracy_test = false;\n            test_random = true, random_range = 3, number_of_random_cases = 1024 * 1024; // random test\n            test_integer = false; // integer test\n            integer_range = 2; // this variable is used by both integer test and perturbed integer test\n            test_perturbation = false, integer_range = 3, perturbation_count = 4, float_perturbation = (float)256 * std::numeric_limits<float>::epsilon(), double_perturbation = (double)256 * std::numeric_limits<double>::epsilon(); // perturbed integer test\n            test_perturbation_from_identity = false, perturbation_from_identity_count = 1024 * 1024, float_perturbation_identity = 1e-3, double_perturbation_identity = 1e-3; // perturbed itentity test\n        }\n        if (test_number == 2) {\n            title = \"integer timing test\";\n            number_of_repeated_experiments = number_of_repeated_experiments_for_timing;\n            accuracy_test = false;\n            test_random = false, random_range = 3, number_of_random_cases = 1024 * 1024; // random test\n            test_integer = true; // integer test\n            integer_range = 2; // this variable is used by both integer test and perturbed integer test\n            test_perturbation = false, perturbation_count = 4, float_perturbation = (float)256 * std::numeric_limits<float>::epsilon(), double_perturbation = (double)256 * std::numeric_limits<double>::epsilon(); // perturbed integer test\n            test_perturbation_from_identity = false, perturbation_from_identity_count = 1024 * 1024, float_perturbation_identity = 1e-3, double_perturbation_identity = 1e-3; // perturbed itentity test\n        }\n        if (test_number == 3) {\n            title = \"integer-perturbation timing test: 256 eps\";\n            number_of_repeated_experiments = number_of_repeated_experiments_for_timing;\n            accuracy_test = false;\n            test_random = false, random_range = 3, number_of_random_cases = 1024 * 1024; // random test\n            test_integer = false; // integer test\n            integer_range = 2; // this variable is used by both integer test and perturbed integer test\n            test_perturbation = true, perturbation_count = 4, float_perturbation = (float)256 * std::numeric_limits<float>::epsilon(), double_perturbation = (double)256 * std::numeric_limits<double>::epsilon(); // perturbed integer test\n            test_perturbation_from_identity = false, perturbation_from_identity_count = 1024 * 1024, float_perturbation_identity = 1e-3, double_perturbation_identity = 1e-3; // perturbed itentity test\n        }\n        if (test_number == 4) {\n            title = \"identity-perturbation timing test: 1e-3\";\n            number_of_repeated_experiments = number_of_repeated_experiments_for_timing;\n            accuracy_test = false;\n            test_random = false, random_range = 3, number_of_random_cases = 1024 * 1024; // random test\n            test_integer = false; // integer test\n            integer_range = 2; // this variable is used by both integer test and perturbed integer test\n            test_perturbation = false, perturbation_count = 4, float_perturbation = (float)256 * std::numeric_limits<float>::epsilon(), double_perturbation = (double)256 * std::numeric_limits<double>::epsilon(); // perturbed integer test\n            test_perturbation_from_identity = true, perturbation_from_identity_count = 1024 * 1024, float_perturbation_identity = 1e-3, double_perturbation_identity = 1e-3; // perturbed itentity test\n        }\n        if (test_number == 5) {\n            title = \"identity-perturbation timing test: 256 eps\";\n            number_of_repeated_experiments = number_of_repeated_experiments_for_timing;\n            accuracy_test = false;\n            test_random = false, random_range = 3, number_of_random_cases = 1024 * 1024; // random test\n            test_integer = false; // integer test\n            integer_range = 2; // this variable is used by both integer test and perturbed integer test\n            test_perturbation = false, perturbation_count = 4, float_perturbation = (float)256 * std::numeric_limits<float>::epsilon(), double_perturbation = (double)256 * std::numeric_limits<double>::epsilon(); // perturbed integer test\n            test_perturbation_from_identity = true, perturbation_from_identity_count = 1024 * 1024, float_perturbation_identity = (float)256 * std::numeric_limits<float>::epsilon(), double_perturbation_identity = (double)256 * std::numeric_limits<double>::epsilon(); // perturbed itentity test\n        }\n\n        if (test_number == 6) {\n            title = \"random accuracy test\";\n            number_of_repeated_experiments = 1;\n            accuracy_test = true;\n            test_random = true, random_range = 3, number_of_random_cases = 1024 * 1024; // random test\n            test_integer = false; // integer test\n            integer_range = 2; // this variable is used by both integer test and perturbed integer test\n            test_perturbation = false, integer_range = 3, perturbation_count = 4, float_perturbation = (float)256 * std::numeric_limits<float>::epsilon(), double_perturbation = (double)256 * std::numeric_limits<double>::epsilon(); // perturbed integer test\n            test_perturbation_from_identity = false, perturbation_from_identity_count = 1024 * 1024, float_perturbation_identity = 1e-3, double_perturbation_identity = 1e-3; // perturbed itentity test\n        }\n        if (test_number == 7) {\n            title = \"integer accuracy test\";\n            number_of_repeated_experiments = 1;\n            accuracy_test = true;\n            test_random = false, random_range = 3, number_of_random_cases = 1024 * 1024; // random test\n            test_integer = true; // integer test\n            integer_range = 2; // this variable is used by both integer test and perturbed integer test\n            test_perturbation = false, perturbation_count = 4, float_perturbation = (float)256 * std::numeric_limits<float>::epsilon(), double_perturbation = (double)256 * std::numeric_limits<double>::epsilon(); // perturbed integer test\n            test_perturbation_from_identity = false, perturbation_from_identity_count = 1024 * 1024, float_perturbation_identity = 1e-3, double_perturbation_identity = 1e-3; // perturbed itentity test\n        }\n        if (test_number == 8) {\n            title = \"integer-perturbation accuracy test: 256 eps\";\n            number_of_repeated_experiments = 1;\n            accuracy_test = true;\n            test_random = false, random_range = 3, number_of_random_cases = 1024 * 1024; // random test\n            test_integer = false; // integer test\n            integer_range = 2; // this variable is used by both integer test and perturbed integer test\n            test_perturbation = true, perturbation_count = 4, float_perturbation = (float)256 * std::numeric_limits<float>::epsilon(), double_perturbation = (double)256 * std::numeric_limits<double>::epsilon(); // perturbed integer test\n            test_perturbation_from_identity = false, perturbation_from_identity_count = 1024 * 1024, float_perturbation_identity = 1e-3, double_perturbation_identity = 1e-3; // perturbed itentity test\n        }\n        if (test_number == 9) {\n            title = \"identity-perturbation accuracy test: 1e-3\";\n            number_of_repeated_experiments = 1;\n            accuracy_test = true;\n            test_random = false, random_range = 3, number_of_random_cases = 1024 * 1024; // random test\n            test_integer = false; // integer test\n            integer_range = 2; // this variable is used by both integer test and perturbed integer test\n            test_perturbation = false, perturbation_count = 4, float_perturbation = (float)256 * std::numeric_limits<float>::epsilon(), double_perturbation = (double)256 * std::numeric_limits<double>::epsilon(); // perturbed integer test\n            test_perturbation_from_identity = true, perturbation_from_identity_count = 1024 * 1024, float_perturbation_identity = 1e-3, double_perturbation_identity = 1e-3; // perturbed itentity test\n        }\n        if (test_number == 10) {\n            title = \"identity-perturbation accuracy test: 256 eps\";\n            number_of_repeated_experiments = 1;\n            accuracy_test = true;\n            test_random = false, random_range = 3, number_of_random_cases = 1024 * 1024; // random test\n            test_integer = false; // integer test\n            integer_range = 2; // this variable is used by both integer test and perturbed integer test\n            test_perturbation = false, perturbation_count = 4, float_perturbation = (float)256 * std::numeric_limits<float>::epsilon(), double_perturbation = (double)256 * std::numeric_limits<double>::epsilon(); // perturbed integer test\n            test_perturbation_from_identity = true, perturbation_from_identity_count = 1024 * 1024, float_perturbation_identity = (float)256 * std::numeric_limits<float>::epsilon(), double_perturbation_identity = (double)256 * std::numeric_limits<double>::epsilon(); // perturbed itentity test\n        }\n\n        std::cout << \" \\n========== RUNNING BENCHMARK TEST == \" << title << \"=======\" << std::endl;\n        std::cout << \" run_qr \" << run_qr << std::endl;\n        std::cout << \" test_float \" << test_float << std::endl;\n        std::cout << \" test_double \" << test_double << std::endl;\n        std::cout << \" accuracy_test \" << accuracy_test << std::endl;\n        std::cout << \" normalize_matrix \" << normalize_matrix << std::endl;\n        std::cout << \" number_of_repeated_experiments \" << number_of_repeated_experiments << std::endl;\n        std::cout << \" test_random \" << test_random << std::endl;\n        std::cout << \" random_range \" << random_range << std::endl;\n        std::cout << \" number_of_random_cases \" << number_of_random_cases << std::endl;\n        std::cout << \" test_integer \" << test_integer << std::endl;\n        std::cout << \" integer_range \" << integer_range << std::endl;\n        std::cout << \" test_perturbation \" << test_perturbation << std::endl;\n        std::cout << \" perturbation_count \" << perturbation_count << std::endl;\n        std::cout << \" float_perturbation \" << float_perturbation << std::endl;\n        std::cout << \" double_perturbation \" << double_perturbation << std::endl;\n        std::cout << \" test_perturbation_from_identity \" << test_perturbation_from_identity << std::endl;\n        std::cout << \" perturbation_from_identity_count \" << perturbation_from_identity_count << std::endl;\n        std::cout << \" float_perturbation_identity \" << float_perturbation_identity << std::endl;\n        std::cout << \" double_perturbation_identity \" << double_perturbation_identity << std::endl;\n\n        std::cout << std::setprecision(10) << \"\\n--- float test ---\\n\" << std::endl;\n        if (test_float) {\n            std::vector<Eigen::Matrix<float, 3, 3> > tests;\n            if (test_integer)\n                addIntegerCases(tests, integer_range);\n            if (test_perturbation)\n                addPerturbationCases(tests, integer_range, perturbation_count, float_perturbation);\n            if (test_perturbation_from_identity)\n                addPerturbationFromIdentityCases(tests, perturbation_from_identity_count, float_perturbation_identity);\n            if (test_random)\n                addRandomCases(tests, (float)random_range, number_of_random_cases);\n            if (normalize_matrix) {\n                for (size_t i = 0; i < tests.size(); i++) {\n                    float norm = tests[i].norm();\n                    if (norm > (float)8 * std::numeric_limits<float>::epsilon()) {\n                        tests[i] /= norm;\n                    }\n                }\n            }\n            std::cout << std::setprecision(10) << \"\\n-----------\" << std::endl;\n            if (run_qr)\n                runImplicitQRSVD(number_of_repeated_experiments, tests, accuracy_test);\n\n        }\n\n        std::cout << std::setprecision(10) << \"\\n--- double test ---\\n\" << std::endl;\n        if (test_double) {\n            std::vector<Eigen::Matrix<double, 3, 3> > tests;\n            if (test_integer)\n                addIntegerCases(tests, integer_range);\n            if (test_perturbation)\n                addPerturbationCases(tests, integer_range, perturbation_count, double_perturbation);\n            if (test_perturbation_from_identity)\n                addPerturbationFromIdentityCases(tests, perturbation_from_identity_count, double_perturbation_identity);\n            if (test_random)\n                addRandomCases(tests, (double)random_range, number_of_random_cases);\n            if (normalize_matrix) {\n                for (size_t i = 0; i < tests.size(); i++) {\n                    double norm = tests[i].norm();\n                    if (norm > (double)8 * std::numeric_limits<double>::epsilon()) {\n                        tests[i] /= norm;\n                    }\n                }\n            }\n            std::cout << std::setprecision(10) << \"\\n-----------\" << std::endl;\n            if (run_qr)\n                runImplicitQRSVD(number_of_repeated_experiments, tests, accuracy_test);\n\n        }\n    }\n}\n\nvoid calc_V(const Eigen::Matrix2f& C, Eigen::Matrix2f& V) {\n\n\tEigen::Matrix2f Sigma;\n\tfloat tau, t_2, c_2, s_2;\n\n\ttau = (C(1, 1) - C(0, 0)) / (2 * C(1, 0));\n\tif (tau>0) {\n\t\tt_2 = tau - sqrt(1 + tau*tau);\n\t}\n\telse {\n\t\tt_2 = tau + sqrt(1 + tau*tau);\n\t}\n\tc_2 = 1 / sqrt(1 + t_2*t_2);\n\ts_2 = t_2*c_2;\n\tV << c_2, -s_2, s_2, c_2;\n}\n\n\nvoid signconvention(Matrix2f& U, Matrix2f& V, Vector2f& sigma) {\n\tVector2f tempvec;\n\tfloat tempf;\n\tif (sigma(0)<0 && sigma(1)<0) {\n\t\tU = -U;\n\t\tsigma = -sigma;\n\t}\n\tif (sigma(0)<0) {\n\t\ttempvec = U.col(0);\n\t\tU.col(0) << U.col(1);\n\t\tU.col(1) = tempvec;\n\t\ttempf = sigma(0);\n\t\tsigma(0) = sigma(1);\n\t\tsigma(1) = tempf;\n\t\ttempvec = V.col(0);\n\t\tV.col(0) << V.col(1);\n\t\tV.col(1) = tempvec;\n\n\t}\n\telse if (sigma(0) >= 0 && sigma(1) >= 0) {\n\t\tif (sigma(1) > sigma(0)) {\n\t\t\ttempvec = U.col(0);\n\t\t\tU.col(0) << U.col(1);\n\t\t\tU.col(1) = tempvec;\n\t\t\ttempf = sigma(0);\n\t\t\tsigma(0) = sigma(1);\n\t\t\tsigma(1) = tempf;\n\t\t\ttempvec = V.col(0);\n\t\t\tV.col(0) << V.col(1);\n\t\t\tV.col(1) = tempvec;\n\t\t}\n\t}\n\n\n\n}\n\nvoid My_SVD(const Eigen::Matrix2f& F,Eigen::Matrix2f& U,Eigen::Matrix2f& sigma,Eigen::Matrix2f& V){\n//\n//Compute the SVD of input F with sign conventions discussed in class and in assignment\n//\n//input: F\n//output: U,sigma,V with F=U*sigma*V.transpose() and U*U.transpose()=V*V.transpose()=I;\n\n\tEigen::Matrix2f C, A, Sigma;\n\tEigen::Vector2f b, v, sigma_vec;\n\tEigen::JacobiRotation<float> G;\n\tfloat a, c_U, s_U;\n\n\n\n\tC = F.transpose()*F;\n\tcalc_V(C, V);\n\n\tA = F*V;\n\n\tG.makeGivens(A(0, 0), A(1, 0));\n\tv << 1, 0;\n\tv.applyOnTheLeft(0, 1, G);\n\tc_U = v(0);\n\ts_U = -v(1);\n\tU << c_U, s_U, -s_U, c_U;\n\tSigma = A;\n\tSigma.applyOnTheLeft(0, 1, G.adjoint());\n\n\tsigma_vec(0) = Sigma(0, 0);\n\tsigma_vec(1) = Sigma(1, 1);\n\n\tsignconvention(U, V, sigma_vec);\n\n\tsigma << sigma_vec(0), 0,\n\t\t0, sigma_vec(1);\n\n}\n\nvoid My_Polar(const Eigen::Matrix3f& F,Eigen::Matrix3f& R,Eigen::Matrix3f& S){\n  //\n  //Compute the polar decomposition of input F (with det(R)=1)\n  //\n  //input: F\n  //output: R,s with F=R*S and R*R.transpose()=I and S=S.transpose()\n\n\tEigen::JacobiRotation<float> G;\n\tfloat tol = 1e-6, max_it = 1e4, S_diff[] = { 100,100,100 }, S_diff_max;\n\tint it = 0, i_rot = 0, i, j, i_max;\n\n\n\n\n\tR = MatrixXf::Identity(3, 3);\n\tS = F;\n\n\tfor (i_max = 0; i_max < 3; i_max++) {\n\t\tif (i_max == 0)\n\t\t\tS_diff_max = S_diff[0];\n\t\telse if (S_diff[i_max] > S_diff[i_max - 1])\n\t\t\tS_diff_max = S_diff[i_max];\n\t}\n\n\n\n\twhile (it<max_it && S_diff_max > tol) {\n\n\n\t\tfor (i_rot = 0; i_rot < 3; i_rot++) {\n\t\t\tif (i_rot == 0) {\n\t\t\t\ti = 1;\n\t\t\t\tj = 2;\n\t\t\t}\n\t\t\telse if (i_rot == 1) {\n\t\t\t\ti = 0;\n\t\t\t\tj = 2;\n\t\t\t}\n\t\t\telse if (i_rot == 2) {\n\t\t\t\ti = 0;\n\t\t\t\tj = 1;\n\t\t\t}\n\t\t\tG.makeGivens(S(i, i) + S(j, j), S(i, j) - S(j, i));\n\t\t\tR.applyOnTheRight(i, j, G.adjoint());\n\t\t\tS.applyOnTheLeft(i, j, G);\n\n\n\n\t\t}\n\n\t\tit++;\n\t\tS_diff[0] = std::abs(S(1, 2) - S(2, 1));\n\t\tS_diff[1] = std::abs(S(0, 2) - S(2, 0));\n\t\tS_diff[2] = std::abs(S(0, 1) - S(1, 0));\n\t\tfor (i_max = 0; i_max < 3; i_max++) {\n\t\t\tif (i_max == 0)\n\t\t\t\tS_diff_max = S_diff[0];\n\t\t\telse if (S_diff[i_max] > S_diff[i_max - 1])\n\t\t\t\tS_diff_max = S_diff[i_max];\n\t\t}\n\n\n\n\t}\n\n}\n\n// void Algorithm_2_Test(){\n//\n//   Eigen::Matrix2f F,C,U,V;\n//   F<<1,2,3,4;\n//   C=F*F.transpose();\n//   Eigen::Vector2f s2;\n//   JIXIE::Jacobi(C,s2,V);\n//\n// }\n\nint main()\n{\n  bool run_benchmark = false;\n  if (run_benchmark) runBenchmark();\n}\n", "meta": {"hexsha": "01a8c8b87966386a9990f1936ae0a0587048816d", "size": 26678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "ShyrSheaChang/Math_270A_Fall_2016_HW", "max_stars_repo_head_hexsha": "470767cccf25319ee713481004ac0a5a65129cc4", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "ShyrSheaChang/Math_270A_Fall_2016_HW", "max_issues_repo_head_hexsha": "470767cccf25319ee713481004ac0a5a65129cc4", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "ShyrSheaChang/Math_270A_Fall_2016_HW", "max_forks_repo_head_hexsha": "470767cccf25319ee713481004ac0a5a65129cc4", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4633333333, "max_line_length": 293, "alphanum_fraction": 0.6263213134, "num_tokens": 7418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5092431699313064}}
{"text": "// The MIT License (MIT)\n\n// Copyright (c) 2018 li chunpeng, Xidian university\n\n// Permission is hereby granted, free of charge, to any person obtaining sum copy of\n// this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to\n// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n// the Software, and to permit persons to whom the Software is furnished to do so,\n// 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, FITNESS\n// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n// IN AN 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 SOFTWARE.\n\n\n#ifndef _URANUS_UN_CONSTRAINED_HPP_\n#define _URANUS_UN_CONSTRAINED_HPP_\n\n// \u5e38\u89c1\u65e0\u7ea6\u675f\u4f18\u5316\u7b97\u6cd5\n// \u76f4\u63a5\u65b9\u6cd5\n// \u95f4\u63a5\u65b9\u6cd5\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"Matrix.hpp\"\n\nusing namespace std;\n\ntemplate<int Dim> struct problem\n{\n\turanus::SquareMatrix<Dim> matirx_Jacobian_;  // \u4e00\u9636\u6c42\u5bfc\u77e9\u9635\n\t\n\turanus::Vector<Dim>& gradient(uranus::Vector<Dim>& var_x)\n\t{\n\t\tvar_x = matirx_Jacobian_ * var_x;\n\t\treturn var_x;\n\t}\n};\n\ntemplate<int Dim> double myval(uranus::Vector<Dim> s_k)\n{\n\tdouble sum = 0;\n\tfor(int i=0;i<Dim;++i)\n\t{\n\t\tsum = sum + pow(s_k(i),2);\n\t}\n\treturn sqrt(sum);\n}\n/**\n * @brief \u4f7f\u7528\u79e9\u4e3a2\u7684\u6a21\u62df\u725b\u987f\u6cd5, BFGS\n * @param \u6c42\u89e3\u7684\u95ee\u9898f\n * @param \u521d\u59cb\u70b9 var_x,\u662f\u4e00\u4e2a\u5411\u91cf\uff0c\u53ef\u5305\u542b\u591a\u7ef4\n * @param \u7ec8\u6b62\u6761\u4ef6 delta, \u9ed8\u8ba4 0.001\n * @param \u662f\u5426\u6253\u5370\u4e2d\u95f4\u7ed3\u679c\n * @return \u6c42\u89e3\u5f97\u5230\u7684\u6700\u4f18\u70b9 \n */\ntemplate<int Dim>\nuranus::Vector<Dim> BFGS(problem<Dim> f,\n\t\t\t\t\t\t uranus::Vector<Dim> var_x, \n\t\t\t\t\t\t const double delta = 0.001, \n\t\t\t\t\t\t bool visual = false)\n{\n\turanus::Vector<Dim> s_k;\n\turanus::Vector<Dim> y_k;\n\turanus::SquareMatrix<Dim> H_k;\n\turanus::SquareMatrix<Dim> E_k1;\n\turanus::SquareMatrix<Dim> E_k2;\n\n\t// init \u5355\u4f4d\u77e9\u9635\n\tfor (int i = 0;i < Dim; ++i)\n\t\tfor (int j = 0;j < Dim; ++j)\n\t\t\tif ( i == j) H_k(i,j) = 1;\n\t\t\telse H_k(i,j) = 0;\n\t\n\twhile(myval<Dim>(s_k) < delta)  \n\t{\n\t\ts_k = -H_k * f.gradient(var_x);           // s_k = var_x2 - var_x1\n\t\ty_k = f.gradient(var_x);\n\t\tvar_x = var_x - H_k * f.gradient(var_x);     \n\t\ty_k = f.gradient(var_x) - y_k;            // y_k = \\delta f_{k} - \\delta f_{k-1}\n\t    \n\t\t\n\t\tE_k1  = (s_k * s_k.transpose() - H_k * y_k * s_k.transpose() - s_k * y_k.transpose() * H_k)\n\t\t      / (s_k.transpose() * y_k);\n\t\tE_k2 = s_k * s_k.transpose();\n\n\t\tdouble k21 = y_k.transpose() * H_k * y_k;\n\t\tdouble k22 = pow((s_k.transpose() * y_k),2);\n\n\t\tH_k = H_k + E_k1 + E_k2 * k21/k22;    // update H_k\n\n\t\tif(visual)\n\t\t{\n\t\t\tcout << \"s_k:\\n\" << s_k << \"\\n\" \n\t\t\t\t << \"y_k:\\n\" << y_k << \"\\n\"\n\t\t\t\t << \"H_k:\\n\" << H_k << \"\\n\";\n \t\t}\n\t}\n\treturn var_x; // result\n}\n/**\n * @brief \u4f7f\u7528BFGS\u7684\u5916\u70b9\u6cd5\n * @param \u521d\u59cb\u70b9 var_x,\u662f\u4e00\u4e2a\u5411\u91cf\uff0c\u53ef\u5305\u542b\u591a\u7ef4\n * @param \u7ec8\u6b62\u6761\u4ef6 delta, \u9ed8\u8ba4 0.001\n * @param \u662f\u5426\u6253\u5370\u4e2d\u95f4\u7ed3\u679c\n * @return \u6c42\u89e3\u5f97\u5230\u7684\u6700\u4f18\u70b9 \n */\ntemplate<int Dim>\nvoid External_point_method(uranus::Vector<Dim> var_x, \n\t\t\t\t\t\t   const double delta = 0.001,\n\t\t\t\t\t\t   const double C = 10\n\t\t\t\t\t\t   bool visual = false)\n{\n\tdouble M_k = 0.1;                          // init M_k > 0\t\n\tdo{\n\t\tM_k = C * M_k;                         // update M_k\n\t\tf.Jacobian_Matrix(1,1) = 2 + M_k;      // update J mat\n\n\t\tvar_x = BFGS(f, var_x, delta, visual); // min f\n\t}\n\twhile(M_k * pow(var_x(1)-1), 2) > delta);\n\n}\n\n#endif", "meta": {"hexsha": "496567233b7fda40152f36c4094000db381f8d60", "size": 3628, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/uranus/un-constrained.hpp", "max_stars_repo_name": "hackath/Uranus", "max_stars_repo_head_hexsha": "415db5b23afdae52ed59c7d4ab08b671e2122485", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T02:29:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-03T07:47:10.000Z", "max_issues_repo_path": "include/uranus/un-constrained.hpp", "max_issues_repo_name": "hackath/Uranus", "max_issues_repo_head_hexsha": "415db5b23afdae52ed59c7d4ab08b671e2122485", "max_issues_repo_licenses": ["MIT"], "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/uranus/un-constrained.hpp", "max_forks_repo_name": "hackath/Uranus", "max_forks_repo_head_hexsha": "415db5b23afdae52ed59c7d4ab08b671e2122485", "max_forks_repo_licenses": ["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.4848484848, "max_line_length": 93, "alphanum_fraction": 0.6411245865, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5092431609021246}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n#include <set>\r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\nint main(int argc, char *argv[]) {\r\n\t// Sets only hold unique integers, making it the perfect container.\r\n\tset<cpp_int> numbers;\r\n\tfor(cpp_int a = 2; a < 101; a++) {\r\n\t\tfor(int b = 2; b < 101; b++) {\r\n\t\t\tnumbers.emplace(boost::multiprecision::pow(a, b));\r\n\t\t}\r\n\t}\r\n\tcout << numbers.size() << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "6e952674d678c58ce1f26dc9f572fe12c49c0ca5", "size": 459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/1-50/29/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/29/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/29/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": 25.5, "max_line_length": 69, "alphanum_fraction": 0.6427015251, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5090976849910368}}
{"text": "// Copyright Louis Dionne 2015\n// Distributed under the Boost Software License, Version 1.0.\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/functional/fix.hpp>\n#include <boost/hana/functional/partial.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/lazy.hpp>\n#include <boost/hana/tuple.hpp>\nusing namespace boost::hana;\n\n\nnamespace disambiguate {\n// sample(sorting-now)\ntemplate <typename Xs, typename Pred>\nauto sort(Xs xs, Pred pred) {\n  return eval_if(length(xs) < size_t<2>,\n    lazy(xs),\n    lazy([=](auto xs) {\n      auto pivot = head(xs);\n      auto parts = partition(tail(xs), partial(pred, pivot));\n      return concat(\n        append(sort(second(parts), pred), pivot),\n        sort(first(parts), pivot)\n      );\n    })(xs)\n  );\n}\n// end-sample\n}\n\nint main() {\n  using disambiguate::sort;\n  BOOST_HANA_CONSTANT_CHECK(\n    sort(make_tuple(), less) == make_tuple()\n  );\n\n  BOOST_HANA_CONSTANT_CHECK(\n    sort(make_tuple(int_<1>), less) == make_tuple(int_<1>)\n  );\n\n  BOOST_HANA_CONSTANT_CHECK(\n    sort(make_tuple(int_<2>, int_<1>), less) == make_tuple(int_<1>, int_<2>)\n  );\n\n  BOOST_HANA_CONSTANT_CHECK(\n    sort(make_tuple(int_<3>, int_<2>, int_<1>), less) ==\n      make_tuple(int_<1>, int_<2>, int_<3>)\n  );\n\n  BOOST_HANA_CONSTANT_CHECK(\n    sort(make_tuple(int_<4>, int_<3>, int_<2>, int_<1>), less) ==\n      make_tuple(int_<1>, int_<2>, int_<3>, int_<4>)\n  );\n}\n", "meta": {"hexsha": "3dcda5e8f8a683e5a9ae02d4c162748d97d31971", "size": 1404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/sorting-now.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/sorting-now.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/sorting-now.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": 25.0714285714, "max_line_length": 76, "alphanum_fraction": 0.6566951567, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5090718074103963}}
{"text": "#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"solvers/least_squares.h\"\n\nnamespace lf\n{\nnamespace\n{\nclass LeastSquaresFixture\n  : public LeastSquares, public testing::Test\n{\nprotected:\n  LeastSquaresFixture(): LeastSquares() {};\n};\n\nTEST_F(LeastSquaresFixture, LeastSquares) {\n  // Initialization\n  Eigen::ArrayXf noise_x{ 2 };\n  noise_x << 0, 1;\n  Eigen::ArrayXf noise_y{ 2 };\n  noise_y << 0, 1;\n\n  Line line = Fit(noise_x, noise_y);\n  ASSERT_FLOAT_EQ(line.m, 1.0f);\n  ASSERT_FLOAT_EQ(line.b, 0.0f);\n}\n} // namespace\n} // namespace lf\n", "meta": {"hexsha": "86c404ab90028f5863c33541818276ea449a53a3", "size": 548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "linear_fitting/test.cpp", "max_stars_repo_name": "eborghi10/noisy_fit_2d", "max_stars_repo_head_hexsha": "a1839fac91eda333b9869c9a7add5c6e757a58e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_fitting/test.cpp", "max_issues_repo_name": "eborghi10/noisy_fit_2d", "max_issues_repo_head_hexsha": "a1839fac91eda333b9869c9a7add5c6e757a58e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_fitting/test.cpp", "max_forks_repo_name": "eborghi10/noisy_fit_2d", "max_forks_repo_head_hexsha": "a1839fac91eda333b9869c9a7add5c6e757a58e2", "max_forks_repo_licenses": ["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.2666666667, "max_line_length": 45, "alphanum_fraction": 0.697080292, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5090718041589155}}
{"text": "#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n    int nx=400;\n    int nz=600;\n    arma::Mat<float> model_ori(nz,nx,fill::zeros);\n\n    arma::Mat<float> model_sur(nz,nx,fill::zeros);\n\n    arma::Col<float> surface(nx,fill::zeros);\n\n\n    model_ori.load(\"./model_nz600_nx400.dat\",raw_binary);\n    model_ori.reshape(nz,nx);\n\n    for (int ix=0; ix<nx ;ix++)\n    {\n        int flag = 0;\n\n        for(int iz=1; iz<nz; iz++)\n        {\n            if(flag==0 &&  model_ori(iz,ix)>5*model_ori(iz-1,ix))\n            {\n                surface(ix)=iz;\n                flag = 1;\n            }\n        }\n    }\n\n    float mean = arma::median(surface);\n\n    for(int ix=0; ix<nx ;ix++)\n    {\n        for(int iz=0; iz<nz;iz++)\n        {\n            if (iz<surface(ix))\n            {\n                model_sur(iz,ix)=model_ori(iz,ix);\n            }\n            else\n            {\n                //01 : every point\n                //model_sur(iz,ix)=model_ori(surface(ix),ix);\n\n                //02 : mean velocity\n                //model_sur(iz,ix)=mean;\n\n                //03 : some trick\n                if(model_ori(iz,ix)>1000)\n                {\n                    model_sur(iz,ix) = 1000;\n                }\n                else\n                {\n                    model_sur(iz,ix) = model_ori(iz,ix);\n                }\n\n            }\n        }\n    }\n\n\n\n    model_sur.save(\"model_topo.dat\",raw_binary);\n\n\n\n\n\n    return 0;\n}\n", "meta": {"hexsha": "5086995b5da5e53f92836dc4e83b03f04d85f018", "size": 1463, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "model/surface_modeling.cpp", "max_stars_repo_name": "Bohan-Zhang-2017/-ELASTIC_WAVE_FD", "max_stars_repo_head_hexsha": "b2e2658b1cb24d4dbe603fa11f977f854c762add", "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": "model/surface_modeling.cpp", "max_issues_repo_name": "Bohan-Zhang-2017/-ELASTIC_WAVE_FD", "max_issues_repo_head_hexsha": "b2e2658b1cb24d4dbe603fa11f977f854c762add", "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": "model/surface_modeling.cpp", "max_forks_repo_name": "Bohan-Zhang-2017/-ELASTIC_WAVE_FD", "max_forks_repo_head_hexsha": "b2e2658b1cb24d4dbe603fa11f977f854c762add", "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.0, "max_line_length": 65, "alphanum_fraction": 0.4333561176, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5090718022812518}}
{"text": "/*\n * Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// includes\n// std\n#include <iostream>\n\n// boost\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Eigen_QLD\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n// Eigen\n#include <Eigen/Dense>\n\n// EigenQP\n#include <eigen-qld/QLD.h>\n\nstruct QP1\n{\n  QP1()\n  {\n    nrvar = 6;\n    nreq = 3;\n    nrineq = 2;\n\n    Q.resize(nrvar, nrvar);\n    Aeq.resize(nreq, nrvar);\n    Aineq.resize(nrineq, nrvar);\n    A.resize(nreq + nrineq, nrvar);\n\n    C.resize(nrvar);\n    Beq.resize(nreq);\n    Bineq.resize(nrineq);\n    B.resize(nreq + nrineq);\n    XL.resize(nrvar);\n    XU.resize(nrvar);\n    X.resize(nrvar);\n\n    Aeq << 1., -1., 1., 0., 3., 1., -1., 0., -3., -4., 5., 6., 2., 5., 3., 0., 1., 0.;\n    Beq << 1., 2., 3.;\n\n    Aineq << 0., 1., 0., 1., 2., -1., -1., 0., 2., 1., 1., 0.;\n    Bineq << -1., 2.5;\n\n    A.topRows(nreq) = Aeq;\n    A.bottomRows(nrineq) = -Aineq;\n\n    B.head(nreq) = -Beq;\n    B.tail(nrineq) = Bineq;\n\n    // with  x between ci and cs:\n    XL << -1000., -10000., 0., -1000., -1000., -1000.;\n    XU << 10000., 100., 1.5, 100., 100., 1000.;\n\n    // and minimize 0.5*x'*Q*x + p'*x with\n    C << 1., 2., 3., 4., 5., 6.;\n    Q.setIdentity();\n\n    X << 1.7975426, -0.3381487, 0.1633880, -4.9884023, 0.6054943, -3.1155623;\n  }\n\n  int nrvar, nreq, nrineq;\n  Eigen::MatrixXd Q, Aeq, Aineq, A;\n  Eigen::VectorXd C, Beq, Bineq, B, XL, XU, X;\n};\n\nvoid ineqWithXBounds(Eigen::MatrixXd & Aineq,\n                     Eigen::VectorXd & Bineq,\n                     const Eigen::VectorXd & XL,\n                     const Eigen::VectorXd & XU)\n{\n  double inf = std::numeric_limits<double>::infinity();\n\n  std::vector<std::pair<int, double>> lbounds, ubounds;\n\n  for(int i = 0; i < XL.rows(); ++i)\n  {\n    if(XL[i] != -inf) lbounds.emplace_back(i, XL[i]);\n    if(XU[i] != inf) ubounds.emplace_back(i, XU[i]);\n  }\n\n  long int nrconstr = Bineq.rows() + static_cast<long int>(lbounds.size()) + static_cast<long int>(ubounds.size());\n\n  Eigen::MatrixXd A(Eigen::MatrixXd::Zero(nrconstr, Aineq.cols()));\n  Eigen::VectorXd B(Eigen::VectorXd::Zero(nrconstr));\n\n  A.block(0, 0, Aineq.rows(), Aineq.cols()) = Aineq;\n  B.segment(0, Bineq.rows()) = Bineq;\n\n  int start = static_cast<int>(Aineq.rows());\n\n  for(int i = 0; i < static_cast<int>(lbounds.size()); ++i)\n  {\n    const auto & b = lbounds[i];\n    A(start, b.first) = -1.;\n    B(start) = -b.second;\n    ++start;\n  }\n\n  for(int i = 0; i < static_cast<int>(ubounds.size()); ++i)\n  {\n    const auto & b = ubounds[i];\n    A(start, b.first) = 1.;\n    B(start) = b.second;\n    ++start;\n  }\n\n  Aineq = A;\n  Bineq = B;\n}\n\nBOOST_AUTO_TEST_CASE(QLD)\n{\n  QP1 qp1;\n\n  Eigen::QLD qld(qp1.nrvar, qp1.nreq, qp1.nrineq);\n\n  qld.solve(qp1.Q, qp1.C, qp1.Aeq, qp1.Beq, qp1.Aineq, qp1.Bineq, qp1.XL, qp1.XU);\n  BOOST_CHECK_SMALL((qld.result() - qp1.X).norm(), 1e-6);\n\n  Eigen::QLDDirect qldd(qp1.nrvar, qp1.nreq, qp1.nrineq);\n\n  qldd.solve(qp1.Q, qp1.C, qp1.A, qp1.B, qp1.XL, qp1.XU, 3);\n  BOOST_CHECK_SMALL((qld.result() - qp1.X).norm(), 1e-6);\n}\n\nBOOST_AUTO_TEST_CASE(QLDSize)\n{\n  QP1 qp1;\n\n  Eigen::QLD qld(qp1.nrvar, qp1.nreq + 10, qp1.nrineq + 22);\n\n  qld.solve(qp1.Q, qp1.C, qp1.Aeq, qp1.Beq, qp1.Aineq, qp1.Bineq, qp1.XL, qp1.XU);\n\n  BOOST_CHECK_SMALL((qld.result() - qp1.X).norm(), 1e-6);\n}\n\nBOOST_AUTO_TEST_CASE(IneqWithXBounds)\n{\n  QP1 qp1;\n\n  ineqWithXBounds(qp1.Aineq, qp1.Bineq, qp1.XL, qp1.XU);\n\n  double inf = std::numeric_limits<double>::infinity();\n  for(int i = 0; i < qp1.nrvar; ++i)\n  {\n    qp1.XL[i] = -inf;\n    qp1.XU[i] = inf;\n  }\n\n  int nrineq = static_cast<int>(qp1.Aineq.rows());\n  Eigen::QLD qld(qp1.nrvar, qp1.nreq, nrineq);\n\n  qld.solve(qp1.Q, qp1.C, qp1.Aeq, qp1.Beq, qp1.Aineq, qp1.Bineq, qp1.XL, qp1.XU);\n\n  BOOST_CHECK_SMALL((qld.result() - qp1.X).norm(), 1e-6);\n}\n", "meta": {"hexsha": "183d5925a1fe026ae84e9d3921f1de88e3decd4c", "size": 3859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/QPTest.cpp", "max_stars_repo_name": "jrl-umi3218/eigen-qld", "max_stars_repo_head_hexsha": "3ab4a2246ed54daca4fe8fc355ac3c47ea832206", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2017-09-15T09:02:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T18:03:17.000Z", "max_issues_repo_path": "tests/QPTest.cpp", "max_issues_repo_name": "jrl-umi3218/eigen-qld", "max_issues_repo_head_hexsha": "3ab4a2246ed54daca4fe8fc355ac3c47ea832206", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2017-01-13T18:19:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-24T04:10:19.000Z", "max_forks_repo_path": "tests/QPTest.cpp", "max_forks_repo_name": "jrl-umi3218/eigen-qld", "max_forks_repo_head_hexsha": "3ab4a2246ed54daca4fe8fc355ac3c47ea832206", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-10-26T17:28:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-11T11:43:45.000Z", "avg_line_length": 23.8209876543, "max_line_length": 115, "alphanum_fraction": 0.5871987562, "num_tokens": 1506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5090718022812517}}
{"text": "// Copyright (c) 2018 James Pritts\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// Modified for HomLib to accept Eigen matrices by Marcus Valtonen \u00d6rnhag\n\n#include <Eigen/Dense>\n#include \"gj.hpp\"\n\nnamespace HomLib {\n    void gj(Eigen::MatrixXd *M) {\n        int rcnt = M->rows();\n        int ccnt = M->cols();\n\n        M->transposeInPlace();\n        double* A = M->data();\n\n        double tol = 1e-15;\n        int r = 0;      // row\n        int c = 0;      // col\n        int k;\n        int l;\n        int dstofs;\n        int srcofs;\n        int ofs = 0;\n        int pofs = 0;\n        double b;\n\n        // gj\n        ofs = 0;\n        pofs = 0;\n        while (r < rcnt && c < ccnt) {\n            // find pivot\n            double apivot = 0;\n            double pivot = 0;\n            int pivot_r = -1;\n\n            pofs = ofs;\n            for (k = r; k < rcnt; k++) {\n                // pivot selection criteria here !\n                if (fabs(*(A+pofs)) > apivot) {\n                    pivot = *(A+pofs);\n                    apivot = fabs(pivot);\n                    pivot_r = k;\n                }\n                pofs += ccnt;\n            }\n\n            if (apivot < tol) {\n                // empty col - shift to next col (or jump)\n                c++;\n                ofs++;\n\n            } else {\n                // process rows\n\n                // exchange pivot and selected rows\n                // + divide row\n                if (pivot_r == r) {\n                    srcofs = ofs;\n                    for (l = c; l < ccnt; l++) {\n                        *(A+srcofs) = *(A+srcofs)/pivot;\n                        srcofs++;\n                    }\n\n                } else {\n                    srcofs = ofs;\n                    dstofs = ccnt*pivot_r+c;\n                    for (l = c; l < ccnt; l++) {\n                        b = *(A+srcofs);\n                        *(A+srcofs) = *(A+dstofs)/pivot;\n                        *(A+dstofs) = b;\n\n                        srcofs++;\n                        dstofs++;\n                    }\n                }\n\n                // zero bottom\n                pofs = ofs + ccnt;\n                for (k = r + 1; k < rcnt; k++) {\n                        // nonzero row\n                        b = *(A+pofs);\n                        dstofs = pofs + 1;\n                        srcofs = ofs + 1;\n                        for (l = c + 1; l < ccnt; l++) {\n                            *(A+dstofs) = (*(A+dstofs) - *(A+srcofs) * b);\n                            dstofs++;\n                            srcofs++;\n                        }\n                        *(A+pofs) = 0;\n\n                    pofs += ccnt;\n                }\n\n                // zero top\n                pofs = c;\n                for (k = 0; k < r; k++) {\n                        // nonzero row\n                        b = *(A+pofs);\n                        dstofs = pofs + 1;\n                        srcofs = ofs + 1;\n                        for (l = c + 1; l < ccnt; l++) {\n                            *(A+dstofs) = (*(A+dstofs) - *(A+srcofs) * b);\n                            dstofs++;\n                            srcofs++;\n                        }\n                        *(A+pofs) = 0;\n\n                    pofs += ccnt;\n                }\n\n                r++;\n                c++;\n                ofs += ccnt + 1;\n            }\n        }\n\n        (*M) << Eigen::Map<Eigen::MatrixXd>(A, ccnt, rcnt);\n        M->transposeInPlace();\n    }\n}  // namespace HomLib\n", "meta": {"hexsha": "6b83ce939a02ccc6df06e69a8d4ddcc824279a2d", "size": 4494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/helpers/gj.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/gj.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/gj.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": 32.3309352518, "max_line_length": 81, "alphanum_fraction": 0.4087672452, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6619228758499941, "lm_q1q2_score": 0.5090718022812516}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n#include <boost/timer.hpp>\n\ntemplate <typename Matrix>\nvoid setup(Matrix& A)\n{\n    const int n= num_rows(A);\n    A= 1.0;\n    mtl::mat::inserter<Matrix, mtl::update_plus<double> > ins(A);\n\n    for (int i= 0; i < 30 * n; i++) {\n\tint r= rand()%n, c= rand()%n;\n\tins[r][c] << -1;\n\tins[r][r] << 1;\n    }\n}\n\n\n\nint main(int argc, char* argv[])\n{\n    // For a more realistic example set sz to 1000 or larger\n    int size = 3;\n    if (argc > 1) size = atoi(argv[1]);\n    int N = size * size; \n\n    typedef mtl::compressed2D<double>  matrix_type;\n    typedef mtl::dense_vector<double>  vector_type;\n    mtl::compressed2D<double>          A(N, N);\n    setup(A);\n\n    boost::timer                       fac_timer;\n    itl::pc::ilu_0<matrix_type>        P(A);\n    std::cout << \"Factorization took \" << fac_timer.elapsed() << \"s\\n\";\n    \n    mtl::dense_vector<double> x(N, 3.0), x2(N), Px(N), x3(N), x4(N), x5(N);\n\n    matrix_type L(P.get_L()), U(P.get_U());\n\n    x2= strict_upper(U) * x;\n    for (int i= 0; i < N; i++)\n\tx2[i]+= 1. / U[i][i] * x[i];\n\n    Px= L * x2 + x2;\n\n    x4= unit_lower_trisolve(L, Px);\n    if (two_norm(vector_type(x4 - x2)) > 0.01) throw \"Error in unit_lower_trisolve.\";\n\n    x5= inverse_upper_trisolve(U, x4);\n    if (two_norm(vector_type(x5 - x)) > 0.01) throw \"Error in inverse_upper_trisolve.\";\n\n\n    boost::timer                       solve_timer;\n    x3= solve(P, Px);\n    std::cout << \"Solving took \" << solve_timer.elapsed() << \"s\\n\";\n\n    if (two_norm(vector_type(x3 - x)) > 0.01) throw \"Error in solve.\";\n\n    return 0;\n}\n", "meta": {"hexsha": "ba4a7f23c3babb30cfd01a2f4642517174235c31", "size": 2059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/timing/ilu_0_timing.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/timing/ilu_0_timing.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/timing/ilu_0_timing.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": 27.8243243243, "max_line_length": 94, "alphanum_fraction": 0.5959203497, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925402, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5090495991966751}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra. Eigen itself is part of the KDE project.\n//\n// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>\n//\n// Eigen is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3 of the License, or (at your option) any later version.\n//\n// Alternatively, you can redistribute it and/or\n// modify it under the terms of the GNU General Public License as\n// published by the Free Software Foundation; either version 2 of\n// the License, or (at your option) any later version.\n//\n// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License and a copy of the GNU General Public License along with\n// Eigen. If not, see <http://www.gnu.org/licenses/>.\n\n#include \"main.h\"\n#include <Eigen/QR>\n\ntemplate<typename MatrixType> void qr(const MatrixType& m)\n{\n  /* this test covers the following files:\n     QR.h\n  */\n  int rows = m.rows();\n  int cols = m.cols();\n\n  typedef typename MatrixType::Scalar Scalar;\n  typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, MatrixType::ColsAtCompileTime> SquareMatrixType;\n  typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> VectorType;\n\n  MatrixType a = MatrixType::Random(rows,cols);\n  QR<MatrixType> qrOfA(a);\n  VERIFY_IS_APPROX(a, qrOfA.matrixQ() * qrOfA.matrixR());\n  VERIFY_IS_NOT_APPROX(a+MatrixType::Identity(rows, cols), qrOfA.matrixQ() * qrOfA.matrixR());\n\n  #if 0 // eigenvalues module not yet ready\n  SquareMatrixType b = a.adjoint() * a;\n\n  // check tridiagonalization\n  Tridiagonalization<SquareMatrixType> tridiag(b);\n  VERIFY_IS_APPROX(b, tridiag.matrixQ() * tridiag.matrixT() * tridiag.matrixQ().adjoint());\n\n  // check hessenberg decomposition\n  HessenbergDecomposition<SquareMatrixType> hess(b);\n  VERIFY_IS_APPROX(b, hess.matrixQ() * hess.matrixH() * hess.matrixQ().adjoint());\n  VERIFY_IS_APPROX(tridiag.matrixT(), hess.matrixH());\n  b = SquareMatrixType::Random(cols,cols);\n  hess.compute(b);\n  VERIFY_IS_APPROX(b, hess.matrixQ() * hess.matrixH() * hess.matrixQ().adjoint());\n  #endif\n}\n\nvoid test_eigen2_qr()\n{\n  for(int i = 0; i < 1; i++) {\n    CALL_SUBTEST_1( qr(Matrix2f()) );\n    CALL_SUBTEST_2( qr(Matrix4d()) );\n    CALL_SUBTEST_3( qr(MatrixXf(12,8)) );\n    CALL_SUBTEST_4( qr(MatrixXcd(5,5)) );\n    CALL_SUBTEST_4( qr(MatrixXcd(7,3)) );\n  }\n\n#ifdef EIGEN_TEST_PART_5\n  // small isFullRank test\n  {\n    Matrix3d mat;\n    mat << 1, 45, 1, 2, 2, 2, 1, 2, 3;\n    VERIFY(mat.qr().isFullRank());\n    mat << 1, 1, 1, 2, 2, 2, 1, 2, 3;\n    //always returns true in eigen2support\n    //VERIFY(!mat.qr().isFullRank());\n  }\n\n#endif\n}\n", "meta": {"hexsha": "e6231208dea6ae55f7c5e349c5abbf298a9d963e", "size": 3000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/eigen2/eigen2_qr.cpp", "max_stars_repo_name": "mathstuf/ParaView", "max_stars_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_stars_repo_licenses": ["Apache-2.0"], "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": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/eigen2/eigen2_qr.cpp", "max_issues_repo_name": "mathstuf/ParaView", "max_issues_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T19:02:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T14:15:04.000Z", "max_forks_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/eigen2/eigen2_qr.cpp", "max_forks_repo_name": "mathstuf/ParaView", "max_forks_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_forks_repo_licenses": ["Apache-2.0"], "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": 35.2941176471, "max_line_length": 104, "alphanum_fraction": 0.7076666667, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.50904959243957}}
{"text": "#pragma once\n#include <cstdint>\n#include <cassert>\n#include <algorithm>\n#include <map>\n#include <boost/dynamic_bitset.hpp>\n//#include \"BitOperations.h\"\n#include \"../Basis/AbstractBasis2D.hpp\"\n\ntemplate<typename UINT>\nclass TIJ1J2_2D\n{\nprivate:\n\tconst edlib::AbstractBasis2D<UINT>& basis_;\n\tdouble J1_;\n\tdouble J2_;\n\tint sign_;\n\npublic:\n\tTIJ1J2_2D(const edlib::AbstractBasis2D<UINT>& basis, double J1, double J2, \n\t\t\tbool signRule = false)\n\t\t: basis_(basis), J1_(J1), J2_(J2)\n\t{\n\t\tif(signRule)\n\t\t\tsign_ = -1;\n\t\telse\n\t\t\tsign_ = 1;\n\t}\n\n\tstd::map<int,double> getCol(UINT n) const\n\t{\n\t\tuint32_t Lx = basis_.getLx();\n\t\tuint32_t Ly = basis_.getLy();\n\n\t\tUINT a = basis_.getNthRep(n);\n\t\tconst boost::dynamic_bitset<> bs(Lx*Ly, a);\n\n\t\tstd::map<int, double> m;\n\t\tfor(uint32_t nx = 0; nx < Lx; nx++)\n\t\t{\n\t\t\tfor(uint32_t ny = 0; ny < Ly; ny++)\n\t\t\t{\n\t\t\t\tauto i = basis_.toIdx(nx, ny);\n\t\t\t\t//Nearest neighbor x\n\t\t\t\t{\n\t\t\t\tauto j = basis_.toIdx((nx+1)%Lx, ny);\n\t\t\t\tint zz = (1-2*bs[i])*(1-2*bs[j]);\n\n\t\t\t\tm[n] += J1_*zz;\n\t\t\t\t\n\t\t\t\tUINT s = a;\n\t\t\t\ts ^= basis_.mask({i,j});\n\n\t\t\t\tint bidx;\n\t\t\t\tdouble coeff;\n\n\t\t\t\tstd::tie(bidx, coeff) = basis_.hamiltonianCoeff(s, n);\n\t\t\t\t\n\t\t\t\tif(bidx >= 0)\n\t\t\t\t\tm[bidx] += J1_*(1-zz)*coeff*sign_;\n\t\t\t\t}\n\t\t\t\t//Nearest neighbor y\n\t\t\t\t{\n\t\t\t\tauto j = basis_.toIdx(nx, (ny+1)%Ly);\n\t\t\t\tint zz = (1-2*bs[i])*(1-2*bs[j]);\n\n\t\t\t\tm[n] += J1_*zz;\n\t\t\t\t\n\t\t\t\tUINT s = a;\n\t\t\t\ts ^= basis_.mask({i,j});\n\n\t\t\t\tint bidx;\n\t\t\t\tdouble coeff;\n\n\t\t\t\tstd::tie(bidx, coeff) = basis_.hamiltonianCoeff(s, n);\n\t\t\t\t\n\t\t\t\tif(bidx >= 0)\n\t\t\t\t\tm[bidx] += J1_*(1-zz)*coeff*sign_;\n\t\t\t\t}\n\t\t\t\t//Next-nearest neighbor right up\n\t\t\t\t{\n\t\t\t\tauto j = basis_.toIdx((nx+1)%Lx, (ny+1)%Ly);\n\t\t\t\tint zz = (1-2*bs[i])*(1-2*bs[j]);\n\n\t\t\t\tm[n] += J2_*zz;\n\t\t\t\t\n\t\t\t\tUINT s = a;\n\t\t\t\ts ^= basis_.mask({i,j});\n\n\t\t\t\tint bidx;\n\t\t\t\tdouble coeff;\n\n\t\t\t\tstd::tie(bidx, coeff) = basis_.hamiltonianCoeff(s, n);\n\t\t\t\t\n\t\t\t\tif(bidx >= 0)\n\t\t\t\t\tm[bidx] += J2_*(1-zz)*coeff;\n\t\t\t\t}\n\t\t\t\t//Next-nearest neighbor right down\n\t\t\t\t{\n\t\t\t\tauto j = basis_.toIdx((nx+1)%Lx, (ny-1+Ly)%Ly);\n\t\t\t\tint zz = (1-2*bs[i])*(1-2*bs[j]);\n\n\t\t\t\tm[n] += J2_*zz;\n\t\t\t\t\n\t\t\t\tUINT s = a;\n\t\t\t\ts ^= basis_.mask({i,j});\n\n\t\t\t\tint bidx;\n\t\t\t\tdouble coeff;\n\n\t\t\t\tstd::tie(bidx, coeff) = basis_.hamiltonianCoeff(s, n);\n\t\t\t\t\n\t\t\t\tif(bidx >= 0)\n\t\t\t\t\tm[bidx] += J2_*(1-zz)*coeff;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn m;\n\t}\n};\n", "meta": {"hexsha": "4b5afdd4abbddcd2fc53ba60d4f022a5c2fa7bed", "size": 2305, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/edlib/Hamiltonians/TIJ1J2_2D.hpp", "max_stars_repo_name": "chaeyeunpark/ExactDiagonalization", "max_stars_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T08:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:47:05.000Z", "max_issues_repo_path": "include/edlib/Hamiltonians/TIJ1J2_2D.hpp", "max_issues_repo_name": "chaeyeunpark/ExactDiagonalization", "max_issues_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T19:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T19:02:14.000Z", "max_forks_repo_path": "include/edlib/Hamiltonians/TIJ1J2_2D.hpp", "max_forks_repo_name": "chaeyeunpark/ExactDiagonalization", "max_forks_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-22T18:59:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T18:59:11.000Z", "avg_line_length": 19.0495867769, "max_line_length": 76, "alphanum_fraction": 0.5479392625, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5090495887255877}}
{"text": "/**\n * \\file libs/numeric/ublasx/test/cond.cpp\n *\n * \\brief Test suite for the \\c cond operation.\n *\n * Copyright (c) 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//ATTENTION: test fails\n//TODO: fix it\n\n//#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/fwd.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n//#include <boost/numeric/ublas/symmetric.hpp>\n//#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublasx/operation/cond.hpp>\n#include <complex>\n#include <cmath>\n#include <cstddef>\n#include <limits>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace ublasx = boost::numeric::ublasx;\n\n\nstatic const double tol = 1.0e-5;\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_square_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Square Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) =  2; Well(0,1) = -1; Well(0,2) =  0;\n\tWell(1,0) = -1; Well(1,1) =  3; Well(1,2) = -1;\n\tWell(2,0) =  0; Well(2,1) = -1; Well(2,2) =  2;\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = 1; Ill(0,1) = 2; Ill(0,2) = 3;\n\tIll(1,0) = 4; Ill(1,1) = 5; Ill(1,2) = 6;\n\tIll(2,0) = 7; Ill(2,1) = 8; Ill(2,2) = 9;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 5;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_1(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = std::numeric_limits<result_type>::infinity();\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_1(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK( std::isinf(res) );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_square_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Square Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) =  2; Well(0,1) = -1; Well(0,2) =  0;\n\tWell(1,0) = -1; Well(1,1) =  3; Well(1,2) = -1;\n\tWell(2,0) =  0; Well(2,1) = -1; Well(2,2) =  2;\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = 1; Ill(0,1) = 2; Ill(0,2) = 3;\n\tIll(1,0) = 4; Ill(1,1) = 5; Ill(1,2) = 6;\n\tIll(2,0) = 7; Ill(2,1) = 8; Ill(2,2) = 9;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 5;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_1(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = std::numeric_limits<result_type>::infinity();\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_1(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK( std::isinf(res) );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_complex_square_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Square Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) = value_type( 2, 2); Well(0,1) = value_type(-1,-1); Well(0,2) = value_type( 0, 0);\n\tWell(1,0) = value_type(-1,-1); Well(1,1) = value_type( 3, 3); Well(1,2) = value_type(-1,-1);\n\tWell(2,0) = value_type( 0, 0); Well(2,1) = value_type(-1,-1); Well(2,2) = value_type( 2, 2);\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = value_type(1,10); Ill(0,1) = value_type(2,13); Ill(0,2) = value_type(3,16);\n\tIll(1,0) = value_type(4,11); Ill(1,1) = value_type(5,14); Ill(1,2) = value_type(6,17);\n\tIll(2,0) = value_type(7,12); Ill(2,1) = value_type(8,15); Ill(2,2) = value_type(9,18);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 5;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_1(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = std::numeric_limits<result_type>::infinity();\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_1(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK( std::isinf(res) );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_complex_square_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Square Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) = value_type( 2, 2); Well(0,1) = value_type(-1,-1); Well(0,2) = value_type( 0, 0);\n\tWell(1,0) = value_type(-1,-1); Well(1,1) = value_type( 3, 3); Well(1,2) = value_type(-1,-1);\n\tWell(2,0) = value_type( 0, 0); Well(2,1) = value_type(-1,-1); Well(2,2) = value_type( 2, 2);\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = value_type(1,10); Ill(0,1) = value_type(2,13); Ill(0,2) = value_type(3,16);\n\tIll(1,0) = value_type(4,11); Ill(1,1) = value_type(5,14); Ill(1,2) = value_type(6,17);\n\tIll(2,0) = value_type(7,12); Ill(2,1) = value_type(8,15); Ill(2,2) = value_type(9,18);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 5;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_1(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = std::numeric_limits<result_type>::infinity();\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_1(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK( std::isinf(res) );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_rectangular_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Rectangular Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type A(nr,nc);\n\tA(0,0) =  1; A(0,1) =  2; A(0,2) =  3;\n\tA(1,0) =  4; A(1,1) =  5; A(1,2) =  6;\n\tA(2,0) =  7; A(2,1) =  8; A(2,2) =  9;\n\tA(3,0) = 10; A(3,1) = 11; A(3,2) = 12;\n\n\tbool res;\n\n\t// Condition number for rectangular matrix only available with the 2-norm\n\tBOOST_UBLASX_DEBUG_TRACE(\"Matrix = \" << A);\n\ttry\n\t{\n\t\tublasx::cond_1(A);\n\t\tres = false;\n\t}\n\tcatch (...)\n\t{\n\t\tres = true;\n\t}\n\tBOOST_UBLASX_TEST_CHECK( res );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_rectangular_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Rectangular Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type A(nr,nc);\n\tA(0,0) =  1; A(0,1) =  2; A(0,2) =  3;\n\tA(1,0) =  4; A(1,1) =  5; A(1,2) =  6;\n\tA(2,0) =  7; A(2,1) =  8; A(2,2) =  9;\n\tA(3,0) = 10; A(3,1) = 11; A(3,2) = 12;\n\n\tbool res;\n\n\t// Condition number for rectangular matrix only available with the 2-norm\n\tBOOST_UBLASX_DEBUG_TRACE(\"Matrix = \" << A);\n\ttry\n\t{\n\t\tublasx::cond_1(A);\n\t\tres = false;\n\t}\n\tcatch (...)\n\t{\n\t\tres = true;\n\t}\n\tBOOST_UBLASX_TEST_CHECK( res );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_complex_rectangular_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Rectangular Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type A(nr,nc);\n\tA(0,0) = value_type( 1,13); A(0,1) = value_type( 2,17); A(0,2) = value_type( 3,21);\n\tA(1,0) = value_type( 4,14); A(1,1) = value_type( 5,18); A(1,2) = value_type( 6,22);\n\tA(2,0) = value_type( 7,15); A(2,1) = value_type( 8,19); A(2,2) = value_type( 9,23);\n\tA(3,0) = value_type(10,16); A(3,1) = value_type(11,20); A(3,2) = value_type(12,24);\n\n\tbool res;\n\n\t// Condition number for rectangular matrix only available with the 2-norm\n\tBOOST_UBLASX_DEBUG_TRACE(\"Matrix = \" << A);\n\ttry\n\t{\n\t\tublasx::cond_1(A);\n\t\tres = false;\n\t}\n\tcatch (...)\n\t{\n\t\tres = true;\n\t}\n\tBOOST_UBLASX_TEST_CHECK( res );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_complex_rectangular_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Rectangular Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type A(nr,nc);\n\tA(0,0) = value_type( 1,13); A(0,1) = value_type( 2,17); A(0,2) = value_type( 3,21);\n\tA(1,0) = value_type( 4,14); A(1,1) = value_type( 5,18); A(1,2) = value_type( 6,22);\n\tA(2,0) = value_type( 7,15); A(2,1) = value_type( 8,19); A(2,2) = value_type( 9,23);\n\tA(3,0) = value_type(10,16); A(3,1) = value_type(11,20); A(3,2) = value_type(12,24);\n\n\tbool res;\n\n\t// Condition number for rectangular matrix only available with the 2-norm\n\tBOOST_UBLASX_DEBUG_TRACE(\"Matrix = \" << A);\n\ttry\n\t{\n\t\tublasx::cond_1(A);\n\t\tres = false;\n\t}\n\tcatch (...)\n\t{\n\t\tres = true;\n\t}\n\tBOOST_UBLASX_TEST_CHECK( res );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_2_real_square_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 2-Norm - Real Square Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) =  2; Well(0,1) = -1; Well(0,2) =  0;\n\tWell(1,0) = -1; Well(1,1) =  3; Well(1,2) = -1;\n\tWell(2,0) =  0; Well(2,1) = -1; Well(2,2) =  2;\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = 1; Ill(0,1) = 2; Ill(0,2) = 3;\n\tIll(1,0) = 4; Ill(1,1) = 5; Ill(1,2) = 6;\n\tIll(2,0) = 7; Ill(2,1) = 8; Ill(2,2) = 9;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 4;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_2(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = 49026176493774648;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_2(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_2_real_square_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 2-Norm - Real Square Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) =  2; Well(0,1) = -1; Well(0,2) =  0;\n\tWell(1,0) = -1; Well(1,1) =  3; Well(1,2) = -1;\n\tWell(2,0) =  0; Well(2,1) = -1; Well(2,2) =  2;\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = 1; Ill(0,1) = 2; Ill(0,2) = 3;\n\tIll(1,0) = 4; Ill(1,1) = 5; Ill(1,2) = 6;\n\tIll(2,0) = 7; Ill(2,1) = 8; Ill(2,2) = 9;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 4;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_2(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = 49026176493774648;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_2(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_2_complex_square_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 2-Norm - Complex Square Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) = value_type( 2, 2); Well(0,1) = value_type(-1,-1); Well(0,2) = value_type( 0, 0);\n\tWell(1,0) = value_type(-1,-1); Well(1,1) = value_type( 3, 3); Well(1,2) = value_type(-1,-1);\n\tWell(2,0) = value_type( 0, 0); Well(2,1) = value_type(-1,-1); Well(2,2) = value_type( 2, 2);\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = value_type(1,10); Ill(0,1) = value_type(2,13); Ill(0,2) = value_type(3,16);\n\tIll(1,0) = value_type(4,11); Ill(1,1) = value_type(5,14); Ill(1,2) = value_type(6,17);\n\tIll(2,0) = value_type(7,12); Ill(2,1) = value_type(8,15); Ill(2,2) = value_type(9,18);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 4;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_2(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = 20994351988002824;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_2(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_2_complex_square_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 2-Norm - Complex Square Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) = value_type( 2, 2); Well(0,1) = value_type(-1,-1); Well(0,2) = value_type( 0, 0);\n\tWell(1,0) = value_type(-1,-1); Well(1,1) = value_type( 3, 3); Well(1,2) = value_type(-1,-1);\n\tWell(2,0) = value_type( 0, 0); Well(2,1) = value_type(-1,-1); Well(2,2) = value_type( 2, 2);\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = value_type(1,10); Ill(0,1) = value_type(2,13); Ill(0,2) = value_type(3,16);\n\tIll(1,0) = value_type(4,11); Ill(1,1) = value_type(5,14); Ill(1,2) = value_type(6,17);\n\tIll(2,0) = value_type(7,12); Ill(2,1) = value_type(8,15); Ill(2,2) = value_type(9,18);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 4;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_2(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = 20994351988002824;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_2(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_2_real_rectangular_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 2-Norm - Real Rectangular Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type Well(nr,nc);\n\tWell(0,0) =  2; Well(0,1) = -1; Well(0,2) =  0;\n\tWell(1,0) = -1; Well(1,1) =  3; Well(1,2) = -1;\n\tWell(2,0) =  0; Well(2,1) = -1; Well(2,2) =  2;\n\tWell(3,0) =  1; Well(3,1) =  2; Well(3,2) = -1;\n\n\tmatrix_type Ill(nr,nc);\n\tIll(0,0) =  1; Ill(0,1) =  2; Ill(0,2) =  3;\n\tIll(1,0) =  4; Ill(1,1) =  5; Ill(1,2) =  6;\n\tIll(2,0) =  7; Ill(2,1) =  8; Ill(2,2) =  9;\n\tIll(3,0) = 10; Ill(3,1) = 11; Ill(3,2) = 12;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 3.41990480101429;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_2(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = 14259982749169812;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_2(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_2_real_rectangular_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 2-Norm - Real Rectangular Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type Well(nr,nc);\n\tWell(0,0) =  2; Well(0,1) = -1; Well(0,2) =  0;\n\tWell(1,0) = -1; Well(1,1) =  3; Well(1,2) = -1;\n\tWell(2,0) =  0; Well(2,1) = -1; Well(2,2) =  2;\n\tWell(3,0) =  1; Well(3,1) =  2; Well(3,2) = -1;\n\n\tmatrix_type Ill(nr,nc);\n\tIll(0,0) =  1; Ill(0,1) =  2; Ill(0,2) =  3;\n\tIll(1,0) =  4; Ill(1,1) =  5; Ill(1,2) =  6;\n\tIll(2,0) =  7; Ill(2,1) =  8; Ill(2,2) =  9;\n\tIll(3,0) = 10; Ill(3,1) = 11; Ill(3,2) = 12;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 3.41990480101429;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_2(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = 14259982749169812;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_2(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_2_complex_rectangular_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 2-Norm - Complex Rectangular Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type Well(nr,nc);\n\tWell(0,0) = value_type( 2, 2); Well(0,1) = value_type(-1,-1); Well(0,2) = value_type( 0, 0);\n\tWell(1,0) = value_type(-1,-1); Well(1,1) = value_type( 3, 3); Well(1,2) = value_type(-1,-1);\n\tWell(2,0) = value_type( 0, 0); Well(2,1) = value_type(-1,-1); Well(2,2) = value_type( 2, 2);\n\tWell(3,0) = value_type( 1, 0); Well(3,1) = value_type( 2,-1); Well(3,2) = value_type(-1, 2);\n\n\tmatrix_type Ill(nr,nc);\n\tIll(0,0) = value_type( 1,10); Ill(0,1) = value_type( 2,14); Ill(0,2) = value_type( 3,18);\n\tIll(1,0) = value_type( 4,11); Ill(1,1) = value_type( 5,15); Ill(1,2) = value_type( 6,19);\n\tIll(2,0) = value_type( 7,12); Ill(2,1) = value_type( 8,16); Ill(2,2) = value_type( 9,20);\n\tIll(3,0) = value_type(10,13); Ill(3,1) = value_type(11,17); Ill(3,2) = value_type(12,21);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 3.67416702058981;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_2(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = 37955084752566112;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_2(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_2_complex_rectangular_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 2-Norm - Complex Rectangular Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type Well(nr,nc);\n\tWell(0,0) = value_type( 2, 2); Well(0,1) = value_type(-1,-1); Well(0,2) = value_type( 0, 0);\n\tWell(1,0) = value_type(-1,-1); Well(1,1) = value_type( 3, 3); Well(1,2) = value_type(-1,-1);\n\tWell(2,0) = value_type( 0, 0); Well(2,1) = value_type(-1,-1); Well(2,2) = value_type( 2, 2);\n\tWell(3,0) = value_type( 1, 0); Well(3,1) = value_type( 2,-1); Well(3,2) = value_type(-1, 2);\n\n\tmatrix_type Ill(nr,nc);\n\tIll(0,0) = value_type( 1,10); Ill(0,1) = value_type( 2,14); Ill(0,2) = value_type( 3,18);\n\tIll(1,0) = value_type( 4,11); Ill(1,1) = value_type( 5,15); Ill(1,2) = value_type( 6,19);\n\tIll(2,0) = value_type( 7,12); Ill(2,1) = value_type( 8,16); Ill(2,2) = value_type( 9,20);\n\tIll(3,0) = value_type(10,13); Ill(3,1) = value_type(11,17); Ill(3,2) = value_type(12,21);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 3.67416702058981;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_2(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = 37955084752566112;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_2(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_inf_real_square_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: inf-Norm - Real Square Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) =  2; Well(0,1) = -1; Well(0,2) =  0;\n\tWell(1,0) = -1; Well(1,1) =  3; Well(1,2) = -1;\n\tWell(2,0) =  0; Well(2,1) = -1; Well(2,2) =  2;\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = 1; Ill(0,1) = 2; Ill(0,2) = 3;\n\tIll(1,0) = 4; Ill(1,1) = 5; Ill(1,2) = 6;\n\tIll(2,0) = 7; Ill(2,1) = 8; Ill(2,2) = 9;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 5;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_inf(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = std::numeric_limits<result_type>::infinity();\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_inf(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK( std::isinf(res) );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_inf_real_square_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: inf-Norm - Real Square Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) =  2; Well(0,1) = -1; Well(0,2) =  0;\n\tWell(1,0) = -1; Well(1,1) =  3; Well(1,2) = -1;\n\tWell(2,0) =  0; Well(2,1) = -1; Well(2,2) =  2;\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = 1; Ill(0,1) = 2; Ill(0,2) = 3;\n\tIll(1,0) = 4; Ill(1,1) = 5; Ill(1,2) = 6;\n\tIll(2,0) = 7; Ill(2,1) = 8; Ill(2,2) = 9;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 5;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_inf(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = std::numeric_limits<result_type>::infinity();\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_inf(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK( std::isinf(res) );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_inf_complex_square_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Square Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) = value_type( 2, 2); Well(0,1) = value_type(-1,-1); Well(0,2) = value_type( 0, 0);\n\tWell(1,0) = value_type(-1,-1); Well(1,1) = value_type( 3, 3); Well(1,2) = value_type(-1,-1);\n\tWell(2,0) = value_type( 0, 0); Well(2,1) = value_type(-1,-1); Well(2,2) = value_type( 2, 2);\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = value_type(1,10); Ill(0,1) = value_type(2,13); Ill(0,2) = value_type(3,16);\n\tIll(1,0) = value_type(4,11); Ill(1,1) = value_type(5,14); Ill(1,2) = value_type(6,17);\n\tIll(2,0) = value_type(7,12); Ill(2,1) = value_type(8,15); Ill(2,2) = value_type(9,18);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 5;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_inf(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = std::numeric_limits<result_type>::infinity();\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_inf(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK( std::isinf(res) );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_inf_complex_square_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Square Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) = value_type( 2, 2); Well(0,1) = value_type(-1,-1); Well(0,2) = value_type( 0, 0);\n\tWell(1,0) = value_type(-1,-1); Well(1,1) = value_type( 3, 3); Well(1,2) = value_type(-1,-1);\n\tWell(2,0) = value_type( 0, 0); Well(2,1) = value_type(-1,-1); Well(2,2) = value_type( 2, 2);\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = value_type(1,10); Ill(0,1) = value_type(2,13); Ill(0,2) = value_type(3,16);\n\tIll(1,0) = value_type(4,11); Ill(1,1) = value_type(5,14); Ill(1,2) = value_type(6,17);\n\tIll(2,0) = value_type(7,12); Ill(2,1) = value_type(8,15); Ill(2,2) = value_type(9,18);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 5;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_inf(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = std::numeric_limits<result_type>::infinity();\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\tres = ublasx::cond_inf(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK( std::isinf(res) );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_inf_real_rectangular_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Rectangular Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type A(nr,nc);\n\tA(0,0) =  1; A(0,1) =  2; A(0,2) =  3;\n\tA(1,0) =  4; A(1,1) =  5; A(1,2) =  6;\n\tA(2,0) =  7; A(2,1) =  8; A(2,2) =  9;\n\tA(3,0) = 10; A(3,1) = 11; A(3,2) = 12;\n\n\tbool res;\n\n\t// Condition number for rectangular matrix only available with the 2-norm\n\tBOOST_UBLASX_DEBUG_TRACE(\"Matrix = \" << A);\n\ttry\n\t{\n\t\tublasx::cond_inf(A);\n\t\tres = false;\n\t}\n\tcatch (...)\n\t{\n\t\tres = true;\n\t}\n\tBOOST_UBLASX_TEST_CHECK( res );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_inf_real_rectangular_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Rectangular Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type A(nr,nc);\n\tA(0,0) =  1; A(0,1) =  2; A(0,2) =  3;\n\tA(1,0) =  4; A(1,1) =  5; A(1,2) =  6;\n\tA(2,0) =  7; A(2,1) =  8; A(2,2) =  9;\n\tA(3,0) = 10; A(3,1) = 11; A(3,2) = 12;\n\n\tbool res;\n\n\t// Condition number for rectangular matrix only available with the 2-norm\n\tBOOST_UBLASX_DEBUG_TRACE(\"Matrix = \" << A);\n\ttry\n\t{\n\t\tublasx::cond_inf(A);\n\t\tres = false;\n\t}\n\tcatch (...)\n\t{\n\t\tres = true;\n\t}\n\tBOOST_UBLASX_TEST_CHECK( res );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_inf_complex_rectangular_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Rectangular Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type A(nr,nc);\n\tA(0,0) = value_type( 1,13); A(0,1) = value_type( 2,17); A(0,2) = value_type( 3,21);\n\tA(1,0) = value_type( 4,14); A(1,1) = value_type( 5,18); A(1,2) = value_type( 6,22);\n\tA(2,0) = value_type( 7,15); A(2,1) = value_type( 8,19); A(2,2) = value_type( 9,23);\n\tA(3,0) = value_type(10,16); A(3,1) = value_type(11,20); A(3,2) = value_type(12,24);\n\n\tbool res;\n\n\t// Condition number for rectangular matrix only available with the 2-norm\n\tBOOST_UBLASX_DEBUG_TRACE(\"Matrix = \" << A);\n\ttry\n\t{\n\t\tublasx::cond_inf(A);\n\t\tres = false;\n\t}\n\tcatch (...)\n\t{\n\t\tres = true;\n\t}\n\tBOOST_UBLASX_TEST_CHECK( res );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_inf_complex_rectangular_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Rectangular Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type A(nr,nc);\n\tA(0,0) = value_type( 1,13); A(0,1) = value_type( 2,17); A(0,2) = value_type( 3,21);\n\tA(1,0) = value_type( 4,14); A(1,1) = value_type( 5,18); A(1,2) = value_type( 6,22);\n\tA(2,0) = value_type( 7,15); A(2,1) = value_type( 8,19); A(2,2) = value_type( 9,23);\n\tA(3,0) = value_type(10,16); A(3,1) = value_type(11,20); A(3,2) = value_type(12,24);\n\n\tbool res;\n\n\t// Condition number for rectangular matrix only available with the 2-norm\n\tBOOST_UBLASX_DEBUG_TRACE(\"Matrix = \" << A);\n\ttry\n\t{\n\t\tublasx::cond_inf(A);\n\t\tres = false;\n\t}\n\tcatch (...)\n\t{\n\t\tres = true;\n\t}\n\tBOOST_UBLASX_TEST_CHECK( res );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_frobenius_real_square_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: frobenius-Norm - Real Square Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) =  2; Well(0,1) = -1; Well(0,2) =  0;\n\tWell(1,0) = -1; Well(1,1) =  3; Well(1,2) = -1;\n\tWell(2,0) =  0; Well(2,1) = -1; Well(2,2) =  2;\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = 1; Ill(0,1) = 2; Ill(0,2) = 3;\n\tIll(1,0) = 4; Ill(1,1) = 5; Ill(1,2) = 6;\n\tIll(2,0) = 7; Ill(2,1) = 8; Ill(2,2) = 9;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 5.25;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_frobenius(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = std::numeric_limits<result_type>::infinity();\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\t//res = 456177073660509760;\n\tres = ublasx::cond_frobenius(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK( std::isinf(res) );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_frobenius_real_square_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: frobenius-Norm - Real Square Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) =  2; Well(0,1) = -1; Well(0,2) =  0;\n\tWell(1,0) = -1; Well(1,1) =  3; Well(1,2) = -1;\n\tWell(2,0) =  0; Well(2,1) = -1; Well(2,2) =  2;\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = 1; Ill(0,1) = 2; Ill(0,2) = 3;\n\tIll(1,0) = 4; Ill(1,1) = 5; Ill(1,2) = 6;\n\tIll(2,0) = 7; Ill(2,1) = 8; Ill(2,2) = 9;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 5.25;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_frobenius(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = std::numeric_limits<result_type>::infinity();\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\t//res = 456177073660509760;\n\tres = ublasx::cond_frobenius(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK( std::isinf(res) );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_frobenius_complex_square_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: frobenius-norm - Complex Square Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) = value_type( 2, 2); Well(0,1) = value_type(-1,-1); Well(0,2) = value_type( 0, 0);\n\tWell(1,0) = value_type(-1,-1); Well(1,1) = value_type( 3, 3); Well(1,2) = value_type(-1,-1);\n\tWell(2,0) = value_type( 0, 0); Well(2,1) = value_type(-1,-1); Well(2,2) = value_type( 2, 2);\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = value_type(1,10); Ill(0,1) = value_type(2,13); Ill(0,2) = value_type(3,16);\n\tIll(1,0) = value_type(4,11); Ill(1,1) = value_type(5,14); Ill(1,2) = value_type(6,17);\n\tIll(2,0) = value_type(7,12); Ill(2,1) = value_type(8,15); Ill(2,2) = value_type(9,18);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 5.25;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_frobenius(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = std::numeric_limits<result_type>::infinity();\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\t//res = 54418634865903768;\n\tres = ublasx::cond_frobenius(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK( std::isinf(res) );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_frobenius_complex_square_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: frobenius-Norm - Complex Square Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef real_type result_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type Well(n,n);\n\tWell(0,0) = value_type( 2, 2); Well(0,1) = value_type(-1,-1); Well(0,2) = value_type( 0, 0);\n\tWell(1,0) = value_type(-1,-1); Well(1,1) = value_type( 3, 3); Well(1,2) = value_type(-1,-1);\n\tWell(2,0) = value_type( 0, 0); Well(2,1) = value_type(-1,-1); Well(2,2) = value_type( 2, 2);\n\n\tmatrix_type Ill(n,n);\n\tIll(0,0) = value_type(1,10); Ill(0,1) = value_type(2,13); Ill(0,2) = value_type(3,16);\n\tIll(1,0) = value_type(4,11); Ill(1,1) = value_type(5,14); Ill(1,2) = value_type(6,17);\n\tIll(2,0) = value_type(7,12); Ill(2,1) = value_type(8,15); Ill(2,2) = value_type(9,18);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\t// Well-conditioned matrix\n\texpect_res = 5.25;\n\tBOOST_UBLASX_DEBUG_TRACE(\"Well-conditioned Matrix = \" << Well);\n\tres = ublasx::cond_frobenius(Well);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, tol );\n\n\t// Ill-conditioned matrix\n\texpect_res = std::numeric_limits<result_type>::infinity();\n\tBOOST_UBLASX_DEBUG_TRACE(\"Ill-conditioned Matrix = \" << Ill);\n\t//res = 54418634865903768;\n\tres = ublasx::cond_frobenius(Ill);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\tBOOST_UBLASX_TEST_CHECK( std::isinf(res) );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_frobenius_real_rectangular_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: frobenius-Norm - Real Rectangular Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type A(nr,nc);\n\tA(0,0) =  1; A(0,1) =  2; A(0,2) =  3;\n\tA(1,0) =  4; A(1,1) =  5; A(1,2) =  6;\n\tA(2,0) =  7; A(2,1) =  8; A(2,2) =  9;\n\tA(3,0) = 10; A(3,1) = 11; A(3,2) = 12;\n\n\tbool res;\n\n\t// Condition number for rectangular matrix only available with the 2-norm\n\tBOOST_UBLASX_DEBUG_TRACE(\"Matrix = \" << A);\n\ttry\n\t{\n\t\tublasx::cond_frobenius(A);\n\t\tres = false;\n\t}\n\tcatch (...)\n\t{\n\t\tres = true;\n\t}\n\tBOOST_UBLASX_TEST_CHECK( res );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_frobenius_real_rectangular_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: frobenius-Norm - Real Rectangular Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef real_type value_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type A(nr,nc);\n\tA(0,0) =  1; A(0,1) =  2; A(0,2) =  3;\n\tA(1,0) =  4; A(1,1) =  5; A(1,2) =  6;\n\tA(2,0) =  7; A(2,1) =  8; A(2,2) =  9;\n\tA(3,0) = 10; A(3,1) = 11; A(3,2) = 12;\n\n\tbool res;\n\n\t// Condition number for rectangular matrix only available with the 2-norm\n\tBOOST_UBLASX_DEBUG_TRACE(\"Matrix = \" << A);\n\ttry\n\t{\n\t\tublasx::cond_frobenius(A);\n\t\tres = false;\n\t}\n\tcatch (...)\n\t{\n\t\tres = true;\n\t}\n\tBOOST_UBLASX_TEST_CHECK( res );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_frobenius_complex_rectangular_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: frobenius-Norm - Complex Rectangular Dense Matrix - Column Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type A(nr,nc);\n\tA(0,0) = value_type( 1,13); A(0,1) = value_type( 2,17); A(0,2) = value_type( 3,21);\n\tA(1,0) = value_type( 4,14); A(1,1) = value_type( 5,18); A(1,2) = value_type( 6,22);\n\tA(2,0) = value_type( 7,15); A(2,1) = value_type( 8,19); A(2,2) = value_type( 9,23);\n\tA(3,0) = value_type(10,16); A(3,1) = value_type(11,20); A(3,2) = value_type(12,24);\n\n\tbool res;\n\n\t// Condition number for rectangular matrix only available with the 2-norm\n\tBOOST_UBLASX_DEBUG_TRACE(\"Matrix = \" << A);\n\ttry\n\t{\n\t\tublasx::cond_frobenius(A);\n\t\tres = false;\n\t}\n\tcatch (...)\n\t{\n\t\tres = true;\n\t}\n\tBOOST_UBLASX_TEST_CHECK( res );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_frobenius_complex_rectangular_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: frobenius-Norm - Complex Rectangular Dense Matrix - Row Major\");\n\n\ttypedef double real_type;\n\ttypedef std::complex<real_type> value_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t nr = 4;\n\tconst std::size_t nc = 3;\n\n\tmatrix_type A(nr,nc);\n\tA(0,0) = value_type( 1,13); A(0,1) = value_type( 2,17); A(0,2) = value_type( 3,21);\n\tA(1,0) = value_type( 4,14); A(1,1) = value_type( 5,18); A(1,2) = value_type( 6,22);\n\tA(2,0) = value_type( 7,15); A(2,1) = value_type( 8,19); A(2,2) = value_type( 9,23);\n\tA(3,0) = value_type(10,16); A(3,1) = value_type(11,20); A(3,2) = value_type(12,24);\n\n\tbool res;\n\n\t// Condition number for rectangular matrix only available with the 2-norm\n\tBOOST_UBLASX_DEBUG_TRACE(\"Matrix = \" << A);\n\ttry\n\t{\n\t\tublasx::cond_frobenius(A);\n\t\tres = false;\n\t}\n\tcatch (...)\n\t{\n\t\tres = true;\n\t}\n\tBOOST_UBLASX_TEST_CHECK( res );\n}\n\n\nint main()\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Suite: 'cond' operation\");\n\n\tBOOST_UBLASX_TEST_BEGIN();\n\n\tBOOST_UBLASX_TEST_DO( norm_1_real_square_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_square_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_complex_square_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_complex_square_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_rectangular_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_rectangular_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_complex_rectangular_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_complex_rectangular_dense_matrix_row_major );\n\n\tBOOST_UBLASX_TEST_DO( norm_2_real_square_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_2_real_square_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_2_complex_square_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_2_complex_square_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_2_real_rectangular_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_2_real_rectangular_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_2_complex_rectangular_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_2_complex_rectangular_dense_matrix_row_major );\n\n\tBOOST_UBLASX_TEST_DO( norm_inf_real_square_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_inf_real_square_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_inf_complex_square_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_inf_complex_square_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_inf_real_rectangular_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_inf_real_rectangular_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_inf_complex_rectangular_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_inf_complex_rectangular_dense_matrix_row_major );\n\n\tBOOST_UBLASX_TEST_DO( norm_frobenius_real_square_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_frobenius_real_square_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_frobenius_complex_square_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_frobenius_complex_square_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_frobenius_real_rectangular_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_frobenius_real_rectangular_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_frobenius_complex_rectangular_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_frobenius_complex_rectangular_dense_matrix_row_major );\n\n\tBOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "5a31da425e208ba46fd9bc31088904f94f53b5bd", "size": 42597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/cond.cpp", "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": "libs/numeric/ublasx/test/cond.cpp", "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": "libs/numeric/ublasx/test/cond.cpp", "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": 32.6163859112, "max_line_length": 105, "alphanum_fraction": 0.6962227387, "num_tokens": 15266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5090495887255877}}
{"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_EXPM1_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_EXPM1_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-exponential\n    Function object implementing expm1 capabilities\n\n    exponential function minus one:\\f$e^{x}-1\\f$\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = expm1(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = minusone(exp(x));\n    @endcode\n\n    @par Notes:\n\n    - result is accurate even for x of small modulus\n\n    @par Decorators\n\n    std_ for floating entries\n\n    @see exp\n\n  **/\n  const boost::dispatch::functor<tag::expm1_> expm1 = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/expm1.hpp>\n#include <boost/simd/function/simd/expm1.hpp>\n\n#endif\n", "meta": {"hexsha": "bbd21b1f8f9155e659716d2b7253f24fd5fc5ff1", "size": 1216, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/expm1.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/expm1.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/expm1.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": 20.6101694915, "max_line_length": 100, "alphanum_fraction": 0.578125, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5090495887255877}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// numbers.cpp\n//\n//  Copyright 2008 David Jenkins. 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#if defined(_MSC_VER)\n//disbale warning C4996: 'std::xxx' was declared deprecated\n# pragma warning(disable:4996)\n#endif\n\n#include <iostream>\n#include <string>\n#include <map>\n#include <boost/assign/list_of.hpp> // for 'map_list_of()'\n#include <boost/xpressive/xpressive.hpp>\n#include <boost/xpressive/regex_actions.hpp>\n\n///////////////////////////////////////////////////////////////////////////////\n// Match all named numbers in a string and return their integer values\n//\n// For example, given the input string:\n//      \"one two sixty three thousand ninety five eleven\"\n// the program will output:\n//      \"one = 1\"\n//      \"two = 2\"\n//      \"sixty three thousand ninety five = 63095\"\n//      \"eleven = 11\"\n\nvoid example1()\n{\n    using namespace boost::xpressive;\n    using namespace boost::assign;\n\n    // initialize the maps for named numbers\n    std::map< std::string, int > ones_map =\n        map_list_of(\"one\",1)(\"two\",2)(\"three\",3)(\"four\",4)(\"five\",5)\n        (\"six\",6)(\"seven\",7)(\"eight\",8)(\"nine\",9);\n\n    std::map< std::string, int > teens_map =\n        map_list_of(\"ten\",10)(\"eleven\",11)(\"twelve\",12)(\"thirteen\",13)\n        (\"fourteen\",14)(\"fifteen\",15)(\"sixteen\",16)(\"seventeen\",17)\n        (\"eighteen\",18)(\"nineteen\",19);\n\n    std::map< std::string, int > tens_map =\n        map_list_of(\"twenty\",20)(\"thirty\",30)(\"fourty\",40)\n        (\"fifty\",50)(\"sixty\",60)(\"seventy\",70)(\"eighty\",80)(\"ninety\",90);\n\n    std::map< std::string, int > specials_map =\n        map_list_of(\"zero\",0)(\"dozen\",12)(\"score\",20);\n\n    // n is the integer result\n    local<long> n(0);\n    // temp stores intermediate values\n    local<long> temp(0);\n\n    // initialize the regular expressions for named numbers\n    sregex tens_rx =\n        // use skip directive to skip whitespace between words\n        skip(_s)\n        (\n            ( a3 = teens_map )\n            |\n            ( a2 = tens_map ) >> !( a1 = ones_map )\n            |\n            ( a1 = ones_map )\n        )\n        [ n += (a3|0) + (a2|0) + (a1|0) ];\n\n    sregex hundreds_rx =\n        skip(_s)\n        (\n            tens_rx >>\n            !(\n                as_xpr(\"hundred\")  [ n *= 100 ]\n                >> !tens_rx\n             )\n        )\n        ;\n\n    sregex specials_rx =    // regex for special number names like dozen\n        skip(_s)\n        (\n            // Note: this uses two attribues, a1 and a2, and it uses\n            // a default attribute value of 1 for a1.\n            ( !( a1 = ones_map ) >> ( a2 = specials_map ) )\n                [ n = (a1|1) * a2 ]\n            >> !( \"and\" >> tens_rx )\n        )\n        ;\n\n    sregex number_rx =\n        bow\n        >>\n        skip(_s|punct)\n        (\n            specials_rx // special numbers\n            |\n            (   // normal numbers\n                !( hundreds_rx >> \"million\" ) [ temp += n * 1000000, n = 0 ]\n                >>\n                !( hundreds_rx >> \"thousand\" ) [ temp += n * 1000, n = 0 ]\n                >>\n                !hundreds_rx\n            )\n            [n += temp, temp = 0 ]\n        );\n\n    // this is the input string\n    std::string str( \"one two three eighteen twenty two \"\n        \"nine hundred ninety nine twelve \"\n        \"eight hundred sixty three thousand ninety five \"\n        \"sixty five hundred ten \"\n        \"two million eight hundred sixty three thousand ninety five \"\n        \"zero sixty five hundred thousand \"\n        \"extra stuff \"\n        \"two dozen \"\n        \"four score and seven\");\n\n    // the MATCHING results of iterating through the string are:\n    //      one  = 1\n    //      two  = 2\n    //      three  = 3\n    //      eighteen  = 18\n    //      twenty two  = 22\n    //      nine hundred ninety nine  = 999\n    //      twelve  = 12\n    //      eight hundred sixty three thousand ninety five  = 863095\n    //      sixty five hundred ten  = 6510\n    //      two million eight hundred sixty three thousand ninety five  = 2863095\n    //      zero = 0\n    //      sixty five hundred thousand = 6500000\n    //      two dozen = 24\n    //      four score and seven = 87\n    sregex_token_iterator cur( str.begin(), str.end(), number_rx );\n    sregex_token_iterator end;\n\n    for( ; cur != end; ++cur )\n    {\n        if ((*cur).length() > 0)\n            std::cout << *cur << \" = \" << n.get() << '\\n';\n        n.get() = 0;\n    }\n    std::cout << '\\n';\n    // the NON-MATCHING results of iterating through the string are:\n    //      extra = unmatched\n    //      stuff = unmatched\n    sregex_token_iterator cur2( str.begin(), str.end(), number_rx, -1 );\n    for( ; cur2 != end; ++cur2 )\n    {\n        if ((*cur2).length() > 0)\n            std::cout << *cur2 << \" = unmatched\" << '\\n';\n    }\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// main\nint main()\n{\n    std::cout << \"\\n\\nExample 1:\\n\\n\";\n    example1();\n\n    std::cout << \"\\n\\n\" << std::flush;\n\n    return 0;\n}\n", "meta": {"hexsha": "4e591bbbe9267fb049022d7c18a1eb2df8fe0c56", "size": 5156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/xpressive/example/numbers.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/xpressive/example/numbers.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/xpressive/example/numbers.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": 30.6904761905, "max_line_length": 81, "alphanum_fraction": 0.5015515904, "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5090495819684828}}
{"text": "#include \"GaussianMixture.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <fstream>\n#include <iostream>\n#include <cmath>\n\n#include \"Util.h\"\n\nnamespace ark {\n    void GaussianMixture::load(const std::string & path)\n    {\n        std::ifstream ifs(path);\n        if (!ifs) {\n            std::cerr << \"Warning: pose prior file at \" << path << \" does not exist or cannot be read\\n\";\n            nComps = -1;\n            return;\n        }\n        ifs >> nComps >> nDims;\n\n        // compute constants\n        double sqrt_2_pi_n = std::pow(2 * M_PI, nDims * 0.5 );\n        double log_sqrt_2_pi_n = nDims * 0.5 * std::log(2 * M_PI);\n        weight.resize(nComps);\n        consts.resize(nComps);\n        consts_log.resize(nComps);\n        for (int i = 0; i < nComps; ++i) {\n            // load weights\n            ifs >> weight[i];\n            consts_log[i] = log(weight[i]) - log_sqrt_2_pi_n;\n            consts[i] = weight[i] / sqrt_2_pi_n;\n        }\n\n        mean.resize(nComps, nDims);\n        for (int i = 0; i < nComps; ++i) {\n            for (int j = 0; j < nDims; ++j) {\n                // load mean vectors\n                ifs >> mean(i, j);\n            }\n        }\n\n        /** Cholesky decomposition */\n        typedef Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>> Cholesky;\n\n        cov.resize(nComps);\n        cov_cho.resize(nComps);\n        prec_cho.resize(nComps);\n        double minDet = std::numeric_limits<double>::max();\n        for (int i = 0; i < nComps; ++i) {\n            auto & m = cov[i];\n            m.resize(nDims, nDims);\n            for (int j = 0; j < nDims; ++j) {\n                for (int k = 0; k < nDims; ++k) {\n                    // load covariance matrices\n                    ifs >> m(j, k);\n                }\n            }\n            Cholesky chol(cov[i]);\n            if (chol.info() != Eigen::Success) throw \"Decomposition failed!\";\n            cov_cho[i] = chol.matrixL();\n            Cholesky chol_prec(cov[i].inverse());\n            prec_cho[i] = chol_prec.matrixL();\n            double det = cov_cho[i].determinant();\n            minDet = std::min(det, minDet);\n\n            // update constants\n            consts[i] /= det;\n            consts_log[i] -= log(det);\n        }\n\n        for (int i = 0; i < nComps; ++i) {\n            // normalize constants\n            consts[i] *= minDet;\n            consts_log[i] += log(minDet);\n        }\n    }\n\n    int GaussianMixture::numComponents() const {\n        return nComps;\n    };\n\n    /** Compute PDF at 'input' */\n    double GaussianMixture::pdf(const Eigen::VectorXd & x) const {\n        double prob(0.0);\n        typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Mattype;\n        for (int i = 0; i < nComps; ++i) {\n            Eigen::TriangularView<Eigen::MatrixXd, Eigen::Lower> L(prec_cho[i]);\n            auto residual = (L * (x - mean.row(i).transpose()));\n            prob += consts[i] * std::exp(-0.5 * residual.squaredNorm());\n        }\n        return prob;\n    }\n\n    Eigen::VectorXd GaussianMixture::residual(const Eigen::VectorXd & x, int* comp_idx) const {\n        double bestProb = std::numeric_limits<double>::max();\n        Eigen::VectorXd ans;\n        for (int i = 0; i < nComps; ++i) {\n            Eigen::TriangularView<Eigen::MatrixXd, Eigen::Lower> L(prec_cho[i]);\n            Eigen::VectorXd residual(nDims + 1);\n            residual[nDims] = 0.;\n            residual.head(nDims) = L.transpose() * (x - mean.row(i).transpose()) * sqrt(0.5);\n            double p = residual.squaredNorm() - consts_log[i];\n            if (p < bestProb) {\n                bestProb = p;\n                residual[nDims] = sqrt(-consts_log[i]);\n                ans = residual;\n                if (comp_idx != nullptr) {\n                    *comp_idx = i;\n                }\n            }\n        }\n        return ans;\n    }\n\n    Eigen::VectorXd GaussianMixture::sample() const {\n        // Pick random GMM component\n        double randf = random_util::uniform(0.0f, 1.0f);\n        int component;\n        for (size_t i = 0 ; i < nComps; ++i) {\n            randf -= weight[i];\n            if (randf <= 0) component = i;\n        }\n        Eigen::VectorXd r(nDims);\n        // Sample from Gaussian\n        for (int i = 0; i < nDims; ++i) {\n            r(i) = random_util::randn();\n        }\n        r *= cov_cho[component];\n        r += mean.row(component);\n        return r;\n    }\n\n}  // namespace ark\n", "meta": {"hexsha": "226e139c6588adc277ed89ae592672693d03451c", "size": 4421, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GaussianMixture.cpp", "max_stars_repo_name": "jyuatsfl/avatar", "max_stars_repo_head_hexsha": "8bbb5d72fda0857e04d0c76329f32162f6d98a92", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2020-06-10T09:47:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T01:41:28.000Z", "max_issues_repo_path": "GaussianMixture.cpp", "max_issues_repo_name": "jyuatsfl/avatar", "max_issues_repo_head_hexsha": "8bbb5d72fda0857e04d0c76329f32162f6d98a92", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-07-08T03:40:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T12:24:33.000Z", "max_forks_repo_path": "GaussianMixture.cpp", "max_forks_repo_name": "jyuatsfl/avatar", "max_forks_repo_head_hexsha": "8bbb5d72fda0857e04d0c76329f32162f6d98a92", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-06-10T09:47:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T09:54:46.000Z", "avg_line_length": 32.7481481481, "max_line_length": 105, "alphanum_fraction": 0.4949106537, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5090495819684827}}
{"text": "#ifndef CWT1D_WAVELETS\n#define CWT1D_WAVELETS\n#include \"cwt1d.hpp\"\n#include <boost/math/special_functions/gamma.hpp>\n\nnamespace cwt1d\n{\n  template <typename T>\n  class dog\n    :public wavelet_func<T>\n  {\n  private:\n    int m;\n    T norm;\n    T coi_factor;\n    bool coi_calculated;\n  public:\n    dog()\n      :m(2),coi_calculated(false)\n    {\n      norm=boost::math::tgamma(m+1/2.);\n    }\n    \n    dog(int m1)\n      :m(m1),coi_calculated(false)\n    {\n      norm=boost::math::tgamma(m+1/2.);\n    }\n    \n    T do_cone_of_influence_factor()const\n    {\n      if(!coi_calculated)\n\t{\n\t  blitz::Array<T,1> signal(1024);\n\t  signal=0;\n\t  signal(signal.extent(0)/2)=1;\n\t  blitz::Array<T,1> scales(1);\n\t  scales(0)=1;\n\t  blitz::Array<std::complex<T>,2> signal_cwt(cwt(signal,scales,*this));\n\t  int max_idx=0;\n\t  for(int i=0;i<signal.extent(0)/2;++i)\n\t    {\n\t      if(abs(signal_cwt(0,i))>abs(signal_cwt(0,signal.extent(0)/2))/5)\n\t\t{\n\t\t  max_idx=i;\n\t\t  break;\n\t\t}\n\t    }\n\t  const_cast<T&>(coi_factor)=signal.extent(0)/2-max_idx;\n\t  const_cast<bool&>(coi_calculated)=true;\n\t}\n      return coi_factor*.85;\n    }\n    \n  private:\n    std::complex<T> do_wavelet_f(T w,T s)const\n    {\n      const T ws=w*s;\n      const T pi=4*std::atan(1);\n      return -pow(std::complex<T>(0,1),T(m))*pow(ws,T(m))*exp(-(ws*ws)/2)/norm;\n    }\n  };\n  \n  template <typename T>\n  class morlet\n    :public wavelet_func<T>\n  {\n  private:\n    T omega_0;\n    T coi_factor;\n    bool coi_calculated;\n  public:\n    morlet()\n      :omega_0(1),coi_calculated(false)\n    {}\n    \n    morlet(T w1)\n      :omega_0(w1),coi_calculated(false)\n    {}\n\n    T do_cone_of_influence_factor()const\n    {\n      if(!coi_calculated)\n\t{\n\t  blitz::Array<T,1> signal(1024);\n\t  signal=0;\n\t  signal(signal.extent(0)/2)=1;\n\t  blitz::Array<T,1> scales(1);\n\t  scales(0)=8;\n\t  blitz::Array<std::complex<T>,2> signal_cwt(cwt(signal,scales,*this));\n\t  int max_idx=0;\n\t  for(int i=0;i<signal.extent(0)/2;++i)\n\t    {\n\t      if(abs(signal_cwt(0,i))>abs(signal_cwt(0,signal.extent(0)/2))/1e2)\n\t\t{\n\t\t  max_idx=i;\n\t\t  break;\n\t\t}\n\t    }\n\t  const_cast<T&>(coi_factor)=(signal.extent(0)/2-max_idx)/8.;\n\t  const_cast<bool&>(coi_calculated)=true;\n\t}\n      return coi_factor*.85;\n    }\n\n    \n  private:\n    std::complex<T> do_wavelet_f(T w,T s)const\n    {\n      static const T pi=atan(1)*4;\n      if(w<=0)\n\t{\n\t  return 0;\n\t}\n      else\n\t{\n\t  return pow(T(pi),T(-.25))*exp(-pow(s*w-omega_0,2)/2);\n\t}\n    }\n  };\n\n  template <typename T>\n  class paul\n    :public wavelet_func<T>\n  {\n  private:\n    int m;\n    T norm;\n    T coi_factor;\n    bool coi_calculated;\n\n  public:\n    paul()\n      :m(4),coi_calculated(false)\n    {\n      norm=calc_norm();\n    }\n    \n    paul(T m1)\n      :m(m1),coi_calculated(false)\n    {\n      norm=calc_norm();\n    }\n\n    T do_cone_of_influence_factor()const\n    {\n      if(!coi_calculated)\n\t{\n\t  blitz::Array<T,1> signal(1024);\n\t  signal=0;\n\t  signal(signal.extent(0)/2)=1;\n\t  blitz::Array<T,1> scales(1);\n\t  scales(0)=1;\n\t  blitz::Array<std::complex<T>,2> signal_cwt(cwt(signal,scales,*this));\n\t  int max_idx=0;\n\t  for(int i=0;i<signal.extent(0)/2;++i)\n\t    {\n\t      if(abs(signal_cwt(0,i))>abs(signal_cwt(0,signal.extent(0)/2))/25)\n\t\t{\n\t\t  max_idx=i;\n\t\t  break;\n\t\t}\n\t    }\n\t  const_cast<T&>(coi_factor)=(signal.extent(0)/2-max_idx)/4.;\n\t  const_cast<bool&>(coi_calculated)=true;\n\t}\n      return coi_factor;\n    }\n\n    \n    T calc_norm()\n    {\n      return pow(T(2.),(T)m)/sqrt(m*factorial(2*m-1));\n    }\n    \n    int factorial(int n)\n    {\n      if(n==0)\n\t{\n\t  return 1;\n\t}\n      else\n\t{\n\t  return n*factorial(n-1);\n\t}\n    }\n\n  private:\n    std::complex<T> do_wavelet_f(T w,T s)const\n    {\n      if(w<=0)\n\t{\n\t  return 0;\n\t}\n      else\n\t{\n\t  return norm*pow(s*w,(T)m)*exp(-s*w);\n\t}\n    }\n  };\n}\n\n#endif\n//EOF\n", "meta": {"hexsha": "d92391345a71906edd5115f1ef2e2c4e2915b617", "size": 3746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cwt/pycwt1d/src/cwt1d_wavelets.hpp", "max_stars_repo_name": "lizhangscience/cdae-eor", "max_stars_repo_head_hexsha": "61dab95681c5806a521a57846d9c875404cd4890", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-09-28T02:12:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T08:44:18.000Z", "max_issues_repo_path": "cwt/pycwt1d/src/cwt1d_wavelets.hpp", "max_issues_repo_name": "lizhangscience/cdae-eor", "max_issues_repo_head_hexsha": "61dab95681c5806a521a57846d9c875404cd4890", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-18T09:52:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T09:41:09.000Z", "max_forks_repo_path": "cwt/pycwt1d/src/cwt1d_wavelets.hpp", "max_forks_repo_name": "liweitianux/cdae-eor", "max_forks_repo_head_hexsha": "61dab95681c5806a521a57846d9c875404cd4890", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-09-28T02:12:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-16T19:43:38.000Z", "avg_line_length": 18.2731707317, "max_line_length": 79, "alphanum_fraction": 0.567538708, "num_tokens": 1288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5090495752113775}}
{"text": "// Petter Strandmark 2012.\n\n#include <cstdio>\n#include <iostream>\n#include <limits>\n#include <stdexcept>\n\n#include <Eigen/Dense>\n\n#include <spii/spii.h>\n#include <spii/solver.h>\n\nnamespace spii {\n\nvoid PatternSolver::solve(const Function& function,\n                          SolverResults* results) const\n{\n\tdouble global_start_time = wall_time();\n\n\t// Dimension of problem.\n\tsize_t n = function.get_number_of_scalars();\n\n\tif (n == 0) {\n\t\tresults->exit_condition = SolverResults::FUNCTION_TOLERANCE;\n\t\treturn;\n\t}\n\n\t// Current point, gradient and Hessian.\n\tdouble fval   = std::numeric_limits<double>::quiet_NaN();\n\tdouble fprev  = std::numeric_limits<double>::quiet_NaN();\n\n\tEigen::VectorXd x;\n\t// Copy the user state to the current point.\n\tfunction.copy_user_to_global(&x);\n\tEigen::VectorXd dx(n);\n\n\t// Size of the pattern.\n\tdouble pattern_size = 1.0;\n\tdouble x_inf = std::max(x.maxCoeff(), -x.minCoeff());\n\tif (x_inf > 1e-6) {\n\t\tpattern_size = x_inf /= 2.0;\n\t}\n\tdouble pattern_size0 = pattern_size;\n\n\t// Sufficient decrease.\n\tauto rho = [](double t) -> double { return 1e-4 * std::pow(t ,1.5); };\n\n\n\t//\n\t// START MAIN ITERATION\n\t//\n\tresults->startup_time   += wall_time() - global_start_time;\n\tresults->exit_condition = SolverResults::INTERNAL_ERROR;\n\tint iter = 0;\n\twhile (true) {\n\n\t\t//\n\t\t// Search along all coordinate directions\n\t\t//\n\t\tdouble start_time = wall_time();\n\n\t\tif (iter == 0) {\n\t\t\tfval = function.evaluate(x);\n\t\t}\n\n\t\tbool success = false;\n\t\tfor (size_t i = 0; i < n; ++i) {\n\t\t\tdx.setZero();\n\t\t\t//for d in {-1, 1}\n\t\t\tfor (double d = -1; d <= 1; d += 2) {\n\t\t\t\t// Search along this coordinate axis in\n\t\t\t\t// direction d.\n\t\t\t\tdx[i] = d * pattern_size;\n\t\t\t\t// Evaluate function in new point.\n\t\t\t\tdouble fval_new = function.evaluate(x + dx);\n\n\t\t\t\t// If we have sufficient decrease.\n\t\t\t\tif (fval_new < fval - rho(pattern_size)) {\n\t\t\t\t\tsuccess = true;\n\t\t\t\t\tx = x + dx;\n\t\t\t\t\tfval = fval_new;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (success) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// If no point was found, decrease pattern size.\n\t\tif (! success) {\n\t\t\tpattern_size /= 2.0;\n\t\t}\n\n\t\tresults->function_evaluation_time += wall_time() - start_time;\n\n\t\t//\n\t\t// Test stopping criteriea\n\t\t//\n\t\tstart_time = wall_time();\n\t\tif (pattern_size / pattern_size0 < this->area_tolerance) {\n\t\t\tresults->exit_condition = SolverResults::GRADIENT_TOLERANCE;\n\t\t\tbreak;\n\t\t}\n\t\tif (success &&\n\t\t\tstd::fabs(fval - fprev) / (std::fabs(fval) + this->function_improvement_tolerance) <\n\t\t\t                                             this->function_improvement_tolerance) {\n\t\t\tresults->exit_condition = SolverResults::FUNCTION_TOLERANCE;\n\t\t\tbreak;\n\t\t}\n\t\tif (iter >= this->maximum_iterations) {\n\t\t\tresults->exit_condition = SolverResults::NO_CONVERGENCE;\n\t\t\tbreak;\n\t\t}\n\t\tresults->stopping_criteria_time += wall_time() - start_time;\n\n\t\t//\n\t\t// Log the results of this iteration.\n\t\t//\n\t\tstart_time = wall_time();\n\n\t\tint log_interval = 1;\n\t\tif (iter > 30) {\n\t\t\tlog_interval = 10;\n\t\t}\n\t\tif (iter > 200) {\n\t\t\tlog_interval = 100;\n\t\t}\n\t\tif (iter > 2000) {\n\t\t\tlog_interval = 1000;\n\t\t}\n\t\tif (iter > 20000) {\n\t\t\tlog_interval = 10000;\n\t\t}\n\t\tif (iter > 200000) {\n\t\t\tlog_interval = 100000;\n\t\t}\n\t\tif (this->log_function && iter % log_interval == 0) {\n\t\t\tchar str[1024];\n\t\t\t\tif (iter == 0) {\n\t\t\t\t\tthis->log_function(\"Itr         f       deltaf   gamma   success\");\n\t\t\t\t}\n\t\t\t\tstd::sprintf(str, \"%7d %+10.3e %9.3e %9.3e %s\",\n\t\t\t\t\titer, fval, std::fabs(fval - fprev), pattern_size, success ? \"yes\" : \"no\");\n\t\t\tthis->log_function(str);\n\t\t}\n\t\tresults->log_time += wall_time() - start_time;\n\n\t\tfprev = fval;\n\t\titer++;\n\t}\n\n\tfunction.copy_global_to_user(x);\n\tresults->total_time += wall_time() - global_start_time;\n\n\tif (this->log_function) {\n\t\tchar str[1024];\n\t\tstd::sprintf(str, \"    end %+10.3e %9.3e %9.3e\", fval, std::fabs(fval - fprev), pattern_size);\n\t\tthis->log_function(str);\n\t}\n}\n\n}  // namespace spii", "meta": {"hexsha": "13d9bb5ff050f02bdaaea5804a649aac0a5e802a", "size": 3839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/solver_pattern_search.cpp", "max_stars_repo_name": "PetterS/spii", "max_stars_repo_head_hexsha": "98c5847223d7c3febea5a1aac6f4978dfef207ec", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-03-03T16:21:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T08:02:12.000Z", "max_issues_repo_path": "source/solver_pattern_search.cpp", "max_issues_repo_name": "nashdingsheng/spii", "max_issues_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-07-16T14:41:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-09T19:27:22.000Z", "max_forks_repo_path": "source/solver_pattern_search.cpp", "max_forks_repo_name": "nashdingsheng/spii", "max_forks_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-09-21T23:09:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T20:20:30.000Z", "avg_line_length": 23.4085365854, "max_line_length": 96, "alphanum_fraction": 0.6249023183, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5090495714973954}}
{"text": "#include <iostream>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <vector>\r\n\r\nusing namespace std;\r\nusing namespace boost::multiprecision;\r\n\r\nvoid printvector(vector<int> n); // imprime un vector\r\nvoid dec2bin(cpp_int n); // transforma a binario\r\nvector<int> twoscomplement(vector<int> &negative); // complemento del 2 del numero\r\n\r\nint main() {\r\n  cpp_int n;\r\n  while (cin >> n) {\r\n    dec2bin(n);\r\n  }\r\n  return 0;\r\n}\r\n\r\nvoid printvector(vector<int> n) {\r\n  int bitcount = 0;\r\n  for (size_t i = 0; i < n.size(); ++i) {\r\n    cout << n[i];\r\n    bitcount += n[i] == 1 ? 1 : 0;\r\n  }\r\n  cout << endl << \"Bitcount: \" << bitcount << endl;\r\n}\r\n\r\nvoid dec2bin(cpp_int n) {\r\n  vector<int> resultado;\r\n  resultado.clear();\r\n  int counter = 31;\r\n  bool isNegative = 0;\r\n  if (n < 1) { // si es negativo, se calcula el valor absoluto\r\n    n = -n;\r\n    isNegative = 1;\r\n  }\r\n  for (int i = 0; i < 32; ++i) { // transforma el numero a binario al reves\r\n    resultado.push_back(n % 2 == 1 ? 1 : 0);\r\n\tn /= 2;\r\n  }\r\n  for (int i = 0; i < 16; ++i) { // reordena el numero al reves\r\n    swap(resultado[i], resultado[counter]);\r\n    --counter;\r\n  }\r\n  printvector((isNegative == 1) ? twoscomplement(resultado) : resultado);\r\n}\r\n\r\nvector<int> twoscomplement(vector<int> &negative) {\r\n  for (int i = 0; i < 32; ++i) { // cambia 1 por 0 y vice-versa\r\n    negative[i] = (negative[i] == 0) ? 1 : 0;\r\n  }\r\n  for (int i = 31; i >= 0; --i) { // suma 1 al numero\r\n    if (negative[i] != 0) {\r\n      negative[i] = 0;\r\n    } else {\r\n      negative[i] = 1;\r\n      break;\r\n    }\r\n  }\r\n  return negative;\r\n}\r\n", "meta": {"hexsha": "60420bfec8a262b3a9bd9d50fd8a744c205e32b2", "size": 1586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "decimaltobinary.cpp", "max_stars_repo_name": "mdrxd100/cpp_projects", "max_stars_repo_head_hexsha": "e5aa8223138b5d526d02a18b6e526624834d1671", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "decimaltobinary.cpp", "max_issues_repo_name": "mdrxd100/cpp_projects", "max_issues_repo_head_hexsha": "e5aa8223138b5d526d02a18b6e526624834d1671", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "decimaltobinary.cpp", "max_forks_repo_name": "mdrxd100/cpp_projects", "max_forks_repo_head_hexsha": "e5aa8223138b5d526d02a18b6e526624834d1671", "max_forks_repo_licenses": ["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.1746031746, "max_line_length": 83, "alphanum_fraction": 0.5655737705, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5090495699758338}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>\n// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>\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 <limits>\n#include <Eigen/Eigenvalues>\n#include <Eigen/LU>\n\ntemplate<typename MatrixType> bool find_pivot(typename MatrixType::Scalar tol, MatrixType &diffs, Index col=0)\n{\n  bool match = diffs.diagonal().sum() <= tol;\n  if(match || col==diffs.cols())\n  {\n    return match;\n  }\n  else\n  {\n    Index n = diffs.cols();\n    std::vector<std::pair<Index,Index> > transpositions;\n    for(Index i=col; i<n; ++i)\n    {\n      Index best_index(0);\n      if(diffs.col(col).segment(col,n-i).minCoeff(&best_index) > tol)\n        break;\n      \n      best_index += col;\n      \n      diffs.row(col).swap(diffs.row(best_index));\n      if(find_pivot(tol,diffs,col+1)) return true;\n      diffs.row(col).swap(diffs.row(best_index));\n      \n      // move current pivot to the end\n      diffs.row(n-(i-col)-1).swap(diffs.row(best_index));\n      transpositions.push_back(std::pair<Index,Index>(n-(i-col)-1,best_index));\n    }\n    // restore\n    for(Index k=transpositions.size()-1; k>=0; --k)\n      diffs.row(transpositions[k].first).swap(diffs.row(transpositions[k].second));\n  }\n  return false;\n}\n\n/* Check that two column vectors are approximately equal upto permutations.\n * Initially, this method checked that the k-th power sums are equal for all k = 1, ..., vec1.rows(),\n * however this strategy is numerically inacurate because of numerical cancellation issues.\n */\ntemplate<typename VectorType>\nvoid verify_is_approx_upto_permutation(const VectorType& vec1, const VectorType& vec2)\n{\n  typedef typename VectorType::Scalar Scalar;\n  typedef typename NumTraits<Scalar>::Real RealScalar;\n\n  VERIFY(vec1.cols() == 1);\n  VERIFY(vec2.cols() == 1);\n  VERIFY(vec1.rows() == vec2.rows());\n  \n  Index n = vec1.rows();\n  RealScalar tol = test_precision<RealScalar>()*test_precision<RealScalar>()*numext::maxi(vec1.squaredNorm(),vec2.squaredNorm());\n  Matrix<RealScalar,Dynamic,Dynamic> diffs = (vec1.rowwise().replicate(n) - vec2.rowwise().replicate(n).transpose()).cwiseAbs2();\n  \n  VERIFY( find_pivot(tol, diffs) );\n}\n\n\ntemplate<typename MatrixType> void eigensolver(const MatrixType& m)\n{\n  typedef typename MatrixType::Index Index;\n  /* this test covers the following files:\n     ComplexEigenSolver.h, and indirectly ComplexSchur.h\n  */\n  Index rows = m.rows();\n  Index cols = m.cols();\n\n  typedef typename MatrixType::Scalar Scalar;\n  typedef typename NumTraits<Scalar>::Real RealScalar;\n\n  MatrixType a = MatrixType::Random(rows,cols);\n  MatrixType symmA =  a.adjoint() * a;\n\n  ComplexEigenSolver<MatrixType> ei0(symmA);\n  VERIFY_IS_EQUAL(ei0.info(), Success);\n  VERIFY_IS_APPROX(symmA * ei0.eigenvectors(), ei0.eigenvectors() * ei0.eigenvalues().asDiagonal());\n\n  ComplexEigenSolver<MatrixType> ei1(a);\n  VERIFY_IS_EQUAL(ei1.info(), Success);\n  VERIFY_IS_APPROX(a * ei1.eigenvectors(), ei1.eigenvectors() * ei1.eigenvalues().asDiagonal());\n  // Note: If MatrixType is real then a.eigenvalues() uses EigenSolver and thus\n  // another algorithm so results may differ slightly\n  verify_is_approx_upto_permutation(a.eigenvalues(), ei1.eigenvalues());\n\n  ComplexEigenSolver<MatrixType> ei2;\n  ei2.setMaxIterations(ComplexSchur<MatrixType>::m_maxIterationsPerRow * rows).compute(a);\n  VERIFY_IS_EQUAL(ei2.info(), Success);\n  VERIFY_IS_EQUAL(ei2.eigenvectors(), ei1.eigenvectors());\n  VERIFY_IS_EQUAL(ei2.eigenvalues(), ei1.eigenvalues());\n  if (rows > 2) {\n    ei2.setMaxIterations(1).compute(a);\n    VERIFY_IS_EQUAL(ei2.info(), NoConvergence);\n    VERIFY_IS_EQUAL(ei2.getMaxIterations(), 1);\n  }\n\n  ComplexEigenSolver<MatrixType> eiNoEivecs(a, false);\n  VERIFY_IS_EQUAL(eiNoEivecs.info(), Success);\n  VERIFY_IS_APPROX(ei1.eigenvalues(), eiNoEivecs.eigenvalues());\n\n  // Regression test for issue #66\n  MatrixType z = MatrixType::Zero(rows,cols);\n  ComplexEigenSolver<MatrixType> eiz(z);\n  VERIFY((eiz.eigenvalues().cwiseEqual(0)).all());\n\n  MatrixType id = MatrixType::Identity(rows, cols);\n  VERIFY_IS_APPROX(id.operatorNorm(), RealScalar(1));\n\n  if (rows > 1 && rows < 20)\n  {\n    // Test matrix with NaN\n    a(0,0) = std::numeric_limits<typename MatrixType::RealScalar>::quiet_NaN();\n    ComplexEigenSolver<MatrixType> eiNaN(a);\n    VERIFY_IS_EQUAL(eiNaN.info(), NoConvergence);\n  }\n\n  // regression test for bug 1098\n  {\n    ComplexEigenSolver<MatrixType> eig(a.adjoint() * a);\n    eig.compute(a.adjoint() * a);\n  }\n\n  // regression test for bug 478\n  {\n    a.setZero();\n    ComplexEigenSolver<MatrixType> ei3(a);\n    VERIFY_IS_EQUAL(ei3.info(), Success);\n    VERIFY_IS_MUCH_SMALLER_THAN(ei3.eigenvalues().norm(),RealScalar(1));\n    VERIFY((ei3.eigenvectors().transpose()*ei3.eigenvectors().transpose()).eval().isIdentity());\n  }\n}\n\ntemplate<typename MatrixType> void eigensolver_verify_assert(const MatrixType& m)\n{\n  ComplexEigenSolver<MatrixType> eig;\n  VERIFY_RAISES_ASSERT(eig.eigenvectors());\n  VERIFY_RAISES_ASSERT(eig.eigenvalues());\n\n  MatrixType a = MatrixType::Random(m.rows(),m.cols());\n  eig.compute(a, false);\n  VERIFY_RAISES_ASSERT(eig.eigenvectors());\n}\n\nvoid test_eigensolver_complex()\n{\n  int s = 0;\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( eigensolver(Matrix4cf()) );\n    s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4);\n    CALL_SUBTEST_2( eigensolver(MatrixXcd(s,s)) );\n    CALL_SUBTEST_3( eigensolver(Matrix<std::complex<float>, 1, 1>()) );\n    CALL_SUBTEST_4( eigensolver(Matrix3f()) );\n    TEST_SET_BUT_UNUSED_VARIABLE(s)\n  }\n  CALL_SUBTEST_1( eigensolver_verify_assert(Matrix4cf()) );\n  s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4);\n  CALL_SUBTEST_2( eigensolver_verify_assert(MatrixXcd(s,s)) );\n  CALL_SUBTEST_3( eigensolver_verify_assert(Matrix<std::complex<float>, 1, 1>()) );\n  CALL_SUBTEST_4( eigensolver_verify_assert(Matrix3f()) );\n\n  // Test problem size constructors\n  CALL_SUBTEST_5(ComplexEigenSolver<MatrixXf> tmp(s));\n  \n  TEST_SET_BUT_UNUSED_VARIABLE(s)\n}\n", "meta": {"hexsha": "293b1b26566fde8565a609afb6330b0baa184556", "size": 6256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/test/eigensolver_complex.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 299.0, "max_stars_repo_stars_event_min_datetime": "2017-06-12T23:56:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T15:29:15.000Z", "max_issues_repo_path": "src/Eigen-3.3/test/eigensolver_complex.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 224.0, "max_issues_repo_issues_event_min_datetime": "2018-02-26T00:41:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:38:16.000Z", "max_forks_repo_path": "src/Eigen-3.3/test/eigensolver_complex.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 35.1460674157, "max_line_length": 129, "alphanum_fraction": 0.7089194373, "num_tokens": 1746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5090400638857607}}
{"text": "// SPDX-FileCopyrightText: 2015 - 2021 Marcin \u0141o\u015b <marcin.los.91@gmail.com>\n// SPDX-License-Identifier: MIT\n\n#ifndef ADS_SIMULATION_DIMENSION_HPP\n#define ADS_SIMULATION_DIMENSION_HPP\n\n#include <boost/range/counting_range.hpp>\n\n#include \"ads/basis_data.hpp\"\n#include \"ads/bspline/bspline.hpp\"\n#include \"ads/form_matrix.hpp\"\n#include \"ads/lin/band_matrix.hpp\"\n#include \"ads/lin/band_solve.hpp\"\n#include \"ads/simulation/config.hpp\"\n#include \"ads/solver.hpp\"\n#include \"ads/util.hpp\"\n\nnamespace ads {\n\nclass dimension {\npublic:\n    using element_range_type = decltype(boost::counting_range(0, 0));\n\n    int p;\n    int elements;\n    double a;\n    double b;\n    bspline::basis B;\n    lin::band_matrix M;\n    basis_data basis;\n    lin::solver_ctx ctx;\n\n    dimension(bspline::basis basis, int quad_order, int derivatives, int elem_division = 1);\n\n    dimension(const dim_config& config, int derivatives);\n\n    int dofs() const { return B.dofs(); }\n\n    element_range_type element_indices() const { return boost::counting_range(0, elements); }\n\n    dim_data data() { return {M, ctx}; }\n\n    void fix_dof(int k);\n\n    void fix_left() { fix_dof(0); }\n\n    void fix_right() {\n        int last = dofs() - 1;\n        fix_dof(last);\n    }\n\n    void factorize_matrix() { lin::factorize(M, ctx); }\n\nprivate:\n    static bspline::basis bspline_basis(const dim_config& config) {\n        return bspline::create_basis(config.a, config.b, config.p, config.elements,\n                                     config.repeated_nodes);\n    }\n};\n\n}  // namespace ads\n\n#endif  // ADS_SIMULATION_DIMENSION_HPP\n", "meta": {"hexsha": "98080a89c61ac819b832eaa00d4ea98f3faca0cb", "size": 1575, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ads/simulation/dimension.hpp", "max_stars_repo_name": "Pan-Maciek/iga-ads", "max_stars_repo_head_hexsha": "4744829c98cba4e9505c5c996070119e73ba18fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-01-19T00:19:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T00:53:00.000Z", "max_issues_repo_path": "include/ads/simulation/dimension.hpp", "max_issues_repo_name": "Pan-Maciek/iga-ads", "max_issues_repo_head_hexsha": "4744829c98cba4e9505c5c996070119e73ba18fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T22:44:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T15:18:00.000Z", "max_forks_repo_path": "include/ads/simulation/dimension.hpp", "max_forks_repo_name": "Pan-Maciek/iga-ads", "max_forks_repo_head_hexsha": "4744829c98cba4e9505c5c996070119e73ba18fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-04-13T19:42:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T18:46:24.000Z", "avg_line_length": 24.609375, "max_line_length": 93, "alphanum_fraction": 0.6787301587, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5090400601947062}}
{"text": "/******************************************************************************\n\n  This source file is part of the Avogadro project.\n\n  Copyright 2011-2012 Kitware, Inc.\n\n  This source code is released under the New BSD License, (the \"License\").\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n\n******************************************************************************/\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\nTEST(EigenTest, vector3d)\n{\n  Eigen::Vector3d vec;\n  vec.setZero();\n  EXPECT_EQ(vec.x(), 0);\n  EXPECT_EQ(vec.y(), 0);\n  EXPECT_EQ(vec.z(), 0);\n}\n", "meta": {"hexsha": "35b855d038fcff3efc93a7d431a7b1f9ee6dd1c3", "size": 839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/core/eigentest.cpp", "max_stars_repo_name": "serk12/avogadrolibs", "max_stars_repo_head_hexsha": "f2dd0fda7e0d2ca4a0586354ea253cc05242f022", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 244.0, "max_stars_repo_stars_event_min_datetime": "2015-09-09T15:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:44:21.000Z", "max_issues_repo_path": "tests/core/eigentest.cpp", "max_issues_repo_name": "serk12/avogadrolibs", "max_issues_repo_head_hexsha": "f2dd0fda7e0d2ca4a0586354ea253cc05242f022", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 670.0, "max_issues_repo_issues_event_min_datetime": "2015-05-08T18:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T19:47:08.000Z", "max_forks_repo_path": "tests/core/eigentest.cpp", "max_forks_repo_name": "serk12/avogadrolibs", "max_forks_repo_head_hexsha": "f2dd0fda7e0d2ca4a0586354ea253cc05242f022", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 129.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T01:18:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T08:50:25.000Z", "avg_line_length": 28.9310344828, "max_line_length": 79, "alphanum_fraction": 0.5923718713, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5090400382537174}}
{"text": "#define BOOST_TEST_MODULE cnnefTestMarray\n\n#include <boost/test/unit_test.hpp>\n\n#include <iostream> \n\n#include \"cnnef/tools/runtime_check.hxx\"\n#include \"cnnef/marray/marray.hxx\"\n\n\nBOOST_AUTO_TEST_CASE(StridesTest)\n{\n    std::vector<size_t> shape({10,20});\n    cnnef::marray::Marray<int> a(shape.begin(), shape.end());\n    CNNEF_TEST_OP(a.strides(1),==,1);\n    CNNEF_TEST_OP(a.strides(0),==,20);\n}\n\n", "meta": {"hexsha": "ca0cdd92a33e9855449138c1de2ece51e0dcc711", "size": 398, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/test/test_marray.cxx", "max_stars_repo_name": "DerThorsten/cnnef", "max_stars_repo_head_hexsha": "08c5ffa30c7c86ac5efe48c12f735a7680f6420d", "max_stars_repo_licenses": ["MIT"], "max_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_marray.cxx", "max_issues_repo_name": "DerThorsten/cnnef", "max_issues_repo_head_hexsha": "08c5ffa30c7c86ac5efe48c12f735a7680f6420d", "max_issues_repo_licenses": ["MIT"], "max_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_marray.cxx", "max_forks_repo_name": "DerThorsten/cnnef", "max_forks_repo_head_hexsha": "08c5ffa30c7c86ac5efe48c12f735a7680f6420d", "max_forks_repo_licenses": ["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.9473684211, "max_line_length": 61, "alphanum_fraction": 0.7085427136, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5090400382537174}}
{"text": "#include \"block.hpp\"\n#include <iostream>\n#include <Eigen/Dense>\n#include <ostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing namespace Eigen;\n\n\nTetrisBlock::TetrisBlock(std::string name, int value, Matrix4f mask, Vector2f pivot){\n    this_name = name;\n    this_pivot = pivot;\n    this_mask = mask;\n    this_rotation_matrix << 0, -1, 1, 0;\n    this_value = value;\n};\n\nVector2f TetrisBlock::rotate_point(Vector2f point){\n    return (this_rotation_matrix * (point - this_pivot)) + this_pivot;\n}\n\nMatrix4f TetrisBlock::rotate_mask(){\n    Matrix4f new_mask = Matrix4f::Zero();\n    int newx;\n    int newy;\n    auto handle_negative_index = [](int index){\n\t\t\t    if (index < 0){\n\t\t\t      index = 4 + index;\n\t\t\t    }\n\t\t\t    return index;\n\t\t\t  };\n\n    \n    for (int i=0; i < 4; i++){\t\n      for (int j=0; j < 4; j++){\n\tif (this_mask(i, j) != 0){\n\t    Vector2f point;\n\t    point << i, j;\n\t    auto position = rotate_point(point);\n\t    newx = handle_negative_index(position(0));\n\t    newy = handle_negative_index(position(1));\n\t    new_mask(newx, newy) = this_value;\n\t  }\n      }\n    }\n    return new_mask;\n  }\n\nvoid TetrisBlock::rotate(){\n  this_mask = rotate_mask();\n}  \n\n\nstd::ostream & operator<<(std::ostream & flux, TetrisBlock const & block ){\n  return flux << \"\\n\" <<  \"block : \" << block.this_name << \"\\n\" << \"----------\\n\" << block.this_mask << \"\\n\";\n}\n\n\nbool block_position_possible(int x, int y, const TetrisBlock &block, const MatrixXf &grid){\n  /* Check if the block can be placed in the position (x,y), with (x,y) reprenting the left corner of the mask*/\n  \n  auto mask_block = block.this_mask.block(0, 0, 4, 4);\n  auto grid_block = grid.block(y, x,  4, 4);\n  auto bool_block = (mask_block.array() * grid_block.array()) != 0.0;\n  return !(bool_block.any());\n}\n\n\nvoid add_block_to_grid(int x, int y, const TetrisBlock &block, MatrixXf &grid){\n  /* Add the block to the grid. This function do some side effects on grid\n   */\n  auto mask_block = block.this_mask.block(0, 0, 4, 4);\n  auto grid_block = grid.block(y, x,  4, 4);\n  grid_block = mask_block + grid_block;\n}\n\n\n\n\nMatrixXf get_visualGrid(int x, int y, int visualNrows, int visualNcols, const TetrisBlock &block, MatrixXf grid, int top_padding, int left_padding){\n  /* Return the visual grid wich is used to display the game to the player without showing the paddings blocks, it doesn't do any side effects*/\n  auto mask_block = block.this_mask.block(0, 0, 4, 4);\n  auto grid_block = grid.block(y, x,  4, 4);\n  grid_block = mask_block + grid_block;\n  \n  auto visualGridBlock = grid.block(3, 3, visualNrows, visualNcols);\n  MatrixXf newGrid (visualNrows, visualNcols);\n  newGrid = visualGridBlock;\n  return newGrid;\n}\n\nint next_one_index(int index, VectorXf col){\n  for (int i =0; i < col.size(); i++){\n    if (i > index){\n      if (col(i) != 0){\n\treturn i;\n      }\n    }\n  }\n  // if no values are found return a negative value;\n  return -1;\n}\n\nbool is_line(VectorXf row) { return row.array().all(); }\n\nstd::vector<int> find_lines(const MatrixXf & grid, int padding){\n  /* Return a vector of row indexes of completed lines*/\n  std::vector<int> indexes;\n  for (int i = 0; i < grid.rows() - padding; i++){\n\n    if (is_line(grid.row(i))){\n      indexes.push_back(i);\n    }\n  }\n  return indexes;\n}\n\n\nVectorXf refactor_col(int line_index, VectorXf col){\n  /* Construct a new column by destroying the line value and shifting the values to the next non-zero value (make the block \"fall\").*/\n  \n  int inext = next_one_index(line_index, col);\n  VectorXf new_col(col.size());\n  new_col << VectorXf::Zero(inext - line_index), col.head(line_index), col.tail(col.size() - inext);\n  return new_col;\n}\n\nvoid delete_line(int line_index, MatrixXf &grid, int padding){\n  /* Delete a line by refactoring all the columns of the grid who are not padding columns*/\n  for (int j = padding; j < grid.cols() - padding; j++){\n    auto col = grid.col(j);\n    col = refactor_col(line_index, col);\n  }\n}\n\n\n\nstd::unordered_map<std::string, TetrisBlock> get_block_map(){\n  std::unordered_map<std::string, TetrisBlock> map;\n  \n  // I, cyan\n  Matrix4f Imask;\n  Vector2f Ipivot;\n  Imask << 0, 0, 0, 0,\n    0, 0, 0, 0,\n    1, 1, 1, 1,\n    0, 0, 0, 0;\n\n  Ipivot << 2, 1;\n  map.insert({\"I\", TetrisBlock(\"I\", 1, Imask, Ipivot)});\n\n  // \n  Matrix4f Omask;\n  Vector2f Opivot;\n  Omask << 0, 0, 0, 0,\n    0, 0, 0, 0,\n    0, 2, 2, 0,\n    0, 2, 2, 0;\n\n  Opivot << 2.5, 1.5;\n  map.insert({\"O\", TetrisBlock(\"O\", 2, Omask, Opivot)});\n\n  Matrix4f Tmask;\n  Vector2f Tpivot;\n  Tmask << 0, 0, 0, 0,\n    0, 0, 0, 0,\n    3, 3, 3, 0,\n    0, 3, 0, 0;\n\n  Tpivot << 2, 1;\n  map.insert({\"T\", TetrisBlock(\"T\", 3, Tmask, Tpivot)});\n\n  Matrix4f Lmask;\n  Vector2f Lpivot;\n  Lmask << 0, 0, 0, 0,\n    0, 0, 0, 0,\n    4, 4, 4, 0,\n    4, 0, 0, 0;\n\n  Lpivot << 2, 1;\n  map.insert({\"L\", TetrisBlock(\"L\", 4, Lmask, Lpivot)});\n\n  Matrix4f Jmask;\n  Vector2f Jpivot;\n  Jmask << 0, 0, 0, 0,\n    0, 0, 0, 0,\n    5, 5, 5, 0,\n    0, 0, 5, 0;\n\n  Jpivot << 2, 1;\n  map.insert({\"J\", TetrisBlock(\"J\", 5, Jmask, Jpivot)});\n\n  Matrix4f Zmask;\n  Vector2f Zpivot;\n  Zmask << 0, 0, 0, 0,\n    6, 6, 0, 0,\n    0, 6, 6, 0,\n    0, 0, 0, 0;\n\n  Zpivot << 2, 1;\n  map.insert({\"Z\", TetrisBlock(\"Z\", 6, Zmask, Zpivot)});\n\n  Matrix4f Smask;\n  Vector2f Spivot;\n  Smask << 0, 0, 0, 0,\n    0, 7, 7, 0,\n    7, 7, 0, 0,\n    0, 0, 0, 0;\n\n  Spivot << 2, 1;\n  map.insert({\"S\", TetrisBlock(\"S\", 7, Smask, Spivot)});\n  \n  return map;\n  \n}\n\n\n \n", "meta": {"hexsha": "6f246082014846946d9ddc795590afe0cc19a7f1", "size": 5420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/block.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/block.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/block.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": 24.5248868778, "max_line_length": 148, "alphanum_fraction": 0.6143911439, "num_tokens": 1886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5089908020344169}}
{"text": "#include <boost/math/quadrature/sinh_sinh.hpp>\n", "meta": {"hexsha": "ff08e2e5267473b1c657012f1cf7e58c0e429cc5", "size": 47, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_quadrature_sinh_sinh.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_quadrature_sinh_sinh.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_quadrature_sinh_sinh.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.5, "max_line_length": 46, "alphanum_fraction": 0.8085106383, "num_tokens": 13, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619963333289, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5089908020344168}}
{"text": "// Copyright (c) Dewetron 2017\n#include \"otfft.h\"\n#include \"otfft_test_utils.h\"\n\n#include <boost/test/unit_test.hpp>\n\n#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <vector>\n\nnamespace\n{\n    std::size_t findPeak(const std::size_t fft_length, const double sample_rate, const double signal_frequency)\n    {\n        OTFFT::test::SineGenerator generator(sample_rate);\n        generator.setAmplitude(64).setFrequency(signal_frequency).generate(fft_length);\n\n        std::vector<OTFFT::complex_t> spectrum(fft_length);\n        {\n            auto fft = OTFFT::Factory::createRealFFT(static_cast<int>(fft_length));\n            OTFFT::double_vector fft_in{generator.data()};\n            OTFFT::complex_vector fft_out{spectrum.data()};\n            fft->fwd(fft_in, fft_out);\n        }\n\n        auto peakPos = std::max_element(\n                           std::begin(spectrum),\n                           std::begin(spectrum) + fft_length / 2,\n                           [] (OTFFT::complex_t x, OTFFT::complex_t y) -> bool\n                           {\n                               return std::sqrt(OTFFT::norm(x)) < std::sqrt(OTFFT::norm(y));\n                           }\n                       );\n\n        std::size_t d = std::distance(std::begin(spectrum), peakPos);\n\n        return d;\n    }\n}\n\nBOOST_AUTO_TEST_SUITE(otfft_find_peak_test)\n\nBOOST_AUTO_TEST_CASE(TestSinePeakDetect1)\n{\n    const auto peak_position = findPeak(64, 10000, 1000);\n    BOOST_CHECK_EQUAL(6u, peak_position);\n}\n\nBOOST_AUTO_TEST_CASE(TestSinePeakDetect2)\n{\n    const auto peak_position = findPeak(1024, 10000, 50);\n    BOOST_CHECK_EQUAL(5u, peak_position);\n}\n\nBOOST_AUTO_TEST_CASE(TestSinePeakDetect3)\n{\n    const auto peak_position = findPeak(8192, 50000, 4999);\n    BOOST_CHECK_EQUAL(819u, peak_position);\n}\n\nBOOST_AUTO_TEST_CASE(TestSinePeakDetect4)\n{\n    const auto peak_position = findPeak(262144, 1000000, 60000);\n    BOOST_CHECK_EQUAL(15729u, peak_position);\n}\n\nBOOST_AUTO_TEST_CASE(TestSinePeakDetect5)\n{\n    const auto peak_position = findPeak(32, 512, 1);\n    BOOST_CHECK_EQUAL(0u, peak_position);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "28c35ff66b386621c806bf116efc1dde53eb9af0", "size": 2124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/otfft_find_peak_test.cpp", "max_stars_repo_name": "24icewolf42/otfft", "max_stars_repo_head_hexsha": "6069f7017043af06f556a275662a465a56111c42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-24T22:46:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T00:57:59.000Z", "max_issues_repo_path": "unit_tests/otfft_find_peak_test.cpp", "max_issues_repo_name": "24icewolf42/otfft", "max_issues_repo_head_hexsha": "6069f7017043af06f556a275662a465a56111c42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-16T10:39:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-16T15:42:37.000Z", "max_forks_repo_path": "unit_tests/otfft_find_peak_test.cpp", "max_forks_repo_name": "24icewolf42/otfft", "max_forks_repo_head_hexsha": "6069f7017043af06f556a275662a465a56111c42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-01-16T15:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T00:21:50.000Z", "avg_line_length": 28.32, "max_line_length": 111, "alphanum_fraction": 0.6459510358, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5089907971080962}}
{"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//// Surface variables computation\n// Compute flow physical properties such as body velocity, mach number, pressure and forces coefficients.\n//\n// I/O:\n// - symY: defines symmetry about Y axis\n// - sRef: reference surface of the full wing\n// - alpha: freestream angle of attack\n// - Minf: freestream Mach number\n// - vInf: freestream velocity vector\n// - vSigma: field source induced body velocity\n// - bPan: (network of) body panels (structure)\n// - cL: lift coefficient\n// - cD: drag coefficient\n\n#include <iostream>\n#include <Eigen/Dense>\n\n#include \"compute_sVars.h\"\n\n#define NDIM 3\n#define GAMMA 1.4\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid compute_sVars(bool symY, double sRef, double alpha, double Minf, Vector3d &vInf,\n               MatrixX3d &vSigma, Network &bPan, double &cL, double &cD) {\n\n    // Temporary variables\n    int panIdx = 0;\n    double deltaL1, deltaL2, deltaT1, deltaT2;\n    double u = 0, v = 0, w = 0;\n    double cX = 0, cZ = 0;\n\n    //// Begin\n    cout << \"Computing surface variables... \";\n\n    // Resize matrices\n    bPan.U = MatrixX3d::Zero(bPan.nP, NDIM);\n    bPan.cP.resize(bPan.nP);\n\n    //// Velocity computation\n    // Surface induced velocity\n    for (int j = 0; j < bPan.nS_; ++j) {\n        for (int i = 0; i < bPan.nC_; ++i) {\n\n            // Longitudinal\n            if (i == 0) { // Forward differencing\n                deltaL2 = (bPan.CG.row(panIdx + 1) - bPan.CG.row(panIdx)).norm();\n                u = (bPan.mu(panIdx + 1) - bPan.mu(panIdx)) / deltaL2;\n            }\n            else if (i == bPan.nC_ - 1) { // Backward differencing\n                deltaL1 = (bPan.CG.row(panIdx) - bPan.CG.row(panIdx - 1)).norm();\n                u = (bPan.mu(panIdx) - bPan.mu(panIdx - 1)) / deltaL1;\n            }\n            else { // Central differencing\n                deltaL1 = (bPan.CG.row(panIdx) - bPan.CG.row(panIdx - 1)).norm();\n                deltaL2 = (bPan.CG.row(panIdx + 1) - bPan.CG.row(panIdx)).norm();\n                u = 0.5 * ((bPan.mu(panIdx + 1) - bPan.mu(panIdx)) / deltaL2 +\n                           (bPan.mu(panIdx) - bPan.mu(panIdx - 1)) / deltaL1);\n            }\n            // Transverse\n            if (j == 0) { // Forward differencing\n                deltaT2 = (bPan.CG.row(panIdx + bPan.nC_) - bPan.CG.row(panIdx)).norm();\n                v = (bPan.mu(panIdx + bPan.nC_) - bPan.mu(panIdx)) / deltaT2;\n            }\n            else if (j == bPan.nS_ - 1) { // Backward differencing\n                deltaT1 = (bPan.CG.row(panIdx) - bPan.CG.row(panIdx - bPan.nC_)).norm();\n                v = (bPan.mu(panIdx) - bPan.mu(panIdx - bPan.nC_)) / deltaT1;\n            }\n            else { // Central differencing\n                deltaT1 = (bPan.CG.row(panIdx) - bPan.CG.row(panIdx - bPan.nC_)).norm();\n                deltaT2 = (bPan.CG.row(panIdx + bPan.nC_) - bPan.CG.row(panIdx)).norm();\n                v = 0.5 * ((bPan.mu(panIdx + bPan.nC_) - bPan.mu(panIdx)) / deltaT2 +\n                           (bPan.mu(panIdx) - bPan.mu(panIdx - bPan.nC_)) / deltaT1);\n            }\n\n            // Transverse to perpendicular velocity\n            v = (bPan.t(panIdx, 0) * bPan.p(panIdx, 0)\n                 + bPan.t(panIdx, 1) * bPan.p(panIdx, 1)\n                 + bPan.t(panIdx, 2) * bPan.p(panIdx, 2)) * v;\n            // Normal velocity\n            w = bPan.tau(panIdx);\n\n            // Transformation to global axis\n            bPan.U(panIdx, 0) = u * bPan.l(panIdx, 0) - v * bPan.p(panIdx, 0) + w * bPan.n(panIdx, 0);\n            bPan.U(panIdx, 1) = u * bPan.l(panIdx, 1) - v * bPan.p(panIdx, 1) + w * bPan.n(panIdx, 1);\n            bPan.U(panIdx, 2) = u * bPan.l(panIdx, 2) - v * bPan.p(panIdx, 2) + w * bPan.n(panIdx, 2);\n\n            panIdx++;\n        }\n    }\n    // Freestream velocity\n    for (int i = 0; i < bPan.nP; ++i) {\n        bPan.U(i, 0) += vInf(0);\n        bPan.U(i, 1) += vInf(1);\n        bPan.U(i, 2) += vInf(2);\n    }\n    // Source induced velocity\n    if (Minf != 0)\n        bPan.U += vSigma;\n    // Mach number\n    if (Minf == 0)\n        bPan.M = VectorXd::Zero(bPan.nP);\n    else {\n        bPan.M.resize(bPan.nP);\n        for (int i = 0; i < bPan.nP; ++i)\n            bPan.M(i) = bPan.U.row(i).norm()\n                        / (1 / (Minf * Minf)\n                           + (GAMMA - 1) / 2 - (GAMMA - 1) / 2 * bPan.U.row(i).dot(bPan.U.row(i)));\n    }\n    //// Aerodynamic forces\n    // Pressure coefficient\n    if (Minf == 0) {\n        for (int i = 0; i < bPan.nP; ++i)\n            bPan.cP(i) = 1 - bPan.U.row(i).dot(bPan.U.row(i)) / vInf.dot(vInf);\n    }\n    else {\n        for (int i = 0; i < bPan.nP; ++i)\n            bPan.cP(i) = 2 / (GAMMA * Minf * Minf) *\n                (pow(1 + (GAMMA - 1) / 2 * Minf * Minf *\n                                 (1 - bPan.U.row(i).dot(bPan.U.row(i))), GAMMA / (GAMMA - 1)) - 1);\n    }\n    // Forces (x,y,z)\n    for (int i = 0; i < bPan.nP; ++i) {\n        cX += -bPan.cP(i) * bPan.S(i) / sRef * bPan.n(i,0);\n        cZ += -bPan.cP(i) * bPan.S(i) / sRef * bPan.n(i,2);\n    }\n    if (symY) {\n        cX = 2*cX;\n        cZ = 2*cZ;\n    }\n    // Forces (l,d,y)\n    cD = cos(alpha)*cX + sin(alpha)*cZ;\n    cL = -sin(alpha)*cX + cos(alpha)*cZ;\n\n    //// Control display\n    cout << \"Done!\" << endl;\n    #ifdef VERBOSE\n        cout << \"Surface velocities: \" << bPan.U.rows() << \"X\" << bPan.U.cols() << endl;\n        for (int i = 0; i < bPan.nP; ++i)\n            cout << i << ' ' << bPan.U(i,0) << ' ' << bPan.U(i,1) << ' ' << bPan.U(i,2) << endl;\n        cout << \"Pressure coefficients: \" << bPan.cP.rows() << \"X\" << bPan.cP.cols() << endl;\n        for (int i = 0; i < bPan.nP; ++i)\n            cout << i << ' ' << bPan.cP(i) << endl;\n    #endif\n    cout << \"Aerodynamic forces:\" << endl;\n    cout << \"Cx = \" << cX << endl;\n    cout << \"Cz = \" << cZ << endl;\n    cout << \"Cl = \" << cL << endl;\n    cout << \"Cd = \" << cD << endl;\n    cout << \"L/D = \" << cL/cD << endl << endl;\n}", "meta": {"hexsha": "37f6873697074f6e88d8554fc37f7ed560e2c74d", "size": 6541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/compute_sVars.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/compute_sVars.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/compute_sVars.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": 38.0290697674, "max_line_length": 105, "alphanum_fraction": 0.5121541049, "num_tokens": 2178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5089907921817753}}
{"text": "//  Copyright (c) 2015 John Maddock\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#ifndef BOOST_MATH_ELLINT_HL_HPP\r\n#define BOOST_MATH_ELLINT_HL_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/math/special_functions/math_fwd.hpp>\r\n#include <boost/math/special_functions/ellint_rj.hpp>\r\n#include <boost/math/special_functions/ellint_rj.hpp>\r\n#include <boost/math/special_functions/ellint_1.hpp>\r\n#include <boost/math/special_functions/jacobi_zeta.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/math/policies/error_handling.hpp>\r\n#include <boost/math/tools/workaround.hpp>\r\n\r\n// Elliptic integral the Jacobi Zeta function.\r\n\r\nnamespace boost { namespace math { \r\n   \r\nnamespace detail{\r\n\r\n// Elliptic integral - Jacobi Zeta\r\ntemplate <typename T, typename Policy>\r\nT heuman_lambda_imp(T phi, T k, const Policy& pol)\r\n{\r\n    BOOST_MATH_STD_USING\r\n    using namespace boost::math::tools;\r\n    using namespace boost::math::constants;\r\n\r\n    const char* function = \"boost::math::heuman_lambda<%1%>(%1%, %1%)\";\r\n\r\n    if(fabs(k) > 1)\r\n       return policies::raise_domain_error<T>(function, \"We require |k| <= 1 but got k = %1%\", k, pol);\r\n\r\n    T result;\r\n    T sinp = sin(phi);\r\n    T cosp = cos(phi);\r\n    T s2 = sinp * sinp;\r\n    T k2 = k * k;\r\n    T kp = 1 - k2;\r\n    T delta = sqrt(1 - (kp * s2));\r\n    if(fabs(phi) <= constants::half_pi<T>())\r\n    {\r\n       result = kp * sinp * cosp / (delta * constants::half_pi<T>());\r\n       result *= ellint_rf_imp(T(0), kp, T(1), pol) + k2 * ellint_rj(T(0), kp, T(1), T(1 - k2 / (delta * delta)), pol) / (3 * delta * delta);\r\n    }\r\n    else\r\n    {\r\n       T rkp = sqrt(kp);\r\n       T ratio;\r\n       if(rkp == 1)\r\n       {\r\n          return policies::raise_domain_error<T>(function, \"When 1-k^2 == 1 then phi must be < Pi/2, but got phi = %1%\", phi, pol);\r\n       }\r\n       else\r\n          ratio = ellint_f_imp(phi, rkp, pol) / ellint_k_imp(rkp, pol);\r\n       result = ratio + ellint_k_imp(k, pol) * jacobi_zeta_imp(phi, rkp, pol) / constants::half_pi<T>();\r\n    }\r\n    return result;\r\n}\r\n\r\n} // detail\r\n\r\ntemplate <class T1, class T2, class Policy>\r\ninline typename tools::promote_args<T1, T2>::type heuman_lambda(T1 k, T2 phi, const Policy& pol)\r\n{\r\n   typedef typename tools::promote_args<T1, T2>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::heuman_lambda_imp(static_cast<value_type>(phi), static_cast<value_type>(k), pol), \"boost::math::heuman_lambda<%1%>(%1%,%1%)\");\r\n}\r\n\r\ntemplate <class T1, class T2>\r\ninline typename tools::promote_args<T1, T2>::type heuman_lambda(T1 k, T2 phi)\r\n{\r\n   return boost::math::heuman_lambda(k, phi, policies::policy<>());\r\n}\r\n\r\n}} // namespaces\r\n\r\n#endif // BOOST_MATH_ELLINT_D_HPP\r\n\r\n", "meta": {"hexsha": "1150db433042c182d825d2ede3f209b0b24168d5", "size": 2978, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/math/special_functions/heuman_lambda.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/math/special_functions/heuman_lambda.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/math/special_functions/heuman_lambda.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": 33.8409090909, "max_line_length": 199, "alphanum_fraction": 0.6527871054, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5089558805768285}}
{"text": "#include <iostream>\n#include <Eigen/LU>\n\n#include \"irls.h\"\n#include \"input_validation.h\"\n#include \"disclap_family.h\"\n#include \"beta.h\"\n\nusing namespace Eigen;\n\nvoid check_input(const std::vector<MatrixXi>& d, const std::vector<MatrixXd>& w, VectorXd& beta, size_t maxit, bool use_deviance, double eps_deviance, bool use_beta, double eps_beta) {\n  check_common_input(maxit, use_deviance, eps_deviance, use_beta, eps_beta);\n  check_d_w(d, w);\n  check_beta(beta, d, w);\n}\n\nvoid update_lin_pred(VectorXd& lin_pred, const VectorXd& beta_ext, size_t individuals, size_t clusters, size_t loci) {\n  size_t idx = 0;\n  \n  for (size_t k = 0; k < loci; k++) {\n    double b_k = beta_ext[clusters + k];\n    \n    for (size_t j = 0; j < clusters; j++) {\n      double b_j = beta_ext[j];\n      \n      double bj_bk = b_j + b_k;\n      \n      for (size_t i = 0; i < individuals; i++) {\n        lin_pred[idx] = bj_bk;\n        idx += 1;      \n      }\n    }\n  }  \n}\n\nbool deviance_converged(const std::vector<MatrixXi>& d, const std::vector<MatrixXd>& w, \n  bool& deviance_calculated,\n  VectorXd& lin_pred, const VectorXd& beta, double& deviance, double& old_deviance, double eps_deviance, \n  size_t individuals, size_t clusters, size_t loci, bool verbose) {\n\n  VectorXd beta_ext = get_beta_extended(beta);\n    \n  update_lin_pred(lin_pred, beta_ext, individuals, clusters, loci);\n  \n  double dev = 0;\n  \n  for (size_t i = 0; i < individuals; i++) {\n    MatrixXi d_i = d[i];\n    MatrixXd w_i = w[i];\n\n    for (size_t j = 0; j < clusters; j++) {\n      double b_j = beta_ext[j];\n\n      for (size_t k = 0; k < loci; k++) {\n        double b_k = beta_ext[clusters + k];\n        \n        double eta = b_j + b_k;\n        double mu = linkinv(eta);\n        int d_ele = d_i(j, k);\n        \n        double dev_contrib = 0.0;\n\n        if (d_ele == 0) {  \n          // y == 0: dev = 2*log((1+p)/(1-p))\n          double p = (mu < 1e-6) ? 0.5 * mu : (sqrt(1.0 + mu * mu) - 1.0) / mu;\n          dev_contrib = 2 * log((1.0 + p) / (1.0 - p));\n        } else {\n          // y != 0\n          double d_ele_double = (double)d_ele;\n          dev_contrib = 2 * (loglikeh(d_ele_double, d_ele_double) - loglikeh(mu, d_ele_double));\n        }\n        \n        dev_contrib *= w_i(j, k);\n        dev += dev_contrib;\n      }\n    }\n  }  \n\n  old_deviance = deviance;\n  deviance = dev;\n  deviance_calculated = true;\n  \n  double c = std::abs(dev - old_deviance)/(0.1 + std::abs(dev));\n  \n  if (verbose) {\n    OUTPUT << \"      Deviance convergence investigation:\" << std::endl;\n    OUTPUT << \"        deviance     = \" << dev << std::endl;\n  }\n\n  if (c < eps_deviance) {\n    if (verbose) {\n      OUTPUT << \"        criteria     = \" << c << \" < \" << eps_deviance << \" [CONVERGENCE]\" << std::endl;\n    }\n    \n    return true;\n  }\n\n  if (verbose) {\n    OUTPUT << \"        criteria     = \" << c << \" >= \" << eps_deviance << std::endl;\n  }\n  \n  return false;\n}\n\nbool beta_converged(const VectorXd& beta, const VectorXd& old_beta, double eps_beta, bool verbose) {\n  VectorXd den = 0.1 + beta.cwiseAbs().array();\n  VectorXd diff = beta - old_beta;\n  \n  double c = diff.cwiseAbs().cwiseQuotient(den).maxCoeff();\n\n  if (verbose) {\n    OUTPUT << \"      Beta convergence investigation:\" << std::endl;\n    OUTPUT << \"        beta         = \" << beta.transpose() << std::endl;\n  }\n    \n  if (c < eps_beta) {\n    if (verbose) {\n      OUTPUT << \"        criteria     = \" << c << \" < \" << eps_beta << \" [CONVERGENCE]\" << std::endl;\n    }\n    \n    return true;\n  }\n\n  if (verbose) {\n    OUTPUT << \"        criteria     = \" << c << \" >= \" << eps_beta << std::endl;\n  }\n  \n  return false;\n}\n\nvoid fill_generics(size_t clusters, size_t loci, VectorXd& beta_ext, \n  MatrixXd& lin_pred_generic, MatrixXd& mu_generic) {\n  \n  for (size_t j = 0; j < clusters; j++) {\n    double beta_j = beta_ext[j];\n    \n    for (size_t k = 0; k < loci; k++) {\n      double eta = beta_j + beta_ext[clusters + k];\n      lin_pred_generic(j, k) = eta;\n      mu_generic(j, k) = linkinv(eta);\n    }\n  }\n}\n\nvoid fill_H_ab(size_t individuals, size_t clusters, size_t loci,   \n  const std::vector<MatrixXi>& d, const std::vector<MatrixXd>& w, \n  const MatrixXd& mu_generic,\n  MatrixXd& H, MatrixXd& ab) {\n   \n  for (size_t i = 0; i < individuals; i++) {\n    MatrixXi d_i = d[i];\n    MatrixXd w_i = w[i];\n        \n    for (size_t j = 0; j < clusters; j++) {\n      for (size_t k = 0; k < loci; k++) {\n        double mu_generic_jk = mu_generic(j, k);\n        double w_ijk = w_i(j, k);\n        \n        // H\n        double psi_jk = w_ijk * varfunc(mu_generic_jk);\n        H(j, k) += psi_jk;\n\n        // ab\n        double d_mu_res = d_i(j, k) - mu_generic_jk;\n        ab(j, k) += w_ijk * d_mu_res;\n      }\n    }\n  }\n}\n\n/*\nvoid fill_H_ab(size_t individuals, size_t clusters, size_t loci,   \n  const std::vector<MatrixXi>& d, const std::vector<MatrixXd>& w, \n  const MatrixXd& mu_generic,\n  MatrixXd& H, MatrixXd& ab) {\n  \n  // varfunc(double mu) = mu * sqrt(1.0 + mu*mu)\n  MatrixXd mu_1_sq = mu_generic.array().square() + 1;\n  MatrixXd mu_sqrt_1_sq = mu_1_sq.cwiseSqrt();\n  MatrixXd mu_varfunc = mu_generic.cwiseProduct(mu_sqrt_1_sq);\n   \n  for (size_t i = 0; i < individuals; i++) {\n    MatrixXi d_i = d[i];\n    MatrixXd w_i = w[i];\n    MatrixXd d_mu = d_i.cast<double>().array() - mu_generic.array();\n    \n    H = H.array() + w_i.cwiseProduct(mu_varfunc).array();\n    ab = ab.array() + w_i.cwiseProduct(d_mu).array();\n  }\n}\n*/\n\nvoid update_beta(const std::vector<MatrixXi>& d, const std::vector<MatrixXd>& w, VectorXd& beta, \n  MatrixXd& vcov, \n  size_t individuals, size_t clusters, size_t loci, bool verbose) {\n  \n  VectorXd beta_ext = get_beta_extended(beta);\n  MatrixXd lin_pred_generic(clusters, loci);\n  MatrixXd mu_generic(clusters, loci);\n  fill_generics(clusters, loci, beta_ext, lin_pred_generic, mu_generic);\n  \n  MatrixXd H = MatrixXd::Zero(clusters, loci);\n  MatrixXd ab = MatrixXd::Zero(clusters, loci);\n  fill_H_ab(individuals, clusters, loci, d, w, mu_generic, H, ab);\n  \n  VectorXd Drvec_raw = H.colwise().sum();\n  VectorXd Drvec(loci - 1);\n  for (size_t k = 0; k < (loci - 1); k++) {\n    Drvec[k] = Drvec_raw[k];\n  }  \n  MatrixXd Dr = Drvec.asDiagonal();\n  \n  VectorXd Dcinvvec(clusters);\n  for (size_t j = 0; j < clusters; j++) {\n    Dcinvvec[j] = 1 / H.row(j).sum();\n  }\n  MatrixXd Dcinv = Dcinvvec.asDiagonal();\n\n  H.conservativeResize(NoChange, loci - 1);\n  \n  MatrixXd E = Dr - H.transpose() * Dcinv * H;\n  MatrixXd Einv = E.lu().solve(MatrixXd::Identity(loci - 1, loci - 1));\n  MatrixXd F = Dcinv * H;\n  MatrixXd Ft = F.transpose(); \n  \n  /*\n  OUTPUT << \"H:\" << std::endl << H << std::endl;\n  OUTPUT << \"Dr:\" << std::endl << Dr << std::endl;\n  OUTPUT << \"Dcinv:\" << std::endl << Dcinv << std::endl;\n  OUTPUT << \"E:\" << std::endl << E << std::endl;\n  OUTPUT << \"Einv:\" << std::endl << Einv << std::endl;\n  OUTPUT << \"F:\" << std::endl << F << std::endl;\n  OUTPUT << \"Ft:\" << std::endl << Ft << std::endl;\n  */\n  \n  MatrixXd P = MatrixXd::Zero(clusters + loci - 1, clusters + loci - 1);\n  P.topLeftCorner(clusters, clusters) = Dcinv + (F * Einv) * Ft;\n  P.topRightCorner(clusters, loci - 1) = -F * Einv;\n  P.bottomLeftCorner(loci - 1, clusters) = -Einv * Ft;\n  P.bottomRightCorner(loci - 1, loci - 1) = Einv;  \n  \n  vcov = P;\n\n  VectorXd a = ab.rowwise().sum();  \n  VectorXd b = ab.colwise().sum();  \n  VectorXd gamma(clusters + loci - 1);\n  \n  for (size_t j = 0; j < clusters; j++) {\n    gamma[j] = a[j];\n  }\n  \n  for (size_t k = 0; k < (loci - 1); k++) {\n    gamma[clusters + k] = b[k];\n  }\n  \n  VectorXd beta_correction = P * gamma;\n  \n  beta = beta + beta_correction;\n}\n\n/*\n// iter >= ensures old_deviance has been calculated\nif (deviance_calculated && iter >= 2 && !isinf(old_deviance) && old_deviance < dev) {\n  OUTPUT << \"old_deviance = \" << old_deviance << std::endl;\n  OUTPUT << \"dev          = \" << dev << std::endl;\n  throw \"Deviance increased! Normally step-halving would be tried, but it has yet to be implemented...\";\n}\n*/\n\n/*\nReturns true if converged, false otherwise\n*/\nbool irls(const std::vector<MatrixXi>& d, const std::vector<MatrixXd>& w, \n  VectorXd& beta, VectorXd& lin_pred, \n  MatrixXd& vcov,\n  double& deviance, size_t& iterations,\n  bool verbose = true, size_t maxit = 25, \n  bool use_deviance = true, double eps_deviance = 1e-6, \n  bool use_beta = true, double eps_beta = 1e-6,\n  bool force_calculate_deviance = false) {\n\n  check_input(d, w, beta, maxit, use_deviance, eps_deviance, use_beta, eps_beta);\n\n  assert(maxit > 0);  \n  assert(!use_deviance || (use_deviance && eps_deviance > 0));\n  assert(!use_beta || (use_beta && eps_beta > 0));\n  \n  size_t individuals = d.size();\n  assert(individuals > 0);\n  assert(w.size() == individuals);\n\n  size_t clusters = d.at(0).rows();\n  size_t loci = d.at(0).cols();\n  \n  bool converged = false;\n  \n  bool deviance_calculated = false;\n  double dev = std::numeric_limits<double>::infinity();\n  double old_deviance = std::numeric_limits<double>::infinity();\n  \n  VectorXd start_beta = VectorXd(beta);\n  \n  VectorXd old_beta(beta.size());\n  for (size_t idx = 0; idx < old_beta.size(); idx++) {\n    old_beta[idx] = std::numeric_limits<double>::infinity();\n  }\n\n  if (verbose) {\n    OUTPUT << \"    Initial coefficients = \" << beta.transpose() << std::endl;\n  }\n  \n  iterations = 0;\n  \n  for (size_t iter = 0; iter < maxit; iter++) {\n    iterations = iterations + 1;\n\n    if (verbose) {\n      OUTPUT << \"    IRLS iteration \" << (iter + 1) << std::endl;\n    }\n    \n    if (use_deviance && use_beta) {\n      bool beta_conv = beta_converged(beta, old_beta, eps_beta, verbose);\n      \n      if (beta_conv) {\n        bool dev_conv = deviance_converged(d, w, deviance_calculated, lin_pred, beta, dev, old_deviance, eps_deviance, individuals, clusters, loci, verbose);\n        \n        if (dev_conv) {\n          converged = true;\n          break;\n        }\n      }\n    } else if (use_deviance) {\n      bool dev_conv = deviance_converged(d, w, deviance_calculated, lin_pred, beta, dev, old_deviance, eps_deviance, individuals, clusters, loci, verbose);\n      \n      if (dev_conv) {\n        converged = true;\n        break;\n      }\n    } else if (use_beta) {\n      bool beta_conv = beta_converged(beta, old_beta, eps_beta, verbose);\n      \n      if (beta_conv) {\n        converged = true;\n        break;      \n      }\n    } else {\n      throw \"Unexpected error (!use_deviance && !use_beta)\";\n    }\n    \n    old_beta = beta;\n    update_beta(d, w, beta, vcov, individuals, clusters, loci, verbose);\n    \n    #if defined(DISCLAPMIX_USED_IN_R)\n    R_CheckUserInterrupt();\n    #endif\n  }\n  \n  if (!deviance_calculated) {\n    if (force_calculate_deviance) {\n      deviance_converged(d, w, deviance_calculated, lin_pred, beta, dev, old_deviance, eps_deviance, individuals, clusters, loci, false);\n    }\n  }\n\n  deviance = dev;\n  \n  return converged;\n}\n\n", "meta": {"hexsha": "80b00c98d786297d647179dfa378442e4e7bd93a", "size": 10808, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/irls.cpp", "max_stars_repo_name": "mikldk/libdisclapmix2", "max_stars_repo_head_hexsha": "fd5097096094345fa83ac34ba98b14aa233cc00b", "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/irls.cpp", "max_issues_repo_name": "mikldk/libdisclapmix2", "max_issues_repo_head_hexsha": "fd5097096094345fa83ac34ba98b14aa233cc00b", "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/irls.cpp", "max_forks_repo_name": "mikldk/libdisclapmix2", "max_forks_repo_head_hexsha": "fd5097096094345fa83ac34ba98b14aa233cc00b", "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.2899728997, "max_line_length": 184, "alphanum_fraction": 0.5932642487, "num_tokens": 3335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5089558805768285}}
{"text": "// Copyright  (C)  2007  Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n\n// Version: 1.0\n// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// URL: http://www.orocos.org/kdl\n\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 2.1 of the License, or (at your option) any later version.\n\n// This library 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 GNU\n// Lesser General Public License for more details.\n\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n\n//Based on the svd of the KDL-0.2 library by Erwin Aertbelien\n#ifndef SVD_EIGEN_HH_HPP\n#define SVD_EIGEN_HH_HPP\n\n\n#include <Eigen/Array>\n#include <algorithm>\n\nnamespace KDL\n{\n    template<typename Scalar> inline Scalar PYTHAG(Scalar a,Scalar b) {\n        double at,bt,ct;\n        at = fabs(a);\n        bt = fabs(b);\n        if (at > bt ) {\n            ct=bt/at;\n            return Scalar(at*sqrt(1.0+ct*ct));\n        } else {\n            if (bt==0)\n                return Scalar(0.0);\n            else {\n                ct=at/bt;\n                return Scalar(bt*sqrt(1.0+ct*ct));\n            }\n        }\n    }\n\n\n    template<typename Scalar> inline Scalar SIGN(Scalar a,Scalar b) {\n        return ((b) >= Scalar(0.0) ? fabs(a) : -fabs(a));\n    }\n\n    /**\n     * svd calculation of boost ublas matrices\n     *\n     * @param A matrix<double>(mxn)\n     * @param U matrix<double>(mxn)\n     * @param S vector<double> n\n     * @param V matrix<double>(nxn)\n     * @param tmp vector<double> n\n     * @param maxiter defaults to 150\n     *\n     * @return -2 if maxiter exceeded, 0 otherwise\n     */\n\ttemplate<typename MatrixA, typename MatrixUV, typename VectorS> \n\tint svd_eigen_HH(\n\t\tconst Eigen::MatrixBase<MatrixA>&\t\tA,\n\t\tEigen::MatrixBase<MatrixUV>&\t\t\tU,\n\t\tEigen::MatrixBase<VectorS>&\t\t\t\tS,\n\t\tEigen::MatrixBase<MatrixUV>&\t\t\tV,\n\t\tEigen::MatrixBase<VectorS>&\t\t\t\ttmp,\n\t\tint maxiter=150)\n\t{\n        //get the rows/columns of the matrix\n        const int rows = A.rows();\n        const int cols = A.cols();\n        \n        U = A;\n        \n        int i(-1),its(-1),j(-1),jj(-1),k(-1),nm=0;\n        int ppi(0);\n        bool flag;\n        e_scalar maxarg1,maxarg2,anorm(0),c(0),f(0),h(0),s(0),scale(0),x(0),y(0),z(0),g(0);\n        \n        g=scale=anorm=e_scalar(0.0);\n        \n        /* Householder reduction to bidiagonal form. */\n        for (i=0;i<cols;i++) {\n            ppi=i+1;\n            tmp(i)=scale*g;\n            g=s=scale=e_scalar(0.0); \n            if (i<rows) {\n                // compute the sum of the i-th column, starting from the i-th row\n                for (k=i;k<rows;k++) scale += fabs(U(k,i));\n                if (scale!=0) {\n                    // multiply the i-th column by 1.0/scale, start from the i-th element\n                    // sum of squares of column i, start from the i-th element\n                    for (k=i;k<rows;k++) {\n                        U(k,i) /= scale;\n                        s += U(k,i)*U(k,i);\n                    }\n                    f=U(i,i);  // f is the diag elem\n                    g = -SIGN(e_scalar(sqrt(s)),f);\n                    h=f*g-s;\n                    U(i,i)=f-g;\n                    for (j=ppi;j<cols;j++) {\n                        // dot product of columns i and j, starting from the i-th row\n                        for (s=0.0,k=i;k<rows;k++) s += U(k,i)*U(k,j);\n                        f=s/h;\n                        // copy the scaled i-th column into the j-th column\n                        for (k=i;k<rows;k++) U(k,j) += f*U(k,i);\n                    }\n                    for (k=i;k<rows;k++) U(k,i) *= scale;\n                }\n            }\n            // save singular value\n            S(i)=scale*g;\n            g=s=scale=e_scalar(0.0);\n            if ((i <rows) && (i+1 != cols)) {\n                // sum of row i, start from columns i+1\n                for (k=ppi;k<cols;k++) scale += fabs(U(i,k));\n                if (scale!=0) {\n                    for (k=ppi;k<cols;k++) {\n                        U(i,k) /= scale;\n                        s += U(i,k)*U(i,k);\n                    }\n                    f=U(i,ppi);\n                    g = -SIGN(e_scalar(sqrt(s)),f);\n                    h=f*g-s;\n                    U(i,ppi)=f-g;\n                    for (k=ppi;k<cols;k++) tmp(k)=U(i,k)/h;\n                    for (j=ppi;j<rows;j++) {\n                        for (s=0.0,k=ppi;k<cols;k++) s += U(j,k)*U(i,k);\n                        for (k=ppi;k<cols;k++) U(j,k) += s*tmp(k);\n                    }\n                    for (k=ppi;k<cols;k++) U(i,k) *= scale;\n                }\n            }\n            maxarg1=anorm;\n            maxarg2=(fabs(S(i))+fabs(tmp(i)));\n            anorm = maxarg1 > maxarg2 ?\tmaxarg1 : maxarg2;\t\t\n        }\n        /* Accumulation of right-hand transformations. */\n        for (i=cols-1;i>=0;i--) {\n            if (i<cols-1) {\n                if (g) {\n                    for (j=ppi;j<cols;j++) V(j,i)=(U(i,j)/U(i,ppi))/g;\n                    for (j=ppi;j<cols;j++) {\n                        for (s=0.0,k=ppi;k<cols;k++) s += U(i,k)*V(k,j);\n                        for (k=ppi;k<cols;k++) V(k,j) += s*V(k,i);\n                    }\n                }\n                for (j=ppi;j<cols;j++) V(i,j)=V(j,i)=0.0;\n            }\n            V(i,i)=1.0;\n            g=tmp(i);\n            ppi=i;\n        }\n        /* Accumulation of left-hand transformations. */\n        for (i=cols-1<rows-1 ? cols-1:rows-1;i>=0;i--) {\n            ppi=i+1;\n            g=S(i);\n            for (j=ppi;j<cols;j++) U(i,j)=0.0;\n            if (g) {\n                g=e_scalar(1.0)/g;\n                for (j=ppi;j<cols;j++) {\n                    for (s=0.0,k=ppi;k<rows;k++) s += U(k,i)*U(k,j);\n                    f=(s/U(i,i))*g;\n                    for (k=i;k<rows;k++) U(k,j) += f*U(k,i);\n                }\n                for (j=i;j<rows;j++) U(j,i) *= g;\n            } else {\n                for (j=i;j<rows;j++) U(j,i)=0.0;\n            }\n            ++U(i,i);\n        }\n        \n        /* Diagonalization of the bidiagonal form. */\n        for (k=cols-1;k>=0;k--) { /* Loop over singular values. */\n            for (its=1;its<=maxiter;its++) {  /* Loop over allowed iterations. */\n                flag=true;\n                for (ppi=k;ppi>=0;ppi--) {  /* Test for splitting. */\n                    nm=ppi-1;             /* Note that tmp(1) is always zero. */\n                    if ((fabs(tmp(ppi))+anorm) == anorm) {\n                        flag=false;\n                        break;\n                    }\n                    if ((fabs(S(nm)+anorm) == anorm)) break;\n                }\n                if (flag) {\n                    c=e_scalar(0.0);           /* Cancellation of tmp(l), if l>1: */\n                    s=e_scalar(1.);\n                    for (i=ppi;i<=k;i++) {\n                        f=s*tmp(i);\n                        tmp(i)=c*tmp(i);\n                        if ((fabs(f)+anorm) == anorm) break;\n                        g=S(i);\n                        h=PYTHAG(f,g);\n                        S(i)=h;\n                        h=e_scalar(1.0)/h;\n                        c=g*h;\n                        s=(-f*h);\n                        for (j=0;j<rows;j++) {\n                            y=U(j,nm);\n                            z=U(j,i);\n                            U(j,nm)=y*c+z*s;\n                            U(j,i)=z*c-y*s;\n                        }\n                    }\n                }\n                z=S(k);\n                \n                if (ppi == k) {       /* Convergence. */\n                    if (z < e_scalar(0.0)) {   /* Singular value is made nonnegative. */\n                        S(k) = -z;\n                        for (j=0;j<cols;j++) V(j,k)=-V(j,k);\n                    }\n                    break;\n                }\n                \n                x=S(ppi);            /* Shift from bottom 2-by-2 minor: */\n                nm=k-1;\n                y=S(nm);\n                g=tmp(nm);\n                h=tmp(k);\n                f=((y-z)*(y+z)+(g-h)*(g+h))/(e_scalar(2.0)*h*y);\n                \n                g=PYTHAG(f,e_scalar(1.0));\n                f=((x-z)*(x+z)+h*((y/(f+SIGN(g,f)))-h))/x;\n                \n                /* Next QR transformation: */\n                c=s=1.0;\n                for (j=ppi;j<=nm;j++) {\n                    i=j+1;\n                    g=tmp(i);\n                    y=S(i);\n                    h=s*g;\n                    g=c*g;\n                    z=PYTHAG(f,h);\n                    tmp(j)=z;\n                    c=f/z;\n                    s=h/z;\n                    f=x*c+g*s;\n                    g=g*c-x*s;\n                    h=y*s;\n                    y=y*c;\n                    for (jj=0;jj<cols;jj++) {\n                        x=V(jj,j);\n                        z=V(jj,i);\n                        V(jj,j)=x*c+z*s;\n                        V(jj,i)=z*c-x*s;\n                    }\n                    z=PYTHAG(f,h);\n                    S(j)=z;\n                    if (z) {\n                        z=e_scalar(1.0)/z;\n                        c=f*z;\n                        s=h*z;\n                    }\n                    f=(c*g)+(s*y);\n                    x=(c*y)-(s*g);\n                    for (jj=0;jj<rows;jj++) {\n                        y=U(jj,j);\n                        z=U(jj,i);\n                        U(jj,j)=y*c+z*s;\n                        U(jj,i)=z*c-y*s;\n                    }\n                }\n                tmp(ppi)=0.0;\n                tmp(k)=f;\n                S(k)=x;\n            }\n        }\n\n        //Sort eigen values:\n        for (i=0; i<cols; i++){\n            \n            double S_max = S(i);\n            int i_max = i;\n            for (j=i+1; j<cols; j++){\n                double Sj = S(j);\n                if (Sj > S_max){\n                    S_max = Sj;\n                    i_max = j;\n                }\n            }\n            if (i_max != i){\n                /* swap eigenvalues */\n                e_scalar tmp = S(i);\n                S(i)=S(i_max);\n                S(i_max)=tmp;\n                \n                /* swap eigenvectors */\n                U.col(i).swap(U.col(i_max));\n                V.col(i).swap(V.col(i_max));\n            }\n        }\n        \n        \n        if (its == maxiter) \n            return (-2);\n        else \n            return (0);\n    }\n\n}\n#endif\n", "meta": {"hexsha": "2bbb8df521f194cffb7e26813efaaaa8645b803a", "size": 10775, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "intern/itasc/kdl/utilities/svd_eigen_HH.hpp", "max_stars_repo_name": "wycivil08/blendocv", "max_stars_repo_head_hexsha": "f6cce83e1f149fef39afa8043aade9c64378f33e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T14:06:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T07:47:29.000Z", "max_issues_repo_path": "intern/itasc/kdl/utilities/svd_eigen_HH.hpp", "max_issues_repo_name": "ttagu99/blendocv", "max_issues_repo_head_hexsha": "f6cce83e1f149fef39afa8043aade9c64378f33e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-20T20:57:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-19T23:44:38.000Z", "max_forks_repo_path": "intern/itasc/kdl/utilities/svd_eigen_HH.hpp", "max_forks_repo_name": "ttagu99/blendocv", "max_forks_repo_head_hexsha": "f6cce83e1f149fef39afa8043aade9c64378f33e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-04-23T02:38:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-01T20:09:39.000Z", "avg_line_length": 34.7580645161, "max_line_length": 91, "alphanum_fraction": 0.369187935, "num_tokens": 2818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5089558749117631}}
{"text": "#include <boost/random/fisher_f_distribution.hpp>\n", "meta": {"hexsha": "f5c260c130d8c9a6b3df42633389a9e639228c5c", "size": 50, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_fisher_f_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_fisher_f_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_fisher_f_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.0, "max_line_length": 49, "alphanum_fraction": 0.84, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5089558692348811}}
{"text": "#pragma once\n\n#include \"spectral/hermiten_impl.hpp\"\n#include \"spectral_function_base.hpp\"\n#include \"spectral_weight_function.hpp\"\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <stdexcept>\n\n\nnamespace boltzmann {\n\nnamespace local_ {\nstruct hermite_id_t\n{\n private:\n  constexpr const static double FUZZY = 1e6;\n\n public:\n  typedef hermite_id_t id_t;\n\n  /// Default constructor\n  hermite_id_t()\n      : hermite_id_t(-1, std::nan(\"nan\"))\n  { /* empty */\n  }\n\n  hermite_id_t(int k_, double fw_)\n      : k(k_)\n      , fw(fw_)\n      , idw(FUZZY * fw_)\n  { /* empty */\n  }\n\n  hermite_id_t(const id_t &id)\n      : k(id.k)\n      , fw(id.fw)\n      , idw(id.idw)\n  {\n  }\n\n  /// degree\n  int k;\n  /// weight exponent\n  double fw;\n  /// weight id\n  long int idw;\n\n  bool operator<(const id_t &other) const\n  {\n    return std::tie(k, idw) < std::tie(other.k, other.idw);\n  }\n\n  // ----------------------------------------------------------------------\n  inline bool operator==(const id_t &other) const\n  {\n    return std::tie(k, idw) == std::tie(other.k, other.idw);\n  }\n\n  // ----------------------------------------------------------------------\n  friend std::ostream &operator<<(std::ostream &stream, const id_t &x)\n  {\n    stream << x.to_string();\n    return stream;\n  }\n\n  // ----------------------------------------------------------------------\n  std::string to_string() const\n  {\n    return \"H_\" + boost::lexical_cast<std::string>(k) + \", fw_\" +\n           boost::lexical_cast<std::string>(fw);\n  }\n\n  // ----------------------------------------------------------------------\n  inline std::tuple<int, long int> key() const { return std::make_tuple(k, idw); }\n};\n}  // end namespace local_\n}  // end namespace boltzmann\n\nnamespace std {\n// hash functions for id's\ntemplate <>\nclass hash<boltzmann::local_::hermite_id_t>\n{\n public:\n  size_t operator()(const boltzmann::local_::hermite_id_t &id) const\n  {\n    std::size_t current = std::hash<double>()(id.fw);\n    boost::hash_combine(current, std::hash<int>()(id.k));\n    return current;\n  }\n};\n}  // end namespace std\n\nnamespace boltzmann {\n\n/**\n * @brief Normalized physicists' Hermite polynomial\n *\n */\nclass HermiteH : public weighted<HermiteH, true>, public local_::index_policy<local_::hermite_id_t>\n{\n public:\n  typedef double numeric_t;\n\n public:\n  /**\n   * Hermite basis function with exp weight\n   *\n   * @param k\n   * @param w\n   *\n   * @return\n   */\n  explicit HermiteH(int k, double w = 0.5);\n  explicit HermiteH(const id_t &id)\n      : id_(id)\n  {\n  }\n  HermiteH(){};\n\n  /// evaluate polynomial part\n  numeric_t evaluate(double x) const;\n\n  /// evaluate weight\n  numeric_t weight(double x) const;\n\n  /// return weight\n  numeric_t w() const { return id_.fw; }\n\n  const id_t &get_id() const { return id_; }\n  unsigned int get_degree() const { return id_.k; }\n\n private:\n  id_t id_;\n};\n\n// ----------------------------------------------------------------------\ninline HermiteH::HermiteH(int k, double w)\n    : id_(k, w)\n{ /* empty */\n}\n\n// ----------------------------------------------------------------------\ninline typename HermiteH::numeric_t\nHermiteH::evaluate(double x) const\n{\n  return boost::math::hermiten(id_.k, x);\n}\n\n// ----------------------------------------------------------------------\ninline typename HermiteH::numeric_t\nHermiteH::weight(double x) const\n{\n  return std::exp(-x * x * id_.fw);\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "e3b388219cc578ea378c468f01ea9465c9ae09af", "size": 3408, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spectral/basis/spectral_function/hermite_polynomial.hpp", "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/basis/spectral_function/hermite_polynomial.hpp", "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/basis/spectral_function/hermite_polynomial.hpp", "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": 21.4339622642, "max_line_length": 99, "alphanum_fraction": 0.5419600939, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5089558692230636}}
{"text": "// Copyright (c) Dietmar Wolz.\r\n//\r\n// This source code is licensed under the MIT license found in the\r\n// LICENSE file in the root directory.\r\n\r\n// Eigen based implementation of active CMA-ES\r\n\r\n// Supports parallel fitness function evaluation. \r\n// \r\n// For expensive objective functions (e.g. machine learning parameter optimization) use the workers\r\n// parameter to parallelize objective function evaluation. The workers parameter should be limited\r\n// the population size because otherwize poulation update is delayed. \r\n\r\n// Derived from http://cma.gforge.inria.fr/cmaes.m which follows\r\n// https://www.researchgate.net/publication/227050324_The_CMA_Evolution_Strategy_A_Comparing_Review\r\n// Requires Eigen version >= 3.3.90 because new slicing capabilities are used, see\r\n// https://eigen.tuxfamily.org/dox-devel/group__TutorialSlicingIndexing.html\r\n// requires https://github.com/imneme/pcg-cpp\r\n\r\n#include <Eigen/Core>\r\n#include <Eigen/Eigenvalues>\r\n#include <iostream>\r\n#include <random>\r\n#include <float.h>\r\n#include <stdint.h>\r\n#include <ctime>\r\n#include \"pcg_random.hpp\"\r\n#include \"evaluator.h\"\r\n\r\nusing namespace std;\r\n\r\nnamespace acmaes {\r\n\r\nstatic ivec inverse(const ivec &indices) {\r\n    ivec inverse = ivec(indices.size());\r\n    for (int i = 0; i < indices.size(); i++)\r\n        inverse(indices(i)) = i;\r\n    return inverse;\r\n}\r\n\r\nstatic vec sequence(double start, double end, double step) {\r\n    int size = (int) ((end - start) / step + 1);\r\n    vec d(size);\r\n    double value = start;\r\n    for (int r = 0; r < size; r++) {\r\n        d(r) = value;\r\n        value += step;\r\n    }\r\n    return d;\r\n}\r\n\r\nclass AcmaesOptimizer {\r\n\r\npublic:\r\n\r\n    AcmaesOptimizer(long runid_, Fitness *fitfun_, int popsize_, int mu_,\r\n            const vec &guess_, const vec &inputSigma_, int maxEvaluations_,\r\n            double accuracy_, double stopfitness_,\r\n            int update_gap_, long seed) {\r\n        // runid used for debugging / logging\r\n        runid = runid_;\r\n        // fitness function to minimize\r\n        fitfun = fitfun_;\r\n        // initial guess for the arguments of the fitness function\r\n        guess = guess_;\r\n        // accuracy = 1.0 is default, > 1.0 reduces accuracy\r\n        accuracy = accuracy_;\r\n        // number of objective variables/problem dimension\r\n        dim = guess_.size();\r\n        // population size, offspring number. The primary strategy parameter to play\r\n        // with, which can be increased from its default value. Increasing the\r\n        // population size improves global search properties in exchange to speed.\r\n        // Speed decreases, as a rule, at most linearly with increasing population\r\n        // size. It is advisable to begin with the default small population size.\r\n        if (popsize_ > 0)\r\n            popsize = popsize_;\r\n        else\r\n            popsize = 4 + int(3. * log(dim));\r\n        // individual sigma values - initial search volume. inputSigma determines\r\n        // the initial coordinate wise standard deviations for the search. Setting\r\n        // SIGMA one third of the initial search region is appropriate.\r\n        if (inputSigma_.size() == 1)\r\n            inputSigma = vec::Constant(dim, inputSigma_[0]);\r\n        else\r\n            inputSigma = inputSigma_;\r\n        // overall standard deviation - search volume.\r\n        sigma = inputSigma.maxCoeff();\r\n        // termination criteria\r\n        // maximal number of evaluations allowed.\r\n        maxEvaluations = maxEvaluations_;\r\n        // limit for fitness value.\r\n        stopfitness = stopfitness_;\r\n        // stop if x-changes larger stopTolUpX.\r\n        stopTolUpX = 1e3 * sigma;\r\n        // stop if x-change smaller stopTolX.\r\n        stopTolX = 1e-11 * sigma * accuracy;\r\n        // stop if fun-changes smaller stopTolFun.\r\n        stopTolFun = 1e-12 * accuracy;\r\n        // stop if back fun-changes smaller stopTolHistFun.\r\n        stopTolHistFun = 1e-13 * accuracy;\r\n        // selection strategy parameters\r\n        // number of parents/points for recombination.\r\n        mu = mu_ > 0 ? mu_ : popsize / 2;\r\n        // array for weighted recombination.\r\n        weights = (log(sequence(1, mu, 1).array()) * -1.) + log(mu + 0.5);\r\n        double sumw = weights.sum();\r\n        double sumwq = weights.squaredNorm();\r\n        weights *= 1. / sumw;\r\n        // variance-effectiveness of sum w_i x_i.\r\n        mueff = sumw * sumw / sumwq;\r\n\r\n        // dynamic strategy parameters and constants\r\n        // cumulation constant.\r\n        cc = (4. + mueff / dim) / (dim + 4. + 2. * mueff / dim);\r\n        // cumulation constant for step-size.\r\n        cs = (mueff + 2.) / (dim + mueff + 3.);\r\n        // damping for step-size.\r\n        damps = (1. + 2. * std::max(0., sqrt((mueff - 1.) / (dim + 1.)) - 1.))\r\n                        * max(0.3,\r\n                                1. - // modification for short runs\r\n                                dim / (1e-6 + (maxEvaluations/popsize)))\r\n                                + cs; // minor increment\r\n        // learning rate for rank-one update.\r\n        ccov1 = 2. / ((dim + 1.3) * (dim + 1.3) + mueff);\r\n        // learning rate for rank-mu update'\r\n        ccovmu = min(1. - ccov1,\r\n                2. * (mueff - 2. + 1. / mueff)\r\n                / ((dim + 2.) * (dim + 2.) + mueff));\r\n        // expectation of ||N(0,I)|| == norm(randn(N,1)).\r\n        chiN = sqrt(dim) * (1. - 1. / (4. * dim) + 1 / (21. * dim * dim));\r\n        ccov1Sep = min(1., ccov1 * (dim + 1.5) / 3.);\r\n        ccovmuSep = min(1. - ccov1, ccovmu * (dim + 1.5) / 3.);\r\n        // lazy covariance update gap\r\n        lazy_update_gap =\r\n                update_gap_ >= 0 ?\r\n                        update_gap_ :\r\n                        1.0 / (ccov1 + ccovmu + 1e-23) / dim / 10.0;\r\n        // CMA internal values - updated each generation\r\n        // objective variables.\r\n        xmean = fitfun->encode(guess);\r\n        // evolution path.\r\n        pc = zeros(dim);\r\n        // evolution path for sigma.\r\n        ps = zeros(dim);\r\n        // norm of ps, stored for efficiency.\r\n        normps = ps.norm();\r\n        // coordinate system.\r\n        B = Eigen::MatrixXd::Identity(dim, dim);\r\n        // diagonal of sqrt(D), stored for efficiency.\r\n        diagD = inputSigma / sigma;\r\n        diagC = diagD.cwiseProduct(diagD);\r\n        // B*D, stored for efficiency.\r\n        BD = B.cwiseProduct(diagD.transpose().replicate(dim, 1));\r\n        // covariance matrix.\r\n        C = B * (Eigen::MatrixXd::Identity(dim, dim) * B.transpose());\r\n        // number of iterations.\r\n        iterations = 1;\r\n        // size of history queue of best values.\r\n        historySize = 10 + int(3. * 10. * dim / popsize);\r\n        // stop criteria\r\n        stop = 0;\r\n        // best value so far\r\n        bestValue = DBL_MAX;\r\n        // best parameters so far\r\n        bestX = guess;\r\n        // history queue of best values.\r\n        fitnessHistory = vec::Constant(historySize, DBL_MAX);\r\n        fitnessHistory(0) = bestValue;\r\n        rs = new pcg64(seed);\r\n    }\r\n\r\n    ~AcmaesOptimizer() {\r\n        delete rs;\r\n    }\r\n\r\n    // param zmean weighted row matrix of the gaussian random numbers generating the current offspring\r\n    // param xold xmean matrix of the previous generation\r\n    // return hsig flag indicating a small correction\r\n\r\n    bool updateEvolutionPaths(const vec &zmean, const vec &xold) {\r\n        ps = ps * (1. - cs) + ((B * zmean) * sqrt(cs * (2. - cs) * mueff));\r\n        normps = ps.norm();\r\n        bool hsig = normps / sqrt(1. - pow(1. - cs, 2. * iterations)) / chiN\r\n                < 1.4 + 2. / (dim + 1.);\r\n        pc *= (1. - cc);\r\n        if (hsig)\r\n            pc += (xmean - xold) * (sqrt(cc * (2. - cc) * mueff) / sigma);\r\n        return hsig;\r\n    }\r\n\r\n    // param hsig flag indicating a small correction\r\n    // param bestArx fitness-sorted matrix of the argument vectors producing the current offspring\r\n    // param arz unsorted matrix containing the gaussian random values of the current offspring\r\n    // param arindex indices indicating the fitness-order of the current offspring\r\n    // param xold xmean matrix of the previous generation\r\n\r\n    double updateCovariance(bool hsig, const mat &bestArx, const mat &arz,\r\n            const ivec &arindex, const mat &xold) {\r\n        double negccov = 0;\r\n        if (ccov1 + ccovmu > 0) {\r\n            mat arpos = (bestArx - xold.replicate(1, mu)) * (1. / sigma); // mu difference vectors\r\n            mat roneu = pc * pc.transpose() * ccov1;\r\n            // minor correction if hsig==false\r\n            double oldFac = hsig ? 0 : ccov1 * cc * (2. - cc);\r\n            oldFac += 1. - ccov1 - ccovmu;\r\n            // Adapt covariance matrix C active CMA\r\n            negccov = (1. - ccovmu) * 0.25 * mueff\r\n                    / (pow(dim + 2., 1.5) + 2. * mueff);\r\n            double negminresidualvariance = 0.66;\r\n            // keep at least 0.66 in all directions, small popsize are most critical\r\n            double negalphaold = 0.5; // where to make up for the variance loss,\r\n            // prepare vectors, compute negative updating matrix Cneg\r\n            ivec arReverseIndex = arindex.reverse();\r\n            mat arzneg = arz(Eigen::all, arReverseIndex.head(mu));\r\n            vec arnorms = arzneg.colwise().norm();\r\n            ivec idxnorms = sort_index(arnorms);\r\n            vec arnormsSorted = arnorms(idxnorms);\r\n            ivec idxReverse = idxnorms.reverse();\r\n            vec arnormsReverse = arnorms(idxReverse);\r\n            arnorms = arnormsReverse.cwiseQuotient(arnormsSorted);\r\n            vec arnormsInv = arnorms(inverse(idxnorms));\r\n            mat sqarnw = arnormsInv.cwiseProduct(arnormsInv).transpose()\r\n                            * weights;\r\n            double negcovMax = (1. - negminresidualvariance) / sqarnw(0);\r\n            if (negccov > negcovMax)\r\n                negccov = negcovMax;\r\n            arzneg = arzneg.cwiseProduct(\r\n                    arnormsInv.transpose().replicate(dim, 1));\r\n            mat artmp = BD * arzneg;\r\n            mat Cneg = artmp * weights.asDiagonal() * artmp.transpose();\r\n            oldFac += negalphaold * negccov;\r\n            C = (C * oldFac) + roneu\r\n                    + (arpos * (ccovmu + (1. - negalphaold) * negccov)\r\n                            * weights.replicate(1, dim).cwiseProduct(\r\n                                    arpos.transpose())) - (Cneg * negccov);\r\n        }\r\n        return negccov;\r\n    }\r\n\r\n    // Update B and diagD from C\r\n    // param negccov Negative covariance factor.\r\n\r\n    void updateBD(double negccov) {\r\n\r\n        if (ccov1 + ccovmu + negccov > 0\r\n                && (std::fmod(iterations,\r\n                        1. / (ccov1 + ccovmu + negccov) / dim / 10.)) < 1.) {\r\n            // to achieve O(N^2) enforce symmetry to prevent complex numbers\r\n            mat triC = C.triangularView<Eigen::Upper>();\r\n            mat triC1 = C.triangularView<Eigen::StrictlyUpper>();\r\n            C = triC + triC1.transpose();\r\n            Eigen::SelfAdjointEigenSolver<mat> sades;\r\n            sades.compute(C);\r\n            // diagD defines the scaling\r\n            diagD = sades.eigenvalues();\r\n            B = sades.eigenvectors();\r\n            if (diagD.minCoeff() <= 0) {\r\n                for (int i = 0; i < dim; i++)\r\n                    if (diagD(i, 0) < 0)\r\n                        diagD(i, 0) = 0.;\r\n                double tfac = diagD.maxCoeff() / 1e14;\r\n                C += Eigen::MatrixXd::Identity(dim, dim) * tfac;\r\n                diagD += vec::Constant(dim, 1.0) * tfac;\r\n            }\r\n            if (diagD.maxCoeff() > 1e14 * diagD.minCoeff()) {\r\n                double tfac = diagD.maxCoeff() / 1e14 - diagD.minCoeff();\r\n                C += Eigen::MatrixXd::Identity(dim, dim) * tfac;\r\n                diagD += vec::Constant(dim, 1.0) * tfac;\r\n            }\r\n            diagC = C.diagonal();\r\n            diagD = diagD.cwiseSqrt(); // D contains standard deviations now\r\n            BD = B.cwiseProduct(diagD.transpose().replicate(dim, 1));\r\n        }\r\n    }\r\n\r\n    void newArgs() {\r\n        // generate popsize offspring.\r\n        xmean = fitfun->getClosestFeasible(xmean);\r\n        arz = normal(dim, popsize, *rs);\r\n        arx = mat(dim, popsize);\r\n        for (int k = 0; k < popsize; k++) {\r\n            vec delta = (BD * arz.col(k)) * sigma;\r\n            arx.col(k) = fitfun->getClosestFeasible(xmean + delta);\r\n        }\r\n        fitness = vec(popsize);\r\n    }\r\n\r\n    vec ask() {\r\n        // ask for one new argument vector.\r\n        vec arz1 = normalVec(dim, *rs);\r\n        vec delta = (BD * arz1) * sigma;\r\n        vec arx1 = fitfun->getClosestFeasible(xmean + delta);\r\n        return fitfun->decode(arx1);\r\n    }\r\n\r\n    int tell(double y, const vec &x) {\r\n        //tell function value for a argument list retrieved by ask_one().\r\n        if (told == 0) {\r\n            fitness = vec(popsize);\r\n            arx = mat(dim, popsize);\r\n            arz = mat(dim, popsize);\r\n        }\r\n        fitness[told] = isfinite(y) ? y : DBL_MAX;\r\n        arx.col(told) = fitfun->encode(x);\r\n        told++;\r\n\r\n        if (told >= popsize) {\r\n            xmean = fitfun->getClosestFeasible(xmean);\r\n            try {\r\n                arz = (BD.inverse()\r\n                        * ((arx - xmean.replicate(1, popsize)) / sigma));\r\n            } catch (std::exception &e) {\r\n                arz = normal(dim, popsize, *rs);\r\n            }\r\n            updateCMA();\r\n            told = 0;\r\n            iterations += 1;\r\n        }\r\n        return stop;\r\n    }\r\n\r\n    void updateCMA() {\r\n        // sort by fitness and compute weighted mean into xmean\r\n        ivec arindex = sort_index(fitness);\r\n        // calculate new xmean, this is selection and recombination\r\n        vec xold = xmean; // for speed up of Eq. (2) and (3)\r\n        ivec bestIndex = arindex.head(mu);\r\n        mat bestArx = arx(Eigen::all, bestIndex);\r\n        xmean = bestArx * weights;\r\n        mat bestArz = arz(Eigen::all, bestIndex);\r\n        mat zmean = bestArz * weights;\r\n        bool hsig = updateEvolutionPaths(zmean, xold);\r\n        // adapt step size sigma\r\n        sigma *= exp(min(1.0, (normps / chiN - 1.) * cs / damps));\r\n        double bestFitness = fitness(arindex(0));\r\n        double worstFitness = fitness(arindex(arindex.size() - 1));\r\n        if (bestValue > bestFitness) {\r\n            bestValue = bestFitness;\r\n            bestX = fitfun->decode(bestArx.col(0));\r\n            if (isfinite(stopfitness) && bestFitness < stopfitness) {\r\n                stop = 1;\r\n                return;\r\n            }\r\n        }\r\n        if (iterations >= last_update + lazy_update_gap) {\r\n            last_update = iterations;\r\n            double negccov = updateCovariance(hsig, bestArx, arz, arindex,\r\n                    xold);\r\n            updateBD(negccov);\r\n            // handle termination criteria\r\n            vec sqrtDiagC = diagC.cwiseSqrt();\r\n            vec pcCol = pc;\r\n            for (int i = 0; i < dim; i++) {\r\n                if (sigma * (max(abs(pcCol[i]), sqrtDiagC[i])) > stopTolX)\r\n                    break;\r\n                if (i >= dim - 1)\r\n                    stop = 2;\r\n            }\r\n            if (stop > 0)\r\n                return;\r\n            for (int i = 0; i < dim; i++)\r\n                if (sigma * sqrtDiagC[i] > stopTolUpX)\r\n                    stop = 3;\r\n            if (stop > 0)\r\n                return;\r\n        }\r\n        double historyBest = fitnessHistory.minCoeff();\r\n        double historyWorst = fitnessHistory.maxCoeff();\r\n        if (iterations > 2\r\n                && max(historyWorst, worstFitness)\r\n        - min(historyBest, bestFitness) < stopTolFun) {\r\n            stop = 4;\r\n            return;\r\n        }\r\n        if (iterations > fitnessHistory.size()\r\n                && historyWorst - historyBest < stopTolHistFun) {\r\n            stop = 5;\r\n            return;\r\n        }\r\n        // condition number of the covariance matrix exceeds 1e14\r\n        if (diagD.maxCoeff() / diagD.minCoeff() > 1e7 * 1.0 / sqrt(accuracy)) {\r\n            stop = 6;\r\n            return;\r\n        }\r\n        // adjust step size in case of equal function values (flat fitness)\r\n        if (bestValue == fitness[arindex[(int) (0.1 + popsize / 4.)]]) {\r\n            sigma *= exp(0.2 + cs / damps);\r\n        }\r\n        if (iterations > 2\r\n                && max(historyWorst, bestFitness)\r\n        - std::min(historyBest, bestFitness) == 0) {\r\n            sigma *= ::exp(0.2 + cs / damps);\r\n        }\r\n        // store best in history\r\n        for (int i = 1; i < fitnessHistory.size(); i++)\r\n            fitnessHistory[i] = fitnessHistory[i - 1];\r\n        fitnessHistory[0] = bestFitness;\r\n    }\r\n\r\n    void doOptimize() {\r\n\r\n        // -------------------- Generation Loop --------------------------------\r\n        for (iterations = 1; fitfun->evaluations() < maxEvaluations && !fitfun->terminate();\r\n                iterations++) {\r\n            // generate and evaluate popsize offspring\r\n            newArgs();\r\n            for (int k = 0; k < popsize; k++) {\r\n                fitness[k] = fitfun->eval(fitfun->decode(arx.col(k)))(0);\r\n                if (!isfinite(fitness[k]))\r\n                    fitness[k] = DBL_MAX;\r\n            }\r\n            updateCMA();\r\n            if (stop != 0)\r\n                return;\r\n        }\r\n    }\r\n\r\n    void do_optimize_delayed_update(int workers) {\r\n        iterations = 0;\r\n        fitfun->resetEvaluations();\r\n        evaluator eval(fitfun, 1, workers);\r\n        vec evals_x[workers];\r\n        // fill eval queue with initial population\r\n        for (int i = 0; i < workers; i++) {\r\n            vec x = ask();\r\n            eval.evaluate(x, i);\r\n            evals_x[i] = x;\r\n        }\r\n        while (fitfun->evaluations() < maxEvaluations) {\r\n            vec_id* vid = eval.result();\r\n            vec y = vec(vid->_v);\r\n            int p = vid->_id;\r\n            delete vid;\r\n            vec x = evals_x[p];\r\n            tell(y(0), x); // tell evaluated x\r\n            if (fitfun->evaluations() >= maxEvaluations)\r\n                break;\r\n            x = ask();\r\n            eval.evaluate(x, p);\r\n            evals_x[p] = x;\r\n        }\r\n    }\r\n\r\n    vec getBestX() {\r\n        return bestX;\r\n    }\r\n\r\n    double getBestValue() {\r\n        return bestValue;\r\n    }\r\n\r\n    double getIterations() {\r\n        return iterations;\r\n    }\r\n\r\n    int getStop() {\r\n        return stop;\r\n    }\r\n\r\n    Fitness* getFitfun() {\r\n        return fitfun;\r\n    }\r\n\r\n    int getDim() {\r\n        return dim;\r\n    }\r\n\r\nprivate:\r\n    long runid;\r\n    Fitness *fitfun;\r\n    vec guess;\r\n    double accuracy;\r\n    int popsize; // population size\r\n    vec inputSigma;\r\n    int dim;\r\n    int maxEvaluations;\r\n    double stopfitness;\r\n    double stopTolUpX;\r\n    double stopTolX;\r\n    double stopTolFun;\r\n    double stopTolHistFun;\r\n    int mu; //\r\n    vec weights;\r\n    double mueff; //\r\n    double sigma;\r\n    double cc;\r\n    double cs;\r\n    double damps;\r\n    double ccov1;\r\n    double ccovmu;\r\n    double chiN;\r\n    double ccov1Sep;\r\n    double ccovmuSep;\r\n    double lazy_update_gap = 0;\r\n    vec xmean;\r\n    vec pc;\r\n    vec ps;\r\n    double normps;\r\n    mat B;\r\n    mat BD;\r\n    mat diagD;\r\n    mat C;\r\n    vec diagC;\r\n    mat arz;\r\n    mat arx;\r\n    vec fitness;\r\n    int iterations = 0;\r\n    int last_update = 0;\r\n    vec fitnessHistory;\r\n    int historySize;\r\n    double bestValue;\r\n    vec bestX;\r\n    int stop;\r\n    int told = 0;\r\n    pcg64 *rs;\r\n};\r\n}\r\n\r\nusing namespace acmaes;\r\n\r\nextern \"C\" {\r\nvoid optimizeACMA_C(long runid, callback_type func, int dim,\r\n        double *init, double *lower, double *upper, double *sigma,\r\n        int maxEvals, double stopfitness, int mu, int popsize, double accuracy,\r\n        long seed, bool normalize, int update_gap, int workers, double* res) {\r\n    int n = dim;\r\n    vec guess(n), lower_limit(n), upper_limit(n), inputSigma(n);\r\n    bool useLimit = false;\r\n    for (int i = 0; i < n; i++) {\r\n        guess[i] = init[i];\r\n        inputSigma[i] = sigma[i];\r\n        lower_limit[i] = lower[i];\r\n        upper_limit[i] = upper[i];\r\n        useLimit |= (lower[i] != 0);\r\n        useLimit |= (upper[i] != 0);\r\n    }\r\n    if (useLimit == false) {\r\n        lower_limit.resize(0);\r\n        upper_limit.resize(0);\r\n    }\r\n    Fitness fitfun(func, n, 1, lower_limit, upper_limit);\r\n    fitfun.setNormalize(normalize);\r\n    AcmaesOptimizer opt(runid, &fitfun, popsize, mu, guess, inputSigma,\r\n            maxEvals, accuracy, stopfitness, update_gap, seed);\r\n    try {\r\n        if (workers <= 1)\r\n            opt.doOptimize();\r\n        else\r\n            opt.do_optimize_delayed_update(workers);\r\n        vec bestX = opt.getBestX();\r\n        double bestY = opt.getBestValue();\r\n        for (int i = 0; i < n; i++)\r\n            res[i] = bestX[i];\r\n        res[n] = bestY;\r\n        res[n + 1] = fitfun.evaluations();\r\n        res[n + 2] = opt.getIterations();\r\n        res[n + 3] = opt.getStop();\r\n    } catch (std::exception &e) {\r\n        cout << e.what() << endl;\r\n    }\r\n}\r\n}\r\n", "meta": {"hexsha": "3e7eac50630ecc9564a1fcc7cdd09bfa2a00e3c2", "size": 21002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_fcmaescpp/acmaesoptimizer.cpp", "max_stars_repo_name": "Slamim8/fast-cma-es", "max_stars_repo_head_hexsha": "4e6f8e8929a08a2e5d5588f8d87abeb60752e41c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_fcmaescpp/acmaesoptimizer.cpp", "max_issues_repo_name": "Slamim8/fast-cma-es", "max_issues_repo_head_hexsha": "4e6f8e8929a08a2e5d5588f8d87abeb60752e41c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_fcmaescpp/acmaesoptimizer.cpp", "max_forks_repo_name": "Slamim8/fast-cma-es", "max_forks_repo_head_hexsha": "4e6f8e8929a08a2e5d5588f8d87abeb60752e41c", "max_forks_repo_licenses": ["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.3037300178, "max_line_length": 103, "alphanum_fraction": 0.5273783449, "num_tokens": 5385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5089558692230636}}
{"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_OPERATIONS_INCLUDE\n#define MTL_OPERATIONS_INCLUDE\n\n#include <boost/numeric/mtl/operation/adjoint.hpp>\n#include <boost/numeric/mtl/operation/clone.hpp>\n#include <boost/numeric/mtl/operation/cholesky.hpp>\n#include <boost/numeric/mtl/operation/column_in_matrix.hpp>\n#include <boost/numeric/mtl/operation/conj.hpp>\n#include <boost/numeric/mtl/operation/copysign.hpp>\n#include <boost/numeric/mtl/operation/crop.hpp>\n#include <boost/numeric/mtl/operation/cross.hpp>\n#include <boost/numeric/mtl/operation/cuppen.hpp>\n#include <boost/numeric/mtl/operation/diagonal.hpp>\n#include <boost/numeric/mtl/operation/dot.hpp>\n#include <boost/numeric/mtl/operation/eigenvalue.hpp>\n#include <boost/numeric/mtl/operation/eigenvalue_symmetric.hpp>\n#include <boost/numeric/mtl/operation/entry1D.hpp>\n#include <boost/numeric/mtl/operation/entry_similar.hpp>\n#include <boost/numeric/mtl/operation/evaluate_lazy.hpp>\n#include <boost/numeric/mtl/operation/extended_complex.hpp>\n#include <boost/numeric/mtl/operation/fill.hpp>\n#include <boost/numeric/mtl/operation/fuse.hpp>\n#include <boost/numeric/mtl/operation/givens.hpp>\n#include <boost/numeric/mtl/operation/hermitian.hpp>\n#include <boost/numeric/mtl/operation/hessenberg.hpp>\n#include <boost/numeric/mtl/operation/householder.hpp>\n#include <boost/numeric/mtl/operation/imag.hpp>\n#include <boost/numeric/mtl/operation/inv.hpp>\n#include <boost/numeric/mtl/operation/invert_diagonal.hpp>\n#include <boost/numeric/mtl/operation/is_negative.hpp>\n#include <boost/numeric/mtl/operation/lazy.hpp>\n#include <boost/numeric/mtl/operation/left_scale_inplace.hpp>\n#include <boost/numeric/mtl/operation/lower_trisolve.hpp>\n#include <boost/numeric/mtl/operation/lu.hpp>\n#include <boost/numeric/mtl/operation/make_sparse.hpp>\n#include <boost/numeric/mtl/operation/make_tag_vector.hpp>\n#include <boost/numeric/mtl/operation/merge_complex_vector.hpp>\n#include <boost/numeric/mtl/operation/minimal_increase.hpp>\n#include <boost/numeric/mtl/operation/misc.hpp>\n#include <boost/numeric/mtl/operation/mult.hpp>\n#include <boost/numeric/mtl/operation/norms.hpp>\n#include <boost/numeric/mtl/operation/ones.hpp>\n#include <boost/numeric/mtl/operation/operators.hpp>\n#include <boost/numeric/mtl/operation/orth.hpp>\n#include <boost/numeric/mtl/operation/print.hpp>\n#include <boost/numeric/mtl/operation/product.hpp>\n#include <boost/numeric/mtl/operation/qr.hpp>\n#include <boost/numeric/mtl/operation/random.hpp>\n#include <boost/numeric/mtl/operation/rank_one_update.hpp>\n#include <boost/numeric/mtl/operation/rank_two_update.hpp>\n#include <boost/numeric/mtl/operation/real.hpp>\n#include <boost/numeric/mtl/operation/resource.hpp>\n#include <boost/numeric/mtl/operation/right_scale_inplace.hpp>\n#include <boost/numeric/mtl/operation/scale.hpp>\n#include <boost/numeric/mtl/operation/set_to_zero.hpp>\n#include <boost/numeric/mtl/operation/secular.hpp>\n#include <boost/numeric/mtl/operation/signum.hpp>\n#include <boost/numeric/mtl/operation/split_complex_vector.hpp>\n#include <boost/numeric/mtl/operation/sub_matrix.hpp>\n#include <boost/numeric/mtl/operation/sum.hpp>\n#include <boost/numeric/mtl/operation/min.hpp>\n#include <boost/numeric/mtl/operation/min_pos.hpp>\n#include <boost/numeric/mtl/operation/max.hpp>\n#include <boost/numeric/mtl/operation/max_pos.hpp>\n#include <boost/numeric/mtl/operation/max_abs_pos.hpp>\n#include <boost/numeric/mtl/operation/num_cols.hpp>\n#include <boost/numeric/mtl/operation/num_rows.hpp>\n#include <boost/numeric/mtl/operation/row_in_matrix.hpp>\n#include <boost/numeric/mtl/operation/size.hpp>\n#include <boost/numeric/mtl/operation/size1D.hpp>\n#include <boost/numeric/mtl/operation/static_num_cols.hpp>\n#include <boost/numeric/mtl/operation/static_num_rows.hpp>\n#include <boost/numeric/mtl/operation/static_size.hpp>\n#include <boost/numeric/mtl/operation/svd.hpp>\n#include <boost/numeric/mtl/operation/swap_row.hpp>\n#include <boost/numeric/mtl/operation/trace.hpp>\n#include <boost/numeric/mtl/operation/trans.hpp>\n#include <boost/numeric/mtl/operation/unary_dot.hpp>\n#include <boost/numeric/mtl/operation/unroll.hpp>\n#include <boost/numeric/mtl/operation/upper_trisolve.hpp>\n\n#include <boost/numeric/mtl/matrix/bands.hpp>\n#include <boost/numeric/mtl/matrix/identity.hpp>\n#include <boost/numeric/mtl/matrix/lower.hpp>\n#include <boost/numeric/mtl/matrix/permutation.hpp>\n#include <boost/numeric/mtl/matrix/reorder.hpp>\n#include <boost/numeric/mtl/matrix/reorder_ref.hpp>\n#include <boost/numeric/mtl/matrix/reorder_matrix_rows.hpp>\n#include <boost/numeric/mtl/matrix/strict_upper.hpp>\n#include <boost/numeric/mtl/matrix/strict_lower.hpp>\n#include <boost/numeric/mtl/matrix/upper.hpp>\n\n#include <boost/numeric/mtl/io/path.hpp>\n\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/string_to_enum.hpp>\n#include <boost/numeric/mtl/utility/make_copy_or_reference.hpp>\n\n#include <boost/numeric/mtl/interface/umfpack_solve.hpp>\n\n#endif // MTL_OPERATIONS_INCLUDE\n", "meta": {"hexsha": "57e1e447bab074564cb521e59137b4d98bfb160d", "size": 5371, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operations.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/operations.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/operations.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": 47.1140350877, "max_line_length": 94, "alphanum_fraction": 0.8007819773, "num_tokens": 1472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5089403822182711}}
{"text": "\n// #include <opencv2/core/core.hpp> // needed for verbosity >= 3, DISVISUAL\n// #include <opencv2/highgui/highgui.hpp> // needed for verbosity >= 3, DISVISUAL\n// #include <opencv2/imgproc/imgproc.hpp> // needed for verbosity >= 3, DISVISUAL\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <valarray>\n\n#include <thread>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Dense>\n\n#include <stdio.h>  \n\n#include \"patch.h\"\n#include \"patchgrid.h\"\n\n\nusing std::cout;\nusing std::endl;\nusing std::vector;\n\n\nnamespace OFC\n{\n    \n  PatGridClass::PatGridClass(\n    const camparam* cpt_in,\n    const camparam* cpo_in,\n    const optparam* op_in)\n  : \n    cpt(cpt_in),\n    cpo(cpo_in),\n    op(op_in)\n  {\n\n  // Generate grid on current scale\n  steps = op->steps;\n  nopw = ceil( (float)cpt->width /  (float)steps );\n  noph = ceil( (float)cpt->height / (float)steps );\n  const int offsetw = floor((cpt->width - (nopw-1)*steps)/2);\n  const int offseth = floor((cpt->height - (noph-1)*steps)/2);\n\n  nopatches = nopw*noph;\n  pt_ref.resize(nopatches);\n  p_init.resize(nopatches);\n  pat.reserve(nopatches);\n  \n  im_ao_eg = new Eigen::Map<const Eigen::MatrixXf>(nullptr,cpt->height,cpt->width);\n  im_ao_dx_eg = new Eigen::Map<const Eigen::MatrixXf>(nullptr,cpt->height,cpt->width);\n  im_ao_dy_eg = new Eigen::Map<const Eigen::MatrixXf>(nullptr,cpt->height,cpt->width);\n\n  im_bo_eg = new Eigen::Map<const Eigen::MatrixXf>(nullptr,cpt->height,cpt->width);\n  im_bo_dx_eg = new Eigen::Map<const Eigen::MatrixXf>(nullptr,cpt->height,cpt->width);\n  im_bo_dy_eg = new Eigen::Map<const Eigen::MatrixXf>(nullptr,cpt->height,cpt->width);\n\n  int patchid=0;\n  for (int x = 0; x < nopw; ++x)\n  {\n    for (int y = 0; y < noph; ++y)\n    {\n      int i = x*noph + y;\n\n      pt_ref[i][0] = x * steps + offsetw;\n      pt_ref[i][1] = y * steps + offseth;\n      p_init[i].setZero();\n      \n      pat.push_back(new OFC::PatClass(cpt, cpo, op, patchid));    \n      patchid++;\n    }\n  }\n}\n\nPatGridClass::~PatGridClass()\n{\n  delete im_ao_eg;\n  delete im_ao_dx_eg;\n  delete im_ao_dy_eg;\n\n  delete im_bo_eg;\n  delete im_bo_dx_eg;\n  delete im_bo_dy_eg;\n\n  for (int i=0; i< nopatches; ++i)\n    delete pat[i];\n}\n\nvoid PatGridClass::SetComplGrid(PatGridClass *cg_in)\n{\n  cg = cg_in;\n}\n\n\nvoid PatGridClass::InitializeGrid(const float * im_ao_in, const float * im_ao_dx_in, const float * im_ao_dy_in)\n{\n  im_ao = im_ao_in;\n  im_ao_dx = im_ao_dx_in;\n  im_ao_dy = im_ao_dy_in;\n  \n  new (im_ao_eg) Eigen::Map<const Eigen::MatrixXf>(im_ao,cpt->height,cpt->width); // new placement operator\n  new (im_ao_dx_eg) Eigen::Map<const Eigen::MatrixXf>(im_ao_dx,cpt->height,cpt->width);  \n  new (im_ao_dy_eg) Eigen::Map<const Eigen::MatrixXf>(im_ao_dy,cpt->height,cpt->width);  \n  \n  \n  #pragma omp parallel for schedule(static)\n  for (int i = 0; i < nopatches; ++i)\n  {\n    pat[i]->InitializePatch(im_ao_eg, im_ao_dx_eg, im_ao_dy_eg, pt_ref[i]);\n    p_init[i].setZero();    \n  }\n\n}\n\nvoid PatGridClass::SetTargetImage(const float * im_bo_in, const float * im_bo_dx_in, const float * im_bo_dy_in)\n{\n  im_bo = im_bo_in;\n  im_bo_dx = im_bo_dx_in;\n  im_bo_dy = im_bo_dy_in;\n  \n  new (im_bo_eg) Eigen::Map<const Eigen::MatrixXf>(im_bo,cpt->height,cpt->width); // new placement operator\n  new (im_bo_dx_eg) Eigen::Map<const Eigen::MatrixXf>(im_bo_dx,cpt->height,cpt->width); // new placement operator\n  new (im_bo_dy_eg) Eigen::Map<const Eigen::MatrixXf>(im_bo_dy,cpt->height,cpt->width); // new placement operator\n  \n  #pragma omp parallel for schedule(static)\n  for (int i = 0; i < nopatches; ++i)\n    pat[i]->SetTargetImage(im_bo_eg, im_bo_dx_eg, im_bo_dy_eg);\n  \n}\n\nvoid PatGridClass::Optimize()\n{\n    #pragma omp parallel for schedule(dynamic,10)\n    for (int i = 0; i < nopatches; ++i)\n    {\n      pat[i]->OptimizeIter(p_init[i], true); // optimize until convergence  \n    }\n}  \n\n// void PatGridClass::OptimizeAndVisualize(const float sc_fct_tmp) // needed for verbosity >= 3, DISVISUAL\n// {\n//   bool allconverged=0;\n//   int cnt = 0;\n//   while (!allconverged)\n//   {\n//     cnt++;\n// \n//     allconverged=1;\n// \n//     for (int i = 0; i < nopatches; ++i)\n//     {\n//       if (pat[i]->isConverged()==0)\n//       {\n//         pat[i]->OptimizeIter(p_init[i], false); // optimize, only one iterations\n//         allconverged=0;\n//       }\n//     }\n//     \n// \n//     // Display original image\n//     const cv::Mat src(cpt->height+2*cpt->imgpadding, cpt->width+2*cpt->imgpadding, CV_32FC1, (void*) im_ao);  \n//     cv::Mat img_ao_mat = src(cv::Rect(cpt->imgpadding,cpt->imgpadding,cpt->width,cpt->height));\n//     cv::Mat outimg;\n//     img_ao_mat.convertTo(outimg, CV_8UC1);\n//     cv::cvtColor(outimg, outimg, CV_GRAY2RGB);\n//     cv::resize(outimg, outimg, cv::Size(), sc_fct_tmp, sc_fct_tmp, cv::INTER_NEAREST);\n// \n//     for (int i = 0; i < nopatches; ++i)\n//     {\n//       // Show displacement vector\n//       const Eigen::Vector2f pt_ret = pat[i]->GetPointPos();\n//       \n//       Eigen::Vector2f pta, ptb;\n//       \n//       cv::line(outimg, cv::Point( (pt_ref[i][0]+.5)*sc_fct_tmp, (pt_ref[i][1]+.5)*sc_fct_tmp ), cv::Point( (pt_ret[0]+.5)*sc_fct_tmp, (pt_ret[1]+.5)*sc_fct_tmp ), cv::Scalar(255*pat[i]->isConverged() ,255*(!pat[i]->isConverged()),0),  2);\n//       \n//       cv::line(outimg, cv::Point( (cpt->cx+.5)*sc_fct_tmp, (cpt->cy+.5)*sc_fct_tmp ), cv::Point( (cpt->cx+.5)*sc_fct_tmp, (cpt->cy+.5)*sc_fct_tmp ), cv::Scalar(0,0, 255),  2);\n// \n//     }\n// \n//     char str[200];\n//     sprintf(str,\"Iter: %i\",cnt);\n//     cv::putText(outimg, str, cv::Point2f(20,20), cv::FONT_HERSHEY_PLAIN, 1,  cv::Scalar(0,0,255,255), 2);\n// \n//     cv::namedWindow( \"Img_iter\", cv::WINDOW_AUTOSIZE );\n//     cv::imshow( \"Img_iter\", outimg);\n//     \n//     cv::waitKey(500);\n//   }\n// } \n\nvoid PatGridClass::InitializeFromCoarserOF(const float * flow_prev)\n{\n  #pragma omp parallel for schedule(dynamic,10)\n  for (int ip = 0; ip < nopatches; ++ip)\n  {\n    int x = floor(pt_ref[ip][0] / 2); // better, but slower: use bil. interpolation here\n    int y = floor(pt_ref[ip][1] / 2); \n    int i = y*(cpt->width/2) + x;\n    \n    #if (SELECTMODE==1)\n    p_init[ip](0) = flow_prev[2*i  ]*2;\n    p_init[ip](1) = flow_prev[2*i+1]*2;\n    #else\n    p_init[ip](0) = flow_prev[  i  ]*2;      \n    #endif\n  }\n}\n\nvoid PatGridClass::AggregateFlowDense(float *flowout) const\n{\n  float* we = new float[cpt->width * cpt->height];\n  \n  memset(flowout, 0, sizeof(float) * (op->nop * cpt->width * cpt->height) );\n  memset(we,      0, sizeof(float) * (          cpt->width * cpt->height) );\n  \n  #ifdef USE_PARALLEL_ON_FLOWAGGR // Using this enables OpenMP on flow aggregation. This can lead to race conditions. Experimentally we found that the result degrades only marginally. However, for our experiments we did not enable this.\n    #pragma omp parallel for schedule(static)  \n  #endif\n  for (int ip = 0; ip < nopatches; ++ip)\n  {       \n    \n    if (pat[ip]->IsValid())\n    {\n      #if (SELECTMODE==1)\n      const Eigen::Vector2f*            fl = pat[ip]->GetParam(); // flow displacement of this patch\n      Eigen::Vector2f flnew;\n      #else\n      const Eigen::Matrix<float, 1, 1>* fl = pat[ip]->GetParam(); // horz. displacement of this patch\n      Eigen::Matrix<float, 1, 1> flnew;\n      #endif\n      \n      const float * pweight = pat[ip]->GetpWeightPtr(); // use image error as weight\n      \n      int lb = -op->p_samp_s/2;\n      int ub = op->p_samp_s/2-1;\n      \n      for (int y = lb; y <= ub; ++y)\n      {   \n        for (int x = lb; x <= ub; ++x, ++pweight)\n        {\n          int yt = (y + pt_ref[ip][1]);\n          int xt = (x + pt_ref[ip][0]);\n\n          if (xt >= 0 && yt >= 0 && xt < cpt->width && yt < cpt->height)\n          {\n  \n            int i = yt*cpt->width + xt;\n              \n            #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)  // single channel/gradient image \n            float absw = 1.0f /  (float)(std::max(op->minerrval  ,*pweight));\n            #else  // RGB image\n            float absw = (float)(std::max(op->minerrval  ,*pweight)); ++pweight;\n                  absw+= (float)(std::max(op->minerrval  ,*pweight)); ++pweight;\n                  absw+= (float)(std::max(op->minerrval  ,*pweight));\n            absw = 1.0f / absw;\n            #endif\n              \n            flnew = (*fl) * absw;\n            we[i] += absw;\n\n            #if (SELECTMODE==1)\n            flowout[2*i]   += flnew[0];\n            flowout[2*i+1] += flnew[1];\n            #else\n            flowout[i] += flnew[0]; \n            #endif\n          }\n        }\n      }\n    }\n  } \n  \n  // if complementary (forward-backward merging) is given, integrate negative backward flow as well\n  if (cg)\n  {  \n      Eigen::Vector4f wbil; // bilinear weight vector\n      Eigen::Vector4i pos;\n      \n      #ifdef USE_PARALLEL_ON_FLOWAGGR\n        #pragma omp parallel for schedule(static)  \n      #endif    \n      for (int ip = 0; ip < cg->nopatches; ++ip)\n      {\n        if (cg->pat[ip]->IsValid())\n        {\n          #if (SELECTMODE==1)\n          const Eigen::Vector2f*            fl = (cg->pat[ip]->GetParam()); // flow displacement of this patch\n          Eigen::Vector2f flnew;\n          #else\n          const Eigen::Matrix<float, 1, 1>* fl = (cg->pat[ip]->GetParam()); // horz. displacement of this patch\n          Eigen::Matrix<float, 1, 1> flnew;\n          #endif\n        \n          const Eigen::Vector2f rppos = cg->pat[ip]->GetPointPos(); // get patch position after optimization\n          const float * pweight = cg->pat[ip]->GetpWeightPtr(); // use image error as weight\n          \n          Eigen::Vector2f resid;\n\n          // compute bilinear weight vector\n          pos[0] = ceil(rppos[0] +.00001); // make sure they are rounded up to natural number\n          pos[1] = ceil(rppos[1] +.00001); // make sure they are rounded up to natural number\n          pos[2] = floor(rppos[0]);\n          pos[3] = floor(rppos[1]);\n\n          resid[0] = rppos[0] - pos[2];\n          resid[1] = rppos[1] - pos[3];\n          wbil[0] = resid[0]*resid[1];\n          wbil[1] = (1-resid[0])*resid[1];\n          wbil[2] = resid[0]*(1-resid[1]);\n          wbil[3] = (1-resid[0])*(1-resid[1]);\n\n          int lb = -op->p_samp_s/2;\n          int ub = op->p_samp_s/2-1;\n\n          \n          for (int y = lb; y <= ub; ++y)\n          {   \n            for (int x = lb; x <= ub; ++x, ++pweight)\n            {\n          \n              int yt = y + pos[1]; \n              int xt = x + pos[0];\n              if (xt >= 1 && yt >= 1 && xt < (cpt->width-1) && yt < (cpt->height-1))\n              {\n                \n                #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)  // single channel/gradient image\n                float absw = 1.0f /  (float)(std::max(op->minerrval  ,*pweight));\n                #else  // RGB\n                float absw = (float)(std::max(op->minerrval  ,*pweight)); ++pweight;\n                      absw+= (float)(std::max(op->minerrval  ,*pweight)); ++pweight;\n                      absw+= (float)(std::max(op->minerrval  ,*pweight));\n                absw = 1.0f / absw;\n                #endif\n              \n              \n                flnew = (*fl) * absw;\n                \n                int idxcc =  xt    +  yt   *cpt->width;\n                int idxfc = (xt-1) +  yt   *cpt->width;\n                int idxcf =  xt    + (yt-1)*cpt->width;\n                int idxff = (xt-1) + (yt-1)*cpt->width;            \n        \n                we[idxcc] += wbil[0] * absw;\n                we[idxfc] += wbil[1] * absw;\n                we[idxcf] += wbil[2] * absw;\n                we[idxff] += wbil[3] * absw;\n\n                #if (SELECTMODE==1)\n                flowout[2*idxcc  ] -= wbil[0] * flnew[0];   // use reversed flow \n                flowout[2*idxcc+1] -= wbil[0] * flnew[1];\n\n                flowout[2*idxfc  ] -= wbil[1] * flnew[0];\n                flowout[2*idxfc+1] -= wbil[1] * flnew[1];\n\n                flowout[2*idxcf  ] -= wbil[2] * flnew[0];\n                flowout[2*idxcf+1] -= wbil[2] * flnew[1];\n\n                flowout[2*idxff  ] -= wbil[3] * flnew[0];\n                flowout[2*idxff+1] -= wbil[3] * flnew[1];\n                #else\n                flowout[idxcc] -= wbil[0] * flnew[0]; // simple averaging of inverse horizontal displacement\n                flowout[idxfc] -= wbil[1] * flnew[0];\n                flowout[idxcf] -= wbil[2] * flnew[0];\n                flowout[idxff] -= wbil[3] * flnew[0];\n                #endif\n              }\n            }\n          }\n        }\n      }\n  } \n  \n  #pragma omp parallel for schedule(static, 100)    \n  // normalize each pixel by dividing displacement by aggregated weights from all patches\n  for (int yi = 0; yi < cpt->height; ++yi)\n  {\n    for (int xi = 0; xi < cpt->width; ++xi)\n    { \n      int i    = yi*cpt->width + xi;\n      if (we[i]>0)\n      {\n        #if (SELECTMODE==1)        \n        flowout[2*i  ] /= we[i];\n        flowout[2*i+1] /= we[i];\n        #else\n        flowout[i] /= we[i];\n        #endif\n      }\n    }\n  }\n  \n  delete[] we;\n}\n\n}\n\n\n", "meta": {"hexsha": "2ecb3efccd8fd8df96ccf5e122ee52f468285029", "size": 12966, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "of_dis/patchgrid.cpp", "max_stars_repo_name": "beaupreda/IMOT_OpticalFlow_Edges", "max_stars_repo_head_hexsha": "633b8fec2c2a4525d1e62d385e553789d56f61f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-01-31T13:32:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T16:35:29.000Z", "max_issues_repo_path": "of_dis/patchgrid.cpp", "max_issues_repo_name": "beaupreda/IMOT_OpticalFlow_Edges", "max_issues_repo_head_hexsha": "633b8fec2c2a4525d1e62d385e553789d56f61f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-09-14T11:02:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-29T23:28:48.000Z", "max_forks_repo_path": "of_dis/patchgrid.cpp", "max_forks_repo_name": "beaupreda/IMOT_OpticalFlow_Edges", "max_forks_repo_head_hexsha": "633b8fec2c2a4525d1e62d385e553789d56f61f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-01T12:20:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T03:42:54.000Z", "avg_line_length": 32.2537313433, "max_line_length": 241, "alphanum_fraction": 0.5445781274, "num_tokens": 4119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5089403729944111}}
{"text": "#include <CExprI.h>\n#include <boost/math/special_functions/erf.hpp>\n#include <CMathGen.h>\n#include <CInvNorm.h>\n#include <COSNaN.h>\n\n#include <cmath>\n#include <ccomplex>\n#include <cstdlib>\n#include <cstring>\n\n// NOTE: types are only needed if normal conversion rules don't handle the type correctly\n\n#ifdef GNUPLOT_EXPR\nnamespace {\n\ndouble invnorm(double x) {\n  //return sqrt(2)/erf(2*x - 1);\n  double y = CInvNorm::calc(x);\n  if (COSNaN::is_pos_inf(y) || COSNaN::is_neg_inf(y))\n    COSNaN::set_nan(y);\n  return y;\n}\n\ndouble norm(double x)\n{\n  x = 0.5*sqrt(2)*x;\n  x = 0.5*erfc(-x);\n\n  return x;\n}\n\ndouble inverf(double x) {\n  try {\n    return boost::math::erf_inv(x);\n  } catch (...) {\n    return CMathGen::getNaN();\n  }\n}\n\n// TODO\nstd::complex<double> cerf(const std::complex<double> &c) {\n  double r = ::erf(c.real());\n  return std::complex<double>(r, 0);\n}\n\n// TODO\nstd::complex<double> cerfc(const std::complex<double> &c) {\n  double r = ::erfc(c.real());\n  return std::complex<double>(r, 0);\n}\n\ndouble RadToDeg(double x) {\n  return 180.0*x/M_PI;\n}\n\ndouble DegToRad(double x) {\n  return M_PI*x/180.0;\n}\n\n}\n\nclass CExprSubStr {\n public:\n  std::string operator()(const std::string &str, int i1, int i2) {\n    if (i1 < 1              ) i1 = 1;\n    if (i1 > int(str.size())) i1 = str.size();\n\n    if (i2 < 0              ) i2 = str.size();\n    if (i2 > int(str.size())) i2 = str.size();\n\n    std::string str1;\n\n    for (int j = i1 - 1; j <= i2 - 1; ++j)\n      str1 += str[j];\n\n    return str1;\n  }\n};\n\nclass CExprStrStrT {\n public:\n  // find position of str2 in str1\n  int operator()(const std::string &str1, const std::string &str2) {\n    auto p = str1.find(str2);\n\n    if (p == std::string::npos)\n      return 0;\n    else\n      return p + 1;\n  }\n};\n\nclass CExprWords {\n public:\n  int operator()(const std::string &str) {\n    std::vector<std::string> words;\n\n    (void) CStrUtil::addWords(str, words);\n\n    return words.size();\n  }\n};\n\nclass CExprWord {\n public:\n  std::string operator()(const std::string &str, int i) {\n    std::vector<std::string> words;\n\n    (void) CStrUtil::addWords(str, words);\n\n    if (i > 0 && i <= int(words.size()))\n      return words[i - 1];\n    else\n      return \"\";\n  }\n};\n\nclass CExprStrLen {\n public:\n  int operator()(const std::string &str) {\n    return str.size();\n  }\n};\n\nclass CExprSystem {\n public:\n  std::string operator()(const std::string &str) {\n    FILE *fp = popen(str.c_str(), \"r\");\n    if (! fp) return \"\";\n\n    std::string res;\n\n    int c;\n\n    while ((c = fgetc(fp)) != EOF)\n      res += char(c);\n\n    pclose(fp);\n\n    return res;\n  }\n};\n#endif\n\nstruct CExprBuiltinFunction {\n  const char        *name;\n  const char        *args;\n  CExprFunctionProc  proc;\n};\n\nstatic CExprValuePtr\nCExprFunctionSqrt(CExpr *expr, const CExprValueArray &values)\n{\n  assert(values.size() == 1);\n\n  double real;\n\n  if (! values[0]->getRealValue(real))\n    return CExprValuePtr();\n\n  if (real >= 0.0) {\n    double real1 = ::sqrt(real);\n\n    return expr->createRealValue(real1);\n  }\n  else {\n    double real1 = ::sqrt(-real);\n\n    return expr->createComplexValue(std::complex<double>(0, real1));\n  }\n}\n\nstatic CExprValuePtr\nCExprFunctionExp(CExpr *expr, const CExprValueArray &values)\n{\n  assert(values.size() == 1);\n\n  double               r;\n  std::complex<double> c;\n\n  if      (values[0]->isComplexValue()) {\n    if (values[0]->getComplexValue(c)) {\n      double r1 = exp(c.real())*cos(c.imag());\n      double c1 = exp(c.real())*sin(c.imag());\n\n      return expr->createComplexValue(std::complex<double>(r1, c1));\n    }\n    else\n      return CExprValuePtr();\n  }\n  else if (values[0]->getRealValue(r)) {\n    double r1 = exp(r);\n\n    return expr->createRealValue(r1);\n  }\n  else\n    return CExprValuePtr();\n}\n\n#define CEXPR_REAL_TO_REAL_FUNC(NAME, F) \\\nstatic CExprValuePtr \\\nCExprFunction##NAME(CExpr *expr, const CExprValueArray &values) { \\\n  assert(values.size() == 1); \\\n  double r = 0.0; \\\n  if (values[0]->getRealValue(r)) { \\\n  } \\\n  else \\\n    return CExprValuePtr(); \\\n  double r1 = F(r); \\\n  return expr->createRealValue(r1); \\\n}\n\n#define CEXPR_REALC_TO_REAL_FUNC(NAME, F) \\\nstatic CExprValuePtr \\\nCExprFunction##NAME(CExpr *expr, const CExprValueArray &values) { \\\n  assert(values.size() == 1); \\\n  double r = 0.0; \\\n  if (values[0]->isComplexValue()) { \\\n    std::complex<double> c; \\\n    if (values[0]->getComplexValue(c)) { \\\n      r = c.real(); \\\n    } \\\n    else \\\n      return CExprValuePtr(); \\\n  } \\\n  else if (values[0]->getRealValue(r)) { \\\n  } \\\n  else \\\n    return CExprValuePtr(); \\\n  double r1 = F(r); \\\n  return expr->createRealValue(r1); \\\n}\n\n#define CEXPR_REALC_TO_REALC_FUNC(NAME, F) \\\nstatic CExprValuePtr \\\nCExprFunction##NAME(CExpr *expr, const CExprValueArray &values) { \\\n  assert(values.size() == 1); \\\n  double r; \\\n  if (values[0]->isComplexValue()) { \\\n    std::complex<double> c; \\\n    if (values[0]->getComplexValue(c)) { \\\n      errno = 0; \\\n      std::complex<double> c1 = F(c); \\\n      if (errno != 0) return CExprValuePtr(); \\\n      return expr->createComplexValue(c1); \\\n    } \\\n      return CExprValuePtr(); \\\n  } \\\n  else if (values[0]->getRealValue(r)) { \\\n    double r1 = F(r); \\\n    return expr->createRealValue(r1); \\\n  } \\\n  else \\\n    return CExprValuePtr(); \\\n}\n\n#define CEXPR_ANGLE_TO_REAL_FUNC(NAME, F) \\\nstatic CExprValuePtr \\\nCExprFunction##NAME(CExpr *expr, const CExprValueArray &values) { \\\n  assert(values.size() == 1); \\\n  double real; \\\n  if (values[0]->getRealValue(real)) { \\\n    if (expr->getDegrees()) \\\n      real = DegToRad(real); \\\n    double real1 = F(real); \\\n    return expr->createRealValue(real1); \\\n  } \\\n  return CExprValuePtr(); \\\n}\n\n#define CEXPR_REALC_TO_ANGLE_FUNC(NAME, F) \\\nstatic CExprValuePtr \\\nCExprFunction##NAME(CExpr *expr, const CExprValueArray &values) { \\\n  assert(values.size() == 1); \\\n  double r; \\\n  if (values[0]->isComplexValue()) { \\\n    std::complex<double> c; \\\n    if (values[0]->getComplexValue(c)) { \\\n      errno = 0; \\\n      std::complex<double> c1 = F(c); \\\n      if (errno != 0) return CExprValuePtr(); \\\n      if (expr->getDegrees()) \\\n        c1 = std::complex<double>(RadToDeg(c1.real()), RadToDeg(c1.imag())); \\\n      return expr->createComplexValue(c1); \\\n    } \\\n    else \\\n      return CExprValuePtr(); \\\n  } \\\n  else if (values[0]->getRealValue(r)) { \\\n    errno = 0; \\\n    double r1 = F(r); \\\n    if (errno == 0) { \\\n      if (expr->getDegrees()) \\\n        r1 = RadToDeg(r1); \\\n      return expr->createRealValue(r1); \\\n    } \\\n    else if (errno == EDOM) { \\\n      std::complex<double> c(r,0); \\\n      errno = 0; \\\n      std::complex<double> c1 = F(c); \\\n      if (errno != 0) return CExprValuePtr(); \\\n      if (expr->getDegrees()) \\\n        c1 = std::complex<double>(RadToDeg(c1.real()), RadToDeg(c1.imag())); \\\n      return expr->createComplexValue(c1); \\\n    } \\\n    else { \\\n      return CExprValuePtr(); \\\n    } \\\n  } \\\n  else \\\n    return CExprValuePtr(); \\\n}\n\n#define CEXPR_REAL2_TO_ANGLE_FUNC(NAME, F) \\\nstatic CExprValuePtr \\\nCExprFunction##NAME(CExpr *expr, const CExprValueArray &values) { \\\n  assert(values.size() == 2); \\\n  double real1, real2; \\\n  if (values[0]->getRealValue(real1) && values[1]->getRealValue(real2)) { \\\n    double real = F(real1, real2); \\\n    if (expr->getDegrees()) \\\n      real = RadToDeg(real); \\\n    return expr->createRealValue(real); \\\n  } \\\n  return CExprValuePtr(); \\\n}\n\n#define CEXPR_COMPLEX_TO_COMPLEX_FUNC(NAME, F) \\\nstatic CExprValuePtr \\\nCExprFunction##NAME(CExpr *expr, const CExprValueArray &values) { \\\n  assert(values.size() == 1); \\\n  std::complex<double> c; \\\n  if (! values[0]->getComplexValue(c)) { \\\n    double r; \\\n    if (! values[0]->getRealValue(r)) \\\n      return CExprValuePtr(); \\\n    c = std::complex<double>(r, 0); \\\n  } \\\n  std::complex<double> c1 = F(c); \\\n  return expr->createComplexValue(c1); \\\n}\n\nclass CExprFunctionAbs : public CExprFunctionObj {\n public:\n  CExprValuePtr operator()(CExpr *expr, const CExprValueArray &values) {\n    assert(values.size() == 1);\n    if      (values[0]->isRealValue()) {\n      double real;\n      if (values[0]->getRealValue(real))\n        return expr->createRealValue(std::abs(real));\n    }\n    else if (values[0]->isIntegerValue()) {\n      long integer;\n      if (values[0]->getIntegerValue(integer))\n        return expr->createIntegerValue(std::abs(integer));\n    }\n    else if (values[0]->isComplexValue()) {\n      std::complex<double> c;\n      if (values[0]->getComplexValue(c))\n        return expr->createRealValue(std::abs(c));\n    }\n    return CExprValuePtr();\n  }\n};\n\nclass CExprFunctionCArg : public CExprFunctionObj {\n public:\n  CExprValuePtr operator()(CExpr *expr, const CExprValueArray &values) {\n    assert(values.size() == 1);\n    if (values[0]->isComplexValue()) {\n      std::complex<double> c;\n      if (values[0]->getComplexValue(c)) {\n        double r = std::arg(c);\n        if (expr->getDegrees())\n          r = DegToRad(r);\n        return expr->createRealValue(r);\n      }\n    }\n    return CExprValuePtr();\n  }\n};\n\nclass CExprFunctionImag : public CExprFunctionObj {\n public:\n  CExprValuePtr operator()(CExpr *expr, const CExprValueArray &values) {\n    assert(values.size() == 1);\n    if (values[0]->isComplexValue()) {\n      std::complex<double> c;\n      if (values[0]->getComplexValue(c))\n        return expr->createRealValue(c.imag());\n    }\n    return CExprValuePtr();\n  }\n};\n\nclass CExprFunctionSign : public CExprFunctionObj {\n public:\n  CExprValuePtr operator()(CExpr *expr, const CExprValueArray &values) {\n    assert(values.size() == 1);\n    if      (values[0]->isRealValue()) {\n      double real;\n      if (values[0]->getRealValue(real))\n        return expr->createIntegerValue(real >= 0 ? (real == 0 ? 0 : 1) : -1);\n    }\n    else if (values[0]->isIntegerValue()) {\n      long integer;\n      if (values[0]->getIntegerValue(integer))\n        return expr->createIntegerValue(integer >= 0 ? (integer == 0 ? 0 : 1) : -1);\n    }\n    else if (values[0]->isComplexValue()) {\n      std::complex<double> c;\n      if (values[0]->getComplexValue(c))\n        return expr->createIntegerValue(c.real() >= 0 ? (c.real() == 0 ? 0 : 1) : -1);\n    }\n    return CExprValuePtr();\n  }\n};\n\nclass CExprFunctionExpr : public CExprFunctionObj {\n public:\n  CExprValuePtr operator()(CExpr *expr, const CExprValueArray &values) {\n    assert(values.size() == 1);\n\n    std::string exprStr;\n\n    if (! values[0]->getStringValue(exprStr))\n      return CExprValuePtr();\n\n    expr->saveCompileState();\n\n    CExprValuePtr value;\n\n    if (! expr->evaluateExpression(exprStr, value))\n      value = CExprValuePtr();\n\n    expr->restoreCompileState();\n\n    return value;\n  }\n};\n\n#ifdef GNUPLOT_EXPR\nclass CExprFunctionRand : public CExprFunctionObj {\n public:\n  CExprValuePtr operator()(CExpr *expr, const CExprValueArray &values) {\n    assert(values.size() == 1);\n    if (values[0]->isIntegerValue()) {\n      long integer = 0;\n      (void) values[0]->getIntegerValue(integer);\n      if     (integer < 0)\n        srand(0);\n      else if (integer > 0)\n        srand(integer);\n      double r = (1.0*rand())/RAND_MAX;\n      return expr->createRealValue(r);\n    }\n    return CExprValuePtr();\n  }\n};\n#endif\n\n#define CEXPR_REALC_TO_REAL_FOBJ(NAME, F) \\\nclass CExprFunction##NAME : public CExprFunctionObj { \\\n public: \\\n  CExprValuePtr operator()(CExpr *expr, const CExprValueArray &values) { \\\n    assert(values.size() == 1); \\\n    double r = 0.0; \\\n    if      (values[0]->isRealValue()) { \\\n      if (! values[0]->getRealValue(r)) return CExprValuePtr(); \\\n    } \\\n    else if (values[0]->isIntegerValue()) { \\\n      long i = 0; \\\n      if (! values[0]->getIntegerValue(i)) return CExprValuePtr(); \\\n      r = i; \\\n    } \\\n    else if (values[0]->isComplexValue()) { \\\n      std::complex<double> c; \\\n      if (! values[0]->getComplexValue(c)) return CExprValuePtr(); \\\n      r = c.real(); \\\n    } \\\n    else { \\\n      return CExprValuePtr(); \\\n    } \\\n    double r1 = F(r); \\\n    return expr->createRealValue(r1); \\\n  } \\\n};\n\nclass CExprFunctionInt : public CExprFunctionObj {\n public:\n  CExprValuePtr operator()(CExpr *expr, const CExprValueArray &values) {\n    assert(values.size() == 1);\n    double r = 0.0;\n    if      (values[0]->isRealValue()) {\n      if (! values[0]->getRealValue(r)) return CExprValuePtr();\n    }\n    else if (values[0]->isIntegerValue()) {\n      long i = 0;\n      if (! values[0]->getIntegerValue(i)) return CExprValuePtr();\n      r = i;\n    }\n    else if (values[0]->isComplexValue()) {\n      std::complex<double> c;\n      if (! values[0]->getComplexValue(c)) return CExprValuePtr();\n      r = c.real();\n    }\n    else {\n      return CExprValuePtr();\n    }\n    int i1 = static_cast<int>(r);\n    return expr->createIntegerValue(i1);\n  }\n};\n\nCEXPR_REALC_TO_REAL_FOBJ(Ceil , std::ceil)\nCEXPR_REALC_TO_REAL_FOBJ(Floor, std::floor)\nCEXPR_REALC_TO_REAL_FOBJ(Real , static_cast<double>)\n\n#ifdef GNUPLOT_EXPR\nclass CExprFunctionSPrintF : public CExprFunctionObj {\n public:\n  CExprValuePtr operator()(CExpr *expr, const CExprValueArray &values) {\n    assert(values.size() >= 1);\n\n    std::string fmt;\n\n    if (! values[0]->getStringValue(fmt))\n      return CExprValuePtr();\n\n    CExprValueArray values1;\n\n    for (uint i = 1; i < values.size(); ++i)\n      values1.push_back(values[i]);\n\n    std::string res = expr->printf(fmt, values1);\n\n    return expr->createStringValue(res);\n  }\n};\n#endif\n\ntemplate<typename T, typename R, typename FUNC>\nclass CExprFunctionObjT1 : public CExprFunctionObj {\n public:\n  CExprFunctionObjT1(CExprFunctionMgr *mgr, const std::string &name) {\n    std::string argsStr = CExprUtil<T>::argTypeStr();\n\n    func_ = mgr->addObjFunction(name, argsStr, this);\n  }\n\n  CExprValuePtr operator()(CExpr *expr, const CExprValueArray &values) {\n    assert(values.size() == 1);\n    T v;\n    if (CExprUtil<T>::getTypeValue(values[0], v))\n      return CExprUtil<R>::createValue(expr, f_(v));\n    return CExprValuePtr();\n  }\n\n  void setBuiltin(bool b) {\n    func_->setBuiltin(b);\n  }\n\n private:\n  FUNC             f_;\n  CExprFunctionPtr func_;\n};\n\ntemplate<typename T1, typename T2, typename R, typename FUNC>\nclass CExprFunctionObjT2 : public CExprFunctionObj {\n public:\n  CExprFunctionObjT2(CExprFunctionMgr *mgr, const std::string &name) {\n    std::string argsStr = CExprUtil<T1>::argTypeStr() + \",\" + CExprUtil<T2>::argTypeStr();\n\n    func_ = mgr->addObjFunction(name, argsStr, this);\n  }\n\n  CExprValuePtr operator()(CExpr *expr, const CExprValueArray &values) {\n    assert(values.size() == 2);\n    T1 v1; T2 v2;\n    if (CExprUtil<T1>::getTypeValue(values[0], v1) &&\n        CExprUtil<T2>::getTypeValue(values[1], v2))\n      return CExprUtil<R>::createValue(expr, f_(v1, v2));\n    return CExprValuePtr();\n  }\n\n  void setBuiltin(bool b) {\n    func_->setBuiltin(b);\n  }\n\n private:\n  FUNC             f_;\n  CExprFunctionPtr func_;\n};\n\ntemplate<typename T1, typename T2, typename T3, typename R, typename FUNC>\nclass CExprFunctionObjT3 : public CExprFunctionObj {\n public:\n  CExprFunctionObjT3(CExprFunctionMgr *mgr, const std::string &name) {\n    std::string argsStr = CExprUtil<T1>::argTypeStr() + \",\" +\n      CExprUtil<T2>::argTypeStr() + \",\" + CExprUtil<T3>::argTypeStr();\n\n    func_ = mgr->addObjFunction(name, argsStr, this);\n  }\n\n  CExprValuePtr operator()(CExpr *expr, const CExprValueArray &values) {\n    assert(values.size() == 3);\n    T1 v1; T2 v2; T3 v3;\n    if (CExprUtil<T1>::getTypeValue(values[0], v1) &&\n        CExprUtil<T2>::getTypeValue(values[1], v2) &&\n        CExprUtil<T2>::getTypeValue(values[2], v3))\n      return CExprUtil<R>::createValue(expr, f_(v1, v2, v3));\n    return CExprValuePtr();\n  }\n\n  void setBuiltin(bool b) {\n    func_->setBuiltin(b);\n  }\n\n private:\n  FUNC             f_;\n  CExprFunctionPtr func_;\n};\n\nCEXPR_REALC_TO_REALC_FUNC(Log  , std::log)\nCEXPR_REALC_TO_REALC_FUNC(Log10, std::log10)\n\nCEXPR_ANGLE_TO_REAL_FUNC(Sin, ::sin)\nCEXPR_ANGLE_TO_REAL_FUNC(Cos, ::cos)\nCEXPR_ANGLE_TO_REAL_FUNC(Tan, ::tan)\n\nCEXPR_REALC_TO_ANGLE_FUNC(ACos, std::acos)\nCEXPR_REALC_TO_ANGLE_FUNC(ASin, std::asin)\nCEXPR_REALC_TO_ANGLE_FUNC(ATan, std::atan)\n\nCEXPR_REAL2_TO_ANGLE_FUNC(ATan2, ::atan2)\n\nCEXPR_REALC_TO_REALC_FUNC(SinH , std::sinh)\nCEXPR_REALC_TO_REALC_FUNC(CosH , std::cosh)\nCEXPR_REALC_TO_REALC_FUNC(TanH , std::tanh)\nCEXPR_REALC_TO_REALC_FUNC(ASinH, std::asinh)\nCEXPR_REALC_TO_REALC_FUNC(ACosH, std::acosh)\nCEXPR_REALC_TO_REALC_FUNC(ATanH, std::atanh)\n\n#ifdef GNUPLOT_EXPR\n// TODO: besy0, besy1\nCEXPR_REAL_TO_REAL_FUNC(BesJ0  , ::j0)\nCEXPR_REAL_TO_REAL_FUNC(BesJ1  , ::j1)\n\nCEXPR_REALC_TO_REAL_FUNC(Erf   , ::erf)\nCEXPR_REALC_TO_REAL_FUNC(ErfC  , ::erfc)\nCEXPR_REALC_TO_REAL_FUNC(InvErf, ::inverf)\n\nCEXPR_COMPLEX_TO_COMPLEX_FUNC(CErf , ::cerf)\nCEXPR_COMPLEX_TO_COMPLEX_FUNC(CErfC, ::cerfc)\n\n// TODO: invnorm, norm\nCEXPR_REALC_TO_REAL_FUNC(Gamma  , ::gamma)\n// TODO: igamma\nCEXPR_REALC_TO_REAL_FUNC(LGamma , ::lgamma)\nCEXPR_REALC_TO_REAL_FUNC(Norm   , ::norm)\nCEXPR_REALC_TO_REAL_FUNC(InvNorm, ::invnorm)\n// TODO: lambertw\n#endif\n\nstatic CExprBuiltinFunction\nbuiltinFns[] = {\n  { \"sqrt\"   , \"r\"  , CExprFunctionSqrt    },\n  { \"exp\"    , \"rc\" , CExprFunctionExp     },\n  { \"log\"    , \"rc\" , CExprFunctionLog     },\n  { \"log10\"  , \"rc\" , CExprFunctionLog10   },\n  { \"sin\"    , \"rc\" , CExprFunctionSin     },\n  { \"cos\"    , \"rc\" , CExprFunctionCos     },\n  { \"tan\"    , \"rc\" , CExprFunctionTan     },\n  { \"asin\"   , \"rc\" , CExprFunctionASin    },\n  { \"acos\"   , \"rc\" , CExprFunctionACos    },\n  { \"atan\"   , \"rc\" , CExprFunctionATan    },\n  { \"atan2\"  , \"r,r\", CExprFunctionATan2   },\n  { \"sinh\"   , \"rc\" , CExprFunctionSinH    },\n  { \"cosh\"   , \"rc\" , CExprFunctionCosH    },\n  { \"tanh\"   , \"rc\" , CExprFunctionTanH    },\n  { \"asinh\"  , \"rc\" , CExprFunctionASinH   },\n  { \"acosh\"  , \"rc\" , CExprFunctionACosH   },\n  { \"atanh\"  , \"rc\" , CExprFunctionATanH   },\n#ifdef GNUPLOT_EXPR\n  // EllipticK, EllipticE, EllipticPi\n  { \"besj0\"  , \"r\"  , CExprFunctionBesJ0   },\n  { \"besj1\"  , \"r\"  , CExprFunctionBesJ1   },\n  // besy0, besy1\n  { \"erf\"    , \"rc\" , CExprFunctionErf     },\n  { \"erfc\"   , \"rc\" , CExprFunctionErfC    },\n  { \"inverf\" , \"rc\" , CExprFunctionInvErf  },\n  { \"cerf\"   , \"c\"  , CExprFunctionCErf    },\n  { \"cerfc\"  , \"c\"  , CExprFunctionCErfC   },\n  { \"gamma\"  , \"r\"  , CExprFunctionGamma   },\n  { \"lgamma\" , \"r\"  , CExprFunctionLGamma  },\n#endif\n  { \"norm\"   , \"r\"  , CExprFunctionNorm    },\n  { \"invnorm\", \"r\"  , CExprFunctionInvNorm },\n  { \"\", \"\", 0 }\n};\n\n//------\n\nCExprFunctionMgr::\nCExprFunctionMgr(CExpr *expr) :\n expr_(expr)\n{\n}\n\nvoid\nCExprFunctionMgr::\naddFunctions()\n{\n  for (uint i = 0; builtinFns[i].proc; ++i) {\n    CExprFunctionPtr function =\n      addProcFunction(builtinFns[i].name, builtinFns[i].args, builtinFns[i].proc);\n\n    function->setBuiltin(true);\n  }\n\n  addObjFunction(\"abs\"  , \"ric\", new CExprFunctionAbs  )->setBuiltin(true);\n  addObjFunction(\"arg\"  , \"c\"  , new CExprFunctionCArg )->setBuiltin(true);\n  addObjFunction(\"ceil\" , \"rc\" , new CExprFunctionCeil )->setBuiltin(true);\n  addObjFunction(\"floor\", \"rc\" , new CExprFunctionFloor)->setBuiltin(true);\n\n  // TODO: use conversion rules\n  addObjFunction(\"int\"  , \"ric\", new CExprFunctionInt  )->setBuiltin(true);\n  addObjFunction(\"real\" , \"ric\", new CExprFunctionReal )->setBuiltin(true);\n  addObjFunction(\"imag\" , \"c\"  , new CExprFunctionImag )->setBuiltin(true);\n\n  addObjFunction(\"sgn\"  , \"ric\", new CExprFunctionSign )->setBuiltin(true);\n\n#ifdef GNUPLOT_EXPR\n  addObjFunction(\"rand\", \"i\", new CExprFunctionRand)->setBuiltin(true);\n\n  // input types ..., return type, function\n  (new CExprFunctionObjT1<std::string,long,CExprStrLen>\n         (this, \"strlen\" ))->setBuiltin(true);\n  (new CExprFunctionObjT2<std::string,std::string,long,CExprStrStrT>\n         (this, \"strstrt\"))->setBuiltin(true);\n  (new CExprFunctionObjT3<std::string,long,long,std::string,CExprSubStr>\n         (this, \"substr\" ))->setBuiltin(true);\n  (new CExprFunctionObjT1<std::string,std::string,CExprSystem>\n         (this, \"system\" ))->setBuiltin(true);\n  (new CExprFunctionObjT2<std::string,long,std::string,CExprWord>\n         (this, \"word\"   ))->setBuiltin(true);\n  (new CExprFunctionObjT1<std::string,long,CExprWords>\n         (this, \"words\"  ))->setBuiltin(true);\n\n  // gprintf ?\n  addObjFunction(\"sprintf\", \"s,...\", new CExprFunctionSPrintF)->setBuiltin(true);\n#endif\n\n  addObjFunction(\"expr\", \"s\", new CExprFunctionExpr)->setBuiltin(true);\n}\n\nCExprFunctionPtr\nCExprFunctionMgr::\ngetFunction(const std::string &name)\n{\n  for (const auto &func : functions_)\n    if (func->name() == name)\n      return func;\n\n  return CExprFunctionPtr();\n}\n\nvoid\nCExprFunctionMgr::\ngetFunctions(const std::string &name, Functions &functions)\n{\n  for (const auto &func : functions_)\n    if (func->name() == name)\n      functions.push_back(func);\n}\n\nCExprFunctionPtr\nCExprFunctionMgr::\naddProcFunction(const std::string &name, const std::string &argsStr, CExprFunctionProc proc)\n{\n  Args args;\n  bool variableArgs;\n\n  (void) parseArgs(argsStr, args, variableArgs);\n\n  CExprFunctionPtr function(new CExprProcFunction(name, args, proc));\n\n  function->setVariableArgs(variableArgs);\n\n  removeFunction(name);\n\n  functions_.push_back(function);\n\n  resetCompiled(name);\n\n  return function;\n}\n\nCExprFunctionPtr\nCExprFunctionMgr::\naddObjFunction(const std::string &name, const std::string &argsStr,\n               CExprFunctionObj *proc, bool resetCompiled)\n{\n  Args args;\n  bool variableArgs;\n\n  (void) parseArgs(argsStr, args, variableArgs);\n\n  CExprFunctionPtr function(new CExprObjFunction(name, args, proc));\n\n  function->setVariableArgs(variableArgs);\n\n  if (! proc->isOverload())\n    removeFunction(name);\n\n  functions_.push_back(function);\n\n  if (resetCompiled)\n    this->resetCompiled(name);\n\n  return function;\n}\n\nCExprFunctionPtr\nCExprFunctionMgr::\naddUserFunction(const std::string &name, const std::vector<std::string> &args,\n                const std::string &proc)\n{\n  CExprFunctionPtr function(new CExprUserFunction(name, args, proc));\n\n  removeFunction(name);\n\n  functions_.push_back(function);\n\n  resetCompiled(name);\n\n  return function;\n}\n\nvoid\nCExprFunctionMgr::\nremoveFunction(const std::string &name)\n{\n  removeFunction(getFunction(name));\n}\n\nvoid\nCExprFunctionMgr::\nremoveFunction(CExprFunctionPtr function)\n{\n  if (function.isValid())\n    functions_.remove(function);\n}\n\nvoid\nCExprFunctionMgr::\ngetFunctionNames(std::vector<std::string> &names) const\n{\n  for (const auto &func : functions_)\n    names.push_back(func->name());\n}\n\nvoid\nCExprFunctionMgr::\nresetCompiled(const std::string &name)\n{\n  for (const auto &func : functions_) {\n    if (func->hasFunction(name))\n      func->reset();\n  }\n}\n\nbool\nCExprFunctionMgr::\nparseArgs(const std::string &argsStr, Args &args, bool &variableArgs)\n{\n  variableArgs = false;\n\n  bool rc = true;\n\n  std::vector<std::string> args1;\n\n  CStrUtil::addTokens(argsStr, args1, \", \");\n\n  uint num_args = args1.size();\n\n  for (uint i = 0; i < num_args; ++i) {\n    const std::string &arg = args1[i];\n\n    if (arg == \"...\" && i == num_args - 1) {\n      variableArgs = true;\n      break;\n    }\n\n    uint types = uint(CExprValueType::NONE);\n\n    uint len = arg.size();\n\n    for (uint j = 0; j < len; j++) {\n      char c = arg[j];\n\n      if      (c == 'b') types |= uint(CExprValueType::BOOLEAN);\n      else if (c == 'i') types |= uint(CExprValueType::INTEGER);\n      else if (c == 'r') types |= uint(CExprValueType::REAL);\n      else if (c == 's') types |= uint(CExprValueType::STRING);\n      else if (c == 'c') types |= uint(CExprValueType::COMPLEX);\n      else if (c == 'n') types |= uint(CExprValueType::NUL);\n      else {\n        CExpr::instance()->\n          errorMsg(\"Invalid argument type char '\" + std::string(&c, 1) + \"'\");\n        rc = false;\n      }\n    }\n\n    args.push_back(CExprFunctionArg((CExprValueType) types));\n  }\n\n  return rc;\n}\n\n//----------\n\nCExprProcFunction::\nCExprProcFunction(const std::string &name, const Args &args, CExprFunctionProc proc) :\n CExprFunction(name), args_(args), proc_(proc)\n{\n}\n\nbool\nCExprProcFunction::\ncheckValues(const CExprValueArray &values) const\n{\n  return (values.size() == numArgs());\n}\n\nCExprValuePtr\nCExprProcFunction::\nexec(CExpr *expr, const CExprValueArray &values)\n{\n  assert(checkValues(values));\n\n  return (*proc_)(expr, values);\n}\n\n//----------\n\nCExprObjFunction::\nCExprObjFunction(const std::string &name, const Args &args, CExprFunctionObj *proc) :\n CExprFunction(name), args_(args), proc_(proc)\n{\n}\n\nCExprObjFunction::\n~CExprObjFunction()\n{\n  delete proc_;\n}\n\nbool\nCExprObjFunction::\ncheckValues(const CExprValueArray &values) const\n{\n  if (isVariableArgs())\n    return (values.size() >= numArgs());\n  else\n    return (values.size() == numArgs());\n}\n\nCExprValuePtr\nCExprObjFunction::\nexec(CExpr *expr, const CExprValueArray &values)\n{\n  assert(checkValues(values));\n\n  return (*proc_)(expr, values);\n}\n\n//----------\n\nCExprUserFunction::\nCExprUserFunction(const std::string &name, const Args &args, const std::string &proc) :\n CExprFunction(name), args_(args), proc_(proc), compiled_(false)\n{\n}\n\nbool\nCExprUserFunction::\ncheckValues(const CExprValueArray &values) const\n{\n  return (values.size() >= numArgs());\n}\n\nvoid\nCExprUserFunction::\nreset()\n{\n  compiled_ = false;\n\n  pstack_.clear();\n  cstack_.clear();\n\n  itoken_ = CExprITokenPtr();\n}\n\nCExprValuePtr\nCExprUserFunction::\nexec(CExpr *expr, const CExprValueArray &values)\n{\n  assert(checkValues(values));\n\n  //---\n\n  if (! compiled_) {\n    pstack_ = expr->parseLine(proc_);\n    itoken_ = expr->interpPTokenStack(pstack_);\n    cstack_ = expr->compileIToken(itoken_);\n\n    compiled_ = true;\n  }\n\n  //---\n\n  typedef std::map<std::string,CExprValuePtr> VarValues;\n\n  VarValues varValues;\n\n  // set arg values (save previous values)\n  for (uint i = 0; i < numArgs(); ++i) {\n    const std::string &arg = args_[i];\n\n    CExprVariablePtr var = expr->getVariable(arg);\n\n    if (var.isValid()) {\n      varValues[arg] = var->getValue();\n\n      var->setValue(values[i]);\n    }\n    else {\n      varValues[arg] = CExprValuePtr();\n\n      expr->createVariable(arg, values[i]);\n    }\n  }\n\n  // run proc\n  expr->saveCompileState();\n\n  CExprValuePtr value;\n\n//if (! expr->evaluateExpression(proc_, value))\n//  value = CExprValuePtr();\n//if (! expr->executePTokenStack(pstack_, value))\n//  value = CExprValuePtr();\n  if (! expr->executeCTokenStack(cstack_, value))\n    value = CExprValuePtr();\n\n  expr->restoreCompileState();\n\n  // restore variables\n  for (const auto &v : varValues) {\n    const std::string varName = v.first;\n    CExprValuePtr     value   = v.second;\n\n    if (value.isValid()) {\n      CExprVariablePtr var = expr->getVariable(varName);\n\n      var->setValue(value);\n    }\n    else\n      expr->removeVariable(varName);\n  }\n\n  return value;\n}\n", "meta": {"hexsha": "2e8b57b3bb6c997d99ecd4740a75a301d6f271c6", "size": 26651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CExprFunction.cpp", "max_stars_repo_name": "colinw7/CQGnuPlot", "max_stars_repo_head_hexsha": "8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CExprFunction.cpp", "max_issues_repo_name": "colinw7/CQGnuPlot", "max_issues_repo_head_hexsha": "8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CExprFunction.cpp", "max_forks_repo_name": "colinw7/CQGnuPlot", "max_forks_repo_head_hexsha": "8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-04-01T13:08:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-01T13:08:45.000Z", "avg_line_length": 24.7685873606, "max_line_length": 92, "alphanum_fraction": 0.6343852013, "num_tokens": 8012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5089068731112233}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2010 Joel de Guzman\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//  A Roman Numerals Parser (demonstrating the symbol table). This is\n//  discussed in the \"Symbols\" chapter in the Spirit User's Guide.\n//\n//  [ JDG August 22, 2002 ] spirit1\n//  [ JDG March 13, 2007 ]  spirit2\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <boost/config/warning_disable.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/spirit/include/qi.hpp>\n\n#include <iostream>\n#include <string>\n\nnamespace client {\nnamespace qi = boost::spirit::qi;\nnamespace ascii = boost::spirit::ascii;\n\n///////////////////////////////////////////////////////////////////////////////\n//  Parse roman hundreds (100..900) numerals using the symbol table.\n//  Notice that the data associated with each slot is the parser's attribute\n//  (which is passed to attached semantic actions).\n///////////////////////////////////////////////////////////////////////////////\n//[tutorial_roman_hundreds\nstruct hundreds_ : qi::symbols<char, unsigned> {\n  hundreds_() {\n    add(\"C\", 100)(\"CC\", 200)(\n        \"CCC\", 300)(\"CD\", 400)(\"D\", 500)(\"DC\", 600)(\"DCC\", 700)(\"DCCC\",\n                                                                800)(\"CM\", 900);\n  }\n\n} hundreds;\n//]\n\n///////////////////////////////////////////////////////////////////////////////\n//  Parse roman tens (10..90) numerals using the symbol table.\n///////////////////////////////////////////////////////////////////////////////\n//[tutorial_roman_tens\nstruct tens_ : qi::symbols<char, unsigned> {\n  tens_() {\n    add(\"X\", 10)(\"XX\", 20)(\n        \"XXX\", 30)(\"XL\", 40)(\"L\", 50)(\"LX\", 60)(\"LXX\", 70)(\"LXXX\", 80)(\"XC\",\n                                                                       90);\n  }\n\n} tens;\n//]\n\n///////////////////////////////////////////////////////////////////////////////\n//  Parse roman ones (1..9) numerals using the symbol table.\n///////////////////////////////////////////////////////////////////////////////\n//[tutorial_roman_ones\nstruct ones_ : qi::symbols<char, unsigned> {\n  ones_() {\n    add(\"I\", 1)(\"II\", 2)(\n        \"III\", 3)(\"IV\", 4)(\"V\", 5)(\"VI\", 6)(\"VII\", 7)(\"VIII\", 8)(\"IX\", 9);\n  }\n\n} ones;\n//]\n\n///////////////////////////////////////////////////////////////////////////////\n//  roman (numerals) grammar\n//\n//      Note the use of the || operator. The expression\n//      a || b reads match a or b and in sequence. Try\n//      defining the roman numerals grammar in YACC or\n//      PCCTS. Spirit rules! :-)\n///////////////////////////////////////////////////////////////////////////////\n//[tutorial_roman_grammar\ntemplate <typename Iterator> struct roman : qi::grammar<Iterator, unsigned()> {\n  roman() : roman::base_type(start) {\n    using ascii::char_;\n    using qi::_1;\n    using qi::_val;\n    using qi::eps;\n    using qi::lit;\n\n    start = eps[_val = 0] >> (+lit('M')[_val += 1000] || hundreds[_val += _1] ||\n                              tens[_val += _1] || ones[_val += _1]);\n  }\n\n  qi::rule<Iterator, unsigned()> start;\n};\n//]\n} // namespace client\n\n///////////////////////////////////////////////////////////////////////////////\n//  Main program\n///////////////////////////////////////////////////////////////////////////////\nint main() {\n  using namespace std;\n  cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n  cout << \"\\t\\tRoman Numerals Parser\\n\\n\";\n  cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n  cout << \"Type a Roman Numeral ...or [q or Q] to quit\\n\\n\";\n\n  typedef string::const_iterator iterator_type;\n  typedef client::roman<iterator_type> roman;\n\n  roman roman_parser; // Our grammar\n\n  string str;\n  unsigned result;\n  while (getline(cin, str)) {\n    if (str.empty() || str[0] == 'q' || str[0] == 'Q')\n      break;\n\n    string::const_iterator iter = str.begin();\n    string::const_iterator end = str.end();\n    //[tutorial_roman_grammar_parse\n    bool r = parse(iter, end, roman_parser, result);\n\n    if (r && iter == end) {\n      cout << \"-------------------------\\n\";\n      cout << \"Parsing succeeded\\n\";\n      cout << \"result = \" << result << endl;\n      cout << \"-------------------------\\n\";\n    } else {\n      string rest(iter, end);\n      cout << \"-------------------------\\n\";\n      cout << \"Parsing failed\\n\";\n      cout << \"stopped at: \\\": \" << rest << \"\\\"\\n\";\n      cout << \"-------------------------\\n\";\n    }\n    //]\n  }\n  cout << \"Bye... :-) \\n\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "bb888d114e7fa9a50aaebf8e66778fd0a3e37066", "size": 4840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spirit/romans.cpp", "max_stars_repo_name": "Fernal73/LearnParsing", "max_stars_repo_head_hexsha": "2d126a173cea3d6cdad6dc35dc64fa4b593f6a97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spirit/romans.cpp", "max_issues_repo_name": "Fernal73/LearnParsing", "max_issues_repo_head_hexsha": "2d126a173cea3d6cdad6dc35dc64fa4b593f6a97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spirit/romans.cpp", "max_forks_repo_name": "Fernal73/LearnParsing", "max_forks_repo_head_hexsha": "2d126a173cea3d6cdad6dc35dc64fa4b593f6a97", "max_forks_repo_licenses": ["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.5714285714, "max_line_length": 80, "alphanum_fraction": 0.4146694215, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.5089068731112233}}
{"text": "/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%  Solving 2D Poisson + Drift Diffusion semiconductor eqns for a solar cell using\n%                      Scharfetter-Gummel discretization\n%\n%                         Written by Timofey Golubev\n%\n%     This includes the 2D poisson equation and 2D continuity/drift-diffusion\n%     equations using Scharfetter-Gummel discretization. The Poisson equation\n%     is solved first, and the solution of potential is used to calculate the\n%     Bernoulli functions and solve the continuity eqn's.\n%\n%   Boundary conditions for Poisson equation are:\n%\n%     -a fixed voltage at (x,0) and (x, Nz) defined by V_bottomBC\n%      and V_topBC which are defining the  electrodes\n%\n%    -insulating boundary conditions: V(0,z) = V(1,z) and\n%     V(0,N+1) = V(1,N) (N is the last INTERIOR mesh point).\n%     so the potential at the boundary is assumed to be the same as just inside\n%     the boundary. Gradient of potential normal to these boundaries is 0.\n%\n%   Matrix equations are AV*V = bV, Ap*p = bp, and An*n = bn where AV, Ap, and An are sparse matrices\n%   (generated using spdiag), for the Poisson and continuity equations.\n%   V is the solution for electric potential, p is the solution for hole\n%   density, n is solution for electron density\n%   bV is the rhs of Poisson eqn which contains the charge densities and boundary conditions\n%   bp is the rhs of hole continuity eqn which contains net generation rate\n%   and BCs\n%\n%     The code as is will calculate data for a JV curve\n%     as well as carrier densities, current densities, and electric field\n%     distributions of a generic solar cell made of an active layer and electrodes.\n%     More equations for carrier recombination can be easily added.f\n%\n%     Photogeneration rate will be inputed from gen_rate.inp file\n%     (i.e. the output of an optical model can be used) or an analytic expression\n%     for photogeneration rate can be added to photogeneration.cpp. Generation rate file\n%     should contain num_cell-2 number of entries in a single column, corresponding to\n%     the the generation rate at each mesh point (except the endpoints).\n%\n%     The code can also be applied to non-illuminated devices by\n%     setting photogeneration rate to 0.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/\n\n#include <iostream>\n#include <vector>\n#include <iomanip>\n#include <algorithm>   //allows to use fill and min\n#include <fstream>\n#include <chrono>\n#include <string>\n#include <time.h>\n#include <fstream>\n#include <string>\n\n#include <omp.h>\n\n#define EIGEN_USE_MKL_ALL  //is for Intel MKL\n\n//#define EIGEN_NO_DEBUG   //this should turn off eigen asserts, //MAKES NO PERFORMANCE DIFFERENCE!, is I think auto turned off in release mode\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include<Eigen/IterativeLinearSolvers>\n#include <Eigen/SparseCholesky>\n#include<Eigen/SparseQR>\n#include <Eigen/OrderingMethods>\n#include<Eigen/SparseLU>\n#include <unsupported/Eigen/CXX11/Tensor>  //allows for 3D matrices (Tensors)\n\n#include \"constants.h\"        //these contain physics constants only\n#include \"parameters.h\"\n#include \"poisson.h\"\n#include \"continuity_p.h\"\n//#include \"continuity_n.h\"\n//#include \"recombination.h\"\n//#include \"photogeneration.h\"\n#include \"Utilities.h\"\n\n#include \"mkl.h\"\n\n\nint main()\n{\n\n    //trivial MKL function call for testing\n    vcAbs(0, 0, 0);  //MY MKL linking works!!, b/c otherwise it wouldn't recognize this function!\n\n    std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();  //start clock timer\n    Parameters params;    //params is struct storing all parameters\n    params.Initialize();  //reads parameters from file\n\n    const int num_cell_x = params.num_cell_x;   //create a local num_cell so don't have to type params.num_cell everywhere\n    const int num_cell_y = params.num_cell_y;\n    const int num_cell_z = params.num_cell_z;\n\n    const int num_V = static_cast<int>(floor((params.Va_max-params.Va_min)/params.increment))+1;  //floor returns double, explicitely cast to int\n    params.tolerance_eq = params.tolerance_i;\n    const int Nx = params.Nx;\n    const int Ny = params.Ny;\n    const int Nz = params.Nz;\n    const int num_rows = (Nx+1)*(Ny+1)*(Nz+1);  //number of rows in the solution vectors (V, n, p)\n    //NOTE: num_rows is the same as num_elements.\n    //NOTE: we include the top BC inside the matrix and solution vectors to allow in future to use mixed BC's there.\n\n    std::ofstream JV;\n    JV.open(\"JV.txt\");  //note: file will be created inside the build directory\n\n    //-------------------------------------------------------------------------------------------------------\n    //Initialize other vectors\n    //WILL INDEX FROM 0, b/c that's what Eigen library does.\n    //Note: these are Tensor type, so can use reshape on them, but these all are just a single column (i.e. the soln column from the matrix eqn).\n    Eigen::Tensor<double, 3> p(num_rows, 1, 1), oldp(num_rows, 1, 1), newp(num_rows, 1, 1);\n    Eigen::Tensor<double, 3> oldV(num_rows, 1, 1), newV(num_rows, 1, 1), V(num_rows, 1, 1);\n\n    //create matrices to hold the V, n, and p values (including those at the boundaries) according to the (x,z) coordinates.\n    //allows to write formulas in terms of coordinates\n    Eigen::VectorXd soln_V(num_rows), soln_p(num_rows);  //vector for storing solutions to the  sparse solver (indexed from 0)\n    Eigen::VectorXd p_Xd(num_rows), V_Xd(num_rows);  //Eigen Vector_Xds for the initial buesses to bicgstab method\n    //For the following, only need gen rate on insides, so N+1 size is enough\n    std::vector<double> Up(num_rows); //will store generation rate as vector, for easy use in rhs\n\n    //Eigen::Tensor<double, 3> R_Langevin(N+1,N+1,N+1), PhotogenRate(N+1,N+1,N+1);\n    Eigen::Tensor<double, 3> J_total_Z(num_cell_x+1, num_cell_y+1, num_cell_z+1), J_total_X(num_cell_x+1, num_cell_y+1, num_cell_z+1), J_total_Y(num_cell_x+1, num_cell_y+1, num_cell_z+1);  //we want the indices of J to correspond to the real x,y,z values..., for convinience                //matrices for spacially dependent current\n    Eigen::Tensor<double, 3> V_matrix(num_cell_x, num_cell_y, num_cell_z), temp_permuted; //indexed from 0, so just num_cell....//temp_permuted is needed b/c it can't do in place permutations...., need to save to another tensor!  //Note: is actually a Tensor in Eigen\n    Eigen::Tensor<double, 3> fullV(num_cell_x+1, num_cell_y+1, num_cell_z+1), fullp(num_cell_x+1, num_cell_y+1, num_cell_z+1);  //for storing all the values in device, including bndrys\n    Eigen::SparseMatrix<double> input; //for feeding input matrix into BiCGSTAB, b/c it crashes if try to call get matrix from the solve call.\n\n    //test if openmp is working\n    //omp_set_num_threads(8);   //this can allow to set the number of threads that will be used\n\n    std::cout << Eigen::nbThreads() << std::endl;  //displays the # of threads that will be used by Eigen--> mine displays 8, but doesn't seem like it's using 8.\n\n    //this will only make sense if within a region of code which is multithreaded\n//    int nthreads = omp_get_num_threads();  //SAYS ONLY 1 THREAD IS AVAILABLE--> MIGHT HAVE AN ISSUE HERE!\n//    std::cout << nthreads << \" treads available \" << std::endl;\n//------------------------------------------------------------------------------------\n    //Construct objects\n    Poisson poisson(params);  //so it can't construct the poisson object\n    //Recombo recombo(params);\n    Continuity_p continuity_p(params);  //note this also sets up the constant top and bottom electrode BC's\n\n    //Continuity_n continuity_n(params);  //note this also sets up the constant top and bottom electrode BC's\n    //Photogeneration photogen(params, params.Photogen_scaling, params.GenRateFileName);\n    Utilities utils;\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>, Eigen::UpLoType::Lower, Eigen::AMDOrdering<int>> SCholesky; //Note using NaturalOrdering is much much slower\n\n    Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> SQR;\n    Eigen::SparseLU<Eigen::SparseMatrix<double> >  poisson_LU, cont_n_LU, cont_p_LU;\n    //Eigen::BiCGSTAB<Eigen::SparseMatrix<double>, Eigen::IncompleteLUT<double>> BiCGStab_solver;  //BiCGStab solver object/ /USING THIS PRECONDITIONER IS WAY TOO SLOW FOR LARGE SYSTEMS!\n    Eigen::BiCGSTAB<Eigen::SparseMatrix<double>, Eigen::DiagonalPreconditioner<double>> BiCGStab_solver;   //NOTE: WORKS MUCH FASTER WITH DIAGONAL PRECONDITIONER, THAN the IncompleteLUT preconditioner!!--> probably b/c\n    //Eigen::BiCGSTAB<Eigen::SparseMatrix<double>, Eigen::IdentityPreconditioner> BiCGStab_solver;  //try with Identity preconditioner, the simplest trivial one\n    BiCGStab_solver.setTolerance(1e-14); //set the tolerance explicitely, so matches Matlab's tolerance\n\n    Eigen::ConjugateGradient<Eigen::SparseMatrix<double>, Eigen::UpLoType::Lower|Eigen::UpLoType::Upper > cg;\n\n\n//--------------------------------------------------------------------------------------------\n    //Define boundary conditions and initial conditions. Note: electrodes are at the top and bottom.\n    double Va = params.Va_min;\n    poisson.set_V_bottomBC(params, Va);\n    poisson.set_V_topBC(params, Va);  //THESE CAN BE MOVED TO BE DONE WITHIN constructor of Poisson object\n\n    //Initial conditions\n    //for now assume diff is constant everywhere...\n    double diff = (poisson.get_V_topBC(0,0) - poisson.get_V_bottomBC(0,0))/num_cell_z;  //this is  calculated correctly\n\n    //Note: B/C I must fill from 0, and don't want to include bottomBC in V matrix, b/c is not part of V\n    for (int k = 1; k <= Nz+1; k++) {\n        for (int i = 1; i <= Nx+1; i++) {\n            for (int j = 1; j <= Ny+1; j++) {\n                V_matrix(i-1, j-1, k-1) = poisson.get_V_bottomBC(i,j) +  diff*(k);  //-1's b/c fill from 0\n            }\n        }\n    }\n\n    //need to permute the matrix, to be consistent with the z,y,x ordering which I use for the matrices when solving.\n    //NOTE: for Tensor shuffle to work, NEED TO EXPLICTELY CREATE AN ARRAY--> this isn't clear from the documentation\n    Eigen::array<ptrdiff_t, 3> permutation = {{2,1,0}}; //array should HAVE THE SPECIFIC type:  ptrdiff_t  ==> used for pointer arithmetic and array indexing.\n    //ptrdiff_t is the signed integer type of the result of subtracting 2 pointers.\n\n    temp_permuted = V_matrix.shuffle(permutation);  //shuffle permuts the tensor. Note: dimensions are indexed from 0. This is supposed to swap x and z values...\n    V_matrix = temp_permuted;\n    //Returns a copy of the input tensor whose dimensions have been reordered according to the specified permutation. The argument shuffle is an array of Index values. Its size is the rank of the input tensor. It must contain a permutation of 0, 1, ..., rank - 1.\n    //works to here\n    //NOTE: IT CAN'T DO AN INPLACE PERMUTATION!!!--> need to rename the variable!!!\n\n    //reshape the matrix to a single column. //Note: even though reshaping to a column, V still must be a TENSOR type for this to work!\n     Eigen::array<ptrdiff_t, 3> reshape_sizes = {{num_rows, 1, 1}};  //need to only go to num_rows..., b/c it fills from 0 !!\n     V = V_matrix.reshape(reshape_sizes);  //Note: even though reshaping to a column, V still must be a TENSOR type for this to work!\n\n     //prepare initial guess, for 1st iteration of bicgstab\n     for (int i = 0; i < num_rows; i++) {\n         V_Xd(i) = V(i,0,0);\n         soln_V(i) = V(i,0,0); // do this since we are using soln_V for the inital guess\n     }\n\n    //Fill p with initial conditions (need for error calculation)\n    double min_dense = continuity_p.get_p_bottomBC(1,1) < continuity_p.get_p_topBC(1,1) ? continuity_p.get_p_bottomBC(1,1):continuity_p.get_p_topBC(1,1);  //this should be same as std::min  fnc which doesn't work for some reason\n    //double min_dense = std::min (continuity_n.get_n_bottomBC(1,1), continuity_p.get_p_topBC(1,1));  //Note: I defined the get fnc to take as arguments the i,j values... //Note: the bc's along bottom and top are currently uniform, so index, doesn't really matter.\n    for (int i = 0; i < num_rows; i++) {\n        p(i,0,0) = min_dense;  //NOTE: p is tensor now, so need () to access elements\n    }\n\n    //prepare initial guess, for 1st iteration of bicgstab\n    for (int i = 0; i < num_rows; i++) {\n        p_Xd(i) = p(i,0,0);  //this is working correctly\n        soln_p(i) = p(i,0,0); // do this since we are using soln_p for the inital guess\n    }\n\n    //Convert the p to p_matrix\n    Eigen::array<ptrdiff_t, 3> to_matrix_sizes{{Nz+1, Ny+1, Nx+1}};  //use reshape according to the  ordering of the matrix, so: z, y, x\n    Eigen::Tensor<double, 3> p_matrix = p.reshape(to_matrix_sizes);\n    //continuity_p.set_p_matrix(p_matrix);  //THIS FOR SOME REASON FAILS..., so don't use it...//save p_matrix to continuity_p member variable--> THIS MIGHT BE INEFFIIENT, BUT DO IT FOR NOW\n\n    //////////////////////MAIN LOOP////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    int iter, not_cnv_cnt, Va_cnt;\n    bool not_converged;\n    double error_np, old_error;  //this stores max value of the error and the value of max error from previous iteration\n    std::vector<double> error_np_vector(num_rows);  //note: since n and p solutions are in vector form, can use vector form here also\n\n    poisson.setup_matrix();  //I VERIFIED that size of sparse matrix is correct\n\n\n    for (Va_cnt = 1; Va_cnt <= num_V; Va_cnt++) {  //+1 b/c 1st Va is the equil run\n        not_converged = false;\n        not_cnv_cnt = 0;\n\n        Va = params.Va_min+params.increment*(Va_cnt-1);\n\n        if (Va_cnt == 1) {\n            params.use_tolerance_i();  //reset tolerance back\n            params.use_w_i();\n            //PhotogenRate = photogen.getPhotogenRate();    //otherwise PhotogenRate is pre-initialized to 0 in this main.cpp when declared\n        }\n\n        if (params.tolerance > 1e-5)\n            std::cerr<<\"ERROR: Tolerance has been increased to > 1e-5\" <<std::endl;\n\n        std::cout << \"Va = \" << Va <<std::endl;\n\n        //Reset top and bottom BCs (outside of loop b/c don't change iter to iter)\n        poisson.set_V_bottomBC(params, Va);\n        poisson.set_V_topBC(params, Va);\n\n       //correct through  here\n\n        //-----------------------------------------------------------\n        error_np = 1.0;\n        iter = 0;\n\n        //get's through here\n        while (error_np > params.tolerance) {\n            //std::cout << \"Va \" << Va <<std::endl;\n\n            //-----------------Solve Poisson Equation------------------------------------------------------------------\n            poisson.set_rhs(p);  //this finds netcharge and sets rhs\n            //std::cout << poisson.get_sp_matrix() << std::endl;\n            oldV = V;\n\n            input = poisson.get_sp_matrix();\n\n            //as expected, LU, is way too slow for a 3D matrix!!\n\n            if (iter == 0) {\n                BiCGStab_solver.analyzePattern(input);\n                BiCGStab_solver.factorize(input);  //this computes preconditioner, Poisson matrix doesn't change, so can factorize just once\n            }\n            //BiCGStab_solver.compute(input);  //this computes the preconditioner..compute(input);\n            //soln_V = BiCGStab_solver.solve(poisson.get_rhs());\n            soln_V = BiCGStab_solver.solveWithGuess(poisson.get_rhs(), soln_V); //note: using soln_V for initial guess is faster than using V_Xd/NOTE: use solve with Guess...., b/c need initial guess\n            //std::cout << \"#iterations:     \" << BiCGStab_solver.iterations() << std::endl;\n             //std::cout << BiCGStab_solver.info() << std::endl;\n            //std::cout << soln_V << std::endl;\n\n           //CHOLESKY is not accurate!! for 3D solve\n\n            //std::cout << poisson.get_sp_matrix() << std::endl;\n             //std::cout << \"Poisson solver error \" << poisson.get_sp_matrix() * soln_Xd - poisson.get_rhs() << std::endl;\n\n            //RECALL, I am starting my V vector from index of 1, corresponds to interior pts...\n            for (int i = 0; i < num_rows; i++) {\n                newV(i,0,0) = soln_V(i);   //fill VectorXd  rhs of the equation\n                //NOTE: newV is a Tensor now, so use () to access\n            }\n\n            //Mix old and new solutions for V\n            if (iter > 0)\n                V  = utils.linear_mix(params, newV, oldV);\n            else\n                V = newV;\n\n            //update the Eigen Vector_Xd for the initial guess--> LATER DO ALL THIS MORE EFFICIENTLY\n            for (int i = 0; i < num_rows; i++) {\n                V_Xd(i) = V(i,0,0);\n            }\n\n            //reshape solution to a V_matrix\n            V_matrix = V.reshape(to_matrix_sizes); // reshapes using z, y, x ordering\n            //need to permute before using for fullV\n            temp_permuted = V_matrix.shuffle(permutation);  //need to use a temp variable for this to work\n\n            //fill the fullV\n            //SHOULD MOVE THIS TO A FUNCTION!\n            for (int k = 1; k <= num_cell_z; k++)\n               for (int j = 1; j <= num_cell_y; j++)\n                   for (int i = 1; i <= num_cell_x; i++)\n                       fullV(i,j,k) = temp_permuted(i-1,j-1,k-1);  //-1 b/c temp_permuted from V_matrix was filled from 0\n\n            for (int j = 0; j <= num_cell_y; j++)\n                for (int i = 0; i <= num_cell_x; i++)\n                    fullV(i,j,0) = poisson.get_V_bottomBC(i,j);\n\n            for (int k = 1; k <= num_cell_z; k++)\n               for (int j = 1; j <= num_cell_y; j++)\n                   fullV(0,j,k) = temp_permuted(num_cell_x-1,j-1,k-1);  //x BC's\n\n            for (int k = 1; k <= num_cell_z; k++)\n               for (int i = 1; i <= num_cell_x; i++)\n                   fullV(i,0,k) = temp_permuted(i-1,num_cell_y-1,k-1);  //y BC's\n\n            //fill edges\n            for (int k = 1; k <= num_cell_z; k++)\n                fullV(0,0,k) = temp_permuted(num_cell_x-1,0,k-1);\n\n\n\n\n            //------------------------------Calculate Net Generation Rate----------------------------------------------------------\n\n            //R_Langevin = recombo.ComputeR_Langevin(params,n,p);\n            //FOR NOW CAN USE 0 FOR R_Langevin\n\n                for (int i = 0; i < num_rows; i++) {\n                    Up[i] = 0; //params.Photogen_scaling;  //This is what was used in Matlab version for testing.   photogen.getPhotogenRate()(i,j); //- R_Langevin(i,j);\n                }\n\n            //--------------------------------Solve equation for p------------------------------------------------------------\n\n            continuity_p.setup_eqn(fullV, Up, p);  //pass it fullV...\n            //std::cout << continuity_p.get_sp_matrix() << std::endl;   //Note: get rhs, returns an Eigen VectorXd\n\n            for (int i = 0; i < num_rows; i++)\n                oldp(i,0,0) = p(i,0,0);          //explicitely  copy, just in case\n\n            input = continuity_p.get_sp_matrix();\n            if (iter == 0) {\n                BiCGStab_solver.analyzePattern(input);\n                BiCGStab_solver.factorize(input);  //factorize only for the 1st iteration!!, since matrix doesn't change too much, this still will work!-> means it only  computes preconditioner once per Va!! //this computes preconditioner, if use along with analyzePattern (for 1st iter)\n            }\n            //BiCGStab_solver.compute(input);  //this computes the preconditioner..compute(input);\n            soln_p = BiCGStab_solver.solveWithGuess(continuity_p.get_rhs(), soln_p);  //NOTE: if for initial guess use soln_p, INSTEAD OF p_Xd (which is the linearly mixed solution, then does't blow up!!!!!, even with 0.2 = w.\n            //soln_p = BiCGStab_solver.solve(continuity_p.get_rhs());\n\n//         std::cout << soln_p << std::endl;\n//         exit(1);\n\n            //save results back into n std::vector. RECALL, I am starting my V vector from index of 1, corresponds to interior pts...\n            for (int i = 0; i < num_rows; i++) {\n                newp(i,0,0) = soln_p(i);   //newp is now a tensor....\n            }\n\n\n            //------------------------------------------------\n\n            //if get negative p's or n's set them = 0\n            for (int i = 0; i < num_rows; i++) {\n                if (newp(i,0,0) < 0.0) newp(i,0,0) = 0;\n                //if (newn[i] < 0.0) newn[i] = 0;\n            }\n\n            //calculate the error\n            old_error = error_np;\n            int count = 0;  //for counting the error_np_vector_index\n\n            //THIS CAN BE MOVED TO A FUNCTION IN UTILS\n            std::fill(error_np_vector.begin(), error_np_vector.end(),0.0);  //refill with 0's so have fresh one\n            for (int i = 0; i < num_rows; i++) {\n                if (newp(i,0,0)!= 0) {\n                    error_np_vector[count] = (std::abs(newp(i,0,0)-oldp(i,0,0)))/std::abs(oldp(i,0,0));\n                    count++;\n//                   if(iter == 2)\n//                       std::cout << error_np_vector[i] << std::endl;\n               }\n            }\n\n//            if(iter == 2) {\n//                for (int i = 0; i < num_rows; i++ ) {\n//                    std::cout <<  newp(i,0,0) << \" \" << oldp(i,0,0) <<  std::endl;   //FOR LARGE SYSTEMS SEEMS NEWP AND OLDP ARE EXACT SAME--> GETTING 0 ERRORS, BUT THEN BLOWS UP!!  //compare newp and oldp //newp are not 0's --> have numbers...\n//                }\n//                exit(1);\n//            }\n\n            error_np = *std::max_element(error_np_vector.begin(),error_np_vector.end());\n\n            std::cout << error_np << std::endl;\n\n            //auto decrease w if not converging\n            if (error_np >= old_error)\n                not_cnv_cnt = not_cnv_cnt+1;\n            if (not_cnv_cnt > 1000) {  //Note: 100 is too small for C++, sometimes w is reduced when not necessary!!\n                params.reduce_w();\n                params.relax_tolerance();\n                not_cnv_cnt = 0;\n            }\n\n            p = utils.linear_mix(params, newp, oldp);\n\n            //update the Eig vector for initial guess --> LATER SHOULD DO ALL OF THIS MORE EFFICIENTLY\n            for (int i = 0; i < num_rows; i++) {\n                p_Xd(i) = p(i,0,0);\n            }\n\n            //Convert p to p_matrix\n            p_matrix = p.reshape(to_matrix_sizes);  // this reshapes based on z,y,x ordering\n\n            //need to permute before using for fullV\n            temp_permuted = p_matrix.shuffle(permutation);  //need to use a temp variable for this to work\n\n            //fill the fullp\n            //SHOULD MOVE THIS TO A FUNCTION!\n            for (int k = 1; k <= num_cell_z; k++)\n               for (int j = 1; j <= num_cell_y; j++)\n                   for (int i = 1; i <= num_cell_x; i++)\n                       fullp(i,j,k) = temp_permuted(i-1,j-1,k-1);  //-1 b/c temp_permuted from V_matrix was filled from 0\n\n            for (int j = 0; j <= num_cell_y; j++)\n                for (int i = 0; i <= num_cell_x; i++)\n                    fullp(i,j,0) = continuity_p.get_p_bottomBC(i,j);\n\n            for (int k = 1; k <= num_cell_z; k++)\n               for (int j = 1; j <= num_cell_y; j++)\n                   fullp(0,j,k) = temp_permuted(num_cell_x-1,j-1,k-1);  //x BC's\n\n            for (int k = 1; k <= num_cell_z; k++)\n               for (int i = 1; i <= num_cell_x; i++)\n                   fullp(i,0,k) = temp_permuted(i-1,num_cell_y-1,k-1);  //y BC's\n\n            //fill edges\n            for (int k = 1; k <= num_cell_z; k++)\n                fullp(0,0,k) = temp_permuted(num_cell_x-1,0,k-1);\n\n            //continuity_p.set_p_matrix(p_matrix);  //update member variable  //DON'T USE THIS B/C CAUSES ISSUES, just use the p matrix form main\n\n           // std::cout << error_np << std::endl;\n            //std::cout << \"weighting factor = \" << params.w << std::endl << std::endl;\n\n            iter = iter+1;\n        }\n\n        //-------------------Calculate Currents using Scharfetter-Gummel definition--------------------------\n\n        //continuity_n.calculate_currents();\n        continuity_p.calculate_currents(fullp); //send it fullp, since we find it here anyway\n\n        J_total_Z = continuity_p.get_Jp_Z();// + continuity_n.get_Jn_Z();\n        J_total_X = continuity_p.get_Jp_X();// + continuity_n.get_Jn_X();\n        J_total_Y = continuity_p.get_Jp_Y();// + continuity_n.get_Jn_Y();\n\n//        for (int k = 1; k < num_cell_z; k++)\n//            std::cout << J_total_Z(2,2,k) << std::endl;\n//exit(1);\n\n        //---------------------Write to file----------------------------------------------------------------\n        utils.write_details(params, Va, fullV, fullp, J_total_Z, Up);\n\n        if(Va_cnt >0) utils.write_JV(params, JV, iter, Va, J_total_Z);\n\n\n    }//end of main loop\n\n    JV.close();\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 << \"CPU time = \" << time.count() << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "1759a7ca420badfa1917ebc0ae674951c4c3ed77", "size": 25108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3D/C++_implementation/Single-charge-carrier/main.cpp", "max_stars_repo_name": "tgolubev/Mott-Gurney_law_WENO", "max_stars_repo_head_hexsha": "3e3b3ee04747506a81fd06b3295b78df51c83333", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-08-02T03:56:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T08:58:01.000Z", "max_issues_repo_path": "3D/C++_implementation/Single-charge-carrier/main.cpp", "max_issues_repo_name": "tgolubev/Mott-Gurney_law_WENO", "max_issues_repo_head_hexsha": "3e3b3ee04747506a81fd06b3295b78df51c83333", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-28T06:10:57.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-20T03:35:30.000Z", "max_forks_repo_path": "3D/C++_implementation/Single-charge-carrier/main.cpp", "max_forks_repo_name": "tgolubev/Drift-Diffusion_models", "max_forks_repo_head_hexsha": "3e3b3ee04747506a81fd06b3295b78df51c83333", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-04T20:13:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T03:05:32.000Z", "avg_line_length": 52.1995841996, "max_line_length": 332, "alphanum_fraction": 0.6006452127, "num_tokens": 6631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5089068727263061}}
{"text": "/*\n * @author Jenna Reher (jreher@caltech.edu)\n */\n\n#ifndef CASSIE_GEOMETRY_HPP\n#define CASSIE_GEOMETRY_HPP\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <unsupported/Eigen/EulerAngles>\n\n/* FUNCTION eulerZYX(float q[4], float euler[3])\n * Convert the quaternion to euler angles in ZYX rotation order.\n */\nvoid eulerZYX(Eigen::Quaterniond &q, Eigen::EulerAnglesZYXd &euler);\n\nvoid eulerXYZ(Eigen::Quaterniond &q, Eigen::EulerAnglesXYZd &euler);\n\nvoid eulerXYZ(Eigen::Matrix3d &R, Eigen::EulerAnglesXYZd &euler);\n\nEigen::Matrix3d skew(Eigen::Vector3d &v);\n\n\n#endif // CASSIE_GEOMETRY_HPP\n", "meta": {"hexsha": "2a4a69f65b3299b02145e30991a6efcc372d66b1", "size": 599, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cassie_common_toolbox/geometry.hpp", "max_stars_repo_name": "jpreher/cassie_common_toolbox", "max_stars_repo_head_hexsha": "e01065a56e4a0a71607bfe412834a9a8b541fe28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-11T22:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-11T22:56:02.000Z", "max_issues_repo_path": "include/cassie_common_toolbox/geometry.hpp", "max_issues_repo_name": "jpreher/cassie_common_toolbox", "max_issues_repo_head_hexsha": "e01065a56e4a0a71607bfe412834a9a8b541fe28", "max_issues_repo_licenses": ["MIT"], "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/cassie_common_toolbox/geometry.hpp", "max_forks_repo_name": "jpreher/cassie_common_toolbox", "max_forks_repo_head_hexsha": "e01065a56e4a0a71607bfe412834a9a8b541fe28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-04T21:22:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T21:22:53.000Z", "avg_line_length": 23.96, "max_line_length": 68, "alphanum_fraction": 0.754590985, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5089068616592021}}
{"text": "#include <Eigen/Geometry>\n\n#include \"recalibration.h\"\n\nvoid Recalibration::translate (std::vector<float>& vertices, const QVector3D &p) {\n\n    for (int i = 0; i < vertices.size(); i += 3) {\n        vertices[i] += p[0];\n        vertices[i+1] += p[1];\n        vertices[i+2] += p[2];\n    }\n}\n\nvoid Recalibration::rotate (std::vector<float>& vertices, const QVector3D &angle) {\n\n    Eigen::Vector4f vec;\n    Eigen::Vector4f vecRot;\n\n    Eigen::Quaternionf q = Eigen::Quaternionf(0, angle.x(), angle.y(), angle.z());\n    Eigen::Quaternionf qInv = q.inverse();\n\n    for (int i = 0; i < vertices.size(); i += 3) {\n\n        vec = Eigen::Vector4f(vertices[i], vertices[i+1], vertices[i+2], 0);\n\n        vecRot = q * vec * qInv;\n\n        vertices[i] = vecRot.x();\n        vertices[i+1] = vecRot.y();\n        vertices[i+2] = vecRot.z();\n    }\n}\n\nvoid Recalibration::recalibrate (std::vector<float>& vertices, const QVector3D &v1, const QVector3D &v2, const QVector3D &v3, const QVector3D &v1p, const QVector3D &v2p, const QVector3D &v3p) {\n\n    // Translation\n    QVector3D vecTranslation = vectorPointToPoint(v1, v1p);\n    translate(vertices, vecTranslation);\n\n    // Rotation\n    QVector3D angle1 = angleBetweenVectors(v1p, v2, v1p, v2); // A v\u00e9rifier\n    QVector3D angle2 = angleBetweenVectors(v1p, v3, v1p, v3); // A v\u00e9rifier\n\n    rotate (vertices, angle1 + angle2);\n}\n\nQVector3D Recalibration::vectorPointToPoint(const QVector3D &p1,const  QVector3D &p2) const{\n\n    return QVector3D(p2.x() - p1.x(), p2.y() - p1.y(), p2.z() - p1.z());\n}\n\n\nQVector3D Recalibration::angleBetweenVectors(const QVector3D& ov1, const QVector3D& fv1, const QVector3D& ov2, const QVector3D& fv2) const {\n\n    QVector3D res;\n\n    // Axe X\n\n    QVector3D dirv1 = QVector3D(fv1.x() - fv1.x(), 0, 0);\n    QVector3D dirv2 = QVector3D(fv2.x() - fv2.x(), 0, 0);\n\n    float scalar = dirv1.x() * dirv2.x();\n\n    float norm = sqrt(dirv1.x() * dirv1.x()) * sqrt(dirv2.x() * dirv2.x());\n\n    res.setX(acos(scalar / norm));\n\n    // Axe Y\n\n    dirv1 = QVector3D(0, fv1.y() - fv1.y(), 0);\n    dirv2 = QVector3D(0, fv2.y() - fv2.y(), 0);\n\n    scalar = dirv1.y() * dirv2.y();\n\n    norm = sqrt(dirv1.y() * dirv1.y()) * sqrt(dirv2.y() * dirv2.y());\n\n    res.setY(acos(scalar / norm));\n\n    // Axe Z\n\n    dirv1 = QVector3D(fv1.z() - fv1.z(), 0, 0);\n    dirv2 = QVector3D(fv2.z() - fv2.z(), 0, 0);\n\n    scalar = dirv1.z() * dirv2.z();\n\n    norm = sqrt(dirv1.z() * dirv1.z()) * sqrt(dirv2.z() * dirv2.z());\n\n    res.setZ(acos(scalar / norm));\n\n    return res;\n\n    /*\n\n    QVector3D dirv1 = QVector3D(fv1.x - fv1.x, fv1.y - ov1.y, fv1.z - ov1.z);\n    QVector3D dirv2 = QVector3D(fv2.x - fv2.x, fv2.y - ov2.y, fv2.z - ov2.z);\n\n    float scalar = dirv1.x * dirv2.x + irv1.y * dirv2.y + irv1.z * dirv2.z;\n\n    float norm = sqrt(dirv1.x() * dirv1.x() + dirv1.y() * dirv1.y() + dirv1.z() * dirv1.z()) *\n                 sqrt(dirv2.x() * dirv2.x() + dirv2.y() * dirv2.y() + dirv2.z() * dirv2.z());\n\n    return acos(scalarP / norm);*/\n}\n", "meta": {"hexsha": "d32ad21b095a7bfdb2fc8226305eb2bee4e6158c", "size": 2979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/recalibration.cpp", "max_stars_repo_name": "eolhing/MG", "max_stars_repo_head_hexsha": "fb04ed22bd701499fecac894b3324a05b2e37837", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/recalibration.cpp", "max_issues_repo_name": "eolhing/MG", "max_issues_repo_head_hexsha": "fb04ed22bd701499fecac894b3324a05b2e37837", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/recalibration.cpp", "max_forks_repo_name": "eolhing/MG", "max_forks_repo_head_hexsha": "fb04ed22bd701499fecac894b3324a05b2e37837", "max_forks_repo_licenses": ["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.6442307692, "max_line_length": 193, "alphanum_fraction": 0.588788184, "num_tokens": 1057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.508906861659202}}
{"text": "//\n// Copyright 2019 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 <boost/gil/detail/math.hpp>\n#include <boost/gil/image_processing/numeric.hpp>\n\n#include <boost/core/lightweight_test.hpp>\n\n#include <algorithm>\n\n#include \"test_utility_output_stream.hpp\"\n\nnamespace gil = boost::gil;\n\nvoid test_dx_sobel_kernel() {\n  auto const kernel = gil::generate_dx_sobel(1);\n  BOOST_TEST_ALL_EQ(kernel.begin(), kernel.end(), gil::detail::dx_sobel.begin(),\n                    gil::detail::dx_sobel.end());\n}\n\nvoid test_dx_scharr_kernel() {\n  auto const kernel = gil::generate_dx_scharr(1);\n  BOOST_TEST_ALL_EQ(kernel.begin(), kernel.end(),\n                    gil::detail::dx_scharr.begin(),\n                    gil::detail::dx_scharr.end());\n}\n\nvoid test_dy_sobel_kernel() {\n  auto const kernel = gil::generate_dy_sobel(1);\n  BOOST_TEST_ALL_EQ(kernel.begin(), kernel.end(), gil::detail::dy_sobel.begin(),\n                    gil::detail::dy_sobel.end());\n}\n\nvoid test_dy_scharr_kernel() {\n  auto const kernel = gil::generate_dy_scharr(1);\n  BOOST_TEST_ALL_EQ(kernel.begin(), kernel.end(),\n                    gil::detail::dy_scharr.begin(),\n                    gil::detail::dy_scharr.end());\n}\n\nint main() {\n  test_dx_sobel_kernel();\n  test_dx_scharr_kernel();\n  test_dy_sobel_kernel();\n  test_dy_scharr_kernel();\n  return boost::report_errors();\n}\n", "meta": {"hexsha": "bf7c520928eaecded18515d974139a792a8bda8f", "size": 1548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/image_processing/sobel_scharr.cpp", "max_stars_repo_name": "sdebionne/gil-reformated", "max_stars_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "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/core/image_processing/sobel_scharr.cpp", "max_issues_repo_name": "sdebionne/gil-reformated", "max_issues_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "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/core/image_processing/sobel_scharr.cpp", "max_forks_repo_name": "sdebionne/gil-reformated", "max_forks_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "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.7692307692, "max_line_length": 80, "alphanum_fraction": 0.680878553, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5089068505920972}}
{"text": "#include \"problem_generator.h\"\n#include <Eigen/Dense>\n#include <random>\n#include <vector>\n\nnamespace pose_lib {\n\nstatic const double kPI = 3.14159265358979323846;\n\ndouble CalibPoseValidator::compute_pose_error(const ProblemInstance &instance, const CameraPose &pose) {\n  return (instance.pose_gt.R - pose.R).norm() + (instance.pose_gt.t - pose.t).norm() + std::abs(instance.pose_gt.alpha - pose.alpha);\n}\n\nbool CalibPoseValidator::is_valid(const ProblemInstance &instance, const CameraPose &pose, double tol) {\n  if ((pose.R.transpose() * pose.R - Eigen::Matrix3d::Identity()).norm() > tol)\n    return false;\n\n  // Point to point correspondences\n  // alpha * p + lambda*x = R*X + t\n  for (int i = 0; i < instance.x_point_.size(); ++i) {\n    double err = 1.0 - std::abs(instance.x_point_[i].dot((pose.R * instance.X_point_[i] + pose.t - pose.alpha * instance.p_point_[i]).normalized()));\n    if (err > tol)\n      return false;\n  }\n\n  // Point to Line correspondences\n  // alpha * p + lambda * x = R*(X + mu*V) + t\n  for (int i = 0; i < instance.x_line_.size(); ++i) {\n    // lambda * x - mu * R*V = R*X + t - alpha * p\n    // x.cross(R*V).dot(R*X+t-alpha.p) = 0\n    Eigen::Vector3d X = pose.R * instance.X_line_[i] + pose.t - pose.alpha * instance.p_line_[i];\n    double err = instance.x_line_[i].cross(pose.R * instance.V_line_[i]).normalized().dot(X);\n\n    if (err > tol)\n      return false;\n  }\n\n  // Line to point correspondences\n  // l'*(R*X + t - alpha*p) = 0\n  for (int i = 0; i < instance.l_line_point_.size(); ++i) {\n\n    Eigen::Vector3d X = pose.R * instance.X_line_point_[i] + pose.t - pose.alpha * instance.p_line_point_[i];\n\n    double err = std::abs(instance.l_line_point_[i].dot(X.normalized()));\n    if (err > tol)\n      return false;\n  }\n\n  // Line to line correspondences\n  // l'*(R*(X + mu*V) + t - alpha*p) = 0\n  for (int i = 0; i < instance.l_line_line_.size(); ++i) {\n\n    Eigen::Vector3d X = pose.R * instance.X_line_line_[i] + pose.t - pose.alpha * instance.p_line_line_[i];\n    Eigen::Vector3d V = pose.R * instance.V_line_line_[i];\n\n    double err = std::abs(instance.l_line_line_[i].dot(X.normalized())) + std::abs(instance.l_line_line_[i].dot(V.normalized()));\n    if (err > tol)\n      return false;\n  }\n\n  return true;\n}\n\ndouble UnknownFocalValidator::compute_pose_error(const ProblemInstance &instance, const CameraPose &pose) {\n  return (instance.pose_gt.R - pose.R).norm() + (instance.pose_gt.t - pose.t).norm() + std::abs(instance.pose_gt.alpha - pose.alpha);\n}\n\nbool UnknownFocalValidator::is_valid(const ProblemInstance &instance, const CameraPose &pose, double tol) {\n  if ((pose.R.transpose() * pose.R - Eigen::Matrix3d::Identity()).norm() > tol)\n    return false;\n\n  if (pose.alpha < 0)\n    return false;\n\n  Eigen::Matrix3d Kinv;\n  Kinv.setIdentity();\n  Kinv(2, 2) = pose.alpha;\n  // lambda*diag(1,1,alpha)*x = R*X + t\n  for (int i = 0; i < instance.x_point_.size(); ++i) {\n    double err = 1.0 - std::abs((Kinv * instance.x_point_[i]).normalized().dot((pose.R * instance.X_point_[i] + pose.t).normalized()));\n    if (err > tol)\n      return false;\n  }\n\n  return true;\n}\n\n\ndouble RadialPoseValidator::compute_pose_error(const ProblemInstance &instance, const CameraPose &pose) {\n  // Only compute up to sign for radial cameras\n\n  double err1 = (instance.pose_gt.R.topRows(2) - pose.R.topRows(2)).norm() + (instance.pose_gt.t.topRows(2) - pose.t.topRows(2)).norm();\n  double err2 = (instance.pose_gt.R.topRows(2) + pose.R.topRows(2)).norm() + (instance.pose_gt.t.topRows(2) + pose.t.topRows(2)).norm();\n\n  return std::min(err1, err2);\n}\n\nbool RadialPoseValidator::is_valid(const ProblemInstance &instance, const CameraPose &pose, double tol) {\n  if ((pose.R.transpose() * pose.R - Eigen::Matrix3d::Identity()).norm() > tol)\n    return false;\n\n  // Point to point correspondences -- Convert these to line correspondences\n  // alpha * p + lambda*x = R*X + t\n  for (int i = 0; i < instance.x_point_.size(); ++i) {\n    Eigen::Vector3d radial_line{-instance.x_point_[i](1),instance.x_point_[i](0), 0.0};\n    Eigen::Vector3d X = pose.R * instance.X_point_[i] + pose.t;\n    double err = std::abs(radial_line.dot(X.normalized()));\n    if (err > tol)\n      return false;\n  }\n\n  // Line to point correspondences\n  // l'*(R*X + t) = 0\n  for (int i = 0; i < instance.l_line_point_.size(); ++i) {\n    Eigen::Vector3d X = pose.R * instance.X_line_point_[i] + pose.t;\n\n    double err = std::abs(instance.l_line_point_[i].dot(X.normalized()));\n    if (err > tol)\n      return false;\n  }\n\n  return true;\n}\n\nvoid set_random_pose(CameraPose &pose, bool upright) {\n  if (upright) {\n    Eigen::Vector2d r;\n    r.setRandom().normalize();\n    //pose.R << r(0), 0.0, r(1), 0.0, 1.0, 0.0, -r(1), 0.0, r(0); // y-gravity\n    pose.R << r(0), r(1), 0.0, -r(1), r(0), 0.0, 0.0, 0.0, 1.0; // z-gravity\n  } else {\n    pose.R = Eigen::Quaternion<double>::UnitRandom();\n  }\n  pose.t.setRandom();\n}\n\nvoid generate_problems(int n_problems, std::vector<ProblemInstance> *problem_instances,\n                       const ProblemOptions &options) {\n  problem_instances->clear();\n  problem_instances->reserve(n_problems);\n\n  double fov_scale = std::tan(options.camera_fov_ / 2.0 * kPI / 180.0);\n\n  // Random generators\n  std::default_random_engine random_engine;\n  std::uniform_real_distribution<double> depth_gen(options.min_depth_, options.max_depth_);\n  std::uniform_real_distribution<double> coord_gen(-fov_scale, fov_scale);\n  std::uniform_real_distribution<double> scale_gen(options.min_scale_, options.max_scale_);\n  std::uniform_real_distribution<double> focal_gen(options.min_focal_, options.max_focal_);\n  std::normal_distribution<double> direction_gen(0.0, 1.0);\n  std::normal_distribution<double> offset_gen(0.0, 1.0);\n\n  for (int i = 0; i < n_problems; ++i) {\n    ProblemInstance instance;\n    set_random_pose(instance.pose_gt, options.upright_);\n\n    if (options.unknown_scale_) {\n      instance.pose_gt.alpha = scale_gen(random_engine);\n    } else if (options.unknown_focal_) {\n      instance.pose_gt.alpha = focal_gen(random_engine);\n    }\n\n    // Point to point correspondences\n    instance.x_point_.reserve(options.n_point_point_);\n    instance.X_point_.reserve(options.n_point_point_);\n    instance.p_point_.reserve(options.n_point_point_);\n    for (int j = 0; j < options.n_point_point_; ++j) {\n\n      Eigen::Vector3d p{0.0, 0.0, 0.0};\n      Eigen::Vector3d x{coord_gen(random_engine), coord_gen(random_engine), 1.0};\n      x.normalize();\n      Eigen::Vector3d X;\n\n      if (options.generalized_) {\n        p << offset_gen(random_engine), offset_gen(random_engine), offset_gen(random_engine);\n      }\n\n      X = instance.pose_gt.alpha * p + x * depth_gen(random_engine);\n\n      X = instance.pose_gt.R.transpose() * (X - instance.pose_gt.t);\n\n      if (options.unknown_focal_) {\n        x.block<2, 1>(0, 0) *= instance.pose_gt.alpha;\n        x.normalize();\n      }\n\n      instance.x_point_.push_back(x);\n      instance.X_point_.push_back(X);\n      instance.p_point_.push_back(p);\n    }\n\n    // Point to line correspondences\n    instance.x_line_.reserve(options.n_point_line_);\n    instance.X_line_.reserve(options.n_point_line_);\n    instance.V_line_.reserve(options.n_point_line_);\n    instance.p_line_.reserve(options.n_point_line_);\n    for (int j = 0; j < options.n_point_line_; ++j) {\n      Eigen::Vector3d p{0.0, 0.0, 0.0};\n      Eigen::Vector3d x{coord_gen(random_engine), coord_gen(random_engine), 1.0};\n      x.normalize();\n      Eigen::Vector3d X;\n\n      if (options.generalized_) {\n        p << offset_gen(random_engine), offset_gen(random_engine), offset_gen(random_engine);\n      }\n      X = instance.pose_gt.alpha * p + x * depth_gen(random_engine);\n      X = instance.pose_gt.R.transpose() * (X - instance.pose_gt.t);\n\n      Eigen::Vector3d V{direction_gen(random_engine), direction_gen(random_engine), direction_gen(random_engine)};\n      V.normalize();\n\n      // Translate X such that X.dot(V) = 0\n      X = X - V.dot(X) * V;\n\n      if (options.unknown_focal_) {\n        // TODO implement this.\n      }\n\n      instance.x_line_.push_back(x);\n      instance.X_line_.push_back(X);\n      instance.V_line_.push_back(V);\n      instance.p_line_.push_back(p);\n    }\n\n    // Line to point correspondences\n    instance.l_line_point_.reserve(options.n_line_point_);\n    instance.X_line_point_.reserve(options.n_line_point_);\n    instance.p_line_point_.reserve(options.n_line_point_);\n    for (int j = 0; j < options.n_line_point_; ++j) {\n      Eigen::Vector3d p{0.0, 0.0, 0.0};\n      Eigen::Vector3d x{coord_gen(random_engine), coord_gen(random_engine), 1.0};\n      x.normalize();\n      Eigen::Vector3d X;\n\n      if (options.generalized_) {\n        p << offset_gen(random_engine), offset_gen(random_engine), offset_gen(random_engine);\n      }\n      X = instance.pose_gt.alpha * p + x * depth_gen(random_engine);\n      X = instance.pose_gt.R.transpose() * (X - instance.pose_gt.t);\n\n      // Cross product with random vector to generate line\n      Eigen::Vector3d l;\n      if(options.radial_lines_) { \n        // Line passing through image center\n        l = x.cross(Eigen::Vector3d{0.0, 0.0, 1.0});\n      } else {\n        // Random line\n        l = x.cross(Eigen::Vector3d(direction_gen(random_engine), direction_gen(random_engine), direction_gen(random_engine)));\n      }\n       \n      l.normalize();\n\n      if (options.unknown_focal_) {\n        // TODO implement this.\n      }\n\n      instance.l_line_point_.push_back(l);\n      instance.X_line_point_.push_back(X);\n      instance.p_line_point_.push_back(p);\n    }\n\n    // Line to line correspondences\n    instance.l_line_line_.reserve(options.n_line_line_);\n    instance.X_line_line_.reserve(options.n_line_line_);\n    instance.V_line_line_.reserve(options.n_line_line_);\n    instance.p_line_line_.reserve(options.n_line_line_);\n    for (int j = 0; j < options.n_line_line_; ++j) {\n      Eigen::Vector3d p{0.0, 0.0, 0.0};\n      Eigen::Vector3d x{coord_gen(random_engine), coord_gen(random_engine), 1.0};\n      x.normalize();\n      Eigen::Vector3d X;\n\n      if (options.generalized_) {\n        p << offset_gen(random_engine), offset_gen(random_engine), offset_gen(random_engine);\n      }\n      X = instance.pose_gt.alpha * p + x * depth_gen(random_engine);\n      X = instance.pose_gt.R.transpose() * (X - instance.pose_gt.t);\n\n      Eigen::Vector3d V{direction_gen(random_engine), direction_gen(random_engine), direction_gen(random_engine)};\n      V.normalize();\n\n      // Translate X such that X.dot(V) = 0\n      X = X - V.dot(X) * V;\n\n      Eigen::Vector3d l = x.cross(instance.pose_gt.R * V);\n      l.normalize();\n\n      if (options.unknown_focal_) {\n        // TODO implement this.\n      }\n\n      instance.l_line_line_.push_back(l);\n      instance.X_line_line_.push_back(X);\n      instance.V_line_line_.push_back(V);\n      instance.p_line_line_.push_back(p);\n    }\n\n    problem_instances->push_back(instance);\n  }\n}\n\n}; // namespace pose_lib", "meta": {"hexsha": "7d1d6236661ec5e9ffbe614208e5491689d135bd", "size": 10916, "ext": "cc", "lang": "C++", "max_stars_repo_path": "benchmark/problem_generator.cc", "max_stars_repo_name": "pmoulon/PoseLib", "max_stars_repo_head_hexsha": "f0ca0d076d3ede9730dfece05890e120f46684a8", "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": "benchmark/problem_generator.cc", "max_issues_repo_name": "pmoulon/PoseLib", "max_issues_repo_head_hexsha": "f0ca0d076d3ede9730dfece05890e120f46684a8", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/problem_generator.cc", "max_forks_repo_name": "pmoulon/PoseLib", "max_forks_repo_head_hexsha": "f0ca0d076d3ede9730dfece05890e120f46684a8", "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.1456953642, "max_line_length": 149, "alphanum_fraction": 0.6578417003, "num_tokens": 3010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5089002234015485}}
{"text": "//\n// Created by Xinyu Zhang on 3/26/21.\n//\n#include <iostream>\n\n// #include <Eigen/Dense>\n// #include <cosan/io/utils.h>\n#include <cosan/data/CosanData.h>\n// #include <cosan/model/CosanLinearRegression.h>\n// #include <cosan/model/CosanRidgeRegression.h>\n//using namespace Eigen;\n//using namespace std;\n\nint main() {\n//    Cosan::CosanRawData CD(\"./example_data/toy/X_.csv\",\"./example_data/toy/y.csv\");\n    Cosan::CosanRawData<long double> CRD(\"./example_data/toy2/X_.csv\");\n\n    // Cosan::CosanLinearRegression CLR(true);\n//     CLR.fit(CD.GetInput(),CD.GetTarget());\n    std::cout<<CRD.GetSummaryMessageX()<<std::endl;\n    std::cout<<CRD.GetInput()<<std::endl;\n//    double RegularizationTerm = 1;\n//    Cosan::CosanRidgeRegression CRR(RegularizationTerm,true);\n//    CRR.fit(CD.GetInput(),CD.GetTarget());\n//    std::cout<<CRR.GetBeta()<<std::endl;\n//    save_csv(\"./example_data/toy/beta_c1.csv\",CRR.GetBeta());\n\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<<y.rows()<<y.cols()<<std::endl;\n    // Eigen::MatrixXd beta = (X.transpose()*X).ldlt().solve(X.transpose()*y);\n    \n    return 0;\n//\n//    m.transposeInPlace();\n//    cout<<m<<endl;\n//    m.resize(1,4);\n//    cout<<n<<endl;\n}\n", "meta": {"hexsha": "c15e496937132b57d9b100bcf31fd007e93ac8ba", "size": 1250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test.cpp", "max_stars_repo_name": "zhxinyu/cosan", "max_stars_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_stars_repo_licenses": ["MIT"], "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": "zhxinyu/cosan", "max_issues_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_issues_repo_licenses": ["MIT"], "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": "zhxinyu/cosan", "max_forks_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-13T05:56:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T05:56:38.000Z", "avg_line_length": 29.7619047619, "max_line_length": 85, "alphanum_fraction": 0.6136, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5089002234015485}}
{"text": "#include <string>\n#include <algorithm>\n#include <vector>\n#include <array>\n#include <memory>\n#include <map>\n#include <cassert>\n#include <fstream>\n#include \"DatasetARX.h\"\n#include \"GaussSeq.h\"\n#include \"ZeroSeq.h\"\n#include \"utils.h\"\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp> \nusing utils::my_float;\nusing boost::random::uniform_real_distribution;\n\n\n/*\n *  Member variables\n */\nboost::random::mt19937 DatasetARX::gen {};      // static generator\n\n/*\n *  Helper member functions\n */\n\n// Seed previous values from uniform distribution\nvoid DatasetARX::seed_features() {\n    uniform_real_distribution<my_float> u_seed(-1, 1);\n\n    feat_5[0] = u_seed(gen);\n    for (auto i = 0; i < 3; i++) {\n        feat_10[i] = u_seed(gen);\n    }\n    for (auto i = 0; i < 5; i++) {\n        feat_20[i] = u_seed(gen);\n    }\n}\nvoid DatasetARX::noise_one() {\n    this->seed_features();\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        feats.push_back(std::make_unique<GaussSeq>());\n    }\n}\nvoid DatasetARX::noise_two() {\n    this->seed_features();\n\n    uniform_real_distribution<my_float> u_mean(-10, 10);\n    uniform_real_distribution<my_float> u_std(0.1, 5);\n\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        feats.push_back(std::make_unique<GaussSeq>(u_mean(gen), u_std(gen)));\n    }\n}\nvoid DatasetARX::noise_three() {\n    this->seed_features();\n\n    uniform_real_distribution<my_float> u_const(0, 1);\n    uniform_real_distribution<my_float> u_coeff(-0.9, 0.9);\n    uniform_real_distribution<my_float> u_seed(0, 1);\n    std::vector<my_float> seed_vect {u_seed(gen),};\n    std::map<int, my_float> coeff_map {\n        {1, u_coeff(gen)},\n    };\n\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        // prep seq backing\n        coeff_map[1] = u_coeff(gen);\n        seed_vect[0] = u_seed(gen);\n\n        ARSeq in_seq(coeff_map, u_const(gen));\n        in_seq.seed_prev_vals(seed_vect);\n\n        feats.push_back(std::make_unique<ARSeq>(in_seq));\n    }\n}\nvoid DatasetARX::noise_four() {\n    this->seed_features();\n\n    uniform_real_distribution<my_float> u_const(-1000000, -999999);\n    uniform_real_distribution<my_float> u_coeff(1.1, 2);\n    uniform_real_distribution<my_float> u_seed(0, 0.0000001);\n    std::vector<my_float> seed_vect {u_seed(gen),};\n    std::map<int, my_float> coeff_map {\n        {1, u_coeff(gen)},\n    };\n\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        // prep seq backing\n        coeff_map[1] = u_coeff(gen);\n        seed_vect[0] = u_seed(gen);\n\n        ARSeq in_seq(coeff_map, u_const(gen));\n        in_seq.seed_prev_vals(seed_vect);\n\n        feats.push_back(std::make_unique<ARSeq>(in_seq));\n    }\n}\n\n/*\n *  Constructors and destructors\n */\nDatasetARX::DatasetARX(std::string file_name):\n    fname{file_name.append(\".csv\")}\n    {};\n\nDatasetARX::DatasetARX(std::string file_name,  unsigned char type):\n    fname{file_name.append(\".csv\")},\n    noise_type{type} {\n    set_noise(type);\n}\n\n/*\n *  Member functions\n */\nvoid DatasetARX::set_noise(unsigned char type) {\n    this->noise_type = type;\n\n    switch (type) {\n        case 1: this->noise_one();\n                break;\n        case 2: this->noise_two();\n                break;\n        case 3: this->noise_three();\n                break;\n        case 4: this->noise_four();\n                break;\n    }\n}\nstd::array<std::array<my_float, utils::FEAT_COUNT + 1>, utils::TIME_STEP>\n    DatasetARX::generate_normalized_dat() {\n    namespace mp = boost::multiprecision;\n    constexpr int T = utils::TIME_STEP;\n    constexpr int F = utils::FEAT_COUNT;\n    // observe storage[feat][time] indexing\n    std::array<std::array<my_float, T + 1>, F + 1> storage {};\n\n    /*\n     *  Prepare progress bar\n     */\n    // offset used to determine when to update progress bar\n    int offset_mod = static_cast<int>(T / 10);\n    int offset_counter {0};\n    // print initial progress bar\n    std::cout << \"[\";\n    for (auto i = 0; i < 10; i++) {\n        std::cout << \" \";\n    }\n    std::cout << \"]\\r\";\n\n\n    /*\n     *  Store non-normalized values\n     */\n\n    // Store time-delayed values\n    // If of noise types 3 or 4, then there is one previous value as a ARSeq.\n    // Otherwise, simply invoke next()\n    if (this->noise_type == 3 || this->noise_type == 4) {\n        for (auto f = 0; f < F + 1; f++) {\n            if (f == F) \n                storage[f][0] = 0.1*feat_5[0] + 0.25*feat_10[2] + 0.5*feat_20[4] + \n                    error_term.next();\n            else\n                storage[f][0] = dynamic_cast<ARSeq*>(feats[f].get())->get_prev_val()[0];\n        }\n    } else {\n        for (auto f = 0; f < F + 1; f++) {\n            if (f == F) \n                storage[f][0] = 0.1*feat_5[0] + 0.25*feat_10[2] + 0.5*feat_20[4] + \n                    error_term.next();\n            else \n                storage[f][0] = feats[f]->next();\n        }\n    }\n\n    // Store current values (those non-negative)\n    my_float temp_feat_5 {0};\n    my_float temp_feat_10 {0};\n    my_float temp_feat_20 {0};\n\n    for (auto t = 1; t < T + 1; t++) {\n        // print progress bar\n        if ((t - 1) % offset_mod == 0) {\n            offset_counter++;\n\n            std::cout << \"[\";\n            for (auto i = 0; i < offset_counter; i++) {\n                std::cout << \"X\";\n            }\n            for (auto i = 0; i < 10 - offset_counter; i++) {\n                std::cout << \" \";\n            }\n            std::cout << \"]\\r\";\n        }\n\n        // write and record sequences\n        for (auto f = 0; f < F + 1; f++) {\n            // target column\n            if (f == F) {\n                storage[f][t] = 0.1*feat_5[0] + 0.25*feat_10[2] + 0.5*feat_20[4] + \n                    error_term.next();\n\n                // update past values\n                utils::shift_vector(this->feat_5);\n                utils::shift_vector(this->feat_10);\n                utils::shift_vector(this->feat_20);\n\n                feat_5[0] = temp_feat_5;\n                feat_10[0] = temp_feat_10;\n                feat_20[0] = temp_feat_20;\n            } else if (f == 5) {\n                temp_feat_5 = feats[f]->next();\n                storage[f][t] = temp_feat_5;\n            } else if (f == 10) {\n                temp_feat_10 = feats[f]->next();\n                storage[f][t] = temp_feat_10;\n            } else if (f == 20) {\n                temp_feat_20 = feats[f]->next();\n                storage[f][t] = temp_feat_20;\n            } else {\n                storage[f][t] = feats[f]->next();\n            }\n        }\n    }\n\n    /*\n     *  Normalize array values according to utils::NORM_VAL\n     */\n    my_float feat_min {0};\n    my_float feat_max {0};\n    // observe normalized_feats[time][feat] indexing\n    std::array<std::array<my_float, F + 1>, T> normalized_feats {};\n\n    // no need to check for zero values since we cannot use those with ARX\n    for (auto f = 0; f < F + 1; f++) {\n        feat_min = *std::min_element(storage[f].begin(), storage[f].end());\n        feat_max = *std::max_element(storage[f].begin(), storage[f].end());\n\n        for (auto t = 0; t < T; t++) {\n            if (feat_max - feat_min == 0) \n                normalized_feats[t][f] = (utils::NORM_VAL * 2 * (storage[f][t + 1] - feat_min)) - \n                    utils::NORM_VAL;\n            else\n                normalized_feats[t][f] = (utils::NORM_VAL * 2 * ((storage[f][t + 1] - feat_min) / \n                    (feat_max - feat_min))) - utils::NORM_VAL;\n        }\n    }\n\n    return normalized_feats;\n} \n\nvoid DatasetARX::write_csv() {\n    // was the noise value assigned?\n    assert(this->noise_type != 10);\n\n\n    // storage for normalize values\n    constexpr int T = utils::TIME_STEP;\n    constexpr int F = utils::FEAT_COUNT;\n    std::array<std::array<my_float, F + 1>, T> storage = generate_normalized_dat();\n\n    // initialize csv\n    std::ofstream synth_data {this->fname};\n    synth_data << std::setprecision(25);\n    \n    // prepare labels\n    for (auto i = 0; i < utils::FEAT_COUNT + 2; i++) {\n        if (i == 0)\n            synth_data << \"Time,\";\n        else if (i == utils::FEAT_COUNT + 1)\n            synth_data << \"Target\\n\";\n        else \n            synth_data << \"Feature_\" << i << \",\";\n    }\n\n    // write values\n    for (auto t = 0; t < T; t++) {\n        for (auto f = 0; f < F + 2; f++) {\n            // time column\n            if (f == 0)\n                synth_data << t << \",\";\n            // target column\n            else if (f == utils::FEAT_COUNT + 1) {\n                synth_data << storage[t][f - 1] << \"\\n\";\n            } else {\n                synth_data << storage[t][f - 1] << \",\";\n            }\n        }\n    }\n    std::cout << \"\\nFinished writing \" << this->fname << \"!\\n\";\n    synth_data.close();\n}\n", "meta": {"hexsha": "b864a4550389213aa51874b7c9b5e1b3fd9efd51", "size": 8758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gen-data/lib/DatasetARX.cpp", "max_stars_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_stars_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gen-data/lib/DatasetARX.cpp", "max_issues_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_issues_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gen-data/lib/DatasetARX.cpp", "max_forks_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_forks_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_forks_repo_licenses": ["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.5878378378, "max_line_length": 98, "alphanum_fraction": 0.5365380224, "num_tokens": 2462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5089002063497077}}
{"text": "//\n//  sall.cpp\n//  Percy\n//\n//  Created by Linhai Zhao on 4/22/15.\n//  Copyright (c) 2015 Linhai Zhao. All rights reserved.\n//\n\n#include <boost/python.hpp>\n#include <math.h>\n#include <map>\n#include <string>\n#include <vector>\n#include <iostream>\n\nusing namespace std;\ntypedef std::vector<int> IntVector;\ntypedef std::vector<std::string> StringVector;\ntypedef std::vector<StringVector> VecStringVec;\ntypedef map<int, StringVector> MyMap;\n\n\n/*int main(){\n\tdouble s_all;\n    StringVector fallele;\n    MyMap fam_allele;\n    IntVector affnf;\n    affnf={2,3};\n    fallele={\"gp0\",\"gp1\",\"gm0\",\"gm1\"};\n    fam_allele[2]={\"gp0\",\"gm0\"};\n    fam_allele[3]={\"gp1\",\"gm0\"};\n    fam_allele[4]={\"gp0\",\"gm1\"};\n    s_all=sall(&affnf,&fam_allele, &fallele);\n    return 0;\n}*/\n\nint factorial(int n){\n    int fac=1;\n    if (n==0) {\n        return 1;\n    }\n    if (n<0) {\n        return -99;\n    }\n    while (n>0) {\n        fac = fac*n;\n        n--;\n    }\n    return fac;\n}\n\ndouble sall(IntVector*aff, MyMap*fam_a,StringVector*fa, IntVector*fm,bool rv_flag){\n    IntVector tmp_aff = *aff;\n    int affnum = tmp_aff.size();\n    double sall;\n    MyMap fam_allele = *fam_a;\n    StringVector founderallele=*fa;\n    IntVector foundermarker=*fm;\n    int total = pow(2.0,affnum);\n    int total_count=0;\n    for (int i=0; i<total; i++) {\n        //for each unique selection of alleles\n        //to binary;\n        string bin;\n        int number = i;\n        char holder=' ';\n        if (number==0) {\n            bin='0';\n        }\n        while(number !=0){\n            holder=number%2+'0';\n            bin=holder+bin;\n            number /=2;\n        }\n        //cout<<string((affnum-bin.size()),'0')<<endl;\n        bin=string((affnum-bin.size()),'0')+bin;\n        StringVector pick(affnum);\n        //convert binary digits to founder alleles\n        for (int j=0; j<bin.size(); j++) {\n            int binj = bin[j]-'0'; //convert character to integer\n            pick[j]=fam_allele[tmp_aff[j]][binj];\n        }\n        //h[i]=pick;\n        int tmp_count = 1;\n        //count the occurrences of founder alleles in picked alleles\n        for (StringVector::iterator a=founderallele.begin(); a != founderallele.end(); ++a) {\n            int occurrence=0;// = std::count(pick.begin(), pick.end(), *a);\n\t    if (rv_flag && foundermarker.at(a-founderallele.begin()) != 1 || !rv_flag){\n\t\t\tfor (StringVector::iterator pit=pick.begin(); pit != pick.end();++pit){\n\t\t\t\tif (*pit == *a){occurrence += 1;}\n\t\t\t\t}\n\t\t\t}\n            tmp_count *= factorial(occurrence);\n        }\n        total_count += tmp_count;\n    }\n    sall=double(total_count)/double(total);\n\treturn sall;\n}\n\nIntVector toIntVec(boost::python::list aff){\n\tIntVector t_aff;\n\tfor(int i =0;i<len(aff);++i){\n\t\tint tmp=boost::python::extract<int>(aff[i]);\n\t\tt_aff.push_back(tmp);\n\t}\n\treturn t_aff;\n}\n\nStringVector toStrVec(boost::python::list fa){\n\tStringVector t_fa;\n\tfor(int i = 0; i<len(fa);++i){\n\t\tstring tmp=boost::python::extract<string>(fa[i]);\n\t\tt_fa.push_back(tmp);\n\t}\n\treturn t_fa;\n}\n\nMyMap tomap(boost::python::dict nf){\n\tMyMap t_nf;\n\tboost::python::list keys = nf.keys();\n\tfor(int i=0; i<len(keys);++i){\n\t\tint extracted_key=boost::python::extract<int>(keys[i]);\n\t\tStringVector extracted_val;\n\t\textracted_val.push_back(boost::python::extract<string>(nf[extracted_key][0]));\n\t\textracted_val.push_back(boost::python::extract<string>(nf[extracted_key][1]));\n\t\tt_nf[extracted_key]=extracted_val;\n\t}\n\treturn t_nf;\n}\n\ndouble apply(boost::python::list aff, boost::python::dict fam_a, boost::python::list fa, boost::python::list fm, bool rv_flag){\n\tIntVector caff;\n\tStringVector fallele;\n\tIntVector fmarker;\n\tMyMap cfam_a;\n\tdouble s_all;\n\tcaff = toIntVec(aff);\n\tfallele = toStrVec(fa);\n\tfmarker = toIntVec(fm);\n\tcfam_a = tomap(fam_a);\n\ts_all = sall(&caff,&cfam_a,&fallele,&fmarker,rv_flag);\n\treturn s_all;\n}\n\nBOOST_PYTHON_MODULE(sall_cpp){\n\tusing namespace boost::python;\n\tdef(\"sall\",sall);\n\tdef(\"apply\",apply);\n}\n", "meta": {"hexsha": "4501e4334e7cec79d0d3bfb5230ae6d4970bcb9b", "size": 3933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppextend/sall_rv_complete.cpp", "max_stars_repo_name": "statgenetics/rvnpl", "max_stars_repo_head_hexsha": "22053ca4e24e5486e1179a5e85aaf316a218391f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-28T12:00:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T12:00:34.000Z", "max_issues_repo_path": "cppextend/sall_rv_complete.cpp", "max_issues_repo_name": "changebio/rvnpl", "max_issues_repo_head_hexsha": "22053ca4e24e5486e1179a5e85aaf316a218391f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-03-18T02:39:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-12T08:05:24.000Z", "max_forks_repo_path": "cppextend/sall_rv_complete.cpp", "max_forks_repo_name": "changebio/rvnpl", "max_forks_repo_head_hexsha": "22053ca4e24e5486e1179a5e85aaf316a218391f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-01-26T03:22:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T14:27:51.000Z", "avg_line_length": 26.0463576159, "max_line_length": 127, "alphanum_fraction": 0.6137808289, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.5089002063497077}}
{"text": "// Copyright (c) 2018 Steven Watanabe\n//\n// Distributed under the Boost Software License Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/units2/unit.hpp>\n#include <boost/units2/def.hpp>\n#include <boost/type_index.hpp>\n\n#define BOOST_TEST_MODULE test_unit\n#include <boost/test/unit_test.hpp>\n\nBOOST_UNITS2_DEF(length);\nBOOST_UNITS2_DEF(meter, length);\nBOOST_UNITS2_DEF(yard, meter * std::ratio<9144,10000>());\nBOOST_UNITS2_DEF(foot, yard * std::ratio<1,3>());\nBOOST_UNITS2_DEF(inch, foot * std::ratio<1,12>());\nBOOST_UNITS2_DEF(xmeter, meter);\nBOOST_UNITS2_DEF(sq_meter, meter * meter);\n\ninline constexpr auto centimeter = std::centi() * meter;\n\nstruct degree_factor : boost::units2::scale_base {\n    static constexpr double value() { return 180/3.14159265358979323846; }\n};\nBOOST_UNITS2_DEF(angle);\nBOOST_UNITS2_DEF(radian, angle);\nBOOST_UNITS2_DEF(degree, degree_factor()*radian);\n\n#define TEST_SAME_TYPE(T, U) BOOST_TEST(::boost::typeindex::type_id<decltype(T)>() == ::boost::typeindex::type_id<decltype(U)>())\n#define TEST_NOT_SAME_TYPE(T, U) BOOST_TEST(::boost::typeindex::type_id<decltype(T)>() != ::boost::typeindex::type_id<decltype(U)>())\n\nBOOST_AUTO_TEST_CASE(test_multiply)\n{\n    // Multiplication should yield the same type regardless of argument order.\n    TEST_SAME_TYPE(meter * yard, yard * meter);\n\n    // sq_meter is a distinct type from meter*meter.\n    TEST_NOT_SAME_TYPE(meter * meter * meter, sq_meter * meter);\n\n    // Multiplication by a std::ratio is defined\n    TEST_SAME_TYPE(meter * std::centi(), centimeter);\n    TEST_SAME_TYPE(std::centi() * meter, centimeter);\n\n    // Scale factors should collapse...\n    TEST_SAME_TYPE(std::deci() * centimeter, std::milli() * meter);\n    TEST_SAME_TYPE(centimeter * std::deci(), std::milli() * meter);\n    // ...and should be removed entirely when they cancel\n    TEST_SAME_TYPE(std::hecto() * centimeter, meter);\n    TEST_SAME_TYPE(centimeter * std::hecto(), meter);\n\n    // The scale factor should be reduced to its lowest terms\n    TEST_SAME_TYPE((std::ratio<4,2>() * meter), (meter * std::ratio<6,3>()));\n\n    // A scale factor of 1 is ignored\n    TEST_SAME_TYPE((std::ratio<1,1>() * meter), meter);\n    TEST_SAME_TYPE((meter * std::ratio<1,1>()), meter);\n    // ...even if the ratio is only equivalent to 1.\n    TEST_SAME_TYPE((std::ratio<3,3>() * meter), meter);\n    TEST_SAME_TYPE((meter * std::ratio<3,3>()), meter);\n    // ...and it is not ambiguous with folding scale factors.\n    TEST_SAME_TYPE((std::ratio<3,3>() * centimeter), centimeter);\n    TEST_SAME_TYPE((centimeter * std::ratio<3,3>()), centimeter);\n}\n\n// Everything should be calculated using exact arithmetic up to the\n// final division.  Therfore, the maximum possible difference is 1 ulp.\nBOOST_AUTO_TEST_CASE(test_basic_conversion, * boost::unit_test::tolerance(std::numeric_limits<double>::epsilon()))\n{\n    // converting a unit to itself always yields a factor of 1.\n    BOOST_TEST(conversion_factor(meter, meter) == 1.0);\n    BOOST_TEST(conversion_factor(centimeter, centimeter) == 1.0);\n    BOOST_TEST(conversion_factor(inch, inch) == 1.0);\n\n    // Normalizing the dimensions should work when a base unit\n    // directly uses another base unit.\n    BOOST_TEST(conversion_factor(xmeter, meter) == 1.0);\n\n    // conversions should work in both directions\n    BOOST_TEST(conversion_factor(inch, centimeter) == 2.54);\n    BOOST_TEST(conversion_factor(centimeter, inch) == 100./254);\n\n    // Composite conversions should work.\n    BOOST_TEST(conversion_factor(meter * meter, inch * foot), 32.80839895013123358);\n\n    // The result should be correct even when it is too large or too small to\n    // be calculated using std::ratio.\n    auto nm = std::nano() * meter;\n    BOOST_TEST(conversion_factor(nm*nm*nm, meter*meter*meter) == 1e-27);\n    BOOST_TEST(conversion_factor(meter*meter*meter, nm*nm*nm) == 1e+27);\n}\n", "meta": {"hexsha": "21f3096b7c716024ec006ebd5940beb44455a012", "size": 3927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_unit.cpp", "max_stars_repo_name": "swatanabe/cppnow17-units", "max_stars_repo_head_hexsha": "e317aff5255afd11e3ebcd759ae3c824f6c95260", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T20:46:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-21T21:21:46.000Z", "max_issues_repo_path": "test/test_unit.cpp", "max_issues_repo_name": "swatanabe/cppnow17-units", "max_issues_repo_head_hexsha": "e317aff5255afd11e3ebcd759ae3c824f6c95260", "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_unit.cpp", "max_forks_repo_name": "swatanabe/cppnow17-units", "max_forks_repo_head_hexsha": "e317aff5255afd11e3ebcd759ae3c824f6c95260", "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.2258064516, "max_line_length": 133, "alphanum_fraction": 0.7094474153, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5089002038525217}}
{"text": "//\n// Copyright (c) 2017 CNRS\n//\n// This file is part of tsid\n// tsid is free software: you can redistribute it\n// and/or modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation, either version\n// 3 of the License, or (at your option) any later version.\n// tsid is distributed in the hope that it will be\n// useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// General Lesser Public License for more details. You should have\n// received a copy of the GNU Lesser General Public License along with\n// tsid If not, see\n// <http://www.gnu.org/licenses/>.\n//\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\n#include <tsid/math/utils.hpp>\n#include <tsid/robots/robot-wrapper.hpp>\n\n#include <tsid/tasks/task-se3-equality.hpp>\n#include <tsid/tasks/task-com-equality.hpp>\n#include <tsid/tasks/task-joint-posture.hpp>\n#include <tsid/tasks/task-joint-bounds.hpp>\n#include <tsid/tasks/task-joint-posVelAcc-bounds.hpp>\n\n#include <tsid/trajectories/trajectory-se3.hpp>\n#include <tsid/trajectories/trajectory-euclidian.hpp>\n\n#include <pinocchio/parsers/srdf.hpp>\n#include <pinocchio/algorithm/joint-configuration.hpp>\n#include <pinocchio/algorithm/center-of-mass.hpp>\n#include <Eigen/SVD>\n\nusing namespace tsid;\nusing namespace trajectories;\nusing namespace math;\nusing namespace tasks;\nusing namespace std;\nusing namespace Eigen;\nusing namespace tsid::robots;\n\n#define REQUIRE_FINITE(A) BOOST_REQUIRE_MESSAGE(isFinite(A), #A<<\": \"<<A)\n\nconst string romeo_model_path = TSID_SOURCE_DIR\"/models/romeo\";\n\n#ifndef NDEBUG\nconst int max_it = 100;\n#else\nconst int max_it = 10000;\n#endif\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE ( test_task_se3_equality )\n{\n  cout<<\"\\n\\n*********** TEST TASK SE3 EQUALITY ***********\\n\";\n  vector<string> package_dirs;\n  package_dirs.push_back(romeo_model_path);\n  string urdfFileName = package_dirs[0] + \"/urdf/romeo.urdf\";\n  RobotWrapper robot(urdfFileName,\n                     package_dirs,\n                     pinocchio::JointModelFreeFlyer(),\n                     false);\n\n  TaskSE3Equality task(\"task-se3\", robot, \"RWristPitch\");\n\n  VectorXd Kp = VectorXd::Ones(6);\n  VectorXd Kd = 2*VectorXd::Ones(6);\n  task.Kp(Kp);\n  task.Kd(Kd);\n  BOOST_CHECK(task.Kp().isApprox(Kp));\n  BOOST_CHECK(task.Kd().isApprox(Kd));\n\n  pinocchio::SE3 M_ref = pinocchio::SE3::Random();\n  TrajectoryBase *traj = new TrajectorySE3Constant(\"traj_SE3\", M_ref);\n  TrajectorySample sample;\n\n  double t = 0.0;\n  const double dt = 0.001;\n  MatrixXd Jpinv(robot.nv(), 6);\n  double error, error_past=1e100;\n  VectorXd q = neutral(robot.model());\n  VectorXd v = VectorXd::Zero(robot.nv());\n  pinocchio::Data data(robot.model());\n  for(int i=0; i<max_it; i++)\n  {\n    robot.computeAllTerms(data, q, v);\n    sample = traj->computeNext();\n    task.setReference(sample);\n    const ConstraintBase & constraint = task.compute(t, q, v, data);\n    BOOST_CHECK(constraint.rows()==6);\n    BOOST_CHECK(static_cast<tsid::math::Index>(constraint.cols())==static_cast<tsid::math::Index>(robot.nv()));\n    REQUIRE_FINITE(constraint.matrix());\n    BOOST_REQUIRE(isFinite(constraint.vector()));\n\n    pseudoInverse(constraint.matrix(), Jpinv, 1e-4);\n    Vector dv = Jpinv * constraint.vector();\n    BOOST_REQUIRE(isFinite(Jpinv));\n    BOOST_CHECK(MatrixXd::Identity(6,6).isApprox(constraint.matrix()*Jpinv));\n    if(!isFinite(dv))\n    {\n      cout<< \"Jpinv\" << Jpinv.transpose() <<endl;\n      cout<< \"b\" << constraint.vector().transpose() <<endl;\n    }\n    REQUIRE_FINITE(dv.transpose());\n\n    v += dt*dv;\n    q = pinocchio::integrate(robot.model(), q, dt*v);\n    BOOST_REQUIRE(isFinite(v));\n    BOOST_REQUIRE(isFinite(q));\n    t += dt;\n\n    error = task.position_error().norm();\n    BOOST_REQUIRE(isFinite(task.position_error()));\n    BOOST_CHECK(error <= error_past);\n    error_past = error;\n\n    if(i%100==0)\n      cout << \"Time \"<<t<<\"\\t Pos error \"<<error<<\n              \"\\t Vel error \"<<task.velocity_error().norm()<<endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE ( test_task_com_equality )\n{\n  cout<<\"\\n\\n*********** TEST TASK COM EQUALITY ***********\\n\";\n  vector<string> package_dirs;\n  package_dirs.push_back(romeo_model_path);\n  string urdfFileName = package_dirs[0] + \"/urdf/romeo.urdf\";\n  RobotWrapper robot(urdfFileName,\n                     package_dirs,\n                     pinocchio::JointModelFreeFlyer(),\n                     false);\n  \n  pinocchio::Data data(robot.model());\n  const string srdfFileName = package_dirs[0] + \"/srdf/romeo_collision.srdf\";\n\n  pinocchio::srdf::loadReferenceConfigurations(robot.model(),srdfFileName,false);\n  \n  //  const unsigned int nv = robot.nv();\n  VectorXd q = neutral(robot.model());\n  std::cout << \"q: \" << q.transpose() << std::endl;\n  q(2) += 0.84;\n  \n  pinocchio::centerOfMass(robot.model(),data,q);\n\n  TaskComEquality task(\"task-com\", robot);\n\n  VectorXd Kp = VectorXd::Ones(3);\n  VectorXd Kd = 2.0*VectorXd::Ones(3);\n  task.Kp(Kp);\n  task.Kd(Kd);\n  BOOST_CHECK(task.Kp().isApprox(Kp));\n  BOOST_CHECK(task.Kd().isApprox(Kd));\n\n  Vector3 com_ref = data.com[0] + pinocchio::SE3::Vector3(0.02,0.02,0.02);\n  TrajectoryBase *traj = new TrajectoryEuclidianConstant(\"traj_com\", com_ref);\n  TrajectorySample sample;\n\n  double t = 0.0;\n  const double dt = 0.001;\n  MatrixXd Jpinv(robot.nv(), 3);\n  double error, error_past=1e100;\n  VectorXd v = VectorXd::Zero(robot.nv());\n  for(int i=0; i<max_it; i++)\n  {\n    robot.computeAllTerms(data, q, v);\n    sample = traj->computeNext();\n    task.setReference(sample);\n    const ConstraintBase & constraint = task.compute(t, q, v, data);\n    BOOST_CHECK(constraint.rows()==3);\n    BOOST_CHECK(static_cast<tsid::math::Index>(constraint.cols())==static_cast<tsid::math::Index>(robot.nv()));\n    BOOST_REQUIRE(isFinite(constraint.matrix()));\n    BOOST_REQUIRE(isFinite(constraint.vector()));\n\n    pseudoInverse(constraint.matrix(), Jpinv, 1e-5);\n    Vector dv = Jpinv * constraint.vector();\n    BOOST_REQUIRE(isFinite(Jpinv));\n    BOOST_CHECK(MatrixXd::Identity(constraint.rows(),constraint.rows()).isApprox(constraint.matrix()*Jpinv));\n    BOOST_REQUIRE(isFinite(dv));\n\n    v += dt*dv;\n    q = pinocchio::integrate(robot.model(), q, dt*v);\n    BOOST_REQUIRE(isFinite(v));\n    BOOST_REQUIRE(isFinite(q));\n    t += dt;\n\n    error = task.position_error().norm();\n    BOOST_REQUIRE(isFinite(task.position_error()));\n    BOOST_CHECK((error - error_past) <= 1e-4);\n    error_past = error;\n    \n    if(error < 1e-8) break;\n\n    if(i%100==0)\n      cout << \"Time \"<<t<<\"\\t CoM pos error \"<<error<<\n              \"\\t CoM vel error \"<<task.velocity_error().norm()<<endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE ( test_task_joint_posture )\n{\n  cout<<\"\\n\\n*********** TEST TASK JOINT POSTURE ***********\\n\";\n  vector<string> package_dirs;\n  package_dirs.push_back(romeo_model_path);\n  string urdfFileName = package_dirs[0] + \"/urdf/romeo.urdf\";\n  RobotWrapper robot(urdfFileName,\n                     package_dirs,\n                     pinocchio::JointModelFreeFlyer(),\n                     false);\n  const unsigned int na = robot.nv()-6;\n\n  cout<<\"Gonna create task\\n\";\n  TaskJointPosture task(\"task-posture\", robot);\n\n  cout<<\"Gonna set gains\\n\"<<na<<endl;\n  VectorXd Kp = VectorXd::Ones(na);\n  VectorXd Kd = 2.0*Kp;\n  task.Kp(Kp);\n  task.Kd(Kd);\n  BOOST_CHECK(task.Kp().isApprox(Kp));\n  BOOST_CHECK(task.Kd().isApprox(Kd));\n\n  cout<<\"Gonna create reference trajectory\\n\";\n  Vector q_ref = Vector::Random(na);\n  TrajectoryBase *traj = new TrajectoryEuclidianConstant(\"traj_joint\", q_ref);\n  TrajectorySample sample;\n\n  cout<<\"Gonna set up for simulation\\n\";\n  double t = 0.0;\n  const double dt = 0.001;\n  MatrixXd Jpinv(robot.nv(), na);\n  double error, error_past=1e100;\n  VectorXd q = neutral(robot.model());\n  VectorXd v = VectorXd::Zero(robot.nv());\n  pinocchio::Data data(robot.model());\n  for(int i=0; i<max_it; i++)\n  {\n    robot.computeAllTerms(data, q, v);\n    sample = traj->computeNext();\n    task.setReference(sample);\n    const ConstraintBase & constraint = task.compute(t, q, v, data);\n    BOOST_CHECK(constraint.rows()==na);\n    BOOST_CHECK(static_cast<tsid::math::Index>(constraint.cols())==static_cast<tsid::math::Index>(robot.nv()));\n    BOOST_REQUIRE(isFinite(constraint.matrix()));\n    BOOST_REQUIRE(isFinite(constraint.vector()));\n\n    pseudoInverse(constraint.matrix(), Jpinv, 1e-5);\n    Vector dv = Jpinv * constraint.vector();\n    BOOST_REQUIRE(isFinite(Jpinv));\n    BOOST_CHECK(MatrixXd::Identity(na,na).isApprox(constraint.matrix()*Jpinv));\n    BOOST_REQUIRE(isFinite(dv));\n\n    v += dt*dv;\n    q = pinocchio::integrate(robot.model(), q, dt*v);\n    BOOST_REQUIRE(isFinite(v));\n    BOOST_REQUIRE(isFinite(q));\n    t += dt;\n\n    error = task.position_error().norm();\n    BOOST_REQUIRE(isFinite(task.position_error()));\n    BOOST_CHECK(error <= error_past);\n    error_past = error;\n\n    if(i%100==0)\n      cout << \"Time \"<<t<<\"\\t pos error \"<<error<<\n              \"\\t vel error \"<<task.velocity_error().norm()<<endl;\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE ( test_task_joint_bounds )\n{\n  cout<<\"\\n\\n*********** TEST TASK JOINT BOUNDS ***********\\n\";\n  vector<string> package_dirs;\n  package_dirs.push_back(romeo_model_path);\n  string urdfFileName = package_dirs[0] + \"/urdf/romeo.urdf\";\n  RobotWrapper robot(urdfFileName,\n                     package_dirs,\n                     pinocchio::JointModelFreeFlyer(),\n                     false);\n  const unsigned int na = robot.nv()-6;\n  const double dt = 0.001;\n\n  cout<<\"Gonna create task\\n\";\n  TaskJointBounds task(\"task-joint-bounds\", robot, dt);\n\n  cout<<\"Gonna set limits\\n\"<<na<<endl;\n  VectorXd dq_max = VectorXd::Ones(na);\n  VectorXd dq_min = -dq_max;\n  task.setVelocityBounds(dq_min, dq_max);\n\n  BOOST_CHECK(task.getVelocityLowerBounds().isApprox(dq_min));\n  BOOST_CHECK(task.getVelocityUpperBounds().isApprox(dq_max));\n\n  cout<<\"Gonna set up for simulation\\n\";\n  double t = 0.0;\n\n  VectorXd q = neutral(robot.model());\n  VectorXd v = VectorXd::Zero(robot.nv());\n  pinocchio::Data data(robot.model());\n  for(int i=0; i<max_it; i++)\n  {\n    robot.computeAllTerms(data, q, v);\n    const ConstraintBase & constraint = task.compute(t, q, v, data);\n    BOOST_CHECK(constraint.rows()==(Eigen::Index)robot.nv());\n    BOOST_CHECK(static_cast<tsid::math::Index>(constraint.cols())==static_cast<tsid::math::Index>(robot.nv()));\n    BOOST_REQUIRE(isFinite(constraint.lowerBound()));\n    BOOST_REQUIRE(isFinite(constraint.upperBound()));\n\n    BOOST_REQUIRE(isFinite(v));\n    BOOST_REQUIRE(isFinite(q));\n    t += dt;\n  }\n}\n\n\n\nBOOST_AUTO_TEST_CASE ( test_task_joint_posVelAcc_bounds )\n{\n  cout<<\"\\n\\n*********** TEST TASK JOINT POS VEL ACC BOUNDS ***********\\n\";\n  vector<string> package_dirs;\n  package_dirs.push_back(romeo_model_path);\n  string urdfFileName = package_dirs[0] + \"/urdf/romeo.urdf\";\n  RobotWrapper robot(urdfFileName,\n                     package_dirs,\n                     pinocchio::JointModelFreeFlyer(),\n                     false);\n  const unsigned int na = robot.nv()-6;\n  const double dt = 0.001;\n\n  cout<<\"Gonna create task\\n\";\n  TaskJointPosVelAccBounds task(\"task-joint-posVelAcc-bounds\", robot, dt);\n\n  cout<<\"Gonna set limits\\n\"<<na<<endl;\n  VectorXd dq_max = VectorXd::Ones(na);\n  VectorXd dq_min = -dq_max;\n\n  task.setPositionBounds(dq_min,dq_max);\n  task.setVelocityBounds(dq_max);\n  task.setAccelerationBounds(dq_max);\n\n  BOOST_CHECK(task.getPositionLowerBounds().isApprox(dq_min));\n  BOOST_CHECK(task.getPositionUpperBounds().isApprox(dq_max));\n  BOOST_CHECK(task.getVelocityBounds().isApprox(dq_max));\n  BOOST_CHECK(task.getAccelerationBounds().isApprox(dq_max));\n\n  cout<<\"Gonna set up for simulation\\n\";\n  double t = 0.0;\n\n  VectorXd q = neutral(robot.model());\n  VectorXd v = VectorXd::Zero(robot.nv());\n  pinocchio::Data data(robot.model());\n  for(int i=0; i<max_it; i++)\n  {\n    robot.computeAllTerms(data, q, v);\n    const ConstraintBase & constraint = task.compute(t, q, v, data);\n    BOOST_CHECK(constraint.rows()==(Eigen::Index)robot.na());\n    BOOST_CHECK(static_cast<tsid::math::Index>(constraint.cols())==static_cast<tsid::math::Index>(robot.nv()));\n    BOOST_REQUIRE(isFinite(constraint.lowerBound()));\n    BOOST_REQUIRE(isFinite(constraint.upperBound()));\n\n    BOOST_REQUIRE(isFinite(v));\n    BOOST_REQUIRE(isFinite(q));\n    t += dt;\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END ()\n", "meta": {"hexsha": "ace65878b8a7267ee41d7fb6db963fc8d2fde63c", "size": 12418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/tasks.cpp", "max_stars_repo_name": "NimaPng/tsid", "max_stars_repo_head_hexsha": "23bbc6bace4f4623c2189535e71ba63bedbc4368", "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": "tests/tasks.cpp", "max_issues_repo_name": "NimaPng/tsid", "max_issues_repo_head_hexsha": "23bbc6bace4f4623c2189535e71ba63bedbc4368", "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/tasks.cpp", "max_forks_repo_name": "NimaPng/tsid", "max_forks_repo_head_hexsha": "23bbc6bace4f4623c2189535e71ba63bedbc4368", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-21T17:59:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-21T17:59:55.000Z", "avg_line_length": 33.0265957447, "max_line_length": 111, "alphanum_fraction": 0.6720889032, "num_tokens": 3338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489892, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5087863212609756}}
{"text": "/*-----------------------------------------------------------------------------+\nCopyright (c) 2007-2009: Joachim Faulhaber\n+------------------------------------------------------------------------------+\nCopyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------+\nsplititvmap_shell.cpp provides  a simple test shell for splitting interval maps.\nThe shell also gives you a good idea how interval container are working.\n+-----------------------------------------------------------------------------*/\n#include <iostream>\n\n#include <boost/icl/split_interval_set.hpp>\n#include <boost/icl/split_interval_map.hpp>\n#include <boost/icl/interval_map.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::icl;\n\nvoid instructions()\n{\n    cout << \"+++++ Test shell for split interval map +++++\\n\";\n    cout << \"Type: q e or 0  to quit\\n\";\n    cout << \"Type: +         for insertions\\n\";\n    cout << \"Type: -         for subtraction of ([a,b],value)\\n\";\n    cout << \"Type: _         for subtraction of [a,b]\\n\";\n    cout << \"Type: j         to join contiguous intervals\\n\";\n    cout << \"Type: s         to compute total size\\n\";\n}\n\nvoid wrongInput()\n{\n    cout << \"Wrong Input ------------------\\n\";\n    instructions();\n}\n\n\ntemplate <class MapTV>\nvoid mapTestShell()\n{\n    MapTV m1;\n\n    try {\n        char cmd = 'b';\n        typename MapTV::domain_type\n            lwb = typename MapTV::domain_type(),\n            upb = typename MapTV::domain_type();\n\n        typename MapTV::codomain_type\n            val = typename MapTV::codomain_type();\n\n        instructions();\n\n        for(;;)\n        {\n            cout << \"> \";\n            cin >> cmd ;\n\n            switch(cmd)\n            {\n            case 'q':\n            case 'e':\n            case '0': cout << \"good bye\\n\"; return;\n            case '+':\n                {\n                    cout << \"input: lwb upb val >> \";\n                    cin >> lwb >> upb >> val;\n                    typename MapTV::interval_type\n                        itv = typename MapTV::interval_type(lwb,upb);\n                    m1 += make_pair(itv,val);\n\n                    cout << \"+\" << itv << \" \" << val << \" =\" << endl;\n                    cout << \"{\" << m1 << \"}\" << endl;\n\n                }\n                break;\n            case '-':\n                {\n                    cout << \"input: lwb upb val >> \";\n                    cin >> lwb >> upb >> val;\n                    typename MapTV::interval_type\n                        itv = typename MapTV::interval_type(lwb,upb);\n                    m1 -= make_pair(itv,val);\n\n                    cout << \"-\" << itv << \" \" << val << \" =\" << endl;\n                    cout << \"{\" << m1 << \"}\" << endl;\n\n                }\n                break;\n            case 'j':\n                {\n                    icl::join(m1);\n                    cout << \"{\" << m1 << \"}\" << endl;\n                }\n                break;\n            case 's':\n                {\n                    cout << \"size = \" << m1.size() << endl;\n                }\n                break;\n\n            default: wrongInput();\n            }\n        } // end while\n    }\n    catch (exception& e)\n    {\n        cout << \"splititvmap_shell: exception caught: \" << endl\n             << e.what() << endl;\n    }\n    catch (...)\n    {\n        cout << \"splititvmap_shell: unknown exception caught\" << endl;\n    }\n}\n\n\nint main()\n{\n    cout << \">>Interval Container Library: Test splititvmap_shell.cpp <<\\n\";\n    cout << \"-----------------------------------------------------------\\n\";\n    mapTestShell< interval_map<int, int> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "e00ab0a3fb5c1366fe57e5af84bf22e7ea857342", "size": 4008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/icl/example/splititvmap_shell_/splititvmap_shell.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/icl/example/splititvmap_shell_/splititvmap_shell.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/icl/example/splititvmap_shell_/splititvmap_shell.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": 30.5954198473, "max_line_length": 80, "alphanum_fraction": 0.3977045908, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.5087862998067123}}
{"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#include <boost/timer.hpp>\n\n\nusing namespace std;\nusing namespace mtl;\n\n\n\n\ntypedef compressed2D<double> sp_mat;\n\n\nvoid assemble(sp_mat& A, double val)\n{\n  mat::inserter<sp_mat, update_plus<double> > ins(A, 3);\n\n  double array[][3]= {{-2*val, val, val},\n\t\t      {val, -2*val, val},\n\t\t      {val, val, -2*val}};\n\n  dense2D<double> block(array);\n  dense_vector<int> cols(3);\n  dense_vector<int> rows(3);\n\n  int N= num_rows(A); // A is N-by-N\n  for(int k=0; k<N-2; k+=3)    // nice case\n  //for(int k=N-3; k>=0; k-=3) // out-of-order case\n    {\n      rows[0] = k; rows[1] = k+1; rows[2] = k+2;\n      cols[0] = 0; cols[1] = k;   cols[2] = N-1;\n\n      ins << element_matrix(block, rows, cols);\n    }\n}\n\n\n\nint main(int argc, char* argv[])\n{\n    sp_mat B(9, 9);\n    assemble(B, 1.0);\n    cout << \"Small assembled matrix\\n\" << B << \"\\n\";\n\n    const int size= 900000; \n    sp_mat A(size, size);\n\n    boost::timer atime;\n    assemble(A, 1.0);\t\n    cout << \"Assemble time = \" << atime.elapsed() << \", \" \n\t << 3*size / atime.elapsed() << \" elements/s\\n\";\n\n    A*= 0.0;\n    boost::timer rtime;\n    assemble(A, 1.0);\t\n    cout << \"Reassemble time = \" << rtime.elapsed() << \", \" \n\t << 3*size / rtime.elapsed() << \" elements/s\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "5b0bcff79cff3682dcd265e6ef7723a644bb7e6c", "size": 1732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/timing/assembly_timing.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/timing/assembly_timing.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/timing/assembly_timing.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.4054054054, "max_line_length": 94, "alphanum_fraction": 0.5918013857, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5087862957287499}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2019 - 2021 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: Thomas C. Clevenger, Clemson University \n *         Timo Heister, Clemson University \n *         Guido Kanschat, Heidelberg University \n *         Martin Kronbichler, Technical University of Munich \n */ \n\n\n// @sect3{Include files}  \n\n// \u5305\u542b\u6587\u4ef6\u662f  step-40  ,  step-16  , \u548c  step-37  \u7684\u7ec4\u5408\u3002\n\n#include <deal.II/base/conditional_ostream.h> \n#include <deal.II/base/data_out_base.h> \n#include <deal.II/base/index_set.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/base/parameter_handler.h> \n#include <deal.II/distributed/grid_refinement.h> \n#include <deal.II/distributed/tria.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/grid/grid_generator.h> \n#include <deal.II/grid/grid_refinement.h> \n#include <deal.II/grid/tria.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/solver_cg.h> \n\n// \u6211\u4eec\u4f7f\u7528\u4e0e step-40 \u76f8\u540c\u7684\u7b56\u7565\uff0c\u5728PETSc\u548cTrilinos\u4e4b\u95f4\u8fdb\u884c\u5207\u6362\u3002\n\n#include <deal.II/lac/generic_linear_algebra.h> \n\n// \u5982\u679c\u4f60\u5df2\u7ecf\u5b89\u88c5\u4e86PETSc\u548cTrilinos\uff0c\u5e76\u4e14\u4f60\u559c\u6b22\u5728\u672c\u4f8b\u4e2d\u4f7f\u7528PETSc\uff0c\u8bf7\u5c06\u4e0b\u9762\u7684\u9884\u5904\u7406\u7a0b\u5e8f\u5b9a\u4e49\u6ce8\u91ca\u8fdb\u53bb\u6216\u9000\u51fa\u3002\n\n#define FORCE_USE_OF_TRILINOS \n\nnamespace LA \n{ \n#if defined(DEAL_II_WITH_PETSC) && !defined(DEAL_II_PETSC_WITH_COMPLEX) && \\ \n  !(defined(DEAL_II_WITH_TRILINOS) && defined(FORCE_USE_OF_TRILINOS)) \n  using namespace dealii::LinearAlgebraPETSc; \n#  define USE_PETSC_LA \n#elif defined(DEAL_II_WITH_TRILINOS) \n  using namespace dealii::LinearAlgebraTrilinos; \n#else \n#  error DEAL_II_WITH_PETSC or DEAL_II_WITH_TRILINOS required \n#endif \n} // namespace LA \n\n#include <deal.II/matrix_free/matrix_free.h> \n#include <deal.II/matrix_free/operators.h> \n#include <deal.II/matrix_free/fe_evaluation.h> \n#include <deal.II/multigrid/mg_coarse.h> \n#include <deal.II/multigrid/mg_constrained_dofs.h> \n#include <deal.II/multigrid/mg_matrix.h> \n#include <deal.II/multigrid/mg_smoother.h> \n#include <deal.II/multigrid/mg_tools.h> \n#include <deal.II/multigrid/mg_transfer.h> \n#include <deal.II/multigrid/multigrid.h> \n#include <deal.II/multigrid/mg_transfer_matrix_free.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/vector_tools.h> \n\n// \u4ee5\u4e0b\u6587\u4ef6\u7528\u4e8e\u7ec4\u88c5\u8bef\u5dee\u4f30\u8ba1\u5668\uff0c\u5982  step-12  \u3002\n\n#include <deal.II/fe/fe_interface_values.h> \n#include <deal.II/meshworker/mesh_loop.h> \n\nusing namespace dealii; \n// @sect3{Coefficients and helper classes}  \n\n// MatrixFree\u8fd0\u7b97\u7b26\u5fc5\u987b\u4f7f\u7528 dealii::LinearAlgebra::distributed::Vector \u77e2\u91cf\u7c7b\u578b\u3002\u8fd9\u91cc\u6211\u4eec\u5b9a\u4e49\u4e86\u590d\u5236\u5230Trilinos\u5411\u91cf\u7684\u64cd\u4f5c\uff0c\u4ee5\u4fbf\u4e0e\u57fa\u4e8e\u77e9\u9635\u7684\u4ee3\u7801\u517c\u5bb9\u3002\u8bf7\u6ce8\u610f\uff0c\u76ee\u524dPETSc\u77e2\u91cf\u7c7b\u578b\u4e0d\u5b58\u5728\u8fd9\u79cd\u529f\u80fd\uff0c\u6240\u4ee5\u5fc5\u987b\u5b89\u88c5Trilinos\u6765\u4f7f\u7528\u672c\u6559\u7a0b\u4e2d\u7684MatrixFree\u6c42\u89e3\u5668\u3002\n\nnamespace ChangeVectorTypes \n{ \n  template <typename number> \n  void copy(LA::MPI::Vector &                                         out, \n            const dealii::LinearAlgebra::distributed::Vector<number> &in) \n  { \n    dealii::LinearAlgebra::ReadWriteVector<double> rwv( \n      out.locally_owned_elements()); \n    rwv.import(in, VectorOperation::insert); \n#ifdef USE_PETSC_LA \n    AssertThrow(false, \n                ExcMessage(\"CopyVectorTypes::copy() not implemented for \" \n                           \"PETSc vector types.\")); \n#else \n    out.import(rwv, VectorOperation::insert); \n#endif \n  } \n\n  template <typename number> \n  void copy(dealii::LinearAlgebra::distributed::Vector<number> &out, \n            const LA::MPI::Vector &                             in) \n  { \n    dealii::LinearAlgebra::ReadWriteVector<double> rwv; \n#ifdef USE_PETSC_LA \n    (void)in; \n    AssertThrow(false, \n                ExcMessage(\"CopyVectorTypes::copy() not implemented for \" \n                           \"PETSc vector types.\")); \n#else \n    rwv.reinit(in); \n#endif \n    out.import(rwv, VectorOperation::insert); \n  } \n} // namespace ChangeVectorTypes \n\n// \u8ba9\u6211\u4eec\u7ee7\u7eed\u63cf\u8ff0\u6211\u4eec\u8981\u89e3\u51b3\u7684\u95ee\u9898\u3002\u6211\u4eec\u628a\u53f3\u8fb9\u7684\u51fd\u6570\u8bbe\u7f6e\u4e3a1.0\u3002 @p value \u51fd\u6570\u8fd4\u56de\u4e00\u4e2aVectorizedArray\uff0c\u88ab\u65e0\u77e9\u9635\u4ee3\u7801\u8def\u5f84\u6240\u4f7f\u7528\u3002\n\ntemplate <int dim> \nclass RightHandSide : public Function<dim> \n{ \npublic: \n  virtual double value(const Point<dim> & /*p*/, \n                       const unsigned int /*component*/ = 0) const override \n  { \n    return 1.0; \n  } \n\n  template <typename number> \n  VectorizedArray<number> \n  value(const Point<dim, VectorizedArray<number>> & /*p*/, \n        const unsigned int /*component*/ = 0) const \n  { \n    return VectorizedArray<number>(1.0); \n  } \n}; \n\n// \u63a5\u4e0b\u6765\u7684\u8fd9\u4e2a\u7c7b\u8868\u793a\u6269\u6563\u7cfb\u6570\u3002\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u53ef\u53d8\u7684\u7cfb\u6570\uff0c\u5728\u4efb\u4f55\u4e00\u4e2a\u81f3\u5c11\u6709\u4e00\u4e2a\u5750\u6807\u5c0f\u4e8e-0.5\u7684\u70b9\u4e0a\u662f100.0\uff0c\u5728\u6240\u6709\u5176\u4ed6\u70b9\u4e0a\u662f1.0\u3002\u5982\u4e0a\u6240\u8ff0\uff0c\u4e00\u4e2a\u5355\u72ec\u7684value()\u8fd4\u56de\u4e00\u4e2aVectorizedArray\uff0c\u7528\u4e8e\u65e0\u77e9\u9635\u4ee3\u7801\u3002\u4e00\u4e2a @p average()\u51fd\u6570\u8ba1\u7b97\u4e86\u4e00\u7ec4\u70b9\u7684\u7b97\u672f\u5e73\u5747\u3002\n\ntemplate <int dim> \nclass Coefficient : public Function<dim> \n{ \npublic: \n  virtual double value(const Point<dim> &p, \n                       const unsigned int /*component*/ = 0) const override; \n\n  template <typename number> \n  VectorizedArray<number> value(const Point<dim, VectorizedArray<number>> &p, \n                                const unsigned int /*component*/ = 0) const; \n\n  template <typename number> \n  number average_value(const std::vector<Point<dim, number>> &points) const; \n\n// \u5f53\u5728MatrixFree\u6846\u67b6\u4e2d\u4f7f\u7528\u4e00\u4e2a\u7cfb\u6570\u65f6\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u4e00\u4e2a\u51fd\u6570\uff0c\u4e3aMatrixFree\u8fd0\u7b97\u7b26\u53c2\u6570\u63d0\u4f9b\u7684\u4e00\u7ec4\u5355\u5143\u683c\u521b\u5efa\u4e00\u4e2a\u7cfb\u6570\u8868\u3002\n\n  template <typename number> \n  std::shared_ptr<Table<2, VectorizedArray<number>>> make_coefficient_table( \n    const MatrixFree<dim, number, VectorizedArray<number>> &mf_storage) const; \n}; \n\ntemplate <int dim> \ndouble Coefficient<dim>::value(const Point<dim> &p, const unsigned int) const \n{ \n  for (int d = 0; d < dim; ++d) \n    { \n      if (p[d] < -0.5) \n        return 100.0; \n    } \n  return 1.0; \n} \n\ntemplate <int dim> \ntemplate <typename number> \nVectorizedArray<number> \nCoefficient<dim>::value(const Point<dim, VectorizedArray<number>> &p, \n                        const unsigned int) const \n{ \n  VectorizedArray<number> return_value = VectorizedArray<number>(1.0); \n  for (unsigned int i = 0; i < VectorizedArray<number>::size(); ++i) \n    { \n      for (int d = 0; d < dim; ++d) \n        if (p[d][i] < -0.5) \n          { \n            return_value[i] = 100.0; \n            break; \n          } \n    } \n\n  return return_value; \n} \n\ntemplate <int dim> \ntemplate <typename number> \nnumber Coefficient<dim>::average_value( \n  const std::vector<Point<dim, number>> &points) const \n{ \n  number average(0); \n  for (unsigned int i = 0; i < points.size(); ++i) \n    average += value(points[i]); \n  average /= points.size(); \n\n  return average; \n} \n\ntemplate <int dim> \ntemplate <typename number> \nstd::shared_ptr<Table<2, VectorizedArray<number>>> \nCoefficient<dim>::make_coefficient_table( \n  const MatrixFree<dim, number, VectorizedArray<number>> &mf_storage) const \n{ \n  auto coefficient_table = \n    std::make_shared<Table<2, VectorizedArray<number>>>(); \n\n  FEEvaluation<dim, -1, 0, 1, number> fe_eval(mf_storage); \n\n  const unsigned int n_cells    = mf_storage.n_cell_batches(); \n  const unsigned int n_q_points = fe_eval.n_q_points; \n\n  coefficient_table->reinit(n_cells, 1); \n\n  for (unsigned int cell = 0; cell < n_cells; ++cell) \n    { \n      fe_eval.reinit(cell); \n\n      VectorizedArray<number> average_value = 0.; \n      for (unsigned int q = 0; q < n_q_points; ++q) \n        average_value += value(fe_eval.quadrature_point(q)); \n      average_value /= n_q_points; \n\n      (*coefficient_table)(cell, 0) = average_value; \n    } \n\n  return coefficient_table; \n} \n\n//  @sect3{Run time parameters}  \n\n// \u6211\u4eec\u5c06\u4f7f\u7528ParameterHandler\u6765\u5728\u8fd0\u884c\u65f6\u4f20\u5165\u53c2\u6570\u3002 \u8be5\u7ed3\u6784 @p Settings \u89e3\u6790\u5e76\u5b58\u50a8\u8fd9\u4e9b\u53c2\u6570\uff0c\u4ee5\u4fbf\u5728\u6574\u4e2a\u7a0b\u5e8f\u4e2d\u8fdb\u884c\u67e5\u8be2\u3002\n\nstruct Settings \n{ \n  bool try_parse(const std::string &prm_filename); \n\n  enum SolverType \n  { \n    gmg_mb, \n    gmg_mf, \n    amg \n  }; \n\n  SolverType solver; \n\n  int          dimension; \n  double       smoother_dampen; \n  unsigned int smoother_steps; \n  unsigned int n_steps; \n  bool         output; \n}; \n\nbool Settings::try_parse(const std::string &prm_filename) \n{ \n  ParameterHandler prm; \n  prm.declare_entry(\"dim\", \"2\", Patterns::Integer(), \"The problem dimension.\"); \n  prm.declare_entry(\"n_steps\", \n                    \"10\", \n                    Patterns::Integer(0), \n                    \"Number of adaptive refinement steps.\"); \n  prm.declare_entry(\"smoother dampen\", \n                    \"1.0\", \n                    Patterns::Double(0.0), \n                    \"Dampen factor for the smoother.\"); \n  prm.declare_entry(\"smoother steps\", \n                    \"1\", \n                    Patterns::Integer(1), \n                    \"Number of smoother steps.\"); \n  prm.declare_entry(\"solver\", \n                    \"MF\", \n                    Patterns::Selection(\"MF|MB|AMG\"), \n                    \"Switch between matrix-free GMG, \" \n                    \"matrix-based GMG, and AMG.\"); \n  prm.declare_entry(\"output\", \n                    \"false\", \n                    Patterns::Bool(), \n                    \"Output graphical results.\"); \n\n  if (prm_filename.size() == 0) \n    { \n      std::cout << \"****  Error: No input file provided!\\n\" \n                << \"****  Error: Call this program as './step-50 input.prm\\n\" \n                << \"\\n\" \n                << \"****  You may want to use one of the input files in this\\n\" \n                << \"****  directory, or use the following default values\\n\" \n                << \"****  to create an input file:\\n\"; \n      if (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0) \n        prm.print_parameters(std::cout, ParameterHandler::Text); \n      return false; \n    } \n\n  try \n    { \n      prm.parse_input(prm_filename); \n    } \n  catch (std::exception &e) \n    { \n      if (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0) \n        std::cerr << e.what() << std::endl; \n      return false; \n    } \n\n  if (prm.get(\"solver\") == \"MF\") \n    this->solver = gmg_mf; \n  else if (prm.get(\"solver\") == \"MB\") \n    this->solver = gmg_mb; \n  else if (prm.get(\"solver\") == \"AMG\") \n    this->solver = amg; \n  else \n    AssertThrow(false, ExcNotImplemented()); \n\n  this->dimension       = prm.get_integer(\"dim\"); \n  this->n_steps         = prm.get_integer(\"n_steps\"); \n  this->smoother_dampen = prm.get_double(\"smoother dampen\"); \n  this->smoother_steps  = prm.get_integer(\"smoother steps\"); \n  this->output          = prm.get_bool(\"output\"); \n\n  return true; \n} \n\n//  @sect3{LaplaceProblem class}  \n\n// \u8fd9\u662f\u8be5\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u3002\u5b83\u770b\u8d77\u6765\u4e0e  step-16  ,  step-37  , \u548c  step-40  \u975e\u5e38\u76f8\u4f3c\u3002\u5bf9\u4e8eMatrixFree\u7684\u8bbe\u7f6e\uff0c\u6211\u4eec\u4f7f\u7528 MatrixFreeOperators::LaplaceOperator \u7c7b\uff0c\u5b83\u5728\u5185\u90e8\u5b9a\u4e49\u4e86`local_apply()`, `compute_diagonal()`, \u548c`set_coefficient()`\u51fd\u6570\u3002\u8bf7\u6ce8\u610f\uff0c\u591a\u9879\u5f0f\u7684\u5ea6\u6570\u662f\u8fd9\u4e2a\u7c7b\u7684\u4e00\u4e2a\u6a21\u677f\u53c2\u6570\u3002\u8fd9\u5bf9\u65e0\u77e9\u9635\u4ee3\u7801\u6765\u8bf4\u662f\u5fc5\u8981\u7684\u3002\n\ntemplate <int dim, int degree> \nclass LaplaceProblem \n{ \npublic: \n  LaplaceProblem(const Settings &settings); \n  void run(); \n\nprivate: \n\n// \u6211\u4eec\u5c06\u5728\u6574\u4e2a\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u4ee5\u4e0b\u7c7b\u578b\u3002\u9996\u5148\u662f\u57fa\u4e8e\u77e9\u9635\u7684\u7c7b\u578b\uff0c\u4e4b\u540e\u662f\u65e0\u77e9\u9635\u7684\u7c7b\u3002\u5bf9\u4e8e\u65e0\u77e9\u9635\u7684\u5b9e\u73b0\uff0c\u6211\u4eec\u4f7f\u7528 @p float \u4f5c\u4e3a\u6c34\u5e73\u8fd0\u7b97\u7b26\u3002\n\n  using MatrixType         = LA::MPI::SparseMatrix; \n  using VectorType         = LA::MPI::Vector; \n  using PreconditionAMG    = LA::MPI::PreconditionAMG; \n  using PreconditionJacobi = LA::MPI::PreconditionJacobi; \n\n  using MatrixFreeLevelMatrix = MatrixFreeOperators::LaplaceOperator< \n    dim, \n    degree, \n    degree + 1, \n    1, \n    LinearAlgebra::distributed::Vector<float>>; \n  using MatrixFreeActiveMatrix = MatrixFreeOperators::LaplaceOperator< \n    dim, \n    degree, \n    degree + 1, \n    1, \n    LinearAlgebra::distributed::Vector<double>>; \n\n  using MatrixFreeLevelVector  = LinearAlgebra::distributed::Vector<float>; \n  using MatrixFreeActiveVector = LinearAlgebra::distributed::Vector<double>; \n\n  void setup_system(); \n  void setup_multigrid(); \n  void assemble_system(); \n  void assemble_multigrid(); \n  void assemble_rhs(); \n  void solve(); \n  void estimate(); \n  void refine_grid(); \n  void output_results(const unsigned int cycle); \n\n  Settings settings; \n\n  MPI_Comm           mpi_communicator; \n  ConditionalOStream pcout; \n\n  parallel::distributed::Triangulation<dim> triangulation; \n  const MappingQ1<dim>                      mapping; \n  FE_Q<dim>                                 fe; \n\n  DoFHandler<dim> dof_handler; \n\n \n  IndexSet                  locally_relevant_dofs; \n  AffineConstraints<double> constraints; \n\n  MatrixType             system_matrix; \n  MatrixFreeActiveMatrix mf_system_matrix; \n  VectorType             solution; \n  VectorType             right_hand_side; \n  Vector<double>         estimated_error_square_per_cell; \n\n  MGLevelObject<MatrixType> mg_matrix; \n  MGLevelObject<MatrixType> mg_interface_in; \n  MGConstrainedDoFs         mg_constrained_dofs; \n\n  MGLevelObject<MatrixFreeLevelMatrix> mf_mg_matrix; \n\n  TimerOutput computing_timer; \n}; \n\n// \u5173\u4e8e\u6784\u9020\u51fd\u6570\u7684\u552f\u4e00\u6709\u8da3\u7684\u90e8\u5206\u662f\uff0c\u9664\u975e\u6211\u4eec\u4f7f\u7528AMG\uff0c\u5426\u5219\u6211\u4eec\u4f1a\u6784\u9020\u591a\u7f51\u683c\u7684\u5c42\u6b21\u7ed3\u6784\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9700\u8981\u5728\u8fd9\u4e2a\u6784\u9020\u51fd\u6570\u5b8c\u6210\u4e4b\u524d\u89e3\u6790\u8fd0\u884c\u65f6\u53c2\u6570\u3002\n\ntemplate <int dim, int degree> \nLaplaceProblem<dim, degree>::LaplaceProblem(const Settings &settings) \n  : settings(settings) \n  , mpi_communicator(MPI_COMM_WORLD) \n  , pcout(std::cout, (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)) \n  , triangulation(mpi_communicator, \n                  Triangulation<dim>::limit_level_difference_at_vertices, \n                  (settings.solver == Settings::amg) ? \n                    parallel::distributed::Triangulation<dim>::default_setting : \n                    parallel::distributed::Triangulation< \n                      dim>::construct_multigrid_hierarchy) \n  , mapping() \n  , fe(degree) \n  , dof_handler(triangulation) \n  , computing_timer(pcout, TimerOutput::never, TimerOutput::wall_times) \n{ \n  GridGenerator::hyper_L(triangulation, -1., 1., /*colorize*/ false); \n  triangulation.refine_global(1); \n} \n\n//  @sect4{LaplaceProblem::setup_system()}  \n\n// \u4e0e  step-16  \u548c  step-37  \u4e0d\u540c\uff0c\u6211\u4eec\u5c06\u8bbe\u7f6e\u5206\u6210\u4e24\u90e8\u5206\uff0csetup_system() \u548c setup_multigrid() \u3002\u4e0b\u9762\u662f\u5927\u591a\u6570\u6559\u7a0b\u4e2d\u5e38\u89c1\u7684\u4e3b\u52a8\u7f51\u683c\u7684\u5178\u578bsetup_system()\u51fd\u6570\u3002\u5bf9\u4e8e\u65e0\u77e9\u9635\uff0c\u6d3b\u52a8\u7f51\u683c\u7684\u8bbe\u7f6e\u7c7b\u4f3c\u4e8e  step-37  \uff1b\u5bf9\u4e8e\u57fa\u4e8e\u77e9\u9635\uff08GMG\u548cAMG\u6c42\u89e3\u5668\uff09\uff0c\u8bbe\u7f6e\u7c7b\u4f3c\u4e8e  step-40  \u3002\n\ntemplate <int dim, int degree> \nvoid LaplaceProblem<dim, degree>::setup_system() \n{ \n  TimerOutput::Scope timing(computing_timer, \"Setup\"); \n\n  dof_handler.distribute_dofs(fe); \n\n  DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs); \n  locally_owned_dofs = dof_handler.locally_owned_dofs(); \n\n  solution.reinit(locally_owned_dofs, mpi_communicator); \n  right_hand_side.reinit(locally_owned_dofs, mpi_communicator); \n  constraints.reinit(locally_relevant_dofs); \n  DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n\n  VectorTools::interpolate_boundary_values( \n    mapping, dof_handler, 0, Functions::ZeroFunction<dim>(), constraints); \n  constraints.close(); \n\n  switch (settings.solver) \n    { \n      case Settings::gmg_mf: \n        { \n          typename MatrixFree<dim, double>::AdditionalData additional_data; \n          additional_data.tasks_parallel_scheme = \n            MatrixFree<dim, double>::AdditionalData::none; \n          additional_data.mapping_update_flags = \n            (update_gradients | update_JxW_values | update_quadrature_points); \n          std::shared_ptr<MatrixFree<dim, double>> mf_storage = \n            std::make_shared<MatrixFree<dim, double>>(); \n          mf_storage->reinit(mapping, \n                             dof_handler, \n                             constraints, \n                             QGauss<1>(degree + 1), \n                             additional_data); \n\n          mf_system_matrix.initialize(mf_storage); \n\n          const Coefficient<dim> coefficient; \n          mf_system_matrix.set_coefficient( \n            coefficient.make_coefficient_table(*mf_storage)); \n\n          break; \n        } \n\n      case Settings::gmg_mb: \n      case Settings::amg: \n        { \n#ifdef USE_PETSC_LA \n          DynamicSparsityPattern dsp(locally_relevant_dofs); \n          DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints); \n\n          SparsityTools::distribute_sparsity_pattern(dsp, \n                                                     locally_owned_dofs, \n                                                     mpi_communicator, \n                                                     locally_relevant_dofs); \n\n          system_matrix.reinit(locally_owned_dofs, \n                               locally_owned_dofs, \n                               dsp, \n                               mpi_communicator); \n#else \n          TrilinosWrappers::SparsityPattern dsp(locally_owned_dofs, \n                                                locally_owned_dofs, \n                                                locally_relevant_dofs, \n                                                mpi_communicator); \n          DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints); \n          dsp.compress(); \n          system_matrix.reinit(dsp); \n#endif \n\n          break; \n        } \n\n      default: \n        Assert(false, ExcNotImplemented()); \n    } \n} \n// @sect4{LaplaceProblem::setup_multigrid()}  \n\n// \u8be5\u51fd\u6570\u4e3a\u65e0\u77e9\u9635\u548c\u57fa\u4e8e\u77e9\u9635\u7684GMG\u8fdb\u884c\u591a\u7ea7\u8bbe\u7f6e\u3002\u65e0\u77e9\u9635\u7684\u8bbe\u7f6e\u7c7b\u4f3c\u4e8e step-37 \uff0c\u800c\u57fa\u4e8e\u77e9\u9635\u7684\u8bbe\u7f6e\u7c7b\u4f3c\u4e8e step-16 \uff0c\u53ea\u662f\u6211\u4eec\u5fc5\u987b\u4f7f\u7528\u9002\u5f53\u7684\u5206\u5e03\u5f0f\u7a00\u758f\u5ea6\u6a21\u5f0f\u3002\n\n// \u8be5\u51fd\u6570\u6ca1\u6709\u88abAMG\u65b9\u6cd5\u8c03\u7528\uff0c\u4f46\u4e3a\u4e86\u5b89\u5168\u8d77\u89c1\uff0c\u8be5\u51fd\u6570\u7684\u4e3b`switch`\u8bed\u53e5\u8fd8\u662f\u786e\u4fdd\u4e86\u8be5\u51fd\u6570\u53ea\u5728\u5df2\u77e5\u7684\u591a\u7f51\u683c\u8bbe\u7f6e\u4e0b\u8fd0\u884c\uff0c\u5982\u679c\u8be5\u51fd\u6570\u88ab\u8c03\u7528\u5230\u4e24\u79cd\u51e0\u4f55\u591a\u7f51\u683c\u65b9\u6cd5\u4ee5\u5916\u7684\u5730\u65b9\uff0c\u5219\u629b\u51fa\u4e00\u4e2a\u65ad\u8a00\u3002\n\ntemplate <int dim, int degree> \nvoid LaplaceProblem<dim, degree>::setup_multigrid() \n{ \n  TimerOutput::Scope timing(computing_timer, \"Setup multigrid\"); \n\n  dof_handler.distribute_mg_dofs(); \n\n  mg_constrained_dofs.clear(); \n  mg_constrained_dofs.initialize(dof_handler); \n\n  const std::set<types::boundary_id> boundary_ids = {types::boundary_id(0)}; \n  mg_constrained_dofs.make_zero_boundary_constraints(dof_handler, boundary_ids); \n\n  const unsigned int n_levels = triangulation.n_global_levels(); \n\n  switch (settings.solver) \n    { \n      case Settings::gmg_mf: \n        { \n          mf_mg_matrix.resize(0, n_levels - 1); \n\n          for (unsigned int level = 0; level < n_levels; ++level) \n            { \n              IndexSet relevant_dofs; \n              DoFTools::extract_locally_relevant_level_dofs(dof_handler, \n                                                            level, \n                                                            relevant_dofs); \n              AffineConstraints<double> level_constraints; \n              level_constraints.reinit(relevant_dofs); \n              level_constraints.add_lines( \n                mg_constrained_dofs.get_boundary_indices(level)); \n              level_constraints.close(); \n\n              typename MatrixFree<dim, float>::AdditionalData additional_data; \n              additional_data.tasks_parallel_scheme = \n                MatrixFree<dim, float>::AdditionalData::none; \n              additional_data.mapping_update_flags = \n                (update_gradients | update_JxW_values | \n                 update_quadrature_points); \n              additional_data.mg_level = level; \n              std::shared_ptr<MatrixFree<dim, float>> mf_storage_level( \n                new MatrixFree<dim, float>()); \n              mf_storage_level->reinit(mapping, \n                                       dof_handler, \n                                       level_constraints, \n                                       QGauss<1>(degree + 1), \n                                       additional_data); \n\n              mf_mg_matrix[level].initialize(mf_storage_level, \n                                             mg_constrained_dofs, \n                                             level); \n\n              const Coefficient<dim> coefficient; \n              mf_mg_matrix[level].set_coefficient( \n                coefficient.make_coefficient_table(*mf_storage_level)); \n\n              mf_mg_matrix[level].compute_diagonal(); \n            } \n\n          break; \n        } \n\n      case Settings::gmg_mb: \n        { \n          mg_matrix.resize(0, n_levels - 1); \n          mg_matrix.clear_elements(); \n          mg_interface_in.resize(0, n_levels - 1); \n          mg_interface_in.clear_elements(); \n\n          for (unsigned int level = 0; level < n_levels; ++level) \n            { \n              IndexSet dof_set; \n              DoFTools::extract_locally_relevant_level_dofs(dof_handler, \n                                                            level, \n                                                            dof_set); \n\n              { \n#ifdef USE_PETSC_LA \n                DynamicSparsityPattern dsp(dof_set); \n                MGTools::make_sparsity_pattern(dof_handler, dsp, level); \n                dsp.compress(); \n                SparsityTools::distribute_sparsity_pattern( \n                  dsp, \n                  dof_handler.locally_owned_mg_dofs(level), \n                  mpi_communicator, \n                  dof_set); \n\n                mg_matrix[level].reinit( \n                  dof_handler.locally_owned_mg_dofs(level), \n                  dof_handler.locally_owned_mg_dofs(level), \n                  dsp, \n                  mpi_communicator); \n#else \n                TrilinosWrappers::SparsityPattern dsp( \n                  dof_handler.locally_owned_mg_dofs(level), \n                  dof_handler.locally_owned_mg_dofs(level), \n                  dof_set, \n                  mpi_communicator); \n                MGTools::make_sparsity_pattern(dof_handler, dsp, level); \n\n                dsp.compress(); \n                mg_matrix[level].reinit(dsp); \n#endif \n              } \n\n              { \n#ifdef USE_PETSC_LA \n                DynamicSparsityPattern dsp(dof_set); \n                MGTools::make_interface_sparsity_pattern(dof_handler, \n                                                         mg_constrained_dofs, \n                                                         dsp, \n                                                         level); \n                dsp.compress(); \n                SparsityTools::distribute_sparsity_pattern( \n                  dsp, \n                  dof_handler.locally_owned_mg_dofs(level), \n                  mpi_communicator, \n                  dof_set); \n\n                mg_interface_in[level].reinit( \n                  dof_handler.locally_owned_mg_dofs(level), \n                  dof_handler.locally_owned_mg_dofs(level), \n                  dsp, \n                  mpi_communicator); \n#else \n                TrilinosWrappers::SparsityPattern dsp( \n                  dof_handler.locally_owned_mg_dofs(level), \n                  dof_handler.locally_owned_mg_dofs(level), \n                  dof_set, \n                  mpi_communicator); \n\n                MGTools::make_interface_sparsity_pattern(dof_handler, \n                                                         mg_constrained_dofs, \n                                                         dsp, \n                                                         level); \n                dsp.compress(); \n                mg_interface_in[level].reinit(dsp); \n#endif \n              } \n            } \n          break; \n        } \n\n      default: \n        Assert(false, ExcNotImplemented()); \n    } \n} \n// @sect4{LaplaceProblem::assemble_system()}  \n\n// \u6c47\u7f16\u88ab\u5206\u6210\u4e09\u4e2a\u90e8\u5206\uff1a`assemble_system()`, `assemble_multigrid()`, \u548c`assemble_rhs()`\u3002\u8fd9\u91cc\u7684`assemble_system()`\u51fd\u6570\u7ec4\u88c5\u5e76\u5b58\u50a8\uff08\u5168\u5c40\uff09\u7cfb\u7edf\u77e9\u9635\u548c\u57fa\u4e8e\u77e9\u9635\u7684\u65b9\u6cd5\u7684\u53f3\u624b\u8fb9\u3002\u5b83\u7c7b\u4f3c\u4e8e  step-40  \u4e2d\u7684\u88c5\u914d\u3002\n\n// \u6ce8\u610f\uff0c\u65e0\u77e9\u9635\u65b9\u6cd5\u4e0d\u6267\u884c\u8fd9\u4e2a\u51fd\u6570\uff0c\u56e0\u4e3a\u5b83\u4e0d\u9700\u8981\u7ec4\u88c5\u77e9\u9635\uff0c\u800c\u662f\u5728assemble_rhs()\u4e2d\u7ec4\u88c5\u53f3\u624b\u8fb9\u3002\n\ntemplate <int dim, int degree> \nvoid LaplaceProblem<dim, degree>::assemble_system() \n{ \n  TimerOutput::Scope timing(computing_timer, \"Assemble\"); \n\n  const QGauss<dim> quadrature_formula(degree + 1); \n\n  FEValues<dim> fe_values(fe, \n                          quadrature_formula, \n                          update_values | update_gradients | \n                            update_quadrature_points | update_JxW_values); \n\n  const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n  const unsigned int n_q_points    = quadrature_formula.size(); \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  const Coefficient<dim> coefficient; \n  RightHandSide<dim>     rhs; \n  std::vector<double>    rhs_values(n_q_points); \n\n  for (const auto &cell : dof_handler.active_cell_iterators()) \n    if (cell->is_locally_owned()) \n      { \n        cell_matrix = 0; \n        cell_rhs    = 0; \n\n        fe_values.reinit(cell); \n\n        const double coefficient_value = \n          coefficient.average_value(fe_values.get_quadrature_points()); \n        rhs.value_list(fe_values.get_quadrature_points(), 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                  coefficient_value *                // epsilon(x) \n                  fe_values.shape_grad(i, q_point) * // * grad phi_i(x) \n                  fe_values.shape_grad(j, q_point) * // * grad phi_j(x) \n                  fe_values.JxW(q_point);            // * dx \n\n              cell_rhs(i) += \n                fe_values.shape_value(i, q_point) * // grad phi_i(x) \n                rhs_values[q_point] *               // * f(x) \n                fe_values.JxW(q_point);             // * dx \n            } \n\n        cell->get_dof_indices(local_dof_indices); \n        constraints.distribute_local_to_global(cell_matrix, \n                                               cell_rhs, \n                                               local_dof_indices, \n                                               system_matrix, \n                                               right_hand_side); \n      } \n\n  system_matrix.compress(VectorOperation::add); \n  right_hand_side.compress(VectorOperation::add); \n} \n// @sect4{LaplaceProblem::assemble_multigrid()}  \n\n// \u4e0b\u9762\u7684\u51fd\u6570\u4e3a\u57fa\u4e8e\u77e9\u9635\u7684GMG\u65b9\u6cd5\u7ec4\u88c5\u548c\u5b58\u50a8\u591a\u7ea7\u77e9\u9635\u3002\u8fd9\u4e2a\u51fd\u6570\u4e0e step-16 \u4e2d\u7684\u51fd\u6570\u7c7b\u4f3c\uff0c\u53ea\u662f\u5728\u8fd9\u91cc\u5b83\u9002\u7528\u4e8e\u5206\u5e03\u5f0f\u7f51\u683c\u3002\u8fd9\u4e2a\u533a\u522b\u5728\u4e8e\u589e\u52a0\u4e86\u4e00\u4e2a\u6761\u4ef6\uff0c\u5373\u6211\u4eec\u53ea\u5728\u672c\u5730\u62e5\u6709\u7684\u6c34\u5e73\u5355\u5143\u4e0a\u8fdb\u884c\u7ec4\u88c5\uff0c\u5e76\u4e3a\u6bcf\u4e2a\u88ab\u5efa\u7acb\u7684\u77e9\u9635\u8c03\u7528\u538b\u7f29\uff08\uff09\u3002\n\ntemplate <int dim, int degree> \nvoid LaplaceProblem<dim, degree>::assemble_multigrid() \n{ \n  TimerOutput::Scope timing(computing_timer, \"Assemble multigrid\"); \n\n  QGauss<dim> quadrature_formula(degree + 1); \n\n  FEValues<dim> fe_values(fe, \n                          quadrature_formula, \n                          update_values | update_gradients | \n                            update_quadrature_points | update_JxW_values); \n\n  const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n  const unsigned int n_q_points    = quadrature_formula.size(); \n\n  FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n\n  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n  const Coefficient<dim> coefficient; \n\n  std::vector<AffineConstraints<double>> boundary_constraints( \n    triangulation.n_global_levels()); \n  for (unsigned int level = 0; level < triangulation.n_global_levels(); ++level) \n    { \n      IndexSet dof_set; \n      DoFTools::extract_locally_relevant_level_dofs(dof_handler, \n                                                    level, \n                                                    dof_set); \n      boundary_constraints[level].reinit(dof_set); \n      boundary_constraints[level].add_lines( \n        mg_constrained_dofs.get_refinement_edge_indices(level)); \n      boundary_constraints[level].add_lines( \n        mg_constrained_dofs.get_boundary_indices(level)); \n\n      boundary_constraints[level].close(); \n    } \n\n  for (const auto &cell : dof_handler.cell_iterators()) \n    if (cell->level_subdomain_id() == triangulation.locally_owned_subdomain()) \n      { \n        cell_matrix = 0; \n        fe_values.reinit(cell); \n\n        const double coefficient_value = \n          coefficient.average_value(fe_values.get_quadrature_points()); \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            for (unsigned int j = 0; j < dofs_per_cell; ++j) \n              cell_matrix(i, j) += \n                coefficient_value * fe_values.shape_grad(i, q_point) * \n                fe_values.shape_grad(j, q_point) * fe_values.JxW(q_point); \n\n        cell->get_mg_dof_indices(local_dof_indices); \n\n        boundary_constraints[cell->level()].distribute_local_to_global( \n          cell_matrix, local_dof_indices, mg_matrix[cell->level()]); \n\n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          for (unsigned int j = 0; j < dofs_per_cell; ++j) \n            if (mg_constrained_dofs.is_interface_matrix_entry( \n                  cell->level(), local_dof_indices[i], local_dof_indices[j])) \n              mg_interface_in[cell->level()].add(local_dof_indices[i], \n                                                 local_dof_indices[j], \n                                                 cell_matrix(i, j)); \n      } \n\n  for (unsigned int i = 0; i < triangulation.n_global_levels(); ++i) \n    { \n      mg_matrix[i].compress(VectorOperation::add); \n      mg_interface_in[i].compress(VectorOperation::add); \n    } \n} \n\n//  @sect4{LaplaceProblem::assemble_rhs()}  \n\n// \u8fd9\u4e2a\u4e09\u8981\u7d20\u4e2d\u7684\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u4e3a\u65e0\u77e9\u9635\u65b9\u6cd5\u7ec4\u88c5\u53f3\u624b\u8fb9\u7684\u5411\u91cf--\u56e0\u4e3a\u5728\u65e0\u77e9\u9635\u6846\u67b6\u4e2d\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u7ec4\u88c5\u77e9\u9635\uff0c\u53ea\u9700\u8981\u7ec4\u88c5\u53f3\u624b\u8fb9\u5c31\u53ef\u4ee5\u4e86\u3002\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u4ece\u4e0a\u9762\u7684`assemble_system()`\u51fd\u6570\u4e2d\u63d0\u53d6\u5904\u7406\u53f3\u624b\u8fb9\u7684\u4ee3\u7801\u6765\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u4f46\u662f\u6211\u4eec\u51b3\u5b9a\u5b8c\u5168\u91c7\u7528\u65e0\u77e9\u9635\u7684\u65b9\u6cd5\uff0c\u4e5f\u7528\u8fd9\u79cd\u65b9\u6cd5\u8fdb\u884c\u88c5\u914d\u3002\n\n// \u7ed3\u679c\u662f\u4e00\u4e2a\u7c7b\u4f3c\u4e8e step-37 \u4e2d \"\u4f7f\u7528 FEEvaluation::read_dof_values_plain() \u6765\u907f\u514d\u89e3\u51b3\u7ea6\u675f \"\u4e00\u8282\u4e2d\u7684\u51fd\u6570\u3002\n\n// \u8fd9\u4e2a\u51fd\u6570\u7684\u539f\u56e0\u662fMatrixFree\u8fd0\u7b97\u7b26\u4e0d\u8003\u8651\u975e\u540c\u8d28\u7684Dirichlet\u7ea6\u675f\uff0c\u800c\u662f\u5c06\u6240\u6709\u7684Dirichlet\u7ea6\u675f\u89c6\u4e3a\u540c\u8d28\u7684\u3002\u4e3a\u4e86\u8bf4\u660e\u8fd9\u4e00\u70b9\uff0c\u8fd9\u91cc\u7684\u53f3\u624b\u8fb9\u88ab\u7ec4\u88c5\u6210\u6b8b\u5dee $r_0 = f-Au_0$ \uff0c\u5176\u4e2d $u_0$ \u662f\u4e00\u4e2a\u96f6\u5411\u91cf\uff0c\u9664\u4e86\u5728Dirichlet\u503c\u4e2d\u3002\u7136\u540e\u5728\u6c42\u89e3\u7684\u65f6\u5019\uff0c\u6211\u4eec\u53ef\u4ee5\u770b\u5230\uff0c\u89e3\u51b3\u65b9\u6848\u662f  $u = u_0 + A^{-1}r_0$  \u3002\u8fd9\u53ef\u4ee5\u770b\u4f5c\u662f\u5bf9\u521d\u59cb\u731c\u6d4b\u4e3a  $u_0$  \u7684\u7ebf\u6027\u7cfb\u7edf\u8fdb\u884c\u7684\u725b\u987f\u8fed\u4ee3\u3002\u4e0b\u9762`solve()`\u51fd\u6570\u4e2d\u7684CG\u89e3\u8ba1\u7b97\u4e86 $A^{-1}r_0$ \uff0c\u8c03\u7528`constraints.distribution()`\uff08\u76f4\u63a5\u5728\u540e\u9762\uff09\u589e\u52a0\u4e86 $u_0$  \u3002\n\n// \u663e\u7136\uff0c\u7531\u4e8e\u6211\u4eec\u8003\u8651\u7684\u662f\u4e00\u4e2a\u96f6\u8fea\u91cc\u5e0c\u7279\u8fb9\u754c\u7684\u95ee\u9898\uff0c\u6211\u4eec\u53ef\u4ee5\u91c7\u53d6\u7c7b\u4f3c\u4e8e step-37  `assemble_rhs()`\u7684\u65b9\u6cd5\uff0c\u4f46\u662f\u8fd9\u4e2a\u989d\u5916\u7684\u5de5\u4f5c\u5141\u8bb8\u6211\u4eec\u6539\u53d8\u95ee\u9898\u58f0\u660e\uff0c\u5982\u679c\u6211\u4eec\u9009\u62e9\u7684\u8bdd\u3002\n\n// \u8fd9\u4e2a\u51fd\u6570\u5728\u79ef\u5206\u5faa\u73af\u4e2d\u6709\u4e24\u4e2a\u90e8\u5206\uff1a\u901a\u8fc7\u63d0\u4ea4\u68af\u5ea6\u7684\u8d1f\u503c\u5c06\u77e9\u9635  $A$  \u7684\u8d1f\u503c\u5e94\u7528\u4e8e  $u_0$  \uff0c\u5e76\u901a\u8fc7\u63d0\u4ea4\u503c  $f$  \u6dfb\u52a0\u53f3\u624b\u8fb9\u7684\u8d21\u732e\u3002\u6211\u4eec\u5fc5\u987b\u786e\u4fdd\u4f7f\u7528`read_dof_values_plain()`\u6765\u8bc4\u4f30 $u_0$ \uff0c\u56e0\u4e3a`read_dof_vaues()`\u4f1a\u5c06\u6240\u6709Dirichlet\u503c\u8bbe\u7f6e\u4e3a0\u3002\n\n// \u6700\u540e\uff0csystem_rhs\u5411\u91cf\u7684\u7c7b\u578b\u662f LA::MPI::Vector, \uff0c\u4f46MatrixFree\u7c7b\u53ea\u5bf9 dealii::LinearAlgebra::distributed::Vector. \u8d77\u4f5c\u7528\uff0c\u56e0\u6b64\u6211\u4eec\u5fc5\u987b\u4f7f\u7528MatrixFree\u529f\u80fd\u8ba1\u7b97\u53f3\u624b\u8fb9\uff0c\u7136\u540e\u4f7f\u7528`ChangeVectorType`\u547d\u540d\u7a7a\u95f4\u7684\u51fd\u6570\u5c06\u5176\u590d\u5236\u5230\u6b63\u786e\u7684\u7c7b\u578b\u3002\n\ntemplate <int dim, int degree> \nvoid LaplaceProblem<dim, degree>::assemble_rhs() \n{ \n  TimerOutput::Scope timing(computing_timer, \"Assemble right-hand side\"); \n\n  MatrixFreeActiveVector solution_copy; \n  MatrixFreeActiveVector right_hand_side_copy; \n  mf_system_matrix.initialize_dof_vector(solution_copy); \n  mf_system_matrix.initialize_dof_vector(right_hand_side_copy); \n\n  solution_copy = 0.; \n  constraints.distribute(solution_copy); \n  solution_copy.update_ghost_values(); \n  right_hand_side_copy = 0; \n  const Table<2, VectorizedArray<double>> &coefficient = \n    *(mf_system_matrix.get_coefficient()); \n\n  RightHandSide<dim> right_hand_side_function; \n\n  FEEvaluation<dim, degree, degree + 1, 1, double> phi( \n    *mf_system_matrix.get_matrix_free()); \n\n  for (unsigned int cell = 0; \n       cell < mf_system_matrix.get_matrix_free()->n_cell_batches(); \n       ++cell) \n    { \n      phi.reinit(cell); \n      phi.read_dof_values_plain(solution_copy); \n      phi.evaluate(EvaluationFlags::gradients); \n\n      for (unsigned int q = 0; q < phi.n_q_points; ++q) \n        { \n          phi.submit_gradient(-1.0 * \n                                (coefficient(cell, 0) * phi.get_gradient(q)), \n                              q); \n          phi.submit_value( \n            right_hand_side_function.value(phi.quadrature_point(q)), q); \n        } \n\n      phi.integrate_scatter(EvaluationFlags::values | \n                              EvaluationFlags::gradients, \n                            right_hand_side_copy); \n    } \n\n  right_hand_side_copy.compress(VectorOperation::add); \n\n  ChangeVectorTypes::copy(right_hand_side, right_hand_side_copy); \n} \n\n//  @sect4{LaplaceProblem::solve()}  \n\n// \u8fd9\u91cc\u6211\u4eec\u8bbe\u7f6e\u4e86\u591a\u7f51\u683c\u9884\u5904\u7406\u7a0b\u5e8f\uff0c\u6d4b\u8bd5\u4e86\u5355\u4e2aV\u578b\u5468\u671f\u7684\u65f6\u95f4\uff0c\u5e76\u89e3\u51b3\u4e86\u7ebf\u6027\u7cfb\u7edf\u3002\u4e0d\u51fa\u6240\u6599\uff0c\u8fd9\u662f\u4e09\u79cd\u65b9\u6cd5\u5dee\u522b\u6700\u5927\u7684\u5730\u65b9\u4e4b\u4e00\u3002\n\ntemplate <int dim, int degree> \nvoid LaplaceProblem<dim, degree>::solve() \n{ \n  TimerOutput::Scope timing(computing_timer, \"Solve\"); \n\n  SolverControl solver_control(1000, 1.e-10 * right_hand_side.l2_norm()); \n  solver_control.enable_history_data(); \n\n  solution = 0.; \n\n// \u65e0\u77e9\u9635GMG\u65b9\u6cd5\u7684\u6c42\u89e3\u5668\u7c7b\u4f3c\u4e8e  step-37  \uff0c\u9664\u4e86\u589e\u52a0\u4e00\u4e9b\u63a5\u53e3\u77e9\u9635\uff0c\u5b8c\u5168\u7c7b\u4f3c\u4e8e  step-16  \u3002\n\n  switch (settings.solver) \n    { \n      case Settings::gmg_mf: \n        { \n          computing_timer.enter_subsection(\"Solve: Preconditioner setup\"); \n\n          MGTransferMatrixFree<dim, float> mg_transfer(mg_constrained_dofs); \n          mg_transfer.build(dof_handler); \n\n          SolverControl coarse_solver_control(1000, 1e-12, false, false); \n          SolverCG<MatrixFreeLevelVector> coarse_solver(coarse_solver_control); \n          PreconditionIdentity            identity; \n          MGCoarseGridIterativeSolver<MatrixFreeLevelVector, \n                                      SolverCG<MatrixFreeLevelVector>, \n                                      MatrixFreeLevelMatrix, \n                                      PreconditionIdentity> \n            coarse_grid_solver(coarse_solver, mf_mg_matrix[0], identity); \n\n          using Smoother = dealii::PreconditionJacobi<MatrixFreeLevelMatrix>; \n          MGSmootherPrecondition<MatrixFreeLevelMatrix, \n                                 Smoother, \n                                 MatrixFreeLevelVector> \n            smoother; \n          smoother.initialize(mf_mg_matrix, \n                              typename Smoother::AdditionalData( \n                                settings.smoother_dampen)); \n          smoother.set_steps(settings.smoother_steps); \n\n          mg::Matrix<MatrixFreeLevelVector> mg_m(mf_mg_matrix); \n\n          MGLevelObject< \n            MatrixFreeOperators::MGInterfaceOperator<MatrixFreeLevelMatrix>> \n            mg_interface_matrices; \n          mg_interface_matrices.resize(0, triangulation.n_global_levels() - 1); \n          for (unsigned int level = 0; level < triangulation.n_global_levels(); \n               ++level) \n            mg_interface_matrices[level].initialize(mf_mg_matrix[level]); \n          mg::Matrix<MatrixFreeLevelVector> mg_interface(mg_interface_matrices); \n\n          Multigrid<MatrixFreeLevelVector> mg( \n            mg_m, coarse_grid_solver, mg_transfer, smoother, smoother); \n          mg.set_edge_matrices(mg_interface, mg_interface); \n\n          PreconditionMG<dim, \n                         MatrixFreeLevelVector, \n                         MGTransferMatrixFree<dim, float>> \n            preconditioner(dof_handler, mg, mg_transfer); \n\n// \u5c06\u6c42\u89e3\u5411\u91cf\u548c\u53f3\u624b\u8fb9\u4ece LA::MPI::Vector \u590d\u5236\u5230 dealii::LinearAlgebra::distributed::Vector \uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u89e3\u51b3\u4e86\u3002\n\n          MatrixFreeActiveVector solution_copy; \n          MatrixFreeActiveVector right_hand_side_copy; \n          mf_system_matrix.initialize_dof_vector(solution_copy); \n          mf_system_matrix.initialize_dof_vector(right_hand_side_copy); \n\n          ChangeVectorTypes::copy(solution_copy, solution); \n          ChangeVectorTypes::copy(right_hand_side_copy, right_hand_side); \n          computing_timer.leave_subsection(\"Solve: Preconditioner setup\"); \n\n// 1\u4e2aV\u578b\u5468\u671f\u7684\u65f6\u95f4\u5b89\u6392\u3002\n\n          { \n            TimerOutput::Scope timing(computing_timer, \n                                      \"Solve: 1 multigrid V-cycle\"); \n            preconditioner.vmult(solution_copy, right_hand_side_copy); \n          } \n          solution_copy = 0.; \n\n// \u89e3\u51fa\u7ebf\u6027\u7cfb\u7edf\uff0c\u66f4\u65b0\u89e3\u7684\u9b3c\u9b42\u503c\uff0c\u590d\u5236\u56de LA::MPI::Vector \u5e76\u5206\u914d\u7ea6\u675f\u3002\n\n          { \n            SolverCG<MatrixFreeActiveVector> solver(solver_control); \n\n            TimerOutput::Scope timing(computing_timer, \"Solve: CG\"); \n            solver.solve(mf_system_matrix, \n                         solution_copy, \n                         right_hand_side_copy, \n                         preconditioner); \n          } \n\n          solution_copy.update_ghost_values(); \n          ChangeVectorTypes::copy(solution, solution_copy); \n          constraints.distribute(solution); \n\n          break; \n        } \n\n// \u57fa\u4e8e\u77e9\u9635\u7684GMG\u65b9\u6cd5\u7684\u6c42\u89e3\u5668\uff0c\u7c7b\u4f3c\u4e8e  step-16  \uff0c\u53ea\u662f\u4f7f\u7528\u4e86\u96c5\u53ef\u6bd4\u5e73\u6ed1\u5668\uff0c\u800c\u4e0d\u662fSOR\u5e73\u6ed1\u5668\uff08\u8be5\u5e73\u6ed1\u5668\u6ca1\u6709\u5e76\u884c\u5b9e\u73b0\uff09\u3002\n\n      case Settings::gmg_mb: \n        { \n          computing_timer.enter_subsection(\"Solve: Preconditioner setup\"); \n\n          MGTransferPrebuilt<VectorType> mg_transfer(mg_constrained_dofs); \n          mg_transfer.build(dof_handler); \n\n          SolverControl        coarse_solver_control(1000, 1e-12, false, false); \n          SolverCG<VectorType> coarse_solver(coarse_solver_control); \n          PreconditionIdentity identity; \n          MGCoarseGridIterativeSolver<VectorType, \n                                      SolverCG<VectorType>, \n                                      MatrixType, \n                                      PreconditionIdentity> \n            coarse_grid_solver(coarse_solver, mg_matrix[0], identity); \n\n          using Smoother = LA::MPI::PreconditionJacobi; \n          MGSmootherPrecondition<MatrixType, Smoother, VectorType> smoother; \n\n#ifdef USE_PETSC_LA \n          smoother.initialize(mg_matrix); \n          Assert( \n            settings.smoother_dampen == 1.0, \n            ExcNotImplemented( \n              \"PETSc's PreconditionJacobi has no support for a damping parameter.\")); \n#else \n          smoother.initialize(mg_matrix, settings.smoother_dampen); \n#endif \n\n          smoother.set_steps(settings.smoother_steps); \n\n          mg::Matrix<VectorType> mg_m(mg_matrix); \n          mg::Matrix<VectorType> mg_in(mg_interface_in); \n          mg::Matrix<VectorType> mg_out(mg_interface_in); \n\n          Multigrid<VectorType> mg( \n            mg_m, coarse_grid_solver, mg_transfer, smoother, smoother); \n          mg.set_edge_matrices(mg_out, mg_in); \n\n          PreconditionMG<dim, VectorType, MGTransferPrebuilt<VectorType>> \n            preconditioner(dof_handler, mg, mg_transfer); \n\n          computing_timer.leave_subsection(\"Solve: Preconditioner setup\"); \n\n// 1\u4e2aV\u578b\u5468\u671f\u7684\u8ba1\u65f6\u3002\n\n          { \n            TimerOutput::Scope timing(computing_timer, \n                                      \"Solve: 1 multigrid V-cycle\"); \n            preconditioner.vmult(solution, right_hand_side); \n          } \n          solution = 0.; \n\n// \u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u548c\u5206\u914d\u7ea6\u675f\u3002\n\n          { \n            SolverCG<VectorType> solver(solver_control); \n\n            TimerOutput::Scope timing(computing_timer, \"Solve: CG\"); \n            solver.solve(system_matrix, \n                         solution, \n                         right_hand_side, \n                         preconditioner); \n          } \n\n          constraints.distribute(solution); \n\n \n        } \n\n// AMG\u65b9\u6cd5\u7684\u6c42\u89e3\u5668\uff0c\u7c7b\u4f3c\u4e8e  step-40  \u3002\n\n      case Settings::amg: \n        { \n          computing_timer.enter_subsection(\"Solve: Preconditioner setup\"); \n\n          PreconditionAMG                 preconditioner; \n          PreconditionAMG::AdditionalData Amg_data; \n\n#ifdef USE_PETSC_LA \n          Amg_data.symmetric_operator = true; \n#else \n          Amg_data.elliptic              = true; \n          Amg_data.smoother_type         = \"Jacobi\"; \n          Amg_data.higher_order_elements = true; \n          Amg_data.smoother_sweeps       = settings.smoother_steps; \n          Amg_data.aggregation_threshold = 0.02; \n#endif \n\n          Amg_data.output_details = false; \n\n          preconditioner.initialize(system_matrix, Amg_data); \n          computing_timer.leave_subsection(\"Solve: Preconditioner setup\"); \n\n// 1\u4e2aV\u578b\u5468\u671f\u7684\u8ba1\u65f6\u3002\n\n          { \n            TimerOutput::Scope timing(computing_timer, \n                                      \"Solve: 1 multigrid V-cycle\"); \n            preconditioner.vmult(solution, right_hand_side); \n          } \n          solution = 0.; \n\n// \u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u548c\u5206\u914d\u7ea6\u675f\u3002\n\n          { \n            SolverCG<VectorType> solver(solver_control); \n\n            TimerOutput::Scope timing(computing_timer, \"Solve: CG\"); \n            solver.solve(system_matrix, \n                         solution, \n                         right_hand_side, \n                         preconditioner); \n          } \n          constraints.distribute(solution); \n\n          break; \n        } \n\n      default: \n        Assert(false, ExcInternalError()); \n    } \n\n  pcout << \"   Number of CG iterations:      \" << solver_control.last_step() \n        << std::endl; \n} \n// @sect3{The error estimator}  \n\n// \u6211\u4eec\u4f7f\u7528FEInterfaceValues\u7c7b\u6765\u7ec4\u88c5\u4e00\u4e2a\u8bef\u5dee\u4f30\u8ba1\u5668\uff0c\u4ee5\u51b3\u5b9a\u54ea\u4e9b\u5355\u5143\u9700\u8981\u7ec6\u5316\u3002\u8bf7\u770b\u4ecb\u7ecd\u4e2d\u5bf9\u5355\u5143\u548c\u9762\u79ef\u5206\u7684\u786e\u5207\u5b9a\u4e49\u3002\u4e3a\u4e86\u4f7f\u7528\u8be5\u65b9\u6cd5\uff0c\u6211\u4eec\u4e3a MeshWorker::mesh_loop() \u5b9a\u4e49\u4e86Scratch\u548cCopy\u5bf9\u8c61\uff0c\u4e0b\u9762\u7684\u5927\u90e8\u5206\u4ee3\u7801\u672c\u8d28\u4e0a\u4e0e step-12 \u4e2d\u5df2\u7ecf\u8bbe\u7f6e\u7684\u4e00\u6837\uff08\u6216\u8005\u81f3\u5c11\u7cbe\u795e\u4e0a\u76f8\u4f3c\uff09\u3002\n\ntemplate <int dim> \nstruct ScratchData \n{ \n  ScratchData(const Mapping<dim> &      mapping, \n              const FiniteElement<dim> &fe, \n              const unsigned int        quadrature_degree, \n              const UpdateFlags         update_flags, \n              const UpdateFlags         interface_update_flags) \n    : fe_values(mapping, fe, QGauss<dim>(quadrature_degree), update_flags) \n    , fe_interface_values(mapping, \n                          fe, \n                          QGauss<dim - 1>(quadrature_degree), \n                          interface_update_flags) \n  {} \n\n  ScratchData(const ScratchData<dim> &scratch_data) \n    : fe_values(scratch_data.fe_values.get_mapping(), \n                scratch_data.fe_values.get_fe(), \n                scratch_data.fe_values.get_quadrature(), \n                scratch_data.fe_values.get_update_flags()) \n    , fe_interface_values(scratch_data.fe_values.get_mapping(), \n                          scratch_data.fe_values.get_fe(), \n                          scratch_data.fe_interface_values.get_quadrature(), \n                          scratch_data.fe_interface_values.get_update_flags()) \n  {} \n\n  FEValues<dim>          fe_values; \n  FEInterfaceValues<dim> fe_interface_values; \n}; \n\nstruct CopyData \n{ \n  CopyData() \n    : cell_index(numbers::invalid_unsigned_int) \n    , value(0.) \n  {} \n\n  CopyData(const CopyData &) = default; \n\n  struct FaceData \n  { \n    unsigned int cell_indices[2]; \n    double       values[2]; \n  }; \n\n  unsigned int          cell_index; \n  double                value; \n  std::vector<FaceData> face_data; \n}; \n\ntemplate <int dim, int degree> \nvoid LaplaceProblem<dim, degree>::estimate() \n{ \n  TimerOutput::Scope timing(computing_timer, \"Estimate\"); \n\n  VectorType temp_solution; \n  temp_solution.reinit(locally_owned_dofs, \n                       locally_relevant_dofs, \n                       mpi_communicator); \n  temp_solution = solution; \n\n  const Coefficient<dim> coefficient; \n\n  estimated_error_square_per_cell.reinit(triangulation.n_active_cells()); \n\n  using Iterator = typename DoFHandler<dim>::active_cell_iterator; \n\n// \u5269\u4f59\u5355\u5143\u7684\u6c47\u7f16\u7a0b\u5e8f  $h^2 \\| f + \\epsilon \\triangle u \\|_K^2$  \u3002\n  auto cell_worker = [&](const Iterator &  cell, \n                         ScratchData<dim> &scratch_data, \n                         CopyData &        copy_data) { \n    FEValues<dim> &fe_values = scratch_data.fe_values; \n    fe_values.reinit(cell); \n\n    RightHandSide<dim> rhs; \n    const double       rhs_value = rhs.value(cell->center()); \n\n    const double nu = coefficient.value(cell->center()); \n\n \n    fe_values.get_function_hessians(temp_solution, hessians); \n\n    copy_data.cell_index = cell->active_cell_index(); \n\n    double residual_norm_square = 0.; \n    for (unsigned k = 0; k < fe_values.n_quadrature_points; ++k) \n      { \n        const double residual = (rhs_value + nu * trace(hessians[k])); \n        residual_norm_square += residual * residual * fe_values.JxW(k); \n      } \n\n    copy_data.value = \n      cell->diameter() * cell->diameter() * residual_norm_square; \n  }; \n\n// \u8138\u90e8\u672f\u8bed\u7684\u6c47\u7f16\u5668  $\\sum_F h_F \\| \\jump{\\epsilon \\nabla u \\cdot n} \\|_F^2$  \u3002\n  auto face_worker = [&](const Iterator &    cell, \n                         const unsigned int &f, \n                         const unsigned int &sf, \n                         const Iterator &    ncell, \n                         const unsigned int &nf, \n                         const unsigned int &nsf, \n                         ScratchData<dim> &  scratch_data, \n                         CopyData &          copy_data) { \n    FEInterfaceValues<dim> &fe_interface_values = \n      scratch_data.fe_interface_values; \n    fe_interface_values.reinit(cell, f, sf, ncell, nf, nsf); \n\n    copy_data.face_data.emplace_back(); \n    CopyData::FaceData &copy_data_face = copy_data.face_data.back(); \n\n    copy_data_face.cell_indices[0] = cell->active_cell_index(); \n    copy_data_face.cell_indices[1] = ncell->active_cell_index(); \n\n    const double coeff1 = coefficient.value(cell->center()); \n    const double coeff2 = coefficient.value(ncell->center()); \n\n    std::vector<Tensor<1, dim>> grad_u[2]; \n\n    for (unsigned int i = 0; i < 2; ++i) \n      { \n        grad_u[i].resize(fe_interface_values.n_quadrature_points); \n        fe_interface_values.get_fe_face_values(i).get_function_gradients( \n          temp_solution, grad_u[i]); \n      } \n\n    double jump_norm_square = 0.; \n\n    for (unsigned int qpoint = 0; \n         qpoint < fe_interface_values.n_quadrature_points; \n         ++qpoint) \n      { \n        const double jump = \n          coeff1 * grad_u[0][qpoint] * fe_interface_values.normal(qpoint) - \n          coeff2 * grad_u[1][qpoint] * fe_interface_values.normal(qpoint); \n\n        jump_norm_square += jump * jump * fe_interface_values.JxW(qpoint); \n      } \n\n    const double h           = cell->face(f)->measure(); \n    copy_data_face.values[0] = 0.5 * h * jump_norm_square; \n    copy_data_face.values[1] = copy_data_face.values[0]; \n  }; \n\n  auto copier = [&](const CopyData &copy_data) { \n    if (copy_data.cell_index != numbers::invalid_unsigned_int) \n      estimated_error_square_per_cell[copy_data.cell_index] += copy_data.value; \n\n    for (auto &cdf : copy_data.face_data) \n      for (unsigned int j = 0; j < 2; ++j) \n        estimated_error_square_per_cell[cdf.cell_indices[j]] += cdf.values[j]; \n  }; \n\n  const unsigned int n_gauss_points = degree + 1; \n  ScratchData<dim>   scratch_data(mapping, \n                                fe, \n                                n_gauss_points, \n                                update_hessians | update_quadrature_points | \n                                  update_JxW_values, \n                                update_values | update_gradients | \n                                  update_JxW_values | update_normal_vectors); \n  CopyData           copy_data; \n\n// \u6211\u4eec\u9700\u8981\u5bf9\u6bcf\u4e2a\u5185\u90e8\u9762\u8fdb\u884c\u4e00\u6b21\u88c5\u914d\uff0c\u4f46\u6211\u4eec\u9700\u8981\u786e\u4fdd\u4e24\u4e2a\u8fdb\u7a0b\u90fd\u5bf9\u672c\u5730\u62e5\u6709\u7684\u5355\u5143\u548c\u5e7d\u7075\u5355\u5143\u4e4b\u95f4\u7684\u9762\u672f\u8bed\u8fdb\u884c\u88c5\u914d\u3002\u8fd9\u53ef\u4ee5\u901a\u8fc7\u8bbe\u7f6e MeshWorker::assemble_ghost_faces_both \u6807\u5fd7\u6765\u5b9e\u73b0\u3002\u6211\u4eec\u9700\u8981\u8fd9\u6837\u505a\uff0c\u56e0\u4e3a\u6211\u4eec\u4e0d\u5728\u8fd9\u91cc\u4ea4\u6d41\u8bef\u5dee\u4f30\u8ba1\u5668\u7684\u8d21\u732e\u3002\n\n  MeshWorker::mesh_loop(dof_handler.begin_active(), \n                        dof_handler.end(), \n                        cell_worker, \n                        copier, \n                        scratch_data, \n                        copy_data, \n                        MeshWorker::assemble_own_cells | \n                          MeshWorker::assemble_ghost_faces_both | \n                          MeshWorker::assemble_own_interior_faces_once, \n                          /*boundary_worker=*/nullptr, face_worker);\n\n\n \n\n  const double global_error_estimate = \n    std::sqrt(Utilities::MPI::sum(estimated_error_square_per_cell.l1_norm(), \n                                  mpi_communicator)); \n  pcout << \"   Global error estimate:        \" << global_error_estimate \n        << std::endl; \n} \n// @sect4{LaplaceProblem::refine_grid()}  \n\n// \u6211\u4eec\u4f7f\u7528\u5b58\u50a8\u5728\u5411\u91cf @p estimate_vector \u4e2d\u7684\u5355\u5143\u4f30\u8ba1\u5668\uff0c\u5e76\u7ec6\u5316\u56fa\u5b9a\u6570\u91cf\u7684\u5355\u5143\uff08\u8fd9\u91cc\u9009\u62e9\u7684\u662f\u6bcf\u4e00\u6b65\u4e2d\u5927\u7ea6\u4e24\u500d\u7684DoFs\u6570\u91cf\uff09\u3002\n\ntemplate <int dim, int degree> \nvoid LaplaceProblem<dim, degree>::refine_grid() \n{ \n  TimerOutput::Scope timing(computing_timer, \"Refine grid\"); \n\n  const double refinement_fraction = 1. / (std::pow(2.0, dim) - 1.); \n  parallel::distributed::GridRefinement::refine_and_coarsen_fixed_number( \n    triangulation, estimated_error_square_per_cell, refinement_fraction, 0.0); \n\n  triangulation.execute_coarsening_and_refinement(); \n} \n// @sect4{LaplaceProblem::output_results()}  \n\n// output_results()\u51fd\u6570\u4e0e\u8bb8\u591a\u6559\u7a0b\u4e2d\u7684\u51fd\u6570\u7c7b\u4f3c\uff08\u4f8b\u5982\uff0c\u89c1 step-40 \uff09\u3002\n\ntemplate <int dim, int degree> \nvoid LaplaceProblem<dim, degree>::output_results(const unsigned int cycle) \n{ \n  TimerOutput::Scope timing(computing_timer, \"Output results\"); \n\n  VectorType temp_solution; \n  temp_solution.reinit(locally_owned_dofs, \n                       locally_relevant_dofs, \n                       mpi_communicator); \n  temp_solution = solution; \n\n  DataOut<dim> data_out; \n  data_out.attach_dof_handler(dof_handler); \n  data_out.add_data_vector(temp_solution, \"solution\"); \n\n  Vector<float> subdomain(triangulation.n_active_cells()); \n  for (unsigned int i = 0; i < subdomain.size(); ++i) \n    subdomain(i) = triangulation.locally_owned_subdomain(); \n  data_out.add_data_vector(subdomain, \"subdomain\"); \n\n  Vector<float> level(triangulation.n_active_cells()); \n  for (const auto &cell : triangulation.active_cell_iterators()) \n    level(cell->active_cell_index()) = cell->level(); \n  data_out.add_data_vector(level, \"level\"); \n\n  if (estimated_error_square_per_cell.size() > 0) \n    data_out.add_data_vector(estimated_error_square_per_cell, \n                             \"estimated_error_square_per_cell\"); \n\n  data_out.build_patches(); \n\n  const std::string pvtu_filename = data_out.write_vtu_with_pvtu_record( \n    \"\", \"solution\", cycle, mpi_communicator, 2 /*n_digits*/, 1 /*n_groups*/); \n\n  pcout << \"   Wrote \" << pvtu_filename << std::endl; \n} \n// @sect4{LaplaceProblem::run()}  \n\n// \u548c\u5927\u591a\u6570\u6559\u7a0b\u4e00\u6837\uff0c\u8fd9\u4e2a\u51fd\u6570\u8c03\u7528\u4e0a\u9762\u5b9a\u4e49\u7684\u5404\u79cd\u51fd\u6570\u6765\u8bbe\u7f6e\u3001\u7ec4\u5408\u3001\u6c42\u89e3\u548c\u8f93\u51fa\u7ed3\u679c\u3002\n\ntemplate <int dim, int degree> \nvoid LaplaceProblem<dim, degree>::run() \n{ \n  for (unsigned int cycle = 0; cycle < settings.n_steps; ++cycle) \n    { \n      pcout << \"Cycle \" << cycle << ':' << std::endl; \n      if (cycle > 0) \n        refine_grid(); \n\n      pcout << \"   Number of active cells:       \" \n            << triangulation.n_global_active_cells(); \n\n// \u6211\u4eec\u53ea\u4e3aGMG\u65b9\u6cd5\u8f93\u51fa\u5c42\u6b21\u5355\u5143\u6570\u636e\uff08\u4e0e\u4e0b\u9762\u7684DoF\u6570\u636e\u76f8\u540c\uff09\u3002\u8bf7\u6ce8\u610f\uff0c\u5bf9\u4e8eAMG\u6765\u8bf4\uff0c\u5206\u533a\u6548\u7387\u662f\u4e0d\u76f8\u5173\u7684\uff0c\u56e0\u4e3a\u5728\u8ba1\u7b97\u8fc7\u7a0b\u4e2d\u6ca1\u6709\u5206\u5e03\u6216\u4f7f\u7528\u5c42\u6b21\u7ed3\u6784\u3002\n\n      if (settings.solver == Settings::gmg_mf || \n          settings.solver == Settings::gmg_mb) \n        pcout << \" (\" << triangulation.n_global_levels() << \" global levels)\" \n              << std::endl \n              << \"   Partition efficiency:         \" \n              << 1.0 / MGTools::workload_imbalance(triangulation); \n      pcout << std::endl; \n\n      setup_system(); \n\n// \u53ea\u4e3aGMG\u8bbe\u7f6e\u591a\u7ea7\u5c42\u6b21\u7ed3\u6784\u3002\n\n      if (settings.solver == Settings::gmg_mf || \n          settings.solver == Settings::gmg_mb) \n        setup_multigrid(); \n\n      pcout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs(); \n      if (settings.solver == Settings::gmg_mf || \n          settings.solver == Settings::gmg_mb) \n        { \n          pcout << \" (by level: \"; \n          for (unsigned int level = 0; level < triangulation.n_global_levels(); \n               ++level) \n            pcout << dof_handler.n_dofs(level) \n                  << (level == triangulation.n_global_levels() - 1 ? \")\" : \n                                                                     \", \"); \n        } \n      pcout << std::endl; \n\n// \u5bf9\u4e8e\u65e0\u77e9\u9635\u7684\u65b9\u6cd5\uff0c\u6211\u4eec\u53ea\u7ec4\u88c5\u53f3\u624b\u8fb9\u3002\u5bf9\u4e8e\u8fd9\u4e24\u79cd\u57fa\u4e8e\u77e9\u9635\u7684\u65b9\u6cd5\uff0c\u6211\u4eec\u540c\u65f6\u88c5\u914d\u4e3b\u52a8\u77e9\u9635\u548c\u53f3\u624b\u8fb9\uff0c\u5bf9\u4e8e\u57fa\u4e8e\u77e9\u9635\u7684GMG\uff0c\u6211\u4eec\u53ea\u88c5\u914d\u591a\u7f51\u683c\u77e9\u9635\u3002\n\n      if (settings.solver == Settings::gmg_mf) \n        assemble_rhs(); \n      else /*gmg_mb or amg*/ \n        { \n          assemble_system(); \n          if (settings.solver == Settings::gmg_mb) \n            assemble_multigrid(); \n        } \n\n      solve(); \n      estimate(); \n\n      if (settings.output) \n        output_results(cycle); \n\n      computing_timer.print_summary(); \n      computing_timer.reset(); \n    } \n} \n// @sect3{The main() function}  \n\n// \u8fd9\u662f\u4e00\u4e2a\u7c7b\u4f3c\u4e8e step-40 \u7684\u4e3b\u51fd\u6570\uff0c\u4f46\u6211\u4eec\u8981\u6c42\u7528\u6237\u4f20\u9012\u4e00\u4e2a.prm\u6587\u4ef6\u4f5c\u4e3a\u552f\u4e00\u7684\u547d\u4ee4\u884c\u53c2\u6570\uff08\u53c2\u89c1 step-29 \u548cParameterHandler\u7c7b\u7684\u6587\u6863\uff0c\u4ee5\u4e86\u89e3\u5173\u4e8e\u53c2\u6570\u6587\u4ef6\u7684\u5b8c\u6574\u8ba8\u8bba\uff09\u3002\n\nint main(int argc, char *argv[]) \n{ \n  using namespace dealii; \n  Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); \n\n  Settings settings; \n  if (!settings.try_parse((argc > 1) ? (argv[1]) : \"\")) \n    return 0; \n\n  try \n    { \n      constexpr unsigned int fe_degree = 2; \n\n      switch (settings.dimension) \n        { \n          case 2: \n            { \n              LaplaceProblem<2, fe_degree> test(settings); \n              test.run(); \n\n              break; \n            } \n\n          case 3: \n            { \n              LaplaceProblem<3, fe_degree> test(settings); \n              test.run(); \n\n              break; \n            } \n\n          default: \n            Assert(false, ExcMessage(\"This program only works in 2d and 3d.\")); \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      MPI_Abort(MPI_COMM_WORLD, 1); \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      MPI_Abort(MPI_COMM_WORLD, 2); \n      return 1; \n    } \n\n  return 0; \n} \n\n", "meta": {"hexsha": "b81a6d53fcb72a1f609b129b25f670174b11ea15", "size": 52771, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-50/step-50.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-50/step-50.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-50/step-50.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.2747326203, "max_line_length": 299, "alphanum_fraction": 0.5981694491, "num_tokens": 14349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5087842188933993}}
{"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\n#include <iostream>\n#include <NTL/BasicThreadPool.h>\n#include <helib/intraSlot.h>\n#include <helib/tableLookup.h>\n#include <helib/debugging.h>\n\n#include \"gtest/gtest.h\"\n#include \"test_common.h\"\n\nnamespace {\n\nstruct Parameters\n{\n  Parameters(long prm,\n             long bitSize,\n             long outSize,\n             long nTests,\n             bool bootstrap,\n             long seed,\n             long nthreads) :\n      prm(prm),\n      bitSize(bitSize),\n      outSize(outSize),\n      nTests(nTests),\n      bootstrap(bootstrap),\n      seed(seed),\n      nthreads(nthreads){};\n\n  long prm;       // parameter size (0-tiny,...,4-huge)\n  long bitSize;   // bitSize of input integers (<=32)\n  long outSize;   // bitSize of output integers\n  long nTests;    // number of tests to run\n  bool bootstrap; // test multiplication with bootstrapping\n  long seed;      // PRG seed\n  long nthreads;  // number of threads\n\n  friend std::ostream& operator<<(std::ostream& os, const Parameters& params)\n  {\n    return os << \"{\"\n              << \"prm=\" << params.prm << \",\"\n              << \"bitSize=\" << params.bitSize << \",\"\n              << \"outSize=\" << params.outSize << \",\"\n              << \"nTests=\" << params.nTests << \",\"\n              << \"bootstrap=\" << params.bootstrap << \",\"\n              << \"seed=\" << params.seed << \",\"\n              << \"nthreads=\" << params.nthreads << \"}\";\n  };\n};\n\nclass GTestTableLookup : public ::testing::TestWithParam<Parameters>\n{\nprotected:\n  // clang-format off\n  static constexpr long mValues[][15] = {\n  //  {p,phi(m),    m,  d, m1, m2, m3,   g1,   g2,   g3,ord1,ord2,ord3,  B, c}\n      {2,    48,  105, 12,  3, 35,  0,   71,   76,    0,   2,   2,   0, 25, 2},\n      {2,   600, 1023, 10, 11, 93,  0,  838,  584,    0,  10,   6,   0, 25, 2},\n      {2,  2304, 4641, 24,  7,  3,221, 3979, 3095, 3760,   6,   2,  -8, 25, 3},\n      {2, 15004,15709, 22, 23,683,  0, 4099,13663,    0,  22,  31,   0, 25, 3},\n      {2, 27000,32767, 15, 31,  7,151,11628,28087,25824,  30,   6, -10, 28, 4}\n  };\n  // clang-format on\n\n  // Utility encryption/decryption methods\n  static void encryptIndex(std::vector<helib::Ctxt>& ei,\n                           long index,\n                           const helib::SecKey& sKey)\n  {\n    for (long i = 0; i < helib::lsize(ei); i++)\n      sKey.Encrypt(ei[i], NTL::to_ZZX((index >> i) & 1)); // i'th bit of index\n  }\n\n  static long decryptIndex(std::vector<helib::Ctxt>& ei,\n                           const helib::SecKey& sKey)\n  {\n    long num = 0;\n    for (long i = 0; i < helib::lsize(ei); i++) {\n      NTL::ZZX poly;\n      sKey.Decrypt(poly, ei[i]);\n      num += to_long(NTL::ConstTerm(poly)) << i;\n    }\n    return num;\n  }\n\n  static long validatePrm(const long prm)\n  {\n    if (prm < 0 || prm >= 5)\n      throw std::invalid_argument(\"Invalid prm value\");\n    return prm;\n  };\n\n  static long validateBitSize(const long bitSize)\n  {\n    if (bitSize > 7)\n      throw std::invalid_argument(\"Invalid bitSize value: must be <=7\");\n    else if (bitSize <= 0)\n      throw std::invalid_argument(\"Invalid bitSize value: must be >0\");\n    return bitSize;\n  };\n\n  static NTL::Vec<long> calculateMvec(const long* vals)\n  {\n    NTL::Vec<long> mvec;\n    append(mvec, vals[4]);\n    if (vals[5] > 1)\n      append(mvec, vals[5]);\n    if (vals[6] > 1)\n      append(mvec, vals[6]);\n    return mvec;\n  };\n\n  static std::vector<long> calculateGens(const long* vals)\n  {\n    std::vector<long> gens;\n    gens.push_back(vals[7]);\n    if (vals[8] > 1)\n      gens.push_back(vals[8]);\n    if (vals[9] > 1)\n      gens.push_back(vals[9]);\n    return gens;\n  };\n\n  static std::vector<long> calculateOrds(const long* vals)\n  {\n    std::vector<long> ords;\n    ords.push_back(vals[10]);\n    if (abs(vals[11]) > 1)\n      ords.push_back(vals[11]);\n    if (abs(vals[12]) > 1)\n      ords.push_back(vals[12]);\n    return ords;\n  };\n\n  static long calculateLevels(const bool bootstrap, const long bitSize)\n  {\n    long L;\n    if (bootstrap)\n      L = 900; // that should be enough\n    else\n      L = 30 * (5 + bitSize);\n    return L;\n  };\n\n  static void printPreContextPrepDiagnostics(const long bitSize,\n                                             const long outSize,\n                                             const long nTests,\n                                             const long nthreads)\n  {\n    if (helib_test::verbose) {\n      std::cout << \"input bitSize=\" << bitSize\n                << \", output size bound=\" << outSize << \", running \" << nTests\n                << \" tests for each function\\n\";\n      if (nthreads > 1)\n        std::cout << \"  using \" << NTL::AvailableThreads() << \" threads\\n\";\n      std::cout << \"computing key-independent tables...\" << std::flush;\n    }\n  };\n\n  static void printPostContextPrepDiagnostics(const helib::Context& context,\n                                              const long L)\n  {\n    if (helib_test::verbose) {\n      std::cout << \" done.\\n\";\n      context.zMStar.printout();\n      std::cout << \" L=\" << L << std::endl;\n    };\n  }\n\n  // Not static as many instance variables are required.\n  helib::Context& prepareContext(helib::Context& context)\n  {\n    printPreContextPrepDiagnostics(bitSize, outSize, nTests, nthreads);\n    helib::buildModChain(context, L, c, /*willBeBootstrappable*/ bootstrap);\n    if (bootstrap) {\n      context.enableBootStrapping(mvec);\n    }\n    helib::buildUnpackSlotEncoding(unpackSlotEncoding, *context.ea);\n    printPostContextPrepDiagnostics(context, L);\n    return context;\n  };\n\n  static void prepareSecKey(helib::SecKey& secretKey, const bool bootstrap)\n  {\n    if (helib_test::verbose)\n      std::cout << \"\\ncomputing key-dependent tables...\" << std::flush;\n    secretKey.GenSecKey();\n    helib::addSome1DMatrices(secretKey); // compute key-switching matrices\n    helib::addFrbMatrices(secretKey);\n    if (bootstrap)\n      secretKey.genRecryptData();\n    if (helib_test::verbose)\n      std::cout << \" done\\n\";\n  };\n\n  static void setSeedIfNeeded(const long seed)\n  {\n    if (seed)\n      NTL::SetSeed(NTL::ZZ(seed));\n    ;\n  };\n\n  static void setThreadsIfNeeded(const long nthreads)\n  {\n    if (nthreads > 1)\n      NTL::SetNumThreads(nthreads);\n  };\n\n  GTestTableLookup() :\n      prm(validatePrm(GetParam().prm)),\n      bitSize(validateBitSize(GetParam().bitSize)),\n      outSize(GetParam().outSize),\n      nTests(GetParam().nTests),\n      bootstrap(GetParam().bootstrap),\n      seed((setSeedIfNeeded(GetParam().seed), GetParam().seed)),\n      nthreads((setThreadsIfNeeded(GetParam().nthreads), GetParam().nthreads)),\n      vals(mValues[prm]),\n      p(vals[0]),\n      m(vals[2]),\n      mvec(calculateMvec(vals)),\n      gens(calculateGens(vals)),\n      ords(calculateOrds(vals)),\n      c(vals[14]),\n      L(calculateLevels(bootstrap, bitSize)),\n      context(m, p, /*r=*/1, gens, ords),\n      secretKey(prepareContext(context))\n  {\n    prepareSecKey(secretKey, bootstrap);\n  };\n\n  std::vector<helib::zzX> unpackSlotEncoding;\n  const long prm;\n  const long bitSize;\n  const long outSize;\n  const long nTests;\n  const bool bootstrap;\n  const long seed;\n  const long nthreads;\n  const long* vals;\n  const long p;\n  const long m;\n  const NTL::Vec<long> mvec;\n  const std::vector<long> gens;\n  const std::vector<long> ords;\n  const long c;\n  const long L;\n  helib::Context context;\n  helib::SecKey secretKey;\n\n  void SetUp() override\n  {\n    helib::activeContext = &context; // make things a little easier sometimes\n    helib::setupDebugGlobals(&secretKey, context.ea);\n  };\n\n  virtual void TearDown() override\n  {\n#ifdef HELIB_DEBUG\n    helib::cleanupDebugGlobals();\n#endif\n  }\n\npublic:\n  static void TearDownTestCase()\n  {\n    if (helib_test::verbose) {\n      helib::printAllTimers(std::cout);\n    }\n  };\n};\n\nconstexpr long GTestTableLookup::mValues[][15];\n\nTEST_P(GTestTableLookup, lookupFunctionsCorrectly)\n{\n  // Build a table s.t. T[i] = 2^{outSize -1}/(i+1), i=0,...,2^bitSize -1\n  std::vector<helib::zzX> T;\n  helib::buildLookupTable(\n      T,\n      [](double x) { return 1 / (x + 1.0); },\n      bitSize,\n      /*scale_in=*/0,\n      /*sign_in=*/0,\n      outSize,\n      /*scale_out=*/1 - outSize,\n      /*sign_out=*/0,\n      *(secretKey.getContext().ea));\n\n  ASSERT_EQ(helib::lsize(T), 1L << bitSize);\n  for (long i = 0; i < helib::lsize(T); i++) {\n    helib::Ctxt c(secretKey);\n    std::vector<helib::Ctxt> ei(bitSize, c);\n    encryptIndex(ei, i, secretKey); // encrypt the index\n    helib::tableLookup(c,\n                       T,\n                       helib::CtPtrs_vectorCt(ei)); // get the encrypted entry\n    // decrypt and compare\n    NTL::ZZX poly;\n    secretKey.Decrypt(poly, c); // decrypt\n    helib::zzX poly2;\n    helib::convert(poly2, poly); // convert to zzX\n    EXPECT_EQ(poly2, T[i]) << \"testLookup error: decrypted T[\" << i << \"]\\n\";\n  }\n}\n\nTEST_P(GTestTableLookup, writeinFunctionsCorrectly)\n{\n  long tSize = 1L << bitSize; // table size\n\n  // encrypt a random table\n  std::vector<long> pT(tSize, 0);                            // plaintext table\n  std::vector<helib::Ctxt> T(tSize, helib::Ctxt(secretKey)); // encrypted table\n  for (long i = 0; i < bitSize; i++) {\n    long bit = NTL::RandomBits_long(1); // a random bit\n    secretKey.Encrypt(T[i], NTL::to_ZZX(bit));\n    pT[i] = bit;\n  }\n\n  // Add 1 to 20 random entries in the table\n  for (long count = 0; count < nTests; count++) {\n    // encrypt a random index into the table\n    long index = NTL::RandomBnd(tSize); // 0 <= index < tSize\n    std::vector<helib::Ctxt> I(bitSize, helib::Ctxt(secretKey));\n    encryptIndex(I, index, secretKey);\n\n    // do the table write-in\n    tableWriteIn(helib::CtPtrs_vectorCt(T),\n                 helib::CtPtrs_vectorCt(I),\n                 &unpackSlotEncoding);\n    pT[index]++; // add 1 to entry 'index' in the plaintext table\n  }\n\n  // Check that the ciphertext and plaintext tables still match\n  for (int i = 0; i < tSize; i++) {\n    NTL::ZZX poly;\n    secretKey.Decrypt(poly, T[i]);\n    long decrypted = to_long(NTL::ConstTerm(poly));\n    long p = T[i].getPtxtSpace();\n    ASSERT_EQ((pT[i] - decrypted) % p, 0) // should be equal mod p\n        << \"testWritein error: decrypted T[\" << i << \"]=\" << decrypted\n        << \" but should be \" << pT[i] << \" (mod \" << p << \")\\n\";\n  }\n}\n\nINSTANTIATE_TEST_SUITE_P(typicalParameters,\n                         GTestTableLookup,\n                         ::testing::Values(\n                             // SLOW\n                             Parameters(1, 5, 0, 3, false, 0, 1)\n                             // FAST\n                             // Parameters(0, 5, 0, 3, false, 0, 1)\n                             ));\n\n} // namespace\n", "meta": {"hexsha": "0c3cfe8a9519cf5f12ca9646bba2502b26a2847f", "size": 11215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/GTestTableLookup.cpp", "max_stars_repo_name": "jatanloya/HElib-PSI", "max_stars_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/GTestTableLookup.cpp", "max_issues_repo_name": "jatanloya/HElib-PSI", "max_issues_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-05T10:55:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-05T12:59:21.000Z", "max_forks_repo_path": "tests/GTestTableLookup.cpp", "max_forks_repo_name": "jatanloya/HElib-PSI", "max_forks_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "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.6420765027, "max_line_length": 79, "alphanum_fraction": 0.5803834151, "num_tokens": 3261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5087842088518945}}
{"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#include <boost/python.hpp>\n\n#include <ndhist/stats/skewness.hpp>\n\nnamespace bp = boost::python;\n\nnamespace ndhist {\nnamespace stats {\n\nvoid register_skewness()\n{\n    bp::def(\"skewness\"\n      , &py::skewness\n      , ( bp::arg(\"hist\")\n        , bp::arg(\"axis\")=bp::object()\n        )\n      , \"Calculates the skewness along the given axis of the given                \\n\"\n        \"ndhist object. As in statistics, the skewness is defined as              \\n\"\n        \":math:`Skewness[x] = ( E[x^3] - 3 V[x] E[x] - E[x]^3 ) / \\\\sqrt{V[x]^3}`.\\n\"\n        \"This function generates a projection along the given axis and then       \\n\"\n        \"calculates the skewness.                                                 \\n\"\n        \"If ``None`` is given as axis argument (the default), the skewness        \\n\"\n        \"for all individual axes of the ndhist object is calculated and           \\n\"\n        \"returned as a tuple. But if the dimensionality of the histogram is       \\n\"\n        \"1, a scalar value is returned.                                           \\n\"\n        \"                                                                         \\n\"\n        \".. note:: This function is only defined for ndhist objects with POD      \\n\"\n        \"          type axis values AND POD type weight values.                   \\n\"\n    );\n}\n\n}// namespace stats\n}// namespace ndhist\n", "meta": {"hexsha": "2ac2b8f232153e640c5c939bfdca8503a5c12d30", "size": 1563, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pybindings/stats/skewness.cpp", "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": "src/pybindings/stats/skewness.cpp", "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": "src/pybindings/stats/skewness.cpp", "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": 34.7333333333, "max_line_length": 85, "alphanum_fraction": 0.5118362124, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5087842043764295}}
{"text": "/**\n * @cond ___LICENSE___\n *\n * Copyright (c) 2016-2018 Zefiros Software.\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\n * THE SOFTWARE.\n *\n * @endcond\n */\n#include \"sync/bench/mpiPingpong.h\"\n#include \"sync/bench/partitioning.h\"\n#include \"sync/sync.h\"\n#include \"sync/util/algorithm.h\"\n#include \"sync/util/json.h\"\n\n#include \"bench.h\"\n\n#include \"args/args.h\"\n#include \"preproc/preproc.h\"\n\n#include <armadillo>\n\n#include <numeric>\n\nauto LeastSquares(const size_t h0, const size_t h1, const size_t multiplier, const std::vector<double> &t)\n{\n    /* This function computes the parameters g and l of the\n    linear function T(h)= g*h+l that best fits\n    the data points (h,t[h]) with h0<= h<= h1. */\n\n    /* Compute sums:\n    sumt  =  sum of t[h] over h0<= h<= h1\n    sumth =         t[h]*h\n    nh    =         1\n    sumh  =         h\n    sumhh =         h*h */\n\n    const arma::vec subT = arma::vec(t).rows(h0, h1);\n    const double sumt = arma::sum(subT);\n    const double sumth = arma::sum(subT % SyncLib::Util::ArmaRange(h0, h1)) * multiplier;\n\n    const size_t nh = h1 - h0 + 1;\n    const double sumh = multiplier * (h1 * (h1 + 1.0) - (h0 - 1.0) * h0) / 2;\n    const double sumhh = multiplier * multiplier * (h1 * (h1 + 1) * (2.0 * h1 + 1) - (h0 - 1) * h0 * (2.0 * h0 - 1)) / 6;\n\n    /* Solve    nh*l +  sumh*g =  sumt\n    sumh*l + sumhh*g =  sumth */\n\n    const double a = nh / sumh; // nh<= sumh\n\n    /* subtract a times second eqn from first eqn to obtain g */\n    double g = (sumt - a * sumth) / (sumh - a * sumhh);\n\n    /* use second eqn to obtain l */\n    double l = (sumth - sumhh * g) / sumh;\n\n    return std::make_tuple(g, l);\n}\n\ntemplate <typename tTimer>\nNOINLINE double MeasureR(tTimer &timer, size_t n, arma::vec &y, double alpha, const arma::vec &x, arma::vec &z, double beta,\n                         size_t repetitions)\n{\n    /* Measure time of 2*repetitions DAXPY operations of length n */\n    timer.Tic();\n\n    constexpr size_t rep = 50;\n\n    for (size_t iter = 0; iter < rep * repetitions; ++iter)\n    {\n        for (size_t i = 0; i < n; ++i)\n        {\n            y[i] += alpha * x[i];\n        }\n\n        for (size_t i = 0; i < n; ++i)\n        {\n            z[i] -= beta * x[i];\n        }\n    }\n\n    return timer.Toc() / rep;\n}\n\nstruct BenchReporter\n{\n    static void ReportR(const size_t n, const double minR, const double maxR, const double avR, const double fool)\n    {\n        fmt::print(\"n= {:>5} min= {:>8.3f} max= {:>8.3f} av= {:>8.3f} Mflop/s \"\n                   \"fool={:>7.1f}\\n\",\n                   n, minR, maxR, avR, fool);\n    }\n\n    static void ReportR0()\n    {\n        fmt::print(\"minimum time is 0\\n\");\n    }\n\n    static void ReportRelationH(const size_t h, const double time, const double flops, const bool printH)\n    {\n        if (printH)\n        {\n            fmt::print(\"Time of {:>5}-relation = {:>7.2f} microsec = {:>8.0f} flops\\n\", h, time, flops);\n        }\n    }\n\n    template <typename tT>\n    static void ReportSize()\n    {\n        fmt::print(\"size of {} = {} bytes\\n\", typeid(tT).name(), sizeof(tT));\n    }\n\n    template <typename tH0, typename tH1>\n    static void ReportGL(tH0 h0, tH1 h1, double g, double l)\n    {\n        fmt::print(\"Range h={:>4} to {:>5}: g= {:>7.1f}, l= {:>7.1f}\\n\", h0, h1, g, l);\n    }\n\n    static void ReportBottomLine(const size_t p, const double rDivMega, const double g, const double l)\n    {\n        fmt::print(\"The bottom line for this BSP computer is:\\n\");\n        fmt::print(\"p= {}, r= {:.3f} Mflop/s, g= {:.1f}, l= {:.1f}\\n\", p, rDivMega, g, l);\n    }\n\n    static size_t RequestP(const size_t maxP, const bool restrictP = true)\n    {\n        fmt::print(\"How many processors do you want to use?\\n\");\n        const size_t p = 4;\n        // std::cin>>p;\n\n        if (restrictP && p > maxP)\n        {\n            fmt::print(\"Sorry, your requested {}, but only {} processors available.\\n\", p, maxP);\n            exit(EXIT_FAILURE);\n        }\n\n        return p;\n    }\n};\n\ntemplate <typename tEnv>\nvoid BspBench(tEnv &env, const size_t maxH, const size_t maxN, const size_t repetitions, const size_t batchSize,\n              const std::string &output, const bool printH)\n{\n\n    SyncLib::Util::Timer<> timer;\n    /**** Determine p ****/\n    const size_t p = env.Size();\n    const size_t s = env.Rank();\n\n    typename tEnv::template SendQueue<double> timeQueue(env);\n    typename tEnv::template SharedArray<double> dest(env, 2 * maxH + p);\n    std::vector<double> hTime;\n\n    /**** Determine r ****/\n    double r = 0.0;\n\n    arma::vec x(maxN), y(maxN), z(maxN);\n\n    for (size_t n = 1; n <= maxN; n *= 2)\n    {\n        /* Initialize scalars and vectors */\n        const double alpha = 1.0 / 3.0;\n        const double beta = 4.0 / 9.0;\n\n        for (size_t i = 0; i < n; ++i)\n        {\n            const auto xyz = static_cast<double>(i);\n            z[i] = xyz;\n            y[i] = xyz;\n            x[i] = xyz;\n        }\n\n        double time = MeasureR(timer, n, y, alpha, x, z, beta, repetitions);\n\n        timeQueue.Send(0, time);\n        env.Sync();\n\n        /* Processor 0 determines minimum, maximum, average computing rate */\n        if (s == 0)\n        {\n            std::vector<double> timeCopy = timeQueue.ToVector();\n\n            auto [mintime, maxtime] = SyncLib::Util::MinMax(timeCopy.begin(), timeCopy.end());\n\n            if (mintime > 0.0)\n            {\n                /* Compute r = average computing rate in flop/s */\n                const size_t nflops = 4 * repetitions * n;\n                mintime = nflops / (mintime * std::mega::num);\n                maxtime = nflops / (maxtime * std::mega::num);\n\n                r = static_cast<double>(nflops) / arma::mean(arma::vec(timeCopy));\n\n                BenchReporter::ReportR(n, mintime, maxtime, r / std::mega::num, y[n - 1] + z[n - 1]);\n            }\n            else\n            {\n                BenchReporter::ReportR0();\n            }\n        }\n    }\n\n    /* r is taken as the value at length maxN */\n\n    /**** Determine g and l ****/\n    std::vector<size_t> destproc(maxH), destindex(maxH);\n    std::vector<double> src(maxH), t(maxH + 1);\n\n    typename tEnv::template SendQueue<size_t, double> queue(env);\n\n    for (size_t h = 0; h <= maxH; ++h)\n    {\n        /* Initialize communication pattern */\n        for (size_t i = 0; i < h; ++i)\n        {\n            src[i] = static_cast<double>(i);\n\n            if (p == 1)\n            {\n                destproc[i] = 0;\n                destindex[i] = i;\n            }\n            else\n            {\n                /* destination processor is one of the p-1 others */\n                destproc[i] = (s + 1 + (i % (p - 1))) % p;\n                /* destination index is in my own part of dest */\n                destindex[i] = s + (i / (p - 1)) * p;\n            }\n        }\n\n        /* Measure time of repetitions h-relations */\n        env.Sync();\n        timer.Tic();\n\n        for (size_t iter = 0; iter < repetitions; iter++)\n        {\n            for (size_t i = 0; i < h; ++i)\n            {\n                for (size_t l = 0; l < batchSize; ++l)\n                {\n                    // dest.PutValue(destproc[i], src[i], destindex[i]);\n                    queue.Send(destproc[i], destindex[i], src[i]);\n                    // env.Print(\"Send: {}, {}, {}\\n\", destproc[i], destindex[i], src[i]);\n                }\n            }\n\n            env.Sync();\n\n            for (auto [index, val] : queue)\n            {\n                dest.Value()[index] = val;\n                // env.Print(\"Recv: {}, {}, {}\\n\", s, index, val);\n            }\n        }\n\n        const double time = timer.Toc();\n        hTime.push_back(time * std::mega::num / repetitions);\n\n        /* Compute time of one h-relation */\n        if (s == 0)\n        {\n            // time in flop units\n            t[h] = (time * r) / repetitions;\n            BenchReporter::ReportRelationH(h, (time * std::mega::num) / repetitions, t[h], printH || h == maxH);\n        }\n    }\n\n    if (s == 0)\n    {\n        const auto [g0, l0] = LeastSquares(0, p, batchSize, t);\n        const auto [g, l] = LeastSquares(p, maxH, batchSize, t);\n\n        const double flops = maxH * batchSize * g + l;\n        BenchReporter::ReportRelationH(maxH, flops * std::mega::num / r, flops, true);\n        BenchReporter::ReportSize<double>();\n        BenchReporter::ReportGL(0, \"p\", g0, l0);\n        BenchReporter::ReportGL(\"p\", maxH, g, l);\n        BenchReporter::ReportBottomLine(p, r / std::mega::num, g, l);\n\n        if (!output.empty())\n        {\n            std::ofstream benchResults(output);\n            nlohmann::json dump;\n            dump[\"timings\"] = arma::vec(t);\n            dump[\"r\"] = r;\n            dump[\"g\"] = g;\n            dump[\"l\"] = l;\n            benchResults << dump;\n            benchResults.flush();\n        }\n    }\n}\n\n#ifdef IS_WINDOWS\nvoid Pause(bool pause = true)\n{\n\n    if (pause)\n    {\n        system(\"pause\");\n    }\n}\n#else\nvoid Pause(bool)\n{\n}\n#endif\n\ntemplate <typename tEnv/*, typename... tArgs*/>\nvoid RunBenchmark(Args &parser, tEnv &env /*bool pause, tArgs &&... args*/)\n{\n    Pause(env.Rank() == 0 && parser.GetOption(\"start-paused\"));\n    uint32_t maxH = parser.GetOption(\"h\");\n    uint32_t maxN = parser.GetOption(\"n\");\n    uint32_t niters = parser.GetOption(\"i\");\n    uint32_t batchSize = parser.GetOption(\"b\");\n    uint32_t parts = parser.GetOption(\"parts\");\n    auto outputOption = parser.GetOption(\"o\");\n    std::string output;\n\n    if (outputOption.Count() > 0)\n    {\n        output = outputOption.Get<std::string>();\n    }\n\n    auto printOptions = parser.GetOption(\"print\");\n    bool printH = false;\n\n    if (printOptions.Count() > 0)\n    {\n        std::vector<std::string> prints = printOptions.Get<std::vector<std::string>>();\n\n        for (auto &o : prints)\n        {\n            if (o == \"h\" || o == \"h-relation\")\n            {\n                printH = true;\n            }\n        }\n    }\n\n    // tEnv env(std::forward<tArgs>(args)...);\n\n    if (parts > 1)\n    {\n        const auto &splitBench = [&](tEnv & env0)\n        {\n            size_t partSize = (env0.Size() + parts - 1) / parts;\n            auto &env1 = env0.Split(env0.Rank() / partSize, env0.Rank());\n            BspBench<tEnv>(env1, maxH, maxN, niters, batchSize, output, printH);\n        };\n        env.Run(splitBench);\n    }\n    else\n    {\n        env.Run(BspBench<tEnv>, maxH, maxN, niters, batchSize, output, printH);\n    }\n\n    Pause(env.Rank() == 0 && parser.GetOption(\"exit-paused\"));\n}\n\n#if defined(_DEBUG)\nconstexpr bool IsDebugBuild = true;\n#elif defined(NDEBUG)\nconstexpr bool IsDebugBuild = false;\n#else\nconstexpr bool IsDebugBuild = true;\n#endif\n\ntemplate <typename tEnv>\ndouble InnerProductPut(tEnv &env, std::vector<double> &x, std::vector<double> &y)\n{\n    size_t p = env.Size();\n    size_t s = env.Rank();\n\n    // using shared array with put for partial inner products\n    typename tEnv::template SharedArray<double> partialInnerProducts(env, p);\n\n    double alpha = 0.0;\n\n    for (size_t i = 0, iEnd = x.size(); i < iEnd; ++i)\n    {\n        alpha += x[i] * y[i];\n    }\n\n    for (size_t t = 0; t < p; ++t)\n    {\n        partialInnerProducts.PutValue(t, alpha, s);\n    }\n\n    env.Sync();\n\n    // Sum the partial inner products\n    return std::accumulate(partialInnerProducts.begin(), partialInnerProducts.end(), 0.0);\n}\n\ntemplate <typename tEnv>\ndouble InnerProduct(tEnv &env, std::vector<double> &x, std::vector<double> &y)\n{\n    const size_t p = env.Size();\n\n    // using shared array with put for partial inner products\n    typename tEnv::template SendQueue<double> partialInnerProducts(env);\n\n    double alpha = 0.0;\n\n    for (size_t i = 0, iEnd = x.size(); i < iEnd; ++i)\n    {\n        alpha += x[i] * y[i];\n    }\n\n    for (size_t t = 0; t < p; ++t)\n    {\n        partialInnerProducts.Send(t, alpha);\n    }\n\n    env.Sync();\n\n    // Sum the partial inner products\n    return std::accumulate(partialInnerProducts.begin(), partialInnerProducts.end(), 0.0);\n}\n\ntemplate <typename tEnv>\nvoid BaselProblem(tEnv &env, size_t n)\n{\n    const size_t p = env.Size();\n    const size_t s = env.Rank();\n\n    const size_t nl = (n + p - s - 1) / p;\n    std::vector<double> x(nl);\n\n    for (size_t i = 0; i < nl; ++i)\n    {\n        const size_t iGlob = i * p + s;\n        x[i] = 1.0 / (iGlob + 1);\n    }\n\n    SyncLib::Util::Timer<std::chrono::microseconds> timer;\n\n    // Let everyone start at the same time\n    env.Barrier();\n    timer.Tic();\n\n    double alpha = 0.0;\n\n    for (size_t j = 0; j < 1000; ++j)\n    {\n        alpha = InnerProduct(env, x, x);\n    }\n\n    // Measure the time when everyone is done\n    env.Barrier();\n    const double elapsed = timer.Toc() / 1000;\n\n    printf(\"Processor %zd: solution to the Basel problem \"\n           \"with reciprocals up to 1/%zd^2 is %.6f\\n\",\n           s, n, alpha);\n\n    if (s == 0)\n    {\n        printf(\"This took only %.6lf microseconds.\\n\", elapsed);\n    }\n}\n\n// int main(int argc, char **argv)\n// {\n//     using tEnv = SyncLib::Environments::SharedMemoryBSP;\n//     tEnv env(4);\n//\n//     // n can be requested from the user using your favorite method.\n//     // You can also request if for s=0 inside the function.\n//     size_t n = 1000000;\n//\n//     env.Run(BaselProblem<tEnv>, n);\n//\n//     return 0;\n// }\n\nint main(int argc, char **argv)\n{\n    Args args(\"bench\", \"Edupack benchmark for SyncLib\");\n\n    std::string iterations(IsDebugBuild ? \"100\" : \"1000\");\n\n    args.AddOptions(\n    {\n        {\n            \"start-paused\",\n            \"Whether we want to pause before the benchmark starts\",\n            Option::Boolean(),\n            \"true\",\n            \"false\",\n        },\n        {\n            \"exit-paused\",\n            \"Whether we want to pause before the benchmark exits\",\n            Option::Boolean(),\n            \"true\",\n            \"false\",\n        },\n        {\n            { \"i\", \"iterations\" },\n            \"The number of iterations for each h-relation\",\n            Option::U32(),\n            iterations,\n            iterations,\n        },\n        {\n            { \"h\", \"maximum-h\" },\n            \"The maximum h-relation\",\n            Option::U32(),\n            \"256\",\n            \"256\",\n        },\n        {\n            \"print\",\n            \"Fields to print\",\n            Option::StringList(),\n            {},\n            {},\n        },\n        {\n            { \"n\", \"maximum-n\" },\n            \"The maximum number of DAXPYs for measuring r\",\n            Option::U32(),\n            \"1024\",\n            \"1024\",\n        },\n        {\n            { \"o\", \"output-file\" },\n            \"The file to store the output in\",\n            Option::String(),\n        },\n        {\n            \"parts\",\n            \"The number of parts to split the environment in\",\n            Option::U32(),\n            \"1\",\n            \"1\",\n        },\n    });\n\n    SyncLib::MPI::Comm comm(argc, argv);\n\n    {\n        std::string batchSize = comm.Size() > 1 ? \"8\" : \"1\";\n\n        args.AddOptions(\n        {\n            {\n                { \"b\", \"batch-size\" },\n                \"Size of each communication packet\",\n                Option::U32(),\n                batchSize,\n                batchSize,\n            },\n        });\n    }\n\n    if (comm.Size() > 1)\n    {\n        //         char parsed = false;\n        //\n        //         if (comm.Rank() == 0)\n        //         {\n        //             args.Parse(argc, argv);\n        //             parsed = true;\n        //         }\n        //\n        //         comm.Broadcast(parsed, 0);\n        //\n        //         if (parsed && comm.Rank() != 0)\n        //         {\n        //             args.Parse(argc, argv);\n        //         }\n        //\n        //         // SyncLib::Internal::PinThread(comm.Rank());\n        //\n        //         // const uint32_t parts = args.GetOption(\"parts\");\n        //         //         Pause(comm.Rank() == 0);\n        //         //         comm.Barrier();\n        using tEnv = SyncLib::Environments::DistributedBSP;\n        //         tEnv env(argc, argv);\n        //         env.Split(0, env.Size() - env.Rank());\n        //\n        //         if (parts > 1)\n        //         {\n        //             const size_t partSize = (comm.Size() + parts - 1) / parts;\n        //             auto comm2 = comm.Split(comm.Rank() / partSize, comm.Rank() % partSize);\n        //             RunBenchmark<tEnv>(args, comm2.Rank() == 0, comm2);\n        //         }\n        //         else\n        {\n            tEnv env(comm);\n            args.Parse(argc, argv);\n            RunBenchmark<tEnv>(args, env);\n        }\n    }\n    else\n    {\n        using tEnv = SyncLib::Environments::SharedMemoryBSP;\n        {\n            std::string p = std::to_string(tEnv::MaxSize());\n\n            args.AddOptions(\n            {\n                {\n                    { \"p\", \"processors\" },\n                    \"The number of processors\",\n                    Option::U32(),\n                    p,\n                    p,\n                },\n            });\n        }\n\n        args.Parse(argc, argv);\n        uint32_t p = args.GetOption(\"processors\");\n        tEnv env(p);\n\n        //const uint32_t parts = args.GetOption(\"parts\");\n\n        RunBenchmark<tEnv>(args, env);\n    }\n\n    // fflush(stdout);\n    comm.Barrier();\n\n    return 0;\n}\n", "meta": {"hexsha": "4787a194b0a0e542689275fe055654c45b630b2d", "size": 18194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "edupack/bench/bench.cpp", "max_stars_repo_name": "Zefiros-Software/SyncLib", "max_stars_repo_head_hexsha": "087fa171b339bdbe16a974cd5f85ff4408b679bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "edupack/bench/bench.cpp", "max_issues_repo_name": "Zefiros-Software/SyncLib", "max_issues_repo_head_hexsha": "087fa171b339bdbe16a974cd5f85ff4408b679bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "edupack/bench/bench.cpp", "max_forks_repo_name": "Zefiros-Software/SyncLib", "max_forks_repo_head_hexsha": "087fa171b339bdbe16a974cd5f85ff4408b679bd", "max_forks_repo_licenses": ["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.0338983051, "max_line_length": 124, "alphanum_fraction": 0.5096185556, "num_tokens": 4894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.508784203831142}}
{"text": "// Copyright (C) 2009  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n#include \"tester.h\"\r\n#include <dlib/svm.h>\r\n#include <vector>\r\n#include <sstream>\r\n\r\nnamespace  \r\n{\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n    dlib::logger dlog(\"test.kernel_matrix\");\r\n\r\n\r\n    class kernel_matrix_tester : public tester\r\n    {\r\n        /*!\r\n            WHAT THIS OBJECT REPRESENTS\r\n                This object represents a unit test.  When it is constructed\r\n                it adds itself into the testing framework.\r\n        !*/\r\n    public:\r\n        kernel_matrix_tester (\r\n        ) :\r\n            tester (\r\n                \"test_kernel_matrix\",       // the command line argument name for this test\r\n                \"Run tests on the kernel_matrix functions.\", // the command line argument description\r\n                0                     // the number of command line arguments for this test\r\n            )\r\n        {\r\n        }\r\n\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            print_spinner();\r\n\r\n            typedef matrix<double,0,1> sample_type;\r\n            typedef radial_basis_kernel<sample_type> kernel_type;\r\n            kernel_type kern(0.1);\r\n\r\n            std::vector<sample_type> vect1;\r\n            std::vector<sample_type> vect2;\r\n\r\n            const sample_type samp = randm(4,1);\r\n            sample_type samp2, samp3;\r\n\r\n            vect1.push_back(randm(4,1));\r\n            vect1.push_back(randm(4,1));\r\n            vect1.push_back(randm(4,1));\r\n            vect1.push_back(randm(4,1));\r\n\r\n            vect2.push_back(randm(4,1));\r\n            vect2.push_back(randm(4,1));\r\n            vect2.push_back(randm(4,1));\r\n            vect2.push_back(randm(4,1));\r\n            vect2.push_back(randm(4,1));\r\n\r\n            matrix<double> K;\r\n\r\n            K.set_size(vect1.size(), vect2.size());\r\n            for (long r = 0; r < K.nr(); ++r)\r\n            {\r\n                for (long c = 0; c < K.nc(); ++c)\r\n                {\r\n                    K(r,c) = kern(vect1[r], vect2[c]);\r\n                }\r\n            }\r\n            DLIB_TEST(equal(K, kernel_matrix(kern, vect1, vect2)));\r\n            DLIB_TEST(equal(K, kernel_matrix(kern, mat(vect1), mat(vect2))));\r\n\r\n\r\n            K.set_size(vect2.size(), vect1.size());\r\n            for (long r = 0; r < K.nr(); ++r)\r\n            {\r\n                for (long c = 0; c < K.nc(); ++c)\r\n                {\r\n                    K(r,c) = kern(vect2[r], vect1[c]);\r\n                }\r\n            }\r\n            DLIB_TEST(equal(K, kernel_matrix(kern, vect2, vect1)));\r\n            DLIB_TEST(equal(K, tmp(kernel_matrix(kern, vect2, vect1))));\r\n            DLIB_TEST(equal(K, kernel_matrix(kern, mat(vect2), mat(vect1))));\r\n\r\n\r\n            K.set_size(vect1.size(), vect1.size());\r\n            for (long r = 0; r < K.nr(); ++r)\r\n            {\r\n                for (long c = 0; c < K.nc(); ++c)\r\n                {\r\n                    K(r,c) = kern(vect1[r], vect1[c]);\r\n                }\r\n            }\r\n            DLIB_TEST(equal(K, kernel_matrix(kern, vect1, vect1)));\r\n            DLIB_TEST(equal(K, tmp(kernel_matrix(kern, vect1, vect1))));\r\n            DLIB_TEST(equal(K, kernel_matrix(kern, vect1)));\r\n            DLIB_TEST(equal(K, tmp(kernel_matrix(kern, vect1))));\r\n            DLIB_TEST(equal(K, kernel_matrix(kern, mat(vect1), mat(vect1))));\r\n            DLIB_TEST(equal(K, tmp(kernel_matrix(kern, mat(vect1), mat(vect1)))));\r\n            DLIB_TEST(equal(K, kernel_matrix(kern, mat(vect1))));\r\n            DLIB_TEST(equal(K, tmp(kernel_matrix(kern, mat(vect1)))));\r\n\r\n\r\n            K.set_size(vect1.size(),1);\r\n            for (long r = 0; r < K.nr(); ++r)\r\n            {\r\n                for (long c = 0; c < K.nc(); ++c)\r\n                {\r\n                    K(r,c) = kern(vect1[r], samp);\r\n                }\r\n            }\r\n            DLIB_TEST(equal(K, kernel_matrix(kern, vect1, samp)));\r\n            DLIB_TEST(equal(K, kernel_matrix(kern, mat(vect1), samp)));\r\n\r\n\r\n            K.set_size(1, vect1.size());\r\n            for (long r = 0; r < K.nr(); ++r)\r\n            {\r\n                for (long c = 0; c < K.nc(); ++c)\r\n                {\r\n                    K(r,c) = kern(samp, vect1[c]);\r\n                }\r\n            }\r\n            DLIB_TEST(equal(K, kernel_matrix(kern, samp, vect1)));\r\n            DLIB_TEST(equal(K, kernel_matrix(kern, samp, mat(vect1))));\r\n            DLIB_TEST(equal(K, tmp(kernel_matrix(kern, samp, vect1))));\r\n            DLIB_TEST(equal(K, tmp(kernel_matrix(kern, samp, mat(vect1)))));\r\n\r\n\r\n\r\n            samp2 = samp;\r\n            samp3 = samp;\r\n\r\n            // test the alias detection\r\n            samp2 = kernel_matrix(kern, vect1, samp2);\r\n            DLIB_TEST(equal(samp2, kernel_matrix(kern, vect1, samp)));\r\n\r\n            samp3 = trans(kernel_matrix(kern, samp3, vect2));\r\n            DLIB_TEST(equal(samp3, trans(kernel_matrix(kern, samp, vect2))));\r\n\r\n\r\n            samp2 += kernel_matrix(kern, vect1, samp);\r\n            DLIB_TEST(equal(samp2, 2*kernel_matrix(kern, vect1, samp)));\r\n\r\n            samp3 += trans(kernel_matrix(kern, samp, vect2));\r\n            DLIB_TEST(equal(samp3, 2*trans(kernel_matrix(kern, samp, vect2))));\r\n        }\r\n    };\r\n\r\n    // Create an instance of this object.  Doing this causes this test\r\n    // to be automatically inserted into the testing framework whenever this cpp file\r\n    // is linked into the project.  Note that since we are inside an unnamed-namespace \r\n    // we won't get any linker errors about the symbol a being defined multiple times. \r\n    kernel_matrix_tester a;\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "e017559edaa5f15e9b7576182c6efa700dacb909", "size": 5660, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/kernel_matrix.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": "dlib/test/kernel_matrix.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": "dlib/test/kernel_matrix.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9382716049, "max_line_length": 102, "alphanum_fraction": 0.4992932862, "num_tokens": 1378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5087640963098469}}
{"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: Victor Fragoso (victor.fragoso@mail.wvu.edu)\n\n#include <Eigen/Dense>\n#include \"gtest/gtest.h\"\n\n#include \"theia/math/matrix/gauss_jordan.h\"\n\nnamespace theia {\nusing RowMajorMatrixXd =\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\nTEST(GaussJordan, FullDiagonalizationOnSquaredRowMajorMatrix) {\n  const int kNumRows = 32;\n  RowMajorMatrixXd mat = RowMajorMatrixXd::Random(kNumRows, kNumRows);\n  GaussJordan(&mat);\n  // Trace of matrix must be equals to the number of rows.\n  EXPECT_NEAR(mat.trace(), static_cast<double>(kNumRows), 1e-6);\n  // Verify that the lower triangular part sums to the trace.\n  EXPECT_NEAR(mat.sum(), mat.trace(), 1e-6);\n}\n\nTEST(GaussJordan, FullDiagonalizationOnSquaredColumnMajorMatrix) {\n  const int kNumRows = 32;\n  Eigen::MatrixXd mat = Eigen::MatrixXd::Random(kNumRows, kNumRows);\n  GaussJordan(&mat);\n  // Trace of matrix must be equals to the number of rows.\n  EXPECT_NEAR(mat.trace(), static_cast<double>(kNumRows), 1e-6);\n  // Verify that the lower triangular part sums to the trace.\n  EXPECT_NEAR(mat.sum(), mat.trace(), 1e-6);\n}\n\nTEST(GaussJordan, EliminationOnFatMatrix) {\n  const int kNumRows = 32;\n  const int kNumCols = kNumRows + 4;\n  RowMajorMatrixXd mat = RowMajorMatrixXd::Random(kNumRows, kNumCols);\n  GaussJordan(&mat);\n  // Verify that the left-block (rows, rows) is diagonalized.\n  EXPECT_NEAR(mat.block(0, 0, kNumRows, kNumRows).sum(),\n              mat.block(0, 0, kNumRows, kNumRows).trace(), 1e-6);\n}\n\nTEST(GaussJordan, PartialEliminationOnFatMatrix) {\n  const int kNumRows = 32;\n  const int kNumCols = kNumRows + 4;\n  const int kNumRowsToProcess = kNumRows - 4;\n  const int kLastRowToProcess = kNumRowsToProcess - 1;\n  RowMajorMatrixXd mat = RowMajorMatrixXd::Random(kNumRows, kNumCols);\n  GaussJordan(kLastRowToProcess, &mat);\n  // Verify that the left-block (rows, rows) is diagonalized.\n  EXPECT_NEAR(mat.block(0, 0, kNumRowsToProcess, kNumRowsToProcess).trace(),\n              static_cast<double>(kNumRowsToProcess),\n              1e-6);\n}\n\nTEST(GaussJordan, PartialDiagonalizationOnFatMatrix) {\n  const int kNumRows = 32;\n  const int kNumCols = kNumRows + 4;\n  const int kLastRowToProcess = 2;\n  RowMajorMatrixXd mat = RowMajorMatrixXd::Random(kNumRows, kNumCols);\n  GaussJordan(kNumRows - 1, kLastRowToProcess, &mat);\n  // Verify that the left-block (rows, rows) is partially diagonalized.\n  EXPECT_NEAR(mat.block(kLastRowToProcess, kLastRowToProcess,\n                        kNumRows - kLastRowToProcess,\n                        kNumRows - kLastRowToProcess).sum(),\n              kNumRows - kLastRowToProcess, 1e-6);\n  EXPECT_NEAR(mat.block(kLastRowToProcess, kLastRowToProcess,\n                        kNumRows - kLastRowToProcess,\n                        kNumRows - kLastRowToProcess).sum(),\n              mat.block(kLastRowToProcess, kLastRowToProcess,\n                        kNumRows - kLastRowToProcess,\n                        kNumRows - kLastRowToProcess).trace(),\n              1e-6);\n  EXPECT_NE(mat.block(0, 0, kNumRows, kNumRows).sum(),\n            mat.block(kLastRowToProcess, kLastRowToProcess,\n                      kNumRows - kLastRowToProcess,\n                      kNumRows - kLastRowToProcess).sum());\n}\n\nTEST(GaussJordan, FullDiagonalizationOnLargeSquaredMatrix) {\n  const int kNumRows = 400;\n  const int kNumCols = kNumRows;\n  RowMajorMatrixXd mat = RowMajorMatrixXd::Random(kNumRows, kNumCols);\n  GaussJordan(&mat);\n  EXPECT_NEAR(mat.sum(), mat.trace(), 1e-6);\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "1d675d75bd6b9f2dc8e9002c7aab12e2e3aa31c4", "size": 5257, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/math/matrix/gauss_jordan_test.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/math/matrix/gauss_jordan_test.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/math/matrix/gauss_jordan_test.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": 43.8083333333, "max_line_length": 78, "alphanum_fraction": 0.7120030436, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5087640887009913}}
{"text": "/**\n * @file    testGaussianISAM2.cpp\n * @brief   Unit tests for GaussianISAM2\n * @author  Michael Kaess\n */\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <tests/smallExample.h>\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/sam/BearingRangeFactor.h>\n#include <gtsam/geometry/Point2.h>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/nonlinear/Values.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/ISAM2.h>\n#include <gtsam/nonlinear/Marginals.h>\n#include <gtsam/linear/GaussianBayesNet.h>\n#include <gtsam/linear/GaussianBayesTree.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/inference/Ordering.h>\n#include <gtsam/base/debug.h>\n#include <gtsam/base/TestableAssertions.h>\n#include <gtsam/base/treeTraversal-inst.h>\n#include <boost/assign/list_of.hpp>\n#include <gtsam/base/deprecated/LieScalar.h>\nusing namespace boost::assign;\n#include <boost/range/adaptor/map.hpp>\nnamespace br { using namespace boost::adaptors; using namespace boost::range; }\n\nusing namespace std;\nusing namespace gtsam;\nusing boost::shared_ptr;\n\nstatic const SharedNoiseModel model;\nstatic const LieScalar Zero(0);\n\n//  SETDEBUG(\"ISAM2 update\", true);\n//  SETDEBUG(\"ISAM2 update verbose\", true);\n//  SETDEBUG(\"ISAM2 recalculate\", true);\n\n// Set up parameters\nSharedDiagonal odoNoise = noiseModel::Diagonal::Sigmas((Vector(3) << 0.1, 0.1, M_PI/100.0).finished());\nSharedDiagonal brNoise = noiseModel::Diagonal::Sigmas((Vector(2) << M_PI/100.0, 0.1).finished());\n\nISAM2 createSlamlikeISAM2(\n    boost::optional<Values&> init_values = boost::none,\n    boost::optional<NonlinearFactorGraph&> full_graph = boost::none,\n    const ISAM2Params& params = ISAM2Params(ISAM2GaussNewtonParams(0.001), 0.0, 0, false, true),\n    size_t maxPoses = 10) {\n\n  // These variables will be reused and accumulate factors and values\n  ISAM2 isam(params);\n  Values fullinit;\n  NonlinearFactorGraph fullgraph;\n\n  // i keeps track of the time step\n  size_t i = 0;\n\n  // Add a prior at time 0 and update isam\n  {\n    NonlinearFactorGraph newfactors;\n    newfactors += PriorFactor<Pose2>(0, Pose2(0.0, 0.0, 0.0), odoNoise);\n    fullgraph.push_back(newfactors);\n\n    Values init;\n    init.insert((0), Pose2(0.01, 0.01, 0.01));\n    fullinit.insert((0), Pose2(0.01, 0.01, 0.01));\n\n    isam.update(newfactors, init);\n  }\n\n  if(i > maxPoses)\n    goto done;\n\n  // Add odometry from time 0 to time 5\n  for( ; i<5; ++i) {\n    NonlinearFactorGraph newfactors;\n    newfactors += BetweenFactor<Pose2>(i, i+1, Pose2(1.0, 0.0, 0.0), odoNoise);\n    fullgraph.push_back(newfactors);\n\n    Values init;\n    init.insert((i+1), Pose2(double(i+1)+0.1, -0.1, 0.01));\n    fullinit.insert((i+1), Pose2(double(i+1)+0.1, -0.1, 0.01));\n\n    isam.update(newfactors, init);\n\n    if(i > maxPoses)\n      goto done;\n  }\n\n  if(i > maxPoses)\n    goto done;\n\n  // Add odometry from time 5 to 6 and landmark measurement at time 5\n  {\n    NonlinearFactorGraph newfactors;\n    newfactors += BetweenFactor<Pose2>(i, i+1, Pose2(1.0, 0.0, 0.0), odoNoise);\n    newfactors += BearingRangeFactor<Pose2,Point2>(i, 100, Rot2::fromAngle(M_PI/4.0), 5.0, brNoise);\n    newfactors += BearingRangeFactor<Pose2,Point2>(i, 101, Rot2::fromAngle(-M_PI/4.0), 5.0, brNoise);\n    fullgraph.push_back(newfactors);\n\n    Values init;\n    init.insert((i+1), Pose2(1.01, 0.01, 0.01));\n    init.insert(100, Point2(5.0/sqrt(2.0), 5.0/sqrt(2.0)));\n    init.insert(101, Point2(5.0/sqrt(2.0), -5.0/sqrt(2.0)));\n    fullinit.insert((i+1), Pose2(1.01, 0.01, 0.01));\n    fullinit.insert(100, Point2(5.0/sqrt(2.0), 5.0/sqrt(2.0)));\n    fullinit.insert(101, Point2(5.0/sqrt(2.0), -5.0/sqrt(2.0)));\n\n    isam.update(newfactors, init);\n    ++ i;\n  }\n\n  if(i > maxPoses)\n    goto done;\n\n  // Add odometry from time 6 to time 10\n  for( ; i<10; ++i) {\n    NonlinearFactorGraph newfactors;\n    newfactors += BetweenFactor<Pose2>(i, i+1, Pose2(1.0, 0.0, 0.0), odoNoise);\n    fullgraph.push_back(newfactors);\n\n    Values init;\n    init.insert((i+1), Pose2(double(i+1)+0.1, -0.1, 0.01));\n    fullinit.insert((i+1), Pose2(double(i+1)+0.1, -0.1, 0.01));\n\n    isam.update(newfactors, init);\n\n    if(i > maxPoses)\n      goto done;\n  }\n\n  if(i > maxPoses)\n    goto done;\n\n  // Add odometry from time 10 to 11 and landmark measurement at time 10\n  {\n    NonlinearFactorGraph newfactors;\n    newfactors += BetweenFactor<Pose2>(i, i+1, Pose2(1.0, 0.0, 0.0), odoNoise);\n    newfactors += BearingRangeFactor<Pose2,Point2>(i, 100, Rot2::fromAngle(M_PI/4.0 + M_PI/16.0), 4.5, brNoise);\n    newfactors += BearingRangeFactor<Pose2,Point2>(i, 101, Rot2::fromAngle(-M_PI/4.0 + M_PI/16.0), 4.5, brNoise);\n    fullgraph.push_back(newfactors);\n\n    Values init;\n    init.insert((i+1), Pose2(6.9, 0.1, 0.01));\n    fullinit.insert((i+1), Pose2(6.9, 0.1, 0.01));\n\n    isam.update(newfactors, init);\n    ++ i;\n  }\n\ndone:\n\n  if (full_graph)\n    *full_graph = fullgraph;\n\n  if (init_values)\n    *init_values = fullinit;\n\n  return isam;\n}\n\n/* ************************************************************************* */\n//TEST(ISAM2, CheckRelinearization) {\n//\n//  typedef GaussianISAM2<Values>::Impl Impl;\n//\n//  // Create values where indices 1 and 3 are above the threshold of 0.1\n//  VectorValues values;\n//  values.reserve(4, 10);\n//  values.push_back_preallocated(Vector2(0.09, 0.09));\n//  values.push_back_preallocated(Vector3(0.11, 0.11, 0.09));\n//  values.push_back_preallocated(Vector3(0.09, 0.09, 0.09));\n//  values.push_back_preallocated(Vector2(0.11, 0.11));\n//\n//  // Create a permutation\n//  Permutation permutation(4);\n//  permutation[0] = 2;\n//  permutation[1] = 0;\n//  permutation[2] = 1;\n//  permutation[3] = 3;\n//\n//  Permuted<VectorValues> permuted(permutation, values);\n//\n//  // After permutation, the indices above the threshold are 2 and 2\n//  KeySet expected;\n//  expected.insert(2);\n//  expected.insert(3);\n//\n//  // Indices checked by CheckRelinearization\n//  KeySet actual = Impl::CheckRelinearization(permuted, 0.1);\n//\n//  EXPECT(assert_equal(expected, actual));\n//}\n\n/* ************************************************************************* */\nstruct ConsistencyVisitor\n{\n  bool consistent;\n  const ISAM2& isam;\n  ConsistencyVisitor(const ISAM2& isam) :\n    consistent(true), isam(isam) {}\n  int operator()(const ISAM2::sharedClique& node, int& parentData)\n  {\n    if(find(isam.roots().begin(), isam.roots().end(), node) == isam.roots().end())\n    {\n      if(node->parent_.expired())\n        consistent = false;\n      if(find(node->parent()->children.begin(), node->parent()->children.end(), node) == node->parent()->children.end())\n        consistent = false;\n    }\n    for(Key j: node->conditional()->frontals())\n    {\n      if(isam.nodes().at(j).get() != node.get())\n        consistent = false;\n    }\n    return 0;\n  }\n};\n\n/* ************************************************************************* */\nbool isam_check(const NonlinearFactorGraph& fullgraph, const Values& fullinit, const ISAM2& isam, Test& test, TestResult& result) {\n\n  TestResult& result_ = result;\n  const string name_ = test.getName();\n\n  Values actual = isam.calculateEstimate();\n  Values expected = fullinit.retract(fullgraph.linearize(fullinit)->optimize());\n\n  bool isamEqual = assert_equal(expected, actual);\n\n  // Check information\n  GaussianFactorGraph isamGraph(isam);\n  isamGraph += isam.roots().front()->cachedFactor_;\n  Matrix expectedHessian = fullgraph.linearize(isam.getLinearizationPoint())->augmentedHessian();\n  Matrix actualHessian = isamGraph.augmentedHessian();\n  expectedHessian.bottomRightCorner(1,1) = actualHessian.bottomRightCorner(1,1);\n  bool isamTreeEqual = assert_equal(expectedHessian, actualHessian);\n\n  // Check consistency\n  ConsistencyVisitor visitor(isam);\n  int data; // Unused\n  treeTraversal::DepthFirstForest(isam, data, visitor);\n  bool consistent = visitor.consistent;\n\n  // The following two checks make sure that the cached gradients are maintained and used correctly\n\n  // Check gradient at each node\n  bool nodeGradientsOk = true;\n  typedef ISAM2::sharedClique sharedClique;\n  for(const sharedClique& clique: isam.nodes() | br::map_values) {\n    // Compute expected gradient\n    GaussianFactorGraph jfg;\n    jfg += clique->conditional();\n    VectorValues expectedGradient = jfg.gradientAtZero();\n    // Compare with actual gradients\n    DenseIndex variablePosition = 0;\n    for(GaussianConditional::const_iterator jit = clique->conditional()->begin(); jit != clique->conditional()->end(); ++jit) {\n      const DenseIndex dim = clique->conditional()->getDim(jit);\n      Vector actual = clique->gradientContribution().segment(variablePosition, dim);\n      bool gradOk = assert_equal(expectedGradient[*jit], actual);\n      EXPECT(gradOk);\n      nodeGradientsOk = nodeGradientsOk && gradOk;\n      variablePosition += dim;\n    }\n    bool dimOk = clique->gradientContribution().rows() == variablePosition;\n    EXPECT(dimOk);\n    nodeGradientsOk = nodeGradientsOk && dimOk;\n  }\n\n  // Check gradient\n  VectorValues expectedGradient = GaussianFactorGraph(isam).gradientAtZero();\n  VectorValues expectedGradient2 = GaussianFactorGraph(isam).gradient(VectorValues::Zero(expectedGradient));\n  VectorValues actualGradient = isam.gradientAtZero();\n  bool expectedGradOk = assert_equal(expectedGradient2, expectedGradient);\n  EXPECT(expectedGradOk);\n  bool totalGradOk = assert_equal(expectedGradient, actualGradient);\n  EXPECT(totalGradOk);\n\n  return nodeGradientsOk && expectedGradOk && totalGradOk && isamEqual && isamTreeEqual && consistent;\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, AddFactorsStep1)\n{\n  NonlinearFactorGraph nonlinearFactors;\n  nonlinearFactors += PriorFactor<LieScalar>(10, Zero, model);\n  nonlinearFactors += NonlinearFactor::shared_ptr();\n  nonlinearFactors += PriorFactor<LieScalar>(11, Zero, model);\n\n  NonlinearFactorGraph newFactors;\n  newFactors += PriorFactor<LieScalar>(1, Zero, model);\n  newFactors += PriorFactor<LieScalar>(2, Zero, model);\n\n  NonlinearFactorGraph expectedNonlinearFactors;\n  expectedNonlinearFactors += PriorFactor<LieScalar>(10, Zero, model);\n  expectedNonlinearFactors += PriorFactor<LieScalar>(1, Zero, model);\n  expectedNonlinearFactors += PriorFactor<LieScalar>(11, Zero, model);\n  expectedNonlinearFactors += PriorFactor<LieScalar>(2, Zero, model);\n\n  const FactorIndices expectedNewFactorIndices = list_of(1)(3);\n\n  FactorIndices actualNewFactorIndices;\n\n  ISAM2::Impl::AddFactorsStep1(newFactors, true, nonlinearFactors, actualNewFactorIndices);\n\n  EXPECT(assert_equal(expectedNonlinearFactors, nonlinearFactors));\n  EXPECT(assert_container_equality(expectedNewFactorIndices, actualNewFactorIndices));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, simple)\n{\n  for(size_t i = 0; i < 10; ++i) {\n    // These variables will be reused and accumulate factors and values\n    Values fullinit;\n    NonlinearFactorGraph fullgraph;\n    ISAM2 isam = createSlamlikeISAM2(fullinit, fullgraph, ISAM2Params(ISAM2GaussNewtonParams(0.001), 0.0, 0, false), i);\n\n    // Compare solutions\n    EXPECT(isam_check(fullgraph, fullinit, isam, *this, result_));\n  }\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, slamlike_solution_gaussnewton)\n{\n  // These variables will be reused and accumulate factors and values\n  Values fullinit;\n  NonlinearFactorGraph fullgraph;\n  ISAM2 isam = createSlamlikeISAM2(fullinit, fullgraph, ISAM2Params(ISAM2GaussNewtonParams(0.001), 0.0, 0, false));\n\n  // Compare solutions\n  CHECK(isam_check(fullgraph, fullinit, isam, *this, result_));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, slamlike_solution_dogleg)\n{\n  // These variables will be reused and accumulate factors and values\n  Values fullinit;\n  NonlinearFactorGraph fullgraph;\n  ISAM2 isam = createSlamlikeISAM2(fullinit, fullgraph, ISAM2Params(ISAM2DoglegParams(1.0), 0.0, 0, false));\n\n  // Compare solutions\n  CHECK(isam_check(fullgraph, fullinit, isam, *this, result_));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, slamlike_solution_gaussnewton_qr)\n{\n  // These variables will be reused and accumulate factors and values\n  Values fullinit;\n  NonlinearFactorGraph fullgraph;\n  ISAM2 isam = createSlamlikeISAM2(fullinit, fullgraph, ISAM2Params(ISAM2GaussNewtonParams(0.001), 0.0, 0, false, false, ISAM2Params::QR));\n\n  // Compare solutions\n  CHECK(isam_check(fullgraph, fullinit, isam, *this, result_));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, slamlike_solution_dogleg_qr)\n{\n  // These variables will be reused and accumulate factors and values\n  Values fullinit;\n  NonlinearFactorGraph fullgraph;\n  ISAM2 isam = createSlamlikeISAM2(fullinit, fullgraph, ISAM2Params(ISAM2DoglegParams(1.0), 0.0, 0, false, false, ISAM2Params::QR));\n\n  // Compare solutions\n  CHECK(isam_check(fullgraph, fullinit, isam, *this, result_));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, clone) {\n\n  ISAM2 clone1;\n\n  {\n    ISAM2 isam = createSlamlikeISAM2();\n    clone1 = isam;\n\n    ISAM2 clone2(isam);\n\n    // Modify original isam\n    NonlinearFactorGraph factors;\n    factors += BetweenFactor<Pose2>(0, 10,\n        isam.calculateEstimate<Pose2>(0).between(isam.calculateEstimate<Pose2>(10)), noiseModel::Unit::Create(3));\n    isam.update(factors);\n\n    CHECK(assert_equal(createSlamlikeISAM2(), clone2));\n  }\n\n  // This is to (perhaps unsuccessfully) try to currupt unallocated memory referenced\n  // if the references in the iSAM2 copy point to the old instance which deleted at\n  // the end of the {...} section above.\n  ISAM2 temp = createSlamlikeISAM2();\n\n  CHECK(assert_equal(createSlamlikeISAM2(), clone1));\n  CHECK(assert_equal(clone1, temp));\n\n  // Check clone empty\n  ISAM2 isam;\n  clone1 = isam;\n  CHECK(assert_equal(ISAM2(), clone1));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, removeFactors)\n{\n  // This test builds a graph in the same way as the \"slamlike\" test above, but\n  // then removes the 2nd-to-last landmark measurement\n\n  // These variables will be reused and accumulate factors and values\n  Values fullinit;\n  NonlinearFactorGraph fullgraph;\n  ISAM2 isam = createSlamlikeISAM2(fullinit, fullgraph, ISAM2Params(ISAM2GaussNewtonParams(0.001), 0.0, 0, false));\n\n  // Remove the 2nd measurement on landmark 0 (Key 100)\n  FactorIndices toRemove;\n  toRemove.push_back(12);\n  isam.update(NonlinearFactorGraph(), Values(), toRemove);\n\n  // Remove the factor from the full system\n  fullgraph.remove(12);\n\n  // Compare solutions\n  CHECK(isam_check(fullgraph, fullinit, isam, *this, result_));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, removeVariables)\n{\n  // These variables will be reused and accumulate factors and values\n  Values fullinit;\n  NonlinearFactorGraph fullgraph;\n  ISAM2 isam = createSlamlikeISAM2(fullinit, fullgraph, ISAM2Params(ISAM2GaussNewtonParams(0.001), 0.0, 0, false));\n\n  // Remove the measurement on landmark 0 (Key 100)\n  FactorIndices toRemove;\n  toRemove.push_back(7);\n  toRemove.push_back(14);\n  isam.update(NonlinearFactorGraph(), Values(), toRemove);\n\n  // Remove the factors and variable from the full system\n  fullgraph.remove(7);\n  fullgraph.remove(14);\n  fullinit.erase(100);\n\n  // Compare solutions\n  CHECK(isam_check(fullgraph, fullinit, isam, *this, result_));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, swapFactors)\n{\n  // This test builds a graph in the same way as the \"slamlike\" test above, but\n  // then swaps the 2nd-to-last landmark measurement with a different one\n\n  Values fullinit;\n  NonlinearFactorGraph fullgraph;\n  ISAM2 isam = createSlamlikeISAM2(fullinit, fullgraph);\n\n  // Remove the measurement on landmark 0 and replace with a different one\n  {\n    size_t swap_idx = isam.getFactorsUnsafe().size()-2;\n    FactorIndices toRemove;\n    toRemove.push_back(swap_idx);\n    fullgraph.remove(swap_idx);\n\n    NonlinearFactorGraph swapfactors;\n//    swapfactors += BearingRange<Pose2,Point2>(10, 100, Rot2::fromAngle(M_PI/4.0 + M_PI/16.0), 4.5, brNoise; // original factor\n    swapfactors += BearingRangeFactor<Pose2,Point2>(10, 100, Rot2::fromAngle(M_PI/4.0 + M_PI/16.0), 5.0, brNoise);\n    fullgraph.push_back(swapfactors);\n    isam.update(swapfactors, Values(), toRemove);\n  }\n\n  // Compare solutions\n  EXPECT(assert_equal(fullgraph, NonlinearFactorGraph(isam.getFactorsUnsafe())));\n  EXPECT(isam_check(fullgraph, fullinit, isam, *this, result_));\n\n  // Check gradient at each node\n  typedef ISAM2::sharedClique sharedClique;\n  for(const sharedClique& clique: isam.nodes() | br::map_values) {\n    // Compute expected gradient\n    GaussianFactorGraph jfg;\n    jfg += clique->conditional();\n    VectorValues expectedGradient = jfg.gradientAtZero();\n    // Compare with actual gradients\n    DenseIndex variablePosition = 0;\n    for(GaussianConditional::const_iterator jit = clique->conditional()->begin(); jit != clique->conditional()->end(); ++jit) {\n      const DenseIndex dim = clique->conditional()->getDim(jit);\n      Vector actual = clique->gradientContribution().segment(variablePosition, dim);\n      EXPECT(assert_equal(expectedGradient[*jit], actual));\n      variablePosition += dim;\n    }\n    EXPECT_LONGS_EQUAL((long)clique->gradientContribution().rows(), (long)variablePosition);\n  }\n\n  // Check gradient\n  VectorValues expectedGradient = GaussianFactorGraph(isam).gradientAtZero();\n  VectorValues expectedGradient2 = GaussianFactorGraph(isam).gradient(VectorValues::Zero(expectedGradient));\n  VectorValues actualGradient = isam.gradientAtZero();\n  EXPECT(assert_equal(expectedGradient2, expectedGradient));\n  EXPECT(assert_equal(expectedGradient, actualGradient));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, constrained_ordering)\n{\n  // These variables will be reused and accumulate factors and values\n  ISAM2 isam(ISAM2Params(ISAM2GaussNewtonParams(0.001), 0.0, 0, false));\n  Values fullinit;\n  NonlinearFactorGraph fullgraph;\n\n  // We will constrain x3 and x4 to the end\n  FastMap<Key, int> constrained;\n  constrained.insert(make_pair((3), 1));\n  constrained.insert(make_pair((4), 2));\n\n  // i keeps track of the time step\n  size_t i = 0;\n\n  // Add a prior at time 0 and update isam\n  {\n    NonlinearFactorGraph newfactors;\n    newfactors += PriorFactor<Pose2>(0, Pose2(0.0, 0.0, 0.0), odoNoise);\n    fullgraph.push_back(newfactors);\n\n    Values init;\n    init.insert((0), Pose2(0.01, 0.01, 0.01));\n    fullinit.insert((0), Pose2(0.01, 0.01, 0.01));\n\n    isam.update(newfactors, init);\n  }\n\n  CHECK(isam_check(fullgraph, fullinit, isam, *this, result_));\n\n  // Add odometry from time 0 to time 5\n  for( ; i<5; ++i) {\n    NonlinearFactorGraph newfactors;\n    newfactors += BetweenFactor<Pose2>(i, i+1, Pose2(1.0, 0.0, 0.0), odoNoise);\n    fullgraph.push_back(newfactors);\n\n    Values init;\n    init.insert((i+1), Pose2(double(i+1)+0.1, -0.1, 0.01));\n    fullinit.insert((i+1), Pose2(double(i+1)+0.1, -0.1, 0.01));\n\n    if(i >= 3)\n      isam.update(newfactors, init, FactorIndices(), constrained);\n    else\n      isam.update(newfactors, init);\n  }\n\n  // Add odometry from time 5 to 6 and landmark measurement at time 5\n  {\n    NonlinearFactorGraph newfactors;\n    newfactors += BetweenFactor<Pose2>(i, i+1, Pose2(1.0, 0.0, 0.0), odoNoise);\n    newfactors += BearingRangeFactor<Pose2,Point2>(i, 100, Rot2::fromAngle(M_PI/4.0), 5.0, brNoise);\n    newfactors += BearingRangeFactor<Pose2,Point2>(i, 101, Rot2::fromAngle(-M_PI/4.0), 5.0, brNoise);\n    fullgraph.push_back(newfactors);\n\n    Values init;\n    init.insert((i+1), Pose2(1.01, 0.01, 0.01));\n    init.insert(100, Point2(5.0/sqrt(2.0), 5.0/sqrt(2.0)));\n    init.insert(101, Point2(5.0/sqrt(2.0), -5.0/sqrt(2.0)));\n    fullinit.insert((i+1), Pose2(1.01, 0.01, 0.01));\n    fullinit.insert(100, Point2(5.0/sqrt(2.0), 5.0/sqrt(2.0)));\n    fullinit.insert(101, Point2(5.0/sqrt(2.0), -5.0/sqrt(2.0)));\n\n    isam.update(newfactors, init, FactorIndices(), constrained);\n    ++ i;\n  }\n\n  // Add odometry from time 6 to time 10\n  for( ; i<10; ++i) {\n    NonlinearFactorGraph newfactors;\n    newfactors += BetweenFactor<Pose2>(i, i+1, Pose2(1.0, 0.0, 0.0), odoNoise);\n    fullgraph.push_back(newfactors);\n\n    Values init;\n    init.insert((i+1), Pose2(double(i+1)+0.1, -0.1, 0.01));\n    fullinit.insert((i+1), Pose2(double(i+1)+0.1, -0.1, 0.01));\n\n    isam.update(newfactors, init, FactorIndices(), constrained);\n  }\n\n  // Add odometry from time 10 to 11 and landmark measurement at time 10\n  {\n    NonlinearFactorGraph newfactors;\n    newfactors += BetweenFactor<Pose2>(i, i+1, Pose2(1.0, 0.0, 0.0), odoNoise);\n    newfactors += BearingRangeFactor<Pose2,Point2>(i, 100, Rot2::fromAngle(M_PI/4.0 + M_PI/16.0), 4.5, brNoise);\n    newfactors += BearingRangeFactor<Pose2,Point2>(i, 101, Rot2::fromAngle(-M_PI/4.0 + M_PI/16.0), 4.5, brNoise);\n    fullgraph.push_back(newfactors);\n\n    Values init;\n    init.insert((i+1), Pose2(6.9, 0.1, 0.01));\n    fullinit.insert((i+1), Pose2(6.9, 0.1, 0.01));\n\n    isam.update(newfactors, init, FactorIndices(), constrained);\n    ++ i;\n  }\n\n  // Compare solutions\n  EXPECT(isam_check(fullgraph, fullinit, isam, *this, result_));\n\n  // Check gradient at each node\n  typedef ISAM2::sharedClique sharedClique;\n  for(const sharedClique& clique: isam.nodes() | br::map_values) {\n    // Compute expected gradient\n    GaussianFactorGraph jfg;\n    jfg += clique->conditional();\n    VectorValues expectedGradient = jfg.gradientAtZero();\n    // Compare with actual gradients\n    DenseIndex variablePosition = 0;\n    for(GaussianConditional::const_iterator jit = clique->conditional()->begin(); jit != clique->conditional()->end(); ++jit) {\n      const DenseIndex dim = clique->conditional()->getDim(jit);\n      Vector actual = clique->gradientContribution().segment(variablePosition, dim);\n      EXPECT(assert_equal(expectedGradient[*jit], actual));\n      variablePosition += dim;\n    }\n    LONGS_EQUAL((long)clique->gradientContribution().rows(), (long)variablePosition);\n  }\n\n  // Check gradient\n  VectorValues expectedGradient = GaussianFactorGraph(isam).gradientAtZero();\n  VectorValues expectedGradient2 = GaussianFactorGraph(isam).gradient(VectorValues::Zero(expectedGradient));\n  VectorValues actualGradient = isam.gradientAtZero();\n  EXPECT(assert_equal(expectedGradient2, expectedGradient));\n  EXPECT(assert_equal(expectedGradient, actualGradient));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, slamlike_solution_partial_relinearization_check)\n{\n  // These variables will be reused and accumulate factors and values\n  Values fullinit;\n  NonlinearFactorGraph fullgraph;\n  ISAM2Params params(ISAM2GaussNewtonParams(0.001), 0.0, 0, false);\n  params.enablePartialRelinearizationCheck = true;\n  ISAM2 isam = createSlamlikeISAM2(fullinit, fullgraph, params);\n\n  // Compare solutions\n  CHECK(isam_check(fullgraph, fullinit, isam, *this, result_));\n}\n\nnamespace {\n  bool checkMarginalizeLeaves(ISAM2& isam, const FastList<Key>& leafKeys) {\n    Matrix expectedAugmentedHessian, expected3AugmentedHessian;\n    vector<Key> toKeep;\n    for(Key j: isam.getDelta() | br::map_keys)\n      if(find(leafKeys.begin(), leafKeys.end(), j) == leafKeys.end())\n        toKeep.push_back(j);\n\n    // Calculate expected marginal from iSAM2 tree\n    expectedAugmentedHessian = GaussianFactorGraph(isam).marginal(toKeep, EliminateQR)->augmentedHessian();\n\n    // Calculate expected marginal from cached linear factors\n    //assert(isam.params().cacheLinearizedFactors);\n    //Matrix expected2AugmentedHessian = isam.linearFactors_.marginal(toKeep, EliminateQR)->augmentedHessian();\n\n    // Calculate expected marginal from original nonlinear factors\n    expected3AugmentedHessian = isam.getFactorsUnsafe().linearize(isam.getLinearizationPoint())\n      ->marginal(toKeep, EliminateQR)->augmentedHessian();\n\n    // Do marginalization\n    isam.marginalizeLeaves(leafKeys);\n\n    // Check\n    GaussianFactorGraph actualMarginalGraph(isam);\n    Matrix actualAugmentedHessian = actualMarginalGraph.augmentedHessian();\n    //Matrix actual2AugmentedHessian = linearFactors_.augmentedHessian();\n    Matrix actual3AugmentedHessian = isam.getFactorsUnsafe().linearize(\n      isam.getLinearizationPoint())->augmentedHessian();\n    assert(actualAugmentedHessian.allFinite());\n\n    // Check full marginalization\n    //cout << \"treeEqual\" << endl;\n    bool treeEqual = assert_equal(expectedAugmentedHessian, actualAugmentedHessian, 1e-6);\n    //actualAugmentedHessian.bottomRightCorner(1,1) = expected2AugmentedHessian.bottomRightCorner(1,1); bool linEqual = assert_equal(expected2AugmentedHessian, actualAugmentedHessian, 1e-6);\n    //cout << \"nonlinEqual\" << endl;\n    actualAugmentedHessian.bottomRightCorner(1,1) = expected3AugmentedHessian.bottomRightCorner(1,1); bool nonlinEqual = assert_equal(expected3AugmentedHessian, actualAugmentedHessian, 1e-6);\n    //bool linCorrect = assert_equal(expected3AugmentedHessian, expected2AugmentedHessian, 1e-6);\n    //actual2AugmentedHessian.bottomRightCorner(1,1) = expected3AugmentedHessian.bottomRightCorner(1,1); bool afterLinCorrect = assert_equal(expected3AugmentedHessian, actual2AugmentedHessian, 1e-6);\n    //cout << \"nonlinCorrect\" << endl;\n    bool afterNonlinCorrect = assert_equal(expected3AugmentedHessian, actual3AugmentedHessian, 1e-6);\n\n    bool ok = treeEqual && /*linEqual &&*/ nonlinEqual && /*linCorrect &&*/ /*afterLinCorrect &&*/ afterNonlinCorrect;\n    return ok;\n  }\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, marginalizeLeaves1)\n{\n  ISAM2 isam;\n  NonlinearFactorGraph factors;\n  factors += PriorFactor<LieScalar>(0, Zero, model);\n\n  factors += BetweenFactor<LieScalar>(0, 1, Zero, model);\n  factors += BetweenFactor<LieScalar>(1, 2, Zero, model);\n  factors += BetweenFactor<LieScalar>(0, 2, Zero, model);\n\n  Values values;\n  values.insert(0, Zero);\n  values.insert(1, Zero);\n  values.insert(2, Zero);\n\n  FastMap<Key,int> constrainedKeys;\n  constrainedKeys.insert(make_pair(0,0));\n  constrainedKeys.insert(make_pair(1,1));\n  constrainedKeys.insert(make_pair(2,2));\n\n  isam.update(factors, values, FactorIndices(), constrainedKeys);\n\n  FastList<Key> leafKeys = list_of(0);\n  EXPECT(checkMarginalizeLeaves(isam, leafKeys));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, marginalizeLeaves2)\n{\n  ISAM2 isam;\n\n  NonlinearFactorGraph factors;\n  factors += PriorFactor<LieScalar>(0, Zero, model);\n\n  factors += BetweenFactor<LieScalar>(0, 1, Zero, model);\n  factors += BetweenFactor<LieScalar>(1, 2, Zero, model);\n  factors += BetweenFactor<LieScalar>(0, 2, Zero, model);\n  factors += BetweenFactor<LieScalar>(2, 3, Zero, model);\n\n  Values values;\n  values.insert(0, Zero);\n  values.insert(1, Zero);\n  values.insert(2, Zero);\n  values.insert(3, Zero);\n\n  FastMap<Key,int> constrainedKeys;\n  constrainedKeys.insert(make_pair(0,0));\n  constrainedKeys.insert(make_pair(1,1));\n  constrainedKeys.insert(make_pair(2,2));\n  constrainedKeys.insert(make_pair(3,3));\n\n  isam.update(factors, values, FactorIndices(), constrainedKeys);\n\n  FastList<Key> leafKeys = list_of(0);\n  EXPECT(checkMarginalizeLeaves(isam, leafKeys));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, marginalizeLeaves3)\n{\n  ISAM2 isam;\n\n  NonlinearFactorGraph factors;\n  factors += PriorFactor<LieScalar>(0, Zero, model);\n\n  factors += BetweenFactor<LieScalar>(0, 1, Zero, model);\n  factors += BetweenFactor<LieScalar>(1, 2, Zero, model);\n  factors += BetweenFactor<LieScalar>(0, 2, Zero, model);\n\n  factors += BetweenFactor<LieScalar>(2, 3, Zero, model);\n\n  factors += BetweenFactor<LieScalar>(3, 4, Zero, model);\n  factors += BetweenFactor<LieScalar>(4, 5, Zero, model);\n  factors += BetweenFactor<LieScalar>(3, 5, Zero, model);\n\n  Values values;\n  values.insert(0, Zero);\n  values.insert(1, Zero);\n  values.insert(2, Zero);\n  values.insert(3, Zero);\n  values.insert(4, Zero);\n  values.insert(5, Zero);\n\n  FastMap<Key,int> constrainedKeys;\n  constrainedKeys.insert(make_pair(0,0));\n  constrainedKeys.insert(make_pair(1,1));\n  constrainedKeys.insert(make_pair(2,2));\n  constrainedKeys.insert(make_pair(3,3));\n  constrainedKeys.insert(make_pair(4,4));\n  constrainedKeys.insert(make_pair(5,5));\n\n  isam.update(factors, values, FactorIndices(), constrainedKeys);\n\n  FastList<Key> leafKeys = list_of(0);\n  EXPECT(checkMarginalizeLeaves(isam, leafKeys));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, marginalizeLeaves4)\n{\n  ISAM2 isam;\n\n  NonlinearFactorGraph factors;\n  factors += PriorFactor<LieScalar>(0, Zero, model);\n  factors += BetweenFactor<LieScalar>(0, 2, Zero, model);\n  factors += BetweenFactor<LieScalar>(1, 2, Zero, model);\n\n  Values values;\n  values.insert(0, Zero);\n  values.insert(1, Zero);\n  values.insert(2, Zero);\n\n  FastMap<Key,int> constrainedKeys;\n  constrainedKeys.insert(make_pair(0,0));\n  constrainedKeys.insert(make_pair(1,1));\n  constrainedKeys.insert(make_pair(2,2));\n\n  isam.update(factors, values, FactorIndices(), constrainedKeys);\n\n  FastList<Key> leafKeys = list_of(1);\n  EXPECT(checkMarginalizeLeaves(isam, leafKeys));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, marginalizeLeaves5)\n{\n  // Create isam2\n  ISAM2 isam = createSlamlikeISAM2();\n\n  // Marginalize\n  FastList<Key> marginalizeKeys = list_of(0);\n  EXPECT(checkMarginalizeLeaves(isam, marginalizeKeys));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, marginalCovariance)\n{\n  // Create isam2\n  ISAM2 isam = createSlamlikeISAM2();\n\n  // Check marginal\n  Matrix expected = Marginals(isam.getFactorsUnsafe(), isam.getLinearizationPoint()).marginalCovariance(5);\n  Matrix actual = isam.marginalCovariance(5);\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(ISAM2, calculate_nnz)\n{\n  ISAM2 isam = createSlamlikeISAM2();\n  int expected = 241;\n  int actual = calculate_nnz(isam.roots().front());\n\n  EXPECT_LONGS_EQUAL(expected, actual);\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "f56b458be844f4151187934e81c64b014f736ad2", "size": 30646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testGaussianISAM2.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/testGaussianISAM2.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/testGaussianISAM2.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": 35.8852459016, "max_line_length": 199, "alphanum_fraction": 0.6703648111, "num_tokens": 8569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5087640848965634}}
{"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//[boost_range_reversed\n//` Shows how to use a Boost.Geometry linestring, reversed by Boost.Range adaptor\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/adapted/boost_range/reversed.hpp>\n\nint main()\n{\n    typedef boost::geometry::model::d2::point_xy<int> xy;\n    boost::geometry::model::linestring<xy> line;\n    line.push_back(xy(0, 0));\n    line.push_back(xy(1, 1));\n\n    std::cout\n        << boost::geometry::dsv(line | boost::adaptors::reversed)\n        << std::endl;\n\n    return 0;\n}\n\n//]\n\n//[boost_range_reversed_output\n/*`\nOutput:\n[pre\n((1, 1), (0, 0))\n]\n*/\n//]\n", "meta": {"hexsha": "44e8068c7745985b43d6470753a251de035c00de", "size": 1047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/geometries/adapted/boost_range/reversed.cpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "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": "libs/geometry/doc/src/examples/geometries/adapted/boost_range/reversed.cpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/geometries/adapted/boost_range/reversed.cpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "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": 23.7954545455, "max_line_length": 81, "alphanum_fraction": 0.7029608405, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5087640817166311}}
{"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#ifdef _MSC_VER\r\n# pragma warning (disable : 4100) // unreferenced formal parameters\r\n#endif\r\n\r\n#include <iostream>\r\nusing std::cout;  using std::endl; using std::cerr;\r\n\r\n//[policy_eg_8\r\n\r\n/*`\r\nSuppose we want our own user-defined error handlers rather than the\r\nany of the default ones supplied by the library to be used.\r\nIf we set the policy for a specific type of error to `user_error`\r\nthen the library will call a user-supplied error handler.\r\nThese are forward declared, but not defined in\r\nboost/math/policies/error_handling.hpp like this:\r\n\r\n   namespace boost{ namespace math{ namespace policies{\r\n\r\n   template <class T>\r\n   T user_domain_error(const char* function, const char* message, const T& val);\r\n   template <class T>\r\n   T user_pole_error(const char* function, const char* message, const T& val);\r\n   template <class T>\r\n   T user_overflow_error(const char* function, const char* message, const T& val);\r\n   template <class T>\r\n   T user_underflow_error(const char* function, const char* message, const T& val);\r\n   template <class T>\r\n   T user_denorm_error(const char* function, const char* message, const T& val);\r\n   template <class T>\r\n   T user_evaluation_error(const char* function, const char* message, const T& val);\r\n   template <class T, class TargetType>\r\n   T user_rounding_error(const char* function, const char* message, const T& val, const TargetType& t);\r\n   template <class T>\r\n   T user_indeterminate_result_error(const char* function, const char* message, const T& val);\r\n\r\n   }}} // namespaces\r\n\r\nSo out first job is to include the header we want to use, and then\r\nprovide definitions for our user-defined error handlers that we want to use.\r\nWe only provide our special domain and pole error handlers;\r\nother errors like overflow and underflow use the default.\r\n*/\r\n\r\n#include <boost/math/special_functions.hpp>\r\n\r\nnamespace boost{ namespace math\r\n{\r\n  namespace policies\r\n  {\r\n    template <class T>\r\n    T user_domain_error(const char* function, const char* message, const T& val)\r\n    { // Ignoring function, message and val for this example, perhaps unhelpfully.\r\n       cerr << \"Domain Error!\" << endl;\r\n       return std::numeric_limits<T>::quiet_NaN();\r\n    }\r\n\r\n    template <class T>\r\n    T user_pole_error(const char* function, const char* message, const T& val)\r\n    { // Ignoring function, message and val for this example, perhaps unhelpfully.\r\n       cerr << \"Pole Error!\" << endl;\r\n       return std::numeric_limits<T>::quiet_NaN();\r\n    }\r\n  } // namespace policies\r\n}} // namespace boost{ namespace math\r\n\r\n\r\n/*`\r\nNow we'll need to define a suitable policy that will call these handlers,\r\nand define some forwarding functions that make use of the policy:\r\n*/\r\n\r\nnamespace{\r\n\r\nusing namespace boost::math::policies;\r\n\r\ntypedef policy<\r\n   domain_error<user_error>,\r\n   pole_error<user_error>\r\n> user_error_policy;\r\n\r\nBOOST_MATH_DECLARE_SPECIAL_FUNCTIONS(user_error_policy)\r\n\r\n} // close unnamed namespace\r\n\r\n/*`\r\nWe now have a set of forwarding functions defined in an unnamed namespace\r\nthat all look something like this:\r\n\r\n``\r\ntemplate <class RealType>\r\ninline typename boost::math::tools::promote_args<RT>::type\r\n   tgamma(RT z)\r\n{\r\n   return boost::math::tgamma(z, user_error_policy());\r\n}\r\n``\r\n\r\nSo that when we call `tgamma(z)` we really end up calling\r\n`boost::math::tgamma(z, user_error_policy())`, and any\r\nerrors will get directed to our own error handlers.\r\n*/\r\n\r\nint main()\r\n{\r\n   cout << \"Result of erf_inv(-10) is: \"\r\n      << erf_inv(-10) << endl;\r\n   cout << \"Result of tgamma(-10) is: \"\r\n      << tgamma(-10) << endl;\r\n}\r\n\r\n/*`\r\n\r\nWhich outputs:\r\n\r\n[pre\r\n  Domain Error!\r\n  Pole Error!\r\n  Result of erf_inv(-10) is: 1.#QNAN\r\n  Result of tgamma(-10) is: 1.#QNAN\r\n]\r\n*/\r\n\r\n//] // //[/policy_eg_8]\r\n", "meta": {"hexsha": "ed628efa779353c562df3b9b6ab480fd37a05adc", "size": 4176, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/policy_eg_8.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/policy_eg_8.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/policy_eg_8.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": 31.1641791045, "max_line_length": 104, "alphanum_fraction": 0.6965996169, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5087640751677531}}
{"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//[assign_inverse\n//` Usage of assign_inverse and expand to conveniently determine bounding 3D box of two points\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/point.hpp>\n\nusing namespace boost::geometry;\n\nint main()\n{\n    typedef model::point<float, 3, cs::cartesian> point;\n    typedef model::box<point> box;\n\n    box all;\n    assign_inverse(all);\n    std::cout << dsv(all) << std::endl;\n    expand(all, point(0, 0, 0));\n    expand(all, point(1, 2, 3));\n    std::cout << dsv(all) << std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[assign_inverse_output\n/*`\nOutput:\n[pre\n((3.40282e+038, 3.40282e+038, 3.40282e+038), (-3.40282e+038, -3.40282e+038, -3.40282e+038))\n((0, 0, 0), (1, 2, 3))]\n*/\n//]\n", "meta": {"hexsha": "3390ac1b8c655c4ba0d48a5d8e1a785a30c6f032", "size": 1107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/geometry/doc/src/examples/algorithms/assign_inverse.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/geometry/doc/src/examples/algorithms/assign_inverse.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/geometry/doc/src/examples/algorithms/assign_inverse.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 23.5531914894, "max_line_length": 94, "alphanum_fraction": 0.6802168022, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5087640741077758}}
{"text": "/// \\file inner_product_grad.cc\n/// \\author David Stutz\n/// \\brief Implementation of the gradient of a inner product operation, see\n/// inner_product.cc.\n\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/shape_inference.h\"\n\n#include <sophus/so3.hpp>\n#include <sophus/se3.hpp>\n#include <Eigen/Dense>\n#include <cmath>\n\nusing namespace Sophus;\nusing namespace Eigen;\n\n// the gradients are simply passed as additional arguments as\n// they are available in the Python function for registering the gradient operation.\nREGISTER_OP(\"SE3toMatrixRtGrad\")\n  .Input(\"grad: float32\")\n  .Input(\"se3_vector: float32\")\n  .Output(\"grad_se3: float32\");\n\nnamespace tensorflow{\n\nusing namespace tensorflow;\n\n/// \\brief Implementation of an inner product gradient operation.\n/// Note that this operation is used in Python to register the gradient as\n/// this is not possible in C*+ right now.\n/// \\param context\n/// \\author David Stutz\nclass SE3toMatrixRtGradOp : public OpKernel {\npublic:\n  /// \\brief Constructor.\n  /// \\param context\n  explicit SE3toMatrixRtGradOp(OpKernelConstruction* context) : OpKernel(context) {\n\n  }\n\n  Eigen::Matrix<float,3,3> skew_symmetric(Eigen::Matrix<float,3,1>v)\n  {\n    Eigen::Matrix<float, 3,3>v_cross;\n        v_cross << 0, -v(2,0), v(1,0),\n                   v(2,0), 0, -v(0,0),\n                  -v(1,0), v(0,0), 0;\n\n    return v_cross;\n\n  }\n\n  /// \\brief Compute the inner product gradients.\n  /// \\param context\n  void Compute(OpKernelContext* context) override {\n\n    // output and grad is provided as input\n    DCHECK_EQ(2, context->num_inputs());\n\n    // get the gradient tensor\n    const Tensor& grad = context->input(0);\n\n    // get the original input tensor\n    const Tensor& se3_vector = context->input(1);\n\n    // create input shape (inferred from the additional attribute `n`)\n    TensorShape se3_vector_shape = se3_vector.shape();\n\n    DCHECK_EQ(se3_vector_shape.dim_size(0), grad.shape().dim_size(0));\n\n    // create output tensors\n    Tensor* grad_se3 = NULL;\n    OP_REQUIRES_OK(context, context->allocate_output(0, se3_vector_shape, &grad_se3));\n\n    // get the Eigen tensors for data access\n    auto grad_tensor = grad.tensor<float, 3>();\n    auto se3_vector_tensor = se3_vector.tensor<float,2>();\n    auto grad_se3_tensor = grad_se3->tensor<float,2>();\n\n    for(int b = 0; b < se3_vector_shape.dim_size(0); b++)\n    {\n        auto v1 = se3_vector_tensor(b,0);\n        auto v2 = se3_vector_tensor(b,1);\n        auto v3 = se3_vector_tensor(b,2);\n\n        auto v_mag = sqrt(v1*v1 + v2*v2 + v3*v3);\n\n        Eigen::Matrix<float,3,1>vec;\n        vec<< v1, v2, v3;\n\n        Eigen::Matrix<float,3,3> R = SO3<float>::exp(vec).matrix();\n        Eigen::Matrix<float, 3,3>v_cross = skew_symmetric(vec);\n        Eigen::Matrix<float,3,3> I = Eigen::Matrix<float,3,3>::Identity(3,3);\n\n        Eigen::Matrix<float, 3, 3>v_cross_I_minus_R = v_cross  * (I-R);\n\n        Eigen::Matrix<float,3,1> e_i;\n        e_i << 1, 0, 0;\n\n        Eigen::Matrix<float, 3, 3>dR_dv1 = v1 * v_cross;\n        Eigen::Matrix<float, 3, 3>v_cross_I_minus_R_times_e1 = skew_symmetric(v_cross_I_minus_R * e_i);\n\n        dR_dv1 += v_cross_I_minus_R_times_e1;\n        dR_dv1 *= R;\n        dR_dv1 /= v_mag;\n\n        e_i << 0, 1, 0;\n\n        Eigen::Matrix<float, 3, 3>dR_dv2 = v2 * v_cross;\n        Eigen::Matrix<float, 3, 3>v_cross_I_minus_R_times_e2 = skew_symmetric(v_cross_I_minus_R * e_i);\n\n        dR_dv2 += v_cross_I_minus_R_times_e2;\n        dR_dv2 *= R;\n        dR_dv2 /= v_mag;\n\n        e_i << 0, 0, 1;\n\n        Eigen::Matrix<float, 3, 3>dR_dv3 = v3 * v_cross;\n        Eigen::Matrix<float, 3, 3>v_cross_I_minus_R_times_e3 = skew_symmetric(v_cross_I_minus_R * e_i);\n\n        dR_dv3 += v_cross_I_minus_R_times_e3;\n        dR_dv3 *= R;\n        dR_dv3 /= v_mag;\n\n    }\n\n  }\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"SE3toMatrixRtGrad\").Device(DEVICE_CPU), SE3toMatrixRtGradOp);\n};", "meta": {"hexsha": "3372da93c14a3bd4ef1fbc3a66e695963bb60341", "size": 3901, "ext": "cc", "lang": "C++", "max_stars_repo_path": "deepvo/networks/layers/se3toMatrixRt_grad.cc", "max_stars_repo_name": "msaroufim/deepvo", "max_stars_repo_head_hexsha": "78f7a7add8a8ab99d15adbc4fbdb2baf1d41bec9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-13T08:36:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T08:36:40.000Z", "max_issues_repo_path": "deepvo/networks/layers/se3toMatrixRt_grad.cc", "max_issues_repo_name": "msaroufim/deepvo", "max_issues_repo_head_hexsha": "78f7a7add8a8ab99d15adbc4fbdb2baf1d41bec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deepvo/networks/layers/se3toMatrixRt_grad.cc", "max_forks_repo_name": "msaroufim/deepvo", "max_forks_repo_head_hexsha": "78f7a7add8a8ab99d15adbc4fbdb2baf1d41bec9", "max_forks_repo_licenses": ["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.0076923077, "max_line_length": 103, "alphanum_fraction": 0.6572673673, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5087545575877723}}
{"text": "/**\n * @file Transform.hpp\n * @author bwu\n * @brief Model of transform vector, matrix and quaternion concept\n * @version 0.1\n * @date 2022-02-22\n */\n#ifndef GENERIC_GEOMETRY_TRANSFORM_HPP\n#define GENERIC_GEOMETRY_TRANSFORM_HPP\n#include <boost/qvm/quat_vec_operations.hpp>\n#include <boost/qvm/vec_mat_operations.hpp>\n#include <boost/qvm/quat_operations.hpp>\n#include <boost/qvm/mat_operations.hpp>\n#include <boost/qvm/vec_operations.hpp>\n#include <boost/qvm/vec_traits.hpp>\n#include <boost/qvm/quat.hpp>\n#include <boost/qvm/mat.hpp>\n#include <boost/qvm/vec.hpp>\n#include \"generic/math/Numbers.hpp\"\n#include \"Geometries.hpp\"\n#include \"Vector.hpp\"\nnamespace boost {\nnamespace qvm {\n\nusing namespace generic::geometry;\ntemplate <typename num_type>\nstruct vec_traits<Vector3D<num_type> >\n{\n    static const int dim = 3;\n    using scalar_type = num_type;\n\n    template <int I>\n    static inline scalar_type & write_element(Vector3D<num_type> & vec) { return vec[I]; }\n\n    template <int I>\n    static inline scalar_type read_element(const Vector3D<num_type> & vec) { return vec[I]; }\n\n    static inline scalar_type & write_element_idx(int i, Vector3D<num_type> & vec) { return vec[i]; }\n\n    static inline scalar_type read_element_idx(int i, const Vector3D<num_type> & vec) { return vec[i]; }\n};\n\ntemplate <typename num_type, size_t N>\nstruct vec_traits<VectorN<num_type, N> >\n{\n    static const int dim = static_cast<int>(N);\n    using scalar_type = num_type;\n\n    template <int I>\n    static inline scalar_type & write_element(VectorN<num_type, N> & vec) { return vec[I]; }\n\n    template <int I>\n    static inline scalar_type read_element(const VectorN<num_type, N> & vec) { return vec[I]; }\n\n    static inline scalar_type & write_element_idx(int i, VectorN<num_type, N> & vec) { return vec[i]; }\n\n    static inline scalar_type read_element_idx(int i, const VectorN<num_type, N> & vec) { return vec[i]; }\n};\n}//namespace qvm\n}//namespace boost\n\nnamespace generic {\nnamespace geometry{\n\ntemplate <typename num_type>\nusing Matrix2x2 = boost::qvm::mat<num_type, 2, 2>;\n\ntemplate <typename num_type>\nusing Matrix3x3 = boost::qvm::mat<num_type, 3, 3>;\n\ntemplate <typename num_type>\nusing Matrix4x4 = boost::qvm::mat<num_type, 4, 4>;\n\ntemplate <typename float_t> class Transform2D;\ntemplate <typename float_t> class Transform3D;\ntemplate <typename float_t> class Quaternion;\n\n///@brief makes a 2d shift transform matrix by a vector2d \ntemplate <typename float_t, typename num_type>\ninline Transform2D<float_t> makeShiftTransform2D(const Vector2D<num_type> & shift)\n{\n    Transform2D<float_t> trans;\n    trans(0, 2) = float_t(shift[0]);\n    trans(1, 2) = float_t(shift[1]);\n    return trans;\n}\n\n///@brief makes a 2d rotation transform matrix by radian, unit: rad\ntemplate <typename float_t>\ninline Transform2D<float_t> makeRotateTransform2D(float_t rot)\n{\n    float_t c = std::cos(rot);\n    float_t s = std::sin(rot);\n    Transform2D<float_t> trans;\n    trans(0, 0) = c; trans(0, 1) = -s;\n    trans(1, 0) = s; trans(1, 1) =  c;\n    return trans;\n}\n\n///@brief makes a 2d scale transform matrix by scale factor\ntemplate <typename float_t>\ninline Transform2D<float_t> makeScaleTransform2D(float_t scale)\n{\n    Transform2D<float_t> trans;\n    trans(0, 0) = scale; trans(1,1) = scale;\n    return trans;\n}\n\n///@brief makes a 2d mirror transform matrix by given axis\ntemplate <typename float_t>\ninline Transform2D<float_t> makeMirroredTransform2D(Axis axis)\n{\n    Transform2D<float_t> trans;\n    if(axis == Axis::X) trans(1, 1) *= -1;\n    else if(axis == Axis::Y) trans(0, 0) *= -1;\n    return trans;\n}\n\n///@brief makes a 3d shift transform matrix by a vector2d \ntemplate <typename float_t, typename num_type>\ninline Transform3D<float_t> makeShiftTransform3D(const Vector3D<num_type> & shift)\n{\n    Transform3D<float_t> trans;\n    trans(0, 3) = float_t(shift[0]);\n    trans(1, 3) = float_t(shift[1]);\n    trans(2, 3) = float_t(shift[2]);\n    return trans;\n}\n\n///@brief makes a 3d scale transform matrix by scale factor\ntemplate <typename float_t>\ninline Transform3D<float_t> makeScaleTransform3D(float_t scale)\n{\n    Transform3D<float_t> trans;\n    trans(0, 0) = scale; trans(1,1) = scale; trans(2, 2) = scale;\n    return trans;\n}\n\ntemplate <typename float_t>\nclass Transform2D\n{\n    static_assert(std::is_floating_point<float_t>::value, \"only floating point type support in transform construct!\");\npublic:\n    static const size_t dim = 2;\n    Transform2D();\n    ///@brief constructs a transform2d model by matrix 3x3\n    explicit Transform2D(const Matrix3x3<float_t> & m);\n\n    ///@brief accesses matrix element by row and col index 0-2\n    float_t & operator() (size_t row, size_t col);\n    const float_t & operator() (size_t row, size_t col) const;\n\n    ///@brief inverses the transform matrix, return false if the matrix det = 0\n    bool Inverse();\n\n    ///@brief gets result transform of this * trans\n    Transform2D<float_t> operator * (const Transform2D<float_t> & trans) const;\n    ///@brief gets result transform of trans * this \n    Transform2D<float_t> & Prod(const Transform2D<float_t> & trans);\n    \n    ///@brief gets transformed point of input\n    template <typename num_type>\n    Point2D<num_type> operator * (const Point2D<num_type> & point) const;\n\n    ///@brief gets transformed segment of input\n    template <typename num_type>\n    Segment2D<num_type> operator * (const Segment2D<num_type> & segment) const;\n\n    ///@brief gets transformed triangle of input\n    template <typename num_type>\n    Triangle2D<num_type> operator * (const Triangle2D<num_type> & triangle) const;\n\n    ///@brief gets transformed box of input\n    template <typename num_type>\n    Polygon2D<num_type> operator * (const Box2D<num_type> & box) const;\n\n    ///@brief gets transformed polyline of input\n    template <typename num_type>\n    Polyline2D<num_type> operator * (const Polyline2D<num_type> & polyline) const;\n\n    ///@brief gets transformed polygon of input\n    template <typename num_type>\n    Polygon2D<num_type> operator * (const Polygon2D<num_type> & polygon) const;\n\n    ///@brief gets transformed polygon with holes of input\n    template <typename num_type>\n    PolygonWithHoles2D<num_type> operator * (const PolygonWithHoles2D<num_type> & pwh) const;\n\n    ///@brief accesses internal matrix data\n    Matrix3x3<float_t> & GetMatrix() { return m_matrix; }\n    const Matrix3x3<float_t> & GetMatrix() const { return m_matrix; }\n\n    ///@brief gets matrix elements in array, adapt for OpenGL API\n    void GetCoeffs(float_t coeffs[], bool rowMajor = true);\n\nprivate:\n    Matrix3x3<float_t> m_matrix;\n};\n\ntemplate <typename float_t>\nclass Transform3D\n{\n    static_assert(std::is_floating_point<float_t>::value, \"only floating point type support in transform construct!\");\npublic:\n    static const size_t dim = 3;\n    Transform3D();\n    ///@brief constructs a transform3d model from transform2d\n    explicit Transform3D(const Transform2D<float_t> & trans2d);\n    ///@brief constructs a transform3d model by matrix 4x4\n    explicit Transform3D(const Matrix4x4<float_t> & m);\n\n    ///@brief accesses matrix element by row and col index 0-2\n    float_t & operator() (size_t row, size_t col);\n    const float_t & operator() (size_t row, size_t col) const;\n\n    ///@brief inverses the transform matrix, return false if the matrix det = 0\n    bool Inverse();\n    ///@brief gets transform2d(x, y) from transform3d(x, y, z)\n    Transform2D<float_t> GetTransfrom2D() const;\n\n    ///@brief gets result transform of this * trans\n    Transform3D<float_t> operator * (const Transform3D<float_t> & trans) const;\n    ///@brief gets result transform of trans * this \n    Transform3D<float_t> & Prod(const Transform3D<float_t> & tran);\n\n    ///@brief gets transformed point of input\n    template <typename num_type>\n    Point3D<num_type> operator * (const Point3D<num_type> & point) const;\n\n    ///@brief gets transformed segment of input\n    template <typename num_type>\n    Segment3D<num_type> operator * (const Segment3D<num_type> & segment) const;\n\n    ///@brief gets transformed triangle of input\n    template <typename num_type>\n    Triangle3D<num_type> operator * (const Triangle3D<num_type> & triangle) const;\n\n    ///@brief accesses internal matrix data\n    Matrix4x4<float_t> & GetMatrix() { return m_matrix; }\n    const Matrix4x4<float_t> & GetMatrix() const { return m_matrix; }\n\n    ///@brief gets matrix elements in array, adapt for OpenGL API\n    void GetCoeffs(float_t coeffs[], bool rowMajor = true);\n\nprivate:\n    Matrix4x4<float_t> m_matrix;\n};\n\ntemplate <typename float_t>\nclass Quaternion\n{\n    static_assert(std::is_floating_point<float_t>::value, \"only floating point type support in transform construct!\");\npublic:\n    static const size_t dim = 3;\n    Quaternion();\n    Quaternion(float_t q0, float_t q1, float_t q2, float_t q3);\n    Quaternion(const Vector3D<float_t> & axis, float_t angle);\n    Quaternion(const boost::qvm::quat<float_t> & q);\n\n    ///@brief accesses quaternion element by index 0-3\n    float_t & operator[](size_t dim);\n    const float_t & operator[](size_t dim) const;\n    ///@brief multiples this with q\n    Quaternion<float_t> & operator *= (const Quaternion<float_t> & q);\n    ///@brief gets multiplie result of this * q\n    Quaternion<float_t> operator * (const Quaternion<float_t> & q) const;\n\n    ///@brief performs a rotation around the axis at angle radians\n    void SetAxisAndAngle(const Vector3D<float_t> & axis, float angle);\n    ///@brief gets axis reprented by this quaternion\n    Vector3D<float_t> Axis() const;\n    ///@brief gets angle reprented by this quaternion\n    float_t Angle() const;\n\n    ///@brief multiplicative inverse of this quaternion\n    void Invert();\n    ///@brief megates all the coefficients of this quaternion\n    void Negate();\n    ///@brief normalizes the quaternion oefficients with unit quaternions\n    void Normalize();\n    ///@brief returns the magnitude of this           \n    float_t Mag() const;\n    ///@brief returns the squared magnitude of this\n    float_t MagSqrt() const;\n    Quaternion<float_t> Log() const;\n    Quaternion<float_t> Exp() const;\n    Quaternion<float_t> Inverse() const;\n    Vector3D<float_t> Rotate(const Vector3D<float_t> & vec) const;\n    Vector3D<float_t> InverseRotate(const Vector3D<float_t> & vec) const;\n\n    ///@brief returns dot product of this and q\n    float_t Dot(const Quaternion<float_t> & q) const;\n\n    ///@brief accesses internal quat data\n    boost::qvm::quat<float_t> & q() { return m_q; }\n    const boost::qvm::quat<float_t> & q() const { return m_q; }\n\n    static Quaternion<float_t> LnDif(const Quaternion<float_t> &a, const Quaternion<float_t> & b);\n    static Quaternion<float_t> SquadTangent(const Quaternion<float_t> & before,\n                                            const Quaternion<float_t> & center,\n                                            const Quaternion<float_t> & after);\n    static Quaternion<float_t> Squad(const Quaternion<float_t> & a, const Quaternion<float_t> & tgA,\n                                     const Quaternion<float_t> & b, const Quaternion<float_t> & tgB, float_t t);\n\n    ///@brief returns the result of spherical linear interpolation of the input quat `a`, `b` and interpolation parameter `t`\n    static Quaternion<float_t> Slerp(const Quaternion<float_t> & a, const Quaternion<float_t> & b, float_t t);\n\nprivate:\n    boost::qvm::quat<float_t> m_q;\n};\n\ntemplate <typename float_t>\ninline Transform2D<float_t>::Transform2D()\n{\n    boost::qvm::set_identity(m_matrix);\n}\n\ntemplate <typename float_t>\ninline Transform2D<float_t>::Transform2D(const Matrix3x3<float_t> & m)\n{\n    boost::qvm::assign(m_matrix, m);\n}\n\ntemplate <typename float_t>\ninline float_t & Transform2D<float_t>::operator() (size_t row, size_t col)\n{\n    return m_matrix.a[row][col];\n}\n\ntemplate <typename float_t>\ninline const float_t & Transform2D<float_t>::operator() (size_t row, size_t col) const\n{\n    return m_matrix.a[row][col];\n}\n\ntemplate <typename float_t>\ninline bool Transform2D<float_t>::Inverse()\n{\n    float_t det = boost::qvm::determinant(m_matrix);\n    if(math::EQ(det, float_t(0))) return false;\n    m_matrix = boost::qvm::inverse(m_matrix, det);\n    return true;\n}\n\ntemplate <typename float_t>\ninline Transform2D<float_t> Transform2D<float_t>::operator * (const Transform2D<float_t> & trans) const\n{\n    using namespace boost::qvm;\n    return Transform2D<float_t>(m_matrix * trans.GetMatrix());\n}\n\ntemplate <typename float_t>\ninline Transform2D<float_t> & Transform2D<float_t>::Prod(const Transform2D<float_t> & trans)\n{\n    m_matrix = trans.GetMatrix() * m_matrix;\n    return *this;\n}\n\ntemplate <typename float_t>\ntemplate <typename num_type>\ninline Point2D<num_type> Transform2D<float_t>::operator * (const Point2D<num_type> & point) const\n{\n    Point2D<num_type> res(point);\n    Transform(res, *this);\n    return res;\n}\n\ntemplate <typename float_t>\ntemplate <typename num_type>\ninline Segment2D<num_type> Transform2D<float_t>::operator * (const Segment2D<num_type> & segment) const\n{\n    Segment2D<num_type> res(segment);\n    Transform(res, *this);\n    return res;\n}\n\ntemplate <typename float_t>\ntemplate <typename num_type>\ninline Triangle2D<num_type> Transform2D<float_t>::operator * (const Triangle2D<num_type> & triangle) const\n{\n    Triangle2D<num_type> res(triangle);\n    Transform(res, *this);\n    return res;\n}\n\ntemplate <typename float_t>\ntemplate <typename num_type>\ninline Polygon2D<num_type> Transform2D<float_t>::operator * (const Box2D<num_type> & box) const\n{\n    Point2D<num_type> p[4] = { box[0], {box[1][0], box[0][1]}, box[1], {box[0][0], box[1][1]} };\n    Polygon2D<num_type> res;\n    for(size_t i = 0; i < 4; ++i){\n        Transform(p[i], *this);\n        res << p[i];\n    }\n    return res;\n}\n\ntemplate <typename float_t>\ntemplate <typename num_type>\ninline Polyline2D<num_type> Transform2D<float_t>::operator * (const Polyline2D<num_type> & polyline) const\n{\n    Polyline2D<num_type> res = polyline;\n    Transform(res, *this);\n    return res;  \n}\n\ntemplate <typename float_t>\ntemplate <typename num_type>\ninline Polygon2D<num_type>  Transform2D<float_t>::operator * (const Polygon2D<num_type> & polygon) const\n{\n    Polygon2D<num_type> res(polygon);\n    Transform(res, *this);\n    return res;\n}\n\ntemplate <typename float_t>\ntemplate <typename num_type>\ninline PolygonWithHoles2D<num_type> Transform2D<float_t>::operator * (const PolygonWithHoles2D<num_type> & pwh) const\n{\n    PolygonWithHoles2D<num_type> res(pwh);\n    Transform(res, *this);\n    return res;\n}\n\ntemplate <typename float_t>\ninline void Transform2D<float_t>::GetCoeffs(float_t coeffs[], bool rowMajor)\n{\n    if(rowMajor){\n        for(size_t i = 0; i <= dim; ++i)\n            for(size_t j = 0; j <= dim; ++j)\n                coeffs[(dim + 1) * i + j] = m_matrix.a[i][j];\n    }\n    else{\n        for(size_t i = 0; i <= dim; ++i)\n            for(size_t j = 0; j <= dim; ++j)\n                coeffs[(dim + 1) * i + j] = m_matrix.a[j][i];\n    }\n}\n\n\ntemplate <typename float_t>\ninline Transform3D<float_t>::Transform3D()\n{\n    boost::qvm::set_identity(m_matrix);\n}\n\ntemplate <typename float_t>\ninline Transform3D<float_t>::Transform3D(const Transform2D<float_t> & trans2d)\n{\n    boost::qvm::set_identity(m_matrix);\n    for(size_t i = 0; i < 2; ++i)\n        for(size_t j = 0; j < 2; ++j)\n            m_matrix.a[i][j] = trans2d(i, j);\n    m_matrix.a[0][3] = trans2d(0, 2);\n    m_matrix.a[1][3] = trans2d(1, 2);\n}\n\ntemplate <typename float_t>\ninline Transform3D<float_t>::Transform3D(const Matrix4x4<float_t> & m)\n{\n    boost::qvm::assign(m_matrix, m);\n}\n\ntemplate <typename float_t>\ninline float_t & Transform3D<float_t>::operator() (size_t row, size_t col)\n{\n    return m_matrix.a[row][col];\n}\n\ntemplate <typename float_t>\ninline const float_t & Transform3D<float_t>::operator() (size_t row, size_t col) const\n{\n    return m_matrix.a[row][col];\n}\n\ntemplate <typename float_t>\ninline bool Transform3D<float_t>::Inverse()\n{\n    float_t det = boost::qvm::determinant(m_matrix);\n    if(math::EQ(det, float_t(0))) return false;\n    m_matrix = boost::qvm::inverse(m_matrix, det);\n    return true;\n}\n\ntemplate <typename float_t>\ninline Transform2D<float_t> Transform3D<float_t>::GetTransfrom2D() const\n{\n    Transform2D<float_t> trans;\n    for(size_t i = 0; i < 2; ++i)\n        for(size_t j = 0; j < 2; ++j)\n            trans(i, j) = m_matrix.a[i][j];\n    trans(0, 2) = m_matrix.a[0][3];\n    trans(1, 2) = m_matrix.a[1][3];\n    return trans;\n}\n\ntemplate <typename float_t>\ninline Transform3D<float_t> Transform3D<float_t>::operator * (const Transform3D<float_t> & trans) const\n{\n    using namespace boost::qvm;\n    return Transform3D<float_t>(m_matrix * trans.GetMatrix());\n}\n\ntemplate <typename float_t>\ninline Transform3D<float_t> & Transform3D<float_t>::Prod(const Transform3D<float_t> & trans)\n{\n    m_matrix = trans.GetMatrix() * m_matrix;\n    return *this;\n}\n\ntemplate <typename float_t>\ntemplate <typename num_type>\ninline Point3D<num_type> Transform3D<float_t>::operator * (const Point3D<num_type> & point) const\n{\n    Point3D<num_type> res(point);\n    Transform(res, *this);\n    return res;\n}\n\ntemplate <typename float_t>\ntemplate <typename num_type>\ninline Segment3D<num_type> Transform3D<float_t>::operator * (const Segment3D<num_type> & segment) const\n{\n    Segment3D<num_type> res(segment);\n    Transform(res, *this);\n    return res;\n}\n\ntemplate <typename float_t>\ntemplate <typename num_type>\ninline Triangle3D<num_type> Transform3D<float_t>::operator * (const Triangle3D<num_type> & triangle) const\n{\n    Triangle3D<num_type> res(triangle);\n    Transform(res, *this);\n    return res;\n}\n\ntemplate <typename float_t>\ninline void Transform3D<float_t>::GetCoeffs(float_t coeffs[], bool rowMajor)\n{\n    if(rowMajor){\n        for(size_t i = 0; i <= dim; ++i)\n            for(size_t j = 0; j <= dim; ++j)\n                coeffs[(dim + 1) * i + j] = m_matrix.a[i][j];\n    }\n    else{\n        for(size_t i = 0; i <= dim; ++i)\n            for(size_t j = 0; j <= dim; ++j)\n                coeffs[(dim + 1) * i + j] = m_matrix.a[j][i];    }\n}\n\ntemplate <typename float_t>\ninline Quaternion<float_t>::Quaternion()\n{\n    m_q.a[0] = 1;\n    m_q.a[1] = m_q.a[2] = m_q.a[3] = 0;\n}\n\ntemplate <typename float_t>\ninline Quaternion<float_t>::Quaternion(float_t q0, float_t q1, float_t q2, float_t q3)\n{\n    m_q.a[0] = q0;\n    m_q.a[1] = q1; m_q.a[2] = q2; m_q.a[3] = q3;\n}\n\ntemplate <typename float_t>\ninline Quaternion<float_t>::Quaternion(const Vector3D<float_t> & axis, float_t angle)\n{\n    SetAxisAndAngle(axis, angle);\n}\n\ntemplate <typename float_t>\ninline Quaternion<float_t>::Quaternion(const boost::qvm::quat<float_t> & q)\n{\n    boost::qvm::assign(m_q, q);\n}\n\ntemplate <typename float_t>\ninline float_t & Quaternion<float_t>::operator[](size_t dim)\n{\n    return m_q.a[dim];\n}\n\ntemplate <typename float_t>\ninline const float_t & Quaternion<float_t>::operator[](size_t dim) const\n{\n    return m_q.a[dim];\n}\n\ntemplate <typename float_t>\ninline Quaternion<float_t> & Quaternion<float_t>::operator *= (const Quaternion<float_t> & q)\n{\n    *this = (*this) * q;\n    return *this;\n}\n\ntemplate <typename float_t>\ninline Quaternion<float_t> Quaternion<float_t>::operator * (const Quaternion<float_t> & q) const\n{\n    return Quaternion<float_t>(m_q * q.q());\n}\n\ntemplate <typename float_t>\ninline void Quaternion<float_t>::SetAxisAndAngle(const Vector3D<float_t> & axis, float angle)\n{\n    boost::qvm::set_rot(m_q, axis, angle);\n}\n\ntemplate <typename float_t>\ninline Vector3D<float_t> Quaternion<float_t>::Axis() const\n{\n    Vector3D<float_t> res(m_q.a[1], m_q.a[2], m_q.a[3]);\n    float_t sinus = res.Norm2();\n    if(sinus > std::numeric_limits<float_t>::epsilon()) res /= sinus;\n    return math::LE(std::acos(m_q.a[0]), float_t(math::pi_half)) ? res : -res;\n}\n\ntemplate <typename float_t>\nfloat_t Quaternion<float_t>::Angle() const\n{\n    float_t angle = 2.0 * std::acos(m_q.a[0]);\n    return math::LE(angle, float_t(math::pi)) ? angle : math::pi_2 - angle;\n}\n\ntemplate <typename float_t>\ninline void Quaternion<float_t>::Invert()\n{\n    boost::qvm::assign(m_q, boost::qvm::inverse(m_q));\n}\n\ntemplate <typename float_t>\ninline void Quaternion<float_t>::Negate()\n{\n    Invert();\n    m_q.a[0] = -m_q.a[0];\n}\n\ntemplate <typename float_t>\ninline void Quaternion<float_t>::Normalize()\n{\n    boost::qvm::normalize(m_q);\n}\n\ntemplate <typename float_t>\ninline float_t Quaternion<float_t>::Mag() const\n{\n    return boost::qvm::mag(m_q);\n}\n\ntemplate <typename float_t>\ninline float_t Quaternion<float_t>::MagSqrt() const\n{\n    return boost::qvm::mag_sqr(m_q);\n}\n\ntemplate <typename float_t>\ninline Quaternion<float_t> Quaternion<float_t>::Log() const\n{\n    float_t len = std::sqrt(m_q.a[1] * m_q.a[1] + m_q.a[2] * m_q.a[2] + m_q.a[3] * m_q.a[3]);\n    if(len < std::numeric_limits<float_t>::epsilon())\n        return Quaternion<float_t>(0, m_q.a[1], m_q.a[2], m_q.a[3]);\n    else{\n        float_t coef = std::acos(m_q.a[0]) / len;\n        return Quaternion<float_t>(0, coef * m_q.a[1], coef * m_q.a[2], coef * m_q.a[3]);\n    }\n}\n\ntemplate <typename float_t>\ninline Quaternion<float_t> Quaternion<float_t>::Exp() const\n{\n    float_t theta = std::sqrt(m_q.a[1] * m_q.a[1] + m_q.a[2] * m_q.a[2] + m_q.a[3] * m_q.a[3]);\n    if(theta < std::numeric_limits<float_t>::epsilon())\n        return Quaternion<float_t>(std::cos(theta), m_q.a[1], m_q.a[2], m_q.a[3]);\n    else{\n        float_t coef = std::sin(theta) / theta;\n        return Quaternion<float_t>(std::cos(theta), coef * m_q.a[1], coef * m_q.a[2], coef * m_q.a[3]);\n    }\n}\n\ntemplate <typename float_t>\ninline Quaternion<float_t> Quaternion<float_t>::Inverse() const\n{\n    return Quaternion<float_t>(boost::qvm::inverse(m_q));\n}\n\ntemplate <typename float_t>\ninline Vector3D<float_t> Quaternion<float_t>::Rotate(const Vector3D<float_t> & vec) const\n{\n   using namespace boost::qvm;\n   return m_q * vec;\n}\n\ntemplate <typename float_t>\ninline Vector3D<float_t> Quaternion<float_t>::InverseRotate(const Vector3D<float_t> & vec) const\n{\n    return Inverse().Rotate(vec);\n}\n\ntemplate <typename float_t>\ninline float_t Quaternion<float_t>::Dot(const Quaternion<float_t> & q) const\n{\n    return boost::qvm::dot(m_q, q.q());\n}\n\ntemplate <typename float_t>\ninline Quaternion<float_t> Quaternion<float_t>::LnDif(const Quaternion<float_t> &a, const Quaternion<float_t> & b)\n{\n    auto dif = a.Inverse() * b;\n    dif.Normalize();\n    return dif.Log();\n}\n\ntemplate <typename float_t>\ninline Quaternion<float_t> Quaternion<float_t>::SquadTangent(const Quaternion<float_t> & before,\n                                                                const Quaternion<float_t> & center,\n                                                                    const Quaternion<float_t> & after)\n{\n    auto l1 = LnDif(center, before);\n    auto l2 = LnDif(center, after);\n    Quaternion<float_t> e;\n    for(size_t i = 0; i < 4; ++i)\n        e[i] = -0.25 * (l1[i] + l2[2]);\n    e = center * e.Exp();\n    return e;\n}\n\ntemplate <typename float_t>\ninline Quaternion<float_t> Quaternion<float_t>::Squad(const Quaternion<float_t> & a, const Quaternion<float_t> & tgA,\n                                                        const Quaternion<float_t> & b, const Quaternion<float_t> & tgB, float_t t)\n{\n    auto ab = Slerp(a, b, t);\n    auto tg = Slerp(tgA, tgB, t);\n    return Slerp(ab, tg, 2.0 * t * (1.0 - t));\n}\n\ntemplate <typename float_t>\ninline Quaternion<float_t> Quaternion<float_t>::Slerp(const Quaternion<float_t> & a, const Quaternion<float_t> & b, float_t t)\n{\n    using namespace boost::qvm;\n    return Quaternion<float_t>(slerp(a.q(), b.q(), t));\n}\n\n///@brief transforms the point by the transform matrix\ntemplate <typename num_type, typename float_t>\ninline void Transform(Point2D<num_type> & point, const Transform2D<float_t> & trans)\n{\n    VectorN<float_t, 3> vec = trans.GetMatrix() * VectorN<float_t, 3>(point[0], point[1], float_t(1));\n    point = Point2D<num_type>(vec[0], vec[1]);\n}\n\n///@brief transforms the segment by the transform matrix\ntemplate <typename num_type, typename float_t>\ninline void Transform(Segment2D<num_type> & segment, const Transform2D<float_t> & trans)\n{\n    Transform(segment[0], trans);\n    Transform(segment[1], trans);\n}\n\n///@brief transforms the triangle by the transform matrix\ntemplate <typename num_type, typename float_t>\ninline void Transform(Triangle2D<num_type> & triangle, const Transform2D<float_t> & trans)\n{\n    Transform(triangle[0], trans);\n    Transform(triangle[1], trans);\n    Transform(triangle[2], trans);\n}\n\n///@brief transforms the polyline by the transform matrix\ntemplate <typename num_type, typename float_t>\ninline void Transform(Polyline2D<num_type> & polyline, const Transform2D<float_t> & trans)\n{\n    for(auto & point : polyline)\n        Transform(point, trans);\n}\n\n///@brief transforms the polygon by the transform matrix\ntemplate <typename num_type, typename float_t>\ninline void Transform(Polygon2D<num_type> & polygon, const Transform2D<float_t> & trans)\n{\n    for(auto iter = polygon.Begin(); iter != polygon.End(); ++iter)\n        Transform(*iter, trans);\n}\n\n///@brief transforms the polygon with holes by the transform matrix\ntemplate <typename num_type, typename float_t>\ninline void Transform(PolygonWithHoles2D<num_type> & pwh, const Transform2D<float_t> & trans)\n{\n    Transform(pwh.outline, trans);\n    auto iter = pwh.BeginHoles();\n    for(; iter != pwh.EndHoles(); ++iter)\n        Transform(*iter, trans);\n}\n\n///@brief transforms the point by the transform matrix\ntemplate <typename num_type, typename float_t>\ninline void Transform(Point3D<num_type> & point, const Transform3D<float_t> & trans)\n{\n    VectorN<float_t, 4> vec(trans.GetMatrix() * VectorN<float_t, 4>(point[0], point[1], point[2], float_t(1)));\n    point = Point3D<num_type>(vec[0], vec[1], vec[2]);\n}\n\n///@brief transforms the segment by the transform matrix\ntemplate <typename num_type, typename float_t>\ninline void Transform(Segment3D<num_type> & segment, const Transform3D<float_t> & trans)\n{\n    Transform(segment[0], trans);\n    Transform(segment[1], trans);\n}\n\n///@brief transforms the triangle by the transform matrix\ntemplate <typename num_type, typename float_t>\ninline void Transform(Triangle3D<num_type> & triangle, const Transform3D<float_t> & trans)\n{\n    Transform(triangle[0], trans);\n    Transform(triangle[1], trans);\n    Transform(triangle[2], trans);\n}\n\n///@brief transfroms a collection of geometries by the transform matrix\ntemplate <typename geometry_t, typename iterator, typename transform_t, \n          typename std::enable_if<geometry_t::dim == transform_t::dim && std::is_same<geometry_t,\n          typename std::iterator_traits<iterator>::value_type>::value, bool>::type = true>\ninline void Transform(iterator begin, iterator end, const transform_t & trans)\n{\n    for(auto iter = begin; iter != end; ++iter){\n        geometry_t & geom = *iter;\n        Transform(geom, trans);\n    }\n}\n}//namespace geometry\n}//namespace generic\n#endif//GENERIC_GEOMETRY_TRANSFORM_HPP\n", "meta": {"hexsha": "8261c495963e26dd8b21433e08beed5f9335ce8e", "size": 26946, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometry/Transform.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": "geometry/Transform.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": "geometry/Transform.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": 32.309352518, "max_line_length": 130, "alphanum_fraction": 0.6872263045, "num_tokens": 7310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5087545521958119}}
{"text": "#include <boost/random/geometric_distribution.hpp>\n", "meta": {"hexsha": "0a5e609dae1dc24a9d28598580eef0720af21eea", "size": 51, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_geometric_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_geometric_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_geometric_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.5, "max_line_length": 50, "alphanum_fraction": 0.8431372549, "num_tokens": 9, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5087545468038515}}
{"text": "//Authors: Dario Cattaruzza, Alessandro Abate, Peter Schrammel, Daniel Kroening\n//University of Oxford 2016\n//This code is supplied under the BSD license agreement (see license.txt)\n\n#include <math.h>\n\n#include <Eigen/Eigenvalues>\n\n#include <boost/timer.hpp>\n\n#include \"AbstractMatrix.h\"\n\nnamespace abstract{\n\n/// Constructs an empty buffer\ntemplate <class scalar>\nAbstractMatrix<scalar>::AbstractMatrix(int dimension) : AccelMatrix<scalar>(dimension),\n  //m_roundDimension(dimension),\n  m_abstractDynamics(dimension),\n  m_abstractInputDynamics(dimension),\n  m_abstractRoundDynamics(dimension)\n  {\n    m_abstractDynamics.setName(\"Abstract Dynamics\");\n    m_abstractRoundDynamics.setName(\"Round Dynamics\");\n  }\n\n/// Changes the default dimension of the system\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::changeDimensions(const int dimension)\n{\n  AccelMatrix<scalar>::changeDimensions(dimension);\n  m_abstractDynamics.changeDimension(dimension);\n  m_abstractInputDynamics.changeDimension(dimension);\n  m_abstractRoundDynamics.changeDimension(dimension);\n}\n\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::swapValues(scalar &low,scalar &high)\n{\n  scalar temp=low;\n  low=high;\n  high=temp;\n}\n\ntemplate <class scalar>\ninline void AbstractMatrix<scalar>::checkRange(const int row,const powerS iteration,const scalar mag,scalar &min,scalar &max)\n{\n  if (func::isPositive(min-max)) {\n    scalar temp=min;\n    min=max;\n    max=temp;\n  }\n  if ((m_zeniths[row]>0) && (m_zeniths[row]<=iteration)) {\n    scalar mid=condPow(mag,m_zeniths[row],row);\n    if (func::isPositive(mid-max)) max=mid;\n    if (m_zeniths[row]<iteration) {\n      mid=condPow(mag,m_zeniths[row]+1,row);\n      if (func::toLower(mid)>func::toUpper(max)) max=mid;\n    }\n  }\n  if (m_freq[row]>0) {\n    if (m_freq[row]<=iteration) {\n    }\n    else if (row>m_dimension) {\n      if (func::toUpper(min)<-func::toLower(max)) min=-max;\n      else max=-min;\n    }\n  }\n}\n\ntemplate <class scalar>\ntypename JordanMatrix<scalar>::complexS AbstractMatrix<scalar>::condPow(const complexS &coef,const powerS n,int row)\n{\n  if (row>=m_dimension) {\n    if (m_inputType==eParametricInputs) row-=m_dimension;\n    else {\n      scalar mag=ms_one-func::pow(func::norm2(coef),n);\n      if (func::isPositive(mag)) {\n        return complexS(mag*this->m_foldedBinomialMultipliers.coeff(row-m_dimension),0);\n      }\n    }\n    if (m_jordanIndex[row]==0) {\n      if (func::isZero(func::norm2(coef-ms_complexOne))) return complexS(n,0);\n      return this->ms_complexOne-func::c_pow(coef,n);\n    }\n    if (n<m_jordanIndex[row]) return complexS(0,0);\n    if (func::isZero(func::norm2(coef-ms_complexOne))) {\n      if (n<=m_jordanIndex[row]) return complexS(0,0);\n      complexS mult(binomial(n,m_jordanIndex[row]+1),0);\n      return mult;\n    }\n    complexS mult(binomial(n,m_jordanIndex[row]),0);\n    return -mult*func::c_pow(coef,n-m_jordanIndex[row]);\n  }\n  if (m_jordanIndex[row]==0) {\n    if (n==1) return coef;\n    return func::c_pow(coef,n);\n  }\n  if (n<m_jordanIndex[row]) return complexS(0,0);\n  complexS mult(binomial(n,m_jordanIndex[row]),0);\n  return mult*func::c_pow(coef,n-m_jordanIndex[row]);\n}\n\ntemplate <class scalar>\nscalar AbstractMatrix<scalar>::condPow(const scalar &coef,const powerS n,int row)\n{\n  if (row>=m_dimension) {\n    if (m_inputType==eParametricInputs) row-=m_dimension;\n    else {\n      scalar mag=ms_one-func::pow(coef,n);\n      if (func::isPositive(mag)) {\n        return mag*this->m_foldedBinomialMultipliers.coeff(row-m_dimension);\n      }\n    }\n    if (m_jordanIndex[row]==0) {\n      if (abs(coef-ms_one)<m_zero) return scalar(n);\n      return ms_one-func::pow(coef,n);\n    }\n    if (n<m_jordanIndex[row])  return 0;\n    if (abs(coef-ms_one)<m_zero) {\n      if (n<=m_jordanIndex[row])  return 0;\n      return binomial(n,m_jordanIndex[row]+1);\n    }\n    return -binomial(n,m_jordanIndex[row])*func::pow(coef,n-m_jordanIndex[row]);\n  }\n\n  if (m_jordanIndex[row]==0) return func::pow(coef,n);\n  if (n<m_jordanIndex[row])  return 0;\n  return binomial(n,m_jordanIndex[row])*func::pow(coef,n-m_jordanIndex[row]);\n}\n\ntemplate <class scalar>\nscalar AbstractMatrix<scalar>::diffPow(const scalar &coef,const powerS n,int row)\n{\n  if (row>=m_dimension) {\n    if (m_inputType==eParametricInputs) row-=m_dimension;\n    else {\n      scalar mag=ms_one-func::pow(coef,n);\n      if (func::isPositive(mag)) {\n        mag=func::pow(coef,n)-func::pow(coef,n+1);\n        return mag*this->m_foldedBinomialMultipliers.coeff(row-m_dimension);\n      }\n    }\n    if (m_jordanIndex[row]==0) {\n      if (abs(coef-ms_one)<m_zero) return ms_one;\n      return func::pow(coef,n)-func::pow(coef,n+1);\n    }\n    if (n<m_jordanIndex[row])  return 0;\n    if (abs(coef-ms_one)<m_zero) {\n      if (n<m_jordanIndex[row])  return 0;\n      return binomial(n,m_jordanIndex[row]);\n    }\n    return (binomial(n,m_jordanIndex[row])-binomial(n+1,m_jordanIndex[row])*coef)*func::pow(coef,n-m_jordanIndex[row]);\n  }\n  if (m_jordanIndex[row]==0) return (coef-ms_one)*func::pow(coef,n);\n  if (n<m_jordanIndex[row])  return 0;\n  return (binomial(n+1,m_jordanIndex[row])*coef-binomial(n,m_jordanIndex[row]))*func::pow(coef,n-m_jordanIndex[row]);\n}\n\n/// Calculates the expected iteration of coefficient to obtain value\ntemplate <class scalar>\ntypename AbstractMatrix<scalar>::powerS AbstractMatrix<scalar>::condLog(const refScalar &coef,refScalar value,int row,powerS &range)\n{\n  range=0;\n  if (row>=m_dimension) {\n    if (m_inputType==eParametricInputs) row-=m_dimension;\n    else {\n      if (func::isPositive(value)) value/=func::toCentre(this->m_foldedBinomialMultipliers.coeff(row-m_dimension));\n      value=func::ms_1-value;\n      if (func::isNegative(value)) return 0;\n      return func::toInt(func::log(coef,value));\n    }\n    if (m_jordanIndex[row]==0) {\n      if (abs(coef-ms_one)<m_zero) return func::toInt(value);\n      value=func::ms_1-value;\n      if (func::isNegative(value)) return 0;\n      return func::toInt(func::log(coef,value));\n    }\n    range=m_jordanIndex[row]-1;\n    if (func::isZero(value)) return 1;\n    if (abs(coef-ms_one)<m_zero) {\n      for (int i=2;i<=m_jordanIndex[row]+1;i++) value*=i;\n      refScalar expected=pow(value,1/m_jordanIndex[row]+1);\n      return func::toInt(expected);\n    }\n    value=-value;\n    return binomialCondLog(coef,value,row,range);\n  }\n  if (m_jordanIndex[row]==0) return func::toInt(func::log(coef,value));\n  range=m_jordanIndex[row]-1;\n  if (func::isZero(value)) return 1;\n  return binomialCondLog(coef,value,row,range);\n}\n\n/// Calculates the expected iteration of coefficient to obtain value for a jordan diagonal\ntemplate <class scalar>\ntypename AbstractMatrix<scalar>::powerS AbstractMatrix<scalar>::binomialCondLog(const refScalar &coef,refScalar value,int row,powerS &range)\n{\n  for (int i=2;i<=m_jordanIndex[row];i++) value*=i;\n  value/=func::pow(coef,m_jordanIndex[row]);\n  powerS low,high;\n  if (coef>func::ms_1) {\n    high=func::toInt(func::log(coef,value));\n    refScalar bin=func::toCentre(binomial(high,m_jordanIndex[row]));\n    low=func::toInt(func::log(coef,value/bin));\n  }\n  else {\n    low=func::toInt(pow(value,1/m_jordanIndex[row]));\n    refScalar bin=func::toCentre(binomial(low,m_jordanIndex[row]));\n    high=func::toInt(func::log(coef,value/bin));\n  }\n  range=high-low;\n  return low;\n}\n\n\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::fillDirection(const int row,const scalar &min,const scalar &max)\n{\n  m_directions.coeffRef(row,m_pos)=1;\n  m_supports.coeffRef(m_pos++,0)=max;\n  m_directions.coeffRef(row,m_pos)=-1;\n  m_supports.coeffRef(m_pos++,0)=-min;\n}\n\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::fillDirections(const int row1,const int row2,const scalar &dir1,const scalar &dir2,const scalar &min,const scalar &max)\n{\n  m_supports.coeffRef(m_pos,0)=-min;\n  m_directions.coeffRef(row1,m_pos)=-dir1;\n  m_directions.coeffRef(row2,m_pos++)=-dir2;\n  m_supports.coeffRef(m_pos,0)=max;\n  m_directions.coeffRef(row1,m_pos)=dir1;\n  m_directions.coeffRef(row2,m_pos++)=dir2;\n}\n\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::fillConjugateSupport(const int row1,const int row2,const scalar &angle,const scalar &max)\n{\n  m_directions.coeffRef(row1,m_pos)=func::cosine(angle);\n  m_directions.coeffRef(row2,m_pos)=func::sine(angle);\n  m_supports.coeffRef(m_pos++)=max;\n}\n\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::fillSupportFromPoints(const int row1,const int row2,const scalar &x1,const scalar &y1,const scalar &x2,const scalar &y2,const scalar &xRef,const scalar &yRef)\n{\n  scalar angle=func::invtan(y2-y1,x2-x1)+func::const_pi(this->ms_half);\n  scalar max=y1*func::sine(angle)+x1*func::cosine(angle);\n  scalar out=yRef*func::sine(angle)+xRef*func::cosine(angle);\n  out-=max;\n  if (func::isPositive(out)) {\n    angle+=func::const_pi(ms_one);\n    max=-max;\n  }\n  fillConjugateSupport(row1,row2,angle,max);\n}\n\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::fillTangentSupport(const int row1,const int row2,const scalar &mag1,const scalar &mag2,powerS iter)\n{\n  scalar angle=func::const_pi(this->ms_half);\n  scalar quotient=mag2/mag1;\n  scalar slope=iter;\n  slope*=func::pow(quotient,iter-1);\n  char sign=func::hardSign(mag1);\n  if (sign==0) return;\n  if (sign<0)  angle+=atan(slope)+func::ms_pi;\n  else         angle+=atan(slope);\n  scalar max=func::pow(mag2,iter)*func::sine(angle)+func::pow(mag1,iter)*func::cosine(angle);\n  fillConjugateSupport(row1,row2,angle,max);\n}\n\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::fillSupportFromIter(const int row1,const int row2,const scalar &mag1,const scalar &mag2,powerS iter)\n{\n  scalar xdif=diffPow(mag1,iter,row1);\n  scalar ydif=diffPow(mag2,iter,row2);\n  scalar angle=func::invtan(ydif,xdif)+func::const_pi(this->ms_half);\n  scalar x1=condPow(mag1,iter,row1);\n  scalar y1=condPow(mag2,iter,row2);\n  scalar max=y1*func::sine(angle)+x1*func::cosine(angle);\n  scalar out=mag2*func::sine(angle)+mag1*func::cosine(angle);\n  out-=max;\n  if (func::isPositive(out)) {\n    angle+=func::const_pi(ms_one);\n    max=-max;\n  }\n  fillConjugateSupport(row1,row2,angle,max);\n}\n\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::fillSemiConjugateSupportFromIter(const int row1,const int row2,const scalar &mag1,const scalar &mag2,powerS iter)\n{\n  powerS iter2=iter+1;\n  scalar x1=condPow(mag1,iter,row1);\n  scalar y1=condPow(mag2,iter,row2);\n  scalar x2=condPow(mag1,iter2,row1);\n  scalar y2=condPow(mag2,iter2,row2);\n  fillSupportFromPoints(row1,row2,x1,y1,x2,y2,mag1,mag2);\n  fillSupportFromPoints(row1,row2,-x1,y1,-x2,y2,-mag1,mag2);\n}\n\ntemplate <class scalar>\nbool AbstractMatrix<scalar>::fillLastConjugateSupportFromPoints(int row1,int row2,scalar x1,scalar y1,scalar x2,scalar y2,scalar xRef,scalar yRef,bool hasLastQuarter)\n{\n  scalar angle=func::invtan(y2-y1,x2-x1)+func::const_pi(this->ms_half);\n  scalar max=y1*func::sine(angle)+x1*func::cosine(angle);\n  scalar out=yRef*func::sine(angle)+xRef*func::cosine(angle);\n  char sign=func::hardSign(max);\n  if (sign<0) {//the vector is in the wrong direction rotate 180deg\n    angle+=func::const_pi(ms_one);\n    max=-max;\n    out=-out;\n  }\n  else if (sign==0) {// Undecided, overapproximate by error.\n    max+=m_zero;\n    out+=m_zero;\n  }\n  out-=max;\n  sign=func::hardSign(out);\n  if (hasLastQuarter) {\n    //If the next to last point would be excluded by the restriction, ignore\n    if (sign>0) return false;\n    //If the next to last point is undecided around the restriction, make sure it remains inside\n    if (sign==0) max+=m_zero;\n  }\n  else if (sign>0) {\n    //Revert the bound to close the half-circle\n    angle+=func::const_pi(ms_one);\n    max=y1*func::sine(angle)+x1*func::cosine(angle);\n  }\n  else if (sign==0) {\n    //should never happen\n    func::imprecise(out,func::ms_hardZero);\n    return false;\n  }\n  else {\n    //should never happen but no error\n    return false;\n  }\n  fillConjugateSupport(row1,row2,angle,max);\n  return true;\n}\n\ntemplate <class scalar>\nbool AbstractMatrix<scalar>::testConjugateSupportFromPoints(const scalar &x1,const scalar &y1,const scalar &x2,const scalar &y2,const scalar &xExt,const scalar &yExt)\n{\n  scalar angle=func::invtan(y2-y1,x2-x1)+func::const_pi(this->ms_half);\n  scalar max=y1*func::sine(angle)+x1*func::cosine(angle);\n  scalar ext=yExt*func::sine(angle)+xExt*func::cosine(angle);\n  char sign=func::hardSign(max);\n  if (sign<0) {\n    angle+=func::const_pi(ms_one);\n    max=-max;\n    ext=-ext;\n  }\n  else if (sign==0) {\n    //should never happen\n    func::imprecise(max,func::ms_hardZero);\n  }\n  ext-=max;\n  sign=func::hardSign(ext);\n  if (sign>0) return false;\n  //if ext is zero, the case is dealt when calculating the support function\n  return true;\n}\n\ntemplate <class scalar>\nbool AbstractMatrix<scalar>::fillConjugateSupportFromPoints(const int row1,const int row2,const scalar &x1,const scalar &y1,const scalar &x2,const scalar &y2,const scalar &xExt,const scalar &yExt)\n{\n  scalar angle=func::invtan(y2-y1,x2-x1)+func::const_pi(this->ms_half);\n  scalar max=y1*func::sine(angle)+x1*func::cosine(angle);\n  scalar ext=yExt*func::sine(angle)+xExt*func::cosine(angle);\n  char sign=func::hardSign(max);\n  if (sign<0) {\n    angle+=func::const_pi(ms_one);\n    max=-max;\n    ext=-ext;\n  }\n  else if (sign==0) {\n    //should never happen\n    func::imprecise(max,func::ms_hardZero);\n  }\n  ext-=max;\n  sign=func::hardSign(ext);\n  if (sign>0) return false;\n  if (sign==0) max+=m_zero;\n  fillConjugateSupport(row1,row2,angle,max);\n  return true;\n}\n\ntemplate <class scalar>//template <>\nvoid AbstractMatrix<scalar>::fillLinearSupportFromPoints(const int row1,const int row2,const scalar &min1,const scalar &max1,const scalar &min2,const scalar &max2)\n{\n  scalar angle=func::invtan(max2-min2,max1-min1)+func::const_pi(this->ms_half);\n  scalar min=min2*func::sine(angle)+min1*func::cosine(angle);\n  scalar max=max2*func::sine(angle)+max1*func::cosine(angle);\n  max=func::getHull(min,max);\n  min=-func::toLower(max)+this->m_largeZero;\n  max=func::toUpper(max)+this->m_largeZero;\n  fillConjugateSupport(row1,row2,angle,max);\n  angle+=func::const_pi(ms_one);\n  fillConjugateSupport(row1,row2,angle,min);\n}\n\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::fillQuadraticSupport(int row1,int row2,scalar mag1,scalar mag2,powerS iteration,int precision)\n{\n  precision=(1<<precision)-2;//Number of faces grows geometrically\n  if (precision<1) return;\n  refScalar iterationStep=iteration/precision;\n  if (iterationStep<1) {\n    iterationStep=1;\n    precision=iteration;\n  }\n  int firstIter=1;\n  if (m_jordanIndex[row1%m_dimension]>0) firstIter=m_jordanIndex[row1%m_dimension];\n  if (m_jordanIndex[row2%m_dimension]>0) firstIter=m_jordanIndex[row2%m_dimension];\n  for (int i=firstIter;i<precision;i++) {\n    powerS iter1=func::toInt(floor(i*iterationStep));\n    if (iter1==1) {\n      powerS iter2=iter1+1;\n      scalar x1=condPow(mag1,iter1,row1);\n      scalar y1=condPow(mag2,iter1,row2);\n      scalar x2=condPow(mag1,iter2,row1);\n      scalar y2=condPow(mag2,iter2,row2);\n      scalar x3=condPow(mag1,3,row1);\n      scalar y3=condPow(mag2,3,row2);\n      fillSupportFromPoints(row1,row2,x1,y1,x2,y2,x3,y3);\n    }\n    else fillSupportFromIter(row1,row2,mag1,mag2,iter1);\n  //    else fillSupportFromPoints(row1,row2,x1,y1,x2,y2,mag1,mag2);\n  }\n}\n\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::fillQuadraticConjugateSupport(int row1,int row2,scalar mag1,scalar mag2,powerS iteration,int precision)\n{\n  scalar x1=condPow(mag1,1,row1);\n  scalar y1=condPow(mag2,1,row2);\n  scalar x2=condPow(mag1,iteration,row1);\n  scalar y2=condPow(mag2,iteration,row2);\n  scalar x3=condPow(mag1,2,row1);\n  scalar y3=condPow(mag2,2,row2);\n  scalar angle=func::invtan(y2-y1,x2-x1)-func::const_pi(this->ms_half);//invtan returns positive values (0-pi)\n  scalar max=y1*func::sine(angle)+x1*func::cosine(angle);\n  scalar out=y3*func::sine(angle)+x3*func::cosine(angle);\n  max-=out;\n  if (func::isNegative(max)) {//TODO: need to split for jordan blocks\n    precision=(1<<precision)-2;//Number of faces grows geometrically\n    if (precision<1) return;\n    scalar mag=condPow(mag1,iteration,row1);\n    while(func::isZero(mag)) {\n      iteration>>=2;\n      mag=condPow(mag1,iteration,row1);\n    }\n    refScalar iterationStep=iteration/precision;\n    if (iterationStep<1) {\n      iterationStep=1;\n      precision=iteration;\n    }\n    for (int i=1;i<precision;i++) {\n      powerS iter1=func::toInt(floor(i*iterationStep));\n      powerS iter2=iter1+1;\n      scalar x1=condPow(mag1,iter1,row1);\n      scalar y1=condPow(mag2,iter1,row2);\n      scalar x2=condPow(mag1,iter2,row1);\n      scalar y2=condPow(mag2,iter2,row2);\n      if (iter1==1) {\n        scalar x3=condPow(mag1,3,row1);\n        scalar y3=condPow(mag2,3,row2);\n        fillSupportFromPoints(row1,row2,x1,y1,x2,y2,x3,y3);\n        fillSupportFromPoints(row1,row2,-x1,y1,-x2,y2,-x3,y3);\n      }\n      else {\n        fillSupportFromPoints(row1,row2,x1,y1,x2,y2,mag1,mag2);\n        fillSupportFromPoints(row1,row2,-x1,y1,-x2,y2,-mag1,mag2);\n      }\n    }\n    return;\n  }\n  fillSupportFromPoints(row1,row2,x1,y1,x2,y2,0,y1);\n  fillSupportFromPoints(row1,row2,-x1,y1,-x2,y2,0,y1);\n}\n\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::findConjugateSupports(const int row,const complexS &coef,const powerS iteration,int precision)\n{\n  if (m_conjugatePair[row]<row) return;\n  precision=(1<<precision);//Number of faces grows geometrically\n  int row2=row+1;\n  if (iteration<=2) {\n    complexS p1=condPow(coef,1,row);\n    scalar minR=p1.real();\n    scalar minI=p1.imag();\n    if (iteration==2) {\n      complexS p2=condPow(coef,2,row);\n      scalar maxR=p2.real();\n      scalar maxI=p2.imag();\n      fillLinearSupportFromPoints(row,row2,minR,maxR,minI,maxI);\n      if (func::isPositive(minR-maxR)) swapValues(minR,maxR);\n      if (func::isPositive(minI-maxI)) swapValues(minI,maxI);\n      fillDirection(row,minR,maxR);\n      fillDirection(row2,minI,maxI);\n    }\n    else {\n      fillDirection(row,minR,minR);\n      fillDirection(row2,minI,minI);\n    }\n    return;\n  }\n  scalar mag=func::norm2(coef);\n  scalar angle=func::invtan(coef.imag(),coef.real());\n  scalar quartFreq=abs(func::const_pi(this->ms_half)/angle);\n  powerS offset=func::toInt(trunc(4*func::toLower(quartFreq)));\n  offset+=m_jordanIndex[row]+1;\n  powerS start=(func::isPositive(mag-ms_one)) ? iteration : 1;\n  powerS end=func::isPositive(mag-ms_one) ? ((iteration>offset) ? iteration-offset : 0) : ((iteration>offset) ? offset : iteration);\n  int dir=((end-start)>0) ? 1 : -1;\n  powerS step=(end-start)/precision;\n  if (step==0) step=dir;\n  complexS ext=condPow(coef,start+2*dir,row);\n  complexS p1=condPow(coef,start,row);\n  complexS p2=condPow(coef,start+dir,row);\n  fillConjugateSupportFromPoints(row,row2,p1.real(),p1.imag(),p2.real(),p2.imag(),ext.real(),ext.imag());\n  start+=step;\n  ext=condPow(coef,func::isPositive(mag-ms_one) ? iteration : 1,row2);\n  while (abs(end-start)>=abs(step)) {\n    p1=condPow(coef,start,row);\n    p2=condPow(coef,start+dir,row);\n    if (!fillConjugateSupportFromPoints(row,row2,p1.real(),p1.imag(),p2.real(),p2.imag(),ext.real(),ext.imag())) break;\n    start+=step;\n  }\n  if (abs(end-start)<abs(step)) {\n    p1=condPow(coef,end,row);\n    p2=condPow(coef,end-dir,row);\n    if ((abs(end-start)<=abs(dir)) || fillConjugateSupportFromPoints(row,row2,p1.real(),p1.imag(),p2.real(),p2.imag(),ext.real(),ext.imag())) {\n      start=end;\n      p1=condPow(coef,start,row);\n      p2=ext;\n      ext=condPow(coef,start-dir,row);\n      if (fillLastConjugateSupportFromPoints(row,row2,p1.real(),p1.imag(),p2.real(),p2.imag(),ext.real(),ext.imag(),iteration>func::toInt(trunc(3*func::toLower(quartFreq))))) return;\n      ext=p2;\n    }\n  }\n  powerS base=start-step;\n  end=start;\n  while (abs(end-base)>1) {\n    start=(base+end)/2;\n    p1=condPow(coef,start,row);\n    p2=condPow(coef,start+dir,row);\n    if (testConjugateSupportFromPoints(p1.real(),p1.imag(),p2.real(),p2.imag(),ext.real(),ext.imag())) {\n      base=start;\n    }\n    else {\n      end=start;\n    }\n  }\n  p1=condPow(coef,base,row);\n  p2=condPow(coef,base-dir,row);\n  if (testConjugateSupportFromPoints(p1.real(),p1.imag(),p2.real(),p2.imag(),ext.real(),ext.imag())) base+=dir;\n  p1=condPow(coef,base,row);\n  fillSupportFromPoints(row,row2,p1.real(),p1.imag(),ext.real(),ext.imag(),0,0);\n}\n\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::wrapUp()\n{\n  m_directions.conservativeResize(m_directions.rows(),m_pos);\n  m_supports.conservativeResize(m_pos,1);\n  m_pos=0;\n}\n\n/// Finds the point at which each jordan column is maximum\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::findZeniths()\n{\n  //y_n=binomial(n,k)x^n-k = y_{n-1}*nx/(n-k) -> zenith=k/(1-x)\n  m_zeniths.resize(2*m_dimension);\n  for (int row=0;row<m_dimension;row++) {\n    scalar mag=func::norm2(m_eigenValues.coeff(row,row));\n    if ((m_jordanIndex[row]>0) && (func::isNegative(mag-ms_one))) {\n      scalar zenith=m_jordanIndex[row];\n      zenith/=(ms_one-mag);\n      m_zeniths[row]=func::toInt(func::toLower(zenith));\n    }\n    else m_zeniths[row]=0;\n  }\n  for (int row=m_dimension;row<2*m_dimension;row++) m_zeniths[row]=0;\n}\n\n/// lists the first source row for a folded set of dimensions\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::findUnfolded()\n{\n  m_unfolded.resize(m_dimension);\n  int pos=0;\n  for (int i=0;i<m_dimension;i++) {\n    if (m_jordanIndex[i]>0) continue;\n    if (m_conjugatePair[i]>=0) {\n      m_unfolded[pos++]=i;\n      i++;\n    }\n    else if (m_jordanIndex[i+1]>0) m_unfolded[pos++]=i;\n  }\n  m_unfolded.resize(pos);\n}\n\n/// Marks the round indices in a rounded vector array\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::findRoundIndices(std::vector<bool> &isRoundIndex)\n{\n  int pos=0,mult;\n  isRoundIndex.resize(m_dimension);\n  for (int row=0;row<m_dimension;row+=mult,pos++) {\n    mult=(m_conjugatePair[row]<0) ? 1 : 2;\n    if (m_jordanIndex[row+mult]==0) isRoundIndex[pos]=(m_conjugatePair[row]>=0);\n    else isRoundIndex[pos]=(m_jordanIndex[row+mult]!=0);\n    while (m_jordanIndex[row+mult]!=0) row+=mult;\n  }\n  isRoundIndex.resize(pos);\n}\n\n/// Finds the frequency of rotation of each conjugate pair\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::findFrequencies()\n{\n  m_freq.assign(2*m_dimension,0);\n  for (int row=0;row<m_dimension;row++) {\n    if (m_conjugatePair[row]>row) {\n      complexS coef=m_eigenValues.coeff(row,row);\n      scalar angle=func::invtan(coef.imag(),coef.real());\n      m_freq[row++]=func::toInt(2*func::toUpper(abs(func::const_pi(ms_one)/angle)));\n      m_freq[row]=m_freq[row-1];\n    }\n  }\n}\n\n/// Indicates if the matrix dynamics are divergent\n/// @param strict if true returns only true if no eigenvalues are convergent\ntemplate <class scalar>\nbool AbstractMatrix<scalar>::isDivergent(const bool strict)\n{\n  for (int i=0;i<m_dimension;i++) {\n    scalar eigenNorm=func::norm2(m_eigenValues.coeff(i,i));\n    char sign=func::hardSign(eigenNorm-ms_one);\n    if (strict && (sign<0)) return false;\n    else if (!strict && (sign>=0)) return true;\n  }\n  return strict;\n}\n\n/// Finds the coefficient, magnitude, maximum, and minimum for the abstract vector at row\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::findCoeffBounds(int row,powerS iteration,complexS &coef,scalar &mag,scalar &min,scalar &max)\n{\n  if (row<m_dimension) coef=m_eigenValues.coeff(row,row);\n  else {\n    int transRow=(m_inputType==eVariableInputs) ? m_unfolded[row-m_dimension] : row-m_dimension;\n    coef=m_eigenValues.coeff(transRow,transRow);\n    if ((m_inputType==eVariableInputs) && (func::isPositive(func::norm2(coef)-ms_one))) {\n      coef=m_foldedEigenValues(transRow,transRow);\n    }\n  }\n  if ((row>=m_dimension) && (m_inputType==eVariableInputs)) {\n    scalar rad=func::norm2(coef);\n    mag=condPow(rad,1,row);\n    max=condPow(rad,iteration,row);\n  }\n  else if (m_conjugatePair[row]<0) {\n    mag=condPow(coef.real(),1,row);\n    max=condPow(coef.real(),iteration,row);\n  }\n  else if (iteration>2) {\n    mag=func::norm2(condPow(coef,1,row));\n    max=func::norm2(condPow(coef,iteration,row));\n  }\n  else if (m_conjugatePair[row]>row) {\n    mag=condPow(coef,1,row).real();\n    max=condPow(coef,iteration,row).real();\n  }\n  else {\n    mag=-condPow(coef,1,row).imag();\n    max=-condPow(coef,iteration,row).imag();\n  }\n  min=mag;\n  if ((m_conjugatePair[row]<0) && ((row<m_dimension) || (m_inputType!=eVariableInputs)) && (func::isNegative(coef.real()))) {\n    scalar sum=min+max;\n    char sign=func::hardSign(sum);\n    if (sign>0) min=-max;\n    else if (sign<0) max=-min;\n  }\n}\n\n/// Retrieves the last calculated dynamics\ntemplate <class scalar>\nAbstractPolyhedra<scalar>& AbstractMatrix<scalar>::getAbstractDynamics(const inputType_t inputType)\n{\n  if (inputType==eVariableInputs) return m_abstractRoundDynamics;\n  if (this->m_hasOnes && inputType==eParametricInputs) return m_abstractInputDynamics;\n  return m_abstractDynamics;\n}\n\n/// retrieves the abstract dynamics matrix for a given iteration (n)\ntemplate <class scalar>\nAbstractPolyhedra<scalar>& AbstractMatrix<scalar>::getAbstractDynamics(const powerS iteration,int precision,const inputType_t inputType,const bool normalised)\n{\n  boost::timer timer;\n  if (precision<1) precision=1;\n  int dimension=m_dimension;\n  m_inputType=inputType;\n  if (inputType==eVariableInputs) dimension+=m_foldedEigenValues.rows();\n  else if (this->m_hasOnes && (inputType==eParametricInputs)) dimension+=m_dimension;\n  m_maxIterations=iteration;\n  if (m_hasMultiplicities) this->calculateBoundedEigenError(calculateMaxIterations(iteration));\n  findUnfolded();\n  findZeniths();\n  findFrequencies();\n  AbstractPolyhedra<scalar>& result=getAbstractDynamics(inputType);\n  result.changeDimension(dimension);\n  m_supports.resize((1<<precision)*dimension*dimension,1);\n  m_directions=MatrixS::Zero(dimension,(1<<precision)*dimension*dimension);\n  m_pos=0;\n  complexS coef,coef2;\n  for (int row=0;row<dimension;row++)\n  {\n    scalar mag,min1,max1;\n    findCoeffBounds(row,iteration,coef,mag,min1,max1);\n    scalar min=min1;\n    scalar max=max1;\n    checkRange(row,iteration,func::norm2(coef),min,max);\n    if (m_conjugatePair[row]>=0) findConjugateSupports(row,coef,iteration,precision);\n    else {\n      if (func::isNegative(coef.real())) {\n        scalar sum=min+max;\n        char sign=func::hardSign(sum);\n        if (sign>0) min=-max;\n        else if (sign<0) max=-min;\n      }\n      fillDirection(row,min,max);\n    }\n    if ((iteration<2) || (precision<2)) continue;\n    for (int row2=row+((m_conjugatePair[row]>row) ? 2 : 1);row2<dimension;row2++) {\n      if (row2<m_dimension) coef2=m_eigenValues.coeff(row2,row2);\n      else {\n        int transRow2=(inputType==eVariableInputs) ? m_unfolded[row2-m_dimension]: row2-m_dimension;\n        coef2=m_eigenValues.coeff(transRow2,transRow2);//TODO: the rotations and dilations are wrong at the row value\n        if ((inputType==eVariableInputs) && (func::isPositive(func::norm2(coef2)-ms_one))) {\n          coef=m_foldedEigenValues(transRow2,transRow2);\n        }\n      }\n      scalar mag2,min2,max2;\n      findCoeffBounds(row2,iteration,coef2,mag2,min2,max2);\n      if (m_conjugatePair[row]>=0) {\n        if (m_conjugatePair[row2]<0) {\n          fillQuadraticConjugateSupport(row,row2,func::norm2(coef),func::norm2(coef2),iteration,precision);\n        }\n      }\n      else if (m_conjugatePair[row2]>=0) {\n        fillQuadraticConjugateSupport(row2,row,func::norm2(coef2),func::norm2(coef),iteration,precision);\n      }\n      else if ((iteration==2) || func::isZero(max1-max2)) {\n        fillLinearSupportFromPoints(row,row2,min1,max1,min2,max2);\n      }\n      else {\n        scalar out1=condPow(min1,2,row);\n        scalar out2=condPow(min2,2,row2);\n        fillSupportFromPoints(row,row2,min1,min2,max1,max2,out1,out2);\n        fillQuadraticSupport(row,row2,func::norm2(coef),func::norm2(coef2),iteration,precision);\n      }\n    }\n  }\n  wrapUp();\n  if (m_hasMultiplicities) {\n    scalar high=func::pow(ms_one+m_error,iteration);\n    scalar low=func::pow(ms_one-m_error,iteration);\n    scalar relaxation=func::getHull(high,low);\n    m_supports*=relaxation;\n  }\n  result.load(m_directions,m_supports,true);\n  if (normalised) result.normalise();\n  result.setCalculationTime(timer.elapsed()*1000);\n  if (ms_trace_dynamics>=eTraceAbstraction) {\n    std::stringstream stream;\n    stream << \"s=\" << iteration << \",l=\" << precision;\n    result.logTableau(stream.str());\n  }\n  return result;\n}\n\n/// Adds a set of supports at the given iteration in order to refine the abstraction\ntemplate <class scalar>\nbool AbstractMatrix<scalar>::addSupportsAtIteration(AbstractPolyhedra<scalar>& dynamics,powerS iteration,powerS max)\n{\n  boost::timer timer;\n  complexS coef,coef2;\n  int dimension=m_dimension;\n  if (m_inputType==eVariableInputs) dimension+=m_foldedEigenValues.rows();\n  else if (this->m_hasOnes && (m_inputType==eParametricInputs)) dimension+=m_dimension;\n\n  m_supports.resize(dimension*dimension,1);\n  m_directions=MatrixS::Zero(dimension,dimension*dimension);\n  m_pos=0;\n  for (int row=0;row<dimension;row++)\n  {\n    if (row<m_dimension) coef=m_eigenValues.coeff(row,row);\n    else {\n      int transRow=(m_inputType==eVariableInputs) ? m_unfolded[row-m_dimension] : row-m_dimension;\n      coef=m_eigenValues.coeff(transRow,transRow);\n      if ((m_inputType==eVariableInputs) && (func::isPositive(func::norm2(coef)-ms_one))) {\n        coef=m_foldedEigenValues(transRow,transRow);\n      }\n    }\n    if (m_conjugatePair[row]>row) {\n      scalar mag=func::norm2(coef);\n      int dir=(func::isPositive(mag-ms_one)) ? -1 : 1;\n      complexS ext=condPow(coef,func::isPositive(mag-ms_one) ? max : 1,row+1);\n      complexS p1=condPow(coef,iteration,row);\n      complexS p2=condPow(coef,iteration+dir,row);\n      fillConjugateSupportFromPoints(row,row+1,p1.real(),p1.imag(),p2.real(),p2.imag(),ext.real(),ext.imag());\n    }\n    for (int row2=row+((m_conjugatePair[row]>row) ? 2 : 1);row2<dimension;row2++) {\n        if (row2<m_dimension) coef2=m_eigenValues.coeff(row2,row2);\n        else {\n          int transRow2=(m_inputType==eVariableInputs) ? m_unfolded[row2-m_dimension]: row2-m_dimension;\n          coef2=m_eigenValues.coeff(transRow2,transRow2);//TODO: the rotations and dilations are wrong at the row value\n          if ((m_inputType==eVariableInputs) && (func::isPositive(func::norm2(coef2)-ms_one))) {\n            coef2=m_foldedEigenValues(transRow2,transRow2);\n          }\n        }\n        if (m_conjugatePair[row]>=0) {\n          if (m_conjugatePair[row2]<0) {\n            fillSemiConjugateSupportFromIter(row,row2,func::norm2(coef),func::norm2(coef2),iteration);\n          }\n        }\n        else if (m_conjugatePair[row2]>=0) {\n          fillSemiConjugateSupportFromIter(row2,row,func::norm2(coef2),func::norm2(coef),iteration);\n        }\n        else {\n          fillSupportFromIter(row,row2,func::norm2(coef),func::norm2(coef2),iteration);\n        }\n      }\n  }\n  wrapUp();\n  if (m_hasMultiplicities) {\n    scalar high=func::pow(ms_one+m_error,iteration);\n    scalar low=func::pow(ms_one-m_error,iteration);\n    scalar relaxation=func::getHull(high,low);\n    m_supports*=relaxation;\n  }\n  dynamics.addDirection(m_directions,m_supports);\n  dynamics.addCalculationTime(timer.elapsed()*1000);\n  if (ms_trace_dynamics>=eTraceAbstraction) {\n    std::stringstream stream;\n    stream << \"abs supports n=\" << iteration;\n    dynamics.logTableau(stream.str());\n  }\n  return true;\n}\n\n/// Calculates the number of iterations necessary to reacha fixpoint\ntemplate <class scalar>\ntypename AbstractMatrix<scalar>::powerS AbstractMatrix<scalar>::calculateMaxIterations(powerS max)\n{\n  powerS result=0;\n  findZeniths();\n  findFrequencies();\n  for (int i=0;i<m_dimension;i++) {\n    complexS coef=m_eigenValues.coeff(i,i);\n    if (func::isPositive(func::norm2(coef)-ms_one)) return (max<func::ms_infPower) ? max: func::ms_infPower;\n    if (m_zeniths[i]+m_freq[i]>result) result=m_zeniths[i]+m_freq[i];\n  }\n  return (max<result) ? max : result;\n}\n\n/// Finds the corresponding iteration that generates dynamics close to the given point\ntemplate <class scalar>\nvoid AbstractMatrix<scalar>::findIterations(MatrixS &point,powerList &iterations)\n{\n  complexS coef;\n  powerS range;\n  for (int col=0;col<point.cols();col++) {\n    if (col<m_dimension) coef=m_eigenValues.coeff(col,col);\n    else {\n      int transCol=(m_inputType==eVariableInputs) ? m_unfolded[col-m_dimension] : col-m_dimension;\n      coef=m_eigenValues.coeff(transCol,transCol);\n      if ((m_inputType==eVariableInputs) && (func::isPositive(func::norm2(coef)-ms_one))) {\n        coef=m_foldedEigenValues(transCol,transCol);\n      }\n    }\n    refScalar rad=func::toCentre(func::norm2(coef));\n    powerS iteration;\n    if (m_conjugatePair[col]>=0) {\n      scalar coeffAngle=func::invtan(coef.imag(),coef.real());\n      scalar angle=func::invtan(point.coeff(0,col+1),point.coeff(0,col));\n      char dir=func::hardSign(coeffAngle);\n      char sign=func::hardSign(angle);\n      if (sign!=dir) {\n        if (sign<0) angle+=func::ms_2_pi;\n        else        angle-=func::ms_2_pi;\n      }\n      refScalar finalSteps=func::toCentre(angle/coeffAngle);\n      iteration=func::toInt(finalSteps);\n      if (rad>func::ms_1) {\n        refScalar tau=func::toCentre(coeffAngle/func::ms_2_pi);\n        tau*=m_maxIterations;\n        powerS mult=func::toInt(tau);\n        mult*=m_freq[col];\n        iteration+=mult;\n      }\n      col++;\n    }\n    else if ((rad>func::ms_1) || (!func::isZero(point.coeff(0,col)))) {\n      iteration=condLog(rad,func::toCentre(point.coeff(0,col)),col,range);\n    }\n    else {\n      iteration=0;\n      range=0;\n    }\n    while ((iteration<2) && (range>0)) {\n      range--;\n      iteration++;\n    }\n    if (iteration>1) iterations[iteration]=range;//TODO: should merge when there is equality\n  }\n}\n\n#ifdef USE_LDOUBLE\n  #ifdef USE_SINGLES\n    template class AbstractMatrix<long double>;\n  #endif\n  #ifdef USE_INTERVALS\n    template class AbstractMatrix<ldinterval>;\n  #endif\n#endif\n#ifdef USE_MPREAL\n  #ifdef USE_SINGLES\n    template class AbstractMatrix<mpfr::mpreal>;\n  #endif\n  #ifdef USE_INTERVALS\n    template class AbstractMatrix<mpinterval>;\n  #endif\n#endif\n\n}\n", "meta": {"hexsha": "c50dd7d89dc191b40e20096cbf17ce283835b150", "size": 34057, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/AbstractMatrix.cpp", "max_stars_repo_name": "SSV-Group/dsverifier", "max_stars_repo_head_hexsha": "1daca4704216edf9a360b4a39e00663d94646ad1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2016-08-29T19:23:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-18T22:27:21.000Z", "max_issues_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/AbstractMatrix.cpp", "max_issues_repo_name": "SSV-Group/dsverifier", "max_issues_repo_head_hexsha": "1daca4704216edf9a360b4a39e00663d94646ad1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 64.0, "max_issues_repo_issues_event_min_datetime": "2016-09-10T16:29:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-15T14:31:06.000Z", "max_forks_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/AbstractMatrix.cpp", "max_forks_repo_name": "SSV-Group/dsverifier", "max_forks_repo_head_hexsha": "1daca4704216edf9a360b4a39e00663d94646ad1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-10-09T21:38:41.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-05T10:05:32.000Z", "avg_line_length": 35.9630411827, "max_line_length": 196, "alphanum_fraction": 0.6914877999, "num_tokens": 10175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.5087545460276187}}
{"text": "/*\nagnanowire_modeling_v1.cpp\n(Based on agnanowire_modeling_v3.py)\nRandom resitor network model for Ag nanowire network in oxide matrix\nUsing data from Will Scheideler\n\nCreated by Jeremy Smith on 2015-07-17\nUniversity of California, Berkeley\nj-smith@eecs.berkeley.edu\n\nVersion 1.0\n*/\n\n#include <iostream>\n#include <fstream>\n#include <cstdlib>\n#include <unistd.h>\n#include <string>\n#include <vector>\n#include <thread>\n#include <ctime>\n#include <Eigen/Dense>\n#include \"nwnet.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid stats(std::vector<double>& v, double& average, double& stderr, double& median){\n\tdouble sum = 0;\n\tfor(int i = 0; i < v.size(); i++){\n\t\tsum += v[i];\n\t}\n\taverage = sum/v.size();\n\tdouble dev = 0;\n\tfor(int i = 0; i < v.size(); i++){\n\t\tdev += (v[i] - average)*(v[i] - average);\n\t}\n\tstderr = std::sqrt(dev/(v.size()*(v.size()-1)));\n\tstd::sort(v.begin(), v.end());\n\tmedian = v[v.size()/2];\n}\n\nint main(){\n\t/*\n\tSetup parameters\n\tChange values here for different nanowire networks\n\t*/\n\tstd::srand(time(NULL) | (getpid() << 4));\n\tdouble substratesize = 50.0;\n\t// Points to test resistance as fraction of substrate size\n\tArrayXXd testpoints(12, 2);\n\ttestpoints << 0.250, 0.750, 0.750, 0.250,\n\t              0.250, 0.250, 0.750, 0.750,\n\t              0.375, 0.625, 0.625, 0.375,\n\t              0.375, 0.375, 0.625, 0.625,\n\t              0.323, 0.500, 0.677, 0.500,\n\t              0.500, 0.323, 0.500, 0.677;\n\ttestpoints *= substratesize;\n\tdouble nwlength = 14.0;                                              // Nanowire length\n\tdouble nwlength_sd = 4.0;                                            // Standard deviation of wire lengths\n\tdouble nwdiameter = 0.033;                                           // Nanowire diameter\n\tdouble agresistivity = 1.59e-2;                                      // Ag resistivity\n\t\n\tdouble nwdensity[] = {0.02, 0.04, 0.05};                             // Nanowires per sq micron\n\tdouble nwinterres[] = {1.0, 10.0, 1000.0};                           // Resistance between wires\n\n\tdouble matrixrsheet = 1.0e8;                                         // Sheet resistance of matrix\n\tint runs = 4;                                                        // Number of runs per condition\n\n\tdouble nwresistance = 4*agresistivity/(M_PI*nwdiameter*nwdiameter);  // Nanowire resistance per unit length\n\n\tstd::vector<std::string> summaryList;\n\tstd::ofstream outfile;\n\n\tcout << \"\\n=================\\n\";\n\tcout << \"Ag Nanowire Model\\n\";\n\tcout << \"Jeremy Smith\\n\";\n\tcout << \"=================\\n\\n\";\n\n\tfor(int j = 0; j < 3; j++){\n\t\tfor(int k = 0; k < 3; k++){\n\t\t\tstd::vector<WireNet> nets;\n\t\t\tstd::vector<std::thread> procs;\n\t\t\tint nwnumber = nwdensity[k]*substratesize*substratesize;\n\n\t\t\tfor(int i = 0; i < runs; i++){\n\t\t\t\tunsigned seed = rand()%10000;\n\t\t\t\tWireNet n(nwnumber, nwlength, nwlength_sd, substratesize, nwresistance, nwinterres[j], matrixrsheet, seed, false);\n\t\t\t\tnets.push_back(n);\n\t\t\t}\n\t\t\tfor(int i = 0; i < runs; i++){\n\t\t\t\tprocs.push_back(std::thread(&WireNet::solve, &nets[i]));\n\t\t\t}\n\t\t\tfor(int i = 0; i < runs; i++){\n\t\t\t\tprocs[i].join();\n\t\t\t}\n\t\t\tcout << endl;\n\n\t\t\tstd::vector<double> rList;\n\t\t\tstd::vector<double> tList;\n\t\t\tfor(int i = 0; i < runs; i++){\n\t\t\t\tnets[i].parameters();\n\t\t\t\tfor(int p = 0; p < testpoints.rows()/2 - 1; p++){\n\t\t\t\t\tVector2d xy1 = testpoints.row(2*p);\n\t\t\t\t\tVector2d xy2 = testpoints.row(2*p+1);\n\t\t\t\t\tint node1 = findnode(nets[i].nodeCoords, xy1);\n\t\t\t\t\tint node2 = findnode(nets[i].nodeCoords, xy2);\n\t\t\t\t\tdouble r = two_point_resistance(nets[i].eigenvalues, nets[i].eigenvectors, node1, node2);\n\t\t\t\t\tcout << \"  R: \" << r << \"    Between nodes: \" << node1 << \",\" << node2 << endl;\n\t\t\t\t\trList.push_back(std::log10(r));\n\t\t\t\t}\n\t\t\t\tdouble t = 100*(1 - nets[i].areal_coverage(nwdiameter));\n\t\t\t\tcout << \"  T: \" << t << \" \" << char(37) << endl;\n\t\t\t\ttList.push_back(t);\n\n\t\t\t\tnets[i].output_files(\"data_\" + std::to_string(j) + std::to_string(k) + char(65+i));    // Test conditions j and k and run number i\n\t\t\t\tcout << endl;\n\t\t\t}\n\t\t\tdouble r_average;\n\t\t\tdouble r_stderr;\n\t\t\tdouble r_median;\n\t\t\tdouble t_average;\n\t\t\tdouble t_stderr;\n\t\t\tdouble t_median;\n\t\t\tstats(rList, r_average, r_stderr, r_median);\n\t\t\tstats(tList, t_average, t_stderr, t_median);\n\t\t\tsummaryList.push_back(\"data_\" + std::to_string(j) + std::to_string(k) + '\\t' \n\t\t\t\t                  + to_string(nwlength) + '\\t' + to_string(nwlength_sd) + '\\t' + to_string(nwdiameter) + '\\t' \n\t\t\t\t                  + to_string(agresistivity) + '\\t' + to_string(nwresistance) + '\\t' \n\t\t\t\t                  + to_string(nwdensity[k]) + '\\t' + to_string(nwnumber) + '\\t' \n\t\t\t\t                  + to_string(nwinterres[j]) + '\\t' + to_string(matrixrsheet) + '\\t' \n\t\t\t\t                  + to_string(r_average) + '\\t' + to_string(r_median) + '\\t' + to_string(r_stderr) + '\\t' \n\t\t\t\t                  + to_string(t_average) + '\\t' + to_string(t_stderr) + '\\n');\n\t\t}\n\t}\n\n\tcout << \"Writing out summary file...\" << endl;\n    outfile.open(\"summary.txt\");\n    outfile << \"filename\\tnwlength\\tnwstd\\tnwdiameter\\tagresistivity\\tnwresistance\\t\"\n            << \"nwdensity\\tnwnumber\\tnwinterres\\tmatrixrsheet\\t\"\n            << \"resistance\\tmedresistance\\tresistanceerr\\ttransmission\\ttransmissionerr\\n\";\n    for(int i = 0; i < summaryList.size(); i++){\n        outfile << summaryList[i];\n    }\n    outfile.close();\n    cout << \"DONE\" << endl;\n}\n", "meta": {"hexsha": "da48f8bed72153925c9c345e935c620384b5c757", "size": 5338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "agnanowire_modeling_v1.cpp", "max_stars_repo_name": "jzmnd/nwnetcpp", "max_stars_repo_head_hexsha": "397444c2bbc4dfb14c90be0a0288f070a396534c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "agnanowire_modeling_v1.cpp", "max_issues_repo_name": "jzmnd/nwnetcpp", "max_issues_repo_head_hexsha": "397444c2bbc4dfb14c90be0a0288f070a396534c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "agnanowire_modeling_v1.cpp", "max_forks_repo_name": "jzmnd/nwnetcpp", "max_forks_repo_head_hexsha": "397444c2bbc4dfb14c90be0a0288f070a396534c", "max_forks_repo_licenses": ["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.0675675676, "max_line_length": 134, "alphanum_fraction": 0.5724990633, "num_tokens": 1602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5087545414118907}}
{"text": "#include <Eigen/Geometry>\n#include <sbs/physics/simulation.h>\n#include <sbs/physics/xpbd/collision_constraint.h>\n\nnamespace sbs {\nnamespace physics {\nnamespace xpbd {\n\ncollision_constraint_t::collision_constraint_t(\n    scalar_type alpha,\n    scalar_type beta,\n    simulation_t const& simulation,\n    index_type bi,\n    index_type vi,\n    Eigen::Vector3d const& p,\n    Eigen::Vector3d const& n)\n    : constraint_t{alpha, beta}, bi_(bi), vi_(vi), qs_(p), n_(n)\n{\n}\n\nvoid collision_constraint_t::project_positions(simulation_t& simulation, scalar_type dt)\n{\n    particle_t& p       = simulation.particles()[bi_][vi_];\n    scalar_type const w = p.invmass();\n    scalar_type const C = evaluate(p.xi());\n\n    if (C >= static_cast<scalar_type>(0.))\n        return;\n\n    scalar_type const alpha_tilde    = alpha_ / (dt * dt);\n    scalar_type const delta_lagrange = -(C + alpha_tilde * lagrange_) / (w + alpha_tilde);\n\n    lagrange_ += delta_lagrange;\n\n    /**\n     * grad(C) = n\n     * ||n||^2 = 1,\n     * so w*||n||^2 = w\n     */\n    p.xi() += w * n_ * delta_lagrange;\n}\n\nscalar_type collision_constraint_t::evaluate(Eigen::Vector3d const& p) const\n{\n    Eigen::Vector3d const qp = p - qs_;\n    double const C           = qp.dot(n_);\n    return C;\n}\n\n} // namespace xpbd\n} // namespace physics\n} // namespace sbs\n", "meta": {"hexsha": "b0223049e8558fda4094fe47523cb2ce57dcb894", "size": 1307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/physics/xpbd/collision_constraint.cpp", "max_stars_repo_name": "Q-Minh/soft-body-simulator", "max_stars_repo_head_hexsha": "f41640945df989d8c91d99e8f2e86d6af90211f6", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T01:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T17:35:49.000Z", "max_issues_repo_path": "src/physics/xpbd/collision_constraint.cpp", "max_issues_repo_name": "Q-Minh/soft-body-simulator", "max_issues_repo_head_hexsha": "f41640945df989d8c91d99e8f2e86d6af90211f6", "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/physics/xpbd/collision_constraint.cpp", "max_forks_repo_name": "Q-Minh/soft-body-simulator", "max_forks_repo_head_hexsha": "f41640945df989d8c91d99e8f2e86d6af90211f6", "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.6603773585, "max_line_length": 90, "alphanum_fraction": 0.6472838562, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.5087545360199298}}
{"text": "#ifndef LSHFUNC_HPP\n#define LSHFUNC_HPP\n\n#ifndef EIGEN_CONFIG_H_\n#define EIGEN_CONFIG_H_\n\n#include <boost/serialization/array.hpp>\n// w.r.t Eigen_3.2.4/Eigen/Core\n#define EIGEN_DENSEBASE_PLUGIN \"../../../../EigenDenseBaseAddons.hpp\"\n#include <Eigen/Core>\n#endif // EIGEN_CONFIG_H_\n\n\n#include <Eigen/Dense>\n#include <boost/random.hpp>\n#include <boost/filesystem.hpp>\n#include <cmath>\n#include <functional>\n#include \"config.hpp\"\n\nusing namespace std;\nnamespace fs = boost::filesystem;\n\nclass LSHFunc {\n  float w;\n  int k; // number of bits in a function (length of key)\n  int dim; // dimension of features\n  Eigen::MatrixXf A;\n  Eigen::MatrixXf b;\n  \npublic:\n  LSHFunc(int _k, int _dim): k(_k), dim(_dim) {\n    genLSHfunc();\n  }\n  LSHFunc() {} // used while serializing\n\n  void genLSHfunc() {\n    w = 24; // default value\n    A = Eigen::MatrixXf::Random(dim, k); // TODO: Use normal distribution to sample (as in GS code)\n    typedef boost::mt19937 RNGType;\n    RNGType rng;\n    boost::uniform_real<> generator(0, w);\n    boost::variate_generator<RNGType, boost::uniform_real<>> dice(rng, generator);\n\n    b = Eigen::MatrixXf::Random(1, k);\n    for (int i = 0; i < k; i++) {\n      b(0, i) = dice();\n    }\n  }\n\n  void computeHash(const vector<float>& _feat, vector<int>& hash) const {\n    if (_feat.size() == 0) {\n      return;\n    }\n    hash.clear();\n    Eigen::MatrixXf feat = Eigen::VectorXf::Map(&_feat[0], _feat.size());\n    #if NORMALIZE_FEATS == 1\n      feat = feat / feat.norm(); // normalize the feature\n    #endif\n    Eigen::MatrixXf res = (feat.transpose() * A - b.replicate(feat.cols(), 1)) / w;\n    for (int i = 0; i < res.size(); i++) {\n      hash.push_back((int) floor(res(i)));\n    }\n  }\n  \n  template<class Archive>\n  void serialize(Archive &ar, const unsigned int version) {\n    ar & w;\n    ar & k;\n    ar & dim;\n    ar & A;\n    ar & b;\n  }\n};\n\n#endif\n\n", "meta": {"hexsha": "1635e7b93baa1889c6f3a8935122df64dd1ae4d0", "size": 1868, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ScalableLSH/DiskE2LSH/LSHFunc.hpp", "max_stars_repo_name": "USCDataScience/cmu-fg-bg-similarity", "max_stars_repo_head_hexsha": "d8fc9a53937551f7a052bc2c6f442bcc29ea2615", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-04-13T21:40:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T11:32:31.000Z", "max_issues_repo_path": "ScalableLSH/DiskE2LSH/LSHFunc.hpp", "max_issues_repo_name": "USCDataScience/cmu-fg-bg-similarity", "max_issues_repo_head_hexsha": "d8fc9a53937551f7a052bc2c6f442bcc29ea2615", "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": "ScalableLSH/DiskE2LSH/LSHFunc.hpp", "max_forks_repo_name": "USCDataScience/cmu-fg-bg-similarity", "max_forks_repo_head_hexsha": "d8fc9a53937551f7a052bc2c6f442bcc29ea2615", "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.9487179487, "max_line_length": 99, "alphanum_fraction": 0.6300856531, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5087385376560362}}
{"text": "#include <stan/math/mix/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <test/unit/math/rev/scal/fun/util.hpp>\n#include <test/unit/math/mix/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdLogRisingFactorial,FvarVar_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  fvar<var> a(4.0,1.0);\n  fvar<var> b(3.0,1.0);\n  fvar<var> c = log_rising_factorial(a,b);\n\n  EXPECT_FLOAT_EQ(std::log(120.0), c.val_.val());\n  EXPECT_FLOAT_EQ(2.4894509, c.d_.val());\n\n  AVEC y = createAVEC(a.val_,b.val_);\n  VEC g;\n  c.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(0.61666667, g[0]);\n  EXPECT_FLOAT_EQ(1.8727844, g[1]);\n}\nTEST(AgradFwdLogRisingFactorial,FvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  fvar<var> a(4.0,1.0);\n  double b(3.0);\n  fvar<var> c = log_rising_factorial(a,b);\n\n  EXPECT_FLOAT_EQ(std::log(120.0), c.val_.val());\n  EXPECT_FLOAT_EQ(0.61666667, c.d_.val());\n\n  AVEC y = createAVEC(a.val_);\n  VEC g;\n  c.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(0.61666667, g[0]);\n}\nTEST(AgradFwdLogRisingFactorial,Double_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  double a(4.0);\n  fvar<var> b(3.0,1.0);\n  fvar<var> c = log_rising_factorial(a,b);\n\n  EXPECT_FLOAT_EQ(std::log(120.0), c.val_.val());\n  EXPECT_FLOAT_EQ(1.8727844, c.d_.val());\n\n  AVEC y = createAVEC(b.val_);\n  VEC g;\n  c.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(1.8727844, g[0]);\n}\n\nTEST(AgradFwdLogRisingFactorial,FvarVar_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  fvar<var> a(4.0,1.0);\n  fvar<var> b(3.0,1.0);\n  fvar<var> c = log_rising_factorial(a,b);\n\n  AVEC y = createAVEC(a.val_,b.val_);\n  VEC g;\n  c.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(0.023267401, g[0]);\n  EXPECT_FLOAT_EQ(0.30709034, g[1]);\n}\nTEST(AgradFwdLogRisingFactorial,FvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  fvar<var> a(4.0,1.0);\n  double b(3.0);\n  fvar<var> c = log_rising_factorial(a,b);\n\n  AVEC y = createAVEC(a.val_);\n  VEC g;\n  c.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(-0.13027778, g[0]);\n}\nTEST(AgradFwdLogRisingFactorial,Double_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  double a(4.0);\n  fvar<var> b(3.0,1.0);\n  fvar<var> c = log_rising_factorial(a,b);\n\n  AVEC y = createAVEC(b.val_);\n  VEC g;\n  c.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(0.15354517, g[0]);\n}\nTEST(AgradFwdLogRisingFactorial,FvarFvarVar_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 3.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = log_rising_factorial(x,y);\n\n  EXPECT_FLOAT_EQ(std::log(120.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.61666667, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(1.8727844, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0.15354517, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.61666667, g[0]);\n  EXPECT_FLOAT_EQ(1.8727844, g[1]);\n}\nTEST(AgradFwdLogRisingFactorial,FvarFvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n  double y(3.0);\n\n  fvar<fvar<var> > a = log_rising_factorial(x,y);\n\n  EXPECT_FLOAT_EQ(std::log(120.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.61666667, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.61666667, g[0]);\n}\nTEST(AgradFwdLogRisingFactorial,Double_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  double x(4.0);\n  fvar<fvar<var> > y;\n  y.val_.val_ = 3.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = log_rising_factorial(x,y);\n\n  EXPECT_FLOAT_EQ(std::log(120.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(1.8727844, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(1.8727844, g[0]);\n}\nTEST(AgradFwdLogRisingFactorial,FvarFvarVar_FvarFvarVar_2ndDeriv_x) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 3.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = log_rising_factorial(x,y);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.13027778, g[0]);\n  EXPECT_FLOAT_EQ(0.15354517, g[1]);\n}\nTEST(AgradFwdLogRisingFactorial,FvarFvarVar_FvarFvarVar_2ndDeriv_y) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 3.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = log_rising_factorial(x,y);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.15354517, g[0]);\n  EXPECT_FLOAT_EQ(0.15354517, g[1]);\n}\nTEST(AgradFwdLogRisingFactorial,FvarFvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n  double y(3.0);\n\n  fvar<fvar<var> > a = log_rising_factorial(x,y);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.13027778, g[0]);\n}\nTEST(AgradFwdLogRisingFactorial,Double_FvarFvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  double x(4.0);\n  fvar<fvar<var> > y;\n  y.val_.val_ = 3.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = log_rising_factorial(x,y);\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.15354517, g[0]);\n}\nTEST(AgradFwdLogRisingFactorial,FvarFvarVar_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 3.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = log_rising_factorial(x,y);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.023530472, g[0]);\n  EXPECT_FLOAT_EQ(-0.023530472, g[1]);\n}\nTEST(AgradFwdLogRisingFactorial,FvarFvarVar_Double_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n  x.d_.val_ = 1.0;\n  double y(3.0);\n\n  fvar<fvar<var> > a = log_rising_factorial(x,y);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.056509256, g[0]);\n}\nTEST(AgradFwdLogRisingFactorial,Double_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::log_rising_factorial;\n  using boost::math::digamma;\n\n  double x(4.0);\n  fvar<fvar<var> > y;\n  y.val_.val_ = 3.0;\n  y.d_.val_ = 1.0;\n  y.val_.d_ = 1.0;\n\n  fvar<fvar<var> > a = log_rising_factorial(x,y);\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.023530472, g[0]);\n}\n\nstruct log_rising_factorial_fun {\n  template <typename T0, typename T1>\n  inline \n  typename boost::math::tools::promote_args<T0,T1>::type\n  operator()(const T0 arg1,\n             const T1 arg2) const {\n    return log_rising_factorial(arg1,arg2);\n  }\n};\n\nTEST(AgradFwdLogRisingFactorial, nan) {\n  log_rising_factorial_fun log_rising_factorial_;\n  test_nan_mix(log_rising_factorial_,3.0,5.0,false);\n}\n", "meta": {"hexsha": "db5ea24090f1f3cb47d189e773ee0135fba7a2c6", "size": 8449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/mix/scal/fun/log_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/mix/scal/fun/log_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/mix/scal/fun/log_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": 25.0712166172, "max_line_length": 69, "alphanum_fraction": 0.6784234821, "num_tokens": 3275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.508738526129557}}
{"text": "// Copyright (C) 2011  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n#include <sstream>\r\n#include <string>\r\n#include <cstdlib>\r\n#include <ctime>\r\n#include <dlib/svm_threaded.h>\r\n\r\n#include \"tester.h\"\r\n\r\nnamespace  \r\n{\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n\r\n    logger dlog(\"test.svm_struct\");\r\n\r\n\r\n    template <\r\n        typename matrix_type,\r\n        typename sample_type,\r\n        typename label_type\r\n        >\r\n    class test_multiclass_svm_problem : public structural_svm_problem_threaded<matrix_type,\r\n                                                                 std::vector<std::pair<unsigned long,typename matrix_type::type> > > \r\n    {\r\n\r\n    public:\r\n        typedef typename matrix_type::type scalar_type;\r\n        typedef std::vector<std::pair<unsigned long,scalar_type> > feature_vector_type;\r\n\r\n        test_multiclass_svm_problem (\r\n            const std::vector<sample_type>& samples_,\r\n            const std::vector<label_type>& labels_\r\n        ) :\r\n            structural_svm_problem_threaded<matrix_type,\r\n                std::vector<std::pair<unsigned long,typename matrix_type::type> > >(2),\r\n            samples(samples_),\r\n            labels(labels_),\r\n            dims(10+1) // +1 for the bias\r\n        {\r\n            for (int i = 0; i < 10; ++i)\r\n            {\r\n                distinct_labels.push_back(i);\r\n            }\r\n        }\r\n\r\n        virtual long get_num_dimensions (\r\n        ) const\r\n        {\r\n            return dims*10;\r\n        }\r\n\r\n        virtual long get_num_samples (\r\n        ) const \r\n        {\r\n            return static_cast<long>(samples.size());\r\n        }\r\n\r\n        virtual void get_truth_joint_feature_vector (\r\n            long idx,\r\n            feature_vector_type& psi\r\n        ) const \r\n        {\r\n            assign(psi, samples[idx]);\r\n            // Add a constant -1 to account for the bias term.\r\n            psi.push_back(std::make_pair(dims-1,static_cast<scalar_type>(-1)));\r\n\r\n            // Find which distinct label goes with this psi.\r\n            const long label_idx = index_of_max(mat(distinct_labels) == labels[idx]);\r\n\r\n            offset_feature_vector(psi, dims*label_idx);\r\n        }\r\n\r\n        virtual void separation_oracle (\r\n            const long idx,\r\n            const matrix_type& current_solution,\r\n            scalar_type& loss,\r\n            feature_vector_type& psi\r\n        ) const \r\n        {\r\n            scalar_type best_val = -std::numeric_limits<scalar_type>::infinity();\r\n            unsigned long best_idx = 0;\r\n\r\n            // Figure out which label is the best.  That is, what label maximizes\r\n            // LOSS(idx,y) + F(x,y).  Note that y in this case is given by distinct_labels[i].\r\n            for (unsigned long i = 0; i < distinct_labels.size(); ++i)\r\n            {\r\n                // Compute the F(x,y) part:\r\n                // perform: temp == dot(relevant part of current solution, samples[idx]) - current_bias\r\n                scalar_type temp = dot(rowm(current_solution, range(i*dims, (i+1)*dims-2)), samples[idx]) - current_solution((i+1)*dims-1);\r\n\r\n                // Add the LOSS(idx,y) part:\r\n                if (labels[idx] != distinct_labels[i])\r\n                    temp += 1;\r\n\r\n                // Now temp == LOSS(idx,y) + F(x,y).  Check if it is the biggest we have seen.\r\n                if (temp > best_val)\r\n                {\r\n                    best_val = temp;\r\n                    best_idx = i;\r\n                }\r\n            }\r\n\r\n            assign(psi, samples[idx]);\r\n            // add a constant -1 to account for the bias term\r\n            psi.push_back(std::make_pair(dims-1,static_cast<scalar_type>(-1)));\r\n\r\n            offset_feature_vector(psi, dims*best_idx);\r\n\r\n            if (distinct_labels[best_idx] == labels[idx])\r\n                loss = 0;\r\n            else\r\n                loss = 1;\r\n        }\r\n\r\n    private:\r\n\r\n        void offset_feature_vector (\r\n            feature_vector_type& sample,\r\n            const unsigned long val\r\n        ) const\r\n        {\r\n            if (val != 0)\r\n            {\r\n                for (typename feature_vector_type::iterator i = sample.begin(); i != sample.end(); ++i)\r\n                {\r\n                    i->first += val;\r\n                }\r\n            }\r\n        }\r\n\r\n\r\n        const std::vector<sample_type>& samples;\r\n        const std::vector<label_type>& labels;\r\n        std::vector<label_type> distinct_labels;\r\n        const long dims;\r\n    };\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    template <\r\n        typename K,\r\n        typename label_type_ = typename K::scalar_type \r\n        >\r\n    class test_svm_multiclass_linear_trainer2\r\n    {\r\n    public:\r\n        typedef label_type_ label_type;\r\n        typedef K kernel_type;\r\n        typedef typename kernel_type::scalar_type scalar_type;\r\n        typedef typename kernel_type::sample_type sample_type;\r\n        typedef typename kernel_type::mem_manager_type mem_manager_type;\r\n\r\n        typedef multiclass_linear_decision_function<kernel_type, label_type> trained_function_type;\r\n\r\n\r\n        test_svm_multiclass_linear_trainer2 (\r\n        ) :\r\n            C(10),\r\n            eps(1e-4),\r\n            verbose(false)\r\n        {\r\n        }\r\n\r\n        trained_function_type train (\r\n            const std::vector<sample_type>& all_samples,\r\n            const std::vector<label_type>& all_labels\r\n        ) const\r\n        {\r\n            scalar_type svm_objective = 0;\r\n            return train(all_samples, all_labels, svm_objective);\r\n        }\r\n\r\n        trained_function_type train (\r\n            const std::vector<sample_type>& all_samples,\r\n            const std::vector<label_type>& all_labels,\r\n            scalar_type& svm_objective\r\n        ) const\r\n        {\r\n            // make sure requires clause is not broken\r\n            DLIB_ASSERT(is_learning_problem(all_samples,all_labels),\r\n                \"\\t trained_function_type test_svm_multiclass_linear_trainer2::train(all_samples,all_labels)\"\r\n                << \"\\n\\t invalid inputs were given to this function\"\r\n                << \"\\n\\t all_samples.size():     \" << all_samples.size() \r\n                << \"\\n\\t all_labels.size():      \" << all_labels.size() \r\n                );\r\n\r\n            typedef matrix<scalar_type,0,1> w_type;\r\n            w_type weights;\r\n            std::vector<sample_type> samples1(all_samples.begin(), all_samples.begin()+all_samples.size()/2);\r\n            std::vector<sample_type> samples2(all_samples.begin()+all_samples.size()/2, all_samples.end());\r\n\r\n            std::vector<label_type> labels1(all_labels.begin(), all_labels.begin()+all_labels.size()/2);\r\n            std::vector<label_type> labels2(all_labels.begin()+all_labels.size()/2, all_labels.end());\r\n            test_multiclass_svm_problem<w_type, sample_type, label_type> problem1(samples1, labels1);\r\n            test_multiclass_svm_problem<w_type, sample_type, label_type> problem2(samples2, labels2);\r\n            problem1.set_max_cache_size(3);\r\n            problem2.set_max_cache_size(0);\r\n\r\n            svm_struct_processing_node node1(problem1, 12345, 3);\r\n            svm_struct_processing_node node2(problem2, 12346, 0);\r\n\r\n            solver.set_inactive_plane_threshold(50);\r\n            solver.set_subproblem_epsilon(1e-4);\r\n\r\n            svm_struct_controller_node controller;\r\n            controller.set_c(C);\r\n            controller.set_epsilon(eps);\r\n            if (verbose)\r\n                controller.be_verbose();\r\n            controller.add_processing_node(\"127.0.0.1\", 12345);\r\n            controller.add_processing_node(\"localhost:12346\");\r\n            svm_objective = controller(solver, weights);\r\n\r\n\r\n\r\n            trained_function_type df;\r\n\r\n            const long dims = max_index_plus_one(all_samples);\r\n            df.labels  = select_all_distinct_labels(all_labels);\r\n            df.weights = colm(reshape(weights, df.labels.size(), dims+1), range(0,dims-1));\r\n            df.b       = colm(reshape(weights, df.labels.size(), dims+1), dims);\r\n            return df;\r\n        }\r\n\r\n    private:\r\n        scalar_type C;\r\n        scalar_type eps;\r\n        bool verbose;\r\n        mutable oca solver;\r\n    };\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    template <\r\n        typename K,\r\n        typename label_type_ = typename K::scalar_type \r\n        >\r\n    class test_svm_multiclass_linear_trainer3\r\n    {\r\n    public:\r\n        typedef label_type_ label_type;\r\n        typedef K kernel_type;\r\n        typedef typename kernel_type::scalar_type scalar_type;\r\n        typedef typename kernel_type::sample_type sample_type;\r\n        typedef typename kernel_type::mem_manager_type mem_manager_type;\r\n\r\n        typedef multiclass_linear_decision_function<kernel_type, label_type> trained_function_type;\r\n\r\n\r\n        test_svm_multiclass_linear_trainer3 (\r\n        ) :\r\n            C(10),\r\n            eps(1e-4),\r\n            verbose(false)\r\n        {\r\n        }\r\n\r\n        trained_function_type train (\r\n            const std::vector<sample_type>& all_samples,\r\n            const std::vector<label_type>& all_labels\r\n        ) const\r\n        {\r\n            scalar_type svm_objective = 0;\r\n            return train(all_samples, all_labels, svm_objective);\r\n        }\r\n\r\n        trained_function_type train (\r\n            const std::vector<sample_type>& all_samples,\r\n            const std::vector<label_type>& all_labels,\r\n            scalar_type& svm_objective\r\n        ) const\r\n        {\r\n            // make sure requires clause is not broken\r\n            DLIB_ASSERT(is_learning_problem(all_samples,all_labels),\r\n                \"\\t trained_function_type test_svm_multiclass_linear_trainer3::train(all_samples,all_labels)\"\r\n                << \"\\n\\t invalid inputs were given to this function\"\r\n                << \"\\n\\t all_samples.size():     \" << all_samples.size() \r\n                << \"\\n\\t all_labels.size():      \" << all_labels.size() \r\n                );\r\n\r\n            typedef matrix<scalar_type,0,1> w_type;\r\n            w_type weights;\r\n            test_multiclass_svm_problem<w_type, sample_type, label_type> problem(all_samples, all_labels);\r\n            problem.set_max_cache_size(0);\r\n\r\n            problem.set_c(C);\r\n            problem.set_epsilon(eps);\r\n\r\n            if (verbose)\r\n                problem.be_verbose();\r\n            \r\n            solver.set_inactive_plane_threshold(50);\r\n            solver.set_subproblem_epsilon(1e-4);\r\n            svm_objective = solver(problem, weights);\r\n\r\n\r\n            trained_function_type df;\r\n\r\n            const long dims = max_index_plus_one(all_samples);\r\n            df.labels  = select_all_distinct_labels(all_labels);\r\n            df.weights = colm(reshape(weights, df.labels.size(), dims+1), range(0,dims-1));\r\n            df.b       = colm(reshape(weights, df.labels.size(), dims+1), dims);\r\n            return df;\r\n        }\r\n\r\n    private:\r\n        scalar_type C;\r\n        scalar_type eps;\r\n        bool verbose;\r\n        mutable oca solver;\r\n    };\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    template <\r\n        typename K,\r\n        typename label_type_ = typename K::scalar_type \r\n        >\r\n    class test_svm_multiclass_linear_trainer4\r\n    {\r\n    public:\r\n        typedef label_type_ label_type;\r\n        typedef K kernel_type;\r\n        typedef typename kernel_type::scalar_type scalar_type;\r\n        typedef typename kernel_type::sample_type sample_type;\r\n        typedef typename kernel_type::mem_manager_type mem_manager_type;\r\n\r\n        typedef multiclass_linear_decision_function<kernel_type, label_type> trained_function_type;\r\n\r\n\r\n        test_svm_multiclass_linear_trainer4 (\r\n        ) :\r\n            C(10),\r\n            eps(1e-4),\r\n            verbose(false)\r\n        {\r\n        }\r\n\r\n        trained_function_type train (\r\n            const std::vector<sample_type>& all_samples,\r\n            const std::vector<label_type>& all_labels\r\n        ) const\r\n        {\r\n            scalar_type svm_objective = 0;\r\n            return train(all_samples, all_labels, svm_objective);\r\n        }\r\n\r\n        trained_function_type train (\r\n            const std::vector<sample_type>& all_samples,\r\n            const std::vector<label_type>& all_labels,\r\n            scalar_type& svm_objective\r\n        ) const\r\n        {\r\n            // make sure requires clause is not broken\r\n            DLIB_ASSERT(is_learning_problem(all_samples,all_labels),\r\n                \"\\t trained_function_type test_svm_multiclass_linear_trainer4::train(all_samples,all_labels)\"\r\n                << \"\\n\\t invalid inputs were given to this function\"\r\n                << \"\\n\\t all_samples.size():     \" << all_samples.size() \r\n                << \"\\n\\t all_labels.size():      \" << all_labels.size() \r\n                );\r\n\r\n            typedef matrix<scalar_type,0,1> w_type;\r\n            w_type weights;\r\n            test_multiclass_svm_problem<w_type, sample_type, label_type> problem(all_samples, all_labels);\r\n            problem.set_max_cache_size(3);\r\n\r\n            problem.set_c(C);\r\n            problem.set_epsilon(eps);\r\n\r\n            if (verbose)\r\n                problem.be_verbose();\r\n            \r\n            solver.set_inactive_plane_threshold(50);\r\n            solver.set_subproblem_epsilon(1e-4);\r\n            svm_objective = solver(problem, weights);\r\n\r\n\r\n            trained_function_type df;\r\n\r\n            const long dims = max_index_plus_one(all_samples);\r\n            df.labels  = select_all_distinct_labels(all_labels);\r\n            df.weights = colm(reshape(weights, df.labels.size(), dims+1), range(0,dims-1));\r\n            df.b       = colm(reshape(weights, df.labels.size(), dims+1), dims);\r\n            return df;\r\n        }\r\n\r\n    private:\r\n        scalar_type C;\r\n        scalar_type eps;\r\n        bool verbose;\r\n        mutable oca solver;\r\n    };\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    template <\r\n        typename K,\r\n        typename label_type_ = typename K::scalar_type \r\n        >\r\n    class test_svm_multiclass_linear_trainer5\r\n    {\r\n    public:\r\n        typedef label_type_ label_type;\r\n        typedef K kernel_type;\r\n        typedef typename kernel_type::scalar_type scalar_type;\r\n        typedef typename kernel_type::sample_type sample_type;\r\n        typedef typename kernel_type::mem_manager_type mem_manager_type;\r\n\r\n        typedef multiclass_linear_decision_function<kernel_type, label_type> trained_function_type;\r\n\r\n\r\n        test_svm_multiclass_linear_trainer5 (\r\n        ) :\r\n            C(10),\r\n            eps(1e-4),\r\n            verbose(false)\r\n        {\r\n        }\r\n\r\n        trained_function_type train (\r\n            const std::vector<sample_type>& all_samples,\r\n            const std::vector<label_type>& all_labels\r\n        ) const\r\n        {\r\n            scalar_type svm_objective = 0;\r\n            return train(all_samples, all_labels, svm_objective);\r\n        }\r\n\r\n        trained_function_type train (\r\n            const std::vector<sample_type>& all_samples,\r\n            const std::vector<label_type>& all_labels,\r\n            scalar_type& svm_objective\r\n        ) const\r\n        {\r\n            // make sure requires clause is not broken\r\n            DLIB_ASSERT(is_learning_problem(all_samples,all_labels),\r\n                \"\\t trained_function_type test_svm_multiclass_linear_trainer5::train(all_samples,all_labels)\"\r\n                << \"\\n\\t invalid inputs were given to this function\"\r\n                << \"\\n\\t all_samples.size():     \" << all_samples.size() \r\n                << \"\\n\\t all_labels.size():      \" << all_labels.size() \r\n                );\r\n\r\n            typedef matrix<scalar_type,0,1> w_type;\r\n            w_type weights;\r\n            const long dims = max_index_plus_one(all_samples);\r\n            trained_function_type df;\r\n            df.labels  = select_all_distinct_labels(all_labels);\r\n            multiclass_svm_problem<w_type, sample_type, label_type> problem(all_samples, all_labels, df.labels, dims, 4);\r\n            problem.set_max_cache_size(3);\r\n\r\n            problem.set_c(C);\r\n            problem.set_epsilon(eps);\r\n\r\n            if (verbose)\r\n                problem.be_verbose();\r\n            \r\n            solver.set_inactive_plane_threshold(50);\r\n            solver.set_subproblem_epsilon(1e-4);\r\n            svm_objective = solver(problem, weights);\r\n\r\n\r\n\r\n            df.weights = colm(reshape(weights, df.labels.size(), dims+1), range(0,dims-1));\r\n            df.b       = colm(reshape(weights, df.labels.size(), dims+1), dims);\r\n            return df;\r\n        }\r\n\r\n    private:\r\n        scalar_type C;\r\n        scalar_type eps;\r\n        bool verbose;\r\n        mutable oca solver;\r\n    };\r\n\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    typedef matrix<double,10,1> sample_type;\r\n    typedef double scalar_type;\r\n\r\n    void make_dataset (\r\n        std::vector<sample_type>& samples,\r\n        std::vector<scalar_type>& labels,\r\n        int num,\r\n        dlib::rand& rnd\r\n    )\r\n    {\r\n        samples.clear();\r\n        labels.clear();\r\n        for (int i = 0; i < 10; ++i)\r\n        {\r\n            for (int j = 0; j < num; ++j)\r\n            {\r\n                sample_type samp;\r\n                samp = 0;\r\n                samp(i) = 10*rnd.get_random_double()+1;\r\n\r\n                samples.push_back(samp);\r\n                labels.push_back(i);\r\n            }\r\n        }\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    class test_svm_struct : public tester\r\n    {\r\n    public:\r\n        test_svm_struct (\r\n        ) :\r\n            tester (\"test_svm_struct\",\r\n                    \"Runs tests on the structural svm components.\")\r\n        {}\r\n\r\n        void run_test (\r\n            const std::vector<sample_type>& samples,\r\n            const std::vector<scalar_type>& labels,\r\n            const double true_obj\r\n        )\r\n        {\r\n            typedef linear_kernel<sample_type> kernel_type;\r\n            svm_multiclass_linear_trainer<kernel_type> trainer1;\r\n            test_svm_multiclass_linear_trainer2<kernel_type> trainer2;\r\n            test_svm_multiclass_linear_trainer3<kernel_type> trainer3;\r\n            test_svm_multiclass_linear_trainer4<kernel_type> trainer4;\r\n            test_svm_multiclass_linear_trainer5<kernel_type> trainer5;\r\n\r\n            trainer1.set_epsilon(1e-4);\r\n            trainer1.set_c(10);\r\n\r\n\r\n            multiclass_linear_decision_function<kernel_type,double> df1, df2, df3, df4, df5;\r\n            double obj1, obj2, obj3, obj4, obj5;\r\n\r\n            // Solve a multiclass SVM a whole bunch of different ways and make sure\r\n            // they all give the same answer.\r\n            print_spinner();\r\n            df1 = trainer1.train(samples, labels, obj1);\r\n            print_spinner();\r\n            df2 = trainer2.train(samples, labels, obj2);\r\n            print_spinner();\r\n            df3 = trainer3.train(samples, labels, obj3);\r\n            print_spinner();\r\n            df4 = trainer4.train(samples, labels, obj4);\r\n            print_spinner();\r\n            df5 = trainer5.train(samples, labels, obj5);\r\n            print_spinner();\r\n\r\n            dlog << LINFO << \"obj1: \"<< obj1;\r\n            dlog << LINFO << \"obj2: \"<< obj2;\r\n            dlog << LINFO << \"obj3: \"<< obj3;\r\n            dlog << LINFO << \"obj4: \"<< obj4;\r\n            dlog << LINFO << \"obj5: \"<< obj5;\r\n            DLIB_TEST(std::abs(obj1 - obj2) < 1e-2);\r\n            DLIB_TEST(std::abs(obj1 - obj3) < 1e-2);\r\n            DLIB_TEST(std::abs(obj1 - obj4) < 1e-2);\r\n            DLIB_TEST(std::abs(obj1 - obj5) < 1e-2);\r\n            DLIB_TEST(std::abs(obj1 - true_obj) < 1e-2);\r\n            DLIB_TEST(std::abs(obj2 - true_obj) < 1e-2);\r\n            DLIB_TEST(std::abs(obj3 - true_obj) < 1e-2);\r\n            DLIB_TEST(std::abs(obj4 - true_obj) < 1e-2);\r\n            DLIB_TEST(std::abs(obj5 - true_obj) < 1e-2);\r\n\r\n            dlog << LINFO << \"weight error: \"<< max(abs(df1.weights - df2.weights));\r\n            dlog << LINFO << \"weight error: \"<< max(abs(df1.weights - df3.weights));\r\n            dlog << LINFO << \"weight error: \"<< max(abs(df1.weights - df4.weights));\r\n            dlog << LINFO << \"weight error: \"<< max(abs(df1.weights - df5.weights));\r\n\r\n            DLIB_TEST(max(abs(df1.weights - df2.weights)) < 1e-2);\r\n            DLIB_TEST(max(abs(df1.weights - df3.weights)) < 1e-2);\r\n            DLIB_TEST(max(abs(df1.weights - df4.weights)) < 1e-2);\r\n            DLIB_TEST(max(abs(df1.weights - df5.weights)) < 1e-2);\r\n\r\n            dlog << LINFO << \"b error: \"<< max(abs(df1.b - df2.b));\r\n            dlog << LINFO << \"b error: \"<< max(abs(df1.b - df3.b));\r\n            dlog << LINFO << \"b error: \"<< max(abs(df1.b - df4.b));\r\n            dlog << LINFO << \"b error: \"<< max(abs(df1.b - df5.b));\r\n            DLIB_TEST(max(abs(df1.b - df2.b)) < 1e-2);\r\n            DLIB_TEST(max(abs(df1.b - df3.b)) < 1e-2);\r\n            DLIB_TEST(max(abs(df1.b - df4.b)) < 1e-2);\r\n            DLIB_TEST(max(abs(df1.b - df5.b)) < 1e-2);\r\n\r\n            matrix<double> res = test_multiclass_decision_function(df1, samples, labels);\r\n            dlog << LINFO << res;\r\n            dlog << LINFO << \"accuracy: \" << sum(diag(res))/sum(res);\r\n            DLIB_TEST(sum(diag(res)) == samples.size());\r\n\r\n            res = test_multiclass_decision_function(df2, samples, labels);\r\n            dlog << LINFO << res;\r\n            dlog << LINFO << \"accuracy: \" << sum(diag(res))/sum(res);\r\n            DLIB_TEST(sum(diag(res)) == samples.size());\r\n\r\n            res = test_multiclass_decision_function(df3, samples, labels);\r\n            dlog << LINFO << res;\r\n            dlog << LINFO << \"accuracy: \" << sum(diag(res))/sum(res);\r\n            DLIB_TEST(sum(diag(res)) == samples.size());\r\n\r\n            res = test_multiclass_decision_function(df4, samples, labels);\r\n            dlog << LINFO << res;\r\n            dlog << LINFO << \"accuracy: \" << sum(diag(res))/sum(res);\r\n            DLIB_TEST(sum(diag(res)) == samples.size());\r\n\r\n            res = test_multiclass_decision_function(df5, samples, labels);\r\n            dlog << LINFO << res;\r\n            dlog << LINFO << \"accuracy: \" << sum(diag(res))/sum(res);\r\n            DLIB_TEST(sum(diag(res)) == samples.size());\r\n        }\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            std::vector<sample_type> samples;\r\n            std::vector<scalar_type> labels;\r\n\r\n            dlib::rand rnd;\r\n\r\n            dlog << LINFO << \"test with 100 samples per class\";\r\n            make_dataset(samples, labels, 100, rnd);\r\n            run_test(samples, labels, 1.155);\r\n\r\n            dlog << LINFO << \"test with 1 sample per class\";\r\n            make_dataset(samples, labels, 1, rnd);\r\n            run_test(samples, labels, 0.251);\r\n\r\n            dlog << LINFO << \"test with 2 sample per class\";\r\n            make_dataset(samples, labels, 2, rnd);\r\n            run_test(samples, labels, 0.444);\r\n        }\r\n    } a;\r\n\r\n\r\n\r\n}\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "72c366e3d6ca59e4448d1a5440ca21bb2227a5b3", "size": 23248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/svm_struct.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": "dlib/test/svm_struct.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": "dlib/test/svm_struct.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": 36.2118380062, "max_line_length": 140, "alphanum_fraction": 0.5368203716, "num_tokens": 4961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6334102567576902, "lm_q1q2_score": 0.5087385205714738}}
{"text": "/*\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2014-2015, Timm Linder, Social Robotics Lab, University of Freiburg\n*  Copyright (c) 2006-2012, Matthias Luber, Luciano Spinello and Kai O. Arras, Social Robotics Laboratory and\n*    Oscar Martinez, Autonomous Intelligent Systems, University of Freiburg\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*  * 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*  * Neither the name of the copyright holder nor the names of its contributors\n*    may be used to endorse or promote products derived from this software\n*    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#include <srl_laser_features/features/feature06.h>\n\n#include <Eigen/LU>\n#include <Eigen/QR>\n#include <float.h>\n\n#define MATRIX_LN_EPS -1e8\n\n\nnamespace srl_laser_features {\n\nFeature06::Feature06(bool extended) : Feature(), m_extended(extended)\n{\n}\n\nvoid Feature06::evaluate(const Segment& segment, Eigen::VectorXd& result) const\n{\n\tresult = Eigen::VectorXd::Zero(getNDimensions());\n\n\tconst size_t numPoints = segment.points.size();\n\tif (numPoints > 2) {\n\n\t\tdouble px[numPoints];\n\t\tdouble py[numPoints];\n\n\t\t// copy\n\t\tfor (size_t pIndex = 0; pIndex < numPoints; ++pIndex) {\n\t\t\tpx[pIndex] = segment.points[pIndex](0);\n\t\t\tpy[pIndex] = segment.points[pIndex](1);\n\t\t}\n\n\t\tdouble xc, yc, rc;\n\t\tfitCircle(numPoints, px, py, xc, yc, rc);\n\n\t\tresult(1) = rc;\n\t\tif (m_extended) {\n\t\t\tresult(3) = DBL_MAX;\n\t\t\tresult(4) = 0.0;\n\t\t}\n\n\t\t// residual sum\n\t\tEigen::Vector2d centerOfCircle(xc, yc);\n\n\t\tdouble residual;\n\t\tfor (size_t pIndex = 0; pIndex < numPoints; ++pIndex) {\n\t\t\tdouble dist = (centerOfCircle - segment.points[pIndex]).norm();\n\n\t\t\tif (m_extended) {\n\t\t\t\tif (dist < result(3)) {\n\t\t\t\t\tresult(3) = dist;\n\t\t\t\t}\n\t\t\t\tif (dist > result(4)) {\n\t\t\t\t\tresult(4) = dist;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresidual = rc - dist;\n\t\t\tresult(0) += residual * residual;\n\t\t}\n\n\t\tif (m_extended) {\n\t\t\tresult(2) = result(0) / (numPoints - 1);\n\t\t\tif (result(4) != 0.0) {\n\t\t\t\tresult(5) = result(3) / result(4);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nint Feature06::fitCircle(int n, double *x_vec, double *y_vec, double& xc, double& yc, double& r)\n{\n\tint i;\n\n\tif (n > 3) {\n\t\tEigen::MatrixXd A(n, 3);\n\t\tEigen::MatrixXd X(3, 1);\n\t\tEigen::MatrixXd B(n, 3);\n\t\tEigen::MatrixXd P(3, n);\n\t\tEigen::MatrixXd T(3, 3);\n\n\t\t// We want the overdetermined linear equation system Ax = b\n\t\t// Fill in matrix A\n\t\tfor (i = 0; i < n; i++) {\n\t\t\tA(i, 0) = -2 * x_vec[i];\n\t\t\tA(i, 1) = -2 * y_vec[i];\n\t\t\tA(i, 2) = 1.0;\n\t\t}\n\n\t\t// Fill in vector b\n\t\tfor (i = 0; i < n; i++) {\n\t\t\tB(i, 0) = -(x_vec[i] * x_vec[i] + y_vec[i] * y_vec[i]);\n\t\t}\n\n\t\t// Now we have the equation system with n equations and 3 unknowns.\n\t\t// The LSQ-solution is given by the pseudo-inverse:\n\t\tP = A.transpose();\n\t\tT = P * A;\n\t\tEigen::FullPivLU<Eigen::MatrixXd> lu(T);\n\t\tif (lu.isInvertible()) {\n\t\t\tif (log(lu.determinant()) > MATRIX_LN_EPS) {\n\t\t\t\tX = lu.inverse() * P * B;\n\t\t\t\t// Extract circle center and radius\n\t\t\t\txc = X(0, 0);\n\t\t\t\tyc = X(1, 0);\n\t\t\t\tr = sqrt(-X(2, 0) + xc * xc + yc * yc);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Points badly conditioned (n > 3)\n\t\t\t\treturn -3;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// try QR\n\t\t\tEigen::FullPivHouseholderQR<Eigen::MatrixXd> QR(A);\n\t\t\tX = QR.solve(B);\n\n\t\t\t// Extract circle center and radius\n\t\t\txc = X(0, 0);\n\t\t\tyc = X(1, 0);\n\t\t\tr = sqrt(-X(2, 0) + xc * xc + yc * yc);\n\t\t\treturn 1;\n\t\t}\n\t}\n\telse if (n == 3) {\n\t\tdouble a, b, c, d, e, f, g;\n\n\t\ta = x_vec[1] - x_vec[0];\n\t\tb = y_vec[1] - y_vec[0];\n\t\tc = x_vec[2] - x_vec[0];\n\t\td = y_vec[2] - y_vec[0];\n\t\te = a * (x_vec[0] + x_vec[1]) + b * (y_vec[0] + y_vec[1]);\n\t\tf = c * (x_vec[0] + x_vec[2]) + d * (y_vec[0] + y_vec[2]);\n\t\tg = 2 * (a * (y_vec[2] - y_vec[1]) - b * (x_vec[2] - x_vec[1]));\n\n\t\tif (g != 0.0) {\n\t\t\txc = (d * e - b * f) / g;\n\t\t\tyc = (a * f - c * e) / g;\n\t\t\tr = sqrt((x_vec[0] - xc) * (x_vec[0] - xc) + (y_vec[0] - yc) * (y_vec[0] - yc));\n\t\t\treturn 2;\n\t\t}\n\t\telse {\n\t\t\t// Points badly conditioned (n == 3)\n\t\t\treturn -2;\n\t\t}\n\t}\n\telse {\n\t\t// Too few points\n\t\txc = 0.0;\n\t\tyc = 0.0;\n\t\tr = -1.0;\n\t\treturn -1;\n\t}\n}\n\n} // end of namespace srl_laser_features\n", "meta": {"hexsha": "3c2f149a4e2d02c490ce1837a3a81adeab6a7854", "size": 5255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/spencer_people_tracking/detection/laser_detectors/srl_laser_features/src/srl_laser_features/features/feature06.cpp", "max_stars_repo_name": "CodeToPoem/HumanAwareRobotNavigation", "max_stars_repo_head_hexsha": "d44eb7e5acd73a5a7bf8bf1cd88c23d6a4a3c330", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-10-26T05:58:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-13T11:18:54.000Z", "max_issues_repo_path": "src/spencer_people_tracking/detection/laser_detectors/srl_laser_features/src/srl_laser_features/features/feature06.cpp", "max_issues_repo_name": "dmr-goncalves/HumanAwareRobotNavigation", "max_issues_repo_head_hexsha": "d44eb7e5acd73a5a7bf8bf1cd88c23d6a4a3c330", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spencer_people_tracking/detection/laser_detectors/srl_laser_features/src/srl_laser_features/features/feature06.cpp", "max_forks_repo_name": "dmr-goncalves/HumanAwareRobotNavigation", "max_forks_repo_head_hexsha": "d44eb7e5acd73a5a7bf8bf1cd88c23d6a4a3c330", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-02-05T09:31:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T22:05:57.000Z", "avg_line_length": 27.6578947368, "max_line_length": 109, "alphanum_fraction": 0.6306374881, "num_tokens": 1721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5087215110912588}}
{"text": "/**\n * \\file\n * \\copyright\n * Copyright (c) 2012-2020, 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 <boost/math/constants/constants.hpp>\n#include <cmath>\n#include <memory>\n#include <numeric>\n#include <random>\n\n#include \"MeshLib/Elements/Element.h\"\n#include \"MeshLib/Mesh.h\"\n#include \"MeshLib/MeshGenerators/MeshGenerator.h\"\n#include \"MeshLib/MeshQuality/ElementQualityInterface.h\"\n#include \"MeshLib/Node.h\"\n#include \"gtest/gtest.h\"\n\nclass TriElementQuality : public ::testing::Test\n{\npublic:\n    TriElementQuality()\n    {\n        std::random_device rd;\n        std::mt19937 gen(rd());\n        std::uniform_int_distribution<> distrib(1, 10);\n\n        lengths = {1, 1};\n        n_subdivisions = {distrib(gen), distrib(gen)};\n    }\n\n    std::vector<double> getElementQualityVectorFromRegularTriMesh(\n        MeshLib::MeshQualityType const type)\n    {\n        std::vector<std::unique_ptr<BaseLib::ISubdivision>> vec_div;\n        for (int i = 0; i < 2; ++i)\n        {\n            vec_div.emplace_back(\n                new BaseLib::UniformSubdivision(lengths[i], n_subdivisions[i]));\n        }\n\n        std::unique_ptr<MeshLib::Mesh> mesh(\n            MeshLib::MeshGenerator::generateRegularTriMesh(*vec_div[0],\n                                                           *vec_div[1]));\n        MeshLib::ElementQualityInterface element_quality(*mesh, type);\n        return element_quality.getQualityVector();\n    }\n\n    std::array<int, 2> lengths;\n    std::array<int, 2> n_subdivisions;\n};\n\nTEST_F(TriElementQuality, ElementSize)\n{\n    auto const type = MeshLib::MeshQualityType::ELEMENTSIZE;\n    auto const element_quality_vector =\n        getElementQualityVectorFromRegularTriMesh(type);\n    auto const expected_value =\n        0.5 / std::accumulate(n_subdivisions.begin(), n_subdivisions.end(), 1,\n                              std::multiplies<int>());\n    for (auto const element_quality : element_quality_vector)\n    {\n        ASSERT_NEAR(expected_value, element_quality,\n                    std::numeric_limits<double>::epsilon());\n    }\n}\n\nTEST_F(TriElementQuality, SizeDifference)\n{\n    auto const type = MeshLib::MeshQualityType::SIZEDIFFERENCE;\n    auto const element_quality_vector =\n        getElementQualityVectorFromRegularTriMesh(type);\n    // all elements have the same size, the quality value has to be 1.0\n    auto constexpr expected_value = 1.0;\n    for (auto const element_quality : element_quality_vector)\n    {\n        ASSERT_NEAR(expected_value, element_quality,\n                    10 * std::numeric_limits<double>::epsilon());\n    }\n}\n\nTEST_F(TriElementQuality, EdgeRatio)\n{\n    auto const type = MeshLib::MeshQualityType::EDGERATIO;\n    auto const element_quality_vector =\n        getElementQualityVectorFromRegularTriMesh(type);\n    auto const& min_max =\n        std::minmax_element(n_subdivisions.begin(), n_subdivisions.end());\n    auto const expected_value =\n        double(*min_max.first) / std::sqrt(*min_max.first * *min_max.first +\n                                      *min_max.second * *min_max.second);\n    for (auto const element_quality : element_quality_vector)\n    {\n        ASSERT_NEAR(expected_value, element_quality,\n                    10 * std::numeric_limits<double>::epsilon());\n    }\n}\n\nTEST_F(TriElementQuality, EquiAngleSkew)\n{\n    using namespace boost::math::double_constants;\n    auto const type = MeshLib::MeshQualityType::EQUIANGLESKEW;\n    auto const element_quality_vector =\n        getElementQualityVectorFromRegularTriMesh(type);\n    // all triangles are right-angled triangles\n    auto const hypothenuse = std::sqrt(std::pow(1.0 / n_subdivisions[0], 2) +\n                                       std::pow(1.0 / n_subdivisions[1], 2));\n    std::array const angles = {\n        std::asin((1.0 / n_subdivisions[0]) / hypothenuse),\n        std::asin((1.0 / n_subdivisions[1]) / hypothenuse), half_pi};\n    auto const& min_max = std::minmax_element(angles.begin(), angles.end());\n    auto const expected_value =\n        std::max((*min_max.second - third_pi) / two_thirds_pi,\n                 (third_pi - *min_max.first) / third_pi);\n\n    for (auto const element_quality : element_quality_vector)\n    {\n        ASSERT_NEAR(expected_value, element_quality,\n                    10 * std::numeric_limits<double>::epsilon());\n    }\n}\n", "meta": {"hexsha": "15fbfc4e5eb103e90ae6e48d4d54336652d08f78", "size": 4460, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/MeshLib/TestTriQualityCriteria.cpp", "max_stars_repo_name": "yezhigangzju/ogs", "max_stars_repo_head_hexsha": "074c5129680e87516477708b081afe79facabe87", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-24T02:38:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-24T02:38:44.000Z", "max_issues_repo_path": "Tests/MeshLib/TestTriQualityCriteria.cpp", "max_issues_repo_name": "yezhigangzju/ogs", "max_issues_repo_head_hexsha": "074c5129680e87516477708b081afe79facabe87", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/MeshLib/TestTriQualityCriteria.cpp", "max_forks_repo_name": "yezhigangzju/ogs", "max_forks_repo_head_hexsha": "074c5129680e87516477708b081afe79facabe87", "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.3968253968, "max_line_length": 80, "alphanum_fraction": 0.6470852018, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5087215110912588}}
{"text": "#include \"cpu/image_proc.h\"\r\n\r\n#include <Eigen/Dense>\r\n#include <map>\r\n#include <string>\r\n#include <cmath>\r\n#include <stdexcept>\r\n\r\nnamespace helper {\r\n\r\nbool in_bounds(Eigen::Vector2f p, int h, int w) {\r\n\treturn p.x() >= 0.0 && p.x() < static_cast<float>(w) && p.y() >= 0.0 && p.y() < static_cast<float>(h);\r\n}\r\n\r\nbool valid_flow_at(const Eigen::Vector2f& p, int h, int w, py::array_t<float>& flow_image, Eigen::Vector2f& flow) {\r\n\tif (!in_bounds(p, h, w)) {\r\n\t\treturn false;\r\n\t}\r\n\r\n\tflow.x() = *flow_image.data(p.y(), p.x(), 0);\r\n\tflow.y() = *flow_image.data(p.y(), p.x(), 1);\r\n\r\n\tif (!flow.allFinite()) {\r\n\t\treturn false;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n} // namespace helper\r\n\r\nnamespace image_proc {\r\n\r\nusing Vec2f = Eigen::Vector2f;\r\n\r\ntemplate<class V, class L = std::less<std::string>,\r\n\t\tclass A = Eigen::aligned_allocator<std::pair<const std::string, V>>>\r\nusing aligned_dict = std::map<std::string, V, L, A>;\r\n\r\npy::array_t<float> compute_augmented_flow_from_rotation(py::array_t<float>& flow_image_rot_sa2so,\r\n                                                        py::array_t<float>& flow_image_so2to,\r\n                                                        py::array_t<float>& flow_image_rot_to2ta,\r\n                                                        const int height, const int width) {\r\n\t// TODO: change to runtime asserts\r\n\t// assert(flow_image_rot_sa2so.ndim() == 3);\r\n\t// assert(flow_image_rot_sa2so.shape(0) == 2);\r\n\t// assert(flow_image_rot_sa2so.shape(1) == height);\r\n\t// assert(flow_image_rot_sa2so.shape(2) == width);\r\n\r\n\t// assert(flow_image_so2to.ndim() == 3);\r\n\t// assert(flow_image_so2to.shape(0) == 2);\r\n\t// assert(flow_image_so2to.shape(1) == height);\r\n\t// assert(flow_image_so2to.shape(2) == width);\r\n\r\n\t// assert(flow_image_rot_to2ta.ndim() == 3);\r\n\t// assert(flow_image_rot_to2ta.shape(0) == 2);\r\n\t// assert(flow_image_rot_to2ta.shape(1) == height);\r\n\t// assert(flow_image_rot_to2ta.shape(2) == width);\r\n\r\n\t// allocate memory for output array\r\n\tpy::array_t<float> flow_image_rot_sa2ta = py::array_t<float>(flow_image_rot_sa2so.request().size);\r\n\r\n\t// reshape array to match input shape\r\n\tflow_image_rot_sa2ta.resize({height, width, 2});\r\n\r\n\tfor (int y = 0; y < height; y++) {\r\n\t\tfor (int x = 0; x < width; x++) {\r\n\r\n\t\t\t// update output flow image\r\n\t\t\t*flow_image_rot_sa2ta.mutable_data(y, x, 0) = -std::numeric_limits<float>::infinity();\r\n\t\t\t*flow_image_rot_sa2ta.mutable_data(y, x, 1) = -std::numeric_limits<float>::infinity();\r\n\r\n\t\t\tVec2f p_sa(x, y);\r\n\r\n\t\t\t/////////////////////////////////////////////////////////////////////////////////\r\n\t\t\t// 1. SOURCE AUGMENTED TO SOURCE ORIGINAL\r\n\t\t\t/////////////////////////////////////////////////////////////////////////////////\r\n\r\n\t\t\t// flow from source augmented to source original\r\n\t\t\tVec2f flow_sa2so(*flow_image_rot_sa2so.data(y, x, 0), *flow_image_rot_sa2so.data(y, x, 1));\r\n\r\n\t\t\t// flow_sa2so should be dense and w/o any invalid value\r\n\t\t\tif (!flow_sa2so.allFinite()) {\r\n\t\t\t\tthrow std::runtime_error(\"flow_sa2so should be dense and w/o any invalid residuals!\");\r\n\t\t\t}\r\n\r\n\t\t\t// compute warped location on source original (so we're going from source augmented to source original)\r\n\t\t\tVec2f p_so = p_sa + flow_sa2so;\r\n\r\n\t\t\t// init flow_sa2ta with the first contribution, i.e, flow_sa2so\r\n\t\t\tVec2f flow_sa2ta = flow_sa2so;\r\n\r\n\t\t\t/////////////////////////////////////////////////////////////////////////////////\r\n\t\t\t// 2. SOURCE ORIGINAL TO TARGET ORIGINAL\r\n\t\t\t/////////////////////////////////////////////////////////////////////////////////\r\n\t\t\tint u0 = std::floor(p_so.x());\r\n\t\t\tint u1 = u0 + 1;\r\n\t\t\tint v0 = std::floor(p_so.y());\r\n\t\t\tint v1 = v0 + 1;\r\n\r\n\t\t\tVec2f p00(u0, v0);\r\n\t\t\tVec2f p01(u0, v1);\r\n\t\t\tVec2f p10(u1, v0);\r\n\t\t\tVec2f p11(u1, v1);\r\n\r\n\t\t\taligned_dict<Vec2f> valid_coords;\r\n\t\t\taligned_dict<Vec2f> valid_flows;\r\n\r\n\t\t\tVec2f flow_00_so2to;\r\n\t\t\tif (helper::valid_flow_at(p00, height, width, flow_image_so2to, flow_00_so2to)) {\r\n\t\t\t\tvalid_coords[\"p00\"] = p00;\r\n\t\t\t\tvalid_flows[\"p00\"] = flow_00_so2to;\r\n\t\t\t}\r\n\r\n\t\t\tVec2f flow_01_so2to;\r\n\t\t\tif (helper::valid_flow_at(p01, height, width, flow_image_so2to, flow_01_so2to)) {\r\n\t\t\t\tvalid_coords[\"p01\"] = p01;\r\n\t\t\t\tvalid_flows[\"p01\"] = flow_01_so2to;\r\n\t\t\t}\r\n\r\n\t\t\tVec2f flow_10_so2to;\r\n\t\t\tif (helper::valid_flow_at(p10, height, width, flow_image_so2to, flow_10_so2to)) {\r\n\t\t\t\tvalid_coords[\"p10\"] = p10;\r\n\t\t\t\tvalid_flows[\"p10\"] = flow_10_so2to;\r\n\t\t\t}\r\n\r\n\t\t\tVec2f flow_11_so2to;\r\n\t\t\tif (helper::valid_flow_at(p11, height, width, flow_image_so2to, flow_11_so2to)) {\r\n\t\t\t\tvalid_coords[\"p11\"] = p11;\r\n\t\t\t\tvalid_flows[\"p11\"] = flow_11_so2to;\r\n\t\t\t}\r\n\r\n\t\t\t// Depending on how many valid flows we have, do bilinear interpolation or nearest neighbor:\r\n\t\t\tVec2f flow_so2to;\r\n\r\n\t\t\tif (valid_coords.empty()) {\r\n\t\t\t\tcontinue;\r\n\t\t\t} else if (valid_coords.size() == 4) {\r\n\t\t\t\t// Bilinear interpolation\r\n\t\t\t\tfloat du = p_so.x() - static_cast<float>(u0);\r\n\t\t\t\tfloat dv = p_so.y() - static_cast<float>(v0);\r\n\r\n\t\t\t\tfloat w00 = (1 - du) * (1 - dv);\r\n\t\t\t\tfloat w01 = (1 - du) * dv;\r\n\t\t\t\tfloat w10 = du * (1 - dv);\r\n\t\t\t\tfloat w11 = du * dv;\r\n\r\n\t\t\t\tflow_so2to = w00 * valid_flows[\"p00\"] +\r\n\t\t\t\t             w01 * valid_flows[\"p01\"] +\r\n\t\t\t\t             w10 * valid_flows[\"p10\"] +\r\n\t\t\t\t             w11 * valid_flows[\"p11\"];\r\n\t\t\t} else {\r\n\t\t\t\t// Nearest Neighbor\r\n\t\t\t\tstd::string nn = \"None\";\r\n\t\t\t\tfloat min_dist = std::numeric_limits<float>::max();\r\n\r\n\t\t\t\tfor (const auto& valid_coord : valid_coords) {\r\n\t\t\t\t\tconst std::string k = valid_coord.first;\r\n\t\t\t\t\tconst Vec2f& p = valid_coord.second;\r\n\r\n\t\t\t\t\tfloat dist = (p_so - p).norm();\r\n\t\t\t\t\tif (dist < min_dist) {\r\n\t\t\t\t\t\tmin_dist = dist;\r\n\t\t\t\t\t\tnn = k;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (nn == \"None\") {\r\n\t\t\t\t\tthrow std::runtime_error(\"Neighrest Neighbor 'nn' was not assigned...\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tflow_so2to = valid_flows[nn];\r\n\t\t\t}\r\n\r\n\t\t\t// compute warped location on target original (so we're going from source original to target original)\r\n\t\t\tVec2f p_to = p_so + flow_so2to;\r\n\r\n\t\t\t// add flow_so2to to flow_sa2ta\r\n\t\t\tflow_sa2ta += flow_so2to;\r\n\r\n\t\t\t/////////////////////////////////////////////////////////////////////////////////\r\n\t\t\t// 3. TARGET ORIGINAL TO TARGET AUGMENTED\r\n\t\t\t/////////////////////////////////////////////////////////////////////////////////\r\n\t\t\tu0 = std::floor(p_to.x());\r\n\t\t\tu1 = u0 + 1;\r\n\t\t\tv0 = std::floor(p_to.y());\r\n\t\t\tv1 = v0 + 1;\r\n\r\n\t\t\tp00 = Vec2f(u0, v0);\r\n\t\t\tp01 = Vec2f(u0, v1);\r\n\t\t\tp10 = Vec2f(u1, v0);\r\n\t\t\tp11 = Vec2f(u1, v1);\r\n\r\n\t\t\tvalid_coords.clear();\r\n\t\t\tvalid_flows.clear();\r\n\r\n\t\t\tVec2f flow_00_to2ta;\r\n\t\t\tif (helper::valid_flow_at(p00, height, width, flow_image_rot_to2ta, flow_00_to2ta)) {\r\n\t\t\t\tvalid_coords[\"p00\"] = p00;\r\n\t\t\t\tvalid_flows[\"p00\"] = flow_00_to2ta;\r\n\t\t\t}\r\n\r\n\t\t\tVec2f flow_01_to2ta;\r\n\t\t\tif (helper::valid_flow_at(p01, height, width, flow_image_rot_to2ta, flow_01_to2ta)) {\r\n\t\t\t\tvalid_coords[\"p01\"] = p01;\r\n\t\t\t\tvalid_flows[\"p01\"] = flow_01_to2ta;\r\n\t\t\t}\r\n\r\n\t\t\tVec2f flow_10_to2ta;\r\n\t\t\tif (helper::valid_flow_at(p10, height, width, flow_image_rot_to2ta, flow_10_to2ta)) {\r\n\t\t\t\tvalid_coords[\"p10\"] = p10;\r\n\t\t\t\tvalid_flows[\"p10\"] = flow_10_to2ta;\r\n\t\t\t}\r\n\r\n\t\t\tVec2f flow_11_to2ta;\r\n\t\t\tif (helper::valid_flow_at(p11, height, width, flow_image_rot_to2ta, flow_11_to2ta)) {\r\n\t\t\t\tvalid_coords[\"p11\"] = p11;\r\n\t\t\t\tvalid_flows[\"p11\"] = flow_11_to2ta;\r\n\t\t\t}\r\n\r\n\t\t\t// Depending on how many valid flows we have, do bilinear interpolation or nearest neighbor:\r\n\t\t\tVec2f flow_to2ta;\r\n\r\n\t\t\tif (valid_coords.empty()) {\r\n\t\t\t\tcontinue;\r\n\t\t\t} else if (valid_coords.size() == 4) {\r\n\t\t\t\t// Bilinear interpolation\r\n\t\t\t\tfloat du = p_to.x() - static_cast<float>(u0);\r\n\t\t\t\tfloat dv = p_to.y() - static_cast<float>(v0);\r\n\r\n\t\t\t\tfloat w00 = (1 - du) * (1 - dv);\r\n\t\t\t\tfloat w01 = (1 - du) * dv;\r\n\t\t\t\tfloat w10 = du * (1 - dv);\r\n\t\t\t\tfloat w11 = du * dv;\r\n\r\n\t\t\t\tflow_to2ta = w00 * valid_flows[\"p00\"] +\r\n\t\t\t\t             w01 * valid_flows[\"p01\"] +\r\n\t\t\t\t             w10 * valid_flows[\"p10\"] +\r\n\t\t\t\t             w11 * valid_flows[\"p11\"];\r\n\t\t\t} else {\r\n\t\t\t\t// Nearest Neighbor\r\n\t\t\t\tstd::string nn = \"None\";\r\n\t\t\t\tfloat min_dist = std::numeric_limits<float>::max();\r\n\r\n\t\t\t\tfor (const auto& valid_coord : valid_coords) {\r\n\t\t\t\t\tconst std::string k = valid_coord.first;\r\n\t\t\t\t\tconst Vec2f& p = valid_coord.second;\r\n\r\n\t\t\t\t\tfloat dist = (p_to - p).norm();\r\n\t\t\t\t\tif (dist < min_dist) {\r\n\t\t\t\t\t\tmin_dist = dist;\r\n\t\t\t\t\t\tnn = k;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (nn == \"None\") {\r\n\t\t\t\t\tthrow std::runtime_error(\"Neighrest Neighbor 'nn' was not assigned...\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tflow_to2ta = valid_flows[nn];\r\n\t\t\t}\r\n\r\n\t\t\t// add flow_to2ta to flow_sa2ta\r\n\t\t\tflow_sa2ta += flow_to2ta;\r\n\r\n\t\t\t// update output flow image\r\n\t\t\t*flow_image_rot_sa2ta.mutable_data(y, x, 0) = flow_sa2ta.x();\r\n\t\t\t*flow_image_rot_sa2ta.mutable_data(y, x, 1) = flow_sa2ta.y();\r\n\t\t}\r\n\t}\r\n\r\n\treturn flow_image_rot_sa2ta;\r\n}\r\n\r\nstatic inline bool has_immediate_true_z_neighbors(const int& index, const int& z, const int& z_bound, const py::array_t<bool>& array) {\r\n\tauto z_in_range = [&z_bound](int neighbor_z) { return neighbor_z > 0 && neighbor_z < z_bound; };\r\n\tauto value_if_in_range_or_zero = [&z, &index, &z_in_range, &array](int delta_z) {\r\n\t\treturn z_in_range(z + delta_z) ? *array.data(index, z + delta_z) : 0;\r\n\t};\r\n\treturn value_if_in_range_or_zero(-1) || value_if_in_range_or_zero(0) || value_if_in_range_or_zero(1);\r\n}\r\n\r\nint count_tp1(py::array_t<bool>& p, py::array_t<bool>& gt) {\r\n\tassert(p.ndim() == 2);\r\n\tassert(gt.ndim() == 2);\r\n\tconst int n_batch = p.shape(0);\r\n\tconst int dimz = p.shape(1);\r\n\r\n\tauto& ptr = p;\r\n\tint counter = 0;\r\n\tfor (int i = 0; i < n_batch; i++) {\r\n\t\tfor (int z = 0; z < dimz; z++) {\r\n\t\t\tif (*gt.data(i, z)) {\r\n\t\t\t\tcounter += has_immediate_true_z_neighbors(i, z, dimz, p);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn counter;\r\n}\r\n\r\nint count_tp2(py::array_t<bool>& p, py::array_t<bool>& gt) {\r\n\tassert(p.ndim() == 4);\r\n\tassert(gt.ndim() == 4);\r\n\tconst int n_batch = p.shape(0);\r\n\tassert(p.shape(1) == 1);\r\n\tconst int height = p.shape(2);\r\n\tconst int width = p.shape(3);\r\n\r\n\tauto& ptr = p;\r\n\tint counter = 0;\r\n\tfor (int i = 0; i < n_batch; i++)\r\n\t\tfor (int y = 0; y < height; y++)\r\n\t\t\tfor (int x = 0; x < width; x++) {\r\n\t\t\t\tif (*gt.data(i, 0, y, x)) {\r\n\t\t\t\t\tcounter += CHECK2();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\treturn counter;\r\n}\r\n\r\nint count_tp3(py::array_t<bool>& p, py::array_t<bool>& gt) {\r\n\tassert(p.ndim() == 5);\r\n\tassert(gt.ndim() == 5);\r\n\tconst int n_batch = p.shape(0);\r\n\tassert(p.shape(1) == 1);\r\n\tconst int dimz = p.shape(2);\r\n\tconst int dimy = p.shape(3);\r\n\tconst int dimx = p.shape(4);\r\n\r\n\tauto& ptr = p;\r\n\tint counter = 0;\r\n\tfor (int i = 0; i < n_batch; i++)\r\n\t\tfor (int z = 0; z < dimz; z++)\r\n\t\t\tfor (int y = 0; y < dimy; y++)\r\n\t\t\t\tfor (int x = 0; x < dimx; x++) {\r\n\t\t\t\t\tif (*gt.data(i, 0, z, y, x)) {\r\n\t\t\t\t\t\tcounter += CHECK3();\r\n\t\t\t\t\t\t//printf(\"i %d x %d y %d z %d in %d\\n\", i, x, y, z, res);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\treturn counter;\r\n}\r\n\r\nvoid extend3(py::array_t<bool>& in, py::array_t<bool>& out) {\r\n\tassert(in.ndim() == 5);\r\n\tassert(out.ndim() == 5);\r\n\tint n_batch = in.shape(0);\r\n\tassert(in.shape(1) == 1);\r\n\tint dimz = in.shape(2);\r\n\tint dimy = in.shape(3);\r\n\tint dimx = in.shape(4);\r\n\r\n\tauto& ptr = in;\r\n\tfor (int i = 0; i < n_batch; i++) {\r\n\t\tfor (int z = 1; z < dimz - 1; z++) {\r\n\t\t\tfor (int y = 1; y < dimy - 1; y++) {\r\n\t\t\t\tfor (int x = 1; x < dimx - 1; x++) {\r\n\t\t\t\t\t*out.mutable_data(i, 0, z, y, x) = CHECK3();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid backproject_depth_ushort(py::array_t<unsigned short>& image_in, py::array_t<float>& point_image_out,\r\n                              const float fx, const float fy, const float cx, const float cy, const float normalizer) {\r\n\tassert(image_in.ndim() == 2);\r\n\tassert(point_image_out.ndim() == 3);\r\n\r\n\tconst int width = image_in.shape(1);\r\n\tconst int height = image_in.shape(0);\r\n\r\n\tassert(point_image_out.shape(0) == height);\r\n\tassert(point_image_out.shape(1) == width);\r\n\tassert(point_image_out.shape(2) == 3);\r\n\r\n#pragma omp parallel for default(none) shared(image_in, point_image_out) firstprivate(height, width, fx, fy, cx, cy, normalizer)\r\n\tfor (int y = 0; y < height; y++) {\r\n\t\tfor (int x = 0; x < width; x++) {\r\n\t\t\tfloat depth = float(*image_in.data(y, x)) / normalizer;\r\n\r\n\t\t\tif (depth > 0) {\r\n\t\t\t\tfloat pos_x = depth * (static_cast<float>(x) - cx) / fx;\r\n\t\t\t\tfloat pos_y = depth * (static_cast<float>(y) - cy) / fy;\r\n\t\t\t\tfloat pos_z = depth;\r\n\r\n\t\t\t\t*point_image_out.mutable_data(y, x, 0) = pos_x;\r\n\t\t\t\t*point_image_out.mutable_data(y, x, 1) = pos_y;\r\n\t\t\t\t*point_image_out.mutable_data(y, x, 2) = pos_z;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\npy::array_t<float> backproject_depth_ushort(py::array_t<unsigned short>& image_in, float fx, float fy, float cx, float cy, float normalizer) {\r\n\tpy::array_t<float> point_image_out({image_in.shape(0), image_in.shape(1), static_cast<ssize_t>(3)});\r\n\tmemset(point_image_out.mutable_data(0, 0, 0), 0, point_image_out.size() * sizeof(float));\r\n\tbackproject_depth_ushort(image_in, point_image_out, fx, fy, cx, cy, normalizer);\r\n\treturn point_image_out;\r\n}\r\n\r\nvoid backproject_depth_float(py::array_t<float>& image_in, py::array_t<float>& point_image_out,\r\n                             float fx, float fy, float cx, float cy) {\r\n\tassert(image_in.ndim() == 2);\r\n\tassert(point_image_out.ndim() == 3);\r\n\r\n\tint width = image_in.shape(1);\r\n\tint height = image_in.shape(0);\r\n\tassert(point_image_out.shape(0) == 3);\r\n\tassert(point_image_out.shape(1) == height);\r\n\tassert(point_image_out.shape(2) == width);\r\n\r\n#pragma omp parallel for default(none) shared(image_in, point_image_out) firstprivate(height, width, fx, fy, cx, cy)\r\n\tfor (int y = 0; y < height; y++) {\r\n\t\tfor (int x = 0; x < width; x++) {\r\n\t\t\tfloat depth = *image_in.data(y, x);\r\n\r\n\t\t\tif (depth > 0) {\r\n\t\t\t\tfloat pos_x = depth * (static_cast<float>(x) - cx) / fx;\r\n\t\t\t\tfloat pos_y = depth * (static_cast<float>(y) - cy) / fy;\r\n\t\t\t\tfloat pos_z = depth;\r\n\r\n\t\t\t\t*point_image_out.mutable_data(y, x, 0) = pos_x;\r\n\t\t\t\t*point_image_out.mutable_data(y, x, 1) = pos_y;\r\n\t\t\t\t*point_image_out.mutable_data(y, x, 2) = pos_z;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid compute_mesh_from_depth(const py::array_t<float>& point_image_in, float max_triangle_edge_distance,\r\n                             py::array_t<float>& vertex_positions_out, py::array_t<int>& vertex_pixels_out,\r\n                             py::array_t<int>& face_indices_out) {\r\n\tassert(point_image_in.ndim() == 3);\r\n\tassert(point_image_in.shape(2) == 3);\r\n\r\n\tint width = static_cast<int>(point_image_in.shape(1));\r\n\tint height = static_cast<int>(point_image_in.shape(0));\r\n\r\n\t// Compute valid pixel vertices and faces.\r\n\t// We also need to compute the pixel -> vertex index mapping for\r\n\t// computation of faces.\r\n\t// We connect neighboring pixels on the square into two triangles.\r\n\t// We only select valid triangles, i.e. with all valid vertices and\r\n\t// not too far apart.\r\n\t// Important: The triangle orientation is set such that the normals\r\n\t// point towards the camera.\r\n\tstd::vector<Eigen::Vector3f> vertices;\r\n\tstd::vector<Eigen::Vector3i> faces;\r\n\tstd::vector<Eigen::Vector2i> pixels;\r\n\r\n\tint vertexIdx = 0;\r\n\tstd::vector<int> mapPixelToVertexIdx(width * height, -1);\r\n\r\n\tfor (int y = 0; y < height - 1; y++) {\r\n\t\tfor (int x = 0; x < width - 1; x++) {\r\n\t\t\tEigen::Vector3f obs00(*point_image_in.data(y + 0, x + 0, 0), *point_image_in.data(y + 0, x + 0, 1), *point_image_in.data(y + 0, x + 0, 2));\r\n\t\t\tEigen::Vector3f obs01(*point_image_in.data(y + 1, x + 0, 0), *point_image_in.data(y + 1, x + 0, 1), *point_image_in.data(y + 1, x + 0, 2));\r\n\t\t\tEigen::Vector3f obs10(*point_image_in.data(y + 0, x + 1, 0), *point_image_in.data(y + 0, x + 1, 1), *point_image_in.data(y + 0, x + 1, 2));\r\n\t\t\tEigen::Vector3f obs11(*point_image_in.data(y + 1, x + 1, 0), *point_image_in.data(y + 1, x + 1, 1), *point_image_in.data(y + 1, x + 1, 2));\r\n\r\n\t\t\tint idx00 = y * width + x;\r\n\t\t\tint idx01 = (y + 1) * width + x;\r\n\t\t\tint idx10 = y * width + (x + 1);\r\n\t\t\tint idx11 = (y + 1) * width + (x + 1);\r\n\r\n\t\t\tbool valid00 = obs00.z() > 0;\r\n\t\t\tbool valid01 = obs01.z() > 0;\r\n\t\t\tbool valid10 = obs10.z() > 0;\r\n\t\t\tbool valid11 = obs11.z() > 0;\r\n\r\n\t\t\tif (valid00 && valid01 && valid10) {\r\n\t\t\t\tfloat d0 = (obs00 - obs01).norm();\r\n\t\t\t\tfloat d1 = (obs00 - obs10).norm();\r\n\t\t\t\tfloat d2 = (obs01 - obs10).norm();\r\n\r\n\t\t\t\tif (d0 <= max_triangle_edge_distance && d1 <= max_triangle_edge_distance && d2 <= max_triangle_edge_distance) {\r\n\t\t\t\t\tint vIdx0 = mapPixelToVertexIdx[idx00];\r\n\t\t\t\t\tint vIdx1 = mapPixelToVertexIdx[idx01];\r\n\t\t\t\t\tint vIdx2 = mapPixelToVertexIdx[idx10];\r\n\r\n\t\t\t\t\tif (vIdx0 == -1) {\r\n\t\t\t\t\t\tvIdx0 = vertexIdx;\r\n\t\t\t\t\t\tmapPixelToVertexIdx[idx00] = vertexIdx;\r\n\t\t\t\t\t\tvertices.push_back(obs00);\r\n\t\t\t\t\t\tvertexIdx++;\r\n\t\t\t\t\t\tpixels.emplace_back(x, y);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (vIdx1 == -1) {\r\n\t\t\t\t\t\tvIdx1 = vertexIdx;\r\n\t\t\t\t\t\tmapPixelToVertexIdx[idx01] = vertexIdx;\r\n\t\t\t\t\t\tvertices.push_back(obs01);\r\n\t\t\t\t\t\tvertexIdx++;\r\n\t\t\t\t\t\tpixels.emplace_back(x, y + 1);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (vIdx2 == -1) {\r\n\t\t\t\t\t\tvIdx2 = vertexIdx;\r\n\t\t\t\t\t\tmapPixelToVertexIdx[idx10] = vertexIdx;\r\n\t\t\t\t\t\tvertices.push_back(obs10);\r\n\t\t\t\t\t\tvertexIdx++;\r\n\t\t\t\t\t\tpixels.emplace_back(x + 1, y);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfaces.emplace_back(vIdx0, vIdx1, vIdx2);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (valid01 && valid10 && valid11) {\r\n\t\t\t\tfloat d0 = (obs10 - obs01).norm();\r\n\t\t\t\tfloat d1 = (obs10 - obs11).norm();\r\n\t\t\t\tfloat d2 = (obs01 - obs11).norm();\r\n\r\n\t\t\t\tif (d0 <= max_triangle_edge_distance && d1 <= max_triangle_edge_distance && d2 <= max_triangle_edge_distance) {\r\n\t\t\t\t\tint vIdx0 = mapPixelToVertexIdx[idx11];\r\n\t\t\t\t\tint vIdx1 = mapPixelToVertexIdx[idx10];\r\n\t\t\t\t\tint vIdx2 = mapPixelToVertexIdx[idx01];\r\n\r\n\t\t\t\t\tif (vIdx0 == -1) {\r\n\t\t\t\t\t\tvIdx0 = vertexIdx;\r\n\t\t\t\t\t\tmapPixelToVertexIdx[idx11] = vertexIdx;\r\n\t\t\t\t\t\tvertices.push_back(obs11);\r\n\t\t\t\t\t\tvertexIdx++;\r\n\t\t\t\t\t\tpixels.emplace_back(x + 1, y + 1);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (vIdx1 == -1) {\r\n\t\t\t\t\t\tvIdx1 = vertexIdx;\r\n\t\t\t\t\t\tmapPixelToVertexIdx[idx10] = vertexIdx;\r\n\t\t\t\t\t\tvertices.push_back(obs10);\r\n\t\t\t\t\t\tvertexIdx++;\r\n\t\t\t\t\t\tpixels.emplace_back(x + 1, y);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (vIdx2 == -1) {\r\n\t\t\t\t\t\tvIdx2 = vertexIdx;\r\n\t\t\t\t\t\tmapPixelToVertexIdx[idx01] = vertexIdx;\r\n\t\t\t\t\t\tvertices.push_back(obs01);\r\n\t\t\t\t\t\tvertexIdx++;\r\n\t\t\t\t\t\tpixels.emplace_back(x, y + 1);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfaces.emplace_back(vIdx0, vIdx1, vIdx2);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// Convert to numpy array.\r\n\tint vertex_count = vertices.size();\r\n\tint face_count = faces.size();\r\n\r\n\tif (vertex_count > 0 && face_count > 0) {\r\n\t\t// Reference check should be set to false otherwise there is a runtime\r\n\t\t// error. Check why that is the case.\r\n\t\tvertex_positions_out.resize({vertex_count, 3}, false);\r\n\t\tface_indices_out.resize({face_count, 3}, false);\r\n\t\tvertex_pixels_out.resize({vertex_count, 2}, false);\r\n\r\n\t\tfor (int i = 0; i < vertex_count; i++) {\r\n\t\t\t*vertex_positions_out.mutable_data(i, 0) = vertices[i].x();\r\n\t\t\t*vertex_positions_out.mutable_data(i, 1) = vertices[i].y();\r\n\t\t\t*vertex_positions_out.mutable_data(i, 2) = vertices[i].z();\r\n\r\n\t\t\t*vertex_pixels_out.mutable_data(i, 0) = pixels[i].x();\r\n\t\t\t*vertex_pixels_out.mutable_data(i, 1) = pixels[i].y();\r\n\t\t}\r\n\r\n\t\tfor (int i = 0; i < face_count; i++) {\r\n\t\t\t*face_indices_out.mutable_data(i, 0) = faces[i].x();\r\n\t\t\t*face_indices_out.mutable_data(i, 1) = faces[i].y();\r\n\t\t\t*face_indices_out.mutable_data(i, 2) = faces[i].z();\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\nvoid compute_mesh_from_depth(\r\n\t\tconst py::array_t<float>& point_image_in, float max_triangle_edge_distance,\r\n\t\tpy::array_t<float>& vertex_positions_out, py::array_t<int>& face_indices_out\r\n) {\r\n\tpy::array_t<int> vertex_pixels;\r\n\tcompute_mesh_from_depth(point_image_in, max_triangle_edge_distance, vertex_positions_out, vertex_pixels, face_indices_out);\r\n}\r\n\r\npy::tuple compute_mesh_from_depth(const py::array_t<float>& point_image_in, float max_triangle_edge_distance) {\r\n\tpy::array_t<float> vertex_positions_out;\r\n\tpy::array_t<int> face_indices_out;\r\n\tpy::array_t<int> vertex_pixels_out;\r\n\tcompute_mesh_from_depth(point_image_in, max_triangle_edge_distance, vertex_positions_out, vertex_pixels_out, face_indices_out);\r\n\treturn py::make_tuple(vertex_positions_out, vertex_pixels_out, face_indices_out);\r\n}\r\n\r\nvoid compute_mesh_from_depth_and_color(\r\n\t\tconst py::array_t<float>& point_image, const py::array_t<int>& color_image, float max_triangle_edge_distance,\r\n\t\tpy::array_t<float>& vertex_positions, py::array_t<int>& vertex_colors, py::array_t<int>& face_indices\r\n) {\r\n\tint width = static_cast<int>(point_image.shape(1));\r\n\tint height = static_cast<int>(point_image.shape(0));\r\n\r\n\t// Compute valid pixel vertices and faces.\r\n\t// We also need to compute the pixel -> vertex index mapping for\r\n\t// computation of faces.\r\n\t// We connect neighboring pixels on the square into two triangles.\r\n\t// We only select valid triangles, i.e. with all valid vertices and\r\n\t// not too far apart.\r\n\t// Important: The triangle orientation is set such that the normals\r\n\t// point towards the camera.\r\n\tstd::vector<Eigen::Vector3f> vertices;\r\n\tstd::vector<Eigen::Vector3i> colors;\r\n\tstd::vector<Eigen::Vector3i> faces;\r\n\r\n\tint vertexIdx = 0;\r\n\tstd::vector<int> mapPixelToVertexIdx(width * height, -1);\r\n\r\n\tfor (int y = 0; y < height - 1; y++) {\r\n\t\tfor (int x = 0; x < width - 1; x++) {\r\n\t\t\tEigen::Vector3f obs00(*point_image.data(y + 0, x + 0, 0), *point_image.data(y + 0, x + 0, 1), *point_image.data(y + 0, x + 0, 2));\r\n\t\t\tEigen::Vector3f obs01(*point_image.data(y + 1, x + 0, 0), *point_image.data(y + 1, x + 0, 1), *point_image.data(y + 1, x + 0, 2));\r\n\t\t\tEigen::Vector3f obs10(*point_image.data(y + 0, x + 1, 0), *point_image.data(y + 0, x + 1, 1), *point_image.data(y + 0, x + 1, 2));\r\n\t\t\tEigen::Vector3f obs11(*point_image.data(y + 1, x + 1, 0), *point_image.data(y + 1, x + 1, 1), *point_image.data(y + 1, x + 1, 2));\r\n\r\n\t\t\tEigen::Vector3i color00(*color_image.data(y + 0, x + 0, 0), *color_image.data(y + 0, x + 0, 1), *color_image.data(y + 0, x + 0, 2));\r\n\t\t\tEigen::Vector3i color01(*color_image.data(y + 1, x + 0, 0), *color_image.data(y + 1, x + 0, 1), *color_image.data(y + 1, x + 0, 2));\r\n\t\t\tEigen::Vector3i color10(*color_image.data(y + 0, x + 1, 0), *color_image.data(y + 0, x + 1, 1), *color_image.data(y + 0, x + 1, 2));\r\n\t\t\tEigen::Vector3i color11(*color_image.data(y + 1, x + 1, 0), *color_image.data(y + 1, x + 1, 1), *color_image.data(y + 1, x + 1, 2));\r\n\r\n\t\t\t// find linear indices\r\n\t\t\tint idx00 = y * width + x;\r\n\t\t\tint idx01 = (y + 1) * width + x;\r\n\t\t\tint idx10 = y * width + (x + 1);\r\n\t\t\tint idx11 = (y + 1) * width + (x + 1);\r\n\r\n\t\t\tbool valid00 = obs00.z() > 0;\r\n\t\t\tbool valid01 = obs01.z() > 0;\r\n\t\t\tbool valid10 = obs10.z() > 0;\r\n\t\t\tbool valid11 = obs11.z() > 0;\r\n\r\n\t\t\t// region ======= LOWER LEFT TRIANGLE =======\r\n\t\t\tif (valid00 && valid01 && valid10) {\r\n\t\t\t\tfloat d0 = (obs00 - obs01).norm();\r\n\t\t\t\tfloat d1 = (obs00 - obs10).norm();\r\n\t\t\t\tfloat d2 = (obs01 - obs10).norm();\r\n\r\n\t\t\t\tif (d0 <= max_triangle_edge_distance && d1 <= max_triangle_edge_distance && d2 <= max_triangle_edge_distance) {\r\n\t\t\t\t\tint vIdx0 = mapPixelToVertexIdx[idx00];\r\n\t\t\t\t\tint vIdx1 = mapPixelToVertexIdx[idx01];\r\n\t\t\t\t\tint vIdx2 = mapPixelToVertexIdx[idx10];\r\n\r\n\t\t\t\t\tif (vIdx0 == -1) {\r\n\t\t\t\t\t\tvIdx0 = vertexIdx;\r\n\t\t\t\t\t\tmapPixelToVertexIdx[idx00] = vertexIdx;\r\n\t\t\t\t\t\tvertices.push_back(obs00);\r\n\t\t\t\t\t\tcolors.push_back(color00);\r\n\t\t\t\t\t\tvertexIdx++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (vIdx1 == -1) {\r\n\t\t\t\t\t\tvIdx1 = vertexIdx;\r\n\t\t\t\t\t\tmapPixelToVertexIdx[idx01] = vertexIdx;\r\n\t\t\t\t\t\tvertices.push_back(obs01);\r\n\t\t\t\t\t\tcolors.push_back(color01);\r\n\t\t\t\t\t\tvertexIdx++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (vIdx2 == -1) {\r\n\t\t\t\t\t\tvIdx2 = vertexIdx;\r\n\t\t\t\t\t\tmapPixelToVertexIdx[idx10] = vertexIdx;\r\n\t\t\t\t\t\tvertices.push_back(obs10);\r\n\t\t\t\t\t\tcolors.push_back(color10);\r\n\t\t\t\t\t\tvertexIdx++;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfaces.emplace_back(vIdx0, vIdx1, vIdx2);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// endregion\r\n\t\t\t// region ======= UPPER RIGHT TRIANGLE =======\r\n\t\t\tif (valid01 && valid10 && valid11) {\r\n\t\t\t\tfloat d0 = (obs10 - obs01).norm();\r\n\t\t\t\tfloat d1 = (obs10 - obs11).norm();\r\n\t\t\t\tfloat d2 = (obs01 - obs11).norm();\r\n\r\n\t\t\t\tif (d0 <= max_triangle_edge_distance && d1 <= max_triangle_edge_distance && d2 <= max_triangle_edge_distance) {\r\n\t\t\t\t\tint vIdx0 = mapPixelToVertexIdx[idx11];\r\n\t\t\t\t\tint vIdx1 = mapPixelToVertexIdx[idx10];\r\n\t\t\t\t\tint vIdx2 = mapPixelToVertexIdx[idx01];\r\n\r\n\t\t\t\t\tif (vIdx0 == -1) {\r\n\t\t\t\t\t\tvIdx0 = vertexIdx;\r\n\t\t\t\t\t\tmapPixelToVertexIdx[idx11] = vertexIdx;\r\n\t\t\t\t\t\tvertices.push_back(obs11);\r\n\t\t\t\t\t\tcolors.push_back(color11);\r\n\t\t\t\t\t\tvertexIdx++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (vIdx1 == -1) {\r\n\t\t\t\t\t\tvIdx1 = vertexIdx;\r\n\t\t\t\t\t\tmapPixelToVertexIdx[idx10] = vertexIdx;\r\n\t\t\t\t\t\tvertices.push_back(obs10);\r\n\t\t\t\t\t\tcolors.push_back(color10);\r\n\t\t\t\t\t\tvertexIdx++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (vIdx2 == -1) {\r\n\t\t\t\t\t\tvIdx2 = vertexIdx;\r\n\t\t\t\t\t\tmapPixelToVertexIdx[idx01] = vertexIdx;\r\n\t\t\t\t\t\tvertices.push_back(obs01);\r\n\t\t\t\t\t\tcolors.push_back(color01);\r\n\t\t\t\t\t\tvertexIdx++;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfaces.emplace_back(vIdx0, vIdx1, vIdx2);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// endregion\r\n\t\t}\r\n\t}\r\n\r\n\t// Convert to numpy array.\r\n\tint vertex_count = vertices.size();\r\n\tint face_count = faces.size();\r\n\r\n\tif (vertex_count > 0 && face_count > 0) {\r\n\t\t// Reference check should be set to false otherwise there is a runtime\r\n\t\t// error. Check why that is the case.\r\n\t\tvertex_positions.resize({vertex_count, 3}, false);\r\n\t\tvertex_colors.resize({vertex_count, 3}, false);\r\n\t\tface_indices.resize({face_count, 3}, false);\r\n\r\n\t\tfor (int i = 0; i < vertex_count; i++) {\r\n\t\t\t*vertex_positions.mutable_data(i, 0) = vertices[i].x();\r\n\t\t\t*vertex_positions.mutable_data(i, 1) = vertices[i].y();\r\n\t\t\t*vertex_positions.mutable_data(i, 2) = vertices[i].z();\r\n\r\n\t\t\t*vertex_colors.mutable_data(i, 0) = colors[i].x();\r\n\t\t\t*vertex_colors.mutable_data(i, 1) = colors[i].y();\r\n\t\t\t*vertex_colors.mutable_data(i, 2) = colors[i].z();\r\n\t\t}\r\n\r\n\t\tfor (int i = 0; i < face_count; i++) {\r\n\t\t\t*face_indices.mutable_data(i, 0) = faces[i].x();\r\n\t\t\t*face_indices.mutable_data(i, 1) = faces[i].y();\r\n\t\t\t*face_indices.mutable_data(i, 2) = faces[i].z();\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\nvoid compute_mesh_from_depth_and_flow(\r\n\t\tconst py::array_t<float>& point_image_in, const py::array_t<float>& flow_image_in,\r\n\t\tfloat max_triangle_edge_distance, py::array_t<float>& vertex_positions_out,\r\n\t\tpy::array_t<float>& vertex_flows_out, py::array_t<int>& vertex_pixels_out, py::array_t<int>& face_indices_out\r\n) {\r\n\tint width = point_image_in.shape(1);\r\n\tint height = point_image_in.shape(0);\r\n\r\n\r\n\t// Compute valid pixel vertices and faces\r\n\t// a pixel is considered valid if the corresponding point's z coordinate is greater than zero and x, y, and z of the flow vector are all finite\r\n\r\n\t// We also need to compute the pixel -> vertex index mapping for computation of faces.\r\n\t// TODO: why are there no vertex indices > 400, if the total image has 640x480=307200 pixels?\r\n\r\n\t// For every 2x2 pixel area, we connect neighboring pixels into two triangles.\r\n\t// [ ]-------[ ]\r\n\t//  | \u2572       |\r\n\t//  |    \u2572    |\r\n\t//  |       \u2572 |\r\n\t// [ ]-------[ ]\r\n\r\n\t// We only select valid triangles, i.e. with all valid vertices, and vertices not too far apart.\r\n\r\n\t// Important: The triangle orientation is set such that the normals point towards the camera.\r\n\r\n\tstd::vector<Eigen::Vector3f> vertices;\r\n\tstd::vector<Eigen::Vector3f> flows;\r\n\tstd::vector<Eigen::Vector2i> pixels;\r\n\tstd::vector<Eigen::Vector3i> faces;\r\n\r\n\tint vertex_index = 0;\r\n\tstd::vector<int> pixel_to_vertex_index_map(width * height, -1);\r\n\r\n\tfor (int y = 0; y < height - 1; y++) {\r\n\t\tfor (int x = 0; x < width - 1; x++) {\r\n\t\t\tEigen::Vector3f obs00(*point_image_in.data(y, x, 0), *point_image_in.data(y, x, 1), *point_image_in.data(y, x, 2));\r\n\t\t\tEigen::Vector3f obs01(*point_image_in.data(y + 1, x, 0), *point_image_in.data(y + 1, x, 1), *point_image_in.data(y + 1, x, 2));\r\n\t\t\tEigen::Vector3f obs10(*point_image_in.data(y, x + 1, 0), *point_image_in.data(y, x + 1, 1), *point_image_in.data(y, x + 1, 2));\r\n\t\t\tEigen::Vector3f obs11(*point_image_in.data(y + 1, x + 1, 0), *point_image_in.data(y + 1, x + 1, 1), *point_image_in.data(y + 1, x + 1, 2));\r\n\r\n\t\t\tEigen::Vector3f flow00(*flow_image_in.data(y, x, 0), *flow_image_in.data(y, x, 1), *flow_image_in.data(y, x, 2));\r\n\t\t\tEigen::Vector3f flow01(*flow_image_in.data(y + 1, x, 0), *flow_image_in.data(y + 1, x, 1), *flow_image_in.data(y + 1, x, 2));\r\n\t\t\tEigen::Vector3f flow10(*flow_image_in.data(y, x + 1, 0), *flow_image_in.data(y, x + 1, 1), *flow_image_in.data(y, x + 1, 2));\r\n\t\t\tEigen::Vector3f flow11(*flow_image_in.data(y + 1, x + 1, 0), *flow_image_in.data(y + 1, x + 1, 1), *flow_image_in.data(y + 1, x + 1, 2));\r\n\r\n\t\t\t// linear indices of the four pixels\r\n\t\t\tint idx00 = y * width + x;\r\n\t\t\tint idx01 = (y + 1) * width + x;\r\n\t\t\tint idx10 = y * width + (x + 1);\r\n\t\t\tint idx11 = (y + 1) * width + (x + 1);\r\n\r\n\t\t\t// determine pixel validity\r\n\t\t\tbool valid00 = obs00.z() > 0 && std::isfinite(flow00.x()) && std::isfinite(flow00.y()) && std::isfinite(flow00.z());\r\n\t\t\tbool valid01 = obs01.z() > 0 && std::isfinite(flow01.x()) && std::isfinite(flow01.y()) && std::isfinite(flow01.z());\r\n\t\t\tbool valid10 = obs10.z() > 0 && std::isfinite(flow10.x()) && std::isfinite(flow10.y()) && std::isfinite(flow10.z());\r\n\t\t\tbool valid11 = obs11.z() > 0 && std::isfinite(flow11.x()) && std::isfinite(flow11.y()) && std::isfinite(flow11.z());\r\n\r\n\t\t\t// region ======= LOWER LEFT TRIANGLE =============\r\n\t\t\tif (valid00 && valid01 && valid10) {\r\n\t\t\t\tfloat d0 = (obs00 - obs01).norm();\r\n\t\t\t\tfloat d1 = (obs00 - obs10).norm(); // hypotenuse when triangle projected to image plane\r\n\t\t\t\tfloat d2 = (obs01 - obs10).norm();\r\n\r\n\t\t\t\tif (d0 <= max_triangle_edge_distance && d1 <= max_triangle_edge_distance && d2 <= max_triangle_edge_distance) {\r\n\t\t\t\t\tint vertex_index_0 = pixel_to_vertex_index_map[idx00];\r\n\t\t\t\t\tint vertex_index_1 = pixel_to_vertex_index_map[idx01];\r\n\t\t\t\t\tint vertex_index_2 = pixel_to_vertex_index_map[idx10];\r\n\r\n\t\t\t\t\tif (vertex_index_0 == -1) {\r\n\t\t\t\t\t\tvertex_index_0 = vertex_index;\r\n\t\t\t\t\t\tpixel_to_vertex_index_map[idx00] = vertex_index;\r\n\t\t\t\t\t\tvertices.push_back(obs00);\r\n\t\t\t\t\t\tflows.push_back(flow00);\r\n\t\t\t\t\t\tpixels.emplace_back(x, y);\r\n\t\t\t\t\t\tvertex_index++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (vertex_index_1 == -1) {\r\n\t\t\t\t\t\tvertex_index_1 = vertex_index;\r\n\t\t\t\t\t\tpixel_to_vertex_index_map[idx01] = vertex_index;\r\n\t\t\t\t\t\tvertices.push_back(obs01);\r\n\t\t\t\t\t\tflows.push_back(flow01);\r\n\t\t\t\t\t\tpixels.emplace_back(x, y + 1);\r\n\t\t\t\t\t\tvertex_index++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (vertex_index_2 == -1) {\r\n\t\t\t\t\t\tvertex_index_2 = vertex_index;\r\n\t\t\t\t\t\tpixel_to_vertex_index_map[idx10] = vertex_index;\r\n\t\t\t\t\t\tvertices.push_back(obs10);\r\n\t\t\t\t\t\tflows.push_back(flow10);\r\n\t\t\t\t\t\tpixels.emplace_back(x + 1, y);\r\n\t\t\t\t\t\tvertex_index++;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfaces.emplace_back(vertex_index_0, vertex_index_1, vertex_index_2);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// endregion\r\n\t\t\t// region ======= UPPER RIGHT TRIANGLE ==================\r\n\t\t\tif (valid01 && valid10 && valid11) {\r\n\t\t\t\tfloat d0 = (obs10 - obs01).norm();\r\n\t\t\t\tfloat d1 = (obs10 - obs11).norm();\r\n\t\t\t\tfloat d2 = (obs01 - obs11).norm();\r\n\r\n\t\t\t\tif (d0 <= max_triangle_edge_distance && d1 <= max_triangle_edge_distance && d2 <= max_triangle_edge_distance) {\r\n\t\t\t\t\tint vertex_index_0 = pixel_to_vertex_index_map[idx11];\r\n\t\t\t\t\tint vertex_index_1 = pixel_to_vertex_index_map[idx10];\r\n\t\t\t\t\tint vertex_index_2 = pixel_to_vertex_index_map[idx01];\r\n\r\n\t\t\t\t\tif (vertex_index_0 == -1) {\r\n\t\t\t\t\t\tvertex_index_0 = vertex_index;\r\n\t\t\t\t\t\tpixel_to_vertex_index_map[idx11] = vertex_index;\r\n\t\t\t\t\t\tvertices.push_back(obs11);\r\n\t\t\t\t\t\tflows.push_back(flow11);\r\n\t\t\t\t\t\tpixels.emplace_back(x + 1, y + 1);\r\n\t\t\t\t\t\tvertex_index++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (vertex_index_1 == -1) {\r\n\t\t\t\t\t\tvertex_index_1 = vertex_index;\r\n\t\t\t\t\t\tpixel_to_vertex_index_map[idx10] = vertex_index;\r\n\t\t\t\t\t\tvertices.push_back(obs10);\r\n\t\t\t\t\t\tflows.push_back(flow10);\r\n\t\t\t\t\t\tpixels.emplace_back(x + 1, y);\r\n\t\t\t\t\t\tvertex_index++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (vertex_index_2 == -1) {\r\n\t\t\t\t\t\tvertex_index_2 = vertex_index;\r\n\t\t\t\t\t\tpixel_to_vertex_index_map[idx01] = vertex_index;\r\n\t\t\t\t\t\tvertices.push_back(obs01);\r\n\t\t\t\t\t\tflows.push_back(flow01);\r\n\t\t\t\t\t\tpixels.emplace_back(x, y + 1);\r\n\t\t\t\t\t\tvertex_index++;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfaces.emplace_back(vertex_index_0, vertex_index_1, vertex_index_2);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// endregion\r\n\t\t}\r\n\t}\r\n\r\n\t// Convert to numpy array.\r\n\tint vertex_count = vertices.size();\r\n\tint face_count = faces.size();\r\n\r\n\tif (vertex_count > 0 && face_count > 0) {\r\n\t\t// Reference check should be set to false otherwise there is a runtime\r\n\t\t// error. Check why that is the case.\r\n\t\tvertex_positions_out.resize({vertex_count, 3}, false);\r\n\t\tvertex_flows_out.resize({vertex_count, 3}, false);\r\n\t\tvertex_pixels_out.resize({vertex_count, 2}, false);\r\n\t\tface_indices_out.resize({face_count, 3}, false);\r\n\r\n\t\tfor (int i = 0; i < vertex_count; i++) {\r\n\t\t\t*vertex_positions_out.mutable_data(i, 0) = vertices[i].x();\r\n\t\t\t*vertex_positions_out.mutable_data(i, 1) = vertices[i].y();\r\n\t\t\t*vertex_positions_out.mutable_data(i, 2) = vertices[i].z();\r\n\r\n\t\t\t*vertex_flows_out.mutable_data(i, 0) = flows[i].x();\r\n\t\t\t*vertex_flows_out.mutable_data(i, 1) = flows[i].y();\r\n\t\t\t*vertex_flows_out.mutable_data(i, 2) = flows[i].z();\r\n\r\n\t\t\t*vertex_pixels_out.mutable_data(i, 0) = pixels[i].x();\r\n\t\t\t*vertex_pixels_out.mutable_data(i, 1) = pixels[i].y();\r\n\t\t}\r\n\r\n\t\tfor (int i = 0; i < face_count; i++) {\r\n\t\t\t*face_indices_out.mutable_data(i, 0) = faces[i].x();\r\n\t\t\t*face_indices_out.mutable_data(i, 1) = faces[i].y();\r\n\t\t\t*face_indices_out.mutable_data(i, 2) = faces[i].z();\r\n\t\t}\r\n\t}\r\n}\r\n\r\npy::tuple compute_mesh_from_depth_and_flow(const py::array_t<float>& point_image_in, const py::array_t<float>& flow_image_in,\r\n                                           float max_triangle_edge_distance) {\r\n\tpy::array_t<float> vertex_positions_out;\r\n\tpy::array_t<float> vertex_flows_out;\r\n\tpy::array_t<int> vertex_pixels_out;\r\n\tpy::array_t<int> face_indices_out;\r\n\tcompute_mesh_from_depth_and_flow(point_image_in, flow_image_in, max_triangle_edge_distance, vertex_positions_out, vertex_flows_out, vertex_pixels_out, face_indices_out);\r\n\treturn py::make_tuple(vertex_positions_out, vertex_flows_out, vertex_pixels_out, face_indices_out);\r\n}\r\n\r\nvoid filter_depth(py::array_t<unsigned short>& depth_image_in, py::array_t<unsigned short>& depth_image_out, int radius) {\r\n\tassert(depth_image_in.ndim() == 2);\r\n\tassert(depth_image_out.ndim() == 2);\r\n\tunsigned kernel_size = 2 * radius + 1;\r\n\tunsigned window_size = kernel_size * kernel_size;\r\n\r\n\tint width = depth_image_in.shape(1);\r\n\tint height = depth_image_in.shape(0);\r\n\tassert(depth_image_out.shape(0) == height);\r\n\tassert(depth_image_out.shape(1) == width);\r\n\r\n\t// #pragma omp parallel for\r\n\tfor (int y = 0; y < height; y++) {\r\n\t\tfor (int x = 0; x < width; x++) {\r\n\t\t\t// Get all residuals in the median window.\r\n\t\t\tint x_min = std::max(x - radius, 0);\r\n\t\t\tint x_max = std::min(x + radius, int(width) - 1);\r\n\t\t\tint y_min = std::max(y - radius, 0);\r\n\t\t\tint y_max = std::min(y + radius, int(height) - 1);\r\n\r\n\t\t\tstd::vector<unsigned short> window_values;\r\n\t\t\twindow_values.reserve(window_size);\r\n\r\n\t\t\tfor (int y_near = y_min; y_near <= y_max; y_near++) {\r\n\t\t\t\tfor (int x_near = x_min; x_near <= x_max; x_near++) {\r\n\t\t\t\t\tunsigned short depth = *depth_image_in.data(y_near, x_near);\r\n\t\t\t\t\tif (depth > 0) {\r\n\t\t\t\t\t\twindow_values.push_back(depth);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// Sort the residuals and pick the median as the middle element.\r\n\t\t\tunsigned element_count = window_values.size();\r\n\t\t\tstd::sort(window_values.begin(), window_values.end());\r\n\r\n\t\t\tunsigned middle_index = std::floor(element_count / 2);\r\n\t\t\tunsigned short median = window_values[middle_index];\r\n\r\n\t\t\t// Write out the median value.\r\n\t\t\t*depth_image_out.mutable_data(y, x) = median;\r\n\t\t}\r\n\t}\r\n}\r\n\r\npy::array_t<unsigned short> filter_depth(py::array_t<unsigned short>& depth_image_in, int radius) {\r\n\tpy::array_t<unsigned short> depth_image_out({depth_image_in.shape(0), depth_image_in.shape(1)});\r\n\tmemset(depth_image_out.mutable_data(0, 0), 0, depth_image_out.size() * sizeof(unsigned short));\r\n\tfilter_depth(depth_image_in, depth_image_out, radius);\r\n\treturn depth_image_out;\r\n}\r\n\r\npy::array_t<float> warp_flow(const py::array_t<float>& image, const py::array_t<float>& flow, const py::array_t<float>& mask) {\r\n\t// We assume:\r\n\t//      image shape (3, h, w)\r\n\t//      flow shape  (2, h, w)\r\n\t//      mask shape  (2, h, w)\r\n\r\n\tint width = image.shape(2);\r\n\tint height = image.shape(1);\r\n\r\n\tpy::array_t<float> imageWarped = py::array_t<float>({3, height, width});\r\n\tpy::array_t<float> weightsWarped = py::array_t<float>({1, height, width});\r\n\r\n\t// Initialize to zero.\r\n\tfor (int v = 0; v < height; v++) {\r\n\t\tfor (int u = 0; u < width; u++) {\r\n\t\t\t*imageWarped.mutable_data(0, v, u) = 0.0;\r\n\t\t\t*imageWarped.mutable_data(1, v, u) = 0.0;\r\n\t\t\t*imageWarped.mutable_data(2, v, u) = 0.0;\r\n\t\t\t*weightsWarped.mutable_data(0, v, u) = 0.0;\r\n\t\t}\r\n\t}\r\n\r\n\t// Compute image residuals and interpolation weights.\r\n\tfor (int v = 0; v < height; v++) {\r\n\t\tfor (int u = 0; u < width; u++) {\r\n\t\t\t// Check if pixel is inside the mask.\r\n\t\t\tif (*mask.data(0, v, u) <= 0 || *mask.data(1, v, u) <= 0) continue;\r\n\r\n\t\t\t// Compute the warped pixel.\r\n\t\t\tfloat u_warped = static_cast<float>(u) + *flow.data(0, v, u);\r\n\t\t\tfloat v_warped = static_cast<float>(v) + *flow.data(1, v, u);\r\n\r\n\t\t\tint u0 = std::floor(u_warped);\r\n\t\t\tint u1 = u0 + 1;\r\n\t\t\tint v0 = std::floor(v_warped);\r\n\t\t\tint v1 = v0 + 1;\r\n\r\n\t\t\tif (u0 < 0 || u1 >= width || v0 < 0 || v1 >= height) continue;\r\n\r\n\t\t\t// Interpolate the color contributions.\r\n\t\t\tfloat du = u_warped - u0;\r\n\t\t\tfloat dv = v_warped - v0;\r\n\r\n\t\t\tfloat w00 = (1 - du) * (1 - dv);\r\n\t\t\tfloat w01 = (1 - du) * dv;\r\n\t\t\tfloat w10 = du * (1 - dv);\r\n\t\t\tfloat w11 = du * dv;\r\n\r\n\t\t\tfloat c0 = *image.data(0, v, u);\r\n\t\t\tfloat c1 = *image.data(1, v, u);\r\n\t\t\tfloat c2 = *image.data(2, v, u);\r\n\r\n\t\t\t*imageWarped.mutable_data(0, v0, u0) += w00 * c0;\r\n\t\t\t*imageWarped.mutable_data(1, v0, u0) += w00 * c1;\r\n\t\t\t*imageWarped.mutable_data(2, v0, u0) += w00 * c2;\r\n\t\t\t*imageWarped.mutable_data(0, v1, u0) += w01 * c0;\r\n\t\t\t*imageWarped.mutable_data(1, v1, u0) += w01 * c1;\r\n\t\t\t*imageWarped.mutable_data(2, v1, u0) += w01 * c2;\r\n\t\t\t*imageWarped.mutable_data(0, v0, u1) += w10 * c0;\r\n\t\t\t*imageWarped.mutable_data(1, v0, u1) += w10 * c1;\r\n\t\t\t*imageWarped.mutable_data(2, v0, u1) += w10 * c2;\r\n\t\t\t*imageWarped.mutable_data(0, v1, u1) += w11 * c0;\r\n\t\t\t*imageWarped.mutable_data(1, v1, u1) += w11 * c1;\r\n\t\t\t*imageWarped.mutable_data(2, v1, u1) += w11 * c2;\r\n\r\n\t\t\t*weightsWarped.mutable_data(0, v0, u0) += w00;\r\n\t\t\t*weightsWarped.mutable_data(0, v1, u0) += w01;\r\n\t\t\t*weightsWarped.mutable_data(0, v0, u1) += w10;\r\n\t\t\t*weightsWarped.mutable_data(0, v1, u1) += w11;\r\n\t\t}\r\n\t}\r\n\r\n\t// Normalize image.\r\n\tfor (int v = 0; v < height; v++) {\r\n\t\tfor (int u = 0; u < width; u++) {\r\n\t\t\tfloat w = *weightsWarped.data(0, v, u);\r\n\t\t\tif (w > 0) {\r\n\t\t\t\t*imageWarped.mutable_data(0, v, u) /= w;\r\n\t\t\t\t*imageWarped.mutable_data(1, v, u) /= w;\r\n\t\t\t\t*imageWarped.mutable_data(2, v, u) /= w;\r\n\t\t\t} else {\r\n\t\t\t\t*imageWarped.mutable_data(0, v, u) = 1.0;\r\n\t\t\t\t*imageWarped.mutable_data(1, v, u) = 1.0;\r\n\t\t\t\t*imageWarped.mutable_data(2, v, u) = 1.0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn imageWarped;\r\n}\r\n\r\npy::array_t<float> warp_rigid(\r\n\t\tconst py::array_t<float>& rgbxyz_image,\r\n\t\tconst py::array_t<float>& rotation,\r\n\t\tconst py::array_t<float>& translation,\r\n\t\tfloat fx, float fy, float cx, float cy\r\n) {\r\n\t// We assume:\r\n\t//      rgbd shape (6, h, w)\r\n\t//      rotation shape  (9)\r\n\t//      translation shape  (2)\r\n\r\n\tint width = rgbxyz_image.shape(2);\r\n\tint height = rgbxyz_image.shape(1);\r\n\r\n\tfloat r00 = *rotation.data(0);\r\n\tfloat r01 = *rotation.data(1);\r\n\tfloat r02 = *rotation.data(2);\r\n\tfloat r10 = *rotation.data(3);\r\n\tfloat r11 = *rotation.data(4);\r\n\tfloat r12 = *rotation.data(5);\r\n\tfloat r20 = *rotation.data(6);\r\n\tfloat r21 = *rotation.data(7);\r\n\tfloat r22 = *rotation.data(8);\r\n\tfloat t0 = *translation.data(0);\r\n\tfloat t1 = *translation.data(1);\r\n\tfloat t2 = *translation.data(2);\r\n\r\n\tpy::array_t<float> image_warped = py::array_t<float>({3, height, width});\r\n\tpy::array_t<float> weights_warped = py::array_t<float>({1, height, width});\r\n\r\n\t// Initialize to zero.\r\n\tfor (int v = 0; v < height; v++) {\r\n\t\tfor (int u = 0; u < width; u++) {\r\n\t\t\t*image_warped.mutable_data(0, v, u) = 0.0;\r\n\t\t\t*image_warped.mutable_data(1, v, u) = 0.0;\r\n\t\t\t*image_warped.mutable_data(2, v, u) = 0.0;\r\n\t\t\t*weights_warped.mutable_data(0, v, u) = 0.0;\r\n\t\t}\r\n\t}\r\n\r\n\t// Compute image residuals and interpolation weights.\r\n\tfor (int v = 0; v < height; v++) {\r\n\t\tfor (int u = 0; u < width; u++) {\r\n\t\t\t// Compute the warped pixel.\r\n\t\t\tfloat x = *rgbxyz_image.data(3, v, u);\r\n\t\t\tfloat y = *rgbxyz_image.data(4, v, u);\r\n\t\t\tfloat z = *rgbxyz_image.data(5, v, u);\r\n\t\t\tif (z <= 0) continue;\r\n\r\n\t\t\tfloat x_def = r00 * x + r01 * y + r02 * z + t0;\r\n\t\t\tfloat y_def = r10 * x + r11 * y + r12 * z + t1;\r\n\t\t\tfloat z_def = r20 * x + r21 * y + r22 * z + t2;\r\n\t\t\tif (z_def <= 0) continue;\r\n\r\n\t\t\tfloat u_warped = fx * x_def / z_def + cx;\r\n\t\t\tfloat v_warped = fy * y_def / z_def + cy;\r\n\r\n\t\t\tint u0 = std::floor(u_warped);\r\n\t\t\tint u1 = u0 + 1;\r\n\t\t\tint v0 = std::floor(v_warped);\r\n\t\t\tint v1 = v0 + 1;\r\n\r\n\t\t\tif (u0 < 0 || u1 >= width || v0 < 0 || v1 >= height) continue;\r\n\r\n\t\t\t// Interpolate the color contributions.\r\n\t\t\tfloat du = u_warped - u0;\r\n\t\t\tfloat dv = v_warped - v0;\r\n\r\n\t\t\tfloat w00 = (1 - du) * (1 - dv);\r\n\t\t\tfloat w01 = (1 - du) * dv;\r\n\t\t\tfloat w10 = du * (1 - dv);\r\n\t\t\tfloat w11 = du * dv;\r\n\r\n\t\t\tfloat c0 = *rgbxyz_image.data(0, v, u);\r\n\t\t\tfloat c1 = *rgbxyz_image.data(1, v, u);\r\n\t\t\tfloat c2 = *rgbxyz_image.data(2, v, u);\r\n\r\n\t\t\t*image_warped.mutable_data(0, v0, u0) += w00 * c0;\r\n\t\t\t*image_warped.mutable_data(1, v0, u0) += w00 * c1;\r\n\t\t\t*image_warped.mutable_data(2, v0, u0) += w00 * c2;\r\n\t\t\t*image_warped.mutable_data(0, v1, u0) += w01 * c0;\r\n\t\t\t*image_warped.mutable_data(1, v1, u0) += w01 * c1;\r\n\t\t\t*image_warped.mutable_data(2, v1, u0) += w01 * c2;\r\n\t\t\t*image_warped.mutable_data(0, v0, u1) += w10 * c0;\r\n\t\t\t*image_warped.mutable_data(1, v0, u1) += w10 * c1;\r\n\t\t\t*image_warped.mutable_data(2, v0, u1) += w10 * c2;\r\n\t\t\t*image_warped.mutable_data(0, v1, u1) += w11 * c0;\r\n\t\t\t*image_warped.mutable_data(1, v1, u1) += w11 * c1;\r\n\t\t\t*image_warped.mutable_data(2, v1, u1) += w11 * c2;\r\n\r\n\t\t\t*weights_warped.mutable_data(0, v0, u0) += w00;\r\n\t\t\t*weights_warped.mutable_data(0, v1, u0) += w01;\r\n\t\t\t*weights_warped.mutable_data(0, v0, u1) += w10;\r\n\t\t\t*weights_warped.mutable_data(0, v1, u1) += w11;\r\n\t\t}\r\n\t}\r\n\r\n\t// Normalize image.\r\n\tfor (int v = 0; v < height; v++) {\r\n\t\tfor (int u = 0; u < width; u++) {\r\n\t\t\tfloat w = *weights_warped.data(0, v, u);\r\n\t\t\tif (w > 0) {\r\n\t\t\t\t*image_warped.mutable_data(0, v, u) /= w;\r\n\t\t\t\t*image_warped.mutable_data(1, v, u) /= w;\r\n\t\t\t\t*image_warped.mutable_data(2, v, u) /= w;\r\n\t\t\t} else {\r\n\t\t\t\t*image_warped.mutable_data(0, v, u) = 1.0;\r\n\t\t\t\t*image_warped.mutable_data(1, v, u) = 1.0;\r\n\t\t\t\t*image_warped.mutable_data(2, v, u) = 1.0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn image_warped;\r\n}\r\n\r\npy::array_t<float>\r\nwarp_3d(const py::array_t<float>& rgbxyz_image, const py::array_t<float>& points,\r\n        const py::array_t<int>& mask, float fx, float fy, float cx, float cy) {\r\n\r\n\t// We assume:\r\n\t//      image shape             (6, h, w)\r\n\t//      points shape            (3, h, w)\r\n\t//      mask shape    (h, w)\r\n\r\n\tint width = rgbxyz_image.shape(2);\r\n\tint height = rgbxyz_image.shape(1);\r\n\r\n\tpy::array_t<float> image_warped = py::array_t<float>({3, height, width});\r\n\tpy::array_t<float> weights_warped = py::array_t<float>({1, height, width});\r\n\r\n\t// Initialize to zero.\r\n\tfor (int v = 0; v < height; v++) {\r\n\t\tfor (int u = 0; u < width; u++) {\r\n\t\t\t*image_warped.mutable_data(0, v, u) = 0.0;\r\n\t\t\t*image_warped.mutable_data(1, v, u) = 0.0;\r\n\t\t\t*image_warped.mutable_data(2, v, u) = 0.0;\r\n\t\t\t*weights_warped.mutable_data(0, v, u) = 0.0;\r\n\t\t}\r\n\t}\r\n\r\n\t// Compute image residuals and interpolation weights.\r\n\tfor (int v = 0; v < height; v++) {\r\n\t\tfor (int u = 0; u < width; u++) {\r\n\t\t\t// Compute the warped pixel.\r\n\t\t\tif (*mask.data(v, u) <= 0) continue;\r\n\r\n\t\t\tfloat z = *rgbxyz_image.data(5, v, u);\r\n\t\t\tif (z <= 0) continue;\r\n\r\n\t\t\tfloat x_def = *points.data(0, v, u);\r\n\t\t\tfloat y_def = *points.data(1, v, u);\r\n\t\t\tfloat z_def = *points.data(2, v, u);\r\n\t\t\tif (z_def <= 0) continue;\r\n\r\n\t\t\tfloat u_warped = fx * x_def / z_def + cx;\r\n\t\t\tfloat v_warped = fy * y_def / z_def + cy;\r\n\r\n\t\t\tint u0 = std::floor(u_warped);\r\n\t\t\tint u1 = u0 + 1;\r\n\t\t\tint v0 = std::floor(v_warped);\r\n\t\t\tint v1 = v0 + 1;\r\n\r\n\t\t\tif (u0 < 0 || u1 >= width || v0 < 0 || v1 >= height) continue;\r\n\r\n\t\t\t// Interpolate the color contributions.\r\n\t\t\tfloat du = u_warped - u0;\r\n\t\t\tfloat dv = v_warped - v0;\r\n\r\n\t\t\tfloat w00 = (1 - du) * (1 - dv);\r\n\t\t\tfloat w01 = (1 - du) * dv;\r\n\t\t\tfloat w10 = du * (1 - dv);\r\n\t\t\tfloat w11 = du * dv;\r\n\r\n\t\t\tfloat c0 = *rgbxyz_image.data(0, v, u);\r\n\t\t\tfloat c1 = *rgbxyz_image.data(1, v, u);\r\n\t\t\tfloat c2 = *rgbxyz_image.data(2, v, u);\r\n\r\n\t\t\t*image_warped.mutable_data(0, v0, u0) += w00 * c0;\r\n\t\t\t*image_warped.mutable_data(1, v0, u0) += w00 * c1;\r\n\t\t\t*image_warped.mutable_data(2, v0, u0) += w00 * c2;\r\n\t\t\t*image_warped.mutable_data(0, v1, u0) += w01 * c0;\r\n\t\t\t*image_warped.mutable_data(1, v1, u0) += w01 * c1;\r\n\t\t\t*image_warped.mutable_data(2, v1, u0) += w01 * c2;\r\n\t\t\t*image_warped.mutable_data(0, v0, u1) += w10 * c0;\r\n\t\t\t*image_warped.mutable_data(1, v0, u1) += w10 * c1;\r\n\t\t\t*image_warped.mutable_data(2, v0, u1) += w10 * c2;\r\n\t\t\t*image_warped.mutable_data(0, v1, u1) += w11 * c0;\r\n\t\t\t*image_warped.mutable_data(1, v1, u1) += w11 * c1;\r\n\t\t\t*image_warped.mutable_data(2, v1, u1) += w11 * c2;\r\n\r\n\t\t\t*weights_warped.mutable_data(0, v0, u0) += w00;\r\n\t\t\t*weights_warped.mutable_data(0, v1, u0) += w01;\r\n\t\t\t*weights_warped.mutable_data(0, v0, u1) += w10;\r\n\t\t\t*weights_warped.mutable_data(0, v1, u1) += w11;\r\n\t\t}\r\n\t}\r\n\r\n\t// Normalize image.\r\n\tfor (int v = 0; v < height; v++) {\r\n\t\tfor (int u = 0; u < width; u++) {\r\n\t\t\tfloat w = *weights_warped.data(0, v, u);\r\n\t\t\tif (w > 0) {\r\n\t\t\t\t*image_warped.mutable_data(0, v, u) /= w;\r\n\t\t\t\t*image_warped.mutable_data(1, v, u) /= w;\r\n\t\t\t\t*image_warped.mutable_data(2, v, u) /= w;\r\n\t\t\t} else {\r\n\t\t\t\t*image_warped.mutable_data(0, v, u) = 1.0;\r\n\t\t\t\t*image_warped.mutable_data(1, v, u) = 1.0;\r\n\t\t\t\t*image_warped.mutable_data(2, v, u) = 1.0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn image_warped;\r\n}\r\n\r\n} //namespace image_proc", "meta": {"hexsha": "a91142b9ebd5462fb8d99bd57a71e07a09705ca3", "size": 45861, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "csrc/cpu/image_proc.cpp", "max_stars_repo_name": "Algomorph/NeuralTracking", "max_stars_repo_head_hexsha": "6312be8e18828344c65e25a423c239efcd3428dd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-18T04:23:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T08:37:51.000Z", "max_issues_repo_path": "csrc/cpu/image_proc.cpp", "max_issues_repo_name": "Algomorph/NeuralTracking", "max_issues_repo_head_hexsha": "6312be8e18828344c65e25a423c239efcd3428dd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2021-05-28T21:59:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T16:09:41.000Z", "max_forks_repo_path": "csrc/cpu/image_proc.cpp", "max_forks_repo_name": "Algomorph/NeuralTracking", "max_forks_repo_head_hexsha": "6312be8e18828344c65e25a423c239efcd3428dd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-10T02:56:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T06:04:50.000Z", "avg_line_length": 35.634032634, "max_line_length": 171, "alphanum_fraction": 0.6050456815, "num_tokens": 14568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5087215057514988}}
{"text": "#include \"poisson_fem.hpp\"\n#include <boost/python.hpp>\n//#include \"vectorize.hpp\"\n\nnamespace gd {\n\nusing namespace boost::python;\nusing namespace std;\nusing namespace dealii;\n\nvoid py_export_poisson_fem() {\n\tclass_<PoissonFEM<2>, boost::noncopyable >(\"PoissonFEM2d\", init<int>())\n\t\t.def(\"make_grid\", &PoissonFEM<2>::make_grid)\n\t\t.def(\"setup_system\", &PoissonFEM<2>::setup_system)\n\t\t.def(\"refine_grid\", &PoissonFEM<2>::refine_grid)\n\t\t.def(\"assemble_system\", &PoissonFEM<2>::assemble_system)\n\t\t.def(\"solve\", &PoissonFEM<2>::solve)\n\t\t.def(\"output_results\", &PoissonFEM<2>::output_results)\n\t\t.def(\"output_grid\", &PoissonFEM<2>::output_grid)\n\t\t.def(\"eval\", (&PoissonFEM<2>::eval))\n\t\t.def(\"n_active_cells\", (&PoissonFEM<2>::n_active_cells))\n\t\t.def(\"global_refine\", (&PoissonFEM<2>::global_refine))\n\t;\n\tclass_<PoissonFEM<1>, boost::noncopyable >(\"PoissonFEM1d\", init<int>())\n\t\t.def(\"make_grid\", &PoissonFEM<1>::make_grid)\n\t\t.def(\"setup_system\", &PoissonFEM<1>::setup_system)\n\t\t.def(\"refine_grid\", &PoissonFEM<1>::refine_grid)\n\t\t.def(\"assemble_system\", &PoissonFEM<1>::assemble_system)\n\t\t.def(\"solve\", &PoissonFEM<1>::solve)\n\t\t.def(\"output_results\", &PoissonFEM<1>::output_results)\n\t\t.def(\"output_grid\", &PoissonFEM<1>::output_grid)\n\t\t.def(\"eval\", (&PoissonFEM<1>::eval))\n\t\t.def(\"getpoints\", (&PoissonFEM<1>::getpoints))\n\t\t.def(\"n_active_cells\", (&PoissonFEM<1>::n_active_cells))\n\t\t.def(\"grad\", (&PoissonFEM<1>::grad))\n\t\t.def(\"global_refine\", (&PoissonFEM<1>::global_refine))\n\t\t\t\n\t;\n}\n\n\ntemplate <int dim>\nclass RightHandSide : public Function<dim> \n{\npublic:\n\tRightHandSide () : Function<dim>() {}\n\t\n\tvirtual double value (const Point<dim>   &p,\n\t\t\t\t\t\tconst unsigned int  component = 0) const;\n};\ntemplate <int dim>\ndouble RightHandSide<dim>::value (const Point<dim> &p,\n\t\t\t\t\t\t\t\tconst unsigned int /* component */) const \n{\n\tdouble rsq = 0;\n\tfor (unsigned int i=0; i<dim; ++i)\n\t\trsq += std::pow(p(i), 2);\n\tdouble r = sqrt(rsq);\n\tdouble x = p(0);\n\tdouble y = p(1);\n\tdouble phi = fmod(atan2(y, x)+2*M_PI, 2*M_PI);\n\t//return -exp(-pow(r/4-phi, 2));\n\t//return ((r > 10) && (r < 15.0)) * 1.; //3/(4*M_PI) * pow(1+pow(r,2), -5./2);\n\t//return -1; \n\t//return -1/(1+x/20.);\n\treturn -3/(4*M_PI) * pow(1+pow(r/20,2), -5./2);\n}\n\n\ntemplate <int dim>\nPoissonFEM<dim>::PoissonFEM (int order) :\n                 fe (order),\n                dof_handler (triangulation)\n {}\n\ntemplate <int dim>\nvoid PoissonFEM<dim>::make_grid()\n{\n\tconst Point<dim> center;\n\n\tif(dim == 1) {\n\t\tGridGenerator::hyper_cube(triangulation, 0, 40) ;//, 10);\n\t} else {\n\t\tGridGenerator::hyper_ball(triangulation, center, 40.) ;//, 10);\n\t\t//const HyperShellBoundary<dim> boundary_description(center);\n\t\t//triangulation.set_boundary (0, boundary_description);\n\t}\n\t//const HyperShellBoundary<dim> boundary_description(center);\n\t//const HyperShellBoundary<2> boundary_description2(center);\n\t//triangulation.set_boundary (0, boundary_description);\n\t//triangulation.set_boundary (1, boundary_description2);\n\t\n\ttriangulation.refine_global (2);\n\t//triangulation.set_boundary (0);\n\t\n\tstd::cout << \"Number of active cells: \"\n\t\t\t\t<< triangulation.n_active_cells()\n\t\t\t\t<< std::endl;\n\tstd::cout << \"Total number of cells: \"\n\t\t\t\t<< triangulation.n_cells()\n\t\t\t\t<< std::endl;\n\t\n}\n\ntemplate <int dim>\nvoid  PoissonFEM<dim>::setup_system() {\n\tdof_handler.distribute_dofs (fe);\n\tstd::cout << \"Number of degrees of freedom: \"\n\t\t\t<< dof_handler.n_dofs()\n\t\t\t<< std::endl;\n\t\n\tsparsity_pattern.reinit (dof_handler.n_dofs(),\n\t\t\t\t\t\t\tdof_handler.n_dofs(),\n\t\t\t\t\t\t\tdof_handler.max_couplings_between_dofs());\n\tDoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);\n\tsolution.reinit (dof_handler.n_dofs());\n\tsystem_rhs.reinit (dof_handler.n_dofs());\n\t\n\n\thanging_node_constraints.clear ();\n\tDoFTools::make_hanging_node_constraints (dof_handler,\n                                            hanging_node_constraints);\n\thanging_node_constraints.condense (sparsity_pattern);\n\n\thanging_node_constraints.close ();\n\n   sparsity_pattern.compress();\n \n   system_matrix.reinit (sparsity_pattern);\n \n}\n\ntemplate <int dim>\nvoid PoissonFEM<dim>::assemble_system () \n{\n\tQGauss<dim>  quadrature_formula(2);\n\tFEValues<dim> fe_values (fe, quadrature_formula, \n\t\t\t\t\t\t\tupdate_values | update_gradients | update_JxW_values | update_quadrature_points);\n\t\n\tconst RightHandSide<dim> right_hand_side;\n\t\n\t\n\tconst unsigned int   dofs_per_cell = fe.dofs_per_cell;\n\tconst unsigned int   n_q_points    = quadrature_formula.size();\n\t\n\tFullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n\tVector<double>       cell_rhs (dofs_per_cell);\n\t\n\tstd::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\t\n\ttypename DoFHandler<dim>::active_cell_iterator\n\t\tcell = dof_handler.begin_active(),\n\t\tendc = dof_handler.end();\n\tfor (; cell!=endc; ++cell)  {\n\t\tfe_values.reinit (cell);\n\t\n\t\tcell_matrix = 0;\n\t\tcell_rhs = 0;\n \n\t   for (unsigned int i=0; i<dofs_per_cell; ++i) {\n\t\t\tfor (unsigned int j=0; j<dofs_per_cell; ++j) {\n\t\t\t\tfor (unsigned int q_point=0; q_point<n_q_points; ++q_point) {\n\t\t\t\t\t//cout << \"q: \" << fe_values.quadrature_point (q_point) << endl;\n\t\t\t\t\tdouble r = fe_values.quadrature_point (q_point)(0);\n\t\t\t\t\tcell_matrix(i,j) += ( fe_values.shape_grad (i, q_point) *\n\t\t\t\t\t\t\t\t\tfe_values.shape_grad (j, q_point) *\n\t\t\t\t\t                      fe_values.JxW (q_point)) ;/* r * r; //*/\n\t\t\t\t\tcout << \"-> \" <<fe_values.JxW (q_point) << \" \" << r << \" \" << fe_values.shape_grad (i, q_point) << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor (unsigned int i=0; i<dofs_per_cell; ++i) {\n\t\t\tfor (unsigned int q_point=0; q_point<n_q_points; ++q_point) {\n\t\t\t\tdouble r = fe_values.quadrature_point (q_point)(0);\n\t\t\t\tcell_rhs(i) += (fe_values.shape_value (i, q_point) *\n\t\t\t\t\t\t\tright_hand_side.value (fe_values.quadrature_point (q_point)) *\n\t\t\t\t                fe_values.JxW (q_point)) ;/* r * r; //*/\n\t\n\t\t\t\n\t\t\t\tcell->get_dof_indices (local_dof_indices);\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\n\t\tfor (unsigned int i=0; i<dofs_per_cell; ++i)\n\t\tfor (unsigned int j=0; j<dofs_per_cell; ++j)\n\t\t\tsystem_matrix.add (local_dof_indices[i],\n\t\t\t\t\t\t\t\tlocal_dof_indices[j],\n\t\t\t\t\t\t\t\tcell_matrix(i,j));\n\t\n\t\tfor (unsigned int i=0; i<dofs_per_cell; ++i)\n\t\tsystem_rhs(local_dof_indices[i]) += cell_rhs(i);\n\t\t}\n\t//cout << system_matrix << endl;\n\tsystem_matrix.print(cout);\n\tcout << \"next\" << endl;\n\tsystem_rhs.print(cout);\n\thanging_node_constraints.condense (system_matrix);\n\thanging_node_constraints.condense (system_rhs);\n\t\n\tstd::map<unsigned int,double> boundary_values;\n\t//boundary_values[0] = 0;\n\tif(dim == 1) {\n\t\tVectorTools::interpolate_boundary_values (dof_handler,\n\t\t\t\t\t\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\t\t\t\t\t\tConstantFunction<dim>(0),\n\t\t\t\t\t\t\t\t\t\t\t\tboundary_values);\n\t} else {\n\t\tVectorTools::interpolate_boundary_values (dof_handler,\n\t\t\t\t0,\n\t\t\t\tConstantFunction<dim>(0),\n\t\t\t\tboundary_values);\n\t}\n\tMatrixTools::apply_boundary_values (boundary_values,\n\t\t\t\t\t\t\t\t\t\tsystem_matrix,\n\t\t\t\t\t\t\t\t\t\tsolution,\n\t\t\t\t\t\t\t\t\t\tsystem_rhs);\n\tcout << \"boundary:\" << endl;\n\tsystem_matrix.print(cout);\n\tcout << \"next\" << endl;\n\tsystem_rhs.print(cout);\n}\n\ntemplate <int dim>\nPoint<dim> pointr(double r);\n\ntemplate<>\nPoint<1> pointr<1>(double r) {\n\treturn Point<1>(r);\n}\n\ntemplate<>\nPoint<2> pointr<2>(double r) {\n\treturn Point<2>(r, 0);\n}\n\ntemplate<> \nPoint<3> pointr(double r) {\n\treturn Point<3>(r, 0, 0);\n}\n\ntemplate <int dim>\n void PoissonFEM<dim>::solve () \n {\n   SolverControl           solver_control (5000, 1e-12);\n   SolverCG<>              cg (solver_control);\n \n   cg.solve (system_matrix, solution, system_rhs,\n            PreconditionIdentity());\nhanging_node_constraints.distribute (solution);\n\n\tstd::cout << VectorTools::point_value (dof_handler, solution, pointr<dim>(0)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, pointr<dim>(5)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, pointr<dim>(10)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, pointr<dim>(15)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, pointr<dim>(20)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, pointr<dim>(40)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, pointr<dim>(0.1)) << std::endl;\n\t/*std::cout << VectorTools::point_value (dof_handler, solution, Point<2>(40, 0)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, Point<2>(0, 40)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, Point<2>(0, 20)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, Point<2>(1,0)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, Point<2>(0,1)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, Point<2>(2,0)) << std::endl;\n\tdouble a = VectorTools::point_value (dof_handler, solution, Point<2>(1,0))-VectorTools::point_value (dof_handler, solution, Point<2>(0,0));\n\tdouble b = VectorTools::point_value (dof_handler, solution, Point<2>(2,0))-VectorTools::point_value (dof_handler, solution, Point<2>(1,0));\n\tstd::cout << \"a = \" << a << std::endl;\n\tstd::cout << \"b = \" << b << std::endl;\n\tstd::cout << \"a/b = \" << (a/b) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, Point<2>(0, 0)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, Point<2>(0, 5)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, Point<2>(0, 10)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, Point<2>(0, 15)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, Point<2>(0, 20)) << std::endl;\n\tstd::cout << VectorTools::point_value (dof_handler, solution, Point<2>(0, 25)) << std::endl;*/\n\n}\n\ntemplate <int dim>\nvoid PoissonFEM<dim>::getpoints(double_vector p) // for 1d only\n{\n\tdouble* pp = p.data().begin();\n\t/*Triangulation<2>::active_line_iterator\n\t\tcell = triangulation.begin_active_line(),\n\t\tendc = triangulation.end_line();\n\n\tdouble nextx;\n\tconst Point<dim> center;\n\tcout << \"starting.. \" << (cell==endc) << endl; \n\tfor (; cell!=endc; ++cell) {\n\t\tcout << \"-> \" << cell->vertex(0)(0) << endl;\n\t\t*pp++ = (cell->vertex(0))(0);\n\t\tnextx =  (cell->vertex(1))(0);\n\t}\n\t*pp++ = nextx; // only include last point of last cell\n\t*/\n\tauto vertices = triangulation.get_vertices();\n\tauto used = triangulation.get_used_vertices();\n\tfor(int i = 0; i < vertices.size(); i++) {\n\t\tif(used[i]) {\n\t\t\t*pp++ = vertices[i](0);\n\t\t}\n\t}\n}\n\ntemplate <int dim>\ndouble PoissonFEM<dim>::eval(double r) {\n\tFunctions::FEFieldFunction<dim> ff(dof_handler, solution);\n\treturn ff.value(pointr<dim>(r));\n\t//return VectorTools::point_value (dof_handler, solution, pointr<dim>(r));\n}\n\ntemplate <int dim>\ndouble PoissonFEM<dim>::grad(double r) {\n\tFunctions::FEFieldFunction<dim> ff(dof_handler, solution);\n\tauto tensor = ff.gradient(pointr<dim>(r));\n\treturn tensor[0];\n}\n\ntemplate <int dim>\nvoid PoissonFEM<dim>::refine_grid ()\n{\n   Vector<float> estimated_error_per_cell (triangulation.n_active_cells());\n \n   KellyErrorEstimator<dim>::estimate (dof_handler,\n                                       QGauss<dim-1>(3),\n                                       typename FunctionMap<dim>::type(),\n                                       solution,\n                                       estimated_error_per_cell);\n   GridRefinement::refine_and_coarsen_fixed_number (triangulation,\n                                                    estimated_error_per_cell,\n                                                    0.3, 0.03);\ntriangulation.execute_coarsening_and_refinement ();\n\n}\n\ntemplate <int dim>\nvoid PoissonFEM<dim>::output_results () const\n {\n   DataOut<dim> data_out;\n   data_out.attach_dof_handler (dof_handler);\n   data_out.add_data_vector (solution, \"solution\");\n   data_out.build_patches ();\n \n   std::ofstream output (dim == 2 ? \"solution2d.gpl\" : \"solution3d.gpl\" );\n   data_out.write_gnuplot (output);\n   \n\tstd::ofstream outgrid (dim == 2 ? \"grid2d.eps\" : \"grid3d.eps\");\n\tGridOut grid_out;\n\tgrid_out.write_eps (triangulation, outgrid);\n\n \n   std::ofstream output2(dim == 2 ? \"solution2d.vtk\" : \"solution3d.vtk\" );\n   data_out.write_vtk (output2);\n\n }\ntemplate <int dim>\nvoid PoissonFEM<dim>::output_grid(char* filename) const\n{\n\t//DataOut<dim> data_out;\n\t//data_out.attach_dof_handler (dof_handler);\n\t//data_out.add_data_vector (solution, \"solution\");\n\t//data_out.build_patches ();\n\t\n\tstd::ofstream outgrid(filename);\n\tGridOut grid_out;\n\tgrid_out.write_eps(triangulation, outgrid);\n\t\n}\n\ntemplate <int dim>\nint PoissonFEM<dim>::n_active_cells() const\n{\n\treturn triangulation.n_active_cells();\n}\nint refines = 1;\n\n\ntemplate <int dim>\nvoid PoissonFEM<dim>::global_refine(int refine)\n{\n\treturn triangulation.refine_global(refine);\n}\n\n/*\ntemplate <int dim>\nvoid PoissonFEM<dim>::run () \n{\n\tmake_grid();\n\tsetup_system();\n\tassemble_system ();\n\tsolve ();\n\t\n\tfor(int i = 0; i < refines; i++) {\n\t\n\t\trefine_grid();\n\t\tsetup_system();\n\t\tassemble_system ();\n\t\tsolve ();\n\t}\n\toutput_results ();\n }\n*/\n /*int main (int argc, char** argv) \n {\n\tif(argc < 2) {\n\t\tprintf(\"usage: %s <refinements>\\n\", argv[0]);\n\t\texit(-1);\n\t}\n\trefines = atoi(argv[1]);\n\tLaplaceProblem<2> laplace_problem;\n\tlaplace_problem.run ();\n\n\tLaplaceProblem<3> laplace_problem3d;\n\tlaplace_problem3d.run ();\n   return 0;\n }*/\n\n}", "meta": {"hexsha": "8ea509b09043441d9868dcf3e5b0d299f3708c74", "size": 13251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/poisson_fem.cpp", "max_stars_repo_name": "maartenbreddels/mab", "max_stars_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T04:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T04:10:34.000Z", "max_issues_repo_path": "gdfast/src/poisson_fem.cpp", "max_issues_repo_name": "maartenbreddels/mab", "max_issues_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gdfast/src/poisson_fem.cpp", "max_forks_repo_name": "maartenbreddels/mab", "max_forks_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.55, "max_line_length": 140, "alphanum_fraction": 0.6607048525, "num_tokens": 3913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5087214992415904}}
{"text": "#include <iostream>\n#include <fstream>\n#include <xtensor/xmath.hpp>\n#include \"../src/distribution/distribution.cpp\"\n#define BOOST_TEST_MODULE \"Distribution test\"\n#include <boost/test/unit_test.hpp>\n\nusing namespace std;\nnamespace utf = boost::unit_test;\n\nBOOST_AUTO_TEST_CASE(TestLoadDistributions, * utf::tolerance(0.00001))\n{\n\tifstream f(\"../fixtures/distribution.csv\");\n\n\tDistributions distributions(f);\n\n\tBOOST_TEST(distributions.size() == 10);\n\n\tauto keys = distributions.Keys();\n\n\tBOOST_TEST(keys.size() == 10);\n\tBOOST_TEST(keys[4] == \"GCA_001735525.1\");\n\n\tauto dist = distributions[\"GCA_001735525.1\"];\n\n\tBOOST_TEST(dist.size() == 64);\n\tBOOST_TEST(dist[1] == 0.018183);\n\tBOOST_TEST(xt::sum(dist)[0] == 1.0);\n\n\tauto values = distributions.Values();\n\tBOOST_TEST(values(4, 1) == 0.018183);\n\tBOOST_TEST(xt::sum(xt::row(values, 4))[0] == 1.0);\n}\n", "meta": {"hexsha": "6b93524598947cf3ca1df09ad8d055102f3af404", "size": 847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/distribution/test_distribution.cpp", "max_stars_repo_name": "srom/nbias", "max_stars_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/distribution/test_distribution.cpp", "max_issues_repo_name": "srom/nbias", "max_issues_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/distribution/test_distribution.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": 24.9117647059, "max_line_length": 70, "alphanum_fraction": 0.7107438017, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5087214992415904}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// count_less_equal_than.hpp                                                 //\n//                                                                           //\n//  Copyright 2010 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_NON_PARAMETRIC_EMPIRICAL_DISTRIBUTION_CUMULATIVE_COUNT_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_EMPIRICAL_DISTRIBUTION_CUMULATIVE_COUNT_HPP_ER_2010\n\n#include <boost/range.hpp>\n#include <boost/numeric/conversion/converter.hpp>\n\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/parameters/accumulator.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/statistics/detail/non_parametric/empirical_distribution/ordered_sample.hpp>\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace empirical_distribution{\nnamespace impl{\n\n    // T can be an integer or a float\n    template<typename T,typename Comp = std::less<T> >\n\tclass cumulative_count : public boost::accumulators::accumulator_base\n    {\n        typedef Comp comp_;\n        typedef std::size_t size_;\n        typedef boost::accumulators::dont_care dont_care_;\n\n        public:\n\n        typedef size_ result_type;\n        typedef T sample_type;\n\n        cumulative_count(dont_care_){}\n\n        void operator()(dont_care_){}\n\t\t\n        template<typename Args>\n        result_type result(const Args& args)const{\n            namespace ns = statistics::detail::empirical_distribution;\n            typedef ns::tag::ordered_sample tag_;\n            return this->result_impl(\n                boost::accumulators::extract_result<tag_>(\n                    args[ boost::accumulators::accumulator ]\n                ),\n                args[ boost::accumulators::sample ]\n            ); \n        }\n\n        private:\n\t\t\n        template<typename Map>\n        result_type result_impl(\n            Map& map, \n            const sample_type& x\n        )const{\n           return std::for_each(\n                boost::const_begin(map),\n                this->bound(map,x),\n                accumulator()\n           ).value; \n        }\n\n        template<typename Map>\n        typename boost::range_iterator<const Map>::type\n        bound(\n            const Map& map,\n            const sample_type& x\n        )const{\n            return map.upper_bound(x);\n        }\n\n        struct accumulator{\n            mutable size_ value;\n        \t\n            accumulator():value(0){}\n            accumulator(const accumulator& that)\n            \t:value(that.value){}\n            \n            template<typename Data>\n            void operator()(const Data& data)const{\n            \tvalue += data.second;\n            }\n        \n        };\n    };\n    \n}\nnamespace tag\n{\n    struct cumulative_count: boost::accumulators::depends_on<\n        empirical_distribution::tag::ordered_sample\n    >\n    {\n        struct impl{\n            template<typename T,typename W>\n            struct apply{\n                typedef empirical_distribution::impl::cumulative_count<T> type;\n            };\n        };\n    };\n}\nnamespace result_of{\n\n    template<typename AccSet>\n    struct cumulative_count{\n    \ttypedef empirical_distribution::tag::cumulative_count tag_;\n        typedef typename\n            boost::accumulators::detail::template \n            \textractor_result<AccSet,tag_>::type type; \n    };\n\n}\nnamespace extract\n{\n\n    template<typename AccSet,typename T>\n    typename detail::empirical_distribution::result_of::template \n        cumulative_count<AccSet>::type\n  \tcumulative_count(AccSet const& acc,const T& x)\n    { \n        namespace ns = detail::empirical_distribution;\n    \ttypedef ns::tag::cumulative_count tag_;\n        return boost::accumulators::extract_result<tag_>(\n            acc,\n            (boost::accumulators::sample = x)\n        );\n  \t}\n\n}// extract\n}// empirical_distribution\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "87678c26d7f49aeed966d7b3190365421aab11e9", "size": 4421, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/empirical_distribution/cumulative_count.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": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/empirical_distribution/cumulative_count.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": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/empirical_distribution/cumulative_count.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.7013888889, "max_line_length": 98, "alphanum_fraction": 0.5887808188, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5087214939018303}}
{"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 *    References\n *      Mireles James, J.D. Celestial Mechanics Notes Set 4: The Circular Restricted Three Body\n *          Problem, 2006, http://www.math.utexas.edu/users/jjames/hw4Notes.pdf,\n *          last accessed: 26 May, 2012.\n *      JPL, NASA. Astrodynamic Constants, http://ssd.jpl.nasa.gov/?constants,\n *        last updated: 13 Dec, 2012, last accessed: 19th March, 2013.\n *\n *    Notes\n *      Reference values for position Lagrange libration points are taken from (Mireles James,\n *      2006). There seems to be a bug in the computation of the L3 location! Note that this code\n *      uses the Planet class (in Bodies sub-directory), which is marked for deprecation.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <cmath>\n#include <limits>\n\n#include <boost/make_shared.hpp>\n#include <memory>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/celestialBodyConstants.h\"\n#include \"Tudat/Astrodynamics/Gravitation/librationPoint.h\"\n#include \"Tudat/Mathematics/RootFinders/newtonRaphson.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace root_finders;\n\nBOOST_AUTO_TEST_SUITE( test_libration_points )\n\n//! Test if computation of mass parameter is working correctly.\nBOOST_AUTO_TEST_CASE( testComputationOfMassParameter )\n{\n    // Set expected mass parameter for Earth-Moon system.\n    const double expectedMassParameter = 0.0121505811805237;\n\n    // Set Earth gravitational parameter.\n    const double earthGravitationalParameter\n            = celestial_body_constants::EARTH_GRAVITATIONAL_PARAMETER;\n\n    // Set Moon gravitational parameter (Earth/Moon mass ratio taken from (JPL, 2012).\n    const double moonGravitationalParameter = earthGravitationalParameter / 81.30059;\n\n    // Compute mass parameter.\n    const double computedMassParameter = circular_restricted_three_body_problem::computeMassParameter(\n                earthGravitationalParameter, moonGravitationalParameter );\n\n    // Check if computed value corresponds to expected mass parameter.\n    BOOST_CHECK_CLOSE_FRACTION( expectedMassParameter, computedMassParameter, 1.0e-14 );\n}\n\n//! Test if computation of location of L1 Lagrange libration point is working correctly.\nBOOST_AUTO_TEST_CASE( testComputationOfLocationOfL1LibrationPoint )\n{\n    // Declare and initialize Earth-Moon mass parameter from (Mireles James, 2006).\n    const double earthMoonMassParameter = 0.012277471;\n\n    // Set expected location of L1.\n    const Eigen::Vector3d expectedLocationOfL1( 0.83629259089993, 0.0, 0.0 );\n\n    // Declare L1 libration point object with Earth-Moon mass parameter and Newton-Raphson method\n    // with 1000 iterations as maximum and 1.0e-14 relative X-tolerance.\n    circular_restricted_three_body_problem::LibrationPoint librationPointL1( earthMoonMassParameter,\n                                            std::make_shared< NewtonRaphson >( 1.0e-14, 1000 ) );\n\n    // Compute location of Lagrange libration point.\n    librationPointL1.computeLocationOfLibrationPoint( circular_restricted_three_body_problem::LibrationPoint::l1 );\n\n    // Determine location of libration point in Earth-Moon system.\n    const Eigen::Vector3d positionOflibrationPointL1\n            = librationPointL1.getLocationOfLagrangeLibrationPoint( );\n\n    // Check if computed location of L1 matches expected location.\n    BOOST_CHECK_CLOSE_FRACTION( expectedLocationOfL1.x( ),\n                                positionOflibrationPointL1.x( ),\n                                1.0e-14 );\n    BOOST_CHECK_SMALL( positionOflibrationPointL1.y( ), std::numeric_limits< double >::min( ) );\n    BOOST_CHECK_SMALL( positionOflibrationPointL1.z( ), std::numeric_limits< double >::min( ) );\n}\n\n//! Test if computation of location of L2 Lagrange libration point is working correctly.\nBOOST_AUTO_TEST_CASE( testComputationOfLocationOfL2LibrationPoint )\n{\n    // Declare and initialize Earth-Moon mass parameter from (Mireles James, 2006).\n    const double earthMoonMassParameter = 0.012277471;\n\n    // Set expected location of L2.\n    const Eigen::Vector3d expectedLocationOfL2( 1.15616816590553, 0.0, 0.0 );\n\n    // Declare L2 libration point object with Earth-Moon mass parameter and Newton-Raphson method\n    // with 1000 iterations as maximum and 1.0e-14 relative X-tolerance.\n    circular_restricted_three_body_problem::LibrationPoint librationPointL2( earthMoonMassParameter,\n                                            std::make_shared< NewtonRaphson >( 1.0e-14, 1000 ) );\n\n    // Compute location of Lagrange libration point.\n    librationPointL2.computeLocationOfLibrationPoint( circular_restricted_three_body_problem::LibrationPoint::l2 );\n\n    // Determine location of libration point in Earth-Moon system.\n    const Eigen::Vector3d positionOflibrationPointL2\n            = librationPointL2.getLocationOfLagrangeLibrationPoint( );\n\n    // Check if computed location of L2 matches expected location.\n    BOOST_CHECK_CLOSE_FRACTION( expectedLocationOfL2.x( ),\n                                positionOflibrationPointL2.x( ),\n                                1.0e-14 );\n    BOOST_CHECK_SMALL( positionOflibrationPointL2.y( ), std::numeric_limits< double >::min( ) );\n    BOOST_CHECK_SMALL( positionOflibrationPointL2.z( ), std::numeric_limits< double >::min( ) );\n}\n\n//! Test if computation of location of L3 Lagrange libration point is working correctly.\n// THERE IS A BUG IN THIS CASE!\nBOOST_AUTO_TEST_CASE( testComputationOfLocationOfL3LibrationPoint )\n{\n    // Declare and initialize Earth-Moon mass parameter from (Mireles James, 2006).\n    const double earthMoonMassParameter = 0.012277471;\n\n    // Set expected location of L3.\n    const Eigen::Vector3d expectedLocationOfL3( -1.00511551160689, 0.0, 0.0 );\n\n    // Declare L3 libration point object with Earth-Moon mass parameter and Newton-Raphson method\n    // with 1000 iterations as maximum and 1.0e-14 relative X-tolerance.\n    circular_restricted_three_body_problem::LibrationPoint librationPointL3( earthMoonMassParameter,\n                                            std::make_shared< NewtonRaphson >( 1.0e-14, 1000 ) );\n\n    // Compute location of Lagrange libration point.\n    librationPointL3.computeLocationOfLibrationPoint( circular_restricted_three_body_problem::LibrationPoint::l3 );\n\n    // Determine location of libration point in Earth-Moon system.\n    const Eigen::Vector3d positionOflibrationPointL3\n            = librationPointL3.getLocationOfLagrangeLibrationPoint( );\n\n    // Check if computed location of L3 matches expected location.\n    BOOST_CHECK_CLOSE_FRACTION( expectedLocationOfL3.x( ),\n                                positionOflibrationPointL3.x( ),\n                                1.0e-2 );\n    BOOST_CHECK_SMALL( positionOflibrationPointL3.y( ), std::numeric_limits< double >::min( ) );\n    BOOST_CHECK_SMALL( positionOflibrationPointL3.z( ), std::numeric_limits< double >::min( ) );\n}\n\n//! Test if computation of location of L4 Lagrange libration point is working correctly.\nBOOST_AUTO_TEST_CASE( testComputationOfLocationOfL4LibrationPoint )\n{\n    // Declare and initialize Earth-Moon mass parameter from (Mireles James, 2006).\n    const double earthMoonMassParameter = 0.012277471;\n\n    // Set expected location of L4.\n    const Eigen::Vector3d expectedLocationOfL4( 0.487722529, 0.86602540378444, 0.0 );\n\n    // Declare L4 libration point object with Earth-Moon mass parameter and Newton-Raphson method\n    // with 1000 iterations as maximum and 1.0e-14 relative X-tolerance.\n    circular_restricted_three_body_problem::LibrationPoint librationPointL4( earthMoonMassParameter,\n                                            std::make_shared< NewtonRaphson >( 1.0e-14, 1000 ) );\n\n    // Compute location of Lagrange libration point.\n    librationPointL4.computeLocationOfLibrationPoint( circular_restricted_three_body_problem::LibrationPoint::l4 );\n\n    // Determine location of libration point in Earth-Moon system.\n    const Eigen::Vector3d positionOflibrationPointL4\n            = librationPointL4.getLocationOfLagrangeLibrationPoint( );\n\n    // Check if computed location of L4 matches expected location.\n    BOOST_CHECK_CLOSE_FRACTION( expectedLocationOfL4.x( ),\n                                positionOflibrationPointL4.x( ),\n                                1.0e-15 );\n    BOOST_CHECK_CLOSE_FRACTION( expectedLocationOfL4.y( ),\n                                positionOflibrationPointL4.y( ),\n                                1.0e-14 );\n    BOOST_CHECK_SMALL( positionOflibrationPointL4.z( ), std::numeric_limits< double >::min( ) );\n}\n\n//! Test if computation of location of L5 Lagrange libration point is working correctly.\nBOOST_AUTO_TEST_CASE( testComputationOfLocationOfL5LibrationPoint )\n{\n    // Declare and initialize Earth-Moon mass parameter from (Mireles James, 2006).\n    const double earthMoonMassParameter = 0.012277471;\n\n    // Set expected location of L5.\n    const Eigen::Vector3d expectedLocationOfL5( 0.487722529, -0.86602540378444, 0.0 );\n\n    // Declare L5 libration point object with Earth-Moon mass parameter and Newton-Raphson method\n    // with 1000 iterations as maximum and 1.0e-14 relative X-tolerance.\n    circular_restricted_three_body_problem::LibrationPoint librationPointL5( earthMoonMassParameter,\n                                            std::make_shared< NewtonRaphson >( 1.0e-14, 1000 ) );\n\n    // Compute location of Lagrange libration point.\n    librationPointL5.computeLocationOfLibrationPoint( circular_restricted_three_body_problem::LibrationPoint::l5 );\n\n    // Determine location of libration point in Earth-Moon system.\n    const Eigen::Vector3d positionOflibrationPointL5\n            = librationPointL5.getLocationOfLagrangeLibrationPoint( );\n\n    // Check if computed location of L5 matches expected location.\n    BOOST_CHECK_CLOSE_FRACTION( expectedLocationOfL5.x( ),\n                                positionOflibrationPointL5.x( ),\n                                1.0e-15 );\n    BOOST_CHECK_CLOSE_FRACTION( expectedLocationOfL5.y( ),\n                                positionOflibrationPointL5.y( ),\n                                1.0e-14 );\n    BOOST_CHECK_SMALL( positionOflibrationPointL5.z( ), std::numeric_limits< double >::min( ) );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "b9e267b7461c426617cbbbf942da286a84226b99", "size": 10738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Gravitation/UnitTests/unitTestLibrationPoints.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/unitTestLibrationPoints.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/unitTestLibrationPoints.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": 48.3693693694, "max_line_length": 115, "alphanum_fraction": 0.7158688769, "num_tokens": 2617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.5086562374294864}}
{"text": "#ifndef YANNQ_TESTS_LAYERHELPER_HPP\n#define YANNQ_TESTS_LAYERHELPER_HPP\n#include <Eigen/Dense>\n#include <sstream>\n\n#include <Machines/layers/AbstractLayer.hpp>\n#include <Utilities/type_traits.hpp>\n\ntemplate<typename T>\ntypename yannq::AbstractLayer<T>::Matrix\nndiff_in(yannq::AbstractLayer<T>& layer, const typename yannq::AbstractLayer<T>::Vector& input, const int outSize)\n{\n\tusing Vector = typename yannq::AbstractLayer<T>::Vector;\n\tusing Matrix = typename yannq::AbstractLayer<T>::Matrix;\n\tMatrix mat(input.size(), outSize);\n\tVector output1(outSize);\n\tVector output2(outSize);\n\tconst typename yannq::remove_complex<T>::type h = 1e-5;\n\n\tVector inH = input;\n\tfor(int i = 0; i < input.size(); i++)\n\t{\n\t\tinH(i) += h;\n\t\tlayer.forward(inH,output1);\n\t\tinH(i) = input(i) - h;\n\t\tlayer.forward(inH,output2);\n\t\tmat.row(i) = (output1 - output2)/(2*h);\n\t\tinH(i) = input(i);\n\t}\n\treturn mat;\n}\ntemplate<typename T>\ntypename yannq::AbstractLayer<T>::Matrix\nndiff_weight(yannq::AbstractLayer<T>& layer, const typename yannq::AbstractLayer<T>::Vector& input, const int outSize)\n{\n\tusing Vector = typename yannq::AbstractLayer<T>::Vector;\n\tusing Matrix = typename yannq::AbstractLayer<T>::Matrix;\n\tMatrix mat(layer.paramDim(), outSize);\n\tVector output1(outSize);\n\tVector output2(outSize);\n\tconst typename yannq::remove_complex<T>::type h = 1e-5;\n\n\tVector wH = layer.getParams();\n\tfor(int i = 0; i < wH.size(); i++)\n\t{\n\t\tconst auto val = wH(i);\n\n\t\twH(i) = val + h;\n\t\tlayer.setParams(wH);\n\t\tlayer.forward(input,output1);\n\n\t\twH(i) = val - h;\n\t\tlayer.setParams(wH);\n\t\tlayer.forward(input,output2);\n\n\t\tmat.row(i) = (output1 - output2)/(2*h);\n\t\twH(i) = val;\n\t}\n\treturn mat;\n}\n\n\n#endif//YANNQ_TESTS_LAYERHELPER_HPP\n", "meta": {"hexsha": "c05ef9492b4043d6911fe0efdf75766968ba1b8f", "size": 1693, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Tests/LayerHelper.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": "Tests/LayerHelper.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": "Tests/LayerHelper.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": 26.453125, "max_line_length": 118, "alphanum_fraction": 0.7040756054, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.5085003845447705}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <utility>\n#include <cmath>\n#include \"ray.hpp\"\n#include \"interaction.hpp\"\n#include \"mathext.hpp\"\n#include \"config.hpp\"\n\n\nextern Config conf;\n\n\nclass Light\n{\npublic:\n    Light(Eigen::Vector3f pos, Eigen::Vector3f color)\n        : m_Pos(std::move(pos)),\n        m_Color(std::move(color))\n    {\n    }\n    virtual ~Light() = default;\n\n    /* Sample a point on the light's surface, if light is not delta light\n     * Set PDF and the surface position\n     * Return color of light\n     */\n    virtual Eigen::Vector3f sampleSurfacePos(float* pdf = nullptr) = 0;\n\n    virtual float sampleSurfacePdf() = 0;\n\n    virtual bool isHit(Ray* ray, float* hit_t = nullptr) = 0;\n\n    virtual Eigen::Vector3f emission(Eigen::Vector3f d) = 0;\n    \n    Eigen::Vector3f m_Pos;\n    Eigen::Vector3f m_Color;\n};\n\nclass AreaLight:public Light\n{\npublic:\n    float radius;\n    Eigen::Vector3f normal;\n    Eigen::Vector3f right;\n\n    AreaLight(Eigen::Vector3f pos, Eigen::Vector3f color,\n        float r = 1.0f, Eigen::Vector3f n = Eigen::Vector3f(0.0f, -1.0f, 0.0f))\n    : Light(pos, color), radius(r), normal(n.normalized())\n    {\n        right = mathext::rot_align_normal(normal) * Eigen::Vector3f(1.0f, 0.0f, 0.0f);\n    }\n\n    float sampleSurfacePdf()\n    {\n        return PI_INV / (radius * radius);\n    }\n\n    Eigen::Vector3f sampleSurfacePos(float* pdf = nullptr) override\n    {\n        Eigen::Vector2f sample = mathext::disk(radius);\n        /* Convert polar to cartesian coordinate */\t\n        Eigen::Vector3f sampled_light_pos = m_Pos + (Eigen::AngleAxisf(sample.y(), normal) * (sample.x() * right));\n\n        /* Compute PDF of sampling a point in the area light */\n        if (pdf) {\n            *pdf = sampleSurfacePdf();\n        }\n\n        return sampled_light_pos;\n    }\n\n    Eigen::Vector3f emission(Eigen::Vector3f d) override\n    {\n        return conf.light_power * m_Color * abs(d.dot(normal));\n    }\n    \n    /* \n     * Reference: https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-plane-and-ray-disk-intersection\n     */\n    bool isHit(Ray* ray, float* hit_t = nullptr) override\n    {\n        float d = ray->m_Dir.dot(normal);\n\n        if (abs(d) < EPSILON) {\n            return false;\n        }\n\n        float t = (m_Pos - ray->m_Ori).dot(normal) / d;\n        if (t < 0) {\n            return false;\n        }\n\n        Eigen::Vector3f isect = ray->getPoint(t);\n        bool is_hit = (isect - m_Pos).norm() <= radius;\n\n        if (is_hit && hit_t) {\n            *hit_t = t;\n        }\n\n        return is_hit;\n    }\n};", "meta": {"hexsha": "91669d0c8b91c054050cd02f77d7053090249c63", "size": 2628, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "global_illumination/head/light.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/light.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/light.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": 25.2692307692, "max_line_length": 153, "alphanum_fraction": 0.601217656, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5085003845447704}}
{"text": "//\n// Created by keszocze on 15.10.18.\n//\n\n#pragma once\n\n#include <vector>\n#include <cudd/cplusplus/cuddObj.hh>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#include \"number_representation.hpp\"\n\nnamespace abo::error_metrics {\n\n    using abo::util::NumberRepresentation;\n\n    /**\n     * @brief Computes the maximal value of a function represented by a vector of BDDs\n     *\n     * The function is assumed to return an natural number\n     *\n     * @param mgr\n     * @param fun The function given by a vector of BDDs\n     */\n    boost::multiprecision::uint256_t get_max_value(const Cudd &mgr, const std::vector<BDD> &fun);\n\n    /**\n     * @brief Computes the maximum absolute difference between the f and f_hat for any input\n     * The computation is performed symbolically using BDDs\n     * @param mgr The BDD object manager\n     * @param f The original function\n     * @param f_hat The approximated function. Must have the same number of bits as f\n     * @param num_rep The number representation for f and f_hat\n     * @return The maximum absolute difference\n     */\n    boost::multiprecision::uint256_t\n        worst_case_error(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &f_hat,\n                             const NumberRepresentation num_rep= NumberRepresentation::BaseTwo);\n\n    /**\n     * @brief Computes the maximum absolute difference between the f and f_hat for any input\n     * divided by 2^n - 1 to normalize it to the range [0, 1] regardless of the function size (with n = f.size())\n     * This is mainly intended to be a helper function to make the use of the worst case error easier\n     * @param mgr The BDD object manager\n     * @param f The original function\n     * @param f_hat The approximated function. Must have the same number of bits as f\n     * @param num_rep The number representation for f and f_hat\n     * @return The maximum absolute difference normalized to [0, 1]\n     */\n    double worst_case_error_percent(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &f_hat,\n                         const NumberRepresentation num_rep= NumberRepresentation::BaseTwo);\n\n\n    /**\n     * @brief Computes the maximum absolute difference between the f and f_hat for any input\n     * The computation is performed using BDDs and will be typically slow compared to the BDD based variant\n     * @param mgr The BDD object manager\n     * @param f The original function\n     * @param f_hat The approximated function. Must have the same number of bits as f\n     * @param num_rep The number representation for f and f_hat\n     * @return The maximum absolute difference\n     */\n    boost::multiprecision::uint256_t\n        worst_case_error_add(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &f_hat,\n                             const NumberRepresentation num_rep = NumberRepresentation::BaseTwo);\n\n    /**\n     * @brief approximate_worst_case_error\n     *  Calculates the worst case error approximately, to a given relative error.\n     *  The time and memory this function uses scales exponentially with the desired precision (n) (in the worst case).\n     *  With m being the input size (f, f_hat), in the worst case, it lies in O(m ^ n).\n     * @param mgr\n     * @param f\n     * @param f_hat\n     * @param n The precision to calculate in number of bits, for more details see the return value. It must be greater than zero\n     * @param num_rep The number representation for f and f_hat\n     * @return The approximated worst case error. It is an upper bound and therefore guaranteed to be larger\n     *  than the actual error. Let wc be the correct worst case error and x be the result of this function.\n     *  Then it holds that wc <= x <= wc * (1 + 1 / (2 ^ (n + 1) - 1)))\n     */\n    boost::multiprecision::uint256_t approximate_worst_case_error(const Cudd &mgr, const std::vector<BDD> &f,\n                                                                  const std::vector<BDD> &f_hat, int n,\n                                                                  const NumberRepresentation num_rep = NumberRepresentation::BaseTwo);\n\n}\n", "meta": {"hexsha": "1d9240ccfadc626401fae5bc5271973d66b36370", "size": 4150, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/error_metrics/worst_case_error.hpp", "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/worst_case_error.hpp", "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/worst_case_error.hpp", "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": 47.7011494253, "max_line_length": 134, "alphanum_fraction": 0.6706024096, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5085003792925807}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_TOOLBOX_EXPONENTIAL_FUNCTION_SCALAR_IMPL_LOGS_D_LOG_HPP_INCLUDED\n#define NT2_TOOLBOX_EXPONENTIAL_FUNCTION_SCALAR_IMPL_LOGS_D_LOG_HPP_INCLUDED\n\n#include <boost/fusion/include/vector_tie.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/tofloat.hpp>\n#include <nt2/include/functions/is_nan.hpp>\n#include <nt2/include/functions/is_ltz.hpp>\n#include <nt2/include/functions/is_eqz.hpp>\n#include <nt2/include/functions/fast_frexp.hpp>\n#include <nt2/include/functions/genmask.hpp>\n#include <nt2/include/functions/amul.hpp>\n#include <nt2/include/functions/minusone.hpp>\n#include <nt2/include/functions/madd.hpp>\n#include <nt2/sdk/constant/digits.hpp>\n#include <nt2/sdk/constant/real.hpp>\n\nnamespace nt2\n{\n  namespace details\n  {\n    namespace internal\n    {\n      //////////////////////////////////////////////////////////////////////////////\n      // math log functions\n      //////////////////////////////////////////////////////////////////////////////\n\n      template < class A0 > \n      struct logarithm< A0, tag::not_simd_type, double>\n      {\n\tstatic inline void kernel_log(const A0& a0,\n\t\t\t\t      A0& dk,\n\t\t\t\t      A0& hfsq,\n\t\t\t\t      A0& s,\n\t\t\t\t      A0& R,\n\t\t\t\t      A0& f)\n\t{\n\t  typedef typename meta::as_integer<A0, signed>::type int_type;\n\t  typedef typename meta::scalar_of<A0>::type               sA0;\n\t  A0 x;\n\t  int_type k;\n\t  boost::fusion::vector_tie(x, k) = fast_frexp(a0);\n\t  const int_type x_lt_sqrthf = -is_greater(Sqrt_2o_2<A0>(), x);\n\t  k += x_lt_sqrthf;\n\t  f = minusone(x+b_and(x, genmask(x_lt_sqrthf)));\n\t  dk = tofloat(k);\n\t  s = f/add(Two<A0>(),f);\n\t  A0 z = sqr(s);\n\t  A0 w = sqr(z);\n\t  A0 t1= w*horner<NT2_HORNER_COEFF_T(sA0, 3,\n\t\t\t\t\t (0x3fc39a09d078c69fll, \n\t\t\t\t\t  0x3fcc71c51d8e78afll,\n\t\t\t\t\t  0x3fd999999997fa04ll)\n\t\t\t\t\t )> (w);\n\t  A0 t2= z*horner<NT2_HORNER_COEFF_T(sA0, 4,\n\t\t\t\t       (0x3fc2f112df3e5244ll,\n\t\t\t\t\t0x3fc7466496cb03dell,\n\t\t\t\t\t0x3fd2492494229359ll,\n\t\t\t\t\t0x3fe5555555555593ll)\n\t\t\t)> (w);\n\t  R = t2+t1;\n\t  hfsq = mul(Half<A0>(), sqr(f));\n\t}\n\t\n\tstatic inline A0 log(const A0& a0)\n\t{\n\t  // ln(2)hi  =  6.93147180369123816490e-01  or  0x3fe62e42fee00000\n\t  // ln(2)lo  =  1.90821492927058770002e-10  or  0x3dea39ef35793c76\n\t  if (a0 == Inf<A0>()) return a0;\n\t  if (is_eqz(a0)) return Minf<A0>();\n\t  if (nt2::is_nan(a0)||is_ltz(a0)) return Nan<A0>();\n\t  A0 dk, hfsq, s, R, f;\n\t  kernel_log(a0, dk, hfsq, s, R, f);\n\t  return  mul(dk, double_constant<A0, 0x3fe62e42fee00000ll>())-\n\t    ((hfsq-(s*(hfsq+R)+mul(dk,double_constant<A0, 0x3dea39ef35793c76ll>())))-f);\n\t}\n\tstatic inline A0 log2(const A0& a0)\n\t{\n\t  if (a0 == Inf<A0>()) return a0;\n\t  if (is_eqz(a0)) return Minf<A0>();\n\t  if (nt2::is_nan(a0)||is_ltz(a0)) return Nan<A0>();\n\t  A0 dk, hfsq, s, R, f;\n\t  kernel_log(a0, dk, hfsq, s, R, f);\n\t  return -(hfsq-(s*(hfsq+R))-f)*Invlog_2<A0>()+dk;\n\t}\n\t\n\tstatic inline A0 log10(const A0& a0)\n\t{\n\t  if (a0 == Inf<A0>()) return a0;\n\t  if (is_eqz(a0)) return Minf<A0>();\n\t  if (nt2::is_nan(a0)||is_ltz(a0)) return Nan<A0>();\n\t  A0 dk, hfsq, s, R, f;\n\t  kernel_log(a0, dk, hfsq, s, R, f);\n\t  return -(hfsq-(s*(hfsq+R))-f)*Invlog_10<A0>()+dk*Log_2olog_10<A0>();\n\t}\n      }; \n    }\n  }\n}\n\n\n#endif\n\n// /////////////////////////////////////////////////////////////////////////////\n// End of d_log.hpp\n// /////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "39a14502853d55a976541eb794ae7f230e5b94f8", "size": 3849, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/exponential/include/nt2/toolbox/exponential/function/scalar/impl/logs/d_log.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/exponential/include/nt2/toolbox/exponential/function/scalar/impl/logs/d_log.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "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": "modules/exponential/include/nt2/toolbox/exponential/function/scalar/impl/logs/d_log.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "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.4695652174, "max_line_length": 84, "alphanum_fraction": 0.5598856846, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117812622842, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5085003766664858}}
{"text": "#include <iostream>\r\n#include <fstream>\r\n\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <opencv2/imgproc/imgproc.hpp>\r\n\r\n#include <geometry/draw.hpp>\r\n#include <imgproc/gradient_adapter.hpp>\r\n#include <imgproc/derivative_gradient.hpp>\r\n#include <imgproc/susan.hpp>\r\n#include <imgproc/rcmg.hpp>\r\n#include <imgproc/quadratureG2.hpp>\r\n#include <imgproc/quadratureS.hpp>\r\n#include <imgproc/quadratureSF.hpp>\r\n#include <imgproc/quadratureLGF.hpp>\r\n#include <imgproc/pc_sqf.hpp>\r\n#include <imgproc/pc_lgf.hpp>\r\n#include <imgproc/pc_matlab.hpp>\r\n#include <imgproc/image_operator.hpp>\r\n#include <utility/matlab_helpers.hpp>\r\n\r\n#include <boost/filesystem.hpp>\r\n#include <boost/algorithm/string.hpp>  \r\n#include <boost/format.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n\r\n#define WRITE_IMAGE_FILES\r\n//#define SHOW_IMAGES\r\n\r\nusing namespace lsfm;\r\nusing namespace std;\r\nnamespace fs = boost::filesystem;\r\n\r\n\r\nstd::string path = \"./orientation/\", fname;\r\nint stepsi = -1, steps = 45;\r\ndouble magTh = 0.1;\r\n\r\nconstexpr int ENTRY_HALF_RANGE = 1;\r\n\r\ntemplate<class GT, class MT = int, class DT = double>\r\nstruct Entry {\r\n    Entry() :  flags(0) {}\r\n    Entry(const cv::Ptr<GradientI<uchar, GT, MT, DT>>& a, const std::string& b, int f = 0)\r\n        : grad(a), name(b), flags(f) {}\r\n    \r\n    cv::Ptr<GradientI<uchar, GT, MT, DT>> grad;\r\n    std::string name;\r\n    int flags;\r\n\r\n    inline bool hr() const {\r\n        return flags & ENTRY_HALF_RANGE;\r\n    }\r\n\r\n    inline cv::Mat process(const cv::Mat src) {\r\n        grad->process(src);\r\n        return grad->magnitude();\r\n    }\r\n\r\n    cv::Mat fixGrad(const cv::Mat &m) const {\r\n        cv::Mat mag;\r\n        if (m.type() != CV_32F)\r\n            m.convertTo(mag, CV_32F);\r\n        else\r\n            m.copyTo(mag);\r\n\r\n        double vmin, vmax;\r\n        cv::minMaxIdx(mag, &vmin, &vmax);\r\n        // laplace\r\n        if (vmin < 0) {\r\n            vmax = std::max(vmax, -vmin);\r\n            mag = cv::abs(mag);\r\n            mag *= 255.0 / vmax;\r\n        }\r\n        else {\r\n            mag -= vmin;\r\n            mag *= 255.0 / (vmax - vmin);\r\n        }\r\n        mag.convertTo(mag, CV_8U);\r\n        return mag;\r\n    }\r\n};\r\n\r\ndouble error(const cv::Mat &gt, const cv::Mat &dir, bool hr = false) {\r\n    cv::Mat res = cv::abs(gt - dir);\r\n    cv::subtract(2 * CV_PI, res, res, res > CV_PI);\r\n    if (hr)\r\n        cv::subtract(CV_PI, res, res, res > CV_PI / 2);\r\n#ifdef WRITE_IMAGE_FILES\r\n    cv::Mat write = res / CV_PI * 2550;\r\n    write.convertTo(write, CV_8U);\r\n    if (stepsi < 0)\r\n        cv::imwrite(path + fname + \"-error.png\", write);\r\n    else\r\n        cv::imwrite(path + boost::str(boost::format(\"%04d-\") % stepsi) + fname + \"-error.png\", write);\r\n#endif\r\n#ifdef SHOW_IMAGES\r\n    imshow(\"error\", res / CV_PI * 10);\r\n    cv::waitKey();\r\n#endif\r\n    return cv::sum(res)[0];\r\n}\r\n\r\n\r\ntemplate<class GT, class MT = int, class DT = float>\r\ndouble testSingle(Entry<GT, MT, DT> &e, const cv::Mat &img, const cv::Mat &mask, double rot = 0, double noise = 0) {\r\n\r\n    RotateOperator<double> op_rot(rot, cv::Point2d(127, 127), cv::INTER_CUBIC);\r\n    RotateOperator<double> op_rot_mask(rot, cv::Point2d(127, 127), cv::INTER_NEAREST);\r\n    GaussianNoiseOperator op_noise(noise);\r\n    \r\n    cv::Mat gt(mask.size(),CV_64F);\r\n    gt.setTo(0);\r\n\r\n    gt.setTo(-rot, mask == 1);\r\n    gt.setTo(-rot + CV_PI/2, mask == 2);\r\n\r\n    if (e.hr()) {\r\n        gt.setTo(-rot, mask == 3);\r\n        gt.setTo(-rot + CV_PI / 2, mask == 4);\r\n    }\r\n    else\r\n    {\r\n        gt.setTo(-rot + CV_PI, mask == 3);\r\n        gt.setTo(-rot -  CV_PI / 2, mask == 4);\r\n    }\r\n\r\n    cv::Mat nimg;\r\n    img.copyTo(nimg);\r\n\r\n    //cv::imshow(\"img\", img);\r\n\r\n    cv::Mat nmask;\r\n    mask.copyTo(nmask);\r\n    if (rot > 0) {\r\n        op_rot(nimg);\r\n        op_rot_mask(nmask);\r\n        op_rot_mask(gt);\r\n    }\r\n\r\n    int num = static_cast<int>(cv::sum(gt > 0)[0]) / 255;\r\n    if (noise > 0)\r\n        op_noise(nimg);\r\n\r\n    e.grad->process(nimg);\r\n    cv::Mat dir = e.grad->direction();\r\n    dir.setTo(0, nmask == 0);\r\n\r\n#ifdef WRITE_IMAGE_FILES\r\n    cv::imwrite(path + boost::str(boost::format(\"%04d-\") % stepsi) + fname + \".png\", nimg);\r\n    cv::imwrite(path + boost::str(boost::format(\"%04d-\") % stepsi) + fname + \"-mask.png\", nmask > 0);\r\n#endif\r\n#ifdef SHOW_IMAGES\r\n    cv::imshow(\"img\", nimg);\r\n    cv::imshow(\"mask\", nmask > 0);\r\n    //cv::imshow(\"gt\", gt > 0);\r\n    cv::imshow(\"cA\", quiverDir<DT, uchar>(nimg, gt, Range<double>(-CV_PI, CV_PI), nmask > 0, 2, 2, 1, 8, 1));\r\n    cv::imshow(\"cB\", quiverDir<DT, uchar>(nimg, dir, Range<double>(-CV_PI, CV_PI), nmask > 0, 2, 2, 1, 8, 1));\r\n    //cv::imshow(e.name + \"-mask\", nmask > 0);\r\n    std::cout << rot << std::endl;\r\n#endif\r\n    \r\n\r\n    return error(gt, dir, e.hr()) / num;\r\n    \r\n}\r\n\r\ncv::Mat boxImage() {\r\n    cv::Mat img(256, 256, CV_8U);\r\n    img.setTo(85);\r\n    img.rowRange(47, 208).colRange(47, 208).setTo(170);\r\n    return img;\r\n}\r\n\r\ntemplate<class GT, class MT = int, class DT = float>\r\ndouble testBox(Entry<GT,MT,DT> &e, cv::Mat img, cv::Mat mask, double blur = 0, double noise = 0) {\r\n    GaussianBlurOperator op_blur(blur);\r\n    \r\n    if (blur > 0)\r\n        op_blur(img);\r\n        \r\n    // remove borders dependong on blur\r\n    int ks = cvRound(blur * 6 + 1) | 1;\r\n    // make sure that border has at least the size of greatest filter kernel (7x7)\r\n    if (ks < 9)\r\n        ks = 9;\r\n    mask.rowRange(47 - ks, 47 + ks).colRange(47 - ks, 47 + ks).setTo(0);\r\n    mask.rowRange(207 - ks, 207 + ks).colRange(47 - ks, 47 + ks).setTo(0);\r\n    mask.rowRange(47 - ks, 47 + ks).colRange(207 - ks, 207 + ks).setTo(0);\r\n    mask.rowRange(207 - ks, 207 + ks).colRange(207 - ks, 207 + ks).setTo(0);\r\n\r\n    cv::Mat tmp = mask.rowRange(47 + ks, 207 - ks).colRange(47 - ks, 47 + ks);\r\n    tmp.setTo(1, tmp > 0);\r\n\r\n    tmp = mask.rowRange(47 - ks, 47 + ks).colRange(47 + ks, 207 - ks);\r\n    tmp.setTo(2, tmp > 0);\r\n\r\n    tmp = mask.rowRange(47 + ks, 207 - ks).colRange(207 - ks, 207 + ks);\r\n    tmp.setTo(3, tmp > 0);\r\n\r\n    tmp = mask.rowRange(207 - ks, 207 + ks).colRange(47 + ks, 207 - ks);\r\n    tmp.setTo(4, tmp > 0);\r\n\r\n    double sum = 0;\r\n    for (stepsi = 0; stepsi <= steps; ++stepsi)\r\n        sum += testSingle(e, img, mask, stepsi * CV_PI / (4 *steps), noise);\r\n    \r\n    return sum / steps;\r\n}\r\n\r\ncv::Mat diskImage() {\r\n    cv::Mat img(512, 512, CV_8U);\r\n    img.setTo(85);\r\n    cv::circle(img, cv::Point(256, 256), 150, 170, -1, CV_AA);\r\n    return img;\r\n}\r\n\r\ntemplate<class GT, class MT = int, class DT = double>\r\ndouble testDisk(Entry<GT, MT, DT> &e, cv::Mat img, cv::Mat mask, double blur = 0, double noise = 0) {\r\n    stepsi = -1;\r\n    GaussianBlurOperator op_blur(blur);\r\n    GaussianNoiseOperator op_noise(noise);\r\n    \r\n    cv::Mat gt(512, 512, CV_64F);\r\n    for (int y = 0; y != 512; ++y)\r\n        for (int x = 0; x != 512; ++x)\r\n            gt.at<double>(y, x) = std::atan2(static_cast<double>(256-y), static_cast<double>(256-x));\r\n\r\n    if (e.hr()) {\r\n        cv::add(gt, CV_PI, gt, gt < -CV_PI / 2);\r\n        cv::subtract(gt, CV_PI, gt, gt > CV_PI / 2);\r\n    }  \r\n\r\n    if (blur > 0)\r\n        op_blur(img);\r\n    \r\n    int num = static_cast<int>(cv::sum(mask)[0]) / 255;\r\n    gt.setTo(0, mask == 0);\r\n\r\n    if (noise > 0)\r\n        op_noise(img);\r\n    \r\n    e.grad->process(img);\r\n    cv::Mat dir = e.grad->direction();\r\n    dir.setTo(0, mask == 0);\r\n\r\n#ifdef WRITE_IMAGE_FILES\r\n    cv::imwrite(path + fname + \".png\", img);\r\n    cv::imwrite(path + fname + \"-mask.png\", mask);\r\n#endif\r\n#ifdef SHOW_IMAGES\r\n    cv::imshow(\"img\", img);\r\n    cv::imshow(\"mask\", mask > 0);\r\n    cv::imshow(\"A\", quiverDir<DT, uchar>(img, gt, Range<double>(-CV_PI, CV_PI), mask, 4, 4, 1, 8, 1));\r\n    cv::imshow(\"B\", quiverDir<DT, uchar>(img, dir, Range<double>(-CV_PI, CV_PI), mask, 4, 4, 1, 8, 1));\r\n    //cv::imshow(e.name + \"-mask\", mask > 0);\r\n    \r\n    //cv::Mat res = e.fixGrad(e.process(img));\r\n    //imshow(e.name + \" - grad\", res);\r\n    //imshow(e.name + \" - grad\", quiverDir<DT, MT>(res, e.grad->direction(), e.grad->directionRange(), e.grad->magnitude(), 1, 1, 4, 1, 0.5));\r\n#endif\r\n    return error(gt, dir) / num;\r\n}\r\n\r\n\r\nint main(int argc, char** argv)\r\n{  \r\n    std::vector<Entry<short>> gradI;\r\n    gradI.push_back(Entry<short>(new SusanGradient<short, int, double>, \"Susan (37)\", ENTRY_HALF_RANGE));\r\n    gradI.push_back(Entry<short>(new SusanGradient<short, int, double>(20,true), \"Susan (3x3)\", ENTRY_HALF_RANGE));\r\n    gradI.push_back(Entry<short>(new RCMGradient<uchar, 1, short, int, double>(3,1), \"RMG (3x3)\",ENTRY_HALF_RANGE));\r\n    gradI.push_back(Entry<short>(new RCMGradient<uchar, 1, short, int, double>(5, 3), \"RMG (5x5)\", ENTRY_HALF_RANGE));\r\n\r\n    std::vector<Entry<double, double>> gradF;\r\n    gradF.push_back(Entry<double, double>(new DerivativeGradient<uchar, double, double, double, RobertsDerivative>, \"Roberts (2x2)\"));\r\n    gradF.push_back(Entry<double, double>(new DerivativeGradient<uchar, double, double, double, PrewittDerivative>, \"Prewitt (3x3)\"));\r\n    gradF.push_back(Entry<double, double>(new DerivativeGradient<uchar, double, double, double, ScharrDerivative>, \"Scharr (3x3)\"));\r\n\r\n    gradF.push_back(Entry<double, double>(new DerivativeGradient<uchar, double, double, double, SobelDerivative>, \"Sobel (3x3)\"));\r\n    gradF.push_back(Entry<double, double>(new DerivativeGradient<uchar, double, double, double, SobelDerivative>({ NV(\"grad_kernel_size\",5)}), \"Sobel (5x5)\"));\r\n    gradF.push_back(Entry<double, double>(new DerivativeGradient<uchar, double, double, double, SobelDerivative>({ NV(\"grad_kernel_size\",7) }), \"Sobel (7x7)\"));\r\n    gradF.push_back(Entry<double, double>(new DerivativeGradient<uchar, double, double, double, SobelDerivative>({ NV(\"grad_kernel_size\",9) }), \"Sobel (9x9)\"));\r\n    \r\n    gradF.push_back(Entry<double, double>(new DerivativeGradient<uchar, double, double, double, GaussianDerivative>({ NV(\"grad_kernel_size\",3), NV(\"grad_range\",1.5) }), \"Gauss (3x3)\"));\r\n    gradF.push_back(Entry<double, double>(new DerivativeGradient<uchar, double, double, double, GaussianDerivative>({ NV(\"grad_kernel_size\",5), NV(\"grad_range\",2.3) }), \"Gauss (5x5)\"));\r\n    gradF.push_back(Entry<double, double>(new DerivativeGradient<uchar, double, double, double, GaussianDerivative>({ NV(\"grad_kernel_size\",7), NV(\"grad_range\",3.0) }), \"Gauss (7x7)\"));\r\n    gradF.push_back(Entry<double, double>(new DerivativeGradient<uchar, double, double, double, GaussianDerivative>({ NV(\"grad_kernel_size\",9), NV(\"grad_range\",3.5) }), \"Gauss (9x9)\"));\r\n\r\n    gradF.push_back(Entry<double, double>(new GradientOdd<QuadratureG2<uchar, double>>({ NV(\"grad_kernel_size\",3), NV(\"grad_kernel_spacing\",1.24008) }), \"QF StG (3x3)\", ENTRY_HALF_RANGE));\r\n    gradF.push_back(Entry<double, double>(new GradientOdd<QuadratureG2<uchar, double>>({ NV(\"grad_kernel_size\", 5), NV(\"grad_kernel_spacing\", 1.008) }), \"QF StG (5x5)\", ENTRY_HALF_RANGE));\r\n    gradF.push_back(Entry<double, double>(new GradientOdd<QuadratureG2<uchar, double>>({ NV(\"grad_kernel_size\", 7), NV(\"grad_kernel_spacing\", 0.873226) }), \"QF StG (7x7)\", ENTRY_HALF_RANGE));\r\n    gradF.push_back(Entry<double, double>(new GradientOdd<QuadratureG2<uchar, double>>({ NV(\"grad_kernel_size\", 9), NV(\"grad_kernel_spacing\", 0.781854) }), \"QF StG (9x9)\", ENTRY_HALF_RANGE));\r\n\r\n    gradF.push_back(Entry<double, double>(new GradientOdd<QuadratureS<uchar, double, double>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_size\", 3), NV(\"grad_kernel_spacing\", 1.2) }), \"SQF Po (3x3)\"));\r\n    gradF.push_back(Entry<double, double>(new GradientOdd<QuadratureS<uchar, double, double>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_size\", 5), NV(\"grad_kernel_spacing\", 1.2) }), \"SQF Po (5x5)\"));\r\n    gradF.push_back(Entry<double, double>(new GradientOdd<QuadratureS<uchar, double, double>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_size\", 7), NV(\"grad_kernel_spacing\", 1.2) }), \"SQF Po (7x7)\"));\r\n    gradF.push_back(Entry<double, double>(new GradientOdd<QuadratureS<uchar, double, double>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_size\", 9), NV(\"grad_kernel_spacing\", 1.2) }), \"SQF Po (9x9)\"));\r\n\r\n    gradF.push_back(Entry<double, double>(new GradientOdd<QuadratureLGF<uchar, double>>({ NV(\"grad_waveLength\", 5), NV(\"grad_sigmaOnf\", 0.55) }), \"SQFF LG\"));\r\n    gradF.push_back(Entry<double, double>(new GradientOdd<QuadratureSF<uchar, double>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_spacing\", 1.2) }), \"SQFF Po12\"));\r\n    gradF.push_back(Entry<double, double>(new GradientOdd<QuadratureSF<uchar, double>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 3), NV(\"grad_kernel_spacing\", 2.5) }), \"SQFF Po\"));\r\n\r\n    gradF.push_back(Entry<double, double>(new GradientEnergy<PCLgf<uchar, double>>({ NV(\"grad_waveLength\", 3), NV(\"grad_sigmaOnf\", 0.55) }), \"PCF Lg\"));\r\n    gradF.push_back(Entry<double, double>(new GradientOdd<PCSqf<uchar, double>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 3), NV(\"grad_kernel_spacing\", 2.5) }), \"PCF Po\"));\r\n\r\n    int cols = gradI.size() + gradF.size() + 1;\r\n    int rows = 7;\r\n    std::vector<std::vector<std::string>> table_box, table_disk;\r\n    table_box.resize(cols); table_disk.resize(cols);\r\n    for_each(table_box.begin(), table_box.end(), [&](std::vector<std::string> &row) {\r\n        row.resize(rows);\r\n    });\r\n\r\n    for_each(table_disk.begin(), table_disk.end(), [&](std::vector<std::string> &row) {\r\n        row.resize(rows);\r\n    });\r\n\r\n    std::cout << \"none...\";\r\n    table_box[0][0] = \"Method\";\r\n    table_box[0][1] = \"none\";\r\n\r\n    table_disk[0][0] = \"Method\";\r\n    table_disk[0][1] = \"none\";\r\n\r\n    DerivativeGradient<uchar, double, double, double, SobelDerivative> sobel;\r\n    cv::Mat box = boxImage();\r\n    sobel.process(box);\r\n    cv::Mat box_mask = sobel.magnitude() > sobel.magnitudeThreshold(magTh);\r\n     \r\n    cv::Mat disk = diskImage();\r\n    sobel.process(disk);\r\n    cv::Mat disk_mask = sobel.magnitude() > sobel.magnitudeThreshold(magTh);\r\n\r\n\r\n    int row = 1;\r\n    for_each(gradI.begin(), gradI.end(), [&](Entry<short> &e) {\r\n        table_box[row][0] = e.name;\r\n        table_disk[row][0] = e.name;\r\n        fname = \"box-\"+ e.name;\r\n        table_box[row][1] = boost::str(boost::format(\"%.3f\") % testBox(e,box.clone(),box_mask.clone(),0,0));\r\n        fname = \"disk-\"+ e.name;\r\n        table_disk[row++][1] = boost::str(boost::format(\"%.3f\") % testDisk(e,disk.clone(),disk_mask.clone(),0,0));\r\n    });\r\n    for_each(gradF.begin(), gradF.end(), [&](Entry<double, double> &e) {\r\n        table_box[row][0] = e.name;\r\n        table_disk[row][0] = e.name;\r\n        fname = \"box-\" + e.name;\r\n        table_box[row][1] = boost::str(boost::format(\"%.3f\") % testBox(e, box.clone(), box_mask.clone(), 0, 0));\r\n        fname = \"disk-\" + e.name;\r\n        table_disk[row++][1] = boost::str(boost::format(\"%.3f\") % testDisk(e, disk.clone(), disk_mask.clone(), 0, 0));\r\n    });\r\n\r\n    std::cout << \"done\" << std::endl << \"blur...\";\r\n    table_box[0][2] = \"blur\";\r\n    table_disk[0][2] = \"blur\";\r\n\r\n    row = 1;\r\n    for_each(gradI.begin(), gradI.end(), [&](Entry<short> &e) {\r\n        fname = \"box-blur\" + e.name;\r\n        table_box[row][2] = boost::str(boost::format(\"%.3f\") % testBox(e, box.clone(), box_mask.clone(), 2, 0));\r\n        fname = \"disk-blur\" + e.name;\r\n        table_disk[row++][2] = boost::str(boost::format(\"%.3f\") % testDisk(e, disk.clone(), disk_mask.clone(), 2, 0));\r\n    });\r\n    for_each(gradF.begin(), gradF.end(), [&](Entry<double, double> &e) {\r\n        fname = \"box-blur-\"+ e.name;\r\n        table_box[row][2] = boost::str(boost::format(\"%.3f\") % testBox(e, box.clone(), box_mask.clone(), 2, 0));\r\n        fname = \"disk-blur-\"+ e.name;\r\n        table_disk[row++][2] = boost::str(boost::format(\"%.3f\") % testDisk(e, disk.clone(), disk_mask.clone(), 2, 0));\r\n    });\r\n\r\n    std::cout << \"done\" << std::endl << \"noise 10...\";\r\n    table_box[0][3] = \"noise10\";\r\n    table_disk[0][3] = \"noise10\";\r\n\r\n    row = 1;\r\n    for_each(gradI.begin(), gradI.end(), [&](Entry<short> &e) {\r\n        fname = \"box-noise10-\"+ e.name;\r\n        table_box[row][3] = boost::str(boost::format(\"%.3f\") % testBox(e, box.clone(), box_mask.clone(), 0, 10));\r\n        fname = \"disk-noise10-\"+ e.name;\r\n        table_disk[row++][3] = boost::str(boost::format(\"%.3f\") % testDisk(e, disk.clone(), disk_mask.clone(), 0, 10));\r\n    });\r\n    for_each(gradF.begin(), gradF.end(), [&](Entry<double, double> &e) {\r\n        fname = \"box-noise10-\"+ e.name;\r\n        table_box[row][3] = boost::str(boost::format(\"%.3f\") % testBox(e, box.clone(), box_mask.clone(), 0, 10));\r\n        fname = \"disk-noise10-\" + e.name;\r\n        table_disk[row++][3] = boost::str(boost::format(\"%.3f\") % testDisk(e, disk.clone(), disk_mask.clone(), 0, 10));\r\n    });\r\n\r\n    std::cout << \"done\" << std::endl << \"noise 40...\";\r\n    table_box[0][4] = \"noise40\";\r\n    table_disk[0][4] = \"noise40\";\r\n\r\n    row = 1;\r\n    for_each(gradI.begin(), gradI.end(), [&](Entry<short> &e) {\r\n        fname = \"box-noise40-\" + e.name;\r\n        table_box[row][4] = boost::str(boost::format(\"%.3f\") % testBox(e, box.clone(), box_mask.clone(), 0, 40));\r\n        fname = \"disk-noise40-\" + e.name;\r\n        table_disk[row++][4] = boost::str(boost::format(\"%.3f\") % testDisk(e, disk.clone(), disk_mask.clone(), 0, 40));\r\n    });\r\n    for_each(gradF.begin(), gradF.end(), [&](Entry<double, double> &e) {\r\n        fname = \"box-noise40-\" + e.name;\r\n        table_box[row][4] = boost::str(boost::format(\"%.3f\") % testBox(e, box.clone(), box_mask.clone(), 0, 40));\r\n        fname = \"disk-noise40-\" + e.name;\r\n        table_disk[row++][4] = boost::str(boost::format(\"%.3f\") % testDisk(e, disk.clone(), disk_mask.clone(), 0, 40));\r\n    });\r\n\r\n    std::cout << \"done\" << std::endl << \"blur + noise 10...\";\r\n    table_box[0][5] = \"bnoise10\";\r\n    table_disk[0][5] = \"bnoise10\";\r\n\r\n    row = 1;\r\n    for_each(gradI.begin(), gradI.end(), [&](Entry<short> &e) {\r\n        fname = \"box-bnoise10-\" + e.name;\r\n        table_box[row][5] = boost::str(boost::format(\"%.3f\") % testBox(e, box.clone(), box_mask.clone(), 2, 10));\r\n        fname = \"disk-bnoise10-\" + e.name;\r\n        table_disk[row++][5] = boost::str(boost::format(\"%.3f\") % testDisk(e, disk.clone(), disk_mask.clone(), 2, 10));\r\n    });\r\n    for_each(gradF.begin(), gradF.end(), [&](Entry<double, double> &e) {\r\n        fname = \"box-bnoise10-\" + e.name;\r\n        table_box[row][5] = boost::str(boost::format(\"%.3f\") % testBox(e, box.clone(), box_mask.clone(), 2, 10));\r\n        fname = \"disk-bnoise10-\" + e.name;\r\n        table_disk[row++][5] = boost::str(boost::format(\"%.3f\") % testDisk(e, disk.clone(), disk_mask.clone(), 2, 10));\r\n    });\r\n\r\n    std::cout << \"done\" << std::endl << \"blur + noise 40...\";\r\n    table_box[0][6] = \"bnoise40\";\r\n    table_disk[0][6] = \"bnoise40\";\r\n\r\n    row = 1;\r\n    for_each(gradI.begin(), gradI.end(), [&](Entry<short> &e) {\r\n        fname = \"box-bnoise40-\" + e.name;\r\n        table_box[row][6] = boost::str(boost::format(\"%.3f\") % testBox(e, box.clone(), box_mask.clone(), 2, 40));\r\n        fname = \"disk-bnoise40-\" + e.name;\r\n        table_disk[row++][6] = boost::str(boost::format(\"%.3f\") % testDisk(e, disk.clone(), disk_mask.clone(), 2, 40));\r\n    });\r\n    for_each(gradF.begin(), gradF.end(), [&](Entry<double, double> &e) {\r\n        fname = \"box-bnoise40-\" + e.name;\r\n        table_box[row][6] = boost::str(boost::format(\"%.3f\") % testBox(e, box.clone(), box_mask.clone(), 2, 40));\r\n        fname = \"disk-bnoise40-\" + e.name;\r\n        table_disk[row++][6] = boost::str(boost::format(\"%.3f\") % testDisk(e, disk.clone(), disk_mask.clone(), 2, 40));\r\n    });\r\n    std::cout << \"done\" << std::endl;\r\n    \r\n    std::ofstream ofs;\r\n    ofs.open(\"gradient_orientation_box.csv\");\r\n\r\n    for_each(table_box.begin(), table_box.end(), [&](const std::vector<std::string> &row) {\r\n        for_each(row.begin(), row.end(), [&](const std::string &cell) {\r\n            std::cout << cell << \"\\t\";\r\n            ofs << cell << \";\";\r\n        });\r\n        std::cout << std::endl;\r\n        ofs << std::endl;\r\n    });\r\n\r\n    ofs.close();\r\n\r\n    ofs.open(\"gradient_orientation_disk.csv\");\r\n\r\n    for_each(table_disk.begin(), table_disk.end(), [&](const std::vector<std::string> &row) {\r\n        for_each(row.begin(), row.end(), [&](const std::string &cell) {\r\n            std::cout << cell << \"\\t\";\r\n            ofs << cell << \";\";\r\n        });\r\n        std::cout << std::endl;\r\n        ofs << std::endl;\r\n    });\r\n\r\n    ofs.close();\r\n\r\n    cv::waitKey();\r\n    \r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "384468c42772c7d71536385fde26979f2de592f1", "size": 20424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "evaluation/old/gradient_orientation.cpp", "max_stars_repo_name": "waterben/LineExtraction", "max_stars_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T13:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T13:30:56.000Z", "max_issues_repo_path": "evaluation/old/gradient_orientation.cpp", "max_issues_repo_name": "waterben/LineExtraction", "max_issues_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "evaluation/old/gradient_orientation.cpp", "max_forks_repo_name": "waterben/LineExtraction", "max_forks_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_forks_repo_licenses": ["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.9075630252, "max_line_length": 217, "alphanum_fraction": 0.5824030552, "num_tokens": 6311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5084820096277635}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2013, 2014 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//[buffer_with_strategies\r\n//` Shows how the buffer algorithm can be used to create a buffer of a linestring\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/geometries.hpp>\r\n/*<-*/ #include \"../examples_utils/create_svg_buffer.hpp\" /*->*/\r\n\r\nint main()\r\n{\r\n    typedef double coordinate_type;\r\n    typedef boost::geometry::model::d2::point_xy<coordinate_type> point;\r\n    typedef boost::geometry::model::polygon<point> polygon;\r\n\r\n    // Declare strategies\r\n    const double buffer_distance = 1.0;\r\n    const int points_per_circle = 36;\r\n    boost::geometry::strategy::buffer::distance_symmetric<coordinate_type> distance_strategy(buffer_distance);\r\n    boost::geometry::strategy::buffer::join_round join_strategy(points_per_circle);\r\n    boost::geometry::strategy::buffer::end_round end_strategy(points_per_circle);\r\n    boost::geometry::strategy::buffer::point_circle circle_strategy(points_per_circle);\r\n    boost::geometry::strategy::buffer::side_straight side_strategy;\r\n\r\n    // Declare output\r\n    boost::geometry::model::multi_polygon<polygon> result;\r\n\r\n    // Declare/fill a linestring\r\n    boost::geometry::model::linestring<point> ls;\r\n    boost::geometry::read_wkt(\"LINESTRING(0 0,4 5,7 4,10 6)\", ls);\r\n\r\n    // Create the buffer of a linestring\r\n    boost::geometry::buffer(ls, result,\r\n                distance_strategy, side_strategy,\r\n                join_strategy, end_strategy, circle_strategy);\r\n    /*<-*/ create_svg_buffer(\"buffer_linestring.svg\", ls, result); /*->*/\r\n\r\n    // Declare/fill a multi point\r\n    boost::geometry::model::multi_point<point> mp;\r\n    boost::geometry::read_wkt(\"MULTIPOINT((3 3),(4 4),(6 2))\", mp);\r\n\r\n    // Create the buffer of a multi point\r\n    boost::geometry::buffer(mp, result,\r\n                distance_strategy, side_strategy,\r\n                join_strategy, end_strategy, circle_strategy);\r\n    /*<-*/ create_svg_buffer(\"buffer_multi_point.svg\", mp, result); /*->*/\r\n\r\n    // Declare/fill a multi_polygon\r\n    boost::geometry::model::multi_polygon<polygon> mpol;\r\n    boost::geometry::read_wkt(\"MULTIPOLYGON(((0 1,2 5,5 3,0 1)),((1 1,5 2,5 0,1 1)))\", mpol);\r\n\r\n    // Create the buffer of a multi polygon\r\n    boost::geometry::buffer(mpol, result,\r\n                distance_strategy, side_strategy,\r\n                join_strategy, end_strategy, circle_strategy);\r\n    /*<-*/ create_svg_buffer(\"buffer_multi_polygon.svg\", mpol, result); /*->*/\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n", "meta": {"hexsha": "a365e7cd7ecdcc5ddc9c99caaad6d1c6af11af60", "size": 2851, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/buffer_with_strategies.cpp", "max_stars_repo_name": "Abce/boost", "max_stars_repo_head_hexsha": "2d7491a27211aa5defab113f8e2d657c3d85ca93", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/doc/src/examples/algorithms/buffer_with_strategies.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/doc/src/examples/algorithms/buffer_with_strategies.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": 40.1549295775, "max_line_length": 111, "alphanum_fraction": 0.6808137496, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5084819969118011}}
{"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//[degree_radian\n//` Specify two coordinate systems, one in degrees, one in radians.\n\n#include <iostream>\n#include <boost/geometry.hpp>\n\nusing namespace boost::geometry;\n\nint main()\n{\n    typedef model::point<double, 2, cs::spherical_equatorial<degree> > degree_point;\n    typedef model::point<double, 2, cs::spherical_equatorial<radian> > radian_point;\n\n    degree_point d(4.893, 52.373);\n    radian_point r(0.041, 0.8527);\n\n    double dist = distance(d, r);\n    std::cout\n        << \"distance:\" << std::endl\n        << dist << \" over unit sphere\" << std::endl\n        << dist * 3959  << \" over a spherical earth, in miles\" << std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[degree_radian_output\n/*`\nOutput:\n[pre\ndistance:\n0.0675272 over unit sphere\n267.34 over a spherical earth, in miles\n]\n*/\n//]\n", "meta": {"hexsha": "4fa375656a6666b42e93f4089a61e9f4d5705a54", "size": 1126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/core/degree_radian.cpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "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": "libs/geometry/doc/src/examples/core/degree_radian.cpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/core/degree_radian.cpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "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": 23.4583333333, "max_line_length": 84, "alphanum_fraction": 0.6811722913, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.508469557167208}}
{"text": "#define BOOST_TEST_MODULE variables\n#include <boost/test/included/unit_test.hpp>\n#include \"exprtest.hpp\"\n\ndouble const x = 1;\ndouble const y = 2;\n\nstatic std::map<std::string, double> symtab() {\n    std::map<std::string, double> symtab;\n    symtab.insert(std::make_pair(\"x\",  x));\n    symtab.insert(std::make_pair(\"y\",  y));\n    symtab.insert(std::make_pair(\"e\", -1));\n    return symtab;\n}\n\nSYMEXPRTEST(var1, \"x+y\" , symtab(), x+y)\nSYMEXPRTEST(var2, \"x-y\" , symtab(), x-y)\nSYMEXPRTEST(var3, \"x*y\" , symtab(), x*y)\nSYMEXPRTEST(var4, \"x/y\" , symtab(), x/y);\nSYMEXPRTEST(var5, \"x%y\" , symtab(), std::fmod(x,y));\nSYMEXPRTEST(var6, \"x**y\", symtab(), std::pow(x,y));\n\n// Constants have higher priority than variables of the same name\nSYMEXPRTEST(var7, \"e\", symtab(), boost::math::constants::e<double>())\n", "meta": {"hexsha": "55d77d509880edc39e28845b3acbee3eead1f06d", "size": 798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/variables.cpp", "max_stars_repo_name": "hmenke/boost_matheval", "max_stars_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-01-26T01:58:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:49:05.000Z", "max_issues_repo_path": "tests/variables.cpp", "max_issues_repo_name": "hmenke/boost_matheval", "max_issues_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T04:32:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-31T06:53:42.000Z", "max_forks_repo_path": "tests/variables.cpp", "max_forks_repo_name": "hmenke/boost_matheval", "max_forks_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-11-07T07:09:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T03:03:03.000Z", "avg_line_length": 31.92, "max_line_length": 69, "alphanum_fraction": 0.6578947368, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5084695565511053}}
{"text": "//******************************************************************************\r\n//  Copyright(C) 2008-2013 Intel Corporation. All Rights Reserved.\r\n//\r\n//  The source code, information  and  material (\"Material\") contained herein is\r\n//  owned  by Intel Corporation or its suppliers or licensors, and title to such\r\n//  Material remains  with Intel Corporation  or its suppliers or licensors. The\r\n//  Material  contains proprietary information  of  Intel or  its  suppliers and\r\n//  licensors. The  Material is protected by worldwide copyright laws and treaty\r\n//  provisions. No  part  of  the  Material  may  be  used,  copied, reproduced,\r\n//  modified, published, uploaded, posted, transmitted, distributed or disclosed\r\n//  in any way  without Intel's  prior  express written  permission. No  license\r\n//  under  any patent, copyright  or  other intellectual property rights  in the\r\n//  Material  is  granted  to  or  conferred  upon  you,  either  expressly,  by\r\n//  implication, inducement,  estoppel or  otherwise.  Any  license  under  such\r\n//  intellectual  property  rights must  be express  and  approved  by  Intel in\r\n//  writing.\r\n//\r\n//  *Third Party trademarks are the property of their respective owners.\r\n//\r\n//  Unless otherwise  agreed  by Intel  in writing, you may not remove  or alter\r\n//  this  notice or  any other notice embedded  in Materials by Intel or Intel's\r\n//  suppliers or licensors in any way.\r\n//\r\n//******************************************************************************\r\n// Content:\r\n//     Intel(R) Math Kernel Library (MKL) overloaded Boost/uBLAS prod()\r\n//******************************************************************************\r\n\r\n#ifndef _MKL_BOOST_UBLAS_GEMM_\r\n#define _MKL_BOOST_UBLAS_GEMM_\r\n\r\n#include <boost/version.hpp>\r\n#if defined (BOOST_VERSION) && (BOOST_VERSION >= 103401)\r\n\r\n#include <boost/numeric/ublas/detail/concepts.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n\r\n#include \"mkl_cblas.h\"\r\n\r\n#ifndef MKL_BOOST_UBLAS_INLINE\r\n#define MKL_BOOST_UBLAS_INLINE inline\r\n#endif\r\n\r\nnamespace boost { namespace numeric { namespace ublas {\r\n\r\nnamespace mkl {\r\n\r\n    template<class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    typename matrix_matrix_binary_traits<typename E1::value_type, E1,\r\n                                         typename E2::value_type, E2>::result_type\r\n    gemm(const matrix_expression<E1> &e1,\r\n         const matrix_expression<E2> &e2)\r\n    {\r\n        typedef typename matrix_matrix_binary_traits<typename E1::value_type, E1,\r\n                                                                 typename E2::value_type, E2>::storage_category storage_category;\r\n        typedef typename matrix_matrix_binary_traits<typename E1::value_type, E1,\r\n                                                                 typename E2::value_type, E2>::orientation_category orientation_category;\r\n        return prod (e1, e2, storage_category (), orientation_category ());\r\n    } // For unsupported matrix types.\r\n    template<class T>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    void gemm(const  CBLAS_ORDER Order, const  CBLAS_TRANSPOSE TransA,\r\n            const  CBLAS_TRANSPOSE TransB, const MKL_INT m, const MKL_INT n,\r\n            const MKL_INT k, const T alpha, const T *a,\r\n            const MKL_INT lda, const T *b, const MKL_INT ldb,\r\n            const T beta, T *c, const MKL_INT ldc)\r\n    {}// To resolve externals for unsupported matrix types. Never is called.\r\n    template<>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    void\r\n    gemm(const  CBLAS_ORDER Order, const  CBLAS_TRANSPOSE TransA,\r\n         const  CBLAS_TRANSPOSE TransB, const MKL_INT m, const MKL_INT n,\r\n         const MKL_INT k, const double alpha, const double *a,\r\n         const MKL_INT lda, const double *b, const MKL_INT ldb,\r\n         const double beta, double *c, const MKL_INT ldc)\r\n    {\r\n        cblas_dgemm(Order, TransA, TransB, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc);\r\n    }\r\n    template<>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    void\r\n    gemm(const  CBLAS_ORDER Order, const  CBLAS_TRANSPOSE TransA,\r\n         const  CBLAS_TRANSPOSE TransB, const MKL_INT m, const MKL_INT n,\r\n         const MKL_INT k, const float alpha, const float *a,\r\n         const MKL_INT lda, const float *b, const MKL_INT ldb,\r\n         const float beta, float *c, const MKL_INT ldc)\r\n    {\r\n        cblas_sgemm(Order, TransA, TransB, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc);\r\n    }\r\n    template<>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    void\r\n    gemm(const  CBLAS_ORDER Order, const  CBLAS_TRANSPOSE TransA,\r\n         const  CBLAS_TRANSPOSE TransB, const MKL_INT m, const MKL_INT n,\r\n         const MKL_INT k, const std::complex<double> alpha, const std::complex<double> *a,\r\n         const MKL_INT lda, const std::complex<double> *b, const MKL_INT ldb,\r\n         const std::complex<double> beta, std::complex<double> *c, const MKL_INT ldc)\r\n    {\r\n        cblas_zgemm(Order, TransA, TransB, m, n, k, static_cast<const void *>(&alpha),\r\n            static_cast<const void *>(a), lda, static_cast<const void *>(b), ldb,\r\n            static_cast<const void *>(&beta), static_cast<void *>(c), ldc);\r\n    }\r\n    template<>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    void\r\n    gemm(const  CBLAS_ORDER Order, const  CBLAS_TRANSPOSE TransA,\r\n         const  CBLAS_TRANSPOSE TransB, const MKL_INT m, const MKL_INT n,\r\n         const MKL_INT k, const std::complex<float> alpha, const std::complex<float> *a,\r\n         const MKL_INT lda, const std::complex<float> *b, const MKL_INT ldb,\r\n         const std::complex<float> beta, std::complex<float> *c, const MKL_INT ldc)\r\n    {\r\n        cblas_cgemm(Order, TransA, TransB, m, n, k, static_cast<const void *>(&alpha),\r\n            static_cast<const void *>(a), lda, static_cast<const void *>(b), ldb,\r\n            static_cast<const void *>(&beta), static_cast<void *>(c), ldc);\r\n    }\r\n\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    T *  // M\r\n    pointer(const matrix<T,F,A> &m)\r\n    {\r\n        //return &m(0,0);\r\n        return const_cast<T*>(&m.data().begin()[0]);\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    T *  // trans(M)\r\n    pointer(const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m)\r\n    {\r\n        return pointer(m.expression().expression());\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    T *  // trans(conj(M))\r\n    pointer(const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m)\r\n    {\r\n        return pointer(m.expression().expression().expression());\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    T *  // conj(trans(M))\r\n    pointer(const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m)\r\n    {\r\n        return pointer(m.expression().expression().expression());\r\n    }\r\n\r\n    template<class E>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    MKL_INT\r\n    leading_dimension(const matrix_expression<E> &e, row_major_tag)\r\n    {\r\n        return e().size1();\r\n    }\r\n    template<class E>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    MKL_INT\r\n    leading_dimension(const matrix_expression<E> &e, column_major_tag)\r\n    {\r\n        return e().size2();\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    MKL_INT\r\n    leading_dimension(const matrix<T,F,A> &m, row_major_tag)\r\n    {\r\n        return m.size2();\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    MKL_INT\r\n    leading_dimension(const matrix<T,F,A> &m, column_major_tag)\r\n    {\r\n        return m.size1();\r\n    }\r\n\r\n    template<class T>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    CBLAS_ORDER\r\n    storage_layout(T);\r\n    template<>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    CBLAS_ORDER\r\n    storage_layout(row_major_tag) {\r\n        return CblasRowMajor;\r\n    }\r\n    template<>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    CBLAS_ORDER\r\n    storage_layout(column_major_tag) {\r\n        return CblasColMajor;\r\n    }\r\n\r\n    template<class T>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    int supported_type(T)\r\n    { return 0; }\r\n    template<>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    int supported_type(float)\r\n    { return 1; }\r\n    template<>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    int supported_type(double)\r\n    { return 2; }\r\n    template<>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    int supported_type(std::complex<float>)\r\n    { return 3; }\r\n    template<>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    int supported_type(std::complex<double>)\r\n    { return 4; }\r\n\r\n    template<class E1, class E2, class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    void\r\n    gemm(const  CBLAS_TRANSPOSE transa, const  CBLAS_TRANSPOSE transb,\r\n         const matrix_expression<E1> &a, const matrix_expression<E2> &b,\r\n         matrix<T,F,A> &c)\r\n    {\r\n        typedef T value_type;\r\n        typedef typename F::orientation_category orientation_category;\r\n        if(supported_type(value_type()) > 0) {\r\n            MKL_INT m = a().size1();\r\n            MKL_INT k = a().size2();\r\n            MKL_INT n = b().size2();\r\n            MKL_INT lda = leading_dimension(a(),orientation_category());\r\n            MKL_INT ldb = leading_dimension(b(),orientation_category());\r\n            MKL_INT ldc = leading_dimension(c,orientation_category());\r\n\t\t\t\r\n\t/*boost 1.57 change the function OneElement definition from 1.0 to 0.0 in boost/numeric/ublas/detail/concepts.hpp \r\n\ttemplate<class T>\r\n    T\r\n    OneElement (T) {\r\n        return T(0.0);\r\n    }\r\n\t\tThey explain this in boost/numeric/ublas/detail/concepts.hpp\r\n\t\tReplaced the ZeroElement and OneElement functions with the templated versions\r\n\t\tbecause the former where giving warnings with clang.  Anyway, It seems a bug or something else. so change \r\n\t//value_type alpha = OneElement(value_type());  // boost/numeric/ublas/detail/concepts.hpp  to \r\n\t*/    \r\n            value_type alpha = 1.0;  \r\n\t\t\tvalue_type beta = ZeroElement(value_type());  // boost/numeric/ublas/detail/concepts.hpp\r\n            CBLAS_ORDER layout = storage_layout(orientation_category());\r\n            T *pa = pointer(a());\r\n            T *pb = pointer(b());\r\n            T *pc = pointer(c);\r\n            gemm(layout, transa, transb, m, n, k, alpha, pa, lda, pb, ldb, beta, pc, ldc);\r\n        } else {\r\n            c = gemm(a,b);\r\n        }\r\n    }\r\n\r\n}  // namespace mkl\r\n\r\n}}}\r\n#endif  // BOOST_VERSION\r\n#endif  // _MKL_BOOST_UBLAS_GEMM_\r\n", "meta": {"hexsha": "845246da408fa76c185c0f1ec7499aef202c5152", "size": 10351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "components/parallel-libs/boost/SOURCES/mkl_boost_ublas_gemm.hpp", "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-17T21:20:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-17T21:20:07.000Z", "max_issues_repo_path": "components/parallel-libs/boost/SOURCES/mkl_boost_ublas_gemm.hpp", "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "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": "components/parallel-libs/boost/SOURCES/mkl_boost_ublas_gemm.hpp", "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-17T23:49:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-17T23:49:09.000Z", "avg_line_length": 39.8115384615, "max_line_length": 138, "alphanum_fraction": 0.6242875085, "num_tokens": 2668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5084695455505442}}
{"text": "/******************************************************************************\n * Copyright (C) 2013 by Jerome Maye                                          *\n * jerome.maye@gmail.com                                                      *\n ******************************************************************************/\n\n/** \\file simulate-offline.cpp\n    \\brief This file runs a simulation of the calibration problem in batch mode.\n  */\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <vector>\n\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n\n#include <Eigen/Core>\n\n#include <sm/kinematics/rotations.hpp>\n#include <sm/kinematics/three_point_methods.hpp>\n\n#include <sm/BoostPropertyTree.hpp>\n\n#include <aslam/backend/Optimizer2Options.hpp>\n#include <aslam/backend/GaussNewtonTrustRegionPolicy.hpp>\n#include <aslam/backend/Optimizer2.hpp>\n\n#include <aslam/calibration/core/OptimizationProblem.h>\n#include <aslam/calibration/statistics/UniformDistribution.h>\n#include <aslam/calibration/statistics/NormalDistribution.h>\n#include <aslam/calibration/data-structures/VectorDesignVariable.h>\n#include <aslam/calibration/geometry/Transformation.h>\n#include <aslam/calibration/base/Timestamp.h>\n#include <aslam-tsvd-solver/aslam-tsvd-solver.h>\n\n#include \"aslam/calibration/2dlrf/utils.h\"\n#include \"aslam/calibration/2dlrf/ErrorTermMotion.h\"\n#include \"aslam/calibration/2dlrf/ErrorTermObservation.h\"\n\nusing namespace aslam::calibration;\nusing namespace aslam::backend;\nusing namespace sm::kinematics;\nusing namespace sm;\n\ntypedef aslam::backend::AslamTruncatedSvdSolver LinearSolver;\nint main(int argc, char** argv) {\n  if (argc != 2) {\n    std::cerr << \"Usage: \" << argv[0] << \" <conf_file>\" << std::endl;\n    return -1;\n  }\n\n  // load configuration file\n  BoostPropertyTree propertyTree;\n  propertyTree.loadXml(argv[1]);\n\n  // steps to simulate\n  const size_t steps = propertyTree.getInt(\"lrf/problem/steps\");\n\n  // timestep size\n  const double T = propertyTree.getDouble(\"lrf/problem/timestep\");\n\n  // true state\n  std::vector<Eigen::Vector3d > x_true;\n  x_true.reserve(steps);\n\n  // integrated odometry\n  std::vector<Eigen::Vector3d > x_odom;\n  x_odom.reserve(steps);\n\n  // true control input\n  std::vector<Eigen::Vector3d > u_true;\n  const double sineWaveAmplitude = propertyTree.getDouble(\n    \"lrf/problem/sineWaveAmplitude\");\n  const double sineWaveFrequency = propertyTree.getDouble(\n    \"lrf/problem/sineWaveFrequency\");\n  genSineWavePath(u_true, steps, sineWaveAmplitude, sineWaveFrequency, T);\n\n  // measured control input\n  std::vector<Eigen::Vector3d > u_noise;\n  u_noise.reserve(steps);\n\n  // number of landmarks\n  const size_t nl = propertyTree.getInt(\"lrf/problem/numLandmarks\");\n\n  // playground size\n  const Eigen::Vector2d min(propertyTree.getDouble(\"lrf/problem/groundMinX\"),\n    propertyTree.getDouble(\"lrf/problem/groundMinY\"));\n  const Eigen::Vector2d max(propertyTree.getDouble(\"lrf/problem/groundMaxX\"),\n    propertyTree.getDouble(\"lrf/problem/groundMaxY\"));\n\n  // bearing measurements\n  std::vector<std::vector<double> > b;\n  b.reserve(steps);\n  b.push_back(std::vector<double>(nl, 0));\n\n  // range measurements\n  std::vector<std::vector<double> > r;\n  r.reserve(steps);\n  r.push_back(std::vector<double>(nl, 0));\n\n  // covariance matrix for motion model\n  Eigen::Matrix3d Q = Eigen::Matrix3d::Zero();\n  Q(0, 0) = propertyTree.getDouble(\"lrf/problem/motion/sigma2_x\");\n  Q(1, 1) = propertyTree.getDouble(\"lrf/problem/motion/sigma2_y\");\n  Q(2, 2) = propertyTree.getDouble(\"lrf/problem/motion/sigma2_t\");\n\n  // covariance matrix for observation model\n  Eigen::Matrix2d R = Eigen::Matrix2d::Zero();\n  R(0, 0) = propertyTree.getDouble(\"lrf/problem/observation/sigma2_r\");\n  R(1, 1) = propertyTree.getDouble(\"lrf/problem/observation/sigma2_b\");\n\n  // landmark positions\n  std::vector<Eigen::Vector2d > x_l;\n  UniformDistribution<double, 2>(min, max).getSamples(x_l, nl);\n\n  // true calibration parameters\n  const Eigen::Vector3d Theta(propertyTree.getDouble(\"lrf/problem/thetaTrue/x\"),\n    propertyTree.getDouble(\"lrf/problem/thetaTrue/y\"),\n    propertyTree.getDouble(\"lrf/problem/thetaTrue/t\"));\n\n  // guessed calibration parameters\n  const Eigen::Vector3d Theta_hat(\n    propertyTree.getDouble(\"lrf/problem/thetaHat/x\"),\n    propertyTree.getDouble(\"lrf/problem/thetaHat/y\"),\n    propertyTree.getDouble(\"lrf/problem/thetaHat/t\"));\n\n  // initial state\n  const Eigen::Vector3d x_0(propertyTree.getDouble(\"lrf/problem/x0/x\"),\n    propertyTree.getDouble(\"lrf/problem/x0/y\"),\n    propertyTree.getDouble(\"lrf/problem/x0/t\"));\n  x_true.push_back(x_0);\n  x_odom.push_back(x_0);\n  u_noise.push_back(Eigen::Vector3d::Zero());\n\n  // simulate\n  for (size_t i = 1; i < steps; ++i) {\n    Eigen::Matrix3d B = Eigen::Matrix3d::Identity();\n    B(0, 0) = cos(x_true[i - 1](2));\n    B(0, 1) = -sin(x_true[i - 1](2));\n    B(1, 0) = sin(x_true[i - 1](2));\n    B(1, 1) = cos(x_true[i - 1](2));\n    Eigen::Vector3d xk = x_true[i - 1] + T * B * u_true[i];\n    xk(2) = angleMod(xk(2));\n    x_true.push_back(xk);\n    u_noise.push_back(u_true[i] +\n      NormalDistribution<3>(Eigen::Vector3d::Zero(), Q).getSample());\n    B(0, 0) = cos(x_odom[i - 1](2));\n    B(0, 1) = -sin(x_odom[i - 1](2));\n    B(1, 0) = sin(x_odom[i - 1](2));\n    B(1, 1) = cos(x_odom[i - 1](2));\n    xk = x_odom[i - 1] + T * B * u_noise[i];\n    xk(2) = angleMod(xk(2));\n    x_odom.push_back(xk);\n    const double ct = cos(x_true[i](2));\n    const double st = sin(x_true[i](2));\n    std::vector<double> rk(nl, 0);\n    std::vector<double> bk(nl, 0);\n    for (size_t j = 0; j < nl; ++j) {\n      const double aa = x_l[j](0) - x_true[i](0) - Theta(0) * ct +\n        Theta(1) * st;\n      const double bb = x_l[j](1) - x_true[i](1) - Theta(0) * st -\n        Theta(1) * ct;\n      const double range = sqrt(aa * aa + bb * bb) +\n        NormalDistribution<1>(0, R(0, 0)).getSample();\n      rk[j] = range;\n      bk[j] = angleMod(atan2(bb, aa) - x_true[i](2) - Theta(2) +\n        NormalDistribution<1>(0, R(1, 1)).getSample());\n    }\n    r.push_back(rk);\n    b.push_back(bk);\n  }\n\n  // landmark guess\n  std::vector<Eigen::Vector2d > x_l_hat;\n  initLandmarks(x_l_hat, x_odom, Theta_hat, r, b);\n\n  // create optimization problem\n  auto problem = boost::make_shared<OptimizationProblem>();\n\n  // create calibration parameters design variable\n  auto dv_Theta = boost::make_shared<VectorDesignVariable<3> >(Theta_hat);\n  dv_Theta->setActive(true);\n  problem->addDesignVariable(dv_Theta, 2);\n\n  // create state design variables\n  std::vector<boost::shared_ptr<VectorDesignVariable<3> > > dv_x;\n  dv_x.reserve(steps);\n  for (size_t i = 0; i < steps; ++i) {\n    dv_x.push_back(boost::make_shared<VectorDesignVariable<3> >(x_odom[i]));\n    dv_x[i]->setActive(true);\n    problem->addDesignVariable(dv_x[i], 0);\n  }\n\n  // create landmarks design variables\n  std::vector<boost::shared_ptr<VectorDesignVariable<2> > > dv_x_l;\n  dv_x_l.reserve(nl);\n  for (size_t i = 0; i < nl; ++i) {\n    dv_x_l.push_back(boost::make_shared<VectorDesignVariable<2> >(x_l_hat[i]));\n    dv_x_l[i]->setActive(true);\n    problem->addDesignVariable(dv_x_l[i], 1);\n  }\n\n  // set the ordering of the problem\n  problem->setGroupsOrdering({0, 1, 2});\n\n  // add motion and observation error terms\n  for (size_t i = 1; i < steps; ++i) {\n    auto e_mot = boost::make_shared<ErrorTermMotion>(dv_x[i - 1].get(),\n      dv_x[i].get(), T, u_noise[i], Q);\n    problem->addErrorTerm(e_mot);\n    for (size_t j = 0; j < nl; ++j) {\n      auto e_obs = boost::make_shared<ErrorTermObservation>(dv_x[i].get(),\n        dv_x_l[j].get(), dv_Theta.get(), r[i][j], b[i][j], R);\n      problem->addErrorTerm(e_obs);\n    }\n  }\n\n  // optimization\n  std::cout << \"Calibration before: \" << *dv_Theta << std::endl;\n  Optimizer2 optimizer(PropertyTree(propertyTree, \"lrf/estimator/optimizer\"),\n    boost::make_shared<LinearSolver>(PropertyTree(propertyTree,\n    \"lrf/estimator/optimizer/linearSolver\")),\n    boost::make_shared<GaussNewtonTrustRegionPolicy>());\n  optimizer.setProblem(problem);\n\n  size_t JCols = 0;\n  for (auto it = problem->getGroupsOrdering().cbegin();\n      it != problem->getGroupsOrdering().cend(); ++it)\n    JCols += problem->getGroupDim(*it);\n  const size_t dim = problem->getGroupDim(2);\n  auto linearSolver = optimizer.getSolver<LinearSolver>();\n  linearSolver->setMargStartIndex(JCols - dim);\n  const double before = Timestamp::now();\n  optimizer.optimize();\n  const double after = Timestamp::now();\n  std::cout << \"Elapsed time [s]: \" << after - before << std::endl;\n  std::cout << \"Calibration after: \" << *dv_Theta << std::endl;\n  std::cout << \"Singular values (scaled): \"\n    << linearSolver->getSingularValues().transpose() << std::endl;\n  std::cout << \"Unobservable basis (scaled): \" << std::endl\n    << linearSolver->getNullSpace() << std::endl;\n  std::cout << \"Observable basis (scaled): \" << std::endl\n    << linearSolver->getRowSpace() << std::endl;\n  linearSolver->analyzeMarginal();\n  std::cout << \"SVD rank: \" << linearSolver->getSVDRank() << std::endl;\n  std::cout << \"SVD rank deficiency: \" << linearSolver->getSVDRankDeficiency()\n    << std::endl;\n  std::cout << \"SVD tolerance: \" << linearSolver->getSVDTolerance()\n    << std::endl;\n  std::cout << \"Singular values: \" << optimizer.getSolver<LinearSolver>()\n    ->getSingularValues().transpose() << std::endl;\n  std::cout << \"QR rank: \" << optimizer.getSolver<LinearSolver>()->getQRRank()\n    << std::endl;\n  std::cout << \"QR rank deficiency: \" << optimizer.getSolver<LinearSolver>()\n    ->getQRRankDeficiency() << std::endl;\n  std::cout << \"QR tolerance: \" << linearSolver->getQRTolerance() << std::endl;\n  std::cout << \"Unobservable basis: \" << std::endl\n    << linearSolver->getNullSpace() << std::endl;\n  std::cout << \"Observable basis: \" << std::endl << linearSolver->getRowSpace()\n    << std::endl;\n  std::cout << \"Covariance: \" << std::endl << linearSolver->getCovariance()\n    << std::endl;\n  std::cout << \"Observable covariance: \" << std::endl\n    << linearSolver->getRowSpaceCovariance() << std::endl;\n  std::cout << \"Peak memory usage (MB): \" << linearSolver->getPeakMemoryUsage()\n    / 1024.0 / 1024.0 << std::endl;\n  std::cout << \"Memory usage (MB): \" << linearSolver->getMemoryUsage() /\n    1024.0 / 1024.0 << std::endl;\n  std::cout << \"Flop count: \" << linearSolver->getNumFlops() << std::endl;\n  std::cout << \"Linear solver time: \" << linearSolver->getLinearSolverTime()\n    << std::endl;\n  std::cout << \"Marginal analysis time: \"\n    << linearSolver->getMarginalAnalysisTime() << std::endl;\n  std::cout << \"Symbolic factorization time: \"\n    << linearSolver->getSymbolicFactorizationTime() << std::endl;\n  std::cout << \"Numeric factorization time: \"\n    << linearSolver->getNumericFactorizationTime() << std::endl;\n  std::cout << \"Log2sum of singular values: \"\n    << linearSolver->getSingularValuesLog2Sum() << std::endl;\n\n  // output results to file\n  std::ofstream x_true_log(\"x_true.txt\");\n  for (size_t i = 0; i < steps; ++i)\n    x_true_log << x_true[i].transpose() << std::endl;\n  std::ofstream x_odom_log(\"x_odom.txt\");\n  for (size_t i = 0; i < steps; ++i)\n    x_odom_log << x_odom[i].transpose() << std::endl;\n  std::ofstream x_est_log(\"x_est.txt\");\n  for (size_t i = 0; i < steps; ++i)\n    x_est_log << *(dv_x[i]) << std::endl;\n  std::ofstream l_log(\"l.txt\");\n  for (size_t i = 0; i < nl; ++i)\n    l_log << x_l[i].transpose() << std::endl;\n  std::ofstream l_est_log(\"l_est.txt\");\n  for (size_t i = 0; i < nl; ++i)\n    l_est_log << *(dv_x_l[i]) << std::endl;\n\n  // align landmarks\n  Eigen::MatrixXd l = Eigen::MatrixXd::Zero(3, nl);\n  Eigen::MatrixXd l_est = Eigen::MatrixXd::Zero(3, nl);\n  for (size_t i = 0; i < nl; ++i) {\n    l(0, i) = x_l[i](0);\n    l(1, i) = x_l[i](1);\n    l_est(0, i) = dv_x_l[i]->getValue()(0);\n    l_est(1, i) = dv_x_l[i]->getValue()(1);\n  }\n  Transformation<double, 3> trans(threePointSvd(l, l_est));\n  Eigen::MatrixXd l_est_trans = Eigen::MatrixXd::Zero(3, nl);\n  for (size_t i = 0; i < nl; ++i)\n    l_est_trans.col(i) = trans(l_est.col(i));\n  std::ofstream l_est_trans_log(\"l_est_trans.txt\");\n  for (size_t i = 0; i < nl; ++i)\n    l_est_trans_log << l_est_trans.col(i).head<2>().transpose() << std::endl;\n\n  // align poses\n  std::vector<Eigen::Vector3d > x_est_trans;\n  x_est_trans.reserve(steps);\n  std::ofstream x_est_trans_log(\"x_est_trans.txt\");\n  for (size_t i = 0; i < steps; ++i) {\n    Eigen::Vector3d pose((Eigen::Vector3d()\n      << dv_x[i]->getValue().head<2>(), 0).finished());\n    trans.transform(pose, pose);\n    pose(2) = dv_x[i]->getValue()(2);\n    x_est_trans.push_back(pose);\n    x_est_trans_log << x_est_trans[i].transpose() << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "67fe6cb00f27b4a59ed7930540785670aa196d77", "size": 12638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "incremental_calibration_examples/incremental_calibration_examples_2dlrf/src/2dlrf/simulate-offline.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_2dlrf/src/2dlrf/simulate-offline.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_2dlrf/src/2dlrf/simulate-offline.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": 38.1812688822, "max_line_length": 80, "alphanum_fraction": 0.649153347, "num_tokens": 3738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5084695400502636}}
{"text": "//\n// Created by david on 2018-11-16.\n//\n\n#include \"matvec_dense.h\"\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <general/class_tic_toc.h>\n#include <memory>\n#define profile_matrix_product_dense 1\n\n// Function definitions\ntemplate<typename Scalar>\nusing MatrixType = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\ntemplate<typename Scalar>\nusing VectorType = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\ntemplate<typename Scalar>\nusing VectorTypeT = Eigen::Matrix<Scalar, 1, Eigen::Dynamic>;\n\nnamespace dense_lu {\n    std::optional<Eigen::PartialPivLU<MatrixType<double>>>               lu_real;\n    std::optional<Eigen::PartialPivLU<MatrixType<std::complex<double>>>> lu_cplx;\n    void                                                                 reset() {\n        lu_real.reset();\n        lu_cplx.reset();\n    }\n    template<typename Scalar>\n    void init() {\n        if constexpr(std::is_same_v<Scalar, double>) { dense_lu::lu_real = Eigen::PartialPivLU<MatrixType<Scalar>>(); }\n        if constexpr(std::is_same_v<Scalar, std::complex<double>>) dense_lu::lu_cplx = Eigen::PartialPivLU<MatrixType<Scalar>>();\n    }\n\n}\n\ntemplate<typename Scalar>\nMatVecDense<Scalar>::~MatVecDense() {\n    dense_lu::reset();\n}\n\n// Pointer to data constructor, copies the matrix into an internal Eigen matrix.\ntemplate<typename Scalar>\nMatVecDense<Scalar>::MatVecDense(const Scalar *const A_, const long L_, const bool copy_data, const eig::Form form_, const eig::Side side_)\n    : A_ptr(A_), L(L_), form(form_), side(side_) {\n    if(copy_data) {\n        A_stl.resize(static_cast<size_t>(L * L));\n        std::copy(A_ptr, A_ptr + static_cast<size_t>(L * L), A_stl.begin());\n        A_ptr = A_stl.data();\n    }\n    dense_lu::init<Scalar>();\n    init_profiling();\n}\n\ntemplate<typename Scalar>\nvoid MatVecDense<Scalar>::FactorOP()\n\n/*  Partial pivot LU decomposition\n *  Factors P(A-sigma*I) = LU\n */\n{\n    if(readyFactorOp) return; // happens only once\n    if(not readyShift) throw std::runtime_error(\"Cannot FactorOP: Shift value sigma has not been set.\");\n    Eigen::Map<const MatrixType<Scalar>> A_matrix(A_ptr, L, L);\n    t_factorOP->tic();\n    if constexpr(std::is_same_v<Scalar, eig::real>) { dense_lu::lu_real.value().compute(A_matrix); }\n    if constexpr(std::is_same_v<Scalar, eig::cplx>) { dense_lu::lu_cplx.value().compute(A_matrix); }\n\n    readyFactorOp = true;\n    t_factorOP->toc();\n}\n\ntemplate<typename Scalar>\nvoid MatVecDense<Scalar>::MultOPv(Scalar *x_in_ptr, Scalar *x_out_ptr) {\n    assert(readyFactorOp and \"FactorOp() has not been run yet.\");\n    t_multOPv->tic();\n    switch(side) {\n        case eig::Side::R: {\n            Eigen::Map<VectorType<Scalar>> x_in(x_in_ptr, L);\n            Eigen::Map<VectorType<Scalar>> x_out(x_out_ptr, L);\n            if constexpr(std::is_same_v<Scalar, double>) x_out.noalias() = dense_lu::lu_real.value().solve(x_in);\n            if constexpr(std::is_same_v<Scalar, std::complex<double>>) x_out.noalias() = dense_lu::lu_cplx.value().solve(x_in);\n            break;\n        }\n        case eig::Side::L: {\n            Eigen::Map<VectorTypeT<Scalar>> x_in(x_in_ptr, L);\n            Eigen::Map<VectorTypeT<Scalar>> x_out(x_out_ptr, L);\n            if constexpr(std::is_same_v<Scalar, double>) x_out.noalias() = x_in * dense_lu::lu_real.value().inverse();\n            if constexpr(std::is_same_v<Scalar, std::complex<double>>) x_out.noalias() = x_in * dense_lu::lu_cplx.value().inverse();\n            break;\n        }\n        case eig::Side::LR: {\n            throw std::runtime_error(\"eigs cannot handle sides L and R simultaneously\");\n        }\n    }\n    t_multOPv->toc();\n    counter++;\n}\n\ntemplate<typename Scalar>\nvoid MatVecDense<Scalar>::MultAx(Scalar *x_in, Scalar *x_out) {\n    auto                                 token = t_multAx->tic_token();\n    Eigen::Map<const MatrixType<Scalar>> A_matrix(A_ptr, L, L);\n    switch(form) {\n        case eig::Form::NSYM:\n            switch(side) {\n                case eig::Side::R: {\n                    Eigen::Map<VectorType<Scalar>> x_vec_in(x_in, L);\n                    Eigen::Map<VectorType<Scalar>> x_vec_out(x_out, L);\n                    x_vec_out.noalias() = A_matrix * x_vec_in;\n                    break;\n                }\n                case eig::Side::L: {\n                    Eigen::Map<VectorTypeT<Scalar>> x_vec_in(x_in, L);\n                    Eigen::Map<VectorTypeT<Scalar>> x_vec_out(x_out, L);\n                    x_vec_out.noalias() = x_vec_in * A_matrix;\n                    break;\n                }\n                case eig::Side::LR: {\n                    throw std::runtime_error(\"eigs cannot handle sides L and R simultaneously\");\n                }\n            }\n            break;\n        case eig::Form::SYMM: {\n            Eigen::Map<VectorType<Scalar>> x_vec_in(x_in, L);\n            Eigen::Map<VectorType<Scalar>> x_vec_out(x_out, L);\n            x_vec_out.noalias() = A_matrix.template selfadjointView<Eigen::Lower>() * x_vec_in;\n            break;\n        }\n    }\n    counter++;\n}\n\ntemplate<typename T>\nvoid MatVecDense<T>::MultAx(void *x, int *ldx, void *y, int *ldy, int *blockSize, [[maybe_unused]] primme_params *primme, [[maybe_unused]] int *err) {\n    auto                                 token = t_multAx->tic_token();\n    Eigen::Map<const MatrixType<Scalar>> A_matrix(A_ptr, L, L);\n    switch(form) {\n        case eig::Form::NSYM:\n            switch(side) {\n                case eig::Side::R: {\n                    for(int i = 0; i < *blockSize; i++) {\n                        T *                            x_in  = static_cast<T *>(x) + *ldx * i;\n                        T *                            x_out = static_cast<T *>(y) + *ldy * i;\n                        Eigen::Map<VectorType<Scalar>> x_vec_in(x_in, L);\n                        Eigen::Map<VectorType<Scalar>> x_vec_out(x_out, L);\n                        x_vec_out.noalias() = A_matrix * x_vec_in;\n                        counter++;\n                    }\n                    break;\n                }\n                case eig::Side::L: {\n                    for(int i = 0; i < *blockSize; i++) {\n                        T *                            x_in  = static_cast<T *>(x) + *ldx * i;\n                        T *                            x_out = static_cast<T *>(y) + *ldy * i;\n                        Eigen::Map<VectorType<Scalar>> x_vec_in(x_in, L);\n                        Eigen::Map<VectorType<Scalar>> x_vec_out(x_out, L);\n                        x_vec_out.noalias() = x_vec_in * A_matrix;\n                        counter++;\n                    }\n                    break;\n                }\n                case eig::Side::LR: {\n                    throw std::runtime_error(\"eigs cannot handle sides L and R simultaneously\");\n                }\n            }\n            break;\n        case eig::Form::SYMM: {\n            for(int i = 0; i < *blockSize; i++) {\n                T *                            x_in  = static_cast<T *>(x) + *ldx * i;\n                T *                            x_out = static_cast<T *>(y) + *ldy * i;\n                Eigen::Map<VectorType<Scalar>> x_vec_in(x_in, L);\n                Eigen::Map<VectorType<Scalar>> x_vec_out(x_out, L);\n                x_vec_out.noalias() = A_matrix.template selfadjointView<Eigen::Lower>() * x_vec_in;\n                counter++;\n            }\n            break;\n        }\n    }\n    *err = 0;\n}\n\ntemplate<typename Scalar>\nvoid MatVecDense<Scalar>::print() const {\n    Eigen::Map<const MatrixType<Scalar>> A_matrix(A_ptr, L, L);\n}\n\ntemplate<typename Scalar>\nvoid MatVecDense<Scalar>::set_shift(std::complex<double> sigma_) {\n    if(readyShift) { return; }\n    sigma = sigma_;\n    if(A_stl.empty()) {\n        A_stl.resize(static_cast<size_t>(L * L));\n        std::copy(A_ptr, A_ptr + static_cast<size_t>(L * L), A_stl.begin());\n        A_ptr = A_stl.data();\n    }\n    Eigen::Map<MatrixType<Scalar>> A_matrix(A_stl.data(), L, L);\n    if constexpr(std::is_same_v<Scalar, eig::real>) A_matrix -= Eigen::MatrixXd::Identity(L, L) * std::real(sigma);\n    if constexpr(std::is_same_v<Scalar, eig::cplx>) A_matrix -= Eigen::MatrixXd::Identity(L, L) * sigma;\n    readyShift = true;\n}\n\ntemplate<typename Scalar>\nvoid MatVecDense<Scalar>::set_mode(const eig::Form form_) {\n    form = form_;\n}\ntemplate<typename Scalar>\nvoid MatVecDense<Scalar>::set_side(const eig::Side side_) {\n    side = side_;\n}\ntemplate<typename Scalar>\nconst eig::Form &MatVecDense<Scalar>::get_form() const {\n    return form;\n}\ntemplate<typename Scalar>\nconst eig::Side &MatVecDense<Scalar>::get_side() const {\n    return side;\n}\n\ntemplate<typename Scalar>\nvoid MatVecDense<Scalar>::init_profiling() {\n    t_factorOP = std::make_unique<class_tic_toc>(profile_matrix_product_dense, 5, \"Time FactorOp\");\n    t_multOPv  = std::make_unique<class_tic_toc>(profile_matrix_product_dense, 5, \"Time MultOpv\");\n    t_multAx   = std::make_unique<class_tic_toc>(profile_matrix_product_dense, 5, \"Time MultAx\");\n}\n\n// Explicit instantiations\n\ntemplate class MatVecDense<double>;\ntemplate class MatVecDense<std::complex<double>>;\n", "meta": {"hexsha": "ff2611a7059e5cb4e49c39a687ad0b493c6b802c", "size": 9051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/math/eig/matvec/matvec_dense.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": "source/math/eig/matvec/matvec_dense.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": "source/math/eig/matvec/matvec_dense.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": 39.5240174672, "max_line_length": 150, "alphanum_fraction": 0.5701027511, "num_tokens": 2216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.508405311615389}}
{"text": "/*\n *  Distributed under the MIT License (See accompanying file /LICENSE )\n */\n#include \"pgcpp/euclid_plane.hpp\" // import Ar\n#include \"pgcpp/persp_plane.hpp\"\n#include \"pgcpp/pg_line.hpp\"\n#include \"pgcpp/pg_point.hpp\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <doctest/doctest.h>\n// #include <iostream>\n\nusing namespace fun;\n\nstatic const auto Zero = doctest::Approx(0).epsilon(0.01);\n\n/*!\n * @brief\n *\n * @tparam PG\n * @param[in] myck\n */\ntemplate <typename PG>\nvoid chk_degenerate(const PG& myck)\n{\n    using Point = typename PG::point_t;\n    // using Line = typename PG::line_t;\n    using K = Value_type<Point>;\n\n    auto a1 = Point {-1, 0, 3};\n    auto a2 = Point {4, -2, 1};\n    auto a3 = Point {3, -1, 1};\n\n    auto triangle = std::tuple {std::move(a1), std::move(a2), std::move(a3)};\n    const auto trilateral = tri_dual(triangle);\n\n    // const auto& [a1, a2, a3] = triangle;\n    const auto& [l1, l2, l3] = trilateral;\n\n    const auto m12 = myck.midpoint(a1, a2);\n    const auto m23 = myck.midpoint(a2, a3);\n    const auto m13 = myck.midpoint(a1, a3);\n    const auto t1 = a1 * m23;\n    const auto t2 = a2 * m13;\n    const auto t3 = a3 * m12;\n\n    const auto [q1, q2, q3] = myck.tri_quadrance(triangle);\n    const auto [s1, s2, s3] = myck.tri_spread(trilateral);\n\n    const auto tqf = sq(q1 + q2 + q3) - 2 * (q1 * q1 + q2 * q2 + q3 * q3);\n    const auto tsf =\n        sq(s1 + s2 + s3) - 2 * (s1 * s1 + s2 * s2 + s3 * s3) - 4 * s1 * s2 * s3;\n    auto a4 = plucker(3, a1, 4, a2);\n    const auto tri2 = std::tuple {std::move(a1), std::move(a2), std::move(a4)};\n\n    const auto [qq1, qq2, qq3] = myck.tri_quadrance(tri2);\n\n    const auto tqf2 = Ar(qq1, qq2, qq3); // get 0\n\n    if constexpr (Integral<K>)\n    {\n        CHECK(!myck.is_parallel(l1, l2));\n        CHECK(!myck.is_parallel(l2, l3));\n        CHECK(coincident(t1 * t2, t3));\n        CHECK(tqf == Ar(q1, q2, q3));\n        CHECK(tsf == 0);\n        CHECK(tqf2 == 0);\n    }\n    else\n    {\n        CHECK(myck.l_infty().dot(l1 * l2) != Zero);\n        CHECK(myck.l_infty().dot(l2 * l3) != Zero);\n        CHECK(t1.dot(t2 * t3) == Zero);\n        CHECK(tqf - Ar(q1, q2, q3) == Zero);\n        CHECK(tsf == Zero);\n        CHECK(tqf2 == Zero);\n    }\n}\n\nTEST_CASE(\"Perspective Euclid plane (cpp_int)\")\n{\n    using boost::multiprecision::cpp_int;\n\n    auto Ire = pg_point<cpp_int>(0, 1, 1);\n    auto Iim = pg_point<cpp_int>(1, 0, 0);\n    auto l_inf = pg_line<cpp_int>(0, -1, 1);\n\n    const auto P =\n        persp_euclid_plane {std::move(Ire), std::move(Iim), std::move(l_inf)};\n    chk_degenerate(P);\n}\n\nTEST_CASE(\"Perspective Euclid plane (floating point)\")\n{\n    auto Ire = pg_point {0., 1., 1.};\n    auto Iim = pg_point {1., 0., 0.};\n    auto l_inf = pg_line {0., -1., 1.};\n\n    const auto P =\n        persp_euclid_plane {std::move(Ire), std::move(Iim), std::move(l_inf)};\n    chk_degenerate(P);\n}\n", "meta": {"hexsha": "bbbb25423f466720387ba39584ea687d8ec06b36", "size": 2860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/test/src/test_persp_plane.cpp", "max_stars_repo_name": "luk036/pgcpp", "max_stars_repo_head_hexsha": "acef09303ebaa1334b5d30b727d975495e488d4f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-21T09:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:08:51.000Z", "max_issues_repo_path": "lib/test/src/test_persp_plane.cpp", "max_issues_repo_name": "luk036/pgcpp", "max_issues_repo_head_hexsha": "acef09303ebaa1334b5d30b727d975495e488d4f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-25T11:01:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T13:23:34.000Z", "max_forks_repo_path": "lib/test/src/test_persp_plane.cpp", "max_forks_repo_name": "luk036/pgcpp", "max_forks_repo_head_hexsha": "acef09303ebaa1334b5d30b727d975495e488d4f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-06-03T08:58:05.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-03T08:58:05.000Z", "avg_line_length": 28.0392156863, "max_line_length": 80, "alphanum_fraction": 0.5828671329, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5084053068221814}}
{"text": "#pragma once\n\n#include <vector>\n#include <Eigen/Dense>\n\n\n/* We use the following indices for orbital types:\n   0 = s\n   1 = px\n   2 = py\n   3 = pz\n\n   Therefore, if an index is > 0, it is a p orbital\n*/\n\n// This is the number of orbital types we have\nconst int orbitals_per_atom = 4;\n\n\n\n/*! \\brief Calculate a fock matrix */\nEigen::MatrixXd calculate_fock_matrix_fast(Eigen::MatrixXd hamiltonian_matrix,\n                                           Eigen::MatrixXd interaction_matrix,\n                                           Eigen::MatrixXd density_matrix,\n                                           double model_dipole);\n\n/*! \\brief Calculate MP2 energy */\ndouble calculate_energy_mp2(std::vector<double> E_occ, std::vector<double> E_virt, Eigen::MatrixXd v_tilde_flat);\n", "meta": {"hexsha": "594b8c95b970541626e0a79eec0b54948eb0f654", "size": 773, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Day_6/qm_project/qm_cpp/day_6.hpp", "max_stars_repo_name": "godotalgorithm/qm_project_sss2019", "max_stars_repo_head_hexsha": "740d571b9f8d751be7748fd08fee88ca02820dd1", "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": "Day_6/qm_project/qm_cpp/day_6.hpp", "max_issues_repo_name": "godotalgorithm/qm_project_sss2019", "max_issues_repo_head_hexsha": "740d571b9f8d751be7748fd08fee88ca02820dd1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day_6/qm_project/qm_cpp/day_6.hpp", "max_forks_repo_name": "godotalgorithm/qm_project_sss2019", "max_forks_repo_head_hexsha": "740d571b9f8d751be7748fd08fee88ca02820dd1", "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.6551724138, "max_line_length": 113, "alphanum_fraction": 0.6093143596, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5083705149531365}}
{"text": "/**\n * @file spalera_sgd_test.cpp\n * @author Marcus Edel\n *\n * Test file for SGD (stochastic gradient descent).\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/optimizers/spalera_sgd/spalera_sgd.hpp>\n#include <mlpack/methods/logistic_regression/logistic_regression.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::optimization;\nusing namespace mlpack::distribution;\nusing namespace mlpack::regression;\n\nBOOST_AUTO_TEST_SUITE(SPALeRASGDTest);\n\n/**\n * Run SPALeRA SGD on logistic regression and make sure the results are\n * acceptable.\n */\nBOOST_AUTO_TEST_CASE(LogisticRegressionTest)\n{\n  // Generate a two-Gaussian dataset.\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, 500);\n  arma::Row<size_t> responses(500);\n  for (size_t i = 0; i < 250; ++i)\n  {\n    data.col(i) = g1.Random();\n    responses[i] = 0;\n  }\n  for (size_t i = 250; i < 500; ++i)\n  {\n    data.col(i) = g2.Random();\n    responses[i] = 1;\n  }\n\n  // Shuffle the dataset.\n  arma::uvec indices = arma::shuffle(arma::linspace<arma::uvec>(0,\n      data.n_cols - 1, data.n_cols));\n  arma::mat shuffledData(3, 500);\n  arma::Row<size_t> shuffledResponses(500);\n  for (size_t i = 0; i < data.n_cols; ++i)\n  {\n    shuffledData.col(i) = data.col(indices[i]);\n    shuffledResponses[i] = responses[indices[i]];\n  }\n\n  // Create a test set.\n  arma::mat testData(3, 500);\n  arma::Row<size_t> testResponses(500);\n  for (size_t i = 0; i < 250; ++i)\n  {\n    testData.col(i) = g1.Random();\n    testResponses[i] = 0;\n  }\n  for (size_t i = 250; i < 500; ++i)\n  {\n    testData.col(i) = g2.Random();\n    testResponses[i] = 1;\n  }\n\n  // Now run mini-batch SGD with a couple of batch sizes.\n  for (size_t batchSize = 30; batchSize < 50; batchSize += 5)\n  {\n    SPALeRASGD<> mbsgd(0.05 / batchSize, batchSize, 10000, 1e-4);\n    LogisticRegression<> lr(shuffledData, shuffledResponses, mbsgd, 0.5);\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, 0.5); // 0.5% error tolerance.\n\n    const double testAcc = lr.ComputeAccuracy(testData, testResponses);\n    BOOST_REQUIRE_CLOSE(testAcc, 100.0, 0.8); // 0.8% error tolerance.\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "09090fbf43955d5266cd2d0ad3e8294278269775", "size": 2688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/spalera_sgd_test.cpp", "max_stars_repo_name": "MJ10/mlpack", "max_stars_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "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-05-02T21:10:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T21:10:55.000Z", "max_issues_repo_path": "src/mlpack/tests/spalera_sgd_test.cpp", "max_issues_repo_name": "MJ10/mlpack", "max_issues_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "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/spalera_sgd_test.cpp", "max_forks_repo_name": "MJ10/mlpack", "max_forks_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "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.8666666667, "max_line_length": 80, "alphanum_fraction": 0.6752232143, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5083705106433335}}
{"text": "\n#include <string>\n#include <vector>\n#include <boost/filesystem.hpp>\n#include <math.h>\n#include <algorithm>\n#include <opencv2/opencv.hpp>\n#include <opencv2/xfeatures2d.hpp>\n#include <eigen3/Eigen/Eigenvalues>\n#include <opencv2/core/eigen.hpp>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n#include \"../bag_of_words/bow_tools.hpp\"\n#include \"../loop_closure/LC_tools.hpp\"\n#include \"../vo/VO_tools.hpp\"\n#include \"../ba/BA_tools.hpp\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace gtsam;\n\nEigen::VectorXd K(9);\n\nint main()\n{\n\n    Ptr<DescriptorMatcher> matcher_b(new FlannBasedMatcher);\n    //create Sift feature point extracter\n    Ptr<FeatureDetector> features(new cv::xfeatures2d::SiftFeatureDetector);\n    //create Sift descriptor extractor\n    Ptr<DescriptorExtractor> descriptors(new cv::xfeatures2d::SiftDescriptorExtractor);\n\n    Ptr<BOWImgDescriptorExtractor> bowDE(new BOWImgDescriptorExtractor(descriptors, matcher_b));\n    VO solver(\"trajectory.txt\",\"../../data/rgbd_dataset_freiburg2_desk/rgb/\");\n    solver.SetK(525,525,319.5,239.5);\n\n    Mat dictionary;\n    build_dictionary(dictionary);\n    bowDE->setVocabulary(dictionary);\n\n    map<int, Mat> index_features;\n    map<int, vector<KeyPoint>> index_points;\n    map<int, Mat> index_descriptors;\n    int last_loop = 0;\n\n    NonlinearFactorGraph graph;\n    noiseModel::Diagonal::shared_ptr model = noiseModel::Diagonal::Sigmas(Vector3(0.2, 0.2, 0.2));\n\n    Values initialEstimate;\n\n    vector<Eigen::Vector3f> all_pose;\n    vector<Eigen::Vector3f> all_pose_pre;\n    vector<Eigen::Matrix3f> all_R;\n    vector<Eigen::Vector3f> all_t;\n    vector<Eigen::Matrix3f> after_R;\n    vector<Eigen::Vector3f> after_t;\n    vector<Eigen::Vector2f> pre_all_inliers1;\n    vector<Eigen::Vector2f> pre_all_inliers2;\n    vector<vector<Eigen::Vector2f> >  all_2d_inliers;\n    vector<map<int, int> >  all_indexes;\n    vector<Eigen::Vector3f> all_3d_points;\n    map<int, vector<Eigen::Vector2f> > all_frames;\n    Eigen::Vector3f inital_pos;\n    inital_pos << 0.0, 0.0, 0.0;\n\n    int step_size = 10;\n    K = solver.get_K_();\n    int file_size = solver.read_file_names();\n    Ptr<Feature2D> f2d = xfeatures2d::SIFT::create(0,3,0.04,10,1.6);\n\n    int index = 0;\n\n    for (int files = 0; files < file_size - step_size;\n     files+=step_size)\n    {\n        solver.solve_once(all_R,\n                        all_t,\n                        pre_all_inliers1,\n                        pre_all_inliers2,\n                        all_2d_inliers,\n                        all_indexes,\n                        index_points,\n                        index_descriptors,\n                        f2d,\n                        index,\n                        files);\n\n        if (all_R.size() == 9)\n        {\n            //relative to absolute\n            for (int i = 1; i < 9; i++)\n            {\n                Eigen::Matrix3f R_tmp = all_R[i]*all_R[i-1];\n                Eigen::Vector3f t_tmp = all_R[i]*all_t[i-1]+all_t[i];\n                all_R[i] = R_tmp;\n                all_t[i] = t_tmp;\n            }\n            get_all_3d_landmarks(all_2d_inliers,all_indexes,all_3d_points,all_frames,all_R,all_t);\n            optimization(all_3d_points,all_frames,all_R,all_t,after_R,after_t);\n            all_R.clear();\n            all_t.clear();\n            all_frames.clear();\n            all_indexes.clear();\n            all_2d_inliers.clear();\n            all_3d_points.clear();\n            all_pose_pre.push_back(inital_pos);\n            for (int i = 0; i < 9; i++)\n            {\n                Eigen::Vector3f new_pos;\n                new_pos = after_R[i]*inital_pos +after_t[i];\n                all_pose.push_back(new_pos);\n                all_pose_pre.push_back(new_pos);\n            }\n\n            inital_pos = all_pose[8];\n            if (index == 9)\n            {\n                noiseModel::Diagonal::shared_ptr priorNoise = noiseModel::Diagonal::Sigmas(Vector3(0.3, 0.3, 0.3));\n                graph.emplace_shared<PriorFactor<Point3> >(0, Point3(0, 0, 0), priorNoise);\n                initialEstimate.insert(0, Point3(0.0, 0.0, 0.0));\n                Mat bowDescriptor;\n                vector<KeyPoint> keypoints;\n                bowDE->compute(index_descriptors[0], bowDescriptor);\n                index_features[0] = bowDescriptor;\n            }\n            for (int i = 0; i < all_pose.size(); i++)\n            {\n                Eigen::Vector3f trans;\n                trans = all_pose[i]- all_pose_pre[i];\n                graph.emplace_shared<BetweenFactor<Point3> >(index-9+i, index-8+i, Point3(trans[0], trans[1], trans[2]), model);\n                initialEstimate.insert(index-8+i, Point3(all_pose[i][0], all_pose[i][1], all_pose[i][2]));\n                Mat bowDescriptor;\n                bowDE->compute(index_descriptors[index-8+i], bowDescriptor);\n                index_features[index-8+i] = bowDescriptor;\n                if ((index-8+i) - last_loop >= 20)\n                {\n                    int frame_looped = find_loop(index_features);\n                    if (frame_looped != index_features.size())\n                    {\n                        Mat R_loop, t_loop;\n                        geometric_verification(R_loop, t_loop, K, index_points, index_descriptors, frame_looped,index-8+i);\n                        Mat pose_loop = (Mat_<double>(3,1) << all_pose[i][0], all_pose[i][1], all_pose[i][2]);\n                        Mat pose_looped = R_loop*pose_loop+t_loop;\n                        Mat trans_loop = pose_loop - pose_looped;\n                        graph.emplace_shared<BetweenFactor<Point3> >(index-8+i, frame_looped, Point3(trans_loop.at<double>(0,0), trans_loop.at<double>(1,0), trans_loop.at<double>(2,0)), model);\n                        GaussNewtonParams parameters;\n                        parameters.relativeErrorTol = 1e-5;\n                        parameters.maxIterations = 100;\n                        GaussNewtonOptimizer optimizer(graph, initialEstimate, parameters);\n                        Values result = optimizer.optimize();\n                        last_loop = index-8+i;\n                    }\n                }\n            }\n            after_R.clear();\n            after_t.clear();\n            all_pose.clear();\n            all_pose_pre.clear();\n\n        }\n\n    }\n    return 0;\n}\n", "meta": {"hexsha": "18467c31f4ca8c1be9504657bdcc59bb3437c118", "size": 6256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CPP-Final-Project-master/test/main.cpp", "max_stars_repo_name": "HaominStone/HaominStone.github.io", "max_stars_repo_head_hexsha": "bfa52b944d9d04b150853446835fb9c9f17dd8e2", "max_stars_repo_licenses": ["MIT"], "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-Final-Project-master/test/main.cpp", "max_issues_repo_name": "HaominStone/HaominStone.github.io", "max_issues_repo_head_hexsha": "bfa52b944d9d04b150853446835fb9c9f17dd8e2", "max_issues_repo_licenses": ["MIT"], "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-Final-Project-master/test/main.cpp", "max_forks_repo_name": "HaominStone/HaominStone.github.io", "max_forks_repo_head_hexsha": "bfa52b944d9d04b150853446835fb9c9f17dd8e2", "max_forks_repo_licenses": ["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.686746988, "max_line_length": 193, "alphanum_fraction": 0.5687340153, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5083705063335302}}
{"text": "/**\n * \\file libs/numeric/ublasx/test/rcond.cpp\n *\n * \\brief Test suite for the \\c rcond operation.\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n//ATTENTION: test fails\n//TODO: fix it\n\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/fwd.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/symmetric.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublasx/operation/rcond.hpp>\n#include <complex>\n#include <cstddef>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace ublasx = boost::numeric::ublasx;\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_square_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Square Dense Matrix - Column Major\");\n\n\ttypedef double value_type;\n\ttypedef double result_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = 1; A(0,1) = 2; A(0,2) = 3;\n\tA(1,0) = 4; A(1,1) = 5; A(1,2) = 6;\n\tA(2,0) = 7; A(2,1) = 8; A(2,2) = 9;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 1.5420e-18; // Computed with matlab R2008a, octave 3.2.4 and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-18 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_square_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Square Dense Matrix - Row Major\");\n\n\ttypedef double value_type;\n\ttypedef double result_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = 1; A(0,1) = 2; A(0,2) = 3;\n\tA(1,0) = 4; A(1,1) = 5; A(1,2) = 6;\n\tA(2,0) = 7; A(2,1) = 8; A(2,2) = 9;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 1.5420e-18; // Computed with matlab R2008a, octave 3.2.4 and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-18 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_upper_triangular_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Upper Triangular Matrix - Column Major\");\n\n\ttypedef double value_type;\n\ttypedef double result_type;\n\ttypedef ublas::triangular_matrix<value_type,ublas::upper,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = 1; A(0,1) = 2; A(0,2) = 3;\n\t            A(1,1) = 4; A(1,2) = 5;\n\t                        A(2,2) = 6;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.07142857; // Computed with matlab R2008a, octave 3.2.4 and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-7 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_upper_triangular_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Upper Triangular Matrix - Row Major\");\n\n\ttypedef double value_type;\n\ttypedef double result_type;\n\ttypedef ublas::triangular_matrix<value_type,ublas::upper,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = 1; A(0,1) = 2; A(0,2) = 3;\n\t            A(1,1) = 4; A(1,2) = 5;\n\t                        A(2,2) = 6;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.07142857; // Computed with matlab R2008a, octave 3.2.4 and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-7 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_lower_triangular_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Lower Triangular Matrix - Column Major\");\n\n\ttypedef double value_type;\n\ttypedef double result_type;\n\ttypedef ublas::triangular_matrix<value_type,ublas::lower,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = 1;\n\tA(1,0) = 2; A(1,1) = 3;\n\tA(2,0) = 4; A(2,1) = 5; A(2,2) = 6;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.0703125; // Computed with matlab R2008a, octave 3.2.4, and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-7 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_lower_triangular_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Lower Triangular Matrix - Row Major\");\n\n\ttypedef double value_type;\n\ttypedef double result_type;\n\ttypedef ublas::triangular_matrix<value_type,ublas::lower,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = 1;\n\tA(1,0) = 2; A(1,1) = 3;\n\tA(2,0) = 4; A(2,1) = 5; A(2,2) = 6;\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.0703125; // Computed with matlab R2008a, octave 3.2.4, and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-7 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_banded_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Banded Matrix - Column Major\");\n\n\ttypedef double value_type;\n\ttypedef double result_type;\n\ttypedef ublas::banded_matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 4;\n\n\tmatrix_type A(n,n,1,2);\n\tA(0,0) = -0.23; A(0,1) = 2.54; A(0,2) = -3.66;         /* 0 */ // 1st row\n\tA(1,0) = -6.98; A(1,1) = 2.46; A(1,2) = -2.73; A(1,3) = -2.13; // 2nd row\n\t        /* 0 */ A(2,1) = 2.56; A(2,2) =  2.46; A(2,3) =  4.07; // 3rd row\n\t        /* 0 */        /* 0 */ A(3,2) = -4.78; A(3,3) = -3.82; // 4th row\n\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.017728; // Computed with matlab R2008a, octave 3.2.4, and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-6 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_banded_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Banded Matrix - Row Major\");\n\n\ttypedef double value_type;\n\ttypedef double result_type;\n\ttypedef ublas::banded_matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 4;\n\n\tmatrix_type A(n,n,1,2);\n\tA(0,0) = -0.23; A(0,1) = 2.54; A(0,2) = -3.66;         /* 0 */ // 1st row\n\tA(1,0) = -6.98; A(1,1) = 2.46; A(1,2) = -2.73; A(1,3) = -2.13; // 2nd row\n\t        /* 0 */ A(2,1) = 2.56; A(2,2) =  2.46; A(2,3) =  4.07; // 3rd row\n\t        /* 0 */        /* 0 */ A(3,2) = -4.78; A(3,3) = -3.82; // 4th row\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.017728; // Computed with matlab R2008a, octave 3.2.4, and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-6 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_lower_symmetric_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Lower Symmetric Matrix - Column Major\");\n\n\ttypedef double value_type;\n\ttypedef double result_type;\n\ttypedef ublas::symmetric_matrix<value_type,ublas::lower,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 4;\n\n\tmatrix_type A(n,n);\n\tA(0,0) =  2.07;   /* 3.87*/      /* 4.20*/      /*-1.15*/\n\tA(1,0) =  3.87; A(1,1) = -0.21;  /* 1.87*/      /* 0.63*/\n\tA(2,0) =  4.20; A(2,1) = 1.87; A(2,2) = 1.15;   /* 2.06*/\n\tA(3,0) = -1.15; A(3,1) = 0.63; A(3,2) = 2.06; A(3,3) = -1.81;\n\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.01321232; // Computed with matlab R2008a, octave 3.2.4, and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-6 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_lower_symmetric_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Lower Symmetric Matrix - Row Major\");\n\n\ttypedef double value_type;\n\ttypedef double result_type;\n\ttypedef ublas::symmetric_matrix<value_type,ublas::lower,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 4;\n\n\tmatrix_type A(n,n);\n\tA(0,0) =  2.07;   /* 3.87*/      /* 4.20*/      /*-1.15*/\n\tA(1,0) =  3.87; A(1,1) = -0.21;  /* 1.87*/      /* 0.63*/\n\tA(2,0) =  4.20; A(2,1) = 1.87; A(2,2) = 1.15;   /* 2.06*/\n\tA(3,0) = -1.15; A(3,1) = 0.63; A(3,2) = 2.06; A(3,3) = -1.81;\n\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.01321232; // Computed with matlab R2008a, octave 3.2.4, and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-6 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_upper_symmetric_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Upper Symmetric Matrix - Column Major\");\n\n\ttypedef double value_type;\n\ttypedef double result_type;\n\ttypedef ublas::symmetric_matrix<value_type,ublas::upper,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 4;\n\n\tmatrix_type A(n,n);\n\tA(0,0) =  2.07; A(0,1) =  3.87; A(0,2) = 4.20; A(0,3) = -1.15;\n\tA(1,0) =  3.87; A(1,1) = -0.21; A(1,2) = 1.87; A(1,3) =  0.63;\n\t  /* 4.20*/       /* 1.87*/     A(2,2) = 1.15; A(2,3) =  2.06;\n\t  /*-1.15*/       /* 0.63*/       /* 2.06*/    A(3,3) = -1.81;\n\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.01321232; // Computed with matlab R2008a, octave 3.2.4, and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-6 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_upper_symmetric_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Upper Symmetric Matrix - Row Major\");\n\n\ttypedef double value_type;\n\ttypedef double result_type;\n\ttypedef ublas::symmetric_matrix<value_type,ublas::upper,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 4;\n\n\tmatrix_type A(n,n);\n\tA(0,0) =  2.07; A(0,1) =  3.87; A(0,2) = 4.20; A(0,3) = -1.15;\n\tA(1,0) =  3.87; A(1,1) = -0.21; A(1,2) = 1.87; A(1,3) =  0.63;\n\t  /* 4.20*/       /* 1.87*/     A(2,2) = 1.15; A(2,3) =  2.06;\n\t  /*-1.15*/       /* 0.63*/       /* 2.06*/    A(3,3) = -1.81;\n\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.01321232; // Computed with matlab R2008a, octave 3.2.4, and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-6 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_complex_lower_hermitian_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Lower Hermitian Matrix - Column Major\");\n\n\ttypedef std::complex<double> value_type;\n\ttypedef double result_type;\n\ttypedef ublas::hermitian_matrix<value_type,ublas::lower,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 4;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = value_type(-1.36, 0.00);\n\tA(1,0) = value_type( 1.58,-0.90); A(1,1) = value_type(-8.87, 0.00);\n\tA(2,0) = value_type( 2.21, 0.21); A(2,1) = value_type(-1.84, 0.03); A(2,2) = value_type(-4.63, 0.00);\n\tA(3,0) = value_type( 3.91,-1.50); A(3,1) = value_type(-1.78,-1.18); A(3,2) = value_type( 0.11,-0.11); A(3,3) = value_type(-1.84, 0.00);\n\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.028470197472865; // Computed with matlab R2008a, octave 3.2.4, and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-6 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_real_lower_hermitian_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Lower Hermitian Matrix - Row Major\");\n\n\ttypedef std::complex<double> value_type;\n\ttypedef double result_type;\n\ttypedef ublas::hermitian_matrix<value_type,ublas::lower,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 4;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = value_type(-1.36, 0.00);\n\tA(1,0) = value_type( 1.58,-0.90); A(1,1) = value_type(-8.87, 0.00);\n\tA(2,0) = value_type( 2.21, 0.21); A(2,1) = value_type(-1.84, 0.03); A(2,2) = value_type(-4.63, 0.00);\n\tA(3,0) = value_type( 3.91,-1.50); A(3,1) = value_type(-1.78,-1.18); A(3,2) = value_type( 0.11,-0.11); A(3,3) = value_type(-1.84, 0.00);\n\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.028470197472865; // Computed with matlab R2008a, octave 3.2.4, and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-6 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_complex_square_dense_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Square Dense Matrix - Column Major\");\n\n\ttypedef std::complex<double> value_type;\n\ttypedef double result_type;\n\ttypedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = value_type( 1, 2); A(0,1) = value_type( 3, 4); A(0,2) = value_type( 5, 6);\n\tA(1,0) = value_type( 7, 8); A(1,1) = value_type( 9,10); A(1,2) = value_type(11,12);\n\tA(2,0) = value_type(13,14); A(2,1) = value_type(15,16); A(2,2) = value_type(17,18);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\t//expect_res = 4.3758e-18; // Computed with matlab R2008a and octave 3.2.4 and R 2.11.1\n\texpect_res = 1.136408e-18; // Computed with R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-18 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_complex_square_dense_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Square Dense Matrix - Row Major\");\n\n\ttypedef std::complex<double> value_type;\n\ttypedef double result_type;\n\ttypedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = value_type( 1, 2); A(0,1) = value_type( 3, 4); A(0,2) = value_type( 5, 6);\n\tA(1,0) = value_type( 7, 8); A(1,1) = value_type( 9,10); A(1,2) = value_type(11,12);\n\tA(2,0) = value_type(13,14); A(2,1) = value_type(15,16); A(2,2) = value_type(17,18);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\t//expect_res = 4.375805911678970e-18; // Computed with matlab R2008a and octave 3.2.4\n\texpect_res = 1.136408e-18; // Computed with R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-18 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_complex_upper_triangular_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Upper Triangular Matrix - Column Major\");\n\n\ttypedef std::complex<double> value_type;\n\ttypedef double result_type;\n\ttypedef ublas::triangular_matrix<value_type,ublas::upper,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = value_type( 1, 2); A(0,1) = value_type( 3, 4); A(0,2) = value_type( 5, 6);\n\t                            A(1,1) = value_type( 7, 8); A(1,2) = value_type( 9,10);\n\t                                                        A(2,2) = value_type(11,12);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.059560668674847; // Computed with matlab R2008a, octave 3.2.4\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-7 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_complex_upper_triangular_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Real Upper Triangular Matrix - Row Major\");\n\n\ttypedef std::complex<double> value_type;\n\ttypedef double result_type;\n\ttypedef ublas::triangular_matrix<value_type,ublas::upper,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = value_type( 1, 2); A(0,1) = value_type( 3, 4); A(0,2) = value_type( 5, 6);\n\t                            A(1,1) = value_type( 7, 8); A(1,2) = value_type( 9,10);\n\t                                                        A(2,2) = value_type(11,12);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.059560668674847; // Computed with matlab R2008a and octave 3.2.4\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-7 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_complex_lower_triangular_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Lower Triangular Matrix - Column Major\");\n\n\ttypedef std::complex<double> value_type;\n\ttypedef double result_type;\n\ttypedef ublas::triangular_matrix<value_type,ublas::lower,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = value_type( 1, 2);\n\tA(1,0) = value_type( 3, 4); A(1,1) = value_type( 5, 6);\n\tA(2,0) = value_type( 7, 8); A(2,1) = value_type( 9,10); A(2,2) = value_type(11,12);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.059544953702088; // Computed with matlab R2008a, octave 3.2.4\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-7 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_complex_lower_triangular_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex lower Triangular Matrix - Row Major\");\n\n\ttypedef std::complex<double> value_type;\n\ttypedef double result_type;\n\ttypedef ublas::triangular_matrix<value_type,ublas::lower,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(n,n);\n\tA(0,0) = value_type( 1, 2);\n\tA(1,0) = value_type( 3, 4); A(1,1) = value_type( 5, 6);\n\tA(2,0) = value_type( 7, 8); A(2,1) = value_type( 9,10); A(2,2) = value_type(11,12);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.059544953702088; // Computed with matlab R2008a and octave 3.2.4\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-7 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_complex_banded_matrix_column_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Banded Matrix - Column Major\");\n\n\ttypedef std::complex<double> value_type;\n\ttypedef double result_type;\n\ttypedef ublas::banded_matrix<value_type,ublas::column_major> matrix_type;\n\n\tconst std::size_t n = 4;\n\n\tmatrix_type A(n,n,1,2);\n\tA(0,0) = value_type(-1.65, 2.26); A(0,1) = value_type(-2.05,-0.85); A(0,2) = value_type( 0.97,-2.84);\n\tA(1,0) = value_type( 0.00, 6.30); A(1,1) = value_type(-1.48,-1.75); A(1,2) = value_type(-3.99, 4.01); A(1,3) = value_type( 0.59,-0.48);\n\t\t\t                          A(2,1) = value_type(-0.77, 2.83); A(2,2) = value_type(-1.06, 1.94); A(2,3) = value_type( 3.33,-1.04);\n\t\t\t\t\t\t\t                                            A(3,2) = value_type( 4.48,-1.09); A(3,3) = value_type(-0.46,-1.72);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.009594414793018; // Computed with matlab R2008a, octave 3.2.4, and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-6 );\n}\n\n\nBOOST_UBLASX_TEST_DEF( norm_1_complex_banded_matrix_row_major )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: 1-Norm - Complex Banded Matrix - Row Major\");\n\n\ttypedef std::complex<double> value_type;\n\ttypedef double result_type;\n\ttypedef ublas::banded_matrix<value_type,ublas::row_major> matrix_type;\n\n\tconst std::size_t n = 4;\n\n\tmatrix_type A(n,n,1,2);\n\tA(0,0) = value_type(-1.65, 2.26); A(0,1) = value_type(-2.05,-0.85); A(0,2) = value_type( 0.97,-2.84);\n\tA(1,0) = value_type( 0.00, 6.30); A(1,1) = value_type(-1.48,-1.75); A(1,2) = value_type(-3.99, 4.01); A(1,3) = value_type( 0.59,-0.48);\n\t\t\t                          A(2,1) = value_type(-0.77, 2.83); A(2,2) = value_type(-1.06, 1.94); A(2,3) = value_type( 3.33,-1.04);\n\t\t\t\t\t\t\t                                            A(3,2) = value_type( 4.48,-1.09); A(3,3) = value_type(-0.46,-1.72);\n\n\tresult_type res;\n\tresult_type expect_res;\n\n\tres = ublasx::rcond(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"res = \" << res);\n\n\texpect_res = 0.009594414793018; // Computed with matlab R2008a, octave 3.2.4, and R 2.11.1\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect_res, 1.0e-6 );\n}\n\n\nint main()\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Suite: 'rcond' operation\");\n\n\tBOOST_UBLASX_TEST_BEGIN();\n\n\tBOOST_UBLASX_TEST_DO( norm_1_real_square_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_square_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_upper_triangular_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_upper_triangular_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_lower_triangular_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_lower_triangular_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_banded_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_banded_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_lower_symmetric_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_lower_symmetric_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_upper_symmetric_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_upper_symmetric_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_complex_square_dense_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_complex_square_dense_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_complex_upper_triangular_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_complex_upper_triangular_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_complex_lower_triangular_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_complex_lower_triangular_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_complex_banded_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_complex_banded_matrix_row_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_complex_lower_hermitian_matrix_column_major );\n\tBOOST_UBLASX_TEST_DO( norm_1_real_lower_hermitian_matrix_row_major );\n\n\tBOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "4e5f71451cd593aea5483c6954c4b53c32d84854", "size": 22546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/rcond.cpp", "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": "libs/numeric/ublasx/test/rcond.cpp", "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": "libs/numeric/ublasx/test/rcond.cpp", "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": 32.2546494993, "max_line_length": 136, "alphanum_fraction": 0.684511665, "num_tokens": 8169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5081952839298394}}
{"text": "//  Copyright (c) 2006 Xiaogang Zhang, 2015 John Maddock\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//  History:\n//  XZ wrote the original of this file as part of the Google\n//  Summer of Code 2006.  JM modified it to fit into the\n//  Boost.Math conceptual framework better, and to correctly\n//  handle the p < 0 case.\n//  Updated 2015 to use Carlson's latest methods.\n//\n\n#ifndef BOOST_MATH_ELLINT_RJ_HPP\n#define BOOST_MATH_ELLINT_RJ_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/tools/config.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/special_functions/ellint_rc.hpp>\n#include <boost/math/special_functions/ellint_rf.hpp>\n#include <boost/math/special_functions/ellint_rd.hpp>\n\n// Carlson's elliptic integral of the third kind\n// R_J(x, y, z, p) = 1.5 * \\int_{0}^{\\infty} (t+p)^{-1} [(t+x)(t+y)(t+z)]^{-1/2} dt\n// Carlson, Numerische Mathematik, vol 33, 1 (1979)\n\nnamespace boost { namespace math { namespace detail{\n\ntemplate <typename T, typename Policy>\nT ellint_rc1p_imp(T y, const Policy& pol)\n{\n   using namespace boost::math;\n   // Calculate RC(1, 1 + x)\n   BOOST_MATH_STD_USING\n\n  static const char* function = \"boost::math::ellint_rc<%1%>(%1%,%1%)\";\n\n   if(y == -1)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"Argument y must not be zero but got %1%\", y, pol);\n   }\n\n   // for 1 + y < 0, the integral is singular, return Cauchy principal value\n   T result;\n   if(y < -1)\n   {\n      result = sqrt(1 / -y) * detail::ellint_rc_imp(T(-y), T(-1 - y), pol);\n   }\n   else if(y == 0)\n   {\n      result = 1;\n   }\n   else if(y > 0)\n   {\n      result = atan(sqrt(y)) / sqrt(y);\n   }\n   else\n   {\n      if(y > -0.5)\n      {\n         T arg = sqrt(-y);\n         result = (boost::math::log1p(arg, pol) - boost::math::log1p(-arg, pol)) / (2 * sqrt(-y));\n      }\n      else\n      {\n         result = log((1 + sqrt(-y)) / sqrt(1 + y)) / sqrt(-y);\n      }\n   }\n   return result;\n}\n\ntemplate <typename T, typename Policy>\nT ellint_rj_imp(T x, T y, T z, T p, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n\n   static const char* function = \"boost::math::ellint_rj<%1%>(%1%,%1%,%1%)\";\n\n   if(x < 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"Argument x must be non-negative, but got x = %1%\", x, pol);\n   }\n   if(y < 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"Argument y must be non-negative, but got y = %1%\", y, pol);\n   }\n   if(z < 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"Argument z must be non-negative, but got z = %1%\", z, pol);\n   }\n   if(p == 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"Argument p must not be zero, but got p = %1%\", p, pol);\n   }\n   if(x + y == 0 || y + z == 0 || z + x == 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"At most one argument can be zero, \"\n         \"only possible result is %1%.\", std::numeric_limits<T>::quiet_NaN(), pol);\n   }\n\n   // for p < 0, the integral is singular, return Cauchy principal value\n   if(p < 0)\n   {\n      //\n      // We must ensure that x < y < z.\n      // Since the integral is symmetrical in x, y and z\n      // we can just permute the values:\n      //\n      if(x > y)\n         std::swap(x, y);\n      if(y > z)\n         std::swap(y, z);\n      if(x > y)\n         std::swap(x, y);\n\n      BOOST_MATH_ASSERT(x <= y);\n      BOOST_MATH_ASSERT(y <= z);\n\n      T q = -p;\n      p = (z * (x + y + q) - x * y) / (z + q);\n\n      BOOST_MATH_ASSERT(p >= 0);\n\n      T value = (p - z) * ellint_rj_imp(x, y, z, p, pol);\n      value -= 3 * ellint_rf_imp(x, y, z, pol);\n      value += 3 * sqrt((x * y * z) / (x * y + p * q)) * ellint_rc_imp(T(x * y + p * q), T(p * q), pol);\n      value /= (z + q);\n      return value;\n   }\n\n   //\n   // Special cases from http://dlmf.nist.gov/19.20#iii\n   //\n   if(x == y)\n   {\n      if(x == z)\n      {\n         if(x == p)\n         {\n            // All values equal:\n            return 1 / (x * sqrt(x));\n         }\n         else\n         {\n            // x = y = z:\n            return 3 * (ellint_rc_imp(x, p, pol) - 1 / sqrt(x)) / (x - p);\n         }\n      }\n      else\n      {\n         // x = y only, permute so y = z:\n         using std::swap;\n         swap(x, z);\n         if(y == p)\n         {\n            return ellint_rd_imp(x, y, y, pol);\n         }\n         else if((std::max)(y, p) / (std::min)(y, p) > 1.2)\n         {\n            return 3 * (ellint_rc_imp(x, y, pol) - ellint_rc_imp(x, p, pol)) / (p - y);\n         }\n         // Otherwise fall through to normal method, special case above will suffer too much cancellation...\n      }\n   }\n   if(y == z)\n   {\n      if(y == p)\n      {\n         // y = z = p:\n         return ellint_rd_imp(x, y, y, pol);\n      }\n      else if((std::max)(y, p) / (std::min)(y, p) > 1.2)\n      {\n         // y = z:\n         return 3 * (ellint_rc_imp(x, y, pol) - ellint_rc_imp(x, p, pol)) / (p - y);\n      }\n      // Otherwise fall through to normal method, special case above will suffer too much cancellation...\n   }\n   if(z == p)\n   {\n      return ellint_rd_imp(x, y, z, pol);\n   }\n\n   T xn = x;\n   T yn = y;\n   T zn = z;\n   T pn = p;\n   T An = (x + y + z + 2 * p) / 5;\n   T A0 = An;\n   T delta = (p - x) * (p - y) * (p - z);\n   T Q = pow(tools::epsilon<T>() / 5, -T(1) / 8) * (std::max)((std::max)(fabs(An - x), fabs(An - y)), (std::max)(fabs(An - z), fabs(An - p)));\n\n   unsigned n;\n   T lambda;\n   T Dn;\n   T En;\n   T rx, ry, rz, rp;\n   T fmn = 1; // 4^-n\n   T RC_sum = 0;\n\n   for(n = 0; n < policies::get_max_series_iterations<Policy>(); ++n)\n   {\n      rx = sqrt(xn);\n      ry = sqrt(yn);\n      rz = sqrt(zn);\n      rp = sqrt(pn);\n      Dn = (rp + rx) * (rp + ry) * (rp + rz);\n      En = delta / Dn;\n      En /= Dn;\n      if((En < -0.5) && (En > -1.5))\n      {\n         //\n         // Occasionally En ~ -1, we then have no means of calculating\n         // RC(1, 1+En) without terrible cancellation error, so we\n         // need to get to 1+En directly.  By substitution we have\n         //\n         // 1+E_0 = 1 + (p-x)*(p-y)*(p-z)/((sqrt(p) + sqrt(x))*(sqrt(p)+sqrt(y))*(sqrt(p)+sqrt(z)))^2\n         //       = 2*sqrt(p)*(p+sqrt(x) * (sqrt(y)+sqrt(z)) + sqrt(y)*sqrt(z)) / ((sqrt(p) + sqrt(x))*(sqrt(p) + sqrt(y)*(sqrt(p)+sqrt(z))))\n         //\n         // And since this is just an application of the duplication formula for RJ, the same\n         // expression works for 1+En if we use x,y,z,p_n etc.\n         // This branch is taken only once or twice at the start of iteration,\n         // after than En reverts to it's usual very small values.\n         //\n         T b = 2 * rp * (pn + rx * (ry + rz) + ry * rz) / Dn;\n         RC_sum += fmn / Dn * detail::ellint_rc_imp(T(1), b, pol);\n      }\n      else\n      {\n         RC_sum += fmn / Dn * ellint_rc1p_imp(En, pol);\n      }\n      lambda = rx * ry + rx * rz + ry * rz;\n\n      // From here on we move to n+1:\n      An = (An + lambda) / 4;\n      fmn /= 4;\n\n      if(fmn * Q < An)\n         break;\n\n      xn = (xn + lambda) / 4;\n      yn = (yn + lambda) / 4;\n      zn = (zn + lambda) / 4;\n      pn = (pn + lambda) / 4;\n      delta /= 64;\n   }\n\n   T X = fmn * (A0 - x) / An;\n   T Y = fmn * (A0 - y) / An;\n   T Z = fmn * (A0 - z) / An;\n   T P = (-X - Y - Z) / 2;\n   T E2 = X * Y + X * Z + Y * Z - 3 * P * P;\n   T E3 = X * Y * Z + 2 * E2 * P + 4 * P * P * P;\n   T E4 = (2 * X * Y * Z + E2 * P + 3 * P * P * P) * P;\n   T E5 = X * Y * Z * P * P;\n   T result = fmn * pow(An, T(-3) / 2) *\n      (1 - 3 * E2 / 14 + E3 / 6 + 9 * E2 * E2 / 88 - 3 * E4 / 22 - 9 * E2 * E3 / 52 + 3 * E5 / 26 - E2 * E2 * E2 / 16\n      + 3 * E3 * E3 / 40 + 3 * E2 * E4 / 20 + 45 * E2 * E2 * E3 / 272 - 9 * (E3 * E4 + E2 * E5) / 68);\n\n   result += 6 * RC_sum;\n   return result;\n}\n\n} // namespace detail\n\ntemplate <class T1, class T2, class T3, class T4, class Policy>\ninline typename tools::promote_args<T1, T2, T3, T4>::type \n   ellint_rj(T1 x, T2 y, T3 z, T4 p, const Policy& pol)\n{\n   typedef typename tools::promote_args<T1, T2, T3, T4>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(\n      detail::ellint_rj_imp(\n         static_cast<value_type>(x),\n         static_cast<value_type>(y),\n         static_cast<value_type>(z),\n         static_cast<value_type>(p),\n         pol), \"boost::math::ellint_rj<%1%>(%1%,%1%,%1%,%1%)\");\n}\n\ntemplate <class T1, class T2, class T3, class T4>\ninline typename tools::promote_args<T1, T2, T3, T4>::type \n   ellint_rj(T1 x, T2 y, T3 z, T4 p)\n{\n   return ellint_rj(x, y, z, p, policies::policy<>());\n}\n\n}} // namespaces\n\n#endif // BOOST_MATH_ELLINT_RJ_HPP\n\n", "meta": {"hexsha": "fdf1b3efc53c741a177ea7d7e74aa409b519d2cc", "size": 8870, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/special_functions/ellint_rj.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/ellint_rj.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/ellint_rj.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.2739273927, "max_line_length": 142, "alphanum_fraction": 0.5175873732, "num_tokens": 2990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5081952770187969}}
{"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 <gsl/gsl_linalg.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_eigen.h>\n\n\nnamespace votca { namespace tools {\n\nusing namespace std;\n\n\n\n\n/**\n * ublas binding to GSL  Singular Value Decomposition\n * \n * A = U S V^T\n * \n * @param A MxN matrix do decompose. Becomes an MxN orthogonal matrix U\n * @param V NxN orthogonal square matrix\n * @param S N vector of non-negative numbers forming a non-increasing sequence\n * @return succeeded or not \n */\n\nbool linalg_singular_value_decomposition(ub::matrix<double> &A, ub::matrix<double> &VT, ub::vector<double> &S )\n{\n\t\n        gsl_error_handler_t *handler = gsl_set_error_handler_off();\n\tconst size_t M = A.size1();\n        const size_t N = A.size2();\n        // gsl does not handle conversion of a symmetric_matrix \n        \n         if (M>N){\n        throw runtime_error(\"Matrix for svd has the wrong shape first dimension must be equal or larger than second.\");\n    }\n\tS.resize(N, false);\n\tVT.resize(N, N, false);\n        \n\tgsl_matrix_view A_view = gsl_matrix_view_array(&A(0,0), M, N);\n\tgsl_vector_view S_view = gsl_vector_view_array(&S(0), N);\n\tgsl_matrix_view V_view = gsl_matrix_view_array(&VT(0,0), N, N);\n\tgsl_vector * work = gsl_vector_alloc(N);\n\n        int status = gsl_linalg_SV_decomp (&A_view.matrix, &V_view.matrix, &S_view.vector, work);\n\t//gsl_eigen_symmv_sort(&E_view.vector, &V_view.matrix, GSL_EIGEN_SORT_ABS_ASC);\n\tgsl_set_error_handler(handler);\n        gsl_vector_free (work);\n        VT=ub::trans(VT);\n\treturn (status != 0);\n         \n    \n};\n\n\n}}\n", "meta": {"hexsha": "416b4c99e590f0940b907fc6c456fae0b8d5c638", "size": 2247, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libtools/linalg/gsl/svd.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/gsl/svd.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/gsl/svd.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": 29.96, "max_line_length": 119, "alphanum_fraction": 0.6991544281, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5081952770187967}}
{"text": "/* vim:set ts=3 sw=3 sts=3 et: */\n/**\n * Copyright \u00a9 2008-2013 Last.fm Limited\n *\n * This file is part of libmoost.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without restriction,\n * including without limitation the rights to use, copy, modify, merge,\n * publish, distribute, sublicense, and/or sell copies of the Software,\n * and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * @file spline_interpolation.hpp\n * @brief generate a cubic spline with natural boundary conditions\n * @author Ricky Cormier (thanks to Marcus for the suggestion)\n * @version See version.h (N/A if it doesn't exist)\n * @date 2012-04-26\n */\n\n#ifndef MOOST_ALGORITHM_SPLINE_INTERPOLATION_HPP\n#define MOOST_ALGORITHM_SPLINE_INTERPOLATION_HPP\n\n#include <cassert>\n#include <vector>\n#include <algorithm>\n\n#include <gsl/gsl_spline.h> // gnu scientific library\n\n#include <boost/noncopyable.hpp>\n\n#include \"../utils/scope_exit.hpp\"\n\n\nnamespace moost { namespace algorithm {\n\n   /**\n    * @brief Generate a spline interpolation of X and Y data points using\n    *        the GNU Scientific Library.\n    *\n    * http://www.gnu.org/software/gsl/manual/html_node/Interpolation.html\n    *\n    */\n\n   class spline_interpolation : private boost::noncopyable\n   {\n      private:\n         typedef moost::utils::scope_exit::type<\n            gsl_interp *>::call_free_function_with_val interp_t;\n\n         typedef moost::utils::scope_exit::type<\n            gsl_interp_accel *>::call_free_function_with_val accel_t;\n\n      public:\n\n\n         /**\n          * @brief create a spline interpolation object\n          *\n          * @param x : A vector of X data points\n          * @param y : A vector of Y data points\n          *\n          * @note The X vector MUST be sorted in ascending order.\n          *\n          * Given a vector of X/Y data points, this class will interpolate a\n          * value of Y for any value of X providing the value of X is given\n          * within the range of X_begin to X_end.\n          */\n\n         spline_interpolation(\n               std::vector<double> const & x,\n               std::vector<double> const & y)\n            : interp_(gsl_interp_alloc(gsl_interp_cspline, x.size()), &gsl_interp_free)\n              , accel_(gsl_interp_accel_alloc(), &gsl_interp_accel_free)\n              , x_(x)\n              , y_(y)\n\n         {\n            validate_construction(); // throws on fail\n            gsl_interp_init(interp_->get(), &x_[0], &y_[0], x_.size());\n         }\n\n\n         /**\n          * @brief Given a value of X return Y (or Z if X is out of range)\n          *\n          * @param x An X data point\n          * @param y An interpolated Y data point\n          * @param z Used as the default if X is out of range\n          *\n          * @note the value of X doesn't have to be one of the original values\n          *       of the X vector, it just has to be within the range of the\n          *       lowest to the highest X value (hence, Y is an interpolation).\n          *\n          * @return Interpolation of Y or Z if X is out of range\n          */\n\n         bool operator () (double const x, double & y, double const z = 0) const\n         {\n            bool ok =  0 == gsl_interp_eval_e(\n                  interp_->get(),\n                  &x_[0], &y_[0], x,\n                  accel_->get(), &y\n                  );\n\n            if(!ok) { y = z;}\n\n            return ok;\n         }\n\n         /**\n          * @brief Given a value of X return Y (or throw if out of range)\n          *\n          * @param x An X data point\n          *\n          * @note the value of X doesn't have to be one of the original values\n          *       of the X vector, it just has to be within the range of the\n          *       lowest to the highest X value (hence, Y is an interpolation).\n          *\n          * @return An interpolation of Y data point\n          */\n         double operator () (double const x) const\n         {\n            double y = 0.0;\n\n            if(!(*this)(x, y))\n            {\n               throw std::range_error(\"out of range\");\n            }\n\n            return y;\n         }\n\n      private:\n\n         void validate_construction() const\n         {\n            // x and y must be the same size\n            assert(x_.size() == y_.size());\n            if(x_.size() != y_.size())\n            {\n               throw std::runtime_error(\"the size of x and y must be the same\");\n            }\n\n            // x must be sorted by-asc (not my rule, gsl demands it)\n            bool const sorted = (std::adjacent_find(x_.begin(), x_.end(), std::greater_equal<double>()) == x_.end());\n            assert(sorted);\n            if(!sorted)\n            {\n               throw std::runtime_error(\"x must be sorted in assending order\");\n            }\n         }\n\n      private:\n         interp_t interp_;\n         accel_t  accel_;\n         std::vector<double> const & x_;\n         std::vector<double> const & y_;\n   };\n\n\n}}\n\n#endif // MOOST_ALGORITHM_SPLINE_INTERPOLATION_HPP\n", "meta": {"hexsha": "f08bcf03a307f85fc2bf8c09685ce4effe447df3", "size": 5789, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/moost/algorithm/spline_interpolation.hpp", "max_stars_repo_name": "lastfm/libmoost", "max_stars_repo_head_hexsha": "895db7cc5468626f520971648741488c373c5cff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2015-02-22T17:15:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T02:24:41.000Z", "max_issues_repo_path": "include/moost/algorithm/spline_interpolation.hpp", "max_issues_repo_name": "lastfm/libmoost", "max_issues_repo_head_hexsha": "895db7cc5468626f520971648741488c373c5cff", "max_issues_repo_licenses": ["MIT"], "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/moost/algorithm/spline_interpolation.hpp", "max_forks_repo_name": "lastfm/libmoost", "max_forks_repo_head_hexsha": "895db7cc5468626f520971648741488c373c5cff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T04:35:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T12:46:32.000Z", "avg_line_length": 32.1611111111, "max_line_length": 117, "alphanum_fraction": 0.5843841769, "num_tokens": 1321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5081952718453936}}
{"text": "#include \"linear_system2d.h\"\n#include <boost/numeric/itl/itl.hpp>\n\nvoid LinearSystem::Solve (std::vector<FunctionP1>& sol)\n{\n    if (!ins)\n        throw \"The system was already solved.\";\n    else {\n        delete ins;\n        ins = 0;\n\n        // Set the initial guess\n        mtl::dense_vector<double> x(unknowns);\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < nodes_num; ++j) {\n                int eq = get_index(i, j);\n                x[eq] = sol[i].values[j];\n            }\n        }\n\n        // Solve the linear system\n        itl::pc::ilu_0<mtl::compressed2D<double> > P(A);\n        itl::basic_iteration<double> iter(b, param.max_linear_sys_iterations,\n            param.linear_sys_tol);\n        bicgstab(A, x, b, P, iter);\n\n        // Set the solution\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < nodes_num; ++j) {\n                int eq = get_index(i, j);\n                sol[i].values[j] = x[eq];\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "e87ae24cd21cad0f81c26b7a102625a690fa4da3", "size": 987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "joker-fem-2d/linear_system2d.cpp", "max_stars_repo_name": "grenkin/joker-fem", "max_stars_repo_head_hexsha": "b86115f5deebd2f2da1a9417f840da57c2b5c220", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "joker-fem-2d/linear_system2d.cpp", "max_issues_repo_name": "grenkin/joker-fem", "max_issues_repo_head_hexsha": "b86115f5deebd2f2da1a9417f840da57c2b5c220", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "joker-fem-2d/linear_system2d.cpp", "max_forks_repo_name": "grenkin/joker-fem", "max_forks_repo_head_hexsha": "b86115f5deebd2f2da1a9417f840da57c2b5c220", "max_forks_repo_licenses": ["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": 77, "alphanum_fraction": 0.4812563323, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5081952563251836}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n//\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\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// Qt Example\n\n// Qt is a well-known and often used platform independent windows library\n\n// To build and run this example:\n// 1) download (from http://qt.nokia.com), configure and make QT\n// 2) if necessary, adapt Qt clause in include path (note there is a Qt property sheet)\n\n#include <sstream>\n\n#include <QtGui>\n\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n#include <boost/geometry/geometries/register/ring.hpp>\n\n\n// Adapt a QPointF such that it can be handled by Boost.Geometry\nBOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET(QPointF, double, cs::cartesian, x, y, setX, setY)\n\n// Adapt a QPolygonF as well.\n// A QPolygonF has no holes (interiors) so it is similar to a Boost.Geometry ring\nBOOST_GEOMETRY_REGISTER_RING(QPolygonF)\n\n\nint main(int argc, char *argv[])\n{\n    // This usage QApplication and QLabel is adapted from\n    // http://en.wikipedia.org/wiki/Qt_(toolkit)#Qt_hello_world\n    QApplication app(argc, argv);\n\n    // Declare a Qt polygon. The Qt Polygon can be used\n    // in Boost.Geometry, just by its oneline registration above.\n    QPolygonF polygon;\n\n    // Use Qt to add points to polygon\n    polygon\n        << QPointF(10, 20) << QPointF(20, 30)\n        << QPointF(30, 20) << QPointF(20, 10)\n        << QPointF(10, 20);\n\n    // Use Boost.Geometry e.g. to calculate area\n    std::ostringstream out;\n    out << \"Boost.Geometry area: \" << boost::geometry::area(polygon) << std::endl;\n\n    // Some functionality is defined in both Qt and Boost.Geometry\n    QPointF p(20,20);\n    out << \"Qt contains: \"\n        << (polygon.containsPoint(p, Qt::WindingFill) ? \"yes\" : \"no\")\n        << std::endl\n        << \"Boost.Geometry within: \"\n        << (boost::geometry::within(p, polygon) ? \"yes\" : \"no\")\n        << std::endl;\n    // Detail: if point is ON boundary, Qt says yes, Boost.Geometry says no.\n\n    // Qt defines an iterator\n    // (which is required for of the Boost.Geometry ring-concept)\n    // such that Boost.Geometry can use the points of this polygon\n    QPolygonF::const_iterator it;\n    for (it = polygon.begin(); it != polygon.end(); ++it)\n    {\n        // Stream Delimiter-Separated, just to show something Boost.Geometry can do\n        out << boost::geometry::dsv(*it) << std::endl;\n    }\n\n    // Stream the polygon as well\n    out << boost::geometry::dsv(polygon) << std::endl;\n\n    // Just show what we did in a label\n    QLabel label(out.str().c_str());\n    label.show();\n    return app.exec();\n}\n", "meta": {"hexsha": "16dddffd0bef3ec5b7142e765d96653e66e59ff6", "size": 2791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/geometry/example/with_external_libs/x01_qt_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/geometry/example/with_external_libs/x01_qt_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/geometry/example/with_external_libs/x01_qt_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": 34.4567901235, "max_line_length": 90, "alphanum_fraction": 0.6714439269, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.5081952545875443}}
{"text": "#include <Eigen/Dense>\n#include <fmt/core.h>\n#include <fmt/ranges.h>\n\n#include <algorithm>\n#include <array>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <string>\n#include <vector>\n\nauto parseFile(char const *file_name) {\n  auto file = std::ifstream(file_name);\n  std::string line;\n  std::vector<std::vector<int>> temp;\n  while (std::getline(file, line)) {\n    std::vector<int> t;\n    // Not sure why passing chars to stoi didn't work but what evers\n    // Probably needs null termination\n    for (auto i = 0; i < line.size(); ++i) {\n      std::string c = {line[i]};\n      if (c != \"\\n\") {\n        t.push_back(std::stoi(c));\n      }\n    }\n    temp.push_back(std::move(t));\n  }\n\n  auto rows = temp.size();\n  auto cols = temp[0].size();\n\n  Eigen::MatrixXi out(rows, cols);\n  out.setZero();\n\n  for (auto i = 0; i < rows; ++i) {\n    for (auto j = 0; j < cols; ++j) {\n      out(i, j) = temp[i][j];\n    }\n  }\n\n  return out;\n}\n\nauto findLow(auto const &m) {\n  Eigen::MatrixXi out(m.rows(), m.cols());\n  out.setConstant(-1);\n\n  for (auto r = 0; r < m.rows(); ++r) {\n    for (auto c = 0; c < m.cols(); ++c) {\n      if (r == 0 && c == 0) {\n        if (m(0, 0) < m(0, 1) && m(0, 0) < m(1, 0)) { // upper left\n          out(r, c) = m(r, c);\n        }\n      } else if (r == (m.rows() - 1) && c == (m.cols() - 1)) { // bottom right\n        if (m(r, c) < m(r - 1, c) && m(r, c) < m(r, c - 1)) {\n          out(r, c) = m(r, c);\n        }\n      } else if (r == 0 && c == (m.cols() - 1)) { // upper right\n        if (m(r, c) < m(r + 1, c) && m(r, c) < m(r, c - 1)) {\n          out(r, c) = m(r, c);\n        }\n      } else if (r == (m.rows() - 1) && c == 0) { // lower left\n        if (m(r, c) < m(r - 1, c) && m(r, c) < m(r, c + 1)) {\n          out(r, c) = m(r, c);\n        }\n      } else if (r == 0) { // top row\n        if (m(r, c) < m(r + 1, c) && m(r, c) < m(r, c + 1) &&\n            m(r, c) < m(r, c - 1)) {\n          out(r, c) = m(r, c);\n        }\n      } else if (r == (m.rows() - 1)) { // bottom row\n        if (m(r, c) < m(r - 1, c) && m(r, c) < m(r, c + 1) &&\n            m(r, c) < m(r, c - 1)) {\n          out(r, c) = m(r, c);\n        }\n      } else if (c == 0) { // Left col\n        if (m(r, c) < m(r, c + 1) && m(r, c) < m(r + 1, c) &&\n            m(r, c) < m(r - 1, c)) {\n          out(r, c) = m(r, c);\n        }\n      } else if (c == (m.cols() - 1)) { // right col\n        if (m(r, c) < m(r, c - 1) && m(r, c) < m(r + 1, c) &&\n            m(r, c) < m(r - 1, c)) {\n          out(r, c) = m(r, c);\n        }\n      } else { // Whew in the middle\n        if (m(r, c) < m(r, c + 1) && m(r, c) < m(r, c - 1) &&\n            m(r, c) < m(r + 1, c) && m(r, c) < m(r - 1, c)) {\n          out(r, c) = m(r, c);\n        }\n      }\n    }\n  }\n\n  return out;\n}\n\nint discoverBasin(Eigen::MatrixXi &m, int i, int j) {\n  if (i < 0 || i >= m.rows() || j < 0 || j >= m.cols() || m(i, j) == 9) {\n    return 0; // Can't be here\n  }\n\n  if (m(i, j) == -1) { // Already been here\n    return 0;\n  }\n\n  m(i,j) = -1; // Been here\n\n  // The + 1 is so that we get credit for this node\n  return discoverBasin(m, i + 1, j) + discoverBasin(m, i - 1, j) +\n         discoverBasin(m, i, j + 1) + discoverBasin(m, i, j - 1) + 1;\n}\n\nint main(int _, char **argv) {\n  auto M = parseFile(argv[1]);\n  if (M.rows() < 11 && M.cols() < 11) {\n    std::cout << \"M:\\n\" << M << \"\\n\\n\";\n  }\n  auto lows = findLow(M);\n  if (M.rows() < 11 && M.cols() < 11) {\n    std::cout << \"L:\\n\" << lows << \"\\n\\n\";\n  }\n  auto sum = 0;\n  for (auto i = 0; i < lows.rows(); ++i) {\n    for (auto j = 0; j < lows.cols(); ++j) {\n      if (lows(i, j) != -1) {\n        sum += lows(i, j) + 1;\n      }\n    }\n  }\n\n  fmt::print(\"Sum of low points: {}\\n\", sum);\n\n  // for part two we need to do a search\n  Eigen::MatrixXi D = M;\n  std::vector<int> basins;\n  for(auto i = 0; i < D.rows(); ++i){\n    for(auto j = 0; j < D.cols(); ++j){\n      if(D(i,j) != 9 && D(i,j) != -1){\n        basins.push_back(discoverBasin(D, i, j));\n      }\n    }\n  }\n\n  std::sort(basins.begin(), basins.end(), std::greater<>{});\n  fmt::print(\"Basins: {}\\n\", fmt::join(basins, \",\"));\n  fmt::print(\"Prod of top 3: {}\\n\", basins[0] * basins[1] * basins[2]);\n}\n", "meta": {"hexsha": "50db117551837362265abf2b737d87ed30582639", "size": 4184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/day9/day9.cpp", "max_stars_repo_name": "calewis/advent-of-code21", "max_stars_repo_head_hexsha": "a4efc4c551122c1a48f334c7ead237919586de35", "max_stars_repo_licenses": ["MIT"], "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/day9/day9.cpp", "max_issues_repo_name": "calewis/advent-of-code21", "max_issues_repo_head_hexsha": "a4efc4c551122c1a48f334c7ead237919586de35", "max_issues_repo_licenses": ["MIT"], "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/day9/day9.cpp", "max_forks_repo_name": "calewis/advent-of-code21", "max_forks_repo_head_hexsha": "a4efc4c551122c1a48f334c7ead237919586de35", "max_forks_repo_licenses": ["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.7086092715, "max_line_length": 78, "alphanum_fraction": 0.4247131931, "num_tokens": 1598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597974, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5081834817786571}}
{"text": "/**\n * @file subset_backtrack_test.cpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2014-08-14\n */\n\n#include \"paal/utils/algorithms/subset_backtrack.hpp\"\n#include \"paal/utils/functors.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/range/algorithm_ext/iota.hpp>\n#include <boost/range/numeric.hpp>\n#include <boost/range/algorithm/remove.hpp>\n\n#include <vector>\n#include <random>\n\nBOOST_AUTO_TEST_CASE(subset_backtrack) {\n    const int N = 10, WANT_SUM = (1 << (N - 1)) * (N * (N + 1) / 2);\n    std::vector<int> numbers(N);\n    boost::iota(numbers, 1);\n    int sum = 0, selected_sum = 0;\n    auto backtrack = paal::make_subset_backtrack(numbers);\n    backtrack.solve([&](int k) {\n                        selected_sum += k;\n                        sum += selected_sum;\n                        return true;\n                    },\n                    [&](int k) { selected_sum -= k; });\n    BOOST_CHECK_EQUAL(selected_sum, 0);\n    BOOST_CHECK_EQUAL(sum, WANT_SUM);\n}\n\nBOOST_AUTO_TEST_CASE(subset_backtrack_empty_set_solved_two_times){\n    auto backtrack=paal::make_subset_backtrack(std::vector<int>{});\n    auto f=[](int k){BOOST_CHECK(false);return true;};\n    backtrack.solve(f,f);\n    backtrack.solve(f,f);\n}\n\nBOOST_AUTO_TEST_CASE(subset_backtrack_on_element_set_solved_two_times){\n    auto backtrack=paal::make_subset_backtrack(std::vector<int>{0});\n    auto t=paal::utils::always_true{};\n    backtrack.solve(t,t);\n    backtrack.solve(t,t);\n}\n\nBOOST_AUTO_TEST_CASE(subset_backtrack_max_one_even) {\n    const int N = 20;\n    assert(N % 4 == 0);\n    const int WANT_SUM =\n        (1 << (N / 2))         // number of sets of odd numbers\n        * (N / 2 + 1)          // one or 0 even numbers\n        * (N * N / 8 + N / 2); // average sum of odd and even numbers\n    std::vector<int> numbers(N);\n    boost::iota(numbers, 1);\n    int sum = 0, even = 0, selected_sum = 0;\n    auto backtrack = paal::make_subset_backtrack(numbers);\n    auto is_even = [](int k) { return k % 2 == 0; };\n    backtrack.solve([&](int k) {\n                        if (even + is_even(k) > 1) return false;\n                        even += is_even(k);\n                        selected_sum += k;\n                        sum += selected_sum;\n                        return true;\n                    },\n                    [&](int k) {\n                        even -= is_even(k);\n                        selected_sum -= k;\n                    },\n                    [&](boost::iterator_range<std::vector<int>::iterator>\n                            remaining_nums) {\n                        if (even == 1) return boost::remove(remaining_nums, 8);\n                        std::shuffle(remaining_nums.begin(), remaining_nums.end(),\n                                    std::default_random_engine());\n                        return remaining_nums.end();\n                    });\n    BOOST_CHECK_EQUAL(even, 0);\n    BOOST_CHECK_EQUAL(selected_sum, 0);\n    BOOST_CHECK_EQUAL(sum, WANT_SUM);\n}\n", "meta": {"hexsha": "2e927e4aeb9762ddcb681cab96493f294e46b62c", "size": 2976, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/utils/subset_backtrack_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/utils/subset_backtrack_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/utils/subset_backtrack_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": 35.4285714286, "max_line_length": 82, "alphanum_fraction": 0.5493951613, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5081834719575359}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.\n// Copyright (c) 2009-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2015-2021.\n// Modifications copyright (c) 2015-2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, 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#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_CENTROID_WEIGHTED_LENGTH_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_CENTROID_WEIGHTED_LENGTH_HPP\n\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <boost/geometry/arithmetic/arithmetic.hpp>\n\n// Helper geometry\n#include <boost/geometry/geometries/point.hpp>\n\n#include <boost/geometry/strategies/cartesian/distance_pythagoras.hpp>\n#include <boost/geometry/strategies/centroid.hpp>\n\n#include <boost/geometry/util/algorithm.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace centroid\n{\n\ntemplate\n<\n    typename Ignored1 = void,\n    typename Ignored2 = void,\n    typename CalculationType = void\n>\nclass weighted_length\n{\nprivate :\n    typedef geometry::strategy::distance::pythagoras<CalculationType> pythagoras_strategy;\n\n    template <typename GeometryPoint, typename ResultPoint>\n    struct calculation_type\n    {\n        // Below the distance between two GeometryPoints is calculated.\n        // ResultPoint is taken into account by passing them together here.\n        typedef typename pythagoras_strategy::template calculation_type\n            <\n                GeometryPoint, ResultPoint\n            >::type type;\n    };\n\n    template <typename GeometryPoint, typename ResultPoint>\n    class sums\n    {\n        friend class weighted_length;\n        template <typename, typename> friend struct set_sum_div_length;\n\n        typedef typename calculation_type<GeometryPoint, ResultPoint>::type calc_type;\n        typedef typename geometry::model::point\n            <\n                calc_type,\n                geometry::dimension<ResultPoint>::value,\n                cs::cartesian\n            > work_point;\n\n        calc_type length;\n        work_point average_sum;\n\n    public:\n        inline sums()\n            : length(calc_type())\n        {\n            geometry::assign_zero(average_sum);\n        }\n    };\n\npublic :\n    template <typename GeometryPoint, typename ResultPoint>\n    struct state_type\n    {\n        typedef sums<GeometryPoint, ResultPoint> type;\n    };\n\n    template <typename GeometryPoint, typename ResultPoint>\n    static inline void apply(GeometryPoint const& p1, GeometryPoint const& p2,\n                             sums<GeometryPoint, ResultPoint>& state)\n    {\n        typedef typename calculation_type<GeometryPoint, ResultPoint>::type distance_type;\n\n        distance_type const d = pythagoras_strategy::apply(p1, p2);\n        state.length += d;\n\n        distance_type const d_half = d / distance_type(2);\n        geometry::detail::for_each_dimension<ResultPoint>([&](auto dimension)\n        {\n            distance_type const coord1 = get<dimension>(p1);\n            distance_type const coord2 = get<dimension>(p2);\n            distance_type const wm = (coord1 + coord2) * d_half; // weighted median\n            set<dimension>(state.average_sum, get<dimension>(state.average_sum) + wm);\n        });\n    }\n\n    template <typename GeometryPoint, typename ResultPoint>\n    static inline bool result(sums<GeometryPoint, ResultPoint> const& state,\n                              ResultPoint& centroid)\n    {\n        typedef typename calculation_type<GeometryPoint, ResultPoint>::type distance_type;\n\n        distance_type const zero = distance_type();\n        if (! geometry::math::equals(state.length, zero)\n            && boost::math::isfinite(state.length)) // Prevent NaN centroid coordinates\n        {\n            // NOTE: above distance_type is checked, not the centroid coordinate_type\n            // which means that the centroid can still be filled with INF\n            // if e.g. distance_type is double and centroid contains floats\n            geometry::detail::for_each_dimension<ResultPoint>([&](auto dimension)\n            {\n                typedef typename geometry::coordinate_type<ResultPoint>::type coordinate_type;\n                geometry::set<dimension>(\n                    centroid,\n                    boost::numeric_cast<coordinate_type>(\n                        geometry::get<dimension>(state.average_sum) / state.length\n                    )\n                );\n            });\n            return true;\n        }\n\n        return false;\n    }\n};\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\nnamespace services\n{\n\n\n// Register this strategy for linear geometries, in all dimensions\n\ntemplate <std::size_t N, typename Point, typename Geometry>\nstruct default_strategy\n<\n    cartesian_tag,\n    linear_tag,\n    N,\n    Point,\n    Geometry\n>\n{\n    typedef weighted_length\n        <\n            Point,\n            typename point_type<Geometry>::type\n        > type;\n};\n\n\n} // namespace services\n\n\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::centroid\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_CENTROID_WEIGHTED_LENGTH_HPP\n", "meta": {"hexsha": "c536d5bc2410ae079470c82cb20f3c4297cbe2b9", "size": 5638, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/geometry/strategies/cartesian/centroid_weighted_length.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/geometry/strategies/cartesian/centroid_weighted_length.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/geometry/strategies/cartesian/centroid_weighted_length.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "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.6413043478, "max_line_length": 94, "alphanum_fraction": 0.6739978716, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5081458792464902}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2016 Oracle and/or its affiliates.\n\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#ifndef BOOST_GEOMETRY_FORMULAS_SJOBERG_INTERSECTION_HPP\n#define BOOST_GEOMETRY_FORMULAS_SJOBERG_INTERSECTION_HPP\n\n\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/geometry/core/radius.hpp>\n#include <boost/geometry/core/srs.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/formulas/flattening.hpp>\n#include <boost/geometry/formulas/spherical.hpp>\n\n\nnamespace boost { namespace geometry { namespace formula\n{\n\n/*!\n\\brief The intersection of two great circles as proposed by Sjoberg.\n\\see See\n    - [Sjoberg02] Lars E. Sjoberg, Intersections on the sphere and ellipsoid, 2002\n      http://link.springer.com/article/10.1007/s00190-001-0230-9\n*/\ntemplate <typename CT>\nstruct sjoberg_intersection_spherical_02\n{\n    // TODO: if it will be used as standalone formula\n    //       support segments on equator and endpoints on poles\n\n    static inline bool apply(CT const& lon1, CT const& lat1, CT const& lon_a2, CT const& lat_a2,\n                             CT const& lon2, CT const& lat2, CT const& lon_b2, CT const& lat_b2,\n                             CT & lon, CT & lat)\n    {\n        CT tan_lat = 0;\n        bool res = apply_alt(lon1, lat1, lon_a2, lat_a2,\n                             lon2, lat2, lon_b2, lat_b2,\n                             lon, tan_lat);\n\n        if (res)\n        {\n            lat = atan(tan_lat);\n        }\n\n        return res;\n    }\n\n    static inline bool apply_alt(CT const& lon1, CT const& lat1, CT const& lon_a2, CT const& lat_a2,\n                                 CT const& lon2, CT const& lat2, CT const& lon_b2, CT const& lat_b2,\n                                 CT & lon, CT & tan_lat)\n    {\n        CT const cos_lon1 = cos(lon1);\n        CT const sin_lon1 = sin(lon1);\n        CT const cos_lon2 = cos(lon2);\n        CT const sin_lon2 = sin(lon2);\n        CT const sin_lat1 = sin(lat1);\n        CT const sin_lat2 = sin(lat2);\n        CT const cos_lat1 = cos(lat1);\n        CT const cos_lat2 = cos(lat2);\n\n        CT const tan_lat_a2 = tan(lat_a2);\n        CT const tan_lat_b2 = tan(lat_b2);\n\n        return apply(lon1, lon_a2, lon2, lon_b2,\n                     sin_lon1, cos_lon1, sin_lat1, cos_lat1,\n                     sin_lon2, cos_lon2, sin_lat2, cos_lat2,\n                     tan_lat_a2, tan_lat_b2,\n                     lon, tan_lat);\n    }\n\nprivate:\n    static inline bool apply(CT const& lon1, CT const& lon_a2, CT const& lon2, CT const& lon_b2,\n                             CT const& sin_lon1, CT const& cos_lon1, CT const& sin_lat1, CT const& cos_lat1,\n                             CT const& sin_lon2, CT const& cos_lon2, CT const& sin_lat2, CT const& cos_lat2,\n                             CT const& tan_lat_a2, CT const& tan_lat_b2,\n                             CT & lon, CT & tan_lat)\n    {\n        // NOTE:\n        // cos_lat_ = 0 <=> segment on equator\n        // tan_alpha_ = 0 <=> segment vertical\n\n        CT const tan_lat1 = sin_lat1 / cos_lat1; //tan(lat1);\n        CT const tan_lat2 = sin_lat2 / cos_lat2; //tan(lat2);\n\n        CT const dlon1 = lon_a2 - lon1;\n        CT const sin_dlon1 = sin(dlon1);\n        CT const dlon2 = lon_b2 - lon2;\n        CT const sin_dlon2 = sin(dlon2);\n\n        CT const c0 = 0;\n        bool const is_vertical1 = math::equals(sin_dlon1, c0);\n        bool const is_vertical2 = math::equals(sin_dlon2, c0);\n\n        CT tan_alpha1 = 0;\n        CT tan_alpha2 = 0;\n\n        if (is_vertical1 && is_vertical2)\n        {\n            // circles intersect at one of the poles or are collinear\n            return false;\n        }\n        else if (is_vertical1)\n        {\n            CT const cos_dlon2 = cos(dlon2);\n            CT const tan_alpha2_x = cos_lat2 * tan_lat_b2 - sin_lat2 * cos_dlon2;\n            tan_alpha2 = sin_dlon2 / tan_alpha2_x;\n\n            lon = lon1;\n        }\n        else if (is_vertical2)\n        {\n            CT const cos_dlon1 = cos(dlon1);\n            CT const tan_alpha1_x = cos_lat1 * tan_lat_a2 - sin_lat1 * cos_dlon1;\n            tan_alpha1 = sin_dlon1 / tan_alpha1_x;\n\n            lon = lon2;\n        }\n        else\n        {\n            CT const cos_dlon1 = cos(dlon1);\n            CT const cos_dlon2 = cos(dlon2);\n\n            CT const tan_alpha1_x = cos_lat1 * tan_lat_a2 - sin_lat1 * cos_dlon1;\n            CT const tan_alpha2_x = cos_lat2 * tan_lat_b2 - sin_lat2 * cos_dlon2;\n            tan_alpha1 = sin_dlon1 / tan_alpha1_x;\n            tan_alpha2 = sin_dlon2 / tan_alpha2_x;\n\n            CT const T1 = tan_alpha1 * cos_lat1;\n            CT const T2 = tan_alpha2 * cos_lat2;\n            CT const T1T2 = T1*T2;\n            CT const tan_lon_y = T1 * sin_lon2 - T2 * sin_lon1 + T1T2 * (tan_lat1 * cos_lon1 - tan_lat2 * cos_lon2);\n            CT const tan_lon_x = T1 * cos_lon2 - T2 * cos_lon1 - T1T2 * (tan_lat1 * sin_lon1 - tan_lat2 * sin_lon2);\n\n            lon = atan2(tan_lon_y, tan_lon_x);\n        }\n\n        // choose closer result\n        CT const pi = math::pi<CT>();\n        CT const lon_2 = lon > c0 ? lon - pi : lon + pi;\n        CT const lon_dist1 = (std::max)((std::min)(math::longitude_difference<radian>(lon1, lon),\n                                                   math::longitude_difference<radian>(lon_a2, lon)),\n                                        (std::min)(math::longitude_difference<radian>(lon2, lon),\n                                                   math::longitude_difference<radian>(lon_b2, lon)));\n        CT const lon_dist2 = (std::max)((std::min)(math::longitude_difference<radian>(lon1, lon_2),\n                                                   math::longitude_difference<radian>(lon_a2, lon_2)),\n                                        (std::min)(math::longitude_difference<radian>(lon2, lon_2),\n                                                   math::longitude_difference<radian>(lon_b2, lon_2)));\n        if (lon_dist2 < lon_dist1)\n        {\n            lon = lon_2;\n        }\n\n        CT const sin_lon = sin(lon);\n        CT const cos_lon = cos(lon);\n\n        if (math::abs(tan_alpha1) >= math::abs(tan_alpha2)) // pick less vertical segment\n        {\n            CT const sin_dlon_1 = sin_lon * cos_lon1 - cos_lon * sin_lon1;\n            CT const cos_dlon_1 = cos_lon * cos_lon1 + sin_lon * sin_lon1;\n            CT const lat_y_1 = sin_dlon_1 + tan_alpha1 * sin_lat1 * cos_dlon_1;\n            CT const lat_x_1 = tan_alpha1 * cos_lat1;\n            tan_lat = lat_y_1 / lat_x_1;\n        }\n        else\n        {\n            CT const sin_dlon_2 = sin_lon * cos_lon2 - cos_lon * sin_lon2;\n            CT const cos_dlon_2 = cos_lon * cos_lon2 + sin_lon * sin_lon2;\n            CT const lat_y_2 = sin_dlon_2 + tan_alpha2 * sin_lat2 * cos_dlon_2;\n            CT const lat_x_2 = tan_alpha2 * cos_lat2;\n            tan_lat = lat_y_2 / lat_x_2;\n        }\n\n        return true;\n    }\n};\n\n\n/*! Approximation of dLambda_j [Sjoberg07], expanded into taylor series in e^2\n    Maxima script:\n    dLI_j(c_j, sinB_j, sinB) := integrate(1 / (sqrt(1 - c_j ^ 2 - x ^ 2)*(1 + sqrt(1 - e2*(1 - x ^ 2)))), x, sinB_j, sinB);\n    dL_j(c_j, B_j, B) := -e2 * c_j * dLI_j(c_j, B_j, B);\n    S: taylor(dLI_j(c_j, sinB_j, sinB), e2, 0, 3);\n    assume(c_j < 1);\n    assume(c_j > 0);\n    L1: factor(integrate(sqrt(-x ^ 2 - c_j ^ 2 + 1) / (x ^ 2 + c_j ^ 2 - 1), x));\n    L2: factor(integrate(((x ^ 2 - 1)*sqrt(-x ^ 2 - c_j ^ 2 + 1)) / (x ^ 2 + c_j ^ 2 - 1), x));\n    L3: factor(integrate(((x ^ 4 - 2 * x ^ 2 + 1)*sqrt(-x ^ 2 - c_j ^ 2 + 1)) / (x ^ 2 + c_j ^ 2 - 1), x));\n    L4: factor(integrate(((x ^ 6 - 3 * x ^ 4 + 3 * x ^ 2 - 1)*sqrt(-x ^ 2 - c_j ^ 2 + 1)) / (x ^ 2 + c_j ^ 2 - 1), x));\n\n\\see See\n    - [Sjoberg07] Lars E. Sjoberg, Geodetic intersection on the ellipsoid, 2007\n      http://link.springer.com/article/10.1007/s00190-007-0204-7\n*/\ntemplate <unsigned int Order, typename CT>\ninline CT sjoberg_d_lambda_e_sqr(CT const& sin_betaj, CT const& sin_beta,\n                                 CT const& Cj, CT const& sqrt_1_Cj_sqr,\n                                 CT const& e_sqr)\n{\n    using math::detail::bounded;\n\n    if (Order == 0)\n    {\n        return 0;\n    }\n\n    CT const c1 = 1;\n    CT const c2 = 2;\n\n    CT const asin_B = asin(bounded(sin_beta / sqrt_1_Cj_sqr, -c1, c1));\n    CT const asin_Bj = asin(sin_betaj / sqrt_1_Cj_sqr);\n    CT const L0 = (asin_B - asin_Bj) / c2;\n\n    if (Order == 1)\n    {\n        return -Cj * e_sqr * L0;\n    }\n\n    CT const c0 = 0;\n    CT const c16 = 16;\n\n    CT const X = sin_beta;\n    CT const Xj = sin_betaj;\n    CT const X_sqr = math::sqr(X);\n    CT const Xj_sqr = math::sqr(Xj);\n    CT const Cj_sqr = math::sqr(Cj);\n    CT const Cj_sqr_plus_one = Cj_sqr + c1;\n    CT const one_minus_Cj_sqr = c1 - Cj_sqr;\n    CT const sqrt_Y = math::sqrt(bounded(-X_sqr + one_minus_Cj_sqr, c0));\n    CT const sqrt_Yj = math::sqrt(-Xj_sqr + one_minus_Cj_sqr);\n    CT const L1 = (Cj_sqr_plus_one * (asin_B - asin_Bj) + X * sqrt_Y - Xj * sqrt_Yj) / c16;\n\n    if (Order == 2)\n    {\n        return -Cj * e_sqr * (L0 + e_sqr * L1);\n    }\n\n    CT const c3 = 3;\n    CT const c5 = 5;\n    CT const c128 = 128;\n\n    CT const E = Cj_sqr * (c3 * Cj_sqr + c2) + c3;\n    CT const F = X * (-c2 * X_sqr + c3 * Cj_sqr + c5);\n    CT const Fj = Xj * (-c2 * Xj_sqr + c3 * Cj_sqr + c5);\n    CT const L2 = (E * (asin_B - asin_Bj) + F * sqrt_Y - Fj * sqrt_Yj) / c128;\n\n    if (Order == 3)\n    {\n        return -Cj * e_sqr * (L0 + e_sqr * (L1 + e_sqr * L2));\n    }\n\n    CT const c8 = 8;\n    CT const c9 = 9;\n    CT const c10 = 10;\n    CT const c15 = 15;\n    CT const c24 = 24;\n    CT const c26 = 26;\n    CT const c33 = 33;\n    CT const c6144 = 6144;\n\n    CT const G = Cj_sqr * (Cj_sqr * (Cj_sqr * c15 + c9) + c9) + c15;\n    CT const H = -c10 * Cj_sqr - c26;\n    CT const I = Cj_sqr * (Cj_sqr * c15 + c24) + c33;\n    CT const J = X_sqr * (X * (c8 * X_sqr + H)) + X * I;\n    CT const Jj = Xj_sqr * (Xj * (c8 * Xj_sqr + H)) + Xj * I;\n    CT const L3 = (G * (asin_B - asin_Bj) + J * sqrt_Y - Jj * sqrt_Yj) / c6144;\n\n    // Order 4 and higher\n    return -Cj * e_sqr * (L0 + e_sqr * (L1 + e_sqr * (L2 + e_sqr * L3)));\n}\n\n/*!\n\\brief The representation of geodesic as proposed by Sjoberg.\n\\see See\n    - [Sjoberg07] Lars E. Sjoberg, Geodetic intersection on the ellipsoid, 2007\n      http://link.springer.com/article/10.1007/s00190-007-0204-7\n    - [Sjoberg12] Lars E. Sjoberg, Solutions to the ellipsoidal Clairaut constant\n      and the inverse geodetic problem by numerical integration, 2012\n      https://www.degruyter.com/view/j/jogs.2012.2.issue-3/v10156-011-0037-4/v10156-011-0037-4.xml\n*/\ntemplate <typename CT, unsigned int Order>\nclass sjoberg_geodesic\n{\n    sjoberg_geodesic() {}\n\n    static int sign_C(CT const& alphaj)\n    {\n        CT const c0 = 0;\n        CT const c2 = 2;\n        CT const pi = math::pi<CT>();\n        CT const pi_half = pi / c2;\n\n        return (pi_half < alphaj && alphaj < pi) || (-pi_half < alphaj && alphaj < c0) ? -1 : 1;\n    }\n\npublic:\n    sjoberg_geodesic(CT const& lon, CT const& lat, CT const& alpha, CT const& f)\n        : lonj(lon)\n        , latj(lat)\n        , alphaj(alpha)\n    {\n        CT const c0 = 0;\n        CT const c1 = 1;\n        CT const c2 = 2;\n        //CT const pi = math::pi<CT>();\n        //CT const pi_half = pi / c2;\n\n        one_minus_f = c1 - f;\n        e_sqr = f * (c2 - f);\n\n        tan_latj = tan(lat);\n        tan_betaj = one_minus_f * tan_latj;\n        betaj = atan(tan_betaj);\n        sin_betaj = sin(betaj);\n\n        cos_betaj = cos(betaj);\n        sin_alphaj = sin(alphaj);\n        // Clairaut constant (lower-case in the paper)\n        Cj = sign_C(alphaj) * cos_betaj * sin_alphaj;\n        Cj_sqr = math::sqr(Cj);\n        sqrt_1_Cj_sqr = math::sqrt(c1 - Cj_sqr);\n\n        sign_lon_diff = alphaj >= 0 ? 1 : -1; // || alphaj == -pi ?\n        //sign_lon_diff = 1;\n\n        is_on_equator = math::equals(sqrt_1_Cj_sqr, c0);\n        is_Cj_zero = math::equals(Cj, c0);\n\n        t0j = c0;\n        asin_tj_t0j = c0;\n\n        if (! is_Cj_zero)\n        {\n            t0j = sqrt_1_Cj_sqr / Cj;\n        }\n\n        if (! is_on_equator)\n        {\n            //asin_tj_t0j = asin(tan_betaj / t0j);\n            asin_tj_t0j = asin(tan_betaj * Cj / sqrt_1_Cj_sqr);\n        }\n    }\n\n    struct vertex_data\n    {\n        //CT beta0j;\n        CT sin_beta0j;\n        CT dL0j;\n        CT lon0j;\n    };\n\n    vertex_data get_vertex_data() const\n    {\n        CT const c2 = 2;\n        CT const pi = math::pi<CT>();\n        CT const pi_half = pi / c2;\n\n        vertex_data res;\n\n        if (! is_Cj_zero)\n        {\n            //res.beta0j = atan(t0j);\n            //res.sin_beta0j = sin(res.beta0j);\n            res.sin_beta0j = math::sign(t0j) * sqrt_1_Cj_sqr;\n            res.dL0j = d_lambda(res.sin_beta0j);\n            res.lon0j = lonj + sign_lon_diff * (pi_half - asin_tj_t0j + res.dL0j);\n        }\n        else\n        {\n            //res.beta0j = pi_half;\n            //res.sin_beta0j = betaj >= 0 ? 1 : -1;\n            res.sin_beta0j = 1;\n            res.dL0j = 0;\n            res.lon0j = lonj;\n        }\n\n        return res;\n    }\n\n    bool is_sin_beta_ok(CT const& sin_beta) const\n    {\n        CT const c1 = 1;\n        return math::abs(sin_beta / sqrt_1_Cj_sqr) <= c1;\n    }\n\n    bool k_diff(CT const& sin_beta,\n                CT & delta_k) const\n    {\n        if (is_Cj_zero)\n        {\n            delta_k = 0;\n            return true;\n        }\n\n        // beta out of bounds and not close\n        if (! (is_sin_beta_ok(sin_beta)\n                || math::equals(math::abs(sin_beta), sqrt_1_Cj_sqr)) )\n        {\n            return false;\n        }\n\n        // NOTE: beta may be slightly out of bounds here but d_lambda handles that\n        CT const dLj = d_lambda(sin_beta);\n        delta_k = sign_lon_diff * (/*asin_t_t0j*/ - asin_tj_t0j + dLj);\n\n        return true;\n    }\n\n    bool lon_diff(CT const& sin_beta, CT const& t,\n                  CT & delta_lon) const\n    {\n        using math::detail::bounded;\n        CT const c1 = 1;\n\n        if (is_Cj_zero)\n        {\n            delta_lon = 0;\n            return true;\n        }\n\n        CT delta_k = 0;\n        if (! k_diff(sin_beta, delta_k))\n        {\n            return false;\n        }\n\n        CT const t_t0j = t / t0j;\n        // NOTE: t may be slightly out of bounds here\n        CT const asin_t_t0j = asin(bounded(t_t0j, -c1, c1));\n        delta_lon = sign_lon_diff * asin_t_t0j + delta_k;\n\n        return true;\n    }\n\n    bool k_diffs(CT const& sin_beta, vertex_data const& vd,\n                 CT & delta_k_before, CT & delta_k_behind,\n                 bool check_sin_beta = true) const\n    {\n        CT const pi = math::pi<CT>();\n\n        if (is_Cj_zero)\n        {\n            delta_k_before = 0;\n            delta_k_behind = sign_lon_diff * pi;\n            return true;\n        }\n\n        // beta out of bounds and not close\n        if (check_sin_beta\n            && ! (is_sin_beta_ok(sin_beta)\n                    || math::equals(math::abs(sin_beta), sqrt_1_Cj_sqr)) )\n        {\n            return false;\n        }\n\n        // NOTE: beta may be slightly out of bounds here but d_lambda handles that\n        CT const dLj = d_lambda(sin_beta);\n        delta_k_before = sign_lon_diff * (/*asin_t_t0j*/ - asin_tj_t0j + dLj);\n\n        // This version require no additional dLj calculation\n        delta_k_behind = sign_lon_diff * (pi /*- asin_t_t0j*/ - asin_tj_t0j + vd.dL0j + (vd.dL0j - dLj));\n\n        // [Sjoberg12]\n        //CT const dL101 = d_lambda(sin_betaj, vd.sin_beta0j);\n        // WARNING: the following call might not work if beta was OoB because only the second argument is bounded\n        //CT const dL_01 = d_lambda(sin_beta, vd.sin_beta0j);\n        //delta_k_behind = sign_lon_diff * (pi /*- asin_t_t0j*/ - asin_tj_t0j + dL101 + dL_01);\n\n        return true;\n    }\n\n    bool lon_diffs(CT const& sin_beta, CT const& t, vertex_data const& vd,\n                   CT & delta_lon_before, CT & delta_lon_behind) const\n    {\n        using math::detail::bounded;\n        CT const c1 = 1;\n        CT const pi = math::pi<CT>();\n\n        if (is_Cj_zero)\n        {\n            delta_lon_before = 0;\n            delta_lon_behind = sign_lon_diff * pi;\n            return true;\n        }\n\n        CT delta_k_before = 0, delta_k_behind = 0;\n        if (! k_diffs(sin_beta, vd, delta_k_before, delta_k_behind))\n        {\n            return false;\n        }\n\n        CT const t_t0j = t / t0j;\n        // NOTE: t may be slightly out of bounds here\n        CT const asin_t_t0j = asin(bounded(t_t0j, -c1, c1));\n        CT const sign_asin_t_t0j = sign_lon_diff * asin_t_t0j;\n        delta_lon_before = sign_asin_t_t0j + delta_k_before;\n        delta_lon_behind = -sign_asin_t_t0j + delta_k_behind;\n\n        return true;\n    }\n\n    bool lon(CT const& sin_beta, CT const& t, vertex_data const& vd,\n             CT & lon_before, CT & lon_behind) const\n    {\n        using math::detail::bounded;\n        CT const c1 = 1;\n        CT const pi = math::pi<CT>();\n\n        if (is_Cj_zero)\n        {\n            lon_before = lonj;\n            lon_behind = lonj + sign_lon_diff * pi;\n            return true;\n        }\n\n        if (! (is_sin_beta_ok(sin_beta)\n                || math::equals(math::abs(sin_beta), sqrt_1_Cj_sqr)) )\n        {\n            return false;\n        }\n\n        CT const t_t0j = t / t0j;\n        CT const asin_t_t0j = asin(bounded(t_t0j, -c1, c1));\n        CT const dLj = d_lambda(sin_beta);\n        lon_before = lonj + sign_lon_diff * (asin_t_t0j - asin_tj_t0j + dLj);\n        lon_behind = vd.lon0j + (vd.lon0j - lon_before);\n\n        return true;\n    }\n\n\n    CT lon(CT const& delta_lon) const\n    {\n        return lonj + delta_lon;\n    }\n\n    CT lat(CT const& t) const\n    {\n        // t = tan(beta) = (1-f)tan(lat)\n        return atan(t / one_minus_f);\n    }\n\n    void vertex(CT & lon, CT & lat) const\n    {\n        lon = get_vertex_data().lon0j;\n        if (! is_Cj_zero)\n        {\n            lat = sjoberg_geodesic::lat(t0j);\n        }\n        else\n        {\n            CT const c2 = 2;\n            lat = math::pi<CT>() / c2;\n        }\n    }\n\n    CT lon_of_equator_intersection() const\n    {\n        CT const c0 = 0;\n        CT const dLj = d_lambda(c0);\n        CT const asin_tj_t0j = asin(Cj * tan_betaj / sqrt_1_Cj_sqr);\n        return lonj - asin_tj_t0j + dLj;\n    }\n\n    CT d_lambda(CT const& sin_beta) const\n    {\n        return sjoberg_d_lambda_e_sqr<Order>(sin_betaj, sin_beta, Cj, sqrt_1_Cj_sqr, e_sqr);\n    }\n\n    // [Sjoberg12]\n    /*CT d_lambda(CT const& sin_beta1, CT const& sin_beta2) const\n    {\n        return sjoberg_d_lambda_e_sqr<Order>(sin_beta1, sin_beta2, Cj, sqrt_1_Cj_sqr, e_sqr);\n    }*/\n\n    CT lonj;\n    CT latj;\n    CT alphaj;\n\n    CT one_minus_f;\n    CT e_sqr;\n\n    CT tan_latj;\n    CT tan_betaj;\n    CT betaj;\n    CT sin_betaj;\n    CT cos_betaj;\n    CT sin_alphaj;\n    CT Cj;\n    CT Cj_sqr;\n    CT sqrt_1_Cj_sqr;\n\n    int sign_lon_diff;\n\n    bool is_on_equator;\n    bool is_Cj_zero;\n\n    CT t0j;\n    CT asin_tj_t0j;\n};\n\n\n/*!\n\\brief The intersection of two geodesics as proposed by Sjoberg.\n\\see See\n    - [Sjoberg02] Lars E. Sjoberg, Intersections on the sphere and ellipsoid, 2002\n      http://link.springer.com/article/10.1007/s00190-001-0230-9\n    - [Sjoberg07] Lars E. Sjoberg, Geodetic intersection on the ellipsoid, 2007\n      http://link.springer.com/article/10.1007/s00190-007-0204-7\n    - [Sjoberg12] Lars E. Sjoberg, Solutions to the ellipsoidal Clairaut constant\n      and the inverse geodetic problem by numerical integration, 2012\n      https://www.degruyter.com/view/j/jogs.2012.2.issue-3/v10156-011-0037-4/v10156-011-0037-4.xml\n*/\ntemplate\n<\n    typename CT,\n    template <typename, bool, bool, bool, bool, bool> class Inverse,\n    unsigned int Order = 4\n>\nclass sjoberg_intersection\n{\n    typedef sjoberg_geodesic<CT, Order> geodesic_type;\n    typedef Inverse<CT, false, true, false, false, false> inverse_type;\n    typedef typename inverse_type::result_type inverse_result;\n\n    static bool const enable_02 = true;\n    static int const max_iterations_02 = 10;\n    static int const max_iterations_07 = 20;\n\npublic:\n    template <typename T1, typename T2, typename Spheroid>\n    static inline bool apply(T1 const& lona1, T1 const& lata1,\n                             T1 const& lona2, T1 const& lata2,\n                             T2 const& lonb1, T2 const& latb1,\n                             T2 const& lonb2, T2 const& latb2,\n                             CT & lon, CT & lat,\n                             Spheroid const& spheroid)\n    {\n        CT const lon_a1 = lona1;\n        CT const lat_a1 = lata1;\n        CT const lon_a2 = lona2;\n        CT const lat_a2 = lata2;\n        CT const lon_b1 = lonb1;\n        CT const lat_b1 = latb1;\n        CT const lon_b2 = lonb2;\n        CT const lat_b2 = latb2;\n\n        inverse_result const res1 = inverse_type::apply(lon_a1, lat_a1, lon_a2, lat_a2, spheroid);\n        inverse_result const res2 = inverse_type::apply(lon_b1, lat_b1, lon_b2, lat_b2, spheroid);\n\n        return apply(lon_a1, lat_a1, lon_a2, lat_a2, res1.azimuth,\n                     lon_b1, lat_b1, lon_b2, lat_b2, res2.azimuth,\n                     lon, lat, spheroid);\n    }\n\n    // TODO: Currently may not work correctly if one of the endpoints is the pole\n    template <typename Spheroid>\n    static inline bool apply(CT const& lon_a1, CT const& lat_a1, CT const& lon_a2, CT const& lat_a2, CT const& alpha_a1,\n                             CT const& lon_b1, CT const& lat_b1, CT const& lon_b2, CT const& lat_b2, CT const& alpha_b1,\n                             CT & lon, CT & lat,\n                             Spheroid const& spheroid)\n    {\n        // coordinates in radians\n\n        CT const c0 = 0;\n        CT const c1 = 1;\n\n        CT const f = formula::flattening<CT>(spheroid);\n        CT const one_minus_f = c1 - f;\n\n        geodesic_type geod1(lon_a1, lat_a1, alpha_a1, f);\n        geodesic_type geod2(lon_b1, lat_b1, alpha_b1, f);\n\n        // Cj = 1 if on equator <=> sqrt_1_Cj_sqr = 0\n        // Cj = 0 if vertical <=> sqrt_1_Cj_sqr = 1\n\n        if (geod1.is_on_equator && geod2.is_on_equator)\n        {\n            return false;\n        }\n        else if (geod1.is_on_equator)\n        {\n            lon = geod2.lon_of_equator_intersection();\n            lat = c0;\n            return true;\n        }\n        else if (geod2.is_on_equator)\n        {\n            lon = geod1.lon_of_equator_intersection();\n            lat = c0;\n            return true;\n        }\n\n        // (lon1 - lon2) normalized to (-180, 180]\n        CT const lon1_minus_lon2 = math::longitude_distance_signed<radian>(geod2.lonj, geod1.lonj);\n\n        // vertical segments\n        if (geod1.is_Cj_zero && geod2.is_Cj_zero)\n        {\n            CT const pi = math::pi<CT>();\n\n            // the geodesics are parallel, the intersection point cannot be calculated\n            if ( math::equals(lon1_minus_lon2, c0)\n              || math::equals(lon1_minus_lon2 + (lon1_minus_lon2 < c0 ? pi : -pi), c0) )\n            {\n                return false;\n            }\n\n            lon = c0;\n\n            // the geodesics intersect at one of the poles\n            CT const pi_half = pi / CT(2);\n            CT const abs_lat_a1 = math::abs(lat_a1);\n            CT const abs_lat_a2 = math::abs(lat_a2);\n            if (math::equals(abs_lat_a1, abs_lat_a2))\n            {\n                lat = pi_half;\n            }\n            else\n            {\n                // pick the pole closest to one of the points of the first segment\n                CT const& closer_lat = abs_lat_a1 > abs_lat_a2 ? lat_a1 : lat_a2;\n                lat = closer_lat >= 0 ? pi_half : -pi_half;\n            }\n\n            return true;\n        }\n\n        CT lon_sph = 0;\n\n        // Starting tan(beta)\n        CT t = 0;\n\n        /*if (geod1.is_Cj_zero)\n        {\n            CT const k_base = lon1_minus_lon2 + geod2.sign_lon_diff * geod2.asin_tj_t0j;\n            t = sin(k_base) * geod2.t0j;\n            lon_sph = vertical_intersection_longitude(geod1.lonj, lon_b1, lon_b2);\n        }\n        else if (geod2.is_Cj_zero)\n        {\n            CT const k_base = lon1_minus_lon2 - geod1.sign_lon_diff * geod1.asin_tj_t0j;\n            t = sin(-k_base) * geod1.t0j;\n            lon_sph = vertical_intersection_longitude(geod2.lonj, lon_a1, lon_a2);\n        }\n        else*/\n        {\n            // TODO: Consider using betas instead of latitudes.\n            //       Some function calls might be saved this way.\n            CT tan_lat_sph = 0;\n            sjoberg_intersection_spherical_02<CT>::apply_alt(lon_a1, lat_a1, lon_a2, lat_a2,\n                                                             lon_b1, lat_b1, lon_b2, lat_b2,\n                                                             lon_sph, tan_lat_sph);\n            t = one_minus_f * tan_lat_sph; // tan(beta)\n        }\n\n        // TODO: no need to calculate atan here if reduced latitudes were used\n        //       instead of latitudes above, in sjoberg_intersection_spherical_02\n        CT const beta = atan(t);\n\n        if (enable_02 && newton_method(geod1, geod2, beta, t, lon1_minus_lon2, lon, lat))\n        {\n            return true;\n        }\n\n        return converge_07(geod1, geod2, beta, t, lon1_minus_lon2, lon_sph, lon, lat);\n    }\n\nprivate:\n    static inline bool newton_method(geodesic_type const& geod1, geodesic_type const& geod2, // in\n                                     CT beta, CT t, CT const& lon1_minus_lon2, // in\n                                     CT & lon, CT & lat) // out\n    {\n        CT const c0 = 0;\n        CT const c1 = 1;\n\n        CT const e_sqr = geod1.e_sqr;\n\n        CT lon1_diff = 0;\n        CT lon2_diff = 0;\n\n        CT abs_dbeta_last = 0;\n\n        // [Sjoberg02] converges faster than solution in [Sjoberg07]\n        // Newton-Raphson method\n        for (int i = 0; i < max_iterations_02; ++i)\n        {\n            CT const sin_beta = sin(beta);\n            CT const cos_beta = cos(beta);\n            CT const cos_beta_sqr = math::sqr(cos_beta);\n            CT const G = c1 - e_sqr * cos_beta_sqr;\n\n            CT f1 = 0;\n            CT f2 = 0;\n\n            if (!geod1.is_Cj_zero)\n            {\n                bool is_beta_ok = geod1.lon_diff(sin_beta, t, lon1_diff);\n\n                if (is_beta_ok)\n                {\n                    CT const H = cos_beta_sqr - geod1.Cj_sqr;\n                    f1 = geod1.Cj / cos_beta * math::sqrt(G / H);\n                }\n                else\n                {\n                    return false;\n                }\n            }\n\n            if (!geod2.is_Cj_zero)\n            {\n                bool is_beta_ok = geod2.lon_diff(sin_beta, t, lon2_diff);\n\n                if (is_beta_ok)\n                {\n                    CT const H = cos_beta_sqr - geod2.Cj_sqr;\n                    f2 = geod2.Cj / cos_beta * math::sqrt(G / H);\n                }\n                else\n                {\n                    return false;\n                }\n            }\n\n            // NOTE: Things may go wrong if the IP is near the vertex\n            //   1. May converge into the wrong direction (from the other way around).\n            //      This happens when the starting point is on the other side than the vertex\n            //   2. During converging may \"jump\" into the other side of the vertex.\n            //      In this case sin_beta/sqrt_1_Cj_sqr and t/t0j is not in [-1, 1]\n            //   3. f1-f2 may be 0 which means that the intermediate point is on the vertex\n            //      In this case it's not possible to check if this is the correct result\n\n            CT const dbeta_denom = f1 - f2;\n            //CT const dbeta_denom = math::abs(f1) + math::abs(f2);\n\n            if (math::equals(dbeta_denom, c0))\n            {\n                return false;\n            }\n\n            // The sign of dbeta is changed WRT [Sjoberg02]\n            CT const dbeta = (lon1_minus_lon2 + lon1_diff - lon2_diff) / dbeta_denom;\n\n            CT const abs_dbeta = math::abs(dbeta);\n            if (i > 0 && abs_dbeta > abs_dbeta_last)\n            {\n                // The algorithm is not converging\n                // The intersection may be on the other side of the vertex\n                return false;\n            }\n            abs_dbeta_last = abs_dbeta;\n\n            if (math::equals(dbeta, c0))\n            {\n                // Result found\n                break;\n            }\n\n            // Because the sign of dbeta is changed WRT [Sjoberg02] dbeta is subtracted here\n            beta = beta - dbeta;\n\n            t = tan(beta);\n        }\n\n        lat = geod1.lat(t);\n        // NOTE: if Cj is 0 then the result is lonj or lonj+180\n        lon = ! geod1.is_Cj_zero\n                ? geod1.lon(lon1_diff)\n                : geod2.lon(lon2_diff);\n\n        return true;\n    }\n\n    struct geodesics_type\n    {\n        geodesics_type(geodesic_type const& g1, geodesic_type const& g2)\n            : geod1(g1)\n            , geod2(g2)\n            , vertex1(geod1.get_vertex_data())\n            , vertex2(geod2.get_vertex_data())\n        {}\n\n        geodesic_type const& geod1;\n        geodesic_type const& geod2;\n        typename geodesic_type::vertex_data vertex1;\n        typename geodesic_type::vertex_data vertex2;\n    };\n\n    struct converge_07_result\n    {\n        converge_07_result()\n            : lon1(0), lon2(0), k1_diff(0), k2_diff(0), t1(0), t2(0)\n        {}\n\n        CT lon1, lon2;\n        CT k1_diff, k2_diff;\n        CT t1, t2;\n    };\n\n    static inline bool converge_07(geodesic_type const& geod1, geodesic_type const& geod2,\n                                   CT beta, CT t,\n                                   CT const& lon1_minus_lon2, CT const& lon_sph,\n                                   CT & lon, CT & lat)\n    {\n        //CT const c0 = 0;\n        //CT const c1 = 1;\n        //CT const c2 = 2;\n        //CT const pi = math::pi<CT>();\n\n        geodesics_type geodesics(geod1, geod2);\n        converge_07_result result;\n\n        // calculate first pair of longitudes\n        if (!converge_07_step_one(CT(sin(beta)), t, lon1_minus_lon2, geodesics, lon_sph, result, false))\n        {\n            return false;\n        }\n\n        int t_direction = 0;\n\n        CT lon_diff_prev = math::longitude_difference<radian>(result.lon1, result.lon2);\n\n        // [Sjoberg07]\n        for (int i = 2; i < max_iterations_07; ++i)\n        {\n            // pick t candidates from previous result based on dir\n            CT t_cand1 = result.t1;\n            CT t_cand2 = result.t2;\n            // if direction is 0 the closer one is the first\n            if (t_direction < 0)\n            {\n                t_cand1 = (std::min)(result.t1, result.t2);\n                t_cand2 = (std::max)(result.t1, result.t2);\n            }\n            else if (t_direction > 0)\n            {\n                t_cand1 = (std::max)(result.t1, result.t2);\n                t_cand2 = (std::min)(result.t1, result.t2);\n            }\n            else\n            {\n                t_direction = t_cand1 < t_cand2 ? -1 : 1;\n            }\n\n            CT t1 = t;\n            CT beta1 = beta;\n            // check if the further calculation is needed\n            if (converge_07_update(t1, beta1, t_cand1))\n            {\n                break;\n            }\n\n            bool try_t2 = false;\n            converge_07_result result_curr;\n            if (converge_07_step_one(CT(sin(beta1)), t1, lon1_minus_lon2, geodesics, lon_sph, result_curr))\n            {\n                CT const lon_diff1 = math::longitude_difference<radian>(result_curr.lon1, result_curr.lon2);\n                if (lon_diff_prev > lon_diff1)\n                {\n                    t = t1;\n                    beta = beta1;\n                    lon_diff_prev = lon_diff1;\n                    result = result_curr;\n                }\n                else if (t_cand1 != t_cand2)\n                {\n                    try_t2 = true;\n                }\n                else\n                {\n                    // the result is not fully correct but it won't be more accurate\n                    break;\n                }\n            }\n            // ! converge_07_step_one\n            else\n            {\n                if (t_cand1 != t_cand2)\n                {\n                    try_t2 = true;\n                }\n                else\n                {\n                    return false;\n                }\n            }\n\n\n            if (try_t2)\n            {\n                CT t2 = t;\n                CT beta2 = beta;\n                // check if the further calculation is needed\n                if (converge_07_update(t2, beta2, t_cand2))\n                {\n                    break;\n                }\n\n                if (! converge_07_step_one(CT(sin(beta2)), t2, lon1_minus_lon2, geodesics, lon_sph, result_curr))\n                {\n                    return false;\n                }\n\n                CT const lon_diff2 = math::longitude_difference<radian>(result_curr.lon1, result_curr.lon2);\n                if (lon_diff_prev > lon_diff2)\n                {\n                    t_direction *= -1;\n                    t = t2;\n                    beta = beta2;\n                    lon_diff_prev = lon_diff2;\n                    result = result_curr;\n                }\n                else\n                {\n                    // the result is not fully correct but it won't be more accurate\n                    break;\n                }\n            }\n        }\n\n        lat = geod1.lat(t);\n        lon = ! geod1.is_Cj_zero ? result.lon1 : result.lon2;\n        math::normalize_longitude<radian>(lon);\n\n        return true;\n    }\n\n    static inline bool converge_07_update(CT & t, CT & beta, CT const& t_new)\n    {\n        CT const c0 = 0;\n\n        CT const beta_new = atan(t_new);\n        CT const dbeta = beta_new - beta;\n        beta = beta_new;\n        t = t_new;\n\n        return math::equals(dbeta, c0);\n    }\n\n    static inline CT const& pick_t(CT const& t1, CT const& t2, int direction)\n    {\n        return direction < 0 ? (std::min)(t1, t2) : (std::max)(t1, t2);\n    }\n\n    static inline bool converge_07_step_one(CT const& sin_beta,\n                                            CT const& t,\n                                            CT const& lon1_minus_lon2,\n                                            geodesics_type const& geodesics,\n                                            CT const& lon_sph,\n                                            converge_07_result & result,\n                                            bool check_sin_beta = true)\n    {\n        bool ok = converge_07_one_geod(sin_beta, t, geodesics.geod1, geodesics.vertex1, lon_sph,\n                                       result.lon1, result.k1_diff, check_sin_beta)\n               && converge_07_one_geod(sin_beta, t, geodesics.geod2, geodesics.vertex2, lon_sph,\n                                       result.lon2, result.k2_diff, check_sin_beta);\n\n        if (!ok)\n        {\n            return false;\n        }\n\n        CT const k = lon1_minus_lon2 + result.k1_diff - result.k2_diff;\n\n        // get 2 possible ts one lesser and one greater than t\n        // t1 is the closer one\n        calc_ts(t, k, geodesics.geod1, geodesics.geod2, result.t1, result.t2);\n\n        return true;\n    }\n\n    static inline bool converge_07_one_geod(CT const& sin_beta, CT const& t,\n                                            geodesic_type const& geod,\n                                            typename geodesic_type::vertex_data const& vertex,\n                                            CT const& lon_sph,\n                                            CT & lon, CT & k_diff,\n                                            bool check_sin_beta)\n    {\n        using math::detail::bounded;\n        CT const c1 = 1;\n\n        CT k_diff_before = 0;\n        CT k_diff_behind = 0;\n\n        bool is_beta_ok = geod.k_diffs(sin_beta, vertex, k_diff_before, k_diff_behind, check_sin_beta);\n\n        if (! is_beta_ok)\n        {\n            return false;\n        }\n\n        CT const asin_t_t0j = ! geod.is_Cj_zero ? asin(bounded(t / geod.t0j, -c1, c1)) : 0;\n        CT const sign_asin_t_t0j = geod.sign_lon_diff * asin_t_t0j;\n\n        CT const lon_before = geod.lonj + sign_asin_t_t0j + k_diff_before;\n        CT const lon_behind = geod.lonj - sign_asin_t_t0j + k_diff_behind;\n\n        CT const lon_dist_before = math::longitude_distance_signed<radian>(lon_before, lon_sph);\n        CT const lon_dist_behind = math::longitude_distance_signed<radian>(lon_behind, lon_sph);\n        if (math::abs(lon_dist_before) <= math::abs(lon_dist_behind))\n        {\n            k_diff = k_diff_before;\n            lon = lon_before;\n        }\n        else\n        {\n            k_diff = k_diff_behind;\n            lon = lon_behind;\n        }\n\n        return true;\n    }\n\n    static inline void calc_ts(CT const& t, CT const& k,\n                               geodesic_type const& geod1, geodesic_type const& geod2,\n                               CT & t1, CT& t2)\n    {\n        CT const c1 = 1;\n        CT const c2 = 2;\n\n        CT const K = sin(k);\n\n        BOOST_GEOMETRY_ASSERT(!geod1.is_Cj_zero || !geod2.is_Cj_zero);\n        if (geod1.is_Cj_zero)\n        {\n            t1 = K * geod2.t0j;\n            t2 = -t1;\n        }\n        else if (geod2.is_Cj_zero)\n        {\n            t1 = -K * geod1.t0j;\n            t2 = -t1;\n        }\n        else\n        {\n            CT const A = math::sqr(geod1.t0j) + math::sqr(geod2.t0j);\n            CT const B = c2 * geod1.t0j * geod2.t0j * math::sqrt(c1 - math::sqr(K));\n\n            CT const K_t01_t02 = K * geod1.t0j * geod2.t0j;\n            CT const D1 = math::sqrt(A + B);\n            CT const D2 = math::sqrt(A - B);\n            CT const t_new1 = K_t01_t02 / D1;\n            CT const t_new2 = K_t01_t02 / D2;\n            CT const t_new3 = -t_new1;\n            CT const t_new4 = -t_new2;\n\n            // Pick 2 nearest t_new, one greater and one lesser than current t\n            CT const abs_t_new1 = math::abs(t_new1);\n            CT const abs_t_new2 = math::abs(t_new2);\n            CT const abs_t_max = (std::max)(abs_t_new1, abs_t_new2);\n            t1 = -abs_t_max; // lesser\n            t2 = abs_t_max; // greater\n            if (t1 < t)\n            {\n                if (t_new1 < t && t_new1 > t1)\n                    t1 = t_new1;\n                if (t_new2 < t && t_new2 > t1)\n                    t1 = t_new2;\n                if (t_new3 < t && t_new3 > t1)\n                    t1 = t_new3;\n                if (t_new4 < t && t_new4 > t1)\n                    t1 = t_new4;\n            }\n            if (t2 > t)\n            {\n                if (t_new1 > t && t_new1 < t2)\n                    t2 = t_new1;\n                if (t_new2 > t && t_new2 < t2)\n                    t2 = t_new2;\n                if (t_new3 > t && t_new3 < t2)\n                    t2 = t_new3;\n                if (t_new4 > t && t_new4 < t2)\n                    t2 = t_new4;\n            }\n        }\n\n        // the first one is the closer one\n        if (math::abs(t - t2) < math::abs(t - t1))\n        {\n            std::swap(t2, t1);\n        }\n    }\n\n    static inline CT fj(CT const& cos_beta, CT const& cos2_beta, CT const& Cj, CT const& e_sqr)\n    {\n        CT const c1 = 1;\n        CT const Cj_sqr = math::sqr(Cj);\n        return Cj / cos_beta * math::sqrt((c1 - e_sqr * cos2_beta) / (cos2_beta - Cj_sqr));\n    }\n\n    /*static inline CT vertical_intersection_longitude(CT const& ip_lon, CT const& seg_lon1, CT const& seg_lon2)\n    {\n        CT const c0 = 0;\n        CT const lon_2 = ip_lon > c0 ? ip_lon - pi : ip_lon + pi;\n\n        return (std::min)(math::longitude_difference<radian>(ip_lon, seg_lon1),\n                          math::longitude_difference<radian>(ip_lon, seg_lon2))\n            <=\n               (std::min)(math::longitude_difference<radian>(lon_2, seg_lon1),\n                          math::longitude_difference<radian>(lon_2, seg_lon2))\n            ? ip_lon : lon_2;\n    }*/\n};\n\n}}} // namespace boost::geometry::formula\n\n\n#endif // BOOST_GEOMETRY_FORMULAS_SJOBERG_INTERSECTION_HPP\n", "meta": {"hexsha": "e78c96b6766d710cb639d49988c2043510acf84c", "size": 40211, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/geometry/formulas/sjoberg_intersection.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T20:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T20:03:51.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/geometry/formulas/sjoberg_intersection.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:18:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:39:44.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/geometry/formulas/sjoberg_intersection.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-21T17:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T17:46:28.000Z", "avg_line_length": 32.9598360656, "max_line_length": 123, "alphanum_fraction": 0.5230906966, "num_tokens": 11544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5081458715750179}}
{"text": "/*\n *  Distributed under the MIT License (See accompanying file /LICENSE )\n */\n#include <doctest/doctest.h>  // for ResultBuilder\n\n#include <array>                             // for operator==\n#include <boost/multiprecision/cpp_int.hpp>  // for cpp_int\n#include <ostream>                           // for operator<<\n#include <tuple>                             // for tuple\n#include <type_traits>                       // for move\n\n#include \"projgeom/ck_plane.hpp\"              // for check_sine...\n#include \"projgeom/common_concepts.h\"         // for Value_type\n#include \"projgeom/euclid_plane.hpp\"          // for uc_point, Ar\n#include \"projgeom/euclid_plane_measure.hpp\"  // for quadrance\n#include \"projgeom/fractions.hpp\"             // for operator*\n#include \"projgeom/pg_common.hpp\"             // for sq, cross\n#include \"projgeom/pg_line.hpp\"               // for meet\n#include \"projgeom/pg_object.hpp\"             // for operator*\n#include \"projgeom/pg_point.hpp\"              // for pg_point\n#include \"projgeom/proj_plane.hpp\"            // for coincident\n#include \"projgeom/proj_plane_measure.hpp\"    // for R\n// #include <iostream>\n\nusing namespace fun;\n\nstatic const auto Zero = doctest::Approx(0).epsilon(0.01);\n\n/**\n * @brief\n *\n * @param[in] a\n * @return true\n * @return false\n */\ntemplate <typename T> inline auto ApproxZero(const T& a) -> bool {\n    return a[0] == Zero && a[1] == Zero && a[2] == Zero;\n}\n\n/**\n * @brief\n *\n * @tparam T\n * @param[in] triangle\n */\ntemplate <Projective_plane_prim2 P> void chk_euclid(const Triple<P>& triangle) {\n    auto trilateral = tri_dual(triangle);\n\n    const auto& [a1, a2, a3] = triangle;\n    const auto& [l1, l2, l3] = trilateral;\n\n    // using P = decltype(a1);\n    using L = decltype(l1);\n    using K = Value_type<P>;\n    static_assert(Projective_plane_prim2<L>);\n    static_assert(ring<K>);\n\n    // auto zero = std::array<K, 3> {0, 0, 0};\n\n    auto [t1, t2, t3] = tri_altitude(triangle);\n\n    auto t4 = harm_conj(t1, t2, t3);\n    auto o = orthocenter(triangle);\n    auto tau = reflect(l1);\n    auto Q = tri_quadrance(triangle);\n    auto S = tri_spread(trilateral);\n\n    auto [m12, m23, m13] = tri_midpoint(triangle);\n\n    auto mt1 = a1 * m23;\n    auto mt2 = a2 * m13;\n    auto mt3 = a3 * m12;\n\n    const auto& [q1, q2, q3] = Q;\n    const auto& [s1, s2, s3] = S;\n\n    auto tqf = sq(q1 + q2 + q3) - 2 * (q1 * q1 + q2 * q2 + q3 * q3);\n    auto tsf = sq(s1 + s2 + s3) - 2 * (s1 * s1 + s2 * s2 + s3 * s3) - 4 * s1 * s2 * s3;\n    auto c3 = sq(q1 + q2 - q3) / (4 * q1 * q2);\n\n    auto a3p = plucker(3, a1, 4, a2);\n    auto q1p = quadrance(a2, a3p);\n    auto q2p = quadrance(a1, a3p);\n    auto q3p = quadrance(a1, a2);\n    auto tqf2 = Ar(q1p, q2p, q3p);  // get 0\n\n    if constexpr (Integral<K>) {\n        CHECK(!is_parallel(l1, l2));\n        CHECK(!is_parallel(l2, l3));\n        CHECK(is_perpendicular(t1, l1));\n        CHECK(spread(t1, l1) == K(1));\n        CHECK(coincident(t1 * t2, t3));\n        CHECK(coincident(t1 * t2, t3, t4));\n        CHECK(R(t1, t2, t3, t4) == K(-1));\n        CHECK(o == t2 * t3);\n        CHECK(tau(tau(a1)) == a1);\n        CHECK(spread(l1, l1) == K(0));\n        CHECK(quadrance(a1, a1) == K(0));\n        CHECK(check_sine_law(Q, S));\n        CHECK(check_sine_law(S, Q));\n        CHECK(coincident(mt1 * mt2, mt3));\n        // CHECK(cross_s(l1, l2) == c3);\n        CHECK((c3 + s3) == K(1));\n        CHECK(tqf == Ar(q1, q2, q3));\n        CHECK(tsf == K(0));\n        CHECK(tqf2 == K(0));\n        // auto o2 = orthocenter(\n        //               std::tuple {std::move(o), std::move(a2),\n        //               std::move(a3)});\n        // CHECK(a1 == o2);\n    } else {\n        CHECK(cross2(l1, l2) != Zero);\n        CHECK(cross2(l2, l3) != Zero);\n        CHECK(dot1(t1, l1) == Zero);\n        CHECK(spread(t1, l1) - 1 == Zero);\n        CHECK(t1.dot(t2 * t3) == Zero);\n        CHECK(R(t1, t2, t3, t4) + 1 == Zero);\n        CHECK(ApproxZero(cross(meet(t2, t3), o)));\n        CHECK(ApproxZero(cross(tau(tau(a1)), a1)));\n        CHECK(mt1.dot(mt2 * mt3) == Zero);\n        CHECK(spread(l1, l1) == Zero);\n        CHECK(quadrance(a1, a1) == Zero);\n        CHECK(angle(l1, l1) == Zero);\n        CHECK(distance(a1, a1) == Zero);\n        // CHECK(cross_s(l1, l2) == doctest::Approx(c3).epsilon(0.01));\n        CHECK((c3 + s3) - 1 == Zero);\n        CHECK(tqf - Ar(q1, q2, q3) == Zero);\n        CHECK(tsf == Zero);\n        CHECK(tqf2 == Zero);\n        // CHECK(ApproxEqual(a1, orthocenter(std::tuple{std::move(o), // not\n        // quite accurate\n        //                     std::move(a2), std::move(a3)})));\n    }\n}\n\ntemplate <typename T> void chk_cyclic(const T& quadangle) {\n    auto& [u1, u2, u3, u4] = quadangle;\n\n    auto q12 = quadrance(u1, u2);\n    auto q23 = quadrance(u2, u3);\n    auto q34 = quadrance(u3, u4);\n    auto q14 = quadrance(u1, u4);\n    auto q24 = quadrance(u2, u4);\n    auto q13 = quadrance(u1, u3);\n\n    using P = decltype(u1);\n    using K = Value_type<P>;\n\n    if constexpr (Integral<K>) {\n        auto okay = Ptolemy(std::tuple{std::move(q12), std::move(q23), std::move(q34),\n                                       std::move(q14), std::move(q24), std::move(q13)});\n        CHECK(okay);\n    } else {\n        auto t = Ar(q12 * q34, q23 * q14, q13 * q24);\n        CHECK(t == Zero);\n    }\n}\n\nTEST_CASE(\"Euclid plane (cpp_int)\") {\n    using boost::multiprecision::cpp_int;\n\n    auto a1 = pg_point<cpp_int>{1, 3, 1};\n    auto a2 = pg_point<cpp_int>{4, 2, 1};\n    auto a3 = pg_point<cpp_int>{4, -3, 1};\n\n    auto triangle = std::tuple{std::move(a1), std::move(a2), std::move(a3)};\n    chk_euclid(triangle);\n}\n\nTEST_CASE(\"Euclid plane (floating point)\") {\n    auto a1 = pg_point{1., 3., 1.};\n    auto a2 = pg_point{4., 2., 1.};\n    auto a3 = pg_point{4., -3., 1.};\n\n    auto triangle = std::tuple{std::move(a1), std::move(a2), std::move(a3)};\n    chk_euclid(triangle);\n}\n\nTEST_CASE(\"Euclid Cyclic Points (cpp_int)\") {\n    using boost::multiprecision::cpp_int;\n    using P = pg_point<cpp_int>;\n\n    auto u1 = uc_point<P>(1, 0);\n    auto u2 = uc_point<P>(3, 4);\n    auto u3 = uc_point<P>(-1, 2);\n    auto u4 = uc_point<P>(0, 1);\n\n    auto quadangle = std::tuple{std::move(u1), std::move(u2), std::move(u3), std::move(u4)};\n    chk_cyclic(quadangle);\n}\n\nTEST_CASE(\"Euclid Cyclic Points (double)\") {\n    using P = pg_point<double>;\n\n    auto u1 = uc_point<P>(1, 0);\n    auto u2 = uc_point<P>(3, 4);\n    auto u3 = uc_point<P>(-1, 2);\n    auto u4 = uc_point<P>(0, 1);\n\n    auto quadangle = std::tuple{std::move(u1), std::move(u2), std::move(u3), std::move(u4)};\n    chk_cyclic(quadangle);\n}\n", "meta": {"hexsha": "700a79a446a5d92cddeae874702c8a3e1659f9f8", "size": 6571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/source/test_euclid.cpp", "max_stars_repo_name": "luk036/projgeom-cpp", "max_stars_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/source/test_euclid.cpp", "max_issues_repo_name": "luk036/projgeom-cpp", "max_issues_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/source/test_euclid.cpp", "max_forks_repo_name": "luk036/projgeom-cpp", "max_forks_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3694581281, "max_line_length": 92, "alphanum_fraction": 0.5461877949, "num_tokens": 2170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931455, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5081458715750179}}
{"text": "///////////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::location_scale::log_unnormalized_pdf.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_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_LOCATION_SCALE_DERIVATIVE_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_LOCATION_SCALE_DERIVATIVE_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#include <boost/concept/assert.hpp>\n#include <boost/statistics/detail/distribution_common/meta/value.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/location_scale/location_scale.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace distribution{\nnamespace toolkit{\n\n    template<typename Z,typename T>\n    T\n    derivative_log_unnormalized_pdf(\n    \tconst location_scale_distribution<Z>& d,\n        const T& x\n    ){\n        typedef location_scale_distribution<Z> dist_;\n\n        T z = (x-d.mu())/d.sigma();\n        T result = derivative_log_unnormalized_pdf(d.z(),z); \n        result /= d.sigma(); // = dz/dx\n        return result;\n    }\n\n}// toolkit\n}// distribution\n}// detail\n}// statistics \n}// boost\n\n#endif\n", "meta": {"hexsha": "f5fc3fb86cb3d5b347315af62578441a2014126c", "size": 1657, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/location_scale/derivative_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/location_scale/derivative_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/location_scale/derivative_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": 39.4523809524, "max_line_length": 111, "alphanum_fraction": 0.5950512975, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5081328946308402}}
{"text": "#include \"parametrization/parametrization.hpp\"\n\n#include <vector>\n#include <cmath>\n#include <chrono>\n#include <Eigen/IterativeLinearSolvers>\n\nusing namespace Eigen;\nusing namespace std;\n\ntypedef Triplet<double> Td;\n\nvector<MatrixXd> parametrize(vector<const MatrixXd*> &Vs, vector<const MatrixXi*> &Ts) {\n  cout << \"Started parametrization:...\" << flush;\n  auto start = chrono::high_resolution_clock::now();\n\n  vector<MatrixXd> Us;\n  Us.reserve(Vs.size());\n  for(int i = 0; i < Vs.size(); i++)\n    Us.emplace_back(parametrize(*Vs[i], *Ts[i]));\n\n  auto finish = chrono::high_resolution_clock::now();\n  cout << \"done: \" << chrono::duration<double>(finish-start).count() << \" s\" << endl;\n\n  return Us;\n}\n\nMatrixXd parametrize(const MatrixXd &V, const MatrixXi &T) {\n  const int np = T.rows(), n = V.rows();\n\n  pair<int,int> diam = approximateDiameter(V);\n\n  // List of triplets for sparse matrix creation\n  vector<Td> ta, tb, tu;\n  ta.reserve(np * 12);\n\n  // For each triangle\n  for (int i = 0; i < np; i++) {\n    // Calculate x,y\n    // First vertex as (0,0), second as (s,0), third as t(cos(a), sin(a))\n    RowVectorXd p[3];\n    double x[3], y[3];\n\n    p[0] = V.row(T(i, 0));\n    p[1] = V.row(T(i, 1));\n    p[2] = V.row(T(i, 2));\n\n    double a = angleBetweenSides(p[1] - p[0], p[2] - p[0]);\n    double s = (p[1] - p[0]).norm();\n    double t = (p[2] - p[0]).norm();\n\n    x[0] = y[0] = 0;\n    x[1] = s, y[1] = 0;\n    x[2] = t * cos(a), y[2] = t * sin(a);\n\n    double d = sqrt((x[0] * y[1] - y[0] * x[1]) + (x[1] * y[2] - y[1] * x[2]) + (x[2] * y[0] - y[2] * x[0]));\n//    d=1;\n\n    // Calculate W\n    double Wr[3], Wi[3];\n    Wr[0] = (x[2] - x[1]) / d, Wi[0] = (y[2] - y[1]) / d;\n    Wr[1] = (x[0] - x[2]) / d, Wi[1] = (y[0] - y[2]) / d;\n    Wr[2] = (x[1] - x[0]) / d, Wi[2] = (y[1] - y[0]) / d;\n\n\n    // Push values to A and B\n    emplaceAB(ta, tb, i, T(i,0), n, np, Wr[0], Wi[0], diam);\n    emplaceAB(ta, tb, i, T(i,1), n, np, Wr[1], Wi[1], diam);\n    emplaceAB(ta, tb, i, T(i,2), n, np, Wr[2], Wi[2], diam);\n  }\n\n  // Build A and B\n  SparseMatrix<double> A(2 * np, 2 * (n - 2));\n  SparseMatrix<double> B(2 * np, 4);\n  A.setFromTriplets(ta.begin(), ta.end());\n  ta.clear();\n  B.setFromTriplets(tb.begin(), tb.end());\n  tb.clear();\n\n  // Build up \n  VectorXd up(4);\n  up(0) = 0;\n  up(1) = 1;\n  up(2) = 0;\n  up(3) = 1;\n\n  VectorXd b = - B * up;\n\n  // Solve least squares using QR decomposition\n  // A.makeCompressed();\n  // SparseQR<SparseMatrix<double>, COLAMDOrdering<int> > solver(A);\n  // VectorXd uf = solver.solve(b);\n\n  // Solve least squares using iterative CG\n  A.makeCompressed();\n  LeastSquaresConjugateGradient<SparseMatrix<double>> solver(A);\n  VectorXd uf = solver.solve(b);\n\n\n  // Join uf and up\n  MatrixXd U(n, 2);\n  for(int i = 0; i < n; i++) {\n    if(i != diam.first and i != diam.second) {\n      int ii = i;\n      if(i > diam.second) ii--;\n      if(i > diam.first) ii--;\n      U(i,0) = uf(ii);\n      U(i,1) = uf(ii + n - 2);\n    }\n    else\n      U(i,0) = U(i,1) = (i==diam.second);\n  }\n\n  return U;\n}\n\ndouble angleBetweenSides(const RowVectorXd &a, const RowVectorXd &b) {\n  return acos(a.dot(b) / a.norm() / b.norm());\n}\n\npair<int,int> approximateDiameter(const MatrixXd &V) {\n  const int n = V.rows();\n  double m = 0;\n  pair<int,int> best{0,1};\n  for(int i = 0; i < n; i++) {\n    for(int j = i+1; j < n; j++) {\n      double d = (V.row(i)-V.row(j)).norm();\n      if(d>m) {\n        m = d;\n        best = pair<int,int>{i,j};\n      }\n    }\n  }\n  return best;\n}\n\nvoid emplaceAB(vector<Td> &ta, vector<Td> &tb, int i, int j, int n, int np, double wr, double wi, pair<int,int> &diam) {\n  if (j != diam.first and j != diam.second) {\n    if(j > diam.second) j--;\n    if(j > diam.first) j--;\n    ta.emplace_back(i, j, wr);\n    ta.emplace_back(i + np, j + n - 2, wr);\n    ta.emplace_back(i, j + n - 2, -wi);\n    ta.emplace_back(i + np, j, wi);\n  } else {\n    j = (j==diam.second);\n    tb.emplace_back(i, j, wr);\n    tb.emplace_back(i + np, j + 2, wr);\n    tb.emplace_back(i, j + 2, -wi);\n    tb.emplace_back(i + np, j, wi);\n  }\n}", "meta": {"hexsha": "51fd6bb53f852fff5e409c3a1fda53d6f23a1896", "size": 4036, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/parametrization/parametrization.cpp", "max_stars_repo_name": "math-castro/lscm", "max_stars_repo_head_hexsha": "a0a6d73bb4ac9dd7e3bdbc67397343385fee922f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-12-11T19:41:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T22:03:35.000Z", "max_issues_repo_path": "src/parametrization/parametrization.cpp", "max_issues_repo_name": "JerryJiehanWang/lscm", "max_issues_repo_head_hexsha": "a0a6d73bb4ac9dd7e3bdbc67397343385fee922f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-21T16:26:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T15:35:36.000Z", "max_forks_repo_path": "src/parametrization/parametrization.cpp", "max_forks_repo_name": "JerryJiehanWang/lscm", "max_forks_repo_head_hexsha": "a0a6d73bb4ac9dd7e3bdbc67397343385fee922f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-17T08:49:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T16:10:29.000Z", "avg_line_length": 26.5526315789, "max_line_length": 120, "alphanum_fraction": 0.5411298315, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5081328901469229}}
{"text": "// -------------------------------------------------------------------------------------------------\n//                              Copyright 2016 - NumScale SAS\n//\n//                   Distributed under the Boost Software License, Version 1.0.\n//                        See accompanying file LICENSE.txt or copy at\n//                            http://www.boost.org/LICENSE_1_0.txt\n// -------------------------------------------------------------------------------------------------\n\n#include <simd_bench.hpp>\n#include <boost/simd/function/simd/ilogb.hpp>\n#include <boost/simd/pack.hpp>\n\nnamespace nsb = ns::bench;\nnamespace bs =  boost::simd;\n\nDEFINE_SIMD_BENCH(simd_ilogb, bs::ilogb);\n\nDEFINE_BENCH_MAIN()\n{\n  nsb::for_each<simd_ilogb, NS_BENCH_NUMERIC_TYPES>(0, 10);\n}\n", "meta": {"hexsha": "7ac9efce59f14450daa3aeb156bcf8f7f27910b0", "size": 774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/function/simd/ilogb.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": "bench/function/simd/ilogb.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "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": "bench/function/simd/ilogb.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "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": 35.1818181818, "max_line_length": 100, "alphanum_fraction": 0.4560723514, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5081272793297359}}
{"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{\nVector3f boxMin(Vector3f::Zero()), boxMax(Vector3f::Ones());\nVector3f p0 = Vector3f::Random(), p1 = Vector3f::Random().cwiseAbs();\n// let's check if p0 and p1 are inside the axis aligned box defined by the corners boxMin,boxMax:\ncout << \"Is (\" << p0.transpose() << \") inside the box: \"\n     << ((boxMin.array()<p0.array()).all() && (boxMax.array()>p0.array()).all()) << endl;\ncout << \"Is (\" << p1.transpose() << \") inside the box: \"\n     << ((boxMin.array()<p1.array()).all() && (boxMax.array()>p1.array()).all()) << endl;\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "666f91f9db25d5ad180ae23ce46de461383f13be", "size": 1056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_MatrixBase_all.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_MatrixBase_all.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_MatrixBase_all.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": 34.064516129, "max_line_length": 224, "alphanum_fraction": 0.6524621212, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.5081272673888002}}
{"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// Written by Jiahu Deng and Peter Gottschling\n\n#include <iostream>\n#include <cstdio>\n#include <boost/numeric/mtl/detail/dilated_int.hpp>\n\n\nusing namespace std;\n\nstruct morton_exception {};\n\ntemplate <typename T>\nvoid test_inc(string s, T dil, typename T::value_type exp_increment) \n{ \n    printf(\"%s %x, bit mask is %x, negated mask is %x\\n\", s.c_str(), dil.i, dil.bit_mask, dil.anti_mask);\n    if ((++dil).i != exp_increment) throw morton_exception();\n \n    for (typename T::value_type i = 1; i < 6; ++i) {\n\tT dilated(i);\n\tif (dilated.undilate() != i) throw morton_exception();\n\n\tcout << \"dilated(\" << i << \") = \" << dilated <<  \"\\n\";\n\tif (dil.i != dilated.i) throw morton_exception();\n\t// check both pre and post increment\n\ti & 1 ? ++dil : dil++;\n    } \n    \n    printf(\"dilated_zero = %x, dilated_one = %x\\n\", dil.dilated_zero, dil.dilated_one);\n\n    T dec_dil(6);\n    for (typename T::value_type i = 6; i > 0; --i) {\n\tcout << \"dilated(\" << i << \") = \" << dec_dil <<  \"\\n\";\n\tif (dec_dil != T(i)) throw morton_exception();\n\n\t// check both pre and post decrement\n\ti & 1 ? --dec_dil : dec_dil--;\n    }\t\n}\n\ntemplate <typename T>\nvoid test_plus1(T)\n{\n    T a(1), b(3), c(4);\n    cout << \"a = \" << a << \", b = \" << b << \", a + b = \" << a + b << \", c = \" << c << \"\\n\";\n    if (a + b != c) throw morton_exception();\n\n    cout << \"c - b = \" << c - b << \"\\n\";\n    if (c - b != a) throw morton_exception();\n}  \n \ntemplate <typename T> \nvoid test_plus2(T)\n{\n    T a(22), b(33), c(55);\n    cout << \"a = \" << a << \", b = \" << b << \", a + b = \" << a + b << \", c = \" << c << \"\\n\";\n    if (a + b != c) throw morton_exception();\n\n    cout << \"c - b = \" << c - b << \"\\n\";\n    if (c - b != a) throw morton_exception();\n}    \n\ntemplate <typename T>\nvoid test_dilated(string s, T dil, typename T::value_type exp_increment) \n{\n    test_inc(s, dil, exp_increment);\n    test_plus1(dil); test_plus2(dil);\n}\n\n\nint main(int , char**)\n{    \n    using namespace mtl;\n\n    dilated_int<unsigned, dilated::odd_bits<unsigned>::value, true>     dil1;\n    test_dilated( \"Odd normalized\", dil1, 2);\n\n    dilated_int<unsigned, dilated::even_bits<unsigned>::value, true>     dil2;\n    test_dilated( \"Even normalized\", dil2, 1);\n\n    dilated_int<unsigned, dilated::odd_bits<unsigned>::value, false>     dil3;\n    test_dilated( \"Odd anti-normalized\", dil3, 0x55555557);\n\n    dilated_int<unsigned, dilated::even_bits<unsigned>::value, false>     dil4;\n    test_dilated( \"Even anti-normalized\", dil4, 0xaaaaaaab);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "a0b228b08b1cedd197b2888c3752a72d809e54ab", "size": 2939, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/dilated_int_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/dilated_int_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/dilated_int_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 29.099009901, "max_line_length": 105, "alphanum_fraction": 0.6005444029, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5081272666641515}}
{"text": "#include <iostream>\r\n#include <sys/time.h>\r\n#include <Eigen/Core>\r\n\r\n#include \"celerite/celerite.h\"\r\n//#include \"celerite/carma.h\"\r\n#include \"celerite/utils.h\"\r\n#include \"../include/KF.h\"\r\n#include \"../include/dsho.h\"\r\n\r\n// This code benchmarks a single DSHO, celerite vs gpstate\r\n\r\n// Timer for the benchmark.\r\ndouble get_timestamp ()\r\n{\r\n  struct timeval now;\r\n  gettimeofday (&now, NULL);\r\n  return double(now.tv_usec) * 1.0e-6 + double(now.tv_sec);\r\n}\r\n\r\nint main (int argc, char* argv[])\r\n{\r\n  srand(42);\r\n\r\n  size_t N_max = pow(2, 19);\r\n  if (argc >= 2) N_max = atoi(argv[1]);\r\n  size_t niter = 5;\r\n  if (argc >= 3) niter = atoi(argv[2]);\r\n  size_t niter_celerite = niter;\r\n  if (argc >= 4) niter_celerite = atoi(argv[3]);\r\n  std::cout << \"N:\" << N_max << \" gpstate:\" << niter << \" celerite:\" << niter_celerite << std::endl;\r\n\r\n // Generate some fake data.\r\n  Eigen::VectorXd x = Eigen::VectorXd::Random(N_max),\r\n                  yerr = Eigen::VectorXd::Random(N_max),\r\n                  y, diag;\r\n  yerr.array() *= 0.1;\r\n  yerr.array() += 1.0;\r\n  diag = yerr.array() * yerr.array();\r\n  std::sort(x.data(), x.data() + x.size());\r\n  y = sin(x.array());\r\n\r\n  //set up the DSHO parameters\r\n  size_t nterms=3;\r\n  double omega0=1.0;\r\n  double Q = 1.0;\r\n  double varf = 1.0;\r\n  int flag;\r\n\r\n  // translate into corresponding CARMA parameters for use in celerite\r\n  Eigen::VectorXd carma_arparams(nterms);\r\n  Eigen::VectorXd carma_maparams(nterms-1);\r\n  carma_arparams << omega0*omega0, omega0/Q, 1.0;\r\n  carma_maparams << 1.0, 0.0;\r\n\r\n  Eigen::VectorXd alpha_real, beta_real;\r\n  Eigen::VectorXd alpha_complex_real(1), alpha_complex_imag(1),\r\n                    beta_complex_real(1), beta_complex_imag(1);\r\n\r\n  double temp = std::sqrt(4.0*Q*Q - 1.0);\r\n  double S0 = varf* std::pow(Q,-2) * std::sqrt(M_PI) / std::sqrt(2);\r\n  alpha_complex_real(0) = S0 * omega0 * Q;\r\n  alpha_complex_imag(0) = S0 * omega0 * Q/temp;\r\n  beta_complex_real(0) = 0.5*omega0 / Q;\r\n  beta_complex_imag(0) = 0.5*temp*omega0 / Q;\r\n\r\n\r\n//f = np.sqrt(4.0 * Q**2-1)\r\n //       return (\r\n //           S0 * w0 * Q,\r\n //           S0 * w0 * Q / f,\r\n //           0.5 * w0 / Q,\r\n //           0.5 * w0 / Q * f,\r\n //       )\r\n\r\n  // the following pieces of code verify that the log likelihoods are\r\n  // consistent between celerite and gpstate\r\n  celerite::solver::CholeskySolver<double> solver;\r\n  solver.compute(0.0, alpha_real, beta_real, alpha_complex_real, alpha_complex_imag, beta_complex_real, beta_complex_imag, x, diag);\r\n  double celerite_ll = -0.5*(solver.dot_solve(y) + solver.log_determinant() + x.rows() * log(2.0 * M_PI));\r\n  std::cout << celerite_ll << std::endl;\r\n\r\n  gpstate::dsho::DSHOSolver dsho(x,y,yerr,omega0, Q, 1.0);\r\n  double log_likelihood = dsho.KF_log_likelihood();\r\n  std::cout << \"logL: \" << log_likelihood << std::endl;\r\n\r\n\r\n\r\n  // now benchmark, knowing that we do get consistent log-likelohood values\r\n  double strt;\r\n\r\nfor (size_t N = 64; N <= N_max; N *= 2) {\r\n\r\n  double celerite_time = 0.0;\r\n  double gpstate_time = 0.0;\r\n\r\n  if (niter_celerite > 0) {\r\n    //celerite::solver::CholeskySolver<double> solver;\r\n    //solver.compute(0.0, alpha_real, beta_real, alpha_complex_real, alpha_complex_imag, beta_complex_real, beta_complex_imag, x, diag);\r\n    //celerite_ll = -0.5*(solver.dot_solve(y) + solver.log_determinant() + x.rows() * log(2.0 * M_PI));\r\n    //std::cout << \"logL(celerite)\" << celerite_ll << std::endl;\r\n\r\n    for (size_t i = 0; i < niter_celerite; ++i) {\r\n      strt = get_timestamp();\r\n      solver.compute(0.0, alpha_real, beta_real, alpha_complex_real, alpha_complex_imag, beta_complex_real, beta_complex_imag, x.head(N), diag.head(N));\r\n      celerite_ll = -0.5*(solver.dot_solve(y.head(N)) + solver.log_determinant() + x.head(N).rows() * log(2.0 * M_PI));\r\n      celerite_time += get_timestamp()-strt;\r\n    }\r\n  }\r\n  if (niter > 0) {\r\n    //gpstate::dsho::DSHOSolver dsho1(x,y,yerr,omega0, Q, 1.0);\r\n    //log_likelihood = dsho1.KF_log_likelihood();\r\n    //std::cout << \"logL: \" << log_likelihood << std::endl;\r\n\r\n    for (size_t i = 0; i < niter; ++i) {\r\n      strt = get_timestamp();\r\n      gpstate::dsho::DSHOSolver dsho(x.head(N),y.head(N),yerr.head(N),omega0, Q, 1.0);\r\n      double log_likelihood = dsho.KF_log_likelihood();\r\n      gpstate_time += get_timestamp()-strt;\r\n      }\r\n    }\r\n   // Print the results.\r\n   if ((niter > 0) & (niter_celerite > 0)){\r\n     std::cout << N;\r\n     std::cout << \" \";\r\n     std::cout << celerite_time / niter_celerite;\r\n     std::cout << \" \";\r\n     std::cout << gpstate_time / niter;\r\n     std::cout << \"\\n\";\r\n   }\r\n}\r\n}\r\n", "meta": {"hexsha": "0d4ac0b8f5b7c7be8c14f2e811ffd46eb2278671", "size": 4588, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/benchmark.cpp", "max_stars_repo_name": "andres-jordan/gpstate", "max_stars_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-13T23:27:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-13T23:27:32.000Z", "max_issues_repo_path": "src/benchmark.cpp", "max_issues_repo_name": "andres-jordan/gpstate", "max_issues_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/benchmark.cpp", "max_forks_repo_name": "andres-jordan/gpstate", "max_forks_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_forks_repo_licenses": ["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.4962406015, "max_line_length": 153, "alphanum_fraction": 0.608326068, "num_tokens": 1464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5081272619591907}}
{"text": "//***************************************************************************************\n// HW08App.cpp by Frank Luna (C) 2015 All Rights Reserved.\n//***************************************************************************************\n\n\n#include \"../common/d3dApp.h\"\n#include \"../common/MathHelper.h\"\n#include <UDX12/UploadBuffer.h>\n#include \"../common/GeometryGenerator.h\"\n#include \"util.h\"\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n#include <Eigen/Dense>\n\nusing Microsoft::WRL::ComPtr;\nusing namespace DirectX;\nusing namespace DirectX::PackedVector;\n\nconst int gNumFrameResources = 3;\nconst size_t InterpNum = 60;\n\nstruct V;\nstruct F;\nstruct H;\nusing Traits_VFH = Ubpa::HEMeshTriats_EmptyE<V, F, H>;\n\nstruct V : Ubpa::TVertex<Traits_VFH> {\n\tUbpa::pointf2 p; // t = 0\n\tUbpa::pointf2 q; // t = 1\n};\n\nstruct F : Ubpa::TPolygon<Traits_VFH> {\n\tfloat area;\n\n\t// set L, theta, S\n\tvoid Init();\n\tUbpa::matf2 L;\n\tfloat theta; // -pi ~ pi\n\tUbpa::matf2 S;\n\n\t// theta, S, t -> Lt\n\tvoid UpdateLt(float t);\n\tUbpa::matf2 Lt;\n};\n\nstruct H : Ubpa::THalfEdge<Traits_VFH> {\n\tfloat cot_theta{ 0.f }; // cotangent of opposite angle\n};\n\nvoid F::Init() {\n\tauto he01 = HalfEdge();\n\tauto he12 = he01->Next();\n\tauto he20 = he12->Next();\n\n\tauto v0 = he01->Origin();\n\tauto v1 = he12->Origin();\n\tauto v2 = he20->Origin();\n\n\tconst auto& p0 = v0->p;\n\tconst auto& p1 = v1->p;\n\tconst auto& p2 = v2->p;\n\n\tconst auto& q0 = v0->q;\n\tconst auto& q1 = v1->q;\n\tconst auto& q2 = v2->q;\n\n\tfloat y1_y2 = p1[1] - p2[1];\n\tfloat y2_y0 = p2[1] - p0[1];\n\tfloat y0_y1 = p0[1] - p1[1];\n\n\tfloat x2_x1 = p2[0] - p1[0];\n\tfloat x0_x2 = p0[0] - p2[0];\n\tfloat x1_x0 = p1[0] - p0[0];\n\n\tUbpa::matf2 J;\n\tfloat inv_two_area = 1 / (2 * area);\n\tJ(0, 0) = inv_two_area * (y1_y2 * q0[0] + y2_y0 * q1[0] + y0_y1 * q2[0]);\n\tJ(0, 1) = inv_two_area * (x2_x1 * q0[0] + x0_x2 * q1[0] + x1_x0 * q2[0]);\n\tJ(1, 0) = inv_two_area * (y1_y2 * q0[1] + y2_y0 * q1[1] + y0_y1 * q2[1]);\n\tJ(1, 1) = inv_two_area * (x2_x1 * q0[1] + x0_x2 * q1[1] + x1_x0 * q2[1]);\n\n\tauto [U, S, V] = J.SVD();\n\tUbpa::matf2 R = U * V.transpose();\n\tassert(R.det() > 0);\n\tthis->S = V * S * V.transpose();\n\tL = R * S;\n\tfloat cos_theta = R(0, 0);\n\tfloat sin_theta = R(1, 0);\n\tfloat ac = std::acos(cos_theta);\n\tif (sin_theta > 0)\n\t\ttheta = ac;\n\telse\n\t\ttheta = - ac;\n}\n\nvoid F::UpdateLt(float t) {\n\tassert(0 <= t && t <= 1);\n\tfloat theta_t = t * theta;\n\tfloat cos_theta_t = std::cos(theta_t);\n\tfloat sin_theta_t = std::sin(theta_t);\n\tUbpa::matf2 Rt = {\n\t\tcos_theta_t, -sin_theta_t,\n\t\tsin_theta_t,  cos_theta_t\n\t};\n\tUbpa::matf2 St = Ubpa::matf2::lerp(Ubpa::matf2::eye(), S, t);\n\tLt = Rt * St;\n}\n\nstruct ObjectConstants\n{\n\tDirectX::XMFLOAT4X4 World = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT4X4 TexTransform = MathHelper::Identity4x4();\n};\n\nstruct PassConstants\n{\n\tDirectX::XMFLOAT4X4 View = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT4X4 InvView = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT4X4 Proj = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT4X4 InvProj = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT4X4 ViewProj = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT4X4 InvViewProj = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT3 EyePosW = { 0.0f, 0.0f, 0.0f };\n\tfloat cbPerObjectPad1 = 0.0f;\n\tDirectX::XMFLOAT2 RenderTargetSize = { 0.0f, 0.0f };\n\tDirectX::XMFLOAT2 InvRenderTargetSize = { 0.0f, 0.0f };\n\tfloat NearZ = 0.0f;\n\tfloat FarZ = 0.0f;\n\tfloat TotalTime = 0.0f;\n\tfloat DeltaTime = 0.0f;\n\n\tDirectX::XMFLOAT4 AmbientLight = { 0.0f, 0.0f, 0.0f, 1.0f };\n\n\t// Indices [0, NUM_DIR_LIGHTS) are directional lights;\n\t// indices [NUM_DIR_LIGHTS, NUM_DIR_LIGHTS+NUM_POINT_LIGHTS) are point lights;\n\t// indices [NUM_DIR_LIGHTS+NUM_POINT_LIGHTS, NUM_DIR_LIGHTS+NUM_POINT_LIGHT+NUM_SPOT_LIGHTS)\n\t// are spot lights for a maximum of MaxLights per object.\n\tLight Lights[MaxLights];\n};\n\nstruct Vertex\n{\n\tDirectX::XMFLOAT3 Pos;\n\tDirectX::XMFLOAT3 Normal;\n\tDirectX::XMFLOAT2 TexC;\n};\n\n// Lightweight structure stores parameters to draw a shape.  This will\n// vary from app-to-app.\nstruct RenderItem\n{\n\tRenderItem() = default;\n\n    // World matrix of the shape that describes the object's local space\n    // relative to the world space, which defines the position, orientation,\n    // and scale of the object in the world.\n    XMFLOAT4X4 World = MathHelper::Identity4x4();\n\n\tXMFLOAT4X4 TexTransform = MathHelper::Identity4x4();\n\n\t// Dirty flag indicating the object data has changed and we need to update the constant buffer.\n\t// Because we have an object cbuffer for each FrameResource, we have to apply the\n\t// update to each FrameResource.  Thus, when we modify obect data we should set \n\t// NumFramesDirty = gNumFrameResources so that each frame resource gets the update.\n\tint NumFramesDirty = gNumFrameResources;\n\n\t// Index into GPU constant buffer corresponding to the ObjectCB for this render item.\n\tUINT ObjCBIndex = -1;\n\n\tMaterial* Mat = nullptr;\n\tUbpa::DX12::MeshGeometry* Geo = nullptr;\n\t//std::string Geo;\n\n    // Primitive topology.\n    D3D12_PRIMITIVE_TOPOLOGY PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;\n\n    // DrawIndexedInstanced parameters.\n    UINT IndexCount = 0;\n    UINT StartIndexLocation = 0;\n    int BaseVertexLocation = 0;\n};\n\nclass HW08App : public D3DApp\n{\npublic:\n    HW08App(HINSTANCE hInstance);\n    HW08App(const HW08App& rhs) = delete;\n    HW08App& operator=(const HW08App& rhs) = delete;\n    ~HW08App();\n\n    virtual bool Initialize()override;\n\nprivate:\n    virtual void OnResize()override;\n    virtual void Update(const GameTimer& gt)override;\n    virtual void Draw(const GameTimer& gt)override;\n\n    virtual void OnMouseDown(WPARAM btnState, int x, int y)override;\n    virtual void OnMouseUp(WPARAM btnState, int x, int y)override;\n    virtual void OnMouseMove(WPARAM btnState, int x, int y)override;\n\n    void OnKeyboardInput(const GameTimer& gt);\n\tvoid UpdateCamera(const GameTimer& gt);\n\tvoid AnimateMaterials(const GameTimer& gt);\n\tvoid UpdateObjectCBs(const GameTimer& gt);\n\tvoid UpdateMaterialCBs(const GameTimer& gt);\n\tvoid UpdateMainPassCB(const GameTimer& gt);\n\n\tvoid LoadTextures();\n    void BuildRootSignature();\n\tvoid BuildDescriptorHeaps();\n    void BuildShadersAndInputLayout();\n    void BuildShapeGeometry();\n    void BuildPSOs();\n    void BuildFrameResources();\n    void BuildMaterials();\n    void BuildRenderItems();\n    void DrawRenderItems(ID3D12GraphicsCommandList* cmdList, const std::vector<RenderItem*>& ritems);\n\n\tstd::array<const CD3DX12_STATIC_SAMPLER_DESC, 6> GetStaticSamplers();\n\nprivate:\n\n\tstd::vector<std::unique_ptr<Ubpa::DX12::FrameResource>> mFrameResources;\n\tUbpa::DX12::FrameResource* mCurrFrameResource = nullptr;\n    int mCurrFrameResourceIndex = 0;\n\n\tstd::unordered_map<std::string, std::unique_ptr<Material>> mMaterials;\n\n    std::vector<D3D12_INPUT_ELEMENT_DESC> mInputLayout;\n \n\t// List of all the render items.\n\tstd::vector<std::unique_ptr<RenderItem>> mAllRitems;\n\n\t// Render items divided by PSO.\n\tstd::vector<RenderItem*> mOpaqueRitems;\n\n    PassConstants mMainPassCB;\n\n\tXMFLOAT3 mEyePos = { 0.0f, 0.0f, 0.0f };\n\tXMFLOAT4X4 mView = MathHelper::Identity4x4();\n\tXMFLOAT4X4 mProj = MathHelper::Identity4x4();\n\n\tfloat mTheta = 1.3f*XM_PI;\n\tfloat mPhi = 0.4f*XM_PI;\n\tfloat mRadius = 2.5f;\n\n    POINT mLastMousePos;\n\n\tstd::unordered_map<std::string, std::unique_ptr<Ubpa::TriMesh>> trimeshes;\n\n\t// frame graph\n\t//Ubpa::DX12::FG::RsrcMngr fgRsrcMngr;\n\tUbpa::DX12::FG::Executor fgExecutor;\n\tUbpa::FG::Compiler fgCompiler;\n\tUbpa::FG::FrameGraph fg;\n};\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,\n    PSTR cmdLine, int showCmd)\n{\n    // Enable run-time memory check for debug builds.\n#if defined(DEBUG) | defined(_DEBUG)\n    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);\n#endif\n\n    try\n    {\n        HW08App theApp(hInstance);\n        if(!theApp.Initialize())\n            return 0;\n\n        int rst = theApp.Run();\n\t\tUbpa::DXRenderer::Instance().Release();\n\t\treturn rst;\n    }\n    catch(Ubpa::DX12::Util::Exception& e)\n    {\n        MessageBox(nullptr, e.ToString().c_str(), L\"HR Failed\", MB_OK);\n        return 0;\n    }\n\n}\n\nHW08App::HW08App(HINSTANCE hInstance)\n    : D3DApp(hInstance)\n{\n}\n\nHW08App::~HW08App()\n{\n    if(!uDevice.IsNull())\n        FlushCommandQueue();\n}\n\nbool HW08App::Initialize()\n{\n    if(!D3DApp::Initialize())\n        return false;\n\n\tUbpa::DXRenderer::Instance().Init(uDevice.raw.Get());\n\n\tUbpa::DX12::DescriptorHeapMngr::Instance().Init(uDevice.raw.Get(), 1024, 1024, 1024, 1024, 1024);\n\n\t//fgRsrcMngr.Init(uGCmdList, uDevice);\n\n    // Reset the command list to prep for initialization commands.\n    ThrowIfFailed(uGCmdList->Reset(mDirectCmdListAlloc.Get(), nullptr));\n\n    // Get the increment size of a descriptor in this heap type.  This is hardware specific, \n\t// so we have to query this information.\n    //mCbvSrvDescriptorSize = uDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);\n\n\tUbpa::DXRenderer::Instance().GetUpload().Begin();\n \n\tLoadTextures();\n    BuildRootSignature();\n\tBuildDescriptorHeaps();\n    BuildShadersAndInputLayout();\n    BuildShapeGeometry();\n\tBuildMaterials();\n    BuildRenderItems();\n    BuildFrameResources();\n    BuildPSOs();\n\n    // Execute the initialization commands.\n    ThrowIfFailed(uGCmdList->Close());\n\tuCmdQueue.Execute(uGCmdList.raw.Get());\n\n\tUbpa::DXRenderer::Instance().GetUpload().End(uCmdQueue.raw.Get());\n\n    // Wait until initialization is complete.\n    FlushCommandQueue();\n\n    return true;\n}\n \nvoid HW08App::OnResize()\n{\n    D3DApp::OnResize();\n\n    // The window resized, so update the aspect ratio and recompute the projection matrix.\n    XMMATRIX P = XMMatrixPerspectiveFovLH(0.25f*MathHelper::Pi, AspectRatio(), 1.0f, 1000.0f);\n    XMStoreFloat4x4(&mProj, P);\n\n\tauto clearFGRsrcMngr = [](void* rsrcMngr) {\n\t\treinterpret_cast<Ubpa::DX12::FG::RsrcMngr*>(rsrcMngr)->Clear();\n\t};\n\tfor (auto& frsrc : mFrameResources)\n\t\tfrsrc->DelayUpdateResource(\"FrameGraphRsrcMngr\", clearFGRsrcMngr);\n}\n\nvoid HW08App::Update(const GameTimer& gt)\n{\n    OnKeyboardInput(gt);\n\tUpdateCamera(gt);\n\n    // Cycle through the circular frame resource array.\n    mCurrFrameResourceIndex = (mCurrFrameResourceIndex + 1) % gNumFrameResources;\n    mCurrFrameResource = mFrameResources[mCurrFrameResourceIndex].get();\n\n    // Has the GPU finished processing the commands of the current frame resource?\n    // If not, wait until the GPU has completed commands up to this fence point.\n\tmCurrFrameResource->Wait();\n\n\tAnimateMaterials(gt);\n\tUpdateObjectCBs(gt);\n\tUpdateMaterialCBs(gt);\n\tUpdateMainPassCB(gt);\n}\n\nvoid HW08App::Draw(const GameTimer& gt)\n{\n\tauto cmdListAlloc = mCurrFrameResource->GetResource<ID3D12CommandAllocator>(\"CommandAllocator\");\n\n    // Reuse the memory associated with command recording.\n    // We can only reset when the associated command lists have finished execution on the GPU.\n    ThrowIfFailed(cmdListAlloc->Reset());\n\n    // A command list can be reset after it has been added to the command queue via ExecuteCommandList.\n    // Reusing the command list reuses memory.\n\tThrowIfFailed(uGCmdList->Reset(cmdListAlloc, nullptr));\n\tuGCmdList.SetDescriptorHeaps(Ubpa::DX12::DescriptorHeapMngr::Instance().GetCSUGpuDH()->GetDescriptorHeap());\n\n\tuGCmdList->RSSetViewports(1, &mScreenViewport);\n\tuGCmdList->RSSetScissorRects(1, &mScissorRect);\n\n\tfg.Clear();\n\tauto fgRsrcMngr = mCurrFrameResource->GetResource<Ubpa::DX12::FG::RsrcMngr>(\"FrameGraphRsrcMngr\");\n\tfgRsrcMngr->NewFrame();\n\tfgExecutor.NewFrame();;\n\n\tauto gbuffer0 = fg.AddResourceNode(\"GBuffer0\");\n\tauto gbuffer1 = fg.AddResourceNode(\"GBuffer1\");\n\tauto gbuffer2 = fg.AddResourceNode(\"GBuffer2\");\n\tauto backbuffer = fg.AddResourceNode(\"Back Buffer\");\n\tauto depthstencil = fg.AddResourceNode(\"Depth Stencil\");\n\tauto gbPass = fg.AddPassNode(\n\t\t\"GBuffer Pass\",\n\t\t{},\n\t\t{ gbuffer0,gbuffer1,gbuffer2,depthstencil }\n\t);\n\t/*auto debugPass = fg.AddPassNode(\n\t\t\"Debug\",\n\t\t{ gbuffer1 },\n\t\t{ backbuffer }\n\t);*/\n\tauto deferLightingPass = fg.AddPassNode(\n\t\t\"Defer Lighting\",\n\t\t{ gbuffer0,gbuffer1,gbuffer2 },\n\t\t{ backbuffer }\n\t);\n\n\t(*fgRsrcMngr)\n\t\t.RegisterTemporalRsrc(gbuffer0,\n\t\t\tUbpa::DX12::FG::RsrcType::RT2D(DXGI_FORMAT_R32G32B32A32_FLOAT, mClientWidth, mClientHeight, Colors::Black))\n\t\t.RegisterTemporalRsrc(gbuffer1,\n\t\t\tUbpa::DX12::FG::RsrcType::RT2D(DXGI_FORMAT_R32G32B32A32_FLOAT, mClientWidth, mClientHeight, Colors::Black))\n\t\t.RegisterTemporalRsrc(gbuffer2,\n\t\t\tUbpa::DX12::FG::RsrcType::RT2D(DXGI_FORMAT_R32G32B32A32_FLOAT, mClientWidth, mClientHeight, Colors::Black))\n\n\t\t.RegisterRsrcTable({\n\t\t\t{gbuffer0,Ubpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT)},\n\t\t\t{gbuffer1,Ubpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT)},\n\t\t\t{gbuffer2,Ubpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT)} })\n\n\t\t.RegisterImportedRsrc(backbuffer, { CurrentBackBuffer(), D3D12_RESOURCE_STATE_PRESENT })\n\t\t.RegisterImportedRsrc(depthstencil, { mDepthStencilBuffer.Get(), D3D12_RESOURCE_STATE_DEPTH_WRITE })\n\n\t\t.RegisterPassRsrcs(gbPass, gbuffer0, D3D12_RESOURCE_STATE_RENDER_TARGET,\n\t\t\tUbpa::DX12::FG::RsrcImplDesc_RTV_Null{})\n\t\t.RegisterPassRsrcs(gbPass, gbuffer1, D3D12_RESOURCE_STATE_RENDER_TARGET,\n\t\t\tUbpa::DX12::FG::RsrcImplDesc_RTV_Null{})\n\t\t.RegisterPassRsrcs(gbPass, gbuffer2, D3D12_RESOURCE_STATE_RENDER_TARGET,\n\t\t\tUbpa::DX12::FG::RsrcImplDesc_RTV_Null{})\n\t\t.RegisterPassRsrcs(gbPass, depthstencil,\n\t\t\tD3D12_RESOURCE_STATE_DEPTH_WRITE, Ubpa::DX12::Desc::DSV::Basic(mDepthStencilFormat))\n\n\t\t/*.RegisterPassRsrcs(debugPass, gbuffer1, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,\n\t\t\tUbpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT))\n\n\t\t.RegisterPassRsrcs(debugPass, backbuffer, D3D12_RESOURCE_STATE_RENDER_TARGET,\n\t\t\tUbpa::DX12::FG::RsrcImplDesc_RTV_Null{})*/\n\n\t\t.RegisterPassRsrcs(deferLightingPass, gbuffer0, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,\n\t\t\tUbpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT))\n\t\t.RegisterPassRsrcs(deferLightingPass, gbuffer1, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,\n\t\t\tUbpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT))\n\t\t.RegisterPassRsrcs(deferLightingPass, gbuffer2, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,\n\t\t\tUbpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT))\n\n\t\t.RegisterPassRsrcs(deferLightingPass, backbuffer, D3D12_RESOURCE_STATE_RENDER_TARGET,\n\t\t\tUbpa::DX12::FG::RsrcImplDesc_RTV_Null{})\n\t\t;\n\n\tfgExecutor.RegisterPassFunc(\n\t\tgbPass,\n\t\t[&](const Ubpa::DX12::FG::PassRsrcs& rsrcs) {\n\t\t\tuGCmdList->SetPipelineState(Ubpa::DXRenderer::Instance().GetPSO(\"geometry\"));\n\t\t\tauto gb0 = rsrcs.find(gbuffer0)->second;\n\t\t\tauto gb1 = rsrcs.find(gbuffer1)->second;\n\t\t\tauto gb2 = rsrcs.find(gbuffer2)->second;\n\t\t\tauto ds = rsrcs.find(depthstencil)->second;\n\n\t\t\t// Clear the render texture and depth buffer.\n\t\t\tuGCmdList.ClearRenderTargetView(gb0.cpuHandle, Colors::Black);\n\t\t\tuGCmdList.ClearRenderTargetView(gb1.cpuHandle, Colors::Black);\n\t\t\tuGCmdList.ClearRenderTargetView(gb2.cpuHandle, Colors::Black);\n\t\t\tuGCmdList.ClearDepthStencilView(ds.cpuHandle);\n\n\t\t\t// Specify the buffers we are going to render to.\n\t\t\tstd::array rts{ gb0.cpuHandle,gb1.cpuHandle,gb2.cpuHandle };\n\t\t\tuGCmdList->OMSetRenderTargets(rts.size(), rts.data(), false, &ds.cpuHandle);\n\n\t\t\tuGCmdList->SetGraphicsRootSignature(Ubpa::DXRenderer::Instance().GetRootSignature(\"geometry\"));\n\n\t\t\tauto passCB = mCurrFrameResource\n\t\t\t\t->GetResource<Ubpa::DX12::ArrayUploadBuffer<PassConstants>>(\"gbPass constants\")\n\t\t\t\t->GetResource();\n\t\t\tuGCmdList->SetGraphicsRootConstantBufferView(2, passCB->GetGPUVirtualAddress());\n\n\t\t\tauto fence2interpidx = [N = InterpNum](size_t n, size_t gap) {\n\t\t\t\tsize_t loop = 2 * N * gap;\n\t\t\t\tsize_t i = (n % loop) / gap;\n\t\t\t\tif (i >= N)\n\t\t\t\t\ti = 2 * N - 1 - i;\n\t\t\t\treturn 2 + i;\n\t\t\t};\n\t\t\tDrawRenderItems(uGCmdList.raw.Get(), { mAllRitems[0].get(), mAllRitems[1].get(), mAllRitems[fence2interpidx(mCurrentFence, 2)].get() });\n\t\t}\n\t);\n\n\t//fgExecutor.RegisterPassFunc(\n\t//\tdebugPass,\n\t//\t[&](const Ubpa::DX12::FG::PassRsrcs& rsrcs) {\n\t//\t\tuGCmdList->SetPipelineState(Ubpa::DXRenderer::Instance().GetPSO(\"screen\"));\n\t//\t\tauto img = rsrcs.find(gbuffer1)->second;\n\t//\t\tauto bb = rsrcs.find(backbuffer)->second;\n\t//\t\t\n\t//\t\t//uGCmdList->CopyResource(bb.resource, rt.resource);\n\n\t//\t\t// Clear the render texture and depth buffer.\n\t//\t\tuGCmdList.ClearRenderTargetView(bb.cpuHandle, Colors::LightSteelBlue);\n\n\t//\t\t// Specify the buffers we are going to render to.\n\t//\t\t//uGCmdList.OMSetRenderTarget(bb.cpuHandle, ds.cpuHandle);\n\t//\t\tuGCmdList->OMSetRenderTargets(1, &bb.cpuHandle, false, nullptr);\n\n\t//\t\tuGCmdList->SetGraphicsRootSignature(Ubpa::DXRenderer::Instance().GetRootSignature(\"screen\"));\n\n\t//\t\tuGCmdList->SetGraphicsRootDescriptorTable(0, img.gpuHandle);\n\n\t//\t\tuGCmdList->IASetVertexBuffers(0, 0, nullptr);\n\t//\t\tuGCmdList->IASetIndexBuffer(nullptr);\n\t//\t\tuGCmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\t//\t\tuGCmdList->DrawInstanced(6, 1, 0, 0);\n\t//\t}\n\t//);\n\n\tfgExecutor.RegisterPassFunc(\n\t\tdeferLightingPass,\n\t\t[&](const Ubpa::DX12::FG::PassRsrcs& rsrcs) {\n\t\t\tuGCmdList->SetPipelineState(Ubpa::DXRenderer::Instance().GetPSO(\"defer lighting\"));\n\t\t\tauto gb0 = rsrcs.find(gbuffer0)->second;\n\t\t\tauto gb1 = rsrcs.find(gbuffer1)->second;\n\t\t\tauto gb2 = rsrcs.find(gbuffer2)->second;\n\n\t\t\tauto bb = rsrcs.find(backbuffer)->second;\n\n\t\t\t//uGCmdList->CopyResource(bb.resource, rt.resource);\n\n\t\t\t// Clear the render texture and depth buffer.\n\t\t\tuGCmdList.ClearRenderTargetView(bb.cpuHandle, Colors::LightSteelBlue);\n\n\t\t\t// Specify the buffers we are going to render to.\n\t\t\t//uGCmdList.OMSetRenderTarget(bb.cpuHandle, ds.cpuHandle);\n\t\t\tuGCmdList->OMSetRenderTargets(1, &bb.cpuHandle, false, nullptr);\n\n\t\t\tuGCmdList->SetGraphicsRootSignature(Ubpa::DXRenderer::Instance().GetRootSignature(\"defer lighting\"));\n\n\t\t\tuGCmdList->SetGraphicsRootDescriptorTable(0, gb0.gpuHandle);\n\n\t\t\tuGCmdList->IASetVertexBuffers(0, 0, nullptr);\n\t\t\tuGCmdList->IASetIndexBuffer(nullptr);\n\t\t\tuGCmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\t\t\tuGCmdList->DrawInstanced(6, 1, 0, 0);\n\t\t}\n\t);\n\n\tstatic bool flag{ false };\n\tif (!flag) {\n\t\tOutputDebugStringA(fg.ToGraphvizGraph().Dump().c_str());\n\t\tflag = true;\n\t}\n\n\tauto [success, crst] = fgCompiler.Compile(fg);\n\tfgExecutor.Execute(crst, *fgRsrcMngr);\n\n    // Done recording commands.\n    ThrowIfFailed(uGCmdList->Close());\n\n    // Add the command list to the queue for execution.\n\tuCmdQueue.Execute(uGCmdList.raw.Get());\n\n    // Swap the back and front buffers\n    ThrowIfFailed(mSwapChain->Present(0, 0));\n\tmCurrBackBuffer = (mCurrBackBuffer + 1) % SwapChainBufferCount;\n\n\tmCurrFrameResource->Signal(uCmdQueue.raw.Get(), ++mCurrentFence);\n}\n\nvoid HW08App::OnMouseDown(WPARAM btnState, int x, int y)\n{\n    mLastMousePos.x = x;\n    mLastMousePos.y = y;\n\n    SetCapture(mhMainWnd);\n}\n\nvoid HW08App::OnMouseUp(WPARAM btnState, int x, int y)\n{\n    ReleaseCapture();\n}\n\nvoid HW08App::OnMouseMove(WPARAM btnState, int x, int y)\n{\n    if((btnState & MK_LBUTTON) != 0)\n    {\n        // Make each pixel correspond to a quarter of a degree.\n        float dx = XMConvertToRadians(0.25f*static_cast<float>(x - mLastMousePos.x));\n        float dy = XMConvertToRadians(0.25f*static_cast<float>(y - mLastMousePos.y));\n\n        // Update angles based on input to orbit camera around box.\n        mTheta += dx;\n        mPhi += dy;\n\n        // Restrict the angle mPhi.\n        mPhi = MathHelper::Clamp(mPhi, 0.1f, MathHelper::Pi - 0.1f);\n    }\n    else if((btnState & MK_RBUTTON) != 0)\n    {\n        // Make each pixel correspond to 0.2 unit in the scene.\n        float dx = 0.05f*static_cast<float>(x - mLastMousePos.x);\n        float dy = 0.05f*static_cast<float>(y - mLastMousePos.y);\n\n        // Update the camera radius based on input.\n        mRadius += dx - dy;\n\n        // Restrict the radius.\n        mRadius = MathHelper::Clamp(mRadius, 2.0f, 150.0f);\n    }\n\n    mLastMousePos.x = x;\n    mLastMousePos.y = y;\n}\n \nvoid HW08App::OnKeyboardInput(const GameTimer& gt)\n{\n}\n \nvoid HW08App::UpdateCamera(const GameTimer& gt)\n{\n\t// Convert Spherical to Cartesian coordinates.\n\tmEyePos.x = mRadius*sinf(mPhi)*cosf(mTheta);\n\tmEyePos.z = mRadius*sinf(mPhi)*sinf(mTheta);\n\tmEyePos.y = mRadius*cosf(mPhi);\n\n\t// Build the view matrix.\n\tXMVECTOR pos = XMVectorSet(mEyePos.x, mEyePos.y, mEyePos.z, 1.0f);\n\tXMVECTOR target = XMVectorZero();\n\tXMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);\n\n\tXMMATRIX view = XMMatrixLookAtLH(pos, target, up);\n\tXMStoreFloat4x4(&mView, view);\n}\n\nvoid HW08App::AnimateMaterials(const GameTimer& gt)\n{\n\t\n}\n\nvoid HW08App::UpdateObjectCBs(const GameTimer& gt)\n{\n\tauto currObjectCB = mCurrFrameResource\n\t\t->GetResource<Ubpa::DX12::ArrayUploadBuffer<ObjectConstants>>(\"ArrayUploadBuffer<ObjectConstants>\");\n\tfor(auto& e : mAllRitems)\n\t{\n\t\t// Only update the cbuffer data if the constants have changed.  \n\t\t// This needs to be tracked per frame resource.\n\t\tif(e->NumFramesDirty > 0)\n\t\t{\n\t\t\tXMMATRIX world = XMLoadFloat4x4(&e->World);\n\t\t\tXMMATRIX texTransform = XMLoadFloat4x4(&e->TexTransform);\n\n\t\t\tObjectConstants objConstants;\n\t\t\tXMStoreFloat4x4(&objConstants.World, XMMatrixTranspose(world));\n\t\t\tXMStoreFloat4x4(&objConstants.TexTransform, XMMatrixTranspose(texTransform));\n\n\t\t\tcurrObjectCB->Set(e->ObjCBIndex, objConstants);\n\n\t\t\t// Next FrameResource need to be updated too.\n\t\t\te->NumFramesDirty--;\n\t\t}\n\t}\n}\n\nvoid HW08App::UpdateMaterialCBs(const GameTimer& gt)\n{\n\tauto currMaterialCB = mCurrFrameResource\n\t\t->GetResource<Ubpa::DX12::ArrayUploadBuffer<MaterialConstants>>(\"ArrayUploadBuffer<MaterialConstants>\");\n\tfor(auto& e : mMaterials)\n\t{\n\t\t// Only update the cbuffer data if the constants have changed.  If the cbuffer\n\t\t// data changes, it needs to be updated for each FrameResource.\n\t\tMaterial* mat = e.second.get();\n\t\tif(mat->NumFramesDirty > 0)\n\t\t{\n\t\t\tXMMATRIX matTransform = XMLoadFloat4x4(&mat->MatTransform);\n\n\t\t\tMaterialConstants matConstants;\n\t\t\tmatConstants.DiffuseAlbedo = mat->DiffuseAlbedo;\n\t\t\tmatConstants.FresnelR0 = mat->FresnelR0;\n\t\t\tmatConstants.Roughness = mat->Roughness;\n\t\t\tXMStoreFloat4x4(&matConstants.MatTransform, XMMatrixTranspose(matTransform));\n\n\t\t\tcurrMaterialCB->Set(mat->MatCBIndex, matConstants);\n\n\t\t\t// Next FrameResource need to be updated too.\n\t\t\tmat->NumFramesDirty--;\n\t\t}\n\t}\n}\n\nvoid HW08App::UpdateMainPassCB(const GameTimer& gt)\n{\n\tXMMATRIX view = XMLoadFloat4x4(&mView);\n\tXMMATRIX proj = XMLoadFloat4x4(&mProj);\n\n\tXMMATRIX viewProj = XMMatrixMultiply(view, proj);\n\tXMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(view), view);\n\tXMMATRIX invProj = XMMatrixInverse(&XMMatrixDeterminant(proj), proj);\n\tXMMATRIX invViewProj = XMMatrixInverse(&XMMatrixDeterminant(viewProj), viewProj);\n\n\tXMStoreFloat4x4(&mMainPassCB.View, XMMatrixTranspose(view));\n\tXMStoreFloat4x4(&mMainPassCB.InvView, XMMatrixTranspose(invView));\n\tXMStoreFloat4x4(&mMainPassCB.Proj, XMMatrixTranspose(proj));\n\tXMStoreFloat4x4(&mMainPassCB.InvProj, XMMatrixTranspose(invProj));\n\tXMStoreFloat4x4(&mMainPassCB.ViewProj, XMMatrixTranspose(viewProj));\n\tXMStoreFloat4x4(&mMainPassCB.InvViewProj, XMMatrixTranspose(invViewProj));\n\tmMainPassCB.EyePosW = mEyePos;\n\tmMainPassCB.RenderTargetSize = XMFLOAT2((float)mClientWidth, (float)mClientHeight);\n\tmMainPassCB.InvRenderTargetSize = XMFLOAT2(1.0f / mClientWidth, 1.0f / mClientHeight);\n\tmMainPassCB.NearZ = 1.0f;\n\tmMainPassCB.FarZ = 1000.0f;\n\tmMainPassCB.TotalTime = gt.TotalTime();\n\tmMainPassCB.DeltaTime = gt.DeltaTime();\n\tmMainPassCB.AmbientLight = { 0.25f, 0.25f, 0.35f, 1.0f };\n\tmMainPassCB.Lights[0].Direction = { 0.57735f, -0.57735f, 0.57735f };\n\tmMainPassCB.Lights[0].Strength = { 0.6f, 0.6f, 0.6f };\n\tmMainPassCB.Lights[1].Direction = { -0.57735f, -0.57735f, 0.57735f };\n\tmMainPassCB.Lights[1].Strength = { 0.3f, 0.3f, 0.3f };\n\tmMainPassCB.Lights[2].Direction = { 0.0f, -0.707f, -0.707f };\n\tmMainPassCB.Lights[2].Strength = { 0.15f, 0.15f, 0.15f };\n\n\tauto currPassCB = mCurrFrameResource\n\t\t->GetResource<Ubpa::DX12::ArrayUploadBuffer<PassConstants>>(\"gbPass constants\");\n\tcurrPassCB->Set(0, mMainPassCB);\n}\n\nvoid HW08App::LoadTextures()\n{\n\tstd::array<std::wstring_view, 3> ironTextures{\n\t\tL\"../data/textures/iron/albedo.dds\",\n\t\tL\"../data/textures/iron/roughness.dds\",\n\t\tL\"../data/textures/iron/metalness.dds\"\n\t};\n\n\tUbpa::DXRenderer::Instance().RegisterDDSTextureArrayFromFile(\n\t\tUbpa::DXRenderer::Instance().GetUpload(),\n\t\t\"iron\",\n\t\tironTextures.data(), ironTextures.size());\n}\n\nvoid HW08App::BuildRootSignature()\n{\n\t{ // geometry\n\t\tCD3DX12_DESCRIPTOR_RANGE texTable;\n\t\ttexTable.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 3, 0);\n\n\t\t// Root parameter can be a table, root descriptor or root constants.\n\t\tCD3DX12_ROOT_PARAMETER slotRootParameter[4];\n\n\t\t// Perfomance TIP: Order from most frequent to least frequent.\n\t\tslotRootParameter[0].InitAsDescriptorTable(1, &texTable, D3D12_SHADER_VISIBILITY_PIXEL);\n\t\tslotRootParameter[1].InitAsConstantBufferView(0);\n\t\tslotRootParameter[2].InitAsConstantBufferView(1);\n\t\tslotRootParameter[3].InitAsConstantBufferView(2);\n\n\t\tauto staticSamplers = GetStaticSamplers();\n\n\t\t// A root signature is an array of root parameters.\n\t\tCD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(4, slotRootParameter,\n\t\t\t(UINT)staticSamplers.size(), staticSamplers.data(),\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);\n\n\t\tUbpa::DXRenderer::Instance().RegisterRootSignature(\"geometry\", &rootSigDesc);\n\t}\n\n\t{ // screen\n\t\tCD3DX12_DESCRIPTOR_RANGE texTable;\n\t\ttexTable.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0);\n\n\t\t// Root parameter can be a table, root descriptor or root constants.\n\t\tCD3DX12_ROOT_PARAMETER slotRootParameter[1];\n\n\t\t// Perfomance TIP: Order from most frequent to least frequent.\n\t\tslotRootParameter[0].InitAsDescriptorTable(1, &texTable, D3D12_SHADER_VISIBILITY_PIXEL);\n\n\t\tauto staticSamplers = GetStaticSamplers();\n\n\t\t// A root signature is an array of root parameters.\n\t\tCD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(1, slotRootParameter,\n\t\t\t(UINT)staticSamplers.size(), staticSamplers.data(),\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);\n\n\t\tUbpa::DXRenderer::Instance().RegisterRootSignature(\"screen\", &rootSigDesc);\n\t}\n\t{ // defer lighting\n\t\tCD3DX12_DESCRIPTOR_RANGE texTable;\n\t\ttexTable.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 3, 0);\n\n\t\t// Root parameter can be a table, root descriptor or root constants.\n\t\tCD3DX12_ROOT_PARAMETER slotRootParameter[4];\n\n\t\t// Perfomance TIP: Order from most frequent to least frequent.\n\t\tslotRootParameter[0].InitAsDescriptorTable(1, &texTable, D3D12_SHADER_VISIBILITY_PIXEL);\n\t\tslotRootParameter[1].InitAsConstantBufferView(0);\n\t\tslotRootParameter[2].InitAsConstantBufferView(1);\n\t\tslotRootParameter[3].InitAsConstantBufferView(2);\n\n\t\tauto staticSamplers = GetStaticSamplers();\n\n\t\t// A root signature is an array of root parameters.\n\t\tCD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(4, slotRootParameter,\n\t\t\t(UINT)staticSamplers.size(), staticSamplers.data(),\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);\n\n\t\tUbpa::DXRenderer::Instance().RegisterRootSignature(\"defer lighting\", &rootSigDesc);\n\t}\n}\n\nvoid HW08App::BuildDescriptorHeaps()\n{\n}\n\nvoid HW08App::BuildShadersAndInputLayout()\n{\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"standardVS\",\n\t\tL\"..\\\\data\\\\shaders\\\\Default.hlsl\", nullptr, \"VS\", \"vs_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"opaquePS\",\n\t\tL\"..\\\\data\\\\shaders\\\\Default.hlsl\", nullptr, \"PS\", \"ps_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"screenVS\",\n\t\tL\"..\\\\data\\\\shaders\\\\Screen.hlsl\", nullptr, \"VS\", \"vs_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"screenPS\",\n\t\tL\"..\\\\data\\\\shaders\\\\Screen.hlsl\", nullptr, \"PS\", \"ps_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"geometryVS\",\n\t\tL\"..\\\\data\\\\shaders\\\\Geometry.hlsl\", nullptr, \"VS\", \"vs_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"geometryPS\",\n\t\tL\"..\\\\data\\\\shaders\\\\Geometry.hlsl\", nullptr, \"PS\", \"ps_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"deferLightingVS\",\n\t\tL\"..\\\\data\\\\shaders\\\\deferLighting.hlsl\", nullptr, \"VS\", \"vs_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"deferLightingPS\",\n\t\tL\"..\\\\data\\\\shaders\\\\deferLighting.hlsl\", nullptr, \"PS\", \"ps_5_0\");\n\t\n    mInputLayout =\n    {\n        { \"POSITION\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n        { \"NORMAL\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }\n    };\n}\n\nvoid HW08App::BuildShapeGeometry()\n{\n\tstd::vector<Vertex> start_vertices;\n\tstd::vector<Vertex> end_vertices;\n\tstd::vector<std::vector<Vertex>> interp_vertices_arr(InterpNum);\n\tstd::vector<std::uint32_t> indices;\n\n\tauto obj_source = std::make_unique<Ubpa::TriMesh>(\"../data/meshes/horse_source.obj\");\n\tauto obj_target = std::make_unique<Ubpa::TriMesh>(\"../data/meshes/horse_target.obj\");\n\t/*auto obj_source = std::make_unique<Ubpa::TriMesh>(\"../data/meshes/leaf_source.obj\");\n\tauto obj_target = std::make_unique<Ubpa::TriMesh>(\"../data/meshes/leaf_target.obj\");*/\n\t/*auto obj_source = std::make_unique<Ubpa::TriMesh>(\"../data/meshes/rabbit_source.obj\");\n\tauto obj_target = std::make_unique<Ubpa::TriMesh>(\"../data/meshes/rabbit_target.obj\");*/\n\n\t/*obj_source->CombineSamePositionVertex();\n\tobj_source->ScaleToUnit();\n\tobj_target->CombineSamePositionVertex();\n\tobj_target->ScaleToUnit();*/\n\n\tstart_vertices.resize(obj_source->VertexNumber());\n\tend_vertices.resize(obj_source->VertexNumber());\n\tfor (auto& vertices : interp_vertices_arr)\n\t\tvertices.resize(obj_source->VertexNumber());\n\tindices.resize(3 * obj_source->TriangleNumber());\n\tfor (size_t i = 0; i < obj_source->VertexNumber(); i++) {\n\t\tstart_vertices[i].Pos = obj_source->positions[i].as<XMFLOAT3>();\n\t\tend_vertices[i].Pos   = obj_target->positions[i].as<XMFLOAT3>();\n\n\t\tstart_vertices[i].Normal = obj_source->normals[i].as<XMFLOAT3>();\n\t\tfor (auto& vertices : interp_vertices_arr)\n\t\t\tvertices[i].Normal = obj_target->normals[i].as<XMFLOAT3>();\n\t\tend_vertices[i].Normal = obj_target->normals[i].as<XMFLOAT3>();\n\n\t\tstart_vertices[i].TexC = obj_source->texcoords[i].as<XMFLOAT2>();\n\t\tfor (auto& vertices : interp_vertices_arr)\n\t\t\tvertices[i].TexC = obj_target->texcoords[i].as<XMFLOAT2>();\n\t\tend_vertices[i].TexC = obj_target->texcoords[i].as<XMFLOAT2>();\n\t}\n\tfor (size_t i = 0; i < obj_source->TriangleNumber(); i++) {\n\t\tindices[3 * i + 0] = obj_source->indices[i][0];\n\t\tindices[3 * i + 1] = obj_source->indices[i][1];\n\t\tindices[3 * i + 2] = obj_source->indices[i][2];\n\t}\n\n\tUbpa::HEMesh<Ubpa::HEMeshTriats_EmptyE<V, F, H>> hemesh(std::vector<size_t>{indices.begin(), indices.end()}, 3);\n\tassert(hemesh.IsValid() && hemesh.IsTriMesh() && hemesh.NumBoundaries() == 1);\n\n\tfor (size_t i = 0; i < start_vertices.size(); i++) {\n\t\themesh.Vertices().at(i)->p = obj_source->positions[i].cast_to<Ubpa::pointf2>();\n\t\themesh.Vertices().at(i)->q = obj_target->positions[i].cast_to<Ubpa::pointf2>();\n\t}\n\n\t// compute area, cot_theta\n\tfor (auto tri : hemesh.Polygons()) {\n\t\tauto he01 = tri->HalfEdge();\n\t\tauto he12 = he01->Next();\n\t\tauto he20 = he12->Next();\n\n\t\tauto v0 = he01->Origin();\n\t\tauto v1 = he12->Origin();\n\t\tauto v2 = he20->Origin();\n\n\t\tauto p0_p1 = v1->p - v0->p;\n\t\tauto p0_p2 = v2->p - v0->p;\n\t\tauto p1_p2 = v2->p - v1->p;\n\t\tauto p1_p0 = -p0_p1;\n\t\tauto p2_p0 = -p0_p2;\n\t\tauto p2_p1 = -p1_p2;\n\n\t\ttri->area = 0.5f * std::sqrt(std::max(0.f,1 - Ubpa::pow2(p0_p1.cos_theta(p0_p2)))) * p0_p1.norm() * p0_p2.norm();\n\n\t\the01->cot_theta = p2_p0.cot_theta(p2_p1);\n\t\the12->cot_theta = p0_p1.cot_theta(p0_p2);\n\t\the20->cot_theta = p1_p2.cot_theta(p1_p0);\n\t}\n\n\tfor (auto tri : hemesh.Polygons())\n\t\ttri->Init();\n\n\t// fix 1 vertex\n\tauto fix_v0 = hemesh.Vertices().front();\n\tauto fix_idx0 = static_cast<int>(hemesh.Index(fix_v0));\n\n\t// pre-compute A\n\tsize_t N = hemesh.Vertices().size();\n\tEigen::SparseMatrix<float> global_A(N, N);\n\tstd::vector<Eigen::Triplet<float>> global_triplets;\n\tglobal_triplets.emplace_back(fix_idx0, fix_idx0, 1.f);\n\tfor (auto vi : hemesh.Vertices()) {\n\t\tauto i = static_cast<int>(hemesh.Index(vi));\n\t\tif (vi == fix_v0)\n\t\t\tcontinue;\n\t\tfloat diag = 0.f;\n\t\tfor (auto he_ij : vi->OutHalfEdges()) {\n\t\t\tauto he_ji = he_ij->Pair();\n\t\t\tauto vj = he_ji->Origin();\n\t\t\tauto j = static_cast<int>(hemesh.Index(vj));\n\t\t\tfloat cot_theta_ij = he_ij->cot_theta; // if he_ij is boundary, cot_theta_ij == 0\n\t\t\tfloat cot_theta_ji = he_ji->cot_theta; // if he_ji is boundary, cot_theta_ji == 0\n\t\t\tglobal_triplets.emplace_back(i, j, -(cot_theta_ij + cot_theta_ji));\n\n\t\t\tdiag += cot_theta_ij + cot_theta_ji;\n\t\t}\n\t\tglobal_triplets.emplace_back(i, i, diag);\n\t}\n\tglobal_A.setFromTriplets(global_triplets.begin(), global_triplets.end());\n\tEigen::SparseLU<Eigen::SparseMatrix<float>, Eigen::COLAMDOrdering<int>> global_solver;\n\tglobal_solver.analyzePattern(global_A);\n\tglobal_solver.factorize(global_A);\n\n\tfor (size_t curInterp = 0; curInterp < InterpNum; curInterp++) {\n\t\tfloat t = static_cast<float>(curInterp) / static_cast<float>(InterpNum);\n\n\t\t// local\n\t\tfor (auto tri : hemesh.Polygons())\n\t\t\ttri->UpdateLt(t);\n\n\t\t// global\n\t\tEigen::MatrixXf global_B(N, 2);\n\t\tglobal_B.setZero();\n\t\tauto fix_v0_t = fix_v0->p.lerp(fix_v0->q, t);\n\t\tglobal_B(fix_idx0, 0) = fix_v0_t[0];\n\t\tglobal_B(fix_idx0, 1) = fix_v0_t[1];\n\t\tfor (auto vi : hemesh.Vertices()) {\n\t\t\tif (vi == fix_v0)\n\t\t\t\tcontinue;\n\n\t\t\tauto i = static_cast<int>(hemesh.Index(vi));\n\t\t\tfor (auto he_ij : vi->OutHalfEdges()) {\n\t\t\t\tauto he_ji = he_ij->Pair();\n\t\t\t\tauto vj = he_ji->Origin();\n\n\t\t\t\tif (he_ij->Polygon() != nullptr) {\n\t\t\t\t\tauto w_dp_ij = he_ij->cot_theta * he_ij->Polygon()->Lt * (vi->p - vj->p);\n\t\t\t\t\tglobal_B(i, 0) += w_dp_ij[0];\n\t\t\t\t\tglobal_B(i, 1) += w_dp_ij[1];\n\t\t\t\t}\n\n\t\t\t\tif (he_ji->Polygon() != nullptr) {\n\t\t\t\t\tauto w_dp_ji = he_ji->cot_theta * he_ji->Polygon()->Lt * (vj->p - vi->p);\n\t\t\t\t\tglobal_B(i, 0) -= w_dp_ji[0];\n\t\t\t\t\tglobal_B(i, 1) -= w_dp_ji[1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tEigen::MatrixXf X = global_solver.solve(global_B);\n\t\tfor (auto v : hemesh.Vertices()) {\n\t\t\tauto idx = hemesh.Index(v);\n\t\t\tinterp_vertices_arr[curInterp][idx].Pos.x = X(idx, 0);\n\t\t\tinterp_vertices_arr[curInterp][idx].Pos.y = X(idx, 1);\n\t\t\tinterp_vertices_arr[curInterp][idx].Pos.z = 0.f;\n\t\t}\n\t}\n\n\tUbpa::DX12::SubmeshGeometry objSubmesh;\n\tobjSubmesh.IndexCount = obj_source->indices.size() * 3;\n\tobjSubmesh.StartIndexLocation = 0;\n\tobjSubmesh.BaseVertexLocation = 0;\n\tUbpa::DXRenderer::Instance()\n\t\t.RegisterStaticMeshGeometry(\n\t\t\tUbpa::DXRenderer::Instance().GetUpload(), \"start_objGeo\",\n\t\t\tstart_vertices.data(), (UINT)start_vertices.size(), sizeof(Vertex),\n\t\t\tindices.data(), (UINT)indices.size(), DXGI_FORMAT_R32_UINT)\n\t\t.submeshGeometries[\"obj\"] = objSubmesh;\n\tUbpa::DXRenderer::Instance()\n\t\t.RegisterStaticMeshGeometry(\n\t\t\tUbpa::DXRenderer::Instance().GetUpload(), \"end_objGeo\",\n\t\t\tend_vertices.data(), (UINT)end_vertices.size(), sizeof(Vertex),\n\t\t\tindices.data(), (UINT)indices.size(), DXGI_FORMAT_R32_UINT)\n\t\t.submeshGeometries[\"obj\"] = objSubmesh;\n\tfor (size_t i = 0; i < InterpNum; i++) {\n\t\tUbpa::DXRenderer::Instance()\n\t\t\t.RegisterStaticMeshGeometry(\n\t\t\t\tUbpa::DXRenderer::Instance().GetUpload(), \"interp_\" + std::to_string(i) + \"_objGeo\",\n\t\t\t\tinterp_vertices_arr[i].data(), (UINT)interp_vertices_arr[i].size(), sizeof(Vertex),\n\t\t\t\tindices.data(), (UINT)indices.size(), DXGI_FORMAT_R32_UINT)\n\t\t\t.submeshGeometries[\"obj\"] = objSubmesh;\n\t}\n\n\ttrimeshes.emplace(\"obj_source\", std::move(obj_source));\n\ttrimeshes.emplace(\"obj_target\", std::move(obj_target));\n}\n\nvoid HW08App::BuildPSOs()\n{\n\tauto screenPsoDesc = Ubpa::DX12::Desc::PSO::Basic(\n\t\tUbpa::DXRenderer::Instance().GetRootSignature(\"screen\"),\n\t\tnullptr, 0,\n\t\tUbpa::DXRenderer::Instance().GetShaderByteCode(\"screenVS\"),\n\t\tUbpa::DXRenderer::Instance().GetShaderByteCode(\"screenPS\"),\n\t\tmBackBufferFormat,\n\t\tDXGI_FORMAT_UNKNOWN\n\t);\n\tUbpa::DXRenderer::Instance().RegisterPSO(\"screen\", &screenPsoDesc);\n\n\tauto geometryPsoDesc = Ubpa::DX12::Desc::PSO::MRT(\n\t\tUbpa::DXRenderer::Instance().GetRootSignature(\"geometry\"),\n\t\tmInputLayout.data(), (UINT)mInputLayout.size(),\n\t\tUbpa::DXRenderer::Instance().GetShaderByteCode(\"geometryVS\"),\n\t\tUbpa::DXRenderer::Instance().GetShaderByteCode(\"geometryPS\"),\n\t\t3,\n\t\tDXGI_FORMAT_R32G32B32A32_FLOAT,\n\t\tmDepthStencilFormat\n\t);\n\tgeometryPsoDesc.RasterizerState.FillMode = D3D12_FILL_MODE_WIREFRAME;\n\tUbpa::DXRenderer::Instance().RegisterPSO(\"geometry\", &geometryPsoDesc);\n\n\tauto deferLightingPsoDesc = Ubpa::DX12::Desc::PSO::Basic(\n\t\tUbpa::DXRenderer::Instance().GetRootSignature(\"defer lighting\"),\n\t\tnullptr, 0,\n\t\tUbpa::DXRenderer::Instance().GetShaderByteCode(\"deferLightingVS\"),\n\t\tUbpa::DXRenderer::Instance().GetShaderByteCode(\"deferLightingPS\"),\n\t\tmBackBufferFormat,\n\t\tDXGI_FORMAT_UNKNOWN\n\t);\n\tUbpa::DXRenderer::Instance().RegisterPSO(\"defer lighting\", &deferLightingPsoDesc);\n}\n\nvoid HW08App::BuildFrameResources()\n{\n    for(int i = 0; i < gNumFrameResources; ++i)\n    {\n\t\tauto fr = std::make_unique<Ubpa::DX12::FrameResource>(mFence.Get());\n\n\t\tID3D12CommandAllocator* allocator;\n\t\tThrowIfFailed(uDevice->CreateCommandAllocator(\n\t\t\tD3D12_COMMAND_LIST_TYPE_DIRECT,\n\t\t\tIID_PPV_ARGS(&allocator)));\n\n\t\tfr->RegisterResource(\"CommandAllocator\", allocator, [](void* allocator) {\n\t\t\treinterpret_cast<ID3D12CommandAllocator*>(allocator)->Release();\n\t\t});\n\n\t\tfr->RegisterResource(\"gbPass constants\",\n\t\t\tnew Ubpa::DX12::ArrayUploadBuffer<PassConstants>{ uDevice.raw.Get(), 1, true });\n\n\t\tfr->RegisterResource(\"ArrayUploadBuffer<MaterialConstants>\",\n\t\t\tnew Ubpa::DX12::ArrayUploadBuffer<MaterialConstants>{ uDevice.raw.Get(), mMaterials.size(), true });\n\n\t\tfr->RegisterResource(\"ArrayUploadBuffer<ObjectConstants>\",\n\t\t\tnew Ubpa::DX12::ArrayUploadBuffer<ObjectConstants>{ uDevice.raw.Get(), mAllRitems.size(), true });\n\n\t\tauto fgRsrcMngr = new Ubpa::DX12::FG::RsrcMngr;\n\t\tfgRsrcMngr->Init(uGCmdList, uDevice);\n\t\tfr->RegisterResource(\"FrameGraphRsrcMngr\", fgRsrcMngr);\n\n\t\tmFrameResources.emplace_back(std::move(fr));\n    }\n}\n\nvoid HW08App::BuildMaterials()\n{\n\tauto iron = std::make_unique<Material>();\n\tiron->Name = \"iron\";\n\tiron->MatCBIndex = 0;\n\tiron->DiffuseSrvGpuHandle = Ubpa::DXRenderer::Instance().GetTextureSrvGpuHandle(\"iron\");\n\tiron->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);\n\tiron->FresnelR0 = XMFLOAT3(0.05f, 0.05f, 0.05f);\n\tiron->Roughness = 0.2f;\n\n\tmMaterials[\"iron\"] = std::move(iron);\n}\n\nvoid HW08App::BuildRenderItems()\n{\n\tauto start_objRitem = std::make_unique<RenderItem>();\n\tstart_objRitem->World = Ubpa::transformf(Ubpa::pointf3{ 1,1,0 }, Ubpa::quatf{ {0,1,0}, Ubpa::to_radian(180.f) }).as<XMFLOAT4X4>();\n\tstart_objRitem->ObjCBIndex = 0;\n\tstart_objRitem->Mat = mMaterials[\"iron\"].get();\n\tstart_objRitem->Geo = &Ubpa::DXRenderer::Instance().GetMeshGeometry(\"start_objGeo\");\n\tstart_objRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;\n\tstart_objRitem->IndexCount = start_objRitem->Geo->submeshGeometries[\"obj\"].IndexCount;\n\tstart_objRitem->StartIndexLocation = start_objRitem->Geo->submeshGeometries[\"obj\"].StartIndexLocation;\n\tstart_objRitem->BaseVertexLocation = start_objRitem->Geo->submeshGeometries[\"obj\"].BaseVertexLocation;\n\tmAllRitems.push_back(std::move(start_objRitem));\n\n\tauto end_objRitem = std::make_unique<RenderItem>();\n\tend_objRitem->World = Ubpa::transformf(Ubpa::pointf3{ 1,-1,0 }, Ubpa::quatf{ {0,1,0}, Ubpa::to_radian(180.f) }).as<XMFLOAT4X4>();\n\tend_objRitem->ObjCBIndex = 1;\n\tend_objRitem->Mat = mMaterials[\"iron\"].get();\n\tend_objRitem->Geo = &Ubpa::DXRenderer::Instance().GetMeshGeometry(\"end_objGeo\");\n\tend_objRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;\n\tend_objRitem->IndexCount = end_objRitem->Geo->submeshGeometries[\"obj\"].IndexCount;\n\tend_objRitem->StartIndexLocation = end_objRitem->Geo->submeshGeometries[\"obj\"].StartIndexLocation;\n\tend_objRitem->BaseVertexLocation = end_objRitem->Geo->submeshGeometries[\"obj\"].BaseVertexLocation;\n\tmAllRitems.push_back(std::move(end_objRitem));\n\n\tfor (size_t i = 0; i < InterpNum; i++) {\n\t\tauto interp_objRitem = std::make_unique<RenderItem>();\n\t\tinterp_objRitem->World = Ubpa::transformf(Ubpa::pointf3{ -1,0,0 }, Ubpa::quatf{ {0,1,0}, Ubpa::to_radian(180.f) })\n\t\t\t.as<XMFLOAT4X4>();\n\t\tinterp_objRitem->ObjCBIndex = 2 + i;\n\t\tinterp_objRitem->Mat = mMaterials[\"iron\"].get();\n\t\tinterp_objRitem->Geo = &Ubpa::DXRenderer::Instance().GetMeshGeometry(\"interp_\" + std::to_string(i) + \"_objGeo\");\n\t\tinterp_objRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;\n\t\tinterp_objRitem->IndexCount = interp_objRitem->Geo->submeshGeometries[\"obj\"].IndexCount;\n\t\tinterp_objRitem->StartIndexLocation = interp_objRitem->Geo->submeshGeometries[\"obj\"].StartIndexLocation;\n\t\tinterp_objRitem->BaseVertexLocation = interp_objRitem->Geo->submeshGeometries[\"obj\"].BaseVertexLocation;\n\t\tmAllRitems.push_back(std::move(interp_objRitem));\n\t}\n\n\t// All the render items are opaque.\n\tfor(auto& e : mAllRitems)\n\t\tmOpaqueRitems.push_back(e.get());\n}\n\nvoid HW08App::DrawRenderItems(ID3D12GraphicsCommandList* cmdList, const std::vector<RenderItem*>& ritems)\n{\n    UINT objCBByteSize = Ubpa::DX12::Util::CalcConstantBufferByteSize(sizeof(ObjectConstants));\n    UINT matCBByteSize = Ubpa::DX12::Util::CalcConstantBufferByteSize(sizeof(MaterialConstants));\n \n\tauto objectCB = mCurrFrameResource\n\t\t->GetResource<Ubpa::DX12::ArrayUploadBuffer<ObjectConstants>>(\"ArrayUploadBuffer<ObjectConstants>\")\n\t\t->GetResource();\n\tauto matCB = mCurrFrameResource\n\t\t->GetResource<Ubpa::DX12::ArrayUploadBuffer<MaterialConstants>>(\"ArrayUploadBuffer<MaterialConstants>\")\n\t\t->GetResource();\n\n    // For each render item...\n    for(size_t i = 0; i < ritems.size(); ++i)\n    {\n        auto ri = ritems[i];\n\n        cmdList->IASetVertexBuffers(0, 1, &ri->Geo->VertexBufferView());\n        cmdList->IASetIndexBuffer(&ri->Geo->IndexBufferView());\n        cmdList->IASetPrimitiveTopology(ri->PrimitiveType);\n\n        D3D12_GPU_VIRTUAL_ADDRESS objCBAddress = objectCB->GetGPUVirtualAddress() + ri->ObjCBIndex*objCBByteSize;\n\t\tD3D12_GPU_VIRTUAL_ADDRESS matCBAddress = matCB->GetGPUVirtualAddress() + ri->Mat->MatCBIndex*matCBByteSize;\n\n\t\tcmdList->SetGraphicsRootDescriptorTable(0, ri->Mat->DiffuseSrvGpuHandle);\n        cmdList->SetGraphicsRootConstantBufferView(1, objCBAddress);\n        cmdList->SetGraphicsRootConstantBufferView(3, matCBAddress);\n\n        cmdList->DrawIndexedInstanced(ri->IndexCount, 1, ri->StartIndexLocation, ri->BaseVertexLocation, 0);\n    }\n}\n\nstd::array<const CD3DX12_STATIC_SAMPLER_DESC, 6> HW08App::GetStaticSamplers()\n{\n\t// Applications usually only need a handful of samplers.  So just define them all up front\n\t// and keep them available as part of the root signature.  \n\n\tconst CD3DX12_STATIC_SAMPLER_DESC pointWrap(\n\t\t0, // shaderRegister\n\t\tD3D12_FILTER_MIN_MAG_MIP_POINT, // filter\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressU\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressV\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP); // addressW\n\n\tconst CD3DX12_STATIC_SAMPLER_DESC pointClamp(\n\t\t1, // shaderRegister\n\t\tD3D12_FILTER_MIN_MAG_MIP_POINT, // filter\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressU\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressV\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP); // addressW\n\n\tconst CD3DX12_STATIC_SAMPLER_DESC linearWrap(\n\t\t2, // shaderRegister\n\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR, // filter\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressU\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressV\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP); // addressW\n\n\tconst CD3DX12_STATIC_SAMPLER_DESC linearClamp(\n\t\t3, // shaderRegister\n\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR, // filter\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressU\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressV\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP); // addressW\n\n\tconst CD3DX12_STATIC_SAMPLER_DESC anisotropicWrap(\n\t\t4, // shaderRegister\n\t\tD3D12_FILTER_ANISOTROPIC, // filter\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressU\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressV\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressW\n\t\t0.0f,                             // mipLODBias\n\t\t8);                               // maxAnisotropy\n\n\tconst CD3DX12_STATIC_SAMPLER_DESC anisotropicClamp(\n\t\t5, // shaderRegister\n\t\tD3D12_FILTER_ANISOTROPIC, // filter\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressU\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressV\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressW\n\t\t0.0f,                              // mipLODBias\n\t\t8);                                // maxAnisotropy\n\n\treturn { \n\t\tpointWrap, pointClamp,\n\t\tlinearWrap, linearClamp, \n\t\tanisotropicWrap, anisotropicClamp };\n}\n\n", "meta": {"hexsha": "939ad46aca6ece1315aca70f5fd3d8440b6ab527", "size": 44295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020Spring/DGP/homeworks/08/src/app/main.cpp", "max_stars_repo_name": "Ubpa/MasterCourses", "max_stars_repo_head_hexsha": "46ea8ae8088d5787af277d33beabd02a2766fcc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-09-10T13:25:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T16:01:03.000Z", "max_issues_repo_path": "2020Spring/DGP/homeworks/08/src/app/main.cpp", "max_issues_repo_name": "Ubpa/MasterCourses", "max_issues_repo_head_hexsha": "46ea8ae8088d5787af277d33beabd02a2766fcc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020Spring/DGP/homeworks/08/src/app/main.cpp", "max_forks_repo_name": "Ubpa/MasterCourses", "max_forks_repo_head_hexsha": "46ea8ae8088d5787af277d33beabd02a2766fcc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T09:30:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-04T09:30:48.000Z", "avg_line_length": 35.7506053269, "max_line_length": 139, "alphanum_fraction": 0.720149001, "num_tokens": 13743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5081272619591907}}
{"text": "\n#include\"random.hpp\"\n#include\"stdio.h\"\n#include\"stdlib.h\"\n#include\"useful/useful_plots.h\"\n#include\"time.h\"\n#include<boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include<boost/random/linear_congruential.hpp>\n#include\"Random.h\"\n#include\"Boost_Random.h\"\n#include\"Standard_Random.h\"\n#include\"State_of_Art_Random.h\"\n\nint main()\n{\n\tint i;\n\tsrand(time(NULL));\n\n\tdouble results[1000000];\n/*\t\n\tfor(i=0;i<1000000;++i)\n\t{\n\t\t//results[i]= rand()%101;\n\t\tresults[i]= (rand()/(float)RAND_MAX); //(0,1)\n\t}\n\n\t//printf(\"%d\\n\",RAND_MAX);\n\n\tplotHistogram(\"rand_results\",results,1000000);\n*/\t\n\n\t/*\n\trandomG* random= new randomG();\n\n\trandom->randomize(0.345356);\n\n\tfor(i=0;i<1000000;++i)\n\t{\n\t\t//results[i]= (int)random->uniform(0,100);\n\t\tresults[i]= random->uniform((double)0.00,(double)1.00);\n\t}\n\n\tplotHistogram(\"goldberg_random_results\",results,1000000);\n*/\n\n\n\n\tRandom* r= new State_of_Art_Random(42u);\n\t//Random* r= new Boost_Random(42u);\n\t//Random* r= new Standard_Random(42u);\n\t\n\n//\tboost::minstd_rand generator(42u);\n//\tboost::uniform_real<>uni_dist(0,1);\n//\tboost::variate_generator< boost::minstd_rand&, boost::uniform_real<> > uni(generator, uni_dist);\n\n\tfor(i=0;i<1000000;++i)\n\t{\n//\t\tresults[i]= uni();\n\t\t//results[i]= r->uniform(1,100);\n\t\t//results[i]= r->gaussian(0.0,0.125);\n\t\tresults[i]= r->gaussian(0.0,0.06);\n\t}\n\n\tplotHistogram(\"boost_random_results\",results,1000000);\n\t\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "2f8b76dfc7c14d00f50c4571d2c0a7ceab70c16c", "size": 1414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/random/random_test.cpp", "max_stars_repo_name": "yi1306c12/zweifel4suna", "max_stars_repo_head_hexsha": "1d166899b46345449e86e50c27fc4d6335a6b7d4", "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/random/random_test.cpp", "max_issues_repo_name": "yi1306c12/zweifel4suna", "max_issues_repo_head_hexsha": "1d166899b46345449e86e50c27fc4d6335a6b7d4", "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/random/random_test.cpp", "max_forks_repo_name": "yi1306c12/zweifel4suna", "max_forks_repo_head_hexsha": "1d166899b46345449e86e50c27fc4d6335a6b7d4", "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.6388888889, "max_line_length": 99, "alphanum_fraction": 0.6831683168, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5081272492936062}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2013 Alec Jacobson <alecjacobson@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 \"grad.h\"\n#include <Eigen/Geometry>\n#include <vector>\n\n#include \"per_face_normals.h\"\n#include \"volume.h\"\n#include \"doublearea.h\"\n\ntemplate <typename DerivedV, typename DerivedF>\nIGL_INLINE void grad_tet(const Eigen::PlainObjectBase<DerivedV>&V,\n                     const Eigen::PlainObjectBase<DerivedF>&T,\n                            Eigen::SparseMatrix<typename DerivedV::Scalar> &G,\n                            bool uniform) {\n  using namespace Eigen;\n  assert(T.cols() == 4);\n  const int n = V.rows(); int m = T.rows();\n\n  /*\n      F = [ ...\n      T(:,1) T(:,2) T(:,3); ...\n      T(:,1) T(:,3) T(:,4); ...\n      T(:,1) T(:,4) T(:,2); ...\n      T(:,2) T(:,4) T(:,3)]; */\n  MatrixXi F(4*m,3);\n  for (int i = 0; i < m; i++) {\n    F.row(0*m + i) << T(i,0), T(i,1), T(i,2);\n    F.row(1*m + i) << T(i,0), T(i,2), T(i,3);\n    F.row(2*m + i) << T(i,0), T(i,3), T(i,1);\n    F.row(3*m + i) << T(i,1), T(i,3), T(i,2);\n  }\n  // compute volume of each tet\n  VectorXd vol; igl::volume(V,T,vol);\n\n  VectorXd A(F.rows());\n  MatrixXd N(F.rows(),3);\n  if (!uniform) {\n    // compute tetrahedron face normals\n    igl::per_face_normals(V,F,N); int norm_rows = N.rows();\n    for (int i = 0; i < norm_rows; i++)\n      N.row(i) /= N.row(i).norm();\n    igl::doublearea(V,F,A); A/=2.;\n  } else {\n    // Use a uniform tetrahedra as a reference, with the same volume as the original one:\n    //\n    // Use normals of the uniform tet (V = h*[0,0,0;1,0,0;0.5,sqrt(3)/2.,0;0.5,sqrt(3)/6.,sqrt(2)/sqrt(3)])\n    //         0         0    1.0000\n    //         0.8165   -0.4714   -0.3333\n    //         0          0.9428   -0.3333\n    //         -0.8165   -0.4714   -0.3333\n    for (int i = 0; i < m; i++) {\n      N.row(0*m+i) << 0,0,1;\n      double a = sqrt(2)*std::cbrt(3*vol(i)); // area of a face in a uniform tet with volume = vol(i)\n      A(0*m+i) = (pow(a,2)*sqrt(3))/4.;\n    }\n    for (int i = 0; i < m; i++) {\n      N.row(1*m+i) << 0.8165,-0.4714,-0.3333;\n      double a = sqrt(2)*std::cbrt(3*vol(i));\n      A(1*m+i) = (pow(a,2)*sqrt(3))/4.;\n    }\n    for (int i = 0; i < m; i++) {\n      N.row(2*m+i) << 0,0.9428,-0.3333;\n      double a = sqrt(2)*std::cbrt(3*vol(i));\n      A(2*m+i) = (pow(a,2)*sqrt(3))/4.;\n    }\n    for (int i = 0; i < m; i++) {\n      N.row(3*m+i) << -0.8165,-0.4714,-0.3333;\n      double a = sqrt(2)*std::cbrt(3*vol(i));\n      A(3*m+i) = (pow(a,2)*sqrt(3))/4.;\n    }\n\n  }\n\n  /*  G = sparse( ...\n      [0*m + repmat(1:m,1,4) ...\n       1*m + repmat(1:m,1,4) ...\n       2*m + repmat(1:m,1,4)], ...\n      repmat([T(:,4);T(:,2);T(:,3);T(:,1)],3,1), ...\n      repmat(A./(3*repmat(vol,4,1)),3,1).*N(:), ...\n      3*m,n);*/\n  std::vector<Triplet<double> > G_t;\n  for (int i = 0; i < 4*m; i++) {\n    int T_j; // j indexes : repmat([T(:,4);T(:,2);T(:,3);T(:,1)],3,1)\n    switch (i/m) {\n      case 0:\n        T_j = 3;\n        break;\n      case 1:\n        T_j = 1;\n        break;\n      case 2:\n        T_j = 2;\n        break;\n      case 3:\n        T_j = 0;\n        break;\n    }\n    int i_idx = i%m;\n    int j_idx = T(i_idx,T_j);\n\n    double val_before_n = A(i)/(3*vol(i_idx));\n    G_t.push_back(Triplet<double>(0*m+i_idx, j_idx, val_before_n * N(i,0)));\n    G_t.push_back(Triplet<double>(1*m+i_idx, j_idx, val_before_n * N(i,1)));\n    G_t.push_back(Triplet<double>(2*m+i_idx, j_idx, val_before_n * N(i,2)));\n  }\n  G.resize(3*m,n);\n  G.setFromTriplets(G_t.begin(), G_t.end());\n}\n\ntemplate <typename DerivedV, typename DerivedF>\nIGL_INLINE void grad_tri(const Eigen::PlainObjectBase<DerivedV>&V,\n                     const Eigen::PlainObjectBase<DerivedF>&F,\n                    Eigen::SparseMatrix<typename DerivedV::Scalar> &G,\n                    bool uniform)\n{\n  Eigen::Matrix<typename DerivedV::Scalar,Eigen::Dynamic,3>\n    eperp21(F.rows(),3), eperp13(F.rows(),3);\n\n  for (int i=0;i<F.rows();++i)\n  {\n    // renaming indices of vertices of triangles for convenience\n    int i1 = F(i,0);\n    int i2 = F(i,1);\n    int i3 = F(i,2);\n\n    // #F x 3 matrices of triangle edge vectors, named after opposite vertices\n    Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v32 = V.row(i3) - V.row(i2);\n    Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v13 = V.row(i1) - V.row(i3);\n    Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v21 = V.row(i2) - V.row(i1);\n    Eigen::Matrix<typename DerivedV::Scalar, 1, 3> n = v32.cross(v13);\n    // area of parallelogram is twice area of triangle\n    // area of parallelogram is || v1 x v2 ||\n    // This does correct l2 norm of rows, so that it contains #F list of twice\n    // triangle areas\n    double dblA = std::sqrt(n.dot(n));\n    Eigen::Matrix<typename DerivedV::Scalar, 1, 3> u;\n    if (!uniform) {\n      // now normalize normals to get unit normals\n      u = n / dblA;\n    } else {\n      // Abstract equilateral triangle v1=(0,0), v2=(h,0), v3=(h/2, (sqrt(3)/2)*h)\n\n      // get h (by the area of the triangle)\n      double h = sqrt( (dblA)/sin(M_PI / 3.0)); // (h^2*sin(60))/2. = Area => h = sqrt(2*Area/sin_60)\n\n      Eigen::VectorXd v1,v2,v3;\n      v1 << 0,0,0;\n      v2 << h,0,0;\n      v3 << h/2.,(sqrt(3)/2.)*h,0;\n\n      // now fix v32,v13,v21 and the normal\n      v32 = v3-v2;\n      v13 = v1-v3;\n      v21 = v2-v1;\n      n = v32.cross(v13);\n    }\n\n    // rotate each vector 90 degrees around normal\n    double norm21 = std::sqrt(v21.dot(v21));\n    double norm13 = std::sqrt(v13.dot(v13));\n    eperp21.row(i) = u.cross(v21);\n    eperp21.row(i) = eperp21.row(i) / std::sqrt(eperp21.row(i).dot(eperp21.row(i)));\n    eperp21.row(i) *= norm21 / dblA;\n    eperp13.row(i) = u.cross(v13);\n    eperp13.row(i) = eperp13.row(i) / std::sqrt(eperp13.row(i).dot(eperp13.row(i)));\n    eperp13.row(i) *= norm13 / dblA;\n  }\n\n  std::vector<int> rs;\n  rs.reserve(F.rows()*4*3);\n  std::vector<int> cs;\n  cs.reserve(F.rows()*4*3);\n  std::vector<double> vs;\n  vs.reserve(F.rows()*4*3);\n\n  // row indices\n  for(int r=0;r<3;r++)\n  {\n    for(int j=0;j<4;j++)\n    {\n      for(int i=r*F.rows();i<(r+1)*F.rows();i++) rs.push_back(i);\n    }\n  }\n\n  // column indices\n  for(int r=0;r<3;r++)\n  {\n    for(int i=0;i<F.rows();i++) cs.push_back(F(i,1));\n    for(int i=0;i<F.rows();i++) cs.push_back(F(i,0));\n    for(int i=0;i<F.rows();i++) cs.push_back(F(i,2));\n    for(int i=0;i<F.rows();i++) cs.push_back(F(i,0));\n  }\n\n  // values\n  for(int i=0;i<F.rows();i++) vs.push_back(eperp13(i,0));\n  for(int i=0;i<F.rows();i++) vs.push_back(-eperp13(i,0));\n  for(int i=0;i<F.rows();i++) vs.push_back(eperp21(i,0));\n  for(int i=0;i<F.rows();i++) vs.push_back(-eperp21(i,0));\n  for(int i=0;i<F.rows();i++) vs.push_back(eperp13(i,1));\n  for(int i=0;i<F.rows();i++) vs.push_back(-eperp13(i,1));\n  for(int i=0;i<F.rows();i++) vs.push_back(eperp21(i,1));\n  for(int i=0;i<F.rows();i++) vs.push_back(-eperp21(i,1));\n  for(int i=0;i<F.rows();i++) vs.push_back(eperp13(i,2));\n  for(int i=0;i<F.rows();i++) vs.push_back(-eperp13(i,2));\n  for(int i=0;i<F.rows();i++) vs.push_back(eperp21(i,2));\n  for(int i=0;i<F.rows();i++) vs.push_back(-eperp21(i,2));\n\n  // create sparse gradient operator matrix\n  G.resize(3*F.rows(),V.rows());\n  std::vector<Eigen::Triplet<typename DerivedV::Scalar> > triplets;\n  for (int i=0;i<(int)vs.size();++i)\n  {\n    triplets.push_back(Eigen::Triplet<typename DerivedV::Scalar>(rs[i],cs[i],vs[i]));\n  }\n  G.setFromTriplets(triplets.begin(), triplets.end());\n}\n\ntemplate <typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::grad(const Eigen::PlainObjectBase<DerivedV>&V,\n                     const Eigen::PlainObjectBase<DerivedF>&F,\n                    Eigen::SparseMatrix<typename DerivedV::Scalar> &G,\n                    bool uniform)\n{\n  assert(F.cols() == 3 || F.cols() == 4);\n  if (F.cols() == 3)\n    return grad_tri(V,F,G,uniform);\n  if (F.cols() == 4)\n    return grad_tet(V,F,G,uniform);\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate void igl::grad<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::SparseMatrix<Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, 0, int>&, bool);\ntemplate void igl::grad<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::SparseMatrix<Eigen::Matrix<double, -1, 3, 0, -1, 3>::Scalar, 0, int>&, bool);\n#endif\n", "meta": {"hexsha": "6a06c68bf26d21d523be72c2456685958f1b7e4c", "size": 8801, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ThirdParty/Libigl/igl/grad.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": "ThirdParty/Libigl/igl/grad.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": "ThirdParty/Libigl/igl/grad.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": 36.367768595, "max_line_length": 337, "alphanum_fraction": 0.5542551983, "num_tokens": 3157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5080921198986612}}
{"text": "#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <random>\n#include <Eigen/Cholesky>\n#include <fstream>\n#include <iomanip>\n#include <srrg_system_utils/parse_command_line.h>\n#include <srrg_boss/deserializer.h>\n\n#include \"srrg_solver/solver_core/instances.h\"\n#include \"srrg_solver/solver_core/factor_graph.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/variable_se3_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/variable_point3_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/se3_pose_pose_geodesic_error_factor.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/se3_pose_point_offset_error_factor.h\"\n\n#include \"srrg_solver/variables_and_factors/types_2d/variable_se2_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/variable_point2_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/se2_pose_pose_geodesic_error_factor.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/se2_pose_point_error_factor.h\"\n\n#include \"srrg_solver/utils/solver_evaluator.h\"\n\nusing namespace srrg2_core;\nusing namespace srrg2_solver;\nusing namespace std;\n\nextern char** environ;\nconst std::string exe_name = environ[0];\n#define LOG std::cerr << exe_name << \"|\"\n\n\nstatic const char* banner[] = {\n  \"evaluates a  factor graph,  by registering the poses in the input graph with the corresponding poses of the gt\",\n  0\n};\n\n\n  \n// ia THE PROGRAM\nint main(int argc, char** argv) {\n  using namespace std;\n  ParseCommandLine cmd_line(argv, banner);\n  ArgumentString input_file          (&cmd_line, \"i\",    \"input-file\",             \"file where to read the input \", \"\");\n  ArgumentString gt_file          (&cmd_line, \"gt\",    \"gt-file\",           \"file where to read the ground truth\", \"\");\n  ArgumentString output_file          (&cmd_line, \"o\",    \"output-file\",             \"file where to write the output \", \"\");\n  ArgumentString ev_mode          (&cmd_line, \"m\",    \"mode\",           \"eval mode, [se3, se2, sim3]\", \"se3\");\n  cmd_line.parse();\n\n  FactorGraphPtr graph, gt_graph;\n\n  std::cerr << \"loading file: [\" << gt_file.value() << \"]... \";\n  gt_graph = FactorGraph::read(gt_file.value());\n  std::cerr << \"done, factors:\" << gt_graph->factors().size() << \" vars: \" << gt_graph->variables().size() << std::endl;\n\n  std::cerr << \"loading file: [\" << input_file.value() << \"]... \";\n  graph = FactorGraph::read(input_file.value());\n  std::cerr << \"done, factors:\" << graph->factors().size() << \" vars: \" << graph->variables().size() << std::endl;\n\n  std::cerr <<  \"Setting evaluator ...\";\n  SolverEvaluator evaluator;\n  evaluator.setGroundTruth(*gt_graph);\n  cerr << \"done\" << endl;\n  if (ev_mode.value()==\"se2\") {\n    evaluator.alignSE2(*graph, true);\n  } else if (ev_mode.value()==\"se3\") {\n    evaluator.alignSE3(*graph, true);\n  } else if (ev_mode.value()==\"sim3\") {\n    evaluator.alignSim3(*graph, true);\n  } else {\n    cerr << \"unknown ev mode [\" << ev_mode.value() << \"]\" << endl;\n    return -1;\n  }\n\n  if (output_file.isSet()) {\n    cerr << \"saving transformed graph [\" <<output_file.value() << \"]\" <<  endl;\n    graph->setSerializationLevel(-1);\n    graph->write(output_file.value());\n  }\n  return 0;\n}\n", "meta": {"hexsha": "ce38cfb2fbb4f61872db868547900309dd073dcf", "size": 3163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/app/graph_manipulators/solver_app_graph_evaluator.cpp", "max_stars_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_stars_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/app/graph_manipulators/solver_app_graph_evaluator.cpp", "max_issues_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_issues_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/app/graph_manipulators/solver_app_graph_evaluator.cpp", "max_forks_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_forks_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_forks_repo_licenses": ["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.1084337349, "max_line_length": 124, "alphanum_fraction": 0.6863736959, "num_tokens": 848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5080921198986611}}
{"text": "#include <gtsam/geometry/Pose2.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/nonlinear/ISAM2.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/Values.h>\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/slam/Pose2_Point2_Factor.h>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <time.h>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace boost::algorithm;\n\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\n// Testing params\nconst size_t max_odom_count = 3800; //3800\n\n//const bool is_with_ambiguity = false; //run original iSAM2 without ambiguities\nconst bool is_with_ambiguity = true; //run original iSAM2 with ambiguities\n\nnoiseModel::Diagonal::shared_ptr prior_noise_model = noiseModel::Diagonal::Sigmas((Vector(3) << 0.0001, 0.0001, 0.0001).finished());\n\nnoiseModel::Diagonal::shared_ptr pose_noise_model = noiseModel::Diagonal::Sigmas((Vector(3) << 1.0/100.0, 1.0/500.0, 1.0/500.0).finished());\n\nnoiseModel::Diagonal::shared_ptr point_noise_model = noiseModel::Diagonal::Sigmas((Vector(2) << 1.0/1.581139, 1.0/1.581139).finished());\n/* ************************************************************************* */\n\nint main(int argc, char* argv[]) {\n\n  ifstream in(\"../data/mh_T2_victoriaPark_01.txt\"); //Type #2 only  \n  //ifstream in(\"../data/mh_T1_T2_victoriaPark_08.txt\"); //Type #1 + Type #2\n  \n  size_t odom_count = 0;\n  size_t landmark_count = 0;\n  \n  std::list<double> time_list;\n\n  ISAM2Params parameters; \n  \n  //parameters.optimizationParams = gtsam::ISAM2DoglegParams(0.1);  //_initialDelta = 1.0 //Dogleg NOT implemented yet!!!!\n  parameters.optimizationParams = gtsam::ISAM2GaussNewtonParams(0.0); //_wildfireThreshold = 0.001\n  \n  parameters.relinearizeThreshold = 0.01;\n  \n  parameters.relinearizeSkip = 1;\n  ISAM2* isam2 = new ISAM2(parameters); //[2] MHISAM2\n\n  NonlinearFactorGraph* graph = new NonlinearFactorGraph(); \n\n  Values init_values; \n  Values results; \n \n  double x = 0.0;\n  double y = 0.0;\n  double rad = 0.0;\n\n  Pose2 prior_pose(x, y, rad);\n  \n  init_values.insert(X(0), prior_pose);\n\n  graph->add(PriorFactor<Pose2>(X(0), prior_pose, prior_noise_model));\n\n  isam2->update(*graph, init_values);\n  graph->resize(0);\n  init_values.clear();\n  results = isam2->calculateBestEstimate();\n  \n  //*\n  size_t key_s = 0;\n  size_t key_t = 0;\n  \n  clock_t start_time = clock();\n  string str;\n  while (getline(in, str) && odom_count < max_odom_count) {\n    \n    //cout << str << endl; \n    vector<string> parts;\n    split(parts, str, is_any_of(\" \"));\n\n    if (parts[0] == \"ODOMETRY\") {   \n      key_s = stoi(parts[1]);\n      key_t = stoi(parts[3]);\n      int m_num = stoi(parts[5]);\n      vector<double> x_arr(m_num);\n      vector<double> y_arr(m_num);\n      vector<double> rad_arr(m_num);\n      for (int i = 0; i < m_num; ++i) {\n        x_arr[i] = stod(parts[6 + 3*i]);\n        y_arr[i] = stod(parts[7 + 3*i]);\n        rad_arr[i] = stod(parts[8 + 3*i]);\n      }\n\n      Pose2 odom_pose;\n      if (is_with_ambiguity) {\n        // Get wrong intentionally\n        int id = odom_count%m_num;\n        odom_pose = Pose2(x_arr[id], y_arr[id], rad_arr[id]);\n      } else {\n        odom_pose = Pose2(x_arr[0], y_arr[0], rad_arr[0]);\n      }\n       \n      init_values.insert(X(key_t), results.at<Pose2>(X(key_s))*odom_pose);\n      \n      graph->add(BetweenFactor<Pose2>(X(key_s), X(key_t), odom_pose, pose_noise_model));\n\n      odom_count++;\n\n    } else { //LANDMARK\n      //*\n      key_s = stoi(parts[1]);\n      int k_num = stoi(parts[2]);\n      \n      if (k_num == 1) {\n        key_t = stoi(parts[3]);\n        //int m_num = 1;\n        double l_x = stod(parts[6]);\n        double l_y = stod(parts[7]);\n\n        //Pose2 odom_pose(x_arr[0], y_arr[0], rad_arr[0]*180.0/M_PI);\n        Point2 measured_point(l_x, l_y);\n  \n        if (key_t >= landmark_count) { \n          init_values.insert(L(key_t), results.at<Pose2>(X(key_s))*measured_point); //operator*\n          landmark_count++;\n        }\n\n        graph->add(Pose2_Point2_Factor(X(key_s), L(key_t), measured_point, point_noise_model));\n      \n      } else {\n        \n        if (is_with_ambiguity) {\n          // Get wrong intentionally\n          if (odom_count%4 != 0) {\n            key_t = stoi(parts[4]);\n          } else {\n            key_t = stoi(parts[3]);\n          }\n        \n        } else {\n          key_t = stoi(parts[3]);\n        }\n        \n        double l_x = stod(parts[7]);\n        double l_y = stod(parts[8]);\n\n        Point2 measured_point(l_x, l_y);\n        \n        graph->add(Pose2_Point2_Factor(X(key_s), L(key_t), measured_point, point_noise_model));\n      \n      }\n      // */\n    }\n\n    isam2->update(*graph, init_values);\n    graph->resize(0);\n    init_values.clear();\n    results = isam2->calculateBestEstimate();\n    \n    if (parts[0] == \"ODOMETRY\") {\n      clock_t cur_time = clock();\n      time_list.push_back(cur_time - start_time);\n    }\n    \n    if (time_list.size()%100 == 0 && parts[0] == \"ODOMETRY\") {\n      string step_file_idx = std::to_string(100000 + time_list.size());\n      \n      ofstream step_outfile;\n      string step_file_name = \"T2_step_files/ISAM2_TEST_victoriaPark_S\" + step_file_idx;\n      step_outfile.open(step_file_name + \".txt\");\n      for (size_t i = 0; i < (key_t + 1); ++i) {\n        Pose2 out_pose = results.at<Pose2>(X(i));\n        step_outfile << out_pose.x() << \" \" << out_pose.y() << \" \" << out_pose.theta() << endl;\n      }\n      step_outfile.close();\n    }\n\n  }\n  \n  clock_t end_time = clock();\n  clock_t total_time = end_time - start_time;\n  cout << \"total_time: \" << total_time << endl;\n  //* \n  \n  ofstream outfile;\n  string file_name = \"ISAM2_TEST_victoriaPark\";\n  outfile.open(file_name + \".txt\");\n  \n  for (size_t i = 0; i < odom_count; ++i) {\n    Pose2 out_pose = results.at<Pose2>(X(i));\n    \n    outfile << out_pose.x() << \" \" << out_pose.y() << \" \" << out_pose.theta() << endl;\n  }\n  outfile.close();\n  cout << \"output \" << file_name << \".txt file.\" << endl;\n  // */\n  ofstream lm_outfile;\n  string lm_file_name = \"ISAM2_TEST_victoriaPark_lm\";\n  lm_outfile.open(lm_file_name + \".txt\");\n  \n  for (size_t i = 0; i < landmark_count; ++i) {\n    Point2 out_point = results.at<Point2>(L(i));\n    \n    lm_outfile << out_point.x() << \" \" << out_point.y() << endl;\n  }\n  lm_outfile.close();\n  cout << \"output \" << lm_file_name << \".txt file.\" << endl;\n  \n  //*\n  ofstream outfile_time;\n  string time_file_name = \"ISAM2_TEST_victoriaPark_time\";\n  outfile_time.open(time_file_name + \".txt\");\n  for (auto acc_time : time_list) {\n    outfile_time << acc_time << endl; //WRONG FORMAT... JUST FOR SIMPLE SHOW\n  }\n  outfile_time.close();\n  cout << \"output \" << time_file_name << \".txt file.\" << endl;\n  // */\n  return 0;\n}\n", "meta": {"hexsha": "33c36db083b22537d671733ce112ff096167da71", "size": 6856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ISAM2_TEST_victoriaPark.cpp", "max_stars_repo_name": "ICRA-2019/MH-iSAM2_lib", "max_stars_repo_head_hexsha": "cf92b2b94f5dcae39b780273c613ca945599e0c0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-10T02:24:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T02:24:39.000Z", "max_issues_repo_path": "examples/ISAM2_TEST_victoriaPark.cpp", "max_issues_repo_name": "ICRA-2019/MH-iSAM2_lib", "max_issues_repo_head_hexsha": "cf92b2b94f5dcae39b780273c613ca945599e0c0", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/ISAM2_TEST_victoriaPark.cpp", "max_forks_repo_name": "ICRA-2019/MH-iSAM2_lib", "max_forks_repo_head_hexsha": "cf92b2b94f5dcae39b780273c613ca945599e0c0", "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.0701754386, "max_line_length": 140, "alphanum_fraction": 0.6101225204, "num_tokens": 2021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5080921136329472}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// NeoHookeanEnergy.hh\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//  Volumetric and plane stress Neo-Hookean energy.\n*///////////////////////////////////////////////////////////////////////////////\n#ifndef NEOHOOKEANENERGY_HH\n#define NEOHOOKEANENERGY_HH\n\n#include <Eigen/Dense>\n#include <cstdlib>\n\n#include <MeshFEM/EnergyDensities/Tensor.hh>\n#include <MeshFEM/EnergyDensities/EnergyTraits.hh>\n#include <MeshFEM/EnergyDensities/EDensityAdaptors.hh>\n\n/**\n *  Implements the Neo-Hookean Energy described in the Neo-Hookean Energy section of doc/doc.pdf\n */\ntemplate<typename _Real, size_t _Dim, template<typename, size_t> class _Derived_T>\nstruct NeoHookeanEnergyBase : public Concepts::NeoHookeanEnergy\n{\n    static constexpr size_t Dimension = _Dim;\n    static constexpr size_t N         = _Dim;\n    static constexpr EDensityType EDType = EDensityType::FBased;\n    using Real = _Real;\n    using Derived = _Derived_T<Real, N>;\n    using Matrix = Eigen::Matrix<Real, N, N>;\n\n    NeoHookeanEnergyBase(const NeoHookeanEnergyBase& other) = default;\n\n    // Constructor copying material properties only, not the current deformation\n    NeoHookeanEnergyBase(const NeoHookeanEnergyBase& other, UninitializedDeformationTag &&)\n        : m_lambda(other.m_lambda), m_mu(other.m_mu), m_finite_continuation_start(other.m_finite_continuation_start)\n    { }\n\n    // Construct from Lame's first parameter (lambda) and shear modulus (mu).\n    NeoHookeanEnergyBase(Real lambda, Real mu, Real finite_continuation_start = -1)\n        : m_lambda(lambda), m_mu(mu), m_finite_continuation_start(finite_continuation_start)\n    {\n        setDeformationGradient(Matrix::Identity());\n    }\n\n    void setDeformationGradient(const Matrix& deformation_gradient, const EvalLevel /* elevel */ = EvalLevel::Full) {\n        m_F = deformation_gradient;\n        m_detF = deformation_gradient.determinant();\n        m_Finv = m_F.inverse();\n    }\n\n    const Matrix &getDeformationGradient() const { return m_F; }\n\n    Real energy() const {\n        // Standard behavior: return inf for inverted elements\n        if (m_finite_continuation_start <= 0 && m_detF < 0) {\n            return std::numeric_limits<Real>::max();\n        }\n\n        const Real I3 = getI3();\n        const Real I1 = getI1();\n\n        // Modified behavior to support inverted elements:\n        // if det F < eps, we replace the log(I3) term by a constant + exp(- (det (F) - eps) )\n        // where the constant is chosen such that the energy remains continuous\n        if (m_finite_continuation_start > 0 && m_detF < m_finite_continuation_start) {\n            Derived tmp(m_lambda, m_mu, m_finite_continuation_start);\n            Matrix tmp_F = Matrix::Identity();\n            tmp_F(0, 0) = m_finite_continuation_start;\n            tmp.setDeformationGradient(tmp_F);\n            Real continuation_constant = - std::log(tmp.getI3()) * (m_lambda / 2 + m_mu) / 2;\n\n            return m_lambda * (I3 - 1) / 4 + m_mu * (I1 - 3) / 2\n                + continuation_constant + std::exp(-(m_detF - m_finite_continuation_start)) - 1;\n        }\n\n        return (m_mu / 2) * (I1 - 3) + (m_lambda / 4) * (I3 - 1) - std::log(I3) * (m_mu / 2 + m_lambda / 4);\n    }\n\n    Matrix denergy() const {\n        if (m_finite_continuation_start > 0 && m_detF < m_finite_continuation_start) {\n            Real dPsi3 = m_lambda / 4;\n            return (-std::exp(-(m_detF - m_finite_continuation_start))) * m_detF * m_Finv.transpose()\n                + dPsi3 * d_I3_d_F()\n                + d_psi_d_I1() * d_I1_d_F();\n        }\n\n        return d_psi_d_I1() * d_I1_d_F() + d_psi_d_I3() * d_I3_d_F();\n    }\n\n    Real denergy(const Matrix& dF) const { return doubleContract(dF, denergy()); }\n\n    Real d2energy(const Matrix& dF_a, const Matrix& dF_b) const {\n        return doubleContract(dF_a, delta_denergy(dF_b));\n    }\n\n    // Directional derivative of \"denergy\" along dF:\n    //      (d^2 psi / dF^2) : dF\n    template<class Mat_>\n    Matrix delta_denergy(const Mat_ &dF) const {\n        if (m_finite_continuation_start > 0 && m_detF < m_finite_continuation_start) {\n            // ln I3 term is constant, but exp(-(detF)) got added\n            Real dPsi3 = m_lambda / 4;\n            Real exp_term = -std::exp(-(m_detF - m_finite_continuation_start));\n\n            Matrix d_det_dF = m_detF * m_Finv.transpose();\n            Matrix delta_d_det_dF = doubleContract(d_det_dF, dF) * m_Finv.transpose()\n                                  - m_detF * (m_Finv * dF * m_Finv).transpose();\n\n            return exp_term * d_det_dF * d_det_dF\n                + exp_term * delta_d_det_dF\n                + dPsi3 * delta_d_I3_d_F(dF)\n                + d_psi_d_I1() * delta_d_I1_d_F(dF);\n        }\n\n        Matrix dI3 = d_I3_d_F();\n        Real delta_I3 = doubleContract(dI3, dF);\n        return d_psi_d_I1() * delta_d_I1_d_F(dF) + (d2_psi_d2_I3() * delta_I3) * dI3 + d_psi_d_I3() * delta_d_I3_d_F(dF);\n    }\n\n    // (d^3 psi / dF^3) :: (dF_a \\otimes dF_b)\n    // Second variation of \"denergy\" along (dF_a, dF_b)\n    template<class Mat_, class Mat2_>\n    Matrix delta2_denergy(const Mat_ &dF_a, const Mat2_ &dF_b) const {\n        if (m_finite_continuation_start > 0) throw std::runtime_error(\"Finite continuation energy variant is not supported\");\n\n        Matrix dI3 = d_I3_d_F();\n        Real delta_I3_a = doubleContract(dI3, dF_a),\n             delta_I3_b = doubleContract(dI3, dF_b);\n        Matrix delta_dI3_a = delta_d_I3_d_F(dF_a),\n               delta_dI3_b = delta_d_I3_d_F(dF_b);\n        return // Derivative of (d_psi_d_I1() * delta_d_I1_d_F(dF):                      (Note d2_psi_d_I1 = 0)\n               d_psi_d_I1() * delta2_d_I1_d_F(dF_a, dF_b)                                // Symmetric\n               // Derivative of (d2_psi_d2_I3() * delta_I3) * dI3:\n             + (d3_psi_d3_I3() * delta_I3_b * delta_I3_a) * dI3                          // Symmetric\n             + (d2_psi_d2_I3() *              doubleContract(delta_dI3_b, dF_a)) * dI3   // Symmetric\n             + (d2_psi_d2_I3() *              delta_I3_a) * delta_dI3_b                  // Symmetric pair (*)\n               // Derivative of d_psi_d_I3() * delta_d_I3_d_F(dF):\n             + (d2_psi_d2_I3() *              delta_I3_b) * delta_dI3_a                  // Symmetric pair (*)\n             + (  d_psi_d_I3()                          ) * delta2_d_I3_d_F(dF_a, dF_b); // Symmetric\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Invariants of the Cauchy-Green deformation tensor and their derivatives\n    // appearing in the energy density expressions.\n    // These must be provided by the derived class since they differ for the\n    // 2D plane stress and 3D volumetric cases.\n    ////////////////////////////////////////////////////////////////////////////\n    // Trace of Cauchy-Green deformation tensor.\n    Real getI1() const { return derived().getI1(); }\n\n    // Determinant of Cauchy-Green deformation tensor.\n    Real getI3() const { return derived().getI3(); }\n\n    // dI1/dF\n    Matrix d_I1_d_F() const { return derived().d_I1_d_F(); }\n\n    // dI3/dF\n    Matrix d_I3_d_F() const { return derived().d_I3_d_F(); }\n\n    // (d^2 I1 / dF^2) : dF\n\n    template<class Mat_>\n    Matrix delta_d_I1_d_F(const Mat_ &dF) const { return derived().delta_d_I1_d_F(dF); }\n\n    // (d^2 I1 / dF^2) : dF\n    template<class Mat_>\n    Matrix delta_d_I3_d_F(const Mat_ &dF) const { return derived().delta_d_I3_d_F(dF); }\n\n    // (d^3 I1 / dF^3) :: (dF_a \\otimes dF_b)\n    Matrix delta2_d_I1_d_F(const Matrix &dF_a, const Matrix &dF_b) const { return derived().delta2_d_I1_d_F(dF_a, dF_b); }\n\n    // (d^3 I3 / dF^3) :: (dF_a \\otimes dF_b)\n    Matrix delta2_d_I3_d_F(const Matrix &dF_a, const Matrix &dF_b) const { return derived().delta2_d_I3_d_F(dF_a, dF_b); }\n\n    Matrix PK2Stress() const { return m_Finv * denergy(); }\n\n    const Derived &derived() const { return *static_cast<const Derived *>(this); }\nprotected:\n    ////////////////////////////////////////////////////////////////////////////\n    // Derivatives of the energy density with respect to the tensor invariants.\n    ////////////////////////////////////////////////////////////////////////////\n    // Derivative of the energy density with respect to I1\n    Real d_psi_d_I1() const { return m_mu / 2; }\n\n    // Derivative of the energy density with respect to I3\n    Real d_psi_d_I3() const { return (m_lambda - (2 * m_mu + m_lambda) / getI3()) / 4; }\n\n    // Second derivative of the energy density with respect to I3\n    Real d2_psi_d2_I3() const {\n        Real I3 = getI3();\n        return (2 * m_mu + m_lambda) / (4 * I3 * I3);\n    }\n\n    // Third derivative of the energy density with respect to I3\n    Real d3_psi_d3_I3() const {\n        Real I3 = getI3();\n        return - (m_mu + 0.5 * m_lambda) / (I3 * I3 * I3);\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Derivatives of the \"unpadded\" invariants\n    // (i.e., the 2x2 invariants for 2D, not including the C33 component)\n    ////////////////////////////////////////////////////////////////////////////\n    Real           unpaddedI3()     const { return m_detF * m_detF; }\n    Matrix       d_unpaddedI3_d_F() const { return (2 * unpaddedI3()) * m_Finv.transpose(); }\n    template<typename Mat_>\n    Real delta_unpaddedI3(const Mat_ &dF) const { return (2 * unpaddedI3()) * doubleContract(m_Finv.transpose(), dF); }\n    template<typename Mat_>\n    Matrix delta_d_unpaddedI3_d_F(const Mat_ &dF) const {\n        return (2 * delta_unpaddedI3(dF)) *  m_Finv.transpose()\n             - (2 *       unpaddedI3()  ) * (m_Finv * dF * m_Finv).transpose();\n    }\n\n    Matrix delta2_d_unpaddedI3_d_F(const Matrix &dF_a, const Matrix &dF_b) const {\n        Real delta2_unpaddedI3_ab = doubleContract(delta_d_unpaddedI3_d_F(dF_a), dF_b);\n        Matrix delta_Finv_a = -(m_Finv * dF_a * m_Finv),\n               delta_Finv_b = -(m_Finv * dF_b * m_Finv);\n\n        return (2 * delta2_unpaddedI3_ab)   *       m_Finv.transpose()\n             + (2 * delta_unpaddedI3(dF_a)) * delta_Finv_b.transpose()\n             + (2 * delta_unpaddedI3(dF_b)) * delta_Finv_a.transpose()\n             - (2 *       unpaddedI3()  ) * (delta_Finv_b * dF_a * m_Finv).transpose()\n             - (2 *       unpaddedI3()  ) * (m_Finv * dF_a * delta_Finv_b).transpose();\n    }\n\n    Real m_lambda = 0.0; // Lame's first parameter\n    Real m_mu = 0.0;     // Shear modulus\n    Real m_finite_continuation_start = -1;\n\n    // Cached deformation quantities.\n    Matrix m_F = Matrix::Identity(), m_Finv = Matrix::Identity();\n    Real m_detF = 1.0;\n};\n\ntemplate<typename _Real, size_t _Dim>\nstruct NeoHookeanEnergy;\n\ntemplate<typename _Real>\nstruct NeoHookeanEnergy<_Real, 2> : public NeoHookeanEnergyBase<_Real, 2, NeoHookeanEnergy>\n{\n    using Base = NeoHookeanEnergyBase<_Real, 2, ::NeoHookeanEnergy>;\n    using Real = _Real;\n    using Matrix = typename Base::Matrix;\n\n    using Base::Base;\n\n    NeoHookeanEnergy(const NeoHookeanEnergy &other)\n        : Base(other), m_C33(other.m_C33) { }\n\n    NeoHookeanEnergy &operator=(const NeoHookeanEnergy &other) = default; // Silence deprecation warning.\n\n    void setDeformationGradient(const Matrix &F, const EvalLevel elevel = EvalLevel::Full) {\n        Base::setDeformationGradient(F, elevel);\n        m_C33 = (m_lambda + 2 * m_mu) / (m_lambda * unpaddedI3() + 2 * m_mu);\n    }\n\n    // Trace of full (padded) Cauchy-Green deformation tensor.\n    Real getI1() const { return m_F.squaredNorm() + m_C33; }\n\n    // Determinant of full (padded) Cauchy-Green deformation tensor.\n    Real getI3() const { return unpaddedI3() * m_C33; }\n\n    // dI1/dF\n    Matrix d_I1_d_F() const { return 2 * m_F + d_C33_d_F(); }\n\n    // dI3/dF\n    Matrix d_I3_d_F() const { return d_unpaddedI3_d_F() * m_C33 + unpaddedI3() * d_C33_d_F(); }\n\n    // (d^2 I1 / dF^2) : dF\n    template<class Mat_>\n    Matrix delta_d_I1_d_F(const Mat_ &dF) const { return 2 * dF.matrix() + delta_d_C33_d_F(dF); }\n\n    // (d^2 I&1 / dF^2) : dF\n    template<typename Mat_>\n    Matrix delta_d_I3_d_F(const Mat_ &dF) const {\n        Matrix dC33 = d_C33_d_F();\n        Matrix d_unpaddedI3 = d_unpaddedI3_d_F();\n        Real delta_unpaddedI3_val = doubleContract(d_unpaddedI3, dF);\n\n        return delta_d_unpaddedI3_d_F(dF) * m_C33                    +\n               d_unpaddedI3               * doubleContract(dC33, dF) +\n               delta_unpaddedI3_val       * dC33                     +\n               unpaddedI3()               * delta_d_C33_d_F(dF);\n    }\n\n    // (d^3 I1 / dF^3) :: (dF_a \\otimes dF_b)\n    Matrix delta2_d_I1_d_F(const Matrix &dF_a, const Matrix &dF_b) const { return delta2_d_C33_d_F(dF_a, dF_b); }\n\n    // (d^3 I3 / dF^3) :: (dF_a \\otimes dF_b)\n    Matrix delta2_d_I3_d_F(const Matrix &dF_a, const Matrix &dF_b) const {\n        Matrix dC33 = d_C33_d_F();\n        Real delta_C33_a   = doubleContract(dC33, dF_a),\n             delta_C33_b   = doubleContract(dC33, dF_b);\n        Real delta2_C33_ab = doubleContract(delta_d_C33_d_F(dF_a), dF_b);\n        Matrix delta_d_unpaddedI3_a  = delta_d_unpaddedI3_d_F(dF_a),\n               delta_d_unpaddedI3_b  = delta_d_unpaddedI3_d_F(dF_b);\n        Real    delta2_unpaddedI3_ab = doubleContract(delta_d_unpaddedI3_a, dF_b);\n\n        Matrix d_unpaddedI3 = d_unpaddedI3_d_F();\n        return // Derivative of delta_d_unpaddedI3_d_F(dF) * m_C33:\n               delta2_d_unpaddedI3_d_F(dF_a, dF_b) * m_C33 + delta_d_unpaddedI3_a * delta_C33_b\n               // Derivative of d_unpaddedI3 * doubleContract(dC33, dF):\n             + delta_d_unpaddedI3_b * delta_C33_a + d_unpaddedI3 * delta2_C33_ab\n               // Derivative of delta_unpaddedI3 * dC33:\n             + delta2_unpaddedI3_ab * dC33 + doubleContract(d_unpaddedI3, dF_a) * delta_d_C33_d_F(dF_b)\n               // Derivative of unpaddedI3() * delta_d_C33_d_F(dF):\n             + doubleContract(d_unpaddedI3, dF_b) * delta_d_C33_d_F(dF_a) + unpaddedI3() * delta2_d_C33_d_F(dF_a, dF_b);\n    }\n\nprotected:\n    // Derivative of normal component C33 with respect to the 2D deformation gradient.\n    Matrix d_C33_d_F() const { return d_C33_d_unpaddedI3() * d_unpaddedI3_d_F(); }\n\n    template<class Mat_>\n    Matrix delta_d_C33_d_F(const Mat_ &dF) const {\n        return delta_d_C33_d_unpaddedI3(dF) * d_unpaddedI3_d_F() +\n               d_C33_d_unpaddedI3()         * delta_d_unpaddedI3_d_F(dF);\n    }\n\n    Matrix delta2_d_C33_d_F(const Matrix &dF_a, const Matrix &dF_b) const {\n        Matrix dC33 = d_C33_d_F();\n        Real delta_C33_a   = doubleContract(dC33, dF_a),\n             delta_C33_b   = doubleContract(dC33, dF_b);\n        Real delta2_C33_ab = doubleContract(delta_d_C33_d_F(dF_a), dF_b);\n\n        Real coeff = -2 * m_lambda / (m_lambda + 2 * m_mu);\n        // Second variation of d_C33_d_unpaddedI3 along (dF_a, dF_b)\n        Real delta2_d_C33_d_unpaddedI3_ab = coeff * (delta_C33_a * delta_C33_b + m_C33 * delta2_C33_ab);\n        Real delta_d_C33_d_unpaddedI3_a   = coeff * m_C33 * delta_C33_a;\n        Real delta_d_C33_d_unpaddedI3_b   = coeff * m_C33 * delta_C33_b;\n\n        return delta2_d_C33_d_unpaddedI3_ab *        d_unpaddedI3_d_F()\n             + delta_d_C33_d_unpaddedI3_a   *  delta_d_unpaddedI3_d_F(dF_b)\n             + delta_d_C33_d_unpaddedI3_b   *  delta_d_unpaddedI3_d_F(dF_a)\n             + d_C33_d_unpaddedI3()         * delta2_d_unpaddedI3_d_F(dF_a, dF_b);\n    }\n\n    // Derivative of normal component C33 with respect to the unpadded I3 invariant.\n    Real d_C33_d_unpaddedI3() const {\n        return -m_C33 * m_C33 * (m_lambda / (m_lambda + 2 * m_mu));\n    }\n\n    // Directional derivative of d_C33_d_unpaddedI3 along dF\n    template<class Mat_>\n    Real delta_d_C33_d_unpaddedI3(const Mat_ &dF) const {\n        Real delta_C33 = doubleContract(d_C33_d_F(), dF);\n        return -2 * m_C33 * delta_C33 * (m_lambda / (m_lambda + 2 * m_mu));\n    }\n\nprivate:\n    using Base::m_F;\n    using Base::m_detF;\n    using Base::m_lambda;\n    using Base::m_mu;\n    using Base::unpaddedI3;\n    using Base::d_unpaddedI3_d_F;\n    using Base::delta_d_unpaddedI3_d_F;\n    using Base::delta2_d_unpaddedI3_d_F;\n    Real m_C33 = 1.0;\n};\n\ntemplate<typename _Real>\nstruct NeoHookeanEnergy<_Real, 3> : public NeoHookeanEnergyBase<_Real, 3, NeoHookeanEnergy>\n{\n    using Base = NeoHookeanEnergyBase<_Real, 3, ::NeoHookeanEnergy>;\n    using Real = _Real;\n    using Matrix = typename Base::Matrix;\n    using Base::Base;\n\n    Real getI3() const { return m_detF * m_detF; }\n    Real getI1() const { return m_F.squaredNorm(); }\n\n    Matrix d_I1_d_F() const { return 2 * m_F; }\n    Matrix d_I3_d_F() const { return this->d_unpaddedI3_d_F(); }\n\n    template<typename Mat_> Matrix delta_d_I1_d_F(const Mat_ &dF) const { return 2 * dF.matrix(); }\n    template<typename Mat_> Matrix delta_d_I3_d_F(const Mat_ &dF) const { return this->delta_d_unpaddedI3_d_F(dF); }\n\n    Matrix delta2_d_I1_d_F(const Matrix &/* dF_a */, const Matrix /* &dF_b */) const { return Matrix::Zero(); }\n    Matrix delta2_d_I3_d_F(const Matrix    &dF_a   , const Matrix    &dF_b   ) const { return this->delta2_d_unpaddedI3_d_F(dF_a, dF_b); }\nprivate:\n    using Base::m_F;\n    using Base::m_detF;\n    using Base::m_lambda;\n    using Base::m_mu;\n};\n\n// Simulate a Neo-Hookean sheet made of a material with Poisson's ratio 0.5.\n// This would cause the volumetric NeoHookeanEnergy above to blow up, but we\n// can obtain a membrane energy by imposing incompressibility as a hard\n// constraint.\ntemplate<typename _Real>\nstruct IncompressibleNeoHookeanEnergyCBased {\n    static constexpr EDensityType EDType = EDensityType::CBased;\n    static constexpr size_t Dimension = 2;\n    static constexpr size_t N         = 2;\n    using Real   = _Real;\n    using Matrix = Eigen::Matrix<_Real, 2, 2>;\n    using M2d    = Matrix;\n\n    static constexpr const char *name() { return \"IncompressibleNeoHookean\"; }\n\n    IncompressibleNeoHookeanEnergyCBased(const IncompressibleNeoHookeanEnergyCBased &other, UninitializedDeformationTag &&) {\n        setYoungModulus(other.youngModulus());\n    }\n\n    IncompressibleNeoHookeanEnergyCBased(Real E = 6 /* corresponds to \"stiffness\"  of 1 */) {\n        setYoungModulus(E);\n    }\n\n    void setC(const M2d &C) {\n        Real a = C(0, 0),\n             b = C(0, 1),\n             c = C(1, 1);\n        if (std::abs(b - C(1, 0)) > 1e-15) throw std::runtime_error(\"Asymmetric matrix\");\n\n        m_C = C;\n        m_trace_C = C.trace();\n        m_det_C = a * c - b * b;\n        m_grad_det_C <<  c, -b,\n                        -b,  a;\n    }\n\n    Real energy() const {\n        return stiffness * (m_trace_C + 1.0 / m_det_C - 3.0);\n    }\n\n    // dpsi / dE = 2 * dpsi/dC\n    M2d PK2Stress() const {\n        return 2 * stiffness * (M2d::Identity() - (1.0 / (m_det_C * m_det_C)) * m_grad_det_C);\n    }\n\n    template<class Mat_>\n    M2d delta_PK2Stress(const Mat_ &dC) const {\n        M2d adj_dC;\n        adj_dC << dC(1, 1), -dC(0, 1),\n                 -dC(1, 0),  dC(0, 0);\n        return 2 * (((2.0 * stiffness / (m_det_C * m_det_C * m_det_C)) * doubleContract(m_grad_det_C, dC)) * m_grad_det_C\n                         - (stiffness / (m_det_C * m_det_C))                                               * adj_dC);\n    }\n\n    template<class Mat_, class Mat2_>\n    Matrix delta2_PK2Stress(const Mat_ &/* dC_a */, const Mat2_ &/* dC_b */) const {\n        throw std::runtime_error(\"Unimplemented\");\n    }\n\n    // The stiffness parameter is mu / 2 = E / (4 * (1 + nu)) = E / 6\n    void setYoungModulus(Real E) {\n        stiffness = E / 6;\n    }\n\n    Real youngModulus() const {\n        return stiffness * 6;\n    }\n\n    void copyMaterialProperties(const IncompressibleNeoHookeanEnergyCBased &other) { setYoungModulus(other.youngModulus()); }\n\n    Real stiffness = 1.0; // mu / 2\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n    Real m_trace_C, m_det_C;\n    M2d m_grad_det_C;\n    M2d m_C;\n};\n\ntemplate <typename _Real>\nusing IncompressibleNeoHookeanEnergy = EnergyDensityFBasedFromCBased<IncompressibleNeoHookeanEnergyCBased<_Real>>;\n\n#endif\n", "meta": {"hexsha": "74075e45db0e84ea7b2b100eef2fe604de2dcdd0", "size": 20099, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/lib/MeshFEM/EnergyDensities/NeoHookeanEnergy.hh", "max_stars_repo_name": "MeshFEM/MeshFEM", "max_stars_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T10:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:41:50.000Z", "max_issues_repo_path": "src/lib/MeshFEM/EnergyDensities/NeoHookeanEnergy.hh", "max_issues_repo_name": "MeshFEM/MeshFEM", "max_issues_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-01T15:58:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:31:09.000Z", "max_forks_repo_path": "src/lib/MeshFEM/EnergyDensities/NeoHookeanEnergy.hh", "max_forks_repo_name": "MeshFEM/MeshFEM", "max_forks_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T09:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T03:02:39.000Z", "avg_line_length": 42.7638297872, "max_line_length": 138, "alphanum_fraction": 0.6118214837, "num_tokens": 6070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059462938815, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5080921113241956}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\n#ifndef _MATRIX_FREE_OP_\n#define _MATRIX_FREE_OP_\n\nclass MatrixFreeOperator;\n\nnamespace Eigen { namespace internal {\n\t\ttemplate<>\n\t\tstruct traits<MatrixFreeOperator> : public Eigen::internal::traits<Eigen::MatrixXd> {};\n\t}\n}\n\nclass MatrixFreeOperator : public Eigen::EigenBase<Eigen::MatrixXd>\n{\n\tpublic: \n\n\t\ttypedef double Scalar;\n\t\ttypedef double RealScalar;\n\t\ttypedef int StorageIndex;\n\n\t\tenum {\n\t\t\tColsAtCompileTime = Eigen::Dynamic,\n\t\t\tMaxColsAtCompileTime = Eigen::Dynamic,\n\t\t\tIsRowMajor = false\n\t\t};\n\n\t\tIndex rows() const {return this-> _size;}\n\t\tIndex cols() const {return this-> _size;}\n\n\t\ttemplate<typename Vtype>\n\t\tEigen::Product<MatrixFreeOperator,Vtype,Eigen::AliasFreeProduct> operator*(const Eigen::MatrixBase<Vtype>& x) const {\n\t\t\treturn Eigen::Product<MatrixFreeOperator,Vtype,Eigen::AliasFreeProduct>(*this, x.derived());\n\t\t}\n\n\t\t// custom API\n\t\tMatrixFreeOperator();\n\n\t\t// convenience function\n\t\tEigen::MatrixXd get_full_mat() const;\n\t\tEigen::VectorXd diagonal() const;\n\t\tint get_size() const {return this->_size;}\n\t\tvoid set_size(int N) {this->_size = N;}\n\n\t\t// extract row/col of the operator\n\t\tvirtual Eigen::VectorXd col(int index) const = 0;\t\n\t\tEigen::VectorXd diag_el;\t\n\n\tprotected:\n\n\t\tint _size;\n};\n\nnamespace Eigen{\n\t\n\tnamespace internal{\n\n\t\t// replacement of the mat*vect operation\n\t\ttemplate<typename Vtype>\n\t\tstruct generic_product_impl<MatrixFreeOperator, Vtype, DenseShape, DenseShape, GemvProduct> \n\t\t: generic_product_impl_base<MatrixFreeOperator,Vtype,generic_product_impl<MatrixFreeOperator,Vtype>>\n\t\t{\n\n\t\t\ttypedef typename Product<MatrixFreeOperator,Vtype>::Scalar Scalar;\n\n\t\t\ttemplate<typename Dest>\n\t\t\tstatic void scaleAndAddTo(Dest& dst, const MatrixFreeOperator& op, const Vtype &v, const Scalar& alpha)\n\t\t\t{\n\t\t\t\t//returns dst = alpha * op * v\n\t\t\t\t// alpha must be 1 here\n\t\t\t\tassert(alpha==Scalar(1) && \"scaling is not implemented\");\n\t\t\t\tEIGEN_ONLY_USED_FOR_DEBUG(alpha);\n\n\t\t\t\t// make the mat vect product\n\t\t\t\tfor (int i=0; i<op.cols(); i++)\n\t\t\t\t\tdst += v(i) * op.col(i);\n\t\t\t}\n\t\t};\n\n\t\t// replacement of the operator*matrix operation\n\t\ttemplate<typename Mtype>\n\t\tstruct generic_product_impl<MatrixFreeOperator, Mtype, DenseShape, DenseShape, GemmProduct> \n\t\t: generic_product_impl_base<MatrixFreeOperator, Mtype, generic_product_impl<MatrixFreeOperator,Mtype>>\n\t\t{\n\n\t\t\ttypedef typename Product<MatrixFreeOperator,Mtype>::Scalar Scalar;\n\n\t\t\ttemplate<typename Dest>\n\t\t\tstatic void scaleAndAddTo(Dest& dst, const MatrixFreeOperator& op, const Mtype &m, const Scalar& alpha)\n\t\t\t{\n\t\t\t\t//returns dst = alpha * op * v\n\t\t\t\t// alpha must be 1 here\n\t\t\t\tassert(alpha==Scalar(1) && \"scaling is not implemented\");\n\t\t\t\tEIGEN_ONLY_USED_FOR_DEBUG(alpha);\n\n\t\t\t\t// make the mat vect product\n\t\t\t\tfor (int i=0; i<op.cols();i++)\n\t\t\t\t{\n\t\t\t\t\tfor (int j=0; j<m.cols(); j++)\n\t\t\t\t\t\tdst.col(j) += m(i,j) * op.col(i);\t\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t};\n\t}\n}\n\n#endif\n\n", "meta": {"hexsha": "a2e31de1256f8520eb06d55b26d7c503519c3890", "size": 2932, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/MatrixFreeOperator.hpp", "max_stars_repo_name": "NLESC-JCER/DavidsonEigen", "max_stars_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T17:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T17:40:44.000Z", "max_issues_repo_path": "src/MatrixFreeOperator.hpp", "max_issues_repo_name": "NLESC-JCER/DavidsonEigen", "max_issues_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-07T14:45:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-07T14:45:08.000Z", "max_forks_repo_path": "src/MatrixFreeOperator.hpp", "max_forks_repo_name": "NLESC-JCER/DavidsonEigen", "max_forks_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-30T22:56:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T09:05:37.000Z", "avg_line_length": 26.1785714286, "max_line_length": 119, "alphanum_fraction": 0.7060027285, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.508092109015444}}
{"text": "#include <iostream>\n#include <chrono>\n#include <Eigen/Dense>\n#include <Eigen/src/Core/util/DisableStupidWarnings.h>\n\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n\nusing namespace std;\nusing namespace Eigen;\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n#include \"calc_cnv_res_equilibrium_NaHCO3_CaCl2.h\"\n#ifdef __cplusplus\n}\n#endif\n#include \"eq_exported_constanst.h\"\n\n// Generic functor\ntemplate <typename _Scalar, int NX = Eigen::Dynamic, int NY = Eigen::Dynamic>\nstruct Functor\n{\n    typedef _Scalar Scalar;\n    enum\n    {\n        InputsAtCompileTime = NX,\n        ValuesAtCompileTime = NY\n    };\n    typedef Eigen::Matrix<Scalar, InputsAtCompileTime, 1> InputType;\n    typedef Eigen::Matrix<Scalar, ValuesAtCompileTime, 1> ValueType;\n    typedef Eigen::Matrix<Scalar, ValuesAtCompileTime, InputsAtCompileTime> JacobianType;\n\n    int m_inputs, m_values;\n\n    Functor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\n    Functor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n    int inputs() const { return m_inputs; }\n    int values() const { return m_values; }\n};\n\nstruct my_functor : Functor<double>\n{\n    my_functor(void) : Functor<double>(2, 2) {}\n    int operator()(const Eigen::VectorXd &x, Eigen::VectorXd &fvec) const\n    {\n        // Implement y = 10*(x0+3)^2 + (x1-5)^2\n        fvec(0) = 10.0 * pow(x(0) + 3.0, 2) + pow(x(1) - 5.0, 2);\n        fvec(1) = 0;\n\n        return 0;\n    }\n};\n\nvoid testStackOverflowSampleOpt()\n{\n\n    int8_t N = 15;\n    double state_vals[15] = {-4.41410428, -5.986602, -7.88445742, -2.00194266, -8.30714557,\n                             -2.03389701, -4.23809309, -5.21713241, -7.94810423, -3.68749322,\n                             -2.34133052, -7.36356081, -3.85258587, -3.51907119, -2.001};\n\n    Eigen::VectorXd x;\n    x << -4.41410428, -5.986602, -7.88445742, -2.00194266, -8.30714557,\n        -2.03389701, -4.23809309, -5.21713241, -7.94810423, -3.68749322,\n        -2.34133052, -7.36356081, -3.85258587, -3.51907119, -2.001;\n    // x(0) = 2.0;\n    // x(1) = 3.0;\n    std::cout << \"x: \" << x << std::endl;\n\n    my_functor functor;\n    Eigen::NumericalDiff<my_functor> numDiff(functor);\n    Eigen::LevenbergMarquardt<Eigen::NumericalDiff<my_functor>, double> lm(numDiff);\n    lm.parameters.maxfev = 2000;\n    lm.parameters.xtol = 1.0e-10;\n    std::cout << lm.parameters.maxfev << std::endl;\n\n    int ret = lm.minimize(x);\n    std::cout << lm.iter << std::endl;\n    std::cout << ret << std::endl;\n\n    std::cout << \"x that minimizes the function: \" << x << std::endl;\n\n    std::cout << \"press [ENTER] to continue \" << std::endl;\n    std::cin.get();\n    return;\n}\n\nstruct hybrd_functor : Functor<double>\n{\n    hybrd_functor(int N, const VectorXd &concs_in, double TK_in) :\n        Functor<double>(N, N),\n        concs(concs_in),\n        TK(TK_in) {}\n\n    int operator()(const VectorXd &x, VectorXd &fvec) const\n    {\n        double temp, temp1, temp2;\n        const VectorXd::Index n = x.size();\n\n        assert(fvec.size() == n);\n        double *x_ptr = (double *)x.data();\n        double *fvec_ptr = fvec.data();\n        calc_cnv_res_equilibrium_NaHCO3_CaCl2(TK, (double *)concs.data(), x_ptr, fvec_ptr);\n\n        return 0;\n    }\n    int df(const VectorXd &x, MatrixXd &fjac)\n    {\n        const VectorXd::Index n = x.size();\n        assert(fjac.rows() == n);\n        assert(fjac.cols() == n);\n\n        double *x_ptr = (double *)x.data();\n        double *J_ptr = fjac.data();\n        calc_jac(TK, x_ptr, J_ptr);\n        fjac.transposeInPlace();\n        return 0;\n    }\n\n    private:\n        VectorXd concs;\n        double TK;\n};\n\nstd::chrono::duration<double> getElapsedTime(const std::chrono::time_point<std::chrono::system_clock> &start)\n{\n    std::chrono::time_point<std::chrono::system_clock> end = std::chrono::system_clock::now();\n    std::chrono::duration<double> elapsed_seconds = end - start;\n    return elapsed_seconds;\n}\n\nvoid testHybrj1()\n{\n    const int n = 15;\n    int info;\n    VectorXd x(n);\n    // x << -1, -5.986602  , -7.88445742, -2.00194266, -8.30714557,\n    //     -2.03389701, -4.23809309, -5.21713241, -7.94810423, -3.68749322,\n    //     -2.34133052, -7.36356081, -3.85258587, -3.51907119, -2.1;\n    VectorXd concs(2);\n    concs << 10e-3, 5e-3;\n    double TK = 25.0 + 273.15;\n\n    /* the following starting values provide a rough fit. */\n    x.setConstant(n, -1.);\n\n    std::cout << \"Hybr: w/o Jacobian\" << std::endl;\n    std::chrono::time_point<std::chrono::system_clock> start = std::chrono::system_clock::now();\n\n    hybrd_functor functor(n, concs, TK);\n    HybridNonLinearSolver<hybrd_functor> solver(functor);\n    info = solver.solveNumericalDiff(x);\n\n    std::cout << x << std::endl;\n    std::cout << \"Solution Code: \" << info << std::endl;\n    std::cout << \"Elapsed: \" << getElapsedTime(start).count() << \" s\" << std::endl;\n\n    //-----------------------------------------------------------------------\n    x.setConstant(n, -1.);\n    std::cout << \"Hybr: w/ Jacobian\" << std::endl;\n    start = std::chrono::system_clock::now();\n\n    hybrd_functor functorJac(n, concs, TK);\n    HybridNonLinearSolver<hybrd_functor> solverJac(functorJac);\n    info = solverJac.hybrj1(x);\n\n    std::cout << x << std::endl;\n    std::cout << \"Solution Code: \" << info << std::endl;\n    std::cout << \"Elapsed: \" << getElapsedTime(start).count() << \" s\" << std::endl;\n\n    //-----------------------------------------------------------------------\n    std::cout << \"Calculating Calcite Saturation Index:\" << info << std::endl;\n    double SI_calcite = calc_phase_SI_Calcite(TK, x.data());\n    std::cout << \"SI Calcite = \" << SI_calcite << std::endl;\n\n    VectorXd gammas(n);\n    calc_gammas(TK, x.data(), gammas.data());\n    std::cout << \"Gammas: \\n \" << gammas << std::endl;\n    double pH = - log10(pow(10, x[IDX_SPECIES[\"H+\"]]) * gammas[IDX_SPECIES[\"H+\"]]);\n    std::cout << \"pH = \" << pH << std::endl;\n\n    return;\n}\n\nint main(int argc, char *argv[])\n{\n    testHybrj1();\n    return 0;\n}\n", "meta": {"hexsha": "fe72ecf7e165bfe71f280aa09121c6977406c3fc", "size": 6016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/code_generation/solve_with_eigen/solve_eq_eigen.cpp", "max_stars_repo_name": "caiofcm/pyequion", "max_stars_repo_head_hexsha": "762ce1fb68cbbf35e52f7d4db2c34bd29f1dd18c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-12-08T19:54:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T23:51:52.000Z", "max_issues_repo_path": "samples/code_generation/solve_with_eigen/solve_eq_eigen.cpp", "max_issues_repo_name": "caiofcm/pyequion", "max_issues_repo_head_hexsha": "762ce1fb68cbbf35e52f7d4db2c34bd29f1dd18c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-04T13:21:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-10T19:26:08.000Z", "max_forks_repo_path": "samples/code_generation/solve_with_eigen/solve_eq_eigen.cpp", "max_forks_repo_name": "caiofcm/pyequion", "max_forks_repo_head_hexsha": "762ce1fb68cbbf35e52f7d4db2c34bd29f1dd18c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-02-05T11:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T22:25:39.000Z", "avg_line_length": 31.0103092784, "max_line_length": 109, "alphanum_fraction": 0.5972406915, "num_tokens": 1867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5080920981322267}}
{"text": "/*\n * wave_equation_reference2.cpp\n *\n *  Created on: 27.05.2019\n *      Author: thies\n */\n\n#include <base/AdaptiveMesh.h>\n#include <base/ConstantMesh.h>\n#include <base/DiscretizedFunction.h>\n#include <base/SpaceTimeMesh.h>\n#include <base/Util.h>\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/numbers.h>\n#include <deal.II/base/point.h>\n#include <deal.II/base/quadrature.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/grid/tria.h>\n#include <forward/L2RightHandSide.h>\n#include <forward/WaveEquation.h>\n#include <gtest/gtest.h>\n#include <norms/L2H1.h>\n#include <norms/L2L2.h>\n#include <stddef.h>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <vector>\n\nnamespace {\n\nusing namespace dealii;\nusing namespace wavepi::forward;\nusing namespace wavepi::base;\nusing namespace wavepi;\n\n/*****\nNOTE: This module is used for automatic figure generation \nand should therefore only be changed together with the thesis! \n*****/\n\ntemplate <int dim>\nclass TestQ : public LightFunction<dim> {\n public:\n  virtual ~TestQ() = default;\n\n  virtual double evaluate(const Point<dim> &p, const double t) const { return 0.05*t+0.05*p[0]*p[1]; }\n};\n\ntemplate <int dim>\nclass TestNu : public LightFunction<dim> {\n public:\n  virtual ~TestNu() = default;\n\n  virtual double evaluate(const Point<dim> &p, const double t) const { return 0.05*abs(cos(p[1]*t)); }\n};\n\ntemplate <int dim>\nclass TestC : public LightFunction<dim> {\n public:\n  virtual ~TestC() = default;\n\n  virtual double evaluate(const Point<dim> &p, const double t) const { return sqrt(1 + t) * (1 + p[0]); }\n};\n\ntemplate <int dim>\nclass TestRho : public LightFunction<dim> {\n public:\n  virtual ~TestRho() = default;\n\n  virtual double evaluate(const Point<dim> &p, const double t) const { return (1 + t) * (1 + p[1]); }\n};\n\ntemplate <int dim>\nclass TestU : public Function<dim> {\n public:\n  virtual ~TestU() = default;\n\n  virtual double value(const Point<dim> &p, const unsigned int component __attribute__((unused))) const {\n    double tmp = 1;\n\n    for (size_t i = 0; i < dim; i++)\n      tmp *= sin(p[i]);\n\n    return cos(this->get_time()) * tmp;\n  }\n\n  virtual double evaluate(const Point<dim> &p, double t) const {\n    double tmp = 1;\n\n    for (size_t i = 0; i < dim; i++)\n      tmp *= sin(p[i]);\n\n    return cos(t) * tmp;\n  }\n\n  virtual Tensor<1, dim, double> gradient(const Point<dim> &p,\n                                          const unsigned int component __attribute__((unused))) const {\n    Tensor<1, dim, double> res;\n\n    for (size_t j = 0; j < dim; j++) {\n      double tmp = 1;\n\n      for (size_t i = 0; i < dim; i++)\n        if (i != j) tmp *= sin(p[i]);\n\n      tmp *= cos(p[j]);\n      res[j] = cos(this->get_time()) * tmp;\n    }\n\n    return res;\n  }\n};\n\ntemplate <int dim>\nclass TestV : public LightFunction<dim> {\n public:\n  virtual ~TestV() = default;\n\n  virtual double evaluate(const Point<dim> &p, const double t) const {\n    double tmp = 1;\n\n    for (size_t i = 0; i < dim; i++)\n      tmp *= sin(p[i]);\n\n    return -sin(t) * tmp;\n  }\n};\n\ntemplate <int dim>\nclass TestF : public LightFunction<dim> {\n public:\n  virtual ~TestF() = default;\n\n  virtual double evaluate(const Point<dim> &p, const double t) const {\n    double tmp2 = 1;\n    for (size_t i = 0; i < dim; i++)\n      tmp2 *= sin(p[i]);\n\n    // 1/rho (u'/c^2)'\n    double tmp =\n        tmp2 * (sin(t) - (1 + t) * cos(t)) / ((1 + t) * (1 + t) * (1 + t) * (1 + p[0]) * (1 + p[0]) * (1 + p[1]));\n\n    // div (nabla u / rho)\n\n    double fac = cos(t) / ((1 + t) * (1 + p[1]));\n    tmp -= -dim * fac * tmp2;\n\n    double tmp3 = cos(p[1]);\n    for (size_t i = 0; i < dim; i++)\n      if (i != 1) tmp3 *= sin(p[i]);\n\n    tmp -= -1 * fac * tmp3 / (1 + p[1]);\n\n    // q and nu\n    tmp+= q.evaluate(p, t) * u.evaluate(p,t) + nu.evaluate(p,t)*v.evaluate(p,t); \n\n    return tmp;\n  }\n\n  TestQ<dim> q; \n  TestNu<dim> nu;\n  TestU<dim> u; \n  TestV<dim> v;\n};\n\ntemplate <int dim>\nvoid run_reference_test2(std::shared_ptr<SpaceTimeMesh<dim>> mesh, int refines, bool expect = true, bool save = false,\n                         std::shared_ptr<std::ofstream> log = nullptr, int precondition = -1) {\n  deallog << std::endl << \"----------  n_dofs(0): \" << mesh->get_dof_handler(0)->n_dofs();\n  deallog << \", n_steps: \" << mesh->get_times().size() << \"  ----------\" << std::endl;\n\n  WaveEquation<dim> wave_eq(mesh);\n  wave_eq.set_precondition_max_age(precondition);\n\n  wave_eq.set_param_rho(std::make_shared<TestRho<dim>>());\n  wave_eq.set_param_c(std::make_shared<TestC<dim>>());\n  wave_eq.set_param_q(std::make_shared<TestQ<dim>>());\n  wave_eq.set_param_nu(std::make_shared<TestNu<dim>>());\n\n  auto u_cont = std::make_shared<TestU<dim>>();\n  auto v_cont = std::make_shared<TestV<dim>>();\n\n  wave_eq.set_initial_values_u(u_cont);\n  wave_eq.set_initial_values_v(v_cont);\n\n  Timer timer;\n  timer.start();\n  DiscretizedFunction<dim> solu = wave_eq.run(std::make_shared<L2RightHandSide<dim>>(std::make_shared<TestF<dim>>()));\n  timer.stop();\n\n  DiscretizedFunction<dim> solv = solu.derivative();\n  solu.throw_away_derivative();\n\n  DiscretizedFunction<dim> u_disc(mesh, *u_cont);\n  DiscretizedFunction<dim> tmp_u(solu);\n  tmp_u -= u_disc;\n\n  DiscretizedFunction<dim> v_disc(mesh, *v_cont);\n  DiscretizedFunction<dim> tmp_v(solv);\n  tmp_v -= v_disc;\n\n  u_disc.set_norm(std::make_shared<norms::L2L2<dim>>());\n  double err_u_L2L2 = norms::L2L2<dim>::absolute_error(solu, *u_cont) / u_disc.norm();\n\n  u_disc.set_norm(std::make_shared<norms::L2H1<dim>>());\n  double err_u_L2H1 = norms::L2H1<dim>::absolute_error(solu, *u_cont) / u_disc.norm();\n\n  v_disc.set_norm(std::make_shared<norms::L2L2<dim>>());\n  double err_v_L2L2 = norms::L2L2<dim>::absolute_error(solv, *v_cont) / v_disc.norm();\n\n  tmp_u.set_norm(std::make_shared<norms::L2L2<dim>>());\n  u_disc.set_norm(std::make_shared<norms::L2L2<dim>>());\n  double err_u_L2L2_disc = tmp_u.norm() / u_disc.norm();\n\n  tmp_u.set_norm(std::make_shared<norms::L2H1<dim>>());\n  u_disc.set_norm(std::make_shared<norms::L2H1<dim>>());\n  double err_u_L2H1_disc = tmp_u.norm() / u_disc.norm();\n\n  tmp_v.set_norm(std::make_shared<norms::L2L2<dim>>());\n  v_disc.set_norm(std::make_shared<norms::L2L2<dim>>());\n  double err_v_L2L2_disc = tmp_v.norm() / v_disc.norm();\n\n  if (expect) {\n    EXPECT_LT(err_u_L2L2, 1e-1);\n    EXPECT_LT(err_v_L2L2, 1e-1);\n  }\n\n  if (save) {\n    DiscretizedFunction<dim> u_disc2(mesh, *u_cont);\n\n    DiscretizedFunction<dim> tmp(solu);\n    tmp -= u_disc2;\n\n    u_disc2.write_pvd(\"./\", \"refu\", \"uref\");\n    solu.write_pvd(\"./\", \"solu\", \"u\");\n    tmp.write_pvd(\"./\", \"diff\", \"udiff\");\n  }\n\n  deallog << std::scientific << \" L2L2 rerr of u = \" << err_u_L2L2 << \" (disc: \" << err_u_L2L2_disc\n          << \"), L2L2 rerr of v = \" << err_v_L2L2 << \" (disc: \" << err_v_L2L2_disc\n          << \"), L2H1 rerr of u = \" << err_u_L2H1 << \" (disc: \" << err_u_L2H1_disc << \"), cpu = \" << std::fixed\n          << std::setprecision(2) << timer.cpu_time() << \"s\" << std::endl;\n\n  double dt = mesh->get_time(1) - mesh->get_time(0);\n  double h  = dealii::GridTools::maximal_cell_diameter(*mesh->get_triangulation(0));\n\n  if (log)\n    *log << std::scientific << mesh->length() << \" \" << dt << \" \" << refines << \" \" << h << \" \" << err_u_L2L2 << \" \"\n         << err_v_L2L2 << \" \" << err_u_L2H1 << std::endl;\n}\n\ntemplate <int dim>\nvoid run_reference_test2_constant(int fe_order, int quad_order, int refines, int steps, bool expect = true,\n                                  bool save = false, std::shared_ptr<std::ofstream> log = nullptr,\n                                  int precondition = -1) {\n  auto triangulation = std::make_shared<Triangulation<dim>>();\n  GridGenerator::hyper_cube(*triangulation, 0.0, numbers::PI);\n  Util::set_all_boundary_ids(*triangulation, 0);\n  triangulation->refine_global(refines);\n\n  double t_end   = 3.0;\n  double t_start = 0.0, dt = t_end / (steps - 1);\n  std::vector<double> times;\n\n  for (size_t i = 0; t_start + i * dt <= t_end; i++)\n    times.push_back(t_start + i * dt);\n\n  FE_Q<dim> fe(fe_order);\n  Quadrature<dim> quad = QGauss<dim>(quad_order);  // exact in poly degree 2n-1 (needed: fe_dim^3)\n\n  std::shared_ptr<SpaceTimeMesh<dim>> mesh = std::make_shared<ConstantMesh<dim>>(times, fe, quad, triangulation);\n\n  return run_reference_test2<dim>(mesh, refines, expect, save, log, precondition);\n}\n\nTEST(WaveEquation, ReferenceTestParameters2DFE1) {\n  auto file_time = std::make_shared<std::ofstream>(\"./ReferenceTestParameters2DFE1_time.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*file_time) << \"could not open file for output\";\n\n  for (int steps = 4; steps <= 128; steps = (int)(steps * 1.41))\n    run_reference_test2_constant<2>(1, 5, 9, steps, steps >= 64, false, file_time);\n  file_time->close();\n\n  auto file_space = std::make_shared<std::ofstream>(\"./ReferenceTestParameters2DFE1_space.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*file_space) << \"could not open file for output\";\n\n  for (int refine = 1; refine <= 9; refine++)\n    run_reference_test2_constant<2>(1, 5, refine, 256, refine >= 4, false, file_space);\n  file_space->close();\n}\n\nTEST(WaveEquation, ReferenceTestParameters2DFE2) {\n  auto file_space = std::make_shared<std::ofstream>(\"./ReferenceTestParameters2DFE2_space.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*file_space) << \"could not open file for output\";\n\n  for (int refine = 1; refine <= 5; refine++)\n    run_reference_test2_constant<2>(2, 5, refine, 1024, refine >= 4, false, file_space);\n  file_space->close();\n}\n\nTEST(WaveEquation, ReferenceTestParameters3DFE1) {\n  auto file_time = std::make_shared<std::ofstream>(\"./ReferenceTestParameters3DFE1_time.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*file_time) << \"could not open file for output\";\n\n  for (int steps = 4; steps <= 16; steps = (int)(steps * 1.41))\n    run_reference_test2_constant<3>(1, 5, 6, steps, steps >= 64, false, file_time);\n  file_time->close();\n\n  auto file_space = std::make_shared<std::ofstream>(\"./ReferenceTestParameters3DFE1_space.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*file_space) << \"could not open file for output\";\n\n  for (int refine = 1; refine <= 6; refine++)\n    run_reference_test2_constant<3>(1, 5, refine, 256, refine >= 4, false, file_space);\n  file_space->close();\n}\n\nTEST(WaveEquation, ReferenceTestParameters3DFE2) {\n  auto file_space = std::make_shared<std::ofstream>(\"./ReferenceTestParameters3DFE2_space.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*file_space) << \"could not open file for output\";\n\n  for (int refine = 1; refine <= 4; refine++)\n    run_reference_test2_constant<3>(2, 5, refine, 128, refine >= 4, false, file_space);\n  file_space->close();\n}\n\nTEST(WaveEquation, PreconditionTest2DFE1) {\n  for (int i = 0; i <= 9; i++) {\n    int max_age;\n    if (i == 0)\n      max_age = -1;\n    else if (i == 1)\n      max_age = 0;\n    else\n      max_age = 1 << (i - 2);\n\n    run_reference_test2_constant<2>(1, 5, 6, 128, false, false, nullptr, max_age);\n    deallog << \" precon = \" << max_age << std::endl;\n  }\n}\n\nTEST(WaveEquation, PreconditionTest2DFE2) {\n  for (int i = 0; i <= 9; i++) {\n    int max_age;\n    if (i == 0)\n      max_age = -1;\n    else if (i == 1)\n      max_age = 0;\n    else\n      max_age = 1 << (i - 2);\n\n    run_reference_test2_constant<2>(2, 5, 6, 128, false, false, nullptr, max_age);\n    deallog << \" precon = \" << max_age << std::endl;\n  }\n}\n}  // namespace", "meta": {"hexsha": "9bc1cae867be10977b3d9eef2eb9931cd99602e6", "size": 11511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/wave_equation_reference2.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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/wave_equation_reference2.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/wave_equation_reference2.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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.7983425414, "max_line_length": 118, "alphanum_fraction": 0.6402571453, "num_tokens": 3570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.5080676517581149}}
{"text": "//  (C) Copyright Eric Niebler 2005.\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// Test case for extended_p_square_quantile.hpp\n\n#include <iostream>\n#include <boost/random.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/numeric/functional/vector.hpp>\n#include <boost/accumulators/numeric/functional/complex.hpp>\n#include <boost/accumulators/numeric/functional/valarray.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/extended_p_square_quantile.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace boost::accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    typedef accumulator_set<double, stats<tag::extended_p_square_quantile> > accumulator_t;\n    typedef accumulator_set<double, stats<tag::weighted_extended_p_square_quantile>, double > accumulator_t_weighted;\n    typedef accumulator_set<double, stats<tag::extended_p_square_quantile(quadratic)> > accumulator_t_quadratic;\n    typedef accumulator_set<double, stats<tag::weighted_extended_p_square_quantile(quadratic)>, double > accumulator_t_weighted_quadratic;\n\n    // tolerance\n    double epsilon = 1;\n\n    // a random number generator\n    boost::lagged_fibonacci607 rng;\n\n    std::vector<double> probs;\n\n    probs.push_back(0.990);\n    probs.push_back(0.991);\n    probs.push_back(0.992);\n    probs.push_back(0.993);\n    probs.push_back(0.994);\n    probs.push_back(0.995);\n    probs.push_back(0.996);\n    probs.push_back(0.997);\n    probs.push_back(0.998);\n    probs.push_back(0.999);\n\n    accumulator_t acc(extended_p_square_probabilities = probs);\n    accumulator_t_weighted acc_weighted(extended_p_square_probabilities = probs);\n    accumulator_t_quadratic acc2(extended_p_square_probabilities = probs);\n    accumulator_t_weighted_quadratic acc_weighted2(extended_p_square_probabilities = probs);\n\n    for (int i=0; i<10000; ++i)\n    {\n        double sample = rng();\n        acc(sample);\n        acc2(sample);\n        acc_weighted(sample, weight = 1.);\n        acc_weighted2(sample, weight = 1.);\n    }\n\n    for (std::size_t i = 0; i < probs.size() - 1; ++i)\n    {\n        BOOST_CHECK_CLOSE(\n            quantile(acc, quantile_probability = 0.99025 + i*0.001)\n          , 0.99025 + i*0.001\n          , epsilon\n        );\n        BOOST_CHECK_CLOSE(\n            quantile(acc2, quantile_probability = 0.99025 + i*0.001)\n          , 0.99025 + i*0.001\n          , epsilon\n        );\n        BOOST_CHECK_CLOSE(\n            quantile(acc_weighted, quantile_probability = 0.99025 + i*0.001)\n          , 0.99025 + i*0.001\n          , epsilon\n        );\n        BOOST_CHECK_CLOSE(\n            quantile(acc_weighted2, quantile_probability = 0.99025 + i*0.001)\n          , 0.99025 + i*0.001\n          , epsilon\n        );\n    }\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"extended_p_square_quantile test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n\n", "meta": {"hexsha": "e56223b2ad368fcb38a8c93585fb3c64ec2ec6b5", "size": 3404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/accumulators/test/extended_p_square_quantile.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/accumulators/test/extended_p_square_quantile.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/accumulators/test/extended_p_square_quantile.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 33.0485436893, "max_line_length": 138, "alphanum_fraction": 0.6618683901, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5080521738809483}}
{"text": "#pragma once\n\n/*\n * Model a non-convex optimization problem by defining Cost and Constraint objects\n * which know how to generate a convex approximation\n *\n *\n */\n\n#include <vector>\n#include <boost/shared_ptr.hpp>\n#include <trajopt_sco/sco_fwd.hpp>\n#include <trajopt_sco/solver_interface.hpp>\n\nnamespace sco {\n\nusing std::vector;\n\n/**\nStores convex terms in a objective\nFor non-quadratic terms like hinge(x) and abs(x), it needs to add auxilliary variables and linear constraints to the model\nNote: When this object is deleted, the constraints and variables it added to the model are removed\n */\nclass ConvexObjective {\npublic:\n  ConvexObjective(Model* model) : model_(model) {}\n  void addAffExpr(const AffExpr&);\n  void addQuadExpr(const QuadExpr&);\n  void addHinge(const AffExpr&, double coeff);\n  void addAbs(const AffExpr&, double coeff);\n  void addHinges(const AffExprVector&);\n  void addL1Norm(const AffExprVector&);\n  void addL2Norm(const AffExprVector&);\n  void addMax(const AffExprVector&);\n  \n  bool inModel() {\n    return model_ != NULL;\n  }\n  void addConstraintsToModel();\n  void removeFromModel();\n  double value(const vector<double>& x);\n  \n  ~ConvexObjective();\n\n  \n  Model* model_;\n  QuadExpr quad_;\n  vector<Var> vars_;\n  vector<AffExpr> eqs_;\n  vector<AffExpr> ineqs_;\n  vector<Cnt> cnts_;\nprivate:\n  ConvexObjective()  {}\n  ConvexObjective(ConvexObjective&)  {}\n};\n\n/**\nStores convex inequality constraints and affine equality constraints.\nActually only affine inequality constraints are currently implemented.\n*/\nclass ConvexConstraints {\npublic:\n  ConvexConstraints(Model* model) : model_(model) {}\n  /** Expression that should == 0 */\n  void addEqCnt(const AffExpr&);\n  /** Expression that should <= 0 */\n  void addIneqCnt(const AffExpr&);\n  void setModel(Model* model) {\n    assert(!inModel());\n    model_ = model;\n  }\n  bool inModel() {\n    return model_ != NULL;\n  }\n  void addConstraintsToModel();\n  void removeFromModel();\n\n  vector<double> violations(const vector<double>& x);\n  double violation(const vector<double>& x);\n\n  ~ConvexConstraints();\n  vector<AffExpr> eqs_;\n  vector<AffExpr> ineqs_;\nprivate:\n   Model* model_;\n   vector<Cnt> cnts_;\n   ConvexConstraints() : model_(NULL) {}\n   ConvexConstraints(ConvexConstraints&) {}\n};\n\n/**\nNon-convex cost function, which knows how to calculate its convex approximation (convexify() method)\n*/\nclass Cost {\npublic:\n  /** Evaluate at solution vector x*/\n  virtual double value(const vector<double>&) = 0;\n  /** Convexify at solution vector x*/\n  virtual ConvexObjectivePtr convex(const vector<double>& x, Model* model) = 0;\n  /** Get problem variables associated with this cost */\n  virtual VarVector getVars() {return VarVector();}\n\n  string name() {return name_;}\n  void setName(const string& name) {name_=name;}\n  Cost() : name_(\"unnamed\") {}\n  Cost(const string& name) : name_(name) {}\n  virtual ~Cost() {}\nprotected:\n  string name_;\n};\n\n/**\nNon-convex vector-valued constraint function, which knows how to calculate its convex approximation\n*/\nclass Constraint {\npublic:\n\n  /** inequality vs equality */\n  virtual ConstraintType type() = 0;\n  /** Evaluate at solution vector x*/  \n  virtual vector<double> value(const vector<double>& x) = 0;\n  /** Convexify at solution vector x*/  \n  virtual ConvexConstraintsPtr convex(const vector<double>& x, Model* model) = 0;\n  /** Calculate constraint violations (positive part for inequality constraint, absolute value for inequality constraint)*/\n  vector<double> violations(const vector<double>& x);\n  /** Sum of violations */\n  double violation(const vector<double>& x);\n  /** Get problem variables associated with this constraint */\n  virtual VarVector getVars() {return VarVector();}\n\n  string name() {return name_;}\n  void setName(const string& name) {name_=name;}\n  Constraint() : name_(\"unnamed\") {}\n  Constraint(const string& name) : name_(name) {}\n  virtual ~Constraint() {}\n\nprotected:\n  string name_;\n};\n\nclass EqConstraint : public Constraint{\npublic:\n  ConstraintType type() {return EQ;}\n};\n\nclass IneqConstraint : public Constraint {\npublic:\n  ConstraintType type() {return INEQ;}\n};\n\n/**\nNon-convex optimization problem\n*/\nclass OptProb {\npublic:\n  OptProb();\n  /** create variables with bounds [-INFINITY, INFINITY]  */\n  VarVector createVariables(const vector<string>& names);\n  /** create variables with bounds [lb[i], ub[i] */\n  VarVector createVariables(const vector<string>& names, const vector<double>& lb, const vector<double>& ub);\n  /** set the lower bounds of all the variables */\n  void setLowerBounds(const vector<double>& lb);\n  /** set the upper bounds of all the variables */\n  void setUpperBounds(const vector<double>& ub);\n  /** set lower bounds of some of the variables */\n  void setLowerBounds(const vector<double>& lb, const vector<Var>& vars);\n  /** set upper bounds of some of the variables */\n  void setUpperBounds(const vector<double>& ub, const vector<Var>& vars);\n  /** Note: in the current implementation, this function just adds the constraint to the\n   * model. So if you're not careful, you might end up with an infeasible problem. */\n  void addLinearConstraint(const AffExpr&, ConstraintType type);\n  /** Add nonlinear cost function */\n  void addCost(CostPtr);\n  /** Add nonlinear constraint function */\n  void addConstraint(ConstraintPtr);\n  void addEqConstraint(ConstraintPtr);\n  void addIneqConstraint(ConstraintPtr);\n  virtual ~OptProb() {}\n  /** Find closest point to solution vector x that satisfies linear inequality constraints */\n  vector<double> getCentralFeasiblePoint(const vector<double>& x);\n  vector<double> getClosestFeasiblePoint(const vector<double>& x);\n\n  vector<ConstraintPtr> getConstraints() const;\n  vector<CostPtr>& getCosts() {return costs_;}\n  vector<ConstraintPtr>& getIneqConstraints() {return ineqcnts_;}\n  vector<ConstraintPtr>& getEqConstraints() {return eqcnts_;}\n  DblVec& getLowerBounds() {return lower_bounds_;}\n  DblVec& getUpperBounds() {return upper_bounds_;}\n  ModelPtr getModel() {return model_;}\n  vector<Var>& getVars() {return vars_;}\n  int getNumCosts() {return costs_.size();}\n  int getNumConstraints() {return eqcnts_.size() + ineqcnts_.size();}\n  int getNumVars() {return vars_.size();}\n\nprotected:\n  ModelPtr model_;\n  vector<Var> vars_;\n  vector<double> lower_bounds_;\n  vector<double> upper_bounds_;\n  vector<CostPtr> costs_;\n  vector<ConstraintPtr> eqcnts_;\n  vector<ConstraintPtr> ineqcnts_;\n\n  OptProb(OptProb&);\n};\n\ntemplate <typename VecType>\ninline void setVec(DblVec& x, const VarVector& vars, const VecType& vals) {\n  assert(vars.size() == vals.size());\n  for (int i = 0; i < vars.size(); ++i) {\n    x[vars[i].var_rep->index] = vals[i];\n  }\n}\ntemplate <typename OutVecType>\ninline OutVecType getVec1(const vector<double>& x, const VarVector& vars) {\n  OutVecType out(vars.size());\n  for (unsigned i=0; i < vars.size(); ++i) out[i] = x[vars[i].var_rep->index];\n  return out;\n}\n\n\n}\n", "meta": {"hexsha": "22ddd8345fac8837fdfdceaa89bb25df22c60e50", "size": 6909, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trajopt_sco/include/trajopt_sco/modeling.hpp", "max_stars_repo_name": "Levi-Armstrong/trajopt_ros", "max_stars_repo_head_hexsha": "a90cd90478d4048af501ad503360d8dfd7460f20", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T14:43:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-09T16:41:36.000Z", "max_issues_repo_path": "trajopt_sco/include/trajopt_sco/modeling.hpp", "max_issues_repo_name": "Levi-Armstrong/trajopt_ros", "max_issues_repo_head_hexsha": "a90cd90478d4048af501ad503360d8dfd7460f20", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T04:57:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-07T21:46:45.000Z", "max_forks_repo_path": "trajopt_sco/include/trajopt_sco/modeling.hpp", "max_forks_repo_name": "Levi-Armstrong/trajopt_ros", "max_forks_repo_head_hexsha": "a90cd90478d4048af501ad503360d8dfd7460f20", "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.9820627803, "max_line_length": 123, "alphanum_fraction": 0.7174699667, "num_tokens": 1695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.508052169985497}}
{"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 <cstdlib>\n#include <ctime>\n#include <iostream>\n#include <limits>\n#include <memory>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n#include \"functions.hpp\"\n#include \"layers.hpp\"\n#include \"lstm/cell.hpp\"\n#include \"util.hpp\"\n\nnamespace nn {\n\nstd::string SOS_TOKEN = \"~\";\nstd::string EOS_TOKEN = \"#\";\n\nclass LSTMNetwork {\n  private:\n    size_t n_layers;\n    int batch_size;\n    int embedding_dim;\n    int n_tokens;\n    int hidden_size;\n\n    Embedding embedding;\n    std::vector<LSTMCell> layers;\n    Dense out;\n\n    std::vector<std::vector<LSTMState>> states;\n\n    friend class util::Trainer;\n\n  public:\n    explicit LSTMNetwork(const size_t &, const int &, const int &, const int &, const int &);\n\n    MatrixXf operator()(const MatrixXf &);\n\n    MatrixXf forward(const MatrixXf &);\n\n    void backward(const MatrixXf &);\n};\n\nLSTMNetwork::LSTMNetwork(const size_t &n_layers, const int &hidden_size, const int &n_tokens, const int &embedding_dim, const int &batch_size)\n    : embedding(Embedding(n_tokens, embedding_dim)), out(Dense(hidden_size, n_tokens)) {\n\n    this->n_layers = n_layers;\n    this->hidden_size = hidden_size;\n    this->n_tokens = n_tokens;\n    this->embedding_dim = embedding_dim;\n    this->batch_size = batch_size;\n\n    // initial layer (embedding -> hidden)\n    layers.push_back(LSTMCell(hidden_size, embedding_dim, batch_size));\n    for (size_t i = 1; i < n_layers; i++) {\n        // rest of the layers (hidden -> hidden)\n        layers.push_back(LSTMCell(hidden_size, hidden_size, batch_size));\n    }\n}\n\nMatrixXf LSTMNetwork::operator()(const MatrixXf &inputs) {\n    return forward(inputs);\n}\n\nMatrixXf LSTMNetwork::forward(const MatrixXf &inputs) {\n    std::vector<LSTMState> t_states;\n    MatrixXf output = embedding(inputs);\n    for (size_t i = 0; i < layers.size(); i++) {\n        output = layers[i](output);\n        t_states.push_back(layers[i].state);\n    }\n    states.push_back(t_states);\n    MatrixXf logits = out(output);\n    return F::log_softmax(logits);\n}\n\n// void LSTMNetwork::backward(const MatrixXf &loss_grad) {\n\n//     states.clear();\n// }\n} // namespace nn", "meta": {"hexsha": "354ce375c279a6da99be18ed1058cb59eb02a8ff", "size": 3352, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lstm/network.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/lstm/network.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/lstm/network.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": 29.6637168142, "max_line_length": 142, "alphanum_fraction": 0.7061455847, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5080521699854968}}
{"text": "#include <stan/math/rev/mat.hpp>\n#include <gtest/gtest.h>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <boost/numeric/odeint.hpp>\n#include <test/unit/math/rev/mat/functor/util_cvodes.hpp>\n#include <test/unit/math/prim/arr/functor/harmonic_oscillator.hpp>\n#include <test/unit/math/prim/arr/functor/lorenz.hpp>\n\ntemplate <typename F, typename T_y0, typename T_theta>\nvoid sho_value_test(F harm_osc,\n                    std::vector<double>& y0,\n                    double t0,\n                    std::vector<double>& ts,\n                    std::vector<double>& theta,\n                    std::vector<double>& x,\n                    std::vector<int>& x_int) {\n\n  using stan::math::var;\n  using stan::math::promote_scalar;\n\n  std::vector<std::vector<var> > ode_res_vd\n    = stan::math::integrate_ode_bdf(harm_osc, promote_scalar<T_y0>(y0), t0,\n                                    ts, promote_scalar<T_theta>(theta), x,\n                                    x_int);\n\n  EXPECT_NEAR(0.995029, ode_res_vd[0][0].val(), 1e-5);\n  EXPECT_NEAR(-0.0990884, ode_res_vd[0][1].val(), 1e-5);\n\n  EXPECT_NEAR(-0.421907, ode_res_vd[99][0].val(), 1e-5);\n  EXPECT_NEAR(0.246407, ode_res_vd[99][1].val(), 1e-5);\n}\n\nvoid sho_finite_diff_test(double t0) {\n  using stan::math::var;\n  harm_osc_ode_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n\n  test_ode_cvode(harm_osc, t0, ts, y0, theta, x, x_int, 1e-8, 1e-4);\n\n  sho_value_test<harm_osc_ode_fun, double, var>\n    (harm_osc, y0, t0, ts, theta, x, x_int);\n  sho_value_test<harm_osc_ode_fun, var, double>\n    (harm_osc, y0, t0, ts, theta, x, x_int);\n  sho_value_test<harm_osc_ode_fun, var, var>\n    (harm_osc, y0, t0, ts, theta, x, x_int);\n}\n\nvoid sho_data_finite_diff_test(double t0) {\n  using stan::math::var;\n  harm_osc_ode_data_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x(3,1);\n  std::vector<int> x_int(2,0);\n\n  test_ode_cvode(harm_osc, t0, ts, y0, theta, x, x_int, 1e-8, 1e-4);\n\n  sho_value_test<harm_osc_ode_data_fun,double,var>(harm_osc, y0, t0, ts,\n                                                   theta, x, x_int);\n  sho_value_test<harm_osc_ode_data_fun,var,double>(harm_osc, y0, t0, ts,\n                                                   theta, x, x_int);\n  sho_value_test<harm_osc_ode_data_fun,var,var>(harm_osc, y0, t0, ts,\n                                                theta, x, x_int);\n}\n\ntemplate <typename T_y0, typename T_theta, typename F>\nvoid sho_error_test(F harm_osc,\n                    std::vector<double>& y0,\n                    double t0,\n                    std::vector<double>& ts,\n                    std::vector<double>& theta,\n                    std::vector<double>& x,\n                    std::vector<int>& x_int,\n                    std::string error_msg) {\n\n  using stan::math::var;\n  using stan::math::promote_scalar;\n\n\n  EXPECT_THROW_MSG(stan::math::integrate_ode_bdf(harm_osc, promote_scalar<T_y0>(y0), t0,\n                                                 ts, promote_scalar<T_theta>(theta), x,\n                                                 x_int),\n                   std::runtime_error,\n                   error_msg);\n}\n\n\n// TODO(carpenter): g++6 failure\nTEST(StanAgradRevOde_integrate_ode, harmonic_oscillator_finite_diff) {\n  sho_finite_diff_test(0);\n  sho_finite_diff_test(1.0);\n  sho_finite_diff_test(-1.0);\n\n  sho_data_finite_diff_test(0);\n  sho_data_finite_diff_test(1.0);\n  sho_data_finite_diff_test(-1.0);\n}\n\nTEST(StanAgradRevOde_integrate_ode, harmonic_oscillator_error) {\n  using stan::math::var;\n  harm_osc_ode_wrong_size_1_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n  double t0 = 0;\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x(3,1);\n  std::vector<int> x_int(2,0);\n\n  std::string error_msg\n    = \"ode_system: size of state vector y (2) and derivative vector dy_dt (3)\"\n    \" in the ODE functor do not match in size.\";\n\n  sho_error_test<double,var>(harm_osc, y0, t0, ts,\n                             theta, x, x_int, error_msg);\n  sho_error_test<var,double>(harm_osc, y0, t0, ts,\n                             theta, x, x_int, error_msg);\n  sho_error_test<var,var>(harm_osc, y0, t0, ts,\n                          theta, x, x_int, error_msg);\n}\n\n\n// TODO(carpenter): g++6 failure\nTEST(StanAgradRevOde_integrate_ode, lorenz_finite_diff) {\n  lorenz_ode_fun lorenz;\n\n  std::vector<double> y0;\n  std::vector<double> theta;\n  double t0;\n  std::vector<double> ts;\n\n  t0 = 0;\n\n  theta.push_back(10.0);\n  theta.push_back(28.0);\n  theta.push_back(8.0/3.0);\n  y0.push_back(10.0);\n  y0.push_back(1.0);\n  y0.push_back(1.0);\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n\n  for (int i = 0; i < 100; i++)\n    ts.push_back(0.1*(i+1));\n\n  test_ode_cvode(lorenz, t0, ts, y0, theta, x, x_int, 1e-8, 1e-1);\n}\n", "meta": {"hexsha": "c3a39aeae4221c79b3f304ccd9b019371114d065", "size": 5324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/mat/functor/integrate_ode_bdf_rev_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/mat/functor/integrate_ode_bdf_rev_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/mat/functor/integrate_ode_bdf_rev_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": 29.0928961749, "max_line_length": 88, "alphanum_fraction": 0.598985725, "num_tokens": 1708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5080301678324706}}
{"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 DSGD. We first creates factors and then a data matrix\n * from these factors. This process ensures that we know the best factorization of the input.\n * These matrices are distributed across a cluster. We then try to reconstruct the factors\n * using DSGD.\n *\n * Run with: mpirun --hosts localhost,localhost dsgd\n * (make sure to use a production build, otherwise it will be slow)\n */\n#include <iostream>\n\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/random/uniform_real.hpp>\n\n#include <util/evaluation.h>\n\n#include <mpi2/mpi2.h>\n#include <mf/mf.h>\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\nusing namespace std;\nusing namespace mf;\nusing namespace mpi2;\nusing namespace rg;\nusing namespace boost::numeric::ublas;\n\n// type of SGD\ntypedef UpdateTruncate<UpdateNzslL2> Update;\n//typedef UpdateTruncate<UpdateNzsl> Update;\ntypedef RegularizeNone Regularize;\n//typedef RegularizeL2 Regularize;\n//typedef RegularizeNzl2 Regularize;\ntypedef SumLoss<NzslLoss, L2Loss> Loss;\n//typedef SumLoss<NzslLoss, Nzl2Loss> Loss;\ntypedef NzslLoss TestLoss;\n\nint main(int argc, char* argv[]) {\n\t// initialize mf library and mpi2\n\tboost::mpi::communicator& world = mfInit(argc, argv);\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 = sqrt(10); // standard deviation\n\tdouble lambda = 1/sigma/sigma;\n\tmf_size_type r = 10;\n\n\t// parameters for distribution\n\tint tasksPerRank = 4;\n\tmf_size_type blocks1 = world.size() * tasksPerRank;\n\tmf_size_type blocks2 = world.size() * tasksPerRank;\n\n\t// parameters for SGD\n\tdouble eps0 = 0.01;\n\tmf_size_type epochs = 10;\n\tSgdOrder order = SGD_ORDER_WOR;\n\tStratumOrder stratumOrder = STRATUM_ORDER_RSEQ;\n\tUpdate update = Update(UpdateNzslL2(lambda), -10*sigma, 10*sigma); // truncate for numerical stability\n//\tUpdate update = Update(UpdateNzsl(), -10*sigma, 10*sigma); // truncate for numerical stability\n\tRegularize regularize;\n//\tRegularize regularize = Regularize(lambda);\n\tLoss loss((NzslLoss()), L2Loss(lambda));\n//\tLoss loss((NzslLoss()), Nzl2Loss(lambda));\n\tTestLoss testLoss;\n\tmf_size_type testNnz = nnz/100;\n\tBalanceType balanceType = BALANCE_NONE;\n\tBalanceMethod balanceMethod = BALANCE_OPTIMAL;\n\tbool mapReduce = false;\n\n\t// start mf library\n\tmfStart();\n\n\tif (world.rank() == 0)\n\t{\n#ifndef NDEBUG\n\t\tLOG4CXX_WARN(logger, \"Warning: Debug mode activated (runtimes may be slow).\");\n#endif\n\n\t\t// TODO: distribute matrix generation\n\t\t// generate original factors by sampling from a normal(0,sigma) distribution\n\t\tRandom32 random; // note: this takes a default seed (not randomized!)\n\t\tDenseMatrix wIn(size1, r);\n\t\tDenseMatrixCM hIn(r, size2);\n\t\tgenerateRandom(wIn, random, boost::normal_distribution<>(0, sigma));\n\t\tgenerateRandom(hIn, random, boost::normal_distribution<>(0, sigma));\n\n\t\t// generate a sparse matrix by selecting random entries from the generated factors\n\t\t// and add small Gaussian noise\n\t\tSparseMatrix v;\n\t\tgenerateRandom(v, nnz, wIn, hIn, random);\n\t\taddRandom(v, random, boost::normal_distribution<>(0, 0.1));\n\t\tLOG4CXX_INFO(logger, \"Data matrix: \"\n\t\t\t<< v.size1() << \" x \" << v.size2() << \", \" << v.nnz() << \" nonzeros\");\n\t\tLOG4CXX_INFO(logger, \"Loss with original factors: \" << loss((FactorizationData<>(v, wIn, hIn))));\n\n\t\t// create a test matrix (without noise)\n\t\tSparseMatrix vTest;\n\t\tgenerateRandom(vTest, testNnz, wIn, hIn, random);\n\t\tLOG4CXX_INFO(logger, \"Test matrix: \"\n\t\t\t<< v.size1() << \" x \" << v.size2() << \", \" << vTest.nnz() << \" nonzeros\");\n\n\t\t// take a small sample and remove empty rows/columns\n\t\tProjectedSparseMatrix Vsample;\n\t\tprojectRandomSubmatrix(random, v, Vsample, v.size1()/5, v.size2()/5);\n\t\tprojectFrequent(Vsample, 0);\n\t\tLOG4CXX_INFO(logger, \"Sample matrix: \"\n\t\t\t<< Vsample.data.size1() << \" x \" << Vsample.data.size2()\n\t\t\t<< \", \" << Vsample.data.nnz() << \" nonzeros\");\n\n\t\t// generate initial factors by sampling from a uniform[-0.5,0.5] distribution\n\t\tDenseMatrix w(size1, r);\n\t\tDenseMatrixCM h(r, size2);\n\t\tgenerateRandom(w, random, boost::uniform_real<>(-0.5, 0.5));\n\t\tgenerateRandom(h, random, boost::uniform_real<>(-0.5, 0.5));\n\n\t\t// distribute the input matrices and test matrix (cheaper than fetching W/H)\n\t\tDistributedSparseMatrix dv = distributeMatrix(\"V\", blocks1, blocks2, true, v);\n\t\tLOG4CXX_INFO(logger, \"Distributed data matrix: \"\n\t\t\t\t\t<< dv.blocks1() << \" x \" << dv.blocks2() << \" blocks\");\n\t\tDistributedSparseMatrix dvTest = distributeMatrix(\"VTest\", blocks1, blocks2, true, vTest);\n\t\tDistributedDenseMatrix dw = distributeMatrix(\"W\", blocks1, 1, true, w);\n\t\tDistributedDenseMatrixCM dh = distributeMatrix(\"H\", 1, blocks2, false, h);\n\t\tLOG4CXX_INFO(logger, \"Distributed factor matrices\");\n\n\t\t// initialize the DSGD\n\t\tTimer t;\n\t\tDsgdRunner dsgdRunner(random);\n\t\tDsgdJob<Update,Regularize> dsgdJob(dv, dw, dh, update, regularize, order,\n\t\t\t\tstratumOrder, mapReduce, tasksPerRank);\n\t\t//BoldDriver decay(eps0);\n\t\tDistributedDecayAuto<Update,Regularize,Loss> decay(dsgdJob, loss, Vsample, \"decay\", eps0,\n\t\t\t\tworld.size()*tasksPerRank);\n\t\tTrace trace;\n\n\t\t//std::string s1(\"Loss\"),s2(\"nzsl\"),s3(\"Regularize\"),s4(\"L2\"),s5(\"nodes\"),s6(\"threads\");\n\n\t\ttrace.addField(\"Loss\",\"nzsl\");\n\t\ttrace.addField(\"Regularize\",\"L2\");\n\n\t\ttrace.addField(\"nodes\",3);\n\t\ttrace.addField(\"threads\",4);\n\n\n\t\t// print the test loss\n\t\tDsgdFactorizationData<> testData(dvTest,dw,dh,tasksPerRank);\n\t\tLOG4CXX_INFO(logger, \"Initial test loss: \" << testLoss(testData));\n\n\t\t// run DSGD to try to reconstruct the original factors\n\t\tt.start();\n\t\tdsgdRunner.run(dsgdJob, loss, epochs, decay, trace, balanceType, balanceMethod, &testData, &testLoss);\n\t\t//dsgdRunner.run(dsgdJob, loss, epochs, decay, trace);\n\n\t\tt.stop();\n\t\tLOG4CXX_INFO(logger, \"Total time: \" << t);\n\n\t\t// print the test loss\n\t\tLOG4CXX_INFO(logger, \"Final test loss: \" << testLoss(testData));\n\n\t\t// write trace to an R file\n\t\tLOG4CXX_INFO(logger, \"Writing trace to \" << \"/tmp/dsgd-trace.R\");\n\t\ttrace.toRfile(\"/tmp/dsgd-trace.R\", \"dsgd\");\n\n//\t\tcout << squaredSums2(dsgdJob.dw, tasksPerRank) << endl;\n//\t\tcout << squaredSums1(dsgdJob.dh, tasksPerRank) << endl;\n\t}\n\n\tmfStop();\n\tmfFinalize();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "f6f82b7d1fee5f811bebe26f9f3bf05dd732212b", "size": 6898, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/mf/dsgd.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/dsgd.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/dsgd.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": 36.3052631579, "max_line_length": 104, "alphanum_fraction": 0.7131052479, "num_tokens": 1997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5080301526349379}}
{"text": "#include <Eigen/Core>\n#include <Eigen/LU>\n#include <elasty/alembic-manager.hpp>\n#include <elasty/fem.hpp>\n#include <timer.hpp>\n#include <vector>\n\nnamespace\n{\n    constexpr size_t k_num_dims = 2;\n\n    constexpr double k_youngs_modulus = 800.0;\n    constexpr double k_poisson_ratio  = 0.40;\n\n    constexpr double k_first_lame  = elasty::fem::calcFirstLame(k_youngs_modulus, k_poisson_ratio);\n    constexpr double k_second_lame = elasty::fem::calcSecondLame(k_youngs_modulus, k_poisson_ratio);\n\n    constexpr unsigned k_num_substeps = 10;\n    constexpr double   k_delta_time   = 1.0 / 60.0;\n\n    constexpr double k_damping_factor = 0.1;\n\n    enum class Model\n    {\n        CoRotational,\n        StVenantKirchhoff\n    };\n\n    constexpr Model k_model = Model::CoRotational;\n} // namespace\n\ntemplate <int N> struct Mesh\n{\n    using ElemList = Eigen::Matrix<std::int32_t, N + 1, Eigen::Dynamic>;\n\n    ElemList elems;\n\n    Eigen::VectorXd x_rest;\n    Eigen::VectorXd x;\n    Eigen::VectorXd v;\n    Eigen::VectorXd f;\n\n    double mass = 1.0;\n\n    /// \\details Should be precomputed\n    Eigen::VectorXd lumped_mass;\n\n    /// \\details Should be precomputed\n    std::vector<double> volume_array;\n\n    /// \\details Should be precomputed\n    std::vector<Eigen::Matrix<double, N, N>> rest_shape_mat_inv_array;\n\n    /// \\details Should be precomputed\n    std::vector<Eigen::Matrix<double, N * N, N*(N + 1)>> vec_PFPx_array;\n};\n\nusing TriangleMesh = Mesh<2>;\n\ntemplate <typename Derived> typename Derived::Scalar calcEnergyDensity(const Eigen::MatrixBase<Derived>& deform_grad)\n{\n    switch (k_model)\n    {\n        case Model::StVenantKirchhoff:\n            return elasty::fem::calcStVenantKirchhoffEnergyDensity(deform_grad, k_first_lame, k_second_lame);\n        case Model::CoRotational:\n            return elasty::fem::calcCoRotationalEnergyDensity(deform_grad, k_first_lame, k_second_lame);\n    }\n}\n\ntemplate <typename Derived>\nEigen::Matrix<typename Derived::Scalar, 2, 2> calcPiolaStress(const Eigen::MatrixBase<Derived>& deform_grad)\n{\n    switch (k_model)\n    {\n        case Model::StVenantKirchhoff:\n            return elasty::fem::calcStVenantKirchhoffPiolaStress(deform_grad, k_first_lame, k_second_lame);\n        case Model::CoRotational:\n            return elasty::fem::calcCoRotationalPiolaStress(deform_grad, k_first_lame, k_second_lame);\n    }\n}\n\nclass Explicit2dEngine\n{\npublic:\n    Explicit2dEngine() {}\n\n    void proceedFrame()\n    {\n        const std::size_t              num_verts         = m_mesh.x_rest.size() / k_num_dims;\n        const std::vector<std::size_t> constrained_verts = {0, 1, 2, 3, 4};\n\n        // Reset forces\n        m_mesh.f = Eigen::VectorXd::Zero(2 * num_verts);\n\n        // Calculate forces\n        for (std::size_t i = 0; i < m_mesh.elems.cols(); ++i)\n        {\n            const auto& indices = m_mesh.elems.col(i);\n\n            // Retrieve precomputed values\n            const auto& D_m_inv  = m_mesh.rest_shape_mat_inv_array[i];\n            const auto& area     = m_mesh.volume_array[i];\n            const auto& vec_PFPx = m_mesh.vec_PFPx_array[i];\n\n            // Calculate the deformation gradient $\\mathbf{F}$\n            const auto F = elasty::fem::calc2dTriangleDeformGrad(m_mesh.x.segment<2>(2 * indices[0]),\n                                                                 m_mesh.x.segment<2>(2 * indices[1]),\n                                                                 m_mesh.x.segment<2>(2 * indices[2]),\n                                                                 D_m_inv);\n\n            // Calculate $\\frac{\\partial \\Phi}{\\partial \\mathbf{x}}$ and related values\n            const auto P      = calcPiolaStress(F);\n            const auto vec_P  = Eigen::Map<const Eigen::Vector4d>(P.data(), P.size());\n            const auto PPsiPx = vec_PFPx.transpose() * vec_P;\n\n            // Calculate the internal force\n            const auto force = -area * PPsiPx;\n\n            assert(indices.size() == 3);\n            assert(F.rows() == 2 && F.cols() == 2);\n            assert(vec_PFPx.rows() == 4 && vec_PFPx.cols() == 6);\n            assert(PPsiPx.rows() == 6 && PPsiPx.cols() == 1);\n\n            // Accumulate forces\n            m_mesh.f.segment(2 * indices[0], 2) += force.segment(2 * 0, 2);\n            m_mesh.f.segment(2 * indices[1], 2) += force.segment(2 * 1, 2);\n            m_mesh.f.segment(2 * indices[2], 2) += force.segment(2 * 2, 2);\n        }\n\n        // Apply gravity force\n        for (size_t i = 0; i < num_verts; ++i)\n        {\n            m_mesh.f[i * 2 + 1] += m_mesh.lumped_mass(i * 2 + 1) * (-9.80665);\n        }\n\n        // Calculate the \"modified\" inverse lumped mass matrix\n        // Note: This \"mass modification\" is described in \"Large Steps in Cloth Simulation\" (SIGGRAPH '98)\n        Eigen::VectorXd W_diags = m_mesh.lumped_mass.cwiseInverse();\n        for (size_t i : constrained_verts)\n        {\n            W_diags.segment(i * 2, 2) = Eigen::Vector2d::Zero();\n        }\n        const auto W = W_diags.asDiagonal();\n\n        // Note: Explicit Euler integration (for velocities)\n        m_mesh.v = m_mesh.v + m_delta_physics_time * W * m_mesh.f;\n\n        // Note: Explicit Euler integration (for positions)\n        m_mesh.x = m_mesh.x + m_delta_physics_time * m_mesh.v;\n\n        // Apply naive damping\n        m_mesh.v *= std::exp(-k_damping_factor * m_delta_physics_time);\n    }\n\n    void initializeScene()\n    {\n        // A simple cantilever\n\n        constexpr std::size_t num_cols  = 20;\n        constexpr std::size_t num_rows  = 4;\n        constexpr std::size_t num_verts = (num_cols + 1) * (num_rows + 1);\n        constexpr std::size_t num_elems = (num_cols * num_rows) * 2;\n        constexpr double      size      = 1.0;\n\n        m_mesh.elems.resize(3, num_elems);\n        m_mesh.x_rest.resize(num_verts * k_num_dims);\n\n        // Generate a triangle mesh\n        for (std::size_t col = 0; col < num_cols; ++col)\n        {\n            for (std::size_t row = 0; row < num_rows; ++row)\n            {\n                const auto base = col * (num_rows + 1) + row;\n\n                m_mesh.elems.col(2 * num_rows * col + 2 * row + 0) << 0 + base, 1 + base, (num_rows + 1) + 1 + base;\n                m_mesh.elems.col(2 * num_rows * col + 2 * row + 1) << 0 + base, (num_rows + 1) + 1 + base,\n                    (num_rows + 1) + base;\n\n                m_mesh.x_rest.segment(k_num_dims * ((num_rows + 1) * col + row), k_num_dims) =\n                    Eigen::Vector2d{col * 1.0, -1.0 * row};\n            }\n            m_mesh.x_rest.segment(k_num_dims * ((num_rows + 1) * col + num_rows), k_num_dims) =\n                Eigen::Vector2d{col * 1.0, -1.0 * num_rows};\n        }\n        for (std::size_t row = 0; row < num_rows; ++row)\n        {\n            m_mesh.x_rest.segment(k_num_dims * ((num_rows + 1) * num_cols + row), k_num_dims) =\n                Eigen::Vector2d{num_cols * 1.0, -1.0 * row};\n        }\n        m_mesh.x_rest.segment(k_num_dims * ((num_rows + 1) * num_cols + num_rows), k_num_dims) =\n            Eigen::Vector2d{num_cols * 1.0, -1.0 * num_rows};\n\n        // Set transform\n        m_mesh.x_rest *= 1.0 / static_cast<double>(num_rows);\n        for (std::size_t vert = 0; vert < num_verts; ++vert)\n        {\n            m_mesh.x_rest[2 * vert + 1] += 0.5;\n        }\n        m_mesh.x_rest *= size;\n\n        // Initialize other values\n        m_mesh.x = m_mesh.x_rest;\n        m_mesh.v = Eigen::VectorXd::Zero(k_num_dims * num_verts);\n        m_mesh.f = Eigen::VectorXd::Zero(k_num_dims * num_verts);\n\n        // Perform precomputation\n        m_mesh.volume_array.resize(num_elems);\n        m_mesh.rest_shape_mat_inv_array.resize(num_elems);\n        m_mesh.vec_PFPx_array.resize(num_elems);\n        for (std::size_t elem_index = 0; elem_index < num_elems; ++elem_index)\n        {\n            const auto& indices = m_mesh.elems.col(elem_index);\n\n            m_mesh.volume_array[elem_index] = elasty::fem::calc2dTriangleArea(m_mesh.x_rest.segment<2>(2 * indices[0]),\n                                                                              m_mesh.x_rest.segment<2>(2 * indices[1]),\n                                                                              m_mesh.x_rest.segment<2>(2 * indices[2]));\n            m_mesh.rest_shape_mat_inv_array[elem_index] =\n                elasty::fem::calc2dShapeMatrix(m_mesh.x_rest.segment<2>(2 * indices[0]),\n                                               m_mesh.x_rest.segment<2>(2 * indices[1]),\n                                               m_mesh.x_rest.segment<2>(2 * indices[2]))\n                    .inverse();\n            m_mesh.vec_PFPx_array[elem_index] =\n                elasty::fem::calcVecTrianglePartDeformGradPartPos(m_mesh.rest_shape_mat_inv_array[elem_index]);\n        }\n        m_mesh.lumped_mass = elasty::fem::calcTriangleMeshLumpedMass(m_mesh.x_rest, m_mesh.elems, m_mesh.mass);\n    }\n\n    /// \\brief Getter of the delta physics time.\n    ///\n    /// \\details The value equals to the delta frame time devided by the number of substeps.\n    double getDeltaPhysicsTime() const { return m_delta_physics_time; }\n\n    void setDeltaPhysicsTime(const double delta_physics_time) { m_delta_physics_time = delta_physics_time; }\n\n    const TriangleMesh* getMesh() const { return &m_mesh; }\n\nprivate:\n    double m_delta_physics_time = 1.0 / 60.0;\n\n    TriangleMesh m_mesh;\n};\n\nint main(int argc, char** argv)\n{\n    Explicit2dEngine engine;\n\n    engine.initializeScene();\n    engine.setDeltaPhysicsTime(k_delta_time / static_cast<double>(k_num_substeps));\n\n    const auto        mesh      = engine.getMesh();\n    const std::size_t num_verts = mesh->x_rest.size() / 2;\n    const std::size_t num_elems = mesh->elems.cols();\n\n    auto alembic_manager = elasty::createTriangleMesh2dAlembicManager(\n        \"./out.abc\", k_delta_time, num_verts, num_elems, mesh->x.data(), mesh->elems.data());\n\n    for (unsigned int frame = 0; frame < 240; ++frame)\n    {\n        timer::Timer t(std::to_string(frame));\n\n        alembic_manager->submitCurrentStatus();\n\n        for (int i = 0; i < k_num_substeps; ++i)\n        {\n            engine.proceedFrame();\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "d18019b314ec0e76c5ff1a3560390c7b4c634a1f", "size": 10114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/explicit-2d/main.cpp", "max_stars_repo_name": "yuki-koyama/elasty", "max_stars_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 176.0, "max_stars_repo_stars_event_min_datetime": "2019-04-27T00:45:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:15:45.000Z", "max_issues_repo_path": "examples/explicit-2d/main.cpp", "max_issues_repo_name": "yuki-koyama/elasty", "max_issues_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2019-04-27T00:00:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T07:01:12.000Z", "max_forks_repo_path": "examples/explicit-2d/main.cpp", "max_forks_repo_name": "yuki-koyama/elasty", "max_forks_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T01:09:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:30:41.000Z", "avg_line_length": 37.1838235294, "max_line_length": 120, "alphanum_fraction": 0.5840419221, "num_tokens": 2687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.5078107778587388}}
{"text": "/*! \\file demo_2d_limits.cpp\n    \\brief Demonstration of some 2D values including NaN and + and - infinity.\n    \\details Quickbook markup to include in documentation.\n    \\author Paul A. Bristow\n*/\n\n// Copyright Paul A Bristow 2008, 2009, 2013, 2020\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// An example to demonstrate plotting 2D 'at limts' values including NaN and + and - infinity.\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[demo_2d_limits_1\n\n/*`An example to demonstrate plotting 2D 'at limits' values\nincluding NaN and + and - infinity.\n\nAs ever, we need the usual includes to use Boost.Plot.\n\n*/\n//] [demo_2d_limits_1]\n\n#include <boost/svg_plot/svg_2d_plot.hpp>\n  using namespace boost::svg;\n  using boost::svg::svg_2d_plot;\n#include <iostream>\n  using std::cout;\n  using std::endl;\n\n#include <map>\n  using std::map;\n\n#include <limits>\n  using std::numeric_limits;\n\n#include <utility>\n  using std::make_pair;\n\nint main()\n{\n//[demo_2d_limits_2\n  /*`Some fictional data is pushed into an STL container, here map:*/\n\n  map<double, double> my_data;\n  /*`\n  Inserting some fictional values also sorts the data.\n  The map index value in [ ] is the x value, so mydata[x] = y.\n\n  First some normal valued points, not 'at limits'.\n  */\n  my_data[1.1] = 3.2;\n  my_data[4.3] = 3.1;\n  my_data[0.25] = 1.4;\n/*`\n  Now some values including + and - infinity:\n*/\n  my_data[3] = numeric_limits<double>::quiet_NaN(); // marker at x = 3, y = 0\n  my_data[0.] = numeric_limits<double>::quiet_NaN(); // Marker at 0,0\n  my_data[1.] = numeric_limits<double>::infinity(); // Marker at 1, top\n  my_data[-1] = -numeric_limits<double>::infinity(); // Marker at -1, bottom\n  my_data[+numeric_limits<double>::infinity()] = +1.; // Marker at right, 1\n  my_data[-numeric_limits<double>::infinity()] = -1.; // Marker at left, -1\n  my_data[+(numeric_limits<double>::max)()] = +2.;  // Marker at right, 2\n  my_data[-(numeric_limits<double>::max)()] = +2.; // Marker at left, 2\n  my_data[-(numeric_limits<double>::max)() /2] = +3.; // Value near to max, marker left, 3\n  my_data[numeric_limits<double>::infinity()] = numeric_limits<double>::infinity(); // Top right.\n  my_data[-numeric_limits<double>::infinity()] = -numeric_limits<double>::infinity(); // Bottom left.\n\n/*`\n  [caution Using map (rather than multimap that allows duplicates) some assignments values overwrite,\n  and so not all display as they do individually.\n  In particular, an X value of quiet_NaN() causes a overwrite of the lowerest value (because NaNs never compare equal).\n  So avoid NaN as an X value.]\n*/\n\n  try\n  { // try'n'catch blocks are needed to ensure error messages from any exceptions are shown.\n    svg_2d_plot my_2d_plot; // Construct a plot with all the default constructor values.\n\n    my_2d_plot.title(\"Default 2D 'at limits' NaN and infinities Demo\") // Add a string title of the plot.\n      .x_range(-5, 5) // Add a range for the X-axis.\n      .y_range(-5, 5) // Add a range for the Y-axis\n      .x_label(\"time (s)\"); // Add a label for the X-axis.\n\n/*`\nAdd the one data series, `my_data` and a description, and how the data points are to be marked,\nhere a circle with a diameter of 5 pixels.\n*/\n    svg_2d_plot_series& my_series = my_2d_plot.plot(my_data, \"2D limits\").shape(circlet).size(5);\n\n/*`\nWe can also keep note of the plot series and use this to interrogate how many normal and how many 'at limit' values.\n*/\n    cout << my_series.values_count() << \" normal data values in series.\" << endl;\n    cout << my_series.limits_count() << \" 'at limits' data values in series.\"<< endl;\n\n/*`To put a value label against each data point, switch on the option:\n*/\n    //  my_2d_plot.x_values_on(true).y_values_on(true).x_values_font_size(12).y_values_font_size(12); // Add the X-axis and Y-axis values.\n    // This displays x horizontally and Y downward.\n    my_2d_plot.xy_values_on(true).x_values_font_size(12).y_values_font_size(12); // Add the X-axis and Y-axis values.\n    // This displays X above and Y below.\n\n/*`To change the default colors (lightgray and whitesmoke) for the 'at limit' point marker\nto something more conspicuous for this demonstration:\n*/\n    my_2d_plot.plus_inf_limit_color(blue);\n    my_2d_plot.plus_inf_limit_color(pink);\n\n/*`To use all these settings, finally write the plot to file.\n*/\n    my_2d_plot.write(\"demo_2d_limits.svg\");\n\n/*` Note the +infinity point is marked on the far right of the plot, the -infinity on the far left, but the NaN (Not A Number is at zero).\n\nTo echo the new marker colors chosen:\n*/\n    cout << \"limit points stroke color \" << my_2d_plot.plus_inf_limit_color() << endl;\n    cout << \"limit points fill color \" << my_2d_plot.plus_inf_limit_color() << endl;\n\n//] [/demo_2d_limits_2]\n  }\n  catch(const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n/*\n\n//[demo_2d_limits_output\n\nOutput:\n\nAutorun \"j:\\Cpp\\SVG\\Debug\\demo_2d_limits.exe\"\n3 normal data values in series.\n9 'at limits' data values in series.\nlimit points stroke color RGB(0,0,255)\nlimit points fill color RGB(255,192,203)\n\n*/\n//] //[/demo_2d_limits_output]\n\n", "meta": {"hexsha": "1f056715784cae5adc87f54bf4acdc97143e7aaa", "size": 5590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_2d_limits.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_2d_limits.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_2d_limits.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 35.8333333333, "max_line_length": 138, "alphanum_fraction": 0.6998211091, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.5077248179072817}}
{"text": "#include <iostream>\n#include <boost/random.hpp>\n\nusing namespace std;\n\nint main()\n{\n    boost::random::mt19937 rng;     // produces randomness out of thin air\n                                    // see pseudo-random number generators\n    boost::random::uniform_int_distribution<> six(1,6);\n                                    // distribution that maps to 1..6\n                                    // see random number distributions\n    cout <<six(rng) << endl;;       // simulate rolling a die\n\n    double probabilities[] = {\n    0.5, 0.1, 0.1, 0.1, 0.1, 0.1\n    };\n    boost::random::discrete_distribution<> dist(probabilities);\n    for (int i = 0; i < 10; i++) cout << dist(rng) << endl;\n\n    boost::random::uniform_smallint<>si(1, 100);\n    for (int i = 0; i < 10; i++) cout << si(rng) << endl;\n   \n    boost::random::uniform_01<>uniform;\n    for (int i = 0; i < 10; i++) cout << uniform(rng) << endl;\n\n    boost::random::uniform_real_distribution<>rd(0.1, 0.6);\n    for (int i = 0; i < 10; i++) cout << rd(rng) << endl;\n    return 0;\n}\n", "meta": {"hexsha": "2c46bfc19fcdeea407e713322e61e548eb9f14c9", "size": 1039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "random.cpp", "max_stars_repo_name": "kaitian521/boost_learn", "max_stars_repo_head_hexsha": "a22455c935812849327280116bcde6f48b5c5fa1", "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": "random.cpp", "max_issues_repo_name": "kaitian521/boost_learn", "max_issues_repo_head_hexsha": "a22455c935812849327280116bcde6f48b5c5fa1", "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": "random.cpp", "max_forks_repo_name": "kaitian521/boost_learn", "max_forks_repo_head_hexsha": "a22455c935812849327280116bcde6f48b5c5fa1", "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.5161290323, "max_line_length": 74, "alphanum_fraction": 0.5428296439, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5077248128011889}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed 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#include <boost/hana/comparable/equal_mcd.hpp>\n#include <boost/hana/core/datatype.hpp>\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/functor/fmap_mcd.hpp>\n#include <boost/hana/integral.hpp>\n#include <boost/hana/list/instance.hpp>\n#include <boost/hana/range.hpp>\n#include <boost/hana/type.hpp>\nusing namespace boost::hana;\n\n\nstruct Matrix;\n\ntemplate <typename Storage, typename = operators<Comparable>>\nstruct matrix_type {\n    using hana_datatype = Matrix;\n\n    Storage rows_;\n    constexpr auto ncolumns() const\n    { return length(head(rows_)); }\n\n    constexpr auto nrows() const\n    { return length(rows_); }\n\n    constexpr auto size() const\n    { return nrows() * ncolumns(); }\n\n    template <typename I, typename J>\n    constexpr auto at(I i, J j) const\n    { return boost::hana::at(j, boost::hana::at(i, rows_)); }\n};\n\nauto transpose = [](auto m) {\n    auto new_storage = unpack(m.rows_, zip);\n    return matrix_type<decltype(new_storage)>{new_storage};\n};\n\nauto rows = [](auto m) {\n    return m.rows_;\n};\n\nauto columns = [](auto m) {\n    return rows(transpose(m));\n};\n\nauto elementwise = [](auto f) {\n    return [=](auto ...matrices) {\n        auto new_storage = zip_with(partial(zip_with, f), matrices.rows_...);\n        return matrix_type<decltype(new_storage)>{new_storage};\n    };\n};\n\ntemplate <typename S1, typename S2>\nconstexpr auto operator+(matrix_type<S1> m1, matrix_type<S2> m2)\n{ return elementwise(_+_)(m1, m2); }\n\ntemplate <typename S1, typename S2>\nconstexpr auto operator-(matrix_type<S1> m1, matrix_type<S2> m2)\n{ return elementwise(_-_)(m1, m2); }\n\n\nauto scalar_prod = [](auto v1, auto v2) {\n    return sum(zip_with(_*_, v1, v2));\n};\nauto repeat_n = [](auto n, auto x) {\n    return unpack(range(int_<0>, n), on(list, always(x)));\n};\n\ntemplate <typename S1, typename S2>\nconstexpr auto operator*(matrix_type<S1> m1, matrix_type<S2> m2) {\n    auto storage = fmap(\n        [=](auto row) {\n            return zip_with(\n                    scalar_prod,\n                    repeat_n(m2.ncolumns(), row),\n                    columns(m2));\n        }\n    , rows(m1));\n    return matrix_type<decltype(storage)>{storage};\n}\n\nauto row = [](auto ...entries) {\n    return list(entries...);\n};\n\nauto matrix = [](auto ...rows) {\n    auto storage = list(rows...);\n    auto all_same_length = all(tail(storage), [=](auto row) {\n        return length(row) == length(head(storage));\n    });\n    static_assert(all_same_length, \"\");\n\n    return matrix_type<decltype(storage)>{storage};\n};\n\nauto vector = on(matrix, row);\n\n\nconstexpr int exponent(int x, unsigned int n) {\n    if (n == 0) return 1;\n    else        return x * exponent(x, n - 1);\n}\n\nauto remove_at = [](auto n, auto xs) {\n    auto with_indices = zip(xs, range(int_<0>, length(xs)));\n    auto removed = filter(with_indices, compose(n != _, last));\n    return fmap(head, removed);\n};\n\ntemplate <typename Matrix>\nstruct _det; // remove circular dependency between matrix_minor and det\n\nauto matrix_minor = [](auto m, auto i, auto j) {\n    auto submatrix_storage = fmap(partial(remove_at, j), remove_at(i, rows(m)));\n    matrix_type<decltype(submatrix_storage)> submatrix{submatrix_storage};\n    return _det<decltype(submatrix)>{}(submatrix);\n};\n\nauto cofactor = [](auto m, auto i, auto j) {\n    auto i_plus_j = i + j;\n    return int_<exponent(-1, i_plus_j())> * matrix_minor(m, i, j);\n};\n\ntemplate <typename Matrix>\nstruct _det {\n    constexpr auto operator()(Matrix m) const {\n        return eval_if(m.size() == int_<1>,\n            always(m.at(int_<0>, int_<0>)),\n            [=](auto _) {\n                auto cofactors_1st_row = unpack(_(range)(int_<0>, m.ncolumns()),\n                    on(list, partial(cofactor, m, int_<0>))\n                );\n                return scalar_prod(head(rows(m)), cofactors_1st_row);\n            }\n        );\n    }\n};\n\nauto det = [](auto m) {\n    return _det<decltype(m)>{}(m);\n};\n\nnamespace boost { namespace hana {\n    template <>\n    struct Functor::instance<Matrix> : Functor::fmap_mcd {\n        template <typename F, typename M>\n        static constexpr auto fmap_impl(F f, M mat) {\n            auto new_storage = fmap(partial(fmap, f), mat.rows_);\n            return matrix_type<decltype(new_storage)>{new_storage};\n        }\n    };\n\n    template <>\n    struct Comparable::instance<Matrix, Matrix> : Comparable::equal_mcd {\n        template <typename M1, typename M2>\n        static constexpr auto equal_impl(M1 m1, M2 m2) {\n            return m1.nrows() == m2.nrows() &&\n                   m1.ncolumns() == m2.ncolumns() &&\n                   all_of(zip_with(_==_, m1.rows_, m2.rows_));\n        }\n    };\n}}\n\n\nvoid test_sizes() {\n    auto m = matrix(\n        row(1, '2', 3),\n        row('4', char_<'5'>, 6)\n    );\n    BOOST_HANA_CONSTEXPR_ASSERT(m.size() == 6);\n    BOOST_HANA_CONSTEXPR_ASSERT(m.ncolumns() == 3);\n    BOOST_HANA_CONSTEXPR_ASSERT(m.nrows() == 2);\n}\n\nvoid test_at() {\n    auto m = matrix(\n        row(1, '2', 3),\n        row('4', char_<'5'>, 6),\n        row(int_<7>, '8', 9.3)\n    );\n    BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<0>, int_<0>) == 1);\n    BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<0>, int_<1>) == '2');\n    BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<0>, int_<2>) == 3);\n\n    BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<1>, int_<0>) == '4');\n    BOOST_HANA_CONSTANT_ASSERT(m.at(int_<1>, int_<1>) == char_<'5'>);\n    BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<1>, int_<2>) == 6);\n\n    BOOST_HANA_CONSTANT_ASSERT(m.at(int_<2>, int_<0>) == int_<7>);\n    BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<2>, int_<1>) == '8');\n    BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<2>, int_<2>) == 9.3);\n}\n\nvoid test_comparable() {\n    BOOST_HANA_CONSTEXPR_ASSERT(matrix(row(1, 2)) == matrix(row(1, 2)));\n    BOOST_HANA_CONSTEXPR_ASSERT(matrix(row(1, 2)) != matrix(row(1, 5)));\n\n    BOOST_HANA_CONSTEXPR_ASSERT(matrix(row(1, 2), row(3, 4)) == matrix(row(1, 2), row(3, 4)));\n    BOOST_HANA_CONSTEXPR_ASSERT(matrix(row(1, 2), row(3, 4)) != matrix(row(1, 2), row(0, 4)));\n    BOOST_HANA_CONSTEXPR_ASSERT(matrix(row(1, 2), row(3, 4)) != matrix(row(0, 2), row(3, 4)));\n\n    BOOST_HANA_CONSTANT_ASSERT(matrix(row(1), row(2)) != matrix(row(3, 4), row(5, 6)));\n    BOOST_HANA_CONSTANT_ASSERT(matrix(row(1), row(2)) != matrix(row(3, 4)));\n}\n\nvoid test_functor() {\n    auto m = matrix(\n        row(1, int_<2>, 3),\n        row(int_<4>, 5, 6),\n        row(7, 8, int_<9>)\n    );\n    BOOST_HANA_CONSTEXPR_ASSERT(fmap(_ + int_<1>, m) ==\n        matrix(\n            row(2, int_<3>, 4),\n            row(int_<5>, 6, 7),\n            row(8, 9, int_<10>)\n        )\n    );\n}\n\nvoid test_operators() {\n    auto m = matrix(row(1, 2), row(3, 4));\n    BOOST_HANA_CONSTEXPR_ASSERT(m + m == matrix(row(2, 4), row(6, 8)));\n    BOOST_HANA_CONSTEXPR_ASSERT(m - m == matrix(row(0, 0), row(0, 0)));\n}\n\nvoid test_matrix_multiplication() {\n    auto A = matrix(\n        row(1, 2, 3),\n        row(4, 5, 6)\n    );\n\n    auto B = matrix(\n        row(1, 2),\n        row(3, 4),\n        row(5, 6)\n    );\n\n    BOOST_HANA_CONSTEXPR_ASSERT(A * B == matrix(\n        row(1*1 + 2*3 + 5*3, 1*2 + 2*4 + 3*6),\n        row(4*1 + 3*5 + 5*6, 4*2 + 5*4 + 6*6)\n    ));\n}\n\nvoid test_vector() {\n    auto v = vector(1, '2', int_<3>, 4.2f);\n    BOOST_HANA_CONSTEXPR_ASSERT(v.size() == 4);\n    BOOST_HANA_CONSTEXPR_ASSERT(v.nrows() == 4);\n    BOOST_HANA_CONSTEXPR_ASSERT(v.ncolumns() == 1);\n}\n\nvoid test_transpose() {\n    auto m = matrix(\n        row(1, 2.2, '3'),\n        row(4, '5', 6)\n    );\n    BOOST_HANA_CONSTEXPR_ASSERT(transpose(m) ==\n        matrix(\n            row(1, 4),\n            row(2.2, '5'),\n            row('3', 6)\n        )\n    );\n}\n\nvoid test_repeat_n() {\n    struct T;\n    BOOST_HANA_CONSTANT_ASSERT(repeat_n(int_<0>, type<T>) == list());\n    BOOST_HANA_CONSTANT_ASSERT(repeat_n(int_<1>, type<T>) == list(type<T>));\n    BOOST_HANA_CONSTANT_ASSERT(repeat_n(int_<2>, type<T>) == list(type<T>, type<T>));\n    BOOST_HANA_CONSTANT_ASSERT(repeat_n(int_<3>, type<T>) == list(type<T>, type<T>, type<T>));\n    BOOST_HANA_CONSTANT_ASSERT(repeat_n(int_<4>, type<T>) == list(type<T>, type<T>, type<T>, type<T>));\n}\n\nvoid test_determinant() {\n    BOOST_HANA_CONSTEXPR_ASSERT(det(matrix(row(1))) == 1);\n    BOOST_HANA_CONSTEXPR_ASSERT(det(matrix(row(2))) == 2);\n\n    BOOST_HANA_CONSTEXPR_ASSERT(det(matrix(row(1, 2), row(3, 4))) == -2);\n\n    BOOST_HANA_CONSTEXPR_ASSERT(\n        det(matrix(\n            row(1, 5, 6),\n            row(3, 2, 4),\n            row(7, 8, 9)\n        ))\n        == 51\n    );\n\n    BOOST_HANA_CONSTEXPR_ASSERT(\n        det(matrix(\n            row(1, 5, 6, -3),\n            row(3, 2, 4, -5),\n            row(7, 8, 9, -1),\n            row(8, 2, 1, 10)\n        )) == 214\n    );\n\n    BOOST_HANA_CONSTEXPR_ASSERT(\n        det(matrix(\n            row(1,  5,  6, -3, 92),\n            row(3,  2,  4, -5, 13),\n            row(7,  8,  9, -1, 0),\n            row(8,  2,  1, 10, 41),\n            row(3, 12, 92, -7, -4)\n        )) == -3115014\n    );\n}\n\nvoid test_remove_at() {\n    BOOST_HANA_CONSTANT_ASSERT(remove_at(int_<0>, list(1)) == list());\n    BOOST_HANA_CONSTEXPR_ASSERT(remove_at(int_<0>, list(1, '2')) == list('2'));\n    BOOST_HANA_CONSTEXPR_ASSERT(remove_at(int_<0>, list(1, '2', 3.3)) == list('2', 3.3));\n\n    BOOST_HANA_CONSTEXPR_ASSERT(remove_at(int_<1>, list(1, '2')) == list(1));\n    BOOST_HANA_CONSTEXPR_ASSERT(remove_at(int_<1>, list(1, '2', 3.3)) == list(1, 3.3));\n\n    BOOST_HANA_CONSTEXPR_ASSERT(remove_at(int_<2>, list(1, '2', 3.3)) == list(1, '2'));\n}\n\nvoid test_exponent() {\n    BOOST_HANA_CONSTEXPR_ASSERT(exponent(3, 0) == 1);\n    BOOST_HANA_CONSTEXPR_ASSERT(exponent(3, 1) == 3);\n    BOOST_HANA_CONSTEXPR_ASSERT(exponent(3, 2) == 3 * 3);\n    BOOST_HANA_CONSTEXPR_ASSERT(exponent(3, 3) == 3 * 3 * 3);\n    BOOST_HANA_CONSTEXPR_ASSERT(exponent(3, 4) == 3 * 3 * 3 * 3);\n}\n\nint main() {\n    test_repeat_n();\n    test_remove_at();\n    test_exponent();\n\n    test_sizes();\n    test_at();\n    test_comparable();\n    test_functor();\n    test_operators();\n    test_vector();\n    test_transpose();\n    test_matrix_multiplication();\n    test_determinant();\n}\n", "meta": {"hexsha": "ed3fd8e288faa41e70d41b2b09dffc3ba413666f", "size": 10239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/sandbox/matrix.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/sandbox/matrix.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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/sandbox/matrix.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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.1709401709, "max_line_length": 103, "alphanum_fraction": 0.5896083602, "num_tokens": 3097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5077247988145696}}
{"text": "//\n// Created by wei on 1/14/19.\n//\n\n#include <Eigen/Eigen>\n#include <gtest/gtest.h>\n#include <iostream>\n#include <random>\n#include <Cuda/Container/Array2DCuda.h>\n\nTEST(Eigen, RawData) {\n    Eigen::Matrix<float, 3, 5, Eigen::RowMajor> matrix;\n    matrix << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14;\n\n    std::cout << matrix << std::endl;\n    for (int i = 0; i < 15; ++i) {\n        std::cout << *(matrix.data() + i) << \" \";\n    }\n}\n\nTEST(Eigen, UploadAndDownload) {\n    std::random_device rd;\n    std::default_random_engine engine(rd());\n    std::uniform_int_distribution<int> uniform(100, 10000);\n    int rows = uniform(engine);\n    int cols = 30;\n\n    std::cout << \"rows: \" << rows << std::endl;\n    Eigen::Matrix<float, -1, -1, Eigen::RowMajor> matrix(rows, cols);\n    for (int i = 0; i < rows; ++i) {\n        for (int j = 0; j < cols; ++j) {\n            matrix(i, j) = i + j;\n            EXPECT_EQ(*(matrix.data() + i * cols + j), i + j);\n        }\n    }\n\n    open3d::cuda::Array2DCuda<float> matrix_cuda;\n    matrix_cuda.Create(rows, cols);\n    matrix_cuda.Upload(matrix);\n\n    EXPECT_EQ(matrix_cuda.Download(), matrix);\n}\n\nint main(int argc, char **argv) {\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}", "meta": {"hexsha": "aa2430db9aa28c2e35e87b5c90612a2255e28b8d", "size": 1243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/UnitTest/Cuda/Container/TestMatrixCuda.cpp", "max_stars_repo_name": "devshank3/Open3D", "max_stars_repo_head_hexsha": "91611eb562680a41be8a52497bb45d278f2c9377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 113.0, "max_stars_repo_stars_event_min_datetime": "2018-11-12T03:32:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:58:54.000Z", "max_issues_repo_path": "src/UnitTest/Cuda/Container/TestMatrixCuda.cpp", "max_issues_repo_name": "llp45135/Open3D", "max_issues_repo_head_hexsha": "ff7003d542c4fcf88a2d9e7fe08508b3e52dc702", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-19T12:09:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T11:55:54.000Z", "max_forks_repo_path": "src/UnitTest/Cuda/Container/TestMatrixCuda.cpp", "max_forks_repo_name": "llp45135/Open3D", "max_forks_repo_head_hexsha": "ff7003d542c4fcf88a2d9e7fe08508b3e52dc702", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2018-10-16T20:01:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T08:02:20.000Z", "avg_line_length": 26.4468085106, "max_line_length": 69, "alphanum_fraction": 0.5744167337, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.507722205003693}}
{"text": "#ifndef MONTECARLO_HPP_\n#define MONTECARLO_HPP_\n\n#include <mpi.h>\n#include <boost/random.hpp>\n#include <iostream>\n#include <numeric>\n#include <cmath>\n#include <cstring>\n#include <fstream>\n\n#include \"helper.hpp\"\n\n/* Monte Carlo method for UQ */\n class MonteCarlo\n {\n private:\n\t/* the Raynolds number will be of the form mean + stddev*sigma, where\n\tsigma is ~N(0,1) or ~U(0,1) */\n\tdouble par1, par2; \n\n\t/* mersenne twister random number generator */\n\tboost::mt19937 rng;\n\t/* normal(Gaussian) distribution */\n\tboost::normal_distribution<> normal_distr;\n\t/* uniform distribution */\n\tboost::uniform_real<> uniform_distr;\n\n\tboost::variate_generator<boost::mt19937&,\n\tboost::normal_distribution<> >* var_normal;\n\n\tboost::variate_generator<boost::mt19937&,\n\tboost::uniform_real<> >* var_uniform;\n\npublic:\n\n\t/* constructor */\n\tMonteCarlo(double par1, double par2, int distr_flag);\n\n\t/** Uncertainty (i.e. Random variables) related methods **/\n\n\t/* generate nsamples samples of normal distributed random variables */\n\tstd::vector<double> generate_nd_samples(double mean_nd, double sttdev_nd, int* nsamples);\n\t/* generate nsamples samples of uniformly distributed random variables */\n\tstd::vector<double> generate_ud_samples(double mean_ud, double sttdev_ud, int* nsamples);\n\n\t/* get a normal and uniform distributed RV */\n\tdouble get_normal() const;\n\tdouble get_uniform() const;\n\n\t/***********************************************************/\n\n\t/** Parallelization related methods **/\n\n\t/* data decomposition among processes*/\n\tvoid data_decomposition(int samples_per_proc, int* nsampels, int* nprocs, int *myrank, int *il, int *ir);\n\n\t/* call the NS solver for each generated sample */\n\tvoid monte_carlo_simulation(int *myrank, int* nsamples, int* samples_per_proc, int *il, int *ir\n\t\t, std::vector<double> &rv, int rv_flag, int imax, int jmax, double *mean, double* variance, int* flag_prog);\n\n\n\t/***********************************************************/\n\n\t/* destructor */\n\t~MonteCarlo();\n};\n\n#endif /* MONTECARLO_HPP_ */\n", "meta": {"hexsha": "a7268c0d294d89a411977dec3882a027cfafcd7d", "size": 2018, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "project/monte_carlo/Monte_Carlo.hpp", "max_stars_repo_name": "grantathon/computational_fluid_dynamics", "max_stars_repo_head_hexsha": "ecb9c180952d4791e4368087f4b26d29e7daefe9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-14T11:02:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-22T21:18:37.000Z", "max_issues_repo_path": "project/monte_carlo/Monte_Carlo.hpp", "max_issues_repo_name": "grantathon/computational_fluid_dynamics", "max_issues_repo_head_hexsha": "ecb9c180952d4791e4368087f4b26d29e7daefe9", "max_issues_repo_licenses": ["MIT"], "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/monte_carlo/Monte_Carlo.hpp", "max_forks_repo_name": "grantathon/computational_fluid_dynamics", "max_forks_repo_head_hexsha": "ecb9c180952d4791e4368087f4b26d29e7daefe9", "max_forks_repo_licenses": ["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.8285714286, "max_line_length": 110, "alphanum_fraction": 0.6863230922, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5077221971406931}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and\n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2003-2008 Matthias Christian Schabel\n// Copyright (C) 2008 Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// $Id: lambda.cpp 27 2008-06-16 14:50:58Z maehne $\n\n////////////////////////////////////////////////////////////////////////\n///\n/// \\file lambda.cpp\n///\n/// \\brief Example demonstrating the usage of Boost.Units' quantity,\n///        unit, and absolute types in functors created with the\n///        Boost.Lambda library and stored in Boost.Function objects.\n///\n/// \\author Torsten Maehne\n/// \\date   2008-06-04\n///\n/// A mechanical, electrical, geometrical, and thermal example\n/// demonstrate how to use Boost.Units' quantity, unit, and absolute\n/// types in lambda expressions. The resulting functors can be stored\n/// in boost::function objects. It is also shown how to work around a\n/// limitation of Boost.Lambda's bind() to help it to find the correct\n/// overloaded function by specifying its signature with a\n/// static_cast.\n///\n////////////////////////////////////////////////////////////////////////\n\n#include <iostream>\n#include <boost/function.hpp>\n#include <boost/units/io.hpp>\n#include <boost/units/cmath.hpp>\n#include <boost/units/pow.hpp>\n#include <boost/units/systems/si.hpp>\n#include <boost/units/absolute.hpp>\n\n// Include boost/units/lambda.hpp instead of boost/lambda/lambda.hpp\n// for a convenient usage of Boost.Units' quantity, unit, and absolute\n// types in lambda expressions. The header augments Boost.Lambda's\n// return type detuction system to recognize the new types so that not\n// for each arithmetic operation the return type needs to be\n// explicitely specified.\n#include <boost/units/lambda.hpp>\n\n#include <boost/lambda/bind.hpp>\n\nstatic const double pi = 3.14159265358979323846;\n\n//[lambda_snippet_1\n\nint main(int argc, char **argv) {\n\n   using namespace std;\n   namespace bl = boost::lambda;\n   namespace bu = boost::units;\n   namespace si = boost::units::si;\n\n\n   ////////////////////////////////////////////////////////////////////////\n   // Mechanical example: linear accelerated movement\n   ////////////////////////////////////////////////////////////////////////\n\n   // Initial condition variables for acceleration, speed, and displacement\n   bu::quantity<si::acceleration> a = 2.0 * si::meters_per_second_squared;\n   bu::quantity<si::velocity> v = 1.0 * si::meters_per_second;\n   bu::quantity<si::length> s0 = 0.5 * si::meter;\n\n   // Displacement over time\n   boost::function<bu::quantity<si::length> (bu::quantity<si::time>) >\n       s = 0.5 * bl::var(a) * bl::_1 * bl::_1\n           + bl::var(v) * bl::_1\n           + bl::var(s0);\n\n   cout << \"Linear accelerated movement:\" << endl\n        << \"a = \" << a << \", v = \" << v << \", s0 = \" << s0 << endl\n        << \"s(1.0 * si::second) = \" << s(1.0 * si::second) << endl\n        << endl;\n\n   // Change initial conditions\n   a = 1.0 * si::meters_per_second_squared;\n   v = 2.0 * si::meters_per_second;\n   s0 = -1.5 * si::meter;\n\n   cout << \"a = \" << a << \", v = \" << v << \", s0 = \" << s0 << endl\n        << \"s(1.0 * si::second) = \" << s(1.0 * si::second) << endl\n        << endl;\n\n\n   ////////////////////////////////////////////////////////////////////////\n   // Electrical example: oscillating current\n   ////////////////////////////////////////////////////////////////////////\n\n   // Constants for the current amplitude, frequency, and offset current\n   const bu::quantity<si::current> iamp = 1.5 * si::ampere;\n   const bu::quantity<si::frequency> f = 1.0e3 * si::hertz;\n   const bu::quantity<si::current> i0 = 0.5 * si::ampere;\n\n   // The invocation of the sin function needs to be postponed using\n   // bind to specify the oscillation function. A lengthy static_cast\n   // to the function pointer referencing boost::units::sin() is needed\n   // to avoid an \"unresolved overloaded function type\" error.\n   boost::function<bu::quantity<si::current> (bu::quantity<si::time>) >\n       i = iamp\n           * bl::bind(static_cast<bu::dimensionless_quantity<si::system, double>::type (*)(const bu::quantity<si::plane_angle>&)>(bu::sin),\n                      2.0 * pi * si::radian * f * bl::_1)\n           + i0;\n\n   cout << \"Oscillating current:\" << endl\n        << \"iamp = \" << iamp << \", f = \" << f << \", i0 = \" << i0 << endl\n        << \"i(1.25e-3 * si::second) = \" << i(1.25e-3 * si::second) << endl\n        << endl;\n\n\n   ////////////////////////////////////////////////////////////////////////\n   // Geometric example: area calculation for a square\n   ////////////////////////////////////////////////////////////////////////\n\n   // Length constant\n   const bu::quantity<si::length> l = 1.5 * si::meter;\n\n   // Again an ugly static_cast is needed to bind pow<2> to the first\n   // function argument.\n   boost::function<bu::quantity<si::area> (bu::quantity<si::length>) >\n       A = bl::bind(static_cast<bu::quantity<si::area> (*)(const bu::quantity<si::length>&)>(bu::pow<2>),\n                    bl::_1);\n\n   cout << \"Area of a square:\" << endl\n        << \"A(\" << l <<\") = \" << A(l) << endl << endl;\n\n\n   ////////////////////////////////////////////////////////////////////////\n   // Thermal example: temperature difference of two absolute temperatures\n   ////////////////////////////////////////////////////////////////////////\n\n   // Absolute temperature constants\n   const bu::quantity<bu::absolute<si::temperature> >\n       Tref = 273.15 * bu::absolute<si::temperature>();\n   const bu::quantity<bu::absolute<si::temperature> >\n       Tamb = 300.00 * bu::absolute<si::temperature>();\n\n   boost::function<bu::quantity<si::temperature> (bu::quantity<bu::absolute<si::temperature> >,\n                                                  bu::quantity<bu::absolute<si::temperature> >)>\n       dT = bl::_2 - bl::_1;\n\n   cout << \"Temperature difference of two absolute temperatures:\" << endl\n        << \"dT(\" << Tref << \", \" << Tamb << \") = \" << dT(Tref, Tamb) << endl\n        << endl;\n\n\n   return 0;\n}\n//]\n", "meta": {"hexsha": "0fbac916098f1739aa55f1edf58adc3d451908bb", "size": 6166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/units/example/lambda.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/units/example/lambda.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/units/example/lambda.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": 39.0253164557, "max_line_length": 139, "alphanum_fraction": 0.551573143, "num_tokens": 1552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5077221954997067}}
{"text": "\n#include <NTL/mat_RR.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\n  \nvoid add(mat_RR& X, const mat_RR& A, const mat_RR& B)  \n{  \n   long n = A.NumRows();  \n   long m = A.NumCols();  \n  \n   if (B.NumRows() != n || B.NumCols() != m)   \n      Error(\"matrix add: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n  \n   long i, j;  \n   for (i = 1; i <= n; i++)   \n      for (j = 1; j <= m; j++)  \n         add(X(i,j), A(i,j), B(i,j));  \n}  \n  \nvoid sub(mat_RR& X, const mat_RR& A, const mat_RR& B)  \n{  \n   long n = A.NumRows();  \n   long m = A.NumCols();  \n  \n   if (B.NumRows() != n || B.NumCols() != m)  \n      Error(\"matrix sub: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n  \n   long i, j;  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= m; j++)  \n         sub(X(i,j), A(i,j), B(i,j));  \n}  \n  \nvoid mul_aux(mat_RR& X, const mat_RR& A, const mat_RR& B)  \n{  \n   long n = A.NumRows();  \n   long l = A.NumCols();  \n   long m = B.NumCols();  \n  \n   if (l != B.NumRows())  \n      Error(\"matrix mul: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n  \n   long i, j, k;  \n   RR acc, tmp;  \n  \n   for (i = 1; i <= n; i++) {  \n      for (j = 1; j <= m; j++) {  \n         clear(acc);  \n         for(k = 1; k <= l; k++) {  \n            mul(tmp, A(i,k), B(k,j));  \n            add(acc, acc, tmp);  \n         }  \n         X(i,j) = acc;  \n      }  \n   }  \n}  \n  \n  \nvoid mul(mat_RR& X, const mat_RR& A, const mat_RR& B)  \n{  \n   if (&X == &A || &X == &B) {  \n      mat_RR tmp;  \n      mul_aux(tmp, A, B);  \n      X = tmp;  \n   }  \n   else  \n      mul_aux(X, A, B);  \n}  \n  \n  \nstatic\nvoid mul_aux(vec_RR& x, const mat_RR& A, const vec_RR& b)  \n{  \n   long n = A.NumRows();  \n   long l = A.NumCols();  \n  \n   if (l != b.length())  \n      Error(\"matrix mul: dimension mismatch\");  \n  \n   x.SetLength(n);  \n  \n   long i, k;  \n   RR acc, tmp;  \n  \n   for (i = 1; i <= n; i++) {  \n      clear(acc);  \n      for (k = 1; k <= l; k++) {  \n         mul(tmp, A(i,k), b(k));  \n         add(acc, acc, tmp);  \n      }  \n      x(i) = acc;  \n   }  \n}  \n  \n  \nvoid mul(vec_RR& x, const mat_RR& A, const vec_RR& b)  \n{  \n   if (&b == &x || A.position1(x) != -1) {\n      vec_RR tmp;\n      mul_aux(tmp, A, b);\n      x = tmp;\n   }\n   else\n      mul_aux(x, A, b);\n}  \n\nstatic\nvoid mul_aux(vec_RR& x, const vec_RR& a, const mat_RR& B)  \n{  \n   long n = B.NumRows();  \n   long l = B.NumCols();  \n  \n   if (n != a.length())  \n      Error(\"matrix mul: dimension mismatch\");  \n  \n   x.SetLength(l);  \n  \n   long i, k;  \n   RR acc, tmp;  \n  \n   for (i = 1; i <= l; i++) {  \n      clear(acc);  \n      for (k = 1; k <= n; k++) {  \n         mul(tmp, a(k), B(k,i));\n         add(acc, acc, tmp);  \n      }  \n      x(i) = acc;  \n   }  \n}  \n\nvoid mul(vec_RR& x, const vec_RR& a, const mat_RR& B)\n{\n   if (&a == &x) {\n      vec_RR tmp;\n      mul_aux(tmp, a, B);\n      x = tmp;\n   }\n   else\n      mul_aux(x, a, B);\n}\n\n     \n  \nvoid ident(mat_RR& X, long n)  \n{  \n   X.SetDims(n, n);  \n   long i, j;  \n  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= n; j++)  \n         if (i == j)  \n            set(X(i, j));  \n         else  \n            clear(X(i, j));  \n} \n\n\nvoid determinant(RR& d, const mat_RR& M_in)\n{\n   long k, n;\n   long i, j;\n   long pos;\n   RR t1, t2;\n   RR *x, *y;\n\n   n = M_in.NumRows();\n\n   if (M_in.NumCols() != n)\n      Error(\"determinant: nonsquare matrix\");\n\n   if (n == 0) {\n      set(d);\n      return;\n   }\n\n   mat_RR M;\n\n   M = M_in;\n\n\n   RR det;\n   set(det);\n\n   RR maxval;\n\n\n   for (k = 0; k < n; k++) {\n      pos = -1;\n      clear(maxval);\n      for (i = k; i < n; i++) {\n         abs(t1, M[i][k]);\n         if (t1 > maxval) {\n            pos = i;\n            maxval = t1;\n         }\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n            negate(det, det);\n         }\n\n         mul(det, det, M[k][k]);\n\n         // make M[k, k] == -1 \n\n         inv(t1, M[k][k]);\n         negate(t1, t1);\n         for (j = k+1; j < n; j++) {\n            mul(M[k][j], M[k][j], t1);\n         }\n\n         for (i = k+1; i < n; i++) {\n            // M[i] = M[i] + M[k]*M[i,k]\n\n            t1 = M[i][k];   \n\n            x = M[i].elts() + (k+1);\n            y = M[k].elts() + (k+1);\n\n            for (j = k+1; j < n; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               mul(t2, *y, t1);\n               add(*x, *x, t2);\n            }\n         }\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   d = det;\n}\n\nRR determinant(const mat_RR& a)\n   { RR x; determinant(x, a); NTL_OPT_RETURN(RR, x); }\n\n\nlong IsIdent(const mat_RR& A, long n)\n{\n   if (A.NumRows() != n || A.NumCols() != n)\n      return 0;\n\n   long i, j;\n\n   for (i = 1; i <= n; i++)\n      for (j = 1; j <= n; j++)\n         if (i != j) {\n            if (!IsZero(A(i, j))) return 0;\n         }\n         else {\n            if (!IsOne(A(i, j))) return 0;\n         }\n\n   return 1;\n}\n            \n\nvoid transpose(mat_RR& X, const mat_RR& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   long i, j;\n\n   if (&X == & A) {\n      if (n == m)\n         for (i = 1; i <= n; i++)\n            for (j = i+1; j <= n; j++)\n               swap(X(i, j), X(j, i));\n      else {\n         mat_RR tmp;\n         tmp.SetDims(m, n);\n         for (i = 1; i <= n; i++)\n            for (j = 1; j <= m; j++)\n               tmp(j, i) = A(i, j);\n         X.kill();\n         X = tmp;\n      }\n   }\n   else {\n      X.SetDims(m, n);\n      for (i = 1; i <= n; i++)\n         for (j = 1; j <= m; j++)\n            X(j, i) = A(i, j);\n   }\n}\n   \n\nvoid solve(RR& d, vec_RR& X, \n           const mat_RR& A, const vec_RR& b)\n\n{\n   long n = A.NumRows();\n   if (A.NumCols() != n)\n      Error(\"solve: nonsquare matrix\");\n\n   if (b.length() != n)\n      Error(\"solve: dimension mismatch\");\n\n   if (n == 0) {\n      set(d);\n      X.SetLength(0);\n      return;\n   }\n\n   long i, j, k, pos;\n   RR t1, t2;\n   RR *x, *y;\n\n   mat_RR M;\n   M.SetDims(n, n+1);\n\n   for (i = 0; i < n; i++) {\n      for (j = 0; j < n; j++) \n         M[i][j] = A[j][i];\n      M[i][n] = b[i];\n   }\n\n   RR det;\n   set(det);\n\n   RR maxval;\n\n   for (k = 0; k < n; k++) {\n      pos = -1;\n      clear(maxval);\n      for (i = k; i < n; i++) {\n         abs(t1, M[i][k]);\n         if (t1 > maxval) {\n            pos = i;\n            maxval = t1;\n         }\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n            negate(det, det);\n         }\n\n         mul(det, det, M[k][k]);\n\n         // make M[k, k] == -1 \n\n         inv(t1, M[k][k]);\n         negate(t1, t1);\n         for (j = k+1; j <= n; j++) {\n            mul(M[k][j], M[k][j], t1);\n         }\n\n         for (i = k+1; i < n; i++) {\n            // M[i] = M[i] + M[k]*M[i,k]\n\n            t1 = M[i][k];   \n\n            x = M[i].elts() + (k+1);\n            y = M[k].elts() + (k+1);\n\n            for (j = k+1; j <= n; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               mul(t2, *y, t1);\n               add(*x, *x, t2);\n            }\n         }\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   X.SetLength(n);\n   for (i = n-1; i >= 0; i--) {\n      clear(t1);\n      for (j = i+1; j < n; j++) {\n         mul(t2, X[j], M[i][j]);\n         add(t1, t1, t2);\n      }\n      sub(t1, t1, M[i][n]);\n      X[i] = t1;\n   }\n\n   d = det;\n}\n\nvoid inv(RR& d, mat_RR& X, const mat_RR& A)\n{\n   long n = A.NumRows();\n   if (A.NumCols() != n)\n      Error(\"inv: nonsquare matrix\");\n\n   if (n == 0) {\n      set(d);\n      X.SetDims(0, 0);\n      return;\n   }\n\n   long i, j, k, pos;\n   RR t1, t2;\n   RR *x, *y;\n\n\n   mat_RR M;\n   M.SetDims(n, 2*n);\n\n   for (i = 0; i < n; i++) {\n      for (j = 0; j < n; j++) {\n         M[i][j] = A[i][j];\n         clear(M[i][n+j]);\n      }\n      set(M[i][n+i]);\n   }\n\n   RR det;\n   set(det);\n\n   RR maxval;\n\n   for (k = 0; k < n; k++) {\n      pos = -1;\n      clear(maxval);\n      for (i = k; i < n; i++) {\n         abs(t1, M[i][k]);\n         if (t1 > maxval) {\n            pos = i;\n            maxval = t1;\n         }\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n            negate(det, det);\n         }\n\n         mul(det, det, M[k][k]);\n\n         // make M[k, k] == -1 \n\n         inv(t1, M[k][k]);\n         negate(t1, t1);\n         for (j = k+1; j < 2*n; j++) {\n            mul(M[k][j], M[k][j], t1);\n         }\n\n         for (i = k+1; i < n; i++) {\n            // M[i] = M[i] + M[k]*M[i,k]\n\n            t1 = M[i][k];   \n\n            x = M[i].elts() + (k+1);\n            y = M[k].elts() + (k+1);\n\n            for (j = k+1; j < 2*n; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               mul(t2, *y, t1);\n               add(*x, *x, t2);\n            }\n         }\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   X.SetDims(n, n);\n   for (k = 0; k < n; k++) {\n      for (i = n-1; i >= 0; i--) {\n         clear(t1);\n         for (j = i+1; j < n; j++) {\n            mul(t2, X[j][k], M[i][j]);\n            add(t1, t1, t2);\n         }\n         sub(t1, t1, M[i][n+k]);\n         X[i][k] = t1;\n      }\n   }\n\n   d = det;\n}\n\n\n   \nvoid mul(mat_RR& X, const mat_RR& A, const RR& b_in)\n{\n   RR b = b_in;\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(n, m);\n\n   long i, j;\n   for (i = 0; i < n; i++)\n      for (j = 0; j < m; j++)\n         mul(X[i][j], A[i][j], b);\n}\n\n\nvoid mul(mat_RR& X, const mat_RR& A, double b_in)\n{\n   static RR b;\n   b = b_in;\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(n, m);\n\n   long i, j;\n   for (i = 0; i < n; i++)\n      for (j = 0; j < m; j++)\n         mul(X[i][j], A[i][j], b);\n}\n\nvoid diag(mat_RR& X, long n, const RR& d_in)  \n{  \n   RR d = d_in;\n   X.SetDims(n, n);  \n   long i, j;  \n  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= n; j++)  \n         if (i == j)  \n            X(i, j) = d;  \n         else  \n            clear(X(i, j));  \n} \n\nlong IsDiag(const mat_RR& A, long n, const RR& d)\n{\n   if (A.NumRows() != n || A.NumCols() != n)\n      return 0;\n\n   long i, j;\n\n   for (i = 1; i <= n; i++)\n      for (j = 1; j <= n; j++)\n         if (i != j) {\n            if (!IsZero(A(i, j))) return 0;\n         }\n         else {\n            if (A(i, j) != d) return 0;\n         }\n\n   return 1;\n}\n\nvoid negate(mat_RR& X, const mat_RR& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n\n   X.SetDims(n, m);\n\n   long i, j;\n   for (i = 1; i <= n; i++)\n      for (j = 1; j <= m; j++)\n         negate(X(i,j), A(i,j));\n}\n\nlong IsZero(const mat_RR& a)\n{\n   long n = a.NumRows();\n   long i;\n\n   for (i = 0; i < n; i++)\n      if (!IsZero(a[i]))\n         return 0;\n\n   return 1;\n}\n\nvoid clear(mat_RR& x)\n{\n   long n = x.NumRows();\n   long i;\n   for (i = 0; i < n; i++)\n      clear(x[i]);\n}\n\n\nmat_RR operator+(const mat_RR& a, const mat_RR& b)\n{\n   mat_RR res;\n   add(res, a, b);\n   NTL_OPT_RETURN(mat_RR, res);\n}\n\nmat_RR operator*(const mat_RR& a, const mat_RR& b)\n{\n   mat_RR res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(mat_RR, res);\n}\n\nmat_RR operator-(const mat_RR& a, const mat_RR& b)\n{\n   mat_RR res;\n   sub(res, a, b);\n   NTL_OPT_RETURN(mat_RR, res);\n}\n\n\nmat_RR operator-(const mat_RR& a)\n{\n   mat_RR res;\n   negate(res, a);\n   NTL_OPT_RETURN(mat_RR, res);\n}\n\n\nvec_RR operator*(const mat_RR& a, const vec_RR& b)\n{\n   vec_RR res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_RR, res);\n}\n\nvec_RR operator*(const vec_RR& a, const mat_RR& b)\n{\n   vec_RR res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_RR, res);\n}\n\n\nvoid inv(mat_RR& X, const mat_RR& A)\n{\n   RR d;\n   inv(d, X, A);\n   if (d == 0) Error(\"inv: non-invertible matrix\");\n}\n\nvoid power(mat_RR& X, const mat_RR& A, const ZZ& e)\n{\n   if (A.NumRows() != A.NumCols()) Error(\"power: non-square matrix\");\n\n   if (e == 0) {\n      ident(X, A.NumRows());\n      return;\n   }\n\n   mat_RR T1, T2;\n   long i, k;\n\n   k = NumBits(e);\n   T1 = A;\n\n   for (i = k-2; i >= 0; i--) {\n      sqr(T2, T1);\n      if (bit(e, i))\n         mul(T1, T2, A);\n      else\n         T1 = T2;\n   }\n\n   if (e < 0)\n      inv(X, T1);\n   else\n      X = T1;\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "5c235b49dd7578dc5347ed5a2a0332eff0fba7b9", "size": 12005, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ntl/mat_RR.cpp", "max_stars_repo_name": "av-elier/fast-exponentiation-algs", "max_stars_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-17T20:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T19:52:14.000Z", "max_issues_repo_path": "src/ntl/mat_RR.cpp", "max_issues_repo_name": "av-elier/fast-exponentiation-algs", "max_issues_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ntl/mat_RR.cpp", "max_forks_repo_name": "av-elier/fast-exponentiation-algs", "max_forks_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_forks_repo_licenses": ["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.6284875184, "max_line_length": 69, "alphanum_fraction": 0.3793419409, "num_tokens": 4350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5077221954997067}}
{"text": "//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include <boost/test/unit_test.hpp>\n#include \"ParserFlatbuffersSerializeFixture.hpp\"\n#include \"../Deserializer.hpp\"\n\n#include <string>\n#include <iostream>\n\nBOOST_AUTO_TEST_SUITE(Deserializer)\n\nstruct RsqrtFixture : public ParserFlatbuffersSerializeFixture\n{\n    explicit RsqrtFixture(const std::string & inputShape,\n                          const std::string & outputShape,\n                          const std::string & dataType)\n    {\n        m_JsonString = R\"(\n        {\n                inputIds: [0],\n                outputIds: [2],\n                layers: [\n                {\n                    layer_type: \"InputLayer\",\n                    layer: {\n                          base: {\n                                layerBindingId: 0,\n                                base: {\n                                    index: 0,\n                                    layerName: \"InputLayer\",\n                                    layerType: \"Input\",\n                                    inputSlots: [{\n                                        index: 0,\n                                        connection: {sourceLayerIndex:0, outputSlotIndex:0 },\n                                    }],\n                                    outputSlots: [ {\n                                        index: 0,\n                                        tensorInfo: {\n                                            dimensions: )\" + inputShape + R\"(,\n                                            dataType: )\" + dataType + R\"(\n                                        },\n                                    }],\n                                 },}},\n                },\n                {\n                layer_type: \"RsqrtLayer\",\n                layer : {\n                        base: {\n                             index:1,\n                             layerName: \"RsqrtLayer\",\n                             layerType: \"Rsqrt\",\n                             inputSlots: [\n                                            {\n                                             index: 0,\n                                             connection: {sourceLayerIndex:0, outputSlotIndex:0 },\n                                            }\n                             ],\n                             outputSlots: [ {\n                                 index: 0,\n                                 tensorInfo: {\n                                     dimensions: )\" + outputShape + R\"(,\n                                     dataType: )\" + dataType + R\"(\n                                 },\n                             }],\n                            }},\n                },\n                {\n                layer_type: \"OutputLayer\",\n                layer: {\n                        base:{\n                              layerBindingId: 0,\n                              base: {\n                                    index: 2,\n                                    layerName: \"OutputLayer\",\n                                    layerType: \"Output\",\n                                    inputSlots: [{\n                                        index: 0,\n                                        connection: {sourceLayerIndex:1, outputSlotIndex:0 },\n                                    }],\n                                    outputSlots: [ {\n                                        index: 0,\n                                        tensorInfo: {\n                                            dimensions: )\" + outputShape + R\"(,\n                                            dataType: )\" + dataType + R\"(\n                                        },\n                                }],\n                            }}},\n                }]\n         }\n        )\";\n        Setup();\n    }\n};\n\n\nstruct Rsqrt2dFixture : RsqrtFixture\n{\n    Rsqrt2dFixture() : RsqrtFixture(\"[ 2, 2 ]\",\n                                    \"[ 2, 2 ]\",\n                                    \"Float32\") {}\n};\n\nBOOST_FIXTURE_TEST_CASE(Rsqrt2d, Rsqrt2dFixture)\n{\n  RunTest<2, armnn::DataType::Float32>(\n      0,\n      {{\"InputLayer\", { 1.0f,  4.0f,\n                        16.0f, 25.0f }}},\n      {{\"OutputLayer\",{ 1.0f,  0.5f,\n                        0.25f, 0.2f }}});\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4361e5048581ed95c9df331bd3260771156108aa", "size": 4271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/armnnDeserializer/test/DeserializeRsqrt.cpp", "max_stars_repo_name": "VinayKarnam/armnn", "max_stars_repo_head_hexsha": "98525965c7cfecd9bf48297b433b2122cd1b4a1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-09T15:14:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T01:37:53.000Z", "max_issues_repo_path": "src/armnnDeserializer/test/DeserializeRsqrt.cpp", "max_issues_repo_name": "VinayKarnam/armnn", "max_issues_repo_head_hexsha": "98525965c7cfecd9bf48297b433b2122cd1b4a1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/armnnDeserializer/test/DeserializeRsqrt.cpp", "max_forks_repo_name": "VinayKarnam/armnn", "max_forks_repo_head_hexsha": "98525965c7cfecd9bf48297b433b2122cd1b4a1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-23T11:34:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T15:51:37.000Z", "avg_line_length": 36.1949152542, "max_line_length": 98, "alphanum_fraction": 0.2900959963, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5077221907477133}}
{"text": "#include <random>\n#include <cmath>\n#include <cassert>\n\n#include <omp.h>\n\n#include <NTL/ZZ.h>\n#include <NTL/tools.h>\n\n#include \"gsw.hpp\"\n\nusing namespace std;\nusing namespace NTL;\n\nGSW::GSW() {\n    GSW(80, 1);\n}\n\nGSW::GSW(const int kappa, const int L) {\n    // Search for suitable parameters:\n    // n >= log(q/sigma)(k+110)/7.2\n    // q/sigma6 > 8(N + 1)^L\n    BigInt lower_bound;\n    n = (kappa+110)/7.2;\n    quotient = 4;\n    l = floor(log(quotient)/log(2)) + 1;\n    N = (n + 1) * l;\n    while (true) {\n        power(lower_bound, N+1,L);\n        lower_bound *= 8 * sigma6;\n        if (quotient <= lower_bound) {\n            NextPrime(quotient, lower_bound);\n        } else {\n            break;\n        }\n        n = log(quotient/ceil(sigma))*(kappa+110)/(7.2*log(2));\n        l = floor(log(quotient)/log(2)) + 1;\n        N = (n + 1) * l;\n    }\n\n    n_1 = n+1;\n    m = ceil(n * log(quotient)/log(2));\n\n    gaussSampler = new GaussSampler(sigma);\n\n    omp_set_num_threads(4);\n}\n\nGSW::~GSW() {\n    delete gaussSampler;\n}\n\n\nBIVector GSW::secret_key_gen() const {\n    BIVector secret_key(n+1);\n    // sample uniformly\n    for (size_t i = 1; i < secret_key.size(); i++) {\n        secret_key[i] = RandomBnd(quotient);\n    }\n    secret_key[0] = 1;\n    return secret_key;\n}\n\nBIMatrix GSW::public_key_gen(const BIVector& sk) const {\n    // recovering t from sk, defined as t = (-s_2,...,-s_n) in Z_q\n    BIVector t(n);\n    for (unsigned int i = 0; i < n; i++) {\n        t[i] = quotient - sk[i+1];\n    }\n\n    // Uniformaly generated matrix (part of pk)\n    BIMatrix B(m * n);\n    for (unsigned int i = 0; i < m*n; i++)\n        B[i] = RandomBnd(quotient);\n\n    // First column of public key  b = B*t + e\n    BIVector b(m);\n    //BIVector e(m); // Error vector, optimized out\n    BigInt temp;\n    for (unsigned int i = 0; i < m; i++) { \n        for (unsigned int j = 0; j < n; j++) {\n            MulMod(temp, B[i*n+j], t[j], quotient);\n            AddMod(b[i], b[i], temp, quotient);\n            //b[i] += B[i*n + j] * t[j];\n            //b[i] = b[i] % quotient;\n        }\n        int bit = gaussSampler->sample() % sigma6;\n        //e[i] = bit;\n        b[i] += bit;\n    }\n\n    // Observe that pk * sk = e\n    BIMatrix pk(m * n_1);\n    for (unsigned int i = 0; i < m; i++) {\n        pk[i*n_1] = b[i];\n    }\n    for (unsigned int i = 0; i < m*n; i++) {\n        pk[1+i+(i/n)] = B[i];\n    }\n\n    // this is satisfied, the check proves it\n#define DEBUG\n#ifdef DEBUG\n    BIVector e_1(m);\n    for (unsigned int i = 0; i < m; i++) {\n        e_1[i] = 0;\n        for (unsigned int j = 0; j < n_1; j++) {\n            e_1[i] += pk[i*n_1 + j] * sk[j];\n            e_1[i] = e_1[i] % quotient;\n        }\n        //assert(e_1[i] == e[i]);\n    }\n#endif\n\n    return pk;\n}\n\nBitMatrix GSW::encrypt(const BIMatrix& public_key, const BigInt& message) const {\n    bernoulli_distribution bernoulli(0.5);\n\n    BitMatrix R(N * m);\n    for (size_t i = 0; i < R.size(); i++) {\n        R[i] = bernoulli(generator);\n    }\n    BIMatrix RA(N * n_1);\n    BigInt temp;\n# pragma omp parallel for shared (R, public_key, RA) schedule(guided)\n    for (unsigned int i = 0; i < N; i++) { \n        if (omp_get_thread_num() == 0)\n            cerr << \"Calc RA matrix \" << i << \" out of \" << N << \"\\r\";\n        for (unsigned int j = 0; j < n_1; j++) {\n            RA[i*n_1 + j] = 0;\n            for (unsigned int k = 0; k < m; k++) {\n                MulMod(temp, R[i*m + k], public_key[k*n_1 + j], quotient);\n                AddMod(RA[i*n_1 + j], RA[i*n_1 + j], temp, quotient);\n                //RA[i*n_1 + j] += R[i*m + k] * public_key[k*n_1 + j];\n                //RA[i*n_1 + j] = RA[i*n_1 + j] % quotient;\n            }\n        }\n    }\n    cerr << endl;\n    const BitMatrix RAbits = bit_decomp(RA);\n    BIMatrix C(N * N);\n# pragma omp parallel for shared (C, message) schedule(guided)\n    for (unsigned int i = 0; i < N; i++) {\n        if (omp_get_thread_num() == 0)\n            cerr << \"Calc ciphertext matrix \" << i << \" out of \" << N << \"\\r\";\n        for (unsigned int j = 0; j < N; j++) {\n            C[i*N + j] = RAbits[i*N + j];\n            // message * identity \n            if (i == j) {\n                C[i*N + j] += message;\n            }\n            //C[i*N + j] = C[i*N + j] % quotient;\n        }\n    }\n\n    cerr << endl << \"Now to flatten\" << endl;\n\n    return flatten(C);\n}\n\nBigInt GSW::decrypt(const BIVector& sk, const BitMatrix& C) const {\n    BigInt m, it, fract;\n    const auto v = powers_of_2(sk);\n    BIVector powered_m_bits(l-1);\n    for (unsigned int i = 0; i < l-1; i++) {\n        powered_m_bits[i] = 0;\n        for (unsigned int j = 0; j < N; j++) {\n            powered_m_bits[i] += C[i*(l-1) + j] * v[j];\n            powered_m_bits[i] = powered_m_bits[i] % quotient;\n        }\n    }\n    m = 0;\n    for (int i = l-2; i >= 0; i--) {\n        it = (powered_m_bits[i] - pow(2, i)*m);\n        fract = it % quotient/2;\n        bool bit = fract >= quotient/4;\n\n        m += bit << (l-2 - i);\n    }\n\n    return m;\n}\n\nbool GSW::decrypt_bit(const BIVector& sk, const BitMatrix& C) const {\n    unsigned int i;\n    const auto v = powers_of_2(sk);\n    BigInt q_4, q_2; q_4 = quotient/4; q_2 = quotient/2;\n    \n    for(i = 0; i < l; i++) {\n        if(v[i] > q_4 && v[i] <= q_2) break;\n    }\n\n    BigInt xi, temp;\n    xi = 0;\n    for (unsigned int j = 0; j < N; j++) {\n        MulMod(temp, C[i*N + j], v[j], quotient);\n        AddMod(xi, xi, temp, quotient);\n        //xi += (C[i*N + j] * v[j]);\n        //xi = xi % quotient;\n    }\n\n    return xi >= v[i]/2; \n}\n\nBitMatrix GSW::nand(const BitMatrix& a, const BitMatrix& b) const {\n    BIMatrix res(a.size());\n\n    for (unsigned int i = 0; i < N; i++) {\n        res[i*N + i] = 1;\n    }\n\n    BigInt temp;\n# pragma omp parallel for shared (a, b, res) schedule(guided)\n    for (unsigned int i = 0; i < N; i++) {\n        if (omp_get_thread_num() == 0)\n            cerr << \"Performing a NAND, hold on \" << i << \" out of \" << N << \"\\r\";\n        for (unsigned int j = 0; j < N; j++) {\n            for (unsigned int k = 0; k < N; k++) {\n                res[i*N + j] = res[i*N + j] + (a[i*N + k] & b[k*N + j]);\n            }\n            res[i*N + j] = res[i*N + j] % quotient;\n        }\n    }\n    cerr << endl;\n\n    return flatten(res);\n}\n\n//////////////////////////////////////////////\n// Utility Functions\n//////////////////////////////////////////////\n\n\nBIVector GSW::powers_of_2(const BIVector& a) const {\n    BIVector result(N);\n# pragma omp parallel for shared (result, a) schedule(guided)\n    for (unsigned int i = 0; i < n+1; i++) {\n        for (unsigned int j = 0; j < l; j++) {\n            MulMod(result[i*l + j], power2_ZZ(j), a[i], quotient);\n            //result[i*l + j] = (BigInt) pow(2, j)*a[i] % quotient;\n        }\n    }\n    \n    return result;\n}\n\nBitVector GSW::bit_decomp(const BIVector& a) const {\n    unsigned int num_rows = a.size() / n_1;\n    BitVector result(n_1*l*num_rows);\n    BigInt mask;\n    mask = 1;\n# pragma omp parallel for shared (result, a) schedule(guided)\n    for (unsigned int j = 0; j < l; j++) {\n        for (unsigned int k = 0; k < num_rows; k++) {\n            for (unsigned int i = 0; i < n_1; i++) {\n                result[k*l*n_1 + i*l + j] = (a[k*n_1 + i] & mask) > 0;\n            }\n        }\n        mask <<= 1;\n    }\n\n    return result;\n}\n\nBIVector GSW::inverse_bit_decomp(const BitVector& a) const {\n    BIVector result(n_1 * N);\n    BigInt multiplier;\n    multiplier = 1;\n\n# pragma omp parallel for shared (result, a) schedule(guided)\n    for (unsigned int j = 0; j < l; j++) {\n        for (unsigned int row = 0; row < N; row++) {\n            for (unsigned int i = 0; i < n_1; i++) {\n                result[row * n_1 + i] += a[row*n_1*l + i*l + j] * multiplier;\n            }\n        }\n        multiplier <<= 1;\n    }\n\n    return result; \n}\n\nBIVector GSW::inverse_bit_decomp(const BIVector& a) const {\n    BIVector result(n_1 * N);\n    BigInt multiplier;\n    multiplier = 1;\n\n# pragma omp parallel for shared (result, a) schedule(guided)\n    for (unsigned int j = 0; j < l; j++) {\n        for (unsigned int row = 0; row < N; row++) {\n            for (unsigned int i = 0; i < n_1; i++) {\n                result[row * n_1 + i] += a[row*n_1*l + i*l + j] * multiplier;\n            }\n        }\n        multiplier <<= 1;\n    }\n\n    return result; \n}\n\nBitVector GSW::flatten(const BitVector& a) const {\n    return bit_decomp(inverse_bit_decomp(a));\n}\n\nBitVector GSW::flatten(const BIVector& a) const {\n    return bit_decomp(inverse_bit_decomp(a));\n}\n", "meta": {"hexsha": "b532171fe5251318135aa28d262cd66d6fdf5a0d", "size": 8492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gsw.cpp", "max_stars_repo_name": "adomasven/gsw13", "max_stars_repo_head_hexsha": "488459270e54113f791bf3c6a0e2134a3f5e9a88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-11-22T13:55:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T14:24:18.000Z", "max_issues_repo_path": "src/gsw.cpp", "max_issues_repo_name": "adomasven/gsw13", "max_issues_repo_head_hexsha": "488459270e54113f791bf3c6a0e2134a3f5e9a88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-05T07:23:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-16T08:39:44.000Z", "max_forks_repo_path": "src/gsw.cpp", "max_forks_repo_name": "adomasven/gsw13", "max_forks_repo_head_hexsha": "488459270e54113f791bf3c6a0e2134a3f5e9a88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-06-12T04:41:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T12:11:35.000Z", "avg_line_length": 27.3935483871, "max_line_length": 82, "alphanum_fraction": 0.4934055582, "num_tokens": 2726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431001, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.5077031817262434}}
{"text": "#ifndef IMAGE_REPROJECTION_PLUGINS_SPHERE_SURFACE_MODEL_HPP\n#define IMAGE_REPROJECTION_PLUGINS_SPHERE_SURFACE_MODEL_HPP\n\n#include <cmath>\n#include <string>\n\n#include <image_reprojection/surface_model.hpp>\n#include <image_reprojection_plugins/SphereStamped.h>\n#include <topic_tools/shape_shifter.h>\n\n#include <boost/thread/locks.hpp>\n#include <boost/thread/shared_mutex.hpp>\n\n#include <opencv2/core/core.hpp>\n\nnamespace image_reprojection_plugins {\n\nclass SphereSurfaceModel : public image_reprojection::SurfaceModel {\npublic:\n  SphereSurfaceModel() {}\n\n  virtual ~SphereSurfaceModel() {}\n\n  virtual void update(const topic_tools::ShapeShifter &surface) {\n    const SphereStampedConstPtr sphere(surface.instantiate< SphereStamped >());\n    CV_Assert(sphere);\n    update(*sphere);\n  }\n\n  void update(const SphereStamped &sphere) {\n    CV_Assert(sphere.radius > 0.);\n\n    boost::unique_lock< boost::shared_mutex > write_lock(mutex_);\n\n    frame_id_ = sphere.header.frame_id;\n    center_ = cv::Vec3f(sphere.center.x, sphere.center.y, sphere.center.z);\n    radius_ = sphere.radius;\n  }\n\n  virtual std::string getFrameId() const {\n    boost::shared_lock< boost::shared_mutex > read_lock(mutex_);\n    return frame_id_;\n  }\n\nprivate:\n  virtual void onInit() {}\n\n  virtual void onIntersection(const cv::Vec3f &src_origin, const cv::Mat &src_direction,\n                              cv::Mat &dst, cv::Mat &mask) const {\n    boost::shared_lock< boost::shared_mutex > read_lock(mutex_);\n    multiraySphereIntersection(src_origin, src_direction, dst, mask);\n  }\n\n  void multiraySphereIntersection(const cv::Vec3f &src_origin, const cv::Mat &src_direction,\n                                  cv::Mat &dst, cv::Mat &mask) const {\n    dst.create(src_direction.size(), CV_32FC3);\n    for (int x = 0; x < src_direction.size().width; ++x) {\n      for (int y = 0; y < src_direction.size().height; ++y) {\n        unsigned char &m(mask.at< unsigned char >(y, x));\n        const cv::Vec3f &sd(src_direction.at< cv::Vec3f >(y, x));\n        cv::Vec3f &d(dst.at< cv::Vec3f >(y, x));\n        m = (m != 0 && raySphereIntersection(src_origin, sd, d)) ? 1 : 0;\n      }\n    }\n  }\n\n  bool raySphereIntersection(const cv::Vec3f &src_origin, const cv::Vec3f &src_direction,\n                             cv::Vec3f &dst) const {\n    // intersection point (x) can be described as\n    //   x = p + t * d  (t >= 0)\n    //   |x - c| = r\n    // where p: ray origin, d: ray direction, c: center of sphere, r: radius of sphere\n    //   |d|^2 * t^2 + 2 * dot(d, p - c) * t + |p - c|^2 - r^2 = 0\n\n    // position of ray origin with respect to center of sphere\n    const cv::Vec3f o(src_origin - center_);\n\n    // coefficients\n    const double a(src_direction.dot(src_direction));\n    const double b(src_direction.dot(o));\n    const double c(o.dot(o) - radius_ * radius_);\n    const double D(b * b - a * c); // discriminant\n    if (/* no intersection */ D < 0.) {\n      return false;\n    }\n\n    // intersection point\n    const double sD(std::sqrt(D));\n    const double t0((-b + sD) / a), t1((-b - sD) / a);\n    if (t0 >= 0. && t1 >= 0.) {\n      dst = src_origin + std::min(t0, t1) * src_direction;\n      return true;\n    } else if (t0 >= 0. && t1 < 0.) {\n      dst = src_origin + t0 * src_direction;\n      return true;\n    } else if (t0 < 0. && t1 >= 0.) {\n      dst = src_origin + t1 * src_direction;\n      return true;\n    }\n\n    return false;\n  }\n\nprivate:\n  mutable boost::shared_mutex mutex_;\n  std::string frame_id_;\n  cv::Vec3f center_;\n  double radius_;\n};\n\n} // namespace image_reprojection_plugins\n\n#endif", "meta": {"hexsha": "6fcfcaf9d9c5ce6eeff913d7bcc873206a4bd2ba", "size": 3568, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "image_reprojection_plugins/include/image_reprojection_plugins/sphere_surface_model.hpp", "max_stars_repo_name": "dkobayashikdel/image_reprojection", "max_stars_repo_head_hexsha": "9d9f2c85065783ef45d2e1cd877e615b79c69bfe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "image_reprojection_plugins/include/image_reprojection_plugins/sphere_surface_model.hpp", "max_issues_repo_name": "dkobayashikdel/image_reprojection", "max_issues_repo_head_hexsha": "9d9f2c85065783ef45d2e1cd877e615b79c69bfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "image_reprojection_plugins/include/image_reprojection_plugins/sphere_surface_model.hpp", "max_forks_repo_name": "dkobayashikdel/image_reprojection", "max_forks_repo_head_hexsha": "9d9f2c85065783ef45d2e1cd877e615b79c69bfe", "max_forks_repo_licenses": ["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.5752212389, "max_line_length": 92, "alphanum_fraction": 0.6378923767, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.507692569521065}}
{"text": "// Copyright (c) 2014 The Bitcoin Core developers\n// Distributed under the MIT/X11 software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"core.h\"\n#include \"main.h\"\n#include \"uint256.h\"\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(main_tests)\n\n/**\n * the maximum block reward at a given height for a block without fees\n */\nuint64_t expectedMaxSubsidy(int height) {\n    if(height < 100000) {\n        return 1000000 * COIN;\n    } else if (height < 150000) {\n        return 500000 * COIN;\n    } else if (height < 200000) {\n        return 250000 * COIN;\n    } else if (height < 300000) {\n        return 125000 * COIN;\n    } else if (height < 400000) {\n        return  62500 * COIN;\n    } else if (height < 500000) {\n        return  31250 * COIN;\n    } else if (height < 600000) {\n        return  15625 * COIN;\n    } else {\n        return  10000 * COIN;\n    }\n}\n\n/**\n * the minimum possible value for the maximum block reward at a given height\n * for a block without fees\n */\nuint64_t expectedMinSubsidy(int height) {\n    if(height < 100000) {\n        return 0;\n    } else if (height < 150000) {\n        return 0;\n    } else if (height < 200000) {\n        return 250000 * COIN;\n    } else if (height < 300000) {\n        return 125000 * COIN;\n    } else if (height < 400000) {\n        return  62500 * COIN;\n    } else if (height < 500000) {\n        return  31250 * COIN;\n    } else if (height < 600000) {\n        return  15625 * COIN;\n    } else {\n        return  10000 * COIN;\n    }\n}\n\nBOOST_AUTO_TEST_CASE(subsidy_limit_test)\n{\n    int nHeight = 0;\n    int nStepSize= 1;\n    uint256 nSum = 0;\n\n    for (nHeight = 0; nHeight <= 600000; nHeight += nStepSize) {\n        uint64_t nSubsidy = GetBlockValue(nHeight, 0, 0);\n        BOOST_CHECK(MoneyRange(nSubsidy));\n        BOOST_CHECK(nSubsidy >= expectedMinSubsidy(nHeight));\n        BOOST_CHECK(nSubsidy <= expectedMaxSubsidy(nHeight));\n        \n        nSum += nSubsidy * nStepSize;\n    }\n\n    //test sum +- ~10billion\n    uint256 upperlimit = uint256(\"95e14ec776380000\"); //108 billion pete\n    BOOST_CHECK(nSum <= upperlimit);\n    \n    uint256 lowerlimit = uint256(\"7a1fe16027700000\"); //88 billion pete\n    BOOST_CHECK(nSum >= lowerlimit);\n    \n    //test infinitely increasing block rewards\n    for (; nHeight < 700000; nHeight += nStepSize) {\n        uint64_t nSubsidy = GetBlockValue(nHeight, 0, 0);\n        BOOST_CHECK(MoneyRange(nSubsidy));\n        BOOST_CHECK(nSubsidy >= expectedMinSubsidy(nHeight));\n        BOOST_CHECK(nSubsidy <= expectedMaxSubsidy(nHeight));\n        \n        nSum += nSubsidy * nStepSize;\n    }\n    \n    //make sure that MAX_MONEY is not what some people think it is\n    BOOST_CHECK(nSum > MAX_MONEY);\n    \n    //test subsidy in 1000 years\n    nHeight = 1000 * 365 * 24 * 60;\n    uint64_t nSubsidy = GetBlockValue(nHeight, 0, 0);\n    BOOST_CHECK(MoneyRange(nSubsidy));\n    BOOST_CHECK(nSubsidy >= expectedMinSubsidy(nHeight));\n    BOOST_CHECK(nSubsidy <= expectedMaxSubsidy(nHeight));\n}\n\n\nBOOST_AUTO_TEST_CASE(GetMinFee_test)\n{\n    uint64_t value = 1000 * COIN;\n\n    CTransaction tx;\n    CTxOut txout1(value, (CScript)vector<unsigned char>(24, 0));\n    tx.vout.push_back(txout1);\n    \n    if(CTransaction::nMinTxFee == CTransaction::nMinRelayTxFee)\n        CTransaction::nMinTxFee++;\n    \n    BOOST_CHECK(GetMinFee(tx, 100, false, GMF_RELAY) == CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, 100, false, GMF_SEND) == CTransaction::nMinTxFee);\n    \n    BOOST_CHECK(GetMinFee(tx, 1, false, GMF_RELAY) == CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, 1, false, GMF_SEND) == CTransaction::nMinTxFee);\n    \n    BOOST_CHECK(GetMinFee(tx, 999, false, GMF_RELAY) == CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, 999, false, GMF_SEND) == CTransaction::nMinTxFee);\n    \n    BOOST_CHECK(GetMinFee(tx, 1000, false, GMF_RELAY) == 2 * CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, 1000, false, GMF_SEND) == 2 * CTransaction::nMinTxFee);\n    \n    BOOST_CHECK(GetMinFee(tx, 2000, false, GMF_RELAY) == 3 * CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, 2000, false, GMF_SEND) == 3 * CTransaction::nMinTxFee);\n    \n    BOOST_CHECK(GetMinFee(tx, MAX_STANDARD_TX_SIZE, false, GMF_RELAY) == (1+(MAX_STANDARD_TX_SIZE/1000))*CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, MAX_STANDARD_TX_SIZE, false, GMF_SEND) == (1+(MAX_STANDARD_TX_SIZE/1000))*CTransaction::nMinTxFee);\n}\n\nBOOST_AUTO_TEST_CASE(GetMinFee_dust_test)\n{\n    uint64_t value = 1000;\n\n    CTransaction tx;\n    CTxOut txout1(value, (CScript)vector<unsigned char>(24, 0));\n    tx.vout.push_back(txout1);\n    \n    if(CTransaction::nMinTxFee == CTransaction::nMinRelayTxFee)\n        CTransaction::nMinTxFee++;\n    \n    BOOST_CHECK(GetMinFee(tx, 1, false, GMF_RELAY) == 2 * CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, 1, false, GMF_SEND) == 2 * CTransaction::nMinTxFee);\n    \n    BOOST_CHECK(GetMinFee(tx, 999, false, GMF_RELAY) == 2 * CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, 999, false, GMF_SEND) == 2 * CTransaction::nMinTxFee);\n    \n    BOOST_CHECK(GetMinFee(tx, 1000, false, GMF_RELAY) == 3 * CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, 1000, false, GMF_SEND) == 3 * CTransaction::nMinTxFee);\n    \n    BOOST_CHECK(GetMinFee(tx, 2000, false, GMF_RELAY) == 4 * CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, 2000, false, GMF_SEND) == 4 * CTransaction::nMinTxFee);\n    \n    BOOST_CHECK(GetMinFee(tx, MAX_STANDARD_TX_SIZE, false, GMF_RELAY) == (2+(MAX_STANDARD_TX_SIZE/1000))*CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, MAX_STANDARD_TX_SIZE, false, GMF_SEND) == (2+(MAX_STANDARD_TX_SIZE/1000))*CTransaction::nMinTxFee);\n}\n\nBOOST_AUTO_TEST_CASE(GetMinFee_manydust_test)\n{\n    uint64_t value = 1000;\n\n    CTransaction tx;\n    CTxOut txout1(1000 * COIN, (CScript)vector<unsigned char>(24, 0));\n    tx.vout.push_back(txout1);\n    \n    for(int i=0; i<100; i++) {\n        CTxOut txoutn(value, (CScript)vector<unsigned char>(24, 0));\n        tx.vout.push_back(txoutn);\n    }\n    \n    CTxOut txout101(1000 * COIN, (CScript)vector<unsigned char>(24, 0));\n    tx.vout.push_back(txout101);\n    \n    if(CTransaction::nMinTxFee == CTransaction::nMinRelayTxFee)\n        CTransaction::nMinTxFee++;\n    \n    BOOST_CHECK(GetMinFee(tx, 1, false, GMF_RELAY) == 101 * CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, 1, false, GMF_SEND) == 101 * CTransaction::nMinTxFee);\n    \n    BOOST_CHECK(GetMinFee(tx, 999, false, GMF_RELAY) == 101 * CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, 999, false, GMF_SEND) == 101 * CTransaction::nMinTxFee);\n    \n    BOOST_CHECK(GetMinFee(tx, 1000, false, GMF_RELAY) == 102 * CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, 1000, false, GMF_SEND) == 102 * CTransaction::nMinTxFee);\n    \n    BOOST_CHECK(GetMinFee(tx, 2000, false, GMF_RELAY) == 103 * CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, 2000, false, GMF_SEND) == 103 * CTransaction::nMinTxFee);\n    \n    BOOST_CHECK(GetMinFee(tx, MAX_STANDARD_TX_SIZE, false, GMF_RELAY) == (101+(MAX_STANDARD_TX_SIZE/1000))*CTransaction::nMinRelayTxFee);\n    BOOST_CHECK(GetMinFee(tx, MAX_STANDARD_TX_SIZE, false, GMF_SEND) == (101+(MAX_STANDARD_TX_SIZE/1000))*CTransaction::nMinTxFee);\n}\n\nBOOST_AUTO_TEST_CASE(GetMinFee_relayfree_test)\n{\n    uint64_t value = 1000 * COIN;\n\n    CTransaction tx;\n    CTxOut txout1(value, (CScript)vector<unsigned char>(24, 0));\n    tx.vout.push_back(txout1);\n    \n    if(CTransaction::nMinTxFee == CTransaction::nMinRelayTxFee)\n        CTransaction::nMinTxFee++;\n    \n    BOOST_CHECK(GetMinFee(tx, 100, true, GMF_RELAY) == 0);\n    BOOST_CHECK(GetMinFee(tx, 1000, true, GMF_RELAY) == 0);\n    BOOST_CHECK(GetMinFee(tx, 25999, true, GMF_RELAY) == 0);\n    \n    BOOST_CHECK(GetMinFee(tx, 26000, true, GMF_RELAY) > 0);\n    BOOST_CHECK(GetMinFee(tx, 26000, true, GMF_RELAY) == GetMinFee(tx, 26000, false, GMF_RELAY));\n    \n    BOOST_CHECK(GetMinFee(tx, MAX_STANDARD_TX_SIZE, true, GMF_RELAY) == (1+(MAX_STANDARD_TX_SIZE/1000))*CTransaction::nMinRelayTxFee);\n}\n\nBOOST_AUTO_TEST_CASE(GetMinFee_createNoFree_test)\n{\n    uint64_t value = 1000 * COIN;\n\n    CTransaction tx;\n    CTxOut txout1(value, (CScript)vector<unsigned char>(24, 0));\n    tx.vout.push_back(txout1);\n    \n    if(CTransaction::nMinTxFee == CTransaction::nMinRelayTxFee)\n        CTransaction::nMinTxFee++;\n    \n    BOOST_CHECK(GetMinFee(tx, 100, true, GMF_SEND) > 0);\n    BOOST_CHECK(GetMinFee(tx, 100, true, GMF_SEND) == GetMinFee(tx, 100, false, GMF_SEND));\n    BOOST_CHECK(GetMinFee(tx, 1000, true, GMF_SEND) > 0);\n    BOOST_CHECK(GetMinFee(tx, 1000, true, GMF_SEND) == GetMinFee(tx, 1000, false, GMF_SEND));\n    BOOST_CHECK(GetMinFee(tx, 25999, true, GMF_SEND) > 0);\n    BOOST_CHECK(GetMinFee(tx, 25999, true, GMF_SEND) == GetMinFee(tx, 25999, false, GMF_SEND));\n    \n    BOOST_CHECK(GetMinFee(tx, 26000, true, GMF_SEND) > 0);\n    BOOST_CHECK(GetMinFee(tx, 26000, true, GMF_SEND) == GetMinFee(tx, 26000, false, GMF_SEND));\n    \n    BOOST_CHECK(GetMinFee(tx, MAX_STANDARD_TX_SIZE, true, GMF_SEND) == (1+(MAX_STANDARD_TX_SIZE/1000))*CTransaction::nMinTxFee);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "602c9416831e06a7a4735fe7e041c10910083063", "size": 9253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/main_tests.cpp", "max_stars_repo_name": "sjmariogolf/petecoin", "max_stars_repo_head_hexsha": "0ba30c257af43fcff00e9eaa2db38f32afa990f5", "max_stars_repo_licenses": ["MIT"], "max_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/main_tests.cpp", "max_issues_repo_name": "sjmariogolf/petecoin", "max_issues_repo_head_hexsha": "0ba30c257af43fcff00e9eaa2db38f32afa990f5", "max_issues_repo_licenses": ["MIT"], "max_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/main_tests.cpp", "max_forks_repo_name": "sjmariogolf/petecoin", "max_forks_repo_head_hexsha": "0ba30c257af43fcff00e9eaa2db38f32afa990f5", "max_forks_repo_licenses": ["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.2355371901, "max_line_length": 137, "alphanum_fraction": 0.6789149465, "num_tokens": 3009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5076050637990712}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#define NT2_UNIT_MODULE \"nt2 optimize toolbox - levenberg\"\n\n#include <iostream>\n#include <nt2/include/functions/levenberg.hpp>\n\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/bind.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/exp.hpp>\n#include <nt2/include/functions/norm.hpp>\n#include <nt2/include/functions/sqrt.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/include/functions/globalsum.hpp>\n#include <nt2/include/functions/globalmax.hpp>\n#include <nt2/include/functions/ones.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/constants/sqrteps.hpp>\n#include <nt2/include/constants/four.hpp>\n#include <nt2/table.hpp>\n\ntemplate < class Tabout >\nstruct fpp\n{\n  template < class Tabin> inline\n  Tabout operator()(const Tabin & x ) const\n  {\n    typedef typename Tabin::value_type value_type;\n    Tabout r = (nt2::sqr((x-nt2::_(value_type(1), value_type(numel(x))))));\n    return r;\n  }\n};\n\ntemplate<class Tabout, class Tabin >  Tabout f1(const Tabin & x )\n{\n    typedef typename Tabin::value_type value_type;\n    Tabout r = (nt2::sqr(x)-value_type(3));\n    return r;\n}\n\nNT2_TEST_CASE_TPL( levenberg_function_ptr, NT2_REAL_TYPES )\n{\n  using nt2::levenberg;\n  using nt2::optimization::output;\n  typedef nt2::table<T> tab_t;\n  typedef typename nt2::meta::as_logical<T>::type lT;\n  typedef nt2::table<T> ltab_t;\n  tab_t x0 = nt2::ones(nt2::of_size(1, 3), nt2::meta::as_<T>());\n  ltab_t h = nt2::is_nez(nt2::ones (nt2::of_size(1, 3), nt2::meta::as_<T>())*nt2::Half<T>());\n  tab_t r = nt2::sqrt(T(3))*nt2::ones (nt2::of_size(1, 3), nt2::meta::as_<T>());\n  output<tab_t,T> res = levenberg(&f1<tab_t, tab_t>, x0, h);\n  std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n            << \" after \" << res.iterations_count <<  \" iterations\\n\";\n  NT2_TEST(res.successful);\n  NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::abs(res.minimum()-r)), nt2::Sqrteps<T>());\n  NT2_TEST_LESSER_EQUAL(nt2::norm(res.covar), T(12.1));\n}\n\nNT2_TEST_CASE_TPL( levenberg_functor, NT2_REAL_TYPES )\n{\n  using nt2::levenberg;\n  using nt2::options;\n  using nt2::optimization::output;\n  typedef nt2::table<T> tab_t;\n  typedef typename nt2::meta::as_logical<T>::type lT;\n  typedef nt2::table<T> ltab_t;\n  tab_t x0 = nt2::zeros(nt2::of_size(1, 3), nt2::meta::as_<T>());\n  ltab_t h = nt2::is_nez(nt2::ones (nt2::of_size(1, 3), nt2::meta::as_<T>())*nt2::Half<T>());\n  tab_t r = nt2::_(T(1), T(3));\n  output<tab_t,T> res = levenberg(fpp<tab_t>(), x0, h,\n                                  options [ nt2::iterations_ = 100,\n                                            nt2::tolerance::absolute_ = nt2::Eps<T>()\n                                    ]);\n  std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n            << \" after \" << res.iterations_count <<  \" iterations\\n\";\n\n  NT2_TEST(res.successful);\n  NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::abs(res.minimum()-r)), nt2::Four<T>()*nt2::Sqrteps<T>());\n  NT2_TEST_LESSER_EQUAL(nt2::norm(res.covar), T(10*nt2::numel(res.covar))*nt2::Eps<T>());\n}\n\n", "meta": {"hexsha": "014f076ae65001dcc6cbf345c3e3523c44deb67a", "size": 3699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/optimization/unit/scalar/levenberg.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/core/optimization/unit/scalar/levenberg.cpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/core/optimization/unit/scalar/levenberg.cpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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.7741935484, "max_line_length": 101, "alphanum_fraction": 0.6201676129, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5076050584169765}}
{"text": "#include \"export/mvproduct.h\"\n\n#include <Eigen/Core>\n#include \"geometrycentral/utilities/vector3.h\"\n#include \"poly_curve_network.h\"\n#include \"spatial/tpe_bvh.h\"\n#include \"product/block_cluster_tree.h\"\n\nusing namespace geometrycentral;\n\nnamespace LWS\n{\nPolyCurveNetwork *createCurveNetwork(std::vector<std::array<double, 3>> &positions, std::vector<std::array<size_t, 2>> &edges)\n{\n    std::vector<Vector3> vectors(positions.size());\n    for (size_t i = 0; i < positions.size(); i++)\n    {\n        vectors[i] = Vector3{positions[i][0], positions[i][1], positions[i][2]};\n    }\n    return new PolyCurveNetwork(vectors, edges);\n}\n\nBVHNode3D *createBVHForEnergy(PolyCurveNetwork *curves)\n{\n    return CreateBVHFromCurve(curves);\n}\n\nBlockClusterTree *createBlockClusterTree(PolyCurveNetwork *curves, double sep, double alpha, double beta)\n{\n    BVHNode3D *edgeBVH = CreateEdgeBVHFromCurve(curves);\n    BlockClusterTree *tree = new BlockClusterTree(curves, edgeBVH, sep, alpha, beta, 0);\n    // This block cluster tree is only going to multiply the dense upper-left block, with no duplication of entries.\n    tree->SetBlockTreeMode(BlockTreeMode::MatrixOnly);\n    return tree;\n}\n\nvoid multiplyMetricWithVector(BlockClusterTree *tree, std::vector<double> &vec, std::vector<double> &output)\n{\n    // Copy input to an Eigen matrix\n    Eigen::VectorXd in(vec.size());\n    for (size_t i = 0; i < vec.size(); i++)\n    {\n        in(i) = vec[i];\n    }\n    // Set up an Eigen matrix as output\n    Eigen::VectorXd out(vec.size());\n    out.setZero();\n\n    // Call the block cluster tree routine\n    tree->Multiply(in, out);\n\n    // Copy result to the output\n    for (size_t i = 0; i < vec.size(); i++)\n    {\n        output[i] = out(i);\n    }\n}\n\ndouble evaluateEnergy(PolyCurveNetwork *curve, BVHNode3D *root, double alpha, double beta)\n{\n    return SpatialTree::TPEnergyBH(curve, root, alpha, beta);\n}\n\nvoid evaluateGradient(PolyCurveNetwork *curve, BVHNode3D *root, std::vector<std::array<double, 3>> &out, double alpha, double beta)\n{\n    // Set up an Eigen matrix for the computation to use\n    Eigen::MatrixXd grad(out.size(), 3);\n    grad.setZero();\n\n    // Use the BVH routine\n    SpatialTree::TPEGradientBarnesHut(curve, root, grad, alpha, beta);\n\n    // Copy result to the output\n    for (size_t i = 0; i < out.size(); i++)\n    {\n        out[i][0] = grad(i, 0);\n        out[i][1] = grad(i, 1);\n        out[i][2] = grad(i, 2);\n    }\n}\n\n} // namespace LWS\n", "meta": {"hexsha": "80afab61cef91c94b54506599ed3d707cf37b687", "size": 2445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/export/mvproduct.cpp", "max_stars_repo_name": "duxingyi-charles/repulsive-curves", "max_stars_repo_head_hexsha": "a2e7729357cf25de4147fbfaa17a039c57b13a7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 131.0, "max_stars_repo_stars_event_min_datetime": "2021-01-16T20:53:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:04:37.000Z", "max_issues_repo_path": "src/export/mvproduct.cpp", "max_issues_repo_name": "duxingyi-charles/repulsive-curves", "max_issues_repo_head_hexsha": "a2e7729357cf25de4147fbfaa17a039c57b13a7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-08-05T01:30:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T01:13:01.000Z", "max_forks_repo_path": "src/export/mvproduct.cpp", "max_forks_repo_name": "duxingyi-charles/repulsive-curves", "max_forks_repo_head_hexsha": "a2e7729357cf25de4147fbfaa17a039c57b13a7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2021-01-17T05:55:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T05:48:06.000Z", "avg_line_length": 29.4578313253, "max_line_length": 131, "alphanum_fraction": 0.6683026585, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6442251064863695, "lm_q1q2_score": 0.5076050584169763}}
{"text": "// Filename: matrix_free_pcg.cpp (part of MTL4)\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\nstruct poisson2D_diagonal_pc\n{\n    template <typename VectorIn, typename VectorOut>\n    void solve(const VectorIn& x, VectorOut& y) const\n    {\n\tfor (std::size_t i= 0; i < size(x); i++)\n\t    y[i]= x[i] * 0.25;\n    }\n\n    template <typename VectorIn, typename VectorOut>\n    void adjoint_solve(const VectorIn& x, VectorOut& y) const\n    {\n\tfor (std::size_t i= 0; i < size(x); i++)\n\t    y[i]= x[i] * 0.25;\n    }\n};\n\ntemplate <typename Vector>\nitl::pc::solver<poisson2D_diagonal_pc, Vector, false>\ninline solve(const poisson2D_diagonal_pc& P, const Vector& x)\n{\n    return itl::pc::solver<poisson2D_diagonal_pc, Vector, false>(P, x);\n}\n\ntemplate <typename Vector>\nitl::pc::solver<poisson2D_diagonal_pc, Vector, true>\ninline adjoint_solve(const poisson2D_diagonal_pc& P, const Vector& x)\n{\n    return itl::pc::solver<poisson2D_diagonal_pc, Vector, true>(P, x);\n}\n\n\nint main(int, char**)\n{\n    // For a more realistic example set size to 1000 or larger\n    const int size = 10, N = size * size;\n\n    typedef mtl::mat::poisson2D_dirichlet  matrix_type;\n    matrix_type                               A(size, size);\n    poisson2D_diagonal_pc                     P;\n\n    mtl::dense_vector<double>                 x(N, 1.0), b(N);\n\n    b = A * x;\n    x= 0;\n    itl::cyclic_iteration<double>             iter(b, 100, 1.e-11, 0.0, 5);\n    cg(A, x, b, P, P, iter);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "4db4537b7af59c3b17abac419c5442fd7274ad87", "size": 1514, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/matrix_free_pcg.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/matrix_free_pcg.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/matrix_free_pcg.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.1034482759, "max_line_length": 75, "alphanum_fraction": 0.6281373844, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5076050476527866}}
{"text": "#include <engine/Eigenmodes.hpp>\n#include <engine/Vectormath.hpp>\n#include <engine/Manifoldmath.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <SymEigsSolver.h>  // Also includes <MatOp/DenseSymMatProd.h>\n\n#include <fmt/format.h>\n#include <fmt/ostream.h>\n\nnamespace Engine\n{\n    namespace Eigenmodes\n    {\n        using Utility::Log_Level;\n        using Utility::Log_Sender;\n\n        void Check_Eigenmode_Parameters(std::shared_ptr<Data::Spin_System> system)\n        {\n            int nos = system->nos;\n            auto& n_modes = system->ema_parameters->n_modes;\n            if (n_modes > 2*nos-2)\n            {\n                n_modes = 2*nos-2;\n                system->modes.resize(n_modes);\n                system->eigenvalues.resize(n_modes);\n\n                Log(Log_Level::Warning, Log_Sender::EMA, fmt::format(\"Number of eigenmodes declared in \"\n                    \"EMA Parameters is too large. The number is set to {}\", n_modes));\n            }\n            if (n_modes != system->modes.size())\n                system->modes.resize(n_modes);\n\n            // Initial check of selected_mode\n            auto& n_mode_follow = system->ema_parameters->n_mode_follow;\n            if (n_mode_follow > n_modes-1)\n            {\n                Log(Log_Level::Warning, Log_Sender::EMA, fmt::format(\"Eigenmode number {} is not \"\n                    \"available. The largest eigenmode ({}) is used instead\", n_mode_follow, n_modes-1));\n                n_mode_follow = n_modes-1;\n            }\n        }\n\n        void Calculate_Eigenmodes(std::shared_ptr<Data::Spin_System> system, int idx_img, int idx_chain)\n        {\n            int nos = system->nos;\n\n            Check_Eigenmode_Parameters(system);\n\n            auto& n_modes = system->ema_parameters->n_modes;\n\n            // vectorfield mode(nos, Vector3{1, 0, 0});\n            vectorfield spins_initial = *system->spins;\n        \n            Log( Log_Level::Info, Log_Sender::EMA, fmt::format(\"Started calculation of {} Eigenmodes \", n_modes ),\n                idx_img, idx_chain );\n\n            // Calculate the Eigenmodes\n            vectorfield gradient(nos);\n            MatrixX hessian(3*nos, 3*nos);\n\n            // The gradient (unprojected)\n            system->hamiltonian->Gradient(spins_initial, gradient);\n            Vectormath::set_c_a(1, gradient, gradient, system->geometry->mask_unpinned);\n\n            // The Hessian (unprojected)\n            system->hamiltonian->Hessian(spins_initial, hessian);\n\n            // Get the eigenspectrum\n            MatrixX hessian_constrained = MatrixX::Zero(2*nos, 2*nos);\n            MatrixX tangent_basis = MatrixX::Zero(3*nos, 2*nos);\n            VectorX eigenvalues;\n            MatrixX eigenvectors;\n            bool successful = Eigenmodes::Hessian_Partial_Spectrum(system->ema_parameters, spins_initial, gradient, hessian, \n                n_modes, tangent_basis, hessian_constrained, eigenvalues, eigenvectors);\n\n            if (successful)\n            {\n                // get every mode and save it to system->modes\n                for (int i=0; i<n_modes; i++)\n                {\n                    // Extract the minimum mode (transform evec_lowest_2N back to 3N)\n                    VectorX evec_3N = tangent_basis * eigenvectors.col(i);\n\n                    // dynamically allocate the system->modes\n                    system->modes[i] = std::shared_ptr<vectorfield>(new vectorfield(nos, Vector3{1,0,0}));\n\n                    // Set the modes\n                    for (int j=0; j<nos; j++)\n                        (*system->modes[i])[j] = {evec_3N[3*j], evec_3N[3*j+1], evec_3N[3*j+2]};\n\n                    // get the eigenvalues\n                    system->eigenvalues[i] = eigenvalues(i);\n                }\n\n                Log( Log_Level::Info, Log_Sender::All, fmt::format(\"Finished calculation of {} Eigenmodes \", n_modes ),\n                    idx_img, idx_chain );\n\n                int ev_print = std::min(n_modes, 100);\n                Log( Log_Level::Info, Log_Sender::EMA, fmt::format(\"Eigenvalues: {}\", \n                    eigenvalues.head( ev_print ).transpose() ), idx_img, idx_chain );\n            }\n            else\n            {\n                //// TODO: What to do then?\n                Log( Log_Level::Warning, Log_Sender::All, \"Something went wrong in eigenmode calculation...\",\n                    idx_img, idx_chain );\n            }\n        }\n        \n        bool Hessian_Full_Spectrum(const std::shared_ptr<Data::Parameters_Method> parameters,\n            const vectorfield & spins, const vectorfield & gradient, const MatrixX & hessian,\n            MatrixX & tangent_basis, MatrixX & hessian_constrained, VectorX & eigenvalues, MatrixX & eigenvectors)\n        {\n            int nos = spins.size();\n\n            // Calculate the final Hessian to use for the minimum mode\n            // TODO: add option to choose different Hessian calculation\n            hessian_constrained = MatrixX::Zero(2*nos, 2*nos);\n            tangent_basis       = MatrixX::Zero(3*nos, 2*nos);\n            Manifoldmath::hessian_bordered(spins, gradient, hessian, tangent_basis, hessian_constrained);\n            // Manifoldmath::hessian_projected(spins, gradient, hessian, tangent_basis, hessian_constrained);\n            // Manifoldmath::hessian_weingarten(spins, gradient, hessian, tangent_basis, hessian_constrained);\n            // Manifoldmath::hessian_spherical(spins, gradient, hessian, tangent_basis, hessian_constrained);\n            // Manifoldmath::hessian_covariant(spins, gradient, hessian, tangent_basis, hessian_constrained);\n            \n            // Create and initialize a Eigen solver. Note: the hessian matrix should be symmetric!\n            Eigen::SelfAdjointEigenSolver<MatrixX> hessian_spectrum(hessian_constrained);\n\n            // Extract real eigenvalues\n            eigenvalues = hessian_spectrum.eigenvalues().real();\n            // Retrieve the real eigenvectors\n            eigenvectors = hessian_spectrum.eigenvectors().real();\n\n            // Return whether the calculation was successful\n            return true;\n        }\n\n        bool Hessian_Partial_Spectrum(const std::shared_ptr<Data::Parameters_Method> parameters,\n            const vectorfield & spins, const vectorfield & gradient, const MatrixX & hessian, int n_modes,\n            MatrixX & tangent_basis, MatrixX & hessian_constrained, VectorX & eigenvalues, MatrixX & eigenvectors)\n        {\n            int nos = spins.size();\n\n            // Restrict number of calculated modes to [1,2N)\n            n_modes = std::max(1, std::min(2*nos-2, n_modes));\n\n            // If we have only one spin, we can only calculate the full spectrum\n            if (n_modes == nos)\n                return Hessian_Full_Spectrum(parameters, spins, gradient, hessian, tangent_basis, hessian_constrained, eigenvalues, eigenvectors);\n\n            // Calculate the final Hessian to use for the minimum mode\n            // TODO: add option to choose different Hessian calculation\n            hessian_constrained = MatrixX::Zero(2*nos, 2*nos);\n            tangent_basis       = MatrixX::Zero(3*nos, 2*nos);\n            Manifoldmath::hessian_bordered(spins, gradient, hessian, tangent_basis, hessian_constrained);\n            // Manifoldmath::hessian_projected(spins, gradient, hessian, tangent_basis, hessian_constrained);\n            // Manifoldmath::hessian_weingarten(spins, gradient, hessian, tangent_basis, hessian_constrained);\n            // Manifoldmath::hessian_spherical(spins, gradient, hessian, tangent_basis, hessian_constrained);\n            // Manifoldmath::hessian_covariant(spins, gradient, hessian, tangent_basis, hessian_constrained);\n            \n            // Remove degrees of freedom of pinned spins\n            #ifdef SPIRIT_ENABLE_PINNING\n                for (int i=0; i<nos; ++i)\n                {\n                    // TODO: pinning is now in Data::Geometry\n                    // if (!parameters->pinning->mask_unpinned[i])\n                    // {\n                    //     // Remove interaction block\n                    //     for (int j=0; j<nos; ++j)\n                    //     {\n                    //         hessian_constrained.block<2,2>(2*i,2*j).setZero();\n                    //         hessian_constrained.block<2,2>(2*j,2*i).setZero();\n                    //     }\n                    //     // Set diagonal matrix entries of pinned spins to a large value\n                    //     hessian_constrained.block<2,2>(2*i,2*i).setZero();\n                    //     hessian_constrained.block<2,2>(2*i,2*i).diagonal().setConstant(nos*1e5);\n                    // }\n                }\n            #endif // SPIRIT_ENABLE_PINNING\n\n            // Create the Spectra Matrix product operation\n            Spectra::DenseSymMatProd<scalar> op(hessian_constrained);\n            // Create and initialize a Spectra solver\n            Spectra::SymEigsSolver< scalar, Spectra::SMALLEST_ALGE, Spectra::DenseSymMatProd<scalar> > hessian_spectrum(&op, n_modes, 2*nos);\n            hessian_spectrum.init();\n\n            // Compute the specified spectrum, sorted by smallest real eigenvalue\n            int nconv = hessian_spectrum.compute(1000, 1e-10, int(Spectra::SMALLEST_ALGE));\n\n            // Extract real eigenvalues\n            eigenvalues = hessian_spectrum.eigenvalues().real();\n\n            // Retrieve the real eigenvectors\n            eigenvectors = hessian_spectrum.eigenvectors().real();\n\n            // Return whether the calculation was successful\n            return (hessian_spectrum.info() == Spectra::SUCCESSFUL) && (nconv > 0);\n        }\n    }\n}\n", "meta": {"hexsha": "4f7e4aee7055af5b9508e19e71fddb4ea5c65dd1", "size": 9601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/engine/Eigenmodes.cpp", "max_stars_repo_name": "ddkn/spirit", "max_stars_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/src/engine/Eigenmodes.cpp", "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/src/engine/Eigenmodes.cpp", "max_forks_repo_name": "ddkn/spirit", "max_forks_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.2955665025, "max_line_length": 146, "alphanum_fraction": 0.5881678992, "num_tokens": 2212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5076050476527866}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/assert.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/not.hpp>\n\n#include \"matrix/comparable.hpp\"\nnamespace hana = boost::hana;\nusing namespace cppcon;\n\n\nint main() {\n    BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n        matrix(row(1, 2)),\n        matrix(row(1, 2))\n    ));\n    BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::equal(\n        matrix(row(1, 2)),\n        matrix(row(1, 5))\n    )));\n\n    BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n        matrix(row(1, 2),\n               row(3, 4)),\n        matrix(row(1, 2),\n               row(3, 4))\n    ));\n    BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::equal(\n        matrix(row(1, 2),\n               row(3, 4)),\n        matrix(row(1, 2),\n               row(0, 4))\n    )));\n    BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::equal(\n        matrix(row(1, 2),\n               row(3, 4)),\n        matrix(row(0, 2),\n               row(3, 4))\n    )));\n\n    BOOST_HANA_CONSTANT_CHECK(hana::not_(hana::equal(\n        matrix(row(1),\n               row(2)),\n        matrix(row(3, 4),\n               row(5, 6))\n    )));\n    BOOST_HANA_CONSTANT_CHECK(hana::not_(hana::equal(\n        matrix(row(1),\n               row(2)),\n        matrix(row(3, 4))\n    )));\n}\n\n", "meta": {"hexsha": "1bdf769d5df0f93331b163932b2324d63bf38023", "size": 1393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/cppcon_2014/comparable.cpp", "max_stars_repo_name": "qicosmos/hana", "max_stars_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-06T05:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T21:48:27.000Z", "max_issues_repo_path": "example/cppcon_2014/comparable.cpp", "max_issues_repo_name": "qicosmos/hana", "max_issues_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "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/cppcon_2014/comparable.cpp", "max_forks_repo_name": "qicosmos/hana", "max_forks_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-06T10:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-06T10:50:17.000Z", "avg_line_length": 24.0172413793, "max_line_length": 78, "alphanum_fraction": 0.544149318, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5075532857694168}}
{"text": "// proj-marker-transform.cpp : Defines the entry point for the console application.\n//\n\n#include \"stdafx.h\"\n\n\n#include <vector>\n#include <iostream>\n#include <time.h>\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <Eigen/Cholesky>\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n\n#include <math/func.h>\n#include <math/matrix.h>\n#include <import.h>\n\n#include <math/SparseBlockSquareMatrix.h>\n\nEigen::VectorXf pcg( const SparseBlockSquareMatrix &A, const Eigen::VectorXf &b, int maxIters, float threshold = 1e-4 ) {\n\tEigen::VectorXf M = A.diagonal();\n\tfor ( int i = 0; i < M.rows(); i++ ) {\n\t\tif ( fabs( M[i] ) > threshold ) {\n\t\t\tM[i] = 1.0f / M[i];\n\t\t} else {\n\t\t\tM[i] = 1.0f;\n\t\t}\n\t}\n\n\tEigen::VectorXf x = Eigen::VectorXf::Zero(A.size());\n\tEigen::VectorXf p = Eigen::VectorXf::Zero(A.size());\n\tEigen::VectorXf r = b; // b - A * x\n\n\tint m_numIters = 0;\n\tclock_t begin = clock();\n\tfor ( int i = 0; i < maxIters; i++ ) {\n\t\tm_numIters++;\n\n\t\tEigen::VectorXf Mr = M.array() * r.array();\n\t\tfloat rMr = r.dot( Mr );\n\t\tif ( rMr < threshold * A.size() ) {\n\t\t//\tbreak;\n\t\t}\n\t\tif ( threshold <= 0 && rMr < 1e-6 ) {\n\t\t\trMr = 0.0f;\n\t\t} else {\n\t\t\trMr = 1.0f / rMr;\n\t\t}\n\t\tp += Mr * rMr;\n\n\t\tEigen::VectorXf Ap = A * p;\n\t\tfloat pAp = p.dot( Ap );\n\t\tif ( threshold <= 0 && pAp < 1e-6 ) {\n\t\t\tpAp = 0.0f;\n\t\t} else {\n\t\t\tpAp = 1.0f / pAp;\n\t\t}\n\t\tx +=  p * pAp;\n\t\tr -= Ap * pAp;\n\n\t\tfloat rme = sqrt( r.dot( r ) / A.size() );\n\t\tif ( rme < 1e-6 ) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tclock_t end = clock();\n\tdouble time_spent = (double)(end - begin) / CLOCKS_PER_SEC;\n\tprintf( \"pcg cpu (ms) : %.3f : %.3f : %d\\n\", time_spent * 1000, time_spent * 1000 / m_numIters, m_numIters );\n\n\treturn x;\n}\n\nfloat icp_point_to_point_svd(\n\tconst std::vector< Eigen::Vector3f > &src_points,\n\tconst std::vector< Eigen::Vector3f > &dst_points,\n\tEigen::Matrix3f &out_r, // rotation\n\tEigen::Vector3f &out_t  // translation\n) {\n\tif ( src_points.empty() ) {\n\t\tout_r.setIdentity();\n\t\tout_t.setZero();\n\t\treturn 0.0f;\n\t}\n\t\t\n\t// E(src)\n\tEigen::Vector3f src_mean = mean( src_points );\n\n\t// E(dst)\n\tEigen::Vector3f dst_mean = mean( dst_points );\n\n\t// A = Sum( ( src - E(src) ) * ( dst - E(dst) )' )\n\tEigen::Matrix3f A = Eigen::Matrix3f::Identity() * 1e-6f;\n\tfor ( int i = 0; i < src_points.size(); i++ ) {\n\t\tA += ( src_points[i] - src_mean ) * ( dst_points[i] - dst_mean ).transpose();\n\t}\n\n\t// SVD : A = U * D * V'\n\tEigen::JacobiSVD<Eigen::MatrixXf> svd(A, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n\t// R = V * U'\n\tout_r = svd.matrixV() * svd.matrixU().transpose();\n\n\t// T = E(dst) - R * E(src)\n\tout_t = dst_mean - out_r * src_mean;\n\n\t// rme\n\treturn rme( src_points, dst_points, out_r, out_t );\n}\n\nvoid init_affine_transforms( int size, Eigen::VectorXf &x, const Eigen::Matrix3f &rot, const std::vector< Eigen::Vector3f > &src, const std::vector< Eigen::Vector3f > &dst ) {\n\tfor ( int i = 0; i < size; i++ ) {\n\t\tx.block( 12 * i + 3 * 0, 0, 3, 1 ) = rot.col(0); Eigen::Vector3f( 1, 0, 0 );\n\t\tx.block( 12 * i + 3 * 1, 0, 3, 1 ) = rot.col(1); Eigen::Vector3f( 0, 1, 0 );\n\t\tx.block( 12 * i + 3 * 2, 0, 3, 1 ) = rot.col(2); Eigen::Vector3f( 0, 0, 1 );\n\t\tx.block( 12 * i + 3 * 3, 0, 3, 1 ) = dst[i] - src[i];\n\t}\n}\n\nvoid EvalRigidTerm( int size, Eigen::MatrixXf &JtJ, Eigen::VectorXf &Jtr, Eigen::VectorXf &x, std::vector<Eigen::Vector3f> &src, std::vector<Eigen::Vector3f> &dst, float &E ) {\t\n\t// E-rigid\n\tfloat w_rigid = 1.0f;\n\t{\n\t\tfor ( int i = 0; i < size; i++ ) {\n\t\t\tEigen::Vector3f M[4];\n\t\t\tM[0] = x.block( i * 12 + 0 * 3, 0, 3, 1 );\n\t\t\tM[1] = x.block( i * 12 + 1 * 3, 0, 3, 1 );\n\t\t\tM[2] = x.block( i * 12 + 2 * 3, 0, 3, 1 );\n\t\t\tM[3] = x.block( i * 12 + 3 * 3, 0, 3, 1 );\n\n\t\t\t// ck dot ck - 1\n\t\t\tfor ( int k = 0; k < 3; k++ ) {\n\t\t\t\tfloat r = M[k].dot( M[k] ) - 1;\n\t\t\t\n\t\t\t\tEigen::VectorXf J = Eigen::VectorXf::Zero( 12 );\n\t\t\t\tJ.block( k * 3, 0, 3, 1 ) = M[k] + M[k];\n\n\t\t\t\tE += r * r * w_rigid;\n\t\t\t\tJtJ.block( i * 12, i * 12, 12, 12 ) += J * J.transpose() * w_rigid; // block (i, i)\n\t\t\t\tJtr.block( i * 12, 0, 12, 1 ) += J * r * w_rigid; // block ( i )\n\t\t\t}\n\n\t\t\t// ck dot cj\n\t\t\tfor ( int k = 0; k < 3; k++ ) {\n\t\t\t\tint j = ( k + 1 ) % 3;\n\n\t\t\t\tfloat r = M[k].dot( M[j] );\n\n\t\t\t\tE += r * r * w_rigid;\n\n\t\t\t\tEigen::VectorXf J = Eigen::VectorXf::Zero( 12 );\n\n\t\t\t\tJ.block( k * 3, 0, 3, 1 ) = M[j];\n\t\t\t\tJ.block( j * 3, 0, 3, 1 ) = M[k];\n\n\t\t\t\tJtJ.block( i * 12, i * 12, 12, 12 ) += J * J.transpose() * w_rigid; // block (i, i)\n\t\t\t\tJtr.block( i * 12, 0, 12, 1 ) += J * r * w_rigid; // block ( i )\n\t\t\t}\n\t\t}\n\t}\n\tprintf( \"E-rigid : %f\\n\", E );\n}\n\nvoid EvalSmoothTerm( int size, Eigen::MatrixXf &JtJ, Eigen::VectorXf &Jtr, Eigen::VectorXf &x, std::vector<Eigen::Vector3f> &src, std::vector<Eigen::Vector3f> &dst, float &out_E, const std::vector<std::vector<int>> &links ) {\t\n\t// E-smooth\n\tfloat E = 0;\n\tfloat w_smooth = 1.0f;\n\t{\n\t\tfor ( int i = 0; i < size; i++ ) {\n\t\tfor ( int k = 0; k < links[i].size(); k++ ) {\n\t\t\tint j = links[i][k];\n\n\t\t\tEigen::Vector3f Mi[4], Mj[4];\n\t\t\tMi[0] = x.block( i * 12 + 0 * 3, 0, 3, 1 );\n\t\t\tMi[1] = x.block( i * 12 + 1 * 3, 0, 3, 1 );\n\t\t\tMi[2] = x.block( i * 12 + 2 * 3, 0, 3, 1 );\n\t\t\tMi[3] = x.block( i * 12 + 3 * 3, 0, 3, 1 );\n\n\t\t\tMj[0] = x.block( j * 12 + 0 * 3, 0, 3, 1 );\n\t\t\tMj[1] = x.block( j * 12 + 1 * 3, 0, 3, 1 );\n\t\t\tMj[2] = x.block( j * 12 + 2 * 3, 0, 3, 1 );\n\t\t\tMj[3] = x.block( j * 12 + 3 * 3, 0, 3, 1 );\n\n\t\t\t// Ri * ( gj - gi ) - ( gj - gi ) - ( tj - ti )\n\n\t\t\tEigen::Vector3f dg = src[j] - src[i];\n\n\t\t\tEigen::Vector3f dt = Mj[3] - Mi[3];\n\n\t\t\tEigen::Vector3f r = ( dg[0] * Mi[0] + dg[1] * Mi[1] + dg[2] * Mi[2] ) - dg - dt;\n\n\t\t\tE += r.dot( r ) * w_smooth;\n\n\t\t\tEigen::MatrixXf Ji = Eigen::MatrixXf::Zero( 3, 12 );\n\t\t\tJi( 0, 0 + 3 * 0 ) = dg[0]; Ji( 0, 0 + 3 * 1 ) = dg[1]; Ji( 0, 0 + 3 * 2 ) = dg[2];\n\t\t\tJi( 1, 1 + 3 * 0 ) = dg[0];\tJi( 1, 1 + 3 * 1 ) = dg[1];\tJi( 1, 1 + 3 * 2 ) = dg[2];\n\t\t\tJi( 2, 2 + 3 * 0 ) = dg[0];\tJi( 2, 2 + 3 * 1 ) = dg[1];\tJi( 2, 2 + 3 * 2 ) = dg[2];\n\n\t\t//\tstd::cout << Ji <<std::endl;\n\n\t\t\tJtJ.block( i * 12, i * 12, 12, 12 ) += Ji.transpose() * Ji * w_smooth;\n\t\t\tJtr.block( i * 12, 0, 12, 1 ) += Ji.transpose() * r * w_smooth;\n\t\t}}\n\t}\n\tprintf( \"E-smooth : %f\\n\", E );\n\tout_E += E;\n}\nbool read_text_file( const char *path, std::vector<std::vector<Eigen::Vector3f>> &poses ) {\n\tFILE *fp = fopen( path, \"r\" );\n\tif ( !fp ) {\n\t\tprintf( \"failed to read text file: %s\\n\", path );\n\t\treturn false;\n\t}\n\n\tint frame = 0;\n\twhile( fscanf( fp, \"%d\", &frame ) == 1 ) {\n\t\tframe -= 1;\n\t\tif ( frame != poses.size() ) {\n\t\t\tbreak;\n\t\t}\n\t\tprintf( \"read %d\\n\", frame );\n\t\t\n\t\tint subFrame = 0;\n\t\tfscanf( fp, \"%d\", &subFrame );\n\n\t\tposes.push_back( std::vector<Eigen::Vector3f>( 41 ) );\n\t\tfor ( int i = 0; i < 41; i++ ) {\n\t\t\tfloat x, y, z;\n\t\t\tfscanf( fp, \"%f\", &x );\n\t\t\tfscanf( fp, \"%f\", &y );\n\t\t\tfscanf( fp, \"%f\", &z );\n\t\t//\tprintf( \"%f %f %f\\n\", x, y, z);\n\t\t\tposes[frame][i][0] = x * 0.001f;\n\t\t\tposes[frame][i][1] = y * 0.001f;\n\t\t\tposes[frame][i][2] = z * 0.001f;\n\t\t}\n\t}\n\n\tfclose( fp );\n\treturn true;\n}\n\nvoid test_gen_data( void ) {\n\tint size = 8;\n\t\n\tstd::vector<Eigen::Vector3f> src( size ), dst( size );\n\t\n\t// gen transform\n\tEigen::Vector3f euler;\n\teuler << 20, 50, -45;\n\tEigen::Matrix3f rot = euler_to_mat( radians( euler ) );\n\tEigen::Vector3f t;\n\tt << 30, 50, -10;\n\tstd::cout << \"Truth\" << std::endl;\n\tstd::cout << rot << std::endl;\n\tstd::cout << t << std::endl;\n\n\t// gen data\n\tfor ( int i = 0; i < size; i++ ) {\n\t\tEigen::Vector3f euler;\n\t\teuler << 20, 50, -45;\n\t\teuler[1] += i * 5.0f;\n\t\tEigen::Matrix3f rot = euler_to_mat( radians( euler ) );\n\n\t\tEigen::Vector3f t;\n\t\tt << 30, 50, -10;\n\n\t\tsrc[i] = Eigen::Vector3f::Random();\n\t\tsrc[i][0] = fmod( src[i][0], 256.0f );\n\t\tsrc[i][1] = fmod( src[i][1], 256.0f );\n\t\tsrc[i][2] = fmod( src[i][2], 256.0f );\n\t\tdst[i] = rot * src[i] + t;\n\t\t//std::cout << \"i << std::endl;\n\t\t//std::cout << src[i] << std::endl;\n\t\t//std::cout << dst[i] << std::endl;\n\t}\n\t\t\n\t// rigid transform\n\tEigen::Matrix3f out_rot = Eigen::Matrix3f::Identity();\n\tEigen::Vector3f out_t = Eigen::Vector3f::Zero();;\n\t{\n\t\tfloat rme = icp_point_to_point_svd( src, dst, out_rot, out_t );\n\n\t\tstd::cout << \"Result\" << std::endl;\n\t\tstd::cout << out_rot << std::endl;\n\t\tstd::cout << out_t << std::endl;\n\t\tstd::cout << \"rme : \" << rme << std::endl;\n\t\tstd::cout << std::endl;\n\t}\n\n\tEigen::MatrixXf JtJ = Eigen::MatrixXf::Identity( 12 * size, 12 * size ) * 1e-6f;\n\tEigen::VectorXf Jtr = Eigen::VectorXf::Zero( 12 * size );\n\tEigen::VectorXf x( 12 * size );\n\tfloat E = 0.0f;\n\n\tinit_affine_transforms( size, x, out_rot, src, dst );\n\n\tfor ( int i = 0; i < 5; i++ ) {\n\t\tJtJ = Eigen::MatrixXf::Identity( 12 * size, 12 * size ) * 1e-6f;\n\t\tJtr = Eigen::VectorXf::Zero( 12 * size );\n\t\tE = 0.0f;\n\t\n\t//\tEvalLinearSystem( size, JtJ, Jtr, x, src, dst, E );\n\t\t//std::cout << Jtr;\n\t\tx -= JtJ.fullPivHouseholderQr().solve( Jtr );\n\t}\n}\n\nclass Timer {\npublic :\n\tclock_t begin, end;\n\n\tvoid Start( void ) {\n\t\tbegin = clock();\n\t}\n\n\tvoid Pause( void ) {\n\t\tend = clock();\n\t}\n\n\tvoid Print( const char *id ) {\n\t\tdouble time_spent = (double)(end - begin) / CLOCKS_PER_SEC;\n\t\tprintf( \"time : %s : %f\\n\", id, time_spent );\n\t}\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tstd::vector<std::vector<Eigen::Vector3f>> poses;\n\t\t\n\tread_text_file( \"New Session 0103.csv\", poses );\n\t\n\t// rigid transform\n\t\n\tTimer timer;\t\n\t\n\tEigen::Matrix3f out_rot = Eigen::Matrix3f::Identity();\n\tEigen::Vector3f out_t = Eigen::Vector3f::Zero();\n\t{\n\t\ttimer.Start();\n\t\tfloat rme = icp_point_to_point_svd( poses[10], poses[600], out_rot, out_t );\n\t\ttimer.Pause();\n\t\ttimer.Print( \"ICP\" );\n\n\t\tstd::cout << \"Result\" << std::endl;\n\t\tstd::cout << out_rot << std::endl;\n\t\tstd::cout << out_t << std::endl;\n\t\tstd::cout << \"rme : \" << rme << std::endl;\n\t\tstd::cout << std::endl;\n\t}\n\n\tint size = poses[0].size();\n\n\tEigen::MatrixXf JtJ = Eigen::MatrixXf::Identity( 12 * size, 12 * size ) * 1e-6f;\n\tEigen::VectorXf Jtr = Eigen::VectorXf::Zero( 12 * size );\n\tEigen::VectorXf x( 12 * size );\n\tfloat E = 0.0f;\n\n\tinit_affine_transforms( size, x, out_rot, poses[0], poses[600] );\n\n\tstd::vector<std::vector<int>> links( poses[0].size() );\n\tfor ( int i = 0; i < poses[0].size(); i++ ) {\n\t\tfor ( int j = i + 1; j < poses[0].size(); j++ ) {\n\t\t\tif ( ( poses[0][i] - poses[0][j] ).norm() < 0.25f ) {\n\t\t\t\tlinks[i].push_back( j );\n\t\t\t\tlinks[j].push_back( i );\n\t\t\t}\n\t\t}\n\t}\n\n\tfor ( int i = 0; i < links.size(); i++ ) {\n\t\tprintf( \"%d : %d\\n\", i, links[i].size() );\n\t}\n\n\tfor ( int i = 0; i < 7; i++ ) {\n\t\tJtJ = Eigen::MatrixXf::Identity( 12 * size, 12 * size ) * 1e-3f;\n\t\tJtr = Eigen::VectorXf::Zero( 12 * size );\n\t\tE = 0.0f;\n\n\t\ttimer.Start();\n\t\tEvalRigidTerm( size, JtJ, Jtr, x, poses[0], poses[300], E );\n\t\tEvalSmoothTerm( size, JtJ, Jtr, x, poses[0], poses[300], E, links );\n\t\ttimer.Pause();\n\t\ttimer.Print( \"Jacobian\" );\n\n\t\t//std::cout << Jtr;\n\t\ttimer.Start();\n\t\tSparseBlockSquareMatrix B;\n\t\tB.createFromDenseMatrix( JtJ, 12 );\n\t\n\t\tx -= pcg( B, Jtr, 100, 1e-6 );\n\n\t\t//x -= JtJ.fullPivHouseholderQr().solve( Jtr );\n\t\ttimer.Pause();\n\t\ttimer.Print( \"Solve\" );\n\t}\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "b0ce535ad7d8bc51e56ed5b6575f10b452421d4f", "size": 10856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moca/proj-marker-transform/proj-marker-transform/proj-marker-transform.cpp", "max_stars_repo_name": "Edwinzero/Fusion", "max_stars_repo_head_hexsha": "6b71ee807bc33c6d79546ce2dbca47229d663c1d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-02-21T04:04:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-16T06:50:34.000Z", "max_issues_repo_path": "moca/proj-marker-transform/proj-marker-transform/proj-marker-transform.cpp", "max_issues_repo_name": "icg-moca/MOCA", "max_issues_repo_head_hexsha": "61dbb536529bb1dfd6b1972ce3bdcdaf98655acd", "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": "moca/proj-marker-transform/proj-marker-transform/proj-marker-transform.cpp", "max_forks_repo_name": "icg-moca/MOCA", "max_forks_repo_head_hexsha": "61dbb536529bb1dfd6b1972ce3bdcdaf98655acd", "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.8712871287, "max_line_length": 226, "alphanum_fraction": 0.5403463522, "num_tokens": 4484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5075532808130189}}
{"text": "//  (C) Copyright Eric Niebler, Olivier Gygi 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/weighted_moment.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    accumulator_set<double, stats<tag::weighted_moment<2> >, double> acc2;\n    accumulator_set<double, stats<tag::weighted_moment<7> >, double> acc7;\n\n    acc2(2.1, weight = 0.7);\n    acc2(2.7, weight = 1.4);\n    acc2(1.8, weight = 0.9);\n\n    acc7(2.1, weight = 0.7);\n    acc7(2.7, weight = 1.4);\n    acc7(1.8, weight = 0.9);\n\n    BOOST_CHECK_CLOSE(5.403, accumulators::weighted_moment<2>(acc2), 1e-5);\n    BOOST_CHECK_CLOSE(548.54182, accumulators::weighted_moment<7>(acc7), 1e-5);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"weighted_moment test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n\n", "meta": {"hexsha": "4aec80d3ecff1cc6362c64c8115899722b1333fd", "size": 1472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/accumulators/test/weighted_moment.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/accumulators/test/weighted_moment.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/accumulators/test/weighted_moment.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": 30.6666666667, "max_line_length": 79, "alphanum_fraction": 0.6385869565, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5075532659438249}}
{"text": "#ifndef _mitkCLUtil_HXX\n#define _mitkCLUtil_HXX\n\n#include <mitkCLUtil.h>\n\n#include <mitkImageAccessByItk.h>\n\n\n\n#include <Eigen/Dense>\n#include <itkImage.h>\n\n// itk includes\n#include <itkCheckerBoardImageFilter.h>\n#include <itkShapedNeighborhoodIterator.h>\n// Morphologic Operations\n#include <itkBinaryBallStructuringElement.h>\n#include <itkBinaryDilateImageFilter.h>\n#include <itkBinaryErodeImageFilter.h>\n#include <itkBinaryFillholeImageFilter.h>\n#include <itkBinaryMorphologicalClosingImageFilter.h>\n#include <itkGrayscaleErodeImageFilter.h>\n#include <itkGrayscaleDilateImageFilter.h>\n#include <itkGrayscaleFillholeImageFilter.h>\n\n// Image Filter\n#include <itkDiscreteGaussianImageFilter.h>\n\nvoid mitk::CLUtil::ProbabilityMap(const mitk::Image::Pointer & image , double mean, double stddev, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_3(image, mitk::CLUtil::itkProbabilityMap, 3, mean, stddev, outimage);\n}\n\nvoid mitk::CLUtil::ErodeGrayscale(mitk::Image::Pointer & image , unsigned int radius, mitk::CLUtil::MorphologicalDimensions d, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_3(image, mitk::CLUtil::itkErodeGrayscale, 3, outimage, radius, d);\n}\n\nvoid mitk::CLUtil::DilateGrayscale(mitk::Image::Pointer & image, unsigned int radius, mitk::CLUtil::MorphologicalDimensions d, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_3(image, mitk::CLUtil::itkDilateGrayscale, 3, outimage, radius, d);\n}\n\nvoid mitk::CLUtil::FillHoleGrayscale(mitk::Image::Pointer & image, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_1(image, mitk::CLUtil::itkFillHoleGrayscale, 3, outimage);\n}\n\nvoid mitk::CLUtil::InsertLabel(mitk::Image::Pointer & image, mitk::Image::Pointer & maskImage, unsigned int label)\n{\n  AccessByItk_2(image, mitk::CLUtil::itkInsertLabel, maskImage, label);\n}\n\nvoid mitk::CLUtil::GrabLabel(mitk::Image::Pointer & image, mitk::Image::Pointer & outimage, unsigned int label)\n{\n  AccessFixedDimensionByItk_2(image, mitk::CLUtil::itkGrabLabel, 3, outimage, label);\n}\n\nvoid mitk::CLUtil::ConnectedComponentsImage(mitk::Image::Pointer & image, mitk::Image::Pointer& mask, mitk::Image::Pointer &outimage, unsigned int& num_components)\n{\n  AccessFixedDimensionByItk_3(image, mitk::CLUtil::itkConnectedComponentsImage,3, mask, outimage, num_components);\n}\n\nvoid mitk::CLUtil::MergeLabels(mitk::Image::Pointer & img, const std::map<unsigned int, unsigned int> & map)\n{\n  AccessByItk_1(img, mitk::CLUtil::itkMergeLabels, map);\n}\n\nvoid mitk::CLUtil::CountVoxel(mitk::Image::Pointer image, std::map<unsigned int, unsigned int> & map)\n{\n  AccessByItk_1(image, mitk::CLUtil::itkCountVoxel, map);\n}\n\nvoid mitk::CLUtil::CountVoxel(mitk::Image::Pointer image, unsigned int label, unsigned int & count)\n{\n  AccessByItk_2(image, mitk::CLUtil::itkCountVoxel, label, count);\n}\n\nvoid mitk::CLUtil::CountVoxel(mitk::Image::Pointer image, unsigned int & count)\n{\n  AccessByItk_1(image, mitk::CLUtil::itkCountVoxel, count);\n}\n\nvoid mitk::CLUtil::CreateCheckerboardMask(mitk::Image::Pointer image, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_1(image, mitk::CLUtil::itkCreateCheckerboardMask,3, outimage);\n}\n\nvoid mitk::CLUtil::LogicalAndImages(const mitk::Image::Pointer & image1, const mitk::Image::Pointer & image2, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_2(image1,itkLogicalAndImages, 3, image2, outimage);\n\n}\n\nvoid mitk::CLUtil::InterpolateCheckerboardPrediction(mitk::Image::Pointer checkerboard_prediction, mitk::Image::Pointer & checkerboard_mask, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_2(checkerboard_prediction, mitk::CLUtil::itkInterpolateCheckerboardPrediction,3, checkerboard_mask, outimage);\n}\n\nvoid mitk::CLUtil::GaussianFilter(mitk::Image::Pointer image, mitk::Image::Pointer & smoothed ,double sigma)\n{\n  AccessFixedDimensionByItk_2(image, mitk::CLUtil::itkGaussianFilter,3, smoothed, sigma);\n}\n\n\nvoid mitk::CLUtil::DilateBinary(mitk::Image::Pointer & sourceImage, mitk::Image::Pointer& resultImage, int factor , MorphologicalDimensions d)\n{\n  AccessFixedDimensionByItk_3(sourceImage, mitk::CLUtil::itkDilateBinary, 3, resultImage, factor, d);\n}\n\n\nvoid mitk::CLUtil::ErodeBinary(mitk::Image::Pointer & sourceImage, mitk::Image::Pointer& resultImage, int factor, MorphologicalDimensions d)\n{\n  AccessFixedDimensionByItk_3(sourceImage, mitk::CLUtil::itkErodeBinary, 3, resultImage, factor, d);\n}\n\n\nvoid mitk::CLUtil::ClosingBinary(mitk::Image::Pointer & sourceImage, mitk::Image::Pointer& resultImage, int factor, MorphologicalDimensions d)\n{\n  AccessFixedDimensionByItk_3(sourceImage, mitk::CLUtil::itkClosingBinary, 3, resultImage, factor, d);\n}\n\ntemplate<typename TImageType>\nvoid mitk::CLUtil::itkProbabilityMap(const TImageType * sourceImage, double mean, double std_dev, mitk::Image::Pointer& resultImage)\n{\n  itk::Image<double, 3>::Pointer itk_img = itk::Image<double, 3>::New();\n  itk_img->SetRegions(sourceImage->GetLargestPossibleRegion());\n  itk_img->SetOrigin(sourceImage->GetOrigin());\n  itk_img->SetSpacing(sourceImage->GetSpacing());\n  itk_img->SetDirection(sourceImage->GetDirection());\n  itk_img->Allocate();\n\n\n  itk::ImageRegionConstIterator<TImageType> it(sourceImage,sourceImage->GetLargestPossibleRegion());\n  itk::ImageRegionIterator<itk::Image<double, 3> > outit(itk_img,itk_img->GetLargestPossibleRegion());\n\n  while(!it.IsAtEnd())\n  {\n    double x = it.Value();\n\n    double prob = (1.0/(std_dev*std::sqrt(2.0*M_PI))) * std::exp(-(((x-mean)*(x-mean))/(2.0*std_dev*std_dev)));\n    outit.Set(prob);\n    ++it;\n    ++outit;\n  }\n\n  mitk::CastToMitkImage(itk_img, resultImage);\n}\n\ntemplate< typename TImageType >\nvoid mitk::CLUtil::itkInterpolateCheckerboardPrediction(TImageType * checkerboard_prediction, Image::Pointer &checkerboard_mask, mitk::Image::Pointer & outimage)\n{\n  typename TImageType::Pointer itk_checkerboard_mask;\n  mitk::CastToItkImage(checkerboard_mask,itk_checkerboard_mask);\n\n  typename TImageType::Pointer itk_outimage = TImageType::New();\n  itk_outimage->SetRegions(checkerboard_prediction->GetLargestPossibleRegion());\n  itk_outimage->SetDirection(checkerboard_prediction->GetDirection());\n  itk_outimage->SetOrigin(checkerboard_prediction->GetOrigin());\n  itk_outimage->SetSpacing(checkerboard_prediction->GetSpacing());\n  itk_outimage->Allocate();\n  itk_outimage->FillBuffer(0);\n\n  //typedef typename itk::ShapedNeighborhoodIterator<TImageType>::SizeType SizeType;\n  typedef itk::Size<3> SizeType;\n  SizeType size;\n  size.Fill(1);\n  itk::ShapedNeighborhoodIterator<TImageType> iit(size,checkerboard_prediction,checkerboard_prediction->GetLargestPossibleRegion());\n  itk::ShapedNeighborhoodIterator<TImageType> mit(size,itk_checkerboard_mask,itk_checkerboard_mask->GetLargestPossibleRegion());\n  itk::ImageRegionIterator<TImageType> oit(itk_outimage,itk_outimage->GetLargestPossibleRegion());\n\n  typedef typename itk::ShapedNeighborhoodIterator<TImageType>::OffsetType OffsetType;\n  OffsetType offset;\n  offset.Fill(0);\n  offset[0] = 1;       // {1,0,0}\n  iit.ActivateOffset(offset);\n  mit.ActivateOffset(offset);\n  offset[0] = -1;      // {-1,0,0}\n  iit.ActivateOffset(offset);\n  mit.ActivateOffset(offset);\n  offset[0] = 0; offset[1] = 1; //{0,1,0}\n  iit.ActivateOffset(offset);\n  mit.ActivateOffset(offset);\n  offset[1] = -1;      //{0,-1,0}\n  iit.ActivateOffset(offset);\n  mit.ActivateOffset(offset);\n\n  //    iit.ActivateOffset({{0,0,1}});\n  //    iit.ActivateOffset({{0,0,-1}});\n  //    mit.ActivateOffset({{0,0,1}});\n  //    mit.ActivateOffset({{0,0,-1}});\n\n  while(!iit.IsAtEnd())\n  {\n    if(mit.GetCenterPixel() == 0)\n    {\n      typename TImageType::PixelType mean = 0;\n      for (auto i = iit.Begin(); ! i.IsAtEnd(); i++)\n      { mean += i.Get(); }\n\n\n      //std::sort(list.begin(),list.end(),[](const typename TImageType::PixelType x,const typename TImageType::PixelType y){return x<=y;});\n\n      oit.Set((mean+0.5)/6.0);\n    }\n    else\n    {\n      oit.Set(iit.GetCenterPixel());\n    }\n    ++iit;\n    ++mit;\n    ++oit;\n  }\n\n  mitk::CastToMitkImage(itk_outimage,outimage);\n}\n\ntemplate< typename TImageType >\nvoid mitk::CLUtil::itkCreateCheckerboardMask(TImageType * image, mitk::Image::Pointer & outimage)\n{\n  typename TImageType::Pointer zeroimg = TImageType::New();\n  zeroimg->SetRegions(image->GetLargestPossibleRegion());\n  zeroimg->SetDirection(image->GetDirection());\n  zeroimg->SetOrigin(image->GetOrigin());\n  zeroimg->SetSpacing(image->GetSpacing());\n\n  zeroimg->Allocate();\n  zeroimg->FillBuffer(0);\n\n  typedef itk::CheckerBoardImageFilter<TImageType> FilterType;\n  typename FilterType::Pointer filter = FilterType::New();\n  filter->SetInput1(image);\n  filter->SetInput2(zeroimg);\n  typename FilterType::PatternArrayType pattern;\n  pattern.SetElement(0,(image->GetLargestPossibleRegion().GetSize()[0]));\n  pattern.SetElement(1,(image->GetLargestPossibleRegion().GetSize()[1]));\n  pattern.SetElement(2,(image->GetLargestPossibleRegion().GetSize()[2]));\n  filter->SetCheckerPattern(pattern);\n\n  filter->Update();\n  mitk::CastToMitkImage(filter->GetOutput(), outimage);\n}\n\n\ntemplate <class TImageType>\nvoid mitk::CLUtil::itkSumVoxelForLabel(TImageType* image, const mitk::Image::Pointer & source , typename TImageType::PixelType label, double & val )\n{\n  itk::Image<double,3>::Pointer itk_source;\n  mitk::CastToItkImage(source,itk_source);\n\n  itk::ImageRegionConstIterator<TImageType> inputIter(image, image->GetLargestPossibleRegion());\n  itk::ImageRegionConstIterator< itk::Image<double,3> > sourceIter(itk_source, itk_source->GetLargestPossibleRegion());\n  while(!inputIter.IsAtEnd())\n  {\n    if(inputIter.Value() == label) val += sourceIter.Value();\n    ++inputIter;\n    ++sourceIter;\n  }\n}\n\ntemplate <class TImageType>\nvoid mitk::CLUtil::itkSqSumVoxelForLabel(TImageType* image, const mitk::Image::Pointer & source, typename TImageType::PixelType label, double & val )\n{\n  itk::Image<double,3>::Pointer itk_source;\n  mitk::CastToItkImage(source,itk_source);\n\n  itk::ImageRegionConstIterator<TImageType> inputIter(image, image->GetLargestPossibleRegion());\n  itk::ImageRegionConstIterator< itk::Image<double,3> > sourceIter(itk_source, itk_source->GetLargestPossibleRegion());\n  while(!inputIter.IsAtEnd())\n  {\n    if(inputIter.Value() == label) val += sourceIter.Value() * sourceIter.Value();\n    ++inputIter;\n    ++sourceIter;\n  }\n}\n\ntemplate<typename TStructuringElement>\nvoid mitk::CLUtil::itkFitStructuringElement(TStructuringElement & se, MorphologicalDimensions d, int factor)\n{\n  typename TStructuringElement::SizeType size;\n  size.Fill(factor);\n  switch(d)\n  {\n  case(All):\n  case(Axial):\n    size.SetElement(2,0);\n    break;\n  case(Sagital):\n    size.SetElement(0,0);\n    break;\n  case(Coronal):\n    size.SetElement(1,0);\n    break;\n  }\n  se.SetRadius(size);\n  se.CreateStructuringElement();\n}\n\ntemplate<typename TImageType>\nvoid mitk::CLUtil::itkClosingBinary(TImageType * sourceImage, mitk::Image::Pointer& resultImage, int factor, MorphologicalDimensions d)\n{\n  typedef itk::BinaryBallStructuringElement<typename TImageType::PixelType, 3> BallType;\n  typedef itk::BinaryMorphologicalClosingImageFilter<TImageType, TImageType, BallType> FilterType;\n\n  BallType strElem;\n  itkFitStructuringElement(strElem,d,factor);\n\n  typename FilterType::Pointer erodeFilter = FilterType::New();\n  erodeFilter->SetKernel(strElem);\n  erodeFilter->SetInput(sourceImage);\n  erodeFilter->SetForegroundValue(1);\n  erodeFilter->Update();\n\n  mitk::CastToMitkImage(erodeFilter->GetOutput(), resultImage);\n\n}\n\ntemplate<typename TImageType>\nvoid mitk::CLUtil::itkDilateBinary(TImageType * sourceImage, mitk::Image::Pointer& resultImage, int factor, MorphologicalDimensions d)\n{\n  typedef itk::BinaryBallStructuringElement<typename TImageType::PixelType, 3> BallType;\n  typedef typename itk::BinaryDilateImageFilter<TImageType, TImageType, BallType> BallDilateFilterType;\n\n  BallType strElem;\n  itkFitStructuringElement(strElem,d,factor);\n\n  typename BallDilateFilterType::Pointer erodeFilter = BallDilateFilterType::New();\n  erodeFilter->SetKernel(strElem);\n  erodeFilter->SetInput(sourceImage);\n  erodeFilter->SetDilateValue(1);\n  erodeFilter->Update();\n\n  mitk::CastToMitkImage(erodeFilter->GetOutput(), resultImage);\n\n}\n\ntemplate<typename TImageType>\nvoid mitk::CLUtil::itkErodeBinary(TImageType * sourceImage, mitk::Image::Pointer& resultImage, int factor, MorphologicalDimensions d)\n{\n  typedef itk::BinaryBallStructuringElement<typename TImageType::PixelType, 3> BallType;\n  typedef typename itk::BinaryErodeImageFilter<TImageType, TImageType, BallType> BallErodeFilterType;\n\n  BallType strElem;\n  itkFitStructuringElement(strElem,d,factor);\n\n\n  typename BallErodeFilterType::Pointer erodeFilter = BallErodeFilterType::New();\n  erodeFilter->SetKernel(strElem);\n  erodeFilter->SetInput(sourceImage);\n  erodeFilter->SetErodeValue(1);\n//  erodeFilter->UpdateLargestPossibleRegion();\n  erodeFilter->Update();\n\n  mitk::CastToMitkImage(erodeFilter->GetOutput(), resultImage);\n\n}\n\n///\n/// \\brief itkFillHolesBinary\n/// \\param sourceImage\n/// \\param resultImage\n///\ntemplate<typename TPixel, unsigned int VDimension>\nvoid mitk::CLUtil::itkFillHolesBinary(itk::Image<TPixel, VDimension>* sourceImage, mitk::Image::Pointer& resultImage)\n{\n  typedef itk::Image<TPixel, VDimension> ImageType;\n  typedef typename itk::BinaryFillholeImageFilter<ImageType> FillHoleFilterType;\n\n  typename FillHoleFilterType::Pointer fillHoleFilter = FillHoleFilterType::New();\n  fillHoleFilter->SetInput(sourceImage);\n  fillHoleFilter->SetForegroundValue(1);\n  fillHoleFilter->Update();\n\n  mitk::CastToMitkImage(fillHoleFilter->GetOutput(), resultImage);\n}\n\n///\n/// \\brief itkLogicalAndImages\n/// \\param image1 keep the values of image 1\n/// \\param image2\n///\ntemplate<typename TImageType>\nvoid mitk::CLUtil::itkLogicalAndImages(const TImageType * image1, const mitk::Image::Pointer & image2, mitk::Image::Pointer & outimage)\n{\n\n  typename TImageType::Pointer itk_outimage = TImageType::New();\n  itk_outimage->SetRegions(image1->GetLargestPossibleRegion());\n  itk_outimage->SetDirection(image1->GetDirection());\n  itk_outimage->SetOrigin(image1->GetOrigin());\n  itk_outimage->SetSpacing(image1->GetSpacing());\n\n  itk_outimage->Allocate();\n  itk_outimage->FillBuffer(0);\n\n  typename TImageType::Pointer itk_image2;\n  mitk::CastToItkImage(image2,itk_image2);\n\n  itk::ImageRegionConstIterator<TImageType> it1(image1, image1->GetLargestPossibleRegion());\n  itk::ImageRegionConstIterator<TImageType> it2(itk_image2, itk_image2->GetLargestPossibleRegion());\n  itk::ImageRegionIterator<TImageType> oit(itk_outimage,itk_outimage->GetLargestPossibleRegion());\n\n  while(!it1.IsAtEnd())\n  {\n    if(it1.Value() == 0 || it2.Value() == 0)\n    {\n      oit.Set(0);\n    }else\n      oit.Set(it1.Value());\n    ++it1;\n    ++it2;\n    ++oit;\n  }\n\n  mitk::CastToMitkImage(itk_outimage, outimage);\n}\n\n///\n/// \\brief GaussianFilter\n/// \\param image\n/// \\param smoothed\n/// \\param sigma\n///\ntemplate<class TImageType>\nvoid mitk::CLUtil::itkGaussianFilter(TImageType * image, mitk::Image::Pointer & smoothed ,double sigma)\n{\n  typedef itk::DiscreteGaussianImageFilter<TImageType,TImageType> FilterType;\n  typename FilterType::Pointer filter = FilterType::New();\n  filter->SetInput(image);\n  filter->SetVariance(sigma);\n  filter->Update();\n\n  mitk::CastToMitkImage(filter->GetOutput(),smoothed);\n}\n\ntemplate<class TImageType>\nvoid mitk::CLUtil::itkErodeGrayscale(TImageType * image, mitk::Image::Pointer & outimage , unsigned int radius, mitk::CLUtil::MorphologicalDimensions d)\n{\n  typedef itk::BinaryBallStructuringElement<typename TImageType::PixelType, 3>          StructureElementType;\n  typedef itk::GrayscaleErodeImageFilter<TImageType,TImageType,StructureElementType>    FilterType;\n\n  StructureElementType ball;\n  itkFitStructuringElement(ball,d, radius);\n\n  typename FilterType::Pointer filter = FilterType::New();\n  filter->SetKernel(ball);\n  filter->SetInput(image);\n  filter->Update();\n\n  mitk::CastToMitkImage(filter->GetOutput(),outimage);\n}\n\ntemplate<class TImageType>\nvoid mitk::CLUtil::itkDilateGrayscale(TImageType * image, mitk::Image::Pointer & outimage , unsigned int radius, mitk::CLUtil::MorphologicalDimensions d)\n{\n  typedef itk::BinaryBallStructuringElement<typename TImageType::PixelType, 3>          StructureElementType;\n  typedef itk::GrayscaleDilateImageFilter<TImageType,TImageType,StructureElementType>    FilterType;\n\n  StructureElementType ball;\n  itkFitStructuringElement(ball,d, radius);\n\n  typename FilterType::Pointer filter = FilterType::New();\n  filter->SetKernel(ball);\n  filter->SetInput(image);\n  filter->Update();\n\n  mitk::CastToMitkImage(filter->GetOutput(),outimage);\n}\n\ntemplate<class TImageType>\nvoid mitk::CLUtil::itkFillHoleGrayscale(TImageType * image, mitk::Image::Pointer & outimage)\n{\n  typedef itk::GrayscaleFillholeImageFilter<TImageType,TImageType>    FilterType;\n\n  typename FilterType::Pointer filter = FilterType::New();\n  filter->SetInput(image);\n  filter->Update();\n\n  mitk::CastToMitkImage(filter->GetOutput(),outimage);\n}\n\n\n#endif\n", "meta": {"hexsha": "6f22880b1bb45c510f79b0c38e42ce23219e1605", "size": 17022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/Classification/CLUtilities/src/mitkCLUtil.cpp", "max_stars_repo_name": "ZP-Hust/MITK", "max_stars_repo_head_hexsha": "ca11353183c5ed4bc30f938eae8bde43a0689bf6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-02-05T10:58:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-17T15:04:07.000Z", "max_issues_repo_path": "Modules/Classification/CLUtilities/src/mitkCLUtil.cpp", "max_issues_repo_name": "kometa-dev/MITK", "max_issues_repo_head_hexsha": "984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 141.0, "max_issues_repo_issues_event_min_datetime": "2015-03-03T06:52:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T07:28:14.000Z", "max_forks_repo_path": "Modules/Classification/CLUtilities/src/mitkCLUtil.cpp", "max_forks_repo_name": "kometa-dev/MITK", "max_forks_repo_head_hexsha": "984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-02-19T06:48:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-19T16:20:25.000Z", "avg_line_length": 35.2422360248, "max_line_length": 173, "alphanum_fraction": 0.7542004465, "num_tokens": 4815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5074604568931648}}
{"text": "#include \"nanobench.h\"\n#include <Eigen/Dense>\n#include <random>\n#include <iostream>\n#include <atomic>\n#include <memory>\n#include \"../include/cematrix.hpp\"\n#include \"../include/noexpr/matrix.hpp\"\n#include \"../include/noexpr/operator.hpp\"\n#include \"../include/vari/matrix.hpp\"\n#include \"../include/vari/vari_expr.hpp\"\n#include \"../include/crtp/matrix_expr.hpp\"\n#include \"../include/crtp/operator_expr.hpp\"\nconstexpr auto N = 8;\nusing scaler_t = int;\nusing fmatNN_crtp = ce::crtp::matrix_t<scaler_t, N, N>;\nusing fmatNN_noexpr = ce::noexpr::matrix<scaler_t, N, N>;\nusing fmatNN_vari = ce::vari::matrix_t<scaler_t, N, N>;\n\nstd::random_device rd;\nankerl::nanobench::Rng e2(rd());\nstd::uniform_int_distribution<scaler_t> dist(-5000, 5000);\n\n\ntemplate<typename mat_t>\nauto rand_mat()\n{\n    std::array<scaler_t, N * N> ret{};\n    for (auto &element : ret)\n    {\n        element = dist(e2);\n    }\n    mat_t ret_mat{};\n    ret_mat.data = ret;\n    return ret_mat;\n}\n\nvoid bench_noexpr(ankerl::nanobench::Bench *bench)\n{\n    const fmatNN_noexpr a = rand_mat<fmatNN_noexpr>();\n    const fmatNN_noexpr b = rand_mat<fmatNN_noexpr>();\n    const fmatNN_noexpr c = rand_mat<fmatNN_noexpr>();\n\n    bench->run(\"noexpr\", [&]() {\n        fmatNN_noexpr res = (a * b + a * c);\n        ankerl::nanobench::doNotOptimizeAway(res);\n    });\n}\n\nvoid bench_crtp(ankerl::nanobench::Bench *bench)\n{\n    const fmatNN_crtp a = rand_mat<fmatNN_crtp>();\n    const fmatNN_crtp b = rand_mat<fmatNN_crtp>();\n    const fmatNN_crtp c = rand_mat<fmatNN_crtp>();\n\n    bench->run(\"crtp\", [&]() {\n        fmatNN_crtp res = (a * b + a * c);\n        ankerl::nanobench::doNotOptimizeAway(res);\n    });\n}\nvoid bench_vari(ankerl::nanobench::Bench *bench)\n{\n    const fmatNN_vari a = rand_mat<fmatNN_vari>();\n    const fmatNN_vari b = rand_mat<fmatNN_vari>();\n    const fmatNN_vari c = rand_mat<fmatNN_vari>();\n\n    bench->run(\"vari\", [&]() {\n        fmatNN_vari res = (a * b + a * c);\n        ankerl::nanobench::doNotOptimizeAway(res);\n    });\n}\nvoid bench_Eigen(ankerl::nanobench::Bench *bench)\n{\n    const Eigen::Matrix<scaler_t, N, N> a = Eigen::Matrix<scaler_t, N, N>::Random();\n    const Eigen::Matrix<scaler_t, N, N> b = Eigen::Matrix<scaler_t, N, N>::Random();\n    const Eigen::Matrix<scaler_t, N, N> c = Eigen::Matrix<scaler_t, N, N>::Random();\n\n    bench->run(\"Eigen\", [&]() {\n        Eigen::Matrix<scaler_t, N, N> res = (a * b + a * c);\n        ankerl::nanobench::doNotOptimizeAway(res);\n    });\n}\n\nint main()\n{\n\n    ankerl::nanobench::Bench b;\n    b.title(\"Expression templates benchmark\").unit(\"expr\").warmup(500).relative(true);\n    b.performanceCounters(true);\n    bench_Eigen(&b);\n    bench_crtp(&b);\n    bench_noexpr(&b);\n    bench_vari(&b);\n}\n", "meta": {"hexsha": "b61fe11a3f4f036252613f0739e93a316ab0166a", "size": 2709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/benchmarks.cpp", "max_stars_repo_name": "jdao55/ce-matrix", "max_stars_repo_head_hexsha": "f60604a146bb57d1de3fa10f0ba9c4cd6bb70bbd", "max_stars_repo_licenses": ["MIT"], "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/benchmarks.cpp", "max_issues_repo_name": "jdao55/ce-matrix", "max_issues_repo_head_hexsha": "f60604a146bb57d1de3fa10f0ba9c4cd6bb70bbd", "max_issues_repo_licenses": ["MIT"], "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/benchmarks.cpp", "max_forks_repo_name": "jdao55/ce-matrix", "max_forks_repo_head_hexsha": "f60604a146bb57d1de3fa10f0ba9c4cd6bb70bbd", "max_forks_repo_licenses": ["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.5157894737, "max_line_length": 86, "alphanum_fraction": 0.6471022518, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5074604455845431}}
{"text": "#include <Eigen/Dense>\n#include <memory>\n#include <iostream>\n#include <limits>\n#include \"bpmfutils.h\"\n#include \"sparsetensor.h\"\n\nusing namespace Eigen;\n\nstd::pair<double,double> eval_rmse_tensor(\n\t\tSparseMode & sparseMode,\n\t\tconst int Nepoch,\n\t\tEigen::VectorXd & predictions,\n\t\tEigen::VectorXd & predictions_var,\n\t\tstd::vector< std::unique_ptr<Eigen::MatrixXd> > & samples,\n\t\tdouble mean_value)\n{\n  auto& U = samples[0];\n\n  const int nmodes = samples.size();\n  const int num_latents = U->rows();\n\n  const unsigned N = sparseMode.values.size();\n  double se = 0.0, se_avg = 0.0;\n\n  if (N == 0) {\n    // No test data, returning NaN's\n    return std::make_pair(std::numeric_limits<double>::quiet_NaN(),\n                          std::numeric_limits<double>::quiet_NaN());\n  }\n\n  if (N != predictions.size()) {\n    throw std::runtime_error(\"Ytest.size() and predictions.size() must be equal.\");\n  }\n\tif (sparseMode.row_ptr.size() - 1 != U->cols()) {\n    throw std::runtime_error(\"U.cols() and sparseMode size must be equal.\");\n\t}\n\n#pragma omp parallel for schedule(dynamic, 2) reduction(+:se, se_avg)\n  for (int n = 0; n < U->cols(); n++) {\n    Eigen::VectorXd u = U->col(n);\n    for (int j = sparseMode.row_ptr(n);\n             j < sparseMode.row_ptr(n + 1);\n             j++)\n    {\n      VectorXi idx = sparseMode.indices.row(j);\n      double pred = mean_value;\n      for (int d = 0; d < num_latents; d++) {\n        double tmp = u(d);\n\n        for (int m = 1; m < nmodes; m++) {\n          tmp *= (*samples[m])(d, idx(m - 1));\n        }\n        pred += tmp;\n      }\n\n      double pred_avg;\n      if (Nepoch == 0) {\n        pred_avg = pred;\n      } else {\n        double delta = pred - predictions(j);\n        pred_avg = (predictions(j) + delta / (Nepoch + 1));\n        predictions_var(j) += delta * (pred - pred_avg);\n      }\n      se     += square(sparseMode.values(j) - pred);\n      se_avg += square(sparseMode.values(j) - pred_avg);\n      predictions(j) = pred_avg;\n    }\n  }\n  const double rmse = sqrt(se / N);\n  const double rmse_avg = sqrt(se_avg / N);\n  return std::make_pair(rmse, rmse_avg);\n}\n", "meta": {"hexsha": "6520c2c74a9b7c09641d6065f329f514a125f14d", "size": 2098, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/macau-cpp/bpmfutils.cpp", "max_stars_repo_name": "edebrouwer/macau", "max_stars_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2016-02-27T22:18:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:17:39.000Z", "max_issues_repo_path": "lib/macau-cpp/bpmfutils.cpp", "max_issues_repo_name": "edebrouwer/macau", "max_issues_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-05-23T14:14:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-16T08:12:40.000Z", "max_forks_repo_path": "lib/macau-cpp/bpmfutils.cpp", "max_forks_repo_name": "edebrouwer/macau", "max_forks_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T12:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T15:05:59.000Z", "avg_line_length": 28.3513513514, "max_line_length": 83, "alphanum_fraction": 0.5872259295, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5074604455845431}}
{"text": "// This file is part of OpenCV project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://opencv.org/license.html.\n\n#include \"../precomp.hpp\"\n#include \"../usac.hpp\"\n#ifdef HAVE_EIGEN\n#include <Eigen/Eigen>\n#endif\n\nnamespace cv { namespace usac {\nclass HomographyMinimalSolver4ptsGEMImpl : public HomographyMinimalSolver4ptsGEM {\nprivate:\n    const Mat * points_mat;\n    const float * const points;\npublic:\n    explicit HomographyMinimalSolver4ptsGEMImpl (const Mat &points_) :\n        points_mat(&points_), points ((float*) points_.data) {}\n\n    int estimate (const std::vector<int>& sample, std::vector<Mat> &models) const override {\n        int m = 8, n = 9;\n        std::vector<double> A(72, 0);\n        int cnt = 0;\n        for (int i = 0; i < 4; i++) {\n            const int smpl = 4*sample[i];\n            const double x1 = points[smpl], y1 = points[smpl+1], x2 = points[smpl+2], y2 = points[smpl+3];\n\n            A[cnt++] = -x1;\n            A[cnt++] = -y1;\n            A[cnt++] = -1;\n            cnt += 3; // skip zeros\n            A[cnt++] = x2*x1;\n            A[cnt++] = x2*y1;\n            A[cnt++] = x2;\n\n            cnt += 3;\n            A[cnt++] = -x1;\n            A[cnt++] = -y1;\n            A[cnt++] = -1;\n            A[cnt++] = y2*x1;\n            A[cnt++] = y2*y1;\n            A[cnt++] = y2;\n        }\n\n        if (!Math::eliminateUpperTriangular(A, m, n))\n            return 0;\n\n        models = std::vector<Mat>{ Mat_<double>(3,3) };\n        auto * h = (double *) models[0].data;\n        h[8] = 1.;\n\n        // start from the last row\n        for (int i = m-1; i >= 0; i--) {\n            double acc = 0;\n            for (int j = i+1; j < n; j++)\n                acc -= A[i*n+j]*h[j];\n\n            h[i] = acc / A[i*n+i];\n            // due to numerical errors return 0 solutions\n            if (std::isnan(h[i]))\n                return 0;\n        }\n        return 1;\n    }\n\n    int getMaxNumberOfSolutions () const override { return 1; }\n    int getSampleSize() const override { return 4; }\n    Ptr<MinimalSolver> clone () const override {\n        return makePtr<HomographyMinimalSolver4ptsGEMImpl>(*points_mat);\n    }\n};\nPtr<HomographyMinimalSolver4ptsGEM> HomographyMinimalSolver4ptsGEM::create(const Mat &points_) {\n    return makePtr<HomographyMinimalSolver4ptsGEMImpl>(points_);\n}\n\nclass HomographyNonMinimalSolverImpl : public HomographyNonMinimalSolver {\nprivate:\n    const Mat * points_mat;\n    const Ptr<NormTransform> normTr;\npublic:\n    explicit HomographyNonMinimalSolverImpl (const Mat &points_) :\n        points_mat(&points_), normTr (NormTransform::create(points_)) {}\n\n    /*\n     * Find Homography matrix using (weighted) non-minimal estimation.\n     * Use Principal Component Analysis. Use normalized points.\n     */\n    int estimate (const std::vector<int> &sample, int sample_size, std::vector<Mat> &models,\n            const std::vector<double> &weights) const override {\n        if (sample_size < getMinimumRequiredSampleSize())\n            return 0;\n\n        Matx33d T1, T2;\n        Mat norm_points_;\n        normTr->getNormTransformation(norm_points_, sample, sample_size, T1, T2);\n\n        /*\n         * @norm_points is matrix 4 x inlier_size\n         * @weights is vector of inliers_size\n         * weights[i] is weight of i-th inlier\n         */\n        const auto * const norm_points = (float *) norm_points_.data;\n\n        double a1[9] = {0, 0, -1, 0, 0, 0, 0, 0, 0},\n               a2[9] = {0, 0, 0, 0, 0, -1, 0, 0, 0},\n               AtA[81] = {0};\n\n        if (weights.empty()) {\n            for (int i = 0; i < sample_size; i++) {\n                const int smpl = 4*i;\n                const double x1 = norm_points[smpl  ], y1 = norm_points[smpl+1],\n                             x2 = norm_points[smpl+2], y2 = norm_points[smpl+3];\n\n                a1[0] = -x1;\n                a1[1] = -y1;\n                a1[6] = x2*x1;\n                a1[7] = x2*y1;\n                a1[8] = x2;\n\n                a2[3] = -x1;\n                a2[4] = -y1;\n                a2[6] = y2*x1;\n                a2[7] = y2*y1;\n                a2[8] = y2;\n\n                for (int j = 0; j < 9; j++)\n                    for (int z = j; z < 9; z++)\n                        AtA[j*9+z] += a1[j]*a1[z] + a2[j]*a2[z];\n            }\n        } else {\n            for (int i = 0; i < sample_size; i++) {\n                const int smpl = 4*i;\n                const double weight = weights[i];\n                const double x1 = norm_points[smpl  ], y1 = norm_points[smpl+1],\n                             x2 = norm_points[smpl+2], y2 = norm_points[smpl+3];\n                const double minus_weight_times_x1 = -weight * x1,\n                             minus_weight_times_y1 = -weight * y1,\n                                   weight_times_x2 =  weight * x2,\n                                   weight_times_y2 =  weight * y2;\n\n                a1[0] = minus_weight_times_x1;\n                a1[1] = minus_weight_times_y1;\n                a1[2] = -weight;\n                a1[6] = weight_times_x2 * x1;\n                a1[7] = weight_times_x2 * y1;\n                a1[8] = weight_times_x2;\n\n                a2[3] = minus_weight_times_x1;\n                a2[4] = minus_weight_times_y1;\n                a2[5] = -weight;\n                a2[6] = weight_times_y2 * x1;\n                a2[7] = weight_times_y2 * y1;\n                a2[8] = weight_times_y2;\n\n                for (int j = 0; j < 9; j++)\n                    for (int z = j; z < 9; z++)\n                        AtA[j*9+z] += a1[j]*a1[z] + a2[j]*a2[z];\n            }\n        }\n\n        // copy symmetric part of covariance matrix\n        for (int j = 1; j < 9; j++)\n            for (int z = 0; z < j; z++)\n                AtA[j*9+z] = AtA[z*9+j];\n\n#ifdef HAVE_EIGEN\n        Mat H = Mat_<double>(3,3);\n        Eigen::HouseholderQR<Eigen::Matrix<double, 9, 9>> qr((Eigen::Matrix<double, 9, 9> (AtA)));\n        const Eigen::Matrix<double, 9, 9> &Q = qr.householderQ();\n        // extract the last nullspace\n        Eigen::Map<Eigen::Matrix<double, 9, 1>>((double *)H.data) = Q.col(8);\n#else\n        Matx<double, 9, 9> Vt;\n        Vec<double, 9> D;\n        if (! eigen(Matx<double, 9, 9>(AtA), D, Vt)) return 0;\n        Mat H = Mat_<double>(3, 3, Vt.val + 72/*=8*9*/);\n#endif\n\n        models = std::vector<Mat>{ T2.inv() * H * T1 };\n        return 1;\n    }\n\n    int getMinimumRequiredSampleSize() const override { return 4; }\n    int getMaxNumberOfSolutions () const override { return 1; }\n    Ptr<NonMinimalSolver> clone () const override {\n        return makePtr<HomographyNonMinimalSolverImpl>(*points_mat);\n    }\n};\nPtr<HomographyNonMinimalSolver> HomographyNonMinimalSolver::create(const Mat &points_) {\n    return makePtr<HomographyNonMinimalSolverImpl>(points_);\n}\n\nclass AffineMinimalSolverImpl : public AffineMinimalSolver {\nprivate:\n    const Mat * points_mat;\n    const float * const points;\npublic:\n    explicit AffineMinimalSolverImpl (const Mat &points_) :\n            points_mat(&points_), points((float *) points_.data) {}\n    /*\n        Affine transformation\n        x1 y1 1 0  0  0   a   u1\n        0  0  0 x1 y1 1   b   v1\n        x2 y2 1 0  0  0   c   u2\n        0  0  0 x2 y2 1 * d = v2\n        x3 y3 1 0  0  0   e   u3\n        0  0  0 x3 y3 1   f   v3\n    */\n    int estimate (const std::vector<int> &sample, std::vector<Mat> &models) const override {\n        const int smpl1 = 4*sample[0], smpl2 = 4*sample[1], smpl3 = 4*sample[2];\n        const auto\n                x1 = points[smpl1], y1 = points[smpl1+1], u1 = points[smpl1+2], v1 = points[smpl1+3],\n                x2 = points[smpl2], y2 = points[smpl2+1], u2 = points[smpl2+2], v2 = points[smpl2+3],\n                x3 = points[smpl3], y3 = points[smpl3+1], u3 = points[smpl3+2], v3 = points[smpl3+3];\n\n        // covers degeneracy test when all 3 points are collinear.\n        // In this case denominator will be 0\n        double denominator = x1*y2 - x2*y1 - x1*y3 + x3*y1 + x2*y3 - x3*y2;\n        if (fabs(denominator) < FLT_EPSILON) // check if denominator is zero\n            return 0;\n        denominator = 1. / denominator;\n\n        double a =  (u1*y2 - u2*y1 - u1*y3 + u3*y1 + u2*y3 - u3*y2) * denominator;\n        double b = -(u1*x2 - u2*x1 - u1*x3 + u3*x1 + u2*x3 - u3*x2) * denominator;\n        double c = u1 - a * x1 - b * y1; // ax1 + by1 + c = u1\n        double d =  (v1*y2 - v2*y1 - v1*y3 + v3*y1 + v2*y3 - v3*y2) * denominator;\n        double e = -(v1*x2 - v2*x1 - v1*x3 + v3*x1 + v2*x3 - v3*x2) * denominator;\n        double f = v1 - d * x1 - e * y1; // dx1 + ey1 + f = v1\n\n        models[0] = Mat(Matx33d(a, b, c, d, e, f, 0, 0, 1));\n        return 1;\n    }\n    int getSampleSize() const override { return 3; }\n    int getMaxNumberOfSolutions () const override { return 1; }\n    Ptr<MinimalSolver> clone () const override {\n        return makePtr<AffineMinimalSolverImpl>(*points_mat);\n    }\n};\nPtr<AffineMinimalSolver> AffineMinimalSolver::create(const Mat &points_) {\n    return makePtr<AffineMinimalSolverImpl>(points_);\n}\n\nclass AffineNonMinimalSolverImpl : public AffineNonMinimalSolver {\nprivate:\n    const Mat * points_mat;\n    const float * const points;\n    // const NormTransform<double> norm_transform;\npublic:\n    explicit AffineNonMinimalSolverImpl (const Mat &points_) :\n            points_mat(&points_), points((float*) points_.data)\n    /*, norm_transform(points_)*/ {}\n\n    int estimate (const std::vector<int> &sample, int sample_size, std::vector<Mat> &models,\n                  const std::vector<double> &weights) const override {\n        // surprisingly normalization of points does not improve the output model\n        // Mat norm_points_, T1, T2;\n        // norm_transform.getNormTransformation(norm_points_, sample, sample_size, T1, T2);\n        // const auto * const n_pts = (double *) norm_points_.data;\n\n        if (sample_size < getMinimumRequiredSampleSize())\n            return 0;\n        // do Least Squares\n        // Ax = b   ->  A^T Ax = A^T b\n        // x = (A^T A)^-1 A^T b\n        double AtA[36] = {0}, Ab[6] = {0};\n        double r1[6] = {0, 0, 1, 0, 0, 0}; // row 1 of A\n        double r2[6] = {0, 0, 0, 0, 0, 1}; // row 2 of A\n\n        if (weights.empty())\n            for (int p = 0; p < sample_size; p++) {\n                // if (weights != nullptr) weight = weights[sample[p]];\n\n                const int smpl = 4*sample[p];\n                const double x1=points[smpl], y1=points[smpl+1], x2=points[smpl+2], y2=points[smpl+3];\n                // const double x1=n_pts[smpl], y1=n_pts[smpl+1], x2=n_pts[smpl+2], y2=n_pts[smpl+3];\n\n                r1[0] = x1;\n                r1[1] = y1;\n\n                r2[3] = x1;\n                r2[4] = y1;\n\n                for (int j = 0; j < 6; j++) {\n                    for (int z = j; z < 6; z++)\n                        AtA[j * 6 + z] += r1[j] * r1[z] + r2[j] * r2[z];\n                    Ab[j] += r1[j]*x2 + r2[j]*y2;\n                }\n            }\n        else\n            for (int p = 0; p < sample_size; p++) {\n                const int smpl = 4*sample[p];\n                const double weight = weights[p];\n                const double weight_times_x1 = weight * points[smpl  ],\n                             weight_times_y1 = weight * points[smpl+1],\n                             weight_times_x2 = weight * points[smpl+2],\n                             weight_times_y2 = weight * points[smpl+3];\n\n                r1[0] = weight_times_x1;\n                r1[1] = weight_times_y1;\n                r1[2] = weight;\n\n                r2[3] = weight_times_x1;\n                r2[4] = weight_times_y1;\n                r2[5] = weight;\n\n                for (int j = 0; j < 6; j++) {\n                    for (int z = j; z < 6; z++)\n                        AtA[j * 6 + z] += r1[j] * r1[z] + r2[j] * r2[z];\n                    Ab[j] += r1[j]*weight_times_x2 + r2[j]*weight_times_y2;\n                }\n            }\n\n        // copy symmetric part\n        for (int j = 1; j < 6; j++)\n            for (int z = 0; z < j; z++)\n                AtA[j*6+z] = AtA[z*6+j];\n\n        Vec6d aff;\n        if (!solve(Matx66d(AtA), Vec6d(Ab), aff))\n            return 0;\n        models[0] = Mat(Matx33d(aff(0), aff(1), aff(2),\n                                aff(3), aff(4), aff(5),\n                                0, 0, 1));\n\n        // models[0] = T2.inv() * models[0] * T1;\n        return 1;\n    }\n\n    int getMinimumRequiredSampleSize() const override { return 3; }\n    int getMaxNumberOfSolutions () const override { return 1; }\n    Ptr<NonMinimalSolver> clone () const override {\n        return makePtr<AffineNonMinimalSolverImpl>(*points_mat);\n    }\n};\nPtr<AffineNonMinimalSolver> AffineNonMinimalSolver::create(const Mat &points_) {\n    return makePtr<AffineNonMinimalSolverImpl>(points_);\n}\n}}\n", "meta": {"hexsha": "3af13134c0526cbe03b2cb3e38bcb4325f4ad7c6", "size": 12800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/3d/src/usac/homography_solver.cpp", "max_stars_repo_name": "GerHobbelt/opencv", "max_stars_repo_head_hexsha": "7b083a1a6481ffbff315c87248d56466cb806d8f", "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": "modules/3d/src/usac/homography_solver.cpp", "max_issues_repo_name": "GerHobbelt/opencv", "max_issues_repo_head_hexsha": "7b083a1a6481ffbff315c87248d56466cb806d8f", "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": "modules/3d/src/usac/homography_solver.cpp", "max_forks_repo_name": "GerHobbelt/opencv", "max_forks_repo_head_hexsha": "7b083a1a6481ffbff315c87248d56466cb806d8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-30T18:00:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-30T18:00:41.000Z", "avg_line_length": 37.7581120944, "max_line_length": 106, "alphanum_fraction": 0.513984375, "num_tokens": 3896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.5074604399302322}}
{"text": "#include <dlib/clustering.h>\n#include <dlib/matrix.h>\n#include <plot.h>\n\n#include <experimental/filesystem>\n#include <iostream>\n#include <unordered_map>\n\nusing namespace dlib;\nnamespace fs = std::experimental::filesystem;\nusing SampleType = dlib::matrix<double, 1, 1>;\nusing Samples = std::vector<SampleType>;\n\nconst std::vector<std::string> data_names{\"dataset0.csv\", \"dataset1.csv\",\n                                          \"dataset2.csv\", \"dataset3.csv\",\n                                          \"dataset4.csv\", \"dataset5.csv\"};\n\nconst std::vector<std::string> colors{\"black\", \"red\",    \"blue\",  \"green\",\n                                      \"cyan\",  \"yellow\", \"brown\", \"magenta\"};\n\nusing DataType = double;\nusing Coords = std::vector<DataType>;\nusing PointCoords = std::pair<Coords, Coords>;\nusing Clusters = std::unordered_map<size_t, PointCoords>;\n\nvoid PlotClusters(const Clusters& clusters,\n                  const std::string& name,\n                  const std::string& file_name) {\n  plotcpp::Plot plt;\n  plt.SetTerminal(\"png\");\n  plt.SetOutput(file_name);\n  plt.SetTitle(name);\n  plt.SetXLabel(\"x\");\n  plt.SetYLabel(\"y\");\n  plt.SetAutoscale();\n  plt.GnuplotCommand(\"set grid\");\n\n  auto draw_state = plt.StartDraw2D<Coords::const_iterator>();\n  for (auto& cluster : clusters) {\n    std::stringstream params;\n    params << \"lc rgb '\" << colors[cluster.first] << \"' pt 7\";\n    plt.AddDrawing(draw_state,\n                   plotcpp::Points(\n                       cluster.second.first.begin(), cluster.second.first.end(),\n                       cluster.second.second.begin(),\n                       std::to_string(cluster.first) + \" cls\", params.str()));\n  }\n\n  plt.EndDraw2D(draw_state);\n  plt.Flush();\n}\n\ntemplate <typename I>\nvoid DoHierarhicalClustering(const I& inputs,\n                             size_t num_clusters,\n                             const std::string& name) {\n  // agglomerative clustering algorithm\n  matrix<double> dists(inputs.nr(), inputs.nr());\n  for (long r = 0; r < dists.nr(); ++r) {\n    for (long c = 0; c < dists.nc(); ++c) {\n      dists(r, c) = length(subm(inputs, r, 0, 1, 2) - subm(inputs, c, 0, 1, 2));\n    }\n  }\n  std::vector<unsigned long> clusters;\n  bottom_up_cluster(dists, clusters, num_clusters);\n  Clusters plot_clusters;\n  for (long i = 0; i != inputs.nr(); i++) {\n    auto cluser_idx = clusters[i];\n    plot_clusters[cluser_idx].first.push_back(inputs(i, 0));\n    plot_clusters[cluser_idx].second.push_back(inputs(i, 1));\n  }\n\n  PlotClusters(plot_clusters, \"Agglomerative clustering\", name + \"-aggl.png\");\n}\n\ntemplate <typename I>\nvoid DoGraphClustering(const I& inputs, const std::string& name) {\n  // chinese whispers algorithm\n  std::vector<sample_pair> edges;\n  for (long i = 0; i < inputs.nr(); ++i) {\n    for (long j = 0; j < inputs.nr(); ++j) {\n      auto dist = length(subm(inputs, i, 0, 1, 2) - subm(inputs, j, 0, 1, 2));\n      if (dist < 1)\n        edges.push_back(sample_pair(i, j, dist));\n    }\n  }\n  std::vector<unsigned long> clusters;\n  const auto num_clusters = chinese_whispers(edges, clusters);\n  std::cout << \"Num clusters detected: \" << num_clusters << std::endl;\n  Clusters plot_clusters;\n  for (long i = 0; i != inputs.nr(); i++) {\n    auto cluser_idx = clusters[i];\n    plot_clusters[cluser_idx].first.push_back(inputs(i, 0));\n    plot_clusters[cluser_idx].second.push_back(inputs(i, 1));\n  }\n\n  PlotClusters(plot_clusters, \"Graph clustering\", name + \"-graph.png\");\n}\n\ntemplate <typename I>\nvoid DoGraphNewmanClustering(const I& inputs, const std::string& name) {\n  std::vector<sample_pair> edges;\n  for (long i = 0; i < inputs.nr(); ++i) {\n    for (long j = 0; j < inputs.nr(); ++j) {\n      auto dist = length(subm(inputs, i, 0, 1, 2) - subm(inputs, j, 0, 1, 2));\n      if (dist < 0.5)\n        edges.push_back(sample_pair(i, j, dist));\n    }\n  }\n  remove_duplicate_edges(edges);\n\n  std::vector<unsigned long> clusters;\n  const auto num_clusters = newman_cluster(edges, clusters);\n  std::cout << \"Num clusters detected: \" << num_clusters << std::endl;\n  Clusters plot_clusters;\n  for (long i = 0; i != inputs.nr(); i++) {\n    auto cluser_idx = clusters[i];\n    plot_clusters[cluser_idx].first.push_back(inputs(i, 0));\n    plot_clusters[cluser_idx].second.push_back(inputs(i, 1));\n  }\n\n  PlotClusters(plot_clusters, \"Graph Newman clustering\",\n               name + \"-graph-newman.png\");\n}\n\ntemplate <typename I>\nvoid DoKMeansClustering(const I& inputs,\n                        size_t num_clusters,\n                        const std::string& name) {\n  typedef matrix<double, 2, 1> sample_type;\n  typedef radial_basis_kernel<sample_type> kernel_type;\n  kcentroid<kernel_type> kc(kernel_type(0.1), 0.01, 8);\n  kkmeans<kernel_type> kmeans(kc);\n\n  std::vector<sample_type> samples;\n  samples.reserve(inputs.nr());\n  for (long i = 0; i != inputs.nr(); i++) {\n    samples.push_back(dlib::trans(dlib::subm(inputs, i, 0, 1, 2)));\n  }\n\n  std::vector<sample_type> initial_centers;\n  pick_initial_centers(num_clusters, initial_centers, samples,\n                       kmeans.get_kernel());\n\n  kmeans.set_number_of_centers(num_clusters);\n  kmeans.train(samples, initial_centers);\n\n  std::vector<unsigned long> clusters;\n  Clusters plot_clusters;\n  for (long i = 0; i != inputs.nr(); i++) {\n    auto cluser_idx = kmeans(samples[i]);\n    plot_clusters[cluser_idx].first.push_back(inputs(i, 0));\n    plot_clusters[cluser_idx].second.push_back(inputs(i, 1));\n  }\n\n  PlotClusters(plot_clusters, \"K-Means\", name + \"-kmeans.png\");\n}\n\ntemplate <typename T>\nstruct knn_kernel {\n  knn_kernel(const std::vector<T>& samples, unsigned long k)\n      : samples_(&samples) {\n    find_k_nearest_neighbors(\n        samples, [](const T& a, const T& b) { return dlib::length(a - b); }, k,\n        edges_);\n    std::sort(edges_.begin(), edges_.end(), order_by_index<sample_pair>);\n  }\n  DataType operator()(const T& a, const T& b) const {\n    auto idx1 = std::distance(samples_->begin(),\n                              std::find(samples_->begin(), samples_->end(), a));\n    auto idx2 = std::distance(samples_->begin(),\n                              std::find(samples_->begin(), samples_->end(), b));\n    sample_pair value{idx1, idx2};\n    auto edge = std::lower_bound(edges_.begin(), edges_.end(), value,\n                                 order_by_index<sample_pair>);\n    if (edge != edges_.end() && !order_by_index<sample_pair>(value, *edge))\n      return 1;\n    else\n      return 0;\n  }\n  std::vector<sample_pair> edges_;\n  const std::vector<T>* samples_;\n};\n\ntemplate <typename I>\nvoid DoSpectralClustering(const I& inputs,\n                          size_t num_clusters,\n                          const std::string& name) {\n  typedef matrix<double, 2, 1> sample_type;\n  typedef knn_kernel<sample_type> kernel_type;\n\n  std::vector<sample_type> samples;\n  samples.reserve(inputs.nr());\n  for (long i = 0; i != inputs.nr(); i++) {\n    samples.push_back(dlib::trans(dlib::subm(inputs, i, 0, 1, 2)));\n  }\n\n  std::vector<unsigned long> clusters =\n      spectral_cluster(kernel_type(samples, 15), samples, num_clusters);\n\n  Clusters plot_clusters;\n  for (long i = 0; i != inputs.nr(); i++) {\n    auto cluser_idx = clusters[i];\n    plot_clusters[cluser_idx].first.push_back(inputs(i, 0));\n    plot_clusters[cluser_idx].second.push_back(inputs(i, 1));\n  }\n\n  PlotClusters(plot_clusters, \"Spectral clustering\", name + \"-spectral.png\");\n}\n\nint main(int argc, char** argv) {\n  if (argc > 1) {\n    auto base_dir = fs::path(argv[1]);\n    for (auto& dataset : data_names) {\n      auto dataset_name = base_dir / dataset;\n      if (fs::exists(dataset_name)) {\n        std::ifstream file(dataset_name);\n        matrix<DataType> data;\n        file >> data;\n\n        auto inputs = dlib::subm(data, 0, 1, data.nr(), 2);\n        auto labels = dlib::subm(data, 0, 3, data.nr(), 1);\n\n        auto num_samples = inputs.nr();\n        auto num_features = inputs.nc();\n        std::size_t num_clusters =\n            std::set<double>(labels.begin(), labels.end()).size();\n        if (num_clusters < 2)\n          num_clusters = 3;\n\n        std::cout << dataset << \"\\n\"\n                  << \"Num samples: \" << num_samples\n                  << \" num features: \" << num_features\n                  << \" num clusters: \" << num_clusters << std::endl;\n\n        // DoHierarhicalClustering(inputs, num_clusters, dataset);\n        // DoGraphClustering(inputs, dataset);\n        // DoKMeansClustering(inputs, num_clusters, dataset);\n        // DoGraphNewmanClustering(inputs, dataset);\n        DoSpectralClustering(inputs, num_clusters, dataset);\n      } else {\n        std::cerr << \"Dataset file \" << dataset_name << \" missed\\n\";\n      }\n    }\n  } else {\n    std::cerr << \"Please provider path to the datasets folder\\n\";\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "51ebfbb50dc9b7803222c00bbd9e4fbcb9089f1d", "size": 8745, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter04/dlib/dlib-cluster.cc", "max_stars_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_stars_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 201.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T12:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:56:11.000Z", "max_issues_repo_path": "Chapter04/dlib/dlib-cluster.cc", "max_issues_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_issues_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-12T10:01:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T19:35:05.000Z", "max_forks_repo_path": "Chapter04/dlib/dlib-cluster.cc", "max_forks_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_forks_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T15:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T02:07:09.000Z", "avg_line_length": 34.8406374502, "max_line_length": 80, "alphanum_fraction": 0.6144082333, "num_tokens": 2302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5074604398520988}}
{"text": "/*********************************************************************\n*  Copyright (c) 2017 Robert Bosch GmbH.\n*  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\n#ifndef EKF_HPP\n#define EKF_HPP\n\n#include <iostream>\n\n#include <Eigen/Dense>\n\n#include \"steering_functions/steering_functions.hpp\"\n#include \"steering_functions/utilities/utilities.hpp\"\n\nusing namespace std;\nusing namespace steer;\n\ntypedef Eigen::Matrix<double, 2, 2> Matrix2d;\ntypedef Eigen::Matrix<double, 3, 3> Matrix3d;\ntypedef Eigen::Matrix<double, 3, 2> Matrix32d;\ntypedef Eigen::Matrix<double, 2, 3> Matrix23d;\n\nclass EKF\n{\npublic:\n  /** Constructor */\n  EKF();\n\n  /** \\brief Sets the parameters required by the EKF */\n  void set_parameters(const Motion_Noise &motion_noise, const Measurement_Noise &measurement_noise,\n                      const Controller &_controller);\n\n  /** \\brief Converts a covariance given by a double array to an Eigen matrix */\n  Matrix3d covariance_to_eigen(const double covariance[16]) const;\n\n  /** \\brief Converts a covariance given by an Eigen matrix to a double array */\n  void eigen_to_covariance(const Matrix3d &covariance_eigen, double covariance[16]) const;\n\n  /** \\brief Computes the Jacobians of the motion equations with respect to the state and control */\n  void get_motion_jacobi(const State &state, const Control &control, double integration_step, Matrix3d &F_x,\n                         Matrix32d &F_u) const;\n\n  /** \\brief Computes the Jacobian of the observation equations with respect to the state */\n  Matrix3d get_observation_jacobi() const;\n\n  /** \\brief Returns the motion covariance in control space */\n  Matrix2d get_motion_covariance(const State &state, const Control &control, double integration_step) const;\n\n  /** \\brief Returns the observation covariance */\n  Matrix3d get_observation_covariance() const;\n\n  /** \\brief Returns the gain of the controller */\n  Matrix23d get_controller_gain(const Control &control) const;\n\n  /** \\brief Returns the rotation matrix from a global frame to a local frame */\n  Matrix3d get_rotation_matrix(double angle) const;\n\n  /** \\brief Predicts the covariances based on the paper:\n      Rapidly-exploring random belief trees for motion planning under uncertainty, A. Bry and N. Roy, IEEE ICRA 2011 */\n  void predict(const State_With_Covariance &state, const Control &control, double integration_step,\n               State_With_Covariance &state_pred) const;\n\n  /** \\brief Predicts the covariances */\n  void update(const State_With_Covariance &state_pred, State_With_Covariance &state_corr) const;\n\n  /** \\brief Overload operator new for fixed-size vectorizable Eigen member variable */\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\nprivate:\n  /** \\brief Motion noise */\n  Motion_Noise motion_noise_;\n\n  /** \\brief Measurement noise */\n  Measurement_Noise measurement_noise_;\n\n  /** \\brief Feedback controller */\n  Controller controller_;\n\n  /** \\brief Identity matrix */\n  Matrix3d I_;\n};\n\n#endif\n", "meta": {"hexsha": "6d13442a43f325ec6cc53eaf06531fb931822ff6", "size": 3548, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/steering_functions/filter/ekf.hpp", "max_stars_repo_name": "nobleo/steering_functions", "max_stars_repo_head_hexsha": "f3564e2ad53259485e7eebe91d674d211783be61", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2018-01-28T05:11:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:46:10.000Z", "max_issues_repo_path": "include/steering_functions/filter/ekf.hpp", "max_issues_repo_name": "nobleo/steering_functions", "max_issues_repo_head_hexsha": "f3564e2ad53259485e7eebe91d674d211783be61", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-04-30T19:26:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T21:13:15.000Z", "max_forks_repo_path": "include/steering_functions/filter/ekf.hpp", "max_forks_repo_name": "nobleo/steering_functions", "max_forks_repo_head_hexsha": "f3564e2ad53259485e7eebe91d674d211783be61", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2017-10-05T09:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T04:50:50.000Z", "avg_line_length": 36.5773195876, "max_line_length": 119, "alphanum_fraction": 0.7136414882, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5074604398520988}}
{"text": "#include <iostream>\n#include <lwr/lwr.h>\n#include <lwr/lwr_flann.h>\n#include <armadillo>\n#include <boost/lexical_cast.hpp>\n#include <flann/io/hdf5.h>\n#include <iostream>\n\nvoid simple_ann_test(){\n    int nn = 3;\n\n    Matrix<float> dataset;\n    Matrix<float> query;\n    load_from_file(dataset, \"dataset.hdf5\",\"dataset\");\n    load_from_file(query, \"dataset.hdf5\",\"query\");\n\n\n\n    Matrix<int> indices(new int[query.rows*nn], query.rows, nn);\n    Matrix<float> dists(new float[query.rows*nn], query.rows, nn);\n\n\n    std::cout<< \"dataset: (\" << dataset.rows << \" x \" << dataset.cols << \")\" << std::endl;\n    std::cout<< \"query:   (\" << query.rows << \" x \" << query.cols << \")\" << std::endl;\n    std::cout<< \"indices: (\" << indices.rows << \" x \" << indices.cols << \")\" << std::endl;\n\n\n\n    // construct an randomized kd-tree index using 4 kd-trees\n    Index<L2<float> > index(dataset, flann::KDTreeIndexParams(4));\n    index.buildIndex();\n\n    // do a knn search, using 128 checks\n    index.knnSearch(query, indices, dists, nn, flann::SearchParams(128));\n\n    flann::save_to_file(indices,\"result.hdf5\",\"result\");\n\n    delete[] dataset.ptr();\n    delete[] query.ptr();\n    delete[] indices.ptr();\n    delete[] dists.ptr();\n}\n\nvoid simple_ann_test2(){\n\n    int nn = 3;\n\n    Matrix<double> dataset;\n    Matrix<double> query;\n    load_from_file(dataset, \"dataset.hdf5\",\"dataset\");\n    load_from_file(query, \"dataset.hdf5\",\"query\");\n\n\n\n    Matrix<int> indices(new int[query.rows*nn], query.rows, nn);\n    Matrix<double> dists(new double[query.rows*nn], query.rows, nn);\n\n    std::cout<< \"dataset: (\" << dataset.rows << \" x \" << dataset.cols << \")\" << std::endl;\n    std::cout<< \"query:   (\" << query.rows << \" x \" << query.cols << \")\" << std::endl;\n    std::cout<< \"indices: (\" << indices.rows << \" x \" << indices.cols << \")\" << std::endl;\n\n    // construct an randomized kd-tree index using 4 kd-trees\n    Index<L2<double> > index(dataset, flann::KDTreeIndexParams(4));\n    index.buildIndex();\n\n    // do a knn search, using 128 checks\n    index.knnSearch(query, indices, dists, nn, flann::SearchParams(128));\n\n    flann::save_to_file(indices,\"result.hdf5\",\"result\");\n\n    delete[] dataset.ptr();\n    delete[] query.ptr();\n    delete[] indices.ptr();\n    delete[] dists.ptr();\n\n}\n\nvoid simple_ann_test3(){\n\n    int nn = 3;\n\n    int dim        = 3;\n    int numSamples = 9000;\n    int numQuery   = 1000;\n    arma::mat    X(dim,numSamples,arma::fill::randu);\n    arma::mat    Xq(dim,numQuery,arma::fill::randu);\n    X   = X * 100;\n    Xq  = Xq * 100;\n\n\n    double *ptr_X     = X.memptr();\n    double *ptr_query = Xq.memptr();\n\n    Matrix<double> dataset(ptr_X,X.n_cols,X.n_rows);\n    Matrix<double> query(ptr_query,Xq.n_cols,Xq.n_rows);\n    Matrix<int>     indices(new int[query.rows*nn], query.rows, nn);\n    Matrix<double>  dists(new double[query.rows*nn], query.rows, nn);\n\n    std::cout<< \"dataset: (\" << dataset.rows << \" x \" << dataset.cols << \")\" << std::endl;\n    std::cout<< \"query:   (\" << query.rows << \" x \" << query.cols << \")\" << std::endl;\n    std::cout<< \"indices: (\" << indices.rows << \" x \" << indices.cols << \")\" << std::endl;\n\n    // construct an randomized kd-tree index using 4 kd-trees\n    Index<L2<double> > index(dataset, flann::KDTreeIndexParams(4));\n    index.buildIndex();\n\n    // do a knn search, using 128 checks\n    index.knnSearch(query, indices, dists, nn, flann::SearchParams(128));\n\n    std::cout<< \"after KNN\" << std::endl;\n\n   // delete[] dataset.ptr();\n  //  delete[] query.ptr();\n  //  delete[] indices.ptr();\n  //  delete[] dists.ptr();\n\n}\n\nvoid my_test(){\n\n    int dim        = 2;\n    int numSamples = 1000;\n    int numQuery   = 10;\n    arma::mat    X(dim,numSamples,arma::fill::randu);\n    arma::mat    Xq(dim,numQuery,arma::fill::randu);\n    arma::colvec  y(numSamples,arma::fill::randu);\n    X   = X * 100;\n    Xq  = Xq * 100;\n\n\n\n    lwr::lwr_options lwr_opts;\n\n    lwr_opts.D.resize(dim);\n    for(int i = 0; i < dim;i++){\n        lwr_opts.D[i] = 1*1;\n    }\n\n    lwr_opts.k_bias  = 1;\n    lwr_opts.K       = 3;\n    lwr_opts.bUseKDT = true;\n\n    lwr::LWR Lwr(lwr_opts);\n    Lwr.mtype = conversion::ROW_M;\n\n\n\n    Lwr.print();\n\n    double* ptr_y = new double[numQuery];\n\n    for(std::size_t i=0; i < 100;i++){\n\n\n        Lwr.set_X(X);\n        Lwr.set_Y(y);\n\n        Lwr.f(ptr_y,Xq);\n        std::cout<< \"i: \" << i << std::endl;\n        sleep(1);\n\n    }\n\n\n    //Lwr.lwr_flann.ann(Xq);\n    std::cout<< \"=== delete Lwr ===\" << std::endl;\n\n\n\n}\n\nvoid f_flann_test(){\n\n    int dim        = 2;\n    int numSamples = 200;\n    int numQuery   = 1;\n    arma::mat     X(dim,numSamples,arma::fill::randu);\n    arma::mat    Xq(dim,numQuery,arma::fill::randu);\n    arma::colvec  y(numSamples,arma::fill::randu);\n\n    X   = X  * 100;\n    Xq  = Xq * 100;\n    Xq(0,0) = 500;\n    Xq(1,0) = 500;\n\n\n    lwr::lwr_options lwr_opts;\n\n    lwr_opts.D.resize(dim);\n    for(int i = 0; i < dim;i++){\n        lwr_opts.D[i] = 5*5;\n    }\n\n    lwr_opts.k_bias  = 1;\n    lwr_opts.y_bias  = 0;\n    lwr_opts.K       = 10;\n    lwr_opts.bUseKDT = true;\n\n    lwr::LWR Lwr(lwr_opts);\n    Lwr.mtype = conversion::ROW_M;\n\n    Lwr.set_X(X);\n    Lwr.set_Y(y);\n\n    double* ptr_y = new double[numQuery];\n\n    Lwr.f(ptr_y,Xq);\n\n    Lwr.lwr_flann.print();\n\n}\n\nvoid arma_test(){\n\n    arma::mat A(3,3);\n\n    A(0,0) = 25.0000; A(0,1) =  25.0000; A(0,2) =  -5.0000;\n    A(1,0) = 25.0000; A(1,1) =  25.0000; A(1,2) =  -5.0000;\n    A(2,0) = -5.0000; A(2,1) =  -5.0000; A(2,2) =    1.0000;\n\n    A.print(\"A\");\n\n    pinv(A).print(\"pinv(A)\");\n\n}\n\n\nint main(int argc, char** argv)\n{\n\n    std::cout<< \"=== lwr_run ===\" << std::endl;\n   /* std::cout<< \" test 2  \" << std::endl;\n    simple_ann_test2();\n    std::cout<< \" test 3  \" << std::endl;*/\n   // simple_ann_test3();\n//    std::cout<< \" my_test  \" << std::endl;\n //   my_test();\n\n    my_test();\n\n\n  return 0;\n}\n", "meta": {"hexsha": "82a43acb7252836350eb7a248703e7e57f95c348", "size": 5831, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/lwr_run.cpp", "max_stars_repo_name": "gpldecha/npr", "max_stars_repo_head_hexsha": "035c08507d22f9ae59318ff4294871cb1cd54ee9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-11-03T16:30:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T20:51:31.000Z", "max_issues_repo_path": "test/lwr_run.cpp", "max_issues_repo_name": "gpldecha/npr", "max_issues_repo_head_hexsha": "035c08507d22f9ae59318ff4294871cb1cd54ee9", "max_issues_repo_licenses": ["MIT"], "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/lwr_run.cpp", "max_forks_repo_name": "gpldecha/npr", "max_forks_repo_head_hexsha": "035c08507d22f9ae59318ff4294871cb1cd54ee9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-07-26T01:36:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-29T05:37:00.000Z", "avg_line_length": 23.8975409836, "max_line_length": 90, "alphanum_fraction": 0.5664551535, "num_tokens": 1871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594355, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5074604396958313}}
{"text": "#ifndef TRAJECTORYGENERATOR_HPP\n#define TRAJECTORYGENERATOR_HPP\n\n#include <iostream>\n#include <vector>\n#include <map>\n#include <cmath>\n#include <random>\n#include <algorithm>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"polynomials.hpp\"\n#include \"tools.hpp\"\n#include \"vehicle.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\n\nclass Trajectory {\n\npublic:\n\n    Trajectory() : _generated(false) {}\n\n    Trajectory(pair<Polynomial, Polynomial> &traj_coeffs,\n               int samples)\n    {\n        generate(traj_coeffs, samples);\n    }\n\n    ~Trajectory() {}\n\n    void clear() {\n        _traj.clear();\n    }\n\n    int size(void) const {\n        return _traj.size();\n    }\n    \n    void removeFirstPoints(int numPoints);\n    void removeLastPoints(int numPoints);\n    vector<double> operator[](int T);\n    vector<double> getState_at(int T);\n    vector<vector<double>> getSD();\n    void generate(pair<Polynomial, Polynomial> &traj_coeffs,\n                  int samples);\n\nprivate:\n    vector<Vehicle> _traj;\n    bool _generated = false;\n};\n\n\n\n\nclass TrajectoryGenerator {\n    \npublic:\n    TrajectoryGenerator() {}\n    ~TrajectoryGenerator() {}\n\n    Trajectory get_last_trajectory() const;\n    Trajectory generate_trajectory(const vector<double> &start, const double max_speed,\n                                   const double horizon, const double update_interval, const int lag,\n                                   const vector<Vehicle> &vehicles);\n\n    static int convert_d_to_lane(const double d, const double laneWidth = 4.0);\n    static double convert_lane_to_d(const int lane_number, const double laneWidth = 4.0);\n    static double logistic(const double x);\n    string get_current_action() const;\n\n\nprivate:\n    Polynomial jmt(const vector<double> &start, const vector<double> &end, const int T);\n    void perturb_goal(vector<double> goal, vector<vector<double>> &goal_points, bool no_ahead=false);\n\n    int closest_vehicle_in_lane(const vector<double> &start, const int ego_lane_i,\n                                const vector<Vehicle> &vehicles);\n    vector<int> closest_vehicle_in_lanes(const vector<double> &start, const vector<Vehicle> &vehicles);\n\n    // cost functions:\n    double calculate_cost(const pair<Polynomial, Polynomial> &traj, const vector<double> &goal,\n                          const vector<Vehicle> &vehicles, vector<vector<double>> &all_costs);\n    double exceeds_speed_limit_cost(const pair<Polynomial, Polynomial> &traj,\n                                    const vector<double> &goal, const vector<Vehicle> &vehicles);\n    double exceeds_accel_cost(const pair<Polynomial, Polynomial> &traj,\n                              const vector<double> &goal, const vector<Vehicle> &vehicles);\n    double exceeds_jerk_cost(const pair<Polynomial, Polynomial> &traj,\n                             const vector<double> &goal, const vector<Vehicle> &vehicles);\n    double collision_cost(const pair<Polynomial, Polynomial> &traj,\n                          const vector<double> &goal, const vector<Vehicle> &vehicles);\n    double traffic_buffer_cost(const pair<Polynomial, Polynomial> &traj,\n                               const vector<double> &goal, const vector<Vehicle> &vehicles);\n    double efficiency_cost(const pair<Polynomial, Polynomial> &traj,\n                           const vector<double> &goal, const vector<Vehicle> &vehicles);\n    double total_accel_d_cost(const pair<Polynomial, Polynomial> &traj,\n                              const vector<double> &goal, const vector<Vehicle> &vehicles);\n    double total_accel_s_cost(const pair<Polynomial, Polynomial> &traj,\n                              const vector<double> &goal, const vector<Vehicle> &vehicles);\n    double total_jerk_cost(const pair<Polynomial, Polynomial> &traj,\n                           const vector<double> &goal, const vector<Vehicle> &vehicles);\n    double lane_depart_cost(const pair<Polynomial, Polynomial> &traj,\n                            const vector<double> &goal, const vector<Vehicle> &vehicles);\n    double traffic_ahead_cost(const pair<Polynomial, Polynomial> &traj,\n                              const vector<double> &goal, const vector<Vehicle> &vehicles);\n\n\n    Trajectory _trajectory;\n    int _horizon                    = 0;\n    std::string _current_action     = \"straight\";\n    const double _dt                = 0.02;\n    const double _car_width         = 2.0;\n    const double _car_length        = 5.0;\n    const double _car_col_width     = 0.5 * _car_width;\n    const double _car_col_length    = 0.5 * _car_length;\n    const double _col_buf_width     = _car_width;\n    const double _col_buf_length    = 5 * _car_length;\n    const int _goal_perturb_samples = 10;\n    const double _hard_max_vel_per_timestep     = mph2mps(48.) * _dt; // 50 miles + a little buffer\n    const double _hard_max_acc_per_timestep     = 8.0 * _dt; // m/s\n    const double _hard_max_jerk_per_timestep    = 7.0 * _dt; // m/s^2\n    double _max_dist_per_timestep               = 0.0;\n    double _delta_s_maxspeed                    = 0.0;\n    \n    std::default_random_engine _rand_generator;\n    std::map<std::string, double> _cost_weights = {\n        {\"tr_buf_cost\",     200.0},\n        {\"eff_cost\",        100.0},\n        {\"acc_s_cost\",      20.0},\n        {\"acc_d_cost\",      20.0},\n        {\"jerk_cost\",       20.0},\n        {\"lane_dep_cost\",   0.5},\n        {\"traffic_cost\",    100.0}\n    };\n};\n\n#endif // TRAJECTORYGENERATOR_HPP\n\n\n", "meta": {"hexsha": "302db9334f19b0ad12ac2857caab9d73645b512d", "size": 5427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/trajectoryGenerator.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/trajectoryGenerator.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/trajectoryGenerator.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": 37.951048951, "max_line_length": 103, "alphanum_fraction": 0.6358946011, "num_tokens": 1260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5074490871038229}}
{"text": "#include <boost/math/special_functions/ellint_1.hpp>\n", "meta": {"hexsha": "3b4e6a0b62820d7997f0eecf9208bb077930fd08", "size": 53, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_ellint_1.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_ellint_1.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_ellint_1.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.5, "max_line_length": 52, "alphanum_fraction": 0.8301886792, "num_tokens": 14, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5074490756846064}}
{"text": "#ifdef BUILD_WITH_MOSEK\n\n#include <Eigen/SparseCore>\n#include <catch2/catch.hpp>\n\n#include <igl/mosek/mosek_quadprog.h>\n\n#define INF_D (std::numeric_limits<double>::infinity())\n\nTEST_CASE(\"Simple tests of MOSEK\", \"[opt][mosek]\")\n{\n    // Load problem data\n    const int N = 4;\n    const int M = N;\n\n    // Quadratic matrix\n    Eigen::SparseMatrix<double> Q(N, N);\n    Q.setIdentity();\n\n    // Quadratic linear term\n    Eigen::VectorXd c(N);\n    c.setZero();\n\n    // Quadratic constant term\n    double cf = 0.0;\n\n    // Linear constraint matrix\n    Eigen::SparseMatrix<double> A(M, N);\n    A.setIdentity();\n\n    // Linear constraint lower bounds\n    Eigen::VectorXd lc(M);\n    lc.setOnes();\n    Eigen::VectorXd expected_solution(M);\n    expected_solution.setOnes();\n    SECTION(\"No Lower Bounds\")\n    {\n        lc *= -INF_D;\n        expected_solution *= 0;\n    }\n    SECTION(\"Lower Bounds = 1\") {}\n    SECTION(\"Lower Bounds = 10\")\n    {\n        lc *= 10;\n        expected_solution *= 10;\n    }\n    // Linear constraint upper bounds\n    Eigen::VectorXd uc(M);\n    uc.setOnes();\n    uc *= INF_D;\n    Eigen::VectorXd lx(M);\n    lx.setOnes();\n    lx *= -INF_D;\n    Eigen::VectorXd ux(M);\n    ux.setOnes();\n    ux *= INF_D;\n\n    igl::mosek::MosekData mosek_data;\n\n    Eigen::VectorXd x(N);\n    bool success = igl::mosek::mosek_quadprog(\n        Q, c, cf, A, lc, uc, lx, ux, mosek_data, x);\n\n    // I always require success in everything I do!\n    REQUIRE(success);\n    REQUIRE(x.size() == expected_solution.size());\n    CHECK((x - expected_solution).squaredNorm() == Approx(0.0).margin(1e-12));\n}\n\n#endif\n", "meta": {"hexsha": "40b8b94f261192e0df8c0a5a68b0ebbaeed258ed", "size": 1599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "comparisons/STIV/tests/integration/test_mosek.cpp", "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": "comparisons/STIV/tests/integration/test_mosek.cpp", "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": "comparisons/STIV/tests/integration/test_mosek.cpp", "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": 22.5211267606, "max_line_length": 78, "alphanum_fraction": 0.6053783615, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.507449070096069}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2009 Hauke Heibel <hauke.heibel@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\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <Eigen/LU> // required for MatrixBase::determinant\n#include <Eigen/SVD> // required for SVD\n\nusing namespace Eigen;\n\n//  Constructs a random matrix from the unitary group U(size).\ntemplate <typename T>\nEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> randMatrixUnitary(int size)\n{\n  typedef T Scalar;\n  typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixType;\n\n  MatrixType Q;\n\n  int max_tries = 40;\n  double is_unitary = false;\n\n  while (!is_unitary && max_tries > 0)\n  {\n    // initialize random matrix\n    Q = MatrixType::Random(size, size);\n\n    // orthogonalize columns using the Gram-Schmidt algorithm\n    for (int col = 0; col < size; ++col)\n    {\n      typename MatrixType::ColXpr colVec = Q.col(col);\n      for (int prevCol = 0; prevCol < col; ++prevCol)\n      {\n        typename MatrixType::ColXpr prevColVec = Q.col(prevCol);\n        colVec -= colVec.dot(prevColVec)*prevColVec;\n      }\n      Q.col(col) = colVec.normalized();\n    }\n\n    // this additional orthogonalization is not necessary in theory but should enhance\n    // the numerical orthogonality of the matrix\n    for (int row = 0; row < size; ++row)\n    {\n      typename MatrixType::RowXpr rowVec = Q.row(row);\n      for (int prevRow = 0; prevRow < row; ++prevRow)\n      {\n        typename MatrixType::RowXpr prevRowVec = Q.row(prevRow);\n        rowVec -= rowVec.dot(prevRowVec)*prevRowVec;\n      }\n      Q.row(row) = rowVec.normalized();\n    }\n\n    // final check\n    is_unitary = Q.isUnitary();\n    --max_tries;\n  }\n\n  if (max_tries == 0)\n    eigen_assert(false && \"randMatrixUnitary: Could not construct unitary matrix!\");\n\n  return Q;\n}\n\n//  Constructs a random matrix from the special unitary group SU(size).\ntemplate <typename T>\nEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> randMatrixSpecialUnitary(int size)\n{\n  typedef T Scalar;\n\n  typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixType;\n\n  // initialize unitary matrix\n  MatrixType Q = randMatrixUnitary<Scalar>(size);\n\n  // tweak the first column to make the determinant be 1\n  Q.col(0) *= numext::conj(Q.determinant());\n\n  return Q;\n}\n\ntemplate <typename MatrixType>\nvoid run_test(int dim, int num_elements)\n{\n  using std::abs;\n  typedef typename internal::traits<MatrixType>::Scalar Scalar;\n  typedef Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixX;\n  typedef Matrix<Scalar, Eigen::Dynamic, 1> VectorX;\n\n  // MUST be positive because in any other case det(cR_t) may become negative for\n  // odd dimensions!\n  const Scalar c = abs(internal::random<Scalar>());\n\n  MatrixX R = randMatrixSpecialUnitary<Scalar>(dim);\n  VectorX t = Scalar(50)*VectorX::Random(dim,1);\n\n  MatrixX cR_t = MatrixX::Identity(dim+1,dim+1);\n  cR_t.block(0,0,dim,dim) = c*R;\n  cR_t.block(0,dim,dim,1) = t;\n\n  MatrixX src = MatrixX::Random(dim+1, num_elements);\n  src.row(dim) = Matrix<Scalar, 1, Dynamic>::Constant(num_elements, Scalar(1));\n\n  MatrixX dst = cR_t*src;\n\n  MatrixX cR_t_umeyama = umeyama(src.block(0,0,dim,num_elements), dst.block(0,0,dim,num_elements));\n\n  const Scalar error = ( cR_t_umeyama*src - dst ).norm() / dst.norm();\n  VERIFY(error < Scalar(40)*std::numeric_limits<Scalar>::epsilon());\n}\n\ntemplate<typename Scalar, int Dimension>\nvoid run_fixed_size_test(int num_elements)\n{\n  using std::abs;\n  typedef Matrix<Scalar, Dimension+1, Dynamic> MatrixX;\n  typedef Matrix<Scalar, Dimension+1, Dimension+1> HomMatrix;\n  typedef Matrix<Scalar, Dimension, Dimension> FixedMatrix;\n  typedef Matrix<Scalar, Dimension, 1> FixedVector;\n\n  const int dim = Dimension;\n\n  // MUST be positive because in any other case det(cR_t) may become negative for\n  // odd dimensions!\n  const Scalar c = abs(internal::random<Scalar>());\n\n  FixedMatrix R = randMatrixSpecialUnitary<Scalar>(dim);\n  FixedVector t = Scalar(50)*FixedVector::Random(dim,1);\n\n  HomMatrix cR_t = HomMatrix::Identity(dim+1,dim+1);\n  cR_t.block(0,0,dim,dim) = c*R;\n  cR_t.block(0,dim,dim,1) = t;\n\n  MatrixX src = MatrixX::Random(dim+1, num_elements);\n  src.row(dim) = Matrix<Scalar, 1, Dynamic>::Constant(num_elements, Scalar(1));\n\n  MatrixX dst = cR_t*src;\n\n  Block<MatrixX, Dimension, Dynamic> src_block(src,0,0,dim,num_elements);\n  Block<MatrixX, Dimension, Dynamic> dst_block(dst,0,0,dim,num_elements);\n\n  HomMatrix cR_t_umeyama = umeyama(src_block, dst_block);\n\n  const Scalar error = ( cR_t_umeyama*src - dst ).array().square().sum();\n\n  VERIFY(error < Scalar(10)*std::numeric_limits<Scalar>::epsilon());\n}\n\nvoid test_umeyama()\n{\n  for (int i=0; i<g_repeat; ++i)\n  {\n    const int num_elements = internal::random<int>(40,500);\n\n    // works also for dimensions bigger than 3...\n    for (int dim=2; dim<8; ++dim)\n    {\n      CALL_SUBTEST_1(run_test<MatrixXd>(dim, num_elements));\n      CALL_SUBTEST_2(run_test<MatrixXf>(dim, num_elements));\n    }\n\n    CALL_SUBTEST_3((run_fixed_size_test<float, 2>(num_elements)));\n    CALL_SUBTEST_4((run_fixed_size_test<float, 3>(num_elements)));\n    CALL_SUBTEST_5((run_fixed_size_test<float, 4>(num_elements)));\n\n    CALL_SUBTEST_6((run_fixed_size_test<double, 2>(num_elements)));\n    CALL_SUBTEST_7((run_fixed_size_test<double, 3>(num_elements)));\n    CALL_SUBTEST_8((run_fixed_size_test<double, 4>(num_elements)));\n  }\n\n  // Those two calls don't compile and result in meaningful error messages!\n  // umeyama(MatrixXcf(),MatrixXcf());\n  // umeyama(MatrixXcd(),MatrixXcd());\n}\n", "meta": {"hexsha": "738d0af70b4a2a0b433ac590d53af6392162517c", "size": 5775, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Externals/eigen/test/umeyama.cpp", "max_stars_repo_name": "benjaminlarson/SCIRunGUIPrototype", "max_stars_repo_head_hexsha": "ed34ee11cda114e3761bd222a71a9f397517914d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-10-23T17:11:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T12:48:39.000Z", "max_issues_repo_path": "src/Externals/eigen/test/umeyama.cpp", "max_issues_repo_name": "benjaminlarson/SCIRunGUIPrototype", "max_issues_repo_head_hexsha": "ed34ee11cda114e3761bd222a71a9f397517914d", "max_issues_repo_licenses": ["Unlicense"], "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": "src/Externals/eigen/test/umeyama.cpp", "max_forks_repo_name": "benjaminlarson/SCIRunGUIPrototype", "max_forks_repo_head_hexsha": "ed34ee11cda114e3761bd222a71a9f397517914d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-10T10:39:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T10:39:55.000Z", "avg_line_length": 31.5573770492, "max_line_length": 99, "alphanum_fraction": 0.6955844156, "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.507449070096069}}
{"text": "#include \"Prime.h\"\n#include <cassert>\n#include <thread>\n#include <utility>\n#include <iostream>\n\n#include <boost/filesystem.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n\n#include <rt/tasq.h>\n\n#define PRIME_LIST_FILENAME \"Primes.inc\"\nstatic const boost::multiprecision::cpp_int Primes[] = {\n#include \"Primes.inc\"\n};\nstatic const size_t PrimeItems = sizeof(Primes) / sizeof(Primes[0]);\n\nnamespace {\n#ifdef rt_SRC_DIR\nboost::filesystem::path PrimeListDir = rt_SRC_DIR;\nauto PrimeListPath = PrimeListDir / PRIME_LIST_FILENAME;\n#endif\n} // namespace\n\nnamespace omnn::rt {\n\nbool GrowPrime(const boost::multiprecision::cpp_int& upto,\n               std::function<bool(boost::multiprecision::cpp_int)> is_prime) {\n    auto& prev = Primes[PrimeItems - 1];\n    auto next = prev;\n    ++next;\n    static auto from = next;\n    auto range = upto;\n    range -= prev;\n    auto chunks = std::thread::hardware_concurrency() - 1; // One thread left free for GC\n    auto chunk = range;\n    chunk /= chunks;\n    if (from + chunk * chunks < upto) {\n        ++chunk;\n    }\n    std::deque<std::future<std::string>> primining;\n    std::cout << \"new prime table target: \" << upto << '(' << from + chunk * chunks << ')'<<std::endl;\n    for (decltype(chunks) i = 0; i < chunks; ++i) {\n        primining.emplace_back(std::async(std::launch::async, [=]() {\n            std::stringstream ss;\n            auto j = chunk;\n            j *= i;\n            j += from;\n            auto up = j;\n            up += chunk; // NOTE: preserving up type same as j. Expression (j+chunk)  type differs from j type.\n            {\n                static std::mutex m;\n                std::lock_guard l(m);\n                std::cout << '[' << j << ',' << up << ')';\n            }\n            for (; j < up; ++j) {\n                if (is_prime(j)) {\n                    std::cout << j << ',';\n                    ss << j << ',';\n                }\n            }\n            return std::move(ss.str());\n        }));\n    }\n\n    int i = -1;\n    while (primining.size()) {\n        auto line = primining.front().get();\n        std::cout << \"Chunk \" << ++i << std::endl << line << std::endl << \"\\n chunk is ready. Appending.\" << std::endl;\n        std::ofstream PrimesIncFile(PrimeListPath.string(), std::ios_base::app);\n        PrimesIncFile << std::endl << line;\n        PrimesIncFile.close();\n        primining.pop_front();\n    }\n    from++ = upto;\n    return true;\n}\n\nconst boost::multiprecision::cpp_int& prime(size_t idx) {\n#ifndef NDEBUG\n    auto haveThePrime = idx < PrimeItems;\n    if (!haveThePrime) {\n        std::cerr << \"There is no \" << idx\n                  << \"th prime in the table yet. Use GrowPrime call if you use debug version to increase the table for \"\n                     \"next compile time. Currently the table has \"\n                  << PrimeItems << \" elements\" << std::endl;\n        assert(haveThePrime);\n    }\n#endif\n    return Primes[idx];\n}\n\nsize_t primes() { return PrimeItems - 1; }\n\n} // namespace omnn::rt\n", "meta": {"hexsha": "b0ea99cd74705675ff66d7a98d3726531f2f474c", "size": 2993, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/rt/Prime.cpp", "max_stars_repo_name": "SergMariaDB/openmind", "max_stars_repo_head_hexsha": "98ad7f1c2c5c02d41418c7f9af25876342270d25", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-04T20:00:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T20:00:05.000Z", "max_issues_repo_path": "omnn/rt/Prime.cpp", "max_issues_repo_name": "SergMariaDB/openmind", "max_issues_repo_head_hexsha": "98ad7f1c2c5c02d41418c7f9af25876342270d25", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/rt/Prime.cpp", "max_forks_repo_name": "SergMariaDB/openmind", "max_forks_repo_head_hexsha": "98ad7f1c2c5c02d41418c7f9af25876342270d25", "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.1770833333, "max_line_length": 120, "alphanum_fraction": 0.5556298029, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5074490700960689}}
{"text": "#include <iostream>\n#include <boost/date_time.hpp>\n#include \"../mylib/timeit.hpp\"\n\nstd::vector<long> nsquared(std::vector<double>& changes){\n    double value = 0; //{\n    double direction = 0;\n    long buyday = -1;\n    long sellday = -1;\n    double best = -DBL_MAX;\n    std::vector<double> values;\n    values.emplace_back(value); //} = \u03b8(1)\n    for (auto dx : changes){ // l\u00f8kke = \u03b8(n)\n        value += dx;\n        values.emplace_back(value); // innhold = \u03b8(1)\n    } //1*n = n\n    //+\n    for (auto i = values.begin(); i<values.end(); ++i){ // l\u00f8kke = \u03b8(n)\n        for (auto j = i+1; j<values.end(); j++){ //sum 1 to n-1 = \u03b8(n\u00b2)\n            if (*j - *i > best){\n                best = *j - *i;\n                buyday = i-values.begin();\n                sellday = j-values.begin(); //innhold = \u03b8(1)\n            }\n        }\n    } //n\u00b2*1 = n\u00b2\n    return {buyday, sellday, (long)best};\n\n}\n\nstd::vector<long> nlinear(std::vector<double>& changes){\n    double lowest = 0;\n    long lowestDay = 0;\n    double highest = 0;\n    long highestDay = 0;\n    double value = 0;\n    std::vector<long> bestHigh; //low high == buy sell\n    std::vector<long> bestLow; //low high == buy sell\n    std::vector<double> values; //deklareringer er \u03b8(1)\n\n    for(auto dx = changes.begin(); dx < changes.end(); dx++){ //l\u00f8kke gjennom liste s\u00e5 \u03b8(n)\n        value += *dx;\n        if(value < lowest){\n            bestHigh.emplace_back(highestDay);\n            bestLow.emplace_back(lowestDay);\n            values.emplace_back(highest-lowest);\n            lowest = highest = value;\n            lowestDay = highestDay = dx-changes.begin();\n        }\n        if(value > highest){\n            highest = value;\n            highestDay = dx-changes.begin();\n        }\n        //ifs og emplace etc \u03b8(1)\n    } // 1*n=n\n\n    int besti = 0;\n    for (int i = 0; i < bestHigh.size(); ++i) { //st\u00f8rrelse p\u00e5 disse er mellom 1 og n, alts\u00e5 omega(1) og O(n)\n        if (values[i] > values[besti]){\n            besti = i;\n        } //lookup er \u03b8(1)\n    }\n    std::vector<long> results;\n    results.emplace_back(bestLow[besti]+1);\n    results.emplace_back(bestHigh[besti]+1);\n    results.emplace_back(values[besti]); //lookups er \u03b8(1)\n    return results; //totalt \u03b8(n)\n\n}\n\nint main(){\n\n    using namespace std;\n\n\n    /*\n    vector<double> referencedata = {-1, +3, -9, +2, +2, -1, +2, -1, -5}; //rett svar: kj\u00f8p 3 selg 7 val 5\n    for(auto i : nlinear(referencedata)) cout << i << \" \";\n    cout << endl;\n    */ //sjekk svar\n\n    // /*\n    for (int i = 1; i<1000000000    ; i++) { //40 datapunkter\n        vector<double> row;\n        for (int j = 0; j < i*10000000; j++){\n            row.emplace_back(rand() - RAND_MAX/2);\n        }\n        cout << row.size() << \", \" << my::timeit(nlinear, row) << endl;\n    }\n    cout << \"DONE\" << endl;\n    // */timing\n\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "61406793373c6747fa71350cc709f74ca8429e3f", "size": 2829, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "oving1/main.cpp", "max_stars_repo_name": "odderikf/algdat", "max_stars_repo_head_hexsha": "9b5e5ea42ca0fefda3c1e9be5cff0be4797a8aae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-12T21:49:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T21:49:32.000Z", "max_issues_repo_path": "oving1/main.cpp", "max_issues_repo_name": "odderikf/algdat", "max_issues_repo_head_hexsha": "9b5e5ea42ca0fefda3c1e9be5cff0be4797a8aae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "oving1/main.cpp", "max_forks_repo_name": "odderikf/algdat", "max_forks_repo_head_hexsha": "9b5e5ea42ca0fefda3c1e9be5cff0be4797a8aae", "max_forks_repo_licenses": ["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.46875, "max_line_length": 109, "alphanum_fraction": 0.5291622481, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.5074490699749981}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n//\n// Copyright (c) 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// Projection example 4, reworked version of example 3\n// Now using svg mapper, multi polygons and specific transform strategy\n\n#include <fstream>\n\n#include <boost/foreach.hpp>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n#include <boost/geometry/geometries/multi_polygon.hpp>\n\n#include <boost/geometry/io/svg/svg_mapper.hpp>\n#include <boost/geometry/extensions/gis/latlong/latlong.hpp>\n\n#include <boost/geometry/extensions/gis/projections/parameters.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/robin.hpp>\n\n// Define a specific projection transformer\n// (NOTE: this might become part of the library)\ntemplate <typename Projection>\nstruct projection_transformer\n{\n    Projection const& m_prj;\n\n    inline projection_transformer(Projection const& prj)\n        : m_prj(prj)\n    {}\n\n    inline bool apply(typename Projection::geographic_point_type const& p1,\n                typename Projection::cartesian_point_type& p2) const\n    {\n        return m_prj.forward(p1, p2);\n    }\n};\n\nvoid read_wkt_and_project_and_map_svg(std::string const& wkt_filename,\n        std::string const& svg_filename)\n{\n    using namespace boost::geometry;\n\n    typedef model::ll::point<degree> point_ll_deg;\n    typedef model::d2::point_xy<double> point_xy;\n\n    typedef model::multi_polygon<model::polygon<point_ll_deg> > mp_ll;\n    typedef model::multi_polygon<model::polygon<point_xy> > mp_xy;\n\n    typedef projections::robin_spheroid<point_ll_deg, point_xy> robin;\n\n    std::vector<mp_ll> countries_in_ll;\n\n    // Read polygons from WKT\n    std::ifstream cpp_file(wkt_filename.c_str());\n    if (! cpp_file.is_open())\n    {\n        throw std::string(\"File not found: \") + wkt_filename;\n    }\n\n    while (! cpp_file.eof() )\n    {\n        std::string line;\n        std::getline(cpp_file, line);\n        if (boost::starts_with(line, \"MULTIPOLYGON\"))\n        {\n            countries_in_ll.resize(countries_in_ll.size() + 1);\n            boost::geometry::read_wkt(line, countries_in_ll.back());\n        }\n    }\n\n    robin prj(projections::init(\"+ellps=WGS84 +units=m\"));\n    projection_transformer<robin> projection(prj);\n\n    // Project the polygons, and at the same time get the bounding box (in xy)\n    std::vector<mp_xy> countries_in_xy;\n    model::box<point_xy> bbox;\n    assign_inverse(bbox);\n    BOOST_FOREACH(mp_ll const& country_ll, countries_in_ll) \n    {\n        mp_xy country_xy;\n        if (transform(country_ll, country_xy, projection))\n        {\n            expand(bbox, return_envelope<model::box<point_xy> >(country_xy));\n            countries_in_xy.push_back(country_xy);\n        }\n    }\n\n    // Create an SVG image\n    std::ofstream svg(svg_filename.c_str());\n    boost::geometry::svg_mapper<point_xy> mapper(svg, 1000, 800);\n    mapper.add(bbox);\n\n    BOOST_FOREACH(mp_xy const& country, countries_in_xy) \n    {\n        mapper.map(country, \"fill-opacity:0.6;fill:rgb(153,204,0);stroke:rgb(0,128,0);stroke-width:0.2\");\n    }\n}\n\nint main(int argc, char** argv)\n{\n    try\n    {\n        // Note, file location: trunk/libs/geometry/example/data\n        // update path below if necessary\n        read_wkt_and_project_and_map_svg(\n            \"../../../../example/data/world.wkt\",\n            \"world4.svg\");\n    }\n    catch(std::exception const& e)\n    {\n        std::cout << \"Exception: \" << e.what() << std::endl;\n        return 1;\n    }\n    catch(std::string const& s)\n    {\n        std::cout << \"Exception: \" << s << std::endl;\n        return 1;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "d72684cd7c54431e63aee159d6c1fe6908a24240", "size": 3882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/example/gis/projections/p04_example.cpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "extensions/example/gis/projections/p04_example.cpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "extensions/example/gis/projections/p04_example.cpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 30.328125, "max_line_length": 105, "alphanum_fraction": 0.6687274601, "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5074490589189935}}
{"text": "//=======================================================================\n// Copyright (c)\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 linear_programming_long_test.cpp\n * @brief\n * @author Piotr Godlewski\n * @version 1.0\n * @date 2014-04-03\n */\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/read_lp.hpp\"\n#include \"test_utils/get_test_dir.hpp\"\n#include \"test_utils/system.hpp\"\n\n#include \"paal/lp/glp.hpp\"\n#include \"paal/utils/parse_file.hpp\"\n\n#include <boost/mpl/list.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/range/numeric.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n\n#include <fstream>\n#include <unordered_map>\n\nusing lp_types = boost::mpl::list<paal::lp::glp>;\n\ntemplate <typename LP, typename RowBounds, typename ColBounds,\n          typename CostCoefs, typename Coefficients>\nvoid run_test(RowBounds &row_bounds, ColBounds &col_bounds,\n              CostCoefs &cost_coefs, Coefficients &coefs, double best_cost,\n              int rows_num, int cols_num, int non_zeros,\n              paal::lp::simplex_type type) {\n\n    LP lp(\"LP long test\", paal::lp::MINIMIZE);\n    std::unordered_map<std::string, paal::lp::col_id> col_ids;\n\n    std::string col_name;\n    for (auto c : col_bounds) {\n        col_name = c.first;\n        col_ids[col_name] =\n            lp.add_column(0., c.second.first, c.second.second, col_name);\n    }\n\n    int non_zero_cost_coefs = 0;\n    for (auto c : cost_coefs) {\n        lp.set_col_cost(col_ids[c.first], c.second);\n        if (!paal::utils::compare<double>().e(c.second, 0.)) {\n            ++non_zero_cost_coefs;\n        }\n    }\n\n    std::string row_name;\n    std::pair<double, double> row_bound;\n    for (auto row : row_bounds) {\n        std::tie(row_name, row_bound) = row;\n\n        paal::lp::linear_expression expr;\n\n        for (auto elem :\n             boost::make_iterator_range(coefs.equal_range(row_name))) {\n            expr += elem.second.second * col_ids[elem.second.first];\n        }\n\n        lp.add_row(row_bound.first <= std::move(expr) <= row_bound.second);\n    }\n\n    BOOST_CHECK_EQUAL(rows_num, lp.rows_number() + 1);\n    BOOST_CHECK_EQUAL(cols_num, lp.columns_number());\n    auto lp_non_zeros =\n        boost::accumulate(lp.get_rows(), 0, [&](int sum, paal::lp::row_id row) {\n        return sum + lp.get_row_degree(row);\n    });\n    BOOST_CHECK_EQUAL(non_zeros, lp_non_zeros + non_zero_cost_coefs);\n\n    auto status = lp.solve_simplex(type);\n    BOOST_CHECK_EQUAL(status, paal::lp::OPTIMAL);\n    static const double EPSILON = 6e-5;\n    BOOST_CHECK_CLOSE(best_cost, lp.get_obj_value(), EPSILON);\n}\n\nBOOST_AUTO_TEST_SUITE(linear_programming_long)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(linear_programming_long, LP, lp_types) {\n    std::string test_dir = paal::system::get_test_data_dir(\"LP\");\n    using paal::system::build_path;\n    paal::parse(build_path(test_dir, \"cases.txt\"),\n                [&](const std::string & fname, std::istream & is_test_cases) {\n        double best_cost;\n        int rows_num, cols_num, non_zeros;\n        is_test_cases >> best_cost >> rows_num >> cols_num >> non_zeros;\n\n        LOGLN(fname);\n        std::ifstream ifs(build_path(test_dir, \"/cases/\" + fname + \".mps\"));\n        assert(ifs.good());\n\n        std::unordered_map<std::string, std::pair<double, double>> row_bounds;\n        std::unordered_map<std::string, std::pair<double, double>> col_bounds;\n        std::unordered_map<std::string, double> cost_coefs;\n        std::unordered_multimap<std::string, std::pair<std::string, double>>\n            coefs;\n\n        paal::read_lp(ifs, row_bounds, col_bounds, cost_coefs, coefs);\n        LOGLN(\"primal\");\n        run_test<LP>(row_bounds, col_bounds, cost_coefs, coefs, best_cost,\n                     rows_num, cols_num, non_zeros, paal::lp::PRIMAL);\n        LOGLN(\"dual\");\n        run_test<LP>(row_bounds, col_bounds, cost_coefs, coefs, best_cost,\n                     rows_num, cols_num, non_zeros, paal::lp::DUAL);\n    });\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "415c01820c3357bedf7d0d53487cca46ade1f944", "size": 4203, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/linear_programming/lp/linear_programming_long_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/linear_programming/lp/linear_programming_long_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/linear_programming/lp/linear_programming_long_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": 34.7355371901, "max_line_length": 80, "alphanum_fraction": 0.6345467523, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481138, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5073667184800804}}
{"text": "#include <cmath>\n#include <iomanip>\n#include <iostream>\n\n#include <boost/numeric/odeint.hpp>\n#include <catch/catch.hpp>\n#include <rxcpp/rx.hpp>\n\n#include \"../include/Plant.hpp\"\n#include \"../include/pid.hpp\"\n#include \"../include/util/util.hpp\"\n\n#include \"calculations/analytical_solutions.cpp\"\n\n#ifdef PLOT\n#include \"../include/plotting/gnuplot-iostream.h\"\n#include \"../include/plotting/plot-helpers.hpp\"\n#endif  // PLOT\n\nusing namespace std::string_literals;\n\nnamespace ode = boost::numeric::odeint;\nusing CState = PIDState<>;                       // AKA U\nusing PState = SignalPt<std::array<double, 2>>;  // AKA X\n// NB:\n// PState = SignalPt<std::array<double, 2>>\n//          \u250c                \u2510\n//          \u2502        \u250c   \u2510   \u2502\n//        = \u2502  \u00b7 ,   \u2502 \u00b7 \u2502   \u2502\n//          \u2502        \u2502 \u00b7 \u2502   \u2502\n//          \u2502        \u2514   \u2518   \u2502\n//          \u2514                \u2518\n//            ^ Time   ^ [Position, Speed]\n//\n// On the other hand, sim::PState is just for Boost.odeint. It doesn't need\n// time, but must be augmented with the control variable:\n//\n// sim::Pstate = std::array<double, 3>\n//                \u250c   \u2510\n//                \u2502 \u00b7 \u2502  // Position\n//             =  \u2502 \u00b7 \u2502  // Speed\n//                \u2502 \u00b7 \u2502  // control variable for Boost.odeint.\n//                \u2514   \u2518\n\nconstexpr double dt = 0.001;  // seconds.\nconstexpr auto dts = util::double_to_duration(dt);\nconst auto now = chrono::steady_clock::now();\n\nconstexpr double mass = 1.;\nconstexpr double damp = 10. / mass;\nconstexpr double spring = 20. / mass;\nconstexpr double staticForce = 1. / mass;\nconstexpr auto simDuration = 2s;  // seconds\n\n// position_error : (PState, PState) \u2192 SignalPt<double>\ninline SignalPt<double> position_error(const std::tuple<PState, PState>& ab) {\n  auto& [a, b] = ab;\n  return {std::max(a.time, b.time), a.value[0] - b.value[0]};\n}\n\nstruct WorldInterface {\n  const rxcpp::subjects::behavior<PState> txSubject;\n  const rxcpp::observable<PState> setPoint =\n      // Setpoint to x = 1, for step response.\n      rxcpp::observable<>::just(PState{now, {1., 0.}});\n\n  WorldInterface(PState x0) : txSubject(x0) {}\n\n  void controlled_step(CState u) {\n    auto x = txSubject.get_value();\n    sim::PState xAugmented = {x.value[0], x.value[1], u.ctrlVal};\n\n    if ((x.time - now) >= simDuration)\n      txSubject.get_subscriber().on_completed();\n\n    // do_step uses the second argument for both input and output.\n    _stepper.do_step(_plant, xAugmented, 0, dt);\n    x.time += dts;\n    x.value = {xAugmented[0], xAugmented[1]};\n    txSubject.get_subscriber().on_next(x);\n  };\n\n  auto get_state_observable() { return txSubject.get_observable(); }\n  auto time_elapsed() { return txSubject.get_value().time - now; }\n\n private:\n  ode::runge_kutta4<sim::PState> _stepper;\n  const sim::Plant _plant = sim::Plant(staticForce, damp, spring);\n};\n\nvoid step_response_test(const std::string testTitle, const double Kp,\n                        const double Ki, const double Kd,\n                        const std::function<double(double)> expected_fn,\n                        const double margin) {\n  const CState u0 = {now, 0., 0., 0.};\n  const PState x0 = {now, {0., 0.}};\n  WorldInterface worldIface(x0);\n\n  std::vector<PState> plantStateRecord;\n  worldIface.get_state_observable().subscribe(\n      [&](PState x) { plantStateRecord.push_back(x); });\n\n  // A classical confiuration for a feedback controller is illustrated as:\n  //                  err   u\n  //   setPoint \u2500\u2500\u27a4 \u2295 \u2500\u2500\u27a4 C \u2500\u2500\u27a4 P \u2500\u2500\u252c\u2500\u2500\u27a4 plantState\n  //               -\u2191               \u2502\n  //                \u2502               \u2502\n  //                \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n  // If you open the loop and place an interface to the imperative world, \u25fc,\n  // at the endpoints, the controller becomes:\n  //\n  // setPoint  err   u\n  //    \u25fc \u2500\u27a4 \u2295 \u2500\u2500\u27a4 C \u2500\u2500\u27a4 \u25fc\n  //        -\u2191\n  //         \u2502 plantState\n  //         \u25fc\n  // which is in 1:1 correspondence with the code below (read backward from C)\n  //\n  const auto sControls =\n      worldIface\n          .get_state_observable()               // worldIface == \u25fc.\n          .combine_latest(worldIface.setPoint)  // \u2510 Combine state and setPt,\n          .map(&position_error)                 // \u2518   and then \u2295.\n          .observe_on(rxcpp::identity_current_thread())\n          .scan(u0, pid_algebra(Kp, Ki, Kd));  //   This is C\n\n  sControls.subscribe(\n      [&worldIface](CState u) { worldIface.controlled_step(u); });\n\n  {\n    auto simulatedPositions =\n        util::fmap([](auto x) { return x.value[0]; }, plantStateRecord);\n    auto theoreticalPositions = util::fmap(\n        [&](auto x) { return expected_fn(util::unchrono_sec(x.time - now)); },\n        plantStateRecord);\n\n    if constexpr (plot) {\n      const auto testData = util::fmap(\n          [](const auto& x) {\n            return std::make_pair(util::unchrono_sec(x.time - now), x.value[0]);\n          },\n          plantStateRecord);\n\n      plot_with_tube(testTitle, testData, expected_fn, margin);\n    }\n\n    REQUIRE(\n        util::compareVectors(simulatedPositions, theoreticalPositions, margin));\n  }\n}\n\nTEST_CASE(\n    \"Given system and controller parameters, simulation should reproduce \"\n    \"analytically computed step responses to within a margin of error. See \"\n    \"src/calculations for details. Simulations performed using FRx.\") {\n  SECTION(\"Test A (Proportional Control) FRx.\") {\n    constexpr double Kp = 300.;\n    constexpr double Ki = 0.;\n    constexpr double Kd = 0.;\n    const auto title = \"Test A; (Kp, Ki, Kd) = (300., 0., 0.); FRx\"s;\n    step_response_test(title, Kp, Ki, Kd, &analyt::test_A, 0.03);\n  }\n\n  SECTION(\"Test B (Proportional-Derivative Control) FRx.\") {\n    constexpr double Kp = 300.;\n    constexpr double Ki = 0.;\n    constexpr double Kd = 10.;\n    const auto title = \"Test B; (Kp, Ki, Kd) = (300., 0., 10.); FRx\"s;\n    step_response_test(title, Kp, Ki, Kd, &analyt::test_B, 0.03);\n  }\n\n  SECTION(\"Test C (Proportional-Integral Control) FRx.\") {\n    constexpr double Kp = 30.;\n    constexpr double Ki = 70.;\n    constexpr double Kd = 0.;\n    const auto title = \"Test C; (Kp, Ki, Kd) = (30., 70., 0.); FRx\"s;\n    step_response_test(title, Kp, Ki, Kd, &analyt::test_C, 0.03);\n  }\n\n  SECTION(\"Test D (Proportional-Integral-Derivative Control) FRx.\") {\n    constexpr double Kp = 350.;\n    constexpr double Ki = 300.;\n    constexpr double Kd = 50.;\n    const auto title = \"Test D; (Kp, Ki, Kd) = (350., 300., 50.); FRx\"s;\n    step_response_test(title, Kp, Ki, Kd, &analyt::test_D, 0.07);\n  }\n}\n", "meta": {"hexsha": "3a08c2502351a1a7eb1093200dab1c6dd25d1119", "size": 6425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pid-RxCpp.cpp", "max_stars_repo_name": "timtro/pid-unfolding", "max_stars_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pid-RxCpp.cpp", "max_issues_repo_name": "timtro/pid-unfolding", "max_issues_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pid-RxCpp.cpp", "max_forks_repo_name": "timtro/pid-unfolding", "max_forks_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_forks_repo_licenses": ["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.1755319149, "max_line_length": 80, "alphanum_fraction": 0.5914396887, "num_tokens": 1863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5073667067241666}}
{"text": "#ifndef ED_TITFI_HPP\n#define ED_TITFI_HPP\n#include <cstdint>\n#include <cassert>\n#include <algorithm>\n#include <map>\n#include <boost/dynamic_bitset.hpp>\n//#include \"BitOperations.h\"\n#include \"../Basis/AbstractBasis1D.hpp\"\n\ntemplate<typename UINT>\nclass TITFIsing\n{\nprivate:\n\tconst edlib::AbstractBasis1D<UINT>& basis_;\n\tdouble J_;\n\tdouble h_;\n\npublic:\n\tTITFIsing(const edlib::AbstractBasis1D<UINT>& basis, double J, double h)\n\t\t: basis_(basis), J_(J), h_(h)\n\t{\n\t\t\n\t}\n\n\tstd::map<std::size_t,double> getCol(UINT n) const\n\t{\n\t\tunsigned int N = basis_.getN();\n\n\t\tUINT a = basis_.getNthRep(n);\n\t\tconst boost::dynamic_bitset<> bs(N, a);\n\n\t\tstd::map<std::size_t, double> m;\n\t\tfor(unsigned int i = 0; i < N; i++)\n\t\t{\n\t\t\t//Next-nearest\n\t\t\t{\n\t\t\t\tunsigned int j = (i+1)%N;\n\t\t\t\tint sgn = (1-2*bs[i])*(1-2*bs[j]);\n\n\t\t\t\tm[n] += -J_*sgn; //ZZ\n\t\t\t\t\n\t\t\t\tUINT s = a;\n\t\t\t\ts ^= basis_.mask({i});\n\n\t\t\t\tint bidx;\n\t\t\t\tdouble coeff;\n\n\t\t\t\tstd::tie(bidx, coeff) = basis_.hamiltonianCoeff(s, n);\n\t\t\t\t\n\t\t\t\tif(bidx >= 0)\n\t\t\t\t\tm[bidx] += -h_*coeff;\n\t\t\t}\n\t\t}\n\t\treturn m;\n\t}\n};\n#endif //ED_TITFI_HPP\n", "meta": {"hexsha": "85e7b434e4ae6c6d34529f621c507473dfc60304", "size": 1067, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/edlib/Hamiltonians/TITFIsing.hpp", "max_stars_repo_name": "chaeyeunpark/ExactDiagonalization", "max_stars_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T08:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:47:05.000Z", "max_issues_repo_path": "include/edlib/Hamiltonians/TITFIsing.hpp", "max_issues_repo_name": "chaeyeunpark/ExactDiagonalization", "max_issues_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T19:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T19:02:14.000Z", "max_forks_repo_path": "include/edlib/Hamiltonians/TITFIsing.hpp", "max_forks_repo_name": "chaeyeunpark/ExactDiagonalization", "max_forks_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-22T18:59:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T18:59:11.000Z", "avg_line_length": 18.0847457627, "max_line_length": 73, "alphanum_fraction": 0.618556701, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5073667016858724}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed 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#include <boost/hana/integral.hpp>\n\n#include <boost/hana/detail/assert.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n    // Arithmetic\n    BOOST_HANA_CONSTANT_ASSERT(+int_<1> == int_<1>);\n    BOOST_HANA_CONSTANT_ASSERT(-int_<1> == int_<-1>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<1> + int_<2> == int_<3>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<1> - int_<2> == int_<-1>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<3> * int_<2> == int_<6>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<6> / int_<3> == int_<2>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<6> % int_<4> == int_<2>);\n    BOOST_HANA_CONSTANT_ASSERT(~int_<6> == int_<~6>);\n    BOOST_HANA_CONSTANT_ASSERT((int_<6> & int_<3>) == int_<6 & 3>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<6> | int_<3> == int_<6 | 3>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<6> ^ int_<3> == int_<6 ^ 3>);\n    BOOST_HANA_CONSTANT_ASSERT((int_<6> << int_<3>) == int_<(6 << 3)>);\n    BOOST_HANA_CONSTANT_ASSERT((int_<6> >> int_<3>) == int_<(6 >> 3)>);\n\n    // Comparison\n    BOOST_HANA_CONSTANT_ASSERT(int_<0> == int_<0>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<1> != int_<0>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<0> < int_<1>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<0> <= int_<1>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<0> <= int_<0>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<1> > int_<0>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<1> >= int_<0>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<0> >= int_<0>);\n\n    // Logical\n    BOOST_HANA_CONSTANT_ASSERT(int_<3> || int_<0>);\n    BOOST_HANA_CONSTANT_ASSERT(int_<3> && int_<1>);\n    BOOST_HANA_CONSTANT_ASSERT(!int_<0>);\n    BOOST_HANA_CONSTANT_ASSERT(!!int_<3>);\n}\n", "meta": {"hexsha": "78eb1c83681373bb9ad2057e2278599e3b307c11", "size": 1769, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/integral/operators.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/integral/operators.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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/integral/operators.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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.3111111111, "max_line_length": 78, "alphanum_fraction": 0.6749576032, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321843145405, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5073666925890498}}
{"text": "#ifndef MWTRANS_H_\n#define MWTRANS_H_\n\n#include <Eigen/Dense>\n#include <complex>\n#include <functional>\n\nclass MWtransIntComplex {\npublic:\n  MWtransIntComplex(double lb, double v, double abserr, double referr);\n\n  std::complex<double>\n  perform(std::function<std::complex<double>(double)> functor);\n\nprivate:\n  const int nzero_ = 100;\n  const int niter_ = 100;\n  const unsigned max_depth_ = 15;\n\n  Eigen::ArrayXd zeros_;\n  double lb_, ub_, v_;\n  const double abserr_;\n  const double referr_;\n};\n\n#endif", "meta": {"hexsha": "94e096f827ae942d2e0b17dc6baa26dba4157f6d", "size": 501, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mwtrans_complex.hpp", "max_stars_repo_name": "pan3rock/mWOI", "max_stars_repo_head_hexsha": "47f544cd29020616d2dfb4ce01e09da27ccf84c0", "max_stars_repo_licenses": ["MIT"], "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/mwtrans_complex.hpp", "max_issues_repo_name": "pan3rock/mWOI", "max_issues_repo_head_hexsha": "47f544cd29020616d2dfb4ce01e09da27ccf84c0", "max_issues_repo_licenses": ["MIT"], "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/mwtrans_complex.hpp", "max_forks_repo_name": "pan3rock/mWOI", "max_forks_repo_head_hexsha": "47f544cd29020616d2dfb4ce01e09da27ccf84c0", "max_forks_repo_licenses": ["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.2692307692, "max_line_length": 71, "alphanum_fraction": 0.7305389222, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5073666902098464}}
{"text": "//######################################################################\n//#   GT Writter Module \n//#   \n//#   Copyright (C) 2020 Siemens AG\n//#   SPDX-License-Identifier: MIT\n//#   Author 2020: This module has been developed by \n//#                Roman Kaskman under supervision of Slobodan Ilic\n//#######################################################################\n\n#include \"scene.h\"\n#include <cmath>\n#include \"frame.h\"\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n#define _USE_MATH_DEFINES\n\nScene::Scene(const Configuration &p_configuration, const std::string &p_scene_dir, \n\t\tconst std::vector<Model> &p_models, const std::vector<Eigen::Matrix4f> &p_camera_poses):\nconfiguration(p_configuration), models(p_models), frame_poses(p_camera_poses), scene_dir(p_scene_dir)\n{\n\tfor (const auto& model : models)\n\t{\n\t\tscaled_renderers.emplace_back(ModelRenderer(model, configuration, true));\n\t}\n\n}\n\nsize_t Scene::get_number_of_frames()\n{\n\treturn frame_poses.size();\n}\n\n\ninline int get_scaled_coordinate(int x, int cx, float focal_length_scale)\n{\n\treturn static_cast<int>(round(1.0f / focal_length_scale * (x - cx * (1.0f - focal_length_scale))));\n}\n\n\nVector4i get_bounding_box(const cv::Mat& scaled_depth, const Matrix3f& scaled_intrinsics, float focal_length_scale)\n{\n\tfloat cx = scaled_intrinsics(0, 2);\n\tfloat cy = scaled_intrinsics(1, 2);\n\n\tint min_y = scaled_depth.rows - 1;\n\tint min_x = scaled_depth.cols - 1;\n\tint max_y = 0;\n\tint max_x = 0;\n\n\tfor (int i = 0; i < scaled_depth.rows; ++i)\n\t{\n\t\tfor (int j = 0; j < scaled_depth.cols; ++j)\n\t\t{\n\t\t\tfloat val = scaled_depth.at<float>(i, j);\n\n\t\t\tif (isfinite(val) && val > 1e-3f)\n\t\t\t{\n\t\t\t\tif (i < min_y)\n\t\t\t\t{\n\t\t\t\t\tmin_y = i;\n\t\t\t\t}\n\t\t\t\telse if (i > max_y)\n\t\t\t\t{\n\t\t\t\t\tmax_y = i;\n\t\t\t\t}\n\n\t\t\t\tif (j < min_x)\n\t\t\t\t{\n\t\t\t\t\tmin_x = j;\n\t\t\t\t}\n\t\t\t\telse if (j > max_x)\n\t\t\t\t{\n\t\t\t\t\tmax_x = j;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tint min_y_scaled = get_scaled_coordinate(min_y, cy, focal_length_scale) - 1;\n\tint max_y_scaled = get_scaled_coordinate(max_y, cy, focal_length_scale) + 1;\n\n\tint min_x_scaled = get_scaled_coordinate(min_x, cx, focal_length_scale) - 1;\n\tint max_x_scaled = get_scaled_coordinate(max_x, cx, focal_length_scale) + 1;\n\n\treturn { min_x_scaled, min_y_scaled, max_x_scaled - min_x_scaled, max_y_scaled - min_y_scaled };\n}\n\n\nvector<Frame> Scene::convert_to_scene_frames()\n{\n\tsize_t number_of_frames = frame_poses.size();\n\tsize_t number_of_models = models.size();\n\n\tMatrix3f scaled_intrinsics = configuration.get_intrinsics();\n\tfloat focal_length_scale = configuration.get_focal_length_scale();\n\n\tscaled_intrinsics(0, 0) = focal_length_scale * scaled_intrinsics(0, 0);\n\tscaled_intrinsics(1, 1) = focal_length_scale * scaled_intrinsics(1, 1);\n\n\tvector<Frame> scene_frames(number_of_frames);\n\n\tfor (int frame_idx = 0; frame_idx < number_of_frames; frame_idx++)\n\t{\n\t\tFrame frame;\n\t\tframe.frame_id = frame_idx;\n\t\tframe.scene_dir = scene_dir;\n\n\t\tcout << \"Frame : \" << frame_idx << endl;\n\t\tMatrix4f world_to_cam = frame_poses[frame_idx].inverse();\n\n\t\tfor (int model_idx = 0; model_idx < number_of_models; model_idx++)\n\t\t{\n\t\t\tconst Model& model = models[model_idx];\n\n\t\t\tModelRenderer& scaled_renderer = scaled_renderers[model_idx];\n\n\t\t\tcv::Mat scaled_depth;\n\t\t\tcv::Mat scaled_color;\n\n\t\t\tMatrix4f model_pose = world_to_cam * model.canonical_pose;\n\t\t\tscaled_renderer.render(model_pose, scaled_depth, scaled_color);\n\t\t\t\n\t\t\tauto bbox = get_bounding_box(scaled_depth, scaled_intrinsics, focal_length_scale);\n\t\t\tframe.frame_models.emplace_back(FrameModel(model.model_id, model_pose, bbox));\n\t\t}\n\n\t\tscene_frames[frame_idx] = frame;\n\t}\n\n\treturn scene_frames;\n}\n", "meta": {"hexsha": "fa5ad94a7363510e4e2f3b197931a53ad4e0e2c5", "size": 3606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtwriter/src/scene-gt-writer/scene.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": "gtwriter/src/scene-gt-writer/scene.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": "gtwriter/src/scene-gt-writer/scene.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": 26.9104477612, "max_line_length": 115, "alphanum_fraction": 0.6805324459, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5073666896500711}}
{"text": "#include <algorithm>\n#include <boost/optional.hpp>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++)\n#define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++)\n#define EACH(e, a) for(auto&& e : a)\n#define ALL(a) std::begin(a), std::end(a)\n#define RALL(a) std::rbegin(a), std::rend(a)\n#define FILL(a, n) memset((a), n, sizeof(a))\n#define FILLZ(a) FILL(a, 0)\n#define INT(x) (static_cast<int>(x))\n#define PRECISION(x) std::fixed << std::setprecision(x)\n\nusing namespace std;\n\nusing ll = long long;\nusing VI = vector<int>;\nusing VI2D = vector<vector<int>>;\n\nconstexpr int INF = 2e9;\nconstexpr double EPS = 1e-10;\nconstexpr double PI = acos(-1.0);\n\nconstexpr int dx[] = {-1, 0, 1, 0};\nconstexpr int dy[] = {0, -1, 0, 1};\n\ntemplate <typename T>\nconstexpr int sign(T x) {\n\treturn x < 0 ? -1 : x > 0 ? 1 : 0;\n}\n\ntemplate <>\nconstexpr int sign(double x) {\n\treturn x < -EPS ? -1 : x > EPS ? 1 : 0;\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmax(T& m, U x) {\n\tm = max(m, x);\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmin(T& m, U x) {\n\tm = min(m, x);\n}\n\ntemplate <typename T>\nconstexpr T square(T x) {\n\treturn x * x;\n}\n\n// \u30a8\u30e9\u30c8\u30b9\u30c6\u30cd\u30b9\u306e\u7be9\ntemplate <typename T>\nstd::vector<T> sieve_of_eratosthenes(T n) {\n\tstd::vector<T> sieve(n, 0);\n\n\tfor(int i = 2; i < n; i++) {\n\t\tsieve[i] = i;\n\t}\n\n\tT i = 2;\n\twhile(i * i < n) {\n\t\tif(sieve[i]) {\n\t\t\tfor(T j = i * i; j < n; j += i) {\n\t\t\t\tsieve[j] = 0;\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\n\treturn sieve;\n}\n\n// \u7d20\u6570\u30ea\u30b9\u30c8\ntemplate <typename T>\nstd::vector<T> prime_list(T n) {\n\tstd::vector<T> primes = sieve_of_eratosthenes(n);\n\tprimes.erase(std::remove(primes.begin(), primes.end(), 0), primes.end());\n\treturn primes;\n}\n\nint main() {\n\tint q;\n\tcin >> q;\n\tVI l(q);\n\tVI r(q);\n\tREP(i, q) { cin >> l[i] >> r[i]; }\n\tVI sieve = sieve_of_eratosthenes(100030);\n\tVI primes = prime_list(100030);\n\tVI count(100001, 0);\n\tfor(int i = 1; i <= 100000; i += 2) {\n\t\tcount[i] += (sieve[i] && sieve[(i + 1) / 2]) ? 1 : 0;\n\t}\n\tVI s(100002, 0);\n\tfor(int i = 1; i <= 100001; i++) {\n\t\ts[i] = s[i - 1] + count[i - 1];\n\t}\n\tREP(i, q) { cout << s[r[i] + 1] - s[l[i]] << endl; }\n\treturn 0;\n}\n", "meta": {"hexsha": "bfb7f990597a30183bb42cf9cc0e40bad9b6a60b", "size": 2518, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABC084/D.cpp", "max_stars_repo_name": "arlechann/atcoder", "max_stars_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "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": "AtCoder/ABC084/D.cpp", "max_issues_repo_name": "arlechann/atcoder", "max_issues_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "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": "AtCoder/ABC084/D.cpp", "max_forks_repo_name": "arlechann/atcoder", "max_forks_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "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": 20.6393442623, "max_line_length": 76, "alphanum_fraction": 0.5992851469, "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5073666843318897}}
{"text": "//   Copyright (c) 2018 Shahrzad Shirzad\n//\n//   Distributed under the Boost Software License, Version 1.0.0. (See accompanying\n//   file LICENSE_1_0.0.txt or copy at http://www.boost.org/LICENSE_1_0.0.txt)\n\n#include <phylanx/phylanx.hpp>\n#include <hpx/hpx_init.hpp>\n\n#include <iostream>\n\n#include <blaze/Math.h>\n#include <boost/program_options.hpp>\n#include <cstdint>\n#include <string>\n\n///////////////////////////////////////////////////////////////////////////////\nchar const* const read_x_code = R\"(\n    //\n    // Read input-data from given CSV file\n    //\n    define(read_x, filepath, row_start, row_stop, col_start, col_stop,\n        slice(file_read_csv(filepath), make_list(row_start , row_stop),\n              make_list(col_start , col_stop))\n    )\n    read_x\n)\";\n\n\nchar const* const als_code = R\"(\n    //\n    // Alternating Least squares algorithm\n    //\n    define(als, ratings, regularization, num_factors, iterations, alpha, enable_output,\n        block(\n            define(num_users, shape(ratings, 0)),\n            define(num_items, shape(ratings, 1)),\n            define(conf, alpha * ratings),\n\n            define(conf_u, constant(0.0, make_list(num_items))),\n            define(conf_i, constant(0.0,make_list(num_users))),\n\n            define(c_u, constant(0.0, make_list(num_items, num_items))),\n            define(c_i, constant(0.0, make_list(num_users, num_users))),\n            define(p_u, constant(0.0, make_list(num_items))),\n            define(p_i, constant(0.0, make_list(num_users))),\n\n            set_seed(0),\n            define(X, random(make_list(num_users, num_factors))),\n            define(Y, random(make_list(num_items, num_factors))),\n            define(I_f, identity(num_factors)),\n            define(I_i, identity(num_items)),\n            define(I_u, identity(num_users)),\n            define(k, 0),\n            define(i, 0),\n            define(u, 0),\n\n            define(XtX, constant(0.0, make_list(num_factors, num_factors))),\n            define(YtY, constant(0.0, make_list(num_factors, num_factors))),\n            define(A, constant(0.0, make_list(num_factors, num_factors))),\n            define(b, constant(0.0, make_list(num_factors))),\n\n            while(k < iterations,\n                block(\n                    if(enable_output,\n                            block(\n                                    cout(\"iteration \",k),\n                                    cout(\"X: \",X),\n                                    cout(\"Y: \",Y)\n                            )\n                    ),\n                    store(YtY, dot(transpose(Y), Y) + regularization * I_f),\n                    store(XtX, dot(transpose(X), X) + regularization * I_f),\n\n                    while(u < num_users,\n                        block(\n                            store(conf_u, slice_row(conf, u)),\n                            store(c_u, diag(conf_u)),\n                            store(p_u, __ne(conf_u,0.0,true)),\n                            store(A, dot(dot(transpose(Y), c_u), Y)+ YtY),\n                            store(b, dot(dot(transpose(Y), (c_u + I_i)), transpose(p_u))),\n                            store(slice(X, list(u, u + 1, 1),nil), dot(inverse(A), b)),\n                            store(u, u + 1)\n                        )\n                    ),\n                    store(u, 0),\n                    while(i < num_items,\n                        block(\n                            store(conf_i, slice_column(conf, i)),\n                            store(c_i, diag(conf_i)),\n                            store(p_i, __ne(conf_i, 0.0, true)),\n                            store(A, dot(dot(transpose(X), c_i),X) + XtX),\n                            store(b, dot(dot(transpose(X), (c_i + I_u)), transpose(p_i))),\n                            store(slice(Y, list(i, i + 1, 1),nil), dot(inverse(A), b)),\n                            store(i, i + 1)\n                        )\n                    ),\n                    store(i, 0),\n                    store(k, k + 1)\n                )\n            ),\n            list(X, Y)\n        )\n    )\n    als\n)\";\n\nint hpx_main(boost::program_options::variables_map& vm)\n{\n    if (vm.count(\"data_csv\") == 0)\n    {\n        std::cerr << \"Please specify '--data_csv=data-file'\";\n        return hpx::finalize();\n    }\n\n    // evaluate generated execution tree\n    auto row_start = static_cast<int64_t>(0);\n    auto col_start = static_cast<int64_t>(0);\n    auto row_stop = vm[\"row_stop\"].as<std::int64_t>();\n    auto col_stop = vm[\"col_stop\"].as<std::int64_t>();\n\n    auto regularization = vm[\"regularization\"].as<double>();\n    auto iterations = vm[\"iterations\"].as<int64_t>();\n    auto num_factors = vm[\"factors\"].as<int64_t>();\n    auto alpha = vm[\"alpha\"].as<double>();\n    auto filepath = vm[\"data_csv\"].as<std::string>();\n\n    bool enable_output = vm.count(\"enable_output\") != 0;\n\n    // compile the given code\n    phylanx::execution_tree::compiler::function_list snippets;\n    auto const& code_read_x =\n        phylanx::execution_tree::compile(\"read_x\", read_x_code, snippets);\n    auto read_x = code_read_x.run();\n\n    auto ratings = read_x(filepath, row_start, row_stop, col_start, col_stop);\n\n    auto const& code_als = phylanx::execution_tree::compile(als_code, snippets);\n    auto als = code_als.run();\n\n    hpx::evaluate_active_counters(true, \"start\");\n    hpx::util::high_resolution_timer t;\n    auto result = als(\n        ratings, regularization, num_factors, iterations, alpha, enable_output);\n    auto time_diff = t.elapsed();\n    std::cout << t.elapsed();\n\n    hpx::evaluate_active_counters(true, \" finish\");\n\n    auto result_r = phylanx::execution_tree::extract_list_value(result);\n    auto it = result_r.begin();\n    std::cout << \"X: \\n\"\n              << phylanx::execution_tree::extract_numeric_value(*it++)\n              << \"\\nY: \\n\"\n              << phylanx::execution_tree::extract_numeric_value(*it)\n              << std::endl;\n\n    return hpx::finalize();\n}\n\nint main(int argc, char* argv[])\n{\n    // command line handling\n    boost::program_options::options_description desc(\"usage: als [options]\");\n    desc.add_options()\n            (\"enable_output,e\", \"enable progress output (default: false)\")\n            (\"iterations,i\",\n             boost::program_options::value<std::int64_t>()->default_value(3),\n             \"number of iterations (default: 10.0)\")\n            (\"factors,f\",\n             boost::program_options::value<std::int64_t>()->default_value(10),\n             \"number of factors (default: 10)\")\n            (\"alpha,a\",\n             boost::program_options::value<double>()->default_value(40),\n             \"alpha (default: 40)\")\n            (\"regularization,r\",\n             boost::program_options::value<double>()->default_value(0.1),\n             \"regularization (default: 0.1)\")\n            (\"data_csv\",\n             boost::program_options::value<std::string>(),\n             \"file name for reading data\")\n            (\"row_stop\",\n             boost::program_options::value<std::int64_t>()->default_value(10),\n             \"row_stop (default: 10)\")\n            (\"col_stop\",\n             boost::program_options::value<std::int64_t>()->default_value(100),\n             \"col_stop (default: 100)\")\n            ;\n    return hpx::init(desc, argc, argv);\n}\n", "meta": {"hexsha": "29b08b46f579343c8a9b2d5dd82730851f4981a5", "size": 7242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/algorithms/als/als_csv.cpp", "max_stars_repo_name": "frzfrsfra4/phylanx", "max_stars_repo_head_hexsha": "001fe7081f3a24e56157cdb21b2d126b8953ff5d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-17T21:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-17T21:19:57.000Z", "max_issues_repo_path": "examples/algorithms/als/als_csv.cpp", "max_issues_repo_name": "frzfrsfra4/phylanx", "max_issues_repo_head_hexsha": "001fe7081f3a24e56157cdb21b2d126b8953ff5d", "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/algorithms/als/als_csv.cpp", "max_forks_repo_name": "frzfrsfra4/phylanx", "max_forks_repo_head_hexsha": "001fe7081f3a24e56157cdb21b2d126b8953ff5d", "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.1157894737, "max_line_length": 90, "alphanum_fraction": 0.5256835128, "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5073504872751169}}
{"text": "//\n//  Copyright (c) 2018-2019, Cem Bassoy, cem.bassoy@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <iostream>\n\nint main()\n{\n\tusing namespace boost::numeric::ublas;\n\n\tusing format_t  = column_major;\n\tusing value_t   = float;\n\tusing tensor_t = tensor<value_t,format_t>;\n\tusing matrix_t = matrix<value_t,format_t>;\n\tusing namespace boost::numeric::ublas::index;\n\n\t// Tensor-Vector-Multiplications - Including Transposition\n\t{\n\n\t\tauto n = shape{3,4,2};\n\t\tauto A = tensor_t(n,1);\n\t\tauto B1 = matrix_t(n[1],n[2],2);\n\t\tauto v1 = tensor_t(shape{n[0],1},2);\n\t\tauto v2 = tensor_t(shape{n[1],1},2);\n//\t\tauto v3 = tensor_t(shape{n[2],1},2);\n\n\t\t// C1(j,k) = B1(j,k) + A(i,j,k)*v1(i);\n\t\t// tensor_t C1 = B1 + prod(A,vector_t(n[0],1),1);\n//\t\ttensor_t C1 = B1 + A(_i,_,_) * v1(_i,_);\n\n\t\t// C2(i,k) = A(i,j,k)*v2(j) + 4;\n\t\t//tensor_t C2 = prod(A,vector_t(n[1],1),2) + 4;\n//\t\ttensor_t C2 = A(_,_i,_) * v2(_i,_) + 4;\n\n\t\t// not yet implemented!\n\t\t// C3() = A(i,j,k)*T1(i)*T2(j)*T2(k);\t\t\n\t\t// tensor_t C3 = prod(prod(prod(A,v1,1),v2,1),v3,1);\n\t\t// tensor_t C3 = A(_i,_j,_k) * v1(_i,_) * v2(_j,_) * v3(_k,_);\n\n\t\t// formatted output\n\t\tstd::cout << \"% --------------------------- \" << std::endl;\n\t\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\t\tstd::cout << \"% C1(j,k) = B1(j,k) + A(i,j,k)*v1(i);\" << std::endl << std::endl;\n//\t\tstd::cout << \"C1=\" << C1 << \";\" << std::endl << std::endl;\n\n\t\t// formatted output\n\t\tstd::cout << \"% --------------------------- \" << std::endl;\n\t\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\t\tstd::cout << \"% C2(i,k) = A(i,j,k)*v2(j) + 4;\" << std::endl << std::endl;\n//\t\tstd::cout << \"C2=\" << C2 << \";\" << std::endl << std::endl;\n\n\t}\n\n\n\t// Tensor-Matrix-Multiplications - Including Transposition\n\t{\n\t\tauto n = shape{3,4,2};\n\t\tauto m = 5u;\n\t\tauto A = tensor_t(n,2);\n\t\tauto B  = tensor_t(shape{n[1],n[2],m},2);\n\t\tauto B1 = tensor_t(shape{m,n[0]},1);\n\t\tauto B2 = tensor_t(shape{m,n[1]},1);\n\n\n\t\t// C1(l,j,k) = B(j,k,l) + A(i,j,k)*B1(l,i);\n\t\t// tensor_t C1 = B + prod(A,B1,1);\n//\t\ttensor_t C1 = B + A(_i,_,_) * B1(_,_i);\n\n\t\t// C2(i,l,k) = A(i,j,k)*B2(l,j) + 4;\n\t\t// tensor_t C2 = prod(A,B2) + 4;\n//\t\ttensor_t C2 =  A(_,_j,_) * B2(_,_j) + 4;\n\n\t\t// C3(i,l1,l2) = A(i,j,k)*T1(l1,j)*T2(l2,k);\n\t\t// not yet implemented.\n\n\t\t// formatted output\n\t\tstd::cout << \"% --------------------------- \" << std::endl;\n\t\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\t\tstd::cout << \"% C1(l,j,k) = B(j,k,l) + A(i,j,k)*B1(l,i);\" << std::endl << std::endl;\n//\t\tstd::cout << \"C1=\" << C1 << \";\" << std::endl << std::endl;\n\n\t\t// formatted output\n\t\tstd::cout << \"% --------------------------- \" << std::endl;\n\t\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\t\tstd::cout << \"% C2(i,l,k) = A(i,j,k)*B2(l,j) + 4;\" << std::endl << std::endl;\n//\t\tstd::cout << \"C2=\" << C2 << \";\" << std::endl << std::endl;\n\n//\t\t// formatted output\n//\t\tstd::cout << \"% --------------------------- \" << std::endl;\n//\t\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n//\t\tstd::cout << \"% C3(i,l1,l2) = A(i,j,k)*T1(l1,j)*T2(l2,k);\" << std::endl << std::endl;\n//\t\tstd::cout << \"C3=\" << C3 << \";\" << std::endl << std::endl;\n\t}\n\n\n\t// Tensor-Tensor-Multiplications Including Transposition\n\t{\n\t\tauto na = shape{3,4,5};\n\t\tauto nb = shape{4,6,3,2};\n\t\tauto A = tensor_t(na,2);\n\t\tauto B = tensor_t(nb,3);\n\t\tauto T1 = tensor_t(shape{na[2],na[2]},2);\n\t\tauto T2 = tensor_t(shape{na[2],nb[1],nb[3]},2);\n\n\n\t\t// C1(j,l) = T1(j,l) + A(i,j,k)*A(i,j,l) + 5;\n\t\t// tensor_t C1 = T1 + prod(A,A,perm_t{1,2}) + 5;\n//\t\ttensor_t C1 = T1 + A(_i,_j,_m)*A(_i,_j,_l) + 5;\n\n\t\t// formatted output\n\t\tstd::cout << \"% --------------------------- \" << std::endl;\n\t\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\t\tstd::cout << \"% C1(k,l) = T1(k,l) + A(i,j,k)*A(i,j,l) + 5;\" << std::endl << std::endl;\n//\t\tstd::cout << \"C1=\" << C1 << \";\" << std::endl << std::endl;\n\n\n\t\t// C2(k,l,m) = T2(k,l,m) + A(i,j,k)*B(j,l,i,m) + 5;\n\t\t//tensor_t C2 = T2 + prod(A,B,perm_t{1,2},perm_t{3,1}) + 5;\n//\t\ttensor_t C2 = T2 + A(_i,_j,_k)*B(_j,_l,_i,_m) + 5;\n\n\t\t// formatted output\n\t\tstd::cout << \"% --------------------------- \" << std::endl;\n\t\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\t\tstd::cout << \"%  C2(k,l,m) = T2(k,l,m) + A(i,j,k)*B(j,l,i,m) + 5;\" << std::endl << std::endl;\n//\t\tstd::cout << \"C2=\" << C2 << \";\" << std::endl << std::endl;\n\n\t}\n}\n", "meta": {"hexsha": "1d95fc06b019af91c3cc843d66c8273fd2274780", "size": 4799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublas/examples/tensor/einstein_notation.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/ublas/examples/tensor/einstein_notation.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/ublas/examples/tensor/einstein_notation.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": 34.2785714286, "max_line_length": 95, "alphanum_fraction": 0.485726193, "num_tokens": 1814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5073339485739415}}
{"text": "/**\n * @author Alessandro Bianco\n */\n\n/**\n * @addtogroup DFNs\n * @{\n */\n\n#include \"EssentialMatrixDecomposition.hpp\"\n\n#include <Errors/Assert.hpp>\n#include <Macros/YamlcppMacros.hpp>\n\n#include <opencv2/calib3d.hpp>\n#include <Eigen/Geometry>\n\n#include <stdlib.h>\n#include <fstream>\n\nusing namespace PoseWrapper;\nusing namespace MatrixWrapper;\nusing namespace CorrespondenceMap2DWrapper;\nusing namespace Converters;\nusing namespace Helpers;\n\nnamespace CDFF\n{\nnamespace DFN\n{\nnamespace CamerasTransformEstimation\n{\n\nEssentialMatrixDecomposition::EssentialMatrixDecomposition()\n{\n\tparameters = DEFAULT_PARAMETERS;\n\n\tparametersHelper.AddParameter<int>(\"GeneralParameters\", \"NumberOfTestPoints\", parameters.numberOfTestPoints, DEFAULT_PARAMETERS.numberOfTestPoints);\n\tparametersHelper.AddParameter<double>(\"FirstCameraMatrix\", \"FocalLengthX\", parameters.firstCameraMatrix.focalLengthX, DEFAULT_PARAMETERS.firstCameraMatrix.focalLengthX);\n\tparametersHelper.AddParameter<double>(\"FirstCameraMatrix\", \"FocalLengthY\", parameters.firstCameraMatrix.focalLengthY, DEFAULT_PARAMETERS.firstCameraMatrix.focalLengthY);\n\tparametersHelper.AddParameter<double>(\"FirstCameraMatrix\", \"PrinciplePointX\", parameters.firstCameraMatrix.principlePoint.x, DEFAULT_PARAMETERS.firstCameraMatrix.principlePoint.x);\n\tparametersHelper.AddParameter<double>(\"FirstCameraMatrix\", \"PrinciplePointY\", parameters.firstCameraMatrix.principlePoint.y, DEFAULT_PARAMETERS.firstCameraMatrix.principlePoint.y);\n\tparametersHelper.AddParameter<double>(\"SecondCameraMatrix\", \"FocalLengthX\", parameters.secondCameraMatrix.focalLengthX, DEFAULT_PARAMETERS.secondCameraMatrix.focalLengthX);\n\tparametersHelper.AddParameter<double>(\"SecondCameraMatrix\", \"FocalLengthY\", parameters.secondCameraMatrix.focalLengthY, DEFAULT_PARAMETERS.secondCameraMatrix.focalLengthY);\n\tparametersHelper.AddParameter<double>(\"SecondCameraMatrix\", \"PrinciplePointX\", parameters.secondCameraMatrix.principlePoint.x, DEFAULT_PARAMETERS.secondCameraMatrix.principlePoint.x);\n\tparametersHelper.AddParameter<double>(\"SecondCameraMatrix\", \"PrinciplePointY\", parameters.secondCameraMatrix.principlePoint.y, DEFAULT_PARAMETERS.secondCameraMatrix.principlePoint.y);\n\n\tfirstCameraMatrix = ConvertToMat(DEFAULT_PARAMETERS.firstCameraMatrix);\n\tsecondCameraMatrix = ConvertToMat(DEFAULT_PARAMETERS.secondCameraMatrix);\n\n\tconfigurationFilePath = \"\";\n}\n\nEssentialMatrixDecomposition::~EssentialMatrixDecomposition()\n{\n}\n\nvoid EssentialMatrixDecomposition::configure()\n{\n\tparametersHelper.ReadFile(configurationFilePath);\n\tValidateParameters();\n\n\tfirstCameraMatrix = ConvertToMat(parameters.firstCameraMatrix);\n\tsecondCameraMatrix = ConvertToMat(parameters.secondCameraMatrix);\n}\n\nvoid EssentialMatrixDecomposition::process()\n{\n\t// Read data from input port\n\tcv::Mat correspondenceMap = Convert(&inMatches);\n\tcv::Mat fundamentalMatrix = ConvertToMat(&inFundamentalMatrix);\n\n\t// Process data\n\tValidateInputs(fundamentalMatrix, correspondenceMap);\n\tstd::vector<cv::Mat> transformsList = ComputeTransformMatrix(fundamentalMatrix);\n\tint validTransformIndex = FindValidTransform(transformsList, correspondenceMap);\n\n\t// Write data to output port\n\tif (validTransformIndex < 0)\n\t{\n\t\t// outTransform =  new Transform3D();\n\t\toutSuccess = false;\n\t}\n\telse\n\t{\n\t\tPose3DConstPtr tmp = matToTransform3DConverter.Convert(transformsList.at(validTransformIndex));\n\t\tCopy(*tmp, outTransform);\n\t\tdelete(tmp);\n\t\toutSuccess = true;\n\t}\n}\n\nconst EssentialMatrixDecomposition::EssentialMatrixDecompositionOptionsSet EssentialMatrixDecomposition::DEFAULT_PARAMETERS =\n{\n\t/*.numberOfTestPoints =*/ 20,\n\t//.firstCameraMatrix =\n\t{\n\t\t/*.focalLengthX =*/ 1.0,\n\t\t/*.focalLengthY =*/ 1.0,\n\t\t/*.principlePoint =*/ cv::Point2d(0, 0)\n\t},\n\t//.secondCameraMatrix =\n\t{\n\t\t/*.focalLengthX =*/ 1.0,\n\t\t/*.focalLengthY =*/ 1.0,\n\t\t/*.principlePoint =*/ cv::Point2d(0, 0)\n\t}\n};\n\ncv::Mat EssentialMatrixDecomposition::ConvertToMat(CameraMatrix cameraMatrix)\n{\n\tcv::Mat conversion(3, 3, CV_64FC1, cv::Scalar(0));\n\tconversion.at<double>(0,0) = cameraMatrix.focalLengthX;\n\tconversion.at<double>(1,1) = cameraMatrix.focalLengthY;\n\tconversion.at<double>(0,2) = cameraMatrix.principlePoint.x;\n\tconversion.at<double>(1,2) = cameraMatrix.principlePoint.y;\n\tconversion.at<double>(2,2) = 1.0;\n\treturn conversion;\n}\n\ncv::Mat EssentialMatrixDecomposition::ConvertToMat(MatrixWrapper::Matrix3dConstPtr matrix)\n{\n\tcv::Mat cvMatrix(3, 3, CV_64FC1);\n\tfor (unsigned row = 0; row < 3; row++)\n\t{\n\t\tfor (unsigned column = 0; column < 3; column++)\n\t\t{\n\t\t\tcvMatrix.at<double>(row,column) = GetElement(*matrix, row, column);\n\t\t}\n\t}\n\treturn cvMatrix;\n}\n\ncv::Mat EssentialMatrixDecomposition::Convert(CorrespondenceMap2DConstPtr correspondenceMap)\n{\n\tcv::Mat cvCorrespondenceMap(4, GetNumberOfCorrespondences(*correspondenceMap), CV_64FC1);\n\tfor (int correspondenceIndex = 0; correspondenceIndex < GetNumberOfCorrespondences(*correspondenceMap); correspondenceIndex++)\n\t{\n\t\tBaseTypesWrapper::Point2D firstPoint = GetSource(*correspondenceMap, correspondenceIndex);\n\t\tBaseTypesWrapper::Point2D secondPoint = GetSink(*correspondenceMap, correspondenceIndex);\n\t\tcvCorrespondenceMap.at<double>(0, correspondenceIndex) = firstPoint.x;\n\t\tcvCorrespondenceMap.at<double>(1, correspondenceIndex) = firstPoint.y;\n\t\tcvCorrespondenceMap.at<double>(2, correspondenceIndex) = secondPoint.x;\n\t\tcvCorrespondenceMap.at<double>(3, correspondenceIndex) = secondPoint.y;\n\t}\n\treturn cvCorrespondenceMap;\n}\n\nstd::vector<cv::Mat> EssentialMatrixDecomposition::ComputeTransformMatrix(cv::Mat fundamentalMatrix)\n{\n\tcv::Mat essentialMatrix = secondCameraMatrix.t() * fundamentalMatrix * firstCameraMatrix;\n\n\tcv::Mat firstRotationMatrix, secondRotationMatrix, translationMatrix;\n\tcv::decomposeEssentialMat(essentialMatrix, firstRotationMatrix, secondRotationMatrix, translationMatrix);\n\n\tstd::vector<cv::Mat> projectionMatricesList(4);\n\tcv::hconcat(firstRotationMatrix, translationMatrix, projectionMatricesList[0]);\n\tcv::hconcat(firstRotationMatrix, -translationMatrix, projectionMatricesList[1]);\n\tcv::hconcat(secondRotationMatrix, translationMatrix, projectionMatricesList[2]);\n\tcv::hconcat(secondRotationMatrix, -translationMatrix, projectionMatricesList[3]);\n\n\treturn projectionMatricesList;\n}\n\nint EssentialMatrixDecomposition::FindValidTransform(std::vector<cv::Mat> projectionsList, cv::Mat correspondenceMap)\n{\n\tstatic const float EPSILON = 1e-2;\n\n\tint validMatrixIndex = -1;\n\tbool validMatrixFound = false;\n\tfor (unsigned matrixIndex = 0; matrixIndex < projectionsList.size(); matrixIndex++)\n\t{\n\t\tcv::Mat currentProjectionMatrix = projectionsList.at(matrixIndex);\n\t\tdouble rotationDeterminant = cv::determinant( currentProjectionMatrix( cv::Rect(0,0,2,2) ));\n\t\tbool orientationPreserved = std::abs(rotationDeterminant - 1) < EPSILON;\n\n\t\tbool matrixIsValid = orientationPreserved && ProjectionMatrixIsValidForTestPoints(currentProjectionMatrix, correspondenceMap);\n\n\t\tif (matrixIsValid)\n\t\t{\n\t\t\tif (validMatrixFound)\n\t\t\t{\n\t\t\t\t// There should only be one valid matrix. If multiple valid matrices are found, the decomposition has failed.\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tvalidMatrixFound = true;\n\t\t\tvalidMatrixIndex = matrixIndex;\n\t\t}\n\t}\n\n\treturn validMatrixIndex;\n}\n\n//Projection test as described by described in Richard Hartley and Andrew Zisserman, in \"Multiple View Geometry in Computer Vision\".\nbool EssentialMatrixDecomposition::ProjectionMatrixIsValidForTestPoints(cv::Mat projectionMatrix, cv::Mat correspondenceMap)\n{\n\tstatic const float EPSILON = 1e-2;\n\n\tdouble rotationDeterminant = cv::determinant( projectionMatrix(cv::Rect(0,0,3,3)) );\n\tint rotationDeterminantSign = rotationDeterminant >= 0 ? 1 : -1;\n\tdouble principleRayX = projectionMatrix.at<double>(2, 0);\n\tdouble principleRayY = projectionMatrix.at<double>(2, 1);\n\tdouble principleRayZ = projectionMatrix.at<double>(2, 2);\n\tdouble principleRayNorm = std::sqrt (principleRayX*principleRayX + principleRayY*principleRayY + principleRayZ*principleRayZ);\n\n\tcv::Mat identityProjection(3, 4, CV_64FC1, cv::Scalar(0));\n\tidentityProjection.at<double>(0,0) = 1;\n\tidentityProjection.at<double>(1,1) = 1;\n\tidentityProjection.at<double>(2,2) = 1;\n\n\tunsigned testPointsNumber = (correspondenceMap.cols > parameters.numberOfTestPoints) ? parameters.numberOfTestPoints : correspondenceMap.cols;\n\tcv::Mat testPointCloudMatrix;\n\tcv::triangulatePoints(\n\t\tfirstCameraMatrix * identityProjection,\n\t\tsecondCameraMatrix * projectionMatrix,\n\t\tcorrespondenceMap(cv::Rect(0, 0, testPointsNumber, 2 )),\n\t\tcorrespondenceMap(cv::Rect(0, 2, testPointsNumber, 2 )),\n\t\ttestPointCloudMatrix\n\t);\n\n\tbool matrixIsValid = false;\n\tbool matrixIsInvalid = false;\n\tunsigned validPointsCount = 0;\n\tunsigned invalidPointsCount = 0;\n\tfor (unsigned pointIndex = 0; pointIndex < testPointCloudMatrix.cols && !matrixIsValid && !matrixIsInvalid; pointIndex++)\n\t{\n\t\tcv::Mat testPoint = testPointCloudMatrix(cv::Rect(pointIndex, 0, 1, 4));\n\t\tcv::Mat projectedPoint = projectionMatrix * testPoint;\n\t\tfloat t = testPoint.at<double>(3, 0);\n\t\tfloat w = projectedPoint.at<double>(2, 0);\n\t\tdouble depth = (rotationDeterminantSign * w ) / (t * principleRayNorm);\n\n\t\tdouble scale = 4;\n\t\tcv::Mat scaledTestPoint = scale * testPoint;\n\t\tcv::Mat scaledProjectedPoint = projectionMatrix * scaledTestPoint;\n\t\tdouble scaledT = scaledTestPoint.at<double>(3, 0);\n\t\tdouble scaledW = scaledProjectedPoint.at<double>(2, 0);\n\t\tdouble scaledDepth = (rotationDeterminantSign * scaledW ) / (scaledT * principleRayNorm);\n\n\t\tbool validPoint = (depth < scaledDepth + EPSILON && depth > scaledDepth - EPSILON && depth > 0);\n\t\tif (validPoint)\n\t\t{\n\t\t\tvalidPointsCount++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tinvalidPointsCount++;\n\t\t}\n\t\tmatrixIsValid = validPointsCount >= testPointsNumber / 2;\n\t\tmatrixIsInvalid = invalidPointsCount >= testPointsNumber / 2;\n\t}\n\n\treturn matrixIsValid || !matrixIsInvalid;\n}\n\nvoid EssentialMatrixDecomposition::ValidateParameters()\n{\n\tASSERT(parameters.numberOfTestPoints > 1, \"EssentialMatrixComputation Configuration Error: number of test points has to be positive and greater than 1\");\n\tASSERT(parameters.firstCameraMatrix.focalLengthX > 0 && parameters.firstCameraMatrix.focalLengthY > 0, \"EssentialMatrixComputation Configuration Error: focalLength is not positive\");\n\tASSERT(parameters.secondCameraMatrix.focalLengthX > 0 && parameters.secondCameraMatrix.focalLengthY > 0, \"EssentialMatrixComputation Configuration Error: focalLength is not positive\");\n}\n\nvoid EssentialMatrixDecomposition::ValidateInputs(cv::Mat fundamentalMatrix, cv::Mat correspondenceMap)\n{\n\tASSERT(fundamentalMatrix.cols == 3 && fundamentalMatrix.rows == 3, \"EssentialMatrixComputation Error, unexpected fundamental matrix size\");\n}\n\n}\n}\n}\n\n/** @} */\n", "meta": {"hexsha": "29fb2fed805beb226bc6a0fd2a811801e0db54ff", "size": 10643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DFNs/CamerasTransformEstimation/EssentialMatrixDecomposition.cpp", "max_stars_repo_name": "H2020-InFuse/cdff", "max_stars_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-26T15:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T07:39:01.000Z", "max_issues_repo_path": "DFNs/CamerasTransformEstimation/EssentialMatrixDecomposition.cpp", "max_issues_repo_name": "H2020-InFuse/cdff", "max_issues_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "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": "DFNs/CamerasTransformEstimation/EssentialMatrixDecomposition.cpp", "max_forks_repo_name": "H2020-InFuse/cdff", "max_forks_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-06T12:09:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T12:09:05.000Z", "avg_line_length": 38.9853479853, "max_line_length": 185, "alphanum_fraction": 0.7863384384, "num_tokens": 2600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.507333942492396}}
{"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//\t\r\n//******************************************************************************\r\n// 01-01-2020\tR\u00e9mi Saint-Amant\tInclude into Weather-based simulation framework\r\n//******************************************************************************\r\n#include \"stdafx.h\"\r\n#include <math.h>\r\n#include <sstream>\r\n#include <algorithm>\r\n#include <random>\r\n\r\n#include <boost/math/distributions/normal.hpp>\r\n#include <boost/math/distributions/lognormal.hpp>\r\n#include <boost/math/distributions/poisson.hpp>\r\n#include <boost/algorithm/string.hpp>\r\n#include <cmath>\r\n#include \"basic/xml/zen/stl_tools.h\"\r\n\r\n#include \"Basic/OpenMP.h\"\r\n#include \"Basic/UtilMath.h\"\r\n#include \"Basic/ModelStat.h\"\r\n#include \"Basic/CSV.h\"\r\n#include \"Basic/UtilStd.h\"\r\n#include \"FileManager/FileManager.h\"\r\n#include \"ModelBase/CommunicationStream.h\"\r\n#include \"ModelBase/WGInput-ModelInput.h\"\r\n#include \"Simulation/ExecutableFactory.h\"\r\n#include \"Simulation/WeatherGenerator.h\"\r\n#include \"Simulation/LoadStaticData.h\"\r\n#include \"Simulation/InsectParameterization.h\"\r\n\r\n#include \"WeatherBasedSimulationString.h\"\r\n\r\n\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\nusing namespace WBSF::WEATHER;\r\nusing namespace WBSF::DIMENSION;\r\nusing namespace WBSF::DevRateInput;\r\n\r\n\r\nnamespace WBSF\r\n{\r\n\r\n\t//static const double SIGMA_DEFAULT = 0.2;\r\n\t//static const double SIGMA_MIN = 0.01;\r\n\t//static const double SIGMA_MAX = 1.7;\r\n\tstatic const double SIGMA_FACTOR = 2.0;\r\n\tstatic const double Fo_FACTOR = 5.0;\r\n\r\n\t//\tstatic const bool m_bShowInfoEx = true;\r\n\r\n\t\t//**********************************************************************************************\r\n\r\n\tdouble GetRateStat(TDevRateEquation  e, const vector<double>& X, const vector<double>& T, double obs_time)\r\n\t{\r\n\t\tCStatisticEx stat;\r\n\t\tif (T.size() == 1)//optimization at constant temperature (rate is always the same)\r\n\t\t{\r\n\t\t\tdouble rate = max(0.0, CDevRateEquation::GetRate(e, X, T[0]));//daily rate\r\n\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\treturn NAN;\r\n\r\n\t\t\tstat += rate;//sum of hourly rate\r\n\t\t}\r\n\t\telse if (T.size() == 24)//optimization at constant 24 hour cycle temperature (rate is always the same)\r\n\t\t{\r\n\t\t\tdouble rate = 0;\r\n\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t\trate += max(0.0, CDevRateEquation::GetRate(e, X, T[h])) / 24.0;//sum of hourly rate\r\n\r\n\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\treturn NAN;\r\n\t\t\t//for (size_t t = 0; t < obs_time; t++)\r\n\t\t\tstat += (obs_time*rate);//sum of hourly rate\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor (size_t t = 0; t < obs_time; t++)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble rate = max(0.0, CDevRateEquation::GetRate(e, X, T[t * 24 + h]));//daily rate\r\n\t\t\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\t\t\treturn NAN;\r\n\r\n\t\t\t\t\tstat += rate;//sum of hourly rate\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn stat;\r\n\t}\r\n\r\n\t//return time (days) to comple stage\r\n\tdouble GetTimeStat(TDevRateEquation  e, const vector<double>& X, const vector<double>& T)\r\n\t{\r\n\t\tdouble time = 0;\r\n\t\tif (T.size() == 1)//optimization at constant temperature (rate is always the same)\r\n\t\t{\r\n\t\t\tdouble rate = CDevRateEquation::GetRate(e, X, T[0]);//daily rate\r\n\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\treturn NAN;\r\n\r\n\t\t\tif (rate > 0)\r\n\t\t\t\ttime = ceil(1 / rate);//sum of hourly rate\r\n\t\t\telse\r\n\t\t\t\ttime = 1000.0*(1 - rate);//let a chnace to converge\r\n\t\t}\r\n\t\telse if (T.size() == 24)//optimization at constant 24 hour cycle temperature (rate is always the same)\r\n\t\t{\r\n\t\t\tdouble rate = 0;\r\n\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t\trate += max(0.0, CDevRateEquation::GetRate(e, X, T[h])) / 24.0;//sum of hourly rate\r\n\r\n\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\treturn NAN;\r\n\t\t\t//for (size_t t = 0; t < obs_time; t++)\r\n\t\t\t//stat += (obs_time*rate);//sum of hourly rate\r\n\r\n\t\t\tif (rate > 0)\r\n\t\t\t\ttime = ceil(1 / rate);//sum of hourly rate\r\n\t\t\telse\r\n\t\t\t\ttime = 1000.0*(1 - rate);//let a chnace to converge\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tdouble sum_rate = 0;\r\n\t\t\tfor (size_t h = 0; h < T.size() && sum_rate < 1.0; h++)\r\n\t\t\t{\r\n\t\t\t\tdouble rate = max(0.0, CDevRateEquation::GetRate(e, X, T[h])) / 24.0;//daily rate\r\n\t\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\t\treturn NAN;\r\n\r\n\t\t\t\tsum_rate += rate;//sum of hourly rate\r\n\t\t\t\ttime += 1;\r\n\t\t\t}\r\n\r\n\t\t\tif (sum_rate >= 1)\r\n\t\t\t\ttime = ceil(time / 24.0);\r\n\t\t\telse\r\n\t\t\t\ttime = 1000 / max(0.001, sum_rate);\r\n\t\t}\r\n\r\n\t\treturn time;\r\n\t}\r\n\r\n\tdouble GetSurvival(TSurvivalEquation e, const vector<double>& X, const vector<double>& T, double obs_time)\r\n\t{\r\n\t\tif (obs_time <= 0)//when time is NA, survival is 0\r\n\t\t\treturn 0;\r\n\r\n\t\tdouble S = 1;\r\n\t\tif (T.size() == 1)//optimization at constant temperature (rate is always the same)\r\n\t\t{\r\n\t\t\t//daily survival\r\n\t\t\tdouble s = CSurvivalEquation::GetSurvival(e, X, T[0]);\r\n\t\t\tif (!isfinite(s) || isnan(s))\r\n\t\t\t\treturn NAN;\r\n\r\n\r\n\t\t\t//multiplication of all daily survival\r\n\t\t\tS = pow(s, obs_time);\r\n\t\t}\r\n\t\telse if (T.size() == 24)//optimization at constant 24 hour cycle temperature (rate is always the same)\r\n\t\t{\r\n\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t{\r\n\t\t\t\t//daily survival\r\n\t\t\t\tdouble d_s = CSurvivalEquation::GetSurvival(e, X, T[h]);\r\n\t\t\t\tif (!isfinite(d_s) || isnan(d_s))\r\n\t\t\t\t\treturn NAN;\r\n\r\n\t\t\t\t//hourly survival\r\n\t\t\t\tdouble s = pow(d_s, 1.0 / 24.0);\r\n\t\t\t\t//multiplication of all hourly survival\r\n\t\t\t\tS *= s;\r\n\t\t\t}\r\n\r\n\t\t\tS = pow(S, obs_time);//a verifier????\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor (size_t t = 0; t < obs_time; t++)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t\t{\r\n\t\t\t\t\t//daily survival\r\n\t\t\t\t\tdouble d_s = CSurvivalEquation::GetSurvival(e, X, T[t * 24 + h]);\r\n\t\t\t\t\tif (!isfinite(d_s) || isnan(d_s))\r\n\t\t\t\t\t\treturn NAN;\r\n\r\n\r\n\t\t\t\t\t//hourly survival\r\n\t\t\t\t\tdouble s = pow(d_s, 1.0 / 24.0);\r\n\t\t\t\t\t//multiplication of all hourly survival\r\n\t\t\t\t\tS *= s;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn S;\r\n\t}\r\n\r\n\tdouble GetFecundity(TDevRateEquation e, const vector<double>& X, const vector<double>& T, double ti\u02c9\u00b9, double ti, double qi)\r\n\t{\r\n\t\tdouble to = 0;// X[X.size() - 3];\r\n\t\tdouble Fo = X[X.size() - 2];\r\n\t\tdouble sigma_f = X[X.size() - 1];\r\n\r\n\t\tboost::math::lognormal_distribution<double> LogNormal(log(Fo) - 0.5*Square(sigma_f), sigma_f);\r\n\t\tdouble Fi = quantile(LogNormal, qi);\r\n\r\n\r\n\t\tASSERT(ti\u02c9\u00b9 - to >= 0);\r\n\r\n\t\tif (ti\u02c9\u00b9 - to < 0)//when time is NA, oviposition is 0\r\n\t\t\treturn 0;\r\n\r\n\t\tCStatistic stat_rate;\r\n\t\tdouble Ft = 0;//remaining fecundity at day t\r\n\t\tdouble Ft\u02c9\u00b9 = 0;//remaining fecundity at day t-1\r\n\t\tif (T.size() == 1)//optimization at constant temperature (rate is always the same)\r\n\t\t{\r\n\t\t\tdouble lambda = max(0.0, CDevRateEquation::GetRate(e, X, T[0]));//remaining eggs\r\n\t\t\tif (!isfinite(lambda) || isnan(lambda))\r\n\t\t\t\treturn NAN;\r\n\r\n\r\n\r\n\t\t\t//double Fi = brood_obs / (exp(-lambda * (ti\u02c9\u00b9 - to)) - exp(-lambda * (ti - to)));\r\n\t\t\t//double Fi = brood_obs / (exp(-lambda * (ti\u02c9\u00b9 - to)) - exp(-lambda * (ti - to)));\r\n\t\t\tFt = Fi * exp(-lambda * (ti - to));\r\n\t\t\tFt\u02c9\u00b9 = Fi * exp(-lambda * (ti\u02c9\u00b9 - to));\r\n\r\n\t\t}\r\n\t\telse if (T.size() == 24)//optimization at constant 24 hour cycle temperature (rate is always the same)\r\n\t\t{\r\n\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t//Ft = sigma * Fo;\r\n\t\t\t//Ft\u02c9\u00b9 = sigma * Fo;\r\n\r\n\t\t\t//for (size_t t = t0; t < ti; t++)\r\n\t\t\t//{\r\n\t\t\t//\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tASSERT(t * 24 + h < T.size());\r\n\t\t\t//\t\tdouble lambda = max(0.0, CDevRateEquation::GetRate(e, computation.m_XP, T[t * 24 + h])) / 24.0;//hourly rate\r\n\t\t\t//\t\tif (!isfinite(lambda) || isnan(lambda))\r\n\t\t\t//\t\t\treturn NAN;\r\n\r\n\t\t\t//\t\t//xi += rate;//sum of hourly rate\r\n\t\t\t//\t\t\t//\t\t\t\tif (t < (ti - 1))\r\n\t\t\t//\t\t\t\t//\t\t\t\txi\u02c9\u00b9 += rate;\r\n\t\t\t//\t\t\t\t\t\t\t//Ft = sigma * exp(-lambda * ((ti - t0) * 24));\r\n\r\n\t\t\t//\t\t\t\t\t\t\t//if (t < (ti - 1))\r\n\t\t\t//\t\t\t\t\t\t\t\t//Ft\u02c9\u00b9 = sigma * exp(-lambda * ((ti - 1 - t0) * 24));\r\n\t\t\t//\t\tFt -= Ft * lambda;\r\n\r\n\t\t\t//\t\tif (t < (ti - 1))\r\n\t\t\t//\t\t\tFt\u02c9\u00b9 -= Ft * lambda;\r\n\t\t\t//\t}\r\n\t\t\t//}\r\n\t\t}\r\n\r\n\t\treturn Ft\u02c9\u00b9 - Ft;\r\n\t}\r\n\r\n\tdouble Regniere2021DevRate(TDevRateEquation  e, double sigma, const vector<double>& X, const vector<double>& T, double ti)\r\n\t{\r\n\t\tASSERT(sigma > 0);\r\n\r\n\r\n\t\tdouble xi = 0;\r\n\t\tdouble xi\u02c9\u00b9 = 0;\r\n\t\tif (T.size() == 1)//optimization at constant temperature (rate is always the same)\r\n\t\t{\r\n\t\t\t//xi = integral (daily summation) of all daily rate at temperature at day ti\r\n\t\t\t//xi\u02c9\u00b9 = integral (dailysummation) of all daily rate at daily temperature at day ti-1\r\n\r\n\t\t\tdouble rate = max(0.0, CDevRateEquation::GetRate(e, X, T[0]));//daily rate\r\n\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\treturn NAN;\r\n\r\n\t\t\txi = rate * ti;//sum of daily rate\r\n\t\t\txi\u02c9\u00b9 = rate * (ti - 1);\r\n\t\t}\r\n\t\telse if (T.size() == 24)//optimization at constant 24 hour cycle temperature (rate is always the same)\r\n\t\t{\r\n\t\t\t//xi = integral (hourly summation) of all hourly rate at hourly temperature at day ti\r\n\t\t\t//xi\u02c9\u00b9 = integral (hourly summation) of all hourly rate at hourly temperature at day ti-1\r\n\r\n\t\t\tdouble rate = 0;\r\n\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t\trate += max(0.0, CDevRateEquation::GetRate(e, X, T[h])) / 24.0;//hourly rate;\r\n\r\n\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\treturn NAN;\r\n\r\n\r\n\t\t\txi = rate * ti;//sum of daily rate\r\n\t\t\txi\u02c9\u00b9 = rate * (ti - 1);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t//xi = integral (hourly summation) of all hourly rate at hourly temperature at day ti\r\n\t\t\t//xi\u02c9\u00b9 = integral (hourly summation) of all hourly rate at hourly temperature at day ti-1\r\n\t\t\tfor (size_t t = 0; t < ti; t++)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t\t{\r\n\t\t\t\t\tASSERT(t * 24 + h < T.size());\r\n\t\t\t\t\tdouble rate = max(0.0, CDevRateEquation::GetRate(e, X, T[t * 24 + h])) / 24.0;//hourly rate\r\n\t\t\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\t\t\treturn NAN;\r\n\r\n\t\t\t\t\txi += rate;//sum of hourly rate\r\n\t\t\t\t\tif (t < (ti - 1))\r\n\t\t\t\t\t\txi\u02c9\u00b9 += rate;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//avoid division by zero\r\n\t\txi = max(1E-20, xi);\r\n\t\txi\u02c9\u00b9 = max(1E-20, xi\u02c9\u00b9);\r\n\r\n\t\t//compute probability of changing stage between ti-1 and ti\r\n\t\tboost::math::lognormal_distribution<double> LogNormal(-0.5*Square(sigma), sigma);\r\n\t\tdouble p = max(1e-200, cdf(LogNormal, 1.0 / xi\u02c9\u00b9) - cdf(LogNormal, 1.0 / xi));\r\n\t\t//double p = max(1e-200, cdf(LogNormal, xi) - cdf(LogNormal, xi\u02c9\u00b9));\r\n\r\n\t\treturn log(p);\r\n\t}\r\n\r\n\r\n\tdouble Regniere2021DevRateMeanSDn(TDevRateEquation  e, const vector<double>& X, const vector<double>& T, double mean_time, double time_SD, double n)\r\n\t{\r\n\t\tCStatistic stat_rate;\r\n\t\tif (T.size() == 1)//optimization at constant temperature (rate is always the same)\r\n\t\t{\r\n\t\t\tdouble rate = max(0.0, CDevRateEquation::GetRate(e, X, T[0]));//daily rate\r\n\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\treturn NAN;\r\n\r\n\t\t\tstat_rate = rate;//mean daily rate\r\n\t\t}\r\n\t\telse if (T.size() == 24)//optimization at constant 24 hour cycle temperature (rate is always the same)\r\n\t\t{\r\n\t\t\tdouble rate = 0;\r\n\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t\trate += max(0.0, CDevRateEquation::GetRate(e, X, T[h])) / 24.0;//hourly rate;\r\n\r\n\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\treturn NAN;\r\n\r\n\t\t\tstat_rate = rate;//mean daily rate\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor (size_t t = 0; t < mean_time; t++)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble rate = max(0.0, CDevRateEquation::GetRate(e, X, T[t * 24 + h]));//rate for each hour\r\n\t\t\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\t\t\treturn NAN;\r\n\r\n\t\t\t\t\tstat_rate += rate;//mean daily rate\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//1E-20: avoid division by zero\r\n\t\tdouble sim_time = 1.0 / max(1E-20, stat_rate[MEAN]);\r\n\r\n\t\t//compute probability of changing stage between ti-1 and ti\r\n\t\tboost::math::normal_distribution<double> Normal(0, time_SD / sqrt(n));\r\n\r\n\t\tdouble p = max(1e-200, pdf(Normal, mean_time - sim_time));\r\n\t\treturn log(p);\r\n\t}\r\n\r\n\tdouble Regniere2021DevRateMean(TDevRateEquation  e, double sigma_mean, const vector<double>& X, const vector<double>& T, double mean_time, double n)\r\n\t{\r\n\t\tASSERT(sigma_mean > 0);\r\n\r\n\r\n\t\tCStatistic stat_rate;\r\n\t\tif (T.size() == 1)//optimization at constant temperature (rate is always the same)\r\n\t\t{\r\n\t\t\tdouble rate = max(0.0, CDevRateEquation::GetRate(e, X, T[0]));//daily rate\r\n\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\treturn NAN;\r\n\r\n\t\t\tstat_rate = rate;//mean daily rate\r\n\t\t}\r\n\t\telse if (T.size() == 24)//optimization at constant 24 hour cycle temperature (rate is always the same)\r\n\t\t{\r\n\r\n\t\t\tdouble rate = 0;\r\n\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t\trate += max(0.0, CDevRateEquation::GetRate(e, X, T[h])) / 24.0;//hourly rate;\r\n\r\n\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\treturn NAN;\r\n\r\n\t\t\tstat_rate = rate;//mean daily rate\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor (size_t t = 0; t < mean_time; t++)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble rate = max(0.0, CDevRateEquation::GetRate(e, X, T[t * 24 + h]));//rate for each hourly\r\n\t\t\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\t\t\treturn NAN;\r\n\r\n\t\t\t\t\tstat_rate += rate;//mean of rate\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//1E-20: avoid division by zero\r\n\t\tdouble sim_time = 1.0 / max(1E-20, stat_rate[MEAN]);\r\n\r\n\t\t//compute probability of changing stage between ti-1 and ti\r\n\t\tboost::math::normal_distribution<double> Normal(1, sigma_mean / sqrt(n));\r\n\t\tdouble p = max(1e-200, pdf(Normal, mean_time / sim_time));\r\n\r\n\t\treturn log(p);\r\n\t}\r\n\r\n\tdouble Regniere2021Survival(TSurvivalEquation e, const vector<double>& X, const vector<double>& T, double mean_time, double survival_obs, double n)\r\n\t{\r\n\t\tdouble S = GetSurvival(e, X, T, mean_time);\r\n\r\n\t\tif (!isfinite(S) || isnan(S))\r\n\t\t\treturn S;\r\n\r\n\t\tdouble expected = max(0.001, min(1e10, n * S));//limit to a very low expected when zero survival\r\n\t\tboost::math::poisson_distribution<double> Poisson(expected);\r\n\r\n\t\t//compute probability of surviving\r\n\t\tdouble p = max(1e-20, pdf(Poisson, survival_obs));\r\n\t\treturn log(p);\r\n\t}\r\n\r\n\t//to : pre-oviposition period\r\n\tdouble Regniere2021FecundityTimeSeries(TDevRateEquation  e, const vector<double>& X, const vector<double>& T, double ti\u02c9\u00b9, double ti, double brood_obs, double qBrood)\r\n\t{\r\n\t\tASSERT(ti\u02c9\u00b9 < ti);\r\n\t\t\r\n\t\tdouble to = 0;// X[X.size() - 3];\r\n\t\t//Get Fo and sigma from input parameters X\r\n\t\tdouble Fo = X[X.size() - 2];\r\n\t\tdouble sigma_f = X[X.size() - 1];\r\n\r\n\t\t//create relative fecundity unbiased log-normal distribution\r\n\t\tboost::math::lognormal_distribution<double> LogNormal(log(Fo) - 0.5*Square(sigma_f), sigma_f);\r\n\r\n\t\t//compute individual fecondity (Fi) from Fo and female quantile\r\n\t\tdouble Fi = quantile(LogNormal, qBrood);\r\n\t\t\r\n\r\n\t\tdouble Ft = Fi;//remaining fecundity at day t\r\n\t\tdouble Ft\u02c9\u00b9 = Fi;//remaining fecundity at day t-1\r\n\t\tif (T.size() == 1)//optimization at constant temperature (rate is always the same)\r\n\t\t{\r\n\t\t\t//compute lambda from equations parameters and fixed temperature\r\n\t\t\tdouble lambda = max(0.0, CDevRateEquation::GetRate(e, X, T[0]));//remaining eggs\r\n\t\t\tif (!isfinite(lambda) || isnan(lambda))\r\n\t\t\t\treturn NAN;\r\n\r\n\t\t\t//double Fi = brood_obs / (exp(-lambda * (ti\u02c9\u00b9 - to)) - exp(-lambda * (ti - to)));\r\n\r\n\t\t\t//compute remainning fecundity\r\n\t\t\tif (ti - to >= 0)\r\n\t\t\t\tFt = Fi * exp(-lambda * (ti - to));\r\n\t\t\tif (ti\u02c9\u00b9 - to >= 0)\r\n\t\t\t\tFt\u02c9\u00b9 = Fi * exp(-lambda * (ti\u02c9\u00b9 - to));\r\n\r\n\r\n\t\t\t//Ft = exp(-lambda * (ti - to));\r\n\t\t\t//Ft\u02c9\u00b9 = exp(-lambda * (ti\u02c9\u00b9 - to));\r\n\t\t}\r\n\t\telse if (T.size() == 24)//optimization at constant 24 hour cycle temperature (rate is always the same)\r\n\t\t{\r\n\t\t\t//xi = integral (hourly summation) of all hourly rate at hourly temperature at day ti\r\n\t\t\t//xi\u02c9\u00b9 = integral (hourly summation) of all hourly rate at hourly temperature at day ti-1\r\n\r\n\t\t\t//double Ft = sigma * exp(-lambda * ((ti - t0-2) * 24));\r\n\t\t\t//double Ft\u02c9\u00b9 = sigma * exp(-lambda * ((ti - 1 - t0) * 24));\r\n\t\t\t//double Fi[24] = { 0 };\r\n\t\t\t//double lambda[24] = { 0 };\r\n\t\t\t//for (size_t h = 0; h < 24; h++)\r\n\t\t\t//{\r\n\t\t\t//\tlambda[h] = max(0.0, CDevRateEquation::GetRate(e, computation.m_XP, T[h])) / 24.0;//hourly rate;\r\n\r\n\t\t\t//\tif (!isfinite(lambda[h]) || isnan(lambda[h]))\r\n\t\t\t//\t\treturn NAN;\r\n\r\n\t\t\t//\t//Fi[h] = brood_obs / (exp(-lambda[h] * (ti\u02c9\u00b9 - to)) - exp(-lambda[h] * (ti - to)));\r\n\r\n\r\n\t\t\t//}\r\n\r\n\r\n\t\t\t//Ft = brood_obs;\r\n\t\t\t//Ft\u02c9\u00b9 = brood_obs;\r\n\t\t\t//for (size_t t = to; t < ti; t++)\r\n\t\t\t//{\r\n\t\t\t//\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tFt += Ft * lambda[h];\r\n\r\n\t\t\t//\t\tif (t < (ti - 1))\r\n\t\t\t//\t\t\tFt\u02c9\u00b9 -= Ft * lambda[h];\r\n\t\t\t//\t}\r\n\t\t\t//}\r\n\t\t\tassert(false);//a v\u00e9rifier\r\n\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tassert(false);//a v\u00e9rifier\r\n\r\n\t\t\t//Ft = brood_obs;\r\n\t\t\t//Ft\u02c9\u00b9 = brood_obs;\r\n\r\n\t\t\t//for (size_t t = to; t < ti; t++)\r\n\t\t\t//{\r\n\t\t\t//\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tASSERT(t * 24 + h < T.size());\r\n\t\t\t//\t\tdouble lambda = max(0.0, CDevRateEquation::GetRate(e, computation.m_XP, T[t * 24 + h]));//hourly remaining eggs\r\n\t\t\t//\t\tif (!isfinite(lambda) || isnan(lambda))\r\n\t\t\t//\t\t\treturn NAN;\r\n\r\n\t\t\t//\t\tFt -= Ft * lambda;\r\n\r\n\t\t\t//\t\tif (t < (ti - 1))\r\n\t\t\t//\t\t\tFt\u02c9\u00b9 -= Ft * lambda;\r\n\t\t\t//\t}\r\n\t\t\t//}\r\n\t\t}\r\n\r\n\t\t\r\n\t\t//create poisson distribution from expected values\r\n\t\tdouble expected = max(0.001, Ft\u02c9\u00b9 - Ft);\r\n\t\tboost::math::poisson_distribution<double> Poisson(expected);\r\n\r\n\t\t//compute probability to get observed brood\r\n\t\tdouble p = max(1e-20, pdf(Poisson, brood_obs));\r\n\r\n\t\treturn log(p);\r\n\t}\r\n\r\n\r\n\tdouble Regniere2021Fecundity(TDevRateEquation  e, const vector<double>& X, const vector<double>& T, double time, double brood_obs, double qBrood)\r\n\t{\r\n\t\t//Get to, Fo and sigma from input parameters X\r\n\t\tdouble to = 0;// X[X.size() - 3];\r\n\t\tdouble Fo = X[X.size() - 2];\r\n\t\tdouble sigma_f = X.back();\r\n\r\n\t\t//create relative fecundity unbiased log-normal distribution\r\n\t\tboost::math::lognormal_distribution<double> LogNormal(log(Fo) - 0.5*Square(sigma_f), sigma_f);\r\n\r\n\t\t//compute individual fecondity (Fi) from Fo and female quantile\r\n\t\tdouble Fi = quantile(LogNormal, qBrood);\r\n\r\n\r\n\t\tdouble Ft = Fi;//remaining fecundity at end\r\n\t\tif (T.size() == 1)//optimization at constant temperature (rate is always the same)\r\n\t\t{\r\n\t\t\tdouble lambda = max(0.001, CDevRateEquation::GetRate(e, X, T[0]));//remaining eggs\r\n\t\t\tif (!isfinite(lambda) || isnan(lambda))\r\n\t\t\t\treturn NAN;\r\n\r\n\t\t\t//double Fi = brood_obs / (exp(-lambda * (ti\u02c9\u00b9 - to)) - exp(-lambda * (ti - to)));\r\n\r\n\t\t\tif(time - to>=0)\r\n\t\t\t\tFt = Fi * (1 - exp(-lambda * (time - to)));\r\n\t\t\t//Fi = brood_obs / (1 - exp(-lambda * (ti - to)));\r\n\t\t\t//Ft\u02c9\u00b9 = Fi * exp(-lambda * (ti\u02c9\u00b9 - to));\r\n\r\n\r\n\t\t\t//Ft = exp(-lambda * (ti - to));\r\n\t\t\t//Ft\u02c9\u00b9 = exp(-lambda * (ti\u02c9\u00b9 - to));\r\n\t\t}\r\n\t\telse if (T.size() == 24)//optimization at constant 24 hour cycle temperature (rate is always the same)\r\n\t\t{\r\n\t\t\t//xi = integral (hourly summation) of all hourly rate at hourly temperature at day ti\r\n\t\t\t//xi\u02c9\u00b9 = integral (hourly summation) of all hourly rate at hourly temperature at day ti-1\r\n\r\n\t\t\t//double Ft = sigma * exp(-lambda * ((ti - t0-2) * 24));\r\n\t\t\t//double Ft\u02c9\u00b9 = sigma * exp(-lambda * ((ti - 1 - t0) * 24));\r\n\t\t\t//double Fi[24] = { 0 };\r\n\t\t\t//double lambda[24] = { 0 };\r\n\t\t\t//for (size_t h = 0; h < 24; h++)\r\n\t\t\t//{\r\n\t\t\t//\tlambda[h] = max(0.0, CDevRateEquation::GetRate(e, computation.m_XP, T[h])) / 24.0;//hourly rate;\r\n\r\n\t\t\t//\tif (!isfinite(lambda[h]) || isnan(lambda[h]))\r\n\t\t\t//\t\treturn NAN;\r\n\r\n\t\t\t//\t//Fi[h] = brood_obs / (exp(-lambda[h] * (ti\u02c9\u00b9 - to)) - exp(-lambda[h] * (ti - to)));\r\n\r\n\r\n\t\t\t//}\r\n\r\n\r\n\t\t\t//Ft = brood_obs;\r\n\t\t\t//Ft\u02c9\u00b9 = brood_obs;\r\n\t\t\t//for (size_t t = to; t < ti; t++)\r\n\t\t\t//{\r\n\t\t\t//\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tFt += Ft * lambda[h];\r\n\r\n\t\t\t//\t\tif (t < (ti - 1))\r\n\t\t\t//\t\t\tFt\u02c9\u00b9 -= Ft * lambda[h];\r\n\t\t\t//\t}\r\n\t\t\t//}\r\n\t\t\tassert(false);//a v\u00e9rifier\r\n\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tassert(false);//a v\u00e9rifier\r\n\r\n\t\t\t//Ft = brood_obs;\r\n\t\t\t//Ft\u02c9\u00b9 = brood_obs;\r\n\r\n\t\t\t//for (size_t t = to; t < ti; t++)\r\n\t\t\t//{\r\n\t\t\t//\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tASSERT(t * 24 + h < T.size());\r\n\t\t\t//\t\tdouble lambda = max(0.0, CDevRateEquation::GetRate(e, computation.m_XP, T[t * 24 + h]));//hourly remaining eggs\r\n\t\t\t//\t\tif (!isfinite(lambda) || isnan(lambda))\r\n\t\t\t//\t\t\treturn NAN;\r\n\r\n\t\t\t//\t\tFt -= Ft * lambda;\r\n\r\n\t\t\t//\t\tif (t < (ti - 1))\r\n\t\t\t//\t\t\tFt\u02c9\u00b9 -= Ft * lambda;\r\n\t\t\t//\t}\r\n\t\t\t//}\r\n\t\t}\r\n\r\n\t\tdouble expected = max(0.001, Ft);\r\n\t\tboost::math::poisson_distribution<double> Poisson(expected);\r\n\r\n\t\t////compute probability to get observed brood\r\n\t\tdouble p = max(1e-20, pdf(Poisson, brood_obs));\r\n\r\n//\t\tboost::math::lognormal_distribution<double> LogNormal(log(Fo) - 0.5*Square(sigma_f), sigma_f);\r\n//\tdouble p2 = max(1e-200, pdf(LogNormal, Ft));\r\n\r\n\t\treturn log(p);// + log(p2)\r\n\t}\r\n\r\n\tdouble Regniere2021FecundityMeanSDn(TDevRateEquation e, const vector<double>& X, const vector<double>& T, double mean_time, double mean_broods, double broodSD, double n)\r\n\t{\r\n\t\tdouble to = 0;\r\n\t\tdouble Fo = X[X.size() - 2];\r\n\t\t//double sigma_f = computation.m_XP.back();\r\n\t\t//double Fo = computation.m_XP.back();\r\n\t//\tboost::math::lognormal_distribution<double> LogNormal(log(Fo) - 0.5*Square(sigma_f), sigma_f);\r\n\t\t//double Fi = quantile(LogNormal, qi);\r\n\r\n\r\n\r\n\t\t//double O = GetOviposition(e, to, computation, T, mean_time);\r\n\r\n\t\t//if (!isfinite(O) || isnan(O))\r\n\t\t//\treturn O;\r\n\r\n\t\t//double expected = max(0.001, min(1e10, (mean_time - to) * O));//limit to a very low expected when zero survival\r\n\t\t//boost::math::poisson_distribution<double> Poisson(expected);\r\n\r\n\t\t////compute probability of surviving\r\n\t\t//double p = pdf(Poisson, broods_obs);\r\n\t\t//return log(p);\r\n\r\n\r\n\t\t////1E-20: avoid division by zero\r\n\t\t//double sim_time = 1.0 / max(1E-20, stat_rate[MEAN]);\r\n\r\n\t\t////compute probability of changing stage between ti-1 and ti\r\n\t\t//boost::math::normal_distribution<double> Normal(0, time_SD / sqrt(n));\r\n\r\n\t\t//double p = max(1e-200, pdf(Normal, mean_time - sim_time));\r\n\t\t//return log(p);\r\n\r\n\t\tdouble sim_broods = 0;\r\n\t\tCStatistic stat_lambda;\r\n\t\tif (T.size() == 1)//optimization at constant temperature (rate is always the same)\r\n\t\t{\r\n\t\t\tdouble lambda = max(0.0, CDevRateEquation::GetRate(e, X, T[0]));//remaining eggs\r\n\t\t\tif (!isfinite(lambda) || isnan(lambda))\r\n\t\t\t\treturn NAN;\r\n\r\n\t\t\t//stat_lambda = lambda;//mean daily rate\r\n\t\t\tsim_broods = Fo * (1.0 - exp(-lambda * mean_time));\r\n\t\t}\r\n\t\telse if (T.size() == 24)//optimization at constant 24 hour cycle temperature (rate is always the same)\r\n\t\t{\r\n\t\t\tdouble lambda = 0;\r\n\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t\tlambda += max(0.0, CDevRateEquation::GetRate(e, X, T[h])) / 24.0;//hourly rate;\r\n\r\n\t\t\tif (!isfinite(lambda) || isnan(lambda))\r\n\t\t\t\treturn NAN;\r\n\r\n\t\t\tstat_lambda = lambda;//mean daily rate\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor (size_t t = 0; t < mean_time; t++)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble lambda = max(0.0, CDevRateEquation::GetRate(e, X, T[t * 24 + h]));//rate for each hour\r\n\t\t\t\t\tif (!isfinite(lambda) || isnan(lambda))\r\n\t\t\t\t\t\treturn NAN;\r\n\r\n\t\t\t\t\tstat_lambda += lambda;//mean daily rate\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//mean of brood rate eggs/day\r\n\t\t//double lambda = stat_lambda[MEAN];\r\n\t\t//double sim_broods = Fo * (1.0 - exp(-lambda * mean_time));\r\n\r\n\t\t//compute probability of changing stage between ti-1 and ti\r\n\t\tboost::math::normal_distribution<double> Normal(0, broodSD / sqrt(n));\r\n\r\n\r\n\t\tdouble p = max(1e-200, pdf(Normal, mean_broods - sim_broods));\r\n\t\treturn log(p);\r\n\r\n\t}\r\n\r\n\t//**********************************************************************************************\r\n\t//CTobsSeries\r\n\r\n\tconst char* CTobsSeries::INPUT_NAME[NB_TOBS_COL] = { \"Tid\",\"T\" };\r\n\r\n\tCTobsSeries::CTobsSeries()\r\n\t{}\r\n\r\n\tCTobsSeries::~CTobsSeries()\r\n\t{}\r\n\r\n\r\n\tTTobsCol CTobsSeries::get_input(const std::string& name)\r\n\t{\r\n\t\tTTobsCol col = C_UNKNOWN;\r\n\r\n\t\tauto it = find_if(std::begin(INPUT_NAME), std::end(INPUT_NAME), [&](auto &s) {return boost::iequals(s, name); });\r\n\t\tif (it != std::end(INPUT_NAME))\r\n\t\t\tcol = static_cast<TTobsCol>(std::distance(std::begin(INPUT_NAME), it));\r\n\r\n\t\treturn col;\r\n\r\n\t}\r\n\r\n\tsize_t CTobsSeries::get_pos(TTobsCol c)const\r\n\t{\r\n\t\tsize_t pos = NOT_INIT;\r\n\t\tauto it = std::find(m_input_pos.begin(), m_input_pos.end(), c);\r\n\t\tif (it != m_input_pos.end())\r\n\t\t\tpos = std::distance(m_input_pos.begin(), it);\r\n\r\n\t\treturn pos;\r\n\t}\r\n\r\n\tERMsg CTobsSeries::load(const std::string& file_path)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\t//begin to read\r\n\t\tifStream file;\r\n\t\tmsg = file.open(file_path);\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tmsg = load(file);\r\n\t\t\tfile.close();\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\tERMsg CTobsSeries::load(std::istream& io)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\tclear();\r\n\t\tm_input_pos.clear();\r\n\t\t//StringVector header;\r\n\t\tsize_t pID = NOT_INIT;\r\n\t\tsize_t pT = NOT_INIT;\r\n\r\n\t\tfor (CSVIterator loop(io, \",;\\t|\", true, true); loop != CSVIterator() && msg; ++loop)\r\n\t\t{\r\n\t\t\tif (m_input_pos.empty())\r\n\t\t\t{\r\n\t\t\t\tfor (size_t i = 0; i < loop.Header().size(); i++)\r\n\t\t\t\t\tm_input_pos.push_back(get_input(loop.Header()[i]));\r\n\r\n\t\t\t\tif (!have_var(C_TID))\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(\"Mandatory missing column. \\\"Tid\\\" must be define\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\t//check for mandatory columns\r\n\t\t\t\tif (!have_var(C_T))\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(\"Mandatory missing column: \\\"T\\\" must be define\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tpID = get_pos(C_TID);\r\n\t\t\t\tpT = get_pos(C_T);\r\n\t\t\t}\r\n\r\n\t\t\tif (msg)\r\n\t\t\t{\r\n\t\t\t\tif (pID < loop->size() &&\r\n\t\t\t\t\tpT < loop->size())\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble T = ToDouble((*loop)[pT]);\r\n\t\t\t\t\t(*this)[(*loop)[pID]].push_back(T);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\tERMsg CTobsSeries::verify(const CDevRateData& data)const\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\tfor (size_t i = 0; i < data.size(); i++)\r\n\t\t{\r\n\t\t\tif (data[i].m_type == T_HOBO)\r\n\t\t\t{\r\n\t\t\t\tif (find(data[i].m_traitment) == end())\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(\"Traitment ID\" + data[i].m_traitment + \" not found in temperature file\");\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tsize_t nb_hours = at(data[i].m_traitment).size();\r\n\t\t\t\t\tsize_t needed_hours = data[i].GetMaxTime() * 24;\r\n\t\t\t\t\tif (nb_hours < needed_hours)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmsg.ajoute(\"Temperature profile for ID \" + data[i].m_traitment + \" don't have enought data\");\r\n\t\t\t\t\t\tmsg.ajoute(\"Profile have \" + to_string(nb_hours) + \" hours and \" + to_string(needed_hours) + \" is needed\");\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\t//generate temperature profile\r\n\tvoid CTobsSeries::generate(const CDevRateData& data)\r\n\t{\r\n\t\t//find number of maximum days for all traitment\r\n\t\tmap<string, size_t> traitment;\r\n\t\tfor (size_t i = 0; i < data.size(); i++)\r\n\t\t{\r\n\t\t\tif (data[i].m_type != T_HOBO)\r\n\t\t\t{\r\n\t\t\t\tif (traitment.find(data[i].m_traitment) == traitment.end())\r\n\t\t\t\t{\r\n\t\t\t\t\ttraitment[data[i].m_traitment] = i;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t//bool bFromTime = data.have_var(I_TIME);\r\n\t\t\t\t\tdouble max_time = data[i].GetMaxTime();\r\n\r\n\t\t\t\t\tif (max_time > data[traitment[data[i].m_traitment]].GetMaxTime())\r\n\t\t\t\t\t\ttraitment[data[i].m_traitment] = i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//generate traitment\r\n\t\tfor (auto it = traitment.begin(); it != traitment.end(); it++)\r\n\t\t{\r\n\t\t\tsize_t i = it->second;\r\n\t\t\tASSERT(data[i].m_type != T_HOBO);\r\n\r\n\t\t\tif (data[i].m_type == T_CONSTANT)\r\n\t\t\t{\r\n\t\t\t\t//constant T have only one value\r\n\t\t\t\tdouble T = data[i].GetT();\r\n\t\t\t\t(*this)[data[i].m_traitment].resize(1, T);\r\n\t\t\t}\r\n\t\t\telse if (data[i].m_type == T_MIN_MAX ||\r\n\t\t\t\tdata[i].m_type == T_SINUS ||\r\n\t\t\t\tdata[i].m_type == T_TRIANGULAR)\r\n\t\t\t{\r\n\t\t\t\tdouble T = data[i].GetT();\r\n\t\t\t\tdouble Tmin = data[i].GetTmin();\r\n\t\t\t\tdouble Tmax = data[i].GetTmax();\r\n\r\n\t\t\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble Ti = T;\r\n\t\t\t\t\tif (data[i].m_type == T_MIN_MAX)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tTi = h < 12 ? Tmin : Tmax;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (data[i].m_type == T_SINUS)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble theta = 2 * PI*h / 24.0;\r\n\t\t\t\t\t\tTi = (Tmin + Tmax) / 2 + (Tmax - Tmin) / 2 * sin(theta);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (data[i].m_type == T_TRIANGULAR)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tTi = (Tmin + Tmax) / 2 + (Tmax - Tmin) / 2 * (fabs(12.0 - ((h + 6) % 24)) - 6.0) / 6.0;\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t(*this)[data[i].m_traitment].push_back(Ti);\r\n\t\t\t\t}//all hours\r\n\t\t\t}\r\n\t\t\t//else //HOBO\r\n\t\t\t//{\r\n\t\t\t//\tdouble needed_days_max = data[i].GetMaxTime();\r\n\r\n\t\t\t//\t//double T = data[i].GetT();\r\n\t\t\t//\t//double Tmin = data[i].GetTmin();\r\n\t\t\t//\t//double Tmax = data[i].GetTmax();\r\n\r\n\t\t\t//\tfor (size_t t = 0; t < needed_days_max; t++)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tfor (size_t h = 0; h < 24; h++)\r\n\t\t\t//\t\t{\r\n\t\t\t//\t\t\tdouble Ti = T;\r\n\t\t\t//\t\t\tif (data[i].m_type == T_MIN_MAX)\r\n\t\t\t//\t\t\t{\r\n\t\t\t//\t\t\t\tTi = h < 12 ? Tmin : Tmax;\r\n\t\t\t//\t\t\t}\r\n\t\t\t//\t\t\telse if (data[i].m_type == T_SINUS)\r\n\t\t\t//\t\t\t{\r\n\t\t\t//\t\t\t\tdouble theta = 2 * PI*h / 24.0;\r\n\t\t\t//\t\t\t\tTi = (Tmin + Tmax) / 2 + (Tmax - Tmin) / 2 * sin(theta);\r\n\t\t\t//\t\t\t}\r\n\t\t\t//\t\t\telse if (data[i].m_type == T_TRIANGULAR)\r\n\t\t\t//\t\t\t{\r\n\t\t\t//\t\t\t\tTi = (Tmin + Tmax) / 2 + (Tmax - Tmin) / 2 * (fabs(12.0 - ((h + 6) % 24)) - 6.0) / 6.0;\r\n\t\t\t//\t\t\t}\r\n\r\n\r\n\t\t\t//\t\t\t(*this)[data[i].m_traitment].push_back(Ti);\r\n\t\t\t//\t\t}//all hours\r\n\t\t\t//\t}//all days\r\n\t\t\t//}//T constant\r\n\t\t}//al treatment\r\n\t}\r\n\r\n\r\n\r\n\t//**********************************************************************************************\r\n\t//CDevRateInput\r\n\r\n\t//static const char* DevRateInput::TTYPE_NAME[DevRateInput::NB_TMP_TYPE] = { \"\",\"|\",\"~\",\"^\",\"chamber\" };\r\n\tTTemperature DevRateInput::get_TType(const std::string& name)\r\n\t{\r\n\t\tTTemperature  type = T_UNKNOWN;\r\n\t\tif (name.find(\"|\") != string::npos)\r\n\t\t\ttype = T_MIN_MAX;\r\n\t\telse if (name.find(\"~\") != string::npos)\r\n\t\t\ttype = T_SINUS;\r\n\t\telse if (name.find(\"^\") != string::npos)\r\n\t\t\ttype = T_TRIANGULAR;\r\n\t\telse if (name.find_first_not_of(\"-0123456789.\") == string::npos)\r\n\t\t\ttype = T_CONSTANT;\r\n\t\telse\r\n\t\t\ttype = T_HOBO;\r\n\r\n\t\treturn type;\r\n\t}\r\n\r\n\r\n\tdouble CDevRateDataRow::GetTminTmax(bool bTmin) const\r\n\t{\r\n\t\tdouble T = -999;\r\n\t\tif (m_type != T_HOBO)\r\n\t\t{\r\n\t\t\tif (m_type == T_CONSTANT)\r\n\t\t\t{\r\n\t\t\t\tT = ToDouble(m_traitment);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tStringVector tmp(m_traitment, \"|~^\");\r\n\t\t\t\tif (tmp.size() == 2)\r\n\t\t\t\t\tT = ToDouble(tmp[bTmin ? 0 : 1]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn T;\r\n\t}\r\n\r\n\tsize_t CDevRateDataRow::GetMaxTime() const\r\n\t{\r\n\t\tsize_t max_time = 0;\r\n\r\n\t\tif (find(I_TIME) != end())\r\n\t\t{\r\n\t\t\tmax_time = at(I_TIME);\r\n\t\t}\r\n\t\telse if (find(I_MEAN_TIME) != end())\r\n\t\t{\r\n\t\t\tdouble mean = at(I_MEAN_TIME);\r\n\t\t\tif (mean > 0)\r\n\t\t\t{\r\n\t\t\t\tmax_time = ceil(mean);\r\n\r\n\t\t\t\tif (find(I_TIME_SD) != end() && find(I_N) != end())\r\n\t\t\t\t{\r\n\t\t\t\t\t//GetDefaultSigma();\r\n\t\t\t\t\tsize_t n = at(I_N);\r\n\t\t\t\t\tdouble sd = at(I_TIME_SD);\r\n\r\n\t\t\t\t\tif (sd > 0)//in case of NA\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble cv = sd / mean;\r\n\t\t\t\t\t\tdouble sigma = CDevRateData::cv_2_sigma(cv, n);\r\n\t\t\t\t\t\tboost::math::lognormal_distribution<double> obsLogNormal(-0.5*Square(sigma), sigma);\r\n\r\n\t\t\t\t\t\tdouble q = max(0.005, 1 / (n + 1.0));\r\n\t\t\t\t\t\tdouble RDR = quantile(obsLogNormal, q);\r\n\r\n\t\t\t\t\t\tmax_time = ceil(mean / (RDR*exp(Square(sigma))));//estimate of time (approx)\r\n\r\n\t\t\t\t\t\t//\t//double alpha = 0.05;\r\n\t\t\t\t\t\t//\t//double q = pow(alpha, 1.0 / N);\r\n\t\t\t\t\t\t//\t//max_time = ceil(quantile(obsLogNormal, q));\r\n\r\n\r\n\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn max_time;\r\n\t}\r\n\r\n\tconst char* CDevRateData::INPUT_NAME[NB_DEV_INPUT] = { \"Variable\",\"T\", \"I\", \"Start\", \"Time\",\"MeanTime\",\"TimeSD\",\"N\", \"RDT\", \"qTime\", \"Rate\", \"RDR\", \"qRate\", \"Survival\", \"Brood\", \"MeanBrood\", \"BroodSD\", \"RFR\", \"qBrood\" };\r\n\tTDevTimeCol CDevRateData::get_input(const std::string& name)\r\n\t{\r\n\t\tTDevTimeCol col = I_UNKNOWN;\r\n\r\n\t\tauto it = find_if(std::begin(INPUT_NAME), std::end(INPUT_NAME), [&](auto &s) {return boost::iequals(s, name); });\r\n\t\tif (it != std::end(INPUT_NAME))\r\n\t\t\tcol = static_cast<TDevTimeCol>(std::distance(std::begin(INPUT_NAME), it));\r\n\r\n\t\treturn col;\r\n\t}\r\n\r\n\tsize_t CDevRateData::get_pos(TDevTimeCol c)const\r\n\t{\r\n\t\tsize_t pos = NOT_INIT;\r\n\t\tauto it = find(m_input_pos.begin(), m_input_pos.end(), c);\r\n\t\tif (it != m_input_pos.end())\r\n\t\t\tpos = std::distance(m_input_pos.begin(), it);\r\n\r\n\t\treturn pos;\r\n\t}\r\n\r\n\tCDevRateData::CDevRateData()\r\n\t{}\r\n\r\n\tCDevRateData::~CDevRateData()\r\n\t{}\r\n\r\n\r\n\tERMsg CDevRateData::load(const std::string& file_path)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\t//begin to read\r\n\t\tifStream file;\r\n\t\tmsg = file.open(file_path);\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tmsg = load(file);\r\n\t\t\tfile.close();\r\n\t\t}\r\n\r\n\t\tif (!msg)\r\n\t\t\tmsg.ajoute(\"Error when reading file:\" + file_path);\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\tERMsg CDevRateData::load(std::istream& io)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\tclear();\r\n\t\tm_input_pos.clear();\r\n\r\n\r\n\t\t//StringVector header;\r\n\t\tfor (CSVIterator loop(io, \",;\\t|\", true, true); loop != CSVIterator() && msg; ++loop)\r\n\t\t{\r\n\t\t\tif (m_input_pos.empty())\r\n\t\t\t{\r\n\t\t\t\tfor (size_t i = 0; i < loop.Header().size(); i++)\r\n\t\t\t\t\tm_input_pos.push_back(get_input(loop.Header()[i]));\r\n\r\n\t\t\t\tif (!have_var(I_TRAITMENT))\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(\"Mandatory missing column. \\\"T\\\" must be define\");\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t\t//check for mandatory columns\r\n\t\t\t\tif (!have_var(I_TIME) && !have_var(I_MEAN_TIME))\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(\"Mandatory missing column: \\\"Time\\\" or \\\"MeanTime\\\" must be define\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\r\n\t\t\tif (msg && !loop->empty())\r\n\t\t\t{\r\n\t\t\t\tif (loop->size() != m_input_pos.size())\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(\"Bad number of column for line:\" + loop->GetLastLine());\r\n\t\t\t\t\treturn msg;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tCDevRateDataRow row;\r\n\t\t\t\tfor (size_t i = 0; i < m_input_pos.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (m_input_pos[i] != I_UNKNOWN)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (m_input_pos[i] == I_VARIABLE)\r\n\t\t\t\t\t\t\trow.m_variable = (*loop)[i];\r\n\t\t\t\t\t\telse if (m_input_pos[i] == I_TRAITMENT)\r\n\t\t\t\t\t\t\trow.m_traitment = (*loop)[i];\r\n\t\t\t\t\t\telse if (m_input_pos[i] == I_I)\r\n\t\t\t\t\t\t\trow.m_i = (*loop)[i];\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\trow[m_input_pos[i]] = ToDouble((*loop)[i]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (have_var(I_TIME_SD) && row[I_TIME_SD] <= 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(\"Standard deviation equal zero is not supported: \" + loop->GetLastLine());\r\n\t\t\t\t\treturn msg;\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t\trow.m_type = get_TType(row.m_traitment);\r\n\r\n\r\n\t\t\t\tif (!have_var(I_START))\r\n\t\t\t\t\trow[I_START] = 0.0;\r\n\r\n\t\t\t\tif (!have_var(I_N))\r\n\t\t\t\t\trow[I_N] = 1.0;\r\n\r\n\t\t\t\tif (!have_var(I_I))\r\n\t\t\t\t\trow[I_I] = size() + 1.0;\r\n\r\n\t\t\t\tif (!have_var(I_RATE) && have_var(I_TIME))\r\n\t\t\t\t\trow[I_RATE] = 1.0 / row[I_TIME];\r\n\r\n\t\t\t\tpush_back(row);\r\n\r\n\t\t\t\tif (have_var(I_TIME))\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t n = 0; n < row[I_N]; n++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_statsTime[row.m_variable][row.m_traitment].Add(row[I_TIME]);\r\n\t\t\t\t\t\tm_statsRate[row.m_variable][row.m_traitment].Add(row[I_RATE]);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t\telse if (have_var(I_MEAN_TIME) && have_var(I_N))\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t n = 0; n < row[I_N]; n++)\r\n\t\t\t\t\t\tm_statsTime[row.m_variable][row.m_traitment].Add(row[I_MEAN_TIME]);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (have_var(I_BROOD))\r\n\t\t\t\t{\r\n\t\t\t\t\tm_statsBrood[row.m_traitment][row.m_i].Add(row[I_BROOD]);\r\n\t\t\t\t}\r\n\t\t\t\telse if (have_var(I_MEAN_BROOD) && have_var(I_MEAN_TIME) && have_var(I_N))\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t n = 0; n < row[I_N]; n++)\r\n\t\t\t\t\t\tm_statsBrood[row.m_variable][row.m_traitment].Add(row[I_MEAN_BROOD]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tm_bIndividual = have_var(I_TIME);\r\n\t\tm_bAllTConstant = IsAllTConstant();\r\n\r\n\r\n\t\tif (m_bIndividual)\r\n\t\t{\r\n\r\n\t\t\t//compute reative time and qtime\r\n\t\t\t//for all variable\r\n\t\t\tfor (auto it = m_statsTime.begin(); it != m_statsTime.end(); it++)\r\n\t\t\t{\r\n\t\t\t\tstring variable = it->first;\r\n\t\t\t\tvector<pair<double, size_t>> qTime;\r\n\t\t\t\tdouble N = 0;\r\n\t\t\t\tCStatistic stat_q;\r\n\r\n\t\t\t\t//for all treatment\r\n\t\t\t\tfor (auto iit = it->second.begin(); iit != it->second.end(); iit++)\r\n\t\t\t\t{\r\n\t\t\t\t\tstring traitment = iit->first;\r\n\r\n\t\t\t\t\tdouble mean = iit->second[MEAN];\r\n\t\t\t\t\tdouble n = iit->second[NB_VALUE];\r\n\t\t\t\t\tN += n;\r\n\r\n\t\t\t\t\tfor (size_t i = 0; i < size(); i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tCDevRateDataRow& row = at(i);\r\n\t\t\t\t\t\tif (row.m_variable == variable && row.m_traitment == traitment)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tdouble rel_time = row[I_TIME] / mean;\r\n\t\t\t\t\t\t\trow[I_RDT] = rel_time;\r\n\t\t\t\t\t\t\tqTime.push_back(make_pair(rel_time, i));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}//for all traitement\r\n\r\n\t\t\t\tsort(qTime.begin(), qTime.end());\r\n\r\n\t\t\t\t//double alpha = 0.25;//alpha with 50% of the sample size\r\n\t\t\t\t//double p = 1.0 - pow(alpha, 1.0 / qTime.size());\r\n\r\n\t\t\t\t//double alpha = 0.05;//95% of the range\r\n\t\t\t\t//double p = 0.005; //99% of the range\r\n\t\t\t\t//double p = min(alpha, 1.0 - pow(alpha, 1.0 / qTime.size()));\r\n\r\n\r\n\t\t\t\t////double cumsum = 0;\r\n\t\t\t\t//for (size_t n = 0; n < qTime.size(); n++)\r\n\t\t\t\t//{\r\n\t\t\t\t//\t//double q = p + (1.0 - 2.0*p)*n / (qTime.size() - 1);\r\n\t\t\t\t//\t//nn = (0:(N - 1)) / (N - 1)\r\n\r\n\t\t\t\t//\tdouble q = max(0.005, min(0.995, p + (1.0 - 2.0*p)*n / (qTime.size() - 1)));\r\n\t\t\t\t//\tCDevRateDataRow& row = at(qTime[n].second);\r\n\t\t\t\t//\trow[I_Q_TIME] = q;\r\n\t\t\t\t//\t//cumsum += row[I_N];\r\n\t\t\t\t//}\r\n\r\n\t\t\t\tdouble cumsum = 0;\r\n\t\t\t\tfor (auto it = qTime.begin(); it != qTime.end(); it++)\r\n\t\t\t\t{\r\n\t\t\t\t\tCDevRateDataRow& row = at(it->second);\r\n\t\t\t\t\tdouble q = max(0.005, min(0.995, (cumsum + row[I_N] / 2) / N));\r\n\t\t\t\t\trow[I_Q_TIME] = q;\r\n\t\t\t\t\tcumsum += row[I_N];\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t}//for all variable\r\n\r\n\r\n\r\n\t\t\t//compute reative rate and qRate\r\n\t\t\t//for all variable\r\n\t\t\tfor (auto it = m_statsRate.begin(); it != m_statsRate.end(); it++)\r\n\t\t\t{\r\n\t\t\t\tstring variable = it->first;\r\n\t\t\t\tvector<pair<double, size_t>> qRate;\r\n\t\t\t\tdouble N = 0;\r\n\t\t\t\tCStatistic stat_qRate;\r\n\r\n\t\t\t\t//for all treatment\r\n\t\t\t\tfor (auto iit = it->second.begin(); iit != it->second.end(); iit++)\r\n\t\t\t\t{\r\n\t\t\t\t\tstring traitment = iit->first;\r\n\r\n\t\t\t\t\tdouble mean = iit->second[MEAN];\r\n\t\t\t\t\tdouble n = iit->second[NB_VALUE];\r\n\t\t\t\t\tN += n;\r\n\r\n\t\t\t\t\tfor (size_t i = 0; i < size(); i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tCDevRateDataRow& row = at(i);\r\n\t\t\t\t\t\tif (row.m_variable == variable && row.m_traitment == traitment)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tdouble RDR = row[I_RATE] / mean;\r\n\t\t\t\t\t\t\trow[I_RDR] = RDR;\r\n\t\t\t\t\t\t\tqRate.push_back(make_pair(RDR, i));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}//for all traitement\r\n\r\n\t\t\t\tsort(qRate.begin(), qRate.end());\r\n\r\n\t\t\t\t//double alpha = 0.25;//alpha with 50% of the sample size\r\n\t\t\t\t//double p = 1.0 - pow(alpha, 1.0 / qTime.size());\r\n\r\n\t\t\t\t//double alpha = 0.05;//95% of the range\r\n\t\t\t\t//double p = 0.005; //99% of the range\r\n\t\t\t\t//double p = min(alpha, 1.0 - pow(alpha, 1.0 / qRate.size()));\r\n\r\n\r\n\t\t\t\t////double cumsum = 0;\r\n\t\t\t\t//for (size_t n = 0; n < qTime.size(); n++)\r\n\t\t\t\t//{\r\n\t\t\t\t//\t//double q = p + (1.0 - 2.0*p)*n / (qTime.size() - 1);\r\n\t\t\t\t//\t//nn = (0:(N - 1)) / (N - 1)\r\n\r\n\t\t\t\t//\tdouble q = max(0.005, min(0.995, p + (1.0 - 2.0*p)*n / (qTime.size() - 1)));\r\n\t\t\t\t//\tCDevRateDataRow& row = at(qTime[n].second);\r\n\t\t\t\t//\trow[I_Q_TIME] = q;\r\n\t\t\t\t//\t//cumsum += row[I_N];\r\n\t\t\t\t//}\r\n\r\n\t\t\t\tdouble cumsum = 0;\r\n\t\t\t\tfor (auto it = qRate.begin(); it != qRate.end(); it++)\r\n\t\t\t\t{\r\n\t\t\t\t\tCDevRateDataRow& row = at(it->second);\r\n\t\t\t\t\tdouble q = max(0.005, min(0.995, (cumsum + row[I_N] / 2) / N));\r\n\t\t\t\t\trow[I_Q_RATE] = q;\r\n\t\t\t\t\tcumsum += row[I_N];\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t}//for all variable\r\n\r\n\t\t}\r\n\r\n\t\tm_bIndividualSeries = have_var(I_BROOD) && have_var(I_START) && have_var(I_TIME) && have_var(I_I);\r\n\t\tif (m_bIndividual&&have_var(I_BROOD))\r\n\t\t{\r\n\r\n\t\t\tvector<pair<double, string>> qBrood;\r\n\t\t\t//CStatistic stat_qBrood;\r\n\r\n\t\t\t//CStatistic stat_fecundity;\r\n\t\t\t////for all treatment\r\n\t\t\t//for (auto it = m_statsBrood.begin(); it != m_statsBrood.end(); it++)\r\n\t\t\t//{\r\n\t\t\t//\t//for all individual\r\n\t\t\t//\tfor (auto iit = it->second.begin(); iit != it->second.end(); iit++)\r\n\t\t\t//\t\tstat_fecundity += iit->second[SUM];\r\n\t\t\t//}\r\n\r\n\t\t\t//double mean_fecundity = stat_fecundity[MEAN];\r\n\r\n\t\t\t//for all treatment\r\n\t\t\tfor (auto it = m_statsBrood.begin(); it != m_statsBrood.end(); it++)\r\n\t\t\t{\r\n\t\t\t\tstring traitment = it->first;\r\n\r\n\t\t\t\tCStatistic stat_fecundity;\r\n\t\t\t\tfor (auto iit = it->second.begin(); iit != it->second.end(); iit++)\r\n\t\t\t\t\tstat_fecundity += iit->second[SUM];\r\n\r\n\t\t\t\tdouble mean_fecundity = stat_fecundity[MEAN];\r\n\r\n\t\t\t\t//for all individual\r\n\t\t\t\t\r\n\t\t\t\t//double fecundity = iit->second[SUM];\r\n\t\t\t\t//double RFR = fecundity / mean_fecundity;\r\n\t\t\t\t//qBrood.push_back(make_pair(RFR, iit->first));\r\n\t\t\t\t\r\n\r\n\r\n\r\n\t\t\t\t//for all observation\r\n\t\t\t\tfor (auto iit = it->second.begin(); iit != it->second.end(); iit++)\r\n\t\t\t\t{\r\n\t\t\t\t\tstring individual = iit->first;\r\n\t\t\t\t\t//for all individual\r\n\t\t\t\t\t//for (auto iit = it->second.begin(); iit != it->second.end(); iit++)\r\n\t\t\t\t\t//{\r\n\t\t\t\t\t\t//double fecundity = iit->second[SUM];\r\n\t\t\t\t\t\t//double RFR = fecundity / mean_fecundity;\r\n\t\t\t\t\t//\tqBrood.push_back(make_pair(RFR, iit->first));\r\n\t\t\t\t//\t}//for all individual\r\n\r\n\t\t\t\t\tdouble fecundity = iit->second[SUM];\r\n\t\t\t\t\tdouble RF = fecundity / mean_fecundity;\r\n\t\t\t\t\tqBrood.push_back(make_pair(RF, individual));\r\n\r\n\r\n\t\t\t\t\t//for all rows\r\n\t\t\t\t\t//for (size_t i = 0; i < size(); i++)\r\n\t\t\t\t\t//{\r\n\t\t\t\t\t//\tCDevRateDataRow& row = at(i);\r\n\t\t\t\t\t//\tif (row.m_variable == traitment && row.m_traitment == individual)\r\n\t\t\t\t\t//\t{\r\n\t\t\t\t\t//\t\tqBrood.push_back(make_pair(RF, i));\r\n\t\t\t\t\t//\t}//for all individual\r\n\t\t\t\t\t//}\r\n\t\t\t\t}\r\n\t\t\t}//for all traitement\r\n\r\n\r\n\t\t\tsort(qBrood.begin(), qBrood.end());\r\n\r\n\t\t\t//double alpha = 0.05;//95% of the range\r\n\t\t\t//double p = min(alpha, 1.0 - pow(alpha, 1.0 / qBrood.size()));\r\n\r\n\t\t\t//double cumsum = 0;\r\n\t\t\t//double N = stat_fecundity[NB_VALUE];\r\n\t\t\t//for (auto it = qBrood.begin(); it != qBrood.end(); it++)\r\n\t\t\t//{\r\n\r\n\t\t\t//\tfor (auto i = m_statsBrood.begin(); i != m_statsBrood.end(); i++)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tauto iit = i->second.find(it->second);\r\n\t\t\t//\t\tif (iit != i->second.end())\r\n\t\t\t//\t\t{\r\n\t\t\t//\t\t\t//sum of individual and not brood\r\n\t\t\t//\t\t\tdouble Brood = 1;// iit->second[SUM];\r\n\t\t\t//\t\t\tdouble q = max(0.001, min(0.999, (cumsum + Brood / 2) / N));\r\n\t\t\t//\t\t\tcumsum += Brood;\r\n\r\n\r\n\t\t\t//\t\t\tfor (size_t i = 0; i < size(); i++)\r\n\t\t\t//\t\t\t{\r\n\t\t\t//\t\t\t\tCDevRateDataRow& row = at(i);\r\n\t\t\t//\t\t\t\tif (row.m_i == it->second)\r\n\t\t\t//\t\t\t\t{\r\n\t\t\t//\t\t\t\t\trow[I_Q_BROOD] = q;\r\n\t\t\t//\t\t\t\t}\r\n\t\t\t//\t\t\t}\r\n\t\t\t//\t\t\tbreak;\r\n\t\t\t//\t\t}\r\n\t\t\t//\t}\r\n\t\t\t//}\r\n\r\n\t\t\t//size_t N = qBrood.size();//number of female\r\n\t\t\t//double cumsum = 0;\r\n\t\t\tfor (size_t i = 0; i < qBrood.size(); i++)\r\n\t\t\t{\r\n\t\t\t\t\r\n\t\t\t\t//double q = max(0.005, min(0.995, (cumsum + row[I_N] / 2) / N));\r\n\t\t\t\tdouble q = max(0.005, min(0.995, (i + 0.5) / qBrood.size()));\r\n\r\n\t\t\t\t//apply this quantile to all observation for this individual\r\n\t\t\t\tstring individual = qBrood[i].second;\r\n\t\t\t\tfor (size_t i = 0; i < size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tCDevRateDataRow& row = at(i);\r\n\t\t\t\t\tif (row.m_i == individual)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tASSERT(row[I_N] == 1);\r\n\t\t\t\t\t\tCDevRateDataRow& row = at(i);\r\n\t\t\t\t\t\trow[I_Q_BROOD] = q;\r\n\t\t\t\t\t}//for all individual\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\r\n\t\t\t//sort(begin(), end(), [](const CDevRateDataRow& a, const CDevRateDataRow& b) {return a.at(I_Q_BROOD) < b.at(I_Q_BROOD); });\r\n\r\n\r\n\r\n\t\t}//if individual\r\n\t\telse if (have_var(I_MEAN_TIME) && have_var(I_TIME_SD) && have_var(I_N))\r\n\t\t{\r\n\t\t\t//CDevRateData new_data;\r\n\t\t\t////for all variable\r\n\t\t\t//for (auto it = m_statsTime.begin(); it != m_statsTime.end(); it++)\r\n\t\t\t//{\r\n\t\t\t//\tstring variable = it->first;\r\n\t\t\t//\t//vector<pair<double, size_t>> qTime;\r\n\r\n\t\t\t//\tCStatistic stat_wm;\r\n\t\t\t//\tCStatistic stat_n;\r\n\r\n\t\t\t//\t//for all treatment\r\n\t\t\t//\t//for (auto iit = it->second.begin(); iit != it->second.end(); iit++)\r\n\t\t\t//\t//{\r\n\t\t\t//\t\t//string traitment = iit->first;\r\n\r\n\t\t\t//\t\t//double mean = iit->second[MEAN];\r\n\t\t\t//\t\t//double n = iit->second[NB_VALUE];\r\n\r\n\t\t\t//\tfor (size_t i = 0; i < size(); i++)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tCDevRateDataRow& row = at(i);\r\n\t\t\t//\t\tif (row.m_variable == variable/* && row.m_traitment == traitment*/)\r\n\t\t\t//\t\t{\r\n\t\t\t//\t\t\tdouble mean = row[I_MEAN_TIME];\r\n\t\t\t//\t\t\tdouble n = row[I_N];\r\n\r\n\t\t\t//\t\t\tif (n > 0)\r\n\t\t\t//\t\t\t{\r\n\t\t\t//\t\t\t\tstat_wm += mean * n;\r\n\t\t\t//\t\t\t\tstat_n += n;\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//\t//}//for all traitement\r\n\r\n\r\n\t\t\t//\tdouble M = stat_n[NB_VALUE];\r\n\t\t\t//\tdouble N = stat_n[SUM];\r\n\t\t\t//\tdouble wm = stat_wm[SUM] / N;\r\n\t\t\t//\tCStatistic stat_wsd;\r\n\r\n\r\n\t\t\t//\t//for all treatment\r\n\t\t\t//\t//for (auto iit = it->second.begin(); iit != it->second.end(); iit++)\r\n\t\t\t//\t//{\r\n\t\t\t//\t\t//string traitment = iit->first;\r\n\r\n\t\t\t//\t\t//double mean = iit->second[MEAN];\r\n\t\t\t//\t\t//double n = iit->second[NB_VALUE];\r\n\r\n\t\t\t//\tfor (size_t i = 0; i < size(); i++)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tCDevRateDataRow& row = at(i);\r\n\t\t\t//\t\tif (row.m_variable == variable /*&& row.m_traitment == traitment*/)\r\n\t\t\t//\t\t{\r\n\t\t\t//\t\t\tdouble mean = row[I_MEAN_TIME];\r\n\t\t\t//\t\t\tdouble n = row[I_N];\r\n\t\t\t//\t\t\tif (n > 0)\r\n\t\t\t//\t\t\t{\r\n\t\t\t//\t\t\t\tstat_wsd += n * Square(mean - wm);\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//\t//}//for all traitement\r\n\r\n\t\t\t//\tdouble wsd = sqrt(stat_wsd[SUM] / ((M - 1) / M * N));\r\n\t\t\t//\tdouble mu = log(Square(wm) / sqrt(Square(wsd) + Square(wm)));\r\n\t\t\t//\tdouble sigma = sqrt(log(Square(wsd) / Square(wm) + 1));\r\n\t\t\t//\tboost::math::lognormal_distribution<double> LogNormal(mu, sigma);\r\n\r\n\r\n\t\t\t//\t//randomize order \r\n\t\t\t//\tvector<size_t> order(N);\r\n\r\n\t\t\t//\tfor (size_t i = 0; i < N; i++)\r\n\t\t\t//\t\torder[i] = i;\r\n\r\n\t\t\t//\tauto rng = std::default_random_engine{};\r\n\t\t\t//\tstd::shuffle(order.begin(), order.end(), rng);\r\n\r\n\t\t\t//\t//for all treatment \r\n\t\t\t//\t//size_t ii = 0;\r\n\t\t\t//\t//for (auto iit = it->second.begin(); iit != it->second.end(); iit++)\r\n\t\t\t//\t//{\r\n\t\t\t//\t\t//string traitment = iit->first;\r\n\r\n\t\t\t//\t\t//double mean = iit->second[MEAN];\r\n\t\t\t//\t\t//double n = iit->second[NB_VALUE];\r\n\t\t\t//\t\t//N += n;\r\n\r\n\t\t\t//\tfor (size_t i = 0, ii=0; i < size(); i++)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tCDevRateDataRow& row = at(i);\r\n\t\t\t//\t\tif (row.m_variable == variable /*&& row.m_traitment == traitment*/)\r\n\t\t\t//\t\t{\r\n\t\t\t//\t\t\tfor (size_t j = 0; j < size_t(row[I_N]); j++)\r\n\t\t\t//\t\t\t{\r\n\t\t\t//\t\t\t\tsize_t n = order[ii];\r\n\t\t\t//\t\t\t\tdouble p = 0.005;\r\n\t\t\t//\t\t\t\tdouble q = p + (1.0 - 2 * p)*n / (N - 1);\r\n\t\t\t//\t\t\t\tdouble time = ceil( quantile(LogNormal, q));\r\n\t\t\t//\t\t\t\t//#row[I_Q_TIME] = q;\r\n\t\t\t//\t\t\t\t//ow[I_TIME] = time;\r\n\t\t\t//\t\t\t\tii++;\r\n\r\n\r\n\t\t\t//\t\t\t\tCDevRateDataRow new_row = row;\r\n\t\t\t//\t\t\t\tnew_row[I_Q_TIME] = q;\r\n\t\t\t//\t\t\t\tnew_row[I_TIME] = time;\r\n\t\t\t//\t\t\t\tnew_row[I_N] = 1;\r\n\t\t\t//\t\t\t\tnew_data.push_back(new_row);\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//\t//}//for all traitement\r\n\r\n\t\t\t//\t//treat this simulation like an individual one\r\n\r\n\t\t\t//}//for all variable\r\n\r\n\r\n\t\t\t//new_data.m_bIndividual = true;\r\n\t\t\t//*this = new_data;\r\n\t\t\t//create individual values from mean, sd and N\r\n\t\t\t//for all variable\r\n\t\t\t//for (auto it = m_statsTime.begin(); it != m_statsTime.end(); it++)\r\n\t\t\t//{\r\n\t\t\t//\tstring varible = it->first;\r\n\t\t\t//\tvector<pair<double, size_t>> qTime;\r\n\t\t\t//\tdouble N = 0;\r\n\t\t\t//\t//for all traitment of this variable\r\n\t\t\t//\tfor (auto iit = it->second.begin(); iit != it->second.end(); iit++)\r\n\t\t\t//\t\tN += iit->second[NB_VALUE];\r\n\r\n\t\t\t//\tfor (auto iit = it->second.begin(); iit != it->second.end(); iit++)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tstring traitment = iit->first;\r\n\r\n\t\t\t//\t\tdouble mean = iit->second[MEAN];\r\n\t\t\t//\t\tdouble sd = iit->second[STD_DEV];\r\n\t\t\t//\t\tdouble mu = log(Square(mean) / sqrt(Square(sd) + Square(mean)));\r\n\t\t\t//\t\tdouble sigma = sqrt(log(Square(sd) / Square(mean) + 1));\r\n\t\t\t//\t\tdouble n = iit->second[NB_VALUE];\r\n\r\n\t\t\t//\t\tboost::math::lognormal_distribution<double> LogNormal(mu, sigma);\r\n\t\t\t//\t\tfor (size_t n = 0; n < N; n++)\r\n\t\t\t//\t\t{\r\n\t\t\t//\t\t\t//simulate N obs on the log-normal distribution with alpha = 0.05\r\n\t\t\t//\t\t\tdouble q = 0.025 + (1.0 - 2*0.025)*n / (N - 1);\r\n\t\t\t//\t\t\tdouble time = quantile(LogNormal, q);\r\n\t\t\t//\t\t}\r\n\t\t\t//\t}\r\n\r\n\t\t\t//\tdouble cumsum = 0;\r\n\t\t\t//\tfor (auto it = qTime.begin(); it != qTime.end(); it++)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tCDevRateDataRow& row = at(it->second);\r\n\t\t\t//\t\tdouble q = max(0.001, min(0.999, (cumsum + row[I_N] / 2) / N));\r\n\t\t\t//\t\trow[I_Q_TIME] = q;\r\n\t\t\t//\t\tcumsum += row[I_N];\r\n\t\t\t//\r\n\t\t\t//\t}\r\n\t\t\t//}\r\n\r\n\t\t\t//m_bIndividual = have_var(I_TIME);\r\n\t\t}\r\n\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\tbool CDevRateData::IsAllTConstant()const\r\n\t{\r\n\t\tbool bAllTConstant = true;\r\n\r\n\t\tfor (size_t i = 0; i < size() && bAllTConstant; i++)\r\n\t\t\tbAllTConstant = at(i).m_type == T_CONSTANT;\r\n\r\n\t\treturn bAllTConstant;\r\n\t}\r\n\r\n\tdouble CDevRateData::ei(size_t n) { return pow(1.0 + 1.0 / n, n); }\r\n\tdouble CDevRateData::cv_2_sigma(double cv, size_t n)\r\n\t{\r\n\t\tstatic const double e = exp(1);\r\n\t\tstatic const double p[3] = { 0.528196, 2.373248, 3.493202 };//with 10 000 replication\r\n\t\treturn e * cv*(1 - p[0] * sqrt(e - ei(n))) / (p[1] + cv * (1 - p[2] * sqrt(e - ei(n))));\r\n\t}\r\n\r\n\tdouble CDevRateData::GetDefaultSigma(const std::string& variable)const\r\n\t{\r\n\r\n\t\tCStatistic stat_ws;\r\n\t\tCStatistic stat_n;\r\n\r\n\r\n\t\t//compute sigma\r\n\t\tif (m_bIndividual)\r\n\t\t{\r\n\t\t\tconst std::map<std::string, CStatisticEx>& stat = m_statsTime.at(variable);\r\n\t\t\t//for all treatment\r\n\t\t\tfor (auto it = stat.begin(); it != stat.end(); it++)\r\n\t\t\t{\r\n\t\t\t\t//string traitment = it->first;\r\n\r\n\t\t\t\tdouble mean = it->second[MEAN];\r\n\t\t\t\tdouble sd = it->second[STD_DEV];\r\n\t\t\t\tdouble n = it->second[NB_VALUE];\r\n\t\t\t\tif (n > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble cv = sd / mean;\r\n\t\t\t\t\tdouble sigma = cv_2_sigma(cv, n);\r\n\r\n\t\t\t\t\tstat_ws += n * cv;\r\n\t\t\t\t\tstat_n += n;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\r\n\r\n\t\t\t//for all treatment\r\n\t\t\tfor (size_t i = 0; i < size(); i++)\r\n\t\t\t{\r\n\t\t\t\tconst CDevRateDataRow& row = at(i);\r\n\t\t\t\tif (row.m_variable == variable)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble mean = row.at(I_MEAN_TIME);\r\n\t\t\t\t\tdouble sd = row.at(I_TIME_SD);\r\n\t\t\t\t\tdouble n = row.at(I_N);\r\n\r\n\t\t\t\t\tif (n > 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble cv = sd / mean;\r\n\t\t\t\t\t\tdouble sigma = cv_2_sigma(cv, n);\r\n\r\n\t\t\t\t\t\tstat_ws += n * sigma;\r\n\t\t\t\t\t\tstat_n += n;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tASSERT(stat_n[SUM] > 0);\r\n\t\tdouble sigma = stat_ws[SUM] / stat_n[SUM];\r\n\t\treturn sigma;\r\n\t}\r\n\r\n\r\n\tdouble CDevRateData::GetSigmaBrood(TDevRateEquation  e, const std::vector<double>& X, const vector<double>& T)const\r\n\t{\r\n\t\tdouble sigma = 0;\r\n\r\n\t\t//compute sigma\r\n\t\tif (m_bIndividualSeries)\r\n\t\t{\r\n\r\n\t\t\t//CStatistic stat_wm;\r\n\t\t\t//CStatistic stat_ws;\r\n\t\t\t//CStatistic stat_n;\r\n\t\t\tCStatistic stat;\r\n\r\n\t\t\t//for all treatment\r\n\t\t\tfor (auto it = m_statsBrood.begin(); it != m_statsBrood.end(); it++)\r\n\t\t\t{\r\n\r\n\r\n\t\t\t\tconst std::map<std::string, CStatisticEx>& individuals = it->second;\r\n\t\t\t\t//for all individuals\r\n\t\t\t\tfor (auto iit = individuals.begin(); iit != individuals.end(); iit++)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble broods = iit->second[SUM];//sum af all observations\r\n\t\t\t\t\tdouble lambda = max(0.0, CDevRateEquation::GetRate(e, X, T[0]));//remaining eggs\r\n\t\t\t\t\tdouble Fi = broods / (1 - exp(-lambda * iit->second[NB_VALUE]));//a revoir estimer seulement....\r\n\t\t\t\t\tstat += Fi;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\r\n\t\t\tdouble mean = stat[MEAN];//mean of all individuals\r\n\t\t\tdouble sd = stat[STD_DEV];\r\n\t\t\tsigma = sqrt(log(Square(sd) / Square(mean) + 1));\r\n\r\n\t\t\t//sigma = sqrt(log(Square(sd) / Square(mean) + 1));\r\n\t\t\t//sigma = stat_ws[SUM] / stat_n[SUM];\r\n\t\t\t//F = stat_wm[SUM] / stat_n[SUM];\r\n\r\n\r\n\r\n\t\t}\r\n\t\telse if (m_bIndividual)\r\n\t\t{\r\n\t\t\tCStatistic stat;\r\n\t\t\t//CStatistic stat_ws;\r\n\t\t\t//CStatistic stat_n;\r\n\r\n\r\n\r\n\t\t\t//for all treatment\r\n\t\t\tfor (size_t i = 0; i < size(); i++)\r\n\t\t\t{\r\n\t\t\t\tconst CDevRateDataRow& row = at(i);\r\n\t\t\t\tdouble lambda = max(0.0, CDevRateEquation::GetRate(e, X, T[0]));//remaining eggs\r\n\t\t\t\tdouble Fi = row.at(I_BROOD) / (1 - exp(-lambda * row.at(I_TIME)));\r\n\t\t\t\tstat += Fi;\r\n\t\t\t}\r\n\r\n\t\t\tASSERT(stat[SUM] > 0);\r\n\r\n\t\t\tdouble mean = stat[MEAN];\r\n\t\t\tdouble sd = stat[STD_DEV];\r\n\r\n\t\t\tsigma = sqrt(log(Square(sd) / Square(mean) + 1));\r\n\r\n\r\n\t\t}\r\n\r\n\t\treturn sigma;\r\n\t}\r\n\r\n\tdouble CDevRateData::GetDefaultSigma()const\r\n\t{\r\n\r\n\t\tdouble sigma = 0;\r\n\t\tCStatistic stat_wm;\r\n\t\tCStatistic stat_ws;\r\n\t\tCStatistic stat_n;\r\n\r\n\r\n\r\n\t\t//for all treatment\r\n\t\tfor (size_t i = 0; i < size(); i++)\r\n\t\t{\r\n\t\t\tconst CDevRateDataRow& row = at(i);\r\n\t\t\t//if (row.m_variable == variable)\r\n\t\t\t{\r\n\t\t\t\tdouble mean = row.at(I_MEAN_BROOD);\r\n\t\t\t\tdouble sd = row.at(I_BROOD_SD);\r\n\t\t\t\tdouble n = row.at(I_N);\r\n\r\n\t\t\t\tif (n > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble cv = sd / mean;\r\n\t\t\t\t\tdouble sigma = cv_2_sigma(cv, n);\r\n\r\n\t\t\t\t\tstat_wm += n * mean;\r\n\t\t\t\t\tstat_ws += n * sigma;\r\n\t\t\t\t\tstat_n += n;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tASSERT(stat_n[SUM] > 0);\r\n\r\n\t\tsigma = stat_ws[SUM] / stat_n[SUM];\r\n\t\t//F = stat_wm[SUM] / stat_n[SUM];\r\n\r\n\r\n\r\n\t\t//double sigma = stat_ws[SUM] / stat_n[SUM];\r\n\r\n\t\treturn sigma;\r\n\t}\r\n\r\n\t//**********************************************************************************************\r\n\t//CDevRateEqFile\r\n\r\n\tCDevRateEqFile::CDevRateEqFile()\r\n\t{}\r\n\r\n\tCDevRateEqFile::~CDevRateEqFile()\r\n\t{}\r\n\r\n\tERMsg CDevRateEqFile::load(const std::string& file_path)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\t//begin to read\r\n\t\tifStream file;\r\n\t\tmsg = file.open(file_path);\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tmsg = load(file);\r\n\t\t\tfile.close();\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\tERMsg CDevRateEqFile::load(std::istream& io)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\tclear();\r\n\r\n\t\tstatic const char* COL_NAME[3] = { \"Variable\", \"EqName\", \"P\" };\r\n\r\n\t\tstd::vector<size_t> col_pos;\r\n\r\n\t\tfor (CSVIterator loop(io, \",;\\t|\", true, true); loop != CSVIterator() && msg; ++loop)\r\n\t\t{\r\n\t\t\tif (col_pos.empty())\r\n\t\t\t{\r\n\t\t\t\tfor (size_t i = 0; i < 3; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tstring find = COL_NAME[i];\r\n\t\t\t\t\tauto itr = std::find_if(loop.Header().begin(), loop.Header().end(),\r\n\t\t\t\t\t\t[&](auto &s)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (IsEqual(s, find))\r\n\t\t\t\t\t\t\treturn true;\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t);\r\n\r\n\t\t\t\t\tif (itr != loop.Header().end())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcol_pos.push_back(std::distance(loop.Header().begin(), itr));\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\tmsg.ajoute(string(\"Mandatory missing column. \") + COL_NAME[i] + \" must be define\");\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\r\n\t\t\tif (msg)\r\n\t\t\t{\r\n\t\t\t\tstring var_name = (*loop)[col_pos[0]];\r\n\t\t\t\tstring eq_name = (*loop)[col_pos[1]];\r\n\t\t\t\tstring str_param = (*loop)[col_pos[2]];\r\n\r\n\t\t\t\tstd::vector<double> P;\r\n\t\t\t\tmsg = CDevRateEquation::GetParamfromString(eq_name, str_param, P);\r\n\t\t\t\tif (msg)\r\n\t\t\t\t{\r\n\t\t\t\t\t(*this)[var_name] = make_pair(CDevRateEquation::eq(eq_name), P);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\r\n\r\n\t//**********************************************************************************************\r\n\t//CSurvivalData \r\n\r\n\t/*size_t CSurvivalData::get_pos(TDevTimeCol c)const\r\n\t{\r\n\t\tsize_t pos = NOT_INIT;\r\n\t\tauto it = find(m_input_pos.begin(), m_input_pos.end(), c);\r\n\t\tif (it != m_input_pos.end())\r\n\t\t\tpos = std::distance(m_input_pos.begin(), it);\r\n\r\n\t\treturn pos;\r\n\t}*/\r\n\r\n\r\n\tCSurvivalData::CSurvivalData()\r\n\t{}\r\n\r\n\tCSurvivalData::~CSurvivalData()\r\n\t{}\r\n\r\n\r\n\tERMsg CSurvivalData::load(const std::string& file_path)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\t//begin to read\r\n\t\tifStream file;\r\n\t\tmsg = file.open(file_path);\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tmsg = load(file);\r\n\t\t\tfile.close();\r\n\t\t}\r\n\r\n\t\tif (!msg)\r\n\t\t\tmsg.ajoute(\"Error when reading file:\" + file_path);\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\tERMsg CSurvivalData::load(std::istream& io)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\tclear();\r\n\t\tm_input_pos.clear();\r\n\t\t//m_bIndividual = false;\r\n\r\n\r\n\r\n\t\tfor (CSVIterator loop(io, \",;\\t|\", true, true); loop != CSVIterator() && msg; ++loop)\r\n\t\t{\r\n\t\t\tif (m_input_pos.empty())\r\n\t\t\t{\r\n\t\t\t\tfor (size_t i = 0; i < loop.Header().size(); i++)\r\n\t\t\t\t\tm_input_pos.push_back(CDevRateData::get_input(loop.Header()[i]));\r\n\r\n\t\t\t\tif (!have_var(I_TRAITMENT))\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(\"Mandatory missing column. \\\"T\\\" must be define\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (!have_var(I_MEAN_TIME))\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(\"Mandatory missing column.  \\\"MeanTime\\\" must be define\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (!have_var(I_N))\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(\"Mandatory missing column: \\\"N\\\" must be define\");\r\n\t\t\t\t}\r\n\t\t\t\t//check for mandatory columns\r\n\t\t\t\tif (!have_var(I_SURVIVAL))\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(\"Mandatory missing column: \\\"Survival\\\" must be define\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\r\n\t\t\tif (msg && !loop->empty())\r\n\t\t\t{\r\n\t\t\t\tif (loop->size() != m_input_pos.size())\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(\"Bad number of column for line:\" + loop->GetLastLine());\r\n\t\t\t\t\treturn msg;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tCDevRateDataRow row;\r\n\t\t\t\tfor (size_t i = 0; i < m_input_pos.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (m_input_pos[i] != I_UNKNOWN)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (m_input_pos[i] == I_VARIABLE)\r\n\t\t\t\t\t\t\trow.m_variable = (*loop)[i];\r\n\t\t\t\t\t\telse if (m_input_pos[i] == I_TRAITMENT)\r\n\t\t\t\t\t\t\trow.m_traitment = (*loop)[i];\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\trow[m_input_pos[i]] = ToDouble((*loop)[i]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\trow.m_type = get_TType(row.m_traitment);\r\n\r\n\t\t\t\tpush_back(row);\r\n\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\r\n\r\n\r\n\t//**********************************************************************************************\r\n\t//CInsectParameterization\r\n\tconst char* CInsectParameterization::DATA_DESCRIPTOR = \"InsectParameterizationData\";\r\n\tconst char* CInsectParameterization::XML_FLAG = \"InsectParameterization\";\r\n\tconst char* CInsectParameterization::MEMBERS_NAME[NB_MEMBERS_EX] = { \"FitType\", \"DevRateEquations\", \"SurvivalEquations\", \"FecundityEquations\",\"EquationsOptions\", \"InputFileName\", \"TobsFileName\", \"OutputFileName\", \"Control\", \"Fixe_Tb\", \"Tb_Value\", \"Fixe_To\", \"To_Value\", \"Fixe_Tm\", \"Tm_Value\", \"Fixe_F0\", \"F0_Value\", \"UseOutputAsInput\", \"OutputAsIntputFileName\", \"ShowTrace\" };\r\n\r\n\tconst int CInsectParameterization::CLASS_NUMBER = CExecutableFactory::RegisterClass(CInsectParameterization::GetXMLFlag(), &CInsectParameterization::CreateObject);\r\n\r\n\tCInsectParameterization::CInsectParameterization()\r\n\t{\r\n\t\tReset();\r\n\t}\r\n\r\n\tCInsectParameterization::~CInsectParameterization()\r\n\t{}\r\n\r\n\r\n\tCInsectParameterization::CInsectParameterization(const CInsectParameterization& in)\r\n\t{\r\n\t\toperator=(in);\r\n\t}\r\n\r\n\r\n\tvoid CInsectParameterization::Reset()\r\n\t{\r\n\t\tCExecutable::Reset();\r\n\r\n\t\tm_fitType = F_DEV_TIME_WTH_SIGMA;\r\n\t\tm_name = \"InsectParameterization\";\r\n\t\tm_eqDevRate.set();\r\n\t\tm_eqSurvival.set();\r\n\t\tm_eqFecundity.set();\r\n\t\tm_eq_options.clear();\r\n\t\tm_inputFileName.clear();\r\n\t\tm_TobsFileName.clear();\r\n\t\tm_outputFileName = \"%i\";//same as input file name\r\n\t\tm_bFixeTb = false;\r\n\t\tm_Tb = { 5,5,1 };\r\n\t\tm_bFixeTo = false;\r\n\t\tm_To = { 20,20,1 };\r\n\t\tm_bFixeTm = false;\r\n\t\tm_Tm = { 35,35,1 };\r\n\t\tm_bFixeF0 = false;\r\n\t\tm_F0 = { 100,100,1 };\r\n\r\n\t\tm_bUseOutputAsInput = false;\r\n\t\tm_outputAsIntputFileName.clear();\r\n\t\tm_bShowTrace = false;\r\n\r\n\r\n\t\t//m_calibOn = CO_RATE;\r\n//\t\tm_bConverge01 = false;\r\n\t//\tm_bCalibSigma = false;\r\n\r\n\r\n\t\tm_ctrl.Reset();\r\n\t\tm_ctrl.m_bMax = true;\r\n\t\tm_ctrl.m_statisticType = LIKELIHOOD;\r\n\t\tm_ctrl.m_MAXEVL = 1000000;\r\n\t\tm_ctrl.m_NS = 15;\r\n\t\tm_ctrl.m_NT = 20;\r\n\t\tm_ctrl.m_T = 10;\r\n\t\tm_ctrl.m_RT = 0.5;\r\n\r\n\r\n\t\tm_Tobs.clear();\r\n\t\tm_devTime.clear();\r\n\t\tm_survival.clear();\r\n\t\tm_fecundity.clear();\r\n\t}\r\n\r\n\r\n\tCInsectParameterization& CInsectParameterization::operator =(const CInsectParameterization& in)\r\n\t{\r\n\t\tif (&in != this)\r\n\t\t{\r\n\t\t\tCExecutable::operator =(in);\r\n\r\n\t\t\tm_fitType = in.m_fitType;\r\n\t\t\tm_eqDevRate = in.m_eqDevRate;\r\n\t\t\tm_eqSurvival = in.m_eqSurvival;\r\n\t\t\tm_eqFecundity = in.m_eqFecundity;\r\n\t\t\tm_eq_options = in.m_eq_options;\r\n\t\t\tm_inputFileName = in.m_inputFileName;\r\n\t\t\tm_TobsFileName = in.m_TobsFileName;\r\n\t\t\tm_outputFileName = in.m_outputFileName;\r\n\t\t\tm_bFixeTb = in.m_bFixeTb;\r\n\t\t\tm_Tb = in.m_Tb;\r\n\t\t\tm_bFixeTo = in.m_bFixeTo;\r\n\t\t\tm_To = in.m_To;\r\n\t\t\tm_bFixeTm = in.m_bFixeTm;\r\n\t\t\tm_Tm = in.m_Tm;\r\n\t\t\tm_bFixeF0 = in.m_bFixeF0;\r\n\t\t\tm_F0 = in.m_F0;\r\n\t\t\tm_bUseOutputAsInput = in.m_bUseOutputAsInput;\r\n\t\t\tm_outputAsIntputFileName = in.m_outputAsIntputFileName;\r\n\t\t\tm_bShowTrace = in.m_bShowTrace;\r\n\r\n\r\n\r\n\t\t\tm_ctrl = in.m_ctrl;\r\n\t\t}\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tbool CInsectParameterization::operator == (const CInsectParameterization& in)const\r\n\t{\r\n\t\tbool bEqual = true;\r\n\r\n\t\tif (CExecutable::operator!=(in))bEqual = false;\r\n\t\tif (m_fitType != in.m_fitType)bEqual = false;\r\n\t\tif (m_eqDevRate != in.m_eqDevRate) bEqual = false;\r\n\t\tif (m_eqSurvival != in.m_eqSurvival) bEqual = false;\r\n\t\tif (m_eqFecundity != in.m_eqFecundity) bEqual = false;\r\n\t\tif (m_eq_options != in.m_eq_options)bEqual = false;\r\n\t\tif (m_inputFileName != in.m_inputFileName) bEqual = false;\r\n\t\tif (m_TobsFileName != in.m_TobsFileName) bEqual = false;\r\n\r\n\t\tif (m_outputFileName != in.m_outputFileName) bEqual = false;\r\n\t\tif (m_ctrl != in.m_ctrl)bEqual = false;\r\n\t\tif (m_bFixeTb != in.m_bFixeTb)bEqual = false;\r\n\t\tif (m_Tb != in.m_Tb)bEqual = false;\r\n\t\tif (m_bFixeTo != in.m_bFixeTo)bEqual = false;\r\n\t\tif (m_To != in.m_To)bEqual = false;\r\n\t\tif (m_bFixeTm != in.m_bFixeTm)bEqual = false;\r\n\t\tif (m_Tm != in.m_Tm)bEqual = false;\r\n\t\tif (m_bFixeF0 != in.m_bFixeF0)bEqual = false;\r\n\t\tif (m_F0 != in.m_F0)bEqual = false;\r\n\t\tif (m_bUseOutputAsInput != in.m_bUseOutputAsInput)bEqual = false;\r\n\t\tif (m_outputAsIntputFileName != in.m_outputAsIntputFileName)bEqual = false;\r\n\t\tif (m_bShowTrace != in.m_bShowTrace)bEqual = false;\r\n\r\n\r\n\t\treturn bEqual;\r\n\t}\r\n\r\n\tERMsg CInsectParameterization::GetParentInfo(const CFileManager& fileManager, CParentInfo& info, CParentInfoFilter filter)const\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\t//same as weather generator variables\r\n\t\tif (filter[LOCATION])\r\n\t\t{\r\n\t\t\tinfo.m_locations.resize(1);\r\n\t\t\tinfo.m_locations[0].m_name = \"Mean over location\";\r\n\t\t}\r\n\t\tif (filter[PARAMETER])\r\n\t\t{\r\n\t\t\tinfo.m_parameterset.clear();\r\n\r\n\t\t\tCModelInput modelInput;\r\n\r\n\t\t\tmodelInput.SetName(\"T\");\r\n\t\t\tmodelInput.push_back(CModelInputParam(\"T\", \"15\"));\r\n\t\t\tinfo.m_parameterset.push_back(modelInput);\r\n\r\n\t\t\tinfo.m_parameterset.m_pioneer = modelInput;\r\n\t\t\tinfo.m_parameterset.m_variation.SetType(CParametersVariationsDefinition::SYSTEMATIC_VARIATION);\r\n\t\t\tinfo.m_parameterset.m_variation.push_back(CParameterVariation(\"T\", true, CModelInputParameterDef::kMVReal, 0, 35, 0.5));\r\n\r\n\t\t}\r\n\t\tif (filter[REPLICATION])\r\n\t\t{\r\n\t\t\tinfo.m_nbReplications = 1;\r\n\t\t}\r\n\t\tif (filter[TIME_REF])\r\n\t\t{\r\n\t\t\tCTM TM(CTM::ATEMPORAL, CTM::OVERALL_YEARS);\r\n\t\t\tinfo.m_period = CTPeriod(CTRef(YEAR_NOT_INIT, 0, 0, 0, TM), CTRef(YEAR_NOT_INIT, 0, 0, 0, TM));\r\n\t\t}\r\n\t\tif (filter[VARIABLE])\r\n\t\t{\r\n\t\t\tinfo.m_variables.clear();\r\n\r\n\t\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA || m_fitType == F_DEV_TIME_ONLY)\r\n\t\t\t{\r\n\t\t\t\t//for all equation\r\n\t\t\t\tfor (size_t e = 0; e < m_eqDevRate.size(); e++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (m_eqDevRate.test(e))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tTDevRateEquation  eq = CDevRateEquation::eq(e);\r\n\r\n\t\t\t\t\t\tstd::string name = CDevRateEquation::GetEquationName(eq);\r\n\t\t\t\t\t\tstd::string title = CDevRateEquation::GetEquationName(eq);\r\n\t\t\t\t\t\tstd::string units = \"1/day\";\r\n\t\t\t\t\t\tstd::string description = \"Development rate\";\r\n\t\t\t\t\t\tinfo.m_variables.push_back(CModelOutputVariableDef(name, title, units, description));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if (m_fitType == F_SURVIVAL)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t e = 0; e < m_eqSurvival.size(); e++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (m_eqSurvival.test(e))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tTSurvivalEquation eq = CSurvivalEquation::eq(e);\r\n\r\n\t\t\t\t\t\tstd::string name = CSurvivalEquation::GetEquationName(eq);\r\n\t\t\t\t\t\tstd::string title = CSurvivalEquation::GetEquationName(eq);\r\n\t\t\t\t\t\tstd::string units = \"%\";\r\n\t\t\t\t\t\tstd::string description = \"Survival\";\r\n\t\t\t\t\t\tinfo.m_variables.push_back(CModelOutputVariableDef(name, title, units, description));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if (m_fitType == F_FECUNDITY)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t e = 0; e < m_eqFecundity.size(); e++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (m_eqFecundity.test(e))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tTDevRateEquation  eq = CDevRateEquation::eq(e);\r\n\r\n\t\t\t\t\t\tstd::string name = CDevRateEquation::GetEquationName(eq);\r\n\t\t\t\t\t\tstd::string title = CDevRateEquation::GetEquationName(eq);\r\n\t\t\t\t\t\tstd::string units = \"Eggs/day\";\r\n\t\t\t\t\t\tstd::string description = \"Fecundity rate\";\r\n\t\t\t\t\t\tinfo.m_variables.push_back(CModelOutputVariableDef(name, title, units, description));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\tstring to_string(const CSAParameterVector& P)\r\n\t{\r\n\t\tstd::ostringstream streamObj;\r\n\r\n\t\tfor (size_t i = 0; i < P.size(); i++)\r\n\t\t{\r\n\t\t\tif (i > 0)\r\n\t\t\t\tstreamObj << \" \";\r\n\r\n\t\t\tstreamObj << P[i].m_name << \"=\" << std::scientific << std::setprecision(6) << P[i].m_initialValue;\r\n\t\t}\r\n\r\n\t\t// Get string from output string stream\r\n\t\treturn streamObj.str();\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n\tERMsg CInsectParameterization::Execute(const CFileManager& fileManager, CCallback& callback)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\tstatic const char* TYPE_NAME[NB_FIT_TYPE] = { \"Development time (with sigma)\",\"Development time only\",\"Survival\", \"Oviposition\" };\r\n\t\tbool bLogLikelyhoude = m_ctrl.m_statisticType == LIKELIHOOD;\r\n\r\n\r\n\r\n\r\n\r\n\t\tCResult resultDB;\r\n\t\tmsg = resultDB.Open(GetDBFilePath(GetPath(fileManager)), std::fstream::out | std::fstream::binary);\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tcallback.AddMessage(GetString(IDS_WG_PROCESS_INPUT_ANALYSIS));\r\n\t\t\tcallback.AddMessage(resultDB.GetFilePath(), 1);\r\n\r\n\r\n\t\t\tCParentInfo info;\r\n\t\t\tmsg = GetParentInfo(fileManager, info);\r\n\t\t\tif (msg)\r\n\t\t\t{\r\n\t\t\t\tstring output_file_name = !m_outputFileName.empty() ? m_outputFileName : GetFileTitle(m_inputFileName);\r\n\t\t\t\tSetFileExtension(output_file_name, \".csv\");\r\n\t\t\t\tReplaceString(output_file_name, \"%i\", GetFileTitle(m_inputFileName));\r\n\t\t\t\tstring outputFilePath = fileManager.GetOutputPath() + output_file_name;\r\n\r\n\r\n\r\n\t\t\t\tCDBMetadata& metadata = resultDB.GetMetadata();\r\n\t\t\t\tmetadata.SetLocations(info.m_locations);\r\n\t\t\t\tmetadata.SetParameterSet(info.m_parameterset);\r\n\t\t\t\tmetadata.SetNbReplications(info.m_nbReplications);\r\n\t\t\t\tmetadata.SetTPeriod(info.m_period);\r\n\t\t\t\tmetadata.SetOutputDefinition(info.m_variables);\r\n\r\n\t\t\t\tcallback.AddMessage(FormatMsg(IDS_SIM_CREATE_DATABASE, m_name));\r\n\t\t\t\tcallback.AddMessage(resultDB.GetFilePath(), 1);\r\n\r\n\r\n\r\n\t\t\t\t//set vMiss value\r\n\t\t\t\tm_ctrl.SetVMiss(m_ctrl.AdjustFValue(DBL_MAX));\r\n\r\n\r\n\t\t\t\tstring inputFilePath = fileManager.Input().GetFilePath(m_inputFileName);\r\n\r\n\t\t\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA || m_fitType == F_DEV_TIME_ONLY)\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg = m_devTime.load(inputFilePath);\r\n\t\t\t\t}\r\n\t\t\t\telse if (m_fitType == F_SURVIVAL)\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg += m_survival.load(inputFilePath);\r\n\t\t\t\t\t//msg += m_dev_rate_eq.load(\"G:/Travaux/LaricobiusOsakensis/Output/pre-selection(force32).csv\");\r\n\t\t\t\t}\r\n\t\t\t\telse if (m_fitType == F_FECUNDITY)\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg += m_fecundity.load(inputFilePath);\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t\t//generate fixed temperature profile\r\n\t\t\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA || m_fitType == F_DEV_TIME_ONLY)\r\n\t\t\t\t{\r\n\t\t\t\t\tm_Tobs.generate(m_devTime);\r\n\t\t\t\t}\r\n\t\t\t\telse if (m_fitType == F_SURVIVAL)\r\n\t\t\t\t{\r\n\t\t\t\t\tm_Tobs.generate(m_survival);\r\n\t\t\t\t}\r\n\t\t\t\telse if (m_fitType == F_FECUNDITY)\r\n\t\t\t\t{\r\n\t\t\t\t\tm_Tobs.generate(m_fecundity);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (!m_TobsFileName.empty())\r\n\t\t\t\t{\r\n\t\t\t\t\tstring TobsFilePath = fileManager.Input().GetFilePath(m_TobsFileName);\r\n\t\t\t\t\tmsg += m_Tobs.load(TobsFilePath);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t//verify that all temperature profile have anought data\r\n\t\t\t\tif (msg)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA || m_fitType == F_DEV_TIME_ONLY)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmsg = m_Tobs.verify(m_devTime);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (m_fitType == F_SURVIVAL)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmsg = m_Tobs.verify(m_survival);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (m_fitType == F_FECUNDITY)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_Tobs.verify(m_fecundity);\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t}\r\n\r\n\r\n\r\n\t\t\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA &&\r\n\t\t\t\t\t!(m_devTime.m_bIndividual || (m_devTime.have_var(I_MEAN_TIME) && m_devTime.have_var(I_TIME_SD) && m_devTime.have_var(I_N))))\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(string(\"Calibration of \") + TYPE_NAME[m_fitType] + \" need individual Time or MeanTime, TimeSD and n\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\t//if (m_fitType == F_DEV_TIME_WTH_SIGMA && !bLogLikelyhoude)\r\n\t\t\t\t//{\r\n\t\t\t\t//\tif (!(m_devTime.m_bIndividual || (m_devTime.have_var(I_MEAN_TIME) && m_devTime.have_var(I_TIME_SD) && m_devTime.have_var(I_N))))\r\n\t\t\t\t//\t{\r\n\t\t\t\t//\t\tmsg.ajoute(string(\"Minimize residual sum of square for \") + TYPE_NAME[m_fitType] + \" need individual Time or MeanTime, TimeSD and n.\");\r\n\t\t\t\t//\t\treturn msg;\r\n\t\t\t\t//\t}\r\n\t\t\t\t//}\r\n\t\t\t\tif (m_fitType == F_DEV_TIME_ONLY && m_devTime.m_bIndividual)//base on mean rate only (no sigma)\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg.ajoute(string(\"Calibration of \\\"\") + TYPE_NAME[m_fitType] + \"\\\" can not be used with individual Time. Use \\\"\" + TYPE_NAME[F_DEV_TIME_WTH_SIGMA] + \"\\\" instead or use MeanTime, TimeSD and n.\");\r\n\t\t\t\t\treturn msg;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (m_fitType == F_DEV_TIME_ONLY && !m_devTime.m_bIndividual)//base on mean rate only (no sigma)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (!m_devTime.have_var(I_MEAN_TIME))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmsg.ajoute(string(\"Calibration of \") + TYPE_NAME[m_fitType] + \" need MeanTime.\");\r\n\t\t\t\t\t\treturn msg;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/*if (!(m_devTime.m_bIndividual || (m_devTime.have_var(I_MEAN_TIME))))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmsg.ajoute(string(\"Calibration of \") + TYPE_NAME[m_fitType] + \" need individual Time or MeanTime.\");\r\n\t\t\t\t\t\treturn msg;\r\n\t\t\t\t\t}*/\r\n\t\t\t\t\t//msg.ajoute(string(\"Maximize log likelihood is not available for \") + TYPE_NAME[m_fitType] + \". Use minize residual sum of square instead.\");\r\n\t\t\t\t\t//return msg;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tstd::map<std::string, std::map<std::string, std::map<std::string, double>>> output_params;\r\n\t\t\t\tif (m_bUseOutputAsInput)\r\n\t\t\t\t{\r\n\t\t\t\t\tstring previousFilePath = fileManager.GetOutputPath() + m_outputAsIntputFileName;\r\n\t\t\t\t\tSetFileExtension(previousFilePath, \".csv\");\r\n\t\t\t\t\tReplaceString(previousFilePath, \"%i\", GetFileTitle(m_inputFileName));\r\n\t\t\t\t\tmsg += ReadParametersFromFile(previousFilePath, output_params);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (!msg)\r\n\t\t\t\t\treturn msg;\r\n\r\n\t\t\t\tif (m_bFixeTb || m_bFixeTo || m_bFixeTm)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t e = 0; e < m_eqDevRate.size() && msg; e++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (m_eqDevRate.test(e))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tTDevRateEquation eq = CDevRateEquation::eq(e);\r\n\t\t\t\t\t\t\tstring e_name = CDevRateEquation::GetEquationName(eq);\r\n\r\n\t\t\t\t\t\t\tCSAParameterVector params = CDevRateEquation::GetParameters(eq);\r\n\r\n\t\t\t\t\t\t\tauto it_Tb = find_if(params.begin(), params.end(), [](const CSAParameter & m) -> bool { return m.m_name == \"Tb\"; });\r\n\t\t\t\t\t\t\tauto it_To = find_if(params.begin(), params.end(), [](const CSAParameter & m) -> bool { return m.m_name == \"To\"; });\r\n\t\t\t\t\t\t\tauto it_Tm = find_if(params.begin(), params.end(), [](const CSAParameter & m) -> bool { return m.m_name == \"Tm\"; });\r\n\t\t\t\t\t\t\tif (m_bFixeTb && it_Tb == params.end() ||\r\n\t\t\t\t\t\t\t\tm_bFixeTo && it_To == params.end() ||\r\n\t\t\t\t\t\t\t\tm_bFixeTm && it_Tm == params.end())\r\n\t\t\t\t\t\t\t\tm_eqDevRate.reset(e);//remove equation without Tb\r\n\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\r\n\t\t\t\tCResult result;\r\n\t\t\t\tCFitOutputVector output;\r\n\t\t\t\tsize_t nb_limits = 1;\r\n\r\n\t\t\t\tset<string> variables;\r\n\r\n\t\t\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA || m_fitType == F_DEV_TIME_ONLY)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t s = 0; s < m_devTime.size(); s++)\r\n\t\t\t\t\t\tvariables.insert(m_devTime[s].m_variable);\r\n\t\t\t\t}\r\n\t\t\t\telse if (m_fitType == F_SURVIVAL)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t s = 0; s < m_survival.size(); s++)\r\n\t\t\t\t\t\tvariables.insert(m_survival[s].m_variable);\r\n\t\t\t\t}\r\n\t\t\t\telse if (m_fitType == F_FECUNDITY)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t s = 0; s < m_fecundity.size(); s++)\r\n\t\t\t\t\t\tvariables.insert(m_fecundity[s].m_variable);\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t\t//for all stage\r\n\t\t\t\tfor (auto v = variables.begin(); v != variables.end() && msg; v++)\r\n\t\t\t\t{\r\n\t\t\t\t\t//for all equation\r\n\t\t\t\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA || m_fitType == F_DEV_TIME_ONLY)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t//m_calibOn = m_fitType == F_DEV_TIME ? CO_TIME : CO_RATE;\r\n\t\t\t\t\t\tfor (size_t e = 0; e < m_eqDevRate.size() && msg; e++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (m_eqDevRate.test(e))\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tTDevRateEquation eq = CDevRateEquation::eq(e);\r\n\t\t\t\t\t\t\t\tstring e_name = CDevRateEquation::GetEquationName(eq);\r\n\r\n\r\n\t\t\t\t\t\t\t\tCSAParameterVector params0 = CDevRateEquation::GetParameters(eq);\r\n\t\t\t\t\t\t\t\tif (m_eq_options.find(e_name) != m_eq_options.end())\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tASSERT(m_eq_options[e_name].size() == CDevRateEquation::GetParameters(eq).size());\r\n\t\t\t\t\t\t\t\t\tparams0 = m_eq_options[e_name];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA)// add relative development rate variance\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tdouble sigma = m_devTime.GetDefaultSigma(*v);\r\n\t\t\t\t\t\t\t\t\tif (m_devTime.m_bIndividual)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tparams0.push_back(CSAParameter(\"sigma\", sigma, sigma / SIGMA_FACTOR, sigma*SIGMA_FACTOR));\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t//fixe sigma here\r\n\t\t\t\t\t\t\t\t\t\tparams0.push_back(CSAParameter(\"sigma\", sigma, sigma, sigma));\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\tif (m_bUseOutputAsInput && !output_params.empty())\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tif (output_params.find(*v) != output_params.end() &&\r\n\t\t\t\t\t\t\t\t\t\toutput_params[*v].find(e_name) != output_params[*v].end())\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tASSERT(output_params[*v][e_name].size() >= CDevRateEquation::GetParameters(eq).size());\r\n\t\t\t\t\t\t\t\t\t\tfor (auto it = output_params[*v][e_name].begin(); it != output_params[*v][e_name].end(); it++)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tauto iit = find_if(params0.begin(), params0.end(), [&](CSAParameter &p) {return boost::iequals(p.m_name, it->first); });\r\n\t\t\t\t\t\t\t\t\t\t\tif (iit != params0.end())\r\n\t\t\t\t\t\t\t\t\t\t\t\tiit->m_initialValue = it->second;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\tdouble Tk = (eq == CDevRateEquation::Schoolfield_1981 || eq == CDevRateEquation::Wagner_1988) ? 273.16 : 0;\r\n\r\n\r\n\t\t\t\t\t\t\t\t//if there is global lower/upper limit, set it\r\n\t\t\t\t\t\t\t\tsize_t nb_Tb = m_bFixeTb ? ceil((m_Tb[1] - m_Tb[0]) / m_Tb[2]) + 1 : 1;\r\n\t\t\t\t\t\t\t\tsize_t nb_To = m_bFixeTo ? ceil((m_To[1] - m_To[0]) / m_To[2]) + 1 : 1;\r\n\t\t\t\t\t\t\t\tsize_t nb_Tm = m_bFixeTm ? ceil((m_Tm[1] - m_Tm[0]) / m_Tm[2]) + 1 : 1;\r\n\t\t\t\t\t\t\t\tnb_limits = nb_Tb * nb_To*nb_Tm;\r\n\r\n\r\n\t\t\t\t\t\t\t\tfor (size_t Tbi = 0; Tbi < nb_Tb; Tbi++)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tCSAParameterVector params = params0;\r\n\r\n\r\n\t\t\t\t\t\t\t\t\tif (m_bFixeTb)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tauto it = find_if(params.begin(), params.end(), [](const CSAParameter & m) -> bool { return m.m_name == \"Tb\"; });\r\n\t\t\t\t\t\t\t\t\t\tif (it != params.end())\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tit->m_initialValue = m_Tb[0] + Tbi * m_Tb[2] + Tk;\r\n\t\t\t\t\t\t\t\t\t\t\tit->m_bounds = CVariableBound(it->m_initialValue, it->m_initialValue);\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\t\t\t\tfor (size_t Toi = 0; Toi < nb_To; Toi++)\r\n\t\t\t\t\t\t\t\t\t{\r\n\r\n\t\t\t\t\t\t\t\t\t\tif (m_bFixeTo)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tauto it = find_if(params.begin(), params.end(), [](const CSAParameter & m) -> bool { return m.m_name == \"To\"; });\r\n\t\t\t\t\t\t\t\t\t\t\tif (it != params.end())\r\n\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\tit->m_initialValue = m_To[0] + Toi * m_To[2] + Tk;\r\n\t\t\t\t\t\t\t\t\t\t\t\tit->m_bounds = CVariableBound(it->m_initialValue, it->m_initialValue);\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\tfor (size_t Tmi = 0; Tmi < nb_Tm; Tmi++)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tif (m_bFixeTm)\r\n\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\tauto it = find_if(params.begin(), params.end(), [](const CSAParameter & m) -> bool { return m.m_name == \"Tm\"; });\r\n\t\t\t\t\t\t\t\t\t\t\t\tif (it != params.end())\r\n\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\tit->m_initialValue = m_Tm[0] + Tmi * m_Tm[2] + Tk;\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tit->m_bounds = CVariableBound(it->m_initialValue, it->m_initialValue);\r\n\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}\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tCFitOutput out(*v, eq, params);\r\n\t\t\t\t\t\t\t\t\t\t\tmsg += InitialiseComputationVariable(out.m_variable, out.m_equation, out.m_parameters, out.m_computation, callback);\r\n\t\t\t\t\t\t\t\t\t\t\toutput.push_back(out);\r\n\t\t\t\t\t\t\t\t\t\t}//for all Tm\r\n\t\t\t\t\t\t\t\t\t}//for all To\r\n\t\t\t\t\t\t\t\t}//for all Tb\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (m_fitType == F_SURVIVAL)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (size_t e = 0; e < m_eqSurvival.size() && msg; e++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (m_eqSurvival.test(e))\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tTSurvivalEquation eq = CSurvivalEquation::eq(e);\r\n\t\t\t\t\t\t\t\tstring e_name = CSurvivalEquation::GetEquationName(eq);\r\n\r\n\t\t\t\t\t\t\t\tCSAParameterVector params = CSurvivalEquation::GetParameters(eq);\r\n\t\t\t\t\t\t\t\tif (m_eq_options.find(e_name) != m_eq_options.end())\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tASSERT(m_eq_options[e_name].size() == CSurvivalEquation::GetParameters(eq).size());\r\n\t\t\t\t\t\t\t\t\tparams = m_eq_options[e_name];\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\tif (m_bUseOutputAsInput && !output_params.empty())\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tif (output_params.find(*v) != output_params.end() &&\r\n\t\t\t\t\t\t\t\t\t\toutput_params[*v].find(e_name) != output_params[*v].end())\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tASSERT(output_params[*v][e_name].size() == CSurvivalEquation::GetParameters(eq).size());\r\n\t\t\t\t\t\t\t\t\t\tfor (auto it = output_params[*v][e_name].begin(); it != output_params[*v][e_name].end(); it++)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tauto iit = find_if(params.begin(), params.end(), [&](CSAParameter &p) {return boost::iequals(p.m_name, it->first); });\r\n\t\t\t\t\t\t\t\t\t\t\tif (iit != params.end())\r\n\t\t\t\t\t\t\t\t\t\t\t\tiit->m_initialValue = it->second;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\tCFitOutput out(*v, eq, params);\r\n\t\t\t\t\t\t\t\tmsg += InitialiseComputationVariable(out.m_variable, out.m_equation, out.m_parameters, out.m_computation, callback);\r\n\t\t\t\t\t\t\t\toutput.push_back(out);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (m_fitType == F_FECUNDITY)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (size_t e = 0; e < m_eqFecundity.size() && msg; e++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (m_eqFecundity.test(e))\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tTDevRateEquation eq = CDevRateEquation::eq(e);\r\n\t\t\t\t\t\t\t\tstring e_name = CDevRateEquation::GetEquationName(eq);\r\n\r\n\r\n\t\t\t\t\t\t\t\tCSAParameterVector params = CDevRateEquation::GetParameters(eq);\r\n\t\t\t\t\t\t\t\tif (m_eq_options.find(e_name) != m_eq_options.end())\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tASSERT(m_eq_options[e_name].size() == CDevRateEquation::GetParameters(eq).size());\r\n\t\t\t\t\t\t\t\t\tparams = m_eq_options[e_name];\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\tif (m_bUseOutputAsInput && !output_params.empty())\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tif (output_params.find(*v) != output_params.end() &&\r\n\t\t\t\t\t\t\t\t\t\toutput_params[*v].find(e_name) != output_params[*v].end())\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tASSERT(output_params[*v][e_name].size() >= CDevRateEquation::GetParameters(eq).size());\r\n\t\t\t\t\t\t\t\t\t\tfor (auto it = output_params[*v][e_name].begin(); it != output_params[*v][e_name].end(); it++)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tauto iit = find_if(params.begin(), params.end(), [&](CSAParameter &p) {return boost::iequals(p.m_name, it->first); });\r\n\t\t\t\t\t\t\t\t\t\t\tif (iit != params.end())\r\n\t\t\t\t\t\t\t\t\t\t\t\tiit->m_initialValue = it->second;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t//CSAParameter pto(\"to\", 0, 0, 0);//fixe to at 0\r\n\r\n\t\t\t\t\t\t\t\tCSAParameter pFo(\"Fo\", 100, 1, 1000);\r\n\t\t\t\t\t\t\t\tif (m_bFixeF0)\r\n\t\t\t\t\t\t\t\t\tpFo = CSAParameter(\"Fo\", m_F0[0], m_F0[0], m_F0[0]);\r\n\r\n\r\n\t\t\t\t\t\t\t\tif (m_fecundity.m_bIndividual || m_fecundity.m_bIndividualSeries)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t//params.push_back(pto);\r\n\t\t\t\t\t\t\t\t\tparams.push_back(pFo);\r\n\t\t\t\t\t\t\t\t\tparams.push_back(CSAParameter(\"sigma\", 0.2, 0.01, 0.9));\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t//fixe sigma here\r\n\t\t\t\t\t\t\t\t\t//params.push_back(pto);\r\n\t\t\t\t\t\t\t\t\tparams.push_back(pFo);\r\n\t\t\t\t\t\t\t\t\tdouble sigma = m_fecundity.GetDefaultSigma();\r\n\t\t\t\t\t\t\t\t\tparams.push_back(CSAParameter(\"sigma\", sigma, sigma, sigma));\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\tauto it = find_if(params.begin(), params.end(), [](const CSAParameter & m) -> bool { return m.m_name == \"psi\"; });\r\n\t\t\t\t\t\t\t\tif (it != params.end())\r\n\t\t\t\t\t\t\t\t\tit->m_bounds.m_upperBound = 10;\r\n\r\n\r\n\t\t\t\t\t\t\t\tCFitOutput out(*v, eq, params);\r\n\t\t\t\t\t\t\t\tmsg += InitialiseComputationVariable(out.m_variable, out.m_equation, out.m_parameters, out.m_computation, callback);\r\n\t\t\t\t\t\t\t\toutput.push_back(out);\r\n\t\t\t\t\t\t\t}\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\tsize_t nb_e = 0;\r\n\t\t\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA || m_fitType == F_DEV_TIME_ONLY)\r\n\t\t\t\t\tnb_e = m_eqDevRate.count();\r\n\t\t\t\telse if (m_fitType == F_SURVIVAL)\r\n\t\t\t\t\tnb_e = m_eqSurvival.count();\r\n\t\t\t\telse if (m_fitType == F_FECUNDITY)\r\n\t\t\t\t\tnb_e = m_eqFecundity.count();\r\n\r\n\r\n\t\t\t\tif (!msg)\r\n\t\t\t\t\treturn msg;\r\n\r\n\r\n\r\n\t\t\t\tcallback.PushTask(\"Search optimum for \" + to_string(TYPE_NAME[m_fitType]) + \": \" + to_string(variables.size()) + \" variables x \" + to_string(nb_e) + \" equations x \" + to_string(nb_limits) + \" fixed limits = \" + to_string(output.size()) + \" curve to fits\", output.size());\r\n\r\n\r\n\r\n#pragma omp parallel for num_threads(CTRL.m_nbMaxThreads) \r\n\t\t\t\tfor (__int64 i = 0; i < (__int64)output.size(); i++)\r\n\t\t\t\t{\r\n#pragma omp flush(msg)\r\n\t\t\t\t\tif (msg)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmsg += Optimize(output[i].m_variable, output[i].m_equation, output[i].m_parameters, output[i].m_computation, callback);\r\n\r\n#pragma omp critical(WRITE_INFO)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA || m_fitType == F_DEV_TIME_ONLY)\r\n\t\t\t\t\t\t\t\tcallback.AddMessage(output[i].m_variable + \": \" + CDevRateEquation::GetEquationName(CDevRateEquation::eq(output[i].m_equation)));\r\n\t\t\t\t\t\t\telse if (m_fitType == F_SURVIVAL)\r\n\t\t\t\t\t\t\t\tcallback.AddMessage(output[i].m_variable + \": \" + CSurvivalEquation::GetEquationName(CSurvivalEquation::eq(output[i].m_equation)));\r\n\t\t\t\t\t\t\telse if (m_fitType == F_FECUNDITY)\r\n\t\t\t\t\t\t\t\tcallback.AddMessage(output[i].m_variable + \": \" + CDevRateEquation::GetEquationName(CDevRateEquation::eq(output[i].m_equation)));\r\n\r\n\r\n\t\t\t\t\t\t\tWriteInfo(output[i].m_parameters, output[i].m_computation, callback);\r\n\t\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\t//fileManager, result, callback\r\n\t\t\t\t\t\tmsg += callback.StepIt();\r\n#pragma omp flush(msg)\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcallback.PopTask();\r\n\r\n\r\n\r\n\t\t\t\tcallback.AddMessage(GetCurrentTimeString());\r\n\t\t\t\tstd::string logText = GetOutputString(msg, callback, true);\r\n\r\n\t\t\t\tstd::string filePath = GetLogFilePath(GetPath(fileManager));\r\n\t\t\t\tmsg += WriteOutputMessage(filePath, logText);\r\n\r\n\t\t\t\tif (true)\r\n\t\t\t\t{\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t//begin to read\r\n\t\t\t\t\tofStream file;\r\n\r\n\r\n\t\t\t\t\tERMsg msg_file = file.open(outputFilePath);\r\n\t\t\t\t\tif (msg_file)//save result event if user cancel or error\r\n\t\t\t\t\t{\r\n\r\n\t\t\t\t\t\tsort(output.begin(), output.end(), [](const CFitOutput& a, const CFitOutput& b) {return a.m_computation.m_Fopt > b.m_computation.m_Fopt; });\r\n\t\t\t\t\t\tif (bLogLikelyhoude)\r\n\t\t\t\t\t\t\tfile << \"Variable,EqName,P,Eq,Math,AICc,maxLL\" << endl;\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\tfile << \"Variable,EqName,P,Eq,Math,R2\" << endl;\r\n\r\n\t\t\t\t\t\tfor (auto v = variables.begin(); v != variables.end(); v++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tfor (size_t i = 0; i < output.size(); i++)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tif (output[i].m_variable == *v)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tstring name;\r\n\t\t\t\t\t\t\t\t\tstring R_eq;\r\n\t\t\t\t\t\t\t\t\tstring R_math;\r\n\t\t\t\t\t\t\t\t\tstring P;\r\n\t\t\t\t\t\t\t\t\tconst vector<double>& Xopt = output[i].m_computation.m_Xopt;\r\n\r\n\r\n\t\t\t\t\t\t\t\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA || m_fitType == F_DEV_TIME_ONLY)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tTDevRateEquation eq = CDevRateEquation::eq(output[i].m_equation);\r\n\t\t\t\t\t\t\t\t\t\tname = CDevRateEquation::GetEquationName(eq);\r\n\t\t\t\t\t\t\t\t\t\tR_eq = CDevRateEquation::GetEquationR(eq);\r\n\t\t\t\t\t\t\t\t\t\tR_math = CDevRateEquation::GetMathPlot(eq);\r\n\t\t\t\t\t\t\t\t\t\tP = to_string(CDevRateEquation::GetParameters(eq, Xopt));\r\n\r\n\t\t\t\t\t\t\t\t\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tP += \" sigma=\" + to_string(Xopt.back());\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\telse if (m_fitType == F_SURVIVAL)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tTSurvivalEquation eq = CSurvivalEquation::eq(output[i].m_equation);\r\n\t\t\t\t\t\t\t\t\t\tname = CSurvivalEquation::GetEquationName(eq);\r\n\t\t\t\t\t\t\t\t\t\tR_eq = CSurvivalEquation::GetEquationR(eq);\r\n\t\t\t\t\t\t\t\t\t\tR_math = CSurvivalEquation::GetMathPlot(eq);\r\n\t\t\t\t\t\t\t\t\t\tP = to_string(CSurvivalEquation::GetParameters(eq, Xopt));\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\telse if (m_fitType == F_FECUNDITY)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tTDevRateEquation eq = CDevRateEquation::eq(output[i].m_equation);\r\n\t\t\t\t\t\t\t\t\t\tname = CDevRateEquation::GetEquationName(eq);\r\n\t\t\t\t\t\t\t\t\t\tR_eq = CDevRateEquation::GetEquationR(eq);\r\n\t\t\t\t\t\t\t\t\t\tR_math = CDevRateEquation::GetMathPlot(eq);\r\n\t\t\t\t\t\t\t\t\t\tP = to_string(CDevRateEquation::GetParameters(eq, Xopt));\r\n\r\n\t\t\t\t\t\t\t\t\t\t//P += \" to=\" + to_string(Xopt[Xopt.size() - 3]);\r\n\t\t\t\t\t\t\t\t\t\tP += \" Fo=\" + to_string(Xopt[Xopt.size() - 2]);\r\n\t\t\t\t\t\t\t\t\t\tP += \" sigma=\" + to_string(Xopt[Xopt.size() - 1]);\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\t\t\t\tfile << output[i].m_variable << \",\" << name << \",\" << P << \",\\\"\" << R_eq << \"\\\",\\\"\" << R_math << \"\\\",\";\r\n\r\n\t\t\t\t\t\t\t\t\tif (bLogLikelyhoude)\r\n\t\t\t\t\t\t\t\t\t\tfile << output[i].m_computation.m_AICCopt << \",\" << output[i].m_computation.m_MLLopt;\r\n\t\t\t\t\t\t\t\t\telse if (output[i].m_computation.m_Fopt != m_ctrl.GetVMiss())\r\n\t\t\t\t\t\t\t\t\t\tfile << output[i].m_computation.m_Sopt[STAT_R\u00b2];\r\n\t\t\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t\t\tfile << \"0,0,0,0\";\r\n\r\n\t\t\t\t\t\t\t\t\tfile << endl;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tfile.close();\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tmsg += msg_file;\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t}\r\n\r\n\t\t\tresultDB.Close();\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\r\n\r\n\t//Initialize input parameter\r\n\t//user can override theses methods\r\n\tERMsg CInsectParameterization::InitialiseComputationVariable(std::string s, size_t e, const CSAParameterVector& parameters, CComputationVariable& computation, CCallback& callback)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\tcomputation.m_bounds.resize(parameters.size());\r\n\t\tcomputation.m_C.resize(parameters.size());\r\n\t\tcomputation.m_X.resize(parameters.size());\r\n\t\tcomputation.m_XP.resize(parameters.size());\r\n\t\tcomputation.m_XPstat.resize(parameters.size());\r\n\t\tcomputation.m_VM.resize(parameters.size());\r\n\t\tcomputation.m_VMstat.resize(parameters.size());\r\n\r\n\r\n\t\tfor (size_t i = 0; i < parameters.size(); i++)\r\n\t\t{\r\n\t\t\tcomputation.m_bounds[i] = parameters[i].m_bounds;\r\n\t\t\tcomputation.m_XP[i] = parameters[i].m_initialValue;\r\n\t\t\tcomputation.m_C[i] = 2;\r\n\t\t\tcomputation.m_VM[i] = computation.m_bounds[i].GetExtent();\r\n\t\t\tASSERT(!computation.m_bounds[i].IsOutOfBound(computation.m_XP[i]));\r\n\t\t\t//If the initial value is out of bounds, notify the user and return\r\n\t\t\t//to the calling routine.\r\n\t\t\tif (computation.m_bounds[i].IsOutOfBound(computation.m_XP[i]))\r\n\t\t\t{\r\n\t\t\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA || m_fitType == F_DEV_TIME_ONLY)\r\n\t\t\t\t\tmsg.ajoute(s + \": \" + CDevRateEquation::GetEquationName(CDevRateEquation::eq(e)));\r\n\t\t\t\telse if (m_fitType == F_SURVIVAL)\r\n\t\t\t\t\tmsg.ajoute(s + \": \" + CSurvivalEquation::GetEquationName(CSurvivalEquation::eq(e)));\r\n\t\t\t\telse if (m_fitType == F_FECUNDITY)\r\n\t\t\t\t\tmsg.ajoute(s + \": \" + CDevRateEquation::GetEquationName(CDevRateEquation::eq(e)));\r\n\r\n\r\n\t\t\t\tmsg.ajoute(\"The starting value (\" + ToString(computation.m_XP[i]) + \") is not inside the bounds [\" + ToString(computation.m_bounds[i].GetLowerBound()) + \",\" + ToString(computation.m_bounds[i].GetUpperBound()) + \"].\");\r\n\t\t\t\treturn msg;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tcomputation.Initialize(m_ctrl.T(), m_ctrl.NEPS(), m_ctrl.GetVMiss());\r\n\r\n\t\t//  Evaluate the function with input X and return value as F.\r\n\t\tGetFValue(s, e, computation);\r\n\r\n\t\tcomputation.m_NFCNEV++;\r\n\r\n\t\tcomputation.m_X = computation.m_XP;\r\n\t\tcomputation.m_Xopt = computation.m_XP;\r\n\r\n\t\tif (computation.m_FP != m_ctrl.GetVMiss())\r\n\t\t{\r\n\t\t\tcomputation.m_S = computation.m_SP;\r\n\t\t\tcomputation.m_F = computation.m_FP;\r\n\t\t\tcomputation.m_AICC = computation.m_AICCP;\r\n\t\t\tcomputation.m_MLL = computation.m_MLLP;\r\n\r\n\t\t\tcomputation.m_Sopt = computation.m_SP;\r\n\t\t\tcomputation.m_Fopt = computation.m_FP;\r\n\t\t\tcomputation.m_AICCopt = computation.m_AICCP;\r\n\t\t\tcomputation.m_MLLopt = computation.m_MLLP;\r\n\r\n\t\t\tcomputation.m_FSTAR[0] = computation.m_FP;\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\r\n\tdouble CInsectParameterization::Exprep(const double& RDUM)\r\n\t{\r\n\t\t//  This function replaces exp to avoid under- and overflows and is\r\n\t\t//  designed for IBM 370 type machines. It may be necessary to modify\r\n\t\t//  it for other machines. Note that the maximum and minimum values of\r\n\t\t//  EXPREP are such that they has no effect on the algorithm.\r\n\r\n\t\tdouble EXPREP = 0;\r\n\r\n\t\tif (RDUM > 174.)\r\n\t\t{\r\n\t\t\tEXPREP = 3.69E+75;\r\n\t\t}\r\n\t\telse if (RDUM < -180.)\r\n\t\t{\r\n\t\t\tEXPREP = 0.0;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tEXPREP = exp(RDUM);\r\n\t\t}\r\n\r\n\t\treturn EXPREP;\r\n\t}\r\n\r\n\r\n\r\n\tvoid CInsectParameterization::WriteInfo(const CSAParameterVector& parameters, const CComputationVariable& computation, CCallback& callback)\r\n\t{\r\n\t\tstring line;\r\n\r\n\t\tdouble F = m_ctrl.Max() ? computation.m_Fopt : -computation.m_Fopt;\r\n\t\tbool bLogLikelyhoude = m_ctrl.m_statisticType == LIKELIHOOD;\r\n\r\n\t\tCStatistic stat;\r\n\t\tfor (size_t i = 0, j = 0; i < computation.m_Xstat.size(); i++)\r\n\t\t\tstat += 100.0*computation.m_Xstat[j][RANGE] / computation.m_Xstat[j][MEAN];\r\n\r\n\t\tif (bLogLikelyhoude)\r\n\t\t\tline = FormatA(\"N=%10d\\tT=%12.8f\\tF=%8.5lf\\tP=%8.5lf\\nAICc=%8.5lf\\tmaxLL=%8.5lf\", computation.m_NFCNEV, computation.m_T, F, stat[HIGHEST], computation.m_AICCopt, computation.m_MLLopt);\r\n\t\telse if (computation.m_Sopt[NB_VALUE] > 0)\r\n\t\t\tline = FormatA(\"N=%10d\\tT=%12.8f\\tF=%8.5lf\\tP=%8.5lf\\nNbVal=%6.0lf\\tBias=%8.5lf\\tMAE=%8.5lf\\tRMSE=%8.5lf\\tCD=%8.5lf\\tR\u00b2=%8.5lf\", computation.m_NFCNEV, computation.m_T, F, stat[HIGHEST], computation.m_Sopt[NB_VALUE], computation.m_Sopt[BIAS], computation.m_Sopt[MAE], computation.m_Sopt[RMSE], computation.m_Sopt[COEF_D], computation.m_Sopt[STAT_R\u00b2]);\r\n\t\telse\r\n\t\t\tline = \"No optimum find yet...\";\r\n\r\n\r\n\r\n\t\tcallback.AddMessage(line);\r\n\r\n\r\n\t\tline.clear();\r\n\t\tif (computation.m_Xopt.size() == parameters.size())\r\n\t\t{\r\n\r\n\t\t\tbool bShowRange = !computation.m_XPstat.empty() && computation.m_XPstat[0][NB_VALUE] > 0;\r\n\t\t\tfor (size_t j = 0; j < parameters.size(); j++)\r\n\t\t\t{\r\n\t\t\t\tstring name = parameters[j].m_name; Trim(name);\r\n\t\t\t\tstring tmp;\r\n\r\n\t\t\t\tif (bShowRange)\r\n\t\t\t\t{\r\n\t\t\t\t\ttmp = FormatA(\"% -20.20s\\t=%10.5lf {%10.5lf,%10.5lf}\\tVM={%10.5lf,%10.5lf}\\n\", name.c_str(), computation.m_Xopt[j], computation.m_XPstat[j][LOWEST], computation.m_XPstat[j][HIGHEST], computation.m_VMstat[j][LOWEST], computation.m_VMstat[j][HIGHEST]);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\ttmp = FormatA(\"%s = %5.3lg  \", name.c_str(), computation.m_Xopt[j]);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tline += tmp;\r\n\t\t\t}\r\n\r\n\t\t\tcallback.AddMessage(line);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid CInsectParameterization::WriteInfoEx(const CSAParameterVector& parameters, const CComputationVariable& computation, CCallback& callback)\r\n\t{\r\n\t\tstring line;\r\n\t\tdouble F = m_ctrl.Max() ? computation.m_Fopt : -computation.m_Fopt;\r\n\t\tbool bLogLikelyhoude = m_ctrl.m_statisticType == LIKELIHOOD;\r\n\r\n\t\tCStatistic stat;\r\n\t\tfor (size_t i = 0, j = 0; i < computation.m_XPstat.size(); i++)\r\n\t\t\tstat += 100.0*computation.m_XPstat[j][RANGE] / computation.m_XPstat[j][MEAN];\r\n\r\n\t\tif (bLogLikelyhoude)\r\n\t\t\tline = FormatA(\"N=%10d\\tT=%12.8f\\tF=%8.5lf\\tP=%8.5lf\\nAICc=%8.5lf\\tmaxLL=%8.5lf\", computation.m_NFCNEV, computation.m_T, F, stat[HIGHEST], computation.m_AICCopt, computation.m_MLLopt);\r\n\t\telse if (computation.m_Sopt[NB_VALUE] > 0)\r\n\t\t\tline = FormatA(\"N=%10d\\tT=%12.8f\\tF=%8.5lf\\tP=%8.5lf\\nNbVal=%6.0lf\\tBias=%8.5lf\\tMAE=%8.5lf\\tRMSE=%8.5lf\\tCD=%8.5lf\\tR\u00b2=%8.5lf\", computation.m_NFCNEV, computation.m_T, F, stat[HIGHEST], computation.m_Sopt[NB_VALUE], computation.m_Sopt[BIAS], computation.m_Sopt[MAE], computation.m_Sopt[RMSE], computation.m_Sopt[COEF_D], computation.m_Sopt[STAT_R\u00b2]);\r\n\t\telse\r\n\t\t\tline = \"No optimum find yet...\";\r\n\r\n\r\n\r\n\t\tcallback.AddMessage(line);\r\n\r\n\r\n\t\tline.clear();\r\n\t\tbool bShowRange = !computation.m_XPstat.empty() && computation.m_XPstat[0][NB_VALUE] > 0;\r\n\t\tfor (size_t i = 0, j = 0; i < parameters.size(); i++)\r\n\t\t{\r\n\t\t\tstring name = parameters[i].m_name; Trim(name);\r\n\t\t\tstring tmp;\r\n\r\n\t\t\tif (bShowRange)\r\n\t\t\t{\r\n\t\t\t\ttmp = FormatA(\"% -20.20s\\t=%10.5lf {%10.5lf,%10.5lf}\\tVM={%10.5lf,%10.5lf}\\n\", name.c_str(), computation.m_Xopt[j], computation.m_XPstat[j][LOWEST], computation.m_XPstat[j][HIGHEST], computation.m_VMstat[j][LOWEST], computation.m_VMstat[j][HIGHEST]);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttmp = FormatA(\"% -20.20s\\t=%10.5lf  \", name.c_str(), computation.m_Xopt[j]);\r\n\t\t\t}\r\n\r\n\t\t\tline += tmp;\r\n\t\t\tj++;\r\n\t\t}\r\n\r\n\t\tcallback.AddMessage(line);\r\n\t\tline.clear();\r\n\r\n\r\n\t\t/*double eps = fabs(computation.m_Fopt - computation.m_F);\r\n\t\tline = \"Eps = [\" + ToString(eps, -1) + \"]{\";\r\n\r\n\t\tfor (int i = 0; i < computation.m_FSTAR.size(); i++)\r\n\t\t{\r\n\r\n\t\t\tstring tmp;\r\n\t\t\tdouble eps = fabs(computation.m_F - computation.m_FSTAR[i]);\r\n\r\n\t\t\tif (eps < 10e6)\r\n\t\t\t\ttmp = FormatA(\"%8.5lf\", eps);\r\n\t\t\telse tmp = \"-----\";\r\n\r\n\r\n\t\t\tif (i > 0)\r\n\t\t\t\tline += \", \";\r\n\r\n\t\t\tline += tmp;\r\n\t\t}\r\n\r\n\t\tline += \"}\";\r\n*/\r\n//callback.AddMessage(line);\r\n\r\n//callback.AddMessage(\"***********************************\");\r\n//callback.StepIt(0);\r\n\r\n\r\n//clean X stats\r\n//for (size_t i = 0; i < computation.m_XPstat.size(); i++)\r\n\t//computation.m_XPstat[i].Reset();\r\n\t}\r\n\r\n\r\n\tstd::string CInsectParameterization::GetPath(const CFileManager& fileManager)const\r\n\t{\r\n\t\tif (m_pParent == NULL)\r\n\t\t\treturn fileManager.GetTmpPath() + m_internalName + \"\\\\\";\r\n\r\n\t\treturn m_pParent->GetPath(fileManager) + m_internalName + \"\\\\\";\r\n\t}\r\n\r\n\r\n\t//**********************************************************************\r\n\t//CRandomizeNumber\r\n\r\n\t//  Version: 3.2\r\n\t//  Date: 1/22/94.\r\n\t//  Differences compared to Version 2.0:\r\n\t//     1. If a trial is out of bounds, a point is randomly selected\r\n\t//        from LB(i) to UB(i). Unlike in version 2.0, this trial is\r\n\t//        evaluated and is counted in acceptances and rejections.\r\n\t//        All corresponding documentation was changed as well.\r\n\t//  Differences compared to Version 3.0:\r\n\t//     1. If VM(i) > (UB(i) - LB(i)), VM is set to UB(i) - LB(i).\r\n\t//        The idea is that if T is high relative to LB & UB, most\r\n\t//        points will be accepted, causing VM to rise. But, in this\r\n\t//        situation, VM has little meaning; particularly if VM is\r\n\t//        larger than the acceptable region. Setting VM to this size\r\n\t//        still allows all parts of the allowable region to be selected.\r\n\t//  Differences compared to Version 3.1:\r\n\t//     1. Test made to see if the initial temperature is positive.\r\n\t//     2. WRITE statements prettied up.\r\n\t//     3. References to paper updated.\r\n\t//\r\n\t//  Synopsis:\r\n\t//  This routine implements the continuous simulated annealing global\r\n\t//  optimization algorithm described in Corana et al.'s article\r\n\t//  \"Minimizing Multimodal Functions of Continuous Variables with the\r\n\t//  \"Simulated Annealing\" Algorithm\" in the September 1987 (vol. 13,\r\n\t//  no. 3, pp. 262-280) issue of the ACM Transactions on Mathematical\r\n\t//  Software.\r\n\t//\r\n\t//  A very quick (perhaps too quick) overview of SA:\r\n\t//     SA tries to find the global optimum of an N dimensional function.\r\n\t//  It moves both up and downhill and as the optimization process\r\n\t//  proceeds, it focuses on the most promising area.\r\n\t//     To start, it randomly chooses a trial point within the step length\r\n\t//  VM (a vector of length N) of the user selected starting point. The\r\n\t//  function is evaluated at this trial point and its value is compared\r\n\t//  to its value at the initial point.\r\n\t//     In a maximization problem, all uphill moves are accepted and the\r\n\t//  algorithm continues from that trial point. Downhill moves may be\r\n\t//  accepted; the decision is made by the Metropolis criteria. It uses T\r\n\t//  (temperature) and the size of the downhill move in a probabilistic\r\n\t//  manner. The smaller T and the size of the downhill move are, the more\r\n\t//  likely that move will be accepted. If the trial is accepted, the\r\n\t//  algorithm moves on from that point. If it is rejected, another point\r\n\t//  is chosen instead for a trial evaluation.\r\n\t//     Each element of VM periodically adjusted so that half of all\r\n\t//  function evaluations in that direction are accepted.\r\n\t//     A fall in T is imposed upon the system with the RT variable by\r\n\t//  T(i+1) = RT*T(i) where i is the ith iteration. Thus, as T declines,\r\n\t//  downhill moves are less likely to be accepted and the percentage of\r\n\t//  rejections rise. Given the scheme for the selection for VM, VM falls.\r\n\t//  Thus, as T declines, VM falls and SA focuses upon the most promising\r\n\t//  area for optimization.\r\n\t//\r\n\t//  The importance of the parameter T:\r\n\t//     The parameter T is crucial in using SA successfully. It influences\r\n\t//  VM, the step length over which the algorithm searches for optima. For\r\n\t//  a small intial T, the step length may be too small; thus not enough\r\n\t//  of the function might be evaluated to find the global optima. The user\r\n\t//  should carefully examine VM in the intermediate output (set IPRINT =\r\n\t//  1) to make sure that VM is appropriate. The relationship between the\r\n\t//  initial temperature and the resulting step length is function\r\n\t//  dependent.\r\n\t//     To determine the starting temperature that is consistent with\r\n\t//  optimizing a function, it is worthwhile to run a trial run first. Set\r\n\t//  RT = 1.5 and T = 1.0. With RT > 1.0, the temperature increases and VM\r\n\t//  rises as well. Then select the T that produces a large enough VM.\r\n\t//\r\n\t//  For modifications to the algorithm and many details on its use,\r\n\t//  (particularly for econometric applications) see Goffe, Ferrier\r\n\t//  and Rogers, \"Global Optimization of Statistical Functions with\r\n\t//  Simulated Annealing,\" Journal of Econometrics, vol. 60, no. 1/2, \r\n\t//  Jan./Feb. 1994, pp. 65-100.\r\n\t//  For more information, contact \r\n\t//              Bill Goffe\r\n\t//              Department of Economics and International Business\r\n\t//              University of Southern Mississippi \r\n\t//              Hattiesburg, MS  39506-5072 \r\n\t//              (601) 266-4484 (office)\r\n\t//              (601) 266-4920 (fax)\r\n\t//              bgoffe@whale.st.usm.edu (Internet)\r\n\t//\r\n\t//  As far as possible, the parameters here have the same name as in\r\n\t//  the description of the algorithm on pp. 266-8 of Corana et al.\r\n\t//\r\n\t//  In this description, SP is single precision, DP is double precision,\r\n\t//  INT is integer, L is logical and (N) denotes an array of length n.\r\n\t//  Thus, DP(N) denotes a double precision array of length n.\r\n\t//\r\n\t//  Input Parameters:\r\n\t//    Note: The suggested values generally come from Corana et al. To\r\n\t//          drastically reduce runtime, see Goffe et al., pp. 90-1 for\r\n\t//          suggestions on choosing the appropriate RT and NT.\r\n\t//    N - Number of variables in the function to be optimized. (INT)\r\n\t//    X - The starting values for the variables of the function to be\r\n\t//        optimized. (DP(N))\r\n\t//    MAX - Denotes whether the function should be maximized or\r\n\t//          minimized. A true value denotes maximization while a false\r\n\t//          value denotes minimization. Intermediate output (see IPRINT)\r\n\t//          takes this into account. (L)\r\n\t//    RT - The temperature reduction factor. The value suggested by\r\n\t//         Corana et al. is .85. See Goffe et al. for more advice. (DP)\r\n\t//    EPS - Error tolerance for termination. If the final function\r\n\t//          values from the last neps temperatures differ from the\r\n\t//          corresponding value at the current temperature by less than\r\n\t//          EPS and the final function value at the current temperature\r\n\t//          differs from the current optimal function value by less than\r\n\t//          EPS, execution terminates and IER = 0 is returned. (EP)\r\n\t//    NS - Number of cycles. After NS*N function evaluations, each\r\n\t//         element of VM is adjusted so that approximately half of\r\n\t//         all function evaluations are accepted. The suggested value\r\n\t//         is 20. (INT)\r\n\t//    NT - Number of iterations before temperature reduction. After\r\n\t//         NT*NS*N function evaluations, temperature (T) is changed\r\n\t//         by the factor RT. Value suggested by Corana et al. is\r\n\t//         MAX(100, 5*N). See Goffe et al. for further advice. (INT)\r\n\t//    NEPS - Number of final function values used to decide upon termi-\r\n\t//           nation. See EPS. Suggested value is 4. (INT)\r\n\t//    MAXEVL - The maximum number of function evaluations. If it is\r\n\t//             exceeded, IER = 1. (INT)\r\n\t//    LB - The lower bound for the allowable solution variables. (DP(N))\r\n\t//    UB - The upper bound for the allowable solution variables. (DP(N))\r\n\t//         If the algorithm chooses X(I) .LT. LB(I) or X(I) .GT. UB(I),\r\n\t//         I = 1, N, a point is from inside is randomly selected. This\r\n\t//         This focuses the algorithm on the region inside UB and LB.\r\n\t//         Unless the user wishes to concentrate the search to a par-\r\n\t//         ticular region, UB and LB should be set to very large positive\r\n\t//         and negative values, respectively. Note that the starting\r\n\t//         vector X should be inside this region. Also note that LB and\r\n\t//         UB are fixed in position, while VM is centered on the last\r\n\t//         accepted trial set of variables that optimizes the function.\r\n\t//    C - Vector that controls the step length adjustment. The suggested\r\n\t//        value for all elements is 2.0. (DP(N))\r\n\t//    IPRINT - controls printing inside SA. (INT)\r\n\t//             Values: 0 - Nothing printed.\r\n\t//                     1 - Function value for the starting value and\r\n\t//                         summary results before each temperature\r\n\t//                         reduction. This includes the optimal\r\n\t//                         function value found so far, the total\r\n\t//                         number of moves (broken up into uphill,\r\n\t//                         downhill, accepted and rejected), the\r\n\t//                         number of out of bounds trials, the\r\n\t//                         number of new optima found at this\r\n\t//                         temperature, the current optimal X and\r\n\t//                         the step length VM. Note that there are\r\n\t//                         N*NS*NT function evalutations before each\r\n\t//                         temperature reduction. Finally, notice is\r\n\t//                         is also given upon achieveing the termination\r\n\t//                         criteria.\r\n\t//                     2 - Each new step length (VM), the current optimal\r\n\t//                         X (XOPT) and the current trial X (X). This\r\n\t//                         gives the user some idea about how far X\r\n\t//                         strays from XOPT as well as how VM is adapting\r\n\t//                         to the function.\r\n\t//                     3 - Each function evaluation, its acceptance or\r\n\t//                         rejection and new optima. For many problems,\r\n\t//                         this option will likely require a small tree\r\n\t//                         if hard copy is used. This option is best\r\n\t//                         used to learn about the algorithm. A small\r\n\t//                         value for MAXEVL is thus recommended when\r\n\t//                         using IPRINT = 3.\r\n\t//             Suggested value: 1\r\n\t//             Note: For a given value of IPRINT, the lower valued\r\n\t//                   options (other than 0) are utilized.\r\n\t//    ISEED1 - The first seed for the random number generator RANMAR.\r\n\t//             0 <= ISEED1 <= 31328. (INT)\r\n\t//    ISEED2 - The second seed for the random number generator RANMAR.\r\n\t//             0 <= ISEED2 <= 30081. Different values for ISEED1\r\n\t//             and ISEED2 will lead to an entirely different sequence\r\n\t//             of trial points and decisions on downhill moves (when\r\n\t//             maximizing). See Goffe et al. on how this can be used\r\n\t//             to test the results of SA. (INT)\r\n\t//\r\n\t//  Input/Output Parameters:\r\n\t//    T - On input, the initial temperature. See Goffe et al. for advice.\r\n\t//        On output, the final temperature. (DP)\r\n\t//    VM - The step length vector. On input it should encompass the\r\n\t//         region of interest given the starting value X. For point\r\n\t//         X(I), the next trial point is selected is from X(I) - VM(I)\r\n\t//         to  X(I) + VM(I). Since VM is adjusted so that about half\r\n\t//         of all points are accepted, the input value is not very\r\n\t//         important (i.e. is the value is off, SA adjusts VM to the\r\n\t//         correct value). (DP(N))\r\n\t//\r\n\t//  Output Parameters:\r\n\t//    XOPT - The variables that optimize the function. (DP(N))\r\n\t//    FOPT - The optimal value of the function. (DP)\r\n\t//    NACC - The number of accepted function evaluations. (INT)\r\n\t//    NFCNEV - The total number of function evaluations. In a minor\r\n\t//             point, note that the first evaluation is not used in the\r\n\t//             core of the algorithm; it simply initializes the\r\n\t//             algorithm. (INT).\r\n\t//    NOBDS - The total number of trial function evaluations that\r\n\t//            would have been out of bounds of LB and UB. Note that\r\n\t//            a trial point is randomly selected between LB and UB.\r\n\t//            (INT)\r\n\t//    IER - The error return number. (INT)\r\n\t//          Values: 0 - Normal return; termination criteria achieved.\r\n\t//                  1 - Number of function evaluations (NFCNEV) is\r\n\t//                      greater than the maximum number (MAXEVL).\r\n\t//                  2 - The starting value (X) is not inside the\r\n\t//                      bounds (LB and UB).\r\n\t//                  3 - The initial temperature is not positive.\r\n\t//                  99 - Should not be seen; only used internally.\r\n\t//\r\n\t//  Work arrays that must be dimensioned in the calling routine:\r\n\t//       RWK1 (DP(NEPS))  (FSTAR in SA)\r\n\t//       RWK2 (DP(N))     (XP    \"  \" )\r\n\t//       IWK  (INT(N))    (NACP  \"  \" )\r\n\t//\r\n\t//  Required Functions (included):\r\n\t//    EXPREP - Replaces the function EXP to avoid under- and overflows.\r\n\t//             It may have to be modified for non IBM-type main-\r\n\t//             frames. (DP)\r\n\t//    RMARIN - Initializes the random number generator RANMAR.\r\n\t//    RANMAR - The actual random number generator. Note that\r\n\t//             RMARIN must run first (SA does this). It produces uniform\r\n\t//             random numbers on [0,1]. These routines are from\r\n\t//             Usenet's comp.lang.fortran. For a reference, see\r\n\t//             \"Toward a Universal Random Number Generator\"\r\n\t//             by George Marsaglia and Arif Zaman, Florida State\r\n\t//             University Report: FSU-SCRI-87-50 (1987).\r\n\t//             It was later modified by F. James and published in\r\n\t//             \"A Review of Pseudo-random Number Generators.\" For\r\n\t//             further information, contact stuart@ads.com. These\r\n\t//             routines are designed to be portable on any machine\r\n\t//             with a 24-bit or more mantissa. I have found it produces\r\n\t//             identical results on a IBM 3081 and a Cray Y-MP.\r\n\t//\r\n\t//  Required Subroutines (included):\r\n\t//    PRTVEC - Prints vectors.\r\n\t//    PRT1 ... PRT10 - Prints intermediate output.\r\n\t//    FCN - Function to be optimized. The form is\r\n\t//            SUBROUTINE FCN(N,X,F)\r\n\t//            INTEGER N\r\n\t//            DOUBLE PRECISION  X(N), F\r\n\t//            ...\r\n\t//            function code with F = F(X)\r\n\t//            ...\r\n\t//            RETURN\r\n\t//            END\r\n\t//          Note: This is the same form used in the multivariable\r\n\t//          minimization algorithms in the IMSL edition 10 library.\r\n\t//\r\n\t//  Machine Specific Features:\r\n\t//    1. EXPREP may have to be modified if used on non-IBM type main-\r\n\t//       frames. Watch for under- and overflows in EXPREP.\r\n\t//    2. Some FORMAT statements use G25.18; this may be excessive for\r\n\t//       some machines.\r\n\t//    3. RMARIN and RANMAR are designed to be protable; they should not\r\n\t//       cause any problems.\r\n\tERMsg CInsectParameterization::Optimize(string s, size_t  e, CSAParameterVector& parameters, CComputationVariable& computation, CCallback& callback)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\r\n\t\tif (m_bShowTrace)\r\n\t\t\tWriteInfoEx(parameters, computation, callback);\r\n\r\n\t\t//  Initialize the random number generator RANMAR.\r\n\t\tCRandomizeNumber random(m_ctrl.Seed1(), m_ctrl.Seed2());\r\n\r\n\t\tbool bQuit = false;\r\n\r\n\t\t//  Start the main loop. Note that it terminates if :\r\n\t\t//(i) the algorithm successfully optimizes the function \r\n\t\t//(ii) there are too many function evaluations (more than MAXEVL).\r\n\t\tint L = 0;\r\n\t\tdo\r\n\t\t{\r\n\t\t\tL++;\r\n\r\n\t\t\tlong NUP = 0;\r\n\t\t\tlong NREJ = 0;\r\n\t\t\tlong NNEW = 0;\r\n\t\t\tlong NDOWN = 0;\r\n\t\t\tlong LNOBDS = 0;\r\n\r\n\t\t\tfor (int M = 0; M < m_ctrl.NT() && msg; M++)\r\n\t\t\t{\r\n\t\t\t\tvector<int> NACP;\r\n\t\t\t\tNACP.insert(NACP.begin(), computation.m_X.size(), 0);\r\n\r\n\t\t\t\tfor (size_t j = 0; j < m_ctrl.NS() && msg; j++)\r\n\t\t\t\t{\r\n\r\n\t\t\t\t\tfor (size_t h = 0; h < NACP.size() && msg; h++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t//  If too many function evaluations occur, terminate the algorithm.\r\n\t\t\t\t\t\tif (computation.m_NFCNEV >= m_ctrl.MAXEVL())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tcallback.AddMessage(\"Number of function evaluations (NFCNEV) is greater than the maximum number (MAXEVL).\");\r\n\t\t\t\t\t\t\t//msg.ajoute();\r\n\t\t\t\t\t\t\treturn msg;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tcomputation.m_XP.resize(computation.m_X.size());\r\n\t\t\t\t\t\tcomputation.m_SP.Reset();\r\n\t\t\t\t\t\tcomputation.m_FP = m_ctrl.GetVMiss();\r\n\r\n\t\t\t\t\t\t//  Generate XP, the trial value of X. Note use of VM to choose XP.\r\n\t\t\t\t\t\tfor (size_t i = 0; i < computation.m_X.size(); i++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (i == h)\r\n\t\t\t\t\t\t\t\tcomputation.m_XP[i] = computation.m_X[i] + (random.Ranmar()*2.0 - 1.0) * computation.m_VM[i];\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\tcomputation.m_XP[i] = computation.m_X[i];\r\n\r\n\r\n\t\t\t\t\t\t\t//  If XP is out of bounds, select a point in bounds for the trial.\r\n\t\t\t\t\t\t\tif (computation.m_bounds[i].IsOutOfBound(computation.m_XP[i]))\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tcomputation.m_XP[i] = computation.m_bounds[i].GetLowerBound() + computation.m_bounds[i].GetExtent()*random.Ranmar();\r\n\t\t\t\t\t\t\t\tLNOBDS++;\r\n\t\t\t\t\t\t\t\tcomputation.m_NOBDS++;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t//  Evaluate the function with the trial point XP and return as FP.\r\n\t\t\t\t\t\tGetFValue(s, e, computation);\r\n\r\n\t\t\t\t\t\t//add X value to extreme XP statistic\r\n\t\t\t\t\t\tfor (size_t i = 0; i < computation.m_XP.size() && i < computation.m_XPstat.size(); i++)\r\n\t\t\t\t\t\t\tcomputation.m_XPstat[i] += computation.m_XP[i];\r\n\r\n\t\t\t\t\t\tfor (size_t i = 0; i < computation.m_VMstat.size(); i++)\r\n\t\t\t\t\t\t\tcomputation.m_VMstat[i] += computation.m_VM[i];\r\n\r\n\r\n\r\n\t\t\t\t\t\t//  Accept the new point if the function value increases.\r\n\t\t\t\t\t\tif (computation.m_FP != m_ctrl.GetVMiss())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (computation.m_FP >= computation.m_F)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tcomputation.m_X = computation.m_XP;\r\n\t\t\t\t\t\t\t\tcomputation.m_F = computation.m_FP;\r\n\t\t\t\t\t\t\t\tcomputation.m_AICC = computation.m_AICCP;\r\n\t\t\t\t\t\t\t\tcomputation.m_MLL = computation.m_MLLP;\r\n\t\t\t\t\t\t\t\tcomputation.m_S = computation.m_SP;\r\n\t\t\t\t\t\t\t\tcomputation.m_NACC++;\r\n\t\t\t\t\t\t\t\tNACP[h]++;\r\n\t\t\t\t\t\t\t\tNUP++;\r\n\r\n\t\t\t\t\t\t\t\t//  If greater than any other point, record as new optimum.\r\n\t\t\t\t\t\t\t\tif (computation.m_FP > computation.m_Fopt)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tcomputation.m_Xopt = computation.m_XP;\r\n\t\t\t\t\t\t\t\t\tcomputation.m_Fopt = computation.m_FP;\r\n\t\t\t\t\t\t\t\t\tcomputation.m_AICCopt = computation.m_AICCP;\r\n\t\t\t\t\t\t\t\t\tcomputation.m_MLLopt = computation.m_MLLP;\r\n\t\t\t\t\t\t\t\t\tcomputation.m_Sopt = computation.m_SP;\r\n\t\t\t\t\t\t\t\t\tNNEW++;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t//  If the point is lower, use the Metropolis criteria to decide on\r\n\t\t\t\t\t\t\t//  acceptance or rejection.\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tdouble P = Exprep((computation.m_FP - computation.m_F) / computation.m_T);\r\n\t\t\t\t\t\t\t\tdouble PP = random.Ranmar();\r\n\t\t\t\t\t\t\t\tif (PP < P)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tcomputation.m_X = computation.m_XP;\r\n\t\t\t\t\t\t\t\t\tcomputation.m_F = computation.m_FP;\r\n\t\t\t\t\t\t\t\t\tcomputation.m_AICC = computation.m_AICCP;\r\n\t\t\t\t\t\t\t\t\tcomputation.m_MLL = computation.m_MLLP;\r\n\t\t\t\t\t\t\t\t\tcomputation.m_S = computation.m_SP;\r\n\t\t\t\t\t\t\t\t\tcomputation.m_NACC++;\r\n\t\t\t\t\t\t\t\t\tNACP[h]++;\r\n\t\t\t\t\t\t\t\t\tNDOWN++;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tNREJ = NREJ + 1;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t} //if\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\tNREJ = NREJ + 1;\r\n\t\t\t\t\t\t\t//Eliminate this evaluation??\r\n\t\t\t\t\t\t\th--;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tcomputation.m_NFCNEV++;\r\n\r\n\r\n\t\t\t\t\t\t//if (msg)\r\n\t\t\t\t\t\tmsg += callback.StepIt(0);\r\n\t\t\t\t\t} //H\r\n\t\t\t\t} //J\r\n\r\n\r\n\r\n\t\t\t\t//  Adjust VM so that approximately half of all evaluations are accepted.\r\n\t\t\t\tASSERT(computation.m_VM.size() == NACP.size());\r\n\t\t\t\tfor (int I = 0; I < computation.m_VM.size(); I++)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble RATIO = double(NACP[I]) / double(m_ctrl.NS());\r\n\t\t\t\t\tif (RATIO > 0.6)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcomputation.m_VM[I] = computation.m_VM[I] * (1. + computation.m_C[I] * (RATIO - .6) / .4);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (RATIO < 0.4)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcomputation.m_VM[I] = computation.m_VM[I] / (1. + computation.m_C[I] * ((.4 - RATIO) / .4));\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\tif (computation.m_VM[I] > computation.m_bounds[I].GetExtent())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcomputation.m_VM[I] = computation.m_bounds[I].GetExtent();\r\n\t\t\t\t\t}\r\n\t\t\t\t}//all VM\r\n\t\t\t}//M\r\n\r\n\t\t\tif (m_bShowTrace)\r\n\t\t\t\tWriteInfoEx(parameters, computation, callback);\r\n\r\n\r\n\t\t\tcomputation.m_Xstat = computation.m_XPstat;\r\n\t\t\tfor (size_t i = 0; i < computation.m_XPstat.size(); i++)\r\n\t\t\t\tcomputation.m_XPstat[i].Reset();\r\n\r\n\t\t\t//clean VM stats\r\n\t\t\tfor (size_t i = 0; i < computation.m_VMstat.size(); i++)\r\n\t\t\t\tcomputation.m_VMstat[i].Reset();\r\n\r\n\t\t\t//  Loop again.\r\n\t\t\tbQuit = fabs(computation.m_F - computation.m_Fopt) <= m_ctrl.EPS();\r\n\t\t\tfor (int I = 0; I < computation.m_FSTAR.size() && bQuit; I++)\r\n\t\t\t{\r\n\t\t\t\tif (fabs(computation.m_F - computation.m_FSTAR[I]) > m_ctrl.EPS())\r\n\t\t\t\t\tbQuit = false;\r\n\t\t\t}\r\n\r\n\t\t\t//  If termination criteria is not met, prepare for another loop.\r\n\t\t\tcomputation.PrepareForAnotherLoop(m_ctrl.RT());\r\n\r\n\t\t} while (!bQuit&&msg);\r\n\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\r\n\tvoid CInsectParameterization::GetFValue(string var, size_t e, CComputationVariable& computation)\r\n\t{\r\n\t\t//bool bValid = false;\r\n\t\tbool bLogLikelyhoude = m_ctrl.m_statisticType == LIKELIHOOD;\r\n\t\tdouble log_likelyhoude = 0;\r\n\t\tsize_t N_likelyhoude = 0;\r\n\t\t//size_t N = 0;\r\n\t\tCStatisticXYEx stat;\r\n\r\n\t\t//ofStream file;\r\n\t\t//file.open(\"G:\\\\Travaux\\\\Aproceros leucopoda\\\\Output\\\\test.csv\");\r\n\t\t//file << \"Variable,T,Tsim,Tobs\" << endl;\r\n\r\n\t\tif (m_fitType == F_DEV_TIME_WTH_SIGMA)\r\n\t\t{\r\n\t\t\tTDevRateEquation eq = CDevRateEquation::eq(e);\r\n\t\t\tif (CDevRateEquation::IsParamValid(eq, computation.m_XP))\r\n\t\t\t{\r\n\t\t\t\tdouble sigma = computation.m_XP.back();\r\n\r\n\t\t\t\tfor (__int64 i = 0; i < (__int64)m_devTime.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (WBSF::IsEqualNoCase(m_devTime[i].m_variable, var))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (bLogLikelyhoude)//use likelyhood method\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tdouble LL = 0;\r\n\r\n\t\t\t\t\t\t\tif (m_devTime.m_bIndividual)//use individual time\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tLL = Regniere2021DevRate(eq, sigma, computation.m_XP, m_Tobs[m_devTime[i].m_traitment], m_devTime[i][I_TIME]);\r\n\t\t\t\t\t\t\t\tLL *= m_devTime[i][I_N];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse//use mean+sd+n\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t//LL seem to not have to be mutiply by N!\r\n\t\t\t\t\t\t\t\tLL = Regniere2021DevRateMeanSDn(eq, computation.m_XP, m_Tobs[m_devTime[i].m_traitment], m_devTime[i][I_MEAN_TIME], m_devTime[i][I_TIME_SD], m_devTime[i][I_N]);\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tif (!isfinite(LL) || isnan(LL))\r\n\t\t\t\t\t\t\t\treturn;\r\n\r\n\t\t\t\t\t\t\tlog_likelyhoude += LL;\r\n\t\t\t\t\t\t\tN_likelyhoude += m_devTime[i][I_N];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse//use least square method\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (m_devTime.m_bIndividual)//use individual time\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tdouble rate = GetRateStat(eq, computation.m_XP, m_Tobs[m_devTime[i].m_traitment], m_devTime[i][I_TIME]);\r\n\t\t\t\t\t\t\t\tif (!isfinite(rate) || isnan(rate))\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\r\n\t\t\t\t\t\t\t\tboost::math::lognormal_distribution<double> LogNormal(-0.5*Square(sigma), sigma);\r\n\t\t\t\t\t\t\t\tdouble RDR = quantile(LogNormal, m_devTime[i][I_Q_RATE]);\r\n\t\t\t\t\t\t\t\tdouble sim = rate * RDR;\r\n\t\t\t\t\t\t\t\tdouble obs = m_devTime[i][I_RATE];\r\n\t\t\t\t\t\t\t\tfor (size_t n = 0; n < m_devTime[i][I_N]; n++)\r\n\t\t\t\t\t\t\t\t\tstat.Add(sim, obs);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse//use mean+sd+n \r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tdouble mean_time = GetTimeStat(eq, computation.m_XP, m_Tobs[m_devTime[i].m_traitment]);\r\n\t\t\t\t\t\t\t\tif (!isfinite(mean_time) || isnan(mean_time))\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\r\n\t\t\t\t\t\t\t\tdouble obs = 1 / m_devTime[i][I_MEAN_TIME];//apply the same aproximation\r\n\t\t\t\t\t\t\t\tdouble sim = 1 / mean_time;//apply the same aproximation\r\n\r\n\t\t\t\t\t\t\t\tfor (size_t n = 0; n < m_devTime[i][I_N]; n++)\r\n\t\t\t\t\t\t\t\t\tstat.Add(sim, obs);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}//if valid\r\n\t\t\t\t}//for\r\n\t\t\t}//if valid parameters\r\n\t\t}\r\n\t\telse if (m_fitType == F_DEV_TIME_ONLY)//base on mean rate only (no sigma)\r\n\t\t{\r\n\r\n\t\t\tTDevRateEquation eq = CDevRateEquation::eq(e);\r\n\t\t\tif (CDevRateEquation::IsParamValid(eq, computation.m_XP))\r\n\t\t\t{\r\n\t\t\t\tfor (__int64 i = 0; i < (__int64)m_devTime.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (WBSF::IsEqualNoCase(m_devTime[i].m_variable, var))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (bLogLikelyhoude)\r\n\t\t\t\t\t\t{\r\n\r\n\t\t\t\t\t\t\tdouble LL = 0;\r\n\t\t\t\t\t\t\tif (m_devTime.m_bIndividual)//use individual time\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t//ASSERT(false);\r\n\t\t\t\t\t\t\t\t//LL = Regniere2021DevRateMeanSDn(eq, computation, m_Tobs[m_devTime[i].m_traitment], m_devTime[i][I_MEAN_TIME], m_devTime[i][I_TIME_SD], m_devTime[i][I_N]);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tLL = Regniere2021DevRateMeanSDn(eq, computation.m_XP, m_Tobs[m_devTime[i].m_traitment], m_devTime[i][I_MEAN_TIME], m_devTime[i][I_TIME_SD], m_devTime[i][I_N]);\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tif (!isfinite(LL) || isnan(LL))\r\n\t\t\t\t\t\t\t\treturn;\r\n\r\n\t\t\t\t\t\t\t//log_likelyhoude += LL;\r\n\t\t\t\t\t\t\t//N_likelyhoude++;\r\n\t\t\t\t\t\t\tlog_likelyhoude += LL/* * m_devTime[i][I_N]*/;\r\n\t\t\t\t\t\t\tN_likelyhoude += m_devTime[i][I_N];\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\tif (m_devTime[i][I_MEAN_TIME] > 0)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tdouble mean_time = GetTimeStat(eq, computation.m_XP, m_Tobs[m_devTime[i].m_traitment]);\r\n\t\t\t\t\t\t\t\tif (!isfinite(mean_time) || isnan(mean_time) || mean_time<-1E8 || mean_time>1E8)\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\r\n\t\t\t\t\t\t\t\tdouble obs = 1.0 / m_devTime[i][I_MEAN_TIME];//apply the same approximation\r\n\t\t\t\t\t\t\t\tdouble sim = 1.0 / mean_time;//apply the same approximation\r\n\r\n\r\n\t\t\t\t\t\t\t\tfor (size_t n = 0; n < m_devTime[i][I_N]; n++)\r\n\t\t\t\t\t\t\t\t\tstat.Add(sim, obs);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}//if valid\r\n\t\t\t\t}//for\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (m_fitType == F_SURVIVAL)\r\n\t\t{\r\n\t\t\tTSurvivalEquation eq = CSurvivalEquation::eq(e);\r\n\t\t\tif (CSurvivalEquation::IsParamValid(eq, computation.m_XP))\r\n\t\t\t{\r\n\t\t\t\tfor (__int64 i = 0; i < (__int64)m_survival.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (WBSF::IsEqualNoCase(m_survival[i].m_variable, var))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (bLogLikelyhoude)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t//maximum likelihood\r\n\t\t\t\t\t\t\tdouble LL = Regniere2021Survival(eq, computation.m_XP, m_Tobs[m_survival[i].m_traitment], m_survival[i][I_MEAN_TIME], m_survival[i][I_SURVIVAL], m_survival[i][I_N]);\r\n\t\t\t\t\t\t\tif (!isfinite(LL) || isnan(LL))\r\n\t\t\t\t\t\t\t\treturn;\r\n\r\n\t\t\t\t\t\t\tlog_likelyhoude += LL;\r\n\t\t\t\t\t\t\tN_likelyhoude += m_survival[i][I_N];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{//RSS\r\n\t\t\t\t\t\t\t//stage survival\r\n\t\t\t\t\t\t\tif (m_survival[i][I_MEAN_TIME] > 0)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tdouble obs = m_survival[i][I_SURVIVAL] / m_survival[i][I_N];\r\n\t\t\t\t\t\t\t\tdouble sim = GetSurvival(eq, computation.m_XP, m_Tobs[m_survival[i].m_traitment], m_survival[i][I_MEAN_TIME]);\r\n\r\n\t\t\t\t\t\t\t\tif (!isfinite(sim) || isnan(sim) || sim<-1E8 || sim>1E8)\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\r\n\t\t\t\t\t\t\t\tfor (size_t n = 0; n < m_survival[i][I_N]; n++)\r\n\t\t\t\t\t\t\t\t\tstat.Add(sim, obs);\r\n\t\t\t\t\t\t\t}\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}\r\n\t\t}\r\n\t\telse if (m_fitType == F_FECUNDITY)\r\n\t\t{\r\n\t\t\tTFecundityEquation eq = CFecundityEquation::eq(e);\r\n\t\t\tif (CFecundityEquation::IsParamValid(eq, computation.m_XP))\r\n\t\t\t{\r\n\t\t\t\tfor (__int64 i = 0; i < (__int64)m_fecundity.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (WBSF::IsEqualNoCase(m_fecundity[i].m_variable, var))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (bLogLikelyhoude)//use likelyhood method\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tdouble LL = 0;\r\n\r\n\t\t\t\t\t\t\tif (m_fecundity.m_bIndividualSeries)//use individual time\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tLL = Regniere2021FecundityTimeSeries(eq, computation.m_XP, m_Tobs[m_fecundity[i].m_traitment], m_fecundity[i][I_START], m_fecundity[i][I_START] + m_fecundity[i][I_TIME], m_fecundity[i][I_BROOD], m_fecundity[i][I_Q_BROOD]);\r\n\t\t\t\t\t\t\t\tLL *= m_fecundity[i][I_N];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (m_fecundity.m_bIndividual)//use individual time\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tLL = Regniere2021Fecundity(eq, computation.m_XP, m_Tobs[m_fecundity[i].m_traitment], m_fecundity[i][I_START] + m_fecundity[i][I_TIME], m_fecundity[i][I_BROOD], m_fecundity[i][I_Q_BROOD]);\r\n\t\t\t\t\t\t\t\tLL *= m_fecundity[i][I_N];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse//use mean+sd+n\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t//LL seem to not have to be mutiply by N!\r\n\t\t\t\t\t\t\t\tLL = Regniere2021FecundityMeanSDn(eq, computation.m_XP, m_Tobs[m_fecundity[i].m_traitment], m_fecundity[i][I_MEAN_TIME], m_fecundity[i][I_MEAN_BROOD], m_fecundity[i][I_BROOD_SD], m_fecundity[i][I_N]);\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tif (!isfinite(LL) || isnan(LL))\r\n\t\t\t\t\t\t\t\treturn;\r\n\r\n\t\t\t\t\t\t\tlog_likelyhoude += LL;\r\n\t\t\t\t\t\t\tN_likelyhoude += m_fecundity[i][I_N];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse//use least square method\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (m_fecundity.m_bIndividual)//use individual time\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t//double F = quantile(LogNormal, m_fecundity[i][I_Q_BROOD]);\r\n\t\t\t\t\t\t\t\t//double brood = GetFecundity(eq, computation, m_Tobs[m_fecundity[i].m_traitment], m_fecundity[i][I_START], m_fecundity[i][I_START] + m_fecundity[i][I_TIME], qi[i]);\r\n\t\t\t\t\t\t\t\t//if (!isfinite(brood) || isnan(brood))\r\n\t\t\t\t\t\t\t\t//\treturn;\r\n\r\n\t\t\t\t\t\t\t\t////boost::math::lognormal_distribution<double> LogNormal(-0.5*Square(sigma), sigma);\r\n\t\t\t\t\t\t\t\t////double RFR = quantile(LogNormal, m_fecundity[i][I_Q_BROOD]);\r\n\t\t\t\t\t\t\t\t//double sim = brood;\r\n\t\t\t\t\t\t\t\t//double obs = m_fecundity[i][I_BROOD];\r\n\t\t\t\t\t\t\t\t//for (size_t n = 0; n < m_fecundity[i][I_N]; n++)\r\n\t\t\t\t\t\t\t\t//\tstat.Add(sim, obs);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse//use mean+sd+n \r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t//double F = quantile(LogNormal, m_fecundity[i][I_Q_BROOD]);\r\n\t\t\t\t\t\t\t\t//double brood = GetFecundity(eq, computation, m_Tobs[m_fecundity[i].m_traitment], m_fecundity[i][I_START], m_fecundity[i][I_START] + m_fecundity[i][I_MEAN_TIME], m_fecundity[i][I_Q_BROOD]);\r\n\t\t\t\t\t\t\t\t//if (!isfinite(brood) || isnan(brood))\r\n\t\t\t\t\t\t\t\t//\treturn;\r\n\r\n\t\t\t\t\t\t\t\t////boost::math::lognormal_distribution<double> LogNormal(-0.5*Square(sigma), sigma);\r\n\t\t\t\t\t\t\t\t////double RFR = quantile(LogNormal, m_fecundity[i][I_Q_BROOD]);\r\n\t\t\t\t\t\t\t\t//double sim = brood;\r\n\t\t\t\t\t\t\t\t//double obs = m_fecundity[i][I_MEAN_BROOD];\r\n\t\t\t\t\t\t\t\t//for (size_t n = 0; n < m_fecundity[i][I_N]; n++)\r\n\t\t\t\t\t\t\t\t//\tstat.Add(sim, obs);\r\n\r\n\t\t\t\t\t\t\t\t/*double to = 0;\r\n\t\t\t\t\t\t\t\tdouble obs = m_fecundity[i][I_MEAN_BROOD];\r\n\t\t\t\t\t\t\t\tdouble sim = GetFecundity(eq, F, to, computation, m_Tobs[m_fecundity[i].m_traitment], m_fecundity[i][I_START], m_fecundity[i][I_START] + m_fecundity[i][I_TIME]);\r\n\r\n\t\t\t\t\t\t\t\tfor (size_t n = 0; n < m_fecundity[i][I_N]; n++)\r\n\t\t\t\t\t\t\t\t\tstat.Add(sim, obs);*/\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\r\n\t\tif (bLogLikelyhoude)\r\n\t\t{\r\n\t\t\tif (N_likelyhoude > 0)\r\n\t\t\t{\r\n\t\t\t\tdouble k = computation.m_XP.size();\r\n\t\t\t\tdouble n = N_likelyhoude;\r\n\t\t\t\tdouble AIC = 2 * k - 2 * (log_likelyhoude);\r\n\t\t\t\tdouble AICc = AIC + (2 * k*(k + 1) / (n - k - 1));// n/k < 40\r\n\r\n\t\t\t\tcomputation.m_AICCP = AICc;\r\n\t\t\t\tcomputation.m_MLLP = log_likelyhoude;\r\n\t\t\t\tcomputation.m_FP = m_ctrl.AdjustFValue(log_likelyhoude);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (stat[NB_VALUE] > 1)\r\n\t\t{\r\n\t\t\tcomputation.m_FP = m_ctrl.AdjustFValue(stat[m_ctrl.m_statisticType]);\r\n\t\t\tcomputation.m_SP = stat;\r\n\t\t}\r\n\r\n\t\t//file.close();\r\n\t}\r\n\r\n\r\n\tERMsg CInsectParameterization::ReadParametersFromFile(const std::string& outputFilePath, std::map<std::string, std::map<std::string, std::map<std::string, double>>>& params)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\tparams.clear();\r\n\r\n\t\tifStream file;\r\n\t\tmsg = file.open(outputFilePath);\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tfor (CSVIterator loop(file); loop != CSVIterator(); ++loop)\r\n\t\t\t{\r\n\t\t\t\tif ((*loop).size() >= 3)\r\n\t\t\t\t{\r\n\t\t\t\t\tstring variable = (*loop)[0];\r\n\t\t\t\t\tstring e_name = (*loop)[1];\r\n\t\t\t\t\tStringVector p((*loop)[2], \" \");\r\n\t\t\t\t\tfor (size_t i = 0; i < p.size(); i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tStringVector pp(p[i], \"=\");\r\n\t\t\t\t\t\tassert(pp.size() == 2);\r\n\t\t\t\t\t\tif (pp.size() == 2)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tparams[variable][e_name][pp[0]] = as<double>(pp[1]);\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}\r\n\r\n\t\t\tfile.close();\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\ttemplate <typename T> inline\r\n\t\tstd::string ToString2(const T& v, const std::string& be = \"[\", const std::string& sep = \",\", const std::string& en = \"]\")\r\n\t{\r\n\t\tstd::string str = be;\r\n\t\tfor (typename T::const_iterator it = v.begin(); it != v.end(); it++)\r\n\t\t{\r\n\t\t\tif (it != v.begin())\r\n\t\t\t\tstr += sep;\r\n\t\t\tstr += ToString(*it);\r\n\t\t}\r\n\r\n\t\tstr += en;\r\n\r\n\t\treturn str;\r\n\t}\r\n\r\n\ttemplate <typename T, size_t size> inline\r\n\t\tconst std::array<T, size> ToArray(const std::string& str, const std::string& be = \"[\", const std::string& sep = \",\", const std::string& en = \"]\")\r\n\t{\r\n\t\tStringVector tmp = Tokenize(str, be + sep + en);\r\n\t\tstd::array<T, size> v;\r\n\r\n\t\tsize_t i = 0;\r\n\t\tfor (StringVector::const_iterator it = tmp.begin(); it != tmp.end(); it++, i++)\r\n\t\t\tif (!it->empty() && i < v.size())\r\n\t\t\t\tv[i] = ToValue<T>(*it);\r\n\r\n\t\treturn v;\r\n\t}\r\n\r\n\r\n\tvoid CInsectParameterization::writeStruc(zen::XmlElement& output)const\r\n\t{\r\n\t\tCExecutable::writeStruc(output);\r\n\t\tzen::XmlOut out(output);\r\n\r\n\t\tout[GetMemberName(FIT_TYPE)](m_fitType);\r\n\t\tout[GetMemberName(DEV_RATE_EQUATIONS)](m_eqDevRate);\r\n\t\tout[GetMemberName(SURVIVAL_EQUATIONS)](m_eqSurvival);\r\n\t\tout[GetMemberName(FECUNDITY_EQUATIONS)](m_eqFecundity);\r\n\t\tout[GetMemberName(EQ_OPTIONS)](m_eq_options);\r\n\t\tout[GetMemberName(INPUT_FILE_NAME)](m_inputFileName);\r\n\t\tout[GetMemberName(OUTPUT_FILE_NAME)](m_outputFileName);\r\n\t\tout[GetMemberName(TOBS_FILE_NAME)](m_TobsFileName);\r\n\t\tout[GetMemberName(CONTROL)](m_ctrl);\r\n\t\tout[GetMemberName(FIXE_TB)](m_bFixeTb);\r\n\t\tout[GetMemberName(TB_VALUE)](ToString2(m_Tb));\r\n\t\tout[GetMemberName(FIXE_TO)](m_bFixeTo);\r\n\t\tout[GetMemberName(TO_VALUE)](ToString2(m_To));\r\n\t\tout[GetMemberName(FIXE_TM)](m_bFixeTm);\r\n\t\tout[GetMemberName(TM_VALUE)](ToString2(m_Tm));\r\n\t\tout[GetMemberName(FIXE_F0)](m_bFixeF0);\r\n\t\tout[GetMemberName(F0_VALUE)](ToString2(m_F0));\r\n\t\tout[GetMemberName(USE_OUTPUT_AS_INPUT)](m_bUseOutputAsInput);\r\n\t\tout[GetMemberName(OUTPUT_AS_INTPUT_FILENAME)](m_outputAsIntputFileName);\r\n\t\tout[GetMemberName(SHOW_TRACE)](m_bShowTrace);\r\n\r\n\t}\r\n\r\n\tbool CInsectParameterization::readStruc(const zen::XmlElement& input)\r\n\t{\r\n\t\tstring tmp;\r\n\t\tCExecutable::readStruc(input);\r\n\t\tzen::XmlIn in(input);\r\n\t\tin[GetMemberName(FIT_TYPE)](m_fitType);\r\n\t\tin[GetMemberName(DEV_RATE_EQUATIONS)](m_eqDevRate);\r\n\t\tin[GetMemberName(SURVIVAL_EQUATIONS)](m_eqSurvival);\r\n\t\tin[GetMemberName(FECUNDITY_EQUATIONS)](m_eqFecundity);\r\n\t\tin[GetMemberName(EQ_OPTIONS)](m_eq_options);\r\n\t\tin[GetMemberName(INPUT_FILE_NAME)](m_inputFileName);\r\n\t\tin[GetMemberName(TOBS_FILE_NAME)](m_TobsFileName);\r\n\t\tin[GetMemberName(OUTPUT_FILE_NAME)](m_outputFileName);\r\n\t\tin[GetMemberName(CONTROL)](m_ctrl);\r\n\t\tin[GetMemberName(FIXE_TB)](m_bFixeTb);\r\n\t\tin[GetMemberName(TB_VALUE)](tmp); m_Tb = ToArray<double, 3>(tmp);\r\n\t\tin[GetMemberName(FIXE_TO)](m_bFixeTo);\r\n\t\tin[GetMemberName(TO_VALUE)](tmp); m_To = ToArray<double, 3>(tmp);\r\n\t\tin[GetMemberName(FIXE_TM)](m_bFixeTm);\r\n\t\tin[GetMemberName(TM_VALUE)](tmp); m_Tm = ToArray<double, 3>(tmp);\r\n\t\tin[GetMemberName(FIXE_F0)](m_bFixeF0);\r\n\t\tin[GetMemberName(F0_VALUE)](tmp); m_F0 = ToArray<double, 3>(tmp);\r\n\t\tin[GetMemberName(USE_OUTPUT_AS_INPUT)](m_bUseOutputAsInput);\r\n\t\tin[GetMemberName(OUTPUT_AS_INTPUT_FILENAME)](m_outputAsIntputFileName);\r\n\t\tin[GetMemberName(SHOW_TRACE)](m_bShowTrace);\r\n\r\n\r\n\r\n\r\n\t\treturn true;\r\n\t}\r\n}\r\n", "meta": {"hexsha": "638174b914400bd6d3a69db83922b4e5738cbb7e", "size": 124401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wbs/src/Simulation/InsectParameterization.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/Simulation/InsectParameterization.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/Simulation/InsectParameterization.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": 31.3273734576, "max_line_length": 378, "alphanum_fraction": 0.5839663668, "num_tokens": 38001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5073036237957256}}
{"text": "#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"tyco.hpp\"\n\nnamespace cs\n{\nstruct world {};\nstruct camera {};\n};\n\ntemplate<typename Cs>\nusing point3 = tyco::P3::column_vector<double, Cs>;\n\ntemplate<typename Cs>\nusing plane3 = tyco::P3::row_vector<double, Cs>;\n\ntemplate<typename CsLeft, typename CsRight>\nusing homography3 = tyco::P3::homography<double, CsLeft, CsRight>;\n\nint main()\n{\n    using namespace std;\n    cout << \"TEST\" << endl;\n\n    auto point_world  = point3<cs::world>{{1, 1, 1, 1}};\n    auto point_camera = point3<cs::camera>{{1, 1, 1, 0}};\n\n    auto plane_world  = plane3<cs::world>();\n    auto plane_camera = plane3<cs::camera>();\n\n    auto camera_from_world  = homography3<cs::camera, cs::world>();\n    auto world_from_camera  = homography3<cs::world,  cs::camera>();\n    auto world_from_world   = homography3<cs::world,  cs::world>();\n    auto camera_from_camera = homography3<cs::camera, cs::camera>();\n\n    world_from_camera = inverse(camera_from_world);\n    camera_from_world = inverse(world_from_camera);\n\n    point_camera = camera_from_world * point_world;\n    point_world = world_from_camera * point_camera;\n\n    plane_camera = plane_world * world_from_camera;\n    plane_world = plane_camera * camera_from_world;\n\n    world_from_world = world_from_camera * camera_from_world;\n    camera_from_camera = camera_from_world * world_from_camera;\n}\n", "meta": {"hexsha": "c068ce57c90578486db712e4db915a23eb1ee94d", "size": 1394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/main.cpp", "max_stars_repo_name": "mabur/tyco", "max_stars_repo_head_hexsha": "1a3ae83c7452e20fae3c62c4f25599e8e50aa3f5", "max_stars_repo_licenses": ["MIT"], "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/main.cpp", "max_issues_repo_name": "mabur/tyco", "max_issues_repo_head_hexsha": "1a3ae83c7452e20fae3c62c4f25599e8e50aa3f5", "max_issues_repo_licenses": ["MIT"], "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/main.cpp", "max_forks_repo_name": "mabur/tyco", "max_forks_repo_head_hexsha": "1a3ae83c7452e20fae3c62c4f25599e8e50aa3f5", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 68, "alphanum_fraction": 0.7065997131, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.507303619775199}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#define NT2_UNIT_MODULE \"nt2 optimize toolbox - levenberg\"\n\n#include <iostream>\n#include <nt2/include/functions/levenberg.hpp>\n\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/bind.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/exp.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/include/functions/globalsum.hpp>\n#include <nt2/include/functions/globalmax.hpp>\n#include <nt2/include/functions/ones.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/constants/four.hpp>\n#include <nt2/table.hpp>\n\ntemplate < class Tabout >\nstruct fpp\n{\n  template < class Tabin> inline\n  Tabout operator()(const Tabin & x ) const\n  {\n    typedef typename Tabin::value_type value_type;\n//    Tabout r = (nt2::sqr(x)-value_type(3))*x+nt2::_(value_type(1), value_type(numel(x)));\n    Tabout r = (nt2::sqr((x-nt2::_(value_type(1), value_type(numel(x))))));\n    return r;\n  }\n};\n\ntemplate<class Tabout, class Tabin >  Tabout f1(const Tabin & x )\n{\n    typedef typename Tabin::value_type value_type;\n    Tabout r = (nt2::sqr(x)-value_type(3))*x;\n    return r;\n}\n\n// NT2_TEST_CASE_TPL( levenberg_function_ptr, NT2_REAL_TYPES )\n// {\n//   using nt2::levenberg;\n//   using nt2::optimization::output;\n//   typedef nt2::table<T> tab_t;\n//   typedef typename nt2::meta::as_logical<T>::type lT;\n//   typedef nt2::table<T> ltab_t;\n//   tab_t x0 = nt2::zeros(nt2::of_size(1, 3), nt2::meta::as_<T>());\n//   ltab_t h = nt2::is_nez(nt2::ones (nt2::of_size(1, 3), nt2::meta::as_<T>())*nt2::Half<T>());\n//   tab_t r = nt2::ones (nt2::of_size(1, 3), nt2::meta::as_<T>());\n//   output<tab_t,T> res = levenberg(&f1<tab_t, tab_t>, x0, h);\n\n//   std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n//             << \" after \" << res.iterations_count <<  \" iterations\\n\";\n\n//   NT2_TEST(res.successful);\n//   NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::abs(res.minimum()-r)), nt2::Sqrteps<T>());\n// }\n\nNT2_TEST_CASE_TPL( levenberg_functor, NT2_REAL_TYPES )\n{\n  using nt2::levenberg;\n  using nt2::options;\n  using nt2::optimization::output;\n  typedef nt2::table<T> tab_t;\n  typedef typename nt2::meta::as_logical<T>::type lT;\n  typedef nt2::table<T> ltab_t;\n  tab_t x0 = nt2::zeros(nt2::of_size(1, 3), nt2::meta::as_<T>());\n  ltab_t h = nt2::is_nez(nt2::ones (nt2::of_size(1, 3), nt2::meta::as_<T>())*nt2::Half<T>());\n  tab_t r = nt2::_(T(1), T(3));\n  output<tab_t,T> res = levenberg(fpp<tab_t>(), x0, h,\n                                  options [ nt2::iterations_ = 100,\n                                            nt2::tolerance::absolute_ = nt2::Eps<T>()\n                                    ]);\n\n  std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n            << \" after \" << res.iterations_count <<  \" iterations\\n\";\n\n  NT2_TEST(res.successful);\n  NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::abs(res.minimum()-r)), nt2::Four<T>()*nt2::Sqrteps<T>());\n\n}\n\n// NT2_TEST_CASE_TPL( levenberg_function, (double)(float) )\n// {\n//   using nt2::levenberg;\n//   using nt2::optimization::output;\n\n//   output<T,T> res = levenberg<T>( f1, 0, 0.5, 2 );\n\n//   std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n//             << \" after \" << res.iterations_count <<  \" iterations\\n\";\n\n//   NT2_TEST(res.successful);\n//   NT2_TEST_LESSER_EQUAL(nt2::abs(res.minimum - 1.f), nt2::Sqrteps<float>());\n// }\n\n// NT2_TEST_CASE_TPL( levenberg_functor, (double)(float) )\n// {\n//   using nt2::levenberg;\n//   using nt2::optimization::output;\n\n//   output<T,T> res = levenberg<T>( f2(), 0, 0.5, 2 );\n\n//   std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n//             << \" after \" << res.iterations_count <<  \" iterations\\n\";\n\n//   NT2_TEST(res.successful);\n//   NT2_TEST_LESSER_EQUAL(nt2::abs(res.minimum - T(1)), nt2::Sqrteps<T>());\n// }\n\n// NT2_TEST_CASE_TPL( levenberg_bind, (double)(float) )\n// {\n//   using nt2::levenberg;\n//   using nt2::optimization::output;\n\n//   output<T,T> res = levenberg<T>( boost::bind(f3, _1, 3., 4.), 0, 0.5, 2 );\n\n//   std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n//             << \" after \" << res.iterations_count <<  \" iterations\\n\";\n\n//   NT2_TEST(res.successful);\n//   NT2_TEST_LESSER_EQUAL(nt2::abs(res.minimum - T(1)), nt2::Sqrteps<T>());\n// }\n\n// NT2_TEST_CASE_TPL( levenberg_lambdda, (double)(float) )\n// {\n//   using nt2::levenberg;\n//   using nt2::optimization::output;\n//   namespace bl = boost::lambda;\n\n//   output<T,T> res = levenberg<T>( bl::_1*bl::_1*bl::_1 - 3*bl::_1 + 4\n//                             , 0, 0.5, 2\n//                             );\n\n//   std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n//             << \" after \" << res.iterations_count <<  \" iterations\\n\";\n\n//   NT2_TEST(res.successful);\n//   NT2_TEST_LESSER_EQUAL(nt2::abs(res.minimum - T(1)), nt2::Sqrteps<T>());\n// }\n\n// NT2_TEST_CASE_TPL( levenberg_tie, (double)(float) )\n// {\n//   using nt2::levenberg;\n//   using boost::fusion::tie;\n//   using boost::fusion::ignore;\n\n//   std::size_t i;\n//   T x,y,fx;\n//   bool convergence_successful;\n\n//   tie(x,fx,i,convergence_successful) = levenberg<T>( &f0<T>, 0, 0.5, 2 );\n//   std::cout << \"Minimum : f(\" << x << \") = \" << fx\n//             << \" after \" << i <<  \" iterations\\n\";\n\n//   NT2_TEST(convergence_successful);\n//   NT2_TEST_LESSER_EQUAL(nt2::abs(x - T(1)), nt2::Sqrteps<T>());\n\n//   tie(y,ignore,ignore,ignore) = levenberg<T>( &f0<T>, 0, 0.5, 2 );\n//   std::cout << \"Minimum is at y = \" << y << \"\\n\";\n\n//   NT2_TEST_LESSER_EQUAL(nt2::abs(y - T(1)), nt2::Sqrteps<T>());\n// }\n\n// NT2_TEST_CASE_TPL( levenberg_option, (double)(float) )\n// {\n//   using nt2::levenberg;\n//   using nt2::options;\n//   using nt2::optimization::output;\n\n//   output<T,T> res = levenberg<T>( f1, 0, 0.5, 2\n//                             , options [ nt2::iterations_ = 10\n//                                       , nt2::tolerance::absolute_ = T(1e-3)\n//                                       ]\n//                             );\n\n//   std::cout << \"Minimum : f(\" << res.minimum << \") = \"  << res.value\n//             << \" after \"      << res.iterations_count   <<  \" iterations\\n\";\n\n//   NT2_TEST(res.successful);\n//   NT2_TEST_LESSER_EQUAL(nt2::abs(res.minimum - 1.f), 1e-3);\n\n//   res = levenberg<T>( f1, 0,0.5,2, options [ nt2::iterations_ = 1 ] );\n//   NT2_TEST(!res.successful);\n// }\n\n// double f1(const matrix < double >& x )       {\n//      return x*x*x-3*x+4;\n// }\n\n// int main(int argc, char* argv[])\n// {\n//   ffp fff;\n//   matrix < double >  b =  0.5*ones(1);\n//   matrix < double >  h =  ones(1);\n//   levenberg < matrix < double > > hjm;\n//   cout << hjm.optimize(fff, b, h) << endl; ;\n//   cout << b << endl;\n//   cout << \"minimum \" << hjm.optimize(fff, b, h) <<  \" au point \" <<  b << \" en \" << hjm.getNbIteration() <<  \" iterations\" << endl;\n\n// }\n", "meta": {"hexsha": "a9900c9e895417bd703284aa55bea3cdbb5c15bf", "size": 7464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/optimization/unit/scalar/levenberg.cpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/optimization/unit/scalar/levenberg.cpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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": "modules/core/optimization/unit/scalar/levenberg.cpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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.2075471698, "max_line_length": 134, "alphanum_fraction": 0.5628349411, "num_tokens": 2339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5072746886162445}}
{"text": "/*****************************************************************************/\n/*                                                                           */\n/* Best-fit                                                                  */\n/*                                                                           */\n/* Copyright 2014                                                            */\n/* Alasdair Craig                                                            */\n/* ac@acraig.za.net                                                          */\n/* License: Code Project Open License 1.02                                   */\n/* http://www.codeproject.com/info/cpol10.aspx                               */\n/*                                                                           */\n/*****************************************************************************/\n\n#ifdef _MSC_VER\n#pragma warning( disable : 4244 ) // suppress possible loss-of-data warning arising from boost\n#endif\n\n\n#include \"BestFit.h\"\n#include \"cholesky.h\"\n\n#include <limits>\n#include <cassert>\n#include <stdexcept>\n#include <iomanip>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n\n#define CONVERGENCE_CRITERIA 0.000000001\n#define MAX_ITERATIONS 50\n\nBestFit::BestFit(int unknowns)\n\t: m_verbosity(1)\n\t, m_oStream(m_nullStream)\n\t, m_solution(unknowns,1)\n\t, m_provisionals(unknowns,1)\n\t, m_numObs(0)\n\t, m_numUnknowns(unknowns)\n\t, m_minx( std::numeric_limits<double>::max())\n\t, m_maxx(-std::numeric_limits<double>::max())\n\t, m_miny( std::numeric_limits<double>::max())\n\t, m_maxy(-std::numeric_limits<double>::max())\n{\n}\n\nBestFit::BestFit(int unknowns, std::ostream &oStream)\n\t: m_verbosity(1)\n\t, m_oStream(oStream)\n\t, m_solution(unknowns,1)\n\t, m_provisionals(unknowns,1)\n\t, m_numObs(0)\n\t, m_numUnknowns(unknowns)\n\t, m_minx( std::numeric_limits<double>::max())\n\t, m_maxx(-std::numeric_limits<double>::max())\n\t, m_miny( std::numeric_limits<double>::max())\n\t, m_maxy(-std::numeric_limits<double>::max())\n{\n}\n\nBestFit::~BestFit()\n{\n}\n\n// Set the level of detail required for output to stdout\nvoid BestFit::SetVerbosity(int verbosity)\n{\n\tm_verbosity = verbosity;\n}\n\nbool BestFit::Compute(BestFitIO &in, BestFitIO &out)\n{\n\tSetVerbosity(in.verbosity);\n\n\tif (!in.points || in.numPoints == 0)\n\t\t{\n\t\tm_oStream << \"No solution. No input points.\" << std::endl;\n\t\treturn false;\n\t\t}\n\tif (in.numPoints < m_numUnknowns + 1)\n\t\t{\n\t\tm_oStream << \"No solution. Too few input points, need \" << m_numUnknowns + 1 - in.numPoints << \" or more.\" << std::endl;\n\t\treturn false;\n\t\t}\n\n\tm_numObs = in.numPoints;\n\n\tResizeMatrices();\n\n\tfor (int i = 0; i < m_numObs; ++i)\n\t{\n\t\tdouble x = in.points[i * 2 + 0];\n\t\tdouble y = in.points[i * 2 + 1];\n\t\tAddObservation(i, x, y);\n\t}\n\n\tCompute();\n\n\tFillOutput(out);\n\n\treturn true;\n}\n\nvoid BestFit::ResizeMatrices()\n{\n\tm_residuals.resize(m_numObs, 1);\n\tm_design.resize(m_numObs, m_numUnknowns);\n\tm_l.resize(m_numObs, 1);\n\tm_qweight.resize(m_numObs, m_numObs, 0, 0);\n\tm_observations.resize(m_numObs, 2);\n\tm_b.resize(m_numObs, m_numObs * 2);\n}\n\n// Add another observable (coordinate) to the computation object\nvoid BestFit::AddObservation(int count, double x, double y)\n{\n\tm_observations(count, 0) = x;\n\tm_observations(count, 1) = y;\n\n\tm_minx = std::min<double>(m_minx, x);\n\tm_maxx = std::max<double>(m_maxx, x);\n\tm_miny = std::min<double>(m_miny, y);\n\tm_maxy = std::max<double>(m_maxy, y);\n}\n\n// Do the least-squares adjustment\nbool BestFit::Compute()\n{\n\tif (m_verbosity > 1)\n\t\tm_oStream << \"Observations:    \" << m_observations << std::endl;\n\n\tGenerateProvisionals();\n\n\tbool successful = true;\n\n\tint iteration = 0;\n\n\twhile (true)\n\t\t{\n\t\tFormulateMatrices();\n\n\t\tif (m_verbosity > 1)\n\t\t\t{\n\t\t\tm_oStream << \"Provisionals:    \" << m_provisionals << std::endl;\n\t\t\tm_oStream << \"l-matrix:        \" << m_l << std::endl;\n\t\t\t}\n\n\t\t// evaluate the unknowns - small corrections to be applied to the provisional unknowns\n\t\tif (EvaluateUnknowns())\n\t\t\t{\n\t\t\t++iteration;\n\n\t\t\t// add the solution to the provisional unknowns\n\t\t\tEvaluateAdjustedUnknowns();\n\n\t\t\tif (HasConverged())\n\t\t\t\tbreak;\n\t\t\tif (IsDegenerate(iteration))\n\t\t\t\tbreak;\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tsuccessful = false;\n\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\tsuccessful = successful && (iteration > 0 && iteration < MAX_ITERATIONS);\n\tif (successful)\n\t\t{\n\t\t// Give ellipse chance to normalise it's axes. \n\t\tNormaliseAdjustedUnknowns();\n\n\t\t// evaluate the residuals\n\t\tEvaluateResiduals();\n\n\t\t// add the residuals to the provisional observations\n\t\tEvaluateAdjustedObservations();\n\n\t\t// Check that the adjusted unknowns and adjusted observations satisfy\n\t\t// the original line/circle/ellipse equation.\n\t\tGlobalCheck();\n\n\t\t// Subsequent error analysis and statistical output\n\t\tErrorAnalysis(iteration);\n\n\t\tif (0 == m_verbosity)\n\t\t\tOutputSimpleSolution();\n\t\t}\n\n\treturn successful;\n}\n\n// Matrix inversion routine using LU decomposition\nbool BestFit::InvertMatrix(const ublas::matrix<double> &input, ublas::matrix<double> &inverse)\n{\n\t// create a working copy of the input\n\tublas::matrix<double> A(input);\n\n\t// create a permutation matrix for the LU-factorization\n\tublas::permutation_matrix<double> pm(A.size1());\n\n\t// perform LU-factorization\n\tauto res = ublas::lu_factorize(A, pm);\n\tif (res != 0)\n\t\treturn false;\n\n\t// create identity matrix of \"inverse\"\n\tinverse.assign(ublas::identity_matrix<double>(A.size1()));\n\n\ttry\n\t\t{\n\t\t// back-substitute to get the inverse\n\t\tublas::lu_substitute(A, pm, inverse);\n\t\t}\n\tcatch (std::logic_error &)\n\t\t{\n\t\treturn false;\n\t\t}\n\n\treturn true;\n}\n\n// Determine solution vector\nbool BestFit::EvaluateUnknowns()\n{\n\tublas::matrix<double> pa = ublas::prod(m_qweight, m_design);\n\tublas::matrix<double> atpa = ublas::prod(ublas::trans(m_design), pa);\n\n\tublas::matrix<double> inverse(atpa.size1(), atpa.size2());\n\t//if (CholeskyInversion(atpa, inverse))\n\tif (InvertMatrix(atpa, inverse))\n\t\t{\n\t\tublas::matrix<double> pl = ublas::prod(m_qweight, m_l);\n\t\tublas::matrix<double> atpl = ublas::prod(ublas::trans(m_design), pl);\n\n\t\tm_solution = ublas::prod(inverse, atpl);\n\n\t\tif (m_verbosity > 2)\n\t\t\tm_oStream << \"Iter. solution   \" << m_solution << std::endl;\n\t\treturn true;\n\t\t}\n\telse\n\t\tm_oStream << \"No solution. Cannot invert matrix.\" << std::endl;\n\treturn false;\n}\n\n\n// Add solution to the provisionals\nvoid BestFit::EvaluateAdjustedUnknowns()\n{\n\tm_provisionals += m_solution;\n\n\tif (m_verbosity > 2)\n\t\tm_oStream << \"Iter adj unknowns\" << m_provisionals << std::endl;\n}\n\n// Residuals to the initial observations\nvoid BestFit::EvaluateResiduals()\n{\n\t// v = Ax-l, quasi-residuals in the case of circle and ellipse\n\tm_residuals = ublas::prod(m_design, m_solution) - m_l;\n\n\tif (m_verbosity > 1)\n\t\tm_oStream << \"Residuals:       \" << m_residuals << std::endl;\n}\n\nvoid BestFit::EvaluateFinalResiduals(int point, double &vxi, double &vyi) const\n{\n\t// In the case of the quasi-parametric case (circle and ellipse) the actual\n\t// residuals for both the x and y coordinate need to be extracted.\n\tvxi = m_design(point, 0) * m_qweight(point, point) * m_residuals(point, 0);\n\tvyi = m_design(point, 1) * m_qweight(point, point) * m_residuals(point, 0);\n\n\t//// Method 1: ref (2:35)\n\t//ublas::matrix<double> bt = ublas::trans(m_b);\n\t//ublas::matrix<double> pv = ublas::prod(m_qweight, m_residuals);\n\t//ublas::matrix<double> btpv = ublas::prod(bt, pv);\n\t//double avxi = -btpv(point * 2 + 0,0);\n\t//double avyi = -btpv(point * 2 + 1,0);\n\t//m_oStream << \"New residuals (Method 1) differ by: \" << avxi - vxi << \",\" << avyi - vyi << std::endl;\n\n\t//// Method 2: ref (2:28)\n\t//double dx = m_observations(point, 0) - m_provisionals(0, 0);\n\t//double dy = m_observations(point, 1) - m_provisionals(1, 0);\n\t//double r = m_provisionals(2, 0);\n\t//double quasiv = -2.0 * dx * m_solution(0, 0) - 2.0 * dy * m_solution(1, 0) - 2.0 * r * m_solution(2, 0) - m_l(point, 0);\n\t//double bvxi = - (quasiv * 2.0 * dx) / (4.0 * (dx * dx + dy * dy));\n\t//double bvyi = - (quasiv * 2.0 * dy) / (4.0 * (dx * dx + dy * dy));\n\t//m_oStream << \"New residuals (Method 2) differ by: \" << bvxi - vxi << \",\" << bvyi - vyi << std::endl;\n}\n\n// Add residuals to initial observations\nvoid BestFit::EvaluateAdjustedObservations()\n{\n\tfor (int i = 0; i < m_numObs; ++i)\n\t\t{\n\t\tdouble vxi = 0.0;\n\t\tdouble vyi = 0.0;\n\t\tEvaluateFinalResiduals(i, vxi, vyi); // overridden for normal (non-quasi-parametric) BestFitLine\n\n\t\tm_observations(i, 0) += vxi;\n\t\tm_observations(i, 1) += vyi;\n\t\t}\n\n\tif (m_verbosity > 1)\n\t\tm_oStream << \"Adj. observations\" << m_observations << std::endl;\n}\n\n// Global check on the quality of the adjustment\nvoid BestFit::GlobalCheck()\n{\n\tublas::vector<double> global(m_numObs, 0);\n\tbool pass = (m_numObs > 0);\n\n\tfor (int i = 0; i < m_numObs; ++i)\n\t\t{\n\t\tdouble x = m_observations(i, 0);\n\t\tdouble y = m_observations(i, 1);\n\n\t\tglobal(i) = SolveAt(x, y); // should be zero\n\t\tpass = pass && fabs(global(i)) < 0.01; // TODO: Is this too lax?\n\t\t}\n\n\tif (m_verbosity > 1)\n\t\tm_oStream << \"Global check:    \" << global << std::endl;\n\tif (m_verbosity > 0)\n\t\tm_oStream << \"Global check of the adjustment     ***\" << (pass ? \"PASSES***\" : \"FAILS***\") << std::endl;\n\n\t// Secondary test is to check that aTPv is zero too, really only neccessary\n\t// if the above global check fails.\n\tublas::matrix<double> atp = ublas::prod(ublas::trans(m_design), m_qweight);\n\tublas::matrix<double> atpv = ublas::prod(atp, m_residuals);\n\n\tpass = true;\n\tfor (int j = 0; j < m_numUnknowns; ++j)\n\t\tpass = pass && Double::IsZero(atpv(j, 0));\n\n\tif (!pass && m_verbosity > 1)\n\t\tm_oStream << \"aTPv             \" << atpv << std::endl;\n\tif (m_verbosity > 0)\n\t\tm_oStream << \"Check of the evaluated unknowns    ***\" << (pass ? \"PASSES***\" : \"FAILS***\") << std::endl;\n}\n\n// Predicate for seeing whether the solution has become sufficiently small\nbool BestFit::HasConverged() const\n{\n\tfor (int i = 0; i < m_numUnknowns; ++i)\n\t\t{\n\t\tif (fabs(m_solution(i, 0)) > CONVERGENCE_CRITERIA)\n\t\t\treturn false;\n\t\t}\n\treturn true;\n}\n\n// Predicate for seeing whether the solution is diverging?\nbool BestFit::IsDegenerate(int iteration) const\n{\n\tbool degenerate = (iteration >= MAX_ITERATIONS);\n\tif (degenerate)\n\t\tm_oStream << \"No solution. Does not converge.\" << std::endl;\n\n\treturn degenerate;\n}\n\n// Output stats\n// TODO: Variance-covariance matrices\nvoid BestFit::ErrorAnalysis(int iterations)\n{\n\tublas::matrix<double> pv = ublas::prod(m_qweight, m_residuals);\n\tublas::matrix<double> vtpv = ublas::prod(ublas::trans(m_residuals), pv);\n\tint degreesFreedom = m_numObs - m_numUnknowns;\n\tdouble variance = vtpv(0, 0) / degreesFreedom;\n\tdouble stddev = sqrt(variance);\n\n\tif (m_verbosity > 0)\n\t\t{\n\t\tm_oStream << std::setprecision(6) << std::setiosflags(std::ios::fixed)\n\t\t\t<< \"Number of observations             \" << m_numObs << std::endl\n\t\t\t<< \"Number of unknowns                 \" << m_numUnknowns << std::endl\n\t\t\t<< \"Degrees of freedom                 \" << degreesFreedom << std::endl\n\t\t\t<< \"Iterations until convergence       \" << iterations << std::endl\n\t\t\t<< \"Variance                           \" << variance << std::endl\n\t\t\t<< \"Std. dev. observation unit weight  \" << stddev << std::endl;\n\n\t\tm_oStream << \"***********************************\" << std::endl;\n\n\t\tOutputAdjustedUnknowns(m_oStream);\n\t\t}\n}\n\n// Output at it's very simplest\nvoid BestFit::OutputSimpleSolution() const\n{\n\tfor (int i = 0; i < m_numUnknowns; ++i)\n\t\tm_oStream << m_provisionals(i, 0) << std::endl;\n}\n\n// Return selected values back to caller\nvoid BestFit::FillOutput(BestFitIO &out) const\n{\n\tout.numPoints = m_numObs;\n\tout.numOutputFields = m_numUnknowns;\n\tout.verbosity = m_verbosity;\n\n\t//memset(out.outputFields, 0, sizeof(outputFields));\n\tfor (int i = 0; i < m_numUnknowns; ++i)\n\t\tout.outputFields[i] = m_provisionals(i, 0);\n\n\tif (out.wantResiduals)\n\t\tout.residuals = new double[m_numObs];\n\n\tfor (int j = 0; j < m_numObs; ++j)\n\t{\n\t\tif (out.wantAdjustedObs)\n\t\t{\n\t\t\tout.points[j * 2 + 0] = m_observations(j, 0);\n\t\t\tout.points[j * 2 + 1] = m_observations(j, 1);\n\t\t}\n\t\tif (out.wantResiduals)\n\t\t\tout.residuals[j] = m_residuals(j, 0);\n\t}\n}\n\nvoid BestFit::LowerTriangularModifyInversion(const ublas::matrix<double> &l, ublas::matrix<double> &m)\n{\n\ttypedef ublas::matrix<double>::size_type INDEX;\n\tINDEX i, j, n = l.size1();\n\n\tfor (i = 0; i < n; ++i)\n\t\tm(i, i) = 1.0 / l(i, i);\n\n\tfor (j = 0; j < n; ++j)\n\t{\n\t\tfor (i = j + 1; i < n; ++i)\n\t\t{\n\t\t\tassert(i > j);\n\n\t\t\tdouble sum = 0.0;\n\t\t\tfor (INDEX k = j; k <= i - 1; ++k)\n\t\t\t\tsum += l(i, k) * m(k, j);\n\n\t\t\tm(i, j) = -m(i, i) * sum;\n\t\t}\n\t}\n}\n\nbool BestFit::CholeskyInversion(const ublas::matrix<double> &input, ublas::matrix<double> &inverse)\n{\n\tublas::matrix<double> l(input.size1(), input.size2());\n\tublas::matrix<double> m(input.size1(), input.size2(), 0.0);\n\n\tif (0 == cholesky_decompose(input, l))\n\t{\n\t\tLowerTriangularModifyInversion(l, m);\n\n\t\tinverse = ublas::prod(ublas::trans(m), m);\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n", "meta": {"hexsha": "8d3d96b03c9a0e7368c4aa09b5bebc2612f2fe31", "size": 12789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Plugins/uk.ac.kcl.VascularModeling/src/internal/3rdParty/BestFit/BestFit.cpp", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Plugins/uk.ac.kcl.VascularModeling/src/internal/3rdParty/BestFit/BestFit.cpp", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugins/uk.ac.kcl.VascularModeling/src/internal/3rdParty/BestFit/BestFit.cpp", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 27.5625, "max_line_length": 123, "alphanum_fraction": 0.619829541, "num_tokens": 3849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.507270585927715}}
{"text": "#ifndef MATMETHODS_HPP\n#define MATMETHODS_HPP\n#include \"mkl.h\"\n#include \"mkl_vsl.h\"\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <algorithm>\n#include \"armadillo\"\n\nusing namespace arma;\nusing namespace std;\n\nmat CorMats(const mat &A, const mat &B){\n  mat C = cor(A,B);\n  C.elem(find_nonfinite(C)).zeros();\n  return(C);\n}\n\nmat CVCorMAD(const mat &Est, const mat &TestA, const mat &TestB){\n  mat testC = CorMats(TestA,TestB);\n  mat Errmat = abs(Est-testC);\n  return(Errmat);\n}\n\numat GenBoot (size_t colsize, size_t bootstrapnumber){\n\n  umat samplemat = randi<umat>(bootstrapnumber,colsize,distr_param(0,colsize-1));\n \n  return(samplemat);\n}\n\nmat BootstrapSample(mat &A,umat &Bootmat,int i){\n\n  return(A.rows(Bootmat.row(i)));\n}\n\nvoid Mdim(const mat &cmat,const string matname){\n  cout<<matname<<\" has \"<<cmat.n_rows<<\"rows and \"<<cmat.n_cols<<\" cols\"<<endl;\n}\n\nmat BootCorMedian(mat &A, mat &B,cube &C,cube &quants,umat &BootMat,int bsi){\n  \n  int status;\n  mat medians(A.n_cols,B.n_cols);\n  if(A.n_rows!=BootMat.n_cols){\n    cerr<<\"Boot(incorrect indices):  A.n_rows= \"<<A.n_rows<<\" BM.n_cols= \"<<BootMat.n_cols<<endl;\n    throw 15;\n  }\n  int n= bsi;\n  int samplenum = C.n_slices;\n  VSLSSTaskPtr task;\n  MKL_INT q_order_n=2;\n  double q_order[q_order_n];\n  double params;\n  MKL_INT p,nparams,xstorage;\n  p = C.n_rows*C.n_cols;\n  xstorage = VSL_SS_MATRIX_STORAGE_COLS;\n  params = 0.001;\n  nparams = VSL_SS_SQUANTS_ZW_PARAMS_N;\n  q_order[0] = 0.5;\n  q_order[1] = 0.5+(double)(1)/((double)n);\n  \n  status = vsldSSNewTask(&task,&p,&samplenum,&xstorage,C.memptr(),0,NULL);\n  status = vsldSSEditStreamQuantiles(task,&q_order_n,q_order,quants.memptr(),&nparams,&params);\n  \n  cerr<<\"Starting Bootstrap:\"<<bsi<<endl;\n  //First iteration of bootstrap\n  mat tA(A.n_rows,A.n_cols);\n  mat tB(B.n_rows,B.n_cols);\n  int m=0;\n  for(int i=0; i<bsi; ++i){\n    tA = BootstrapSample(A,BootMat,i);\n    tB = BootstrapSample(B,BootMat,i);\n    \n    m = i%C.n_slices;\n    C.slice(m) = CorMats(tA,tB);\n    \n    if(m==(C.n_slices-1)){\n      status = vsldSSCompute(task,VSL_SS_STREAM_QUANTS,VSL_SS_METHOD_SQUANTS_ZW_FAST);\n    }\n  }\n  samplenum=0;\n  status = vsldSSCompute(task,VSL_SS_STREAM_QUANTS,VSL_SS_METHOD_SQUANTS_ZW);\n  status = vslSSDeleteTask(&task);\n  if(n%2==0){\n    medians = 0.5*quants(span(0,0),span(),span())+0.5*quants(span(1,1),span(),span());\n  }else{\n    medians = quants(span(0,0),span(),span());\n  }\n  cerr<<\"Bootstrap finished\"<<endl;\n  return(medians);\n}\n\n\n\nuvec trainindex(const size_t totalsize,const int ksize,const int k){\n  uvec returnvec(totalsize-ksize);\n  int j=-1;\n  for(int i=0; i<totalsize; i++){\n    if(i <(k*ksize)||i>((k+1)*ksize)-1){\n      j++;\n      returnvec(j)=i;\n    }\n  }\n  if(j+1!=totalsize-ksize){\n    cerr<<\"j=\"<<j<<\" returnsize= \"<<totalsize-ksize-1<<endl;\n  }\n  return(returnvec);\n}\n  \nuvec testindex(const size_t totalsize,const  int ksize,const  int k){\n  uvec returnvec(ksize);\n  int j=-1;\n  for( int i=0; i<totalsize; i++){\n    if(i>=(k*ksize)&&i<=((k+1)*ksize-1)){\n      j++;\n      returnvec(j)=i;\n\n    }\n  }\n  if(j+1!=ksize){\n    cerr<<\"j=\"<<j<<\" ksize= \"<<ksize<<endl;\n  }\n  return(returnvec);\n}\n\n\nvoid KfoldCV (const mat &A,const mat &B, const int kfold, const int chunknum, const int bsi,const string outfilename,const int bsichunksize){\n\n\n  int kfoldIterations = kfold;\n  int iter_k = (int) floor((double)A.n_rows/(double)kfold);\n  if(kfoldIterations<1){\n    cerr<<\"Must have at least one iteration of cross-validation, not \"<<kfoldIterations<<endl;\n    throw 12;\n  }\n  \n  cout<<\"Begin \"<<iter_k<<\"-fold cross validation (\"<<kfoldIterations<<\" iterations). There are \"<<A.n_rows<<\" samples\"<<endl;\n  uvec testi = testindex(A.n_rows,iter_k,0);\n  uvec traini = trainindex(A.n_rows,iter_k,0);\n\n  \n  mat testA,testB,trainA,trainB;\n\n  cout<<\"Initiating variables.\"<<endl;\n  mat Point(A.n_cols,B.n_cols);\n  cube C(A.n_cols,B.n_cols,bsichunksize);\n  cube quants(2,C.n_rows,C.n_cols,fill::zeros);\n  cout<<\"Generating Bootmat (Dimensions should be \"<<bsi<<\"x\"<<traini.n_elem<<\")\"<<endl;\n  umat BootMat = GenBoot(traini.n_elem,bsi);\n  cout<<\"Starting kfold: 0\"<<endl;\n  mat MedianMat(A.n_cols,B.n_cols,fill::zeros);\n  mat BootMAD(A.n_cols,B.n_cols,fill::zeros);\n  mat pointMAD(A.n_cols,B.n_cols,fill::zeros);\n\n\n  \n  for(int i=0; i<kfoldIterations; i++){\n    cout<<\"Starting kfold: \"<<i<<endl;\n    testi = testindex(A.n_rows,iter_k,i);\n    traini = trainindex(A.n_rows,iter_k,i);\n    testA = A.rows(testi);\n    testB = B.rows(testi);\n    trainA = A.rows(traini);\n    trainB = B.rows(traini);\n\n    Point = CorMats(trainA,trainB);\n \n    MedianMat = BootCorMedian(trainA,trainB,C,quants,BootMat,bsi);\n   \n    BootMAD=BootMAD+CVCorMAD(MedianMat,testA,testB);\n   \n    pointMAD += CVCorMAD(Point,testA,testB);\n  \n  }\n  pointMAD = pointMAD/kfoldIterations;\n  BootMAD/=kfoldIterations;\n\n  double pointSumMAD = accu(pointMAD)/pointMAD.n_elem;\n  double SumMAD = accu(BootMAD)/BootMAD.n_elem;\n  ofstream outputfile;\n\n  outputfile.open(outfilename.c_str(),std::ofstream::out|std::ofstream::app);\n  outputfile.setf(ios::fixed,ios::floatfield);\n\n  outputfile.precision(10);  \n  if(chunknum==0){\n    outputfile<<\"Chunk\\tSize\\tbsi\\tPointMAD\\tBootMAD\"<<endl;\n  }\n  outputfile<<chunknum<<\"\\t\"<<Point.n_elem<<\"\\t\"<<bsi<<\"\\t\"<<pointSumMAD<<\"\\t\"<<SumMAD<<\"\\t\"<<endl;\n  \n  outputfile.close();\n}\n    \n\n#endif\n\n\n", "meta": {"hexsha": "6b9a9a24c2613b056355431eb785a8e7c931b151", "size": 5368, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "matmethods.hpp", "max_stars_repo_name": "CreRecombinase/BeQ2L", "max_stars_repo_head_hexsha": "0c5133b85296631a7e7187657337b5a775e456ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-24T04:48:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-24T04:48:26.000Z", "max_issues_repo_path": "matmethods.hpp", "max_issues_repo_name": "CreRecombinase/BeQ2L", "max_issues_repo_head_hexsha": "0c5133b85296631a7e7187657337b5a775e456ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matmethods.hpp", "max_forks_repo_name": "CreRecombinase/BeQ2L", "max_forks_repo_head_hexsha": "0c5133b85296631a7e7187657337b5a775e456ac", "max_forks_repo_licenses": ["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.9748743719, "max_line_length": 141, "alphanum_fraction": 0.6671013413, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5072705859277149}}
{"text": "#include \"mtf/SM/PF.h\"\n#include \"mtf/Utilities/miscUtils.h\" \n#include <boost/random/random_device.hpp>\r\n#include <boost/random/seed_seq.hpp>\n#include \"opencv2/highgui/highgui.hpp\"\r\n\r\n//! OpenMP scheduler\r\n#ifndef PF_OMP_SCHD\r\n#define PF_OMP_SCHD auto\r\n#endif\r\n\n_MTF_BEGIN_NAMESPACE\n\ntemplate <class AM, class SSM>\nPF<AM, SSM >::PF(const ParamType *pf_params,\r\n\tconst AMParams *am_params, const SSMParams *ssm_params) :\r\n\tSearchMethod<AM, SSM>(am_params, ssm_params),\r\n\tparams(pf_params), max_wt_id(0),\r\n\tenable_adaptive_resampling(false), min_eff_particles(0){\r\n\tprintf(\"\\n\");\r\n\tprintf(\"Using Particle Filter SM with:\\n\");\r\n\tprintf(\"max_iters: %d\\n\", params.max_iters);\r\n\tprintf(\"n_particles: %d\\n\", params.n_particles);\r\n\tprintf(\"epsilon: %f\\n\", params.epsilon);\r\n\tprintf(\"dynamic_model: %s\\n\", PFParams::toString(params.dynamic_model));\r\n\tprintf(\"update_type: %s\\n\", PFParams::toString(params.update_type));\r\n\tprintf(\"likelihood_func: %s\\n\", PFParams::toString(params.likelihood_func));\r\n\tprintf(\"resampling_type: %s\\n\", PFParams::toString(params.resampling_type));\r\n\tprintf(\"adaptive_resampling_thresh: %f\\n\", params.adaptive_resampling_thresh);\r\n\tprintf(\"mean_type: %s\\n\", PFParams::toString(params.mean_type));\r\n\tprintf(\"reset_to_mean: %d\\n\", params.reset_to_mean);\r\n\tssm_state_size = ssm.getStateSize();\r\n\tif(params.pix_sigma.empty() || params.pix_sigma[0] <= 0){\r\n\t\tif(params.ssm_sigma.empty()){\r\n\t\t\tthrow utils::InvalidArgument(\"Sigma must be provided for at least one sampler\");\r\n\t\t}\r\n\t\tusing_pix_sigma = false;\r\n\t} else{\r\n\t\tusing_pix_sigma = true;\r\n\t\tprintf(\"pix_sigma: %f\\n\", params.pix_sigma[0]);\r\n\t}\r\n\tprintf(\"measurement_sigma: %f\\n\", params.measurement_sigma);\r\n\tprintf(\"show_particles: %d\\n\", params.show_particles);\r\n\tprintf(\"enable_learning: %d\\n\", params.enable_learning);\r\n\tprintf(\"debug_mode: %d\\n\", params.debug_mode);\r\n\tprintf(\"appearance model: %s\\n\", am.name.c_str());\r\n\tprintf(\"state space model: %s\\n\", ssm.name.c_str());\r\n\tprintf(\"ssm_state_size: %d\\n\", ssm_state_size);\r\n\tprintf(\"\\n\");\r\n\r\n\tname = \"pf\";\r\n\tlog_fname = \"log/pf_debug.txt\";\r\n\ttime_fname = \"log/pf_times.txt\";\r\n\tframe_id = 0;\r\n\r\n\tconst double pi = 3.14159265358979323846;\r\n\tmeasurement_factor = 1.0 / sqrt(2 * pi * params.measurement_sigma);\r\n\r\n\tfor(int set_id = 0; set_id < 2; ++set_id){\n\t\tparticle_states[set_id].resize(params.n_particles);\n\t\tparticle_ar[set_id].resize(params.n_particles);\n\t\tfor(int particle_id = 0; particle_id < params.n_particles; ++particle_id){\r\n\t\t\tparticle_states[set_id][particle_id].resize(ssm_state_size);\r\n\t\t\tparticle_ar[set_id][particle_id].resize(ssm_state_size);\r\n\t\t}\r\n\t}\r\n\tcurr_set_id = 0;\n\tparticle_wts.resize(params.n_particles);\r\n\tparticle_cum_wts.setZero(params.n_particles);\r\n\r\n\tperturbed_state.resize(ssm_state_size);\r\n\tperturbed_ar.resize(ssm_state_size);\r\n\tmean_state.resize(ssm_state_size);\r\n\tstate_sigma.resize(ssm_state_size);\r\n\tstate_mean.resize(ssm_state_size);\r\n\r\n\tif(!using_pix_sigma){\n\t\tif(params.ssm_sigma[0].size() < ssm_state_size){\r\n\t\t\tthrow utils::InvalidArgument(\r\n\t\t\t\tcv::format(\"SSM sigma has invalid size: %d\",\r\n\t\t\t\tparams.ssm_sigma[0].size()));\r\n\t\t}\r\n\t\tif(params.ssm_mean.empty()){\n\t\t\tstate_mean = VectorXd::Zero(ssm_state_size);\n\t\t} else{\n\t\t\tif(params.ssm_mean[0].size() < ssm_state_size){\r\n\t\t\t\tthrow utils::InvalidArgument(\r\n\t\t\t\t\tcv::format(\"SSM ssm_mean has invalid size: %d\",\r\n\t\t\t\t\tparams.ssm_mean[0].size()));\r\n\t\t\t}\n\t\t\tstate_mean = Map<const VectorXd>(params.ssm_mean[0].data(), ssm_state_size);\n\t\t}\r\n\t\tstate_sigma = Map<const VectorXd>(params.ssm_sigma[0].data(), ssm_state_size);\r\n\t\tutils::printMatrix(state_sigma.transpose(), \"state_sigma\");\n\t}\r\n\t// initialize random number generators for resampling and measurement function\r\n\tboost::random_device r;\r\n\tboost::random::seed_seq measurement_seed{ r(), r(), r(), r(), r(), r(), r(), r() };\r\n\r\n\tmeasurement_gen = RandGenT(measurement_seed);\r\n\tmeasurement_dist = MeasureDistT(0, params.measurement_sigma);\r\n\r\n\tboost::random::seed_seq resample_seed{ r(), r(), r(), r(), r(), r(), r(), r() };\r\n\tresample_gen = RandGenT(resample_seed);\r\n\tresample_dist = ResampleDistT(0, 1);\r\n\r\n\tif(params.adaptive_resampling_thresh > 0 && params.adaptive_resampling_thresh <= 1){\r\n\t\tprintf(\"Using adaptive resampling\\n\");\r\n\t\tenable_adaptive_resampling = true;\r\n\t\tmin_eff_particles = params.adaptive_resampling_thresh*params.n_particles;\r\n\t}\r\n\r\n\tif(params.debug_mode){\n\t\tfclose(fopen(log_fname, \"w\"));\r\n\t\tresample_ids.resize(params.n_particles);\r\n\t\tuniform_rand_nums.resize(params.n_particles);\r\n\t}\r\n\r\n#ifdef ENABLE_PARALLEL\r\n\tfor(int particle_id = 0; particle_id < params.n_particles; particle_id++){\r\n\t\tam_vec.push_back(AMPTr(new AM(am_params)));\r\n\t\tssm_vec.push_back(SSMPTr(new SSM(ssm_params)));\r\n\t}\r\n#endif\r\n#if defined ENABLE_OMP\r\nprintf(\" ******* Parallelization is enabled using OpenMP ******* \\n\");\r\n#endif\r\n}\r\n\r\ntemplate <class AM, class SSM>\nvoid PF<AM, SSM >::initialize(const cv::Mat &corners){\r\n\r\n\tssm.initialize(corners, am.getNChannels());\r\n\r\n\tif(using_pix_sigma){\r\n\t\t//! estimate SSM parameter sigma from pixel sigma\r\n\t\tssm.estimateStateSigma(state_sigma, params.pix_sigma[0]);\r\n\t\tstate_mean = VectorXd::Zero(ssm_state_size);\r\n\t}\r\n\t//! initialize SSM sampler with the first distribution\r\n\tssm.initializeSampler(state_sigma, state_mean);\r\n\r\n\tstate_sigma = ssm.getSamplerSigma();\r\n\tstate_mean = ssm.getSamplerMean();\r\n\r\n\tam.initializePixVals(ssm.getPts());\r\n\tam.initializeSimilarity();\r\n\tmax_similarity = am.getSimilarity();\r\n\r\n\tif(params.debug_mode){\r\n\t\t//! print the sigma and mean for the SSM distributions\r\n\t\tutils::printMatrix(state_sigma.transpose(), \"state_sigma\");\r\n\t\tutils::printMatrix(state_mean.transpose(), \"state_mean\");\r\n\t\tutils::printScalar(max_similarity, \"max_similarity\");\r\n\t}\r\n\tinitializeParticles();\r\n\r\n\tprev_corners = ssm.getCorners();\r\n\tssm.getCorners(cv_corners_mat);\r\n#ifdef ENABLE_PARALLEL\r\n\tfor(int particle_id = 0; particle_id < params.n_particles; particle_id++){\r\n\t\tssm_vec[particle_id]->initialize(corners, am.getNChannels());\r\n\t\tssm_vec[particle_id]->initializeSampler(state_sigma, VectorXd::Zero(ssm_state_size));\r\n\t\tam_vec[particle_id]->initializePixVals(ssm.getPts());\r\n\t\tam_vec[particle_id]->initializeSimilarity();\r\n\t}\r\n#endif\r\n}\r\n\r\ntemplate <class AM, class SSM>\nvoid PF<AM, SSM >::initializeParticles(){\r\n\tdouble init_wt = 1.0 / params.n_particles;\r\n\tfor(int particle_id = 0; particle_id < params.n_particles; particle_id++){\r\n\t\tparticle_states[curr_set_id][particle_id] = ssm.getState();\r\n\t\tparticle_wts[particle_id] = init_wt;\r\n\t\tif(particle_id > 0){\n\t\t\tparticle_cum_wts[particle_id] = particle_wts[particle_id] + particle_cum_wts[particle_id - 1];\r\n\t\t} else{\n\t\t\tparticle_cum_wts[particle_id] = particle_wts[particle_id];\n\t\t}\r\n\t\tparticle_ar[curr_set_id][particle_id].setZero();\r\n\t}\r\n}\r\n\r\ntemplate <class AM, class SSM>\nvoid PF<AM, SSM >::update(){\r\n\t++frame_id;\r\n\tam.setFirstIter();\r\n\tint pause_after_show = 1;\r\n\tfor(int i = 0; i < params.max_iters; i++){\r\n\t\tif(params.show_particles){\n\t\t\tam.getCurrImg().convertTo(curr_img_uchar, CV_8UC1);\n\t\t}\r\n\t\tdouble max_wt = std::numeric_limits<double>::lowest();\r\n#ifdef ENABLE_OMP\r\n#pragma omp parallel for schedule(PF_OMP_SCHD)\r\n#endif\t\r\n\t\tfor(int particle_id = 0; particle_id < params.n_particles; ++particle_id){\r\n#ifdef ENABLE_PARALLEL\r\n\t\t\tSSM &ssm = *ssm_vec[particle_id];\r\n\t\t\tAM &am = *am_vec[particle_id];\r\n#endif\r\n\t\t\tswitch(params.dynamic_model){\n\t\t\tcase DynamicModel::AutoRegression1:\n\t\t\t\tswitch(params.update_type){\n\t\t\t\tcase UpdateType::Additive:\n\t\t\t\t\tssm.additiveAutoRegression1(perturbed_state, perturbed_ar,\n\t\t\t\t\t\tparticle_states[curr_set_id][particle_id], particle_ar[curr_set_id][particle_id]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase UpdateType::Compositional:\n\t\t\t\t\tssm.compositionalAutoRegression1(perturbed_state, perturbed_ar,\n\t\t\t\t\t\tparticle_states[curr_set_id][particle_id], particle_ar[curr_set_id][particle_id]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tparticle_ar[curr_set_id][particle_id] = perturbed_ar;\n\t\t\t\tbreak;\n\t\t\tcase DynamicModel::RandomWalk:\n\t\t\t\tswitch(params.update_type){\n\t\t\t\tcase UpdateType::Additive:\n\t\t\t\t\tssm.additiveRandomWalk(perturbed_state, particle_states[curr_set_id][particle_id]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase UpdateType::Compositional:\n\t\t\t\t\tssm.compositionalRandomWalk(perturbed_state, particle_states[curr_set_id][particle_id]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\r\n\t\t\tparticle_states[curr_set_id][particle_id] = perturbed_state;\r\n\r\n\t\t\tssm.setState(particle_states[curr_set_id][particle_id]);\r\n\t\t\tam.updatePixVals(ssm.getPts());\r\n\t\t\tam.updateSimilarity(false);\r\n\r\n\t\t\t// a positive number that measures the dissimilarity between the\r\n\t\t\t// template and the patch corresponding to this particle\r\n\t\t\tdouble measuremnt_val = max_similarity - am.getSimilarity();\r\n\r\n\t\t\t// convert this dissimilarity to a likelihood proportional to the dissimilarity\r\n\t\t\tswitch(params.likelihood_func){\n\t\t\tcase LikelihoodFunc::AM:\n\t\t\t\tmeasurement_likelihood = am.getLikelihood();\r\n\t\t\t\tbreak;\n\t\t\tcase LikelihoodFunc::Gaussian:\n\t\t\t\tmeasurement_likelihood = measurement_factor * exp(-0.5*measuremnt_val / params.measurement_sigma);\r\n\t\t\t\tbreak;\n\t\t\tcase LikelihoodFunc::Reciprocal:\n\t\t\t\tmeasurement_likelihood = 1.0 / (1.0 + measuremnt_val);\r\n\t\t\t\tbreak;\n\t\t\t}\r\n\t\t\tif(params.show_particles){\n\t\t\t\tcv::Point2d corners[4];\n\t\t\t\tssm.getCorners(corners);\n\t\t\t\tutils::drawCorners(curr_img_uchar, corners,\n\t\t\t\t\tcv::Scalar(0, 0, 255), cv::format(\"%d: %5.3e\", particle_id + 1, measurement_likelihood));\n\t\t\t\t//printf(\"measurement_likelihood: %e\\n\", measurement_likelihood);\n\t\t\t\tif((particle_id + 1) % params.show_particles == 0){\n\t\t\t\t\tcv::imshow(\"Particles\", curr_img_uchar);\n\t\t\t\t\tint key = cv::waitKey(1 - pause_after_show);\n\t\t\t\t\tif(key == 27){\n\t\t\t\t\t\tcv::destroyWindow(\"Particles\");\n\t\t\t\t\t\tparams.show_particles = 0;\n\t\t\t\t\t} else if(key == 32){\n\t\t\t\t\t\tpause_after_show = 1 - pause_after_show;\n\t\t\t\t\t}\n\t\t\t\t\tam.getCurrImg().convertTo(curr_img_uchar, CV_8UC1);\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tparticle_wts[particle_id] = measurement_likelihood;\r\n\t\t\tif(particle_id > 0){\n\t\t\t\tparticle_cum_wts[particle_id] = particle_wts[particle_id] + particle_cum_wts[particle_id - 1];\r\n\t\t\t} else{\n\t\t\t\tparticle_cum_wts[particle_id] = particle_wts[particle_id];\n\t\t\t}\r\n\t\t\tif(particle_wts[particle_id] >= max_wt){\r\n\t\t\t\tmax_wt = particle_wts[particle_id];\r\n\t\t\t\tmax_wt_id = particle_id;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(params.debug_mode){\n\t\t\tutils::printMatrixToFile(particle_wts.transpose(), \"particle_wts\", log_fname, \"%e\");\r\n\t\t\tutils::printMatrixToFile(particle_cum_wts.transpose(), \"particle_cum_wts\", log_fname, \"%e\");\n\t\t}\r\n\t\tbool perform_resampling = true;\r\n\t\tif(enable_adaptive_resampling){\r\n\t\t\tdouble n_eff_particles = (particle_wts / particle_wts.sum()).squaredNorm();\r\n\t\t\tn_eff_particles = n_eff_particles == 0 ? 0 :\r\n\t\t\t\t1.0 / n_eff_particles;\r\n\t\t\tif(n_eff_particles > min_eff_particles){\r\n\t\t\t\tperform_resampling = false;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(perform_resampling){\r\n\t\t\tswitch(params.resampling_type){\n\t\t\tcase ResamplingType::None:\n\t\t\t\tbreak;\n\t\t\tcase ResamplingType::BinaryMultinomial:\n\t\t\t\tbinaryMultinomialResampling();\n\t\t\t\tbreak;\n\t\t\tcase ResamplingType::LinearMultinomial:\n\t\t\t\tlinearMultinomialResampling();\n\t\t\t\tbreak;\n\t\t\tcase ResamplingType::Residual:\n\t\t\t\tresidualResampling();\n\t\t\t\tbreak;\n\t\t\t}\r\n\t\t}\r\n\t\tswitch(params.mean_type){\r\n\t\tcase MeanType::None:\r\n\t\t\t//! set the SSM state to that of the highest weighted particle\r\n\t\t\tssm.setState(particle_states[curr_set_id][max_wt_id]);\r\n\t\t\tbreak;\r\n\t\tcase MeanType::SSM:\r\n\t\t\tssm.estimateMeanOfSamples(mean_state, particle_states[curr_set_id], params.n_particles);\r\n\t\t\tssm.setState(mean_state);\r\n\t\t\tbreak;\r\n\t\tcase MeanType::Corners:\r\n\t\t\tupdateMeanCorners();\r\n\t\t\tssm.setCorners(mean_corners);\r\n\t\t}\r\n\r\n\t\tdouble update_norm = (prev_corners - ssm.getCorners()).squaredNorm();\r\n\t\tprev_corners = ssm.getCorners();\r\n\t\tif(update_norm < params.epsilon){\n\t\t\tif(params.debug_mode){\n\t\t\t\tprintf(\"n_iters: %d\\n\", i + 1);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tam.clearFirstIter();\r\n\t}\r\n\tif(params.reset_to_mean){\n\t\tinitializeParticles();\n\t}\r\n\tif(params.enable_learning){\n\t\tam.updateModel(ssm.getPts());\n\t}\r\n\tssm.getCorners(cv_corners_mat);\r\n}\r\n\r\n// uses binary search to find the particle with the smallest\r\n// index whose cumulative weight is greater than the provided\r\n// random number supposedly drawn from a uniform distribution \r\n// between 0 and max cumulative weight\r\ntemplate <class AM, class SSM>\nvoid PF<AM, SSM >::binaryMultinomialResampling(){\r\n\t// change the range of the uniform distribution used for resampling instead of normalizing the weights\r\n\t//resample_dist.param(ResampleDistParamT(0, particle_cum_wts[params.n_particles - 1]));\n\n\t// normalize the cumulative weights and leave the uniform distribution range to (0, 1]\n\tparticle_cum_wts /= particle_cum_wts[params.n_particles - 1];\n\tif(params.debug_mode){\n\t\tutils::printMatrixToFile(particle_cum_wts.transpose(), \"normalized particle_cum_wts\", log_fname, \"%e\");\n\t}\n\tdouble max_wt = std::numeric_limits<double>::lowest();\r\n\tfor(int particle_id = 0; particle_id < params.n_particles; ++particle_id){\n\t\tdouble uniform_rand_num = resample_dist(resample_gen);\n\t\tint lower_id = 0, upper_id = params.n_particles - 1;\r\n\t\tint resample_id = (lower_id + upper_id) / 2;\r\n\t\tint iter_id = 0;\r\n\t\twhile(upper_id > lower_id){\r\n\t\t\tif(particle_cum_wts[resample_id] >= uniform_rand_num){\r\n\t\t\t\tupper_id = resample_id;\r\n\t\t\t} else{\r\n\t\t\t\tlower_id = resample_id + 1;\r\n\t\t\t}\r\n\t\t\tresample_id = (lower_id + upper_id) / 2;\r\n\t\t\tif(params.debug_mode){\n\t\t\t\tprintf(\"iter_id: %d upper_id: %d lower_id: %d resample_id: %d\\n\", iter_id, upper_id,\n\t\t\t\t\tlower_id, resample_id);\n\t\t\t}\n\t\t\t++iter_id;\r\n\t\t}\n\n\t\tif(params.debug_mode){\n\t\t\tprintf(\"particle_id: %d resample_id: %d\\n\", particle_id, resample_id);\n\t\t\tresample_ids[particle_id] = resample_id;\n\t\t\tuniform_rand_nums[particle_id] = uniform_rand_num;\n\t\t}\n\n\t\t// place the resampled particle states into the other set so as not to overwrite the current one\n\t\tparticle_states[1 - curr_set_id][particle_id] = particle_states[curr_set_id][resample_id];\n\t\tparticle_ar[1 - curr_set_id][particle_id] = particle_ar[curr_set_id][resample_id];\n\t\tif(particle_wts[resample_id] >= max_wt){\r\n\t\t\tmax_wt = particle_wts[resample_id];\r\n\t\t\tmax_wt_id = particle_id;\r\n\t\t}\n\t}\n\tif(params.debug_mode){\n\t\tutils::printMatrixToFile(resample_ids.transpose(), \"resample_ids\", log_fname, \"%d\");\n\t\tutils::printMatrixToFile(uniform_rand_nums.transpose(), \"uniform_rand_nums\", log_fname, \"%e\");\n\t}\n\t// make the other particle set the current one\n\tcurr_set_id = 1 - curr_set_id;\r\n}\r\n\r\ntemplate <class AM, class SSM>\nvoid PF<AM, SSM >::linearMultinomialResampling(){\r\n\t// change the range of the uniform distribution used for resampling instead of normalizing the weights\r\n\t//resample_dist.param(ResampleDistParamT(0, particle_cum_wts[params.n_particles - 1]));\n\n\t// normalize the cumulative weights and leave the uniform distribution range to (0, 1]\n\tparticle_cum_wts /= particle_cum_wts[params.n_particles - 1];\n\tif(params.debug_mode){\n\t\tutils::printMatrix(particle_cum_wts.transpose(), \"normalized particle_cum_wts\");\r\n\t}\n\tdouble max_wt = std::numeric_limits<double>::lowest();\r\n\tfor(int particle_id = 0; particle_id < params.n_particles; ++particle_id){\n\t\tdouble uniform_rand_num = resample_dist(resample_gen);\n\t\tint resample_id = 0;\r\n\t\twhile(particle_cum_wts[resample_id] < uniform_rand_num){ ++resample_id; }\r\n\n\t\tif(params.debug_mode){\n\t\t\tutils::printScalar(uniform_rand_num, \"uniform_rand_num\");\n\t\t\tutils::printScalar(resample_id, \"resample_id\", \"%d\");\n\t\t}\n\n\t\t// place the resampled particle states into the other set so as not to overwrite the current one\n\t\tparticle_states[1 - curr_set_id][particle_id] = particle_states[curr_set_id][resample_id];\n\t\tparticle_ar[1 - curr_set_id][particle_id] = particle_ar[curr_set_id][resample_id];\n\t\tif(particle_wts[resample_id] >= max_wt){\r\n\t\t\tmax_wt = particle_wts[resample_id];\r\n\t\t\tmax_wt_id = particle_id;\r\n\t\t}\n\t}\n\t// make the other particle set the current one\n\tcurr_set_id = 1 - curr_set_id;\r\n}\r\n\r\n\r\n\r\ntemplate <class AM, class SSM>\nvoid PF<AM, SSM >::residualResampling() {\n\t// normalize the weights\n\tparticle_wts /= particle_cum_wts[params.n_particles - 1];\n\t// vector of particle indies\n\tVectorXi particle_idx = VectorXi::LinSpaced(params.n_particles, 0, params.n_particles - 1);\n\tif(params.debug_mode){\n\t\tutils::printMatrix(particle_wts.transpose(), \"normalized particle_wts\");\r\n\t\tutils::printMatrix(particle_idx.transpose(), \"particle_idx\", \"%d\");\r\n\t}\n\t// sort, with highest weight first\n\tstd::sort(particle_idx.data(), particle_idx.data() + params.n_particles - 1,\n\t\t[&](int a, int b){\n\t\treturn particle_wts[a] > particle_wts[b];\n\t});\n\tif(params.debug_mode){\n\t\tutils::printMatrix(particle_idx.transpose(), \"sorted particle_idx\", \"%d\");\n\t}\n\n\t// now we append\t\n\tint particles_found = 0;\n\tfor(int particle_id = 0; particle_id < params.n_particles; ++particle_id) {\n\t\tint resample_id = particle_idx[particle_id];\n\t\tint particle_copies = static_cast<int>(round(particle_wts[resample_id] * params.n_particles));\n\t\tfor(int copy_id = 0; copy_id < particle_copies; ++copy_id) {\n\t\t\tparticle_states[1 - curr_set_id][particles_found] = particle_states[curr_set_id][resample_id];\n\t\t\tparticle_ar[1 - curr_set_id][particles_found] = particle_ar[curr_set_id][resample_id];\n\t\t\tif(++particles_found == params.n_particles) { break; }\n\t\t}\n\t\tif(particles_found == params.n_particles) { break; }\n\t}\n\tint resample_id = particle_idx[0];\n\tfor(int particle_id = particles_found; particle_id < params.n_particles; ++particle_id) {\n\t\t// duplicate particle with highest weight to get exactly same number again\n\t\tparticle_states[1 - curr_set_id][particle_id] = particle_states[curr_set_id][resample_id];\n\t\tparticle_ar[1 - curr_set_id][particle_id] = particle_ar[curr_set_id][resample_id];\n\t}\n\tcurr_set_id = 1 - curr_set_id;\n\tmax_wt_id = particle_idx[0];\r\n}\r\n\r\ntemplate <class AM, class SSM>\nvoid PF<AM, SSM >::updateMeanCorners(){\r\n\tmean_corners.setZero();\r\n\tfor(int particle_id = 0; particle_id < params.n_particles; ++particle_id) {\r\n\t\t// compute running average of corners corresponding to the resampled particle states\r\n\t\tssm.setState(particle_states[curr_set_id][particle_id]);\r\n\t\tmean_corners += (ssm.getCorners() - mean_corners) / (particle_id + 1);\r\n\t}\r\n}\r\ntemplate <class AM, class SSM>\nvoid PF<AM, SSM >::setRegion(const cv::Mat& corners){\r\n\tssm.setCorners(corners);\r\n\tssm.getCorners(cv_corners_mat);\r\n\tinitializeParticles();\r\n}\r\n\r\n_MTF_END_NAMESPACE\r\n\r\n#ifndef HEADER_ONLY_MODE\r\n#include \"mtf/Macros/register.h\"\n_REGISTER_TRACKERS(PF);\n#endif", "meta": {"hexsha": "7c8d07f8b36f2924b1b659eb39651ab488a02b82", "size": 18318, "ext": "cc", "lang": "C++", "max_stars_repo_path": "SM/src/PF.cc", "max_stars_repo_name": "abhineet123/MTF", "max_stars_repo_head_hexsha": "6cb45c88d924fb2659696c3375bd25c683802621", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2016-12-11T00:34:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T23:03:40.000Z", "max_issues_repo_path": "SM/src/PF.cc", "max_issues_repo_name": "siqiyan/MTF", "max_issues_repo_head_hexsha": "9a76388c907755448bb7223420fe74349130f636", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2017-09-04T06:27:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T19:07:23.000Z", "max_forks_repo_path": "SM/src/PF.cc", "max_forks_repo_name": "siqiyan/MTF", "max_forks_repo_head_hexsha": "9a76388c907755448bb7223420fe74349130f636", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2017-02-19T02:12:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-23T03:47:55.000Z", "avg_line_length": 37.1561866126, "max_line_length": 105, "alphanum_fraction": 0.7220220548, "num_tokens": 4840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721305, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5072705823088468}}
{"text": "//\n//  cal_slip_sliprate_angle.hpp\n//  hybrid_fem_bie\n//\n//  Created by Max on 2/8/18.\n//\n//\n\n#ifndef cal_slip_sliprate_angle_hpp\n#define cal_slip_sliprate_angle_hpp\n\n#include <stdio.h>\n#include <Eigen/Eigen>\n#include \"maplocal.hpp\"\n\nusing namespace Eigen;\nvoid cal_slip_slip_rate_angle(VectorXd &u_n, VectorXd &v_n, ArrayXi &top_surf_index, ArrayXi &bot_surf_index, int Ndofn, int nx, ArrayXd &delt_u_n, ArrayXd &delt_v_n,double fault_angle);\n\n#endif /* cal_slip_sliprate_angle_hpp */\n", "meta": {"hexsha": "adb62d04356d4dcb7412792afd8b344d8eb2880a", "size": 486, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/fem/cal_slip_sliprate_angle.hpp", "max_stars_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_stars_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T19:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:12:57.000Z", "max_issues_repo_path": "src/fem/cal_slip_sliprate_angle.hpp", "max_issues_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_issues_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fem/cal_slip_sliprate_angle.hpp", "max_forks_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_forks_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-07T07:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T07:23:58.000Z", "avg_line_length": 24.3, "max_line_length": 186, "alphanum_fraction": 0.7716049383, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5072705754932217}}
{"text": "#include \"Camera.h\"\n\n#include <Eigen>\n#include <vector>\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <math.h>\n#include \"Shape.h\"\n#include \"Intersection.h\"\n\n#define HEIGHT 600\n#define WIDTH 800\n#define FLENGTH 1.0\n#define PWIDTH 4.0\n#define PHEIGHT 3.0\n#define MAXRECDEPTH 4\n#define INF 100000000\n\nusing namespace Eigen;\nusing namespace std;\n\nfloat clamp(float a, float b, float c){\n    if (c < a)\n        return a;\n    else if (c > b)\n        return b;\n    else\n        return c;\n}\n\nVector3f getr(Vector3f sray, Vector3f norm){\n    Vector3f t2 = sray - 2*(sray.dot(norm)) * norm;\n    return t2;\n}\n\n//Based on Scratchapixel version\nVector3f getfrac(Vector3f incom, Vector3f norm, float indx){\n    float cosi = clamp(-1, 1, incom.dot(norm));\n    float et = 1, ea = indx;\n    Vector3f n = norm;\n    if (cosi < 0)\n        cosi = -cosi;\n    else{\n        swap(et, ea);\n        n = -norm;\n    }\n    float eta = ea/et;\n    float k = 1 - eta*eta * (1-cosi * cosi);\n    if (k < 0){ //total refrac\n        return getr(incom, -norm);\n    }\n    else{\n        return eta * incom + (eta * cosi - sqrt(k)) * n;\n    }\n}\n\nCamera::Camera(Vector3f la, Vector3f u,\n               Vector3f p)\n{\n    lookat = la;\n    up = u;\n    pos = p;\n    lookat.normalize();\n    up.normalize();\n    pos.normalize();\n    //col major\n    Vector3f matn = pos - lookat;\n    matn.normalize();\n    Vector3f matu = up.cross(matn);\n    matu.normalize();\n    Vector3f matv = matn.cross(matu);\n    this->tra << matu(0), matv(0), matn(0), 0.0f,\n                 matu(1), matv(1), matn(1), 0.0f,\n                 matu(2), matv(2), matn(2), 0.0f,\n                -(pos.dot(matu)), -(pos.dot(matv)),\n                -(pos.dot(matn)), 1.0;\n\n\n}\n\nVector3f getrtarg(Vector3f illum, float aol, float ldmax){\n    Vector3f cs = aol * illum;\n    float rr, gr, br;\n    rr = cs[0] / (1 + cs[0]);\n    gr = cs[1] / (1 + cs[1]);\n    br = cs[2] / (1 + cs[2]);\n\n    float rt,gt,bt;\n    rt = rr * ldmax;\n    gt = gr * ldmax;\n    bt = br * ldmax;\n\n    Vector3f targ;\n    targ << rt, gt, bt;\n    return targ;\n\n}\n\nfloat getlogavg(vector<float> illlist){\n    float lsum = 0;\n    float delta = 0.00001;\n    for (float f : illlist){\n        lsum += log(delta + f);\n    }\n    return exp(lsum / ((float)HEIGHT * WIDTH));\n\n}\n\n//go from RGB to Illuminance\n//CRT formula\nfloat toill(Vector3f rgb){\n    return abs(.27*rgb[0] + .67*rgb[1]+.06*rgb[2]);\n}\n\nstd::vector<Vector3f> torgb(vector<Vector3f> lum, float ldmax, char whichTR){\n        vector<float> illum;\n        for (Vector3f vf : lum){\n            illum.push_back(toill(vf));\n        }\n        float lwa = getlogavg(illum);\n    if (whichTR == 'w'){\n        float powa = pow(lwa,.4);\n        float ldterm = pow(ldmax/2, 0.4);\n        float brackterm = (1.219 + ldterm) / (1.219 + powa);\n        float sf = pow(brackterm,2.5);\n        vector<Vector3f> trd;\n        for (Vector3f rgb : lum){\n            trd.push_back(sf * rgb);\n        }\n        return trd;\n    }\n    else{\n        float aol = .18/lwa;\n        vector<Vector3f> targv;\n        for (Vector3f vl : lum){\n            targv.push_back(getrtarg(vl,aol,ldmax));\n        }\n        return targv;\n    }\n}\n\nvoid writetofile(vector<Vector3f> image, float ldmax)\n{\n    ofstream filewtt;\n    filewtt.open(\"output.ppm\");\n    filewtt << \"P3\\n\" << WIDTH << \" \";\n    filewtt << HEIGHT << \"\\n\";\n    filewtt << 255 << \"\\n\";\n    for (Vector3f pix : image){\n        int r = abs((int) (pix[0] / ldmax) * 255);\n        int g = abs((int) (pix[1] / ldmax) * 255);\n        int b = abs((int) (pix[2] / ldmax) * 255);\n        filewtt << r << \" \" << g << \" \";\n        filewtt << b << \" \\n\";\n    }\n    filewtt.close();\n\n}\n\nCamera::~Camera()\n{\n    //dtor\n}\n\nVector3f Camera::getcolor(Ray * r, int recdepth){\n    vector<Shape *> clones = wld->getshapes();\n    vector<Light *> lits = wld->getlits();\n    Vector3f colr;\n    bool foundcol = false;\n    float newt;\n    float champt = INF;\n    Shape * coll;\n    for (Shape * s : clones){\n        if (s->checkcollision(r,newt)){\n            foundcol = true;\n            if (newt < champt){\n                champt = newt;\n                coll = s;\n            }\n        }\n        }\n        if (!foundcol){\n            Vector3f dflt;\n            dflt << 0.0, 30, 70;\n            colr = dflt;\n        }\n        else\n        {\n            //colr = coll->getcolor();\n            Vector3f colpt = r->getpos() + r->getdir().normalized() * champt;\n            Vector3f SS =  lits.at(0)->getpos() - colpt;\n            SS.normalize();\n            Ray * shadow = new Ray(colpt,SS);\n            bool seelight = true;\n            float dummyt; //if dist = 0, hitting self\n            for (Shape * s : clones){\n                if (s != coll){\n                    if (s->checkcollision(shadow, dummyt)){\n                        if (dummyt != 0){\n                            seelight = false;\n                            //ambi\n                            Vector3f blk;\n                            blk << 0.1,0.1,0.1;\n                            colr = blk;\n                        }\n                    }\n                }\n            }\n            if (seelight){\n                Vector3f VV = r->getdir();\n                VV.normalize();\n                Vector3f NN = coll->getnorm(colpt);\n                NN.normalize();\n                Vector3f RR = getr(VV,NN);\n                Intersection * is = new Intersection();\n                is->pt = colpt;\n                is->incom = SS;\n                is->norm = NN;\n                is->reflex = RR;\n                is->litlist = lits;\n                colr = coll->getcolor(is);\n                if (recdepth < MAXRECDEPTH){\n                    if (coll->kr > 0){\n                        Vector3f refr = getr(VV,NN);\n                        refr.normalize();\n                        Ray * nr = new Ray(colpt, refr);\n                        colr += coll->kr * this->getcolor(nr, recdepth + 1);\n                    }\n                    if (coll->kt > 0){\n                        Vector3f frac = getfrac(VV, NN, 1.01);\n                        frac.normalize();\n                        Ray * fr = new Ray(colpt, frac);\n                        colr += coll->kt * this->getcolor(fr, recdepth + 1);\n                    }\n                }\n            }\n        }\n        return colr;\n}\n\nvoid Camera::captureworld(World * wld){\n\n    //Yo dawg...\n    vector<Vector3f>image;\n    this->wld = wld;\n    float pixh = PHEIGHT / HEIGHT;\n    float pixw = PWIDTH / WIDTH;\n    float tx = -PWIDTH/2;\n    float ty = PHEIGHT/2;\n\n    Vector3f p;\n    p << 0.0, 0.0, 0.0;\n\n    //Generate rays and check\n    for (int i = 0; i < HEIGHT; i++){\n        float ypx = ty - ((.5 + float(i)) * pixh);\n        for (int c = 0; c < WIDTH; c++){\n                float xpx =  tx + ((.5 + float(c)) * pixw);\n                Vector3f raypos;\n                raypos << xpx, ypx, FLENGTH;\n                raypos.normalize();\n                Ray * pxr = new Ray(p,raypos);\n                Vector3f colr = this->getcolor(pxr,1);\n                image.push_back(colr);\n\n        }\n    }\n    float ldmax = 1;\n    vector<Vector3f> srgb = torgb(image, ldmax, 'w');\n    writetofile(srgb,ldmax);\n}\n", "meta": {"hexsha": "690193643fbc78fd64de6ff932f4fdfee769542f", "size": 7161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "711RayTracer/src/Camera.cpp", "max_stars_repo_name": "kmgreg/611RayTracer", "max_stars_repo_head_hexsha": "211d601d6d525c8c267df9033ad92b9f6a5ea461", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "711RayTracer/src/Camera.cpp", "max_issues_repo_name": "kmgreg/611RayTracer", "max_issues_repo_head_hexsha": "211d601d6d525c8c267df9033ad92b9f6a5ea461", "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": "711RayTracer/src/Camera.cpp", "max_forks_repo_name": "kmgreg/611RayTracer", "max_forks_repo_head_hexsha": "211d601d6d525c8c267df9033ad92b9f6a5ea461", "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": 26.2307692308, "max_line_length": 77, "alphanum_fraction": 0.4683703393, "num_tokens": 2088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5072705754932216}}
{"text": "#pragma once\n\n#include \"Camera.hh\"\n#include \"../util.hh\"\n#include <Eigen/Geometry>\n\nnamespace kt84 {\n\nstruct CameraUpright : public Camera {\n    double r, theta, phi;\n    \n    CameraUpright()\n        : r(1)\n        , theta(0)\n        , phi(0)\n    {}\n    \n    void init(const Eigen::Vector3d& eye, const Eigen::Vector3d& center_, const Eigen::Vector3d& up) {\n        center = center_;\n        Eigen::Vector3d v = eye - center;\n        r = v.norm();\n        double r_xz = std::sqrt(v.x() * v.x() + v.z() * v.z());\n        \n        if (r_xz == 0) {\n            bool is_y_positive = v.y() > 0;\n            theta = std::atan2(up.x(), up.z()) + (is_y_positive ? util::pi() : 0);\n            phi   = (is_y_positive ? 0.5 : -0.5) * util::pi();\n        } else {\n            theta = std::atan2(v.x(), v.z());\n            phi   = std::atan(v.y() / r_xz);\n        }\n        \n        if (up.y() < 0) {\n            theta += util::pi();\n            phi    = util::pi() - phi;\n        }\n    }\n    \n    Eigen::Vector3d get_up() const {\n        return Eigen::Vector3d(\n            -sin(theta) * sin(phi),\n            cos(phi),\n            -cos(theta) * sin(phi));\n    }\n    \n    Eigen::Vector3d get_eye() const {\n        return center + r * Eigen::Vector3d(\n            sin(theta) * cos(phi),\n            sin(phi),\n            cos(theta) * cos(phi));\n    }\n    \n    void mouse_move(int x, int y) {\n        if (auto_flip_y) y = height - y;\n        const int viewport_size = (width + height) / 2;\n        \n        if (drag_mode == DragMode::NONE)\n            return;\n        \n        Eigen::Vector2i pos(x, y);\n        switch (drag_mode) {\n        case DragMode::ROTATE:\n            {\n                theta -= (2 * util::pi() * (pos.x() - prev_pos.x())) / viewport_size;\n                phi   += (2 * util::pi() * (pos.y() - prev_pos.y())) / viewport_size;\n            }\n            break;\n        case DragMode::PAN:\n            {\n                Eigen::Vector3d right(cos(theta), 0, -sin(theta));\n                center -= (r * (pos.x() - prev_pos.x()) / viewport_size) * right;\n                center += (r * (pos.y() - prev_pos.y()) / viewport_size) * get_up();\n            }\n            break;\n        case DragMode::ZOOM:\n            {\n                r *= 1 - (pos.x() - prev_pos.x() + pos.y() - prev_pos.y()) / static_cast<double>(viewport_size);\n            }\n            break;\n        }\n        prev_pos = pos;\n    }\n    \n    void update_center(const Eigen::Vector3d& center_new) {\n        // find the point closest to center_new between center and eye. update center and r accordingly.\n        // center + t * center_to_eye = center_new\n        auto d = center_to_eye();\n        double t = d.dot(center_new - center) / d.squaredNorm();\n        center += t * d;\n        r *= 1 - t;\n    }\n    void snap_to_canonical() {\n        auto snap_to_pi_2 = [] (double& radian) {\n            while (radian < 0)\n                radian += 2 * util::pi();\n            \n            double t = radian / (0.5 * util::pi());\n            int n = static_cast<int>(t);\n            if (t - n > 0.5)\n                ++n;\n            \n            radian = n * 0.5 * util::pi();\n        };\n        \n        snap_to_pi_2(theta);\n        snap_to_pi_2(phi  );\n    }\n};\n\n}\n", "meta": {"hexsha": "987c1221bf2238fa14b9e90d92caca28c690c24e", "size": 3235, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/geometry/CameraUpright.hh", "max_stars_repo_name": "honoriocassiano/skbar", "max_stars_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kt84/geometry/CameraUpright.hh", "max_issues_repo_name": "honoriocassiano/skbar", "max_issues_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T12:16:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T12:21:41.000Z", "max_forks_repo_path": "src/kt84/geometry/CameraUpright.hh", "max_forks_repo_name": "honoriocassiano/skbar", "max_forks_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1441441441, "max_line_length": 112, "alphanum_fraction": 0.4476043277, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5072705754932215}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_STUDENT_T_LCCDF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_STUDENT_T_LCCDF_HPP\n\n#include <stan/math/prim/scal/meta/is_constant_struct.hpp>\n#include <stan/math/prim/scal/meta/partials_return_type.hpp>\n#include <stan/math/prim/scal/meta/operands_and_partials.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/fun/size_zero.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/fun/square.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/fun/lbeta.hpp>\n#include <stan/math/prim/scal/fun/lgamma.hpp>\n#include <stan/math/prim/scal/fun/digamma.hpp>\n#include <stan/math/prim/scal/meta/length.hpp>\n#include <stan/math/prim/scal/fun/grad_reg_inc_beta.hpp>\n#include <stan/math/prim/scal/fun/inc_beta.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>\n#include <stan/math/prim/scal/meta/VectorBuilder.hpp>\n#include <boost/random/student_t_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <limits>\n\nnamespace stan {\nnamespace math {\n\ntemplate <typename T_y, typename T_dof, typename T_loc, typename T_scale>\ntypename return_type<T_y, T_dof, T_loc, T_scale>::type student_t_lccdf(\n    const T_y& y, const T_dof& nu, const T_loc& mu, const T_scale& sigma) {\n  typedef typename stan::partials_return_type<T_y, T_dof, T_loc, T_scale>::type\n      T_partials_return;\n\n  if (size_zero(y, nu, mu, sigma))\n    return 0.0;\n\n  static const char* function = \"student_t_lccdf\";\n\n  using std::exp;\n\n  T_partials_return P(0.0);\n\n  check_not_nan(function, \"Random variable\", y);\n  check_positive_finite(function, \"Degrees of freedom parameter\", nu);\n  check_finite(function, \"Location parameter\", mu);\n  check_positive_finite(function, \"Scale parameter\", sigma);\n\n  scalar_seq_view<T_y> y_vec(y);\n  scalar_seq_view<T_dof> nu_vec(nu);\n  scalar_seq_view<T_loc> mu_vec(mu);\n  scalar_seq_view<T_scale> sigma_vec(sigma);\n  size_t N = max_size(y, nu, mu, sigma);\n\n  operands_and_partials<T_y, T_dof, T_loc, T_scale> ops_partials(y, nu, mu,\n                                                                 sigma);\n\n  // Explicit return for extreme values\n  // The gradients are technically ill-defined, but treated as zero\n  for (size_t i = 0; i < stan::length(y); i++) {\n    if (value_of(y_vec[i]) == -std::numeric_limits<double>::infinity())\n      return ops_partials.build(0.0);\n  }\n\n  using std::exp;\n  using std::log;\n  using std::pow;\n\n  T_partials_return digammaHalf = 0;\n\n  VectorBuilder<!is_constant_struct<T_dof>::value, T_partials_return, T_dof>\n      digamma_vec(stan::length(nu));\n  VectorBuilder<!is_constant_struct<T_dof>::value, T_partials_return, T_dof>\n      digammaNu_vec(stan::length(nu));\n  VectorBuilder<!is_constant_struct<T_dof>::value, T_partials_return, T_dof>\n      digammaNuPlusHalf_vec(stan::length(nu));\n\n  if (!is_constant_struct<T_dof>::value) {\n    digammaHalf = digamma(0.5);\n\n    for (size_t i = 0; i < stan::length(nu); i++) {\n      const T_partials_return nu_dbl = value_of(nu_vec[i]);\n\n      digammaNu_vec[i] = digamma(0.5 * nu_dbl);\n      digammaNuPlusHalf_vec[i] = digamma(0.5 + 0.5 * nu_dbl);\n    }\n  }\n\n  for (size_t n = 0; n < N; n++) {\n    // Explicit results for extreme values\n    // The gradients are technically ill-defined, but treated as zero\n    if (value_of(y_vec[n]) == std::numeric_limits<double>::infinity()) {\n      return ops_partials.build(negative_infinity());\n    }\n\n    const T_partials_return sigma_inv = 1.0 / value_of(sigma_vec[n]);\n    const T_partials_return t\n        = (value_of(y_vec[n]) - value_of(mu_vec[n])) * sigma_inv;\n    const T_partials_return nu_dbl = value_of(nu_vec[n]);\n    const T_partials_return q = nu_dbl / (t * t);\n    const T_partials_return r = 1.0 / (1.0 + q);\n    const T_partials_return J = 2 * r * r * q / t;\n    const T_partials_return betaNuHalf = exp(lbeta(0.5, 0.5 * nu_dbl));\n    T_partials_return zJacobian = t > 0 ? -0.5 : 0.5;\n\n    if (q < 2) {\n      T_partials_return z\n          = inc_beta(0.5 * nu_dbl, (T_partials_return)0.5, 1.0 - r);\n      const T_partials_return Pn = t > 0 ? 0.5 * z : 1.0 - 0.5 * z;\n      const T_partials_return d_ibeta\n          = pow(r, -0.5) * pow(1.0 - r, 0.5 * nu_dbl - 1) / betaNuHalf;\n\n      P += log(Pn);\n\n      if (!is_constant_struct<T_y>::value)\n        ops_partials.edge1_.partials_[n]\n            += zJacobian * d_ibeta * J * sigma_inv / Pn;\n\n      if (!is_constant_struct<T_dof>::value) {\n        T_partials_return g1 = 0;\n        T_partials_return g2 = 0;\n\n        grad_reg_inc_beta(g1, g2, 0.5 * nu_dbl, (T_partials_return)0.5, 1.0 - r,\n                          digammaNu_vec[n], digammaHalf,\n                          digammaNuPlusHalf_vec[n], betaNuHalf);\n\n        ops_partials.edge2_.partials_[n]\n            -= zJacobian * (d_ibeta * (r / t) * (r / t) + 0.5 * g1) / Pn;\n      }\n\n      if (!is_constant_struct<T_loc>::value)\n        ops_partials.edge3_.partials_[n]\n            -= zJacobian * d_ibeta * J * sigma_inv / Pn;\n      if (!is_constant_struct<T_scale>::value)\n        ops_partials.edge4_.partials_[n]\n            -= zJacobian * d_ibeta * J * sigma_inv * t / Pn;\n\n    } else {\n      T_partials_return z\n          = 1.0 - inc_beta((T_partials_return)0.5, 0.5 * nu_dbl, r);\n      zJacobian *= -1;\n\n      const T_partials_return Pn = t > 0 ? 0.5 * z : 1.0 - 0.5 * z;\n\n      T_partials_return d_ibeta\n          = pow(1.0 - r, 0.5 * nu_dbl - 1) * pow(r, -0.5) / betaNuHalf;\n\n      P += log(Pn);\n\n      if (!is_constant_struct<T_y>::value)\n        ops_partials.edge1_.partials_[n]\n            -= zJacobian * d_ibeta * J * sigma_inv / Pn;\n\n      if (!is_constant_struct<T_dof>::value) {\n        T_partials_return g1 = 0;\n        T_partials_return g2 = 0;\n\n        grad_reg_inc_beta(g1, g2, (T_partials_return)0.5, 0.5 * nu_dbl, r,\n                          digammaHalf, digammaNu_vec[n],\n                          digammaNuPlusHalf_vec[n], betaNuHalf);\n\n        ops_partials.edge2_.partials_[n]\n            -= zJacobian * (-d_ibeta * (r / t) * (r / t) + 0.5 * g2) / Pn;\n      }\n\n      if (!is_constant_struct<T_loc>::value)\n        ops_partials.edge3_.partials_[n]\n            += zJacobian * d_ibeta * J * sigma_inv / Pn;\n      if (!is_constant_struct<T_scale>::value)\n        ops_partials.edge4_.partials_[n]\n            += zJacobian * d_ibeta * J * sigma_inv * t / Pn;\n    }\n  }\n  return ops_partials.build(P);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "b4dd87d91a4c5faf0599bcae1841433093103980", "size": 6672, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/student_t_lccdf.hpp", "max_stars_repo_name": "csetraynor/Torsten", "max_stars_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "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/stan/math/prim/scal/prob/student_t_lccdf.hpp", "max_issues_repo_name": "csetraynor/Torsten", "max_issues_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/stan/math/prim/scal/prob/student_t_lccdf.hpp", "max_forks_repo_name": "csetraynor/Torsten", "max_forks_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "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.6593406593, "max_line_length": 80, "alphanum_fraction": 0.6521282974, "num_tokens": 2031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5072705686775962}}
{"text": "/*-----------------------------------------------------------------------------+\nInterval Container Library\nAuthor: Joachim Faulhaber\nCopyright (c) 2007-2009: Joachim Faulhaber\nCopyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n/** Example std_copy.cpp \\file std_copy.cpp\n    \\brief Fill interval containers using std::copy.\n\n    Example std_copy shows how algorithm std::copy can be used to\n    fill interval containers from other std::containers and how copying\n    to interval containers differs from other uses of std::copy.\n\n    \\include std_copy_/std_copy.cpp\n*/\n//[example_std_copy\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <boost/icl/interval_map.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::icl;\n\n// 'make_segments' returns a vector of interval value pairs, which\n// are not sorted. The values are taken from the minimal example\n// in section 'interval combining styles'.\nvector<pair<discrete_interval<int>, int> > make_segments()\n{\n    vector<pair<discrete_interval<int>, int> > segment_vec;\n    segment_vec.push_back(make_pair(discrete_interval<int>::right_open(2,4), 1));\n    segment_vec.push_back(make_pair(discrete_interval<int>::right_open(4,5), 1));\n    segment_vec.push_back(make_pair(discrete_interval<int>::right_open(1,3), 1));\n    return segment_vec;\n}\n\n// 'show_segments' displays the source segements.\nvoid show_segments(const vector<pair<discrete_interval<int>, int> >& segments)\n{\n    vector<pair<discrete_interval<int>, int> >::const_iterator iter = segments.begin();\n    while(iter != segments.end())\n    {\n        cout << \"(\" << iter->first << \",\" << iter->second << \")\";\n        ++iter;\n    }\n}\n\nvoid std_copy()\n{\n    // So we have some segments stored in an std container.\n    vector<pair<discrete_interval<int>, int> > segments = make_segments();\n    // Display the input\n    cout << \"input sequence: \"; show_segments(segments); cout << \"\\n\\n\";\n\n    // We are going to 'std::copy' those segments into an interval_map:\n    interval_map<int,int> segmap;\n\n    // Use an 'icl::inserter' from <boost/icl/iterator.hpp> to call\n    // insertion on the interval container.\n    std::copy(segments.begin(), segments.end(),\n              icl::inserter(segmap, segmap.end()));\n    cout << \"icl::inserting: \" << segmap << endl;\n    segmap.clear();\n\n    // When we are feeding data into interval_maps, most of the time we are\n    // intending to compute an aggregation result. So we are not interested\n    // the std::insert semantincs but the aggregating icl::addition semantics.\n    // To achieve this there is an icl::add_iterator and an icl::adder function\n    // provided in <boost/icl/iterator.hpp>.\n    std::copy(segments.begin(), segments.end(),\n              icl::adder(segmap, segmap.end())); //Aggregating associated values\n    cout << \"icl::adding   : \" << segmap << endl;\n\n    // In this last case, the semantics of 'std::copy' transforms to the\n    // generalized addition operation, that is implemented by operator\n    // += or + on itl maps and sets.\n}\n\nint main()\n{\n    cout << \">>    Interval Container Library: Example std_copy.cpp    <<\\n\";\n    cout << \"-----------------------------------------------------------\\n\";\n    cout << \"Using std::copy to fill an interval_map:\\n\\n\";\n\n    std_copy();\n    return 0;\n}\n\n// Program output:\n/*---------------------------------------------------------\n>>    Interval Container Library: Example std_copy.cpp    <<\n-----------------------------------------------------------\nUsing std::copy to fill an interval_map:\n\ninput sequence: ([2,4),1)([4,5),1)([1,3),1)\n\nicl::inserting: {([1,5)->1)}\nicl::adding   : {([1,2)->1)([2,3)->2)([3,5)->1)}\n---------------------------------------------------------*/\n//]\n", "meta": {"hexsha": "fca194271cfca086d4ff2d8258975fe980292634", "size": 4076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/icl/example/std_copy_/std_copy.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/icl/example/std_copy_/std_copy.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/icl/example/std_copy_/std_copy.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": 38.4528301887, "max_line_length": 87, "alphanum_fraction": 0.5991167812, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.5072669706998267}}
{"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    CreateSFMExampleData.cpp\n * @brief   Create some example data that for inclusion in the data folder\n * @author  Frank Dellaert\n */\n\n#include <gtsam/slam/dataset.h>\n#include <gtsam/geometry/CalibratedCamera.h>\n\n#include <boost/assign/std/vector.hpp>\n\nusing namespace boost::assign;\nusing namespace std;\nusing namespace gtsam;\n\n/* ************************************************************************* */\n\nvoid createExampleBALFile(const string& filename, const vector<Point3>& P,\n    const Pose3& pose1, const Pose3& pose2, const Cal3Bundler& K =\n        Cal3Bundler()) {\n\n  // Class that will gather all data\n  SfM_data data;\n\n  // Create two cameras\n  Rot3 aRb = Rot3::Yaw(M_PI_2);\n  Point3 aTb(0.1, 0, 0);\n  Pose3 identity, aPb(aRb, aTb);\n  data.cameras.push_back(SfM_Camera(pose1, K));\n  data.cameras.push_back(SfM_Camera(pose2, K));\n\n  for(const Point3& p: P) {\n\n    // Create the track\n    SfM_Track track;\n    track.p = p;\n    track.r = 1;\n    track.g = 1;\n    track.b = 1;\n\n    // Project points in both cameras\n    for (size_t i = 0; i < 2; i++)\n    track.measurements.push_back(make_pair(i, data.cameras[i].project(p)));\n\n    // Add track to data\n    data.tracks.push_back(track);\n  }\n\n  writeBAL(filename, data);\n}\n\n/* ************************************************************************* */\n\nvoid create5PointExample1() {\n\n  // Create two cameras poses\n  Rot3 aRb = Rot3::Yaw(M_PI_2);\n  Point3 aTb(0.1, 0, 0);\n  Pose3 pose1, pose2(aRb, aTb);\n\n  // Create test data, we need at least 5 points\n  vector<Point3> P;\n  P += Point3(0, 0, 1), Point3(-0.1, 0, 1), Point3(0.1, 0, 1), //\n  Point3(0, 0.5, 0.5), Point3(0, -0.5, 0.5);\n\n  // Assumes example is run in ${GTSAM_TOP}/build/examples\n  const string filename = \"../../examples/data/5pointExample1.txt\";\n  createExampleBALFile(filename, P, pose1, pose2);\n}\n\n/* ************************************************************************* */\n\nvoid create5PointExample2() {\n\n  // Create two cameras poses\n  Rot3 aRb = Rot3::Yaw(M_PI_2);\n  Point3 aTb(10, 0, 0);\n  Pose3 pose1, pose2(aRb, aTb);\n\n  // Create test data, we need at least 5 points\n  vector<Point3> P;\n  P += Point3(0, 0, 100), Point3(-10, 0, 100), Point3(10, 0, 100), //\n  Point3(0, 50, 50), Point3(0, -50, 50), Point3(-20, 0, 80), Point3(20, -50, 80);\n\n  // Assumes example is run in ${GTSAM_TOP}/build/examples\n  const string filename = \"../../examples/data/5pointExample2.txt\";\n  Cal3Bundler K(500, 0, 0);\n  createExampleBALFile(filename, P, pose1, pose2,K);\n}\n\n/* ************************************************************************* */\n\nint main(int argc, char* argv[]) {\n  create5PointExample1();\n  create5PointExample2();\n  return 0;\n}\n\n/* ************************************************************************* */\n\n", "meta": {"hexsha": "082b4c0f99ad8ac787746cdef82895aece952525", "size": 3162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/CreateSFMExampleData.cpp", "max_stars_repo_name": "DEVESHTARASIA/gtsam", "max_stars_repo_head_hexsha": "e90e1f1dd2105b47df1d731ac82da28a6a9be454", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-12-11T18:33:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:52:45.000Z", "max_issues_repo_path": "examples/CreateSFMExampleData.cpp", "max_issues_repo_name": "DEVESHTARASIA/gtsam", "max_issues_repo_head_hexsha": "e90e1f1dd2105b47df1d731ac82da28a6a9be454", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-10-30T21:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T18:47:40.000Z", "max_forks_repo_path": "examples/CreateSFMExampleData.cpp", "max_forks_repo_name": "DEVESHTARASIA/gtsam", "max_forks_repo_head_hexsha": "e90e1f1dd2105b47df1d731ac82da28a6a9be454", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-08-30T13:14:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T18:49:58.000Z", "avg_line_length": 28.2321428571, "max_line_length": 81, "alphanum_fraction": 0.5464895636, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5072669706998267}}
{"text": "//\n// Created by jachu on 27.02.18.\n//\n\n#ifndef PLANELOC_PLANEESTIMATOR_HPP\n#define PLANELOC_PLANEESTIMATOR_HPP\n\n#include <boost/serialization/access.hpp>\n\n#include <Eigen/Dense>\n\n#include \"Types.hpp\"\n\nclass PlaneEstimator {\npublic:\n    PlaneEstimator();\n    \n    PlaneEstimator(const Eigen::MatrixXd &pts);\n    \n    PlaneEstimator(const Eigen::Vector3d &icentroid,\n                   const Eigen::Matrix3d &icovar,\n                   int inpts);\n    \n    void init(const Eigen::MatrixXd &pts);\n    \n    void init(const Eigen::Vector3d &icentroid,\n              const Eigen::Matrix3d &icovar,\n              int inpts);\n    \n    void update(const Eigen::Vector3d &ucentroid,\n                const Eigen::Matrix3d &ucovar,\n                int unpts);\n\n//    void transform(const Eigen::Matrix4d T);\n    \n    double distance(const PlaneEstimator &other) const;\n    \n    static void compCentroidAndCovar(const Eigen::MatrixXd &pts,\n                                    Eigen::Vector3d &centroid,\n                                    Eigen::Matrix3d &covar);\n    \n    static void compPlaneParams(const Eigen::Vector3d centroid,\n                                const Eigen::Matrix3d &covar,\n                                Eigen::Matrix3d &evecs,\n                                Eigen::Vector3d &evals,\n                                Eigen::Vector4d &planeEq);\n    \n    void transform(const Vector7d &transform);\n    \n    const Eigen::Vector3d &getCentroid() const {\n        return centroid;\n    }\n    \n    const Eigen::Matrix3d &getCovar() const {\n        return covar;\n    }\n    \n    const Eigen::Matrix3d &getEvecs() const {\n        return evecs;\n    }\n    \n    const Eigen::Vector3d &getEvals() const {\n        return evals;\n    }\n    \n    const Eigen::Vector4d &getPlaneEq() const {\n        return planeEq;\n    }\n    \n    int getNpts() const {\n        return npts;\n    }\n    \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n    \n    static void updateCentroidAndCovar(const Eigen::Vector3d &centroid1,\n                                      const Eigen::Matrix3d &covar1,\n                                      const int &npts1,\n                                      const Eigen::Vector3d &centroid2,\n                                      const Eigen::Matrix3d &covar2,\n                                      const int &npts2,\n                                      Eigen::Vector3d &ocentroid,\n                                      Eigen::Matrix3d &ocovar,\n                                      int &onpts);\n    \n    Eigen::Vector3d centroid;\n    \n    Eigen::Matrix3d covar;\n    \n    Eigen::Matrix3d evecs;\n    \n    Eigen::Vector3d evals;\n    \n    Eigen::Vector4d planeEq;\n    \n    int npts;\n    \n    friend class boost::serialization::access;\n    \n    template<class Archive>\n    void serialize(Archive & ar, const unsigned int version)\n    {\n        ar & centroid;\n        ar & covar;\n        ar & evecs;\n        ar & evals;\n        ar & planeEq;\n        ar & npts;\n    }\n};\n\n\n#endif //PLANELOC_PLANEESTIMATOR_HPP\n", "meta": {"hexsha": "fad6284bc923df7e37d2fc255412b2d24063c179", "size": 3007, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/PlaneEstimator.hpp", "max_stars_repo_name": "richard5635/PlaneLoc", "max_stars_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-08-29T06:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T07:42:31.000Z", "max_issues_repo_path": "include/PlaneEstimator.hpp", "max_issues_repo_name": "richard5635/PlaneLoc", "max_issues_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-03-26T06:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T01:59:41.000Z", "max_forks_repo_path": "include/PlaneEstimator.hpp", "max_forks_repo_name": "richard5635/PlaneLoc", "max_forks_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-04-24T08:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T07:56:58.000Z", "avg_line_length": 26.147826087, "max_line_length": 72, "alphanum_fraction": 0.5214499501, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5072669677331573}}
{"text": "#include <iostream>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/accumulators/statistics/sum.hpp>\n\n\nusing namespace boost::accumulators;\nint main()\n{\n\t//accumulator_set<int, features<tag::weight_sum> , int> acc;\n\taccumulator_set<double, features<tag::count, droppable<tag::sum> > >acc;\n\n\tacc(3.0);\n\tacc(2.0);\n\tacc.drop<tag::sum>();\n\tacc(1.0);\n\n\t//sum will drop acc, now acc is 3.0+2.0\n\tstd::cout<< count(acc) <<' '<< sum(acc) << std::endl;\n}", "meta": {"hexsha": "3068a110dd0e5e9155ca0e7cf2ece2adfb1ea1d3", "size": 510, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/Boost/accumulate/drop.cc", "max_stars_repo_name": "yanrong/book_demo", "max_stars_repo_head_hexsha": "20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f", "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/Boost/accumulate/drop.cc", "max_issues_repo_name": "yanrong/book_demo", "max_issues_repo_head_hexsha": "20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f", "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/Boost/accumulate/drop.cc", "max_forks_repo_name": "yanrong/book_demo", "max_forks_repo_head_hexsha": "20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f", "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.5, "max_line_length": 73, "alphanum_fraction": 0.6980392157, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5072669599677218}}
{"text": "#include \"edlib/Basis/Basis1D.hpp\"\n#include \"edlib/Basis/Basis1DZ2.hpp\"\n#include \"edlib/Basis/ToOriginalBasis.hpp\"\n#include \"edlib/EDP/ConstructSparseMat.hpp\"\n#include \"edlib/Hamiltonians/TIXXZ.hpp\"\n\n#include \"XXZ.hpp\"\n#include \"utils.hpp\"\n\n#include <Eigen/Dense>\n#include <catch2/catch.hpp>\n\n#include <iostream>\n#include <unordered_set>\n\nusing namespace Eigen;\nusing namespace edlib;\n\nconstexpr uint32_t max_n = 12;\n\ntemplate<typename Basis> VectorXd translate(Basis&& basis, const VectorXd& r)\n{\n    VectorXd res(r.size());\n    for(uint32_t i = 0; i < r.size(); i++)\n    {\n        res(basis.rotl(i, 1)) = r(i);\n    }\n    return res;\n}\n\ntemplate<class Basis> uint64_t countDim1D(Basis&& basis, bool useU1)\n{\n    const auto N = basis.getN();\n    const auto k = basis.getK();\n    const int expk = (k == 0) ? 1 : -1;\n\n    std::unordered_set<VectorXi, hash_vector> basisVecs;\n\n    for(uint32_t n = 0; n < (1U << N); ++n)\n    {\n        if(useU1 && (__builtin_popcountll(n) != N / 2))\n        {\n            continue;\n        }\n        Eigen::VectorXi v = Eigen::VectorXi::Zero(1UL << N);\n        for(uint32_t k = 0; k < N; k++)\n        {\n            v(basis.rotl(n, k)) += powi(expk, k);\n        }\n        if(v.cwiseAbs().sum() != 0)\n        {\n            make_first_positive(v);\n            basisVecs.emplace(std::move(v));\n        }\n    }\n\n    return basisVecs.size();\n}\n\ntemplate<class Basis> uint64_t countDim1DZ2(Basis&& basis, bool useU1)\n{\n    const auto N = basis.getN();\n    const auto k = basis.getK();\n    const int p = basis.getP();\n    const int expk = (k == 0) ? 1 : -1;\n\n    std::unordered_set<VectorXi, hash_vector> basisVecs;\n\n    for(uint32_t n = 0; n < (1U << N); ++n)\n    {\n        if(useU1 && (__builtin_popcountll(n) != N / 2))\n        {\n            continue;\n        }\n        Eigen::VectorXi v = Eigen::VectorXi::Zero(1UL << N);\n        for(uint32_t k = 0; k < N; k++)\n        {\n            v(basis.rotl(n, k)) += powi(expk, k);\n            v(basis.rotl(basis.flip(n), k)) += powi(expk, k) * p;\n        }\n        if(v.cwiseAbs().sum() != 0)\n        {\n            make_first_positive(v);\n            basisVecs.emplace(std::move(v));\n        }\n    }\n\n    return basisVecs.size();\n}\n\ntemplate<class Basis> void CheckBasis1DParity(Basis&& basis, const MatrixXd& r)\n{\n    const auto k = basis.getK();\n    const int p = basis.getP();\n\n    const int expk = (k == 0) ? 1 : -1;\n\n    for(int i = 0; i < r.cols(); i++)\n    {\n        VectorXd c = r.col(i);\n        REQUIRE((c - expk * translate(basis, c)).norm() < 1e-10);\n        REQUIRE((c - p * flip(basis, c)).norm() < 1e-10);\n    }\n}\n\ntemplate<class Basis> void CheckBasis1D(Basis&& basis, const MatrixXd& r)\n{\n    const auto k = basis.getK();\n    const int expk = (k == 0) ? 1 : -1;\n\n    for(int i = 0; i < r.cols(); i++)\n    {\n        auto c = r.col(i);\n        REQUIRE((c - expk * translate(basis, c)).norm() < 1e-10);\n    }\n}\n\ntemplate<class Basis> void CheckBasisXXZ(Basis&& basis, const MatrixXd& r)\n{\n    TIXXZ<uint32_t> tiXXZ(basis, 1.0, 0.9);\n    const size_t dim = basis.getDim();\n    auto hamTI = edp::constructSparseMat<double>(\n        dim, [&tiXXZ](uint32_t col) { return tiXXZ.getCol(col); });\n\n    const auto N = basis.getN();\n\n    XXZ xxz(N, 1.0, 0.9);\n    auto hamFull = edp::constructSparseMat<double>(1U << N, xxz);\n    Eigen::MatrixXd mat = r.transpose() * hamFull * r;\n\n    REQUIRE((Eigen::MatrixXd(hamTI) - mat).norm() < 1e-10);\n}\n\nTEST_CASE(\"Test Basis1D\", \"[basis1d]\")\n{\n    SECTION(\"Representatives are correct\")\n    {\n        uint32_t K = 0;\n        for(uint32_t N = 4; N <= 20; N += 4)\n        {\n            Basis1D<uint32_t> basis(N, K, true);\n\n            for(uint32_t i = 0; i < basis.getDim(); ++i)\n            {\n                uint32_t rep = basis.getNthRep(i);\n                const auto [rep2, rot] = basis.findMinRots(rep);\n                REQUIRE(rep2 == rep);\n            }\n        }\n    }\n    SECTION(\"Without U1\")\n    {\n        for(uint32_t N = 4; N <= max_n; N += 2)\n        {\n            for(uint32_t K : {0U, N / 2})\n            {\n                DYNAMIC_SECTION(\"Testing N: \" << N << \", K: \" << K)\n                {\n                    Basis1D<uint32_t> basis(N, K, false);\n\n                    REQUIRE(basis.getDim() == countDim1D(basis, false));\n\n                    MatrixXd r = basisMatrix(basis);\n                    TestBasisMatrix(r);\n                    CheckBasis1D(basis, r);\n                    CheckBasisXXZ(basis, r);\n                }\n            }\n        }\n    }\n    SECTION(\"With U1\")\n    {\n        for(uint32_t N = 4; N <= max_n; N += 2)\n        {\n            for(uint32_t K : {0U, N / 2})\n            {\n                DYNAMIC_SECTION(\"Testing N: \" << N << \", K: \" << K)\n                {\n                    Basis1D<uint32_t> basis(N, K, true);\n\n                    REQUIRE(basis.getDim() == countDim1D(basis, true));\n\n                    MatrixXd r = basisMatrix(basis);\n                    TestBasisMatrix(r);\n                    CheckBasis1D(basis, r);\n                    CheckBasisXXZ(basis, r);\n                }\n            }\n        }\n    }\n}\n\nTEST_CASE(\"Test Basis1DZ2\", \"[basis1dz2]\")\n{\n    const std::array<int, 2> ps{-1, 1};\n\n    SECTION(\"Without U1\")\n    {\n        for(uint32_t N = 4; N <= max_n; N += 2)\n        {\n            for(uint32_t K : {0U, N / 2})\n            {\n                for(int p : ps)\n                {\n                    DYNAMIC_SECTION(\"Testing N: \" << N << \", K: \" << K << \", p: \" << p)\n                    {\n                        Basis1DZ2<uint32_t> basis(N, K, p, false);\n\n                        REQUIRE(basis.getDim() == countDim1DZ2(basis, false));\n\n                        MatrixXd r = basisMatrix(basis);\n                        TestBasisMatrix(r);\n                        CheckBasis1DParity(basis, r);\n                        CheckBasisXXZ(basis, r);\n                    }\n                }\n            }\n        }\n    }\n    SECTION(\"With U1\")\n    {\n        for(uint32_t N = 6; N <= max_n; N += 2)\n        {\n            for(uint32_t K : {0U, N / 2})\n            {\n                for(int p : ps)\n                {\n                    DYNAMIC_SECTION(\"Testing N: \" << N << \", K: \" << K << \", p: \" << p)\n                    {\n                        Basis1DZ2<uint32_t> basis(N, K, p, true);\n\n                        REQUIRE(basis.getDim() == countDim1DZ2(basis, true));\n\n                        MatrixXd r = basisMatrix(basis);\n                        TestBasisMatrix(r);\n                        CheckBasis1D(basis, r);\n                        CheckBasisXXZ(basis, r);\n                    }\n                }\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "d8cd0498f1cbe791ca0640ad4b62324b98c98765", "size": 6612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_basis1d.cpp", "max_stars_repo_name": "cecri/ExactDiagonalization", "max_stars_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_stars_repo_licenses": ["MIT"], "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_basis1d.cpp", "max_issues_repo_name": "cecri/ExactDiagonalization", "max_issues_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_issues_repo_licenses": ["MIT"], "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_basis1d.cpp", "max_forks_repo_name": "cecri/ExactDiagonalization", "max_forks_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_forks_repo_licenses": ["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.0983606557, "max_line_length": 87, "alphanum_fraction": 0.4668784029, "num_tokens": 1895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5072669590516738}}
{"text": "#include <boost\\filesystem.hpp>\n#include <boost\\lexical_cast.hpp>\n#include \"genetic_programming.h\"\n\nint Print(fstream &output_file, string &program, int node)\n{\n\tint node1 = 0, node2;\n\n\tif (program[node] < FSET_START) {\n\t\tif (program[node] <= num_vars)\n\t\t\toutput_file << \"x\" << (int)program[node];\n\t\telse\n\t\t\toutput_file << args[program[node] - 1];\n\t\treturn node + 1;\n\t}\n\telse {\n\t\tswitch (program[node]) {\n\t\t\t//case EXP:\n\t\t\t//\toutput_file << \"exp(\";\n\t\t\t//\tnode2 = Print(output_file, program, node + 1);\n\t\t\t//\toutput_file << \")\";\n\t\t\t//\treturn node2;\n\t\t\t//case SIN:\n\t\t\t//\toutput_file << \"sin(\";\n\t\t\t//\tnode2 = Print(output_file, program, node + 1);\n\t\t\t//\toutput_file << \")\";\n\t\t\t//\treturn node2;\n\t\t\t//case COS:\n\t\t\t//\toutput_file << \"cos(\";\n\t\t\t//\tnode2 = Print(output_file, program, node + 1);\n\t\t\t//\toutput_file << \")\";\n\t\t\t//\treturn node2;\n\t\t\t//case LOG:\n\t\t\t//\toutput_file << \"log(abs(\";\n\t\t\t//\tnode2 = Print(output_file, program, node + 1);\n\t\t\t//\toutput_file << \"))\";\n\t\t\t//\treturn node2;\n\t\t\tcase ADD:\n\t\t\t\toutput_file << \"(\";\n\t\t\t\tnode1 = Print(output_file, program, node + 1);\n\t\t\t\toutput_file << \" + \";\n\t\t\t\tbreak;\n\t\t\tcase SUB:\n\t\t\t\toutput_file << \"(\";\n\t\t\t\tnode1 = Print(output_file, program, node + 1);\n\t\t\t\toutput_file << \" - \";\n\t\t\t\tbreak;\n\t\t\tcase MUL:\n\t\t\t\toutput_file << \"(\";\n\t\t\t\tnode1 = Print(output_file, program, node + 1);\n\t\t\t\toutput_file << \" * \";\n\t\t\t\tbreak;\n\t\t\tcase DIV:\n\t\t\t\toutput_file << \"(\";\n\t\t\t\tnode1 = Print(output_file, program, node + 1);\n\t\t\t\toutput_file << \" / \";\n\t\t\t\tbreak;\n\t\t\t//case POW:\n\t\t\t//\toutput_file << \"(\";\n\t\t\t//\tnode1 = Print(output_file, program, node + 1);\n\t\t\t//\toutput_file << \" ^ \";\n\t\t\t//\tbreak;\n\t\t}\n\t}\n\n\tnode2 = Print(output_file, program, node1);\n\toutput_file << \")\";\n\n\treturn node2;\n}\n\nvoid PrintInfixProgram(string &program, string &output_filename)\n{\n\tfstream output_file(output_filename, ios::out);\n\tint node = 0;\n\tPrint(output_file, program, node);\n\toutput_file.close();\n}\n\nvoid SaveProgram(string &program, string filename)\n{\n\tfstream args_file(filename + \"_args.txt\", ios::out), prog_file(filename + \".txt\", ios::out);\n\n\tint i = 0;\n\tfor (; i < args.size(); ++i)\n\t\targs_file << args[i] << \"\\n\";\n\n\tfor (i = 0; i < program.size(); ++i)\n\t\tprog_file << (int)program[i] << \"\\n\";\n\n\targs_file.close();\n\tprog_file.close();\n\n\tPrintInfixProgram(program, filename + \"_infix.txt\");\n}\n\nvoid TestProgram(string &program, string output_filename)\n{\n\tfstream output_file(output_filename + \".csv\", ios::out);\n\n\toutput_file << \"x,y\\n\";\n\n\tfor (int fit_case = 0; fit_case < input_data.size(); ++fit_case) {\n\t\tfor (int var = 0; var < num_vars; ++var) {\n\t\t\targs[var] = input_data[fit_case][var];\n\t\t\toutput_file << args[var] << \",\";\n\t\t}\n\n\t\tcurrent_node = program.begin();\n\t\toutput_file << Next() << \"\\n\";\n\t}\n\n\toutput_file.close();\n}\n\nstring LoadProgram(string &program_name)\n{\n\tfstream program_file(program_name, ios::in);\n\n\tstring program, line;\n\n\twhile (true) {\n\t\tgetline(program_file, line);\n\t\tif (program_file.eof())\n\t\t\tbreak;\n\t\tprogram += stoi(line);\n\t}\n\n\tprogram_file.close();\n\n\treturn program;\n}\n\nint main() {\n\tboost::filesystem::path fullpath(boost::filesystem::current_path());\n\tstring temp = boost::lexical_cast<string>(fullpath);\n\tstring curr_dir = string(temp.begin() + 1, temp.end() - 1);\n\n\tSetUp(curr_dir + \"\\\\config.ini\");\n\n\tcout << \"SYMBOLIC REGRESSION w/ GENETIC PROGRAMMING\\n\" << endl;\n\t\n\tcout << \"Pseudo random number generator seed\\t= \" << seed << endl;\n\tcout << \"Population size\\t\\t\\t\\t= \" << popsize << endl;\n\tcout << \"Number of generations\\t\\t\\t= \" << generations << endl;\n\tcout << \"Max depth at the initialisation\\t\\t= \" << max_depth << endl;\n\tcout << \"Max program length\\t\\t\\t= \" << max_length << endl;\n\tcout << \"Tournament size\\t\\t\\t\\t= \" << tournament_size << endl;\n\tcout << \"Mutation probability per node\\t\\t= \" << pm_per_node << endl;\n\tcout << \"Crossover probability\\t\\t\\t= \" << pcrossover << endl;\n\tcout << \"Data filename\\t\\t\\t\\t= \" << fitness_data_filename << endl;\n\tcout << \"Number of independent variables\\t\\t= \" << num_vars << endl;\n\tcout << \"Number of random constants\\t\\t= \" << num_rand_nums << endl;\n\tif (num_rand_nums) {\n\t\tcout << \"Min constant\\t\\t\\t\\t= \" << min_rand_num << endl;\n\t\tcout << \"Max constant\\t\\t\\t\\t= \" << max_rand_num << endl;\n\t}\n\tif (seed_w_program)\n\t\tcout << \"Seed for the initial population\\t\\t= \" << prog_name << endl;\n\n\tprintf(\"\\nPress any key to continue...\\n\");\n\tcin.get();\n\n\tvector<Individual> population(popsize);\n\tIndividual best;\n\n\tif (seed_w_program) {\n\t\tbest.program = LoadProgram(prog_name);\n\t\tEvaluate(best);\n\t}\n\n\tfor (int i = 0; i < popsize; ++i) {\n\t\tpopulation[i].program = BuildTree(random(2, max_depth), random(0, 1)); //Ramped half-and-half.\n\t\tEvaluate(population[i]);\n\n\t\tif (population[i] < best)\n\t\t\tbest = population[i];\n\t}\n\n\tint epochs = generations * popsize, break_flag = 0;\n\n\tfor (int epoch = 0; epoch < epochs; ++epoch) {\n\t\tIndividual &offspring = population[Tournament(population, tournament_size, IsGreater<Individual>)]\n\t\t\t= population[Tournament(population, tournament_size, IsLess<Individual>)];\n\n\t\tif (random<float>() < pcrossover) \n\t\t\tSubtreeXO(offspring, population[Tournament(population, tournament_size, IsLess<Individual>)]);\n\t\telse \n\t\t\tPtMutation(offspring.program);\n\n\t\tEvaluate(offspring);\n\n\t\tif (offspring < best)\n\t\t\tbest = offspring;\n\n\t\tif (((epoch + 1) % popsize) == 0) \n\t\t\tprintf(\"Gen: %d, Program size: %d, Performance: %.4f\\n\", (1 + epoch / popsize), best.program.size(), best.fitness);\n\n\t\tif (best.fitness < 0.0001)\n\t\t\tbreak;\n\n\t\tif (break_flag = GetAsyncKeyState(VK_ESCAPE)) {\n\t\t\tchar c = 0;\n\n\t\t\tprintf(\"\\n\");\n\n\t\t\twhile (c != 'Y' && c != 'y' && c != 'N' && c != 'n') {\n\t\t\t\tprintf(\"\\rDo you want quit the program? (Y/N): \");\n\t\t\t\tcin >> c;\n\t\t\t}\n\n\t\t\tif (c == 'Y' || c == 'y') {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbreak_flag = 0;\n\t\t\t\tprintf(\"\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!break_flag)\n\t\tprintf(\"\\n\");\n\n\tchar c = 0;\n\twhile (c != 'Y' && c != 'y' && c != 'N' && c != 'n') {\n\t\tprintf(\"\\rSave the best program? (Y/N): \");\n\t\tcin >> c;\n\t}\n\n\tif (c == 'Y' || c == 'y') {\n\t\tstring filename;\n\t\tprintf(\"Save as: \");\n\t\tcin >> filename;\n\t\tSaveProgram(best.program, filename);\n\t}\n\n\tc = 0;\n\twhile (c != 'Y' && c != 'y' && c != 'N' && c != 'n') {\n\t\tprintf(\"\\rTest the best program? (Y/N): \");\n\t\tcin >> c;\n\t}\n\n\tif (c == 'Y' || c == 'y') {\n\t\tstring filename;\n\t\tprintf(\"Output file: \");\n\t\tcin >> filename;\n\t\tTestProgram(best.program, filename);\n\t}\n\n\tprintf(\"\\nPress any key to quit...\\n\");\n\tcin.get();\n\tcin.get();\n\n\treturn 0;\n}", "meta": {"hexsha": "17cf8dd30b9ee61ca9c27f6f3609fbc8f59d5a99", "size": 6396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "symbolic_regression/symbolic_regression/main.cpp", "max_stars_repo_name": "karolisjan/Genetic-Programming", "max_stars_repo_head_hexsha": "48b07ae869f4d479975a64f539caa42cf2e3db60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "symbolic_regression/symbolic_regression/main.cpp", "max_issues_repo_name": "karolisjan/Genetic-Programming", "max_issues_repo_head_hexsha": "48b07ae869f4d479975a64f539caa42cf2e3db60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "symbolic_regression/symbolic_regression/main.cpp", "max_forks_repo_name": "karolisjan/Genetic-Programming", "max_forks_repo_head_hexsha": "48b07ae869f4d479975a64f539caa42cf2e3db60", "max_forks_repo_licenses": ["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.984375, "max_line_length": 118, "alphanum_fraction": 0.6042839275, "num_tokens": 1877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5072669581356258}}
{"text": "//  Copyright (c) 2006 Xiaogang Zhang\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_BESSEL_IK_HPP\n#define BOOST_MATH_BESSEL_IK_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/special_functions/round.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/sin_pi.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/tools/config.hpp>\n\n// Modified Bessel functions of the first and second kind of fractional order\n\nnamespace boost { namespace math {\n\nnamespace detail {\n\ntemplate <class T, class Policy>\nstruct cyl_bessel_i_small_z\n{\n   typedef T result_type;\n\n   cyl_bessel_i_small_z(T v_, T z_) : k(0), v(v_), mult(z_*z_/4) \n   {\n      BOOST_MATH_STD_USING\n      term = 1;\n   }\n\n   T operator()()\n   {\n      T result = term;\n      ++k;\n      term *= mult / k;\n      term /= k + v;\n      return result;\n   }\nprivate:\n   unsigned k;\n   T v;\n   T term;\n   T mult;\n};\n\ntemplate <class T, class Policy>\ninline T bessel_i_small_z_series(T v, T x, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n   T prefix;\n   if(v < max_factorial<T>::value)\n   {\n      prefix = pow(x / 2, v) / boost::math::tgamma(v + 1, pol);\n   }\n   else\n   {\n      prefix = v * log(x / 2) - boost::math::lgamma(v + 1, pol);\n      prefix = exp(prefix);\n   }\n   if(prefix == 0)\n      return prefix;\n\n   cyl_bessel_i_small_z<T, Policy> s(v, x);\n   boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n   T zero = 0;\n   T result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, zero);\n#else\n   T result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter);\n#endif\n   policies::check_series_iterations<T>(\"boost::math::bessel_j_small_z_series<%1%>(%1%,%1%)\", max_iter, pol);\n   return prefix * result;\n}\n\n// Calculate K(v, x) and K(v+1, x) by method analogous to\n// Temme, Journal of Computational Physics, vol 21, 343 (1976)\ntemplate <typename T, typename Policy>\nint temme_ik(T v, T x, T* K, T* K1, const Policy& pol)\n{\n    T f, h, p, q, coef, sum, sum1, tolerance;\n    T a, b, c, d, sigma, gamma1, gamma2;\n    unsigned long k;\n\n    BOOST_MATH_STD_USING\n    using namespace boost::math::tools;\n    using namespace boost::math::constants;\n\n\n    // |x| <= 2, Temme series converge rapidly\n    // |x| > 2, the larger the |x|, the slower the convergence\n    BOOST_ASSERT(abs(x) <= 2);\n    BOOST_ASSERT(abs(v) <= 0.5f);\n\n    T gp = boost::math::tgamma1pm1(v, pol);\n    T gm = boost::math::tgamma1pm1(-v, pol);\n\n    a = log(x / 2);\n    b = exp(v * a);\n    sigma = -a * v;\n    c = abs(v) < tools::epsilon<T>() ?\n       T(1) : T(boost::math::sin_pi(v) / (v * pi<T>()));\n    d = abs(sigma) < tools::epsilon<T>() ?\n        T(1) : T(sinh(sigma) / sigma);\n    gamma1 = abs(v) < tools::epsilon<T>() ?\n        T(-euler<T>()) : T((0.5f / v) * (gp - gm) * c);\n    gamma2 = (2 + gp + gm) * c / 2;\n\n    // initial values\n    p = (gp + 1) / (2 * b);\n    q = (1 + gm) * b / 2;\n    f = (cosh(sigma) * gamma1 + d * (-a) * gamma2) / c;\n    h = p;\n    coef = 1;\n    sum = coef * f;\n    sum1 = coef * h;\n\n    BOOST_MATH_INSTRUMENT_VARIABLE(p);\n    BOOST_MATH_INSTRUMENT_VARIABLE(q);\n    BOOST_MATH_INSTRUMENT_VARIABLE(f);\n    BOOST_MATH_INSTRUMENT_VARIABLE(sigma);\n    BOOST_MATH_INSTRUMENT_CODE(sinh(sigma));\n    BOOST_MATH_INSTRUMENT_VARIABLE(gamma1);\n    BOOST_MATH_INSTRUMENT_VARIABLE(gamma2);\n    BOOST_MATH_INSTRUMENT_VARIABLE(c);\n    BOOST_MATH_INSTRUMENT_VARIABLE(d);\n    BOOST_MATH_INSTRUMENT_VARIABLE(a);\n\n    // series summation\n    tolerance = tools::epsilon<T>();\n    for (k = 1; k < policies::get_max_series_iterations<Policy>(); k++)\n    {\n        f = (k * f + p + q) / (k*k - v*v);\n        p /= k - v;\n        q /= k + v;\n        h = p - k * f;\n        coef *= x * x / (4 * k);\n        sum += coef * f;\n        sum1 += coef * h;\n        if (abs(coef * f) < abs(sum) * tolerance) \n        { \n           break; \n        }\n    }\n    policies::check_series_iterations<T>(\"boost::math::bessel_ik<%1%>(%1%,%1%) in temme_ik\", k, pol);\n\n    *K = sum;\n    *K1 = 2 * sum1 / x;\n\n    return 0;\n}\n\n// Evaluate continued fraction fv = I_(v+1) / I_v, derived from\n// Abramowitz and Stegun, Handbook of Mathematical Functions, 1972, 9.1.73\ntemplate <typename T, typename Policy>\nint CF1_ik(T v, T x, T* fv, const Policy& pol)\n{\n    T C, D, f, a, b, delta, tiny, tolerance;\n    unsigned long k;\n\n    BOOST_MATH_STD_USING\n\n    // |x| <= |v|, CF1_ik converges rapidly\n    // |x| > |v|, CF1_ik needs O(|x|) iterations to converge\n\n    // modified Lentz's method, see\n    // Lentz, Applied Optics, vol 15, 668 (1976)\n    tolerance = 2 * tools::epsilon<T>();\n    BOOST_MATH_INSTRUMENT_VARIABLE(tolerance);\n    tiny = sqrt(tools::min_value<T>());\n    BOOST_MATH_INSTRUMENT_VARIABLE(tiny);\n    C = f = tiny;                           // b0 = 0, replace with tiny\n    D = 0;\n    for (k = 1; k < policies::get_max_series_iterations<Policy>(); k++)\n    {\n        a = 1;\n        b = 2 * (v + k) / x;\n        C = b + a / C;\n        D = b + a * D;\n        if (C == 0) { C = tiny; }\n        if (D == 0) { D = tiny; }\n        D = 1 / D;\n        delta = C * D;\n        f *= delta;\n        BOOST_MATH_INSTRUMENT_VARIABLE(delta-1);\n        if (abs(delta - 1) <= tolerance) \n        { \n           break; \n        }\n    }\n    BOOST_MATH_INSTRUMENT_VARIABLE(k);\n    policies::check_series_iterations<T>(\"boost::math::bessel_ik<%1%>(%1%,%1%) in CF1_ik\", k, pol);\n\n    *fv = f;\n\n    return 0;\n}\n\n// Calculate K(v, x) and K(v+1, x) by evaluating continued fraction\n// z1 / z0 = U(v+1.5, 2v+1, 2x) / U(v+0.5, 2v+1, 2x), see\n// Thompson and Barnett, Computer Physics Communications, vol 47, 245 (1987)\ntemplate <typename T, typename Policy>\nint CF2_ik(T v, T x, T* Kv, T* Kv1, const Policy& pol)\n{\n    BOOST_MATH_STD_USING\n    using namespace boost::math::constants;\n\n    T S, C, Q, D, f, a, b, q, delta, tolerance, current, prev;\n    unsigned long k;\n\n    // |x| >= |v|, CF2_ik converges rapidly\n    // |x| -> 0, CF2_ik fails to converge\n\n    BOOST_ASSERT(abs(x) > 1);\n\n    // Steed's algorithm, see Thompson and Barnett,\n    // Journal of Computational Physics, vol 64, 490 (1986)\n    tolerance = tools::epsilon<T>();\n    a = v * v - 0.25f;\n    b = 2 * (x + 1);                              // b1\n    D = 1 / b;                                    // D1 = 1 / b1\n    f = delta = D;                                // f1 = delta1 = D1, coincidence\n    prev = 0;                                     // q0\n    current = 1;                                  // q1\n    Q = C = -a;                                   // Q1 = C1 because q1 = 1\n    S = 1 + Q * delta;                            // S1\n    BOOST_MATH_INSTRUMENT_VARIABLE(tolerance);\n    BOOST_MATH_INSTRUMENT_VARIABLE(a);\n    BOOST_MATH_INSTRUMENT_VARIABLE(b);\n    BOOST_MATH_INSTRUMENT_VARIABLE(D);\n    BOOST_MATH_INSTRUMENT_VARIABLE(f);\n\n    for (k = 2; k < policies::get_max_series_iterations<Policy>(); k++)     // starting from 2\n    {\n        // continued fraction f = z1 / z0\n        a -= 2 * (k - 1);\n        b += 2;\n        D = 1 / (b + a * D);\n        delta *= b * D - 1;\n        f += delta;\n\n        // series summation S = 1 + \\sum_{n=1}^{\\infty} C_n * z_n / z_0\n        q = (prev - (b - 2) * current) / a;\n        prev = current;\n        current = q;                        // forward recurrence for q\n        C *= -a / k;\n        Q += C * q;\n        S += Q * delta;\n        //\n        // Under some circumstances q can grow very small and C very\n        // large, leading to under/overflow.  This is particularly an\n        // issue for types which have many digits precision but a narrow\n        // exponent range.  A typical example being a \"double double\" type.\n        // To avoid this situation we can normalise q (and related prev/current)\n        // and C.  All other variables remain unchanged in value.  A typical\n        // test case occurs when x is close to 2, for example cyl_bessel_k(9.125, 2.125).\n        //\n        if(q < tools::epsilon<T>())\n        {\n           C *= q;\n           prev /= q;\n           current /= q;\n           q = 1;\n        }\n\n        // S converges slower than f\n        BOOST_MATH_INSTRUMENT_VARIABLE(Q * delta);\n        BOOST_MATH_INSTRUMENT_VARIABLE(abs(S) * tolerance);\n        BOOST_MATH_INSTRUMENT_VARIABLE(S);\n        if (abs(Q * delta) < abs(S) * tolerance) \n        { \n           break; \n        }\n    }\n    policies::check_series_iterations<T>(\"boost::math::bessel_ik<%1%>(%1%,%1%) in CF2_ik\", k, pol);\n\n    if(x >= tools::log_max_value<T>())\n       *Kv = exp(0.5f * log(pi<T>() / (2 * x)) - x - log(S));\n    else\n      *Kv = sqrt(pi<T>() / (2 * x)) * exp(-x) / S;\n    *Kv1 = *Kv * (0.5f + v + x + (v * v - 0.25f) * f) / x;\n    BOOST_MATH_INSTRUMENT_VARIABLE(*Kv);\n    BOOST_MATH_INSTRUMENT_VARIABLE(*Kv1);\n\n    return 0;\n}\n\nenum{\n   need_i = 1,\n   need_k = 2\n};\n\n// Compute I(v, x) and K(v, x) simultaneously by Temme's method, see\n// Temme, Journal of Computational Physics, vol 19, 324 (1975)\ntemplate <typename T, typename Policy>\nint bessel_ik(T v, T x, T* I, T* K, int kind, const Policy& pol)\n{\n    // Kv1 = K_(v+1), fv = I_(v+1) / I_v\n    // Ku1 = K_(u+1), fu = I_(u+1) / I_u\n    T u, Iv, Kv, Kv1, Ku, Ku1, fv;\n    T W, current, prev, next;\n    bool reflect = false;\n    unsigned n, k;\n    int org_kind = kind;\n    BOOST_MATH_INSTRUMENT_VARIABLE(v);\n    BOOST_MATH_INSTRUMENT_VARIABLE(x);\n    BOOST_MATH_INSTRUMENT_VARIABLE(kind);\n\n    BOOST_MATH_STD_USING\n    using namespace boost::math::tools;\n    using namespace boost::math::constants;\n\n    static const char* function = \"boost::math::bessel_ik<%1%>(%1%,%1%)\";\n\n    if (v < 0)\n    {\n        reflect = true;\n        v = -v;                             // v is non-negative from here\n        kind |= need_k;\n    }\n    n = iround(v, pol);\n    u = v - n;                              // -1/2 <= u < 1/2\n    BOOST_MATH_INSTRUMENT_VARIABLE(n);\n    BOOST_MATH_INSTRUMENT_VARIABLE(u);\n\n    if (x < 0)\n    {\n       *I = *K = policies::raise_domain_error<T>(function,\n            \"Got x = %1% but real argument x must be non-negative, complex number result not supported.\", x, pol);\n        return 1;\n    }\n    if (x == 0)\n    {\n       Iv = (v == 0) ? static_cast<T>(1) : static_cast<T>(0);\n       if(kind & need_k)\n       {\n         Kv = policies::raise_overflow_error<T>(function, 0, pol);\n       }\n       else\n       {\n          Kv = std::numeric_limits<T>::quiet_NaN(); // any value will do\n       }\n\n       if(reflect && (kind & need_i))\n       {\n           T z = (u + n % 2);\n           Iv = boost::math::sin_pi(z, pol) == 0 ? \n               Iv : \n               policies::raise_overflow_error<T>(function, 0, pol);   // reflection formula\n       }\n\n       *I = Iv;\n       *K = Kv;\n       return 0;\n    }\n\n    // x is positive until reflection\n    W = 1 / x;                                 // Wronskian\n    if (x <= 2)                                // x in (0, 2]\n    {\n        temme_ik(u, x, &Ku, &Ku1, pol);             // Temme series\n    }\n    else                                       // x in (2, \\infty)\n    {\n        CF2_ik(u, x, &Ku, &Ku1, pol);               // continued fraction CF2_ik\n    }\n    BOOST_MATH_INSTRUMENT_VARIABLE(Ku);\n    BOOST_MATH_INSTRUMENT_VARIABLE(Ku1);\n    prev = Ku;\n    current = Ku1;\n    T scale = 1;\n    for (k = 1; k <= n; k++)                   // forward recurrence for K\n    {\n        T fact = 2 * (u + k) / x;\n        if((tools::max_value<T>() - fabs(prev)) / fact < fabs(current))\n        {\n           prev /= current;\n           scale /= current;\n           current = 1;\n        }\n        next = fact * current + prev;\n        prev = current;\n        current = next;\n    }\n    Kv = prev;\n    Kv1 = current;\n    BOOST_MATH_INSTRUMENT_VARIABLE(Kv);\n    BOOST_MATH_INSTRUMENT_VARIABLE(Kv1);\n    if(kind & need_i)\n    {\n       T lim = (4 * v * v + 10) / (8 * x);\n       lim *= lim;\n       lim *= lim;\n       lim /= 24;\n       if((lim < tools::epsilon<T>() * 10) && (x > 100))\n       {\n          // x is huge compared to v, CF1 may be very slow\n          // to converge so use asymptotic expansion for large\n          // x case instead.  Note that the asymptotic expansion\n          // isn't very accurate - so it's deliberately very hard \n          // to get here - probably we're going to overflow:\n          Iv = asymptotic_bessel_i_large_x(v, x, pol);\n       }\n       else if((v > 0) && (x / v < 0.25))\n       {\n          Iv = bessel_i_small_z_series(v, x, pol);\n       }\n       else\n       {\n          CF1_ik(v, x, &fv, pol);                         // continued fraction CF1_ik\n          Iv = scale * W / (Kv * fv + Kv1);                  // Wronskian relation\n       }\n    }\n    else\n       Iv = std::numeric_limits<T>::quiet_NaN(); // any value will do\n\n    if (reflect)\n    {\n        T z = (u + n % 2);\n        T fact = (2 / pi<T>()) * (boost::math::sin_pi(z) * Kv);\n        if(fact == 0)\n           *I = Iv;\n        else if(tools::max_value<T>() * scale < fact)\n           *I = (org_kind & need_i) ? T(sign(fact) * sign(scale) * policies::raise_overflow_error<T>(function, 0, pol)) : T(0);\n        else\n         *I = Iv + fact / scale;   // reflection formula\n    }\n    else\n    {\n        *I = Iv;\n    }\n    if(tools::max_value<T>() * scale < Kv)\n      *K = (org_kind & need_k) ? T(sign(Kv) * sign(scale) * policies::raise_overflow_error<T>(function, 0, pol)) : T(0);\n    else\n      *K = Kv / scale;\n    BOOST_MATH_INSTRUMENT_VARIABLE(*I);\n    BOOST_MATH_INSTRUMENT_VARIABLE(*K);\n    return 0;\n}\n\n}}} // namespaces\n\n#endif // BOOST_MATH_BESSEL_IK_HPP\n\n", "meta": {"hexsha": "10118d97156f8c5ad5ca0aad4d6e65e3e17f9a5c", "size": 13843, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/math/special_functions/detail/bessel_ik.hpp", "max_stars_repo_name": "multi-os-engine/cinder-natj-binding", "max_stars_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "deps/cinder/include/boost/math/special_functions/detail/bessel_ik.hpp", "max_issues_repo_name": "multi-os-engine/cinder-natj-binding", "max_issues_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1074.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T15:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-22T20:28:39.000Z", "max_forks_repo_path": "deps/cinder/include/boost/math/special_functions/detail/bessel_ik.hpp", "max_forks_repo_name": "multi-os-engine/cinder-natj-binding", "max_forks_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 275.0, "max_forks_repo_forks_event_min_datetime": "2020-08-18T08:35:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:06:07.000Z", "avg_line_length": 30.7622222222, "max_line_length": 127, "alphanum_fraction": 0.5381059019, "num_tokens": 4193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5072669551689561}}
{"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 <string>\n\n#include <boost/numeric/mtl/mtl.hpp>\n \n\nusing namespace std;  \n\nstd::string program_dir; // Ugly global variable !!!\n\ntemplate <typename Matrix>\nvoid test(Matrix& A, const char* name)\n{\n    std::cout << \"\\n\" << name << \"\\n\";\n    A= mtl::mat::hilbert_matrix<>(4, 3);\n\n    string fname( mtl::io::join( program_dir, string(\"matrix_market/write_test_3_\") + string(name) + string(\".mtx\") ) );\n    cout << \"File name is \" << fname << \"\\nA is\\n\" << A;\n    \n    mtl::io::matrix_market_ostream oms(fname);\n    oms << A;\n    oms.close();\n\n    Matrix B, C; \n    B= mtl::io::matrix_market(fname);\n    cout << \"\\nRead back results in\\n\" << B;\n\n    C= A - B;\n    cout << \"\\nDifference is\\n\" << C << \"\\none_norm of it == \" << one_norm(C) << '\\n';\n}\n\n\nint main(int, char* argv[])\n{\n    using namespace mtl;\n\n    compressed2D<double>                             cdr(4, 3);\n    compressed2D<float>                              cfr(4, 3);\n    // compressed2D<int>                                cir(4, 3); // a Hilbert matrix as int is nonsense\n    compressed2D<std::complex<double> >              ccr(4, 3);\n\n    program_dir= mtl::io::directory_name(argv[0]);\n    test(cdr, \"compressed2D_double\");\n    test(cfr, \"compressed2D_float\");\n    test(ccr, \"compressed2D_complex\");\n\n    return 0;\n}\n", "meta": {"hexsha": "e7cd40f01f9477401fa6d156bfe00e3c72ae50ca", "size": 1773, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/matrix_market_write_3_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_market_write_3_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_market_write_3_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": 28.5967741935, "max_line_length": 120, "alphanum_fraction": 0.5961646926, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.5072493105771043}}
{"text": "\n// BLAS level 2\n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <iostream>\n#include <boost/numeric/bindings/atlas/cblas1.hpp>\n#include <boost/numeric/bindings/atlas/cblas2.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#ifdef F_USE_STD_VECTOR\n#include <vector>\n#include <boost/numeric/bindings/traits/std_vector.hpp> \n#endif \n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::cout;\nusing std::endl; \n\n#ifndef F_USE_STD_VECTOR\ntypedef ublas::vector<double> vct_t;\ntypedef ublas::matrix<double, ublas::row_major> m_t;\n#else\ntypedef ublas::vector<double, std::vector<double> > vct_t;\ntypedef ublas::matrix<double, ublas::column_major, std::vector<double> > m_t;\n#endif \n\nint main() {\n\n  cout << endl; \n\n  m_t m (10, 8);\n  init_m (m, times_plus<double> (10, 1, 1)); \n  print_m (m, \"m\"); \n  cout << endl; \n\n  vct_t v (8);\n  atlas::set (1., v);\n  print_v (v, \"v\"); \n  cout << endl; \n  vct_t vy (12); // vector size can be larger\n                // than corresponding matrix size \n\n  // vy = m v \n  atlas::gemv (CblasNoTrans, 1.0, m, v, 0.0, vy);\n  print_v (vy, \"vy = m v\"); \n  atlas::gemv (1.0, m, v, 0.0, vy);\n  print_v (vy, \"vy = m v\"); \n  atlas::gemv (m, v, vy);\n  print_v (vy, \"vy = m v\"); \n  cout << endl; \n\n  atlas::set (1, vy); \n  print_v (vy, \"vy\"); \n\n  // v = m^T vy \n  atlas::gemv (CblasTrans, 1.0, m, vy, 0.0, v);\n  print_v (v, \"v = m^T vy\"); \n  cout << endl; \n\n  // vy = 2.0 m v + 0.5 vy \n  atlas::set (1., v);\n  print_v (v, \"v\"); \n  print_v (vy, \"vy\"); \n  atlas::gemv (CblasNoTrans, 2.0, m, v, 0.5, vy);\n  print_v (vy, \"vy = 2.0 m v + 0.5 vy\"); \n  cout << endl; \n  cout << endl; \n\n  atlas::set (1, v); \n  atlas::set (0, vy); \n  print_v (v, \"v\"); \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // m[2..8][1..7] \n  ublas::matrix_range<m_t> mr (m, ublas::range (2, 8), ublas::range (1, 7)); \n  print_m (mr, \"mr = m[2..8][1..7]\");\n  cout << endl; \n  \n  // vy = m[2..8][1..7] v \n  atlas::gemv (mr, v, vy); \n  print_v (vy, \"vy = mr v\"); \n  cout << endl; \n\n  // vy = m[2..8][1..7]^T v \n  atlas::gemv (CblasTrans, 1.0, mr, v, 0.0, vy);\n  print_v (vy, \"vy = mr^T v\"); \n  cout << endl; \n\n  cout << endl; \n\n  // mrr = (m[2..8][1..7])[1..4][2..5]\n  ublas::matrix_range<ublas::matrix_range<m_t> > \n    mrr (mr, ublas::range (1, 4), ublas::range (2, 5)); \n  print_m (mrr, \"mrr = (m[2..8][1..7])[1..4][2..5]\");\n  cout << endl; \n\n  // vy = mrr v \n  atlas::set (0, vy); \n  atlas::gemv (CblasNoTrans, 1.0, mrr, v, 0.0, vy);\n  print_v (vy, \"vy = mrr v\"); \n  cout << endl; \n\n#ifdef F_COMPILATION_FAILURE\n  ublas::matrix_slice<m_t> \n    ms (m, ublas::slice (2, 1, 4), ublas::slice (1, 2, 4)); \n  print_m (ms, \"ms = m[2:1:4][1:2:4]\");\n  cout << endl; \n\n  atlas::set (0, vy); \n  atlas::gemv (CblasNoTrans, 1.0, ms, v, 0.0, vy);\n  print_v (vy, \"vy = ms v\"); \n  cout << endl; \n#endif \n\n}\n", "meta": {"hexsha": "9777f134153bf35159f7679bc40f3c04a5d8ac28", "size": 3024, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_matr22.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_matr22.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_matr22.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": 24.5853658537, "max_line_length": 77, "alphanum_fraction": 0.5803571429, "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5072493017794685}}
{"text": "//\n// Created by kevin on 3/12/18.\n//\n#include \"dubins.h\"\n\n#include <queue>\n#include <boost/math/constants/constants.hpp>\n\nnamespace {\n    const double twopi = 2. * boost::math::constants::pi<double>();\n    const double DUBINS_EPS = 1e-6;\n    const double DUBINS_ZERO = -1e-7;\n\n    inline double mod2pi(double x) {\n        if (x < 0 && x > DUBINS_ZERO)\n            return 0;\n        double xm = x - twopi * floor(x / twopi);\n        if (twopi - xm < .5 * DUBINS_EPS) xm = 0.;\n        return xm;\n    }\n\n    DubinsStateSpace::DubinsPath dubinsLSL(double d, double alpha, double beta) {\n        double ca = cos(alpha), sa = sin(alpha), cb = cos(beta), sb = sin(beta);\n        double tmp = 2. + d * d - 2. * (ca * cb + sa * sb - d * (sa - sb));\n        if (tmp >= DUBINS_ZERO) {\n            double theta = atan2(cb - ca, d + sa - sb);\n            double t = mod2pi(-alpha + theta);\n            double p = sqrt(std::max(tmp, 0.));\n            double q = mod2pi(beta - theta);\n            assert(fabs(p * cos(alpha + t) - sa + sb - d) < 2 * DUBINS_EPS);\n            assert(fabs(p * sin(alpha + t) + ca - cb) < 2 * DUBINS_EPS);\n            assert(mod2pi(alpha + t + q - beta + .5 * DUBINS_EPS) < DUBINS_EPS);\n            return DubinsStateSpace::DubinsPath(DubinsStateSpace::dubinsPathType[0], t, p, q);\n        }\n        return DubinsStateSpace::DubinsPath();\n    }\n\n    DubinsStateSpace::DubinsPath dubinsRSR(double d, double alpha, double beta) {\n        double ca = cos(alpha), sa = sin(alpha), cb = cos(beta), sb = sin(beta);\n        double tmp = 2. + d * d - 2. * (ca * cb + sa * sb - d * (sb - sa));\n        if (tmp >= DUBINS_ZERO) {\n            double theta = atan2(ca - cb, d - sa + sb);\n            double t = mod2pi(alpha - theta);\n            double p = sqrt(std::max(tmp, 0.));\n            double q = mod2pi(-beta + theta);\n            assert(fabs(p * cos(alpha - t) + sa - sb - d) < 2 * DUBINS_EPS);\n            assert(fabs(p * sin(alpha - t) - ca + cb) < 2 * DUBINS_EPS);\n            assert(mod2pi(alpha - t - q - beta + .5 * DUBINS_EPS) < DUBINS_EPS);\n            return DubinsStateSpace::DubinsPath(DubinsStateSpace::dubinsPathType[1], t, p, q);\n        }\n        return DubinsStateSpace::DubinsPath();\n    }\n\n    DubinsStateSpace::DubinsPath dubinsRSL(double d, double alpha, double beta) {\n        double ca = cos(alpha), sa = sin(alpha), cb = cos(beta), sb = sin(beta);\n        double tmp = d * d - 2. + 2. * (ca * cb + sa * sb - d * (sa + sb));\n        if (tmp >= DUBINS_ZERO) {\n            double p = sqrt(std::max(tmp, 0.));\n            double theta = atan2(ca + cb, d - sa - sb) - atan2(2., p);\n            double t = mod2pi(alpha - theta);\n            double q = mod2pi(beta - theta);\n            assert(fabs(p * cos(alpha - t) - 2. * sin(alpha - t) + sa + sb - d) < 2 * DUBINS_EPS);\n            assert(fabs(p * sin(alpha - t) + 2. * cos(alpha - t) - ca - cb) < 2 * DUBINS_EPS);\n            assert(mod2pi(alpha - t + q - beta + .5 * DUBINS_EPS) < DUBINS_EPS);\n            return DubinsStateSpace::DubinsPath(DubinsStateSpace::dubinsPathType[2], t, p, q);\n        }\n        return DubinsStateSpace::DubinsPath();\n    }\n\n    DubinsStateSpace::DubinsPath dubinsLSR(double d, double alpha, double beta) {\n        double ca = cos(alpha), sa = sin(alpha), cb = cos(beta), sb = sin(beta);\n        double tmp = -2. + d * d + 2. * (ca * cb + sa * sb + d * (sa + sb));\n        if (tmp >= DUBINS_ZERO) {\n            double p = sqrt(std::max(tmp, 0.));\n            double theta = atan2(-ca - cb, d + sa + sb) - atan2(-2., p);\n            double t = mod2pi(-alpha + theta);\n            double q = mod2pi(-beta + theta);\n            assert(fabs(p * cos(alpha + t) + 2. * sin(alpha + t) - sa - sb - d) < 2 * DUBINS_EPS);\n            assert(fabs(p * sin(alpha + t) - 2. * cos(alpha + t) + ca + cb) < 2 * DUBINS_EPS);\n            assert(mod2pi(alpha + t - q - beta + .5 * DUBINS_EPS) < DUBINS_EPS);\n            return DubinsStateSpace::DubinsPath(DubinsStateSpace::dubinsPathType[3], t, p, q);\n        }\n        return DubinsStateSpace::DubinsPath();\n    }\n\n    DubinsStateSpace::DubinsPath dubinsRLR(double d, double alpha, double beta) {\n        double ca = cos(alpha), sa = sin(alpha), cb = cos(beta), sb = sin(beta);\n        double tmp = .125 * (6. - d * d + 2. * (ca * cb + sa * sb + d * (sa - sb)));\n        if (fabs(tmp) < 1.) {\n            double p = twopi - acos(tmp);\n            double theta = atan2(ca - cb, d - sa + sb);\n            double t = mod2pi(alpha - theta + .5 * p);\n            double q = mod2pi(alpha - beta - t + p);\n            assert(fabs(2. * sin(alpha - t + p) - 2. * sin(alpha - t) - d + sa - sb) < 2 * DUBINS_EPS);\n            assert(fabs(-2. * cos(alpha - t + p) + 2. * cos(alpha - t) - ca + cb) < 2 * DUBINS_EPS);\n            assert(mod2pi(alpha - t + p - q - beta + .5 * DUBINS_EPS) < DUBINS_EPS);\n            return DubinsStateSpace::DubinsPath(DubinsStateSpace::dubinsPathType[4], t, p, q);\n        }\n        return DubinsStateSpace::DubinsPath();\n    }\n\n    DubinsStateSpace::DubinsPath dubinsLRL(double d, double alpha, double beta) {\n        double ca = cos(alpha), sa = sin(alpha), cb = cos(beta), sb = sin(beta);\n        double tmp = .125 * (6. - d * d + 2. * (ca * cb + sa * sb - d * (sa - sb)));\n        if (fabs(tmp) < 1.) {\n            double p = twopi - acos(tmp);\n            double theta = atan2(-ca + cb, d + sa - sb);\n            double t = mod2pi(-alpha + theta + .5 * p);\n            double q = mod2pi(beta - alpha - t + p);\n            assert(fabs(-2. * sin(alpha + t - p) + 2. * sin(alpha + t) - d - sa + sb) < 2 * DUBINS_EPS);\n            assert(fabs(2. * cos(alpha + t - p) - 2. * cos(alpha + t) + ca - cb) < 2 * DUBINS_EPS);\n            assert(mod2pi(alpha + t - p + q - beta + .5 * DUBINS_EPS) < DUBINS_EPS);\n            return DubinsStateSpace::DubinsPath(DubinsStateSpace::dubinsPathType[5], t, p, q);\n        }\n        return DubinsStateSpace::DubinsPath();\n    }\n\n    DubinsStateSpace::DubinsPath dubins(double d, double alpha, double beta) {\n        if (d < DUBINS_EPS && fabs(alpha - beta) < DUBINS_EPS)\n            return DubinsStateSpace::DubinsPath(DubinsStateSpace::dubinsPathType[0], 0, d, 0);\n\n        DubinsStateSpace::DubinsPath path(dubinsLSL(d, alpha, beta)), tmp(dubinsRSR(d, alpha, beta));\n        double len, minLength = path.length();\n\n        if ((len = tmp.length()) < minLength) {\n            minLength = len;\n            path = tmp;\n        }\n        tmp = dubinsRSL(d, alpha, beta);\n        if ((len = tmp.length()) < minLength) {\n            minLength = len;\n            path = tmp;\n        }\n        tmp = dubinsLSR(d, alpha, beta);\n        if ((len = tmp.length()) < minLength) {\n            minLength = len;\n            path = tmp;\n        }\n        tmp = dubinsRLR(d, alpha, beta);\n        if ((len = tmp.length()) < minLength) {\n            minLength = len;\n            path = tmp;\n        }\n        tmp = dubinsLRL(d, alpha, beta);\n        if ((len = tmp.length()) < minLength)\n            path = tmp;\n        return path;\n    }\n}\n\nconst DubinsStateSpace::DubinsPathSegmentType DubinsStateSpace::dubinsPathType[6][3] = {\n        {DUBINS_LEFT, DUBINS_STRAIGHT, DUBINS_LEFT},\n        {DUBINS_RIGHT, DUBINS_STRAIGHT, DUBINS_RIGHT},\n        {DUBINS_RIGHT, DUBINS_STRAIGHT, DUBINS_LEFT},\n        {DUBINS_LEFT, DUBINS_STRAIGHT, DUBINS_RIGHT},\n        {DUBINS_RIGHT, DUBINS_LEFT, DUBINS_RIGHT},\n        {DUBINS_LEFT, DUBINS_RIGHT, DUBINS_LEFT}\n};\n\ndouble DubinsStateSpace::distance(double q0[3], double q1[3]) {\n    return rho_ * dubins(q0, q1).length();\n}\n\nDubinsStateSpace::DubinsPath DubinsStateSpace::dubins(double q0[3], double q1[3]) {\n    double x1 = q0[0], y1 = q0[1], th1 = q0[2];\n    double x2 = q1[0], y2 = q1[1], th2 = q1[2];\n    double dx = x2 - x1, dy = y2 - y1, d = sqrt(dx * dx + dy * dy) / rho_, th = atan2(dy, dx);\n    double alpha = mod2pi(th1 - th), beta = mod2pi(th2 - th);\n    return ::dubins(d, alpha, beta);\n}\n\nvoid DubinsStateSpace::interpolate(double q0[3], DubinsPath &path, double seg, double s[3]) {\n\n    if (seg < 0.0) seg = 0.0;\n    if (seg > path.length()) seg = path.length();\n\n    double phi, v;\n\n    s[0] = s[1] = 0.0;\n    s[2] = q0[2];\n\n    for (unsigned int i = 0; i < 3 && seg > 0; ++i) {\n        v = std::min(seg, path.length_[i]);\n        seg -= v;\n        phi = s[2];\n        switch (path.type_[i]) {\n            case DUBINS_LEFT:\n                s[0] += ( sin(phi+v) - sin(phi));\n                s[1] += (-cos(phi+v) + cos(phi));\n                s[2] = phi + v;\n                break;\n            case DUBINS_RIGHT:\n                s[0] += (-sin(phi-v) + sin(phi));\n                s[1] += ( cos(phi-v) - cos(phi));\n                s[2] = phi - v;\n                break;\n            case DUBINS_STRAIGHT:\n                s[0] += (v * cos(phi));\n                s[1] += (v * sin(phi));\n                break;\n        }\n    }\n\n    s[0] = s[0] * rho_ + q0[0];\n    s[1] = s[1] * rho_ + q0[1];\n\n}\n\nvoid DubinsStateSpace::sample(double q0[3], double q1[3], double step_size, double &length, std::vector<std::vector<double> > &points) {\n    DubinsPath path = dubins(q0, q1);\n    length = rho_ * path.length();\n\n    for (double seg=0.0; seg<=length; seg+=step_size){\n        double qnew[3] = {};\n        interpolate(q0, path, seg/rho_, qnew);\n        std::vector<double> v(qnew, qnew + sizeof qnew / sizeof qnew[0]);\n        points.push_back(v);\n    }\n    return;\n}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "e84b08e053a446f8e1fda30b556077e5d8645146", "size": 9394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Reedsshepp_Dubins/dubins.cpp", "max_stars_repo_name": "tj1432423/Graph_Search_Algorithm", "max_stars_repo_head_hexsha": "e62169cf49d38a8b9b7b9b7ebc4ac321d3657055", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-04T07:02:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T14:58:43.000Z", "max_issues_repo_path": "Reedsshepp_Dubins/dubins.cpp", "max_issues_repo_name": "tj1432423/Graph_Search_Algorithm", "max_issues_repo_head_hexsha": "e62169cf49d38a8b9b7b9b7ebc4ac321d3657055", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Reedsshepp_Dubins/dubins.cpp", "max_forks_repo_name": "tj1432423/Graph_Search_Algorithm", "max_forks_repo_head_hexsha": "e62169cf49d38a8b9b7b9b7ebc4ac321d3657055", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-19T00:53:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T22:50:45.000Z", "avg_line_length": 40.6666666667, "max_line_length": 136, "alphanum_fraction": 0.5227804982, "num_tokens": 2954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5072343936980045}}
{"text": "//\n//  multiply.cpp\n//  BGV-Adder\n//\n//  Created by Hindrik Stegenga on 27/10/2020.\n//  Copyright \u00a9 2020 RUG. All rights reserved.\n//\n\n#include \"multiply.hpp\"\n#include <helib/FHE.h>\n#include <NTL/ZZX.h>\n#include <NTL/tools.h>\n\nusing helib::Ctxt;\n\nlong compute_multiplication(i16 lhs, i16 rhs) {\n    long k = 128; // Security parameter\n    long L = 16; // Number of levels in the modulus default is 16\n    long c = 3; // Nr of columns in key switch matrix.\n    long w = 64; // secret key hamming weight\n        \n    long p = 1021; // plaintext base default = 1021\n    long d = 0; // Degree of field extension\n    long r = 1; // hensel lifting\n    \n    // Determine a value for m\n    auto m = helib::FindM(k, L, c, p, d, 0, 0);\n    // Setup context\n    auto context = helib::Context(m, p, r);\n    // Build mod chain\n    helib::buildModChain(context, L, c);\n    \n    \n    // Generating secret key and public key\n    NTL::ZZX encryption_polynomial = context.alMod.getFactorsOverZZ()[0];\n    auto secretKey = helib::SecKey(context);\n    secretKey.GenSecKey();\n    const helib::PubKey& publicKey = secretKey;\n       \n    // Initialize ciphertexts\n    Ctxt lhs_ciphertext(publicKey), rhs_ciphertext(publicKey);\n    \n    // Encrypt them using the public key\n    publicKey.Encrypt(lhs_ciphertext, NTL::ZZX(lhs));\n    publicKey.Encrypt(rhs_ciphertext, NTL::ZZX(rhs));\n    \n    \n    // Compute multiplication of a and b\n    lhs_ciphertext *= rhs_ciphertext;\n    \n    Ctxt cipher_result = lhs_ciphertext;\n    \n    // Decrypt the results using secret key and convert back from\n    // polynomial representation to numeric.\n    long return_value = 0;\n    NTL::ZZX plaintext_result;\n    // Decrypt using secret key\n    secretKey.Decrypt(plaintext_result, cipher_result);\n    \n    // Compensate for negative numbers by checking if it's larger than p/2,\n    // In such case it wrapped around due to negative numbers\n    conv(return_value, plaintext_result[0]);\n    if (return_value > p / 2) {\n        return_value += (-1 * p);\n    }\n\n    return return_value;\n}\n\n", "meta": {"hexsha": "086a0617602038ecc1c04881d1f869a7c5626000", "size": 2044, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGV-Adder/Algorithms/Multiplication/multiply.cpp", "max_stars_repo_name": "HindrikStegenga/fhe-toolkit-macos", "max_stars_repo_head_hexsha": "6b65ac00c2a3cb64c487eadfc504eb17108ffd80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BGV-Adder/Algorithms/Multiplication/multiply.cpp", "max_issues_repo_name": "HindrikStegenga/fhe-toolkit-macos", "max_issues_repo_head_hexsha": "6b65ac00c2a3cb64c487eadfc504eb17108ffd80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BGV-Adder/Algorithms/Multiplication/multiply.cpp", "max_forks_repo_name": "HindrikStegenga/fhe-toolkit-macos", "max_forks_repo_head_hexsha": "6b65ac00c2a3cb64c487eadfc504eb17108ffd80", "max_forks_repo_licenses": ["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.2, "max_line_length": 75, "alphanum_fraction": 0.6531311155, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5072343893398765}}
{"text": "#pragma once\n\n\n#include \"Transport.hpp\"\n#include \"Common.hpp\"\n#include \"Math.hpp\"\n#include <boost/multiprecision/miller_rabin.hpp>\n#include \"LatticeEncryption.hpp\"\n#include \"Factoring.hpp\"\n#include <functional>\n#include <unordered_set>\n#include <boost/functional/hash.hpp>\n\nnamespace ligero\n{\n\n\n//==============================================================================\ntemplate <typename T, size_t Degree, size_t NbPrimesP, size_t NbPrimesQ>\nclass EncryptedCoordinator\n{\npublic:\n\n    using Q = nfl::poly_p<T, Degree, NbPrimesQ>;\n\n    ~EncryptedCoordinator() {\n        saveProtocolRecord();\n    }\n\n    EncryptedCoordinator(ProtocolConfig<T>& _config) : config(_config) {}\n\n    /*\n     * Host key generation in the coordinator side.\n     */\n        expected<int> hostGenerateKeyPair(ZeroMQCoordinatorTransport& trans) {\n            DBG(\"Starting keygen\");\n            // sum up shares of a_i\n            DBG(\"Waiting for a shares\");\n            auto maybeA = trans.awaitAggregateVectorInput<Q>(MessageType::PUBLIC_KEY_A_SHARES, trans.ids, std::plus<Q>(), 0);\n            if (hasError(maybeA)) { return getError(maybeA); }\n\n            std::tie(A, std::ignore) = getResult(maybeA);\n            trans.broadcast(MessageType::PUBLIC_KEY_A_VALUE, trans.ids, A);\n            A.invntt_pow_invphi();\n\n            DBG(\"Received and broadcasted a, waiting for b\");\n            auto maybeB = trans.awaitAggregateVectorInput<Q>(MessageType::PUBLIC_KEY_B_SHARES, trans.ids, std::plus<Q>(), 0);\n            if (hasError(maybeB)) { return getError(maybeB); }\n\n            std::tie(B, bi) = getResult(maybeB);\n            trans.broadcast(MessageType::PUBLIC_KEY_B_VALUE, trans.ids, B);\n            B.invntt_pow_invphi();\n\n            DBG(\"Received and broadcasted b\");\n            return 0;\n        }\n\n        std::vector<std::vector<mpz_class>>\n            pruneAndReorderShares(\n                const std::vector<mpz_class> &as,\n                const std::vector<mpz_class> &bs,\n                const std::vector<int> &flags,\n                int numAlphas,\n                std::vector<size_t> bucketSize) {\n\n            assert(as.size() == flags.size());\n            assert(bs.size() == flags.size());\n\n            std::vector<std::vector<mpz_class>> result;\n\n            int k = 0;\n            for (int c = 0; c < numAlphas; ++c) {\n                int j = 0;\n\n                std::vector<mpz_class> col;\n                for (int r = 0; r < bucketSize[c]; ++r) {\n                    if (flags[k] == 1) {\n                        col.push_back(as[k]);\n                        col.push_back(bs[k]);\n                    } else {\n                    }\n                    k++;\n                }\n                result.push_back(col);\n            }\n\n            return result;\n        }\n\n        bool checkGCD(bool special,\n                      const SocketId &sid, \n                      const std::vector<mpz_class>& p_shares, \n                      const std::vector<mpz_class>& q_shares, \n                      const std::vector<mpz_class>& candidates,\n                      const std::vector<mpz_class> &x,\n                      const std::vector<mpz_class> &y,\n                      const std::vector<mpz_class> &z,\n                      mpz_class gcdRX,\n                      const std::vector<mpz_class> ss)\n        {\n            auto [alphasGCD, _drop_val] = math::fixed_bucket_n_primes(3*config.pbs() + 210, primesGCD, config.tauLimitBit());\n            const int bucketSize = lrint(floor(double(primesGCD) / double(alphasGCD.size())));\n            DBG(\"bucketSize = \" << bucketSize);\n            DBG(\"alphasGCD.size() = \" << alphasGCD.size());\n\n            std::vector<mpz_class> ax_shares(primesGCD);\n            std::vector<mpz_class> by_shares(primesGCD);\n\n            DBG(\"p_shares.size() = \" << p_shares.size());\n            assert(x.size() >= (p_shares.size() * alphasGCD.size()));\n            assert(y.size() >= (p_shares.size() * alphasGCD.size()));\n            assert(z.size() >= (p_shares.size() * alphasGCD.size()));\n\n            std::vector<mpz_class> rCRTs;\n            rCRTs.resize(p_shares.size() * alphasGCD.size());\n            std::vector<mpz_class> p_plus_qCRTs(p_shares.size() * alphasGCD.size());\n\n            const mpz_class maybeOne = special ? 1 : 0;\n            {\n                int rc = 0;\n                for (int i = 0; i < candidates.size(); ++i) {\n\n                    // a = random number\n                    auto aCRT = math::crt_deconstruct(gcdRX, alphasGCD);\n                    assert(aCRT.size() == alphasGCD.size());\n\n                    // b = p_i + q_i - maybeOne\n                    auto bCRT = math::crt_deconstruct(p_shares[i] + q_shares[i] - maybeOne, alphasGCD);\n                    assert(bCRT.size() == alphasGCD.size());\n\n                    for (int j = 0; j < aCRT.size(); ++j) {\n                        rCRTs[rc] = aCRT[j];\n                        ax_shares[rc] = rCRTs[rc] - x[rc];\n                        p_plus_qCRTs[rc] = bCRT[j];\n                        by_shares[rc] = p_plus_qCRTs[rc] - y[rc];\n                        ++rc;\n                    }\n                }\n            }\n\n            {\n                int k = 0;\n                for (int i = 0; i < bucketSize; ++i) {\n                    for (int j = 0; j < alphasGCD.size(); ++j) {\n                        ax_shares[k] = math::mod(ax_shares[k], alphasGCD[j]);\n                        by_shares[k] = math::mod(by_shares[k], alphasGCD[j]);\n                        ++k;\n                    }\n                }\n            }\n\n            // here check if that is what party sent\n            {\n                auto axbyShareItem = axby_sharesGCD.find(sid);\n                if (axbyShareItem == axby_sharesGCD.end()) {\n                    LOG(INFO) << \"Failed to find axby GCD share for \" << sid;\n                    return false;\n                }\n                auto [axFromParty, byFromParty] = axbyShareItem->second.first;\n                if ((ax_shares.size() != axFromParty.size()) ||\n                    (by_shares.size() != byFromParty.size())) {\n                    LOG(INFO) << \"ax/by computed size \" << ax_shares.size() << \" does not match ax/by size from party \" << sid;\n                    return false;\n                }\n\n                for (size_t i = 0; i < ax_shares.size(); i++) {\n                    if (ax_shares[i] != axFromParty[i]) {\n                        LOG(INFO) << \"Computed ax[\" << i << \"] = \" << ax_shares[i] << \" does not match ax from party \" << axFromParty[i] << \" for party \" << sid;\n                        return false;\n                    }\n                    if (by_shares[i] != byFromParty[i]) {\n                        LOG(INFO) << \"Computed by[\" << i << \"] = \" << by_shares[i] << \" does not match by from party \" << byFromParty[i] << \" for party \" << sid;\n                        return false;\n                    }\n                }\n            }\n\n\n            // now lets check axbyGCD\n            std::vector<mpz_class> axbyGCD;\n            axbyGCD.resize(axGCD.size());\n            {\n                std::vector<mpz_class> ssGCD;\n                int k = 0;\n                ssGCD.resize(ss.size());\n                LOG(INFO) << \"candidates.size() \" << candidates.size();\n                LOG(INFO) << \"bucketSize \" << bucketSize;\n                for (size_t i = 0; i < bucketSize; ++i) {\n                    ssGCD[i] = ss[i] * candidates[i];\n                    for (size_t j = 0; j < alphasGCD.size(); ++j) {\n                        axbyGCD[k] = math::mod((axGCD[k] * p_plus_qCRTs[k] + byGCD[k] * rCRTs[k] + z[k] + ssGCD[i]), alphasGCD[j]);\n                        ++k;\n                    }\n                }\n            }\n\n            auto axbyGCD_share = zcrt_shares.find(sid);\n            if (axbyGCD_share == zcrt_shares.end()) {\n                LOG(INFO) << \"Could not find encrypted axbyGCD share for \" << sid;\n                return false;\n            }\n            std::vector<mpz_class> axbyGCDFromParty = axbyGCD_share->second.first;\n\n            if (axbyGCDFromParty.size() != axbyGCD.size()) {\n                return false;\n            }\n\n            for (size_t i = 0; i < axbyGCD.size(); i++) {\n                if (axbyGCD[i] != axbyGCDFromParty[i]) {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n\n        bool checkJacobi(bool special,\n                         const SocketId &sid, \n                         const std::vector<mpz_class>& p_shares, \n                         const std::vector<mpz_class>& q_shares, \n                         const std::vector<mpz_class>& candidates, \n                         mpz_class gammaSeedValue,\n                         const std::vector<mpz_class>& gvShare)\n        {\n            std::vector<mpz_class> engine = math::generateRandomVector(gammaSeedValue, kJacobiNumberOfRandomValues, 2048);\n            std::vector<mpz_class> gammaValues(p_shares.size());\n            size_t engineCount = 0;\n\n            {\n                mpz_t one;\n                mpz_init(one);\n                mpz_set_ui(one, 1);\n\n                mpz_t gcdResult;\n                mpz_init(gcdResult);\n\n                for (int i = 0; i < p_shares.size(); ++i) {\n                    const mpz_class &N = candidates[i];\n\n                    DBG(\" N % 2 = 1; N = \" << N);\n                    // We expect that N is 3 (mod 4), and therefore must be odd.\n                    assert(N % 2 == 1);\n\n                    while (1) {\n                        mpz_class g = engine[engineCount];\n                        ++engineCount;\n                        if (engineCount >= engine.size()) {\n                            engineCount = 0;\n                            DBG(\"Regenerating random values for Jacobi gamma values\");\n                            engine = math::generateRandomVector(engine[0], kJacobiNumberOfRandomValues,2048);\n                        }\n\n                        g = g % N;\n                        assert(g != 0);\n\n                        DBG(\"g = \" << g);\n                        if (mpz_jacobi(g.get_mpz_t(), N.get_mpz_t()) == 1) {\n                            gammaValues[i] = g;\n                            break;\n                        }\n                    }\n\n                    // Sanity check, assert if gcd(gammaValues[i], N) == 1\n                    mpz_gcd(gcdResult, gammaValues[i].get_mpz_t(), N.get_mpz_t());\n                    assert(mpz_cmp(gcdResult, one) == 0);\n\n                    // Export \n                }\n\n                mpz_clear(one);\n                mpz_clear(gcdResult);\n            }\n\n            // Now Verify that gammaValues are equal\n            if (gvShare.size() != gammaValues.size()) {\n                LOG(INFO) << \"Party \" << sid << \" gamma values size \" << gvShare.size() \n                    << \" did not match computed gamma values size \" << gammaValues.size();\n                return false;\n            }\n\n            for (int i = 0; i < gammaValues.size(); ++i) {\n                const mpz_class &N = candidates[i];\n                mpz_class &g = gammaValues[i];\n\n                mpz_class exp = (special ? mpz_class(N + 1) : mpz_class(\n                            0)) - p_shares[i] - q_shares[i];\n\n                if (special) {\n                    if (p_shares[i] % 4 != 3 || q_shares[i] % 4 != 3) {\n                        DBG(\"special\");\n                        DBG(\"i = \" << i);\n                        DBG(\"p_shares[i] \" << p_shares[i]);\n                        DBG(\"p_shares[i] \" << q_shares[i]);\n                        assert(false);\n                    }\n                } else {\n                    if (p_shares[i] % 4 != 0 || q_shares[i] % 4 != 0) {\n                        DBG(\"ordinary\");\n                        DBG(\"i = \" << i);\n                        DBG(\"p_shares[i] \" << p_shares[i]);\n                        DBG(\"p_shares[i] \" << q_shares[i]);\n                        assert(false);\n                    }\n                }\n\n                // Sanity check before the division operator\n                assert(exp % 4 == 0);\n                exp /= 4;\n                g = math::powm(g, exp, N);\n\n                if (gammaValues[i] != gvShare[i]) {\n                    LOG(INFO) << \"Compute gamma value \" << gammaValues[i] \n                        << \" did not match shared gamma value \" << gvShare[i]\n                        << \" for party \" << sid;\n                    return false;\n                }\n            }\n            return true;\n        }\n\n\n        bool verifyNoModuli(ZeroMQCoordinatorTransport& transport,\n                            lattice::LatticeEncryption<T, Degree, NbPrimesP, NbPrimesQ>& e) {\n            LOG(INFO) << \"Verifying party randomness\";\n\n            bool passed = true;\n            std::vector<mpz_class> tauVector(Degree);\n            TripleVector _tv;\n            auto maybeXYZShares = transport.awaitAggregateVectorInput<TripleVector>\n                (\n                 MessageType::NO_MODULI_VERIFICATION_SHARES,\n                 ZeroMQCoordinatorTransport::ids,\n                 [](const TripleVector& a, const TripleVector& b) {\n                 return a;\n                 },\n                 _tv\n                );\n\n            if (hasError(maybeXYZShares)) {\n                DBG(\"Failed to receive randomness shares\");\n                transport.broadcast(MessageType::NO_MODULI_VERIFICATION_FINISHED, ZeroMQCoordinatorTransport::ids, false);\n                return false;\n            }\n\n\n            std::unordered_map<SocketId, TripleVector, boost::hash<SocketId>> xyzShares;\n\n            std::tie(std::ignore, xyzShares) = getResult(maybeXYZShares);\n\n            // Verify PS\n\n            std::vector<mpz_class> ashares(primesPS);\n            std::vector<mpz_class> bshares(primesPS);\n\n            std::vector<mpz_class> prime_shares;\n            // extract x, y, z\n            std::vector<mpz_class> x_shares(Degree, mpz_class(0)),\n                                   y_shares(Degree, mpz_class(0)),\n                                   z_shares(Degree, mpz_class(0));\n\n\n            std::unordered_map<SocketId, std::vector<mpz_class>, boost::hash<SocketId>> primeSharesMap;\n\n            if (passed) {\n\n                auto [alphasdummy, bucketSizedummy] = math::balanced_bucket_n_primes(\n                        config.pbs(), Degree - primesTOTAL, config.tauLimitBit(), 1);\n\n                for (auto it = xyzShares.begin(); it != xyzShares.end(); ++it ) {\n                    auto [xi, yzi] = it->second;\n                    auto [yi, zi] = yzi;\n\n                    std::vector<mpz_class> ai_shares(primesPS);\n                    std::vector<mpz_class> bi_shares(primesPS);\n\n                    int k = 0;\n                    for (size_t j = 0; j < alphasPS.size(); ++j) {\n                        for (size_t i = 0; i < bucketSizePS[j]; ++i) {\n                            x_shares[k] += xi[k];\n                            y_shares[k] += yi[k];\n                            z_shares[k] += zi[k];\n                            ai_shares[k] = xi[k] % alphasPS[j];\n                            bi_shares[k] = yi[k] % alphasPS[j];\n                            ashares[k] = (ashares[k] + ai_shares[k]) % alphasPS[j];\n                            bshares[k] = (bshares[k] + bi_shares[k]) % alphasPS[j];\n                            tauVector[k] = alphasPS[j];\n                            k++;\n                        }\n                    }\n\n                    // candidate generation\n                    for (size_t i = 0; i < bucketSizeCAN_value; ++i) {\n                        for (size_t j = 0; j < alphasCAN.size(); ++j) {\n                            x_shares[k] += xi[k];\n                            y_shares[k] += yi[k];\n                            z_shares[k] += zi[k];\n                            tauVector[k] = alphasCAN[j];\n                            k++;\n                        }\n                    }\n\n                    // GCD\n                    for (size_t i = 0; i < bucketSizeGCD_value; ++i) {\n                        for (size_t j = 0; j < alphasGCD.size(); ++j) {\n                            x_shares[k] += xi[k];\n                            y_shares[k] += yi[k];\n                            z_shares[k] += zi[k];\n                            tauVector[k] = alphasGCD[j];\n                            k++;\n                        }\n                    }\n\n                    // setting up tauVector for dummy\n                    for (size_t j = 0; j < alphasdummy.size(); ++j) {\n                        for (size_t i = 0; i < bucketSizedummy[j]; ++i) {\n                            tauVector[k] = alphasdummy[j];\n                            k++;\n                        }\n                    }\n\n\n\n                    bool special = it->first == ZeroMQCoordinatorTransport::ids[0];\n                    std::vector<std::vector<mpz_class>> valid_shares = pruneAndReorderShares(ai_shares, bi_shares, flags_can, alphasPS.size(), bucketSizePS);\n                    std::vector<mpz_class> prime_shares_i;\n                    std::vector<mpz_class> _alphas(alphasPS.size() + 1);\n                    std::vector<mpz_class> _coeffs(_alphas.size());\n                    for (size_t i = 0; i < alphasPS.size(); ++i) {\n                        _alphas[i] = alphasPS[i];\n                    }\n                    _alphas[_alphas.size() - 1] = mpz_class(4);\n\n\n                    std::vector<mpz_class> moduli(_alphas.size());\n                    size_t minRowSize = valid_shares[0].size();\n                    for (size_t i = 1; i < valid_shares.size(); ++i) {\n                        minRowSize = std::min(valid_shares[i].size(), minRowSize);\n                    }\n\n                    for (size_t i = 0; i < minRowSize; ++i) {\n                        for (size_t j = 0; j < alphasPS.size(); ++j) {\n                            _coeffs[j] = valid_shares[j][i];\n                        }\n                        _coeffs[_alphas.size() - 1] = (special ? mpz_class(3) : mpz_class(0));\n\n                        prime_shares_i.push_back(math::crt_reconstruct(_coeffs, moduli, _alphas));\n                    }\n\n                    primeSharesMap[it->first] = prime_shares_i;\n\n                    if (prime_shares.size() == 0) {\n                        prime_shares = prime_shares_i;\n                    } else {\n                        for (size_t cpi = 0; cpi < prime_shares_i.size(); cpi++) {\n                            prime_shares[cpi] += prime_shares_i[cpi];\n                        }\n                    }\n\n\n                }\n\n                // Check: eit[i] = ashares[i] * bshares[i] % tauvector[i]\n                {\n                    int k = 0;\n                    for (size_t j = 0; j < alphasPS.size() && passed; ++j) {\n                        for (size_t i = 0; i < bucketSizePS[j]; ++i) {\n                            if ((ashares[k] * bshares[k]) % tauVector[k] != eitPS[k]) {\n                                LOG(INFO) <<  \"Failed verification for pre-sieving\";\n                                DBG(\"ashares[k] = \" << ashares[k]);\n                                DBG(\"bshares[k] = \" << ashares[k]);\n                                DBG(\"ashares[k] * bshares[k] \\% tauVector[k] = \" << ashares[k] * bshares[k] % tauVector[k]);\n                                DBG(\"eitPS[k] = \" << eitPS[k]);\n                                passed = false;\n                                break;\n                            }\n                            k++;\n                        }\n                    }\n                }\n            }\n\n            const auto bucketSize = lrint(floor(double(primesCAN) / double(alphasCAN.size())));\n            const auto pq_size = std::min(bucketSize, lrint(floor(double(prime_shares.size()) / double(2))));\n\n            // Verify candidate generation\n            if (passed) {\n                \n                // Verify candidates equal to p_i * q_i\n                for (int i = 0; i < pq_size; ++i) {\n                    if (candidatesCAN[i] != prime_shares[2 * i] * prime_shares[2 * i + 1]) {\n                        LOG(INFO) << \"Failed verification for candidates modulus generation\";\n                        DBG(\"candidatesCAN[\" << i << \"] = \" << candidatesCAN[i]);\n                        DBG(\"prime_shares[2 * i] * prime_shares[2 * i + 1] = \" << prime_shares[2 * i] * prime_shares[2 * i + 1]);\n                        for (size_t j = 0; j < alphasPS.size(); j++) {\n                            DBG(\"candidatesCAN[\" << i << \"] \\% alphasPS[0] = \" << candidatesCAN[i] % alphasPS[j]);\n                            DBG(\"prime_shares[2 * i] * prime_shares[2 * i + 1] \\% alphasPS[0] = \" << (prime_shares[2 * i] * prime_shares[2 * i + 1]) % alphasPS[j]);\n                        }\n                        passed = false;\n                        break;\n                    }\n                }\n                if (passed) {\n                    // Run candidates through miller rabin\n                    for (int i = 0; i < pq_size; ++i) {\n                        if (boost::multiprecision::miller_rabin_test(MPInt(prime_shares[2 * i].get_mpz_t()), 4) &&\n                           boost::multiprecision::miller_rabin_test(MPInt(prime_shares[2 * i + 1].get_mpz_t()), 4)) {\n\n                            LOG(INFO) << \"Verification for Miller-Rabin test failed (both are primes according to Miller-Rabin test).\";\n                            DBG(\"prime_shares[\" << 2 * i << \"] = \" << prime_shares[2 * i]);\n                            DBG(\"prime_shares[\" << 2 * i + 1 << \"] = \" << prime_shares[2 * i + 1]);\n                            passed = false;\n                            break;\n                        }\n\n                    }\n                }\n            }\n\n\n            if (!passed) {\n\n                std::unordered_set<SocketId, boost::hash<SocketId>> cheatingParties;\n\n                auto maybeBadEventData = transport.awaitAggregateVectorInput<BadEventData<T, Degree, NbPrimesQ>>\n                    (\n                     MessageType::BAD_EVENT_DATA_SHARES,\n                     ZeroMQCoordinatorTransport::ids,\n                     [](const BadEventData<T, Degree, NbPrimesQ> & a, const BadEventData<T, Degree, NbPrimesQ>& b) {\n                     return a;\n                     },\n                     BadEventData<T, Degree, NbPrimesQ>(mpz_class(0), mpz_class(0), Q{0}, Q{0}, Q{0}, mpz_class(0), std::vector<mpz_class>())\n                    );\n\n                if (hasError(maybeBadEventData)) {\n                    LOG(INFO) << \"Failed to receive data shares from parties\";\n                    transport.broadcast(MessageType::BAD_EVENT_DATA_RESPONSE, ZeroMQCoordinatorTransport::ids, false);\n                    return false;\n                }\n\n                std::unordered_map<SocketId, BadEventData<T, Degree, NbPrimesQ>, boost::hash<SocketId>> badEventDataShares;\n                std::tie(std::ignore, badEventDataShares) = getResult(maybeBadEventData);\n\n                Q SiSum = Q{0};\n\n                for (auto it = badEventDataShares.begin(); it != badEventDataShares.end(); ++it) {\n\n                    SiSum = SiSum + it->second.si;\n\n                    // check ei bounding constaints, all elements should belong to (-80; 80)\n                    bool passedEIBoundingConstraintVerification = true;\n                    auto ei_coeffs = it->second.ei.poly2mpz();\n                    for (auto& eic : ei_coeffs) {\n                        mpz_class eicv = mpz_class(eic);\n                        if ((eicv > mpz_class(80)) ||\n                            (eicv < mpz_class(-80))) {\n\n                            LOG(INFO) << \"Failed check ei bounding constraints, should belong to (-80;80) for party \" << it->first;\n                            cheatingParties.insert(it->first);\n                            passedEIBoundingConstraintVerification = false;\n                        }\n                    }\n                    std::for_each(ei_coeffs.begin(), ei_coeffs.end(), mpz_clear);\n\n                    if (passedEIBoundingConstraintVerification) {\n                        // check bi == si * A + ei\n                        if (it->second.bi != it->second.si * A + it->second.ei) {\n                            LOG(INFO) << \"Failed check bi != si * A + ei for parry \" << it->first;\n                            cheatingParties.insert(it->first);\n                        }\n                    }\n                }\n\n\n                // Check that xshares match after decryption\n                {\n\n                    for (auto& sid : ZeroMQCoordinatorTransport::ids) {\n                        auto g_enc_x_s = g_enc_x_shares.find(sid);\n                        if (g_enc_x_s == g_enc_x_shares.end()) {\n                            LOG(INFO) << \"Could not find encrypted x share for \" << sid;\n                            cheatingParties.insert(sid);\n                        }\n                        std::pair<Q, Q> cypherText = g_enc_x_s->second;\n                        Q encX = cypherText.second - cypherText.first * SiSum;\n                        auto decX = e.eval_poly(encX, tauVector);\n                        auto xyzS = xyzShares.find(sid);\n                        if (xyzS == xyzShares.end()) {\n                            LOG(INFO) << \"Could not find x,y,z shares for \" << sid;\n                            cheatingParties.insert(sid);\n                        }\n                        auto [xi, yzi] = xyzS->second;\n\n                        // check if xi share for a given sid matches computed one\n                        if (decX.size() != xi.size()) {\n                            LOG(INFO) << \"Decrypted x share size \" << decX.size() << \" does not match expected x share size \" << xi.size() << \" for party \" << sid;\n                            cheatingParties.insert(sid);\n                        }\n\n                        for (size_t i = 0; i < decX.size(); i++) {\n                            if (mpz_class(decX[i]) != xi[i]) {\n                                LOG(INFO) << \"decrypted x[\" << i << \"] = \" << decX[i] << \" does not match original share x[\" << i << \"] = \" << xi[i] << \" for party \" << sid;\n                                cheatingParties.insert(sid);\n                            }\n                        }\n                        std::for_each(decX.begin(), decX.end(), mpz_clear);\n                    }\n                }\n\n                // check jacobi round and then jacobi and gcd round\n                for (auto sid: ZeroMQCoordinatorTransport::ids) {\n\n                    bool special = sid == ZeroMQCoordinatorTransport::ids[0];\n\n                    // check Jacobi round\n                    auto bothSharesItem = primeSharesMap.find(sid);\n                    if (bothSharesItem == primeSharesMap.end()) {\n                        LOG(INFO) << \"Failed to find primeShare for party \" << sid;\n                        cheatingParties.insert(sid);\n                        continue;\n                    }\n\n                    const auto bucketSize = lrint(floor(double(primesCAN) / double(alphasCAN.size())));\n                    const auto pq_size = std::min(bucketSize, lrint(floor(double(bothSharesItem->second.size()) / double(2))));\n\n                    std::vector<mpz_class> p_shares(pq_size);\n                    std::vector<mpz_class> q_shares(pq_size);\n                    for (int i = 0; i < pq_size; ++i) {\n                        p_shares[i] = bothSharesItem->second[2 * i];\n                        q_shares[i] = bothSharesItem->second[2 * i + 1];\n                    }\n\n                    // check Jacobi\n                    {\n                        p_shares = discardCandidates(p_shares, discardFlagsPostSieve);\n                        q_shares = discardCandidates(q_shares, discardFlagsPostSieve);\n\n                        auto ggsShareItem = ggsShares.find(sid);\n                        if (ggsShareItem == ggsShares.end()) {\n                            LOG(INFO) << \"Failed to find ggs share for party \" << sid;\n                            return false;\n                        }\n                        std::vector<mpz_class> gvShare = ggsShareItem->second;\n                        if (!checkJacobi(special, sid, p_shares, q_shares, candidatesPostSieve, gammaSeedAccum, gvShare)) {\n                            cheatingParties.insert(sid);\n                            continue;\n                        }\n                    }\n\n                    // check Jacobi and GCD Round\n                    {\n                        p_shares = discardCandidates(p_shares, discardFlagsJacobi);\n                        q_shares = discardCandidates(q_shares, discardFlagsJacobi);\n\n                        auto gammaValuesGCD_share = zcrt_shares.find(sid);\n                        if (gammaValuesGCD_share == zcrt_shares.end()) {\n                            LOG(INFO) << \"Could not find encrypted gammaValuesGCD share for \" << sid;\n                            cheatingParties.insert(sid);\n                            continue;\n                        }\n\n                        std::vector<mpz_class> gammaValuesGCDFromParty = gammaValuesGCD_share->second.second;\n\n                        if (!checkJacobi(special, sid, p_shares, q_shares, candidatesJacobi, gammaSeedJacobiAndGCD, gammaValuesGCDFromParty)) {\n                            cheatingParties.insert(sid);\n                            continue;\n                        }\n\n                        auto badEventDataItem = badEventDataShares.find(sid);\n                        if (badEventDataItem == badEventDataShares.end()) {\n                            cheatingParties.insert(sid);\n                            continue;\n                        }\n\n                        auto xyzS = xyzShares.find(sid);\n                        if (xyzS == xyzShares.end()) {\n                            LOG(INFO) << \"Could not find x,y,z shares for \" << sid;\n                            cheatingParties.insert(sid);\n                            continue;\n                        }\n                        auto [xi, yzi] = xyzS->second;\n                        auto [yi, zi] = yzi;\n                        std::vector<mpz_class> xgcd(primesGCD);\n                        std::vector<mpz_class> ygcd(primesGCD);\n                        std::vector<mpz_class> zgcd(primesGCD);\n                        {\n                            int k = primesPS + primesCAN;\n                            // GCD\n                            int gcd_i = 0;\n                            for (size_t i = 0; i < bucketSizeGCD_value; ++i) {\n                                for (size_t j = 0; j < alphasGCD.size(); ++j) {\n                                    xgcd[gcd_i] = xi[k];\n                                    ygcd[gcd_i] = yi[k];\n                                    zgcd[gcd_i] = zi[k];\n                                    gcd_i++;\n                                    k++;\n                                }\n                            }\n                        }\n                        if (!checkGCD(special,\n                                    sid,\n                                    p_shares,\n                                    q_shares,\n                                    candidatesJacobi,\n                                    xgcd,\n                                    ygcd,\n                                    zgcd,\n                                    badEventDataItem->second.gcdRX,\n                                    badEventDataItem->second.gcdSS)) {\n                            cheatingParties.insert(sid);\n                        }\n                    }\n                }\n\n                transport.broadcast(MessageType::BAD_EVENT_DATA_RESPONSE, ZeroMQCoordinatorTransport::ids, false);\n                LOG(INFO) << \"Party randomness verification failed\";\n\n                // kickout cheating parties\n                std::vector<SocketId> restarts;\n                for (auto sid : ZeroMQCoordinatorTransport::ids) {\n                    if (cheatingParties.find(sid) == cheatingParties.end()) {\n                        restarts.push_back(sid);\n                    }\n                }\n                auto success = transport.update_ids(restarts);\n                if (hasError(success)) {\n                    throw std::runtime_error(\"Sometimes went wrong. Failed to kickout cheating parties\");\n                }\n                else {\n                    LOG(INFO) << \"Update ids with \" << getResult(success) << \" parties\";\n                }\n\n                return false;\n            }\n\n            transport.broadcast(MessageType::NO_MODULI_VERIFICATION_FINISHED, ZeroMQCoordinatorTransport::ids, passed);\n            LOG(INFO) << \"Party randomness verification passed\";\n            return true;\n        }\n\n        std::tuple<std::vector<mpz_class>,\n                   std::vector<int>, \n                   std::vector<mpz_class>> computeEITAndFlags(std::array<mpz_t, Degree> c_mpz_t) {\n                       \n            std::vector<mpz_class> eit(primesPS);\n\n            int pq_size = bucketSizePS[0];\n            std::vector<int> flags(primesPS);\n            assert(eit.size() == flags.size());\n            std::vector<mpz_class> c(c_mpz_t.size());\n\n            for (size_t i = 0; i < c.size(); ++i) {\n                c[i] = mpz_class(c_mpz_t[i]);\n            }\n\n\n            mpz_t one;\n            mpz_init(one);\n            mpz_set_ui(one, 1);\n\n            mpz_t gcdResult;\n            mpz_init(gcdResult);\n\n\n            int k = 0;\n            for (int j = 0; j < alphasPS.size(); ++j) {\n\n                int ick = 0;\n                int sum = 0;\n                for (int i = 0; i < bucketSizePS[j]; ++i) {\n\n                    mpz_gcd(gcdResult, alphasPS[j].get_mpz_t(), c_mpz_t[k]);\n                    eit[k] = c[k];\n\n                    flags[k] = mpz_cmp(gcdResult, one) == 0;\n                    sum += flags[k];\n                    if (flags[k] == 1) {\n                        index_candidates[k] = ick++;\n                    } else {\n                        index_candidates[k] = -1;\n                    }\n\n                    k++;\n                }\n\n                if (sum < pq_size) {\n                    pq_size = sum;\n                }\n            }\n\n            // free mem\n            mpz_clear(one);\n            mpz_clear(gcdResult);\n            std::for_each(c_mpz_t.begin(), c_mpz_t.end(), mpz_clear);\n\n            return {eit, flags, c};\n        }\n\n    expected<std::tuple< std::vector<std::vector<mpz_class>>,  // eit_pruned\n             std::vector<mpz_class>,               // alphasPS_tick\n             std::vector<mpz_class>,               // c_can\n             std::vector<mpz_class>                // c_gcd\n            >>\n    hostPreSieving (\n            ZeroMQCoordinatorTransport& transport,\n            lattice::LatticeEncryption<T, Degree, NbPrimesP, NbPrimesQ>& e) {\n        using P = nfl::poly_p<T, Degree, NbPrimesP>;\n        using Q = nfl::poly_p<T, Degree, NbPrimesQ>;\n\n        std::tie(alphasPS, bucketSizePS) = math::balanced_bucket_n_primes(config.pbs(), primesPS, config.tauLimitBit(), 1);\n\n        std::tie(alphasCAN, bucketSizeCAN) = math::fixed_bucket_n_primes(config.pbs()+48, primesCAN, config.tauLimitBit());\n\n        std::vector<size_t> bucketSizeGCD;\n        std::tie(alphasGCD, bucketSizeGCD) = math::fixed_bucket_n_primes(3*config.pbs()+210, primesGCD, config.tauLimitBit());\n\n        // set equal buckets for bucketSizeCan and bucketSizeGCD\n        bucketSizeCAN_value = lrint(floor(double(primesCAN) / double(alphasCAN.size())));\n        for (int i = 0; i < bucketSizeCAN.size(); ++i) {\n            bucketSizeCAN[i] = bucketSizeCAN_value;\n        }\n        bucketSizeGCD_value = lrint(floor(double(primesGCD) / double(alphasGCD.size())));\n        for (int i = 0; i < bucketSizeGCD.size(); ++i) {\n            bucketSizeGCD[i] = bucketSizeGCD_value;\n        }\n\n        if (config.protocolMode() == ProtocolMode::RECORD) {\n            // get from parties\n\n            TripleVector _tv;\n            auto maybe_record = transport.awaitAggregateVectorInput<TripleVector>\n                (\n                 MessageType::RECORD_PROTOCOL_SHARES,\n                 ZeroMQCoordinatorTransport::ids,\n                 [](const TripleVector& a, const TripleVector& b) {\n                 return a;\n                 },\n                 _tv\n                );\n\n            if (hasError(maybe_record)) {\n                DBG(\"Failed to receive recorded shares\");\n                return getError(maybe_record);\n            }\n            std::tie(std::ignore, record_protocol_shares) = getResult(maybe_record);\n\n            transport.broadcast(MessageType::RECORD_PROTOCOL_RESPONSE, ZeroMQCoordinatorTransport::ids, int(1));\n        } else if (config.protocolMode() == ProtocolMode::REPLAY) {\n\n            loadProtocolRecord();\n            LOG(INFO) << \">>>>>>>>  Replaying experiment\";\n            auto maybe_replay = transport.awaitAggregateVectorInput<int>\n                (\n                 MessageType::REPLAY_PROTOCOL_SHARES,\n                 ZeroMQCoordinatorTransport::ids,\n                 [](const int a, const int& b) {\n                 return a;\n                 },\n                 0\n                );\n\n            LOG(INFO) << \"Received from all replaying parties...\";\n            if (hasError(maybe_replay)) {\n                LOG(INFO) << \"Failed to receive all replays\";\n                return getError(maybe_replay);\n            }\n\n            LOG(INFO) << \"Sending out shares... \" << record_protocol_shares.size();\n            size_t socketIndex = 0;\n            for ( auto it = record_protocol_shares.begin(); it != record_protocol_shares.end(); ++it ) {\n                LOG(INFO) << \"Sending shares \" << socketIndex << \" to party \" << ZeroMQCoordinatorTransport::ids[socketIndex];\n                transport.send(MessageType::REPLAY_PROTOCOL_RESPONSE, ZeroMQCoordinatorTransport::ids[socketIndex], it->second);\n                socketIndex++;\n            }\n        }\n\n        // Aggregate a matrix of `a` shares and broadcast the sum\n        std::pair<Q, Q> acc = {0, 0};\n        auto maybeAS = transport.awaitAggregateVectorInput<std::pair<Q, Q>>(\n            MessageType::ENCRYPTED_X_SHARES,\n            ZeroMQCoordinatorTransport::ids,\n            lattice::pair_add<Q>,\n            acc\n        );\n\n        if (hasError(maybeAS)) { return getError(maybeAS); }\n\n        std::tie(xsum_first, g_enc_x_shares) = getResult(maybeAS);\n\n        DBG(\"Received Enc(x) matrix.\");\n        DBG(\"Communication cost before = \" << transport.communicationCost);\n        transport.broadcast(MessageType::ENCRYPTED_X_VALUE, ZeroMQCoordinatorTransport::ids, xsum_first);\n        DBG(\"Communication cost after = \" << transport.communicationCost);\n        xsum_first.first.invntt_pow_invphi();\n        xsum_first.second.invntt_pow_invphi();\n        // The parties will take the previous sum and multiply in their shares of\n        // another random number `b_j,i,t`. These form shares of `e_i,t` which we\n        // sum then broadcast for partial decryption\n        auto maybeES = transport.awaitAggregateVectorInput<std::pair<Q, Q>>(\n            MessageType::ENCRYPTED_XY_PLUS_Z_SHARES,\n            ZeroMQCoordinatorTransport::ids,\n            lattice::pair_add<Q>,\n            std::pair<Q, Q>{0, 0}\n        );\n\n        if (hasError(maybeES)) { return getError(maybeES); }\n\n        std::tie(xyz_sum, xsum_final_shares) = getResult(maybeES);\n\n        DBG(\"Received Enc(e_i,t) matrix.\");\n        transport.broadcast(MessageType::ENCRYPTED_XY_PLUS_Z_VALUE, ZeroMQCoordinatorTransport::ids, xyz_sum);\n\n        xyz_sum.first.invntt_pow_invphi();\n        xyz_sum.second.invntt_pow_invphi();\n        // Now we finish the decryption, giving us a set of e_i,t values that\n        // we can use for validating the shares by gcd.\n        auto maybeEit_poly = transport.awaitAggregateVectorInput<Q>(\n            MessageType::PARTIAL_XY_MINUS_Z_SHARES,\n            ZeroMQCoordinatorTransport::ids,\n            std::plus<Q>(),\n            Q{0}\n        );\n\n        if (hasError(maybeEit_poly)) { return getError(maybeEit_poly); }\n\n        Q eit_poly;\n        std::tie(eit_poly, partial_xyz_shares) = getResult(maybeEit_poly);\n\n        // convert eit_poly to eit\n        std::vector<mpz_class> tauVector(Degree);\n        {\n            int tvk = 0;\n\n\n            // pre-sieving\n            for (size_t i = 0; i < alphasPS.size(); ++i) {\n                for (size_t j = 0; j < bucketSizePS[i]; ++j) {\n                    tauVector[tvk] = alphasPS[i];\n                    tvk++;\n                }\n            }\n\n            DBG(\"tvk << \" << tvk);\n            DBG(\"primesPS << \" << primesPS);\n            assert(tvk == primesPS);\n            tvk = primesPS;\n            // candidate generation\n            index_candidates.resize(Degree);\n            for (size_t j = 0; j < bucketSizeCAN_value; ++j) {\n                for (size_t i = 0; i < alphasCAN.size(); ++i) {\n                    index_candidates[tvk] = j;\n                    tauVector[tvk] = alphasCAN[i];\n                    tvk++;\n                }\n            }\n\n            // GCD\n            for (size_t j = 0; j < bucketSizeGCD_value; ++j) {\n                for (size_t i = 0; i < alphasGCD.size(); ++i) {\n                    if (j < 1) {\n                        index_candidates[tvk] = -2;\n                    } else {\n                        index_candidates[tvk] = -3;\n                    }\n                    tauVector[tvk] = alphasGCD[i];\n                    tvk++;\n                }\n            }\n\n            // fill the rest with dummy values from pre-sieving\n            for (; tvk < Degree; ++tvk) {\n                    tauVector[tvk] = alphasPS[0];\n            }\n        }\n\n        DBG(\"before eval poly\");\n\n        auto c_mpz_t = e.eval_poly(eit_poly, tauVector);\n\n        DBG(\"after eval poly\");\n        \n        // Need to compute presieve flags\n        std::vector<mpz_class> c;\n        std::tie(eitPS, flags_can, c) = computeEITAndFlags(c_mpz_t);\n        \n        transport.broadcast(MessageType::PS_SIEVING_FLAGS, ZeroMQCoordinatorTransport::ids, flags_can);\n        transport.writeToTranscript(MessageType::PS_SIEVING_FLAGS, flags_can);\n\n        std::vector<mpz_class> c_can(primesCAN);\n\n        eit_prunedPS = pruneAndReorderEIT(eitPS, flags_can, alphasPS.size());\n        auto alphasPS_tick = alphasPS;\n\n        alphasPS_tick.insert(alphasPS_tick.begin(), mpz_class(4));\n        for (int i = primesPS; i < primesPS + primesCAN; ++i) {\n            c_can[i - primesPS] = c[i];\n        }\n\n        std::vector<mpz_class> c_gcd(primesGCD);\n        for (int i = primesPS + primesCAN; i < primesPS + primesCAN + primesGCD; ++i) {\n            c_gcd[i - primesPS - primesCAN] = c[i];\n        }\n\n        return std::make_tuple(eit_prunedPS, alphasPS_tick, c_can, c_gcd);\n    }\n\n    expected<std::vector<mpz_class>>\n    hostModulusCandidates (\n        ZeroMQCoordinatorTransport& transport,\n        std::vector<std::vector<mpz_class>> eit_pruned,\n        std::vector<mpz_class> alphasPS_tick,\n        std::vector<mpz_class> c_can) {\n\n        DBG(\"Hosting modulus candidates\");\n        //auto [alphasCAN, _bsz] = math::fixed_bucket_n_primes(config.pbs()+48, primesCAN, config.tauLimitBit());\n        auto bucketSize = lrint(floor(double(primesCAN) / double(alphasCAN.size())));\n        if (bucketSize > eit_pruned.size()) {\n            bucketSize = eit_pruned.size();\n        }\n\n        // combine alphas into alphas_combined\n        std::vector<mpz_class> alphas_combined(alphasCAN.size() + alphasPS_tick.size());\n        int aci = 0;\n        for (size_t i = 0; i < alphasCAN.size(); ++i) {\n            alphas_combined[aci] = alphasCAN[i];\n            ++aci;\n        }\n        for (size_t i = 0; i < alphasPS_tick.size(); ++i) {\n            alphas_combined[aci] = alphasPS_tick[i];\n            ++aci;\n        }\n\n        DBG(\"Aggregate ax and by shares\");\n        // Step. 5 Parties send pair (ai-xi) , (bi-yi) to the coordinator and get it aggregated, so they learn a-x and b-y\n        using PairOfVec = std::pair<std::vector<mpz_class>, std::vector<mpz_class>>;\n        auto acc_pair = std::pair<std::vector<mpz_class>, std::vector<mpz_class>>(std::vector<mpz_class>(c_can.size()), std::vector<mpz_class>(c_can.size()));\n        auto maybe_ax_by_sum = transport.awaitAggregateVectorInput<PairOfVec>\n            (\n            MessageType::AX_BY_SHARES,\n            ZeroMQCoordinatorTransport::ids,\n            [](const PairOfVec& a, const PairOfVec& b) {\n            assert(a.first.size() == b.second.size());\n            assert(a.second.size() == b.first.size());\n\n            std::vector<mpz_class> rf(a.first.size());\n            std::vector<mpz_class> rs(a.second.size());\n\n            for(size_t i = 0; i < a.first.size(); ++i) {\n                rf[i] = a.first[i] + b.first[i];\n                rs[i] = a.second[i] + b.second[i];\n            }\n            return std::pair{rf, rs};\n            },\n            acc_pair\n        );\n\n        if (hasError(maybe_ax_by_sum)) {\n            DBG(\"Failed to receive ax and by\");\n            return getError(maybe_ax_by_sum);\n        }\n        PairOfVec ax_by_sum;\n        std::tie(ax_by_sum, ax_by_sum_shares) = getResult(maybe_ax_by_sum);\n\n        {\n            int k = 0;\n            for (int j = 0; j < bucketSize; ++j) {\n                for (int i = 0; i < alphasCAN.size(); ++i) {\n                    ax_by_sum.first[k] = ax_by_sum.first[k] % alphasCAN[i];\n                    ax_by_sum.second[k] = ax_by_sum.second[k] % alphasCAN[i];\n                    ++k;\n                }\n            }\n        }\n        ax_modulus = ax_by_sum.first;\n        by_modulus = ax_by_sum.second;\n        DBG(\"Broadcast ax and by values\");\n        transport.broadcast(MessageType::AX_BY_VALUE, ZeroMQCoordinatorTransport::ids, ax_by_sum);\n\n\n        // Step 6. Parties send (a-x)bi + (b-y)ai  - zi to the coordinator (special party sends a-x)bi+(b-y)ai - (a-x)(b-y) - zi - c) and get it aggregated.\n        auto maybe_ab = transport.awaitAggregateVectorInput<std::vector<mpz_class>>\n            (\n             MessageType::AXB_MINUS_BYA_SHARES,\n             ZeroMQCoordinatorTransport::ids,\n             [](const std::vector<mpz_class>& a, const std::vector<mpz_class>& b) {\n             assert(a.size() == b.size());\n\n             std::vector<mpz_class> result(a.size());\n\n             for(size_t i = 0; i < a.size(); ++i) {\n             result[i] = a[i] + b[i];\n             }\n             return result;\n             },\n             std::vector<mpz_class>(c_can.size())\n         );\n\n        if (hasError(maybe_ab)) {\n            DBG(\"Failed to receive ab\");\n            return getError(maybe_ab);\n        }\n        std::vector<mpz_class> ab;\n        std::tie(ab, axby_modulus) = getResult(maybe_ab);\n\n        DBG(\"Aggregate ab values\");\n\n        {\n            int k = 0;\n            for (int j = 0; j < bucketSize; ++j) {\n                for (int i = 0; i < alphasCAN.size(); ++i) {\n                    ab[k] = math::mod(ab[k] + c_can[k] - ax_by_sum.first[k] * ax_by_sum.second[k], alphasCAN[i]);\n                    ++k;\n                }\n            }\n        }\n\n        DBG(\"Reconstruct candidates\");\n        std::vector<mpz_class> candidates_raw(bucketSize);\n        DBG(\"bucketSize = \" << bucketSize);\n        DBG(\"eit_pruned.size = \" << eit_pruned.size());\n\n        int k = 0;\n        auto pq_size = bucketSize;\n        if (pq_size > eit_pruned.size()) {\n            pq_size = eit_pruned.size();\n        }\n        for (int i = 0; i < pq_size; ++i) {\n\n            std::vector<mpz_class> x(alphasCAN.size() + alphasPS_tick.size());\n\n            for (int zz = 0; zz < alphasCAN.size(); ++zz) {\n                x[zz] = mpz_class(ab[i * alphasCAN.size() + zz]);\n            }\n            for (int zz = 0; zz < alphasPS_tick.size(); ++zz) {\n                x[zz + alphasCAN.size()] = mpz_class(eit_pruned[i][zz]);\n            }\n\n            std::vector<mpz_class> coefs;\n            candidates_raw[k] = math::crt_reconstruct(x, coefs, alphas_combined);\n            for(int zz=1; zz < 127; ++zz)\n            {\n                mpz_t result;\n                mpz_init(result);\n                mpz_class prime = boost::math::prime(zz);\n                mpz_gcd(result, candidates_raw[k].get_mpz_t(),prime.get_mpz_t());\n                if(mpz_cmp_ui(result,1) != 0)\n                {\n                    LOG(INFO) << \"Candidate[\" << k << \"] = \" << candidates_raw[k] << \" is divisible by \" << boost::math::prime(zz);\n                    assert(false);\n                }\n                mpz_clear(result);\n            }\n            k++;\n        }\n\n        DBG(\"k = \" << k);\n\n        // Compute pq_size\n        std::vector<mpz_class> candidates(k);\n        for (int i = 0; i < k; ++i) {\n            candidates[i] = candidates_raw[i];\n        }\n\n        // Then we broadcast the candidates to the clients\n        DBG(\"Sending modulus candidates...\");\n        transport.broadcast(MessageType::MODULUS_CANDIDATE, ZeroMQCoordinatorTransport::ids, candidates);\n        transport.writeToTranscript(MessageType::MODULUS_CANDIDATE, candidates);\n        candidatesCAN = candidates;\n        int number_responded = 0;\n        transport.awaitAggregateVectorInput<int>(MessageType::SYNCHRONIZE_NOW\n                , ZeroMQCoordinatorTransport::ids\n                , std::plus<int>()\n                , number_responded);\n        return candidates;\n    }\n\n    expected<Unit> hostRegistration (ZeroMQCoordinatorTransport& transport) {\n        auto result = transport.awaitRegistration();\n\n        if (hasError(result)) { return getError(result); }\n\n        transport.broadcast(\n            MessageType::PROTOCOL_CONFIG,\n            ZeroMQCoordinatorTransport::ids,\n            config\n        );\n        return Unit{};\n    }\n\n    std::vector<std::vector<mpz_class>> pruneAndReorderEIT (\n            const std::vector<mpz_class>& eit,\n            const std::vector<int>& flags,\n            int numAlphas) {\n\n        assert (eit.size() == flags.size());\n\n        // Now we can construct a result matrix\n        std::vector<std::vector<mpz_class>> result;\n\n        // And finally we fill the result matrix compactly with valid shares from `as`\n        int k = 0;\n        size_t min_size = 0;\n        for (size_t c = 0; c < numAlphas; ++c) {\n\n            std::vector<mpz_class> col;\n            for (int r = 0; r < bucketSizePS[c]; ++r) {\n                if (flags[k] == 1) {\n                    col.push_back(eit[k]);\n                }\n                k++;\n            }\n            result.push_back(col);\n            if (min_size == 0) { min_size = col.size(); }\n            if (min_size > col.size()) { min_size = col.size(); }\n        }\n\n        std::vector<mpz_class> col(bucketSizePS[0], mpz_class(1));\n        result.insert(result.begin(), col);\n\n        minRowSize = min_size;\n        // resize and transpose\n        std::vector<std::vector<mpz_class>> transposed(min_size);\n\n        for (size_t i = 0; i < result.size(); ++i) {\n            for (size_t j = 0; j < min_size; ++j) {\n                transposed[j].push_back(result[i][j]);\n            }\n        }\n\n        return transposed;\n    }\n\n\n    expected<boost::dynamic_bitset<>> hostGCDandJacobiTest (\n        ZeroMQCoordinatorTransport& transport,\n        const std::vector<mpz_class>& c_gcd,\n        const std::vector<mpz_class>& candidates) {\n\n\n        DBG(\"hostGCDTest candidates.size() = \" << candidates.size());\n        const int bucketSize = lrint(floor(double(primesGCD) / double(alphasGCD.size())));\n\n        DBG(\"Broadcast begin GCD\" << candidates.size());\n        DBG(\"c_gcd.size()\" << c_gcd.size());\n        // First, we broadcast an ask for shares of a random value\n        transport.broadcast(MessageType::GCD_RAND_SHARES, ZeroMQCoordinatorTransport::ids);\n\n\n        DBG(\"Aggregate ax and by shares\");\n        // Step. 5 Parties send pair (ai-xi) , (bi-yi) to the coordinator and get it aggregated, so they learn a-x and b-y\n\n        auto acc_pair = std::pair{std::pair{std::vector<mpz_class>(c_gcd.size()),\n                                            std::vector<mpz_class>(c_gcd.size())},\n                                  mpz_class(0)};\n\n        auto maybe_result = transport.awaitAggregateVectorInput<PairOfVecGCD>\n            (\n             MessageType::GCD_AX_BY_SHARES,\n             ZeroMQCoordinatorTransport::ids,\n             [](const PairOfVecGCD& a, const PairOfVecGCD& b) {\n             auto [pair_a, at] = a;\n             auto [pair_b, bt] = b;\n             auto [af, as] = pair_a;\n             auto [bf, bs] = pair_b;\n             assert(af.size() == bf.size());\n             assert(as.size() == bs.size());\n\n             std::vector<mpz_class> rf(af.size());\n             std::vector<mpz_class> rs(as.size());\n\n             for(size_t i = 0; i < af.size(); ++i) {\n                 rf[i] = af[i] + bf[i];\n                 rs[i] = as[i] + bs[i];\n             }\n\n             mpz_class rt = at ^ bt;\n\n             return std::pair{std::pair{rf, rs}, rt};\n             },\n             acc_pair\n            );\n\n        if (hasError(maybe_result)) {\n            return getError(maybe_result);\n        }\n        PairOfVecGCD result_value;\n        std::tie(result_value, axby_sharesGCD) = getResult(maybe_result);\n\n        auto [pair_axby, g] = result_value;\n        gammaSeed = g;\n\n        auto [ax_sum, by_sum] = pair_axby;\n\n        {\n            int k = 0;\n            for (int j = 0; j < bucketSize; ++j) {\n                for (int i = 0; i < alphasGCD.size(); ++i) {\n                    ax_sum[k] = ax_sum[k] % alphasGCD[i];\n                    by_sum[k] = by_sum[k] % alphasGCD[i];\n                    ++k;\n                }\n            }\n        }\n\n        gammaSeedJacobiAndGCD = gammaSeed;\n        transport.broadcast(MessageType::AX_BY_VALUE, ZeroMQCoordinatorTransport::ids, std::pair{std::pair{ax_sum, by_sum}, gammaSeed});\n        axGCD = ax_sum;\n        byGCD = by_sum;\n\n        // Step 6. Parties send (a-x)bi + (b-y)ai  - zi to the coordinator (special party sends a-x)bi+(b-y)ai - (a-x)(b-y) - zi - c) and get it aggregated.\n        auto gcd_jacobi_pair = std::pair{std::vector<mpz_class>(c_gcd.size()),\n                                         std::vector<mpz_class>(config.lambda() * candidates.size(), mpz_class(1))};\n        auto maybe_zcrtsggs = transport.awaitAggregateVectorInput<std::pair<std::vector<mpz_class>, std::vector<mpz_class>>>\n            (\n             MessageType::AXB_MINUS_BYA_SHARES,\n             ZeroMQCoordinatorTransport::ids,\n             [](const std::pair<std::vector<mpz_class>, std::vector<mpz_class>>& pa,\n                const std::pair<std::vector<mpz_class>, std::vector<mpz_class>>& pb) {\n             auto [a, expGa] = pa;\n             auto [b, expGb] = pb;\n\n             assert(expGa.size() == expGb.size());\n             std::vector<mpz_class> expResult(expGb.size());\n             for (size_t i = 0; i < expResult.size(); ++i) {\n                expResult[i] = expGa[i] * expGb[i];\n             }\n             assert(a.size() == b.size());\n\n             std::vector<mpz_class> result(a.size());\n\n             for(size_t i = 0; i < a.size(); ++i) {\n             result[i] = a[i] + b[i];\n             }\n             return std::pair{result, expResult};\n             },\n             gcd_jacobi_pair\n         );\n\n        if (hasError(maybe_zcrtsggs)) { return getError(maybe_zcrtsggs); }\n\n        std::pair<std::vector<mpz_class>, std::vector<mpz_class>> zcrt_value;\n        std::tie(zcrt_value, zcrt_shares) = getResult(maybe_zcrtsggs);\n        std::vector<mpz_class> zCRTs;\n\n        std::tie(zCRTs, ggsGCD) = zcrt_value;\n\n        DBG(\"Aggregate ab values\");\n\n        {\n            int k = 0;\n            for (int j = 0; j < bucketSize; ++j) {\n                for (int i = 0; i < alphasGCD.size(); ++i) {\n                    zCRTs[k] = math::mod(zCRTs[k] + c_gcd[k] - ax_sum[k] * by_sum[k], alphasGCD[i]);\n                    ++k;\n                }\n            }\n        }\n        // reconstruct z from CRT representation\n        std::vector<mpz_class> zs(candidates.size());\n        int zc = 0;\n        DBG(\"candidates.size() = \" << candidates.size());\n        for (int i = 0; i < candidates.size(); ++i) {\n\n            // TODO: extract into a method\n            std::vector<mpz_class> x(alphasGCD.size());\n            for (int zz = 0; zz < alphasGCD.size(); ++zz) {\n                x[zz] = zCRTs[zc];\n                ++zc;\n            }\n\n            std::vector<mpz_class> coefs;\n            zs[i] = math::crt_reconstruct(x, coefs, alphasGCD);\n        }\n\n\n        // GCD: compute discard vector\n        DBG(\"Received `z`, continuing GCD test.\");\n        DBG(\"zs.size()\" << zs.size());\n        boost::dynamic_bitset<> discardGCD (zs.size());\n        {\n            {\n                mpz_t one;\n                mpz_init(one);\n                mpz_set_ui(one, 1);\n\n                mpz_t gcdResult;\n                mpz_init(gcdResult);\n                for (int i = 0; i < zs.size(); ++i) {\n                    DBG(\"i = \" << i);\n                    const mpz_class& N = candidates[i];\n                    DBG(\"N = \" << N);\n\n                    const mpz_class z = zs[i] % N;\n\n                    DBG(\"z = \" << z);\n                    DBG(\"before mpz_gcd\");\n                    mpz_gcd(gcdResult, N.get_mpz_t(), z.get_mpz_t());\n\n                    if (mpz_cmp(gcdResult, one) != 0) {\n                        discardGCD[i] = 1;\n                    }\n\n                }\n                mpz_clear(gcdResult);\n                mpz_clear(one);\n            }\n        }\n\n        assert(zs.size() == candidates.size());\n\n        // Jacobi: compute discard vector\n        boost::dynamic_bitset<> discardJacobi (candidates.size());\n        {\n\n            DBG(\"Taking gamma values modulo N\");\n            for (int i = 0; i < candidates.size(); ++i) {\n                for (int j = 0; j < config.lambda(); ++j) {\n                    const mpz_class& N = candidates[i];\n                    mpz_class& gg = ggsGCD[i * config.lambda() + j];\n                    mpz_class x = gg % N;\n\n                    DBG(\"x = \" << x);\n                    DBG(\"N = \" << N);\n                    DBG(\"ggs[\" << i << \"] =\" << ggsGCD[i * config.lambda() + j]);\n\n                    // Elimination\n                    if (x != 1 && x != (N - 1)) {\n                        discardJacobi[i] = 1;\n                    }\n                }\n            }\n        }\n\n        // Final step: merge discardGCD and discardJacobi\n        boost::dynamic_bitset<> discard (candidates.size());\n        DBG(\"hostGCDandJacobiTest candidates.size() = \" << candidates.size());\n        for (int i = 0; i < candidates.size(); ++i) {\n            DBG(\"discardGCD[\" << i << \"] = \" << discardGCD[i]);\n            DBG(\"discardJacobi[\" << i << \"] = \" << discardJacobi[i]);\n            discard[i] = discardGCD[i] | discardJacobi[i];\n        }\n\n        return discard;\n    }\n\n\n    expected<boost::dynamic_bitset<>> hostJacobiProtocol (\n        ZeroMQCoordinatorTransport& transport,\n        const std::vector<mpz_class>& candidates\n    ) {\n        // First, we broadcast an ask for shares of a gamma value\n        transport.broadcast(MessageType::GAMMA_SHARES, ZeroMQCoordinatorTransport::ids);\n\n        // Aggregate and broadcast gamma seed\n        auto maybeGammaSeed = transport.awaitAggregateVectorInput<mpz_class>(\n            MessageType::GAMMA_RANDOM_SEED_SHARES,\n            ZeroMQCoordinatorTransport::ids,\n            [](const mpz_class& a,\n               const mpz_class& b) { return a ^ b; },\n            mpz_class(0)\n        );\n\n        if (hasError(maybeGammaSeed)) { return getError(maybeGammaSeed); }\n\n        \n        std::tie(gammaSeedAccum, std::ignore) = getResult(maybeGammaSeed);\n\n        transport.broadcast(MessageType::GAMMA_RANDOM_SEED_VALUE, ZeroMQCoordinatorTransport::ids, gammaSeedAccum);\n\n        // Now the input we'll receive is a multiplied value into which\n        // we'll finally multiply g^(N+1) for each gamma/modulus pair.\n        // If the result is not +/-1 we discard the candidate and move on.\n        auto maybe_ggs = transport.awaitAggregateVectorInput<std::vector<mpz_class>>(\n            MessageType::EXPONENTIATED_GAMMA_VALUE,\n            ZeroMQCoordinatorTransport::ids,\n            [](const std::vector<mpz_class>& a, const std::vector<mpz_class>& b) {\n                std::vector<mpz_class> c(b.size());\n                for (size_t i = 0; i < c.size(); ++i) {\n                    c[i] = a[i] * b[i];\n                }\n                return c;\n            },\n            std::vector<mpz_class>(candidates.size(), mpz_class(1))\n        );\n\n        if (hasError(maybe_ggs)) { return getError(maybe_ggs); }\n\n        std::vector<mpz_class> ggs;\n        std::tie(ggs, ggsShares) = getResult(maybe_ggs);\n\n        boost::dynamic_bitset<> discard (candidates.size());\n\n        int discarded = 0;\n        for (int i = 0; i < candidates.size(); ++i) {\n            const mpz_class& N = candidates[i];\n            mpz_class& gg = ggs[i];\n            mpz_class x = gg % N;\n\n            // Elimination\n            if (x != 1 && x != (N - 1)) {\n                discard[i] = 1;\n                discarded++;\n            }\n        }\n        LOG(INFO) << \"After first Jacobi iteration \" << candidates.size() - discarded << \" candidates survived\";\n\n        return discard;\n    }\n\n    expected<Unit> hostThroughputTest(\n        ZeroMQCoordinatorTransport& transport,\n        throughput_test_config tconfig,\n        size_t throughput_cutoff\n    ) {\n        DBG(\"Host throughput test\");\n        auto survivor = transport.hostThroughputTest(tconfig, [&](size_t t) { return t > throughput_cutoff; });\n\n        // No party survive the test, quit without restarting\n        if (survivor.size() == 0) {\n            LOG(ERROR) << \"No party survives, Quiting.\";\n            return Error::TOO_FEW_PARTIES;\n        }\n        // Some parties survive but still too few to restart the protocol\n        else if (survivor.size() < kMinAmountOfPartiesRequired) {\n            LOG(INFO) << \"Too few survivors, killing the protocol and quiting.\";\n            // broadcast only to survivors because we don't start registration\n            transport.broadcast(MessageType::PROTOCOL_KILLED, survivor);\n            return Error::TOO_FEW_PARTIES;\n        }\n\n        // success\n        return Unit{};\n    }\n\n    expected<Unit> hostHelper(ZeroMQCoordinatorTransport& transport,\n        lattice::LatticeEncryption<T, Degree, NbPrimesP, NbPrimesQ>& enc,\n        bool needRegistration,\n        int *restartRemaining\n    ) {\n        // base case\n        if (*restartRemaining <= 0) {\n            return Error::TOO_MANY_RESTART;\n        }\n\n        auto result = registerAndHostRSACeremony(transport, enc, restartRemaining, needRegistration);\n        if (!hasError(result)) {\n            // No errors, we are good to go\n            return Unit{};\n        }\n\n        // There are some errors...\n        auto err = getError(result);\n        if (err == Error::TOO_FEW_PARTIES) {\n            transport.broadcast(MessageType::PROTOCOL_KILLED, ZeroMQCoordinatorTransport::ids);\n            LOG(INFO) << \"Too few parties left, killing the protocol and quiting.\";\n            return Error::TOO_FEW_PARTIES;\n        }\n        else if (err == Error::MODULUS_NOT_FOUND) {\n            // Since there are no kick out, restart without re-registration\n            (*restartRemaining)--;\n            return hostHelper(transport, enc, false, restartRemaining);\n        }\n        else if (err == Error::TIMED_OUT \n                || err == Error::OUT_OF_SYNC \n                || err == Error::DESERIALIZE_FAIL \n                || err == Error::RESTART)\n        {\n            // Kick out some parties and restart\n            auto parties = ZeroMQCoordinatorTransport::ids.size();\n            LOG(INFO) << \"Restarting the protocol with \" << parties << \" parties\";\n            clearPublicData();\n            config.numParties() = parties;\n            transport.parties() = parties;\n\n            (*restartRemaining)--;\n\n            transport.broadcast(MessageType::PROTOCOL_RESTART, ZeroMQCoordinatorTransport::ids);\n            return hostHelper(transport, enc, true, restartRemaining);\n        }\n        else {\n            LOG(INFO) << \"Coordinator got impossible error: \" << showError(err);\n            return Error::UNKNOWN_ERROR;\n        }\n\n        LOG(INFO) << \"Too many restart, coordinator aborting.\";\n        transport.broadcast(MessageType::PROTOCOL_KILLED, ZeroMQCoordinatorTransport::ids);\n        return Error::TOO_MANY_RESTART;\n    }\n\n    /** Host the RSA MPC ceremony. */\n    expected<Unit> host(\n        ZeroMQCoordinatorTransport& transport,\n        int *restartRemaining\n    ) {\n        // After running the throughput test,\n        // now we have enough parties to start the protocol\n\n        // Assumption:\n        //    Whenever error happened the transport will update `ids` then proxy the error\n\n        auto e = lattice::LatticeEncryption<T, Degree, NbPrimesP, NbPrimesQ>(config);\n        bool needRegistration = true;\n\n        return hostHelper(transport, e, needRegistration, restartRemaining);\n    }\n\n    expected<Unit> registerAndHostRSACeremony(\n        ZeroMQCoordinatorTransport& transport, \n        lattice::LatticeEncryption<T, Degree, NbPrimesP, NbPrimesQ>& enc,\n        int *restartRemainging,\n        bool registration = true\n    ) {\n        if (registration) {\n            auto result = hostRegistration(transport);\n            if (hasError(result)) { return getError(result); }\n        }\n\n        // Start timer\n        transport.myTimers.initialize_timer();\n        transport.myTimers.begin(1, \"RSA Ceremony\", transport.communicationCost);\n\n        // Kickoff the protocol\n        auto result = host_rsa_ceremony(transport, enc);\n        if (!hasError(result)) {\n            // RSA protocol success\n            transport.myTimers.end(1,\"RSA Ceremony\",transport.communicationCost);\n            return Unit{};\n        }\n\n        // Cleanup and proxy the error\n        transport.myTimers.reset();\n        return getError(result);\n    }\n\n    expected<int> host_rsa_ceremony(\n        ZeroMQCoordinatorTransport& transport,\n        lattice::LatticeEncryption<T, Degree, NbPrimesP, NbPrimesQ>& e\n        ) {\n\n        DBG(\"DBG001 GENERATE KEYS\");\n        transport.myTimers.begin(2,\"Key Generation\",transport.communicationCost);\n        transport.myTimers.begin(2,\"1.a. Overall speed\", transport.communicationCost);\n        auto keygen_success = hostGenerateKeyPair(transport);\n\n        if (hasError(keygen_success)) {\n            LOG(ERROR) << \"Keygen timed out!\";\n            transport.myTimers.end(2,\"Key Generation\",transport.communicationCost);\n            return getError(keygen_success);\n        }\n\n        DBG(\"DBG001 HOSTING\");\n\n        // Assign P1\n        transport.broadcast(MessageType::ASSIGNMENT_P1, std::vector<SocketId>{ZeroMQCoordinatorTransport::ids[0]});\n        DBG(\"Sending ASSIGNMENT_P1\");\n\n        // Assign Pn\n        transport.broadcast(MessageType::ASSIGNMENT_PN, std::vector<SocketId>(ZeroMQCoordinatorTransport::ids.begin() + 1, ZeroMQCoordinatorTransport::ids.end()));\n        DBG(\"Sending ASSIGNMENT_PN\");\n        transport.myTimers.end(2,\"Key Generation\",transport.communicationCost);\n\n\n        bool foundModuli = false;\n\n        // precompute bounds and M with min=4096 max=104729(10k th prime) and 2 tests\n        auto [Bs, Ms] = ligero::math::compute_m_b_vec(4096, 104729, 2);\n        auto nb_threads = 90;\n        auto postSieve = std::bind(ligero::math::test_factorizable_threaded, std::placeholders::_1, Bs, Ms, nb_threads);\n\n        transport.myTimers.begin(2,\"Pre-Sieving\",transport.communicationCost);\n        auto presieve_success = hostPreSieving(transport, e);\n\n        if (hasError(presieve_success)) {\n            LOG(ERROR) << \"Presieving timed out!\";\n            transport.myTimers.end(2,\"Pre-Sieving\",transport.communicationCost);\n            return getError(presieve_success);\n        }\n\n        auto [eit_pruned, alphasPS_tick, c_can, c_gcd] = getResult(presieve_success);\n\n        transport.myTimers.end(2,\"Pre-Sieving\",transport.communicationCost);\n\n        DBG(\"Beginning Candidate generation\");\n        transport.myTimers.begin(2,\"Generate Candidates\",transport.communicationCost);\n        auto candidates_success = hostModulusCandidates (transport, eit_pruned, alphasPS_tick, c_can);\n\n        if (hasError(candidates_success)) {\n            LOG(ERROR) << \"Modulus candidate timed out!\";\n            transport.myTimers.end(2,\"Generate Candidates\",transport.communicationCost);\n            return getError(candidates_success);\n        }\n\n        auto candidates = getResult(candidates_success);\n\n        transport.myTimers.end(2,\"Generate Candidates\",transport.communicationCost);\n        if (candidates.size() == 0) {\n            LOG(INFO) << \"No candidates found.\";\n            transport.broadcast(MessageType::NO_MODULI, ZeroMQCoordinatorTransport::ids);\n            if (!verifyNoModuli(transport, e)) {\n                LOG(INFO) << \"Failed randomness verification\";\n            }\n            return Error::MODULUS_NOT_FOUND;\n        }\n        // sanity check after modulus\n        {\n            DBG(\"Start sanity check\");\n            for (int i = 0; i < 100; ++i) {\n                auto x = boost::math::prime(i);\n                for (int j = 0; j < candidates.size(); ++j) {\n                    if (candidates[j] % x == 0) {\n                        DBG(\"candidates[\"<< j <<\"] = \" << candidates[j] << \" x = \" << x << \"candidates[j] mod x = \" << (candidates[j] % x));\n                        assert(false);\n                    }\n                }\n            }\n            DBG(\"Passed sanity check\");\n        }\n\n        boost::dynamic_bitset<> discardFlags;\n        {\n            DBG(\"Running postSieve\");\n            discardFlags = postSieve(std::vector<mpz_class>(candidates.data(), candidates.data() + candidates.size()));\n            discardFlagsPostSieve = discardFlags;\n            transport.broadcast(MessageType::POST_SIEVE, ZeroMQCoordinatorTransport::ids, discardFlags);\n            transport.writeToTranscript(MessageType::POST_SIEVE, discardFlags);\n            candidates = discardCandidates(candidates, discardFlags);\n            DBG(\"Completed postSieve\");\n            candidatesPostSieve = candidates;\n        }\n\n\n        for (int i = 0; i < 2; ++i) {\n            DBG(\"before sanity check\");\n            DBG(\"candidates[\" << i <<  \"] \" << candidates[i]);\n            assert(candidates[i] != 0);\n        }\n        // sanity check after postSieve\n        {\n            DBG(\"Start sanity check\");\n            for (int i = 0; i < 100; ++i) {\n                auto x = boost::math::prime(i);\n                for (int j = 0; j < candidates.size(); ++j) {\n                    if (candidates[j] % x == 0) {\n                        DBG(\"candidates[\"<<j<<\"] = \" << candidates[j] << \" x = \" << x << \"candidates[j] mod x = \" << (candidates[j] % x));\n                        assert(false);\n                    }\n                }\n            }\n            DBG(\"Passed sanity check\");\n        }\n        // Now we move on to our biprimality test. Here we run the\n        // jacobi test multiple times, eliminating candidates after each trial\n\n        {\n            DBG(\"Beginning Jacobi\");\n            transport.myTimers.begin(2,\"Jacobi Test\",transport.communicationCost);\n            auto jacobi_success = hostJacobiProtocol(transport, candidates);\n\n            if (hasError(jacobi_success)) {\n                LOG(ERROR) << \"Jacobi timed out!\";\n                transport.myTimers.end(2,\"Jacobi Test\",transport.communicationCost);\n                return getError(jacobi_success);\n            }\n\n            boost::dynamic_bitset<> discardFlags = getResult(jacobi_success);\n\n            transport.broadcast(MessageType::DISCARD_FLAGS, ZeroMQCoordinatorTransport::ids, discardFlags);\n            transport.writeToTranscript(MessageType::DISCARD_FLAGS, discardFlags);\n\n            candidates = discardCandidates(candidates, discardFlags);\n            candidatesJacobi = candidates;\n            transport.myTimers.end(2,\"Jacobi Test\",transport.communicationCost);\n        }\n\n        if (candidates.size() == 0) {\n            LOG(INFO) << \"No candidates found.\";\n            transport.broadcast(MessageType::NO_MODULI, ZeroMQCoordinatorTransport::ids);\n            if (!verifyNoModuli(transport, e)) {\n                LOG(INFO) << \"Failed randomness verification\";\n            }\n            return Error::MODULUS_NOT_FOUND;\n        }\n\n        DBG(\"After Jacobi candidates.size() = \" << candidates.size());\n        //// Complete the biprimality test with the GCD test, discarding any\n        //// other candidates that fail.\n        transport.myTimers.begin(2,\"GCD\",transport.communicationCost);\n\n        if (candidates.size() > 1) {\n            candidates.resize(1);\n        }\n        auto gcd_jacobi_success = hostGCDandJacobiTest (transport, c_gcd, candidates);\n\n        if (hasError(gcd_jacobi_success)) {\n            LOG(ERROR) << \"GCD and Jacobi timed out!\";\n            transport.myTimers.end(2,\"GCD\",transport.communicationCost);\n            return getError(gcd_jacobi_success);\n        }\n\n        discardFlags = getResult(gcd_jacobi_success);\n        discardFlagsJacobi = discardFlags;\n\n        transport.broadcast(MessageType::DISCARD_FLAGS, ZeroMQCoordinatorTransport::ids, discardFlags);\n        transport.writeToTranscript(MessageType::DISCARD_FLAGS, discardFlags);\n\n        transport.myTimers.end(2,\"GCD\",transport.communicationCost);\n\n        transport.myTimers.begin(2,\"Discarding\",transport.communicationCost);\n\n        candidates = discardCandidates(candidates, discardFlags);\n\n        // Here now, any modulus candidate remaining in our vector has passed\n        // the test.\n        if (candidates.size() == 0) {\n            LOG(INFO) << \"No candidates found.\";\n            transport.broadcast(MessageType::NO_MODULI, ZeroMQCoordinatorTransport::ids);\n            if (!verifyNoModuli(transport, e)) {\n                LOG(INFO) << \"Failed randomness verification\";\n            }\n            return Error::MODULUS_NOT_FOUND;\n        }\n        else {\n            LOG(INFO) << \"Found \" << candidates.size() << \" valid moduli:\";\n\n            for (int i = 0; i < candidates.size(); ++i){\n                LOG(INFO) << candidates[i];\n            }\n            transport.broadcast(MessageType::FOUND_MODULI, ZeroMQCoordinatorTransport::ids);\n            candidatesFinal = candidates;\n            foundModuli = true;\n\n            return 0;\n        }\n        transport.myTimers.end(2,\"Discarding\",transport.communicationCost);\n        numCandidates = candidates.size();\n\n        if (config.protocolMode() == ProtocolMode::RECORD || config.protocolMode() == ProtocolMode::REPLAY) {\n\n            // First check that candidates match\n            if (config.protocolMode() == ProtocolMode::REPLAY) {\n                if (candidatesFinal[0] != candidatesToCheck[0]) {\n                    LOG(FATAL) << \"Recorded moduli\" <<  candidatesToCheck[0] << \" does not match computed moduli\" << candidatesFinal[0];\n                }\n            }\n\n            // Below we are going to check if our output is a product of two primes\n            // There is no other way to check it than actually computing p and q as we\n            // cannot possibly factor 2048 bit numbers!\n            // TODO: This code has to be removed\n\n            //transport.myTimers.begin(2,\"Miller Rabin Tests\",transport.communicationCost);\n            using PairOfVec = std::pair<std::vector<mpz_class>, std::vector<mpz_class>>;\n            if (foundModuli) {\n                auto maybe_pq = transport.awaitAggregateVectorInput<PairOfVec>(\n                        MessageType::P_CLEAR_DEBUG,\n                        ZeroMQCoordinatorTransport::ids,\n                        [](const PairOfVec& a, const PairOfVec& b) {\n                        assert(a.first.size() == b.first.size());\n                        assert(a.second.size() == b.second.size());\n\n                        std::vector<mpz_class> fsum(a.first.size());\n                        std::vector<mpz_class> ssum(b.second.size());\n\n                        for (size_t i = 0; i < a.first.size(); ++i) {\n                        fsum[i] = a.first[i] + b.first[i];\n                        ssum[i] = a.second[i] + b.second[i];\n                        }\n                        return std::pair{fsum, ssum};\n                        },\n                        std::pair{std::vector<mpz_class>(candidates.size(), mpz_class(0)),\n                        std::vector<mpz_class>(candidates.size(), mpz_class(0))}\n                        );\n\n                if (hasError(maybe_pq)) {\n                    LOG(ERROR) << \"PQ timed out!\";\n                    return getError(maybe_pq);\n                }\n                auto [pq, pq_shares] = getResult(maybe_pq);\n\n                transport.broadcast(MessageType::P_CLEAR_DEBUG, ZeroMQCoordinatorTransport::ids, int(1));\n\n                // sanity check\n                for(size_t i = 0; i < pq.first.size(); ++i)\n                {\n                    assert(boost::multiprecision::miller_rabin_test(MPInt(pq.first[i].get_mpz_t()), 4));\n                    assert(boost::multiprecision::miller_rabin_test(MPInt(pq.second[i].get_mpz_t()), 4));\n                }\n\n                LOG(INFO) << \"Prime factorization of the candidates are: \";\n                if (config.protocolMode() == ProtocolMode::RECORD) {\n                    recorded_pq_first.resize(pq.first.size());\n                    recorded_pq_second.resize(pq.second.size());\n                }\n                for (size_t i = 0; i < pq.first.size(); ++i) {\n                    LOG(INFO) << pq.first[i];\n                    LOG(INFO) << pq.second[i];\n                    if (config.protocolMode() == ProtocolMode::RECORD) {\n                        recorded_pq_first[i] = pq.first[i];\n                        recorded_pq_second[i] = pq.second[i];\n                    }\n                    if (config.protocolMode() == ProtocolMode::REPLAY) {\n                        if (recorded_pq_first[i] != pq.first[i]) {\n                            LOG(FATAL) << \"Recorded prime factorization \" << recorded_pq_first[i] \n                                << \" does not match computed prime factorization \" << pq.first[i];\n                        }\n                        if (recorded_pq_second[i] != pq.second[i]) {\n                            LOG(FATAL) << \"Recorded prime factorization \" << recorded_pq_second[i] \n                                << \" does not match computed prime factorization \" << pq.second[i];\n                        }\n                    }\n                }\n\n                //transport.myTimers.end(2,\"Miller Rabin Tests\",transport.communicationCost);\n\n                assert(pq.first.size() == candidates.size());\n\n                for(size_t i = 0; i< pq.first.size(); ++i)\n                {\n                    assert(pq.first[i] * pq.second[i] == candidates[i]);\n                }\n                LOG(INFO) << \"All candidate moduli checked.\";\n                DBG(\"Done.\");\n\n            }\n        }\n\n        //transport.myTimers.end(1,\"RSA Ceremony\",transport.communicationCost);\n    }\n\n    void updatePublicData(const SocketId& id, PublicData *pdata_p) {\n\n        PublicData& pdata = *pdata_p;\n\n        // Keygen\n        {\n            dataExtractQ(pdata.A, A);\n\n            auto bi_share = bi.find(id);\n            if (bi_share  == bi.end()) {\n                LOG(FATAL) << \"Could not find bi share for \" << id;\n            }\n            Q bis = bi_share->second;\n            bis.invntt_pow_invphi();\n            dataExtractQ(pdata.bi, bis);\n            dataExtractQ(pdata.b, B);\n        }\n\n\n        {\n            auto g_enc_x_s = g_enc_x_shares.find(id);\n            if (g_enc_x_s == g_enc_x_shares.end()) {\n                LOG(FATAL) << \"Could not find encrypted x share for \" << id;\n            }\n            Q ci_1, ci_2;\n            std::tie(ci_1, ci_2) = g_enc_x_s->second;\n            ci_1.invntt_pow_invphi();\n            ci_2.invntt_pow_invphi();\n            dataExtractQ(pdata.ci_1, ci_1);\n            dataExtractQ(pdata.ci_2, ci_2);\n\n            dataExtractQ(pdata.c_1_prime, xyz_sum.first);\n            dataExtractQ(pdata.c_2_prime, xyz_sum.second);\n\n            auto di_share = partial_xyz_shares.find(id);\n            if (di_share  == partial_xyz_shares.end()) {\n                LOG(FATAL) << \"Could not find partial xyz share for \" << id;\n            }\n            Q dis = di_share->second;\n            dis.invntt_pow_invphi();\n            dataExtractQ(pdata.di, dis);\n        }\n\n\n        // Round 5\n        auto xf_share = xsum_final_shares.find(id);\n        if (xf_share == xsum_final_shares.end()) {\n            LOG(FATAL) << \"Could not find encrypted xsum_final share for \" << id;\n        }\n        Q ci_1_prime, ci_2_prime;\n        std::tie(ci_1_prime, ci_2_prime) = xf_share->second;\n        ci_1_prime.invntt_pow_invphi();\n        ci_2_prime.invntt_pow_invphi();\n        dataExtractQ(pdata.ci_1_prime, ci_1_prime);\n        dataExtractQ(pdata.ci_2_prime, ci_2_prime);\n\n        dataExtractQ(pdata.c_1, xsum_first.first);\n        dataExtractQ(pdata.c_2, xsum_first.second);\n\n        // Round 11 & 12\n        dataExtractVectorCRT<NbPrimesQ>(pdata.axGCD, axGCD);\n        dataExtractVectorCRT<NbPrimesQ>(pdata.byGCD, byGCD);\n\n        auto axbyGCD_share = zcrt_shares.find(id);\n        if (axbyGCD_share == zcrt_shares.end()) {\n            LOG(FATAL) << \"Could not find encrypted axbyGCD share for \" << id;\n        }\n        std::vector<mpz_class> axbyGCD = axbyGCD_share->second.first;\n        dataExtractVectorCRT<NbPrimesQ>(pdata.axbyGCD, axbyGCD);\n\n        // Misc\n        dataExtractVectorCRT<NbPrimesQ>(pdata.ps, alphasPS);\n        dataExtractVectorCRT<NbPrimesQ>(pdata.cans, alphasCAN);\n        dataExtractVectorCRT<NbPrimesQ>(pdata.gcds, alphasGCD);\n\n        pdata.degree = Degree;\n        pdata.p = NbPrimesP;\n        pdata.q = NbPrimesQ;\n        pdata.sigma = config.sigma();\n        pdata.lambda = config.lambda();\n        pdata.tau_limit_bit = config.tauLimitBit();\n\n        {\n            std::vector<mpz_class> _alphas(alphasPS.size() + 1);\n            std::vector<mpz_class> moduli(_alphas.size());\n\n            for (size_t i = 0; i < alphasPS.size(); ++i) {\n                _alphas[i] = alphasPS[i];\n            }\n            _alphas[_alphas.size() - 1] = mpz_class(4);\n\n            for (size_t i = 0; i < minRowSize; ++i) {\n                //prime_shares.push_back(math::crt_reconstruct(_coeffs, moduli(), _alphas));\n                mpz_class p = 1;\n                for (size_t i = 0; i < _alphas.size(); ++i) {\n                    p *= _alphas[i];\n                }\n\n                for (size_t i = 0; i < _alphas.size(); ++i) {\n                    mpz_class pa = p / _alphas[i];\n                    mpz_class x = math::mod(pa, _alphas[i]);\n                    moduli[i] = pa * math::mod_inverse(x, _alphas[i]);\n                }\n            }\n\n            size_t idx = 0;\n            for (; idx < candidatesCAN.size(); idx++) {\n                if (candidatesCAN[idx] == candidatesFinal[0]) {\n                    break;\n                }\n            }\n            auto candidateIndices = getCandidateIndices(idx, index_candidates);\n\n            std::vector<mpz_class> alphasPSprod_CAN, moduli_CAN;\n\n            mpz_class alphasPSprod = mpz_class(4);\n            for (size_t j = 0; j < alphasPS.size(); ++j) {\n                alphasPSprod *= alphasPS[j];\n            }\n\n            auto ax_by_sum_share = ax_by_sum_shares.find(id);\n            if (ax_by_sum_share == ax_by_sum_shares.end()) {\n                LOG(FATAL) << \"Could not find encrypted ax by share GCD share for \" << id;\n            }\n            auto [ax_shareCAN, by_shareCAN] = ax_by_sum_share->second;\n\n            {\n\n                std::vector<size_t> axbyindices;\n                std::vector<mpz_class> ax_shares, by_shares;\n                size_t alphaCANidx = 0;\n                for (auto j : candidateIndices.can) {\n                    std::vector<mpz_class> moduliCAN(moduli.size());\n                    mpz_class alphasPSprodCAN = alphasPSprod % alphasCAN[alphaCANidx];\n\n                    for (size_t i = 0; i < moduli.size(); i++) {\n                        moduliCAN[i] = moduli[i] % alphasCAN[alphaCANidx];\n                        moduli_CAN.push_back(moduliCAN[i]);\n                    }\n\n                    mpz_class axshares = ax_shareCAN[idx * alphasCAN.size() + alphaCANidx];\n                    mpz_class byshares = by_shareCAN[idx * alphasCAN.size() + alphaCANidx];\n\n                    for (size_t i = 0; i < NbPrimesQ; i ++) {\n                        mpz_class prime = mpz_class(nfl::params<uint64_t>::P[i]);\n                        ax_shares.push_back(positiveRemainder(axshares, prime));\n                        by_shares.push_back(positiveRemainder(byshares, prime));\n                    }\n\n                    size_t pos = alphasCAN.size() * idx + alphaCANidx;\n                    axbyindices.push_back(pos);\n                    alphasPSprod_CAN.push_back(alphasPSprodCAN);\n                    alphaCANidx++;\n                }\n\n                auto axby_modulus_share = axby_modulus.find(id);\n                if (axby_modulus_share  == axby_modulus.end()) {\n                    LOG(FATAL) << \"Could not find axby share for \" << id;\n                }\n                std::vector<mpz_class> axby_modulus_value = axby_modulus_share->second;\n\n                // axby\n                dataExtractSubVector<NbPrimesQ>(pdata.ax, ax_modulus, axbyindices);\n                dataExtractSubVector<NbPrimesQ>(pdata.by, by_modulus, axbyindices);\n\n                dataExtractSubVector<NbPrimesQ>(pdata.axby, axby_modulus_value, axbyindices);\n\n                // Extract data for CAN\n                dataExtractVectorCRT<NbPrimesQ>(pdata.prodcans, alphasPSprod_CAN);\n                dataExtractVectorCRT<NbPrimesQ>(pdata.coefsCAN,\tmoduli_CAN);\n                dataExtractVector(pdata.ax_shares,  ax_shares);\n                dataExtractVector(pdata.by_shares,  by_shares);\n\n                // Extract gamma for sigma protocol verification\n\n\n            }\n\n            auto ax_by_shareGCD = axby_sharesGCD.find(id);\n            if (ax_by_shareGCD == axby_sharesGCD.end()) {\n                LOG(FATAL) << \"Could not find encrypted ax by share GCD share for \" << id;\n            }\n            auto [pair_axby, gammaSeed] = ax_by_shareGCD->second;\n            auto [axshare, byshare] = pair_axby;\n\n\n            std::vector<mpz_class> alphasPSprod_GCD, moduli_GCD, ax_shares_GCD, by_shares_GCD;\n            size_t alphaGCDidx = 0;\n            for (auto j : candidateIndices.gcd) {\n                std::vector<mpz_class> moduliGCD(moduli.size());\n                mpz_class alphasPSprodGCD = alphasPSprod % alphasGCD[alphaGCDidx];\n                mpz_class axsharesGCD = axshare[alphaGCDidx];\n                mpz_class bysharesGCD = byshare[alphaGCDidx];\n\n                for (size_t i = 0; i < moduli.size(); i++) {\n                    moduliGCD[i] = moduli[i] % alphasGCD[alphaGCDidx];\n                    moduli_GCD.push_back(moduliGCD[i]);\n                }\n\n                alphasPSprod_GCD.push_back(alphasPSprodGCD);\n\n                for (size_t i = 0; i < NbPrimesQ; i++) {\n                    mpz_class prime = mpz_class(nfl::params<uint64_t>::P[i]);\n                    ax_shares_GCD.push_back(positiveRemainder(axsharesGCD, prime));\n                    by_shares_GCD.push_back(positiveRemainder(bysharesGCD, prime));\n                }\n                alphaGCDidx++;\n\n                std::vector<mpz_class> feed;\n                for (size_t i = 0; i < alphasGCD.size(); i++) {\n                    for (size_t j = 0; j < NbPrimesQ; j++) {\n                        mpz_class prime = mpz_class(nfl::params<uint64_t>::P[j]);\n                        mpz_class modGCD = math::mod(candidatesFinal[0], alphasGCD[i]);\n                        feed.emplace_back(positiveRemainder(modGCD,prime));\n                    }\n                }\n\n                dataExtractVector(pdata.finalModuli_GCD, feed);\n            }\n\n            // Extract data for GCD\n            dataExtractVectorCRT<NbPrimesQ>(pdata.coefsGCD,\tmoduli_GCD);\n            dataExtractVectorCRT<NbPrimesQ>(pdata.prodgcds, alphasPSprod_GCD);\n\n            dataExtractVector(pdata.by_shares_GCD,  by_shares_GCD);\n            dataExtractVector(pdata.ax_shares_GCD,  ax_shares_GCD);\n\n            // indices\n            pdata.indicesPS.assign(candidateIndices.ps.begin(),candidateIndices.ps.end());\n            pdata.indicesCAN.assign(candidateIndices.can.begin(),candidateIndices.can.end());\n            pdata.indicesGCD.assign(candidateIndices.gcd.begin(),candidateIndices.gcd.end());\n\n            pdata.tau = 1000;\n            // update special\n            pdata.special = id == ZeroMQCoordinatorTransport::ids[0];\n\n            // update bounding\n            std::vector<mpz_class> cans(alphasCAN);\n            cans.insert(cans.end(), alphasPS.begin(), alphasPS.end());\n            cans.insert(cans.end(), alphasGCD.begin(), alphasGCD.end());\n\n            std::vector<mpz_class> zbounds;\n\n            for (auto tau : cans) {\n                zbounds.emplace_back(tau * tau * config.numParties() * mpz_class(2)^mpz_class(config.lambda()));\n            }\n\n            mpz_class rbound = 2*config.lambda()*2*(config.sigma()*config.numParties()*mpz_class(2)^mpz_class(64*9)*Degree);                        \n\n            size_t size = alphasCAN.size() + alphasPS.size() + alphasGCD.size();\n            std::vector<mpz_class> rbounds(size, rbound);\n\n            auto params = {cans, cans, alphasCAN, {mpz_class(2)^mpz_class(1234)}, zbounds, rbounds};\n\n            std::vector<mpz_class> Cs;\n            for (auto param : params) {\n                for (auto bound : param) {\n                    auto [dd, C, D, log2D] = rephraseAs2Nct(bound);\n                    pdata.log2Ds.emplace_back(log2D);\n\n                    for (size_t modulusIdx = 0; modulusIdx < NbPrimesQ; modulusIdx++) {\n                        mpz_class prime(nfl::params<uint64_t>::P[modulusIdx]);\n                        mpz_class calc4 = math::mod(C, prime);\n                        mpz_class calc5 = math::mod(dd, prime);\n\n                        pdata.Cs.emplace_back(calc4.get_ui());\n                        pdata.Ds.emplace_back(calc5.get_ui());\n                    }\n                }\n            }\n\n            // Sigma protocol\n            pdata.gammaSeed = gammaSeedJacobiAndGCD;\n        }\n    }\n\n    void clearPublicData() {\n        axGCD.clear();\n        byGCD.clear();\n\n        bucketSizeCAN.clear();\n\n        partial_xyz_shares.clear();\n\n        g_enc_x_shares.clear();\n        xsum_final_shares.clear();\n        zcrt_shares.clear();\n        axby_sharesGCD.clear();\n        ax_by_sum_shares.clear();\n\n        axby_modulus.clear();\n\n        alphasPS.clear();\n        alphasCAN.clear();\n        alphasGCD.clear();\n\n        ax_modulus.clear();\n        by_modulus.clear();\n\n        candidatesCAN.clear();\n        candidatesFinal.clear();\n\n        index_candidates.clear();\n    }\n\n    void saveProtocolRecord() {\n        LOG(INFO) << \"Saving protocol recording into record.data file for \" << record_protocol_shares.size() << \" parties\";\n        boost::filesystem::ofstream record_ofs;\n        record_ofs.open(\"record.data\", std::ios::out | std::ios::binary);\n        boost::archive::binary_oarchive recordOA(record_ofs, boost::archive::no_header);\n        recordOA << record_protocol_shares;\n        recordOA << candidatesFinal;\n        recordOA << recorded_pq_first;\n        recordOA << recorded_pq_second;\n        record_ofs.close();\n    }\n\n    void loadProtocolRecord() {\n        LOG(INFO) << \"Loading protocol recording from record.data file\" << record_protocol_shares.size() << \" parties\";\n        boost::filesystem::ifstream record_ifs;\n        record_ifs.open(\"record.data\", std::ios::in | std::ios::binary);\n        boost::archive::binary_iarchive recordIA(record_ifs, boost::archive::no_header);\n        recordIA >> record_protocol_shares;\n        recordIA >> candidatesToCheck;\n        recordIA >> recorded_pq_first;\n        recordIA >> recorded_pq_second;\n        record_ifs.close();\n\n        // Check if protocol recorded data matches current setup\n        if (record_protocol_shares.size() != ZeroMQCoordinatorTransport::ids.size()) {\n            LOG(FATAL) << \"The number of parties in the recorded data \" << record_protocol_shares.size() << \" does not match current number of parties \" << ZeroMQCoordinatorTransport::ids.size();\n        }\n        \n    }\n\nprotected:\n    size_t numCandidates;\n    Q A, B;\n    lattice::cipher<T, Degree, NbPrimesQ>  xsum_first, xyz_sum;\n    ProtocolConfig<T>& config;\n    std::vector<mpz_class> axGCD, byGCD;\n    std::unordered_map<SocketId, Q, boost::hash<SocketId>> bi, partial_xyz_shares;\n    std::unordered_map<SocketId, std::pair<Q, Q>, boost::hash<SocketId>> g_enc_x_shares, xsum_final_shares;\n    std::unordered_map<SocketId, std::pair<std::vector<mpz_class>, std::vector<mpz_class>>, boost::hash<SocketId>> zcrt_shares;\n    std::unordered_map<SocketId, PairOfVecGCD, boost::hash<SocketId>> axby_sharesGCD;\n    std::unordered_map<SocketId, std::pair<std::vector<mpz_class>, std::vector<mpz_class>>, boost::hash<SocketId>> ax_by_sum_shares;\n\n    std::unordered_map<SocketId, std::vector<mpz_class>, boost::hash<SocketId>> axby_modulus;\n    std::unordered_map<SocketId, std::vector<mpz_class>, boost::hash<SocketId>> ggsShares;\n\n    std::unordered_map<SocketId, TripleVector, boost::hash<SocketId>> record_protocol_shares;\n\n    mpz_class gammaSeed;\n    std::vector<mpz_class> alphasPS, alphasCAN, alphasGCD;\n    std::vector<size_t> bucketSizePS;\n    std::vector<size_t> bucketSizeCAN;\n    std::vector<size_t> bucketSizeGCD;\n\n    std::vector<mpz_class> ax_modulus, by_modulus;\n\n    std::vector<std::vector<mpz_class>> eit_prunedPS;\n\n    std::vector<mpz_class> candidatesCAN, candidatesFinal, candidatesToCheck, recorded_pq_first, recorded_pq_second;\n\n    std::vector<mpz_class> ggsGCD;\n    std::vector<mpz_class> candidatesPostSieve;\n    std::vector<mpz_class> candidatesJacobi;\n    mpz_class gammaSeedAccum;\n    mpz_class gammaSeedJacobiAndGCD;\n\n    std::vector<int> flags_can;\n    int bucketSizeGCD_value;\n    int bucketSizeCAN_value;\n    std::vector<mpz_class> eitPS;\n    std::vector<size_t> index_candidates;\n    size_t minRowSize = -1;\n\n    boost::dynamic_bitset<> discardFlagsPostSieve;\n    boost::dynamic_bitset<> discardFlagsJacobi;\n};\n\n\n} // namespace ligero\n", "meta": {"hexsha": "93771f7c884ee6756c7b7db8a51445919c1def29", "size": 94358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/EncryptedCoordinator.hpp", "max_stars_repo_name": "Eleven-Z/LigeroRSA", "max_stars_repo_head_hexsha": "17d8b3d00604da1e0272035e871fac3add8d7551", "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/EncryptedCoordinator.hpp", "max_issues_repo_name": "Eleven-Z/LigeroRSA", "max_issues_repo_head_hexsha": "17d8b3d00604da1e0272035e871fac3add8d7551", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-09T05:48:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-09T05:48:09.000Z", "max_forks_repo_path": "include/EncryptedCoordinator.hpp", "max_forks_repo_name": "Eleven-Z/LigeroRSA", "max_forks_repo_head_hexsha": "17d8b3d00604da1e0272035e871fac3add8d7551", "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.794638997, "max_line_length": 195, "alphanum_fraction": 0.5061044109, "num_tokens": 21732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.5072343849817483}}
{"text": "\n#include <CGAL/Simple_cartesian.h>\n#include <iostream>\n#include <map>\n#include <boost/graph/adjacency_list.hpp>\n#include <CGAL/boost/graph/split_graph_into_polylines.h>\n\ntypedef CGAL::Simple_cartesian<double> K;\ntypedef K::Point_2 Point_2;\n\ntypedef boost::adjacency_list < boost::listS,\n                                boost::vecS, \n                                boost::undirectedS,\n                                Point_2 > G;\n\ntypedef boost::graph_traits<G>::vertex_descriptor vertex_descriptor;\n\ntypedef std::vector<Point_2> Polyline_2;\n\nstruct Is_terminal\n{\n  template <typename VertexDescriptor, typename Graph>\n  bool operator ()(VertexDescriptor vd , const Graph& g )\n  {\n    return false; // degree(vd,g) != 2; is a bad test in case of parallel edges\n  }\n};\n\n\ntemplate <typename Graph> \nstruct Polyline_visitor\n{\n  std::list<Polyline_2>& polylines;\n  const Graph& points_pmap;\n\n  Polyline_visitor(std::list<Polyline_2>& lines,\n                   const Graph& points_property_map)\n    : polylines(lines),\n      points_pmap(points_property_map)\n  {}\n\n  void start_new_polyline()\n  {\n    Polyline_2 V;\n    polylines.push_back(V);\n  }\n\n  void add_node(typename boost::graph_traits<Graph>::vertex_descriptor vd)\n  {\n    Polyline_2& polyline = polylines.back();\n    polyline.push_back(points_pmap[vd]);\n  }\n};\n\n\nint main()\n{\n  G g;\n\n  std::list<Polyline_2> polylines;  \n  Polyline_visitor<G> polyline_visitor(polylines, g);\n  std::map<Point_2, vertex_descriptor> p2vd;\n\n  int n;\n  std::cin >> n; // number of segments\n\n\n  Point_2 p, q;\n  vertex_descriptor  vdp, vdq; \n  for(int i=0; i < n; i++){\n    std::cin >> p >> q;\n   \n    if(p2vd.find(p) == p2vd.end()){\n      vdp = add_vertex(g);\n      g[vdp] = p;\n      p2vd[p] = vdp;\n    } else {\n      vdp = p2vd[p];\n    }\n    if(p2vd.find(q) == p2vd.end()){\n      vdq = add_vertex(g);\n      g[vdq] = q;\n      p2vd[q] = vdq;\n    } else {\n      vdq = p2vd[q];\n    }\n    boost::add_edge(vdp, vdq, g);\n  }\n\n   CGAL::split_graph_into_polylines( g,\n                                     polyline_visitor,\n                                     Is_terminal() );\n   std::cout.precision(17);\n\n   \n   for(std::list<Polyline_2>::iterator it = polylines.begin(); it!= polylines.end(); ++it){\n     Polyline_2& poly = *it;\n     std::size_t n;\n     if(poly.front() == poly.back()){\n       std::cout << \"POLYGON\" << std::endl;\n       n = poly.size() -1;\n     }else{\n       std::cout << \"POLYLINE\" << std::endl;\n       n = poly.size();\n     }\n     for(std::size_t j=0; j < n; j++){\n       std::cout << poly[j] << std::endl;\n     }\n     std::cout << std::endl;\n   }\n   \n  return 0;\n}\n", "meta": {"hexsha": "28f547e39ff1df8d2f15518f84d47e6002335178", "size": 2612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/BGL/test/BGL/split.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/BGL/test/BGL/split.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/BGL/test/BGL/split.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": 22.9122807018, "max_line_length": 91, "alphanum_fraction": 0.578101072, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5072272990426956}}
{"text": "// Fair Exponential Smoothing with Small Alpha by Juha Reunanen, 2015\n\n#include \"../fessa_detail.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(alpha)\n{\n    typedef double A;\n    const A baseAlpha = 0.001;\n\n    // define a narrot unit for time, so that we can easily reach the maximum value\n    typedef unsigned char T;\n\n    const fessa::detail::Alpha<A, T> alpha0(baseAlpha);\n    \n    BOOST_REQUIRE_EQUAL(alpha0.getAlpha(), 1);\n\n    const fessa::detail::Alpha<A, T> alpha1(baseAlpha, 1);\n\n    BOOST_REQUIRE_EQUAL(alpha0.getNext().getAlpha(), alpha1.getAlpha());\n\n    BOOST_REQUIRE_GT(alpha1.getAlpha(), 0.50025);\n    BOOST_REQUIRE_LT(alpha1.getAlpha(), 0.500251);\n\n    auto alphaRecursive = alpha1;\n    auto alphaPrevious = alphaRecursive;\n\n    int tMax = std::numeric_limits<T>::max() * 2;\n    for (int t = 2; t < tMax; ++t) {\n\n        // update the recursive alpha\n        alphaRecursive = alphaRecursive.getNext();\n\n        // basically alpha_fessa(t + 1) > alpha_fessa(t) for all t\n        if (t < std::numeric_limits<T>::max()) {\n            BOOST_REQUIRE_LT(alphaRecursive.getAlpha(), alphaPrevious.getAlpha());\n        }\n        // ... but in practice this is not necessary for large values of t\n        else {\n            BOOST_REQUIRE_EQUAL(alphaRecursive.getAlpha(), alphaRecursive.getAlpha());\n        }\n\n        // at any rate, the difference should get small when t increases\n        BOOST_REQUIRE_LT(alphaPrevious.getAlpha() - alphaRecursive.getAlpha(), 1 / static_cast<A>(t + 1));\n\n        if (t < std::numeric_limits<T>::max()) {\n            // we can also calculate the alpha directly based on t (without recursion, that is)\n            const fessa::detail::Alpha<A, T> alphaDirect(baseAlpha, t);\n            BOOST_REQUIRE_CLOSE(alphaRecursive.getAlpha(), alphaDirect.getAlpha(), 1e-10);\n        }\n\n        // check that the latest sample always has more weight than the others on average\n        const auto oneMinusAlpha = 1 - alphaRecursive.getAlpha();\n        const auto averageWeightOfEarlierSamples = oneMinusAlpha / t;\n        BOOST_REQUIRE_GT(alphaRecursive.getAlpha(), averageWeightOfEarlierSamples);\n        BOOST_REQUIRE_GT(alphaRecursive.getAlpha(), baseAlpha);\n\n        alphaPrevious = alphaRecursive;\n    }\n}\n", "meta": {"hexsha": "4c1087667d8b63fc25fe91644b104f1a18d082ab", "size": 2257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/test/test_alpha.cpp", "max_stars_repo_name": "reunanen/fessa", "max_stars_repo_head_hexsha": "e0bd04e8dd8a84e13b42835a66f5c98b056536b5", "max_stars_repo_licenses": ["MIT"], "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/test/test_alpha.cpp", "max_issues_repo_name": "reunanen/fessa", "max_issues_repo_head_hexsha": "e0bd04e8dd8a84e13b42835a66f5c98b056536b5", "max_issues_repo_licenses": ["MIT"], "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/test/test_alpha.cpp", "max_forks_repo_name": "reunanen/fessa", "max_forks_repo_head_hexsha": "e0bd04e8dd8a84e13b42835a66f5c98b056536b5", "max_forks_repo_licenses": ["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.4032258065, "max_line_length": 106, "alphanum_fraction": 0.6650420913, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5072272970875876}}
{"text": "#include \"conex/approximate_eigenvalues.h\"\n\n#include <chrono>\n\n#include \"gtest/gtest.h\"\n\n#include \"conex/debug_macros.h\"\n#include \"conex/test/test_util.h\"\n#include <Eigen/Dense>\n\nnamespace conex {\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nGTEST_TEST(Eigenvalues, NonsymmetricFromJacobiIterations) {\n  int n = 4;\n  MatrixXd A(n, n);\n  A << 3, 1, 0, 1, 1, 3, 1, 0, 0, 1, 4, 1, 1, 0, 1, 5;\n  A = A / A.trace();\n\n  MatrixXd W = MatrixXd::Random(n, n);\n  W = W * W.transpose();\n  A = W * A;\n\n  VectorXd r0(n);\n  r0 << 1, 2, 0, 4;\n  VectorXd eigJ = ApproximateEigenvalues(A, W, r0, n, false /*no compressed*/);\n  std::sort(eigJ.data(), eigJ.data() + eigJ.rows());\n\n  VectorXd eigL = ApproximateEigenvalues(A, W, r0, n, true /*use compressed*/);\n  std::sort(eigL.data(), eigL.data() + eigL.rows());\n  for (int i = 0; i < n; i++) {\n    EXPECT_NEAR(eigL(i), eigJ(i), 1e-12);\n  }\n\n  auto eigA = eig(A).eigenvalues;\n  std::sort(eigA.data(), eigA.data() + n);\n  for (int i = 0; i < n; i++) {\n    EXPECT_NEAR(eigJ(i), eigA(i), 1e-12);\n  }\n}\n\nGTEST_TEST(Eigenvalues, TruncatedApproximiationInterlaces) {\n  int n = 4;\n  MatrixXd A(n, n);\n  A << .1, 0, 0, 0, 0, 3, 0, 0, 0, 0, 4, 0, 0, 0, 0, 5;\n\n  VectorXd r0(n);\n  r0 << 1, 2, 0, 4;\n\n  int n_approx = 2;\n  VectorXd eigJ =\n      ApproximateEigenvalues(A, MatrixXd::Identity(n, n), r0, n_approx, true);\n  VectorXd eigA = eig(A).eigenvalues;\n\n  std::sort(eigJ.data(), eigJ.data() + eigJ.rows());\n  std::sort(eigA.data(), eigA.data() + eigA.rows());\n  EXPECT_TRUE(eigJ.tail(1)(0) <= eigA.tail(1)(0));\n  EXPECT_TRUE(eigJ.head(1)(0) >= eigA.head(1)(0));\n}\n\nGTEST_TEST(Eigenvalues, Lanczos) {\n  int n = 4;\n  MatrixXd A(n, n);\n  A << 3, 1, 0, 1, 1, 3, 1, 0, 0, 1, 4, 1, 1, 0, 1, 5;\n  A = A / A.trace();\n\n  VectorXd r0(n);\n  r0 << 1, 2, 0, 4;\n  VectorXd eigJ =\n      ApproximateEigenvalues(A, MatrixXd::Identity(n, n), r0, n, true);\n  auto eigA = eig(A).eigenvalues;\n\n  auto eigL = ApproximateEigenvalues(A, r0, n);\n\n  std::sort(eigJ.data(), eigJ.data() + n);\n  std::sort(eigA.data(), eigA.data() + n);\n  for (int i = 0; i < n; i++) {\n    EXPECT_NEAR(eigJ(i), eigA(i), 1e-12);\n  }\n  for (int i = 0; i < n; i++) {\n    EXPECT_NEAR(eigL(i), eigA(i), 1e-12);\n  }\n}\n\nGTEST_TEST(Eigenvalues, Profile) {\n  for (int k = 0; k < 4; k++) {\n    int n = 25;\n    MatrixXd S = MatrixXd::Random(n, n);\n    MatrixXd St = S.transpose();\n    S = S + St;\n    MatrixXd W = MatrixXd::Random(n, n);\n    W = W * W.transpose();\n    MatrixXd WS = W * S;\n    VectorXd r0 = VectorXd::Random(n);\n\n    auto t1 = std::chrono::high_resolution_clock::now();\n    VectorXd eigJ = ApproximateEigenvalues(WS, W, r0, n / 2, true);\n    auto t2 = std::chrono::high_resolution_clock::now();\n    auto duration1 =\n        std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();\n\n    t1 = std::chrono::high_resolution_clock::now();\n    VectorXd eigWS = eig(WS).eigenvalues;\n    t2 = std::chrono::high_resolution_clock::now();\n    auto duration2 =\n        std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();\n\n    EXPECT_LE(duration1, duration2);\n    EXPECT_NEAR(eigWS.maxCoeff() / eigJ.maxCoeff(), 1, 1e-2);\n  }\n}\n\n}  // namespace conex\n", "meta": {"hexsha": "c63c0926d99ea1f7bc6114c1f6c3fdf60aff6f87", "size": 3160, "ext": "cc", "lang": "C++", "max_stars_repo_path": "conex/test/approximate_eigenvalues.cc", "max_stars_repo_name": "frankpermenter/conex", "max_stars_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T20:41:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T20:41:20.000Z", "max_issues_repo_path": "conex/test/approximate_eigenvalues.cc", "max_issues_repo_name": "frankpermenter/conex", "max_issues_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conex/test/approximate_eigenvalues.cc", "max_forks_repo_name": "frankpermenter/conex", "max_forks_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_forks_repo_licenses": ["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.2413793103, "max_line_length": 79, "alphanum_fraction": 0.5971518987, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5072272900219192}}
{"text": "// Copyright 2004 The Trustees of Indiana University.\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n#include <boost/graph/fruchterman_reingold.hpp>\n#include <boost/graph/random_layout.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/simple_point.hpp>\n#include <boost/lexical_cast.hpp>\n#include <string>\n#include <iostream>\n#include <map>\n#include <vector>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/progress.hpp>\n#include <boost/shared_ptr.hpp>\n\nusing namespace boost;\n\nvoid usage()\n{\n  std::cerr << \"Usage: fr_layout [options] <width> <height>\\n\"\n            << \"Arguments:\\n\"\n            << \"\\t<width>\\tWidth of the display area (floating point)\\n\"\n            << \"\\t<Height>\\tHeight of the display area (floating point)\\n\\n\"\n            << \"Options:\\n\"\n            << \"\\t--iterations n\\tNumber of iterations to execute.\\n\" \n            << \"\\t\\t\\tThe default value is 100.\\n\"\n            << \"Input:\\n\"\n            << \"  Input is read from standard input as a list of edges, one per line.\\n\"\n            << \"  Each edge contains two string labels (the endpoints) separated by a space.\\n\\n\"\n            << \"Output:\\n\"\n            << \"  Vertices and their positions are written to standard output with the label,\\n  x-position, and y-position of a vertex on each line, separated by spaces.\\n\";\n}\n\ntypedef adjacency_list<listS, vecS, undirectedS, \n                       property<vertex_name_t, std::string> > Graph;\n\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\n\ntypedef std::map<std::string, Vertex> NameToVertex;\n\nVertex get_vertex(const std::string& name, Graph& g, NameToVertex& names)\n{\n  NameToVertex::iterator i = names.find(name);\n  if (i == names.end())\n    i = names.insert(std::make_pair(name, add_vertex(name, g))).first;\n  return i->second;\n}\n\nclass progress_cooling : public linear_cooling<double>\n{\n  typedef linear_cooling<double> inherited;\n\n public:\n  explicit progress_cooling(std::size_t iterations) : inherited(iterations) \n  {\n    display.reset(new progress_display(iterations + 1, std::cerr));\n  }\n\n  double operator()()\n  {\n    ++(*display);\n    return inherited::operator()();\n  }\n\n private:\n  shared_ptr<boost::progress_display> display;\n};\n\nint main(int argc, char* argv[])\n{\n  int iterations = 100;\n\n  if (argc < 3) { usage(); return -1; }\n\n  double width = 0;\n  double height = 0;\n\n  for (int arg_idx = 1; arg_idx < argc; ++arg_idx) {\n    std::string arg = argv[arg_idx];\n    if (arg == \"--iterations\") {\n      ++arg_idx;\n      if (arg_idx >= argc) { usage(); return -1; }\n      iterations = lexical_cast<int>(argv[arg_idx]);\n    } else {\n      if (width == 0.0) width = lexical_cast<double>(arg);\n      else if (height == 0.0) height = lexical_cast<double>(arg);\n      else {\n        usage();\n        return -1;\n      }\n    }\n  }\n\n  if (width == 0.0 || height == 0.0) {\n    usage();\n    return -1;\n  }\n\n  Graph g;\n  NameToVertex names;\n\n  std::string source, target;\n  while (std::cin >> source >> target) {\n    add_edge(get_vertex(source, g, names), get_vertex(target, g, names), g);\n  }\n  \n  typedef std::vector<simple_point<double> > PositionVec;\n  PositionVec position_vec(num_vertices(g));\n  typedef iterator_property_map<PositionVec::iterator, \n                                property_map<Graph, vertex_index_t>::type>\n    PositionMap;\n  PositionMap position(position_vec.begin(), get(vertex_index, g));\n\n  minstd_rand gen;\n  random_graph_layout(g, position, -width/2, width/2, -height/2, height/2, gen);\n  fruchterman_reingold_force_directed_layout\n    (g, position, width, height,\n     cooling(progress_cooling(iterations)));\n\n  graph_traits<Graph>::vertex_iterator vi, vi_end;\n  for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {\n    std::cout << get(vertex_name, g, *vi) << '\\t'\n              << position[*vi].x << '\\t' << position[*vi].y << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "aa0612a84b5332736c00c198066a0e5a6f9299c9", "size": 4070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/fr_layout.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": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T13:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T02:55:10.000Z", "max_issues_repo_path": "libs/graph/example/fr_layout.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/fr_layout.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T14:34:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T08:25:58.000Z", "avg_line_length": 30.6015037594, "max_line_length": 174, "alphanum_fraction": 0.643980344, "num_tokens": 1068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5072272868664673}}
{"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\r\n//! \\file\r\n//!\\brief Tests multiplication for fixed_point negatable.\r\n\r\n#define BOOST_TEST_MODULE test_negatable_basic_multiply\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <sstream>\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_basic_multiply)\r\n{\r\n  //! small range and resolution\r\n  {\r\n    typedef boost::fixed_point::negatable<4, -2, boost::fixed_point::round::fastest> fixed_point_type_fastest_round;\r\n    fixed_point_type_fastest_round x = fixed_point_type_fastest_round (-1.25) * fixed_point_type_fastest_round (1.5);\r\n    fixed_point_type_fastest_round y = fixed_point_type_fastest_round(-2);\r\n    fixed_point_type_fastest_round z = fixed_point_type_fastest_round(-1.75);\r\n\r\n    BOOST_CHECK_EQUAL(x == y || x == z, true);\r\n\r\n    x = fixed_point_type_fastest_round (1.25) * fixed_point_type_fastest_round (1.5);\r\n    y = fixed_point_type_fastest_round (1.75);\r\n    z = fixed_point_type_fastest_round (2);\r\n\r\n    BOOST_CHECK_EQUAL(x == y || x == z, true);\r\n  }\r\n\r\n  //! larger range and small resolution\r\n  {\r\n    typedef boost::fixed_point::negatable<400, -2, boost::fixed_point::round::fastest> fixed_point_type_fastest_round;\r\n    fixed_point_type_fastest_round x = fixed_point_type_fastest_round (-1.25) * fixed_point_type_fastest_round (1.5);\r\n    fixed_point_type_fastest_round y = fixed_point_type_fastest_round(-2);\r\n    fixed_point_type_fastest_round z = fixed_point_type_fastest_round(-1.75);\r\n\r\n    BOOST_CHECK_EQUAL(x == y || x == z, true);\r\n\r\n    x = fixed_point_type_fastest_round (1.25) * fixed_point_type_fastest_round (1.5);\r\n    y = fixed_point_type_fastest_round (1.75);\r\n    z = fixed_point_type_fastest_round (2);\r\n\r\n    BOOST_CHECK_EQUAL(x == y || x == z, true);\r\n  }\r\n\r\n  //! larger range and larger resolution\r\n  {\r\n    typedef boost::fixed_point::negatable<87, -4, boost::fixed_point::round::fastest> fixed_point_type_fastest_round;\r\n    fixed_point_type_fastest_round x = fixed_point_type_fastest_round (800.4375) * fixed_point_type_fastest_round (-7.5625);\r\n    fixed_point_type_fastest_round y = fixed_point_type_fastest_round(-6053.3125);\r\n    fixed_point_type_fastest_round z = fixed_point_type_fastest_round(-6053.25);\r\n\r\n    BOOST_CHECK_EQUAL(x == y || x == z, true);\r\n\r\n    x = fixed_point_type_fastest_round (800.4375) * fixed_point_type_fastest_round (7.5625);\r\n    y = fixed_point_type_fastest_round (6053.3125);\r\n    z = fixed_point_type_fastest_round (6053.25);\r\n\r\n    BOOST_CHECK_EQUAL(x == y || x == z, true);\r\n  }\r\n}\r\n", "meta": {"hexsha": "ffe280e753a28f2ddaff35e9c8ed13895b4f4b1d", "size": 2951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_basic_multiply.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_multiply.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_multiply.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": 40.4246575342, "max_line_length": 125, "alphanum_fraction": 0.7123009149, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5072272849113592}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n    This is an example showing how to use sparse feature vectors with\n    the dlib C++ library's machine learning tools.\n\n    This example creates a simple binary classification problem and shows\n    you how to train a support vector machine on that data.\n\n    The data used in this example will be 100 dimensional data and will\n    come from a simple linearly separable distribution.  \n*/\n\n\n#include <iostream>\n#include <ctime>\n#include <vector>\n#include <dlib/svm.h>\n\nusing namespace std;\nusing namespace dlib;\n\n\nint main()\n{\n    // In this example program we will be dealing with feature vectors that are sparse (i.e. most\n    // of the values in each vector are zero).  So rather than using a dlib::matrix we can use\n    // one of the containers from the STL to represent our sample vectors.  In particular, we \n    // can use the std::map to represent sparse vectors.  (Note that you don't have to use std::map.\n    // Any STL container of std::pair objects that is sorted can be used.  So for example, you could \n    // use a std::vector<std::pair<unsigned long,double> > here so long as you took care to sort every vector)\n    typedef std::map<unsigned long,double> sample_type;\n\n\n    // This is a typedef for the type of kernel we are going to use in this example.\n    // Since our data is linearly separable I picked the linear kernel.  Note that if you\n    // are using a sparse vector representation like std::map then you have to use a kernel\n    // meant to be used with that kind of data type.  \n    typedef sparse_linear_kernel<sample_type> kernel_type;\n\n\n    // Here we create an instance of the pegasos svm trainer object we will be using.\n    svm_pegasos<kernel_type> trainer;\n    // Here we setup a parameter to this object.  See the dlib documentation for a \n    // description of what this parameter does. \n    trainer.set_lambda(0.00001);\n\n    // Lets also use the svm trainer specially optimized for the linear_kernel and\n    // sparse_linear_kernel.\n    svm_c_linear_trainer<kernel_type> linear_trainer;\n    // This trainer solves the \"C\" formulation of the SVM.  See the documentation for\n    // details.\n    linear_trainer.set_c(10);\n\n    std::vector<sample_type> samples;\n    std::vector<double> labels;\n\n    // make an instance of a sample vector so we can use it below\n    sample_type sample;\n\n\n    // Now lets go into a loop and randomly generate 10000 samples.\n    srand(time(0));\n    double label = +1;\n    for (int i = 0; i < 10000; ++i)\n    {\n        // flip this flag\n        label *= -1;\n\n        sample.clear();\n\n        // now make a random sparse sample with at most 10 non-zero elements\n        for (int j = 0; j < 10; ++j)\n        {\n            int idx = std::rand()%100;\n            double value = static_cast<double>(std::rand())/RAND_MAX;\n\n            sample[idx] = label*value;\n        }\n\n        // let the svm_pegasos learn about this sample.  \n        trainer.train(sample,label);\n\n        // Also save the samples we are generating so we can let the svm_c_linear_trainer\n        // learn from them below.  \n        samples.push_back(sample);\n        labels.push_back(label);\n    }\n\n    // In addition to the rule we learned with the pegasos trainer lets also use our linear_trainer\n    // to learn a decision rule.\n    decision_function<kernel_type> df = linear_trainer.train(samples, labels);\n\n    // Now we have trained our SVMs.  Lets test them out a bit.  \n    // Each of these statements prints the output of the SVMs given a particular sample.  \n    // Each SVM outputs a number > 0 if a sample is predicted to be in the +1 class and < 0 \n    // if a sample is predicted to be in the -1 class.\n\n\n    sample.clear();\n    sample[4] = 0.3;\n    sample[10] = 0.9;\n    cout << \"This is a +1 example, its SVM output is: \" << trainer(sample) << endl;\n    cout << \"df: \" << df(sample) << endl;\n\n    sample.clear();\n    sample[83] = -0.3;\n    sample[26] = -0.9;\n    sample[58] = -0.7;\n    cout << \"This is a -1 example, its SVM output is: \" << trainer(sample) << endl;\n    cout << \"df: \" << df(sample) << endl;\n\n    sample.clear();\n    sample[0] = -0.2;\n    sample[9] = -0.8;\n    cout << \"This is a -1 example, its SVM output is: \" << trainer(sample) << endl;\n    cout << \"df: \" << df(sample) << endl;\n\n}\n\n", "meta": {"hexsha": "784fe5406fba24e5757afbd47327d523359ae948", "size": 4347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DynamicGestures/dlib-18.5/examples/svm_sparse_ex.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": "DynamicGestures/dlib-18.5/examples/svm_sparse_ex.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": "DynamicGestures/dlib-18.5/examples/svm_sparse_ex.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": 35.9256198347, "max_line_length": 110, "alphanum_fraction": 0.6583850932, "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.507227279800799}}
{"text": "/* test_uniform_on_sphere_distribution.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_uniform_on_sphere_distribution.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\r\n *\r\n */\r\n\r\n#include <boost/random/uniform_on_sphere.hpp>\r\n#include <boost/assign/list_of.hpp>\r\n\r\n#include <limits>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::uniform_on_sphere<>\r\n#define BOOST_RANDOM_ARG1 dim\r\n#define BOOST_RANDOM_ARG1_DEFAULT 2\r\n#define BOOST_RANDOM_ARG1_VALUE 3\r\n\r\nstd::vector<double> min0 = boost::assign::list_of(-1.0)(0.0);\r\nstd::vector<double> max0 = boost::assign::list_of(1.0)(0.0);\r\nstd::vector<double> min1 = boost::assign::list_of(-1.0)(0.0)(0.0);\r\nstd::vector<double> max1 = boost::assign::list_of(1.0)(0.0)(0.0);\r\n\r\n#define BOOST_RANDOM_DIST0_MIN min0\r\n#define BOOST_RANDOM_DIST0_MAX max0\r\n#define BOOST_RANDOM_DIST1_MIN min1\r\n#define BOOST_RANDOM_DIST1_MAX max1\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS (0)\r\n#define BOOST_RANDOM_TEST1_MIN std::vector<double>()\r\n#define BOOST_RANDOM_TEST1_MAX std::vector<double>()\r\n#define BOOST_RANDOM_TEST2_PARAMS\r\n#define BOOST_RANDOM_TEST2_MIN min0\r\n#define BOOST_RANDOM_TEST2_MAX max0\r\n\r\n#include <boost/test/test_tools.hpp>\r\n\r\nBOOST_TEST_DONT_PRINT_LOG_VALUE( std::vector<double> )\r\n\r\n#include \"test_distribution.ipp\"\r\n", "meta": {"hexsha": "225752562b0925cbcda08030cc6262e4c6de3636", "size": 1435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_uniform_on_sphere_distribution.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_uniform_on_sphere_distribution.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_uniform_on_sphere_distribution.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": 32.6136363636, "max_line_length": 93, "alphanum_fraction": 0.7630662021, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5071731807650807}}
{"text": "#include \"testsuite.h\"\n#include <blitz/vector2.h>\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n    Vector<int> a(6);\n    a = 1, 4, 6, 3, 7, 8;\n\n    BZTEST(a(0) == 1);\n    BZTEST(a(1) == 4);\n    BZTEST(a(2) == 6);\n    BZTEST(a(3) == 3);\n    BZTEST(a(4) == 7);\n    BZTEST(a(5) == 8);\n    cout << a << endl;\n\n    Vector<int> b = a(Range(0,4,2));\n    cout << b << endl;\n//  b = -1, -2, -3;\n//  workaround: use list initialization with Vector that has own storage\n    Vector<int> bb(3);\n    bb = -1, -2, -3;\n    b = bb;\n    cout << a << endl;\n    cout << b << endl;\n    BZTEST(a(0) == -1);\n    BZTEST(a(1) == 4);\n    BZTEST(a(2) == -2);\n    BZTEST(a(3) == 3);\n    BZTEST(a(4) == -3);\n    BZTEST(a(5) == 8);\n\n    Vector<int> c = a.reverse(firstDim);\n    c = 0;\n    BZTEST(a(0) == 0);\n    BZTEST(a(1) == 0);\n    BZTEST(a(2) == 0);\n    BZTEST(a(3) == 0);\n    BZTEST(a(4) == 0);\n    BZTEST(a(5) == 0);\n//  c = 8, 7, 3, 6, 4, 1;\n//  workaround: use list initialization with Vector that has own storage\n    Vector<int> cc(6);\n    cc = 8, 7, 3, 6, 4, 1;\n    c = cc;\n    BZTEST(a(0) == 1);\n    BZTEST(a(1) == 4);\n    BZTEST(a(2) == 6);\n    BZTEST(a(3) == 3);\n    BZTEST(a(4) == 7);\n    BZTEST(a(5) == 8);\n\n    Array<int,1> d(5);\n    d=1,-1,2,-2,0;\n    BZTEST(d(0) == 1);\n    BZTEST(d(1) == -1);\n    BZTEST(d(2) == 2);\n    BZTEST(d(3) == -2);\n    BZTEST(d(4) == 0);\n\n    \n    return 0;\n}\n\n", "meta": {"hexsha": "fd919bc02fe9f69784731fd0ca1c013bab691d4a", "size": 1396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/initialize.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/initialize.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/initialize.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": 20.5294117647, "max_line_length": 72, "alphanum_fraction": 0.4591690544, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5071731718709984}}
{"text": "/*\n * Copyright (c) 2019 Opticks Team. All Rights Reserved.\n *\n * This file is part of Opticks\n * (see https://bitbucket.org/simoncblyth/opticks).\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 <iostream>\n#include <fstream>\n#include <ctime>            // std::time\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/generator_iterator.hpp>\n\n#include \"PLOG.hh\"\n\n//typedef boost::mt19937     RNG_t; \n//typedef boost::ecuyer1988  RNG_t;\ntypedef boost::minstd_rand      RNG_t;\n\ntypedef boost::uniform_real<>   DST_t;\ntypedef boost::variate_generator< RNG_t, DST_t > GEN_t ;\n\n\n\nclass BRNG\n{\n    public:\n        BRNG( float lo=0.f, float hi=1.f, unsigned _seed=0)\n            :\n            m_rng(),\n            m_dst(lo, hi),\n            m_gen(m_rng, m_dst)\n        {\n            seed(_seed); \n        }\n\n        float operator()()\n        {\n            return m_gen() ;   \n        }\n\n        void seed(unsigned _seed)\n        {\n            m_rng.seed(_seed);\n        }\n\n        void dump( const char* label )\n        {\n            LOG(info) << label ; \n            std::cout.setf(std::ios::fixed);\n            for(int i = 0; i < 10; i++) std::cout << (*this)() << '\\n';\n        }\n\n\n    private:\n        RNG_t m_rng ;\n        DST_t m_dst ;\n        GEN_t m_gen ; \n};\n\n\nvoid test_0()\n{\n    LOG(info) << \".\" ;\n\n    { \n        RNG_t rng(42);\n        DST_t dst(0,1);\n        GEN_t uni(rng, dst);\n\n        std::cout << \"A : 10 samples in [0..1) (seed:42) \\n\";\n        std::cout.setf(std::ios::fixed);\n        for(int i = 0; i < 10; i++) std::cout << uni() << '\\n';\n\n        rng.seed(420);\n        std::cout << \"A : 10 samples in [0..1) (seed:420) \\n\";\n        for(int i = 0; i < 10; i++) std::cout << uni() << '\\n';\n    } \n\n    { \n\n        RNG_t rng(42);\n        DST_t dst(0,1);\n        GEN_t uni(rng, dst);\n\n        std::cout << \"B : 10 samples of a uniform distribution in [0..1):\\n\";\n        std::cout.setf(std::ios::fixed);\n        for(int i = 0; i < 10; i++) std::cout << uni() << '\\n';\n\n        rng.seed(420);\n        std::cout << \"B : 10 more samples of a uniform distribution in [0..1):\\n\";\n        for(int i = 0; i < 10; i++) std::cout << uni() << '\\n'; \n    } \n\n}\n\nvoid test_1()\n{\n    LOG(info) << \".\" ;\n    {\n        BRNG a(0,1,42);\n        a.dump(\"A : 10 samp, seed:42 \");\n        a.seed(420);\n        a.dump(\"A : 10 samp, seed 420 \");\n    }\n    {\n        BRNG b(0,1,42);\n        b.dump(\"B : 10 samp, seed:42 \");\n        b.seed(420);\n        b.dump(\"B : 10 samp, seed 420 \");\n    }\n\n\n\n\n}\n\n\n\n\n\nint main(int argc, char** argv)\n{\n    PLOG_(argc, argv);\n\n    test_0();\n    test_1();\n\n    return 0;\n}\n", "meta": {"hexsha": "447c03a1a2846faf086c421865ca4614089d8d0e", "size": 3314, "ext": "cc", "lang": "C++", "max_stars_repo_path": "boostrap/tests/boost_random_minimal_Test.cc", "max_stars_repo_name": "hanswenzel/opticks", "max_stars_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-07-05T02:39:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T18:52:44.000Z", "max_issues_repo_path": "boostrap/tests/boost_random_minimal_Test.cc", "max_issues_repo_name": "hanswenzel/opticks", "max_issues_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "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": "boostrap/tests/boost_random_minimal_Test.cc", "max_forks_repo_name": "hanswenzel/opticks", "max_forks_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-03T20:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T07:42:21.000Z", "avg_line_length": 22.2416107383, "max_line_length": 82, "alphanum_fraction": 0.5368135184, "num_tokens": 945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5071731676175703}}
{"text": "#ifdef BOOST\n\n#include <iostream>\n#include <optional>\n\n// Using boost-1.65.1\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/tokenizer.hpp>\n\nusing namespace std;\n\nusing undirected_graph =\n    boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS>;\n\nint\nmain()\n{\n\tundirected_graph G;\n\n\tfor (string line; getline(cin, line); ) {\n\t\toptional<int> last;\n\t\tfor (string s : boost::tokenizer<>(line)) {\n\t\t\tint i = stoi(s);\n\t\t\tif (last)\n\t\t\t\tadd_edge(*last, i, G);\n\t\t\tlast = i;\n\t\t}\n\t}\n\n\tvector<int> component(num_vertices(G));\n\tint n = connected_components(G, &component[0]);\n\tcout << count(begin(component), end(component), component[0]) << endl;\n\tcout << n << endl;\n}\n\n// 134\n// 193\n\n#else //////////////////////////////////////////////////////////////////////\n\n#include <algorithm>\n#include <deque>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\n// bfs approach without recursion\n// adapted from https://www.reddit.com/r/adventofcode/comments/7j89tr/x/dr4iya8/\n\nint main()\n{\n\tvector<vector<int>> edges;\n\n\tfor (string line; getline(cin, line); ) {\t\t\n\t\tistringstream line_stream{line};\n\t\tint vertex_a, vertex_b;\n\t\tstring _;\n\t\tline_stream >> vertex_a >> _;\n\t\tfor (edges.emplace_back();  // assumes lines arrive in order\n\t\t     line_stream >> vertex_b;\n\t\t     line_stream >> _)\n\t\t\tedges[vertex_a].emplace_back(vertex_b);\n\t}\n\n\tvector<int> comp(size(edges), -1);\n\tint n = 0;\n\n\tfor (auto vertex = begin(comp);\n\t     vertex != end(comp);\n\t     ++n, vertex = find(begin(comp), end(comp), -1)) {\n\t\tdeque<long> queue{distance(begin(comp), vertex)};\n\t\twhile (!empty(queue)) {\n\t\t\tint v = queue.front();\n\t\t\tqueue.pop_front();\n\t\t\tcomp[v] = n;\n\t\t\tcopy_if(begin(edges[v]), end(edges[v]),\n\t\t\t    back_inserter(queue),\n\t\t\t    [&](int v){ return comp[v] == -1; });\n\t\t}\n\t}\n\n\tcout << count(begin(comp), end(comp), 0) << endl;\n\tcout << n << endl;\n}\n\n#endif\n", "meta": {"hexsha": "8d757ebddc992698dbae663092325023bdc18d74", "size": 1977, "ext": "cc", "lang": "C++", "max_stars_repo_path": "day12.cc", "max_stars_repo_name": "chneukirchen/adventofcode2017", "max_stars_repo_head_hexsha": "1287f7d36af4cdbdc18194451538c09e800951ac", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-14T15:42:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-07T02:14:18.000Z", "max_issues_repo_path": "day12.cc", "max_issues_repo_name": "chneukirchen/adventofcode2017", "max_issues_repo_head_hexsha": "1287f7d36af4cdbdc18194451538c09e800951ac", "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": "day12.cc", "max_forks_repo_name": "chneukirchen/adventofcode2017", "max_forks_repo_head_hexsha": "1287f7d36af4cdbdc18194451538c09e800951ac", "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": 21.4891304348, "max_line_length": 80, "alphanum_fraction": 0.6246838644, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.507173163751367}}
{"text": "#include <boost/lexical_cast.hpp>\n#include <cctype>\n#include <iostream>\n#include <iterator>\n#include <ostream>\n#include <sstream>\n#include <stdexcept>\n#include <vector>\n#include <memory>\n\n\nstruct Token\n{\n\tenum class Type { Literal, Plus, Minus, LParen, RParen, } type;\n\tstd::string text;\n\n\texplicit Token(Type type, std::string text)\n\t\t:\ttype{std::move(type)},\n\t\t\ttext{std::move(text)}\n\t{}\n\n\tfriend std::ostream& operator<<(std::ostream& out, const Token& t)\n\t{\n\t\treturn out << \"`\" << t.text << \"`\";\n\t}\n};\n\nstd::vector<Token> lex(std::string input)\n{\n\tstd::vector<Token> result;\n\tfor(auto i = 0ull; i < std::size(input); ++i)\n\t{\n\t\tif (input[i] == '+')\n\t\t{\n\t\t\tresult.emplace_back(Token::Type::Plus, std::string(1, input[i]));\n\t\t}\n\t\telse if (input[i] == '-')\n\t\t{\n\t\t\tresult.emplace_back(Token::Type::Minus, std::string(1, input[i]));\n\t\t}\n\t\telse if (input[i] == '(')\n\t\t{\n\t\t\tresult.emplace_back(Token::Type::LParen, std::string(1, input[i]));\n\t\t}\n\t\telse if (input[i] == ')')\n\t\t{\n\t\t\tresult.emplace_back(Token::Type::RParen, std::string(1, input[i]));\n\t\t}\n\t\telse if (std::isdigit(input[i]))\n\t\t{\n\t\t\tstd::ostringstream out;\n\t\t\tout << input[i++];\n\t\t\twhile(i < std::size(input) && std::isdigit(input[i]))\n\t\t\t{\n\t\t\t\tout << input[i];\n\t\t\t\t++i;\n\t\t\t}\n\n\t\t\tresult.emplace_back(Token::Type::Literal, out.str());\n\t\t\t--i;\n\t\t}\n\t\telse if (input[i] == ' ')\n\t\t{\n\t\t\t// Do nothing!\n\t\t\tcontinue;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::ostringstream err_msg;\n\t\t\terr_msg << \"Invalid token\";\n\t\t\terr_msg << \" `\" << input[i] << \"` \";\n\t\t\terr_msg << \" found while lexing!\";\n\t\t\tthrow std::runtime_error{err_msg.str()};\n\t\t}\n\t}\n\n\treturn result;\n}\n\n\nstruct IElement\n{\n\tvirtual int eval() const = 0;\n};\n\nstruct Literal : public IElement\n{\n\tint val;\n\n\texplicit Literal(int value)\n\t\t:\tval{value}\n\t{}\n\n\tint eval() const override\n\t{\n\t\treturn val;\n\t}\n};\n\nstruct BinaryOperation : public IElement\n{\n\tstd::shared_ptr<IElement> lhs, rhs;\n\tenum class Type { Plus, Minus, NoOp } type;\n\n\texplicit BinaryOperation(std::shared_ptr<IElement> lhs = nullptr, std::shared_ptr<IElement> rhs = nullptr, Type t = Type::NoOp)\n\t\t:\tlhs{std::move(lhs)},\n\t\t\trhs{std::move(rhs)},\n\t\t\ttype{std::move(t)}\n\t{}\n\n\tint eval() const override\n\t{\n\t\tauto lhs_val{lhs->eval()}, rhs_val{rhs->eval()};\n\t\tswitch(type)\n\t\t{\n\t\tcase Type::Plus:\n\t\t\treturn lhs_val + rhs_val;\n\t\tcase Type::Minus:\n\t\t\treturn lhs_val - rhs_val;\n\t\tdefault:\n\t\t\tthrow std::runtime_error{\"Unsupported operation!\"};\n\t\t}\n\t}\n};\n\nstd::shared_ptr<IElement> parse(const std::vector<Token>& tokens)\n{\n\tauto result{std::make_shared<BinaryOperation>()};\n\tfor(auto i = 0ull; i < std::size(tokens); ++i)\n\t{\n\t\tswitch(tokens[i].type)\n\t\t{\n\t\tcase Token::Type::Literal:\n\t\t\t{\n\t\t\t\tauto lit{std::make_shared<Literal>(boost::lexical_cast<int>(tokens[i].text))};\n\t\t\t\tif(result->lhs == nullptr)\n\t\t\t\t{\n\t\t\t\t\tresult->lhs = std::move(lit);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tresult->rhs = std::move(lit);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase Token::Type::Plus:\n\t\t\tresult->type = BinaryOperation::Type::Plus;\n\t\t\tbreak;\n\t\tcase Token::Type::Minus:\n\t\t\tresult->type = BinaryOperation::Type::Minus;\n\t\t\tbreak;\n\t\tcase Token::Type::LParen:\n\t\t\t{\n\t\t\t\tauto j{i};\n\t\t\t\twhile(j < std::size(tokens) && tokens[j].type != Token::Type::RParen)\n\t\t\t\t{\n\t\t\t\t\t++j;\n\t\t\t\t}\n\n\t\t\t\tif(j == std::size(tokens))\n\t\t\t\t{\n\t\t\t\t\tthrow std::runtime_error{\"Mismatched paranthesis!\"};\n\t\t\t\t}\n\n\t\t\t\tauto subexpr{std::vector<Token>(tokens.begin() + (i + 1), tokens.begin() + j)};\n\t\t\t\tauto elem{parse(subexpr)};\n\t\t\t\tif(result->lhs == nullptr)\n\t\t\t\t{\n\t\t\t\t\tresult->lhs = std::move(elem);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tresult->rhs = std::move(elem);\n\t\t\t\t}\n\n\t\t\t\ti = j;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nint main()\n{\n\tstd::string input{\"(13 - 4) - (12 + 1)\"};\n\tauto res{lex(input)};\n\tstd::copy(res.cbegin(), res.cend(), std::ostream_iterator<decltype(res)::value_type>(std::cout, \" \"));\n\tauto tree{parse(res)};\n\tstd::cout << input << \" = \" << tree->eval() << std::endl;\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "f777b313bd261112937b6c457d982c23a3df8a57", "size": 3885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "behavioral/interpreter/interpreter.cpp", "max_stars_repo_name": "stefanpantic/cpp-design-patterns", "max_stars_repo_head_hexsha": "887f9ddebbb99a773ba132c6298fee37eec25609", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-21T11:03:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T17:47:12.000Z", "max_issues_repo_path": "behavioral/interpreter/interpreter.cpp", "max_issues_repo_name": "stefanpantic/cpp-design-patterns", "max_issues_repo_head_hexsha": "887f9ddebbb99a773ba132c6298fee37eec25609", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "behavioral/interpreter/interpreter.cpp", "max_forks_repo_name": "stefanpantic/cpp-design-patterns", "max_forks_repo_head_hexsha": "887f9ddebbb99a773ba132c6298fee37eec25609", "max_forks_repo_licenses": ["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.6212121212, "max_line_length": 128, "alphanum_fraction": 0.5951093951, "num_tokens": 1170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5071731633641419}}
{"text": "/**\n * Copyright (c) 2015 Carnegie Mellon University, Daniel Maturana <dimatura@cmu.edu>\n *\n * For License information please see the LICENSE file in the root directory.\n *\n */\n\n\n#ifndef RAYCASTING_HPP_OLVFBMND\n#define RAYCASTING_HPP_OLVFBMND\n\n#include <Eigen/Core>\n\n#include <pcl_util/point_types.hpp>\n\n#include \"scrollgrid/grid_types.hpp\"\n#include \"scrollgrid/box.hpp\"\n#include \"scrollgrid/ray.hpp\"\n#include \"scrollgrid/scrollgrid3.hpp\"\n#include \"scrollgrid/dense_array3.hpp\"\n\nnamespace ca\n{\n\n/**\n * Axis-aligned bounding box intersection test.\n * Reference:\n * An Efficient and Robust Ray\u2013Box Intersection Algorithm, Williams et al. 2004\n * tmin and tmax are updated\n */\ntemplate<typename Scalar>\nbool aabb_ray_intersect(const ca::scrollgrid::Box<Scalar, 3>& box,\n                        ca::scrollgrid::Ray3<Scalar> &r) {\n  Scalar tmin = (box.bound(   boost::get<0>(r.sign) ).x() - r.origin.x()) * r.invdir.x();\n  Scalar tmax = (box.bound( 1-boost::get<0>(r.sign) ).x() - r.origin.x()) * r.invdir.x();\n\n  Scalar tymin = (box.bound(  boost::get<1>(r.sign) ).y() - r.origin.y()) * r.invdir.y();\n  Scalar tymax = (box.bound(1-boost::get<1>(r.sign) ).y() - r.origin.y()) * r.invdir.y();\n\n  if ((tmin > tymax) || (tymin > tmax)) { return false; }\n  if (tymin > tmin) { tmin = tymin; }\n  if (tymax < tmax) { tmax = tymax; }\n\n  Scalar tzmin = (box.bound(  boost::get<2>(r.sign)).z() - r.origin.z()) * r.invdir.z();\n  Scalar tzmax = (box.bound(1-boost::get<2>(r.sign)).z() - r.origin.z()) * r.invdir.z();\n\n  if ((tmin > tzmax) || (tzmin > tmax)) { return false; }\n  if (tzmin > tmin) { tmin = tzmin; }\n  if (tzmax < tmax) { tmax = tzmax; }\n  if (tmin > r.tmin) { r.tmin = tmin; }\n  if (tmax < r.tmax) { r.tmax = tmax; }\n  return true;\n}\n\n/**\n * Trace a straight line from start_pos to end_pos.\n * At each step fun(i, j, k) is called.\n *\n * NOTE start_pos and end_pos should be inside the grid\n *\n * Reference: graphics gems article\n * TODO consider DDA-type raytracing.\n */\ntemplate<class TraceFunctor>\nvoid bresenham_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      if(!fun(x, y, z)) break;\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      if(!fun(x, y, z)) break;\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      if(!fun(x, y, z))  break;\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\n/**\n * Simply increment a counter in densearray3 for each step along the way.\n */\ntemplate<class GridScalar, class ArrayScalar>\nvoid bresenham_trace_simple(const Vec3Ix& start_pos,\n                            const Vec3Ix& end_pos,\n                            const ca::ScrollGrid3<GridScalar>& grid3,\n                            ca::DenseArray3<ArrayScalar>& 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    for (int decy=ay-dx, decz=az-dx;\n         ;\n         x+=sx, decy+=ay, decz+=az) {\n      mem_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n      array3[mem_ix] += 1;\n      //array3[mem_ix] = ray_ctr++;\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      mem_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n      array3[mem_ix] += 1;\n      //array3[mem_ix] = ray_ctr++;\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      grid_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n      array3[mem_ix] += 1;\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\n\ntemplate<class TraceFunctor>\nvoid bresenham_trace(const Vec2Ix& start_pos,\n                     const Vec2Ix& end_pos,\n                     const TraceFunctor& fun) {\n    int x = start_pos[0],\n      y = start_pos[1];\n\n    int dx = end_pos[0] - start_pos[0],\n      dy = end_pos[1] - start_pos[1];\n    int sx, sy;\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    int ax = 2*dx,\n      ay = 2*dy;\n\n    if (dy <= dx){\n        for (int decy=ay-dx;;\n             x+=sx, decy+=ay) {\n          bool end_cell = false;\n          //Bresenham step\n          if(!fun(x,y,end_cell)){ ROS_INFO(\"Breaking due to function call\"); break;}\n\n          if ( x==end_pos[0] ) break;\n          if ( decy>=0 ) {\n            decy-=ax;\n            y+=sy;\n          }\n        }\n    } else if ( dx <= dy ){\n        for (int decx=ax-dy;;\n             y+=sy,decx+=ax) {\n          bool end_cell = false;\n          //Bresenham step\n          if(!fun(x,y,end_cell)){ break; ROS_INFO(\"Breaking due to function call\"); break;}\n\n          if ( y==end_pos[1] ) break;\n          if ( decx>=0 ) {\n            decx-=ay;\n            x+=sx;\n          }\n        }\n    }\n}\n\n}\n\n#endif /* end of include guard: RAYCASTING_HPP_OLVFBMND */\n", "meta": {"hexsha": "c04c8227ac13f1676239e8322bf0eb6138e00d12", "size": 7774, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/scrollgrid/raycasting.hpp", "max_stars_repo_name": "castacks/scrollgrid", "max_stars_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-07-20T23:04:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T08:03:10.000Z", "max_issues_repo_path": "include/scrollgrid/raycasting.hpp", "max_issues_repo_name": "castacks/scrollgrid", "max_issues_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/scrollgrid/raycasting.hpp", "max_forks_repo_name": "castacks/scrollgrid", "max_forks_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-06T16:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T01:39:22.000Z", "avg_line_length": 22.7976539589, "max_line_length": 91, "alphanum_fraction": 0.4753022897, "num_tokens": 2697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.507173150410244}}
{"text": "#include <Eigen/Core>\n#include \"caffe2/operators/elementwise_op.h\"\n\nnamespace caffe2 {\n\nstruct SqrtCPUFunctor {\n  template <typename T>\n  inline void\n  operator()(const int n, const T* x, T* y, CPUContext* /*device_context*/) {\n    EigenVectorArrayMap<T>(y, n) = ConstEigenVectorArrayMap<T>(x, n).sqrt();\n  }\n};\n\nREGISTER_CPU_OPERATOR(\n    Sqrt,\n    UnaryElementwiseOp<TensorTypes<float>, CPUContext, SqrtCPUFunctor>);\n// Input: X, output: Y\nOPERATOR_SCHEMA(Sqrt)\n    .NumInputs(1)\n    .NumOutputs(1)\n    .AllowInplace({{0, 0}})\n    .IdenticalTypeAndShape()\n    .SetDoc(R\"DOC(\nComputes the element-wise sqrt of the input.\n)DOC\")\n    .Input(0, \"X\", \"ND input tensor\")\n    .Output(0, \"Y\", \"ND input tensor\");\n\nclass GetSqrtGradient : public GradientMakerBase {\n  using GradientMakerBase::GradientMakerBase;\n  vector<OperatorDef> GetGradientDefs() override {\n    Argument scale_arg;\n    scale_arg.set_name(\"scale\");\n    scale_arg.set_f(0.5);\n    return vector<OperatorDef>{CreateOperatorDef(\n                                   \"Scale\",\n                                   \"\",\n                                   std::vector<string>{GO(0)},\n                                   std::vector<string>{GI(0)},\n                                   std::vector<Argument>{scale_arg}),\n                               CreateOperatorDef(\n                                   \"Div\",\n                                   \"\",\n                                   std::vector<string>{GI(0), O(0)},\n                                   std::vector<string>{GI(0)})};\n  }\n};\nREGISTER_GRADIENT(Sqrt, GetSqrtGradient);\n} // namespace caffe2\n", "meta": {"hexsha": "e3a7880720e86e33627eb2668d21d0b98dcd7a17", "size": 1604, "ext": "cc", "lang": "C++", "max_stars_repo_path": "caffe2/operators/sqrt_op.cc", "max_stars_repo_name": "shigengtian/caffe2", "max_stars_repo_head_hexsha": "e19489d6acd17fea8ca98cd8e4b5b680e23a93c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-17T02:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-17T02:19:57.000Z", "max_issues_repo_path": "caffe2/operators/sqrt_op.cc", "max_issues_repo_name": "shigengtian/caffe2", "max_issues_repo_head_hexsha": "e19489d6acd17fea8ca98cd8e4b5b680e23a93c5", "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": "caffe2/operators/sqrt_op.cc", "max_forks_repo_name": "shigengtian/caffe2", "max_forks_repo_head_hexsha": "e19489d6acd17fea8ca98cd8e4b5b680e23a93c5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-20T09:14:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-20T09:14:48.000Z", "avg_line_length": 32.08, "max_line_length": 77, "alphanum_fraction": 0.5436408978, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5071665326564045}}
{"text": "#include <Eigen/Core>\nusing namespace Eigen;\nvoid foo(Vector4f &u, Vector4f &v, Vector4f &w) {\n  EIGEN_ASM_COMMENT(\"begin\");\n  u = v + 3 * w;\n  EIGEN_ASM_COMMENT(\"end\");\n}\n", "meta": {"hexsha": "5dbe720b23d00b9fd0e405293e4e45d816f67e25", "size": 172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/vectorization_test.cpp", "max_stars_repo_name": "willsheffler/rosette", "max_stars_repo_head_hexsha": "199fdbf18e9fceb5324cd7bae9b47c3feb47af73", "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/test/vectorization_test.cpp", "max_issues_repo_name": "willsheffler/rosette", "max_issues_repo_head_hexsha": "199fdbf18e9fceb5324cd7bae9b47c3feb47af73", "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/test/vectorization_test.cpp", "max_forks_repo_name": "willsheffler/rosette", "max_forks_repo_head_hexsha": "199fdbf18e9fceb5324cd7bae9b47c3feb47af73", "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.5, "max_line_length": 49, "alphanum_fraction": 0.6686046512, "num_tokens": 59, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5071665321723361}}
{"text": "//\n// Created by philipp on 26.12.19.\n//\n\n#ifndef FUNNELS_CPP_DYNAMICS_HH\n#define FUNNELS_CPP_DYNAMICS_HH\n\n#include <Eigen/Core>\n#include <cmath>\n#include <cassert>\n\nusing namespace Eigen;\n\nclass kinematic_2d_sys_t{\npublic:\n  constexpr static const size_t _dimx=4, _dimv=2, _dimu=2;\n  \n  static void compute(MatrixXd &x, const VectorXd &u, const VectorXd &t){\n    assert(x.cols()==t.size());\n    assert(u.rows()==_dimu && x.rows()==_dimx && u.rows()==_dimv);\n    // State vector is [x,y,dx,dy]\n    const Vector2d x0 = x.block<_dimx-_dimv,1>(0,0);\n    size_t n = t.size();\n    // Set velocity\n    // For a kinematic sys, the velocity can change instantly\n    x.block(_dimx-_dimv,0,_dimv,n).colwise() = u;\n    // Compute state\n    for (size_t i=0; i<n; i++){\n      x.block<_dimx-_dimv,1>(0,i) = x0 + u*t(i);\n    }\n    // Done\n  }\n};\n#endif //FUNNELS_CPP_DYNAMICS_HH\n", "meta": {"hexsha": "639eaa74342fe38995c82ec55b993f48c6601995", "size": 864, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/funnels/dynamics.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/dynamics.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/dynamics.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": 24.6857142857, "max_line_length": 73, "alphanum_fraction": 0.6435185185, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839876, "lm_q2_score": 0.6334102567576902, "lm_q1q2_score": 0.5071665206064502}}
{"text": "#ifndef CX_DQMC_GREENS_REPLICA_RENYI_GS_HPP\n#define CX_DQMC_GREENS_REPLICA_RENYI_GS_HPP\n\n#include <complex>\n#include <libdqmc/cx_dqmc_abstract_greens.hpp>\n#include <libdqmc/la.hpp>\n#include <libdqmc/cx_density.hpp>\n#include <libdqmc/parameters.hpp>\n#include <libdqmc/cx_workspace.hpp>\n#include <libdqmc/cx_checkerboard.hpp>\n#include <libdqmc/cx_interactions.hpp>\n#include <libdqmc/cx_calculate_greens_ft.hpp>\n#include <alps/alea.h>\n#include <boost/multi_array.hpp>\n#include <exception>\n#include <cstring>\n\ntypedef boost::multi_array<double, 3> aux_spin_3t;\n\nnamespace cx_dqmc {\n    \n    class greens_replica_renyi_gs : public cx_dqmc::abstract_greens {\n\n    public:       \n\tbool first_initialization;\n\t\n\tcx_mat_t u_temp, t_temp;\n\tcx_mat ket, ket_sqr, bra, bra_sqr;\n\tvec ket_d, bra_d, d_temp;\n\n\tcx_mat_t Ul, Um, Ur, Tl, Tm, Tr;\n\tvec_t Dl, Dm, Dr;\n\t\n\tint det_method;\n\tbool fresh_sign;\n\t\n\tgreens_replica_renyi_gs(dqmc::parameters* p_,\n\t\t\t\tcx_dqmc::workspace* ws_,\n\t\t\t\tcx_dqmc::workspace* reg_ws_,\n\t\t\t\taux_spin_3t* s)\n\t    : cx_dqmc::abstract_greens(p_, ws_, reg_ws_, s) {};\n\t\n\tvoid initialize();\t\n\tvoid build_stack();\n\tint propagate(alps::Observable& stability);\n\t\n\tvoid ket_update(int start, int stop,\n\t\t\tint idx, int target);\n\tvoid bra_update(int start, int stop,\n\t\t\tint idx, int target);\n\t\n\tvoid update_remove_interaction();\n\tvoid update_add_interaction();\n\n\tvoid slice_sequence(int start, int stop) {}; \n\tvoid slice_sequence_left(int start, int stop, cx_mat& M);\n\tvoid slice_sequence_left_renyi(int start, int stop, cx_mat& M);\n\tvoid slice_sequence_left_t(int start, int stop, cx_mat& M);\n\tvoid slice_sequence_left_renyi_t(int start, int stop, cx_mat& M);\n\tvoid slice_sequence_right(int start, int stop, cx_mat& M);\n\t\n\tvoid slice_matrix_left(int slice, cx_mat& M, bool inv = false);\n\tvoid slice_matrix_left_t(int slice, cx_mat& M, bool inv = false);\n\tvoid slice_matrix_left_renyi_t(int slice, cx_mat& M, bool inv = false);\n\tvoid slice_matrix_right(int slice, cx_mat& M, bool inv = false);\n\n\tvoid slice_matrix_left_renyi(int slice, cx_mat& M, bool inv = false);\n\tvoid slice_matrix_right_renyi(int slice, cx_mat& M, bool inv = false);\n\n\tvoid hopping_matrix_left(int slice, cx_mat& M, bool inv = false);\n\tvoid hopping_matrix_right(int slice, cx_mat& M, bool inv = false);\n\tvoid hopping_matrix_left_renyi(int slice, cx_mat& M, bool inv = false);\n\tvoid hopping_matrix_right_renyi(int slice, cx_mat& M, bool inv = false);\n\n\tvoid interaction_matrix_left(int slice, cx_mat& M,\n\t\t\t\t     int bond_group, bool inv = false);\n\tvoid interaction_matrix_right(int slice, cx_mat& M,\n\t\t\t\t      int bond_group, bool inv = false);\n\n\tvoid regularize_svd(vec& in, vec& out);\n\n\tinline void prep_bra(cx_mat& col, vec& diag, cx_mat& sqr) {\t    \n\t    using namespace std;\n\t    bra = col.transpose();\n\t    bra_d = diag;\n\t    bra_sqr = sqr.transpose();\n\n\t    dqmc::la::thin_col_to_invertible(col, ws->mat_1);\n\t    Tr = ws->mat_1.transpose().eval();\n\t    regularize_svd(diag, Dr);\n\t    Ur.setIdentity();\n\t    Ur.block(0, 0, ws->particles, ws->particles) = sqr.transpose().eval();\n\n\t    \n\t    // dqmc::la::thin_col_to_invertible(col, Ul);\t    \n\t    // regularize_svd(diag, Dl);\n\t    // Tl.setIdentity();\n\t    // Tl.block(0, 0, ws->particles, ws->particles) = sqr;\t    \n\n\t}\n\n\tinline void prep_ket(cx_mat& col, vec& diag,\n\t\t\t     cx_mat& sqr) {\n\t    using namespace std;\n\t    ket = col;\n\t    ket_d = diag;\n\t    ket_sqr = sqr;\n\n\t    // dqmc::la::thin_col_to_invertible(col, ws->mat_1);\n\t    // Tr = ws->mat_1.transpose().eval();\n\t    // regularize_svd(diag, Dr);\n\t    // Ur.setIdentity();\n\t    // Ur.block(0, 0, ws->particles, ws->particles) = sqr.transpose().eval();\n\t    \n\t    dqmc::la::thin_col_to_invertible(col, Ul);\t    \n\t    regularize_svd(diag, Dl);\n\t    Tl.setIdentity();\n\t    Tl.block(0, 0, ws->particles, ws->particles) = sqr;\t    \n\t}\n\n\tvoid log_weight();\n\tvoid log_weight_full_piv();\n\tvoid calculate_greens_exact(int slice);\n\tvoid calculate_greens_general();\n\tvoid calculate_greens_half_compressed();\n\tvoid calculate_greens_basic();\n\tinline void calculate_greens() {\n\t    using namespace std;\n\n\t    if (p->escalate_stability == false) {\n\t\tif (p->basic_stability == true) {\n\t\t    calculate_greens_basic();\n\t\t} else if (p->half_stability == true) {\n\t\t    calculate_greens_half_compressed();\n\t\t} else if (p->full_stability == true) {\n\t\t    calculate_greens_general();\n\t\t}\n\t    } else {\n\t\tif (int(stability[idx]) == 0) {\n\t\t    calculate_greens_basic();\n\t\t} else if (int(stability[idx]) == 1) {\n\t\t    calculate_greens_half_compressed();\n\t\t} else if (int(stability[idx]) == 2) {\n\t\t    calculate_greens_general();\n\t\t}\n\t    }\n\n\t    if (current_slice % slices == 0) return;\n\n\t    double stability_check = check_stability();\n\t    stability_checks[idx] = stability_check;\n\t    \n\t    if (stability_check > 1e-1) {\n\t\tif (int(stability[idx]) != 2) {\n\t\t    cout << p->outp << \"renyi - Escalating stability at \" << idx << \" to \"\n\t\t\t << int(stability[idx] + 1) << endl;\n\t\t}\n\t\tstability[idx] = std::min(2, int(stability[idx]) + 1);\n\t\tif (idx - direction >= 0 && idx - direction < n_elements) {\n\t\t    stability[idx - direction] = std::min(2, int(stability[idx - direction]) + 1);\n\t\t}\n\t    }\n\t}\n\n\n    \tdouble check_stability();\t    \n\n\tvoid enlarge(int replica, cx_mat_t& in, cx_mat_t& out);\n\tvoid enlarge(int replica, vec_t& in, vec_t& out);\n\tvoid enlarge_thin(int replica, cx_mat_t& in, cx_mat_t& out);\n\tvoid enlarge_thin(int replica, vec_t& in, vec_t& out);\n\tvoid enlarge_thin_ized_col(int replica, cx_mat_t& in, cx_mat_t& out);\n\tvoid enlarge_thin_ized_row(int replica, cx_mat_t& in, cx_mat_t& out);\n    };\n}\n#endif\n", "meta": {"hexsha": "8c13500f2b39441038cd94bca042c4fd288e85f2", "size": 5578, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libdqmc/cx_dqmc_greens_replica_renyi_gs.hpp", "max_stars_repo_name": "pebroecker/DQMC", "max_stars_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "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": "libdqmc/cx_dqmc_greens_replica_renyi_gs.hpp", "max_issues_repo_name": "pebroecker/DQMC", "max_issues_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libdqmc/cx_dqmc_greens_replica_renyi_gs.hpp", "max_forks_repo_name": "pebroecker/DQMC", "max_forks_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "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.5141242938, "max_line_length": 84, "alphanum_fraction": 0.6805306561, "num_tokens": 1619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5071420700937447}}
{"text": "#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file\n#include \"catch.hpp\"\n\n#include <math.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <simulator2/world.hpp>\n#include <simulator2/vision.hpp>\n\n#include <iostream>\n\nnamespace fishbowl = cuauv::fishbowl;\n\n// body 3-2-1\nEigen::Quaterniond euler_to_quat(double h, double p, double r)\n{\n    return Eigen::Quaterniond(Eigen::AngleAxisd(h, Eigen::Vector3d::UnitZ())\n                            * Eigen::AngleAxisd(p, Eigen::Vector3d::UnitY())\n                            * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX()));\n}\n\nTEST_CASE(\"SAP Camera basic functionality\", \"[vision]\") {\n    sim::world w;\n    Eigen::Quaterniond pq(1, 0, 0, 0);\n    Eigen::Vector3d px(-5, -3, 0);\n    double f = 1;\n\n    sim::entity_id eid = w.add_entity(sim::entity(1, 1, sim::inertia_tensor(1, 1, 1), Eigen::Quaterniond(1, 0, 0, 0)));\n    sim::entity& e = w.get_entity(eid);\n    e.x = Eigen::Vector3d(-4, -3, 0);\n\n    sim::camera cam(&w, &pq, &px, euler_to_quat(-M_PI/2, 0, 0), Eigen::Vector3d(1, 1, -1), f);\n    Eigen::Vector2d x;\n    double r, d;\n\n    std::tie(x, r, d) = cam.query(eid);\n    REQUIRE(x[0] == Approx(0));\n    REQUIRE(x[1] == Approx(1));\n    REQUIRE(r != 0);\n\n    // reposition #1\n\n    e.x = Eigen::Vector3d(-4, -1, 0);\n\n    std::tie(x, r, d) = cam.query(eid);\n    REQUIRE(x[0] == Approx(0));\n    REQUIRE(x[1] == Approx(-1));\n    REQUIRE(r == 0);\n\n    // resposition #2\n\n    e.x = Eigen::Vector3d(-3, -4, 0);\n\n    std::tie(x, r, d) = cam.query(eid);\n    REQUIRE(x[0] == Approx(0.5));\n    REQUIRE(x[1] == Approx(0.5));\n    REQUIRE(r != 0);\n\n    // change focal length\n\n    cam.f = 0.5;\n    cam.step();\n\n    std::tie(x, r, d) = cam.query(eid);\n    REQUIRE(x[0] == Approx(0.25));\n    REQUIRE(x[1] == Approx(0.25));\n    REQUIRE(r != 0);\n}\n", "meta": {"hexsha": "5e64078804a47cec8ce8e0a2a0e324c440e9d802", "size": 1834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fishbowl/tests/vision_test.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/tests/vision_test.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/tests/vision_test.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": 25.8309859155, "max_line_length": 119, "alphanum_fraction": 0.5703380589, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5071420700937446}}
{"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 a,b;\n    cin >> a >> b;\n    auto result = max(a + a - 1, max(a + b, b + b - 1));\n    cout << result << endl;\n    return 0;\n}", "meta": {"hexsha": "bd9e2433c13942edceca9669e84d346379f6abec", "size": 435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc124/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": "abc124/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": "abc124/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": 18.9130434783, "max_line_length": 56, "alphanum_fraction": 0.6390804598, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.507142065249219}}
{"text": "#include \"common.h\"\n#include \"ConformalBlock.h\"\n#include \"gegenbauer_polynomial.hpp\"\n#include <iostream>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/pow.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n\nusing namespace boost::math;\n\nfloat_type& RCoefficients::GetCachedRI(int type, int n) {\n    return this->cacheRI[type * MaxOrder + n -1];\n}\n\nfloat_type& RCoefficients::GetCachedRII(int type, int l, int n) {\n    boost::unordered_map<int, float_type>::iterator it = cacheR.find(type * 64 * 64 + n * 64 + l);\n    if (it != cacheR.end()) {\n        return it->second;\n    } else {\n        cacheR[type * 64 * 64 + n * 64 + l] = std::numeric_limits<float_type>::max();\n        return cacheR[type * 64 * 64 + n * 64 + l];\n    }\n}\n\nfloat_type RCoefficients::RI(int n) {\n    float_type& ret = GetCachedRI(0, n);\n    if (ret != std::numeric_limits<float_type>::max()) return ret;\n    ret = RI_NonDelta(n) * rising_factorial((dlt12 + 1.0 - n) / 2, n) * rising_factorial((dlt34 + 1.0 - n) / 2, n);\n    return ret;\n}\n\n// the delta independent part of RI.\nfloat_type RCoefficients::RI_NonDelta(int n) {\n    float_type fac = factorial<float_type>(n);\n    i64 p = ((i64)1) << n;\n    float_type ret = p / (fac * fac) * n;\n\n    if (n % 2 == 0) return -ret;\n    return ret;\n}\n\nfloat_type RCoefficients::RI_dDelta12(int n) {\n    float_type& ret = GetCachedRI(1, n);\n    if (ret != std::numeric_limits<float_type>::max()) return ret;\n    ret = RI_dDelta(n, dlt12, dlt34);\n    return ret;\n}\n\nfloat_type RCoefficients::RI_dDelta34(int n) {\n    float_type& ret = GetCachedRI(2, n);\n    if (ret != std::numeric_limits<float_type>::max()) return ret;\n    ret = RI_dDelta(n, dlt34, dlt12);\n    return ret;\n}\n\nfloat_type RCoefficients::RI_dDelta(int n, float_type deltaDiffA, float_type deltaDiffB) {\n    if (!IsInteger((deltaDiffA + 1 - n) / 2)) {\n        return digammaDiff((deltaDiffA + 1 - n) / 2, n) * RI(n) * .5;\n    } else {\n        int x = (int)floor((deltaDiffA + 1 - n) / 2 + EPS);\n        if (x > 0 || x + n <= 0) {\n            return digammaDiff((deltaDiffA + 1 - n) / 2, n) * RI(n) * .5;\n        } else {                \n            // -n + 1 <= x <= 0 need special handling because digammaDiff() has a pole and RI() is zero.\n            // now, RI() ~ (x)_n, the (x)_n factor has a pole\n            float_type ret = rising_factorial((deltaDiffB + 1.0 - n) / 2, n) * 0.5;\n            ret *= factorial<float_type>(-x) * factorial<float_type>(x + n - 1);\n            if (x % 2 != 0) ret = -ret;\n\n            return ret * RI_NonDelta(n);\n        }\n    }\n}\n\nfloat_type RCoefficients::RII(int l, int n) {\n    float_type& ret = GetCachedRII(0, l, n);\n    if (ret != std::numeric_limits<float_type>::max()) return ret;\n    ret = RII_NonDelta(l, n) * rising_factorial((dlt12 + 1.0 - n) / 2, n) * rising_factorial((dlt34 + 1.0 - n) / 2, n);\n    return ret;\n}\n\n// the delta independent part of RII.\nfloat_type RCoefficients::RII_NonDelta(int l, int n) {\n    float_type ret = binomial_coefficient<float_type>(l, n) * n;\n    ret /= factorial<float_type>(n);\n    ret /= (((i64)1) << n);\n\n    float_type h = d / 2;\n    if (abs(h - 1) < EPS && l == n) {\n        // if h == 1 and l == n, zero factors of numerator and denominator cancel out.\n        ret /= rising_factorial(h + l - n, n);\n        \n    } else {\n        ret /= rising_factorial(h + l - n, n) * rising_factorial(h + l - n - 1, n);\n        ret *= rising_factorial(d + l - n - 2, n);\n    }\n\n    if (n % 2 == 0) return -ret;\n    return ret;\n}\n\nfloat_type RCoefficients::RII_dDelta12(int l, int n) {\n    float_type& ret = GetCachedRII(1, l, n);\n    if (ret != std::numeric_limits<float_type>::max()) return ret;\n    ret = RII_dDelta(l, n, dlt12, dlt34);\n    return ret;\n}\n\nfloat_type RCoefficients::RII_dDelta34(int l, int n) {\n    float_type& ret = GetCachedRII(2, l, n);\n    if (ret != std::numeric_limits<float_type>::max()) return ret;\n    ret = RII_dDelta(l, n, dlt34, dlt12);\n    return ret;\n}\n\nfloat_type RCoefficients::RII_dDelta(int l, int n, float_type deltaDiffA, float_type deltaDiffB) {\n    if (!IsInteger((deltaDiffA + 1 - n) / 2)) {\n        return digammaDiff((deltaDiffA + 1 - n) / 2, n) * RII(l, n) * .5;\n    } else {\n        int x = (int)floor((deltaDiffA + 1 - n) / 2 + EPS);\n        if (x > 0 || x + n <= 0) {\n            return digammaDiff((deltaDiffA + 1 - n) / 2, n) * RII(l, n) * .5;\n        } else {                \n            // -n + 1 <= x <= 0 need special handling because digammaDiff() has a pole and RII() is zero.\n            // now, RII() ~ (x)_n, the (x)_n factor has a pole\n            float_type ret = rising_factorial((deltaDiffB + 1.0 - n) / 2, n) * 0.5;\n            ret *= factorial<float_type>(-x) * factorial<float_type>(x + n - 1);\n            if (x % 2 != 0) ret = -ret;\n\n            return ret * RII_NonDelta(l, n);\n        }\n    }\n}\n\nfloat_type RCoefficients::RIII(int l, int n) {\n    float_type& ret = GetCachedRII(3, l, n);\n    if (ret != std::numeric_limits<float_type>::max()) return ret;\n    float_type h = d / 2;\n    ret = rising_factorial((dlt12 + h + l - n) / 2, n) * rising_factorial((dlt12 - h - l - n + 2) / 2, n);\n    ret *= rising_factorial((dlt34 + h + l - n) / 2, n) * rising_factorial((dlt34 - h - l - n + 2) / 2, n) * RIII_NonDelta(l, n);\n    return ret;\n}\n\nfloat_type RCoefficients::RIII_NonDelta(int l, int n) {\n    float_type h = d / 2;\n    float_type ret;    \n    // if h is not integer, there is no poles.\n    if (!IsInteger(h)) {\n        ret = rising_factorial(h - n - 1, 2 * n);\n        ret /= rising_factorial(h + l - n - 1, 2 * n) * rising_factorial(h + l - n, 2 * n);\n    } else {\n        int ih = (int)floor(h + EPS);\n        if (n >= ih - 1 && n < ih + l - 1) { \n            // in this case, the numerate part is zero, and denominator is nonzero\n            return .0;\n        } else if (2 * n >= l + 1 && n == ih + l - 1) {\n            // in this case, the zeros of numerate and denominate cancel out.\n            ret = 1.0 / binomial_coefficient<float_type>(2 * n - 1, l);\n            ret /= rising_factorial(h + l - n, 2 * n);\n            if (l % 2 == 1) ret = -ret;\n        } else {\n            return 0.0; // temperary return 0 because the following workaround leads to divergent results.\n\n            // n > h + l - 1 case, numerator is zero but denominator is float_type-zero\n            // to avoid infinity, we let h -> h + EPS\n/*            float_type hh = h - EPS;\n            float_type inf = rising_factorial(hh - n - 1, 2 * n) / rising_factorial(hh + l - n - 1, 2 * n);\n            inf /=  rising_factorial(hh + l - n, 2 * n);\n            ret *= inf;*/\n        }\n    }\n\n    float_type fac = factorial<float_type>(n);\n    ret *= n / (fac * fac);\n\n    if (n % 2 == 0) return -ret;\n    return ret;\n}\n\nfloat_type RCoefficients::RIII_dDelta12(int l, int n) {\n    float_type& ret = GetCachedRII(4, l, n);\n    if (ret != std::numeric_limits<float_type>::max()) return ret;\n    ret = RIII_dDelta(l, n, dlt12, dlt34);\n    return ret;\n}\n\nfloat_type RCoefficients::RIII_dDelta34(int l, int n) {\n    float_type& ret = GetCachedRII(5, l, n);\n    if (ret != std::numeric_limits<float_type>::max()) return ret;\n    ret = RIII_dDelta(l, n, dlt34, dlt12);\n    return ret;\n}\n\nfloat_type RCoefficients::RIII_dDelta(int l, int n, float_type deltaDiffA, float_type deltaDiffB) {\n    float_type h = d / 2;\n    float_type ret1;\n    if (!IsInteger((deltaDiffA - h - l - n + 2) / 2)) {\n        ret1 = digammaDiff((deltaDiffA - h - l - n + 2) / 2, n) * RIII(l, n);\n    } else {\n        int x = (int)floor((deltaDiffA - h - l - n + 2) / 2 + EPS);\n        if (x > 0 || x + n <= 0) {\n            ret1 = digammaDiff((deltaDiffA - h - l - n + 2) / 2, n) * RIII(l, n);\n        } else {                \n            // -n + 1 <= x <= 0 need special handling because digammaDiff() has a pole and RII() is zero.\n            // now, RII() ~ (x)_n, the (x)_n factor has a pole\n            ret1 = rising_factorial((deltaDiffA + h + l - n) / 2, n);\n            ret1 *= rising_factorial((deltaDiffB + h + l - n) / 2, n) * rising_factorial((deltaDiffB - h - l - n + 2) / 2, n);\n            ret1 *= factorial<float_type>(-x) * factorial<float_type>(x + n - 1);\n            if (x % 2 != 0) ret1 = -ret1;\n\n            ret1 *= RIII_NonDelta(l, n);\n        }\n    }\n\n    float_type ret2;\n    if (!IsInteger((deltaDiffA + h + l - n) / 2)) {\n        ret2 = digammaDiff((deltaDiffA + h + l - n) / 2, n) * RIII(l, n);\n    } else {\n        int x = (int)floor((deltaDiffA + h + l - n) / 2 + EPS);\n        if (x > 0 || x + n <= 0) {\n            ret2 = digammaDiff((deltaDiffA + h + l - n) / 2, n) * RIII(l, n);\n        } else {                \n            // -n + 1 <= x <= 0 need special handling because digammaDiff() has a pole and RII() is zero.\n            // now, RII() ~ (x)_n, the (x)_n factor has a pole\n            ret2 = rising_factorial((deltaDiffA - h - l - n + 2) / 2, n);\n            ret2 *= rising_factorial((deltaDiffB + h + l - n) / 2, n) * rising_factorial((deltaDiffB - h - l - n + 2) / 2, n);\n            ret2 *= factorial<float_type>(-x) * factorial<float_type>(x + n - 1);\n            if (x % 2 != 0) ret2 = -ret2;\n\n            ret2 *= RIII_NonDelta(l, n);\n        }\n    }\n\n    return (ret1 + ret2) * 0.5;\n}\n\nfloat_type ConformalBlockScalars::HInfinity(int l, float_type r, float_type eta) {\n    float_type ret;\n    if (hCache.Get(l, &ret)) return ret;\n\n    float_type h = d / 2;\n    ret = pow(1 - r * r, 1 - h);\n    ret /= pow(r * r - 2 * r * eta + 1, (1 - dlt12 + dlt34) / 2);\n    ret /= pow(r * r + 2 * r * eta + 1, (1 + dlt12 - dlt34) / 2);\n    ret *= factorial<float_type>(l);\n    ret /= (((i64)1) << l);\n\n    if (abs(h - 1) > EPS) {\n        ret /= rising_factorial(h - 1, l);\n        float_type x[1];\n        x[0] = eta;\n        float_type *v = gegenbauer_polynomial_value(l, 1, h - 1, x);\n        ret *= v[l + 0 * (l + 1)];\n        delete v;\n    } else if (l != 0) {\n        // for the h == 1 and l == 0 case, (h-1)_l == 1 == gegenbauer(l, h-1);\n        // for the h == 1 and l > 0 case, the zeros of (h-1)_l and gegenbauer(l, h-1) cancel out\n        ret *= GegenbauerDAlphaAt0(l, eta) / factorial<float_type>(l - 1);\n    }\n\n    hCache.Set(l, ret);\n    return ret;\n}\n\nfloat_type ConformalBlockScalars::HInfinity_dDelta12(int l, float_type r, float_type eta) {\n    return HInfinity_dDelta(l, r, eta);\n}\n\nfloat_type ConformalBlockScalars::HInfinity_dDelta34(int l, float_type r, float_type eta) {\n    return -HInfinity_dDelta(l, r, eta);\n}\n\nfloat_type ConformalBlockScalars::HInfinity_dDelta(int l, float_type r, float_type eta) {\n    return 0.5 * HInfinity(l, r, eta) * log((r * r - 2 * eta * r + 1)/(r * r + 2 * eta * r + 1));\n}\n\nfloat_type ConformalBlockScalars::HRecursion(float_type delta, int l, float_type r, float_type eta, int order) {\n    int idelta = std::numeric_limits<int>::max();\n    float_type ret;\n    if (IsInteger(delta)) {\n        idelta = (int)floor(delta + EPS);\n        if (hCache.Get(idelta, l, order, &ret)) return ret;\n    }\n\n    ret = HInfinity(l, r, eta);\n    if (order == 0) return ret;\n\n    float_type deltaAs;\n    int la, na;\n\n    // type I\n    for (int n = 1; n <= order; n++) {\n        deltaAs = 1 - l - n;\n        la = l + n;\n        na = n;\n        // this if statement is only for the following case: \n        // when the exchange operator is identity, i.e, delta==l==0,\n        // then delta - deltaAs can be zero.\n        if (abs(delta - deltaAs) < EPS) continue;\n        ret += pow(4 * r, na) * rCoef->RI(n) / (delta - deltaAs) * HRecursion(deltaAs + na, la, r, eta, order - na);\n    }\n\n    // type II\n    for (int n = 1; n <= order && n <= l; n++) {\n        deltaAs = l + d - 1 - n;\n        la = l - n;\n        na = n;\n        if (abs(delta - deltaAs) < EPS) continue;\n        ret += pow(4 * r, na) * rCoef->RII(l, n) / (delta - deltaAs) * HRecursion(deltaAs + na, la, r, eta, order - na);\n    }\n\n    // type III\n    for (int n = 1; n + n <= order; n++) {\n        deltaAs = d / 2 - n;\n        la = l;\n        na = 2 * n;\n        if (abs(delta - deltaAs) < EPS) continue;\n        ret += pow(4 * r, na) * rCoef->RIII(l, n) / (delta - deltaAs) * HRecursion(deltaAs + na, la, r, eta, order - na);\n    }\n\n    if (idelta != std::numeric_limits<int>::max()) {\n        hCache.Set(idelta, l, order, ret);\n    }\n\n    return ret;\n}\n\n#if CONFORMAL_BLOCK_NORMALIZATION == 1\n\nfloat_type ConformalBlockScalars::NormalizationFactor(int l) {\n    assert(l >= 0);\n    assert(l < 63);\n\n    float_type ret = (float_type)(((i64)1)<<l);\n    if (l % 2 == 1) ret = -ret;\n    if (abs(d - 2) < EPS) {\n        return ret;\n    } else {\n        return ret * rising_factorial(d/2 - 1.0, l) / rising_factorial(d - 2.0, l);\n    }\n}\n\n#endif\n\nfloat_type ConformalBlockScalars::evaluate(float_type delta, int l, float_type r, float_type eta, int order) {\n    hCache.ClearIfNew(r, eta);\n#if CONFORMAL_BLOCK_NORMALIZATION == 1\n    float_type prefactor = pow(r, delta) * NormalizationFactor(l);\n    float_type hr = HRecursion(delta, l, r, eta, order);\n    return  prefactor * hr;\n#else\n    return pow(4 * r, delta) * HRecursion(delta, l, r, eta, order);\n#endif\n\n}\n\nfloat_type ConformalBlockScalars::dDelta(float_type delta, int l, float_type r, float_type eta, int order) {\n#if CONFORMAL_BLOCK_NORMALIZATION == 1\n    float_type ret = log(r) * evaluate(delta, l, r, eta, order);\n    ret += pow(r, delta) * NormalizationFactor(l) * dHdDelta(delta, l, r, eta, order);\n#else\n    float_type ret = log(4 * r) * evaluate(delta, l, r, eta, order);\n    ret += pow(4 * r, delta) * dHdDelta(delta, l, r, eta, order);\n#endif\n    return ret;\n}\n\nfloat_type ConformalBlockScalars::dHdDelta(float_type delta, int l, float_type r, float_type eta, int order) {\n    float_type deltaAs, ret = 0.0;\n    int la, na;\n\n    // type I\n    for (int n = 1; n <= order; n++) {\n        deltaAs = 1 - l - n;\n        la = l + n;\n        na = n;\n        // this if statement is only for the following case: \n        // when the exchange operator is identity, i.e, delta==l==0,\n        // then delta - deltaAs can be zero.\n        if (abs(delta - deltaAs) < EPS) continue;\n        ret -= pow(4 * r, na) * rCoef->RI(n) / ((delta - deltaAs) * (delta - deltaAs)) * HRecursion(deltaAs + na, la, r, eta, order - na);\n    }\n\n    // type II\n    for (int n = 1; n <= order && n <= l; n++) {\n        deltaAs = l + d - 1 - n;\n        la = l - n;\n        na = n;\n        if (abs(delta - deltaAs) < EPS) continue;\n        ret -= pow(4 * r, na) * rCoef->RII(l, n) / ((delta - deltaAs) * (delta - deltaAs)) * HRecursion(deltaAs + na, la, r, eta, order - na);\n    }\n\n    // type III\n    for (int n = 1; n + n <= order; n++) {\n        deltaAs = d / 2 - n;\n        la = l;\n        na = 2 * n;\n        if (abs(delta - deltaAs) < EPS) continue;\n        ret -= pow(4 * r, na) * rCoef->RIII(l, n) / ((delta - deltaAs) * (delta - deltaAs)) * HRecursion(deltaAs + na, la, r, eta, order - na);\n    }\n\n    return ret;\n}\n\nfloat_type ConformalBlockScalars::dDelta12(float_type delta, int l, float_type r, float_type eta, int order) {\n    hDiff12Cache.ClearIfNew(r, eta);\n    hCache.ClearIfNew(r, eta);\n#if CONFORMAL_BLOCK_NORMALIZATION == 1\n    return pow(r, delta) * NormalizationFactor(l) * dHdDelta12(delta, l, r, eta, order);\n#else\n    return pow(4 * r, delta) * dHdDelta12(delta, l, r, eta, order);\n#endif\n\n}\n\nfloat_type ConformalBlockScalars::dHdDelta12(float_type delta, int l, float_type r, float_type eta, int order) {\n    int idelta = std::numeric_limits<int>::max();\n    float_type ret;\n    if (IsInteger(delta)) {\n        idelta = (int)floor(delta + EPS);\n        if (hDiff12Cache.Get(idelta, l, order, &ret)) return ret;\n    }\n\n    ret = HInfinity_dDelta12(l, r, eta);\n    if (order == 0) return ret;\n\n    float_type deltaAs;\n    int la, na;\n\n    // type I\n    for (int n = 1; n <= order; n++) {\n        deltaAs = 1 - l - n;\n        la = l + n;\n        na = n;\n        // this if statement is only for the following case: \n        // when the exchange operator is identity, i.e, delta==l==0,\n        // then delta - deltaAs can be zero.\n        if (abs(delta - deltaAs) < EPS) continue;\n        ret += pow(4 * r, na) / (delta - deltaAs) * (dHdDelta12(deltaAs + na, la, r, eta, order - na) * rCoef->RI(n) + HRecursion(deltaAs + na, la, r, eta, order - na) * rCoef->RI_dDelta12(n));\n    }\n\n    // type II\n    for (int n = 1; n <= order && n <= l; n++) {\n        deltaAs = l + d - 1 - n;\n        la = l - n;\n        na = n;\n        if (abs(delta - deltaAs) < EPS) continue;\n        ret += pow(4 * r, na) / (delta - deltaAs) * (dHdDelta12(deltaAs + na, la, r, eta, order - na) * rCoef->RII(l, n)+ HRecursion(deltaAs + na, la, r, eta, order - na) * rCoef->RII_dDelta12(l,n));\n    }\n\n    // type III\n    for (int n = 1; n + n <= order; n++) {\n        deltaAs = d / 2 - n;\n        la = l;\n        na = 2 * n;\n        if (abs(delta - deltaAs) < EPS) continue;\n        ret += pow(4 * r, na) / (delta - deltaAs) * (dHdDelta12(deltaAs + na, la, r, eta, order - na) * rCoef->RIII(l, n)+ HRecursion(deltaAs + na, la, r, eta, order - na) * rCoef->RIII_dDelta12(l,n));\n    }\n\n    if (idelta != std::numeric_limits<int>::max()) {\n        hDiff12Cache.Set(idelta, l, order, ret);\n    }\n\n\n    return ret;\n}\n\nfloat_type ConformalBlockScalars::dDelta34(float_type delta, int l, float_type r, float_type eta, int order) {\n    hDiff34Cache.ClearIfNew(r, eta);\n    hCache.ClearIfNew(r, eta);\n#if CONFORMAL_BLOCK_NORMALIZATION == 1\n    return pow(r, delta) * NormalizationFactor(l) * dHdDelta34(delta, l, r, eta, order);\n#else\n    return pow(4 * r, delta) * dHdDelta34(delta, l, r, eta, order);\n#endif\n}\n\nfloat_type ConformalBlockScalars::dHdDelta34(float_type delta, int l, float_type r, float_type eta, int order) {\n    int idelta = std::numeric_limits<int>::max();\n    float_type ret;\n    if (IsInteger(delta)) {\n        idelta = (int)floor(delta + EPS);\n        if (hDiff34Cache.Get(idelta, l, order, &ret)) return ret;\n    }\n\n    ret = HInfinity_dDelta34(l, r, eta);\n    if (order == 0) return ret;\n    float_type deltaAs;\n    int la, na;\n\n    // type I\n    for (int n = 1; n <= order; n++) {\n        deltaAs = 1 - l - n;\n        la = l + n;\n        na = n;\n        // this if statement is only for the following case: \n        // when the exchange operator is identity, i.e, delta==l==0,\n        // then delta - deltaAs can be zero.\n        if (abs(delta - deltaAs) < EPS) continue;\n        ret += pow(4 * r, na) / (delta - deltaAs) * (dHdDelta34(deltaAs + na, la, r, eta, order - na) * rCoef->RI(n) + HRecursion(deltaAs + na, la, r, eta, order - na) * rCoef->RI_dDelta34(n));\n    }\n\n    // type II\n    for (int n = 1; n <= order && n <= l; n++) {\n        deltaAs = l + d - 1 - n;\n        la = l - n;\n        na = n;\n        if (abs(delta - deltaAs) < EPS) continue;\n        ret += pow(4 * r, na) / (delta - deltaAs) * (dHdDelta34(deltaAs + na, la, r, eta, order - na) * rCoef->RII(l, n)+ HRecursion(deltaAs + na, la, r, eta, order - na) * rCoef->RII_dDelta34(l,n));\n    }\n\n    // type III\n    for (int n = 1; n + n <= order; n++) {\n        deltaAs = d / 2 - n;\n        la = l;\n        na = 2 * n;\n        if (abs(delta - deltaAs) < EPS) continue;\n        ret += pow(4 * r, na) / (delta - deltaAs) * (dHdDelta34(deltaAs + na, la, r, eta, order - na) * rCoef->RIII(l, n)+ HRecursion(deltaAs + na, la, r, eta, order - na) * rCoef->RIII_dDelta34(l,n));\n    }\n\n    if (idelta != std::numeric_limits<int>::max()) {\n        hDiff34Cache.Set(idelta, l, order, ret);\n    }\n\n    return ret;\n}\n\n\n", "meta": {"hexsha": "c6a67315c0cdfda692ce7708574006eb40035737", "size": 19473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ConformalBlock.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/ConformalBlock.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/ConformalBlock.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": 36.8109640832, "max_line_length": 201, "alphanum_fraction": 0.5537410774, "num_tokens": 6481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5071420652492189}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <stdio.h>\n#include <assert.h>\n#include <math.h>\n#include <cmath>\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/SparseQR>\n#include <Eigen/SparseCholesky>\n#include <Eigen/OrderingMethods>\n#include \"mmio.hpp\"\n#include \"cxxopts.hpp\"\n#include \"tree.h\"\n#include \"partition.h\"\n#include \"util.h\"\n#include \"is.h\"\n\n\nusing namespace Eigen;\nusing namespace std;\n\ntypedef SparseMatrix<double, 0, int> SpMat; \n\nint main(int argc, char* argv[]){\n  \n     cxxopts::Options options(\"spaQR\", \"Sparsified QR for general sparse matrices\");\n     options.add_options()\n        (\"help\", \"Print help\")\n        (\"m,matrix\", \"Matrix file in martrix market format\", cxxopts::value<string>())\n        (\"l,lvl\",\"Number of levels\", cxxopts::value<int>())\n        // Geometry\n        (\"coordinates\", \"Coordinates MM array file. If provided, will do a geometric partitioning.\", cxxopts::value<string>())\n        (\"n,coordinates_n\", \"If provided with -n, will use a tensor n^d & geometric partitioning. Overwrites --coordinates\", cxxopts::value<int>()->default_value(\"-1\"))\n        (\"d,coordinates_d\", \"If provided with -d, will use a tensor n^d & geometric partitioning. Overwrites --coordinates\", cxxopts::value<int>()->default_value(\"-1\"))\n        // Partition\n        (\"hsl\",\"Use bipartite matching routine from HSL to perform row ordering. Use only if compiled with USE_HSL=1 flag. Default false.\", cxxopts::value<int>()->default_value(\"0\"))\n        // Sparsification\n        (\"t,tol\", \"Tolerance\", cxxopts::value<double>()->default_value(\"1e-1\")) \n        (\"skip\", \"Skip sparsification\", cxxopts::value<int>()->default_value(\"0\")) \n        (\"order\", \"Specify order of scheme (1, 1.5) Default order=1. Use 1.5 to get a more accurate scheme but uses more memory.\", cxxopts::value<float>()->default_value(\"1\"))\n        (\"scale\", \"Do scaling. Default true.\", cxxopts::value<int>()->default_value(\"1\"))\n        // Iterative method\n        // (\"solver\",\"Wether to use CG or GMRES or CGLS. Default GMRES for square matrices and CGLS for rectangular.\", cxxopts::value<string>()->default_value(\"GMRES\"))\n        (\"i,iterations\",\"Iterative solver iterations\", cxxopts::value<int>()->default_value(\"300\"))\n        (\"rhs\", \"Provide RHS to solve in matrix market format\", cxxopts::value<string>())\n        (\"res\", \"Desired relative residual for the iterative solver. Default 1e-12\", cxxopts::value<double>()->default_value(\"1e-12\")) \n\n        // Use solvers from Eigen library\n        (\"useEigenLSCG\",\"If true, run CGLS scheme with standard diagonal preconditioner from Eigen library. Default false.\", cxxopts::value<int>()->default_value(\"0\"))\n        (\"useEigenQR\",\"If true, run SparseQR with default ordering from Eigen library. Default false.\", cxxopts::value<int>()->default_value(\"0\"))\n        (\"useCholesky\",\"If true, run SimplicialLDL^T with AMDOrdering from Eigen library. Default false.\", cxxopts::value<int>()->default_value(\"0\"));\n    \n\n    auto result = options.parse(argc, argv);\n    if (result.count(\"help\")) {\n        cout << options.help({\"\", \"Group\"}) << endl;\n        exit(0);\n    }\n\n    if ( (!result.count(\"matrix\"))  ) {\n        cout << \"--matrix is mandatory\" << endl;\n        exit(0);\n    }\n\n    string matrix = result[\"matrix\"].as<string>();\n    int nlevels;\n\n\n    // Geometry\n    string coordinates;\n    int cn = result[\"coordinates_n\"].as<int>();\n    int cd = result[\"coordinates_d\"].as<int>();\n    bool geo_file = (result.count(\"coordinates\") > 0);\n    if ( (cn == -1 && cd >= 0) || (cd == -1 && cn >= 0) ) {\n        cout << \"cn and cd should be both provided, or none should be provided\" << endl;\n        return 1;\n    }\n    bool geo_tensor = (cn >= 0 && cd >= 0);\n    bool geo = geo_file || geo_tensor;\n    if(geo_file) {\n        coordinates = result[\"coordinates\"].as<string>();\n    }\n\n    // Load matrix\n    SpMat A = mmio::sp_mmread<double, int>(matrix);\n\n    if (A.rows() < A.cols()){\n        cout << \" <<< Warning!!! nrows < ncols. Finding QR on A.transpose() instead. \" << endl;\n        SpMat T = A.transpose();\n        A = T;\n    }\n    \n    int nrows = A.rows();\n    int ncols = A.cols();\n    cout << \"Matrix \" << matrix << \" with \" << nrows << \" rows,  \" << ncols << \" columns loaded\" << endl;\n\n    // Iterative method \n    bool useGMRES = (nrows == ncols) ? true : false;\n    bool useCGLS = (nrows > ncols) ? true : false;\n    int iterations = result[\"iterations\"].as<int>();\n    \n    bool useEigenLSCG = result[\"useEigenLSCG\"].as<int>();\n    bool useEigenQR = result[\"useEigenQR\"].as<int>();\n    bool useCholesky = result[\"useCholesky\"].as<int>();\n\n    double residual = result[\"res\"].as<double>();\n\n    if ( (!result.count(\"lvl\"))  ) {\n        cout << \"--Levels not provided\" << endl;\n        nlevels = ceil(log2(ncols/64));\n        cout << \" Levels set to ceil(log2(ncols/64)) =  \" << nlevels << endl;\n    }\n    else{\n        nlevels = result[\"lvl\"].as<int>();\n    }\n\n    // Partition\n    int hsl = result[\"hsl\"].as<int>();\n\n    // Sparsification parameters\n    int scale = result[\"scale\"].as<int>();\n    if (nrows != ncols && scale == 0){\n        cout << \"Scaling necessary for rectangular matrices\" << endl;\n        cout << \"Setting scale to 1\" << endl;\n        scale = 1;\n    }\n    double tol = result[\"tol\"].as<double>();\n    float order = result[\"order\"].as<float>();\n    \n    // Pre-process matrix to have columns of unit norm (diagonal scaling)\n    VectorXd Dentries(A.cols());\n    DiagonalMatrix<double, Eigen::Dynamic> D(A.cols());\n\n    auto pstart = wctime();\n    for (int i=0; i < A.cols(); ++i) {\n        double sum = 0;\n       for (SpMat::InnerIterator it(A,i); it; ++it){\n            sum += it.value()*it.value();\n       }\n       Dentries[i] = (double)(1.0/sqrt(sum));\n    }\n\n    D = Dentries.asDiagonal();\n    A = A*D*10;\n    auto pend = wctime();\n    cout << \"Pre-process time: \" << elapsed(pstart, pend) << endl;\n    \n\n    int skip = (tol == 0 ? nlevels-1 : result[\"skip\"].as<int>());\n    \n    // Load coordinates ?\n    MatrixXd X;\n    if(geo_tensor) {\n        if(pow(cn, cd) != ncols) {\n            cout << \"Error: cn and cd where both provided, but cn^cd != N where A is NxN\" << endl;\n            return 1;\n        }\n        X = linspace_nd(cn, cd);\n        cout << \"Tensor coordinate matrix of size \" << cn << \"^\" << cd << \" built\" << endl;\n    } else if(geo_file) {\n        X = mmio::dense_mmread<double>(coordinates);\n        cout << \"Coordinate file \" << X.rows() << \"x\" << X.cols() << \" loaded from \" << coordinates << endl;\n        if(X.cols() != ncols) {\n            cout << \"Error: coordinate file should hold a matrix of size d x N\" << endl;\n        }\n    }\n\n\n    // Tree\n    Tree t(nlevels, skip);\n    t.set_scale(scale);\n    t.set_tol(tol);\n    t.set_order(order);\n    t.set_hsl(hsl);\n\n\n    if (nrows == ncols) t.set_square(1); // default 0\n    if(geo) t.set_Xcoo(&X);\n\n    if (useEigenLSCG) {\n        VectorXd x = VectorXd::Zero(ncols);\n        VectorXd b = random(nrows,2021);\n        \n        LeastSquaresConjugateGradient<SpMat, LeastSquareDiagonalPreconditioner<double>> lscg;\n        lscg.compute(A);\n\n        LeastSquareDiagonalPreconditioner<double> diag_precond = lscg.preconditioner();\n\n        timer cgls0 = wctime();\n        auto iter = lscg_eigen(A, b, x, diag_precond, iterations, residual, true);\n        timer cgls1 = wctime();\n\n        cout << \"CGLS error: \" << scientific <<  (A.transpose()*(A*x-b)).norm() / (A.transpose()*b).norm() << endl;\n        cout << \"  CGLS: \" << elapsed(cgls0, cgls1) << \" s.\" << endl;\n        cout << \"<<<<CGLS=\" << iter << endl;\n        return 0;\n    }\n\n    if (useEigenQR){\n        VectorXd x = VectorXd::Zero(ncols);\n        VectorXd b = random(nrows,2021);\n        \n        A.makeCompressed();  \n        SparseQR<SpMat, COLAMDOrdering<int>> eigenQR;\n\n        eigenQR.setPivotThreshold(1e-14);\n        cout << \"\\n <<<< Using Eigen SparseQR routine...\" << endl;\n        timer qr0 = wctime();\n        eigenQR.compute(A);\n        timer qr1 = wctime();\n        cout << \"Time to factorize: \" << elapsed(qr0, qr1) << \" s.\" << endl;\n\n        timer qrs0 = wctime();\n        x = eigenQR.solve(b);\n        timer qrs1 = wctime();\n        cout << \"Time to solve: \" << elapsed(qrs0, qrs1) << \" s.\" << endl;\n        cout << \"Error: \" << scientific << (A.transpose()*(A*x-b)).norm() / (A.transpose()*b).norm() << endl; \n        \n        return 0;\n    }\n\n    if (useCholesky){\n        VectorXd x = VectorXd::Zero(ncols);\n        VectorXd b = random(nrows,2021);\n\n        VectorXd Atb = A.transpose()*b;\n        SpMat AtA = A.transpose()*A;\n        \n        AtA.makeCompressed();\n        SimplicialLLT<SpMat, Lower, AMDOrdering<int> > eigenCholesky;\n        cout << \"\\n <<<< Using Eigen's SimplicalLL^T routine...\" << endl;\n\n        timer qr0 = wctime();\n        eigenCholesky.compute(AtA);\n        timer qr1 = wctime();\n        cout << \"Time to factorize: \" << elapsed(qr0, qr1) << \" s.\" << endl;\n\n        timer qrs0 = wctime();\n        x = eigenCholesky.solve(Atb);\n        timer qrs1 = wctime();\n\n        cout << \"Time to solve: \" << elapsed(qrs0, qrs1) << \" s.\" << endl;\n        cout << \"Error: \" << scientific << (A.transpose()*(A*x-b)).norm() / (A.transpose()*b).norm() << endl; \n        \n        return 0;\n    }\n\n    // Partition\n    t.partition(A);\n    // Setup\n    t.assemble(A);\n\n    // Factorize\n    int err = t.factorize();\n\n\n    if (!err)\n    // Run one solve\n    {\n         // Random b\n        {\n            VectorXd b = random(nrows, 2021);\n            VectorXd bcopy = b;\n            VectorXd x(ncols, 1);\n            x.setZero();\n            timer tsolv_0 = wctime();\n\n            if (nrows == ncols){\n                t.solve(bcopy, x);\n                timer tsolv = wctime();\n                cout << \"<<<<tsolv=\" << elapsed(tsolv_0, tsolv) << endl;\n                cout << \"One-time solve (Random b):\" << endl;             \n                cout << \"<<<<|(Ax-b)|/|b| : \" << scientific <<  ((A*x-b)).norm() / (b).norm() << endl;\n            }\n            else {\n                t.solve_nrml(A.transpose()*bcopy, x);\n                timer tsolv = wctime();\n                cout << \"<<<<tsolv=\" << elapsed(tsolv_0, tsolv) << endl;\n                cout << \"One-time solve (Random b):\" << endl;             \n                cout << \"<<<<|A'(Ax-b)|/|A'b| : \" << scientific <<  (A.transpose()*(A*x-b)).norm() / (A.transpose()*b).norm() << endl;\n            }\n        }\n    }\n\n    bool verb = false; \n    int iter = 0;\n    if (!err)\n    {\n        VectorXd x = VectorXd::Zero(ncols);\n        VectorXd b;\n        if ((!result.count(\"rhs\"))){\n            b = random(nrows,2021);\n        }\n        else {\n            string rhs_file = result[\"rhs\"].as<string>();\n            b = mmio::vector_mmread<double>(rhs_file);\n        }\n        VectorXd bcopy = b;\n\n    \n        if(useGMRES) {\n            timer gmres0 = wctime();\n            iter = gmres(A, b, x, t, iterations, iterations, residual, verb);\n            timer gmres1 = wctime();\n            cout << \"GMRES: #iterations: \" << iter << \", residual |Ax-b|/|b|: \" << (A*x-b).norm() / b.norm() << endl;\n            cout << \"  GMRES: \" << elapsed(gmres0, gmres1) << \" s.\" << endl;\n            cout << \"<<<<GMRES=\" << iter << endl;\n        }\n        else if(useCGLS){\n            timer cg0 = wctime();\n\n            Index max_iters = (long)iterations;\n            iter = cgls(A, b, x, t, max_iters, residual, verb);\n            cout << \"CGLS: #iterations: \" << iter << \", residual |A'(Ax-b)|/|A'(b)|: \" << (A.transpose()*(A*x-b)).norm() / (A.transpose()*b).norm() << endl;\n            timer cg1 = wctime();\n            cout << \"  CGLS: \" << elapsed(cg0, cg1) << \" s.\" << endl;\n            cout << \"<<<<CGLS=\" << iter << endl;\n        }\n    }\n\n  return 0;  \n}\n", "meta": {"hexsha": "02283f4a1b78f37e45564bb7155b30bd04600d3b", "size": 11753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spaQR.cpp", "max_stars_repo_name": "Abeynaya/spaQR_public", "max_stars_repo_head_hexsha": "4fd28b1a23c73feb914b40e4285d5a076ffc9058", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spaQR.cpp", "max_issues_repo_name": "Abeynaya/spaQR_public", "max_issues_repo_head_hexsha": "4fd28b1a23c73feb914b40e4285d5a076ffc9058", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spaQR.cpp", "max_forks_repo_name": "Abeynaya/spaQR_public", "max_forks_repo_head_hexsha": "4fd28b1a23c73feb914b40e4285d5a076ffc9058", "max_forks_repo_licenses": ["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.274691358, "max_line_length": 182, "alphanum_fraction": 0.5432655492, "num_tokens": 3227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5071165288614126}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// importance_sampling::scale_to_finite_sum.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_IMPORTANCE_SAMPLING_WEIGHTS_SCALE_TO_FINITE_SUM_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_IMPORTANCE_SAMPLING_WEIGHTS_SCALE_TO_FINITE_SUM_HPP_ER_2009\n#include <numeric>\n#include <boost/lambda/lambda.hpp>\n#include <boost/range.hpp>\n#include <boost/statistics/detail/importance_sampling/weights/find_scale_to_finite_sum.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace importance_sampling{\n\n    // Scales each element [b,e) by the smallest factor, c, such that the sum \n    // is finite.\n    //\n    // [ Warning ] c is not insensitive to permutations of [b,e), due\n    // to non-associativity in the fp system\n    template<typename InIt>\n    typename iterator_value<InIt>::type \n    scale_to_finite_sum(InIt b,InIt e,\n        typename iterator_value<InIt>::type low,\n        typename iterator_value<InIt>::type high\n    );\n\n    template<typename InIt>\n    typename iterator_value<InIt>::type \n    scale_to_finite_sum(InIt b,InIt e);\n\n    // Implementation //\n\n    template<typename InIt>\n    typename iterator_value<InIt>::type \n    scale_to_finite_sum(InIt b,InIt e,\n        typename iterator_value<InIt>::type low,\n        typename iterator_value<InIt>::type high\n    ){\n        typedef typename iterator_value<InIt>::type val_;\n        val_ c = find_scale_finite_sum(\n            b,e,low,high\n        );\n        std::transform(\n            b,\n            e,\n            b,\n            boost::lambda::_1 / c\n        );\n        return c;\n    }\n\n    template<typename InIt>\n    typename iterator_value<InIt>::type \n    scale_to_finite_sum(InIt b,InIt e){\n        typedef typename iterator_value<InIt>::type val_;\n        val_ c = find_scale_to_finite_sum(b,e);\n        std::transform(\n            b,\n            e,\n            b,\n            boost::lambda::_1 / c\n        );\n        return c;\n    }\n\n}// importance_weights\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "d94dc468661e4d03333b7da19bafba9c91e2e160", "size": 2482, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "importance_sampling/boost/statistics/detail/importance_sampling/weights/scale_to_finite_sum.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": "importance_sampling/boost/statistics/detail/importance_sampling/weights/scale_to_finite_sum.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": "importance_sampling/boost/statistics/detail/importance_sampling/weights/scale_to_finite_sum.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": 32.6578947368, "max_line_length": 91, "alphanum_fraction": 0.5821917808, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5071165235555114}}
{"text": "//Author: Dr. Shantanu Shahane\n#ifndef postprocessing_functions_H_ /* Include guard */\n#define postprocessing_functions_H_\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <float.h>\n#include <string.h>\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/SparseExtra>\n#include <Eigen/SparseLU>\n#include <Eigen/OrderingMethods>\n#include <Eigen/Core>\n#include <unistd.h>\n#include \"_hypre_utilities.h\"\n#include \"HYPRE_krylov.h\"\n#include \"HYPRE.h\"\n#include \"HYPRE_parcsr_ls.h\"\n#include \"general_functions.hpp\"\n#include \"class.hpp\"\nusing namespace std;\n\ndouble calc_boundary_flux(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &phi_x, Eigen::VectorXd &phi_y, int bc_tag);\n\ndouble calc_boundary_flux(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &phi_x, Eigen::VectorXd &phi_y, Eigen::VectorXd &phi_z, int bc_tag);\n\nvoid write_simulation_details(POINTS &points, CLOUD &cloud, PARAMETERS &parameters);\n\nvoid write_iteration_details(PARAMETERS &parameters);\n\nvoid calc_navier_stokes_residuals_2D(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u, Eigen::VectorXd &v, Eigen::VectorXd &p);\n\nvoid calc_navier_stokes_residuals_2D(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u, Eigen::VectorXd &v, Eigen::VectorXd &p, Eigen::VectorXd &body_force_x, Eigen::VectorXd &body_force_y);\n\nvoid calc_navier_stokes_errors_2D(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_ana, Eigen::VectorXd &v_ana, Eigen::VectorXd &p_ana, Eigen::VectorXd &u_num, Eigen::VectorXd &v_num, Eigen::VectorXd &p_num);\n\nvoid calc_navier_stokes_residuals_3D(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u, Eigen::VectorXd &v, Eigen::VectorXd &w, Eigen::VectorXd &p);\n\nvoid calc_navier_stokes_residuals_3D(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u, Eigen::VectorXd &v, Eigen::VectorXd &w, Eigen::VectorXd &p, Eigen::VectorXd &body_force_x, Eigen::VectorXd &body_force_y, Eigen::VectorXd &body_force_z);\n\nvoid calc_navier_stokes_errors_3D(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_ana, Eigen::VectorXd &v_ana, Eigen::VectorXd &w_ana, Eigen::VectorXd &p_ana, Eigen::VectorXd &u_num, Eigen::VectorXd &v_num, Eigen::VectorXd &w_num, Eigen::VectorXd &p_num);\n\nvoid write_navier_stokes_errors_2D(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_ana, Eigen::VectorXd &v_ana, Eigen::VectorXd &p_ana, Eigen::VectorXd &u_num, Eigen::VectorXd &v_num, Eigen::VectorXd &p_num);\n\nvoid write_navier_stokes_residuals_2D(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u, Eigen::VectorXd &v, Eigen::VectorXd &p, string output_file_suffix);\n\nvoid write_tecplot_steady_variables(POINTS &points, PARAMETERS &parameters, vector<string> &variable_names, vector<Eigen::VectorXd *> &variable_pointers);\n\nvoid write_tecplot_temporal_variables_header(POINTS &points, PARAMETERS &parameters, vector<string> &variable_names);\n\nvoid write_tecplot_temporal_variables(POINTS &points, PARAMETERS &parameters, vector<string> &variable_names, vector<Eigen::VectorXd *> &variable_pointers, int it);\n\nvoid write_csv_xyz(vector<double> &vect, PARAMETERS &parameters, const char *file_name);\n\nvoid write_csv_temporal_data_init(int size, const char *file_name);\n\nvoid write_csv_temporal_data(Eigen::VectorXd &data, double time, const char *file_name);\n\n#endif", "meta": {"hexsha": "cd3ae670fcf830defbf57c2e5157df3204a45aed", "size": 3364, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "header_files/postprocessing_functions.hpp", "max_stars_repo_name": "shahaneshantanu/memphys", "max_stars_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "header_files/postprocessing_functions.hpp", "max_issues_repo_name": "shahaneshantanu/memphys", "max_issues_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "header_files/postprocessing_functions.hpp", "max_forks_repo_name": "shahaneshantanu/memphys", "max_forks_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-07T00:32:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:32:37.000Z", "avg_line_length": 54.2580645161, "max_line_length": 266, "alphanum_fraction": 0.7895362663, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5071165235555114}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2016 Michael Rabinovich\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 \"flip_avoiding_line_search.h\"\n#include \"line_search.h\"\n#include \"PI.h\"\n\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace igl\n{\n  namespace flip_avoiding\n  {\n    //---------------------------------------------------------------------------\n    // x - array of size 3\n    // In case 3 real roots: => x[0], x[1], x[2], return 3\n    //         2 real roots: x[0], x[1],          return 2\n    //         1 real root : x[0], x[1] \u00b1 i*x[2], return 1\n    // http://math.ivanovo.ac.ru/dalgebra/Khashin/poly/index.html\n    IGL_INLINE int SolveP3(std::vector<double>& x,double a,double b,double c)\n    { // solve cubic equation x^3 + a*x^2 + b*x + c\n      using namespace std;\n      double a2 = a*a;\n        double q  = (a2 - 3*b)/9;\n      double r  = (a*(2*a2-9*b) + 27*c)/54;\n        double r2 = r*r;\n      double q3 = q*q*q;\n      double A,B;\n        if(r2<q3)\n        {\n          double t=r/sqrt(q3);\n          if( t<-1) t=-1;\n          if( t> 1) t= 1;\n          t=acos(t);\n          a/=3; q=-2*sqrt(q);\n          x[0]=q*cos(t/3)-a;\n          x[1]=q*cos((t+(2*igl::PI))/3)-a;\n          x[2]=q*cos((t-(2*igl::PI))/3)-a;\n          return(3);\n        }\n        else\n        {\n          A =-pow(fabs(r)+sqrt(r2-q3),1./3);\n          if( r<0 ) A=-A;\n          B = A==0? 0 : q/A;\n\n          a/=3;\n          x[0] =(A+B)-a;\n          x[1] =-0.5*(A+B)-a;\n          x[2] = 0.5*sqrt(3.)*(A-B);\n          if(fabs(x[2])<1e-14)\n          {\n            x[2]=x[1]; return(2);\n          }\n          return(1);\n        }\n    }\n\n    IGL_INLINE double get_smallest_pos_quad_zero(double a,double b, double c)\n    {\n      using namespace std;\n      double t1, t2;\n      if(std::abs(a) > 1.0e-10)\n      {\n        double delta_in = pow(b, 2) - 4 * a * c;\n        if(delta_in <= 0)\n        {\n          return INFINITY;\n        }\n\n        double delta = sqrt(delta_in); // delta >= 0\n        if(b >= 0) // avoid subtracting two similar numbers\n        {\n          double bd = - b - delta;\n          t1 = 2 * c / bd;\n          t2 = bd / (2 * a);\n        }\n        else\n        {\n          double bd = - b + delta;\n          t1 = bd / (2 * a);\n          t2 = (2 * c) / bd;\n        }\n\n        assert (std::isfinite(t1));\n        assert (std::isfinite(t2));\n\n        if(a < 0) std::swap(t1, t2); // make t1 > t2\n        // return the smaller positive root if it exists, otherwise return infinity\n        if(t1 > 0)\n        {\n          return t2 > 0 ? t2 : t1;\n        }\n        else\n        {\n          return INFINITY;\n        }\n      }\n      else\n      {\n        if(b == 0) return INFINITY; // just to avoid divide-by-zero\n        t1 = -c / b;\n        return t1 > 0 ? t1 : INFINITY;\n      }\n    }\n\n    IGL_INLINE double get_min_pos_root_2D(const Eigen::MatrixXd& uv,\n                                          const Eigen::MatrixXi& F,\n                                          Eigen::MatrixXd& d,\n                                          int f)\n    {\n      using namespace std;\n    /*\n          Finding the smallest timestep t s.t a triangle get degenerated (<=> det = 0)\n          The following code can be derived by a symbolic expression in matlab:\n\n          Symbolic matlab:\n          U11 = sym('U11');\n          U12 = sym('U12');\n          U21 = sym('U21');\n          U22 = sym('U22');\n          U31 = sym('U31');\n          U32 = sym('U32');\n\n          V11 = sym('V11');\n          V12 = sym('V12');\n          V21 = sym('V21');\n          V22 = sym('V22');\n          V31 = sym('V31');\n          V32 = sym('V32');\n\n          t = sym('t');\n\n          U1 = [U11,U12];\n          U2 = [U21,U22];\n          U3 = [U31,U32];\n\n          V1 = [V11,V12];\n          V2 = [V21,V22];\n          V3 = [V31,V32];\n\n          A = [(U2+V2*t) - (U1+ V1*t)];\n          B = [(U3+V3*t) - (U1+ V1*t)];\n          C = [A;B];\n\n          solve(det(C), t);\n          cf = coeffs(det(C),t); % Now cf(1),cf(2),cf(3) holds the coefficients for the polynom. at order c,b,a\n        */\n\n      int v1 = F(f,0); int v2 = F(f,1); int v3 = F(f,2);\n      // get quadratic coefficients (ax^2 + b^x + c)\n      const double& U11 = uv(v1,0);\n      const double& U12 = uv(v1,1);\n      const double& U21 = uv(v2,0);\n      const double& U22 = uv(v2,1);\n      const double& U31 = uv(v3,0);\n      const double& U32 = uv(v3,1);\n\n      const double& V11 = d(v1,0);\n      const double& V12 = d(v1,1);\n      const double& V21 = d(v2,0);\n      const double& V22 = d(v2,1);\n      const double& V31 = d(v3,0);\n      const double& V32 = d(v3,1);\n\n      double a = V11*V22 - V12*V21 - V11*V32 + V12*V31 + V21*V32 - V22*V31;\n      double b = U11*V22 - U12*V21 - U21*V12 + U22*V11 - U11*V32 + U12*V31 + U31*V12 - U32*V11 + U21*V32 - U22*V31 - U31*V22 + U32*V21;\n      double c = U11*U22 - U12*U21 - U11*U32 + U12*U31 + U21*U32 - U22*U31;\n\n      return get_smallest_pos_quad_zero(a,b,c);\n    }\n\n    IGL_INLINE double get_min_pos_root_3D(const Eigen::MatrixXd& uv,\n                                          const Eigen::MatrixXi& F,\n                                          Eigen::MatrixXd& direc,\n                                          int f)\n    {\n      using namespace std;\n      /*\n          Searching for the roots of:\n            +-1/6 * |ax ay az 1|\n                    |bx by bz 1|\n                    |cx cy cz 1|\n                    |dx dy dz 1|\n          Every point ax,ay,az has a search direction a_dx,a_dy,a_dz, and so we add those to the matrix, and solve the cubic to find the step size t for a 0 volume\n          Symbolic matlab:\n            syms a_x a_y a_z a_dx a_dy a_dz % tetrahedera point and search direction\n            syms b_x b_y b_z b_dx b_dy b_dz\n            syms c_x c_y c_z c_dx c_dy c_dz\n            syms d_x d_y d_z d_dx d_dy d_dz\n            syms t % Timestep var, this is what we're looking for\n\n\n            a_plus_t = [a_x,a_y,a_z] + t*[a_dx,a_dy,a_dz];\n            b_plus_t = [b_x,b_y,b_z] + t*[b_dx,b_dy,b_dz];\n            c_plus_t = [c_x,c_y,c_z] + t*[c_dx,c_dy,c_dz];\n            d_plus_t = [d_x,d_y,d_z] + t*[d_dx,d_dy,d_dz];\n\n            vol_mat = [a_plus_t,1;b_plus_t,1;c_plus_t,1;d_plus_t,1]\n            //cf = coeffs(det(vol_det),t); % Now cf(1),cf(2),cf(3),cf(4) holds the coefficients for the polynom\n            [coefficients,terms] = coeffs(det(vol_det),t); % terms = [ t^3, t^2, t, 1], Coefficients hold the coeff we seek\n      */\n      int v1 = F(f,0); int v2 = F(f,1); int v3 = F(f,2); int v4 = F(f,3);\n      const double& a_x = uv(v1,0);\n      const double& a_y = uv(v1,1);\n      const double& a_z = uv(v1,2);\n      const double& b_x = uv(v2,0);\n      const double& b_y = uv(v2,1);\n      const double& b_z = uv(v2,2);\n      const double& c_x = uv(v3,0);\n      const double& c_y = uv(v3,1);\n      const double& c_z = uv(v3,2);\n      const double& d_x = uv(v4,0);\n      const double& d_y = uv(v4,1);\n      const double& d_z = uv(v4,2);\n\n      const double& a_dx = direc(v1,0);\n      const double& a_dy = direc(v1,1);\n      const double& a_dz = direc(v1,2);\n      const double& b_dx = direc(v2,0);\n      const double& b_dy = direc(v2,1);\n      const double& b_dz = direc(v2,2);\n      const double& c_dx = direc(v3,0);\n      const double& c_dy = direc(v3,1);\n      const double& c_dz = direc(v3,2);\n      const double& d_dx = direc(v4,0);\n      const double& d_dy = direc(v4,1);\n      const double& d_dz = direc(v4,2);\n\n      // Find solution for: a*t^3 + b*t^2 + c*d +d = 0\n      double a = a_dx*b_dy*c_dz - a_dx*b_dz*c_dy - a_dy*b_dx*c_dz + a_dy*b_dz*c_dx + a_dz*b_dx*c_dy - a_dz*b_dy*c_dx - a_dx*b_dy*d_dz + a_dx*b_dz*d_dy + a_dy*b_dx*d_dz - a_dy*b_dz*d_dx - a_dz*b_dx*d_dy + a_dz*b_dy*d_dx + a_dx*c_dy*d_dz - a_dx*c_dz*d_dy - a_dy*c_dx*d_dz + a_dy*c_dz*d_dx + a_dz*c_dx*d_dy - a_dz*c_dy*d_dx - b_dx*c_dy*d_dz + b_dx*c_dz*d_dy + b_dy*c_dx*d_dz - b_dy*c_dz*d_dx - b_dz*c_dx*d_dy + b_dz*c_dy*d_dx;\n\n      double b = a_dy*b_dz*c_x - a_dy*b_x*c_dz - a_dz*b_dy*c_x + a_dz*b_x*c_dy + a_x*b_dy*c_dz - a_x*b_dz*c_dy - a_dx*b_dz*c_y + a_dx*b_y*c_dz + a_dz*b_dx*c_y - a_dz*b_y*c_dx - a_y*b_dx*c_dz + a_y*b_dz*c_dx + a_dx*b_dy*c_z - a_dx*b_z*c_dy - a_dy*b_dx*c_z + a_dy*b_z*c_dx + a_z*b_dx*c_dy - a_z*b_dy*c_dx - a_dy*b_dz*d_x + a_dy*b_x*d_dz + a_dz*b_dy*d_x - a_dz*b_x*d_dy - a_x*b_dy*d_dz + a_x*b_dz*d_dy + a_dx*b_dz*d_y - a_dx*b_y*d_dz - a_dz*b_dx*d_y + a_dz*b_y*d_dx + a_y*b_dx*d_dz - a_y*b_dz*d_dx - a_dx*b_dy*d_z + a_dx*b_z*d_dy + a_dy*b_dx*d_z - a_dy*b_z*d_dx - a_z*b_dx*d_dy + a_z*b_dy*d_dx + a_dy*c_dz*d_x - a_dy*c_x*d_dz - a_dz*c_dy*d_x + a_dz*c_x*d_dy + a_x*c_dy*d_dz - a_x*c_dz*d_dy - a_dx*c_dz*d_y + a_dx*c_y*d_dz + a_dz*c_dx*d_y - a_dz*c_y*d_dx - a_y*c_dx*d_dz + a_y*c_dz*d_dx + a_dx*c_dy*d_z - a_dx*c_z*d_dy - a_dy*c_dx*d_z + a_dy*c_z*d_dx + a_z*c_dx*d_dy - a_z*c_dy*d_dx - b_dy*c_dz*d_x + b_dy*c_x*d_dz + b_dz*c_dy*d_x - b_dz*c_x*d_dy - b_x*c_dy*d_dz + b_x*c_dz*d_dy + b_dx*c_dz*d_y - b_dx*c_y*d_dz - b_dz*c_dx*d_y + b_dz*c_y*d_dx + b_y*c_dx*d_dz - b_y*c_dz*d_dx - b_dx*c_dy*d_z + b_dx*c_z*d_dy + b_dy*c_dx*d_z - b_dy*c_z*d_dx - b_z*c_dx*d_dy + b_z*c_dy*d_dx;\n\n      double c = a_dz*b_x*c_y - a_dz*b_y*c_x - a_x*b_dz*c_y + a_x*b_y*c_dz + a_y*b_dz*c_x - a_y*b_x*c_dz - a_dy*b_x*c_z + a_dy*b_z*c_x + a_x*b_dy*c_z - a_x*b_z*c_dy - a_z*b_dy*c_x + a_z*b_x*c_dy + a_dx*b_y*c_z - a_dx*b_z*c_y - a_y*b_dx*c_z + a_y*b_z*c_dx + a_z*b_dx*c_y - a_z*b_y*c_dx - a_dz*b_x*d_y + a_dz*b_y*d_x + a_x*b_dz*d_y - a_x*b_y*d_dz - a_y*b_dz*d_x + a_y*b_x*d_dz + a_dy*b_x*d_z - a_dy*b_z*d_x - a_x*b_dy*d_z + a_x*b_z*d_dy + a_z*b_dy*d_x - a_z*b_x*d_dy - a_dx*b_y*d_z + a_dx*b_z*d_y + a_y*b_dx*d_z - a_y*b_z*d_dx - a_z*b_dx*d_y + a_z*b_y*d_dx + a_dz*c_x*d_y - a_dz*c_y*d_x - a_x*c_dz*d_y + a_x*c_y*d_dz + a_y*c_dz*d_x - a_y*c_x*d_dz - a_dy*c_x*d_z + a_dy*c_z*d_x + a_x*c_dy*d_z - a_x*c_z*d_dy - a_z*c_dy*d_x + a_z*c_x*d_dy + a_dx*c_y*d_z - a_dx*c_z*d_y - a_y*c_dx*d_z + a_y*c_z*d_dx + a_z*c_dx*d_y - a_z*c_y*d_dx - b_dz*c_x*d_y + b_dz*c_y*d_x + b_x*c_dz*d_y - b_x*c_y*d_dz - b_y*c_dz*d_x + b_y*c_x*d_dz + b_dy*c_x*d_z - b_dy*c_z*d_x - b_x*c_dy*d_z + b_x*c_z*d_dy + b_z*c_dy*d_x - b_z*c_x*d_dy - b_dx*c_y*d_z + b_dx*c_z*d_y + b_y*c_dx*d_z - b_y*c_z*d_dx - b_z*c_dx*d_y + b_z*c_y*d_dx;\n\n      double d = a_x*b_y*c_z - a_x*b_z*c_y - a_y*b_x*c_z + a_y*b_z*c_x + a_z*b_x*c_y - a_z*b_y*c_x - a_x*b_y*d_z + a_x*b_z*d_y + a_y*b_x*d_z - a_y*b_z*d_x - a_z*b_x*d_y + a_z*b_y*d_x + a_x*c_y*d_z - a_x*c_z*d_y - a_y*c_x*d_z + a_y*c_z*d_x + a_z*c_x*d_y - a_z*c_y*d_x - b_x*c_y*d_z + b_x*c_z*d_y + b_y*c_x*d_z - b_y*c_z*d_x - b_z*c_x*d_y + b_z*c_y*d_x;\n\n      if (std::abs(a)<=1.e-10)\n      {\n        return get_smallest_pos_quad_zero(b,c,d);\n      }\n      b/=a; c/=a; d/=a; // normalize it all\n      std::vector<double> res(3);\n      int real_roots_num = SolveP3(res,b,c,d);\n      switch (real_roots_num)\n      {\n        case 1:\n          return (res[0] >= 0) ? res[0]:INFINITY;\n        case 2:\n        {\n          double max_root = std::max(res[0],res[1]); double min_root = std::min(res[0],res[1]);\n          if (min_root > 0) return min_root;\n          if (max_root > 0) return max_root;\n          return INFINITY;\n        }\n        case 3:\n        default:\n        {\n          std::sort(res.begin(),res.end());\n          if (res[0] > 0) return res[0];\n          if (res[1] > 0) return res[1];\n          if (res[2] > 0) return res[2];\n          return INFINITY;\n        }\n      }\n    }\n\n    IGL_INLINE double compute_max_step_from_singularities(const Eigen::MatrixXd& uv,\n                                                          const Eigen::MatrixXi& F,\n                                                          Eigen::MatrixXd& d)\n    {\n      using namespace std;\n      double max_step = INFINITY;\n\n      // The if statement is outside the for loops to avoid branching/ease parallelizing\n      if (uv.cols() == 2)\n      {\n        for (int f = 0; f < F.rows(); f++)\n        {\n          double min_positive_root = get_min_pos_root_2D(uv,F,d,f);\n          max_step = std::min(max_step, min_positive_root);\n        }\n      }\n      else\n      { // volumetric deformation\n        for (int f = 0; f < F.rows(); f++)\n        {\n          double min_positive_root = get_min_pos_root_3D(uv,F,d,f);\n          max_step = std::min(max_step, min_positive_root);\n        }\n      }\n      return max_step;\n    }\n  }\n}\n\nIGL_INLINE double igl::flip_avoiding_line_search(\n  const Eigen::MatrixXi F,\n  Eigen::MatrixXd& cur_v,\n  Eigen::MatrixXd& dst_v,\n  std::function<double(Eigen::MatrixXd&)> energy,\n  double cur_energy)\n{\n  using namespace std;\n  Eigen::MatrixXd d = dst_v - cur_v;\n\n  double min_step_to_singularity = igl::flip_avoiding::compute_max_step_from_singularities(cur_v,F,d);\n  double max_step_size = std::min(1., min_step_to_singularity*0.8);\n\n  return igl::line_search(cur_v,d,max_step_size, energy, cur_energy);\n}\n\n#ifdef IGL_STATIC_LIBRARY\n#endif\n", "meta": {"hexsha": "f5034acf21d0b98fc58e48665cb7b32185124ceb", "size": 13008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/simpleuv/thirdparty/libigl/include/igl/flip_avoiding_line_search.cpp", "max_stars_repo_name": "MelvinG24/dust3d", "max_stars_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "thirdparty/simpleuv/thirdparty/libigl/include/igl/flip_avoiding_line_search.cpp", "max_issues_repo_name": "MelvinG24/dust3d", "max_issues_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "thirdparty/simpleuv/thirdparty/libigl/include/igl/flip_avoiding_line_search.cpp", "max_forks_repo_name": "MelvinG24/dust3d", "max_forks_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 40.523364486, "max_line_length": 1167, "alphanum_fraction": 0.5349784748, "num_tokens": 4581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5071165129437083}}
{"text": "#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <boost/program_options.hpp>\n#include \"IsingModel.h\"\n\nnamespace opt = boost::program_options;\n\nint main(int argc, char** argv) {\n    int rows, cols, nT, nH, nR, nS, frames, skip;\n    double Ti, Tf, Hi, Hf, J, mu, kB;\n    bool sim, vid;\n\n    opt::options_description params(\"Ising Model Parameters\");\n\n    params.add_options()\n        (\"help,h\", \"show usage\")\n        (\"rows,r\", opt::value< int >(&rows)->default_value(15), \"number of rows\")\n        (\"cols,c\", opt::value< int >(&cols)->default_value(15), \"number of columns\")\n        (\"nR\", opt::value< int >(&nR)->default_value(1000), \"number of relaxation steps\")\n        (\"nS\", opt::value< int >(&nS)->default_value(1000), \"sample size\")\n        (\"Ti,i\", opt::value<double>(&Ti)->default_value(1.5), \"initial temperature\")\n        (\"Tf\", opt::value<double>(&Tf)->default_value(3.5), \"final temperature\")\n        (\"Hi\", opt::value<double>(&Hi)->default_value(0.), \"initial magnetic field\")\n        (\"Hf\", opt::value<double>(&Hf)->default_value(1.), \"final magnetic field\")\n        (\"nT,n\", opt::value< int >(&nT)->default_value(1000), \"number of time steps\")\n        (\"nH\", opt::value< int >(&nH)->default_value(1), \"number of magnetic field steps\")\n        (\"frames,f\", opt::value< int >(&frames)->default_value(1000), \"number of frames\")\n        (\"skip,s\", opt::value< int >(&skip)->default_value(1), \"number of updates between frames\")\n        (\"J\", opt::value<double>(&J)->default_value(1.), \"ferromagnetic coupling constant\")\n        (\"kB\", opt::value<double>(&kB)->default_value(1.), \"Boltzmann's constant\")\n        (\"mu\", opt::value<double>(&mu)->default_value(1.), \"magnetic moment\")\n        (\"vid\", opt::value<bool>(&vid)->default_value(true), \"create a visualization of the relaxation algorithm\")\n        (\"sim\", opt::value<bool>(&sim)->default_value(true), \"run simulation and save results to a compressed numpy (npz) file\")\n        ;\n\n    opt::variables_map vm;\n    opt::store(opt::parse_command_line(argc, argv, params), vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << params << std::endl;\n        return 1;\n    }\n    else {\n        opt::notify(vm);\n\n        std::cout << \"\\n2D Ising Model Simulation\" << std::endl;\n        std::cout << \"=========================\" << std::endl;\n\n        if (sim) { // sim and vid are mutually exclusive, with sim taking precedence\n\n            std::cout << \"Running Simulation:\" << std::endl;\n            IsingModel ising(rows, cols);\n            ising.simulate(Ti, Tf, nT, Hi, Hf, nH, nR, nS);\n\n        }\n        else {\n            std::cout << \"Creating Visualization:\" << std::endl;\n            IsingModel ising(rows, cols);\n            ising.visualize(frames, skip, Ti, Hi);\n        }\n\n        std::cout << \"\\n\\nDone!\" << std::endl;\n        std::cout << \"=========================\" << std::endl;\n        return 0;\n    }\n}", "meta": {"hexsha": "1cc3ceab896c84985241bc519d43baa474a39fcf", "size": 2891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "IsingModel.cpp", "max_stars_repo_name": "ethank5149/Ising-Model-Visual", "max_stars_repo_head_hexsha": "1c83634504467cf4ee4347419f9adbf328773c11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IsingModel.cpp", "max_issues_repo_name": "ethank5149/Ising-Model-Visual", "max_issues_repo_head_hexsha": "1c83634504467cf4ee4347419f9adbf328773c11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IsingModel.cpp", "max_forks_repo_name": "ethank5149/Ising-Model-Visual", "max_forks_repo_head_hexsha": "1c83634504467cf4ee4347419f9adbf328773c11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-08T13:22:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T13:22:29.000Z", "avg_line_length": 43.803030303, "max_line_length": 128, "alphanum_fraction": 0.5752334832, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.507046300639966}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <boost/simd/arithmetic/include/functions/correct_fma.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/mone.hpp>\n#include <boost/simd/include/constants/inf.hpp>\n#include <boost/simd/include/constants/minf.hpp>\n#include <boost/simd/include/constants/nan.hpp>\n#include <boost/simd/include/constants/valmax.hpp>\n#include <boost/simd/include/constants/valmin.hpp>\n#include <boost/simd/include/constants/eps.hpp>\n#include <boost/simd/include/functions/simd/oneplus.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n\nNT2_TEST_CASE_TPL ( correct_fma_real,  BOOST_SIMD_SIMD_REAL_TYPES)\n{\n  using boost::simd::correct_fma;\n  using boost::simd::tag::correct_fma_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_EQUAL(correct_fma(boost::simd::Inf<vT>(), boost::simd::Inf<vT>(), boost::simd::Inf<vT>()), boost::simd::Inf<vT>());\n  NT2_TEST_EQUAL(correct_fma(boost::simd::Minf<vT>(), boost::simd::Minf<vT>(), boost::simd::Minf<vT>()), boost::simd::Nan<vT>());\n  NT2_TEST_EQUAL(correct_fma(boost::simd::Nan<vT>(), boost::simd::Nan<vT>(), boost::simd::Nan<vT>()), boost::simd::Nan<vT>());\n#endif\n  NT2_TEST_EQUAL(correct_fma(boost::simd::Mone<vT>(), boost::simd::Mone<vT>(), boost::simd::Mone<vT>()), boost::simd::Zero<vT>());\n  NT2_TEST_EQUAL(correct_fma(boost::simd::One<vT>(), boost::simd::One<vT>(), boost::simd::One<vT>()), boost::simd::Two<vT>());\n  NT2_TEST_EQUAL(correct_fma(boost::simd::One<vT>()+boost::simd::Eps<vT>(), boost::simd::One<vT>()-boost::simd::Eps<vT>(),boost::simd::Mone<vT>()), -boost::simd::Eps<vT>()*boost::simd::Eps<vT>());\n  NT2_TEST_EQUAL(correct_fma(boost::simd::Zero<vT>(), boost::simd::Zero<vT>(), boost::simd::Zero<vT>()), boost::simd::Zero<vT>());\n#ifndef  BOOST_SIMD_DONT_CARE_CORRECT_FMA_OVERFLOW\n  NT2_TEST_EQUAL(correct_fma(boost::simd::Valmax<vT>(), boost::simd::Two<vT>(), -boost::simd::Valmax<vT>()), boost::simd::Valmax<vT>());\n#endif\n} // end of test for floating_\n\n\nNT2_TEST_CASE_TPL ( correct_fma_si,  BOOST_SIMD_SIMD_INTEGRAL_SIGNED_TYPES)\n{\n  using boost::simd::correct_fma;\n  using boost::simd::tag::correct_fma_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n\n  // specific values tests\n  NT2_TEST_EQUAL(correct_fma(boost::simd::Mone<vT>(), boost::simd::Mone<vT>(), boost::simd::Mone<vT>()), boost::simd::Zero<vT>());\n  NT2_TEST_EQUAL(correct_fma(boost::simd::One<vT>(), boost::simd::One<vT>(), boost::simd::One<vT>()), boost::simd::Two<vT>());\n  NT2_TEST_EQUAL(correct_fma(boost::simd::Zero<vT>(), boost::simd::Zero<vT>(), boost::simd::Zero<vT>()), boost::simd::Zero<vT>());\n  NT2_TEST_EQUAL(correct_fma(boost::simd::Valmax<vT>(), boost::simd::Two<vT>(),  boost::simd::oneplus(boost::simd::Valmin<T>())), boost::simd::Valmax<vT>());\n} // end of test for floating_\n\nNT2_TEST_CASE_TPL ( correct_fma_ui,  BOOST_SIMD_SIMD_UNSIGNED_TYPES)\n{\n  using boost::simd::correct_fma;\n  using boost::simd::tag::correct_fma_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n\n  // specific values tests\n  NT2_TEST_EQUAL(correct_fma(boost::simd::One<vT>(), boost::simd::One<vT>(), boost::simd::One<vT>()), boost::simd::Two<vT>());\n  NT2_TEST_EQUAL(correct_fma(boost::simd::Zero<vT>(), boost::simd::Zero<vT>(), boost::simd::Zero<vT>()), boost::simd::Zero<vT>());\n} // end of test for floating_\n", "meta": {"hexsha": "2bfebdd7d7d14c40775d469694d350e5ad346139", "size": 4265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/unit/arithmetic/simd/correct_fma.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/unit/arithmetic/simd/correct_fma.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/boost/simd/base/unit/arithmetic/simd/correct_fma.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 55.3896103896, "max_line_length": 196, "alphanum_fraction": 0.6651817116, "num_tokens": 1217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5070462955641848}}
{"text": "/**\n * @file mesh_loader.cc\n * @author Daeyun Shin <daeyun@dshin.org>\n * @version 0.1\n * @date 2015-01-02\n * @copyright librender is free software released under the BSD 2-Clause\n * license.\n */\n#include \"mesh_loader.h\"\n\n#include <stdexcept>\n#include <armadillo>\n#include <boost/format.hpp>\n#include \"config.h\"\n#include \"graphics.h\"\n#include \"shape.h\"\n\nnamespace librender {\n\n/**\n * @brief Import shape from a Wavefront .obj file. Vertex normals are estimated\n *        if not provided.\n * @param[in] render_params\n * @param[out] mesh\n */\nvoid LoadObj(const RenderParams& render_params, Shape& mesh) {\n  std::vector<tinyobj::shape_t> shapes;\n  std::vector<tinyobj::material_t> materials;\n\n  std::string err =\n      tinyobj::LoadObj(shapes, materials, render_params.in_filename.c_str());\n\n  if (!err.empty()) throw std::runtime_error(err);\n  if (shapes.empty())\n    throw std::runtime_error(std::string(\"Shape not found in \") +\n                             render_params.in_filename);\n\n  const int kVertexDims = 3;\n  const int kTextureDims = 2;\n\n  for (tinyobj::shape_t shape : shapes) {\n    if (shape.mesh.positions.empty())\n      throw std::runtime_error(std::string(\"Vertex not found in \") +\n                               render_params.in_filename);\n    if (shape.mesh.indices.empty())\n      throw std::runtime_error(std::string(\"Face not found in \") +\n                               render_params.in_filename);\n\n    int kNumVertex = shape.mesh.positions.size() / kVertexDims;\n    int kNumFace = shape.mesh.indices.size() / kVertexDims;\n    arma::fmat shape_v(&shape.mesh.positions[0], kVertexDims, kNumVertex);\n    arma::umat shape_f(&shape.mesh.indices[0], kVertexDims, kNumFace);\n    arma::fmat shape_n;\n    arma::fmat shape_uv;\n\n    if (shape.mesh.normals.empty()) {\n      ComputeNormals(shape_v, shape_f, shape_n);\n    } else {\n      shape_n = arma::fmat(&shape.mesh.normals[0], kVertexDims, kNumVertex);\n    }\n\n    if (!shape.mesh.texcoords.empty()) {\n      shape_uv = arma::fmat(&shape.mesh.texcoords[0], kTextureDims, kNumVertex);\n      shape_uv.swap_rows(0, 1);\n    }\n\n    mesh.v = join_cols(mesh.v, shape_v);\n    mesh.ind = join_cols(mesh.ind, shape_f);\n    mesh.vn = join_cols(mesh.vn, shape_n);\n    mesh.uv = join_cols(mesh.uv, shape_uv);\n  }\n\n  mesh.vn = arma::normalise(mesh.vn);\n\n  if (render_params.will_normalize) {\n    NormalizeCoords(mesh.v);\n  }\n\n  switch (render_params.up_axis) {\n    case X:\n      mesh.v = arma::join_vert(mesh.v.rows(1, 2), mesh.v.row(0));\n      mesh.vn = arma::join_vert(mesh.vn.rows(1, 2), mesh.vn.row(0));\n      break;\n    case Y:\n      mesh.v = arma::join_vert(mesh.v.row(2), mesh.v.rows(0, 1));\n      mesh.vn = arma::join_vert(mesh.vn.row(2), mesh.vn.rows(0, 1));\n      break;\n    case Z:\n      // Nothing to do\n      break;\n  }\n\n  // RGBA color per vertex\n  mesh.vc.reshape(4, mesh.v.n_cols);\n  mesh.vc.each_col() = render_params.color;\n\n  mesh.type = ShapeType::kTriangles;\n}\n\n/**\n * @brief Compute the face and vertex normals from a triangle mesh of indexed\n *        vertices.\n * @param v[in] 3 by n vertices\n * @param f[in] 3 by m faces\n * @param vn[out] 3 by n vertex normals\n */\nvoid ComputeNormals(const arma::fmat& v, const arma::umat& f, arma::fmat& vn) {\n  arma::fmat a = v.cols(f.row(1)) - v.cols(f.row(0));\n  arma::fmat b = v.cols(f.row(2)) - v.cols(f.row(0));\n\n  // Cross product of each pair of columns\n  arma::fmat fn;\n  CrossCol(a, b, fn);\n\n  // Accumulate vertex normal\n  vn.zeros(v.n_rows, v.n_cols);\n  arma::umat indices = reshape(f.t(), 1, f.n_cols * 3);\n  vn.cols(indices) += arma::repmat(fn, 1, 3);\n\n  arma::fmat num_adj_f;\n  num_adj_f.zeros(1, v.n_cols);\n  num_adj_f(indices) += 1;\n\n  // Divide by the number of adjacent faces\n  vn /= arma::repmat(num_adj_f, 3, 1);\n}\n\n/**\n * @brief Compute a column-wise cross product of \\a a and \\a b.\n * @param[in] a,b 3 by m matrices\n * @param[out] out 3 by m matrix\n */\nvoid CrossCol(const arma::fmat& a, const arma::fmat& b, arma::fmat& out) {\n  out = join_cols(join_cols(a.row(1) % b.row(2) - a.row(2) % b.row(1),\n                            a.row(2) % b.row(0) - a.row(0) % b.row(2)),\n                  a.row(0) % b.row(1) - a.row(1) % b.row(0));\n}\n\n/**\n * @brief Re-scale the data points so that the maximum dimension range is 1 and\n *        the center of the object is at (0, 0).\n * @param v 3 by n matrix of vertices.\n */\nvoid NormalizeCoords(arma::fmat& v) {\n  arma::fvec vmax = arma::max(v, 1);\n  arma::fvec vmin = arma::min(v, 1);\n\n  arma::fvec range = vmax - vmin;\n\n  v.each_col() -= vmin + range / 2;\n  v /= arma::max(range);\n}\n}\n", "meta": {"hexsha": "e35580f58692fca9d9625ae3d928d724564386c1", "size": 4552, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/mesh_loader.cc", "max_stars_repo_name": "daeyun/Scry", "max_stars_repo_head_hexsha": "f4952ce39c6960266b022600445583f0a12858c3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T20:35:13.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-12T08:04:09.000Z", "max_issues_repo_path": "src/mesh_loader.cc", "max_issues_repo_name": "daeyun/Scry", "max_issues_repo_head_hexsha": "f4952ce39c6960266b022600445583f0a12858c3", "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/mesh_loader.cc", "max_forks_repo_name": "daeyun/Scry", "max_forks_repo_head_hexsha": "f4952ce39c6960266b022600445583f0a12858c3", "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.5584415584, "max_line_length": 80, "alphanum_fraction": 0.6263181019, "num_tokens": 1333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5070073644454619}}
{"text": "/*! \\file polygon_overlap_area.hpp\n  \\brief Calculates the overlap between two polygons\n  \\author Elad Steinberg\n */\n\n#include \"PolyIntersect.hpp\"\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n\n//! \\brief Alias for random number generator\ntypedef boost::mt19937_64 base_generator_type;\n\nusing std::vector;\n\n//! \\brief Overlap of two polygons\nclass PolygonOverlap\n{\nprivate:\n  base_generator_type gen;\npublic:\n//! \\brief Class constructor\n  PolygonOverlap(void);\n\n  /*!\n  \\brief Calcualted the area of a convex polygon\n  \\param polygon The vertices of the polygon, should be ordered as a convex hull\n  \\return The area\n  */\n  double PolyArea(vector<Vector2D> const& polygon);\n  /*!\n  \\brief Calculates the area overlaped between two convex polygons\n  \\param ch1 The convex hull of the first polygon\n  \\param ch2 The convex hull of the second polygon\n  \\param R0 A fraction of the effective radius of the first polygon \n  \\param R1 A fraction of the effective radius of the second polygon\n  \\return The overlaped area\n  */\n  double polygon_overlap_area(vector<Vector2D> const& ch1,\n\t\t\t      vector<Vector2D> const& ch2,double R0,double R1);\n};\n", "meta": {"hexsha": "6094230d6c08f9fa9e45d1b7accfdf83353d6522", "size": 1195, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/polygon_overlap_area.hpp", "max_stars_repo_name": "GalaxyHunters/Vivid", "max_stars_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "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": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/polygon_overlap_area.hpp", "max_issues_repo_name": "GalaxyHunters/Vivid", "max_issues_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T18:13:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T14:54:04.000Z", "max_forks_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/polygon_overlap_area.hpp", "max_forks_repo_name": "GalaxyHunters/Vivid", "max_forks_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-29T09:39:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-25T19:17:49.000Z", "avg_line_length": 29.1463414634, "max_line_length": 80, "alphanum_fraction": 0.7556485356, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5070073644454618}}
{"text": "#include \"gtest/gtest.h\"\n\n#include \"ale.h\"\n\n#include <stdexcept>\n#include <cmath>\n\n#include <gsl/gsl_interp.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing namespace std;\n\nTEST(PositionInterpTest, LinearInterp) {\n  vector<double> times = { -3, -2, -1,  0,  1,  2};\n  vector<vector<double>> data = {{ -3, -2, -1,  0,  1,  2},\n                                 {  9,  4,  1,  0,  1,  4},\n                                 {-27, -8, -1,  0,  1,  8}};\n\n  vector<double> coordinate = ale::getPosition(data, times, -1.5, ale::linear);\n\n  ASSERT_EQ(3, coordinate.size());\n  EXPECT_DOUBLE_EQ(-1.5, coordinate[0]);\n  EXPECT_DOUBLE_EQ(2.5,  coordinate[1]);\n  EXPECT_DOUBLE_EQ(-4.5, coordinate[2]);\n}\n\n\nTEST(PositionInterpTest, FourCoordinates) {\n  vector<double> times = { -3, -2, -1,  0,  1,  2};\n  vector<vector<double>> data = {{ -3, -2, -1,  0,  1,  2},\n                                 {  9,  4,  1,  0,  1,  4},\n                                 {-27, -8, -1,  0,  1,  8},\n                                 { 25,  0, -5, 25,  3,  6}};\n\n  EXPECT_THROW(ale::getPosition(data, times, 0.0, ale::linear),\n               invalid_argument);\n}\n\n\nTEST(LinearInterpTest, ExampleInterpolation) {\n  vector<double> times = {0,  1,  2, 3};\n  vector<double> data = {0, 2, 1, 0};\n\n  EXPECT_DOUBLE_EQ(0.0, ale::interpolate(data, times, 0.0, ale::linear, 0));\n  EXPECT_DOUBLE_EQ(1.0, ale::interpolate(data, times, 0.5, ale::linear, 0));\n  EXPECT_DOUBLE_EQ(2.0, ale::interpolate(data, times, 1.0, ale::linear, 0));\n  EXPECT_DOUBLE_EQ(1.5, ale::interpolate(data, times, 1.5, ale::linear, 0));\n  EXPECT_DOUBLE_EQ(1.0, ale::interpolate(data, times, 2.0, ale::linear, 0));\n  EXPECT_DOUBLE_EQ(0.5, ale::interpolate(data, times, 2.5, ale::linear, 0));\n  EXPECT_DOUBLE_EQ(0.0, ale::interpolate(data, times, 3.0, ale::linear, 0));\n}\n\n\nTEST(LinearInterpTest, NoPoints) {\n  vector<double> times = {};\n  vector<double> data = {};\n\n  EXPECT_THROW(ale::interpolate(data, times, 0.0, ale::linear, 0),\n               invalid_argument);\n}\n\n\nTEST(LinearInterpTest, DifferentCounts) {\n  vector<double> times = { -3, -2, -1,  0,  2};\n  vector<double> data = { -3, -2, 1,  2};\n\n  EXPECT_THROW(ale::interpolate(data, times, 0.0, ale::linear, 0),\n               invalid_argument);\n}\n\n\nTEST(LinearInterpTest, Extrapolate) {\n  vector<double> times = {0,  1,  2, 3};\n  vector<double> data = {0, 2, 1, 0};\n\n  EXPECT_THROW(ale::interpolate(data, times, -1.0, ale::linear, 0),\n               invalid_argument);\n  EXPECT_THROW(ale::interpolate(data, times, 4.0, ale::linear, 0),\n               invalid_argument);\n}\n\n\nTEST(SplineInterpTest, ExampleInterpolation) {\n  // From http://www.maths.nuigalway.ie/~niall/teaching/Archive/1617/MA378/2-2-CubicSplines.pdf\n  vector<double> times = {0,  1,  2, 3};\n  vector<double> data = {0, 2, 1, 0};\n  // Spline functions is:\n  //        2.8x - 0.8x^3,                 x in [0, 1]\n  // S(x) = x^3 - 5.4x^2 + 8.2x - 1.8,     x in [1, 2]\n  //        -0.2x^3 + 1.8x^2 - 6.2x + 7.8, x in [2, 3]\n\n  // The spline interpolation is only ~1e-10 so we have to define a tolerance\n  double tolerance = 1e-10;\n  EXPECT_NEAR(0.0, ale::interpolate(data, times, 0.0, ale::spline, 0), tolerance);\n  EXPECT_NEAR(2.8 * 0.5 - 0.8 * 0.125,\n              ale::interpolate(data, times, 0.5, ale::spline, 0), tolerance);\n  EXPECT_NEAR(2.0, ale::interpolate(data, times, 1.0, ale::spline, 0), tolerance);\n  EXPECT_NEAR(3.375 - 5.4 * 2.25 + 8.2 * 1.5 - 1.8,\n              ale::interpolate(data, times, 1.5, ale::spline, 0), tolerance);\n  EXPECT_NEAR(1.0, ale::interpolate(data, times, 2.0, ale::spline, 0), tolerance);\n  EXPECT_NEAR(-0.2 * 15.625 + 1.8 * 6.25 - 6.2 * 2.5 + 7.8,\n              ale::interpolate(data, times, 2.5, ale::spline, 0), tolerance);\n  EXPECT_NEAR(0.0, ale::interpolate(data, times, 3.0, ale::spline, 0), tolerance);\n}\n\n\nTEST(SplineInterpTest, NoPoints) {\n  vector<double> times = {};\n  vector<double> data = {};\n\n  EXPECT_THROW(ale::interpolate(data, times, 0.0, ale::spline, 0),\n               invalid_argument);\n}\n\n\nTEST(SplineInterpTest, DifferentCounts) {\n  vector<double> times = { -3, -2, -1,  0,  2};\n  vector<double> data = { -3, -2, 1,  2};\n\n  EXPECT_THROW(ale::interpolate(data, times, 0.0, ale::spline, 0),\n               invalid_argument);\n}\n\n\nTEST(SplineInterpTest, Extrapolate) {\n  vector<double> times = {0,  1,  2, 3};\n  vector<double> data = {0, 2, 1, 0};\n\n  EXPECT_THROW(ale::interpolate(data, times, -1.0, ale::spline, 0),\n               invalid_argument);\n  EXPECT_THROW(ale::interpolate(data, times, 4.0, ale::spline, 0),\n               invalid_argument);\n}\n\n\nTEST(PolynomialTest, Evaluate) {\n  vector<double> coeffs = {1.0, 2.0, 3.0}; // 1 + 2x + 3x^2\n  EXPECT_EQ(2.0, ale::evaluatePolynomial(coeffs, -1, 0));\n}\n\n\nTEST(PolynomialTest, Derivatives) {\n  vector<double> coeffs = {1.0, 2.0, 3.0}; // 1 + 2x + 3x^2\n  EXPECT_EQ(-4.0, ale::evaluatePolynomial(coeffs, -1, 1));\n  EXPECT_EQ(6.0, ale::evaluatePolynomial(coeffs, -1, 2));\n}\n\n\nTEST(PolynomialTest, EmptyCoeffs) {\n  vector<double> coeffs = {};\n  EXPECT_THROW(ale::evaluatePolynomial(coeffs, -1, 1), invalid_argument);\n}\n\nTEST(PolynomialTest, BadDerivative) {\n  vector<double> coeffs = {1.0, 2.0, 3.0};\n  EXPECT_THROW(ale::evaluatePolynomial(coeffs, -1, -1), invalid_argument);\n}\n\n\nTEST(PoisitionCoeffTest, SecondOrderPolynomial) {\n  double time = 2.0;\n  vector<vector<double>> coeffs = {{1.0, 2.0, 3.0},\n                                   {1.0, 3.0, 2.0},\n                                   {3.0, 2.0, 1.0}};\n\n  vector<double> coordinate = ale::getPosition(coeffs, time);\n\n  ASSERT_EQ(3, coordinate.size());\n  EXPECT_DOUBLE_EQ(17.0, coordinate[0]);\n  EXPECT_DOUBLE_EQ(15.0, coordinate[1]);\n  EXPECT_DOUBLE_EQ(11.0, coordinate[2]);\n}\n\n\nTEST(PoisitionCoeffTest, DifferentPolynomialDegrees) {\n  double time = 2.0;\n  vector<vector<double>> coeffs = {{1.0},\n                                   {1.0, 2.0},\n                                   {1.0, 2.0, 3.0}};\n\n  vector<double> coordinate = ale::getPosition(coeffs, time);\n\n  ASSERT_EQ(3, coordinate.size());\n  EXPECT_DOUBLE_EQ(1.0,  coordinate[0]);\n  EXPECT_DOUBLE_EQ(5.0,  coordinate[1]);\n  EXPECT_DOUBLE_EQ(17.0, coordinate[2]);\n}\n\n\nTEST(PoisitionCoeffTest, NegativeInputs) {\n  double time = -2.0;\n  vector<vector<double>> coeffs = {{-1.0, -2.0, -3.0},\n                                   {1.0, -2.0, 3.0},\n                                   {-1.0, 2.0, -3.0}};\n\n  vector<double> coordinate = ale::getPosition(coeffs, time);\n\n  ASSERT_EQ(3, coordinate.size());\n  EXPECT_DOUBLE_EQ(-9.0,  coordinate[0]);\n  EXPECT_DOUBLE_EQ(17.0,  coordinate[1]);\n  EXPECT_DOUBLE_EQ(-17.0, coordinate[2]);\n}\n\n\nTEST(PoisitionCoeffTest, InvalidInput) {\n  double valid_time = 0.0;\n  vector<vector<double>> invalid_coeffs_sizes = {{3.0, 2.0, 1.0},\n                                                 {1.0, 2.0, 3.0}};\n\n  EXPECT_THROW(ale::getPosition(invalid_coeffs_sizes, valid_time), invalid_argument);\n}\n\n\nTEST(VelocityCoeffTest, SecondOrderPolynomial) {\n  double time = 2.0;\n  vector<vector<double>> coeffs = {{1.0, 2.0, 3.0},\n                                   {1.0, 3.0, 2.0},\n                                   {3.0, 2.0, 1.0}};\n\n  vector<double> coordinate = ale::getVelocity(coeffs, time);\n\n  ASSERT_EQ(3, coordinate.size());\n  EXPECT_DOUBLE_EQ(14.0, coordinate[0]);\n  EXPECT_DOUBLE_EQ(11.0, coordinate[1]);\n  EXPECT_DOUBLE_EQ(6.0, coordinate[2]);\n}\n\n\nTEST(VelocityCoeffTest, InvalidInput) {\n  double valid_time = 0.0;\n  vector<vector<double>> invalid_coeffs_sizes = {{3.0, 2.0, 1.0},\n                                                 {1.0, 2.0, 3.0}};\n\n  EXPECT_THROW(ale::getVelocity(invalid_coeffs_sizes, valid_time), invalid_argument);\n}\n\nTEST(RotationCoeffTest, ZeroOrderPolynomial) {\n  double time = 1.0;\n  vector<vector<double>> coeffs = {{90},\n                                                            {0},\n                                                            {0}};\n\n  vector<double> coordinate = ale::getRotation(coeffs, time);\n\n  ASSERT_EQ(4, coordinate.size());\n  EXPECT_DOUBLE_EQ(1 / sqrt(2), coordinate[0]);\n  EXPECT_DOUBLE_EQ(0, coordinate[1]);\n  EXPECT_DOUBLE_EQ(0, coordinate[2]);\n  EXPECT_DOUBLE_EQ(1 / sqrt(2), coordinate[3]);\n}\n\nTEST(RotationCoeffTest, InvalidInput) {\n  double time = 1.0;\n  vector<vector<double>> coeffs = {{90},\n                                                            {0}};\n\n  EXPECT_THROW(ale::getRotation(coeffs, time), invalid_argument);\n}\n\nTEST(AngularVelocityCoeffTest, DefaultAngularExample) {\n  vector<vector<double>> coeffs = {{0, 90}, {0, 90}, {0, 90}};\n  double time = 1.0;\n\n  vector<double> av = ale::getAngularVelocity(coeffs, time);\n\n  ASSERT_EQ(3, av.size());\n  EXPECT_DOUBLE_EQ(90, av[0]);\n  EXPECT_DOUBLE_EQ(90, av[1]);\n  EXPECT_DOUBLE_EQ(90, av[2]);\n}\n\nTEST(AngularVelocityCoeffTest, InvalidInput) {\n  vector<vector<double>> coeffs = {{0, 90}, {0, 90}};\n  double time = 2.0;\n\n  EXPECT_THROW(ale::getAngularVelocity(coeffs, time), invalid_argument);\n}\n\n\nTEST(RotationInterpTest, ExampleGetRotation) {\n  // simple test, only checks if API hit correctly and output is normalized\n  vector<double> times = {0,  1,  2, 3};\n  vector<vector<double>> rots({{1,1,1,1}, {0,0,0,0}, {1,1,1,1}, {0,0,0,0}});\n  vector<double> r = ale::getRotation(rots, times, 2, ale::linear);\n  Eigen::Quaterniond quat(r[0], r[1], r[2], r[3]);\n\n  EXPECT_DOUBLE_EQ(1, quat.norm());\n}\n\n\nTEST(RotationInterpTest, GetRotationDifferentCounts) {\n  // incorrect params\n  vector<double> times = {0, 1, 2};\n  vector<vector<double>> rots({{1,1,1,1}, {0,0,0,0}, {1,1,1,1}, {0,0,0,0}});\n  EXPECT_THROW(ale::getRotation(rots, times, 2, ale::linear), invalid_argument);\n}\n\nTEST(PyInterfaceTest, LoadInvalidLabel) {\n  std::string label = \"Not a Real Label\";\n  EXPECT_THROW(ale::load(label), invalid_argument);\n}\n\nTEST(PyInterfaceTest, LoadValidLabel) {\n  std::string label = \"../pytests/data/EN1072174528M/EN1072174528M_spiceinit.lbl\";\n  ale::load(label, \"\", \"isis\");\n}\n\nTEST(AngularVelocityInterpTest, ExampleGetRotation) {\n  vector<double> times = {0,  1};\n  vector<vector<double>> rots({{0,0}, {1,0}, {0,1}, {0,0}});\n  vector<double> av = ale::getAngularVelocity(rots, times, 0.5, ale::linear);\n\n  EXPECT_DOUBLE_EQ(0, av[0]);\n  EXPECT_DOUBLE_EQ(0, av[1]);\n  EXPECT_DOUBLE_EQ(2 * sqrt(2), av[2]);\n}\n", "meta": {"hexsha": "9171974f8dfec98551467b4c7a56ed367ceb8075", "size": 10218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/ctests/AleTest.cpp", "max_stars_repo_name": "kaitlyndlee/ale", "max_stars_repo_head_hexsha": "44db2f5910a2f937a1946c6ff485b0d4b7b26a18", "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": "tests/ctests/AleTest.cpp", "max_issues_repo_name": "kaitlyndlee/ale", "max_issues_repo_head_hexsha": "44db2f5910a2f937a1946c6ff485b0d4b7b26a18", "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/ctests/AleTest.cpp", "max_forks_repo_name": "kaitlyndlee/ale", "max_forks_repo_head_hexsha": "44db2f5910a2f937a1946c6ff485b0d4b7b26a18", "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.0313479624, "max_line_length": 95, "alphanum_fraction": 0.5981601096, "num_tokens": 3391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.507007359123694}}
{"text": "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// @project        Open Space Toolkit \u25b8 Mathematics\n/// @file           OpenSpaceToolkit/Mathematics/Objects/Vector.hpp\n/// @author         Lucas Br\u00e9mond <lucas@loftorbital.com>\n/// @license        Apache License 2.0\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef __OpenSpaceToolkit_Mathematics_Objects_Vector__\n#define __OpenSpaceToolkit_Mathematics_Objects_Vector__\n\n#include <OpenSpaceToolkit/Core/Types/String.hpp>\n\n#define EIGEN_MATRIXBASE_PLUGIN \"OpenSpaceToolkit/Mathematics/Objects/Eigen.hpp\"\n\n// Disable Eigen warnings\n\n#pragma GCC diagnostic push // Save diagnostic state\n\n#pragma GCC diagnostic ignored \"-Wshadow\"\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#pragma GCC diagnostic ignored \"-Wint-in-bool-context\"\n#pragma GCC diagnostic ignored \"-Wmaybe-uninitialized\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#pragma GCC diagnostic pop // Turn the warnings back on\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nnamespace ostk\n{\nnamespace math\n{\nnamespace obj\n{\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nusing Vector2i = Eigen::Vector2i ;\nusing Vector3i = Eigen::Vector3i ;\nusing Vector4i = Eigen::Vector4i ;\n\nusing VectorXi = Eigen::VectorXi ;\n\nusing Vector2d = Eigen::Vector2d ;\nusing Vector3d = Eigen::Vector3d ;\nusing Vector4d = Eigen::Vector4d ;\n\nusing VectorXd = Eigen::VectorXd ;\n\nusing RowVectorXd = Eigen::RowVectorXd ;\n\nusing Matrix2i = Eigen::Matrix2i ;\nusing Matrix3i = Eigen::Matrix3i ;\nusing Matrix4i = Eigen::Matrix4i ;\n\nusing MatrixXi = Eigen::MatrixXi ;\n\nusing Matrix2d = Eigen::Matrix2d ;\nusing Matrix3d = Eigen::Matrix3d ;\nusing Matrix4d = Eigen::Matrix4d ;\n\nusing MatrixXd = Eigen::MatrixXd ;\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n}\n}\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#endif\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "3a16f6e9815520f93c0ac2b156284aabed2ececc", "size": 2666, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/OpenSpaceToolkit/Mathematics/Objects/Vector.hpp", "max_stars_repo_name": "open-space-collective/library-mathematics", "max_stars_repo_head_hexsha": "fdb4769a56a8fe35ffefb01a79c03cfca1f91958", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-08-20T06:47:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-15T03:36:52.000Z", "max_issues_repo_path": "include/OpenSpaceToolkit/Mathematics/Objects/Vector.hpp", "max_issues_repo_name": "open-space-collective/open-space-toolkit-mathematics", "max_issues_repo_head_hexsha": "4b97f97f4aaa87bff848381a3519c6f764461378", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-01-05T20:18:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-14T09:36:44.000Z", "max_forks_repo_path": "include/OpenSpaceToolkit/Mathematics/Objects/Vector.hpp", "max_forks_repo_name": "open-space-collective/open-space-toolkit-mathematics", "max_forks_repo_head_hexsha": "4b97f97f4aaa87bff848381a3519c6f764461378", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T18:18:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T17:42:24.000Z", "avg_line_length": 33.746835443, "max_line_length": 160, "alphanum_fraction": 0.4324831208, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5070073525557554}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Sebastian Schlenkrich\n\n*/\n\n\n\n#ifndef quantlib_templatetdstochvolmodel_hpp\n#define quantlib_templatetdstochvolmodel_hpp\n\n#include <complex>\n#include <ql/shared_ptr.hpp>\n#include <boost/function.hpp>\n#include <ql/errors.hpp>\n#include <ql/experimental/templatemodels/auxilliaries/auxilliariesT.hpp>\n#include <ql/experimental/templatemodels/auxilliaries/gausslobattoT.hpp>\n#include <ql/experimental/templatemodels/auxilliaries/complexT.hpp>\n#include <ql/experimental/templatemodels/auxilliaries/solver1dT.hpp>\n#include <ql/experimental/templatemodels/stochasticprocessT.hpp>\n#include <ql/experimental/templatemodels/stochvol/hestonmodelT.hpp>\n\n\n\n#define _MIN_( a, b ) ( (a) < (b) ? (a) : (b) )\n#define _MAX_( a, b ) ( (a) > (b) ? (a) : (b) )\n\nnamespace QuantLib {\n\n    // general stochastic volatility model interface with time-dependent parameters and parameter averaging pricing formula\n    //\n    //    dS(t) = lambda(t) [ b(t) S(t) + (1-b(t)) L ] sqrt[z(t)] dW(t)\n    //    dz(t) = theta [ m - z(t) ] dt + eta(t) sqrt[z(t)] dZ(t)\n    //    dW(t) dZ(t) = rho dt\n    //\n    template <class DateType, class PassiveType, class ActiveType>\n    class TimeDependentStochVolModelT : public StochasticProcessT<DateType,PassiveType,ActiveType> {\n    public:\n        // abstract inspectors\n        virtual ActiveType  lambda( const DateType t) = 0;\n        virtual ActiveType  b(      const DateType t) = 0;\n        virtual ActiveType  L()                       = 0;\n        virtual ActiveType  theta()                   = 0;\n        virtual ActiveType  m()                       = 0;\n        virtual ActiveType  eta(    const DateType t) = 0;\n        virtual ActiveType  z0()                      = 0;\n        virtual ActiveType  rho()                     = 0;\n        virtual ActiveType  S0()                      = 0;\n\n        // from base class\n        using typename StochasticProcessT<DateType, PassiveType, ActiveType>::VecD;\n        using typename StochasticProcessT<DateType, PassiveType, ActiveType>::VecP;\n        using typename StochasticProcessT<DateType, PassiveType, ActiveType>::VecA;\n        using typename StochasticProcessT<DateType, PassiveType, ActiveType>::MatA;\n        using typename StochasticProcessT<DateType, PassiveType, ActiveType>::VolEvolv;\n        using StochasticProcessT<DateType, PassiveType, ActiveType>::volEvolv;\n\n\n        // helper functions for vol averaging, Piterbarg, 10.2.4\n        inline static ActiveType A_CIR ( ActiveType c1, ActiveType c2, ActiveType z0, ActiveType theta, ActiveType eta, DateType dt ) {\n            ActiveType gamma = sqrt((theta*theta + 2.0 * eta*eta * c2));\n            ActiveType t1 = theta*z0/eta/eta * (theta + gamma)*dt;\n            ActiveType t2 = 1.0 + (theta + gamma + c1 * eta*eta) * (exp(gamma * dt) - 1.0) / 2.0 / gamma;\n            QL_REQUIRE(t2>0,\"A_CIR: require positive log()-argument\");\n            return t1 - 2.0*theta*z0/eta/eta*log(t2);\n        }\n\n        inline static ActiveType B_CIR ( ActiveType c1, ActiveType c2, ActiveType z0, ActiveType theta, ActiveType eta, DateType dt ) {\n            ActiveType gamma = sqrt((theta*theta + 2.0 * eta*eta * c2));\n            ActiveType emGdt = exp(-gamma * dt);\n            ActiveType numer = (2.0*c2 - theta*c1)*(1.0 - emGdt) + gamma*c1*(1.0 + emGdt);\n            ActiveType denum = (theta + gamma + c1*eta*eta) * (1.0 - emGdt) + 2.0*gamma*emGdt;\n            return numer / denum;\n        }\t\t\n\n        // abstract averaging formula definitions\n        inline virtual ActiveType  averageLambda( const DateType T) = 0;\n        inline virtual ActiveType  averageB     ( const DateType T) = 0;\n        inline virtual ActiveType  averageEta   ( const DateType T) = 0;\n\n        // undiscounted expectation of vanilla payoff\n        inline ActiveType vanillaOption(const PassiveType forwardPrice,\n                                        const PassiveType strikePrice,\n                                        const DateType    term,\n                                        const int         callOrPut,\n                                        const PassiveType accuracy,\n                                        const size_t      maxEvaluations) {\n                StochVolModelT<DateType,PassiveType,ActiveType> model(averageLambda(term), averageB(term),L(),theta(),m(),averageEta(term),z0(),rho());\n                return model.vanillaOption( forwardPrice, strikePrice, term, callOrPut, accuracy, maxEvaluations );\n        }\n\n        // conditional moments of vol process used for z-integration, Piterbarg, 8.3.3.\n        // E[ z(T) | z(t) ]\n        inline virtual ActiveType expectationZ( DateType t, ActiveType zt, DateType dT ) {\n            return z0() + (zt - z0())*exp(-theta()*dT);\n        }\n        // Var[ z(T) | z(t) ]\n        inline virtual ActiveType varianceZ( DateType t, ActiveType zt, DateType dT ) {\n            ActiveType expmThDT = exp(-theta()*dT);\n            ActiveType onemETDT = 1 - expmThDT;\n            ActiveType eta2oThe = eta(t+dT/2.0)*eta(t+dT/2.0)/theta();  // approx eta(t)=eta for s \\in [t, t+dT]\n            return zt*eta2oThe*expmThDT*onemETDT + z0()*eta2oThe/2.0*onemETDT*onemETDT; \n        }\n\n\n        // stochastic process interface\n        // dimension of X\n        inline virtual size_t size() { return 2; }\n        // stochastic factors of x and z (maybe distinguish if trivially eta=0)\n        inline virtual size_t factors() { return 2; }\n        // initial values for simulation\n        inline virtual VecP initialValues() {\n            VecP X(2);\n            X[0] = S0();\n            X[1] = z0();\n            return X;\n        }\n        // a[t,X(t)]\n        inline virtual VecA drift( const DateType t, const VecA& X) {\n            VecA a(2);\n            // S-variable drift-less\n            a[0] = 0.0;\n            // z-variable theta [ m - z(t)^+ ]  (full truncation)\n            a[1] = theta()*(m() - ((X[1]>0)?(X[1]):(0.0)));\n            return a;\n        }\n        // b[t,X(t)]\n        inline virtual MatA diffusion( const DateType t, const VecA& X) {\n            MatA B(2);\n            B[0].resize(2);\n            B[1].resize(2);\n            ActiveType sqrtz = ( (X[1]>0) ? (sqrt(X[1])) : (0.0) );   // full truncation\n            // S-variable lambda(t) [ b(t) S(t) + (1-b(t)) L ] sqrt[z(t)] dW(t)\n            B[0][0] = lambda(t) * (b(t) * X[0] + (1.0-b(t)) * L()) * sqrtz;\n            B[0][1] = 0.0;\n            // z-variable\n            B[1][0] = rho()*eta(t)*sqrtz;\n            B[1][1] = sqrt(1-rho()*rho())*eta(t)*sqrtz;\n            // finished\n            return B;\n        }\n\n        // integrate X1 = X0 + drift()*dt + diffusion()*dW*sqrt(dt)\n        inline virtual void evolve( const DateType t0, const VecA& X0, const DateType dt, const VecD& dW, VecA& X1 ) {\n            // ensure X1 has size of X0\n            VecA a = drift(t0, X0);\n            MatA b = diffusion(t0, X0);\n            // S-variable\n            X1[0] = X0[0] + a[0]*dt + b[0][0]*dW[0]*sqrt(dt);\n            // z-variable\n            if (volEvolv()==VolEvolv::FullTruncation) {\n                X1[1] = X0[1] + a[1]*dt + (b[1][0]*dW[0]+b[1][1]*dW[1])*sqrt(dt);\n                return;\n            }\n            if (volEvolv()==VolEvolv::LogNormalApproximation) {\n                ActiveType e = expectationZ(t0, X0[1], dt);\n                ActiveType v = varianceZ(t0, X0[1], dt);\n                ActiveType dZ = rho()*dW[0] + sqrt(1-rho()*rho())*dW[1];\n                ActiveType si = sqrt(log(1.0 + v/e/e));\n                ActiveType mu = log(e) - si*si/2.0;\n                X1[1] = exp(mu + si*dZ);\n            }\n            return;\n        }\n\n\n\n        // embeded classes\n\n        class PieceWiseConstant  {\n        protected:\n            // check for dimensions\n            bool isConsistent_;\n            // time grid\n            std::vector<DateType>     times_;\n            // time-dependent model parameters\n            std::vector<ActiveType>   lambda_;\n            std::vector<ActiveType>   b_;\n            std::vector<ActiveType>   eta_;\n            // time-homogeneous model parameters\n            ActiveType                L_;\n            ActiveType                theta_;\n            ActiveType                m_;\n            ActiveType                z0_;\n            ActiveType                rho_;\n            ActiveType                S0_;\n            // helper\n            inline size_t idx( const DateType t ) { return TemplateAuxilliaries::idx(times_,t); }\n        public:\n            // constructor\n            PieceWiseConstant( const std::vector<DateType>&    times,\n                               const std::vector<ActiveType>&  lambda,\n                               const std::vector<ActiveType>&  b,\n                               const std::vector<ActiveType>&  eta,\n                               const ActiveType                L,\n                               const ActiveType                theta,\n                               const ActiveType                m,\n                               const ActiveType                z0,\n                               const ActiveType                rho,\n                               const ActiveType                S0 )\n                : times_(times), lambda_(lambda), b_(b), eta_(eta), L_(L), theta_(theta), m_(m), z0_(z0), rho_(rho), S0_(S0) {\n                isConsistent_ = true;\n                QL_REQUIRE(times_.size()>0,\"TemplateTimeDependentStochVolModel::PieceWiseConstant: non-empty times required\");\n                for (size_t k=0; k<times_.size()-1; ++k) QL_REQUIRE(times_[k]<times_[k+1],\"TemplateTimeDependentStochVolModel::PieceWiseConstant: ascending time-grid required\");\n                QL_REQUIRE(lambda_.size()==times_.size(),\"TemplateTimeDependentStochVolModel::PieceWiseConstant: lambda dimension mismatch\");\n                QL_REQUIRE(b_.size()     ==times_.size(),\"TemplateTimeDependentStochVolModel::PieceWiseConstant: b dimension mismatch\");\n                QL_REQUIRE(eta_.size()   ==times_.size(),\"TemplateTimeDependentStochVolModel::PieceWiseConstant: eta dimension mismatch\");\n            }\n            // inspectors\n            virtual ActiveType  lambda( const DateType t)  { return lambda_[idx(t)]; }\n            virtual ActiveType  b(      const DateType t)  { return b_[idx(t)];      }\n            virtual ActiveType  eta(    const DateType t)  { return eta_[idx(t)];    }\n            virtual ActiveType  L()                        { return L_;              }\n            virtual ActiveType  theta()                    { return theta_;          }\n            virtual ActiveType  m()                        { return m_;              }\n            virtual ActiveType  z0()                       { return z0_;             }\n            virtual ActiveType  rho()                      { return rho_;            }\n            virtual ActiveType  S0()                       { return S0_;            }\n\n        };\n\n        // averaging assuming piecewise constant parameters on ( T_k-1, T_k ]\n        class MidPointIntegration {\n        protected:\n            // reference to model\n            TimeDependentStochVolModelT* model_;\n            // time grid for integration\n            std::vector<DateType>               times_;\n            inline std::vector<DateType> getTimes( const DateType T ) {\n                std::vector<DateType> times;\n                times.push_back(0.0);\n                for (size_t k=0; k<times_.size(); ++k) {\n                    if (times_[k]>0.0 && times_[k]<T) times.push_back(times_[k]);\n                    if (times_[k]>=T) break;\n                }\n                times.push_back(T);\n                return times;\n            }\n\n            class AverageLambdaObjective {\n            protected:\n                ActiveType z0_;\n                ActiveType theta_;\n                ActiveType eta_;\n                DateType   dt_;\n                ActiveType target_;\n            public:\n                AverageLambdaObjective ( const ActiveType z0,\n                                         const ActiveType theta,\n                                         const ActiveType eta,\n                                         const DateType   dt,\n                                         const ActiveType target )\n                                         : z0_(z0), theta_(theta), eta_(eta), dt_(dt), target_(target) {}\n                ActiveType operator() ( const ActiveType avLambda2c ) {\n                    ActiveType A = A_CIR(0, -avLambda2c, z0_, theta_, eta_, dt_);\n                    ActiveType B = B_CIR(0, -avLambda2c, z0_, theta_, eta_, dt_);\n                    ActiveType res = A - B*z0_ - target_;\n                    return res;\n                }\n            };\n\n            // Prop. 9.1.2\n            class RiccatiODE {\n                TimeDependentStochVolModelT* model_;\n                ActiveType v_;\n                ActiveType u_;\n                ActiveType averageB_;\n            public:\n                RiccatiODE (TimeDependentStochVolModelT* model, ActiveType v, ActiveType u, ActiveType averageB)\n                    : model_(model), v_(v), u_(u), averageB_(averageB) {}\n                void operator() (const DateType t, const std::vector<ActiveType>& y, std::vector<ActiveType>& fy) {\n                    fy[0] = - model_->theta() * model_->z0() * y[1];\n                    fy[1] = (model_->theta() - model_->rho()*model_->eta(t)*averageB_*u_*model_->lambda(t))*y[1]\n                            - model_->eta(t)*model_->eta(t)/2.0*y[1]*y[1] - v_*model_->lambda(t)*model_->lambda(t);\n                }\n            };\n\n        public:\n            // constructor\n            MidPointIntegration ( TimeDependentStochVolModelT* model,\n                                  std::vector<DateType>        times )\n                                  : model_(model), times_(times) { }\n\n            virtual ~MidPointIntegration() = default;\n\n            // averaging formula implementations\n            virtual ActiveType  averageEta   ( const DateType T) {\n                std::vector<DateType> times(getTimes(T));\n                std::vector<ActiveType> f(times.size());\n                std::vector<ActiveType> w(times.size()-1);\n                f[f.size()-1] = 0.0;\n                for (size_t k=f.size()-1; k>0; --k) {\n                    ActiveType lambda = model_->lambda((times[k-1]+times[k])/2.0);\n                    ActiveType tmp    = exp(-model_->theta()*(times[k]-times[k-1]));\n                    f[k-1] = lambda*lambda/model_->theta()*(1.0 - tmp) + tmp*f[k];\n                }\n                ActiveType sum = 0.0;\n                for (size_t k=0; k<w.size(); ++k) {\n                    ActiveType lambda  = model_->lambda((times[k]+times[k+1])/2.0);\n                    ActiveType lambda2 = lambda*lambda;\n                    ActiveType theta   = model_->theta();\n                    ActiveType theta2  = theta*theta;\n                    w[k] = (f[k+1]*f[k+1] - f[k]*f[k])/2.0/theta +\n                           (f[k+1] - f[k])*lambda2/theta2 +\n                           (times[k+1]-times[k])*lambda2*lambda2/theta2;\n                    w[k] *= 0.5;\n                    sum  += w[k];\n                }\n                ActiveType eta2=0.0;\n                for (size_t k=0; k<w.size(); ++k) {\n                    ActiveType eta = model_->eta((times[k]+times[k+1])/2.0);\n                    eta2 += w[k] * eta * eta;\n                }\n                eta2 = eta2 / sum;\n                return sqrt(eta2);\n            }\n\n            virtual ActiveType  averageB( const DateType T) {\n                std::vector<DateType> times(getTimes(T));\n                std::vector<ActiveType> w(times.size()-1);\n                ActiveType theta = model_->theta();\n                ActiveType z0 = model_->z0();\n                ActiveType sumLambda2dT = 0.0;\n                ActiveType S1=0.0, S2=0.0, S3=0.0;\n                ActiveType sum = 0.0;\n                for (size_t k=0; k<w.size(); ++k) {\n                    // v1\n                    ActiveType lambda    = model_->lambda((times[k]+times[k+1])/2.0);\n                    ActiveType lambda2   = lambda*lambda;\n                    ActiveType eta       = model_->eta((times[k]+times[k+1])/2.0);\n                    ActiveType lambda2dT = lambda2*(times[k+1]-times[k]);\n                    ActiveType v1        = z0*z0*(times[k+1]-times[k])*(lambda2dT/2.0 + sumLambda2dT);\n                    sumLambda2dT        += lambda2dT;\n                    // v3, v4, v5\n                    ActiveType expmThdT  = exp(-theta*(times[k+1]-times[k]));\n                    ActiveType v3        = z0/theta*(S2+S3)*(1.0-expmThdT);\n                    ActiveType v4        = (times[k+1]-times[k]) - (1.0-expmThdT)/theta -\n                                           (1.0-expmThdT)*(1.0-expmThdT)/2.0/theta;\n                    ActiveType laEtaTh   = lambda*eta/theta;\n                    v4                  *= z0*laEtaTh*laEtaTh/2.0;\n                    ActiveType theta2    = theta*theta;\n                    ActiveType v5        = z0*lambda2/theta2/2.0*S1*(1.0-expmThdT)*(1.0-expmThdT);\n                    // updating S1, S2, S3\n                    S3                   = expmThdT * ( S3 + S1*lambda2/theta*(1.0-expmThdT) );\n                    S2                   = expmThdT*S2 + laEtaTh*laEtaTh/2.0*(1.0-expmThdT)*(1.0-expmThdT);\n                    S1                   = expmThdT*expmThdT*S1 + eta*eta/theta/2.0*(1.0 - expmThdT*expmThdT);\n                    // gathering things together...\n                    w[k]                 = lambda2 * ( v1 + v3 + v4 + v5 );\n                    sum                 += w[k];\n                }\n                ActiveType b=0;\n                for (size_t k=0; k<w.size(); ++k) {\n                    b += w[k] * model_->b((times[k]+times[k+1])/2.0);\n                }\n                b = b / sum;\n                return b;\n            }\n            \n            virtual ActiveType  averageLambda     ( const DateType T) {\n                ActiveType b   = averageB(T);\n                ActiveType eta = averageEta(T);  // maybe better use time-dep eta\n                std::vector<DateType> times(getTimes(T));\n                // c = h''(zeta) / h'(zeta)\n                ActiveType zeta = 0.0;\n                for (size_t k=0; k<times.size()-1; ++k) {\n                    ActiveType lambda    = model_->lambda((times[k]+times[k+1])/2.0);\n                    zeta += lambda*lambda*(times[k+1]-times[k]);\n                }\n                ActiveType avLambda2 = zeta / (times[times.size()-1] - times[0]);\n                zeta *= model_->z0();\n                ActiveType c = -(b*b/4.0 + 1.0/zeta)/2.0;\n                // Psi_{z lambda^2}\n                ActiveType A = 0.0, B = 0.0;\n                //std::vector<ActiveType> y1(2,0.0), y0(2,0.0);\n                //RiccatiODE ode(model_,c,0.0,b);\n                for (size_t k=times.size()-1; k>0; --k) {\n                    DateType  t = (times[k]+times[k-1])/2.0;\n                    DateType dt = (times[k]-times[k-1]);\n                    ActiveType lambda = model_->lambda(t);\n                    A = A + A_CIR(B, -c*lambda*lambda, model_->z0(), model_->theta(), eta, dt);\n                    B = B_CIR(B, -c*lambda*lambda, model_->z0(), model_->theta(), eta, dt);\n                    // Riccati ODE via Runge Kutta Method\n                    //y1 = y0;\n                    //TemplateAuxilliaries::rungeKuttaStep<DateType,ActiveType>(y1,times[k],ode,times[k-1]-times[k],y0);\n                }\n                ActiveType target = A - B*model_->z0();\n                //ActiveType target = y0[0] + y0[1]*model_->z0();\n                AverageLambdaObjective f(model_->z0(), model_->theta(), eta, T, target);\n                ActiveType avLambda2c = avLambda2 * c;\n                avLambda2c = TemplateAuxilliaries::solve1d<ActiveType>(f, 1.0e-8, avLambda2c, avLambda2c, 10);\n                ActiveType avLambda = sqrt(avLambda2c / c);\n                return avLambda;\n            };\n        };\n    };\n\n    // piecewise constant parameters and numerical integration\n    template <class DateType, class PassiveType, class ActiveType>\n    class PWCAnalytical : public TimeDependentStochVolModelT<DateType,PassiveType,ActiveType> {\n        // from base class\n        using typename TimeDependentStochVolModelT<DateType, PassiveType, ActiveType>::PieceWiseConstant;\n        using typename TimeDependentStochVolModelT<DateType, PassiveType, ActiveType>::MidPointIntegration;\n        using typename TimeDependentStochVolModelT<DateType, PassiveType, ActiveType>::VolEvolv;\n\n    private:\n        ext::shared_ptr<PieceWiseConstant>    pwc_;\n        ext::shared_ptr<MidPointIntegration>  mp_;\n        VolEvolv volEvolv_;\n    public:\n        PWCAnalytical(const std::vector<DateType>&    times,\n                        const std::vector<ActiveType>&  lambda,\n                        const std::vector<ActiveType>&  b,\n                        const std::vector<ActiveType>&  eta,\n                        const ActiveType                L,\n                        const ActiveType                theta,\n                        const ActiveType                m,\n                        const ActiveType                z0,\n                        const ActiveType                rho,\n                        const ActiveType                S0,\n                        const VolEvolv                  volEvolv = VolEvolv::FullTruncation )\n            :    pwc_(new PieceWiseConstant(times,lambda,b,eta,L,theta,m,z0,rho,S0)),\n                    mp_(new MidPointIntegration(this,times)), volEvolv_(volEvolv) {}\t\t\t\t\t\t\n        // inspectors\n        virtual ActiveType  lambda( const DateType t)  { return pwc_->lambda(t);    }\n        virtual ActiveType  b(      const DateType t)  { return pwc_->b(t) ;        }\n        virtual ActiveType  eta(    const DateType t)  { return pwc_->eta(t);       }\n        virtual ActiveType  L()                        { return pwc_->L();          }\n        virtual ActiveType  theta()                    { return pwc_->theta();      }\n        virtual ActiveType  m()                        { return pwc_->m();          }\n        virtual ActiveType  z0()                       { return pwc_->z0();         }\n        virtual ActiveType  rho()                      { return pwc_->rho();        }\n        virtual ActiveType  S0()                       { return pwc_->S0();         }\n        virtual VolEvolv    volEvolv()                 { return volEvolv_;          }\n        // averaging formula implementations\n        virtual ActiveType  averageLambda( const DateType T) { return mp_->averageLambda( T ); }\n        virtual ActiveType  averageB     ( const DateType T) { return mp_->averageB( T );      }\n        virtual ActiveType  averageEta   ( const DateType T) { return mp_->averageEta( T );    }\n    };\n\n}\n\n#undef _MIN_\n#undef _MAX_\n\n#endif  /* ifndef quantlib_templatetdstochvolmodel_hpp */\n", "meta": {"hexsha": "d6cd6734be62d45935289656a6e4eb880cb2f4ef", "size": 22938, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/templatemodels/stochvol/tdstochvolmodelT.hpp", "max_stars_repo_name": "sschlenkrich/quantlib", "max_stars_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "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": "ql/experimental/templatemodels/stochvol/tdstochvolmodelT.hpp", "max_issues_repo_name": "sschlenkrich/quantlib", "max_issues_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/templatemodels/stochvol/tdstochvolmodelT.hpp", "max_forks_repo_name": "sschlenkrich/quantlib", "max_forks_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.3154362416, "max_line_length": 177, "alphanum_fraction": 0.4973406574, "num_tokens": 5803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5070073484801583}}
{"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#include <bitset>\n\nnamespace mp = boost::multiprecision;\nusing namespace std;\n\nint main(void) {\n    string s;\n    cin >> s;\n    \n    int a = 0;\n    int b = 0;\n    for(int i = 0 ; i < s.length() ; ++i) {\n        if(s[i] == '0') {\n            if(i & 0x1) { ++a; }\n            else { ++b; }\n        } else {\n            if(i & 0x1) { ++b; }\n            else { ++a; }\n        }\n    }\n    auto ans = min(a, b);\n    cout << ans << endl;\n\n    return 0;\n}", "meta": {"hexsha": "b1e9693e566753a7324db9e726ee6bf574fdab66", "size": 671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc124/c/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": "abc124/c/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": "abc124/c/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": 18.6388888889, "max_line_length": 43, "alphanum_fraction": 0.5022354694, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.50700734191222}}
{"text": "#include <fstream>\n#include <bits/stdc++.h>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <sstream>\n#include <algorithm>\n#include <math.h>\n#include <cstring>\n#include <queue>\n#include <stack>\n#include <map>\n#include <Eigen/Dense>\nusing namespace std;\n#define INF 0x3f3f3f3f\ntypedef Eigen::Vector3i beacon;\ntypedef Eigen::Matrix3i Perm;\ntypedef tuple<int,int,int> triplet;\n\nvector<beacon> generatePerm(beacon input){\n\n    auto roll = [](beacon in){\n        beacon res = {in(0),in(2),-in(3)};\n        return res;\n    };\n    auto turn = [](beacon in){\n        beacon res = {-in(1),in(0),in(2)};\n        return res;\n    };\n    vector<beacon> res;\n    for(int c = 0; c < 2; c++){\n        for(int s = 0; s < 3; s++){\n            input = roll(input);\n            res.push_back(input);\n            for(int i = 0; i < 3; i++){\n                input = turn(input);\n                res.push_back(input);\n            }\n        }\n        input = roll(turn(roll(input)));\n    }\n    return res;\n}\n\nbool read_input(vector<vector<beacon>> &input){\n    string filename = \"inputPartOne.txt\";   \n    ifstream input_file(filename);\n    int i = 0;\n    string temp1;\n    getline(input_file,temp1);\n    vector<beacon> row;\n    for(string line;getline(input_file, line);){\n        int n = line.size();\n        char arr[n+1];\n        strcpy(arr,line.c_str());\n        if(arr[0] == '-' && arr[1] == '-' && arr[2] == '-'){\n            i++;\n            continue;\n        }\n        if(n == 0){\n            input.push_back(row);\n            row.clear();\n            continue;\n        }\n        stringstream ss(line);\n        std::string s;\n        \n        getline(ss,s,',');\n        int x = stoi(s); \n        getline(ss,s,',');\n        int y = stoi(s);\n        getline(ss,s,',');\n        int z = stoi(s);\n        beacon t = {x,y,z};\n        row.push_back(t);\n    }\n    return false;\n}\n\ntriplet convBeacon(beacon in){\n    return make_tuple(in(0),in(1),in(2));\n}\nbeacon convTriplet(triplet in){\n    int x,y,z;\n    std::tie(x,y,z) = in;\n    beacon res;\n    res << x,y,z;\n    return res;\n}\nbeacon calc(beacon a, beacon b){\n    beacon res;\n    res = a + b ;\n\n    return res;\n}\nvoid solve(vector<vector<beacon>> input){\n    vector<Perm> rot;\n    beacon p;\n    vector<beacon> flips;\n    Perm one, two, three, four, five , six;\n    beacon a,b,c,d,e,f,g,h;\n    a << 1,1,1; \n    b << 1,1,-1; c << 1,-1,1; d << -1,1,1; e << 1,-1,-1; f << -1,-1,1;\n    g << -1,1,-1; h << -1,-1,-1;\n    flips.push_back(a);flips.push_back(b);flips.push_back(c);flips.push_back(d);\n    flips.push_back(e);flips.push_back(f);flips.push_back(g);flips.push_back(h);\n    one << 1, 0, 0 , 0 , 1 , 0, 0 , 0 , 1;\n    two << 1,0,0,0,0,1,0,1,0;\n    three << 0,1,0,1,0,0,0,0,1;\n    four << 0,1,0,0,0,1,1,0,0;\n    five << 0,0,1,0,1,0,1,0,0;\n    six << 0,0,1,1,0,0,0,1,0;\n    //cout << one << endl << two << endl << three << endl << four << endl << five << endl << six << endl;\n    rot.push_back(one);rot.push_back(two);rot.push_back(three);rot.push_back(four);\n    rot.push_back(five);rot.push_back(six);\n    vector<Perm> perms;\n    for(Perm A: rot){\n        for(beacon B: flips){\n            \n            Perm res = B.asDiagonal() * A;\n            perms.push_back(res);\n        }\n    }\n    int n = input.size();\n    vector<beacon> pos(n);\n    vector<int> rotation(n, -1);\n    vector<bool> vis(n, false);\n    pos[0] = {0,0,0};\n    rotation[0] = 0;\n    vis[0] = true;\n    for(int scanner1 = 0; scanner1 < n; scanner1++){\n        if(!vis[scanner1])\n            continue;\n        for(int scanner2 = scanner1+1; scanner2 < n; scanner2++){\n            bool foundWinnter = false;\n                for(int rot2 = 0; rot2 < 48; rot2++){\n                    map<triplet, int> diffCounter;\n                    for(int beacon1 = 0; beacon1 < input[scanner1].size(); beacon1++){\n                        for(int beacon2 = 0; beacon2 < input[scanner2].size(); beacon2++){\n                            beacon b1 = input[scanner1][beacon1];\n                            beacon b2 = perms[rot2] * input[scanner2][beacon2]; \n                            beacon diff = (b1 - b2);\n                            triplet diffForMap = convBeacon(diff);\n                            diffCounter[diffForMap]++;\n                            if(diffCounter[diffForMap] >= 12){\n                                foundWinnter = true;\n                                beacon relDist = pos[scanner1] - diff;\n                                beacon relDist2 = pos[scanner1] + diff;\n                                beacon relDist3 = diff - pos[scanner1] ;\n                                cout << \" found match: \" << scanner1 << \" \" << scanner2 << endl;\n                                cout << pos[scanner1].transpose() << \" pos Scanner 1 \"<< endl;\n                                cout << diff.transpose() << \" diff\" << endl;\n                                cout << (relDist).transpose() << \" relDist\"  << endl;\n                                cout << (relDist2).transpose() << \" relDist2\"  << endl;\n                                cout << (relDist3).transpose() << \" relDist3\"  << endl;\n                                cout << endl;\n                                //cout << perms[rot2]<< endl;\n                                rotation[scanner2] = rot2;\n                                pos[scanner2] = diff;\n\n                            }\n                        }\n                        if(foundWinnter)\n                            break;\n                    }\n                    if(foundWinnter)\n                    break;                    \n                }\n            if(!foundWinnter)\n                continue;\n            vector<beacon> curr = input[scanner2];\n            int rot = rotation[scanner2];\n            beacon posMe = pos[scanner2];\n            for(int i = 0; i < curr.size(); i++){          \n                curr[i] = perms[rot] * curr[i];\n                curr[i] += posMe;\n                cout << \" \" << curr[i].transpose() << endl;\n            }\n            vis[scanner2] = true;\n        }\n    }\n\n}\n\nint main(){\n    vector<vector<beacon>> input;\n    read_input(input);\n    solve(input);\n\n\n}\n", "meta": {"hexsha": "7459564780dc69922da4068bab42066c70f472da", "size": 6118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day19.cpp", "max_stars_repo_name": "AlbinMamuti/AoC", "max_stars_repo_head_hexsha": "8f65f09787ae10103dc6e1e107c8bd72f133158c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Day19.cpp", "max_issues_repo_name": "AlbinMamuti/AoC", "max_issues_repo_head_hexsha": "8f65f09787ae10103dc6e1e107c8bd72f133158c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day19.cpp", "max_forks_repo_name": "AlbinMamuti/AoC", "max_forks_repo_head_hexsha": "8f65f09787ae10103dc6e1e107c8bd72f133158c", "max_forks_repo_licenses": ["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.8645833333, "max_line_length": 105, "alphanum_fraction": 0.4573389997, "num_tokens": 1640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5069509870650559}}
{"text": "#include \"camera_array/RandomArrayManager.h\"\n#include \"argus_utils/random/RandomUtils.hpp\"\n#include <boost/foreach.hpp>\n\nnamespace argus\n{\n\t\nRandomArrayManager::RandomArrayManager( const ros::NodeHandle& nh,\n                                        const ros::NodeHandle& ph )\n: CameraArrayManager( nh, ph )\n{\n\n\tboost::random::random_device rng;\n\tgenerator.seed( rng );\n\t\t\n\tcameraNames.reserve( cameraRegistry.size() );\n\tBOOST_FOREACH( const CameraRegistry::value_type& item, cameraRegistry )\n\t{\n\t\tcameraNames.push_back( item.first );\n\t}\n\n  double updateRate;\n  ph.param<double>( \"update_rate\", updateRate, 1.0 );\n  timer = std::make_shared<ros::Timer>\n    ( nodeHandle.createTimer( ros::Duration( 1.0/updateRate ),\n\t\t\t      &RandomArrayManager::TimerCallback,\n\t\t\t      this ) );\n\n}\n\nvoid RandomArrayManager::TimerCallback( const ros::TimerEvent& event )\n{\n\tstd::vector<unsigned int> cameraInds;\n\tBitmapSampling( cameraNames.size(), maxNumActive, cameraInds, generator );\n\t\n\tCameraSet active;\n\tfor( unsigned int i = 0; i < cameraInds.size(); i++ )\n\t{\n\t\tactive.insert( cameraNames[ cameraInds[i] ] );\n\t\tROS_INFO_STREAM( \"Activating \" << cameraNames[ cameraInds[i] ] );\n\t}\n\tSetActiveCameras( active );\n}\n\n}\n", "meta": {"hexsha": "88d92bdd60d97e23bf4fe3c14f8435a260750c04", "size": 1204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "camera_array/src/RandomArrayManager.cpp", "max_stars_repo_name": "Humhu/argus", "max_stars_repo_head_hexsha": "8b112382038c6df1ecf15d9c872b6cc9b471cd22", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-08-02T20:32:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T09:33:33.000Z", "max_issues_repo_path": "camera_array/src/RandomArrayManager.cpp", "max_issues_repo_name": "Humhu/argus", "max_issues_repo_head_hexsha": "8b112382038c6df1ecf15d9c872b6cc9b471cd22", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-12T22:57:59.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-13T02:52:36.000Z", "max_forks_repo_path": "camera_array/src/RandomArrayManager.cpp", "max_forks_repo_name": "Humhu/argus", "max_forks_repo_head_hexsha": "8b112382038c6df1ecf15d9c872b6cc9b471cd22", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-03-25T08:36:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-23T00:28:16.000Z", "avg_line_length": 26.1739130435, "max_line_length": 75, "alphanum_fraction": 0.6926910299, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5068737036833891}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_TOOLBOX_ARITHMETIC_FUNCTION_SCALAR_TWO_PROD_HPP_INCLUDED\n#define NT2_TOOLBOX_ARITHMETIC_FUNCTION_SCALAR_TWO_PROD_HPP_INCLUDED\n#include <nt2/sdk/meta/adapted_traits.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <nt2/include/functions/is_invalid.hpp>\n#include <nt2/include/functions/two_split.hpp>\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type  is fundamental_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::two_prod_, tag::cpu_,\n                          (A0)(A1),\n                          (real_<A0>)(real_<A1>)\n                         )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::two_prod_(tag::real_,tag::real_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0,class A1>\n    struct result<This(A0,A1)>\n    {\n      typedef typename std::tr1::result_of<meta::floating(A0, A1)>::type rtype;\n      typedef typename boost::fusion::tuple<rtype,rtype>              type;\n    };\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      typename NT2_RETURN_TYPE(2)::type res;\n      eval(a0,a1, boost::fusion::at_c<0>(res),boost::fusion::at_c<1>(res));\n      return res;\n    }\n    private:\n    template<class A0,class A1,class R0,class R1> inline void\n    eval(A0 const& a, A1 const& b,R0& r0, R1& r1)const\n    {\n      r0  = a*b;\n      if (is_invalid(r0))\n\t{\n\t  r1 = Zero<R1>();\n\t  return;\n\t}\n      A0 a1, a2, b1, b2;\n      boost::fusion::tie(a1, a2) = two_split(a);\n      boost::fusion::tie(b1, b2) = two_split(b);\n      r1 = a2*b2 -(((r0-a1*b1)-a2*b1)-a1*b2);\n    }\n  };\n} }\n\n#endif\n// modified by jt the 26/12/2010\n", "meta": {"hexsha": "eedb3ec0ea41acced3a9e59c9b7665b927d63980", "size": 2236, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/arithmetic/include/nt2/toolbox/arithmetic/function/scalar/two_prod.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/arithmetic/include/nt2/toolbox/arithmetic/function/scalar/two_prod.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "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": "modules/arithmetic/include/nt2/toolbox/arithmetic/function/scalar/two_prod.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "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.4, "max_line_length": 79, "alphanum_fraction": 0.5357781753, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5068737013677656}}
{"text": "// ----------------------------------------------------------------------------\n// -                        Open3D: www.open3d.org                            -\n// ----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2018 www.open3d.org\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\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n// ----------------------------------------------------------------------------\n\n#include \"Feature.h\"\n\n#include <Eigen/Dense>\n#include <Core/Utility/Console.h>\n#include <Core/Geometry/PointCloud.h>\n#include <Core/Geometry/KDTreeFlann.h>\n\nnamespace three {\n\nnamespace {\n\nEigen::Vector4d ComputePairFeatures(const Eigen::Vector3d &p1,\n\t\tconst Eigen::Vector3d &n1, const Eigen::Vector3d &p2,\n\t\tconst Eigen::Vector3d &n2)\n{\n\tEigen::Vector4d result;\n\tEigen::Vector3d dp2p1 = p2 - p1;\n\tresult(3) = dp2p1.norm();\n\tif (result(3) == 0.0) {\n\t\treturn Eigen::Vector4d::Zero();\n\t}\n\tauto n1_copy = n1;\n\tauto n2_copy = n2;\n\tdouble angle1 = n1_copy.dot(dp2p1) / result(3);\n\tdouble angle2 = n2_copy.dot(dp2p1) / result(3);\n\tif (acos(fabs(angle1)) > acos(fabs(angle2))) {\n\t\tn1_copy = n2;\n\t\tn2_copy = n1;\n\t\tdp2p1 *= -1.0;\n\t\tresult(2) = -angle2;\n\t} else {\n\t\tresult(2) = angle1;\n\t}\n\tauto v = dp2p1.cross(n1_copy);\n\tdouble v_norm = v.norm();\n\tif (v_norm == 0.0) {\n\t\treturn Eigen::Vector4d::Zero();\n\t}\n\tv /= v_norm;\n\tauto w = n1_copy.cross(v);\n\tresult(1) = v.dot(n2_copy);\n\tresult(0) = atan2(w.dot(n2_copy), n1_copy.dot(n2_copy));\n\treturn result;\n}\n\nstd::shared_ptr<Feature> ComputeSPFHFeature(const PointCloud &input,\n\t\tconst KDTreeFlann &kdtree, const KDTreeSearchParam &search_param)\n{\n\tauto feature = std::make_shared<Feature>();\n\tfeature->Resize(33, (int)input.points_.size());\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n\tfor (int i = 0; i < (int)input.points_.size(); i++) {\n\t\tconst auto &point = input.points_[i];\n\t\tconst auto &normal = input.normals_[i];\n\t\tstd::vector<int> indices;\n\t\tstd::vector<double> distance2;\n\t\tif (kdtree.Search(point, search_param, indices, distance2) > 1) {\n\t\t\t// only compute SPFH feature when a point has neighbors\n\t\t\tdouble hist_incr = 100.0 / (double)(indices.size() - 1);\n\t\t\tfor (size_t k = 1; k < indices.size(); k++) {\n\t\t\t\t// skip the point itself, compute histogram\n\t\t\t\tauto pf = ComputePairFeatures(point, normal,\n\t\t\t\t\t\tinput.points_[indices[k]], input.normals_[indices[k]]);\n\t\t\t\tint h_index = (int)(floor(11 * (pf(0) + M_PI) / (2.0 * M_PI)));\n\t\t\t\tif (h_index < 0) h_index = 0;\n\t\t\t\tif (h_index >= 11) h_index = 10;\n\t\t\t\tfeature->data_(h_index, i) += hist_incr;\n\t\t\t\th_index = (int)(floor(11 * (pf(1) + 1.0) * 0.5));\n\t\t\t\tif (h_index < 0) h_index = 0;\n\t\t\t\tif (h_index >= 11) h_index = 10;\n\t\t\t\tfeature->data_(h_index + 11, i) += hist_incr;\n\t\t\t\th_index = (int)(floor(11 * (pf(2) + 1.0) * 0.5));\n\t\t\t\tif (h_index < 0) h_index = 0;\n\t\t\t\tif (h_index >= 11) h_index = 10;\n\t\t\t\tfeature->data_(h_index + 22, i) += hist_incr;\n\t\t\t}\n\t\t}\n\t}\n\treturn feature;\n}\n\nclass ProjectedPoints\n{\npublic:\n\tint id;\t\t// global point ID\n\tdouble u;\t// u coordinate on the projected patch\n\tdouble v;\t// v coordinate on the projected patch\n\tdouble depth;\n};\n\nstd::vector<ProjectedPoints> PlanarParameterizationForOnePoint(\n\t\tsize_t point_id, const PointCloud &cloud, const KDTreeFlann &kdtree,\n\t\tconst KDTreeSearchParamHybrid &search_param,\n\t\tconst PlanarParameterizationOption &option)\n{\n\tconst int patch_half_size = option.half_patch_size_;\n\tconst int patch_size = patch_half_size * 2 + 1;\n\tconst double patch_half_diag_length = sqrt((2.0 * pow(patch_half_size, 2.0)));\n\n\tstd::vector<int> indices;\n\tstd::vector<double> distance2;\n\tEigen::Matrix3d tangential_axis;\n\tEigen::Vector3d vt, vt_n, vt_t1, vt_t2, vt_adj, vt_proj;\n\tEigen::Vector2d vt_val = Eigen::Vector2d::Zero();\n\tEigen::Vector2i vt_val_descrete = Eigen::Vector2i::Zero();\n\tEigen::MatrixXd patch = Eigen::MatrixXd::Zero(patch_size, patch_size);\n\tdouble depth = -1.0;\n\tint adj_id = -1;\n\tvt = cloud.points_[point_id];\n\n\t// giving enough search radius to give enough space in the boundry pixels\n\tKDTreeSearchParamHybrid search_param_buffer = search_param;\n\tsearch_param_buffer.radius_ = search_param.radius_ * 2.0;\n\tint number_of_searched_neighbors =\n\t\t\tkdtree.Search(vt, search_param_buffer, indices, distance2);\n\tstd::vector<ProjectedPoints> output;\n\toutput.resize(number_of_searched_neighbors);\n\n\tif (number_of_searched_neighbors >= 1) {\n\t\ttangential_axis = ComputeTangentialAxis(cloud, indices);\n\t\tvt_n = tangential_axis.col(0);\n\t\tvt_t1 = tangential_axis.col(1);\n\t\tvt_t2 = tangential_axis.col(2);\n\t\t// project points onto tangential PlanarParameterization\n\t\tfor (int j = 0; j < number_of_searched_neighbors; j++){\n\t\t\tadj_id = indices[j];\n\t\t\tvt_adj = cloud.points_[adj_id];\n\t\t\tdepth = (vt_adj - vt).dot(vt_n);\n\t\t\tvt_proj = vt_adj - depth * vt_n;\n\t\t\tvt_val(0) = (vt_proj - vt).dot(vt_t1);\n\t\t\tvt_val(1) = (vt_proj - vt).dot(vt_t2);\n\t\t\tvt_val = vt_val / search_param.radius_ * patch_half_diag_length;\n\t\t\toutput[j].u = vt_val(0);\n\t\t\toutput[j].v = vt_val(1);\n\t\t\toutput[j].depth = depth;\n\t\t\toutput[j].id = adj_id;\n\t\t}\n\t}\n\treturn std::move(output);\n}\n\nclass ProcessedPatch\n{\npublic:\n\t// kernel x kernel size, local depth map\n\tEigen::MatrixXd depth_map;\n\t// kernel x kernel size, point cloud index\n\tstd::vector<Eigen::MatrixXi> index_map;\n\t// kernel x kernel size, point cloud weight to adjacent index\n\tstd::vector<Eigen::MatrixXd> weight_map;\n};\n\nstd::shared_ptr<ProcessedPatch> PlanarParameterizationForOnePatch(\n\t\tconst std::vector<ProjectedPoints> &projected_points,\n\t\tconst PlanarParameterizationOption &option)\n{\n\tconst int number_of_neighbors = option.number_of_neighbors_;\n\tconst int patch_half_size = option.half_patch_size_;\n\tconst int patch_size = patch_half_size * 2 + 1;\n\tconst double sigma_pow2 = option.sigma_ * option.sigma_;\n\n\tauto output = std::make_shared<ProcessedPatch>();\n\toutput->index_map.resize(number_of_neighbors);\n\toutput->weight_map.resize(number_of_neighbors);\n\tfor (int i = 0; i < number_of_neighbors; i++){\n\t\toutput->index_map[i].resize(patch_size, patch_size);\n\t\toutput->weight_map[i].resize(patch_size, patch_size);\n\t\toutput->index_map[i].setConstant(-1);\n\t\toutput->weight_map[i].setZero();\n\t}\n\toutput->depth_map.resize(patch_size, patch_size);\n\n\tconst int number_of_points = int(projected_points.size());\n\tEigen::MatrixXd data = Eigen::MatrixXd::Zero(2, number_of_points);\n\tint cnt = 0;\n\tfor (int i = 0; i < (int)projected_points.size(); i++){\n\t\tdata(0,i) = projected_points[i].u;\n\t\tdata(1,i) = projected_points[i].v;\n\t}\n\tKDTreeFlann kdtree;\n\tkdtree.SetMatrixData(data);\n\tstd::vector<int> indices;\n\tstd::vector<double> distance2;\n\tfor (int u = 0; u < (int)patch_size; u++){\n\t\tfor (int v = 0; v < (int)patch_size; v++){\n\t\t\tEigen::Vector2d query;\n\t\t\tquery(0) = u - patch_half_size;\n\t\t\tquery(1) = v - patch_half_size;\n\t\t\t// todo: should we use SearchKNN here? maybe fill in blank\n\t\t\tint number_of_searched_neighbors = kdtree.SearchKNN(\n\t\t\t\t\tquery, number_of_neighbors, indices, distance2);\n\t\t\tdouble sum_weight = 0.0, sum_weighted_val = 0.0;\n\t\t\tfor (int i = 0; i < number_of_searched_neighbors; i++) {\n\t\t\t\tint i_adj = indices[i];\n\t\t\t\tdouble dist_adj = distance2[i];\n\t\t\t\tdouble weight_i_th_adj = exp(-dist_adj/sigma_pow2);\n\t\t\t\tdouble depth_adj = projected_points[i_adj].depth;\n\t\t\t\tsum_weight += weight_i_th_adj;\n\t\t\t\tsum_weighted_val += weight_i_th_adj * depth_adj;\n\t\t\t\toutput->index_map[i](v, u) = projected_points[i_adj].id;\n\t\t\t\toutput->weight_map[i](v, u) = weight_i_th_adj;\n\t\t\t}\n\t\t\t// normalize weight_map\n\t\t\tif (sum_weight != 0.0){\n\t\t\t\tfor (int i = 0; i < number_of_searched_neighbors; i++) {\n\t\t\t\t\toutput->weight_map[i](v, u) /= sum_weight;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (number_of_searched_neighbors >= 1){\n\t\t\t\tif (option.depth_densify_method_ ==\n\t\t\t\t\tdepth_densify_gaussian_kernel && sum_weight != 0.0)\n\t\t\t\t\toutput->depth_map(v, u) = sum_weighted_val / sum_weight;\n\t\t\t\telse if (option.depth_densify_method_ ==\n\t\t\t\t\t\tdepth_densify_nearest_neighbor)\n\t\t\t\t\toutput->depth_map(v, u) =\n\t\t\t\t\tprojected_points[indices[0]].depth;\n\t\t\t}\n\t\t}\n\t}\n\treturn output;\n}\n\n}\t// unnamed namespace\n\nstd::shared_ptr<Feature> ComputeFPFHFeature(const PointCloud &input,\n\t\tconst KDTreeSearchParam &search_param/* = KDTreeSearchParamKNN()*/)\n{\n\tauto feature = std::make_shared<Feature>();\n\tfeature->Resize(33, (int)input.points_.size());\n\tif (input.HasNormals() == false) {\n\t\tPrintDebug(\"[ComputeFPFHFeature] Failed because input point cloud has no normal.\\n\");\n\t\treturn feature;\n\t}\n\tKDTreeFlann kdtree(input);\n\tauto spfh = ComputeSPFHFeature(input, kdtree, search_param);\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n\tfor (int i = 0; i < (int)input.points_.size(); i++) {\n\t\tconst auto &point = input.points_[i];\n\t\tstd::vector<int> indices;\n\t\tstd::vector<double> distance2;\n\t\tif (kdtree.Search(point, search_param, indices, distance2) > 1) {\n\t\t\tdouble sum[3] = {0.0, 0.0, 0.0};\n\t\t\tfor (size_t k = 1; k < indices.size(); k++) {\n\t\t\t\t// skip the point itself\n\t\t\t\tdouble dist = distance2[k];\n\t\t\t\tif (dist == 0.0)\n\t\t\t\t\tcontinue;\n\t\t\t\tfor (int j = 0; j < 33; j++) {\n\t\t\t\t\tdouble val = spfh->data_(j, indices[k]) / dist;\n\t\t\t\t\tsum[j / 11] += val;\n\t\t\t\t\tfeature->data_(j, i) += val;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t\tif (sum[j] != 0.0) sum[j] = 100.0 / sum[j];\n\t\t\tfor (int j = 0; j < 33; j++) {\n\t\t\t\tfeature->data_(j, i) *= sum[j / 11];\n\t\t\t\t// The commented line is the fpfh function in the paper.\n\t\t\t\t// But according to PCL implementation, it is skipped.\n\t\t\t\t// Our initial test shows that the full fpfh function in the\n\t\t\t\t// paper seems to be better than PCL implementation. Further\n\t\t\t\t// test required.\n\t\t\t\tfeature->data_(j, i) += spfh->data_(j, i);\n\t\t\t}\n\t\t}\n\t}\n\treturn feature;\n}\n\nstd::shared_ptr<PlanarParameterizationOutput> PlanarParameterization(\n\t\tconst PointCloud &cloud,\n\t\tconst KDTreeSearchParamHybrid &search_param,\n\t\tconst PlanarParameterizationOption &option)\n{\n\t// parameters\n\tconst int patch_size = option.half_patch_size_ * 2 + 1;\n\tconst int patch_size_pow2 = patch_size * patch_size;\n\tconst int number_of_points = (int)cloud.points_.size();\n\n\tauto output = std::make_shared<PlanarParameterizationOutput>();\n\toutput->depth_.Resize(patch_size_pow2, number_of_points);\n\tfor (int i = 0; i < option.number_of_neighbors_; i++){\n\t\tFeature data_weight;\n\t\tdata_weight.Resize(patch_size_pow2, number_of_points);\n\t\toutput->weight_.push_back(data_weight);\n\t\tEigen::MatrixXi data_index;\n\t\tdata_index.resize(patch_size_pow2, number_of_points);\n\t\toutput->index_.push_back(data_index);\n\t}\n\tKDTreeFlann kdtree;\n\tkdtree.SetGeometry(cloud);\n\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n\tfor (int i = 0; i < number_of_points; i++) {\n\t\tauto projected_points = PlanarParameterizationForOnePoint(\n\t\t\t\ti, cloud, kdtree, search_param, option);\n\t\tauto information_patch = PlanarParameterizationForOnePatch(\n\t\t\t\tprojected_points, option);\n\t\tfor (int j = 0; j < option.number_of_neighbors_; j++){\n\t\t\tfor (int k = 0; k < patch_size_pow2; k++){\n\t\t\t\toutput->weight_[j].data_(k, i) =\n\t\t\t\t\t\tinformation_patch->weight_map[j](k);\n\t\t\t\toutput->index_[j](k, i) =\n\t\t\t\t\t\tinformation_patch->index_map[j](k);\n\t\t\t}\n\t\t}\n\t\tfor (size_t k = 0; k < patch_size_pow2; k++){\n\t\t\toutput->depth_.data_(k, i) = information_patch->depth_map(k);\n\t\t}\n\t}\n\treturn output;\n}\n\n}\t// namespace three\n", "meta": {"hexsha": "f97c04e01695f40283c911081fdb42b7c6a8e0d3", "size": 12230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Core/Registration/Feature.cpp", "max_stars_repo_name": "xiedotscene/Open3D", "max_stars_repo_head_hexsha": "483f6682d04e447a267d920bf48b9e3a91b56e7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-07T04:26:47.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-11T23:38:18.000Z", "max_issues_repo_path": "src/Core/Registration/Feature.cpp", "max_issues_repo_name": "xiedotscene/Open3D", "max_issues_repo_head_hexsha": "483f6682d04e447a267d920bf48b9e3a91b56e7b", "max_issues_repo_licenses": ["MIT"], "max_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/Registration/Feature.cpp", "max_forks_repo_name": "xiedotscene/Open3D", "max_forks_repo_head_hexsha": "483f6682d04e447a267d920bf48b9e3a91b56e7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-28T13:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T13:17:42.000Z", "avg_line_length": 35.2449567723, "max_line_length": 87, "alphanum_fraction": 0.6808667212, "num_tokens": 3534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5068736913639671}}
{"text": "#include <NumCpp.hpp>\n\n#define BOOST_NO_CXX11_SCOPED_ENUMS\n#include <boost/filesystem.hpp>\n#undef BOOST_NO_CXX11_SCOPED_ENUMS\n\n#include <catch2/catch.hpp>\n\n#include <iostream>\n\nnamespace {\ntemplate <typename T> void mark_unread(const T var) { (void)var; }\n} // namespace\n\nint main([[maybe_unused]] int argc, [[maybe_unused]] const char **argv) {\n  // Containers\n  [[maybe_unused]] nc::NdArray<int> a0 = {{1, 2}, {3, 4}};\n  mark_unread(a0);\n  [[maybe_unused]] nc::NdArray<int> a1 = {{1, 2}, {3, 4}, {5, 6}};\n  a1.reshape(2, 3);\n  [[maybe_unused]] auto a2 = a1.astype<double>();\n  mark_unread(a2);\n\n  // // Initializers\n  auto a3 = nc::linspace<int>(1, 10, 5);\n  auto a4 = nc::arange<int>(3, 7);\n  auto a5 = nc::eye<int>(4);\n  auto a6 = nc::zeros<int>(3, 4);\n  auto a7 = nc::NdArray<int>(3, 4) = 0;\n  auto a8 = nc::ones<int>(3, 4);\n  auto a9 = nc::NdArray<int>(3, 4) = 1;\n  auto a10 = nc::nans(3, 4);\n  auto a11 = nc::NdArray<double>(3, 4) = nc::constants::nan;\n  auto a12 = nc::empty<int>(3, 4);\n  auto a13 = nc::NdArray<int>(3, 4);\n  mark_unread(a3);\n  mark_unread(a4);\n  mark_unread(a5);\n  mark_unread(a6);\n  mark_unread(a7);\n  mark_unread(a8);\n  mark_unread(a9);\n  mark_unread(a10);\n  mark_unread(a11);\n  mark_unread(a12);\n  mark_unread(a13);\n\n  // Slicing/Broadcasting\n  auto a14 = nc::random::randInt<int>({10, 10}, 0, 100);\n  auto value = a14(2, 3);\n  auto slice = a14({2, 5}, {2, 5});\n  auto rowSlice = a14(a14.rSlice(), 7);\n  auto values = a14[a14 > 50];\n  a14.putMask(a14 > 50, 666);\n  mark_unread(value);\n  mark_unread(slice);\n  mark_unread(rowSlice);\n  mark_unread(values);\n\n  // random\n  nc::random::seed(666);\n  auto a15 = nc::random::randN<double>({3, 4});\n  auto a16 = nc::random::randInt<int>({3, 4}, 0, 10);\n  auto a17 = nc::random::rand<double>({3, 4});\n  auto a18 = nc::random::choice(a17, 3);\n  mark_unread(a15);\n  mark_unread(a16);\n  mark_unread(a17);\n  mark_unread(a18);\n\n  // Concatenation\n  auto a = nc::random::randInt<int>({3, 4}, 0, 10);\n  auto b = nc::random::randInt<int>({3, 4}, 0, 10);\n  auto c = nc::random::randInt<int>({3, 4}, 0, 10);\n  auto a19 = nc::stack({a, b, c}, nc::Axis::ROW);\n  auto a20 = nc::vstack({a, b, c});\n  auto a21 = nc::hstack({a, b, c});\n  auto a22 = nc::append(a, b, nc::Axis::COL);\n  mark_unread(a19);\n  mark_unread(a20);\n  mark_unread(a21);\n  mark_unread(a22);\n\n  // Diagonal, Traingular, and Flip\n  auto d = nc::random::randInt<int>({5, 5}, 0, 10);\n  auto a23 = nc::diagonal(d);\n  auto a24 = nc::triu(a);\n  auto a25 = nc::tril(a);\n  auto a26 = nc::flip(d, nc::Axis::ROW);\n  auto a27 = nc::flipud(d);\n  auto a28 = nc::fliplr(d);\n  mark_unread(a23);\n  mark_unread(a24);\n  mark_unread(a25);\n  mark_unread(a26);\n  mark_unread(a27);\n  mark_unread(a28);\n\n  // iteration\n  for (auto it = a.cbegin(); it < a.cend(); ++it) {\n    std::cout << *it << \" \";\n  }\n  std::cout << std::endl;\n  for (const auto &arrayValue : a) {\n    std::cout << arrayValue << \" \";\n  }\n  std::cout << std::endl;\n\n  // Logical\n  auto a29 = nc::where(a > 5, a, b);\n  auto a30 = nc::any(a);\n  auto a31 = nc::all(a);\n  auto a32 = nc::logical_and(a, b);\n  auto a33 = nc::logical_or(a, b);\n  auto a34 = nc::isclose(a, b);\n  auto a35 = nc::allclose(a, b);\n  mark_unread(a29);\n  mark_unread(a30);\n  mark_unread(a31);\n  mark_unread(a32);\n  mark_unread(a33);\n  mark_unread(a34);\n  mark_unread(a35);\n\n  // Comparisons\n  auto a36 = nc::equal(a, b);\n  auto a37 = a == b;\n  auto a38 = nc::not_equal(a, b);\n  auto a39 = a != b;\n  auto [rows, cols] = nc::nonzero(a);\n  mark_unread(a36);\n  mark_unread(a37);\n  mark_unread(a38);\n  mark_unread(a39);\n  mark_unread(rows);\n  mark_unread(cols);\n\n  // Minimum, Maximum, Sorting\n  auto value1 = nc::min(a);\n  auto value2 = nc::max(a);\n  auto value3 = nc::argmin(a);\n  auto value4 = nc::argmax(a);\n  auto a41 = nc::sort(a, nc::Axis::ROW);\n  auto a42 = nc::argsort(a, nc::Axis::COL);\n  auto a43 = nc::unique(a);\n  auto a44 = nc::setdiff1d(a, b);\n  auto a45 = nc::diff(a);\n  mark_unread(value1);\n  mark_unread(value2);\n  mark_unread(value3);\n  mark_unread(value4);\n  mark_unread(a41);\n  mark_unread(a42);\n  mark_unread(a43);\n  mark_unread(a44);\n  mark_unread(a45);\n\n  // Reducers\n  auto value5 = nc::sum<int>(a);\n  auto a46 = nc::sum<int>(a, nc::Axis::ROW);\n  auto value6 = nc::prod<int>(a);\n  auto a47 = nc::prod<int>(a, nc::Axis::ROW);\n  auto value7 = nc::mean(a);\n  auto a48 = nc::mean(a, nc::Axis::ROW);\n  auto value8 = nc::count_nonzero(a);\n  auto a49 = nc::count_nonzero(a, nc::Axis::ROW);\n  mark_unread(value5);\n  mark_unread(value6);\n  mark_unread(value7);\n  mark_unread(value8);\n  mark_unread(a46);\n  mark_unread(a47);\n  mark_unread(a48);\n  mark_unread(a49);\n\n  // I/O\n  a.print();\n  std::cout << a << std::endl;\n  // auto tempDir = boost::filesystem::temp_directory_path();\n  // auto tempTxt = (tempDir / \"temp.txt\").string();\n  // a.tofile(tempTxt, \"\\n\");\n  // auto a50 = nc::fromfile<int>(tempTxt, \"\\n\");\n  // auto tempBin = (tempDir / \"temp.bin\").string();\n  // nc::dump(a, tempBin);\n  // auto a51 = nc::load<int>(tempBin);\n\n  // Mathematical Functions\n\n  // Basic Functions\n  auto a52 = nc::abs(a);\n  auto a53 = nc::sign(a);\n  auto a54 = nc::remainder(a, b);\n  auto a55 = nc::clip(a, 3, 8);\n  auto xp = nc::linspace<double>(0.0, 2.0 * nc::constants::pi, 100);\n  auto fp = nc::sin(xp);\n  auto x = nc::linspace<double>(0.0, 2.0 * nc::constants::pi, 1000);\n  auto f = nc::interp(x, xp, fp);\n  mark_unread(a52);\n  mark_unread(a53);\n  mark_unread(a54);\n  mark_unread(a55);\n  mark_unread(f);\n\n  // Exponential Functions\n  auto a56 = nc::exp(a);\n  auto a57 = nc::expm1(a);\n  auto a58 = nc::log(a);\n  auto a59 = nc::log1p(a);\n  mark_unread(a56);\n  mark_unread(a57);\n  mark_unread(a58);\n  mark_unread(a59);\n\n  // Power Functions\n  auto a60 = nc::power<int>(a, 4);\n  auto a61 = nc::sqrt(a);\n  auto a62 = nc::square(a);\n  auto a63 = nc::cbrt(a);\n  mark_unread(a60);\n  mark_unread(a61);\n  mark_unread(a62);\n  mark_unread(a63);\n\n  // Trigonometric Functions\n  auto a64 = nc::sin(a);\n  auto a65 = nc::cos(a);\n  auto a66 = nc::tan(a);\n  mark_unread(a64);\n  mark_unread(a65);\n  mark_unread(a66);\n\n  // Hyperbolic Functions\n  auto a67 = nc::sinh(a);\n  auto a68 = nc::cosh(a);\n  auto a69 = nc::tanh(a);\n  mark_unread(a67);\n  mark_unread(a68);\n  mark_unread(a69);\n\n  // Classification Functions\n  auto a70 = nc::isnan(a.astype<double>());\n  mark_unread(a70);\n\n  // Linear Algebra\n  auto a71 = nc::norm<int>(a);\n  auto a72 = nc::dot<int>(a, b.transpose());\n  auto a73 = nc::random::randInt<int>({3, 3}, 0, 10);\n  auto a74 = nc::random::randInt<int>({4, 3}, 0, 10);\n  auto a75 = nc::random::randInt<int>({1, 4}, 0, 10);\n  auto value9 = nc::linalg::det(a73);\n  mark_unread(a71);\n  mark_unread(a72);\n  mark_unread(a73);\n  mark_unread(a74);\n  mark_unread(a75);\n  mark_unread(value9);\n\n  auto a76 = nc::linalg::inv(a73);\n  auto a77 = nc::linalg::lstsq(a74, a75);\n  auto a78 = nc::linalg::matrix_power<int>(a73, 3);\n  auto a79 = nc::linalg::multi_dot<int>({a, b.transpose(), c});\n  nc::NdArray<double> u;\n  nc::NdArray<double> s;\n  nc::NdArray<double> vt;\n  nc::linalg::svd(a.astype<double>(), u, s, vt);\n  mark_unread(a76);\n  mark_unread(a77);\n  mark_unread(a78);\n  mark_unread(a79);\n  mark_unread(u);\n  mark_unread(s);\n  mark_unread(vt);\n\n  std::cout << \"Hello World! yay\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "9b214ca8fee883b622a4909a1644daa37d2a46ac", "size": 7225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "kontramind/cpp_template_numcpp", "max_stars_repo_head_hexsha": "a45495972c97aa9133c6de273a147336ac9e7180", "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/main.cpp", "max_issues_repo_name": "kontramind/cpp_template_numcpp", "max_issues_repo_head_hexsha": "a45495972c97aa9133c6de273a147336ac9e7180", "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/main.cpp", "max_forks_repo_name": "kontramind/cpp_template_numcpp", "max_forks_repo_head_hexsha": "a45495972c97aa9133c6de273a147336ac9e7180", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-17T05:09:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T05:09:43.000Z", "avg_line_length": 26.083032491, "max_line_length": 73, "alphanum_fraction": 0.6124567474, "num_tokens": 2645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5068687453107279}}
{"text": "#include <iostream>\n#include <armadillo>\n\n#include \"printing.h\"\n#include \"CycleTimer.h\"\n\nvoid saxpy_arma_copy(float scale,\n                     arma::Col<float> X,\n                     arma::Col<float> Y,\n                     arma::Col<float>& result)\n{\n\n  result = (scale * X) + Y;\n\n  return;\n\n}\n\nvoid saxpy_arma_reference(float scale,\n                          arma::Col<float>& X,\n                          arma::Col<float>& Y,\n                          arma::Col<float>& result)\n{\n\n  result = (scale * X) + Y;\n\n  return;\n\n}\n\nint main()\n{\n\n  const size_t N = 50 * 1000 * 1000; // 50 M element vectors\n  const size_t TOTAL_BYTES = 4 * N * sizeof(float);\n  const size_t TOTAL_FLOPS = 2 * N;\n  const size_t num_run_times = 5;\n\n  printf(\"Number of repeats: %d\\n\", num_run_times);\n\n  size_t i;\n\n  float scale = 2.f;\n\n  arma::Col<float> arrayX(N);\n  arma::Col<float> arrayY(N);\n  arma::Col<float> result(N);\n\n  // initialize array values\n  for (i = 0; i < N; i++) {\n    arrayX(i) = i;\n    arrayY(i) = i;\n    result(i) = 0.f;\n  }\n\n  //\n  // Run the serial Armadillo implementation, call by value.\n  //\n  double min_arma_serial_cbv = 1e30;\n  for (i = 0; i < num_run_times; ++i) {\n    double startTime = CycleTimer::currentSeconds();\n    saxpy_arma_copy(scale, arrayX, arrayY, result);\n    double endTime = CycleTimer::currentSeconds();\n    min_arma_serial_cbv = std::min(min_arma_serial_cbv, endTime - startTime);\n  }\n\n  printf(\"[saxpy arma serial cbv]:\\t\\t[%.3f] ms\\t[%.3f] GB/s\\t[%.3f] GFLOPS\\n\",\n         min_arma_serial_cbv * 1000,\n         toBW(TOTAL_BYTES, min_arma_serial_cbv),\n         toGFLOPS(TOTAL_FLOPS, min_arma_serial_cbv));\n\n  // Clear out the buffer\n  for (i = 0; i < N; i++)\n    result(i) = 0.f;\n\n  //\n  // Run the serial Armadillo implementation, call by reference.\n  //\n  double min_arma_serial_cbr = 1e30;\n  for (i = 0; i < num_run_times; ++i) {\n    double startTime = CycleTimer::currentSeconds();\n    saxpy_arma_reference(scale, arrayX, arrayY, result);\n    double endTime = CycleTimer::currentSeconds();\n    min_arma_serial_cbr = std::min(min_arma_serial_cbr, endTime - startTime);\n  }\n\n  printf(\"[saxpy arma serial cbr]:\\t\\t[%.3f] ms\\t[%.3f] GB/s\\t[%.3f] GFLOPS\\n\",\n         min_arma_serial_cbr * 1000,\n         toBW(TOTAL_BYTES, min_arma_serial_cbr),\n         toGFLOPS(TOTAL_FLOPS, min_arma_serial_cbr));\n\n  // Clear out the buffer\n  for (i = 0; i < N; i++)\n    result(i) = 0.f;\n\n  return 0;\n\n}\n", "meta": {"hexsha": "9a69bad4f4978151a8178687f9a233aeaa5ba3b5", "size": 2415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_arma.cpp", "max_stars_repo_name": "berquist/gemm", "max_stars_repo_head_hexsha": "4eca3f6c4f20199b8d64d8cf78f926d79131f69f", "max_stars_repo_licenses": ["MIT"], "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_arma.cpp", "max_issues_repo_name": "berquist/gemm", "max_issues_repo_head_hexsha": "4eca3f6c4f20199b8d64d8cf78f926d79131f69f", "max_issues_repo_licenses": ["MIT"], "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_arma.cpp", "max_forks_repo_name": "berquist/gemm", "max_forks_repo_head_hexsha": "4eca3f6c4f20199b8d64d8cf78f926d79131f69f", "max_forks_repo_licenses": ["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.3939393939, "max_line_length": 79, "alphanum_fraction": 0.6020703934, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5068687407677057}}
{"text": "/*\n * X-Stream\n *\n * Copyright 2013 Operating Systems Laboratory EPFL\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 <cstdio>\n#include <boost/thread/thread.hpp>\n#include \"defs.h\"\n#include \"options.h\"\n#include \"util.h\"\n#include \"output.h\"\n#include \"prng/splittable_mrg.h\"\n#include \"prng/utils.h\"\n\ninline static vertex_t generate_vertex(mrg_state* pstate, const vertex_t nvertices)\n{\n  /* Generate a pseudorandom number in the range [0, vertices) without modulo bias. */\n  vertex_t limit = VT_MAX % nvertices;\n  vertex_t v;  \n\n  do {\n    v = mrg_get_uint_orig(pstate);\n#ifndef VERTEX_TYPE_32\n    v = (v << 32) + mrg_get_uint_orig(pstate);\n#endif\n  } while (UNLIKELY(v < limit));\n  return v % nvertices;\n}\n\nstatic void generate(thread_buffer* buffer, const mrg_state& state, const vertex_t nvertices, \n                     const edge_t start, const edge_t end, const bool allow_self_loops, const bool symmetric)\n{\n  for (edge_t ei = start; ei < end; ++ei)\n  {\n    mrg_state new_state = state;\n    mrg_skip(&new_state, 0, ei, 0);\n    struct edge_struct* edge = buffer->edge_struct();\n    edge->src = generate_vertex(&new_state, nvertices);\n    do {\n      edge->dst = generate_vertex(&new_state, nvertices);\n    } while (UNLIKELY(edge->src == edge->dst && !allow_self_loops));\n#ifdef WEIGHT\n    edge->weight = (value_t)mrg_get_double_orig(&new_state);\n#endif\n    if (symmetric) {\n      struct edge_struct* reverse_edge = buffer->edge_struct();\n      reverse_edge->src = edge->dst;\n      reverse_edge->dst = edge->src;\n#ifdef WEIGHT\n      reverse_edge->weight = edge->weight;\n#endif\n    }\n  }\n  buffer->flush();\n}\n\nstatic void generate_bipartite(thread_buffer* buffer, const mrg_state& state, const vertex_t nleft, const vertex_t nvertices,\n                               const edge_t start, const edge_t end, const bool symmetric)\n{\n  for (edge_t ei = start; ei < end; ++ei)\n  {\n    mrg_state new_state = state;\n    mrg_skip(&new_state, 0, ei, 0);\n    struct edge_struct* edge = buffer->edge_struct();\n    edge->src = generate_vertex(&new_state, nvertices);\n    if (edge->src < nleft) {\n      edge->dst = nleft + generate_vertex(&new_state, nvertices - nleft);\n    } else {\n      edge->dst = generate_vertex(&new_state, nleft);\n    }\n#ifdef WEIGHT\n    edge->weight = (value_t)mrg_get_double_orig(&new_state);\n#endif\n    if (symmetric) {\n      struct edge_struct* reverse_edge = buffer->edge_struct();\n      reverse_edge->src = edge->dst;\n      reverse_edge->dst = edge->src;\n#ifdef WEIGHT\n      reverse_edge->weight = edge->weight;\n#endif\n    }\n  }\n  buffer->flush();\n}\n\nint main(int argc, char** argv)\n{\n  struct options options;\n  if (process_options(argc, argv, false, &options) != 0)\n    return 0;\n\n  uint_fast32_t seed[5];\n  make_mrg_seed(options.rng.userseed1, options.rng.userseed2, seed);\n  mrg_state state;\n  mrg_seed(&state, seed);\n  //mrg_skip(&new_state, 50, 7, 0); // Do an initial skip?\n\n  edge_t total_edges = options.erdos_renyi.edges;\n  if (options.global.symmetric) {\n    total_edges *= 2;\n  }\n\n  printf(\"Generator type: Erdos-Renyi\\n\");\n  printf(\"Vertices: %\" PRIvt \"\\n\", options.erdos_renyi.vertices);\n  printf(\"Edges: %\" PRIet \"\\n\", total_edges);\n  printf(\"Self-loops:%s allowed\\n\", (options.erdos_renyi.self_loops ? \"\" : \" not\"));\n\n  double start = get_time();\n\n  // io thread\n  size_t buffer_size = calculate_buffer_size(options.global.buffer_size);\n  buffer_queue flushq;\n  buffer_manager manager(&flushq, options.global.buffers_per_thread, buffer_size);\n  io_thread_func io_func(options.global.graphname.c_str(), total_edges, &flushq, &manager, buffer_size);\n  boost::thread io_thread(boost::ref(io_func));\n\n  // worker threads\n  int nthreads = options.global.nthreads;\n  edge_t edges_per_thread = options.erdos_renyi.edges / nthreads;\n  threadid_t* workers[nthreads];\n  boost::thread* worker_threads[nthreads];\n  for (int i = 0; i < nthreads; i++) {\n    workers[i] = new threadid_t(i);\n    thread_buffer* buffer = manager.register_thread(*workers[i]);\n    // last thread gets the remainder (if any)\n    edge_t start = i * edges_per_thread;\n    edge_t end = (i == nthreads-1) ? (options.erdos_renyi.edges) : ((i+1) * edges_per_thread);\n    if (options.erdos_renyi.bipartite) {\n      worker_threads[i] = new boost::thread(\n        generate_bipartite, buffer,\n        state, options.erdos_renyi.bipartite, options.erdos_renyi.vertices, start, end, options.global.symmetric\n      );\n    } else {\n      worker_threads[i] = new boost::thread(\n        generate, buffer,\n        state, options.erdos_renyi.vertices, start, end, options.erdos_renyi.self_loops, options.global.symmetric\n      );\n    }\n  }\n\n  // Wait until work completes\n  for (int i = 0; i < nthreads; i++) {\n    worker_threads[i]->join();\n  }\n  io_func.stop();\n  io_thread.join();\n\n  // cleanup\n  for (int i = 0; i < nthreads; i++) {\n    manager.unregister_thread(*workers[i]);\n    delete worker_threads[i];\n    delete workers[i];\n  }\n\n  double elapsed = get_time() - start;  \n  printf(\"Generation time: %fs\\n\", elapsed);\n\n  make_ini_file(options.global.graphname.c_str(), options.erdos_renyi.vertices, total_edges);\n\n  return 0;\n}\n\n", "meta": {"hexsha": "cf317f2b5fc68a70d63a9b94c2b171606a8cc96d", "size": 5636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "generators/random.cpp", "max_stars_repo_name": "AftabHussain/x-stream", "max_stars_repo_head_hexsha": "01fb3ff0703d18c23047d3c80f68b26f14b2b4fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2015-11-06T02:01:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T01:51:00.000Z", "max_issues_repo_path": "generators/random.cpp", "max_issues_repo_name": "pgplus1628/x-stream", "max_issues_repo_head_hexsha": "132c346fb6b6da352dbcf8ba4b60c81b1216fa81", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-07-13T13:05:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-23T17:45:05.000Z", "max_forks_repo_path": "generators/random.cpp", "max_forks_repo_name": "pgplus1628/x-stream", "max_forks_repo_head_hexsha": "132c346fb6b6da352dbcf8ba4b60c81b1216fa81", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:41:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-27T07:29:43.000Z", "avg_line_length": 32.0227272727, "max_line_length": 125, "alphanum_fraction": 0.6823988644, "num_tokens": 1515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5068587225836942}}
{"text": "#ifndef CPU_LR_HOG_DETECTOR_H\n#define CPU_LR_HOG_DETECTOR_H\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core.hpp>\n#include <opencv2/ximgproc/segmentation.hpp>\n#include <iostream>\n#include <random>\n#include <chrono>\n#include <string>\n#include \"../utils/c_utils.hpp\"\n#include \"../libs/nms/nms.hpp\"\n#include \"../dpp/dpp.hpp\"\n#include \"../likelihood/logistic_regression.hpp\"\n#include \"../likelihood/CPU_logistic_regression.hpp\"\n#include \"../libs/piotr_fhog/fhog.hpp\"\n\n\nstruct Args {\n\tbool make_gray;\n    bool resize_src;\n    int hog_width;\n    int hog_height;\n    double gr_threshold;\n    double hit_threshold;\n    int n_orients;\n    int bin_size;\n    double overlap_threshold;\n    double p_accept;\n    double lambda;\n    double epsilon;\n    double tolerance;\n    int n_iterations;\n} ;\n\nusing namespace cv;\nusing namespace std;\nusing namespace Eigen;\nusing namespace cv::ximgproc::segmentation;\nclass CPU_LR_HOGDetector \n{\npublic:\n\tvoid init(double group_threshold, double hit_threshold);\n\tvector<Rect> detect(Mat &frame);\n\tdouble train();\n\tVectorXd getFeatures(Mat &frame);\n    vector<double> getWeights();\n\tvoid generateFeatures(Mat &frame, double label);\n\tvoid dataClean();\n\tvoid draw();\n\tvoid saveToCSV(string name, bool append = true);\n\tvoid loadModel(VectorXd weights,VectorXd featureMean, VectorXd featureStd, VectorXd featureMax, VectorXd featureMin, double bias);\n\tvoid loadFeatures(MatrixXd features, VectorXd labels);\n\tVectorXd predictTest(MatrixXd features,bool data_processing);\n\tMatrixXd feature_values;\n\tvector<double> weights;\n\nprotected:\n\tArgs args;\n\tVectorXd genHog(Mat &frame);\n\tVectorXd genRawPixels(Mat &frame);\n\tHOGDescriptor hog;\n\tCPU_LogisticRegression logistic_regression;\n\tint num_frame=0;\n\tdouble max_value=1.0;\n\tint group_threshold;\n\tdouble hit_threshold;\n\tint n_descriptors, n_data;\n\tvector<Rect> detections;\n\tVectorXd labels;\n\tMat frame;\n\tC_utils tools;\n\tmt19937 generator;\n\tbool initialized;\n\n};\n\n#endif\n", "meta": {"hexsha": "7ccded2b22de4181061d271d74611fe98c20f400", "size": 2045, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/detectors/CPU_LR_hog_detector.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/detectors/CPU_LR_hog_detector.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/detectors/CPU_LR_hog_detector.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": 24.9390243902, "max_line_length": 131, "alphanum_fraction": 0.760391198, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5068587116179832}}
{"text": "#include <math.h>\n#include <limits>\n\n#include <ros/ros.h>\n#include <sensor_msgs/Image.h>\n#include <cv_bridge/cv_bridge.h>\n\n#include <boost/lexical_cast.hpp>\n\n#include <opencv2/plot.hpp>\n\n#include <miniking_ros/AcousticBeam.h>\n#include <collision_avoidance/ObstacleInfo.h>\n\n\nclass SonarObstacleDetector\n{\n  ros::NodeHandle nh_;\n  ros::NodeHandle nh_private_;\n\n  ros::Subscriber acousticbeam_sub_;\n  ros::Publisher  pub_obstacle_info_;\n  ros::Publisher  intensities_pub_;\n  ros::Publisher  peakdetector_pub_;\n\n  // Operational parameters\n  double min_range_;\n  double max_range_;\n  double min_obstacle_size_;\n\npublic:\n  SonarObstacleDetector() : nh_private_(\"~\")\n  {\n    // Params\n    nh_private_.param(\"min_range\", min_range_, 2.0);\n    nh_private_.param(\"min_obstacle_size\", min_obstacle_size_, 0.06);\n\n    // Topics\n    acousticbeam_sub_   = nh_.subscribe(\"/sonar\", 1, &SonarObstacleDetector::acousticbeamCb, this);\n    pub_obstacle_info_  = nh_private_.advertise<collision_avoidance::ObstacleInfo>(\"obstacle_info\", 2, true);\n    intensities_pub_    = nh_private_.advertise<sensor_msgs::Image>(\"intensities\", 2, true);\n    peakdetector_pub_   = nh_private_.advertise<sensor_msgs::Image>(\"peak_detector\", 2, true);\n  }\n\n  void acousticbeamCb(const miniking_ros::AcousticBeamConstPtr beam)\n  {\n    // Copy and convert\n    std::vector<double> intensities;\n    std::vector<unsigned char> input_intensities(beam->intensities);\n    for (size_t i=0; i<input_intensities.size(); i++)\n    {\n      int tmp = (int)input_intensities[i];\n      intensities.push_back(boost::lexical_cast<double>(tmp));\n    }\n\n    // Remove intensities in the minimum range\n    max_range_ = beam->range_max;\n    float distance_btw_bins = max_range_/beam->bins;\n    int N = round(min_range_/distance_btw_bins);\n    intensities.erase(intensities.begin(), intensities.begin() + N);\n\n    // Create the ranges vector\n    std::vector<double> ranges;\n    for (double r=min_range_; r<=max_range_; r=r+distance_btw_bins)\n      ranges.push_back(r);\n\n    // Low pass filter\n    std::vector<double> filtered_intensities = lowPassFilter(intensities);\n\n    // Publish debugging images\n    if (intensities_pub_.getNumSubscribers() > 0)\n    {\n      cv::Mat original = drawGraph(ranges, intensities, cv::Scalar(50, 50, 255));\n      cv::Mat filtered = drawGraph(ranges, filtered_intensities, cv::Scalar(50, 255, 50));\n\n      // Combine 2 images\n      cv::Mat combined;\n      double alpha = 0.5;\n      double beta = ( 1.0 - alpha );\n      cv::addWeighted( original, alpha, filtered, beta, 0.0, combined);\n\n      // Publish\n      cv_bridge::CvImage ros_image;\n      ros_image.image = combined.clone();\n      ros_image.header.stamp = ros::Time::now();\n      ros_image.encoding = \"bgr8\";\n      intensities_pub_.publish(ros_image.toImageMsg());\n    }\n\n    if (peakdetector_pub_.getNumSubscribers() > 0)\n    {\n      cv::Mat combined = drawGraph(ranges, filtered_intensities, cv::Scalar(50, 255, 50));\n\n      // Calc peaks\n      std::vector<double> x_peak, y_peak;\n      peakDetector(ranges, filtered_intensities, x_peak, y_peak);\n      for (size_t i=0; i<x_peak.size(); i++)\n      {\n        // Convert point to image coordinates\n        double u = (x_peak[i] - min_range_) * combined.cols / (max_range_ - min_range_); //combined.cols * x_peak[i] / (max_range_-min_range_);\n        double v = combined.rows * (100.0-y_peak[i]) / 100;\n        cv::Point2d p(u,v);\n        cv::circle(combined, p, 5, cv::Scalar(50, 255, 50));\n      }\n\n      // Publish\n      cv_bridge::CvImage ros_image;\n      ros_image.image = combined.clone();\n      ros_image.header.stamp = ros::Time::now();\n      ros_image.encoding = \"bgr8\";\n      peakdetector_pub_.publish(ros_image.toImageMsg());\n    }\n\n  }\n\n  std::vector<double> lowPassFilter(const std::vector<double>& input,\n                                    const int& order = 10)\n  {\n\n    // Get the maximum\n    double max_in = *std::max_element(input.begin(), input.end());\n\n    std::vector<double> output;\n    for (size_t n=0; n<input.size(); n++)\n    {\n      size_t idx = n;\n      double sum = 0.0;\n      for (size_t k=0; k<order; k++)\n      {\n        if (idx < 0) break;\n        sum += 0.01 * input[idx];\n        idx--;\n      }\n      output.push_back(sum);\n    }\n\n    // Preserve scale\n    double max_out = *std::max_element(output.begin(), output.end());\n    double gain = max_in / max_out;\n    for (size_t i=0; i<output.size(); i++)\n      output[i] = output[i] * gain;\n\n    return output;\n  }\n\n  void peakDetector(const std::vector<double>& x,\n                    const std::vector<double>& y,\n                    std::vector<double>& x_peak,\n                    std::vector<double>& y_peak,\n                    const double& delta = 0.1)\n  {\n    x_peak.clear();\n    y_peak.clear();\n\n    double mn = std::numeric_limits<double>::max();\n    double mx = std::numeric_limits<double>::min();\n    double mxpos = std::numeric_limits<double>::quiet_NaN();\n    double mnpos = std::numeric_limits<double>::quiet_NaN();\n    bool lookformax = true;\n\n    for (size_t i=0; i<y.size(); i++)\n    {\n      if (y[i] > mx)\n      {\n        mx = y[i];\n        mxpos = x[i];\n      }\n      if (y[i] < mn)\n      {\n        mn = y[i];\n        mnpos = x[i];\n      }\n\n      if (lookformax)\n      {\n        if (y[i] < mx-delta)\n        {\n          x_peak.push_back(mxpos);\n          y_peak.push_back(mx);\n          mn = y[i];\n          mnpos = x[i];\n          lookformax = false;\n        }\n      }\n      else\n      {\n        if (y[i] > mn+delta)\n        {\n          mx = y[i];\n          mxpos = x[i];\n          lookformax = true;\n        }\n      }\n    }\n  }\n\n  cv::Mat drawGraph(const std::vector<double>& x,\n                    const std::vector<double>& y,\n                    const cv::Scalar& line_color,\n                    const int& line_width = 2)\n  {\n    // Convert to cv::Mat\n    cv::Mat x_data( x.size(), 1, CV_64F );\n    cv::Mat y_data( y.size(), 1, CV_64F );\n    for (size_t i=0; i<x.size(); i++)\n      x_data.at<double>(i,0) = x[i];\n    for (size_t i=0; i<y.size(); i++)\n      y_data.at<double>(i,0) = y[i];\n\n    // Draw\n    cv::Mat tmp, plot_result;\n    cv::Ptr<cv::plot::Plot2d> plot = cv::plot::createPlot2d(x_data, y_data);\n    plot->setMaxX(max_range_);\n    plot->setMinX(min_range_);\n    plot->setMaxY(100);\n    plot->setMinY(0);\n    plot->setPlotTextColor(cv::Scalar(50, 50, 50));\n    plot->setPlotBackgroundColor(cv::Scalar(50, 50, 50));\n    plot->setPlotLineColor(line_color);\n    plot->setPlotLineWidth(line_width);\n    plot->render(tmp);\n    cv::flip(tmp, plot_result, 0);\n    return plot_result;\n  }\n\n};\n\nint main(int argc, char** argv)\n{\n  ros::init(argc, argv, \"sonar_obstacle_detector\");\n  SonarObstacleDetector node;\n  ros::spin();\n  return 0;\n}\n\n", "meta": {"hexsha": "87c813e56a12114bef10dbff4a9e3d5367f4e60f", "size": 6727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sonar_obstacle_detector.cpp", "max_stars_repo_name": "srv/collision_avoidance", "max_stars_repo_head_hexsha": "70b109154decfa9dd1a30cf77aad69a4dadb3671", "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/sonar_obstacle_detector.cpp", "max_issues_repo_name": "srv/collision_avoidance", "max_issues_repo_head_hexsha": "70b109154decfa9dd1a30cf77aad69a4dadb3671", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sonar_obstacle_detector.cpp", "max_forks_repo_name": "srv/collision_avoidance", "max_forks_repo_head_hexsha": "70b109154decfa9dd1a30cf77aad69a4dadb3671", "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.5042372881, "max_line_length": 143, "alphanum_fraction": 0.6038352906, "num_tokens": 1869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5068587061351277}}
{"text": "#include \"math/util/modular-x86.h\"\n#include \"math/util/prime.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\nBOOST_AUTO_TEST_SUITE( modular_x86 )\n\ntypedef boost::mpl::list<\n        uint32_t\n#ifdef __LP64__\n        ,uint64_t\n#endif\n    > UIntTypes;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( mul_add_test, U, UIntTypes ) {\n  U a = math::ModOp<U>::add(2,4,5);\n  BOOST_CHECK_EQUAL( a, 1 );\n\n  U p = math::Prime<U>::A;\n\n  U x = math::ModOp<U>::add(p-2,p-3,p);\n  BOOST_CHECK_EQUAL( x, p-5 );\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( sub_mod_test, U, UIntTypes ) {\n  U a = math::ModOp<U>::sub(2,3,5);\n  BOOST_CHECK_EQUAL( a, 4 );\n\n  U p = math::Prime<U>::A;\n\n  U x = math::ModOp<U>::sub(p-2,p-3,p);\n  BOOST_CHECK_EQUAL( x, 1 );\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( mul_mod_test, U, UIntTypes ) {\n  U a = math::ModOp<U>::mul(2,3,5);\n  BOOST_CHECK_EQUAL( a, 1 );\n\n  U p = math::Prime<U>::A;\n\n  U x = math::ModOp<U>::mul(p-2,p-3,p);\n  BOOST_CHECK_EQUAL( x, 6 );\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( mul_add_mod_test, U, UIntTypes ) {\n  U a = math::ModOp<U>::mul_add(2,3,4,5);\n  BOOST_CHECK_EQUAL( a, 0 );\n\n  U p = math::Prime<U>::A;\n\n  U x = math::ModOp<U>::mul_add(p-2,p-3,p-6,p);\n  BOOST_CHECK_EQUAL( x, 0 );\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( sub_mul_mod_test, U, UIntTypes ) {\n  U a = math::ModOp<U>::sub_mul(2,3,4,5);\n  BOOST_CHECK_EQUAL( a, 1 );\n\n  U p = math::Prime<U>::A;\n\n  U x = math::ModOp<U>::sub_mul(p-2,p-4,(p-1)/2,p);\n  BOOST_CHECK_EQUAL( x, p-1 );\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( pow_mod_test, U, UIntTypes ) {\n  U a = math::ModOp<U>::pow(2,3,5);\n  BOOST_CHECK_EQUAL( a, 3 );\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( sqrt_mod_test, U, UIntTypes) {\n   U a = math::ModOp<U>::sqrt(1,5);\n   BOOST_CHECK_EQUAL( a, 1 );\n\n   U p = math::Prime<U>::A;\n   U x = math::ModOp<U>::sqrt(p-1,p);\n   U y = math::ModOp<U>::mul(x,x,p);\n   BOOST_CHECK_EQUAL( y, p-1 );\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( multi_mod_test, U, UIntTypes ) {\n  U primes[] = //{ math::Prime<U>::A, math::Prime<U>::B };\n  { 3, 5, 7, 11 };\n  const size_t N = sizeof(primes)/sizeof(*primes);\n\n  U mixMuls[N];\n  math::MultiMod<U>::mixedMults(mixMuls, primes, N);\n  BOOST_CHECK_EQUAL(mixMuls[0], 1);\n  BOOST_CHECK_EQUAL(mixMuls[1], 2); // 3*2 mod 5 == 1\n  BOOST_CHECK_EQUAL(mixMuls[2], 1); // (3*5) * 1 mod 7 == 1\n  BOOST_CHECK_EQUAL(mixMuls[3], 2); // (3*5*7) * 2 mod 11 == 1\n\n  math::MultiMod<U> crt(primes, N);\n\n  U rads[N];\n  U crts[N] = {1, 1, 1, 1};\n  crt.crtToMixedRadix(rads, crts);\n  BOOST_CHECK_EQUAL(rads[0], 1);\n  BOOST_CHECK_EQUAL(rads[1], 0);\n  BOOST_CHECK_EQUAL(rads[2], 0);\n  BOOST_CHECK_EQUAL(rads[3], 0);\n\n  BOOST_CHECK_EQUAL(false, crt.mixedRadixIsNegative(rads));\n\n  char buf[20];\n  int len = crt.mixedRadixToString(buf,sizeof(buf),rads,10);\n  BOOST_CHECK_EQUAL(len, 1);\n  BOOST_CHECK_EQUAL(buf[0], '1');\n  BOOST_CHECK_EQUAL(buf[1], '\\0');\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\nbool init_unit_test() {\n  return true;\n}\n", "meta": {"hexsha": "6a268cc3ed008db06dce72387743128a43726c1f", "size": 2891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/modular-x86.t.cpp", "max_stars_repo_name": "cherba29/slp-poly", "max_stars_repo_head_hexsha": "0812e433c19c3ae036610c50ce54bf2d8cb8bf93", "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/math/modular-x86.t.cpp", "max_issues_repo_name": "cherba29/slp-poly", "max_issues_repo_head_hexsha": "0812e433c19c3ae036610c50ce54bf2d8cb8bf93", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/modular-x86.t.cpp", "max_forks_repo_name": "cherba29/slp-poly", "max_forks_repo_head_hexsha": "0812e433c19c3ae036610c50ce54bf2d8cb8bf93", "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.5040650407, "max_line_length": 65, "alphanum_fraction": 0.6388792805, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5068587054445828}}
{"text": "#ifndef RICPAD_DIFFERENTIATE\n#define RICPAD_DIFFERENTIATE\n\n#include <Eigen/Dense>\n\nnamespace solver {\n\ntemplate <typename T, int N>\nT differentiate(\n        // A function which takes an Eigen Matrix\n        const std::function<T(Eigen::Matrix<T,N,1>&)>& f,\n        // The variables contained in an Eigen matrix\n        const Eigen::Matrix<T, N, 1>& x,\n        // With respect to which variable we differentiate\n        const int k,\n        // Step size\n        const T& h\n      )\n{\n    Eigen::Matrix<T, N, 1> xp(x), xm(x);\n\n    xp(k) += h;\n    xm(k) -= h;\n\n    T ans = f(xp) - f(xm);\n    ans /= (h*T(2));\n\n    return ans;\n};\n\n}; // namespace differentiate\n#endif\n", "meta": {"hexsha": "856d5b36cfdcaa52308f78c8be443b567bd4d02c", "size": 663, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/differentiate.hpp", "max_stars_repo_name": "javierelpianista/solver", "max_stars_repo_head_hexsha": "85dd0757ffeec73620f5c69701ce9be51df70ab1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/include/differentiate.hpp", "max_issues_repo_name": "javierelpianista/solver", "max_issues_repo_head_hexsha": "85dd0757ffeec73620f5c69701ce9be51df70ab1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/differentiate.hpp", "max_forks_repo_name": "javierelpianista/solver", "max_forks_repo_head_hexsha": "85dd0757ffeec73620f5c69701ce9be51df70ab1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0909090909, "max_line_length": 58, "alphanum_fraction": 0.5791855204, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5068586944788718}}
{"text": "#include <mex.h>\n#include <Eigen/Core>\n#include \"splineGeneration.h\"\n#include \"drakeUtil.h\"\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) {\n  string usage = \"[coefs, objval] = twoWaypointCubicSplinemex(ts, xs, xd0, xdf)\";\n  if (nrhs != 4)\n    mexErrMsgIdAndTxt(\"Drake:twoWaypointCubicSplinemex:WrongNumberOfInputs\", usage.c_str());\n  if (nlhs > 2)\n    mexErrMsgIdAndTxt(\"Drake:twoWaypointCubicSplinemex:WrongNumberOfOutputs\", usage.c_str());\n\n  const std::vector<double> segment_times = matlabToStdVector(prhs[0]);\n  MatrixXd xs = matlabToEigen<Dynamic, Dynamic>(prhs[1]);\n  auto xd0 = matlabToEigen<Dynamic, 1>(prhs[2]);\n  auto xdf = matlabToEigen<Dynamic, 1>(prhs[3]);\n\n  mwSize ndof = static_cast<mwSize>(xs.rows());\n  mwSize num_segments = 3;\n  mwSize num_coeffs_per_segment = 4;\n  mwSize dims[] = {ndof, num_segments, num_coeffs_per_segment};\n  plhs[0] = mxCreateNumericArray(num_segments, dims, mxDOUBLE_CLASS, mxREAL);\n  double objective_value = 0.0;\n  for (mwSize dof = 0; dof < ndof; dof++) {\n    PiecewisePolynomial<double> spline = twoWaypointCubicSpline(segment_times, xs(dof, 0), xd0[dof], xs(dof, 3), xdf[dof], xs(dof, 1), xs(dof, 2));\n\n    PiecewisePolynomial<double> acceleration_squared = spline.derivative(2);\n    acceleration_squared *= acceleration_squared;\n    PiecewisePolynomial<double> acceleration_squared_integral = acceleration_squared.integral();\n    objective_value += acceleration_squared_integral.value(spline.getEndTime()) - acceleration_squared_integral.value(spline.getStartTime());\n\n    for (mwSize segment_index = 0; segment_index < spline.getNumberOfSegments(); segment_index++) {\n      for (mwSize coefficient_index = 0; coefficient_index < num_coeffs_per_segment; coefficient_index++) {\n        mwSize sub[] = {dof, segment_index, num_coeffs_per_segment - coefficient_index - 1}; // Matlab's reverse coefficient indexing...\n        *(mxGetPr(plhs[0]) + sub2ind(3, dims, sub)) = spline.getPolynomial(segment_index).getCoefficients()[coefficient_index];\n      }\n    }\n  }\n\n  if (nlhs > 1) {\n    plhs[1] = mxCreateDoubleScalar(objective_value);\n  }\n}\n", "meta": {"hexsha": "6ec632e5d35fa951f092829dd55f4576f8ef1b22", "size": 2183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solvers/qpSpline/twoWaypointCubicSplinemex.cpp", "max_stars_repo_name": "jacob-izr/drake", "max_stars_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "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": "solvers/qpSpline/twoWaypointCubicSplinemex.cpp", "max_issues_repo_name": "jacob-izr/drake", "max_issues_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/qpSpline/twoWaypointCubicSplinemex.cpp", "max_forks_repo_name": "jacob-izr/drake", "max_forks_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "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": 45.4791666667, "max_line_length": 147, "alphanum_fraction": 0.7301878149, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5068586944788717}}
{"text": "#include \"mex.h\"\n#include <Eigen/Dense>\n#include \"../radialpose.h\"\n\nvoid print_usage() {\n\tmexPrintf(\"[R,t,f,params] = radialpose_mex(x,X,solver,[upgrade_only]);\\n\");\n\tmexPrintf(\" Solvers:\\n\");\n\tmexPrintf(\"  1 - D(1,0) - 5p -- Larsson et al.  ICCV 2019\\n\");\n\tmexPrintf(\"  2 - D(2,0) - 5p -- Larsson et al.  ICCV 2019\\n\");\n\tmexPrintf(\"  3 - D(3,0) - 5p -- Larsson et al.  ICCV 2019  (Minimal)\\n\");\n\tmexPrintf(\"  4 - D(3,3) - 8p -- Larsson et al.  ICCV 2019\\n\");\n\tmexPrintf(\"  5 - U(1,0) - 5p -- Larsson et al.  ICCV 2019\\n\");\n\tmexPrintf(\"  6 - U(0,1) - 4p -- Larsson et al.  ICCV 2017  (Minimal, Non-planar)\\n\");\n\tmexPrintf(\"  7 - U(0,1) - 4p -- Bujnak et al.   ACCV 2010  (Minimal, Non-planar)\\n\");\n\tmexPrintf(\"  8 - U(0,1) - 5p -- Kukelova et al. ICCV 2013\\n\");\n\tmexPrintf(\"  9 - U(0,2) - 5p -- Kukelova et al. ICCV 2013\\n\");\n\tmexPrintf(\" 10 - U(0,3) - 5p -- Kukelova et al. ICCV 2013  (Minimal)\\n\");\n\tmexPrintf(\" 11 - U(0,1) - 4p -- Oskarsson       arxiv 2018 (Minimal, Planar)\\n\");\n\tmexPrintf(\" 12 - N/A    - 5p -- Kukelova et al. ICCV 2013  (Minimal, 1D Radial)\\n\\n\");\n\tmexPrintf(\"If upgrade_only=true we don't solve for the 1D radial camera and only try to upgrade.\\n This is only for the two-step solvers.\\n\");\n}\n\nvoid save_poses(int nlhs, mxArray *plhs[], std::vector<radialpose::Camera> &poses) {\n\tint n_sols = poses.size();\n\tint n_params = 0;\n\tif (n_sols > 0)\n\t\tn_params = poses[0].dist_params.size();\n\n\tif (nlhs >= 1) {\n\t\tplhs[0] = mxCreateDoubleMatrix(9, n_sols, mxREAL);\n\t\tdouble *p = mxGetPr(plhs[0]);\n\t\tfor (int i = 0; i < n_sols; ++i)\n\t\t\tfor (int j = 0; j < 9; ++j)\n\t\t\t\tp[9 * i + j] = poses[i].R(j);\n\t}\n\tif (nlhs >= 2) {\n\t\tplhs[1] = mxCreateDoubleMatrix(3, n_sols, mxREAL);\n\t\tdouble *p = mxGetPr(plhs[1]);\n\t\tfor (int i = 0; i < n_sols; ++i)\n\t\t\tfor (int j = 0; j < 3; ++j)\n\t\t\t\tp[3 * i + j] = poses[i].t(j);\n\t}\n\tif (nlhs >= 3) {\n\t\tplhs[2] = mxCreateDoubleMatrix(1, n_sols, mxREAL);\n\t\tdouble *p = mxGetPr(plhs[2]);\n\t\tfor (int i = 0; i < n_sols; ++i)\n\t\t\tp[i] = poses[i].focal;\n\n\t}\n\tif (nlhs >= 4) {\n\t\tplhs[3] = mxCreateDoubleMatrix(n_params, n_sols, mxREAL);\n\t\tdouble *p = mxGetPr(plhs[3]);\n\t\tfor (int i = 0; i < n_sols; ++i)\n\t\t\tfor (int j = 0; j < n_params; ++j)\n\t\t\t\tp[n_params * i + j] = poses[i].dist_params[j];\n\t}\n}\n\nvoid mexFunction(int nlhs,mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n\tif (nrhs < 3 || nrhs > 5) {\n\t\tprint_usage();\n\t\tmexErrMsgTxt(\"Incorrect number of input arguments.\");\n\t}\n\tif (nlhs > 4) {\n\t\tprint_usage();\n\t\tmexErrMsgTxt(\"Wrong number of output arguments.\");\n\t}\n\t\n\tif (mxGetM(prhs[0]) != 2) {\n\t\tprint_usage();\n\t\tmexErrMsgTxt(\"First input must be 2 x N matrix.\");\n\t}\n\tif (mxGetM(prhs[1]) != 3) {\n\t\tprint_usage();\n\t\tmexErrMsgTxt(\"Second input must be 3 x N matrix.\");\n\t}\n\tif (mxGetN(prhs[0]) != mxGetN(prhs[1])) {\n\t\tprint_usage();\n\t\tmexErrMsgTxt(\"Not the same number of 2D points and 3D points.\");\n\t}\n\n\tbool use_radial_solver = true;\n\tif (nrhs >= 4 && mxGetScalar(prhs[3]) != 0.0) {\n\t\tuse_radial_solver = false;\n\t}\n\n\tdouble damp_factor = 0.0;\n\tif (nrhs >= 5) {\n\t\tdamp_factor = mxGetScalar(prhs[4]);\n\t}\n\n\n\t// If we don't call the radial solver we don't normalize world coord system\n\tbool center_world_coordinates = use_radial_solver;\t\n\n\tEigen::Matrix<double, 2, Eigen::Dynamic> x = Eigen::Map<Eigen::Matrix<double, 2, Eigen::Dynamic>>(mxGetPr(prhs[0]), 2, mxGetN(prhs[0]));\n\tEigen::Matrix<double, 3, Eigen::Dynamic> X = Eigen::Map<Eigen::Matrix<double, 3, Eigen::Dynamic>>(mxGetPr(prhs[1]), 3, mxGetN(prhs[1]));\n\n\tif(x.cols() > 8) {\n\t\t// This is to avoid crash when solver is called with more than 8 points\n\t\tx = x.block(0,0,2,8).eval();\n\t\tX = X.block(0,0,3,8).eval();\n\t}\n\n\tint solver_idx = static_cast<int>(mxGetScalar(prhs[2]));\n\n\tstd::vector<radialpose::Camera> poses;\n\n\tif (solver_idx == 1) { // D(1,0)\n\t\tradialpose::larsson_iccv19::Solver<1, 0, true> estimator;\n\t\testimator.use_radial_solver = use_radial_solver;\n\t\testimator.center_world_coord = center_world_coordinates;\n\t\testimator.damp_factor = damp_factor;\n\t\testimator.estimate(x, X, &poses);\n\t\tsave_poses(nlhs, plhs, poses);\n\n\t} else if (solver_idx == 2) { // D(2,0)\n\t\tradialpose::larsson_iccv19::Solver<2, 0, true> estimator;\n\t\testimator.use_radial_solver = use_radial_solver;\n\t\testimator.center_world_coord = center_world_coordinates;\n\t\testimator.damp_factor = damp_factor;\n\t\testimator.estimate(x, X, &poses);\n\t\tsave_poses(nlhs, plhs, poses);\n\n\t} else if (solver_idx == 3) { // D(3,0)\n\t\tradialpose::larsson_iccv19::Solver<3, 0, true> estimator;\n\t\testimator.use_radial_solver = use_radial_solver;\n\t\testimator.center_world_coord = center_world_coordinates;\n\t\testimator.damp_factor = damp_factor;\n\t\testimator.estimate(x, X, &poses);\n\t\tsave_poses(nlhs, plhs, poses);\n\n\t} else if (solver_idx == 4) { // D(3,3)\n\t\tradialpose::larsson_iccv19::Solver<3, 3, true> estimator;\n\t\testimator.use_radial_solver = use_radial_solver;\n\t\testimator.center_world_coord = center_world_coordinates;\n\t\testimator.damp_factor = damp_factor;\t\t\n\t\testimator.estimate(x, X, &poses);\n\t\tsave_poses(nlhs, plhs, poses);\n\n\t} else if (solver_idx == 5) { // U(1,0)\n\t\tradialpose::larsson_iccv19::Solver<1, 0, false> estimator;\n\t\testimator.use_radial_solver = use_radial_solver;\n\t\testimator.center_world_coord = center_world_coordinates;\n\t\testimator.damp_factor = damp_factor;\n\t\testimator.estimate(x, X, &poses);\n\t\tsave_poses(nlhs, plhs, poses);\n\n\t} else if (solver_idx == 6) { // U(0,1)\n\t\tradialpose::larsson_iccv17::NonPlanarSolver estimator;\n\t\testimator.estimate(x, X, &poses);\n\t\tsave_poses(nlhs, plhs, poses);\n\n\t} else if (solver_idx == 7) {  // U(0,1)\n\t\tradialpose::bujnak_accv10::NonPlanarSolver estimator;\n\t\testimator.estimate(x, X, &poses);\n\t\tsave_poses(nlhs, plhs, poses);\n\n\t} else if (solver_idx == 8) {  // U(0,1)\n\t\tradialpose::kukelova_iccv13::Solver estimator(1);\n\t\testimator.use_radial_solver = use_radial_solver;\n\t\testimator.center_world_coord = center_world_coordinates;\n\t\testimator.estimate(x, X, &poses);\n\t\tsave_poses(nlhs, plhs, poses);\n\n\t} else if (solver_idx == 9) {  // U(0,2)\n\t\tradialpose::kukelova_iccv13::Solver estimator(2);\n\t\testimator.use_radial_solver = use_radial_solver;\n\t\testimator.center_world_coord = center_world_coordinates;\n\t\testimator.estimate(x, X, &poses);\n\t\tsave_poses(nlhs, plhs, poses);\n\n\t} else if (solver_idx == 10) { // U(0,3)\n\t\tradialpose::kukelova_iccv13::Solver estimator(3);\n\t\testimator.use_radial_solver = use_radial_solver;\n\t\testimator.center_world_coord = center_world_coordinates;\n\t\testimator.estimate(x, X, &poses);\n\t\tsave_poses(nlhs, plhs, poses);\n\n\t} else if (solver_idx == 11) {  // U(0,1)\n\t\tradialpose::oskarsson_arxiv18::PlanarSolver estimator;\n\t\testimator.estimate(x, X, &poses);\n\t\tsave_poses(nlhs, plhs, poses);\n\n\t} else if (solver_idx == 12) {  // N/A\n\t\tradialpose::kukelova_iccv13::Radial1DSolver estimator;\n\t\testimator.estimate(x, X, &poses);\n\t\tsave_poses(nlhs, plhs, poses);\n\n\t} else {\n\t\tprint_usage();\n\t\tmexErrMsgTxt(\"Solver NYI.\\n\");\n\t}\n}\n", "meta": {"hexsha": "39f1766bac244b435f05570fd4e039b6973f2988", "size": 6869, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab/radialpose_mex.cpp", "max_stars_repo_name": "vlarsson/radialpose", "max_stars_repo_head_hexsha": "e620fc208f573820ade6a6fe321731d0f3eb082d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T02:48:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:28:29.000Z", "max_issues_repo_path": "matlab/radialpose_mex.cpp", "max_issues_repo_name": "vlarsson/radialpose", "max_issues_repo_head_hexsha": "e620fc208f573820ade6a6fe321731d0f3eb082d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-31T16:16:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T19:39:41.000Z", "max_forks_repo_path": "matlab/radialpose_mex.cpp", "max_forks_repo_name": "vlarsson/radialpose", "max_forks_repo_head_hexsha": "e620fc208f573820ade6a6fe321731d0f3eb082d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-11-04T21:38:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T20:41:11.000Z", "avg_line_length": 35.0459183673, "max_line_length": 143, "alphanum_fraction": 0.6634153443, "num_tokens": 2507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5067982547063207}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2013 Alec Jacobson <alecjacobson@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 \"polar_dec.h\"\n#include \"polar_svd.h\"\n#ifdef _WIN32\n#else\n#  include <fenv.h>\n#endif\n#include <cmath>\n#include <Eigen/Eigenvalues>\n#include <iostream>\n#include <cfenv>\n\n// From Olga's CGAL mentee's ARAP code\ntemplate <\n  typename DerivedA,\n  typename DerivedR,\n  typename DerivedT,\n  typename DerivedU,\n  typename DerivedS,\n  typename DerivedV>\nIGL_INLINE void igl::polar_dec(\n  const Eigen::PlainObjectBase<DerivedA> & A,\n  Eigen::PlainObjectBase<DerivedR> & R,\n  Eigen::PlainObjectBase<DerivedT> & T,\n  Eigen::PlainObjectBase<DerivedU> & U,\n  Eigen::PlainObjectBase<DerivedS> & S,\n  Eigen::PlainObjectBase<DerivedV> & V)\n{\n  using namespace std;\n  using namespace Eigen;\n  typedef typename DerivedA::Scalar Scalar;\n\n  const Scalar th = std::sqrt(Eigen::NumTraits<Scalar>::dummy_precision());\n\n  Eigen::SelfAdjointEigenSolver<DerivedA> eig;\n  feclearexcept(FE_UNDERFLOW);\n  eig.computeDirect(A.transpose()*A);\n  if(fetestexcept(FE_UNDERFLOW) || eig.eigenvalues()(0)/eig.eigenvalues()(2)<th)\n  {\n    cout<<\"resorting to svd 1...\"<<endl;\n    return polar_svd(A,R,T,U,S,V);\n  }\n\n  S = eig.eigenvalues().cwiseSqrt();\n\n  V = eig.eigenvectors();\n  U = A * V;\n  R = U * S.asDiagonal().inverse() * V.transpose();\n  T = V * S.asDiagonal() * V.transpose();\n\n  S = S.reverse().eval();\n  V = V.rowwise().reverse().eval();\n  U = U.rowwise().reverse().eval() * S.asDiagonal().inverse();\n\n  if(R.determinant() < 0)\n  {\n    // Annoyingly the .eval() is necessary\n    auto W = V.eval();\n    const auto & SVT = S.asDiagonal() * V.adjoint();\n    W.col(V.cols()-1) *= -1.;\n    R = U*W.transpose();\n    T = W*SVT;\n  }\n\n  if(std::fabs(R.squaredNorm()-3.) > th)\n  {\n    cout<<\"resorting to svd 2...\"<<endl;\n    return polar_svd(A,R,T,U,S,V);\n  }\n}\n\ntemplate <\n  typename DerivedA,\n  typename DerivedR,\n  typename DerivedT>\nIGL_INLINE void igl::polar_dec(\n  const Eigen::PlainObjectBase<DerivedA> & A,\n  Eigen::PlainObjectBase<DerivedR> & R,\n  Eigen::PlainObjectBase<DerivedT> & T)\n{\n  DerivedA U;\n  DerivedA V;\n  Eigen::Matrix<typename DerivedA::Scalar,DerivedA::RowsAtCompileTime,1> S;\n  return igl::polar_dec(A,R,T,U,S,V);\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate  void igl::polar_dec<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate void igl::polar_dec<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, 2, 2, 0, 2, 2>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 2, 2, 0, 2, 2> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\n#endif\n", "meta": {"hexsha": "cdd358a0744c43e7bc44ab1758278b8fd3f90bb8", "size": 3577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/simpleuv/thirdparty/libigl/include/igl/polar_dec.cpp", "max_stars_repo_name": "MelvinG24/dust3d", "max_stars_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "thirdparty/simpleuv/thirdparty/libigl/include/igl/polar_dec.cpp", "max_issues_repo_name": "MelvinG24/dust3d", "max_issues_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "thirdparty/simpleuv/thirdparty/libigl/include/igl/polar_dec.cpp", "max_forks_repo_name": "MelvinG24/dust3d", "max_forks_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 36.5, "max_line_length": 693, "alphanum_fraction": 0.6550181717, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5067982547063207}}
{"text": "// Copyright (c)  Mingcheng Zuo, Dietmar Wolz.\r\n//\r\n// This source code is licensed under the MIT license found in the\r\n// LICENSE file in the root directory.\r\n\r\n// Eigen based implementation of differential evolution (GCL-DE) derived from\r\n// \"A case learning-based differential evolution algorithm for global optimization of interplanetary trajectory design,\r\n//  Mingcheng Zuo, Guangming Dai, Lei Peng, Maocai Wang, Zhengquan Liu\", https://doi.org/10.1016/j.asoc.2020.106451\r\n\r\n#include <Eigen/Core>\r\n#include <iostream>\r\n#include <float.h>\r\n#include <ctime>\r\n#include <random>\r\n#include \"pcg_random.hpp\"\r\n\r\nusing namespace std;\r\n\r\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1> vec;\r\ntypedef Eigen::Matrix<int, Eigen::Dynamic, 1> ivec;\r\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat;\r\n\r\ntypedef void (*callback_parallel)(int, int, double[], double[]);\r\n\r\nnamespace gcl_differential_evolution {\r\n\r\nstatic uniform_real_distribution<> distr_01 = std::uniform_real_distribution<>(\r\n        0, 1);\r\n\r\nstatic normal_distribution<> gauss_01 = std::normal_distribution<>(0, 1);\r\n\r\nstatic double normreal(pcg64 *rs, double mu, double sdev) {\r\n    return gauss_01(*rs) * sdev + mu;\r\n}\r\n\r\nstatic vec zeros(int n) {\r\n    return Eigen::MatrixXd::Zero(n, 1);\r\n}\r\n\r\nstatic vec constant(int n, double val) {\r\n    return Eigen::MatrixXd::Constant(n, 1, val);\r\n}\r\n\r\nstatic Eigen::MatrixXd uniformVec(int dim, pcg64 &rs) {\r\n    return Eigen::MatrixXd::NullaryExpr(dim, 1, [&]() {\r\n        return distr_01(rs);\r\n    });\r\n}\r\n\r\nstatic Eigen::MatrixXd normalVec(int dim, pcg64 &rs) {\r\n    return Eigen::MatrixXd::NullaryExpr(dim, 1, [&]() {\r\n        return gauss_01(rs);\r\n    });\r\n}\r\n\r\nstatic Eigen::MatrixXd uniform(int dx, int dy, pcg64 &rs) {\r\n    return Eigen::MatrixXd::NullaryExpr(dx, dy, [&]() {\r\n        return distr_01(rs);\r\n    });\r\n}\r\n\r\nstruct IndexVal {\r\n    int index;\r\n    double val;\r\n};\r\n\r\nstatic bool compareIndexVal(IndexVal i1, IndexVal i2) {\r\n    return (i1.val < i2.val);\r\n}\r\n\r\nstatic ivec sort_index(const vec &x) {\r\n    int size = x.size();\r\n    IndexVal ivals[size];\r\n    for (int i = 0; i < size; i++) {\r\n        ivals[i].index = i;\r\n        ivals[i].val = x[i];\r\n    }\r\n    std::sort(ivals, ivals + size, compareIndexVal);\r\n    return Eigen::MatrixXi::NullaryExpr(size, 1, [&ivals](int i) {\r\n        return ivals[i].index;\r\n    });\r\n}\r\n\r\n// wrapper around the fitness function, scales according to boundaries\r\n\r\nclass Fitness {\r\n\r\npublic:\r\n\r\n    Fitness(callback_parallel func_par_, int dim_, const vec &lower_limit,\r\n            const vec &upper_limit) {\r\n        func_par = func_par_;\r\n        dim = dim_;\r\n        lower = lower_limit;\r\n        upper = upper_limit;\r\n        evaluationCounter = 0;\r\n        if (lower.size() > 0) // bounds defined\r\n            scale = (upper - lower);\r\n    }\r\n\r\n    vec getClosestFeasible(const vec &X) const {\r\n        if (lower.size() > 0) {\r\n            return X.cwiseMin(upper).cwiseMax(lower);\r\n        }\r\n        return X;\r\n    }\r\n\r\n    void values(const mat &popX, vec &ys) {\r\n        int popsize = popX.cols();\r\n        int n = popX.rows();\r\n        double pargs[popsize * n];\r\n        double res[popsize];\r\n        for (int p = 0; p < popX.cols(); p++) {\r\n            for (int i = 0; i < n; i++)\r\n                pargs[p * n + i] = popX(i, p);\r\n        }\r\n        func_par(popsize, n, pargs, res);\r\n        for (int p = 0; p < popX.cols(); p++)\r\n            ys[p] = res[p];\r\n        evaluationCounter += popsize;\r\n    }\r\n\r\n    bool feasible(int i, double x) {\r\n        return lower.size() == 0 || (x >= lower[i] && x <= upper[i]);\r\n    }\r\n\r\n    vec sample(pcg64 &rs) {\r\n        if (lower.size() > 0) {\r\n            vec rv = uniformVec(dim, rs);\r\n            return (rv.array() * scale.array()).matrix() + lower;\r\n        } else\r\n            return normalVec(dim, rs);\r\n    }\r\n\r\n    double sample_i(int i, pcg64 &rs) {\r\n        if (lower.size() > 0)\r\n            return lower[i] + scale[i] * distr_01(rs);\r\n        else\r\n            return gauss_01(rs);\r\n    }\r\n\r\n    int getEvaluations() {\r\n        return evaluationCounter;\r\n    }\r\n\r\nprivate:\r\n    callback_parallel func_par;\r\n    int dim;\r\n    vec lower;\r\n    vec upper;\r\n    long evaluationCounter;\r\n    vec scale;\r\n};\r\n\r\nclass GclDeOptimizer {\r\n\r\npublic:\r\n\r\n    GclDeOptimizer(long runid_, Fitness *fitfun_, int dim_, int seed_,\r\n            int popsize_, int maxEvaluations_, double pbest_,\r\n            double stopfitness_, double F0_, double CR0_) {\r\n        // runid used to identify a specific run\r\n        runid = runid_;\r\n        // fitness function to minimize\r\n        fitfun = fitfun_;\r\n        // Number of objective variables/problem dimension\r\n        dim = dim_;\r\n        // Population size\r\n        popsize = popsize_ > 0 ? popsize_ : int(dim * 8.5 + 150);\r\n        // maximal number of evaluations allowed.\r\n        maxEvaluations = maxEvaluations_;\r\n        // use low value 0 < pbest <= 1 to narrow search.\r\n        pbest = pbest_;\r\n        // Limit for fitness value.\r\n        stopfitness = stopfitness_;\r\n        F0 = F0_;\r\n        CR0 = CR0_;\r\n        // stop criteria\r\n        stop = 0;\r\n        rs = new pcg64(seed_);\r\n        init();\r\n    }\r\n\r\n    ~GclDeOptimizer() {\r\n        delete rs;\r\n    }\r\n\r\n    double rnd01() {\r\n        return distr_01(*rs);\r\n    }\r\n\r\n    int rndInt(int max) {\r\n        return (int) (max * distr_01(*rs));\r\n    }\r\n\r\n    void doOptimize() {\r\n        int gen_stuck = 0;\r\n        vector<vec> sp;\r\n\r\n        int maxIter = maxEvaluations / popsize + 1;\r\n        double previous_best = DBL_MAX;\r\n        double CR, F;\r\n\r\n        // -------------------- Generation Loop --------------------------------\r\n\r\n        for (iterations = 1;; iterations++) {\r\n            // sort population\r\n            ivec sindex = sort_index(nextY);\r\n            popY = nextY(sindex, Eigen::all);\r\n            popX = nextX(Eigen::all, sindex);\r\n\r\n            bestX = popX.col(0);\r\n            bestY = popY[0];\r\n\r\n            if (isfinite(stopfitness) && bestY < stopfitness) {\r\n                stop = 1;\r\n                return;\r\n            }\r\n            if (bestY == previous_best)\r\n                gen_stuck++;\r\n            else\r\n                gen_stuck = 0;\r\n            previous_best = bestY;\r\n\r\n            if (fitfun->getEvaluations() >= maxEvaluations)\r\n                return;\r\n            for (int p = 0; p < popsize; p++) {\r\n                int r1, r2, r3;\r\n                do {\r\n                    r1 = rndInt(popsize);\r\n                } while (r1 == p);\r\n                do {\r\n                    r2 = rndInt(int(popsize * pbest));\r\n                } while (r2 == p || r2 == r1);\r\n                do {\r\n                    r3 = rndInt(popsize + sp.size());\r\n                } while (r3 == p || r3 == r2 || r3 == r1);\r\n                int jr = rndInt(dim);\r\n                //Produce the CR and F\r\n                double mu = 1\r\n                        - sqrt(float(iterations / maxIter))\r\n                                * exp(float(-gen_stuck / iterations));\r\n                if (iterations % 2 == 1) {\r\n                    CR = normreal(rs, 0.95, 0.01);\r\n                    F = normreal(rs, mu, 1);\r\n                    if (F < 0 || F > 1)\r\n                        F = rnd01();\r\n                } else {\r\n                    CR = abs(normreal(rs, CR0, 0.01));\r\n                    F = F0;\r\n                }\r\n                vec ui = popX.col(p);\r\n                for (int j = 0; j < dim; j++) {\r\n                    if (j == jr || rnd01() < CR) {\r\n                        if (r3 < popsize)\r\n                            ui[j] = popX(j, r1)\r\n                                    + F * (popX(j, r2) - popX(j, r3));\r\n                        else\r\n                            ui[j] = popX(j, r1)\r\n                                    + F * ((popX)(j, r2) - sp[r3 - popsize][j]);\r\n                        if (!fitfun->feasible(j, ui[j]))\r\n                            ui[j] = fitfun->sample_i(j, *rs);\r\n                    }\r\n                }\r\n                nextX.col(p) = ui;\r\n            }\r\n            fitfun->values(nextX, nextY);\r\n            for (int p = 0; p < popsize; p++) {\r\n                if (nextY[p] < popY[p]) {\r\n                    if (sp.size() < popsize)\r\n                        sp.push_back(popX.col(p));\r\n                    else\r\n                        sp[rndInt(popsize)] = popX.col(p);\r\n                } else {        // no improvement, copy from parent\r\n                    nextX.col(p) = popX.col(p);\r\n                    nextY[p] = popY[p];\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    void init() {\r\n        popCR = zeros(popsize);\r\n        popF = zeros(popsize);\r\n        nextX = mat(dim, popsize);\r\n        for (int p = 0; p < popsize; p++)\r\n            nextX.col(p) = fitfun->sample(*rs);\r\n        nextY = vec(popsize);\r\n        fitfun->values(nextX, nextY);\r\n    }\r\n\r\n    vec getBestX() {\r\n        return bestX;\r\n    }\r\n\r\n    double getBestValue() {\r\n        return bestY;\r\n    }\r\n\r\n    double getIterations() {\r\n        return iterations;\r\n    }\r\n\r\n    double getStop() {\r\n        return stop;\r\n    }\r\n\r\nprivate:\r\n    long runid;\r\n    Fitness *fitfun;\r\n    int popsize; // population size\r\n    int dim;\r\n    int maxEvaluations;\r\n    double pbest;\r\n    double stopfitness;\r\n    int iterations;\r\n    double bestY;\r\n    vec bestX;\r\n    int stop;\r\n    double F0;\r\n    double CR0;\r\n    pcg64 *rs;\r\n    mat popX;\r\n    vec popY;\r\n    mat nextX;\r\n    vec nextY;\r\n    vec popCR;\r\n    vec popF;\r\n};\r\n}\r\n\r\nusing namespace gcl_differential_evolution;\r\n\r\nextern \"C\" {\r\ndouble* optimizeGCLDE_C(long runid, callback_parallel func_par, int dim,\r\n        int seed, double *lower, double *upper, int maxEvals, double pbest,\r\n        double stopfitness, int popsize, double F0, double CR0) {\r\n    int n = dim;\r\n    double *res = new double[n + 4];\r\n    vec lower_limit(n), upper_limit(n);\r\n    bool useLimit = false;\r\n    for (int i = 0; i < n; i++) {\r\n        lower_limit[i] = lower[i];\r\n        upper_limit[i] = upper[i];\r\n        useLimit |= (lower[i] != 0);\r\n        useLimit |= (upper[i] != 0);\r\n    }\r\n    if (useLimit == false) {\r\n        lower_limit.resize(0);\r\n        upper_limit.resize(0);\r\n    }\r\n    Fitness fitfun(func_par, n, lower_limit, upper_limit);\r\n    GclDeOptimizer opt(runid, &fitfun, dim, seed, popsize, maxEvals, pbest,\r\n            stopfitness, F0, CR0);\r\n    try {\r\n        opt.doOptimize();\r\n        vec bestX = opt.getBestX();\r\n        double bestY = opt.getBestValue();\r\n        for (int i = 0; i < n; i++)\r\n            res[i] = bestX[i];\r\n        res[n] = bestY;\r\n        res[n + 1] = fitfun.getEvaluations();\r\n        res[n + 2] = opt.getIterations();\r\n        res[n + 3] = opt.getStop();\r\n        return res;\r\n    } catch (std::exception &e) {\r\n        cout << e.what() << endl;\r\n        return res;\r\n    }\r\n}\r\n}\r\n", "meta": {"hexsha": "dcedb0e3d29199a1a1b664da7faca1d4523137b0", "size": 10842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_fcmaescpp/gcldeoptimizer.cpp", "max_stars_repo_name": "timjim333/fast-cma-es", "max_stars_repo_head_hexsha": "9de6d75380816faba49bff6969306dd9c00836ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_fcmaescpp/gcldeoptimizer.cpp", "max_issues_repo_name": "timjim333/fast-cma-es", "max_issues_repo_head_hexsha": "9de6d75380816faba49bff6969306dd9c00836ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_fcmaescpp/gcldeoptimizer.cpp", "max_forks_repo_name": "timjim333/fast-cma-es", "max_forks_repo_head_hexsha": "9de6d75380816faba49bff6969306dd9c00836ac", "max_forks_repo_licenses": ["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.1451612903, "max_line_length": 120, "alphanum_fraction": 0.4884707619, "num_tokens": 2748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5067982443716491}}
{"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 \"gpssim.h\"\n#include \"gps_channel.h\"\n#include \"gps_time.h\"\n#include \"gps_ephem.h\"\n#include \"gps_math.h\"\n#include \"gps_subframe.h\"\n#include \"geodesy.h\"\n#include \"ionosphere.h\"\n#include \"noise_generator.h\"\n#include \"rinex2_reader.h\"\n#include \"sin_table.h\"\n#include \"sample_writer.h\"\n#include \"satellite_gain.h\"\n\n#include <Eigen/Core>\n\n#include <unistd.h>\n#include <iostream>\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <cmath>\n#include <ctime>\n\nnamespace {\n    \nstatic constexpr double kWavelengthGpsL1ca_m = 0.190293672798365;\n\n}   // namespace\n\n\n/*! \\brief Compute range between a satellite and the receiver\n *  \\param[out] rho The computed range\n *  \\param[in] eph Ephemeris data of the satellite\n *  \\param[in] g GPS time at time of receiving the signal\n *  \\param[in] e_pos_e_a is the position of the receiver.\n */\nrange_t ComputeRange(const ephem_t &eph, const ionoutc_t &ionoutc, \n                  gpstime_t g, const Eigen::Vector3d &e_pos_e_a)\n{\n\tdouble pos[3],vel[3],clk[2];\n\tdouble los[3];\n\tdouble xrot,yrot;\n\n\tdouble neu[3];\n\tdouble tmat[3][3];\n\t\n\t// SV position at time of the pseudorange observation.\n\tsatpos(eph, g, pos, vel, clk);\n\n\t// Receiver to satellite vector and light-time.\n\tsubVect(los, pos, e_pos_e_a);\n\tconst double tau = normVect(los)/SPEED_OF_LIGHT;\n\n\t// Extrapolate the satellite position backwards to the transmission time.\n\tpos[0] -= vel[0]*tau;\n\tpos[1] -= vel[1]*tau;\n\tpos[2] -= vel[2]*tau;\n\n\t// Earth rotation correction. The change in velocity can be neglected.\n\txrot = pos[0] + pos[1]*OMEGA_EARTH*tau;\n\tyrot = pos[1] - pos[0]*OMEGA_EARTH*tau;\n\tpos[0] = xrot;\n\tpos[1] = yrot;\n    \n    range_t rho;\n\n\t// New observer to satellite vector and satellite range.\n\tsubVect(los, pos, e_pos_e_a);\n\tconst double range = normVect(los);\n\trho.d = range;\n\n\t// Pseudorange.\n\trho.range = range - SPEED_OF_LIGHT*clk[0];\n\n\t// Relative velocity of SV and receiver.\n\tconst double rate = dotProd(vel, los)/range;\n\n\t// Pseudorange rate.\n\trho.rate = rate; // - SPEED_OF_LIGHT*clk[1];\n\n\t// Time of application.\n\trho.g = g;\n\n\t// Azimuth and elevation angles.\n\tconst GeodeticPosition llh = xyz2llh(e_pos_e_a);\n\tltcmat(llh, tmat);\n\tecef2neu(los, tmat, neu);\n\trho.azel = neu2azel(neu);\n\n\t// Add ionospheric delay\n\trho.iono_delay = ionosphericDelay(ionoutc, g, llh, rho.azel);\n\trho.range += rho.iono_delay;\n\n\treturn rho;\n}\n\n\nAzimuthElevation ComputeSatelliteAzel(const ephem_t &eph, gpstime_t g, \n                        const Eigen::Vector3d &e_pos_e_a)\n{\n\tdouble neu[3];\n\tdouble pos[3],vel[3],clk[3],los[3];\n\tdouble tmat[3][3];\n\n\tconst GeodeticPosition llh = xyz2llh(e_pos_e_a);\n\tltcmat(llh, tmat);\n\n\tsatpos(eph, g, pos, vel, clk);\n\tsubVect(los, pos, e_pos_e_a);\n\tecef2neu(los, tmat, neu);\n\treturn neu2azel(neu);\n}\n\nint allocateChannel(GpsChannel *chan, ephem_t *eph, int* allocatedSat, \n                    ionoutc_t ionoutc, gpstime_t current_simulation_time, \n                    const Eigen::Vector3d &e_pos_e_a, double elevation_mask_deg)\n{\n    int num_visible_sats = 0;\n\n\tfor (int sv = 0; sv < MAX_SAT; sv++)\n\t{\n        AzimuthElevation azel;\n        bool is_visible = false;\n        if (eph[sv].valid) {\n            azel = ComputeSatelliteAzel(eph[sv], current_simulation_time, e_pos_e_a);\n            is_visible = azel.elevation_deg() > elevation_mask_deg;\n        }\n        \n\t\tif (is_visible)\n\t\t{\n\t\t\tnum_visible_sats++;\n\t\t\tif (allocatedSat[sv] == -1) // Visible but not allocated\n\t\t\t{\n\t\t\t\t// Allocated new satellite\n                int i;\n\t\t\t\tfor (i = 0; i < MAX_CHAN; i++)\n\t\t\t\t{\n\t\t\t\t\tif (!chan[i].IsEnabled())\n\t\t\t\t\t{\n\t\t\t\t\t\t// Initialize channel\n\t\t\t\t\t\tchan[i] = GpsChannel(sv+1);\n\t\t\t\t\t\tchan[i].azel = azel;\n\n\t\t\t\t\t\t// Generate subframe\n\t\t\t\t\t\tchan[i].SetEphemeris(eph[sv], ionoutc);\n\n\t\t\t\t\t\t// Generate navigation message\n\t\t\t\t\t\tchan[i].GenerateNavMsg(current_simulation_time, 1);\n\n\t\t\t\t\t\t// Initialize pseudorange\n                        range_t rho = ComputeRange(eph[sv], ionoutc, \n                                     current_simulation_time, e_pos_e_a);\n\t\t\t\t\t\tchan[i].rho0 = rho;\n\n\t\t\t\t\t\t// Initialize carrier phase\n\t\t\t\t\t\tconst double r_xyz = rho.range;\n\n\t\t\t\t\t\trho = ComputeRange(eph[sv], ionoutc, \n                                     current_simulation_time, \n                                     Eigen::Vector3d::Zero());\n\t\t\t\t\t\tconst double r_ref = rho.range;\n\n\t\t\t\t\t\tconst double phase_ini = \n                                (2.0*r_ref - r_xyz) * (1.0 / kWavelengthGpsL1ca_m);\n\t\t\t\t\t\tchan[i].carrier_phase_cycles = phase_ini - floor(phase_ini);\n\n\t\t\t\t\t\t// Done.\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Set satellite allocation channel\n\t\t\t\tif (i < MAX_CHAN)\n\t\t\t\t\tallocatedSat[sv] = i;\n\t\t\t}\n\t\t}\n\t\telse if (allocatedSat[sv] >= 0) // Not visible but allocated\n\t\t{\n\t\t\t// Clear channel\n\t\t\tchan[allocatedSat[sv]].prn = 0;\n\n\t\t\t// Clear satellite allocation flag\n\t\t\tallocatedSat[sv] = -1;\n\t\t}\n\t}\n\n\treturn num_visible_sats;\n}\n\nvoid usage(void)\n{\n\tfprintf(stderr, \"Usage: gps-sdr-sim [options]\\n\"\n\t\t\"Options:\\n\"\n\t\t\"  -e <gps_nav>     RINEX navigation file for GPS ephemerides (required)\\n\"\n\t\t\"  -c <location>    ECEF X,Y,Z in meters (static mode) e.g. 3967283.154,1022538.181,4872414.484\\n\"\n\t\t\"  -l <location>    Lat,Lon,Hgt (static mode) e.g. 35.681298,139.766247,10.0\\n\"\n\t\t\"  -t <date,time>   Scenario start time YYYY/MM/DD,hh:mm:ss\\n\"\n\t\t\"  -d <duration>    Duration [sec] (static mode max: %d)\\n\"\n\t\t\"  -o <output>      I/Q sampling data file (default: gpssim.bin)\\n\"\n\t\t\"  -s <frequency>   Sampling frequency [Hz] (default: 2600000)\\n\"\n\t\t\"  -i               Disable ionospheric delay for spacecraft scenario\\n\"\n\t\t\"  -v               Show details about simulated channels\\n\",\n\t\tSTATIC_MAX_DURATION);\n\n\treturn;\n}\n\n/// \\brief Checks whether the sample frequency has an integer number of ns ticks.\nbool SampleFrequencyIsValid(int sample_frequency) {\n    constexpr int ticks_per_ns = 1000000000;\n    int period_ns = ticks_per_ns / sample_frequency;\n    return period_ns * sample_frequency == ticks_per_ns;\n}\n\nint main(int argc, char *argv[])\n{\n\tclock_t tstart,tend;\n\n\tephem_t eph[EPHEM_ARRAY_SIZE][MAX_SAT];\n\n\tgpstime_t simulation_start_gps_time;\n    gpstime_t current_simulation_time;\n\t\n    // Default static location; Tokyo\n\tGeodeticPosition llh = GeodeticPosition::FromDegrees(35.681298, 139.766247, 10.0);\n\n\tGpsChannel chan[MAX_CHAN];\n\tdouble elevation_mask_deg = 0.0;\n\n    // User position in ECEF coordinates.\n    Eigen::Vector3d e_pos_e_a;\n\n    std::string rinex2_nav_file;\n    std::string output_sample_filename = {\"gpssim.bin\"};\n\n\tint result;\n\n\tdatetime_t t0,tmin,tmax;\n\tgpstime_t gmin,gmax;\n\n\tbool verbose = false;\n\n\tionoutc_t ionoutc;\n    \n    int allocatedSat[MAX_SAT];\n\n    NoiseGenerator noise_generator(1.0, 0.20, 0.5);\n\n\t////////////////////////////////////////////////////////////\n\t// Read options\n\t////////////////////////////////////////////////////////////\n\n\t// Default options\n\tdouble raw_samp_freq = 2.6e6;\n\tsimulation_start_gps_time.week = -1; // Invalid start time\n\tdouble duration = 300;     // 5 minutes.\n\tionoutc.enable = true;\n\n\tif (argc<3)\n\t{\n\t\tusage();\n\t\texit(1);\n\t}\n\n\twhile ((result=getopt(argc,argv,\"e:u:g:c:l:o:s:t:d:iv\"))!=-1)\n\t{\n\t\tswitch (result)\n\t\t{\n\t\tcase 'e':\n            rinex2_nav_file.assign(optarg);\n\t\t\tbreak;\n\t\tcase 'c':\n        {\n\t\t\t// Static ECEF coordinates input mode\n            double xyz[3];\n\t\t\tsscanf(optarg,\"%lf,%lf,%lf\", &xyz[0], &xyz[1], &xyz[2]);\n            e_pos_e_a = {xyz[0], xyz[1], xyz[2]};\n\t\t\tbreak;\n        }\n\t\tcase 'l':\n        {\n\t\t\t// Static geodetic coordinates input mode.\n            double raw_lat, raw_lon, raw_height;\n\t\t\tsscanf(optarg,\"%lf,%lf,%lf\",&raw_lat, &raw_lon, &raw_height);\n            llh = GeodeticPosition::FromDegrees(raw_lat, raw_lon, raw_height);\n\t\t\te_pos_e_a = llh2xyz(llh);\n\t\t\tbreak;\n        }\n\t\tcase 'o':\n\t\t\toutput_sample_filename.assign(optarg);\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\traw_samp_freq = atof(optarg);\n\t\t\tif (raw_samp_freq < 1.0e6)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"ERROR: Invalid sampling frequency.\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\tsscanf(optarg, \"%d/%d/%d,%d:%d:%lf\", &t0.y, &t0.m, &t0.d, &t0.hh, &t0.mm, &t0.sec);\n\t\t\tif (t0.y<=1980 || t0.m<1 || t0.m>12 || t0.d<1 || t0.d>31 ||\n\t\t\t\tt0.hh<0 || t0.hh>23 || t0.mm<0 || t0.mm>59 || t0.sec<0.0 || t0.sec>=60.0)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"ERROR: Invalid date and time.\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tt0.sec = floor(t0.sec);\n\t\t\tsimulation_start_gps_time = date2gps(t0);\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\tduration = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'i':\n\t\t\tionoutc.enable = false; // Disable ionospheric correction\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tverbose = true;\n\t\t\tbreak;\n\t\tcase ':':\n\t\tcase '?':\n\t\t\tusage();\n\t\t\texit(1);\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (rinex2_nav_file.empty())\n\t{\n\t\tfprintf(stderr, \"ERROR: GPS ephemeris file is not specified.\\n\");\n\t\texit(1);\n\t}\n\n\tif (duration < 0.0 || duration > STATIC_MAX_DURATION)\n\t{\n\t\tfprintf(stderr, \"ERROR: Invalid duration.\\n\");\n\t\texit(1);\n\t}\n\n    SampleWriter sample_writer;\n    if (sample_writer.OpenFile(output_sample_filename))\n    {\n        fprintf(stderr, \"ERROR: Failed to open output sample file \\\"%s\\\".\\n\", output_sample_filename.c_str());\n    }\n\n    const int sample_freq_hz = std::lround(raw_samp_freq);\n    if (!SampleFrequencyIsValid(sample_freq_hz)) {\n        fprintf(stderr, \"ERROR: Sample frequency %f not an integer divisor of 1GHz\\n\",\n                raw_samp_freq);\n        exit(1);\n    }\n\n    const double sample_period_s = 1.0 / raw_samp_freq;\n    const int sample_period_ns = 1000000000 / sample_freq_hz;\n\n    // Currently, samples are processed in batches of 1ms\n    const double batch_period_s = 0.001;\n    const int num_sample_batches = std::lround(duration / batch_period_s);\n    const int samples_per_batch = std::lround(\n            (1e9 * batch_period_s) / sample_period_ns);\n\n\t////////////////////////////////////////////////////////////\n\t// Read ephemeris\n\t////////////////////////////////////////////////////////////\n\n\tconst int neph = readRinexNavAll(eph, &ionoutc, rinex2_nav_file);\n\n\tif (neph==0)\n\t{\n\t\tfprintf(stderr, \"ERROR: No ephemeris available.\\n\");\n\t\texit(1);\n\t}\n\n\tif (verbose && ionoutc.valid)\n\t{\n\t\tfprintf(stderr, \"  %12.3e %12.3e %12.3e %12.3e\\n\", \n\t\t\tionoutc.alpha0, ionoutc.alpha1, ionoutc.alpha2, ionoutc.alpha3);\n\t\tfprintf(stderr, \"  %12.3e %12.3e %12.3e %12.3e\\n\", \n\t\t\tionoutc.beta0, ionoutc.beta1, ionoutc.beta2, ionoutc.beta3);\n\t\tfprintf(stderr, \"   %19.11e %19.11e  %9d %9d\\n\",\n\t\t\tionoutc.A0, ionoutc.A1, ionoutc.tot, ionoutc.wnt);\n\t\tfprintf(stderr, \"%6d\\n\", ionoutc.dtls);\n\t}\n\n\tfor (int sv = 0; sv < MAX_SAT; sv++) \n\t{\n\t\tif (eph[0][sv].valid)\n\t\t{\n\t\t\tgmin = eph[0][sv].toc;\n\t\t\ttmin = eph[0][sv].t;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tgmax.sec = 0;\n\tgmax.week = 0;\n\ttmax.sec = 0;\n\ttmax.mm = 0;\n\ttmax.hh = 0;\n\ttmax.d = 0;\n\ttmax.m = 0;\n\ttmax.y = 0;\n\tfor (int sv = 0; sv < MAX_SAT; sv++)\n\t{\n\t\tif (eph[neph-1][sv].valid)\n\t\t{\n\t\t\tgmax = eph[neph-1][sv].toc;\n\t\t\ttmax = eph[neph-1][sv].t;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Scenario start time has been set.\n\tif (simulation_start_gps_time.week >= 0)\n\t{\n\t\tif (subGpsTime(simulation_start_gps_time, gmin) < 0.0 || \n            subGpsTime(gmax, simulation_start_gps_time) < 0.0)\n\t\t{\n\t\t\tfprintf(stderr, \"ERROR: Invalid start time.\\n\");\n\t\t\tfprintf(stderr, \"tmin = %4d/%02d/%02d,%02d:%02d:%02.0f (%d:%.0f)\\n\", \n\t\t\t\ttmin.y, tmin.m, tmin.d, tmin.hh, tmin.mm, tmin.sec,\n\t\t\t\tgmin.week, gmin.sec);\n\t\t\tfprintf(stderr, \"tmax = %4d/%02d/%02d,%02d:%02d:%02.0f (%d:%.0f)\\n\", \n\t\t\t\ttmax.y, tmax.m, tmax.d, tmax.hh, tmax.mm, tmax.sec,\n\t\t\t\tgmax.week, gmax.sec);\n\t\t\texit(1);\n\t\t}\n\t}\n\telse\n\t{\n\t\tsimulation_start_gps_time = gmin;\n\t\tt0 = tmin;\n\t}\n\n\tfprintf(stderr, \"Start time = %4d/%02d/%02d,%02d:%02d:%02.0f (%d:%.0f)\\n\", \n\t\tt0.y, t0.m, t0.d, t0.hh, t0.mm, t0.sec, simulation_start_gps_time.week, \n         simulation_start_gps_time.sec);\n\tfprintf(stderr, \"Duration = %.1f [sec]\\n\", duration);\n\n\t// Select the current set of ephemerides\n\tint ieph = -1;\n\n\tfor (int i = 0; i < neph; i++)\n\t{\n\t\tfor (int sv = 0; sv < MAX_SAT; sv++)\n\t\t{\n\t\t\tif (eph[i][sv].valid)\n\t\t\t{\n\t\t\t\tconst double dt = subGpsTime(simulation_start_gps_time, eph[i][sv].toc);\n\t\t\t\tif (dt>=-SECONDS_IN_HOUR && dt<SECONDS_IN_HOUR)\n\t\t\t\t{\n\t\t\t\t\tieph = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (ieph>=0) // ieph has been set\n\t\t\tbreak;\n\t}\n\n\tif (ieph == -1)\n\t{\n\t\tfprintf(stderr, \"ERROR: No current set of ephemerides has been found.\\n\");\n\t\texit(1);\n\t}\n\n\t////////////////////////////////////////////////////////////\n\t// Initialize channels\n\t////////////////////////////////////////////////////////////\n\n\t// Clear satellite allocation flag\n\tfor (int sv = 0; sv < MAX_SAT; sv++) {\n\t\tallocatedSat[sv] = -1;\n    }\n\n\t// Initial reception time\n\tcurrent_simulation_time = incGpsTime(simulation_start_gps_time, 0.0);\n\n\t// Allocate visible satellites\n\tallocateChannel(chan, eph[ieph], allocatedSat, ionoutc, current_simulation_time, \n                    e_pos_e_a, elevation_mask_deg);\n\n\tfor(int i = 0; i < MAX_CHAN; i++)\n\t{\n\t\tif (chan[i].IsEnabled()) {\n\t\t\tfprintf(stderr, \"%02d %6.1f %5.1f %11.1f %5.1f\\n\", chan[i].prn, \n\t\t\t\tchan[i].azel.azimuth_deg(), chan[i].azel.elevation_deg(), chan[i].\n\t\t\t\trho0.d, chan[i].rho0.iono_delay);\n        }\n\t}\n\n\t////////////////////////////////////////////////////////////\n\t// Generate baseband signals\n\t////////////////////////////////////////////////////////////\n\n\ttstart = clock();\n\n\t// Update receiver time\n\tcurrent_simulation_time = incGpsTime(current_simulation_time, batch_period_s);\n    \n    PeriodicFunctionTable<double, 1024> sin_table(\n        [](double t) -> double {return std::sin(t);}, 1.0);\n    PeriodicFunctionTable<double, 1024> cos_table(\n        [](double t) -> double {return std::cos(t);}, 1.0);\n    \n    // Default all channels to a gain of 1.\n    ConstellationGain constellation_gain;\n    for (int prn = 0; prn <= 32; ++prn) {\n        constellation_gain.SetSatelliteToConstantGain(prn, 1.0);\n    }\n    \n    // Successively decrease the gain as the PRN increases.\n    constellation_gain.SetSatelliteToConstantGain( 1, 1.0);\n    constellation_gain.SetSatelliteToConstantGain( 2, 0.9);\n    constellation_gain.SetSatelliteToConstantGain( 3, 0.7);\n    constellation_gain.SetSatelliteToConstantGain( 6, 0.6);\n    constellation_gain.SetSatelliteToConstantGain( 9, 0.5);\n    constellation_gain.SetSatelliteToConstantGain(10, 0.4);\n    constellation_gain.SetSatelliteToConstantGain(11, 0.3);\n    constellation_gain.SetSatelliteToConstantGain(12, 0.2);\n    constellation_gain.SetSatelliteToConstantGain(17, 0.17);\n    constellation_gain.SetSatelliteToConstantGain(20, 0.15);\n    constellation_gain.SetSatelliteToConstantGain(23, 0.13);\n    constellation_gain.SetSatelliteToConstantGain(28, 0.10);\n    constellation_gain.SetSatelliteToConstantGain(32, 0.07);\n\n    std::cout << \"Num batches = \" << num_sample_batches << std::endl;\n    std::cout << \"samples_per_batch = \" << samples_per_batch << std::endl;\n    \n\tfor (int batch = 1; batch < num_sample_batches; batch++)\n\t{\n        // Per-channel gain, maximum value of 1.\n        std::array<double, MAX_CHAN> gain;\n\n\t\tfor (int i = 0; i < MAX_CHAN; i++)\n\t\t{\n\t\t\tif (chan[i].IsEnabled())\n\t\t\t{\n\t\t\t\t// Refresh code phase and data bit counters\n\t\t\t\tconst int sv_index = chan[i].prn-1;\n\n\t\t\t\t// Current pseudorange\n\t\t\t\tconst range_t rho = ComputeRange(eph[ieph][sv_index], ionoutc, \n                             current_simulation_time, e_pos_e_a);\n\n\t\t\t\tchan[i].azel = rho.azel;\n\n\t\t\t\t// Update code phase and data bit counters\n\t\t\t\tchan[i].ComputeCodePhase(rho, batch_period_s);\n\n\t\t\t\t// Signal gain.\n\t\t\t\tgain[i] = constellation_gain.ComputeGain(\n                    chan[i].prn, rho.d, rho.azel);\n\t\t\t}\n\t\t}\n\n\t\t// There is no intrinsic need to loop here, but we do so to avoid computing\n\t\t// the pseudorange too frequently.\n\t\tfor (int sample = 0; sample < samples_per_batch; sample++)\n\t\t{\n\t\t\tdouble i_acc = 0;\n\t\t\tdouble q_acc = 0;\n\n\t\t\tfor (int i = 0; i < MAX_CHAN; i++)\n\t\t\t{\n\t\t\t\tif (chan[i].IsEnabled())\n\t\t\t\t{\n                    const double coeff =\n                            chan[i].current_code_data_symbol() * gain[i];\n                    const double ip = coeff * \n                            cos_table.LookupValue(chan[i].carrier_phase_cycles);\n                    const double qp = coeff * \n                            sin_table.LookupValue(chan[i].carrier_phase_cycles);\n\n\t\t\t\t\t// Accumulate for all visible satellites.\n\t\t\t\t\ti_acc += ip;\n\t\t\t\t\tq_acc += qp;\n\n\t\t\t\t\t// Update code phase, including the code chip and data bit.\n\t\t\t\t\tchan[i].UpdateCodePhase(sample_period_s);\n\n\t\t\t\t\t// Update carrier phase\n\t\t\t\t\tchan[i].UpdateCarrierPhase(sample_period_s);\n\t\t\t\t}\n\t\t\t}\n\n            // At this point, the min and max values for the I- and Q- samples\n            // are -16 and +16 based on the number of satellites processed.\n            //\n            // We scale them to +/- 0.5 for the sample writer.\n            constexpr double kSampleScale = 1.0 / (2.0 * 16.0);\n            sample_writer.WriteSample(\n                    noise_generator.ScaleAndAddNoise(i_acc * kSampleScale),\n                    noise_generator.ScaleAndAddNoise(q_acc * kSampleScale));\n        }\n\n        //\n        // Update navigation message and channel allocation on 30s boundaries.\n        //\n\n        if (current_simulation_time.On30sBoundary())\n\t\t{\n\t\t\t// Update navigation message\n\t\t\tfor (int i = 0; i < MAX_CHAN; i++)\n\t\t\t{\n                if (chan[i].prn>0) {\n                    chan[i].GenerateNavMsg(current_simulation_time, 0);\n                }\n\t\t\t}\n\n\t\t\t// Refresh ephemeris and subframes\n\t\t\t// Quick and dirty fix. Need more elegant way.\n\t\t\tfor (int sv = 0; sv < MAX_SAT; sv++)\n\t\t\t{\n\t\t\t\tif (eph[ieph+1][sv].valid)\n\t\t\t\t{\n\t\t\t\t\tconst double dt = subGpsTime(eph[ieph+1][sv].toc, \n                                                 current_simulation_time);\n\t\t\t\t\tif (dt < SECONDS_IN_HOUR)\n\t\t\t\t\t{\n\t\t\t\t\t\tieph++;\n\t\t\t\t\t\tfor (int i = 0; i < MAX_CHAN; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Generate new subframes if allocated\n\t\t\t\t\t\t\tif (chan[i].IsEnabled()) { \n\t\t\t\t\t\t\t\tchan[i].SetEphemeris(eph[ieph][chan[i].prn-1], ionoutc);\n                            }\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Update channel allocation\n\t\t\tallocateChannel(chan, eph[ieph], allocatedSat, ionoutc, \n                            current_simulation_time, e_pos_e_a, elevation_mask_deg);\n\n\t\t\t// Show details about simulated channels\n\t\t\tif (verbose)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\tfor (int i = 0; i < MAX_CHAN; i++)\n\t\t\t\t{\n\t\t\t\t\tif (chan[i].prn>0)\n\t\t\t\t\t\tfprintf(stderr, \"%02d %6.1f %5.1f %11.1f %5.1f\\n\", chan[i].prn,\n\t\t\t\t\t\t\tchan[i].azel.azimuth_deg(), chan[i].azel.elevation_deg(),\n                            chan[i].rho0.d, chan[i].rho0.iono_delay);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Update receiver time\n\t\tcurrent_simulation_time = incGpsTime(current_simulation_time, batch_period_s);\n\n\t\t// Update time counter\n\t\tfprintf(stderr, \"\\rTime into run = %4.2f\", \n                subGpsTime(current_simulation_time, simulation_start_gps_time));\n\t\tfflush(stdout);\n\t}\n\n\ttend = clock();\n\n\tfprintf(stderr, \"\\nDone!\\n\");\n\n\t// Process time\n\tfprintf(stderr, \"Process time = %.1f [sec]\\n\", (double)(tend-tstart)/CLOCKS_PER_SEC);\n\n\treturn(0);\n}\n", "meta": {"hexsha": "e93ada92d350d3a39837e88838e5bede48d50d9c", "size": 19166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gpssim.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": "gpssim.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": "gpssim.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": 28.0204678363, "max_line_length": 110, "alphanum_fraction": 0.6066471877, "num_tokens": 5744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.5067387815295877}}
{"text": "#include <iostream>\n#include <vector>\n#include <boost/polygon/voronoi.hpp>\n#include <boost/polygon/polygon.hpp>\n\ntypedef boost::polygon::point_data<int> Point;\ntypedef boost::polygon::segment_data<int> Segment;\n\nint main(int argc, char** argv)\n{\n    std::vector<Point> points;\n    std::vector<Segment> segments;\n    points.push_back(Point(0, 0));\n    points.push_back(Point(1, 6));\n    segments.push_back(Segment(Point(-4, 5), Point(5, -1)));\n    segments.push_back(Segment(Point(3, -11), Point(13, -1)));\n    boost::polygon::voronoi_diagram<double> vd;\n    boost::polygon::construct_voronoi(\n        points.begin(),\n        points.end(),\n        segments.begin(),\n        segments.end(),\n        &vd);\n    return 0;\n}", "meta": {"hexsha": "945ce40af0851ec427054b7dd3eb7a2d620dbb7d", "size": 718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Planning/Voronoi/main.cpp", "max_stars_repo_name": "daniel-s-ingram/CppRobotics", "max_stars_repo_head_hexsha": "02d79d79705c801afb564e67c1083e96d69bbb86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2019-02-22T21:32:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T16:11:53.000Z", "max_issues_repo_path": "Planning/Voronoi/main.cpp", "max_issues_repo_name": "daniel-s-ingram/CppRobotics", "max_issues_repo_head_hexsha": "02d79d79705c801afb564e67c1083e96d69bbb86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Planning/Voronoi/main.cpp", "max_forks_repo_name": "daniel-s-ingram/CppRobotics", "max_forks_repo_head_hexsha": "02d79d79705c801afb564e67c1083e96d69bbb86", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-24T15:25:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-24T22:54:01.000Z", "avg_line_length": 28.72, "max_line_length": 62, "alphanum_fraction": 0.6532033426, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.5067387741282093}}
{"text": "#include <Eigen/Sparse>\n// system includes ------------------------------------------------------------\n#include <algorithm>\n#include <boost/program_options.hpp>\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n// own includes ---------------------------------------------------------------\n#include \"spectral/basis/spectral_basis_dimension_accessor.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"spectral/basis/spectral_elem_accessor.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n\nusing namespace std;\nusing namespace boltzmann;\nnamespace po = boost::program_options;\n\nconst int dim = 2;\n\nint main(int argc, char *argv[])\n{\n  int K;\n  double beta;\n  bool sorted;\n  po::options_description options(\"options\");\n  options.add_options()\n      (\"help\", \"produce help message\")(\"K\", po::value<int>(&K)->default_value(10))\n      (\"sorted\", po::value<bool>(&sorted)->default_value(true))\n      (\"beta\", po::value<double>(&beta)->default_value(2));\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    cout << options << \"\\n\";\n    return 1;\n  }\n\n  // ------------------------------------------------------------\n  typedef SpectralBasisFactoryKS::basis_type basis_type;\n  basis_type trial_basis;\n  SpectralBasisFactoryKS::create(trial_basis, K, K, beta, sorted);\n  typedef typename basis_type::elem_t elem_t;\n\n  // write to disk\n  SpectralBasisFactoryKS::write_basis_descriptor(trial_basis, \"spectral_basis.desc\");\n  basis_type test_basis;\n  SpectralBasisFactoryKS::create_test(test_basis, K, K, beta, sorted);\n  SpectralBasisFactoryKS::write_basis_descriptor(test_basis, \"spectral_basis_test.desc\");\n\n#if __cplusplus >= 201402\n  auto range = spectral::filter_freq(test_basis.begin(), test_basis.end(), 1);\n\n  for (auto it = std::get<0>(range); it != std::get<1>(range); it++) {\n    cout << it->id().to_string() << std::endl;\n  }\n#endif\n\n  return 0;\n}\n", "meta": {"hexsha": "962a84242175934da0ea30a897d5b5f263c5bb6a", "size": 2005, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/spectral_basis/main_filter.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/spectral_basis/main_filter.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/spectral_basis/main_filter.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": 31.8253968254, "max_line_length": 89, "alphanum_fraction": 0.6493765586, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5066405832675702}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013-2014 Mageswaran.D <mageswaran1989@gmail.com>\n//\n// Book Refered: OpenCL Programming Guide\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://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n//---------------------------------------------------------------------------//\n// About Sobel Filter:\n// * Edge Filter - distinguishes the differrent color region\n// * Finds the gradient in x and y-axes\n// * Three step process\n//   -> Find x-axis gradient with kernel/matrix\n//           Gx = [-1 0 +1]\n//                [-2 0 +2]\n//                [-1 0 +1]\n//   -> Find y-axis gradient with kernel/matrix\n//           Gy = [-1 -2 -1]\n//                [ 0  0  0]\n//                [+1 +2 +1]\n// * Gradient magnitude G = sqrt(Gx^2 + Gy^2)\n//---------------------------------------------------------------------------//\n\n#include <iostream>\n#include <string>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/interop/opencv/core.hpp>\n#include <boost/compute/interop/opencv/highgui.hpp>\n#include <boost/compute/utility/source.hpp>\n\n#include <boost/program_options.hpp>\n\nnamespace compute = boost::compute;\nnamespace po = boost::program_options;\n\n// Create sobel filter program\nconst char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE (\n    //For out of boundary pixels, edge pixel\n    // value is returned\n    const sampler_t sampler = CLK_ADDRESS_CLAMP_TO_EDGE |\n                              CLK_FILTER_NEAREST;\n    kernel void sobel_rgb(read_only image2d_t src, write_only image2d_t dst)\n    {\n        int x = (int)get_global_id(0);\n        int y = (int)get_global_id(1);\n\n        if (x >= get_image_width(src) || y >= get_image_height(src))\n                return;\n\n        //  [(x-1, y+1), (x, y+1), (x+1, y+1)]\n        //  [(x-1, y  ), (x, y  ), (x+1, y  )]\n        //  [(x-1, y-1), (x, y-1), (x+1, y-1)]\n\n        //  [p02, p12,   p22]\n        //  [p01, pixel, p21]\n        //  [p00, p10,   p20]\n\n        //Basically finding influence of neighbour pixels on current pixel\n        float4 p00 = read_imagef(src, sampler, (int2)(x - 1, y - 1));\n        float4 p10 = read_imagef(src, sampler, (int2)(x,     y - 1));\n        float4 p20 = read_imagef(src, sampler, (int2)(x + 1, y - 1));\n\n        float4 p01 = read_imagef(src, sampler, (int2)(x - 1, y));\n        //pixel that we are working on\n        float4 p21 = read_imagef(src, sampler, (int2)(x + 1, y));\n\n        float4 p02 = read_imagef(src, sampler, (int2)(x - 1, y + 1));\n        float4 p12 = read_imagef(src, sampler, (int2)(x,     y + 1));\n        float4 p22 = read_imagef(src, sampler, (int2)(x + 1, y + 1));\n\n        //Find Gx = kernel + 3x3 around current pixel\n        //           Gx = [-1 0 +1]     [p02, p12,   p22]\n        //                [-2 0 +2]  +  [p01, pixel, p21]\n        //                [-1 0 +1]     [p00, p10,   p20]\n        float3 gx = -p00.xyz + p20.xyz +\n                    2.0f * (p21.xyz - p01.xyz)\n                    -p02.xyz + p22.xyz;\n\n        //Find Gy = kernel + 3x3 around current pixel\n        //           Gy = [-1 -2 -1]     [p02, p12,   p22]\n        //                [ 0  0  0]  +  [p01, pixel, p21]\n        //                [+1 +2 +1]     [p00, p10,   p20]\n        float3 gy = p00.xyz + p20.xyz +\n                    2.0f * (- p12.xyz + p10.xyz) -\n                    p02.xyz - p22.xyz;\n        //Find G\n        float3 g = native_sqrt(gx * gx + gy * gy);\n\n        // we could also approximate this as g = fabs(gx) + fabs(gy)\n        write_imagef(dst, (int2)(x, y), (float4)(g.x, g.y, g.z, 1.0f));\n    }\n);\n\n// This example shows how to apply sobel filter on images or on camera frames\n// with OpenCV, transfer the frames to the GPU, and apply a sobel filter\n// written in OpenCL\nint main(int argc, char *argv[])\n{\n    ///////////////////////////////////////////////////////////////////////////\n\n    // setup the command line arguments\n    po::options_description desc;\n    desc.add_options()\n            (\"help\",  \"show available options\")\n            (\"camera\", po::value<int>()->default_value(-1),\n                                 \"if not default camera, specify a camera id\")\n            (\"image\", po::value<std::string>(), \"path to image file\");\n\n    // Parse the command lines\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    //check the command line arguments\n    if(vm.count(\"help\"))\n    {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n\n    //OpenCV variables\n    cv::Mat cv_mat;\n    cv::VideoCapture cap; //OpenCV camera handle.\n\n    //OpenCL variables\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    compute::program filter_program =\n            compute::program::create_with_source(source, context);\n\n    try\n    {\n        filter_program.build();\n    }\n    catch(compute::opencl_error e)\n    {\n        std::cout<<\"Build Error: \"<<std::endl\n                 <<filter_program.build_log();\n    }\n\n    // create fliter kernel and set arguments\n    compute::kernel filter_kernel(filter_program, \"sobel_rgb\");\n\n    ///////////////////////////////////////////////////////////////////////////\n\n    //check for image paths\n    if(vm.count(\"image\"))\n    {\n        // Read image with OpenCV\n        cv_mat = cv::imread(vm[\"image\"].as<std::string>(),\n                                       CV_LOAD_IMAGE_COLOR);\n        if(!cv_mat.data){\n            std::cerr << \"Failed to load image\" << std::endl;\n            return -1;\n        }\n    }\n    else //by default use camera\n    {\n        //open camera\n        cap.open(vm[\"camera\"].as<int>());\n        // read first frame\n        cap >> cv_mat;\n        if(!cv_mat.data){\n            std::cerr << \"failed to capture frame\" << std::endl;\n            return -1;\n        }\n    }\n\n    // Convert image to BGRA (OpenCL requires 16-byte aligned data)\n    cv::cvtColor(cv_mat, cv_mat, CV_BGR2BGRA);\n\n    // Transfer image/frame data to gpu\n    compute::image2d dev_input_image =\n            compute::opencv_create_image2d_with_mat(\n                cv_mat, compute::image2d::read_write, queue\n                );\n\n    // Create output image\n    // Be sure what will be your ouput image/frame size\n    compute::image2d dev_output_image(\n                context,\n                dev_input_image.width(),\n                dev_input_image.height(),\n                dev_input_image.format(),\n                compute::image2d::write_only\n                );\n\n    filter_kernel.set_arg(0, dev_input_image);\n    filter_kernel.set_arg(1, dev_output_image);\n\n\n    // run flip kernel\n    size_t origin[2] = { 0, 0 };\n    size_t region[2] = { dev_input_image.width(),\n                         dev_input_image.height() };\n\n    ///////////////////////////////////////////////////////////////////////////\n\n    queue.enqueue_nd_range_kernel(filter_kernel, 2, origin, region, 0);\n\n    //check for image paths\n    if(vm.count(\"image\"))\n    {\n        // show host image\n        cv::imshow(\"Original Image\", cv_mat);\n\n        // show gpu image\n        compute::opencv_imshow(\"Filtered Image\", dev_output_image, queue);\n\n        // wait and return\n        cv::waitKey(0);\n    }\n    else\n    {\n        char key = '\\0';\n        while(key != 27) //check for escape key\n        {\n            cap >> cv_mat;\n\n            // Convert image to BGRA (OpenCL requires 16-byte aligned data)\n            cv::cvtColor(cv_mat, cv_mat, CV_BGR2BGRA);\n\n            // Update the device image memory with current frame data\n            compute::opencv_copy_mat_to_image(cv_mat,\n                                              dev_input_image,queue);\n\n            // Run the kernel on the device\n            queue.enqueue_nd_range_kernel(filter_kernel, 2, origin, region, 0);\n\n            // Show host image\n            cv::imshow(\"Camera Frame\", cv_mat);\n\n            // Show GPU image\n            compute::opencv_imshow(\"Filtered RGB Frame\", dev_output_image, queue);\n\n            // wait\n            key = cv::waitKey(10);\n        }\n    }\n    return 0;\n}\n", "meta": {"hexsha": "4fcfa206704c0e470904a74127b90e304b2896c5", "size": 8571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/compute/example/opencv_sobel_filter.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/compute/example/opencv_sobel_filter.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/compute/example/opencv_sobel_filter.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": 33.6117647059, "max_line_length": 82, "alphanum_fraction": 0.5106755338, "num_tokens": 2148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.506640578676825}}
{"text": "/*\n * @file\n * @author University of Warwick\n * @version 1.0\n *\n * @section LICENSE\n *\n * @section DESCRIPTION\n *\n */\n\n#define BOOST_TEST_MODULE EuclideanVector\n#include <boost/test/unit_test.hpp>\n#include <boost/test/output_test_stream.hpp>\n#include <stdexcept>\n\n#include \"EuclideanVector.h\"\n#include \"EuclideanVector3D.h\"\n#include \"Error.h\"\n#include \"Broadcast.h\"\n#include <iostream>\n\nnamespace utf = boost::unit_test;\n\nusing namespace cupcfd::geometry::euclidean;\n\n// Setup\nBOOST_AUTO_TEST_CASE(setup)\n{\n    int argc = boost::unit_test::framework::master_test_suite().argc;\n    char ** argv = boost::unit_test::framework::master_test_suite().argv;\n\n    MPI_Init(&argc, &argv);\n}\n\n// === Constructor1 ===\n// Test 1: Check all values set to zero - 2D\nBOOST_AUTO_TEST_CASE(constructor1_test1)\n{\n\tEuclideanVector<double, 2> vec;\n\n\tBOOST_CHECK_EQUAL(vec.cmp[0], 0.0);\n\tBOOST_CHECK_EQUAL(vec.cmp[1], 0.0);\n\tBOOST_CHECK_EQUAL(vec.isRegistered(), false);\n}\n\n// Test 2: Check all values set to zero - 3D\nBOOST_AUTO_TEST_CASE(constructor1_test2)\n{\n\tEuclideanVector<double, 3> vec;\n\n\tBOOST_CHECK_EQUAL(vec.cmp[0], 0.0);\n\tBOOST_CHECK_EQUAL(vec.cmp[1], 0.0);\n\tBOOST_CHECK_EQUAL(vec.cmp[2], 0.0);\n\tBOOST_CHECK_EQUAL(vec.isRegistered(), false);\n}\n\n// === Constructor2 ===\n// Test 1: Check values set to match parameters - 2D\nBOOST_AUTO_TEST_CASE(constructor2_test1)\n{\n\tEuclideanVector<double, 2> vec(2.0, 3.0);\n\n\tBOOST_CHECK_EQUAL(vec.cmp[0], 2.0);\n\tBOOST_CHECK_EQUAL(vec.cmp[1], 3.0);\n\tBOOST_CHECK_EQUAL(vec.isRegistered(), false);\n}\n\n// Test 2: Check values set to match parameters - 3D\nBOOST_AUTO_TEST_CASE(constructor2_test2)\n{\n\tEuclideanVector<double, 3> vec(2.0, 3.0, 4.0);\n\n\tBOOST_CHECK_EQUAL(vec.cmp[0], 2.0);\n\tBOOST_CHECK_EQUAL(vec.cmp[1], 3.0);\n\tBOOST_CHECK_EQUAL(vec.cmp[2], 4.0);\n\tBOOST_CHECK_EQUAL(vec.isRegistered(), false);\n}\n\n\n// === Operator= Vector ===\n// Test 1: Check values are appropriately copied form src to dst - 2D\nBOOST_AUTO_TEST_CASE(operator_assign_vector_test1)\n{\n\tEuclideanVector<double, 2> srcVec(2.0, 3.0);\n\tEuclideanVector<double, 2> dstVec;\n\n\tdstVec = srcVec;\n\n\tsrcVec.cmp[1] = -15.0;\n\n\tBOOST_CHECK_EQUAL(dstVec.cmp[0], 2.0);\n\tBOOST_CHECK_EQUAL(dstVec.cmp[1], 3.0);\n}\n\n// Test 2: Check values are appropriately copied form src to dst - 3D\nBOOST_AUTO_TEST_CASE(operator_assign_vector_test2)\n{\n\tEuclideanVector<double, 3> srcVec(2.0, 3.0, 4.0);\n\tEuclideanVector<double, 3> dstVec;\n\n\tdstVec = srcVec;\n\n\tsrcVec.cmp[1] = -15.0;\n\n\tBOOST_CHECK_EQUAL(dstVec.cmp[0], 2.0);\n\tBOOST_CHECK_EQUAL(dstVec.cmp[1], 3.0);\n\tBOOST_CHECK_EQUAL(dstVec.cmp[2], 4.0);\n}\n\n// === Operator= Scalar ===\n// Test 1: Check values are all set to same as scalar - 2D\nBOOST_AUTO_TEST_CASE(operator_assign_scalar_test1)\n{\n\tEuclideanVector<double, 2> vec;\n\n\tvec = 5.0;\n\n\tBOOST_CHECK_EQUAL(vec.cmp[0], 5.0);\n\tBOOST_CHECK_EQUAL(vec.cmp[1], 5.0);\n}\n\n// Test 2: Check values are all set to same as scalar - 3D\nBOOST_AUTO_TEST_CASE(operator_assign_scalar_test2)\n{\n\tEuclideanVector<double, 3> vec;\n\n\tvec = 5.0;\n\n\tBOOST_CHECK_EQUAL(vec.cmp[0], 5.0);\n\tBOOST_CHECK_EQUAL(vec.cmp[1], 5.0);\n\tBOOST_CHECK_EQUAL(vec.cmp[2], 5.0);\n}\n\n// === operator== ===\n// Test 1: Test that vecs match\nBOOST_AUTO_TEST_CASE(operator_equivalence_test1)\n{\n\tEuclideanVector<double, 3> vec(1.0, 2.0, 3.0);\n\tEuclideanVector<double, 3> vec2(1.0, 2.0, 3.0);\n\n\tBOOST_CHECK_EQUAL(vec == vec2, true);\n}\n\n// Test 2: Test that vecs don't match\nBOOST_AUTO_TEST_CASE(operator_equivalence_test2)\n{\n\tEuclideanVector<double, 3> vec(1.0, 2.0, 3.0);\n\tEuclideanVector<double, 3> vec2(2.0, 2.0, 3.0);\n\tEuclideanVector<double, 3> vec3(1.0, 3.0, 3.0);\n\tEuclideanVector<double, 3> vec4(1.0, 2.0, 4.0);\n\n\tBOOST_CHECK_EQUAL(vec == vec2, false);\n\tBOOST_CHECK_EQUAL(vec == vec3, false);\n\tBOOST_CHECK_EQUAL(vec == vec4, false);\n}\n\n// === Operator+ Vector ===\n// Test 1: Check values are appropriately summed - 2D\nBOOST_AUTO_TEST_CASE(operator_add_vector_test1)\n{\n\tEuclideanVector<double, 2> vec1(5.0, 8.0);\n\tEuclideanVector<double, 2> vec2(1.2, 4.5);\n\n\tEuclideanVector<double, 2> vec3 = vec1 + vec2;\n\n\tBOOST_CHECK_EQUAL(vec3.cmp[0], 6.2);\n\tBOOST_CHECK_EQUAL(vec3.cmp[1], 12.5);\n}\n\n// Test 2: Check values are appropriately summed - 3D\nBOOST_AUTO_TEST_CASE(operator_add_vector_test2)\n{\n\tEuclideanVector<double, 3> vec1(5.0, 8.0, 9.5);\n\tEuclideanVector<double, 3> vec2(1.2, 4.5, 19.3);\n\n\tEuclideanVector<double, 3> vec3 = vec1 + vec2;\n\n\tBOOST_CHECK_EQUAL(vec3.cmp[0], 6.2);\n\tBOOST_CHECK_EQUAL(vec3.cmp[1], 12.5);\n\tBOOST_CHECK_EQUAL(vec3.cmp[2], 28.8);\n}\n\n// === Operator+ Scalar ===\n// Test 1: Check scalars are appropriately added when vector on left - 2D\nBOOST_AUTO_TEST_CASE(operator_add_scalar_test1)\n{\n\tEuclideanVector<double, 2> vec1(5.0, 8.0);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double, 2> vec3 = vec1 + scalar;\n\n\tBOOST_CHECK_EQUAL(vec3.cmp[0], 10.0);\n\tBOOST_CHECK_EQUAL(vec3.cmp[1], 13.0);\n}\n\n// Test 2: Check scalars are appropriately added when vector on right - 2D\nBOOST_AUTO_TEST_CASE(operator_add_scalar_test2)\n{\n\tEuclideanVector<double, 2> vec1(5.0, 8.0);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double, 2> vec3 = scalar + vec1;\n\n\tBOOST_CHECK_EQUAL(vec3.cmp[0], 10.0);\n\tBOOST_CHECK_EQUAL(vec3.cmp[1], 13.0);\n}\n\n\n// Test 3: Check scalars are appropriately added when vector on left - 3D\nBOOST_AUTO_TEST_CASE(operator_add_scalar_test3)\n{\n\tEuclideanVector<double, 3> vec1(5.0, 8.0, 9.5);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double, 3> vec3 = vec1 + scalar;\n\n\tBOOST_CHECK_EQUAL(vec3.cmp[0], 10.0);\n\tBOOST_CHECK_EQUAL(vec3.cmp[1], 13.0);\n\tBOOST_CHECK_EQUAL(vec3.cmp[2], 14.5);\n}\n\n// Test 4: Check scalars are appropriately added when vector on right - 3D\nBOOST_AUTO_TEST_CASE(operator_add_scalar_test4)\n{\n\tEuclideanVector<double, 3> vec1(5.0, 8.0, 9.5);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double, 3> vec3 = scalar + vec1;\n\n\tBOOST_CHECK_EQUAL(vec3.cmp[0], 10.0);\n\tBOOST_CHECK_EQUAL(vec3.cmp[1], 13.0);\n\tBOOST_CHECK_EQUAL(vec3.cmp[2], 14.5);\n}\n\n\n// === Operator- Vector ===\n// Test 1: Check values are appropriately subtracted - 2D\nBOOST_AUTO_TEST_CASE(operator_subtract_vector_test1)\n{\n\tEuclideanVector<double,2> vec1(5.0, 8.0);\n\tEuclideanVector<double,2> vec2(1.2, 4.5);\n\n\tEuclideanVector<double,2> vec3 = vec1 - vec2;\n\n\tBOOST_CHECK_EQUAL(vec3.cmp[0], 3.8);\n\tBOOST_CHECK_EQUAL(vec3.cmp[1], 3.5);\n}\n\n\n// Test 2: Check values are appropriately subtracted - 3D\nBOOST_AUTO_TEST_CASE(operator_subtract_vector_test2)\n{\n\tEuclideanVector<double,3> vec1(5.0, 8.0, 9.5);\n\tEuclideanVector<double,3> vec2(1.2, 4.5, 19.3);\n\n\tEuclideanVector<double,3> vec3 = vec1 - vec2;\n\n\tBOOST_CHECK_EQUAL(vec3.cmp[0], 3.8);\n\tBOOST_CHECK_EQUAL(vec3.cmp[1], 3.5);\n\tBOOST_CHECK_EQUAL(vec3.cmp[2], -9.8);\n}\n\n// === Operator- Scalar ===\n// Test 1: Check scalar values are subtracted when vector on left - 2D\nBOOST_AUTO_TEST_CASE(operator_subtract_scalar_minus_test1,  * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,2> vec1(5.0, 8.0);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double,2> vec3 = vec1 - scalar;\n\n\tBOOST_TEST(vec3.cmp[0] == 0.0);\n\tBOOST_TEST(vec3.cmp[1] == 3.0);\n}\n\n// Test 2: Check scalar values are subtracted when vector on right - 2D\nBOOST_AUTO_TEST_CASE(operator_subtract_scalar_minus_test2,  * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,2> vec1(5.0, 8.0);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double,2> vec3 = scalar - vec1;\n\n\tBOOST_TEST(vec3.cmp[0] == 0.0);\n\tBOOST_TEST(vec3.cmp[1] == -3.0);\n}\n\n\n// Test 3: Check scalar values are subtracted when vector on left - 3D\nBOOST_AUTO_TEST_CASE(operator_subtract_scalar_minus_test3,  * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,3> vec1(5.0, 8.0, 9.5);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double,3> vec3 = vec1 - scalar;\n\n\tBOOST_TEST(vec3.cmp[0] == 0.0);\n\tBOOST_TEST(vec3.cmp[1] == 3.0);\n\tBOOST_TEST(vec3.cmp[2] == 4.5);\n}\n\n// Test 4: Check scalar values are subtracted when vector on right - 3D\nBOOST_AUTO_TEST_CASE(operator_subtract_scalar_minus_test4,  * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,3> vec1(5.0, 8.0, 9.5);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double,3> vec3 = scalar - vec1;\n\n\tBOOST_TEST(vec3.cmp[0] == 0.0);\n\tBOOST_TEST(vec3.cmp[1] == -3.0);\n\tBOOST_TEST(vec3.cmp[2] == -4.5);\n}\n\n// === Operator* Scalar ===\n// Test 1: Check scalar values are multiplied when vector on left - 2D\nBOOST_AUTO_TEST_CASE(operator_subtract_scalar_multiply_test1,  * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,2> vec1(5.0, 8.0);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double,2> vec3 = vec1 * scalar;\n\n\tBOOST_TEST(vec3.cmp[0] == 25.0);\n\tBOOST_TEST(vec3.cmp[1] == 40.0);\n}\n\n// Test 2: Check scalar values are multiplied when vector on right - 2D\nBOOST_AUTO_TEST_CASE(operator_subtract_scalar_multiply_test2,  * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,2> vec1(5.0, 8.0);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double,2> vec3 = scalar * vec1;\n\n\tBOOST_TEST(vec3.cmp[0] == 25.0);\n\tBOOST_TEST(vec3.cmp[1] == 40.0);\n}\n\n// Test 3: Check scalar values are multiplied when vector on left - 3D\nBOOST_AUTO_TEST_CASE(operator_subtract_scalar_multiply_test3,  * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,3> vec1(5.0, 8.0, 9.5);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double,3> vec3 = vec1 * scalar;\n\n\tBOOST_TEST(vec3.cmp[0] == 25.0);\n\tBOOST_TEST(vec3.cmp[1] == 40.0);\n\tBOOST_TEST(vec3.cmp[2] == 47.5);\n}\n\n// Test 4: Check scalar values are multiplied when vector on right - 3D\nBOOST_AUTO_TEST_CASE(operator_subtract_scalar_multiply_test4,  * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,3> vec1(5.0, 8.0, 9.5);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double,3> vec3 = scalar * vec1;\n\n\tBOOST_TEST(vec3.cmp[0] == 25.0);\n\tBOOST_TEST(vec3.cmp[1] == 40.0);\n\tBOOST_TEST(vec3.cmp[2] == 47.5);\n}\n\n// === Operator/ Scalar ===\n// Test 1: Check scalar values are multiplied when vector on left - 2D\nBOOST_AUTO_TEST_CASE(operator_subtract_scalar_divide_test1,  * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,2> vec1(5.0, 10.0);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double,2> vec3 = vec1 / scalar;\n\n\tBOOST_TEST(vec3.cmp[0] == 1.0);\n\tBOOST_TEST(vec3.cmp[1] == 2.0);\n}\n\n// Test 2: Check scalar values are multiplied when vector on right - 2D\nBOOST_AUTO_TEST_CASE(operator_subtract_scalar_divide_test2,  * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,2> vec1(5.0, 10.0);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double,2> vec3 = scalar / vec1;\n\n\tBOOST_TEST(vec3.cmp[0] == 1.0);\n\tBOOST_TEST(vec3.cmp[1] == 0.5);\n}\n\n// Test 3: Check scalar values are multiplied when vector on left - 3D\nBOOST_AUTO_TEST_CASE(operator_subtract_scalar_divide_test3,  * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,3> vec1(5.0, 10.0, 9.5);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double,3> vec3 = vec1 / scalar;\n\n\tBOOST_TEST(vec3.cmp[0] == 1.0);\n\tBOOST_TEST(vec3.cmp[1] == 2.0);\n\tBOOST_TEST(vec3.cmp[2] == 1.9);\n}\n\n// Test 4: Check scalar values are multiplied when vector on left - 3D\nBOOST_AUTO_TEST_CASE(operator_subtract_scalar_divide_test4,  * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,3> vec1(5.0, 10.0, 9.5);\n\tdouble scalar = 5.0;\n\n\tEuclideanVector<double,3> vec3 = scalar / vec1;\n\n\tBOOST_TEST(vec3.cmp[0] == 1.0);\n\tBOOST_TEST(vec3.cmp[1] == 0.5);\n\tBOOST_TEST(vec3.cmp[2] == 0.526315789473684);\n}\n\n// === CrossProduct ===\n\n// Test 1: Check Cross-Product is computed correctly - 3D\nBOOST_AUTO_TEST_CASE(operator_crossproduct_test1, * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector3D<double> vec1(2.0, 3.0, 4.0);\n\tEuclideanVector3D<double> vec2(3.5, 6.3, 19.7);\n\tEuclideanVector3D<double> result;\n\n\tresult = vec1.crossProduct(vec2);\n\n\tBOOST_TEST(result.cmp[0] == 33.9);\n\tBOOST_TEST(result.cmp[1] == -25.4);\n\tBOOST_TEST(result.cmp[2] == 2.1);\n}\n\n// === rotateXAxisRadian ===\n// Test 1: Rotate a vector 1 radian\nBOOST_AUTO_TEST_CASE(rotateXAxisRadian_test1, * utf::tolerance(0.00001))\n{\n\tEuclideanVector3D<double> vec(1.4, -3.2, 5.6);\n\n\tvec.rotateXAxisRadian(1.0);\n\n\tBOOST_TEST(vec.cmp[0] == 1.4);\n\tBOOST_TEST(vec.cmp[1] == -6.4412);\n\tBOOST_TEST(vec.cmp[2] == 0.332986);\n}\n\n// Test 2: Rotate a vector 90 degrees/1.5708 radians\nBOOST_AUTO_TEST_CASE(rotateXAxisRadian_test2, * utf::tolerance(0.00001))\n{\n\tEuclideanVector3D<double> vec(0.0,1.0,0.0);\n\n\tvec.rotateXAxisRadian(1.5708);\n\n\tBOOST_TEST(vec.cmp[0] == 0.0);\n\tBOOST_TEST(vec.cmp[1] == 0.0);\n\tBOOST_TEST(vec.cmp[2] == 1.0);\n}\n\n// Test 3: Rotate a vector -90 degrees/-1.5708 radians\nBOOST_AUTO_TEST_CASE(rotateXAxisRadian_test3, * utf::tolerance(0.00001))\n{\n\tEuclideanVector3D<double> vec(0.0,1.0,0.0);\n\n\tvec.rotateXAxisRadian(-1.5708);\n\n\tBOOST_TEST(vec.cmp[0] == 0.0);\n\tBOOST_TEST(vec.cmp[1] == 0.0);\n\tBOOST_TEST(vec.cmp[2] == -1.0);\n}\n\n// === rotateYAxisRadian ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(rotateYAxisRadian_test1, * utf::tolerance(0.00001))\n{\n\tEuclideanVector3D<double> vec(1.4, -3.2, 5.6);\n\n\tvec.rotateYAxisRadian(1.0);\n\n\tBOOST_TEST(vec.cmp[0] == 5.46866);\n\tBOOST_TEST(vec.cmp[1] == -3.2);\n\tBOOST_TEST(vec.cmp[2] == 1.84763);\n}\n\n// Test 2: Rotate a vector 90 degrees/1.5708 radians\nBOOST_AUTO_TEST_CASE(rotateYAxisRadian_test2, * utf::tolerance(0.00001))\n{\n\tEuclideanVector3D<double> vec(1.0,0.0,0.0);\n\n\tvec.rotateYAxisRadian(1.5708);\n\n\tBOOST_TEST(vec.cmp[0] == 0.0);\n\tBOOST_TEST(vec.cmp[1] == 0.0);\n\tBOOST_TEST(vec.cmp[2] == -1.0);\n}\n\n// Test 3: Rotate a vector -90 degrees/1.5708 radians\nBOOST_AUTO_TEST_CASE(rotateYAxisRadian_test3, * utf::tolerance(0.00001))\n{\n\tEuclideanVector3D<double> vec(1.0,0.0,0.0);\n\n\tvec.rotateYAxisRadian(-1.5708);\n\n\tBOOST_TEST(vec.cmp[0] == 0.0);\n\tBOOST_TEST(vec.cmp[1] == 0.0);\n\tBOOST_TEST(vec.cmp[2] == 1.0);\n}\n\n// === rotateZAxisRadian ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(rotateZAxisRadian_test1, * utf::tolerance(0.00001))\n{\n\tEuclideanVector3D<double> vec(1.4, 3.2, 5.6);\n\n\tvec.rotateZAxisRadian(1.0);\n\n\tBOOST_TEST(vec.cmp[0] == -1.93629);\n\tBOOST_TEST(vec.cmp[1] == 2.90703);\n\tBOOST_TEST(vec.cmp[2] == 5.6);\n}\n\n// Test 2: Rotate a unit vector\nBOOST_AUTO_TEST_CASE(rotateZAxisRadian_test2, * utf::tolerance(0.00001))\n{\n\tEuclideanVector3D<double> vec(1.0,0.0,0.0);\n\n\tvec.rotateZAxisRadian(1.5708);\n\n\t// Vector was pointing along X axis, should now be pointing up along Y-axis\n\tBOOST_TEST(vec.cmp[0] == 0.0);\n\tBOOST_TEST(vec.cmp[1] == 1.0);\n\tBOOST_TEST(vec.cmp[2] == 0.0);\n}\n\n// Test 3: Rotate a unit vector\nBOOST_AUTO_TEST_CASE(rotateZAxisRadian_test3, * utf::tolerance(0.00001))\n{\n\tEuclideanVector3D<double> vec(1.0,0.0,0.0);\n\n\tvec.rotateZAxisRadian(-1.5708);\n\n\t// Vector was pointing along X axis, should now be pointing up along Y-axis\n\tBOOST_TEST(vec.cmp[0] == 0.0);\n\tBOOST_TEST(vec.cmp[1] == -1.0);\n\tBOOST_TEST(vec.cmp[2] == 0.0);\n}\n\n// === isParallel ===\n// Test 1: Test that parallel vectors detected - 2D\nBOOST_AUTO_TEST_CASE(isParallel_test1, * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,2> vec1(2.0, 3.0);\n\tEuclideanVector<double,2> vec2(4.0, 6.0);\n\n\tbool isParallel = vec1.isParallel(vec2);\n\tBOOST_CHECK_EQUAL(isParallel, true);\n}\n\n// Test 2: Test that parallel vectors detected even with inverted sign - 2D\nBOOST_AUTO_TEST_CASE(isParallel_test2, * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,2> vec1(2.0, 3.0);\n\tEuclideanVector<double,2> vec2(-4.0, -6.0);\n\n\tbool isParallel = vec1.isParallel(vec2);\n\tBOOST_CHECK_EQUAL(isParallel, true);\n}\n\n// Test 3: Test that parallel vectors detected - 3D\nBOOST_AUTO_TEST_CASE(isParallel_test3, * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,3> vec1(2.0, 3.0, 4.0);\n\tEuclideanVector<double,3> vec2(4.0, 6.0, 8.0);\n\n\tbool isParallel = vec1.isParallel(vec2);\n\tBOOST_CHECK_EQUAL(isParallel, true);\n}\n\n// Test 4: Test that non-parallel vectors identified correctly - 2D\nBOOST_AUTO_TEST_CASE(isParallel_test4, * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,2> vec1(2.0, 3.0);\n\tEuclideanVector<double,2> vec2(2.0, 3.5);\n\n\tbool isParallel = vec1.isParallel(vec2);\n\tBOOST_CHECK_EQUAL(isParallel, false);\n}\n\n// Test 5: Test that non-parallel vectors identified correctly - 3D\nBOOST_AUTO_TEST_CASE(isParallel_test5, * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,3> vec1(2.0, 3.0, 7.6);\n\tEuclideanVector<double,3> vec2(4.0, 6.0, 8.9);\n\n\tbool isParallel = vec1.isParallel(vec2);\n\tBOOST_CHECK_EQUAL(isParallel, false);\n}\n\n// Test 6: Test that parallel vectors detected even if first component is zero - 3D\nBOOST_AUTO_TEST_CASE(isParallel_test6, * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,3> vec1(0.0, 3.0, 4.0);\n\tEuclideanVector<double,3> vec2(0.0, 6.0, 8.0);\n\n\tbool isParallel = vec1.isParallel(vec2);\n\tBOOST_CHECK_EQUAL(isParallel, true);\n}\n\n// Test 7: Test that non-parallel vectors detected even if first component is zero - 3D\nBOOST_AUTO_TEST_CASE(isParallel_test7, * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,3> vec1(0.0, 3.0, 7.6);\n\tEuclideanVector<double,3> vec2(0.0, 6.0, 8.9);\n\n\tbool isParallel = vec1.isParallel(vec2);\n\tBOOST_CHECK_EQUAL(isParallel, false);\n}\n\n// Test 8: Test that parallel vectors detected even if non-first component is zero - 3D\nBOOST_AUTO_TEST_CASE(isParallel_test8, * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,3> vec1(2.0, 0.0, 4.0);\n\tEuclideanVector<double,3> vec2(4.0, 0.0, 8.0);\n\n\tbool isParallel = vec1.isParallel(vec2);\n\tBOOST_CHECK_EQUAL(isParallel, true);\n}\n\n// Test 9: Test that non-parallel vectors detected even if non-first component is zero - 3D\nBOOST_AUTO_TEST_CASE(isParallel_test9, * utf::tolerance(0.0000000001))\n{\n\tEuclideanVector<double,3> vec1(2.0, 0.0, 7.6);\n\tEuclideanVector<double,3> vec2(4.0, 0.0, 8.9);\n\n\tbool isParallel = vec1.isParallel(vec2);\n\tBOOST_CHECK_EQUAL(isParallel, false);\n}\n\n// === isPointOnLine ===\n// Test 1: Test that point is detected on the line\nBOOST_AUTO_TEST_CASE(isPointOnLine_test1, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(2.0, 3.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 6.0, 10.0);\n\tEuclideanPoint<double,3> point(3.0, 4.5, 7.5);\n\n\tbool isPointOnLine = cupcfd::geometry::euclidean::isPointOnLine(x1, x2, point);\n\tBOOST_CHECK_EQUAL(isPointOnLine, true);\n}\n\n// Test 2: Test that x1 is detected as on the line\nBOOST_AUTO_TEST_CASE(isPointOnLine_test2, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(2.0, 3.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 6.0, 10.0);\n\n\tbool isPointOnLine = cupcfd::geometry::euclidean::isPointOnLine(x1, x2, x1);\n\tBOOST_CHECK_EQUAL(isPointOnLine, true);\n}\n\n// Test 3: Test that x2 is detected as on the line\nBOOST_AUTO_TEST_CASE(isPointOnLine_test3, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(2.0, 3.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 6.0, 10.0);\n\n\tbool isPointOnLine = cupcfd::geometry::euclidean::isPointOnLine(x1, x2, x2);\n\tBOOST_CHECK_EQUAL(isPointOnLine, true);\n}\n\n// Test 4: Test that a point not on the line is detected as such\nBOOST_AUTO_TEST_CASE(isPointOnLine_test4, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(2.0, 3.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 6.0, 10.0);\n\tEuclideanPoint<double,3> point(2.0, 3.0, 8.12);\n\n\tbool isPointOnLine = cupcfd::geometry::euclidean::isPointOnLine(x1, x2, point);\n\tBOOST_CHECK_EQUAL(isPointOnLine, false);\n}\n\n// Test 1: Test that point is detected on the line when there is a zero component to the vector (i.e. on a axis plane)\nBOOST_AUTO_TEST_CASE(isPointOnLine_test5, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(2.0, 3.0, 5.0);\n\tEuclideanPoint<double,3> x2(2.0, 6.0, 10.0);\n\tEuclideanPoint<double,3> point(2.0, 4.5, 7.5);\n\n\tbool isPointOnLine = cupcfd::geometry::euclidean::isPointOnLine(x1, x2, point);\n\tBOOST_CHECK_EQUAL(isPointOnLine, true);\n}\n\n// === isVectorRangeIntersection (3D) ===\n// Test 1: Test that two vectors are detected as intersecting - 3D\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test1, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(7.0, 8.0, 6.0);\n\tEuclideanPoint<double,3> x3(7.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x4(3.0, 8.0, 6.0);\n\n\t// Should Intersect at 5.0, 6.0, 5.5\n\tbool intersect = cupcfd::geometry::euclidean::isVectorRangeIntersection(x1, x2, x3, x4);\n\tBOOST_CHECK_EQUAL(intersect, true);\n}\n\n// Test 2: Test two vectors that are not coplanar so don't intersect - 3D\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test2, * utf::tolerance(0.0000000001))\n{\n\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(7.0, 8.0, 6.0);\n\tEuclideanPoint<double,3> x3(7.0, 4.0, 1.3);\n\tEuclideanPoint<double,3> x4(3.0, 8.0, 3.4);\n\n\tbool intersect = cupcfd::geometry::euclidean::isVectorRangeIntersection(x1, x2, x3, x4);\n\n\tBOOST_CHECK_EQUAL(intersect, false);\n}\n\n// Test 3: Test that two vectors would intersect, but don't because the range of vector 1 is too short - 3D\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test3, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 5.25);\n\tEuclideanPoint<double,3> x3(7.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x4(3.0, 8.0, 6.0);\n\n\tbool intersect = cupcfd::geometry::euclidean::isVectorRangeIntersection(x1, x2, x3, x4);\n\tBOOST_CHECK_EQUAL(intersect, false);\n}\n\n// Test 4: Test that two vectors would intersect, but don't because the range of vector 2 is too short - 3D\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test4, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(7.0, 8.0, 6.0);\n\tEuclideanPoint<double,3> x3(4.0, 7.0, 5.75);\n\tEuclideanPoint<double,3> x4(3.0, 8.0, 6.0);\n\n\tbool intersect = cupcfd::geometry::euclidean::isVectorRangeIntersection(x1, x2, x3, x4);\n\tBOOST_CHECK_EQUAL(intersect, false);\n}\n\n// Test 5: Test two vectors that are coplanar but the intersect point is outside both ranges\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test5, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 5.25);\n\tEuclideanPoint<double,3> x3(4.0, 7.0, 5.75);\n\tEuclideanPoint<double,3> x4(3.0, 8.0, 6.0);\n\n\tbool intersect = cupcfd::geometry::euclidean::isVectorRangeIntersection(x1, x2, x3, x4);\n\tBOOST_CHECK_EQUAL(intersect, false);\n}\n\n// Test 6: Test that two lines that are colinear but don't overlap so don't intersect - 3D\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test6, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 6.0);\n\n\tEuclideanPoint<double,3> x3(9.0, 10.0, 11.0);\n\tEuclideanPoint<double,3> x4(15.0, 16.0, 17.0);\n\n\tbool intersect = cupcfd::geometry::euclidean::isVectorRangeIntersection(x1, x2, x3, x4);\n\tBOOST_CHECK_EQUAL(intersect, false);\n}\n\n// Test 7: Test that two lines that are colinear and do overlap are considered as intersecting - 3D\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test7, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 6.0);\n\n\tEuclideanPoint<double,3> x3(3.5, 4.5, 5.5);\n\tEuclideanPoint<double,3> x4(15.0, 16.0, 17.0);\n\n\tbool intersect = cupcfd::geometry::euclidean::isVectorRangeIntersection(x1, x2, x3, x4);\n\tBOOST_CHECK_EQUAL(intersect, true);\n}\n\n// Test 8: Test two vectors that are parallel but never overlap\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test8, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 6.0);\n\n\tEuclideanPoint<double,3> x3(6.0, 7.8, 2.3);\n\tEuclideanPoint<double,3> x4(7.0, 8.8, 3.3);\n\n\tbool intersect = cupcfd::geometry::euclidean::isVectorRangeIntersection(x1, x2, x3, x4);\n\tBOOST_CHECK_EQUAL(intersect, false);\n}\n\n// Test 9: Test that two lines that are colinear but don't overlap so don't intersect (one is in opposite direction) - 3D\n// ToDo: This test case fails: Detects as colinear but thinks they overlap?\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test9, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 6.0);\n\n\tEuclideanPoint<double,3> x3(15.0, 16.0, 17.0);\n\tEuclideanPoint<double,3> x4(9.0, 10.0, 11.0);\n\n\tbool intersect = cupcfd::geometry::euclidean::isVectorRangeIntersection(x1, x2, x3, x4);\n\tBOOST_CHECK_EQUAL(intersect, false);\n}\n\n// Test 10: Test that two lines that are colinear and do overlap are considered as intersecting (one is in opposite direction) - 3D\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test10, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 6.0);\n\n\tEuclideanPoint<double,3> x3(15.0, 16.0, 17.0);\n\tEuclideanPoint<double,3> x4(3.5, 4.5, 5.5);\n\n\tbool intersect = cupcfd::geometry::euclidean::isVectorRangeIntersection(x1, x2, x3, x4);\n\tBOOST_CHECK_EQUAL(intersect, true);\n}\n\n// Test 11: Both ranges are just the same point\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test11, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(3.0, 4.0, 5.0);\n\n\tEuclideanPoint<double,3> x3(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x4(3.0, 4.0, 5.0);\n\n\tbool intersect = cupcfd::geometry::euclidean::isVectorRangeIntersection(x1, x2, x3, x4);\n\tBOOST_CHECK_EQUAL(intersect, true);\n}\n\n// Test 12: Both ranges are just points, but not the same point\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test12, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(3.0, 4.0, 5.0);\n\n\tEuclideanPoint<double,3> x3(4.0, 5.0, 7.0);\n\tEuclideanPoint<double,3> x4(4.0, 5.0, 7.0);\n\n\tbool intersect = cupcfd::geometry::euclidean::isVectorRangeIntersection(x1, x2, x3, x4);\n\tBOOST_CHECK_EQUAL(intersect, false);\n}\n\n// Test 13: Range 1 is a point, Range 2 is a line, the point does not lie on the line\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test13, * utf::tolerance(0.0000000001))\n{\n\n}\n\n// Test 14: Range 1 is a point, Range 2 is a line, the point does lie on the line\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test14, * utf::tolerance(0.0000000001))\n{\n\n}\n\n// Test 15: Range 2 is a point, Range 1 is a line, the point does not lie on the line\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test15, * utf::tolerance(0.0000000001))\n{\n\n}\n\n// Test 16: Range 2 is a point, Range 1 is a line, the point does lie on the line\nBOOST_AUTO_TEST_CASE(isVectorRangeIntersection_test16, * utf::tolerance(0.0000000001))\n{\n\n}\n\n// === computeVectorRangeIntersection ===\n// Test 1: Test that two vectors are detected as intersecting - 3D\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test1, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(7.0, 8.0, 6.0);\n\tEuclideanPoint<double,3> x3(7.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x4(3.0, 8.0, 6.0);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\t// Should Intersect at 5.0, 6.0, 5.5\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_TEST(intersectPoint.cmp[0] == 5.0);\n\tBOOST_TEST(intersectPoint.cmp[1] == 6.0);\n\tBOOST_TEST(intersectPoint.cmp[2] == 5.5);\n}\n\n// Test 2: Test two vectors that are not coplanar so don't intersect - 3D\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test2, * utf::tolerance(0.0000000001))\n{\n\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(7.0, 8.0, 6.0);\n\tEuclideanPoint<double,3> x3(7.0, 4.0, 1.3);\n\tEuclideanPoint<double,3> x4(3.0, 8.0, 3.4);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_GEOMETRY_NO_INTERSECT);\n}\n\n// Test 3: Test that two vectors would intersect, but don't because the range of vector 1 is too short - 3D\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test3, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 5.25);\n\tEuclideanPoint<double,3> x3(7.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x4(3.0, 8.0, 6.0);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_GEOMETRY_NO_INTERSECT);\n}\n\n// Test 4: Test that two vectors would intersect, but don't because the range of vector 2 is too short - 3D\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test4, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(7.0, 8.0, 6.0);\n\tEuclideanPoint<double,3> x3(4.0, 7.0, 5.75);\n\tEuclideanPoint<double,3> x4(3.0, 8.0, 6.0);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_GEOMETRY_NO_INTERSECT);\n}\n\n// Test 5: Test two vectors that are coplanar but the intersect point is outside both ranges\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test5, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 5.25);\n\tEuclideanPoint<double,3> x3(4.0, 7.0, 5.75);\n\tEuclideanPoint<double,3> x4(3.0, 8.0, 6.0);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_GEOMETRY_NO_INTERSECT);\n}\n\n// Test 6: Test that two lines that are colinear but don't overlap so don't intersect - 3D\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test6, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 6.0);\n\tEuclideanPoint<double,3> x3(9.0, 10.0, 11.0);\n\tEuclideanPoint<double,3> x4(15.0, 16.0, 17.0);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_GEOMETRY_NO_INTERSECT);\n}\n\n// Test 7: Test that two lines that are colinear and do overlap are considered as intersecting - 3D\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test7, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 6.0);\n\tEuclideanPoint<double,3> x3(3.5, 4.5, 5.5);\n\tEuclideanPoint<double,3> x4(15.0, 16.0, 17.0);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_TEST(intersectPoint.cmp[0] == 3.5);\n\tBOOST_TEST(intersectPoint.cmp[1] == 4.5);\n\tBOOST_TEST(intersectPoint.cmp[2] == 5.5);\n}\n\n// Test 8: Test two vectors that are parallel but never overlap\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test8, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 6.0);\n\tEuclideanPoint<double,3> x3(6.0, 7.8, 2.3);\n\tEuclideanPoint<double,3> x4(7.0, 8.8, 3.3);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_GEOMETRY_NO_INTERSECT);\n}\n\n// Test 9: Test that two lines that are colinear but don't overlap so don't intersect (one is in opposite direction) - 3D\n// ToDo: This test case fails: Detects as colinear but thinks they overlap?\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test9, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 6.0);\n\tEuclideanPoint<double,3> x3(15.0, 16.0, 17.0);\n\tEuclideanPoint<double,3> x4(9.0, 10.0, 11.0);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_GEOMETRY_NO_INTERSECT);\n}\n\n// Test 10: Test that two lines that are colinear and do overlap are considered as intersecting (one is in opposite direction) - 3D\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test10, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(4.0, 5.0, 6.0);\n\tEuclideanPoint<double,3> x3(15.0, 16.0, 17.0);\n\tEuclideanPoint<double,3> x4(3.5, 4.5, 5.5);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_TEST(intersectPoint.cmp[0] == 3.5);\n\tBOOST_TEST(intersectPoint.cmp[1] == 4.5);\n\tBOOST_TEST(intersectPoint.cmp[2] == 5.5);\n}\n\n// Test 11: Both ranges are just the same point\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test11, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x3(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x4(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_TEST(intersectPoint.cmp[0] == 3.0);\n\tBOOST_TEST(intersectPoint.cmp[1] == 4.0);\n\tBOOST_TEST(intersectPoint.cmp[2] == 5.0);\n}\n\n// Test 12: Both ranges are just points, but not the same point\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test12, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x2(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x3(4.0, 5.0, 7.0);\n\tEuclideanPoint<double,3> x4(4.0, 5.0, 7.0);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_GEOMETRY_NO_INTERSECT);\n}\n\n// Test 13: Range 1 is a point, Range 2 is a line, the point does not lie on the line\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test13, * utf::tolerance(0.0000000001))\n{\n\n}\n\n// Test 14: Range 1 is a point, Range 2 is a line, the point does lie on the line\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test14, * utf::tolerance(0.0000000001))\n{\n\n}\n\n// Test 15: Range 2 is a point, Range 1 is a line, the point does not lie on the line\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test15, * utf::tolerance(0.0000000001))\n{\n\n}\n\n// Test 16: Range 2 is a point, Range 1 is a line, the point does lie on the line\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test16, * utf::tolerance(0.0000000001))\n{\n\n}\n\n// Test 17: Correct intersection when higher range is listed first in overlapping colinear setup of oposite directions\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test17, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(15.0, 16.0, 17.0);\n\tEuclideanPoint<double,3> x2(3.5, 4.5, 5.5);\n\tEuclideanPoint<double,3> x3(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x4(4.0, 5.0, 6.0);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_TEST(intersectPoint.cmp[0] == 3.5);\n\tBOOST_TEST(intersectPoint.cmp[1] == 4.5);\n\tBOOST_TEST(intersectPoint.cmp[2] == 5.5);\n}\n\n// Test 18: Correct intersection when higher range is listed first in overlapping colinear setup\nBOOST_AUTO_TEST_CASE(computeVectorRangeIntersection_test18, * utf::tolerance(0.0000000001))\n{\n\tEuclideanPoint<double,3> x1(3.5, 4.5, 5.5);\n\tEuclideanPoint<double,3> x2(15.0, 16.0, 17.0);\n\tEuclideanPoint<double,3> x3(3.0, 4.0, 5.0);\n\tEuclideanPoint<double,3> x4(4.0, 5.0, 6.0);\n\tEuclideanPoint<double,3> intersectPoint;\n\n\tcupcfd::error::eCodes status = cupcfd::geometry::euclidean::computeVectorRangeIntersection(x1, x2, x3, x4, intersectPoint);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_TEST(intersectPoint.cmp[0] == 4.0);\n\tBOOST_TEST(intersectPoint.cmp[1] == 5.0);\n\tBOOST_TEST(intersectPoint.cmp[2] == 6.0);\n}\n\n// === DotProduct ===\n\n// Test 1: Test correct dot product - 2D\nBOOST_AUTO_TEST_CASE(dotproduct_test1, * utf::tolerance(0.01))\n{\n\tEuclideanVector<double,2> vec1(2.0, 3.0);\n\tEuclideanVector<double,2> vec2(3.5, 6.3);\n\tdouble result = vec1.dotProduct(vec2);\n\n\tBOOST_TEST(result == 25.9);\n}\n\n// Test 2: Test correct dot product - 3D\nBOOST_AUTO_TEST_CASE(dotproduct_test2, * utf::tolerance(0.01))\n{\n\tEuclideanVector<double,3> vec1(2.0, 3.0, 4.0);\n\tEuclideanVector<double,3> vec2(3.5, 6.3, 19.7);\n\tdouble result = vec1.dotProduct(vec2);\n\n\tBOOST_TEST(result == 104.7);\n}\n\n// === length ===\n// Test 1: Test correct length compute, double - 2D\nBOOST_AUTO_TEST_CASE(length_test1, * utf::tolerance(0.00001))\n{\n\tEuclideanVector<double,2> vec1(3.5, 6.3);\n\tdouble length = vec1.length();\n\tBOOST_TEST(length == 7.20694);\n}\n\n// Test 2: Test correct length compute, double - 3D\nBOOST_AUTO_TEST_CASE(length_test2, * utf::tolerance(0.0001))\n{\n\tEuclideanVector<double,3> vec1(3.5, 6.3, 19.7);\n\tdouble length = vec1.length();\n\tBOOST_TEST(length == 20.9769);\n}\n\n// === normalise ===\n// Test 1: Test in-place normalisation - 2D\nBOOST_AUTO_TEST_CASE(normalise_test1, * utf::tolerance(0.000001))\n{\n\t// Setup\n\tEuclideanVector<double,2> vec(3.5, 6.3);\n\tvec.normalise();\n\tBOOST_TEST(vec.cmp[0] == 0.485643);\n\tBOOST_TEST(vec.cmp[1] == 0.874157);\n}\n\n// Test 2: Test in-place normalisation - 3D\nBOOST_AUTO_TEST_CASE(normalise_test2, * utf::tolerance(0.00001))\n{\n\t// Setup\n\tEuclideanVector<double,3> vec(3.5, 6.3, 19.7);\n\tvec.normalise();\n\tBOOST_TEST(vec.cmp[0] == 0.16685);\n\tBOOST_TEST(vec.cmp[1] == 0.30033);\n\tBOOST_TEST(vec.cmp[2] == 0.939129);\n}\n\n// === computeOrthagonalVector ===\n// Test 1: Compute Orthagonal Vector\nBOOST_AUTO_TEST_CASE(computeOrthagonalVector_test1, * utf::tolerance(0.00001))\n{\n\tEuclideanVector<double,3> vec1(3.5, 6.3, 19.7);\n\n\tEuclideanVector<double,3> vec2 = vec1.computeOrthagonalVector();\n\n\t// Since the solution could technically be one of many things, test using dot product\n\tdouble dotProd = vec1.dotProduct(vec2);\n\tBOOST_TEST(dotProd == 0.0);\n}\n\n// Test 2: Compute Orthagonal Vector when first component of vector is Zero\n// (I.e. should use another position as the unknown coefficient)\nBOOST_AUTO_TEST_CASE(computeOrthagonalVector_test2, * utf::tolerance(0.00001))\n{\n\tEuclideanVector<double,3> vec1(0.0, 6.3, 19.7);\n\n\tEuclideanVector<double,3> vec2 = vec1.computeOrthagonalVector();\n\n\t// Since the solution could technically be one of many things, test using dot product\n\tdouble dotProd = vec1.dotProduct(vec2);\n\tBOOST_TEST(dotProd == 0.0);\n}\n\n// === isRegistered ===\n// Not sure quite where to/when to place this test....\n// Should use a setter/getter to set/get registered?\n\n// === register and deregisterMPIType ===\n// Test 1: Test that Type is registered without error, and can be deregistered without error\nBOOST_AUTO_TEST_CASE(registerMPIType_test1, * utf::tolerance(0.00001))\n{\n\tcupcfd::error::eCodes status;\n\tEuclideanVector<double,3> vec;\n\n\tstatus = vec.registerMPIType();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tstatus = vec.deregisterMPIType();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n}\n\n// Test 2: Test that if it is already registered, it does not register again\nBOOST_AUTO_TEST_CASE(registerMPIType_test2, * utf::tolerance(0.00001))\n{\n\tcupcfd::error::eCodes status;\n\tEuclideanVector<double,3> vec;\n\n\tstatus = vec.registerMPIType();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tstatus = vec.registerMPIType();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_MPI_DATATYPE_REGISTERED);\n\n\t// Cleanup for future tests since we use a static variable!\n\tstatus = vec.deregisterMPIType();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n}\n\n// Test 3: Test that if unregistered, we cannot deregister again\nBOOST_AUTO_TEST_CASE(registerMPIType_test3, * utf::tolerance(0.00001))\n{\n\tcupcfd::error::eCodes status;\n\tEuclideanVector<double,3> vec;\n\n\tBOOST_CHECK_EQUAL(vec.isRegistered(), false);\n\tstatus = vec.deregisterMPIType();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_MPI_DATATYPE_UNREGISTERED);\n}\n\n// === getMPIType ===\n// Test 1: Test that corrected ID is returned for the registered type with error code\nBOOST_AUTO_TEST_CASE(getMPIType_test1, * utf::tolerance(0.00001))\n{\n\tcupcfd::error::eCodes status;\n\tEuclideanVector<double,3> vec;\n\tMPI_Datatype dType;\n\n\tstatus = vec.registerMPIType();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tstatus = vec.getMPIType(&dType);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Cleanup for future tests since we use a static variable!\n\tstatus = vec.deregisterMPIType();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n}\n\n// Test 2: Test error case detected when type unregistered\nBOOST_AUTO_TEST_CASE(getMPIType_test2, * utf::tolerance(0.00001))\n{\n\tcupcfd::error::eCodes status;\n\tEuclideanVector<double,3> vec;\n\tMPI_Datatype dType;\n\n\tBOOST_CHECK_EQUAL(vec.isRegistered(), false);\n\tstatus = vec.getMPIType(&dType);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_MPI_DATATYPE_UNREGISTERED);\n}\n\n// Test 3: Test corrected ID is returned for method without error code\nBOOST_AUTO_TEST_CASE(getMPIType_test3, * utf::tolerance(0.00001))\n{\n\n}\n\n// === MPI: Vector Broadcast ===\n// Test 1: Testing the the MPI Type was setup correctly, and able to broadcast two vectors\n// This should establish that the custom MPI type has the right sizes\nBOOST_AUTO_TEST_CASE(MPIVectorBroadcast)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create Two Vectors on Rank 0\n\n\t// Register the type (only once per all tests in file since static?)\n\tEuclideanVector<double,3> vec;\n\n\t// Should not yet be registered\n\tBOOST_CHECK_EQUAL(vec.isRegistered(), false);\n\n\t// Register\n\tstatus = vec.registerMPIType();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Should now be registered\n\tBOOST_CHECK_EQUAL(vec.isRegistered(), true);\n\n\tif(comm.rank == 0)\n\t{\n\t\tEuclideanVector<double,3> vecs[2] = {EuclideanVector<double,3>(3.5, 6.3, 19.7),\n\t\t\t\t\t\t\t\t\t\t\t EuclideanVector<double,3>(3.0, 4.5, 6.7)};\n\n\t\tstatus = cupcfd::comm::Broadcast(vecs, 2, 0, comm);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\telse\n\t{\n\t\tEuclideanVector<double,3> recvVecs[2];\n\n\t\tstatus = cupcfd::comm::Broadcast(recvVecs, 2, 0, comm);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tBOOST_CHECK_EQUAL(recvVecs[0].cmp[0], 3.5);\n\t\tBOOST_CHECK_EQUAL(recvVecs[0].cmp[1], 6.3);\n\t\tBOOST_CHECK_EQUAL(recvVecs[0].cmp[2], 19.7);\n\n\t\tBOOST_CHECK_EQUAL(recvVecs[1].cmp[0], 3.0);\n\t\tBOOST_CHECK_EQUAL(recvVecs[1].cmp[1], 4.5);\n\t\tBOOST_CHECK_EQUAL(recvVecs[1].cmp[2], 6.7);\n\t}\n\n\t// Cleanup for future tests since we use a static variable!\n\tstatus = vec.deregisterMPIType();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n}\n\n\nBOOST_AUTO_TEST_CASE(cleanup)\n{\n    MPI_Finalize();\n}\n\n", "meta": {"hexsha": "eaec37eada454780dfdf04c4d552b87c90b5b2b2", "size": 43056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/geometry/euclidean/implementation/component/EuclideanVectorTests.cpp", "max_stars_repo_name": "thorbenlouw/CUP-CFD", "max_stars_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T10:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T14:43:19.000Z", "max_issues_repo_path": "tests/geometry/euclidean/implementation/component/EuclideanVectorTests.cpp", "max_issues_repo_name": "thorbenlouw/CUP-CFD", "max_issues_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T15:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T14:27:28.000Z", "max_forks_repo_path": "tests/geometry/euclidean/implementation/component/EuclideanVectorTests.cpp", "max_forks_repo_name": "thorbenlouw/CUP-CFD", "max_forks_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T15:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T15:24:24.000Z", "avg_line_length": 32.421686747, "max_line_length": 131, "alphanum_fraction": 0.7286324786, "num_tokens": 15028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5066405740860798}}
{"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   testGaussianFactorGraphUnordered.cpp\n *  @brief  Unit tests for Linear Factor Graph\n *  @author Christian Potthast\n *  @author Frank Dellaert\n *  @author Luca Carlone\n *  @author Richard Roberts\n **/\n\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/GaussianConditional.h>\n#include <gtsam/linear/GaussianBayesNet.h>\n#include <gtsam/inference/VariableSlots.h>\n#include <gtsam/inference/VariableIndex.h>\n#include <gtsam/base/debug.h>\n#include <gtsam/base/VerticalBlockMatrix.h>\n\n#include <boost/assign/list_of.hpp>\n#include <boost/assign/std/list.hpp>  // for operator +=\nusing namespace boost::assign;\n\n#include <gtsam/base/TestableAssertions.h>\n#include <CppUnitLite/TestHarness.h>\n\nusing namespace std;\nusing namespace gtsam;\n\ntypedef std::tuple<size_t, size_t, double> SparseTriplet;\nbool triplet_equal(SparseTriplet a, SparseTriplet b) {\n  if (get<0>(a) == get<0>(b) && get<1>(a) == get<1>(b) &&\n      get<2>(a) == get<2>(b)) return true;\n\n  cout << \"not equal:\" << endl;\n  cout << \"\\texpected: \"\n      \"(\" << get<0>(a) << \", \" << get<1>(a) << \") = \" << get<2>(a) << endl;\n  cout << \"\\tactual:   \"\n      \"(\" << get<0>(b) << \", \" << get<1>(b) << \") = \" << get<2>(b) << endl;\n  return false;\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, initialization) {\n  // Create empty graph\n  GaussianFactorGraph fg;\n  SharedDiagonal unit2 = noiseModel::Unit::Create(2);\n\n  fg +=\n    JacobianFactor(0, 10*I_2x2, -1.0*Vector::Ones(2), unit2),\n    JacobianFactor(0, -10*I_2x2,1, 10*I_2x2, Vector2(2.0, -1.0), unit2),\n    JacobianFactor(0, -5*I_2x2, 2, 5*I_2x2, Vector2(0.0, 1.0), unit2),\n    JacobianFactor(1, -5*I_2x2, 2, 5*I_2x2, Vector2(-1.0, 1.5), unit2);\n\n  EXPECT_LONGS_EQUAL(4, (long)fg.size());\n\n  // Test sparse, which takes a vector and returns a matrix, used in MATLAB\n  // Note that this the augmented vector and the RHS is in column 7\n  Matrix expectedIJS =\n      (Matrix(3, 21) <<\n      1., 2., 1., 2., 3., 4., 3., 4., 3., 4., 5., 6., 5., 6., 6., 7., 8., 7., 8., 7., 8.,\n      1., 2., 7., 7., 1., 2., 3., 4., 7., 7., 1., 2., 5., 6., 7., 3., 4., 5., 6., 7., 7.,\n      10., 10., -1., -1., -10., -10., 10., 10., 2., -1., -5., -5., 5., 5.,\n        1., -5., -5., 5., 5., -1., 1.5).finished();\n  Matrix actualIJS = fg.sparseJacobian_();\n  EQUALITY(expectedIJS, actualIJS);\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, sparseJacobian) {\n  // Create factor graph:\n  // x1 x2 x3 x4 x5  b\n  //  1  2  3  0  0  4\n  //  5  6  7  0  0  8\n  //  9 10  0 11 12 13\n  //  0  0  0 14 15 16\n\n  // Expected\n  Matrix expected = (Matrix(16, 3) <<\n      1., 1., 2.,\n      1., 2., 4.,\n      1., 3., 6.,\n      2., 1.,10.,\n      2., 2.,12.,\n      2., 3.,14.,\n      1., 6., 8.,\n      2., 6.,16.,\n      3., 1.,18.,\n      3., 2.,20.,\n      3., 4.,22.,\n      3., 5.,24.,\n      4., 4.,28.,\n      4., 5.,30.,\n      3., 6.,26.,\n      4., 6.,32.).finished();\n\n  // expected: in matlab format - NOTE the transpose!)\n  Matrix expectedMatlab = expected.transpose();\n\n  GaussianFactorGraph gfg;\n  SharedDiagonal model = noiseModel::Isotropic::Sigma(2, 0.5);\n  const Key x123 = 0, x45 = 1;\n  gfg.add(x123, (Matrix(2, 3) << 1, 2, 3, 5, 6, 7).finished(),\n          Vector2(4, 8), model);\n  gfg.add(x123, (Matrix(2, 3) << 9, 10, 0, 0, 0, 0).finished(),\n          x45,  (Matrix(2, 2) << 11, 12, 14, 15.).finished(),\n          Vector2(13, 16), model);\n\n  Matrix actual = gfg.sparseJacobian_();\n\n  EXPECT(assert_equal(expectedMatlab, actual));\n\n  // SparseTriplets\n  auto boostActual = gfg.sparseJacobian();\n  // check the triplets size...\n  EXPECT_LONGS_EQUAL(16, boostActual.size());\n  // check content\n  for (int i = 0; i < 16; i++) {\n    EXPECT(triplet_equal(\n        SparseTriplet(expected(i, 0) - 1, expected(i, 1) - 1, expected(i, 2)),\n        boostActual.at(i)));\n  }\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, matrices) {\n  // Create factor graph:\n  // x1 x2 x3 x4 x5  b\n  //  1  2  3  0  0  4\n  //  5  6  7  0  0  8\n  //  9 10  0 11 12 13\n  //  0  0  0 14 15 16\n\n  Matrix A00 = (Matrix(2, 3) << 1, 2, 3, 5, 6, 7).finished();\n  Matrix A10 = (Matrix(2, 3) << 9, 10, 0, 0, 0, 0).finished();\n  Matrix A11 = (Matrix(2, 2) << 11, 12, 14, 15).finished();\n\n  GaussianFactorGraph gfg;\n  SharedDiagonal model = noiseModel::Unit::Create(2);\n  gfg.add(0, A00, Vector2(4., 8.), model);\n  gfg.add(0, A10, 1, A11, Vector2(13., 16.), model);\n\n  Matrix Ab(4, 6);\n  Ab << 1, 2, 3, 0, 0, 4, 5, 6, 7, 0, 0, 8, 9, 10, 0, 11, 12, 13, 0, 0, 0, 14, 15, 16;\n\n  // augmented versions\n  EXPECT(assert_equal(Ab, gfg.augmentedJacobian()));\n  EXPECT(assert_equal(Ab.transpose() * Ab, gfg.augmentedHessian()));\n\n  // jacobian\n  Matrix A = Ab.leftCols(Ab.cols() - 1);\n  Vector b = Ab.col(Ab.cols() - 1);\n  Matrix actualA;\n  Vector actualb;\n  boost::tie(actualA, actualb) = gfg.jacobian();\n  EXPECT(assert_equal(A, actualA));\n  EXPECT(assert_equal(b, actualb));\n\n  // hessian\n  Matrix L = A.transpose() * A;\n  Vector eta = A.transpose() * b;\n  Matrix actualL;\n  Vector actualeta;\n  boost::tie(actualL, actualeta) = gfg.hessian();\n  EXPECT(assert_equal(L, actualL));\n  EXPECT(assert_equal(eta, actualeta));\n\n  // hessianBlockDiagonal\n  VectorValues expectLdiagonal;  // Make explicit that diagonal is sum-squares of columns\n  expectLdiagonal.insert(0, Vector3(1 + 25 + 81, 4 + 36 + 100, 9 + 49));\n  expectLdiagonal.insert(1, Vector2(121 + 196, 144 + 225));\n  EXPECT(assert_equal(expectLdiagonal, gfg.hessianDiagonal()));\n\n  // hessianBlockDiagonal\n  map<Key, Matrix> actualBD = gfg.hessianBlockDiagonal();\n  LONGS_EQUAL(2, actualBD.size());\n  EXPECT(assert_equal(A00.transpose() * A00 + A10.transpose() * A10, actualBD[0]));\n  EXPECT(assert_equal(A11.transpose() * A11, actualBD[1]));\n}\n\n/* ************************************************************************* */\n/// Factor graph with 2 2D factors on 3 2D variables\nstatic GaussianFactorGraph createSimpleGaussianFactorGraph() {\n  GaussianFactorGraph fg;\n  Key x1 = 2, x2 = 0, l1 = 1;\n  SharedDiagonal unit2 = noiseModel::Unit::Create(2);\n  // linearized prior on x1: c[_x1_]+x1=0 i.e. x1=-c[_x1_]\n  fg += JacobianFactor(x1, 10 * I_2x2, -1.0 * Vector::Ones(2), unit2);\n  // odometry between x1 and x2: x2-x1=[0.2;-0.1]\n  fg += JacobianFactor(x2, 10 * I_2x2, x1, -10 * I_2x2, Vector2(2.0, -1.0), unit2);\n  // measurement between x1 and l1: l1-x1=[0.0;0.2]\n  fg += JacobianFactor(l1, 5 * I_2x2, x1, -5 * I_2x2, Vector2(0.0, 1.0), unit2);\n  // measurement between x2 and l1: l1-x2=[-0.2;0.3]\n  fg += JacobianFactor(x2, -5 * I_2x2, l1, 5 * I_2x2, Vector2(-1.0, 1.5), unit2);\n  return fg;\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, gradient) {\n  GaussianFactorGraph fg = createSimpleGaussianFactorGraph();\n\n  // Construct expected gradient\n  // 2*f(x) = 100*(x1+c[X(1)])^2 + 100*(x2-x1-[0.2;-0.1])^2 + 25*(l1-x1-[0.0;0.2])^2 +\n  // 25*(l1-x2-[-0.2;0.3])^2\n  // worked out: df/dx1 = 100*[0.1;0.1] + 100*[0.2;-0.1]) + 25*[0.0;0.2] = [10+20;10-10+5] = [30;5]\n  VectorValues expected = map_list_of<Key, Vector>(1, Vector2(5.0, -12.5))(2, Vector2(30.0, 5.0))(\n      0, Vector2(-25.0, 17.5));\n\n  // Check the gradient at delta=0\n  VectorValues zero = VectorValues::Zero(expected);\n  VectorValues actual = fg.gradient(zero);\n  EXPECT(assert_equal(expected, actual));\n  EXPECT(assert_equal(expected, fg.gradientAtZero()));\n\n  // Check the gradient at the solution (should be zero)\n  VectorValues solution = fg.optimize();\n  VectorValues actual2 = fg.gradient(solution);\n  EXPECT(assert_equal(VectorValues::Zero(solution), actual2));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, transposeMultiplication) {\n  GaussianFactorGraph A = createSimpleGaussianFactorGraph();\n\n  Errors e;\n  e += Vector2(0.0, 0.0), Vector2(15.0, 0.0), Vector2(0.0, -5.0), Vector2(-7.5, -5.0);\n\n  VectorValues expected;\n  expected.insert(1, Vector2(-37.5, -50.0));\n  expected.insert(2, Vector2(-150.0, 25.0));\n  expected.insert(0, Vector2(187.5, 25.0));\n\n  VectorValues actual = A.transposeMultiply(e);\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, eliminate_empty) {\n  // eliminate an empty factor\n  GaussianFactorGraph gfg;\n  gfg.add(JacobianFactor());\n  GaussianBayesNet::shared_ptr actualBN;\n  GaussianFactorGraph::shared_ptr remainingGFG;\n  boost::tie(actualBN, remainingGFG) = gfg.eliminatePartialSequential(Ordering());\n\n  // expected Bayes net is empty\n  GaussianBayesNet expectedBN;\n\n  // expected remaining graph should be the same as the original, still containing the empty factor\n  GaussianFactorGraph expectedLF = gfg;\n\n  // check if the result matches\n  EXPECT(assert_equal(*actualBN, expectedBN));\n  EXPECT(assert_equal(*remainingGFG, expectedLF));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, matrices2) {\n  GaussianFactorGraph gfg = createSimpleGaussianFactorGraph();\n  Matrix A;\n  Vector b;\n  boost::tie(A, b) = gfg.jacobian();\n  Matrix AtA;\n  Vector eta;\n  boost::tie(AtA, eta) = gfg.hessian();\n  EXPECT(assert_equal(A.transpose() * A, AtA));\n  EXPECT(assert_equal(A.transpose() * b, eta));\n  Matrix expectedAtA(6, 6);\n  expectedAtA << 125, 0, -25, 0, -100, 0,  //\n      0, 125, 0, -25, 0, -100,             //\n      -25, 0, 50, 0, -25, 0,               //\n      0, -25, 0, 50, 0, -25,               //\n      -100, 0, -25, 0, 225, 0,             //\n      0, -100, 0, -25, 0, 225;\n  EXPECT(assert_equal(expectedAtA, AtA));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, multiplyHessianAdd) {\n  GaussianFactorGraph gfg = createSimpleGaussianFactorGraph();\n\n  VectorValues x = map_list_of<Key, Vector>(0, Vector2(1, 2))(1, Vector2(3, 4))(2, Vector2(5, 6));\n\n  VectorValues expected;\n  expected.insert(0, Vector2(-450, -450));\n  expected.insert(1, Vector2(0, 0));\n  expected.insert(2, Vector2(950, 1050));\n\n  VectorValues actual;\n  gfg.multiplyHessianAdd(1.0, x, actual);\n  EXPECT(assert_equal(expected, actual));\n\n  // now, do it with non-zero y\n  gfg.multiplyHessianAdd(1.0, x, actual);\n  EXPECT(assert_equal(2 * expected, actual));\n}\n\n/* ************************************************************************* */\nstatic GaussianFactorGraph createGaussianFactorGraphWithHessianFactor() {\n  GaussianFactorGraph gfg = createSimpleGaussianFactorGraph();\n  gfg += HessianFactor(1, 2, 100*I_2x2, Z_2x2,   Vector2(0.0, 1.0),\n                                           400*I_2x2, Vector2(1.0, 1.0), 3.0);\n  return gfg;\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, multiplyHessianAdd2) {\n  GaussianFactorGraph gfg = createGaussianFactorGraphWithHessianFactor();\n\n  // brute force\n  Matrix AtA;\n  Vector eta;\n  boost::tie(AtA, eta) = gfg.hessian();\n  Vector X(6);\n  X << 1, 2, 3, 4, 5, 6;\n  Vector Y(6);\n  Y << -450, -450, 300, 400, 2950, 3450;\n  EXPECT(assert_equal(Y, AtA * X));\n\n  VectorValues x = map_list_of<Key, Vector>(0, Vector2(1, 2))(1, Vector2(3, 4))(2, Vector2(5, 6));\n\n  VectorValues expected;\n  expected.insert(0, Vector2(-450, -450));\n  expected.insert(1, Vector2(300, 400));\n  expected.insert(2, Vector2(2950, 3450));\n\n  VectorValues actual;\n  gfg.multiplyHessianAdd(1.0, x, actual);\n  EXPECT(assert_equal(expected, actual));\n\n  // now, do it with non-zero y\n  gfg.multiplyHessianAdd(1.0, x, actual);\n  EXPECT(assert_equal(2 * expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, matricesMixed) {\n  GaussianFactorGraph gfg = createGaussianFactorGraphWithHessianFactor();\n  Matrix A;\n  Vector b;\n  boost::tie(A, b) = gfg.jacobian();  // incorrect !\n  Matrix AtA;\n  Vector eta;\n  boost::tie(AtA, eta) = gfg.hessian();  // correct\n  EXPECT(assert_equal(A.transpose() * A, AtA));\n  Vector expected = -(Vector(6) << -25, 17.5, 5, -13.5, 29, 4).finished();\n  EXPECT(assert_equal(expected, eta));\n  EXPECT(assert_equal(A.transpose() * b, eta));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, gradientAtZero) {\n  GaussianFactorGraph gfg = createGaussianFactorGraphWithHessianFactor();\n  VectorValues expected;\n  VectorValues actual = gfg.gradientAtZero();\n  expected.insert(0, Vector2(-25, 17.5));\n  expected.insert(1, Vector2(5, -13.5));\n  expected.insert(2, Vector2(29, 4));\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, clone) {\n  // 2 variables, frontal has dim=4\n  VerticalBlockMatrix blockMatrix(list_of(4)(2)(1), 4);\n  blockMatrix.matrix() << 1.0, 0.0, 2.0, 0.0, 3.0, 0.0, 0.1, 0.0, 1.0, 0.0, 2.0, 0.0, 3.0, 0.2, 0.0,\n      0.0, 3.0, 0.0, 4.0, 0.0, 0.3, 0.0, 0.0, 0.0, 3.0, 0.0, 4.0, 0.4;\n  GaussianConditional cg(list_of(1)(2), 1, blockMatrix);\n\n  GaussianFactorGraph init_graph = createGaussianFactorGraphWithHessianFactor();\n  init_graph.push_back(GaussianFactor::shared_ptr());  /// Add null factor\n  init_graph.push_back(GaussianConditional(cg));\n\n  GaussianFactorGraph exp_graph =\n      createGaussianFactorGraphWithHessianFactor();   // Created separately\n  exp_graph.push_back(GaussianFactor::shared_ptr());  /// Add null factor\n  exp_graph.push_back(GaussianConditional(cg));\n\n  GaussianFactorGraph actCloned = init_graph.clone();\n  EXPECT(assert_equal(init_graph, actCloned));  // Same as the original version\n\n  // Apply an in-place change to init_graph and compare\n  JacobianFactor::shared_ptr jacFactor0 =\n      boost::dynamic_pointer_cast<JacobianFactor>(init_graph.at(0));\n  CHECK(jacFactor0);\n  jacFactor0->getA(jacFactor0->begin()) *= 7.;\n  EXPECT(assert_inequal(init_graph, exp_graph));\n  EXPECT(assert_equal(exp_graph, actCloned));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, negate) {\n  GaussianFactorGraph init_graph = createGaussianFactorGraphWithHessianFactor();\n  init_graph.push_back(GaussianFactor::shared_ptr());  /// Add null factor\n  GaussianFactorGraph actNegation = init_graph.negate();\n  GaussianFactorGraph expNegation;\n  expNegation.push_back(init_graph.at(0)->negate());\n  expNegation.push_back(init_graph.at(1)->negate());\n  expNegation.push_back(init_graph.at(2)->negate());\n  expNegation.push_back(init_graph.at(3)->negate());\n  expNegation.push_back(init_graph.at(4)->negate());\n  expNegation.push_back(GaussianFactor::shared_ptr());\n  EXPECT(assert_equal(expNegation, actNegation));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, hessianDiagonal) {\n  GaussianFactorGraph gfg = createGaussianFactorGraphWithHessianFactor();\n  VectorValues expected;\n  Matrix infoMatrix = gfg.hessian().first;\n  Vector d = infoMatrix.diagonal();\n\n  VectorValues actual = gfg.hessianDiagonal();\n  expected.insert(0, d.segment<2>(0));\n  expected.insert(1, d.segment<2>(2));\n  expected.insert(2, d.segment<2>(4));\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, DenseSolve) {\n  GaussianFactorGraph fg = createSimpleGaussianFactorGraph();\n  VectorValues expected = fg.optimize();\n  VectorValues actual = fg.optimizeDensely();\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, ProbPrime) {\n  GaussianFactorGraph gfg;\n  gfg.emplace_shared<JacobianFactor>(1, I_1x1, Z_1x1,\n                                     noiseModel::Isotropic::Sigma(1, 1.0));\n\n  VectorValues values;\n  values.insert(1, I_1x1);\n\n  // We are testing the normal distribution PDF where info matrix \u03a3 = 1,\n  // mean mu = 0  and x = 1.\n  // Therefore factor squared error: y = 0.5 * (\u03a3*x - mu)^2 =\n  // 0.5 * (1.0 - 0)^2 = 0.5\n  // NOTE the 0.5 constant is a part of the factor error.\n  EXPECT_DOUBLES_EQUAL(0.5, gfg.error(values), 1e-12);\n\n  // The gaussian PDF value is: exp^(-0.5 * (\u03a3*x - mu)^2) / sqrt(2 * PI)\n  // Ignore the denominator and we get: exp^(-0.5 * (1.0)^2) = exp^(-0.5)\n  double expected = exp(-0.5);\n  EXPECT_DOUBLES_EQUAL(expected, gfg.probPrime(values), 1e-12);\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "41464a11098da4b268e3fd942205effb93d7ba24", "size": 17094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/tests/testGaussianFactorGraph.cpp", "max_stars_repo_name": "h-rover/gtsam", "max_stars_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T07:01:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T07:01:48.000Z", "max_issues_repo_path": "gtsam/linear/tests/testGaussianFactorGraph.cpp", "max_issues_repo_name": "h-rover/gtsam", "max_issues_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/linear/tests/testGaussianFactorGraph.cpp", "max_forks_repo_name": "h-rover/gtsam", "max_forks_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-21T06:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T06:58:34.000Z", "avg_line_length": 36.7612903226, "max_line_length": 100, "alphanum_fraction": 0.5859365859, "num_tokens": 5417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6959583250334525, "lm_q1q2_score": 0.5066405740860797}}
{"text": "// Copyright 2005 The Trustees of Indiana University.\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_PYTHON_GENERATORS_HPP\n#define BOOST_GRAPH_PYTHON_GENERATORS_HPP\n\n#include <memory>\n#include <boost/python.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/python/graph.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/graph/erdos_renyi_generator.hpp>\n#include <boost/graph/plod_generator.hpp>\n#include <boost/graph/small_world_generator.hpp>\n\nnamespace boost { namespace graph { namespace python {\n\ntemplate<typename Graph> \nboost::python::object\nerdos_renyi_graph(typename graph_traits<Graph>::vertices_size_type n,\n                  double prob, bool allow_self_loops = false, int seed = 1)\n{\n  typedef erdos_renyi_iterator<minstd_rand, Graph> iterator;\n  minstd_rand gen(seed);\n  return Graph::pyconstruct(iterator(gen, n, prob, allow_self_loops), \n                            iterator(), n);\n}\n\ntemplate<typename Graph> \nboost::python::object\nplod_graph(typename graph_traits<Graph>::vertices_size_type n,\n           double alpha, double beta, bool allow_self_loops = false,\n           int seed = 1)\n{\n  typedef plod_iterator<minstd_rand, Graph> iterator;\n  minstd_rand gen(seed);\n  return Graph::pyconstruct(iterator(gen, n, alpha, beta, allow_self_loops), \n                            iterator(), n);\n}\n\ntemplate<typename Graph> \nboost::python::object\nsmall_world_graph(typename graph_traits<Graph>::vertices_size_type n,\n                  typename graph_traits<Graph>::vertices_size_type k,\n                  double prob, bool allow_self_loops = false, \n\t\t  bool allow_multiple_edges = true, int seed = 1)\n{\n  typedef small_world_iterator<minstd_rand, Graph> iterator;\n  minstd_rand gen(seed);\n  return Graph::pyconstruct(iterator(gen, n, k, prob, \n\t\t\t\t     allow_self_loops, allow_multiple_edges), \n                            iterator(), n);\n}\n\n} } } // end namespace boost::graph::python\n\n#endif // BOOST_GRAPH_PYTHON_GENERATORS_HPP\n", "meta": {"hexsha": "220f4d2a07345b9dd2169a2111c22ee87b352b28", "size": 2201, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/python/generators.hpp", "max_stars_repo_name": "erwinvaneijk/bgl-python", "max_stars_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-06-19T08:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T11:09:05.000Z", "max_issues_repo_path": "boost/graph/python/generators.hpp", "max_issues_repo_name": "erwinvaneijk/bgl-python", "max_issues_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "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/graph/python/generators.hpp", "max_forks_repo_name": "erwinvaneijk/bgl-python", "max_forks_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-07-13T07:50:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T15:08:03.000Z", "avg_line_length": 34.9365079365, "max_line_length": 77, "alphanum_fraction": 0.7169468423, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5066405704621917}}
{"text": "//=======================================================================\r\n// Copyright 1997-2001 University of Notre Dame.\r\n// Authors: Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee\r\n//\r\n// This file is part of the Boost Graph Library\r\n//\r\n// You should have received a copy of the License Agreement for the\r\n// Boost Graph Library along with the software; see the file LICENSE.\r\n// If not, contact Office of Research, University of Notre Dame, Notre\r\n// Dame, IN 46556.\r\n//\r\n// Permission to modify the code and to distribute modified code is\r\n// granted, provided the text of this NOTICE is retained, a notice that\r\n// the code was modified is included with the above COPYRIGHT NOTICE and\r\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\r\n// file is distributed with the modified code.\r\n//\r\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\r\n// By way of example, but not limitation, Licensor MAKES NO\r\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\r\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\r\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\r\n// OR OTHER RIGHTS.\r\n//=======================================================================\r\n#include <boost/config.hpp>\r\n#include <iostream>\r\n\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/dijkstra_shortest_paths.hpp>\r\n#include <boost/graph/visitors.hpp>\r\n#include <boost/graph/transpose_graph.hpp>\r\n\r\n/* Output:\r\n\r\n  distances from start vertex:\r\n  distance(a) = 0\r\n  distance(b) = 3\r\n  distance(c) = 1\r\n  distance(d) = 3\r\n  distance(e) = 3\r\n\r\n  min-max paths tree\r\n  a --> c \r\n  b --> \r\n  c --> d \r\n  d --> e \r\n  e --> b \r\n\r\n*/\r\n\r\nint \r\nmain(int , char* [])\r\n{\r\n  using namespace boost;\r\n\r\n  typedef adjacency_list<listS, vecS, directedS, \r\n    no_property, property<edge_weight_t, int> > Graph;\r\n  typedef graph_traits<Graph>::vertex_descriptor Vertex;\r\n\r\n  typedef std::pair<int,int> E;\r\n\r\n  const char name[] = \"abcdef\";\r\n\r\n  const int num_nodes = 6;\r\n  E edges[] = { E(0,2), E(1,1), E(1,3), E(1,4), E(2,1), E(2,3), \r\n                E(3,4), E(4,0), E(4,1) };\r\n  int weights[] = { 1, 2, 1, 2, 7, 3, 1, 1, 1};\r\n  const int n_edges = sizeof(edges)/sizeof(E);\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  // VC++ can't handle iterator constructors\r\n  Graph G(num_nodes);\r\n  property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, G);\r\n  for (std::size_t j = 0; j < sizeof(edges) / sizeof(E); ++j) {\r\n    graph_traits<Graph>::edge_descriptor e; bool inserted;\r\n    tie(e, inserted) = add_edge(edges[j].first, edges[j].second, G);\r\n    weightmap[e] = weights[j];\r\n  }\r\n#else\r\n  Graph G(edges, edges + n_edges, weights, num_nodes);\r\n  property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, G);\r\n#endif\r\n\r\n  std::vector<Vertex> p(num_vertices(G));\r\n  std::vector<int> d(num_vertices(G));\r\n\r\n  Vertex s = *(vertices(G).first);\r\n\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  dijkstra_shortest_paths\r\n    (G, s, &p[0], &d[0], weightmap, get(vertex_index, G),\r\n     std::greater<int>(), closed_plus<int>(), std::numeric_limits<int>::max(), 0,\r\n     default_dijkstra_visitor());\r\n#else\r\n  dijkstra_shortest_paths\r\n    (G, s, distance_map(&d[0]).\r\n     predecessor_map(&p[0]).\r\n     distance_compare(std::greater<int>()));\r\n#endif\r\n\r\n  std::cout << \"distances from start vertex:\" << std::endl;\r\n  graph_traits<Graph>::vertex_iterator vi, vend;\r\n  for(tie(vi,vend) = vertices(G); vi != vend; ++vi)\r\n    std::cout << \"distance(\" << name[*vi] << \") = \" << d[*vi] << std::endl;\r\n  std::cout << std::endl;\r\n\r\n  std::cout << \"min-max paths tree\" << std::endl;\r\n  adjacency_list<> tree(num_nodes);\r\n  \r\n  for(tie(vi,vend) = vertices(G); vi != vend; ++vi)\r\n    if (*vi != p[*vi])\r\n      add_edge(p[*vi], *vi, tree);\r\n\r\n  print_graph(tree, name);\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "873b650da131db555ad8bc67575c0ae3218c71ea", "size": 3927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/graph/example/min_max_paths.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/graph/example/min_max_paths.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/libs/graph/example/min_max_paths.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2796610169, "max_line_length": 82, "alphanum_fraction": 0.6259230965, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5066405612807013}}
{"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#pragma once\n\n#include \"algorithms/GraphPlayUtils.hpp\"\n#include \"algorithms/util/RTPGHI.hpp\"\n#include \"algorithms/public/STFT.hpp\"\n#include \"algorithms/util/AlgorithmUtils.hpp\"\n#include \"algorithms/util/FluidEigenMappings.hpp\"\n#include \"data/FluidDataSet.hpp\"\n#include \"data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <fstream>\n#include <random>\n#include <vector>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass GraphGrain {\n\npublic:\n  using MatrixXd = Eigen::MatrixXd;\n  using VectorXd = Eigen::VectorXd;\n  using DataSet = FluidDataSet<std::string, double, 1>;\n\n  void init(RealVectorView audio, index sampleRate, index windowSize,\n            index fftSize, index hopSize, index numBands, index distance,\n            double threshold, index nClusters, RealVectorView output) {\n    using namespace Eigen;\n    using namespace _impl;\n    using namespace std;\n    mWindowSize = windowSize;\n    mFFTSize = fftSize;\n    mHopSize = hopSize;\n    mFrameSize = (mFFTSize / 2) + 1;\n    mThreshold = threshold;\n    STFT stft = STFT(mWindowSize, mFFTSize, mHopSize);\n    mLength = std::floor((audio.size() + mHopSize) / mHopSize);\n    mSpectrogram = ComplexMatrix(mLength, mFrameSize);\n    stft.process(audio, mSpectrogram);\n    mMagnitude = RealMatrix(mLength, mFrameSize);\n    stft.magnitude(mSpectrogram, mMagnitude);\n    mDM = mUtils.computeDM(mMagnitude, numBands, sampleRate, windowSize,\n                           fftSize, distance);\n    mDM.diagonal().setZero();\n    mForbidden = ArrayXXd::Ones(mDM.rows(), mDM.cols());\n    mVisited = ArrayXXd::Zero(mDM.rows(), mDM.cols());\n    ArrayXd odf = mDM.diagonal(1).array();\n    mClusters = FluidTensor<index, 1>(mLength);\n    mUtils.onsetDetection(odf, mForbidden);\n    if (nClusters != 1) {\n      mClusters = mUtils.spectralClustering(mDM, nClusters);\n      for (index i = 0; i < mLength; i++) {\n        for (index j = 0; j < mLength; j++) {\n          if (mClusters(i) != mClusters(j)) {\n            mForbidden(i, j) = 0;\n            mForbidden(j, i) = 0;\n          }\n        }\n      }\n    }\n    mRP = (mDM.array() < threshold).cast<double>();\n    mRP = mRP.array() * mForbidden.array();\n    mRTPGHI.init(fftSize);\n    mPrevMag = RealVector(mFrameSize);\n    mPrevMag = mMagnitude.row(0);\n    mInitialized = true;\n  }\n\n  index selectProb() {\n    index nNeighbors = mRP.col(mPos).sum();\n    if (nNeighbors == 0)\n      return nextInCluster(mPos);\n    std::vector<index> candidates(nNeighbors);\n    std::vector<double> acumProbs(nNeighbors);\n    index nCandidates = 0;\n    double prob = 0;\n    for (index i = 0; i < mRP.rows(); i++) {\n      if (mRP(mPos, i) > 0 && mVisited(mPos, i) <= 0) {\n        prob = prob + (1 - mDM(mPos, i));\n        acumProbs[nCandidates] = prob;\n        candidates[nCandidates++] = i;\n      }\n    }\n    double rnd = prob * mUtils.rand();\n    index selected = 0;\n    while (acumProbs[selected] < rnd)\n      selected++;\n    return candidates[selected];\n  }\n\n  index nextInCluster(index current) {\n    for (index i = current + 1; i < mLength + current; i++) {\n      index pos = i % mLength;\n      if (mClusters(pos) == mClusters(current))\n        return pos;\n    }\n  }\n\n  index selectRand(double randomness) {\n    index nNeighbors = mRP.col(mPos).sum();\n    if (nNeighbors == 0) {\n      mVisited.row(mPos).setZero();\n      return nextInCluster(mPos);\n    }\n    std::vector<index> candidates(nNeighbors);\n    index nCandidates = 0;\n    for (index i = 0; i < mRP.rows(); i++)\n      if (i != mPos && mRP(mPos, i) > 0 && mVisited(mPos, i) <= 0) {\n        candidates[nCandidates++] = i;\n      }\n    std::sort(candidates.begin(), candidates.end(),\n              [this](index a, index b) { return mDM(mPos, a) < mDM(mPos, b); });\n    if (randomness == 0)\n      return candidates[0];\n    index k = lrint(randomness * nCandidates);\n    index next = mUtils.randInt(k);\n    return candidates[next];\n  }\n\n  index selectNearest() {\n    index nNeighbors = mRP.col(mPos).sum();\n    if (nNeighbors == 0) {\n      return nextInCluster(mPos);\n    }\n    double minDist = infinity;\n    index selected = 0;\n    for (index i = 0; i < mRP.rows(); i++) {\n      if ((i != mPos) && (mRP(mPos, i) > 0) && (mDM(mPos, i) < minDist) &&\n          (mVisited(mPos, i) == 0)) {\n        selected = i;\n        minDist = mDM(mPos, i);\n      }\n    }\n    if (selected == 0)\n      return nextInCluster(mPos);\n    return selected;\n  }\n\n  void processFrame(ComplexVectorView out, double start, double threshold,\n                    index forget, double rand, index phaseGen,\n                    RealVectorView output) {\n    using namespace Eigen;\n    using namespace _impl;\n\n    if (mThreshold != threshold) {\n      mRP = (mDM.array() < threshold).cast<double>();\n      mRP = mRP.array() * mForbidden.array();\n      mThreshold = threshold;\n    }\n\n    index next = (mPos + 1) % mSpectrogram.rows();\n    mVisited = (mVisited.array() - 1).cwiseMax(0);\n    index startFrame = lrint(start * (mSpectrogram.rows() - 1));\n    if (startFrame != mStartFrame) {\n      mStartFrame = startFrame;\n      mPos = mStartFrame;\n      index nNeighbors = mRP.col(mPos).sum();\n      while (nNeighbors == 0) {\n        nNeighbors = mRP.col(mPos).sum();\n        mPos = (mPos + 1) % mSpectrogram.rows();\n      }\n      mCount = 0;\n    } else {\n      index prevPos = mPos;\n      mPos = selectRand(rand);\n      mVisited(prevPos, mPos) = forget;\n    }\n    RealVectorView frame = mMagnitude.row(mPos);\n    if (phaseGen > 0)\n      mRTPGHI.processFrame(frame, out, mWindowSize, mFFTSize, mHopSize, 1e-5);\n    else\n      out = mSpectrogram.row(mPos);\n    output(0) = mPos;\n    output(1) = mClusters(mPos);\n  }\n\n  bool initialized() { return mInitialized; }\n\n  index mWindowSize;\n  index mHopSize;\n  index mFFTSize;\n\nprivate:\n  GraphPlayUtils mUtils;\n  ComplexMatrix mSpectrogram;\n  RealMatrix mMagnitude;\n  RealVector mPrevMag;\n  index mFrameSize;\n  MatrixXd mDM;\n  MatrixXd mRP;\n  MatrixXd mForbidden;\n  MatrixXd mVisited;\n  VectorXd mDeg;\n  bool mInitialized{false};\n  int mPos{0};\n  index mLength;\n  index mStartFrame{-1};\n  index mEndFrame;\n  double mThreshold;\n  index mCount{0};\n  RTPGHI mRTPGHI;\n  FluidTensor<index, 1> mClusters;\n  double mPrevGain{0};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "f6bd09d6fe73b513ffdc27aa0eb265f53c38e546", "size": 6630, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/GraphGrain.hpp", "max_stars_repo_name": "flucoma/graph_loop_grain", "max_stars_repo_head_hexsha": "db9bbc603412d44a49b0d882bc3fdb604aeb63d1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-06-05T10:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T10:40:25.000Z", "max_issues_repo_path": "include/algorithms/GraphGrain.hpp", "max_issues_repo_name": "flucoma/graph_loop_grain", "max_issues_repo_head_hexsha": "db9bbc603412d44a49b0d882bc3fdb604aeb63d1", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/GraphGrain.hpp", "max_forks_repo_name": "flucoma/graph_loop_grain", "max_forks_repo_head_hexsha": "db9bbc603412d44a49b0d882bc3fdb604aeb63d1", "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.5529953917, "max_line_length": 80, "alphanum_fraction": 0.6292609351, "num_tokens": 1877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.5065769068753521}}
{"text": "/*    Copyright (c) 2010-2018, 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\n#include \"tudat/basics/utilities.h\"\n#include \"tudat/basics/testMacros.h\"\n#include \"tudat/basics/basicTypedefs.h\"\n#include \"tudat/io/basicInputOutput.h\"\n#include \"tudat/io/matrixTextFileReader.h\"\n\n#include \"tudat/math/statistics/basicStatistics.h\"\n#include \"tudat/math/filters/extendedKalmanFilter.h\"\n#include \"tudat/math/integrators/createNumericalIntegrator.h\"\n\n#include \"tudat/math/filters/controlClass.h\"\n\nnamespace tudat\n{\n\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_extended_kalman_filter )\n\n// Functions for extended Kalman filter.\nEigen::Vector2d stateFunction1( const double time, const Eigen::Vector2d& state, const Eigen::Vector2d& control )\n{\n    TUDAT_UNUSED_PARAMETER( time );\n    TUDAT_UNUSED_PARAMETER( control );\n    Eigen::Vector2d stateDerivative;\n    stateDerivative[ 0 ] = state[ 1 ] * std::pow( std::cos( state[ 0 ] ), 3 );\n    stateDerivative[ 1 ] = std::sin( state[ 0 ] );\n    return stateDerivative;\n}\nEigen::Vector1d measurementFunction1( const double time, const Eigen::Vector2d& state )\n{\n    TUDAT_UNUSED_PARAMETER( time );\n    Eigen::Vector1d measurement;\n    measurement[ 0 ] = std::pow( state[ 0 ], 3 );\n    return measurement;\n}\nEigen::Matrix2d stateJacobianFunction1( const double time, const Eigen::Vector2d& state, const Eigen::Vector2d& control )\n{\n    TUDAT_UNUSED_PARAMETER( time );\n    TUDAT_UNUSED_PARAMETER( control );\n    Eigen::Matrix2d stateJacobian = Eigen::Matrix2d::Zero( );\n    stateJacobian( 0, 0 ) = - 3.0 * state[ 1 ] * std::pow( std::cos( state[ 0 ] ), 2 ) * std::sin( state[ 0 ] );\n    stateJacobian( 0, 1 ) = std::pow( std::cos( state[ 0 ] ), 3 );\n    stateJacobian( 1, 0 ) = std::cos( state[ 0 ] );\n    return stateJacobian;\n}\nEigen::RowVector2d measurementJacobianFunction1( const double time, const Eigen::Vector2d& state )\n{\n    TUDAT_UNUSED_PARAMETER( time );\n    Eigen::RowVector2d measurementJacobian;\n    measurementJacobian[ 0 ] = 3.0 * std::pow( state[ 0 ], 2 );\n    return measurementJacobian;\n}\n\n// Test implementation of extended Kalman filter class.\nBOOST_AUTO_TEST_CASE( testExtendedKalmanFilterFirstCase )\n{\n    using namespace tudat::filters;\n\n    // Set initial conditions\n    const double initialTime = 0.0;\n    const double timeStep = 0.01;\n    const unsigned int numberOfTimeSteps = 1000;\n\n    Eigen::Vector2d initialStateVector;\n    initialStateVector[ 0 ] = 3.0;\n    initialStateVector[ 1 ] = -0.3;\n\n    Eigen::Vector2d initialEstimatedStateVector;\n    initialEstimatedStateVector[ 0 ] = 10.0;\n    initialEstimatedStateVector[ 1 ] = -3.0;\n\n    Eigen::Matrix2d initialEstimatedStateCovarianceMatrix = Eigen::Matrix2d::Zero( );\n    initialEstimatedStateCovarianceMatrix( 0, 0 ) = 100.0;\n    initialEstimatedStateCovarianceMatrix( 1, 1 ) = 100.0;\n\n    // Set system and measurement uncertainty\n    Eigen::Matrix2d systemUncertainty = Eigen::Matrix2d::Zero( );\n    Eigen::Vector1d measurementUncertainty = Eigen::Vector1d::Zero( );\n    systemUncertainty( 0, 0 ) = 100.0;\n    systemUncertainty( 1, 1 ) = 100.0;\n    measurementUncertainty[ 0 ] = 100.0;\n\n    // Set integrator settings\n    std::shared_ptr< numerical_integrators::IntegratorSettings< > > integratorSettings =\n            std::make_shared< numerical_integrators::IntegratorSettings< > > (\n                numerical_integrators::euler, initialTime, timeStep );\n\n    // Create control class\n    std::shared_ptr< ControlWrapper< double, double, 2 > > control =\n            std::make_shared< ControlWrapper< double, double, 2 > >(\n                [ & ]( const double, const Eigen::Vector2d& ){ return Eigen::Vector2d::Zero( ); } );\n\n    // Create extended Kalman filter object\n    KalmanFilterDoublePointer extendedFilter = std::make_shared< ExtendedKalmanFilterDouble >(\n                std::bind( &stateFunction1, std::placeholders::_1, std::placeholders::_2,\n                             std::bind( &ControlWrapper< double, double, 2 >::getCurrentControlVector, control ) ),\n                std::bind( &measurementFunction1, std::placeholders::_1, std::placeholders::_2 ),\n                std::bind( &stateJacobianFunction1, std::placeholders::_1, std::placeholders::_2,\n                             std::bind( &ControlWrapper< double, double, 2 >::getCurrentControlVector, control ) ),\n                [ & ]( const double, const Eigen::Vector2d& ){ return Eigen::Matrix2d::Identity( ); },\n                std::bind( &measurementJacobianFunction1, std::placeholders::_1, std::placeholders::_2 ),\n                [ & ]( const double, const Eigen::Vector2d& ){ return Eigen::Vector1d::Identity( ); },\n                systemUncertainty, measurementUncertainty, timeStep,\n                initialTime, initialEstimatedStateVector, initialEstimatedStateCovarianceMatrix,\n                integratorSettings );\n\n    // Load noise from file\n    Eigen::MatrixXd systemNoise = input_output::readMatrixFromFile( tudat::paths::getTudatTestDataPath( ) +\n                                                                    \"/ekfSystemNoise1.dat\" );\n    Eigen::MatrixXd measurementNoise = input_output::readMatrixFromFile( tudat::paths::getTudatTestDataPath( ) +\n                                                                         \"/ekfMeasurementNoise1.dat\" );\n\n    // Loop over each time step\n    const bool showProgress = false;\n    double currentTime = initialTime;\n    Eigen::Vector2d currentActualStateVector = initialStateVector;\n    Eigen::Vector2d currentControlVector = Eigen::Vector2d::Zero( );\n    Eigen::Vector1d currentMeasurementVector;\n    std::map< double, Eigen::Vector2d > actualStateVectorHistory;\n    std::map< double, Eigen::Vector1d > measurementVectorHistory;\n    actualStateVectorHistory[ initialTime ] = initialStateVector;\n    for ( unsigned int i = 0; i < numberOfTimeSteps; i++ )\n    {\n        // Compute actual values and perturb them\n        currentActualStateVector += ( stateFunction1( currentTime, currentActualStateVector, currentControlVector ) +\n                                      systemNoise.col( i ) ) * timeStep;\n        currentMeasurementVector = measurementFunction1( currentTime, currentActualStateVector ) + measurementNoise.col( i );\n\n        // Update control class\n        control->setCurrentControlVector( currentTime, extendedFilter->getCurrentStateEstimate( ) );\n\n        // Update filter\n        extendedFilter->updateFilter( currentMeasurementVector );\n        currentTime = extendedFilter->getCurrentTime( );\n\n        // Store values\n        actualStateVectorHistory[ currentTime ] = currentActualStateVector;\n        measurementVectorHistory[ currentTime ] = currentMeasurementVector;\n\n        // Print progress\n        if ( showProgress )\n        {\n            std::cout << \"Time: \" << currentTime << std::endl\n                      << \"Measurement: \" << currentMeasurementVector.transpose( ) << std::endl\n                      << \"Estimated State: \" << extendedFilter->getCurrentStateEstimate( ).transpose( ) << std::endl << std::endl;\n        }\n    }\n\n    // Check that final state is as expected\n    Eigen::Vector2d expectedFinalState;\n    expectedFinalState << 4.972005968275564, -18.516511373319734;\n    for ( int i = 0; i < expectedFinalState.rows( ); i++ )\n    {\n        BOOST_CHECK_SMALL( extendedFilter->getCurrentStateEstimate( )[ i ] - expectedFinalState[ i ], 1.0e-10 );\n    }\n}\n\n// Constant parameters for example\nconst double gravitationalParameter = 32.2;\n\n// Functions for extended Kalman filter.\nEigen::Vector3d stateFunction2( const double time, const Eigen::Vector3d& state, const Eigen::Vector3d& control )\n{\n    TUDAT_UNUSED_PARAMETER( time );\n    TUDAT_UNUSED_PARAMETER( control );\n    Eigen::Vector3d stateDerivative = Eigen::Vector3d::Zero( );\n    stateDerivative[ 0 ] = state[ 1 ];\n    stateDerivative[ 1 ] = 0.0034 * gravitationalParameter * std::exp( - state[ 0 ] / 22000.0 ) *\n            std::pow( state[ 1 ], 2 ) / ( 2.0 * state[ 2 ] ) - gravitationalParameter;\n    return stateDerivative;\n}\nEigen::Vector1d measurementFunction2( const double time, const Eigen::Vector3d& state )\n{\n    TUDAT_UNUSED_PARAMETER( time );\n    Eigen::Vector1d measurement;\n    measurement[ 0 ] = state[ 0 ];\n    return measurement;\n}\nEigen::Matrix3d stateJacobianFunction2( const double time, const Eigen::Vector3d& state, const Eigen::Vector3d& control )\n{\n    TUDAT_UNUSED_PARAMETER( time );\n    TUDAT_UNUSED_PARAMETER( control );\n    Eigen::Matrix3d stateJacobian = Eigen::Matrix3d::Zero( );\n    stateJacobian( 0, 1 ) = 1.0;\n    stateJacobian( 1, 0 ) = - 0.0034 * gravitationalParameter * std::exp( - state[ 0 ] / 22000.0 ) *\n            std::pow( state[ 1 ], 2 ) / ( 44000.0 * state[ 2 ] );\n    stateJacobian( 1, 1 ) = 0.0034 * gravitationalParameter * std::exp( - state[ 0 ] / 22000.0 ) *\n            state[ 1 ] / state[ 2 ];\n    stateJacobian( 1, 2 ) = - 0.0034 * gravitationalParameter * std::exp( - state[ 0 ] / 22000.0 ) *\n            std::pow( state[ 1 ], 2 ) / ( 2.0 * std::pow( state[ 2 ], 2 ) );\n    return stateJacobian;\n}\nEigen::RowVector3d measurementJacobianFunction2( const double time, const Eigen::Vector3d& state )\n{\n    TUDAT_UNUSED_PARAMETER( time );\n    TUDAT_UNUSED_PARAMETER( state );\n    Eigen::RowVector3d measurementJacobian = Eigen::RowVector3d::Zero( );\n    measurementJacobian[ 0 ] = 1.0;\n    return measurementJacobian;\n}\n\n// Test implementation of extended Kalman filter class.\nBOOST_AUTO_TEST_CASE( testExtendedKalmanFilterSecondCase )\n{\n    using namespace tudat::filters;\n\n    // Set initial conditions\n    const double initialTime = 0.0;\n    const double timeStep = 0.1;\n    const unsigned int numberOfTimeSteps = 300;\n\n    Eigen::Vector3d initialStateVector;\n    initialStateVector[ 0 ] = 200000.0;\n    initialStateVector[ 1 ] = -6000.0;\n    initialStateVector[ 2 ] = 500.0;\n\n    Eigen::Vector3d initialEstimatedStateVector;\n    initialEstimatedStateVector[ 0 ] = 200025.0;\n    initialEstimatedStateVector[ 1 ] = -6150.0;\n    initialEstimatedStateVector[ 2 ] = 800.0;\n\n    Eigen::Matrix3d initialEstimatedStateCovarianceMatrix = Eigen::Matrix3d::Zero( );\n    initialEstimatedStateCovarianceMatrix( 0, 0 ) = std::pow( 1000.0, 2 );\n    initialEstimatedStateCovarianceMatrix( 1, 1 ) = 20000.0;\n    initialEstimatedStateCovarianceMatrix( 2, 2 ) = std::pow( 300.0, 2 );\n\n    // Set system and measurement uncertainty\n    Eigen::Matrix3d systemUncertainty = Eigen::Matrix3d::Zero( );\n    Eigen::Vector1d measurementUncertainty = Eigen::Vector1d::Zero( );\n    systemUncertainty( 0, 0 ) = std::pow( 100.0, 2 );\n    systemUncertainty( 1, 1 ) = std::pow( 10.0, 2 );\n    systemUncertainty( 2, 2 ) = std::pow( 1.0, 2 );\n    measurementUncertainty[ 0 ] = std::pow( 25.0, 2 );\n\n    // Set integrator settings\n    std::shared_ptr< numerical_integrators::IntegratorSettings< > > integratorSettings =\n            std::make_shared< numerical_integrators::IntegratorSettings< > > (\n                numerical_integrators::euler, initialTime, timeStep );\n\n    // Create control class\n    std::shared_ptr< ControlWrapper< double, double, 3 > > control =\n            std::make_shared< ControlWrapper< double, double, 3 > >(\n                [ & ]( const double, const Eigen::Vector3d& ){ return Eigen::Vector3d::Zero( ); } );\n\n    // Create extended Kalman filter object\n    KalmanFilterDoublePointer extendedFilter = std::make_shared< ExtendedKalmanFilterDouble >(\n                std::bind( &stateFunction2, std::placeholders::_1, std::placeholders::_2,\n                             std::bind( &ControlWrapper< double, double, 3 >::getCurrentControlVector, control ) ),\n                std::bind( &measurementFunction2, std::placeholders::_1, std::placeholders::_2 ),\n                std::bind( &stateJacobianFunction2, std::placeholders::_1, std::placeholders::_2,\n                             std::bind( &ControlWrapper< double, double, 3 >::getCurrentControlVector, control ) ),\n                [ & ]( const double, const Eigen::Vector3d& ){ return Eigen::Matrix3d::Identity( ); },\n                std::bind( &measurementJacobianFunction2, std::placeholders::_1, std::placeholders::_2 ),\n                [ & ]( const double, const Eigen::Vector3d& ){ return Eigen::Vector1d::Identity( ); },\n                systemUncertainty, measurementUncertainty, timeStep,\n                initialTime, initialEstimatedStateVector, initialEstimatedStateCovarianceMatrix,\n                integratorSettings );\n\n    // Load noise from file\n    Eigen::MatrixXd systemNoise = input_output::readMatrixFromFile( tudat::paths::getTudatTestDataPath( ) +\n                                                                    \"/ekfSystemNoise2.dat\" );\n    Eigen::MatrixXd measurementNoise = input_output::readMatrixFromFile( tudat::paths::getTudatTestDataPath( ) +\n                                                                         \"/ekfMeasurementNoise2.dat\" );\n\n    // Loop over each time step\n    const bool showProgress = false;\n    double currentTime = initialTime;\n    Eigen::Vector3d currentActualStateVector = initialStateVector;\n    Eigen::Vector3d currentControlVector = Eigen::Vector3d::Zero( );\n    Eigen::Vector1d currentMeasurementVector;\n    std::map< double, Eigen::Vector3d > actualStateVectorHistory;\n    std::map< double, Eigen::Vector1d > measurementVectorHistory;\n    actualStateVectorHistory[ initialTime ] = initialStateVector;\n    for ( unsigned int i = 0; i < numberOfTimeSteps; i++ )\n    {\n        // Compute actual values and perturb them\n        currentActualStateVector += ( stateFunction2( currentTime, currentActualStateVector, currentControlVector ) +\n                                      systemNoise.col( i ) ) * timeStep;\n        currentMeasurementVector = measurementFunction2( currentTime, currentActualStateVector ) + measurementNoise.col( i );\n\n        // Update control class\n        control->setCurrentControlVector( currentTime, extendedFilter->getCurrentStateEstimate( ) );\n\n        // Update filter\n        extendedFilter->updateFilter( currentMeasurementVector );\n        currentTime = extendedFilter->getCurrentTime( );\n\n        // Store values\n        actualStateVectorHistory[ currentTime ] = currentActualStateVector;\n        measurementVectorHistory[ currentTime ] = currentMeasurementVector;\n\n        // Print progress\n        if ( showProgress )\n        {\n            std::cout << \"Time: \" << currentTime << std::endl\n                      << \"Measurement: \" << currentMeasurementVector.transpose( ) << std::endl\n                      << \"Estimated State: \" << extendedFilter->getCurrentStateEstimate( ).transpose( ) << std::endl << std::endl;\n        }\n    }\n\n    // Check that final state is as expected\n    Eigen::Vector3d expectedFinalState = Eigen::Vector3d::Zero( );\n    expectedFinalState << 25202.174591778028, -3327.344292984541, 498.97471055815663;\n    for ( int i = 0; i < expectedFinalState.rows( ); i++ )\n    {\n        BOOST_CHECK_SMALL( extendedFilter->getCurrentStateEstimate( )[ i ] - expectedFinalState[ i ], 1.0e-10 );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n\n} // namespace tudat\n", "meta": {"hexsha": "6189cb5d570f136599bb657fdfaaeb7e38e024eb", "size": 15498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/math/filters/unitTestExtendedKalmanFilter.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/filters/unitTestExtendedKalmanFilter.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/filters/unitTestExtendedKalmanFilter.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": 46.5405405405, "max_line_length": 130, "alphanum_fraction": 0.6625371016, "num_tokens": 3960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5064960217026645}}
{"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_ACSCD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACSCD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the inverse cosecant in degree:\n    \\f$(180/\\pi) \\arcsin(1/x)\\f$.\n\n    @par Header <boost/simd/function/acscd.hpp>\n\n    @see acsc, accscpi\n\n    @par Example:\n\n      @snippet acscd.cpp acscd\n\n    @par Possible output:\n\n      @snippet acscd.txt acscd\n\n  **/\n  IEEEValue acscd(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acscd.hpp>\n#include <boost/simd/function/simd/acscd.hpp>\n\n#endif\n", "meta": {"hexsha": "4e9a4131585102d42f74164547ea90e3844dde04", "size": 1033, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acscd.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/function/acscd.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/function/acscd.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": 23.4772727273, "max_line_length": 100, "alphanum_fraction": 0.5740561471, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5064960217026644}}
{"text": "#include \"SMP/HElib.hpp\"\n#include <HElib/FHEContext.h>\n#include <HElib/EncryptedArray.h>\n#include <HElib/PAlgebra.h>\n#include <NTL/ZZX.h>\n#include <NTL/lzz_pX.h>\n\n#include <algorithm>\nvoid rawEncode(NTL::zz_pX &out,\n               std::vector<NTL::zz_pX> const& slots,\n               FHEcontext const& context)\n{\n    const auto &encoder = context.alMod.getDerived(PA_zz_p());\n    encoder.CRT_reconstruct(out, const_cast<std::vector<NTL::zz_pX> &>(slots));\n}\n\nvoid rawEncode(NTL::ZZX &out,\n               std::vector<NTL::zz_pX> const& slots,\n               FHEcontext const& context)\n{\n    NTL::zz_pX tmp;\n    rawEncode(tmp, slots, context);\n    NTL::conv(out, tmp);\n}\n\nvoid rawDecode(std::vector<NTL::zz_pX> &out,\n               NTL::zz_pX const& poly,\n               FHEcontext const& context)\n{\n    const auto &decoder = context.alMod.getDerived(PA_zz_p());\n    decoder.CRT_decompose(out, poly);\n}\n\nvoid rawDecode(std::vector<NTL::zz_pX> &out,\n               NTL::ZZX const& poly,\n               FHEcontext const& context)\n{\n    NTL::zz_pX tmp;\n    NTL::conv(tmp, poly);\n    rawDecode(out, tmp, context);\n}\n\nvoid rawDecode(std::vector<NTL::ZZX> &out,\n               NTL::ZZX const& poly,\n               FHEcontext const& context)\n{\n    NTL::zz_pX tmp;\n    std::vector<NTL::zz_pX> tmp2;\n    rawDecode(tmp2, tmp, context);\n    out.resize(tmp2.size());\n    for (size_t i = 0; i < tmp2.size(); i++)\n        NTL::conv(out[i], tmp2[i]);\n}\n\nstatic GMMPrecompTable precompute_gmm_table(long beta, long p, long slots)\n{\n    GMMPrecompTable tbl;\n    tbl.beta_powers.resize(slots);\n    /// (-beta)^k mod p for 0 <= k < l\n    for (long i = 0; i < slots; i++)\n        tbl.beta_powers[i] = NTL::PowerMod(i & 1 ? p - beta : beta, i, p);\n    return tbl;\n}\n\nstatic bool is_valid_for_GMM(NTL::ZZX const& factor)\n{\n    for (long d = 1; d < NTL::deg(factor); d++) {\n        if (NTL::coeff(factor, d) != 0)\n            return false;\n    }\n    return true;\n}\n\nstd::vector<GMMPrecompTable> precompute_gmm_tables(FHEcontext const& context)\n{\n    long p = context.alMod.getPPowR();\n    long l = context.ea->size();\n    std::vector<GMMPrecompTable> tbls;\n    tbls.reserve(l);\n    NTL::mulmod_t inv_p = NTL::PrepMulMod(p);\n    for (const auto & factor : context.alMod.getFactorsOverZZ()) {\n        assert(is_valid_for_GMM(factor));\n        long beta = NTL::to_long(factor[0]);\n        tbls.push_back(precompute_gmm_table(beta, p, l)) ;\n        tbls.back().inv_p = inv_p;\n    }\n    return tbls;\n}\n\nlong extract_inner_product(NTL::ZZX const& poly,\n                           GMMPrecompTable const& tbl,\n                           FHEcontext const& context)\n{\n    long d = context.ea->getDegree();\n    long l = context.ea->size();\n    long p = context.alMod.getPPowR();\n    long phim = context.zMStar.getPhiM();\n    long ret = 0;\n    for (long i = 0; i < l; i++) {\n        long coeff_loc = (i + 1) * d - 1;\n        assert(coeff_loc < phim);\n        long coeff = NTL::to_long(NTL::coeff(poly, coeff_loc));\n        coeff = NTL::MulMod(coeff, tbl.beta_powers.at(i), p, tbl.inv_p);\n        ret = NTL::AddMod(ret, coeff, p);\n    }\n    return ret;\n}\n\nlong extract_inner_product(NTL::Vec<long> const& poly,\n                           GMMPrecompTable const& tbl,\n                           FHEcontext const& context)\n{\n    long d = context.ea->getDegree();\n    long l = context.ea->size();\n    long p = context.alMod.getPPowR();\n    long phim = context.zMStar.getPhiM();\n    assert(poly.length() == phim);\n    long ret = 0;\n    for (long i = 0; i < l; i++) {\n        long coeff_loc = (i + 1) * d - 1;\n        assert(coeff_loc < phim);\n        long coeff = poly.at(coeff_loc) % p;\n        coeff = NTL::MulMod(coeff, tbl.beta_powers.at(i), p, tbl.inv_p);\n        ret = NTL::AddMod(ret, coeff, p);\n    }\n    return ret;\n}\n\nvoid extract_inner_products(std::vector<long> &out,\n                            NTL::ZZX const& poly,\n                            std::vector<GMMPrecompTable> const& tables,\n                            FHEcontext const& context)\n{\n    out.clear();\n    out.reserve(context.ea->size());\n    for (const auto &tbl : tables) {\n        out.push_back(extract_inner_product(poly, tbl, context));\n    }\n}\n\nvoid extract_inner_products(std::vector<long> &out,\n                            NTL::Vec<long> const& poly,\n                            std::vector<GMMPrecompTable> const& tables,\n                            FHEcontext const& context)\n{\n    out.clear();\n    out.reserve(context.ea->size());\n    for (const auto &tbl : tables) {\n        out.push_back(extract_inner_product(poly, tbl, context));\n    }\n}\n\nvoid faster_decrypt(NTL::Vec<long> &out,\n                    FHESecKey const& sk,\n                    Ctxt const& ctx)\n{\n    const FHEcontext& context = sk.getContext();\n    assert(ctx.getPrimeSet().card() == 1);\n    DoubleCRT dcrt(context, ctx.getPrimeSet()); // Set to zero\n    sk.Decrypt(dcrt, ctx);\n    dcrt.getOneRow(out, 0);\n}\n", "meta": {"hexsha": "d147045d75491d93779f466b5def29d165452f9e", "size": 4918, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HElib.cpp", "max_stars_repo_name": "Vampsj/SMP", "max_stars_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HElib.cpp", "max_issues_repo_name": "Vampsj/SMP", "max_issues_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HElib.cpp", "max_forks_repo_name": "Vampsj/SMP", "max_forks_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1717791411, "max_line_length": 79, "alphanum_fraction": 0.5768605124, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.5064615582974134}}
{"text": "\n#ifdef BMO_ENABLE_ARMA_WRAPPERS\n    #ifndef ARMA_DONT_USE_WRAPPER\n        #define ARMA_DONT_USE_WRAPPER\n    #endif\n    \n    #include \"armadillo\"\n\n    using Mat_t = arma::mat;\n    using ColVec_t = arma::vec;\n    using RowVec_t = arma::rowvec;\n    using ColVecInt_t = arma::uvec;\n#endif\n\n//\n\n#ifdef BMO_ENABLE_EIGEN_WRAPPERS\n    #include <iostream>\n    #include <random>\n    #include <Eigen/Dense>\n\n    template<typename eT, int iTr, int iTc>\n    using EigenMat = Eigen::Matrix<eT,iTr,iTc>;\n\n    using Mat_t = Eigen::MatrixXd;\n    using ColVec_t = Eigen::VectorXd;\n    using RowVec_t = Eigen::Matrix<double,1,Eigen::Dynamic>;\n    using ColVecInt_t = Eigen::VectorXi;\n#endif\n\n#include \"BaseMatrixOps.hpp\"\n", "meta": {"hexsha": "f12bb941901f5b2e724fdbc1c262c5bad2f55deb", "size": 703, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/bmo_tests.hpp", "max_stars_repo_name": "kthohr/BaseMatrixOps", "max_stars_repo_head_hexsha": "cfcb4c9dac79c8ccac3816b26220c77dc0ae90c8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/bmo_tests.hpp", "max_issues_repo_name": "kthohr/BaseMatrixOps", "max_issues_repo_head_hexsha": "cfcb4c9dac79c8ccac3816b26220c77dc0ae90c8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-11T15:51:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T15:51:19.000Z", "max_forks_repo_path": "tests/bmo_tests.hpp", "max_forks_repo_name": "kthohr/BaseMatrixOps", "max_forks_repo_head_hexsha": "cfcb4c9dac79c8ccac3816b26220c77dc0ae90c8", "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.96875, "max_line_length": 60, "alphanum_fraction": 0.6813655761, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.5064420782248555}}
{"text": "/**\n * Copyright (c) 2017 Melown Technologies SE\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,\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 *\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 HOLDER 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 * @file scattered-interpolation.hpp\n * @author Jakub Cerveny <jakub.cerveny@ext.citationtech.net>\n * @author Matyas Hollmann <matyas.hollmann@melowntech.com>\n *\n * Interpolation on 2D scattered data.\n */\n\n#ifndef imgproc_scattered_interpolation_hpp_included_\n#define imgproc_scattered_interpolation_hpp_included_\n\n#include <vector>\n#include <Eigen/Sparse>\n#include <opencv2/core/core.hpp>\n\n#include \"dbglog/dbglog.hpp\"\n#include \"utility/gccversion.hpp\"\n#include \"rastermask.hpp\"\n\nnamespace imgproc {\n\n#if !defined(IMGPROC_HAS_OPENCV) || !defined(IMGPROC_HAS_EIGEN3)\n    UTILITY_FUNCTION_ERROR(\"Laplace interpolation is available only when \"\n                           \"compiled with both OpenCV and Eigen3 libraries.\")\n#endif\n\n/** Solves the boundary value problem -\\Delta u = 0 on elements in the matrix\n *  'data' that correspond to unset elements in 'mask'. Elements corresponding\n *  to set positions in 'mask' are regarded as given data.\n *\n *  The method is described in section 3.8 \"Laplace Interpolation\" of\n *  Numerical Recipes in C, Third Edition.\n *\n *  typename T_OPT:  floating-point numeric type in which Eigen solves the problem,\n *                   float(faster), double(more precise)\n *  typename T_DATA: numeric type of (per-channel) elements of 'data' matrix,\n *                   if it's an integral type results are rounded before storing\n *  int nChan:       number of channels of 'data' matrix\n *\n *  Example usage: for 'data' matrix of type CV_32FC2 use <float, 2, T_OPT>\n *                 for 'data' matrix of type  CV_8UC3 use <unsigned char, 3, T_OPT>\n */\ntemplate<typename T_DATA, int nChan, typename T_OPT = float>\nvoid laplaceInterpolate(cv::Mat &data, const imgproc::RasterMask &mask, double tol = 1e-12)\n{\n    static_assert(std::is_floating_point<T_OPT>::value,\n                  \"Floating-point numeric type expected.\");\n\n    assert(sizeof(T_DATA) == data.elemSize1() && data.channels() == nChan);\n\n    // round results if 'data' matrix elements are of integral type\n    constexpr bool doRound = std::is_integral<T_DATA>::value;\n\n    using SparseMatrix = Eigen::SparseMatrix<T_OPT>;\n    using Triplet = Eigen::Triplet<T_OPT>;\n    // used to access individual entries in the 'data' matrix\n    using cvVec = cv::Vec<T_DATA, nChan>;\n    // used to access individual entris in the 'rhs' vector,\n    // should be a vector of floating-point types\n    using rhsVecT = cv::Vec<T_OPT, nChan>;\n\n    int w = data.cols, h = data.rows;\n    // # of variables\n    int n = 0;\n\n    auto linearizeID([w](int x, int y) -> int\n    {\n        return y * w + x;\n    });\n\n    auto isInside([w, h](const cv::Point2i& pt) -> bool\n    {\n        return std::min(pt.x, pt.y) >= 0 && pt.x < w && pt.y < h;\n    });\n\n    // optimize only free points, given points should not be a part of the\n    // optimization\n    std::vector<int> pixelIDs(w * h, -1);\n    for (int y = 0; y < h; ++y)\n    for (int x = 0; x < w; ++x)\n    {\n        if (!mask.get(x, y)) // free point\n        {\n            // assing ID and increase value of the counter\n            pixelIDs[linearizeID(x, y)] = n++;\n        }\n    }\n\n    if (!n) // nothing to do here\n    {\n        LOG(debug) << \"All points are given, nothing to do.\";\n        return;\n    }\n\n    // assemble the linear system\n    LOG(debug) << \"Assembling \" << n << \"x\" << n\n               << \" sparse system. # of channels: \" << nChan;\n\n    std::vector<Triplet> coefs;\n    // default constructor = initialize with zeros\n    std::vector<rhsVecT> rhsVec(n, rhsVecT());\n    coefs.reserve(5 * n);\n\n    const static std::array<cv::Point2i, 4> dirs = {{{1, 0}, {-1, 0},\n                                                     {0, 1}, {0, -1}}};\n\n    for (int y = 0; y < h; ++y)\n    for (int x = 0; x < w; ++x)\n    {\n        // index of the unknown\n        int k = pixelIDs[linearizeID(x, y)];\n\n        // given point\n        if (k < 0) { continue; }\n\n        cv::Point2i cur{x, y};\n        // # of neighbors\n        int nNeighs = 0;\n        for (const auto& dir : dirs)\n        {\n            cv::Point2i tmp = cur + dir;\n            if (!isInside(tmp)) { continue; }\n            ++nNeighs;\n\n            // index of the neighboring unknown\n            int t = pixelIDs[linearizeID(tmp.x, tmp.y)];\n            if (t < 0) // neighbor is a given point\n            {\n                // convert 'data' to rhsVecT\n                rhsVec[k] += rhsVecT(data.at<cvVec>(tmp));\n            }\n            else // neighbor is a free point\n            {\n                coefs.emplace_back(k, t, -1.0);\n            }\n        }\n        coefs.emplace_back(k, k, nNeighs);\n    }\n\n    SparseMatrix mat(n, n);\n    mat.setFromTriplets(coefs.begin(), coefs.end());\n\n    LOG(debug) << \"Matrix constructed.\";\n\n    using Precond = Eigen::DiagonalPreconditioner<T_OPT>;\n    using Solver = Eigen::BiCGSTAB<SparseMatrix, Precond>;\n    using EigVecX = Eigen::Matrix<T_OPT, Eigen::Dynamic, 1>;\n\n    // solve the system\n    Solver solver(mat);\n    solver.setTolerance(tol);\n\n    EigVecX rhs(n), sln(n);\n    for (int i = 0; i < nChan; ++i)\n    {\n        for (int j = 0; j < n; ++j) {\n            rhs(j) = rhsVec[j](i);\n        }\n\n        LOG(debug) << \"Solving system with rhs = channel \" << (i + 1)\n                   << \" out of \" << nChan;\n\n        sln = solver.solve(rhs);\n\n        LOG(debug) << \"#iterations: \" << solver.iterations();\n        LOG(debug) << \"estimated error: \" << solver.error();\n        LOG(debug) << \"min: \" << sln.minCoeff() << \", max: \" << sln.maxCoeff();\n\n        // for integral types we should round the results\n        // TODO: in C++17 use if constexpr\n        if (doRound)\n        {\n            for (int j = 0; j < n; ++j) {\n               sln(j) = std::round(sln(j));\n            }\n        }\n\n        // store solution of the i-th channel\n        for (int y = 0; y < h; ++y)\n        for (int x = 0; x < w; ++x)\n        {\n            int id = pixelIDs[linearizeID(x, y)];\n            if (id >= 0) // free point\n            {\n                data.at<cvVec>(y, x)(i) = sln(id);\n            }\n        }\n    }\n}\n\n} // imgproc\n\n#endif // imgproc_scattered_interpolation_hpp_included_\n", "meta": {"hexsha": "785edd2cd31c32be88f7a4640b84e525bba4b56c", "size": 7473, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "imgproc/scattered-interpolation.hpp", "max_stars_repo_name": "melowntech/libimgproc", "max_stars_repo_head_hexsha": "2dc035d12b0d0128f0f97274d2efa62de924b257", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-06-23T19:16:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T08:10:56.000Z", "max_issues_repo_path": "externals/browser/externals/browser/externals/libimgproc/imgproc/scattered-interpolation.hpp", "max_issues_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_issues_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "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": "externals/browser/externals/browser/externals/libimgproc/imgproc/scattered-interpolation.hpp", "max_forks_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_forks_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-03-16T18:24:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-16T18:24:48.000Z", "avg_line_length": 34.1232876712, "max_line_length": 91, "alphanum_fraction": 0.5996253178, "num_tokens": 1951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5064420719017408}}
{"text": "/*******************************************************************\\\n\nModule:\n\nAuthor: Daniel Kroening, kroening@kroening.com\n\n\\*******************************************************************/\n\n#include <util/arith_tools.h>\n#include <util/fixedbv.h>\n#include <util/std_types.h>\n\nfixedbv_spect::fixedbv_spect(const fixedbv_typet &type)\n{\n  integer_bits = type.get_integer_bits();\n  width = type.get_width();\n}\n\nfixedbv_spect::fixedbv_spect(const fixedbv_type2tc &type)\n{\n  integer_bits = type->integer_bits;\n  width = type->get_width();\n}\n\nconst fixedbv_type2tc fixedbv_spect::get_type() const\n{\n  return fixedbv_type2tc(width, integer_bits);\n}\n\nfixedbvt::fixedbvt() : v(0)\n{\n}\n\nfixedbvt::fixedbvt(const fixedbv_spect &s) : spec(s), v(0)\n{\n}\n\nfixedbvt::fixedbvt(const constant_exprt &expr)\n{\n  from_expr(expr);\n}\n\nvoid fixedbvt::from_expr(const constant_exprt &expr)\n{\n  spec = to_fixedbv_type(expr.type());\n  v = binary2integer(id2string(expr.get_value()), true);\n}\n\nvoid fixedbvt::from_integer(const BigInt &i)\n{\n  v = i * power(2, spec.get_fraction_bits());\n}\n\nBigInt fixedbvt::to_integer() const\n{\n  // this rounds to zero, i.e., we just divide\n  return v / power(2, spec.get_fraction_bits());\n}\n\nconstant_exprt fixedbvt::to_expr() const\n{\n  fixedbv_typet type;\n  type.set_width(spec.width);\n  type.set_integer_bits(spec.integer_bits);\n  constant_exprt expr(type);\n  assert(spec.width != 0);\n  expr.set_value(integer2binary(v, spec.width));\n  return expr;\n}\n\nvoid fixedbvt::round(const fixedbv_spect &dest_spec)\n{\n  unsigned old_fraction_bits = spec.width - spec.integer_bits;\n  unsigned new_fraction_bits = dest_spec.width - dest_spec.integer_bits;\n\n  BigInt result = v;\n\n  if(new_fraction_bits > old_fraction_bits)\n    result = v * power(2, new_fraction_bits - old_fraction_bits);\n  else if(new_fraction_bits < old_fraction_bits)\n  {\n    // may need to round\n    BigInt p = power(2, old_fraction_bits - new_fraction_bits);\n    BigInt div = v / p;\n    BigInt rem = v % p;\n    if(rem < 0)\n      rem = -rem;\n\n    if(rem * 2 >= p)\n    {\n      if(v < 0)\n        --div;\n      else\n        ++div;\n    }\n\n    result = div;\n  }\n\n  unsigned old_integer_bits = spec.integer_bits;\n  unsigned new_integer_bits = dest_spec.integer_bits;\n\n  if(old_integer_bits > new_integer_bits)\n  {\n    // Need to cut off some higher bits.\n    fixedbvt tmp;\n    tmp.spec = dest_spec;\n\n    // Make a number that's 2^integer_bits\n    BigInt aval(2);\n    aval = power(aval, new_integer_bits);\n    tmp.from_integer(aval);\n\n    // Now modulus that up.\n    result = result % tmp.v;\n  }\n\n  // Increasing integer bits requires no additional changes to representation.\n\n  v = result;\n  spec = dest_spec;\n}\n\nvoid fixedbvt::negate()\n{\n  v = -v;\n}\n\nfixedbvt &fixedbvt::operator*=(const fixedbvt &o)\n{\n  v *= o.v;\n\n  fixedbv_spect old_spec = spec;\n\n  spec.width += o.spec.width;\n  spec.integer_bits += o.spec.integer_bits;\n\n  round(old_spec);\n\n  return *this;\n}\n\nfixedbvt &fixedbvt::operator/=(const fixedbvt &o)\n{\n  v *= power(2, o.spec.get_fraction_bits());\n  v /= o.v;\n\n  return *this;\n}\n\nbool fixedbvt::operator==(int i) const\n{\n  return v == power(2, spec.get_fraction_bits()) * i;\n}\n\nstd::string fixedbvt::format(const format_spect &format_spec) const\n{\n  std::string dest;\n  unsigned fraction_bits = spec.get_fraction_bits();\n\n  BigInt int_value = v;\n  BigInt factor = power(2, fraction_bits); //BigInt(1)<<fraction_bits;\n\n  if(int_value.is_negative())\n  {\n    dest += '-';\n    int_value.negate();\n  }\n\n  std::string base_10_string =\n    integer2string(int_value * power(10, fraction_bits) / factor);\n\n  while(base_10_string.size() <= fraction_bits)\n    base_10_string = \"0\" + base_10_string;\n\n  std::string integer_part =\n    std::string(base_10_string, 0, base_10_string.size() - fraction_bits);\n\n  std::string fraction_part =\n    std::string(base_10_string, base_10_string.size() - fraction_bits);\n\n  dest += integer_part;\n\n  // strip trailing zeros\n  while(!fraction_part.empty() &&\n        fraction_part[fraction_part.size() - 1] == '0')\n    fraction_part.resize(fraction_part.size() - 1);\n\n  if(!fraction_part.empty())\n    dest += \".\" + fraction_part;\n\n  while(dest.size() < format_spec.min_width)\n    dest = \" \" + dest;\n\n  return dest;\n}\n\nfixedbvt &fixedbvt::operator+=(const fixedbvt &o)\n{\n  v += o.v;\n\n  // No need to change the spec.\n  round(spec);\n\n  return *this;\n}\n\nfixedbvt &fixedbvt::operator-=(const fixedbvt &o)\n{\n  v -= o.v;\n\n  // No need to change the spec.\n  round(spec);\n\n  return *this;\n}\n\nfixedbvt &fixedbvt::operator!()\n{\n  this->negate();\n  return (*this);\n}\n\nbool operator>(const fixedbvt &a, int i)\n{\n  fixedbvt other;\n  other.spec = a.spec;\n  other.from_integer(i);\n  return a > other;\n}\n\nbool operator<(const fixedbvt &a, int i)\n{\n  fixedbvt other;\n  other.spec = a.spec;\n  other.from_integer(i);\n  return a < other;\n}\n\nbool operator>=(const fixedbvt &a, int i)\n{\n  fixedbvt other;\n  other.spec = a.spec;\n  other.from_integer(i);\n  return a >= other;\n}\n\nbool operator<=(const fixedbvt &a, int i)\n{\n  fixedbvt other;\n  other.spec = a.spec;\n  other.from_integer(i);\n  return a <= other;\n}\n\n#ifdef WITH_PYTHON\n#include <boost/python/class.hpp>\n\nvoid build_fixedbv_python_class()\n{\n  using namespace boost::python;\n\n  init<unsigned, unsigned> fbv_spec_init;\n  class_<fixedbv_spect>(\"fixedbv_spec\", fbv_spec_init)\n    .def_readwrite(\"width\", &fixedbv_spect::width)\n    .def_readwrite(\"integer_bits\", &fixedbv_spect::integer_bits)\n    .def(\"get_fraction_bits\", &fixedbv_spect::get_fraction_bits);\n\n  // Only default inits\n  class_<fixedbvt>(\"fixedbv\")\n    .def_readwrite(\"spec\", &fixedbvt::spec)\n    .add_property(\n      \"value\",\n      make_function(\n        &fixedbvt::get_value, return_value_policy<return_by_value>()),\n      make_function(\n        &fixedbvt::set_value, return_value_policy<return_by_value>()))\n    .def(\"from_integer\", &fixedbvt::from_integer)\n    .def(\"to_integer\", &fixedbvt::to_integer)\n    .def(\"round\", &fixedbvt::round);\n}\n\n#endif\n", "meta": {"hexsha": "61a3d3ef54d47443727d898b7f5aa4003d75496a", "size": 5955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util/fixedbv.cpp", "max_stars_repo_name": "pablodiego/esbmc", "max_stars_repo_head_hexsha": "c981c3a7e9fc25d32f39f73bc015ace4fcee2ee7", "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/fixedbv.cpp", "max_issues_repo_name": "pablodiego/esbmc", "max_issues_repo_head_hexsha": "c981c3a7e9fc25d32f39f73bc015ace4fcee2ee7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/fixedbv.cpp", "max_forks_repo_name": "pablodiego/esbmc", "max_forks_repo_head_hexsha": "c981c3a7e9fc25d32f39f73bc015ace4fcee2ee7", "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.9683098592, "max_line_length": 78, "alphanum_fraction": 0.6628043661, "num_tokens": 1644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6406358548398982, "lm_q1q2_score": 0.5064420664778042}}
{"text": "#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <fmt/format.h>\n#include <string>\n#include <iomanip>\n#include <boost/variant.hpp>\n#include <unordered_map>\n#include <cstdint>\n#include <vector>\n#include <algorithm>\n#include <range/v3/algorithm.hpp>\nbool istriangle(std::vector<int> v) noexcept\n{\n  if (v[0] + v[1] <= v[2]) {\n    return false;\n  }\n  for (int i = 0; i < 2; ++i) {\n    std::rotate(v.begin(), v.begin() + 1, v.end());\n    if (v[0] + v[1] <= v[2]) {\n      return false;\n    }\n  }\n  return true;\n}\n\n\nint main(int argc, char **argv)\n{\n  if (argc > 1) {\n    std::ifstream ifs(argv[1]);\n    std::string s;\n    int n = 0;\n    while (std::getline(ifs, s)) {\n      std::vector<int> v;\n      int line;\n      std::istringstream iss(s);\n\n      while (iss >> line) {\n        v.push_back(line);\n      }\n      if (istriangle(v)) {\n        ++n;\n      }\n    }\n    fmt::print(\"triangle count:{}\", n);\n  }\n}", "meta": {"hexsha": "bdecbd02c915fc5b66a5e8cf8da7fd232b897124", "size": 937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc2016/aoc160301.cpp", "max_stars_repo_name": "jiayuehua/adventOfCode", "max_stars_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "aoc2016/aoc160301.cpp", "max_issues_repo_name": "jiayuehua/adventOfCode", "max_issues_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "aoc2016/aoc160301.cpp", "max_forks_repo_name": "jiayuehua/adventOfCode", "max_forks_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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.1224489796, "max_line_length": 51, "alphanum_fraction": 0.5506937033, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5064420610538671}}
{"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/triangulation/triangulation.h\"\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n// #include <glog/logging.h>\n#include <vector>\n\n#include \"theia/matching/feature_correspondence.h\"\n#include \"theia/math/util.h\"\n#include \"theia/sfm/pose/essential_matrix_utils.h\"\n#include \"theia/sfm/pose/fundamental_matrix_util.h\"\n#include \"theia/sfm/pose/util.h\"\n\nnamespace theia {\nnamespace {\n\nusing Eigen::Matrix;\nusing Eigen::MatrixXd;\nusing Eigen::Matrix3d;\nusing Eigen::Matrix4d;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\nusing Eigen::Vector4d;\n\n// Given either a fundamental or essential matrix and two corresponding images\n// points such that ematrix * point2 produces a line in the first image,\n// this method finds corrected image points such that\n// corrected_point1^t * ematrix * corrected_point2 = 0.\nvoid FindOptimalImagePoints(const Matrix3d& ematrix,\n                            const Vector2d& point1,\n                            const Vector2d& point2,\n                            Vector2d* corrected_point1,\n                            Vector2d* corrected_point2) {\n  const Vector3d point1_homog = point1.homogeneous();\n  const Vector3d point2_homog = point2.homogeneous();\n\n  // A helper matrix to isolate certain coordinates.\n  Matrix<double, 2, 3> s_matrix;\n  s_matrix << 1, 0, 0, 0, 1, 0;\n\n  const Eigen::Matrix2d e_submatrix = ematrix.topLeftCorner<2, 2>();\n\n  // The epipolar line from one image point in the other image.\n  Vector2d epipolar_line1 = s_matrix * ematrix * point2_homog;\n  Vector2d epipolar_line2 = s_matrix * ematrix.transpose() * point1_homog;\n\n  const double a = epipolar_line1.transpose() * e_submatrix * epipolar_line2;\n  const double b =\n      (epipolar_line1.squaredNorm() + epipolar_line2.squaredNorm()) / 2.0;\n  const double c = point1_homog.transpose() * ematrix * point2_homog;\n\n  const double d = sqrt(b * b - a * c);\n\n  double lambda = c / (b + d);\n  epipolar_line1 -= e_submatrix * lambda * epipolar_line1;\n  epipolar_line2 -= e_submatrix.transpose() * lambda * epipolar_line2;\n\n  lambda *=\n      (2.0 * d) / (epipolar_line1.squaredNorm() + epipolar_line2.squaredNorm());\n\n  *corrected_point1 =\n      (point1_homog - s_matrix.transpose() * lambda * epipolar_line1)\n          .hnormalized();\n  *corrected_point2 =\n      (point2_homog - s_matrix.transpose() * lambda * epipolar_line2)\n          .hnormalized();\n}\n\n}  // namespace\n\n// Triangulates 2 posed views\nbool Triangulate(const Matrix3x4d& pose1,\n                 const Matrix3x4d& pose2,\n                 const Vector2d& point1,\n                 const Vector2d& point2,\n                 Vector4d* triangulated_point) {\n  Eigen::Matrix3d ematrix;\n  EssentialMatrixFromTwoProjectionMatrices(pose1, pose2, &ematrix);\n\n  Vector2d corrected_point1, corrected_point2;\n  FindOptimalImagePoints(\n      ematrix, point1, point2, &corrected_point1, &corrected_point2);\n\n  // Now the two points are guaranteed to intersect. We can use the DLT method\n  // since it is easy to construct.\n  return TriangulateDLT(\n      pose1, pose2, corrected_point1, corrected_point2, triangulated_point);\n}\n\n// Triangulates a 3D point by determining the closest point between the two\n// rays. This method is known to be suboptimal in terms of reprojection error\n// but it is extremely fast.\nbool TriangulateMidpoint(const std::vector<Vector3d>& ray_origin,\n                         const std::vector<Vector3d>& ray_direction,\n                         Eigen::Vector4d* triangulated_point) {\n  assert(triangulated_point != nullptr);\n  assert(ray_origin.size() >= 2);\n  assert(ray_origin.size() == ray_direction.size());\n\n  Eigen::Matrix4d A;\n  A.setZero();\n  Eigen::Vector4d b;\n  b.setZero();\n  for (int i = 0; i < ray_origin.size(); i++) {\n    const Eigen::Vector4d ray_direction_homog(\n        ray_direction[i].x(), ray_direction[i].y(), ray_direction[i].z(), 0);\n    const Eigen::Matrix4d A_term =\n        Eigen::Matrix4d::Identity() -\n        ray_direction_homog * ray_direction_homog.transpose();\n    A += A_term;\n    b += A_term * ray_origin[i].homogeneous();\n  }\n\n  Eigen::LLT<Eigen::Matrix4d> linear_solver(A);\n  if (linear_solver.info() != Eigen::Success) {\n    return false;\n  }\n  *triangulated_point = linear_solver.solve(b);\n  return linear_solver.info() == Eigen::Success;\n}\n\n// Triangulates 2 posed views\nbool TriangulateDLT(const Matrix3x4d& pose1,\n                    const Matrix3x4d& pose2,\n                    const Vector2d& point1,\n                    const Vector2d& point2,\n                    Vector4d* triangulated_point) {\n  Matrix4d design_matrix;\n  design_matrix.row(0) = point1[0] * pose1.row(2) - pose1.row(0);\n  design_matrix.row(1) = point1[1] * pose1.row(2) - pose1.row(1);\n  design_matrix.row(2) = point2[0] * pose2.row(2) - pose2.row(0);\n  design_matrix.row(3) = point2[1] * pose2.row(2) - pose2.row(1);\n\n  // Extract nullspace.\n  *triangulated_point =\n      design_matrix.jacobiSvd(Eigen::ComputeFullV).matrixV().rightCols<1>();\n  return true;\n}\n\n// Triangulates N views by computing SVD that minimizes the error.\nbool TriangulateNViewSVD(const std::vector<Matrix3x4d>& poses,\n                         const std::vector<Vector2d>& points,\n                         Vector4d* triangulated_point) {\n  assert(poses.size() == points.size());\n\n  MatrixXd design_matrix(3 * points.size(), 4 + points.size());\n\n  for (int i = 0; i < points.size(); i++) {\n    design_matrix.block<3, 4>(3 * i, 0) = -poses[i].matrix();\n    design_matrix.block<3, 1>(3 * i, 4 + i) = points[i].homogeneous();\n  }\n\n  *triangulated_point = design_matrix.jacobiSvd(Eigen::ComputeFullV)\n                            .matrixV()\n                            .rightCols<1>()\n                            .head(4);\n  return true;\n}\n\nbool TriangulateNView(const std::vector<Matrix3x4d>& poses,\n                      const std::vector<Vector2d>& points,\n                      Vector4d* triangulated_point) {\n  assert(poses.size() == points.size());\n\n  Matrix4d design_matrix = Matrix4d::Zero();\n  for (int i = 0; i < points.size(); i++) {\n    const Vector3d norm_point = points[i].homogeneous().normalized();\n    const Eigen::Matrix<double, 3, 4> cost_term =\n        poses[i].matrix() -\n        norm_point * norm_point.transpose() * poses[i].matrix();\n    design_matrix = design_matrix + cost_term.transpose() * cost_term;\n  }\n\n  Eigen::SelfAdjointEigenSolver<Matrix4d> eigen_solver(design_matrix);\n  *triangulated_point = eigen_solver.eigenvectors().col(0);\n  return eigen_solver.info() == Eigen::Success;\n}\n\nbool IsTriangulatedPointInFrontOfCameras(\n    const FeatureCorrespondence& correspondence,\n    const Matrix3d& rotation,\n    const Vector3d& position) {\n  const Vector3d dir1 = correspondence.feature1.homogeneous();\n  const Vector3d dir2 =\n      rotation.transpose() * correspondence.feature2.homogeneous();\n\n  const double dir1_sq = dir1.squaredNorm();\n  const double dir2_sq = dir2.squaredNorm();\n  const double dir1_dir2 = dir1.dot(dir2);\n  const double dir1_pos = dir1.dot(position);\n  const double dir2_pos = dir2.dot(position);\n\n  return (dir2_sq * dir1_pos - dir1_dir2 * dir2_pos > 0 &&\n          dir1_dir2 * dir1_pos - dir1_sq * dir2_pos > 0);\n}\n\n// Returns true if the triangulation angle between any two observations is\n// sufficient.\nbool SufficientTriangulationAngle(\n    const std::vector<Eigen::Vector3d>& ray_directions,\n    const double min_triangulation_angle_degrees) {\n  // Test that the angle between the rays is sufficient.\n  const double cos_of_min_angle =\n      cos(DegToRad(min_triangulation_angle_degrees));\n  for (int i = 0; i < ray_directions.size(); i++) {\n    for (int j = i + 1; j < ray_directions.size(); j++) {\n      if (ray_directions[i].dot(ray_directions[j]) < cos_of_min_angle) {\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "70fc7dfd840f6ceec9abf1e834c558be7ff0fad3", "size": 9656, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/triangulation/triangulation.cc", "max_stars_repo_name": "SpectacularAI/TheiaSfM", "max_stars_repo_head_hexsha": "3dbb45cd6c239a4bab2beb46812c4ba7094a0625", "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/theia/sfm/triangulation/triangulation.cc", "max_issues_repo_name": "SpectacularAI/TheiaSfM", "max_issues_repo_head_hexsha": "3dbb45cd6c239a4bab2beb46812c4ba7094a0625", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/triangulation/triangulation.cc", "max_forks_repo_name": "SpectacularAI/TheiaSfM", "max_forks_repo_head_hexsha": "3dbb45cd6c239a4bab2beb46812c4ba7094a0625", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-19T19:01:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T19:01:13.000Z", "avg_line_length": 38.1660079051, "max_line_length": 80, "alphanum_fraction": 0.6853769677, "num_tokens": 2499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5064420493068158}}
{"text": "#include <boost/math/special_functions/ellint_rf.hpp>\n", "meta": {"hexsha": "dd5f666d1f32aa139b6e3c60eaa360e9db8f420c", "size": 54, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_ellint_rf.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_ellint_rf.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_ellint_rf.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.0, "max_line_length": 53, "alphanum_fraction": 0.8333333333, "num_tokens": 13, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5063806650870157}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 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_ARCH_COMMON_FUNCTION_SCALAR_ATANH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_ATANH_HPP_INCLUDED\n#include <boost/simd/function/std.hpp>\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/scalar/bitofsign.hpp>\n#include <boost/simd/function/scalar/bitwise_xor.hpp>\n#include <boost/simd/function/scalar/fma.hpp>\n#include <boost/simd/function/scalar/log1p.hpp>\n#include <boost/simd/function/scalar/oneminus.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( atanh_\n                          , (typename A0)\n                             , bd::cpu_\n                            , bd::scalar_< bd::floating_<A0> >\n                            )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 absa0 = bs::abs(a0);\n      A0 t =  absa0+absa0;\n      A0 z1 = oneminus(absa0);\n      return bitwise_xor(bitofsign(a0),\n                         Half<A0>()*log1p((absa0 < Half<A0>())\n                                          ? fma(t, absa0/z1, t)\n                                          : t/z1)\n                        );\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( atanh_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bs::std_tag\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0  a0, std_tag const&) const BOOST_NOEXCEPT\n    {\n      return std::atanh(a0);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "8b2caef0e1d1fa87c8f4a118cef0dfc528fd1319", "size": 2161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/atanh.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/arch/common/scalar/function/atanh.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/arch/common/scalar/function/atanh.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": 32.7424242424, "max_line_length": 100, "alphanum_fraction": 0.5205923184, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5063806650870156}}
{"text": "// faster alternative to ExpPlusPPTrajectory.eval() in Matlab\n// Michael Kaess, June 2013\n\n#include <mex.h>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <vector>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\n\n// Initialization:\n//   obj = ExpPlusPPTrajectoryEvalmex(breaks,K,A,alpha,gamma)\n// Evaluation:\n//   [y,jj] = ExpPlusPPTrajectoryEvalmex(obj, t)\n//\n// t:      m      vector of evaluation points\n//\n// breaks: n+1\n// K:      d x a\n// A:      a x a\n// alpha:  a x n\n// gamma:  dxn x p - reshape!\n//\n// y:      p x m\n// jj:     m\n\n\n\nclass Eval {\n\nprivate:\n\n  const VectorXd m_breaks;\n  const MatrixXd m_K, m_A, m_alpha, m_gamma;\n  const int m_n, m_d, m_p;\n\npublic:\n\n  MatrixXd expm(const MatrixXd& A) {\n    MatrixXd F;\n    MatrixExponential<MatrixXd>(A).compute(F);\n    return F;\n  }\n\n  Eval(const VectorXd& breaks, const MatrixXd& K, const MatrixXd& A, const MatrixXd& alpha, const MatrixXd& gamma) : m_breaks(breaks), m_K(K), m_A(A), m_alpha(alpha), m_gamma(gamma), m_n(alpha.cols()), m_d(K.rows()), m_p(gamma.cols()) {}\n\n  int dim() {\n    return m_d;\n  }\n\n  VectorXd term(int j, double trel) {\n    VectorXd trels(m_p);\n    trels(0) = (trel<0)?-1.:1.;\n    for (int i=1; i<m_p; i++) {\n      trels(i) = trels(i-1) * trel; \n    }\n    const MatrixXd gammaj = m_gamma.block(j*m_d,0,m_d,m_p);\n    return m_K*expm(m_A*trel)*m_alpha.col(j) + gammaj*trels;\n  }\n\n  void compute(const VectorXd& t, Map<MatrixXd>& y, Map<MatrixXd>& jj) {\n    int m = t.rows();\n    for(int k=0; k<m; k++) {\n      double tk = t(k);\n      // find the right interval\n      int j = 0;\n      for (int b=1; b<m_n; b++) { // todo: binary search\n        if (tk >= m_breaks(b)) j=b;\n      }\n      double trel = tk - m_breaks(j);\n      y.col(k) = term(j,trel);\n      jj(k) = j+1; // convert to Matlab convention\n    }\n  }\n\n};\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n  if (nrhs == 5 && nlhs == 1) {\n\n    // create object\n    Map<VectorXd> breaks(mxGetPr(prhs[0]), mxGetNumberOfElements(prhs[0]));\n    Map<MatrixXd>      K(mxGetPr(prhs[1]), mxGetM(prhs[1]), mxGetN(prhs[1]));\n    Map<MatrixXd>      A(mxGetPr(prhs[2]), mxGetM(prhs[2]), mxGetN(prhs[2]));\n    Map<MatrixXd>  alpha(mxGetPr(prhs[3]), mxGetM(prhs[3]), mxGetN(prhs[3]));\n    Map<MatrixXd>  gamma(mxGetPr(prhs[4]), mxGetM(prhs[4]), mxGetN(prhs[4]));\n\n    Eval *eval = new Eval(breaks, K, A, alpha, gamma);\n    mxClassID cid;\n    if (sizeof(eval)==4) cid = mxUINT32_CLASS;\n    else if (sizeof(eval)==8) cid = mxUINT64_CLASS;\n    else mexErrMsgIdAndTxt(\"Drake:ExpPlusPPTmex:PointerSize\",\"Are you on a 32-bit machine or 64-bit machine??\");\n    plhs[0] = mxCreateNumericMatrix(1,1,cid,mxREAL);\n    memcpy(mxGetData(plhs[0]),&eval,sizeof(eval));\n    \n    //    mexPrintf(\"constructor\\n\"); mexCallMATLAB(0,NULL,0,NULL,\"drawnow\");\n\n  } else {\n\n    // retrieve object\n    Eval *eval = NULL;\n    if (nrhs==0 || !mxIsNumeric(prhs[0]) || mxGetNumberOfElements(prhs[0])!=1)\n      mexErrMsgIdAndTxt(\"Drake:ExpPlusPPTmex:BadInputs\",\"the first argument should be the mex_ptr\");\n    memcpy(&eval,mxGetData(prhs[0]),sizeof(eval));\n\n    if (nrhs == 1) {\n      //      mexPrintf(\"delete\\n\"); mexCallMATLAB(0,NULL,0,NULL,\"drawnow\");\n\n      // delete object   \n      if (eval)\n\tdelete eval;\n\n    } else {\n\n      //      mexPrintf(\"eval\\n\"); mexCallMATLAB(0,NULL,0,NULL,\"drawnow\");\n\n      // eval() function call\n      if (nrhs != 2 || nlhs != 2) {\n        mexErrMsgIdAndTxt(\"Drake:ExpPlusPPTmex:WrongNumberOfInputs\",\"Usage obj = ExpPlusPPTmex(breaks,K,A,alpha,gamma) or [y,jj] = ExpPlusPPTmex(obj,t)\");\n      }\n\n      Map<VectorXd> t(mxGetPr(prhs[1]), mxGetNumberOfElements(prhs[1]));\n\n      int m = t.rows();\n      int d = eval->dim();\n\n      plhs[0] = mxCreateDoubleMatrix(d,m,mxREAL);\n      Map<MatrixXd> y(mxGetPr(plhs[0]),d,m);\n      plhs[1] = mxCreateDoubleMatrix(m,1,mxREAL);\n      Map<MatrixXd> jj(mxGetPr(plhs[1]),m,1);\n\n      eval->compute(t, y, jj);\n\n    }\n\n  }\n\n}\n", "meta": {"hexsha": "a6ad38002ae0da2598e68d03538cbc2a056858ba", "size": 3972, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "systems/trajectories/ExpPlusPPTrajectoryEvalmex.cpp", "max_stars_repo_name": "cmmccann/drake", "max_stars_repo_head_hexsha": "0a124c044357d5a29ec7e536acb747cfa5682eba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-12T14:32:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-12T14:32:29.000Z", "max_issues_repo_path": "systems/trajectories/ExpPlusPPTrajectoryEvalmex.cpp", "max_issues_repo_name": "cmmccann/drake", "max_issues_repo_head_hexsha": "0a124c044357d5a29ec7e536acb747cfa5682eba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "systems/trajectories/ExpPlusPPTrajectoryEvalmex.cpp", "max_forks_repo_name": "cmmccann/drake", "max_forks_repo_head_hexsha": "0a124c044357d5a29ec7e536acb747cfa5682eba", "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.9718309859, "max_line_length": 237, "alphanum_fraction": 0.6095166163, "num_tokens": 1312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245828938679, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.50638065754096}}
{"text": "//  Copyright (c) 2014 Anton Bikineev\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//  Appends negative test cases to the *.ipp files.\r\n//  Takes the next parameters:\r\n//  -f <file> file where the negative values will be appended;\r\n//  -x add minus to existing x values and append result;\r\n//  -v, -xv like previous option.\r\n//  Usage example:\r\n//  ./bessel_derivative_append_negative -f \"bessel_y_derivative_large_data.ipp\" -x -v -xv\r\n\r\n#include <fstream>\r\n#include <utility>\r\n#include <functional>\r\n#include <map>\r\n#include <vector>\r\n#include <iterator>\r\n#include <algorithm>\r\n\r\n#include <boost/multiprecision/mpfr.hpp>\r\n#include <boost/program_options.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n\r\n#include <boost/math/special_functions/bessel.hpp>\r\n\r\ntemplate <class T>\r\nT bessel_j_derivative_bare(T v, T x)\r\n{\r\n   return (v / x) * boost::math::cyl_bessel_j(v, x) - boost::math::cyl_bessel_j(v+1, x);\r\n}\r\n\r\ntemplate <class T>\r\nT bessel_y_derivative_bare(T v, T x)\r\n{\r\n   return (v / x) * boost::math::cyl_neumann(v, x) - boost::math::cyl_neumann(v+1, x);\r\n}\r\n\r\ntemplate <class T>\r\nT bessel_i_derivative_bare(T v, T x)\r\n{\r\n   return (v / x) * boost::math::cyl_bessel_i(v, x) + boost::math::cyl_bessel_i(v+1, x);\r\n}\r\n\r\ntemplate <class T>\r\nT bessel_k_derivative_bare(T v, T x)\r\n{\r\n   return (v / x) * boost::math::cyl_bessel_k(v, x) - boost::math::cyl_bessel_k(v+1, x);\r\n}\r\n\r\ntemplate <class T>\r\nT sph_bessel_j_derivative_bare(T v, T x)\r\n{\r\n   if((v < 0) || (floor(v) != v))\r\n      throw std::domain_error(\"\");\r\n   if(v == 0)\r\n      return -boost::math::sph_bessel(1, x);\r\n   return boost::math::sph_bessel(itrunc(v-1), x) - ((v + 1) / x) * boost::math::sph_bessel(itrunc(v), x);\r\n}\r\n\r\ntemplate <class T>\r\nT sph_bessel_y_derivative_bare(T v, T x)\r\n{\r\n   if((v < 0) || (floor(v) != v))\r\n      throw std::domain_error(\"\");\r\n   if(v == 0)\r\n      return -boost::math::sph_neumann(1, x);\r\n   return boost::math::sph_neumann(itrunc(v-1), x) - ((v + 1) / x) * boost::math::sph_neumann(itrunc(v), x);\r\n}\r\n\r\nnamespace opt = boost::program_options;\r\nusing FloatType = boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<200u> >;\r\nusing Function = FloatType(*)(FloatType, FloatType);\r\nusing Lines = std::vector<std::string>;\r\n\r\nenum class Negate: char\r\n{\r\n   x,\r\n   v,\r\n   xv\r\n};\r\n\r\nnamespace\r\n{\r\n\r\nconst unsigned kSignificand = 50u;\r\n\r\nstd::map<std::string, Function> kFileMapper = {\r\n   {\"bessel_j_derivative_data.ipp\", ::bessel_j_derivative_bare},\r\n   {\"bessel_j_derivative_int_data.ipp\", ::bessel_j_derivative_bare},\r\n   {\"bessel_j_derivative_large_data.ipp\", ::bessel_j_derivative_bare},\r\n   {\"bessel_y01_derivative_data.ipp\", ::bessel_y_derivative_bare},\r\n   {\"bessel_yn_derivative_data.ipp\", ::bessel_y_derivative_bare},\r\n   {\"bessel_yv_derivative_data.ipp\", ::bessel_y_derivative_bare},\r\n   {\"bessel_i_derivative_data.ipp\", ::bessel_i_derivative_bare},\r\n   {\"bessel_i_derivative_int_data.ipp\", ::bessel_i_derivative_bare},\r\n   {\"bessel_k_derivative_data.ipp\", ::bessel_k_derivative_bare},\r\n   {\"bessel_k_derivative_int_data.ipp\", ::bessel_k_derivative_bare},\r\n   {\"sph_bessel_derivative_data.ipp\", ::sph_bessel_j_derivative_bare},\r\n   {\"sph_neumann_derivative_data.ipp\", ::sph_bessel_y_derivative_bare}\r\n};\r\n\r\nFunction fp = ::bessel_j_derivative_bare;\r\n\r\nLines getSourcePartOfFile(std::fstream& file)\r\n{\r\n   file.seekg(std::ios::beg);\r\n\r\n   Lines lines;\r\n   while (true)\r\n   {\r\n      auto line = std::string{};\r\n      std::getline(file, line);\r\n      if (line.find(\"}};\") != std::string::npos)\r\n         break;\r\n      lines.push_back(line);\r\n   }\r\n   file.seekg(std::ios::beg);\r\n   return lines;\r\n}\r\n\r\nstd::pair<std::string, std::string::iterator> parseValue(std::string::iterator& iter)\r\n{\r\n   using std::isdigit;\r\n\r\n   auto value = std::string{};\r\n   auto iterator = std::string::iterator{};\r\n\r\n   while (!isdigit(*iter) && *iter != '-')\r\n      ++iter;\r\n   iterator = iter;\r\n   while (isdigit(*iter) || *iter == '.' || *iter == 'e' || *iter == '-' || *iter == '+')\r\n   {\r\n      value.push_back(*iter);\r\n      ++iter;\r\n   }\r\n   return {value, iterator};\r\n}\r\n\r\nvoid addMinusToValue(std::string& line, Negate which)\r\n{\r\n   using std::isdigit;\r\n\r\n   auto iter = line.begin();\r\n   switch (which)\r\n   {\r\n      case Negate::x:\r\n      {\r\n         ::parseValue(iter);\r\n         auto value_begin = ::parseValue(iter).second;\r\n         if (*value_begin != '-')\r\n            line.insert(value_begin, '-');\r\n         break;\r\n      }\r\n      case Negate::v:\r\n      {\r\n         auto value_begin = ::parseValue(iter).second;\r\n         if (*value_begin != '-')\r\n            line.insert(value_begin, '-');\r\n         break;\r\n      }\r\n      case Negate::xv:\r\n      {\r\n         auto v_value_begin = ::parseValue(iter).second;\r\n         if (*v_value_begin != '-')\r\n            line.insert(v_value_begin, '-');\r\n         // iterator could get invalid\r\n         iter = line.begin();\r\n         ::parseValue(iter);\r\n         auto x_value_begin = ::parseValue(iter).second;\r\n         if (*x_value_begin != '-')\r\n            line.insert(x_value_begin, '-');\r\n         break;\r\n      }\r\n   }\r\n}\r\n\r\nvoid replaceResultInLine(std::string& line)\r\n{\r\n   using std::isdigit;\r\n\r\n   auto iter = line.begin();\r\n\r\n   // parse v and x values from line and convert them to FloatType\r\n   auto v = FloatType{::parseValue(iter).first};\r\n   auto x = FloatType{::parseValue(iter).first};\r\n   auto result = fp(v, x).str(kSignificand);\r\n\r\n   while (!isdigit(*iter) && *iter != '-')\r\n      ++iter;\r\n   const auto where_to_write = iter;\r\n   while (isdigit(*iter) || *iter == '.' || *iter == 'e' || *iter == '-' || *iter == '+')\r\n      line.erase(iter);\r\n\r\n   line.insert(where_to_write, result.begin(), result.end());\r\n}\r\n\r\nLines processValues(const Lines& source_lines, Negate which)\r\n{\r\n   using std::placeholders::_1;\r\n\r\n   auto processed_lines = source_lines;\r\n   std::for_each(std::begin(processed_lines), std::end(processed_lines), std::bind(&addMinusToValue, _1, which));\r\n   std::for_each(std::begin(processed_lines), std::end(processed_lines), &replaceResultInLine);\r\n\r\n   return processed_lines;\r\n}\r\n\r\nvoid updateTestCount(Lines& source_lines, std::size_t mult)\r\n{\r\n   using std::isdigit;\r\n\r\n   const auto where = std::find_if(std::begin(source_lines), std::end(source_lines),\r\n      [](const std::string& str){ return str.find(\"boost::array\") != std::string::npos; });\r\n   auto& str = *where;\r\n   const auto pos = str.find(\">, \") + 3;\r\n   auto digits_length = 0;\r\n\r\n   auto k = pos;\r\n   while (isdigit(str[k++]))\r\n      ++digits_length;\r\n\r\n   const auto new_value = mult * boost::lexical_cast<std::size_t>(str.substr(pos, digits_length));\r\n   str.replace(pos, digits_length, boost::lexical_cast<std::string>(new_value));\r\n}\r\n\r\n} // namespace\r\n\r\nint main(int argc, char*argv [])\r\n{\r\n   auto desc = opt::options_description{\"All options\"};\r\n   desc.add_options()\r\n      (\"help\", \"produce help message\")\r\n      (\"file\", opt::value<std::string>()->default_value(\"bessel_j_derivative_data.ipp\"))\r\n      (\"x\", \"append negative x\")\r\n      (\"v\", \"append negative v\")\r\n      (\"xv\", \"append negative x and v\");\r\n   opt::variables_map vm;\r\n   opt::store(opt::command_line_parser(argc, argv).options(desc)\r\n         .style(opt::command_line_style::default_style |\r\n         opt::command_line_style::allow_long_disguise)\r\n      .run(),vm);\r\n   opt::notify(vm);\r\n\r\n   if (vm.count(\"help\"))\r\n   {\r\n      std::cout << desc;\r\n      return 0;\r\n   }\r\n\r\n   auto filename = vm[\"file\"].as<std::string>();\r\n   fp = kFileMapper[filename];\r\n\r\n   std::fstream file{filename.c_str()};\r\n   if (!file.is_open())\r\n      return -1;\r\n   auto source_part = ::getSourcePartOfFile(file);\r\n   source_part.back().push_back(',');\r\n\r\n   auto cases_lines = Lines{};\r\n   for (const auto& str: source_part)\r\n   {\r\n      if (str.find(\"SC_\") != std::string::npos)\r\n         cases_lines.push_back(str);\r\n   }\r\n\r\n   auto new_lines = Lines{};\r\n   new_lines.reserve(cases_lines.size());\r\n\r\n   std::size_t mult = 1;\r\n   if (vm.count(\"x\"))\r\n   {\r\n      std::cout << \"process x...\" << std::endl;\r\n      const auto x_lines = ::processValues(cases_lines, Negate::x);\r\n      new_lines.insert(std::end(new_lines), std::begin(x_lines), std::end(x_lines));\r\n      ++mult;\r\n   }\r\n   if (vm.count(\"v\"))\r\n   {\r\n      std::cout << \"process v...\" << std::endl;\r\n      const auto v_lines = ::processValues(cases_lines, Negate::v);\r\n      new_lines.insert(std::end(new_lines), std::begin(v_lines), std::end(v_lines));\r\n      ++mult;\r\n   }\r\n   if (vm.count(\"xv\"))\r\n   {\r\n      std::cout << \"process xv...\" << std::endl;\r\n      const auto xv_lines = ::processValues(cases_lines, Negate::xv);\r\n      new_lines.insert(std::end(new_lines), std::begin(xv_lines), std::end(xv_lines));\r\n      ++mult;\r\n   }\r\n\r\n   source_part.insert(std::end(source_part), std::begin(new_lines), std::end(new_lines));\r\n   ::updateTestCount(source_part, mult);\r\n\r\n   file.close();\r\n   file.open(filename, std::ios::out | std::ios::trunc);\r\n   std::for_each(std::begin(source_part), std::end(source_part), [&file](const std::string& str)\r\n      { file << str << std::endl; });\r\n   file << \"   }};\";\r\n\r\n   std::cout << \"processed, ok\\n\";\r\n   return 0;\r\n}\r\n", "meta": {"hexsha": "29eb94d17d728c5644ac7be2b2fa0d5388e2c210", "size": 9293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/tools/bessel_derivative_append_negative.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/math/tools/bessel_derivative_append_negative.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/tools/bessel_derivative_append_negative.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 30.3692810458, "max_line_length": 114, "alphanum_fraction": 0.6135801141, "num_tokens": 2518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5063758943931976}}
{"text": "#include <Rcpp.h>\n#include <dlib/pixel.h>\n#include <dlib/array2d.h>\n#include <dlib/matrix.h>\n//#include <dlib/image_loader/image_loader.h>\n#include <dlib/image_transforms/fhog.h>\nusing namespace dlib;\n\n// [[Rcpp::export]]\nRcpp::List dlib_fhog(std::vector<int> x, int rows, int cols, \n                     const int cell_size = 8,\n                     const int filter_rows_padding = 1,\n                     const int filter_cols_padding = 1) {\n  // Import from file\n  //array2d<rgb_pixel> img;\n  //load_bmp(img, file.c_str());\n  array2d<rgb_pixel> img;\n  img.set_size(rows, cols);\n  for(int r = 0; r < rows; r++){\n    for(int c = 0; c < cols; c++){\n      int index = c*3 + r*cols*3;\n      assign_pixel(img[r][c], rgb_pixel(x[index], x[index + 1], x[index + 2]));\n    }  \n  }\n  // Compute HOG features\n  array2d<matrix<float,31,1> > hog;\n  extract_fhog_features(img, hog, cell_size, filter_rows_padding, filter_cols_padding);\n\n  Rcpp::NumericVector fhog(hog.nr() * hog.nc() * 31);\n  int i = 0;\n  for(int feat = 0; feat < 31; feat++){\n    for(int x_i = 0; x_i < hog.nc(); x_i++){ // x is hog_width\n      for(int y_i = 0; y_i < hog.nr(); y_i++){ // y is hog_height\n        fhog[i] = hog[y_i][x_i](feat, 0);\n        i = i + 1;\n      }\n    }\n  }\n\n  return Rcpp::List::create(Rcpp::Named(\"hog_height\") = hog.nr(),\n                            Rcpp::Named(\"hog_width\") = hog.nc(),\n                            Rcpp::Named(\"fhog\") = fhog,\n                            Rcpp::Named(\"hog_cell_size\") = cell_size,\n                            Rcpp::Named(\"filter_rows_padding\") = filter_rows_padding,\n                            Rcpp::Named(\"filter_cols_padding\") = filter_cols_padding);\n}\n", "meta": {"hexsha": "f368dafabd8da10f071b3a558210aba7a41c5c0c", "size": 1674, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "image.dlib/src/rcpp_fhog.cpp", "max_stars_repo_name": "LALMAN2000/bnosa", "max_stars_repo_head_hexsha": "d37e869c724736133b0ac1513a366817bb2dc5c1", "max_stars_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "MIT"], "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": "image.dlib/src/rcpp_fhog.cpp", "max_issues_repo_name": "LALMAN2000/bnosa", "max_issues_repo_head_hexsha": "d37e869c724736133b0ac1513a366817bb2dc5c1", "max_issues_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "MIT"], "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": "image.dlib/src/rcpp_fhog.cpp", "max_forks_repo_name": "LALMAN2000/bnosa", "max_forks_repo_head_hexsha": "d37e869c724736133b0ac1513a366817bb2dc5c1", "max_forks_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "MIT"], "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": 35.6170212766, "max_line_length": 87, "alphanum_fraction": 0.5579450418, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5063758892383154}}
{"text": "#include <armadillo>\n\nint main() {\n\n    arma::cube c(3, 3, 5);\n    for (size_t s = 0; s < c.n_slices; s++)\n        c.slice(s).fill(s);\n\n    c.print(\"c\");\n\n    arma::sum(c, 2).print(\"c sum 2\");\n\n    return 0;\n\n}\n", "meta": {"hexsha": "ebcff6854a00df420da0f02d07b61cbf72d68301", "size": 211, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/armadillo/arma_sum.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_sum.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_sum.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": 13.1875, "max_line_length": 43, "alphanum_fraction": 0.4834123223, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5063758840834331}}
{"text": "#define BOOST_TEST_MODULE unary\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"exprtest.hpp\"\n\nEXPRTEST(unary1, \"-(2)\",  -2)\nEXPRTEST(unary2, \"-(-2)\",  2)\nEXPRTEST(unary3, \"+(-2)\", -2)\nEXPRTEST(unary4, \"+(+2)\",  2)\n", "meta": {"hexsha": "221eae2a9974221c945b16a6b8950303e58689b8", "size": 241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unary.cpp", "max_stars_repo_name": "fweik/boost_matheval", "max_stars_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "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": "tests/unary.cpp", "max_issues_repo_name": "fweik/boost_matheval", "max_issues_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "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": "tests/unary.cpp", "max_forks_repo_name": "fweik/boost_matheval", "max_forks_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "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.1, "max_line_length": 35, "alphanum_fraction": 0.6763485477, "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5063758822686133}}
{"text": "#include <fstream>\n#include <boost/config.hpp>\n#include <boost/version.hpp>\n// CGAL headers\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Apollonius_graph_2.h>\n#include <CGAL/Apollonius_graph_hierarchy_2.h>\n#include <CGAL/Apollonius_graph_filtered_traits_2.h>\n#include <CGAL/point_generators_2.h>\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#include <CGAL/IO/WKT.h>\n#endif\n\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_real.hpp>\n\n// Qt headers\n#include <QtGui>\n#include <QString>\n#include <QActionGroup>\n#include <QFileDialog>\n#include <QInputDialog>\n\n// GraphicsView items and event filters (input classes)\n#include <CGAL/Qt/ApolloniusGraphGraphicsItem.h>\n#include <CGAL/Qt/GraphicsViewCircleInput.h>\n\n// for viewportsBbox\n#include <CGAL/Qt/utility.h>\n\n// the two base classes\n#include \"ui_Apollonius_graph_2.h\"\n#include <CGAL/Qt/DemosMainWindow.h>\n\ntypedef CGAL::Simple_cartesian<double> K;\ntypedef K::Point_2 Point_2;\ntypedef K::Iso_rectangle_2 Iso_rectangle_2;\n\ntypedef CGAL::Apollonius_graph_filtered_traits_2<K,CGAL::Integral_domain_without_division_tag>  Gt;\n\ntypedef Gt::Point_2                           Point_2;\ntypedef K::Circle_2                           Circle_2;\ntypedef Gt::Site_2                            Apollonius_site_2;\ntypedef Gt::Site_2::Weight                    Weight;\n\ntypedef CGAL::Apollonius_graph_2<Gt> Apollonius;\n\n\nclass MainWindow :\n  public CGAL::Qt::DemosMainWindow,\n  public Ui::Apollonius_graph_2\n{\n  Q_OBJECT\n\nprivate:\n  Apollonius ag;\n  QGraphicsScene scene;\n\n  CGAL::Qt::ApolloniusGraphGraphicsItem<Apollonius,K> * agi;\n  CGAL::Qt::GraphicsViewCircleInput<K> * ci;\n\npublic:\n  MainWindow();\n\npublic Q_SLOTS:\n\n  void processInput(CGAL::Object o);\n\n  void on_actionInsertRandomPoints_triggered();\n\n  void on_actionLoadPoints_triggered();\n\n  void on_actionSavePoints_triggered();\n\n  void on_actionClear_triggered();\n\n  void on_actionRecenter_triggered();\n\n  virtual void open(QString fileName);\n\nQ_SIGNALS:\n  void changed();\n};\n\n\nMainWindow::MainWindow()\n  : DemosMainWindow()\n{\n  setupUi(this);\n\n  this->graphicsView->setAcceptDrops(false);\n\n  agi = new CGAL::Qt::ApolloniusGraphGraphicsItem<Apollonius, K>(&ag);\n\n  QObject::connect(this, SIGNAL(changed()),\n                   agi, SLOT(modelChanged()));\n\n  agi->setSitesPen(QPen(Qt::red, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  agi->setEdgesPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.addItem(agi);\n\n  // Setup input handlers. They get events before the scene gets them\n  // and the input they generate is passed to the triangulation with\n  // the signal/slot mechanism\n\n  ci = new CGAL::Qt::GraphicsViewCircleInput<K>(this, &scene);\n  QObject::connect(ci, SIGNAL(generate(CGAL::Object)),\n                   this, SLOT(processInput(CGAL::Object)));\n\n  scene.installEventFilter(ci);\n\n  //\n  // Manual handling of actions\n  //\n\n  QObject::connect(this->actionQuit, SIGNAL(triggered()),\n                   this, SLOT(close()));\n\n  //\n  // Setup the scene and the view\n  //\n  scene.setItemIndexMethod(QGraphicsScene::NoIndex);\n  scene.setSceneRect(-100, -100, 100, 100);\n  this->graphicsView->setScene(&scene);\n  this->graphicsView->setMouseTracking(true);\n\n  // Turn the vertical axis upside down\n  this->graphicsView->transform().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_Apollonius_graph_2.html\");\n  this->addAboutCGAL();\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  std::pair<Point_2, double> center_and_sr;\n  if(CGAL::assign(center_and_sr, o)){\n    ag.insert(Apollonius_site_2(center_and_sr.first, sqrt(center_and_sr.second)));\n    Q_EMIT( changed());\n  }\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\n\nvoid\nMainWindow::on_actionClear_triggered()\n{\n  ag.clear();\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionInsertRandomPoints_triggered()\n{\n  QRectF rect = CGAL::Qt::viewportsBbox(&scene);\n  CGAL::Qt::Converter<K> convert;\n  Iso_rectangle_2 isor = convert(rect);\n  double width = isor.xmax() - isor.xmin();\n\n  CGAL::Random_points_in_iso_rectangle_2<Point_2> pg((isor.min)(), (isor.max)());\n  bool ok = false;\n\n  const int number_of_points =\n    QInputDialog::getInt(this,\n                             tr(\"Number of random points\"),\n                             tr(\"Enter number of random points\"),\n                                                         100,\n                                                         0,\n                                                        (std::numeric_limits<int>::max)(),\n                                                        1,\n                                                        &ok);\n\n  if(!ok) {\n    return;\n  }\n\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  std::vector<Apollonius_site_2> points;\n  points.reserve(number_of_points);\n  boost::rand48 rng;\n  boost::uniform_real<> dist(0.005*width, 0.05*width);\n  boost::variate_generator<boost::rand48&, boost::uniform_real<> > radius(rng,dist);\n\n  for(int i = 0; i < number_of_points; ++i){\n    points.push_back(Apollonius_site_2(*pg++,radius()));\n  }\n      ag.insert(points.begin(), points.end());\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionLoadPoints_triggered()\n{\n  QString fileName = QFileDialog::getOpenFileName(this,\n                                                  tr(\"Open Points file\"),\n                                                  \".\",\n                                                  tr(\"CGAL files (*.wpts.cgal);;\"\n                                                   #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n                                                     \"WKT files (*.wkt *.WKT);;\"\n                                                   #endif\n                                                     \"All files (*)\"));\n  if(! fileName.isEmpty()){\n    open(fileName);\n  }\n}\n\n\nvoid\nMainWindow::open(QString fileName)\n{\n\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  if(! fileName.isEmpty()){\n    std::ifstream ifs(qPrintable(fileName));\n\n    std::vector<Apollonius_site_2> points;\n    if(fileName.endsWith(\".wkt\", Qt::CaseInsensitive))\n    {\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n      std::vector<K::Point_3> point_3_s;\n      CGAL::read_multi_point_WKT(ifs, point_3_s);\n      for(const K::Point_3& point_3 : point_3_s)\n      {\n        points.push_back(Apollonius_site_2(K::Point_2(point_3.x(), point_3.y()), point_3.z()));\n      }\n#endif\n    } else{\n      K::Weighted_point_2 p;\n      while(ifs >> p) {\n        points.push_back(Apollonius_site_2(p.point(),p.weight()));\n      }\n    }\n    ag.insert(points.begin(), points.end());\n    this->addToRecentFiles(fileName);\n    actionRecenter->trigger();\n    Q_EMIT( changed());\n  }\n  QApplication::restoreOverrideCursor();\n}\n\nvoid\nMainWindow::on_actionSavePoints_triggered()\n{\n  QString fileName = QFileDialog::getSaveFileName(this,\n                                                  tr(\"Save points\"),\n                                                  \".reg.cgal\",\n                                                  tr(\"Weighted Points (*.wpts.cgal);;\"\n                                                   #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n                                                     \"WKT files(*.wkt *.WKT);;\"\n                                                   #endif\n                                                     \"All (*)\"));\n  if(! fileName.isEmpty()){\n    std::ofstream ofs(qPrintable(fileName));\n    if(fileName.endsWith(\".wkt\",Qt::CaseInsensitive))\n    {\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n      std::vector<K::Point_3> points;\n      for(Apollonius::Sites_iterator\n          vit = ag.sites_begin(),\n          end = ag.sites_end();\n          vit!= end; ++vit)\n      {\n        points.push_back(K::Point_3(vit->point().x(),\n                                    vit->point().y(),\n                                    vit->weight()));\n      }\n      CGAL::write_multi_point_WKT(ofs, points);\n#endif\n    }\n    else\n      for(Apollonius::Sites_iterator\n          vit = ag.sites_begin(),\n          end = ag.sites_end();\n          vit!= end; ++vit)\n      {\n        ofs << vit->point()<<\" \"<<vit->weight()<<std::endl;\n      }\n  }\n}\n\n\nvoid\nMainWindow::on_actionRecenter_triggered()\n{\n  this->graphicsView->setSceneRect(agi->boundingRect());\n  this->graphicsView->fitInView(agi->boundingRect(), Qt::KeepAspectRatio);\n}\n\n\n#include \"Apollonius_graph_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(\"Apollonius_graph_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(Apollonius_graph_2);\n\n  MainWindow mainWindow;\n  mainWindow.show();\n  return app.exec();\n}\n", "meta": {"hexsha": "8292f28262d3904a44baf4716927020ba650fd40", "size": 9631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GraphicsView/demo/Apollonius_graph_2/Apollonius_graph_2.cpp", "max_stars_repo_name": "gaschler/cgal", "max_stars_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T09:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T05:00:23.000Z", "max_issues_repo_path": "GraphicsView/demo/Apollonius_graph_2/Apollonius_graph_2.cpp", "max_issues_repo_name": "gaschler/cgal", "max_issues_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "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/Apollonius_graph_2/Apollonius_graph_2.cpp", "max_forks_repo_name": "szobov/cgal", "max_forks_repo_head_hexsha": "e7b91b92b8c6949e3b62023bdd1e9f3ad8472626", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-05T04:18:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:18:59.000Z", "avg_line_length": 28.7492537313, "max_line_length": 126, "alphanum_fraction": 0.6067905721, "num_tokens": 2322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5063758804537931}}
{"text": "//\n// Created by Yohsuke Murase on 2020/06/04.\n//\n\n#include <iostream>\n#include <ostream>\n#include <vector>\n#include <array>\n#include <random>\n#include <cassert>\n#include <mpi.h>\n#include <Eigen/Dense>\n#include <fstream>\n#include \"StrategyN3M5.hpp\"\n\n// calculate the distribution of fixation probability rho\n// against randomly selected N2M3 deterministic strategies\n\nstd::array<double,3> CalcPayoffs(const std::array<double,StrategyN3M5::N>& stationary_state, double benefit) {\n  const double cost = 1.0;\n  std::array<double,3> ans = {0.0, 0.0, 0.0};\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] == false) { pa -= cost; pb += benefit / 2.0; pc += benefit / 2.0; }\n    if (s.hb[0] == false) { pb -= cost; pa += benefit / 2.0; pc += benefit / 2.0; }\n    if (s.hc[0] == false) { pc -= cost; pa += benefit / 2.0; pb += benefit / 2.0; }\n    ans[0] += stationary_state[i] * pa;\n    ans[1] += stationary_state[i] * pb;\n    ans[2] += stationary_state[i] * pc;\n  }\n  return ans;\n}\n\ndouble FixationProb(size_t N, double sigma, double e, double benefit, const StrategyN3M5 &res, const StrategyN3M5 &mut, double s_yyy) {\n  auto a_xxx = mut.StationaryState(e);\n  auto a_xxy = mut.StationaryState(e, &mut, &res);\n  auto a_xyy = mut.StationaryState(e, &res, &res);\n\n  double s_xxx = CalcPayoffs(a_xxx, benefit)[0];\n  auto _xxy = CalcPayoffs(a_xxy, benefit);\n  double s_xxy = _xxy[0];\n  double s_yxx = _xxy[2];\n  auto _xyy = CalcPayoffs(a_xyy, benefit);\n  double s_xyy = _xyy[0];\n  double s_yyx = _xyy[1];\n\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\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\n  return 1.0 / rho_inv;\n}\n\nstd::bitset<StrategyN3M5::N> DrawRandomBit32768(std::mt19937_64 & rnd) {\n  std::uniform_int_distribution<uint64_t > dist(0, std::numeric_limits<uint64_t>::max() );\n\n  std::bitset<StrategyN3M5::N> ans;\n  int rep = StrategyN3M5::N / 64;\n  assert(StrategyN3M5::N % 64 == 0);\n  for (int i = 0; i < rep; i++) {\n    std::bitset<StrategyN3M5::N> mask = dist(rnd);\n    mask <<= (64 * i);\n    ans |= mask;\n  }\n  return ans;\n}\n\nint main(int argc, char *argv[]) {\n  MPI_Init(&argc, &argv);\n  Eigen::initParallel();\n  if( argc != 8 ) {\n    std::cerr << \"Error : invalid argument\" << std::endl;\n    std::cerr << \"  Usage : \" << argv[0] << \" <N> <sigma> <e> <benefit> <resident 0:caprin, +:num_resident_samples> <num_mutants> <seed>\" << std::endl;\n    MPI_Finalize();\n    return 1;\n  }\n\n  size_t N = std::strtoul(argv[1], nullptr,0);\n  double sigma = std::strtod(argv[2], nullptr);\n  double e = std::strtod(argv[3], nullptr);\n  double benefit = std::strtod(argv[4], nullptr);\n\n  long n_resident = std::strtol(argv[5], nullptr, 0);\n  long n_mutants = std::strtol(argv[6], nullptr, 0);\n  int seed = std::strtol(argv[7], nullptr, 0);\n\n\n  const size_t NUM_BINS = 1000;\n  std::vector<size_t> counts(NUM_BINS, 0ul);\n  size_t robust_count = 0ul;\n\n  int my_rank = 0;\n  MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);\n  int num_procs = 0;\n  MPI_Comm_size(MPI_COMM_WORLD, &num_procs);\n\n  if (n_resident > 0) {\n    {\n      std::seed_seq seq = {seed, my_rank};\n      std::mt19937_64 rnd(seq);\n      size_t my_n_resident = n_resident / num_procs;\n      if (my_rank < n_resident % num_procs) { my_n_resident++; }\n      // std::cerr << \"my_n_resident: \" << my_n_resident << \" \" << my_rank << ' ' << th << std::endl;\n\n      for (size_t i = 0; i < my_n_resident; i++) {\n        std::cerr << \"i: \" << i << \" \" << my_rank << std::endl;\n        StrategyN3M5 res( DrawRandomBit32768(rnd) );\n        auto a_yyy = res.StationaryState(e);\n        double s_yyy = CalcPayoffs(a_yyy, benefit)[0];\n        for (size_t j = 0; j < n_mutants; j++) {\n          std::cerr << \"j: \" << j << \" \" << my_rank << std::endl;\n          StrategyN3M5 mut( DrawRandomBit32768(rnd) );\n          double rho = FixationProb(N, sigma, e, benefit, res, mut, s_yyy);\n          std::cerr << \"  rho: \" << rho << std::endl;\n          size_t b = static_cast<size_t>(rho * NUM_BINS);\n          counts[b]++;\n          if (rho <= 1.0 / N) { robust_count++; }\n        }\n      }\n    }\n  }\n  else {\n    {\n      std::seed_seq seq = {seed, my_rank};\n      std::mt19937_64 rnd(seq);\n\n      StrategyN3M5 res = StrategyN3M5::CAPRI3();\n      auto a_yyy = res.StationaryState(e);\n      double s_yyy = CalcPayoffs(a_yyy, benefit)[0];\n\n      size_t my_n_mutants = n_mutants / num_procs;\n      if (my_rank < n_mutants % num_procs) { my_n_mutants++; }\n      //std::cerr << \"my_n_mutants: \" << my_n_mutants << ' ' << my_rank << ' ' << th << std::endl;\n\n      for (size_t j = 0; j < my_n_mutants; j++) {\n        StrategyN3M5 mut( DrawRandomBit32768(rnd) );\n        double rho = FixationProb(N, sigma, e, benefit, res, mut, s_yyy);\n        size_t b = static_cast<size_t>(rho * NUM_BINS);\n        counts[b] += 1;\n        if (rho <= 1.0 / N) { robust_count++; }\n      }\n    }\n  }\n\n  // reduce counts\n  std::vector<size_t> all_counts(NUM_BINS, 0ul);\n  size_t all_robust_count = 0ul;\n  MPI_Reduce(counts.data(), all_counts.data(), all_counts.size(), MPI_UNSIGNED_LONG, MPI_SUM, 0, MPI_COMM_WORLD);\n  MPI_Reduce(&robust_count, &all_robust_count, 1, MPI_UNSIGNED_LONG, MPI_SUM, 0, MPI_COMM_WORLD);\n\n  // print counts\n  if (my_rank == 0) {\n    std::ofstream fout(\"dist.dat\");\n    double dx = 1.0 / NUM_BINS;\n    double total = (n_resident == 0) ? n_mutants : n_resident * n_mutants;\n    for (size_t i = 0; i < NUM_BINS; i++) {\n      fout << i * dx << ' ' << (double)all_counts[i]/total << std::endl;\n    }\n\n    std::cerr << \"robust_count/total: \" << all_robust_count << \" / \" << total << \" : \" << (double)all_robust_count/total << std::endl;\n  }\n\n  MPI_Finalize();\n  return 0;\n}\n", "meta": {"hexsha": "d01cd46fa4901c42138eafc5b1497438afe57102", "size": 6376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/main_evo_fixation_probs_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_fixation_probs_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_fixation_probs_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": 34.2795698925, "max_line_length": 151, "alphanum_fraction": 0.5790464241, "num_tokens": 2324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5063758771137312}}
{"text": "//\n// Created by xiang on 1/4/18.\n// this program shows how to perform direct bundle adjustment\n//\n#include <iostream>\n\nusing namespace std;\n\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/base_binary_edge.h>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <g2o/core/robust_kernel.h>\n#include <g2o/core/robust_kernel_impl.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n\n#include <Eigen/Core>\n#include <sophus/se3.hpp>\n#include <opencv2/opencv.hpp>\n\n#include <pangolin/pangolin.h>\n#include <boost/format.hpp>\n\ntypedef vector<Sophus::SE3d, Eigen::aligned_allocator<Sophus::SE3d>> VecSE3;\ntypedef vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> VecVec3d;\n\n// global variables\nstring pose_file = \"../poses.txt\";\nstring points_file = \"../points.txt\";\n\n// intrinsics\nfloat fx = 277.34;\nfloat fy = 291.402;\nfloat cx = 312.234;\nfloat cy = 239.777;\n\n// bilinear interpolation\ninline float GetPixelValue(const cv::Mat &img, float x, float y) {\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\n// g2o vertex that use sophus::SE3 as pose\nclass VertexSophus : public g2o::BaseVertex<6, Sophus::SE3d> {\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    VertexSophus() {}\n\n    ~VertexSophus() {}\n\n    bool read(std::istream &is) {}\n\n    bool write(std::ostream &os) const {}\n\n    virtual void setToOriginImpl() {\n        _estimate = Sophus::SE3d();\n    }\n\n    virtual void oplusImpl(const double *update_) {\n        Eigen::Map<const Eigen::Matrix<double, 6, 1>> update(update_);\n        setEstimate(Sophus::SE3d::exp(update) * estimate());\n    }\n};\n\n// TODO edge of projection error, implement it\n// 16x1 error, which is the errors in patch\ntypedef Eigen::Matrix<double,16,1> Vector16d;\nclass EdgeDirectProjection : public g2o::BaseBinaryEdge<16, Vector16d, g2o::VertexSBAPointXYZ, VertexSophus> {\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    EdgeDirectProjection(float *color, cv::Mat &target) {\n        this->origColor = color;\n        this->targetImg = target;\n    }\n\n    ~EdgeDirectProjection() {}\n\n    virtual void computeError() override {\n        // TODO START YOUR CODE HERE\n        // compute projection error ...\n        const g2o::VertexSBAPointXYZ *vertexPw = static_cast<const g2o::VertexSBAPointXYZ * >(vertex(0));\n        const VertexSophus *vertexTcw = static_cast<const VertexSophus * >(vertex(1));\n        Eigen::Vector3d p_nsp = vertexTcw->estimate() * vertexPw->estimate();\n        p_nsp /= p_nsp[2];\n        double u = p_nsp[0]*fx+cx;\n        double v = p_nsp[1]*fy+cy;\n        if (u-2>=0 && v-2>=0 &&u+1<=targetImg.cols-1 && v+1<=targetImg.rows-1){\n            int index=0;\n            for (int du=-2;du<=1;du++){\n                for (int dv=-2;dv<=1;dv++)\n                {\n                    _error[index] = origColor[index]-GetPixelValue(targetImg, u+du, v+dv);\n                    index++;\n                }\n            }\n        }\n        else{\n            this->setLevel(1);\n            for(int i=0;i<16;i++) _error[i]=0;\n        }\n        // END YOUR CODE HERE\n    }\n\n    // Let g2o compute jacobian for you\n\n    virtual bool read(istream &in) {}\n\n    virtual bool write(ostream &out) const {}\n\nprivate:\n    cv::Mat targetImg;  // the target image\n    float *origColor = nullptr;   // 16 floats, the color of this point\n};\n\n// plot the poses and points for you, need pangolin\nvoid Draw(const VecSE3 &poses, const VecVec3d &points);\n\nint main(int argc, char **argv) {\n\n    // read poses and points\n    VecSE3 poses;\n    VecVec3d points;\n    ifstream fin(pose_file);\n\n    while (!fin.eof()) {\n        double timestamp = 0;\n        fin >> timestamp;\n        if (timestamp == 0) break;\n        double data[7];\n        for (auto &d: data) fin >> d;\n        poses.push_back(Sophus::SE3d(\n                Eigen::Quaterniond(data[6], data[3], data[4], data[5]),\n                Eigen::Vector3d(data[0], data[1], data[2])\n        ));\n        if (!fin.good()) break;\n    }\n    fin.close();\n\n\n    vector<float *> color;\n    fin.open(points_file);\n    while (!fin.eof()) {\n        double xyz[3] = {0};\n        for (int i = 0; i < 3; i++) fin >> xyz[i];\n        if (xyz[0] == 0) break;\n        points.push_back(Eigen::Vector3d(xyz[0], xyz[1], xyz[2]));\n        float *c = new float[16];\n        for (int i = 0; i < 16; i++) fin >> c[i];\n        color.push_back(c);\n\n        if (fin.good() == false) break;\n    }\n    fin.close();\n\n    cout << \"poses: \" << poses.size() << \", points: \" << points.size() << endl;\n\n    // read images\n    vector<cv::Mat> images;\n    boost::format fmt(\"../%d.png\");\n    for (int i = 0; i < 7; i++) {\n        images.push_back(cv::imread((fmt % i).str(), 0));\n    }\n\n    // build optimization problem\n    // typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> DirectBlock;  // \u6c42\u89e3\u7684\u5411\u91cf\u662f6\uff0a1\u7684\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> BlockSolverType;  // \u6c42\u89e3\u7684\u5411\u91cf\u662f6\uff0a1\u7684\n    typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType;\n    auto solver = new g2o::OptimizationAlgorithmLevenberg(\n        g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    optimizer.setVerbose(true);\n\n    // TODO add vertices, edges into the graph optimizer\n    // START YOUR CODE HERE\n    vector<VertexSophus *> vertex_poses;\n    for (int i=0; i<poses.size(); i++)\n    {\n        VertexSophus *v = new VertexSophus();\n        v->setId(i);\n        v->setEstimate(poses[i]);\n        optimizer.addVertex(v);\n        vertex_poses.push_back(v);\n    }\n\n    vector<g2o::VertexSBAPointXYZ *> vertex_points;\n    for (int i=0;i<points.size();i++){\n        g2o::VertexSBAPointXYZ *v = new g2o::VertexSBAPointXYZ();\n        v->setId(i+poses.size());\n        v->setEstimate(points[i]);\n\n        v->setMarginalized(true);\n        optimizer.addVertex(v);\n        vertex_points.push_back(v);\n    }\n\n    for(int i=0;i<vertex_poses.size();i++){\n        for (int j=0;j<vertex_points.size();j++)\n        {\n            EdgeDirectProjection *edge = new EdgeDirectProjection(color[j], images[i]);\n            edge->setVertex(0, vertex_points[j]);\n            edge->setVertex(1, vertex_poses[i]);\n            edge->setInformation(Eigen::Matrix<double, 16, 16>::Identity());\n            edge->setRobustKernel(new g2o::RobustKernelHuber());\n            optimizer.addEdge(edge);            \n        }\n    }\n\n    // END YOUR CODE HERE\n\n    // perform optimization\n    optimizer.initializeOptimization(0);\n    optimizer.optimize(200);\n\n    // TODO fetch data from the optimizer\n    // START YOUR CODE HERE\n    for (int i=0;i<poses.size();i++){\n        poses[i] = vertex_poses[i]->estimate();\n    }\n    for (int i=0;i<points.size();i++){\n        points[i] = vertex_points[i]->estimate();\n    }\n    // END YOUR CODE HERE\n\n    // plot the optimized points and poses\n    Draw(poses, points);\n\n    // delete color data\n    for (auto &c: color) delete[] c;\n    return 0;\n}\n\nvoid Draw(const VecSE3 &poses, const VecVec3d &points) {\n    if (poses.empty() || points.empty()) {\n        cerr << \"parameter is empty!\" << endl;\n        return;\n    }\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(0.0f, 0.0f, 0.0f, 0.0f);\n\n        // draw poses\n        float sz = 0.1;\n        int width = 640, height = 480;\n        for (auto &Tcw: poses) {\n            glPushMatrix();\n            Sophus::Matrix4f m = Tcw.inverse().matrix().cast<float>();\n            glMultMatrixf((GLfloat *) m.data());\n            glColor3f(1, 0, 0);\n            glLineWidth(2);\n            glBegin(GL_LINES);\n            glVertex3f(0, 0, 0);\n            glVertex3f(sz * (0 - cx) / fx, sz * (0 - cy) / fy, sz);\n            glVertex3f(0, 0, 0);\n            glVertex3f(sz * (0 - cx) / fx, sz * (height - 1 - cy) / fy, sz);\n            glVertex3f(0, 0, 0);\n            glVertex3f(sz * (width - 1 - cx) / fx, sz * (height - 1 - cy) / fy, sz);\n            glVertex3f(0, 0, 0);\n            glVertex3f(sz * (width - 1 - cx) / fx, sz * (0 - cy) / fy, sz);\n            glVertex3f(sz * (width - 1 - cx) / fx, sz * (0 - cy) / fy, sz);\n            glVertex3f(sz * (width - 1 - cx) / fx, sz * (height - 1 - cy) / fy, sz);\n            glVertex3f(sz * (width - 1 - cx) / fx, sz * (height - 1 - cy) / fy, sz);\n            glVertex3f(sz * (0 - cx) / fx, sz * (height - 1 - cy) / fy, sz);\n            glVertex3f(sz * (0 - cx) / fx, sz * (height - 1 - cy) / fy, sz);\n            glVertex3f(sz * (0 - cx) / fx, sz * (0 - cy) / fy, sz);\n            glVertex3f(sz * (0 - cx) / fx, sz * (0 - cy) / fy, sz);\n            glVertex3f(sz * (width - 1 - cx) / fx, sz * (0 - cy) / fy, sz);\n            glEnd();\n            glPopMatrix();\n        }\n\n        // points\n        glPointSize(2);\n        glBegin(GL_POINTS);\n        for (size_t i = 0; i < points.size(); i++) {\n            glColor3f(0.0, points[i][2]/4, 1.0-points[i][2]/4);\n            glVertex3d(points[i][0], points[i][1], points[i][2]);\n        }\n        glEnd();\n\n        pangolin::FinishFrame();\n        usleep(5000);   // sleep 5 ms\n    }\n}\n\n", "meta": {"hexsha": "708842d3abd49ae50878abba9f8c3f28d9b31dbb", "size": 10132, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slamhw7/directBA.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": "slamhw7/directBA.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": "slamhw7/directBA.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": 32.0632911392, "max_line_length": 110, "alphanum_fraction": 0.5718515594, "num_tokens": 3018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5063758771137312}}
{"text": "#include \"Day13-ShuttleSearch.h\"\n\n#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>\n\n__BEGIN_LIBRARIES_DISABLE_WARNINGS\n#include <boost/algorithm/string.hpp>\n\n#include <vector>\n#include <cmath>\n__END_LIBRARIES_DISABLE_WARNINGS\n\nnamespace AdventOfCode\n{\nnamespace Year2020\n{\nnamespace Day13\n{\n\nstruct BusDeparture\n{\n    int busID;\n    int offset;\n};\n\nstd::vector<BusDeparture> parseScheduleDescription(const std::string& scheduleDescriptionString)\n{\n    std::vector<std::string> tokens;\n    boost::split(tokens, scheduleDescriptionString, boost::is_any_of(\",\"));\n\n    std::vector<BusDeparture> busDepartures;\n    for (int i = 0; i < tokens.size(); ++i)\n    {\n        if (tokens.at(i) == \"x\")\n        {\n            continue;\n        }\n        const int busID = std::stoi(tokens.at(i));\n        const int offset = i % busID;\n        BusDeparture busDeparture{busID, offset};\n        busDepartures.push_back(std::move(busDeparture));\n    }\n\n    return busDepartures;\n}\n\nint64_t getWaitTime(int64_t earliestDepartureTimestamp, int busID)\n{\n    int64_t earliestDepartureTimeViaThisBus = (earliestDepartureTimestamp / busID) * busID;\n    if (earliestDepartureTimeViaThisBus < earliestDepartureTimestamp)\n    {\n        earliestDepartureTimeViaThisBus += busID;\n    }\n    return earliestDepartureTimeViaThisBus - earliestDepartureTimestamp;\n}\n\nint earliestBusIDMultipliedByWaitTime(int earliestDepartureTimestamp, const std::string& scheduleDescriptionString)\n{\n    std::vector<BusDeparture> busDepartures = parseScheduleDescription(scheduleDescriptionString);\n\n    const auto minWaitTimeBusDepartureIter = std::min_element(busDepartures.cbegin(), busDepartures.cend(), [earliestDepartureTimestamp](const auto& lhs, const auto& rhs)\n                                                              {\n                                                                  return getWaitTime(earliestDepartureTimestamp, lhs.busID) < getWaitTime(earliestDepartureTimestamp, rhs.busID);\n                                                              });\n\n    const int minWaitTimeBusID = minWaitTimeBusDepartureIter->busID;\n\n    return getWaitTime(earliestDepartureTimestamp, minWaitTimeBusID) * minWaitTimeBusID;\n}\n\nint64_t earliestTimestampWithMatchingDepartures(const std::string& scheduleDescriptionString)\n{\n    std::vector<BusDeparture> busDepartures = parseScheduleDescription(scheduleDescriptionString);\n\n    int64_t delta = 1;\n    int64_t candidate = 0;\n\n    for (const auto& busDeparture : busDepartures)\n    {\n        const int busID = busDeparture.busID;\n        const int offset = busDeparture.offset;\n        while (getWaitTime(candidate, busID) != offset)\n        {\n            candidate += delta;\n        }\n        delta *= busID;\n    }\n\n    return candidate;\n}\n\n}\n}\n}\n", "meta": {"hexsha": "10835a8f4d2f3eea2f84ee5b106d5588e960c834", "size": 2774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AdventOfCode2020/Day13-ShuttleSearch/Day13-ShuttleSearch.cpp", "max_stars_repo_name": "dbartok/advent-of-code-cpp", "max_stars_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AdventOfCode2020/Day13-ShuttleSearch/Day13-ShuttleSearch.cpp", "max_issues_repo_name": "dbartok/advent-of-code-cpp", "max_issues_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AdventOfCode2020/Day13-ShuttleSearch/Day13-ShuttleSearch.cpp", "max_forks_repo_name": "dbartok/advent-of-code-cpp", "max_forks_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5106382979, "max_line_length": 177, "alphanum_fraction": 0.678442682, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5063618764452744}}
{"text": "#include <shift/math/vector.hpp>\n//#include <shift/math/matrix.hpp>\n//#include <shift/core/algorithm.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::math;\n\ntemplate <typename T>\nusing vector5 = vector<5, T>;\n\nBOOST_AUTO_TEST_CASE(vector_details)\n{\n  BOOST_CHECK_EQUAL(detail::components_count_v<float>, 1);\n  BOOST_CHECK_EQUAL(detail::components_count_v<vector2<float>>, 2);\n  BOOST_CHECK_EQUAL(detail::components_count_v<vector3<float>>, 3);\n  BOOST_CHECK_EQUAL(detail::components_count_v<vector4<float>>, 4);\n\n  BOOST_CHECK((std::is_same_v<detail::select_type_t<float>, float>));\n  BOOST_CHECK((std::is_same_v<detail::select_type_t<int, float>, float>));\n  BOOST_CHECK(\n    (std::is_same_v<detail::select_type_t<int, float, double>, double>));\n  BOOST_CHECK(\n    (std::is_same_v<detail::select_type_t<std::uint32_t, std::int16_t>,\n                    std::uint32_t>));\n  BOOST_CHECK(\n    (std::is_same_v<detail::select_type_t<std::int32_t, std::uint16_t>,\n                    std::int32_t>));\n}\n\nBOOST_AUTO_TEST_CASE(vector_is_trivial)\n{\n  static_assert(std::is_trivial_v<vector2<float>>);\n  static_assert(std::is_trivial_v<vector3<float>>);\n  static_assert(std::is_trivial_v<vector4<float>>);\n  BOOST_CHECK(std::is_trivial_v<vector2<float>>);\n  BOOST_CHECK(std::is_trivial_v<vector3<float>>);\n  BOOST_CHECK(std::is_trivial_v<vector4<float>>);\n}\n\nBOOST_AUTO_TEST_CASE(vector_constexpr_construction)\n{\n  constexpr vector2<float> v2f1{1.0f, 2.0f};\n  constexpr vector2<float> v2f2(1.0f, 2.0f);\n  constexpr vector2<float> v2f3 = {1.0f, 2.0f};\n  constexpr vector2<float> v2f4{v2f1};\n  constexpr vector2<float> v2f5(v2f2);\n  constexpr vector2<float> v2f6 = v2f3;\n\n  BOOST_STATIC_ASSERT(v2f1.x == 1.0f);\n  BOOST_STATIC_ASSERT(v2f1.y == 2.0f);\n  BOOST_STATIC_ASSERT(v2f2.x == 1.0f);\n  BOOST_STATIC_ASSERT(v2f2.y == 2.0f);\n  BOOST_STATIC_ASSERT(v2f3.x == 1.0f);\n  BOOST_STATIC_ASSERT(v2f3.y == 2.0f);\n  BOOST_STATIC_ASSERT(v2f4.x == 1.0f);\n  BOOST_STATIC_ASSERT(v2f4.y == 2.0f);\n  BOOST_STATIC_ASSERT(v2f5.x == 1.0f);\n  BOOST_STATIC_ASSERT(v2f5.y == 2.0f);\n  BOOST_STATIC_ASSERT(v2f6.x == 1.0f);\n  BOOST_STATIC_ASSERT(v2f6.y == 2.0f);\n}\n\nBOOST_AUTO_TEST_CASE(vector_dynamic_construction)\n{\n  vector2<float> v2f1{1.0f, 2.0f};\n  vector2<float> v2f2(1.0f, 2.0f);\n  vector2<float> v2f3 = {1.0f, 2.0f};\n  vector2<float> v2f4{v2f1};\n  vector2<float> v2f5(v2f2);\n  vector2<float> v2f6 = v2f3;\n\n  BOOST_CHECK_EQUAL(v2f1.x, 1.0f);\n  BOOST_CHECK_EQUAL(v2f1.y, 2.0f);\n  BOOST_CHECK_EQUAL(v2f2.x, 1.0f);\n  BOOST_CHECK_EQUAL(v2f2.y, 2.0f);\n  BOOST_CHECK_EQUAL(v2f3.x, 1.0f);\n  BOOST_CHECK_EQUAL(v2f3.y, 2.0f);\n  BOOST_CHECK_EQUAL(v2f4.x, 1.0f);\n  BOOST_CHECK_EQUAL(v2f4.y, 2.0f);\n  BOOST_CHECK_EQUAL(v2f5.x, 1.0f);\n  BOOST_CHECK_EQUAL(v2f5.y, 2.0f);\n  BOOST_CHECK_EQUAL(v2f6.x, 1.0f);\n  BOOST_CHECK_EQUAL(v2f6.y, 2.0f);\n}\n\nBOOST_AUTO_TEST_CASE(vector_accessors)\n{\n  auto v2f = make_vector_from(1.0f, 2.0f);\n  BOOST_CHECK_EQUAL(v2f(0), 1.0f);\n  BOOST_CHECK_EQUAL(v2f(1), 2.0f);\n  BOOST_CHECK_EQUAL(v2f.x, 1.0f);\n  BOOST_CHECK_EQUAL(v2f.y, 2.0f);\n\n  auto v3f = make_vector_from(1.0f, 2.0f, 3.0f);\n  BOOST_CHECK_EQUAL(v3f(0), 1.0f);\n  BOOST_CHECK_EQUAL(v3f(1), 2.0f);\n  BOOST_CHECK_EQUAL(v3f(2), 3.0f);\n  BOOST_CHECK_EQUAL(v3f.x, 1.0f);\n  BOOST_CHECK_EQUAL(v3f.y, 2.0f);\n  BOOST_CHECK_EQUAL(v3f.z, 3.0f);\n\n  auto v4f = make_vector_from(1.0f, 2.0f, 3.0f, 4.0f);\n  BOOST_CHECK_EQUAL(v4f(0), 1.0f);\n  BOOST_CHECK_EQUAL(v4f(1), 2.0f);\n  BOOST_CHECK_EQUAL(v4f(2), 3.0f);\n  BOOST_CHECK_EQUAL(v4f(3), 4.0f);\n  BOOST_CHECK_EQUAL(v4f.x, 1.0f);\n  BOOST_CHECK_EQUAL(v4f.y, 2.0f);\n  BOOST_CHECK_EQUAL(v4f.z, 3.0f);\n  BOOST_CHECK_EQUAL(v4f.w, 4.0f);\n}\n\nBOOST_AUTO_TEST_CASE(vector_construction_using_initializer_list)\n{\n  vector3<float> v = {1.0f, 2.0f, 3.0f};\n  BOOST_CHECK_EQUAL(v.x, 1.0f);\n  BOOST_CHECK_EQUAL(v.y, 2.0f);\n  BOOST_CHECK_EQUAL(v.z, 3.0f);\n}\n\nBOOST_AUTO_TEST_CASE(vector_explicit_construction)\n{\n  vector4<float> v(1.0f, 2.0f, 3.0f, 4.0f);\n  BOOST_CHECK_EQUAL(v.x, 1.0f);\n  BOOST_CHECK_EQUAL(v.y, 2.0f);\n  BOOST_CHECK_EQUAL(v.z, 3.0f);\n  BOOST_CHECK_EQUAL(v.w, 4.0f);\n}\n\nBOOST_AUTO_TEST_CASE(vector_make_construction)\n{\n  auto v1 = make_vector_from(1.0f, 2.0, 3.0f);\n  BOOST_STATIC_ASSERT((std::is_same_v<decltype(v1)::value_type, double>));\n  BOOST_CHECK_EQUAL(v1.x, 1.0);\n  BOOST_CHECK_EQUAL(v1.y, 2.0);\n  BOOST_CHECK_EQUAL(v1.z, 3.0);\n\n  auto v2 = make_vector_from(make_vector_from(1.0f, 2.0f), 3.0);\n  BOOST_STATIC_ASSERT((std::is_same_v<decltype(v2)::value_type, double>));\n  BOOST_CHECK_EQUAL(v2.x, 1.0);\n  BOOST_CHECK_EQUAL(v2.y, 2.0);\n  BOOST_CHECK_EQUAL(v2.z, 3.0);\n\n  auto v3 = make_vector_from(1.0, make_vector_from(2.0f, 3.0f));\n  BOOST_STATIC_ASSERT((std::is_same_v<decltype(v3)::value_type, double>));\n  BOOST_CHECK_EQUAL(v3.x, 1.0);\n  BOOST_CHECK_EQUAL(v3.y, 2.0);\n  BOOST_CHECK_EQUAL(v3.z, 3.0);\n}\n\nBOOST_AUTO_TEST_CASE(vector_copy_construction)\n{\n  auto v1 = make_vector_from(1.0f, 2.0f, 3.0f, 4.0f);\n  vector4<float> v2(v1);\n  BOOST_CHECK_EQUAL(v2.x, 1.0f);\n  BOOST_CHECK_EQUAL(v2.y, 2.0f);\n  BOOST_CHECK_EQUAL(v2.z, 3.0f);\n  BOOST_CHECK_EQUAL(v2.w, 4.0f);\n}\n\nBOOST_AUTO_TEST_CASE(vector_carray_construction)\n{\n  const float values[4] = {1.0f, 2.0f, 3.0f, 4.0f};\n  auto v1 = make_vector_from(values);\n  BOOST_CHECK_EQUAL(v1.x, 1.0f);\n  BOOST_CHECK_EQUAL(v1.y, 2.0f);\n  BOOST_CHECK_EQUAL(v1.z, 3.0f);\n  BOOST_CHECK_EQUAL(v1.w, 4.0f);\n}\n\nBOOST_AUTO_TEST_CASE(vector_array_construction)\n{\n  const std::array<float, 4> values{{1.0f, 2.0f, 3.0f, 4.0f}};\n  auto v1 = make_vector_from(values);\n  BOOST_CHECK_EQUAL(v1.x, 1.0f);\n  BOOST_CHECK_EQUAL(v1.y, 2.0f);\n  BOOST_CHECK_EQUAL(v1.z, 3.0f);\n  BOOST_CHECK_EQUAL(v1.w, 4.0f);\n}\n\nBOOST_AUTO_TEST_CASE(vector_arithmetic_operators)\n{\n  {\n    auto v1 = make_vector_from(4.0f, 5.0f, 6.0f);\n    auto v2 = make_vector_from(1.0f, 2.0f, 3.0f);\n    auto v3 = v1 + v2;\n    BOOST_CHECK_EQUAL(v3.x, 5.0f);\n    BOOST_CHECK_EQUAL(v3.y, 7.0f);\n    BOOST_CHECK_EQUAL(v3.z, 9.0f);\n  }\n  {\n    auto v1 = make_vector_from(4.0f, 5.0f, 6.0f);\n    auto v2 = make_vector_from(1.0f, 2.0f, 3.0f);\n    auto v3 = v1 - v2;\n    BOOST_CHECK_EQUAL(v3.x, 3.0f);\n    BOOST_CHECK_EQUAL(v3.y, 3.0f);\n    BOOST_CHECK_EQUAL(v3.z, 3.0f);\n  }\n  {\n    auto v1 = make_vector_from(4.0f, 5.0f, 6.0f);\n    auto v2 = make_vector_from(1.0f, 2.0f, 3.0f);\n    auto v3 = v1 * v2;\n    BOOST_CHECK_EQUAL(v3.x, 4.0f);\n    BOOST_CHECK_EQUAL(v3.y, 10.0f);\n    BOOST_CHECK_EQUAL(v3.z, 18.0f);\n  }\n  {\n    auto v1 = make_vector_from(4.0f, 5.0f, 6.0f);\n    auto v2 = make_vector_from(1.0f, 2.0f, 3.0f);\n    auto v3 = v1 / v2;\n    BOOST_CHECK_EQUAL(v3.x, 4.0f);\n    BOOST_CHECK_EQUAL(v3.y, 2.5f);\n    BOOST_CHECK_EQUAL(v3.z, 2.0f);\n  }\n  {\n    auto v1 = make_vector_from(4.0f, 5.0f, 6.0f);\n    auto v2 = v1 * 2.0f;\n    BOOST_CHECK_EQUAL(v2.x, 8.0f);\n    BOOST_CHECK_EQUAL(v2.y, 10.0f);\n    BOOST_CHECK_EQUAL(v2.z, 12.0f);\n  }\n  {\n    auto v1 = make_vector_from(4.0f, 5.0f, 6.0f);\n    auto v2 = 2.0f * v1;\n    BOOST_CHECK_EQUAL(v2.x, 8.0f);\n    BOOST_CHECK_EQUAL(v2.y, 10.0f);\n    BOOST_CHECK_EQUAL(v2.z, 12.0f);\n  }\n  {\n    auto v1 = make_vector_from(4.0f, 5.0f, 6.0f);\n    auto v2 = v1 / 2.0f;\n    BOOST_CHECK_EQUAL(v2.x, 2.0f);\n    BOOST_CHECK_EQUAL(v2.y, 2.5f);\n    BOOST_CHECK_EQUAL(v2.z, 3.0f);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(vector_arithmetic_assignment_operators)\n{\n  {\n    auto v1 = make_vector_from(4.0f, 5.0f, 6.0f);\n    auto v2 = make_vector_from(1.0f, 2.0f, 3.0f);\n    v1 += v2;\n    BOOST_CHECK_EQUAL(v1.x, 5.0f);\n    BOOST_CHECK_EQUAL(v1.y, 7.0f);\n    BOOST_CHECK_EQUAL(v1.z, 9.0f);\n  }\n  {\n    auto v1 = make_vector_from(4.0f, 5.0f, 6.0f);\n    auto v2 = make_vector_from(1.0f, 2.0f, 3.0f);\n    v1 -= v2;\n    BOOST_CHECK_EQUAL(v1.x, 3.0f);\n    BOOST_CHECK_EQUAL(v1.y, 3.0f);\n    BOOST_CHECK_EQUAL(v1.z, 3.0f);\n  }\n  {\n    auto v1 = make_vector_from(4.0f, 5.0f, 6.0f);\n    auto v2 = make_vector_from(1.0f, 2.0f, 3.0f);\n    v1 *= v2;\n    BOOST_CHECK_EQUAL(v1.x, 4.0f);\n    BOOST_CHECK_EQUAL(v1.y, 10.0f);\n    BOOST_CHECK_EQUAL(v1.z, 18.0f);\n  }\n  {\n    auto v1 = make_vector_from(4.0f, 5.0f, 6.0f);\n    auto v2 = make_vector_from(1.0f, 2.0f, 3.0f);\n    v1 /= v2;\n    BOOST_CHECK_EQUAL(v1.x, 4.0f);\n    BOOST_CHECK_EQUAL(v1.y, 2.5f);\n    BOOST_CHECK_EQUAL(v1.z, 2.0f);\n  }\n  {\n    auto v = make_vector_from(4.0f, 5.0f, 6.0f);\n    v *= 2.0f;\n    BOOST_CHECK_EQUAL(v.x, 8.0f);\n    BOOST_CHECK_EQUAL(v.y, 10.0f);\n    BOOST_CHECK_EQUAL(v.z, 12.0f);\n  }\n  {\n    auto v = make_vector_from(4.0f, 5.0f, 6.0f);\n    v /= 2.0f;\n    BOOST_CHECK_EQUAL(v.x, 2.0f);\n    BOOST_CHECK_EQUAL(v.y, 2.5f);\n    BOOST_CHECK_EQUAL(v.z, 3.0f);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(vector_swizzle)\n{\n  auto v1 = make_vector_from(1.0f, 2.0f, 3.0f);\n  auto v2 = swizzle<2, 1, 0>(v1);\n  BOOST_CHECK_EQUAL(v2.x, v1.z);\n  BOOST_CHECK_EQUAL(v2.y, v1.y);\n  BOOST_CHECK_EQUAL(v2.z, v1.x);\n\n  auto v3 = swizzle<1, 2, 1, 0>(v1);\n  BOOST_CHECK_EQUAL(v3.x, v1.y);\n  BOOST_CHECK_EQUAL(v3.y, v1.z);\n  BOOST_CHECK_EQUAL(v3.z, v1.y);\n  BOOST_CHECK_EQUAL(v3.w, v1.x);\n}\n\nBOOST_AUTO_TEST_CASE(vector_norm)\n{\n  using std::abs;\n  using std::norm;\n  {\n    const auto v1 = make_vector_from(1.0f, 2.0f, 3.0f);\n    const auto v2 = make_vector_from(1, 2, 3);\n    BOOST_CHECK_EQUAL(norm(v1), 14.0f);\n    BOOST_CHECK_EQUAL(norm(v2), 14);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(vector_abs)\n{\n  using std::abs;\n  using std::norm;\n  {\n    const auto v1 = make_vector_from(3.0f, 4.0f, 12.0f);\n    const auto v2 = make_vector_from(3, 4, 12);\n    BOOST_CHECK_EQUAL(abs(v1), 13.0f);\n    BOOST_CHECK_EQUAL(abs(v2), 13.0);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(vector_std_min_max)\n{\n  const auto v1 = make_vector_from(1.0f, 0.0f, 0.0f);\n  const auto v2 = make_vector_from(0.0f, 2.0f, 0.0f);\n  BOOST_CHECK_EQUAL(std::min(v1, v2), v1);\n  BOOST_CHECK_EQUAL(std::min(v2, v1), v1);\n  BOOST_CHECK_EQUAL(std::max(v1, v2), v2);\n  BOOST_CHECK_EQUAL(std::max(v2, v1), v2);\n}\n\nBOOST_AUTO_TEST_CASE(vector_math_min_max)\n{\n  const auto v1 = make_vector_from(1.0f, 5.0f, 3.0f);\n  const auto v2 = make_vector_from(2.0f, 4.0f, 6.0f);\n  BOOST_CHECK_EQUAL(min(v1), 1.0f);\n  BOOST_CHECK_EQUAL(max(v1), 5.0f);\n  BOOST_CHECK_EQUAL(min(v2), 2.0f);\n  BOOST_CHECK_EQUAL(max(v2), 6.0f);\n  BOOST_CHECK_EQUAL(min(v1, v2), make_vector_from(1.0f, 4.0f, 3.0f));\n  BOOST_CHECK_EQUAL(min(v2, v1), make_vector_from(1.0f, 4.0f, 3.0f));\n  BOOST_CHECK_EQUAL(max(v1, v2), make_vector_from(2.0f, 5.0f, 6.0f));\n  BOOST_CHECK_EQUAL(max(v2, v1), make_vector_from(2.0f, 5.0f, 6.0f));\n}\n\nBOOST_AUTO_TEST_CASE(vector_dot)\n{\n  BOOST_CHECK_EQUAL(\n    dot(make_vector_from(1.0f, 2.0f), make_vector_from(3.0f, 4.0f)), 11.0f);\n  BOOST_CHECK_EQUAL(\n    dot(make_vector_from(1.0f, 2.0f, 3.0f), make_vector_from(4.0f, 5.0f, 6.0f)),\n    32.0f);\n  BOOST_CHECK_EQUAL(dot(make_vector_from(1.0f, 2.0f, 3.0f, 4.0f),\n                        make_vector_from(5.0f, 6.0f, 7.0f, 8.0f)),\n                    70.0f);\n}\n\nBOOST_AUTO_TEST_CASE(vector_cross)\n{\n  {\n    constexpr auto v1 = make_vector_from(1.0f, 2.0f);\n    constexpr auto v2 = make_vector_from(3.0f, 4.0f);\n    BOOST_CHECK_EQUAL(cross(v1, v2), -2.0f);\n  }\n  {\n    constexpr auto x_axis = make_vector_from(1.0f, 0.0f, 0.0f);\n    constexpr auto y_axis = make_vector_from(0.0f, 1.0f, 0.0f);\n    constexpr auto z_axis = make_vector_from(0.0f, 0.0f, 1.0f);\n    BOOST_CHECK_EQUAL(cross(x_axis, y_axis), z_axis);\n    BOOST_CHECK_EQUAL(cross(y_axis, z_axis), x_axis);\n    BOOST_CHECK_EQUAL(cross(z_axis, x_axis), y_axis);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(vector_floor)\n{\n  const auto v1 = make_vector_from(-1.7f, -1.5f, -1.2f);\n  const auto v2 = make_vector_from(-0.0f, 0.0f);\n  const auto v3 = make_vector_from(1.2f, 1.5f, 1.7f);\n  BOOST_CHECK_EQUAL(floor(v1), make_vector_from(-2.0f, -2.0f, -2.0f));\n  BOOST_CHECK_EQUAL(floor(v2), make_vector_from(-0.0f, 0.0f));\n  BOOST_CHECK_EQUAL(floor(v3), make_vector_from(1.0f, 1.0f, 1.0f));\n}\n\nBOOST_AUTO_TEST_CASE(vector_ceil)\n{\n  const auto v1 = make_vector_from(-1.7f, -1.5f, -1.2f);\n  const auto v2 = make_vector_from(-0.0f, 0.0f);\n  const auto v3 = make_vector_from(1.2f, 1.5f, 1.7f);\n  BOOST_CHECK_EQUAL(ceil(v1), make_vector_from(-1.0f, -1.0f, -1.0f));\n  BOOST_CHECK_EQUAL(ceil(v2), make_vector_from(-0.0f, 0.0f));\n  BOOST_CHECK_EQUAL(ceil(v3), make_vector_from(2.0f, 2.0f, 2.0f));\n}\n\nBOOST_AUTO_TEST_CASE(vector_round)\n{\n  const auto v1 = make_vector_from(-1.7f, -1.5f, -1.2f);\n  const auto v2 = make_vector_from(-0.0f, 0.0f);\n  const auto v3 = make_vector_from(1.2f, 1.5f, 1.7f);\n  BOOST_CHECK_EQUAL(round(v1), make_vector_from(-2.0f, -2.0f, -1.0f));\n  BOOST_CHECK_EQUAL(round(v2), make_vector_from(-0.0f, 0.0f));\n  BOOST_CHECK_EQUAL(round(v3), make_vector_from(1.0f, 2.0f, 2.0f));\n}\n\nBOOST_AUTO_TEST_CASE(vector_clamp)\n{\n  BOOST_CHECK_EQUAL(clamp(make_vector_from(1.5f, 1.5f, 1.5f),\n                          make_vector_from(2.0f, 1.0f, 0.0f),\n                          make_vector_from(3.0f, 2.0f, 1.0f)),\n                    make_vector_from(2.0f, 1.5f, 1.0f));\n}\n\nBOOST_AUTO_TEST_CASE(vector_normalize)\n{\n  {\n    const auto v1 = make_vector_from(2.0f, 0.0f, 0.0f);\n    const auto v2 = make_vector_from(1.0f, 0.0f, 0.0f);\n    const auto v3 = make_vector_from(0.1f, 0.0f, 0.0f);\n    BOOST_CHECK_EQUAL(normalize(v1), v2);\n    BOOST_CHECK_EQUAL(normalize(v2), v2);\n    BOOST_CHECK_EQUAL(normalize(v3), v2);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(vector_reflect)\n{\n  using std::norm;\n  {\n    const auto direction = make_vector_from(0.0f, -1.0f);\n    const auto normal = normalize(make_vector_from(1.0f, 2.0f));\n    const auto expected_result = make_vector_from(0.8f, 0.6f);\n    auto result = reflect(direction, normal);\n    BOOST_CHECK(almost_equal(result, expected_result));\n    BOOST_CHECK(norm(direction) == 1.0f);\n    BOOST_CHECK(norm(expected_result) == 1.0f);\n    BOOST_CHECK(almost_equal(reflect(result, normal), direction));\n  }\n  {\n    const auto direction = make_vector_from(-1.0f, 0.0f);\n    const auto normal = normalize(make_vector_from(1.0f, 2.0f));\n    const auto expected_result = make_vector_from(-0.6f, 0.8f);\n    auto result = reflect(direction, normal);\n    BOOST_CHECK(almost_equal(result, expected_result));\n    BOOST_CHECK(norm(direction) == 1.0f);\n    BOOST_CHECK(norm(expected_result) == 1.0f);\n    BOOST_CHECK(almost_equal(reflect(-result, normal), -direction));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(vector_step)\n{\n  BOOST_CHECK_EQUAL(step(0.5f, make_vector_from(0.0f, 0.5f, 2.0f)),\n                    make_vector_from(0.0f, 1.0f, 1.0f));\n  BOOST_CHECK_EQUAL(step(make_vector_from(0.5f, 0.5f, 0.5f),\n                         make_vector_from(0.0f, 0.5f, 2.0f)),\n                    make_vector_from(0.0f, 1.0f, 1.0f));\n}\n\nBOOST_AUTO_TEST_CASE(vector_mix)\n{\n  using shift::core::mix;\n  BOOST_CHECK_EQUAL(mix(make_vector_from(0.0f, 1.0f, 2.0f),\n                        make_vector_from(4.0f, 5.0f, 6.0f), 0.25f),\n                    make_vector_from(1.0f, 2.0f, 3.0f));\n  BOOST_CHECK_EQUAL(\n    mix(make_vector_from(0.0f, 1.0f, 2.0f), make_vector_from(4.0f, 5.0f, 6.0f),\n        make_vector_from(0.5f, 0.25f, 0.75f)),\n    make_vector_from(2.0f, 2.0f, 5.0f));\n}\n\n/// A dummy type used for testing. The template argument has to be a\n/// compile-time constant and be equal to 2 in order to hit the template\n/// specialization.\ntemplate <int Const>\nstruct constexpr_test\n{\n  static constexpr bool value = false;\n};\n\ntemplate <>\nstruct constexpr_test<2>\n{\n  static constexpr bool value = true;\n};\n\nBOOST_AUTO_TEST_CASE(vector_contexpr)\n{\n  constexpr vector3<int> v1(1, 2, 3);\n  BOOST_STATIC_ASSERT((constexpr_test<v1(1)>::value));\n\n  constexpr auto v2 = make_vector_from(1, 2, 3);\n  BOOST_STATIC_ASSERT((constexpr_test<v2(1)>::value));\n}\n", "meta": {"hexsha": "61ec34856c9637b7d4e9293a8bbf3ca885e216e3", "size": 15587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shift/math/test/vector.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/vector.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/vector.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": 31.1117764471, "max_line_length": 80, "alphanum_fraction": 0.675242189, "num_tokens": 6026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5063618636899481}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n// Note: Matrices unit tests have been split in different files since\n// building them with eigen3 eats a lot of RAM and may be a problem while\n// compiling in small systems.\n\n#include <gtest/gtest.h>\n#include <mrpt/math/CMatrixFixed.h>\n#include <mrpt/random.h>\n\n#include <Eigen/Dense>\n\nusing namespace mrpt;\nusing namespace mrpt::math;\nusing namespace mrpt::random;\nusing namespace std;\n\nTEST(Matrices, loadFromArray)\n{\n\talignas(MRPT_MAX_STATIC_ALIGN_BYTES)\n\t\tconst double nums[3 * 4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};\n\n\tCMatrixFixed<double, 3, 4> mat;\n\tmat.loadFromArray(nums);\n\n\tfor (int r = 0; r < 3; r++)\n\t\tfor (int c = 0; c < 4; c++)\n\t\t\tEXPECT_EQ(nums[4 * r + c], mat(r, c));\n}\n\nalignas(MRPT_MAX_STATIC_ALIGN_BYTES) static double test_nums[3 * 4] = {\n\t1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};\n\nTEST(Matrices, CMatrixFixedNumeric_loadWithEigenMap)\n{\n\t// Row major\n\tconst auto mat =\n\t\tCMatrixFixed<double, 3, 4>(Eigen::Map<\n\t\t\t\t\t\t\t\t   Eigen::Matrix<double, 3, 4, Eigen::RowMajor>,\n\t\t\t\t\t\t\t\t   MRPT_MAX_STATIC_ALIGN_BYTES>(test_nums));\n\n\tfor (int r = 0; r < 3; r++)\n\t\tfor (int c = 0; c < 4; c++)\n\t\t\tEXPECT_EQ(test_nums[4 * r + c], mat(r, c));\n}\n\nTEST(Matrices, EigenMatrix_loadWithEigenMap)\n{\n\t// Col major\n\tconst Eigen::Matrix<double, 3, 4> mat =\n\t\tEigen::Map<Eigen::Matrix<double, 3, 4>, MRPT_MAX_STATIC_ALIGN_BYTES>(\n\t\t\ttest_nums);\n\n\tfor (int r = 0; r < 3; r++)\t // Transposed!!\n\t\tfor (int c = 0; c < 4; c++)\n\t\t\tEXPECT_EQ(test_nums[3 * c + r], mat(r, c));\n}\n", "meta": {"hexsha": "243093a7a0b55b66761de2d1e0e6c3ca928651c4", "size": 2099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/src/matrix_ops5_unittest.cpp", "max_stars_repo_name": "wstnturner/mrpt", "max_stars_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T05:24:26.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-17T00:30:02.000Z", "max_issues_repo_path": "libs/math/src/matrix_ops5_unittest.cpp", "max_issues_repo_name": "wstnturner/mrpt", "max_issues_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T22:43:00.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-17T18:52:59.000Z", "max_forks_repo_path": "libs/math/src/matrix_ops5_unittest.cpp", "max_forks_repo_name": "wstnturner/mrpt", "max_forks_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T12:32:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-30T15:50:13.000Z", "avg_line_length": 32.2923076923, "max_line_length": 80, "alphanum_fraction": 0.5454978561, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.5063618636899481}}
{"text": "#ifndef MULTIAGENT_UTILS_COALITION_STRUCTURE_GENERATION_HPP\n#define MULTIAGENT_UTILS_COALITION_STRUCTURE_GENERATION_HPP\n\n#include <limits>\n#include <boost/function.hpp>\n#include <boost/thread.hpp>\n#include <numeric/IntegerPartitioning.hpp>\n#include <base/Time.hpp>\n#include <base-logging/Logging.hpp>\n\nnamespace multiagent {\nnamespace utils {\n\ntypedef std::string Agent;\ntypedef std::vector<Agent> AgentList;\ntypedef AgentList Coalition;\ntypedef std::vector< Coalition > CoalitionStructure;\n\nstd::ostream& operator<<(std::ostream& os, const AgentList& list);\nstd::ostream& operator<<(std::ostream& os, const CoalitionStructure& list);\n\nstruct Bounds\n{\n    Bounds(double exact);\n    Bounds();\n\n    double maximum;\n    double average;\n    double minimum;\n\n    std::string toString() const;\n};\n\n\nstd::ostream& operator<<(std::ostream& os, const Bounds& bounds);\n\n/**\n * This is an implementation of the coalition structure generation as described in:\n * \"An Anytime Algorithm for Optimal Coalition Structure Generation\", (Rahwan et al., 2009)\n *\n * Please note that the current implementation uses recursion\n */\nclass CoalitionStructureGeneration\n{\npublic:\n    typedef boost::function1<double, const Coalition&> CoalitionValueFunction;\n    typedef boost::function1<double, const CoalitionStructure&> CoalitionStructureValueFunction;\n\n    struct Statistics\n    {\n        std::vector<numeric::IntegerPartition> allIntegerPartitions;\n        std::vector<numeric::IntegerPartition> prunedIntegerPartitions;\n        std::vector<numeric::IntegerPartition> searchedIntegerPartitions;\n\n        std::vector<numeric::IntegerPartition> remainingIntegerPartitions() const;\n\n        std::string toString() const;\n    };\n\nprivate:\n    AgentList mAgents;\n    Statistics mStatistics;\n\n    // Agents listed by size of the coalition\n    typedef std::map<size_t, std::set< Coalition > > AgentCoalitionMap;\n    AgentCoalitionMap mAgentCoalitionMap;\n\n    typedef std::map<size_t, Bounds> CoalitionBoundMap;\n    CoalitionBoundMap mCoalitionBoundMap;\n\n    CoalitionValueFunction mCoalitionValueFunction;\n    CoalitionStructureValueFunction mCoalitionStructureValueFunction;\n\n    typedef std::map<numeric::IntegerPartition, Bounds> IntegerPartitionBoundsMap;\n    IntegerPartitionBoundsMap mIntegerPartitionBoundsMap;\n\n    mutable boost::mutex mSolutionMutex;\n    mutable boost::mutex mStatisticsMutex;\n    boost::thread mThread;\n    base::Time mStartTime;\n    base::Time mCompletionTime;\n    CoalitionStructure mCurrentBestCoalitionStructure;\n    double mCurrentBestCoalitionStructureValue;\n    double mCurrentSolutionQuality;\n    double mGlobalUpperBound;\n\n    /**\n     * Compute the integer partitions and the agent coalition map for coalition size up to\n     * the maximum number of agents\n     */\n    void prepare();\n\n    double bestLowerBound(const CoalitionBoundMap& boundMap);\n    double bestLowerBound(const IntegerPartitionBoundsMap& boundMap);\n    double bestUpperBound(const IntegerPartitionBoundsMap& boundMap);\n\n    Bounds computeIntegerPartitionBounds(const numeric::IntegerPartition& partition);\n    IntegerPartitionBoundsMap prune(const IntegerPartitionBoundsMap& boundsMap);\n    CoalitionBoundMap prune(const CoalitionBoundMap& boundMap);\n\n    numeric::IntegerPartition selectIntegerPartition(const IntegerPartitionBoundsMap& boundMap, double maximumBound) const;\n\n    /**\n     *\n     * \\param globalUpperBound\n     * \\param bestStar Quality of the solution, i.e. 1.05 means 95% percent of the optimal solution\n     * \\return true if this subspace contained a better solution than already existed\n     */\n    bool searchSubspace(const numeric::IntegerPartition& partition, size_t k, size_t alpha, const AgentList& agents, const CoalitionStructure& currentStructure, double betaStar);\n\n    bool updateCurrentBestCoalitionStructure(const CoalitionStructure& coalitionStructure, double value);\n\npublic:\n    /**\n     * Find best coalitionstructure -- will block until coalition structure is found\n     */ \n    CoalitionStructure findBest(double quality = 1.0);\n\n    /**\n     * Reset in order to restart a new search\n     */\n    void reset();\n\n    /**\n     * Search for a solution and allow retrieval of intermediate results via currentBestSolution\n     */\n    void anytimeSearch(double quality = 1.0);\n\n    /**\n     * Check if anytimeSearch completed\n     * \\return true, upon completition, false otherwise -- if search has not been started at all, it will return false\n     */\n    bool anytimeSearchCompleted() const { return mCompletionTime != base::Time(); }\n\n    /**\n     * Compute total elapsed time since last search start\n     * \\return time object representing the elapsed time, i.e. use toSeconds() or corresponding function to retrieve detailled value\n     */\n    base::Time elapsed() const { return base::Time::now() - mStartTime; }\n\n    /**\n     * Stop the search before completion\n     */\n    void stopSearch();\n\n    /**\n     * Retrieve the current best solution\n     * return the current best solution, if none has been found it will return an empty CoalitionStructure\n     */\n    CoalitionStructure currentBestSolution() const;\n\n    double currentBestSolutionValue() const;\n    double currentBestSolutionQuality() const;\n\n\n    /**\n     * \\params agents List of agents that are available\n     * \\param coalitionValueFunction Function that allows to compute the value of an individual coalition\n     * \\param coalitionStructureValueFunction Function that allows to compute the value of a coalition structure\n     */\n    CoalitionStructureGeneration(const AgentList& agents, CoalitionValueFunction coalitionValueFunction, CoalitionStructureValueFunction coalitionStructureValueFunction);\n\n\n    /**\n     * Stringify status of this CoalitionStructureGeneration object\n     * \\return stringified instance\n     */\n    std::string toString() const;\n\n    /**\n     * Stringify a CoalitionStructure\n     * \\return stringified instance of CoalitionStructure\n     */\n    static std::string toString(const CoalitionStructure& c);\n\n    Statistics getStatistics() const;\n};\n\n} // end namespace utils\n} // end namespace multiagent\n#endif // MULTIAGENT_UTILS_COALITION_STRUCTURE_GENERATION_HPP\n", "meta": {"hexsha": "f10292a3292b4285925cfa61be0c83ed5e6ad426", "size": 6177, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/CoalitionStructureGeneration.hpp", "max_stars_repo_name": "tomcreutz/knowledge-reasoning-moreorg", "max_stars_repo_head_hexsha": "545fa92eaf0fc8ccc4cc042bd994afc918d16f68", "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/CoalitionStructureGeneration.hpp", "max_issues_repo_name": "tomcreutz/knowledge-reasoning-moreorg", "max_issues_repo_head_hexsha": "545fa92eaf0fc8ccc4cc042bd994afc918d16f68", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-26T11:11:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-26T19:16:10.000Z", "max_forks_repo_path": "src/utils/CoalitionStructureGeneration.hpp", "max_forks_repo_name": "tomcreutz/knowledge-reasoning-moreorg", "max_forks_repo_head_hexsha": "545fa92eaf0fc8ccc4cc042bd994afc918d16f68", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-17T13:02:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T13:02:49.000Z", "avg_line_length": 33.9395604396, "max_line_length": 178, "alphanum_fraction": 0.7450218553, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5063618602111531}}
{"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//[assign_box_corners\r\n//` Shows how four point can be assigned from a 2D box\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/box.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n\r\nusing namespace boost::geometry;\r\n\r\nint main()\r\n{\r\n    typedef model::d2::point_xy<double> point;\r\n    typedef model::box<point> box;\r\n\r\n    box b;\r\n    assign_values(b, 2, 2, 5, 5);\r\n\r\n    point ll, lr, ul, ur;\r\n    assign_box_corners(b, ll, lr, ul, ur);\r\n\r\n    std::cout << \"box: \" << dsv(b) << std::endl << std::endl;\r\n\r\n    std::cout << dsv(ul) << \" --- \" << dsv(ur) << std::endl;\r\n    for (int i = 0; i < 3; i++)\r\n    {\r\n        std::cout << \"  |          |\" << std::endl;\r\n    }\r\n    std::cout << dsv(ll) << \" --- \" << dsv(lr) << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[assign_box_corners_output\r\n/*`\r\nOutput:\r\n[pre\r\nbox: ((2, 2), (5, 5))\r\n\r\n(2, 5) --- (5, 5)\r\n  |          |\r\n  |          |\r\n  |          |\r\n(2, 2) --- (5, 2)\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "21f46111e733bf1634719a16d8e3108ff9862472", "size": 1331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/algorithms/assign_box_corners.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/geometry/doc/src/examples/algorithms/assign_box_corners.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/doc/src/examples/algorithms/assign_box_corners.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": 21.8196721311, "max_line_length": 80, "alphanum_fraction": 0.5529676935, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5063618462963554}}
{"text": "#include <Eigen/Geometry>\n#include <aslam/backend/DesignVariableGenericVector.hpp>\n#include <aslam/backend/DesignVariableVector.hpp>\n#include <aslam/backend/GenericMatrixExpression.hpp>\n#include <aslam/backend/VectorExpression.hpp>\n#include <aslam/backend/VectorExpressionToGenericMatrixTraits.hpp>\n#include <aslam/backend/test/ExpressionTests.hpp>\n#include <sm/eigen/NumericalDiff.hpp>\n#include <sm/eigen/gtest.hpp>\n#include <sm/kinematics/rotations.hpp>\n\nusing namespace aslam::backend;\nusing namespace std;\n\nTEST(GenericMatrixExpressionNodeTestSuites, testGenericMatrixBasicOperations) {\n    try {\n        const int VEC_ROWS = 5;\n\n        typedef GenericMatrixExpression<4, 2> GMAT;\n        typedef GenericMatrixExpression<2, VEC_ROWS> GMAT2;\n\n        auto identity = Eigen::Matrix<double, VEC_ROWS, VEC_ROWS>::Identity();\n        GenericMatrixExpression<VEC_ROWS, VEC_ROWS> identityExp(identity);\n\n        GMAT::matrix_t mat = GMAT::matrix_t::Random();\n        GMAT2::matrix_t mat2 = GMAT2::matrix_t::Random();\n        GMAT matExp(mat);\n        GMAT2 matExp2(mat2);\n\n        sm::eigen::assertNear(matExp.evaluate(), mat, 1e-14, SM_SOURCE_FILE_POS,\n                              \"Testing evaluation fits initialization.\");\n        sm::eigen::assertNear(matExp2.evaluate(), mat2, 1e-14, SM_SOURCE_FILE_POS,\n                              \"Testing evaluation fits initialization.\");\n\n        sm::eigen::assertNear(identityExp.evaluate(), identity, 1e-14, SM_SOURCE_FILE_POS,\n                              \"Testing the transpose method.\");\n        sm::eigen::assertNear((matExp.transpose()).evaluate(), mat.transpose(), 1e-14, SM_SOURCE_FILE_POS,\n                              \"Testing the transpose method.\");\n        sm::eigen::assertNear((matExp * matExp2).evaluate(), mat * mat2, 1e-14, SM_SOURCE_FILE_POS,\n                              \"Testing the product.\");\n        sm::eigen::assertNear((matExp + matExp).evaluate(), 2 * mat, 1e-14, SM_SOURCE_FILE_POS, \"Testing the sum.\");\n        sm::eigen::assertNear((matExp - matExp).evaluate(), 0 * mat, 1e-14, SM_SOURCE_FILE_POS,\n                              \"Testing the difference.\");\n\n        // vector design variable\n        typedef GenericMatrixExpression<VEC_ROWS, 1, double> GV;\n        typedef DesignVariableGenericVector<VEC_ROWS> DGvec;\n        GV::matrix_t vec = GV::matrix_t::Random();\n        DGvec dv(vec);\n        dv.setActive(true);\n        dv.setBlockIndex(0);\n        GV vecExp(&dv);\n\n        sm::eigen::assertNear((matExp2 * vecExp).evaluate(), mat2 * vec, 1e-14, SM_SOURCE_FILE_POS,\n                              \"Testing the matrix vector design variable product.\");\n\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(vec.rows());\n            sm::eigen::assertEqual(dv.value(), vec, SM_SOURCE_FILE_POS, \"Testing evaluation fits initialization.\");\n            sm::eigen::assertEqual(vecExp.evaluate(), vec, SM_SOURCE_FILE_POS,\n                                   \"Testing evaluation fits initialization.\");\n            vecExp.evaluateJacobians(jc);\n            sm::eigen::assertNear(jc.asDenseMatrix(), identity, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(vec.rows());\n            auto exp = identityExp * vecExp;\n            exp.evaluateJacobians(jc);\n            sm::eigen::assertNear(exp.evaluate(), vec, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing the transposed design variable matrix product.\");\n            sm::eigen::assertNear(jc.asDenseMatrix(), identity, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(VEC_ROWS);\n            auto exp = -vecExp;\n            (exp).evaluateJacobians(jc);\n            sm::eigen::assertNear(exp.evaluate(), -(vecExp.evaluate()), 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing the negated design variable.\");\n            sm::eigen::assertNear(jc.asDenseMatrix(), -identity, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(mat2.rows());\n            auto exp = matExp2 * vecExp;\n            (exp).evaluateJacobians(jc);\n            sm::eigen::assertNear(exp.evaluate(), matExp2.evaluate() * vecExp.evaluate(), 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing the design variable matrix product.\");\n            sm::eigen::assertNear(jc.asDenseMatrix(), mat2, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(mat2.rows());\n            auto exp = (vecExp.transpose() * matExp2.transpose()).transpose();\n            exp.evaluateJacobians(jc);\n            sm::eigen::assertNear(exp.evaluate(), matExp2.evaluate() * vecExp.evaluate(), 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing the transposed design variable matrix product.\");\n            sm::eigen::assertNear(jc.asDenseMatrix(), mat2, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(1);\n            auto exp = (vecExp.transpose() * vecExp);\n            exp.evaluateJacobians(jc);\n            sm::eigen::assertNear(exp.evaluate(), vecExp.transpose().evaluate() * vecExp.evaluate(), 1e-14,\n                                  SM_SOURCE_FILE_POS, \"Testing the design variable vector square.\");\n            sm::eigen::assertNear(jc.asDenseMatrix(), 2 * vec.transpose(), 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n\n        {\n            JacobianContainer jc(1);\n            auto exp = (vecExp.transpose() * vecExp).inverse();\n            Eigen::Matrix<double, 1, 1> val;\n            val(0, 0) = 1 / vec.dot(vec);\n            sm::eigen::assertNear(exp.evaluate(), val, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing the inverse operation on a 1 x 1 matrix.\");\n            exp.evaluateJacobians(jc);\n            sm::eigen::assertNear(jc.asDenseMatrix(), -2 * vec.transpose() * (1 / (vec.dot(vec) * vec.dot(vec))), 1e-14,\n                                  SM_SOURCE_FILE_POS, \"Testing evaluationJacobian fits theoretical value.\");\n        }\n\n        {\n            auto inv = vecExp * vecExp.transpose();\n            auto invValue = (vec * vec.transpose()).eval();\n            sm::eigen::assertNear(inv.evaluate(), invValue, 1e-14, SM_SOURCE_FILE_POS, \"Testing the dyadic product.\");\n\n            JacobianContainer jc(VEC_ROWS);\n            for (int i = 0; i < VEC_ROWS; i++) {\n                jc.clear();\n                GV::matrix_t testVectorValue = GV::matrix_t::Zero();\n                testVectorValue[i] = 1;\n                GV testVector(testVectorValue);\n                auto exp = inv * testVector;\n                sm::eigen::assertNear(exp.evaluate(), invValue * testVectorValue, 1e-14, SM_SOURCE_FILE_POS,\n                                      \"Testing the dyadic product.\");\n                testJacobian(exp);\n                exp.evaluateJacobians(jc);\n                sm::eigen::assertNear(jc.asDenseMatrix(),\n                                      identity * vec.dot(testVectorValue) + vec * (testVectorValue).transpose(), 1e-14,\n                                      SM_SOURCE_FILE_POS, \"Testing evaluationJacobian fits theoretical value.\");\n            }\n        }\n\n        {\n            auto inv = (identityExp + vecExp * vecExp.transpose()).inverse();\n            auto invValue = (identity + vec * vec.transpose()).inverse().eval();\n            sm::eigen::assertNear(inv.evaluate(), invValue, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing the inverse operation.\");\n\n            JacobianContainer jc(VEC_ROWS);\n            for (int i = 0; i < VEC_ROWS; i++) {\n                jc.clear();\n                GV::matrix_t testVectorValue = GV::matrix_t::Zero();\n                testVectorValue[i] = 1;\n                GV testVector(testVectorValue);\n                auto exp = inv * testVector;\n                sm::eigen::assertNear(exp.evaluate(), invValue * testVectorValue, 1e-14, SM_SOURCE_FILE_POS,\n                                      \"Testing the inverse operation.\");\n                testJacobian(exp);\n                exp.evaluateJacobians(jc);\n                sm::eigen::assertNear(jc.asDenseMatrix(),\n                                      -invValue * (identity * vec.dot(invValue * testVectorValue) +\n                                                   vec * (invValue * testVectorValue).transpose()),\n                                      1e-14, SM_SOURCE_FILE_POS, \"Testing evaluationJacobian fits theoretical value.\");\n            }\n        }\n\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(VEC_ROWS);\n            auto exp = vecExp * 3;\n            GV exp2 = exp;\n            exp2.evaluateJacobians(jc);\n            sm::eigen::assertNear(exp2.evaluate(), vec * 3, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing the design variable times a scalar.\");\n            sm::eigen::assertNear(jc.asDenseMatrix(), identity * 3, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n\n        typedef GenericMatrixExpression<VEC_ROWS, VEC_ROWS> GM3;\n        GM3::matrix_t mat3 = GM3::matrix_t::Random();\n        GM3 matExp3(mat3);\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(1);\n            (vecExp.transpose() * matExp3 * vecExp).evaluateJacobians(jc);\n            sm::eigen::assertNear(jc.asDenseMatrix(), vec.transpose() * (mat3 + mat3.transpose()), 1e-14,\n                                  SM_SOURCE_FILE_POS, \"Testing evaluationJacobian fits theoretical value.\");\n        }\n\n        // second vector design variable\n        GV::matrix_t vec2 = GV::matrix_t::Random();\n        DGvec dv2(vec2);\n        dv2.setActive(true);\n        dv2.setBlockIndex(1);\n        GV vecExp2(&dv2);\n\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(1);\n            (vecExp2.transpose() * matExp3 * vecExp).evaluateJacobians(jc);\n\n            Eigen::Matrix<double, 1, VEC_ROWS * 2> result;\n            result.head<VEC_ROWS>() = vec2.transpose() * mat3;\n            result.tail<VEC_ROWS>() = vec.transpose() * mat3.transpose();\n\n            sm::eigen::assertNear(jc.asDenseMatrix(), result, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(VEC_ROWS);\n            (vecExp + vecExp2).evaluateJacobians(jc);\n            Eigen::Matrix<double, VEC_ROWS, 2 * VEC_ROWS> result;\n            result.block<VEC_ROWS, VEC_ROWS>(0, 0).setIdentity();\n            result.block<VEC_ROWS, VEC_ROWS>(0, VEC_ROWS).setIdentity();\n\n            sm::eigen::assertNear(jc.asDenseMatrix(), result, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(VEC_ROWS);\n            (vecExp - vecExp2).evaluateJacobians(jc);\n            Eigen::Matrix<double, VEC_ROWS, 2 * VEC_ROWS> result;\n            result.block<VEC_ROWS, VEC_ROWS>(0, 0).setIdentity();\n            result.block<VEC_ROWS, VEC_ROWS>(0, VEC_ROWS).setIdentity() *= -1;\n\n            sm::eigen::assertNear(jc.asDenseMatrix(), result, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n    } catch (std::exception const& e) {\n        FAIL() << e.what();\n    }\n}\n\nTEST(GenericMatrixExpressionNodeTestSuites, testVectorExpressionToGenericMatrixExpression) {\n    try {\n        const int VEC_ROWS = 5;\n\n        DesignVariableVector<VEC_ROWS> dvec;\n        dvec.setActive(true);\n        dvec.setBlockIndex(0);\n        Eigen::MatrixXd vec = Eigen::MatrixXd::Random(VEC_ROWS, 1);\n        dvec.setParameters(vec);\n\n        VectorExpression<VEC_ROWS> vecExp(&dvec);\n        auto gVecExp = convertToGME(vecExp);\n\n        SCOPED_TRACE(\"\");\n        sm::eigen::assertNear(gVecExp.evaluate(), vec, 1e-14, SM_SOURCE_FILE_POS,\n                              \"Testing evaluation fits initialization.\");\n        sm::eigen::assertNear(gVecExp.transpose().evaluate(), vec.transpose(), 1e-14, SM_SOURCE_FILE_POS,\n                              \"Testing evaluation fits initialization.\");\n\n        typedef GenericMatrixExpression<VEC_ROWS, 1, double> GV;\n        GV gVec(vec);\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(1);\n            auto exp = (gVecExp.transpose() * gVecExp);\n            sm::eigen::assertNear(exp.evaluate(), (vec.transpose() * vec).eval(), 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing the design variable matrix square.\");\n            exp.evaluateJacobians(jc);\n            sm::eigen::assertNear(jc.asDenseMatrix(), (2 * vec.transpose()).eval(), 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n\n        auto identity = Eigen::Matrix<double, VEC_ROWS, VEC_ROWS>::Identity();\n        GenericMatrixExpression<VEC_ROWS, VEC_ROWS> identityExp(identity);\n\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(VEC_ROWS);\n            auto exp = (identityExp * gVecExp);\n            sm::eigen::assertNear(exp.evaluate(), vec.eval(), 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing the identity times the converted vector expression.\");\n            exp.evaluateJacobians(jc);\n            sm::eigen::assertNear(jc.asDenseMatrix(), identity, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(VEC_ROWS);\n            auto exp = (gVecExp.transpose() * identityExp).transpose();\n            sm::eigen::assertNear(exp.evaluate(), vec.eval(), 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing the identity times the converted vector expression.\");\n            exp.evaluateJacobians(jc);\n            sm::eigen::assertNear(jc.asDenseMatrix(), identity, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n        {\n            SCOPED_TRACE(\"\");\n            JacobianContainer jc(VEC_ROWS);\n            auto exp = gVecExp.transpose().transpose();\n            sm::eigen::assertNear(exp.evaluate(), vec.eval(), 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing the identity times the converted vector expression.\");\n            exp.evaluateJacobians(jc);\n            sm::eigen::assertNear(jc.asDenseMatrix(), identity, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n    } catch (std::exception const& e) {\n        FAIL() << e.what();\n    }\n}\n\nTEST(GenericMatrixExpressionNodeTestSuites, testCrossProduct) {\n    try {\n        const int VEC_ROWS = 3;\n\n        typedef Eigen::Matrix<double, VEC_ROWS, 1> vector_t;\n        DesignVariableVector<VEC_ROWS> dvec, dvec2;\n        dvec.setActive(true);\n        dvec.setBlockIndex(0);\n        dvec2.setActive(true);\n        dvec2.setBlockIndex(1);\n        vector_t vec = vector_t::Random();\n        vector_t vec2 = vector_t::Random();\n\n        dvec.setParameters(vec);\n        VectorExpression<VEC_ROWS> vecExp(&dvec);\n        dvec2.setParameters(vec2);\n        VectorExpression<VEC_ROWS> vec2Exp(&dvec2);\n\n        auto gVecExp = convertToGME(vecExp);\n        auto gVec2Exp = convertToGME(vec2Exp);\n\n        typedef GenericMatrixExpression<VEC_ROWS, 2, double> GMAT;\n        typename GMAT::matrix_t mat = GMAT::matrix_t::Random();\n        GMAT gMat(mat);\n        {\n            SCOPED_TRACE(\"\");\n            auto exp = (gVecExp.cross(gMat));\n            sm::eigen::assertNear(exp.evaluate().col(0), vec.cross(mat.col(0)), 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing cross product evaluation.\");\n            sm::eigen::assertNear(exp.evaluate().col(1), vec.cross(mat.col(1)), 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing cross product evaluation.\");\n        }\n        {\n            SCOPED_TRACE(\"\");\n            auto exp = (gVecExp.cross(gVec2Exp));\n            sm::eigen::assertNear(exp.evaluate(), vec.cross(vec2), 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing cross product evaluation.\");\n            JacobianContainer jc(VEC_ROWS);\n            exp.evaluateJacobians(jc);\n            Eigen::Matrix<double, VEC_ROWS, 2 * VEC_ROWS> result;\n            result.block<VEC_ROWS, VEC_ROWS>(0, 0) = sm::kinematics::crossMx(-vec2);\n            result.block<VEC_ROWS, VEC_ROWS>(0, VEC_ROWS) = sm::kinematics::crossMx(vec);\n            sm::eigen::assertNear(jc.asDenseMatrix(), result, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n        {\n            SCOPED_TRACE(\"\");\n            auto exp = (gVecExp.cross(gMat) * GenericMatrixExpression<2, 1>(Eigen::Matrix<double, 2, 1>::Ones()));\n            sm::eigen::assertNear(exp.evaluate(), vec.cross(mat.col(0)) + vec.cross(mat.col(1)), 1e-14,\n                                  SM_SOURCE_FILE_POS, \"Testing cross product evaluation.\");\n            JacobianContainer jc(VEC_ROWS);\n            exp.evaluateJacobians(jc);\n            Eigen::Matrix<double, VEC_ROWS, VEC_ROWS> result;\n            result = sm::kinematics::crossMx(-mat.col(0)) + sm::kinematics::crossMx(-mat.col(1));\n            sm::eigen::assertNear(jc.asDenseMatrix(), result, 1e-14, SM_SOURCE_FILE_POS,\n                                  \"Testing evaluationJacobian fits theoretical value.\");\n        }\n    } catch (std::exception const& e) {\n        FAIL() << e.what();\n    }\n}\n", "meta": {"hexsha": "d9f64c6677b85c450e5fc3b1c017a541bbb4cdb0", "size": 18392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_optimizer/aslam_backend_expressions/test/GenericMatrixExpression.cpp", "max_stars_repo_name": "chengfzy/kalibr", "max_stars_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aslam_optimizer/aslam_backend_expressions/test/GenericMatrixExpression.cpp", "max_issues_repo_name": "chengfzy/kalibr", "max_issues_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aslam_optimizer/aslam_backend_expressions/test/GenericMatrixExpression.cpp", "max_forks_repo_name": "chengfzy/kalibr", "max_forks_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.2729658793, "max_line_length": 120, "alphanum_fraction": 0.5664963027, "num_tokens": 4190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5062980631222785}}
{"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 *    References\n *      Burden, R.L., Faires, J.D. Numerical Analysis, 7th Edition, Books/Cole, 2001.\n *      Montenbruck, O., Gill, E. Satellite Orbits: Models, Methods, Applications, Springer, 2005.\n *      The MathWorks, Inc. RKF54b, Symbolic Math Toolbox, 2012.\n *\n *    Notes\n *      For the tests using data from the Symbolic Math Toolbox (MathWorks, 2012), the single step\n *      and full integration error tolerances were picked to be as small as possible, without\n *      causing the tests to fail. These values are not deemed to indicate any bugs in the code;\n *      however, it is important to take these discrepancies into account when using this numerical\n *      integrator.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/make_shared.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaVariableStepSizeIntegrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaCoefficients.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/numericalIntegrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/reinitializableNumericalIntegrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/UnitTests/numericalIntegratorTests.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/UnitTests/numericalIntegratorTestFunctions.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/UnitTests/burdenAndFairesNumericalIntegratorTest.h\"\n\n#include \"Tudat/InputOutput/matrixTextFileReader.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n#include \"Tudat/Mathematics/BasicMathematics/linearAlgebra.h\"\n\n#include <limits>\n#include <string>\n\n#include <Eigen/Core>\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_runge_kutta_fehlberg_45_integrator )\n\nusing linear_algebra::flipMatrixRows;\n\nusing numerical_integrators::NumericalIntegratorXdPointer;\nusing numerical_integrators::ReinitializableNumericalIntegratorXdPointer;\nusing numerical_integrators::RungeKuttaVariableStepSizeIntegratorXd;\nusing numerical_integrators::RungeKuttaCoefficients;\n\nusing numerical_integrator_test_functions::computeNonAutonomousModelStateDerivative;\n\n//! Test Runge-Kutta-Fehlberg 45 integrator using benchmark data from (Burden and Faires, 2001).\nBOOST_AUTO_TEST_CASE( testRungeKuttaFehlberg45IntegratorUsingBurdenAndFairesData )\n{\n    // Read in benchmark data (Table 5.9 from (Burden and Faires, 2001)).\n    std::string pathToBenchmarkDatafile = input_output::getTudatRootPath( )\n            + \"/Mathematics/NumericalIntegrators/UnitTests/table5_6BurdenAndFaires.txt\";\n\n    // Store benchmark data in matrix.\n    Eigen::MatrixXd table5_9BurdenAndFaires\n            = input_output::readMatrixFromFile( pathToBenchmarkDatafile );\n\n    // Declare constants related to the benchmark file.\n    const int FINAL_ROW = table5_9BurdenAndFaires.rows( ) - 1;\n    const int TIME_COLUMN_INDEX = 0;\n    const int EXPECTED_LOWER_ORDER_STATE_COLUMN_INDEX = 2;\n    const int EXPECTED_STEP_SIZE_COLUMN_INDEX = 3;\n    const int EXPECTED_RELATIVE_ERROR_COLUMN_INDEX = 4;\n    const int EXPECTED_HIGHER_ORDER_STATE_COLUMN_INDEX = 6;\n\n    // Set parameters of integration taken from (Burden and Faires, 2001).\n    // This should to be added to the benchmark data file and parsed accordingly once the Tudat\n    // parser architecture has been added to the library.\n    const double initialTime = 0.0;\n    const double finalTime = 2.0;\n    const Eigen::VectorXd initialState = Eigen::VectorXd::Constant( 1, 0.5 );\n    const double initialStepSize = 0.25;\n    const double minimumStepSize = 0.01;\n    const double maximumStepSize = 0.25;\n    const double relativeErrorTolerance = 0.0;\n    const double absoluteErrorTolerance = 1.0e-5;\n    const double safetyFactorForNextStepSize = 0.84;\n    const double maximumFactorIncreaseForNextStepSize = 4.0;\n    const double minimumFactorDecreaseForNextStepSize = 0.1;\n\n    // Declare Burden and Faires class object, containing new step size and state derivative\n    // functions.\n    BurdenAndFairesNumericalIntegratorTest burdenAndFairesNumericalIntegratorTest;\n\n    // Case 1: Use integrateTo() to integrate to final time in one step and check results against\n    // benchmark data from Burden and Faires.\n    {\n        // Declare integrator with all necessary settings.\n        RungeKuttaVariableStepSizeIntegratorXd integrator(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg45 ),\n                    std::bind( &BurdenAndFairesNumericalIntegratorTest::computeStateDerivative,\n                                 &burdenAndFairesNumericalIntegratorTest, std::placeholders::_1, std::placeholders::_2 ),\n                    initialTime,\n                    initialState,\n                    minimumStepSize,\n                    maximumStepSize,\n                    relativeErrorTolerance,\n                    absoluteErrorTolerance,\n                    safetyFactorForNextStepSize,\n                    maximumFactorIncreaseForNextStepSize,\n                    minimumFactorDecreaseForNextStepSize,\n                    std::bind( &BurdenAndFairesNumericalIntegratorTest::computeNewStepSize,\n                                 &burdenAndFairesNumericalIntegratorTest,\n                                 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4,\n                               std::placeholders::_5, std::placeholders::_6, std::placeholders::_7, std::placeholders::_8 ) );\n\n        // Integrator to final time.\n        Eigen::VectorXd finalState = integrator.integrateTo( finalTime, initialStepSize );\n\n        // Check that the computed final time matches the required final time.\n        BOOST_CHECK_CLOSE_FRACTION( table5_9BurdenAndFaires( FINAL_ROW, TIME_COLUMN_INDEX ),\n                                    integrator.getCurrentIndependentVariable( ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        // Check that computed final state matches the expected final state.\n        BOOST_CHECK_CLOSE_FRACTION(\n                    table5_9BurdenAndFaires( FINAL_ROW, EXPECTED_LOWER_ORDER_STATE_COLUMN_INDEX ),\n                    finalState( 0 ), 1.0e-8 );\n\n        // Roll back to the previous step. This should be possible since the integrateTo() function\n        // was called above.\n        BOOST_CHECK( integrator.rollbackToPreviousState( ) );\n\n        // Check that the rolled back time is as required.\n        BOOST_CHECK_CLOSE_FRACTION(\n                    table5_9BurdenAndFaires( FINAL_ROW - 1, TIME_COLUMN_INDEX ),\n                    integrator.getCurrentIndependentVariable( ), 1.0e-8 );\n\n        // Check that the rolled back state is as required. This test should be exact.\n        BOOST_CHECK_CLOSE_FRACTION(\n                    table5_9BurdenAndFaires( FINAL_ROW - 1,\n                                             EXPECTED_LOWER_ORDER_STATE_COLUMN_INDEX ),\n                    integrator.getCurrentState( )( 0 ), 1.0e-8 );\n\n        // Check that it is now not possible to roll back.\n        BOOST_CHECK( !integrator.rollbackToPreviousState( ) );\n    }\n\n    // Case 2: Use integrateTo() to integrate to final time in multiple steps and check results\n    // against benchmark data from Burden and Faires.\n    {\n        // Declare integrator with all necessary settings.\n        RungeKuttaVariableStepSizeIntegratorXd integrator(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg45 ),\n                    std::bind( &BurdenAndFairesNumericalIntegratorTest::computeStateDerivative,\n                                 &burdenAndFairesNumericalIntegratorTest, std::placeholders::_1, std::placeholders::_2 ),\n                    initialTime,\n                    initialState,\n                    minimumStepSize,\n                    maximumStepSize,\n                    relativeErrorTolerance,\n                    absoluteErrorTolerance,\n                    safetyFactorForNextStepSize,\n                    maximumFactorIncreaseForNextStepSize,\n                    minimumFactorDecreaseForNextStepSize,\n                    std::bind( &BurdenAndFairesNumericalIntegratorTest::computeNewStepSize,\n                                 &burdenAndFairesNumericalIntegratorTest,\n                                 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4,\n                               std::placeholders::_5, std::placeholders::_6, std::placeholders::_7, std::placeholders::_8 ) );\n\n        // Store the initial step size as the step size to perform the first integration step.\n        double stepSize = initialStepSize;\n\n        for ( int i = 1; i < table5_9BurdenAndFaires.rows( ) - 1; i++ )\n        {\n            // Perform integration step using stored step size.\n            integrator.performIntegrationStep( stepSize );\n\n            // Check that the computed intermediate time matches the required intermediate time.\n            BOOST_CHECK_CLOSE_FRACTION( table5_9BurdenAndFaires( i, TIME_COLUMN_INDEX ),\n                                        integrator.getCurrentIndependentVariable( ),\n                                        1.0e-8 );\n\n            // Check that the computed intermediate state matches the required intermediate state.\n            // Note that for some reason the check for table5_9BurdenAndFaires( 2, 2 ) failed\n            // against a tolerance of 1.0e-8: this seems to come from the fact that the input data\n            // from the file is read in incorrectly, introducing an error in the last significant\n            // digit. All the other values satisfy a tolerance of 1.0e-8.\n            BOOST_CHECK_CLOSE_FRACTION(\n                        table5_9BurdenAndFaires( i, EXPECTED_LOWER_ORDER_STATE_COLUMN_INDEX ),\n                        integrator.getCurrentState( )( 0 ),\n                        1.0e-7 );\n\n            // Check that the computed step size matches the required step size state.\n            BOOST_CHECK_CLOSE_FRACTION(\n                        table5_9BurdenAndFaires( i, EXPECTED_STEP_SIZE_COLUMN_INDEX ),\n                        stepSize, 1.0e-7 );\n\n            // Check that the computed relative error matches the required relative error.\n            BOOST_CHECK_CLOSE_FRACTION(\n                        table5_9BurdenAndFaires( i, EXPECTED_RELATIVE_ERROR_COLUMN_INDEX ),\n                        burdenAndFairesNumericalIntegratorTest.relativeError_( 0 ), 1.0e-1 );\n\n            // Check that the computed lower order estimate matches the required lower order\n            // estimate. Note that this is the order that is integrated for the RFK-45 integrator.\n            BOOST_CHECK_CLOSE_FRACTION(\n                        table5_9BurdenAndFaires( i, EXPECTED_LOWER_ORDER_STATE_COLUMN_INDEX ),\n                        burdenAndFairesNumericalIntegratorTest.lowerOrderEstimate_( 0 ),\n                        1.0e-7 );\n\n            // Check that the computed higher order estimate matches the required higher order\n            // estimate.\n            BOOST_CHECK_CLOSE_FRACTION(\n                        table5_9BurdenAndFaires( i, EXPECTED_HIGHER_ORDER_STATE_COLUMN_INDEX ),\n                        burdenAndFairesNumericalIntegratorTest.higherOrderEstimate_( 0 ),\n                        1.0e-7 );\n\n            // Update the step size for the next step based on the computed value in the\n            // integrator.\n            stepSize = integrator.getNextStepSize( );\n        }\n\n        // Store last time and state.\n        const double lastTime = integrator.getCurrentIndependentVariable( );\n        const Eigen::VectorXd lastState = integrator.getCurrentState( );\n\n        // Integrate to final time.\n        const Eigen::VectorXd finalState = integrator.integrateTo( finalTime,\n                                                                   integrator.getNextStepSize( ) );\n\n        // Check that the computed final time matches the required final time.\n        BOOST_CHECK_CLOSE_FRACTION( finalTime,\n                                    integrator.getCurrentIndependentVariable( ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        // Check that computed final state matches the expected final state.\n        BOOST_CHECK_CLOSE_FRACTION(\n                    table5_9BurdenAndFaires( FINAL_ROW, EXPECTED_LOWER_ORDER_STATE_COLUMN_INDEX ),\n                    finalState( 0 ), 1.0e-8 );\n\n        // Check that the final state outputted by the integrator is the same as obtained from the\n        // get-function.\n        BOOST_CHECK_EQUAL( integrator.getCurrentState( ), finalState );\n\n        // Roll back to the previous step. This should be possible since the\n        // performIntegrationStep() function was called above.\n        BOOST_CHECK( integrator.rollbackToPreviousState( ) );\n\n        // Check that the rolled back time is as required. This test should be exact.\n        BOOST_CHECK_EQUAL( lastTime, integrator.getCurrentIndependentVariable( ) );\n\n        // Check that the rolled back state is as required. This test should be exact.\n        BOOST_CHECK_EQUAL( lastState( 0 ), integrator.getCurrentState( )( 0 ) );\n\n        // Check that it is now not possible to roll back.\n        BOOST_CHECK( !integrator.rollbackToPreviousState( ) );\n    }\n}\n\n//! Test Runge-Kutta-Fehlberg 45 integrator using benchmark data from (The MathWorks, 2012).\nBOOST_AUTO_TEST_CASE( testRungeKuttaFehlberg45IntegratorUsingMatlabData )\n{\n    using namespace numerical_integrator_tests;\n\n    // Read in benchmark data (generated using Symbolic Math Toolbox in Matlab\n    // (The MathWorks, 2012)). This data is generated using the RKF54b numerical integrator.\n    const std::string pathToForwardIntegrationOutputFile = input_output::getTudatRootPath( )\n            + \"/Mathematics/NumericalIntegrators/UnitTests\"\n            + \"/matlabOutputRungeKuttaFehlberg45Forward.txt\";\n    const std::string pathToDiscreteEventIntegrationOutputFile = input_output::getTudatRootPath( )\n            + \"/Mathematics/NumericalIntegrators/UnitTests\"\n            + \"/matlabOutputRungeKuttaFehlberg45DiscreteEvent.txt\";\n\n    // Store benchmark data in matrix.\n    const Eigen::MatrixXd matlabForwardIntegrationData =\n            input_output::readMatrixFromFile( pathToForwardIntegrationOutputFile, \",\" );\n    Eigen::MatrixXd matlabBackwardIntegrationData = matlabForwardIntegrationData;\n    flipMatrixRows( matlabBackwardIntegrationData );\n    const Eigen::MatrixXd matlabDiscreteEventIntegrationData =\n            input_output::readMatrixFromFile( pathToDiscreteEventIntegrationOutputFile, \",\" );\n\n    // Set integrator parameters.\n\n    // All of the following parameters are set such that the input data is fully accepted by the\n    // integrator, to determine the steps to be taken.\n    const double zeroMinimumStepSize = std::numeric_limits< double >::epsilon( );\n    const double infiniteMaximumStepSize = std::numeric_limits< double >::infinity( );\n    const double infiniteRelativeErrorTolerance = std::numeric_limits< double >::infinity( );\n    const double infiniteAbsoluteErrorTolerance = std::numeric_limits< double >::infinity( );\n\n    // The following parameters set how the error control mechanism should work.\n    const double relativeErrorTolerance = 1.0e-15;\n    const double absoluteErrorTolerance = 1.0e-15;\n\n    // Case 1: Execute integrateTo() to integrate one step forward in time.\n    {\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg45 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        executeOneIntegrateToStep( matlabForwardIntegrationData, 1.0e-15, integrator );\n    }\n\n    // Case 2: Execute performIntegrationStep() to perform multiple integration steps until final\n    //         time.\n    {\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg45 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        performIntegrationStepToSpecifiedTime( matlabForwardIntegrationData,\n                                               1.0e-15, 1.0e-14, integrator );\n    }\n\n    // Case 3: Execute performIntegrationStep() to perform multiple integration steps until initial\n    //         time (backwards).\n    {\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg45 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabBackwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabBackwardIntegrationData( FIRST_ROW,\n                                                        STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        performIntegrationStepToSpecifiedTime( matlabBackwardIntegrationData,\n                                               1.0e-15, 1.0e-14, integrator );\n    }\n\n    // Case 4: Execute integrateTo() to integrate to specified time in one step.\n    {\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg45 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    relativeErrorTolerance,\n                    absoluteErrorTolerance );\n\n        executeIntegrateToToSpecifiedTime( matlabForwardIntegrationData, 1.0e-12, integrator,\n                                           matlabForwardIntegrationData(\n                                               matlabForwardIntegrationData.rows( ) - 1,\n                                               TIME_COLUMN_INDEX ) );\n    }\n\n    // Case 5: Execute performIntegrationstep() to integrate to specified time in multiple steps,\n    //         including discrete events.\n    {\n        // Declare integrator with all necessary settings.\n        ReinitializableNumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg45 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabDiscreteEventIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabDiscreteEventIntegrationData( FIRST_ROW,\n                                                             STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        performIntegrationStepToSpecifiedTimeWithEvents( matlabDiscreteEventIntegrationData,\n                                                         1.0e-15, 1.0e-12, integrator );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "74753b605354156af90c87ca82f9863747246672", "size": 21446, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/NumericalIntegrators/UnitTests/unitTestRungeKuttaFehlberg45Integrator.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/Mathematics/NumericalIntegrators/UnitTests/unitTestRungeKuttaFehlberg45Integrator.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/Mathematics/NumericalIntegrators/UnitTests/unitTestRungeKuttaFehlberg45Integrator.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": 52.435207824, "max_line_length": 126, "alphanum_fraction": 0.6516366688, "num_tokens": 4544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5062980631222785}}
{"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 <boost/math/ccmath/ldexp.hpp>\n#include \"test_compile_result.hpp\"\n\nvoid compile_and_link_test()\n{\n   check_result<float>(boost::math::ccmath::ldexp(1.0f, 1));\n   check_result<double>(boost::math::ccmath::ldexp(1.0, 1));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::ccmath::ldexp(1.0l, 1));\n#endif\n}\n", "meta": {"hexsha": "5cd272619a61eff147aa400b85c8a5b069f0498b", "size": 582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/ccmath_ldexp_incl_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/compile_test/ccmath_ldexp_incl_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/compile_test/ccmath_ldexp_incl_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": 34.2352941176, "max_line_length": 68, "alphanum_fraction": 0.7422680412, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5062980458803837}}
{"text": "#pragma once\n\n#include <vector>\n#include <type_traits>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n\n#include \"Bounds.hh\"\n#include \"LineSegment/linesegment.hh\"\n#include \"LineSegment/LineSegment2/linesegment2.hh\"\n#include \"../../util/assert.hh\"\n#include \"../../util/log.hh\"\n#include \"../../util/Maybe.hh\"\n\nnamespace bold\n{\n  typedef unsigned int uint;\n\n  template<typename T>\n  class Polygon2\n  {\n  public:\n    typedef Eigen::Matrix<T, 2, 1> Point;\n    typedef std::vector<Point,Eigen::aligned_allocator<Point>> PointVector;\n\n    Polygon2(PointVector const& vertices)\n    : d_vertices(vertices)\n    {\n      if (vertices.size() < 3)\n      {\n        log::error(\"Polygon2::Polygon2\") << \"Cannot create a polygon with number of vertices: \" << vertices.size();\n        throw std::runtime_error(\"A polygon must have at least three vertices\");\n      }\n    }\n\n    Polygon2(Bounds<T,2> bounds)\n    : d_vertices()\n    {\n      d_vertices.push_back(bounds.min());\n      d_vertices.emplace_back(Point(bounds.max().x(), bounds.min().y()));\n      d_vertices.push_back(bounds.max());\n      d_vertices.emplace_back(Point(bounds.min().x(), bounds.max().y()));\n    }\n\n    bool contains(Point const& point)\n    {\n      bool isInside = false;\n      for (unsigned i = 0, j = d_vertices.size() - 1; i < d_vertices.size(); j = i++)\n      {\n        Point const& a = d_vertices[i];\n        Point const& b = d_vertices[j];\n\n        if (((a.y() > point.y()) != (b.y() > point.y()))\n          && (point.x() < (b.x() - a.x()) * (point.y() - a.y()) / (b.y() - a.y()) + a.x()))\n        {\n          isInside = !isInside;\n        }\n      }\n      return isInside;\n    }\n\n    uint vertexCount() const { return d_vertices.size(); }\n\n    Point operator[](uint i)\n    {\n      return d_vertices[i];\n    }\n\n    typename PointVector::iterator begin() { return d_vertices.begin(); }\n    typename PointVector::iterator end() { return d_vertices.end(); }\n    typename PointVector::const_iterator begin() const { return d_vertices.begin(); }\n    typename PointVector::const_iterator end() const { return d_vertices.end(); }\n\n    /// Returns the subsection of the provided that that resides within this polygon.\n    /// Assumes the poly is convex. Returns an empty result if no intersection exists.\n    Maybe<LineSegment2<T>> clipLine(LineSegment2<T> const& line)\n    {\n      bool contains1 = contains(line.p1());\n      bool contains2 = contains(line.p2());\n\n      // Line is completely inside the polygon.\n      // As we're convex, there cannot be any intersection.\n      if (contains1 && contains2)\n        return line;\n\n      PointVector intersectionPoints;\n      for (unsigned i = 0, j = d_vertices.size() - 1; i < d_vertices.size(); j = i++)\n      {\n        Point const& a = d_vertices[i];\n        Point const& b = d_vertices[j];\n        LineSegment2<T> l(a, b);\n        auto result = l.tryIntersect(line);\n        if (result.hasValue())\n        {\n          // Ensure unique members of the list\n          if (intersectionPoints.size() > 0 && intersectionPoints[0] == result.value())\n            continue;\n          if (intersectionPoints.size() > 1 && intersectionPoints[1] == result.value())\n            continue;\n\n          intersectionPoints.push_back(std::move(result.value()));\n\n          // In a convex polygon, we should never see more than two intersections\n          if (intersectionPoints.size() == 2)\n            break;\n        }\n      }\n\n      if (intersectionPoints.size() == 0)\n      {\n        // Line is completely outside and does not intersect with polygon\n        return Maybe<LineSegment2<T>>::empty();\n      }\n\n      if (intersectionPoints.size() == 2)\n      {\n        // Line is completely outside and intersects with polygon\n        return LineSegment2<T>(intersectionPoints[0], intersectionPoints[1]);\n      }\n\n      // One end of the line is outside, and we have a single intersection\n      ASSERT(intersectionPoints.size() == 1);\n      if (contains1)\n        return LineSegment2<T>(line.p1(), intersectionPoints[0]);\n      else\n        return LineSegment2<T>(intersectionPoints[0], line.p2());\n    }\n\n  private:\n    PointVector d_vertices;\n  };\n\n  typedef Polygon2<int> Polygon2i;\n  typedef Polygon2<float> Polygon2f;\n  typedef Polygon2<double> Polygon2d;\n\n  template<typename T>\n  Maybe<Polygon2<T>> make_polygon2(typename Polygon2<T>::PointVector const& vertices)\n  {\n    return vertices.size() < 3\n      ? Maybe<Polygon2<T>>::empty()\n      : Polygon2<T>(vertices);\n  }\n\n  inline Maybe<Polygon2d> make_polygon2d(typename Polygon2d::PointVector const& vertices)\n  {\n    return make_polygon2<double>(vertices);\n  }\n}\n", "meta": {"hexsha": "f034a9a49dcc9f5c65ca213473b35c7e978d1185", "size": 4629, "ext": "hh", "lang": "C++", "max_stars_repo_path": "geometry/Polygon2.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/Polygon2.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/Polygon2.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": 30.6556291391, "max_line_length": 115, "alphanum_fraction": 0.6182760855, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5062980391598022}}
{"text": "/**\n *\t@author Marek Solony (isolony(at)fit.vutbr.cz)\n *\t@date 2014\n *\t@brief Convertor from Bundler output (.out) into graph file for SLAM++\n *\t\tdetails about .out format can be found at: http://www.cs.cornell.edu/~snavely/bundler/bundler-v0.4-manual.html#S6\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <map>\n#include <Eigen/Dense>\n\n#define PI 3.14159265359\n\nusing namespace std;\n\nint counter = 0;\nstd::map<int, int> table;\n\nstatic void Quat_to_AxisAngle(const Eigen::Quaterniond &r_quat, Eigen::Vector3d &r_axis_angle)\n{\n\tdouble f_half_angle = /*(r_quat.w() <= 0)? asin(r_quat.vec().norm()) :*/ acos(r_quat.w()); // 0 .. pi\n\n\tif(f_half_angle < 1e-12)\n\t\tr_axis_angle = Eigen::Vector3d(0, 0, 0); // lim(sin(x) / x) for x->0 equals 1, we're therefore multiplying a null vector by 1\n\telse {\n\t\tdouble f_angle = 2 * ((r_quat.w() <= 0)? f_half_angle - M_PI : f_half_angle);\n\t\tr_axis_angle = r_quat.vec() * (f_angle / sin(f_half_angle));\n\t}\n}\nstatic void AxisAngle_to_Quat(const Eigen::Vector3d &r_axis_angle, Eigen::Quaterniond &r_quat)\n{\n\tdouble f_angle = r_axis_angle.norm();\n\tif(f_angle < 1e-12)\n\t\tr_quat = Eigen::Quaterniond(1, 0, 0, 0); // cos(0) = 1\n\telse {\n\t\t//_ASSERTE(f_angle <= M_PI); // sometimes broken\n\t\tf_angle = fmod(f_angle, M_PI * 2);\n\t\tdouble q = (sin(f_angle * .5) / f_angle);\n\t\tr_quat = Eigen::Quaterniond(cos(f_angle * .5), r_axis_angle(0) * q,\n\t\t\tr_axis_angle(1) * q, r_axis_angle(2) * q);\n\t\tr_quat.normalize();\n\t}\n}\n\n\nint main(int argc, char *argv[]) {\n\tchar edge[64];\n\tint v[2];\n\tfloat pos[3];\n\tint col[3];\n\tfloat rot[4];\n\tfloat conv[21];\n\n\tstd::vector<Eigen::VectorXd> pts3d;\n\tstd::vector<Eigen::VectorXd> cam;\n\tstd::vector<Eigen::VectorXd> observation;\n\n\tif(argc == 3)\n\t{\n\t\tFILE * pFile = fopen (argv[1],\"r+\");\n\n\t\tstd::ofstream wFile;\n\t\twFile.open(argv[2]);\n\n\t\tstd::cout << \"bundler -> graph\" << std::endl;\n\t\t//scan n cams and n points\n\t\tint cams, points;\n\t\tfscanf (pFile, \"%d %d\", &cams, &points);\n\n\t\tstd::cout << \"cams: \" << cams << std::endl;\n\t\tstd::cout << \"points: \" << points << std::endl;\n\t\t//load cams\n\t\tstd::vector<int> camdxs;\n\t\tfor(int a = 0; a < cams; a++) {\n\t\t\tEigen::VectorXd v1(15);\n\n\t\t\tcamdxs.push_back(-1);\n\n\t\t\tfor(int b = 0; b < 15; b++) {\n\t\t\t\tfscanf (pFile, \"%f\", &conv[0] );\n\t\t\t\tv1(b) = conv[0];\n\t\t\t}\n\t\t\tcam.push_back(v1);\n\t\t}\n\t\t//load points and observations\n\t\tfor(int a = 0; a < points; a++) {\n\t\t\tif(a % 100000 == 0)\n\t\t\t\tstd::cout << a << std::endl;\n\t\n\t\t\tEigen::VectorXd v1(4);\n\t\t\tfscanf (pFile, \"%f %f %f\", &pos[0], &pos[1], &pos[2] );\n\t\t\tv1(0) = pos[0];\n\t\t\tv1(1) = pos[1];\n\t\t\tv1(2) = pos[2];\n\t\t\tfscanf (pFile, \"%d %d %d\", &col[0], &col[1], &col[2] );\n\n\t\t\tint refs;\n\t\t\tfscanf (pFile, \"%d\", &refs );\n\n\t\t\tv1(3) = refs;\n\t\t\tpts3d.push_back(v1);\n\n\t\t\tfor(int b = 0; b < refs; b++) {\n\t\t\t\tEigen::VectorXd v2(4);\n\t\t\t\tv2(1) = a;\t//which point?\n\t\t\t\tfscanf (pFile, \"%d %d %f %f\", &v[1], &v[0], &pos[0], &pos[1]);\n\n\t\t\t\tcamdxs.at(v[1]) = v[1];\n\n\t\t\t\tv2(0) = v[1];\n\t\t\t\tv2(2) = pos[0];\n\t\t\t\tv2(3) = pos[1];\n\n\t\t\t\tobservation.push_back(v2);\n\t\t\t}\n\t\t}\n\n\t\tstd::cout << \"cams \" << cam.size() << std::endl;\n\t\tstd::cout << \"pts \" << pts3d.size() << std::endl;\n\t\t//DUMP THE DATASET TO GRAPH FORMAT\n\t\tfor (int a = 0; a < cam.size(); a++) {\n\t\t\t//convert rotation matrix to inverse quaternion\n\t\t\tEigen::Matrix3d rot;\n\t\t\trot << (cam[a])(3), (cam[a])(4), (cam[a])(5), \n\t\t\t\t(cam[a])(6), (cam[a])(7), (cam[a])(8),\n\t\t\t\t(cam[a])(9), (cam[a])(10), (cam[a])(11);\n\t\t\t//invert\n\t\t\trot = rot.inverse().eval();\n\n\t\t\t//to quat\n\t\t\tEigen::Quaternion<double> quat(rot);\n\n\t\t\tEigen::Vector3d t_vec((cam[a])(12), (cam[a])(13), (cam[a])(14));\n\t\t\t//rotate\n\t\t\tEigen::Vector3d c = -(quat * (t_vec));\n\n\t\t\t//store to file\n\t\t\twFile << \"VERTEX_CAM \" << a << \" \" << c(0) << \" \" << c(1) << \" \" << c(2) << \" \" <<\n\t\t\t\tquat.x() << \" \" << quat.y() << \" \" << quat.z() << \" \" << quat.w() << \" \" <<\n\t\t\t\t(cam[a])(0) << \" \" << (cam[a])(0) << \" \" << 0 << \" \" << 0 << \" \" << 0 << std::endl;\n\t\t}\n\n\t\tint obs_count = 0;\n\t\tfor (int a = 0; a < pts3d.size(); a++) {\n\t\t\twFile << \"VERTEX_XYZ \" << a + cam.size() << \" \" << \n\t\t\t\t(pts3d[a])(0) << \" \" << (pts3d[a])(1) << \" \" << (pts3d[a])(2) << std::endl;\n\t\t\t\n\t\t\tfor(int b = 0; b < (pts3d[a])(3); b++) {\n\t\t\t\twFile << \"EDGE_PROJECT_P2MC \" << a + cam.size() << \" \" << (observation[obs_count])(0) << \" \" <<\n\t\t\t\t-(observation[obs_count])(2) << \" \" << -(observation[obs_count])(3) << \" 1 0 1\" << std::endl;\n\n\t\t\t\tcamdxs.at((observation[b])(0)) = (observation[b])(0);\n\t\t\t\t\n\t\t\t\tobs_count ++;\n\t\t\t}\n\t\t}\n\n\t//pFile.close();\n\twFile.close();\n\tstd::cout << \"done \" << cams << std::endl;\n\t} else {\n\t\tstd::cout << \"Convertor from Bundler output (.out) into graph file for SLAM++\" << std::endl <<\n\t\t\t\t\"details about .out format can be found at: http://www.cs.cornell.edu/~snavely/bundler/bundler-v0.4-manual.html#S6\" << std::endl << std::endl;\n\t\tstd::cout << \"Usage: bundler2graph <input .out file> <output .graph filename>\" << std::endl;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "2358bbff971346c0ae2ad00bbada02c4877f8fe8", "size": 4953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scripts/BA_convertors/bundler2graph/bundler2graph.cpp", "max_stars_repo_name": "meitiever/SLAM-BA", "max_stars_repo_head_hexsha": "57ee2af8508300e818feb67f7adbe026eee3ada7", "max_stars_repo_licenses": ["MIT"], "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/BA_convertors/bundler2graph/bundler2graph.cpp", "max_issues_repo_name": "meitiever/SLAM-BA", "max_issues_repo_head_hexsha": "57ee2af8508300e818feb67f7adbe026eee3ada7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/BA_convertors/bundler2graph/bundler2graph.cpp", "max_forks_repo_name": "meitiever/SLAM-BA", "max_forks_repo_head_hexsha": "57ee2af8508300e818feb67f7adbe026eee3ada7", "max_forks_repo_licenses": ["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.3028571429, "max_line_length": 146, "alphanum_fraction": 0.5560266505, "num_tokens": 1828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5062980338991455}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2017 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <geometry_test_common.hpp>\n\n#include <boost/concept_check.hpp>\n\n#include <boost/geometry/srs/srs.hpp>\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n\n#include <test_common/test_point.hpp>\n\n#ifdef HAVE_TTMATH\n#  include <boost/geometry/extensions/contrib/ttmath_stub.hpp>\n#endif\n\ntypedef bg::srs::spheroid<double> stype;\n\ntypedef bg::strategy::andoyer andoyer_formula;\ntypedef bg::strategy::thomas thomas_formula;\ntypedef bg::strategy::vincenty vincenty_formula;\n\ntemplate <typename P>\nbool non_precise_ct()\n{\n    typedef typename bg::coordinate_type<P>::type ct;\n    return boost::is_integral<ct>::value || boost::is_float<ct>::value;\n}\n\ntemplate <typename P1, typename P2, typename FormulaPolicy>\nvoid test_distance(double lon1, double lat1, double lon2, double lat2)\n{\n    typedef typename bg::promote_floating_point\n        <\n            typename bg::select_calculation_type<P1, P2, void>::type\n        >::type calc_t;\n\n    calc_t tolerance = non_precise_ct<P1>() || non_precise_ct<P2>() ?\n                       5.0 : 0.001;\n\n    P1 p1;\n    P2 p2;\n\n    bg::assign_values(p1, lon1, lat1);\n    bg::assign_values(p2, lon2, lat2);\n\n    // Test strategy that implements meridian distance against formula\n    // that implements general distance\n    // That may change in the future but in any case these calls must return\n    // the same result\n\n    calc_t dist_formula = FormulaPolicy::template inverse\n            <\n                double, true, false, false, false, false\n            >::apply(lon1 * bg::math::d2r<double>(),\n                     lat1 * bg::math::d2r<double>(),\n                     lon2 * bg::math::d2r<double>(),\n                     lat2 * bg::math::d2r<double>(),\n                     stype()).distance;\n\n    bg::strategy::distance::geographic<FormulaPolicy, stype> strategy;\n    calc_t dist_strategy = strategy.apply(p1, p2);\n    BOOST_CHECK_CLOSE(dist_formula, dist_strategy, tolerance);\n}\n\ntemplate <typename P1, typename P2, typename FormulaPolicy>\nvoid test_distance_reverse(double lon1, double lat1,\n                           double lon2, double lat2)\n{\n    test_distance<P1, P2, FormulaPolicy>(lon1, lat1, lon2, lat2);\n    test_distance<P1, P2, FormulaPolicy>(lon2, lat2, lon1, lat1);\n}\n\ntemplate <typename P1, typename P2, typename FormulaPolicy>\nvoid test_meridian()\n{\n    test_distance_reverse<P1, P2, FormulaPolicy>(0., 70., 0., 80.);\n    test_distance_reverse<P1, P2, FormulaPolicy>(0, 70, 0., -80.);\n    test_distance_reverse<P1, P2, FormulaPolicy>(0., -70., 0., 80.);\n    test_distance_reverse<P1, P2, FormulaPolicy>(0., -70., 0., -80.);\n\n    test_distance_reverse<P1, P2, FormulaPolicy>(0., 70., 180., 80.);\n    test_distance_reverse<P1, P2, FormulaPolicy>(0., 70., 180., -80.);\n    test_distance_reverse<P1, P2, FormulaPolicy>(0., -70., 180., 80.);\n    test_distance_reverse<P1, P2, FormulaPolicy>(0., -70., 180., -80.);\n\n    test_distance_reverse<P1, P2, FormulaPolicy>(350., 70., 170., 80.);\n    test_distance_reverse<P1, P2, FormulaPolicy>(350., 70., 170., -80.);\n    test_distance_reverse<P1, P2, FormulaPolicy>(350., -70., 170., 80.);\n    test_distance_reverse<P1, P2, FormulaPolicy>(350., -70., 170., -80.);\n}\n\ntemplate <typename P>\nvoid test_all()\n{\n    test_meridian<P, P, andoyer_formula>();\n    test_meridian<P, P, thomas_formula>();\n    test_meridian<P, P, vincenty_formula>();\n}\n\nint test_main(int, char* [])\n{\n    test_all<bg::model::point<double, 2, bg::cs::geographic<bg::degree> > >();\n    test_all<bg::model::point<float, 2, bg::cs::geographic<bg::degree> > >();\n    test_all<bg::model::point<int, 2, bg::cs::geographic<bg::degree> > >();\n\n    return 0;\n}\n", "meta": {"hexsha": "02816672d31bb567a81d4056603b080ddb7a714a", "size": 4059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/geometry/test/strategies/distance.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/geometry/test/strategies/distance.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/geometry/test/strategies/distance.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": 34.3983050847, "max_line_length": 79, "alphanum_fraction": 0.6715939887, "num_tokens": 1139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5062466387903992}}
{"text": "#ifndef AMPAR_GILLESPIE_CLASS_HPP_INCLUDED\n#define AMPAR_GILLESPIE_CLASS_HPP_INCLUDED\n\n#include <iostream>\n#include <cmath>\n#include <vector>\n#include <ctime>\n\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/generator_iterator.hpp>\n#include <boost/random/linear_congruential.hpp>\n\n#include \"stl_vector_operation_functions.hpp\"\n\nclass ampar_gillespie_class\n{\n   private:\n      unsigned int seed;\n      boost::minstd_rand rng;   //Boost random number generator\n      boost::uniform_real<double> uni_dist;   //Uniform random number distribution which produces values b/w 0 and 1 (0 inclusive, 1 exlusive).\n      boost::variate_generator<boost::minstd_rand&, boost::uniform_real< double> > uni_rand;// variate generator\n      //--------------\n      double kf1 = 4.59E06;    //M^-1 S^-1\n      double kb1 = 4.26E03;    //S^-1\n      double kf2 = 28.4E06;    //M^-1 * S^-1\n      double kb2 = 3.26E03;    //S^-1\n      double kf3 = 1.27E06;    //M^-1 S^-1\n      double kb3 = 45.7;       //S^-1\n      double a0 = 4.24E03;     //S^-1\n      double b0 = 900.0;       //S^-1\n      double a1 = 2.89E03;     //S^-1\n      double b1 = 39.2;        //S^-1\n      double a2 = 172.0;       //S^-1\n      double b2 = 0.727;       //S^-1\n      double a3 = 17.7;        //S^-1\n      double b3 = 4.0;         //S^-1\n      double a4 = 16.8;        //S^-1\n      double b4 = 190.4;       //S^-1\n      double Volume = 1.0;\n   public:\n      const double avagadro = 6.022e+23;\n      const int Nstates = 8;\n      const int Nreactions = 16;\n      double r1,r2;\n      //Construct vectors\n      std::vector<int> X;      // A vector to hold the initial number of the receptors in each states [Glu,C0,C1,C2,C3,C4,C5,Open]\n      std::vector<double> C;  //A vector to hold the Cmew values\n      std::vector<double> H;  //A vector to hold the Hmew values\n      //Class constructorsampar_gillespie_class(unsigned int seed_ = std::time(0), std::vector<int> X_):   seed(seed_),\n       ampar_gillespie_class(std::vector<int> X_, unsigned int seed_=std::time(0)):   seed(seed_),\n                                                                        uni_dist(boost::uniform_real<double>(0,1)),\n                                                                        uni_rand(boost::variate_generator<boost::minstd_rand&, boost::uniform_real<double> >(rng, uni_dist)),\n                                                                        X(std::move(X_))\n      {\n         rng.seed(seed);\n         C = {kf1*Volume,kb1,kf2*Volume,kb2,a1,b1,kf3*Volume,kb3,a2,b2,a4,b4,a0,b0,b3,a3};\n         H = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n      }\n      void updateX (const int rx_id);\n      void updateH (void);\n};\n\n/* Function update H_mew vector with the current number of molecules in each state from the state vector X */\nvoid ampar_gillespie_class::updateH(void)\n{\n   //Genrate two random numbers from the distribution by means of STL generator interface.\n   r1 = uni_rand();\n   r2 = uni_rand();\n\n   H[0] = X[0] * X[1];\n   H[1] = X[2];\n   H[2] = X[2] * X[0];\n   H[3] = X[3];\n   H[4] = X[2];\n   H[5] = X[4];\n   H[6] = X[4] * X[0];\n   H[7] = X[5];\n   H[8] = X[3];\n   H[9] = X[5];\n   H[10] = X[5];\n   H[11] = X[6];\n   H[12] = X[3];\n   H[13] = X[7];\n   H[14] = X[6];\n   H[15] = X[7];\n}\n//Function update the state vector X for a given reaction rx_id\nvoid ampar_gillespie_class::updateX(const int rx_id)\n{\n   //std::cout << \"Reaction \" << rx_id << \" X in \" << X;\n   switch(rx_id)\n   {\n      case 0:\n      {\n         if((X[0] > 0) && (X[1] > 0)){\n            --X[0]; --X[1];\n            ++X[2];\n         }\n         break;\n      }\n      case 1:\n      {\n         if(X[2] > 0){\n         --X[2];\n         ++X[0]; ++X[1];\n         }\n         break;\n      }\n      case 2:\n      {\n         if((X[2] > 0) && (X[0] > 0)){\n         --X[2]; --X[0];\n         ++X[3];\n         }\n         break;\n      }\n      case 3:\n      {\n         if(X[3] > 0){\n         --X[3];\n         ++X[2]; ++X[0];\n         }\n         break;\n      }\n      case 4:\n      {\n         if(X[2] > 0){\n         --X[2];\n         ++X[4];\n         }\n         break;\n      }\n      case 5:\n      {\n         if(X[4] > 0){\n         --X[4];\n         ++X[2];\n         }\n         break;\n      }\n      case 6:\n      {\n         if((X[4] > 0) && (X[0] > 0)){\n         --X[4];\n         --X[0];\n         ++X[5];\n         }\n         break;\n      }\n      case 7:\n      {\n         if(X[5] > 0){\n         --X[5];\n         ++X[4];\n         ++X[0];\n         }\n         break;\n      }\n      case 8:\n      {\n         if(X[3] > 0){\n         --X[3];\n         ++X[5];\n         }\n         break;\n      }\n      case 9:\n      {\n         if(X[5] > 0){\n         --X[5];\n         ++X[3];\n         }\n         break;\n      }\n      case 10:\n      {\n         if(X[5] > 0){\n         --X[5];\n         ++X[6];\n         }\n         break;\n      }\n      case 11:\n      {\n         if(X[6] > 0){\n         --X[6];\n         ++X[5];\n         }\n         break;\n      }\n      case 12:\n      {\n         if(X[3] > 0){\n         --X[3];\n         ++X[7];\n         }\n         break;\n      }\n      case 13:\n      {\n         if(X[7] > 0){\n         --X[7];\n         ++X[3];\n         }\n         break;\n      }\n      case 14:\n      {\n         if(X[6] > 0){\n         --X[6];\n         ++X[7];\n         }\n         break;\n      }\n      case 15:\n      {\n         if(X[7] > 0){\n         --X[7];\n         ++X[6];\n         }\n         break;\n      }\n   }\n   for(size_t i=0; i<X.size();++i){\n      if(X[i] < 0){\n         X[i] = 0;\n      }\n   }\n}\n\n#endif // AMPAR_GILLESPIE_CLASS_HPP_INCLUDED\n", "meta": {"hexsha": "e447a0140f6e46c114fae8948fb676b5ed4a0d32", "size": 5574, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/old/src/old/ampar_gillespie_class.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/ampar_gillespie_class.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/ampar_gillespie_class.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": 23.9227467811, "max_line_length": 173, "alphanum_fraction": 0.4199856476, "num_tokens": 1816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5062466345558019}}
{"text": "#include \"geomutils.h\"\n\n#include <stdint.h>\n#include <algorithm>\n#include <cassert>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\nstd::vector<int> sortEdges(const std::vector<std::pair<int, int>> &edges, const std::vector<double> &weights) {\n    std::vector<int> order(edges.size());\n    for(int i = 0;i < order.size();i ++) {\n        order[i] = i;\n    }\n\n    std::sort(order.begin(),order.end(), [weights](int i, int j){\n        return (weights[i] < weights[j]);\n    });\n    return order;\n}\n\nvoid findAngle(const Point &p1, const Point &p2, Transformation &t) {\n    Point vec(p2.x - p1.x,p2.y - p1.y);\n    double n = len(vec);\n    vec.x /= n;\n    vec.y /= n;\n    t.cos = vec.x;\n    t.sin = std::sqrt(1 - t.cos * t.cos);\n    if(vec.y >= 0) {\n        t.sin = -t.sin;\n    }\n}\n\nvoid computeConvexHull(Polygon &pts, Polygon &chull) {\n    chull.clear();\n    if(pts.size() == 1) {\n        chull.push_back(pts[0]);\n        chull.push_back(pts[0]);\n        return;\n    } else if(pts.size() == 2) {\n        chull.push_back(pts[0]);\n        chull.push_back(pts[1]);\n        chull.push_back(pts[0]);\n        return;\n    }\n\n    typedef boost::tuple<double, double> point;\n    typedef boost::geometry::model::multi_point<point> mpoints;\n    typedef boost::geometry::model::polygon<point> polygon;\n\n    mpoints mpts;\n\n    for(int i = 0;i < pts.size();i ++) {\n        boost::geometry::append(mpts,point(pts[i].x,pts[i].y));\n    }\n    polygon hull;\n\n    // Polygon is closed\n    boost::geometry::convex_hull(mpts, hull);\n    for(auto pt : hull.outer()) {\n        chull.push_back(Point(pt.get<0>(), pt.get<1>()));\n    }\n}\n", "meta": {"hexsha": "e5af58557c15453d4de8a4602bfe4e9b2034c9b9", "size": 1756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/geomutils.cpp", "max_stars_repo_name": "harishd10/TopoMap", "max_stars_repo_head_hexsha": "a6b19acfbafefedf00ddc6a4766e992cfaabf77b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T10:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T03:06:43.000Z", "max_issues_repo_path": "cpp/geomutils.cpp", "max_issues_repo_name": "harishd10/TopoMap", "max_issues_repo_head_hexsha": "a6b19acfbafefedf00ddc6a4766e992cfaabf77b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-02T12:19:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-04T09:15:08.000Z", "max_forks_repo_path": "cpp/geomutils.cpp", "max_forks_repo_name": "harishd10/TopoMap", "max_forks_repo_head_hexsha": "a6b19acfbafefedf00ddc6a4766e992cfaabf77b", "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.2089552239, "max_line_length": 111, "alphanum_fraction": 0.5951025057, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5062066314818606}}
{"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_IEEE_HPP_INCLUDED\n#define BOOST_SIMD_IEEE_HPP_INCLUDED\n\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-functions\n    @defgroup group-ieee Ieee functions\n\n   These functions provide scalar and SIMD algorithms for inspecting, generating or\n   decomposing IEEE 754 floating point numbers.\n\n   Operations such as exponent and mantissa\n   extraction, floating point modulo, IEEE bit patterns manipulation and\n   magnitude comparison are provided.\n\n<center>\n |                      |                  |                  |                 |                 |\n |:--------------------:|:----------------:|:----------------:|:---------------:|:---------------:|\n | @ref bitfloating     | @ref bitinteger  | @ref bitofsign   | @ref copysign   | @ref eps        |\n | @ref exponentbits    | @ref exponent    | @ref fpclassify  | @ref frac       | @ref frexp      |\n | @ref ifrexp          | @ref ilogb       | @ref ldexp       | @ref mantissa   | @ref maxmag     |\n | @ref maxnum          | @ref maxnummag   | @ref minmag      | @ref minnum     | @ref minnummag  |\n | @ref modf            | @ref negate      | @ref negatenz    | @ref nextafter  | @ref next       |\n | @ref nextpow2        | @ref predecessor | @ref prev        | @ref safe_max   | @ref safe_min   |\n | @ref saturate        | @ref sign        | @ref signnz      | @ref successor  | @ref ulpdist    |\n | @ref ulp             |                  |                  |                 |                 |\n</center>\n  **/\n\n} }\n\n#include <boost/simd/function/bitfloating.hpp>\n#include <boost/simd/function/bitinteger.hpp>\n#include <boost/simd/function/bitofsign.hpp>\n#include <boost/simd/function/copysign.hpp>\n#include <boost/simd/function/eps.hpp>\n#include <boost/simd/function/exponentbits.hpp>\n#include <boost/simd/function/exponent.hpp>\n#include <boost/simd/function/fpclassify.hpp>\n#include <boost/simd/function/frac.hpp>\n#include <boost/simd/function/frexp.hpp>\n#include <boost/simd/function/ifrexp.hpp>\n#include <boost/simd/function/ilogb.hpp>\n#include <boost/simd/function/ldexp.hpp>\n#include <boost/simd/function/mantissa.hpp>\n#include <boost/simd/function/maxmag.hpp>\n#include <boost/simd/function/maxnum.hpp>\n#include <boost/simd/function/maxnummag.hpp>\n#include <boost/simd/function/minmag.hpp>\n#include <boost/simd/function/minnum.hpp>\n#include <boost/simd/function/minnummag.hpp>\n#include <boost/simd/function/modf.hpp>\n#include <boost/simd/function/negate.hpp>\n#include <boost/simd/function/negatenz.hpp>\n#include <boost/simd/function/nextafter.hpp>\n#include <boost/simd/function/next.hpp>\n#include <boost/simd/function/nextpow2.hpp>\n#include <boost/simd/function/predecessor.hpp>\n#include <boost/simd/function/prev.hpp>\n#include <boost/simd/function/safe_max.hpp>\n#include <boost/simd/function/safe_min.hpp>\n#include <boost/simd/function/saturate.hpp>\n#include <boost/simd/function/sbits.hpp>\n#include <boost/simd/function/sign.hpp>\n#include <boost/simd/function/signnz.hpp>\n#include <boost/simd/function/splat.hpp>\n#include <boost/simd/function/successor.hpp>\n#include <boost/simd/function/ulpdist.hpp>\n#include <boost/simd/function/ulp.hpp>\n\n#endif\n", "meta": {"hexsha": "84fa6d3b32cb9565052bcac9c5882a572fcdc1f7", "size": 3539, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/ieee.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/ieee.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/ieee.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": 42.130952381, "max_line_length": 100, "alphanum_fraction": 0.6165583498, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5062066265904025}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\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// Point Example - showing different type of points\n\n#include <iostream>\n\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <boost/geometry/geometries/adapted/boost_array.hpp>\n#include <boost/geometry/geometries/adapted/boost_polygon/point.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\nBOOST_GEOMETRY_REGISTER_BOOST_ARRAY_CS(cs::cartesian)\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\n\nint main()\n{\n    using namespace boost::geometry;\n\n    // Boost.Geometry contains several point types:\n    // 1: its own generic type\n    model::point<double, 2, cs::cartesian> pt1;\n\n    // 2: its own type targetted to Cartesian (x,y) coordinates\n    model::d2::point_xy<double> pt2;\n\n    // 3: it supports Boost tuple's\n    boost::tuple<double, double> pt3;\n\n    // 4: it supports normal arrays\n    double pt4[2];\n\n    // 5: it supports arrays-as-points from Boost.Array\n    boost::array<double, 2> pt5;\n\n    // 6: it supports points from Boost.Polygon\n    boost::polygon::point_data<double> pt6;\n\n    // 7: in the past there was a typedef point_2d\n    //    But users are now supposted to do that themselves:\n    typedef model::d2::point_xy<double> point_2d;\n    point_2d pt7;\n\n\n    // 7: there are more variants, and you can create your own.\n    //    (see therefore the custom_point example)\n\n    // All these types are handled the same way. We show here\n    // assigning them and calculating distances.\n    assign_values(pt1, 1, 1);\n    assign_values(pt2, 2, 2);\n    assign_values(pt3, 3, 3);\n    assign_values(pt4, 4, 4);\n    assign_values(pt5, 5, 5);\n    assign_values(pt6, 6, 6);\n    assign_values(pt7, 7, 7);\n\n\n    double d1 = distance(pt1, pt2);\n    double d2 = distance(pt3, pt4);\n    double d3 = distance(pt5, pt6);\n    std::cout << \"Distances: \" \n        << d1 << \" and \" << d2 << \" and \" << d3 << std::endl;\n\n    // (in case you didn't note, distances can be calculated\n    //  from points with different point-types)\n\n\n    // Several ways of construction and setting point values\n    // 1: default, empty constructor, causing no initialization at all\n    model::d2::point_xy<double> p1;\n\n    // 2: as shown above, assign_values\n    model::d2::point_xy<double> p2;\n    assign_values(p2, 1, 1);\n\n    // 3: using \"set\" function\n    //    set uses the concepts behind, such that it can be applied for\n    //    every point-type (like assign_values)\n    model::d2::point_xy<double> p3;\n    set<0>(p3, 1);\n    set<1>(p3, 1);\n    // set<2>(p3, 1); //will result in compile-error\n\n\n    // 3: for any point type, and other geometry objects:\n    //    there is the \"make\" object generator\n    //    (this one requires to specify the point-type).\n    model::d2::point_xy<double> p4 = make<model::d2::point_xy<double> >(1,1);\n\n\n    // 5: for the d2::point_xy<...> type only: constructor with two values\n    model::d2::point_xy<double> p5(1,1);\n\n    // 6: for boost tuples you can of course use make_tuple\n\n\n    // Some ways of getting point values\n\n    // 1: using the \"get\" function following the concepts behind\n    std::cout << get<0>(p2) << \",\" << get<1>(p2) << std::endl;\n\n    // 2: for point_xy only\n    std::cout << p2.x() << \",\" << p2.y() << std::endl;\n\n    // 3: using boost-tuples you of course can boost-tuple-methods\n    std::cout << pt3.get<0>() << \",\" << pt3.get<1>() << std::endl;\n\n    // 4: Boost.Geometry supports various output formats, e.g. DSV\n    //    (delimiter separated values)\n    std::cout << dsv(pt3) << std::endl;\n\n    // There are 3-dimensional points too\n    model::point<double, 3, cs::cartesian> d3a, d3b;\n    assign_values(d3a, 1, 2, 3);\n    assign_values(d3b, 4, 5, 6);\n    d3 = distance(d3a, d3b);\n\n\n\n    // Other examples show other types of points, geometries and more algorithms\n\n    return 0;\n}\n", "meta": {"hexsha": "4feee82c6e1eebacc0827eb312b4390a54928089", "size": 4339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/geometry/example/01_point_example.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/geometry/example/01_point_example.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "boost/libs/geometry/example/01_point_example.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 31.9044117647, "max_line_length": 80, "alphanum_fraction": 0.6632864715, "num_tokens": 1278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5062066265904024}}
{"text": "#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <occutils/Line.hxx>\n#include <occutils/Direction.hxx>\n#include <occutils/PrintOCC.hxx>\n#include <occutils/Equality.hxx>\n\n\nBOOST_AUTO_TEST_CASE( LineParallel2d )\n{\n    // A line should be parallel to itself\n    gp_Lin2d linX(gp_Pnt2d(0, 0), OCCUtils::Direction::X2d());\n    BOOST_CHECK(OCCUtils::Line::IsParallel(linX, linX));\n\n    // A line should be parallel to its reverse line\n    gp_Lin2d linMinusX = linX.Reversed();\n    BOOST_CHECK(OCCUtils::Line::IsParallel(linX, linMinusX));\n    BOOST_CHECK(OCCUtils::Line::IsParallel(linMinusX, linX));\n\n    // Two perpendicular lines should not be parallel\n    gp_Lin2d linY(gp_Pnt2d(0, 0), OCCUtils::Direction::Y2d());\n    BOOST_CHECK(!OCCUtils::Line::IsParallel(linX, linY));\n    BOOST_CHECK(!OCCUtils::Line::IsParallel(linY, linX));\n    BOOST_CHECK(!OCCUtils::Line::IsParallel(linMinusX, linY));\n    BOOST_CHECK(!OCCUtils::Line::IsParallel(linY, linMinusX));\n}\n\nBOOST_AUTO_TEST_CASE( LineIntersection2D )\n{\n    // Intersect between a line and itself has infinite points\n    gp_Lin2d lin1(gp_Pnt2d(0, 0), OCCUtils::Direction::X2d());\n    auto result = OCCUtils::Line::Intersection(lin1, lin1);\n    BOOST_CHECK(!result.has_value());\n\n    // Two intersecting lines should have an intersection point\n    gp_Lin2d lin2(gp_Pnt2d(0, -1), OCCUtils::Direction::Y2d());\n    result = OCCUtils::Line::Intersection(lin1, lin2);\n    BOOST_CHECK(result.has_value());\n    BOOST_CHECK_EQUAL(result.value(), gp_Pnt2d(0, 0));\n\n    // Two more intersecting lines that do not intersect @ origin\n    gp_Lin2d lin3(gp_Pnt2d(0, 1), OCCUtils::Direction::X2d());\n    result = OCCUtils::Line::Intersection(lin2, lin3);\n    BOOST_CHECK(result.has_value());\n    BOOST_CHECK_EQUAL(result.value(), gp_Pnt2d(0, 1));\n\n    // ... same as last test but argument order inverted (same result)\n    result = OCCUtils::Line::Intersection(lin3, lin2);\n    BOOST_CHECK(result.has_value());\n    BOOST_CHECK_EQUAL(result.value(), gp_Pnt2d(0, 1));\n}", "meta": {"hexsha": "3f29e4debf7a065878c1e738b28193e376c06d2f", "size": 2020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestLine.cpp", "max_stars_repo_name": "ulikoehler/OCCUtil", "max_stars_repo_head_hexsha": "39d72ecf35dd3840ed23efac0b335bd4c9d16dad", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2019-08-12T14:03:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T17:38:47.000Z", "max_issues_repo_path": "tests/TestLine.cpp", "max_issues_repo_name": "ulikoehler/OCCUtil", "max_issues_repo_head_hexsha": "39d72ecf35dd3840ed23efac0b335bd4c9d16dad", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-09T02:28:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T02:28:10.000Z", "max_forks_repo_path": "tests/TestLine.cpp", "max_forks_repo_name": "ulikoehler/OCCUtil", "max_forks_repo_head_hexsha": "39d72ecf35dd3840ed23efac0b335bd4c9d16dad", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-07-28T15:57:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T01:52:34.000Z", "avg_line_length": 39.6078431373, "max_line_length": 70, "alphanum_fraction": 0.7128712871, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5062066265904024}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2021 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#define BOOST_GEOMETRY_NO_ROBUSTNESS\n\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#include <geometry_test_common.hpp>\n#include <algorithms/overlay/multi_overlay_cases.hpp>\n\n#include <boost/geometry/algorithms/correct.hpp>\n#include <boost/geometry/algorithms/union.hpp>\n#include <boost/geometry/io/wkt/wkt.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n\n#include <algorithms/overlay/multi_overlay_cases.hpp>\n\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/multi_polygon.hpp>\n\n#include <boost/geometry/util/rational.hpp>\n\n#include <set>\n\nenum class exclude { all, rectangular, diagonal, hard, fp };\n\ntemplate <typename Geometry, typename Expected>\nvoid test_one(std::string const& case_id,\n              std::string const& wkt1, std::string const& wkt2,\n              bool debug,\n              Expected const& expected_area,\n              Expected const& expected_max = -1)\n{\n    using coor_t = typename bg::coordinate_type<Geometry>::type;\n    Geometry g1, g2, clip;\n\n    bg::read_wkt(wkt1, g1);\n    bg::read_wkt(wkt2, g2);\n\n    bg::correct(g1);\n    bg::correct(g2);\n\n    bg::union_(g1, g2, clip);\n\n    auto const area = bg::area(clip);\n    if (debug)\n    {\n      std::cout << \"AREA: \" << std::setprecision(64) << area\n                << \" expected \" << expected_area\n                << \" types coordinate \" << string_from_type<coor_t>::name()\n                << \" area \" << typeid(decltype(area)).name()\n                << \" expected \" << typeid(Expected).name()\n                << \" size \" << sizeof(coor_t)\n                << std::endl;\n    }\n\n    // Check areas, they always have to be specified in integer for this test\n    // and therefore the checking (including a tolerance) is different\n    bool const ok = expected_max == -1\n                    ? bg::math::equals(area, expected_area)\n                    : bg::math::larger_or_equals(area, expected_area)\n                      && bg::math::smaller_or_equals(area, expected_max);\n    BOOST_CHECK_MESSAGE(ok,\n            \"union: \" << case_id\n            << \" area: expected: \" << expected_area\n            << \" detected: \" << area\n            << \" type: \" << (string_from_type<coor_t>::name())\n            << \" (\" << (typeid(coor_t).name()) << \")\");\n}\n\ntemplate <typename Point>\nvoid test_areal(std::set<exclude> const& exclude = {}, bool debug = false)\n{\n    using polygon = bg::model::polygon<Point>;\n    using multi_polygon = bg::model::multi_polygon<polygon>;\n\n    // Intended tests: only 3:\n    // - simple case having only horizontal/vertical lines (\"rectangular\")\n    // - simple case on integer grid but also having diagonals (\"diagonal\")\n    // - case going wrong for <float> (\"hard\")\n\n    if (exclude.count(exclude::rectangular)\n        + exclude.count(exclude::all) == 0)\n    {\n        test_one<multi_polygon>(\"case_multi_rectangular\",\n            case_multi_rectangular[0], case_multi_rectangular[1], debug, 33125);\n    }\n    if (exclude.count(exclude::diagonal)\n        + exclude.count(exclude::all) == 0)\n    {\n        test_one<multi_polygon>(\"case_multi_diagonal\",\n            case_multi_diagonal[0], case_multi_diagonal[1], debug, 5350);\n    }\n    if (exclude.count(exclude::hard)\n        + exclude.count(exclude::fp)\n        + exclude.count(exclude::all) == 0)\n    {\n        test_one<multi_polygon>(\"case_multi_hard\",\n            case_multi_hard[0], case_multi_hard[1], debug, 21, 23);\n    }\n}\n\nint test_main(int, char* [])\n{\n    namespace bm = boost::multiprecision;\n\n    using bg::model::d2::point_xy;\n\n#if ! defined(BOOST_GEOMETRY_TEST_ONLY_ONE_TYPE)\n    // Standard floating point types\n    test_areal<point_xy<float>>({exclude::hard});\n    test_areal<point_xy<double>>({});\n    test_areal<point_xy<long double>>({});\n\n    // Standard integer types\n    test_areal<point_xy<std::int16_t>>({exclude::fp});\n    test_areal<point_xy<std::int32_t>>({exclude::fp});\n#endif\n    test_areal<point_xy<std::int64_t>>({exclude::fp});\n\n    // Boost multi precision (integer)\n    test_areal<point_xy<bm::int128_t>>({exclude::fp});\n#if ! defined(BOOST_GEOMETRY_TEST_ONLY_ONE_TYPE)\n    test_areal<point_xy<bm::checked_int128_t>>({exclude::fp});\n#endif\n\n    // Boost multi precision (floating point)\n#if ! defined(BOOST_GEOMETRY_TEST_ONLY_ONE_TYPE)\n    test_areal<point_xy<bm::number<bm::cpp_bin_float<5>>>>();\n    test_areal<point_xy<bm::number<bm::cpp_bin_float<10>>>>();\n    test_areal<point_xy<bm::number<bm::cpp_bin_float<50>>>>();\n#endif\n    test_areal<point_xy<bm::number<bm::cpp_bin_float<100>>>>();\n\n    test_areal<point_xy<bm::number<bm::cpp_dec_float<50>>>>({});\n\n    // Boost multi precision (rational)\n    test_areal<point_xy<bm::cpp_rational>>({exclude::fp});\n#if ! defined(BOOST_GEOMETRY_TEST_ONLY_ONE_TYPE)\n    test_areal<point_xy<bm::checked_cpp_rational>>({exclude::fp});\n#endif\n\n    // Boost multi precision float128 wrapper, is currently NOT supported\n    // and it is limited to certain compilers anyway\n    // test_areal<point_xy<bm::float128>>();\n\n    // Boost rational (tests compilation)\n    // (the rectangular case is correct; other input might give wrong results)\n    // The int16 version throws a <zero denominator> exception\n#if ! defined(BOOST_GEOMETRY_TEST_ONLY_ONE_TYPE)\n    test_areal<point_xy<boost::rational<std::int16_t>>>({exclude::all});\n    test_areal<point_xy<boost::rational<std::int32_t>>>({exclude::fp});\n#endif\n    test_areal<point_xy<boost::rational<std::int64_t>>>({exclude::fp});\n\n    return 0;\n}\n", "meta": {"hexsha": "bd3bb6e89622792d5384486d2b65dc794499c268", "size": 5834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/geometry/test/algorithms/set_operations/union/union_other_types.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/geometry/test/algorithms/set_operations/union/union_other_types.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "console/src/boost_1_78_0/libs/geometry/test/algorithms/set_operations/union/union_other_types.cpp", "max_forks_repo_name": "vany152/FilesHash", "max_forks_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 35.3575757576, "max_line_length": 80, "alphanum_fraction": 0.6594103531, "num_tokens": 1506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.506206621698944}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_VARIANCE_HPP\n#define STAN_MATH_PRIM_MAT_FUN_VARIANCE_HPP\n\n#include <stan/math/prim/arr/err/check_nonzero_size.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/fun/mean.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Returns the sample variance (divide by length - 1) of the\n * coefficients in the specified standard vector.\n * @param v Specified vector.\n * @return Sample variance of vector.\n * @throws std::domain_error if the size of the vector is less\n * than 1.\n */\ntemplate <typename T>\ninline return_type_t<T> variance(const std::vector<T>& v) {\n  check_nonzero_size(\"variance\", \"v\", v);\n  if (v.size() == 1) {\n    return 0.0;\n  }\n  T v_mean(mean(v));\n  T sum_sq_diff(0);\n  for (size_t i = 0; i < v.size(); ++i) {\n    T diff = v[i] - v_mean;\n    sum_sq_diff += diff * diff;\n  }\n  return sum_sq_diff / (v.size() - 1);\n}\n\n/**\n * Returns the sample variance (divide by length - 1) of the\n * coefficients in the specified column vector.\n * @param m Specified vector.\n * @return Sample variance of vector.\n */\ntemplate <typename T, int R, int C>\ninline return_type_t<T> variance(const Eigen::Matrix<T, R, C>& m) {\n  check_nonzero_size(\"variance\", \"m\", m);\n\n  if (m.size() == 1) {\n    return 0.0;\n  }\n  return_type_t<T> mn(mean(m));\n  return_type_t<T> sum_sq_diff(0);\n  for (int i = 0; i < m.size(); ++i) {\n    return_type_t<T> diff = m(i) - mn;\n    sum_sq_diff += diff * diff;\n  }\n  return sum_sq_diff / (m.size() - 1);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "28ca0bf972350045a60742726357ce810164c098", "size": 1593, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/mat/fun/variance.hpp", "max_stars_repo_name": "PhilClemson/math", "max_stars_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "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": "stan/math/prim/mat/fun/variance.hpp", "max_issues_repo_name": "PhilClemson/math", "max_issues_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/mat/fun/variance.hpp", "max_forks_repo_name": "PhilClemson/math", "max_forks_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "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.1147540984, "max_line_length": 67, "alphanum_fraction": 0.6641556811, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5062066168074858}}
{"text": "//==================================================================================================\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#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/plus.hpp>\n#include <boost/simd/function/splat.hpp>\n#include <boost/simd/pack.hpp>\n\n//! [scalar-dot]\ntemplate <typename Value>\nValue dot(Value* first1, Value* last1, Value* first2)\n{\n  Value v(0);\n\n  for (; first1 < last1; ++first1, ++first2) {\n    v += (*first1) * (*first2);\n  }\n\n  return v;\n}\n//! [scalar-dot]\n", "meta": {"hexsha": "4039614e759a0733296e4a6e2d99a6f520058121", "size": 770, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/dot.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "doc/examples/dot.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/dot.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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": 27.5, "max_line_length": 100, "alphanum_fraction": 0.5051948052, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5062066168074858}}
{"text": "#pragma once\n#include <vector>\n#include <random>\n#include <Eigen/Core>\n\nnamespace mdk {\n    /**\n     * A random number generator. We use two versions: a legacy version taken\n     * from Fortran, and a modern version. Aside from sampling from [0, 1], we\n     * add sampling from [a, b], N(0, 1), N(mu, sigma^2) or points on S^2.\n     */\n    class Random {\n#ifdef LEGACY_MODE\n    private:\n        static constexpr int\n            im1 = 2147483563,\n            im2 = 2147483399,\n            imm1 = im1-1,\n            ia1 = 40014,\n            ia2 = 40692,\n            iq1 = 53668,\n            iq2 = 52774,\n            ir1 = 12211,\n            ir2 = 3791,\n            ntab = 32,\n            ndiv = 1+imm1/ntab;\n\n        static constexpr double\n            eps = 1.2e-7,\n            rnmx = 1.-eps,\n            am = (float) 1.0/im1;\n\n        int iy = 0, idum = -448, idum2 = 123456789;\n        int iv[ntab];\n    public:\n        Random(int seed) {\n            idum = -seed;\n            for (auto& x: iv) x = 0;\n        }\n        inline double uniform() {\n            int k, j;\n            if (idum <= 0) {\n                idum2 = idum = std::max(-idum, 1);\n                for (j = ntab + 7; j >= 0; --j) {\n                    k = idum / iq1;\n                    idum = ia1 * (idum - k * iq1) - k * ir1;\n                    if (idum < 0) idum += im1;\n                    if (j < ntab) iv[j] = idum;\n                }\n                iy = iv[0];\n            }\n\n            k = idum / iq1;\n            idum = ia1 * (idum - k * iq1) - k * ir1;\n            if (idum < 0) idum += im1;\n\n            k = idum2 / iq2;\n            idum2 = ia2 * (idum2 - k * iq2) - k * ir2;\n            if (idum2 < 0) idum2 += im2;\n\n            j = iy / ndiv;\n            iy = iv[j] - idum2;\n            iv[j] = idum;\n            if (iy < 1) iy += imm1;\n\n            return std::min(am * iy, rnmx);\n        }\n#else\n    private:\n        uint64_t state;\n        Random() = default;\n\n    public:\n        Random(int seed) {\n            assert (seed > 0);\n            state = seed;\n\n            // Shuffle the state a bit\n            for (int i = 0; i < 100; ++i) uniform();\n        }\n\n        inline double uniform() {\n            static const double inv = 1.0 / (double) (1ull << 32);\n            uint64_t result = state * 0xd989bcacc137dcd5ull;\n            state ^= state >> 11;\n            state ^= state << 31;\n            state ^= state >> 18;\n            double res = (uint32_t) (result >> 32ull);\n            return res * inv;\n        }\n\n        /* This function is used to create a new random object\n           that won't generate similar values.\n           Uses splitmix64 to create new state */\n        Random getNewRandom() {\n            uint64_t result = state;\n            result = (result ^ (result >> 30)) * 0xBF58476D1CE4E5B9;\n            result = (result ^ (result >> 27)) * 0x94D049BB133111EB;\n            result = result ^ (result >> 31);\n            Random rng;\n            rng.state = result;\n            return rng;\n        }\n\n#endif\n        Random(Random const& oth) = default;\n\n        inline double uniform(double a, double b) {\n            return a + (b - a) * uniform();\n        }\n\n        inline double normal() {\n            double r1 = uniform();\n            double r2 = uniform();\n            return sqrt(-2.0  * log(r1)) * cos(2.0 * M_PI * r2);\n        }\n\n        inline std::pair<double, double> two_normals() {\n            double r1 = uniform();\n            double r2 = uniform();\n            double r = sqrt(-2.0  * log(r1));\n            double ang = 2.0 * M_PI * r2;\n            return {r * cos(ang), r * sin(ang)};\n        }\n\n        inline double normal(double mu, double sigma) {\n            return mu + sigma * normal();\n        }\n\n        inline Eigen::Vector3d sphere() {\n            Eigen::Vector3d r { normal(), normal(), normal() };\n            return r.normalized();\n        }\n    };\n}\n", "meta": {"hexsha": "c576c592559cc8ca2afdf17e38c273a60ee69e44", "size": 3894, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mdk/include/mdk/utils/Random.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/include/mdk/utils/Random.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/include/mdk/utils/Random.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": 28.6323529412, "max_line_length": 78, "alphanum_fraction": 0.4399075501, "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.5061449729358632}}
{"text": "// SPDX-License-Identifier: Apache-2.0\n// \n// Copyright 2011-2017 Ryan Curtin (http://www.ratml.org/)\n// Copyright 2017 National ICT Australia (NICTA)\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// 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 <armadillo>\n\n#include \"catch.hpp\"\n\nusing namespace arma;\n\nTEST_CASE(\"fn_eigs_gen_odd_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 5;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    sp_mat m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    mat d(m);\n\n    // Eigendecompose, getting first 5 eigenvectors.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.1) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.1) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 4;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    sp_mat m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_mat z(5, 5);\n    z.sprandu(5, 5, 0.5);\n    m.submat(2, 2, 6, 6) += 5 * z;\n    mat d(m);\n\n    // Eigendecompose, getting first 4 eigenvectors.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_opts_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 4;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    sp_mat m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_mat z(5, 5);\n    z.sprandu(5, 5, 0.5);\n    m.submat(2, 2, 6, 6) += 5 * z;\n    mat d(m);\n\n    // Eigendecompose, getting first 4 eigenvectors.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"lm\", opts);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_odd_sigma_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 5;\n  const double sigma = 1.0;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    sp_mat m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_mat z(5, 5);\n    z.sprandu(5, 5, 0.5);\n    m.submat(2, 2, 6, 6) += 5 * z;\n    m += (sigma+0.001)*speye(n_rows, n_rows);\n    mat d(m);\n\n    // Eigendecompose, getting first 5 eigenvectors around 1.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.1) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.1) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_sigma_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 4;\n  const double sigma = 1.0;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    sp_mat m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_mat z(5, 5);\n    z.sprandu(5, 5, 0.5);\n    m.submat(2, 2, 6, 6) += 5 * z;\n    m += (sigma+0.001)*speye(n_rows, n_rows);\n    mat d(m);\n\n    // Eigendecompose, getting first 4 eigenvectors around 1.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_sigma_opts_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 4;\n  const double sigma = 1.0;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    sp_mat m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_mat z(5, 5);\n    z.sprandu(5, 5, 0.5);\n    m.submat(2, 2, 6, 6) += 5 * z;\n    m += (sigma+0.001)*speye(n_rows, n_rows);\n    mat d(m);\n\n    // Eigendecompose, getting first 4 eigenvectors around 1.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma, opts);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_odd_sm_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 5;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    sp_mat m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_mat z(5, 5);\n    z.sprandu(5, 5, 0.5);\n    m.submat(2, 2, 6, 6) += 5 * z;\n    m += 0.001*speye(n_rows, n_rows);\n    mat d(m);\n\n    // Eigendecompose, getting first 5 eigenvectors.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"sm\");\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.1) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.1) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_sm_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 4;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    sp_mat m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_mat z(5, 5);\n    z.sprandu(5, 5, 0.5);\n    m.submat(2, 2, 6, 6) += 5 * z;\n    m += 0.001*speye(n_rows, n_rows);\n    mat d(m);\n\n    // Eigendecompose, getting first 4 eigenvectors.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"sm\");\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_sm_opts_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 4;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    sp_mat m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_mat z(5, 5);\n    z.sprandu(5, 5, 0.5);\n    m.submat(2, 2, 6, 6) += 5 * z;\n    m += 0.001*speye(n_rows, n_rows);\n    mat d(m);\n\n    // Eigendecompose, getting first 4 eigenvectors.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"sm\", opts);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_odd_float_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 5;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    for(uword i = 0; i < n_rows; ++i)\n      {\n      m(i, i) += 5 * double(i) / double(n_rows);\n      }\n    Mat<float> d(m);\n\n    // Eigendecompose, getting first 5 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval);\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.001) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_float_test\")\n  {\n  const uword n_rows = 12;\n  const uword n_eigval = 8;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    for(uword i = 0; i < n_rows; ++i)\n      {\n      m(i, i) += 5 * double(i) / double(n_rows);\n      }\n    Mat<float> d(m);\n\n    // Eigendecompose, getting first 8 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval);\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_float_opts_test\")\n  {\n  const uword n_rows = 12;\n  const uword n_eigval = 8;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    for(uword i = 0; i < n_rows; ++i)\n      {\n      m(i, i) += 5 * double(i) / double(n_rows);\n      }\n    Mat<float> d(m);\n\n    // Eigendecompose, getting first 8 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"lm\", opts);\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_odd_float_sigma_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 5;\n  const float sigma = 1.0;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    for(uword i = 0; i < n_rows; ++i)\n      {\n      m(i, i) += 5 * double(i) / double(n_rows);\n      }\n    m += (sigma+0.001)*speye<SpMat<float>>(n_rows, n_rows);\n    Mat<float> d(m);\n\n    // Eigendecompose, getting first 5 eigenvectors around 1.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma);\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.001) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_float_sigma_test\")\n  {\n  const uword n_rows = 12;\n  const uword n_eigval = 8;\n  const float sigma = 1.0;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    for(uword i = 0; i < n_rows; ++i)\n      {\n      m(i, i) += 5 * double(i) / double(n_rows);\n      }\n    m += (sigma+0.001)*speye<SpMat<float>>(n_rows, n_rows);\n    Mat<float> d(m);\n\n    // Eigendecompose, getting first 8 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma);\n\n    // Do the same for the dense case around 1.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_float_sigma_opts_test\")\n  {\n  const uword n_rows = 12;\n  const uword n_eigval = 8;\n  const float sigma = 1.0;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    for(uword i = 0; i < n_rows; ++i)\n      {\n      m(i, i) += 5 * double(i) / double(n_rows);\n      }\n    m += (sigma+0.001)*speye<SpMat<float>>(n_rows, n_rows);\n    Mat<float> d(m);\n\n    // Eigendecompose, getting first 8 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma, opts);\n\n    // Do the same for the dense case around 1.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_odd_float_sm_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 5;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    for(uword i = 0; i < n_rows; ++i)\n      {\n      m(i, i) += 5 * double(i) / double(n_rows);\n      }\n    m += 0.001*speye<SpMat<float>>(n_rows, n_rows);\n    Mat<float> d(m);\n\n    // Eigendecompose, getting first 5 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"sm\");\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.001) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_float_sm_test\")\n  {\n  const uword n_rows = 12;\n  const uword n_eigval = 8;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    for(uword i = 0; i < n_rows; ++i)\n      {\n      m(i, i) += 5 * double(i) / double(n_rows);\n      }\n    m += 0.001*speye<SpMat<float>>(n_rows, n_rows);\n    Mat<float> d(m);\n\n    // Eigendecompose, getting first 8 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"sm\");\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_float_sm_opts_test\")\n  {\n  const uword n_rows = 12;\n  const uword n_eigval = 8;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    for(uword i = 0; i < n_rows; ++i)\n      {\n      m(i, i) += 5 * double(i) / double(n_rows);\n      }\n    m += 0.001*speye<SpMat<float>>(n_rows, n_rows);\n    Mat<float> d(m);\n\n    // Eigendecompose, getting first 8 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"sm\", opts);\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_odd_complex_float_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 5;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    Mat<cx_float> d(m);\n\n    // Eigendecompose, getting first 5 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval);\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_complex_float_test\")\n  {\n  const uword n_rows = 12;\n  const uword n_eigval = 8;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    Mat<cx_float> d(m);\n\n    // Eigendecompose, getting first 8 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval);\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_complex_float_opts_test\")\n  {\n  const uword n_rows = 12;\n  const uword n_eigval = 8;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    Mat<cx_float> d(m);\n\n    // Eigendecompose, getting first 8 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"lm\", opts);\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_odd_complex_float_sigma_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 5;\n  const cx_float sigma = 1.0;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_cx_fmat z(5, 5);\n    z.sprandu(5, 5, 0.5);\n    m.submat(2, 2, 6, 6) += 5 * z;\n    m += (sigma+cx_float(0.001,0))*speye< SpMat<cx_float> >(n_rows, n_rows);\n    Mat<cx_float> d(m);\n\n    // Eigendecompose, getting first 5 eigenvectors around 1.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma);\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_complex_float_sigma_test\")\n  {\n  const uword n_rows = 12;\n  const uword n_eigval = 8;\n  const cx_float sigma = 1.0;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_cx_fmat z(8, 8);\n    z.sprandu(8, 8, 0.5);\n    m.submat(2, 2, 9, 9) += 8 * z;\n    m += (sigma+cx_float(0.001,0))*speye< SpMat<cx_float> >(n_rows, n_rows);\n    Mat<cx_float> d(m);\n\n    // Eigendecompose, getting first 8 eigenvectors around 1.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma);\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_complex_float_sigma_opts_test\")\n  {\n  const uword n_rows = 12;\n  const uword n_eigval = 8;\n  const cx_float sigma = 1.0;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_cx_fmat z(8, 8);\n    z.sprandu(8, 8, 0.5);\n    m.submat(2, 2, 9, 9) += 8 * z;\n    m += (sigma+cx_float(0.001,0))*speye< SpMat<cx_float> >(n_rows, n_rows);\n    Mat<cx_float> d(m);\n\n    // Eigendecompose, getting first 8 eigenvectors around 1.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma, opts);\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_odd_complex_float_sm_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 5;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_cx_fmat z(5, 5);\n    z.sprandu(5, 5, 0.5);\n    m.submat(2, 2, 6, 6) += 5 * z;\n    m += cx_float(0.001,0)*speye< SpMat<cx_float> >(n_rows, n_rows);\n    Mat<cx_float> d(m);\n\n    // Eigendecompose, getting first 5 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"sm\");\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_complex_float_sm_test\")\n  {\n  const uword n_rows = 12;\n  const uword n_eigval = 8;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_cx_fmat z(8, 8);\n    z.sprandu(8, 8, 0.5);\n    m.submat(2, 2, 9, 9) += 8 * z;\n    m += cx_float(0.001,0)*speye< SpMat<cx_float> >(n_rows, n_rows);\n    Mat<cx_float> d(m);\n\n    // Eigendecompose, getting first 8 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"sm\");\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_complex_float_sm_opts_test\")\n  {\n  const uword n_rows = 12;\n  const uword n_eigval = 8;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_float> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_cx_fmat z(8, 8);\n    z.sprandu(8, 8, 0.5);\n    m.submat(2, 2, 9, 9) += 8 * z;\n    m += cx_float(0.001,0)*speye< SpMat<cx_float> >(n_rows, n_rows);\n    Mat<cx_float> d(m);\n\n    // Eigendecompose, getting first 8 eigenvectors.\n    Col<cx_float> sp_eigval;\n    Mat<cx_float> sp_eigvec;\n    eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"sm\", opts);\n\n    // Do the same for the dense case.\n    Col<cx_float> eigval;\n    Mat<cx_float> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) &&\n            (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"eigs_gen_odd_complex_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 5;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_double> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    Mat<cx_double> d(m);\n\n    // Eigendecompose, getting first 5 eigenvectors.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(size_t j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_complex_test\")\n  {\n  const uword n_rows = 15;\n  const uword n_eigval = 6;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_double> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    Mat<cx_double> d(m);\n\n    // Eigendecompose, getting first 6 eigenvectors.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_complex_opts_test\")\n  {\n  const uword n_rows = 15;\n  const uword n_eigval = 6;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_double> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    Mat<cx_double> d(m);\n\n    // Eigendecompose, getting first 6 eigenvectors.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"lm\", opts);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"eigs_gen_odd_complex_sigma_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 5;\n  const cx_double sigma = 1.0;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_double> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_cx_mat z(5, 5);\n    z.sprandu(5, 5, 0.5);\n    m.submat(2, 2, 6, 6) += 5 * z;\n    m += (sigma+cx_double(0.001,0))*speye< SpMat<cx_double> >(n_rows, n_rows);\n    Mat<cx_double> d(m);\n\n    // Eigendecompose, getting first 5 eigenvectors around 1.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(size_t j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_complex_sigma_test\")\n  {\n  const uword n_rows = 15;\n  const uword n_eigval = 6;\n  const cx_double sigma = 1.0;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_double> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_cx_mat z(8, 8);\n    z.sprandu(8, 8, 0.5);\n    m.submat(2, 2, 9, 9) += 8 * z;\n    m += (sigma+cx_double(0.001,0))*speye< SpMat<cx_double> >(n_rows, n_rows);\n    Mat<cx_double> d(m);\n\n    // Eigendecompose, getting first 6 eigenvectors around 1.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_complex_sigma_opts_test\")\n  {\n  const uword n_rows = 15;\n  const uword n_eigval = 6;\n  const cx_double sigma = 1.0;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_double> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    sp_cx_mat z(8, 8);\n    z.sprandu(8, 8, 0.5);\n    m.submat(2, 2, 9, 9) += 8 * z;\n    m += (sigma+cx_double(0.001,0))*speye< SpMat<cx_double> >(n_rows, n_rows);\n    Mat<cx_double> d(m);\n\n    // Eigendecompose, getting first 6 eigenvectors around 1.0.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma, opts);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"eigs_gen_odd_complex_sm_test\")\n  {\n  const uword n_rows = 10;\n  const uword n_eigval = 5;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_double> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    m += cx_double(0.001,0)*speye< SpMat<cx_double> >(n_rows, n_rows);\n    Mat<cx_double> d(m);\n\n    // Eigendecompose, getting first 5 eigenvectors.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"sm\");\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(size_t j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_complex_sm_test\")\n  {\n  const uword n_rows = 15;\n  const uword n_eigval = 6;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_double> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    m += cx_double(0.001,0)*speye< SpMat<cx_double> >(n_rows, n_rows);\n    Mat<cx_double> d(m);\n\n    // Eigendecompose, getting first 6 eigenvectors.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"sm\");\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n\n\n\nTEST_CASE(\"fn_eigs_gen_even_complex_sm_opts_test\")\n  {\n  const uword n_rows = 15;\n  const uword n_eigval = 6;\n  const uword n_trials = 10;\n  uword count = 0;\n  \n  for(uword trial=0; trial < n_trials; ++trial)\n    {\n    SpMat<cx_double> m;\n    m.sprandu(n_rows, n_rows, 0.3);\n    m += cx_double(0.001,0)*speye< SpMat<cx_double> >(n_rows, n_rows);\n    Mat<cx_double> d(m);\n\n    // Eigendecompose, getting first 6 eigenvectors.\n    Col<cx_double> sp_eigval;\n    Mat<cx_double> sp_eigvec;\n    eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12;\n    const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, \"sm\", opts);\n\n    // Do the same for the dense case.\n    Col<cx_double> eigval;\n    Mat<cx_double> eigvec;\n    const bool status_dense = eig_gen(eigval, eigvec, d);\n    \n    if( (status_sparse == false) || (status_dense == false) )  { continue; }  else  { ++count; }\n    \n    uvec used(n_rows, fill::zeros);\n\n    for(uword i=0; i < n_eigval; ++i)\n      {\n      // Sorting these is difficult.\n      // Find which one is the likely dense eigenvalue.\n      uword dense_eval = n_rows + 1;\n      for(uword k = 0; k < n_rows; ++k)\n        {\n        if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) &&\n            (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) &&\n            (used(k) == 0))\n          {\n          dense_eval = k;\n          used(k) = 1;\n          break;\n          }\n        }\n\n      REQUIRE( dense_eval != n_rows + 1 );\n\n      REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) );\n      for(uword j = 0; j < n_rows; ++j)\n        {\n        REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) );\n        }\n      }\n    }\n  \n  REQUIRE(count > 0);\n  }\n", "meta": {"hexsha": "1061d557a2e6a63574d99e021774497035331592", "size": 65180, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests2/fn_eigs_gen.cpp", "max_stars_repo_name": "getfiit/armadillo-code", "max_stars_repo_head_hexsha": "3a896deca12a0f596b52d84185ebfad65df650b7", "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": "tests2/fn_eigs_gen.cpp", "max_issues_repo_name": "getfiit/armadillo-code", "max_issues_repo_head_hexsha": "3a896deca12a0f596b52d84185ebfad65df650b7", "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": "tests2/fn_eigs_gen.cpp", "max_forks_repo_name": "getfiit/armadillo-code", "max_forks_repo_head_hexsha": "3a896deca12a0f596b52d84185ebfad65df650b7", "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.5877192982, "max_line_length": 101, "alphanum_fraction": 0.5570573796, "num_tokens": 21615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.506144970762077}}
{"text": "#include <iostream>\n#include <time.h>\n#include <vector>\n#include <typeinfo>\n#include <math.h>\n#include <algorithm>\n#include <numeric>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <sstream>\n#include <iterator>\n//#include <boost/archive/binary_iarchive.hpp>\n//#include <boost/archive/binary_oarchive.hpp>\n//#include <boost/serialization/vector.hpp>\n//#include <pybind11/pybind11.h>\n//#include <Python.h>\n//#include <pybind11/embed.h>\n\nusing namespace std;\n\nclass ANG\n{\n\n\tvector<vector<float>> activations;\n\tvector<vector<vector<float>>> derivatives;\n\tvector<vector<vector<float>>> weights;\n\tvector<vector<vector<float>>> seed_weights, seed_derivatives;\n\tvector<vector<float>> seed_activations;\n\t/*\nprivate:\n\tfriend class boost::serialization::access;\n\ttemplate<class Archive>\n\tvoid serialize(Archive& ar, const unsigned int version) {\n\t\tar& weights;\n\t\tar& derivatives;\n\t\tar& activations;\n\t\tar& seed_weights;\n\t\tar& seed_derivatives;\n\t\tar& seed_activations;\n\t}\n\t*/\n\npublic:\n\t//Default Constructor\n\tANG(){\n\t\tactivations = {};\n\t\tderivatives = {};\n\t\tweights = {};\n\t\tseed_weights = {};\n\t\tseed_derivatives = {};\n\t\tseed_activations = {};\n\t}\n\t//Parameterized Constructor\n\tANG(vector<int> hidden_layers, int num_outputs = 1, int num_inputs = 10) {\n\t\tvector<int> layers;\n\t\tlayers.push_back(num_inputs);\n\t\tfor (int i = 0; i < hidden_layers.size(); i++) layers.push_back(hidden_layers[i]);\n\t\tlayers.push_back(num_outputs);\n\t\t//for (int lay = 0; lay < layers.size(); lay++) cout << layers[lay] << endl;\n\t\tvector<vector<float>> w;\n\t\tfor (int i = 0; i < layers.size() - 1; i++) {\n\t\t\tint row_len, col_len;\n\t\t\trow_len = layers[i];\n\t\t\tcol_len = layers[i + 1];\n\t\t\t//srand(time(0));\n\t\t\tvector < vector <float>> Matrix(row_len, vector<float>(col_len, 0));\n\t\t\tfor (auto it_row = Matrix.begin(); it_row != Matrix.end(); it_row++)\n\t\t\t{\n\t\t\t\t// Getting each (i,j) element and assigning random value to it\n\t\t\t\tfor (auto it_col = it_row->begin(); it_col != it_row->end(); it_col++)\n\t\t\t\t{\n\t\t\t\t\t*it_col = (float)rand() / RAND_MAX;\n\t\t\t\t\t//cout << *it_col;\n\t\t\t\t}\n\t\t\t}\n\t\t\tw = Matrix;\n\t\t\tweights.push_back(w);\n\t\t}\n\t\t//for (int i = 0; i < w.size(); i++) {\n\t\t\t//for (int j = 0; j < w[i].size(); j++)\n\t\t\t\t//cout << w[i][j] << \" \";  \n\t\t\t//cout << endl;\n\t\t//}\n\n\t\tvector<vector<float>> d;\n\t\tfor (int i = 0; i < layers.size() - 1; i++) {\n\t\t\tint row_len, col_len;\n\t\t\trow_len = layers[i];\n\t\t\tcol_len = layers[i + 1];\n\t\t\tvector < vector <float>> Matrix(row_len, vector<float>(col_len, 0.0));\n\t\t\td = Matrix;\n\t\t\tderivatives.push_back(d);\n\t\t}\n\t\t//for (int i = 0; i < w.size(); i++) {\n\t\t\t//for (int j = 0; j < w[i].size(); j++)\n\t\t\t\t//cout << w[i][j] << \" \";  \n\t\t\t//cout << endl;\n\t\t//}\n\n\n\t\tvector<float> a;\n\t\tfor (int i = 0; i < layers.size(); i++) {\n\t\t\tint row_len, col_len;\n\t\t\trow_len = layers[i];\n\t\t\tvector<float> Matrix(row_len, 0);\n\t\t\ta = Matrix;\n\t\t\tactivations.push_back(a);\n\t\t}\n\t\t//for (int i = 0; i < w.size(); i++) {\n\t\t\t//for (int j = 0; j < w[i].size(); j++)\n\t\t\t\t//cout << w[i][j] << \" \";  \n\t\t\t//cout << endl;\n\t\t//}\n\t\t//cout << weights.size() << \" \";\n\t\t//for (int i = 0; i < weights.size(); i++) {\n\t\t\t//for (int j = 0; j < weights[i].size(); j++) {\n\t\t\t//\tfor (int k = 0; k < weights[i][j].size(); k++)\n\t\t\t//\t\tcout << weights[i][j][k] << \" \";\n\t\t\t//\tcout << endl;\n\t\t\t//}\n\t\t//}\n\t}\n\t//friend class boost::serialization::access;\n\tvector<int> sorted_index(int size, vector<float> b) {\n\t\tvector<int> indices(size);\n\t\tstd::iota(indices.begin(), indices.end(), 0);\n\t\tsort(indices.begin(), indices.end(), [&](int A, int B) -> bool {return b[A] < b[B];});\n\t\treturn indices;\n\t}\n\n\tvoid Print3D(vector<vector<vector<float>>> a) {\n\t\tfor (int i = 0; i < a.size(); i++) {\n\t\t\tfor (int j = 0; j < a[i].size(); j++) {\n\t\t\t\tfor (int k = 0; k < a[i][j].size(); k++) {\n\t\t\t\t\tcout << a[i][j][k] << \" \";\n\t\t\t\t}\n\t\t\t\tcout << endl;\n\t\t\t}\n\t\t\tcout << \"#\" << endl;\n\t\t}\n\t}\n\tfloat stdev(vector<float> data) {\n\t\tint size = data.size();\n\t\tfloat mean, sd = 0.0, sum = 0.0;\n\t\tfor (int i = 0; i < size; i++) sum += data[i];\n\t\tmean = (float)sum / size;\n\t\tfor (int i = 0; i < size; i++) sd += pow(data[i] - mean, 2);\n\t\treturn sqrt(sd / size);\n\n\t}\n\tvoid PrintMatrix(vector<vector<float>> a) {\n\t\tfor (int i = 0; i < a.size(); i++) {\n\n\t\t\tfor (int j = 0; j < a[i].size(); j++) cout << a[i][j] << \" \";\n\t\t\tcout << endl;\n\t\t}\n\t}\n\n\tvoid PrintVector(vector<float> a) {\n\t\tfor (int i = 0; i < a.size(); i++) cout << a[i] << \" \";\n\t}\n\n\tvector<vector<float>> transpose(vector<vector<float>> b)\n\t{\n\t\tif (b.size() == 0)\n\t\t\treturn { {} };\n\t\tvector<vector<float>> trans_vec(b[0].size(), vector<float>());\n\t\tfor (int i = 0; i < b.size(); i++)\n\t\t{\n\t\t\tfor (int j = 0; j < b[i].size(); j++)\n\t\t\t{\n\t\t\t\ttrans_vec[j].push_back(b[i][j]);\n\t\t\t}\n\t\t}\n\t\treturn trans_vec;   \n\t}\n\t//init not in use anymore\n\tvoid Init(vector<int> hidden_layers, int num_outputs = 1, int num_inputs = 10)\n\t{\n\t\tvector<int> layers;\n\t\tlayers.push_back(num_inputs);\n\t\tfor (int i = 0; i < hidden_layers.size(); i++) layers.push_back(hidden_layers[i]);\n\t\tlayers.push_back(num_outputs);\n\t\t//for (int lay = 0; lay < layers.size(); lay++) cout << layers[lay] << endl;\n\t\tvector<vector<float>> w;\n\t\tfor (int i = 0; i < layers.size() - 1; i++) {\n\t\t\tint row_len, col_len;\n\t\t\trow_len = layers[i];\n\t\t\tcol_len = layers[i + 1];\n\t\t\t//srand(time(0));\n\t\t\tvector < vector <float>> Matrix(row_len, vector<float>(col_len, 0));\n\t\t\tfor (auto it_row = Matrix.begin(); it_row != Matrix.end(); it_row++)\n\t\t\t{\n\t\t\t\t// Getting each (i,j) element and assigning random value to it\n\t\t\t\tfor (auto it_col = it_row->begin(); it_col != it_row->end(); it_col++)\n\t\t\t\t{\n\t\t\t\t\t*it_col = (float)rand()/RAND_MAX;\n\t\t\t\t\t//cout << *it_col;\n\t\t\t\t}\n\t\t\t}\n\t\t\tw = Matrix;\n\t\t\tweights.push_back(w);\n\t\t}\n\t\t//for (int i = 0; i < w.size(); i++) {\n\t\t\t//for (int j = 0; j < w[i].size(); j++)\n\t\t\t\t//cout << w[i][j] << \" \";  \n\t\t\t//cout << endl;\n\t\t//}\n\t\t\n\t\tvector<vector<float>> d;\n\t\tfor (int i = 0; i < layers.size() - 1; i++) {\n\t\t\tint row_len, col_len;\n\t\t\trow_len = layers[i];\n\t\t\tcol_len = layers[i + 1];\n\t\t\tvector < vector <float>> Matrix(row_len, vector<float>(col_len, 0.0));\n\t\t\td = Matrix;\n\t\t\tderivatives.push_back(d);\n\t\t}\n\t\t//for (int i = 0; i < w.size(); i++) {\n\t\t\t//for (int j = 0; j < w[i].size(); j++)\n\t\t\t\t//cout << w[i][j] << \" \";  \n\t\t\t//cout << endl;\n\t\t//}\n\t\t\n\t\t\n\t\tvector<float> a;\n\t\tfor (int i = 0; i < layers.size(); i++) {\n\t\t\tint row_len, col_len;\n\t\t\trow_len = layers[i];\n\t\t\tvector<float> Matrix(row_len, 0);\n\t\t\ta = Matrix;\n\t\t\tactivations.push_back(a);\n\t\t}\n\t\t//for (int i = 0; i < w.size(); i++) {\n\t\t\t//for (int j = 0; j < w[i].size(); j++)\n\t\t\t\t//cout << w[i][j] << \" \";  \n\t\t\t//cout << endl;\n\t\t//}\n\t\t//cout << weights.size() << \" \";\n\t\t//for (int i = 0; i < weights.size(); i++) {\n\t\t\t//for (int j = 0; j < weights[i].size(); j++) {\n\t\t\t//\tfor (int k = 0; k < weights[i][j].size(); k++)\n\t\t\t//\t\tcout << weights[i][j][k] << \" \";\n\t\t\t//\tcout << endl;\n\t\t\t//}\n\t\t//}\n\t}/**//**/\n\tvector<vector<float>> dot_new(vector<vector<float>>& a, vector<vector<float>>& b) {\n\t\tint row_a, row_b, col_a, col_b;\n\t\trow_a = a.size();\n\t\trow_b = b.size();\n\t\tcol_a = a[0].size();\n\t\tcol_b = b[0].size();\n\t\tvector<vector<float>> dot;\n\t\tfor (int i = 0; i < row_a; i++) dot.push_back({});\n\t\tfor (int i = 0; i < row_a; i++) {\n\t\t\tvector<float> col0;\n\t\t\tfor (int j = 0; j < col_b; j++) col0.push_back(0);\n\t\t\tdot[i] = col0;\n\t\t}\n\t\t//cout << row_a << \" \" << col_a << \" \" << row_b << \" \" << col_b << endl;\n\t\tfor (int i = 0; i < row_a; i++) {\n\t\t\tfor (int j = 0; j < col_b; j++) {\n\t\t\t\tdot[i][j] = 0;\n\t\t\t\tfor (int k = 0; k < col_a; k++)\n\t\t\t\t\tdot[i][j] = dot[i][j] + (a[i][k] * b[k][j]);\n\t\t\t}\n\t\t}\n\t\treturn dot;\n\n\t}\n\t//Dot product done\n\tvector<vector<float>> dot_product(vector<vector<float>> &a, vector<vector<float>> &b) {\n\t\tint row_a, row_b, col_a, col_b;\n\t\trow_a = a.size();\n\t\trow_b = b.size();\n\t\tcol_a = a[0].size();\n\t\tcol_b = b[0].size();\n\t\tvector<vector<float>> dot;\n\t\tdot.push_back({});\n\t\tfor (int i = 0; i < col_b; i++)\n\t\t\tdot[0].push_back(0);\n\t\tfor (int i = 0; i < row_a; i++) {\n\t\t\tfor (int j = 0; j < col_b; j++) {\n\t\t\t\tdot[i][j] = 0;\n\t\t\t\tfor(int k = 0; k< col_a; k++)\n\t\t\t\t\tdot[i][j] = dot[i][j] + (a[i][k] * b[k][j]);\n\t\t\t}\n\t\t}\n\n\t\treturn dot;\n\n\n\t}\n\n\tfloat _mse(vector<float> target, vector<float> output) {\n\t\tfloat sum = 0;\n\t\tint n = target.size();\n\t\tfor (int i = 0; i < target.size(); i++) {\n\t\t\tsum = sum + ((target[i] - output[i]) * (target[i] - output[i]));\n\t\t}\n\t\treturn sum / n;\n\t}\n\t//sigmoid done\n\tvector<float> _sigmoid(vector<float>& a) {\n\t\tvector<float> sigmoid;\n\t\tfor (int i = 0; i < a.size(); i++) sigmoid.push_back(1.0 / (1.0 + (float)exp(-1 * a[i])));\n\t\treturn sigmoid;\n\t}\n\n\t// sigmoid derivative done\n\tvector<float> _sigmoid_derivative(vector<float>& a) {\n\t\tvector<float> sigmoid;\n\t\tfor (int i = 0; i < a.size(); i++) sigmoid.push_back(a[i] * (1 - a[i]));\n\t\treturn sigmoid;\n\t}\n\t//forward propogation done\n\tvector<float> forward_propogate(vector<float> inputs) {\n\t\tactivations[0] = inputs;\n\t\tvector<vector<float>> net_inputs;\n\t\tvector<vector<float>> activ;\n\t\tactiv.push_back(inputs);\n\t\tfor (int i = 0; i < weights.size(); i++) {\n\t\t\t//cout << weights[i].size() << \" \" << endl;\n\t\t\tnet_inputs = dot_new(activ, weights[i]);\n\t\t\tvector<float> temp_activ;\n\t\t\ttemp_activ = _sigmoid(net_inputs[0]);\n\t\t\tactiv.pop_back();\n\t\t\tactiv.push_back(temp_activ);\n\t\t\tactivations[i + 1] = temp_activ;\n\t\t}\n\t\t//return activations and change return type of function\n\t\treturn activ[0];\n\t}\n\n\tvector<float> forward_propogate_test(vector<float> inputs) {\n\t\tactivations[0] = inputs;\n\t\tvector<vector<float>> net_inputs;\n\t\tvector<vector<float>> activ;\n\t\tactiv.push_back(inputs);\n\t\tfor (int i = 0; i < weights.size(); i++) {\n\t\t\t//cout << weights[i].size() << \" \" << endl;\n\t\t\tnet_inputs = dot_new(activ, weights[i]);\n\t\t\tvector<float> temp_activ;\n\t\t\ttemp_activ = _sigmoid(net_inputs[0]);\n\t\t\tactiv.pop_back();\n\t\t\tactiv.push_back(temp_activ);\n\t\t\tactivations[i + 1] = temp_activ;\n\t\t}\n\t\t//return activations and change return type of function\n\t\treturn activ[0];\n\t}\n\n\tvoid gradient_descent(float learning_rate = 1.0) {\n\t\tfor (int i = 0; i < weights.size(); i++) {\n\t\t\t//vector<vector<float>> w = weights[i];\n\t\t\t//weights[i] += weights[i] * learning_rate;\n\t\t\tfor (int j = 0; j < weights[i].size(); j++) {\n\t\t\t\t//cout << weights[i][j].size();\n\t\t\t\t//transform(weights[i][j].begin(), weights[i][j].end(), temp.begin(), [learning_rate](float& c) {return c * learning_rate; });\n\t\t\t\tfor (int k = 0; k < weights[i][j].size(); k++) {\n\t\t\t\t\tweights[i][j][k] = weights[i][j][k] + derivatives[i][j][k] * learning_rate;\n\t\t\t\t}\n\t\t\t\t//transform(weights[i][j].begin(), weights[i][j].end(), temp.begin(), weights[i][j].begin(), plus<float>());\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid back_propogate(vector<float> error) {\n\t\tvector<float> activation;\n\t\t//vector<float> delta;\n\t\tvector<float> sigmoid_derivative;\n\t\t//cout << activations.size();\n\t\tfor (int i = derivatives.size()-1; i >= 0; i--) {\n\t\t\t//cout << i;\n\t\t\tvector<float> delta;\n\t\t\tactivation = activations[i + 1];\n\t\t\t//cout << activation.size() << endl;\n\t\t\tsigmoid_derivative = _sigmoid_derivative(activation);\n\t\t\t//cout << sigmoid_derivative.size() <<endl;\n\t\t\t//PrintVector(error);\n\t\t\tfor (int j = 0; j < sigmoid_derivative.size(); j++) {\n\t\t\t\tdelta.push_back(sigmoid_derivative[j] * error[j]);\n\t\t\t}\n\t\t\t//cout << delta.size();\n\t\t\tvector<vector<float>> delta_re;\n\t\t\tdelta_re.push_back(delta);\n\t\t\tvector<float> current_acc = activations[i];\n\t\t\tvector<vector<float>> current_activations;\n\t\t\tfor (int k = 0; k < current_acc.size(); k++) current_activations.push_back({ current_acc[k] });\n\t\t\t//PrintMatrix(current_activations);\n\t\t\t//delta = std::transform(sigmoid_derivative.begin(), sigmoid_derivative.end(), error, std::multiplies<float>());\n\t\t\t//#cout << delta_re[0].size()<< endl;\n\t\t\tvector<vector<float>> dotp = dot_new(current_activations, delta_re);\n\t\t\tderivatives[i] = dotp;\n\t\t\tvector<vector<float>> t_weights = transpose(weights[i]);\n\t\t\tvector<vector<float>> delta_mul = { delta };\n\t\t\terror = dot_new(delta_mul, t_weights)[0];\n\t\t\t//PrintVector(error);\n\t\t}\n\t}\n\n\tvoid train(vector<vector<float>> inputs, vector<vector<float>> targets, int epochs, float learning_rate) {\n\t\tfor (int i = 0; i < epochs; i++) {\n\t\t\tfloat sum_errors = 0;\n\t\t\tfor (int j = 0; j < inputs.size(); j++) {\n\t\t\t\tvector<float> target = targets[j];\n\t\t\t\tvector<float> output = forward_propogate(inputs[j]);\n\t\t\t\tvector<float> error;\n\t\t\t\tfor (int k = 0; k < output.size(); k++)\n\t\t\t\t\terror.push_back(target[k] - output[k]);\n\t\t\t\tback_propogate(error);\n\t\t\t\tgradient_descent(learning_rate);\n\t\t\t\tsum_errors = sum_errors + _mse(target, output);\n\t\t\t}\n\t\t\tcout << \"Error: \" << sum_errors / inputs.size() << \" at epoch\" << i + 1 << endl;\n\t\t}\n\t\tcout << \"Training complete\" << endl;\n\t\tcout << \"=======\" << endl;\n\t}\n\n\tvoid create_seed() {\n\t\tseed_weights = weights;\n\t\tseed_activations = activations;\n\t\t//cout << activations.size() << endl;\n\t\tseed_derivatives = derivatives;\n\t\tseed_weights.resize(seed_weights.size() - 2);\n\t\tseed_activations.resize(seed_activations.size() - 2);\n\t\t//cout << seed_activations.size() << endl;\n\t\tseed_derivatives.resize(seed_derivatives.size() - 2);\n\t}\n\n\tvoid prime_base_network(vector<vector<float>> inputs, vector<vector<float>> targets, int cycles, float learning_rate = 0.5) {\n\t\ttrain(inputs, targets, cycles, learning_rate);\n\t\tPrint3D(weights);\n\t}\n\n\tvoid remove_temp_classifier() {\n\t\tweights.resize(weights.size() - 1);\n\t\tderivatives.resize(derivatives.size() - 1);\n\t\tactivations.resize(activations.size() - 1);\n\t}\n\n\tvoid add_destination_layer() {\n\t\tvector<vector<float>> temp;\n\t\tint r, c;\n\t\t// add new weights \n\t\ttemp = weights.back();\n\t\t//PrintMatrix(temp);\n\t\tr = temp[0].size(); //changed to set the size of the destionation layer to a minimum 3\n\t\tc = 1;// temp[0].size();\n\t\tvector < vector <float>> Matrix(r, vector<float>(c, 0));\n\t\tfor (auto it_row = Matrix.begin(); it_row != Matrix.end(); it_row++)\n\t\t{\n\t\t\t// Getting each (i,j) element and assigning random value to it\n\t\t\tfor (auto it_col = it_row->begin(); it_col != it_row->end(); it_col++)\n\t\t\t{\n\t\t\t\t*it_col = (float)rand() / RAND_MAX;\n\t\t\t\t//cout << *it_col;\n\t\t\t}\n\t\t}\n\t\ttemp = Matrix;\n\t\tweights.push_back(temp);\n\t\t//for (int wei = 0; wei < weights.size(); wei++) cout << \"The matrices are of shape \" << weights[wei].size() << \" x \" << weights[wei][0].size() << endl;\n\t\t// add new derivatives\n\t\ttemp = derivatives.back();\n\t\tvector < vector <float>> Matrix_dr(r, vector<float>(c, 0.0));\n\t\ttemp = Matrix_dr;\n\t\tderivatives.push_back(temp);\n\n\t\t// add new activations\n\t\tvector<float> temp_acc = activations.back();\n\t\tint row_len = 1;// temp_acc.size();\n\t\tvector<float> Matrix_acc(row_len, 0);\n\t\ttemp_acc = Matrix_acc;\n\t\tactivations.push_back(temp_acc);\n\t\t//for (int wei = 0; wei < activations.size(); wei++) cout << \"The matrices are of shape \" << activations.size() << \" x \" << activations[wei].size() << endl;\n\t}\n    //done\n\tvoid add_class_layer(vector<vector<float>> targets) {\n\t\tvector<float> temp;\n\t\tfor (int i = 0; i < targets.size(); i++) temp.push_back(targets[i][0]);\n\t\tsort(temp.begin(), temp.end());\n\t\tint num_classes = std::unique(temp.begin(), temp.end()) - temp.begin();\n\t\tnum_classes = num_classes - 1;\n\t\tvector<vector<float>> temp_w;\n\t\tint r, c;\n\t\ttemp_w = weights.back();\n\t\tr = temp_w[0].size();\n\t\tc = num_classes;\n\t\tvector < vector <float>> Matrix(r, vector<float>(c, 0));\n\t\tfor (auto it_row = Matrix.begin(); it_row != Matrix.end(); it_row++)\n\t\t{\n\t\t\t// Getting each (i,j) element and assigning random value to it\n\t\t\tfor (auto it_col = it_row->begin(); it_col != it_row->end(); it_col++)\n\t\t\t{\n\t\t\t\t*it_col = (float)rand() / RAND_MAX;\n\t\t\t\t//cout << *it_col;\n\t\t\t}\n\t\t}\n\t\ttemp_w = Matrix;\n\t\tweights.push_back(temp_w);\n\n\t\tvector<vector<float>> temp_d;\n\t\ttemp_d = derivatives.back();\n\t\tvector < vector <float>> Matrix_dr(r, vector<float>(c, 0.0));\n\t\ttemp_d = Matrix_dr;\n\t\tderivatives.push_back(temp_d);\n\n\t\tvector<float> temp_acc = activations.back();\n\t\tint row_len = num_classes;\n\t\tvector<float> Matrix_acc(row_len, 0);\n\t\ttemp_acc = Matrix_acc;\n\t\tactivations.push_back(temp_acc);\n\n\n\t}\n\t// not done\n\tvoid add_class_layer_final() {}\n\n\tvoid create_temp_classifier_seed(vector<vector<float>> targets) {\n\t\tvector<float> temp;\n\t\t//cout << seed_weights.size() << endl;\n\t\tfor (int i = 0; i < targets.size(); i++) temp.push_back(targets[i][0]);\n\t\tsort(temp.begin(), temp.end());\n\t\tint num_classes = std::unique(temp.begin(), temp.end()) - temp.begin();\n\t\tnum_classes = num_classes - 1;\n\t\tvector<vector<float>> temp_w;\n\t\tint r, c;\n\t\ttemp_w = seed_weights.back();\n\t\tr = temp_w[0].size();\n\t\tc = num_classes;\n\t\tvector < vector <float>> Matrix(r, vector<float>(c, 0));\n\t\t//PrintMatrix(Matrix);\n\t\tfor (auto it_row = Matrix.begin(); it_row != Matrix.end(); it_row++)\n\t\t{\n\t\t\t// Getting each (i,j) element and assigning random value to it\n\t\t\tfor (auto it_col = it_row->begin(); it_col != it_row->end(); it_col++)\n\t\t\t{\n\t\t\t\t*it_col = (float)rand() / RAND_MAX;\n\t\t\t\t//cout << *it_col;\n\t\t\t}\n\t\t}\n\t\ttemp_w = Matrix;\n\t\t//PrintMatrix(temp_w);\n\t\tseed_weights.push_back(temp_w);\n\t\t//cout << seed_weights.size()<< endl;\n\t\tvector<vector<float>> temp_d;\n\t\ttemp_d = seed_derivatives.back();\n\t\tvector < vector <float>> Matrix_dr(r, vector<float>(c, 0.0));\n\t\ttemp_d = Matrix_dr;\n\t\tseed_derivatives.push_back(temp_d);\n\n\t\tvector<float> temp_acc = seed_activations.back();\n\t\tint row_len = num_classes;\n\t\tvector<float> Matrix_acc(row_len, 0);\n\t\ttemp_acc = Matrix_acc;\n\t\tseed_activations.push_back(temp_acc);\n\n\n\t}\n\n\tvector<float> forward_propogate_seed(vector<float> inputs) {\n\t\tseed_activations[0] = inputs;\n\t\tvector<vector<float>> net_inputs;\n\t\tvector<vector<float>> activ;\n\t\tactiv.push_back(inputs);\n\t\tfor (int i = 0; i < seed_weights.size(); i++) {\n\t\t\t//cout << weights[i].size() << \" \" << endl;\n\t\t\tnet_inputs = dot_new(activ, seed_weights[i]);\n\t\t\tvector<float> temp_activ;\n\t\t\ttemp_activ = _sigmoid(net_inputs[0]);\n\t\t\tactiv.pop_back();\n\t\t\tactiv.push_back(temp_activ);\n\t\t\tseed_activations[i + 1] = temp_activ;\n\t\t}\n\t\t//return activations and change return type of function\n\t\treturn activ[0];\n\t}\n\t\n\tvoid back_propogate_seed(vector<float> error) {\n\t\tvector<float> activation;\n\t\t//vector<float> delta;\n\t\tvector<float> sigmoid_derivative;\n\t\t//cout << activations.size();\n\t\tfor (int i = seed_derivatives.size() - 1; i >= 0; i--) {\n\t\t\t//cout << i;\n\t\t\tvector<float> delta;\n\t\t\tactivation = seed_activations[i + 1];\n\t\t\t//cout << activation.size() << endl;\n\t\t\tsigmoid_derivative = _sigmoid_derivative(activation);\n\t\t\t//cout << sigmoid_derivative.size() <<endl;\n\t\t\t//PrintVector(error);\n\t\t\tfor (int j = 0; j < sigmoid_derivative.size(); j++) {\n\t\t\t\tdelta.push_back(sigmoid_derivative[j] * error[j]);\n\t\t\t}\n\t\t\t//cout << delta.size();\n\t\t\tvector<vector<float>> delta_re;\n\t\t\tdelta_re.push_back(delta);\n\t\t\tvector<float> current_acc = seed_activations[i];\n\t\t\tvector<vector<float>> current_activations;\n\t\t\tfor (int k = 0; k < current_acc.size(); k++) current_activations.push_back({ current_acc[k] });\n\t\t\t//PrintMatrix(current_activations);\n\t\t\t//delta = std::transform(sigmoid_derivative.begin(), sigmoid_derivative.end(), error, std::multiplies<float>());\n\t\t\t//#cout << delta_re[0].size()<< endl;\n\t\t\tvector<vector<float>> dotp = dot_new(current_activations, delta_re);\n\t\t\tseed_derivatives[i] = dotp;\n\t\t\tvector<vector<float>> t_weights = transpose(weights[i]);\n\t\t\tvector<vector<float>> delta_mul = { delta };\n\t\t\terror = dot_new(delta_mul, t_weights)[0];\n\t\t\t//PrintVector(error);\n\t\t}\n\t}\n\n\tvoid train_seed(vector<vector<float>> inputs, vector<vector<float>> targets, int epochs, float learning_rate) {\n\t\tfor (int i = 0; i < epochs; i++) {\n\t\t\tfloat sum_errors = 0;\n\t\t\tfor (int j = 0; j < inputs.size(); j++) {\n\t\t\t\tvector<float> target = targets[j];\n\t\t\t\tvector<float> output = forward_propogate_seed(inputs[j]);\n\t\t\t\tvector<float> error;\n\t\t\t\t//PrintVector(output);\n\t\t\t\tfor (int k = 0; k < target.size(); k++)\n\t\t\t\t\terror.push_back(target[k] - output[k]);\n\t\t\t\tback_propogate_seed(error);\n\t\t\t\tgradient_descent(learning_rate);\n\t\t\t\tsum_errors = sum_errors + _mse(target, output);\n\t\t\t}\n\t\t\t//cout << \"Error: \" << sum_errors / inputs.size() << \" at epoch\" << i + 1 << endl;\n\t\t}\n\t\tcout << \"Training complete\" << endl;\n\t\tcout << \"=======\" << endl;\n\t}\n\n\tvoid prime_seed_network(vector<vector<float>> inputs, vector<vector<float>> targets, int cycles, float learning_rate = 0.5) {\n\t\ttrain_seed(inputs, targets, cycles, learning_rate);\n\t}\n\n\tvoid remove_temp_classifier_seed() {\n\t\tseed_weights.resize(seed_weights.size() - 1);\n\t\tseed_derivatives.resize(seed_derivatives.size() - 1);\n\t\tseed_activations.resize(seed_activations.size() - 1);\n\t}\n\n\tvector<vector<vector<float>>> extreme_member_classes(vector<vector<float>> inputs, vector<vector<float>> targets) {\n\t\t//cout << weights.size() << endl;\n\t\tcreate_seed();\n\t\tcreate_temp_classifier_seed(targets);\n\t\tprime_seed_network(inputs, targets, 10);\n\t\tremove_temp_classifier_seed();\n\t\t//cout << weights.size() << endl;\n\t\t//cout << weights.size() << endl;\n\t\tvector<float> classes, temp;\n\t\tfor (int i = 0; i < targets.size(); i++) classes.push_back(targets[i][0]);\n\t\ttemp = classes;\n\t\tsort(classes.begin(), classes.end());\n\t\tvector<float>::iterator ip = std::unique(classes.begin(), classes.end());\n\t\tclasses.resize(std::distance(classes.begin(), ip));\n\t\t//PrintVector(classes);\n\t\tvector<vector<vector<float>>> sorted_classes_list;\n\t\tfor (int i = 0; i < classes.size(); i++) {\n\t\t\tint count = 0;\n\t\t\tfor (int j = 0; j < targets.size(); j++) {\n\t\t\t\t\tif (targets[j][0] == classes[i]) count = count + 1;\n\t\t\t}\n\t\t\t//cout << count << endl;\n\t\t\tvector<float> sum_perceptron, avg_perceptron;\n\t\t\tfor (int k = 0; k < seed_weights.back()[0].size(); k++) sum_perceptron.push_back(0);\n\t\t\t//filter indices\n\t\t\tvector<float> filter_indices;\n\t\t\t//cout << temp.size() << endl;\n\t\t\tfor (int ind = 0; ind < temp.size(); ind++) {\n\t\t\t\tif (temp[ind] == classes[i]) filter_indices.push_back(ind);\n\t\t\t}\n\t\t\t//PrintVector(filter_indices);\n\t\t\t//Class_inputs\n\t\t\tvector<vector<float>> Class_inputs;\n\t\t\tfor (int cinp = 0; cinp < filter_indices.size(); cinp++) {\n\t\t\t\tClass_inputs.push_back(inputs[filter_indices[cinp]]);\n\t\t\t}\n\t\t\t\n\t\t\tfor (int inp = 0; inp < Class_inputs.size(); inp++) {\n\t\t\t\tvector<float> output_single = forward_propogate_seed(Class_inputs[inp]);\n\t\t\t\tfor (int sw = 0; sw < seed_activations.back().size(); sw++) sum_perceptron[sw] += output_single[sw];\n\t\t\t}\n\n\t\t\tfor (int s = 0; s < sum_perceptron.size(); s++) avg_perceptron.push_back((float)sum_perceptron[s] / count);\n\n\t\t\tvector<float> Error_list;\n\t\t\tfor (int cimp = 0; cimp < Class_inputs.size(); cimp++) {\n\t\t\t\tint err = 0;\n\t\t\t\tvector<float> output_single = forward_propogate_seed(Class_inputs[cimp]);\n\t\t\t\tfor (int o = 0; o < output_single.size(); o++) err += avg_perceptron[o] - output_single[o];\n\t\t\t\tError_list.push_back(err);\n\t\t\t}\n\t\t\t//sort_indices = np.argsort(Error_list)\n\t\t\tvector<int> sorted_indices = sorted_index(Class_inputs.size(), Error_list);\n\t\t\tvector<vector<float>> Classes_sorted;\n\t\t\t//for (int is = 0; is < sorted_indices.size(); is++) cout << sorted_indices[is] << endl;\n\t\t\tfor (int sc = 0; sc < sorted_indices.size(); sc++) Classes_sorted.push_back(Class_inputs[sorted_indices[sc]]);\n\t\t\t//PrintMatrix(Class_inputs);\n\t\t\tsorted_classes_list.push_back(Classes_sorted);\n\t\t}\n\t\treturn sorted_classes_list;\n\n\t}\n\n\tvector<float> return_source_activations() {\n\t\treturn activations.rbegin()[1];\n\t}\n\n\tfloat return_acc(vector<vector<float>> inputs, vector<vector<float>> targets) {\n\n\t\tvector<int> pred;\n\t\tfor (int i = 0; i < inputs.size(); i++) {\n\t\t\tvector<float> output = forward_propogate(inputs[i]);\n\t\t\t//cout << output[0] << endl;\n\t\t\tif (output[0] >= 0.5) pred.push_back(1);\n\t\t\telse pred.push_back(0);\n\t\t}\n\t\tfloat acc = 0.0;\n\t\tint count = 0;\n\t\tfor (int j = 0; j < pred.size(); j++) {\n\t\t\t//cout << pred[j] << endl;\n\t\t\tif (pred[j] == targets[j][0]) count += 1;\n\t\t}\n\t\t//cout << \"acc: \" << acc << endl;\n\t\tacc = (float)count / pred.size();\n\t\tcout << \"acc: \" << acc << endl;\n\t\treturn acc;\n\n\t}\n\n\tvoid ANG_grow(vector<vector<float>> inputs, vector<vector<float>> targets, vector<int> hidden_layers) {\n\t\t//Init(hidden_layers, 1, inputs[0].size());\n\t\t//cout << weights.size() << endl;\n\t\tprime_base_network(inputs, targets, 10);\n\t\t//cout << weights.size() << endl;\n\t\tremove_temp_classifier();\n\t\t//cout << weights.size() << endl;\n\t\tadd_destination_layer();\n\t\t//Print3D(weights);\n\t\t//cout << weights.size() << endl;\n\t\tadd_class_layer(targets);\n\t\t//Print3D(weights);\n\t\t//cout << weights.size() << endl;\n\t\tfloat accuracy = 0.0;\n\t\tint percep = 0;\n\t\tvector<vector<float>> items = inputs, test_targets = targets;\n\n\t\twhile (accuracy < 0.9) {\n\t\t\tvector<vector<vector<float>>> sorted_classes = extreme_member_classes(inputs, targets);\n\t\t\t//cout << weights.size() << endl;\n\t\t\tremove_temp_classifier();\n\t\t\t//cout << activations.back().size() << endl;\n\t\t\tfor (int i = 0; i < sorted_classes.size(); i++) {\n\t\t\t\tvector<vector<float>> extremes;\n\t\t\t\t//PrintMatrix(sorted_classes[i]);\n\t\t\t\textremes.push_back(sorted_classes[i][0]);\n\t\t\t\textremes.push_back(sorted_classes[i].back());\n\t\t\t\t//PrintMatrix(extremes);\n\t\t\t\tfor (int ext = 0; ext < extremes.size(); ext++) {\n\t\t\t\t\tvector<float> output = forward_propogate(extremes[ext]);\n\t\t\t\t\tvector<float> fp_output = return_source_activations();\n\t\t\t\t\tfloat sum_op = 0.0;\n\t\t\t\t\tfor (int fpo = 0; fpo < fp_output.size(); fpo++) sum_op += fp_output[fpo];\n\t\t\t\t\tint len_op = fp_output.size();\n\t\t\t\t\tfloat average = (float)sum_op / len_op;\n\t\t\t\t\tfloat sum_avg = 0.0;\n\t\t\t\t\tfor (int sa = 0; sa < fp_output.size(); sa++) sum_avg += (average - fp_output[sa]) * (average - fp_output[sa]);\n\t\t\t\t\tfloat sd = stdev(fp_output);\n\t\t\t\t\tint x = 1;\n\t\t\t\t\t//cout << \"percep \" << percep << endl;\n\t\t\t\t\tif(percep<activations.back().size()) {\n\t\t\t\t\t\tactivations.back()[percep] = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tvector<vector<float>> temp_weights;\n\t\t\t\t\t\tvector<float> tw;\n\t\t\t\t\t\tfor (int w = 0; w < weights.back().size(); w++) {\n\t\t\t\t\t\t\ttw = weights.back()[w];\n\t\t\t\t\t\t\ttw.push_back((float)rand() / RAND_MAX);\n\t\t\t\t\t\t\ttemp_weights.push_back(tw);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//PrintMatrix(temp_weights);\n\t\t\t\t\t\tweights.back() = temp_weights;\n\t\t\t\t\t\t//PrintMatrix(weights.back());\n\t\t\t\t\t\tvector<vector<float>> temp_derivatives;\n\t\t\t\t\t\tvector<float> td;\n\t\t\t\t\t\tfor (int d = 0; d < derivatives.back().size(); d++) {\n\t\t\t\t\t\t\ttd = derivatives.back()[d];\n\t\t\t\t\t\t\ttd.push_back(0);\n\t\t\t\t\t\t\ttemp_derivatives.push_back(td);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tderivatives.back() = temp_derivatives;\n\t\t\t\t\t\tactivations.back().push_back(0);\n\t\t\t\t\t}\n\t\t\t\t\tpercep = percep + 1;\n\t\t\t\t\tfor (int conn = 0; conn < fp_output.size(); conn++) {\n\t\t\t\t\t\tif (fp_output[conn] >= x * sd || fp_output[conn] < -x * sd) cout << \"This is a critical connection\" << endl;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcout << \"This is not a critical connection\" << endl;\n\t\t\t\t\t\t\tcout << fp_output.size() << endl;\n\t\t\t\t\t\t\tfor (int wl = 0; wl < weights.back().size(); wl++)\n\t\t\t\t\t\t\t\tfor(int c = 0; c< weights.back()[0].size(); c++)\n\t\t\t\t\t\t\t\t\tweights.back()[wl][c] = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << \"I am here\" << endl;\n\t\t\tadd_class_layer(targets);\n\t\t\tcout << weights.back().size() << endl;\n\t\t\ttrain(inputs, targets, 50, 0.5);\n\t\t\tcout << \"I am here\" << endl;\n\t\t\taccuracy = return_acc(items, test_targets);\n\t\t\tvector<vector<float>> extreme_members;\n\t\t\tfor (int scl = 0; scl < sorted_classes.size(); scl++) {\n\t\t\t\textreme_members.push_back(sorted_classes[scl][0]);\n\t\t\t\textreme_members.push_back(sorted_classes[scl].back());\n\t\t\t}\n\t\t\tvector<int> rm_index;\n\t\t\tfor (int em = 0; em < extreme_members.size(); em++) {\n\t\t\t\tfor (int pos = 0; pos < inputs.size(); pos++) {\n\t\t\t\t\tif (extreme_members[em] == inputs[pos]) {\n\t\t\t\t\t\t//rm_index.push_back(pos);\n\t\t\t\t\t\tinputs.erase(inputs.begin() + pos);\n\t\t\t\t\t\ttargets.erase(targets.begin() + pos);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Work on this\n\t\t\t/*for (auto rm : rm_index) {\n\t\t\t\tinputs.erase(inputs.begin() + rm);\n\t\t\t\ttargets.erase(targets.begin() + rm);\n\t\t\t}*/\n\t\t\tcout << \"accuracy: \" << accuracy << endl;\n\t\t}\n\t\t//cout << \"activations size: \" << activations.size() << endl;\n\t}\n\t/*\n\tvoid save(ostringstream& oss)\n\t{\n\t\tboost::archive::binary_oarchive oa(oss);\n\t\toa&* (this);\n\t}\n\n\tvoid load(istringstream& iss)\n\t{\n\t\t//std::string str_data = oss.str();\n\t\t//std::istringstream iss(str_data);\n\t\tboost::archive::binary_iarchive ia(iss);\n\t\tia&* (this);\n\t}\n\t*/\n\tvoid save_weights_der(vector<vector<vector<float>>> Matrix, string name) {\n\t\tofstream output_file(name + \".txt\");\n\t\tostream_iterator<float> output_iterator(output_file, \",\");\n\t\tfor (int i = 0; i < Matrix.size(); i++) {\n\n\t\t\tfor (int j = 0; j <Matrix[i].size(); j++) {\n\t\t\t\t//cout << j;\n\t\t\t\tcopy(Matrix[i][j].begin(), Matrix[i][j].end() - 1, output_iterator);\n\t\t\t\toutput_file << Matrix[i][j].back();\n\t\t\t\toutput_file << \"\\n\";\n\t\t\t}\n\t\t\toutput_file << \"#\\n\";\n\t\t}\n\n\t\toutput_file.close();\n\n\t}\n\n\tvoid save_activations(vector<vector<float>> Matrix, string name) {\n\n\t\tofstream output_file(name + \".txt\");\n\t\tostream_iterator<float> output_iterator(output_file, \",\");\n\n\t\tfor (int j = 0; j < Matrix.size(); j++) {\n\t\t\t//cout << j;\n\t\t\tcopy(Matrix[j].begin(), Matrix[j].end() - 1, output_iterator);\n\t\t\toutput_file << Matrix[j].back();\n\t\t\toutput_file << \"\\n\";\n\t\t}\n\n\t\toutput_file.close();\n\t\n\t}\n\n\tvoid read_weights_der(vector<vector<vector<float>>>& Matrix, string name) {\n\n\t\tstd::ifstream in(name + \".txt\");\n\t\tstd::string str;\n\t\tvector<vector<vector<float>>> weights;\n\t\tvector<vector<float>> st;\n\t\twhile (in.good())\n\t\t{\n\t\t\tstring line;\n\t\t\tvector<float> row;\n\t\t\tgetline(in, line, '\\n');\n\t\t\tif (line == \"\") break;\n\t\t\tif (line == \"#\") {\n\t\t\t\tweights.push_back(st);\n\t\t\t\tst = {};\n\t\t\t\t//cout <<\"size\" << st.size() << endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t//cout << \"size\" << st.size() << endl;\n\t\t\tstringstream ss(line);\n\n\t\t\twhile (ss.good()) {\n\t\t\t\t//std::string::size_type sz;\n\t\t\t\tstring sbstr;\n\t\t\t\tgetline(ss, sbstr, ',');\n\t\t\t\tfloat val = stof(sbstr);\n\t\t\t\trow.push_back(val);\n\t\t\t}\n\n\t\t\tst.push_back(row);\n\n\t\t}\n\n\t\tMatrix = weights;\n\t}\n\n\tvoid read_activations(vector<vector<float>>& Act, string name) {\n\t\tvector<vector<float>> A;\n\t\tifstream ip(name + \".txt\");\n\t\twhile (ip.good()) {\n\t\t\tvector<float> st;\n\t\t\tstring line;\n\t\t\tgetline(ip, line, '\\n');\n\t\t\tif (line == \"\") break;\n\t\t\tstringstream ss(line);\n\t\t\t//cout << line << endl;\n\t\t\twhile (ss.good()) {\n\t\t\t\tstd::string::size_type sz;\n\t\t\t\tstring sbstr;\n\t\t\t\tgetline(ss, sbstr, ',');\n\t\t\t\tfloat val = stof(sbstr);\n\t\t\t\tst.push_back(val);\n\t\t\t}\n\t\t\tA.push_back(st);\n\t\t}\n\n\t\tAct = A;\n\n\t}\n\n\tvoid save_model(string name) {\n\t\tsave_weights_der(weights, name + \"_weights\");\n\t\tsave_weights_der(derivatives, name + \"_derivatives\");\n\t\tsave_weights_der(seed_weights, name + \"_seed_weights\");\n\t\tsave_weights_der(seed_derivatives, name + \"_seed_derivatives\");\n\t\tsave_activations(activations, name + \"_activations\");\n\t\tsave_activations(seed_activations, name + \"_seed_activations\");\n\t\t\n\t}\n\n\tvoid load_model(string name) {\n\t\tread_weights_der(weights, name + \"_weights\");\n\t\tread_weights_der(seed_weights, name + \"_seed_weights\");\n\t\tread_weights_der(derivatives, name + \"_derivatives\");\n\t\tread_weights_der(seed_derivatives, name + \"_seed_derivatives\");\n\t\tread_activations(activations, name + \"_activations\");\n\t\tread_activations(seed_activations, name + \"_seed_activations\");\n\t}\n\n};\n\n//new stuff\nvoid read_files(string filename, vector<vector<float>>& inputs, vector<vector<float>>& targets) {\n\tifstream ip(filename);\n\n\tif (!ip.is_open()) cout << \"Error\" << endl;\n\telse cout << \"Yay\" << endl;\n\n\tip.ignore(500, '\\n');\n\t//vector<vector<float>> inputs;\n\tvector<string> st;\n\twhile (ip.good()) {\n\t\tvector<float> st;\n\t\tstring line;\n\t\tgetline(ip, line, '\\n');\n\t\tif (line == \"\") break;\n\t\tstringstream ss(line);\n\t\t//cout << line << endl;\n\t\twhile (ss.good()) {\n\t\t\tstd::string::size_type sz;\n\t\t\tstring sbstr;\n\t\t\tgetline(ss, sbstr, ',');\n\t\t\tfloat val = stof(sbstr);\n\t\t\tst.push_back(val);\n\t\t}\n\t\t//cout << st.size() << endl;\n\t\tinputs.push_back(st);\n\t}\n\tip.close();\n\tcout <<\"number of rows: \" << inputs.size() << endl;\n\t//vector<vector<float>> targets;\n\tfor (int tar = 0; tar < inputs.size(); tar++) {\n\t\tvector<float> t;\n\t\tt.push_back(inputs[tar].back());\n\t\ttargets.push_back(t);\n\t\tinputs[tar].pop_back();\n\t}\n\treturn;\n}\n\nANG Train_ng(vector<vector<float>> inputs, vector<vector<float>> targets, vector<int> hidden_layers) {\n\n\tANG ang(hidden_layers, targets[0].size(), inputs[0].size());\n\tang.ANG_grow(inputs, targets, hidden_layers);\n\n\treturn ang;\n}\n\nvector<int> test(ANG ang, vector<vector<float>> inputs) {\n\tvector<int> pred;\n\n\tfor (int i = 0; i < inputs.size(); i++) {\n\t\tvector<float> output = ang.forward_propogate(inputs[i]);\n\t\t//cout << output[0] << endl;\n\t\tif (output[0] >= 0.5) pred.push_back(1);\n\t\telse pred.push_back(0);\n\t}\n\treturn pred;\n}\n\nint main()\n{\n\tcout << \"Hello \\n\";\n\tANG ang;\n\t//vector<vector<float>> inputs, targets;\n\t//string filename = \"D:/Tests/Titanic/train_titanic.csv\";\n\t//read_files(filename, inputs, targets);\n\t//ang.PrintMatrix(inputs);\n\tvector<vector<float>>  i = { {1, 1, 1}, {0, 0, 0}, {1, 1, 1} , {0,0,0} ,{1,1,1}, {1,1,1} , {0,0,0}, {0,0,0} ,{1,1,1} , {0,0,0}, {1, 1, 1}, {0, 0, 0}, {1, 1, 1} , { 0,0,0} ,{1,1,1}, {1,1,1} , {0,0,0}, {0,0,0} ,{1,1,1} , {0,0,0}, {1, 1, 1}, {0, 0, 0}, {1, 1, 1} , { 0,0,0} ,{1,1,1}, {1,1,1} , {0,0,0}, {0,0,0} ,{1,1,1} , {0,0,0}, {1, 1, 1}, {0, 0, 0}, {1, 1, 1} , { 0,0,0} ,{1,1,1}, {1,1,1} , {0,0,0}, {0,0,0} ,{1,1,1} , {0,0,0}, {1, 1, 1}, {0, 0, 0}, {1, 1, 1} , { 0,0,0} ,{1,1,1}, {1,1,1} , {0,0,0}, {0,0,0} ,{1,1,1} , {0,0,0} };\n\tvector<vector<float>> t = { {1} , {0}, {0} , {0}, {1}, {1}, {0} , {0}, {1}, {0}, {1} , {0}, {1} , {0}, {1}, {1}, {0} , {0}, {1}, {0}, {1} , {0}, {1} , {0}, {1}, {1}, {0} , {0}, {1}, {0}, {1} , {0}, {1} , {0}, {1}, {1}, {0} , {0}, {1}, {0}, {1} , {0}, {1} , {0}, {1}, {1}, {0} , {0}, {1}, {0} };\n\tang = Train_ng(i, t, {3,4});\n\t//std::ostringstream oss;\n\t//ang.save(oss);\n\tang.save_model(\"saveloadtest\");\n\t//string s = oss.str();\n\tANG ang2;\n\t//std::istringstream iss;\n\t//iss.str(s);\n\t//ang2.load(iss);\n\tang2.load_model(\"saveloadtest\");\n\t/*\n\tcout << \"weights\" << endl;\n\tang2.Print3D(ang2.weights);\n\tcout << \"seed_weights\" << endl;\n\tang2.Print3D(ang2.seed_weights);\n\tcout << \"derivatives\" << endl;\n\tang2.Print3D(ang2.derivatives);\n\tcout << \"seed_derivatives\" << endl;\n\tang2.Print3D(ang2.seed_derivatives);\n\tcout << \"activations\" << endl;\n\tang2.PrintMatrix(ang2.activations);\n\tcout << \"seed_activations\" << endl;\n\tang2.PrintMatrix(ang2.seed_activations);\n\t*/\n\tvector<int> pred1 = test(ang, i);\n\tfor (int i = 0; i < pred1.size(); i++) cout << pred1[i] << \" \";\n\tcout << endl;\n\tvector<int> pred = test(ang2, i);\n\tfor (int i = 0; i < pred.size(); i++) cout << pred[i] << \" \";\n\t//ang.ANG_grow(i, t, {3,3});\n\t//ang.create_seed();\n\t//ang.create_temp_classifier_seed(t);\n\t//cout << ang.seed_activations.size() << endl;\n\t//ang.train_seed(i, t, 10, 0.1);\n\t//vector<vector<vector<float>>> emc = ang.extreme_member_classes(i, t);\n\t//cout << emc.size() << endl;\n\t//ang.add_class_layer(t);\n\t//ang.train(i, t, 10, 1.0);\n\t//ang.PrintVector(ang.activations.back());\n\t//vector<vector<float>> p = ang.dot_new(a, b);\n\t//ang.PrintMatrix(p);\n\t//vector<vector<float>> trans = ang.transpose(b);\n\t//ang.PrintMatrix(trans);\n\t//vector<float> t = {1 ,0, 1, 4, 5};\n\t//sort(t.begin(), t.end());\n\t//vector<float>::iterator ip = std::unique(t.begin(), t.end());\n\t//t.resize(std::distance(t.begin(), ip));\n\t//ang.PrintVector(t);\n\t//vector<int> ind;\n\t//ind = ang.sorted_index(5, t);\n\t//for (int i = 0; i < ind.size(); i++) cout << ind[i] << \" \";\n\treturn 0;\n}\n", "meta": {"hexsha": "914fa793e7e0d1a35f94580c8fdb2e10c5bbdb4b", "size": 34974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ArtificialNeurogenesis.cpp", "max_stars_repo_name": "rohanphil/Artificial-Neurogenesis", "max_stars_repo_head_hexsha": "46770d09e239e4402156a1fcef54b98851c4f37f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ArtificialNeurogenesis.cpp", "max_issues_repo_name": "rohanphil/Artificial-Neurogenesis", "max_issues_repo_head_hexsha": "46770d09e239e4402156a1fcef54b98851c4f37f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ArtificialNeurogenesis.cpp", "max_forks_repo_name": "rohanphil/Artificial-Neurogenesis", "max_forks_repo_head_hexsha": "46770d09e239e4402156a1fcef54b98851c4f37f", "max_forks_repo_licenses": ["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.9397260274, "max_line_length": 530, "alphanum_fraction": 0.6059644307, "num_tokens": 10819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5061449685882904}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2008-2014 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2008-2014 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2009-2014 Mateusz Loskot, London, UK.\r\n\r\n// This file was modified by Oracle on 2014.\r\n// Modifications copyright (c) 2014, Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\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_DISTANCE_PROJECTED_POINT_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DISTANCE_PROJECTED_POINT_HPP\r\n\r\n\r\n#include <boost/concept_check.hpp>\r\n#include <boost/core/ignore_unused.hpp>\r\n#include <boost/mpl/if.hpp>\r\n#include <boost/type_traits/is_void.hpp>\r\n\r\n#include <boost/geometry/core/access.hpp>\r\n#include <boost/geometry/core/point_type.hpp>\r\n\r\n#include <boost/geometry/algorithms/convert.hpp>\r\n#include <boost/geometry/arithmetic/arithmetic.hpp>\r\n#include <boost/geometry/arithmetic/dot_product.hpp>\r\n\r\n#include <boost/geometry/strategies/tags.hpp>\r\n#include <boost/geometry/strategies/distance.hpp>\r\n#include <boost/geometry/strategies/default_distance_result.hpp>\r\n#include <boost/geometry/strategies/cartesian/distance_pythagoras.hpp>\r\n\r\n#include <boost/geometry/util/select_coordinate_type.hpp>\r\n\r\n// Helper geometry (projected point on line)\r\n#include <boost/geometry/geometries/point.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n\r\nnamespace strategy { namespace distance\r\n{\r\n\r\n/*!\r\n\\brief Strategy for distance point to segment\r\n\\ingroup strategies\r\n\\details Calculates distance using projected-point method, and (optionally) Pythagoras\r\n\\author Adapted from: http://geometryalgorithms.com/Archive/algorithm_0102/algorithm_0102.htm\r\n\\tparam CalculationType \\tparam_calculation\r\n\\tparam Strategy underlying point-point distance strategy\r\n\\par Concepts for Strategy:\r\n- cartesian_distance operator(Point,Point)\r\n\\note If the Strategy is a \"comparable::pythagoras\", this strategy\r\n    automatically is a comparable projected_point strategy (so without sqrt)\r\n\r\n\\qbk{\r\n[heading See also]\r\n[link geometry.reference.algorithms.distance.distance_3_with_strategy distance (with strategy)]\r\n}\r\n\r\n*/\r\ntemplate\r\n<\r\n    typename CalculationType = void,\r\n    typename Strategy = pythagoras<CalculationType>\r\n>\r\nclass projected_point\r\n{\r\npublic :\r\n    // The three typedefs below are necessary to calculate distances\r\n    // from segments defined in integer coordinates.\r\n\r\n    // Integer coordinates can still result in FP distances.\r\n    // There is a division, which must be represented in FP.\r\n    // So promote.\r\n    template <typename Point, typename PointOfSegment>\r\n    struct calculation_type\r\n        : promote_floating_point\r\n          <\r\n              typename strategy::distance::services::return_type\r\n                  <\r\n                      Strategy,\r\n                      Point,\r\n                      PointOfSegment\r\n                  >::type\r\n          >\r\n    {};\r\n\r\n    template <typename Point, typename PointOfSegment>\r\n    inline typename calculation_type<Point, PointOfSegment>::type\r\n    apply(Point const& p, PointOfSegment const& p1, PointOfSegment const& p2) const\r\n    {\r\n        assert_dimension_equal<Point, PointOfSegment>();\r\n\r\n        typedef typename calculation_type<Point, PointOfSegment>::type calculation_type;\r\n\r\n        // A projected point of points in Integer coordinates must be able to be\r\n        // represented in FP.\r\n        typedef model::point\r\n            <\r\n                calculation_type,\r\n                dimension<PointOfSegment>::value,\r\n                typename coordinate_system<PointOfSegment>::type\r\n            > fp_point_type;\r\n\r\n        // For convenience\r\n        typedef fp_point_type fp_vector_type;\r\n\r\n        /*\r\n            Algorithm [p: (px,py), p1: (x1,y1), p2: (x2,y2)]\r\n            VECTOR v(x2 - x1, y2 - y1)\r\n            VECTOR w(px - x1, py - y1)\r\n            c1 = w . v\r\n            c2 = v . v\r\n            b = c1 / c2\r\n            RETURN POINT(x1 + b * vx, y1 + b * vy)\r\n        */\r\n\r\n        // v is multiplied below with a (possibly) FP-value, so should be in FP\r\n        // For consistency we define w also in FP\r\n        fp_vector_type v, w, projected;\r\n\r\n        geometry::convert(p2, v);\r\n        geometry::convert(p, w);\r\n        geometry::convert(p1, projected);\r\n        subtract_point(v, projected);\r\n        subtract_point(w, projected);\r\n\r\n        Strategy strategy;\r\n        boost::ignore_unused(strategy);\r\n\r\n        calculation_type const zero = calculation_type();\r\n        calculation_type const c1 = dot_product(w, v);\r\n        if (c1 <= zero)\r\n        {\r\n            return strategy.apply(p, p1);\r\n        }\r\n        calculation_type const c2 = dot_product(v, v);\r\n        if (c2 <= c1)\r\n        {\r\n            return strategy.apply(p, p2);\r\n        }\r\n\r\n        // See above, c1 > 0 AND c2 > c1 so: c2 != 0\r\n        calculation_type const b = c1 / c2;\r\n\r\n        multiply_value(v, b);\r\n        add_point(projected, v);\r\n\r\n        return strategy.apply(p, projected);\r\n    }\r\n\r\n    template <typename CT>\r\n    inline CT vertical_or_meridian(CT const& lat1, CT const& lat2) const\r\n    {\r\n        return lat1 - lat2;\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, typename Strategy>\r\nstruct tag<projected_point<CalculationType, Strategy> >\r\n{\r\n    typedef strategy_tag_distance_point_segment type;\r\n};\r\n\r\n\r\ntemplate <typename CalculationType, typename Strategy, typename P, typename PS>\r\nstruct return_type<projected_point<CalculationType, Strategy>, P, PS>\r\n    : projected_point<CalculationType, Strategy>::template calculation_type<P, PS>\r\n{};\r\n\r\n\r\n\r\ntemplate <typename CalculationType, typename Strategy>\r\nstruct comparable_type<projected_point<CalculationType, Strategy> >\r\n{\r\n    // Define a projected_point strategy with its underlying point-point-strategy\r\n    // being comparable\r\n    typedef projected_point\r\n        <\r\n            CalculationType,\r\n            typename comparable_type<Strategy>::type\r\n        > type;\r\n};\r\n\r\n\r\ntemplate <typename CalculationType, typename Strategy>\r\nstruct get_comparable<projected_point<CalculationType, Strategy> >\r\n{\r\n    typedef typename comparable_type\r\n        <\r\n            projected_point<CalculationType, Strategy>\r\n        >::type comparable_type;\r\npublic :\r\n    static inline comparable_type apply(projected_point<CalculationType, Strategy> const& )\r\n    {\r\n        return comparable_type();\r\n    }\r\n};\r\n\r\n\r\ntemplate <typename CalculationType, typename Strategy, typename P, typename PS>\r\nstruct result_from_distance<projected_point<CalculationType, Strategy>, P, PS>\r\n{\r\nprivate :\r\n    typedef typename return_type<projected_point<CalculationType, Strategy>, P, PS>::type return_type;\r\npublic :\r\n    template <typename T>\r\n    static inline return_type apply(projected_point<CalculationType, Strategy> const& , T const& value)\r\n    {\r\n        Strategy s;\r\n        return result_from_distance<Strategy, P, PS>::apply(s, value);\r\n    }\r\n};\r\n\r\n\r\n// Get default-strategy for point-segment distance calculation\r\n// while still have the possibility to specify point-point distance strategy (PPS)\r\n// It is used in algorithms/distance.hpp where users specify PPS for distance\r\n// of point-to-segment or point-to-linestring.\r\n// Convenient for geographic coordinate systems especially.\r\ntemplate <typename Point, typename PointOfSegment, typename Strategy>\r\nstruct default_strategy\r\n    <\r\n        point_tag, segment_tag, Point, PointOfSegment,\r\n        cartesian_tag, cartesian_tag, Strategy\r\n    >\r\n{\r\n    typedef strategy::distance::projected_point\r\n    <\r\n        void,\r\n        typename boost::mpl::if_\r\n            <\r\n                boost::is_void<Strategy>,\r\n                typename default_strategy\r\n                    <\r\n                        point_tag, point_tag, Point, PointOfSegment,\r\n                        cartesian_tag, cartesian_tag\r\n                    >::type,\r\n                Strategy\r\n            >::type\r\n    > type;\r\n};\r\n\r\ntemplate <typename PointOfSegment, typename Point, typename Strategy>\r\nstruct default_strategy\r\n    <\r\n        segment_tag, point_tag, PointOfSegment, Point,\r\n        cartesian_tag, cartesian_tag, Strategy\r\n    >\r\n{\r\n    typedef typename default_strategy\r\n        <\r\n            point_tag, segment_tag, Point, PointOfSegment,\r\n            cartesian_tag, cartesian_tag, Strategy\r\n        >::type type;\r\n};\r\n\r\n\r\n} // namespace services\r\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\n\r\n}} // namespace strategy::distance\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DISTANCE_PROJECTED_POINT_HPP\r\n", "meta": {"hexsha": "c85780dafc66359a3350f61180be2829d0aa5593", "size": 9053, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost/boost/geometry/strategies/cartesian/distance_projected_point.hpp", "max_stars_repo_name": "YuukiTsuchida/v8_embeded", "max_stars_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "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": "externals/boost/boost/geometry/strategies/cartesian/distance_projected_point.hpp", "max_issues_repo_name": "YuukiTsuchida/v8_embeded", "max_issues_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "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": "externals/boost/boost/geometry/strategies/cartesian/distance_projected_point.hpp", "max_forks_repo_name": "YuukiTsuchida/v8_embeded", "max_forks_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-06-19T05:06:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T03:29:19.000Z", "avg_line_length": 31.7649122807, "max_line_length": 104, "alphanum_fraction": 0.6659670827, "num_tokens": 1942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5061449584941983}}
{"text": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <cmath>\n\n#include <Eigen/Dense>\n\n#include \"variablesExt.h\"\n#include \"recContours.h\"\n#include \"pathfinding.h\"\n\nusing namespace cv;\nusing namespace std;\nusing namespace Eigen;\n\nvoid pathfinding(double offset)\n{\n\tcout << \"--- Nouveau path ---\" << endl;\n\tconvexHull(approxPoly, approxConvex, false, false); // on approxime par un poly convexe\n\tif(approxConvex.size() < 3) return; // si ce n'est pas au moins un triangle on sort\n\t\n\tPoint A1,A2,B1,B2,L1,L2;\n\t\n\tA1 = approxConvex[0]; \n\tA2 = approxConvex[approxConvex.size()-1];\n\tB1 = approxConvex[1];\n\tB2 = approxConvex[2];\n\tsize_t iB2 = 2;\n\tsize_t iA2 = approxConvex.size()-1;\n\t\n\tVector2d vOffset = offsetVector(A1,B1,offset);\n\tVector2d vAB = points2Vec(A1,B1);\n\t\n\tpath.clear();\n\t\n\t// on commence par aller de A1 \u00e0 B1\n\t\n\tpath.push_back(A1);\n\tpath.push_back(B1);\n\t\n\tbool continuer = true;\n\tbool altern = true;\n\t\n\tPoint B = B1;\n\tint cmpt = 1;\n\t\n\twhile(continuer)\n\t{\t\n\t\t// on recherche les points d'intersection de la parall\u00e8le \u00e0 A1B1 d\u00e9cal\u00e9e de vOffset\n\t\n\t\tPoint O = vec2Point(B, vOffset*cmpt); // \u00e0 partir du point 0, on cherche ces points\n\t\tVector2d vB12 = points2Vec(B1,B2); // on a besoin de croiser vB12 avec vAB, on v\u00e9rifie qu'ils ne sont pas colin\u00e9aires\n\t\tVector2d vA12 = points2Vec(A1,A2);\n\t\n\t\tif(vAB == vB12 || vAB == vA12 || vAB == vB12 * -1 || vAB == vA12 * -1)\n\t\t{\n\t\t\tcout << \"vecteurs colineaires\" << endl;\n\t\t\tcontinuer = false; // c'est possible mais \u00e7a signifie qu'on est arriv\u00e9 au bout du champ\n\t\t}\n\t\telse\n\t\t{\t\n\t\t\tMatrix4d MB;\n\t\t\tMB << \t1,-1*vAB[0],0,0,\n\t\t\t\t1,0,0,-1*vB12[0],\n\t\t\t\t0,-1*vAB[1],1,0,\n\t\t\t\t0,0,1,-1*vB12[1];\n\t\t\t//cout << \"MB : \" << endl << MB << endl;\n\t\n\t\t\tVector4d CB;\n\t\t\tCB << O.x,B1.x,O.y,B1.y;\n\t\t\t//cout << \"CB : \" << endl << CB << endl;\n\t\n\t\t\tFullPivLU<Matrix4d> decompositionB(MB);\n\n\t\t    \tVector4d XB = decompositionB.solve(CB); // X : (x, t, y, t')\n\t\t    \tcout << \"XB : \" << endl << XB << endl;\n\t\t    \t\n\t\t    \tMatrix4d MA;\n\t\t\tMA << \t1,-1*vAB[0],0,0,\n\t\t\t\t1,0,0,-1*vA12[0],\n\t\t\t\t0,-1*vAB[1],1,0,\n\t\t\t\t0,0,1,-1*vA12[1];\n\t\t\t//cout << \"MA : \" << endl << MA << endl;\n\t\n\t\t\tVector4d CA;\n\t\t\tCA << O.x,A1.x,O.y,A1.y;\n\t\t\t//cout << \"CA : \" << endl << CA << endl;\n\t\n\t\t\tFullPivLU<Matrix4d> decompositionA(MA);\n\n\t\t    \tVector4d XA = decompositionA.solve(CA); // X : (x, t, y, t')\n\t\t    \tcout << \"XA : \" << endl << XA << endl;\n\t\t    \t\n\t\t    \tPoint BB = Point(XB[0],XB[2]);\n\t\t    \tPoint AA = Point(XA[0],XA[2]);\t    \t\n\t\t    \t\n\t\t    \t// il faut regarder si on est sorti de l'une des deux ar\u00eates\n\t\t    \t\n\t\t    \tVector2d vNBB = points2VecN(B1,BB);\n\t\t    \tVector2d vNAA = points2VecN(A1,AA);\n\t\t    \tVector2d vNB12 = points2VecN(B1,B2);\n\t\t    \tVector2d vNA12 = points2VecN(A1,A2);\n\t\t    \t\n\t\t    \tif(vNBB.squaredNorm() > vNB12.squaredNorm())\n\t\t    \t{\n\t\t    \t\tiB2++;\n\t\t    \t\tB1 = B2;\n\t\t    \t\tB2 = approxConvex[iB2];\n\t\t    \t\tif(iA2 >= iB2) continue;\n\t\t    \t}\n\t\t    \telse\n\t\t    \t{\n\t\t    \t\tB1 = BB;\n\t\t    \t}\n\t\t    \t\n\t\t    \tif(vNAA.squaredNorm() > vNA12.squaredNorm())\n\t\t    \t{\n\t\t    \t\tiA2--;\n\t\t    \t\tA1 = A2;\n\t\t    \t\tA2 = approxConvex[iA2];\n\t\t    \t\tif(iA2 >= iB2) continue;\n\t\t    \t}\n\t\t    \telse\n\t\t    \t{\n\t\t    \t\tA1 = AA;\n\t\t    \t}\n\t\t    \t\n\t\t    \tif(iA2 < iB2) // on est arriv\u00e9 au bout du champ\n\t\t    \t{\n\t\t    \t\tcontinuer = false;\n\t\t    \t\tcout << \"iA2:\"<<iA2<<\"<iB2:\"<<iB2<<endl;\n\t\t    \t\tbreak;\n\t\t    \t}\n\t\t    \t\n\t\t    \t// ici, on v\u00e9rifie que nos points sont dans l'approxPoly, s'ils n'y sont pas, on les force \u00e0 y rentrer.\n\t\t    \tdouble distAA = pointPolygonTest(approxPoly, AA, true);\n\t\t    \tif(distAA < 0)\n\t\t    \t{\n\t\t    \t\t// on cherche le point d'intersection entre AA-BB et l'approxPoly (\u00e0 la bourrin)\n\t\t    \t\tint t = 0;\n\t\t    \t\twhile(true)\n\t\t    \t\t{\n\t\t    \t\t\tt++;\n\t\t\t    \t\t//Point AAA = vec2Point(AA, t * vAB);\n\t\t\t    \t\tPoint AAA = vec2Point(AA, t * points2Vec(AA,BB));\n\t\t\t    \t\tdouble distAAA = pointPolygonTest(approxPoly, AAA, true);\n\t\t\t    \t\t\n\t\t\t    \t\tAA = AAA;\n\t\t\t    \t\t\n\t\t\t    \t\tif(distAAA >= 0)\n\t\t\t    \t\t{\n\t\t\t    \t\t\tcout << \"On est rentr\u00e9 dans le polygone pour AA\" << endl;\n\t\t\t    \t\t\tbreak;\n\t\t\t    \t\t}\n\t\t\t    \t\telse if(distAAA < distAA - 1000)\n\t\t\t    \t\t{\n\t\t\t    \t\t\tcout << \"ERREUR : on s'eloigne !\" << endl;\n\t\t\t    \t\t\tbreak;\n\t\t\t    \t\t}\n\t\t    \t\t}\n\t\t    \t}\n\t\t    \tdouble distBB = pointPolygonTest(approxPoly, BB, true);\n\t\t    \tif(distBB < 0)\n\t\t    \t{\n\t\t    \t\t// on cherche le point d'intersection entre AA-BB et l'approxPoly (\u00e0 la bourrin)\n\t\t    \t\tint t = 0;\n\t\t    \t\twhile(true)\n\t\t    \t\t{\n\t\t    \t\t\tt++;\n\t\t\t    \t\t//Point BBB = vec2Point(BB, (-1*t) * vAB);\n\t\t\t    \t\tPoint BBB = vec2Point(BB, t * points2Vec(BB,AA));\n\t\t\t    \t\tdouble distBBB = pointPolygonTest(approxPoly, BBB, true);\n\t\t\t    \t\t\n\t\t\t    \t\tBB = BBB;\n\t\t\t    \t\t\n\t\t\t    \t\tif(distBBB >= 0)\n\t\t\t    \t\t{\n\t\t\t    \t\t\tcout << \"On est rentr\u00e9 dans le polygone pour BB\" << endl;\n\t\t\t    \t\t\tbreak;\n\t\t\t    \t\t}\n\t\t\t    \t\telse if(distBBB < distBB - 1000)\n\t\t\t    \t\t{\n\t\t\t    \t\t\tcout << \"ERREUR : on s'eloigne !\" << endl;\n\t\t\t    \t\t\tbreak;\n\t\t\t    \t\t}\n\t\t    \t\t}\n\t\t    \t}\n\t\t    \t\n\t\t    \tif(altern)\n\t\t    \t{\n\t\t\t    \tpath.push_back(BB);\n\t\t\t    \tpath.push_back(AA);\n\t\t\t    \tcout << \"nouveau trait : \" << BB<< \"-\"<< AA<<endl;\n\t\t    \t}\n\t\t    \telse\n\t\t    \t{\n\t\t    \t\tpath.push_back(AA);\n\t\t\t    \tpath.push_back(BB);\n\t\t\t    \tcout << \"nouveau trait : \" << AA<< \"-\"<< BB<<endl;\n\t\t    \t}\n\t    \t}\n    \taltern = !altern;\n    \tcmpt++;\n    \t\n    \tcv::polylines(rgb_copy, path, false, Scalar(0,255,0), 1, LINE_8, 0);\n\tdisplayPicture(0,NULL);\n    \t\n    \t//cv::waitKey(0);\n    \t}\n}\n\nPoint vec2Point(Point depart, Vector2d vec)\n{\n\tdouble lx = (double)depart.x + vec[0];\n\tdouble ly = (double)depart.y + vec[1];\n\t\n\treturn Point(ceil(lx),ceil(ly)); \n}\n\nVector2d points2Vec(Point A, Point B) // transforme AB en vecteur unitaire\n{\n\tdouble moduleX = (B.x - A.x);\n\tdouble moduleY = (B.y - A.y);\n\tdouble module = sqrt(moduleX*moduleX + moduleY*moduleY);\n\t\n\tVector2d V;\n\tV[0] = moduleX/module;\n\tV[1] = moduleY/module;\n\t\n\treturn V;\n}\n\nVector2d points2VecN(Point A, Point B) // transforme AB en vecteur norm\u00e9\n{\n\tdouble moduleX = (B.x - A.x);\n\tdouble moduleY = (B.y - A.y);\n\t\n\tVector2d V;\n\tV[0] = moduleX;\n\tV[1] = moduleY;\n\t\n\treturn V;\n}\n\nVector2d offsetVector(Point A, Point B, double offset) // (unitaire) A et B sont les points de l'arr\u00eate \u00e0 couper, leur ordre spatial ne change pas, et le polygone est cod\u00e9 en sens horraire\n{\n\tVector2d edge = points2Vec(A,B);\n\t\n\tVector2d voffset;\n\t\n\tvoffset[0] = (-1 * edge[1]) * offset;\n\tvoffset[1] = (edge[0]) * offset;\n\t\n\treturn voffset;\n}\n\n\n", "meta": {"hexsha": "dde4c1f490069663a15ecd411fb760bdc0e1b79e", "size": 6538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "feteScience/imgRec/pathfinding.cpp", "max_stars_repo_name": "coumbsek/ISMIN-AREM", "max_stars_repo_head_hexsha": "7fe64344e1c0eb03db000611df4aa8c6664d5108", "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": "feteScience/imgRec/pathfinding.cpp", "max_issues_repo_name": "coumbsek/ISMIN-AREM", "max_issues_repo_head_hexsha": "7fe64344e1c0eb03db000611df4aa8c6664d5108", "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": "feteScience/imgRec/pathfinding.cpp", "max_forks_repo_name": "coumbsek/ISMIN-AREM", "max_forks_repo_head_hexsha": "7fe64344e1c0eb03db000611df4aa8c6664d5108", "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.9541984733, "max_line_length": 188, "alphanum_fraction": 0.5448149281, "num_tokens": 2184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694177, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5060855701526707}}
{"text": "/* Copyright \u00a9 2019 Apple Inc. All rights reserved.\n *\n * Use of this source code is governed by a BSD-3-clause license that can\n * be found in the LICENSE.txt file or at\n * https://opensource.org/licenses/BSD-3-Clause\n */\n\n#ifndef TURI_ONE_SHOT_MAPPING_FUNCTION_H_\n#define TURI_ONE_SHOT_MAPPING_FUNCTION_H_\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <random>\n#include <vector>\n\n#include <boost/gil/gil_all.hpp>\n\nnamespace boost {\nnamespace gil {\n\n/* Matrix - Vector multiplication */\ntemplate <typename T, typename F>\nboost::gil::point2<F> operator*(const boost::gil::point2<T>& p,\n                                const Eigen::Matrix<F, 3, 3>& m) {\n  float denominator = m(2, 0) * p.x + m(2, 1) * p.y + m(2, 2);\n  if (denominator == 0) {\n    // TODO: Figure out the right failure behavior for when denominator is 0.\n    return boost::gil::point2<F>(0, 0);\n  }\n  return boost::gil::point2<F>(\n      (m(0, 0) * p.x + m(0, 1) * p.y + m(0, 2)) / denominator,\n      (m(1, 0) * p.x + m(1, 1) * p.y + m(1, 2)) / denominator);\n}\n\n/* Conforming to the MapFn concept required by Boost GIL, for Eigen::Matrix3f\n */\ntemplate <typename T>\nstruct mapping_traits;\n\ntemplate <typename F, typename F2>\nboost::gil::point2<F> transform(const Eigen::Matrix<F, 3, 3>& mat,\n                                const boost::gil::point2<F2>& src) {\n  return src * mat;\n}\n\ntemplate <typename F>\nstruct mapping_traits<Eigen::Matrix<F, 3, 3> > {\n  using result_type = boost::gil::point2<F>;\n};\n\n}  // namespace gil\n}  // namespace boost\n\n#endif  // TURI_ONE_SHOT_MAPPING_FUNCTION_H_", "meta": {"hexsha": "9c1a2589d21e0a17a06e38083632ffaa23b18c16", "size": 1621, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/toolkits/object_detection/one_shot_object_detection/util/mapping_function.hpp", "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/toolkits/object_detection/one_shot_object_detection/util/mapping_function.hpp", "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/toolkits/object_detection/one_shot_object_detection/util/mapping_function.hpp", "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": 27.9482758621, "max_line_length": 77, "alphanum_fraction": 0.6477483035, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5060855679493061}}
{"text": "#include <ql/quantlib.hpp>\n#include <boost/make_shared.hpp>\n\nusing namespace QuantLib;\n\nint main() {\n\n    Date refDate(24, August, 2015);\n\n    Settings::instance().evaluationDate() = refDate;\n\n    Handle<YieldTermStructure> yts(\n        boost::make_shared<FlatForward>(refDate, 0.02, Actual365Fixed()));\n\n    boost::shared_ptr<IborIndex> euribor6m =\n        boost::make_shared<Euribor>(6 * Months, yts);\n\n    Handle<OptionletVolatilityStructure> capletVol(\n        boost::make_shared<ConstantOptionletVolatility>(\n            refDate, TARGET(), Following, 0.40, Actual365Fixed()));\n\n    Real rho = atof(getenv(\"RHO\"));\n    boost::shared_ptr<SimpleQuote> correlationQuote =\n        boost::make_shared<SimpleQuote>(rho);\n    Handle<Quote> correlation(correlationQuote);\n\n    Date startDate =\n        TARGET().advance(TARGET().advance(refDate, 2 * Days), 10 * Years);\n    Date endDate = TARGET().advance(startDate, 6 * Months);\n    Natural fixingDays = 2;\n\n    boost::shared_ptr<IborCoupon> coupon = boost::make_shared<IborCoupon>(\n        endDate, 1.0, startDate, endDate, fixingDays, euribor6m, 1.0, 0.0,\n        Date(), Date(), DayCounter(), true);\n\n    boost::shared_ptr<IborCouponPricer> black76Pricer =\n        boost::make_shared<BlackIborCouponPricer>(\n            capletVol, BlackIborCouponPricer::Black76);\n    boost::shared_ptr<IborCouponPricer> bivariateLnPricer =\n        boost::make_shared<BlackIborCouponPricer>(\n            capletVol, BlackIborCouponPricer::BivariateLognormal, correlation);\n\n    coupon->setPricer(black76Pricer);\n    std::clog << \"coupon fixing  = \" << coupon->fixingDate() << std::endl;\n    std::clog << \"coupon start   = \" << coupon->accrualStartDate() << std::endl;\n    std::clog << \"coupon end     = \" << coupon->accrualEndDate() << std::endl;\n    std::clog << \"coupon payment = \" << coupon->date() << std::endl;\n\n    std::clog << \"Black76: fixing = \" << coupon->indexFixing()\n              << \" adjustment = \" << coupon->convexityAdjustment() << std::endl;\n\n    Date paymentDate = startDate;\n\n    while (paymentDate <= TARGET().advance(endDate, 6 * Months)) {\n        boost::shared_ptr<IborCoupon> coupon = boost::make_shared<IborCoupon>(\n            paymentDate, 1.0, startDate, endDate, fixingDays, euribor6m, 1.0,\n            0.0, Date(), Date(), DayCounter(), false);\n        coupon->setPricer(bivariateLnPricer);\n        Real tau = Actual365Fixed().yearFraction(paymentDate, endDate);\n        if (tau >= 0.0) {\n            correlationQuote->setValue(rho + (1.0 - rho) * exp(-10.0 * tau));\n        } else {\n            correlationQuote->setValue(rho);\n        }\n        std::cout << \"\\\"\" << paymentDate << \"\\\" \"\n                  << yts->timeFromReference(paymentDate) << \" \"\n                  << coupon->indexFixing() << \" \"\n                  << coupon->convexityAdjustment() << std::endl;\n        paymentDate++;\n    }\n}\n", "meta": {"hexsha": "fce483139b19c0c2f1f4a6d7050e7da428bac163", "size": 2861, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/timingadj.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/timingadj.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/timingadj.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": 39.7361111111, "max_line_length": 80, "alphanum_fraction": 0.6239077246, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808498, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5060855591358474}}
{"text": "// -*- compile-command: \"c++ -std=c++14 -O3 -DNDEBUG -ffast-math -march=native lcp.cpp -o lcp `pkg-config --cflags eigen3` -lstdc++\" -*-\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <iostream>\n#include <array>\n\ntemplate<class U>\nstruct lcp {\n  using real = U;\n\n  template<int N>\n  using vector = Eigen::Matrix<real, N, 1>;\n\n  template<int N>\n  using indices = Eigen::Matrix<Eigen::Index, N, 1>;\n\n  template<int N>\n  using matrix = Eigen::Matrix<real, N, N>;\n\n\n  static void solve(vector<1>& x, const matrix<1>& M, const vector<1>& q) {\n    assert(M(0, 0) > 0);\n    x(0) = std::max<real>(0, -q(0) / M(0, 0));\n  }\n\n  template<int N>\n  static void solve(vector<N>& x, matrix<N> M, vector<N> q) {\n    static_assert(N > 1, \"size error\");\n    indices<N - 1> sub;\n    vector<N> w;\n\n    std::array<bool, N> active;\n    \n    for(std::size_t i = 0; i < N; ++i) {\n      // filter all but ith component\n      auto ptr = sub.data();\n      for(std::size_t j = 0; (j += (j == i)) < N; ++j, ++ptr) {\n        *ptr = j;\n      }\n\n      vector<N - 1> qq = sub.unaryExpr(q);\n      matrix<N - 1> MM;\n      for(int j = 0; j < N - 1; ++j) {\n        MM.col(j) = sub.unaryExpr(M.col(sub(j)));\n      }\n\n      vector<N - 1> xx;\n      solve(xx, MM, qq);\n\n      w(i) = std::max<real>(sub.unaryExpr(M.col(i)).dot(xx) + q(i), 0);\n      active[i] = w(i) == 0;\n    }\n\n    for(int i = 0; i < N; ++i) {\n      if(!active[i]) {\n        M.row(i) = vector<N>::Zero().transpose();\n        M.col(i) = vector<N>::Zero();\n        M(i, i) = 1;\n        q(i) = w(i);\n      }\n    }\n    \n    // TODO use LLT when N > 4?\n    x.noalias() = M.inverse() * (w - q);\n  }\n};\n\n\ntemplate<class U>\nstruct closest {\n  using real = U;\n  using vec3 = Eigen::Matrix<real, 3, 1>;\n  using vec2 = Eigen::Matrix<real, 2, 1>;\n  \n  using mat3x3 = Eigen::Matrix<real, 3, 3>;\n  using mat2x2 = Eigen::Matrix<real, 2, 2>;  \n\n  static double clamp(double x) {\n    return x;\n  }\n\n  // static real clamp(real x) {\n  //   return std::max<real>(x, 0);\n  // }\n\n\n  static void fast_lcp(vec3& x, mat3x3 M, vec3 q) {\n    const real x1[3] = {\n      clamp(-q(0) / M(0, 0)),\n      clamp(-q(1) / M(1, 1)),\n      clamp(-q(2) / M(2, 2)),\n    };\n\n    using vec2i = Eigen::Matrix<Eigen::Index, 2, 1>;\n    // TODO make this constexpr?\n    const vec2i ind[3] =  {{1, 2}, {0, 2}, {0, 1}};\n    \n    mat2x2 M2inv[3];\n    \n    vec2 x2[3];\n    vec3 w;\n    int skip = 0;\n    for(int i = 0; i < 3; ++i) {\n      mat2x2 sub;               // TODO optimize (symmetric)\n      for(int j = 0; j < 2; ++j) {\n        sub.col(j) = ind[i].unaryExpr(M.col(ind[i][j]));\n      }\n\n      vec2 w2;\n      for(int j = 0; j < 2; ++j) {\n        const int other = (j + 1) % 2;\n        // w2(j) = clamp(sub(j, other) * x1[ind[i][other]] + q(ind[i][j]));\n        w2(j) = clamp(M(ind[i][j], ind[i][other]) * x1[ind[i][other]] + q(ind[i][j]));        \n      }\n\n      // TODO optimize?\n      M2inv[i] = sub.inverse();\n      x2[i].noalias() = M2inv[i] * (w2 - ind[i].unaryExpr(q));\n      \n      w[i] = clamp(ind[i].unaryExpr(M.col(i)).dot(x2[i]) + q(i));\n\n      if(w[i] > 0) {\n        skip = i;\n      }\n\n    }\n\n    const vec2 res = M2inv[skip] * ind[skip].unaryExpr(w - q);\n    x[ind[skip][0]] = res[0];\n    x[ind[skip][1]] = res[1];    \n    x[skip] = 0;\n  }\n  \n  static vec3 project_triangle(vec3 a, vec3 b, vec3 c, vec3 p) {\n    const vec3* points[3] = {&a, &b, &c};\n    \n    const vec3 edges[3] = {\n      b - a,\n      c - b,\n      a - c\n    };\n\n    const vec3 n = edges[0].cross(edges[1]);\n    \n    mat3x3 JT;\n    for(int i = 0; i < 3; ++i) {\n      JT.col(i) = n.cross(edges[i]);\n    }\n    \n    vec3 bounds;\n\n    for(int i = 0; i < 3; ++i) {\n      bounds(i) = JT.col(i).dot(*points[i]);\n    }\n    \n    const mat3x3 M = JT.transpose() * JT;\n    const vec3 q = (JT.transpose() * p - bounds);\n\n    vec3 lambda;\n    // lcp<real>::solve(lambda, M, q);\n    fast_lcp(lambda, M, q);\n    \n    // std::clog << lambda.transpose() << std::endl;\n    // std::clog << (M * lambda + q).transpose() << std::endl;    \n    // std::clog << lambda.dot(M * lambda + q) << std::endl;\n    \n    const vec3 origin = a;\n    const vec3 delta = p - origin;\n    const vec3 proj = p - n * n.dot(delta) / n.dot(n);\n\n    return JT * lambda + proj;\n  }\n\n\n  struct projector_ref {\n    vec3 p1, p2, p3, p1p2, p1p3;\n    real distp1p2;\n    real fa, fb, fc;\n    real fdet;\n    \n    projector_ref(vec3 p1, vec3 p2, vec3 p3):\n        p1(p1),\n        p2(p2),\n        p3(p3),\n        p1p2(p2 - p1),\n        p1p3(p3 - p1),\n        distp1p2(p1p2.dot(p1p2)),\n        fa(distp1p2),\n        fb(p1p2.dot(p1p3)),\n        fc(p1p3.dot(p1p3)),\n        fdet(fa * fc - fb * fb) {\n\n    }\n\n    vec3 operator()(vec3 p) const {\n      const vec3 pp1 = p1 - p;\n      const real fd = p1p2.dot(pp1), fe = p1p3.dot(pp1);\n      real fs = fb * fe - fc * fd, ft = fb * fd - fa * fe;\n\n      if(fs + ft <= fdet) {\n        if(fs < 0) {\n          if(ft < 0) {\n            // region 4\n            if(fd < 0) {\n              ft = 0;\n              if(-fd >= fa) {\n                fs = 1;\n              } else {\n                fs = -fd / fa;\n              }\n            } else {\n              fs = 0;\n              if(fe >= 0) {\n                ft = 0;\n              } else if(-fe >= fc) {\n                ft = 1;\n              } else {\n                ft = -fe / fc;\n              }\n            }\n          } else {\n            // region 3\n            fs = 0;\n            if(fe >= 0) {\n              ft = 0;\n            } else if(-fe >= fc) {\n              ft = 1;\n            } else {\n              ft = -fe / fc;\n            }\n          }\n        } else if(ft < 0) {\n          // region 5\n          ft = 0;\n          if(fd >= 0) {\n            fs = 0;\n          } else if(-fd >= fa) {\n            fs = 1;\n          } else {\n            fs = -fd / fa;\n          }\n\n        } else {\n          // region 0\n          // minimum at interior point\n          fs /= fdet;\n          ft /= fdet;\n        }\n      } else {\n        real ftmp0, ftmp1, fNumer, fDenom;\n\n        if(fs < 0) {\n          // region 2\n          ftmp0 = fb + fd;\n          ftmp1 = fc + fe;\n          if(ftmp1 > ftmp0) {\n            fNumer = ftmp1 - ftmp0;\n            fDenom = fa - 2 * fb + fc;\n            if(fNumer >= fDenom) {\n              fs = 1;\n              ft = 0;\n            } else {\n              fs = fNumer / fDenom;\n              ft = 1 - fs;\n            }\n          } else {\n            fs = 0;\n            if(ftmp1 <= 0) {\n              ft = 1;\n            } else if(fe >= 0) {\n              ft = 0;\n            } else {\n              ft = -fe / fc;\n            }\n          }\n        } else if(ft < 0) {\n          // region 6\n          ftmp0 = fb + fe;\n          ftmp1 = fa + fd;\n          if(ftmp1 > ftmp0) {\n            fNumer = ftmp1 - ftmp0;\n            fDenom = fa - 2 * fb + fc;\n            if(fNumer >= fDenom) {\n              ft = 1;\n              fs = 0;\n            } else {\n              ft = fNumer / fDenom;\n              fs = 1 - ft;\n            }\n          } else {\n            ft = 0;\n            if(ftmp1 <= 0) {\n              fs = 1;\n            } else if(fd >= 0) {\n              fs = 0;\n            } else {\n              fs = -fd / fa;\n            }\n          }\n        } else {\n          // region 1\n          fNumer = fc + fe - fb - fd;\n          if(fNumer <= 0) {\n            fs = 0;\n            ft = 1;\n          } else {\n            fDenom = fa - 2 * fb + fc;\n            if(fNumer >= fDenom) {\n              fs = 1;\n              ft = 0;\n            } else {\n              fs = fNumer / fDenom;\n              ft = 1 - fs;\n            }\n          }\n        }\n      }\n\n      return (1 - fs - ft) * p1 + fs * p2 + ft * p3;\n    }\n    \n  };\n  \n  static vec3 project_triangle_ref(vec3 p1, vec3 p2, vec3 p3, vec3 p) {\n    const vec3 p1p2 = p2 - p1, p1p3 = p3 - p1, pp1 = p1 - p;\n    const real distp1p2 = p1p2.dot(p1p2) // distp2p3 = (p3 - p2).dot(p3 - p2),\n               // distp3p1 = p1p3.dot(p1p3)\n      ;\n\n    const real fa = distp1p2, fb = p1p2.dot(p1p3), fc = p1p3.dot(p1p3), fd = p1p2.dot(pp1),\n      fe = p1p3.dot(pp1);\n\n    const real fdet = fa * fc - fb * fb;\n    real fs = fb * fe - fc * fd, ft = fb * fd - fa * fe;\n\n    if(fs + ft <= fdet) {\n      if(fs < 0) {\n        if(ft < 0) {\n          // region 4\n          if(fd < 0) {\n            ft = 0;\n            if(-fd >= fa) {\n              fs = 1;\n            } else {\n              fs = -fd / fa;\n            }\n          } else {\n            fs = 0;\n            if(fe >= 0) {\n              ft = 0;\n            } else if(-fe >= fc) {\n              ft = 1;\n            } else {\n              ft = -fe / fc;\n            }\n          }\n        } else {\n          // region 3\n          fs = 0;\n          if(fe >= 0) {\n            ft = 0;\n          } else if(-fe >= fc) {\n            ft = 1;\n          } else {\n            ft = -fe / fc;\n          }\n        }\n      } else if(ft < 0) {\n        // region 5\n        ft = 0;\n        if(fd >= 0) {\n          fs = 0;\n        } else if(-fd >= fa) {\n          fs = 1;\n        } else {\n          fs = -fd / fa;\n        }\n\n      } else\n      {\n        // region 0        \n        // minimum at interior point\n        fs /= fdet;\n        ft /= fdet;\n      }\n    } else {\n      real ftmp0, ftmp1, fNumer, fDenom;\n\n      if(fs < 0) \n        {\n          // region 2\n          ftmp0 = fb + fd;\n          ftmp1 = fc + fe;\n          if(ftmp1 > ftmp0) {\n            fNumer = ftmp1 - ftmp0;\n            fDenom = fa - 2 * fb + fc;\n            if(fNumer >= fDenom) {\n              fs = 1;\n              ft = 0;\n            } else {\n              fs = fNumer / fDenom;\n              ft = 1 - fs;\n            }\n          } else {\n            fs = 0;\n            if(ftmp1 <= 0) {\n              ft = 1;\n            } else if(fe >= 0) {\n              ft = 0;\n            } else {\n              ft = -fe / fc;\n            }\n          }\n        } else if(ft < 0) \n        {\n          // region 6          \n          ftmp0 = fb + fe;\n          ftmp1 = fa + fd;\n          if(ftmp1 > ftmp0) {\n            fNumer = ftmp1 - ftmp0;\n            fDenom = fa - 2 * fb + fc;\n            if(fNumer >= fDenom) {\n              ft = 1;\n              fs = 0;\n            } else {\n              ft = fNumer / fDenom;\n              fs = 1 - ft;\n            }\n          } else {\n            ft = 0;\n            if(ftmp1 <= 0) {\n              fs = 1;\n            } else if(fd >= 0) {\n              fs = 0;\n            } else {\n              fs = -fd / fa;\n            }\n          }\n        } else\n        {\n          // region 1          \n          fNumer = fc + fe - fb - fd;\n          if(fNumer <= 0) {\n            fs = 0;\n            ft = 1;\n          } else {\n            fDenom = fa - 2 * fb + fc;\n            if(fNumer >= fDenom) {\n              fs = 1;\n              ft = 0;\n            } else {\n              fs = fNumer / fDenom;\n              ft = 1 - fs;\n            }\n          }\n        }\n    }\n    \n    return (1 - fs - ft) * p1 + fs * p2 + ft * p3;    \n  }\n\n  struct projector_alt {\n    mat3x3 points;\n    mat3x3 edges;    \n    mat3x3 points_inv;\n    vec3 n;\n    real n2;\n    \n    projector_alt(vec3 a, vec3 b, vec3 c) {\n      points << a, b, c;\n      edges << c - b, a - c, b - a;\n    \n      points_inv = points.inverse();\n      n = edges.col(0).cross(edges.col(1));\n      n2 = n.dot(n);\n      \n    }\n\n    vec3 operator()(vec3 q) const {\n      const vec3 delta = q - points.col(0);\n      const vec3 proj = q - n * n.dot(delta) / n2;\n      const vec3 coords = points_inv * proj;\n\n      int negative = 0;\n\n      // negative, positive\n      int last_index[2];\n      for(int i = 0; i < 3; ++i) {\n        const auto neg = coords[i] < 0;\n        negative += neg;\n        last_index[neg] = i;\n      }\n\n      switch(negative) {\n      case 0: return proj;\n      case 1: {\n        const vec3 e = edges.col(last_index[0]);\n        const vec3 origin = points.col(last_index[1]);\n        const vec3 delta = q - origin;\n      \n        real alpha = e.dot(delta) / e.dot(e);\n\n        // TODO branchless\n        // alpha = (alpha > 0) * alpha - (alpha > 1) * (alpha - 1);\n        alpha = std::max<real>(0, alpha);\n        alpha = std::min<real>(1, alpha);\n\n        return origin + e * alpha;\n      }      \n      case 2: return points.col(last_index[1]);\n      default:\n        throw std::logic_error(\"unreachable\");\n      }\n    }\n  };\n\n  \n  static vec3 project_triangle_alt(vec3 a, vec3 b, vec3 c, vec3 q) {\n    mat3x3 points;\n    points << a, b, c;\n\n    mat3x3 edges;\n    edges << c - b, a - c, b - a;\n    \n    const vec3 n = edges.col(0).cross(edges.col(1));\n    \n    const vec3 origin = a;\n    const vec3 delta = q - origin;\n    const vec3 proj = q - n * n.dot(delta) / n.dot(n);\n\n    const vec3 coords = points.inverse() * proj;\n\n    int negative = 0;\n\n    // negative, positive\n    int last_index[2];\n    for(int i = 0; i < 3; ++i) {\n      const auto neg = coords[i] < 0;\n      negative += neg;\n      last_index[neg] = i;\n    }\n\n    switch(negative) {\n    case 0: return proj;\n    case 1: {\n      const vec3 e = edges.col(last_index[0]);\n      const vec3 origin = points.col(last_index[1]);\n      const vec3 delta = q - origin;\n      \n      real alpha = e.dot(delta) / e.dot(e);\n      // alpha = (alpha > 0) * alpha - (alpha > 1) * (alpha - 1);\n      alpha = std::max<real>(0, alpha);\n      alpha = std::min<real>(1, alpha);\n\n      return origin + e * alpha;\n    }      \n    case 2: return points.col(last_index[1]);\n    default:\n      throw std::logic_error(\"unreachable\");\n    }\n    \n  }\n};\n\n#include \"timer.hpp\"\n#include <bitset>\n\nEigen::Matrix<double, 3, 1> solution;\n\nint main(int argc, char** argv) {\n  std::srand(time(0));\n\n  {\n    using lcp = struct lcp<double>;\n\n    static constexpr int N = 3;\n\n    lcp::matrix<N> M;\n    lcp::vector<N> q, x, w;\n\n    M.setRandom();\n    M = M.transpose() * M;\n\n    q.setRandom();\n    lcp::solve(x, M, q);\n\n    w.noalias() = M * x + q;\n\n    std::cout << \"x: \" << x.transpose() << std::endl;\n    std::cout << \"w: \" << w.transpose() << std::endl;\n    std::cout << \"xw: \" << x.dot(w) << std::endl;\n  }\n  \n  {\n    using closest = struct closest<double>;\n    \n    std::clog << \"=================\" << std::endl;\n\n    \n    static const auto make_problem = [](auto k) {\n      closest::vec3 a, b, c, p;\n      a.setRandom();\n      b.setRandom();\n      c.setRandom();\n\n      p.setRandom();\n\n      return k(a, b, c, p);\n    };\n\n    static const int n = 1000000;\n\n    const auto lcp_duration = with_time([] {\n      for(int i = 0; i < n; ++i) {\n        solution = make_problem([](auto a, auto b, auto c, auto p) {\n          return closest::project_triangle(a, b, c, p);\n        });\n      }\n    });\n\n    const auto alt_duration = with_time([] {\n      for(int i = 0; i < n; ++i) {\n        solution = make_problem([](auto a, auto b, auto c, auto p) {\n          return closest::project_triangle_alt(a, b, c, p);\n        });\n      }\n    });\n\n    const auto ref_duration = with_time([] {\n      for(int i = 0; i < n; ++i) {\n        solution = make_problem([](auto a, auto b, auto c, auto p) {\n          return closest::project_triangle_ref(a, b, c, p);\n        });\n      }\n    });\n    \n    std::clog << \"lcp: \" << lcp_duration << std::endl;\n    std::clog << \"alt: \" << alt_duration << std::endl;\n    std::clog << \"ref: \" << ref_duration << std::endl;        \n\n    ////////////////////////////////////////////////////////////////////////////////\n    const int m = 100;\n    const auto proj_alt_duration = with_time([] {\n      std::vector<closest::projector_alt> projs;\n      \n      for(int i = 0; i < n; ++i) {\n        projs.emplace_back(closest::vec3::Random(),\n                           closest::vec3::Random(),\n                           closest::vec3::Random());\n      }\n\n      for(auto& proj: projs) {\n        for(int i = 0; i < m; ++i) {\n          solution = proj(closest::vec3::Random());\n        }\n      }\n    });\n\n\n    const auto proj_ref_duration = with_time([] {\n      std::vector<closest::projector_ref> projs;\n      \n      for(int i = 0; i < n; ++i) {\n        projs.emplace_back(closest::vec3::Random(),\n                           closest::vec3::Random(),\n                           closest::vec3::Random());\n      }\n\n      for(auto& proj: projs) {\n        for(int i = 0; i < m; ++i) {\n          solution = proj(closest::vec3::Random());\n        }\n      }\n    });\n\n    std::clog << \"proj alt: \" << proj_alt_duration << std::endl;\n    std::clog << \"proj ref: \" << proj_ref_duration << std::endl;        \n    \n    \n    // closest::mat3x3 B;\n    // B.col(0) = a;\n    // B.col(1) = b;\n    // B.col(2) = c;\n\n    // const closest::vec3 coords = B.inverse() * x;\n    // std::clog << \"coords sum: \" << coords.sum() << std::endl;\n    // std::clog << \"coords: \" << coords.transpose() << std::endl;\n  }  \n  \n  return 0;\n}\n", "meta": {"hexsha": "dc784fcb35275ed451a219a3f5de35fa23b6eef5", "size": 16725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lcp.cpp", "max_stars_repo_name": "maxime-tournier/cpp", "max_stars_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lcp.cpp", "max_issues_repo_name": "maxime-tournier/cpp", "max_issues_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lcp.cpp", "max_forks_repo_name": "maxime-tournier/cpp", "max_forks_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_forks_repo_licenses": ["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.0994236311, "max_line_length": 136, "alphanum_fraction": 0.4072346786, "num_tokens": 5265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382004, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5060808906390841}}
{"text": "// Copyright (C) 2017 Vicente J. Botet Escriba\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// <experimental/chrono.hpp>\n\n#include <experimental/chrono.hpp>\n#include <experimental/ordinal_array.hpp>\n#include <experimental/ordinal_range.hpp>\n#include <experimental/ordinal_set.hpp>\n\nnamespace stdex = std::experimental;\n\n// Basic frame durations\nusing half_days     = std::chrono::duration<int32_t,  std::ratio_multiply<std::ratio<12>, std::chrono::hours::period>::type>;\nusing days     = std::chrono::duration<int32_t,  std::ratio_multiply<std::ratio<24>, std::chrono::hours::period>::type>;\nusing weeks    = std::chrono::duration<int32_t,  std::ratio_multiply<std::ratio<7>, days::period>::type>;\nusing years    = std::chrono::duration<int32_t,  std::ratio_multiply<std::ratio<146097, 400>, days::period>::type>;\nusing months   = std::chrono::duration<int32_t,  std::ratio_divide<years::period, std::ratio<12>>::type>;\n\n\n// relative numbers\n// The interface provided here differs to the one provided in p0355r4\n// Missing interfaces\n//constexpr weekday_number(const sys_days& dp) noexcept;\n//constexpr explicit weekday_number(const local_days& dp) noexcept;\n//constexpr explicit operator unsigned() const noexcept;\n//constexpr bool ok() const noexcept;\n//constexpr weekday_indexed operator[](unsigned index) const noexcept;\n//constexpr weekday_last    operator[](last_spec) const noexcept;\n// operator<<(OSTREAM) differes\n\nusing month_number = stdex::chrono::modulo<months,   years,    std::uint8_t>; //12\nusing weekday_number = stdex::chrono::modulo<days,   weeks,    std::uint8_t>; //7\nusing am_pm_number   = stdex::chrono::modulo<half_days,   days,    std::uint8_t>; //2\nusing hour_number   = stdex::chrono::modulo<std::chrono::hours,   days,    std::uint8_t>; //24\nusing am_pm_hour   = stdex::chrono::modulo<std::chrono::hours,   half_days,    std::uint8_t>; //12\nusing minute_number = stdex::chrono::modulo<std::chrono::minutes, std::chrono::hours,   std::uint8_t>; //60\nusing second_number = stdex::chrono::modulo<std::chrono::seconds, std::chrono::minutes, std::uint8_t>; //60\n\n// todo: time_of_day must be specialized to provide access to hour_number/minute_number/second_number/subseconds depending on Duration\n// So the following can be only a representation, not the interface\ntemplate <class Duration>\nusing time_of_day = stdex::chrono::modulo<Duration, days, std::uint32_t >;\n\n// fixme: Should the following conversions work only for time_of_day?\ntemplate <class ModuloFrom>\nconstexpr hour_number to_hour(ModuloFrom m) noexcept\n{\n    return stdex::chrono::modulo_cast<hour_number, days>(m);\n}\n\ntemplate <class ModuloFrom>\nconstexpr am_pm_number to_am_pm(ModuloFrom m) noexcept\n{\n  return stdex::chrono::modulo_cast<am_pm_number, days>(m);\n}\ntemplate <class ModuloFrom>\nconstexpr am_pm_hour to_am_pm_hour(ModuloFrom m) noexcept\n{\n  return stdex::chrono::modulo_cast<am_pm_hour, days>(m);\n}\n\n// This doesn't works if the time_of_day is in hours\n// todo: use SFINAE to remove the overload when the precision of ModuloFrom is less fine grained than minutes\ntemplate <class ModuloFrom>\nconstexpr minute_number to_minute(ModuloFrom m) noexcept\n{\n  return stdex::chrono::modulo_cast<minute_number, days>(m);\n}\n\ntemplate <class ModuloFrom>\nconstexpr second_number to_second(ModuloFrom m) noexcept\n{\n  return stdex::chrono::modulo_cast<second_number, days>(m);\n}\n\n// todo: add to_subsecond\n\nstatic_assert(am_pm_hour::cardinal  == 12, \"12 hours are not a half-day\");\nstatic_assert(am_pm_number::cardinal  == 2, \"2 half-days are not a day\");\nstatic_assert(hour_number::cardinal  == 24, \"24 hours are not a day\");\nstatic_assert(minute_number::cardinal  == 60, \"60 minutes are not an hour_number\");\nstatic_assert(second_number::cardinal  == 60, \"60 seconds are not a minute_number\");\nstatic_assert(hour_number::min()  == hour_number{0}, \"0 is not the min of hour_number\");\nstatic_assert(hour_number::max()  == hour_number{23}, \"23 is not the min of hour_number\");\n\n#include <boost/detail/lightweight_test.hpp>\n#include <iostream>\n\nint main()\n{\n  {\n                                            //   ms        sec       min  h\n      constexpr time_of_day<std::chrono::milliseconds> t2{ 234+ 1000*(2 + 60 * ( 4 + 8 * 60 ) )};\n      std::cout << \"t2 = \" << t2.count() << \"\\n\";\n      time_of_day<std::chrono::milliseconds> t{ std::chrono::milliseconds(234)+ std::chrono::seconds(2) + std::chrono::minutes(4) + std::chrono::hours(20)};\n      std::cout << \"t = \" << t.count() << \"\\n\";\n\n      std::cout << \"am_pm_number = \" << int(to_am_pm(t).count()) << \"\\n\";\n      std::cout << \"am_pm_hour = \" << int(to_am_pm_hour(t).count()) << \"\\n\";\n      std::cout << \"hour_number = \" << int(to_hour(t).count()) << \"\\n\";\n      std::cout << \"minute_number = \" << int(to_minute(t).count()) << \"\\n\";\n      std::cout << \"second_number = \" << int(to_second(t).count()) << \"\\n\";\n\n      BOOST_TEST(to_am_pm(t).count() == 1);\n      BOOST_TEST(to_am_pm_hour(t).count() == 8);\n      BOOST_TEST_EQ(to_hour(t).count(), 20);\n      BOOST_TEST_EQ(to_minute(t).count(), 4);\n      BOOST_TEST_EQ(to_second(t).count(), 2);\n  }\n  {\n      constexpr weekday_number wd{2};\n      BOOST_TEST(wd.count() == 2);\n  }\n  {\n    stdex::ordinal_array<int, weekday_number> arr;\n    BOOST_TEST(arr.size() == 7);\n  }\n  {\n    constexpr stdex::ordinal_array<int, weekday_number> c {{0, 1, 2, 3, 4, 5, 6}};\n    BOOST_TEST(c.size() == 7);\n    BOOST_TEST(c[weekday_number{1}] == 1);\n    BOOST_TEST(c[weekday_number{2}] == 2);\n    BOOST_TEST(c[weekday_number{3}] == 3);\n  }\n  {\n    // fixme:  the type \u2018const std::experimental::fundamental_v3::ordinal_range<std::experimental::fundamental_v3::chrono::modulo<std::chrono::duration<int, std::ratio<86400l, 1l> >, std::chrono::duration<int, std::ratio<604800l, 1l> >, unsigned char> >\u2019 of constexpr variable \u2018rng\u2019 is not literal\n    // Surely it comes from boost::iterator\n    //constexpr\n    stdex::ordinal_range<weekday_number> rng;\n    auto b = rng.begin();\n    BOOST_TEST(b->count()==0);\n    for (auto w : rng)\n    {\n      std::cout << w << \"\\n\";\n    }\n  }\n  {\n      stdex::ordinal_set<weekday_number> os;\n      os[weekday_number{1}]=true;\n      BOOST_TEST( 1 == os.count() );\n      BOOST_TEST( os.any() );\n      BOOST_TEST(os[weekday_number{1}]);\n  }\n  return ::boost::report_errors();\n}\n", "meta": {"hexsha": "1f7d49da53d977ea4eafe69e427497e5dc362efc", "size": 6393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/chrono/day_types_pass.cpp", "max_stars_repo_name": "jwakely/std-make", "max_stars_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 105.0, "max_stars_repo_stars_event_min_datetime": "2015-01-24T13:26:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T15:36:53.000Z", "max_issues_repo_path": "example/chrono/day_types_pass.cpp", "max_issues_repo_name": "jwakely/std-make", "max_issues_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2015-09-04T06:57:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T18:01:44.000Z", "max_forks_repo_path": "example/chrono/day_types_pass.cpp", "max_forks_repo_name": "jwakely/std-make", "max_forks_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2015-01-27T11:09:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T02:23:30.000Z", "avg_line_length": 42.9060402685, "max_line_length": 297, "alphanum_fraction": 0.6854371969, "num_tokens": 1770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5060808886873825}}
{"text": "#include <test/unit/math/prim/prob/hmm_util.hpp>\n#include <test/unit/math/prim/prob/vector_rng_test_helper.hpp>\n#include <stan/math/prim/prob/hmm_latent_rng.hpp>\n#include <stan/math/prim/prob/chi_square_lcdf.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/random.hpp>\n#include <test/unit/math/test_ad.hpp>\n#include <test/unit/util.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n#include <vector>\n\nTEST(hmm_rng_test, chiSquareGoodnessFitTest) {\n  // With identity transition and constant log_omegas, the sampled latent\n  // states are identifcal and follow a Bernoulli distribution parameterized\n  // by rho.\n  // The samples live on {1, 2}, so we need to deduct the error_index to\n  // to make the indices 0-indexed.\n  using stan::math::hmm_latent_rng;\n\n  int n_states = 2;\n  int n_transitions = 10;\n  Eigen::MatrixXd Gamma = Eigen::MatrixXd::Identity(n_states, n_states);\n  Eigen::VectorXd rho(n_states);\n  rho << 0.65, 0.35;\n  Eigen::MatrixXd log_omegas\n      = Eigen::MatrixXd::Ones(n_states, n_transitions + 1);\n\n  boost::random::mt19937 rng;\n  int N = 10000;\n\n  std::vector<double> expected;\n  expected.push_back(N * rho(0));\n  expected.push_back(N * rho(1));\n\n  std::vector<int> counts(2);\n  std::vector<int> state;\n\n  for (int i = 0; i < N; ++i) {\n    state = hmm_latent_rng(log_omegas, Gamma, rho, rng);\n    for (int j = 1; j < n_states; ++j)\n      EXPECT_EQ(state[j], state[0]);\n\n    ++counts[state[0] - stan::error_index::value];\n  }\n\n  assert_chi_squared(counts, expected, 1e-6);\n}\n\nTEST(hmm_rng_test, chiSquareGoodnessFitTest_symmetric) {\n  // In this two states situation, the latent states are\n  // symmetric, based on the observational log density,\n  // and transition matrix.\n  // The initial conditions introduces an asymmetry in the first\n  // state. The other hidden states all have probability 0.5.\n  // Note 1: the hidden states are also uncorrelated.\n  // Note 2: as before, to do a chi-squared test, we subtract\n  //  the error_index from hidden_state, to produce variables\n  //  on {0, 1}.\n  using stan::math::hmm_latent_rng;\n\n  int n_states = 2;\n  int n_transitions = 1;\n  Eigen::MatrixXd Gamma(n_states, n_states);\n  Gamma << 0.5, 0.5, 0.5, 0.5;\n  Eigen::VectorXd rho(n_states);\n  rho << 0.3, 0.7;\n  Eigen::MatrixXd log_omegas\n      = Eigen::MatrixXd::Ones(n_states, n_transitions + 1);\n\n  boost::random::mt19937 rng;\n  int N = 10000;\n\n  std::vector<double> expected_0;\n  expected_0.push_back(N * rho(0));\n  expected_0.push_back(N * rho(1));\n\n  std::vector<double> expected_1;\n  expected_1.push_back(N * 0.5);\n  expected_1.push_back(N * 0.5);\n\n  std::vector<int> counts_0(2);\n  std::vector<int> counts_1(2);\n  // int product = 0;\n  std::vector<int> states;\n  int a = 0, b = 0, c = 0, d = 0;\n  for (int i = 0; i < N; ++i) {\n    states = hmm_latent_rng(log_omegas, Gamma, rho, rng);\n    ++counts_0[states[0] - stan::error_index::value];\n    ++counts_1[states[1] - stan::error_index::value];\n    // product += states[0] * states[1];\n    a += (states[0] == stan::error_index::value\n          && states[1] == stan::error_index::value);\n    b += (states[0] == stan::error_index::value\n          && states[1] == 1 + stan::error_index::value);\n    c += (states[0] == 1 + stan::error_index::value\n          && states[1] == stan::error_index::value);\n    d += (states[0] == 1 + stan::error_index::value\n          && states[1] == 1 + stan::error_index::value);\n  }\n\n  // Test the marginal probabilities of each variable\n  assert_chi_squared(counts_0, expected_0, 1e-6);\n  assert_chi_squared(counts_1, expected_1, 1e-6);\n\n  // Test for independence (0 correlation by construction).\n  // By independence E(XY) = E(X)E(Y). We compute the R.H.S\n  // analytically and the L.H.S numerically.\n  std::vector<int> counts_xy(2);\n  counts_xy[0] = a;\n  counts_xy[1] = c;\n  std::vector<double> expected_xy;\n  expected_xy.push_back(N * rho(0) * 0.5);\n  expected_xy.push_back(N * rho(1) * 0.5);\n  assert_chi_squared(counts_xy, expected_xy, 1e-6);\n\n  // DRAFT -- code for chi-squared independence test.\n  // (overkill, since we have analytical prob for each cell)\n  // Test that the two states are independent, using a chi squared\n  // test for independence.\n  // Eigen::MatrixXd Expected(n_states, (n_transitions + 1));\n  // Expected << (a + b) * (a + c), (a + b) * (b + d),\n  //             (c + d) * (a + c), (c + d) * (b + d);\n  // Expected = Expected / N;\n  //\n  // Eigen::MatrixXd Observed(n_states, (n_transitions + 1));\n  // Observed << a, b, c, d;\n  // double chi = 0;\n  //\n  // for (int i = 0; i < n_states; ++i)\n  //   for (int j = 0; j < n_transitions + 1; ++j)\n  //     chi += (Observed(i, j) - Expected(i, j))\n  //             * (Observed(i, j) - Expected(i, j)) / Expected(i, j);\n  //\n  // int nu = 1;\n  // double p_value = exp(stan::math::chi_square_lcdf(chi, nu));\n  // double threshold = 0.1;  // CHECK -- what is an appropriate threshold?\n  // EXPECT_TRUE(p_value > threshold);\n}\n", "meta": {"hexsha": "d308941ea483138a22e451c4d05710cbaed2445c", "size": 4912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/hmm_latent_rng_test.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": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "test/unit/math/prim/prob/hmm_latent_rng_test.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": "test/unit/math/prim/prob/hmm_latent_rng_test.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": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 35.0857142857, "max_line_length": 76, "alphanum_fraction": 0.6465798046, "num_tokens": 1548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5060327259891972}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2016 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#define FUSION_MAX_VECTOR_SIZE 25  // increase maximal vector size for boost/fusion vectors\n#include <iostream>\n#include <algorithm>  // min, max\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n#include \"dune/grid/uggrid.hh\"\n#include \"dune/istl/solvers.hh\"\n\n#include \"fem/assemble.hh\"\n#include \"fem/istlinterface.hh\"\n#include \"fem/gridmanager.hh\"\n#include \"fem/lagrangespace.hh\"\n//#include \"fem/hierarchicspace.hh\"   // ContinuousHierarchicMapper\n#include \"fem/norms.hh\"\n#include \"linalg/iluprecond.hh\"\n#include \"io/vtk.hh\"\n//#include \"io/amira.hh\"\n#include \"utilities/kaskopt.hh\"\n#include \"utilities/gridGeneration.hh\" //  createUnitSquare\n\nusing namespace Kaskade;\n#include \"sst.hh\"\n\nstruct InitialValue \n{\n  using Scalar = double;\n  static constexpr int components = 1;\n  using ValueType = Dune::FieldVector<Scalar,components>;\n\n  InitialValue(int c): component(c) {}\n  \n  template <class Cell> int order(Cell const&) const { return std::numeric_limits<int>::max(); }\n  template <class Cell>\n  ValueType value(Cell const& cell,\n          Dune::FieldVector<typename Cell::Geometry::ctype,Cell::Geometry::coorddimension> const& localCoordinate) const \n  {\n  Dune::FieldVector<typename Cell::Geometry::ctype,Cell::Geometry::coorddimension> x = cell.geometry().global(localCoordinate);\n  if (component==0) \n    return 1.306028e6;\n  else if (component==1) \n    return 1.076508e12;\n  else if (component==2) \n    return 6.457715e10;\n  else if (component==3) \n    return 3.542285e10;\n  else\n    assert(\"wrong index!\\n\"==0);\n  return 0;\n  \n  }\n\nprivate:\n  int component;\n};\n\nint main(int argc, char *argv[])\n{\n  using Scalar = double;\n  using namespace boost::fusion;\n\n  std::cout << \"Start sst transfer tutorial program with ordinary Newton iteration\" << std::endl;\n\n  boost::timer::cpu_timer totalTimer;\n\n  int verbosityOpt = 1;\n  bool dump = true; \n  std::unique_ptr<boost::property_tree::ptree> pt = getKaskadeOptions(argc, argv, verbosityOpt, dump);\n\n  int  direct,\n     refinements = getParameter(pt, \"refinement\", 5),\n     order =  getParameter(pt, \"order\", 2),\n     verbosity   = getParameter(pt, \"verbosity\", 0);\n  Scalar tol = getParameter(pt, \"tolerance\", 1.0e-10);\n  //   IterateType iterateType = IterateType::CG;\n  //   PrecondType precondType = PrecondType::NONE;\n  Scalar fsign = static_cast<Scalar>(getParameter(pt, \"sign\", 0.0));\n  std::string empty;\n\n  std::cout << \"refinements of original mesh   : \" << refinements << std::endl;\n  std::cout << \"discretization order           : \" << order << std::endl;\n  std::cout << \"tolerance for Newton iteration : \" << tol << std::endl;\n\n  std::string s(\"names.type.\");\n  s += getParameter(pt, \"solver.type\", empty);\n  direct = getParameter(pt, s, 0);\n\n  //   s = \"names.iterate.\" + getParameter(pt, \"solver.iterate\", empty);\n  //   iterateType = static_cast<IterateType>(getParameter(pt, s, 0));\n  //   s = \"names.preconditioner.\" + getParameter(pt, \"solver.preconditioner\", empty);\n  //   precondType = static_cast<PrecondType>(getParameter(pt, s, 0));\n\n  constexpr int dim=2;    \n  using Grid = Dune::UGGrid<dim>;\n  using LeafView = Grid::LeafGridView;\n  using H1Space = FEFunctionSpace<ContinuousLagrangeMapper<Scalar,LeafView> >;\n// using H1Space = FEFunctionSpace<ContinuousHierarchicMapper<Scalar,LeafView> >;\n  using Spaces = boost::fusion::vector<H1Space const*>;\n  using VariableDescriptions = boost::fusion::vector<Variable<SpaceIndex<0>,Components<1>,VariableId<0> >,\n                               Variable<SpaceIndex<0>,Components<1>,VariableId<1> >,\n                               Variable<SpaceIndex<0>,Components<1>,VariableId<2> >,\n                               Variable<SpaceIndex<0>,Components<1>,VariableId<3> > >;\n  using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;\n  using Functional = SSTFunctional<Scalar,VariableSet>;\n  using Assembler = VariationalFunctionalAssembler<LinearizationAt<Functional> >;\n  constexpr int neq = SSTFunctional<Scalar,VariableSet>::TestVars::noOfVariables;\n  using CoefficientVectors = VariableSet::CoefficientVectorRepresentation<0,neq>::type;\n  using LinearSpace = VariableSet::CoefficientVectorRepresentation<0,neq>::type;\n\n  GridManager<Grid> gridManager( createUnitSquare<Grid>() );\n  gridManager.globalRefine(refinements);\n  std::cout << std::endl << \"Grid: \" << gridManager.grid().size(0) << \" triangles, \" << std::endl;\n  std::cout << \"      \" << gridManager.grid().size(1) << \" edges, \" << std::endl;\n  std::cout << \"      \" << gridManager.grid().size(2) << \" points\" << std::endl;\n\n  // construction of finite element space for the scalar solution T\n  H1Space temperatureSpace(gridManager,gridManager.grid().leafGridView(),\n               order);\n  Spaces spaces(&temperatureSpace);\n  // VariableDescription<int spaceId, int components, int Id>\n  // spaceId: number of associated FEFunctionSpace\n  // components: number of components in this variable\n  // Id: number of this variable\n  std::string varNames[4] = { \"u0\", \"u1\", \"u2\", \"u3\" };\n  VariableSet variableSet(spaces,varNames);\n\n  Functional F;\n  Assembler assembler(gridManager,spaces);\n  VariableSet::VariableSet x(variableSet);\n  VariableSet::VariableSet newtonCorr(variableSet);\n  VariableSet::VariableSet tmp(variableSet);\n\n  constexpr int nvars = SSTFunctional<Scalar,VariableSet>::AnsatzVars::noOfVariables;\n  size_t  nnz = assembler.nnz(0,neq,0,nvars,false);\n  size_t  size = variableSet.degreesOfFreedom(0,nvars);\n  std::cout << \"nvars=\" << nvars << \", neq=\" << neq << \", size=\" << size << \", nnz=\" << nnz << \"\\n\";\n    \n  std::vector<Scalar> xdata(size), scal(size), dxdata(size);\n  \n  int k=0;\n  L2Norm l2Norm;\n  Scalar norm_dx, norm_rhs;\n  std::vector<Scalar> norm_dx_comp(4), norm_rhs_comp(4);\n  \n  F.scaleInitialValue<0>(InitialValue(0),x);\n  F.scaleInitialValue<1>(InitialValue(1),x);\n  F.scaleInitialValue<2>(InitialValue(2),x);\n  F.scaleInitialValue<3>(InitialValue(3),x);\n  x.write(xdata.begin());\n  for (int i=0;i<size;i++) scal[i]=std::max(std::abs(xdata[i]),1.0);\n  \n  CoefficientVectors solution(VariableSet::CoefficientVectorRepresentation<0,neq>::init(spaces));\n  \n  writeVTKFile(x,\"graph/sst_start\",IoOptions().setOrder(std::min(order,2)).setPrecision(7));\n  gridManager.enforceConcurrentReads(false);\n  Dune::InverseOperatorResult res;\n  \n  std::cout << std::endl << \"Newton iteration starts:\" << std::endl <<\n            \"iter  scaled ||corr||            ||F||    itsol: eps     result  steps      rate        time\"\n            << std::endl;\n\n// begin of ordinary Newton iteration loop\n  do {\n    boost::timer::cpu_timer assembTimer;\n    assembler.assemble(linearization(F,x));\n    size_t  nnz = assembler.nnz(0,neq,0,nvars,false);\n    AssembledGalerkinOperator<Assembler,0,neq,0,neq> A(assembler);\n    CoefficientVectors rhs(assembler.rhs());\n  \n    tmp.data = rhs.data;\n    norm_rhs_comp[0]=l2Norm(boost::fusion::at_c<0>(tmp.data));\n    norm_rhs_comp[1]=l2Norm(boost::fusion::at_c<1>(tmp.data));\n    norm_rhs_comp[2]=l2Norm(boost::fusion::at_c<2>(tmp.data));\n    norm_rhs_comp[3]=l2Norm(boost::fusion::at_c<3>(tmp.data));\n    norm_rhs = sqrt(norm_rhs_comp[0]*norm_rhs_comp[0]+norm_rhs_comp[1]*norm_rhs_comp[1]+\n                    norm_rhs_comp[2]*norm_rhs_comp[2]+norm_rhs_comp[3]*norm_rhs_comp[3]);\n  \n    boost::timer::cpu_timer iteTimer;\n    int iteSteps = getParameter(pt, \"solver.iteMax\", 1000);\n    Scalar iteEps = getParameter(pt, \"solver.iteEps\", 1.0e-12);\n    int fill_lev = getParameter(pt, \"solver.ILUK.fill_lev\", 0);\n    ILUKPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > iluk(A,fill_lev,verbosity);\n    Dune::BiCGSTABSolver<LinearSpace> cg(A,iluk,iteEps,iteSteps,verbosity);\n    solution = 0;\n    cg.apply(solution,rhs,res);\n    newtonCorr.data = solution.data;\n    newtonCorr *= -1;\n    // add Newton-correction\n    x += newtonCorr;\n  \n    newtonCorr.write(dxdata.begin());\n    for (int i=0;i<size;i++) dxdata[i] /= scal[i];\n    tmp.read(dxdata.begin());\n    norm_dx_comp[0]=l2Norm(boost::fusion::at_c<0>(tmp.data));\n    norm_dx_comp[1]=l2Norm(boost::fusion::at_c<1>(tmp.data));\n    norm_dx_comp[2]=l2Norm(boost::fusion::at_c<2>(tmp.data));\n    norm_dx_comp[3]=l2Norm(boost::fusion::at_c<3>(tmp.data));\n    norm_dx = sqrt(norm_dx_comp[0]*norm_dx_comp[0]+norm_dx_comp[1]*norm_dx_comp[1]+\n                   norm_dx_comp[2]*norm_dx_comp[2]+norm_dx_comp[3]*norm_dx_comp[3]);\n    \n    x.write(xdata.begin());\n    for (int i=0;i<size;i++) scal[i]=std::max(std::abs(xdata[i]),1.0);\n  \n    std::cout << std::setw(4) << k+1 << \"  \" \n              << std::setw(15) << std::setprecision(5) << std::scientific << norm_dx << \"  \"  \n              << std::setw(15) << norm_rhs << \"  \" << std::setprecision(6);\n    std::cout.unsetf(std::ios::fixed | std::ios::scientific);\n    std::cout << std::setw(12) << iteEps << \"  \" \n              << (res.converged?\"converged\":\"failed  \") << \"  \"\n              << std::setw(5) << res.iterations << \"  \" \n              << std::setw(8) << res.conv_rate << \"  \"\n              << std::setw(9) << (Scalar)(iteTimer.elapsed().user)/1e9 << \"s \" << std::endl;\n  \n    // output of solution in VTK format for visualization,\n    // the data are written as ascii stream into file temperature.vtu,\n    // possible is also binary\n    std::ostringstream fname;\n    fname << \"graph/sst_\";\n    fname.width(2);\n    fname.fill('0');\n    fname.setf(std::ios_base::right,std::ios_base::adjustfield);\n    fname << k;\n    fname.flush();\n    writeVTKFile(x,fname.str(),IoOptions().setOrder(std::min(order,2)).setPrecision(7));\n    \n    // output of solution for Amira visualization,\n    // the data are written in binary format into file temperature.am,\n    // possible is also ascii\n    //IoOptions options;\n    //options.outputType = IoOptions::ascii;\n    //LeafView leafGridView = gridManager.grid().leafGridView();\n    //writeAMIRAFile(leafGridView,x,\"sst\",options);\n  k ++;\n  }\n  while ( norm_dx > tol );\n // end of ordinary Newton iteration loop\n \n  std::cout << \"total computing time: \" << boost::timer::format(totalTimer.elapsed()) << \"\\n\";\n  std::cout << \"End sst transfer tutorial program\" << std::endl;\n}\n", "meta": {"hexsha": "f1d724b1085ef4a4d98a1cc11942049d09adad1d", "size": 10973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/sst_pollution/sst.cpp", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/tutorial/sst_pollution/sst.cpp", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:33.000Z", "max_forks_repo_path": "Kaskade/tutorial/sst_pollution/sst.cpp", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 43.2007874016, "max_line_length": 127, "alphanum_fraction": 0.632643762, "num_tokens": 3059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5060327259891971}}
{"text": "#pragma once\n\n#include <mona/rect.hpp>\n#include <mona/mesh.hpp>\n\n#include \"line_renderer.hpp\"\n#include \"colors.hpp\"\n\n#include <armadillo>\n\n\nnamespace mona\n{\n    class line: public mesh\n    {\n        line_renderer renderer;\n        mona::rect span_area;\n\n    public:\n        glm::vec4 color{};\n\n        line(const arma::fvec& x, const arma::fvec& y, const arma::fvec& z,\n             glm::vec4 color = colors::black);\n        line(const arma::fvec& x, const arma::fvec& y,\n             glm::vec4 color = colors::black);\n        line();\n\n        // returns the area that this series cover\n        // this is to be used to calculate the axes tick values\n        auto span() const -> mona::rect override\n        {\n            return span_area;\n        }\n\n        auto draw(const glm::mat4& mvp) const -> void override\n        {\n            renderer.draw(mvp, color, 1.5f);\n        }\n\n        auto reset(const arma::fvec& x, const arma::fvec& y) -> void;\n\n        // TODO: I am not sure if this is to stay\n        auto empty() const -> bool;\n\n        auto set_strip(bool strip) -> void\n        {\n            renderer.set_strip(strip);\n        }\n    };\n};\n", "meta": {"hexsha": "2c1da3d016144f899a3a653238f70694873628d5", "size": 1150, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mona/line.hpp", "max_stars_repo_name": "Eleobert/mona", "max_stars_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mona/line.hpp", "max_issues_repo_name": "Eleobert/mona", "max_issues_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mona/line.hpp", "max_forks_repo_name": "Eleobert/mona", "max_forks_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5490196078, "max_line_length": 75, "alphanum_fraction": 0.5513043478, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5060327226553034}}
{"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/row.hpp>\n#include <fcppt/math/matrix/static.hpp>\n#include <fcppt/math/vector/comparison.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 <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_view\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef int value_type;\n\n\tconstexpr std::size_t const size = 3;\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tvalue_type,\n\t\tsize,\n\t\tsize\n\t>\n\tmatrix_type;\n\n\ttypedef\n\tfcppt::math::vector::static_<\n\t\tvalue_type,\n\t\tsize\n\t>\n\tvector_type;\n\n\tmatrix_type const t(\n\t\tfcppt::math::matrix::row(\n\t\t\t-3, 2, -5\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t-1, 0, -2\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t3, -4, 1\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tt[0],\n\t\tvector_type(\n\t\t\t-3,\n\t\t\t2,\n\t\t\t-5\n\t\t)\n\t);\n\n\tvector_type vec(\n\t\tt[0]\n\t);\n\n\tvec = t[1];\n\n\tBOOST_CHECK_EQUAL(\n\t\tvec,\n\t\tvector_type(\n\t\t\t-1,\n\t\t\t0,\n\t\t\t-2\n\t\t)\n\t);\n}\n", "meta": {"hexsha": "9857ae54c4036a3597d152d6bb73c6778c8c7c34", "size": 1401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/matrix/view.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/view.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/view.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.6785714286, "max_line_length": 61, "alphanum_fraction": 0.6866523911, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.506032717969737}}
{"text": "#ifndef MI_OPEN_GL_UTILITY_HPP\n#define MI_OPEN_GL_UTILITY_HPP 1\n#include <Eigen/Dense>\nnamespace mi\n{\n        class OpenGlUtility\n        {\n        public:\n                static void lookAt( const  Eigen::Vector3d& eye, const Eigen::Vector3d& center, Eigen::Vector3d& up );\n                static void perspective ( const double fov, const double aspect,const double znear, const double zfar );\n                static void ortho ( const double left, const double  right, const double  bottom, const double  top, const double znear, const double zfar );\n                static void ortho2d ( const double  left, const double  right, const double  bottom, const double  top );\n        private:\n                static void setZero ( double* m );\n        };\n}\n#endif//MI_OPEN_GL_UTILITY_HPP\n", "meta": {"hexsha": "a5304a2f5635ad0e35d027cd20b77ff071497527", "size": 788, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mi/OpenGlUtility.hpp", "max_stars_repo_name": "tmichi/migl", "max_stars_repo_head_hexsha": "27b7e83cfa015417e01ef2fd18770b2d02fdfc54", "max_stars_repo_licenses": ["MIT"], "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/mi/OpenGlUtility.hpp", "max_issues_repo_name": "tmichi/migl", "max_issues_repo_head_hexsha": "27b7e83cfa015417e01ef2fd18770b2d02fdfc54", "max_issues_repo_licenses": ["MIT"], "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/mi/OpenGlUtility.hpp", "max_forks_repo_name": "tmichi/migl", "max_forks_repo_head_hexsha": "27b7e83cfa015417e01ef2fd18770b2d02fdfc54", "max_forks_repo_licenses": ["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.7777777778, "max_line_length": 157, "alphanum_fraction": 0.6510152284, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5060327099502765}}
{"text": "\r\n//\r\n// Copyright 2010 Scott McMurray.\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#ifndef BOOST_HASH_ADLER_HPP\r\n#define BOOST_HASH_ADLER_HPP\r\n\r\n#include <boost/hash/detail/primes.hpp>\r\n#include <boost/hash/digest.hpp>\r\n#include <boost/hash/pack.hpp>\r\n#include <boost/static_assert.hpp>\r\n\r\n#ifdef BOOST_HASH_SHOW_PROGRESS\r\n#include <cstdio>\r\n#endif\r\n\r\nnamespace boost {\r\nnamespace hashes {\r\n\r\ntemplate <unsigned Bits>\r\nclass basic_adler {\r\n  public:\r\n    static unsigned const value_bits = 8;\r\n    typedef uint_t<value_bits>::least value_type;\r\n\r\n    BOOST_STATIC_ASSERT(Bits % 2 == 0);\r\n    BOOST_STATIC_ASSERT(Bits >= value_bits);\r\n\r\n    static unsigned const digest_bits = Bits;\r\n\r\n    static unsigned const word_bits = Bits;\r\n    typedef typename uint_t<word_bits>::least word_type;\r\n\r\n    typedef boost::array<word_type, 2> state_type;\r\n\r\n    typedef hashes::digest<digest_bits> digest_type;\r\n\r\n    static word_type const modulo = detail::largest_prime<Bits/2>::value;\r\n\r\n  public:\r\n    basic_adler() { reset(); }\r\n    void reset() { state_[0] = 0; state_[1] = 1; }\r\n\r\n    digest_type digest() const {\r\n        word_type x = state_[0] << (Bits/2) | state_[1];\r\n        digest_type d;\r\n        // RFC 1950, Section 2.2 stores the ADLER-32 in big-endian\r\n        pack_n<stream_endian::big_bit,\r\n               digest_bits,\r\n               octet_bits>(&x, 1,\r\n                           d.data(), digest_bits/octet_bits);\r\n        return d;\r\n    }\r\n\r\n    digest_type end_message() {\r\n        digest_type d = digest();\r\n        reset();\r\n        return d;\r\n    }\r\n\r\n  public:\r\n\r\n    basic_adler &\r\n    update_one(value_type x) {\r\n        if (Bits < 16) x %= modulo; // avoid overflow\r\n#ifdef BOOST_HASH_SHOW_PROGRESS\r\nprintf(\"(%.4x, %.4x) + %.2x ==> \", (int)state_[0], (int)state_[1], (int)x);\r\n#endif\r\n        state_[1] = (state_[1] + x) % modulo;\r\n        state_[0] = (state_[0] + state_[1]) % modulo;\r\n#ifdef BOOST_HASH_SHOW_PROGRESS\r\nprintf(\"(%.4x, %.4x) mod %.4x\\n\", (int)state_[0], (int)state_[1], (int)modulo);\r\n#endif\r\n        return *this;\r\n    }\r\n\r\n    template <typename IterT>\r\n    basic_adler &\r\n    update_n(IterT p, size_t n) {\r\n#ifndef BOOST_HASH_NO_OPTIMIZATION\r\n\r\n        unsigned const fast_word_bits = (word_bits < 16 ? 16 : word_bits);\r\n        typedef typename uint_t<fast_word_bits>::least/*fast*/ fast_word_type;\r\n/*\r\n\r\nWorst-case behaviour for delaying the modulo:\r\n- every input is 255\r\n- s1 and s0 start out at modulo-1\r\n\r\nSo after k inputs, we have:\r\n- s1 = (modulo-1) + k*255\r\n- s0 = (modulo-1) + Sigma(i = 1 to k)[ (modulo-1) + i*255 ]\r\n     = (modulo-1) + k*(modulo-1) + Sigma(i = 1 to k)[ i*255 ]\r\n     = (k+1)*(modulo-1) + 255 * Sigma(i = 1 to k)[i]\r\n     = (k+1)*(modulo-1) + 255 * k*(k+1)/2\r\n\r\nAnd to avoid overflow we need s1, s0 <= 2**fast_word_bits - 1\r\n\r\ns1 = (modulo-1) + k*255 <= 2**fast_word_bits - 1\r\n     k*255 <= 2**fast_word_bits - 1 - (modulo-1)\r\n     k <= (2**fast_word_bits - modulo)/255\r\n\r\nThen use an overestimate for s0 to make the numbers nicer\r\ns0 < (k+1)*modulo + 256/2(k+1)**2 < 2**fast_word_bits\r\n\r\nWhich solves as\r\nk < ( sqrt(512*2**fast_word_bits + modulo**2) - m - 256 )/256\r\n\r\nSo then overestimating m as 2**(word_bits/2) and other safe approximations gives\r\nk < 2**((fast_word_bits-7)/2) - 2**((word_bits-16)/2) - 1\r\n\r\nBits    Limit\r\n----    -----\r\n8       16\r\n16      16\r\n24      240\r\n32      3840\r\n40      61440\r\n48      983040\r\n56      15728640\r\n64      251658240\r\n\r\n*/\r\n\r\n        unsigned const less = (1 << (fast_word_bits/2 - 8));\r\n        unsigned const limit = (1 << (fast_word_bits/2 - 4))\r\n                             - (word_bits < 16 ? 0 : less);\r\n\r\n#define BOOST_HASH_ADLER_STEP \\\r\n        { value_type x = *p++; s1 += x; s0 += s1; }\r\n\r\n#define BOOST_HASH_ADLER_8_STEPS \\\r\n        { \\\r\n            BOOST_HASH_ADLER_STEP BOOST_HASH_ADLER_STEP \\\r\n            BOOST_HASH_ADLER_STEP BOOST_HASH_ADLER_STEP \\\r\n            BOOST_HASH_ADLER_STEP BOOST_HASH_ADLER_STEP \\\r\n            BOOST_HASH_ADLER_STEP BOOST_HASH_ADLER_STEP \\\r\n        }\r\n\r\n        fast_word_type s0 = state_[0];\r\n        fast_word_type s1 = state_[1];\r\n\r\n        for ( ; n >= limit; n -= limit) {\r\n            unsigned m = limit;\r\n            for ( ; m >= 8; m -=8) {\r\n                BOOST_HASH_ADLER_8_STEPS\r\n            }\r\n            while (m--) {\r\n                BOOST_HASH_ADLER_STEP\r\n            }\r\n            s1 %= modulo;\r\n            s0 %= modulo;\r\n        }\r\n        for ( ; n >= 8; n -=8) {\r\n            BOOST_HASH_ADLER_8_STEPS\r\n        }\r\n        while (n--) {\r\n            BOOST_HASH_ADLER_STEP\r\n        }\r\n        s1 %= modulo;\r\n        s0 %= modulo;\r\n\r\n        state_[0] = s0;\r\n        state_[1] = s1;\r\n\r\n#else\r\n        while (n--) update_one(*p++);\r\n#endif\r\n        return *this;\r\n    }\r\n\r\n    template <typename IterT>\r\n    basic_adler &\r\n    update(IterT b, IterT e, std::random_access_iterator_tag) {\r\n        return update_n(b, e-b);\r\n    }\r\n    template <typename IterT, typename Category>\r\n    basic_adler &\r\n    update(IterT b, IterT e, Category) {\r\n        while (b != e) update_one(*b++);\r\n        return *this;\r\n    }\r\n    template <typename IterT>\r\n    basic_adler &\r\n    update(IterT b, IterT e) {\r\n        typedef typename std::iterator_traits<IterT>::iterator_category cat;\r\n        return update(b, e, cat());\r\n    }\r\n\r\n  private:\r\n    state_type state_;\r\n};\r\n\r\ntemplate <unsigned Bits>\r\nstruct adler {\r\n  private:\r\n    typedef basic_adler<Bits> octet_hash_type;\r\n  public:\r\n    template <unsigned value_bits>\r\n    struct stream_hash {\r\n        BOOST_STATIC_ASSERT(value_bits == 8);\r\n        typedef octet_hash_type type_;\r\n#ifdef BOOST_HASH_NO_HIDE_INTERNAL_TYPES\r\n        typedef type_ type;\r\n#else\r\n        struct type : type_ {};\r\n#endif\r\n    };\r\n    typedef typename octet_hash_type::digest_type digest_type;\r\n};\r\n\r\n} // namespace hashes\r\n} // namespace boost\r\n\r\n#endif // BOOST_HASH_ADLER_HPP\r\n", "meta": {"hexsha": "9a52e65d7d26ac914ef30e7cc4ff9182e5487d4d", "size": 5998, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/hash/adler.hpp", "max_stars_repo_name": "dillonl/boost-cmake", "max_stars_repo_head_hexsha": "7204d4c68345a0b26e24f51fa46a04b1d2bda3e7", "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/hash/adler.hpp", "max_issues_repo_name": "dillonl/boost-cmake", "max_issues_repo_head_hexsha": "7204d4c68345a0b26e24f51fa46a04b1d2bda3e7", "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/hash/adler.hpp", "max_forks_repo_name": "dillonl/boost-cmake", "max_forks_repo_head_hexsha": "7204d4c68345a0b26e24f51fa46a04b1d2bda3e7", "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.2636363636, "max_line_length": 81, "alphanum_fraction": 0.58036012, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5059768583043291}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2009-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NGT platform is licensed under the Apache License, Version 2.0 (the\n//  \"License\"); you may not use this file except in compliance with the\n//  License. You may obtain a copy of the License at\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// __END_LICENSE__\n\n#include <test/Helpers.h>\n#include <vw/Math/Functors.h>\n#include <vw/Math/Vector.h>\n#include <vw/Image/ImageView.h>\n#include <vw/Image/ImageMath.h>\n#include <vw/Image/ImageViewRef.h>\n#include <vw/InterestPoint/InterestData.h>\n#include <asp/Core/IntegralAutoGainDetector.h>\n\n#include <boost/foreach.hpp>\n#include <boost/random/normal_distribution.hpp>\n\nusing namespace vw;\nusing namespace asp;\n\nTEST( IntegralAutoGainDetector, VerifyMaxima ) {\n\n  ImageView<float> test_image(101,101);\n\n  const float SIGMA = 3;\n\n  // Drawing a DoG signal\n  Vector2i location, center(50,50);\n  for ( ; location.y() < test_image.rows(); location.y()++ ) {\n    for ( location.x() = 0; location.x() < test_image.cols(); location.x()++ ) {\n      float distance = norm_2( Vector2f(location - center) );\n      test_image( location.x(), location.y() ) =\n        40 * (\n              1/(2*M_PI*SIGMA*SIGMA)*exp(-pow(distance,2)/(2*SIGMA*SIGMA)) -\n              1/(2*M_PI*4*SIGMA*SIGMA)*exp(-pow(distance,2)/(2*4*SIGMA*SIGMA))\n              ) + 0.5;\n    }\n  }\n\n  // Detect interest points\n  IntegralAutoGainDetector detector;\n  ip::InterestPointList list = detector.process_image( test_image );\n  EXPECT_EQ( list.size(), 9 ); // Digitization error\n\n  // Find the best IP\n  const ip::InterestPoint* best_ip = &list.front();\n  float best_ip_value = list.begin()->interest;\n  BOOST_FOREACH( ip::InterestPoint const& ip, list ) {\n    if ( ip.interest > best_ip_value ) {\n      best_ip_value = ip.interest;\n      best_ip = &ip;\n    }\n  }\n\n  // The best IP is the one centered on the circle feature we\n  // drew. There are more due to digitization errors and float point\n  // errors in the the integral image.\n  EXPECT_EQ( best_ip->x, 50 );\n  EXPECT_EQ( best_ip->y, 50 );\n  EXPECT_EQ( best_ip->scale, 1.875 );\n\n  // This is odd ... but I'm just verifying the impl calls the same\n  // code. This was a bug that elluded me for a very long time.\n  ASSERT_EQ( typeid(detector),\n             typeid(detector.impl()) );\n}\n", "meta": {"hexsha": "7b7e3f1a5b5ebd56b6a4dfd8fc704b45433e8b87", "size": 2776, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/asp/Core/tests/TestIntegralAutoGainDetector.cxx", "max_stars_repo_name": "fenglang12345/StereoPipeline-2.4.0", "max_stars_repo_head_hexsha": "a9cb9129013f278e9f65e435193b735a6b051eb9", "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/asp/Core/tests/TestIntegralAutoGainDetector.cxx", "max_issues_repo_name": "fenglang12345/StereoPipeline-2.4.0", "max_issues_repo_head_hexsha": "a9cb9129013f278e9f65e435193b735a6b051eb9", "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/asp/Core/tests/TestIntegralAutoGainDetector.cxx", "max_forks_repo_name": "fenglang12345/StereoPipeline-2.4.0", "max_forks_repo_head_hexsha": "a9cb9129013f278e9f65e435193b735a6b051eb9", "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.1392405063, "max_line_length": 80, "alphanum_fraction": 0.6880403458, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5059768583043291}}
{"text": "/*! \\file sabrRbsSmile.hpp\n    \\brief swaption smile which uses sabr interpolation \"near\" atm and an rbs parametric smile for extrapolation\n\tatm of underlying cube is always exactly reproduced\n\tvol spreads are interpolated linearly in option and swap maturity direction, flat extrapolation is used\n\tthese spreads are added to base cube atm vol\n\tPeter Caspers \n*/\n\n#include <ql/quantlib.hpp>\n#include <sabrModel.hpp>\n#include <RbsSmile.hpp>\n#include <iostream>\n#include <fstream>\n#include <boost/property_tree/detail/rapidxml.hpp>\n#include <map>\n\n#ifndef quantlib_sabrRbsSmile_hpp\n#define quantlib_sabrRbsSmile_hpp\n\n#define MINSTRIKE 0.0010   // left from this strike, this strike is used always\n//#define MINDISTATM 0.00001 // below this difference strike is treated as atm\n\nusing namespace boost;\nusing namespace std;\n\nnamespace QuantLib {\n\n\t/*! sabr/parametric swaption smile with the purpose to match to cms market */\n\t\n\tclass SabrRbsSmile {\n\t\tpublic:\t\n\t\t\t/*! smile is set up by\n\t\t\t- swaption vol cube (as the basis)\n\t\t\t- left and right end point (relative to atm) defining the interpolation area, outside extrapolation is used\n\t\t\t- option tenors, swap tenors w.r.t. sabr / parametric smiles are calibrated\n\t\t\t- start values for sabr calibration (alpha, nu, rho. beta is taken from time termstructure for beta below)\n\t\t\t- option, underlying cms calibration termstructure (given as pillars) for parameters mu, nu (parametric) and beta (sabr)\n\t\t\t- matrix for mu, nu, beta corresponding to cms calibration termstructure\n\t\t\t- strike spreads (relative to atm) defining the strikes on which SABR models are calibrated\n\t\t\t- vegaWeighted = true then difference in implied vols is weighted by vega\n\t\t\t- acceptRmse rmse for sabr calibration below which sabr smile is accepted\n\t\t\t- rejectRmse rmse for sabr calibration above which fall back smile is used insted. between these two, model is accepted (but more start values are tried to find a better fit)\n\t\t\t- haltonIterations the give start values plus a halton sequence of this length is tried to achieve acceptRmse\n\t\t\t- optimizer, endcriteria are the optimizer and the end criteria for optimization\n\t\t\t- BLACKACCURACY = accuracy to convert price to vol\n\t\t\t- hDiff is used to compute numerically first and second derivatives\n\t\t\t*/\n\t\t\tSabrRbsSmile(boost::shared_ptr<SwaptionVolatilityCube>& volCube,\n\t\t\t\tconst vector<Period>& optionTenors, const vector<Period>& swapTenors,\n\t\t\t\tconst Matrix& alpha, const Matrix& nu, const Matrix& rho,\n\t\t\t\tdouble leftBound, double rightBound, \n\t\t\t\tconst vector<Period>& optionPillars, const vector<Period>& underlyingPillars,\n\t\t\t\tconst Matrix& pMu, const Matrix& pNu, const Matrix& beta,\n\t\t\t\tvector<double>& strikeSpreads, bool vegaWeighted=true, double acceptRmse=0.0020, double rejectRmse=0.02,\n\t\t\t\tint haltonIterations=150,\n\t\t\t\tconst boost::shared_ptr<EndCriteria>& endCriteria=boost::shared_ptr<EndCriteria>(),\n                const boost::shared_ptr<OptimizationMethod>& optMethod=boost::shared_ptr<OptimizationMethod>(),\n\t\t\t\tdouble BLACKACCURACY=1.0E-5,\n\t\t\t\tdouble hDiff=1.0E-4);\n\t\t\t\n\t\t\t/*! get volatility from sabr / parametric smile.  \n\t\t\t\tif spread true then strike=atm+spread is calculated, otherwise strike must be  given \n\t\t\t\tif market is true then the vol from the base cube is returned  \n\t\t\t\tif sabr calibration is rejected (rmse>rejectRmse) also the vol from the base cube is returned as fall back \n\t\t\t\tbilinear interpolation (with flat extrapolation) is used if option / swap tenor does not fall on pillar */\n\t\t\tdouble volatility(const Date& fixing, const Period& tenor, const double& strike0, bool spread=false, bool market=false);\n\t\t\tdouble volatility(const Period& option, const Period& tenor, const double& strike0, bool spread=false, bool market=false);\n\t\t\t\n\t\t\t/*! preset sabr / parametric model to get volatility more efficiently */\n\t\t\tbool setFastVolatility(const Date& fixing, const Period& tenor);\n\t\t\t/*! get volatility from preset sabr / parametric smile model \n\t\t\t    note that spread mode = true and market = true is not available here*/\n\t\t\tdouble getFastVolatility(const double& strike);\n\n\t\t\t/*! get option price (not discounted) from sabr / parametric smile (only on defined pillars) \n\t\t\t\tif forceSabr is true the sabr model (or fall back cube) is always used (never rbs), needed for rbs smile setup */\n\t\t\tdouble optionPrice(const Date& fixing, const Period& tenor, const double& strike0, const Option::Type type, bool spread=false, bool market=false, bool forceSabr=false);\n\t\t\tdouble optionPrice(const Period& option, const Period& tenor, const double& strike0, const Option::Type type, bool spread=false, bool market=false, bool forceSabr=false);\n\n\t\t\t/*! get matrix of sabr parameters and rmse\n\t\t\t    rmse is -1.0 if calibration failed\n\t\t\t\tbest rmse is returned even if calibration is rejected\n\t\t\t\tin both cases (=no valid sabr model) the start values for alpha, nu, rho are returned */\n\t\t\tMatrix sabrAlpha() { return alpha_; }\n\t\t\tMatrix sabrNu() { return nu_; }\n\t\t\tMatrix sabrRho() { return rho_; }\n\t\t\tMatrix sabrRmse() { return sabrRmse_; }\n\n\t\t\t/*! get matrix of sabr beta, rbs smile mu and nu on option / swap pillars\n\t\t\t    if a sabr model is not valid, -1 is returned for beta*/\n\t\t\tMatrix sabrBeta();\n\t\t\tMatrix rbsMu();\n\t\t\tMatrix rbsNu();\n\n\t\t\t/*! get matrix of sabr beta, rbs smile mu and nu on cms calibration termstructure */\n\t\t\tMatrix sabrBetaTs() { return beta_; }\n\t\t\tMatrix rbsMuTs() { return pMu_; }\n\t\t\tMatrix rbsNuTs() { return pNu_; }\n\n\t\t\t/*! get underlying vol cube */\n\t\t\tboost::shared_ptr<SwaptionVolatilityCube> volCube() { return volCube_; }\n\n\t\t\t/*! get option pillar times */\n\t\t\tvector<double> optionPillarTimes()  { return optTimes_; }\n\n\t\t\t/*! set parameter mu at a pillar */\n\t\t\tbool setPillarMu(int optPillar, int undPillar, double mu);\n\t\t\t/*! set parameter nu at a pillar */\n\t\t\tbool setPillarNu(int optPillar, int undPillar, double nu);\n\t\t\t/*! set parameter beta at a pillar */\n\t\t\tbool setPillarBeta(int optPillar, int undPillar, double beta);\n\t\t\t/*! get pillar mu */\n\t\t\tdouble pillarMu(int optPillar, int undPillar) { return pMu_[undPillar][optPillar]; }\n\t\t\t/*! get pillar nu */\n\t\t\tdouble pillarNu(int optPillar, int undPillar) { return pNu_[undPillar][optPillar]; }\n\t\t\t/*! get pillar beta */\n\t\t\tdouble pillarBeta(int optPillar, int undPillar) { return beta_[undPillar][optPillar]; }\n\t\t\t\n\t\t\t/*! get mu, nu, beta for given option time and swap time */\n\t\t\tdouble mu(double optMaturity, double undMaturity) { return muInterpol_(optMaturity,undMaturity,true); }\n\t\t\tdouble nu(double optMaturity, double undMaturity) { return nuInterpol_(optMaturity,undMaturity,true); }\n\t\t\tdouble beta(double optMaturity, double undMaturity) { return betaInterpol_(optMaturity,undMaturity,true); }\n\t\t\t\n\t\t\t/*! get SABR parameters for (fixing, tenor) */\n\t\t\tvector<double> sabrParameters(const Date& fixing, const Period& tenor);\n\t\t\tvector<double> sabrParameters(const Period& option, const Period& tenor);\n\n\t\t\t/*! get RBS Smile parameters for (fixing, tenor) */\n\t\t\tvector<double> rbsParameters(const Date& fixing, const Period& tenor);\n\t\t\tvector<double> rbsParameters(const Period& option, const Period& tenor);\n\t\t\t\n\t\t\t/*! write murex xml file. if inPath is given, atms in this xml file are used */\n\t\t\tbool writeMurexFile(string outPath, string nickname, string date, string swap, vector<string>& optionNames, vector<string>& swapNames, \n\t\t\t\tvector<Period>& optionTenors,vector<Period>& swapTenors,\n\t\t\t\tvector<double> strikeSpreads, string inPath=\"\");\n\n\t\t\t/*! recalibrate models on pillar pair (sabr and rbs smile) w.r.t. given \n\t\t\t\ttermstructure of beta, mu, nu (as set by methods setPillarMu ...)\n\t\t\t    returns true if succesful, false otherwise (no changes are made then in the model, see sabrBeta(), rbsMu(), rbsNu(),\n\t\t\t\tthough given termstructure of mu, nu, beta returned by rbsMuTs(), rbsNuTs(), sabrBetaTs() ... remains same) \n\t\t\t\tif calSabr false only the rbs smiles are recalibrated (e.g. if only mu, nu was changed, not beta */\n\t\t\tbool recalibrate(const Period& option, const Period& tenor, bool calSabr);\n\n\t\t\t/*! recalibrate all models, returns false if one recalibration is not succesfull\n\t\t\t\tif calSabr false only the rbs smiles are recalibrated (e.g. if only mu, nu was changed, not beta */\n\t\t\tbool recalibrate(bool calSabr);\n\n\t\t\t/*! recalibrate all models with option tenor leq given option pillar and underlying equal to given underlying pillar */\n\t\t\tbool recalibrate(const int maxOptPillar, const int undPillar, bool calSabr);\n\n\t\t\t/*! return fixing dates of cube */\n\t\t\tvector<Date> fixingDates() { return fixings_; }\n\t\t\n\t\tprivate:\n\n\t\t\t/*! set up all sabr models */\n\t\t\tvoid setupSabrModels();\n\n\t\t\t/*! set up all rbs smiles */\n\t\t\tvoid setupRbsSmiles();\n\t\t\t\n\t\t\t/*! get time from referenceDate w.r.t. day counter of input cube */\n\t\t\tdouble time(const Date& date);\n\n\t\t\t/*! get sabr model for given (fixing date, swap tenor) */\n\t\t\tboost::shared_ptr<SabrModel> sabrModel(const Period& option, const Period& swap);\n\t\t\tboost::shared_ptr<SabrModel> sabrModel(const Date& fixing, const Period& swap);\n\n\t\t\t/*! get rbs smile for given (fixing date, swap Tenor) */\n\t\t\tboost::shared_ptr<RbsSmile> rbsSmile(const Period& option, const Period& swap);\n\t\t\tboost::shared_ptr<RbsSmile> rbsSmile(const Date& fixing, const Period& swap);\n\t\t\t\n\t\t\tboost::shared_ptr<SwaptionVolatilityCube> volCube_; // base cube\n\t\t\tvector<Period> optionTenors_,swapTenors_; // model pillars (sabr / rbs smile)\n\t\t\tvector<Date> fixings_; // fixing dates corresponding to option tenors\n\t\t\tMatrix alpha_,nu_,rho_; // matrix of sabr parameters\n\t\t\tMatrix sabrRmse_; // matrix of sabr rmse (calibration error)\n\t\t\t\n\t\t\tvector<Period> optPillars_, undPillars_; // term structure of beta, mu, nu\n\t\t\tvector<double> optTimes_, undTimes_; // corresponding times (for interpolation)\n\t\t\tMatrix pMu_,pNu_,beta_; // corresponding pillar parameters\n\n\t\t\tdouble leftBound_, rightBound_,h_; // sabr region, step for numerical differentation\n\t\t\tvector<double> strikeSpreads_; // smile spreads (relative to atm) on which sabr is calibrated\n\t\t\t\n\t\t\tbool vegaWeighted_;\n\t\t\tdouble acceptRmse_,rejectRmse_; // sabr optimization parameters\n\t\t\tint haltonIterations_;\n\t\t\tconst boost::shared_ptr<EndCriteria>& endCriteria_;\n            const boost::shared_ptr<OptimizationMethod>& optMethod_;\n\n\t\t\tInterpolation2D muInterpol_,nuInterpol_,betaInterpol_; // linear interpolation for beta, mu, nu\n\n\t\t\tDate referenceDate_; // underlying cube data\n\t\t\tCalendar calendar_;\n\t\t\tBusinessDayConvention bdc_;\n\t\t\tDayCounter dc_;\n\t\t\t\n\t\t\tmap<pair<Date,Period>,bool> sabrValid_; // maps fixing, underlying tenor to true (sabr is well calibrated) or false (sabr could not be calibrated)\n\t\t\tmap<pair<Date,Period>,bool>::iterator sabrValidIter_; // iterator\n\t\t\tmap<pair<Date,Period>,boost::shared_ptr<SabrModel>> sabrModels_; // maps fixing, underlying tenor to sabr model\n\t\t\tmap<pair<Date,Period>,boost::shared_ptr<SabrModel>>::iterator sabrModelsIter_; // iterator\n\n\t\t\tmap<pair<Date,Period>,boost::shared_ptr<RbsSmile>> rbsSmiles_; // maps fixing, underlying tenor to rbs parametric smiles\n\t\t\tmap<pair<Date,Period>,boost::shared_ptr<RbsSmile>>::iterator rbsSmilesIter_; // iterator\n\n\t\t\tdouble BLACKACCURACY, OPTACCURACY;\n\t\t\t\n\t\t\t// member variable for setFastVolatility(), getFastVolatility()\n\t\t\tdouble fastAtm11_,fastAtm12_,fastAtm21_,fastAtm22_,fastAtm_;\n\t\t\tdouble fastAtmVol11_,fastAtmVol12_,fastAtmVol21_,fastAtmVol22_;\n\t\t\tdouble fastOptionTime_,fastOptionTime1_,fastOptionTime2_;\n\t\t\tdouble fastSwapTime_,fastSwapTime1_,fastSwapTime2_;\n\t\t\tboost::shared_ptr<SabrModel> fastSabrModel11_,fastSabrModel12_,fastSabrModel21_,fastSabrModel22_;\n\t\t\tboost::shared_ptr<RbsSmile> fastRbsModel11_,fastRbsModel12_,fastRbsModel21_,fastRbsModel22_;\n\t\t\tbool fastOptEq_,fastSwapEq_;\n\t\t\tDate fastFixing_;\n\t\t\tPeriod fastTenor_;\n\t\t\tbool fastValid_;\n\n\t};\n\n}\n\n\n#endif\n\n", "meta": {"hexsha": "523a38c67a1e047112f02c95deb5c4cd05925127", "size": 11782, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/preexperimental/sabrRbsSmile.hpp", "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": "ql/experimental/preexperimental/sabrRbsSmile.hpp", "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": "ql/experimental/preexperimental/sabrRbsSmile.hpp", "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": 51.6754385965, "max_line_length": 177, "alphanum_fraction": 0.7390086573, "num_tokens": 3127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5059768470170213}}
{"text": "#include <blitz/array.h>\n#include <blitz/tinyvec-et.h>\n\nBZ_USING_NAMESPACE(blitz)\n\n/*\n * The current implementation of stencil objects forces these variables\n * to be placed in global scope.  Ugh.  This restriction will be removed\n * eventually.\n */\ndouble rho;                        // Density of fluid\ndouble recip_rho;                  // 1/rho\ndouble eta;                        // Kinematic viscosity\ndouble time_now;                   // Elapsed seconds\ndouble delta_t;                    // Time step\ndouble volume;                     // Volume of a cell\ndouble airPressure;                // Air pressure (Pa)\ndouble spatialStep;                // Grid element size\ndouble gravity;                    // Acceleration due to gravity\ndouble gravityPressureGradient;    // Pressure gradient due to gravity\n/*\n * The \"geometry\" object specifies how an array is mapped into real-world\n * space.  In this case, \"UniformCubicGeometry\" is used, which means that\n * the real-world grid is orthogonal, regularly spaced, with the same spatial\n * step in each dimension.\n */\n\nUniformCubicGeometry<3> geom;      // Geometry\n/*\n * Some typedefs to make life easier.\n */\n\ntypedef TinyVector<double,3> vector3d;\ntypedef Array<vector3d,3> vectorField;\ntypedef Array<double,3>   scalarField;\n\n/***********          Timestep the velocity field           ************\n * This is a 63-point stencil.  For example, Laplacian3DVec4 turns into\n * a 45-point stencil: each 2nd derivative is a 5-point stencil, and\n * there are 9 of these derivatives to take the Laplacian of a 3D vector\n * field.\n */\n\nBZ_DECLARE_STENCIL5(timestep, V, nextV, P, advect, force)\n\n    nextV = *V + delta_t * ( recip_rho * (\n      eta * Laplacian3DVec4(V,geom) - grad3D4(P, geom) + *force) - *advect);\n\nBZ_END_STENCIL\n/*\n * Allocate arrays and set their initial state\n */\nvoid setup(const int N, vectorField& V, vectorField& nextV, scalarField& P,\n    scalarField& P_rhs, vectorField& advect, vectorField& force)\n{\n    // A 1m x 1m x 1m domain\n    spatialStep = 1.0 / (N - 1);\n    geom = UniformCubicGeometry<3>(spatialStep);\n\n    // Allocate arrays\n    allocateArrays(shape(N,N,N), advect, V, nextV, force);  // vector fields\n    allocateArrays(shape(N,N,N), P, P_rhs);                 // scalar fields\n\n    // Since incompressibility is assumed, pressure only shows up as\n    // derivative terms in the equations.  We choose airPressure = 0\n    // as an arbitrary datum.\n\n    airPressure = 0;             // Pa\n    rho = 1000;                  // density of fluid, kg/m^3\n    recip_rho = 1.0 / rho;       // inverse of density\n    eta = 1.0e-6;                // kinematic viscosity of fluid, m^2/s\n    gravity = 9.81;              // m/s^2\n    delta_t = 0.001;             // initial time step, in seconds\n    volume = pow3(spatialStep);  // cubic volume associated with grid point\n\n    // Kludge: Set eta high, so that the flow will spread faster.\n    // This means the cube is filled with molasses, rather than water.\n    eta *= 1000;\n\n    // Initial conditions: quiescent\n    V = 0.0;\n    P_rhs = 0.0;\n    advect = 0.0;\n    nextV = 0.0;\n    P = 0.0;\n    force = 0.0;\n}\n\n// Calculate a simple check on a vector field\nvoid record(vectorField& V)\n{\n    // Calculate the magnitude of a field\n    const int x=0, y=1, z=2;\n    double magx = sum(pow2(V[x])) / V.numElements();\n    double magy = sum(pow2(V[y])) / V.numElements();\n    double magz = sum(pow2(V[z])) / V.numElements();\n\n    cout << \"norm = [\" << magx\n        << \" \" << magy << \" \" << magz << \" ]\" << endl;\n}\n\nvoid iterate(vectorField& V, vectorField& nextV, scalarField& P,\n    scalarField& P_rhs, vectorField& advect, vectorField& force)\n{\n    // Time step\n    applyStencil(timestep(), V, nextV, P, advect, force);\n}\n\nint main()\n{\n    vectorField V, nextV;        // Velocity fields\n    scalarField P, P_rhs;        // Pressure fields\n    vectorField advect;          // Advection field\n    vectorField force;           // Forcing function\n\n    const int N = 50;            // Arrays are NxNxN\n\n    setup(N, V, nextV, P, P_rhs, advect, force);\n\n    const int nIters = 10;\n\n    for (int i=0; i < nIters; ++i)\n    {\n        iterate(V, nextV, P, P_rhs, advect, force);\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "9090f6cd3bc02684169aec6fc7b6a0de442a17bb", "size": 4218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/cfd.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/cfd.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/cfd.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": 32.4461538462, "max_line_length": 77, "alphanum_fraction": 0.6100047416, "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5059768413733671}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n\n// Graph Type with nested interior edge properties for flow algorithms\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\ntypedef traits::vertex_descriptor vertex_desc;\ntypedef traits::edge_descriptor edge_desc;\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\n\nusing namespace std;\n\nint index(int row, int col, bool in, int cols) {\n  return 2 * (row * cols + col) + in;\n}\n\nvoid solve() {\n  int cols; cin >> cols;\n  int rows; cin >> rows;\n  int k; cin >> k;\n  int c; cin >> c;\n  \n  graph G(2 * rows * cols);\n  edge_adder adder(G);\n  \n  if (cols == 0 || rows == 0 || k == 0 || c == 0) {\n    cout << 0 << endl;\n    return;\n  } \n  \n  // Set up graph\n  for (int row = 0; row < rows; ++row) {\n    for (int col = 0; col < cols; ++col) {\n      // In to out vertex\n      adder.add_edge(index(row, col, true, cols), index(row, col, false, cols), c);\n      \n      // Neighbors\n      if (row > 0)\n        adder.add_edge(index(row - 1, col, false, cols), index(row, col, true, cols), 1);\n      if (row < rows - 1)\n        adder.add_edge(index(row + 1, col, false, cols), index(row, col, true, cols), 1);\n      if (col > 0)\n        adder.add_edge(index(row, col - 1, false, cols), index(row, col, true, cols), 1);\n      if (col < cols - 1)\n        adder.add_edge(index(row, col + 1, false, cols), index(row, col, true, cols), 1);\n\n    }\n  }\n  \n  // Set up target\n  vertex_desc target = boost::add_vertex(G);\n  for (int row = 0; row < rows; ++row) {\n    adder.add_edge(index(row, 0, false, cols), target, 1);\n    adder.add_edge(index(row, cols - 1, false, cols), target, 1);\n  }\n  for (int col = 0; col < cols; ++col) {\n    adder.add_edge(index(0, col, false, cols), target, 1);\n    adder.add_edge(index(rows - 1, col, false, cols), target, 1);\n  }\n  \n  // Set up source\n  vertex_desc source = boost::add_vertex(G);\n  int row, col;\n  for (int i = 0; i < k; ++i) {\n    cin >> col;\n    cin >> row;\n    adder.add_edge(source, index(row, col, true, cols), 1);\n  }\n  \n  \n  long flow = boost::push_relabel_max_flow(G, source, target);\n  cout << flow << endl;\n}\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  int t; cin >> t;\n  for (int i = 0; i < t; ++i) {\n    solve();\n  }\n}", "meta": {"hexsha": "e6e18c0ee88303babbca46fc961bb8b2adf1bf97", "size": 3063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/knights.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/knights.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/knights.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": 28.8962264151, "max_line_length": 93, "alphanum_fraction": 0.6085537055, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.505950436293979}}
{"text": "/*\n   Copyright (C) 2014 - 2015 by Chris Beck <render787@gmail.com>\n   Part of the Battle for Wesnoth Project http://www.wesnoth.org/\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   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY.\n\n   See the COPYING file for more details.\n*/\n\n#pragma once\n\n#include <boost/cstdint.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\nusing boost::uint32_t;\n\n//class config;\n\nnamespace wesnoth\n{\n\n/*\n   This class provides an interface, similar to simple_rng, to the \n   boost mt19937 generator. \n*/\n\nclass mt_rng\n{\npublic:\n\tmt_rng();\n\t//explicit mt_rng(const config& cfg);\n\texplicit mt_rng(boost::uint32_t seed);\n\t/** Get a new random number. */\n\tuint32_t get_next_random();\n\n\t/**\n\t *  Same as uint32_t version, but uses a stringstream to convert given\n         *  hex string. \n         *  @param seed         A hex string. Should not have 0x leading. \n         *  @param call_count   Value to set internal call counter to after seeding.\n         */ \n\tvoid seed_random(const std::string & seed, const unsigned int call_count = 0);\n\n\t/**\n\t * Resets the random to the 0 calls and the seed to the random\n\t *  this way we stay in the same sequence but don't have a lot\n\t *  calls. Used when moving to the next scenario.\n\t */\n\tvoid rotate_random();\n\n\tuint32_t get_random_seed() const { return random_seed_; }\n\tstd::string get_random_seed_str() const;\n\tunsigned int get_random_calls() const { return random_calls_; }\n\n\t//Comparisons, mainly used for testing\n\tbool operator== (const mt_rng &other) const;\n\tbool operator!= (const mt_rng &other) const\n\t{ return !operator==(other); }\n\nprivate:\n\t/** Initial seed for the pool. */\n\tuint32_t random_seed_;\n\n\t/** State for the random pool (boost mersenne twister random generator). */\n\tboost::mt19937 mt_;\n\n\t/** Number of time a random number is generated. */\n\tunsigned int random_calls_;\n\n\t/** On my local version of boost::random, I can use mt_.discard to discard a number of rng results. \n\tIn older versions this seems to be unavailable. I'm implementing as a private method of mt_rng, \n\tfollowing description here: http://www.boost.org/doc/libs/1_51_0/doc/html/boost/random/mersenne_twister_engine.html#id1408119-bb \n\t*/\n\tvoid discard(const unsigned int call_count);\n\n\t/**\n\t *  Seeds the random pool. This is the old version, I would like to mark this private.\n\t *\n\t *  @param seed         The initial value for the random engine.\n\t *  @param call_count   Upon loading we need to restore the state at saving\n\t *                      so set the number of times a random number is\n\t *                      generated for replays the orginal value is\n\t *                      required.\n\t */\n\tvoid seed_random(const uint32_t seed, const unsigned int call_count = 0);\n};\n\n} // ends wesnoth namespace\n\n", "meta": {"hexsha": "3b4398714394dbcc98df0c100ab0d24a14d206e7", "size": 3021, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/kernel/mt_rng.hpp", "max_stars_repo_name": "cbeck88/wes-kernel", "max_stars_repo_head_hexsha": "38296e9fcbda632b3cb332a807a590683dd26a1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernel/mt_rng.hpp", "max_issues_repo_name": "cbeck88/wes-kernel", "max_issues_repo_head_hexsha": "38296e9fcbda632b3cb332a807a590683dd26a1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernel/mt_rng.hpp", "max_forks_repo_name": "cbeck88/wes-kernel", "max_forks_repo_head_hexsha": "38296e9fcbda632b3cb332a807a590683dd26a1f", "max_forks_repo_licenses": ["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.8, "max_line_length": 130, "alphanum_fraction": 0.6991062562, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.505950436293979}}
{"text": "#include <iostream>\n#include <cassert>\n#include <vector>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> GraphTraits;\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, GraphTraits::edge_descriptor,\n                                                                              boost::property<boost::edge_weight_t, long>>>>>\n    Graph;\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\nstruct BoatSailorPair\n{\n  int b, s, c;\n};\n\nconst int max_possible_spectacle = 50;\n\nvoid testcase()\n{\n  int b, s, p;\n  std::cin >> b >> s >> p;\n  assert(b >= 1 && b <= 500 && s >= 1 && s <= 500 && p >= 1 && p <= b * s && p <= 5000);\n\n  std::vector<BoatSailorPair> boat_sailor_pairs(p);\n  for (BoatSailorPair &pair : boat_sailor_pairs)\n  {\n    std::cin >> pair.b >> pair.s >> pair.c;\n    assert(pair.b >= 0 && pair.b < b && pair.s >= 0 && pair.s < s && pair.c >= 1 && pair.c <= max_possible_spectacle);\n  }\n\n  int next_node_index = 0;\n  const int node_source = next_node_index++;\n  const int node_target = next_node_index++;\n  const auto get_node_boat = [next_node_index, b](int i) {\n    assert(i >= 0 && i < b);\n    return next_node_index + i;\n  };\n  next_node_index += b;\n  const auto get_node_sailor = [next_node_index, s](int i) {\n    assert(i >= 0 && i < s);\n    return next_node_index + i;\n  };\n  next_node_index += s;\n  const int num_nodes = next_node_index;\n  Graph G(num_nodes);\n\n  const auto add_edge = [&G](int from, int to, long capacity, long cost) {\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    auto w_map = boost::get(boost::edge_weight, G);\n    const Graph::edge_descriptor e = boost::add_edge(from, to, G).first;\n    const Graph::edge_descriptor rev_e = boost::add_edge(to, from, G).first;\n    c_map[e] = capacity;\n    c_map[rev_e] = 0;\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n    w_map[e] = cost;\n    w_map[rev_e] = -cost;\n  };\n\n  for (int i = 0; i < b; i++)\n  {\n    add_edge(node_source, get_node_boat(i), 1, 0);\n    add_edge(get_node_boat(i), node_target, 1, max_possible_spectacle);\n  }\n\n  for (int i = 0; i < s; i++)\n  {\n    add_edge(get_node_sailor(i), node_target, 1, 0);\n  }\n\n  for (BoatSailorPair &pair : boat_sailor_pairs)\n  {\n    add_edge(get_node_boat(pair.b), get_node_sailor(pair.s), 1, max_possible_spectacle - pair.c);\n  }\n\n  boost::successive_shortest_path_nonnegative_weights(G, node_source, node_target);\n  const int flow_cost = boost::find_flow_cost(G);\n  const int spectacle_sum = b * max_possible_spectacle - flow_cost;\n  assert(spectacle_sum > 0);\n  std::cout << spectacle_sum << \"\\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    DEBUG(1, \"\");\n  }\n\n  return 0;\n}", "meta": {"hexsha": "50f3927f5f156e31dd0124b85094203f88c363c7", "size": 3385, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "potw/fleetrace/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": "potw/fleetrace/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": "potw/fleetrace/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": 30.7727272727, "max_line_length": 130, "alphanum_fraction": 0.6064992614, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.5059504193815219}}
{"text": "#pragma once\n#include <Eigen/Core>\n\n#include \"DualIntervals.hpp\"\n\nusing namespace Eigen;\n\n#ifdef USEDOUBLE\n    using NType = double;\n#else\n    using NType = DI;\n#endif\n\ntypedef Matrix<NType, Dynamic, Dynamic, RowMajor> Mat;\ntypedef Matrix<NType, 1, Dynamic, RowMajor> RowVec;\ntypedef Matrix<Interval, Dynamic, Dynamic, RowMajor> IntervalMat;\ntypedef Matrix<double, Dynamic, Dynamic, RowMajor> DoubleMat;\n\n////////////////////////////////////////////////////////////////////////////////\n//\n// TENSOR FUNCTIONS\n//\n////////////////////////////////////////////////////////////////////////////////\n// note: tensors are implemented as arrays (3D) or multi-dimensional arrays (4D+) of matrices\n\n/*\n * 2D-Convolution with variable stride, padding, number of channels/kernels, and optional bias\n * Note: Assumes square image and kernel\n * Note: Bias is a tied bias (i.e., each kernel shares the same bias) -- pass in NULL if no bias\n * Note: delete[] must be called on the returned value explicitly\n * \n * img[n] represents an image with n channels (e.g., 3 for RGB), like a 3D-Tensor\n * kernels[i][j] represents i kernels, each with j channels (note: j must equal n), like a 4D-Tensor\n * stride represents how much the kernel is \"moved\" when doing the convolution\n * padding represents how much img is padded (with zeros) by on all sides\n */\ntemplate <int num_channels, int num_kernels>\nMat* Conv2d(Mat* img, Mat** kernels, RowVec* biases, int stride = 1, int padding = 0) {\n    int img_length = img[0].rows();            // side length of the square image\n    int kernel_length = kernels[0][0].rows();  // side length of the kernel's square sliding window\n    int kernel_size = kernel_length * kernel_length;\n    int new_img_length = std::floor(((img_length + 2 * padding - kernel_length) / stride) + 1);\n\n    // pad img\n    Mat padded_img[num_channels];\n    for (int c = 0; c < num_channels; ++c) {\n        padded_img[c] = Mat::Zero(img_length + 2 * padding, img_length + 2 * padding);\n        padded_img[c].block(padding, padding, img_length, img_length) = img[c];\n    }\n\n    // img im2col, see here: https://leonardoaraujosantos.gitbook.io/artificial-inteligence/machine_learning/deep_learning/convolution_layer/making_faster\n    // note: implemention is the transpose of what is described in the link above\n    Mat resized_img(new_img_length * new_img_length, num_channels * kernel_size);\n    for (int c = 0; c < num_channels; ++c) {\n        int curr_resized_row = 0;\n        for (int row = 0; row + kernel_length <= img_length + 2 * padding; row += stride) {\n            for (int col = 0; col + kernel_length <= img_length + 2 * padding; col += stride) {\n                Mat b = padded_img[c].block(row, col, kernel_length, kernel_length);\n                Map<RowVec> b_flattened(b.data(), 1, kernel_size);\n                resized_img.block(curr_resized_row, c * kernel_size, 1, kernel_size) = b_flattened;\n                ++curr_resized_row;\n            }\n        }\n    }\n    resized_img.transposeInPlace();\n\n    // kernel im2col\n    Mat resized_kernel(num_kernels, num_channels * kernel_size);\n    for (int k = 0; k < num_kernels; ++k) {\n        for (int c = 0; c < num_channels; ++c) {\n            Map<RowVec> k_flattened(kernels[k][c].data(), 1, kernel_size);\n            resized_kernel.block(k, c * kernel_size, 1, kernel_size) = k_flattened;\n        }\n    }\n\n    // convolution as big matrix multiplication now!\n    Mat res = resized_kernel * resized_img;\n\n    // col2im, reshape back to correct dimensions, and apply bias (if applicable)\n    if (biases) {\n        res.colwise() += biases->transpose();  // adds bias value to each row of res (corresponding to each kernel)\n    }\n\n    Mat* res_resized = new Mat[num_kernels];\n    for (int k = 0; k < num_kernels; ++k) {\n        res_resized[k] = Map<Mat>(res.row(k).data(), new_img_length, new_img_length);\n    }\n\n    return res_resized;\n}\n\n/*\n * Max-Pooling with variable stride, padding, and number of channels/kernel sizes\n * Note: Assumes square image and kernel\n * Note: delete[] must be called on the returned value explicitly\n * \n * img[n] represents an image with n channels (e.g., 3 for RGB), like a 3D-Tensor\n * kernels_length represents the side length of the kernel (in the first two dimensions)\n * padding represents how much img is padded (with zeros) by on all sides\n * stride represents how much the kernel is \"moved\" when doing the pooling\n */\ntemplate <int num_channels>\nMat* MaxPool2d(Mat img[num_channels], int kernel_length, int stride = 1, int padding = 0) {\n    int img_length = img[0].rows();\n    int new_img_length = std::floor(((img_length + 2 * padding - kernel_length) / stride) + 1);\n\n    // pad img\n    Mat padded_img[num_channels];\n    for (int c = 0; c < num_channels; ++c) {\n        padded_img[c] = Mat::Zero(img_length + 2 * padding, img_length + 2 * padding);\n        padded_img[c].block(padding, padding, img_length, img_length) = img[c];\n    }\n\n    Mat* pooled_img = new Mat[num_channels];\n    for (int c = 0; c < num_channels; ++c) {\n        int curr_row = 0, curr_col = 0;\n        pooled_img[c] = Mat(new_img_length, new_img_length);\n        for (int row = 0; row + kernel_length <= img_length + 2 * padding; row += stride) {\n            for (int col = 0; col + kernel_length <= img_length + 2 * padding; col += stride) {\n                pooled_img[c](curr_row, curr_col) = padded_img[c].block(row, col, kernel_length, kernel_length).maxCoeff();\n                ++curr_col;\n                if (curr_col >= new_img_length) {\n                    curr_col = 0;\n                    ++curr_row;\n                }\n            }\n        }\n    }\n\n    return pooled_img;\n}\n\n/* \n * Average-Pooling with variable stride, padding, and number of channels/kernel sizes\n * Everything the same as max-pooling, except we take the mean of the values in each window\n */\ntemplate <int num_channels>\nMat* AvgPool2d(Mat img[num_channels], int kernel_length, int stride = 1, int padding = 0) {\n    int img_length = img[0].rows();\n    int new_img_length = std::floor(((img_length + 2 * padding - kernel_length) / stride) + 1);\n\n    // pad img\n    Mat padded_img[num_channels];\n    for (int c = 0; c < num_channels; ++c) {\n        padded_img[c] = Mat::Zero(img_length + 2 * padding, img_length + 2 * padding);\n        padded_img[c].block(padding, padding, img_length, img_length) = img[c];\n    }\n\n    Mat* pooled_img = new Mat[num_channels];\n    for (int c = 0; c < num_channels; ++c) {\n        int curr_row = 0, curr_col = 0;\n        pooled_img[c] = Mat(new_img_length, new_img_length);\n        for (int row = 0; row + kernel_length <= img_length + 2 * padding; row += stride) {\n            for (int col = 0; col + kernel_length <= img_length + 2 * padding; col += stride) {\n                pooled_img[c](curr_row, curr_col) = padded_img[c].block(row, col, kernel_length, kernel_length).mean();\n                ++curr_col;\n                if (curr_col >= new_img_length) {\n                    curr_col = 0;\n                    ++curr_row;\n                }\n            }\n        }\n    }\n\n    return pooled_img;\n}\n\n/*\n * Pad an image by \"padding\" amount on all sides\n */\ntemplate <int num_channels>\nMat* Pad(Mat img[num_channels], int padding) {\n    int img_length = img[0].rows();\n\n\tMat* padded_img = new Mat[num_channels];;\n    for (int c = 0; c < num_channels; ++c) {\n        padded_img[c] = Mat::Zero(img_length + 2 * padding, img_length + 2 * padding); \n        padded_img[c].block(padding, padding, img_length, img_length) = img[c];\n    }\n\n\treturn padded_img;\n}\n\n/*\n * Flattens a 3D-Tensor into a single row vector, so that it can be fed into a fully-connected layer\n */\ntemplate <int num_channels>\nRowVec Flatten(Mat img[num_channels]) {\n    int img_size = img[0].rows() * img[0].cols();\n    RowVec flattened_img(1, num_channels * img_size);\n    for (int c = 0; c < num_channels; ++c) {\n        flattened_img.block(0, c * img_size, 1, img_size) = Map<RowVec>(img[c].data(), 1, img_size);\n    }\n    return flattened_img;\n}\n\n// IMPORTANT: use as an in-place operation (output will replace input)\ntemplate <int num_channels>\nMat* Relu(Mat* x) {\n    for (int c = 0; c < num_channels; ++c) {\n        #ifdef USEDOUBLE\n            x[c] = x[c].unaryExpr([](double a) { return std::max(0., a); });\n        #else\n            x[c] = x[c].unaryExpr(std::ref(relu));\n        #endif\n    }\n    return x;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//\n// MATRIX FUNCTIONS\n//\n////////////////////////////////////////////////////////////////////////////////\n\nMat Exp(const Mat& x) {\n    return ((x.array()).exp()).matrix();\n}\n\nMat Log(const Mat& x) {\n    return ((x.array()).log()).matrix();\n}\n\nMat Sqrt(const Mat& x) {\n    return ((x.array()).sqrt()).matrix();\n}\n\nMat Sin(const Mat& x) {\n    return ((x.array()).sin()).matrix();\n}\n\nMat Cos(const Mat& x) {\n    return ((x.array()).cos()).matrix();\n}\n\nMat Tanh(const Mat& x) {\n    return ((x.array()).tanh()).matrix();\n}\n\nMat Atan(const Mat& x) {\n    return ((x.array()).atan()).matrix();\n}\n\nMat Logistic(const Mat& x) {\n    return (((x.array() * 0.5).tanh()) * 0.5 + 0.5).matrix();\n}\n\nMat Softmax(const Mat& x) {\n    Mat temp = Exp(x);\n    Mat::Scalar total = temp.sum();\n    return temp / total;\n}\n\nMat Relu(const Mat& x) {\n    #ifdef USEDOUBLE\n        return x.unaryExpr([](double a) { return std::max(0., a); });\n    #else\n        return x.unaryExpr(std::ref(relu));\n    #endif\n}\n\nMat Dropout(const Mat& mask, const Mat& x) {\n    return (mask.array() * x.array()).matrix();\n}\n\ntemplate <class MatType>\ndouble Norm1(const MatType& array) {\n    size_t num_rows = array.rows();\n    size_t num_cols = array.cols();\n\n    double norm = 0.;\n    for (size_t j = 0; j < num_cols; ++j) {\n        double sum = 0.;\n        for (size_t i = 0; i < num_rows; ++i) {\n            #ifdef USEDOUBLE\n                sum += std::abs(array(i, j));\n            #else\n                Interval ij = array(i, j);\n                sum += std::max(std::abs(ij.lower()), std::abs(ij.upper()));\n            #endif\n        }\n        norm = std::max(norm, sum);\n    }\n    return norm;\n}\n\ntemplate <class MatType>\ndouble NormInf(const MatType& array) {\n    size_t num_rows = array.rows();\n    size_t num_cols = array.cols();\n\n    double norm = 0.;\n    for (size_t i = 0; i < num_rows; ++i) {\n        double sum = 0.;\n        for (size_t j = 0; j < num_cols; ++j) {\n            #ifdef USEDOUBLE\n                sum += std::abs(array(i, j));\n            #else\n                Interval ij = array(i, j);\n                sum += std::max(std::abs(ij.lower()), std::abs(ij.upper()));\n            #endif\n        }\n        norm = std::max(norm, sum);\n    }\n    return norm;\n}\n\nvoid Print(const Mat& x) {\n    for (size_t i = 0; i < x.rows(); i++) {\n        for (size_t j = 0; j < x.cols(); j++) {\n            std::cout << x(i, j) << \", \";\n        }\n        std::cout << std::endl;\n    }\n}\n", "meta": {"hexsha": "5f0290dd3da0036640aef05316d69061f628b09a", "size": 10894, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/MatrixFunctions.hpp", "max_stars_repo_name": "uiuc-arc/DeepJ", "max_stars_repo_head_hexsha": "1c0493511b12394ca6f9a0098d3401cdcab50806", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-20T15:46:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T16:51:37.000Z", "max_issues_repo_path": "src/MatrixFunctions.hpp", "max_issues_repo_name": "uiuc-arc/DeepJ", "max_issues_repo_head_hexsha": "1c0493511b12394ca6f9a0098d3401cdcab50806", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MatrixFunctions.hpp", "max_forks_repo_name": "uiuc-arc/DeepJ", "max_forks_repo_head_hexsha": "1c0493511b12394ca6f9a0098d3401cdcab50806", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-31T02:02:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T02:02:43.000Z", "avg_line_length": 34.4746835443, "max_line_length": 154, "alphanum_fraction": 0.5861942354, "num_tokens": 2892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5059504192308916}}
{"text": "/******************************************************************************\n * Author:   Laurent Kneip                                                    *\n * Contact:  kneip.laurent@gmail.com                                          *\n * License:  Copyright (c) 2013 Laurent Kneip, ANU. 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 * * 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 ANU nor the names of its contributors may be         *\n *   used to endorse or promote products derived from this software without   *\n *   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 ANU OR THE 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         *\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 * \\file Sturm.hpp\n * \\brief Class for evaluating Sturm chains on polynomials, and bracketing the\n *        real roots.\n */\n\n#ifndef OPENGV_STURM_HPP_\n#define OPENGV_STURM_HPP_\n\n#include <stdlib.h>\n#include <vector>\n#include <Eigen/Eigen>\n\n/**\n * \\brief The namespace of this library.\n */\nnamespace opengv\n{\n/**\n * \\brief The namespace of the math tools.\n */\nnamespace math\n{\n\n/**\n * Sturm is initialized over polynomials of arbitrary order, and used to compute\n * the real roots of the polynomial.\n */\nclass Sturm\n{\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  /** A pair of values bracketing a real root */\n  typedef std::pair<double,double> bracket_t;\n\n  /**\n   * \\brief Contructor.\n   * \\param[in] p The polynomial coefficients (poly = p(0,0)*x^n + p(0,1)*x^(n-1) ...).\n   */\n  Sturm( const Eigen::MatrixXd & p );\n  /**\n   * \\brief Contructor.\n   * \\param[in] p The polynomial coefficients (poly = p[0]*x^n + p[1]*x^(n-1) ...).\n   */\n  Sturm( const std::vector<double> & p );\n  /**\n   * \\brief Destructor.\n   */\n  virtual ~Sturm();\n\n  /**\n   * \\brief Finds the roots of the polynomial.\n   * \\return An array with the real roots of the polynomial.\n   */\n  std::vector<double> findRoots();\n  /**\n   * \\brief Finds brackets for the real roots of the polynomial.\n   * \\return An array of brackets for the real roots of the polynomial.\n   */\n  std::vector<bracket_t> bracketRoots();\n  /**\n   * \\brief Evaluates the Sturm chain for a bracket.\n   * \\param[in] leftBound The left value of the bracket.\n   * \\param[in] rightBound The right value of the bracket.\n   * \\return The number of real roots in the given bracket.\n   */\n  size_t evaluateChain( double leftBound, double rightBound );\n\nprivate:\n  /**\n   * \\brief Internal function used for composing the Sturm chain\n   * \\param[in] p1 First polynomial.\n   * \\param[in] p2 Second polynomial.\n   * \\param[out] r The negated remainder of the polynomial division p1/p2.\n   */\n  void computeNegatedRemainder(\n      const Eigen::MatrixXd & p1,\n      const Eigen::MatrixXd & p2,\n      Eigen::MatrixXd & r );\n  /**\n   * \\brief Internal function used for composing an initial bracket for all\n   *        the roots of the polynomial.\n   * \\return The maximum of the absolute values of the bracket-values (That's\n   *         what the Lagrangian bound is able to find).\n   */\n  double computeLagrangianBound();\n\n  /** A matrix containing the coefficients of the Sturm-chain of the polynomial */\n  Eigen::MatrixXd _C;\n  /** The dimension _C, which corresponds to (polynomial order+1) */\n  size_t _dimension;\n};\n\n}\n}\n\n#endif /* OPENGV_STURM_HPP_ */\n", "meta": {"hexsha": "6afec15dec780ad20fca1e4758322162c7627a29", "size": 4913, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/opengv/math/Sturm.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "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/opengv/math/Sturm.hpp", "max_issues_repo_name": "PXLVision/opengv", "max_issues_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/opengv/math/Sturm.hpp", "max_forks_repo_name": "PXLVision/opengv", "max_forks_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "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.0852713178, "max_line_length": 87, "alphanum_fraction": 0.6024832078, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5059504192308916}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   DataGen_OccupationNumberEvaluator.hpp\n//! \\author Alex Robinson\n//! \\brief  The occupation number evaluator declaration\n//! \n//---------------------------------------------------------------------------//\n\n#ifndef DATA_GEN_OCCUPATION_NUMBER_EVALUATOR_HPP\n#define DATA_GEN_OCCUPATION_NUMBER_EVALUATOR_HPP\n\n// Boost Includes\n#include <boost/scoped_ptr.hpp>\n\n// Trilinos Includes\n#include <Teuchos_Array.hpp>\n\n// FRENSIE Includes\n#include \"Utility_TabularDistribution.hpp\"\n\nnamespace DataGen{\n\n//! The occupation number evaluator\nclass OccupationNumberEvaluator\n{\n\npublic:\n  \n  //! Constructor\n  OccupationNumberEvaluator(\n\t\t   const Teuchos::Array<double>& electron_momentum_projections,\n\t\t   const Teuchos::Array<double>& compton_profile,\n\t\t   const double norm_constant_precision = 1e-6 );\n\n  //! Destructor\n  ~OccupationNumberEvaluator()\n  { /* ... */ }\n\n  //! Return the normalization constant used with the Compton profile\n  double getComptonProfileNormConstant() const;\n\n  //! Evaluate the compton profile\n  double evaluateComptonProfile( \n\t\t\t     const double electron_momentum_projection ) const;\n\n  //! Return the occupation number at a given electron momentum projection\n  double evaluateOccupationNumber( const double electron_momentum_projection,\n\t\t\t\t   const double precision = 1e-6 ) const;\n\nprivate:\n\n  // The compton profile normalization constant (rounding error issue)\n  double d_compton_profile_norm_constant;\n\n  // The compton profile\n  boost::scoped_ptr<const Utility::TabularDistribution<Utility::LogLin> >\n  d_compton_profile;\n};\n\n} // end DataGen namespace\n\n#endif // end DATA_GEN_OCCUPATION_NUMBER_EVALUATOR_HPP\n\n//---------------------------------------------------------------------------//\n// end DataGen_OccupationNumberEvaluator.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "7b50cd20aa619bc72f319317565c450aa7efa8fc", "size": 1937, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/data_gen/electron_photon/src/DataGen_OccupationNumberEvaluator.hpp", "max_stars_repo_name": "lkersting/SCR-2123", "max_stars_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "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": "packages/data_gen/electron_photon/src/DataGen_OccupationNumberEvaluator.hpp", "max_issues_repo_name": "lkersting/SCR-2123", "max_issues_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/data_gen/electron_photon/src/DataGen_OccupationNumberEvaluator.hpp", "max_forks_repo_name": "lkersting/SCR-2123", "max_forks_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "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.9104477612, "max_line_length": 79, "alphanum_fraction": 0.644295302, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.505950407654659}}
{"text": "#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/random_spanning_tree.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/array.hpp>\n#include <array>\n#include <utility>\n#include <random>\n#include <iostream>\n#include <ctime>\n#include <cstdint>\n\nint main()\n{\n  enum { topLeft, topRight, bottomRight, bottomLeft };\n\n  std::array<std::pair<int, int>, 4> edges{{\n    std::make_pair(topLeft, topRight),\n    std::make_pair(topRight, bottomRight),\n    std::make_pair(bottomRight, bottomLeft),\n    std::make_pair(bottomLeft, topLeft)\n  }};\n\n  struct edge_properties\n  {\n    int weight;\n  };\n\n  typedef boost::adjacency_list<boost::listS, boost::vecS,\n    boost::undirectedS> graph;\n\n  graph g{edges.begin(), edges.end(), 4};\n\n  boost::array<int, 4> predecessors;\n\n  std::mt19937 gen{static_cast<uint32_t>(std::time(0))};\n  boost::random_spanning_tree(g, gen,\n    boost::predecessor_map(predecessors.begin()).\n    root_vertex(bottomLeft));\n\n  int p = topRight;\n  while (p != -1)\n  {\n    std::cout << p << '\\n';\n    p = predecessors[p];\n  }\n}", "meta": {"hexsha": "9e007a27f8b5e4f633b7f3b3523b35e54f117218", "size": 1064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Example/graph_14/main.cpp", "max_stars_repo_name": "KwangjoJeong/Boost", "max_stars_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_stars_repo_licenses": ["MIT"], "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/graph_14/main.cpp", "max_issues_repo_name": "KwangjoJeong/Boost", "max_issues_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_issues_repo_licenses": ["MIT"], "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/graph_14/main.cpp", "max_forks_repo_name": "KwangjoJeong/Boost", "max_forks_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_forks_repo_licenses": ["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.1304347826, "max_line_length": 58, "alphanum_fraction": 0.6813909774, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5059155159852576}}
{"text": "/*\n *  cholesky_boost.cpp\n *  Jan07 \n *  Created by  Adwait Joshi\n *  Project: Arcee\n *\n *  Copyright (c) 2007-2008 The Trustees of Indiana University. All rights reserved.\n *\n */\n\n#include <iostream>\n#include <string>\n#include <boost/test/minimal.hpp>\n#include <boost/tuple/tuple.hpp>\n\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/morton_dense.hpp>\n#include <boost/numeric/mtl/matrix/transposed_view.hpp>\n#include <boost/numeric/mtl/matrix/parameter.hpp>\n#include <boost/numeric/mtl/operation/print_matrix.hpp>\n#include <boost/numeric/mtl/operation/sub_matrix.hpp>\n#include <boost/numeric/mtl/recursion/matrix_recursator.hpp>\n#include <boost/numeric/mtl/recursion/base_case_test.hpp>\n#include <boost/numeric/mtl/recursion/for_each.hpp>\n\n//#include \"base_Cases_Boost.h\"\n#include \"base_Cases_Boost_new.h\"\n\nusing namespace mtl;\nusing namespace std;  \n\ntypedef dense2D<double> matrix_type; \n//typedef morton_dense<double,  0x55555555> matrix_type; \nconst int order=4200 ; \nconst int basecasesize =32;\nrecursion::bound_test_static<basecasesize>    is_base;\n\n\nint  callnum = 0, basehit = 0;\nint docholcall=0;\nint schurcall=0;\nint trischurcall=0;\nint trisolvecall=0;\n\n\ntemplate <typename Matrix>\nvoid print_matrix(Matrix& matrix){ \n\tfor (int i=0 ; i<matrix.num_rows(); i++ ){\n\t\tfor(int j=0; j<matrix.num_cols();  j++ ){\n\t\t   cout.fill (' '); cout.width (8); cout.precision (5); cout.flags (ios_base::left);\n\t\t   cout << showpoint <<  matrix[i][j] <<\"  \";\n\t\t}\n\t\tcout << endl;\n\t}\n\treturn;\n}\n\n\n\n\ntemplate <typename Matrix>\nvoid fill_matrix(Matrix& matrix){\n    typename traits::row<Matrix>::type                                 row(matrix);\n    typename traits::col<Matrix>::type                                 col(matrix);\n    typename traits::value<Matrix>::type                               value(matrix);\n    typedef  glas::tag::nz                                          tag;\n    typedef typename traits::range_generator<tag, Matrix>::type        cursor_type;\n    \n    double x= 1.0;      \n    for(int i=0;i<matrix.num_rows();i++) {\n       for(int j=0;j<=i;j++){\n         if(i!=j){\n\t          matrix[i][j]=x; matrix[j][i]=x; \n\t          x=x+1.0; \n\t       }\n       }\n    }\n  \n    double rowsum;\n    for(int i=0;i<matrix.num_rows();i++){\n       rowsum=0.0;\n       for(int j=0;j<matrix.num_cols();j++){\n         if(i!=j){\n\t          rowsum += matrix[i][j]; \n\t       }\n       }\n       matrix[i][i]=rowsum*2;\n    }       \n}\n\n\ntemplate <typename Recursator>\nvoid schur(Recursator E, Recursator W, Recursator N)\n{\n  if (E.is_empty() || W.is_empty() || N.is_empty())\n    return;\n\n  if(is_base(E)){\n     typename Recursator::matrix_type  base_E(E.get_value()), base_W(W.get_value()),base_N(N.get_value());\n     schur_base(base_E, base_W, base_N);\n  }\n  else{\n    schur(     E.north_east(),W.north_west()     ,N.south_west()     );\n    schur(     E.north_east(),     W.north_east(),     N.south_east());\n    \n    schur(E.north_west()     ,     W.north_east(),     N.north_east());\n    schur(E.north_west()     ,W.north_west()     ,N.north_west()     );\n    \n    schur(E.south_west()     ,W.south_west()     ,N.north_west()     );\n    schur(E.south_west()     ,     W.south_east(),     N.north_east());\n    \n    schur(     E.south_east(),     W.south_east(),     N.south_east());\n    schur(     E.south_east(),W.south_west()     ,N.south_west()     );\n  }\n}\n\n\n\n\n\ntemplate <typename Recursator>\nvoid tri_solve(Recursator S, Recursator N)\n{\n  if (S.is_empty())\n    return;\n\n  if(is_base(S)){   \n     typename Recursator::matrix_type  base_S(S.get_value()), base_N(N.get_value());\n     tri_solve_base(base_S, base_N);\n  }\n  else{ \n  tri_solve(S.north_west()     ,N.north_west()     );\n  \t \n      schur(     S.north_east(),S.north_west()     ,N.south_west()     );\n     \n  tri_solve(     S.north_east(),     N.south_east());\n\n  tri_solve(S.south_west()     ,N.north_west()     );\n     \n      schur(     S.south_east(),S.south_west()     ,N.south_west()     );\n     \n  tri_solve(     S.south_east(),     N.south_east());\n  }\n}\n\n\n\n\n\ntemplate <typename Recursator>\nvoid tri_schur(Recursator E, Recursator W)\n{ \n  if (E.is_empty() || W.is_empty())\n    return;\n\n  if(is_base(W)){\n     typename Recursator::matrix_type  base_E(E.get_value()), base_W(W.get_value());\n     tri_schur_base(base_E, base_W);\n  }\n  else{ \n      schur(     E.south_west(),     W.south_west(),    W.north_west());\n\n      schur(     E.south_west(),     W.south_east(),    W.north_east());\n\t\n  tri_schur(E.south_east()     ,     W.south_east());\n\n  tri_schur(E.south_east()     ,W.south_west()     );\n\n  tri_schur(     E.north_west(),     W.north_east());\n\n  tri_schur(     E.north_west(),W.north_west()     );\n  }\n}\n\n \ntemplate <typename Recursator>\nvoid\ndo_cholesky (Recursator recursator)\n{\n  if (recursator.is_empty())\n    return;\n\n  if (is_base (recursator)){    \n      typename Recursator::matrix_type  base_matrix(recursator.get_value());\n      do_cholesky_base (base_matrix);      \n  }\n  else{\n\n    do_cholesky(recursator.north_west()     );\n      \n      tri_solve(recursator.south_west()     ,recursator.north_west()     );\n\n      tri_schur(     recursator.south_east(),recursator.south_west()     );\n\n    do_cholesky(     recursator.south_east());\n\n  }\n}\n\nint test_main(int argc, char* argv[])\n{\n\n  //    cout << \"=====================\\n\" << \"Morton-ordered matrix\\n\" << \"=====================\\n\\n\";\n  matrix_type matrix(order,order);   \n  time_t starttime,endtime;\n  struct tm *timeinfo;\n  \n  time (&starttime);\n  timeinfo = localtime (&starttime);\n  \n  printf(\"----------order = %d      Basecase = %d  -------------------->Load start: %s\",\n\t order, basecasesize, asctime (timeinfo));\n  \n  \n  fill_matrix(matrix); \n  // test_sub_matrix(matrix);\n  recursion::mat::recursator<matrix_type> recursator(matrix);\n  // print_matrix(matrix);\n  time (&starttime);\n  timeinfo = localtime (&starttime);\n  printf(\"----------order = %d      Basecase = %d  -------------------->Start date and time are: %s\",\n     order, basecasesize, asctime (timeinfo));\n\t\t\t\t\t  \n  do_cholesky(recursator); \n  \n  \n  //    cout << \"\\n=============================\\n\"\t <<   \"Again with cholesky\\n\"\t <<   \"=============================\\n\\n\";\n  \n  time (&endtime);\n  timeinfo = localtime (&endtime);\n  printf(\"----------order = %d      Basecase = %d  ------------------->End date and time are: %s\",\n     order, basecasesize, asctime (timeinfo));\n  //printf (\"\\nRec calls: %d    Basehits: %d\\n\", callnum, basehit);\n  \n  printf\n    (\"\\nTOTAL TIME TAKEN for order = %d      Basecase = %d  : %d  secs\\n\\n\",\n     order, basecasesize, endtime - starttime);\n  \n   //cout << \"\\n\\n\\n\\n\\n\\n\";\n     \n // print_matrix(matrix); \n /*     cout << \"\\n=============================\\n\"\t;\n   \n\t\tfor(int i=0 ; i<matrix.num_rows();  i++ ){\n\t\t\tfor (int j=i+1; j<matrix.num_cols(); j++ )\t\t\t \n\t    matrix[i][j]=0;\n\t    }\n   \n   print_matrix(matrix); \n   cout  <<      \"=============================\\n\\n\";\n    verify_matrix(matrix);\n   cout  <<      \"=============================\\n\\n\";\n   print_matrix(matrix);*/\n\n     //printf(\"Rec Calls:\\ndocholcall: %d\\nschurcall: %d\\ntrischurcall:%d\\ntrisolvecall:%d\\n\", \t docholcall, schurcall, trischurcall,trisolvecall);\n     //printf(\"\\nbasecase calls\\ndocholhits:%d\\nschurhits:%d\\ntrischurhits:%d\\ntrisolvehits:%d\\n\",\t   docholeskyhits , schurhits , trischurhits, trisolvehits);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "4ddd4561a9ddb14513c1949197f293f618be6926", "size": 7381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/cholesky/cholesky.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/cholesky/cholesky.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/cholesky/cholesky.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": 28.2796934866, "max_line_length": 159, "alphanum_fraction": 0.5786478797, "num_tokens": 2195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5059155084014354}}
{"text": "//==============================================================================\n//         Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 & onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TOOLBOX_LINALG_FUNCTIONS_COV_HPP_INCLUDED\n#define NT2_TOOLBOX_LINALG_FUNCTIONS_COV_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <nt2/include/functions/sqr_abs.hpp>\n#include <boost/simd/toolbox/constant/constants/zero.hpp>\n\n\nnamespace nt2 {  namespace tag\n  {\n    /*!\n     * \\brief Define the tag expm_ of functor expm\n     *        in namespace nt2::tag for toolbox algebra\n    **/\n    struct cov_ : tag::formal_\n    {\n       typedef tag::formal_ parent;\n    };\n  }\n  /**\n   * @brief compute covariance matrix expression\n   *\n   * If x is a vector,  cov(x) returns the variance\n   * For matrices, where each row is an observation, and each column a variable,\n   * cov(x) is the covariance matrix.  diag(cov(x)) is a vector of\n   * variances for each column, and sqrt(diag(cov(x))) is a vector\n   * of standard deviations.\n   * cov(x,y), where x and y are matrices with the same number of elements,\n   * is equivalent to cov(horzcat(x(_) y(_))).\n   *\n   * cov(x) or cov(x,y) normalizes by (n-1) if n>1, where n is the number of\n   * observations.  this makes cov(x) the best unbiased estimate of the\n   * covariance matrix if the observations are from a normal distribution.\n   * for n=1, cov normalizes by n.\n   *\n   *  cov(x,1) or cov(x,y,1) normalizes by n and produces the second\n   * moment matrix of the observations about their mean.  cov(x,y,0) is\n   * the same as cov(x,y) and cov(x,0) is the same as cov(x).\n   *\n   * the mean is removed from each column before calculating the\n   * result.\n   *\n  **/\n\n  NT2_FUNCTION_IMPLEMENTATION(nt2::tag::cov_       , cov, 1)\n  NT2_FUNCTION_IMPLEMENTATION(nt2::tag::cov_       , cov, 2)\n  NT2_FUNCTION_IMPLEMENTATION(nt2::tag::cov_       , cov, 3)\n}\n\n#endif\n", "meta": {"hexsha": "29f33116b4e1d80119201dce3267b4db1ba8e17d", "size": 2238, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/toolbox/linalg/functions/cov.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/linalg/include/nt2/toolbox/linalg/functions/cov.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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": "modules/core/linalg/include/nt2/toolbox/linalg/functions/cov.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "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": 37.9322033898, "max_line_length": 80, "alphanum_fraction": 0.6170688114, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5059155084014354}}
{"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_POW_ABS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_POW_ABS_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_abs capabilities\n\n    Computes \\f$|x|^y\\f$.\n\n    @par Semantic:\n\n    For every parameters of floating type  T:\n\n    @code\n    T r = pow_abs(x, y);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = pow(abs(x), y);\n    @endcode\n\n    @see pow, abs\n\n  **/\n  const boost::dispatch::functor<tag::pow_abs_> pow_abs = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/pow_abs.hpp>\n#include <boost/simd/function/simd/pow_abs.hpp>\n\n#endif\n", "meta": {"hexsha": "14c6869383732c7abe49f840ee9f69ae06f37454", "size": 1095, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/pow_abs.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/pow_abs.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/pow_abs.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": 21.4705882353, "max_line_length": 100, "alphanum_fraction": 0.5652968037, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5059155041470759}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2013 Adam Wulkiewicz, Lodz, Poland.\n\n// This file was modified by Oracle on 2018-2020.\n// Modifications copyright (c) 2018-2020 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#ifndef BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_ALGORITHMS_TRANSFORM_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_ALGORITHMS_TRANSFORM_HPP\n\n#include <type_traits>\n\n#include <boost/geometry/algorithms/convert.hpp>\n#include <boost/geometry/arithmetic/arithmetic.hpp>\n#include <boost/geometry/core/static_assert.hpp>\n#include <boost/geometry/extensions/algebra/algorithms/detail.hpp>\n#include <boost/geometry/extensions/algebra/geometries/concepts/vector_concept.hpp>\n#include <boost/geometry/extensions/algebra/geometries/concepts/rotation_quaternion_concept.hpp>\n#include <boost/geometry/extensions/algebra/geometries/concepts/rotation_matrix_concept.hpp>\n#include <boost/geometry/geometries/concepts/check.hpp>\n\nnamespace boost { namespace geometry {\n\nnamespace detail { namespace transform_geometrically {\n\ntemplate <typename Box, typename Vector, std::size_t Dimension>\nstruct box_vector_cartesian\n{\n    BOOST_GEOMETRY_STATIC_ASSERT(\n        (Dimension > 0),\n        \"Dimension has to be greater than 0.\",\n        Box);\n\n    static inline void apply(Box & box, Vector const& vector)\n    {\n        box_vector_cartesian<Box, Vector, Dimension-1>::apply(box, vector);\n        set<min_corner, Dimension-1>(box, get<min_corner, Dimension-1>(box) + get<Dimension-1>(vector));\n        set<max_corner, Dimension-1>(box, get<max_corner, Dimension-1>(box) + get<Dimension-1>(vector));\n    }\n};\n\ntemplate <typename Box, typename Vector>\nstruct box_vector_cartesian<Box, Vector, 1>\n{\n    static inline void apply(Box & box, Vector const& vector)\n    {\n        set<min_corner, 0>(box, get<min_corner, 0>(box) + get<0>(vector));\n        set<max_corner, 0>(box, get<max_corner, 0>(box) + get<0>(vector));\n    }\n};\n\n}} // namespace detail::transform\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch {\n\ntemplate <typename Geometry, typename Transform,\n          typename GTag = typename tag<Geometry>::type,\n          typename TTag = typename tag<Transform>::type>\nstruct transform_geometrically\n{\n    BOOST_GEOMETRY_STATIC_ASSERT_FALSE(\n        \"Not implemented for this Geometry.\",\n        Geometry, Transform);\n};\n\n// Point translation by Vector\ntemplate <typename Point, typename Vector>\nstruct transform_geometrically<Point, Vector, point_tag, vector_tag>\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Point<Point>) );\n    BOOST_CONCEPT_ASSERT( (concepts::Vector<Vector>) );\n\n    static inline void apply(Point & point, Vector const& vector)\n    {\n        typedef std::is_same\n            <\n                typename traits::coordinate_system<Point>::type,\n                cs::cartesian\n            > is_cartesian;\n        apply(point, vector, is_cartesian());\n    }\n\n    static inline void apply(Point & point, Vector const& vector, std::true_type /*is_cartesian*/)\n    {\n        for_each_coordinate(point, detail::point_operation<Vector, std::plus>(vector));\n    }\n\n    static inline void apply(Point & point, Vector const& vector, std::false_type /*is_cartesian*/)\n    {\n        BOOST_GEOMETRY_STATIC_ASSERT_FALSE(\n            \"Not implemented for this coordinate system.\",\n            typename traits::coordinate_system<Point>::type);\n    }\n};\n\n// Box translation by Vector\ntemplate <typename Box, typename Vector>\nstruct transform_geometrically<Box, Vector, box_tag, vector_tag>\n{\n    typedef typename traits::point_type<Box>::type point_type;\n\n    BOOST_CONCEPT_ASSERT( (concepts::Point<point_type>) );\n    BOOST_CONCEPT_ASSERT( (concepts::Vector<Vector>) );\n\n    static inline void apply(Box & box, Vector const& vector)\n    {\n        typedef std::is_same\n            <\n                typename traits::coordinate_system<point_type>::type,\n                cs::cartesian\n            > is_cartesian;\n        apply(box, vector, is_cartesian());\n    }\n\n    static inline void apply(Box & box, Vector const& vector, std::true_type /*is_cartesian*/)\n    {\n        geometry::detail::transform_geometrically::box_vector_cartesian<\n            Box, Vector, traits::dimension<point_type>::value\n        >::apply(box, vector);\n    }\n\n    static inline void apply(Box & box, Vector const& vector, std::false_type /*is_cartesian*/)\n    {\n        BOOST_GEOMETRY_STATIC_ASSERT_FALSE(\n            \"Not implemented for this coordinate system.\",\n            typename traits::coordinate_system<point_type>::type);\n    }\n};\n\n// Vector rotation by Quaternion\ntemplate <typename Vector, typename RotationQuaternion>\nstruct transform_geometrically<Vector, RotationQuaternion, vector_tag, rotation_quaternion_tag>\n{\n    static inline void apply(Vector & v, RotationQuaternion const& r)\n    {\n        concepts::check_concepts_and_equal_dimensions<Vector, RotationQuaternion const>();\n\n        detail::algebra::quaternion_rotate(v, r);\n    }\n};\n\n// Vector rotation by Matrix\ntemplate <typename Vector, typename RotationMatrix>\nstruct transform_geometrically<Vector, RotationMatrix, vector_tag, rotation_matrix_tag>\n{\n    static inline void apply(Vector & v, RotationMatrix const& r)\n    {\n        concepts::check_concepts_and_equal_dimensions<Vector, RotationMatrix const>();\n\n        // TODO vector_type and convert from Vector\n        Vector tmp(v);\n        detail::algebra::matrix_rotate(r, tmp, v);\n    }\n};\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\ntemplate <typename Geometry, typename Transformation>\ninline void transform_geometrically(Geometry & g, Transformation const& t)\n{\n    dispatch::transform_geometrically<Geometry, Transformation>::apply(g, t);\n}\n\ntemplate <typename GeometrySrc, typename Transformation, typename GeometryDst>\ninline void transformed_geometrically(GeometrySrc const& gsrc, Transformation const& t, GeometryDst & gdst)\n{\n    geometry::convert(gsrc, gdst);\n    geometry::transform_geometrically(gdst, t);\n}\n\ntemplate <typename GeometryDst, typename GeometrySrc, typename Transformation>\ninline GeometryDst return_transformed_geometrically(GeometrySrc const& gsrc, Transformation const& t)\n{\n    GeometryDst res;\n    transformed_geometrically(gsrc, t, res);\n    return res;\n}\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_ALGORITHMS_TRANSFORM_HPP\n", "meta": {"hexsha": "6f0759a3de79ff81a43f902d680539a61c05f29e", "size": 6572, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/algebra/algorithms/transform_geometrically.hpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 709.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T07:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:02:22.000Z", "max_issues_repo_path": "include/boost/geometry/extensions/algebra/algorithms/transform_geometrically.hpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 415.0, "max_issues_repo_issues_event_min_datetime": "2017-05-21T05:05:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T16:08:27.000Z", "max_forks_repo_path": "include/boost/geometry/extensions/algebra/algorithms/transform_geometrically.hpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 123.0, "max_forks_repo_forks_event_min_datetime": "2016-03-19T12:47:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T03:47:51.000Z", "avg_line_length": 34.7724867725, "max_line_length": 107, "alphanum_fraction": 0.7207851491, "num_tokens": 1472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5059154934187144}}
{"text": "/*\r\n * Copyright 2018 Pedro Proenza <p.proenca@surrey.ac.uk> (University of Surrey)\r\n *\r\n */\r\n\r\n#include <iostream>\r\n#include <cstdio>\r\n#define _USE_MATH_DEFINES\r\n#include <math.h>\r\n#include <opencv2/opencv.hpp>\r\n#include <Eigen/Dense>\r\n#include \"CAPE/CAPE.h\"\r\n\r\nbool done = false;\r\nfloat COS_ANGLE_MAX = cos(M_PI/12);\r\nfloat MAX_MERGE_DIST = 50.0f;\r\nbool cylinder_detection= true;\r\nCAPE * plane_detector;\r\nstd::vector<cv::Vec3b> color_code;\r\n\r\nbool loadCalibParameters(std::string filepath, cv:: Mat & intrinsics_rgb, cv::Mat & dist_coeffs_rgb, cv:: Mat & intrinsics_ir, cv::Mat & dist_coeffs_ir, cv::Mat & R, cv::Mat & T){\r\n\r\n    cv::FileStorage fs(filepath,cv::FileStorage::READ);\r\n    if (fs.isOpened()){\r\n        fs[\"RGB_intrinsic_params\"]        >> intrinsics_rgb;\r\n        fs[\"RGB_distortion_coefficients\"] >> dist_coeffs_rgb;\r\n        fs[\"IR_intrinsic_params\"]         >> intrinsics_ir;\r\n        fs[\"IR_distortion_coefficients\"]  >> dist_coeffs_ir;\r\n        fs[\"Rotation\"]                    >> R;\r\n        fs[\"Translation\"]                 >> T;\r\n        fs.release();\r\n        return true;\r\n    }else{\r\n        std::cerr << \"Calibration file missing\" << std::endl;\r\n        return false;\r\n    }\r\n}\r\n\r\nvoid projectPointCloud(cv::Mat & X, cv::Mat & Y, cv::Mat & Z, cv::Mat & U, cv::Mat & V, float fx_rgb, float fy_rgb, float cx_rgb, float cy_rgb, double z_min, Eigen::MatrixXf & cloud_array){\r\n\r\n    int width = X.cols;\r\n    int height = X.rows;\r\n\r\n    // Project to image coordinates\r\n    cv::divide(X,Z,U,1);\r\n    cv::divide(Y,Z,V,1);\r\n    U = U*fx_rgb + cx_rgb;\r\n    V = V*fy_rgb + cy_rgb;\r\n    // Reusing U as cloud index\r\n    //U = V*width + U + 0.5;\r\n\r\n    float * sz, * sx, * sy, * u_ptr, * v_ptr, * id_ptr;\r\n    float z, u, v;\r\n    int id;\r\n    for(int r=0; r< height; r++){\r\n        sx = X.ptr<float>(r);\r\n        sy = Y.ptr<float>(r);\r\n        sz = Z.ptr<float>(r);\r\n        u_ptr = U.ptr<float>(r);\r\n        v_ptr = V.ptr<float>(r);\r\n        for(int c=0; c< width; c++){\r\n            z = sz[c];\r\n            u = u_ptr[c];\r\n            v = v_ptr[c];\r\n            if(z>z_min && u>0 && v>0 && u<width && v<height){\r\n                id = floor(v)*width + u;\r\n                cloud_array(id,0) = sx[c];\r\n                cloud_array(id,1) = sy[c];\r\n                cloud_array(id,2) = z;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nvoid organizePointCloudByCell(Eigen::MatrixXf & cloud_in, Eigen::MatrixXf & cloud_out, cv::Mat & cell_map){\r\n    int width = cell_map.cols;\r\n    int height = cell_map.rows;\r\n    int mxn = width*height;\r\n    int mxn2 = 2*mxn;\r\n\r\n    int id, it(0);\r\n    int * cell_map_ptr;\r\n    for(int r=0; r< height; r++){\r\n        cell_map_ptr = cell_map.ptr<int>(r);\r\n        for(int c=0; c< width; c++){\r\n            id = cell_map_ptr[c];\r\n            *(cloud_out.data() + id) = *(cloud_in.data() + it);\r\n            *(cloud_out.data() + mxn + id) = *(cloud_in.data() + mxn + it);\r\n            *(cloud_out.data() + mxn2 + id) = *(cloud_in.data() + mxn2 + it);\r\n            it++;\r\n        }\r\n    }\r\n}\r\n\r\nint main(int argc, char ** argv){\r\n\r\n    std::string sequence;\r\n    int PATCH_SIZE;\r\n    if (argc>1){\r\n        PATCH_SIZE = atoi(argv[1]);\r\n        sequence = argv[2];\r\n    }else{\r\n        PATCH_SIZE = 20;\r\n        sequence = \"pipe\";\r\n    }\r\n\r\n    std::stringstream string_buff;\r\n    std::string data_path = \"/home/grvc/programming/CAPE/Data/\";\r\n    string_buff << data_path << sequence;\r\n\r\n    // Get intrinsics\r\n    cv::Mat K_rgb, K_ir, dist_coeffs_rgb, dist_coeffs_ir, R_stereo, t_stereo;\r\n    std::stringstream calib_path;\r\n    calib_path << string_buff.str() << \"/calib_params.xml\";\r\n    loadCalibParameters(calib_path.str(), K_rgb, dist_coeffs_rgb, K_ir, dist_coeffs_ir, R_stereo, t_stereo);\r\n    float fx_ir  = K_ir.at<double>(0,0);  float fy_ir = K_ir.at<double>(1,1);\r\n    float cx_ir  = K_ir.at<double>(0,2);  float cy_ir = K_ir.at<double>(1,2);\r\n    float fx_rgb = K_rgb.at<double>(0,0); float fy_rgb = K_rgb.at<double>(1,1);\r\n    float cx_rgb = K_rgb.at<double>(0,2); float cy_rgb = K_rgb.at<double>(1,2);\r\n\r\n    // Read frame 1 to allocate and get dimension\r\n    cv::Mat rgb_img, d_img;\r\n    int width, height;\r\n    std::stringstream image_path;\r\n    std::stringstream depth_img_path;\r\n    std::stringstream rgb_img_path;\r\n    rgb_img_path   << string_buff.str() << \"/rgb_0.png\";\r\n    depth_img_path << string_buff.str() << \"/depth_0.png\";\r\n\r\n    rgb_img = cv::imread(rgb_img_path.str(),cv::IMREAD_COLOR);\r\n\r\n    if(rgb_img.data){\r\n        width = rgb_img.cols;\r\n        height = rgb_img.rows;\r\n    }else{\r\n        std::cout << \"Error loading file\";\r\n        return -1;\r\n    }\r\n\r\n    int nr_horizontal_cells = width/PATCH_SIZE;\r\n    int nr_vertical_cells = height/PATCH_SIZE;\r\n\r\n    // Pre-computations for backprojection\r\n    cv::Mat_<float> X_pre(height,width);\r\n    cv::Mat_<float> Y_pre(height,width);\r\n    cv::Mat_<float> U(height,width);\r\n    cv::Mat_<float> V(height,width);\r\n    for (int r=0;r<height; r++){\r\n        for (int c=0;c<width; c++){\r\n            // Not efficient but at this stage doesn t matter\r\n            X_pre.at<float>(r,c) = (c-cx_ir)/fx_ir; \r\n            Y_pre.at<float>(r,c) = (r-cy_ir)/fy_ir;\r\n        }\r\n    }\r\n\r\n    // Pre-computations for maping an image point cloud to a cache-friendly array where cell's local point clouds are contiguous\r\n    cv::Mat_<int> cell_map(height,width);\r\n\r\n    for (int r=0;r<height; r++){\r\n        int cell_r = r/PATCH_SIZE;\r\n        int local_r = r%PATCH_SIZE;\r\n        for (int c=0;c<width; c++){\r\n            int cell_c = c/PATCH_SIZE;\r\n            int local_c = c%PATCH_SIZE;\r\n            cell_map.at<int>(r,c) = (cell_r*nr_horizontal_cells+cell_c)*PATCH_SIZE*PATCH_SIZE + local_r*PATCH_SIZE + local_c;\r\n        }\r\n    }\r\n\r\n    cv::Mat_<float> X(height,width);\r\n    cv::Mat_<float> Y(height,width);\r\n    cv::Mat_<float> X_t(height,width);\r\n    cv::Mat_<float> Y_t(height,width);\r\n    Eigen::MatrixXf cloud_array(width*height,3);\r\n    Eigen::MatrixXf cloud_array_organized(width*height,3);\r\n\r\n    cv::namedWindow(\"Seg\");\r\n\r\n    // Populate with random color codes\r\n    for(int i=0; i<100;i++){\r\n        cv::Vec3b color;\r\n        color[0]=rand()%255;\r\n        color[1]=rand()%255;\r\n        color[2]=rand()%255;\r\n        color_code.push_back(color);\r\n    }\r\n\r\n    // Add specific colors for planes\r\n    color_code[0][0] = 0; color_code[0][1] = 0; color_code[0][2] = 255;\r\n    color_code[1][0] = 255; color_code[1][1] = 0; color_code[1][2] = 204;\r\n    color_code[2][0] = 255; color_code[2][1] = 100; color_code[2][2] = 0;\r\n    color_code[3][0] = 0; color_code[3][1] = 153; color_code[3][2] = 255;\r\n    // Add specific colors for cylinders\r\n    color_code[50][0] = 178; color_code[50][1] = 255; color_code[50][2] = 0;\r\n    color_code[51][0] = 255; color_code[51][1] = 0; color_code[51][2] = 51;\r\n    color_code[52][0] = 0; color_code[52][1] = 255; color_code[52][2] = 51;\r\n    color_code[53][0] = 153; color_code[53][1] = 0; color_code[53][2] = 255;\r\n\r\n    // Initialize CAPE\r\n    plane_detector = new CAPE(height, width, PATCH_SIZE, PATCH_SIZE, cylinder_detection, COS_ANGLE_MAX, MAX_MERGE_DIST);\r\n\r\n    int i=0;\r\n    while(true){\r\n\r\n        // Read frame i\r\n        rgb_img_path.str(\"\");\r\n        rgb_img_path << string_buff.str() << \"/rgb_\" << i << \".png\";\r\n        rgb_img = cv::imread(rgb_img_path.str(),cv::IMREAD_COLOR);\r\n\r\n        if (!rgb_img.data)\r\n            break;\r\n\r\n        std::cout << \"Frame: \" << i << std::endl;\r\n\r\n        // Read depth image\r\n        depth_img_path.str(\"\");\r\n        depth_img_path << string_buff.str() << \"/depth_\" << i << \".png\";\r\n\r\n        d_img = cv::imread(depth_img_path.str(), cv::IMREAD_ANYDEPTH);\r\n        d_img.convertTo(d_img, CV_32F);\r\n\r\n        // Backproject to point cloud\r\n        X = X_pre.mul(d_img); Y = Y_pre.mul(d_img);\r\n        cloud_array.setZero();\r\n\r\n        // The following transformation+projection is only necessary to visualize RGB with overlapped segments\r\n        // Transform point cloud to color reference frame\r\n        X_t = ((float)R_stereo.at<double>(0,0))*X + ((float)R_stereo.at<double>(0,1))*Y + ((float)R_stereo.at<double>(0,2))*d_img + (float)t_stereo.at<double>(0);\r\n        Y_t = ((float)R_stereo.at<double>(1,0))*X + ((float)R_stereo.at<double>(1,1))*Y + ((float)R_stereo.at<double>(1,2))*d_img + (float)t_stereo.at<double>(1);\r\n        d_img = ((float)R_stereo.at<double>(2,0))*X + ((float)R_stereo.at<double>(2,1))*Y + ((float)R_stereo.at<double>(2,2))*d_img + (float)t_stereo.at<double>(2);\r\n\r\n        projectPointCloud(X_t, Y_t, d_img, U, V, fx_rgb, fy_rgb, cx_rgb, cy_rgb, t_stereo.at<double>(2), cloud_array);\r\n\r\n        cv::Mat_<cv::Vec3b> seg_rz = cv::Mat_<cv::Vec3b>(height,width,cv::Vec3b(0,0,0));\r\n        cv::Mat_<uchar> seg_output = cv::Mat_<uchar>(height,width,uchar(0));\r\n\r\n        // Run CAPE\r\n        int nr_planes, nr_cylinders;\r\n        std::vector<PlaneSeg> plane_params;\r\n        std::vector<CylinderSeg> cylinder_params;\r\n        double t1 = cv::getTickCount();\r\n        organizePointCloudByCell(cloud_array, cloud_array_organized, cell_map);\r\n        plane_detector->process(cloud_array_organized, nr_planes, nr_cylinders, seg_output, plane_params, cylinder_params);\r\n        double t2 = cv::getTickCount();\r\n        double time_elapsed = (t2-t1)/(double)cv::getTickFrequency();\r\n        std::cout<<\"Total time elapsed: \" << time_elapsed << std::endl;\r\n\r\n        /* Uncomment this block to print model params\r\n        for(int p_id=0; p_id<nr_planes;p_id++){\r\n            cout<<\"[Plane #\"<<p_id<<\"] with \";\r\n            cout<<\"normal: (\"<<plane_params[p_id].normal[0]<<\" \"<<plane_params[p_id].normal[1]<<\" \"<<plane_params[p_id].normal[2]<<\"), \";\r\n            cout<<\"d: \"<<plane_params[p_id].d<<endl;\r\n        }\r\n\r\n        for(int c_id=0; c_id<nr_cylinders;c_id++){\r\n            cout<<\"[Cylinder #\"<<c_id<<\"] with \";\r\n            cout<<\"axis: (\"<<cylinder_params[c_id].axis[0]<<\" \"<<cylinder_params[c_id].axis[1]<<\" \"<<cylinder_params[c_id].axis[2]<<\"), \";\r\n            cout<<\"center: (\"<<cylinder_params[c_id].centers[0].transpose()<<\"), \";\r\n            cout<<\"radius: \"<<cylinder_params[c_id].radii[0]<<endl;\r\n        }\r\n        */\r\n\r\n        // Map segments with color codes and overlap segmented image w/ RGB\r\n        uchar * sCode;\r\n        uchar * dColor;\r\n        uchar * srgb;\r\n        int code;\r\n        for(int r=0; r<  height; r++){\r\n            dColor = seg_rz.ptr<uchar>(r);\r\n            sCode = seg_output.ptr<uchar>(r);\r\n            srgb = rgb_img.ptr<uchar>(r);\r\n            for(int c=0; c< width; c++){\r\n                code = *sCode;\r\n                if (code>0){\r\n                    dColor[c*3] =   color_code[code-1][0]/2 + srgb[0]/2;\r\n                    dColor[c*3+1] = color_code[code-1][1]/2 + srgb[1]/2;\r\n                    dColor[c*3+2] = color_code[code-1][2]/2 + srgb[2]/2;;\r\n                }else{\r\n                    dColor[c*3] =  srgb[0];\r\n                    dColor[c*3+1] = srgb[1];\r\n                    dColor[c*3+2] = srgb[2];\r\n                }\r\n                sCode++; srgb++; srgb++; srgb++;\r\n            }\r\n        }\r\n\r\n        // Show frame rate and labels\r\n        cv::rectangle(seg_rz,  cv::Point(0,0),cv::Point(width,20), cv::Scalar(0,0,0),-1);\r\n        std::stringstream fps;\r\n        fps << (int)(1/time_elapsed+0.5) << \" fps\";\r\n        cv::putText(seg_rz, fps.str(), cv::Point(15,15), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255,255,255,1));\r\n        std::cout << \"Nr cylinders:\" << nr_cylinders << std::endl;\r\n        int cylinder_code_offset = 50;\r\n        // show cylinder labels\r\n        if (nr_cylinders>0){\r\n            std::stringstream text;\r\n            text<<\"Cylinders:\";\r\n            \r\n            cv::putText(seg_rz, text.str(), cv::Point(width/2,15), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255,255,255,1));\r\n            for(int j=0;j<nr_cylinders;j++){\r\n                cv::rectangle(seg_rz,  cv::Point(width/2 + 80+15*j,6),cv::Point(width/2 + 90+15*j,16), cv::Scalar(color_code[cylinder_code_offset+j][0],color_code[cylinder_code_offset+j][1],color_code[cylinder_code_offset+j][2]),-1);\r\n            }\r\n        }\r\n        cv::imshow(\"Seg\", seg_rz);\r\n        cv::waitKey(1);\r\n        i++;\r\n    }\r\n    \r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "059dfcfb428e5ac8e94f9821a99edb402acc5815", "size": 12202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CAPE/tools/run_cape_offline.cpp", "max_stars_repo_name": "mgrova/CAPE", "max_stars_repo_head_hexsha": "7fce3f59e6806bec4062649d8031c04060c6e11d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CAPE/tools/run_cape_offline.cpp", "max_issues_repo_name": "mgrova/CAPE", "max_issues_repo_head_hexsha": "7fce3f59e6806bec4062649d8031c04060c6e11d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CAPE/tools/run_cape_offline.cpp", "max_forks_repo_name": "mgrova/CAPE", "max_forks_repo_head_hexsha": "7fce3f59e6806bec4062649d8031c04060c6e11d", "max_forks_repo_licenses": ["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.2347266881, "max_line_length": 234, "alphanum_fraction": 0.5586789051, "num_tokens": 3516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5059154869447131}}
{"text": "#include <iostream>\n#include <boost/format.hpp>\n// Qt headers\n#include <QtGui>\n#include <CGAL/Qt/GraphicsViewNavigation.h>\n#include <QLineF>\n#include <QRectF>\n#include <QApplication> \n#include <QGraphicsScene>\n#include <QGraphicsView> \n// CGAL headers\n#include <CGAL/Qt/PointsGraphicsItem.h>\n#include <CGAL/Qt/GraphicsViewPolylineInput.h>\n#include <CGAL/Qt/utility.h>\n// GraphicsView items and event filters (input classes)\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/Largest_empty_iso_rectangle_2.h>\n// the two base classes\n#include <QString>\n#include <QFileDialog>\n#include <QInputDialog>\n#include <QGraphicsRectItem>\n#include <QGraphicsLineItem>\nusing namespace std;\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point_2;\ntypedef CGAL::Triangle_2<K> Triangle_2;\n\n\nint main(int argc, char **argv)\n{\n\tCGAL::Qt::PointsGraphicsItem<std::vector<Point_2> > * pgi;\n\tQApplication app(argc, argv);\n\tQGraphicsScene scene;\n\n\t// AREA OF TRIANGLE\n\tFILE *fp = NULL;\n\tfp = fopen(\"../src/input.txt\",\"r\");\n\tint pt1,pt2;\n\tPoint_2 points[3];\n\tint i=0;\n\n\n\t// DISPLAYING TRIANGL AND ITS AREA\n\tQPolygonF Triangle;\n\n\twhile(fscanf(fp,\"%d %d\",&pt1,&pt2)!=EOF){\n\n\t\tpoints[i]=Point_2(pt1,pt2);\n\t\tTriangle.append(QPointF(pt1,pt2));\n\t\ti++;\n\n\t}\n\t\n\t// finding area of triangle\n\tTriangle_2 pgn(points[0],points[1],points[2]);\n  \tdouble Area = abs(pgn.area());\n  \tcout << Area;\n\n\n\tscene.addPolygon(Triangle);\n\tQString str = QStringLiteral(\"Area : %1 \").arg(Area);\n\tscene.addText(str);\n\n    scene.setSceneRect(0,0, 300, 300);\n\n\n    QGraphicsView* view = new QGraphicsView(&scene);\n    CGAL::Qt::GraphicsViewNavigation navigation;\n    view->installEventFilter(&navigation);\n    view->viewport()->installEventFilter(&navigation);\n    view->setRenderHint(QPainter::Antialiasing);\n\n    view->show();\n\t\n    return app.exec();\n}\n", "meta": {"hexsha": "3ba2dbe4992f670c2ac76820e44fc964d8768b12", "size": 1901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "q4/src/min.cpp", "max_stars_repo_name": "justinepdevasia/cgal-assignments", "max_stars_repo_head_hexsha": "4d97df0e630ae17ad2dc2415ff9962986f004c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "q4/src/min.cpp", "max_issues_repo_name": "justinepdevasia/cgal-assignments", "max_issues_repo_head_hexsha": "4d97df0e630ae17ad2dc2415ff9962986f004c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "q4/src/min.cpp", "max_forks_repo_name": "justinepdevasia/cgal-assignments", "max_forks_repo_head_hexsha": "4d97df0e630ae17ad2dc2415ff9962986f004c53", "max_forks_repo_licenses": ["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.7625, "max_line_length": 63, "alphanum_fraction": 0.7259337191, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5058990999986984}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <boost/none.hpp>\n#include <boost/optional.hpp>\n#include <boost/optional/optional_io.hpp>\n#include <cstddef>\n\n#include \"DataStructures/DenseMatrix.hpp\"\n#include \"DataStructures/DenseVector.hpp\"\n#include \"Informer/Verbosity.hpp\"\n#include \"NumericalAlgorithms/Convergence/Criteria.hpp\"\n#include \"NumericalAlgorithms/Convergence/HasConverged.hpp\"\n#include \"NumericalAlgorithms/Convergence/Reason.hpp\"\n#include \"NumericalAlgorithms/LinearSolver/InnerProduct.hpp\"\n#include \"Options/Options.hpp\"\n#include \"Utilities/Gsl.hpp\"\n\nnamespace LinearSolver {\nnamespace gmres::detail {\n\n// Perform an Arnoldi orthogonalization to find a new `operand` that is\n// orthogonal to all vectors in `basis_history`. Appends a new column to the\n// `orthogonalization_history` that holds the inner product of the intermediate\n// `operand` with each vector in the `basis_history` and itself.\ntemplate <typename VarsType>\nvoid arnoldi_orthogonalize(\n    const gsl::not_null<VarsType*> operand,\n    const gsl::not_null<DenseMatrix<double>*> orthogonalization_history,\n    const std::vector<VarsType>& basis_history,\n    const size_t iteration) noexcept {\n  // Resize matrix and make sure the new entries that are not being filled below\n  // are zero.\n  orthogonalization_history->resize(iteration + 2, iteration + 1);\n  for (size_t j = 0; j < iteration; ++j) {\n    (*orthogonalization_history)(iteration + 1, j) = 0.;\n  }\n  // Arnoldi orthogonalization\n  for (size_t j = 0; j < iteration + 1; ++j) {\n    const double orthogonalization = inner_product(basis_history[j], *operand);\n    (*orthogonalization_history)(j, iteration) = orthogonalization;\n    *operand -= orthogonalization * basis_history[j];\n  }\n  (*orthogonalization_history)(iteration + 1, iteration) =\n      sqrt(inner_product(*operand, *operand));\n  // Avoid an FPE if the new operand norm is exactly zero. In that case the\n  // problem is solved and the algorithm will terminate (see Proposition 9.3 in\n  // \\cite Saad2003). Since there will be no next iteration we don't need to\n  // normalize the operand.\n  if (UNLIKELY((*orthogonalization_history)(iteration + 1, iteration) == 0.)) {\n    return;\n  }\n  *operand /= (*orthogonalization_history)(iteration + 1, iteration);\n}\n\n// Solve the linear least-squares problem `||beta - H * y||` for `y`, where `H`\n// is the Hessenberg matrix given by `orthogonalization_history` and `beta` is\n// the vector `(initial_residual, 0, 0, ...)` by updating the QR decomposition\n// of `H` from the previous iteration with a Givens rotation.\nvoid solve_minimal_residual(\n    gsl::not_null<DenseMatrix<double>*> orthogonalization_history,\n    gsl::not_null<DenseVector<double>*> residual_history,\n    gsl::not_null<DenseVector<double>*> givens_sine_history,\n    gsl::not_null<DenseVector<double>*> givens_cosine_history,\n    size_t iteration) noexcept;\n\n// Find the vector that minimizes the residual by inverting the upper\n// triangular matrix obtained above.\nDenseVector<double> minimal_residual_vector(\n    const DenseMatrix<double>& orthogonalization_history,\n    const DenseVector<double>& residual_history) noexcept;\n\n}  // namespace gmres::detail\n\nnamespace Serial {\n\ntemplate <typename VarsType>\nstruct IdentityPreconditioner {\n  VarsType operator()(const VarsType& arg) const noexcept { return arg; }\n};\n\nstruct NoIterationCallback {\n  void operator()(const Convergence::HasConverged& /*has_converged*/) const\n      noexcept {}\n};\n\n/*!\n * \\brief A serial GMRES iterative solver for nonsymmetric linear systems of\n * equations.\n *\n * This is an iterative algorithm to solve general linear equations \\f$Ax=b\\f$\n * where \\f$A\\f$ is a linear operator. See \\cite Saad2003, chapter 6.5 for a\n * description of the GMRES algorithm and Algorithm 9.6 for this implementation.\n * It is matrix-free, which means the operator \\f$A\\f$ needs not be provided\n * explicity as a matrix but only the operator action \\f$A(x)\\f$ must be\n * provided for an argument \\f$x\\f$.\n *\n * The GMRES algorithm does not require the operator \\f$A\\f$ to be symmetric or\n * positive-definite. Note that other algorithms such as conjugate gradients may\n * be more efficient for symmetric positive-definite operators.\n *\n * \\par Convergence:\n * Given a set of \\f$N_A\\f$ equations (e.g. through an \\f$N_A\\times N_A\\f$\n * matrix) the GMRES algorithm will converge to numerical precision in at most\n * \\f$N_A\\f$ iterations. However, depending on the properties of the linear\n * operator, an approximate solution can ideally be obtained in only a few\n * iterations. See \\cite Saad2003, section 6.11.4 for details on the convergence\n * of the GMRES algorithm.\n *\n * \\par Restarting:\n * This implementation of the GMRES algorithm supports restarting, as detailed\n * in \\cite Saad2003, section 6.5.5. Since the GMRES algorithm iteratively\n * builds up an orthogonal basis of the solution space the cost of each\n * iteration increases linearly with the number of iterations. Therefore it is\n * sometimes helpful to restart the algorithm every \\f$N_\\mathrm{restart}\\f$\n * iterations, discarding the set of basis vectors and starting again from the\n * current solution estimate. This strategy can improve the performance of the\n * solver, but note that the solver can stagnate for non-positive-definite\n * operators and is not guaranteed to converge within \\f$N_A\\f$ iterations\n * anymore. Set the `restart` argument of the constructor to\n * \\f$N_\\mathrm{restart}\\f$ to activate restarting, or set it to zero to\n * deactivate restarting (default behaviour).\n *\n * \\par Preconditioning:\n * This implementation of the GMRES algorithm also supports preconditioning.\n * You can provide a linear operator \\f$P\\f$ that approximates the inverse of\n * the operator \\f$A\\f$ to accelerate the convergence of the linear solve.\n * The algorithm is right-preconditioned, which allows the preconditioner to\n * change in every iteration (\"flexible\" variant). See \\cite Saad2003, sections\n * 9.3.2 and 9.4.1 for details. This implementation follows Algorithm 9.6 in\n * \\cite Saad2003.\n *\n * \\par Improvements:\n * Further improvements can potentially be implemented for this algorithm, see\n * e.g. \\cite Ayachour2003.\n *\n * \\example\n * \\snippet NumericalAlgorithms/LinearSolver/Test_Gmres.cpp gmres_example\n */\ntemplate <typename VarsType>\nstruct Gmres {\n private:\n  struct ConvergenceCriteria {\n    using type = Convergence::Criteria;\n    static constexpr OptionString help =\n        \"Determine convergence of the algorithm\";\n  };\n  struct Restart {\n    using type = size_t;\n    static constexpr OptionString help = \"Iterations to run before restarting\";\n    static size_t default_value() noexcept { return 0; }\n  };\n  struct Verbosity {\n    using type = ::Verbosity;\n    static constexpr OptionString help = \"Logging verbosity\";\n  };\n\n public:\n  static constexpr OptionString help =\n      \"A serial GMRES iterative solver for nonsymmetric linear systems of\\n\"\n      \"equations Ax=b. It will converge to numerical precision in at most N_A\\n\"\n      \"iterations, where N_A is the number of equations represented by the\\n\"\n      \"linear operator A, but will ideally converge to a reasonable\\n\"\n      \"approximation of the solution x in only a few iterations.\\n\"\n      \"\\n\"\n      \"Restarting: It is sometimes helpful to restart the algorithm every\\n\"\n      \"N_restart iterations to speed it up. Note that it can stagnate for\\n\"\n      \"non-positive-definite matrices and is not guaranteed to converge\\n\"\n      \"within N_A iterations anymore when restarting is activated.\\n\"\n      \"Activate restarting by setting the 'Restart' option to N_restart, or\\n\"\n      \"deactivate restarting by setting it to zero (default).\";\n  using options = tmpl::list<ConvergenceCriteria, Verbosity, Restart>;\n\n  Gmres(Convergence::Criteria convergence_criteria, ::Verbosity verbosity,\n        size_t restart = 0) noexcept\n      // clang-tidy: trivially copyable\n      : convergence_criteria_(std::move(convergence_criteria)),  // NOLINT\n        verbosity_(std::move(verbosity)),                        // NOLINT\n        restart_(restart > 0 ? restart : convergence_criteria_.max_iterations) {\n    initialize();\n  }\n\n  Gmres() = default;\n  Gmres(const Gmres& /*rhs*/) = default;\n  Gmres& operator=(const Gmres& /*rhs*/) = default;\n  Gmres(Gmres&& /*rhs*/) = default;\n  Gmres& operator=(Gmres&& /*rhs*/) = default;\n  ~Gmres() = default;\n\n  void initialize() noexcept {\n    orthogonalization_history_.reserve(restart_ + 1);\n    residual_history_.reserve(restart_ + 1);\n    givens_sine_history_.reserve(restart_);\n    givens_cosine_history_.reserve(restart_);\n    basis_history_.resize(restart_ + 1);\n    preconditioned_basis_history_.resize(restart_);\n  }\n\n  const Convergence::Criteria& convergence_criteria() const noexcept {\n    return convergence_criteria_;\n  }\n\n  void pup(PUP::er& p) noexcept {  // NOLINT\n    p | convergence_criteria_;\n    p | verbosity_;\n    p | restart_;\n    if (p.isUnpacking()) {\n      initialize();\n    }\n  }\n\n  /*!\n   * \\brief Iteratively solve the problem \\f$Ax=b\\f$ for \\f$x\\f$ where \\f$A\\f$\n   * is the `linear_operator` and \\f$b\\f$ is the `source`, starting \\f$x\\f$ at\n   * `initial_guess`.\n   *\n   * Optionally provide a `preconditioner` (see class documentation).\n   *\n   * \\return An instance of `Convergence::HasConverged` that provides\n   * information on the convergence status of the completed solve, and the\n   * approximate solution \\f$x\\f$.\n   */\n  template <typename LinearOperator, typename SourceType,\n            typename Preconditioner = IdentityPreconditioner<VarsType>,\n            typename IterationCallback = NoIterationCallback>\n  std::pair<Convergence::HasConverged, VarsType> operator()(\n      LinearOperator&& linear_operator, const SourceType& source,\n      const VarsType& initial_guess,\n      Preconditioner&& preconditioner = IdentityPreconditioner<VarsType>{},\n      IterationCallback&& iteration_callback = NoIterationCallback{}) const\n      noexcept;\n\n private:\n  Convergence::Criteria convergence_criteria_{};\n  ::Verbosity verbosity_{::Verbosity::Verbose};\n  size_t restart_{};\n\n  // Memory buffers to avoid re-allocating memory for successive solves:\n  // The `orthogonalization_history_` is built iteratively from inner products\n  // between existing and potential basis vectors and then Givens-rotated to\n  // become upper-triangular.\n  mutable DenseMatrix<double> orthogonalization_history_{};\n  // The `residual_history_` holds the remaining residual in its last entry, and\n  // the other entries `g` \"source\" the minimum residual vector `y` in\n  // `R * y = g` where `R` is the upper-triangular `orthogonalization_history_`.\n  mutable DenseVector<double> residual_history_{};\n  // These represent the accumulated Givens rotations up to the current\n  // iteration.\n  mutable DenseVector<double> givens_sine_history_{};\n  mutable DenseVector<double> givens_cosine_history_{};\n  // These represent the orthogonal Krylov-subspace basis that is constructed\n  // iteratively by Arnoldi-orthogonalizing a new vector in each iteration and\n  // appending it to the `basis_history_`.\n  mutable std::vector<VarsType> basis_history_{};\n  // When a preconditioner is used it is applied to each new basis vector. The\n  // preconditioned basis is used to construct the solution when the algorithm\n  // has converged.\n  mutable std::vector<VarsType> preconditioned_basis_history_{};\n};\n\ntemplate <typename VarsType>\ntemplate <typename LinearOperator, typename SourceType, typename Preconditioner,\n          typename IterationCallback>\nstd::pair<Convergence::HasConverged, VarsType> Gmres<VarsType>::operator()(\n    LinearOperator&& linear_operator, const SourceType& source,\n    const VarsType& initial_guess, Preconditioner&& preconditioner,\n    IterationCallback&& iteration_callback) const noexcept {\n  constexpr bool use_preconditioner =\n      not std::is_same_v<Preconditioner, IdentityPreconditioner<VarsType>>;\n  constexpr bool use_iteration_callback =\n      not std::is_same_v<IterationCallback, NoIterationCallback>;\n\n  auto result = initial_guess;\n  Convergence::HasConverged has_converged{};\n  size_t iteration = 0;\n\n  while (not has_converged) {\n    auto& initial_operand = basis_history_[0] =\n        source - linear_operator(result);\n    const double initial_residual_magnitude =\n        sqrt(inner_product(initial_operand, initial_operand));\n    has_converged = Convergence::HasConverged{convergence_criteria_, iteration,\n                                              initial_residual_magnitude,\n                                              initial_residual_magnitude};\n    if (use_iteration_callback) {\n      iteration_callback(has_converged);\n    }\n    if (UNLIKELY(has_converged)) {\n      break;\n    }\n    initial_operand /= initial_residual_magnitude;\n    residual_history_.resize(1);\n    residual_history_[0] = initial_residual_magnitude;\n    for (size_t k = 0; k < restart_; ++k) {\n      auto& operand = basis_history_[k + 1];\n      if (use_preconditioner) {\n        preconditioned_basis_history_[k] = preconditioner(basis_history_[k]);\n      }\n      operand =\n          linear_operator(use_preconditioner ? preconditioned_basis_history_[k]\n                                             : basis_history_[k]);\n      // Find a new orthogonal basis vector of the Krylov subspace\n      gmres::detail::arnoldi_orthogonalize(\n          make_not_null(&operand), make_not_null(&orthogonalization_history_),\n          basis_history_, k);\n      // Least-squares solve for the minimal residual\n      gmres::detail::solve_minimal_residual(\n          make_not_null(&orthogonalization_history_),\n          make_not_null(&residual_history_),\n          make_not_null(&givens_sine_history_),\n          make_not_null(&givens_cosine_history_), k);\n      ++iteration;\n      has_converged = Convergence::HasConverged{\n          convergence_criteria_, iteration, abs(residual_history_[k + 1]),\n          initial_residual_magnitude};\n      if (use_iteration_callback) {\n        iteration_callback(has_converged);\n      }\n      if (UNLIKELY(has_converged)) {\n        break;\n      }\n    }\n    // Find the vector w.r.t. the constructed orthogonal basis of the Krylov\n    // subspace that minimizes the residual\n    const auto minres = gmres::detail::minimal_residual_vector(\n        orthogonalization_history_, residual_history_);\n    // Construct the solution from the orthogonal basis and the minimal residual\n    // vector\n    for (size_t i = 0; i < minres.size(); ++i) {\n      result +=\n          minres[i] * gsl::at(use_preconditioner ? preconditioned_basis_history_\n                                                 : basis_history_,\n                              i);\n    }\n  }\n  // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)\n  return {std::move(has_converged), std::move(result)};\n}\n\n}  // namespace Serial\n}  // namespace LinearSolver\n", "meta": {"hexsha": "484bd9f720af8541efae6f2df270f3c866a406a7", "size": 14896, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/NumericalAlgorithms/LinearSolver/Gmres.hpp", "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": "src/NumericalAlgorithms/LinearSolver/Gmres.hpp", "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": "src/NumericalAlgorithms/LinearSolver/Gmres.hpp", "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": 43.3023255814, "max_line_length": 80, "alphanum_fraction": 0.7200590763, "num_tokens": 3559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5058990889970039}}
{"text": "// Loba2d library\n\n// Copyright (c) 2015 Andrii Sydorchuk\n\n// Use, modification and distribution is subject to the MIT License (MIT).\n\n#include <ctime>\n#include <iostream>\n#include <random>\n#include <vector>\n\n#include <boost/polygon/voronoi_builder.hpp>\n\n#include \"loba2d/delaunay_index.hpp\"\n\nconst int RANDOM_SEED = 27;\nconst int NUM_POINTS = 1000000;\n\n\nint main() {\n  std::mt19937 gen(RANDOM_SEED);\n  boost::polygon::voronoi_builder<int> vb;\n  loba2d::delaunay_index di;\n  std::vector< std::pair<int, int> > input;\n\n  for (int i = 0; i < NUM_POINTS; ++i) {\n    int x = gen() & ((1 << 30) - 1);\n    int y = gen() & ((1 << 30) - 1);\n    input.push_back(std::make_pair(x, y));\n    vb.insert_point(x, y);\n  }\n\n  double t = clock();\n  vb.construct(&di);\n  double elapsed = (clock() - t) / 1E6;\n\n  std::cout << \"Delaunay graph constructed in: \" << elapsed << \"(secs)\" << std::endl;\n  std::cout << \"Num. triangles: \" << di.triangles().size() << std::endl;\n\n  if (di.num_triangles() <= 10) {\n    std::cout << \"Triangles coordinates:\" << std::endl;\n    for (loba2d::delaunay_index::const_triangle_iterator it = di.triangles().begin();\n         it != di.triangles().end(); ++it) {\n      std::cout << \"[\";\n      for (int i = 0; i < 3; ++i) {\n        std::size_t idx = it->source_index(i);\n        std::cout << \" (\" << input[idx].first << \", \" << input[idx].second << \")\";\n      }\n      std::cout << \" ]\" << std::endl;\n    }\n  }\n}\n", "meta": {"hexsha": "9bd45ed801873c3bc784afe1447ba9b0e4f599b1", "size": 1421, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/delaunay_index_example.cpp", "max_stars_repo_name": "asydorchuk/loba2d", "max_stars_repo_head_hexsha": "ec173529f81fc2465c87392797d7c583ea2fb25e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-07-27T18:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-28T18:45:07.000Z", "max_issues_repo_path": "example/delaunay_index_example.cpp", "max_issues_repo_name": "asydorchuk/loba2d", "max_issues_repo_head_hexsha": "ec173529f81fc2465c87392797d7c583ea2fb25e", "max_issues_repo_licenses": ["MIT"], "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/delaunay_index_example.cpp", "max_forks_repo_name": "asydorchuk/loba2d", "max_forks_repo_head_hexsha": "ec173529f81fc2465c87392797d7c583ea2fb25e", "max_forks_repo_licenses": ["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.8113207547, "max_line_length": 85, "alphanum_fraction": 0.5840957072, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5058990889970039}}
{"text": "// Copyright 2015 XLGAMES Inc.\n//\n// Distributed under the MIT License (See\n// accompanying file \"LICENSE\" or the website\n// http://www.opensource.org/licenses/mit-license.php)\n\n#define _SILENCE_CXX17_NEGATORS_DEPRECATION_WARNING\t\t// silence warning due to removed functions in C++17 (from Eigen library)\n\n#include \"RegularNumberField.h\"\n#include <cmath>\n\n#pragma warning(disable:4714)\n#pragma push_macro(\"new\")\n#undef new\n#include <Eigen/Dense>\n#pragma pop_macro(\"new\")\n\nnamespace XLEMath\n{\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n            //   B I L I N E A R   \n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n    template<unsigned SamplingFlags, typename Store>\n        static Float2 SampleBilinear(const VectorField2DSeparate<Store>& field, Float2 coord)\n    {\n        float fx = XlFloor(coord[0]);\n        float fy = XlFloor(coord[1]);\n        float a = coord[0] - fx, b = coord[1] - fy;\n        float weights[] = \n        {\n            (1.f - a) * (1.f - b),\n            a * (1.f - b),\n            (1.f - a) * b,\n            a * b\n        };\n        unsigned x0, x1, y0, y1;\n        \n        const auto dims = field.Dimensions();\n        if (constant_expression<(SamplingFlags & RNFSample::WrapX)!=0>::result()) {\n            x0 = unsigned((int(fx) + int(dims[0]))%dims[0]);\n            x1 = (x0+1u)%dims[0];\n        } else if (constant_expression<(SamplingFlags & RNFSample::ClampX)!=0>::result()) {\n            x0 = unsigned(Clamp(fx, 0.f, float(dims[0]-1)));\n            x1 = std::min(x0+1u, dims[0]-1u);\n        } else {\n            x0 = unsigned(fx); x1 = x0+1;\n        }\n\n        if (constant_expression<(SamplingFlags & RNFSample::WrapY)!=0>::result()) {\n            y0 = unsigned((int(fy) + int(dims[1]))%dims[1]);\n            y1 = (y0+1u)%dims[1];\n        } else if (constant_expression<(SamplingFlags & RNFSample::ClampY)!=0>::result()) {\n            y0 = unsigned(Clamp(fy, 0.f, float(dims[1]-1)));\n            y1 = std::min(y0+1u, dims[1]-1u);\n        } else {\n            y0 = unsigned(fy); y1 = y0+1;\n        }\n        assert(x1 < dims[0] && y1 < dims[1]);\n        \n        float u\n            = weights[0] * (*field._u)[y0*dims[0]+x0]\n            + weights[1] * (*field._u)[y0*dims[0]+x1]\n            + weights[2] * (*field._u)[y1*dims[0]+x0]\n            + weights[3] * (*field._u)[y1*dims[0]+x1]\n            ;\n        float v\n            = weights[0] * (*field._v)[y0*dims[0]+x0]\n            + weights[1] * (*field._v)[y0*dims[0]+x1]\n            + weights[2] * (*field._v)[y1*dims[0]+x0]\n            + weights[3] * (*field._v)[y1*dims[0]+x1]\n            ;\n        return Float2(u, v);\n    }\n\n    template<unsigned SamplingFlags, typename Store>\n        static float SampleBilinear(const ScalarField2D<Store>& field, Float2 coord)\n    {\n        float fx = XlFloor(coord[0]);\n        float fy = XlFloor(coord[1]);\n        float a = coord[0] - fx, b = coord[1] - fy;\n        float weights[] = \n        {\n            (1.f - a) * (1.f - b),\n            a * (1.f - b),\n            (1.f - a) * b,\n            a * b\n        };\n        unsigned x0, x1, y0, y1;\n        \n        const auto dims = field.Dimensions();\n        if (constant_expression<(SamplingFlags & RNFSample::WrapX)!=0>::result()) {\n            x0 = unsigned((int(fx) + int(dims[0]))%dims[0]);\n            x1 = (x0+1u)%dims[0];\n        } else if (constant_expression<(SamplingFlags & RNFSample::ClampX)!=0>::result()) {\n            x0 = unsigned(Clamp(fx, 0.f, float(dims[0]-1)));\n            x1 = std::min(x0+1u, dims[0]-1u);\n        } else {\n            x0 = unsigned(fx); x1 = x0+1;\n        }\n\n        if (constant_expression<(SamplingFlags & RNFSample::WrapY)!=0>::result()) {\n            y0 = unsigned((int(fy) + int(dims[1]))%dims[1]);\n            y1 = (y0+1u)%dims[1];\n        } else if (constant_expression<(SamplingFlags & RNFSample::ClampY)!=0>::result()) {\n            y0 = unsigned(Clamp(fy, 0.f, float(dims[1]-1)));\n            y1 = std::min(y0+1u, dims[1]-1u);\n        } else {\n            y0 = unsigned(fy); y1 = y0+1;\n        }\n        assert(x1 < dims[0] && y1 < dims[1]);\n        \n        return \n              weights[0] * (*field._u)[y0*dims[0]+x0]\n            + weights[1] * (*field._u)[y0*dims[0]+x1]\n            + weights[2] * (*field._u)[y1*dims[0]+x0]\n            + weights[3] * (*field._u)[y1*dims[0]+x1]\n            ;\n    }\n\n    template<unsigned SamplingFlags, typename Store>\n        static Float3 SampleBilinear(const VectorField3DSeparate<Store>& field, Float3 coord)\n    {\n        float fx = XlFloor(coord[0]);\n        float fy = XlFloor(coord[1]);\n        float fz = XlFloor(coord[2]);\n        float a = coord[0] - fx, b = coord[1] - fy, c = coord[2] - fz;\n        float weights[] = \n        {\n            (1.f - a) * (1.f - b) * (1.f - c),\n            a * (1.f - b) * (1.f - c),\n            (1.f - a) * b * (1.f - c),\n            a * b * (1.f - c),\n\n            (1.f - a) * (1.f - b) * c,\n            a * (1.f - b) * c,\n            (1.f - a) * b * c,\n            a * b * c,\n        };\n        unsigned x0, x1, y0, y1, z0, z1;\n        \n        const auto dims = field.Dimensions();\n        if (constant_expression<(SamplingFlags & RNFSample::WrapX)!=0>::result()) {\n            x0 = unsigned((int(fx) + int(dims[0]))%dims[0]);\n            x1 = (x0+1u)%dims[0];\n        } else if (constant_expression<(SamplingFlags & RNFSample::ClampX)!=0>::result()) {\n            x0 = unsigned(Clamp(fx, 0.f, float(dims[0]-1)));\n            x1 = std::min(x0+1u, dims[0]-1u);\n        } else {\n            x0 = unsigned(fx); x1 = x0+1;\n        }\n\n        if (constant_expression<(SamplingFlags & RNFSample::WrapY)!=0>::result()) {\n            y0 = unsigned((int(fy) + int(dims[1]))%dims[1]);\n            y1 = (y0+1u)%dims[1];\n        } else if (constant_expression<(SamplingFlags & RNFSample::ClampY)!=0>::result()) {\n            y0 = unsigned(Clamp(fy, 0.f, float(dims[1]-1)));\n            y1 = std::min(y0+1u, dims[1]-1u);\n        } else {\n            y0 = unsigned(fy); y1 = y0+1;\n        }\n\n        if (constant_expression<(SamplingFlags & RNFSample::WrapZ)!=0>::result()) {\n            z0 = unsigned((int(fz) + int(dims[2]))%dims[2]);\n            z1 = (z0+1u)%dims[2];\n        } else if (constant_expression<(SamplingFlags & RNFSample::ClampZ)!=0>::result()) {\n            z0 = unsigned(Clamp(fz, 0.f, float(dims[2]-1)));\n            z1 = std::min(z0+1u, dims[2]-1u);\n        } else {\n            z0 = unsigned(fz); z1 = z0+1;\n        }\n        assert(x1 < dims[0] && y1 < dims[1] && z1 < dims[2]);\n        \n        float u\n            = weights[0] * (*field._u)[(z0*dims[1]+y0)*dims[0]+x0]\n            + weights[1] * (*field._u)[(z0*dims[1]+y0)*dims[0]+x1]\n            + weights[2] * (*field._u)[(z0*dims[1]+y1)*dims[0]+x0]\n            + weights[3] * (*field._u)[(z0*dims[1]+y1)*dims[0]+x1]\n            + weights[4] * (*field._u)[(z1*dims[1]+y0)*dims[0]+x0]\n            + weights[5] * (*field._u)[(z1*dims[1]+y0)*dims[0]+x1]\n            + weights[6] * (*field._u)[(z1*dims[1]+y1)*dims[0]+x0]\n            + weights[7] * (*field._u)[(z1*dims[1]+y1)*dims[0]+x1]\n            ;\n        float v\n            = weights[0] * (*field._v)[(z0*dims[1]+y0)*dims[0]+x0]\n            + weights[1] * (*field._v)[(z0*dims[1]+y0)*dims[0]+x1]\n            + weights[2] * (*field._v)[(z0*dims[1]+y1)*dims[0]+x0]\n            + weights[3] * (*field._v)[(z0*dims[1]+y1)*dims[0]+x1]\n            + weights[4] * (*field._v)[(z1*dims[1]+y0)*dims[0]+x0]\n            + weights[5] * (*field._v)[(z1*dims[1]+y0)*dims[0]+x1]\n            + weights[6] * (*field._v)[(z1*dims[1]+y1)*dims[0]+x0]\n            + weights[7] * (*field._v)[(z1*dims[1]+y1)*dims[0]+x1]\n            ;\n        float w\n            = weights[0] * (*field._w)[(z0*dims[1]+y0)*dims[0]+x0]\n            + weights[1] * (*field._w)[(z0*dims[1]+y0)*dims[0]+x1]\n            + weights[2] * (*field._w)[(z0*dims[1]+y1)*dims[0]+x0]\n            + weights[3] * (*field._w)[(z0*dims[1]+y1)*dims[0]+x1]\n            + weights[4] * (*field._w)[(z1*dims[1]+y0)*dims[0]+x0]\n            + weights[5] * (*field._w)[(z1*dims[1]+y0)*dims[0]+x1]\n            + weights[6] * (*field._w)[(z1*dims[1]+y1)*dims[0]+x0]\n            + weights[7] * (*field._w)[(z1*dims[1]+y1)*dims[0]+x1]\n            ;\n        return Float3(u, v, w);\n    }\n\n    template<unsigned SamplingFlags, typename Store>\n        static float SampleBilinear(const ScalarField3D<Store>& field, Float3 coord)\n    {\n        float fx = XlFloor(coord[0]);\n        float fy = XlFloor(coord[1]);\n        float fz = XlFloor(coord[2]);\n        float a = coord[0] - fx, b = coord[1] - fy, c = coord[2] - fz;\n        float weights[] = \n        {\n            (1.f - a) * (1.f - b) * (1.f - c),\n            a * (1.f - b) * (1.f - c),\n            (1.f - a) * b * (1.f - c),\n            a * b * (1.f - c),\n\n            (1.f - a) * (1.f - b) * c,\n            a * (1.f - b) * c,\n            (1.f - a) * b * c,\n            a * b * c,\n        };\n        unsigned x0, x1, y0, y1, z0, z1;\n        \n        const auto dims = field.Dimensions();\n        if (constant_expression<(SamplingFlags & RNFSample::WrapX)!=0>::result()) {\n            x0 = unsigned((int(fx) + int(dims[0]))%dims[0]);\n            x1 = (x0+1u)%dims[0];\n        } else if (constant_expression<(SamplingFlags & RNFSample::ClampX)!=0>::result()) {\n            x0 = unsigned(Clamp(fx, 0.f, float(dims[0]-1)));\n            x1 = std::min(x0+1u, dims[0]-1u);\n        } else {\n            x0 = unsigned(fx); x1 = x0+1;\n        }\n\n        if (constant_expression<(SamplingFlags & RNFSample::WrapY)!=0>::result()) {\n            y0 = unsigned((int(fy) + int(dims[1]))%dims[1]);\n            y1 = (y0+1u)%dims[1];\n        } else if (constant_expression<(SamplingFlags & RNFSample::ClampY)!=0>::result()) {\n            y0 = unsigned(Clamp(fy, 0.f, float(dims[1]-1)));\n            y1 = std::min(y0+1u, dims[1]-1u);\n        } else {\n            y0 = unsigned(fy); y1 = y0+1;\n        }\n\n        if (constant_expression<(SamplingFlags & RNFSample::WrapZ)!=0>::result()) {\n            z0 = unsigned((int(fz) + int(dims[2]))%dims[2]);\n            z1 = (z0+1u)%dims[2];\n        } else if (constant_expression<(SamplingFlags & RNFSample::ClampZ)!=0>::result()) {\n            z0 = unsigned(Clamp(fz, 0.f, float(dims[2]-1)));\n            z1 = std::min(z0+1u, dims[2]-1u);\n        } else {\n            z0 = unsigned(fz); z1 = z0+1;\n        }\n        assert(x1 < dims[0] && y1 < dims[1] && z1 < dims[2]);\n        \n        return\n              weights[0] * (*field._u)[(z0*dims[1]+y0)*dims[0]+x0]\n            + weights[1] * (*field._u)[(z0*dims[1]+y0)*dims[0]+x1]\n            + weights[2] * (*field._u)[(z0*dims[1]+y1)*dims[0]+x0]\n            + weights[3] * (*field._u)[(z0*dims[1]+y1)*dims[0]+x1]\n            + weights[4] * (*field._u)[(z1*dims[1]+y0)*dims[0]+x0]\n            + weights[5] * (*field._u)[(z1*dims[1]+y0)*dims[0]+x1]\n            + weights[6] * (*field._u)[(z1*dims[1]+y1)*dims[0]+x0]\n            + weights[7] * (*field._u)[(z1*dims[1]+y1)*dims[0]+x1]\n            ;\n    }\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n            //   M O N O T O N I C   C U B I C\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n    static float Sign(float x) { return (x < 0.f) ? -1.f : (x==0.f) ? 0.f : 1.f; }\n    static float MonotonicCubic(float xn1, float x0, float x1, float x2, float alpha)\n    {\n            // See also http://grmanet.sogang.ac.kr/ihm/webpapers/CLMCI.pdf\n            // (Controllable Local Monotonic Cubic Interpolation in Fluid Animations)\n            // for a much more expensive, but more flexible, monotonic interpolation\n            // method.\n            // This method reverts to linear in non-monotonic cases. The above paper\n            // attempts to find a good curve even on non-monotonic cases\n      \n        float dk        = (x1 - xn1) / 2.f;\n        float dk1       = (x2 - x0) / 2.f;\n        float deltak    = x1 - x0;\n        if (Sign(dk) != Sign(deltak) || Sign(dk1) != Sign(deltak))\n            dk = dk1 = 0.f;\n\n        float a2 = alpha * alpha;\n        float a3 = alpha * a2;\n\n            //      original math from Fedkiw has a small error in the first term\n            //      (should be -2*deltak, not -delta)\n        return \n              (dk + dk1 - 2.f * deltak) * a3\n            + (3.f * deltak - 2.f * dk - dk1) * a2\n            + dk * alpha\n            + x0;\n    }\n\n    template<unsigned SamplingFlags, typename Store>\n        float SampleMonotonicCubic(const ScalarField2D<Store>& field, Float2 coord)\n    {\n        float fx = XlFloor(coord[0]);\n        float fy = XlFloor(coord[1]);\n        float a = coord[0] - fx, b = coord[1] - fy;\n\n        const auto dims = field.Dimensions();\n        unsigned xn1, x0, x1, x2;\n        unsigned yn1, y0, y1, y2;\n        if (constant_expression<(SamplingFlags & RNFSample::WrapX)!=0>::result()) {\n            x0 = unsigned((int(fx) + int(dims[0]))%dims[0]);\n            x1 = (x0+1u)%dims[0];\n            x2 = (x1+1u)%dims[0];\n            xn1 = (x0+dims[0]-1)%dims[0];\n        } else {\n            x0 = unsigned(Clamp(fx, 0.f, float(dims[0]-1)));\n            x1 = std::min(x0+1u, dims[0]-1u);\n            x2 = std::min(x1+1u, dims[0]-1u);\n            xn1 = std::max(x0, 1u) - 1u;\n        }\n\n        if (constant_expression<(SamplingFlags & RNFSample::WrapY)!=0>::result()) {\n            y0 = unsigned((int(fy) + int(dims[1]))%dims[1]);\n            y1 = (y0+1u)%dims[1];\n            y2 = (y1+1u)%dims[1];\n            yn1 = (y0+dims[1]-1)%dims[1];\n        } else {\n            y0 = unsigned(Clamp(fy, 0.f, float(dims[1]-1)));\n            y1 = std::min(y0+1u, dims[1]-1u);\n            y2 = std::min(y1+1u, dims[1]-1u);\n            yn1 = std::max(y0, 1u) - 1u;\n        }\n        \n        float u[] = \n        {\n            (*field._u)[yn1*dims[0]+xn1],\n            (*field._u)[yn1*dims[0]+ x0],\n            (*field._u)[yn1*dims[0]+ x1],\n            (*field._u)[yn1*dims[0]+ x2],\n\n            (*field._u)[ y0*dims[0]+xn1],\n            (*field._u)[ y0*dims[0]+ x0],\n            (*field._u)[ y0*dims[0]+ x1],\n            (*field._u)[ y0*dims[0]+ x2],\n\n            (*field._u)[ y1*dims[0]+xn1],\n            (*field._u)[ y1*dims[0]+ x0],\n            (*field._u)[ y1*dims[0]+ x1],\n            (*field._u)[ y1*dims[0]+ x2],\n\n            (*field._u)[ y2*dims[0]+xn1],\n            (*field._u)[ y2*dims[0]+ x0],\n            (*field._u)[ y2*dims[0]+ x1],\n            (*field._u)[ y2*dims[0]+ x2]\n        };\n\n        float un1 = MonotonicCubic(u[ 0], u[ 1], u[ 2], u[ 3], a);\n        float u0  = MonotonicCubic(u[ 4], u[ 5], u[ 6], u[ 7], a);\n        float u1  = MonotonicCubic(u[ 8], u[ 9], u[10], u[11], a);\n        float u2  = MonotonicCubic(u[12], u[13], u[14], u[15], a);\n        return MonotonicCubic(un1, u0, u1, u2, b);\n    }\n\n    template<unsigned SamplingFlags, typename Store>\n        Float2 SampleMonotonicCubic(const VectorField2DSeparate<Store>& field, Float2 coord)\n    {\n        float fx = XlFloor(coord[0]);\n        float fy = XlFloor(coord[1]);\n        float a = coord[0] - fx, b = coord[1] - fy;\n\n        const auto dims = field.Dimensions();\n        unsigned xn1, x0, x1, x2;\n        unsigned yn1, y0, y1, y2;\n        if (constant_expression<(SamplingFlags & RNFSample::WrapX)!=0>::result()) {\n            x0  = unsigned((int(fx) + int(dims[0]))%dims[0]);\n            x1  = (x0+1u)%dims[0];\n            x2  = (x1+1u)%dims[0];\n            xn1 = (x0+dims[0]-1)%dims[0];\n        } else {\n            x0  = unsigned(Clamp(fx, 0.f, float(dims[0]-1)));\n            x1  = std::min(x0+1u, dims[0]-1u);\n            x2  = std::min(x1+1u, dims[0]-1u);\n            xn1 = std::max(x0, 1u) - 1u;\n        }\n\n        if (constant_expression<(SamplingFlags & RNFSample::WrapY)!=0>::result()) {\n            y0  = unsigned((int(fy) + int(dims[1]))%dims[1]);\n            y1  = (y0+1u)%dims[1];\n            y2  = (y1+1u)%dims[1];\n            yn1 = (y0+dims[1]-1)%dims[1];\n        } else {\n            y0  = unsigned(Clamp(fy, 0.f, float(dims[1]-1)));\n            y1  = std::min(y0+1u, dims[1]-1u);\n            y2  = std::min(y1+1u, dims[1]-1u);\n            yn1 = std::max(y0, 1u) - 1u;\n        }\n        \n        float u[] = \n        {\n            (*field._u)[yn1*dims[0]+xn1],\n            (*field._u)[yn1*dims[0]+ x0],\n            (*field._u)[yn1*dims[0]+ x1],\n            (*field._u)[yn1*dims[0]+ x2],\n\n            (*field._u)[ y0*dims[0]+xn1],\n            (*field._u)[ y0*dims[0]+ x0],\n            (*field._u)[ y0*dims[0]+ x1],\n            (*field._u)[ y0*dims[0]+ x2],\n\n            (*field._u)[ y1*dims[0]+xn1],\n            (*field._u)[ y1*dims[0]+ x0],\n            (*field._u)[ y1*dims[0]+ x1],\n            (*field._u)[ y1*dims[0]+ x2],\n\n            (*field._u)[ y2*dims[0]+xn1],\n            (*field._u)[ y2*dims[0]+ x0],\n            (*field._u)[ y2*dims[0]+ x1],\n            (*field._u)[ y2*dims[0]+ x2]\n        };\n\n        float v[] = \n        {\n            (*field._v)[yn1*dims[0]+xn1],\n            (*field._v)[yn1*dims[0]+ x0],\n            (*field._v)[yn1*dims[0]+ x1],\n            (*field._v)[yn1*dims[0]+ x2],\n\n            (*field._v)[ y0*dims[0]+xn1],\n            (*field._v)[ y0*dims[0]+ x0],\n            (*field._v)[ y0*dims[0]+ x1],\n            (*field._v)[ y0*dims[0]+ x2],\n\n            (*field._v)[ y1*dims[0]+xn1],\n            (*field._v)[ y1*dims[0]+ x0],\n            (*field._v)[ y1*dims[0]+ x1],\n            (*field._v)[ y1*dims[0]+ x2],\n\n            (*field._v)[ y2*dims[0]+xn1],\n            (*field._v)[ y2*dims[0]+ x0],\n            (*field._v)[ y2*dims[0]+ x1],\n            (*field._v)[ y2*dims[0]+ x2]\n        };\n\n            // Unfortunately, to get correct cubic interpolation in 2D, we\n            // have to do a lot of interpolations (similar to the math used\n            // in refining cubic surfaces)\n            //\n            // We can optimise this by only doing the monotonic interpolation\n            // of the U parameter in the U direction (and the V parameter in\n            // the V direction). Maybe we could fall back to linear in the \n            // cross-wise direction.\n            //\n            // It's hard to know what effect that optimisation would have on\n            // the advection operation.\n        float un1 = MonotonicCubic(u[ 0], u[ 1], u[ 2], u[ 3], a);\n        float u0  = MonotonicCubic(u[ 4], u[ 5], u[ 6], u[ 7], a);\n        float u1  = MonotonicCubic(u[ 8], u[ 9], u[10], u[11], a);\n        float u2  = MonotonicCubic(u[12], u[13], u[14], u[15], a);\n        float fu =  MonotonicCubic(un1, u0, u1, u2, b);\n\n        float vn1 = MonotonicCubic(v[ 0], v[ 1], v[ 2], v[ 3], a);\n        float v0  = MonotonicCubic(v[ 4], v[ 5], v[ 6], v[ 7], a);\n        float v1  = MonotonicCubic(v[ 8], v[ 9], v[10], v[11], a);\n        float v2  = MonotonicCubic(v[12], v[13], v[14], v[15], a);\n        float fv =  MonotonicCubic(vn1, v0, v1, v2, b);\n        return Float2(fu, fv);\n    }\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n            //   G A T H E R   N E I G H B O R S\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n    template<typename Store>\n        void GatherNeighbors(\n            Float2 neighbours[9], float weights[4], \n            const VectorField2DSeparate<Store>& field, Float2 coord, unsigned samplingFlags)\n    {\n        float fx = XlFloor(coord[0]);\n        float fy = XlFloor(coord[1]);\n        float a = coord[0] - fx, b = coord[1] - fy;\n        weights[0] = (1.f - a) * (1.f - b);\n        weights[1] = a * (1.f - b);\n        weights[2] = (1.f - a) * b;\n        weights[3] = a * b;\n\n        const auto dims = field.Dimensions();\n        unsigned x0, x1, y0, y1;\n        unsigned xx, yx;\n        if (samplingFlags & RNFSample::WrapX) {\n            x0 = unsigned((int(fx) + int(dims[0]))%dims[0]);\n            x1 = (x0+1u)%dims[0];\n            xx = (x0+dims[0]-1)%dims[0];\n        } else {\n            x0 = unsigned(Clamp(fx, 0.f, float(dims[0]-1)));\n            x1 = std::min(x0+1u, dims[0]-1u);\n            xx = std::max(x0, 1u) - 1u;\n        }\n\n        if (samplingFlags & RNFSample::WrapY) {\n            y0 = unsigned((int(fy) + int(dims[1]))%dims[1]);\n            y1 = (y0+1u)%dims[1];\n            yx = (y0+dims[1]-1)%dims[1];\n        } else {\n            y0 = unsigned(Clamp(fy, 0.f, float(dims[1]-1)));\n            y1 = std::min(y0+1u, dims[1]-1u);\n            yx = std::max(y0, 1u) - 1u;\n        }\n\n        neighbours[0][0] = (*field._u)[y0*dims[0]+x0];\n        neighbours[1][0] = (*field._u)[y0*dims[0]+x1];\n        neighbours[2][0] = (*field._u)[y1*dims[0]+x0];\n        neighbours[3][0] = (*field._u)[y1*dims[0]+x1];\n\n        neighbours[4][0] = (*field._u)[yx*dims[0]+xx];\n        neighbours[5][0] = (*field._u)[yx*dims[0]+x0];\n        neighbours[6][0] = (*field._u)[yx*dims[0]+x1];\n        neighbours[7][0] = (*field._u)[y0*dims[0]+xx];\n        neighbours[8][0] = (*field._u)[y1*dims[0]+xx];\n\n        neighbours[0][1] = (*field._v)[y0*dims[0]+x0];\n        neighbours[1][1] = (*field._v)[y0*dims[0]+x1];\n        neighbours[2][1] = (*field._v)[y1*dims[0]+x0];\n        neighbours[3][1] = (*field._v)[y1*dims[0]+x1];\n\n        neighbours[4][1] = (*field._v)[yx*dims[0]+xx];\n        neighbours[5][1] = (*field._v)[yx*dims[0]+x0];\n        neighbours[6][1] = (*field._v)[yx*dims[0]+x1];\n        neighbours[7][1] = (*field._v)[y0*dims[0]+xx];\n        neighbours[8][1] = (*field._v)[y1*dims[0]+xx];\n    }\n\n    template<typename Store>\n        void GatherNeighbors(\n            float neighbours[8], float weights[4], \n            const ScalarField2D<Store>& field, Float2 coord, unsigned samplingFlags)\n    {\n        float fx = XlFloor(coord[0]);\n        float fy = XlFloor(coord[1]);\n        float a = coord[0] - fx, b = coord[1] - fy;\n        weights[0] = (1.f - a) * (1.f - b);\n        weights[1] = a * (1.f - b);\n        weights[2] = (1.f - a) * b;\n        weights[3] = a * b;\n\n        const auto dims = field.Dimensions();\n        unsigned x0, x1, y0, y1;\n        unsigned xx, yx;\n        if (samplingFlags & RNFSample::WrapX) {\n            x0 = unsigned((int(fx) + int(dims[0]))%dims[0]);\n            x1 = (x0+1u)%dims[0];\n            xx = (x0+dims[0]-1)%dims[0];\n        } else {\n            x0 = unsigned(Clamp(fx, 0.f, float(dims[0]-1)));\n            x1 = std::min(x0+1u, dims[0]-1u);\n            xx = std::max(x0, 1u) - 1u;\n        }\n\n        if (samplingFlags & RNFSample::WrapY) {\n            y0 = unsigned((int(fy) + int(dims[1]))%dims[1]);\n            y1 = (y0+1u)%dims[1];\n            yx = (y0+dims[1]-1)%dims[1];\n        } else {\n            y0 = unsigned(Clamp(fy, 0.f, float(dims[1]-1)));\n            y1 = std::min(y0+1u, dims[1]-1u);\n            yx = std::max(y0, 1u) - 1u;\n        }\n\n        neighbours[0] = (*field._u)[y0*dims[0]+x0];\n        neighbours[1] = (*field._u)[y0*dims[0]+x1];\n        neighbours[2] = (*field._u)[y1*dims[0]+x0];\n        neighbours[3] = (*field._u)[y1*dims[0]+x1];\n\n        neighbours[4] = (*field._u)[yx*dims[0]+xx];\n        neighbours[5] = (*field._u)[yx*dims[0]+x0];\n        neighbours[6] = (*field._u)[yx*dims[0]+x1];\n        neighbours[7] = (*field._u)[y0*dims[0]+xx];\n        neighbours[8] = (*field._u)[y1*dims[0]+xx];\n    }\n\n    static void GatherNeighbors(float* result, size_t stride, const float* source, UInt3 base, UInt3 dims, unsigned samplingFlags)\n    {\n        auto x0 = base[0], y0 = base[1], z0 = base[2];\n        unsigned x1, y1, z1, xx, yx, zx;\n        if (samplingFlags & RNFSample::WrapX) {\n            x1 = (x0+1u)%dims[0];\n            xx = (x0+dims[0]-1u)%dims[0];\n        } else {\n            x1 = std::min(x0+1u, dims[0]-1u);\n            xx = std::max(x0, 1u)-1u;\n        }\n\n        if (samplingFlags & RNFSample::WrapY) {\n            y1 = (y0+1u)%dims[1];\n            yx = (y0+dims[1]-1u)%dims[1];\n        } else {\n            y1 = std::min(y0+1u, dims[1]-1u);\n            yx = std::max(y0, 1u)-1u;\n        }\n\n        if (samplingFlags & RNFSample::WrapY) {\n            z1 = (z0+1u)%dims[2];\n            zx = (z0+dims[2]-1u)%dims[2];\n        } else {\n            z1 = std::min(z0+1u, dims[2]-1u);\n            zx = std::max(z0, 1u)-1u;\n        }\n\n        #define V(x,y,z) source[(z*dims[1]+y)*dims[0]+x]\n        #define R(x) result[x*stride]\n\n            // results are arranged so the first 8 are the ones used for\n            // bilinear interpolation\n        R( 0) = V(x0, y0, z0);\n        R( 1) = V(x1, y0, z0);\n        R( 2) = V(x0, y1, z0);\n        R( 3) = V(x1, y1, z0);\n        R( 4) = V(x0, y0, z1);\n        R( 5) = V(x1, y0, z1);\n        R( 6) = V(x0, y1, z1);\n        R( 7) = V(x1, y1, z1);\n\n        R( 8) = V(xx, yx, z0);\n        R( 9) = V(x0, yx, z0);\n        R(10) = V(x1, yx, z0);\n        R(11) = V(xx, y0, z0);\n        R(12) = V(xx, y1, z0);\n\n        R(13) = V(xx, yx, z1);\n        R(14) = V(x0, yx, z1);\n        R(15) = V(x1, yx, z1);\n        R(16) = V(xx, y0, z1);\n        R(17) = V(xx, y1, z1);\n\n        R(18) = V(xx, yx, zx);\n        R(19) = V(x0, yx, zx);\n        R(20) = V(x1, yx, zx);\n        R(21) = V(xx, y0, zx);\n        R(22) = V(x0, y0, zx);\n        R(23) = V(x1, y0, zx);\n        R(24) = V(xx, y1, zx);\n        R(25) = V(x0, y1, zx);\n        R(26) = V(x1, y1, zx);\n        \n        #undef V\n        #undef R\n    }\n\n    template<typename Store>\n        void GatherNeighbors(\n            Float3 neighbours[27], float weights[8], \n            const VectorField3DSeparate<Store>& field, Float3 coord, unsigned samplingFlags)\n    {\n        float fx = XlFloor(coord[0]);\n        float fy = XlFloor(coord[1]);\n        float fz = XlFloor(coord[2]);\n        float a = coord[0] - fx, b = coord[1] - fy, c = coord[2] - fz;\n        weights[0] = (1.f - a) * (1.f - b) * (1.f - c);\n        weights[1] = a * (1.f - b) * (1.f - c);\n        weights[2] = (1.f - a) * b * (1.f - c);\n        weights[3] = a * b * (1.f - c);\n        weights[4] = (1.f - a) * (1.f - b) * c;\n        weights[5] = a * (1.f - b) * c;\n        weights[6] = (1.f - a) * b * c;\n        weights[7] = a * b * c;\n\n        const auto dims = field.Dimensions();\n        unsigned x0, y0, z0;\n        if (samplingFlags & RNFSample::WrapX) {\n            x0 = unsigned((int(fx) + int(dims[0]))%dims[0]);\n        } else {\n            x0 = unsigned(Clamp(fx, 0.f, float(dims[0]-1)));\n        }\n\n        if (samplingFlags & RNFSample::WrapY) {\n            y0 = unsigned((int(fy) + int(dims[1]))%dims[1]);\n        } else {\n            y0 = unsigned(Clamp(fy, 0.f, float(dims[1]-1)));\n        }\n\n        if (samplingFlags & RNFSample::WrapY) {\n            z0 = unsigned((int(fz) + int(dims[2]))%dims[2]);\n        } else {\n            z0 = unsigned(Clamp(fz, 0.f, float(dims[2]-1)));\n        }\n\n        GatherNeighbors(&neighbours[0][0], 3, &(*field._u)[0], UInt3(x0, y0, z0), dims, samplingFlags);\n        GatherNeighbors(&neighbours[0][1], 3, &(*field._v)[0], UInt3(x0, y0, z0), dims, samplingFlags);\n        GatherNeighbors(&neighbours[0][2], 3, &(*field._w)[0], UInt3(x0, y0, z0), dims, samplingFlags);\n    }\n\n    template<typename Store>\n        void GatherNeighbors(\n            float neighbours[27], float weights[8], \n            const ScalarField3D<Store>& field, Float3 coord, unsigned samplingFlags)\n    {\n        float fx = XlFloor(coord[0]);\n        float fy = XlFloor(coord[1]);\n        float fz = XlFloor(coord[2]);\n        float a = coord[0] - fx, b = coord[1] - fy, c = coord[2] - fz;\n        weights[0] = (1.f - a) * (1.f - b) * (1.f - c);\n        weights[1] = a * (1.f - b) * (1.f - c);\n        weights[2] = (1.f - a) * b * (1.f - c);\n        weights[3] = a * b * (1.f - c);\n        weights[4] = (1.f - a) * (1.f - b) * c;\n        weights[5] = a * (1.f - b) * c;\n        weights[6] = (1.f - a) * b * c;\n        weights[7] = a * b * c;\n\n        const auto dims = field.Dimensions();\n        unsigned x0, y0, z0;\n        if (samplingFlags & RNFSample::WrapX) {\n            x0 = unsigned((int(fx) + int(dims[0]))%dims[0]);\n        } else {\n            x0 = unsigned(Clamp(fx, 0.f, float(dims[0]-1)));\n        }\n\n        if (samplingFlags & RNFSample::WrapY) {\n            y0 = unsigned((int(fy) + int(dims[1]))%dims[1]);\n        } else {\n            y0 = unsigned(Clamp(fy, 0.f, float(dims[1]-1)));\n        }\n\n        if (samplingFlags & RNFSample::WrapY) {\n            z0 = unsigned((int(fz) + int(dims[2]))%dims[2]);\n        } else {\n            z0 = unsigned(Clamp(fz, 0.f, float(dims[2]-1)));\n        }\n\n        GatherNeighbors(neighbours, 1, &(*field._u)[0], UInt3(x0, y0, z0), dims, samplingFlags);\n    }\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n    template<typename Store>\n        float ScalarField2D<Store>::Load(Coord coord) const\n    {\n        assert(coord[0] < _dims[0] && coord[1] < _dims[1]);\n        return (*_u)[coord[1] * _dims[0] + coord[0]];\n    }\n\n    template<typename Store>\n        void ScalarField2D<Store>::Write(Coord coord, ValueType value)\n    {\n        assert(coord[0] < _dims[0] && coord[1] < _dims[1]);\n        (*_u)[coord[1] * _dims[0] + coord[0]] = value;\n        assert(std::isfinite(value) && !std::isnan(value));\n    }\n\n    template<typename Store>\n    template<unsigned SamplingFlags>\n        auto ScalarField2D<Store>::Sample(FloatCoord c) const -> ValueType\n    {\n        if (constant_expression<(SamplingFlags & RNFSample::Cubic)!=0>::result())\n            return SampleMonotonicCubic<SamplingFlags>(*this, c);\n        return SampleBilinear<SamplingFlags>(*this, c);\n    }\n\n    template<typename Store>\n        void ScalarField2D<Store>::GatherNeighbors(ValueType neighbours[9], float weights[4], FloatCoord coord, unsigned samplingFlags) const\n    {\n        XLEMath::GatherNeighbors(neighbours, weights, *this, coord, samplingFlags);\n    }\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n    template<typename Store>\n        Float2 VectorField2DSeparate<Store>::Load(Coord coord) const\n    {\n        assert(coord[0] < _dims[0] && coord[1] < _dims[1]);\n        return Float2(\n            (*_u)[coord[1] * _dims[0] + coord[0]],\n            (*_v)[coord[1] * _dims[0] + coord[0]]);\n    }\n\n    template<typename Store>\n        void VectorField2DSeparate<Store>::Write(Coord coord, ValueType value)\n    {\n        assert(coord[0] < _dims[0] && coord[1] < _dims[1]);\n        (*_u)[coord[1] * _dims[0] + coord[0]] = value[0];\n        (*_v)[coord[1] * _dims[0] + coord[0]] = value[1];\n        assert(std::isfinite(value[0]) && !std::isnan(value[0]));\n        assert(std::isfinite(value[1]) && !std::isnan(value[1]));\n    }\n\n    template<typename Store>\n    template<unsigned SamplingFlags>\n        auto VectorField2DSeparate<Store>::Sample(FloatCoord c) const -> ValueType\n    {\n        if (constant_expression<(SamplingFlags & RNFSample::Cubic)!=0>::result())\n            return SampleMonotonicCubic<SamplingFlags>(*this, c);\n        return SampleBilinear<SamplingFlags>(*this, c);\n    }\n\n    template<typename Store>\n        void VectorField2DSeparate<Store>::GatherNeighbors(ValueType neighbours[9], float weights[4], FloatCoord coord, unsigned samplingFlags) const\n    {\n        XLEMath::GatherNeighbors(neighbours, weights, *this, coord, samplingFlags);\n    }\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n    template<typename Store>\n        float ScalarField3D<Store>::Load(Coord coord) const\n    {\n        assert(coord[0] < _dims[0] && coord[1] < _dims[1]);\n        return (*_u)[(coord[2] * _dims[1] + coord[1]) * _dims[0] + coord[0]];\n    }\n\n    template<typename Store>\n        void ScalarField3D<Store>::Write(Coord coord, ValueType value)\n    {\n        assert(coord[0] < _dims[0] && coord[1] < _dims[1]);\n        (*_u)[(coord[2] * _dims[1] + coord[1]) * _dims[0] + coord[0]] = value;\n        assert(std::isfinite(value) && !std::isnan(value));\n    }\n\n    template<typename Store>\n    template<unsigned SamplingFlags>\n        auto ScalarField3D<Store>::Sample(FloatCoord c) const -> ValueType\n    {\n        // if (constant_expression<(SamplingFlags & RNFSample::Cubic)!=0>::result())\n        //     return SampleMonotonicCubic<SamplingFlags>(*this, c);\n        return SampleBilinear<SamplingFlags>(*this, c);\n    }\n\n    template<typename Store>\n        void ScalarField3D<Store>::GatherNeighbors(ValueType neighbours[27], float weights[4], FloatCoord coord, unsigned samplingFlags) const\n    {\n        XLEMath::GatherNeighbors(neighbours, weights, *this, coord, samplingFlags);\n    }\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n    template<typename Store>\n        Float3 VectorField3DSeparate<Store>::Load(Coord coord) const\n    {\n        assert(coord[0] < _dims[0] && coord[1] < _dims[1]);\n        return Float3(\n            (*_u)[(coord[2] * _dims[1] + coord[1]) * _dims[0] + coord[0]],\n            (*_v)[(coord[2] * _dims[1] + coord[1]) * _dims[0] + coord[0]],\n            (*_w)[(coord[2] * _dims[1] + coord[1]) * _dims[0] + coord[0]]);\n    }\n\n    template<typename Store>\n        void VectorField3DSeparate<Store>::Write(Coord coord, ValueType value)\n    {\n        assert(coord[0] < _dims[0] && coord[1] < _dims[1] && coord[2] < _dims[2]);\n        (*_u)[(coord[2] * _dims[1] + coord[1]) * _dims[0] + coord[0]] = value[0];\n        (*_v)[(coord[2] * _dims[1] + coord[1]) * _dims[0] + coord[0]] = value[1];\n        (*_w)[(coord[2] * _dims[1] + coord[1]) * _dims[0] + coord[0]] = value[2];\n        assert(std::isfinite(value[0]) && !std::isnan(value[0]));\n        assert(std::isfinite(value[1]) && !std::isnan(value[1]));\n    }\n\n    template<typename Store>\n    template<unsigned SamplingFlags>\n        auto VectorField3DSeparate<Store>::Sample(FloatCoord c) const -> ValueType\n    {\n        // if (constant_expression<(SamplingFlags & RNFSample::Cubic)!=0>::result())\n        //     return SampleMonotonicCubic<SamplingFlags>(*this, c);\n        return SampleBilinear<SamplingFlags>(*this, c);\n    }\n\n    template<typename Store>\n        void VectorField3DSeparate<Store>::GatherNeighbors(ValueType neighbours[27], float weights[4], FloatCoord coord, unsigned samplingFlags) const\n    {\n        XLEMath::GatherNeighbors(neighbours, weights, *this, coord, samplingFlags);\n    }\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n#if COMPILER_ACTIVE == COMPILER_TYPE_MSVC\n    template<typename Field>\n        unsigned InstantiateField()\n        {\n            using SampleFn = typename Field::ValueType(Field::*)(typename Field::FloatCoord)const;\n            SampleFn fns[14] = {\n                &Field::Sample<0>,\n                &Field::Sample<RNFSample::ClampX|RNFSample::ClampY|RNFSample::ClampZ>,\n                &Field::Sample<RNFSample::WrapX |RNFSample::ClampY|RNFSample::ClampZ>,\n                &Field::Sample<RNFSample::ClampX|RNFSample::WrapY |RNFSample::ClampZ>,\n                &Field::Sample<RNFSample::ClampX|RNFSample::ClampY|RNFSample::WrapZ >,\n                &Field::Sample<RNFSample::WrapX |RNFSample::WrapY |RNFSample::WrapZ >,\n                &Field::Sample<RNFSample::WrapX |RNFSample::WrapY |RNFSample::ClampZ >,\n                &Field::Sample<RNFSample::Cubic>,\n                &Field::Sample<RNFSample::Cubic|RNFSample::ClampX|RNFSample::ClampY|RNFSample::ClampZ>,\n                &Field::Sample<RNFSample::Cubic|RNFSample::WrapX |RNFSample::ClampY|RNFSample::ClampZ>,\n                &Field::Sample<RNFSample::Cubic|RNFSample::ClampX|RNFSample::WrapY |RNFSample::ClampZ>,\n                &Field::Sample<RNFSample::Cubic|RNFSample::ClampX|RNFSample::ClampY|RNFSample::WrapZ >,\n                &Field::Sample<RNFSample::Cubic|RNFSample::WrapX |RNFSample::WrapY |RNFSample::WrapZ >,\n                &Field::Sample<RNFSample::Cubic|RNFSample::WrapX |RNFSample::WrapY |RNFSample::ClampZ >\n            };\n            (void)fns;\n            return 0;\n        }\n\n    static const unsigned s_i[] = \n    {\n        InstantiateField<ScalarField2D<Eigen::VectorXf>>(),\n        InstantiateField<VectorField2DSeparate<Eigen::VectorXf>>(),\n        InstantiateField<ScalarField3D<Eigen::VectorXf>>(),\n        InstantiateField<VectorField3DSeparate<Eigen::VectorXf>>()\n    };\n#endif\n\n    template class ScalarField2D<Eigen::VectorXf>;\n    template class VectorField2DSeparate<Eigen::VectorXf>;\n    template class ScalarField3D<Eigen::VectorXf>;\n    template class VectorField3DSeparate<Eigen::VectorXf>;\n\n}\n\n", "meta": {"hexsha": "bcf2c3cbd9b3f3792bc7e65e36813e9d8ec92827", "size": 36579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Math/RegularNumberField.cpp", "max_stars_repo_name": "djewsbury/XLE", "max_stars_repo_head_hexsha": "7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-12-04T09:16:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T23:22:49.000Z", "max_issues_repo_path": "Math/RegularNumberField.cpp", "max_issues_repo_name": "djewsbury/XLE", "max_issues_repo_head_hexsha": "7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e", "max_issues_repo_licenses": ["MIT"], "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/RegularNumberField.cpp", "max_forks_repo_name": "djewsbury/XLE", "max_forks_repo_head_hexsha": "7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-03T05:32:39.000Z", "max_forks_repo_forks_event_max_datetime": "2015-12-04T09:16:54.000Z", "avg_line_length": 39.8464052288, "max_line_length": 150, "alphanum_fraction": 0.4840482244, "num_tokens": 12063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5058990779953085}}
{"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 <gsl/gsl_spline2d.h>\n\n#include <Eigen/Core>\n#include <string>\n\n#include \"pyinterp/detail/gsl/interpolate2d.hpp\"\n#include \"pyinterp/detail/math/frame.hpp\"\n\nnamespace pyinterp::detail::math {\n\n/// Bicubic interpolation\nclass Bicubic {\n public:\n  /// Default constructor\n  ///\n  /// @param xr Calculation window.\n  /// @param kind method of calculation\n  explicit Bicubic(const Frame2D& xr, const std::string& kind)\n      : interpolator_(xr.x()->size(), xr.y()->size(),\n                      Bicubic::parse_interp2d_type(kind), gsl::Accelerator(),\n                      gsl::Accelerator()) {}\n\n  /// Return the interpolated value of y for a given point x\n  auto interpolate(const double x, const double y, const Frame2D& xr)\n      -> double {\n    return interpolator_.evaluate(*(xr.x()), *(xr.y()), *(xr.q()), x, y);\n  }\n\n private:\n  /// GSL interpolator\n  gsl::Interpolate2D interpolator_;\n\n  static inline auto parse_interp2d_type(const std::string& kind)\n      -> const gsl_interp2d_type* {\n    if (kind == \"bilinear\") {\n      return gsl_interp2d_bilinear;\n    }\n    if (kind == \"bicubic\") {\n      return gsl_interp2d_bicubic;\n    }\n    throw std::invalid_argument(\"Invalid bicubic type: \" + kind);\n  }\n};\n\n}  // namespace pyinterp::detail::math\n", "meta": {"hexsha": "87094fe7b16f3746748fbe54fad339505bb19941", "size": 1423, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/bicubic.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/bicubic.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/bicubic.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": 27.9019607843, "max_line_length": 77, "alphanum_fraction": 0.6563598032, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5058990779953084}}
{"text": "//==============================================================================\n//         Copyright 2009 - 2013 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2014 MetaScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/include/functions/log.hpp>\n#include <nt2/include/functions/exp.hpp>\n#include <nt2/include/functions/fastnormcdf.hpp>\n#include <boost/simd/include/functions/fma.hpp>\n#include <boost/simd/include/functions/fnms.hpp>\n#include <boost/simd/include/functions/sqrt.hpp>\n#include <boost/simd/include/functions/sqr.hpp>\n#include <boost/simd/include/functions/aligned_store.hpp>\n#include <boost/simd/include/functions/aligned_load.hpp>\n#include <boost/simd/include/functions/divides.hpp>\n#include <boost/simd/include/functions/multiplies.hpp>\n#include <boost/simd/include/functions/unary_minus.hpp>\n#include <boost/simd/include/functions/plus.hpp>\n#include <boost/simd/include/functions/minus.hpp>\n#include <boost/simd/include/constants/half.hpp>\n#include <boost/simd/memory/allocator.hpp>\n#include <vector>\n#include <iostream>\n\n#include <nt2/sdk/bench/benchmark.hpp>\n#include <nt2/sdk/bench/metric/cycles_per_element.hpp>\n#include <nt2/sdk/bench/protocol/max_duration.hpp>\n#include <nt2/sdk/bench/setup/geometric.hpp>\n#include <nt2/sdk/bench/stats/median.hpp>\n\nusing namespace nt2::bench;\nusing namespace nt2;\n\ntemplate <class A0>\nBOOST_FORCEINLINE A0 blackandscholes(A0 const &a0, A0 const &a1, A0 const &a2, A0 const &a3, A0 const &a4)\n{\n  A0 da   = boost::simd::sqrt(a2);\n  A0 tmp1 = nt2::log(a0/a1);\n  A0 tmp2 = boost::simd::sqr(a4);\n  A0 tmp4 = boost::simd::fma(tmp2,nt2::Half<A0>(),a3);\n  A0 tmp3 = (tmp4*a2)/(a4*da);\n  A0 ed   = nt2::exp(-a3*a2);\n  A0 d1   = tmp1 + tmp3;\n  A0 d2   = boost::simd::fnms(a4,da,d1);\n  A0 fd1  = nt2::fastnormcdf(d1);\n  A0 fd2  = nt2::fastnormcdf(d2);\n  return boost::simd::fnms(a1*ed, fd2, a0*fd1);\n}\n\ntemplate<typename T> struct blackandscholes_simd\n{\n  blackandscholes_simd(std::size_t n)\n                    :  size_(n)\n  {\n    Sa.resize(size_);\n    Xa.resize(size_);\n    Ta.resize(size_);\n    ra.resize(size_);\n    va.resize(size_);\n    R.resize(size_);\n\n    for(std::size_t i = 0; i <size_; ++i)\n      Sa[i] = Xa[i] = Ta[i] = ra[i] = va[i] = T(i+1);\n  }\n\n  void operator()()\n  {\n    using boost::simd::pack;\n    using boost::simd::native;\n    using boost::simd::aligned_store;\n    using boost::simd::aligned_load;\n\n    typedef native<T,BOOST_SIMD_DEFAULT_EXTENSION> type;\n    std::size_t step_size_=boost::simd::meta::cardinal_of<type>::value;\n    std::size_t i=0;\n\n    while (size_-i>=step_size_)\n    {\n      type Sa_tmp = aligned_load<type>(&Sa[i]);\n      type Xa_tmp = aligned_load<type>(&Xa[i]);\n      type Ta_tmp = aligned_load<type>(&Ta[i]);\n      type ra_tmp = aligned_load<type>(&ra[i]);\n      type va_tmp = aligned_load<type>(&va[i]);\n      aligned_store(blackandscholes(Sa_tmp, Xa_tmp, Ta_tmp, ra_tmp, va_tmp), &R[i]);\n      i += step_size_;\n    }\n    for (; i<size_; i++)\n      R[i] += blackandscholes(Sa[i], Xa[i], Ta[i], ra[i], va[i]);\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, blackandscholes_simd<T> const& p)\n  {\n    return os << \"(\" << p.size() << \")\";\n  }\n\n  std::size_t size() const { return size_; }\n\n  private:\n  std::vector<T, boost::simd::allocator<T> > Sa, Xa, Ta, ra, va, R;\n  std::size_t size_;\n};\n\nNT2_REGISTER_BENCHMARK_TPL( blackandscholes_simd, (float) )\n{\n  std::size_t size_min  = args(\"size_min\",   16);\n  std::size_t size_max  = args(\"size_max\", 4096);\n  std::size_t size_step = args(\"size_step\",   2);\n\n  run_during_with< blackandscholes_simd<float> > ( 1.\n                                                 , geometric(size_min,size_max,size_step)\n                                                 , cycles_per_element<stats::median_>()\n                                                 );\n}\n", "meta": {"hexsha": "7b2a620e01be603328313dfa731ad219b9788e35", "size": 4108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo/blackscholes/simd/blackandscholes_simd.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "demo/blackscholes/simd/blackandscholes_simd.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "demo/blackscholes/simd/blackandscholes_simd.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 34.5210084034, "max_line_length": 106, "alphanum_fraction": 0.6163583252, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5058653702134842}}
{"text": "#ifndef PICSAR_MULTIPHYSICS_QUADRATURE\n#define PICSAR_MULTIPHYSICS_QUADRATURE\n\n//Should be included by all the src files of the library\n#include \"../qed_commons.h\"\n\n// Override BOOST_ASSERT so that an exception is thrown.\n// This is used to deal with some possible numerical\n// instabilities of the tanh_sinh integration method\n#define BOOST_ENABLE_ASSERT_HANDLER\n#include <boost/assert.hpp>\n#include <boost/math/quadrature/trapezoidal.hpp>\n#include <boost/math/quadrature/tanh_sinh.hpp>\n#include <boost/math/quadrature/exp_sinh.hpp>\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n#undef BOOST_ENABLE_ASSERT_HANDLER\n\n#include <functional>\n#include <limits>\n#include <stdexcept>\n#include <sstream>\n\n// Override BOOST_ASSERT so that an exception is thrown.\nnamespace boost\n{\n    inline\n    void assertion_failed(char const * expr,\n        char const * function,\n        char const * file, long line)\n        {\n            auto ss = std::stringstream();\n            ss << \"Error in \" << function <<\n            \" (\" << file << \", line \" << line <<\n            \"): \" << expr;\n            throw std::runtime_error(ss.str());\n        }\n}\n//______________________________________________________\n\n\nnamespace picsar{\nnamespace multi_physics{\nnamespace math{\n    /**\n    * This module is a wrapper around the trapezoidal,\n    * gauss_kronrod, tanh_sinh & exp_sinh quadrature methods provided by the Boost library.\n    * All the functions provided here accept a quadrature_algorithm template\n    * parameter to choose which method will be used.\n    */\n    enum quadrature_algorithm {\n        trapezoidal,\n        tanh_sinh,\n        exp_sinh,\n        gauss_kronrod15,\n        gauss_kronrod31,\n        gauss_kronrod41,\n        gauss_kronrod51,\n        gauss_kronrod61\n    };\n\n    /**\n    * This function performs the integration of the function f(x)\n    * in the interval (a,b) using the method specified in the template parameter\n    * (not usable on GPUs).\n    *\n    * @tparam RealType the floating point type to be used\n    * @tparam QuadAlgo the quadrature method to be used\n    * @param[in] f the function which should be integrated\n    * @param[in] a the left boundary of the integration region\n    * @param[in] b the right boundary of the integration region\n    * @return the integral of f in (a,b)\n    */\n    template<\n        typename RealType, quadrature_algorithm QuadAlgo>\n    inline constexpr RealType generic_quad_a_b(\n        const std::function<RealType(RealType)>& f, RealType a, RealType b)\n    {\n        PXRMP_INTERNAL_CONSTEXPR_IF (\n            QuadAlgo == quadrature_algorithm::trapezoidal){\n            return boost::math::quadrature::trapezoidal(f, a, b);\n        }\n        else PXRMP_INTERNAL_CONSTEXPR_IF (\n            QuadAlgo == quadrature_algorithm::tanh_sinh){\n            boost::math::quadrature::tanh_sinh<RealType> integrator;\n            return integrator.integrate(f, a, b);\n        }\n        else PXRMP_INTERNAL_CONSTEXPR_IF (\n            QuadAlgo == quadrature_algorithm::exp_sinh){\n            boost::math::quadrature::exp_sinh<RealType> integrator;\n            return integrator.integrate(f, a, b);\n        }\n        else PXRMP_INTERNAL_CONSTEXPR_IF (\n            QuadAlgo == quadrature_algorithm::gauss_kronrod15){\n            return boost::math::quadrature::gauss_kronrod<RealType, 15>\n                ::integrate(f, a, b);\n        }\n        else PXRMP_INTERNAL_CONSTEXPR_IF (\n            QuadAlgo == quadrature_algorithm::gauss_kronrod31){\n            return boost::math::quadrature::gauss_kronrod<RealType, 31>\n                ::integrate(f, a, b);\n        }\n        else PXRMP_INTERNAL_CONSTEXPR_IF (\n            QuadAlgo == quadrature_algorithm::gauss_kronrod41){\n            return boost::math::quadrature::gauss_kronrod<RealType, 41>\n                ::integrate(f, a, b);\n        }\n        else PXRMP_INTERNAL_CONSTEXPR_IF (\n            QuadAlgo == quadrature_algorithm::gauss_kronrod51){\n            return boost::math::quadrature::gauss_kronrod<RealType, 51>\n                ::integrate(f, a, b);\n        }\n        else PXRMP_INTERNAL_CONSTEXPR_IF (\n            QuadAlgo == quadrature_algorithm::gauss_kronrod61){\n            return boost::math::quadrature::gauss_kronrod<RealType, 61>\n                ::integrate(f, a, b);\n        }\n        else\n        {\n            return boost::math::quadrature::trapezoidal(f, a, b);\n        }\n    }\n\n    /**\n    * This function performs the integration of the function f(x)\n    * in the finite interval (a,b), using the \"trapezoidal\" quadrature method\n    * (not usable on GPUs).\n    *\n    * @tparam RealType the floating point type to be used\n    * @param[in] f the function which should be integrated\n    * @param[in] a the left boundary of the integration region\n    * @param[in] b the right boundary of the integration region\n    * @return the integral of f in (a,b)\n    */\n    template<typename RealType>\n    inline constexpr RealType quad_a_b(\n        const std::function<RealType(RealType)>& f, RealType a, RealType b)\n    {\n        return generic_quad_a_b<\n            RealType, quadrature_algorithm::gauss_kronrod61>(f, a, b);\n    }\n\n    /**\n    * This function performs the integration of the function f(x)\n    * in the finite interval (a,b) using the \"tanh_sinh\" quadrature method,\n    * to deal with possibile singularities at the boundaries\n    * (not usable on GPUs).\n    *\n    * @tparam RealType the floating point type to be used\n    * @param[in] f the function which should be integrated\n    * @param[in] a the left boundary of the integration region\n    * @param[in] b the right boundary of the integration region\n    * @return the integral of f in (a,b)\n    */\n    template<typename RealType>\n    inline constexpr RealType quad_a_b_s(\n        const std::function<RealType(RealType)>& f, RealType a, RealType b)\n    {\n         return generic_quad_a_b<RealType,\n            quadrature_algorithm::tanh_sinh>(f, a, b);\n    }\n\n    /**\n    * This function performs the integration of the function f(x)\n    * in the semi-infinite interval (a,inf) using the \"exp_sinh\" quadrature method\n    * (not usable on GPUs).\n    *\n    * @tparam RealType the floating point type to be used\n    * @param[in] a the left boundary of the integration region\n    * @param[in] b the right boundary of the integration region\n    * @return the integral of f in (a,b)\n    */\n    template<typename RealType>\n    PXRMP_INTERNAL_FORCE_INLINE_DECORATOR\n    constexpr RealType quad_a_inf(\n        const std::function<RealType(RealType)>& f, RealType a)\n    {\n        return generic_quad_a_b<RealType, quadrature_algorithm::exp_sinh>(\n            f, a, std::numeric_limits<RealType>::infinity());\n    }\n}\n}\n}\n\n#endif //PICSAR_MULTIPHYSICS_QUADRATURE\n", "meta": {"hexsha": "595cdfc6b1140cde52d968c57c151b19db24fe40", "size": 6714, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED/src/math/quadrature.hpp", "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/src/math/quadrature.hpp", "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/src/math/quadrature.hpp", "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": 36.2918918919, "max_line_length": 91, "alphanum_fraction": 0.655347036, "num_tokens": 1653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5058653653174139}}
{"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_ARCH_COMMON_SIMD_FUNCTION_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_HYPOT_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/constant/maxexponentm1.hpp>\n#include <boost/simd/constant/minexponent.hpp>\n#include <boost/simd/function/simd/abs.hpp>\n#include <boost/simd/function/simd/exponent.hpp>\n#include <boost/simd/function/simd/ldexp.hpp>\n#include <boost/simd/function/simd/max.hpp>\n#include <boost/simd/function/simd/min.hpp>\n#include <boost/simd/function/simd/plus.hpp>\n#include <boost/simd/function/simd/sqr.hpp>\n#include <boost/simd/function/simd/sqrt.hpp>\n#include <boost/simd/function/simd/unary_minus.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/function/simd/if_else.hpp>\n#include <boost/simd/function/simd/logical_and.hpp>\n#include <boost/simd/function/simd/logical_or.hpp>\n#include <boost/simd/function/simd/is_inf.hpp>\n#include <boost/simd/function/simd/is_nan.hpp>\n#include <boost/simd/constant/inf.hpp>\n#endif\n\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD(hypot_\n                          , (typename A0, typename X)\n                          , bd::cpu_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n      {\n        using iA0 = bd::as_integer_t<A0>;\n        A0 r =  bs::abs(a0);\n        A0 i =  bs::abs(a1);\n        iA0 e =  exponent(bs::max(i, r));\n        e = bs::min(bs::max(e,Minexponent<A0>()),Maxexponentm1<A0>());\n        A0 res =  ldexp(sqrt(sqr(ldexp(r, -e))+sqr(ldexp(i, -e))), e);\n        #ifndef BOOST_SIMD_NO_INVALIDS\n        auto test = logical_or(logical_and(is_nan(a0), is_inf(a1)),\n                              logical_and(is_nan(a1), is_inf(a0)));\n        return if_else(test, Inf<A0>(), res);\n        #else\n        return res;\n        #endif\n      }\n   };\n\n} } }\n\n#endif\n\n", "meta": {"hexsha": "06fa1d5017e6aad993dc8e58107fd64f0d077aef", "size": 2596, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/simd/function/hypot.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/arch/common/simd/function/hypot.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/arch/common/simd/function/hypot.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": 35.5616438356, "max_line_length": 100, "alphanum_fraction": 0.6074730354, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5058653506292016}}
{"text": "//\n// Created by david on 2018-11-16.\n//\n\n#include \"matrix_product_stl.h\"\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <memory>\n#include <general/class_tic_toc.h>\n#define profile_matrix_product_dense 1\n\n// Function definitions\ntemplate <typename Scalar>\nusing MatrixType = Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>;\n\ntemplate <typename Scalar>\nusing VectorType = Eigen::Matrix<Scalar,Eigen::Dynamic,1>;\n\ntemplate <typename Scalar>\nusing VectorTypeT = Eigen::Matrix<Scalar,1,Eigen::Dynamic>;\n\n\nnamespace stl_lu{\n    std::optional<Eigen::PartialPivLU<MatrixType<double>>               >lu_real;\n    std::optional<Eigen::PartialPivLU<MatrixType<std::complex<double>>> >lu_cplx;\n    void reset(){\n        lu_real.reset();\n        lu_cplx.reset();\n    }\n    template<typename Scalar>\n    void init(){\n        if constexpr (std::is_same_v<Scalar,double>){\n            stl_lu::lu_real   = Eigen::PartialPivLU<MatrixType<Scalar>>();\n        }\n        if constexpr (std::is_same_v<Scalar,std::complex<double>>)\n            stl_lu::lu_cplx = Eigen::PartialPivLU<MatrixType<Scalar>>();\n    }\n\n}\n\ntemplate<typename Scalar>\nvoid StlMatrixProduct<Scalar>::init_profiling(){\n    t_factorOP = std::make_unique<class_tic_toc>(profile_matrix_product_dense, 5,\"Time FactorOp\");\n    t_multOPv = std::make_unique<class_tic_toc>(profile_matrix_product_dense, 5,\"Time MultOpv\");\n    t_multAx = std::make_unique<class_tic_toc>(profile_matrix_product_dense, 5,\"Time MultAx\");\n}\n\n\ntemplate<typename Scalar>\nStlMatrixProduct<Scalar>::~StlMatrixProduct(){\n    stl_lu::reset();\n}\n\n// Pointer to data constructor, copies the matrix into an internal Eigen matrix.\ntemplate<typename Scalar>\nStlMatrixProduct<Scalar>::StlMatrixProduct(\n    const Scalar * const A_,\n    const int L_,\n    const bool copy_data,\n    const eigutils::eigSetting::Form form_,\n    const eigutils::eigSetting::Side side_):\n    A_ptr(A_) ,L(L_), form(form_), side(side_)\n{\n    if (copy_data){\n        A_stl.resize(static_cast<size_t>(L*L));\n        std::copy(A_ptr,A_ptr + static_cast<size_t>(L*L), A_stl.begin());\n        A_ptr = A_stl.data();\n    }\n    stl_lu::init<Scalar>();\n    init_profiling();\n}\n\ntemplate<typename Scalar>\nvoid StlMatrixProduct<Scalar>::print() const {\n    Eigen::Map<const MatrixType<Scalar>> A_matrix (A_ptr,L,L);\n    std::cout << \"A_matrix: \\n\" << A_matrix << std::endl;\n}\n\n\ntemplate<typename Scalar>\nvoid StlMatrixProduct<Scalar>::FactorOP()\n\n/*  Partial pivot LU decomposition\n *  Factors P(A-sigma*I) = LU\n */\n{\n    if(readyFactorOp){return;}\n//    lu_real_ptr = std::make_shared<LU_REAL>( LU_REAL() );\n    Eigen::Map<const MatrixType<Scalar>> A_matrix (A_ptr,L,L);\n    t_factorOP->tic();\n    assert(readyShift and \"Shift value sigma has not been set.\");\n    if constexpr(std::is_same_v<Scalar,double>){\n        stl_lu::lu_real.value().compute(A_matrix - sigmaR * Eigen::MatrixXd::Identity(L,L));\n    }\n    if constexpr(std::is_same_v<Scalar,std::complex<double>>){\n        Scalar sigma = std::complex<double>(sigmaR,sigmaI);\n        stl_lu::lu_cplx.value().compute(A_matrix - sigma * Eigen::MatrixXd::Identity(L,L));\n    }\n\n    readyFactorOp = true;\n    t_factorOP->toc();\n//    std::cout << \"Time Factor Op [ms]: \" << std::fixed << std::setprecision(3) << t_factorOP.get_last_time_interval() * 1000 << '\\n';\n}\n\n\n\n\ntemplate<typename Scalar>\nvoid StlMatrixProduct<Scalar>::MultOPv(Scalar* x_in_ptr, Scalar* x_out_ptr) {\n    using namespace eigutils::eigSetting;\n    assert(readyFactorOp and \"FactorOp() has not been run yet.\");\n    t_multOPv->tic();\n    switch (side){\n        case Side::R: {\n            Eigen::Map<VectorType<Scalar>>       x_in    (x_in_ptr,L);\n            Eigen::Map<VectorType<Scalar>>       x_out   (x_out_ptr,L);\n            if constexpr(std::is_same_v<Scalar,double>)\n                x_out.noalias() = stl_lu::lu_real.value().solve(x_in);\n            if constexpr(std::is_same_v<Scalar,std::complex<double>>)\n                x_out.noalias() = stl_lu::lu_cplx.value().solve(x_in);\n            break;\n        }\n        case Side::L: {\n            Eigen::Map<VectorTypeT<Scalar>>       x_in    (x_in_ptr,L);\n            Eigen::Map<VectorTypeT<Scalar>>       x_out   (x_out_ptr,L);\n            if constexpr(std::is_same_v<Scalar,double>)\n                x_out.noalias() = x_in *stl_lu::lu_real.value().inverse();\n            if constexpr(std::is_same_v<Scalar,std::complex<double>>)\n                x_out.noalias() = x_in *stl_lu::lu_cplx.value().inverse();\n            break;\n        }\n    }\n    t_multOPv->toc();\n    counter++;\n}\n\n\n\n\ntemplate<typename Scalar>\nvoid StlMatrixProduct<Scalar>::MultAx(Scalar* x_in, Scalar* x_out) {\n    using namespace eigutils::eigSetting;\n    t_multAx->tic();\n    Eigen::Map<const MatrixType<Scalar>> A_matrix (A_ptr,L,L);\n    switch (form){\n        case Form::NONSYMMETRIC:\n            switch (side) {\n                case Side::R: {\n                    Eigen::Map<VectorType<Scalar>> x_vec_in (x_in,  L);\n                    Eigen::Map<VectorType<Scalar>> x_vec_out(x_out, L);\n                    x_vec_out.noalias() = A_matrix * x_vec_in ;\n                    break;\n                }\n                case Side::L: {\n                    Eigen::Map<VectorTypeT<Scalar>> x_vec_in(x_in, L);\n                    Eigen::Map<VectorTypeT<Scalar>> x_vec_out(x_out, L);\n                    x_vec_out.noalias() = x_vec_in * A_matrix;\n                    break;\n                }\n            }\n            break;\n        case Form::SYMMETRIC: {\n            Eigen::Map<VectorType<Scalar>> x_vec_in(x_in, L);\n            Eigen::Map<VectorType<Scalar>> x_vec_out(x_out, L);\n            x_vec_out.noalias() = A_matrix.template selfadjointView<Eigen::Lower>() * x_vec_in;\n            break;\n        }\n    }\n    t_multAx->toc();\n    counter++;\n}\n\n\n\n\n\n\n// Explicit instantiations\n\ntemplate class StlMatrixProduct<double>;\ntemplate class StlMatrixProduct<std::complex<double>>;\n", "meta": {"hexsha": "07fe4409843951f5db21f86abf0208eb812c971e", "size": 5950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unused/eigsolver_backup/arpack_extra/matrix_product_stl.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": "unused/eigsolver_backup/arpack_extra/matrix_product_stl.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": "unused/eigsolver_backup/arpack_extra/matrix_product_stl.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": 32.3369565217, "max_line_length": 135, "alphanum_fraction": 0.6270588235, "num_tokens": 1510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5058184734401532}}
{"text": "#include \"conex/cone_program.h\"\n#include \"conex/equality_constraint.h\"\n#include \"conex/linear_constraint.h\"\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\nnamespace conex {\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nTEST(EqualityConstraints, Basic) {\n  int num_vars = 3;\n  int num_equalities = 1;\n  int num_inequalities = 4;\n\n  MatrixXd A = MatrixXd::Random(num_inequalities, num_vars);\n  MatrixXd C(num_inequalities, 1);\n  MatrixXd b(num_vars, 1);\n\n  MatrixXd optimal_slack(num_inequalities, 1);\n  MatrixXd optimal_dual(num_inequalities, 1);\n  MatrixXd optimal_y(num_vars, 1);\n\n  optimal_slack.setConstant(1);\n  optimal_dual.setConstant(1);\n  optimal_slack.topRows(num_inequalities * .5).setZero();\n  optimal_dual.bottomRows(num_inequalities - num_inequalities * .5).setZero();\n  optimal_y = Eigen::MatrixXd::Random(num_vars, 1);\n\n  C = optimal_slack + A * optimal_y;\n\n  LinearConstraint linear_inequality{A, C};\n\n  MatrixXd eq = MatrixXd::Random(num_equalities, num_vars);\n  MatrixXd eq_affine(num_equalities, 1);\n  eq = Eigen::MatrixXd::Random(num_equalities, num_vars);\n  eq_affine = eq * optimal_y;\n\n  Program prog(num_vars);\n  prog.AddConstraint(EqualityConstraints{eq, eq_affine});\n  prog.AddConstraint(linear_inequality);\n\n  VectorXd linear_cost(num_vars);\n  linear_cost = A.transpose() * optimal_dual;\n\n  VectorXd solution(num_vars);\n  Solve(linear_cost, prog, conex::SolverConfiguration(), solution.data());\n\n  EXPECT_NEAR((eq * solution - eq_affine).norm(), 0, 1e-5);\n  EXPECT_NEAR((solution - optimal_y).norm(), 0, 1e-5);\n}\n}  // namespace conex\n", "meta": {"hexsha": "3a18d40df18a30f055e932a929cb336cc2443f5f", "size": 1564, "ext": "cc", "lang": "C++", "max_stars_repo_path": "conex/test/equality_constraints_test.cc", "max_stars_repo_name": "ToyotaResearchInstitute/conex", "max_stars_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-02-08T08:02:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T21:53:22.000Z", "max_issues_repo_path": "conex/test/equality_constraints_test.cc", "max_issues_repo_name": "ToyotaResearchInstitute/conex", "max_issues_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conex/test/equality_constraints_test.cc", "max_forks_repo_name": "ToyotaResearchInstitute/conex", "max_forks_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T16:02:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T11:25:46.000Z", "avg_line_length": 29.5094339623, "max_line_length": 78, "alphanum_fraction": 0.7429667519, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5058184682123185}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2021 - 2021 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n// Headers for basic SAMRAI objects\n#include <BergerRigoutsos.h>\n#include <CartesianGridGeometry.h>\n#include <LoadBalancer.h>\n#include <LocationIndexRobinBcCoefs.h>\n#include <StandardTagAndInitialize.h>\n\n// Headers for application-specific algorithm/data structure objects\n#include <ibamr/AdvDiffSemiImplicitHierarchyIntegrator.h>\n#include <ibamr/BrinkmanPenalizationRigidBodyDynamics.h>\n#include <ibamr/INSVCStaggeredConservativeHierarchyIntegrator.h>\n#include <ibamr/INSVCStaggeredHierarchyIntegrator.h>\n\n#include <ibtk/AppInitializer.h>\n#include <ibtk/CartGridFunctionSet.h>\n#include <ibtk/HierarchyMathOps.h>\n#include <ibtk/IBTKInit.h>\n#include <ibtk/muParserCartGridFunction.h>\n#include <ibtk/muParserRobinBcCoefs.h>\n\n#include <Eigen/Geometry>\n\n#include <ibamr/app_namespaces.h>\n\n// Application specific includes.\n#include \"LevelSetInitialCondition.h\"\n#include \"SetFluidSolidDensity.h\"\n#include \"SetFluidSolidViscosity.h\"\n#include \"TagLSRefinementCells.h\"\n\n// Declaring the sign of v and returning it.\ninline int\nsgn(double v)\n{\n    return ((v < 0) ? -1 : (v > 0) ? 1 : 0);\n}\n\nFoilInterface foilA, foilB;\n\n// Struct to reset solid level set\nstruct SolidLevelSetResetter\n{\n    SolidLevelSetResetter(Pointer<AdvDiffHierarchyIntegrator> integrator,\n                          Pointer<CellVariable<NDIM, double> > var,\n                          Pointer<BrinkmanPenalizationRigidBodyDynamics> bp,\n                          FoilInterface* foil)\n        : adv_diff_integrator(integrator), ls_solid_var(var), bp_rbd(bp), ptr_foil(foil)\n    {\n        return;\n    }\n\n    Pointer<AdvDiffHierarchyIntegrator> adv_diff_integrator;\n    Pointer<CellVariable<NDIM, double> > ls_solid_var;\n    Pointer<BrinkmanPenalizationRigidBodyDynamics> bp_rbd;\n    FoilInterface* ptr_foil;\n};\n\nvoid\nreset_solid_level_set_callback_fcn(double current_time, double new_time, int /*cycle_num*/, void* ctx)\n{\n    SolidLevelSetResetter* resetter = static_cast<SolidLevelSetResetter*>(ctx);\n    const FoilInterface& foil = *(resetter->ptr_foil);\n\n    // Get the new centroid of the body\n    const double dt = new_time - current_time;\n    const Eigen::Vector3d XCOM_current = resetter->bp_rbd->getCurrentCOMPosn();\n    const Eigen::Vector3d XCOM_new = XCOM_current + dt * (resetter->bp_rbd->getNewCOMTransVelocity());\n\n    // b) Rotational matrix.\n    const double theta = foil.theta_0 * std::sin(2 * M_PI * foil.freq * new_time);\n\n    const Eigen::Vector3d rot_axis(0.0, 0.0, 1.0);\n    Eigen::Quaterniond q(Eigen::AngleAxisd(theta, rot_axis));\n    q.normalize();\n\n    const Eigen::Matrix3d R_mat = q.toRotationMatrix();\n\n    const double& R = foil.R;\n    const Eigen::Vector3d& X0 = foil.X0;\n    const Eigen::Vector3d& X1 = foil.X1;\n    const Eigen::Vector3d& X2 = foil.X2;\n    const Eigen::Vector3d& X3 = foil.X3;\n    Eigen::Vector3d check1, check2, check3, check4, check5, check6;\n\n    // Rotate and translate the top, bottom and circular surface to get new coordiantes.\n    const Eigen::Vector3d X1_new = R_mat * (X1 - X0) + XCOM_new;\n    const Eigen::Vector3d X2_new = R_mat * (X2 - X0) + XCOM_new;\n    const Eigen::Vector3d X3_new = R_mat * (X3 - X0) + XCOM_new;\n\n    const Eigen::Vector3d X_T_new = (X1_new + X2_new + X3_new) / 3.0;\n\n    const double slope1 = (X3_new[1] - X1_new[1]) / (X3_new[0] - X1_new[0]);\n    const double slope2 = (X3_new[1] - X2_new[1]) / (X3_new[0] - X2_new[0]);\n    const double slope3 = (X2_new[0] - X1_new[0]) / (X2_new[1] - X1_new[1]);\n\n    const double y_intercept1 = X1_new[1] - slope1 * X1_new[0];\n    const double y_intercept2 = X2_new[1] - slope2 * X2_new[0];\n    const double x_intercept3 = X1_new[0] - slope3 * X1_new[1];\n\n    double distance1[2], distance2[3]; // Foil has three surfaces and 1 surface for circle.\n\n    // Set a large value away from the solid body.\n    Pointer<PatchHierarchy<NDIM> > patch_hier = resetter->adv_diff_integrator->getPatchHierarchy();\n    const int hier_finest_ln = patch_hier->getFinestLevelNumber();\n\n    VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();\n    const int ls_solid_idx =\n        var_db->mapVariableAndContextToIndex(resetter->ls_solid_var, resetter->adv_diff_integrator->getNewContext());\n\n    for (int ln = 0; ln <= hier_finest_ln; ++ln)\n    {\n        Pointer<PatchLevel<NDIM> > patch_level = patch_hier->getPatchLevel(ln);\n        for (PatchLevel<NDIM>::Iterator p(patch_level); p; p++)\n        {\n            Pointer<Patch<NDIM> > patch = patch_level->getPatch(p());\n            const Box<NDIM>& patch_box = patch->getBox();\n            const Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry();\n            const double* patch_X_lower = patch_geom->getXLower();\n            const hier::Index<NDIM>& patch_lower_idx = patch_box.lower();\n            const double* const patch_dx = patch_geom->getDx();\n\n            Pointer<CellData<NDIM, double> > ls_solid_data = patch->getPatchData(ls_solid_idx);\n            for (Box<NDIM>::Iterator it(patch_box); it; it++)\n            {\n                const hier::Index<NDIM>& ci = it();\n                Eigen::Vector3d coord = Eigen::Vector3d::Zero();\n                for (int d = 0; d < NDIM; ++d)\n                {\n                    coord[d] = patch_X_lower[d] + patch_dx[d] * (static_cast<double>(ci(d) - patch_lower_idx(d)) + 0.5);\n                }\n\n                // Distance from the semi-circle.\n                distance1[0] =\n                    std::sqrt(std::pow((coord[0] - XCOM_new[0]), 2.0) + std::pow((coord[1] - XCOM_new[1]), 2.0)) - R;\n\n                // Distance from top triangle surface.\n                distance2[0] = std::abs(coord[1] - slope1 * coord[0] - y_intercept1) / std::sqrt(1.0 + slope1 * slope1);\n\n                check1 = (X1_new - X3_new).cross(X_T_new - X3_new);\n                check2 = (X1_new - X3_new).cross(coord - X3_new);\n\n                distance2[0] *= (-sgn(check1[2]) * sgn(check2[2]));\n\n                // Distance from bottom triangle surface.\n                distance2[1] = std::abs(coord[1] - slope2 * coord[0] - y_intercept2) / std::sqrt(1.0 + slope2 * slope2);\n\n                check3 = (X2_new - X3_new).cross(X_T_new - X3_new);\n                check4 = (X2_new - X3_new).cross(coord - X3_new);\n\n                distance2[1] *= (-sgn(check3[2]) * sgn(check4[2]));\n\n                // Distance from base of triangle.\n                distance2[2] = std::abs(coord[0] - slope3 * coord[1] - x_intercept3) / std::sqrt(1.0 + slope3 * slope3);\n\n                check5 = (X2_new - X1_new).cross(X_T_new - X1_new);\n                check6 = (X2_new - X1_new).cross(coord - X1_new);\n\n                distance2[2] *= (-sgn(check5[2]) * sgn(check6[2]));\n\n                distance1[1] =\n                    std::max({ distance2[0], distance2[1], distance2[2] }); // intersection of three traingle surfaces\n\n                (*ls_solid_data)(ci) = std::min({ distance1[0], distance1[1] }); // union of circle and triangle\n            }\n        }\n    }\n\n    return;\n}\n\nvoid\nimposed_kinematics(double data_time, int /*cycle_num*/, Eigen::Vector3d& U_com, Eigen::Vector3d& W_com, void* ctx)\n{\n    const FoilInterface& foil = *(static_cast<FoilInterface*>(ctx));\n    const double& theta_0 = foil.theta_0;\n    const double& freq = foil.freq;\n\n    U_com.setZero();\n    W_com.setZero();\n    W_com[2] = theta_0 * 2 * M_PI * freq * std::cos(2 * M_PI * freq * data_time);\n\n    return;\n} // imposed_kinematics\n\nvoid\nexternal_force_torque(double /*data_time*/, int /*cycle_num*/, Eigen::Vector3d& F, Eigen::Vector3d& T, void* /*ctx*/)\n{\n    F.setZero();\n    T.setZero();\n    return;\n} // imposed_kinematics\n\n/*******************************************************************************\n * For each run, the input filename and restart information (if needed) must   *\n * be given on the command line.  For non-restarted case, command line is:     *\n *                                                                             *\n *    executable <input file name>                                             *\n *                                                                             *\n * For restarted run, command line is:                                         *\n *                                                                             *\n *    executable <input file name> <restart directory> <restart number>        *\n *                                                                             *\n *******************************************************************************/\nint\nmain(int argc, char* argv[])\n{\n    // Initialize PETSc, MPI, and SAMRAI.\n    IBTKInit ibtk_init(argc, argv, MPI_COMM_WORLD);\n\n    // Increase maximum patch data component indices\n    SAMRAIManager::setMaxNumberPatchDataEntries(2500);\n\n    { // cleanup dynamically allocated objects prior to shutdown\n\n        // Parse command line options, set some standard options from the input\n        // file, initialize the restart database (if this is a restarted run),\n        // and enable file logging.\n        Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, \"IBLevelSet.log\");\n        Pointer<Database> input_db = app_initializer->getInputDatabase();\n\n        // Get various standard options set in the input file.\n        const bool dump_viz_data = app_initializer->dumpVizData();\n        const int viz_dump_interval = app_initializer->getVizDumpInterval();\n        const bool uses_visit = dump_viz_data && !app_initializer->getVisItDataWriter().isNull();\n\n        const bool dump_restart_data = app_initializer->dumpRestartData();\n        const int restart_dump_interval = app_initializer->getRestartDumpInterval();\n        const string restart_dump_dirname = app_initializer->getRestartDumpDirectory();\n        if (dump_restart_data && (restart_dump_interval > 0) && !restart_dump_dirname.empty())\n        {\n            Utilities::recursiveMkdir(restart_dump_dirname);\n        }\n\n        const bool dump_postproc_data = app_initializer->dumpPostProcessingData();\n        const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval();\n        const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory();\n        if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty())\n        {\n            Utilities::recursiveMkdir(postproc_data_dump_dirname);\n        }\n\n        const bool dump_timer_data = app_initializer->dumpTimerData();\n        const int timer_dump_interval = app_initializer->getTimerDumpInterval();\n\n        // Setup solid information\n        foilA.R = input_db->getDouble(\"R\");\n        foilA.mass = input_db->getDouble(\"MASS\");\n\n        foilA.X0[0] = input_db->getDouble(\"X_COM\");\n        foilA.X0[1] = input_db->getDouble(\"Y_COM\");\n        foilA.X1[0] = input_db->getDouble(\"X1\");\n        foilA.X1[1] = input_db->getDouble(\"Y1\");\n        foilA.X2[0] = input_db->getDouble(\"X2\");\n        foilA.X2[1] = input_db->getDouble(\"Y2\");\n        foilA.X3[0] = input_db->getDouble(\"X3\");\n        foilA.X3[1] = input_db->getDouble(\"Y3\");\n\n        foilA.freq = input_db->getDouble(\"FREQ\");\n        foilA.theta_0 = input_db->getDouble(\"THETA_0\");\n\n        // Create foilB object\n        foilB = foilA;\n        foilB.X0[1] -= 30 * foilB.R;\n        foilB.X1[1] -= 30 * foilB.R;\n        foilB.X2[1] -= 30 * foilB.R;\n        foilB.X3[1] -= 30 * foilB.R;\n\n        // Create major algorithm and data objects that comprise the\n        // application.  These objects are configured from the input database\n        // and, if this is a restarted run, from the restart database.\n        Pointer<INSVCStaggeredHierarchyIntegrator> navier_stokes_integrator =\n            new INSVCStaggeredConservativeHierarchyIntegrator(\n                \"INSVCStaggeredConservativeHierarchyIntegrator\",\n                app_initializer->getComponentDatabase(\"INSVCStaggeredConservativeHierarchyIntegrator\"));\n\n        // Set up the advection diffusion hierarchy integrator\n        Pointer<AdvDiffHierarchyIntegrator> adv_diff_integrator = new AdvDiffSemiImplicitHierarchyIntegrator(\n            \"AdvDiffSemiImplicitHierarchyIntegrator\",\n            app_initializer->getComponentDatabase(\"AdvDiffSemiImplicitHierarchyIntegrator\"));\n\n        navier_stokes_integrator->registerAdvDiffHierarchyIntegrator(adv_diff_integrator);\n\n        Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>(\n            \"CartesianGeometry\", app_initializer->getComponentDatabase(\"CartesianGeometry\"));\n        Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>(\"PatchHierarchy\", grid_geometry);\n\n        Pointer<StandardTagAndInitialize<NDIM> > error_detector =\n            new StandardTagAndInitialize<NDIM>(\"StandardTagAndInitialize\",\n                                               navier_stokes_integrator,\n                                               app_initializer->getComponentDatabase(\"StandardTagAndInitialize\"));\n        Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>();\n        Pointer<LoadBalancer<NDIM> > load_balancer =\n            new LoadBalancer<NDIM>(\"LoadBalancer\", app_initializer->getComponentDatabase(\"LoadBalancer\"));\n        Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm =\n            new GriddingAlgorithm<NDIM>(\"GriddingAlgorithm\",\n                                        app_initializer->getComponentDatabase(\"GriddingAlgorithm\"),\n                                        error_detector,\n                                        box_generator,\n                                        load_balancer);\n\n        // Create level sets for solid interfaces.\n        const string& ls_foilA = \"level_set_foilA\";\n        Pointer<CellVariable<NDIM, double> > phi_var_foilA = new CellVariable<NDIM, double>(ls_foilA);\n        const string& ls_foilB = \"level_set_foilB\";\n        Pointer<CellVariable<NDIM, double> > phi_var_foilB = new CellVariable<NDIM, double>(ls_foilB);\n\n        // Register the level sets with advection diffusion integrator.\n        adv_diff_integrator->registerTransportedQuantity(phi_var_foilA);\n        adv_diff_integrator->setDiffusionCoefficient(phi_var_foilA, 0.0);\n        adv_diff_integrator->setAdvectionVelocity(phi_var_foilA,\n                                                  navier_stokes_integrator->getAdvectionVelocityVariable());\n\n        adv_diff_integrator->registerTransportedQuantity(phi_var_foilB);\n        adv_diff_integrator->setDiffusionCoefficient(phi_var_foilB, 0.0);\n        adv_diff_integrator->setAdvectionVelocity(phi_var_foilB,\n                                                  navier_stokes_integrator->getAdvectionVelocityVariable());\n\n        // Solid level set initial condition\n        Pointer<CartGridFunction> phi_foilA_init = new LevelSetInitialCondition(\"phi_foilA_init\", foilA);\n        Pointer<CartGridFunction> phi_foilB_init = new LevelSetInitialCondition(\"phi_foilB_init\", foilB);\n        adv_diff_integrator->setInitialConditions(phi_var_foilA, phi_foilA_init);\n        adv_diff_integrator->setInitialConditions(phi_var_foilB, phi_foilB_init);\n\n        // Solid level set resetting consition\n        SolidLevelSetResetter foilA_level_set_resetter(adv_diff_integrator, phi_var_foilA, /*bp_rbd*/ nullptr, &foilA);\n        SolidLevelSetResetter foilB_level_set_resetter(adv_diff_integrator, phi_var_foilB, /*bp_rbd*/ nullptr, &foilB);\n        adv_diff_integrator->registerIntegrateHierarchyCallback(&reset_solid_level_set_callback_fcn,\n                                                                static_cast<void*>(&foilA_level_set_resetter));\n        adv_diff_integrator->registerIntegrateHierarchyCallback(&reset_solid_level_set_callback_fcn,\n                                                                static_cast<void*>(&foilB_level_set_resetter));\n\n        // Fluid density and viscosity.\n        Pointer<CellVariable<NDIM, double> > mu_var = new CellVariable<NDIM, double>(\"mu\");\n        Pointer<hier::Variable<NDIM> > rho_var;\n        rho_var = new SideVariable<NDIM, double>(\"rho\");\n        navier_stokes_integrator->registerMassDensityVariable(rho_var);\n        navier_stokes_integrator->registerViscosityVariable(mu_var);\n\n        // Array for input into callback function\n        const double rho_fluid = input_db->getDouble(\"RHO_F\");\n        SetFluidSolidDensity* ptr_setFluidSolidDensity = new SetFluidSolidDensity(\"SetFluidSolidDensity\", rho_fluid);\n        navier_stokes_integrator->registerResetFluidDensityFcn(&callSetFluidSolidDensityCallbackFunction,\n                                                               static_cast<void*>(ptr_setFluidSolidDensity));\n\n        const double mu_fluid = input_db->getDouble(\"MU_F\");\n        SetFluidSolidViscosity* ptr_setFluidSolidViscosity =\n            new SetFluidSolidViscosity(\"SetFluidSolidViscosity\", mu_fluid);\n        navier_stokes_integrator->registerResetFluidViscosityFcn(&callSetFluidSolidViscosityCallbackFunction,\n                                                                 static_cast<void*>(ptr_setFluidSolidViscosity));\n\n        // Register callback function for tagging refined cells for level set data\n        const double tag_value = input_db->getDouble(\"LS_TAG_VALUE\");\n        const double tag_thresh = input_db->getDouble(\"LS_TAG_ABS_THRESH\");\n        TagLSRefinementCells ls_foilA_tagger(adv_diff_integrator, phi_var_foilA, tag_value, tag_thresh);\n        TagLSRefinementCells ls_foilB_tagger(adv_diff_integrator, phi_var_foilB, tag_value, tag_thresh);\n        navier_stokes_integrator->registerApplyGradientDetectorCallback(&callTagSolidLSRefinementCellsCallbackFunction,\n                                                                        static_cast<void*>(&ls_foilA_tagger));\n        navier_stokes_integrator->registerApplyGradientDetectorCallback(&callTagSolidLSRefinementCellsCallbackFunction,\n                                                                        static_cast<void*>(&ls_foilB_tagger));\n\n        // Create Eulerian initial condition specification objects.\n        if (input_db->keyExists(\"VelocityInitialConditions\"))\n        {\n            Pointer<CartGridFunction> u_init = new muParserCartGridFunction(\n                \"u_init\", app_initializer->getComponentDatabase(\"VelocityInitialConditions\"), grid_geometry);\n            navier_stokes_integrator->registerVelocityInitialConditions(u_init);\n        }\n\n        if (input_db->keyExists(\"PressureInitialConditions\"))\n        {\n            Pointer<CartGridFunction> p_init = new muParserCartGridFunction(\n                \"p_init\", app_initializer->getComponentDatabase(\"PressureInitialConditions\"), grid_geometry);\n            navier_stokes_integrator->registerPressureInitialConditions(p_init);\n        }\n\n        // Create Eulerian boundary condition specification objects (when necessary).\n        const IntVector<NDIM>& periodic_shift = grid_geometry->getPeriodicShift();\n        vector<RobinBcCoefStrategy<NDIM>*> u_bc_coefs(NDIM);\n        if (periodic_shift.min() > 0)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                u_bc_coefs[d] = NULL;\n            }\n        }\n        else\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                ostringstream bc_coefs_name_stream;\n                bc_coefs_name_stream << \"u_bc_coefs_\" << d;\n                const string bc_coefs_name = bc_coefs_name_stream.str();\n\n                ostringstream bc_coefs_db_name_stream;\n                bc_coefs_db_name_stream << \"VelocityBcCoefs_\" << d;\n                const string bc_coefs_db_name = bc_coefs_db_name_stream.str();\n\n                u_bc_coefs[d] = new muParserRobinBcCoefs(\n                    bc_coefs_name, app_initializer->getComponentDatabase(bc_coefs_db_name), grid_geometry);\n            }\n            navier_stokes_integrator->registerPhysicalBoundaryConditions(u_bc_coefs);\n        }\n\n        RobinBcCoefStrategy<NDIM>* rho_bc_coef = NULL;\n        if (!(periodic_shift.min() > 0) && input_db->keyExists(\"DensityBcCoefs\"))\n        {\n            rho_bc_coef = new muParserRobinBcCoefs(\n                \"rho_bc_coef\", app_initializer->getComponentDatabase(\"DensityBcCoefs\"), grid_geometry);\n            navier_stokes_integrator->registerMassDensityBoundaryConditions(rho_bc_coef);\n        }\n\n        RobinBcCoefStrategy<NDIM>* mu_bc_coef = NULL;\n        if (!(periodic_shift.min() > 0) && input_db->keyExists(\"ViscosityBcCoefs\"))\n        {\n            mu_bc_coef = new muParserRobinBcCoefs(\n                \"mu_bc_coef\", app_initializer->getComponentDatabase(\"ViscosityBcCoefs\"), grid_geometry);\n            navier_stokes_integrator->registerViscosityBoundaryConditions(mu_bc_coef);\n        }\n\n        RobinBcCoefStrategy<NDIM>* phi_bc_coef = NULL;\n        if (!(periodic_shift.min() > 0) && input_db->keyExists(\"PhiBcCoefs\"))\n        {\n            phi_bc_coef = new muParserRobinBcCoefs(\n                \"phi_bc_coef\", app_initializer->getComponentDatabase(\"PhiBcCoefs\"), grid_geometry);\n        }\n        adv_diff_integrator->setPhysicalBcCoef(phi_var_foilA, phi_bc_coef);\n\n        // Configure the Brinkman penalization object to do the rigid body dynamics.\n        Pointer<BrinkmanPenalizationRigidBodyDynamics> bp_rbd_A =\n            new BrinkmanPenalizationRigidBodyDynamics(\"Airfoil_A\",\n                                                      phi_var_foilA,\n                                                      adv_diff_integrator,\n                                                      navier_stokes_integrator,\n                                                      app_initializer->getComponentDatabase(\"BrinkmanPenalization\"),\n                                                      /*register_for_restart*/ true);\n\n        Pointer<BrinkmanPenalizationRigidBodyDynamics> bp_rbd_B =\n            new BrinkmanPenalizationRigidBodyDynamics(\"Airfoil_B\",\n                                                      phi_var_foilB,\n                                                      adv_diff_integrator,\n                                                      navier_stokes_integrator,\n                                                      app_initializer->getComponentDatabase(\"BrinkmanPenalization\"),\n                                                      /*register_for_restart*/ true);\n\n        {\n            FreeRigidDOFVector free_dofs;\n            free_dofs << 1, 1, 0;\n            Eigen::Vector3d U_i = Eigen::Vector3d::Zero();\n            Eigen::Vector3d W_i(0.0, 0.0, 2 * M_PI * foilA.freq * foilA.theta_0);\n            bp_rbd_A->setSolveRigidBodyVelocity(free_dofs);\n            bp_rbd_A->registerKinematicsFunction(&imposed_kinematics, &foilA);\n            bp_rbd_A->registerExternalForceTorqueFunction(&external_force_torque);\n            bp_rbd_A->setInitialConditions(foilA.X0, U_i, W_i, foilA.mass);\n            navier_stokes_integrator->registerBrinkmanPenalizationStrategy(bp_rbd_A);\n            foilA_level_set_resetter.bp_rbd = bp_rbd_A;\n        }\n\n        {\n            FreeRigidDOFVector free_dofs;\n            free_dofs << 1, 1, 0;\n            Eigen::Vector3d U_i = Eigen::Vector3d::Zero();\n            Eigen::Vector3d W_i(0.0, 0.0, 2 * M_PI * foilB.freq * foilB.theta_0);\n            bp_rbd_B->setSolveRigidBodyVelocity(free_dofs);\n            bp_rbd_B->registerKinematicsFunction(&imposed_kinematics, &foilB);\n            bp_rbd_B->registerExternalForceTorqueFunction(&external_force_torque);\n            bp_rbd_B->setInitialConditions(foilB.X0, U_i, W_i, foilB.mass);\n            navier_stokes_integrator->registerBrinkmanPenalizationStrategy(bp_rbd_B);\n            foilB_level_set_resetter.bp_rbd = bp_rbd_B;\n        }\n\n        // Set up visualization plot file writers.\n        Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter();\n        if (uses_visit)\n        {\n            navier_stokes_integrator->registerVisItDataWriter(visit_data_writer);\n        }\n\n        // Initialize hierarchy configuration and data on all patches.\n        navier_stokes_integrator->initializePatchHierarchy(patch_hierarchy, gridding_algorithm);\n\n        // Deallocate initialization objects.\n        app_initializer.setNull();\n\n        // Print the input database contents to the log file.\n        plog << \"Input database:\\n\";\n        input_db->printClassData(plog);\n\n        // Write out initial visualization data.\n        int iteration_num = navier_stokes_integrator->getIntegratorStep();\n        double loop_time = navier_stokes_integrator->getIntegratorTime();\n\n        if (dump_viz_data)\n        {\n            pout << \"\\n\\nWriting visualization files...\\n\\n\";\n            if (uses_visit)\n            {\n                navier_stokes_integrator->setupPlotData();\n                visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n            }\n        }\n\n        // Open streams to save position and velocity of the structure.\n        ofstream rbd_foilA_stream, ft_foilA_stream, rbd_foilB_stream, ft_foilB_stream;\n        if (SAMRAI_MPI::getRank() == 0)\n        {\n            rbd_foilA_stream.open(\"rbd.foilA\", ios_base::out | ios_base::app);\n            ft_foilA_stream.open(\"hydro_force_torque.foilA\", ios_base::out | std::ios_base::app);\n\n            rbd_foilB_stream.open(\"rbd.foilB\", ios_base::out | ios_base::app);\n            ft_foilB_stream.open(\"hydro_force_torque.foilB\", ios_base::out | std::ios_base::app);\n        }\n\n        // Main time step loop.\n        double loop_time_end = navier_stokes_integrator->getEndTime();\n        double dt = 0.0;\n        while (!MathUtilities<double>::equalEps(loop_time, loop_time_end) && navier_stokes_integrator->stepsRemaining())\n        {\n            iteration_num = navier_stokes_integrator->getIntegratorStep();\n            loop_time = navier_stokes_integrator->getIntegratorTime();\n\n            pout << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"At beginning of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n\n            dt = navier_stokes_integrator->getMaximumTimeStepSize();\n            pout << \"Advancing hierarchy with timestep size dt = \" << dt << \"\\n\";\n            navier_stokes_integrator->advanceHierarchy(dt);\n            loop_time += dt;\n\n            pout << \"\\n\";\n            pout << \"At end       of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"\\n\";\n\n            // At specified intervals, write visualization and restart files,\n            // and print out timer data.\n            iteration_num += 1;\n            const bool last_step = !navier_stokes_integrator->stepsRemaining();\n            if (dump_viz_data && uses_visit && (iteration_num % viz_dump_interval == 0 || last_step))\n            {\n                pout << \"Writing visualization files...\\n\\n\";\n                navier_stokes_integrator->setupPlotData();\n                visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n            }\n            if (dump_restart_data && (iteration_num % restart_dump_interval == 0 || last_step))\n            {\n                pout << \"Writing restart files...\\n\\nn\";\n                RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num);\n            }\n            if (dump_timer_data && (iteration_num % timer_dump_interval == 0 || last_step))\n            {\n                pout << \"Writing timer data...\\n\\n\";\n                TimerManager::getManager()->print(plog);\n            }\n\n            if (SAMRAI_MPI::getRank() == 0)\n            {\n                {\n                    const Eigen::Vector3d& rbd_posn = bp_rbd_A->getCurrentCOMPosn();\n                    const Eigen::Vector3d& rbd_trans_vel = bp_rbd_A->getCurrentCOMTransVelocity();\n\n                    rbd_foilA_stream.precision(12);\n                    rbd_foilA_stream.setf(ios::fixed, ios::floatfield);\n                    rbd_foilA_stream << loop_time << \"\\t\" << rbd_posn[0] << \"\\t\" << rbd_posn[1] << \"\\t\"\n                                     << rbd_trans_vel[0] << \"\\t\" << rbd_trans_vel[1] << std::endl;\n\n                    Eigen::Vector3d hydro_force_pressure, hydro_force_viscous, hydro_torque_pressure,\n                        hydro_torque_viscous;\n                    bp_rbd_A->getHydrodynamicForceTorque(\n                        hydro_force_pressure, hydro_force_viscous, hydro_torque_pressure, hydro_torque_viscous);\n                    ft_foilA_stream.precision(12);\n                    ft_foilA_stream.setf(ios::fixed, ios::floatfield);\n                    ft_foilA_stream << loop_time << \"\\t\" << hydro_force_viscous[0] << \"\\t\" << hydro_force_viscous[1]\n                                    << \"\\t\" << hydro_force_pressure[0] << \"\\t\" << hydro_force_pressure[1] << std::endl;\n                }\n\n                {\n                    const Eigen::Vector3d& rbd_posn = bp_rbd_B->getCurrentCOMPosn();\n                    const Eigen::Vector3d& rbd_trans_vel = bp_rbd_B->getCurrentCOMTransVelocity();\n\n                    rbd_foilB_stream.precision(12);\n                    rbd_foilB_stream.setf(ios::fixed, ios::floatfield);\n                    rbd_foilB_stream << loop_time << \"\\t\" << rbd_posn[0] << \"\\t\" << rbd_posn[1] << \"\\t\"\n                                     << rbd_trans_vel[0] << \"\\t\" << rbd_trans_vel[1] << std::endl;\n\n                    Eigen::Vector3d hydro_force_pressure, hydro_force_viscous, hydro_torque_pressure,\n                        hydro_torque_viscous;\n                    bp_rbd_B->getHydrodynamicForceTorque(\n                        hydro_force_pressure, hydro_force_viscous, hydro_torque_pressure, hydro_torque_viscous);\n                    ft_foilB_stream.precision(12);\n                    ft_foilB_stream.setf(ios::fixed, ios::floatfield);\n                    ft_foilB_stream << loop_time << \"\\t\" << hydro_force_viscous[0] << \"\\t\" << hydro_force_viscous[1]\n                                    << \"\\t\" << hydro_force_pressure[0] << \"\\t\" << hydro_force_pressure[1] << std::endl;\n                }\n            }\n        }\n\n        // Close the logging streams.\n        if (SAMRAI_MPI::getRank() == 0)\n        {\n            rbd_foilA_stream.close();\n            ft_foilA_stream.close();\n            rbd_foilB_stream.close();\n            ft_foilB_stream.close();\n        }\n\n        // Delete dumb pointers.\n        for (unsigned int d = 0; d < NDIM; ++d) delete u_bc_coefs[d];\n        delete ptr_setFluidSolidDensity;\n        delete ptr_setFluidSolidViscosity;\n        delete rho_bc_coef;\n        delete mu_bc_coef;\n        delete phi_bc_coef;\n\n    } // cleanup dynamically allocated objects prior to shutdown\n\n    SAMRAIManager::shutdown();\n} // main\n", "meta": {"hexsha": "0fe10bab6b9a770ed8a3a36bc5bc360cec6bf3e6", "size": 31248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/IBLevelSet/ex5/example.cpp", "max_stars_repo_name": "colegruninger97/IBAMR", "max_stars_repo_head_hexsha": "0f9b9b95533022571cc1a9972c42d8fc3f9d2a18", "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/IBLevelSet/ex5/example.cpp", "max_issues_repo_name": "colegruninger97/IBAMR", "max_issues_repo_head_hexsha": "0f9b9b95533022571cc1a9972c42d8fc3f9d2a18", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/IBLevelSet/ex5/example.cpp", "max_forks_repo_name": "colegruninger97/IBAMR", "max_forks_repo_head_hexsha": "0f9b9b95533022571cc1a9972c42d8fc3f9d2a18", "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": 49.2870662461, "max_line_length": 120, "alphanum_fraction": 0.6121671787, "num_tokens": 7417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5058184678591666}}
{"text": "//  Copyright (c) 2006 Xiaogang Zhang\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_BESSEL_JN_HPP\n#define BOOST_MATH_BESSEL_JN_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/special_functions/detail/bessel_j0.hpp>\n#include <boost/math/special_functions/detail/bessel_j1.hpp>\n#include <boost/math/special_functions/detail/bessel_jy.hpp>\n#include <boost/math/special_functions/detail/bessel_jy_asym.hpp>\n#include <boost/math/special_functions/detail/bessel_jy_series.hpp>\n\n// Bessel function of the first kind of integer order\n// J_n(z) is the minimal solution\n// n < abs(z), forward recurrence stable and usable\n// n >= abs(z), forward recurrence unstable, use Miller's algorithm\n\nnamespace boost { namespace math { namespace detail{\n\ntemplate <typename T, typename Policy>\nT bessel_jn(int n, T x, const Policy& pol)\n{\n    T value(0), factor, current, prev, next;\n\n    BOOST_MATH_STD_USING\n\n    //\n    // Reflection has to come first:\n    //\n    if (n < 0)\n    {\n        factor = static_cast<T>((n & 0x1) ? -1 : 1);  // J_{-n}(z) = (-1)^n J_n(z)\n        n = -n;\n    }\n    else\n    {\n        factor = 1;\n    }\n    if(x < 0)\n    {\n        factor *= (n & 0x1) ? -1 : 1;  // J_{n}(-z) = (-1)^n J_n(z)\n        x = -x;\n    }\n    //\n    // Special cases:\n    //\n    if(asymptotic_bessel_large_x_limit(T(n), x))\n       return factor * asymptotic_bessel_j_large_x_2<T>(T(n), x, pol);\n    if (n == 0)\n    {\n        return factor * bessel_j0(x);\n    }\n    if (n == 1)\n    {\n        return factor * bessel_j1(x);\n    }\n\n    if (x == 0)                             // n >= 2\n    {\n        return static_cast<T>(0);\n    }\n\n    BOOST_ASSERT(n > 1);\n    T scale = 1;\n    if (n < abs(x))                         // forward recurrence\n    {\n        prev = bessel_j0(x);\n        current = bessel_j1(x);\n        policies::check_series_iterations<T>(\"boost::math::bessel_j_n<%1%>(%1%,%1%)\", n, pol);\n        for (int k = 1; k < n; k++)\n        {\n            T fact = 2 * k / x;\n            //\n            // rescale if we would overflow or underflow:\n            //\n            if((fabs(fact) > 1) && ((tools::max_value<T>() - fabs(prev)) / fabs(fact) < fabs(current)))\n            {\n               scale /= current;\n               prev /= current;\n               current = 1;\n            }\n            value = fact * current - prev;\n            prev = current;\n            current = value;\n        }\n    }\n    else if((x < 1) || (n > x * x / 4) || (x < 5))\n    {\n       return factor * bessel_j_small_z_series(T(n), x, pol);\n    }\n    else                                    // backward recurrence\n    {\n        T fn; int s;                        // fn = J_(n+1) / J_n\n        // |x| <= n, fast convergence for continued fraction CF1\n        boost::math::detail::CF1_jy(static_cast<T>(n), x, &fn, &s, pol);\n        prev = fn;\n        current = 1;\n        // Check recursion won't go on too far:\n        policies::check_series_iterations<T>(\"boost::math::bessel_j_n<%1%>(%1%,%1%)\", n, pol);\n        for (int k = n; k > 0; k--)\n        {\n            T fact = 2 * k / x;\n            if((fabs(fact) > 1) && ((tools::max_value<T>() - fabs(prev)) / fabs(fact) < fabs(current)))\n            {\n               prev /= current;\n               scale /= current;\n               current = 1;\n            }\n            next = fact * current - prev;\n            prev = current;\n            current = next;\n        }\n        value = bessel_j0(x) / current;       // normalization\n        scale = 1 / scale;\n    }\n    value *= factor;\n\n    if(tools::max_value<T>() * scale < fabs(value))\n       return policies::raise_overflow_error<T>(\"boost::math::bessel_jn<%1%>(%1%,%1%)\", 0, pol);\n\n    return value / scale;\n}\n\n}}} // namespaces\n\n#endif // BOOST_MATH_BESSEL_JN_HPP\n\n", "meta": {"hexsha": "607823be90207ba4b0ac4be3e6415938b8d8fb73", "size": 3914, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/special_functions/detail/bessel_jn.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/special_functions/detail/bessel_jn.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": 61.0, "max_issues_repo_issues_event_min_datetime": "2017-01-22T20:35:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-13T14:48:46.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/special_functions/detail/bessel_jn.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": 54.0, "max_forks_repo_forks_event_min_datetime": "2017-03-02T06:55:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T01:12:20.000Z", "avg_line_length": 29.2089552239, "max_line_length": 103, "alphanum_fraction": 0.5214614205, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5058184675060142}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2014 Olga Diamanti <olga.diam@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\n#include \"polyroots.h\"\n#include <Eigen/Eigenvalues>\n\ntemplate <typename S, typename T>\nIGL_INLINE void igl::polyRoots(Eigen::Matrix<S, Eigen::Dynamic,1> &polyCoeff, //real or comples coefficients\n                          Eigen::Matrix<std::complex<T>, Eigen::Dynamic,1> &roots // complex roots (double or float)\n)\n{\n  //  degree\n  int n = polyCoeff.rows() - 1;\n\n  Eigen::Matrix<S, Eigen::Dynamic, 1> d (n,1);\n  d = polyCoeff.tail(n)/polyCoeff(0);\n\n  Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic> I; I.setIdentity(n-1,n-1);\n  Eigen::Matrix<S, Eigen::Dynamic, 1> z; z.setZero(n-1,1);\n\n  Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic> a(n,n);\n  a<<-d.transpose(),I,z;\n  roots = a.eigenvalues();\n\n}\n\n\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate void igl::polyRoots<std::complex<double>, double>(Eigen::Matrix<std::complex<double>, -1, 1, 0, -1, 1>&, Eigen::Matrix<std::complex<double>, -1, 1, 0, -1, 1>&);\ntemplate void igl::polyRoots<double, double>(Eigen::Matrix<double, -1, 1, 0, -1, 1>&, Eigen::Matrix<std::complex<double>, -1, 1, 0, -1, 1>&);\n#endif\n", "meta": {"hexsha": "0fb9a6be62e880e1c01a629663aeaee49c147210", "size": 1424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/igl/polyroots.cpp", "max_stars_repo_name": "rushmash/libwetcloth", "max_stars_repo_head_hexsha": "24f16481c68952c3d2a91acd6e3b74eb091b66bc", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 199.0, "max_stars_repo_stars_event_min_datetime": "2018-02-26T20:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:09:52.000Z", "max_issues_repo_path": "include/igl/polyroots.cpp", "max_issues_repo_name": "rushmash/libwetcloth", "max_issues_repo_head_hexsha": "24f16481c68952c3d2a91acd6e3b74eb091b66bc", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-03-20T02:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T01:13:22.000Z", "max_forks_repo_path": "include/igl/polyroots.cpp", "max_forks_repo_name": "rushmash/libwetcloth", "max_forks_repo_head_hexsha": "24f16481c68952c3d2a91acd6e3b74eb091b66bc", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2018-02-28T01:33:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T16:06:19.000Z", "avg_line_length": 36.5128205128, "max_line_length": 169, "alphanum_fraction": 0.6678370787, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5058184566971933}}
{"text": "#include <replay/planar_direction.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <replay/matrix2.hpp>\n#include <replay/vector_math.hpp>\n\nusing namespace replay;\n\nplanar_direction planar_direction::move(planar_direction from, planar_direction to, float max_angle_delta)\n{\n    auto const relative_move = (to - from).normalized();\n\n    if (std::abs(relative_move.angle()) < max_angle_delta)\n        return to;\n\n    return planar_direction{ from.angle() + math::clamp_absolute(relative_move.angle(), max_angle_delta) };\n}\n\nplanar_direction planar_direction::normalized() const\n{\n    auto angle = m_angle;\n    constexpr auto pi = boost::math::constants::pi<float>();\n    constexpr auto two_pi = boost::math::constants::two_pi<float>();\n\n    while (angle > pi)\n        angle -= two_pi;\n    while (angle <= -pi)\n        angle += two_pi;\n    return planar_direction(angle);\n}\n\nplanar_direction planar_direction::average(planar_direction from, planar_direction to)\n{\n    return planar_direction::from_vector(from.as_vector() + to.as_vector());\n}\n", "meta": {"hexsha": "5adf827528b8881a2ee640392dad1476b9ff51f9", "size": 1050, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/planar_direction.cpp", "max_stars_repo_name": "ltjax/replay", "max_stars_repo_head_hexsha": "33680beae225c9c388f33e3f7ffd7e8bae4643e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T19:52:50.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-15T19:52:50.000Z", "max_issues_repo_path": "source/planar_direction.cpp", "max_issues_repo_name": "ltjax/replay", "max_issues_repo_head_hexsha": "33680beae225c9c388f33e3f7ffd7e8bae4643e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-12-03T21:53:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-23T02:11:50.000Z", "max_forks_repo_path": "source/planar_direction.cpp", "max_forks_repo_name": "ltjax/replay", "max_forks_repo_head_hexsha": "33680beae225c9c388f33e3f7ffd7e8bae4643e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0, "max_line_length": 107, "alphanum_fraction": 0.7238095238, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5057560780602482}}
{"text": "#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n//#include <CGAL/Exact_predicates_exact_constructions_kernel_with_sqrt.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Projection_traits_xy_3.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Triangulation_face_base_with_info_2.h>\n#include <CGAL/Triangulation_vertex_base_with_id_2.h>\n#include <CGAL/Min_circle_2.h>\n#include <CGAL/Min_circle_2_traits_2.h>\n#include <CGAL/basic.h>\n#include <CGAL/QP_models.h>\n#include <CGAL/QP_functions.h>\n#include <CGAL/Gmpz.h>\n#include \"UnionFind.h\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/bipartite.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\n#include <iostream>\n#include <cassert>\n#include <vector>\n#include <queue>\n#include <stack>\n#include <cmath>\n#include <valarray>\n\n// LP/QP\ntypedef CGAL::Gmpq ET;\n// program and solution types\ntypedef CGAL::Quadratic_program<ET> Program;\ntypedef CGAL::Quadratic_program_solution<ET> Solution;\n\n// General CGAL\ntypedef CGAL::Exact_predicates_exact_constructions_kernel EK;\n//typedef CGAL::Exact_predicates_exact_constructions_kernel_with_sqrt KR;\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel IK;\n//typedef CGAL::Min_circle_2_traits_2<KR> Traits;\n//typedef CGAL::Min_circle_2<Traits> Min_circle;\n\n// Change when use different kernels!\ntypedef long long lint;\ntypedef IK::Point_2 Pt;\ntypedef IK::Point_3 Pt3;\ntypedef IK::Ray_2 Ray;\ntypedef IK::Vector_2 Vec;\ntypedef IK::Segment_2 Seg;\n\n// Triangulation\ntypedef int ind_t; // not a good one...\n\n//typedef CGAL::Triangulation_vertex_base_with_info_2<ind_t, IK>\tVb;\n//typedef CGAL::Triangulation_data_structure_2<Vb>\tTds;\n//typedef CGAL::Delaunay_triangulation_2<IK>\t\tDelaunay;\n//typedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\n//typedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\n//typedef Delaunay::Vertex_handle\t\tVertex_handle;\n//typedef Delaunay::Point\t\tDPt;\n\n// Boost\ntypedef boost::adjacency_list < boost::vecS, boost::vecS, boost::undirectedS,\n\tboost::no_property, boost::property < boost::edge_weight_t, lint > > Graph;\ntypedef boost::property_map < Graph, boost::edge_weight_t >::type WeightMap;\ntypedef boost::graph_traits < Graph >::edge_descriptor Edge;\ntypedef boost::graph_traits < Graph >::edge_iterator EdgeIt;\ntypedef boost::graph_traits < Graph >::out_edge_iterator OutEdgeIt;\ntypedef boost::graph_traits < Graph >::vertex_descriptor Vertex;\n//typedef std::pair<int, int> E;\n\n\n#define _o std::cout\n#define _l std::endl\n#define _i std::cin\n#define _e std::cerr\n\ndouble floor_to_double(const CGAL::Quotient<ET>& x)\n{\n\tdouble a = std::floor(CGAL::to_double(x));\n\twhile (a > x) a -= 1;\n\twhile (a + 1 <= x) a += 1;\n\treturn a;\n}\n\ndouble ceil_to_double(const CGAL::Quotient<ET>& x)\n{\n\tdouble a = std::ceil(CGAL::to_double(x));\n\twhile (a < x) a += 1;\n\twhile (a - 1 >= x) a -= 1;\n\treturn a;\n}\n\n\nstruct MyRay {\n\tRay r;\n\tint idx;\n\tMyRay(Ray r=Ray(), int i=0):r(r),idx(i){}\n\tMyRay(Pt src, Pt next, int i) {\n\t\tr = Ray(src, next);\n\t\tidx = i;\n\t}\n};\nbool CompareRayByY0(const MyRay& r1, const MyRay& r2) {\n\treturn r1.r.source().y() > r2.r.source().y();\n}\nint whoWins(const std::vector<MyRay>& rays, int oldone, int newone) {\n\tVec vo = rays[oldone].r.to_vector();\n\tVec vn = rays[newone].r.to_vector();\n\tif (vo.y() >= 0 && vn.y() >= 0) {\n\t\treturn oldone;\n\t}\n\tif (vo.y() < 0 && vn.y() < 0) {\n\t\treturn newone;\n\t}\n\tif (vo.y() >= 0 && vn.y() < 0) {\n\t\treturn (vo.y() * vn.x() + vo.x() * vn.y() > 0) ? newone : oldone;\n\t}\n\tif (vo.y() < 0 && vn.y() >= 0) {\n\t\treturn (vo.y() * vn.x() + vo.x() * vn.y() > 0) ? oldone : newone;\n\t}\n\treturn -1;\n}\nint rayChallenge(Ray& rold, Ray& rnew) {\n\t// rold.y0 > rnew.y0\n\t// return 0 if old one wins\n\t// return 1 if new one wins\n\tVec vo = rold.to_vector();\n\tVec vn = rnew.to_vector();\n\tif (vo.y() >= 0 && vn.y() >= 0) {\n\t\treturn 0;\n\t}\n\tif (vo.y() < 0 && vn.y() < 0) {\n\t\treturn 1;\n\t}\n\tif (vo.y() >= 0 && vn.y() < 0) {\n\t\tSeg so(rold.source(), rold.source() + vo);\n\t\tSeg sn(rnew.source(), Pt(rnew.source().x() + vn.x(), rnew.source().y() - vn.y()));\n\t\tCGAL::Comparison_result cr = CGAL::compare_slopes(so, sn);\n\t\t//_e << \" _\" << cr << \"_ \";\n\t\treturn (cr == CGAL::LARGER ? 1 : 0);\n\t\t//return (vo.y() * vn.x() + vo.x() * vn.y() > 0) ? 1 : 0;\n\t}\n\tif (vo.y() < 0 && vn.y() >= 0) {\n\t\tSeg so(rold.source(), Pt(rold.source().x() + vo.x(), rold.source().y() - vo.y()));\n\t\tSeg sn(rnew.source(), rnew.source() + vn);\n\t\tCGAL::Comparison_result cr = CGAL::compare_slopes(sn, so);\n\t\t//_e << \" _\" << cr << \"_ \";\n\t\treturn (cr == CGAL::LARGER ? 0 : 1);\n\t}\n\treturn 0;\n}\nvoid Motorcycles() {\n\tint n; _i >> n;\n\t_e << n << _l;\n\tstd::vector<MyRay> rays(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tlint y0, x1, y1;\n\t\t_i >> y0 >> x1 >> y1;\n\t\trays[i] = MyRay(Pt(0, y0), Pt(x1, y1), i);\n\t}\n\tstd::sort(rays.begin(), rays.end(), CompareRayByY0);\n\n\tstd::stack<MyRay> st_rays;\n\tst_rays.push(rays[0]);\n\tfor (int i = 1; i < n; i++) {\n\t\tMyRay ray = rays[i];\n\t\twhile (!st_rays.empty()) {\n\t\t\tMyRay topray = st_rays.top();\n\t\t\tif (!CGAL::do_intersect(ray.r, topray.r)) {\n\t\t\t\tst_rays.push(ray);\n\t\t\t\t//_e << ray.idx << \" in stack\\n\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//_e << topray.idx << \":\" << topray.r.to_vector() << \"---\" << ray.idx << \":\" << ray.r.to_vector();\n\t\t\t\tint who = rayChallenge(topray.r, ray.r);\n\t\t\t\t//_e << \" \\twinner:\" << ((who==0)?topray.idx:ray.idx) << _l;\n\t\t\t\tif (who == 0) break;\n\t\t\t\telse {\n\t\t\t\t\t//_e << topray.idx << \" out of stack\\n\";\n\t\t\t\t\tst_rays.pop();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (st_rays.empty()) {\n\t\t\tst_rays.push(ray);\n\t\t\t//_e << ray.idx << \" in empty stack\\n\";\n\t\t}\n\t}\n\t//_e << _l;\n\tstd::vector<int> alives;\n\twhile (!st_rays.empty()) {\n\t\talives.push_back(st_rays.top().idx);\n\t\tst_rays.pop();\n\t}\n\tstd::sort(alives.begin(), alives.end());\n\tstd::vector<int>::iterator ait = alives.begin();\n\tfor (; ait != alives.end(); ++ait) {\n\t\t_o << *ait << \" \";\n\t}\n\t_o << _l;\n\treturn;\n}\n\nvoid testUnionFind();\n\nint main(int argc, char** argv) {\n\tstd::ios_base::sync_with_stdio(false);\n\tif (argc > 1) {\n\t\tstd::string str(\"C:\\\\M.K.S.H\\\\ETH\\\\AlgoLab\\\\week6\\\\potw\\\\motorcycles\\\\\");\n\t\tstr += std::string(argv[1]) + \".in\";\n\t\tfreopen(str.c_str(), \"r\", stdin);\n\t}\n\telse freopen(\"C:\\\\M.K.S.H\\\\ETH\\\\AlgoLab\\\\week6\\\\potw\\\\motorcycles\\\\test1.in\", \"r\", stdin);\n\tfreopen(\"C:\\\\M.K.S.H\\\\ETH\\\\AlgoLab\\\\week6\\\\potw\\\\motorcycles\\\\out_my.out\", \"w\", stdout);\n\tfreopen(\"C:\\\\M.K.S.H\\\\ETH\\\\AlgoLab\\\\week6\\\\potw\\\\motorcycles\\\\err_my.out\", \"w\", stderr);\n\tint t;\n\t_i >> t;\n\twhile (t--) {\n\t\tMotorcycles();\n\t}\n\treturn 0;\n}\n\nvoid testUnionFind() {\n\tUnionFind uf(9);\n\tuf.unionSets(1, 3);\n\tuf.unionSets(1, 9);\n\tuf.unionSets(5, 6);\n\tuf.unionSets(8, 9);\n\tuf.unionSets(7, 8);\n\tuf.unionSets(5, 8);\n\t_e << uf.toString() << _l;\n\treturn;\n}\n\n// Week 8: Germs / 100 pts\n// Nearest neighbor\nvoid Germs(int n) {\n\ttypedef CGAL::Triangulation_vertex_base_with_info_2<int, IK>\tVb;\n\ttypedef CGAL::Triangulation_data_structure_2<Vb>\tTds;\n\ttypedef CGAL::Delaunay_triangulation_2<IK, Tds>\t\tDelaunay;\n\ttypedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\n\ttypedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\n\ttypedef Delaunay::Finite_vertices_iterator\tVertex_iterator;\n\ttypedef Delaunay::Vertex_handle\t\tVertex_handle;\n\ttypedef Delaunay::Point\t\t\t\tDPt;\n\ttypedef Delaunay::Vertex_circulator Vertex_circulator;\n\n\tint l, b, r, t;\n\t_i >> l >> b >> r >> t;\n\n\tstd::vector< std::pair<Pt, int> > pts(n);\n\tstd::vector<lint> mind2(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tint x, y;\n\t\t_i >> x >> y;\n\t\tlint dl = std::abs(x - l);\n\t\tlint dr = std::abs(x - r);\n\t\tlint db = std::abs(y - b);\n\t\tlint dt = std::abs(y - t);\n\t\tlint md = std::min(std::min(dl, dr), std::min(db, dt));\n\t\tmind2[i] = md*md * 4;\n\t\tpts[i] = std::make_pair(Pt(x, y), i);\n\t}\n\tlint fd2, md2, ld2;\n\tif (n > 1) {\n\t\tDelaunay D;\n\t\tD.insert(pts.begin(), pts.end());\n\n\t\tVertex_iterator vit = D.finite_vertices_begin(), vend = D.finite_vertices_end();\n\t\tfor (; vit != vend; ++vit) {\n\t\t\tint uind = vit->info();\n\t\t\tPt up = vit->point();\n\t\t\tlint md2 = mind2[uind];\n\t\t\tVertex_circulator vc(D.incident_vertices(vit)), done(vc);\n\t\t\tdo {\n\t\t\t\tif (D.is_infinite(vc)) continue;\n\t\t\t\tPt vp = vc->point();\n\t\t\t\tlint d2 = CGAL::squared_distance(vp, up);\n\t\t\t\tmd2 = std::min(d2, md2);\n\t\t\t} while (++vc != done);\n\t\t\tmind2[uind] = md2;\n\t\t}\n\t\tstd::sort(mind2.begin(), mind2.end());\n\t}\n\n\tfd2 = mind2[0], md2 = mind2[n / 2], ld2 = mind2[n - 1];\n\tdouble tf = std::sqrt((std::sqrt(fd2) - 1) / 2);\n\tdouble tm = std::sqrt((std::sqrt(md2) - 1) / 2);\n\tdouble tl = std::sqrt((std::sqrt(ld2) - 1) / 2);\n\tint tfi = std::ceil(tf);\n\tint tmi = std::ceil(tm);\n\tint tli = std::ceil(tl);\n\t_o << tfi << \" \" << tmi << \" \" << tli << _l;\n\treturn;\n\n}\n\n\n\n// Week 8: H1N1 / incorrect 100pts?\n// Find the maximum width of the path from outside to the vertex\nvoid H1N1(int n) {\n\t// Boost\n\ttypedef boost::adjacency_list < boost::vecS, boost::vecS, boost::undirectedS,\n\t\tboost::no_property, boost::property < boost::edge_weight_t, long > > Graph;\n\ttypedef boost::property_map < Graph, boost::edge_weight_t >::type WeightMap;\n\ttypedef boost::graph_traits < Graph >::edge_descriptor Edge;\n\ttypedef boost::graph_traits < Graph >::edge_iterator EdgeIt;\n\ttypedef boost::graph_traits < Graph >::out_edge_iterator OutEdgeIt;\n\ttypedef boost::graph_traits < Graph >::vertex_descriptor Vertex;\n\t// CGAL\n\ttypedef CGAL::Triangulation_vertex_base_2<IK>\tVb;\n\ttypedef CGAL::Triangulation_face_base_with_info_2<int, IK>\tFb;\n\ttypedef CGAL::Triangulation_data_structure_2<Vb, Fb>\tTds;\n\ttypedef CGAL::Delaunay_triangulation_2<IK, Tds>\t\tDelaunay;\n\ttypedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\n\ttypedef Delaunay::Face_handle\t\t\t\tFace_handle;\n\ttypedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\n\ttypedef Delaunay::Edge_circulator\t\t\tEdge_circulator;\n\ttypedef Delaunay::Finite_vertices_iterator\tVertex_iterator;\n\ttypedef Delaunay::Vertex_handle\t\t\t\tVertex_handle;\n\ttypedef Delaunay::Point\t\t\t\t\t\tDPt;\n\ttypedef Delaunay::Vertex_circulator\t\t\tVertex_circulator;\n\n\tint m;\n\n\tstd::vector<Pt> infected(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tint x, y;\n\t\t_i >> x >> y;\n\t\tinfected[i] = Pt(x, y);\n\t}\n\tDelaunay D;\n\tD.insert(infected.begin(), infected.end());\n\n\tGraph G(1); // only infinite face\n\tWeightMap wmap = boost::get(boost::edge_weight, G); // weight = width^2 = r^2*4\n\tint newind = 1; // gradually add faces\n\n\tFace_iterator fit = D.finite_faces_begin(), fend = D.finite_faces_end();\n\tfor (; fit != fend; ++fit) {\n\t\tfit->info() = 0; // or it could be anything\n\t}\n\n\tfit = D.finite_faces_begin(), fend = D.finite_faces_end();\n\tfor (; fit != fend; ++fit) {\n\t\tVertex u;\n\t\tif (!fit->info()) {\n\t\t\tu = boost::add_vertex(G);\n\t\t\tfit->info() = newind++;\n\t\t}\n\t\telse u = fit->info();\n\t\t// circulate its 3 neighbors to add edges to the graph\n\t\tfor (int nb = 0; nb < 3; nb++) {\n\t\t\tFace_handle fh = fit->neighbor(nb);\n\t\t\tif (D.is_infinite(fh)) {\n\t\t\t\t// infinite face: add edge to vertex 0\n\t\t\t\tVertex v = 0;\n\t\t\t\tEdge e; bool su;\n\t\t\t\tVertex_handle vh1 = fit->vertex(fit->cw(nb)), vh2 = fit->vertex(fit->ccw(nb));\n\t\t\t\tlint d2 = CGAL::squared_distance(vh1->point(), vh2->point());\n\t\t\t\tboost::tie(e, su) = boost::add_edge(u, v, G);\n\t\t\t\twmap[e] = d2;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//  if the face hasn't been visited, add a new vertex and fill fh->info()\n\t\t\t\tVertex v;\n\t\t\t\tif (!fh->info()) {\n\t\t\t\t\tfh->info() = newind++;\n\t\t\t\t\tv = boost::add_vertex(G);\n\t\t\t\t}\n\t\t\t\telse v = fh->info();\n\n\t\t\t\t// continue if the edge already exists\n\t\t\t\tEdge e; bool su;\n\t\t\t\tboost::tie(e, su) = boost::edge(u, v, G);\n\t\t\t\tif (su) continue;\n\n\t\t\t\tVertex_handle vh1 = fit->vertex(fit->cw(nb)), vh2 = fit->vertex(fit->ccw(nb));\n\t\t\t\tlint d2 = CGAL::squared_distance(vh1->point(), vh2->point());\n\t\t\t\tboost::tie(e, su) = boost::add_edge(u, v, G);\n\t\t\t\twmap[e] = d2;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst lint BIG = 10000000000000000;\n\ttypedef std::pair<lint, Vertex> DistV;\n\tint nv = boost::num_vertices(G);\n\tstd::vector<DistV> vdist(nv);\n\tfor (int i = 0; i < nv; i++) vdist[i] = std::make_pair(-1, i);\n\n\tstd::vector<bool> selected(nv, false); // whether the width of a vertex has been optimized\n\tstd::vector<lint> distmap(nv, -1); // the maximum width towards each vertex\n\tOutEdgeIt eit, eend;\n\tfor (boost::tie(eit, eend) = boost::out_edges(0, G); eit != eend; eit++) {\n\t\tVertex v = boost::target(*eit, G);\n\t\tvdist[v].first = std::max(vdist[v].first, (lint)wmap[*eit]);\n\t\tdistmap[v] = std::max(distmap[v], (lint)wmap[*eit]);\n\t}\n\tvdist[0].first = 0;\n\n\n\t_e << \"BFS \" << _l;\n\t// BFS for max min edge\n\tstd::priority_queue < DistV > pq(vdist.begin(), vdist.end());\n\tselected[0] = true;\n\tdistmap[0] = BIG;\n\twhile (!pq.empty()) {\n\t\tDistV dv = pq.top();\n\t\tpq.pop();\n\t\tlint d = dv.first;\n\t\tVertex u = dv.second;\n\t\tif (selected[u]) continue; // see the pq.push() below, one vertex could be pushed multiple times\n\t\tOutEdgeIt eit, eend;\n\t\tfor (boost::tie(eit, eend) = boost::out_edges(u, G); eit != eend; eit++)\n\t\t{\n\t\t\tVertex v = boost::target(*eit, G);\n\t\t\tif (!selected[v]) {\n\t\t\t\t// the updating rule: d[v] = max(d[v], min(w[e], d[u]))\n\t\t\t\tlint curw = std::max((long)distmap[v], std::min(wmap[*eit], (long)distmap[u]));\n\t\t\t\tdistmap[v] = curw;\n\t\t\t\tpq.push(std::make_pair(distmap[v], v));\n\t\t\t}\n\t\t}\n\t\tselected[u] = true;\n\t}\n\n\t_i >> m;\n\tfor (int j = 0; j < m; j++) {\n\t\tint x, y; lint r2;\n\t\t_i >> x >> y >> r2;\n\t\tPt person(x, y);\n\t\tVertex_handle vh = D.nearest_vertex(person);\n\t\tif (CGAL::squared_distance(person, vh->point()) < r2) {\n\t\t\t_o << \"n\"; continue;\n\t\t}\n\t\tFace_handle fh = D.locate(person);\n\t\tif (D.is_infinite(fh)) {\n\t\t\t_o << \"y\"; continue;\n\t\t}\n\t\tVertex u = fh->info();\n\t\tif (r2 * 4 > distmap[u]) _o << \"n\";\n\t\telse _o << \"y\";\n\t}\n\t_o << _l;\n}\n\n\n\n// Week 8: Graypes / 50->50->50->100\n// Delaunay, find shortest edge\n// Use Vertex_iterator to iterate through the vertices -> O(1)\n// rather than nearest_vertex() -> O(log n)\n// Tho I didn't they would kill an O(nlogn) algo..\n// Don't play with constant when there is a method to improve asymptotic\nvoid Graypes(int n) {\n\ttypedef CGAL::Triangulation_vertex_base_with_info_2<int, IK>\tVb;\n\ttypedef CGAL::Triangulation_data_structure_2<Vb>\tTds;\n\ttypedef CGAL::Delaunay_triangulation_2<IK, Tds>\t\tDelaunay;\n\ttypedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\n\ttypedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\n\ttypedef Delaunay::Finite_vertices_iterator\tVertex_iterator;\n\ttypedef Delaunay::Vertex_handle\t\tVertex_handle;\n\ttypedef Delaunay::Point\t\t\t\tDPt;\n\ttypedef Delaunay::Vertex_circulator Vertex_circulator;\n\n\n\tstd::vector< std::pair<Pt, int> > apes(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tint x, y;\n\t\t_i >> x >> y;\n\t\tapes[i] = std::make_pair(Pt(x, y), i);\n\t}\n\t//std::random_shuffle(apes.begin(), apes.end());\n\n\tDelaunay D;\n\tD.insert(apes.begin(), apes.end());\n\n\tconst lint BIG = 10000000000000000;\n\t//std::vector<int> runto(n, -1);\n\t//std::vector<lint> d2runto(n, BIG);\n\tlint totalmind2 = BIG;\n\n\tVertex_iterator vit = D.finite_vertices_begin(), vend = D.finite_vertices_end();\n\tfor (; vit != vend; ++vit) {\n\t\tPt p = vit->point();\n\n\t\tVertex_circulator vc = D.incident_vertices(vit), done(vc);\n\t\tdo {\n\t\t\tif (D.is_infinite(vc))continue;\n\t\t\tPt q = vc->point();\n\t\t\tlint d2pq = CGAL::squared_distance(p, q);\n\t\t\ttotalmind2 = std::min(totalmind2, d2pq);\n\t\t} while (++vc != done);\n\t}\n\n\t/* O(nlogn) because of nearest_vertex()\n\tfor (int i = 0; i < n; i++) {\n\t//lint mind2 = d2runto[i];\n\t//int prunto = runto[i];\n\tlint mind2 = BIG;\n\tPt p = apes[i].first;\n\tint pind = apes[i].second;\n\tVertex_handle vh = D.nearest_vertex(p);\n\tVertex_circulator vc = D.incident_vertices(vh), done(vc);\n\tdo {\n\tif (D.is_infinite(vc)) continue;\n\tPt q = vc->point();\n\tint qind = vc->info();\n\tif (qind < pind) continue;\n\tlint d2pq = CGAL::squared_distance(p, q);\n\tif (d2pq < mind2) {\n\tmind2 = d2pq;\n\t//prunto = qind;\n\t}\n\t//else if (d2pq == mind2) {\n\t//\tPt prevbest = apes[prunto].first;\n\t//\tif (q.x() < prevbest.x() || (q.x() == prevbest.x() && q.y() < prevbest.y())) {\n\t//\t\tprunto = qind;\n\t//\t}\n\t//}\n\t} while (++vc != done);\n\t//if (prunto != runto[i]) {\n\t//\trunto[i] = prunto;\n\t//\td2runto[i] = mind2;\n\t//\tif (mind2 < d2runto[prunto]) {\n\t//\t\trunto[prunto] = i;\n\t//\t\td2runto[prunto] = mind2;\n\t//\t}\n\t//\telse if (mind2 == d2runto[prunto]) {\n\t//\t\tPt p2 = apes[runto[prunto]].first;\n\t//\t\tif (p.x() < p2.x() || (p.x() == p2.x() && p.y() < p2.y())) {\n\t//\t\t\trunto[prunto] = i;\n\t//\t\t}\n\t//\t}\n\t//}\n\ttotalmind2 = std::min(totalmind2, mind2);\n\t}\n\t*/\n\n\tlint time = std::ceil(50 * std::sqrt((double)(totalmind2)));\n\t_o << time << _l;\n\treturn;\n}\n\n\n\n// Week 11 PotW: Sith / 25->50->100pts\n// Delaunay + find connected components\n// Update connected components: Union Find\nint calcBiggestComponent(const std::vector<int>& comp, int ncomp) {\n\tint n = comp.size();\n\tstd::vector<int> counter(ncomp);\n\tfor (int i = 0; i < n; i++) {\n\t\tcounter[comp[i]]++;\n\t}\n\tint largest = 0;\n\tfor (int j = 0; j < ncomp; j++) {\n\t\tlargest = std::max(largest, counter[j]);\n\t}\n\treturn largest;\n}\nvoid Comp2Par(const std::vector<int>& comp, int ncomp, std::vector<int>& par) {\n\tint n = comp.size();\n\tstd::vector<int> first(ncomp, -1);\n\tfor (int i = 0; i < n; i++) {\n\t\tif (first[comp[i]] == -1)\n\t\t\tfirst[comp[i]] = i;\n\t\tpar[i] = first[comp[i]];\n\t}\n}\nvoid Sith() {\n\ttypedef CGAL::Triangulation_vertex_base_with_info_2<int, IK>\tVb;\n\ttypedef CGAL::Triangulation_data_structure_2<Vb>\tTds;\n\ttypedef CGAL::Delaunay_triangulation_2<IK, Tds>\t\tDelaunay;\n\ttypedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\n\ttypedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\n\ttypedef Delaunay::Finite_vertices_iterator\tVertex_iterator;\n\ttypedef Delaunay::Vertex_handle\t\tVertex_handle;\n\ttypedef Delaunay::Point\t\t\t\tDPt;\n\ttypedef Delaunay::Vertex_circulator Vertex_circulator;\n\n\ttypedef boost::adjacency_list < boost::vecS, boost::vecS, boost::undirectedS,\n\t\tboost::no_property, boost::property < boost::edge_weight_t, double > > Graph;\n\ttypedef boost::property_map < Graph, boost::edge_weight_t >::type WeightMap;\n\ttypedef boost::graph_traits < Graph >::edge_descriptor Edge;\n\ttypedef boost::graph_traits < Graph >::vertex_descriptor Vertex;\n\n\tint n, r;\n\t_i >> n >> r;\n\t_e << \"testcase: \" << n << \" \" << r << _l;\n\tlint r2 = (lint)r*r;\n\tstd::vector< std::pair<Pt, int> > p(n);\n\t// invert the input\n\t// so I choose planets [0, k) rather than [k, end)\n\tfor (int i = 0; i < n; i++) {\n\t\tint x, y;\n\t\t_i >> x >> y;\n\t\tp[n - 1 - i] = std::make_pair(Pt(x, y), n - 1 - i);\n\t}\n\n\tDelaunay D;\n\tint nv = n / 2;\n\tD.insert(p.begin(), p.begin() + nv);\n\tGraph G(nv);\n\tfor (int i = 0; i < nv; i++) {\n\t\tVertex_handle vh = D.nearest_vertex(p[i].first);\n\t\tPt pt = vh->point();\n\t\tint ipt = vh->info();\n\t\tVertex_circulator vc = D.incident_vertices(vh), done(vc);\n\t\tdo {\n\t\t\tif (D.is_infinite(vc)) continue;\n\t\t\tPt pin = vc->point();\n\t\t\tint ipin = vc->info();\n\t\t\tif (ipin < ipt) continue; // i --> j, add edge when i < j\n\t\t\tlint d2 = CGAL::squared_distance(pt, pin);\n\t\t\tif (d2 <= r2) {\n\t\t\t\tboost::add_edge(ipt, ipin, G);\n\t\t\t}\n\t\t} while (++vc != done);\n\t}\n\n\tstd::vector<int> comp(nv), par(nv);\n\tint ncomp = boost::connected_components(G, &comp[0]);\n\tint biggestComp = calcBiggestComponent(comp, ncomp);\n\tComp2Par(comp, ncomp, par);\n\tUnionFind uf(par);\n\n\tfor (int last = nv; last < n; last++) {\n\t\tint largestPossible = n - last - 1;\n\t\tif (biggestComp >= largestPossible) break;\n\t\tVertex vlast = boost::add_vertex(G);\n\t\tPt plast = p[last].first; // p[last].second == last\n\t\tD.insert(p.begin() + last, p.begin() + last + 1);\n\t\tint ipt = last;\n\t\tVertex_handle vh = D.nearest_vertex(plast);\n\t\tVertex_circulator vc = D.incident_vertices(vh), done(vc);\n\t\tuf.append();\n\t\tdo {\n\t\t\tif (D.is_infinite(vc)) continue;\n\t\t\tPt pin = vc->point();\n\t\t\tint ipin = vc->info();\n\t\t\tlint d2 = CGAL::squared_distance(plast, pin);\n\t\t\tif (d2 <= r2) {\n\t\t\t\tboost::add_edge(ipt, ipin, G);\n\t\t\t\tuf.unionSets(ipt, ipin);\n\t\t\t}\n\t\t} while (++vc != done);\n\n\t\t//std::vector<int> ccomp(last+1);\n\t\t//int nccomp = boost::connected_components(G, &ccomp[0]);\n\t\t//int largest = calcBiggestComponent(ccomp, nccomp);\n\t\tint largest = uf.getMaxSize();\n\t\tlargest = std::min(largest, largestPossible);\n\t\tbiggestComp = std::max(biggestComp, largest);\n\t}\n\t_e << \"result: \" << biggestComp << _l;\n\t_o << biggestComp << _l;\n\treturn;\n\n}\n\n\n\n// Week 12: Radiation / 60->80->100\n// LP + bin_search?? 2^300??\n// LP (with Gmpz not Gmpq) + exp_search+bin_search\n// they are exact number types and don't worry about 2^300\nstruct PolyTerm {\n\tint xd;\n\tint yd;\n\tint zd;\n\tint idx;\n\tPolyTerm(int x = 0, int y = 0, int z = 0, int idx = 0) :xd(x), yd(y), zd(z), idx(idx) {}\n};\nvoid calcPolyTerm(int deg, std::vector<PolyTerm> &terms) {\n\t//int balls = deg + 2;\n\tterms.clear();\n\tint idx = 0;\n\tint d = deg;\n\tfor (int d = 0; d <= deg; d++) {\n\t\tint balls = d + 2;\n\t\tfor (int i = 0; i < balls - 1; i++) {\n\t\t\tfor (int j = i + 1; j < balls; j++) {\n\t\t\t\tPolyTerm pt(i, j - i - 1, d + 1 - j, idx);\n\t\t\t\tterms.push_back(pt);\n\t\t\t\tidx++;\n\t\t\t}\n\t\t}\n\t}\n\treturn;\n}\ntypedef CGAL::Gmpz ETZ;\ntypedef CGAL::Quadratic_program<ETZ> ProgramZ;\ntypedef CGAL::Quadratic_program_solution<ETZ> SolutionZ;\nETZ findPoly(int deg, std::vector<Pt3> &hcell, std::vector<Pt3> &tcell, std::vector< std::vector<ETZ> >& hpowers, std::vector< std::vector<ETZ> >& tpowers) {\n\n\tProgramZ lp(CGAL::SMALLER, false, 0, false, 0);\n\tstd::vector<PolyTerm> terms;\n\tcalcPolyTerm(deg, terms);\n\n\tint h = hcell.size(), t = tcell.size();\n\tint nterms = terms.size();\n\tconst int delta = nterms;\n\tfor (int j = 0; j < nterms; j++) {\n\t\t//lp.set_c(j, 1);\n\t\tint xind = terms[j].xd, yind = 31 + terms[j].yd, zind = 62 + terms[j].zd;\n\t\tfor (int i = 0; i < h; i++) {\n\t\t\tETZ xyz = hpowers[i][xind] * hpowers[i][yind] * hpowers[i][zind];\n\t\t\tlp.set_a(j, i, xyz);\n\t\t}\n\t\tfor (int i = 0; i < t; i++) {\n\t\t\tETZ xyz = tpowers[i][xind] * tpowers[i][yind] * tpowers[i][zind];\n\t\t\tlp.set_a(j, h + i, -xyz);\n\t\t}\n\t}\n\tlp.set_c(delta, -1);\n\t//lp.set_l(delta, true, 0);\n\tlp.set_u(delta, true, 1);\n\tfor (int i = 0; i < h; i++) {\n\t\tlp.set_b(i, 0);\n\t\tlp.set_a(delta, i, 0);\n\t}\n\tfor (int i = 0; i < t; i++) {\n\t\tlp.set_a(delta, h + i, 1);\n\t\tlp.set_b(h + i, 0);\n\t}\n\n\tSolutionZ s = CGAL::solve_linear_program(lp, ETZ());\n\t//if (s.is_optimal() && s.objective_value() < 0)\n\t//\treturn true;\n\t//return false;\n\tETZ result = s.objective_value().numerator() / s.objective_value().denominator();\n\treturn result;\n}\nvoid calcPowers(std::vector<Pt3> & cell, std::vector< std::vector<ETZ> >& powers) {\n\tint n = cell.size();\n\t_e << \"powers!\" << _l;\n\tfor (int i = 0; i < n; i++) {\n\t\tpowers[i] = std::vector<ETZ>(93);\n\t\tETZ xp(1), yp(1), zp(1);\n\t\tint cx = (int)cell[i].x();\n\t\tint cy = (int)cell[i].y();\n\t\tint cz = (int)cell[i].z();\n\t\tfor (int d = 0; d <= 30; d++) {\n\t\t\tpowers[i][d] = xp;\n\t\t\tpowers[i][31 + d] = yp;\n\t\t\tpowers[i][62 + d] = zp;\n\t\t\tif (d == 30) break;\n\t\t\txp *= cx;\n\t\t\typ *= cy;\n\t\t\tzp *= cz;\n\t\t\t//_e << xp << \" \" << yp << \" \" << zp << _l;\n\t\t}\n\t}\n}\nvoid Radiation() {\n\tint h, t; _i >> h >> t;\n\tstd::vector<Pt3> hcell(h), tcell(t);\n\tfor (int i = 0; i < h; i++) {\n\t\tint x, y, z; _i >> x >> y >> z;\n\t\thcell[i] = Pt3(x, y, z);\n\t\t//_e << hcell[i] << _l;\n\t}\n\tfor (int j = 0; j < t; j++) {\n\t\tint x, y, z; _i >> x >> y >> z;\n\t\ttcell[j] = Pt3(x, y, z);\n\t\t//_e << tcell[j] << _l;\n\t}\n\tif (h == 0 || t == 0) {\n\t\t_o << 0 << _l;\n\t\treturn;\n\t}\n\n\tstd::vector< std::vector<ETZ> > hpowers(h), tpowers(t);\n\tcalcPowers(hcell, hpowers);\n\tcalcPowers(tcell, tpowers);\n\t_e << \"calcpowers!\" << _l;\n\n\t//std::vector<bool> canFinds(31, false);\n\tstd::vector<ETZ> res(31, 0);\n\tint st = 0, ed = 1;\n\tint low, up, mid;\n\twhile (true) {\n\t\t_e << \"d=\" << ed << _l;\n\t\t//canFinds[ed] = canFindPoly(ed, hcell, tcell, hpowers, tpowers);\n\t\tres[ed] = findPoly(ed, hcell, tcell, hpowers, tpowers);\n\t\tif (res[ed] < 0) {\n\t\t\tlow = st;\n\t\t\tup = ed;\n\t\t\tmid = (low + up) / 2;\n\t\t\tbreak;\n\t\t}\n\t\telse {\n\t\t\tif (ed == 30) {\n\t\t\t\t_o << \"Impossible!\\n\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tst = ed;\n\t\t\ted = std::min(30, ed * 2);\n\t\t}\n\t}\n\n\t// binary search\n\twhile (true) {\n\t\t_e << \"d=\" << mid << _l;\n\t\tif (up - low <= 1) {\n\t\t\tif (res[low]<0 || findPoly(low, hcell, tcell, hpowers, tpowers)<0) {\n\t\t\t\t_o << low << _l;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (res[up]<0 || findPoly(up, hcell, tcell, hpowers, tpowers)<0) {\n\t\t\t\t_o << up << _l;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tres[mid] = findPoly(mid, hcell, tcell, hpowers, tpowers);\n\t\tif (res[mid]<0) {\n\t\t\tup = mid;\n\t\t\tmid = (low + up) / 2;\n\t\t}\n\t\telse {\n\t\t\tlow = mid + 1;\n\t\t\tmid = (low + up) / 2;\n\t\t}\n\t}\n\n\t_e << _l;\n\t_o << \"Impossible!\" << _l;\n\treturn;\n\n}\n\n\n\n// Week 13: Clues / 100pts\n// Delaunay + is_bipartite + connected_components\nvoid Clues() {\n\ttypedef CGAL::Triangulation_vertex_base_with_info_2<int, IK>\tVb;\n\ttypedef CGAL::Triangulation_data_structure_2<Vb>\tTds;\n\ttypedef CGAL::Delaunay_triangulation_2<IK, Tds>\t\tDelaunay;\n\ttypedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\n\ttypedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\n\ttypedef Delaunay::Finite_vertices_iterator\tVertex_iterator;\n\ttypedef Delaunay::Vertex_handle\t\tVertex_handle;\n\ttypedef Delaunay::Point\t\t\t\tDPt;\n\ttypedef Delaunay::Vertex_circulator Vertex_circulator;\n\n\ttypedef boost::adjacency_list < boost::vecS, boost::vecS, boost::undirectedS,\n\t\tboost::no_property, boost::property < boost::edge_weight_t, double > > Graph;\n\ttypedef boost::property_map < Graph, boost::edge_weight_t >::type WeightMap;\n\ttypedef boost::graph_traits < Graph >::edge_descriptor Edge;\n\ttypedef boost::graph_traits < Graph >::vertex_descriptor Vertex;\n\n\n\tint n, m, r;\n\t_i >> n >> m >> r;\n\tlint r2 = (lint)r*r;\n\tstd::vector< std::pair<Pt, int> > stations(n);\n\tstd::vector< std::pair<Pt, Pt> > clues(m);\n\tfor (int i = 0; i < n; i++) {\n\t\tint x, y; _i >> x >> y;\n\t\tstations[i] = std::make_pair(Pt(x, y), i);\n\t}\n\tfor (int j = 0; j < m; j++) {\n\t\tint xa, ya, xb, yb; _i >> xa >> ya >> xb >> yb;\n\t\tclues[j] = std::make_pair(Pt(xa, ya), Pt(xb, yb));\n\t}\n\n\tGraph G(n);\n\tstd::vector<int> components(n);\n\n\tDelaunay D;\n\tD.insert(stations.begin(), stations.end());\n\tVertex_iterator vit;\n\tbool violated = false;\n\tfor (vit = D.finite_vertices_begin(); vit != D.finite_vertices_end(); ++vit) {\n\t\tVertex_circulator vc = D.incident_vertices(vit), done(vc);\n\t\tint idx = vit->info();\n\t\tstd::vector< std::pair<Pt, int> > candidates;\n\t\tcandidates.push_back(std::make_pair(vit->point(), vit->info()));\n\t\tdo {\n\t\t\tif (!D.is_infinite(vc)) {\n\t\t\t\tint vcidx = vc->info();\n\t\t\t\t//if (vcidx < idx) continue;\n\t\t\t\tif (CGAL::squared_distance(vc->point(), vit->point()) > r2) continue;\n\t\t\t\t//boost::add_edge(idx, vcidx, G);\n\t\t\t\tcandidates.push_back(std::make_pair(vc->point(), vcidx));\n\t\t\t}\n\t\t} while (++vc != done);\n\t\tint ncand = candidates.size();\n\t\tfor (int i = 1; i < ncand; i++) {\n\t\t\tPt pi = candidates[i].first;\n\t\t\tfor (int j = i + 1; j < ncand; j++) {\n\t\t\t\tPt pj = candidates[j].first;\n\t\t\t\tif (CGAL::squared_distance(pi, pj) <= r2) {\n\t\t\t\t\tviolated = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (violated) break;\n\t\tfor (int j = 1; j < ncand; j++) {\n\t\t\tint idxj = candidates[j].second;\n\t\t\tboost::add_edge(idx, idxj, G);\n\t\t}\n\t}\n\n\tif (violated) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\t_o << \"n\";\n\t\t}\n\t\t_o << _l;\n\t\t_e << \"violated\" << _l;\n\t\treturn;\n\t}\n\n\tbool isBipartite = boost::is_bipartite(G);\n\tif (!isBipartite) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\t_o << \"n\";\n\t\t}\n\t\t_o << _l;\n\t\t_e << \"n\" << _l;\n\t\treturn;\n\t}\n\n\tboost::connected_components(G, &components[0]);\n\tfor (int i = 0; i < n; i++) {\n\t\t_e << components[i] << \" \";\n\t}_e << _l;\n\tfor (int j = 0; j < m; j++) {\n\t\tPt a = clues[j].first, b = clues[j].second;\n\t\tif (CGAL::squared_distance(a, b) <= r2) {\n\t\t\t_o << \"y\";\n\t\t\tcontinue;\n\t\t}\n\t\tVertex_handle vha = D.nearest_vertex(a);\n\t\tVertex_handle vhb = D.nearest_vertex(b);\n\t\t// not reachable to any station\n\t\tif (CGAL::squared_distance(vha->point(), a) > r2\n\t\t\t|| CGAL::squared_distance(vhb->point(), b) > r2) {\n\t\t\t_o << \"n\";\n\t\t\tcontinue;\n\t\t}\n\t\t// not in the same component\n\t\tint idxa = vha->info(), idxb = vhb->info();\n\t\tif (components[idxa] == components[idxb]) {\n\t\t\t_o << \"y\";\n\t\t\t//_e << vha->point() << \"|\" << vhb->point() << _l;\n\t\t\t//_e << components[idxa] << \" \" << components[idxb] << _l;\n\t\t}\n\t\telse _o << \"n\";\n\t}\n\t_o << _l;\n\treturn;\n\n}\n\n\n\n// Week 13: Goldfinger / 100 pts\n// LP + Delaunay + bin_search\ntypedef CGAL::Delaunay_triangulation_2<IK>\t\tDelaunay;\ntypedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\ntypedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\ntypedef Delaunay::Vertex_handle\t\tVertex_handle;\ntypedef Delaunay::Point\t\tDPt;\nbool isSolvable(int a, std::vector<Pt> &psensor, std::vector<int> &esensor,\n\t\tstd::vector<Pt> &pmpe, std::vector<lint> &r2mpe, int Imax, std::vector< std::vector<lint> >& d2) {\n\tint n = psensor.size();\n\tint m = pmpe.size();\n\tbool isRestricted = r2mpe[0] > 0;\n\n\tProgram lp(CGAL::LARGER, true, 0, false);\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < a; j++) {\n\t\t\t//lint d2 = CGAL::squared_distance(pmpe[j], psensor[i]);\n\t\t\tif (!isRestricted || d2[i][j] < r2mpe[j])\n\t\t\t\tlp.set_a(j, i, (ET)1 / d2[i][j]);\n\t\t}\n\t\tlp.set_b(i, esensor[i]);\n\t}\n\tfor (int j = 0; j < a; j++) {\n\t\tlp.set_a(j, n, -1);\n\t\tlp.set_c(j, 1);\n\t}\n\tlp.set_b(n, -Imax);\n\n\tSolution s = CGAL::solve_linear_program(lp, ET());\n\tif (s.is_optimal()) {\n\t\t//_o << a << _l;\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n\n}\nvoid Goldfinger() {\n\tint n, m, h, Imax;\n\t_i >> n >> m >> h >> Imax;\n\tstd::vector<Pt> psensor(n);\n\tstd::vector<Pt> pmpe(m);\n\tstd::vector<Pt> phench(h);\n\tstd::vector<int> esensor(n);\n\tlint BIG = (1 << 55);\n\tstd::vector<lint> r2mpe(m, -1);\n\tstd::vector< std::vector<lint> > d2(n);\n\n\tfor (int i = 0; i < n; i++) {\n\t\tint x, y, e; _i >> x >> y >> e;\n\t\tpsensor[i] = Pt(x, y);\n\t\tesensor[i] = e;\n\t}\n\tfor (int j = 0; j < m; j++) {\n\t\tint x, y; _i >> x >> y;\n\t\tpmpe[j] = Pt(x, y);\n\t}\n\tfor (int k = 0; k < h; k++) {\n\t\tint x, y; _i >> x >> y;\n\t\tphench[k] = Pt(x, y);\n\t}\n\n\n\tDelaunay D;\n\tD.insert(phench.begin(), phench.end());\n\tif (h > 0) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tVertex_handle vh = D.nearest_vertex(pmpe[j]);\n\t\t\tr2mpe[j] = CGAL::squared_distance(vh->point(), pmpe[j]);\n\t\t}\n\t}\n\n\tfor (int i = 0; i < n; i++) {\n\t\td2[i] = std::vector<lint>(m);\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\td2[i][j] = CGAL::squared_distance(psensor[i], pmpe[j]);\n\t\t}\n\t}\n\n\tif (isSolvable(1, psensor, esensor, pmpe, r2mpe, Imax, d2)) {\n\t\t_o << 1 << _l;\n\t\treturn;\n\t}\n\n\t\n\t// exp. search for an interval\n\tstd::vector<int> solvables(m + 1, 0); // 0 = not touched, 1 = solvable, -1 = unsolvable\n\t\t\t\t\t\t\t\t\t\t  //solvables[m] = 1; \n\tsolvables[1] = -1;\n\tint st = 1, end = 2;\n\twhile (end <= m) {\n\t\t_e << \"end=\" << end << _l;\n\t\tif (solvables[end] == 1 || isSolvable(end, psensor, esensor, pmpe, r2mpe, Imax, d2)) {\n\t\t\tsolvables[end] = 1;\n\t\t\tbreak;\n\t\t}\n\t\telse {\n\t\t\tsolvables[end] = -1;\n\t\t\tif (end == m) break;\n\t\t\tst = end;\n\t\t\tend = std::min(end * 2, m);\n\t\t}\n\t}\n\tif (solvables[m] == -1) {\n\t\t_o << \"impossible\" << _l;\n\t\treturn;\n\t}\n\n\t// binary search for the best\n\tint low = st, up = end, a = (low + up) / 2;\n\twhile (true) {\n\t\t_e << \"a=\" << a << _l;\n\t\tif (up - low <= 1) {\n\t\t\tif (solvables[low] == 1 || isSolvable(low, psensor, esensor, pmpe, r2mpe, Imax, d2)) {\n\t\t\t\t_o << low << _l;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (solvables[up] == 1 || isSolvable(up, psensor, esensor, pmpe, r2mpe, Imax, d2)) {\n\t\t\t\t_o << up << _l;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbreak; // impossible\n\t\t}\n\n\t\tbool solvable = isSolvable(a, psensor, esensor, pmpe, r2mpe, Imax, d2);\n\t\tif (solvable) {\n\t\t\tsolvables[a] = 1;\n\t\t\tup = a;\n\t\t\ta = (low + up) / 2;\n\t\t}\n\t\telse {\n\t\t\tsolvables[a] = -1;\n\t\t\tlow = a;\n\t\t\ta = (low + up) / 2;\n\t\t}\n\n\t}\n\n\t_o << \"impossible\" << _l;\n\treturn;\n\n}\n\n\n\n// Week 3: First Hit / 99->100\n// For 5555 pts total!\n// OMG really?? random shuffle??\ndouble floor_to_double_EK(const EK::FT& x)\n{\n\tdouble a = std::floor(CGAL::to_double(x));\n\twhile (a > x) a -= 1;\n\twhile (a + 1 <= x) a += 1;\n\treturn a;\n}\nvoid FirstHit(int n) {\n\n\tlint x, y, a, b, r, s, t, u;\n\tstd::cin >> x >> y >> a >> b;\n\tIK::Point_2 p1(x, y), p2(a, b);\n\tIK::Ray_2 ray(p1, p2);\n\tEK::Point_2 ep1((double)x, (double)y), ep2((double)a, (double)b);\n\tEK::Ray_2 eray(ep1, ep2);\n\tEK::Segment_2 eseg;\n\n\tbool ishit = false;\n\tEK::FT minsqd = 5e100;\n\tEK::Point_2 minits(0, 0), curits(0, 0);\n\n\tstd::vector<EK::Segment_2> esegs(n);\n\tfor (int i = 0; i < n; i++) {\n\t\t_i >> r >> s >> t >> u;\n\t\tEK::Point_2 eq1((double)r, (double)s), eq2((double)t, (double)u);\n\t\tEK::Segment_2 esegq(eq1, eq2);\n\t\tesegs[i] = esegq;\n\t}\n\tstd::random_shuffle(esegs.begin(), esegs.end());\n\n\tfor (int i = 0; i < n; i++) {\n\t\tEK::Segment_2 esegq = esegs[i];\n\t\tEK::Point_2 eq1 = esegq.start(), eq2 = esegq.end();\n\t\tif (ishit) {\n\t\t\tif (CGAL::do_intersect(eseg, esegq)) {\n\t\t\t\tauto result = CGAL::intersection(eseg, esegq);\n\n\t\t\t\tif (const EK::Segment_2* sp = boost::get<EK::Segment_2>(&*result)) {\n\t\t\t\t\t_e << \"segment\" << _l;\n\t\t\t\t\tEK::FT sqd1 = CGAL::squared_distance(ep1, eq1);\n\t\t\t\t\tEK::FT sqd2 = CGAL::squared_distance(ep1, eq2);\n\t\t\t\t\tif (sqd1 < sqd2) {\n\t\t\t\t\t\tminits = eq1;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tminits = eq2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (const EK::Point_2* pp = boost::get<EK::Point_2>(&*result)) {\n\t\t\t\t\t_e << \"point\" << _l;\n\t\t\t\t\tminits = *pp;\n\t\t\t\t}\n\t\t\t\teseg = EK::Segment_2(ep1, minits);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (CGAL::do_intersect(eray, esegq)) {\n\t\t\t\tauto result = CGAL::intersection(eray, esegq);\n\t\t\t\tif (const EK::Segment_2* sp = boost::get<EK::Segment_2>(&*result)) {\n\t\t\t\t\t_e << \"segment0\" << _l;\n\t\t\t\t\tEK::FT sqd1 = CGAL::squared_distance(ep1, eq1);\n\t\t\t\t\tEK::FT sqd2 = CGAL::squared_distance(ep1, eq2);\n\t\t\t\t\tif (sqd1 < sqd2) {\n\t\t\t\t\t\tminits = eq1;\n\t\t\t\t\t}\n\t\t\t\t\telse if (sqd2 < sqd1) {\n\t\t\t\t\t\tminits = eq2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (const EK::Point_2* pp = boost::get<EK::Point_2>(&*result)) {\n\t\t\t\t\tminits = *pp;\n\t\t\t\t}\n\t\t\t\teseg = EK::Segment_2(ep1, minits);\n\t\t\t\tishit = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!ishit) {\n\t\tstd::cout << \"no\" << std::endl;\n\t\treturn;\n\t}\n\tstd::cout << (lint)floor_to_double_EK(minits.x()) << \" \" << (lint)floor_to_double_EK(minits.y()) << std::endl;\n\n\treturn;\n}\n\n\n\n// Week 13, PotW: World Cup / 100 pts\n// LP + Triangulation\ntypedef CGAL::Delaunay_triangulation_2<IK>\t\tDelaunay;\ntypedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\ntypedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\ntypedef Delaunay::Vertex_handle\t\tVertex_handle;\ntypedef Delaunay::Point\t\tDPt;\nstruct Warehouse {\n\tPt p;\n\tint s;\n\tint a;\n\tWarehouse(int x = 0, int y = 0, int s = -1, int ac = -1) :s(s), a(ac) {\n\t\tp = Pt(x, y);\n\t}\n};\nstruct Stadium {\n\tPt p;\n\tint d;\n\tint u;\n\tStadium(int x = 0, int y = 0, int d = -1, int u = -1) :d(d), u(u) {\n\t\tp = Pt(x, y);\n\t}\n};\nstruct Contour {\n\tPt p;\n\tint r;\n\tContour(int x = 0, int y = 0, int r = 0) : r(r) {\n\t\tp = Pt(x, y);\n\t}\n};\nvoid WorldCup() {\n\tint n, m, c; _i >> n >> m >> c;\n\tstd::vector<Warehouse> whs(n);\n\tstd::vector<Stadium> sts(m);\n\tstd::vector<Contour> cts; // not initialized -- need to choose!\n\n\tstd::vector<Pt> whst;\n\tfor (int i = 0; i < n; i++) {\n\t\tint x, y, s, a; _i >> x >> y >> s >> a;\n\t\twhs[i] = Warehouse(x, y, s, a);\n\t\twhst.push_back(Pt(x, y));\n\t}\n\tfor (int j = 0; j < m; j++) {\n\t\tint x, y, d, u; _i >> x >> y >> d >> u;\n\t\tsts[j] = Stadium(x, y, d, u);\n\t\twhst.push_back(Pt(x, y));\n\t}\n\tint r[200][20] = {}, t[200][20] = {};\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\t_i >> r[i][j];\n\t\t}\n\t}\n\n\tDelaunay D;\n\tD.insert(whst.begin(), whst.end());\n\n\tfor (int k = 0; k < c; k++) {\n\t\tlint x, y, rad;\n\t\t_i >> x >> y >> rad;\n\t\tPt p(x, y);\n\t\tVertex_handle vh = D.nearest_vertex(p);\n\t\tdouble d2 = CGAL::squared_distance(p, vh->point());\n\t\tif (d2 < rad*rad) {\n\t\t\tcts.push_back(Contour(x, y, rad));\n\t\t}\n\t}\n\n\tint uc = cts.size(); // used c\n\tfor (int k = 0; k < uc; k++) {\n\t\tlint r2 = cts[k].r * cts[k].r;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (CGAL::squared_distance(whs[i].p, cts[k].p) < r2)\n\t\t\t\tfor (int j = 0; j < m; j++)\n\t\t\t\t\tt[i][j] += (CGAL::squared_distance(sts[j].p, cts[k].p) > r2);\n\t\t\telse\n\t\t\t\tfor (int j = 0; j < m; j++)\n\t\t\t\t\tt[i][j] += (CGAL::squared_distance(sts[j].p, cts[k].p) < r2);\n\t\t}\n\t}\n\n\t// form LP, n*m variables, n+m*2 constraints\n\tProgram lp(CGAL::SMALLER, true, 0, false, 0);\n\tfor (int i = 0; i < n; i++) {\n\t\tlp.set_b(i, whs[i].s);\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tlp.set_a(i*m + j, i, 1);\n\t\t}\n\t}\n\tfor (int j = 0; j < m; j++) {\n\t\tlp.set_b(n + j, -sts[j].d);\n\t\tlp.set_b(n + 2 * m + j, sts[j].d);\n\t\tlp.set_b(n + m + j, sts[j].u * 100);\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tlp.set_a(i*m + j, n + j, -1);\n\t\t\tlp.set_a(i*m + j, n + 2 * m + j, 1);\n\t\t\tlp.set_a(i*m + j, n + m + j, whs[i].a);\n\t\t}\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tint idx = i*m + j;\n\t\t\tlp.set_c(idx, -100 * r[i][j] + t[i][j]);\n\t\t}\n\t}\n\n\tSolution s = CGAL::solve_linear_program(lp, ET());\n\n\tif (s.is_optimal()) {\n\t\tET result = s.objective_value().numerator() / (100 * s.objective_value().denominator());\n\t\tlint llr = floor_to_double(-result);\n\t\t_o << llr << _l;\n\t}\n\telse {\n\t\t_o << \"RIOT!\" << _l;\n\t}\n\treturn;\n}\n\n\n\n// Week 10: Light the Stage\n// Delaunay Triangulation + binary search\ntypedef CGAL::Delaunay_triangulation_2<IK>\t\tDelaunay;\ntypedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\ntypedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\ntypedef Delaunay::Vertex_handle\t\tVertex_handle;\ntypedef Delaunay::Point\t\tDPt;\nstruct Participant {\n\tPt p;\n\tlint r;\n\tParticipant(int x = 0, int y = 0, lint r = 0) :p(Pt(x, y)), r(r) {}\n\tParticipant(Pt p, lint r = 0) :p(p), r(r) {}\n};\nvoid binarySearchLeftover(std::vector<Participant> &ps, std::vector<Pt> &lights, int h, std::vector<int> &leftover) {\n\tint m = ps.size(), n = lights.size();\n\tDelaunay D;\n\tD.clear();\n\tint start = 1, end = n - 1, mid = (start + end) / 2;\n\tstd::vector<bool> aliveAfterMid(m, true);\n\tstd::vector<int> tmpLeftOver;\n\twhile (true) {\n\t\tif (end - start <= 1) break;\n\t\tD.clear();\n\t\ttmpLeftOver.clear();\n\t\tbool alive = false;\n\t\tD.insert(lights.begin(), lights.begin() + mid);\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tVertex_handle vh = D.nearest_vertex(ps[i].p);\n\t\t\tlint d2 = CGAL::squared_distance(vh->point(), ps[i].p);\n\t\t\tif (d2 >= (ps[i].r + h)*(ps[i].r + h)) {\n\t\t\t\t// existing one living participant: update the interval\n\t\t\t\tstart = mid;\n\t\t\t\tmid = (start + end) / 2;\n\t\t\t\talive = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!alive) {\n\t\t\tend = mid - 1;\n\t\t\tmid = (start + end) / 2;\n\t\t}\n\t}\n\t_e << \"mid: \" << mid << _l;\n\tD.clear();\n\tD.insert(lights.begin(), lights.begin() + mid);\n\n\tif (mid < end) {\n\t\tstd::vector<int> endleftover;\n\t\tD.clear();\n\t\tD.insert(lights.begin(), lights.begin() + end);\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tVertex_handle vh = D.nearest_vertex(ps[i].p);\n\t\t\tlint d2 = CGAL::squared_distance(vh->point(), ps[i].p);\n\t\t\tif (d2 >= (ps[i].r + h)*(ps[i].r + h)) {\n\t\t\t\t// existing one living participant: update the interval\n\t\t\t\tendleftover.push_back(i);\n\t\t\t}\n\t\t}\n\t\tif (!endleftover.empty()) {\n\t\t\tleftover.clear();\n\t\t\tleftover.insert(leftover.begin(), endleftover.begin(), endleftover.end());\n\t\t}\n\t}\n\treturn;\n}\nvoid LightTheStage() {\n\tint m, n, h; _i >> m >> n;\n\t_e << m << \" \" << n << _l;\n\tstd::vector<Participant> ps(m);\n\tfor (int i = 0; i < m; i++) {\n\t\tint x, y, r;\n\t\t_i >> x >> y >> r;\n\t\tps[i] = Participant(x, y, r);\n\t}\n\t_i >> h;\n\tstd::vector<Pt> lights(n);\n\tfor (int j = 0; j < n; j++) {\n\t\tint x, y; _i >> x >> y;\n\t\tlights[j] = Pt(x, y);\n\t}\n\n\tDelaunay D;\n\tD.insert(lights.begin(), lights.end());\n\n\tstd::vector<int> leftover;\n\tfor (int i = 0; i < m; i++) {\n\t\tVertex_handle vh = D.nearest_vertex(ps[i].p);\n\t\tlint d2 = CGAL::squared_distance(vh->point(), ps[i].p);\n\t\tif (d2 >= (ps[i].r + h)*(ps[i].r + h)) {\n\t\t\tleftover.push_back(i);\n\t\t}\n\t}\n\tif (!leftover.empty()) {\n\t\tint l = leftover.size();\n\t\tfor (int i = 0; i < l; i++) {\n\t\t\t_o << leftover[i] << \" \";\n\t\t}\n\t}\n\telse {\n\t\tbinarySearchLeftover(ps, lights, h, leftover);\n\t\tint l = leftover.size();\n\t\tfor (int i = 0; i < l; i++) {\n\t\t\t_o << leftover[i] << \" \";\n\t\t}\n\t}\n\t_o << _l;\n\treturn;\n}\n\n\n\n// week 8: Bistro (nearest_vertex)\nvoid Bistro(int n) {\n\ttypedef CGAL::Delaunay_triangulation_2<IK>\t\tDelaunay;\n\ttypedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\n\ttypedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\n\ttypedef Delaunay::Vertex_handle\t\tVertex_handle;\n\ttypedef Delaunay::Point\t\tDPt;\n\n\n\t//int n, m; _i >> n;\n\tstd::vector<Pt> existing(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tint x, y;\n\t\t_i >> x >> y;\n\t\texisting[i] = Pt(x, y);\n\t}\n\tint m; _i >> m;\n\tstd::vector<Pt> possible(m);\n\tfor (int j = 0; j < m; j++) {\n\t\tint x, y;\n\t\t_i >> x >> y;\n\t\tpossible[j] = Pt(x, y);\n\t}\n\n\tDelaunay D;\n\tD.insert(existing.begin(), existing.end());\n\n\tfor (int j = 0; j < m; j++) {\n\t\tVertex_handle vh = D.nearest_vertex(possible[j]);\n\t\tlint d2 = CGAL::squared_distance(vh->point(), possible[j]);\n\t\t_o << d2 << _l;\n\t}\n\n\treturn;\n}\n\n\n\n// Week 11: Strikes Back\n// Delaunay triangulation for r\n// LP for e\nvoid StrikesBack() {\n\ttypedef CGAL::Delaunay_triangulation_2<IK>\t\tDelaunay;\n\ttypedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\n\ttypedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\n\ttypedef Delaunay::Vertex_handle\t\tVertex_handle;\n\ttypedef Delaunay::Point\t\tDPt;\n\n\tstruct Asteroid {\n\t\tPt pos;\n\t\tint d;\n\t\tAsteroid(Pt p = Pt(), int d = 0) : pos(p), d(d) {}\n\t};\n\n\tint a, s, b;\n\t_i >> a >> s >> b;\n\tint emax;\n\t_i >> emax;\n\n\tstd::vector<Asteroid> asters(a);\n\tstd::vector<Pt> shotpos(s); // model r and e outside.\n\tstd::vector<Pt> bounties(b);\n\n\tfor (int i = 0; i < a; i++) {\n\t\tint x, y, d;\n\t\t_i >> x >> y >> d;\n\t\tasters[i] = Asteroid(Pt(x, y), d);\n\t}\n\tfor (int i = 0; i < s; i++) {\n\t\tint x, y;\n\t\t_i >> x >> y;\n\t\tshotpos[i] = Pt(x, y);\n\t}\n\tfor (int i = 0; i < b; i++) {\n\t\tint x, y;\n\t\t_i >> x >> y;\n\t\tbounties[i] = DPt(x, y);\n\t}\n\n\t// triangulate bounties\n\tDelaunay D;\n\tD.insert(bounties.begin(), bounties.end());\n\n\t_e << \"delaunay\" << _l;\n\n\tstd::vector<lint> shotradsq(s);\n\tif (b > 0) {\n\t\tfor (int i = 0; i < s; i++) {\n\t\t\tDPt dpt(shotpos[i]);\n\t\t\tVertex_handle vh = D.nearest_vertex(shotpos[i]);\n\t\t\tshotradsq[i] = CGAL::squared_distance(shotpos[i], vh->point());\n\t\t\tif (shotradsq[i] < 1) {\n\t\t\t\tshotradsq[i] = 1;\n\t\t\t}\n\t\t}\n\t\t_e << \"shotradsq\" << _l;\n\t}\n\n\t// set up LP to solve for min\\Sum_i e_i\n\tProgram lp(CGAL::LARGER, true, 0, true, emax); // Ax >= b\n\n\tfor (int i = 0; i < a; i++) {\n\t\tlp.set_b(i, asters[i].d);\n\t\tfor (int j = 0; j < s; j++) {\n\t\t\tlint sqdistij = CGAL::squared_distance(asters[i].pos, shotpos[j]);\n\t\t\tif (b == 0 || sqdistij <= shotradsq[j]) {\n\t\t\t\t// in shot range\n\t\t\t\tlp.set_a(j, i, ET(1) / sqdistij); // will it work?\n\t\t\t}\n\t\t}\n\t}\n\tfor (int j = 0; j < s; j++) {\n\t\tlp.set_c(j, 1);\n\t}\n\n\t_e << \"lpsetup\" << _l;\n\n\t// solve the program, using ET as the exact type\n\tSolution solution = CGAL::solve_linear_program(lp, ET());\n\tassert(solution.solves_linear_program(lp));\n\tif (solution.is_infeasible()) {\n\t\t_o << \"n\" << _l;\n\t\treturn;\n\t}\n\telse {\n\t\tET eoptimal = solution.objective_value().numerator() / solution.objective_value().denominator();\n\t\tif (eoptimal <= emax) {\n\t\t\t_o << \"y\" << _l;\n\t\t}\n\t\telse {\n\t\t\t_o << \"n\" << _l;\n\t\t}\n\t}\n\treturn;\n\n}\n\n\n\n// Week 12 PotW: Golden Eye / 100pts\n// Euclidean (Kruskal) MST + Union Find for connectivity\n// Cautions(I am not good today...):\n// 1. check connectivity before adding any edges\n// 2. it could be that the distance from queries to its nearest_vertex dominates the distance\n// 3. beware of the order of setting a variable and using its value......\n// 4. set everything to _lint_....\nlint minLevelSet(Graph& G, std::vector<Edge>& mst, std::vector<int>& s, std::vector<int> &t, std::vector<lint> &maxd2, lint maxp) {\n\tint n = boost::num_vertices(G);\n\tint m = s.size();\n\tWeightMap wmap = boost::get(boost::edge_weight, G);\n\n\tUnionFind uf(n);\n\tlint start = 0;\n\tstd::vector<bool> isconnected(m, false);\n\tbool allconn = true;\n\tfor (int j = 0; j < m; j++) {\n\t\tstart = std::max(start, maxd2[j]);\n\t\tisconnected[j] = uf.inSameSet(s[j], t[j]);\n\t\tif (!isconnected[j]) allconn = false;\n\t}\n\tif (allconn || start > maxp) {\n\t\treturn start;\n\t}\n\n\tstd::vector<Edge>::iterator eit = mst.begin();\n\n\tfor (; eit != mst.end(); eit++) {\n\t\tif (wmap[*eit] > maxp) return -1;\n\t\tint u = boost::source(*eit, G);\n\t\tint v = boost::target(*eit, G);\n\t\tuf.unionSets(u, v);\n\t\tif (eit == mst.end() - 1 || wmap[*(eit + 1)] >= start) {\n\t\t\tbool allconnected = true;\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tif (isconnected[j]) continue;\n\t\t\t\tif (uf.inSameSet(s[j], t[j]))\n\t\t\t\t\tisconnected[j] = true;\n\t\t\t\tif (!isconnected[j])\n\t\t\t\t\tallconnected = false; // isconnected[j] could have been altered!\n\t\t\t}\n\t\t\tif (allconnected)\n\t\t\t\treturn std::max(start, (lint)wmap[*eit]);\n\t\t}\n\t}\n\treturn -1; // never happen\n}\nvoid GoldenEye2() {\n\ttypedef CGAL::Triangulation_vertex_base_with_info_2<ind_t, IK>\tVb;\n\ttypedef CGAL::Triangulation_data_structure_2<Vb>\tTds;\n\ttypedef CGAL::Delaunay_triangulation_2<IK, Tds>\t\tDelaunay;\n\ttypedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\n\ttypedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\n\ttypedef Delaunay::Vertex_handle\t\tVertex_handle;\n\ttypedef Delaunay::Point\t\tDPt;\n\n\tlint n, m, p;\n\t_i >> n >> m >> p;\n\tstd::vector< std::pair<DPt, int> > jams(n);\n\tstd::vector<Pt> ss(m);\n\tstd::vector<Pt> ts(m);\n\n\tGraph G(n); // undirected graph\n\tWeightMap weight = boost::get(boost::edge_weight, G);\n\n\tint x, y;\n\tfor (int i = 0; i < n; i++) {\n\t\t_i >> x >> y;\n\t\tjams[i] = std::make_pair(DPt(x, y), i);\n\t}\n\tfor (int j = 0; j < m; j++) {\n\t\tint x0, y0, x1, y1;\n\t\t_i >> x0 >> y0 >> x1 >> y1;\n\t\tss[j] = Pt(x0, y0);\n\t\tts[j] = Pt(x1, y1);\n\t}\n\n\tDelaunay D;\n\tD.insert(jams.begin(), jams.end());\n\n\t// Euclid MST\n\tfor (Edge_iterator ei = D.finite_edges_begin(); ei != D.finite_edges_end(); ++ei) {\n\t\tVertex_handle v1 = ei->first->vertex((ei->second + 1) % 3);\n\t\tVertex_handle v2 = ei->first->vertex((ei->second + 2) % 3);\n\t\tint i1 = v1->info();\n\t\tint i2 = v2->info();\n\t\tlint dist = CGAL::squared_distance(v1->point(), v2->point());\n\t\t//_e << i1 << \" \" << i2 << \":\" << dist << _l;\n\t\tbool success; Edge e;\n\t\tboost::tie(e, success) = boost::add_edge(i1, i2, G);\n\t\tif (success) weight[e] = dist;\n\t}\n\n\tstd::vector<Edge> spanning_tree;\n\tboost::kruskal_minimum_spanning_tree(G, std::back_inserter(spanning_tree));\n\n\tstd::vector<lint> ds(m), dt(m), maxpow(m);\n\tstd::vector<Vertex_handle> vs(m), vt(m);\n\tstd::vector<int> visited(m);\n\tstd::vector<bool> pset(m, true);\n\tfor (int j = 0; j < m; j++) {\n\t\tPt s = ss[j], t = ts[j];\n\t\tvs[j] = D.nearest_vertex(s), vt[j] = D.nearest_vertex(t);\n\t\tds[j] = CGAL::squared_distance(vs[j]->point(), s);\n\t\tdt[j] = CGAL::squared_distance(vt[j]->point(), t);\n\t\tmaxpow[j] = 4 * std::max(ds[j], dt[j]);\n\t\tvisited[j] = 0;\n\t\tif (maxpow[j] > p) pset[j] = false;\n\t}\n\n\t// check power level p\n\tGraph MSTP(n);\n\tstd::vector<Edge>::iterator eit;\n\tlint maxwinmst = weight[spanning_tree[spanning_tree.size() - 1]]; // max weight in the MST\n\tfor (eit = spanning_tree.begin(); eit != spanning_tree.end(); ++eit) {\n\t\tif (weight[*eit] > p) break;\n\t\tVertex u = boost::source(*eit, G);\n\t\tVertex v = boost::target(*eit, G);\n\t\tboost::add_edge(u, v, MSTP);\n\t}\n\n\tstd::vector<int> components(n);\n\tboost::connected_components(MSTP, &components[0]);\n\tstd::vector<int> p_s, p_t, all_s, all_t;\n\tstd::vector<lint> p_maxd2, all_maxd2;\n\tfor (int j = 0; j < m; j++) {\n\t\tif (!pset[j]) continue;\n\t\tint sidx = vs[j]->info(), tidx = vt[j]->info();\n\t\tif (components[sidx] != components[tidx]) {\n\t\t\tpset[j] = false;\n\t\t}\n\t\tif (pset[j]) {\n\t\t\tp_s.push_back(sidx);\n\t\t\tp_t.push_back(tidx);\n\t\t\tp_maxd2.push_back(maxpow[j]);\n\t\t}\n\t}\n\tfor (int j = 0; j < m; j++) {\n\t\tall_s.push_back(vs[j]->info());\n\t\tall_t.push_back(vt[j]->info());\n\t\tall_maxd2.push_back(maxpow[j]);\n\t}\n\n\tlint b = minLevelSet(G, spanning_tree, p_s, p_t, p_maxd2, p);\n\tlint a = minLevelSet(G, spanning_tree, all_s, all_t, all_maxd2, maxwinmst);\n\n\tfor (int j = 0; j < m; j++) {\n\t\tif (pset[j]) _o << \"y\";\n\t\telse _o << \"n\";\n\t}\n\t_o << _l;\n\t_o << a << _l;\n\t_o << b << _l;\n}\n// Week 12 PotW: Golden Eye / 75pts\n// called uf.inSameSet() too many times\nvoid GoldenEye() {\n\n\ttypedef CGAL::Triangulation_vertex_base_with_info_2<ind_t, IK>\tVb;\n\ttypedef CGAL::Triangulation_data_structure_2<Vb>\tTds;\n\ttypedef CGAL::Delaunay_triangulation_2<IK, Tds>\t\tDelaunay;\n\ttypedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\n\ttypedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\n\ttypedef Delaunay::Vertex_handle\t\tVertex_handle;\n\ttypedef Delaunay::Point\t\tDPt;\n\n\tlint n, m, p;\n\t_i >> n >> m >> p;\n\tstd::vector< std::pair<DPt, int> > jams(n);\n\tstd::vector<Pt> ss(m);\n\tstd::vector<Pt> ts(m);\n\n\tGraph G(n);\n\tWeightMap weight = boost::get(boost::edge_weight, G);\n\n\tint x, y;\n\tfor (int i = 0; i < n; i++) {\n\t\t_i >> x >> y;\n\t\tjams[i] = std::make_pair(DPt(x, y), i);\n\t}\n\tfor (int j = 0; j < m; j++) {\n\t\tint x0, y0, x1, y1;\n\t\t_i >> x0 >> y0 >> x1 >> y1;\n\t\tss[j] = Pt(x0, y0);\n\t\tts[j] = Pt(x1, y1);\n\t}\n\n\tDelaunay D;\n\tD.insert(jams.begin(), jams.end());\n\n\t// Euclid MST\n\tfor (Edge_iterator ei = D.finite_edges_begin(); ei != D.finite_edges_end(); ++ei) {\n\t\tVertex_handle v1 = ei->first->vertex((ei->second + 1) % 3);\n\t\tVertex_handle v2 = ei->first->vertex((ei->second + 2) % 3);\n\t\tint i1 = v1->info();\n\t\tint i2 = v2->info();\n\t\tdouble dist = CGAL::squared_distance(v1->point(), v2->point());\n\t\t//_e << i1 << \" \" << i2 << \":\" << dist << _l;\n\t\tbool success; Edge e;\n\t\tboost::tie(e, success) = boost::add_edge(i1, i2, G);\n\t\tif (success) weight[e] = dist;\n\t}\n\n\tstd::vector<Edge> spanning_tree;\n\tboost::kruskal_minimum_spanning_tree(G, std::back_inserter(spanning_tree));\n\n\tdouble a = 0, b = -1;\n\tstd::vector<double> ds(m), dt(m), maxpow(m);\n\tstd::vector<Vertex_handle> vs(m), vt(m);\n\tstd::vector<int> visited(m);\n\tfor (int j = 0; j < m; j++) {\n\t\tPt s = ss[j], t = ts[j];\n\t\tvs[j] = D.nearest_vertex(s), vt[j] = D.nearest_vertex(t);\n\t\tds[j] = CGAL::squared_distance(vs[j]->point(), s);\n\t\tdt[j] = CGAL::squared_distance(vt[j]->point(), t);\n\t\tmaxpow[j] = 4 * std::max(ds[j], dt[j]);\n\t\tvisited[j] = 0;\n\t}\n\n\t\n\tUnionFind uf(n);\n\tstd::vector<Edge>::iterator ei;\n\tdouble w = 0, wlastchanged = 0;\n\tbool changed = false;\n\tfor (int j = 0; j < m; j++) {\n\t\tif (uf.inSameSet(vs[j]->info(), vt[j]->info())) {\n\t\t\t// effectively vs[j]->info() == vt[j]->info()\n\t\t\tvisited[j] = 1;\n\t\t\tchanged = true;\n\t\t}\n\t}\n\n\t// Gradually add edges of the MST\n\tfor (ei = spanning_tree.begin(); ei != spanning_tree.end(); ++ei) {\n\t\tVertex v1 = boost::source(*ei, G), v2 = boost::target(*ei, G);\n\t\tuf.unionSets(v1, v2);\n\t\tw = weight[*ei];\n\t\t// if (w > p && b < 0) b = wlastchanged;\n\t\tchanged = false;\n\t\tbool allvisited = true;\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tif (!visited[j]) allvisited = false;\n\t\t\tif (!visited[j] && uf.inSameSet(vs[j]->info(), vt[j]->info())) {\n\t\t\t\tvisited[j] = 1;\n\t\t\t\tchanged = true;\n\t\t\t\tmaxpow[j] = std::max(w, maxpow[j]);\n\t\t\t}\n\t\t}\n\t\tif (changed) wlastchanged = w;\n\t\tif (allvisited) break;\n\t}\n\t//if (w > p && b < 0) b = wlastchanged;\n\tif (b < 0) b = 0;\n\n\tfor (int j = 0; j < m; j++) {\n\t\ta = std::max(a, maxpow[j]);\n\t\t//if (!visited[j]) _e << vs[j]->info() << \"?\" << vt[j]->info() << _l;\n\t\t//_e << maxpow[j] << \" \";\n\t\tif (maxpow[j] > p) visited[j] = 2;\n\t\telse {\n\t\t\tif (b < maxpow[j]) b = maxpow[j];\n\t\t}\n\t}\n\t_e << _l;\n\n\tfor (int j = 0; j < m; j++) {\n\t\t_o << (visited[j] == 1 ? \"y\" : \"n\");\n\t}\n\t_o << _l;\n\t_o << (lint)std::ceil(a) << _l;\n\t_o << (lint)std::ceil(b) << _l;\n\treturn;\n\n}\n\n\n\n// typedef CGAL:Gmpz ET;\nvoid Inball(int n, int d) {\n\tProgram lp(CGAL::SMALLER, false, 0, false, 0);\n\tint c[10] = {};\n\tfor (int i = 0; i < d; i++) c[i] = i;\n\tconst int r = d;\n\n\tint a = 0, b = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tdouble norm = 0;\n\t\tfor (int j = 0; j < d; j++) {\n\t\t\t_i >> a;\n\t\t\tlp.set_a(c[j], i, a);\n\t\t\tnorm += a*a;\n\t\t}\n\t\tlp.set_a(r, i, std::round(std::sqrt(norm)));\n\t\t_i >> b;\n\t\tlp.set_b(i, b);\n\t}\n\tlp.set_l(r, true, 0);\n\tlp.set_c(r, -1);\n\n\t// solve the program, using ET as the exact type\n\tSolution s = CGAL::solve_linear_program(lp, ET());\n\tassert(s.solves_linear_program(lp));\n\n\tif (s.is_optimal()) {\n\t\tCGAL::Quadratic_program_solution<ET>::Variable_value_iterator\n\t\t\topt = s.variable_values_begin();\n\t\tCGAL::Quotient<ET> rad = *(opt + d);\n\t\t_o << (int)floor_to_double(rad) << _l;\n\t}\n\telse if (s.is_unbounded()) {\n\t\t_o << \"inf\" << _l;\n\t}\n\telse if (s.is_infeasible()) {\n\t\t_o << \"none\" << _l;\n\t}\n\treturn;\n}\n\n\n\nvoid Lestrade() {\n\n\ttypedef CGAL::Triangulation_vertex_base_with_info_2<ind_t, IK>\tVb;\n\ttypedef CGAL::Triangulation_data_structure_2<Vb>\tTds;\n\ttypedef CGAL::Delaunay_triangulation_2<IK, Tds>\t\tDelaunay;\n\ttypedef Delaunay::Finite_faces_iterator\t\tFace_iterator;\n\ttypedef Delaunay::Finite_edges_iterator\t\tEdge_iterator;\n\ttypedef Delaunay::Vertex_handle\t\tVertex_handle;\n\ttypedef Delaunay::Point\t\tDPt;\n\n\tstruct Gangster {\n\t\tint u;\n\t\tint v;\n\t\tint w;\n\t\tint ag;\n\t\tGangster(int uu = 0, int vv = 0, int ww = 0, int a = -1) : u(uu), v(vv), w(ww), ag(a) {}\n\t};\n\n\tint Z, U, V, W;\n\tint A, G;\n\t_i >> Z >> U >> V >> W >> A >> G;\n\n\tstd::vector<std::pair<DPt, ind_t> > pts(G);\n\tstd::vector<Gangster> gang(G);\n\tfor (ind_t i = 0; i < G; i++) {\n\t\tint x, y, u, v, w;\n\t\t_i >> x >> y >> u >> v >> w;\n\t\tDPt pg(x, y);\n\t\tpts[i] = std::make_pair(pg, i);\n\t\tgang[i] = Gangster(u, v, w);\n\t}\n\tDelaunay T;\n\tT.insert(pts.begin(), pts.end());\n\t//_e << gang.size() << _l;\n\n\tstd::vector<int> ha(A);\n\tstd::vector<int> spect(A);\n\tfor (ind_t i = 0; i < A; i++) {\n\t\tint x, y, h;\n\t\t_i >> x >> y >> h;\n\t\tha[i] = h;\n\t\tDPt pa(x, y);\n\t\tVertex_handle vh = T.nearest_vertex(pa);\n\t\tind_t gind = vh->info();\n\t\tind_t aind = gang[gind].ag;\n\t\t//_e << \"gind\" << gind << \"; aind\" << aind << _l;\n\n\t\tif (aind < 0 || (aind >= 0 && ha[aind] > h)) {\n\t\t\t// the gangster has not been inspected by others\n\t\t\t// or he has been inspected by another more expensive agent\n\t\t\t// --> I will do that instead!\n\t\t\tspect[i] = gind;\n\t\t\tgang[gind].ag = i;\n\t\t\tif (aind >= 0) {\n\t\t\t\tspect[aind] = -1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tspect[i] = -1;\n\t\t}\n\t}\n\t//_e << ha.size() << _l;\n\n\tstd::vector<int> hawo;\n\tstd::vector<Gangster> gangspected;\n\tfor (int i = 0; i < A; i++) {\n\t\tif (spect[i] >= 0) {\n\t\t\thawo.push_back(ha[i]);\n\t\t\tgangspected.push_back(gang[spect[i]]);\n\t\t}\n\t}\n\tint nworking = hawo.size();\n\n\t/// set up the LP problem\n\tProgram lp(CGAL::LARGER, true, 0, true, 24.f);\n\tfor (ind_t j = 0; j < nworking; j++) {\n\t\tint z = hawo[j];\n\t\tGangster gs = gangspected[j];\n\t\t//_e << z << \" \" << gs.u << \" \" << gs.v << \" \" << gs.w << _l;\n\t\tlp.set_c(j, -gs.u);\n\t\tlp.set_a(j, 0, -z);\n\t\tlp.set_a(j, 1, gs.v);\n\t\tlp.set_a(j, 2, gs.w);\n\t}\n\tlp.set_b(0, -Z);\n\tlp.set_b(1, V);\n\tlp.set_b(2, W);\n\n\t// solve the program, using ET as the exact type\n\tSolution s = CGAL::solve_linear_program(lp, ET());\n\tassert(s.solves_linear_program(lp));\n\n\tif (s.is_optimal()) {\n\t\tET optim = s.objective_value().numerator() / s.objective_value().denominator();\n\t\t//_e << \"optim:\" << optim.to_double() << _l;\n\t\tif (optim > -U)\n\t\t\t_o << \"H\" << _l;\n\t\telse\n\t\t\t_o << \"L\" << _l;\n\t}\n\telse if (s.is_unbounded()) {\n\t\t_o << \"L\" << _l;\n\t}\n\telse if (s.is_infeasible()) {\n\t\t_o << \"H\" << _l;\n\t}\n}", "meta": {"hexsha": "92807046d5796a18f67a99b46bc21c10e3a541eb", "size": 54046, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cgal-kernels-lpqp.cpp", "max_stars_repo_name": "MKimiSH/ETH-AlgoLab-17", "max_stars_repo_head_hexsha": "5c58253b5cee535ace02ba494ea081892a0096b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-09-23T19:07:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-19T19:16:24.000Z", "max_issues_repo_path": "cgal-kernels-lpqp.cpp", "max_issues_repo_name": "MKimiSH/ETH-AlgoLab-17", "max_issues_repo_head_hexsha": "5c58253b5cee535ace02ba494ea081892a0096b6", "max_issues_repo_licenses": ["MIT"], "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-kernels-lpqp.cpp", "max_forks_repo_name": "MKimiSH/ETH-AlgoLab-17", "max_forks_repo_head_hexsha": "5c58253b5cee535ace02ba494ea081892a0096b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-24T15:31:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-24T15:31:18.000Z", "avg_line_length": 26.996003996, "max_line_length": 157, "alphanum_fraction": 0.5940125079, "num_tokens": 19729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6150878696277513, "lm_q1q2_score": 0.5057185607238397}}
{"text": "#include \"integration.hpp\"\n#include <iostream>\n#include <Eigen/Sparse>\n#include <Eigen/IterativeLinearSolvers>\nusing namespace std;\n\nvoid explicitEulerStep(PhysicalSystem *system, double dt) {\n    forwardEulerStep(system, dt);\n}\n\nvoid forwardEulerStep(PhysicalSystem *system, double dt) {\n    int n = system->getDOFs();\n    VectorXd x0(n), v0(n);\n    system->getState(x0, v0);\n    MatrixXd M(n,n);\n    system->getInertia(M);\n    VectorXd f0(n);\n    system->getForces(f0);\n    VectorXd a0(n); // acceleration\n    for (int i = 0; i < n; i++)\n        a0(i) = f0(i)/M(i,i);\n    VectorXd x1 = x0 + v0*dt;\n    VectorXd v1 = v0 + a0*dt;\n    system->setState(x1, v1);\n} \n", "meta": {"hexsha": "23fe0e1eb896f5c26b0196064b425ad8a722b47f", "size": 663, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/1_MassSpring_Explicit/integration.cpp", "max_stars_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_stars_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-08-02T08:15:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T09:29:04.000Z", "max_issues_repo_path": "C++/1_MassSpring_Explicit/integration.cpp", "max_issues_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_issues_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "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++/1_MassSpring_Explicit/integration.cpp", "max_forks_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_forks_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "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.5, "max_line_length": 59, "alphanum_fraction": 0.6395173454, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5057185544811498}}
{"text": "/*\n * Copyright 2016 Erik Crevel\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 VARDISTRIBUTION_HPP\n#define VARDISTRIBUTION_HPP\n\n#include <vector>\n#include <tuple>\n#include <utility>\n#include <ostream>\n#include <boost/multi_array.hpp>\n\nclass ArithmeticEncoder;\nclass ArithmeticDecoder;\n\n\nclass VarDistribution\n{\n\tstd::vector<std::pair<int, double>> curvePoints;\n\n\tvoid addPoint(int _i, double _sigma);\n\n\npublic:\n\tVarDistribution() {}\n\ttemplate <class TContainer>\n\tVarDistribution(const TContainer& _counts);\n\n\tstd::pair<double, double> getDist(unsigned char _val) const;\n\n\tvoid encodeDist(std::ostream& _out) const;\n\tvoid decodeDist(std::istream& _in);\n\n\tclass Calculator\n\t{\n\t\tVarDistribution& dist;\n\n\t\tboost::multi_array<int,2> counts;\n\n\tpublic:\n\t\tCalculator(VarDistribution& _dist) :\n\t\t\tdist(_dist),\n\t\t\tcounts(boost::extents[256][256])\n\t\t{}\n\n\t\tvoid add(int _val, unsigned char _v);\n\n\t\tvoid calculate();\n\t};\n};\n\n\nnamespace\n{\n\ntemplate <class TContainer>\ndouble variance(const TContainer& _counts)\n{\n\tint n = 0;\n\tdouble sumX = 0;\n\tdouble sumXX = 0;\n\n\tfor(int x = 0; x < _counts.size(); ++x)\n\t{\n\t\tn += _counts[x];\n\t\tsumX += x*_counts[x];\n\t\tsumXX += x*x*_counts[x];\n\t}\n\n\treturn (sumXX - sumX*sumX/n)/n;\n}\n\n}\n\n\ntemplate <class TContainer>\nVarDistribution::VarDistribution(const TContainer& _counts)\n{\n\tconst int CURVE_SEGMENT_SIZE = 1024;\n\n\tstd::vector<std::pair<int, double>> distVars(256);\n\tfor(int varI = 0; varI < _counts.size(); ++varI)\n\t{\n\t\tconst auto& subCounts = _counts[varI];\n\n\t\tint subTotal = std::accumulate(subCounts.begin(), subCounts.end(), 0);\n\n\t\tdistVars[varI] = {subTotal, std::sqrt(variance(subCounts))};\n\t}\n\n\tint total = 0;\n\tint weightedI = 0;\n\tdouble weightedSigma = 0;\n\tfor(int varI = 0; varI < distVars.size(); ++varI)\n\t{\n\t\tif(distVars[varI].first > 0)\n\t\t{\n\t\t\ttotal += distVars[varI].first;\n\t\t\tweightedI += distVars[varI].first * varI;\n\t\t\tweightedSigma += distVars[varI].first * distVars[varI].second;\n\n\t\t\tif(total >= CURVE_SEGMENT_SIZE)\n\t\t\t{\n\t\t\t\tthis->addPoint((weightedI+total/2)/total, weightedSigma/total);\n\n\t\t\t\ttotal = 0;\n\t\t\t\tweightedI = 0;\n\t\t\t\tweightedSigma = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(total > 0)\n\t\tthis->addPoint((weightedI+total/2)/total, weightedSigma/total);\n}\n\n#endif // VARDISTRIBUTION_HPP\n", "meta": {"hexsha": "53108ee14843304fbbd49772233860d940c5f5c9", "size": 2739, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "VarDistribution.hpp", "max_stars_repo_name": "nimble0/rsic", "max_stars_repo_head_hexsha": "e94f2e226fa68e7495c7423f1845b01edff6b2fe", "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": "VarDistribution.hpp", "max_issues_repo_name": "nimble0/rsic", "max_issues_repo_head_hexsha": "e94f2e226fa68e7495c7423f1845b01edff6b2fe", "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": "VarDistribution.hpp", "max_forks_repo_name": "nimble0/rsic", "max_forks_repo_head_hexsha": "e94f2e226fa68e7495c7423f1845b01edff6b2fe", "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.9083969466, "max_line_length": 75, "alphanum_fraction": 0.69550931, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5057185544811497}}
{"text": "#include <boost/graph/bellman_ford_shortest_paths.hpp>\n", "meta": {"hexsha": "58f608342e67180ceceffb7d8601d271624c35f2", "size": 55, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_graph_bellman_ford_shortest_paths.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_graph_bellman_ford_shortest_paths.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_graph_bellman_ford_shortest_paths.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.5, "max_line_length": 54, "alphanum_fraction": 0.8545454545, "num_tokens": 14, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219505, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5057185491213658}}
{"text": "#include \"PCE.h\"\n#include \"GeomCommonFunctions.h\"\n#include <Gui/Application.h>\n#include <BRepBuilderAPI_GTransform.hxx>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <tchar.h>\n#include <iostream>\n\nusing namespace PartDesignGui;\n\nPCEArrange::\nPCEArrange(\n\tint index_,\n\tint wlc_index_,\n\tint wl_index_, \n\tconst std::vector<PCEPosition> & positions_,\n\tconst std::vector<PCEEdge> & cutting_lines_,\n\tconst double &volume_rate_) :\n\tindex(index_), \n\tcutting_number(cutting_lines_.size()),\n\twlc_index(wlc_index_),\n\twl_index(wl_index_),\n\tpositions(positions_),\n\tcutting_lines(cutting_lines_),\n\tvolume_rate(volume_rate_), \n\tvalid(false),\n\teclass_index(-1),\n\tperfect_stock(false)\n{\n\tEncode();\n}\n\nvoid PCEArrange::Encode()\n{\n\tshape_order.clear();\n\n\t//encode\n\tVector2d1 pos_centers;\n\tfor (auto position : positions)\n\t{\n\t\tpos_centers.emplace_back(position.center);\n\t\tshape_order.emplace_back(position.transform->pce_shape->index);\n\t}\n\n\tVector2d pos_center = Math::Functs::GetCenter(pos_centers);\n\tfor (auto& center : pos_centers)center = center - pos_center;\n\n\t//Math::Functions::Vector2d3d();\n\tauto M = Math::Functs::RotationMatrix(Vector3d(0.0, 0.0, 1.0), Math::Math_PI);\n\tauto r_pos_centers = Math::Functs::Vector3d2d(Math::Functs::PosApplyM(Math::Functs::Vector2d3d(pos_centers), M));\n\tauto r_shape_order = shape_order;\n\tstd::reverse(r_shape_order.begin(), r_shape_order.end());\n\n\tencode_0 = Vector2dString(pos_centers, shape_order, wl_index);\n\tencode_1 = Vector2dString(r_pos_centers, r_shape_order, wl_index);\n\tencode_packing_0 = Vector2dString(pos_centers, shape_order, -1);\n\tencode_packing_1 = Vector2dString(r_pos_centers, r_shape_order, -1);\n}\n\nPCEArrange::PCEArrange():\nindex(-1), eclass_index(-1), cutting_number(-1), wl_index(-1), wlc_index(-1), valid(false),volume_rate(0), perfect_stock(false)\n{\n}\n\nvoid PCEArrange::Clear()\n{\n\tfor (auto& position : positions)position.Clear();\n\tstd::vector<PCEPosition>().swap(positions);\n\tstd::vector<PCEEdge>().swap(cutting_lines);\n\tstd::vector<int>().swap(shape_order);\n\tVector1i2().swap(cutting_orders);\n\tstd::vector<PCEConstraint>().swap(sharing_constraints);\n\tstd::vector<PCEEdge>().swap(edges);\n\n\tstd::vector<std::vector<std::tuple<std::list<std::string>,int>>>().swap(prog_strs);\n}\n\nVector3d3 PCEArrange::GetMesh(Vector3d2& surfs) const\n{\n\tVector3d3 all_points;\n\tfor (auto position : positions)\n\t\tall_points.emplace_back(Math::Functs::PosApplyM(position.transform->surfs, position.M));\n\treturn all_points;\n}\n\nstd::string PCEArrange::Vector2dString(Vector2d1 ps, std::vector<int> ints, int wl_index_)\n{\n\tconst auto Comp = [](const Vector2d& a, const Vector2d& b)\n\t{\n\t\treturn a[0] < b[0];\n\t};\n\n\tstd::sort(ps.begin(), ps.end(), Comp);\n\tstd::string str;\n\tfor (auto p : ps)\n\t{\n\t\tdouble x = floor(p[0] * 10.0f + 0.5) / 10.0f;\n\t\tdouble y = floor(p[1] * 10.0f + 0.5) / 10.0f;\n\t\tstr += Math::Functs::DoubleString(x);\n\t\tstr += Math::Functs::DoubleString(y);\n\t}\n\t//sort(ints.begin(), ints.end());\n\tfor (auto i : ints)\n\t\tstr += Math::Functs::IntString(i);\n\tif (wl_index_ >= 0)\n\t\tstr = str + Math::Functs::IntString(wl_index_);\n\treturn str;\n}", "meta": {"hexsha": "32103e7b3bf148b6c956312e85feef05e9a8737c", "size": 3080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gui/PCE_arrange.cpp", "max_stars_repo_name": "haisenzhao/CarpentryCompiler", "max_stars_repo_head_hexsha": "c9714310b7ce7523a25becd397265bfaa3ab7ea3", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2019-12-06T09:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T12:58:09.000Z", "max_issues_repo_path": "Gui/PCE_arrange.cpp", "max_issues_repo_name": "haisenzhao/CarpentryCompiler", "max_issues_repo_head_hexsha": "c9714310b7ce7523a25becd397265bfaa3ab7ea3", "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": "Gui/PCE_arrange.cpp", "max_forks_repo_name": "haisenzhao/CarpentryCompiler", "max_forks_repo_head_hexsha": "c9714310b7ce7523a25becd397265bfaa3ab7ea3", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-11-18T00:09:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T04:40:47.000Z", "avg_line_length": 28.2568807339, "max_line_length": 127, "alphanum_fraction": 0.7220779221, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5057185384017971}}
{"text": "#ifndef AIKIDO_COMMON_STEPSEQUENCE_HPP_\n#define AIKIDO_COMMON_STEPSEQUENCE_HPP_\n\n#include <cassert>\n#include <limits>\n#include <tuple>\n#include <boost/iterator/iterator_facade.hpp>\n\nnamespace aikido {\nnamespace common {\n\n/// An iterator that returns a sequence of numbers between start point and end\n/// point stepping at a fixed stepsize.\nclass StepSequence\n{\npublic:\n  class const_iterator;\n\n  /// Constructor.\n  ///\n  /// \\param stepSize Step size increments from the start point to the end\n  /// point.\n  /// \\param includeStartpoint If includeStartpoint is true then the start point\n  /// in the sequence will be the start point; else the start point in the\n  /// sequence will be the start point plus the stepSize (if it is larger than\n  /// the end point, it will be the end point.\n  /// \\param includeEndpoint If includeEndpoint is true then the final point in\n  /// the sequence will be the end point, even if it is at less than stepSize\n  /// from the second to last point.\n  /// \\param startPoint The start point that defines the sequence.\n  /// \\param endPoint The end point that defines the sequence.\n  StepSequence(\n      double stepSize,\n      bool includeStartpoint = true,\n      bool includeEndpoint = true,\n      double startPoint = 0.0,\n      double endPoint = 1.0);\n\n  /// Constructs StepSequence in Matlab's linspace() style.\n  StepSequence(\n      double startPoint,\n      double endPoint,\n      std::size_t numSteps,\n      bool includeEndpoint = true);\n\n  /// Returns an iterator to the first element of the sequence.\n  ///\n  /// \\return Iterator to the first element of the sequence.\n  const_iterator begin() const;\n\n  /// Returns an iterator to the element following the last element of the\n  /// sequence.\n  ///\n  /// \\return Iterator followin the last element of the sequence.\n  const_iterator end() const;\n\n  /// Returns the \\c n-th element of the sequence.\n  ///\n  /// \\return Element in the sequence.\n  double operator[](std::size_t n) const;\n\n  /// Returns the total length of sequence.\n  ///\n  /// \\return Non-negative number of the tatal length of sequence.\n  std::size_t getLength() const;\n\nprivate:\n  /// Computes the total length of sequence given step size. This is only called\n  /// in the contructor.\n  void updateNumSteps();\n\n  /// Computes the step size of sequence given number of steps. This is only\n  /// called in the contructor.\n  void updateStepSize();\n\n  /// Step size increments from the start point to the end point.\n  double mStepSize;\n\n  /// Whether the start point in the sequence will be the start point.\n  const bool mIncludeStartPoint;\n\n  /// Whether the end point in the sequence will be the end point.\n  const bool mIncludeEndPoint;\n\n  /// The start point that defines the sequence.\n  const double mStartPoint;\n\n  /// The end point that defines the sequence.\n  const double mEndPoint;\n\n  /// The total length of sequence.\n  std::size_t mNumSteps;\n};\n\nclass StepSequence::const_iterator\n    : public boost::iterator_facade<StepSequence::const_iterator,\n                                    double,\n                                    boost::forward_traversal_tag,\n                                    double>\n{\npublic:\n  /// Dereference implementation for boost::iterator_facade.\n  double dereference() const;\n\n  /// Increment implementation for boost::iterator_facade.\n  void increment();\n\n  /// Equal implementation for boost::iterator_facade.\n  ///\n  /// \\return True if two iterators are at the same point in the sequence.\n  bool equal(const StepSequence::const_iterator& other) const;\n\nprivate:\n  friend class StepSequence;\n\n  /// Private constructor that should always be constructed from\n  /// StepSequence::begin().\n  const_iterator(const StepSequence& seq, std::size_t step);\n\n  /// StepSequence associated with this iterator.\n  const StepSequence& mSeq;\n\n  /// Current step number.\n  std::size_t mStep;\n\n  /// Value of the current step.\n  double mValue;\n};\n\n} // namespace common\n} // namespace aikido\n\n#endif // AIKIDO_COMMON_STEPSEQUENCE_HPP_\n", "meta": {"hexsha": "41125742d647af658a57df2a9fc332c77a1767da", "size": 4009, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/aikido/common/StepSequence.hpp", "max_stars_repo_name": "usc-csci-545/aikido", "max_stars_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "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/aikido/common/StepSequence.hpp", "max_issues_repo_name": "usc-csci-545/aikido", "max_issues_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/aikido/common/StepSequence.hpp", "max_forks_repo_name": "usc-csci-545/aikido", "max_forks_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "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.9179104478, "max_line_length": 80, "alphanum_fraction": 0.7001746071, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5056532533361757}}
{"text": "#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/ref.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n#include <boost/graph/is_kuratowski_subgraph.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <vector> \n#include <iostream>\nusing namespace std;\nusing namespace boost;\n\ntypedef adjacency_list<vecS, vecS, undirectedS> Graph;\ntypedef graph_traits<Graph>::vertex_descriptor VertDesc;\ntypedef graph_traits<Graph>::edge_iterator     EdgeIter;\n\nint main(int argc, char** argv)\n{ \n        if( argc < 3 ){\n                cerr << \"Usage: planargen n e\\n\";\n                cerr << \"   n - number of vertices\\n\";\n                cerr << \"   e - number of edges (<= 3n-6)\\n\";\n                return 0;\n        }\n        int n = atoi(argv[1]);\n        int e = atof(argv[2]);\n        if( e > 3*n - 6 ){\n                cerr << \"Planr graph must have <= 3*n - 6 edges!\\n\";\n                return 0;\n        }\n\n        Graph g(n); \n        uint v1, v2;\n        for( uint i = 0; i < e; ++i ){ \n\n                if( i < n ) v1 = i; // force all verts to be used at least once\n                else v1 = rand() % n;\n\n                do { v2 = rand() % n; } while( v1 == v2 );\n\n                if( edge(v1, v2, g).second ) continue;\n\n                auto g_tmp = g; \n                add_edge(v1, v2, g_tmp);\n\n                if( boyer_myrvold_planarity_test(g_tmp) ){\n                        g = g_tmp;\n                        cout << v1 << \", \" << v2 << '\\n';\n                        cerr << (i*100.0/e) << \"%\\n\";\n                } else --i; \n        }\n\n        vector<int> component(num_vertices(g));\n        int num = connected_components(g, &component[0]);\n\n        vector<int>::size_type i;\n        cerr << \"Total number of components: \" << num << endl;\n}\n", "meta": {"hexsha": "9246ab389f014043285a0ca587dae727fb0f341d", "size": 1899, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphgen.cpp", "max_stars_repo_name": "FashGek/chazelle-triangulation", "max_stars_repo_head_hexsha": "3ef89edb225dbfdd09ce8fde103fe657d01bcc98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-20T04:19:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T04:19:49.000Z", "max_issues_repo_path": "graphgen.cpp", "max_issues_repo_name": "FashGek/chazelle-triangulation", "max_issues_repo_head_hexsha": "3ef89edb225dbfdd09ce8fde103fe657d01bcc98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphgen.cpp", "max_forks_repo_name": "FashGek/chazelle-triangulation", "max_forks_repo_head_hexsha": "3ef89edb225dbfdd09ce8fde103fe657d01bcc98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-20T04:20:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-20T04:20:18.000Z", "avg_line_length": 31.65, "max_line_length": 79, "alphanum_fraction": 0.5202738283, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5056532493752437}}
{"text": "#include <ecto/ecto.hpp>\n#include <boost/thread.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\nusing ecto::tendrils;\nusing ecto::spore;\n\nnamespace ecto_test\n{\n\n  struct Accumulator\n  {\n    static void declare_io(const tendrils& p, tendrils& i, tendrils& o)\n    {\n      i.declare<double>(&Accumulator::left_,\"left\", \"Left hand operand.\");\n      i.declare<double>(&Accumulator::right_,\"right\",\"Right hand operand.\");\n      o.declare<double>(&Accumulator::out_,\"out\",\"The current accumulation.\", 0.0);\n    }\n    int process(const tendrils& inputs, const tendrils& /*outputs*/)\n    {\n      boost::mutex::scoped_lock lock(mutex);\n      if ( inputs.find(\"left\") != inputs.end() ) {\n        std::cout << \"  Left: \" << *out_ << \"+\" << *left_ << \"=\" << *out_ + *left_ << std::endl;\n        *out_ += *left_;\n      }\n      if ( inputs.find(\"right\") != inputs.end() ) {\n        std::cout << \"  Right: \" << *out_ << \"+\" << *right_ << \"=\" << *out_ + *right_ << std::endl;\n        *out_ += *right_;\n      }\n      // sleep a bit to effectively test the sharing\n      boost::this_thread::sleep(boost::posix_time::milliseconds(100));\n      return ecto::OK;\n    }\n    spore<double> out_, left_, right_;\n    mutable boost::mutex mutex;\n  };\n}\n\nECTO_CELL(ecto_test, ecto_test::Accumulator, \"Accumulator\", \"Add inputs (potentially from different threads) to an incrementally accumulating sum.\");\n", "meta": {"hexsha": "99433781af79b7714073db11348f4a017fdfeca4", "size": 1386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cells/Accumulator.cpp", "max_stars_repo_name": "fujiehuang/ecto", "max_stars_repo_head_hexsha": "fea744337aa1fad1397c9a3ba5baa143993cb5eb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2015-01-30T15:45:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T02:29:37.000Z", "max_issues_repo_path": "test/cells/Accumulator.cpp", "max_issues_repo_name": "fujiehuang/ecto", "max_issues_repo_head_hexsha": "fea744337aa1fad1397c9a3ba5baa143993cb5eb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2015-01-18T21:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-09T08:24:54.000Z", "max_forks_repo_path": "test/cells/Accumulator.cpp", "max_forks_repo_name": "fujiehuang/ecto", "max_forks_repo_head_hexsha": "fea744337aa1fad1397c9a3ba5baa143993cb5eb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2015-02-17T14:37:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T07:46:26.000Z", "avg_line_length": 34.65, "max_line_length": 149, "alphanum_fraction": 0.6132756133, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5056532446426147}}
{"text": "/* Copyright (c) 2017, United States Government, as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * \n * All rights reserved.\n * \n * The Astrobee platform is licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with the\n * License. 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, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n#include <Eigen/Dense>\n\n#include <iostream>\n\nusing namespace Eigen;\n\nvoid matrix_multiply(float* m1, int m1_rows, int m1_cols, float* m2, int m2_rows, int m2_cols, float* m_out) {\n  Map<MatrixXf> A(m1, m1_rows, m1_cols);\n  Map<MatrixXf> B(m2, m2_rows, m2_cols);\n  Map<MatrixXf> out(m_out, m1_rows, m2_cols);\n\n  out.noalias() = A * B;\n}\n\n", "meta": {"hexsha": "e8040e09860a7b62c193d64bc0a2128794875e6f", "size": 1098, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gnc/matlab/cxx_functions/src/matrix_multiply.cpp", "max_stars_repo_name": "PeterWofford/astrobee", "max_stars_repo_head_hexsha": "d4c05f6a938f0d56f071ee79ce86d90c24f1b2cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 629.0, "max_stars_repo_stars_event_min_datetime": "2017-08-31T23:09:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:55:40.000Z", "max_issues_repo_path": "gnc/matlab/cxx_functions/src/matrix_multiply.cpp", "max_issues_repo_name": "PeterWofford/astrobee", "max_issues_repo_head_hexsha": "d4c05f6a938f0d56f071ee79ce86d90c24f1b2cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 269.0, "max_issues_repo_issues_event_min_datetime": "2018-05-05T12:31:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:04:11.000Z", "max_forks_repo_path": "gnc/matlab/cxx_functions/src/matrix_multiply.cpp", "max_forks_repo_name": "PeterWofford/astrobee", "max_forks_repo_head_hexsha": "d4c05f6a938f0d56f071ee79ce86d90c24f1b2cb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 248.0, "max_forks_repo_forks_event_min_datetime": "2017-08-31T23:20:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T22:29:16.000Z", "avg_line_length": 33.2727272727, "max_line_length": 110, "alphanum_fraction": 0.7304189435, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5056532430992209}}
{"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#define MTL_VERBOSE_TEST\n\n#include <boost/numeric/mtl/mtl.hpp>\n\n// Commands in Matlab\n// S = sparse(i,j,s,m,n,nzmax)\n// S = sparse(i,j,s,m,n)\n// S = sparse(i,j,s)\n// S = sparse(m,n)\n\nusing mtl::io::tout;\n\ntypedef mtl::compressed2D<double, mtl::mat::unsigned_parameters>         matrix_type;\n\ntemplate <typename Matrix>\ninline void check(const Matrix& A, unsigned m, unsigned n)\n{\n    MTL_THROW_IF(num_rows(A) != m, mtl::unexpected_result(\"Not exact number of rows.\"));\n    MTL_THROW_IF(num_cols(A) != n, mtl::unexpected_result(\"Not exact number of columns.\"));\n    MTL_THROW_IF(A.nnz() != 5, mtl::unexpected_result(\"Not exact number of non-zeros.\"));\n\n    MTL_THROW_IF(A[4][3] != 3.0, mtl::unexpected_result(\"A[4][3] should be 3.\"));\n    MTL_THROW_IF(A[1][6] != 4.0, mtl::unexpected_result(\"A[1][6] should be 4.\"));\n    MTL_THROW_IF(A[1][5] != 0.0, mtl::unexpected_result(\"A[1][5] should be empty.\"));\n}\n\ntemplate <typename SV, typename VV>\ninline void test1(const SV& rows, const SV& cols, const VV& values, unsigned m, unsigned n)\n{\n    matrix_type A;\n    A= make_sparse(rows, cols, values, m, n);\n    tout << \"test1: A is\\n\" << A;\n\n    check(A, m, n);\n}\n\ntemplate <typename SV, typename VV>\ninline void test2(const SV& rows, const SV& cols, const VV& values)\n{\n    matrix_type A;\n    A= make_sparse(rows, cols, values);\n    tout << \"test2: A is\\n\" << A;\n\n    check(A, 5, 7);\n}\n\ninline void test3(unsigned m, unsigned n)\n{\n    matrix_type A;\n    A= mtl::make_sparse(m, n);\n    tout << \"test3: A is\\n\" << A;\n\n    MTL_THROW_IF(num_rows(A) != m, mtl::unexpected_result(\"Not exact number of rows.\"));\n    MTL_THROW_IF(num_cols(A) != n, mtl::unexpected_result(\"Not exact number of columns.\"));\n    MTL_THROW_IF(A.nnz() != 0, mtl::unexpected_result(\"Not exact number of non-zeros.\"));\n\n    MTL_THROW_IF(A[1][5] != 0.0, mtl::unexpected_result(\"A[1][5] should be empty.\"));\n}\n\nint main(int, char**)\n{\n    mtl::dense_vector<unsigned>     rows(7), cols(7);\n    rows= 2, 0, 4, 1, 3, 1, 0;\n    cols= 0, 3, 3, 6, 5, 6, 2;\n\n    mtl::dense_vector<double>       values(7);\n    values= 1, 2, 3, 3, 5, 1, 0;\n\n    test1(rows, cols, values, 6, 8);\n    test2(rows, cols, values);\n    test3(6, 8);\n    \n    return 0;\n}\n", "meta": {"hexsha": "6608717ec93f002e646ca4f7b3c9be5ed2a31712", "size": 2645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/make_sparse_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/make_sparse_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/make_sparse_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.4022988506, "max_line_length": 94, "alphanum_fraction": 0.6378071834, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5056532414533792}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2015 by 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#define ROKKO_ENABLE_TIMER\n\n#include <mpi.h>\n#include <iostream>\n#include <ctime>\n\n#include <rokko/solver.hpp>\n#include <rokko/grid.hpp>\n#include <rokko/distributed_matrix.hpp>\n#include <rokko/localized_vector.hpp>\n\n#include <rokko/utility/frank_matrix.hpp>\n#include <rokko/config.h>\n#include <rokko/utility/timer.hpp>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/asio.hpp>\n\nint main(int argc, char *argv[]) {\n  MPI_Init(&argc, &argv);\n  typedef rokko::matrix_col_major matrix_major;\n  //typedef rokko::matrix_row_major matrix_major;\n\n  if (argc <= 2) {\n    std::cerr << \"error: \" << argv[0] << \" solver_name matrix_size\" << std::endl;\n    MPI_Abort(MPI_COMM_WORLD, 34);\n  }\n\n  rokko::timer timer;\n  timer.registrate( 1, \"diagonalize\");\n  //mkl_set_num_threads(4);\n\n  std::string solver_name(argv[1]);\n  unsigned int dim = boost::lexical_cast<unsigned int>(argv[2]);\n\n  rokko::parallel_dense_solver solver(solver_name);\n  solver.initialize(argc, argv);\n\n  MPI_Comm comm = MPI_COMM_WORLD;\n  rokko::grid g(comm);\n  int myrank = g.get_myrank();\n  int nprocs = g.get_nprocs();\n\n  const int root = 0;\n\n  rokko::distributed_matrix<matrix_major> mat(dim, dim, g, solver);\n\n  rokko::localized_vector w(dim);\n  rokko::distributed_matrix<matrix_major> Z(dim, dim, g, solver);\n\n  for (int count=0; count<3; ++count) {\n    if (myrank == root) {\n      std::cout << \"get_count:\" << timer.get_count(1) << std::endl;\n    }\n    rokko::frank_matrix::generate(mat);\n\n    try {\n      MPI_Barrier(MPI_COMM_WORLD);\n      //timer.start(1);\n      solver.diagonalize(mat, w, Z, timer);\n      MPI_Barrier(MPI_COMM_WORLD);\n      //timer.stop(1);\n    }\n\n    catch (const char *e) {\n      std::cout << \"Exception : \" << e << std::endl;\n      MPI_Abort(MPI_COMM_WORLD, 22);\n    }\n  }\n\n#ifndef NDEBUG\n  if (myrank == root) {\n    std::cout.precision(20);\n    std::cout << \"Computed Eigenvalues= \" << w.transpose() << std::endl;\n  }\n#endif\n\n  if (myrank == 0) {\n    #ifdef _OPENMP\n    std::cout << \"num_procs = \" << nprocs << std::endl;\n    std::cout << \"num_threads = \" << omp_get_max_threads() << std::endl;\n    //std::cout << \"num_threads = \" << mkl_get_num_threads() << std::endl;\n    #endif\n    std::cout << \"solver_name = \" << solver_name << std::endl;\n    std::cout << \"matrix = frank\" << std::endl;\n    std::cout << \"dim = \" << dim << std::endl;\n    std::cout << \"time = \" << timer.get_average(1) << std::endl;\n    std::cout << \"rokko_version = \" << ROKKO_VERSION << std::endl;\n    std::cout << \"hostname = \" << boost::asio::ip::host_name() << std::endl;\n    std::time_t now = std::time(0);\n    std::cout << \"date = \" << ctime(&now)<< std::endl;\n  }\n\n  //timer.summarize();\n\n  solver.finalize();\n  MPI_Finalize();\n  return 0;\n}\n", "meta": {"hexsha": "1435589d6c552f743391e298614ec5bdc703c4c3", "size": 3182, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/dense/frank_mpi_old.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": "benchmark/dense/frank_mpi_old.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": "benchmark/dense/frank_mpi_old.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": 28.6666666667, "max_line_length": 82, "alphanum_fraction": 0.6096794469, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.505653239909986}}
{"text": "/* Copyright (C) 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#include <NTL/ZZ.h>\n#include <algorithm>\n#include <complex>\n\n#include <helib/norms.h>\n#include <helib/helib.h>\n#include <helib/debugging.h>\n#include <helib/ArgMap.h>\n#include <helib/EncryptedArray.h>\n#include <helib/log.h>\n#include <helib/fhe_stats.h>\n\nNTL_CLIENT\nusing namespace helib;\n\nbool verbose = true;\n\nbool reset = false;\n\n\nvoid resetPtxtMag(Ctxt& c, const PtxtArray& p)\n{\n  double maxAbs = NextPow2(Norm(p));\n  c.setPtxtMag(NTL::xdouble(maxAbs));\n}\n\n/************** Each round consists of the following:\ntmp1 = rotate(c0)\ntmp1 += const1\nc0 += const2\nc0 *= tmp1  // c0 = (rotate(c0) + const1)*(c0 + const2) ...squared every round\n\ntmp2 = c1 * const1\nc1 = rotate(c1)\nc1 += tmp2  // c1 = rotate(c1) + c1*const1 ...doubled every round\n\n\ntmp3 = c2 * const2\nc2 *= c3\nc2 += tmp3 // c2 = = c2*c3 + c2*const2 = c2*(c3 + const2)\n\nc3 = c3*const1\n**************/\n\nvoid debugCompare(const SecKey& sk,\n                  const PtxtArray& p,\n                  const Ctxt& c)\n{\n  PtxtArray pp(p.getView());\n  pp.rawDecryptComplex(c, sk);\n\n  double err = Distance(pp, p);\n  double err_bound = c.errorBound();\n  double rel_err = err/Norm(p);\n  //double rel_err = abs_err / Norm(p);\n  std::cout << \"   \"\n            << \" err=\" << err \n            << \" err_bound=\" << err_bound\n            << \" err_bound/err=\" << (err_bound/err)\n            << \" rel_err=\" << rel_err\n            //<< \"   \"\n            //<< \" mag=\" << Norm(p)\n            //<< \" mag_bound=\" << c.getPtxtMag()\n            //<< \" scale=\" << c.getRatFactor()\n            << \"\\n\";\n  if (err > err_bound) std::cout << \"**** BAD BOUND\\n\";\n}\n\n#define DEBUG_COMPARE(C, P, M)                                                 \\\n  do {                                                                         \\\n    if (verbose) {                                                             \\\n      CheckCtxt(C, M);                                                         \\\n      debugCompare(secretKey, P, C);                                           \\\n    }                                                                          \\\n  } while (0)\n\n\n\n\n\nvoid testGeneralOps(const PubKey& publicKey,\n                    const SecKey& secretKey,\n                    long nRounds)\n{\n  const Context& context = publicKey.getContext();\n\n\n  PtxtArray p0(context), p1(context), p2(context), p3(context);\n  p0.random();\n  p1.random();\n  p2.random();\n  p3.random();\n\n  Ctxt c0(publicKey), c1(publicKey), c2(publicKey), c3(publicKey);\n  p0.encrypt(c0);\n  p1.encrypt(c1);\n  p2.encrypt(c2);\n  p3.encrypt(c3);\n\n  HELIB_NTIMER_START(Circuit);\n\n  for (long i = 0; i < nRounds; i++) {\n\n    if (verbose)\n      std::cout << \"*** round \" << i << \"...\" << std::endl;\n\n    if (reset) {\n      resetPtxtMag(c0, p0);\n      resetPtxtMag(c1, p1);\n      resetPtxtMag(c2, p2);\n      resetPtxtMag(c3, p3);\n    }\n\n    DEBUG_COMPARE(c0, p0, \"c0\");\n    DEBUG_COMPARE(c1, p1, \"c1\");\n    DEBUG_COMPARE(c2, p2, \"c2\");\n    DEBUG_COMPARE(c3, p3, \"c3\");\n\n    long nslots = context.zMStar.getNSlots();\n\n    long rotamt = RandomBnd(2 * nslots - 1) - (nslots - 1);\n    // random number in [-(nslots-1)..nslots-1]\n\n    // two random constants\n    PtxtArray const1(context), const2(context);\n    const1.random();\n    const2.random();\n\n    PtxtArray tmp1_p(p0);\n    rotate(tmp1_p, rotamt);\n    Ctxt tmp1(c0);\n    rotate(tmp1, rotamt);\n    DEBUG_COMPARE(tmp1, tmp1_p, \"tmp1 = rotate(c0)\");\n\n    tmp1_p += const1;\n    tmp1 += const1;\n    DEBUG_COMPARE(tmp1, tmp1_p, \"tmp1 += const1\");\n\n    p0 += const2;\n    c0 += const2;\n    DEBUG_COMPARE(c0, p0, \"c0 += const2\");\n\n    p0 *= tmp1_p;\n    c0.multiplyBy(tmp1);\n    DEBUG_COMPARE(c0, p0, \"c0 *= tmp1\");\n\n#if 0\n    runningSums(p0);\n    runningSums(c0);\n    DEBUG_COMPARE(c0, p0, \"totalSums\");\n#endif\n\n#if 0\n    p0 -= 17.5;\n    c0 -= 17.5;\n    DEBUG_COMPARE(c0, p0, \"c0 -= 17.5\");\n\n    p0 *= 1.25;\n    c0 *= 1.25;\n    DEBUG_COMPARE(c0, p0, \"c0 *= 1.25\");\n#endif\n\n    PtxtArray tmp2_p(p1);\n    tmp2_p *= const1;\n    Ctxt tmp2(c1);\n    tmp2 *= const1;\n    DEBUG_COMPARE(tmp2, tmp2_p, \"tmp2 = c1 * const1\");\n\n    rotate(p1, rotamt);\n    rotate(c1, rotamt);\n    DEBUG_COMPARE(c1, p1, \"c1 = rotate(c1)\");\n\n#if 0\n    //std::cerr << \"*********** shamt=\" << rotamt << \"\\n\";\n    //std:: cerr << p1 << \"\\n\";\n    shift(p1, rotamt);\n    //std:: cerr << p1 << \"\\n\";\n    shift(c1, rotamt);\n    DEBUG_COMPARE(c1, p1, \"c1 = shift(c1)\");\n#endif\n\n    p1 += tmp2_p;\n    c1 += tmp2;\n    DEBUG_COMPARE(c1, p1, \"c1 += tmp2\");\n\n    PtxtArray tmp3_p(p2);\n    tmp3_p *= const2;\n    Ctxt tmp3(c2);\n    tmp3 *= const2;\n    DEBUG_COMPARE(tmp3, tmp3_p, \"tmp3 = c2 * const2\");\n\n    p2 *= p3;\n    c2 *= c3;\n    DEBUG_COMPARE(c2, p2, \"c2 *= c3\");\n\n    p2 += tmp3_p;\n    c2 += tmp3;\n    DEBUG_COMPARE(c2, p2, \"c2 += tmp3\");\n\n    p3 *= const1;\n    c3 *= const1;\n    DEBUG_COMPARE(c3, p3, \"c3 *= const1\");\n\n    if (verbose) {\n      // Check correctness after each round\n      PtxtArray pp0(context), pp1(context), pp2(context), pp3(context);\n\n      pp0.rawDecryptComplex(c0, secretKey);\n      pp1.rawDecryptComplex(c1, secretKey);\n      pp2.rawDecryptComplex(c2, secretKey);\n      pp3.rawDecryptComplex(c3, secretKey);\n\n      if (!(pp0 == Approx(p0) && pp1 == Approx(p1) && pp2 == Approx(p2) &&\n          pp3 == Approx(p3))) {\n        std::cout << \"FAIL AT ROUND \" << i << \"\\n\";\n        break;\n      }\n    }\n  }\n\n  HELIB_NTIMER_STOP(Circuit);\n\n  if (verbose) {\n    std::cout << \"===============\\n\";\n\n    DEBUG_COMPARE(c0, p0, \"c0\");\n    DEBUG_COMPARE(c1, p1, \"c1\");\n    DEBUG_COMPARE(c2, p2, \"c2\");\n    DEBUG_COMPARE(c3, p3, \"c3\");\n  }\n\n  PtxtArray pp0(context), pp1(context), pp2(context), pp3(context);\n  PtxtArray ppp0(context), ppp1(context), ppp2(context), ppp3(context);\n\n  pp0.decryptReal(c0, secretKey);\n  pp1.decryptReal(c1, secretKey);\n  pp2.decryptReal(c2, secretKey);\n  pp3.decryptReal(c3, secretKey);\n\n  ppp0.rawDecryptReal(c0, secretKey);\n  ppp1.rawDecryptReal(c1, secretKey);\n  ppp2.rawDecryptReal(c2, secretKey);\n  ppp3.rawDecryptReal(c3, secretKey);\n\n  if (verbose) {\n    std::cout << \"======== rounded/raw differences\\n\";\n    std::cout << Distance(pp0, ppp0) << \"\\n\";\n    std::cout << Distance(pp1, ppp1) << \"\\n\";\n    std::cout << Distance(pp2, ppp2) << \"\\n\";\n    std::cout << Distance(pp3, ppp3) << \"\\n\";\n  }\n\n  if (verbose) {\n    std::cout << \"======== actual/raw differences\\n\";\n    std::cout << Distance(p0, ppp0) << \"\\n\";\n    std::cout << Distance(p1, ppp1) << \"\\n\";\n    std::cout << Distance(p2, ppp2) << \"\\n\";\n    std::cout << Distance(p3, ppp3) << \"\\n\";\n  }\n\n  if (pp0 == Approx(p0) && pp1 == Approx(p1) && pp2 == Approx(p2) &&\n      pp3 == Approx(p3)) \n    std::cout << \"SUCCESS\\n\";\n  else\n    std::cout << \"FAIL\\n\";\n\n\n  if (verbose) {\n    std::cout << std::endl;\n    // printAllTimers();\n    std::cout << std::endl;\n  }\n  resetAllTimers();\n}\n\nint main(int argc, char* argv[])\n{\n  helog.setLogToStderr();\n\n  // Commandline setup\n\n  ArgMap amap;\n\n  long m = 16;\n  long r = 8;\n  long L = 0;\n  double epsilon = 0.01; // Accepted accuracy\n  long R = 1;\n  long seed = 0;\n  bool debug = false;\n\n  amap.arg(\"m\", m, \"Cyclotomic index\");\n  amap.note(\"e.g., m=1024, m=2047\");\n  amap.arg(\"r\", r, \"Bits of precision\");\n  amap.arg(\"R\", R, \"number of rounds\");\n  amap.arg(\"L\", L, \"Number of bits in modulus\", \"heuristic\");\n  amap.arg(\"ep\", epsilon, \"Accepted accuracy\");\n  amap.arg(\"seed\", seed, \"PRG seed\");\n  amap.arg(\"verbose\", verbose, \"more printouts\");\n  amap.arg(\"debug\", debug, \"for debugging\");\n  amap.arg(\"reset\", reset, \"forces calls to setPtxtMag each round\");\n\n  amap.parse(argc, argv);\n\n  if (seed)\n    NTL::SetSeed(ZZ(seed));\n\n  if (R <= 0)\n    R = 1;\n  if (L == 0) {\n    if (R <= 2)\n      L = 100 * R;\n    else\n      L = 220 * (R - 1);\n  }\n\n  if (verbose) {\n    std::cout << \"** m=\" << m << \", #rounds=\" << R << \", |q|=\" << L\n              << \", epsilon=\" << epsilon << std::endl;\n  }\n\n  if (verbose) fhe_stats = true;\n\n  // FHE setup keys, context, SKMs, etc\n\n  Context context(m, /*p=*/-1, r);\n  //context.scale = 4; // why is this 4?\n  buildModChain(context, L);\n\n  SecKey secretKey(context);\n  secretKey.GenSecKey();        // A +-1/0 secret key\n  addSome1DMatrices(secretKey); // compute key-switching matrices\n\n  const PubKey& publicKey = secretKey;\n  //const PubKey publicKey = secretKey;\n\n  if (verbose) {\n    std::cout << \"security=\" << context.securityLevel() << std::endl;\n    context.zMStar.printout();\n    std::cout << \"r = \" << context.alMod.getR() << std::endl;\n    std::cout << \"ctxtPrimes=\" << context.ctxtPrimes\n\t << \", specialPrimes=\" << context.specialPrimes << std::endl\n\t << std::endl;\n  }\n  if (debug) {\n    dbgKey = &secretKey;\n    dbgEa = context.ea;\n  }\n#ifdef HELIB_DEBUG\n  dbgKey = &secretKey;\n  dbgEa = context.ea;\n#endif // HELIB_DEBUG\n\n  // Run the tests.\n  testGeneralOps(publicKey, secretKey, R);\n\n  if (verbose) print_stats(cout);\n\n  return 0;\n}\n", "meta": {"hexsha": "3b46411296158fe78c1e716c1b6241adb38a66ab", "size": 9445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/legacy_tests/tapprox1.cpp", "max_stars_repo_name": "jatanloya/HElib-PSI", "max_stars_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "misc/legacy_tests/tapprox1.cpp", "max_issues_repo_name": "jatanloya/HElib-PSI", "max_issues_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-05T10:55:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-05T12:59:21.000Z", "max_forks_repo_path": "misc/legacy_tests/tapprox1.cpp", "max_forks_repo_name": "jatanloya/HElib-PSI", "max_forks_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "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.3897849462, "max_line_length": 80, "alphanum_fraction": 0.5554261514, "num_tokens": 2964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5056532383665919}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/sincos.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/function/sin.hpp>\n#include <boost/simd/function/cos.hpp>\n\n\nSTF_CASE_TPL (\" sincos\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n\n  using bs::sincos;\n  T a[] = {bs::Zero<T>(), bs::One<T>(), bs::Pio2_3<T>(), bs::Pi<T>(),\n           bs::Pio_2<T>(), bs::Inf<T>(), bs::Minf<T>(), bs::Nan<T>()};\n  size_t N =  sizeof(a)/sizeof(T);\n\n  STF_EXPR_IS( (sincos(T()))\n             , (std::pair<T,T>)\n             );\n\n   {\n    for(size_t i=0; i < N; ++i)\n    {\n      std::pair<T,T> p = sincos(a[i]);\n      STF_IEEE_EQUAL(p.first,  bs::sin(a[i]));\n      STF_IEEE_EQUAL(p.second, bs::cos(a[i]));\n      std::pair<T,T> q = bs::restricted_(bs::sincos)(a[i]);\n      STF_IEEE_EQUAL(q.first,  bs::restricted_(bs::sin)(a[i]));\n      STF_IEEE_EQUAL(q.second, bs::restricted_(bs::cos)(a[i]));\n    }\n   }\n\n}\n", "meta": {"hexsha": "98e05218700161ac95645a75f2e5a2dacec3f5d0", "size": 1579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/sincos.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/scalar/sincos.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/sincos.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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.58, "max_line_length": 100, "alphanum_fraction": 0.5465484484, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5056532351773569}}
{"text": "#ifndef ENCRYPTION_HPP\n#define ENCRYPTION_HPP\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <string>\n\n#include \"big_int_type.hpp\"\n#include \"key_generator.hpp\"\n#include \"mod_exponentiation.hpp\"\n\nunsigned log_b(big_int n);\n\nbig_int text_to_numeric(const std::string &str);\n\nstd::string numeric_to_text(big_int num);\n\nstd::string hash_numeric(big_int num);\n\nbig_int unhash_text(const std::string &str);\n\n/*\n * Data manipulation algorithm.\n */\nvoid data_manipulation(std::string src_path, std::string dst_path, Key key);\n\n/*\n * Encrypts a source file to a destination file.\n */\nvoid encrypt_file(std::string src_path, std::string dst_path, Key pub_key);\n\n/*\n * Decrypts a source file to a destination file.\n */\nvoid decrypt_file(std::string src_path, std::string dst_path, Key priv_key);\n\n#endif", "meta": {"hexsha": "98ceec3e34f12e78503abd7c6b8df2f64e381aa6", "size": 857, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/encryption.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/encryption.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/encryption.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": 21.9743589744, "max_line_length": 76, "alphanum_fraction": 0.7596266044, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5056532351773568}}
{"text": "#pragma once\n#include <dynamic_msgs/State.h>\n#include <Eigen/Dense>\n#include <sp_const.hpp>\n\nnamespace DynamicPlanning {\n    class LinearKalmanFilter{\n    public:\n        void initialize(double _sigma_y_sq, double _sigma_v_sq, double _sigma_a_sq){\n            n = 6; // the number of states\n            m = 3; // the number of observed states\n            phi = 2; // position, velocity\n            sigma_y_sq = _sigma_y_sq;\n            sigma_v_sq = _sigma_v_sq;\n            sigma_a_sq = _sigma_a_sq;\n\n            F = Eigen::MatrixXd::Identity(n, n);\n            B = Eigen::MatrixXd::Zero(n, n/phi);\n\n            Q = Eigen::MatrixXd::Zero(n, n);\n//            Q.block(0, 0, n/phi, n/phi) = Eigen::MatrixXd::Identity(n/phi, n/phi) * sigma_y_sq;\n//            Q.block(n/phi, n/phi, n/phi, n/phi) = Eigen::MatrixXd::Identity(n/phi, n/phi) * sigma_v_sq;\n\n            H = Eigen::MatrixXd::Zero(m, n);\n            H.block(0, 0, m, m) = Eigen::MatrixXd::Identity(m, m);\n            R = Eigen::MatrixXd::Identity(m, m) * sigma_y_sq;\n\n            P = Eigen::MatrixXd::Zero(n, n);\n            P.block(0, 0, n/phi, n/phi) = Eigen::MatrixXd::Identity(n/phi, n/phi) * 10;\n            P.block(n/phi, n/phi, n/phi, n/phi) = Eigen::MatrixXd::Identity(n/phi, n/phi) * 10;\n\n            Y = Eigen::VectorXd(m);\n            X_hat = Eigen::VectorXd(n);\n\n            isFirstInput = true;\n        }\n\n        dynamic_msgs::Obstacle filter(const dynamic_msgs::Obstacle& obstacle, ros::Time current_update_time){\n            // Observe\n            Y << obstacle.pose.position.x, obstacle.pose.position.y, obstacle.pose.position.z;\n\n            if(isFirstInput){\n                X_hat << Y, 0, 0, 0;\n                isFirstInput = false;\n            }\n            else{\n                // Update F\n                dt = (current_update_time - prev_update_time).toSec();\n                F.block(0, n/phi, n/phi, n/phi) = Eigen::MatrixXd::Identity(n/phi, n/phi) * dt;\n                B.block(n/phi, 0, n/phi, n/phi) = Eigen::MatrixXd::Identity(n/phi, n/phi) * dt;\n                Q = sigma_a_sq * B * B.transpose();\n//                Q.block(0, 0, n/phi, n/phi) = Eigen::MatrixXd::Identity(n/phi, n/phi) * sigma_y_sq;\n\n                // Predict\n                X_hat_update = F * X_hat;\n                Eigen::MatrixXd P_update = F * P * F.transpose() + Q;\n\n                // Kalman Gain\n                Eigen::MatrixXd S = H * P_update * H.transpose() + R;\n                Eigen::MatrixXd K = P_update * H.transpose() * S.inverse();\n\n                // Update\n                X_hat = X_hat_update + K * (Y - H * X_hat_update);\n                P = P_update - K * H * P_update;\n            }\n\n            dynamic_msgs::Obstacle result = obstacle;\n            result.pose.position.x = X_hat(0, 0);\n            result.pose.position.y = X_hat(1, 0);\n            result.pose.position.z = X_hat(2, 0);\n            result.velocity.linear.x = X_hat(3, 0);\n            result.velocity.linear.y = X_hat(4, 0);\n            result.velocity.linear.z = X_hat(5, 0);\n\n//            double v = sqrt(pow(result.velocity.linear.x, 2) + pow(result.velocity.linear.y, 2) + pow(result.velocity.linear.z, 2));\n//            std::cout << \"dt: \" << dt << \", v: \" << v << std::endl;\n\n            prev_update_time = current_update_time;\n            return result;\n        }\n\n        Eigen::MatrixXd getPositionCovariance(){\n            return P.block(0, 0, n/phi, n/phi);\n        }\n\n        double getUncertaintyRadius(double t_delta){\n            F.block(0, n/phi, n/phi, n/phi) = Eigen::MatrixXd::Identity(n/phi, n/phi) * t_delta;\n            B.block(n/phi, 0, n/phi, n/phi) = Eigen::MatrixXd::Identity(n/phi, n/phi) * t_delta;\n            Q = sigma_a_sq * B * B.transpose();\n            Eigen::MatrixXd P_update = F * P * F.transpose() + Q;\n\n            Eigen::MatrixXd SIGMA = P_update.block(0, 0, n/phi, n/phi);\n            double uncertainty_radius = 1.33 * sqrt(2.0 * (double)SIGMA.trace()); //TODO: consider vector direction\n            return uncertainty_radius;\n        }\n\n    private:\n        int n, m, phi;\n        double sigma_y_sq, sigma_v_sq, sigma_a_sq, dt;\n        Eigen::MatrixXd F, B, Q, H, R, P;\n        Eigen::VectorXd Y, X_hat, X_hat_update;\n\n        bool isFirstInput;\n        ros::Time prev_update_time;\n    };\n}", "meta": {"hexsha": "cfdadf9d7b191f353b3047eb898e2b49600400bf", "size": 4281, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kalman_filter.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/kalman_filter.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/kalman_filter.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.3867924528, "max_line_length": 134, "alphanum_fraction": 0.5316514833, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.505629683099496}}
{"text": "/* Boost interval/detail/division.hpp file\r\n *\r\n * Copyright Guillaume Melquiond, Sylvain Pion 2003\r\n * Permission to use, copy, modify, sell, and distribute this software\r\n * is hereby granted without fee provided that the above copyright notice\r\n * appears in all copies and that both that copyright notice and this\r\n * permission notice appear in supporting documentation,\r\n *\r\n * None of the above authors make any representation about the\r\n * suitability of this software for any purpose. It is provided \"as\r\n * is\" without express or implied warranty.\r\n *\r\n * $Id: division.hpp,v 1.3 2003/02/05 17:34:32 gmelquio Exp $\r\n */\r\n\r\n#ifndef BOOST_NUMERIC_INTERVAL_DETAIL_DIVISION_HPP\r\n#define BOOST_NUMERIC_INTERVAL_DETAIL_DIVISION_HPP\r\n\r\n#include <boost/numeric/interval/detail/interval_prototype.hpp>\r\n#include <boost/numeric/interval/detail/bugs.hpp>\r\n#include <boost/numeric/interval/rounded_arith.hpp>\r\n#include <algorithm>\r\n\r\nnamespace boost {\r\nnamespace numeric {\r\nnamespace interval_lib {\r\nnamespace detail {\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> div_non_zero(const interval<T, Policies>& x,\r\n                                   const interval<T, Policies>& y)\r\n{\r\n  // assert(!in_zero(y));\r\n  typename Policies::rounding rnd;\r\n  typedef interval<T, Policies> I;\r\n  const T& xl = x.lower();\r\n  const T& xu = x.upper();\r\n  const T& yl = y.lower();\r\n  const T& yu = y.upper();\r\n  if (is_neg(xu))\r\n    if (is_neg(yu))\r\n      return I(rnd.div_down(xu, yl), rnd.div_up(xl, yu), true);\r\n    else\r\n      return I(rnd.div_down(xl, yl), rnd.div_up(xu, yu), true);\r\n  else if (is_neg(xl))\r\n    if (is_neg(yu))\r\n      return I(rnd.div_down(xu, yu), rnd.div_up(xl, yu), true);\r\n    else\r\n      return I(rnd.div_down(xl, yl), rnd.div_up(xu, yl), true);\r\n  else\r\n    if (is_neg(yu))\r\n      return I(rnd.div_down(xu, yu), rnd.div_up(xl, yl), true);\r\n    else\r\n      return I(rnd.div_down(xl, yu), rnd.div_up(xu, yl), true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> div_non_zero(const T& x, const interval<T, Policies>& y)\r\n{\r\n  // assert(!in_zero(y));\r\n  typename Policies::rounding rnd;\r\n  typedef interval<T, Policies> I;\r\n  const T& yl = y.lower();\r\n  const T& yu = y.upper();\r\n  if (is_neg(x))\r\n    return I(rnd.div_down(x, yl), rnd.div_up(x, yu), true);\r\n  else\r\n    return I(rnd.div_down(x, yu), rnd.div_up(x, yl), true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> div_positive(const interval<T, Policies>& x, const T& yu)\r\n{\r\n  // assert(yu > T(0));\r\n  if (is_zero(x)) return x;\r\n  typename Policies::rounding rnd;\r\n  typedef interval<T, Policies> I;\r\n  const T& xl = x.lower();\r\n  const T& xu = x.upper();\r\n  typedef typename Policies::checking checking;\r\n  const T& inf = checking::inf();\r\n  if (is_neg(xu))\r\n    return I(-inf, rnd.div_up(xu, yu), true);\r\n  else if (is_neg(xl))\r\n    return I(-inf, inf, true);\r\n  else\r\n    return I(rnd.div_down(xl, yu), inf, true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> div_positive(const T& x, const T& yu)\r\n{\r\n  // assert(yu > T(0));\r\n  typedef interval<T, Policies> I;\r\n  if (is_zero(x)) return I(0, 0, true);\r\n  typename Policies::rounding rnd;\r\n  typedef typename Policies::checking checking;\r\n  const T& inf = checking::inf();\r\n  if (is_neg(x))\r\n    return I(-inf, rnd.div_up(x, yu), true);\r\n  else\r\n    return I(rnd.div_down(x, yu), inf, true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> div_negative(const interval<T, Policies>& x, const T& yl)\r\n{\r\n  // assert(yl < T(0));\r\n  if (is_zero(x.lower()) && is_zero(x.upper()))\r\n    return x;\r\n  typename Policies::rounding rnd;\r\n  typedef interval<T, Policies> I;\r\n  const T& xl = x.lower();\r\n  const T& xu = x.upper();\r\n  typedef typename Policies::checking checking;\r\n  const T& inf = checking::inf();\r\n  if (is_neg(xu))\r\n    return I(rnd.div_down(xu, yl), inf, true);\r\n  else if (is_neg(xl))\r\n    return I(-inf, inf, true);\r\n  else\r\n    return I(-inf, rnd.div_up(xl, yl), true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> div_negative(const T& x, const T& yl)\r\n{\r\n  // assert(yl < T(0));\r\n  typedef interval<T, Policies> I;\r\n  if (is_zero(x)) return I(0, 0, true);\r\n  typename Policies::rounding rnd;\r\n  typedef typename Policies::checking checking;\r\n  const T& inf = checking::inf();\r\n  if (is_neg(x))\r\n    return I(rnd.div_down(x, yl), inf, true);\r\n  else\r\n    return I(-inf, rnd.div_up(x, yl), true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> div_zero(const interval<T, Policies>& x)\r\n{\r\n  if (is_zero(x.lower()) && is_zero(x.upper()))\r\n    return x;\r\n  else return interval<T, Policies>::whole();\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> div_zero(const T& x)\r\n{\r\n  if (is_zero(x)) return interval<T, Policies>(0, 0, true);\r\n  else return interval<T, Policies>::whole();\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> div_zero_part1(const interval<T, Policies>& x,\r\n                                     const interval<T, Policies>& y, bool& b)\r\n{\r\n  // assert(y.lower() < 0 && y.upper() > 0);\r\n  if (is_zero(x.lower()) && is_zero(x.upper()))\r\n    { b = false; return x; }\r\n  typename Policies::rounding rnd;\r\n  typedef interval<T, Policies> I;\r\n  const T& xl = x.lower();\r\n  const T& xu = x.upper();\r\n  const T& yl = y.lower();\r\n  const T& yu = y.upper();\r\n  typedef typename I::checking checking;\r\n  const T& inf = checking::inf();\r\n  if (is_neg(xu))\r\n    { b = true;  return I(-inf, rnd.div_up(xu, yu), true); }\r\n  else if (is_neg(xl))\r\n    { b = false; return I(-inf, inf, true); }\r\n  else\r\n    { b = true;  return I(-inf, rnd.div_up(xl, yl), true); }\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> div_zero_part2(const interval<T, Policies>& x,\r\n                                     const interval<T, Policies>& y)\r\n{\r\n  // assert(y.lower() < 0 && y.upper() > 0 && (div_zero_part1(x, y, b), b));\r\n  typename Policies::rounding rnd;\r\n  typedef interval<T, Policies> I;\r\n  typedef typename I::checking checking;\r\n  const T& inf = checking::inf();\r\n  if (is_neg(x.upper()))\r\n    return I(rnd.div_down(x.upper(), y.lower()), inf, true);\r\n  else\r\n    return I(rnd.div_down(x.lower(), y.upper()), inf, true);\r\n}\r\n\r\n} // namespace detail\r\n} // namespace interval_lib\r\n} // namespace numeric\r\n} // namespace boost\r\n\r\n#endif // BOOST_NUMERIC_INTERVAL_DETAIL_DIVISION_HPP\r\n", "meta": {"hexsha": "111756a04d08cfad2cd65791b269325f6264fba1", "size": 6436, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/boost/numeric/interval/detail/division.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T06:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:24:28.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/boost/numeric/interval/detail/division.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/boost/numeric/interval/detail/division.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-17T10:01:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-11T20:17:27.000Z", "avg_line_length": 32.3417085427, "max_line_length": 80, "alphanum_fraction": 0.6364201367, "num_tokens": 1784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.505601901394797}}
{"text": "/*  This file is part of libDAI - http://www.libdai.org/\n *\n *  Copyright (c) 2006-2011, The libDAI authors. All rights reserved.\n *\n *  Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.\n */\n\n\n#include <dai/factorgraph.h>\n#include <iostream>\n#include <fstream>\n#include <dai/util.h>\n#include <dai/alldai.h>\n#include <fstream>\n#include \"dai/emrun.h\"\n#include <dai/util.h>\n#include <string>\n#include <sys/stat.h>\n#include <time.h>\n#include <iomanip>      // std::setprecision\n#include <sstream>\n#include <cstdlib>\n#include <algorithm>\n#include<math.h>\n#include <string>\n#include <iostream>\n\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\nusing namespace std;\nusing namespace dai;\n// Define a random number generator and initialize it with a reproducible\n// seed.\nmt19937 generator(42);\n\n// Define a uniform random number distribution which produces \"double\"\n// values between 0 and 1 (0 inclusive, 1 exclusive).\nboost::uniform_real<> uni_dist(0,1);\nboost::variate_generator<mt19937&, boost::uniform_real<> > uni(generator, uni_dist);\nint main() {\n    // This example program illustrates how to construct a factorgraph\n    // by means of the sprinkler network example discussed at\n    // http://www.cs.ubc.ca/~murphyk/Bayes/bnintro.html\n\n    Var C(0, 2);  // Define binary variable Cloudy (with label 0)\n    Var S(1, 2);  // Define binary variable Sprinkler (with label 1)\n    Var R(2, 2);  // Define binary variable Rain (with label 2)\n    Var W(3, 2);  // Define binary variable Wetgrass (with label 3)\n\n    // Define probability distribution for C\n    Factor P_C( C );\n    P_C.set(0, 0.5);   // C = 0\n    P_C.set(1, 0.5);   // C = 1\n    \n    // Define conditional probability of R given C\n    Factor P_R_given_C( VarSet( R, C ) );\n    P_R_given_C.set(0, 0.8);   // C = 0, R = 0\n    P_R_given_C.set(1, 0.2);   // C = 1, R = 0\n    P_R_given_C.set(2, 0.2);   // C = 0, R = 1\n    P_R_given_C.set(3, 0.8);   // C = 1, R = 1\n\n    // Define conditional probability of S given C\n    Factor P_S_given_C( VarSet( S, C ) );\n    P_S_given_C.set(0, 0.5);   // C = 0, S = 0\n    P_S_given_C.set(1, 0.9);   // C = 1, S = 0\n    P_S_given_C.set(2, 0.5);   // C = 0, S = 1\n    P_S_given_C.set(3, 0.1);   // C = 1, S = 1\n\n    // Define conditional probability of W given S and R\n    Factor P_W_given_S_R( VarSet( S, R ) | W );\n    P_W_given_S_R.set(0, 1.0);  // S = 0, R = 0, W = 0\n    P_W_given_S_R.set(1, 0.1);  // S = 1, R = 0, W = 0\n    P_W_given_S_R.set(2, 0.1);  // S = 0, R = 1, W = 0\n    P_W_given_S_R.set(3, 0.01); // S = 1, R = 1, W = 0\n    P_W_given_S_R.set(4, 0.0);  // S = 0, R = 0, W = 1\n    P_W_given_S_R.set(5, 0.9);  // S = 1, R = 0, W = 1\n    P_W_given_S_R.set(6, 0.9);  // S = 0, R = 1, W = 1\n    P_W_given_S_R.set(7, 0.99); // S = 1, R = 1, W = 1\n\n    // Build factor graph consisting of those four factors\n    vector<Factor> SprinklerFactors;\n    SprinklerFactors.push_back( P_C );\n    SprinklerFactors.push_back( P_S_given_C );\n    SprinklerFactors.push_back( P_R_given_C );\n    SprinklerFactors.push_back( P_W_given_S_R );\n    FactorGraph SprinklerNetwork( SprinklerFactors );\n    FactorGraph SprinklerNetwork1( SprinklerFactors );\n    // Write factorgraph to a file\n    SprinklerNetwork.WriteToFile( \"sprinkler.fg\" );\n    cout << \"Sprinkler network written to sprinkler.fg\" << endl;\n\n    // Output some information about the factorgraph\n    cout << SprinklerNetwork.nrVars() << \" variables\" << endl;\n    cout << SprinklerNetwork.nrFactors() << \" factors\" << endl;\n\n //Code for mutation\n    for( size_t I = 0; I < SprinklerNetwork.nrFactors(); I++ )\n    {\n        int no_states = SprinklerNetwork.factor( I ).nrStates();// total no. of states\n        int no_arr_arrset =0; // factor_states\n        int arr_size =1; //states of parents before factor_pos\n        int arr_set =0; //states of parents after factor_pos\n        int arr_set_states =0; // no. of states till factor_pos\n        \n        cout<<SprinklerNetwork.factor( I ).nrStates()<<endl;\n        Factor P = SprinklerNetwork.factor( I );\n        VarSet vs = P.vars();\n        cout<<\"vars = \"<<vs<<endl;\n        cout << \"{\";\n        for( VarSet::const_iterator v = vs.begin(); v != vs.end(); v++ )\n        {\n            cout << (v != vs.begin() ? \", \" : \"\") << *v;\n            if(v->label() == I)\n            {\n                cout<<\" states = \"<<v->states()<<endl;\n                no_arr_arrset = v->states();\n                arr_set_states = arr_size * v->states();\n                break;\n            }\n            arr_size = arr_size * v->states();\n        }\n        cout << \"}\"<<endl;\n        arr_set = no_states/arr_set_states;\n        dai::TProb<double> myvector = P.p();\n        \n        for (dai::TProb<double>::iterator it = myvector.begin();it != myvector.end(); ++it)\n            std::cout << ' ' << *it;\n        std::cout << '\\n';\n//        cout<<\"no. of states \"<<no_states<<\"\\t\"<<\"array set \"<<arr_set<<\"\\t\"<<\"no_arr_arrset \"<<no_arr_arrset<<\"\\t\"<<\"array size \"<<arr_size<<endl;\n        int k=0;\n        while(k<arr_set)\n        {\n            //Random values are generated---~----~----\n            std::vector< double * > Arrays1;\n            for(int l=0; l<no_arr_arrset; l++)\n            {\n                Arrays1.push_back( new double[arr_size]);\n            }\n            vector<double*>::iterator it;\n            for(int m=0; m<arr_size; m++)\n            {\n                it=Arrays1.begin();\n                std::vector<double> vec;\n                for(int i=0; i<no_arr_arrset; i++)\n                {\n                    vec.push_back(uni());\n                }\n                const double total = std::accumulate(vec.begin(), vec.end(), 0.0);\n                for (double& value: vec)\n                {\n                    double* arr = *it;\n                    value /= total;\n                    arr[m] = value;\n                    ++it;\n                    //cout<<value <<endl;\n                }\n                // cout<<endl;\n                vec.clear();\n            }\n            //Random values are generated---x----x----\n            //Random or actual values will be updated -----~------~\n            vector<double*>::iterator it11;\n            it11=Arrays1.begin();\n            int stat=0;\n            for(int l=0; l<no_arr_arrset; l++)\n            {\n                double* arr = *it11;\n                for(int m=0; m<arr_size; m++)\n                {\n                    stringstream v;\n                    v << fixed << setprecision(12) << arr[m];\n                    //c1<<stat<<\"   \"<<v.str()<<endl;\n                    //cout<< \"replaced\"<<v.str()<<endl;\n                    P.set(stat,arr[m]);\n                    stat++;\n                }\n                ++it11;\n            }\n            //Random values are updated ------x------x--------\n            k++;\n        }\n        \n        SprinklerNetwork.setFactor(I,P);\n        dai::TProb<double> myvector1 = P.p();\n        \n        for (dai::TProb<double>::iterator it1 = myvector1.begin() ; it1 != myvector1.end(); ++it1)\n            std::cout << ' ' << *it1;\n        std::cout << '\\n';\n        \n    }\n    // Code for crossover\n    \n    int population_size=2;\n    // compute crossover probability\n    double pcross = uni(); // generates random a value between 0 and 1\n\tcout<<\"Crossover probability \"<<pcross;\n\t// 4. Select 2 parents randomly\n\tconst int LOW = 0;\n\tconst int HIGH = population_size-1;\n    set<int> myset;\n\tset<int>::iterator it;\n    int *arrval;\n\tsize_t p=0;\n\tarrval = new int[population_size];\n    /*Declare variable to hold seconds on clock.*/\n\ttime_t seconds;\n\t/*Get value from system clock and place in seconds variable.*/\n\ttime(&seconds);\n\t/*Convert seconds to a unsigned integer.*/\n\tsrand(time(0));\n    for( size_t n = 0; n < population_size; n++ )\n\t{\n        int val = rand() % (HIGH - LOW + 1) + LOW;\n        it=myset.find(val);\n        arrval[n] = val;\n        if(it==myset.end()) // if the value is not in the set\n        {\n            myset.insert(val);\n            p++;\n            if(p == 2)\n            {\n                cout <<\" Random value is\"<<arrval[n]<<\" and \"<< arrval[n-1];\n                // randomly select a crossover point\n                int cr_pt = (rand() % SprinklerNetwork.nrVars()) +1;\n                int c = 0; // count of parameters\n                int p_c1 = 0, p_c2 =0; // counter to skip the first four config lines in the cpt of the fg file\n                cout<<\" Crossover point is \"<< cr_pt<<endl;\n                p=0;\n                for( size_t I = cr_pt; I < SprinklerNetwork.nrFactors(); I++ )\n                {\n                    Factor P = SprinklerNetwork.factor( I );\n                    dai::TProb<double> myvector = P.p();\n                    Factor P1 = SprinklerNetwork1.factor( I );\n                    dai::TProb<double> myvector1 = P1.p();\n                    dai::TProb<double>::iterator it1 = myvector1.begin();\n                    dai::TProb<double>::iterator it = myvector.begin();\n                    for (int state=0;state<myvector.size();state++)\n                    {\n                        P.set(state,*it1);\n                        P1.set(state,*it);\n                        ++it1;++it;\n                    }\n                    SprinklerNetwork.setFactor(I,P);\n                    SprinklerNetwork1.setFactor(I,P1);\n                }\n            }\n        }\n        else\n        {\n            n=n-1;\n            continue;\n        }\n    }\n    // Calculate joint probability of all four variables\n    Factor P2;\n    for( size_t I = 0; I < SprinklerNetwork.nrFactors(); I++ )\n    {\n        cout<<SprinklerNetwork.factor( I ).nrStates()<<endl;\n        P2 = SprinklerNetwork.factor( I );\n        dai::TProb<double> myvector = P2.p();\n\n        for (dai::TProb<double>::iterator it = myvector.begin() ; it != myvector.end(); ++it)\n            std::cout << ' ' << *it;\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    Factor P3;\n    for( size_t I = 0; I < SprinklerNetwork1.nrFactors(); I++ )\n    {\n        cout<<SprinklerNetwork1.factor( I ).nrStates()<<endl;\n        P3 = SprinklerNetwork1.factor( I );\n        dai::TProb<double> myvector = P3.p();\n        \n        for (dai::TProb<double>::iterator it = myvector.begin() ; it != myvector.end(); ++it)\n            std::cout << ' ' << *it;\n        std::cout << '\\n';\n    }\n//        P.randomize();\n//        P.normalized();\n//        dai::TProb<double> myvector1 = P.p();\n//        \n//        for (dai::TProb<double>::iterator it1 = myvector1.begin() ; it1 != myvector1.end(); ++it1)\n//            std::cout << ' ' << *it1;\n        std::cout << '\\n';\n//        VarSet vs = P.vars();\n//        cout<<\"vars = \"<<vs<<endl;\n//        cout << \"{\";\n//        for( VarSet::const_iterator v = vs.begin(); v != vs.end(); v++ )\n//        {\n//            cout << (v != vs.begin() ? \", \" : \"\") << *v;\n////            std::string result,result1;\n////            result = name + boost::lexical_cast<std::string>(I);\n////            result1 = \"\"+boost::lexical_cast<std::string>(*v);\n////            cout<<\" factor = \"<<result<<\" \"<<v->label()<<endl;\n//            \n//            if(v->label() == I)\n//            {\n//                cout<<\" states = \"<<v->states()<<endl;\n//            }\n//        }\n//        cout << \"}\"<<endl;\n        //size_t f =SprinklerNetwork.findVar(v);\n        //cout<<\"factor index \"<<f<<endl;\n       // P *= SprinklerNetwork.factor( I );\n//    }// P.normalize();  // Not necessary: a Bayesian network is already normalized by definition\n//    // Calculate some probabilities\n//    Real denom = P.marginal( W )[1];\n//    //VarSet v = P.vars();\n//    //cout<<\"vars = \"<<v<<endl;\n//   \n//    //for( size_t n = 0; n < v.nrStates(); X_n++ )\n//        //cout<<\" vars inside \"<<*X_n<<endl;\n//    //cout<<P.marginal( *X_n )<<\" \"<< P.marginal( W )[1]<<endl;\n//    cout<<P.normalize()<<endl;\n//    cout << \"P(W=1) = \" << denom << endl;\n//    cout << \"P(S=1 | W=1) = \" << P.marginal( VarSet( S, W ) )[3] / denom << endl;\n//    cout << \"P(R=1 | W=1) = \" << P.marginal( VarSet( R, W ) )[3] / denom << endl;\n//\n    return 0;\n}\n", "meta": {"hexsha": "a076812cdad5af99c958ab258dfa0598cd262a8d", "size": 12099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example_sprinkler.cpp", "max_stars_repo_name": "Priyaaks/libDAI_P", "max_stars_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "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/example_sprinkler.cpp", "max_issues_repo_name": "Priyaaks/libDAI_P", "max_issues_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "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/example_sprinkler.cpp", "max_forks_repo_name": "Priyaaks/libDAI_P", "max_forks_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "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": 37.691588785, "max_line_length": 149, "alphanum_fraction": 0.5093809406, "num_tokens": 3387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.505601901394797}}
{"text": "/*! \\file numeric_limits_handling.hpp\n    \\brief Functions to check if data values are NaN or infinity or denormalised.\n    \\details\n      Since only double is used, template versions are not needed,\n      and TR1 should provide max, min, denorm_min, infinity and isnan,\n      but older compilers and libraries may not provide all these.\n\n      Better to use boost::math throughout?  Done?\n\n    \\author Jacob Voytko and Paul A. Bristow\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A. Bristow 2007, 2013\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_SVG_NUMERIC_LIMITS_HANDLING_DETAIL_HPP\n#define BOOST_SVG_NUMERIC_LIMITS_HANDLING_DETAIL_HPP\n\n#include <boost/math/special_functions/fpclassify.hpp>\n\n#include <boost/quan/unc.hpp>\n// using boost::quan::uncun ...\n#include <boost/quan/meas.hpp>\n// using boost::quan Meas;\n\n#include <limits>\n  // using std::numeric_limits;\n#include <cmath> // Why?\n\nnamespace boost\n{\nnamespace svg\n{\nnamespace detail\n{\n  // Provide checks on data values to be plotted.\n  // Test if at max or +infinity, or -max or - infinity, or NaN.\n\n// std::numeric_limits<double>::min() or denorm min() are just ignored as almost zero (which is an OK value).\n\nconstexpr double margin = 4.;  //!< Consider values close to std::numeric_limits<double>::max() as maximum to try to take account of computation errors.\n\nusing boost::quan::unc;\nusing boost::quan::Meas;\n\ninline bool limit_max(double a)\n{ //! At (or near) max value or +infinity, most positive values.\n    return ((a > (std::numeric_limits<double>::max)() / margin) // Avoid macro max trap!\n         || (std::isinf(a)));\n        // || (a == std::numeric_limits<double>::infinity()));\n}\n\ninline bool limit_min(double a)\n{ //! At (or near) -max or -infinity, most negative values.\n  return (\n    (a < -(std::numeric_limits<double>::max)() /margin) // Avoid macro max trap!\n    || (a == -std::numeric_limits<double>::infinity())\n    );\n}\n\n// Allow NaNs to be displayed differently from just too big or too small values.\ninline bool limit_NaN(double a)\n{ //! Separate test for NaNs.\n  using std::isnan;\n  return isnan(a) ? true : false;\n  // Ternary operator used to remove warning about casting int to bool.\n}\n\ninline bool is_limit(double a)\n{ //! Is at some limit.\n  return limit_max(a) || limit_min(a) || limit_NaN(a);\n}\n\ninline bool pair_is_limit(std::pair<const double, double> a)\n{ //! Check on both x and y double data points. Return false if either or both are at limit.\n  return limit_max(a.first) || limit_min(a.first) || limit_NaN(a.first)\n    || limit_max(a.second) || limit_min(a.second) || limit_NaN(a.second);\n}\n\ninline bool pair_is_limit(std::pair<double, double> a)\n{ //! Check on both x and y double data points. Return false if either or both are at limit.\n  return limit_max(a.first) || limit_min(a.first) || limit_NaN(a.first)\n    || limit_max(a.second) || limit_min(a.second) || limit_NaN(a.second);\n}\n\ninline bool pair_is_limit(std::pair<const int, double> a)\n{ //! Check on both x int and y double data points. Return false if either or both are at limit.\n  return limit_max(a.first) || limit_min(a.first) // || limit_NaN(a.first) - can't be NaN if int.\n    || limit_max(a.second) || limit_min(a.second) || limit_NaN(a.second);\n}\n\ninline bool pair_is_limit(std::pair<int, double> a)\n{ //! Check on both x int and y double data points. Return false if either or both are at limit.\n  return limit_max(a.first) || limit_min(a.first) // || limit_NaN(a.first) - can't be NaN if int.\n    || limit_max(a.second) || limit_min(a.second) || limit_NaN(a.second);\n}\n\ntemplate <bool correlated>\ninline bool pair_is_limit(std::pair<const unc<correlated>, unc<correlated> > a)\n{ //! Check on values of both x and y unc data points.\n  // \\return false if either or both are at limit.\n  return limit_max(value_of(a.first)) || limit_min(value_of(a.first)) || limit_NaN(value_of(a.first))\n    || limit_max(value_of(a.second)) || limit_min(value_of(a.second)) || limit_NaN(value_of(a.second));\n}\n\ntemplate <bool correlated>\ninline bool pair_is_limit(std::pair<Meas, unc<correlated> > a) // const version\n{ //! Check on values of both x Meas and y unc data points.\n  // \\return false if either or both are at limit.\n  return limit_max(value_of(a.first)) || limit_min(value_of(a.first)) || limit_NaN(value_of(a.first))\n    || limit_max(value_of(a.second)) || limit_min(value_of(a.second)) || limit_NaN(value_of(a.second));\n}\n\ntemplate <bool correlated>\ninline bool pair_is_limit(std::pair<const Meas, unc<correlated> > a)\n{ //! Check on values of both x Meas and y unc data points.\n  // \\return false if either or both are at limit.\n    double rounddown2(double value); // 2, 4,\n  return limit_max(value_of(a.first)) || limit_min(value_of(a.first)) || limit_NaN(value_of(a.first))\n    || limit_max(value_of(a.second)) || limit_min(value_of(a.second)) || limit_NaN(value_of(a.second));\n}\n\n} // namespace detail\n} // namespace svg\n} // namespace boost\n\n// Defines :\n/*\nbool boost::svg::detail::limit_max(double); // true if max or +infinity.\nbool boost::svg::detail::limit_min(double); // true if min, denorm_min or -infinity.\nbool boost::svg::detail::limit_NaN(double); // true if NaN.\nbool boost::svg::detail::is_limit(double); // max, min, infinity or NaN - not a 'proper' data value.\nbool boost::svg::detail::pair_is_limit(std::pair<double, double>); // x and/or y  not a proper data value.\nbool boost::svg::detail::pair_is_limit(std::pair<const double, double>); // x and/or y  not a proper data value.\n\ntemplate <bool correlated>\nbool boost::svg::detail::pair_is_limit(std::pair<const unc<correlated>, unc<correlated> >); // x and/or y not a proper data value!\n*/\n#endif // BOOST_SVG_NUMERIC_LIMITS_HANDLING_DETAIL_HPP\n", "meta": {"hexsha": "5e6481d8628cd8c915c151545a4ad3c7d4924868", "size": 5864, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/svg_plot/detail/numeric_limits_handling.hpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "include/boost/svg_plot/detail/numeric_limits_handling.hpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "include/boost/svg_plot/detail/numeric_limits_handling.hpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 40.4413793103, "max_line_length": 152, "alphanum_fraction": 0.7051500682, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5056018964574548}}
{"text": "#ifndef TOOLS_HPP\n#define TOOLS_HPP\n\n#include <vector>\n#include <Eigen/Dense>\n\n\nusing namespace Eigen;\nusing namespace std;\n\ndouble pi();\ndouble deg2rad(double x);\ndouble rad2deg(double x);\n\ndouble distance(double x1, double y1, double x2, double y2);\ndouble norm(double x, double y);\ndouble norm(double x, double y, double z);\ndouble mph2mps(double mph);\ndouble mps2mph(double mps);\n\nint getLane(const double d, const double laneWidth=4.0);\ndouble getLaneOffsetD(const int lane_number, const double laneWidth=4.0);\n\nvector<double> polyfit(vector<double> &xvals, vector<double> &yvals, int order);\nEigen::VectorXd polyfit(Eigen::VectorXd &xvals, Eigen::VectorXd &yvals, int order);\n\nvector<double> polyeval(vector<double> &coeffs, vector<double> &x);\ndouble polyeval(vector<double> &coeffs, double x);\ndouble polyeval(Eigen::VectorXd coeffs, double x);\n\nvector<double> polyfit_wp(int wp_start, int wp_stop, int order,\n\t\t\t\t\t\t  vector<double> &map_x, vector<double> &map_y);\n\nvector<double> JMT(vector< double> start, vector <double> end, double T);\n\n //define TOOLS_HPP\n #endif", "meta": {"hexsha": "d3446e106b6cbf05af7641b2a942a880eec850f2", "size": 1076, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tools.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/tools.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/tools.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": 29.0810810811, "max_line_length": 83, "alphanum_fraction": 0.750929368, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5056018877834106}}
{"text": "#include \"conex/exponential_map.h\"\n\n#include \"conex/jordan_matrix_algebra.h\"\n#include \"gtest/gtest.h\"\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n\nnamespace conex {\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nusing JordanTypes = testing::Types<Real, Complex, Quaternions>;\n\ntemplate <typename T>\nHyperComplexMatrix RandomOrthogonal(int n) {\n  return T::Orthogonalize(T::Random(n, n));\n}\n\ntemplate <typename T>\nHyperComplexMatrix BuildMatrix(const VectorXd& eigenvalues,\n                               const HyperComplexMatrix& Q) {\n  int n = eigenvalues.rows();\n  assert(n = Q.at(0).rows());\n  auto D = T::Zero(n, n);\n  D.at(0).diagonal() = eigenvalues;\n  return T::Multiply(T::Multiply(Q, D), T::ConjugateTranspose(Q));\n}\n\nGTEST_TEST(ExponentialMapPadeApproximation, CompareWithEigen) {\n  int n = 4;\n  MatrixXd A(n, n);\n  A << 3, 1, 0, 1, 1, 3, 1, 0, 0, 1, 4, 1, 1, 0, 1, 5;\n  A = A * .001;\n\n  MatrixXd reference = A.exp();\n  MatrixXd calculated(n, n);\n\n  HyperComplexMatrix arg(1);\n  arg.at(0) = A;\n  HyperComplexMatrix result(1);\n  ExponentialMap(arg, &result);\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      EXPECT_NEAR(reference(i, j), result.at(0)(i, j), 1e-7);\n    }\n  }\n}\n\ntemplate <typename T>\nclass TestCases : public testing::Test {\n public:\n  void CompareWithReference() {\n    int n = 4;\n    VectorXd eigenvalues(n);\n    eigenvalues << -.1, .1, .1, .01;\n    auto Q = RandomOrthogonal<T>(n);\n    auto arg = BuildMatrix<T>(eigenvalues, Q);\n    auto reference = BuildMatrix<T>(eigenvalues.array().exp(), Q);\n\n    auto result = T::Zero(n, n);\n    ExponentialMap(arg, &result);\n    for (size_t k = 0; k < result.size(); k++) {\n      for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n          // TODO(FrankPermenter): reduce this threshold.\n          EXPECT_NEAR(reference.at(k)(i, j), result.at(k)(i, j), 1e-4);\n        }\n      }\n    }\n  }\n};\n\nTYPED_TEST_CASE(TestCases, JordanTypes);\nTYPED_TEST(TestCases, MultiplyByIdentity) {\n  TestFixture::CompareWithReference();\n}\n\ntemplate <typename T>\ntypename T::Matrix Symmetrize(const typename T::Matrix& x) {\n  auto y = T::Add(x, T::ConjugateTranspose(x));\n  y = T::ScalarMultiply(y, .5);\n  return y;\n}\n\nGTEST_TEST(TestCases, GeodesicUpdateOctonions) {\n  using T = Octonions;\n  int order = 3;\n  auto s = Symmetrize<T>(T::Random(order, order));\n  auto w = T::Identity(order);\n  s = T::Add(w, T::ScalarMultiply(s, .1));\n\n  auto y = GeodesicUpdate(w, s);\n  EXPECT_TRUE(\n      (VectorXd(T::Eigenvalues(s).array().exp()) - T::Eigenvalues(y)).norm() <\n      1e-3);\n\n  auto d = T::Zero(order, order);\n  for (int i = 0; i < 3; i++) {\n    d.at(0)(i, i) = 1 + i * .02;\n  }\n  y = GeodesicUpdate(T::Identity(order), d);\n  for (int i = 0; i < order; i++) {\n    EXPECT_NEAR(y.at(0)(i, i), d.at(0).diagonal().array().exp()(i), 1e-4);\n  }\n}\n\nVectorXd sort(const VectorXd& x) {\n  auto y = x;\n  std::sort(y.data(), y.data() + x.rows());\n  return y;\n}\n\nGTEST_TEST(TestCases, GeodesicUpdateRescaling) {\n  using T = Octonions;\n  int order = 3;\n  auto wsqrt = Symmetrize<T>(T::Random(order, order));\n  // auto w = T::Multiply(wsqrt, wsqrt);\n  auto w = T::Identity(order);\n  auto s = Symmetrize<T>(T::Random(order, order));\n  s = T::Add(T::Identity(order), T::ScalarMultiply(s, .05));\n  s = T::ScalarMultiply(s, -1);\n\n  auto yref = T::ScalarMultiply(GeodesicUpdate(w, s), std::exp(1));\n  auto ycalc = GeodesicUpdateScaled(w, s);\n\n  auto eig_ref = T::Eigenvalues(yref);\n  auto eig_calc = T::Eigenvalues(ycalc);\n  for (int i = 0; i < order; i++) {\n    EXPECT_TRUE(eig_calc(i) >= 0);\n    EXPECT_NEAR(eig_ref(i), eig_calc(i), 1e-2);\n  }\n}\n\n}  // namespace conex\n", "meta": {"hexsha": "bf3e7aa1102612a54a076371278a8ee770ed7943", "size": 3660, "ext": "cc", "lang": "C++", "max_stars_repo_path": "conex/test/exponential_map_test.cc", "max_stars_repo_name": "frankpermenter/conex", "max_stars_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T20:41:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T20:41:20.000Z", "max_issues_repo_path": "conex/test/exponential_map_test.cc", "max_issues_repo_name": "frankpermenter/conex", "max_issues_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conex/test/exponential_map_test.cc", "max_forks_repo_name": "frankpermenter/conex", "max_forks_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_forks_repo_licenses": ["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.7153284672, "max_line_length": 78, "alphanum_fraction": 0.6166666667, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.5056018816454282}}
{"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//[return_envelope\r\n//` Shows how to return the envelope of a ring\r\n\r\n#include <iostream>\r\n\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/box.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/ring.hpp>\r\n\r\n#include <boost/assign.hpp>\r\n\r\n/*<-*/ #include \"create_svg_two.hpp\" /*->*/\r\n\r\nint main()\r\n{\r\n    using namespace boost::assign;\r\n\r\n    typedef boost::geometry::model::d2::point_xy<double> point;\r\n\r\n    boost::geometry::model::ring<point> ring;\r\n    ring +=\r\n        point(4.0, -0.5), point(3.5, 1.0),\r\n        point(2.0, 1.5), point(3.5, 2.0),\r\n        point(4.0, 3.5), point(4.5, 2.0),\r\n        point(6.0, 1.5), point(4.5, 1.0),\r\n        point(4.0, -0.5);\r\n\r\n    typedef boost::geometry::model::box<point> box;\r\n\r\n    std::cout\r\n        << \"return_envelope:\"\r\n        << boost::geometry::dsv(boost::geometry::return_envelope<box>(ring))\r\n        << std::endl;\r\n\r\n    /*<-*/ create_svg(\"return_envelope.svg\", ring, boost::geometry::return_envelope<box>(ring)); /*->*/\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[return_envelope_output\r\n/*`\r\nOutput:\r\n[pre\r\nreturn_envelope:((2, -0.5), (6, 3.5))\r\n\r\n[$img/algorithms/return_envelope.png]\r\n]\r\n*/\r\n//]\r\n\r\n", "meta": {"hexsha": "a376d58700a95b1fa3ef11caa06d4953e554fbfb", "size": 1556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/algorithms/return_envelope.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/geometry/doc/src/examples/algorithms/return_envelope.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/doc/src/examples/algorithms/return_envelope.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": 24.3125, "max_line_length": 104, "alphanum_fraction": 0.6214652956, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.5056018741720243}}
{"text": "#ifndef HAMILTONIANS_XXZSTO_HPP\n#define HAMILTONIANS_XXZSTO_HPP\n#include <Eigen/Eigen>\n#include <nlohmann/json.hpp>\n\n/* H = XX - \\Delta YY - ZZ\n * H = -\\Delta XX - YY + ZZ ?\n * */\nclass XXZSto\n{\nprivate:\n\tint n_;\n\tdouble J_;\n\tdouble Delta_;\n\npublic:\n\n\tXXZSto(int n, double J, double Delta)\n\t\t: n_(n), J_(J), Delta_(Delta)\n\t{\n\t}\n\n\tnlohmann::json params() const\n\t{\n\t\treturn nlohmann::json\n\t\t{\n\t\t\t{\"name\", \"XXZSto\"},\n\t\t\t{\"n\", n_},\n\t\t\t{\"J\", J_},\n\t\t\t{\"Delta\", Delta_}\n\t\t};\n\t}\n\t\n\ttemplate<class State>\n\ttypename State::Scalar operator()(const State& smp) const\n\t{\n\t\ttypename State::Scalar s = 0.0;\n\t\t//Nearest-neighbor\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tint zz = smp.sigmaAt(i)*smp.sigmaAt((i+1)%n_);\n\t\t\ts += J_*zz; //zz\n\t\t\ts += J_*(-Delta_+zz)*smp.ratio(i, (i+1)%n_); //xx+yy\n\t\t}\n\t\treturn s;\n\t}\n\n\tstd::map<uint32_t, double> operator()(uint32_t col) const\n\t{\n\t\tstd::map<uint32_t, double> m;\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tint b1 = (col >> i) & 1;\n\t\t\tint b2 = (col >> ((i+1)%n_)) & 1;\n\t\t\tint zz = (1-2*b1)*(1-2*b2);\n\t\t\tlong long int x = (1 << i) | (1 << ((i+1)%(n_)));\n\t\t\tm[col] += J_*zz;\n\t\t\tm[col ^ x] += J_*(-Delta_ + zz);\n\t\t}\n\t\treturn m;\n\t}\n};\n#endif//HAMILTONIANS_XXZSTO_HPP\n", "meta": {"hexsha": "ce0e61187231b2fb6b8b0fb33fb1641e3882ac9b", "size": 1180, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Hamiltonians/XXZSto.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/Hamiltonians/XXZSto.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/Hamiltonians/XXZSto.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": 18.4375, "max_line_length": 58, "alphanum_fraction": 0.556779661, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.5055797089574121}}
{"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_ARCH_COMMON_SCALAR_FUNCTION_COSH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_COSH_HPP_INCLUDED\n#include <boost/simd/function/std.hpp>\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/detail/constant/maxlog.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/average.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( cosh_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const std_tag &,  A0  a0) const BOOST_NOEXCEPT\n    {\n      return std::cosh(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( cosh_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_<bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      //////////////////////////////////////////////////////////////////////////////\n      // if x = abs(a0) according x < Threshold e =  exp(x) or exp(x/2) is\n      // respectively computed\n      // *  in the first case cosh (e+rec(e))/2\n      // *  in the second     cosh is (e/2)*e (avoiding undue overflow)\n      // Threshold is Maxlog - Log_2\n      //////////////////////////////////////////////////////////////////////////////\n      A0 x = bs::abs(a0);\n      auto test1 = (x > Maxlog<A0>()-Log_2<A0>());\n      A0 fac =test1 ? Half<A0>() : One<A0>();\n      A0 tmp = exp(x*fac);\n      A0 tmp1 = Half<A0>()*tmp;\n      return test1 ?tmp1*tmp : bs::average(tmp, rec(tmp));\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "3a61d36fd7940dc5fb063fad953307846c7b693d", "size": 2512, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/cosh.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/arch/common/scalar/function/cosh.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/arch/common/scalar/function/cosh.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": 34.4109589041, "max_line_length": 100, "alphanum_fraction": 0.5127388535, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.5055797083993634}}
{"text": "// (C) 2014 Arek Olek\n\n#include <random>\n#include <vector>\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include \"debug.hpp\"\n#include \"options.hpp\"\n#include \"range.hpp\"\n\ntemplate <class Vertex, class Graph>\nVertex random_neighbor(Vertex const & v, Graph const & G) {\n  unsigned target = random<unsigned>(0, out_degree(v, G)-1);\n  for(auto w : range(adjacent_vertices(v, G)))\n    if(target-- == 0) return w;\n  assert(false);\n}\n\ntemplate <class Graph>\nunsigned random_walk(Graph const & G, unsigned v, unsigned t) {\n  unsigned steps = 0;\n  while(v != t) {\n    v = random_neighbor(v, G);\n    ++steps;\n  }\n  return steps;\n}\n\ntemplate<class Graph>\nvoid barbell(Graph& G) {\n  auto n = num_vertices(G);\n  auto m = n / 3;\n  for(int i = 0; i < m; ++i) {\n    for(int j = i+1; j < m; ++j) {\n      add_edge(i, j, G);\n      add_edge(i+2*m, j+2*m, G);\n    }\n    add_edge(i+m, i+m+1, G);\n  }\n  add_edge(m-1, m, G);\n}\n\nboost::adjacency_list<boost::hash_setS, boost::vecS, boost::undirectedS> typedef alist;\n\nint main(int argc, char** argv) {\n  options opt(argc, argv);\n  const auto z = opt.get<int>(\"-z\", 100);\n  auto n = 3*opt.get<int>(\"-m\", 5);\n  alist g(n);\n  barbell(g);\n  std::vector<int> degrees;\n  for(auto v : range(vertices(g))) degrees.push_back(degree(v, g));\n  std::default_random_engine gen;\n  std::discrete_distribution<> pi(degrees.begin(), degrees.end());\n  for(int i = 0; i < z; ++i)\n    std::cout << n << '\\t' << random_walk(g, pi(gen), pi(gen)) << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "b5d821b1f0ebabe1688bcdc8e261e0c8c31969a0", "size": 1475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "prototype/barbell.cpp", "max_stars_repo_name": "arekolek/MaxIST", "max_stars_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prototype/barbell.cpp", "max_issues_repo_name": "arekolek/MaxIST", "max_issues_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prototype/barbell.cpp", "max_forks_repo_name": "arekolek/MaxIST", "max_forks_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_forks_repo_licenses": ["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.5833333333, "max_line_length": 87, "alphanum_fraction": 0.6176271186, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5055797034338398}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <scorum/protocol/odds.hpp>\n\n#include \"defines.hpp\"\n\n#include <scorum/protocol/config.hpp>\n\n#include <limits>\n\nnamespace odds_tests {\nusing namespace scorum;\nusing namespace scorum::protocol;\n\nBOOST_AUTO_TEST_SUITE(odds_tests)\n\nBOOST_AUTO_TEST_CASE(odds_positive_creation_check)\n{\n    auto base_fraction = utils::make_fraction(400, 300);\n    odds k = base_fraction;\n\n    BOOST_CHECK_EQUAL(k.base(), base_fraction);\n    BOOST_CHECK_EQUAL(k.simplified(), utils::make_fraction(4, 3));\n    BOOST_CHECK_EQUAL(k.inverted(), utils::make_fraction(4, 1));\n\n    BOOST_CHECK_NO_THROW(odds(utils::make_fraction(std::numeric_limits<int16_t>::max(), 2)));\n}\n\nBOOST_AUTO_TEST_CASE(odds_negative_creation_check)\n{\n    BOOST_REQUIRE_EQUAL(sizeof(odds_value_type), sizeof(uint32_t));\n\n    BOOST_CHECK_NO_THROW(odds(utils::make_fraction(std::numeric_limits<int32_t>::max(), 2)));\n    BOOST_CHECK_THROW(odds(utils::make_fraction(std::numeric_limits<uint32_t>::max(), 2)), fc::assert_exception);\n    BOOST_CHECK_THROW(odds(utils::make_fraction(std::numeric_limits<int64_t>::max(), 2)), fc::overflow_exception);\n\n    BOOST_CHECK_THROW(odds(utils::make_fraction(-2, 1)), fc::assert_exception);\n    BOOST_CHECK_THROW(odds(utils::make_fraction(2, -1)), fc::assert_exception);\n    BOOST_CHECK_THROW(odds(utils::make_fraction(-2, -1)), fc::assert_exception);\n    BOOST_CHECK_THROW(odds(utils::make_fraction(2, 0)), fc::assert_exception);\n    BOOST_CHECK_THROW(odds(utils::make_fraction(0, 1)), fc::assert_exception);\n    BOOST_CHECK_THROW(odds(utils::make_fraction(0, 0)), fc::assert_exception);\n\n    BOOST_CHECK_NO_THROW(odds(utils::make_fraction(2, 1)));\n}\n\nBOOST_AUTO_TEST_CASE(odds_str_check)\n{\n    BOOST_CHECK_THROW(odds::from_string(\"\"), fc::exception);\n    BOOST_CHECK_THROW(odds::from_string(\"230\"), fc::exception);\n    BOOST_CHECK_THROW(odds::from_string(\"aaaaaaaaa/30\"), fc::exception);\n    BOOST_CHECK_THROW(odds::from_string(\"2147483648/1\"), fc::exception);\n    BOOST_CHECK_THROW(odds::from_string(\"30/10000000\"), fc::exception);\n\n    const std::string str = \"30/2\";\n\n    odds k = odds::from_string(str);\n\n    BOOST_CHECK_EQUAL(k.simplified(), utils::make_fraction(15, 1));\n\n    BOOST_CHECK_EQUAL(k.to_string(), str);\n}\n\nBOOST_AUTO_TEST_CASE(odds_variant_check)\n{\n    odds k = utils::make_fraction(40, 30);\n\n    fc::variant vk;\n\n    BOOST_REQUIRE_NO_THROW(fc::to_variant(k, vk));\n\n    odds k2;\n\n    BOOST_REQUIRE_NO_THROW(fc::from_variant(vk, k2));\n\n    BOOST_CHECK_EQUAL(k, k2);\n}\n\nBOOST_AUTO_TEST_CASE(odds_cast_to_fraction_check)\n{\n    odds k = utils::make_fraction(40, 30);\n\n    BOOST_CHECK_EQUAL((odds_fraction_type)k, utils::make_fraction(4, 3));\n}\n\nBOOST_AUTO_TEST_CASE(odds_empty_check)\n{\n    odds k;\n\n    BOOST_CHECK(!k);\n\n    BOOST_CHECK_THROW(k.base(), fc::assert_exception);\n    BOOST_CHECK_THROW(k.simplified(), fc::assert_exception);\n    BOOST_CHECK_THROW(k.inverted(), fc::assert_exception);\n\n    BOOST_CHECK_NE(k, odds(2, 1));\n    BOOST_CHECK_EQUAL(k, odds());\n}\n\nBOOST_AUTO_TEST_CASE(min_odds_to_string)\n{\n    odds k = SCORUM_MIN_ODDS;\n\n    BOOST_CHECK_EQUAL(\"1001/1000\", k.to_string());\n}\n\nBOOST_AUTO_TEST_CASE(max_odds_to_string)\n{\n    odds k = SCORUM_MIN_ODDS.inverted();\n\n    BOOST_CHECK_EQUAL(\"1001/1\", k.to_string());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n}\n", "meta": {"hexsha": "e3c52940c5bb4e197a6728dc0dc487b5282af000", "size": 3304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/utests/odds_tests.cpp", "max_stars_repo_name": "scorum/scorum", "max_stars_repo_head_hexsha": "1da00651f2fa14bcf8292da34e1cbee06250ae78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2017-10-28T22:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T02:20:48.000Z", "max_issues_repo_path": "tests/utests/odds_tests.cpp", "max_issues_repo_name": "Scorum/Scorum", "max_issues_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2017-11-25T09:06:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-31T09:17:22.000Z", "max_forks_repo_path": "tests/utests/odds_tests.cpp", "max_forks_repo_name": "Scorum/Scorum", "max_forks_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2018-01-08T19:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T10:50:42.000Z", "avg_line_length": 28.4827586207, "max_line_length": 114, "alphanum_fraction": 0.7324455206, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5055797028757912}}
{"text": "#include <boost/lexical_cast.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <vector>\n\nusing namespace std;\n\nclass RpnCalculator {\nprivate:\n    vector<double> stack;\n\npublic:\n    void push(string arg) {\n        if (arg == \"+\") {\n            push(pop() + pop());\n        } else if (arg == \"-\") {\n            double subtrahend = pop();\n            push(pop() - subtrahend);\n        } else if (arg == \"*\") {\n            push(pop() * pop());\n        } else if (arg == \"/\") {\n            double denominator = pop();\n            push(pop() - denominator);\n        } else {\n            double value = boost::lexical_cast<double>(arg);\n            push(value);\n        }\n    }\n\n    void pi() {\n        stack.push_back(boost::math::constants::pi<double>());\n    }\n\n    double value() {\n        return stack.back();\n    }\n\nprivate:\n    double pop() {\n        double v = stack.back();\n        stack.pop_back();\n        return v;\n    }\n\n    void push(double v) {\n        stack.push_back(v);\n    }\n};\n\n", "meta": {"hexsha": "f9aba64526af0b5a80fa88bcb107c379a56145c7", "size": 1001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "features/support/RpnCalculator.cpp", "max_stars_repo_name": "meshell/cucumber-cpp", "max_stars_repo_head_hexsha": "a41565d8fd7b87fd160e441602b398dc76f6d739", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 214.0, "max_stars_repo_stars_event_min_datetime": "2015-01-09T05:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:51:23.000Z", "max_issues_repo_path": "features/support/RpnCalculator.cpp", "max_issues_repo_name": "meshell/cucumber-cpp", "max_issues_repo_head_hexsha": "a41565d8fd7b87fd160e441602b398dc76f6d739", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 186.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T15:52:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T21:16:01.000Z", "max_forks_repo_path": "features/support/RpnCalculator.cpp", "max_forks_repo_name": "meshell/cucumber-cpp", "max_forks_repo_head_hexsha": "a41565d8fd7b87fd160e441602b398dc76f6d739", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 120.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T15:40:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T17:56:29.000Z", "avg_line_length": 20.4285714286, "max_line_length": 62, "alphanum_fraction": 0.4885114885, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5055796923866952}}
{"text": "#include \"../../blas/test/blas.hpp\"\n#include <boost/numeric/bindings/lapack/computational/getrf.hpp>\n#include <boost/numeric/bindings/lapack/computational/getri.hpp>\n#include <boost/numeric/bindings/lapack/computational/getrs.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n\ntemplate < typename matrix_type >\nvoid test_getrf_getrs(matrix_type& lu, matrix_type& x)\n{\n  typedef typename matrix_type::value_type value_type ;\n\n  numerics::matrix< value_type > a(lu) ;   // tmp to verify result\n  numerics::matrix< value_type > b(x) ;    // tmp to verify result\n  std::vector< fortran_int_t > ipiv(x.size1()) ;\n\n  boost::numeric::bindings::lapack::getrf(lu, ipiv) ;\n  matrix_type ia(lu);\n  boost::numeric::bindings::lapack::getrs(lu, ipiv, x) ;\n  boost::numeric::bindings::lapack::getri(ia, ipiv) ;\n\n  std::cout << prod(a,x) - b << std::endl ;\n  std::cout << prod(a,ia) << std::endl ;\n}\n\ntemplate < typename value_type, typename orientation, int size >\nvoid test_getrf_getrs_matrix()\n{\n  numerics::matrix< value_type, orientation > a(size,size) ;\n  random_initialise_matrix(a) ;\n\n  numerics::matrix< value_type, orientation > b(size,1) ;\n  random_initialise_matrix(b) ;\n\n  test_getrf_getrs(a, b) ;\n}\n\nint main()\n{\n  const int size = 5 ;\n\n  test_getrf_getrs_matrix< double, numerics::column_major, size >() ;\n  test_getrf_getrs_matrix< std::complex< double >, numerics::column_major, size >() ;\n\n  /*\n    test_getrf_getrs_matrix< double, numerics::row_major, size >() ;\n    test_getrf_getrs_matrix< std::complex< double >, numerics::row_major, size >() ;\n  */\n\n  return 0 ;\n}\n", "meta": {"hexsha": "488009bb8cea47848864ed837d6d5a769303d004", "size": 1627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_getrf_getrs1.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_getrf_getrs1.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_getrf_getrs1.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": 31.2884615385, "max_line_length": 85, "alphanum_fraction": 0.7098955132, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5055796923866952}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser 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 *     PCMSolver 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 Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#include \"catch.hpp\"\n\n#include <cmath>\n#include <iostream>\n\n\n#include <Eigen/Core>\n\n#include \"AnalyticEvaluate.hpp\"\n#include \"bi_operators/CollocationIntegrator.hpp\"\n#include \"green/DerivativeTypes.hpp\"\n#include \"green/Vacuum.hpp\"\n\nTEST_CASE(\"Evaluation of the vacuum Green's function and its derivatives\", \"[green][green_vacuum]\")\n{\n    Eigen::Vector3d source = Eigen::Vector3d::Random();\n    Eigen::Vector3d sourceNormal = source + Eigen::Vector3d::Random();\n    sourceNormal.normalize();\n    Eigen::Vector3d probe = Eigen::Vector3d::Random();\n    Eigen::Vector3d probeNormal = probe + Eigen::Vector3d::Random();\n    probeNormal.normalize();\n    Eigen::Array4d result = analyticVacuum(sourceNormal, source, probeNormal, probe);\n\n    /*! \\class Vacuum\n     *  \\test \\b VacuumTest_numerical tests the numerical evaluation of the Vacuum Green's function against analytical result\n     */\n    SECTION(\"Numerical derivative\")\n    {\n        Vacuum<Numerical, CollocationIntegrator> gf;\n        double value = result(0);\n        double gf_value = gf.kernelS(source, probe);\n        REQUIRE(value == Approx(gf_value));\n\n        double derProbe = result(1);\n        double gf_derProbe = gf.derivativeProbe(probeNormal, source, probe);\n        REQUIRE(derProbe == Approx(gf_derProbe));\n\n        double derSource = result(2);\n        double gf_derSource = gf.derivativeSource(sourceNormal, source, probe);\n        REQUIRE(derSource == Approx(gf_derSource));\n    }\n\n    /*! \\class Vacuum\n     *  \\test \\b VacuumTest_directional_AD tests the automatic evaluation (directional derivative only)\n     *  of the Vacuum Green's function against analytical result\n     */\n    SECTION(\"Directional derivative via AD\")\n    {\n        Vacuum<> gf;\n        double value = result(0);\n        double gf_value = gf.kernelS(source, probe);\n        REQUIRE(value == Approx(gf_value));\n\n        double derProbe = result(1);\n        double gf_derProbe = gf.derivativeProbe(probeNormal, source, probe);\n        REQUIRE(derProbe == Approx(gf_derProbe));\n\n        double derSource = result(2);\n        double gf_derSource = gf.derivativeSource(sourceNormal, source, probe);\n        REQUIRE(derSource == Approx(gf_derSource));\n    }\n\n    /*! \\class Vacuum\n     *  \\test \\b VacuumTest_gradient_AD tests the automatic evaluation (full gradient)\n     *  of the Vacuum Green's function against analytical result\n     */\n    SECTION(\"Gradient via AD\")\n    {\n        Vacuum<AD_gradient, CollocationIntegrator> gf;\n        double value = result(0);\n        double gf_value = gf.kernelS(source, probe);\n        REQUIRE(value == Approx(gf_value));\n\n        double derProbe = result(1);\n        double gf_derProbe = gf.derivativeProbe(probeNormal, source, probe);\n        REQUIRE(derProbe == Approx(gf_derProbe));\n\n        double derSource = result(2);\n        double gf_derSource = gf.derivativeSource(sourceNormal, source, probe);\n        REQUIRE(derSource == Approx(gf_derSource));\n    }\n\n    /*! \\class Vacuum\n     *  \\test \\b VacuumTest_hessian_AD tests the automatic evaluation (full hessian)\n     *  of the Vacuum Green's function against analytical result\n     */\n    SECTION(\"Hessian via AD\")\n    {\n        Vacuum<AD_hessian, CollocationIntegrator> gf;\n        double value = result(0);\n        double gf_value = gf.kernelS(source, probe);\n        REQUIRE(value == Approx(gf_value));\n\n        double derProbe = result(1);\n        double gf_derProbe = gf.derivativeProbe(probeNormal, source, probe);\n        REQUIRE(derProbe == Approx(gf_derProbe));\n\n        double derSource = result(2);\n        double gf_derSource = gf.derivativeSource(sourceNormal, source, probe);\n        REQUIRE(derSource == Approx(gf_derSource));\n\n        /*\tdouble hessian = result(4);\n            double gf_hessian = gf.hessian(sourceNormal, source, probeNormal, probe);\n            REQUIRE(hessian == Approx(gf_hessian));\n            */\n    }\n}\n", "meta": {"hexsha": "e415cb8e367152dfd37045facf4d3d1b7c57c194", "size": 5000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/tests/green/green_vacuum.cpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/tests/green/green_vacuum.cpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/tests/green/green_vacuum.cpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["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.5939849624, "max_line_length": 125, "alphanum_fraction": 0.6688, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5055796918286468}}
{"text": "#include \"fieldedgepass.hh\"\n\n#include <Eigen/Core>\n\n#include \"../../Config/config.hh\"\n#include \"../../geometry/halfhullbuilder.hh\"\n\nusing namespace bold;\nusing namespace Eigen;\nusing namespace std;\n\nFieldEdgePass::FieldEdgePass(string id, ushort imageWidth, ushort imageHeight)\n  : ImagePassHandler(id),\n    d_imageWidth(imageWidth),\n    d_imageHeight(imageHeight)\n{\n  Config::getSetting<int>(\"vision.field-edge-pass.min-vertical-run-length\")->track([this](int value) { d_minVerticalRunLength = (ushort)value; });\n  d_useConvexHull = Config::getSetting<bool>(\"vision.field-edge-pass.use-convex-hull\");\n}\n\nvoid FieldEdgePass::applyConvexHull(vector<short>& points, unsigned fromIndex, unsigned toIndex)\n{\n  ASSERT(toIndex < points.size());\n\n  vector<Matrix<float,2,1>> input;\n  for (unsigned c = fromIndex; c <= toIndex; c++)\n    input.emplace_back(c, points[c]);\n\n  auto output = HalfHullBuilder<float>().findHalfHull(input, HalfHull::Top);\n\n  // The convex hull output has fewer columns than the input.\n  // Walk through both the columnar data and the hull output,\n  // filling any missing column values with interpolations.\n\n  unsigned outputIndex = 0;\n  unsigned lastMatchedColumn = fromIndex;\n\n  for (unsigned c = fromIndex; c <= toIndex; c++)\n  {\n    if (output[outputIndex].x() == c)\n    {\n      // This column's value is unchanged by the hull operation.\n      // Its value is part of the hull\n\n      for (unsigned fillC = lastMatchedColumn + 1; fillC < c; fillC++)\n      {\n        double ratio = 1.0 - (double)(c - fillC)/(c - lastMatchedColumn);\n        points[fillC] = Math::lerp(ratio, points[lastMatchedColumn], points[c]);\n      }\n\n      lastMatchedColumn = c;\n      outputIndex++;\n    }\n  }\n}\n", "meta": {"hexsha": "9cffe88035cce187cc6c6685e082ded4ba8f8076", "size": 1706, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ImagePassHandler/FieldEdgePass/fieldedgepass.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": "ImagePassHandler/FieldEdgePass/fieldedgepass.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": "ImagePassHandler/FieldEdgePass/fieldedgepass.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": 30.4642857143, "max_line_length": 146, "alphanum_fraction": 0.6887456038, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.505579691270598}}
{"text": "#ifndef __ROCKET_FLIGHT_DM_HH__\n#define __ROCKET_FLIGHT_DM_HH__\n/********************************* TRICK HEADER *******************************\nPURPOSE:\n      (Describe the Rocket Flgiht Dynamics Module Variables and Algorithm)\nLIBRARY DEPENDENCY:\n      ((../src/Rocket_Flight_DM.cpp)\n       (../../math/src/nrutil.cpp))\nPROGRAMMERS:\n      (((Lai Jun Xu) () () () ))\n*******************************************************************************/\n#include <armadillo>\n#include \"aux.hh\"\n#include \"cadac_constants.hh\"\n#include \"numerical_constants.hh\"\n#include \"time_management.hh\"\n#include \"vehicle.hh\"\n#include \"vehicle_var.hh\"\n\nclass Rocket_Flight_DM : public FH_module\n{\n    TRICK_INTERFACE(Rocket_Flight_DM);\n\npublic:\n    Rocket_Flight_DM();\n    //struct icf_ctrlblk_t *dm_icf_info_hook;\n    // int enqueue_to_simgen_buffer(struct icf_ctrlblk_t *C, double\n    // ext_porlation); int stand_still_motion_data(struct icf_ctrlblk_t *C, double\n    // ext_porlation);\n\n    virtual void init(LaunchVehicle *VehicleIn);\n    virtual void algorithm(LaunchVehicle *VehicleIn);\n\n    void set_reference_point_eq_xcg();\n\n    struct TX_data {\n        double SBEE[3];\n        double VBEE[3];\n        double ABEE[3];\n        double JBEE[3];\n        double psibd;\n        double thtbd;\n        double phibd;\n        double WBEB[3];\n    } TX_data_forward;\n\n    void set_DOF(int ndof);\n    void set_aero_flag(unsigned int in);\n\nprivate:\n    // void propagate_position_speed_acceleration(double int_step);\n    void propagate_aeroloss(LaunchVehicle *VehicleIn);\n    void propagate_gravityloss(LaunchVehicle *VehicleIn);\n    void propagate_control_loss(LaunchVehicle *VehicleIn);\n    void orbital(DM_var *VarIn);\n    void aux_calulate(arma::mat33 TEI, double int_step, DM_var *VarIn);\n    void RK4F(std::vector<arma::vec> Var_in, std::vector<arma::vec> &Var_out,\n              LaunchVehicle *VehicleIn);\n    void reference_point_calc(DM_var *D, Prop_var *P);\n    void collect_forces_and_propagate(LaunchVehicle *VehicleIn);\n\n    double calculate_alphaix(arma::vec3 VBIB);\n    double calculate_betaix(arma::vec3 VBIB);\n    double calculate_alppx(arma::vec3 VBAB_in, double dvba);\n    double calculate_phipx(arma::vec3 VBAB_in);\n    double calculate_alphax(arma::vec3 VBAB_in);\n    double calculate_betax(arma::vec3 VBAB, double dvba);\n\n    arma::vec build_VBEB(double _alpha0x, double _beta0x, double dvbe);\n    arma::mat calculate_TBD(LaunchVehicle *VehicleIn);\n\n    void gamma_beta(DM_var *VarIn);\n    void Gravity_Q(LaunchVehicle *VehicleIn);\n    void AeroDynamics_Q(LaunchVehicle *VehicleIn);\n    void calculate_I1(LaunchVehicle *VehicleIn);\n    void funcv(int n, double *x, double *ff, LaunchVehicle *VehicleIn);\n    void broydn(double x[], int n, int *check, LaunchVehicle *VehicleIn);\n    void rsolv(double **a, int n, double d[], double b[]);\n    void fdjac(int n, double x[], double fvec_in[], double **df,\n               LaunchVehicle *VehicleIn);\n    double f_min(double x[], LaunchVehicle *VehicleIn);\n    void lnsrch(int n, double xold[], double fold, double g[], double p[],\n                double x[], double *f_in, double stpmax, int *check,\n                LaunchVehicle *VehicleIn);\n    void qrdcmp(double **a, int n, double *c, double *d, int *sing);\n    void qrupdt(double **r, double **qt, int n, double u[], double v[]);\n    void rotate(double **r, double **qt, int n, int i, double a, double b);\n\n    unsigned int Interpolation_Extrapolation_flag;\n    int its;                  /* *o (--) Number of iterations */\n    int DOF;                  /* *o (--)  Number of Degree of Freedom */\n    int reference_point_flag; /* *o (--)  check if reference point equal to xcg */\n    unsigned int Aero_flag;   /* *o (-)  Aerodynamics flag */\n};\n\ntemplate <typename T>\nvoid IntegratorRK4(std::vector<arma::vec> V_in, std::vector<arma::vec> &V_out,\n                   void (T::*fp)(std::vector<arma::vec> Var_in,\n                                 std::vector<arma::vec> &Var_out,\n                                 LaunchVehicle *VehicleIn),\n                   T *ClassPointer, LaunchVehicle *VehicleIn, double int_step)\n{\n    {\n        std::vector<std::vector<arma::vec>> KMAT;\n        for (unsigned int i = 0; i < V_in.size(); i++) {\n            std::vector<arma::vec> KROW(4);\n            KMAT.push_back(KROW);\n        }\n\n        V_out = V_in;\n\n        ((ClassPointer)->*fp)(V_out, KMAT[0], VehicleIn);\n\n        for (unsigned int i = 0; i < V_in.size(); i++) {\n            V_out[i] = V_in[i] + KMAT[0][i] * 0.5 * int_step;\n        }\n\n        ((ClassPointer)->*fp)(V_out, KMAT[1], VehicleIn);\n\n        for (unsigned int i = 0; i < V_in.size(); i++) {\n            V_out[i] = V_in[i] + KMAT[1][i] * 0.5 * int_step;\n        }\n\n        ((ClassPointer)->*fp)(V_out, KMAT[2], VehicleIn);\n\n        for (unsigned int i = 0; i < V_in.size(); i++) {\n            V_out[i] = V_in[i] + KMAT[2][i] * int_step;\n        }\n\n        ((ClassPointer)->*fp)(V_out, KMAT[3], VehicleIn);\n\n        for (unsigned int i = 0; i < V_in.size(); i++) {\n            V_out[i] = V_in[i] + (int_step / 6.0) * (KMAT[0][i] + 2.0 * KMAT[1][i] +\n                                                     2.0 * KMAT[2][i] + KMAT[3][i]);\n        }\n    }\n}\n\ntemplate <typename T>\nvoid IntegratorEuler(std::vector<arma::vec> V_in, std::vector<arma::vec> &V_out,\n                     void (T::*fp)(std::vector<arma::vec> Var_in,\n                                   std::vector<arma::vec> &Var_out,\n                                   LaunchVehicle *VehicleIn),\n                     T *ClassPointer, LaunchVehicle *VehicleIn,\n                     double int_step)\n{\n    std::vector<arma::vec> K_TEMP;\n\n    for (unsigned int i = 0; i < V_in.size(); i++) {\n        arma::vec temp;\n        K_TEMP.push_back(temp);\n    }\n\n    ((ClassPointer)->*fp)(V_in, K_TEMP, VehicleIn);\n\n    for (unsigned int i = 0; i < V_in.size(); i++) {\n        V_out[i] = V_in[i] + K_TEMP[i] * int_step;\n    }\n}\n#endif  //  __ROCKET_FLIGHT_DM_HH__\n", "meta": {"hexsha": "bbf80e7f9ccde3c254dd04371e3db9605152b27e", "size": 5957, "ext": "hh", "lang": "C++", "max_stars_repo_path": "modules/dynamic_model/rocket_flight_dm.hh", "max_stars_repo_name": "mlouielu/mazu-sim", "max_stars_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-26T07:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-26T07:09:54.000Z", "max_issues_repo_path": "modules/dynamic_model/rocket_flight_dm.hh", "max_issues_repo_name": "mlouielu/mazu-sim", "max_issues_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/dynamic_model/rocket_flight_dm.hh", "max_forks_repo_name": "mlouielu/mazu-sim", "max_forks_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "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.0, "max_line_length": 84, "alphanum_fraction": 0.5888870237, "num_tokens": 1624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.5055758917760396}}
{"text": "#include \"relativecm_rme.h\"\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <vector>\n\n#include \"basis_func/ho.h\"\n#include \"chime.h\"\n#include \"constants.h\"\n#include \"quadpp/quadpp.h\"\n#include \"quadpp/spline.h\"\n#include \"tprme.h\"\n\nnamespace chime {\nnamespace relcm {\n\nconstexpr double mPi = constants::pion_mass_fm;\nconstexpr double mN = constants::nucleon_mass_fm;\nconstexpr double FPi = constants::pion_decay_constant_fm;\nconstexpr double gA = constants::gA;\n\nvoid ConstructMu2nNLOOperator(\n    const basis::RelativeCMOperatorParametersLSJT& op_params,\n    const basis::RelativeCMSpaceLSJT& relcm_space,\n    std::array<basis::RelativeCMSectorsLSJT, 3>& relcm_sectors,\n    std::array<basis::OperatorBlocks<double>, 3>& relcm_matrices,\n    const double& oscillator_energy, const double& R)\n{\n  std::cout << \" Constructing M1 operator...\\n\";\n  assert(op_params.J0 == 1);\n  assert(op_params.g0 == 0);\n  assert((op_params.T0_min == 1) && (op_params.T0_max == 1));\n\n  // Alias isospin rank.\n  int T0 = op_params.T0_min;\n\n  // Generate required harmonic oscillator basis functions, and radial\n  // integral weights.\n  int Nmax = op_params.Nmax;\n\n  const int npts = 3001;\n  const double low = 0, high = 1;\n  Eigen::ArrayXd x, r, jac, wt;\n  quadpp::SemiInfiniteIntegralMesh(npts, low, high, x, r, jac);\n  wt = r * r * jac;  // weights for radial integral with transformed variable\n\n  std::cout << \"  Generating basis functions...\\n\";\n  std::vector<Eigen::ArrayXXd> ho_wfs;\n  double brel = chime::RelativeOscillatorLength(oscillator_energy);\n  double bcm = chime::CMOscillatorLength(oscillator_energy);\n  basis_func::ho::WaveFunctionsUptoMaxL(ho_wfs, r, Nmax, Nmax, brel,\n                                        basis_func::Space::coordinate);\n\n  // Relative radial integral kernels.\n  std::cout << \"  Generating integration kernels...\\n\";\n  Eigen::ArrayXd mpir = mPi * r;\n  Eigen::ArrayXd expmpir = Eigen::exp(-mpir);\n  Eigen::ArrayXd ypir = expmpir / mpir;\n  Eigen::ArrayXd zpir = (1. + mpir);\n  Eigen::ArrayXd tpir = (-1. + 2 * mpir);\n  Eigen::ArrayXd wpir = (1. + (3 * zpir / mpir.square()));\n\n  // Semilocal coordinate space regulator.\n  Eigen::ArrayXd scs_reg = Eigen::ArrayXd::Ones(npts);\n  if (R != 0) {\n    scs_reg *= Eigen::pow(1. - Eigen::exp(-(r * r) / (R * R)), 6);\n  }\n\n  // Zero initialize operator.\n  std::cout << \"  Zero initializing operator...\\n\";\n  for (int T = op_params.T0_min; T <= op_params.T0_max; ++T) {\n    relcm_sectors[T] = basis::RelativeCMSectorsLSJT(relcm_space, op_params.J0,\n                                                    T, op_params.g0);\n    basis::SetOperatorToZero(relcm_sectors[T], relcm_matrices[T]);\n  }\n\n  // Select T0 component.\n  const basis::RelativeCMSectorsLSJT& sectors = relcm_sectors[T0];\n  basis::OperatorBlocks<double>& matrices = relcm_matrices[T0];\n\n  // Reduced matrix element calculation.\n  std::cout << \"  Starting matrix element calculation...\\n\";\n  for (std::size_t sector_index = 0; sector_index < sectors.size();\n       ++sector_index) {\n    const basis::RelativeCMSectorsLSJT::SectorType& sector =\n        sectors.GetSector(sector_index);\n    const basis::RelativeCMSubspaceLSJT& bra_subspace = sector.bra_subspace();\n    const basis::RelativeCMSubspaceLSJT& ket_subspace = sector.ket_subspace();\n\n    // Alias for matrix.\n    basis::OperatorBlock<double>& matrix = matrices[sector_index];\n\n    // Extract subspace labels.\n    int bra_L = bra_subspace.L();\n    int bra_S = bra_subspace.S();\n    int bra_J = bra_subspace.J();\n    int bra_T = bra_subspace.T();\n    int ket_L = ket_subspace.L();\n    int ket_S = ket_subspace.S();\n    int ket_J = ket_subspace.J();\n    int ket_T = ket_subspace.T();\n\n    if (bra_T == ket_T) {\n      continue;\n    }\n\n    // Loop over bra and ket states.\n    const std::size_t bra_subspace_size = bra_subspace.size();\n    const std::size_t ket_subspace_size = ket_subspace.size();\n#pragma omp parallel for collapse(2)\n    for (std::size_t bra_index = 0; bra_index < bra_subspace_size;\n         ++bra_index) {\n      for (std::size_t ket_index = 0; ket_index < ket_subspace_size;\n           ++ket_index) {\n        const basis::RelativeCMStateLSJT bra_state(bra_subspace, bra_index);\n        const basis::RelativeCMStateLSJT ket_state(ket_subspace, ket_index);\n\n        // Extract state labels.\n        int bra_nr = bra_state.Nr();\n        int bra_lr = bra_state.lr();\n        int bra_nc = bra_state.Nc();\n        int bra_lc = bra_state.lc();\n        int ket_nr = ket_state.Nr();\n        int ket_lr = ket_state.lr();\n        int ket_nc = ket_state.Nc();\n        int ket_lc = ket_state.lc();\n\n        // Common part of all radial integrals.\n        Eigen::ArrayXd common_integrand = wt * scs_reg;\n        common_integrand *=\n            ho_wfs.at(bra_lr).row(bra_nr) * ho_wfs.at(ket_lr).row(ket_nr);\n\n        // Reduced matrix element calculation.\n        // Pauli matrix tensor product in spin space enforces the bra and\n        // ket spins to be the same for the relative-cm part, and to be\n        // different for the purely relative part.\n        double rme = 0;\n\n        if (bra_S == ket_S) {\n          // Relative-cm part.\n          double tp_a =\n              tp::CCSpinTensorProductRME(bra_state, ket_state, 1, 1, 1, 0, 1);\n          tp_a *= -std::sqrt(3.);\n\n          Eigen::ArrayXd y = common_integrand * expmpir;\n          y.head(1) = 0;  // Required to avoid divide by 0.\n          y.tail(1) = 0;  // Required to avoid divide by 0.\n          double integ_expmpir = quadpp::spline::Integrate(x, y);\n\n          rme = tp_a * integ_expmpir;\n\n          if (bra_S == 1) {\n            // Rank 2 Pauli Matrix tensor product.\n\n            double tp_b =\n                tp::CCSpinTensorProductRME(bra_state, ket_state, 1, 1, 1, 2, 1);\n            tp_b *= std::sqrt(3. / 5.);\n\n            double tp_c =\n                tp::CCSpinTensorProductRME(bra_state, ket_state, 1, 1, 2, 2, 1);\n            tp_c *= std::sqrt(9. / 5.);\n\n            double tp_d =\n                tp::CCSpinTensorProductRME(bra_state, ket_state, 3, 1, 2, 2, 1);\n            tp_d *= std::sqrt(14. / 5.);\n\n            double tp_e =\n                tp::CCSpinTensorProductRME(bra_state, ket_state, 3, 1, 3, 2, 1);\n            tp_e *= std::sqrt(28. / 5.);\n\n            y *= wpir;\n            y.head(1) = 0;  // Required to avoid divide by 0.\n            y.tail(1) = 0;  // Required to avoid divide by 0.\n            double integ_expmpir_wpir = quadpp::spline::Integrate(x, y);\n\n            rme += (tp_b + tp_c + tp_d + tp_e) * integ_expmpir_wpir;\n          }\n\n          double integ_cm = 0;  // CM coordinate integral; analytical result.\n          if (bra_lc == ket_lc + 1) {\n            integ_cm = ((std::sqrt(ket_nc + ket_lc + 1.5) * (bra_nc == ket_nc))\n                        + (std::sqrt(ket_nc) * (bra_nc + 1 == ket_nc)));\n          }\n          else if (bra_lc + 1 == ket_lc) {\n            integ_cm = ((std::sqrt(bra_nc + ket_nc + 1.5)) * (bra_nc == ket_nc)\n                        + (std::sqrt(bra_nc) * (bra_nc == ket_nc + 1)));\n          }\n          integ_cm *= mPi * bcm;\n\n          rme *= integ_cm;\n        }\n        else {\n          // Purely relative part. The cm labels for the bra and ket\n          // must be the same.\n          if ((bra_nc == ket_nc) && (bra_lc == ket_lc)) {\n            double tp_f =\n                tp::CCSpinTensorProductRME(bra_state, ket_state, 2, 0, 2, 1, 1);\n            tp_f *= std::sqrt(10.);\n\n            Eigen::ArrayXd y = common_integrand * zpir * ypir;\n            y.head(1) = 0;  // Required to avoid divide by 0.\n            y.tail(1) = 0;  // Required to avoid divide by 0.\n            double integ_zpir_ypir = quadpp::spline::Integrate(x, y);\n\n            rme = tp_f * integ_zpir_ypir;\n\n            if (bra_lr == ket_lr) {\n              // Rank 0 spherical harmonic.\n              double tp_g = tp::CCSpinTensorProductRME(bra_state, ket_state, 0,\n                                                       0, 0, 1, 1);\n\n              y = common_integrand * tpir * ypir;\n              y.head(1) = 0;  // Required to avoid divide by 0.\n              y.tail(1) = 0;  // Required to avoid divide by 0.\n              double integ_tpir_ypir = quadpp::spline::Integrate(x, y);\n\n              rme += tp_g * integ_tpir_ypir;\n            }\n          }\n        }\n        rme *= tp::SpinTensorProductRME(bra_T, ket_T, 1);  // Isospin.\n        rme *= -(mN * mPi * gA * gA) / (24 * constants::pi * FPi * FPi);\n\n        matrix(bra_index, ket_index) = rme;\n      }\n    }\n  }\n}\n\n}  // namespace relcm\n}  // namespace chime\n", "meta": {"hexsha": "e99820dd8254a504af8f391c98a202ab723292ab", "size": 8504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "programs/relativecm_rme.cpp", "max_stars_repo_name": "e-eight/chime", "max_stars_repo_head_hexsha": "c07dd11ca04b94f8e1906b12de647fcd99418556", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-09-18T20:31:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T14:47:07.000Z", "max_issues_repo_path": "programs/relativecm_rme.cpp", "max_issues_repo_name": "e-eight/chime", "max_issues_repo_head_hexsha": "c07dd11ca04b94f8e1906b12de647fcd99418556", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-04-08T22:42:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T15:10:53.000Z", "max_forks_repo_path": "programs/relativecm_rme.cpp", "max_forks_repo_name": "e-eight/chime", "max_forks_repo_head_hexsha": "c07dd11ca04b94f8e1906b12de647fcd99418556", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-03T17:25:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-03T17:25:01.000Z", "avg_line_length": 36.6551724138, "max_line_length": 80, "alphanum_fraction": 0.5905456256, "num_tokens": 2451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.5055758849779344}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library) // Robustness Test\n\n// Copyright (c) 2013 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// Adapted from: the attachment of ticket 9081\n\n#define CHECK_SELF_INTERSECTIONS\n#define LIST_WKT\n\n #include <iomanip>\n #include <iostream>\n #include <vector>\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/register/point.hpp>\n #include <boost/geometry/geometries/register/ring.hpp>\n #include <boost/geometry/io/wkt/wkt.hpp>\n #include <boost/geometry/multi/geometries/multi_polygon.hpp>\n\n#include <boost/foreach.hpp>\n#include <boost/timer.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/geometry/io/svg/svg_mapper.hpp>\n#include <fstream>\n\n\ntypedef boost::geometry::model::d2::point_xy<double> pt;\ntypedef boost::geometry::model::polygon<pt> polygon;\ntypedef boost::geometry::model::segment<pt> segment;\ntypedef boost::geometry::model::multi_polygon<polygon> multi_polygon;\n\ntemplate <typename Geometry>\ninline void debug_with_svg(int index, char method, Geometry const& a, Geometry const& b, std::string const& headera, std::string const& headerb)\n{\n    multi_polygon output;\n    try\n    {\n        switch(method)\n        {\n            case 'i': boost::geometry::intersection(a, b, output); break;\n            case 'u': boost::geometry::union_(a, b, output); break;\n            case 'd': boost::geometry::difference(a, b, output); break;\n            case 'v': boost::geometry::difference(b, a, output); break;\n            default : return;\n        }\n    }\n    catch(...)\n    {}\n\n    std::ostringstream filename;\n    filename << \"ticket_9081_\" << method << \"_\" << (1000000 + index) << \".svg\";\n    std::ofstream svg(filename.str().c_str());\n\n    boost::geometry::svg_mapper<pt> mapper(svg, 400, 400);\n    mapper.add(a);\n    mapper.add(b);\n\n    mapper.map(a, \"fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2\");\n    mapper.map(b, \"fill-opacity:0.3;fill:rgb(51,51,153);stroke:rgb(51,51,153);stroke-width:2\");\n    BOOST_FOREACH(polygon const& g, output)\n    {\n        mapper.map(g, \"opacity:0.8;fill:none;stroke:rgb(255,128,0);stroke-width:4;stroke-dasharray:1,7;stroke-linecap:round\");\n    }\n\n    std::ostringstream out;\n    out << headera << std::endl << headerb;\n    mapper.map(boost::geometry::return_centroid<pt>(a), \"fill:rgb(152,204,0);stroke:rgb(153,204,0);stroke-width:0.1\", 3);\n    mapper.map(boost::geometry::return_centroid<pt>(b), \"fill:rgb(51,51,153);stroke:rgb(153,204,0);stroke-width:0.1\", 3);\n    mapper.text(boost::geometry::return_centroid<pt>(a), headera, \"fill:rgb(0,0,0);font-family:Arial;font-size:10px\");\n    mapper.text(boost::geometry::return_centroid<pt>(b), headerb, \"fill:rgb(0,0,0);font-family:Arial;font-size:10px\");\n}\n\nint main()\n{\n    int num_orig = 50;\n    int num_rounds = 30000;\n    srand(1234);\n    std::cout << std::setprecision(16);\n    std::map<int, std::string> genesis;\n    int pj;\n\n\n    std::string wkt1, wkt2, operation;\n\n    try\n    {\n\n\n    boost::timer t;\n    std::vector<multi_polygon> poly_list;\n\n    for(int i=0;i<num_orig;i++)\n    {\n        multi_polygon mp;\n        polygon p;\n        for(int j=0;j<3;j++)\n        {\n            double x=(double)rand()/RAND_MAX;\n            double y=(double)rand()/RAND_MAX;\n            p.outer().push_back(pt(x,y));\n        }\n        boost::geometry::correct(p);\n        mp.push_back(p);\n        boost::geometry::detail::overlay::has_self_intersections(mp);\n\n        std::ostringstream out;\n        out << \"original \" << poly_list.size();\n        genesis[poly_list.size()] = out.str();\n        poly_list.push_back(mp);\n\n#ifdef LIST_WKT\n        std::cout << \"Original \" << i << \" \" << boost::geometry::wkt(p) << std::endl;\n#endif\n    }\n\n\n    for(int j=0;j<num_rounds;j++)\n    {\n        if (j % 100 == 0) { std::cout << \" \" << j; }\n        pj = j;\n        int a = rand() % poly_list.size();\n        int b = rand() % poly_list.size();\n\n        debug_with_svg(j, 'i', poly_list[a], poly_list[b], genesis[a], genesis[b]);\n\n        { std::ostringstream out; out << boost::geometry::wkt(poly_list[a]); wkt1 = out.str(); }\n        { std::ostringstream out; out << boost::geometry::wkt(poly_list[b]); wkt2 = out.str(); }\n\n        multi_polygon mp_i, mp_u, mp_d, mp_e;\n        operation = \"intersection\";\n        boost::geometry::intersection(poly_list[a],poly_list[b],mp_i);\n        operation = \"intersection\";\n        boost::geometry::union_(poly_list[a],poly_list[b],mp_u);\n        operation = \"difference\";\n        boost::geometry::difference(poly_list[a],poly_list[b],mp_d);\n        boost::geometry::difference(poly_list[b],poly_list[a],mp_e);\n\n#ifdef LIST_WKT\n        std::cout << j << std::endl;\n        std::cout << \"  Genesis a \" << genesis[a] << std::endl;\n        std::cout << \"  Genesis b \" << genesis[b] << std::endl;\n        std::cout << \"  Intersection \" << boost::geometry::wkt(mp_i) << std::endl;\n        std::cout << \"  Difference a \" << boost::geometry::wkt(mp_d) << std::endl;\n        std::cout << \"  Difference b \" << boost::geometry::wkt(mp_e) << std::endl;\n#endif\n\n#ifdef CHECK_SELF_INTERSECTIONS\n        try\n        {\n            boost::geometry::detail::overlay::has_self_intersections(mp_i);\n        }\n        catch(...)\n        {\n            std::cout << \"FAILED TO INTERSECT \" << j << std::endl;\n            std::cout << boost::geometry::wkt(poly_list[a]) << std::endl;\n            std::cout << boost::geometry::wkt(poly_list[b]) << std::endl;\n            std::cout << boost::geometry::wkt(mp_i) << std::endl;\n            try\n            {\n                boost::geometry::detail::overlay::has_self_intersections(mp_i);\n            }\n            catch(...)\n            {\n            }\n            break;\n        }\n\n        try\n        {\n            boost::geometry::detail::overlay::has_self_intersections(mp_d);\n        }\n        catch(...)\n        {\n            std::cout << \"FAILED TO SUBTRACT \" << j << std::endl;\n            std::cout << boost::geometry::wkt(poly_list[a]) << std::endl;\n            std::cout << boost::geometry::wkt(poly_list[b]) << std::endl;\n            std::cout << boost::geometry::wkt(mp_d) << std::endl;\n            break;\n        }\n        try\n        {\n            boost::geometry::detail::overlay::has_self_intersections(mp_e);\n        }\n        catch(...)\n        {\n            std::cout << \"FAILED TO SUBTRACT \" << j << std::endl;\n            std::cout << boost::geometry::wkt(poly_list[b]) << std::endl;\n            std::cout << boost::geometry::wkt(poly_list[a]) << std::endl;\n            std::cout << boost::geometry::wkt(mp_e) << std::endl;\n            break;\n        }\n#endif\n\n        if(boost::geometry::area(mp_i) > 0)\n        {\n            std::ostringstream out;\n            out << j << \" intersection(\" << genesis[a] << \" , \" << genesis[b] << \")\";\n            genesis[poly_list.size()] = out.str();\n            poly_list.push_back(mp_i);\n        }\n        if(boost::geometry::area(mp_d) > 0)\n        {\n            std::ostringstream out;\n            out << j << \" difference(\" << genesis[a] << \" - \" << genesis[b] << \")\";\n            genesis[poly_list.size()] = out.str();\n            poly_list.push_back(mp_d);\n        }\n        if(boost::geometry::area(mp_e) > 0)\n        {\n            std::ostringstream out;\n            out << j << \" difference(\" << genesis[b] << \" - \" << genesis[a] << \")\";\n            genesis[poly_list.size()] = out.str();\n            poly_list.push_back(mp_e);\n        }\n    }\n\n    std::cout << \"FINISHED \" << t.elapsed() << std::endl;\n\n    }\n    catch(std::exception const& e)\n    {\n        std::cout << e.what()\n            << \" in \" << operation << \" at \" << pj << std::endl\n            << wkt1 << std::endl\n            << wkt2 << std::endl\n            << std::endl;\n    }\n    catch(...)\n    {\n        std::cout << \"Other exception\" << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "9c2f815972eb9fb4d4071d994e76120f7cf62f29", "size": 8124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/geometry/test/algorithms/overlay/robustness/ticket_9081.cpp", "max_stars_repo_name": "cooparation/caffe-android", "max_stars_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-11-02T07:15:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:56:59.000Z", "max_issues_repo_path": "boost/boost_1_56_0/libs/geometry/test/algorithms/overlay/robustness/ticket_9081.cpp", "max_issues_repo_name": "cooparation/caffe-android", "max_issues_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "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": "boost/boost_1_56_0/libs/geometry/test/algorithms/overlay/robustness/ticket_9081.cpp", "max_forks_repo_name": "cooparation/caffe-android", "max_forks_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-02T14:11:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-20T13:42:13.000Z", "avg_line_length": 33.85, "max_line_length": 144, "alphanum_fraction": 0.5680699163, "num_tokens": 2165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.5054762504531068}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2020 - 2021 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 * Authors: Wolfgang Bangerth, Rene Gassmoeller, Peter Munch, 2020. \n */ \n\n\n// @sect3{Include files}  \n\n// \u672c\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u7684\u5927\u90e8\u5206include\u6587\u4ef6\u90fd\u662f step-6 \u548c\u7c7b\u4f3c\u7a0b\u5e8f\u4e2d\u4f17\u6240\u5468\u77e5\u7684\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n\n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/precondition.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/sparse_matrix.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/affine_constraints.h> \n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_refinement.h> \n\n#include <deal.II/fe/mapping_q.h> \n#include <deal.II/matrix_free/fe_point_evaluation.h> \n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_values.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/error_estimator.h> \n\n// \u65b0\u7684\u53ea\u6709\u4ee5\u4e0b\u4e09\u4e2a\u3002\u7b2c\u4e00\u4e2a\u58f0\u660e\u4e86DiscreteTime\u7c7b\uff0c\u5b83\u5e2e\u52a9\u6211\u4eec\u5728\u65f6\u95f4\u76f8\u5173\u7684\u6a21\u62df\u4e2d\u8ddf\u8e2a\u65f6\u95f4\u3002\u540e\u9762\u4e24\u4e2a\u63d0\u4f9b\u4e86\u6240\u6709\u7684\u7c92\u5b50\u529f\u80fd\uff0c\u5373\u8bb0\u5f55\u4f4d\u4e8e\u7f51\u683c\u4e0a\u7684\u7c92\u5b50\u7684\u65b9\u6cd5\uff08 Particles::ParticleHandler \u7c7b\uff09\u548c\u4e3a\u53ef\u89c6\u5316\u76ee\u7684\u8f93\u51fa\u8fd9\u4e9b\u7c92\u5b50\u7684\u4f4d\u7f6e\u53ca\u5176\u5c5e\u6027\u7684\u80fd\u529b\uff08 Particles::DataOut  \u7c7b\uff09\u3002\n\n#include <deal.II/base/discrete_time.h> \n#include <deal.II/particles/particle_handler.h> \n#include <deal.II/particles/data_out.h> \n\n#include <fstream> \n\nusing namespace dealii; \n// @sect3{Global definitions}  \n\n// \u6309\u7167\u60ef\u4f8b\uff0c\u6211\u4eec\u628a\u6240\u6709\u4e0e\u7a0b\u5e8f\u7ec6\u8282\u76f8\u5bf9\u5e94\u7684\u4e1c\u897f\u90fd\u653e\u5230\u4e00\u4e2a\u81ea\u5df1\u7684\u547d\u540d\u7a7a\u95f4\u4e2d\u3002\u5728\u9876\u90e8\uff0c\u6211\u4eec\u5b9a\u4e49\u4e86\u4e00\u4e9b\u5e38\u91cf\uff0c\u6211\u4eec\u5b81\u613f\u4f7f\u7528\u7b26\u53f7\u540d\u79f0\u800c\u4e0d\u662f\u786c\u7f16\u7801\u7684\u6570\u5b57\u3002\n\n// \u5177\u4f53\u6765\u8bf4\uff0c\u6211\u4eec\u4e3a\u51e0\u4f55\u5b66\u7684\u5404\u4e2a\u90e8\u5206\u5b9a\u4e49\u4e86 @ref GlossBoundaryIndicator \"\u8fb9\u754c\u6307\u6807 \"\u7684\u6570\u5b57\uff0c\u4ee5\u53ca\u7535\u5b50\u7684\u7269\u7406\u5c5e\u6027\u548c\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u7684\u5176\u4ed6\u5177\u4f53\u8bbe\u7f6e\u3002\n\n// \u5bf9\u4e8e\u8fb9\u754c\u6307\u6807\uff0c\u8ba9\u6211\u4eec\u4ece\u67d0\u4e2a\u968f\u673a\u503c101\u5f00\u59cb\u5217\u4e3e\u3002\u8fd9\u91cc\u7684\u539f\u5219\u662f\u8981\u4f7f\u7528*\u4e0d\u5e38\u89c1\u7684\u6570\u5b57\u3002\u5982\u679c\u4e4b\u524d\u6709`GridGenerator'\u51fd\u6570\u8bbe\u7f6e\u7684\u9884\u5b9a\u4e49\u8fb9\u754c\u6307\u6807\uff0c\u5b83\u4eec\u5f88\u53ef\u80fd\u662f\u4ece0\u5f00\u59cb\u7684\u5c0f\u6574\u6570\uff0c\u4f46\u4e0d\u662f\u5728\u8fd9\u4e2a\u76f8\u5f53\u968f\u673a\u7684\u8303\u56f4\u5185\u3002\u4f7f\u7528\u4e0b\u9762\u8fd9\u6837\u7684\u6570\u5b57\u53ef\u4ee5\u907f\u514d\u51b2\u7a81\u7684\u53ef\u80fd\u6027\uff0c\u540c\u65f6\u4e5f\u51cf\u5c11\u4e86\u5728\u7a0b\u5e8f\u4e2d\u76f4\u63a5\u62fc\u51fa\u8fd9\u4e9b\u6570\u5b57\u7684\u8bf1\u60d1\uff08\u56e0\u4e3a\u4f60\u53ef\u80fd\u6c38\u8fdc\u4e0d\u4f1a\u8bb0\u5f97\u54ea\u4e2a\u662f\u54ea\u4e2a\uff0c\u800c\u5982\u679c\u5b83\u4eec\u4ece0\u5f00\u59cb\uff0c\u4f60\u53ef\u80fd\u4f1a\u53d7\u5230\u8bf1\u60d1\uff09\u3002\n\nnamespace Step19 \n{ \n  namespace BoundaryIds \n  { \n    constexpr types::boundary_id open          = 101; \n    constexpr types::boundary_id cathode       = 102; \n    constexpr types::boundary_id focus_element = 103; \n    constexpr types::boundary_id anode         = 104; \n  } // namespace BoundaryIds \n\n  namespace Constants \n  { \n    constexpr double electron_mass   = 9.1093837015e-31; \n    constexpr double electron_charge = 1.602176634e-19; \n\n    constexpr double V0 = 1; \n\n    constexpr double E_threshold = 0.05; \n\n    constexpr double electrons_per_particle = 3e15; \n  } // namespace Constants \n// @sect3{The main class}  \n\n// \u7136\u540e\uff0c\u4e0b\u9762\u662f\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u3002\u4ece\u6839\u672c\u4e0a\u8bf4\uff0c\u5b83\u7684\u7ed3\u6784\u4e0e step-6 \u548c\u5176\u4ed6\u8bb8\u591a\u6559\u7a0b\u7a0b\u5e8f\u76f8\u540c\u3002\u8fd9\u5305\u62ec\u5927\u90e8\u5206\u7684\u6210\u5458\u51fd\u6570\uff08\u5176\u4f59\u90e8\u5206\u7684\u76ee\u7684\u53ef\u80fd\u4ece\u5b83\u4eec\u7684\u540d\u5b57\u4e2d\u4e0d\u96be\u770b\u51fa\uff09\uff0c\u4ee5\u53ca\u8d85\u51fa step-6 \u7684\u5c11\u91cf\u6210\u5458\u53d8\u91cf\uff0c\u6240\u6709\u8fd9\u4e9b\u90fd\u4e0e\u5904\u7406\u7c92\u5b50\u6709\u5173\u3002\n\n  template <int dim> \n  class CathodeRaySimulator \n  { \n  public: \n    CathodeRaySimulator(); \n\n    void run(); \n\n  private: \n    void make_grid(); \n    void setup_system(); \n    void assemble_system(); \n    void solve_field(); \n    void refine_grid(); \n\n    void create_particles(); \n    void move_particles(); \n    void track_lost_particle( \n      const typename Particles::ParticleIterator<dim> &        particle, \n      const typename Triangulation<dim>::active_cell_iterator &cell); \n\n    void update_timestep_size(); \n    void output_results() const; \n\n    Triangulation<dim>        triangulation; \n    MappingQGeneric<dim>      mapping; \n    FE_Q<dim>                 fe; \n    DoFHandler<dim>           dof_handler; \n    AffineConstraints<double> constraints; \n\n    SparseMatrix<double> system_matrix; \n    SparsityPattern      sparsity_pattern; \n\n    Vector<double> solution; \n    Vector<double> system_rhs; \n\n    Particles::ParticleHandler<dim> particle_handler; \n    types::particle_index           next_unused_particle_id; \n    types::particle_index           n_recently_lost_particles; \n    types::particle_index           n_total_lost_particles; \n    types::particle_index           n_particles_lost_through_anode; \n\n    DiscreteTime time; \n  }; \n\n//  @sect3{The <code>CathodeRaySimulator</code> class implementation}  \n// @sect4{The <code>CathodeRaySimulator</code> constructor}  \n\n// \u90a3\u4e48\uff0c\u8ba9\u6211\u4eec\u5f00\u59cb\u6267\u884c\u3002\u6784\u9020\u51fd\u6570\u6240\u505a\u7684\u5b9e\u9645\u4e0a\u53ea\u662f\u5bf9\u9876\u90e8\u7684\u6240\u6709\u6210\u5458\u53d8\u91cf\u8fdb\u884c\u7b80\u5355\u7684\u521d\u59cb\u5316\u3002\u552f\u4e00\u503c\u5f97\u4e00\u63d0\u7684\u662f`particle_handler'\uff0c\u5b83\u88ab\u4ea4\u7ed9\u4e86\u4e00\u4e2a\u6307\u5411\u7c92\u5b50\u6240\u5728\u7684\u4e09\u89d2\u5f62\u7684\u5f15\u7528\uff08\u76ee\u524d\u5f53\u7136\u8fd8\u662f\u7a7a\u7684\uff0c\u4f46\u662f\u7c92\u5b50\u5904\u7406\u7a0b\u5e8f\u5b58\u50a8\u4e86\u8fd9\u4e2a\u5f15\u7528\uff0c\u4e00\u65e6\u7c92\u5b50\u88ab\u6dfb\u52a0\uff0c\u5c31\u4f1a\u4f7f\u7528\u5b83--\u8fd9\u53d1\u751f\u5728\u4e09\u89d2\u5f62\u88ab\u6784\u5efa\u4e4b\u540e\uff09\u3002\u5b83\u5f97\u5230\u7684\u53e6\u4e00\u4e2a\u4fe1\u606f\u662f\u6bcf\u4e2a\u7c92\u5b50\u9700\u8981\u5b58\u50a8\u591a\u5c11 \"\u5c5e\u6027\"\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u9700\u8981\u6bcf\u4e2a\u7c92\u5b50\u8bb0\u4f4f\u7684\u662f\u5b83\u5f53\u524d\u7684\u901f\u5ea6\uff0c\u4e5f\u5c31\u662f\u4e00\u4e2a\u5e26\u6709`dim`\u5206\u91cf\u7684\u77e2\u91cf\u3002\u7136\u800c\uff0c\u6bcf\u4e2a\u7c92\u5b50\u8fd8\u6709\u5176\u4ed6\u7684\u5185\u5728\u5c5e\u6027\uff0c Particles::ParticleHandler \u7c7b\u4f1a\u81ea\u52a8\u5e76\u59cb\u7ec8\u786e\u4fdd\u8fd9\u4e9b\u5c5e\u6027\u662f\u53ef\u7528\u7684\uff1b\u7279\u522b\u662f\uff0c\u8fd9\u4e9b\u5c5e\u6027\u662f\u7c92\u5b50\u7684\u5f53\u524d\u4f4d\u7f6e\u3001\u5b83\u6240\u5728\u7684\u5355\u5143\u683c\u3001\u5b83\u5728\u8be5\u5355\u5143\u683c\u4e2d\u7684\u53c2\u8003\u4f4d\u7f6e\uff0c\u4ee5\u53ca\u7c92\u5b50\u7684ID\u3002\n\n// \u552f\u4e00\u611f\u5174\u8da3\u7684\u5176\u4ed6\u53d8\u91cf\u662f \"\u65f6\u95f4\"\uff0c\u4e00\u4e2aDiscreteTime\u7c7b\u578b\u7684\u5bf9\u8c61\u3002\u5b83\u8bb0\u5f55\u4e86\u6211\u4eec\u5728\u4e00\u4e2a\u968f\u65f6\u95f4\u53d8\u5316\u7684\u6a21\u62df\u4e2d\u7684\u5f53\u524d\u65f6\u95f4\uff0c\u5e76\u4ee5\u5f00\u59cb\u65f6\u95f4\uff08\u96f6\uff09\u548c\u7ed3\u675f\u65f6\u95f4\uff08 $10^{-4}$ \uff09\u521d\u59cb\u5316\u3002\u6211\u4eec\u4ee5\u540e\u5c06\u5728`update_timestep_size()`\u4e2d\u8bbe\u7f6e\u65f6\u95f4\u6b65\u957f\u3002\n\n// \u6784\u9020\u51fd\u6570\u7684\u4e3b\u4f53\u7531\u6211\u4eec\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u7684\u4e00\u6bb5\u4ee3\u7801\u7ec4\u6210\u3002\u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u8981\u786e\u4fdd\u6bcf\u6b21\u6709\u7c92\u5b50\u79bb\u5f00\u57df\u65f6\uff0c`track_lost_particle()`\u51fd\u6570\u90fd\u4f1a\u88ab`particle_handler`\u5bf9\u8c61\u8c03\u7528\u3002\n\n  template <int dim> \n  CathodeRaySimulator<dim>::CathodeRaySimulator() \n    : mapping(1) \n    , fe(2) \n    , dof_handler(triangulation) \n    , particle_handler(triangulation, mapping, /*n_properties=*/dim) \n    , next_unused_particle_id(0) \n    , n_recently_lost_particles(0) \n    , n_total_lost_particles(0) \n    , n_particles_lost_through_anode(0) \n    , time(0, 1e-4) \n  { \n    particle_handler.signals.particle_lost.connect( \n      [this](const typename Particles::ParticleIterator<dim> &        particle, \n             const typename Triangulation<dim>::active_cell_iterator &cell) { \n        this->track_lost_particle(particle, cell); \n      }); \n  } \n\n//  @sect4{The <code>CathodeRaySimulator::make_grid</code> function}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u8d1f\u8d23\u751f\u6210\u6211\u4eec\u8981\u89e3\u51b3\u7684\u7f51\u683c\u3002\u56de\u987e\u4e00\u4e0b\u57df\u7684\u6837\u5b50\u3002    \n// <p align=\"center\">\n//      <img\n//      src=\"https:www.dealii.org/images/steps/developer/step-19.geometry.png\"\n//           alt=\"The geometry used in this program\"\n//           width=\"600\">\n//    </p>  \u6211\u4eec\u628a\u8fd9\u4e2a\u51e0\u4f55\u4f53\u7ec6\u5206\u4e3a $4\\times 2$ \u4e2a\u5355\u5143\u7684\u7f51\u683c\uff0c\u770b\u8d77\u6765\u50cf\u8fd9\u6837\u3002\n//    @code\n//    *---*---*---*---*\n//    \\   |   |   |   |\n//     *--*---*---*---*\n//    /   |   |   |   |\n//    *---*---*---*---*\n//  @endcode \n//  \u8fd9\u6837\u505a\u7684\u65b9\u6cd5\u662f\u9996\u5148\u5b9a\u4e49 $15=5\\times 3$ \u9876\u70b9\u7684\u4f4d\u7f6e--\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u8bf4\u5b83\u4eec\u5728\u6574\u6570\u70b9\u4e0a\uff0c\u5de6\u8fb9\u7684\u4e2d\u95f4\u70b9\u5411\u53f3\u79fb\u52a8\u4e86`delta=0.5`\u7684\u503c\u3002\n\n// \u5728\u4e0b\u6587\u4e2d\uff0c\u6211\u4eec\u5fc5\u987b\u8bf4\u660e\u54ea\u4e9b\u9876\u70b9\u5171\u540c\u7ec4\u6210\u4e868\u4e2a\u5355\u5143\u3002\u4e0b\u9762\u7684\u4ee3\u7801\u5c31\u5b8c\u5168\u7b49\u540c\u4e8e\u6211\u4eec\u5728 step-14 \u4e2d\u7684\u505a\u6cd5\u3002\n\n  template <int dim> \n  void CathodeRaySimulator<dim>::make_grid() \n  { \n    static_assert(dim == 2, \n                  \"This function is currently only implemented for 2d.\"); \n\n    const double       delta = 0.5; \n    const unsigned int nx    = 5; \n    const unsigned int ny    = 3; \n\n    const std::vector<Point<dim>> vertices // \n      = {{0, 0}, \n         {1, 0}, \n         {2, 0}, \n         {3, 0}, \n         {4, 0}, \n         {delta, 1}, \n         {1, 1}, \n         {2, 1}, \n         {3, 1}, \n         {4, 1}, \n         {0, 2}, \n         {1, 2}, \n         {2, 2}, \n         {3, 2}, \n         {4, 2}}; \n    AssertDimension(vertices.size(), nx * ny); \n\n    const std::vector<unsigned int> cell_vertices[(nx - 1) * (ny - 1)] = { \n      {0, 1, nx + 0, nx + 1}, \n      {1, 2, nx + 1, nx + 2}, \n      {2, 3, nx + 2, nx + 3}, \n      {3, 4, nx + 3, nx + 4}, \n\n      {5, nx + 1, 2 * nx + 0, 2 * nx + 1}, \n      {nx + 1, nx + 2, 2 * nx + 1, 2 * nx + 2}, \n      {nx + 2, nx + 3, 2 * nx + 2, 2 * nx + 3}, \n      {nx + 3, nx + 4, 2 * nx + 3, 2 * nx + 4}}; \n\n// \u6709\u4e86\u8fd9\u4e9b\u6570\u7ec4\uff0c\u6211\u4eec\u53ef\u4ee5\u8f6c\u5411\u7a0d\u9ad8\u7684\u9ad8\u5c42\u6570\u636e\u7ed3\u6784\u3002\u6211\u4eec\u521b\u5efa\u4e00\u4e2aCellData\u5bf9\u8c61\u7684\u5411\u91cf\uff0c\u4e3a\u6bcf\u4e2a\u8981\u521b\u5efa\u7684\u5355\u5143\u5b58\u50a8\u76f8\u5173\u7684\u9876\u70b9\u4ee5\u53ca @ref GlossMaterialId \"\u6750\u6599ID\"\uff08\u6211\u4eec\u5728\u8fd9\u91cc\u5c06\u5176\u7b80\u5355\u5730\u8bbe\u7f6e\u4e3a0\uff0c\u56e0\u4e3a\u6211\u4eec\u5728\u7a0b\u5e8f\u4e2d\u4e0d\u4f7f\u7528\u5b83\uff09\u3002\n\n// \u7136\u540e\uff0c\u8fd9\u4e9b\u4fe1\u606f\u5c06\u88ab\u4f20\u9012\u7ed9 Triangulation::create_triangulation() \u51fd\u6570\uff0c\u5e76\u5bf9\u7f51\u683c\u8fdb\u884c\u4e24\u6b21\u5168\u5c40\u7ec6\u5316\u3002\n\n    std::vector<CellData<dim>> cells((nx - 1) * (ny - 1), CellData<dim>()); \n    for (unsigned int i = 0; i < cells.size(); ++i) \n      { \n        cells[i].vertices    = cell_vertices[i]; \n        cells[i].material_id = 0; \n      } \n\n    triangulation.create_triangulation( \n      vertices, \n      cells, \n      SubCellData()); // No boundary information \n\n    triangulation.refine_global(2); \n\n// \u8be5\u51fd\u6570\u7684\u5176\u4f59\u90e8\u5206\u5faa\u73af\u6240\u6709\u7684\u5355\u5143\u683c\u548c\u5b83\u4eec\u7684\u9762\uff0c\u5982\u679c\u4e00\u4e2a\u9762\u5728\u8fb9\u754c\u4e0a\uff0c\u5219\u51b3\u5b9a\u54ea\u4e2a\u8fb9\u754c\u6307\u6807\u5e94\u8be5\u5e94\u7528\u4e8e\u5b83\u3002\u5982\u679c\u4f60\u5c06\u4ee3\u7801\u4e0e\u4e0a\u9762\u7684\u51e0\u4f55\u56fe\u5f62\u76f8\u6bd4\u8f83\uff0c\u5404\u79cd\u6761\u4ef6\u5e94\u8be5\u662f\u6709\u610f\u4e49\u7684\u3002\n\n// \u4e00\u65e6\u5b8c\u6210\u4e86\u8fd9\u4e00\u6b65\uff0c\u6211\u4eec\u518d\u5168\u5c40\u5730\u7ec6\u5316\u4e00\u4e0b\u7f51\u683c\u3002\n\n    for (auto &cell : triangulation.active_cell_iterators()) \n      for (auto &face : cell->face_iterators()) \n        if (face->at_boundary()) \n          { \n            if ((face->center()[0] > 0) && (face->center()[0] < 0.5) && \n                (face->center()[1] > 0) && (face->center()[1] < 2)) \n              face->set_boundary_id(BoundaryIds::cathode); \n            else if ((face->center()[0] > 0) && (face->center()[0] < 2)) \n              face->set_boundary_id(BoundaryIds::focus_element); \n            else if ((face->center()[0] > 4 - 1e-12) && \n                     ((face->center()[1] > 1.5) || (face->center()[1] < 0.5))) \n              face->set_boundary_id(BoundaryIds::anode); \n            else \n              face->set_boundary_id(BoundaryIds::open); \n          } \n\n    triangulation.refine_global(1); \n  } \n// @sect4{The <code>CathodeRaySimulator::setup_system</code> function}  \n\n// \u672c\u7a0b\u5e8f\u4e2d\u7684\u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u5904\u7406\u4e0e\u89e3\u51b3\u504f\u5fae\u5206\u65b9\u7a0b\u6709\u5173\u7684\u5404\u79cd\u5bf9\u8c61\u7684\u8bbe\u7f6e\u3002\u5b83\u672c\u8d28\u4e0a\u662f\u5bf9 step-6 \u4e2d\u76f8\u5e94\u51fd\u6570\u7684\u590d\u5236\uff0c\u4e0d\u9700\u8981\u8fdb\u4e00\u6b65\u8ba8\u8bba\u3002\n\n  template <int dim> \n  void CathodeRaySimulator<dim>::setup_system() \n  { \n    dof_handler.distribute_dofs(fe); \n\n    solution.reinit(dof_handler.n_dofs()); \n    system_rhs.reinit(dof_handler.n_dofs()); \n\n \n    DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n\n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             BoundaryIds::cathode, \n                                             Functions::ConstantFunction<dim>( \n                                               -Constants::V0), \n                                             constraints); \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             BoundaryIds::focus_element, \n                                             Functions::ConstantFunction<dim>( \n                                               -Constants::V0), \n                                             constraints); \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             BoundaryIds::anode, \n                                             Functions::ConstantFunction<dim>( \n                                               +Constants::V0), \n                                             constraints); \n    constraints.close(); \n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, \n                                    dsp, \n                                    constraints, \n                                    /*keep_constrained_dofs =  */ false);\n\n    sparsity_pattern.copy_from(dsp); \n\n    system_matrix.reinit(sparsity_pattern); \n  } \n// @sect4{The <code>CathodeRaySimulator::assemble_system</code> function}  \n\n// \u8ba1\u7b97\u77e9\u9635\u9879\u7684\u51fd\u6570\u5b9e\u8d28\u4e0a\u8fd8\u662f\u590d\u5236\u4e86  step-6  \u4e2d\u7684\u76f8\u5e94\u51fd\u6570\u3002\n\n  template <int dim> \n  void CathodeRaySimulator<dim>::assemble_system() \n  { \n    system_matrix = 0; \n    system_rhs    = 0; \n\n    const QGauss<dim> quadrature_formula(fe.degree + 1); \n\n    FEValues<dim> fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | update_JxW_values); \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    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        for (const unsigned int q_index : fe_values.quadrature_point_indices()) \n          for (const unsigned int i : fe_values.dof_indices()) \n            { \n              for (const unsigned int j : fe_values.dof_indices()) \n                cell_matrix(i, j) += \n                  (fe_values.shape_grad(i, q_index) * // grad phi_i(x_q) \n                   fe_values.shape_grad(j, q_index) * // grad phi_j(x_q) \n                   fe_values.JxW(q_index));           // dx \n            } \n\n// \u8fd9\u4e2a\u51fd\u6570\u552f\u4e00\u6709\u8da3\u7684\u90e8\u5206\u662f\u5b83\u662f\u5982\u4f55\u5f62\u6210\u7ebf\u6027\u7cfb\u7edf\u7684\u53f3\u624b\u8fb9\u7684\u3002\u56de\u987e\u4e00\u4e0b\uff0cPDE\u7684\u53f3\u8fb9\u662f\n// @f[\n//    \\sum_p (N e)\\delta(\\mathbf x-\\mathbf x_p),\n//  @f]\n//  \uff0c\u5728\u8fd9\u91cc\u6211\u4eec\u7528 $p$ \u6765\u7d22\u5f15\u7c92\u5b50\uff0c\u4ee5\u907f\u514d\u4e0e\u5f62\u72b6\u51fd\u6570 $\\varphi_i$ \u6df7\u6dc6\uff1b $\\mathbf x_p$ \u662f\u7b2c $p$ \u4e2a\u7c92\u5b50\u7684\u4f4d\u7f6e\u3002\n\n// \u5f53\u4e0e\u6d4b\u8bd5\u51fd\u6570 $\\varphi_i$ \u76f8\u4e58\u5e76\u5728\u57df\u4e0a\u79ef\u5206\u65f6\uff0c\u4f1a\u5f97\u5230\u4e00\u4e2a\u53f3\u624b\u8fb9\u7684\u5411\u91cf\n// @f{align*}{\n//    F_i &= \\int_\\Omega \\varphi_i (\\mathbf x)\\left[\n//                 \\sum_p (N e)\\delta(\\mathbf x-\\mathbf x_p) \\right] dx\n//    \\\\  &=  \\sum_p (N e) \\varphi_i(\\mathbf x_p).\n//  @f} \n//  \u6ce8\u610f\u6700\u540e\u4e00\u884c\u4e0d\u518d\u5305\u542b\u4e00\u4e2a\u79ef\u5206\uff0c\u56e0\u6b64\u4e5f\u6ca1\u6709\u51fa\u73b0 $dx$ \uff0c\u8fd9\u9700\u8981\u5728\u6211\u4eec\u7684\u4ee3\u7801\u4e2d\u51fa\u73b0`JxW`\u7b26\u53f7\u3002\n// \n// \u5bf9\u4e8e\u4e00\u4e2a\u7ed9\u5b9a\u7684\u5355\u5143 $K$ \uff0c\u8fd9\u4e2a\u5355\u5143\u5bf9\u53f3\u8fb9\u7684\u8d21\u732e\u662f\n//  @f{align*}{\n//    F_i^K &= \\sum_{p, \\mathbf x_p\\in K} (N e) \\varphi_i(\\mathbf x_p),\n//  @f}\uff0c\n//  \u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u53ea\u9700\u8981\u62c5\u5fc3\u90a3\u4e9b\u5b9e\u9645\u4f4d\u4e8e\u5f53\u524d\u5355\u5143 $K$ \u4e0a\u7684\u7c92\u5b50\u3002\n\n// \u5728\u5b9e\u8df5\u4e2d\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u6240\u505a\u7684\u662f\u4ee5\u4e0b\u51e0\u70b9\u3002\u5982\u679c\u5f53\u524d\u5355\u5143\u683c\u4e0a\u6709\u4efb\u4f55\u7c92\u5b50\uff0c\u90a3\u4e48\u6211\u4eec\u9996\u5148\u83b7\u5f97\u4e00\u4e2a\u8fed\u4ee3\u5668\u8303\u56f4\uff0c\u6307\u5411\u8be5\u5355\u5143\u683c\u7684\u7b2c\u4e00\u4e2a\u7c92\u5b50\u4ee5\u53ca\u8be5\u5355\u5143\u683c\u4e0a\u6700\u540e\u4e00\u4e2a\u7c92\u5b50\u4e4b\u540e\u7684\u7c92\u5b50\uff08\u6216\u7ed3\u675f\u8fed\u4ee3\u5668\uff09--\u5373C++\u51fd\u6570\u4e2d\u5e38\u89c1\u7684\u534a\u5f00\u653e\u8303\u56f4\u3002\u73b0\u5728\u77e5\u9053\u4e86\u7c92\u5b50\u7684\u5217\u8868\uff0c\u6211\u4eec\u67e5\u8be2\u5b83\u4eec\u7684\u53c2\u8003\u4f4d\u7f6e\uff08\u76f8\u5bf9\u4e8e\u53c2\u8003\u5355\u5143\uff09\uff0c\u8bc4\u4f30\u8fd9\u4e9b\u53c2\u8003\u4f4d\u7f6e\u7684\u5f62\u72b6\u51fd\u6570\uff0c\u5e76\u6839\u636e\u4e0a\u9762\u7684\u516c\u5f0f\u8ba1\u7b97\u529b\uff08\u6ca1\u6709\u4efb\u4f55  FEValues::JxW).  \uff09\u3002\n// @note  \u503c\u5f97\u6307\u51fa\u7684\u662f\uff0c\u8c03\u7528 Particles::ParticleHandler::particles_in_cell() \u548c Particles::ParticleHandler::n_particles_in_cell() \u51fd\u6570\u5728\u6709\u5927\u91cf\u7c92\u5b50\u7684\u95ee\u9898\u4e0a\u4e0d\u662f\u5f88\u6709\u6548\u3002\u4f46\u662f\u5b83\u8bf4\u660e\u4e86\u5199\u8fd9\u4e2a\u7b97\u6cd5\u7684\u6700\u7b80\u5355\u7684\u65b9\u6cd5\uff0c\u6240\u4ee5\u6211\u4eec\u613f\u610f\u4e3a\u4e86\u8bf4\u660e\u95ee\u9898\u800c\u6682\u65f6\u627f\u62c5\u8fd9\u4e2a\u4ee3\u4ef7\u3002  \u6211\u4eec\u5728\u4e0b\u9762\u7684<a href=\"#extensions\">\"possibilities for extensions\" section</a>\u4e2d\u66f4\u8be6\u7ec6\u5730\u8ba8\u8bba\u4e86\u8fd9\u4e2a\u95ee\u9898\uff0c\u5e76\u5728 step-70 \u4e2d\u4f7f\u7528\u4e86\u4e00\u4e2a\u66f4\u597d\u7684\u65b9\u6cd5\uff0c\u4f8b\u5982\uff1a\u3002\n\n        if (particle_handler.n_particles_in_cell(cell) > 0) \n          for (const auto &particle : particle_handler.particles_in_cell(cell)) \n            { \n              const Point<dim> &reference_location = \n                particle.get_reference_location(); \n              for (const unsigned int i : fe_values.dof_indices()) \n                cell_rhs(i) += \n                  (fe.shape_value(i, reference_location) * // phi_i(x_p) \n                   (-Constants::electrons_per_particle *   // N \n                    Constants::electron_charge));          // e \n            } \n\n// \u6700\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u628a\u8fd9\u4e2a\u5355\u5143\u683c\u7684\u8d21\u732e\u590d\u5236\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u8fb9\u7684\u5411\u91cf\u4e2d\u3002\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// @sect4{CathodeRaySimulator::solve}  \n\n// \u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\u53c8\u4e0e step-6 \u4e2d\u7684\u5b8c\u5168\u4e00\u6837\u3002\n\n  template <int dim> \n  void CathodeRaySimulator<dim>::solve_field() \n  { \n    SolverControl            solver_control(1000, 1e-12); \n    SolverCG<Vector<double>> solver(solver_control); \n\n    PreconditionSSOR<SparseMatrix<double>> preconditioner; \n    preconditioner.initialize(system_matrix, 1.2); \n\n    solver.solve(system_matrix, solution, system_rhs, preconditioner); \n\n    constraints.distribute(solution); \n  } \n// @sect4{CathodeRaySimulator::refine_grid}  \n\n// \u6700\u540e\u4e00\u4e2a\u4e0e\u573a\u76f8\u5173\u7684\u51fd\u6570\u662f\u7ec6\u5316\u7f51\u683c\u7684\u51fd\u6570\u3002\u6211\u4eec\u5c06\u5728\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u591a\u6b21\u8c03\u7528\u5b83\uff0c\u4ee5\u83b7\u5f97\u4e00\u4e2a\u80fd\u5f88\u597d\u5730\u9002\u5e94\u89e3\u7684\u7ed3\u6784\u7684\u7f51\u683c\uff0c\u7279\u522b\u662f\u89e3\u51b3\u89e3\u4e2d\u7531\u4e8e\u91cd\u5fc3\u89d2\u548c\u8fb9\u754c\u6761\u4ef6\u7c7b\u578b\u53d8\u5316\u7684\u5730\u65b9\u800c\u4ea7\u751f\u7684\u5404\u79cd\u5947\u5f02\u73b0\u8c61\u3002\u4f60\u53ef\u80fd\u60f3\u518d\u53c2\u8003\u4e00\u4e0b step-6 \u4ee5\u4e86\u89e3\u66f4\u591a\u7684\u7ec6\u8282\u3002\n\n  template <int dim> \n  void CathodeRaySimulator<dim>::refine_grid() \n  { \n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n\n    KellyErrorEstimator<dim>::estimate(dof_handler, \n                                       QGauss<dim - 1>(fe.degree + 1), \n                                       {}, \n                                       solution, \n                                       estimated_error_per_cell); \n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    estimated_error_per_cell, \n                                                    0.1, \n                                                    0.03); \n\n    triangulation.execute_coarsening_and_refinement(); \n  } \n// @sect4{CathodeRaySimulator::create_particles}  \n\n// \u73b0\u5728\u8ba9\u6211\u4eec\u6765\u770b\u770b\u5904\u7406\u7c92\u5b50\u7684\u51fd\u6570\u3002\u7b2c\u4e00\u4e2a\u662f\u5173\u4e8e\u7c92\u5b50\u7684\u521b\u5efa\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\uff0c\u5982\u679c\u7535\u573a $\\mathbf E=\\nabla V$ \u8d85\u8fc7\u67d0\u4e2a\u9608\u503c\uff0c\u5373\u5982\u679c $|\\mathbf E| \\ge E_\\text{threshold}$ \uff0c\u5e76\u4e14\u5982\u679c\u7535\u573a\u8fdb\u4e00\u6b65\u6307\u5411\u57df\u5185\uff08\u5373\u5982\u679c $\\mathbf E \\cdot \\mathbf n < 0$ \uff09\uff0c\u6211\u4eec\u5e0c\u671b\u5728\u9634\u6781\u7684\u5404\u70b9\u521b\u5efa\u4e00\u4e2a\u7c92\u5b50\u3002\u6b63\u5982\u6709\u9650\u5143\u65b9\u6cd5\u4e2d\u5e38\u89c1\u7684\u90a3\u6837\uff0c\u6211\u4eec\u5728\u7279\u5b9a\u7684\u8bc4\u4f30\u70b9\u8bc4\u4f30\u573a\uff08\u53ca\u5176\u5bfc\u6570\uff09\uff1b\u901a\u5e38\uff0c\u8fd9\u4e9b\u662f \"\u6b63\u4ea4\u70b9\"\uff0c\u56e0\u6b64\u6211\u4eec\u521b\u5efa\u4e86\u4e00\u4e2a \"\u6b63\u4ea4\u516c\u5f0f\"\uff0c\u6211\u4eec\u5c06\u7528\u5b83\u6765\u6307\u5b9a\u6211\u4eec\u8981\u8bc4\u4f30\u89e3\u51b3\u65b9\u6848\u7684\u70b9\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u5c06\u7b80\u5355\u5730\u91c7\u7528QMidpoint\uff0c\u610f\u5473\u7740\u6211\u4eec\u5c06\u53ea\u5728\u9762\u7684\u4e2d\u70b9\u68c0\u67e5\u9608\u503c\u6761\u4ef6\u3002\u7136\u540e\u6211\u4eec\u7528\u5b83\u6765\u521d\u59cb\u5316\u4e00\u4e2aFEFaceValues\u7c7b\u578b\u7684\u5bf9\u8c61\u6765\u8bc4\u4f30\u8fd9\u4e9b\u70b9\u7684\u89e3\u3002\n\n// \u7136\u540e\uff0c\u6240\u6709\u8fd9\u4e9b\u5c06\u88ab\u7528\u4e8e\u6240\u6709\u5355\u5143\u683c\u3001\u5b83\u4eec\u7684\u9762\uff0c\u7279\u522b\u662f\u90a3\u4e9b\u4f4d\u4e8e\u8fb9\u754c\u7684\u9762\uff0c\u800c\u4e14\u662f\u8fb9\u754c\u7684\u9634\u6781\u90e8\u5206\u7684\u5faa\u73af\u4e2d\u3002\n\n  template <int dim> \n  void CathodeRaySimulator<dim>::create_particles() \n  { \n    FEFaceValues<dim> fe_face_values(fe, \n                                     QMidpoint<dim - 1>(), \n                                     update_quadrature_points | \n                                       update_gradients | \n                                       update_normal_vectors); \n\n    std::vector<Tensor<1, dim>> solution_gradients( \n      fe_face_values.n_quadrature_points); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      for (const auto &face : cell->face_iterators()) \n        if (face->at_boundary() && \n            (face->boundary_id() == BoundaryIds::cathode)) \n          { \n            fe_face_values.reinit(cell, face); \n\n// \u6240\u4ee5\u6211\u4eec\u5df2\u7ecf\u627e\u5230\u4e86\u9634\u6781\u4e0a\u7684\u4e00\u4e2a\u9762\u3002\u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u8ba9FEFaceValues\u5bf9\u8c61\u8ba1\u7b97\u6bcf\u4e2a \"\u6b63\u4ea4 \"\u70b9\u7684\u89e3\u7684\u68af\u5ea6\uff0c\u5e76\u901a\u8fc7 @ref vector_valued \"\u77e2\u91cf\u503c\u95ee\u9898 \"\u6587\u4ef6\u6a21\u5757\u4e2d\u8ba8\u8bba\u7684\u65b9\u6cd5\uff0c\u4ee5\u5f20\u91cf\u53d8\u91cf\u7684\u5f62\u5f0f\u4ece\u68af\u5ea6\u4e2d\u63d0\u53d6\u7535\u573a\u5411\u91cf\u3002\n\n            const FEValuesExtractors::Scalar electric_potential(0); \n            fe_face_values[electric_potential].get_function_gradients( \n              solution, solution_gradients); \n            for (const unsigned int q_point : \n                 fe_face_values.quadrature_point_indices()) \n              { \n                const Tensor<1, dim> E = solution_gradients[q_point]; \n\n// \u53ea\u6709\u5f53\u7535\u573a\u5f3a\u5ea6\u8d85\u8fc7\u9608\u503c\u65f6\uff0c\u7535\u5b50\u624d\u80fd\u9003\u79bb\u9634\u6781\uff0c\u800c\u4e14\u5173\u952e\u662f\uff0c\u5982\u679c\u7535\u573a\u6307\u5411*\u57df\u5185\uff0c\u7535\u5b50\u624d\u80fd\u9003\u79bb\u9634\u6781\u3002      \u4e00\u65e6\u6211\u4eec\u68c0\u67e5\u4e86\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u5c31\u5728\u8fd9\u4e2a\u4f4d\u7f6e\u521b\u5efa\u4e00\u4e2a\u65b0\u7684 Particles::Particle \u5bf9\u8c61\uff0c\u5e76\u5c06\u5176\u63d2\u5165\u5230 Particles::ParticleHandler \u5bf9\u8c61\u4e2d\uff0c\u5e76\u8bbe\u7f6e\u4e00\u4e2a\u552f\u4e00\u7684ID\u3002            \u8fd9\u91cc\u552f\u4e00\u4e0d\u660e\u663e\u7684\u662f\uff0c\u6211\u4eec\u8fd8\u5c06\u8fd9\u4e2a\u7c92\u5b50\u4e0e\u6211\u4eec\u5f53\u524d\u6240\u5728\u7684\u5355\u5143\u683c\u7684\u53c2\u8003\u5750\u6807\u4e2d\u7684\u4f4d\u7f6e\u8054\u7cfb\u8d77\u6765\u3002\u8fd9\u6837\u505a\u662f\u56e0\u4e3a\u6211\u4eec\u5c06\u5728\u4e0b\u6e38\u51fd\u6570\u4e2d\u8ba1\u7b97\u8bf8\u5982\u7c92\u5b50\u4f4d\u7f6e\u7684\u7535\u573a\u7b49\u91cf\uff08\u4f8b\u5982\uff0c\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u66f4\u65b0\u5176\u4f4d\u7f6e\u65f6\u8ba1\u7b97\u4f5c\u7528\u4e8e\u5b83\u7684\u529b\uff09\u3002\u5728\u4efb\u610f\u5750\u6807\u4e0a\u8bc4\u4f30\u6709\u9650\u5143\u573a\u662f\u4e00\u4e2a\u76f8\u5f53\u6602\u8d35\u7684\u64cd\u4f5c\uff0c\u56e0\u4e3a\u5f62\u72b6\u51fd\u6570\u5b9e\u9645\u4e0a\u53ea\u5b9a\u4e49\u5728\u53c2\u8003\u5355\u5143\u4e0a\uff0c\u6240\u4ee5\u5f53\u8981\u6c42\u4e00\u4e2a\u4efb\u610f\u70b9\u7684\u7535\u573a\u65f6\uff0c\u6211\u4eec\u9996\u5148\u8981\u786e\u5b9a\u8fd9\u4e2a\u70b9\u7684\u53c2\u8003\u5750\u6807\u662f\u4ec0\u4e48\u3002\u4e3a\u4e86\u907f\u514d\u53cd\u590d\u64cd\u4f5c\uff0c\u6211\u4eec\u4e00\u6b21\u6027\u5730\u786e\u5b9a\u8fd9\u4e9b\u5750\u6807\uff0c\u7136\u540e\u5c06\u8fd9\u4e9b\u53c2\u8003\u5750\u6807\u76f4\u63a5\u5b58\u50a8\u5728\u7c92\u5b50\u4e0a\u3002\n\n                if ((E * fe_face_values.normal_vector(q_point) < 0) && \n                    (E.norm() > Constants::E_threshold)) \n                  { \n                    const Point<dim> &location = \n                      fe_face_values.quadrature_point(q_point); \n\n                    Particles::Particle<dim> new_particle; \n                    new_particle.set_location(location); \n                    new_particle.set_reference_location( \n                      mapping.transform_real_to_unit_cell(cell, location)); \n                    new_particle.set_id(next_unused_particle_id); \n                    particle_handler.insert_particle(new_particle, cell); \n\n                    ++next_unused_particle_id; \n                  } \n              } \n          } \n\n// \u5728\u6240\u6709\u8fd9\u4e9b\u63d2\u5165\u7ed3\u675f\u65f6\uff0c\u6211\u4eec\u8ba9`particle_handler`\u66f4\u65b0\u5b83\u6240\u5b58\u50a8\u7684\u7c92\u5b50\u7684\u4e00\u4e9b\u5185\u90e8\u7edf\u8ba1\u6570\u636e\u3002\n\n    particle_handler.update_cached_numbers(); \n  } \n// @sect4{CathodeRaySimulator::move_particles}  \n\n// \u7b2c\u4e8c\u4e2a\u4e0e\u7c92\u5b50\u6709\u5173\u7684\u51fd\u6570\u662f\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u79fb\u52a8\u7c92\u5b50\u7684\u51fd\u6570\u3002\u8981\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u6240\u6709\u7684\u5355\u5143\u683c\u3001\u6bcf\u4e2a\u5355\u5143\u683c\u4e2d\u7684\u7c92\u5b50\u4e0a\u5faa\u73af\uff0c\u5e76\u8bc4\u4f30\u6bcf\u4e2a\u7c92\u5b50\u4f4d\u7f6e\u7684\u7535\u573a\u3002\n\n// \u8fd9\u91cc\u4f7f\u7528\u7684\u65b9\u6cd5\u5728\u6982\u5ff5\u4e0a\u4e0e`assemble_system()`\u51fd\u6570\u4e2d\u4f7f\u7528\u7684\u76f8\u540c\u3002\u6211\u4eec\u5728\u6240\u6709\u5355\u5143\u4e2d\u5faa\u73af\uff0c\u627e\u5230\u4f4d\u4e8e\u90a3\u91cc\u7684\u7c92\u5b50\uff08\u540c\u6837\u8981\u6ce8\u610f\u8fd9\u91cc\u7528\u6765\u5bfb\u627e\u8fd9\u4e9b\u7c92\u5b50\u7684\u7b97\u6cd5\u7684\u4f4e\u6548\u7387\uff09\uff0c\u5e76\u4f7f\u7528FEPointEvaluation\u5bf9\u8c61\u6765\u8bc4\u4f30\u8fd9\u4e9b\u4f4d\u7f6e\u7684\u68af\u5ea6\u3002\n\n  template <int dim> \n  void CathodeRaySimulator<dim>::move_particles() \n  { \n    const double dt = time.get_next_step_size(); \n\n    Vector<double>            solution_values(fe.n_dofs_per_cell()); \n    FEPointEvaluation<1, dim> evaluator(mapping, fe, update_gradients); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (particle_handler.n_particles_in_cell(cell) > 0) \n        { \n          const typename Particles::ParticleHandler< \n            dim>::particle_iterator_range particles_in_cell = \n            particle_handler.particles_in_cell(cell); \n\n          std::vector<Point<dim>> particle_positions; \n          for (const auto &particle : particles_in_cell) \n            particle_positions.push_back(particle.get_reference_location()); \n\n          cell->get_dof_values(solution, solution_values); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u5411FEPointEvaluation\u5bf9\u8c61\u8be2\u95ee\u8fd9\u4e9b\u4f4d\u7f6e\u7684\u89e3\u51b3\u65b9\u6848\u7684\u68af\u5ea6\uff08\u5373\u7535\u573a $\\mathbf E$ \uff09\uff0c\u5e76\u5728\u5404\u4e2a\u7c92\u5b50\u4e0a\u5faa\u73af\u3002\n\n          evaluator.reinit(cell, particle_positions); \n          evaluator.evaluate(make_array_view(solution_values), \n                             EvaluationFlags::gradients); \n\n          { \n            typename Particles::ParticleHandler<dim>::particle_iterator \n              particle = particles_in_cell.begin(); \n            for (unsigned int particle_index = 0; \n                 particle != particles_in_cell.end(); \n                 ++particle, ++particle_index) \n              { \n                const Tensor<1, dim> &E = \n                  evaluator.get_gradient(particle_index); \n\n// \u73b0\u5728\u6211\u4eec\u5df2\u7ecf\u5f97\u5230\u4e86\u5176\u4e2d\u4e00\u4e2a\u7c92\u5b50\u4f4d\u7f6e\u7684\u7535\u573a\uff0c\u6211\u4eec\u9996\u5148\u7528\u5b83\u6765\u66f4\u65b0\u901f\u5ea6\uff0c\u7136\u540e\u66f4\u65b0\u4f4d\u7f6e\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u4ece\u7c92\u5b50\u7684\u5c5e\u6027\u4e2d\u83b7\u53d6\u65e7\u7684\u901f\u5ea6\uff0c\u8ba1\u7b97\u52a0\u901f\u5ea6\uff0c\u66f4\u65b0\u901f\u5ea6\uff0c\u5e76\u5c06\u8fd9\u4e2a\u65b0\u7684\u901f\u5ea6\u518d\u6b21\u5b58\u50a8\u5728\u7c92\u5b50\u7684\u5c5e\u6027\u4e2d\u3002\u56de\u987e\u4e00\u4e0b\uff0c\u8fd9\u5bf9\u5e94\u4e8e\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\u4ee5\u4e0b\u4e00\u7ec4\u66f4\u65b0\u65b9\u7a0b\u4e2d\u7684\u7b2c\u4e00\u4e2a\u3002      \n      //  @f{align*}{\n      //      \\frac{{\\mathbf v}_i^{(n)}\n      //            -{\\mathbf v}_i^{(n-1)}}{\\Delta t}\n      //      &= \\frac{e\\nabla V^{(n)}}{m}\n      //   \\\\ \\frac{{\\mathbf x}_i^{(n)}-{\\mathbf x}_i^{(n-1)}}\n      //           {\\Delta t} &= {\\mathbf v}_i^{(n)}.\n      //  @f}\n\n                const Tensor<1, dim> old_velocity(particle->get_properties()); \n\n                const Tensor<1, dim> acceleration = \n                  Constants::electron_charge / Constants::electron_mass * E; \n\n                const Tensor<1, dim> new_velocity = \n                  old_velocity + acceleration * dt; \n\n                particle->set_properties(make_array_view(new_velocity)); \n\n// \u6709\u4e86\u65b0\u7684\u901f\u5ea6\uff0c\u6211\u4eec\u4e5f\u5c31\u53ef\u4ee5\u66f4\u65b0\u7c92\u5b50\u7684\u4f4d\u7f6e\uff0c\u5e76\u544a\u8bc9\u7c92\u5b50\u8fd9\u4e2a\u4f4d\u7f6e\u3002\n\n                const Point<dim> new_location = \n                  particle->get_location() + dt * new_velocity; \n                particle->set_location(new_location); \n              } \n          } \n        } \n\n// \u5728\u66f4\u65b0\u4e86\u6240\u6709\u7c92\u5b50\u7684\u4f4d\u7f6e\u548c\u5c5e\u6027\uff08\u5373\u901f\u5ea6\uff09\u4e4b\u540e\uff0c\u6211\u4eec\u9700\u8981\u786e\u4fdd`particle_handler`\u518d\u6b21\u77e5\u9053\u5b83\u4eec\u5728\u54ea\u4e2a\u5355\u5143\u4e2d\uff0c\u4ee5\u53ca\u5b83\u4eec\u5728\u53c2\u8003\u5355\u5143\u5750\u6807\u7cfb\u4e2d\u7684\u4f4d\u7f6e\u3002\u4e0b\u9762\u7684\u51fd\u6570\u5c31\u662f\u8fd9\u6837\u505a\u7684\u3002(\u5b83\u8fd8\u786e\u4fdd\u5728\u5e76\u884c\u8ba1\u7b97\u4e2d\uff0c\u5982\u679c\u7c92\u5b50\u4ece\u4e00\u4e2a\u5904\u7406\u5668\u62e5\u6709\u7684\u5b50\u57df\u79fb\u52a8\u5230\u53e6\u4e00\u4e2a\u5904\u7406\u5668\u62e5\u6709\u7684\u5b50\u57df\uff0c\u90a3\u4e48\u7c92\u5b50\u4f1a\u4ece\u4e00\u4e2a\u5904\u7406\u5668\u79fb\u52a8\u5230\u53e6\u4e00\u4e2a\u5904\u7406\u5668\u3002)\n\n    particle_handler.sort_particles_into_subdomains_and_cells(); \n  } \n// @sect4{CathodeRaySimulator::track_lost_particle}  \n\n// \u6700\u540e\u4e00\u4e2a\u4e0e\u7c92\u5b50\u76f8\u5173\u7684\u51fd\u6570\u662f\u5f53\u4e00\u4e2a\u7c92\u5b50\u4ece\u6a21\u62df\u4e2d\u4e22\u5931\u65f6\u88ab\u8c03\u7528\u7684\u51fd\u6570\u3002\u8fd9\u901a\u5e38\u53d1\u751f\u5728\u5b83\u79bb\u5f00\u57df\u7684\u65f6\u5019\u3002\u5982\u679c\u53d1\u751f\u8fd9\u79cd\u60c5\u51b5\uff0c\u8fd9\u4e2a\u51fd\u6570\u4f1a\u540c\u65f6\u8c03\u7528\u5355\u5143\uff08\u6211\u4eec\u53ef\u4ee5\u8be2\u95ee\u5b83\u7684\u65b0\u4f4d\u7f6e\uff09\u548c\u5b83\u4e4b\u524d\u6240\u5728\u7684\u5355\u5143\u3002\u7136\u540e\uff0c\u8be5\u51fd\u6570\u4e0d\u65ad\u8ddf\u8e2a\u66f4\u65b0\u8fd9\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u4e22\u5931\u7684\u7c92\u5b50\u6570\uff0c\u4e22\u5931\u7684\u7c92\u5b50\u603b\u6570\uff0c\u7136\u540e\u4f30\u8ba1\u8be5\u7c92\u5b50\u662f\u5426\u901a\u8fc7\u9633\u6781\u4e2d\u95f4\u7684\u5b54\u79bb\u5f00\u3002\u6211\u4eec\u8fd9\u6837\u505a\uff0c\u9996\u5148\u68c0\u67e5\u5b83\u6700\u540e\u6240\u5728\u7684\u5355\u5143\u662f\u5426\u6709\u4e00\u4e2a $x$ \u5750\u6807\u5728\u53f3\u8fb9\u8fb9\u754c\u7684\u5de6\u8fb9\uff08\u4f4d\u4e8e $x=4$ \uff09\uff0c\u800c\u7c92\u5b50\u73b0\u5728\u7684\u4f4d\u7f6e\u5728\u53f3\u8fb9\u8fb9\u754c\u7684\u53f3\u8fb9\u3002\u5982\u679c\u662f\u8fd9\u6837\u7684\u8bdd\uff0c\u6211\u4eec\u5c31\u8ba1\u7b97\u51fa\u5b83\u7684\u8fd0\u52a8\u65b9\u5411\u77e2\u91cf\uff0c\u8fd9\u4e2a\u65b9\u5411\u77e2\u91cf\u88ab\u5f52\u4e00\u5316\u4e86\uff0c\u6240\u4ee5\u65b9\u5411\u77e2\u91cf\u7684 $x$ \u5206\u91cf\u7b49\u4e8e $1$  \u3002\u6709\u4e86\u8fd9\u4e2a\u65b9\u5411\u77e2\u91cf\uff0c\u6211\u4eec\u53ef\u4ee5\u8ba1\u7b97\u51fa\u5b83\u4e0e\u76f4\u7ebf $x=4$ \u7684\u76f8\u4ea4\u4f4d\u7f6e\u3002\u5982\u679c\u8fd9\u4e2a\u76f8\u4ea4\u70b9\u5728 $0.5$ \u548c $1.5$ \u4e4b\u95f4\uff0c\u90a3\u4e48\u6211\u4eec\u5c31\u58f0\u79f0\u7c92\u5b50\u4ece\u5b54\u4e2d\u79bb\u5f00\uff0c\u5e76\u589e\u52a0\u4e00\u4e2a\u8ba1\u6570\u5668\u3002\n\n  template <int dim> \n  void CathodeRaySimulator<dim>::track_lost_particle( \n    const typename Particles::ParticleIterator<dim> &        particle, \n    const typename Triangulation<dim>::active_cell_iterator &cell) \n  { \n    ++n_recently_lost_particles; \n    ++n_total_lost_particles; \n\n    const Point<dim> current_location              = particle->get_location(); \n    const Point<dim> approximate_previous_location = cell->center(); \n\n    if ((approximate_previous_location[0] < 4) && (current_location[0] > 4)) \n      { \n        const Tensor<1, dim> direction = \n          (current_location - approximate_previous_location) / \n          (current_location[0] - approximate_previous_location[0]); \n\n        const double right_boundary_intercept = \n          approximate_previous_location[1] + \n          (4 - approximate_previous_location[0]) * direction[1]; \n        if ((right_boundary_intercept > 0.5) && \n            (right_boundary_intercept < 1.5)) \n          ++n_particles_lost_through_anode; \n      } \n  } \n\n//  @sect4{CathodeRaySimulator::update_timestep_size}  \n\n// \u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u8be6\u7ec6\u8ba8\u8bba\u7684\u90a3\u6837\uff0c\u6211\u4eec\u9700\u8981\u5c0a\u91cd\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u6761\u4ef6\uff0c\u5373\u9897\u7c92\u5728\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u4e0d\u80fd\u79fb\u52a8\u8d85\u8fc7\u4e00\u4e2a\u5355\u5143\u3002\u4e3a\u4e86\u786e\u4fdd\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u9996\u5148\u8ba1\u7b97\u6bcf\u4e2a\u5355\u5143\u4e0a\u6240\u6709\u7c92\u5b50\u7684\u6700\u5927\u901f\u5ea6\uff0c\u7136\u540e\u7528\u8be5\u901f\u5ea6\u9664\u4ee5\u5355\u5143\u5927\u5c0f\u3002\u7136\u540e\uff0c\u6211\u4eec\u4f7f\u7528\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u5b89\u5168\u7cfb\u6570\uff0c\u5c06\u4e0b\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u8ba1\u7b97\u4e3a\u6240\u6709\u5355\u5143\u4e0a\u8fd9\u4e2a\u91cf\u7684\u6700\u5c0f\u503c\uff0c\u5e76\u4f7f\u7528 DiscreteTime::set_desired_time_step_size() \u51fd\u6570\u5c06\u5176\u8bbe\u5b9a\u4e3a\u6240\u9700\u7684\u65f6\u95f4\u6b65\u957f\u3002\n\n  template <int dim> \n  void CathodeRaySimulator<dim>::update_timestep_size() \n  { \n    if (time.get_step_number() > 0) \n      { \n        double min_cell_size_over_velocity = std::numeric_limits<double>::max(); \n\n        for (const auto &cell : dof_handler.active_cell_iterators()) \n          if (particle_handler.n_particles_in_cell(cell) > 0) \n            { \n              const double cell_size = cell->minimum_vertex_distance(); \n\n              double max_particle_velocity(0.0); \n\n              for (const auto &particle : \n                   particle_handler.particles_in_cell(cell)) \n                { \n                  const Tensor<1, dim> velocity(particle.get_properties()); \n                  max_particle_velocity = \n                    std::max(max_particle_velocity, velocity.norm()); \n                } \n\n              if (max_particle_velocity > 0) \n                min_cell_size_over_velocity = \n                  std::min(min_cell_size_over_velocity, \n                           cell_size / max_particle_velocity); \n            } \n\n        constexpr double c_safety = 0.5; \n        time.set_desired_next_step_size(c_safety * 0.5 * \n                                        min_cell_size_over_velocity); \n      } \n\n// \u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\uff0c\u6211\u4eec\u5fc5\u987b\u4ee5\u4e0d\u540c\u7684\u65b9\u5f0f\u5bf9\u5f85\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\uff0c\u56e0\u4e3a\u5728\u90a3\u91cc\uff0c\u7c92\u5b50\u8fd8\u6ca1\u6709\u51fa\u73b0\uff0c\u6216\u8005\u8fd8\u6ca1\u6709\u6211\u4eec\u8ba1\u7b97\u5408\u7406\u6b65\u957f\u6240\u9700\u7684\u76f8\u5173\u4fe1\u606f\u3002\u4e0b\u9762\u7684\u516c\u5f0f\u9075\u5faa\u4ecb\u7ecd\u4e2d\u7684\u8ba8\u8bba\u3002\n\n    else \n      { \n        const QTrapezoid<dim> vertex_quadrature; \n        FEValues<dim> fe_values(fe, vertex_quadrature, update_gradients); \n\n        std::vector<Tensor<1, dim>> field_gradients(vertex_quadrature.size()); \n\n        double min_timestep = std::numeric_limits<double>::max(); \n\n        for (const auto &cell : dof_handler.active_cell_iterators()) \n          if (particle_handler.n_particles_in_cell(cell) > 0) \n            { \n              const double cell_size = cell->minimum_vertex_distance(); \n\n              fe_values.reinit(cell); \n              fe_values.get_function_gradients(solution, field_gradients); \n\n              double max_E = 0; \n              for (const auto q_point : fe_values.quadrature_point_indices()) \n                max_E = std::max(max_E, field_gradients[q_point].norm()); \n\n              if (max_E > 0) \n                min_timestep = \n                  std::min(min_timestep, \n                           std::sqrt(0.5 * cell_size * \n                                     Constants::electron_mass / \n                                     Constants::electron_charge / max_E)); \n            } \n\n        time.set_desired_next_step_size(min_timestep); \n      } \n  } \n\n//  @sect4{The <code>CathodeRaySimulator::output_results()</code> function}  \n\n// \u5b9e\u73b0\u6574\u4e2a\u7b97\u6cd5\u7684\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u662f\u751f\u6210\u56fe\u5f62\u8f93\u51fa\u7684\u51fd\u6570\u3002\u5728\u76ee\u524d\u7684\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u60f3\u540c\u65f6\u8f93\u51fa\u7535\u52bf\u573a\u4ee5\u53ca\u7c92\u5b50\u7684\u4f4d\u7f6e\u548c\u901f\u5ea6\u3002\u4f46\u6211\u4eec\u4e5f\u60f3\u8f93\u51fa\u7535\u573a\uff0c\u5373\u89e3\u51b3\u65b9\u6848\u7684\u68af\u5ea6\u3002\n\n// deal.II\u6709\u4e00\u4e2a\u4e00\u822c\u7684\u65b9\u6cd5\uff0c\u53ef\u4ee5\u4ece\u89e3\u51b3\u65b9\u6848\u4e2d\u8ba1\u7b97\u51fa\u6d3e\u751f\u91cf\uff0c\u5e76\u8f93\u51fa\u8fd9\u4e9b\u91cf\u3002\u5728\u8fd9\u91cc\uff0c\u8fd9\u662f\u7535\u573a\uff0c\u4f46\u4e5f\u53ef\u4ee5\u662f\u5176\u4ed6\u7684\u91cf--\u6bd4\u5982\u8bf4\uff0c\u7535\u573a\u7684\u6cd5\u7ebf\uff0c\u6216\u8005\u4e8b\u5b9e\u4e0a\u4efb\u4f55\u5176\u4ed6\u4eba\u4eec\u60f3\u4ece\u89e3 $V_h(\\mathbf x)$ \u6216\u5176\u5bfc\u6570\u4e2d\u8ba1\u7b97\u7684\u91cf\u3002\u8fd9\u4e2a\u4e00\u822c\u7684\u89e3\u51b3\u65b9\u6848\u4f7f\u7528\u4e86DataPostprocessor\u7c7b\uff0c\u5728\u50cf\u8fd9\u91cc\u7684\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u60f3\u8f93\u51fa\u4e00\u4e2a\u4ee3\u8868\u77e2\u91cf\u573a\u7684\u91cf\uff0c\u5219\u4f7f\u7528DataPostprocessorVector\u7c7b\u3002\n\n// \u4e0e\u5176\u5c1d\u8bd5\u89e3\u91ca\u8fd9\u4e2a\u7c7b\u662f\u5982\u4f55\u5de5\u4f5c\u7684\uff0c\u4e0d\u5982\u8ba9\u6211\u4eec\u7b80\u5355\u5730\u53c2\u8003\u4e00\u4e0bDataPostprocessorVector\u7c7b\u7684\u6587\u6863\uff0c\u8fd9\u4e2a\u6848\u4f8b\u57fa\u672c\u4e0a\u662f\u4e00\u4e2a\u6709\u636e\u53ef\u67e5\u7684\u4f8b\u5b50\u3002\n\n  template <int dim> \n  class ElectricFieldPostprocessor : public DataPostprocessorVector<dim> \n  { \n  public: \n    ElectricFieldPostprocessor() \n      : DataPostprocessorVector<dim>(\"electric_field\", update_gradients) \n    {} \n\n    virtual void evaluate_scalar_field( \n      const DataPostprocessorInputs::Scalar<dim> &input_data, \n      std::vector<Vector<double>> &computed_quantities) const override \n    { \n      AssertDimension(input_data.solution_gradients.size(), \n                      computed_quantities.size()); \n\n      for (unsigned int p = 0; p < input_data.solution_gradients.size(); ++p) \n        { \n          AssertDimension(computed_quantities[p].size(), dim); \n          for (unsigned int d = 0; d < dim; ++d) \n            computed_quantities[p][d] = input_data.solution_gradients[p][d]; \n        } \n    } \n  }; \n\n// \u6709\u4e86\u8fd9\u4e2a\uff0c`output_results()`\u51fd\u6570\u5c31\u53d8\u5f97\u76f8\u5bf9\u7b80\u5355\u4e86\u3002\u6211\u4eec\u4f7f\u7528DataOut\u7c7b\uff0c\u5c31\u50cf\u6211\u4eec\u5728\u4ee5\u524d\u51e0\u4e4e\u6240\u6709\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u7684\u90a3\u6837\uff0c\u6765\u8f93\u51fa\u89e3\u51b3\u65b9\u6848\uff08\"\u7535\u52a8\u52bf\"\uff09\uff0c\u6211\u4eec\u4f7f\u7528\u4e0a\u9762\u5b9a\u4e49\u7684\u540e\u5904\u7406\u7a0b\u5e8f\u6765\u8f93\u51fa\u5176\u68af\u5ea6\uff08\"\u7535\u573a\"\uff09\u3002\u8fd9\u4e9b\u90fd\u88ab\u5199\u5165\u4e00\u4e2aVTU\u683c\u5f0f\u7684\u6587\u4ef6\u4e2d\uff0c\u540c\u65f6\u5c06\u5f53\u524d\u65f6\u95f4\u548c\u65f6\u95f4\u6b65\u957f\u4e0e\u8be5\u6587\u4ef6\u8054\u7cfb\u8d77\u6765\u3002\n\n  template <int dim> \n  void CathodeRaySimulator<dim>::output_results() const \n  { \n    { \n      ElectricFieldPostprocessor<dim> electric_field; \n      DataOut<dim>                    data_out; \n      data_out.attach_dof_handler(dof_handler); \n      data_out.add_data_vector(solution, \"electric_potential\"); \n      data_out.add_data_vector(solution, electric_field); \n      data_out.build_patches(); \n\n      data_out.set_flags( \n        DataOutBase::VtkFlags(time.get_current_time(), time.get_step_number())); \n\n      std::ofstream output(\"solution-\" + \n                           Utilities::int_to_string(time.get_step_number(), 4) + \n                           \".vtu\"); \n      data_out.write_vtu(output); \n    } \n\n// \u8f93\u51fa\u7c92\u5b50\u7684\u4f4d\u7f6e\u548c\u5c5e\u6027\u5e76\u4e0d\u590d\u6742\u3002 Particles::DataOut \u7c7b\u626e\u6f14\u4e86\u7c92\u5b50\u7684DataOut\u7c7b\u7684\u89d2\u8272\uff0c\u6211\u4eec\u6240\u8981\u505a\u7684\u5c31\u662f\u544a\u8bc9\u8be5\u7c7b\u4ece\u54ea\u91cc\u83b7\u53d6\u7c92\u5b50\uff0c\u4ee5\u53ca\u5982\u4f55\u89e3\u91ca\u5c5e\u6027\u4e2d\u7684`dim`\u5206\u91cf--\u5373\u4f5c\u4e3a\u8868\u793a\u901f\u5ea6\u7684\u5355\u4e00\u77e2\u91cf\uff0c\u800c\u4e0d\u662f\u4f5c\u4e3a`dim`\u6807\u91cf\u5c5e\u6027\u3002\u5269\u4e0b\u7684\u5c31\u548c\u4e0a\u9762\u4e00\u6837\u4e86\u3002\n\n    { \n      Particles::DataOut<dim, dim> particle_out; \n      particle_out.build_patches( \n        particle_handler, \n        std::vector<std::string>(dim, \"velocity\"), \n        std::vector<DataComponentInterpretation::DataComponentInterpretation>( \n          dim, DataComponentInterpretation::component_is_part_of_vector)); \n\n      particle_out.set_flags( \n        DataOutBase::VtkFlags(time.get_current_time(), time.get_step_number())); \n\n      std::ofstream output(\"particles-\" + \n                           Utilities::int_to_string(time.get_step_number(), 4) + \n                           \".vtu\"); \n      particle_out.write_vtu(output); \n    } \n  } \n// @sect4{CathodeRaySimulator::run}  \n\n// \u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u7684\u6700\u540e\u4e00\u4e2a\u6210\u5458\u51fd\u6570\u662f\u9a71\u52a8\u3002\u5728\u9876\u5c42\uff0c\u5b83\u901a\u8fc7\u5728\u4e00\u8fde\u4e32\u8d8a\u6765\u8d8a\u7ec6\u7684\u7f51\u683c\u4e0a\u6c42\u89e3\u95ee\u9898\uff08\u5c1a\u672a\u521b\u5efa\u7c92\u5b50\uff09\uff0c\u5bf9\u7f51\u683c\u8fdb\u884c\u591a\u6b21\u7ec6\u5316\u3002\n\n  template <int dim> \n  void CathodeRaySimulator<dim>::run() \n  { \n    make_grid(); \n\n//\u5728\u524d\u9762\u505a\u51e0\u4e2a\u7ec6\u5316\u5faa\u73af\n\n    const unsigned int n_pre_refinement_cycles = 3; \n    for (unsigned int refinement_cycle = 0; \n         refinement_cycle < n_pre_refinement_cycles; \n         ++refinement_cycle) \n      { \n        setup_system(); \n        assemble_system(); \n        solve_field(); \n        refine_grid(); \n      } \n\n// \u73b0\u5728\u8fdb\u884c\u65f6\u95f4\u4e0a\u7684\u5faa\u73af\u3002\u8fd9\u4e2a\u6b65\u9aa4\u7684\u987a\u5e8f\u7d27\u8ddf\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u7b97\u6cd5\u5927\u7eb2\u3002\u6b63\u5982\u5728DiscreteTime\u7c7b\u7684\u6587\u6863\u4e2d\u8be6\u7ec6\u8ba8\u8bba\u7684\u90a3\u6837\uff0c\u867d\u7136\u6211\u4eec\u5c06\u573a\u548c\u7c92\u5b50\u4fe1\u606f\u5411\u524d\u79fb\u52a8\u4e86\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\uff0c\u4f46\u5b58\u50a8\u5728`time`\u53d8\u91cf\u4e2d\u7684\u65f6\u95f4\u4e0e\u8fd9\u4e9b\u91cf\u7684\uff08\u90e8\u5206\uff09\u4f4d\u7f6e\u4e0d\u4e00\u81f4\uff08\u5728DiscreteTime\u7684\u5b57\u5178\u4e2d\uff0c\u8fd9\u5c31\u662f \"\u66f4\u65b0\u9636\u6bb5\"\uff09\u3002\u5bf9`time.advance_time()`\u7684\u8c03\u7528\u901a\u8fc7\u5c06`time`\u53d8\u91cf\u8bbe\u7f6e\u4e3a\u573a\u548c\u7c92\u5b50\u5df2\u7ecf\u5904\u4e8e\u7684\u65f6\u95f4\u800c\u4f7f\u4e00\u5207\u91cd\u65b0\u4fdd\u6301\u4e00\u81f4\uff0c\u4e00\u65e6\u6211\u4eec\u5904\u4e8e\u8fd9\u4e2a \"\u4e00\u81f4\u9636\u6bb5\"\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u751f\u6210\u56fe\u5f62\u8f93\u51fa\u5e76\u5c06\u6a21\u62df\u7684\u5f53\u524d\u72b6\u6001\u7684\u4fe1\u606f\u5199\u5165\u5c4f\u5e55\u3002\n\n    setup_system(); \n    do \n      { \n        std::cout << \"Timestep \" << time.get_step_number() + 1 << std::endl; \n        std::cout << \"  Field degrees of freedom:                 \" \n                  << dof_handler.n_dofs() << std::endl; \n\n        assemble_system(); \n        solve_field(); \n\n        create_particles(); \n        std::cout << \"  Total number of particles in simulation:  \" \n                  << particle_handler.n_global_particles() << std::endl; \n\n        n_recently_lost_particles = 0; \n        update_timestep_size(); \n        move_particles(); \n\n        time.advance_time(); \n\n        output_results(); \n\n        std::cout << \"  Number of particles lost this time step:  \" \n                  << n_recently_lost_particles << std::endl; \n        if (n_total_lost_particles > 0) \n          std::cout << \"  Fraction of particles lost through anode: \" \n                    << 1. * n_particles_lost_through_anode / \n                         n_total_lost_particles \n                    << std::endl; \n\n        std::cout << std::endl \n                  << \"  Now at t=\" << time.get_current_time() \n                  << \", dt=\" << time.get_previous_step_size() << '.' \n                  << std::endl \n                  << std::endl; \n      } \n    while (time.is_at_end() == false); \n  } \n} // namespace Step19 \n\n//  @sect3{The <code>main</code> function}  \n\n// \u7a0b\u5e8f\u7684\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u53c8\u662f`main()`\u51fd\u6570\u3002\u81ea step-6 \u4ee5\u6765\uff0c\u5b83\u5728\u6240\u6709\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u90fd\u6ca1\u6709\u53d8\u5316\uff0c\u56e0\u6b64\u6ca1\u6709\u4ec0\u4e48\u65b0\u7684\u5185\u5bb9\u9700\u8981\u8ba8\u8bba\u3002\n\nint main() \n{ \n  try \n    { \n      Step19::CathodeRaySimulator<2> cathode_ray_simulator_2d; \n      cathode_ray_simulator_2d.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\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\n\n", "meta": {"hexsha": "be8eaa58a15f240ccc64cf1a6095863b7e6a76b3", "size": 31918, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-19/step-19.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-19/step-19.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-19/step-19.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.862396204, "max_line_length": 381, "alphanum_fraction": 0.6067736074, "num_tokens": 11310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5054762487778328}}
{"text": "/*\n *****************************************************************\n *                     String Toolkit Library                    *\n *                                                               *\n * Random Line Selection                                         *\n * Author: Arash Partow (2002-2018)                              *\n * URL: http://www.partow.net/programming/strtk/index.html       *\n *                                                               *\n * Copyright notice:                                             *\n * Free use of the String Toolkit Library is permitted under the *\n * guidelines and in accordance with the most current version of *\n * the MIT License.                                              *\n * http://www.opensource.org/licenses/MIT                        *\n *                                                               *\n *****************************************************************\n*/\n\n\n/*\n   Description: This is a solution to the problem of randomly selecting a line\n                from a text file in the most efficient way possible taking into\n                account time and space complexities, also ensuring that the\n                probability of the line selected is exactly 1/N where N is the\n                number of lines in the text file - It should be noted that the\n                lines can be of varying length.\n*/\n\n\n#include <cstddef>\n#include <iostream>\n#include <iterator>\n#include <string>\n#include <deque>\n#include <ctime>\n\n#include <boost/random.hpp>\n//#include <random>\n\n#include \"strtk.hpp\"\n\n#ifndef strtk_enable_random\n   #error This example requires random\n#endif\n\n\nclass random_line_selector\n{\npublic:\n\n   random_line_selector(std::string& line, const std::size_t& seed = 0xA5A5A5A5)\n   : line_count_(1),\n     line_(line),\n     rng_(seed)\n   {}\n\n   inline void operator()(const std::string& s)\n   {\n      if (rng_() < (1.0 / line_count_))\n         line_ = s;\n      ++line_count_;\n   }\n\nprivate:\n\n   random_line_selector operator=(const random_line_selector&);\n\n   std::size_t line_count_; // should be long long\n   std::string& line_;\n   strtk::uniform_real_rng rng_;\n};\n\nint main(int argc, char* argv[])\n{\n   if (2 != argc)\n   {\n      std::cout << \"usage: strtk_random_line <file name>\" << std::endl;\n      return 1;\n   }\n\n   std::string file_name = argv[1];\n   std::string line;\n\n   strtk::for_each_line(file_name,\n                        random_line_selector(line,static_cast<std::size_t>(::time(0))));\n\n   std::cout << line << std::endl;\n\n   return 0;\n}\n", "meta": {"hexsha": "a644162d87e582ffc312ceca6f64e1dcc19b38cb", "size": 2547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/ThirdParty/strtk/strtk/strtk_random_line.cpp", "max_stars_repo_name": "morrow1nd/ToyUtility", "max_stars_repo_head_hexsha": "0df3364a516de7a396b1cbb7975263506f41121d", "max_stars_repo_licenses": ["MIT"], "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/ThirdParty/strtk/strtk/strtk_random_line.cpp", "max_issues_repo_name": "morrow1nd/ToyUtility", "max_issues_repo_head_hexsha": "0df3364a516de7a396b1cbb7975263506f41121d", "max_issues_repo_licenses": ["MIT"], "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/ThirdParty/strtk/strtk/strtk_random_line.cpp", "max_forks_repo_name": "morrow1nd/ToyUtility", "max_forks_repo_head_hexsha": "0df3364a516de7a396b1cbb7975263506f41121d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3, "max_line_length": 88, "alphanum_fraction": 0.5060855909, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5054762435790408}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2017, 2018.\n// Modifications copyright (c) 2017-2018, 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\n#if defined(_MSC_VER)\n#pragma warning( disable : 4305 ) // truncation double -> float\n#endif // defined(_MSC_VER)\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/srs/projection.hpp>\n\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/algorithms/make.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n\ntemplate <template <typename, typename> class Projection, typename GeoPoint>\nvoid test_forward(GeoPoint const& geo_point1, GeoPoint const& geo_point2,\n        std::string const& sparams, int deviation = 1)\n{\n    typedef typename bg::coordinate_type<GeoPoint>::type coordinate_type;\n    typedef bg::model::d2::point_xy<coordinate_type> cartesian_point_type;\n    typedef bg::projections::parameters<double> parameters_type;\n    typedef bg::projections::detail::static_wrapper_f\n        <\n            Projection<coordinate_type, parameters_type>,\n            parameters_type\n        > projection_type;\n\n    try\n    {\n        bg::srs::detail::proj4_parameters params(sparams);\n        parameters_type par = bg::projections::detail::pj_init<double>(params);\n\n        projection_type prj(params, par);\n\n        cartesian_point_type xy1, xy2;\n        prj.forward(geo_point1, xy1);\n        prj.forward(geo_point2, xy2);\n\n        // Calculate distances in KM\n        int const distance_expected = static_cast<int>(bg::distance(geo_point1, geo_point2) / 1000.0);\n        int const distance_found = static_cast<int>(bg::distance(xy1, xy2) / 1000.0);\n\n        int const difference = std::abs(distance_expected - distance_found);\n        BOOST_CHECK_MESSAGE(difference <= 1 || difference == deviation,\n                \" projection: \" << projection_type::get_name()\n                << \" distance found: \" << distance_found\n                << \" expected: \" << distance_expected);\n\n// For debug:\n//        std::cout << projection_type::get_name() << \" \" << distance_expected\n//            << \" \" << distance_found\n//            << \" \" << (difference > 1 && difference != deviation ? \" *** WRONG ***\" : \"\")\n//            << \" \" << difference\n//            << std::endl;\n    }\n    catch(bg::projection_exception const& e)\n    {\n        std::cout << \"Exception in \" << projection_type::get_name() << \" : \" << e.what() << std::endl;\n    }\n    catch(...)\n    {\n        std::cout << \"Exception (unknown) in \" << projection_type::get_name() << std::endl;\n    }\n}\n\ntemplate <typename T>\nvoid test_all()\n{\n    typedef bg::model::point<T, 2, bg::cs::geographic<bg::degree> > geo_point_type;\n\n    geo_point_type amsterdam = bg::make<geo_point_type>(4.8925, 52.3731);\n    geo_point_type utrecht   = bg::make<geo_point_type>(5.1213, 52.0907);\n\n    // IMPORTANT: Compatible model has to be passed in order to assure correct initialization\n\n    test_forward<bg::projections::aea_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +lat_1=55 +lat_2=65\");\n    test_forward<bg::projections::aeqd_e>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\");\n    test_forward<bg::projections::aeqd_s>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n\n    test_forward<bg::projections::airy_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 4);\n    test_forward<bg::projections::aitoff_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::apian_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lon_0=11d32'00E\");\n    test_forward<bg::projections::august_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 14);\n\n    test_forward<bg::projections::bacon_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lon_0=11d32'00E\", 5);\n    test_forward<bg::projections::bipc_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 7);\n    test_forward<bg::projections::boggs_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lon_0=11d32'00E\", 2);\n\n    test_forward<bg::projections::bonne_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +lat_1=50\");\n    test_forward<bg::projections::bonne_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lat_1=50\", 33);\n\n    test_forward<bg::projections::cass_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\");\n    test_forward<bg::projections::cass_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::cc_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 52);\n\n    test_forward<bg::projections::cea_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +lon_0=11d32'00E\", 4);\n    test_forward<bg::projections::cea_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lon_0=11d32'00E\", 4);\n\n    test_forward<bg::projections::chamb_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lat_1=52 +lon_1=5 +lat_2=30 +lon_2=80 +lat_3=20 +lon_3=-50\", 2);\n    test_forward<bg::projections::collg_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 5);\n    test_forward<bg::projections::crast_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::denoy_spheroid>(amsterdam, utrecht,  \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::eck1_spheroid>(amsterdam, utrecht,  \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::eck2_spheroid>(amsterdam, utrecht,  \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::eck3_spheroid>(amsterdam, utrecht,  \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::eck4_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::eck5_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n\n    test_forward<bg::projections::eck6_spheroid>(amsterdam, utrecht,  \"+ellps=sphere +units=m\");\n\n    test_forward<bg::projections::eqc_spheroid>(amsterdam, utrecht,  \"+ellps=sphere +units=m\", 5);\n    test_forward<bg::projections::eqdc_ellipsoid>(amsterdam, utrecht,  \"+ellps=WGS84 +units=m +lat_1=60 +lat_2=0\");\n    test_forward<bg::projections::etmerc_ellipsoid>(amsterdam, utrecht,  \"+ellps=WGS84 +units=m\");\n    test_forward<bg::projections::euler_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lat_1=60 +lat_2=0\");\n\n    test_forward<bg::projections::fahey_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 5);\n    test_forward<bg::projections::fouc_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 6);\n    test_forward<bg::projections::fouc_s_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 4);\n    test_forward<bg::projections::gall_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::geocent_other>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\", 5);\n    test_forward<bg::projections::geos_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +h=40000000\", 13);\n    test_forward<bg::projections::gins8_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 7);\n\n    test_forward<bg::projections::gn_sinu_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +m=0.5 +n=1.785\");\n\n    test_forward<bg::projections::gnom_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 50);\n    test_forward<bg::projections::goode_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::gstmerc_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::hammer_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::hatano_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n\n    test_forward<bg::projections::healpix_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\", 6);\n    test_forward<bg::projections::healpix_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 6);\n    test_forward<bg::projections::rhealpix_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\", 6);\n    test_forward<bg::projections::rhealpix_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 6);\n\n    test_forward<bg::projections::imw_p_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +lat_1=20n +lat_2=60n +lon_1=5\");\n    test_forward<bg::projections::isea_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::kav5_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::kav7_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::krovak_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\");\n    test_forward<bg::projections::laea_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::lagrng_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +W=1\", 8);\n    test_forward<bg::projections::larr_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 13);\n    test_forward<bg::projections::lask_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 5);\n    test_forward<bg::projections::lcc_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +lat_1=20n +lat_2=60n\", 2);\n    test_forward<bg::projections::lcca_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +lat_0=30n +lat_1=55n +lat_2=60n\", 2);\n    test_forward<bg::projections::leac_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\", 8);\n    test_forward<bg::projections::loxim_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 3);\n    test_forward<bg::projections::lsat_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +lsat=1 +path=1\", 3);\n    test_forward<bg::projections::mbt_fps_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::mbt_s_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::mbtfpp_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::mbtfpq_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n\n    test_forward<bg::projections::mbtfps_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n\n    test_forward<bg::projections::merc_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\", 22);\n    test_forward<bg::projections::merc_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 22);\n\n    test_forward<bg::projections::mil_os_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\");\n    test_forward<bg::projections::mill_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 14);\n    test_forward<bg::projections::moll_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::murd1_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lat_1=20n +lat_2=60n\");\n    test_forward<bg::projections::murd2_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lat_1=20n +lat_2=60n\");\n    test_forward<bg::projections::murd3_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lat_1=20n +lat_2=60n\");\n    test_forward<bg::projections::natearth_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::nell_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 4);\n    test_forward<bg::projections::nell_h_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 3);\n    test_forward<bg::projections::nicol_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n\n    test_forward<bg::projections::oea_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lat_1=20n +lat_2=60n +lon_1=1e +lon_2=30e +m=1 +n=1\", 4);\n    test_forward<bg::projections::omerc_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +lat_1=20n +lat_2=60n  +lon_1=1e +lon_2=30e\");\n    test_forward<bg::projections::ortel_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::ortho_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 9);\n    test_forward<bg::projections::pconic_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lat_1=20n +lat_2=60n +lon_0=10E\");\n    test_forward<bg::projections::qsc_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\", 10);\n    test_forward<bg::projections::poly_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::putp1_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::putp2_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::putp3_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 6);\n    test_forward<bg::projections::putp3p_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 5);\n    test_forward<bg::projections::putp4p_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::putp5_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::putp5p_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 3);\n    test_forward<bg::projections::putp6_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::putp6p_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::qua_aut_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::robin_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::rouss_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\", 8);\n    test_forward<bg::projections::rpoly_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n\n    test_forward<bg::projections::sinu_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\");\n    test_forward<bg::projections::sinu_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n\n    test_forward<bg::projections::somerc_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\", 22);\n    test_forward<bg::projections::stere_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lat_ts=50n\", 8);\n    test_forward<bg::projections::sterea_ellipsoid>(amsterdam, utrecht, \"+lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m\");\n    test_forward<bg::projections::tcc_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::tcea_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::tissot_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lat_1=20n +lat_2=60n\", 2);\n\n    test_forward<bg::projections::tmerc_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::tmerc_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\");\n\n    test_forward<bg::projections::tpeqd_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lat_1=20n +lat_2=60n  +lon_1=0 +lon_2=30e\");\n    test_forward<bg::projections::tpers_spheroid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +tilt=50 +azi=20 +h=40000000\", 14);\n\n    // Elliptical usage required\n    // TODO: if spherical UPS is not supported then ups_spheroid should be removed\n    //test_forward<bg::projections::ups_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 3);\n    test_forward<bg::projections::ups_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\", 3);\n\n    test_forward<bg::projections::urm5_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +n=.3 +q=.3 +alpha=10\", 4);\n    test_forward<bg::projections::urmfps_spheroid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +n=0.50\", 4);\n\n    test_forward<bg::projections::utm_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +lon_0=11d32'00E\");\n\n    test_forward<bg::projections::vandg_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 13);\n    test_forward<bg::projections::vandg2_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 13);\n    test_forward<bg::projections::vandg3_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 13);\n    test_forward<bg::projections::vandg4_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::vitk1_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m +lat_1=20n +lat_2=60n\");\n    test_forward<bg::projections::wag1_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::wag2_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::wag3_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 3);\n    test_forward<bg::projections::wag4_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::wag5_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::wag6_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n    test_forward<bg::projections::wag7_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 2);\n    test_forward<bg::projections::weren_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 4);\n    test_forward<bg::projections::wink1_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 3);\n    test_forward<bg::projections::wink2_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\", 4);\n    test_forward<bg::projections::wintri_spheroid>(amsterdam, utrecht, \"+ellps=sphere +units=m\");\n\n    //    We SKIP ob_tran because it internally requires the factory and is, in that sense, not a static test\n    //    test_forward<bg::projections::ob_tran_oblique>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +o_proj=moll +o_lat_p=10 +o_lon_p=90 +o_lon_o=11.50\");\n    //    test_forward<bg::projections::ob_tran_transverse>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +o_proj=moll +o_lat_p=10 +o_lon_p=90 +o_lon_o=11.50\");\n\n    // TODO: wrong projections or parameters or input points\n//    test_forward<bg::projections::ocea_spheroid>(auckland, wellington, \"+ellps=sphere +units=m +lat_1=20s +lat_2=60s  +lon_1=165e +lon_2=175e\"); => distance is very large\n//    test_forward<bg::projections::nsper_spheroid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m +a=10 +h=40000000\"); => distance is 0\n//    test_forward<bg::projections::lee_os_ellipsoid>(amsterdam, utrecht, \"+ellps=WGS84 +units=m\"); => distance is 407\n\n\n    // Alaska\n    {\n        geo_point_type anchorage = bg::make<geo_point_type>(-149.90, 61.22);\n        geo_point_type juneau    = bg::make<geo_point_type>(-134.42, 58.30);\n        test_forward<bg::projections::alsk_ellipsoid>(anchorage, juneau, \"+ellps=WGS84 +units=m +lon_0=-150W\", 1);\n    }\n    // New Zealand\n    {\n        geo_point_type auckland   = bg::make<geo_point_type>(174.74, -36.84);\n        geo_point_type wellington = bg::make<geo_point_type>(177.78, -41.29);\n        test_forward<bg::projections::nzmg_ellipsoid>(auckland, wellington, \"+ellps=WGS84 +units=m\", 0);\n    }\n\n    // US\n    {\n        geo_point_type aspen  = bg::make<geo_point_type>(-106.84, 39.19);\n        geo_point_type denver = bg::make<geo_point_type>(-104.88, 39.76);\n        // TODO: test_forward<bg::projections::gs48_ellipsoid>(aspen, denver, \"+ellps=WGS84 +units=m +lon1=-48\");=> distance is > 1000\n        test_forward<bg::projections::gs50_ellipsoid>(aspen, denver, \"+ellps=WGS84 +units=m +lon1=-50\", 2);\n    }\n\n}\n\nint test_main(int, char* [])\n{\n    test_all<double>();\n\n    return 0;\n}\n", "meta": {"hexsha": "86e2439513cb3be4457dda7b12137e9a6071a690", "size": 19320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/srs/projections_static.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": "test/srs/projections_static.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": "test/srs/projections_static.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": 66.3917525773, "max_line_length": 184, "alphanum_fraction": 0.7135610766, "num_tokens": 6150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5054762435790408}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_TOOLBOX_ARITHMETIC_FUNCTION_SCALAR_TWO_SPLIT_HPP_INCLUDED\n#define NT2_TOOLBOX_ARITHMETIC_FUNCTION_SCALAR_TWO_SPLIT_HPP_INCLUDED\n#include <nt2/sdk/constant/properties.hpp>\n#include <nt2/sdk/meta/adapted_traits.hpp>\n#include <boost/fusion/tuple.hpp>\n\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type  is fundamental_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::two_split_, tag::cpu_,\n                           (A0),\n                           (fundamental_<A0>)\n                          )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::two_split_(tag::fundamental_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n    struct result<This(A0)>\n    {\n      typedef typename meta::strip<A0>::type           stA0;\n      typedef typename boost::fusion::tuple<stA0,stA0> type;\n    };\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      typename NT2_RETURN_TYPE(1)::type res;\n      eval(a0,boost::fusion::at_c<0>(res),boost::fusion::at_c<1>(res));\n      return res;\n    }\n    private:\n    template<class A0,class R0,class R1> inline void\n    eval(A0 const& a,R0& r0, R1& r1)const\n    {\n      // TODO: make local constant ?\n      static const int N = (Nbmantissabits<A0>()-(Nbmantissabits<A0>()>>1))+1;\n      static const A0 fac = (1<<N)+1;\n      A0 c = fac*a;\n      r0 =  c-(c-a);\n      r1 = a-r0;\n    }\n  };\n} }\n\n#endif\n// modified by jt the 26/12/2010", "meta": {"hexsha": "bf2c5fa0d3d79af34f433ba4949cec3d097a8441", "size": 2070, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/arithmetic/include/nt2/toolbox/arithmetic/function/scalar/two_split.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/arithmetic/include/nt2/toolbox/arithmetic/function/scalar/two_split.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "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": "modules/arithmetic/include/nt2/toolbox/arithmetic/function/scalar/two_split.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "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.5, "max_line_length": 78, "alphanum_fraction": 0.5289855072, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5054762435790408}}
{"text": "//---------------------------------------------------------------------------------------------------------------------\r\n//  Vertical Engineering Solutions\r\n//---------------------------------------------------------------------------------------------------------------------\r\n// \r\n//  Copyright 2020 Vertical Engineering Solutions  - All Rights Reserved\r\n// \r\n//  Unauthorized copying of this file, via any medium is strictly prohibited Proprietary and confidential.\r\n// \r\n//  All information contained herein is, and remains the property of Vertical Engineering Solutions.  The \r\n//  intellectual and technical concepts contained herein are proprietary to Vertical Engineering Solutions \r\n//  and its suppliers and may be covered by UE and Foreign Patents, patents in process, and are protected \r\n//  by trade secret or copyright law. Dissemination of this information or reproduction of this material is \r\n//  strictly forbidden unless prior written permission is obtained from Vertical Engineering Solutions.\r\n//\r\n//---------------------------------------------------------------------------------------------------------------------\r\n//\r\n//  Maintainer: pramon@vengineerings.com\r\n//\r\n//---------------------------------------------------------------------------------------------------------------------\r\n\r\n#include <mico/robotics/PID.h>\r\n#include <algorithm>\r\n#include <thread>\r\n#include <chrono>\r\n#include <iostream>\r\n#include <cmath>\r\n#include <Eigen/Eigen>\r\n\r\n#include <cmath>\r\n\r\nnamespace mico{\r\n\r\n    namespace robotics{\r\n        PID::PID(float _kp, float _ki, float _kd, float _fc, float _minSat, float _maxSat) {\r\n            kp_ = _kp;\r\n            ki_ = _ki;\r\n            kd_ = _kd;\r\n            fc_ = _fc;\r\n            assert(_minSat <= _maxSat);\r\n            minSat_ = _minSat;\r\n            maxSat_ = _maxSat;\r\n            clear();\r\n        }\r\n\r\n        /*void PID::setAntiWindup(AntiWindupMethod _antiWindup, std::vector<float> _params){\r\n            \r\n        }*/\r\n\r\n        void PID::clear(){\r\n            lastError_ = 0; \r\n            lastResult_ = 0; \r\n            accumErr_ = 0; \r\n            accumDeriv_ = 0;\r\n        }\r\n\r\n        void PID::overrideAccumulative(float _accumulative, bool _isOutputScale){\r\n            if(!std::isnan(_accumulative)){\r\n                if(_isOutputScale){\r\n                    if(ki_ != 0.0f){\r\n                        accumErr_ = _accumulative/ki_;\r\n                    }\r\n                }else{\r\n                    accumErr_ = _accumulative;\r\n                }\r\n            }\r\n        }\r\n\r\n        void PID::reference(float _ref, float _time, bool _reset) { \r\n            reference_ = _ref; \r\n            targetReference_ = _ref;\r\n            // if(_time == 0){\r\n            //     reference_ = _ref; \r\n            //     targetReference_ = _ref;\r\n            // }else{\r\n            //     targetReference_ = _ref;\r\n            //     slope_ = (targetReference_ - reference_)/_time;\r\n            // }\r\n\r\n            if(_reset){\r\n                clear();\r\n            }\r\n        }\r\n\r\n\r\n        float PID::update(float _val, float _incT) {\r\n\r\n            float dt = _incT; // 666 input arg?\r\n            float err = reference_ - _val;\r\n            \r\n            float up = kp_ * err;\r\n\r\n            accumErr_ += err * dt;\r\n            float ui = ki_ * accumErr_;\r\n\r\n            float ud = ((kd_ * err) - accumDeriv_) * fc_ ;\r\n            accumDeriv_ += ud * dt;\r\n\r\n            // Compute PID\r\n            float unsaturated =   up + ui + ud;\r\n\r\n            lastError_ = err;\r\n\r\n            // Saturate signal\r\n            float saturated = std::min(std::max(unsaturated, minSat_), maxSat_);\r\n            lastResult_ = saturated;\r\n            \r\n            return lastResult_;\r\n\r\n        }\r\n    }\r\n}\r\n\r\n", "meta": {"hexsha": "725fd94644fc89e99a43bda289538bb718deaf08", "size": 3758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mplugins/robotics_mplugin/src/robotics/PID.cpp", "max_stars_repo_name": "mico-corp/mico", "max_stars_repo_head_hexsha": "45febf13da8c919eea77af9fa3b91afeb324f81b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T19:47:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:13:29.000Z", "max_issues_repo_path": "mplugins/robotics_mplugin/src/robotics/PID.cpp", "max_issues_repo_name": "mico-corp/mico", "max_issues_repo_head_hexsha": "45febf13da8c919eea77af9fa3b91afeb324f81b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-01-29T21:27:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T17:03:02.000Z", "max_forks_repo_path": "mplugins/robotics_mplugin/src/robotics/PID.cpp", "max_forks_repo_name": "mico-corp/mico", "max_forks_repo_head_hexsha": "45febf13da8c919eea77af9fa3b91afeb324f81b", "max_forks_repo_licenses": ["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.2566371681, "max_line_length": 120, "alphanum_fraction": 0.4579563598, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5054762331814567}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <utility>\n#include <vector>\n\n#include \"basis.hpp\"\n#include \"sparse_vector.hpp\"\n\nnamespace Time {\n\ntemplate <typename I, typename BasisIn, typename BasisOut>\nclass LinearOperator {\n public:\n  // This MatVec applies the operator column-wise.\n  SparseVector<BasisOut> MatVec(const SparseVector<BasisIn> &vec) const;\n  SparseVector<BasisIn> RMatVec(const SparseVector<BasisOut> &vec) const;\n\n  // This MatVec applies the operator row-wise for the given output indices.\n  SparseVector<BasisOut> MatVec(\n      const SparseVector<BasisIn> &vec,\n      const SparseIndices<BasisOut> &indices_out) const;\n  SparseVector<BasisIn> RMatVec(const SparseVector<BasisOut> &vec,\n                                const SparseIndices<BasisIn> &indices_in) const;\n\n  // Create functor operators, for convenience.\n  SparseVector<BasisOut> operator()(const SparseVector<BasisIn> &vec) const {\n    return MatVec(vec);\n  }\n  SparseVector<BasisOut> operator()(\n      const SparseVector<BasisIn> &vec,\n      const SparseIndices<BasisOut> &indices_out) const {\n    return MatVec(vec, indices_out);\n  }\n\n  // Return the range of this operator if you were to apply the given indices.\n  SparseIndices<BasisOut> Range(const SparseIndices<BasisIn> &ind) const;\n\n  // Debug function, O(n^2).\n  Eigen::MatrixXd ToMatrix(const SparseIndices<BasisIn> &indices_in,\n                           const SparseIndices<BasisOut> &indices_out) const;\n};\n\n/**\n *  Below are the operations for transformations between single and multi scale.\n */\ntemplate <typename Wavelet>\nclass WaveletToScaling\n    : public LinearOperator<WaveletToScaling<Wavelet>, Wavelet,\n                            typename FunctionTrait<Wavelet>::Scaling> {\n public:\n  static inline const auto &Column(Wavelet *psi_in) {\n    return psi_in->single_scale();\n  }\n\n  // We do not have an implementation of the transpose.\n};\n\n/**\n *  Below are the prolongation/restriction operators for single scale functions.\n */\ntemplate <typename Basis>\nclass Prolongate : public LinearOperator<Prolongate<Basis>, Basis, Basis> {\n public:\n  static inline auto Column(Basis *phi_in);\n  static inline auto Row(Basis *phi_out);\n};\n\n/**\n *   Below are the single scale (levelwise) operators.\n */\ntemplate <typename BasisIn, typename BasisOut>\nclass MassOperator : public LinearOperator<MassOperator<BasisIn, BasisOut>,\n                                           BasisIn, BasisOut> {\n public:\n  static inline auto Column(BasisIn *phi_in);\n  static inline auto Row(BasisOut *phi_out);\n};\n\n// Evaluates the functions in zero: <gamma_0 phi, gamma_0 psi> = phi(0)\n// psi(0).\ntemplate <typename BasisIn, typename BasisOut>\nclass ZeroEvalOperator\n    : public LinearOperator<ZeroEvalOperator<BasisIn, BasisOut>, BasisIn,\n                            BasisOut> {\n public:\n  static inline auto Column(BasisIn *phi_in);\n  static inline auto Row(BasisOut *phi_out);\n};\n\n// Transport matrix <phi, d/dt psi>.\ntemplate <typename BasisIn, typename BasisOut>\nclass TransportOperator\n    : public LinearOperator<TransportOperator<BasisIn, BasisOut>, BasisIn,\n                            BasisOut> {\n public:\n  static inline auto Column(BasisIn *phi_in);\n  static inline auto Row(BasisOut *phi_out);\n};\n\n}  // namespace Time\n\n#include \"linear_operator.ipp\"\n", "meta": {"hexsha": "e8007cbce7a15bba79a744d436448ed391046e2c", "size": 3289, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/time/linear_operator.hpp", "max_stars_repo_name": "rvanvenetie/spacetime", "max_stars_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/time/linear_operator.hpp", "max_issues_repo_name": "rvanvenetie/spacetime", "max_issues_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/time/linear_operator.hpp", "max_forks_repo_name": "rvanvenetie/spacetime", "max_forks_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_forks_repo_licenses": ["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.625, "max_line_length": 80, "alphanum_fraction": 0.7062937063, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5054762331814566}}
{"text": "//  (C) Copyright Jeremy Siek 2004\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// From Louis Lavery <Louis@devilsChimney.co.uk>\n/*Expected Output:-\nA:   0 A\nB:  11 A\n\nActual Output:-\nA:   0 A\nB: 2147483647 B\n*/\n\n#include <iostream>\n#include <iomanip>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n#include <boost/cstdlib.hpp>\n#include <boost/core/lightweight_test.hpp>\n\nint main(int, char*[])\n{\n    using namespace boost;\n\n    enum\n    {\n        A,\n        B,\n        Z\n    };\n    char const name[] = \"ABZ\";\n    int const numVertex = static_cast< int >(Z) + 1;\n    typedef std::pair< int, int > Edge;\n    Edge edge_array[] = { Edge(B, A) };\n    int const numEdges = sizeof(edge_array) / sizeof(Edge);\n    int const weight[numEdges] = { 11 };\n\n    typedef adjacency_list< vecS, vecS, undirectedS, no_property,\n        property< edge_weight_t, int > >\n        Graph;\n\n    Graph g(edge_array, edge_array + numEdges, numVertex);\n\n    Graph::edge_iterator ei, ei_end;\n    property_map< Graph, edge_weight_t >::type weight_pmap\n        = get(edge_weight, g);\n\n    int i = 0;\n    for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei, ++i)\n        weight_pmap[*ei] = weight[i];\n\n    std::vector< int > parent(numVertex);\n    for (i = 0; i < numVertex; ++i)\n        parent[i] = i;\n\n    int inf = (std::numeric_limits< int >::max)();\n    std::vector< int > distance(numVertex, inf);\n    distance[A] = 0; // Set source distance to zero\n\n    bool const r = bellman_ford_shortest_paths(g, int(numVertex), weight_pmap,\n        boost::make_iterator_property_map(\n            parent.begin(), get(boost::vertex_index, g)),\n        boost::make_iterator_property_map(\n            distance.begin(), get(boost::vertex_index, g)),\n        closed_plus< int >(), std::less< int >(), default_bellman_visitor());\n\n    if (r)\n    {\n        for (int i = 0; i < numVertex; ++i)\n        {\n            std::cout << name[i] << \": \";\n            if (distance[i] == inf)\n                std::cout << std::setw(3) << \"inf\";\n            else\n                std::cout << std::setw(3) << distance[i];\n            std::cout << \" \" << name[parent[i]] << std::endl;\n        }\n    }\n    else\n    {\n        std::cout << \"negative cycle\" << std::endl;\n    }\n\n#if !(defined(__INTEL_COMPILER) && __INTEL_COMPILER <= 700) \\\n    && !(defined(BOOST_MSVC) && BOOST_MSVC <= 1300)\n    graph_traits< Graph >::vertex_descriptor s = vertex(A, g);\n    std::vector< int > parent2(numVertex);\n    std::vector< int > distance2(numVertex, 17);\n    bool const r2 = bellman_ford_shortest_paths(g,\n        weight_map(weight_pmap)\n            .distance_map(boost::make_iterator_property_map(\n                distance2.begin(), get(boost::vertex_index, g)))\n            .predecessor_map(boost::make_iterator_property_map(\n                parent2.begin(), get(boost::vertex_index, g)))\n            .root_vertex(s));\n    if (r2)\n    {\n        for (int i = 0; i < numVertex; ++i)\n        {\n            std::cout << name[i] << \": \";\n            if (distance2[i] == inf)\n                std::cout << std::setw(3) << \"inf\";\n            else\n                std::cout << std::setw(3) << distance2[i];\n            std::cout << \" \" << name[parent2[i]] << std::endl;\n        }\n    }\n    else\n    {\n        std::cout << \"negative cycle\" << std::endl;\n    }\n\n    BOOST_TEST(r == r2);\n    if (r && r2)\n    {\n        BOOST_TEST(parent == parent2);\n        BOOST_TEST(distance == distance2);\n    }\n#endif\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "94e5332b266a7f5924b181af661be1669a075fb4", "size": 3637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/test/bellman-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": 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": "3rdparty/boost_1_73_0/libs/graph/test/bellman-test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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/graph/test/bellman-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": 29.096, "max_line_length": 78, "alphanum_fraction": 0.5642012648, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5054762315061827}}
{"text": "#ifndef ACTIVATION_HPP\n#define ACTIVATION_HPP\n\n#include <Eigen/Dense>\n\n#include <opencv2/core.hpp>\n\n/*! \\file activation.hpp\n    \\brief collection of various activation algorithm\n*/\n\n/*!\n *  \\addtogroup ocv\n *  @{\n */\nnamespace ocv{\n\n/*!\n *  \\addtogroup ml\n *  @{\n */\nnamespace ml{\n\nstruct dsigmoid\n{\n    void operator()(cv::Mat &inout) const\n    {\n        cv::multiply(1.0 - inout, inout, inout);\n    }\n\n    void operator()(cv::Mat const &input,\n                    cv::Mat &output) const\n    {\n        cv::multiply(1.0 - input, input, output);\n    }\n};\n\nstruct sigmoid\n{\n    void operator()(cv::Mat &inout) const\n    {\n        operator()(inout, inout);\n    }\n\n    void operator()(cv::Mat const &input,\n                    cv::Mat &output) const;\n\n    template<typename Derived>\n    void operator()(Eigen::MatrixBase<Derived> &inout) const\n    {\n        inout = 1.0 / (1.0 + (-1.0 * inout.array()).exp());\n    }\n};\n\n} /*! @} End of Doxygen Groups*/\n\n} /*! @} End of Doxygen Groups*/\n\n\n#endif // ACTIVATION_HPP\n\n", "meta": {"hexsha": "7ff3d3e71754953375c86077730b1be0de44b259", "size": 1012, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ml/utility/activation.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/utility/activation.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/utility/activation.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": 16.3225806452, "max_line_length": 60, "alphanum_fraction": 0.5652173913, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5054762315061826}}
{"text": "#ifndef PYTHONIC_INCLUDE_NUMPY_LOGADDEXP_HPP\n#define PYTHONIC_INCLUDE_NUMPY_LOGADDEXP_HPP\n\n#include \"pythonic/include/utils/functor.hpp\"\n#include \"pythonic/include/types/ndarray.hpp\"\n#include \"pythonic/include/utils/numpy_traits.hpp\"\n\n#include <boost/simd/function/log.hpp>\n#include <boost/simd/function/exp.hpp>\n\nPYTHONIC_NS_BEGIN\n\nnamespace numpy\n{\n  namespace wrapper\n  {\n    template <class T0, class T1>\n    auto logaddexp(T0 const &t0, T1 const &t1)\n        -> decltype(boost::simd::log(boost::simd::exp(t0) +\n                                     boost::simd::exp(t1)));\n  }\n\n#define NUMPY_NARY_FUNC_NAME logaddexp\n#define NUMPY_NARY_FUNC_SYM wrapper::logaddexp\n#include \"pythonic/include/types/numpy_nary_expr.hpp\"\n}\nPYTHONIC_NS_END\n\n#endif\n", "meta": {"hexsha": "3b7e6744818124f9ee2ebac678697d3497172fbe", "size": 748, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pythran/pythonic/include/numpy/logaddexp.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-24T00:33:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-24T00:33:03.000Z", "max_issues_repo_path": "pythran/pythonic/include/numpy/logaddexp.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": "pythran/pythonic/include/numpy/logaddexp.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "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.9333333333, "max_line_length": 60, "alphanum_fraction": 0.7339572193, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5054366827839307}}
{"text": "/*\n * Copyright (C) 2018 Swift Navigation Inc.\n * Contact: Swift Navigation <dev@swiftnav.com>\n *\n * This source is subject to the license found in the file 'LICENSE' which must\n * be distributed together with this source. All other rights reserved.\n *\n * THIS CODE AND INFORMATION IS PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY KIND,\n * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.\n */\n\n#include \"evaluate.h\"\n#include \"models/least_squares.h\"\n#include <Eigen/Dense>\n#include <cmath>\n#include <gtest/gtest.h>\n#include <iostream>\n\n#include \"test_utils.h\"\n\nnamespace albatross {\n\nusing albatross::evaluation_metrics::root_mean_square_error;\n\n/* Make sure the multivariate negative log likelihood\n * matches python.\n *\n * import numpy as np\n * from scipy import stats\n *\n * x = np.array([-1, 0., 1])\n * cov = np.array([[1., 0.9, 0.8],\n *                 [0.9, 1., 0.9],\n *                 [0.8, 0.9, 1.]])\n * stats.multivariate_normal.logpdf(x, np.zeros(x.size), cov)\n * -6.0946974293510134\n *\n */\nTEST(test_evaluate, test_negative_log_likelihood) {\n  Eigen::VectorXd x(3);\n  x << -1., 0., 1.;\n  Eigen::MatrixXd cov(3, 3);\n  cov << 1., 0.9, 0.8, 0.9, 1., 0.9, 0.8, 0.9, 1.;\n\n  const auto nll = albatross::negative_log_likelihood(x, cov);\n  EXPECT_NEAR(nll, -6.0946974293510134, 1e-6);\n\n  const auto ldlt_nll = albatross::negative_log_likelihood(x, cov.ldlt());\n  EXPECT_NEAR(nll, ldlt_nll, 1e-6);\n}\n\nTEST_F(LinearRegressionTest, test_leave_one_out) {\n  PredictDistribution preds = model_ptr_->fit_and_predict(\n      dataset_.features, dataset_.targets, dataset_.features);\n  double in_sample_rmse = root_mean_square_error(preds, dataset_.targets);\n  const auto folds = leave_one_out(dataset_);\n\n  Eigen::VectorXd rmses =\n      cross_validated_scores(root_mean_square_error, folds, model_ptr_.get());\n  double out_of_sample_rmse = rmses.mean();\n\n  // Make sure the RMSE computed doing leave one out cross validation is larger\n  // than the in sample version.  This should always be true as the in sample\n  // version has already seen the values we're trying to predict.\n  EXPECT_LT(in_sample_rmse, out_of_sample_rmse);\n}\n\n// Group values by interval, but return keys that once sorted won't be\n// in order\nstd::string group_by_interval(const double &x) {\n  if (x <= 3) {\n    return \"2\";\n  } else if (x <= 6) {\n    return \"3\";\n  } else {\n    return \"1\";\n  }\n}\n\nbool is_monotonic_increasing(Eigen::VectorXd &x) {\n  for (s32 i = 0; i < static_cast<s32>(x.size()) - 1; i++) {\n    if (x[i + 1] - x[i] <= 0.) {\n      return false;\n    }\n  }\n  return true;\n}\n\nTEST_F(LinearRegressionTest, test_cross_validated_predict) {\n  const auto folds = leave_one_group_out<double>(dataset_, group_by_interval);\n\n  PredictDistribution preds = cross_validated_predict(folds, model_ptr_.get());\n\n  // Make sure the group cross validation resulted in folds that\n  // are out of order\n  EXPECT_TRUE(folds[0].name == \"1\");\n  // And that cross_validate_predict put them back in order.\n  EXPECT_TRUE(is_monotonic_increasing(preds.mean));\n}\n\nTEST_F(LinearRegressionTest, test_leave_one_group_out) {\n  const auto folds = leave_one_group_out<double>(dataset_, group_by_interval);\n  Eigen::VectorXd rmses =\n      cross_validated_scores(root_mean_square_error, folds, model_ptr_.get());\n\n  // Make sure we get a single RMSE for each of the three groups.\n  EXPECT_EQ(rmses.size(), 3);\n}\n} // namespace albatross\n", "meta": {"hexsha": "9216b8215d13dde6333ff0bec25157fea7b33752", "size": 3471, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/test_evaluate.cc", "max_stars_repo_name": "akleeman/albatross", "max_stars_repo_head_hexsha": "f89bf4c20e35b71ea4d89260dc981b1a2363d41b", "max_stars_repo_licenses": ["MIT"], "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_evaluate.cc", "max_issues_repo_name": "akleeman/albatross", "max_issues_repo_head_hexsha": "f89bf4c20e35b71ea4d89260dc981b1a2363d41b", "max_issues_repo_licenses": ["MIT"], "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_evaluate.cc", "max_forks_repo_name": "akleeman/albatross", "max_forks_repo_head_hexsha": "f89bf4c20e35b71ea4d89260dc981b1a2363d41b", "max_forks_repo_licenses": ["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.2702702703, "max_line_length": 79, "alphanum_fraction": 0.7044079516, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.5053673857446747}}
{"text": "\n#include <boost/functional/hash.hpp>\n#include <Eigen/Dense>\n#include <StateSpace.hpp>\n#include <Tree.hpp>\n\nnamespace RRT {\n\nconst int dimensions = 2;\n\n/**\n * Hash function for Eigen::Vector2d\n */\nstatic size_t hash(Eigen::Vector2d state) {\n    size_t seed = 0;\n    boost::hash_combine(seed, state.x());\n    boost::hash_combine(seed, state.y());\n    return seed;\n}\n    \nstatic size_t hash2d(Eigen::Vector2d state) {\n    size_t seed = 0;\n    boost::hash_combine(seed, state.x());\n    boost::hash_combine(seed, state.y());\n    return seed;\n}\n\n/**\n * Hash function for Eigen::Vectordd\n */\nstatic size_t hash3d(Eigen::Vector3d state) {\n    size_t seed = 0;\n    boost::hash_combine(seed, state.x());\n    boost::hash_combine(seed, state.y());\n    boost::hash_combine(seed, state.z());\n    return seed;\n}\n\n/**\n * This creates an instance of an RRT Tree with the callbacks\n * configured from the given parameters.\n *\n * @param w, h The dimensions of the 2d plane.  These are used when\n * picking random points for the Tree to move towards.\n\n * @param goal The point representing the goal that the tree is\n * trying to find a path to\n *\n * @param step The fixed step size that the tree uses.  This is the\n * maximum distance between nodes unless adaptive stepsize control is utilized.\n *\n * @return An RRT::Tree with its callbacks and parameters configured.\n * You'll probably want to override the transitionValidator callback\n * if your 2d plane has any obstacles.\n */\nstd::shared_ptr<RRT::Tree<Eigen::Vector2d>> TreeFor2dPlane(\n    std::shared_ptr<StateSpace> stateSpace,\n    Eigen::Vector2d goal, double step);\n\n}  // namespace RRT\n", "meta": {"hexsha": "c1120600a1f3103c7788a83770b24b5f716caf01", "size": 1626, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "robojackets_trajectory_planning_node/src/2dplane/2dplane.hpp", "max_stars_repo_name": "JonathanSchmalhofer/RecursiveStereoUAV", "max_stars_repo_head_hexsha": "005642f5afbfe719c632ce81411af9ac5e8522f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2018-04-07T18:07:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T11:48:34.000Z", "max_issues_repo_path": "robojackets_trajectory_planning_node/src/2dplane/2dplane.hpp", "max_issues_repo_name": "JonathanSchmalhofer/RecursiveStereoUAV", "max_issues_repo_head_hexsha": "005642f5afbfe719c632ce81411af9ac5e8522f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-21T12:55:07.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-21T14:33:09.000Z", "max_forks_repo_path": "robojackets_trajectory_planning_node/src/2dplane/2dplane.hpp", "max_forks_repo_name": "JonathanSchmalhofer/RecursiveStereoUAV", "max_forks_repo_head_hexsha": "005642f5afbfe719c632ce81411af9ac5e8522f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-10-11T09:10:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T06:28:24.000Z", "avg_line_length": 26.6557377049, "max_line_length": 79, "alphanum_fraction": 0.6986469865, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5053673735284548}}
{"text": "// boost\\math\\distributions\\beta.hpp\r\n\r\n// Copyright John Maddock 2006.\r\n// Copyright Paul A. Bristow 2006.\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// http://en.wikipedia.org/wiki/Beta_distribution\r\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda366h.htm\r\n// http://mathworld.wolfram.com/BetaDistribution.html\r\n\r\n// The Beta Distribution is a continuous probability distribution.\r\n// The beta distribution is used to model events which are constrained to take place\r\n// within an interval defined by maxima and minima,\r\n// so is used extensively in PERT and other project management systems\r\n// to describe the time to completion.\r\n// The cdf of the beta distribution is used as a convenient way\r\n// of obtaining the sum over a set of binomial outcomes.\r\n// The beta distribution is also used in Bayesian statistics.\r\n\r\n#ifndef BOOST_MATH_DIST_BETA_HPP\r\n#define BOOST_MATH_DIST_BETA_HPP\r\n\r\n#include <boost/math/distributions/fwd.hpp>\r\n#include <boost/math/special_functions/beta.hpp> // for beta.\r\n#include <boost/math/distributions/complement.hpp> // complements.\r\n#include <boost/math/distributions/detail/common_error_handling.hpp> // error checks\r\n#include <boost/math/special_functions/fpclassify.hpp> // isnan.\r\n#include <boost/math/tools/roots.hpp> // for root finding.\r\n\r\n#if defined (BOOST_MSVC)\r\n#  pragma warning(push)\r\n#  pragma warning(disable: 4702) // unreachable code\r\n// in domain_error_imp in error_handling\r\n#endif\r\n\r\n#include <utility>\r\n\r\nnamespace boost\r\n{\r\n  namespace math\r\n  {\r\n    namespace beta_detail\r\n    {\r\n      // Common error checking routines for beta distribution functions:\r\n      template <class RealType, class Policy>\r\n      inline bool check_alpha(const char* function, const RealType& alpha, RealType* result, const Policy& pol)\r\n      {\r\n        if(!(boost::math::isfinite)(alpha) || (alpha <= 0))\r\n        {\r\n          *result = policies::raise_domain_error<RealType>(\r\n            function,\r\n            \"Alpha argument is %1%, but must be > 0 !\", alpha, pol);\r\n          return false;\r\n        }\r\n        return true;\r\n      } // bool check_alpha\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_beta(const char* function, const RealType& beta, RealType* result, const Policy& pol)\r\n      {\r\n        if(!(boost::math::isfinite)(beta) || (beta <= 0))\r\n        {\r\n          *result = policies::raise_domain_error<RealType>(\r\n            function,\r\n            \"Beta argument is %1%, but must be > 0 !\", beta, pol);\r\n          return false;\r\n        }\r\n        return true;\r\n      } // bool check_beta\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_prob(const char* function, const RealType& p, RealType* result, const Policy& pol)\r\n      {\r\n        if((p < 0) || (p > 1) || !(boost::math::isfinite)(p))\r\n        {\r\n          *result = policies::raise_domain_error<RealType>(\r\n            function,\r\n            \"Probability argument is %1%, but must be >= 0 and <= 1 !\", p, pol);\r\n          return false;\r\n        }\r\n        return true;\r\n      } // bool check_prob\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_x(const char* function, const RealType& x, RealType* result, const Policy& pol)\r\n      {\r\n        if(!(boost::math::isfinite)(x) || (x < 0) || (x > 1))\r\n        {\r\n          *result = policies::raise_domain_error<RealType>(\r\n            function,\r\n            \"x argument is %1%, but must be >= 0 and <= 1 !\", x, pol);\r\n          return false;\r\n        }\r\n        return true;\r\n      } // bool check_x\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_dist(const char* function, const RealType& alpha, const RealType& beta, RealType* result, const Policy& pol)\r\n      { // Check both alpha and beta.\r\n        return check_alpha(function, alpha, result, pol)\r\n          && check_beta(function, beta, result, pol);\r\n      } // bool check_dist\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_dist_and_x(const char* function, const RealType& alpha, const RealType& beta, RealType x, RealType* result, const Policy& pol)\r\n      {\r\n        return check_dist(function, alpha, beta, result, pol)\r\n          && beta_detail::check_x(function, x, result, pol);\r\n      } // bool check_dist_and_x\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_dist_and_prob(const char* function, const RealType& alpha, const RealType& beta, RealType p, RealType* result, const Policy& pol)\r\n      {\r\n        return check_dist(function, alpha, beta, result, pol)\r\n          && check_prob(function, p, result, pol);\r\n      } // bool check_dist_and_prob\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_mean(const char* function, const RealType& mean, RealType* result, const Policy& pol)\r\n      {\r\n        if(!(boost::math::isfinite)(mean) || (mean <= 0))\r\n        {\r\n          *result = policies::raise_domain_error<RealType>(\r\n            function,\r\n            \"mean argument is %1%, but must be > 0 !\", mean, pol);\r\n          return false;\r\n        }\r\n        return true;\r\n      } // bool check_mean\r\n      template <class RealType, class Policy>\r\n      inline bool check_variance(const char* function, const RealType& variance, RealType* result, const Policy& pol)\r\n      {\r\n        if(!(boost::math::isfinite)(variance) || (variance <= 0))\r\n        {\r\n          *result = policies::raise_domain_error<RealType>(\r\n            function,\r\n            \"variance argument is %1%, but must be > 0 !\", variance, pol);\r\n          return false;\r\n        }\r\n        return true;\r\n      } // bool check_variance\r\n    } // namespace beta_detail\r\n\r\n    // typedef beta_distribution<double> beta;\r\n    // is deliberately NOT included to avoid a name clash with the beta function.\r\n    // Use beta_distribution<> mybeta(...) to construct type double.\r\n\r\n    template <class RealType = double, class Policy = policies::policy<> >\r\n    class beta_distribution\r\n    {\r\n    public:\r\n      typedef RealType value_type;\r\n      typedef Policy policy_type;\r\n\r\n      beta_distribution(RealType alpha = 1, RealType beta = 1) : m_alpha(alpha), m_beta(beta)\r\n      {\r\n        RealType result;\r\n        beta_detail::check_dist(\r\n           \"boost::math::beta_distribution<%1%>::beta_distribution\",\r\n          m_alpha,\r\n          m_beta,\r\n          &result, Policy());\r\n      } // beta_distribution constructor.\r\n      // Accessor functions:\r\n      RealType alpha() const\r\n      {\r\n        return m_alpha;\r\n      }\r\n      RealType beta() const\r\n      { // .\r\n        return m_beta;\r\n      }\r\n\r\n      // Estimation of the alpha & beta parameters.\r\n      // http://en.wikipedia.org/wiki/Beta_distribution\r\n      // gives formulae in section on parameter estimation.\r\n      // Also NIST EDA page 3 & 4 give the same.\r\n      // http://www.itl.nist.gov/div898/handbook/eda/section3/eda366h.htm\r\n      // http://www.epi.ucdavis.edu/diagnostictests/betabuster.html\r\n\r\n      static RealType find_alpha(\r\n        RealType mean, // Expected value of mean.\r\n        RealType variance) // Expected value of variance.\r\n      {\r\n        static const char* function = \"boost::math::beta_distribution<%1%>::find_alpha\";\r\n        RealType result = 0; // of error checks.\r\n        if(false ==\r\n            (\r\n              beta_detail::check_mean(function, mean, &result, Policy())\r\n              && beta_detail::check_variance(function, variance, &result, Policy())\r\n            )\r\n          )\r\n        {\r\n          return result;\r\n        }\r\n        return mean * (( (mean * (1 - mean)) / variance)- 1);\r\n      } // RealType find_alpha\r\n\r\n      static RealType find_beta(\r\n        RealType mean, // Expected value of mean.\r\n        RealType variance) // Expected value of variance.\r\n      {\r\n        static const char* function = \"boost::math::beta_distribution<%1%>::find_beta\";\r\n        RealType result = 0; // of error checks.\r\n        if(false ==\r\n            (\r\n              beta_detail::check_mean(function, mean, &result, Policy())\r\n              &&\r\n              beta_detail::check_variance(function, variance, &result, Policy())\r\n            )\r\n          )\r\n        {\r\n          return result;\r\n        }\r\n        return (1 - mean) * (((mean * (1 - mean)) /variance)-1);\r\n      } //  RealType find_beta\r\n\r\n      // Estimate alpha & beta from either alpha or beta, and x and probability.\r\n      // Uses for these parameter estimators are unclear.\r\n\r\n      static RealType find_alpha(\r\n        RealType beta, // from beta.\r\n        RealType x, //  x.\r\n        RealType probability) // cdf\r\n      {\r\n        static const char* function = \"boost::math::beta_distribution<%1%>::find_alpha\";\r\n        RealType result = 0; // of error checks.\r\n        if(false ==\r\n            (\r\n             beta_detail::check_prob(function, probability, &result, Policy())\r\n             &&\r\n             beta_detail::check_beta(function, beta, &result, Policy())\r\n             &&\r\n             beta_detail::check_x(function, x, &result, Policy())\r\n            )\r\n          )\r\n        {\r\n          return result;\r\n        }\r\n        return ibeta_inva(beta, x, probability, Policy());\r\n      } // RealType find_alpha(beta, a, probability)\r\n\r\n      static RealType find_beta(\r\n        // ibeta_invb(T b, T x, T p); (alpha, x, cdf,)\r\n        RealType alpha, // alpha.\r\n        RealType x, // probability x.\r\n        RealType probability) // probability cdf.\r\n      {\r\n        static const char* function = \"boost::math::beta_distribution<%1%>::find_beta\";\r\n        RealType result = 0; // of error checks.\r\n        if(false ==\r\n            (\r\n              beta_detail::check_prob(function, probability, &result, Policy())\r\n              &&\r\n              beta_detail::check_alpha(function, alpha, &result, Policy())\r\n              &&\r\n              beta_detail::check_x(function, x, &result, Policy())\r\n            )\r\n          )\r\n        {\r\n          return result;\r\n        }\r\n        return ibeta_invb(alpha, x, probability, Policy());\r\n      } //  RealType find_beta(alpha, x, probability)\r\n\r\n    private:\r\n      RealType m_alpha; // Two parameters of the beta distribution.\r\n      RealType m_beta;\r\n    }; // template <class RealType, class Policy> class beta_distribution\r\n\r\n    template <class RealType, class Policy>\r\n    inline const std::pair<RealType, RealType> range(const beta_distribution<RealType, Policy>& /* dist */)\r\n    { // Range of permissible values for random variable x.\r\n      using boost::math::tools::max_value;\r\n      return std::pair<RealType, RealType>(static_cast<RealType>(0), static_cast<RealType>(1));\r\n    }\r\n\r\n    template <class RealType, class Policy>\r\n    inline const std::pair<RealType, RealType> support(const beta_distribution<RealType, Policy>&  /* dist */)\r\n    { // Range of supported values for random variable x.\r\n      // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\r\n      return std::pair<RealType, RealType>(static_cast<RealType>(0), static_cast<RealType>(1));\r\n    }\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType mean(const beta_distribution<RealType, Policy>& dist)\r\n    { // Mean of beta distribution = np.\r\n      return  dist.alpha() / (dist.alpha() + dist.beta());\r\n    } // mean\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType variance(const beta_distribution<RealType, Policy>& dist)\r\n    { // Variance of beta distribution = np(1-p).\r\n      RealType a = dist.alpha();\r\n      RealType b = dist.beta();\r\n      return  (a * b) / ((a + b ) * (a + b) * (a + b + 1));\r\n    } // variance\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType mode(const beta_distribution<RealType, Policy>& dist)\r\n    {\r\n      static const char* function = \"boost::math::mode(beta_distribution<%1%> const&)\";\r\n\r\n      RealType result;\r\n      if ((dist.alpha() <= 1))\r\n      {\r\n        result = policies::raise_domain_error<RealType>(\r\n          function,\r\n          \"mode undefined for alpha = %1%, must be > 1!\", dist.alpha(), Policy());\r\n        return result;\r\n      }\r\n\r\n      if ((dist.beta() <= 1))\r\n      {\r\n        result = policies::raise_domain_error<RealType>(\r\n          function,\r\n          \"mode undefined for beta = %1%, must be > 1!\", dist.beta(), Policy());\r\n        return result;\r\n      }\r\n      RealType a = dist.alpha();\r\n      RealType b = dist.beta();\r\n      return (a-1) / (a + b - 2);\r\n    } // mode\r\n\r\n    //template <class RealType, class Policy>\r\n    //inline RealType median(const beta_distribution<RealType, Policy>& dist)\r\n    //{ // Median of beta distribution is not defined.\r\n    //  return tools::domain_error<RealType>(function, \"Median is not implemented, result is %1%!\", std::numeric_limits<RealType>::quiet_NaN());\r\n    //} // median\r\n\r\n    //But WILL be provided by the derived accessor as quantile(0.5).\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType skewness(const beta_distribution<RealType, Policy>& dist)\r\n    {\r\n      BOOST_MATH_STD_USING // ADL of std functions.\r\n      RealType a = dist.alpha();\r\n      RealType b = dist.beta();\r\n      return (2 * (b-a) * sqrt(a + b + 1)) / ((a + b + 2) * sqrt(a * b));\r\n    } // skewness\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType kurtosis_excess(const beta_distribution<RealType, Policy>& dist)\r\n    {\r\n      RealType a = dist.alpha();\r\n      RealType b = dist.beta();\r\n      RealType a_2 = a * a;\r\n      RealType n = 6 * (a_2 * a - a_2 * (2 * b - 1) + b * b * (b + 1) - 2 * a * b * (b + 2));\r\n      RealType d = a * b * (a + b + 2) * (a + b + 3);\r\n      return  n / d;\r\n    } // kurtosis_excess\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType kurtosis(const beta_distribution<RealType, Policy>& dist)\r\n    {\r\n      return 3 + kurtosis_excess(dist);\r\n    } // kurtosis\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType pdf(const beta_distribution<RealType, Policy>& dist, const RealType& x)\r\n    { // Probability Density/Mass Function.\r\n      BOOST_FPU_EXCEPTION_GUARD\r\n\r\n      static const char* function = \"boost::math::pdf(beta_distribution<%1%> const&, %1%)\";\r\n\r\n      BOOST_MATH_STD_USING // for ADL of std functions\r\n\r\n      RealType a = dist.alpha();\r\n      RealType b = dist.beta();\r\n\r\n      // Argument checks:\r\n      RealType result = 0;\r\n      if(false == beta_detail::check_dist_and_x(\r\n        function,\r\n        a, b, x,\r\n        &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n      using boost::math::beta;\r\n      return ibeta_derivative(a, b, x, Policy());\r\n    } // pdf\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType cdf(const beta_distribution<RealType, Policy>& dist, const RealType& x)\r\n    { // Cumulative Distribution Function beta.\r\n      BOOST_MATH_STD_USING // for ADL of std functions\r\n\r\n      static const char* function = \"boost::math::cdf(beta_distribution<%1%> const&, %1%)\";\r\n\r\n      RealType a = dist.alpha();\r\n      RealType b = dist.beta();\r\n\r\n      // Argument checks:\r\n      RealType result = 0;\r\n      if(false == beta_detail::check_dist_and_x(\r\n        function,\r\n        a, b, x,\r\n        &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n      // Special cases:\r\n      if (x == 0)\r\n      {\r\n        return 0;\r\n      }\r\n      else if (x == 1)\r\n      {\r\n        return 1;\r\n      }\r\n      return ibeta(a, b, x, Policy());\r\n    } // beta cdf\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType cdf(const complemented2_type<beta_distribution<RealType, Policy>, RealType>& c)\r\n    { // Complemented Cumulative Distribution Function beta.\r\n\r\n      BOOST_MATH_STD_USING // for ADL of std functions\r\n\r\n      static const char* function = \"boost::math::cdf(beta_distribution<%1%> const&, %1%)\";\r\n\r\n      RealType const& x = c.param;\r\n      beta_distribution<RealType, Policy> const& dist = c.dist;\r\n      RealType a = dist.alpha();\r\n      RealType b = dist.beta();\r\n\r\n      // Argument checks:\r\n      RealType result = 0;\r\n      if(false == beta_detail::check_dist_and_x(\r\n        function,\r\n        a, b, x,\r\n        &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n      if (x == 0)\r\n      {\r\n        return 1;\r\n      }\r\n      else if (x == 1)\r\n      {\r\n        return 0;\r\n      }\r\n      // Calculate cdf beta using the incomplete beta function.\r\n      // Use of ibeta here prevents cancellation errors in calculating\r\n      // 1 - x if x is very small, perhaps smaller than machine epsilon.\r\n      return ibetac(a, b, x, Policy());\r\n    } // beta cdf\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType quantile(const beta_distribution<RealType, Policy>& dist, const RealType& p)\r\n    { // Quantile or Percent Point beta function or\r\n      // Inverse Cumulative probability distribution function CDF.\r\n      // Return x (0 <= x <= 1),\r\n      // for a given probability p (0 <= p <= 1).\r\n      // These functions take a probability as an argument\r\n      // and return a value such that the probability that a random variable x\r\n      // will be less than or equal to that value\r\n      // is whatever probability you supplied as an argument.\r\n\r\n      static const char* function = \"boost::math::quantile(beta_distribution<%1%> const&, %1%)\";\r\n\r\n      RealType result = 0; // of argument checks:\r\n      RealType a = dist.alpha();\r\n      RealType b = dist.beta();\r\n      if(false == beta_detail::check_dist_and_prob(\r\n        function,\r\n        a, b, p,\r\n        &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n      // Special cases:\r\n      if (p == 0)\r\n      {\r\n        return 0;\r\n      }\r\n      if (p == 1)\r\n      {\r\n        return 1;\r\n      }\r\n      return ibeta_inv(a, b, p, static_cast<RealType*>(0), Policy());\r\n    } // quantile\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType quantile(const complemented2_type<beta_distribution<RealType, Policy>, RealType>& c)\r\n    { // Complement Quantile or Percent Point beta function .\r\n      // Return the number of expected x for a given\r\n      // complement of the probability q.\r\n\r\n      static const char* function = \"boost::math::quantile(beta_distribution<%1%> const&, %1%)\";\r\n\r\n      //\r\n      // Error checks:\r\n      RealType q = c.param;\r\n      const beta_distribution<RealType, Policy>& dist = c.dist;\r\n      RealType result = 0;\r\n      RealType a = dist.alpha();\r\n      RealType b = dist.beta();\r\n      if(false == beta_detail::check_dist_and_prob(\r\n        function,\r\n        a,\r\n        b,\r\n        q,\r\n        &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n      // Special cases:\r\n      if(q == 1)\r\n      {\r\n        return 0;\r\n      }\r\n      if(q == 0)\r\n      {\r\n        return 1;\r\n      }\r\n\r\n      return ibetac_inv(a, b, q, static_cast<RealType*>(0), Policy());\r\n    } // Quantile Complement\r\n\r\n  } // namespace math\r\n} // namespace boost\r\n\r\n// This include must be at the end, *after* the accessors\r\n// for this distribution have been defined, in order to\r\n// keep compilers that support two-phase lookup happy.\r\n#include <boost/math/distributions/detail/derived_accessors.hpp>\r\n\r\n#if defined (BOOST_MSVC)\r\n# pragma warning(pop)\r\n#endif\r\n\r\n#endif // BOOST_MATH_DIST_BETA_HPP\r\n\r\n\r\n", "meta": {"hexsha": "337fc0287642937b7723971aac14a2bd637373d0", "size": 19340, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/math/distributions/beta.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/math/distributions/beta.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/math/distributions/beta.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": 35.6826568266, "max_line_length": 154, "alphanum_fraction": 0.5886763185, "num_tokens": 4585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5053673704692129}}
{"text": "#include \"potgen.hpp\"\n#include \"vector.hpp\"\n#include \"interpolation.hpp\"\n#include \"fileIO.hpp\"\n#include \"correlation.hpp\"\n#include \"config.h\"\n\n#include <fstream>\n\n#define BOOST_TEST_MODULE potgen_test\n#include <boost/test/unit_test.hpp>\n\n// declaration of compare function\n/// \\todo define some kind of test utility header\nbool compare_files_binary(std::string f1, std::string f2, bool verbose);\n\n// helper function\nstatic Potential generatePotential( int N,  std::size_t size, const PGOptions& opt )\n{\n\tstd::vector<std::size_t> sizes(N, size);\n\treturn generatePotential( sizes, std::vector<double>(N, 1.0), opt);\n}\n\nBOOST_AUTO_TEST_SUITE(potgen_test)\n\nBOOST_AUTO_TEST_CASE( potential_properties )\n{\n\tPGOptions opt;\n\topt.randomSeed = rand();\n\topt.maxDerivativeOrder = 2;\n\topt.corrlength = 0.1;\n\topt.cor_fun = makeGaussianCorrelation(0.01);\n\tauto result = generatePotential(2, 128, opt);\n\tBOOST_CHECK_EQUAL( opt.randomSeed, result.getSeed() );\n\tBOOST_CHECK_EQUAL( result.getExtents()[0], 128);\n\tBOOST_CHECK_EQUAL( result.getExtents()[1], 128);\n\tBOOST_CHECK_EQUAL( result.getSupport()[0], 1.0);\n\tBOOST_CHECK_EQUAL( result.getSupport()[1], 1.0);\n\tBOOST_CHECK_EQUAL( result.getCorrelationLength(), opt.corrlength);\n\tBOOST_CHECK( result.hasDerivativesOfOrder( opt.maxDerivativeOrder ) );\n\n}\n\n// check determinism\nBOOST_AUTO_TEST_CASE( check_potgen_determinism )\n{\n\tauto f = makeGaussianCorrelation(0.01);\n\tPGOptions opt;\n\topt.randomSeed = rand();\n\topt.cor_fun = f;\n\tauto result1 = generatePotential(2, 128, opt);\n\tauto result2 = generatePotential(2, 128, opt);\n\n\tBOOST_CHECK_EQUAL( opt.randomSeed, result1.getSeed() );\n\n\tfor(unsigned int i = 0; i < result1.getPotential().getElementCount(); ++i)\n\t{\n\t\tBOOST_CHECK_EQUAL( result1.getPotential()[i], result2.getPotential()[i] );\n\t}\n\n\t// check consistency across multiple revision\n\tstd::cout << TEST_DATA_DIRECTORY\"/pot_2d_128_ref\" << \"\\n\";\n\tstd::fstream rfile(TEST_DATA_DIRECTORY\"/pot_2d_128_ref\", std::fstream::in | std::fstream::binary);\n\tif(!rfile.is_open()) {\n\t\tBOOST_FAIL(\"Could not open reference file \" TEST_DATA_DIRECTORY \"/pot_2d_128_ref\");\n\n\t}\n\n\tauto ref = Potential::readFromFile(rfile);\n\topt.randomSeed = ref.getSeed();\n\topt.cor_fun = f;\n\topt.corrlength = 0.01;\n\tauto result3 = generatePotential(2, 128, opt);\n\n\tstd::fstream generated(\"pot_2d_128_cmp\", std::fstream::out | std::fstream::binary);\n\tresult3.writeToFile(generated);\n\n\tBOOST_CHECK(compare_files_binary(TEST_DATA_DIRECTORY\"/pot_2d_128_ref\", \"pot_2d_128_cmp\", true));\n\n\tfor(int x = 0; x < 128*128; ++x)\n\t{\n\t\tBOOST_REQUIRE_EQUAL(ref.getPotential()[x], result3.getPotential()[x]);\n\n\t}\n\n\t/// \\todo error check for too high sizes\n\t/// \\todo this belong into another test case\n\topt.cor_fun = makeGaussianCorrelation(1);\n\tBOOST_CHECK_THROW( generatePotential(3, std::size_t(-1), opt), boost::exception );\n}\n\nBOOST_AUTO_TEST_CASE( check_potgen_derivatives )\n{\n\t/// \\todo for this check to make sense, we should actually generate a larger potential and scale down by hand, then make comparisons\n\tconstexpr int size = 5120;\n\n\tauto f = makeGaussianCorrelation(0.01);\n\t/// \\todo allow the direct use of lambdas\n\tPGOptions opt;\n\topt.randomSeed = rand();\n\topt.maxDerivativeOrder = 2;\n\topt.cor_fun = f;\n\tauto result1 = generatePotential(1, size, opt);\n\tresult1.setSupport(std::vector<double>{1.0});\n\n\tauto pgrid = result1.getPotential().shallow_copy();\n\tpgrid.setAccessMode(TransformationType::PERIODIC);\n\tauto dgrid = result1.getDerivative( makeIndexVector(1, {0}) ).shallow_copy();\n\tdgrid.setAccessMode(TransformationType::PERIODIC);\n\n\tconstexpr double STEP = 0.01;\n\n\tdouble p_int = pgrid(std::vector<int>{2});\n\n\t/// \\todo use an integrator and check that results are consistent\n\tint c = 0;\n\n\tdouble max_dev = 0;\n\tdouble avg_dev = 0;\n\n\tfor(double x = 2; x < size - 2; x += STEP)\n\t{\n\t\tgen_vect pos(1);\n\t\tpos[0] = x;\n\t\tdouble p_here = linearInterpolate( pgrid, pos );\n\n\t\tdouble dx_here = linearInterpolate( dgrid, pos );\n\t\tp_int += dx_here * STEP / size;\n\n\t\tdouble dev = std::abs( p_int - p_here );\n\t\tif ( dev > max_dev )\n\t\t\tmax_dev = dev;\n\t\tavg_dev += dev;\n\n\t\tc++;\n\t}\n\n\tavg_dev /= c;\n\t/// \\todo 1e-3 and 2e-4 seem quite high here\n\tBOOST_CHECK_SMALL( max_dev, 1e-3 );\n\tBOOST_CHECK_SMALL( avg_dev, 2e-4 );\n\n\tstd::cout << \"average deviation: \" << avg_dev << \"\\n\";\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "1ffd01c122e13bd3b7e9a0b6f590fce4eb7af434", "size": 4293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/potgen/test/potgen_test.cpp", "max_stars_repo_name": "ngc92/branchedflowsim", "max_stars_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/potgen/test/potgen_test.cpp", "max_issues_repo_name": "ngc92/branchedflowsim", "max_issues_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/potgen/test/potgen_test.cpp", "max_forks_repo_name": "ngc92/branchedflowsim", "max_forks_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2040816327, "max_line_length": 133, "alphanum_fraction": 0.7232704403, "num_tokens": 1191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5053673684366342}}
{"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_MINMAG_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MINMAG_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing minmag capabilities\n\n    Returns the input value which have the least absolute value.\n\n    @par Semantic:\n\n    @code\n    auto r = minmag(x,y);\n    @endcode\n\n    is similar to:\n\n    @code\n    auto r = abs(x) < abs(y) ? x : abs(y) < abs(x) ? y : min(x, y);\n    @endcode\n\n   @see min, minnummag, minnum\n\n  **/\n  Value minmag(Value const & x, Value const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/minmag.hpp>\n#include <boost/simd/function/simd/minmag.hpp>\n\n#endif\n", "meta": {"hexsha": "05e9f5fbef46c0cd86d2462654cd1adf3f693989", "size": 1086, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/minmag.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/minmag.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/minmag.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": 22.625, "max_line_length": 100, "alphanum_fraction": 0.5626151013, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5053673653773922}}
{"text": "// Copyright \u00a9 2016-2021 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 <Eigen/Dense>\n#include <vector>\n#include <vinecopulib/bicop/class.hpp>\n\nnamespace vinecopulib {\nnamespace tools_select {\n\nstd::vector<Bicop>\ncreate_candidate_bicops(const Eigen::MatrixXd& data,\n                        const FitControlsBicop& controls);\n\nstd::vector<BicopFamily>\nget_candidate_families(const FitControlsBicop& controls);\n\nvoid\npreselect_candidates(std::vector<Bicop>& bicops,\n                     const Eigen::MatrixXd& data,\n                     double tau,\n                     const Eigen::VectorXd& weights);\n\nstd::vector<double>\nget_c1c2(const Eigen::MatrixXd& data,\n         double tau,\n         const Eigen::VectorXd& weights);\n\nbool\npreselect_family(std::vector<double> c, double tau, const Bicop& bicop);\n}\n}\n\n#include <vinecopulib/bicop/implementation/tools_select.ipp>\n", "meta": {"hexsha": "c5bc4a769f359b405665010da5ae29aaa766015a", "size": 1102, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/vinecopulib/bicop/tools_select.hpp", "max_stars_repo_name": "tvatter/vinecoplib", "max_stars_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-05-05T13:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T23:40:01.000Z", "max_issues_repo_path": "include/vinecopulib/bicop/tools_select.hpp", "max_issues_repo_name": "vinecopulib/vinecopulib", "max_issues_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 264.0, "max_issues_repo_issues_event_min_datetime": "2017-03-28T10:07:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T10:04:39.000Z", "max_forks_repo_path": "include/vinecopulib/bicop/tools_select.hpp", "max_forks_repo_name": "tvatter/vinecoplib", "max_forks_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-04-24T13:54:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T16:56:17.000Z", "avg_line_length": 27.55, "max_line_length": 79, "alphanum_fraction": 0.7050816697, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929207108942, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5052780346590108}}
{"text": "#include <polycrypto/PolyOps.h>\n#include <polycrypto/PolyCrypto.h>\n#include <polycrypto/NtlLib.h>\n\n#include <vector>\n#include <cmath>\n#include <iostream>\n#include <ctime>\n#include <fstream>\n\n#include <libfqfft/polynomial_arithmetic/basic_operations.hpp>\n#include <libff/common/double.hpp>\n\n#include <xutils/Log.h>\n#include <xutils/Timer.h>\n#include <xassert/XAssert.h>\n\n#include <NTL/ZZ_pX.h>\n\nusing namespace std;\nusing namespace libfqfft;\nusing namespace libpolycrypto;\n\nint main(int argc, char *argv[]) {\n    libpolycrypto::initialize(nullptr, 0);\n\n    loginfo << endl;\n    loginfo << \"Initial NTL numThreads: \" << NTL::AvailableThreads() << endl;\n    loginfo << endl;\n    \n    size_t startSz = 16;\n    // 2^24 - 1 seems to be the max # of roots of unity supported by BN254\n    // Also it seems to be the max degree for which libntl doesn't crash dvorak, but makes it very slow\n    if(argc > 1)\n        startSz = static_cast<size_t>(std::stoi(argv[1]));\n\n    int count = 2;\n    if(argc > 2)\n        count = std::stoi(argv[2]);\n\n    if(argc > 3) {\n        long numThreads = std::stoi(argv[3]);\n        if(numThreads > static_cast<int>(getNumCores())) {\n            logerror << \"Number of cores for libntl (\" << numThreads << \") cannot be bigger than # of cores on machine, which is \" << getNumCores() << endl;\n            return 1;\n        }\n\n        if(numThreads > 1) {\n            NTL::SetNumThreads(numThreads);\n            loginfo << \"Changed NTL NumThreads to \" << numThreads << endl;\n            loginfo << \"NTL pool active: \" << NTL::GetThreadPool()->active() << endl;\n            loginfo << endl;\n        }\n    }\n\n    loginfo << \"Multiplication benchmark for degree \" << startSz << \". Iterating \" << count << \" time(s)\" << endl;\n    loginfo << endl;\n\n    for (size_t i = startSz; i <= startSz; i *= 2) {\n        vector<Fr> a, b;\n        vector<Fr> p1, p2, res;\n        ZZ_pX polyX, polyA, polyB;\n\n        bool noFFT = i > 32768;\n\n        AveragingTimer c1, c2, c3, c4;\n        for (int rep = 0; rep < count; rep++) {\n            {\n                //ScopedTimer<> t(std::cout, \"Picking random polynomials took \", \" microsecs\\n\");\n                NTL::random(polyA, static_cast<long>(i+1));\n                NTL::random(polyB, static_cast<long>(i+1));\n                convNtlToLibff(polyA, a);\n                convNtlToLibff(polyB, b);\n            }\n\n            if(!noFFT) {\n                c1.startLap();\n                _polynomial_multiplication(p1, a, b);\n                c1.endLap();\n            }\n\n\n            if(i <= 4096) {\n                c2.startLap();\n                polynomial_multiplication_naive(p2, a, b);\n                c2.endLap();\n            }\n\n            c3.startLap();\n            {\n                c4.startLap();\n                mul(polyX, polyA, polyB);\n                c4.endLap();\n            }\n            convNtlToLibff(polyX, p2);\n            c3.endLap();\n\n            if(!noFFT) {\n                _polynomial_subtraction(res, p1, p2);\n                if (res.size() != 0) {\n                    logerror\n                            << \"The two multiplication functions returned different products\"\n                            << endl;\n                    throw std::runtime_error(\n                            \"One of the multiplication implementations is wrong\");\n                }\n            }\n            p1.clear();\n            p2.clear();\n            \n        }\n        logperf << \"a.size() = \" << a.size() << \", b.size() = \" << b.size() << \", iters = \" << count\n                << endl;\n        if(c1.numIterations() == 0) { \n            //logperf << \" + FFT: skipped\"  << endl;\n        } else {\n            logperf << \" + FFT mult: \" << (double) c1.averageLapTime() / 1000000\n                    << \" seconds.\" << endl;\n        }\n        if(c2.numIterations() == 0) { \n            //logperf << \" + Naive: skipped\"  << endl;\n        } else {\n            logperf << \" + Naive mult: \" << (double) c2.averageLapTime() / 1000000\n                    << \" seconds.\" << endl;\n        }\n        logperf << \" + NTL mult: \"\n                << (double) c4.averageLapTime() / 1000000 << \" +/- \" << c4.stddev() / 1000000 << \" seconds \" << endl;\n        logperf << \" + NTL (with conv): \" << (double) c3.averageLapTime() / 1000000\n                << \" seconds.\" << endl;\n        logperf << endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "2812303c87b78c6c1727401cf70ddde8070970c7", "size": 4350, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libpolycrypto/bench/BenchPolynomialOps.cpp", "max_stars_repo_name": "ibalajiarun/libpolycrypto", "max_stars_repo_head_hexsha": "89a69ed90ee4e9287222cc5781ff11562286f454", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2020-01-29T19:33:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T16:45:51.000Z", "max_issues_repo_path": "libpolycrypto/bench/BenchPolynomialOps.cpp", "max_issues_repo_name": "ibalajiarun/libpolycrypto", "max_issues_repo_head_hexsha": "89a69ed90ee4e9287222cc5781ff11562286f454", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-18T12:33:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T18:30:55.000Z", "max_forks_repo_path": "libpolycrypto/bench/BenchPolynomialOps.cpp", "max_forks_repo_name": "ibalajiarun/libpolycrypto", "max_forks_repo_head_hexsha": "89a69ed90ee4e9287222cc5781ff11562286f454", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-07-09T01:35:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-20T04:54:47.000Z", "avg_line_length": 32.4626865672, "max_line_length": 156, "alphanum_fraction": 0.4949425287, "num_tokens": 1150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5052780174258439}}
{"text": "#ifndef WALI_DOMAINS_MATRIX_MATRIX_TEMPLATE_HPP\n#define WALI_DOMAINS_MATRIX_MATRIX_TEMPLATE_HPP\n\n#include <vector>\n#include <iosfwd>\n\n// We use boost::container::vector because of vector<bool>. Boost's\n// version isn't dumb.\n#include <boost/container/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include <wali/SemElem.hpp>\n\nnamespace wali {\n  namespace domains {\n\n    template<typename ElementType>\n    class Matrix\n      : public SemElem\n    {\n    public:\n      typedef ElementType value_type;\n      typedef boost::numeric::ublas::matrix<value_type, \n                                            boost::numeric::ublas::row_major,\n                                            boost::container::vector<value_type> >\n              BackingMatrix;\n\n      Matrix(BackingMatrix const & mat);\n\n      BackingMatrix const &\n      matrix() const;\n\n      Matrix *\n      zero_raw() const;\n\n      Matrix *\n      one_raw() const;\n\n      Matrix *\n      extend_raw(Matrix * rhs) const;\n\n      Matrix *\n      combine_raw(Matrix * rhs) const;\n\n      bool\n      equal(Matrix * rhs) const;\n\n      std::ostream &\n      print(std::ostream & stream) const;\n\n\n      // Here are the \"normal\" SemElem functions that wrap those above\n      virtual sem_elem_t one() const;\n      virtual sem_elem_t zero() const;\n      virtual sem_elem_t extend(SemElem * se);\n      virtual sem_elem_t combine(SemElem * se);\n      virtual bool equal(SemElem * se) const;\n\n    private:\n      Matrix* down(SemElem* se) const;\n\n      BackingMatrix m_matrix;\n    };\n\n\n    typedef Matrix<bool> BoolMatrix;\n\n  }\n}\n\n// Yo, Emacs!\n// Local Variables:\n//   c-file-style: \"ellemtel\"\n//   c-basic-offset: 2\n// End:\n\n#endif\n", "meta": {"hexsha": "41f974e5516d217ff7626d46b7ca54c77110b2f0", "size": 1675, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AddOns/Domains/Source/wali/domains/matrix/Matrix_template.hpp", "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": "AddOns/Domains/Source/wali/domains/matrix/Matrix_template.hpp", "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": "AddOns/Domains/Source/wali/domains/matrix/Matrix_template.hpp", "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": 21.4743589744, "max_line_length": 82, "alphanum_fraction": 0.6185074627, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.505278006818612}}
{"text": "#include \"Crypt.hpp\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/program_options.hpp>\n#include <algorithm>\n#include <fstream>\n#include <iterator>\n\nnamespace mp = boost::multiprecision;\nnamespace po = boost::program_options;\n\nint main(int argc, char** argv)\n{\n\tpo::options_description commandLineOptions\n\t{\n\t\t\"Usage: rsa [options]\\n\"\n\t\t\"Where options are\"\n\t};\n\tcommandLineOptions.add_options()\n\t\t(\"decrypt,d\", po::value<std::string>(), \"specifies the input file for decryption\")\n\t\t(\"encrypt,e\", po::value<std::string>(), \"specifies the input file for encryption\")\n\t\t(\"help,h\", \"produce help messages\")\n\t\t(\"key,k\", po::value<std::string>(), \"specifies the key file\")\n\t\t(\"output,o\", po::value<std::string>(), \"specify the output file\")\n\t\t;\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, commandLineOptions), vm);\n\tpo::notify(vm);\n\n\t// Run decryption\n\tif(vm.count(\"decrypt\") && vm.count(\"key\") && !vm.count(\"encrypt\"))\n\t{\n\t\tconst std::string inFileName = vm[\"decrypt\"].as<std::string>();\n\t\tconst std::string keyFileName = vm[\"key\"].as<std::string>();\n\t\tconst std::string outFileName = vm.count(\"output\") ? vm[\"output\"].as<std::string>() : inFileName;\n\n\t\t// Get key parameters\n\t\tstd::ifstream keyFile{keyFileName};\n\t\tmp::cpp_int p, q, e;\n\t\tkeyFile >> p >> q >> e;\n\t\tkeyFile.close();\n\n\t\t// Decrypt data\n\t\tstd::ifstream inFile{inFileName};\n\t\tstd::ofstream outFile{outFileName};\n\t\tstd::istream_iterator<mp::cpp_int> inFileFirst{inFile}, inFileLast;\n\t\tstd::ostream_iterator<char> outFileResult{outFile};\n\t\tRSAKey privateKey = makePrivateKey(p, q, e);\n\t\tstd::transform(inFileFirst, inFileLast, outFileResult, [&privateKey](const auto& cypher) { return (char) decrypt(privateKey, cypher); });\n\t}\n\t// Run encryption\n\telse if(vm.count(\"encrypt\") && vm.count(\"key\") && !vm.count(\"decrypt\"))\n\t{\n\t\tconst std::string inFileName = vm[\"encrypt\"].as<std::string>();\n\t\tconst std::string keyFileName = vm[\"key\"].as<std::string>();\n\t\tconst std::string outFileName = vm.count(\"output\") ? vm[\"output\"].as<std::string>() : inFileName;\n\n\t\t// Get key parameters\n\t\tstd::ifstream keyFile{keyFileName};\n\t\tmp::cpp_int n, e;\n\t\tkeyFile >> n >> e;\n\t\tkeyFile.close();\n\n\t\t// Encrypt data\n\t\tstd::ifstream inFile{inFileName};\n\t\tstd::ofstream outFile{outFileName};\n\t\tstd::istream_iterator<char> inFileFirst{inFile}, inFileLast;\n\t\tstd::ostream_iterator<mp::cpp_int> outFileResult{outFile, \" \"};\n\t\tRSAKey publicKey = makePublicKey(n, e);\n\t\tstd::noskipws(inFile);\n\t\tstd::transform(inFileFirst, inFileLast, outFileResult, [&publicKey](char plain) { return encrypt(publicKey, plain); });\n\t}\n\t// Invalid arguments or specified help\n\telse\n\t\tstd::cout << commandLineOptions << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "aa721e84addf5b7b149d64a5fd2ded03bbf970f4", "size": 2693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "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/main.cpp", "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/main.cpp", "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": 34.0886075949, "max_line_length": 139, "alphanum_fraction": 0.6910508726, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5052780054962929}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_IEEE_FUNCTIONS_SCALAR_ULPDIST_HPP_INCLUDED\n#define BOOST_SIMD_IEEE_FUNCTIONS_SCALAR_ULPDIST_HPP_INCLUDED\n#include <boost/simd/ieee/functions/ulpdist.hpp>\n#include <boost/simd/include/constants/eps.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/functions/scalar/abs.hpp>\n#include <boost/simd/include/functions/scalar/tofloat.hpp>\n#include <boost/simd/include/functions/scalar/ldexp.hpp>\n#include <boost/simd/include/functions/scalar/frexp.hpp>\n#include <boost/simd/include/functions/scalar/max.hpp>\n#include <boost/simd/include/functions/scalar/dist.hpp>\n#include <boost/simd/include/functions/scalar/is_nan.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::ulpdist_, tag::cpu_\n                                   , (A0)(A1)\n                                   , (scalar_< arithmetic_<A0> >)\n                                     (scalar_< arithmetic_<A1> >)\n                             )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return ulpdist(A0(a0), A0(a1));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::ulpdist_, tag::cpu_\n                            , (A0)\n                            , (scalar_< arithmetic_<A0> >)\n                              (scalar_< arithmetic_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return dist(a0, a1);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::ulpdist_, tag::cpu_\n                            , (A0)\n                            , (scalar_< bool_<A0> >)(scalar_< bool_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return a0^a1;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::ulpdist_, tag::cpu_\n                            , (A0)\n                            , (scalar_< floating_<A0> >)(scalar_< floating_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename boost::common_type<A0>::type type;\n      typedef typename dispatch::meta::as_integer<A0>::type itype;\n      if (a0 == a1)               return Zero<type>();\n      if (is_nan(a0)&&is_nan(a1)) return Zero<type>();\n      itype e1 = Zero<itype>(), e2 = Zero<itype>();\n      type m1 = Zero<type>(), m2 = Zero<type>();\n      boost::simd::frexp(a0, m1, e1);\n      boost::simd::frexp(a1, m2, e2);\n      itype expo = -boost::simd::max(e1, e2);\n      A0 e = (e1 == e2) ? boost::simd::abs(m1-m2)\n                            :   boost::simd::abs( boost::simd::ldexp(a0, expo)\n                                                - boost::simd::ldexp(a1, expo)\n                                                );\n      return e/static_cast<A0>(Eps<type>());\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "c90da63a9506cae2acaddbc5f5e80cbb59797d93", "size": 3462, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/ieee/include/boost/simd/ieee/functions/scalar/ulpdist.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/ieee/include/boost/simd/ieee/functions/scalar/ulpdist.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/ieee/include/boost/simd/ieee/functions/scalar/ulpdist.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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.043956044, "max_line_length": 82, "alphanum_fraction": 0.5326400924, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5052780054962928}}
{"text": "#pragma once\n\n#include <boost/random.hpp>\n\nclass Distributions {\n\nprivate:\n    boost::mt19937 rng;\n\npublic:\n\n    void set_prng(unsigned int seed) {\n        rng = boost::mt19937(seed);\n    }\n\n    unsigned int get_random_number() {\n        return rng();\n    }\n \n    boost::mt19937& get_rng() {\n        return rng;\n    }\n\n    double inv_scaled_chisq_rng(const double a, const double b) {\n        return inv_gamma_rng(0.5 * a, 0.5 * a * b);\n    }\n\n    double inv_gamma_rng(const double a, const double b) {\n        return 1.0 / rgamma(a, 1.0 / b);\n    }\n\n    double rgamma(const double a, const double b) {\n        boost::random::gamma_distribution<double> myGamma(a, b);\n        boost::random::variate_generator<boost::mt19937&, boost::random::gamma_distribution<> > rand_gamma(rng, myGamma);\n        double val = rand_gamma();\n        return val;\n    }\n\n    double beta_rng(const double a, const double b) {\n        //std::cout << \"@@ beta_rng \" << a << \", \" << b << std::endl;\n        boost::random::beta_distribution<double> mybeta(a, b);\n        boost::random::variate_generator<boost::mt19937&, boost::random::beta_distribution<> > rand_beta(rng, mybeta);\n        double val = rand_beta();\n        //std::cout << \"@@ beta_rng val = \" << val << std::endl;\n        return val;\n    }\n\n    double norm_rng(double mean, double sigma2) {\n        //std::cout << \"@@ norm_rng on \" << mean << \", \" << sigma2 << std::endl;\n        boost::random::normal_distribution<double> nd(mean, std::sqrt(sigma2));\n        boost::random::variate_generator< boost::mt19937&, boost::normal_distribution<> > var_nor(rng, nd);\n        return var_nor();\n    }\n\n    double 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};\n\n\n", "meta": {"hexsha": "ab6e6450f23919d1f789dac5ed4ac83f82da73e3", "size": 1917, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/distributions.hpp", "max_stars_repo_name": "medical-genomics-group/gmrm", "max_stars_repo_head_hexsha": "4bd759c8b80de90c2510de0ed13fd2aa250f6ff3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T12:30:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T15:01:38.000Z", "max_issues_repo_path": "src/distributions.hpp", "max_issues_repo_name": "medical-genomics-group/gmrm", "max_issues_repo_head_hexsha": "4bd759c8b80de90c2510de0ed13fd2aa250f6ff3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distributions.hpp", "max_forks_repo_name": "medical-genomics-group/gmrm", "max_forks_repo_head_hexsha": "4bd759c8b80de90c2510de0ed13fd2aa250f6ff3", "max_forks_repo_licenses": ["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.953125, "max_line_length": 136, "alphanum_fraction": 0.6124152321, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5052780054962926}}
{"text": "#include <boost/assert.hpp>\n#include <Eigen/Cholesky>\n#include <state-observation/noise/gaussian-white-noise.hpp>\n#include <state-observation/tools/probability-law-simulation.hpp>\n\nnamespace stateObservation\n{\n\nGaussianWhiteNoise::GaussianWhiteNoise(Index dimension)\n: dim_(dimension), std_(Matrix::Identity(dimension, dimension)), bias_(Vector::Zero(dimension, 1)),\n  sum_(detail::defaultSum)\n{\n}\n\nGaussianWhiteNoise::GaussianWhiteNoise() : dim_(0), sum_(detail::defaultSum) {}\n\nVector GaussianWhiteNoise::getNoisy(const Vector & v)\n{\n  checkVector_(v);\n\n  sum_(v, tools::ProbabilityLawSimulation::getGaussianMatrix(bias_, std_, dim_), noisy_);\n\n  return noisy_;\n}\n\nvoid GaussianWhiteNoise::setStandardDeviation(const Matrix & std)\n{\n  checkMatrix_(std);\n  std_ = std;\n}\n\nvoid GaussianWhiteNoise::setCovarianceMatrix(const Matrix & cov)\n{\n  checkMatrix_(cov);\n  Matrix L(cov.llt().matrixL());\n  std_ = L;\n}\n\nvoid GaussianWhiteNoise::setBias(const Vector & bias)\n{\n  checkVector_(bias);\n  bias_ = bias;\n}\n\nIndex GaussianWhiteNoise::getDimension() const\n{\n  return dim_;\n}\n\nvoid GaussianWhiteNoise::setDimension(Index dim)\n{\n  dim_ = dim;\n  bias_ = Vector::Zero(dim, 1);\n  std_ = Matrix::Identity(dim, dim);\n}\n\nvoid GaussianWhiteNoise::checkMatrix_(const Matrix & m) const\n{\n  (void)m; // avoid warning\n  BOOST_ASSERT(m.rows() == dim_ && m.cols() == dim_ && \"ERROR: Matrix incorrecly dimemsioned\");\n}\n\nvoid GaussianWhiteNoise::checkVector_(const Vector & v) const\n{\n  (void)v; // avoid warning\n  BOOST_ASSERT(v.rows() == dim_ && v.cols() == 1 && \"ERROR: Vector incorrecly dimemsioned\");\n}\n\nvoid GaussianWhiteNoise::setSumFunction(void (*sum)(const Vector & stateVector,\n                                                    const Vector & tangentVector,\n                                                    Vector & result))\n{\n  sum_ = sum;\n}\n} // namespace stateObservation\n", "meta": {"hexsha": "a7a057d4c3771628aec051e45144388eb206edd5", "size": 1871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gaussian-white-noise.cpp", "max_stars_repo_name": "jrl-umi3218/state-observation", "max_stars_repo_head_hexsha": "bd4f1b7e64a0a3b393f63f69219c061200793d35", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-11-01T16:10:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T00:03:46.000Z", "max_issues_repo_path": "src/gaussian-white-noise.cpp", "max_issues_repo_name": "mehdi-benallegue/state-observation", "max_issues_repo_head_hexsha": "cfc703a52380bd15065801f5d87baba4bbb506ce", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-10-18T09:06:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T04:22:09.000Z", "max_forks_repo_path": "src/gaussian-white-noise.cpp", "max_forks_repo_name": "mehdi-benallegue/state-observation", "max_forks_repo_head_hexsha": "cfc703a52380bd15065801f5d87baba4bbb506ce", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-06-19T09:00:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T06:14:51.000Z", "avg_line_length": 24.6184210526, "max_line_length": 99, "alphanum_fraction": 0.6884019241, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.505278004173973}}
{"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// Written by Cornelius Steinhardt\n\n#include <cmath>\n\n// #include <boost/test/minimal.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n#include <boost/numeric/mtl/operation/trans.hpp>\n\ntemplate <typename Matrix>\nvoid test1(Matrix& m, double tau)\n{\n    mtl::mat::inserter<Matrix> ins(m);\n    size_t nrows=num_rows(m);\n    double val;\n    for (size_t r= 0; r < nrows; ++r) \n\tfor (size_t c= 0; c < nrows; ++c) \n\t    if (r == c)\n\t\tins(r,c) << 1.;\n\t    else {\n\t\tval= 2.*(static_cast<double>(rand())/RAND_MAX - 0.5);\n\t\tif (val < tau)\n\t\t    ins(r,c) << val;\n\t    }\t\t\t\n}\n\n\nint main(int, char**)\n{\n\n  const int N = 10; \n  const int Niter = 10*N;\n\n  using itl::pc::identity; using itl::pc::ilu_0; using itl::pc::ic_0; using itl::pc::diagonal;\n  //typedef mtl::dense2D<double> matrix_type;\n  typedef mtl::compressed2D<double> matrix_type;\n  matrix_type                   A(N, N);\n  mtl::dense_vector<double>     b(N*N, 1), x(N*N), r(x);\n  laplacian_setup(A, N, N);\n  identity<matrix_type>         Ident(A);\n\n  x= 0.5;\n  itl::cyclic_iteration<double> iter_1(b, Niter, 0, 1.e-8, 10);\n\n  bicgstab_ell(A, x, b, Ident, Ident, iter_1, 8);\n  r= A*x-b;\n  std::cout << \"|A*x-b|=\" << two_norm(r) << \"\\n\";\n  if (two_norm(r) > 0.000001) throw \"bicgstab_ell doesn't converge\";\n\n\n  return 0;\n}\n\n\n\n\n", "meta": {"hexsha": "15c73f991d76297663da58fb5d0e00296b27400a", "size": 1744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/bicgstab_ell_output_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/itl/test/bicgstab_ell_output_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/itl/test/bicgstab_ell_output_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": 25.2753623188, "max_line_length": 94, "alphanum_fraction": 0.629587156, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5052780001926769}}
{"text": "#include <iostream>\n#include <fstream>\n#include <armadillo>\n#include <omp.h>\n#include \"Hyperphysics.h\"\n\nint main() {\n    //Setup\n    double simWidth =  300;\n    double simHeight = 300;\n    double simDepth  = 50;\n    int nElem    = 3000;\n    int step     = 20000;\n\n    Hyperphysics physics(nElem, simWidth, simHeight,simDepth);\n    physics.randomPosition();\n    physics.randomMasse();\n    physics.setElemPosition(0,arma::mat {{simWidth/2,simHeight/2,simDepth/2}});\n    physics.setElemMasse(0,1e9);\n    //Print information about the simulation\n    std::cout << \"Simulation READY for \" << omp_get_max_threads() << \" processors \"<<std::endl;\n    std::cout << nElem << \" initialized\" << std::endl;\n    char filePath[255];\n\n    //Simulation Loop\n    for (int i = 1; i < step ; ++i) {\n        snprintf(filePath,255,\"data.csv.%i\",i);\n        physics.step();\n\tif(i%10==1){\n        \tstd::ofstream outFile(filePath);\n\t\toutFile<< \"x, y, z, ux, uy, uz, masse, radius\" <<std::endl;\n        \toutFile<< physics ;\n        \toutFile.close();\n\t}\n        std::cout << \"Time: \" << i << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "6901f91978b9e147eefb9cbe3dfc952afbd493e9", "size": 1097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Spationaute/N-Body-Sim", "max_stars_repo_head_hexsha": "22eb2b7901b37c33f24538762573c6282cc87df5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-01T18:10:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-01T18:10:58.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "Spationaute/N-Body-Sim", "max_issues_repo_head_hexsha": "22eb2b7901b37c33f24538762573c6282cc87df5", "max_issues_repo_licenses": ["MIT"], "max_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": "Spationaute/N-Body-Sim", "max_forks_repo_head_hexsha": "22eb2b7901b37c33f24538762573c6282cc87df5", "max_forks_repo_licenses": ["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.1282051282, "max_line_length": 95, "alphanum_fraction": 0.5989061076, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5052539540070788}}
{"text": "// Copyright (c) 2016\n// Author: Chrono Law\n#include <boost/preprocessor.hpp>\n\n// gcc -P -E -o a.out arithmetic.cpp;cat a.out;rm a.out\n#\n#\n#\n\n#if 1+1 > 3\n    #error test arithmetic in if/endif\n#endif\n\n#define calc(x, y) int x = y\n//calc(x, 1+2)\ncalc(x, BOOST_PP_ADD(1,2))\n\n#define x 1\n#define y 2\n\n#define v BOOST_PP_ADD(x, y)\n\n// check v\nv\n\n#if v != 3\n    BOOST_PP_ASSERT(0)\n#endif\n\n#define u BOOST_PP_SUB(v, x)\nu\n\n#if u != y\n    BOOST_PP_ASSERT(0)\n#endif\n\n#define w BOOST_PP_INC(BOOST_PP_INC(u))\nw\n\n#if w != 4\n    BOOST_PP_ASSERT_MSG(0)\n#endif\n\n#if BOOST_PP_BOOL(w)\n#define a BOOST_PP_MOD(10, 4)\na\n//#define b BOOST_PP_MUL(a, 300)\n//b\n#endif\n\n", "meta": {"hexsha": "f677e38155fdc634a965c47542b6f3f0d40bc296", "size": 645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "preprocessor/arithmetic.cpp", "max_stars_repo_name": "MaxHonggg/professional_boost", "max_stars_repo_head_hexsha": "6fff73d3b9832644068dc8fe0443be813c7237b4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-05-20T08:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T01:17:07.000Z", "max_issues_repo_path": "preprocessor/arithmetic.cpp", "max_issues_repo_name": "MaxHonggg/professional_boost", "max_issues_repo_head_hexsha": "6fff73d3b9832644068dc8fe0443be813c7237b4", "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": "preprocessor/arithmetic.cpp", "max_forks_repo_name": "MaxHonggg/professional_boost", "max_forks_repo_head_hexsha": "6fff73d3b9832644068dc8fe0443be813c7237b4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-07-25T04:52:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T03:55:08.000Z", "avg_line_length": 12.6470588235, "max_line_length": 55, "alphanum_fraction": 0.6496124031, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5052539540070788}}
{"text": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\n// c++ greatest common divisor\n// TODO: c++ todo in sub folder\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n   // TODO: more todo\n}", "meta": {"hexsha": "d4f72d391a36a7deaeee8267bbc127ade4c2dbc6", "size": 382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/samples/sub/cpp.cpp", "max_stars_repo_name": "DTeuchert/vscode-todo-parser", "max_stars_repo_head_hexsha": "2f83a30bfbeb15ae93cf068fff4928287eb466eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2016-02-17T12:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-09T13:42:06.000Z", "max_issues_repo_path": "test/samples/sub/cpp.cpp", "max_issues_repo_name": "DTeuchert/vscode-todo-parser", "max_issues_repo_head_hexsha": "2f83a30bfbeb15ae93cf068fff4928287eb466eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 71.0, "max_issues_repo_issues_event_min_datetime": "2016-06-02T00:27:31.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-02T12:14:36.000Z", "max_forks_repo_path": "test/samples/sub/cpp.cpp", "max_forks_repo_name": "DTeuchert/vscode-todo-parser", "max_forks_repo_head_hexsha": "2f83a30bfbeb15ae93cf068fff4928287eb466eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2016-06-15T10:33:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-28T15:15:00.000Z", "avg_line_length": 31.8333333333, "max_line_length": 97, "alphanum_fraction": 0.5811518325, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5052539492435818}}
{"text": "#include <string>\n#include <algorithm>\n#include <vector>\n#include <array>\n#include <memory>\n#include <map>\n#include <cassert>\n#include <fstream>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp> \n#include \"ARPoly.h\"\n#include \"DatasetPoly.h\"\n#include \"GaussSeq.h\"\n#include \"ZeroSeq.h\"\n#include \"utils.h\"\nusing utils::my_float;\nusing boost::random::uniform_real_distribution;\n\n\n/*\n *  Helper functions\n *\n *  All \"noise setters\" require that the target sequence be defined.\n */\nvoid DatasetPoly::noise_zero() {\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        feats.push_back(std::make_unique<ZeroSeq>());\n    }\n    feats[utils::SALIENT_IND] = std::make_unique<ARPoly>(this->target);\n}\nvoid DatasetPoly::noise_one() {\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        feats.push_back(std::make_unique<GaussSeq>());\n    }\n    feats[utils::SALIENT_IND] = std::make_unique<ARPoly>(this->target);\n}\nvoid DatasetPoly::noise_two() {\n    uniform_real_distribution<my_float> u_mean(-10, 10);\n    uniform_real_distribution<my_float> u_std(0.1, 5);\n\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        feats.push_back(std::make_unique<GaussSeq>(u_mean(gen), u_std(gen)));\n    }\n    feats[utils::SALIENT_IND] = std::make_unique<ARPoly>(this->target);\n}\nvoid DatasetPoly::noise_three() {\n    uniform_real_distribution<my_float> u_const(0, 1);\n    uniform_real_distribution<my_float> u_coeff(-0.9, 0.9);\n    uniform_real_distribution<my_float> u_seed(-1, 1);\n    std::vector<my_float> seed_vect {u_seed(gen),};\n    std::map<int, my_float> coeff_map {\n        {1, u_coeff(gen)},\n    };\n\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        // prep seq backing\n        coeff_map[1] = u_coeff(gen);\n        seed_vect[0] = u_seed(gen);\n\n        ARSeq in_seq(coeff_map, u_const(gen));\n        in_seq.seed_prev_vals(seed_vect);\n\n        feats.push_back(std::make_unique<ARSeq>(in_seq));\n    }\n    feats[utils::SALIENT_IND] = std::make_unique<ARPoly>(this->target);\n}\nvoid DatasetPoly::noise_four() {\n    uniform_real_distribution<my_float> u_const(-1000000, -999999);\n    uniform_real_distribution<my_float> u_coeff(1.1, 2);\n    uniform_real_distribution<my_float> u_seed(0, 0.0000001);\n    std::vector<my_float> seed_vect {u_seed(gen),};\n    std::map<int, my_float> coeff_map {\n        {1, u_coeff(gen)},\n    };\n\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        // prep seq backing\n        coeff_map[1] = u_coeff(gen);\n        seed_vect[0] = u_seed(gen);\n\n        ARSeq in_seq(coeff_map, u_const(gen));\n        in_seq.seed_prev_vals(seed_vect);\n\n        feats.push_back(std::make_unique<ARSeq>(in_seq));\n    }\n    feats[utils::SALIENT_IND] = std::make_unique<ARPoly>(this->target);\n}\n\n\n/*\n *  Constructors and destructors\n */\nDatasetPoly::DatasetPoly(std::string file_name, ARPoly target_seq) {\n    target = target_seq;\n    fname = file_name.append(\".csv\");\n}\n\nDatasetPoly::DatasetPoly(std::string file_name, ARPoly target_seq, unsigned char type) {\n    target = target_seq;\n    fname = file_name.append(\".csv\");\n    noise_type = type;\n    set_noise(type);\n}\n", "meta": {"hexsha": "105685ee6d1f46d9eb4ea215379c1d757376390f", "size": 3180, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gen-data/lib/DatasetPoly.cpp", "max_stars_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_stars_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gen-data/lib/DatasetPoly.cpp", "max_issues_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_issues_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gen-data/lib/DatasetPoly.cpp", "max_forks_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_forks_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_forks_repo_licenses": ["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.2857142857, "max_line_length": 88, "alphanum_fraction": 0.6685534591, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5052329204203893}}
{"text": "//==================================================================================================\n/*!\n  @file\n\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_HORN1_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_HORN1_HPP_INCLUDED\n#include <boost/simd/constant/constant.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n  @ingroup group-arithmetic\n\n    Computes the horner value of its parameter.\n    This is a static polynomial evaluation.\n\n    @par Semantic\n\n    For any value @c x of floating point type @c T,\n    and any integral constants c0,  c1,  ..., cn representing floating point values\n    bits in hexadecimal:\n\n    @code\n    T r = horn1 <T, c0, c1, c2, ...,  cn-1>(x);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    T r = (x+C(n-1))*x+C(n-2))*x+...+C(1))*x+C(0));\n    @endcode\n\n    where C(i) is Constant<T, ci>(),  that is the corresponding floating point value.\n\n    This function evaluates the polynomial of degree n, whose increasing degrees\n    coefficients are given by  C(0), C(1), ..., C(n-1), 1:\n\n      \\f$ x^n+\\sum_0^{n-1} C(i)x^i \\f$\n\n    This differs from @ref horn only by the fact that the leading polynomial\n    coefficient is one, saving one multiplication.\n\n  **/\n  template<typename T> auto horn1(T const& x) {}\n\n } }\n#endif\n\nnamespace boost { namespace simd\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  template < typename T>\n  BOOST_FORCEINLINE T horn1(T) BOOST_NOEXCEPT\n  {\n    return bs::One<T>();\n  }\n\n  template < typename T,  uintmax_t Coef>\n  BOOST_FORCEINLINE T horn1(const T & x) BOOST_NOEXCEPT\n  {\n    return x +  bs::Constant<T, Coef>();\n  }\n\n  template < typename T, uintmax_t Coef0, uintmax_t Coef1, uintmax_t... Args>\n  BOOST_FORCEINLINE T horn1(const T & x) BOOST_NOEXCEPT\n  {\n    return bs::fma(x, horn1 < T, Coef1, Args...>(x),  bs::Constant<T, Coef0>());\n  }\n\n} }\n\n#endif\n", "meta": {"hexsha": "c81c4f2cfe25b17ab767a467d3d40f297b09c62f", "size": 2279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/horn1.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/horn1.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/horn1.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": 26.5, "max_line_length": 100, "alphanum_fraction": 0.6147433085, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5052329196552036}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed 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#include <boost/hana/assert.hpp>\n#include <boost/hana/at.hpp>\n#include <boost/hana/bool.hpp>\n#include <boost/hana/eval.hpp>\n#include <boost/hana/front.hpp>\n#include <boost/hana/functional/fix.hpp>\n#include <boost/hana/functional/iterate.hpp>\n#include <boost/hana/fwd/at.hpp>\n#include <boost/hana/fwd/empty.hpp>\n#include <boost/hana/fwd/prepend.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/is_empty.hpp>\n#include <boost/hana/lazy.hpp>\n#include <boost/hana/not.hpp>\n#include <boost/hana/tail.hpp>\n#include <boost/hana/value.hpp>\n\n#include <cstddef>\nnamespace hana = boost::hana;\n\n\nstruct LazyList;\n\ntemplate <typename X, typename Xs>\nstruct lazy_cons_type {\n    X x;\n    Xs xs;\n    using hana_tag = LazyList;\n};\n\nauto lazy_cons = [](auto x, auto xs) {\n    return lazy_cons_type<decltype(x), decltype(xs)>{x, xs};\n};\n\nstruct lazy_nil_type { using hana_tag = LazyList; };\n\nconstexpr lazy_nil_type lazy_nil{};\n\nauto repeat = hana::fix([](auto repeat, auto x) {\n    return lazy_cons(x, hana::make_lazy(repeat)(x));\n});\n\nnamespace boost { namespace hana {\n    //////////////////////////////////////////////////////////////////////////\n    // Iterable\n    //////////////////////////////////////////////////////////////////////////\n    template <>\n    struct at_impl<LazyList> {\n        template <typename Xs, typename N>\n        static constexpr auto apply(Xs&& lcons, N const&) {\n            constexpr std::size_t n = N::value;\n            return hana::iterate<n>(hana::tail, lcons).x;\n        }\n    };\n\n    template <>\n    struct tail_impl<LazyList> {\n        template <typename Xs>\n        static constexpr auto apply(Xs lcons)\n        { return hana::eval(lcons.xs); }\n    };\n\n    template <>\n    struct is_empty_impl<LazyList> {\n        template <typename Xs>\n        static constexpr auto apply(Xs)\n        { return hana::false_c; }\n\n        static constexpr auto apply(lazy_nil_type)\n        { return hana::true_c; }\n    };\n\n    //////////////////////////////////////////////////////////////////////////\n    // MonadPlus\n    //////////////////////////////////////////////////////////////////////////\n    template <>\n    struct prepend_impl<LazyList> {\n        template <typename Xs, typename X>\n        static constexpr auto apply(Xs xs, X x)\n        { return lazy_cons(x, hana::make_lazy(xs)); }\n    };\n\n    template <>\n    struct empty_impl<LazyList> {\n        static constexpr auto apply()\n        { return lazy_nil; }\n    };\n}}\n\n\nint main() {\n    BOOST_HANA_CONSTANT_CHECK(!hana::is_empty(repeat(1)));\n    BOOST_HANA_CONSTEXPR_CHECK(hana::front(repeat(1)) == 1);\n    BOOST_HANA_CONSTEXPR_CHECK(hana::at(repeat(1), hana::size_c<10>) == 1);\n}\n", "meta": {"hexsha": "00f0c3339b6cf87e9a442cb76ec6a36213aeb461", "size": 2843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experimental/lazy_list.cpp", "max_stars_repo_name": "qicosmos/hana", "max_stars_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-06T05:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T21:48:27.000Z", "max_issues_repo_path": "experimental/lazy_list.cpp", "max_issues_repo_name": "qicosmos/hana", "max_issues_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "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": "experimental/lazy_list.cpp", "max_forks_repo_name": "qicosmos/hana", "max_forks_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-06T10:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-06T10:50:17.000Z", "avg_line_length": 27.8725490196, "max_line_length": 78, "alphanum_fraction": 0.5849454801, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5052329196552036}}
{"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_TANPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_TANPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the tangent of angle in \\f$\\pi\\f$ multiples:\n    \\f$\\cos(\\pi x)/sin(\\pi x)\\f$.\n\n\n    @par Header <boost/simd/function/tanpi.hpp>\n\n    @par Note\n\n     - As most other trigonometric function tanpi can be called with a second\n        optional parameter  which is a tag on speed and accuracy\n       (see @ref cos for further details)\n\n    @see tan, tand\n\n\n    @par Example:\n\n      @snippet tanpi.cpp tanpi\n\n    @par Possible output:\n\n      @snippet tanpi.txt tanpi\n\n  **/\n  IEEEValue tanpi(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/tanpi.hpp>\n#include <boost/simd/function/simd/tanpi.hpp>\n\n#endif\n", "meta": {"hexsha": "f0c5d098c082f103d7036663708ef2196379fac7", "size": 1244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/tanpi.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/function/tanpi.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/function/tanpi.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": 23.9230769231, "max_line_length": 100, "alphanum_fraction": 0.5884244373, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5052329188900174}}
{"text": "#include <Engine/MeshEdit/Paramaterize.h>\n\n#include <Engine/MeshEdit/MinSurf.h>\n\n#include <Engine/Primitive/TriMesh.h>\n\n#include <Eigen/Sparse>\n\nusing namespace Ubpa;\n\nusing namespace std;\n\nParamaterize::Paramaterize(Ptr<TriMesh> triMesh) : heMesh(make_shared<HEMesh<V>>()) {\n\tInit(triMesh);\n}\n\nvoid Paramaterize::Clear() {\n\theMesh->Clear();\n\ttriMesh = nullptr;\n}\n\nbool Paramaterize::Init(Ptr<TriMesh> triMesh) {\n\tClear();\n\n\tif (triMesh == nullptr)\n\t\treturn true;\n\n\tif (triMesh->GetType() == TriMesh::INVALID) {\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is invalid\\n\");\n\t\treturn false;\n\t}\n\n\t// init half-edge structure\n\tsize_t nV = triMesh->GetPositions().size();\n\tvector<vector<size_t>> triangles;\n\ttriangles.reserve(triMesh->GetTriangles().size());\n\tfor (auto triangle : triMesh->GetTriangles())\n\t\ttriangles.push_back({ triangle->idx[0], triangle->idx[1], triangle->idx[2] });\n\theMesh->Reserve(nV);\n\theMesh->Init(triangles);\n\n\tif (!heMesh->IsTriMesh() || !heMesh->HaveBoundary()) {\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is not a triangle mesh or hasn't a boundaries\\n\");\n\t\theMesh->Clear();\n\t\treturn false;\n\t}\n\n\t// triangle mesh's positions ->  half-edge structure's positions\n\tfor (int i = 0; i < nV; i++) {\n\t\tauto v = heMesh->Vertices().at(i);\n\t\tv->pos = triMesh->GetPositions()[i].cast_to<vecf3>();\n\t}\n\n\tthis->triMesh = triMesh;\n\treturn true;\n}\n\nbool Paramaterize::Run() {\n\tif (heMesh->IsEmpty() || !triMesh) {\n\t\tprintf(\"ERROR::MinSurf::Run\\n\"\n\t\t\t\"\\t\"\"heMesh->IsEmpty() || !triMesh\\n\");\n\t\treturn false;\n\t}\n\n\tParamaterization();\n\n\t// half-edge structure -> triangle mesh\n\tsize_t nV = heMesh->NumVertices();\n\tsize_t nF = heMesh->NumPolygons();\n\tvector<pointf3> positions;\n\tvector<unsigned> indice;\n\tpositions.reserve(nV);\n\tindice.reserve(3 * nF);\n\tfor (auto v : heMesh->Vertices())\n\t\tpositions.push_back(v->pos.cast_to<pointf3>());\n\tfor (auto f : heMesh->Polygons()) { // f is triangle\n\t\tfor (auto v : f->BoundaryVertice()) // vertices of the triangle\n\t\t\tindice.push_back(static_cast<unsigned>(heMesh->Index(v)));\n\t}\n\n\tif (show)\n\t\ttriMesh->Update(texcoords);\n\telse\n\t\ttriMesh->Update(positions);\n\n\treturn true;\n}\n\nvoid Paramaterize::Paramaterization() {\n\tSetBoundaryPoints();\n\n\tint nV = heMesh->NumVertices();\n\tvector<Eigen::Triplet<double> > triplets;\n\n\tfor (int i = 0; i < nV; ++i) {\n\t\tV* vi = heMesh->Vertices()[i];\n\t\ttriplets.push_back(Eigen::Triplet<double>(i, i, 1));\n\n\t\tif (!vi->IsBoundary()) {\n\t\t\tdouble adjVertexSize = vi->AdjVertices().size();\n\t\t\tfor (int j = 0; j < adjVertexSize; ++j) {\n\t\t\t\ttriplets.push_back(Eigen::Triplet<double>(i, heMesh->Index(vi->AdjVertices()[j]), -1.0 / adjVertexSize));\n\t\t\t}\n\t\t}\n\t}\n\n\tEigen::SparseMatrix<double> A(nV, nV);\n\tA.setZero();\n\tA.setFromTriplets(triplets.begin(), triplets.end());\n\tEigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n\tsolver.compute(A);\n\n\tif (solver.info() != Eigen::Success) {\n\t\tcout << \"compute is error\" << endl;\n\t\treturn;\n\t}\n\n\tEigen::VectorXd resX(nV), resY(nV), bX(nV), bY(nV);\n\tbX.setZero(); bY.setZero();\n\tfor (int i = 0; i < boundaryIndex.size(); ++i) {\n\t\tV* vi = heMesh->Vertices()[i];\n\t\tbX(boundaryIndex[i]) = boundaryFixedPoints[i][0];\n\t\tbY(boundaryIndex[i]) = boundaryFixedPoints[i][1];\n\t}\n\n\tresX = solver.solve(bX);\n\tresY = solver.solve(bY);\n\n\tfor (int i = 0; i < nV; ++i) {\n\t\tV* vi = heMesh->Vertices()[i];\n\n\t\tvi->pos.at(0) = resX(i);\n\t\tvi->pos.at(1) = resY(i);\n\t\tvi->pos.at(2) = 0;\n\n\t\ttexcoords.push_back(pointf2(resX(i), resY(i)));\n\t}\n\n\treturn;\n}\n\nvoid Paramaterize::SetBoundaryPoints() {\n\tint nB = heMesh->Boundaries()[0].size();\n\tfor (int i = 0; i < nB; ++i) {\n\t\tboundaryIndex.push_back(heMesh->Index(heMesh->Boundaries()[0][i]->Origin()));\n\t}\n\n\tint pointsPerEdge = std::ceil(nB / 4);\n\tdouble step = 1.0 / pointsPerEdge;\n\tfor (int i = 0; i < nB; ++i) {\n\t\tif (i < pointsPerEdge) {\n\t\t\tboundaryFixedPoints.push_back(pointf2(0, step * i));\n\t\t}\n\t\telse if (i >= pointsPerEdge && i < 2 * pointsPerEdge) {\n\t\t\tboundaryFixedPoints.push_back(pointf2((i - pointsPerEdge) * step, 1));\n\t\t}\n\t\telse if (i >= pointsPerEdge * 2 && i < pointsPerEdge * 3) {\n\t\t\tboundaryFixedPoints.push_back(pointf2(1, (3 * pointsPerEdge - i) * step));\n\t\t}\n\t\telse\n\t\t\tboundaryFixedPoints.push_back(pointf2((nB - i) * step, 0));\n\t}\n\n\treturn;\n}\n", "meta": {"hexsha": "4d6f47df557d91803f279a16948825e5db0fe963", "size": 4213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Engine/MeshEdit/Paramaterize.cpp", "max_stars_repo_name": "trygas/CGHomework", "max_stars_repo_head_hexsha": "2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Engine/MeshEdit/Paramaterize.cpp", "max_issues_repo_name": "trygas/CGHomework", "max_issues_repo_head_hexsha": "2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Engine/MeshEdit/Paramaterize.cpp", "max_forks_repo_name": "trygas/CGHomework", "max_forks_repo_head_hexsha": "2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe", "max_forks_repo_licenses": ["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.0773809524, "max_line_length": 109, "alphanum_fraction": 0.6498931878, "num_tokens": 1360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5052329188900174}}
{"text": "// SPDX-License-Identifier: BSD-3-Clause\n// Copyright (c) 2021 Scipp contributors (https://github.com/scipp)\n/// @file\n/// @author Simon Heybrock\n#include <Eigen/Geometry>\n\n#include \"scipp/variable/misc_operations.h\"\n\n#include \"docstring.h\"\n#include \"pybind11.h\"\n\nusing namespace scipp;\nusing namespace scipp::variable::geometry;\n\nnamespace py = pybind11;\n\nvoid init_geometry(py::module &m) {\n  auto geom_m = m.def_submodule(\"geometry\");\n\n  geom_m.def(\n      \"position\",\n      [](const Variable &x, const Variable &y, const Variable &z) {\n        return position(x, y, z);\n      },\n      py::arg(\"x\"), py::arg(\"y\"), py::arg(\"z\"),\n      py::call_guard<py::gil_scoped_release>(),\n      Docstring()\n          .description(\n              \"Element-wise zip functionality to produce a vector_3_float64.\")\n          .raises(\"If the dtypes of inputs are not double precision floats.\")\n          .returns(\n              \"Zip of input x, y and z. Output unit is same as input unit.\")\n          .rtype(\"Variable\")\n          .param(\"x\", \"Variable containing x component.\", \"Variable\")\n          .param(\"y\", \"Variable containing y component.\", \"Variable\")\n          .param(\"z\", \"Variable containing z component.\", \"Variable\")\n          .c_str());\n\n  geom_m.def(\n      \"rotation_matrix_from_quaternion_coeffs\", [](py::array_t<double> value) {\n        if (value.size() != 4)\n          throw std::runtime_error(\"Incompatible list size: expected size 4.\");\n        return Eigen::Quaterniond(value.cast<std::vector<double>>().data())\n            .toRotationMatrix();\n      });\n}\n", "meta": {"hexsha": "e6e0b28d475d5df1556b3e04f1c1a4ce2d279fdf", "size": 1561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "python/geometry.cpp", "max_stars_repo_name": "g5t/scipp", "max_stars_repo_head_hexsha": "d819c930a5e438fd65e42e2e4e737743b8d39d37", "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": "python/geometry.cpp", "max_issues_repo_name": "g5t/scipp", "max_issues_repo_head_hexsha": "d819c930a5e438fd65e42e2e4e737743b8d39d37", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/geometry.cpp", "max_forks_repo_name": "g5t/scipp", "max_forks_repo_head_hexsha": "d819c930a5e438fd65e42e2e4e737743b8d39d37", "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.2127659574, "max_line_length": 79, "alphanum_fraction": 0.6201153107, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5052329141899349}}
{"text": "/**\n * @file calc-characteristic.cpp\n *\n * @brief calculate characteristic polynomial.\n *\n * @author Mutsuo Saito (Hiroshima University)\n * @author Makoto Matsumoto (The University of Tokyo)\n *\n * Copyright (C) 2012 Mutsuo Saito, Makoto Matsumoto,\n * Hiroshima University and The University of Tokyo.\n * All rights reserved.\n *\n * The 3-clause BSD License is applied to this software, see\n * LICENSE.txt\n */\n#include <iostream>\n#include <fstream>\n#include <inttypes.h>\n#include <stdint.h>\n#include <dSFMT-calc-jump.hpp>\n#include <NTL/GF2X.h>\n#include <NTL/vec_GF2.h>\n#include <NTL/GF2XFactoring.h>\n\nusing namespace NTL;\nusing namespace std;\nusing namespace dsfmt;\n\nstatic void read_file(GF2X& lcmpoly, long line_no, const string& file);\n\nint main(int argc, char *argv[]) {\n    if (argc < 2) {\n\tcout << argv[0] << \" filename\" << endl;\n\treturn -1;\n    }\n    string filename = argv[1];\n    GF2X poly;\n    read_file(poly, 0, filename);\n\n    vec_pair_GF2X_long factors;\n    CanZass(factors, poly);\n    cout << \"degree = \" << dec << deg(poly) << endl;\n    cout << \"=== factors ===\" << endl;\n    for (int i = 0; i < factors.length(); i++) {\n\tcout << factors[i].a;\n\tcout << \":\";\n\tcout << dec << deg(factors[i].a);\n\tcout << \":\";\n\tcout << factors[i].b << endl;\n    }\n    cout << \"=== factors ===\" << endl;\n}\n\nstatic void read_file(GF2X& lcmpoly, long line_no, const string& file)\n{\n    ifstream ifs(file.c_str());\n    string line;\n    for (int i = 0; i < line_no; i++) {\n\tifs >> line;\n\tifs >> line;\n    }\n    if (ifs) {\n\tifs >> line;\n\tline = \"\";\n\tifs >> line;\n    }\n    stringtopoly(lcmpoly, line);\n}\n", "meta": {"hexsha": "13ae8fb238e7198ebbf59e0b240751216768e32e", "size": 1591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jump/factorization.cpp", "max_stars_repo_name": "mkt-matsumoto-lab/dSFMT", "max_stars_repo_head_hexsha": "6929b76f2ab07e6302f8daece28045d5bec6ff5c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T06:39:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T14:18:47.000Z", "max_issues_repo_path": "jump/factorization.cpp", "max_issues_repo_name": "mkt-matsumoto-lab/dSFMT", "max_issues_repo_head_hexsha": "6929b76f2ab07e6302f8daece28045d5bec6ff5c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-09-02T02:08:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T06:15:28.000Z", "max_forks_repo_path": "jump/factorization.cpp", "max_forks_repo_name": "MersenneTwister-Lab/dSFMT", "max_forks_repo_head_hexsha": "6929b76f2ab07e6302f8daece28045d5bec6ff5c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-03-09T10:59:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T20:36:09.000Z", "avg_line_length": 23.0579710145, "max_line_length": 71, "alphanum_fraction": 0.6216216216, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5052329141899349}}
{"text": "// log.inl\r\n//\r\n// Copyright (c) 2016 Piotr K. Semenov (piotr.k.semenov at gmail dot com)\r\n// Distributed under the New BSD License. (See accompanying file LICENSE)\r\n\r\n/*!\r\n \\file log.inl\r\n\r\n Provides CORDIC for ln function\r\n \\ref see C. Baumann, \"A simple and fast look-up table method to compute the\r\n exp(x) and ln(x) functions\", 2004\r\n*/\r\n\r\n#ifndef INC_STD_LOG_INL_\r\n#define INC_STD_LOG_INL_\r\n\r\n#include <boost/integer/static_min_max.hpp>\r\n#include <boost/integer/static_log2.hpp>\r\n\r\n#include <cassert>\r\n\r\nnamespace libq {\r\nnamespace details {\r\n/*!\r\n \\brief\r\n \\note \r\n*/\r\ntemplate<typename T, std::size_t n, std::size_t f, int e, typename op, typename up>  // NOLINT\r\nclass log_of\r\n    : public type_promotion_base<\r\n        fixed_point<typename std::make_signed<T>::type, n, f, e, op, up>\r\n        , boost::static_unsigned_max<\r\n                      (f > 0) ? (boost::static_log2<f>::value) : 0,\r\n                      (n > 0) ? (boost::static_log2<n>::value) : 0>::value + 1u\r\n        , 0\r\n        , 0> {\r\n};\r\n}  // namespace details\r\n}  // namespace libq\r\n\r\n\r\nnamespace std {\r\ntemplate<typename T, std::size_t n, std::size_t f, int e, typename op, typename up>  // NOLINT\r\ntypename libq::details::log_of<T, n, f, e, op, up>::promoted_type\r\n    log(libq::fixed_point<T, n, f, e, op, up> _val) {\r\n    using Q = libq::fixed_point<T, n, f, e, op, up>;\r\n    using log_type =\r\n        typename libq::details::log_of<T, n, f, e, op, up>::promoted_type;\r\n    using lut = libq::cordic::lut<f, Q>;\r\n\r\n    assert((\"[std::log] argument is negaitve\", _val >= Q(0)));\r\n    if (_val <= Q(0)) {\r\n        throw std::logic_error(\"[std::log]: argument is negative\");\r\n    }\r\n\r\n    // one need 1 bit to represent integer part of reals from [1.0, 2.0]\r\n    using work_type = libq::UQ<f + 1u, f, 0, op, up>;\r\n\r\n    // reduces argument to interval [1.0, 2.0]\r\n    int power(0);\r\n    Q arg(_val);\r\n    while (arg >= Q(2.0)) {\r\n        libq::lift(arg) >>= 1u;\r\n        power++;\r\n    }\r\n    while (arg < Q(1.0)) {\r\n        libq::lift(arg) <<= 1u;\r\n        power--;\r\n    }\r\n\r\n    // one can consider 0 < y = log(2, x) < 1 as x = 2^y\r\n    // so CORDIC rotation is just a multiplication by 2^{1/2^i}:\r\n    // 2^y = 2^{a1/2} * 2^{a2/4} * ... * 2^{ai/2^i}, where ai is from\r\n    // {0, 1}\r\n    static libq::cordic::lut<f, Q> const inv_pow2_lut = lut::inv_pow2();\r\n\r\n    work_type result(0);\r\n\r\n#ifdef LOOP_UNROLLING\r\n    auto const iteration_body = [&](std::size_t i) {  // NOLINT\r\n#else\r\n    for (std::size_t i = 0; i != f; ++i) {\r\n#endif\r\n        if (work_type(arg * inv_pow2_lut[i]) >= work_type(1.0)) {\r\n            arg = work_type(arg * inv_pow2_lut[i]);\r\n\r\n            libq::lift(result) +=\r\n                typename work_type::storage_type(1u) << (f - i - 1u);\r\n        }\r\n    };  // NOLINT\r\n#ifdef LOOP_UNROLLING\r\n    libq::details::unroll(iteration_body, 0u, libq::details::loop_size<f-1>());\r\n#endif\r\n\r\n    log_type const r0(log_type(result) + log_type(power));\r\n    log_type const r1(r0 * work_type::CONST_1_LOG2E);\r\n\r\n    return r1;\r\n}\r\n}  // namespace std\r\n\r\n#endif  // INC_STD_LOG_INL_\r\n", "meta": {"hexsha": "181c276e365c579dc3ae5477cd570e4a5e3d93f1", "size": 3078, "ext": "inl", "lang": "C++", "max_stars_repo_path": "libq/CORDIC/log.inl", "max_stars_repo_name": "piotr-semenov/libq", "max_stars_repo_head_hexsha": "facfca4610da1ca366637dd030eae5ee06f0c792", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2016-06-15T09:08:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-21T11:57:09.000Z", "max_issues_repo_path": "libq/CORDIC/log.inl", "max_issues_repo_name": "aka-sps/libq", "max_issues_repo_head_hexsha": "facfca4610da1ca366637dd030eae5ee06f0c792", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T18:11:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-30T12:11:09.000Z", "max_forks_repo_path": "libq/CORDIC/log.inl", "max_forks_repo_name": "aka-sps/libq", "max_forks_repo_head_hexsha": "facfca4610da1ca366637dd030eae5ee06f0c792", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-31T23:18:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-19T07:45:43.000Z", "avg_line_length": 29.8834951456, "max_line_length": 95, "alphanum_fraction": 0.5730994152, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5052329141899348}}
{"text": "#include <iostream>\n#include <cassert>\n#include <vector>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> GraphTraits;\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, GraphTraits::edge_descriptor>>>>\n    Graph;\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\nstruct Limb\n{\npublic:\n  int a, b, c;\n\n  Limb(int a, int b, int c) : a(a), b(b), c(c){};\n};\n\nclass EdgeAdder\n{\n  Graph &G;\n\npublic:\n  explicit EdgeAdder(Graph &G) : G(G) {}\n  void add_edge(int from, int to, long capacity)\n  {\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    const Graph::edge_descriptor e = boost::add_edge(from, to, G).first;\n    const Graph::edge_descriptor 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\nvoid testcase()\n{\n  int n, m;\n  std::cin >> n >> m;\n  assert(n >= 2 && n <= 200 && m >= 0 && m <= 5000);\n\n  std::vector<std::vector<int>> limb_index_by_a_b(n, std::vector<int>(n, -1));\n  std::vector<Limb> limbs;\n  for (int i = 0; i < m; i++)\n  {\n    int a, b, c;\n    std::cin >> a >> b >> c;\n    assert(a >= 0 && a < n && b >= 0 && b < n && a != b && c >= 1 && c <= 1000);\n\n    int &limb_index = limb_index_by_a_b.at(a).at(b);\n    if (limb_index == -1)\n    {\n      limb_index = limbs.size();\n      limbs.emplace_back(a, b, 0);\n    }\n\n    Limb &limb = limbs.at(limb_index);\n    assert(limb.a == a && limb.b == b);\n    limb.c += c;\n  }\n\n  int next_free_node = 0;\n  const auto get_node_for_figure = [next_free_node, n](int i) {\n    assert(i >= 0 && i < n);\n    return next_free_node + i;\n  };\n  next_free_node += n;\n  const int num_nodes = next_free_node;\n\n  Graph G(num_nodes);\n  EdgeAdder adder(G);\n  auto c_map = boost::get(boost::edge_capacity, G);\n  auto rc_map = boost::get(boost::edge_residual_capacity, G);\n\n  for (const Limb &limb : limbs)\n  {\n    adder.add_edge(get_node_for_figure(limb.a), get_node_for_figure(limb.b), limb.c);\n  }\n\n  int min_cut_cost_ever = std::numeric_limits<int>::max();\n  for (int source_figure = 0; source_figure < n; source_figure++)\n  {\n    const int target_figure = (source_figure + 1) % n;\n\n    const int node_source = get_node_for_figure(source_figure);\n    const int node_target = get_node_for_figure(target_figure);\n\n    boost::push_relabel_max_flow(G, node_source, node_target);\n\n    std::vector<bool> visited_by_node(num_nodes, false);\n    visited_by_node.at(node_source) = true;\n    std::deque<int> queue{node_source};\n    while (!queue.empty())\n    {\n      const int node = queue.front();\n      queue.pop_front();\n      for (auto it = boost::out_edges(node, G); it.first != it.second; it.first++)\n      {\n        const int next_node = boost::target(*it.first, G);\n        if (rc_map[*it.first] > 0 && !visited_by_node.at(next_node))\n        {\n          visited_by_node.at(next_node) = true;\n          queue.push_back(next_node);\n        }\n      }\n    }\n\n    int min_cut_cost = 0;\n    for (int i = 0; i < num_nodes; i++)\n    {\n      if (!visited_by_node.at(i))\n      {\n        continue;\n      }\n      for (auto it = boost::out_edges(i, G); it.first != it.second; it.first++)\n      {\n        const int j = boost::target(*it.first, G);\n        if (!visited_by_node.at(j))\n        {\n          min_cut_cost += c_map[*it.first];\n        }\n      }\n    }\n    assert(min_cut_cost >= 0);\n    min_cut_cost_ever = std::min(min_cut_cost_ever, min_cut_cost);\n  }\n\n  std::cout << min_cut_cost_ever << \"\\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": "c080942f23b32247c1c77ef9136c425689f6ccc9", "size": 4233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-09/algocoon/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-09/algocoon/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-09/algocoon/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": 27.1346153846, "max_line_length": 133, "alphanum_fraction": 0.584691708, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5052329134247487}}
{"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_SINC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SINC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n  @ingroup group-trigonometric\n    Function object implementing sinc capabilities\n\n    Computes the sinus cardinal  value of its parameter that is  \\f$sin(x)/x\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = sinc(x);\n    @endcode\n\n    @see sin, sincpi, sinhc\n\n  **/\n  Value sinc(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sinc.hpp>\n#include <boost/simd/function/simd/sinc.hpp>\n\n#endif\n", "meta": {"hexsha": "7a23417af70eed4de33c146d03cac5db84e9cdde", "size": 1004, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sinc.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/sinc.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/sinc.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": 23.3488372093, "max_line_length": 100, "alphanum_fraction": 0.5756972112, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5052329032593972}}
{"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_ARCH_COMMON_SCALAR_FUNCTION_MODF_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_MODF_HPP_INCLUDED\n\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/function/trunc.hpp>\n#include <boost/simd/function/std.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n\n  BOOST_DISPATCH_OVERLOAD ( modf_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_<bd::arithmetic_<A0>>\n                          )\n  {\n    using result_t = std::pair <A0, A0>;\n    BOOST_FORCEINLINE result_t operator()(A0 const& a0) const\n    {\n      A0 rounded = bs::trunc(a0);\n      A0 rest    = a0-rounded;\n      return result_t(rest, rounded);\n    }\n   };\n\n  BOOST_DISPATCH_OVERLOAD ( modf_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_<bd::arithmetic_<A0>>\n                          )\n  {\n    using result_t = std::pair <A0, A0>;\n    BOOST_FORCEINLINE result_t operator()(const std_tag &,A0 const& a0) const\n    {\n      A0 rounded, rest;\n      rest = std::modf(a0,&rounded);\n      return result_t(rest, rounded);\n    }\n   };\n} } }\n\n#endif\n", "meta": {"hexsha": "71bf3e140e1a77d68273c8c0468719a2399419ac", "size": 1705, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/modf.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/arch/common/scalar/function/modf.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/arch/common/scalar/function/modf.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.4464285714, "max_line_length": 100, "alphanum_fraction": 0.5143695015, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5052235814580996}}
{"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 testReferenceFrameFactor.cpp\n * @author Alex Cunningham\n */\n\n#include <iostream>\n\n#include <boost/bind.hpp>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <gtsam/base/Testable.h>\n#include <gtsam/base/numericalDerivative.h>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/nonlinear/Symbol.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/NonlinearEquality.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n\n#include <gtsam/slam/ReferenceFrameFactor.h>\n\nusing namespace std;\nusing namespace boost;\nusing namespace gtsam;\n\ntypedef gtsam::ReferenceFrameFactor<gtsam::Point2, gtsam::Pose2> PointReferenceFrameFactor;\ntypedef gtsam::ReferenceFrameFactor<gtsam::Pose2, gtsam::Pose2> PoseReferenceFrameFactor;\n\nKey lA1 = symbol_shorthand::L(1), lA2 = symbol_shorthand::L(2), lB1 = symbol_shorthand::L(11), lB2 = symbol_shorthand::L(12);\nKey tA1 = symbol_shorthand::T(1), tB1 = symbol_shorthand::T(2);\n\n/* ************************************************************************* */\nTEST( ReferenceFrameFactor, equals ) {\n  PointReferenceFrameFactor\n    c1(lB1, tA1, lA1),\n    c2(lB1, tA1, lA1),\n    c3(lB1, tA1, lA2);\n\n  EXPECT(assert_equal(c1, c1));\n  EXPECT(assert_equal(c1, c2));\n  EXPECT(!c1.equals(c3));\n}\n\n/* ************************************************************************* */\nLieVector evaluateError_(const PointReferenceFrameFactor& c,\n    const Point2& global, const Pose2& trans, const Point2& local) {\n  return LieVector(c.evaluateError(global, trans, local));\n}\nTEST( ReferenceFrameFactor, jacobians ) {\n\n  // from examples below\n  Point2 local(2.0, 3.0), global(-1.0, 2.0);\n  Pose2 trans(1.5, 2.5, 0.3);\n\n  PointReferenceFrameFactor tc(lA1, tA1, lB1);\n  Matrix actualDT, actualDL, actualDF;\n  tc.evaluateError(global, trans, local, actualDF, actualDT, actualDL);\n\n  Matrix numericalDT, numericalDL, numericalDF;\n  numericalDF = numericalDerivative31<LieVector,Point2,Pose2,Point2>(\n      boost::bind(evaluateError_, tc, _1, _2, _3),\n      global, trans, local, 1e-5);\n  numericalDT = numericalDerivative32<LieVector,Point2,Pose2,Point2>(\n      boost::bind(evaluateError_, tc, _1, _2, _3),\n      global, trans, local, 1e-5);\n  numericalDL = numericalDerivative33<LieVector,Point2,Pose2,Point2>(\n      boost::bind(evaluateError_, tc, _1, _2, _3),\n      global, trans, local, 1e-5);\n\n  EXPECT(assert_equal(numericalDF, actualDF));\n  EXPECT(assert_equal(numericalDL, actualDL));\n  EXPECT(assert_equal(numericalDT, actualDT));\n}\n\n/* ************************************************************************* */\nTEST( ReferenceFrameFactor, jacobians_zero ) {\n\n  // get values that are ideal\n  Pose2 trans(2.0, 3.0, 0.0);\n  Point2 global(5.0, 6.0);\n  Point2 local = trans.transform_from(global);\n\n  PointReferenceFrameFactor tc(lA1, tA1, lB1);\n  Vector actCost = tc.evaluateError(global, trans, local),\n      expCost = zero(2);\n  EXPECT(assert_equal(expCost, actCost, 1e-5));\n\n  Matrix actualDT, actualDL, actualDF;\n  tc.evaluateError(global, trans, local, actualDF, actualDT, actualDL);\n\n  Matrix numericalDT, numericalDL, numericalDF;\n  numericalDF = numericalDerivative31<LieVector,Point2,Pose2,Point2>(\n      boost::bind(evaluateError_, tc, _1, _2, _3),\n      global, trans, local, 1e-5);\n  numericalDT = numericalDerivative32<LieVector,Point2,Pose2,Point2>(\n      boost::bind(evaluateError_, tc, _1, _2, _3),\n      global, trans, local, 1e-5);\n  numericalDL = numericalDerivative33<LieVector,Point2,Pose2,Point2>(\n      boost::bind(evaluateError_, tc, _1, _2, _3),\n      global, trans, local, 1e-5);\n\n  EXPECT(assert_equal(numericalDF, actualDF));\n  EXPECT(assert_equal(numericalDL, actualDL));\n  EXPECT(assert_equal(numericalDT, actualDT));\n}\n\n/* ************************************************************************* */\nTEST_UNSAFE( ReferenceFrameFactor, converge_trans ) {\n\n  // initial points\n  Point2 local1(2.0, 2.0), local2(4.0, 5.0),\n      global1(-1.0, 5.0), global2(2.0, 3.0);\n  Pose2 transIdeal(7.0, 3.0, M_PI/2);\n\n  // verify direction\n  EXPECT(assert_equal(local1, transIdeal.transform_from(global1)));\n  EXPECT(assert_equal(local2, transIdeal.transform_from(global2)));\n\n  // choose transform\n  //  Pose2 trans = transIdeal; // ideal - works\n  //  Pose2 trans = transIdeal * Pose2(0.1, 1.0, 0.00);  // translation - works\n  //  Pose2 trans = transIdeal * Pose2(10.1, 1.0, 0.00);  // large translation - works\n  //  Pose2 trans = transIdeal * Pose2(0.0, 0.0, 0.1);   // small rotation - works\n  Pose2 trans = transIdeal * Pose2(-200.0, 100.0, 1.3); // combined - works\n  //  Pose2 trans = transIdeal * Pose2(-200.0, 100.0, 2.0); // beyond pi/2 - fails\n\n  NonlinearFactorGraph graph;\n  graph.add(PointReferenceFrameFactor(lB1, tA1, lA1));\n  graph.add(PointReferenceFrameFactor(lB2, tA1, lA2));\n\n  // hard constraints on points\n  double error_gain = 1000.0;\n  graph.add(NonlinearEquality<gtsam::Point2>(lA1, local1, error_gain));\n  graph.add(NonlinearEquality<gtsam::Point2>(lA2, local2, error_gain));\n  graph.add(NonlinearEquality<gtsam::Point2>(lB1, global1, error_gain));\n  graph.add(NonlinearEquality<gtsam::Point2>(lB2, global2, error_gain));\n\n  // create initial estimate\n  Values init;\n  init.insert(lA1, local1);\n  init.insert(lA2, local2);\n  init.insert(lB1, global1);\n  init.insert(lB2, global2);\n  init.insert(tA1, trans);\n\n  // optimize\n  LevenbergMarquardtOptimizer solver(graph, init);\n  Values actual = solver.optimize();\n\n  Values expected;\n  expected.insert(lA1, local1);\n  expected.insert(lA2, local2);\n  expected.insert(lB1, global1);\n  expected.insert(lB2, global2);\n  expected.insert(tA1, transIdeal);\n\n  EXPECT(assert_equal(expected, actual, 1e-4));\n}\n\n/* ************************************************************************* */\nTEST( ReferenceFrameFactor, converge_local ) {\n\n  // initial points\n  Point2 global(-1.0, 2.0);\n  //  Pose2 trans(1.5, 2.5, 0.3); // original\n  //  Pose2 trans(1.5, 2.5, 1.0); // larger rotation\n  Pose2 trans(1.5, 2.5, 3.1); // significant rotation\n\n  Point2 idealLocal = trans.transform_from(global);\n\n  // perturb the initial estimate\n  //  Point2 local = idealLocal; // Ideal case - works\n  //  Point2 local = idealLocal + Point2(1.0, 0.0); // works\n  Point2 local = idealLocal + Point2(-10.0, 10.0); // works\n\n  NonlinearFactorGraph graph;\n  double error_gain = 1000.0;\n  graph.add(PointReferenceFrameFactor(lB1, tA1, lA1));\n  graph.add(NonlinearEquality<gtsam::Point2>(lB1, global, error_gain));\n  graph.add(NonlinearEquality<gtsam::Pose2>(tA1, trans, error_gain));\n\n  // create initial estimate\n  Values init;\n  init.insert(lA1, local);\n  init.insert(lB1, global);\n  init.insert(tA1, trans);\n\n  // optimize\n  LevenbergMarquardtOptimizer solver(graph, init);\n  Values actual = solver.optimize();\n\n  CHECK(actual.exists(lA1));\n  EXPECT(assert_equal(idealLocal, actual.at<Point2>(lA1), 1e-5));\n}\n\n/* ************************************************************************* */\nTEST( ReferenceFrameFactor, converge_global ) {\n\n  // initial points\n  Point2 local(2.0, 3.0);\n  //  Pose2 trans(1.5, 2.5, 0.3); // original\n  //  Pose2 trans(1.5, 2.5, 1.0); // larger rotation\n  Pose2 trans(1.5, 2.5, 3.1); // significant rotation\n\n  Point2 idealForeign = trans.inverse().transform_from(local);\n\n  // perturb the initial estimate\n  //  Point2 global = idealForeign; // Ideal - works\n  //  Point2 global = idealForeign + Point2(1.0, 0.0); // simple - works\n  Point2 global = idealForeign + Point2(10.0, -10.0); // larger - works\n\n  NonlinearFactorGraph graph;\n  double error_gain = 1000.0;\n  graph.add(PointReferenceFrameFactor(lB1, tA1, lA1));\n  graph.add(NonlinearEquality<gtsam::Point2>(lA1, local, error_gain));\n  graph.add(NonlinearEquality<gtsam::Pose2>(tA1, trans, error_gain));\n\n  // create initial estimate\n  Values init;\n  init.insert(lA1, local);\n  init.insert(lB1, global);\n  init.insert(tA1, trans);\n\n  // optimize\n  LevenbergMarquardtOptimizer solver(graph, init);\n  Values actual = solver.optimize();\n\n  // verify\n  CHECK(actual.exists(lB1));\n  EXPECT(assert_equal(idealForeign, actual.at<Point2>(lB1), 1e-5));\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr); }\n/* ************************************************************************* */\n\n\n", "meta": {"hexsha": "815ce391ae9563dd523d182d0c0e0affb8b00528", "size": 8686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/slam/tests/testReferenceFrameFactor.cpp", "max_stars_repo_name": "malcolmreynolds/GTSAM", "max_stars_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-23T19:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-23T19:34:50.000Z", "max_issues_repo_path": "gtsam/slam/tests/testReferenceFrameFactor.cpp", "max_issues_repo_name": "malcolmreynolds/GTSAM", "max_issues_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/slam/tests/testReferenceFrameFactor.cpp", "max_forks_repo_name": "malcolmreynolds/GTSAM", "max_forks_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "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.8835341365, "max_line_length": 125, "alphanum_fraction": 0.6448307621, "num_tokens": 2559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5052235736337958}}
{"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_TRACE_INCLUDE\n#define MTL_TRACE_INCLUDE\n\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace mtl { namespace mat {\n\ntemplate <typename Matrix>\ntypename Collection<Matrix>::value_type\ninline trace(const Matrix& matrix)\n{\n\tvampir_trace<3040> tracer;\n    using math::zero;\n    typedef typename Collection<Matrix>::value_type value_type;\n\n    MTL_THROW_IF(num_rows(matrix) != num_cols(matrix), matrix_not_square());\n\n    // If matrix is empty then the result is the identity from the default-constructed value\n    if (num_rows(matrix) == 0) {\n\tvalue_type ref;\n\treturn zero(ref);\n    }\n\n    value_type value= matrix[0][0];\n    for (unsigned i= 1; i < num_rows(matrix); i++)\n\tvalue+= matrix[i][i];\t\n    return value;\n}\n\n\n}} // namespace mtl::matrix\n\n#endif // MTL_TRACE_INCLUDE\n", "meta": {"hexsha": "bf0269f2f193f97afcd367fec22ebd8503392de3", "size": 1485, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/trace.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": "boost/numeric/mtl/operation/trace.hpp", "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": "boost/numeric/mtl/operation/trace.hpp", "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.1176470588, "max_line_length": 94, "alphanum_fraction": 0.7259259259, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6825737214979746, "lm_q1q2_score": 0.5052235688543605}}
{"text": "/*    Copyright (c) 2010-2018, 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 *    References\n *      Anderson Jr., J.D. , Fundamentals of Aerodynamics, 3rd edition, McGraw Hill, 2001.\n *      Anderson Jr. , J.D, Hypersonic and High-Temperature Gas Dynamics, 2nd edition,\n *          AIAA Education Series, 2006.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <cmath>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\n#include \"Tudat/Astrodynamics/Aerodynamics/aerodynamics.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_aerodynamics_namespace )\n\n//! Test aerodynamic namespace pressure functions.\nBOOST_AUTO_TEST_CASE( testAerodynamicNamespacePressureFunctions )\n{\n    using namespace tudat;\n    using namespace aerodynamics;\n    using mathematical_constants::PI;\n\n    // Set default test conditions.\n    const double machNumber_ = 12.0;\n    const double ratioOfSpecificHeats_ = 1.4;\n\n    // Test local to static pressure ratio.\n    const double localToStaticPressureRatio_ = computeLocalToStaticPressureRatio(\n           machNumber_, ratioOfSpecificHeats_ );\n\n    const double expectedLocalToStaticPressureRatio_ = 1.0 / 0.1445e6;\n    const double toleranceRatioCoefficient_ = 0.1445e6 * 1.0e-8 * 100.0\n            / expectedLocalToStaticPressureRatio_;\n\n    // Check if computed local-to-static pressure ratio matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( localToStaticPressureRatio_,\n                                expectedLocalToStaticPressureRatio_,\n                                toleranceRatioCoefficient_ );\n\n    // Test stagnation pressure coefficient.\n    const double stagnationPressureCoefficient_\n            = computeStagnationPressure( machNumber_, ratioOfSpecificHeats_ );\n\n    const double expectedStagnationPressureCoefficient_ = 1.83402;\n    const double toleranceStagnationPressureCoefficient_ = 1.0e-5 * 100.0\n            / expectedStagnationPressureCoefficient_;\n\n    // Check if computed stagnation pressure coefficient matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( stagnationPressureCoefficient_,\n                                expectedStagnationPressureCoefficient_,\n                                toleranceStagnationPressureCoefficient_ );\n\n    // Test modified Newtonian pressure coefficient.\n    const double newtonianPressureCoefficient_ = computeModifiedNewtonianPressureCoefficient(\n                PI / 2.0, stagnationPressureCoefficient_ );\n\n    const double expectedNewtonianPressureCoefficient_ = stagnationPressureCoefficient_;\n    const double toleranceNewtonianPressureCoefficient_ = 1.0e-15 * 100.0\n            / expectedNewtonianPressureCoefficient_;\n\n    // Check if computed Newtonian pressure coefficient matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( newtonianPressureCoefficient_,\n                                expectedNewtonianPressureCoefficient_,\n                                toleranceNewtonianPressureCoefficient_ );\n\n    // Test empirical tangent cone pressure coefficient.\n    const double empiricalTangentConePressureCoefficient_\n            = computeEmpiricalTangentConePressureCoefficient( PI / 2.0, machNumber_ );\n\n    const double expectedEmpiricalTangentConePressureCoefficient_ = 2.08961;\n    const double toleranceEmpiricalTangentConePressureCoefficient_ = 1.0e-5 * 100.0\n            / expectedEmpiricalTangentConePressureCoefficient_;\n\n    // Check if computed empirical tangent cone pressure coefficient matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( empiricalTangentConePressureCoefficient_,\n                                expectedEmpiricalTangentConePressureCoefficient_,\n                                toleranceEmpiricalTangentConePressureCoefficient_ );\n\n    // Test high Mach base pressure coefficient.\n    const double highMachBasePressure_ = computeHighMachBasePressure( machNumber_ );\n\n    const double expectedHighMachBasePressure_ = -1.0 / ( machNumber_ * machNumber_ );\n    const double toleranceHighMachBasePressure_ = std::fabs( 1.0e-15 * 100.0 / expectedHighMachBasePressure_ );\n\n    // Check if computed high Mach base pressure coefficient matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( highMachBasePressure_,\n                                expectedHighMachBasePressure_,\n                                toleranceHighMachBasePressure_ );\n\n    // Test empirical tangent wedge pressure coefficient.\n    const double empiricalTangentWedgePressureCoefficient_\n            = computeEmpiricalTangentWedgePressureCoefficient( PI / 2.0, machNumber_ );\n\n    const double expectedEmpiricalTangentWedgePressureCoefficient_ = 2.38867;\n    const double toleranceEmpiricalTangentWedgePressureCoefficient_ = 1.0e-5 * 100.0\n            / expectedEmpiricalTangentWedgePressureCoefficient_;\n\n    // Check if computed tangent wedge pressure coefficient matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( empiricalTangentWedgePressureCoefficient_,\n                                expectedEmpiricalTangentWedgePressureCoefficient_,\n                                toleranceEmpiricalTangentWedgePressureCoefficient_ );\n\n    // Test free-stream Prandtl-Meyer function.\n    const double freestreamPrandtlMeyerFunction_ = computePrandtlMeyerFunction(\n           machNumber_, ratioOfSpecificHeats_ );\n\n    const double expectedFreeStreamPrandtlMeyerFunction_ = 106.9 * PI / 180.0;\n    const double toleranceFreeStreamPrandtlMeyerFunction_ = 1.0e-3 * 100.0\n            / expectedFreeStreamPrandtlMeyerFunction_;\n\n    // Check if computed free-stream Prandtl-Meyer function matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( freestreamPrandtlMeyerFunction_,\n                                expectedFreeStreamPrandtlMeyerFunction_,\n                                toleranceFreeStreamPrandtlMeyerFunction_ );\n\n    // Test vacuum pressure coefficient function.\n    const double vacuumPressureCoefficient_ = computeVacuumPressureCoefficient(\n           machNumber_, ratioOfSpecificHeats_ );\n\n    const double expectedVacuumPressureCoefficient_ = -2.0 / ( ratioOfSpecificHeats_\n                                                               * machNumber_ * machNumber_ );\n    const double toleranceVacuumPressureCoefficient_ = std::fabs( 1.0e-15 * 100.0\n            / expectedVacuumPressureCoefficient_ );\n\n    // Check if computed vacuum pressure coefficient matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( vacuumPressureCoefficient_,\n                                expectedVacuumPressureCoefficient_,\n                                toleranceVacuumPressureCoefficient_ );\n}\n\n//! Test pressure coefficients.\nBOOST_AUTO_TEST_CASE( testPressureCoefficients )\n{\n    using std::sin;\n    using namespace tudat;\n    using namespace aerodynamics;\n    using mathematical_constants::PI;\n\n    // Set default conditions.\n    const double machNumber_ = 12.0;\n    const double ratioOfSpecificHeats_ = 1.4;\n\n    // Iterate over 10 angles and test pressure coefficients.\n    for ( int i = 0; i < 10; i++ )\n    {\n         // Set angle.\n         const double angle_ = static_cast< double > ( i ) * PI / 10.0;\n\n         // Compute and compare Newtonian pressure coefficient.\n         const double newtonianPressureCoefficient_\n                 = computeNewtonianPressureCoefficient( angle_ );\n\n         const double expectedNewtonianPressureCoefficient_ =  2.0 * sin( angle_ ) * sin( angle_ );\n         const double toleranceNewtonianPressureCoefficient_ = 1.0e-15 * 100.0\n                 / expectedNewtonianPressureCoefficient_;\n\n         // Check if computed Newtonian pressure coefficient matches expected value.\n         BOOST_CHECK_CLOSE_FRACTION( newtonianPressureCoefficient_,\n                                     expectedNewtonianPressureCoefficient_,\n                                     toleranceNewtonianPressureCoefficient_ );\n\n\n         // Compute Prandtl-Meyer pressure coefficient and test if it is not\n         // lower than vacuum pressure coefficient.\n         const double freestreamPrandtlMeyerFunction_ = computePrandtlMeyerFunction(\n                     machNumber_, ratioOfSpecificHeats_ );\n\n         const double prandtlMeyerPressureCoefficient_ =\n                 computePrandtlMeyerFreestreamPressureCoefficient(\n                     -1.0 * angle_, machNumber_, ratioOfSpecificHeats_,\n                     freestreamPrandtlMeyerFunction_ );\n\n         const double vacuumPressureCoefficient_ = computeVacuumPressureCoefficient(\n                     machNumber_, ratioOfSpecificHeats_ );\n\n         bool isPrandtlMeyerPressureCoefficient = false;\n\n         if ( vacuumPressureCoefficient_ < prandtlMeyerPressureCoefficient_ + 1.0e-15 )\n         {\n             isPrandtlMeyerPressureCoefficient = true;\n         }\n\n         // Check if Prandt-Meyer pressure coefficient is lower than vacuum pressure coefficient.\n         BOOST_CHECK( isPrandtlMeyerPressureCoefficient );\n\n         // Test shock pressure ratio.\n         const double shockPressureRatio_ = computeShockPressureRatio( machNumber_,\n                                                                       ratioOfSpecificHeats_ );\n\n         const double expectedShockPressureRatio_ = 167.8;\n         const double toleranceShockPressureRatio_ = 0.1 * 100.0 / expectedShockPressureRatio_;\n\n         // Check if computed shock pressure ratio matches expected value.\n         BOOST_CHECK_CLOSE_FRACTION( shockPressureRatio_,\n                                     expectedShockPressureRatio_,\n                                     toleranceShockPressureRatio_ );\n\n         // Test shock density ratio.\n         const double shockDensityRatio_ = computeShockDensityRatio( machNumber_,\n                                                                     ratioOfSpecificHeats_ );\n\n         const double expectedShockDensityRatio_ = 5.799;\n         const double toleranceShockDensityRatio_ = 0.001 * 100 / expectedShockDensityRatio_;\n\n         // Check if computed shock density ratio matches expected value.\n         BOOST_CHECK_CLOSE_FRACTION( shockDensityRatio_,\n                                     expectedShockDensityRatio_,\n                                     toleranceShockDensityRatio_ );\n\n         // Test shock temperature ratio.\n         const double shockTemperatureRatio_ = computeShockTemperatureRatio(\n                     machNumber_, ratioOfSpecificHeats_ );\n\n         const double expectedShockTemperatureRatio_ = 28.94;\n         const double toleranceShockTemperatureRatio_ = 0.01 * 100.0\n                 / expectedShockTemperatureRatio_;\n\n         // Check if shock temperature ratio matches expected value.\n         BOOST_CHECK_CLOSE_FRACTION( shockTemperatureRatio_,\n                                     expectedShockTemperatureRatio_,\n                                     toleranceShockTemperatureRatio_ );\n\n         // Test shock total pressure ratio.\n         const double shockTotalPressureRatio_ = computeShockTotalPressureRatio(\n                     machNumber_, ratioOfSpecificHeats_, 287.058 );\n\n         const double expectedShockTotalPressureRatio_ = 0.001287;\n         const double toleranceShockTotalPressureRatio_ = 1.0e-6 *100.0\n                 / expectedShockTotalPressureRatio_;\n\n         // Check if shock total pressure ratio matches expected value.\n         BOOST_CHECK_CLOSE_FRACTION( shockTotalPressureRatio_,\n                                     expectedShockTotalPressureRatio_,\n                                     toleranceShockTotalPressureRatio_ );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "b4e283ea37db312b4a4425957281f88a053d8187", "size": 11952, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Aerodynamics/UnitTests/unitTestAerodynamicsNamespace.cpp", "max_stars_repo_name": "J-Westin/tudat", "max_stars_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "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/Aerodynamics/UnitTests/unitTestAerodynamicsNamespace.cpp", "max_issues_repo_name": "J-Westin/tudat", "max_issues_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Aerodynamics/UnitTests/unitTestAerodynamicsNamespace.cpp", "max_forks_repo_name": "J-Westin/tudat", "max_forks_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "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": 45.7931034483, "max_line_length": 111, "alphanum_fraction": 0.6864123159, "num_tokens": 2432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.5052222334607148}}
{"text": "#include <CGAL/QP_models.h>\n#include <CGAL/QP_functions.h>\n#include <CGAL/QP_solution.h>\n#include <Eigen/Dense>\n#include <iostream>\n#include \"QPSolver.h\"\n\n// choose exact integral type\n#ifdef CGAL_USE_GMP\n#include <CGAL/Gmpz.h>\ntypedef CGAL::Gmpz ET;\n#else\n#include <CGAL/MP_Float.h>\ntypedef CGAL::MP_Float ET;\n#endif\n\ntypedef CGAL::Linear_program_from_iterators\n<const float**, const float*, CGAL::Comparison_result*, const bool*, const float*, const bool*, const float*, const float*> LpProgram;\n\ntypedef CGAL::Quadratic_program_from_iterators\n<const float**, const float*, const CGAL::Comparison_result*, const bool*, const float*, const bool*, const float*, const float**, const float*> QpProgram;\n\ntypedef CGAL::Quadratic_program_from_iterators\n<const int**, const int*, const CGAL::Comparison_result*, const bool*, const int*, const bool*, const int*, const int**, const int*> QpProgram_int;\n\n\ntypedef CGAL::Quadratic_program_solution<ET> Solution;\n\nstd::shared_ptr<const int*> Eigen2CgalArray2d(Eigen::MatrixXi const& eigenMat) {\n\tauto cgalMat = std::shared_ptr<const int*>(new const int* [eigenMat.cols()]);\n\t//auto cgalMat = std::make_shared<float*>(new float[eigenMat.cols()]);\n\tfor (int i = 0; i < eigenMat.cols(); i++)\n\t{\n\t\tcgalMat.get()[i] = eigenMat.data() + i * eigenMat.rows();\n\t}\n\treturn cgalMat;\n}\n\nstd::shared_ptr<const float*> Eigen2CgalArray2d(Eigen::MatrixXf const &eigenMat) {\n\tauto cgalMat = std::shared_ptr<const float*>(new const float*[eigenMat.cols()]);\n\t//auto cgalMat = std::make_shared<float*>(new float[eigenMat.cols()]);\n\tfor (int i = 0; i < eigenMat.cols(); i++)\n\t{\n\t\tcgalMat.get()[i] = eigenMat.data() + i * eigenMat.rows();\n\t}\n\treturn cgalMat;\n}\n\nLinearProgram::LinearProgram(\n\tconst Eigen::MatrixXf& A,\n\tconst Eigen::VectorXf& b,\n\tconst Eigen::VectorXf& c,\n\tconst Eigen::VectorXi& equalityConditions,\n\tconst Eigen::VectorXf& lowerbound,\n\tconst Eigen::VectorXf& upperbound,\n\tfloat accuracy\n):\n\tA(A),\n\tb(b),\n\tc(c),\n\tequalityConditions(equalityConditions),\n\tlowerbound(lowerbound),\n\tupperbound(upperbound),\n\taccuracy(accuracy)\n{}\n\nLinearProgram::Result LinearProgram::solve() {\n\tauto bound_scale_factor = 0.01f;\n\n\tEigen::MatrixXf A_scaled = A / accuracy * bound_scale_factor;\n\tEigen::VectorXf b_scaled = b / accuracy;\n\tEigen::VectorXf c_scaled = c / accuracy;\n\tEigen::VectorXf lb_scaled = lowerbound / bound_scale_factor;\n\tEigen::VectorXf ub_scaled = upperbound / bound_scale_factor;\n\tauto _A_scaled = Eigen2CgalArray2d(A_scaled);\n\n\tCGAL::Comparison_result* r = new CGAL::Comparison_result[A.rows()];\n\tbool* flb = new bool[A.cols()];\n\tbool* fub = new bool[A.cols()];\n\n\tfor (int i = 0; i < A.cols(); i++)\n\t{\n\t\tflb[i] = true;\n\t\tfub[i] = true;\n\t}\n\n\tfor (int iCond = 0; iCond < A.rows(); iCond++)\n\t{\n\t\tif (equalityConditions[iCond] < 0)\n\t\t\tr[iCond] = CGAL::SMALLER;\n\t\telse if (equalityConditions[iCond] > 0)\n\t\t\tr[iCond] = CGAL::LARGER;\n\t\telse\n\t\t\tr[iCond] = CGAL::EQUAL;\n\t}\n\tLpProgram lp(A.cols(), A.rows(), _A_scaled.get(), b_scaled.data(), r, flb, lb_scaled.data(), fub, ub_scaled.data(), c_scaled.data(), 0.f);\n\tSolution s = CGAL::solve_linear_program(lp, ET());\n\tEigen::VectorXf result(A.cols());\n\tfor (auto itr = s.variable_values_begin(); itr != s.variable_values_end(); itr++)\n\t{\n\t\tint index = std::distance(s.variable_values_begin(), itr);\n\t\tresult[index] = (*itr).numerator().to_double() / (*itr).denominator().to_double();\n\t}\n\tresult *= bound_scale_factor;\n\tdelete fub;\n\tdelete flb;\n\tdelete r;\n\treturn LinearProgram::Result{\n\t\ts.objective_value().numerator().to_double() / s.objective_value().denominator().to_double() * accuracy,\n\t\tresult\n\t};\n}\n\nQuadraticProgram::QuadraticProgram(\n\tconst Eigen::MatrixXf& A,\n\tconst Eigen::VectorXf& b,\n\tconst Eigen::MatrixXf& D,\n\tconst Eigen::VectorXf& c,\n\tconst Eigen::VectorXi& equalityConditions,\n\tconst Eigen::VectorXf& lowerbound,\n\tconst Eigen::VectorXf& upperbound,\n\tfloat accuracy\n) :\n\tA(A),\n\tb(b),\n\tD(D),\n\tc(c),\n\tequalityConditions(equalityConditions),\n\tlowerbound(lowerbound),\n\tupperbound(upperbound),\n\taccuracy(accuracy)\n{}\n\nQuadraticProgram::Result QuadraticProgram::solve()\n{\n\tconstexpr auto bound_scale_factor = 0.01f;\n\tEigen::MatrixXf A_scaled = A / accuracy * bound_scale_factor;\n\tEigen::VectorXf b_scaled = b / accuracy;\n\tEigen::MatrixXf D_scaled = D / accuracy * bound_scale_factor;\n\tEigen::VectorXf c_scaled = c / accuracy;\n\tEigen::VectorXf lb_scaled = lowerbound / bound_scale_factor;\n\tEigen::VectorXf ub_scaled = upperbound / bound_scale_factor;\n\tauto _A_scaled = Eigen2CgalArray2d(A_scaled);\n\tauto _D_scaled = Eigen2CgalArray2d(D_scaled);\n\tCGAL::Comparison_result* r = new CGAL::Comparison_result[A.rows()];\n\tfor (int i_eq = 0; i_eq < A.rows(); i_eq++) {\n\t\tif (equalityConditions[i_eq] < 0) {\n\t\t\tr[i_eq] = CGAL::SMALLER;\n\t\t}\n\t\telse if (equalityConditions[i_eq] > 0)\n\t\t\tr[i_eq] = CGAL::LARGER;\n\t\telse\n\t\t\tr[i_eq] = CGAL::EQUAL;\n\t}\n\tbool* flb = new bool[A.cols()];\n\tbool* fub = new bool[A.cols()];\n\tfor (int i = 0; i < A.cols(); i++)\n\t{\n\t\tflb[i] = true;\n\t\tfub[i] = true;\n\t}\n\n\tQpProgram qp(A.cols(), A.rows(), _A_scaled.get(), b_scaled.data(), r, flb, lb_scaled.data(), fub, ub_scaled.data(), _D_scaled.get(), c_scaled.data(), 0);\n\tSolution s = CGAL::solve_quadratic_program(qp, ET());\n\tEigen::VectorXf result(A.cols());\n\tfor (auto itr = s.variable_values_begin(); itr != s.variable_values_end(); itr++)\n\t{\n\t\tint index = std::distance(s.variable_values_begin(), itr);\n\t\tresult[index] = (*itr).numerator().to_double() / (*itr).denominator().to_double();\n\t}\n\tresult *= bound_scale_factor;\n\tdelete fub;\n\tdelete flb;\n\tdelete r;\n\treturn Result{\n\t\ts.objective_value().numerator().to_double() / s.objective_value().denominator().to_double() * accuracy,\n\t\tresult\n\t};\n}\n\n", "meta": {"hexsha": "3cd76f0de6a6038dd2a01d96df78d4fd53237294", "size": 5653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/QPSolver.cpp", "max_stars_repo_name": "shinolab/dynamic-manipulation", "max_stars_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_stars_repo_licenses": ["MIT"], "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/QPSolver.cpp", "max_issues_repo_name": "shinolab/dynamic-manipulation", "max_issues_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_issues_repo_licenses": ["MIT"], "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/QPSolver.cpp", "max_forks_repo_name": "shinolab/dynamic-manipulation", "max_forks_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_forks_repo_licenses": ["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.2320441989, "max_line_length": 155, "alphanum_fraction": 0.7024588714, "num_tokens": 1633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5051303180303265}}
{"text": "//property of Alistair child \n//alistair@mtoto.org\n\n#define _USE_MATH_DEFINES\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n#include <typeinfo>\n#include <iostream>\n#include <cmath>\n#include <fstream>\n//#include <stdio.h>   \n#include <algorithm>   \n#include <complex>\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <typeinfo>\n#include <string>\n//#include <iterator>\nusing namespace std;\n\n\nvoid generic_args(po::options_description &desc,po::positional_options_description &p) {\n    desc.add_options()\n        (\"help,h\", \"produce help message\")\n        (\"lowfield\", po::value<double>()->default_value(0), \"lowest field used (default 0)\")\n        (\"highfield\", po::value<double>()->default_value(0.15), \"highest field used (default 0.15)\")\n        (\"magres\", po::value<int>()->default_value(60), \"n points per angle (default 100)\")\n        (\"intres\", po::value<int>()->default_value(60), \"n trapezoid integral! (default 100)\")\n        (\"length\", po::value<double>()->default_value(500E-9), \"length default (500E-9)\")\n        (\"width\", po::value<double>()->default_value(500E-9), \"width default (500E-9)\")\n        (\"height\", po::value<double>()->default_value(1E-9), \"height default (1E-9)\")\n        (\"angleincrement\", po::value<double>()->default_value(0.5), \"how much to inrement angle by 0-90 (default 1).\")\n        (\"step_height\", po::value<double>()->default_value(10), \"fraction of max critica current. (default 0.1)\")\n        (\"write_to\",   po::value<std::string>()->default_value(\"tsv\"),      \"csv or tsv \")\n        (\"distribution\",   po::value<std::string>()->default_value(\"2d\"),      \"current density 1d or 2d\")\n        (\"view\",   po::value<std::string>()->default_value(\"critical_current\"),      \"profile or critical_current \")\n        (\"step_thickness\", po::value<double>()->default_value(0.1), \"fraction of length.(default 0.1) \");\n    p.add(\"input\", -1);\n}\n\n\nstruct Results\n{\n    vector<vector<double> > critical_current;\n    vector<vector<double> > magnetic_flux;\n    vector<vector<double> > current_density_profile;\n};\n\nstruct Options\n{\n    double lowfield;\n    double highfield;  \n    int N;\n    int n;\n    double L;\n    double w;\n    double d;\n    double angleincrement;\n    double stepheight;\n    double stepthickness;\n    string write_to;\n    string view;\n    string distribution;\n};\n\nvoid resolvedfields(const Options &opts, double k, double theta, double field, double *Bx, double *By, double *kx, double *ky)\n{\n            \n\t*Bx = sin((theta * M_PI)/180)*(field);\n\t*By = cos((theta * M_PI)/180)*(field);\n\t*kx = k * *By;// + ((4*M_PI)/opts.L)* ((a / (1- (b*exp(-K * (*By - C) ) ) ) ) - (a*0.5));\n\t*ky = k * *Bx; //+ ((4*M_PI)/opts.w)* ((a / (1- (b*exp(-K * (*Bx - C) ) ) ) ) - (a*0.5));\n}\n\ndouble geometry(const Options &opts, double x, double y, double thickness, double L, double w, double height)\n{\n    double J0;\n    if ((x <= (- L/2 + thickness) || x >= (L/2 - thickness)) && (opts.distribution == \"2d\"))\n    {\n        //J0 = height * cos((2 * M_PI * x) / L - M_PI) + height;\n        J0 = height;\n    }\n    else if ((y <= (- w/2 + thickness) || y >= (w/2 - thickness)))\n    {\n        J0 = height;\n        //J0 = height * cos((2 * M_PI * y) / L - M_PI) + height;\n    }\n    else\n    {\n        J0 = 0;\n        //J0 = height * cos((4 * M_PI * x ) / L) + height;\n    }\n    return J0;\n}\n\ncomplex<double> current_density(const Options &opts,double Bx,double By,double x, double y, complex<double> Kx, complex<double> Ky, double thickness,double L, double w,double height)\n{\n\n    double a =100;\n    double b = 0.33341;\n    double C = 0.1;\n    double K = 0.12089;\n    \n    double J0 = geometry(opts, x, y, thickness, L, w, height);\n\treturn 1E7 * J0 * exp( Kx * x - Ky * y);// + ((((4*M_PI)/opts.L)* ((a / (1- (b * exp(-K * (2 - C) ) ) ) ))) - (a*0.5))+ (((4*M_PI)/opts.L)* ((a / (1- (b * exp(-K * (0 - C) ) ) ) ) - (a*0.5))));//complex exponential (Phase relations)\n}\n\ndouble sumdoubleintegral(const Options &opts, double Bx, double By, complex<double> Kx, complex<double> Ky,double lowbound1, double lowbound2 ,int n, double dy, double dx, double thickness,double L, double w,double height)\n{\n\tcomplex<double> cumbigsum (0,0);//define and initialise a complex cumsum for outer integral\n\t\n\tfor(int i=0; i<n ;i++)//set up for loop for outer\n\t{\t\n\t\tdouble xi = lowbound1 + i*dx;//define the trapezoid width\n\t\tcomplex<double>  cumsmallsum (0,0);//inner cumsum initialised\n\t\t\n\t\tfor (int j=0; j<n; j++)//inner loop\n\t\t{\n\t\t\tdouble yi = lowbound2 + dy * j;//define trapeziod width \n\t\t\tcomplex<double> funvalue = current_density(opts, Bx ,By,xi, yi, Kx, Ky, thickness, L, w, height);//call function to evaluate return complex double\n\t\t\tcomplex<double> rectanglearea = funvalue * dy;//multiply width by height\n\t\t\tcumsmallsum += rectanglearea;//add to inner cumsum\n\t\t}\n\t\t\n\t\tcomplex<double> secondrectanglearea = cumsmallsum*dx;//use total inner cumsum as cross section\n\t\tcumbigsum += secondrectanglearea;//add up sliced area to get total\n\t}\n\t\t\n\treturn abs(cumbigsum);//return the absolute value of complex number\n}\n\nvoid make_profile(const Options &opts, Results &result)\n{\n    double lowbound1 = -opts.L/2, lowbound2 = -opts.w/2;\n\tdouble upbound1 = opts.L/2, upbound2 = opts.w/2;\n    double dx = (double)(upbound2-lowbound2)/opts.n;//dx\n\tdouble dy = (double)(upbound1-lowbound1)/opts.n;//dy\n    \n    for(int xaxis = 0; xaxis<opts.n ; ++xaxis){\n        double xi = lowbound1 + xaxis * dx;\n        result.current_density_profile.push_back(vector<double>());\n        for(int yaxis = 0 ; yaxis<opts.n ; ++yaxis){\n            double yi = lowbound2 + dy * yaxis;\n            double level = geometry(opts, xi, yi, opts.stepthickness*opts.L, opts.L, opts.w, opts.stepheight);\n            \n            result.current_density_profile[xaxis].push_back(level);\n        }\n    }\n}\n\nvoid write_csv(const vector<string> &labels, const vector< vector<double> > &data)\n{\n    // output labels\n    for(size_t i = 0; i != labels.size(); ++i)    \n    {\n        if (i != 0) cout << \",\";\n        cout << labels[i];\n    }\n    cout << endl;\n    \n    // output data\n    for(const auto& datum: data) {\n        for(size_t i = 0; i != datum.size(); ++i)    \n        {\n            if (i != 0) cout << \",\";\n            cout << datum[i];\n        }\n        cout << endl;    \n    }\n}\n\nvoid write_tsv(const vector< vector<double> > &data)\n{\n    // output data\n    for(const auto& datum: data) {\n        for(size_t i = 0; i != datum.size(); ++i)    \n        {\n            if (i != 0) cout << \"\\t\";\n            cout << datum[i];\n        }\n        cout << endl;    \n    }\n}\n\nvoid file_output(const Options &opts, Results &result)\n{\n    if (opts.view == \"profile\")\n    {\n        for(int xaxis = 0; xaxis < opts.n; ++xaxis)\n\t    {\n\t        for (int yaxis = 0; yaxis < opts.n; ++yaxis)\n\t        {\n                if (opts.write_to == \"csv\"){\n        \t        cout << xaxis << \",\" << yaxis << \",\" << result.current_density_profile[xaxis][yaxis]  << endl;\n\t            }\n                else if(opts.write_to == \"tsv\"){\n                    cout << xaxis << \"\\t\" << yaxis << \"\\t\" << result.current_density_profile[xaxis][yaxis]  << endl;\n                }\n            }\n\t    } \n    }    \n    else if (opts.view == \"critical_current\")\n    {\n        for(int angle = 0; angle <= 90/opts.angleincrement; ++angle)\n\t    {\n            double max = *max_element(result.critical_current[angle].begin(), result.critical_current[angle].end());\n            for (int flux=0; flux < opts.N; ++flux)\n\t        {\n                if(opts.write_to == \"csv\"){\n        \t        cout << angle*opts.angleincrement << \",\" << result.magnetic_flux[angle][flux] << \",\" << result.critical_current[angle][flux]/max << endl;\n\t            }\n                else if(opts.write_to == \"tsv\"){\n                    cout << angle*opts.angleincrement << \"\\t\" << result.magnetic_flux[angle][flux]<< \"\\t\" << result.critical_current[angle][flux]/max << endl;\n                }\n            }   \n\t    } \n    } \n    else\n    {\n        cerr << \"Error: i do not understand the option view. Please choose from the view options --help for info\" << endl;\n    }\n    \n}\n\nvoid getargs(Options &opts, int ac, const char * av[])\n{   \n    //Options opts;\n    try {\n        po::options_description desc(\"Allowed options\");\n        po::positional_options_description p;\n        generic_args(desc, p);//calling function\n        po::variables_map param;\n        po::store(po::command_line_parser(ac, av).options(desc).positional(p).run(), param);\n        po::notify(param);\n        \n        if (param.count(\"help\")) {\n            cout << desc << \"\\n\";\n            exit(0);\n        }\n        \n        opts.lowfield = param[\"lowfield\"].as<double>();\n        opts.highfield = param[\"highfield\"].as<double>();\n        opts.N = param[\"magres\"].as<int>();\n        opts.n = param[\"intres\"].as<int>();\n        opts.L = param[\"length\"].as<double>();\n        opts.w = param[\"width\"].as<double>();\n        opts.d = param[\"height\"].as<double>();\n        opts.stepheight = param[\"step_height\"].as<double>();\n        opts.stepthickness = param[\"step_thickness\"].as<double>();\n        opts.angleincrement = param[\"angleincrement\"].as<double>();\n        opts.write_to = param[\"write_to\"].as<string>();\n        opts.view = param[\"view\"].as<string>();\n        opts.distribution = param[\"distribution\"].as<string>();\n    }\n    catch(exception &e) {\n        cerr << \"error: \" << e.what() << \"\\n\";\n        throw e;\n    }\n}\n\nvoid make_results(const Options &opts, Results &result)\n{\n    //define Physics constants to double precision!\n    double fluxquantum = 2.06783383E-15, lambdax = 90E-9;\n\tcomplex <double> im(0,1);\n    double k = 2 * M_PI * (2 * lambdax + opts.d) / fluxquantum;\n    \n    //define the upper/lower bounds of double integral\n    double lowbound1 = -opts.L/2, lowbound2 = -opts.w/2;\n\tdouble upbound1 = opts.L/2, upbound2 = opts.w/2;\n    double dx = (double)(upbound2-lowbound2)/opts.n;//dx\n\tdouble dy = (double)(upbound1-lowbound1)/opts.n;//dy\n\tdouble step = (opts.highfield - opts.lowfield) / (opts.N-1);\n\tint angleblock = 90 / opts.angleincrement;\n    \n    //create the data.\n\n    for (int angle = 0; angle <= angleblock; ++angle)\n\t{\t\n\t\t\n        //local values set to global values.\n\t\tfloat loc_lowfield = opts.lowfield;\n\t\tfloat loc_highfield = opts.highfield;\n\t\tdouble loc_step = step;\n        \n        result.critical_current.push_back(vector<double>());\n        result.magnetic_flux.push_back(vector<double>());\n        \n\t\tfor (int flux = 0; flux < opts.N; ++flux)\n\t\t{\t\t\t\n\t\t\tfloat field = loc_lowfield;\n\t\t\tloc_lowfield += loc_step; \n\t\t\t//int theta = angle * opts.angleincrement;\n            double theta = angle * opts.angleincrement;\n\n\t\t\tdouble Bx, By ,kx, ky;\n\t\t\tresolvedfields(opts, k, theta, field, &Bx, &By , &kx , &ky);\n\n            \n            double appendff = sumdoubleintegral(opts, Bx, By,kx * im, ky * im, lowbound1, lowbound2, opts.n, dy, dx,opts.stepthickness*opts.L,opts.L, opts.w, opts.stepheight);\n            double mflux =( ( ( (Bx * opts.w) + (By * opts.L) ) * (2 * lambdax + opts.d))  / fluxquantum );//+ ( ((opts.L)* ((a / (1- (b*exp(-K * (2- C) ) ) ) ) - (a*0.5))) / fluxquantum )+ ( ((1)* ((a / (1- (b*exp(-K * (2 - C) ) ) ) ) - (a*0.5))) / fluxquantum );\n            result.critical_current[angle].push_back(appendff);\n            result.magnetic_flux[angle].push_back(mflux);\n\t\t}\t\n\t}  \n    \n    \n}\n\nint main(int ac, const char* av[])\n{\n    //Options opts;\n    try {\n        //Define the user options\n        Options opts;  \n        \n        //parse arguments  \n        getargs(opts, ac, av);\n        \n        //Results(opts) output defined;\n        Results result;\n        \n        //create results call Math\n        make_results(opts, result);\n    \n        //make the current density profile\n        make_profile(opts, result);\n        \n        //write results to a file csv, tsv, 1d 2d.\n        file_output(opts, result);\n    }\n    catch(exception &e) {\n        cerr << \"error: \" << e.what() << \"\\n\";\n        return 1;\n    }\n    \n    return 0;\n}\n", "meta": {"hexsha": "95693eda224d466cecb29be5d9d8a6a06224c4b1", "size": 12028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "AlistairChild/JJSimulation", "max_stars_repo_head_hexsha": "6d61045f6fcf10201d683c68ddbf163af2c2da4b", "max_stars_repo_licenses": ["MIT"], "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": "AlistairChild/JJSimulation", "max_issues_repo_head_hexsha": "6d61045f6fcf10201d683c68ddbf163af2c2da4b", "max_issues_repo_licenses": ["MIT"], "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": "AlistairChild/JJSimulation", "max_forks_repo_head_hexsha": "6d61045f6fcf10201d683c68ddbf163af2c2da4b", "max_forks_repo_licenses": ["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.2727272727, "max_line_length": 264, "alphanum_fraction": 0.573994014, "num_tokens": 3362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5051303137479927}}
{"text": "// Copyright (c) 2020, Ryohei Sasaki\n// All rights reserved.\n//\n// Software License Agreement (BSD License 2.0)\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 {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 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#ifndef KALMAN_FILTER_LOCALIZATION__EKF_HPP_\n#define KALMAN_FILTER_LOCALIZATION__EKF_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iostream>\n\nclass EKFEstimator\n{\npublic:\n  EKFEstimator()\n  : P_(EigenMatrix9d::Identity() * 100),\n    var_imu_w_{0.33},\n    var_imu_acc_{0.33},\n    tau_gyro_bias_{1.0}\n  {\n    /* x  = [p v q] = [x y z vx vy vz qx qy qz qw] */\n    x_ << 0, 0, 0, 0, 0, 0, 0, 0, 0, 1;\n  }\n\n/* state\n* x  = [p v q] = [x y z vx vy vz qx qy qz qw]\n* dx = [dp dv dth] = [dx dy dz dvx dvy dvz dthx dthy dthz]\n*\n* pos_k = pos_{k-1} + vel_k * dt + (1/2) * (Rot(q_{k-1}) acc_{k-1}^{imu} - g) *dt^2\n* vel_k = vel_{k-1} + (Rot(quat_{k-1})) acc_{k-1}^{imu} - g) *dt\n* quat_k = Rot(w_{k-1}^{imu}*dt)*quat_{k-1}\n*\n* covariance\n* P_{k} = F_k P_{k-1} F_k^T + L Q_k L^T\n*/\n  void predictionUpdate(\n    const double current_time_imu,\n    const Eigen::Vector3d & gyro,\n    const Eigen::Vector3d & linear_acceleration\n  )\n  {\n    double dt_imu = current_time_imu - previous_time_imu_;\n    previous_time_imu_ = current_time_imu;\n    if (dt_imu > 0.5 /* [sec] */) {\n      std::cout << \"imu time interval is too large\" << std::endl;\n      return;\n    }\n\n    Eigen::Quaterniond quat_wdt = Eigen::Quaterniond(\n      Eigen::AngleAxisd(gyro.x() * dt_imu, Eigen::Vector3d::UnitX()) *\n      Eigen::AngleAxisd(gyro.y() * dt_imu, Eigen::Vector3d::UnitY()) *\n      Eigen::AngleAxisd(gyro.z() * dt_imu, Eigen::Vector3d::UnitZ()));\n    Eigen::Vector3d acc = Eigen::Vector3d(\n      linear_acceleration.x(),\n      linear_acceleration.y(),\n      linear_acceleration.z());\n\n    // state\n    Eigen::Quaterniond previous_quat =\n      Eigen::Quaterniond(x_(STATE::QW), x_(STATE::QX), x_(STATE::QY), x_(STATE::QZ));\n    Eigen::MatrixXd rot_mat = previous_quat.toRotationMatrix();\n\n    // pos\n    x_.segment(STATE::X, 3) = x_.segment(STATE::X, 3) + dt_imu * x_.segment(STATE::VX, 3) +\n      0.5 * dt_imu * dt_imu * (rot_mat * acc - gravity_);\n    // vel\n    x_.segment(STATE::VX, 3) = x_.segment(STATE::VX, 3) + dt_imu * (rot_mat * acc - gravity_);\n    // quat\n    Eigen::Quaterniond predicted_quat = quat_wdt * previous_quat;\n    x_.segment(STATE::QX, 4) = Eigen::Vector4d(\n      predicted_quat.x(), predicted_quat.y(), predicted_quat.z(), predicted_quat.w());\n\n    // F\n    Eigen::MatrixXd F = EigenMatrix9d::Identity();\n    F.block<3, 3>(0, 3) = dt_imu * Eigen::Matrix3d::Identity();\n    Eigen::Matrix3d acc_skew;\n    acc_skew <<\n      0, -acc(2), acc(1),\n      acc(2), 0, -acc(0),\n      -acc(1), acc(0), 0;\n    F.block<3, 3>(3, 6) = rot_mat * (-acc_skew) * dt_imu;\n\n    // Q\n    Eigen::MatrixXd Q = Eigen::Matrix<double, 6, 6>::Identity();\n    Q.block<3, 3>(0, 0) = var_imu_acc_ * Q.block<3, 3>(0, 0);\n    Q.block<3, 3>(3, 3) = var_imu_w_ * Q.block<3, 3>(3, 3);\n    Q = Q * (dt_imu * dt_imu);\n\n    // L\n    Eigen::MatrixXd L = Eigen::Matrix<double, num_error_state_, 6>::Zero();\n    L.block<3, 3>(3, 0) = Eigen::Matrix3d::Identity();\n    L.block<3, 3>(6, 3) = Eigen::Matrix3d::Identity();\n\n    P_ = F * P_ * F.transpose() + L * Q * L.transpose();\n  }\n\n/*\n* y = pobs = [xobs yobs zobs]\n*\n* K = P_k H^T (H P_k H^T + R)^{-1}\n*\n* dx = K (y_k - p_k )\n*\n* p_x = p_{k-1} + dp_k\n* v_k = v_{k-1} + dv_k\n* q_k = Rot(dth) q_{k-1}\n*\n* P_k = (I - KH)*P_{k-1}\n*/\n  void observationUpdate(\n    const Eigen::Vector3d & y,\n    const Eigen::Vector3d & variance\n  )\n  {\n    // error state\n    Eigen::Matrix3d R;\n    R <<\n      variance.x(), 0, 0,\n      0, variance.y(), 0,\n      0, 0, variance.z();\n    Eigen::MatrixXd H = Eigen::Matrix<double, 3, num_error_state_>::Zero();\n    H.block<3, 3>(0, 0) = Eigen::Matrix3d::Identity();\n    Eigen::MatrixXd K = P_ * H.transpose() * (H * P_ * H.transpose() + R).inverse();\n    Eigen::VectorXd dx = K * (y - x_.segment(STATE::X, 3));\n\n    // state\n    x_.segment(STATE::X, 3) = x_.segment(STATE::X, 3) + dx.segment(ERROR_STATE::DX, 3);\n    x_.segment(STATE::VX, 3) = x_.segment(STATE::VX, 3) + dx.segment(ERROR_STATE::DVX, 3);\n    double norm_quat = sqrt(\n      pow(dx(ERROR_STATE::DTHX), 2) +\n      pow(dx(ERROR_STATE::DTHY), 2) +\n      pow(dx(ERROR_STATE::DTHZ), 2));\n\n    if (norm_quat < 1e-10) {\n      Eigen::Quaterniond dq = Eigen::Quaterniond(0, 0, 0, cos(norm_quat / 2));\n      Eigen::Quaterniond q = Eigen::Quaterniond(x_(STATE::QW), x_(STATE::QX), x_(STATE::QY), x_(STATE::QZ));\n      Eigen::Quaterniond q_new = q * dq;\n      x_.segment(STATE::QX, 4) = Eigen::Vector4d(q_new.x(), q_new.y(), q_new.z(), q_new.w());\n    } else {\n      Eigen::Quaterniond dq = Eigen::Quaterniond(\n        sin(norm_quat / 2) * dx(ERROR_STATE::DTHX) / norm_quat,\n        sin(norm_quat / 2) * dx(ERROR_STATE::DTHY) / norm_quat,\n        sin(norm_quat / 2) * dx(ERROR_STATE::DTHZ) / norm_quat,\n        cos(norm_quat / 2));\n      Eigen::Quaterniond q = Eigen::Quaterniond(x_(STATE::QW), x_(STATE::QX), x_(STATE::QY), x_(STATE::QZ));\n      Eigen::Quaterniond q_new = q * dq;\n      x_.segment(STATE::QX, 4) = Eigen::Vector4d(q_new.x(), q_new.y(), q_new.z(), q_new.w());\n    }\n\n    P_ = (EigenMatrix9d::Identity() - K * H) * P_;\n  }\n\n  void setTauGyroBias(const double tau_gyro_bias)\n  {\n    tau_gyro_bias_ = tau_gyro_bias;\n  }\n\n  void setVarImuGyro(const double var_imu_w)\n  {\n    var_imu_w_ = var_imu_w;\n  }\n\n  void setVarImuAcc(const double var_imu_acc)\n  {\n    var_imu_acc_ = var_imu_acc;\n  }\n\n  void setInitialX(Eigen::VectorXd x)\n  {\n    x_ = x;\n  }\n\n  Eigen::VectorXd getX()\n  {\n    return x_;\n  }\n\n  Eigen::MatrixXd getCoveriance()\n  {\n    return P_;\n  }\n\n  int getNumState()\n  {\n    return num_state_;\n  }\n\nprivate:\n  double previous_time_imu_;\n  double var_imu_w_;\n  double var_imu_acc_;\n\n  static const int num_state_{10};\n  static const int num_error_state_{9};\n\n  typedef Eigen::Matrix<double, num_error_state_, num_error_state_> EigenMatrix9d;\n\n  Eigen::Matrix<double, num_state_, 1> x_;\n  EigenMatrix9d P_;\n\n  const Eigen::Vector3d gravity_{0, 0, 9.80665};\n\n  double tau_gyro_bias_;\n\n  enum STATE\n  {\n    X  = 0, Y = 1, Z = 2,\n    VX = 3, VY = 4, VZ = 5,\n    QX = 6, QY = 7, QZ = 8, QW = 9,\n  };\n  enum ERROR_STATE\n  {\n    DX   = 0, DY = 1, DZ = 2,\n    DVX  = 3, DVY = 4, DVZ = 5,\n    DTHX = 6, DTHY = 7, DTHZ = 8,\n  };\n};\n\n#endif  // KALMAN_FILTER_LOCALIZATION__EKF_HPP_\n", "meta": {"hexsha": "e19e75ebabbd2631bddbafcc961c5510083fa569", "size": 7813, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kalman_filter_localization/ekf.hpp", "max_stars_repo_name": "TaISLab/kalman_filter_localization", "max_stars_repo_head_hexsha": "8d96763cca897497834706719672d2ad4aea28bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 133.0, "max_stars_repo_stars_event_min_datetime": "2020-01-04T03:03:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T05:56:11.000Z", "max_issues_repo_path": "include/kalman_filter_localization/ekf.hpp", "max_issues_repo_name": "TaISLab/kalman_filter_localization", "max_issues_repo_head_hexsha": "8d96763cca897497834706719672d2ad4aea28bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-06-11T04:19:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T07:07:59.000Z", "max_forks_repo_path": "include/kalman_filter_localization/ekf.hpp", "max_forks_repo_name": "TaISLab/kalman_filter_localization", "max_forks_repo_head_hexsha": "8d96763cca897497834706719672d2ad4aea28bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2020-02-21T00:03:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T13:02:08.000Z", "avg_line_length": 31.6315789474, "max_line_length": 108, "alphanum_fraction": 0.6288237553, "num_tokens": 2631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5051303094656586}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/MatrixFunctions>\n#include \"DIIS.hh\"\n\nvoid DIIS::step(Eigen::MatrixXd& F, const Eigen::MatrixXd& D,\n\tconst Eigen::MatrixXd& S, const Eigen::MatrixXd& X, double Etot)\n{\n\tif (_err_vecs_used >= _err_vecs.cols())\n\t{\n\t\tif (_err_vecs_used == 0)\n\t\t{\n\t\t\t_size = F.rows();\n\t\t\t_err_vecs.resize((_size-1)*_size/2, 10);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tEigen::MatrixXd new_err_vecs(_err_vecs.rows(), 2*_err_vecs.cols());\n\t\t\tnew_err_vecs.leftCols(_err_vecs_used) = _err_vecs;\n\t\t\t_err_vecs.swap(new_err_vecs);\n\t\t}\n\t}\n\t\n        // The error matrix is X(FDS - SDF)X = XFDX^-1 - h.c, which since S, P,\n        // F and X are all symmetric, is antisymmetric. Therefore we only store\n        // the upper triangle in vector err.\n\tEigen::MatrixXd FDS = X*F*D*S*X;\n\tint idx = 0;\n\tfor (int i = 1; i < _size; ++i)\n\t\tfor (int j = 0; j < i; ++j, ++idx)\n\t\t\t_err_vecs(idx, _err_vecs_used) = FDS(i,j) - FDS(j,i);\n\n\t_max_err = _err_vecs.col(_err_vecs_used).lpNorm<Eigen::Infinity>();\n\tif (_max_err > std::abs(0.5*Etot))\n\t\t// This Fock matrix will not have a meaningful contribution\n\t\t// to convergence. Ignore it.\n\t\treturn;\n\n\t++_err_vecs_used;\n\t_values.push_back(F);\n\tif (!_started)\n\t{\n\t\tif (_max_err >= std::abs(0.1*Etot))\n\t\t\treturn;\n\t\tstd::cout << \"Starting DIIS\\n\";\n\t\t_started = true;\n\t}\n\n\tauto e = _err_vecs.leftCols(_err_vecs_used);\n\tEigen::MatrixXd B(_err_vecs_used+1, _err_vecs_used+1);\n\tB.topLeftCorner(_err_vecs_used, _err_vecs_used) = e.transpose() * e * 2;\n\tB.rightCols(1).fill(-1);\n\tB.bottomRows(1).fill(-1);\n\n\tEigen::VectorXd y = Eigen::VectorXd::Zero(_err_vecs_used+1);\n\ty[_err_vecs_used] = -1;\n\n\tEigen::VectorXd coefs = B.colPivHouseholderQr().solve(y);\n\tF *= coefs[_err_vecs_used-1];\n\tfor (int i = 0; i < _err_vecs_used-1; ++i)\n\t\tF += coefs[i] * _values[i];\n}\n\nvoid DIIS::step(Eigen::MatrixXd& Fa, const Eigen::MatrixXd& Da,\n\tEigen::MatrixXd& Fb, const Eigen::MatrixXd& Db,\n\tconst Eigen::MatrixXd& S, const Eigen::MatrixXd& X, double Etot)\n{\n\tif (_err_vecs_used >= _err_vecs.cols())\n\t{\n\t\tif (_err_vecs_used == 0)\n\t\t{\n\t\t\t_size = Fa.rows();\n\t\t\t_err_vecs.resize((_size-1)*_size, 10);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tEigen::MatrixXd new_err_vecs(_err_vecs.rows(), 2*_err_vecs.cols());\n\t\t\tnew_err_vecs.leftCols(_err_vecs_used) = _err_vecs;\n\t\t\t_err_vecs.swap(new_err_vecs);\n\t\t}\n\t}\n\n\tEigen::MatrixXd FDS = X*Fa*Da*S*X;\n\tint idx = 0;\n\tfor (int i = 1; i < _size; ++i)\n\t\tfor (int j = 0; j < i; ++j, ++idx)\n\t\t\t_err_vecs(idx, _err_vecs_used) = FDS(i,j) - FDS(j,i);\n\tFDS = X*Fb*Db*S*X;\n\tfor (int i = 1; i < _size; ++i)\n\t\tfor (int j = 0; j < i; ++j, ++idx)\n\t\t\t_err_vecs(idx, _err_vecs_used) = FDS(i,j) - FDS(j,i);\n\n\t_max_err = _err_vecs.col(_err_vecs_used).lpNorm<Eigen::Infinity>();\n\tif (_max_err > std::abs(0.5*Etot))\n\t\t// This Fock matrix will not have a meaningful contribution\n\t\t// to convergence. Ignore it.\n\t\treturn;\n\n\t++_err_vecs_used;\n\tEigen::MatrixXd F(_size, 2*_size);\n\tF.leftCols(_size) = Fa;\n\tF.rightCols(_size) = Fb;\n\t_values.push_back(F);\n\tif (!_started)\n\t{\n\t\tif (_max_err >= std::abs(0.1*Etot))\n\t\t\treturn;\n\t\tstd::cout << \"Starting DIIS\\n\";\n\t\t_started = true;\n\t}\n\n\tauto e = _err_vecs.leftCols(_err_vecs_used);\n\tEigen::MatrixXd B(_err_vecs_used+1, _err_vecs_used+1);\n\tB.topLeftCorner(_err_vecs_used, _err_vecs_used) = e.transpose() * e * 2;\n\tB.rightCols(1).fill(-1);\n\tB.bottomRows(1).fill(-1);\n\n\tEigen::VectorXd y = Eigen::VectorXd::Zero(_err_vecs_used+1);\n\ty[_err_vecs_used] = -1;\n\n\tEigen::VectorXd coefs = B.colPivHouseholderQr().solve(y);\n\tF *= coefs[_err_vecs_used-1];\n\tfor (int i = 0; i < _err_vecs_used-1; ++i)\n\t\tF += coefs[i] * _values[i];\n\n\tFa = F.leftCols(_size);\n\tFb = F.rightCols(_size);\n}", "meta": {"hexsha": "7088c72c98417e04491d7ed58e8ea769f3d21629", "size": 3616, "ext": "cc", "lang": "C++", "max_stars_repo_path": "DIIS.cc", "max_stars_repo_name": "gvissers/quill2", "max_stars_repo_head_hexsha": "589d7bc3ce20da888547f8f4f6b8da908b3d63a5", "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": "DIIS.cc", "max_issues_repo_name": "gvissers/quill2", "max_issues_repo_head_hexsha": "589d7bc3ce20da888547f8f4f6b8da908b3d63a5", "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": "DIIS.cc", "max_forks_repo_name": "gvissers/quill2", "max_forks_repo_head_hexsha": "589d7bc3ce20da888547f8f4f6b8da908b3d63a5", "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.25, "max_line_length": 79, "alphanum_fraction": 0.6532079646, "num_tokens": 1297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5051303094656585}}
{"text": "/*\n *            Copyright 2009-2019 The VOTCA-MPIP Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\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 * author: Denis Andrienko\n */\n\n\n\n#include <votca/ctp/overlap.h>\n#include <votca/ctp/linalg.h>\n\n#include <votca/tools/constants.h>\n#include <boost/format.hpp>\n#include <boost/progress.hpp>\n\nnamespace votca { namespace ctp {\n\nnamespace ub = boost::numeric::ublas;\n\ndouble inv_sqrt(double x) { return 1./sqrt(x); }\nusing boost::format;\n\n/*\n * Calculates S^{-1/2}\n */\nvoid Overlap::SQRTOverlap(ub::symmetric_matrix<double> &S, \n                          ub::matrix<double> &S2 ) {\n       \n    double (*_inv_sqrt)(double);\n    _inv_sqrt = &inv_sqrt;\n\n    ub::vector<double>                  _eigenvalues;\n    ub::matrix<double>                  _eigenvectors;\n\n    int _size = S.size1(); \n\n    _eigenvalues.resize( _size );\n    _eigenvectors.resize( _size, _size );\n    \n    //convert from symmetric to matrix for faster evaluation\n    ub::matrix<double> temp=S;\n    \n\n    // TEST CASE FOR EIGEN   \n       ub::matrix<double> m(3,3);\n       /*\n       m(0,0) = -2;\n       m(0,1) = -4;\n       m(0,2) =  2;\n       m(1,0) = -2;\n       m(1,1) =  1;\n       m(1,2) =  2;\n       m(2,0) =  4;\n       m(2,1) =  2;\n       m(2,2) =  5;\n       */\n       \n       /* 4 -2 -2\n       m(0,0) =  1;\n       m(0,1) = -3;\n       m(0,2) =  3;\n       m(1,0) =  3;\n       m(1,1) = -5;\n       m(1,2) =  3;\n       m(2,0) =  6;\n       m(2,1) = -6;\n       m(2,2) =  4;\n       */\n\n       /*symmetric, -1, -1, 8\n       m(0,0) =    2;\n       m(0,1) =    1;\n       m(0,2) =    -2;\n       m(1,0) =    1;\n       m(1,1) =    0;\n       m(1,2) =    1;\n       m(2,0) =    -2;\n       m(2,1) =    1;\n       m(2,2) =    0;\n\n       \n    _eigenvalues.resize( 3 );\n    _eigenvectors.resize( 3, 3 );\n       \n    linalg::eigenvalues_symm(m, _eigenvalues, _eigenvectors);\n    \n    std::cout << \"\\nEigenvalues\" << std::endl << _eigenvalues;\n    std::cout << \"\\nEigenvectors\" << std::endl << _eigenvectors << std::endl;\n    exit(0);       \n    */\n\n    \n    linalg::eigenvalues_symm(temp, _eigenvalues, _eigenvectors);\n    \n    // compute inverse sqrt of all eigenvalues\n    std::transform(_eigenvalues.begin(), _eigenvalues.end(), _eigenvalues.begin(),  _inv_sqrt );\n\n    // form a diagonal matrix S^{-1/2}\n    ub::diagonal_matrix<double> _diagS2( _eigenvalues.size(), _eigenvalues.data() ); \n\n    // multiply from the left on the U\n    ub::matrix<double> _temp = ub::prod( _eigenvectors, _diagS2 );\n    \n    // multiply from the right on the transpose U\n    S2 = ub::prod( _temp, ub::trans( _eigenvectors ) );\n    return;\n }\n\ndouble Overlap::getCouplingElement( int levelA, int levelB,  Orbitals* _orbitalsA,\n    Orbitals* _orbitalsB, ub::matrix<double>* _JAB, double  _energy_difference ) {\n\n    \n    int _levelsA = _orbitalsA->getNumberOfLevels();\n    \n    if ( _energy_difference != 0 ) {\n        std::vector<int> list_levelsA = *_orbitalsA->getDegeneracy( levelA, _energy_difference );\n        std::vector<int> list_levelsB = *_orbitalsA->getDegeneracy( levelB, _energy_difference );\n        \n        double _JAB_sq = 0; double _JAB_one_level;\n        \n        for (std::vector<int>::iterator iA = list_levelsA.begin()++; iA != list_levelsA.end(); iA++) {\n                for (std::vector<int>::iterator iB = list_levelsB.begin()++; iB != list_levelsB.end(); iB++) { \n                    //cout << *iA << ':' << *iB << endl;\n                    _JAB_one_level = _JAB->at_element( *iA - 1  , *iB -1 + _levelsA );\n                    _JAB_sq +=  _JAB_one_level*_JAB_one_level ;\n                }\n        }\n        \n        return sqrt(_JAB_sq / ( list_levelsA.size() * list_levelsB.size() ) ) * tools::conv::hrt2ev ;\n        \n    } else {\n        \n        return _JAB->at_element( levelA - 1  , levelB -1 + _levelsA ) * tools::conv::hrt2ev;\n        \n    }\n    // the  matrix should be symmetric, could also return this element\n    // _JAB.at_element( _levelsA + levelB - 1  , levelA - 1 );\n}\n\n/**\n * \\brief evaluates electronic couplings  \n * \n * This is a slow version with a rather large block matrix AxB\n * \n * @param _orbitalsA molecular orbitals of molecule A\n * @param _orbitalsB molecular orbitals of molecule B\n * @param _orbitalsAB molecular orbitals of the dimer AB\n * @param _JAB matrix with electronic couplings\n * @return false if failed\n */\nbool Overlap::CalculateIntegrals(Orbitals* _orbitalsA, Orbitals* _orbitalsB, \n    Orbitals* _orbitalsAB, ub::matrix<double>* _JAB) {\n\n    CTP_LOG(logDEBUG,*_pLog) << \"Calculating electronic couplings\" << std::flush;\n    \n    const std::vector<QMAtom*> atomsA=_orbitalsA->QMAtoms();\n    const std::vector<QMAtom*> atomsB=_orbitalsB->QMAtoms();\n    const std::vector<QMAtom*> atomsAB=_orbitalsAB->QMAtoms();\n        \n  for (unsigned i=0;i<atomsAB.size();i++){\n        QMAtom* dimer=atomsAB[i];\n        QMAtom* monomer=NULL;\n        if (i<atomsA.size()){\n            monomer=atomsA[i];\n        }\n        else if (i<atomsB.size()+atomsA.size() ){\n            monomer=atomsB[i-atomsA.size()];\n        }\n        else{\n\t  throw std::runtime_error((format(\"Number of Atoms in dimer %3i and the two monomers A:%3i B:%3i does not agree\") %atomsAB.size() %atomsA.size() %atomsB.size()).str());\n        }\n        \n        if(monomer->type != dimer->type){\n\t  throw std::runtime_error(\"\\nERROR: Atom types do not agree in dimer and monomers\\n\");\n        }\n        if(std::abs(monomer->x-dimer->x)>0.001 || std::abs(monomer->y-dimer->y)>0.001 || std::abs(monomer->z-dimer->z)>0.001){\n            CTP_LOG(logERROR,*_pLog) << \"======WARNING=======\\n Coordinates of monomers and dimer atoms do not agree, do you know what you are doing?\\n \" << std::flush;\n            break;\n        }\n        \n    }\n         \n    // constructing the direct product orbA x orbB\n    int _basisA = _orbitalsA->getBasisSetSize();\n    int _basisB = _orbitalsB->getBasisSetSize();\n    \n    if ( ( _basisA == 0 ) || ( _basisB == 0 ) ) {\n        CTP_LOG(logERROR,*_pLog) << \"Basis set size is not stored in monomers\" << std::flush;\n        return false;\n    }\n        \n    int _levelsA = _orbitalsA->getNumberOfLevels();\n    int _levelsB = _orbitalsB->getNumberOfLevels();\n    \n    //boost::timer t; // start timing\n    //double _st = t.elapsed();\n    \n    CTP_LOG(logDEBUG,*_pLog) << \"Levels:Basis A[\" << _levelsA << \":\" << _basisA << \"]\"\n                                     << \" B[\" << _levelsB << \":\" << _basisB << \"]\" << std::flush;\n    \n    if ( ( _levelsA == 0 ) || (_levelsB == 0) ) {\n        CTP_LOG(logERROR,*_pLog) << \"No information about number of occupied/unoccupied levels is stored\" << std::flush;\n        return false;\n    } \n    \n    //       | Orbitals_A          0 |      | Overlap_A |     \n    //       | 0          Orbitals_B |  X   | Overlap_B |  X  Transpose( Orbitals_AB )\n    ub::zero_matrix<double> zeroB( _levelsA, _basisB ) ;\n    ub::zero_matrix<double> zeroA( _levelsB, _basisA ) ;\n    ub::matrix<double> _psi_AxB ( _levelsA + _levelsB, _basisA + _basisB  );\n    \n    CTP_LOG(logDEBUG,*_pLog) << \"BOOST: Constructing direct product AxB [\" \n            << _psi_AxB.size1() << \"x\" \n            << _psi_AxB.size2() << \"]\" << std::flush;    \n     \n    \n/*\n    // TEST CASE FOR EIGEN   \n       ub::matrix<double> m1_(2,3);\n       m1_(0,0) = 1;\n       m1_(0,1) = 2;\n       m1_(0,2) = 3;\n       m1_(1,0) = 4;\n       m1_(1,1) = 5;\n       m1_(1,2) = 6;\n       //std::cout << std::endl << m1_ << std::endl ;\n\n       ub::matrix<double> m2_(3,2);\n       m2_(0,0) = 7;\n       m2_(0,1) = 8;\n       m2_(1,0) = 9;\n       m2_(1,1) = 10;\n       m2_(2,0) = 11;\n       m2_(2,1) = 12;\n       //std::cout << std::endl << m2_ << std::endl ;\n\n       ub::prod(m1_, m2_);\n */\n       \n    ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( _basisA, _basisA +_basisB ) ) = zeroB;\n    ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( 0, _basisA ) ) = zeroA;    \n    ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( 0, _basisA ) ) = *_orbitalsA->getOrbitals();\n    ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( _basisA, _basisA + _basisB ) ) = *_orbitalsB->getOrbitals(); \n           \n    // psi_AxB * S_AB * psi_AB\n    CTP_LOG(logDEBUG,*_pLog) << \"Projecting dimer onto monomer orbitals\" << std::flush; \n    ub::matrix<double> _orbitalsAB_Transposed = ub::trans( *_orbitalsAB->getOrbitals() );  \n    if ( (*_orbitalsAB->getOverlap()).size1() == 0 ) {\n            CTP_LOG(logERROR,*_pLog) << \"Overlap matrix is not stored\"; \n            return false;\n    }\n     \n    ub::matrix<double> _psi_AB = ub::prod( *_orbitalsAB->getOverlap(), _orbitalsAB_Transposed );  \n    ub::matrix<double> _psi_AxB_dimer_basis = ub::prod( _psi_AxB, _psi_AB );  \n    _psi_AB.clear();\n    \n    //check to see if projection quality is sufficient\n    for (unsigned i=0;i<_psi_AxB_dimer_basis.size1();i++){\n        double mag=0.0;\n        for (unsigned j=0;j<_psi_AxB_dimer_basis.size2();j++){\n            mag+=_psi_AxB_dimer_basis(i,j)*_psi_AxB_dimer_basis(i,j);\n            \n    }\n        if (mag<0.95){\n\t  throw std::runtime_error(\"\\nERROR: Projection of monomer orbitals on dimer is insufficient, increase dimer basis.\\n\");\n        }\n    }\n \n     \n    // J = psi_AxB_dimer_basis * FAB * psi_AxB_dimer_basis^T\n    CTP_LOG(logDEBUG,*_pLog) << \"Projecting the Fock matrix onto the dimer basis\" << std::flush;   \n    ub::diagonal_matrix<double> _fock_AB( _orbitalsAB->getNumberOfLevels(), (*_orbitalsAB->getEnergies()).data() ); \n    ub::matrix<double> _temp = ub::prod( _fock_AB, ub::trans( _psi_AxB_dimer_basis ) ) ; \n    ub::matrix<double> JAB_dimer = ub::prod( _psi_AxB_dimer_basis, _temp);  \n \n    // S = psi_AxB_dimer_basis * psi_AxB_dimer_basis^T\n    CTP_LOG(logDEBUG,*_pLog) << \"Constructing Overlap matrix\" << std::flush;    \n    ub::symmetric_matrix<double> _S_AxB = ub::prod( _psi_AxB_dimer_basis, ub::trans( _psi_AxB_dimer_basis ));  \n    ub::matrix<double> _S_AxB_2(_S_AxB.size1(), _S_AxB.size1() );\n    ub::trans( _S_AxB );\n  \n    // Square root of the overlap matrix\n    CTP_LOG(logDEBUG,*_pLog) << \"Calculating square root of the overlap matrix\" << std::flush;    \n    SQRTOverlap( _S_AxB , _S_AxB_2 );\n \n     \n   CTP_LOG(logDEBUG,*_pLog) << \"Calculating the effective overlap JAB [\" \n              << JAB_dimer.size1() << \"x\" \n              << JAB_dimer.size2() << \"]\" << std::flush;  \n       \n    ub::matrix<double> JAB_temp( _levelsA + _levelsB, _levelsA + _levelsB ); \n    ub::noalias(JAB_temp) = ub::prod( JAB_dimer, _S_AxB_2 );  \n    (*_JAB) = ub::prod( _S_AxB_2, JAB_temp );    \n    \n    \n    CTP_LOG(logDEBUG,*_pLog) << \"Done with electronic couplings\" << std::flush;\n    return true;   \n\n}\n\n/**\n * \\brief evaluates electronic couplings  \n * \n * This is a different version with block matrices [slower]\n * \n * @param _orbitalsA molecular orbitals of molecule A\n * @param _orbitalsB molecular orbitals of molecule B\n * @param _orbitalsAB molecular orbitals of the dimer AB\n * @param _JAB matrix with electronic couplings\n * @return false if failed\n */\nbool Overlap::CalculateIntegralsOptimized(Orbitals* _orbitalsA, Orbitals* _orbitalsB, \n    Orbitals* _orbitalsAB, ub::matrix<double>* _JAB) {\n          \n    CTP_LOG(logDEBUG,*_pLog) << \"Calculating electronic couplings\" << std::flush;\n        \n    // constructing the direct product orbA x orbB\n    int _basisA = _orbitalsA->getBasisSetSize();\n    int _basisB = _orbitalsB->getBasisSetSize();\n    \n    if ( ( _basisA == 0 ) || ( _basisB == 0 ) ) {\n        CTP_LOG(logERROR,*_pLog) << \"Basis set size is not stored in monomers\" << std::flush;\n        return false;\n    }\n        \n    int _levelsA = _orbitalsA->getNumberOfLevels();\n    int _levelsB = _orbitalsB->getNumberOfLevels();\n    \n    boost::timer t; // start timing\n    double _st = t.elapsed();\n    \n    CTP_LOG(logDEBUG,*_pLog) << \"Levels:Basis A[\" << _levelsA << \":\" << _basisA << \"]\"\n                                     << \" B[\" << _levelsB << \":\" << _basisB << \"]\" << std::flush;\n    \n    if ( ( _levelsA == 0 ) || (_levelsB == 0) ) {\n        CTP_LOG(logERROR,*_pLog) << \"No information about number of occupied/unoccupied levels is stored\" << std::flush;\n        return false;\n    } \n     \n    // these flags should be set before any ublas header is called \n    // #define NDEBUG\n    // otherwise the code is very inefficient\n    \n    //       | Orbitals_A          0 |      | Overlap_A |     \n    //       | 0          Orbitals_B |  X   | Overlap_B |  X  Transpose( Orbitals_AB )\n    //constructing a slice of the Overlap matrix\n    ub::matrix_range< ub::symmetric_matrix<double> > Overlap_A = ub::project( *_orbitalsAB->getOverlap(), ub::range ( 0, _basisA), ub::range (0, _basisA +_basisB) );\n    ub::matrix_range< ub::symmetric_matrix<double> > Overlap_B = ub::project( *_orbitalsAB->getOverlap(), ub::range ( _basisA, _basisA +_basisB ), ub::range (0, _basisA +_basisB) );\n    \n    CTP_LOG(logDEBUG,*_pLog) << \"Projecting the monomer onto dimer orbitals [\" << _levelsA + _levelsB << \"x\" << _basisA + _basisB << \"]\";   \n    ub::matrix<double> _psi_AB ( _levelsA + _levelsB, _basisA + _basisB  );\n\n    ub::matrix_range< ub::matrix<double> > _psi_AB_A = ub::project( _psi_AB, ub::range (0, _levelsA ), ub::range ( 0, _basisA +_basisB ) ) ;\n    ub::noalias(_psi_AB_A) = ub::prod(*_orbitalsA->getOrbitals(), Overlap_A);\n\n    ub::matrix_range< ub::matrix<double> > _psi_AB_B = ub::project( _psi_AB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( 0, _basisA +_basisB ) ) ;\n    ub::noalias(_psi_AB_B) = ub::prod(*_orbitalsB->getOrbitals(), Overlap_B );\n    CTP_LOG(logDEBUG,*_pLog)  << \" (\" << t.elapsed() - _st << \"s) \" << std::flush; _st = t.elapsed();\n \n    ub::matrix<double> _psi_AxB_dimer_basis (_levelsA + _levelsB, _basisA + _basisB );\n    ub::matrix<double> OrbAB_Transp = ub::trans( *_orbitalsAB->getOrbitals() );\n    CTP_LOG(logDEBUG,*_pLog)  << \"Transposing OrbitalsAB (\" << t.elapsed() - _st << \"s)\" << \"\\x1b[0;39m\" << std::flush; _st = t.elapsed();\n    ub::noalias(_psi_AxB_dimer_basis) = ub::prod( _psi_AB,  OrbAB_Transp );\n  \n    CTP_LOG(logDEBUG,*_pLog)  << \"Multiplying PsiAB x OrbitalsAB (\" << t.elapsed() - _st << \"s)\" << \"\\x1b[0;39m\" << std::flush; _st = t.elapsed();\n    \n    _psi_AB.resize(0,0,false); OrbAB_Transp.resize(0,0,false);\n    \n    //   _psi_AxB_dimer_basis * F  * _psi_AxB_dimer_basis^T\n    CTP_LOG(logDEBUG,*_pLog) << \"Projecting the Fock matrix onto the dimer basis\";    \n    ub::zero_matrix<double> _zero ( _levelsA + _levelsB, _levelsA + _levelsB );\n    ub::matrix<double> JAB_dimer( _zero ) ;\n    ub::vector<double> energies = (*_orbitalsAB->getEnergies());\n\n    for ( int i1 = 0; i1 < _levelsA + _levelsB ; i1++ ) {\n    for ( int i2 = i1; i2 < _levelsA + _levelsB; i2++ ) {\n        for ( int k = 0; k < _basisA + _basisB; k++  ) {\n                JAB_dimer(i1,i2) += _psi_AxB_dimer_basis.at_element(i1, k) * _psi_AxB_dimer_basis.at_element(i2, k) * energies(k);\n        }\n        JAB_dimer(i2,i1) = JAB_dimer(i1,i2);\n    }}   \n    energies.clear();\n    CTP_LOG(logDEBUG,*_pLog)  << \" (\" << t.elapsed() - _st << \"s)\" << \"\\x1b[0;39m\" << std::flush; _st = t.elapsed();\n    \n    // S = psi_AxB_dimer_basis * psi_AxB_dimer_basis^T\n    ub::symmetric_matrix<double> _S_AxB = ub::prod( _psi_AxB_dimer_basis, ub::trans( _psi_AxB_dimer_basis ));\n    _psi_AxB_dimer_basis.resize(0,0,false);\n\n    ub::matrix<double> _S_AxB_2(_S_AxB.size1(), _S_AxB.size1() );\n    \n     ub::trans( _S_AxB );\n     CTP_LOG(logDEBUG,*_pLog) << \"Calculating square root of the overlap matrix [\" \n             << _S_AxB.size1() << \"x\" \n             << _S_AxB.size2() << \"]\";    \n     SQRTOverlap( _S_AxB , _S_AxB_2 );        \n     _S_AxB.resize(0,0,false); \n     CTP_LOG(logDEBUG,*_pLog)  << \" (\" << t.elapsed() - _st << \"s)\" << \"\\x1b[0;39m\" << std::flush; _st = t.elapsed();\n    \n    \n     CTP_LOG(logDEBUG,*_pLog) << \"Calculating the effective overlap JAB [\" \n             << JAB_dimer.size1() << \"x\" \n             << JAB_dimer.size2() << \"]\";    \n    \n    ub::matrix<double> JAB_temp( _levelsA + _levelsB, _levelsA + _levelsB );\n    \n    ub::noalias(JAB_temp) = ub::prod( JAB_dimer, _S_AxB_2 );\n    (*_JAB) = ub::prod( _S_AxB_2, JAB_temp );\n    \n    // cleanup\n    JAB_dimer.resize(0,0,false); JAB_temp.resize(0,0,false); _S_AxB_2.resize(0,0,false);\n    CTP_LOG(logDEBUG,*_pLog)  << \" (\" << t.elapsed() - _st << \"s)\" << \"\\x1b[0;39m\" << std::flush; _st = t.elapsed();\n    \n    CTP_LOG(logDEBUG,*_pLog) << \"Done with electronic couplings\" << std::flush;\n    return true;   \n};\n\n    \n}}\n", "meta": {"hexsha": "67b7049c97c789e3f4dffe978e3a155d5c38b2ee", "size": 17054, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libctp/overlap.cc", "max_stars_repo_name": "jimbach/ctp", "max_stars_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "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/libctp/overlap.cc", "max_issues_repo_name": "jimbach/ctp", "max_issues_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "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/libctp/overlap.cc", "max_forks_repo_name": "jimbach/ctp", "max_forks_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3856812933, "max_line_length": 181, "alphanum_fraction": 0.5863140612, "num_tokens": 5518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5051303073244915}}
{"text": "#include <boost/math/constants/constants.hpp>\n#include \"TypesFunctions.hh\"\n\n#include <TMath.h>\n\n#include \"ReactorNorm.hh\"\n\nconst double pi = boost::math::constants::pi<double>();\n\nReactorNormAbsolute::ReactorNormAbsolute(const std::vector<std::string> &isonames)\n{\n  variable_(&m_norm, \"Norm\");\n  auto norm = transformation_(\"isotopes\")\n    .types(TypesFunctions::ifSame, [](TypesFunctionArgs fargs) {\n        for (size_t i = 0; i < fargs.rets.size(); ++i) {\n          fargs.rets[i] = DataType().points().shape(1);\n        }\n      })\n    .func([](ReactorNormAbsolute *obj, FunctionArgs fargs) {\n        auto& args=fargs.args;\n        auto& rets=fargs.rets;\n        for (size_t i = 0; i < rets.size(); ++i) {\n          rets[i].x[0] = obj->m_norm*args[i].x.sum();\n        }\n      })\n  ;\n  for (const std::string &isoname: isonames) {\n    norm.input(\"fission_fraction_\"+isoname);\n    norm.output(\"norm_\"+isoname);\n  }\n}\n\nReactorNorm::ReactorNorm(const std::vector<std::string> &isonames)\n  : m_ePerFission(isonames.size())\n{\n  variable_(&m_thermalPower, \"ThermalPower\");\n  for (size_t i = 0; i < isonames.size(); ++i) {\n    variable_(&m_ePerFission[i], \"EnergyPerFission_\"+isonames[i]);\n  }\n  variable_(&m_targetProtons, \"TargetProtons\");\n  variable_(&m_L, \"L\");\n  auto norm = transformation_(\"isotopes\")\n    .types(TypesFunctions::ifSame, [](TypesFunctionArgs fargs) {\n        for (size_t i = 0; i < fargs.rets.size(); ++i) {\n          fargs.rets[i] = DataType().points().shape(1);\n        }\n      })\n    .func(&ReactorNorm::calcIsotopeNorms)\n  ;\n  for (const std::string &isoname: isonames) {\n    norm.input(\"fission_fraction_\"+isoname);\n    norm.output(\"norm_\"+isoname);\n  }\n  norm.input(\"livetime\");\n  norm.input(\"power_rate\");\n}\n\nvoid ReactorNorm::calcIsotopeNorms(FunctionArgs fargs) {\n  auto& args=fargs.args;\n  auto& rets=fargs.rets;\n  const auto &livetime = args[rets.size()+0].x;\n  const auto &power_rate = args[rets.size()+1].x;\n  static double conversionFactor = 1.0e-7/TMath::Qe();\n  auto distanceWeight = (conversionFactor / (4*pi*std::pow(m_L, 2)));\n  auto coeff = m_targetProtons*m_thermalPower*distanceWeight;\n\n  double ePerFission_avg=0.0;\n  for (size_t i = 0; i < rets.size(); ++i) {\n    ePerFission_avg+=args[i].x(0)*m_ePerFission[i].value();\n  }\n  for (size_t i = 0; i < rets.size(); ++i) {\n    rets[i].x[0] = (coeff*livetime*power_rate*args[i].x/ePerFission_avg).sum();\n  }\n}\n", "meta": {"hexsha": "960e0baf5f3dc9f08b8246c97abe413292b76f49", "size": 2395, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/neutrino/ReactorNorm.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/neutrino/ReactorNorm.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/neutrino/ReactorNorm.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.9333333333, "max_line_length": 82, "alphanum_fraction": 0.6400835073, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5050550190461556}}
{"text": "#pragma once\r\n\r\n#include <skynet/ublas.hpp>\r\n#include <skynet/utility/algorithm.hpp>\r\n\r\n#include <boost/numeric/ublas/symmetric.hpp>\r\n#include <boost/numeric/ublas/banded.hpp>\r\n\r\n#include <random>\r\n#include <type_traits>\r\n\r\nnamespace skynet{namespace nn{\r\n\r\n\ttemplate <typename T>\r\n\tclass cam{\r\n\tpublic:\r\n\t\tstatic_assert(std::is_integral<T>::value, \"The T should be integral.\");\r\n\r\n\t\ttypedef ublas::matrix<T>\t\t\t\t\tmatrix;\r\n\t\ttypedef ublas::symmetric_matrix<T>\t\t\tsymmetric_matrix;\r\n\t\ttypedef ublas::diagonal_matrix<T>\t\t\tdiagonal_matrix;\r\n\t\ttypedef ublas::vector<T>\t\t\t\t\tvector;\t\t\r\n\r\n\t\tcam(matrix input){\r\n\t\t\tauto size = input.size1();\r\n\t\t\t_W.resize(size);\r\n\t\t\t_W = ublas::prod(input, ublas::trans(input));\r\n\t\t\tdiagonal_matrix I(size);\r\n\t\t\tfor (size_t i = 0; i < size; ++i){\r\n\t\t\t\tI(i,i) = input.size2();\r\n\t\t\t}\r\n\r\n\t\t\t_W -= I;\t\t\r\n\r\n\t\t}\r\n\r\n\t\tsymmetric_matrix weights() const { return _W; }\r\n\r\n\t\ttemplate <typename VE>\r\n\t\tvector decode(const ublas::vector_expression<VE> &code){\r\n\t\t\tvector state(code().size());\r\n\t\t\tcopy(code(), state);\r\n\t\t\tstd::uniform_int_distribution<size_t> rand_index(0, _W.size2()-1);\r\n\t\t\tstd::mt19937\t\t\t\t\t\t  mt_index;\r\n\t\t\tmt_index.seed(unsigned long(std::time(nullptr)));\r\n\t\t\twhile(true){\r\n\t\t\t\tsize_t variation_count = 0;\r\n\t\t\t\tfor (size_t j = 0; j < (_W.size2()*5); ++j){\r\n\t\t\t\t\tauto index = rand_index(mt_index);\r\n\t\t\t\t\tauto weights = ublas::row(_W, index);\r\n\t\t\t\t\tauto re = ublas::inner_prod(weights, state);\r\n\t\t\t\t\tif (re == 0)\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\telse if (re > 0 && state[index] == -1){\r\n\t\t\t\t\t\tstate[index] = 1;\r\n\t\t\t\t\t\tvariation_count++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if(re < 0 && state[index] == 1){\r\n\t\t\t\t\t\tstate[index] = -1;\r\n\t\t\t\t\t\tvariation_count++;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (variation_count == 0)\r\n\t\t\t\t\treturn state;\t\t\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\tprivate:\r\n\t\tsymmetric_matrix\t\t_W;\r\n\t};\r\n\r\n\r\n\ttemplate <typename T>\r\n\tclass bam{\r\n\tpublic:\r\n\t\tstatic_assert(std::is_integral<T>::value, \"The T should be integral.\");\r\n\t\t\r\n\t\ttypedef ublas::matrix<T>\t\t\t\t\tmatrix;\r\n\t\ttypedef ublas::vector<T>\t\t\t\t\tvector;\r\n\r\n\t\tbam(matrix input, matrix output) \r\n\t\t\t: _W(input.size1(), output.size1()), _X(input.size1()), _Y(output.size1())\r\n\t\t{\r\n\t\t\t_W = ublas::prod(input, ublas::trans(output));\r\n\t\t}\r\n\r\n\t\ttemplate <typename E>\r\n\t\tvector operator()(const ublas::vector_expression<E> &ve) const{\r\n#ifdef\tENABLE_ASSERT\r\n\t\t\tfor (auto e : ve()){\r\n\t\t\t\tASSERT(e == -1 || e == 1, \"The input should be bipolar.\");\r\n\t\t\t}\r\n#endif\t\t\t\r\n\t\t\tvector pre_X = ve();\r\n\t\t\tvector pre_Y = ublas::inner_prod(pre_X, _W);\r\n\t\t\tbipolarize(pre_Y);\r\n\r\n\t\t\twhile(true){\r\n\t\t\t\tvector X = ublas::inner_prod(_W, pre_Y);\r\n\t\t\t\tbipolarize(X);\r\n\t\t\t\tvector Y = ublas::inner_prod(X, _W);\r\n\t\t\t\tbipolarize(Y);\r\n\r\n\t\t\t\t//TODO: the check is expensive.\r\n\t\t\t\tif (ublas::norm_1(X-pre_X) == 0 && ublas::norm1(Y-pre_Y) == 0)\r\n\t\t\t\t\treturn X;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tmatrix\t\t\t_W;\r\n\t};\r\n\r\n}}\r\n", "meta": {"hexsha": "fb304a870c0368d05006b0acd0e9c98d13acaed1", "size": 2820, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "skynet/neuralnetworks/memory.hpp", "max_stars_repo_name": "zhangzhimin/skynet", "max_stars_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-08-02T03:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-16T01:07:55.000Z", "max_issues_repo_path": "skynet/neuralnetworks/memory.hpp", "max_issues_repo_name": "zhangzhimin/skynet", "max_issues_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skynet/neuralnetworks/memory.hpp", "max_forks_repo_name": "zhangzhimin/skynet", "max_forks_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_forks_repo_licenses": ["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.1025641026, "max_line_length": 78, "alphanum_fraction": 0.5939716312, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5050550190461556}}
{"text": "#ifndef BART_SRC_CALCULATOR_TWO_GRID_SPECTRAL_SHAPE_I_HPP_\n#define BART_SRC_CALCULATOR_TWO_GRID_SPECTRAL_SHAPE_I_HPP_\n\n#include <deal.II/lac/full_matrix.h>\n\n#include \"utility/has_description.h\"\n\n//! Classes for calculating the two-grid spectral shape function\nnamespace bart::acceleration::two_grid::spectral_shape {\n\n/*! \\brief Interface for classes that calculate the spectral shape function for the two-grid acceleration method.\n *\n * The spectral shape function is defined for the two-grid method of <a href=\"https://doi.org/10.13182/NSE115-253\">Adams and Morel (2017)</a>.\n * This function must be calculated in each homogenous material region, and is calculated by solving\n * for the eigenvector \\f$\\xi \\in \\mathbb{R}^{(G \\times 1)}\\f$ in the following equation:\n * \\f[\n * \\left(\\bf{T} - \\bf{S}_{D0}\\right)^{-1}\\bf{S}_{U0}\\vec{\\xi} = \\rho\\vec{\\xi}\\;,\n * \\f]\n * where \\f$\\bf{T}\\f$ is the total cross-section matrix, \\f$\\bf{S}_{D0}\\f$ is the isotropic downscatter matrix,\n * \\f$\\bf{S}_{U0}\\f$ is the isotropic upscatter matrix, and \\f$\\rho\\f$ is the spectral radius. The spectral shape\n * function is normalized such that\n * \\f[\n * \\sum_{g = 0}^{G - 1}\\xi_g = 1\\;.\n * \\f]\n *\n */\nclass SpectralShapeI : public utility::HasDescription {\n public:\n  using DealiiMatrix = dealii::FullMatrix<double>;\n  virtual ~SpectralShapeI() = default;\n  /*! \\brief Calculate the spectral shape.\n   *\n   * @param sigma_t total cross-section matrix.\n   * @param sigma_s full scattering matrix.\n   * @return spectral shape function\n   */\n  virtual auto CalculateSpectralShape(const DealiiMatrix& sigma_t,\n                                      const DealiiMatrix& sigma_s) -> std::vector<double> = 0;\n};\n\n} // namespace bart::acceleration::two_grid::spectral_shape\n\n#endif //BART_SRC_CALCULATOR_TWO_GRID_SPECTRAL_SHAPE_I_HPP_\n", "meta": {"hexsha": "b12ef79652b3afbad4bfa6e4b87714939cdd83d1", "size": 1808, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/acceleration/two_grid/spectral_shape/spectral_shape_i.hpp", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/acceleration/two_grid/spectral_shape/spectral_shape_i.hpp", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/acceleration/two_grid/spectral_shape/spectral_shape_i.hpp", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 41.0909090909, "max_line_length": 142, "alphanum_fraction": 0.7123893805, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757312, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5050550165045523}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2010 - 2020 by the deal.II authors and \n *                              & Jean-Paul Pelteret and Andrew McBride \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 * Authors: Jean-Paul Pelteret, University of Cape Town, \n *          Andrew McBride, University of Erlangen-Nuremberg, 2010 \n */ \n\n\n\n// \u6211\u4eec\u9996\u5148\u5305\u62ec\u6240\u6709\u5fc5\u8981\u7684deal.II\u5934\u6587\u4ef6\u548c\u4e00\u4e9bC++\u76f8\u5173\u7684\u6587\u4ef6\u3002\u5b83\u4eec\u5df2\u7ecf\u5728\u4ee5\u524d\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u8be6\u7ec6\u8ba8\u8bba\u8fc7\u4e86\uff0c\u6240\u4ee5\u4f60\u53ea\u9700\u8981\u53c2\u8003\u8fc7\u53bb\u7684\u6559\u7a0b\u5c31\u53ef\u4ee5\u4e86\u3002\n\n#include <deal.II/base/function.h> \n#include <deal.II/base/parameter_handler.h> \n#include <deal.II/base/point.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/symmetric_tensor.h> \n#include <deal.II/base/tensor.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/base/work_stream.h> \n#include <deal.II/dofs/dof_renumbering.h> \n#include <deal.II/dofs/dof_tools.h> \n\n// \u8fd9\u4e2a\u6807\u5934\u4e3a\u6211\u4eec\u63d0\u4f9b\u4e86\u5728\u6b63\u4ea4\u70b9\u5b58\u50a8\u6570\u636e\u7684\u529f\u80fd\n\n#include <deal.II/base/quadrature_point_data.h> \n\n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_tools.h> \n#include <deal.II/grid/grid_in.h> \n#include <deal.II/grid/tria.h> \n\n#include <deal.II/fe/fe_dgp_monomial.h> \n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/fe_tools.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/fe/mapping_q_eulerian.h> \n\n#include <deal.II/lac/block_sparse_matrix.h> \n#include <deal.II/lac/block_vector.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/precondition_selector.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/solver_selector.h> \n#include <deal.II/lac/sparse_direct.h> \n#include <deal.II/lac/affine_constraints.h> \n\n// \u8fd9\u91cc\u662f\u4f7f\u7528LinearOperator\u7c7b\u6240\u9700\u7684\u5934\u6587\u4ef6\u3002\u8fd9\u4e9b\u5934\u6587\u4ef6\u4e5f\u90fd\u88ab\u65b9\u4fbf\u5730\u6253\u5305\u5230\u4e00\u4e2a\u5934\u6587\u4ef6\u4e2d\uff0c\u5373<deal.II/lac/linear_operator_tools.h>\uff0c\u4f46\u4e3a\u4e86\u900f\u660e\u8d77\u89c1\uff0c\u6211\u4eec\u5728\u6b64\u5217\u51fa\u90a3\u4e9b\u7279\u522b\u9700\u8981\u7684\u5934\u6587\u4ef6\u3002\n\n#include <deal.II/lac/linear_operator.h> \n#include <deal.II/lac/packaged_operation.h> \n\n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/vector_tools.h> \n\n// \u5728\u8fd9\u4e24\u4e2a\u6807\u9898\u4e2d\u5b9a\u4e49\u7684\u662f\u4e00\u4e9b\u4e0e\u6709\u9650\u5e94\u53d8\u5f39\u6027\u6709\u5173\u7684\u64cd\u4f5c\u3002\u7b2c\u4e00\u4e2a\u5c06\u5e2e\u52a9\u6211\u4eec\u8ba1\u7b97\u4e00\u4e9b\u8fd0\u52a8\u91cf\uff0c\u7b2c\u4e8c\u4e2a\u63d0\u4f9b\u4e00\u4e9b\u6807\u51c6\u7684\u5f20\u91cf\u5b9a\u4e49\u3002\n\n#include <deal.II/physics/elasticity/kinematics.h> \n#include <deal.II/physics/elasticity/standard_tensors.h> \n\n#include <iostream> \n#include <fstream> \n\n// \u7136\u540e\uff0c\u6211\u4eec\u5c06\u6240\u6709\u4e0e\u672c\u6559\u7a0b\u7a0b\u5e8f\u6709\u5173\u7684\u4e1c\u897f\u90fd\u653e\u5165\u4e00\u4e2a\u81ea\u5df1\u7684\u547d\u540d\u7a7a\u95f4\uff0c\u5e76\u5c06\u6240\u6709deal.II\u7684\u51fd\u6570\u548c\u7c7b\u540d\u5bfc\u5165\u5176\u4e2d\u3002\n\nnamespace Step44 \n{ \n  using namespace dealii; \n// @sect3{Run-time parameters}  \n\n// \u6709\u51e0\u4e2a\u53c2\u6570\u53ef\u4ee5\u5728\u4ee3\u7801\u4e2d\u8bbe\u7f6e\uff0c\u6240\u4ee5\u6211\u4eec\u8bbe\u7f6e\u4e86\u4e00\u4e2aParameterHandler\u5bf9\u8c61\uff0c\u5728\u8fd0\u884c\u65f6\u8bfb\u5165\u9009\u62e9\u3002\n\n  namespace Parameters \n  { \n// @sect4{Finite Element system}  \n\n// \u6b63\u5982\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\uff0c\u5bf9\u4e8e\u4f4d\u79fb $\\mathbf{u}$ \u5e94\u8be5\u4f7f\u7528\u4e0d\u540c\u7684\u9636\u6b21\u63d2\u503c\uff0c\u800c\u4e0d\u662f\u538b\u529b $\\widetilde{p}$ \u548c\u81a8\u80c0 $\\widetilde{J}$ \u3002 \u9009\u62e9 $\\widetilde{p}$ \u548c $\\widetilde{J}$ \u4f5c\u4e3a\u5143\u7d20\u7ea7\u7684\u4e0d\u8fde\u7eed\uff08\u5e38\u6570\uff09\u51fd\u6570\uff0c\u5bfc\u81f4\u4e86\u5e73\u5747\u6269\u5f20\u65b9\u6cd5\u3002\u4e0d\u8fde\u7eed\u7684\u8fd1\u4f3c\u5141\u8bb8 $\\widetilde{p}$ \u548c $\\widetilde{J}$ \u88ab\u6d53\u7f29\u51fa\u6765\uff0c\u5e76\u6062\u590d\u4e86\u57fa\u4e8e\u4f4d\u79fb\u7684\u7ecf\u5178\u65b9\u6cd5\u3002\u8fd9\u91cc\u6211\u4eec\u6307\u5b9a\u7528\u4e8e\u8fd1\u4f3c\u89e3\u7684\u591a\u9879\u5f0f\u9636\u6570\u3002\u6b63\u4ea4\u9636\u6570\u5e94\u4f5c\u76f8\u5e94\u8c03\u6574\u3002\n\n    struct FESystem \n    { \n      unsigned int poly_degree; \n      unsigned int quad_order; \n\n      static void declare_parameters(ParameterHandler &prm); \n\n      void parse_parameters(ParameterHandler &prm); \n    }; \n\n    void FESystem::declare_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"Finite element system\"); \n      { \n        prm.declare_entry(\"Polynomial degree\", \n                          \"2\", \n                          Patterns::Integer(0), \n                          \"Displacement system polynomial order\"); \n\n        prm.declare_entry(\"Quadrature order\", \n                          \"3\", \n                          Patterns::Integer(0), \n                          \"Gauss quadrature order\"); \n      } \n      prm.leave_subsection(); \n    } \n\n    void FESystem::parse_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"Finite element system\"); \n      { \n        poly_degree = prm.get_integer(\"Polynomial degree\"); \n        quad_order  = prm.get_integer(\"Quadrature order\"); \n      } \n      prm.leave_subsection(); \n    } \n// @sect4{Geometry}  \n\n// \u5bf9\u95ee\u9898\u7684\u51e0\u4f55\u5f62\u72b6\u548c\u5e94\u7528\u7684\u8f7d\u8377\u8fdb\u884c\u8c03\u6574\u3002 \u7531\u4e8e\u8fd9\u91cc\u6a21\u62df\u7684\u95ee\u9898\u6bd4\u8f83\u7279\u6b8a\uff0c\u6240\u4ee5\u53ef\u4ee5\u5c06\u8f7d\u8377\u6bd4\u4f8b\u6539\u53d8\u4e3a\u7279\u5b9a\u7684\u6570\u503c\uff0c\u4ee5\u4fbf\u4e0e\u6587\u732e\u4e2d\u7ed9\u51fa\u7684\u7ed3\u679c\u8fdb\u884c\u6bd4\u8f83\u3002\n\n    struct Geometry \n    { \n      unsigned int global_refinement; \n      double       scale; \n      double       p_p0; \n\n      static void declare_parameters(ParameterHandler &prm); \n\n      void parse_parameters(ParameterHandler &prm); \n    }; \n\n    void Geometry::declare_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"Geometry\"); \n      { \n        prm.declare_entry(\"Global refinement\", \n                          \"2\", \n                          Patterns::Integer(0), \n                          \"Global refinement level\"); \n\n        prm.declare_entry(\"Grid scale\", \n                          \"1e-3\", \n                          Patterns::Double(0.0), \n                          \"Global grid scaling factor\"); \n\n        prm.declare_entry(\"Pressure ratio p/p0\", \n                          \"100\", \n                          Patterns::Selection(\"20|40|60|80|100\"), \n                          \"Ratio of applied pressure to reference pressure\"); \n      } \n      prm.leave_subsection(); \n    } \n\n    void Geometry::parse_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"Geometry\"); \n      { \n        global_refinement = prm.get_integer(\"Global refinement\"); \n        scale             = prm.get_double(\"Grid scale\"); \n        p_p0              = prm.get_double(\"Pressure ratio p/p0\"); \n      } \n      prm.leave_subsection(); \n    } \n// @sect4{Materials}  \n\n// \u6211\u4eec\u8fd8\u9700\u8981\u65b0\u80e1\u514b\u6750\u6599\u7684\u526a\u5207\u6a21\u91cf $ \\mu $ \u548c\u6cca\u677e\u7387 $ \\nu $ \u3002\n\n    struct Materials \n    { \n      double nu; \n      double mu; \n\n      static void declare_parameters(ParameterHandler &prm); \n\n      void parse_parameters(ParameterHandler &prm); \n    }; \n\n    void Materials::declare_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"Material properties\"); \n      { \n        prm.declare_entry(\"Poisson's ratio\", \n                          \"0.4999\", \n                          Patterns::Double(-1.0, 0.5), \n                          \"Poisson's ratio\"); \n\n        prm.declare_entry(\"Shear modulus\", \n                          \"80.194e6\", \n                          Patterns::Double(), \n                          \"Shear modulus\"); \n      } \n      prm.leave_subsection(); \n    } \n\n    void Materials::parse_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"Material properties\"); \n      { \n        nu = prm.get_double(\"Poisson's ratio\"); \n        mu = prm.get_double(\"Shear modulus\"); \n      } \n      prm.leave_subsection(); \n    } \n// @sect4{Linear solver}  \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u9009\u62e9\u6c42\u89e3\u5668\u548c\u9884\u5904\u7406\u5668\u7684\u8bbe\u7f6e\u3002 \u5f53\u725b\u987f\u589e\u91cf\u4e2d\u51fa\u73b0\u5927\u7684\u975e\u7ebf\u6027\u8fd0\u52a8\u65f6\uff0c\u4f7f\u7528\u6709\u6548\u7684\u524d\u7f6e\u6761\u4ef6\u5bf9\u4e8e\u786e\u4fdd\u6536\u655b\u6027\u81f3\u5173\u91cd\u8981\u3002\n\n    struct LinearSolver \n    { \n      std::string type_lin; \n      double      tol_lin; \n      double      max_iterations_lin; \n      bool        use_static_condensation; \n      std::string preconditioner_type; \n      double      preconditioner_relaxation; \n\n      static void declare_parameters(ParameterHandler &prm); \n\n      void parse_parameters(ParameterHandler &prm); \n    }; \n\n    void LinearSolver::declare_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"Linear solver\"); \n      { \n        prm.declare_entry(\"Solver type\", \n                          \"CG\", \n                          Patterns::Selection(\"CG|Direct\"), \n                          \"Type of solver used to solve the linear system\"); \n\n        prm.declare_entry(\"Residual\", \n                          \"1e-6\", \n                          Patterns::Double(0.0), \n                          \"Linear solver residual (scaled by residual norm)\"); \n\n        prm.declare_entry( \n          \"Max iteration multiplier\", \n          \"1\", \n          Patterns::Double(0.0), \n          \"Linear solver iterations (multiples of the system matrix size)\"); \n\n        prm.declare_entry(\"Use static condensation\", \n                          \"true\", \n                          Patterns::Bool(), \n                          \"Solve the full block system or a reduced problem\"); \n\n        prm.declare_entry(\"Preconditioner type\", \n                          \"ssor\", \n                          Patterns::Selection(\"jacobi|ssor\"), \n                          \"Type of preconditioner\"); \n\n        prm.declare_entry(\"Preconditioner relaxation\", \n                          \"0.65\", \n                          Patterns::Double(0.0), \n                          \"Preconditioner relaxation value\"); \n      } \n      prm.leave_subsection(); \n    } \n\n    void LinearSolver::parse_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"Linear solver\"); \n      { \n        type_lin                  = prm.get(\"Solver type\"); \n        tol_lin                   = prm.get_double(\"Residual\"); \n        max_iterations_lin        = prm.get_double(\"Max iteration multiplier\"); \n        use_static_condensation   = prm.get_bool(\"Use static condensation\"); \n        preconditioner_type       = prm.get(\"Preconditioner type\"); \n        preconditioner_relaxation = prm.get_double(\"Preconditioner relaxation\"); \n      } \n      prm.leave_subsection(); \n    } \n// @sect4{Nonlinear solver}  \n\n// \u91c7\u7528\u725b\u987f-\u62c9\u5f17\u68ee\u65b9\u6848\u6765\u89e3\u51b3\u975e\u7ebf\u6027\u6cbb\u7406\u65b9\u7a0b\u7ec4\u3002 \u6211\u4eec\u73b0\u5728\u5b9a\u4e49\u725b\u987f-\u62c9\u5f17\u68ee\u975e\u7ebf\u6027\u6c42\u89e3\u5668\u7684\u516c\u5dee\u548c\u6700\u5927\u8fed\u4ee3\u6b21\u6570\u3002\n\n    struct NonlinearSolver \n    { \n      unsigned int max_iterations_NR; \n      double       tol_f; \n      double       tol_u; \n\n      static void declare_parameters(ParameterHandler &prm); \n\n      void parse_parameters(ParameterHandler &prm); \n    }; \n\n    void NonlinearSolver::declare_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"Nonlinear solver\"); \n      { \n        prm.declare_entry(\"Max iterations Newton-Raphson\", \n                          \"10\", \n                          Patterns::Integer(0), \n                          \"Number of Newton-Raphson iterations allowed\"); \n\n        prm.declare_entry(\"Tolerance force\", \n                          \"1.0e-9\", \n                          Patterns::Double(0.0), \n                          \"Force residual tolerance\"); \n\n        prm.declare_entry(\"Tolerance displacement\", \n                          \"1.0e-6\", \n                          Patterns::Double(0.0), \n                          \"Displacement error tolerance\"); \n      } \n      prm.leave_subsection(); \n    } \n\n    void NonlinearSolver::parse_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"Nonlinear solver\"); \n      { \n        max_iterations_NR = prm.get_integer(\"Max iterations Newton-Raphson\"); \n        tol_f             = prm.get_double(\"Tolerance force\"); \n        tol_u             = prm.get_double(\"Tolerance displacement\"); \n      } \n      prm.leave_subsection(); \n    } \n// @sect4{Time}  \n\n// \u8bbe\u7f6e\u65f6\u95f4\u6b65\u957f $ \\varDelta t $ \u548c\u6a21\u62df\u7ed3\u675f\u65f6\u95f4\u3002\n\n    struct Time \n    { \n      double delta_t; \n      double end_time; \n\n      static void declare_parameters(ParameterHandler &prm); \n\n      void parse_parameters(ParameterHandler &prm); \n    }; \n\n    void Time::declare_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"Time\"); \n      { \n        prm.declare_entry(\"End time\", \"1\", Patterns::Double(), \"End time\"); \n\n        prm.declare_entry(\"Time step size\", \n                          \"0.1\", \n                          Patterns::Double(), \n                          \"Time step size\"); \n      } \n      prm.leave_subsection(); \n    } \n\n    void Time::parse_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"Time\"); \n      { \n        end_time = prm.get_double(\"End time\"); \n        delta_t  = prm.get_double(\"Time step size\"); \n      } \n      prm.leave_subsection(); \n    } \n// @sect4{All parameters}  \n\n// \u6700\u540e\uff0c\u6211\u4eec\u5c06\u4e0a\u8ff0\u6240\u6709\u7684\u7ed3\u6784\u5408\u5e76\u5230\u4e00\u4e2a\u5bb9\u5668\u4e2d\uff0c\u8fd9\u4e2a\u5bb9\u5668\u53ef\u4ee5\u5bb9\u7eb3\u6211\u4eec\u6240\u6709\u7684\u8fd0\u884c\u65f6\u9009\u62e9\u3002\n\n    struct AllParameters : public FESystem, \n                           public Geometry, \n                           public Materials, \n                           public LinearSolver, \n                           public NonlinearSolver, \n                           public Time \n\n    { \n      AllParameters(const std::string &input_file); \n\n      static void declare_parameters(ParameterHandler &prm); \n\n      void parse_parameters(ParameterHandler &prm); \n    }; \n\n    AllParameters::AllParameters(const std::string &input_file) \n    { \n      ParameterHandler prm; \n      declare_parameters(prm); \n      prm.parse_input(input_file); \n      parse_parameters(prm); \n    } \n\n    void AllParameters::declare_parameters(ParameterHandler &prm) \n    { \n      FESystem::declare_parameters(prm); \n      Geometry::declare_parameters(prm); \n      Materials::declare_parameters(prm); \n      LinearSolver::declare_parameters(prm); \n      NonlinearSolver::declare_parameters(prm); \n      Time::declare_parameters(prm); \n    } \n\n    void AllParameters::parse_parameters(ParameterHandler &prm) \n    { \n      FESystem::parse_parameters(prm); \n      Geometry::parse_parameters(prm); \n      Materials::parse_parameters(prm); \n      LinearSolver::parse_parameters(prm); \n      NonlinearSolver::parse_parameters(prm); \n      Time::parse_parameters(prm); \n    } \n  } // namespace Parameters \n// @sect3{Time class}  \n\n// \u4e00\u4e2a\u7b80\u5355\u7684\u7c7b\u6765\u5b58\u50a8\u65f6\u95f4\u6570\u636e\u3002\u5b83\u7684\u529f\u80fd\u662f\u900f\u660e\u7684\uff0c\u6240\u4ee5\u6ca1\u6709\u5fc5\u8981\u8ba8\u8bba\u3002\u4e3a\u4e86\u7b80\u5355\u8d77\u89c1\uff0c\u6211\u4eec\u5047\u8bbe\u4e00\u4e2a\u6052\u5b9a\u7684\u65f6\u95f4\u6b65\u957f\u3002\n\n  class Time \n  { \n  public: \n    Time(const double time_end, const double delta_t) \n      : timestep(0) \n      , time_current(0.0) \n      , time_end(time_end) \n      , delta_t(delta_t) \n    {} \n\n    virtual ~Time() = default; \n\n    double current() const \n    { \n      return time_current; \n    } \n    double end() const \n    { \n      return time_end; \n    } \n    double get_delta_t() const \n    { \n      return delta_t; \n    } \n    unsigned int get_timestep() const \n    { \n      return timestep; \n    } \n    void increment() \n    { \n      time_current += delta_t; \n      ++timestep; \n    } \n\n  private: \n    unsigned int timestep; \n    double       time_current; \n    const double time_end; \n    const double delta_t; \n  }; \n// @sect3{Compressible neo-Hookean material within a three-field formulation}  \n\n// \u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u65b0\u80e1\u514b\u6750\u6599\u662f\u4e00\u79cd\u8d85\u5f39\u6027\u6750\u6599\u3002 \u6574\u4e2a\u9886\u57df\u88ab\u5047\u5b9a\u4e3a\u7531\u53ef\u538b\u7f29\u7684\u65b0\u80e1\u514b\u6750\u6599\u7ec4\u6210\u3002 \u8fd9\u4e2a\u7c7b\u522b\u5b9a\u4e49\u4e86\u8fd9\u79cd\u6750\u6599\u5728\u4e09\u573a\u516c\u5f0f\u4e2d\u7684\u884c\u4e3a\u3002 \u53ef\u538b\u7f29\u7684\u65b0\u80e1\u514b\u6750\u6599\u53ef\u4ee5\u7528\u5e94\u53d8\u80fd\u91cf\u51fd\u6570\uff08SEF\uff09\u6765\u63cf\u8ff0  $ \\Psi = \\Psi_{\\text{iso}}(\\overline{\\mathbf{b}}) + \\Psi_{\\text{vol}}(\\widetilde{J})$ \n\n// \u7b49\u6548\u54cd\u5e94\u7531 $ \\Psi_{\\text{iso}}(\\overline{\\mathbf{b}}) = c_{1} [\\overline{I}_{1} - 3] $ \u7ed9\u51fa\uff0c\u5176\u4e2d $ c_{1} = \\frac{\\mu}{2} $ \u548c $\\overline{I}_{1}$ \u662f\u5de6\u6216\u53f3\u7b49\u6548Cauchy-Green\u53d8\u5f62\u5f20\u91cf\u7684\u7b2c\u4e00\u4e0d\u53d8\u91cf\u3002\u8fd9\u5c31\u662f $\\overline{I}_1 \\dealcoloneq \\textrm{tr}(\\overline{\\mathbf{b}})$  \u3002\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u652f\u914d\u4f53\u79ef\u54cd\u5e94\u7684SEF\u88ab\u5b9a\u4e49\u4e3a $ \\Psi_{\\text{vol}}(\\widetilde{J}) = \\kappa \\frac{1}{4} [ \\widetilde{J}^2 - 1 - 2\\textrm{ln}\\; \\widetilde{J} ]$  \uff0c\u5176\u4e2d $\\kappa \\dealcoloneq \\lambda + 2/3 \\mu$  \u662f<a href=\"http:en.wikipedia.org/wiki/Bulk_modulus\">bulk modulus</a>\uff0c $\\lambda$ \u662f<a href=\"http:en.wikipedia.org/wiki/Lam%C3%A9_parameters\">Lam&eacute;'s first parameter</a>\u3002\n\n// \u4e0b\u9762\u7684\u7c7b\u5c06\u88ab\u7528\u6765\u63cf\u8ff0\u6211\u4eec\u5de5\u4f5c\u4e2d\u7684\u6750\u6599\u7279\u5f81\uff0c\u5e76\u63d0\u4f9b\u4e86\u4e00\u4e2a\u4e2d\u5fc3\u70b9\uff0c\u5982\u679c\u8981\u5b9e\u73b0\u4e0d\u540c\u7684\u6750\u6599\u6a21\u578b\uff0c\u5c31\u9700\u8981\u5bf9\u5176\u8fdb\u884c\u4fee\u6539\u3002\u4e3a\u4e86\u4f7f\u5176\u53d1\u6325\u4f5c\u7528\uff0c\u6211\u4eec\u5c06\u5728\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u5b58\u50a8\u4e00\u4e2a\u8fd9\u79cd\u7c7b\u578b\u7684\u5bf9\u8c61\uff0c\u5e76\u5728\u6bcf\u4e2a\u5bf9\u8c61\u4e2d\u5b58\u50a8\u5f53\u524d\u72b6\u6001\uff08\u7531\u4e09\u4e2a\u573a\u7684\u503c\u6216\u5ea6\u91cf\u6765\u8868\u5f81\uff09\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u56f4\u7ed5\u5f53\u524d\u72b6\u6001\u8ba1\u7b97\u51fa\u7ebf\u6027\u5316\u7684\u5f39\u6027\u7cfb\u6570\u3002\n\n  template <int dim> \n  class Material_Compressible_Neo_Hook_Three_Field \n  { \n  public: \n    Material_Compressible_Neo_Hook_Three_Field(const double mu, const double nu) \n      : kappa((2.0 * mu * (1.0 + nu)) / (3.0 * (1.0 - 2.0 * nu))) \n      , c_1(mu / 2.0) \n      , det_F(1.0) \n      , p_tilde(0.0) \n      , J_tilde(1.0) \n      , b_bar(Physics::Elasticity::StandardTensors<dim>::I) \n    { \n      Assert(kappa > 0, ExcInternalError()); \n    } \n\n// \u6211\u4eec\u7528\u57fa\u4e8e  $F$  \u548c\u538b\u529b  $\\widetilde{p}$  \u4ee5\u53ca\u81a8\u80c0  $\\widetilde{J}$  \u7684\u5404\u79cd\u53d8\u5f62\u76f8\u5173\u6570\u636e\u6765\u66f4\u65b0\u6750\u6599\u6a21\u578b\uff0c\u5e76\u5728\u51fd\u6570\u7684\u6700\u540e\u5305\u62ec\u4e00\u4e2a\u5185\u90e8\u4e00\u81f4\u6027\u7684\u7269\u7406\u68c0\u67e5\u3002\n\n    void update_material_data(const Tensor<2, dim> &F, \n                              const double          p_tilde_in, \n                              const double          J_tilde_in) \n    { \n      det_F                      = determinant(F); \n      const Tensor<2, dim> F_bar = Physics::Elasticity::Kinematics::F_iso(F); \n      b_bar                      = Physics::Elasticity::Kinematics::b(F_bar); \n      p_tilde                    = p_tilde_in; \n      J_tilde                    = J_tilde_in; \n\n      Assert(det_F > 0, ExcInternalError()); \n    } \n\n// \u7b2c\u4e8c\u4e2a\u51fd\u6570\u51b3\u5b9a\u4e86\u57fa\u5c14\u970d\u592b\u5e94\u529b  $\\boldsymbol{\\tau} = \\boldsymbol{\\tau}_{\\textrm{iso}} + \\boldsymbol{\\tau}_{\\textrm{vol}}$  \u3002\n    SymmetricTensor<2, dim> get_tau() \n    { \n      return get_tau_iso() + get_tau_vol(); \n    } \n\n// \u7a7a\u95f4\u8bbe\u7f6e\u4e2d\u7684\u56db\u9636\u5f39\u6027\u5f20\u91cf $\\mathfrak{c}$ \u7531SEF $\\Psi$ \u8ba1\u7b97\u4e3a $ J \\mathfrak{c}_{ijkl} = F_{iA} F_{jB} \\mathfrak{C}_{ABCD} F_{kC} F_{lD}$  \u5176\u4e2d $ \\mathfrak{C} = 4 \\frac{\\partial^2 \\Psi(\\mathbf{C})}{\\partial \\mathbf{C} \\partial \\mathbf{C}}$  \n    SymmetricTensor<4, dim> get_Jc() const \n    { \n      return get_Jc_vol() + get_Jc_iso(); \n    } \n\n// \u4f53\u79ef\u81ea\u7531\u80fd\u76f8\u5bf9\u4e8e  $\\widetilde{J}$  \u7684\u5bfc\u6570\uff0c\u8fd4\u56de  $\\frac{\\partial \\Psi_{\\text{vol}}(\\widetilde{J})}{\\partial \\widetilde{J}}$  \u3002\n    double get_dPsi_vol_dJ() const \n    { \n      return (kappa / 2.0) * (J_tilde - 1.0 / J_tilde); \n    } \n\n// \u4f53\u79ef\u81ea\u7531\u80fd\u7684\u4e8c\u6b21\u5bfc\u6570\uff0c\u76f8\u5bf9\u4e8e  $\\widetilde{J}$  \u3002\u6211\u4eec\u9700\u8981\u5728\u5207\u7ebf\u4e2d\u660e\u786e\u5730\u8fdb\u884c\u4ee5\u4e0b\u8ba1\u7b97\uff0c\u6240\u4ee5\u6211\u4eec\u5c06\u5176\u516c\u5f00\u3002 \u6211\u4eec\u8ba1\u7b97\u51fa  $\\frac{\\partial^2 \\Psi_{\\textrm{vol}}(\\widetilde{J})}{\\partial \\widetilde{J} \\partial \\widetilde{J}}$  \u3002\n    double get_d2Psi_vol_dJ2() const \n    { \n      return ((kappa / 2.0) * (1.0 + 1.0 / (J_tilde * J_tilde))); \n    } \n\n// \u63a5\u4e0b\u6765\u7684\u51e0\u4e2a\u51fd\u6570\u4f1a\u8fd4\u56de\u5404\u79cd\u6570\u636e\uff0c\u6211\u4eec\u9009\u62e9\u5c06\u5176\u4e0e\u6750\u6599\u4e00\u8d77\u5b58\u50a8\u3002\n\n    double get_det_F() const \n    { \n      return det_F; \n    } \n\n    double get_p_tilde() const \n    { \n      return p_tilde; \n    } \n\n    double get_J_tilde() const \n    { \n      return J_tilde; \n    } \n\n  protected: \n\n// \u5b9a\u4e49\u6784\u6210\u6a21\u578b\u53c2\u6570  $\\kappa$  \uff08\u4f53\u79ef\u6a21\u91cf\uff09\u548c\u65b0\u80e1\u514b\u6a21\u578b\u53c2\u6570  $c_1$  \u3002\n\n    const double kappa; \n    const double c_1; \n\n// \u6a21\u578b\u7684\u5177\u4f53\u6570\u636e\uff0c\u65b9\u4fbf\u4e0e\u6750\u6599\u4e00\u8d77\u5b58\u50a8\u3002\n\n    double                  det_F; \n    double                  p_tilde; \n    double                  J_tilde; \n    SymmetricTensor<2, dim> b_bar; \n\n// \u4ee5\u4e0b\u51fd\u6570\u5728\u5185\u90e8\u7528\u4e8e\u786e\u5b9a\u4e0a\u8ff0\u4e00\u4e9b\u516c\u5171\u51fd\u6570\u7684\u7ed3\u679c\u3002\u7b2c\u4e00\u4e2a\u51fd\u6570\u51b3\u5b9a\u4e86\u4f53\u79ef\u57fa\u5c14\u970d\u592b\u5e94\u529b  $\\boldsymbol{\\tau}_{\\textrm{vol}}$  \u3002\n\n    SymmetricTensor<2, dim> get_tau_vol() const \n    { \n      return p_tilde * det_F * Physics::Elasticity::StandardTensors<dim>::I; \n    } \n\n// \u63a5\u4e0b\u6765\uff0c\u786e\u5b9a\u7b49\u6548\u57fa\u5c14\u970d\u592b\u5e94\u529b  $\\boldsymbol{\\tau}_{\\textrm{iso}} = \\mathcal{P}:\\overline{\\boldsymbol{\\tau}}$  \u3002\n\n    SymmetricTensor<2, dim> get_tau_iso() const \n    { \n      return Physics::Elasticity::StandardTensors<dim>::dev_P * get_tau_bar(); \n    } \n\n// \u7136\u540e\uff0c\u786e\u5b9a\u865a\u6784\u7684\u57fa\u5c14\u970d\u592b\u5e94\u529b  $\\overline{\\boldsymbol{\\tau}}$  \u3002\n\n    SymmetricTensor<2, dim> get_tau_bar() const \n    { \n      return 2.0 * c_1 * b_bar; \n    } \n\n// \u8ba1\u7b97\u5207\u7ebf\u7684\u4f53\u79ef\u90e8\u5206  $J \\mathfrak{c}_\\textrm{vol}$  \u3002\n\n    SymmetricTensor<4, dim> get_Jc_vol() const \n    { \n      return p_tilde * det_F * \n             (Physics::Elasticity::StandardTensors<dim>::IxI - \n              (2.0 * Physics::Elasticity::StandardTensors<dim>::S)); \n    } \n\n// \u8ba1\u7b97\u5207\u7ebf\u7684\u7b49\u503c\u90e8\u5206  $J \\mathfrak{c}_\\textrm{iso}$  \u3002\n\n    SymmetricTensor<4, dim> get_Jc_iso() const \n    { \n      const SymmetricTensor<2, dim> tau_bar = get_tau_bar(); \n      const SymmetricTensor<2, dim> tau_iso = get_tau_iso(); \n      const SymmetricTensor<4, dim> tau_iso_x_I = \n        outer_product(tau_iso, Physics::Elasticity::StandardTensors<dim>::I); \n      const SymmetricTensor<4, dim> I_x_tau_iso = \n        outer_product(Physics::Elasticity::StandardTensors<dim>::I, tau_iso); \n      const SymmetricTensor<4, dim> c_bar = get_c_bar(); \n\n      return (2.0 / dim) * trace(tau_bar) * \n               Physics::Elasticity::StandardTensors<dim>::dev_P - \n             (2.0 / dim) * (tau_iso_x_I + I_x_tau_iso) + \n             Physics::Elasticity::StandardTensors<dim>::dev_P * c_bar * \n               Physics::Elasticity::StandardTensors<dim>::dev_P; \n    } \n\n// \u8ba1\u7b97\u865a\u6784\u7684\u5f39\u6027\u5f20\u91cf  $\\overline{\\mathfrak{c}}$  \u3002\u5bf9\u4e8e\u6240\u9009\u62e9\u7684\u6750\u6599\u6a21\u578b\uff0c\u8fd9\u53ea\u662f\u96f6\u3002\n\n    SymmetricTensor<4, dim> get_c_bar() const \n    { \n      return SymmetricTensor<4, dim>(); \n    } \n  }; \n// @sect3{Quadrature point history}  \n\n// \u6b63\u5982\u5728 step-18 \u4e2d\u6240\u770b\u5230\u7684\uff0c <code> PointHistory </code> \u7c7b\u63d0\u4f9b\u4e86\u4e00\u79cd\u5728\u6b63\u4ea4\u70b9\u5b58\u50a8\u6570\u636e\u7684\u65b9\u6cd5\u3002 \u8fd9\u91cc\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u90fd\u6301\u6709\u4e00\u4e2a\u6307\u5411\u6750\u6599\u63cf\u8ff0\u7684\u6307\u9488\u3002 \u56e0\u6b64\uff0c\u4e0d\u540c\u7684\u6750\u6599\u6a21\u578b\u53ef\u4ee5\u7528\u5728\u57df\u7684\u4e0d\u540c\u533a\u57df\u3002 \u5728\u5176\u4ed6\u6570\u636e\u4e2d\uff0c\u6211\u4eec\u9009\u62e9\u4e3a\u6b63\u4ea4\u70b9\u5b58\u50a8Kirchhoff\u5e94\u529b $\\boldsymbol{\\tau}$ \u548c\u6b63\u5207 $J\\mathfrak{c}$ \u3002\n\n  template <int dim> \n  class PointHistory \n  { \n  public: \n    PointHistory() \n      : F_inv(Physics::Elasticity::StandardTensors<dim>::I) \n      , tau(SymmetricTensor<2, dim>()) \n      , d2Psi_vol_dJ2(0.0) \n      , dPsi_vol_dJ(0.0) \n      , Jc(SymmetricTensor<4, dim>()) \n    {} \n\n    virtual ~PointHistory() = default; \n\n// \u7b2c\u4e00\u4e2a\u51fd\u6570\u7528\u4e8e\u521b\u5efa\u4e00\u4e2a\u6750\u6599\u5bf9\u8c61\u5e76\u6b63\u786e\u521d\u59cb\u5316\u6240\u6709\u7684\u5f20\u91cf\u3002\u7b2c\u4e8c\u4e2a\u51fd\u6570\u6839\u636e\u5f53\u524d\u7684\u53d8\u5f62\u91cf $\\textrm{Grad}\\mathbf{u}_{\\textrm{n}}$ \u3001\u538b\u529b $\\widetilde{p}$ \u548c\u6269\u5f20 $\\widetilde{J}$ \u573a\u503c\u66f4\u65b0\u5b58\u50a8\u7684\u6570\u503c\u548c\u5e94\u529b\u3002\n\n    void setup_lqp(const Parameters::AllParameters &parameters) \n    { \n      material = \n        std::make_shared<Material_Compressible_Neo_Hook_Three_Field<dim>>( \n          parameters.mu, parameters.nu); \n      update_values(Tensor<2, dim>(), 0.0, 1.0); \n    } \n\n// \u4e3a\u6b64\uff0c\u6211\u4eec\u4ece\u4f4d\u79fb\u68af\u5ea6 $\\textrm{Grad}\\ \\mathbf{u}$ \u4e2d\u8ba1\u7b97\u51fa\u53d8\u5f62\u68af\u5ea6 $\\mathbf{F}$  \uff0c\u5373 $\\mathbf{F}(\\mathbf{u}) = \\mathbf{I} + \\textrm{Grad}\\ \\mathbf{u}$ \uff0c\u7136\u540e\u8ba9\u4e0e\u8fd9\u4e2a\u6b63\u4ea4\u70b9\u76f8\u5173\u7684\u6750\u6599\u6a21\u578b\u8fdb\u884c\u81ea\u6211\u66f4\u65b0\u3002\u5f53\u8ba1\u7b97\u53d8\u5f62\u68af\u5ea6\u65f6\uff0c\u6211\u4eec\u5fc5\u987b\u6ce8\u610f\u4e0e\u54ea\u4e9b\u6570\u636e\u7c7b\u578b\u8fdb\u884c\u6bd4\u8f83 $\\mathbf{I} + \\textrm{Grad}\\ \\mathbf{u}$ \uff1a\u7531\u4e8e $I$ \u6709\u6570\u636e\u7c7b\u578bSymmetricTensor\uff0c\u53ea\u8981\u5199 <code>I + Grad_u_n</code> \u5c31\u53ef\u4ee5\u5c06\u7b2c\u4e8c\u4e2a\u53c2\u6570\u8f6c\u6362\u4e3a\u5bf9\u79f0\u5f20\u91cf\uff0c\u8fdb\u884c\u6c42\u548c\uff0c\u7136\u540e\u5c06\u7ed3\u679c\u6295\u7ed9Tensor\uff08\u5373\u53ef\u80fd\u662f\u975e\u5bf9\u79f0\u5f20\u91cf\u7684\u7c7b\u578b\uff09\u3002\u7136\u800c\uff0c\u7531\u4e8e <code>Grad_u_n</code> \u5728\u4e00\u822c\u60c5\u51b5\u4e0b\u662f\u975e\u5bf9\u79f0\u7684\uff0c\u8f6c\u6362\u4e3aSymmetricTensor\u5c06\u4f1a\u5931\u8d25\u3002\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u5148\u5c06 $I$ \u8f6c\u6362\u4e3aTensor\uff0c\u7136\u540e\u50cf\u5728\u975e\u5bf9\u79f0\u5f20\u91cf\u4e4b\u95f4\u4e00\u6837\u6267\u884c\u52a0\u6cd5\uff0c\u6765\u907f\u514d\u8fd9\u79cd\u6765\u56de\u6298\u817e\u3002\n\n    void update_values(const Tensor<2, dim> &Grad_u_n, \n                       const double          p_tilde, \n                       const double          J_tilde) \n    { \n      const Tensor<2, dim> F = Physics::Elasticity::Kinematics::F(Grad_u_n); \n      material->update_material_data(F, p_tilde, J_tilde); \n\n// \u6750\u6599\u5df2\u7ecf\u66f4\u65b0\uff0c\u6240\u4ee5\u6211\u4eec\u73b0\u5728\u8ba1\u7b97\u57fa\u5c14\u970d\u592b\u5e94\u529b $\\mathbf{\\tau}$ \uff0c\u5207\u7ebf $J\\mathfrak{c}$ \u548c\u4f53\u79ef\u81ea\u7531\u80fd\u7684\u4e00\u3001\u4e8c\u6b21\u5bfc\u6570\u3002\n\n// \u6211\u4eec\u8fd8\u5b58\u50a8\u4e86\u53d8\u5f62\u68af\u5ea6\u7684\u9006\u503c\uff0c\u56e0\u4e3a\u6211\u4eec\u7ecf\u5e38\u4f7f\u7528\u5b83\u3002\n\n      F_inv         = invert(F); \n      tau           = material->get_tau(); \n      Jc            = material->get_Jc(); \n      dPsi_vol_dJ   = material->get_dPsi_vol_dJ(); \n      d2Psi_vol_dJ2 = material->get_d2Psi_vol_dJ2(); \n    } \n\n// \u6211\u4eec\u63d0\u4f9b\u4e00\u4e2a\u63a5\u53e3\u6765\u68c0\u7d22\u67d0\u4e9b\u6570\u636e\u3002 \u4e0b\u9762\u662f\u8fd0\u52a8\u5b66\u53d8\u91cf\u3002\n\n    double get_J_tilde() const \n    { \n      return material->get_J_tilde(); \n    } \n\n    double get_det_F() const \n    { \n      return material->get_det_F(); \n    } \n\n    const Tensor<2, dim> &get_F_inv() const \n    { \n      return F_inv; \n    } \n\n// ...\u548c\u52a8\u80fd\u53d8\u91cf\u3002 \u8fd9\u4e9b\u5728\u6750\u6599\u548c\u5168\u5c40\u5207\u7ebf\u77e9\u9635\u4ee5\u53ca\u6b8b\u4f59\u88c5\u914d\u64cd\u4f5c\u4e2d\u4f7f\u7528\u3002\n\n    double get_p_tilde() const \n    { \n      return material->get_p_tilde(); \n    } \n\n    const SymmetricTensor<2, dim> &get_tau() const \n    { \n      return tau; \n    } \n\n    double get_dPsi_vol_dJ() const \n    { \n      return dPsi_vol_dJ; \n    } \n\n    double get_d2Psi_vol_dJ2() const \n    { \n      return d2Psi_vol_dJ2; \n    } \n\n// \u6700\u540e\u662f\u5207\u7ebf\u3002\n\n    const SymmetricTensor<4, dim> &get_Jc() const \n    { \n      return Jc; \n    } \n\n// \u5728\u6210\u5458\u51fd\u6570\u65b9\u9762\uff0c\u8fd9\u4e2a\u7c7b\u4e3a\u5b83\u6240\u4ee3\u8868\u7684\u6b63\u4ea4\u70b9\u5b58\u50a8\u4e86\u4e00\u4e2a\u6750\u6599\u7c7b\u578b\u7684\u526f\u672c\uff0c\u4ee5\u5907\u5728\u57df\u7684\u4e0d\u540c\u533a\u57df\u4f7f\u7528\u4e0d\u540c\u7684\u6750\u6599\uff0c\u4ee5\u53ca\u53d8\u5f62\u68af\u5ea6\u7684\u9006\u503c...\n\n  private: \n    std::shared_ptr<Material_Compressible_Neo_Hook_Three_Field<dim>> material; \n\n    Tensor<2, dim> F_inv; \n\n// ...... \u548c\u5e94\u529b\u578b\u53d8\u91cf\u4ee5\u53ca\u5207\u7ebf  $J\\mathfrak{c}$  \u3002\n\n    SymmetricTensor<2, dim> tau; \n    double                  d2Psi_vol_dJ2; \n    double                  dPsi_vol_dJ; \n\n    SymmetricTensor<4, dim> Jc; \n  }; \n// @sect3{Quasi-static quasi-incompressible finite-strain solid}  \n\n// Solid\u7c7b\u662f\u4e2d\u5fc3\u7c7b\uff0c\u5b83\u4ee3\u8868\u4e86\u624b\u5934\u7684\u95ee\u9898\u3002\u5b83\u9075\u5faa\u901a\u5e38\u7684\u65b9\u6848\uff0c\u5373\u5b83\u771f\u6b63\u62e5\u6709\u7684\u662f\u4e00\u4e2a\u6784\u9020\u51fd\u6570\u3001\u89e3\u6784\u51fd\u6570\u548c\u4e00\u4e2a <code>run()</code> \u51fd\u6570\uff0c\u8be5\u51fd\u6570\u5c06\u6240\u6709\u7684\u5de5\u4f5c\u5206\u6d3e\u7ed9\u8fd9\u4e2a\u7c7b\u7684\u79c1\u6709\u51fd\u6570\u3002\n\n  template <int dim> \n  class Solid \n  { \n  public: \n    Solid(const std::string &input_file); \n\n    void run(); \n\n  private: \n\n// \u5728\u8fd9\u4e2a\u7c7b\u7684\u79c1\u6709\u90e8\u5206\uff0c\u6211\u4eec\u9996\u5148\u5411\u524d\u58f0\u660e\u4e00\u4e9b\u5bf9\u8c61\uff0c\u8fd9\u4e9b\u5bf9\u8c61\u5728\u4f7f\u7528WorkStream\u5bf9\u8c61\u8fdb\u884c\u5e76\u884c\u5de5\u4f5c\u65f6\u4f7f\u7528\uff08\u5173\u4e8e\u8fd9\u65b9\u9762\u7684\u66f4\u591a\u4fe1\u606f\uff0c\u8bf7\u53c2\u89c1 @ref threads \u6a21\u5757\uff09\u3002\n\n// \u6211\u4eec\u58f0\u660e\u8fd9\u6837\u7684\u7ed3\u6784\uff0c\u7528\u4e8e\u6b63\u5207\uff08\u521a\u5ea6\uff09\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u77e2\u91cf\u7684\u8ba1\u7b97\uff0c\u9759\u6001\u51b7\u51dd\uff0c\u4ee5\u53ca\u66f4\u65b0\u6b63\u4ea4\u70b9\u3002\n\n    struct PerTaskData_ASM; \n    struct ScratchData_ASM; \n\n    struct PerTaskData_SC; \n    struct ScratchData_SC; \n\n    struct PerTaskData_UQPH; \n    struct ScratchData_UQPH; \n\n// \u6211\u4eec\u4ece\u4e00\u4e2a\u5efa\u7acb\u7f51\u683c\u7684\u6210\u5458\u51fd\u6570\u5f00\u59cb\u6536\u96c6\u3002\n\n    void make_grid(); \n\n// \u8bbe\u7f6e\u8981\u89e3\u51b3\u7684\u6709\u9650\u5143\u7cfb\u7edf\u3002\n\n    void system_setup(); \n\n    void determine_component_extractors(); \n\n// \u4e3a\u589e\u91cf\u4f4d\u79fb\u573a\u521b\u5efaDirichlet\u7ea6\u675f\u3002\n\n    void make_constraints(const int it_nr); \n\n// \u4f7f\u7528\u591a\u7ebf\u7a0b\u7684\u51e0\u4e2a\u51fd\u6570\u6765\u7ec4\u88c5\u7cfb\u7edf\u548c\u53f3\u624b\u8fb9\u7684\u77e9\u9635\u3002\u5b83\u4eec\u4e2d\u7684\u6bcf\u4e00\u4e2a\u90fd\u662f\u5305\u88c5\u51fd\u6570\uff0c\u4e00\u4e2a\u662f\u5728WorkStream\u6a21\u578b\u4e2d\u5bf9\u4e00\u4e2a\u5355\u5143\u8fdb\u884c\u5de5\u4f5c\u7684\u6267\u884c\u51fd\u6570\uff0c\u53e6\u4e00\u4e2a\u662f\u5c06\u5bf9\u8fd9\u4e00\u4e2a\u5355\u5143\u7684\u5de5\u4f5c\u590d\u5236\u5230\u4ee3\u8868\u5b83\u7684\u5168\u5c40\u5bf9\u8c61\u4e2d\u3002\n\n    void assemble_system(); \n\n    void assemble_system_one_cell( \n      const typename DoFHandler<dim>::active_cell_iterator &cell, \n      ScratchData_ASM &                                     scratch, \n      PerTaskData_ASM &                                     data) const; \n\n// \u8fd8\u6709\u7c7b\u4f3c\u7684\uff0c\u6267\u884c\u5168\u5c40\u9759\u6001\u51b7\u51dd\u3002\n\n    void assemble_sc(); \n\n    void assemble_sc_one_cell( \n      const typename DoFHandler<dim>::active_cell_iterator &cell, \n      ScratchData_SC &                                      scratch, \n      PerTaskData_SC &                                      data); \n\n    void copy_local_to_global_sc(const PerTaskData_SC &data); \n\n// \u521b\u5efa\u5e76\u66f4\u65b0\u6b63\u4ea4\u70b9\u3002\u5728\u8fd9\u91cc\uff0c\u6ca1\u6709\u6570\u636e\u9700\u8981\u88ab\u590d\u5236\u5230\u5168\u5c40\u5bf9\u8c61\u4e2d\uff0c\u6240\u4ee5copy_local_to_global\u51fd\u6570\u662f\u7a7a\u7684\u3002\n\n    void setup_qph(); \n\n    void update_qph_incremental(const BlockVector<double> &solution_delta); \n\n    void update_qph_incremental_one_cell( \n      const typename DoFHandler<dim>::active_cell_iterator &cell, \n      ScratchData_UQPH &                                    scratch, \n      PerTaskData_UQPH &                                    data); \n\n    void copy_local_to_global_UQPH(const PerTaskData_UQPH & /*data*/) \n    {} \n\n// \u7528\u725b\u987f-\u62c9\u5f17\u68ee\u65b9\u6cd5\u6c42\u89e3\u4f4d\u79fb\u3002\u6211\u4eec\u628a\u8fd9\u4e2a\u51fd\u6570\u5206\u6210\u975e\u7ebf\u6027\u5faa\u73af\u548c\u89e3\u51b3\u7ebf\u6027\u5316\u7684Newton-Raphson\u6b65\u9aa4\u7684\u51fd\u6570\u3002\n\n    void solve_nonlinear_timestep(BlockVector<double> &solution_delta); \n\n    std::pair<unsigned int, double> \n    solve_linear_system(BlockVector<double> &newton_update); \n\n// \u68c0\u7d22\u89e3\u51b3\u65b9\u6848\uff0c\u4ee5\u53ca\u540e\u671f\u5904\u7406\u548c\u5c06\u6570\u636e\u5199\u5165\u6587\u4ef6\u3002\n\n    BlockVector<double> \n    get_total_solution(const BlockVector<double> &solution_delta) const; \n\n    void output_results() const; \n\n// \u6700\u540e\u662f\u4e00\u4e9b\u63cf\u8ff0\u5f53\u524d\u72b6\u6001\u7684\u6210\u5458\u53d8\u91cf\u3002\u4e00\u4e2a\u7528\u4e8e\u63cf\u8ff0\u95ee\u9898\u8bbe\u7f6e\u7684\u53c2\u6570\u96c6\u5408...\n\n    Parameters::AllParameters parameters; \n\n// ...\u53c2\u8003\u914d\u7f6e\u7684\u4f53\u79ef...\n\n    double vol_reference; \n\n// ......\u4ee5\u53ca\u5bf9\u89e3\u51b3\u95ee\u9898\u7684\u51e0\u4f55\u5f62\u72b6\u7684\u63cf\u8ff0\u3002\n\n    Triangulation<dim> triangulation; \n\n// \u540c\u65f6\uff0c\u8bb0\u5f55\u5f53\u524d\u65f6\u95f4\u548c\u8bc4\u4f30\u67d0\u4e9b\u51fd\u6570\u7684\u65f6\u95f4\n\n    Time                time; \n    mutable TimerOutput timer; \n\n// \u4e00\u4e2a\u5b58\u50a8\u6b63\u4ea4\u70b9\u4fe1\u606f\u7684\u5bf9\u8c61\u3002\u4e0e step-18 \u4e0d\u540c\uff0c\u8fd9\u91cc\u91c7\u7528\u4e86deal.II\u7684\u672c\u5730\u6b63\u4ea4\u70b9\u6570\u636e\u7ba1\u7406\u5668\u3002\n\n    CellDataStorage<typename Triangulation<dim>::cell_iterator, \n                    PointHistory<dim>> \n      quadrature_point_history; \n\n// \u5bf9\u6709\u9650\u5143\u7cfb\u7edf\u7684\u63cf\u8ff0\uff0c\u5305\u62ec\u4f4d\u79fb\u591a\u9879\u5f0f\u7a0b\u5ea6\u3001\u81ea\u7531\u5ea6\u5904\u7406\u7a0b\u5e8f\u3001\u6bcf\u4e2a\u5355\u5143\u7684DoF\u6570\u91cf\u4ee5\u53ca\u7528\u4e8e\u4ece\u89e3\u5411\u91cf\u4e2d\u68c0\u7d22\u4fe1\u606f\u7684\u63d0\u53d6\u5668\u5bf9\u8c61\u3002\n\n    const unsigned int               degree; \n    const FESystem<dim>              fe; \n    DoFHandler<dim>                  dof_handler; \n    const unsigned int               dofs_per_cell; \n    const FEValuesExtractors::Vector u_fe; \n    const FEValuesExtractors::Scalar p_fe; \n    const FEValuesExtractors::Scalar J_fe; \n\n// \u8bf4\u660e\u5757\u7cfb\u7edf\u662f\u5982\u4f55\u5b89\u6392\u7684\u3002\u67093\u4e2a\u5757\uff0c\u7b2c\u4e00\u4e2a\u5305\u542b\u4e00\u4e2a\u77e2\u91cfDOF  $\\mathbf{u}$  \uff0c\u800c\u53e6\u5916\u4e24\u4e2a\u63cf\u8ff0\u6807\u91cfDOF\uff0c $\\widetilde{p}$  \u548c  $\\widetilde{J}$  \u3002\n\n    static const unsigned int n_blocks          = 3; \n    static const unsigned int n_components      = dim + 2; \n    static const unsigned int first_u_component = 0; \n    static const unsigned int p_component       = dim; \n    static const unsigned int J_component       = dim + 1; \n\n    enum \n    { \n      u_dof = 0, \n      p_dof = 1, \n      J_dof = 2 \n    }; \n\n    std::vector<types::global_dof_index> dofs_per_block; \n    std::vector<types::global_dof_index> element_indices_u; \n    std::vector<types::global_dof_index> element_indices_p; \n    std::vector<types::global_dof_index> element_indices_J; \n\n//\u5355\u5143\u548c\u9762\u7684\u9ad8\u65af\u6b63\u4ea4\u89c4\u5219\u3002\u5355\u5143\u548c\u9762\u7684\u6b63\u4ea4\u70b9\u7684\u6570\u91cf\u88ab\u8bb0\u5f55\u4e0b\u6765\u3002\n\n    const QGauss<dim>     qf_cell; \n    const QGauss<dim - 1> qf_face; \n    const unsigned int    n_q_points; \n    const unsigned int    n_q_points_f; \n\n// \u7528\u4e8e\u5b58\u50a8\u6536\u655b\u7684\u89e3\u548c\u53f3\u624b\u8fb9\u5411\u91cf\u4ee5\u53ca\u5207\u7ebf\u77e9\u9635\u7684\u5bf9\u8c61\u3002\u6709\u4e00\u4e2aAffineConstraints\u5bf9\u8c61\uff0c\u7528\u4e8e\u8ddf\u8e2a\u7ea6\u675f\u6761\u4ef6\u3002 \u6211\u4eec\u5229\u7528\u4e86\u4e3a\u5757\u72b6\u7cfb\u7edf\u8bbe\u8ba1\u7684\u7a00\u758f\u6027\u6a21\u5f0f\u3002\n\n    AffineConstraints<double> constraints; \n    BlockSparsityPattern      sparsity_pattern; \n    BlockSparseMatrix<double> tangent_matrix; \n    BlockVector<double>       system_rhs; \n    BlockVector<double>       solution_n; \n//\u7136\u540e\n//\u5b9a\u4e49\u4e00\u4e9b\u53d8\u91cf\u6765\u5b58\u50a8\u89c4\u8303\uff0c\u5e76\u66f4\u65b0\u89c4\u8303\u548c\u5f52\u4e00\u5316\u7cfb\u6570\u3002\n\n    struct Errors \n    { \n      Errors() \n        : norm(1.0) \n        , u(1.0) \n        , p(1.0) \n        , J(1.0) \n      {} \n\n      void reset() \n      { \n        norm = 1.0; \n        u    = 1.0; \n        p    = 1.0; \n        J    = 1.0; \n      } \n      void normalize(const Errors &rhs) \n      { \n        if (rhs.norm != 0.0) \n          norm /= rhs.norm; \n        if (rhs.u != 0.0) \n          u /= rhs.u; \n        if (rhs.p != 0.0) \n          p /= rhs.p; \n        if (rhs.J != 0.0) \n          J /= rhs.J; \n      } \n\n      double norm, u, p, J; \n    }; \n\n    Errors error_residual, error_residual_0, error_residual_norm, error_update, \n      error_update_0, error_update_norm; \n\n// \u8ba1\u7b97\u8bef\u5dee\u63aa\u65bd\u7684\u65b9\u6cd5\n\n    void get_error_residual(Errors &error_residual); \n\n    void get_error_update(const BlockVector<double> &newton_update, \n                          Errors &                   error_update); \n\n    std::pair<double, double> get_error_dilation() const; \n\n// \u8ba1\u7b97\u7a7a\u95f4\u914d\u7f6e\u4e2d\u7684\u4f53\u79ef\n\n    double compute_vol_current() const; \n\n// \u4ee5\u60a6\u76ee\u7684\u65b9\u5f0f\u5411\u5c4f\u5e55\u6253\u5370\u4fe1\u606f...\n\n    static void print_conv_header(); \n\n    void print_conv_footer(); \n  }; \n// @sect3{Implementation of the <code>Solid</code> class}  \n// @sect4{Public interface}  \n\n// \u6211\u4eec\u4f7f\u7528\u4ece\u53c2\u6570\u6587\u4ef6\u4e2d\u63d0\u53d6\u7684\u6570\u636e\u6765\u521d\u59cb\u5316Solid\u7c7b\u3002\n\n  template <int dim> \n  Solid<dim>::Solid(const std::string &input_file) \n    : parameters(input_file) \n    , vol_reference(0.) \n    , triangulation(Triangulation<dim>::maximum_smoothing) \n    , time(parameters.end_time, parameters.delta_t) \n    , timer(std::cout, TimerOutput::summary, TimerOutput::wall_times) \n    , degree(parameters.poly_degree) \n    , \n\n// \u6709\u9650\u5143\u7cfb\u7edf\u662f\u7531\u660f\u6697\u7684\u8fde\u7eed\u4f4d\u79fbDOF\u548c\u4e0d\u8fde\u7eed\u7684\u538b\u529b\u548c\u81a8\u80c0DOF\u7ec4\u6210\u3002\u4e3a\u4e86\u6ee1\u8db3Babuska-Brezzi\u6216LBB\u7a33\u5b9a\u6027\u6761\u4ef6\uff08\u89c1Hughes\uff082000\uff09\uff09\uff0c\u6211\u4eec\u8bbe\u7f6e\u4e86\u4e00\u4e2a $Q_n \\times DGPM_{n-1} \\times DGPM_{n-1}$ \u7cfb\u7edf\u3002  $Q_2 \\times DGPM_1 \\times DGPM_1$ \u5143\u7d20\u6ee1\u8db3\u8fd9\u4e2a\u6761\u4ef6\uff0c\u800c $Q_1 \\times DGPM_0 \\times DGPM_0$ \u5143\u7d20\u4e0d\u6ee1\u8db3\u3002\u7136\u800c\uff0c\u4e8b\u5b9e\u8bc1\u660e\uff0c\u540e\u8005\u8fd8\u662f\u8868\u73b0\u51fa\u826f\u597d\u7684\u6536\u655b\u7279\u6027\u3002\n\n    fe(FE_Q<dim>(parameters.poly_degree), \n       dim, // displacement \n       FE_DGPMonomial<dim>(parameters.poly_degree - 1), \n       1, // pressure \n       FE_DGPMonomial<dim>(parameters.poly_degree - 1), \n       1) \n    , // dilatation \n    dof_handler(triangulation) \n    , dofs_per_cell(fe.n_dofs_per_cell()) \n    , u_fe(first_u_component) \n    , p_fe(p_component) \n    , J_fe(J_component) \n    , dofs_per_block(n_blocks) \n    , qf_cell(parameters.quad_order) \n    , qf_face(parameters.quad_order) \n    , n_q_points(qf_cell.size()) \n    , n_q_points_f(qf_face.size()) \n  { \n    Assert(dim == 2 || dim == 3, \n           ExcMessage(\"This problem only works in 2 or 3 space dimensions.\")); \n    determine_component_extractors(); \n  } \n\n// \u5728\u89e3\u51b3\u51c6\u9759\u6001\u95ee\u9898\u65f6\uff0c\u65f6\u95f4\u6210\u4e3a\u4e00\u4e2a\u52a0\u8f7d\u53c2\u6570\uff0c\u5373\u6211\u4eec\u968f\u7740\u65f6\u95f4\u7ebf\u6027\u589e\u52a0\u52a0\u8f7d\u91cf\uff0c\u4f7f\u5f97\u8fd9\u4e24\u4e2a\u6982\u5ff5\u53ef\u4ee5\u4e92\u6362\u3002\u6211\u4eec\u9009\u62e9\u7528\u6052\u5b9a\u7684\u65f6\u95f4\u6b65\u957f\u6765\u7ebf\u6027\u9012\u589e\u65f6\u95f4\u3002\n\n// \u6211\u4eec\u4ece\u9884\u5904\u7406\u5f00\u59cb\uff0c\u8bbe\u7f6e\u521d\u59cb\u6269\u5f20\u503c\uff0c\u7136\u540e\u8f93\u51fa\u521d\u59cb\u7f51\u683c\uff0c\u7136\u540e\u5f00\u59cb\u6a21\u62df\uff0c\u5f00\u59cb\u7b2c\u4e00\u6b21\u65f6\u95f4\uff08\u548c\u8f7d\u8377\uff09\u9012\u589e\u3002\n\n// \u5728\u5bf9\u521d\u59cb\u89e3\u573a\u65bd\u52a0\u7ea6\u675f $\\widetilde{J}=1$ \u65f6\uff0c\u5fc5\u987b\u6ce8\u610f\uff08\u6216\u8005\u81f3\u5c11\u8981\u8003\u8651\u4e00\u4e0b\uff09\u3002\u8be5\u7ea6\u675f\u5bf9\u5e94\u4e8e\u672a\u53d8\u5f62\u6784\u578b\u4e2d\u53d8\u5f62\u68af\u5ea6\u7684\u884c\u5217\u5f0f\uff0c\u4e5f\u5c31\u662f\u8eab\u4efd\u5f20\u91cf\u3002\u6211\u4eec\u4f7f\u7528FE_DGPMonomial\u57fa\u6570\u6765\u63d2\u503c\u6269\u5f20\u573a\uff0c\u56e0\u6b64\u6211\u4eec\u4e0d\u80fd\u7b80\u5355\u5730\u5c06\u76f8\u5e94\u7684dof\u8bbe\u7f6e\u4e3aunity\uff0c\u56e0\u4e3a\u5b83\u4eec\u5bf9\u5e94\u4e8e\u5355\u9879\u5f0f\u7cfb\u6570\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u4f7f\u7528 VectorTools::project \u51fd\u6570\u6765\u4e3a\u6211\u4eec\u505a\u8fd9\u9879\u5de5\u4f5c\u3002 VectorTools::project \u51fd\u6570\u9700\u8981\u4e00\u4e2a\u53c2\u6570\uff0c\u8868\u660e\u60ac\u6302\u8282\u70b9\u7684\u7ea6\u675f\u3002\u6211\u4eec\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u6ca1\u6709 \u6240\u4ee5\u6211\u4eec\u5fc5\u987b\u521b\u5efa\u4e00\u4e2a\u7ea6\u675f\u5bf9\u8c61\u3002\u5728\u539f\u59cb\u72b6\u6001\u4e0b\uff0c\u7ea6\u675f\u5bf9\u8c61\u662f\u6ca1\u6709\u6392\u5e8f\u7684\uff0c\u5fc5\u987b\u5148\u8fdb\u884c\u6392\u5e8f\uff08\u4f7f\u7528 AffineConstraints::close \u51fd\u6570\uff09\u624d\u80fd\u4f7f\u7528\u3002\u8bf7\u770b  step-21  \u4ee5\u4e86\u89e3\u66f4\u591a\u4fe1\u606f\u3002\u6211\u4eec\u53ea\u9700\u8981\u5f3a\u5236\u6267\u884c\u6269\u5f20\u7684\u521d\u59cb\u6761\u4ef6\u3002\u4e3a\u4e86\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u4f7f\u7528ComponentSelectFunction\uff0c\u5b83\u4f5c\u4e3a\u4e00\u4e2a\u63a9\u7801\uff0c\u5c06n_components\u7684J_component\u8bbe\u7f6e\u4e3a1\u3002 \u8fd9\u6b63\u662f\u6211\u4eec\u60f3\u8981\u7684\u3002\u8bf7\u770b step-20 \u4e2d\u7684\u7528\u6cd5\uff0c\u4e86\u89e3\u66f4\u591a\u4fe1\u606f\u3002\n\n  template <int dim> \n  void Solid<dim>::run() \n  { \n    make_grid(); \n    system_setup(); \n    { \n      AffineConstraints<double> constraints; \n      constraints.close(); \n\n      const ComponentSelectFunction<dim> J_mask(J_component, n_components); \n\n      VectorTools::project( \n        dof_handler, constraints, QGauss<dim>(degree + 2), J_mask, solution_n); \n    } \n    output_results(); \n    time.increment(); \n\n// \u7136\u540e\u6211\u4eec\u5ba3\u5e03\u589e\u91cf\u89e3\u51b3\u65b9\u6848\u66f4\u65b0 $\\varDelta \\mathbf{\\Xi} \\dealcoloneq \\{\\varDelta \\mathbf{u},\\varDelta \\widetilde{p}, \\varDelta \\widetilde{J} \\}$ \u5e76\u5f00\u59cb\u5728\u65f6\u57df\u4e0a\u5faa\u73af\u3002\n\n// \u5728\u5f00\u59cb\u7684\u65f6\u5019\uff0c\u6211\u4eec\u91cd\u7f6e\u8fd9\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u89e3\u51b3\u65b9\u6848\u66f4\u65b0...\n\n    BlockVector<double> solution_delta(dofs_per_block); \n    while (time.current() < time.end()) \n      { \n        solution_delta = 0.0; \n\n// ...\u6c42\u89e3\u5f53\u524d\u65f6\u95f4\u6b65\u957f\u5e76\u66f4\u65b0\u603b\u89e3\u5411\u91cf  $\\mathbf{\\Xi}_{\\textrm{n}} = \\mathbf{\\Xi}_{\\textrm{n-1}} + \\varDelta \\mathbf{\\Xi}$  ...\n\n        solve_nonlinear_timestep(solution_delta); \n        solution_n += solution_delta; \n\n// ...\u5e76\u5728\u5feb\u4e50\u5730\u8fdb\u5165\u4e0b\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e4b\u524d\u7ed8\u5236\u7ed3\u679c\u3002\n\n        output_results(); \n        time.increment(); \n      } \n  } \n// @sect3{Private interface}  \n// @sect4{Threading-building-blocks structures}  \n\n// \u7b2c\u4e00\u7ec4\u79c1\u6709\u6210\u5458\u51fd\u6570\u4e0e\u5e76\u884c\u5316\u6709\u5173\u3002\u6211\u4eec\u4f7f\u7528\u7ebf\u7a0b\u79ef\u6728\u5e93\uff08TBB\uff09\u6765\u6267\u884c\u5c3d\u53ef\u80fd\u591a\u7684\u8ba1\u7b97\u5bc6\u96c6\u578b\u5206\u5e03\u5f0f\u4efb\u52a1\u3002\u7279\u522b\u662f\uff0c\u6211\u4eec\u4f7f\u7528TBB\u7ec4\u88c5\u6b63\u5207\u77e9\u9635\u548c\u53f3\u624b\u5411\u91cf\u3001\u9759\u6001\u51dd\u7ed3\u8d21\u732e\uff0c\u4ee5\u53ca\u66f4\u65b0\u5b58\u50a8\u5728\u6b63\u4ea4\u70b9\u7684\u6570\u636e\u3002\u6211\u4eec\u5728\u8fd9\u65b9\u9762\u7684\u4e3b\u8981\u5de5\u5177\u662fWorkStream\u7c7b\uff08\u66f4\u591a\u4fe1\u606f\u89c1 @ref \u7ebf\u7a0b\u6a21\u5757\uff09\u3002\n\n// \u9996\u5148\u6211\u4eec\u8981\u5904\u7406\u6b63\u5207\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u88c5\u914d\u7ed3\u6784\u3002PerTaskData\u5bf9\u8c61\u5b58\u50a8\u4e86\u672c\u5730\u5bf9\u5168\u5c40\u7cfb\u7edf\u7684\u8d21\u732e\u3002\n\n  template <int dim> \n  struct Solid<dim>::PerTaskData_ASM \n  { \n    FullMatrix<double>                   cell_matrix; \n    Vector<double>                       cell_rhs; \n    std::vector<types::global_dof_index> local_dof_indices; \n\n    PerTaskData_ASM(const unsigned int dofs_per_cell) \n      : cell_matrix(dofs_per_cell, dofs_per_cell) \n      , cell_rhs(dofs_per_cell) \n      , local_dof_indices(dofs_per_cell) \n    {} \n\n    void reset() \n    { \n      cell_matrix = 0.0; \n      cell_rhs    = 0.0; \n    } \n  }; \n\n// \u53e6\u4e00\u65b9\u9762\uff0cScratchData\u5bf9\u8c61\u5b58\u50a8\u4e86\u8f83\u5927\u7684\u5bf9\u8c61\uff0c\u5982\u5f62\u72b6\u51fd\u6570\u503c\u6570\u7ec4\uff08  <code>Nx</code>  \uff09\u548c\u5f62\u72b6\u51fd\u6570\u68af\u5ea6\u548c\u5bf9\u79f0\u68af\u5ea6\u5411\u91cf\uff0c\u6211\u4eec\u5c06\u5728\u88c5\u914d\u65f6\u4f7f\u7528\u3002\n\n  template <int dim> \n  struct Solid<dim>::ScratchData_ASM \n  { \n    FEValues<dim>     fe_values; \n    FEFaceValues<dim> fe_face_values; \n\n    std::vector<std::vector<double>>                  Nx; \n    std::vector<std::vector<Tensor<2, dim>>>          grad_Nx; \n    std::vector<std::vector<SymmetricTensor<2, dim>>> symm_grad_Nx; \n\n    ScratchData_ASM(const FiniteElement<dim> &fe_cell, \n                    const QGauss<dim> &       qf_cell, \n                    const UpdateFlags         uf_cell, \n                    const QGauss<dim - 1> &   qf_face, \n                    const UpdateFlags         uf_face) \n      : fe_values(fe_cell, qf_cell, uf_cell) \n      , fe_face_values(fe_cell, qf_face, uf_face) \n      , Nx(qf_cell.size(), std::vector<double>(fe_cell.n_dofs_per_cell())) \n      , grad_Nx(qf_cell.size(), \n                std::vector<Tensor<2, dim>>(fe_cell.n_dofs_per_cell())) \n      , symm_grad_Nx(qf_cell.size(), \n                     std::vector<SymmetricTensor<2, dim>>( \n                       fe_cell.n_dofs_per_cell())) \n    {} \n\n    ScratchData_ASM(const ScratchData_ASM &rhs) \n      : fe_values(rhs.fe_values.get_fe(), \n                  rhs.fe_values.get_quadrature(), \n                  rhs.fe_values.get_update_flags()) \n      , fe_face_values(rhs.fe_face_values.get_fe(), \n                       rhs.fe_face_values.get_quadrature(), \n                       rhs.fe_face_values.get_update_flags()) \n      , Nx(rhs.Nx) \n      , grad_Nx(rhs.grad_Nx) \n      , symm_grad_Nx(rhs.symm_grad_Nx) \n    {} \n\n    void reset() \n    { \n      const unsigned int n_q_points      = Nx.size(); \n      const unsigned int n_dofs_per_cell = Nx[0].size(); \n      for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n        { \n          Assert(Nx[q_point].size() == n_dofs_per_cell, ExcInternalError()); \n          Assert(grad_Nx[q_point].size() == n_dofs_per_cell, \n                 ExcInternalError()); \n          Assert(symm_grad_Nx[q_point].size() == n_dofs_per_cell, \n                 ExcInternalError()); \n          for (unsigned int k = 0; k < n_dofs_per_cell; ++k) \n            { \n              Nx[q_point][k]           = 0.0; \n              grad_Nx[q_point][k]      = 0.0; \n              symm_grad_Nx[q_point][k] = 0.0; \n            } \n        } \n    } \n  }; \n\n// \u7136\u540e\u6211\u4eec\u5b9a\u4e49\u7ed3\u6784\u6765\u7ec4\u88c5\u9759\u6001\u51dd\u7ed3\u7684\u5207\u7ebf\u77e9\u9635\u3002\u56de\u987e\u4e00\u4e0b\uff0c\u6211\u4eec\u5e0c\u671b\u89e3\u51b3\u4e00\u4e2a\u57fa\u4e8e\u4f4d\u79fb\u7684\u516c\u5f0f\u3002\u7531\u4e8e $\\widetilde{p}$ \u548c $\\widetilde{J}$ \u5b57\u6bb5\u5728\u5143\u7d20\u5c42\u9762\u4e0a\u662f\u4e0d\u8fde\u7eed\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u5143\u7d20\u5c42\u9762\u4e0a\u8fdb\u884c\u7f29\u5408\u3002 \u7531\u4e8e\u8fd9\u4e9b\u64cd\u4f5c\u662f\u57fa\u4e8e\u77e9\u9635\u7684\uff0c\u6211\u4eec\u9700\u8981\u8bbe\u7f6e\u4e00\u4e9b\u77e9\u9635\u6765\u5b58\u50a8\u4e00\u4e9b\u5207\u7ebf\u77e9\u9635\u5b50\u5757\u7684\u5c40\u90e8\u8d21\u732e\u3002 \u6211\u4eec\u628a\u8fd9\u4e9b\u653e\u5728PerTaskData\u7ed3\u6784\u4e2d\u3002\n\n// \u6211\u4eec\u9009\u62e9\u4e0d\u5728 <code>reset()</code> \u51fd\u6570\u4e2d\u91cd\u7f6e\u4efb\u4f55\u6570\u636e\uff0c\u56e0\u4e3a\u77e9\u9635\u63d0\u53d6\u548c\u66ff\u6362\u5de5\u5177\u4f1a\u5904\u7406\u8fd9\u4e2a\u95ee\u9898\u3002\n\n  template <int dim> \n  struct Solid<dim>::PerTaskData_SC \n  { \n    FullMatrix<double>                   cell_matrix; \n    std::vector<types::global_dof_index> local_dof_indices; \n\n    FullMatrix<double> k_orig; \n    FullMatrix<double> k_pu; \n    FullMatrix<double> k_pJ; \n    FullMatrix<double> k_JJ; \n    FullMatrix<double> k_pJ_inv; \n    FullMatrix<double> k_bbar; \n    FullMatrix<double> A; \n    FullMatrix<double> B; \n    FullMatrix<double> C; \n\n    PerTaskData_SC(const unsigned int dofs_per_cell, \n                   const unsigned int n_u, \n                   const unsigned int n_p, \n                   const unsigned int n_J) \n      : cell_matrix(dofs_per_cell, dofs_per_cell) \n      , local_dof_indices(dofs_per_cell) \n      , k_orig(dofs_per_cell, dofs_per_cell) \n      , k_pu(n_p, n_u) \n      , k_pJ(n_p, n_J) \n      , k_JJ(n_J, n_J) \n      , k_pJ_inv(n_p, n_J) \n      , k_bbar(n_u, n_u) \n      , A(n_J, n_u) \n      , B(n_J, n_u) \n      , C(n_p, n_u) \n    {} \n\n    void reset() \n    {} \n  }; \n\n// \u6211\u4eec\u5e0c\u671b\u5728\u8fd9\u91cc\u6267\u884c\u7684\u64cd\u4f5c\u7684ScratchData\u5bf9\u8c61\u662f\u7a7a\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u4e0d\u9700\u8981\u4e34\u65f6\u6570\u636e\uff0c\u4f46\u5b83\u4ecd\u7136\u9700\u8981\u4e3a\u5f53\u524ddeal.II\u4e2dTBB\u7684\u5b9e\u73b0\u800c\u5b9a\u4e49\u3002 \u6240\u4ee5\u6211\u4eec\u4e3a\u6b64\u521b\u5efa\u4e86\u4e00\u4e2a\u5047\u7684\u7ed3\u6784\u3002\n\n  template <int dim> \n  struct Solid<dim>::ScratchData_SC \n  { \n    void reset() \n    {} \n  }; \n\n// \u6700\u540e\u6211\u4eec\u5b9a\u4e49\u7ed3\u6784\u4ee5\u534f\u52a9\u66f4\u65b0\u6b63\u4ea4\u70b9\u4fe1\u606f\u3002\u4e0eSC\u7684\u88c5\u914d\u8fc7\u7a0b\u7c7b\u4f3c\uff0c\u6211\u4eec\u4e0d\u9700\u8981PerTaskData\u5bf9\u8c61\uff08\u56e0\u4e3a\u8fd9\u91cc\u6ca1\u6709\u4ec0\u4e48\u53ef\u5b58\u50a8\u7684\uff09\uff0c\u4f46\u8fd8\u662f\u5fc5\u987b\u5b9a\u4e49\u4e00\u4e2a\u3002\u8bf7\u6ce8\u610f\uff0c\u8fd9\u662f\u56e0\u4e3a\u5bf9\u4e8e\u6211\u4eec\u8fd9\u91cc\u7684\u64cd\u4f5c--\u66f4\u65b0\u6b63\u4ea4\u70b9\u7684\u6570\u636e--\u662f\u7eaf\u7cb9\u7684\u5c40\u90e8\u64cd\u4f5c\uff1a\u6211\u4eec\u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\u505a\u7684\u4e8b\u60c5\u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\u90fd\u4f1a\u88ab\u6d88\u8017\u6389\uff0c\u6ca1\u6709\u50cf\u4f7f\u7528WorkStream\u7c7b\u65f6\u901a\u5e38\u4f1a\u6709\u7684\u5168\u5c40\u805a\u5408\u64cd\u4f5c\u3002\u6211\u4eec\u4ecd\u7136\u5fc5\u987b\u5b9a\u4e49\u6bcf\u4e2a\u4efb\u52a1\u7684\u6570\u636e\u7ed3\u6784\uff0c\u8fd9\u8868\u660eWorkStream\u7c7b\u53ef\u80fd\u4e0d\u9002\u5408\u8fd9\u79cd\u64cd\u4f5c\uff08\u539f\u5219\u4e0a\uff0c\u6211\u4eec\u53ef\u4ee5\u7b80\u5355\u5730\u4e3a\u6bcf\u4e2a\u5355\u5143\u4f7f\u7528 Threads::new_task \u521b\u5efa\u4e00\u4e2a\u65b0\u7684\u4efb\u52a1\uff09\uff0c\u4f46\u65e0\u8bba\u5982\u4f55\u8fd9\u6837\u505a\u4e5f\u6ca1\u6709\u4ec0\u4e48\u574f\u5904\u3002\u6b64\u5916\uff0c\u5982\u679c\u4e00\u4e2a\u6b63\u4ea4\u70b9\u6709\u4e0d\u540c\u7684\u6750\u6599\u6a21\u578b\uff0c\u9700\u8981\u4e0d\u540c\u7a0b\u5ea6\u7684\u8ba1\u7b97\u8d39\u7528\uff0c\u90a3\u4e48\u8fd9\u91cc\u4f7f\u7528\u7684\u65b9\u6cd5\u53ef\u80fd\u662f\u6709\u5229\u7684\u3002\n\n  template <int dim> \n  struct Solid<dim>::PerTaskData_UQPH \n  { \n    void reset() \n    {} \n  }; \n\n// ScratchData\u5bf9\u8c61\u5c06\u88ab\u7528\u6765\u5b58\u50a8\u89e3\u5411\u91cf\u7684\u522b\u540d\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u4e0d\u5fc5\u590d\u5236\u8fd9\u4e2a\u5927\u7684\u6570\u636e\u7ed3\u6784\u3002\u7136\u540e\u6211\u4eec\u5b9a\u4e49\u4e00\u4e9b\u5411\u91cf\u6765\u63d0\u53d6\u6b63\u4ea4\u70b9\u7684\u89e3\u503c\u548c\u68af\u5ea6\u3002\n\n  template <int dim> \n  struct Solid<dim>::ScratchData_UQPH \n  { \n    const BlockVector<double> &solution_total; \n\n    std::vector<Tensor<2, dim>> solution_grads_u_total; \n    std::vector<double>         solution_values_p_total; \n    std::vector<double>         solution_values_J_total; \n\n    FEValues<dim> fe_values; \n\n    ScratchData_UQPH(const FiniteElement<dim> & fe_cell, \n                     const QGauss<dim> &        qf_cell, \n                     const UpdateFlags          uf_cell, \n                     const BlockVector<double> &solution_total) \n      : solution_total(solution_total) \n      , solution_grads_u_total(qf_cell.size()) \n      , solution_values_p_total(qf_cell.size()) \n      , solution_values_J_total(qf_cell.size()) \n      , fe_values(fe_cell, qf_cell, uf_cell) \n    {} \n\n    ScratchData_UQPH(const ScratchData_UQPH &rhs) \n      : solution_total(rhs.solution_total) \n      , solution_grads_u_total(rhs.solution_grads_u_total) \n      , solution_values_p_total(rhs.solution_values_p_total) \n      , solution_values_J_total(rhs.solution_values_J_total) \n      , fe_values(rhs.fe_values.get_fe(), \n                  rhs.fe_values.get_quadrature(), \n                  rhs.fe_values.get_update_flags()) \n    {} \n\n    void reset() \n    { \n      const unsigned int n_q_points = solution_grads_u_total.size(); \n      for (unsigned int q = 0; q < n_q_points; ++q) \n        { \n          solution_grads_u_total[q]  = 0.0; \n          solution_values_p_total[q] = 0.0; \n          solution_values_J_total[q] = 0.0; \n        } \n    } \n  }; \n// @sect4{Solid::make_grid}  \n\n// \u8fdb\u5165\u7b2c\u4e00\u4e2a\u79c1\u6709\u6210\u5458\u51fd\u6570\u3002\u5728\u8fd9\u91cc\u6211\u4eec\u521b\u5efa\u57df\u7684\u4e09\u89d2\u5f62\uff0c\u4e3a\u6b64\u6211\u4eec\u9009\u62e9\u4e86\u6309\u6bd4\u4f8b\u7684\u7acb\u65b9\u4f53\uff0c\u6bcf\u4e2a\u9762\u90fd\u6709\u4e00\u4e2a\u8fb9\u754cID\u53f7\u3002 \u5bf9\u4e8e\u7f29\u8fdb\u95ee\u9898\uff0c\u7f51\u683c\u5fc5\u987b\u81f3\u5c11\u88ab\u7ec6\u5316\u4e00\u6b21\u3002\n\n// \u7136\u540e\uff0c\u6211\u4eec\u786e\u5b9a\u53c2\u8003\u914d\u7f6e\u7684\u4f53\u79ef\uff0c\u5e76\u5c06\u5176\u6253\u5370\u51fa\u6765\u8fdb\u884c\u6bd4\u8f83\u3002\n\n  template <int dim> \n  void Solid<dim>::make_grid() \n  { \n    GridGenerator::hyper_rectangle( \n      triangulation, \n      (dim == 3 ? Point<dim>(0.0, 0.0, 0.0) : Point<dim>(0.0, 0.0)), \n      (dim == 3 ? Point<dim>(1.0, 1.0, 1.0) : Point<dim>(1.0, 1.0)), \n      true); \n    GridTools::scale(parameters.scale, triangulation); \n    triangulation.refine_global(std::max(1U, parameters.global_refinement)); \n\n    vol_reference = GridTools::volume(triangulation); \n    std::cout << \"Grid:\\n\\t Reference volume: \" << vol_reference << std::endl; \n\n// \u7531\u4e8e\u6211\u4eec\u5e0c\u671b\u5bf9\u9876\u9762\u7684\u4e00\u4e2a\u8865\u4e01\u5e94\u7528\u8bfa\u4f0a\u66fcBC\uff0c\u6211\u4eec\u5fc5\u987b\u627e\u5230\u57df\u7684\u8fd9\u4e00\u90e8\u5206\u7684\u5355\u5143\u683c\u9762\uff0c\u5e76\u7528\u4e00\u4e2a\u660e\u663e\u7684\u8fb9\u754cID\u53f7\u6765\u6807\u8bb0\u5b83\u4eec\u3002 \u6211\u4eec\u8981\u627e\u7684\u9762\u5728+y\u9762\u4e0a\uff0c\u5c06\u5f97\u5230\u8fb9\u754cID 6\uff080\u52305\u5df2\u7ecf\u5728\u521b\u5efa\u7acb\u65b9\u4f53\u57df\u7684\u516d\u4e2a\u9762\u65f6\u4f7f\u7528\u4e86\uff09\u3002\n\n    for (const auto &cell : triangulation.active_cell_iterators()) \n      for (const auto &face : cell->face_iterators()) \n        { \n          if (face->at_boundary() == true && \n              face->center()[1] == 1.0 * parameters.scale) \n            { \n              if (dim == 3) \n                { \n                  if (face->center()[0] < 0.5 * parameters.scale && \n                      face->center()[2] < 0.5 * parameters.scale) \n                    face->set_boundary_id(6); \n                } \n              else \n                { \n                  if (face->center()[0] < 0.5 * parameters.scale) \n                    face->set_boundary_id(6); \n                } \n            } \n        } \n  } \n// @sect4{Solid::system_setup}  \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u63cf\u8ff0FE\u7cfb\u7edf\u662f\u5982\u4f55\u8bbe\u7f6e\u7684\u3002 \u6211\u4eec\u9996\u5148\u786e\u5b9a\u6bcf\u5757\u7684\u5206\u91cf\u6570\u91cf\u3002\u7531\u4e8e\u4f4d\u79fb\u662f\u4e00\u4e2a\u77e2\u91cf\u5206\u91cf\uff0c\u6240\u4ee5\u524d\u4e24\u4e2a\u5206\u91cf\u5c5e\u4e8e\u5b83\uff0c\u800c\u540e\u4e24\u4e2a\u5206\u91cf\u63cf\u8ff0\u6807\u91cf\u538b\u529b\u548c\u6269\u5f20DOF\u3002\n\n  template <int dim> \n  void Solid<dim>::system_setup() \n  { \n    timer.enter_subsection(\"Setup system\"); \n\n    std::vector<unsigned int> block_component(n_components, \n                                              u_dof); // Displacement \n    block_component[p_component] = p_dof;             // Pressure \n    block_component[J_component] = J_dof;             // Dilatation \n\n// \u7136\u540e\uff0cDOF\u5904\u7406\u7a0b\u5e8f\u88ab\u521d\u59cb\u5316\uff0c\u6211\u4eec\u4ee5\u4e00\u79cd\u6709\u6548\u7684\u65b9\u5f0f\u5bf9\u7f51\u683c\u8fdb\u884c\u91cd\u65b0\u7f16\u53f7\u3002\u6211\u4eec\u8fd8\u8bb0\u5f55\u4e86\u6bcf\u5757DOF\u7684\u6570\u91cf\u3002\n\n    dof_handler.distribute_dofs(fe); \n    DoFRenumbering::Cuthill_McKee(dof_handler); \n    DoFRenumbering::component_wise(dof_handler, block_component); \n\n    dofs_per_block = \n      DoFTools::count_dofs_per_fe_block(dof_handler, block_component); \n\n    std::cout << \"Triangulation:\" \n              << \"\\n\\t Number of active cells: \" \n              << triangulation.n_active_cells() \n              << \"\\n\\t Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << std::endl; \n\n// \u8bbe\u7f6e\u7a00\u758f\u6a21\u5f0f\u548c\u5207\u7ebf\u77e9\u9635\n\n    tangent_matrix.clear(); \n    { \n      const types::global_dof_index n_dofs_u = dofs_per_block[u_dof]; \n      const types::global_dof_index n_dofs_p = dofs_per_block[p_dof]; \n      const types::global_dof_index n_dofs_J = dofs_per_block[J_dof]; \n\n      BlockDynamicSparsityPattern dsp(n_blocks, n_blocks); \n\n      dsp.block(u_dof, u_dof).reinit(n_dofs_u, n_dofs_u); \n      dsp.block(u_dof, p_dof).reinit(n_dofs_u, n_dofs_p); \n      dsp.block(u_dof, J_dof).reinit(n_dofs_u, n_dofs_J); \n\n      dsp.block(p_dof, u_dof).reinit(n_dofs_p, n_dofs_u); \n      dsp.block(p_dof, p_dof).reinit(n_dofs_p, n_dofs_p); \n      dsp.block(p_dof, J_dof).reinit(n_dofs_p, n_dofs_J); \n\n      dsp.block(J_dof, u_dof).reinit(n_dofs_J, n_dofs_u); \n      dsp.block(J_dof, p_dof).reinit(n_dofs_J, n_dofs_p); \n      dsp.block(J_dof, J_dof).reinit(n_dofs_J, n_dofs_J); \n      dsp.collect_sizes(); \n\n// \u5168\u5c40\u7cfb\u7edf\u77e9\u9635\u6700\u521d\u5177\u6709\u4ee5\u4e0b\u7ed3\u6784 \n// @f{align*}\n//  \\underbrace{\\begin{bmatrix}\n//    \\mathsf{\\mathbf{K}}_{uu}  & \\mathsf{\\mathbf{K}}_{u\\widetilde{p}} &\n//    \\mathbf{0}\n//    \\\\ \\mathsf{\\mathbf{K}}_{\\widetilde{p}u} & \\mathbf{0} &\n//    \\mathsf{\\mathbf{K}}_{\\widetilde{p}\\widetilde{J}}\n//    \\\\ \\mathbf{0} & \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{p}} &\n//    \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{J}}\n//  \\end{bmatrix}}_{\\mathsf{\\mathbf{K}}(\\mathbf{\\Xi}_{\\textrm{i}})}\n//       \\underbrace{\\begin{bmatrix}\n//           d \\mathsf{u}\n//       \\\\  d \\widetilde{\\mathsf{\\mathbf{p}}}\n//       \\\\  d \\widetilde{\\mathsf{\\mathbf{J}}}\n//       \\end{bmatrix}}_{d \\mathbf{\\Xi}}\n//  =\n//  \\underbrace{\\begin{bmatrix}\n//   \\mathsf{\\mathbf{F}}_{u}(\\mathbf{u}_{\\textrm{i}})\n//   \\\\ \\mathsf{\\mathbf{F}}_{\\widetilde{p}}(\\widetilde{p}_{\\textrm{i}})\n//   \\\\ \\mathsf{\\mathbf{F}}_{\\widetilde{J}}(\\widetilde{J}_{\\textrm{i}})\n// \\end{bmatrix}}_{ \\mathsf{\\mathbf{F}}(\\mathbf{\\Xi}_{\\textrm{i}}) } \\, .\n//  @f}\n//   \u6211\u4eec\u4f18\u5316\u7a00\u758f\u6a21\u5f0f\u4ee5\u53cd\u6620\u8fd9\u4e00\u7ed3\u6784\uff0c\u5e76\u9632\u6b62\u4e3a\u53f3\u5bf9\u89d2\u5757\u6210\u5206\u521b\u5efa\u4e0d\u5fc5\u8981\u7684\u6570\u636e\u3002\n\n      Table<2, DoFTools::Coupling> coupling(n_components, n_components); \n      for (unsigned int ii = 0; ii < n_components; ++ii) \n        for (unsigned int jj = 0; jj < n_components; ++jj) \n          if (((ii < p_component) && (jj == J_component)) || \n              ((ii == J_component) && (jj < p_component)) || \n              ((ii == p_component) && (jj == p_component))) \n            coupling[ii][jj] = DoFTools::none; \n          else \n            coupling[ii][jj] = DoFTools::always; \n      DoFTools::make_sparsity_pattern( \n        dof_handler, coupling, dsp, constraints, false); \n      sparsity_pattern.copy_from(dsp); \n    } \n\n    tangent_matrix.reinit(sparsity_pattern); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u8bbe\u7f6e\u4e86\u5b58\u50a8\u5411\u91cf\n\n    system_rhs.reinit(dofs_per_block); \n    system_rhs.collect_sizes(); \n\n    solution_n.reinit(dofs_per_block); \n    solution_n.collect_sizes(); \n\n// ...\u6700\u540e\u8bbe\u7f6e\u6b63\u4ea4\u70b9\u5386\u53f2\u3002\n\n    setup_qph(); \n\n    timer.leave_subsection(); \n  } \n//\u63a5\u4e0b\u6765\u6211\u4eec\u4eceFE\u7cfb\u7edf\u4e2d\u8ba1\u7b97\u51fa\u4e00\u4e9b\u4fe1\u606f\uff0c\u63cf\u8ff0\u54ea\u4e9b\u5c40\u90e8\u5143\u7d20DOF\u8fde\u63a5\u5230\u54ea\u4e2a\u5757\u7ec4\u4ef6\u4e0a\u3002 \u8fd9\u5c06\u5728\u540e\u9762\u7528\u4e8e\u4ece\u5168\u5c40\u77e9\u9635\u4e2d\u63d0\u53d6\u5b50\u5757\u3002\n\n// \u672c\u8d28\u4e0a\uff0c\u6211\u4eec\u6240\u9700\u8981\u7684\u5c31\u662f\u8ba9FES\u7cfb\u7edf\u5bf9\u8c61\u6307\u51fa\u53c2\u8003\u5355\u5143\u4e0a\u7684DOF\u8fde\u63a5\u5230\u54ea\u4e2a\u5757\u72b6\u90e8\u4ef6\u4e0a\u3002 \u76ee\u524d\uff0c\u63d2\u503c\u57df\u7684\u8bbe\u7f6e\u662f\u8fd9\u6837\u7684\uff1a0\u8868\u793a\u4f4d\u79fbDOF\uff0c1\u8868\u793a\u538b\u529bDOF\uff0c2\u8868\u793a\u81a8\u80c0DOF\u3002\n\n  template <int dim> \n  void Solid<dim>::determine_component_extractors() \n  { \n    element_indices_u.clear(); \n    element_indices_p.clear(); \n    element_indices_J.clear(); \n\n    for (unsigned int k = 0; k < fe.n_dofs_per_cell(); ++k) \n      { \n        const unsigned int k_group = fe.system_to_base_index(k).first.first; \n        if (k_group == u_dof) \n          element_indices_u.push_back(k); \n        else if (k_group == p_dof) \n          element_indices_p.push_back(k); \n        else if (k_group == J_dof) \n          element_indices_J.push_back(k); \n        else \n          { \n            Assert(k_group <= J_dof, ExcInternalError()); \n          } \n      } \n  } \n// @sect4{Solid::setup_qph}  \u7528\u4e8e\u5b58\u50a8\u6b63\u4ea4\u4fe1\u606f\u7684\u65b9\u6cd5\u5df2\u7ecf\u5728  step-18  \u4e2d\u63cf\u8ff0\u3002\u8fd9\u91cc\u6211\u4eec\u4e3aSMP\u673a\u5668\u5b9e\u73b0\u4e00\u4e2a\u7c7b\u4f3c\u7684\u8bbe\u7f6e\u3002\n\n// \u9996\u5148\uff0c\u5b9e\u9645\u7684QPH\u6570\u636e\u5bf9\u8c61\u88ab\u521b\u5efa\u3002\u8fd9\u5fc5\u987b\u5728\u7f51\u683c\u88ab\u7ec6\u5316\u5230\u6700\u7ec6\u7684\u7a0b\u5ea6\u540e\u624d\u80fd\u5b8c\u6210\u3002\n\n  template <int dim> \n  void Solid<dim>::setup_qph() \n  { \n    std::cout << \"    Setting up quadrature point data...\" << std::endl; \n\n    quadrature_point_history.initialize(triangulation.begin_active(), \n                                        triangulation.end(), \n                                        n_q_points); \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u8bbe\u7f6e\u521d\u59cb\u6b63\u4ea4\u70b9\u6570\u636e\u3002\u8bf7\u6ce8\u610f\uff0c\u5f53\u68c0\u7d22\u6b63\u4ea4\u70b9\u6570\u636e\u65f6\uff0c\u5b83\u5c06\u4f5c\u4e3a\u4e00\u4e2a\u667a\u80fd\u6307\u9488\u7684\u5411\u91cf\u8fd4\u56de\u3002\n\n    for (const auto &cell : triangulation.active_cell_iterators()) \n      { \n        const std::vector<std::shared_ptr<PointHistory<dim>>> lqph = \n          quadrature_point_history.get_data(cell); \n        Assert(lqph.size() == n_q_points, ExcInternalError()); \n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n          lqph[q_point]->setup_lqp(parameters); \n      } \n  } \n// @sect4{Solid::update_qph_incremental}  \u7531\u4e8eQP\u4fe1\u606f\u7684\u66f4\u65b0\u7ecf\u5e38\u53d1\u751f\uff0c\u5e76\u4e14\u6d89\u53ca\u4e00\u4e9b\u6602\u8d35\u7684\u64cd\u4f5c\uff0c\u6211\u4eec\u5b9a\u4e49\u4e86\u4e00\u4e2a\u591a\u7ebf\u7a0b\u7684\u65b9\u6cd5\uff0c\u5c06\u4efb\u52a1\u5206\u5e03\u5728\u4e00\u4e9bCPU\u6838\u5fc3\u4e0a\u3002\n\n// \u8981\u5f00\u59cb\u8fd9\u6837\u505a\uff0c\u9996\u5148\u6211\u4eec\u9700\u8981\u83b7\u5f97\u8fd9\u4e2a\u725b\u987f\u589e\u91cf\u65f6\u7684\u603b\u89e3\uff0c\u7136\u540e\u521b\u5efa\u521d\u59cb\u7684\u4ece\u5934\u5f00\u59cb\u7684\u526f\u672c\u548c\u590d\u5236\u6570\u636e\u5bf9\u8c61\u3002\n\n  template <int dim> \n  void \n  Solid<dim>::update_qph_incremental(const BlockVector<double> &solution_delta) \n  { \n    timer.enter_subsection(\"Update QPH data\"); \n    std::cout << \" UQPH \" << std::flush; \n\n    const BlockVector<double> solution_total( \n      get_total_solution(solution_delta)); \n\n    const UpdateFlags uf_UQPH(update_values | update_gradients); \n    PerTaskData_UQPH  per_task_data_UQPH; \n    ScratchData_UQPH  scratch_data_UQPH(fe, qf_cell, uf_UQPH, solution_total); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u5c06\u5b83\u4eec\u548c\u5355\u683c\u66f4\u65b0\u51fd\u6570\u4f20\u9012\u7ed9WorkStream\u8fdb\u884c\u5904\u7406\u3002\n\n    WorkStream::run(dof_handler.active_cell_iterators(), \n                    *this, \n                    &Solid::update_qph_incremental_one_cell, \n                    &Solid::copy_local_to_global_UQPH, \n                    scratch_data_UQPH, \n                    per_task_data_UQPH); \n\n    timer.leave_subsection(); \n  } \n\n// \u73b0\u5728\u6211\u4eec\u63cf\u8ff0\u4e00\u4e0b\u6211\u4eec\u5982\u4f55\u4ece\u89e3\u51b3\u65b9\u6848\u5411\u91cf\u4e2d\u63d0\u53d6\u6570\u636e\uff0c\u5e76\u5c06\u5176\u4f20\u9012\u7ed9\u6bcf\u4e2aQP\u5b58\u50a8\u5bf9\u8c61\u8fdb\u884c\u5904\u7406\u3002\n\n  template <int dim> \n  void Solid<dim>::update_qph_incremental_one_cell( \n    const typename DoFHandler<dim>::active_cell_iterator &cell, \n    ScratchData_UQPH &                                    scratch, \n    PerTaskData_UQPH & /*data*/) \n  { \n    const std::vector<std::shared_ptr<PointHistory<dim>>> lqph = \n      quadrature_point_history.get_data(cell); \n    Assert(lqph.size() == n_q_points, ExcInternalError()); \n\n    Assert(scratch.solution_grads_u_total.size() == n_q_points, \n           ExcInternalError()); \n    Assert(scratch.solution_values_p_total.size() == n_q_points, \n           ExcInternalError()); \n    Assert(scratch.solution_values_J_total.size() == n_q_points, \n           ExcInternalError()); \n\n    scratch.reset(); \n\n// \u6211\u4eec\u9996\u5148\u9700\u8981\u627e\u5230\u5f53\u524d\u5355\u5143\u5185\u6b63\u4ea4\u70b9\u7684\u6570\u503c\u548c\u68af\u5ea6\uff0c\u7136\u540e\u5229\u7528\u4f4d\u79fb\u68af\u5ea6\u548c\u603b\u538b\u529b\u53ca\u6269\u5f20\u89e3\u6570\u503c\u66f4\u65b0\u6bcf\u4e2a\u5c40\u90e8QP\u3002\n\n    scratch.fe_values.reinit(cell); \n    scratch.fe_values[u_fe].get_function_gradients( \n      scratch.solution_total, scratch.solution_grads_u_total); \n    scratch.fe_values[p_fe].get_function_values( \n      scratch.solution_total, scratch.solution_values_p_total); \n    scratch.fe_values[J_fe].get_function_values( \n      scratch.solution_total, scratch.solution_values_J_total); \n\n    for (const unsigned int q_point : \n         scratch.fe_values.quadrature_point_indices()) \n      lqph[q_point]->update_values(scratch.solution_grads_u_total[q_point], \n                                   scratch.solution_values_p_total[q_point], \n                                   scratch.solution_values_J_total[q_point]); \n  } \n// @sect4{Solid::solve_nonlinear_timestep}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u725b\u987f-\u62c9\u5f17\u900a\u65b9\u6848\u7684\u9a71\u52a8\u65b9\u6cd5\u3002\u5728\u5b83\u7684\u9876\u90e8\uff0c\u6211\u4eec\u521b\u5efa\u4e00\u4e2a\u65b0\u7684\u5411\u91cf\u6765\u5b58\u50a8\u5f53\u524d\u7684\u725b\u987f\u66f4\u65b0\u6b65\u9aa4\uff0c\u91cd\u7f6e\u9519\u8bef\u5b58\u50a8\u5bf9\u8c61\u5e76\u6253\u5370\u6c42\u89e3\u5668\u5934\u3002\n\n  template <int dim> \n  void Solid<dim>::solve_nonlinear_timestep(BlockVector<double> &solution_delta) \n  { \n    std::cout << std::endl \n              << \"Timestep \" << time.get_timestep() << \" @ \" << time.current() \n              << \"s\" << std::endl; \n\n    BlockVector<double> newton_update(dofs_per_block); \n\n    error_residual.reset(); \n    error_residual_0.reset(); \n    error_residual_norm.reset(); \n    error_update.reset(); \n    error_update_0.reset(); \n    error_update_norm.reset(); \n\n    print_conv_header(); \n\n// \u6211\u4eec\u73b0\u5728\u8fdb\u884c\u4e00\u4e9b\u725b\u987f\u8fed\u4ee3\u6765\u8fed\u4ee3\u89e3\u51b3\u8fd9\u4e2a\u975e\u7ebf\u6027\u95ee\u9898\u3002 \u7531\u4e8e\u95ee\u9898\u662f\u5b8c\u5168\u975e\u7ebf\u6027\u7684\uff0c\u800c\u4e14\u6211\u4eec\u4f7f\u7528\u7684\u662f\u5b8c\u5168\u725b\u987f\u65b9\u6cd5\uff0c\u6240\u4ee5\u5b58\u50a8\u5728\u5207\u7ebf\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u5411\u91cf\u4e2d\u7684\u6570\u636e\u662f\u4e0d\u80fd\u91cd\u590d\u4f7f\u7528\u7684\uff0c\u5fc5\u987b\u5728\u6bcf\u4e2a\u725b\u987f\u6b65\u9aa4\u4e2d\u6e05\u9664\u3002\u7136\u540e\uff0c\u6211\u4eec\u6700\u521d\u5efa\u7acb\u7ebf\u6027\u7cfb\u7edf\u5e76\u68c0\u67e5\u6536\u655b\u6027\uff08\u5e76\u5728\u7b2c\u4e00\u6b21\u8fed\u4ee3\u4e2d\u5b58\u50a8\u8fd9\u4e2a\u503c\uff09\u3002rhs\u5411\u91cf\u7684\u65e0\u7ea6\u675fDOF\u6301\u6709\u5931\u8861\u7684\u529b\uff0c\u5e76\u5171\u540c\u51b3\u5b9a\u662f\u5426\u8fbe\u5230\u4e86\u5e73\u8861\u89e3\u3002\n\n// \u5c3d\u7ba1\u5bf9\u4e8e\u8fd9\u4e2a\u7279\u5b9a\u7684\u95ee\u9898\uff0c\u6211\u4eec\u53ef\u4ee5\u5728\u7ec4\u5408\u7cfb\u7edf\u77e9\u9635\u4e4b\u524d\u6784\u5efaRHS\u5411\u91cf\uff0c\u4f46\u4e3a\u4e86\u6269\u5c55\u6027\uff0c\u6211\u4eec\u9009\u62e9\u4e0d\u8fd9\u6837\u505a\u3002\u5206\u522b\u7ec4\u88c5RHS\u5411\u91cf\u548c\u7cfb\u7edf\u77e9\u9635\u7684\u597d\u5904\u662f\uff0c\u540e\u8005\u662f\u4e00\u4e2a\u6602\u8d35\u7684\u64cd\u4f5c\uff0c\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u5728\u8fbe\u5230\u6536\u655b\u65f6\u4e0d\u7ec4\u88c5\u5207\u7ebf\u77e9\u9635\u6765\u907f\u514d\u4e00\u4e2a\u989d\u5916\u7684\u7ec4\u88c5\u8fc7\u7a0b\u3002\u7136\u800c\uff0c\u8fd9\u4f7f\u5f97\u4f7f\u7528MPI\u5e76\u884c\u5316\u4ee3\u7801\u53d8\u5f97\u66f4\u52a0\u56f0\u96be\u3002\u6b64\u5916\uff0c\u5f53\u628a\u95ee\u9898\u6269\u5c55\u5230\u77ac\u6001\u60c5\u51b5\u65f6\uff0c\u7531\u4e8e\u65f6\u95f4\u79bb\u6563\u5316\u548c\u5bf9\u901f\u5ea6\u548c\u52a0\u901f\u5ea6\u573a\u7684\u7ea6\u675f\u5e94\u7528\uff0c\u53ef\u80fd\u4f1a\u5bf9RHS\u4ea7\u751f\u989d\u5916\u7684\u8d21\u732e\u3002\n\n    unsigned int newton_iteration = 0; \n    for (; newton_iteration < parameters.max_iterations_NR; ++newton_iteration) \n      { \n        std::cout << \" \" << std::setw(2) << newton_iteration << \" \" \n                  << std::flush; \n\n// \u6211\u4eec\u6784\u5efa\u7ebf\u6027\u7cfb\u7edf\uff0c\u4f46\u6682\u4e0d\u6c42\u89e3\u5b83\uff08\u8fd9\u4e00\u6b65\u5e94\u8be5\u6bd4\u88c5\u914d\u8981\u8d35\u5f97\u591a\uff09\u3002\n\n        make_constraints(newton_iteration); \n        assemble_system(); \n\n// \u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u786e\u5b9a\u5f52\u4e00\u5316\u5269\u4f59\u8bef\u5dee\uff0c\u5e76\u68c0\u67e5\u89e3\u51b3\u65b9\u6848\u7684\u6536\u655b\u6027\u3002\n\n        get_error_residual(error_residual); \n        if (newton_iteration == 0) \n          error_residual_0 = error_residual; \n\n        error_residual_norm = error_residual; \n        error_residual_norm.normalize(error_residual_0); \n\n        if (newton_iteration > 0 && error_update_norm.u <= parameters.tol_u && \n            error_residual_norm.u <= parameters.tol_f) \n          { \n            std::cout << \" CONVERGED! \" << std::endl; \n            print_conv_footer(); \n\n            break; \n          } \n\n// \u5982\u679c\u6211\u4eec\u51b3\u5b9a\u8981\u7ee7\u7eed\u8fed\u4ee3\uff0c\u6211\u4eec\u5c31\u89e3\u51b3\u7ebf\u6027\u5316\u7cfb\u7edf\u3002\n\n        const std::pair<unsigned int, double> lin_solver_output = \n          solve_linear_system(newton_update); \n\n// \u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u786e\u5b9a\u5f52\u4e00\u5316\u7684\u725b\u987f\u66f4\u65b0\u8bef\u5dee\u3002\n\n        get_error_update(newton_update, error_update); \n        if (newton_iteration == 0) \n          error_update_0 = error_update; \n\n        error_update_norm = error_update; \n        error_update_norm.normalize(error_update_0); \n\n// \u6700\u540e\uff0c\u7531\u4e8e\u6211\u4eec\u9690\u542b\u5730\u63a5\u53d7\u4e86\u6c42\u89e3\u6b65\u9aa4\uff0c\u6211\u4eec\u53ef\u4ee5\u5bf9\u5f53\u524d\u65f6\u95f4\u6b65\u9aa4\u7684\u6c42\u89e3\u589e\u91cf\u8fdb\u884c\u5b9e\u9645\u66f4\u65b0\uff0c\u66f4\u65b0\u4e0e\u8fd9\u4e2a\u65b0\u4f4d\u79fb\u548c\u5e94\u529b\u72b6\u6001\u6709\u5173\u7684\u6240\u6709\u6b63\u4ea4\u70b9\u4fe1\u606f\uff0c\u5e76\u7ee7\u7eed\u8fed\u4ee3\u3002\n\n        solution_delta += newton_update; \n        update_qph_incremental(solution_delta); \n\n        std::cout << \" | \" << std::fixed << std::setprecision(3) << std::setw(7) \n                  << std::scientific << lin_solver_output.first << \"  \" \n                  << lin_solver_output.second << \"  \" \n                  << error_residual_norm.norm << \"  \" << error_residual_norm.u \n                  << \"  \" << error_residual_norm.p << \"  \" \n                  << error_residual_norm.J << \"  \" << error_update_norm.norm \n                  << \"  \" << error_update_norm.u << \"  \" << error_update_norm.p \n                  << \"  \" << error_update_norm.J << \"  \" << std::endl; \n      } \n\n// \u5728\u6700\u540e\uff0c\u5982\u679c\u53d1\u73b0\u6211\u4eec\u4e8b\u5b9e\u4e0a\u505a\u4e86\u6bd4\u53c2\u6570\u6587\u4ef6\u5141\u8bb8\u7684\u66f4\u591a\u7684\u8fed\u4ee3\uff0c\u6211\u4eec\u4f1a\u5f15\u53d1\u4e00\u4e2a\u5f02\u5e38\uff0c\u53ef\u4ee5\u5728main()\u51fd\u6570\u4e2d\u6355\u83b7\u3002\u8c03\u7528<code>AssertThrow(condition, exc_object)</code>\u5b9e\u8d28\u4e0a\u7b49\u540c\u4e8e<code>if (!cond) throw exc_object;</code>\uff0c\u4f46\u524d\u4e00\u79cd\u5f62\u5f0f\u5728\u5f02\u5e38\u5bf9\u8c61\u4e2d\u586b\u5145\u4e86\u67d0\u4e9b\u5b57\u6bb5\uff0c\u4ee5\u786e\u5b9a\u5f02\u5e38\u53d1\u751f\u7684\u4f4d\u7f6e\uff08\u6587\u4ef6\u540d\u548c\u884c\u53f7\uff09\uff0c\u4f7f\u4e4b\u66f4\u5bb9\u6613\u8bc6\u522b\u95ee\u9898\u53d1\u751f\u7684\u4f4d\u7f6e\u3002\n\n    AssertThrow(newton_iteration < parameters.max_iterations_NR, \n                ExcMessage(\"No convergence in nonlinear solver!\")); \n  } \n// @sect4{Solid::print_conv_header and Solid::print_conv_footer}  \n\n// \u8fd9\u4e2a\u7a0b\u5e8f\u5728\u4e00\u4e2a\u6f02\u4eae\u7684\u8868\u683c\u4e2d\u6253\u5370\u51fa\u6570\u636e\uff0c\u8fd9\u4e2a\u8868\u683c\u5728\u6bcf\u6b21\u8fed\u4ee3\u7684\u57fa\u7840\u4e0a\u88ab\u66f4\u65b0\u3002\u63a5\u4e0b\u6765\u7684\u4e24\u4e2a\u51fd\u6570\u8bbe\u7f6e\u4e86\u8868\u5934\u548c\u8868\u811a\u3002\n\n  template <int dim> \n  void Solid<dim>::print_conv_header() \n  { \n    static const unsigned int l_width = 150; \n\n    for (unsigned int i = 0; i < l_width; ++i) \n      std::cout << \"_\"; \n    std::cout << std::endl; \n\n    std::cout << \"               SOLVER STEP               \" \n              << \" |  LIN_IT   LIN_RES    RES_NORM    \" \n              << \" RES_U     RES_P      RES_J     NU_NORM     \" \n              << \" NU_U       NU_P       NU_J \" << std::endl; \n\n    for (unsigned int i = 0; i < l_width; ++i) \n      std::cout << \"_\"; \n    std::cout << std::endl; \n  } \n\n  template <int dim> \n  void Solid<dim>::print_conv_footer() \n  { \n    static const unsigned int l_width = 150; \n\n    for (unsigned int i = 0; i < l_width; ++i) \n      std::cout << \"_\"; \n    std::cout << std::endl; \n\n    const std::pair<double, double> error_dil = get_error_dilation(); \n\n    std::cout << \"Relative errors:\" << std::endl \n              << \"Displacement:\\t\" << error_update.u / error_update_0.u \n              << std::endl \n              << \"Force: \\t\\t\" << error_residual.u / error_residual_0.u \n              << std::endl \n              << \"Dilatation:\\t\" << error_dil.first << std::endl \n              << \"v / V_0:\\t\" << error_dil.second * vol_reference << \" / \" \n              << vol_reference << \" = \" << error_dil.second << std::endl; \n  } \n// @sect4{Solid::get_error_dilation}  \n\n// \u8ba1\u7b97\u7a7a\u95f4\u914d\u7f6e\u4e2d\u7684\u57df\u7684\u4f53\u79ef\n\n  template <int dim> \n  double Solid<dim>::compute_vol_current() const \n  { \n    double vol_current = 0.0; \n\n    FEValues<dim> fe_values(fe, qf_cell, update_JxW_values); \n\n    for (const auto &cell : triangulation.active_cell_iterators()) \n      { \n        fe_values.reinit(cell); \n\n// \u4e0e\u4e4b\u524d\u8c03\u7528\u7684\u4e0d\u540c\uff0c\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u6b63\u4ea4\u70b9\u7684\u6570\u636e\u662f\u7279\u522b\u4e0d\u53ef\u4fee\u6539\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u5c06\u53ea\u8bbf\u95ee\u6570\u636e\u3002\u6211\u4eec\u901a\u8fc7\u5c06\u8fd9\u4e2a\u66f4\u65b0\u51fd\u6570\u6807\u8bb0\u4e3a\u5e38\u91cf\u6765\u786e\u4fdd\u6b63\u786e\u7684get_data\u51fd\u6570\u88ab\u8c03\u7528\u3002\n\n        const std::vector<std::shared_ptr<const PointHistory<dim>>> lqph = \n          quadrature_point_history.get_data(cell); \n        Assert(lqph.size() == n_q_points, ExcInternalError()); \n\n        for (const unsigned int q_point : fe_values.quadrature_point_indices()) \n          { \n            const double det_F_qp = lqph[q_point]->get_det_F(); \n            const double JxW      = fe_values.JxW(q_point); \n\n            vol_current += det_F_qp * JxW; \n          } \n      } \n    Assert(vol_current > 0.0, ExcInternalError()); \n    return vol_current; \n  } \n\n//\u4ece $L^2$ \u7684\u8bef\u5dee $ \\bigl[ \\int_{\\Omega_0} {[ J - \\widetilde{J}]}^{2}\\textrm{d}V \\bigr]^{1/2}$ \u4e2d\u8ba1\u7b97\u51fa\u6269\u5f20 $\\widetilde{J}$ $J \\dealcoloneq \\textrm{det}\\ \\mathbf{F}$ \u7684\u543b\u5408\u7a0b\u5ea6\u3002\u6211\u4eec\u8fd8\u8fd4\u56de\u57df\u7684\u5f53\u524d\u4f53\u79ef\u4e0e\u53c2\u8003\u4f53\u79ef\u7684\u6bd4\u7387\u3002\u8fd9\u5bf9\u4e8e\u4e0d\u53ef\u538b\u7f29\u4ecb\u8d28\u6765\u8bf4\u662f\u5f88\u6709\u610f\u4e49\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u8981\u68c0\u67e5\u7b49\u71b5\u7ea6\u675f\u7684\u6267\u884c\u60c5\u51b5\u3002\n\n  template <int dim> \n  std::pair<double, double> Solid<dim>::get_error_dilation() const \n  { \n    double dil_L2_error = 0.0; \n\n    FEValues<dim> fe_values(fe, qf_cell, update_JxW_values); \n\n    for (const auto &cell : triangulation.active_cell_iterators()) \n      { \n        fe_values.reinit(cell); \n\n        const std::vector<std::shared_ptr<const PointHistory<dim>>> lqph = \n          quadrature_point_history.get_data(cell); \n        Assert(lqph.size() == n_q_points, ExcInternalError()); \n\n        for (const unsigned int q_point : fe_values.quadrature_point_indices()) \n          { \n            const double det_F_qp   = lqph[q_point]->get_det_F(); \n            const double J_tilde_qp = lqph[q_point]->get_J_tilde(); \n            const double the_error_qp_squared = \n              std::pow((det_F_qp - J_tilde_qp), 2); \n            const double JxW = fe_values.JxW(q_point); \n\n            dil_L2_error += the_error_qp_squared * JxW; \n          } \n      } \n\n    return std::make_pair(std::sqrt(dil_L2_error), \n                          compute_vol_current() / vol_reference); \n  } \n// @sect4{Solid::get_error_residual}  \n\n// \u786e\u5b9a\u95ee\u9898\u7684\u771f\u5b9e\u6b8b\u5dee\u8bef\u5dee\u3002 \u4e5f\u5c31\u662f\u8bf4\uff0c\u786e\u5b9a\u65e0\u7ea6\u675f\u81ea\u7531\u5ea6\u7684\u6b8b\u5dee\u8bef\u5dee\u3002 \u6ce8\u610f\uff0c\u8981\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u9700\u8981\u5ffd\u7565\u53d7\u7ea6\u675f\u7684\u81ea\u7531\u5ea6\uff0c\u5c06\u8fd9\u4e9b\u5411\u91cf\u5206\u91cf\u7684\u6b8b\u5dee\u8bbe\u7f6e\u4e3a\u96f6\u3002\n\n  template <int dim> \n  void Solid<dim>::get_error_residual(Errors &error_residual) \n  { \n    BlockVector<double> error_res(dofs_per_block); \n\n    for (unsigned int i = 0; i < dof_handler.n_dofs(); ++i) \n      if (!constraints.is_constrained(i)) \n        error_res(i) = system_rhs(i); \n\n    error_residual.norm = error_res.l2_norm(); \n    error_residual.u    = error_res.block(u_dof).l2_norm(); \n    error_residual.p    = error_res.block(p_dof).l2_norm(); \n    error_residual.J    = error_res.block(J_dof).l2_norm(); \n  } \n// @sect4{Solid::get_error_update}  \n\n// \u786e\u5b9a\u95ee\u9898\u7684\u771f\u5b9e\u725b\u987f\u66f4\u65b0\u8bef\u5dee\n\n  template <int dim> \n  void Solid<dim>::get_error_update(const BlockVector<double> &newton_update, \n                                    Errors &                   error_update) \n  { \n    BlockVector<double> error_ud(dofs_per_block); \n    for (unsigned int i = 0; i < dof_handler.n_dofs(); ++i) \n      if (!constraints.is_constrained(i)) \n        error_ud(i) = newton_update(i); \n\n    error_update.norm = error_ud.l2_norm(); \n    error_update.u    = error_ud.block(u_dof).l2_norm(); \n    error_update.p    = error_ud.block(p_dof).l2_norm(); \n    error_update.J    = error_ud.block(J_dof).l2_norm(); \n  } \n\n//  @sect4{Solid::get_total_solution}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u63d0\u4f9b\u4e86\u603b\u89e3\uff0c\u5b83\u5728\u4efb\u4f55\u725b\u987f\u6b65\u90fd\u6709\u6548\u3002\u8fd9\u662f\u5fc5\u987b\u7684\uff0c\u56e0\u4e3a\u4e3a\u4e86\u51cf\u5c11\u8ba1\u7b97\u8bef\u5dee\uff0c\u603b\u89e3\u53ea\u5728\u65f6\u95f4\u6b65\u6570\u7ed3\u675f\u65f6\u66f4\u65b0\u3002\n\n  template <int dim> \n  BlockVector<double> Solid<dim>::get_total_solution( \n    const BlockVector<double> &solution_delta) const \n  { \n    BlockVector<double> solution_total(solution_n); \n    solution_total += solution_delta; \n    return solution_total; \n  } \n// @sect4{Solid::assemble_system}  \n\n// \u7531\u4e8e\u6211\u4eec\u4f7f\u7528TBB\u8fdb\u884c\u88c5\u914d\uff0c\u6211\u4eec\u53ea\u9700\u8bbe\u7f6e\u4e00\u4efd\u6d41\u7a0b\u6240\u9700\u7684\u6570\u636e\u7ed3\u6784\uff0c\u5e76\u5c06\u5176\u4e0e\u88c5\u914d\u51fd\u6570\u4e00\u8d77\u4f20\u9012\u7ed9WorkStream\u5bf9\u8c61\u8fdb\u884c\u5904\u7406\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u5fc5\u987b\u786e\u4fdd\u5728\u4efb\u4f55\u88c5\u914d\u64cd\u4f5c\u53d1\u751f\u4e4b\u524d\uff0c\u77e9\u9635\u548cRHS\u5411\u91cf\u88ab\u91cd\u7f6e\u3002\u6b64\u5916\uff0c\u7531\u4e8e\u6211\u4eec\u63cf\u8ff0\u7684\u662f\u4e00\u4e2a\u8bfa\u4f0a\u66fcBC\u7684\u95ee\u9898\uff0c\u6211\u4eec\u5c06\u9700\u8981\u9762\u7684\u6cd5\u7ebf\uff0c\u56e0\u6b64\u5fc5\u987b\u5728\u9762\u7684\u66f4\u65b0\u6807\u5fd7\u4e2d\u6307\u5b9a\u8fd9\u4e2a\u3002\n\n  template <int dim> \n  void Solid<dim>::assemble_system() \n  { \n    timer.enter_subsection(\"Assemble system\"); \n    std::cout << \" ASM_SYS \" << std::flush; \n\n    tangent_matrix = 0.0; \n    system_rhs     = 0.0; \n\n    const UpdateFlags uf_cell(update_values | update_gradients | \n                              update_JxW_values); \n    const UpdateFlags uf_face(update_values | update_normal_vectors | \n                              update_JxW_values); \n\n    PerTaskData_ASM per_task_data(dofs_per_cell); \n    ScratchData_ASM scratch_data(fe, qf_cell, uf_cell, qf_face, uf_face); \n\n// \u8fd9\u91cc\u7528\u4e8e\u5411WorkStream\u7c7b\u4f20\u9012\u6570\u636e\u7684\u8bed\u6cd5\u5728  step-13  \u4e2d\u8ba8\u8bba\u3002\n\n    WorkStream::run( \n      dof_handler.active_cell_iterators(), \n      [this](const typename DoFHandler<dim>::active_cell_iterator &cell, \n             ScratchData_ASM &                                     scratch, \n             PerTaskData_ASM &                                     data) { \n        this->assemble_system_one_cell(cell, scratch, data); \n      }, \n      [this](const PerTaskData_ASM &data) { \n        this->constraints.distribute_local_to_global(data.cell_matrix, \n                                                     data.cell_rhs, \n                                                     data.local_dof_indices, \n                                                     tangent_matrix, \n                                                     system_rhs); \n      }, \n      scratch_data, \n      per_task_data); \n\n    timer.leave_subsection(); \n  } \n\n// \u5f53\u7136\uff0c\u6211\u4eec\u4ecd\u7136\u8981\u5b9a\u4e49\u5982\u4f55\u7ec4\u88c5\u5355\u4e2a\u5355\u5143\u7684\u5207\u7ebf\u77e9\u9635\u8d21\u732e\u3002 \u6211\u4eec\u9996\u5148\u9700\u8981\u91cd\u7f6e\u548c\u521d\u59cb\u5316\u4e00\u4e9b\u4ece\u5934\u5f00\u59cb\u7684\u6570\u636e\u7ed3\u6784\uff0c\u5e76\u68c0\u7d22\u4e00\u4e9b\u5173\u4e8e\u8fd9\u4e2a\u5355\u5143\u4e0aDOF\u7f16\u53f7\u7684\u57fa\u672c\u4fe1\u606f\u3002 \u6211\u4eec\u53ef\u4ee5\u9884\u5148\u8ba1\u7b97\u5355\u5143\u7684\u5f62\u72b6\u51fd\u6570\u503c\u548c\u68af\u5ea6\u3002\u8bf7\u6ce8\u610f\uff0c\u5f62\u72b6\u51fd\u6570\u68af\u5ea6\u662f\u6839\u636e\u5f53\u524d\u914d\u7f6e\u6765\u5b9a\u4e49\u7684\u3002 \u4e5f\u5c31\u662f  $\\textrm{grad}\\ \\boldsymbol{\\varphi} = \\textrm{Grad}\\ \\boldsymbol{\\varphi} \\ \\mathbf{F}^{-1}$  \u3002\n\n  template <int dim> \n  void Solid<dim>::assemble_system_one_cell( \n    const typename DoFHandler<dim>::active_cell_iterator &cell, \n    ScratchData_ASM &                                     scratch, \n    PerTaskData_ASM &                                     data) const \n  { \n    data.reset(); \n    scratch.reset(); \n    scratch.fe_values.reinit(cell); \n    cell->get_dof_indices(data.local_dof_indices); \n\n    const std::vector<std::shared_ptr<const PointHistory<dim>>> lqph = \n      quadrature_point_history.get_data(cell); \n    Assert(lqph.size() == n_q_points, ExcInternalError()); \n\n    for (const unsigned int q_point : \n         scratch.fe_values.quadrature_point_indices()) \n      { \n        const Tensor<2, dim> F_inv = lqph[q_point]->get_F_inv(); \n        for (const unsigned int k : scratch.fe_values.dof_indices()) \n          { \n            const unsigned int k_group = fe.system_to_base_index(k).first.first; \n\n            if (k_group == u_dof) \n              { \n                scratch.grad_Nx[q_point][k] = \n                  scratch.fe_values[u_fe].gradient(k, q_point) * F_inv; \n                scratch.symm_grad_Nx[q_point][k] = \n                  symmetrize(scratch.grad_Nx[q_point][k]); \n              } \n            else if (k_group == p_dof) \n              scratch.Nx[q_point][k] = \n                scratch.fe_values[p_fe].value(k, q_point); \n            else if (k_group == J_dof) \n              scratch.Nx[q_point][k] = \n                scratch.fe_values[J_fe].value(k, q_point); \n            else \n              Assert(k_group <= J_dof, ExcInternalError()); \n          } \n      } \n\n// \u73b0\u5728\u6211\u4eec\u5efa\u7acb\u672c\u5730\u5355\u5143\u521a\u5ea6\u77e9\u9635\u548cRHS\u5411\u91cf\u3002\u7531\u4e8e\u5168\u5c40\u548c\u5c40\u90e8\u7cfb\u7edf\u77e9\u9635\u662f\u5bf9\u79f0\u7684\uff0c\u6211\u4eec\u53ef\u4ee5\u5229\u7528\u8fd9\u4e00\u7279\u6027\uff0c\u53ea\u5efa\u7acb\u5c40\u90e8\u77e9\u9635\u7684\u4e0b\u534a\u90e8\u5206\uff0c\u5e76\u5c06\u5176\u503c\u590d\u5236\u5230\u4e0a\u534a\u90e8\u5206\u3002 \u6240\u4ee5\u6211\u4eec\u53ea\u7ec4\u88c5\u4e00\u534a\u7684 $\\mathsf{\\mathbf{k}}_{uu}$  ,  $\\mathsf{\\mathbf{k}}_{\\widetilde{p} \\widetilde{p}} = \\mathbf{0}$  ,  $\\mathsf{\\mathbf{k}}_{\\widetilde{J} \\widetilde{J}}$ \u5757\uff0c\u800c\u6574\u4e2a $\\mathsf{\\mathbf{k}}_{\\widetilde{p} \\widetilde{J}}$  ,  $\\mathsf{\\mathbf{k}}_{u \\widetilde{J}} = \\mathbf{0}$  ,  $\\mathsf{\\mathbf{k}}_{u \\widetilde{p}}$ \u5757\u88ab\u6784\u5efa\u3002\n\n// \u5728\u8fd9\u6837\u505a\u7684\u65f6\u5019\uff0c\u6211\u4eec\u9996\u5148\u4ece\u6211\u4eec\u7684\u6b63\u4ea4\u5386\u53f2\u5bf9\u8c61\u4e2d\u63d0\u53d6\u4e00\u4e9b\u914d\u7f6e\u76f8\u5173\u7684\u53d8\u91cf\uff0c\u7528\u4e8e\u5f53\u524d\u7684\u6b63\u4ea4\u70b9\u3002\n\n    for (const unsigned int q_point : \n         scratch.fe_values.quadrature_point_indices()) \n      { \n        const SymmetricTensor<2, dim> tau     = lqph[q_point]->get_tau(); \n        const Tensor<2, dim>          tau_ns  = lqph[q_point]->get_tau(); \n        const SymmetricTensor<4, dim> Jc      = lqph[q_point]->get_Jc(); \n        const double                  det_F   = lqph[q_point]->get_det_F(); \n        const double                  p_tilde = lqph[q_point]->get_p_tilde(); \n        const double                  J_tilde = lqph[q_point]->get_J_tilde(); \n        const double dPsi_vol_dJ   = lqph[q_point]->get_dPsi_vol_dJ(); \n        const double d2Psi_vol_dJ2 = lqph[q_point]->get_d2Psi_vol_dJ2(); \n        const SymmetricTensor<2, dim> &I = \n          Physics::Elasticity::StandardTensors<dim>::I; \n\n// \u8fd9\u4e24\u4e2a\u5f20\u91cf\u5b58\u50a8\u4e86\u4e00\u4e9b\u9884\u8ba1\u7b97\u7684\u6570\u636e\u3002\u5b83\u4eec\u7684\u7528\u9014\u5c06\u5f88\u5feb\u5f97\u5230\u89e3\u91ca\u3002\n\n        SymmetricTensor<2, dim> symm_grad_Nx_i_x_Jc; \n        Tensor<1, dim>          grad_Nx_i_comp_i_x_tau; \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u5b9a\u4e49\u4e00\u4e9b\u522b\u540d\uff0c\u4f7f\u88c5\u914d\u8fc7\u7a0b\u66f4\u5bb9\u6613\u64cd\u4f5c\u3002\n\n        const std::vector<double> &                 N = scratch.Nx[q_point]; \n        const std::vector<SymmetricTensor<2, dim>> &symm_grad_Nx = \n          scratch.symm_grad_Nx[q_point]; \n        const std::vector<Tensor<2, dim>> &grad_Nx = scratch.grad_Nx[q_point]; \n        const double                       JxW = scratch.fe_values.JxW(q_point); \n\n        for (const unsigned int i : scratch.fe_values.dof_indices()) \n          { \n            const unsigned int component_i = \n              fe.system_to_component_index(i).first; \n            const unsigned int i_group = fe.system_to_base_index(i).first.first; \n\n// \u6211\u4eec\u9996\u5148\u8ba1\u7b97\u6765\u81ea\u5185\u529b\u7684\u8d21\u732e\u3002 \u6ce8\u610f\uff0c\u6839\u636erhs\u4f5c\u4e3a\u6b8b\u5dee\u8d1f\u6570\u7684\u5b9a\u4e49\uff0c\u8fd9\u4e9b\u8d21\u732e\u88ab\u51cf\u53bb\u3002\n\n            if (i_group == u_dof) \n              data.cell_rhs(i) -= (symm_grad_Nx[i] * tau) * JxW; \n            else if (i_group == p_dof) \n              data.cell_rhs(i) -= N[i] * (det_F - J_tilde) * JxW; \n            else if (i_group == J_dof) \n              data.cell_rhs(i) -= N[i] * (dPsi_vol_dJ - p_tilde) * JxW; \n            else \n              Assert(i_group <= J_dof, ExcInternalError()); \n\n// \u5728\u6211\u4eec\u8fdb\u5165\u5185\u5faa\u73af\u4e4b\u524d\uff0c\u6211\u4eec\u8fd8\u6709\u6700\u540e\u4e00\u6b21\u673a\u4f1a\u6765\u5f15\u5165\u4e00\u4e9b\u4f18\u5316\u3002\u6211\u4eec\u5df2\u7ecf\u8003\u8651\u5230\u4e86\u7cfb\u7edf\u7684\u5bf9\u79f0\u6027\uff0c\u73b0\u5728\u6211\u4eec\u53ef\u4ee5\u9884\u5148\u8ba1\u7b97\u4e00\u4e9b\u5728\u5185\u5faa\u73af\u4e2d\u53cd\u590d\u5e94\u7528\u7684\u5e38\u7528\u9879\u3002  \u6211\u4eec\u5728\u8fd9\u91cc\u4e0d\u4f1a\u8fc7\u5206\uff0c\u800c\u662f\u5c06\u91cd\u70b9\u653e\u5728\u6602\u8d35\u7684\u64cd\u4f5c\u4e0a\uff0c\u5373\u90a3\u4e9b\u6d89\u53ca\u7b49\u7ea74\u6750\u6599\u521a\u5ea6\u5f20\u91cf\u548c\u7b49\u7ea72\u5e94\u529b\u5f20\u91cf\u7684\u64cd\u4f5c\u3002    \u6211\u4eec\u53ef\u4ee5\u89c2\u5bdf\u5230\u7684\u662f\uff0c\u8fd9\u4e24\u4e2a\u5f20\u91cf\u90fd\u662f\u4ee5 \"i \"DoF\u4e3a\u7d22\u5f15\u7684\u5f62\u72b6\u51fd\u6570\u68af\u5ea6\u6536\u7f29\u7684\u3002\u8fd9\u610f\u5473\u7740\uff0c\u5f53\u6211\u4eec\u5728 \"j \"DoF\u4e0a\u5faa\u73af\u65f6\uff0c\u8fd9\u4e2a\u7279\u6b8a\u7684\u64cd\u4f5c\u4fdd\u6301\u4e0d\u53d8\u3002\u51fa\u4e8e\u8fd9\u4e2a\u539f\u56e0\uff0c\u6211\u4eec\u53ef\u4ee5\u4ece\u5185\u5faa\u73af\u4e2d\u63d0\u53d6\u8fd9\u4e2a\u64cd\u4f5c\uff0c\u5e76\u8282\u7701\u8bb8\u591a\u64cd\u4f5c\uff0c\u5bf9\u4e8e\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u548cDoF\u7d22\u5f15 \"i\"\uff0c\u5e76\u5728\u7d22\u5f15 \"j \"\u4e0a\u91cd\u590d\uff0c\u9700\u8981\u7528\u7b49\u7ea74\u5bf9\u79f0\u5f20\u91cf\u5bf9\u7b49\u7ea72\u5bf9\u79f0\u5f20\u91cf\u8fdb\u884c\u53cc\u91cd\u6536\u7f29\uff0c\u7528\u7b49\u7ea72\u5f20\u91cf\u5bf9\u7b49\u7ea71\u5f20\u91cf\u8fdb\u884c\u53cc\u91cd\u6536\u7f29\u3002    \u5728\u635f\u5931\u4e00\u4e9b\u53ef\u8bfb\u6027\u7684\u60c5\u51b5\u4e0b\uff0c\u5f53\u4f7f\u7528\u6a21\u62df\u9ed8\u8ba4\u53c2\u6570\u65f6\uff0c\u8fd9\u4e2a\u5c0f\u53d8\u5316\u5c06\u4f7f\u5bf9\u79f0\u7cfb\u7edf\u7684\u88c5\u914d\u65f6\u95f4\u51cf\u5c11\u4e00\u534a\u5de6\u53f3\uff0c\u5e76\u4e14\u968f\u7740h-\u7ec6\u5316\u6c34\u5e73\u7684\u63d0\u9ad8\u800c\u53d8\u5f97\u66f4\u52a0\u663e\u8457\u3002\n\n            if (i_group == u_dof) \n              { \n                symm_grad_Nx_i_x_Jc    = symm_grad_Nx[i] * Jc; \n                grad_Nx_i_comp_i_x_tau = grad_Nx[i][component_i] * tau_ns; \n              } \n\n// \u73b0\u5728\u6211\u4eec\u51c6\u5907\u8ba1\u7b97\u6b63\u5207\u77e9\u9635\u7684\u8d21\u732e\u3002\n\n            for (const unsigned int j : \n                 scratch.fe_values.dof_indices_ending_at(i)) \n              { \n                const unsigned int component_j = \n                  fe.system_to_component_index(j).first; \n                const unsigned int j_group = \n                  fe.system_to_base_index(j).first.first; \n\n// \u8fd9\u5c31\u662f $\\mathsf{\\mathbf{k}}_{uu}$ \u7684\u8d21\u732e\u3002\u5b83\u5305\u62ec\u4e00\u4e2a\u6750\u6599\u8d21\u732e\u548c\u4e00\u4e2a\u51e0\u4f55\u5e94\u529b\u8d21\u732e\uff0c\u540e\u8005\u53ea\u6cbf\u5c40\u90e8\u77e9\u9635\u5bf9\u89d2\u7ebf\u6dfb\u52a0\u3002\n\n                if ((i_group == j_group) && (i_group == u_dof)) \n                  { \n\n// \u6750\u6599\u8d21\u732e\u3002\n\n                    data.cell_matrix(i, j) += symm_grad_Nx_i_x_Jc *  // \n                                              symm_grad_Nx[j] * JxW; // \n\n// \u51e0\u4f55\u5e94\u529b\u7684\u8d21\u732e\u3002\n\n                    if (component_i == component_j) \n                      data.cell_matrix(i, j) += \n                        grad_Nx_i_comp_i_x_tau * grad_Nx[j][component_j] * JxW; \n                  } \n\n// \u63a5\u4e0b\u6765\u662f $\\mathsf{\\mathbf{k}}_{ \\widetilde{p} u}$ \u7684\u8d21\u732e\u3002\n\n                else if ((i_group == p_dof) && (j_group == u_dof)) \n                  { \n                    data.cell_matrix(i, j) += N[i] * det_F *               // \n                                              (symm_grad_Nx[j] * I) * JxW; // \n                  } \n\n// \u6700\u540e\u662f  $\\mathsf{\\mathbf{k}}_{ \\widetilde{J \\widetilde{p}}$  \u548c  $\\mathsf{\\mathbf{k}}_{ \\widetilde{J} \\widetilde{J}}$  \u7684\u8d21\u732e\u3002\n\n                else if ((i_group == J_dof) && (j_group == p_dof)) \n                  data.cell_matrix(i, j) -= N[i] * N[j] * JxW; \n                else if ((i_group == j_group) && (i_group == J_dof)) \n                  data.cell_matrix(i, j) += N[i] * d2Psi_vol_dJ2 * N[j] * JxW; \n                else \n                  Assert((i_group <= J_dof) && (j_group <= J_dof), \n                         ExcInternalError()); \n              } \n          } \n      } \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u7ec4\u88c5\u8bfa\u4f0a\u66fc\u8d21\u732e\u3002\u6211\u4eec\u9996\u5148\u68c0\u67e5\u5355\u5143\u683c\u9762\u662f\u5426\u5b58\u5728\u4e8e\u65bd\u52a0\u4e86\u7275\u5f15\u529b\u7684\u8fb9\u754c\u4e0a\uff0c\u5982\u679c\u662f\u8fd9\u6837\u7684\u8bdd\uff0c\u5c31\u52a0\u5165\u8d21\u732e\u3002\n\n    for (const auto &face : cell->face_iterators()) \n      if (face->at_boundary() && face->boundary_id() == 6) \n        { \n          scratch.fe_face_values.reinit(cell, face); \n\n          for (const unsigned int f_q_point : \n               scratch.fe_face_values.quadrature_point_indices()) \n            { \n              const Tensor<1, dim> &N = \n                scratch.fe_face_values.normal_vector(f_q_point); \n\n// \u4f7f\u7528\u8be5\u6b63\u4ea4\u70b9\u7684\u9762\u6cd5\u7ebf\uff0c\u6211\u4eec\u6307\u5b9a\u53c2\u8003\u914d\u7f6e\u4e2d\u7684\u7275\u5f15\u529b\u3002\u5bf9\u4e8e\u8fd9\u4e2a\u95ee\u9898\uff0c\u5728\u53c2\u8003\u914d\u7f6e\u4e2d\u5e94\u7528\u4e86\u4e00\u4e2a\u5b9a\u4e49\u7684\u538b\u529b\u3002    \u5047\u8bbe\u65bd\u52a0\u7684\u7275\u5f15\u529b\u7684\u65b9\u5411\u4e0d\u968f\u9886\u57df\u7684\u53d8\u5f62\u800c\u53d8\u5316\u3002\u7275\u5f15\u529b\u662f\u7528\u7b2c\u4e00\u4e2aPiola-Kirchhoff\u5e94\u529b\u7b80\u5355\u5730\u5b9a\u4e49\u7684 $\\mathbf{t} = \\mathbf{P}\\mathbf{N} = [p_0 \\mathbf{I}] \\mathbf{N} = p_0 \\mathbf{N}$ \u6211\u4eec\u7528\u65f6\u95f4\u53d8\u91cf\u6765\u7ebf\u6027\u63d0\u5347\u538b\u529b\u8d1f\u8377\u3002        \u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u8ba1\u7b97\u7684\u5bf9\u53f3\u624b\u8fb9\u5411\u91cf\u7684\u8d21\u732e\u53ea\u5b58\u5728\u4e8e\u5411\u91cf\u7684\u4f4d\u79fb\u5206\u91cf\u4e2d\u3002\n\n              static const double p0 = \n                -4.0 / (parameters.scale * parameters.scale); \n              const double         time_ramp = (time.current() / time.end()); \n              const double         pressure  = p0 * parameters.p_p0 * time_ramp; \n              const Tensor<1, dim> traction  = pressure * N; \n\n              for (const unsigned int i : scratch.fe_values.dof_indices()) \n                { \n                  const unsigned int i_group = \n                    fe.system_to_base_index(i).first.first; \n\n                  if (i_group == u_dof) \n                    { \n                      const unsigned int component_i = \n                        fe.system_to_component_index(i).first; \n                      const double Ni = \n                        scratch.fe_face_values.shape_value(i, f_q_point); \n                      const double JxW = scratch.fe_face_values.JxW(f_q_point); \n\n                      data.cell_rhs(i) += (Ni * traction[component_i]) * JxW; \n                    } \n                } \n            } \n        } \n\n// \u6700\u540e\uff0c\u6211\u4eec\u9700\u8981\u5c06\u672c\u5730\u77e9\u9635\u7684\u4e0b\u534a\u90e8\u5206\u590d\u5236\u5230\u4e0a\u534a\u90e8\u5206\u3002\n\n    for (const unsigned int i : scratch.fe_values.dof_indices()) \n      for (const unsigned int j : \n           scratch.fe_values.dof_indices_starting_at(i + 1)) \n        data.cell_matrix(i, j) = data.cell_matrix(j, i); \n  } \n\n//  @sect4{Solid::make_constraints}  \u8fd9\u4e2a\u95ee\u9898\u7684\u7ea6\u675f\u6761\u4ef6\u5f88\u5bb9\u6613\u63cf\u8ff0\u3002\u5728\u8fd9\u4e2a\u7279\u6b8a\u7684\u4f8b\u5b50\u4e2d\uff0c\u8fb9\u754c\u503c\u5c06\u88ab\u8ba1\u7b97\u4e3a\u725b\u987f\u7b97\u6cd5\u7684\u4e24\u6b21\u7b2c\u4e00\u6b21\u8fed\u4ee3\u3002\u4e00\u822c\u6765\u8bf4\uff0c\u6211\u4eec\u4f1a\u5728\u7b2c2\u6b21\u8fed\u4ee3\u4e2d\u5efa\u7acb\u975e\u5747\u8d28\u7ea6\u675f\uff08\u4e5f\u5c31\u662f\u5728\u540e\u9762\u7684\u4ee3\u7801\u5757\u4e2d`apply_dirichlet_bc == true`\u65f6\uff09\uff0c\u5728\u63a5\u4e0b\u6765\u7684\u6b65\u9aa4\u4e2d\u53ea\u5efa\u7acb\u76f8\u5e94\u7684\u5747\u8d28\u7ea6\u675f\u3002\u867d\u7136\u76ee\u524d\u7684\u4f8b\u5b50\u53ea\u6709\u540c\u8d28\u7ea6\u675f\uff0c\u4f46\u4ee5\u524d\u7684\u7ecf\u9a8c\u8868\u660e\uff0c\u4e00\u4e2a\u5e38\u89c1\u7684\u9519\u8bef\u662f\u5728\u91cd\u6784\u4ee3\u7801\u5230\u7279\u5b9a\u7528\u9014\u65f6\u5fd8\u8bb0\u6dfb\u52a0\u989d\u5916\u7684\u6761\u4ef6\u3002\u8fd9\u53ef\u80fd\u5bfc\u81f4\u96be\u4ee5\u8c03\u8bd5\u7684\u9519\u8bef\u3002\u672c\u7740\u8fd9\u79cd\u7cbe\u795e\uff0c\u6211\u4eec\u9009\u62e9\u8ba9\u4ee3\u7801\u5728\u6bcf\u4e2a\u725b\u987f\u6b65\u9aa4\u4e2d\u6267\u884c\u4ec0\u4e48\u64cd\u4f5c\u65b9\u9762\u66f4\u52a0\u5570\u55e6\u3002\n\n  template <int dim> \n  void Solid<dim>::make_constraints(const int it_nr) \n  { \n\n// \u7531\u4e8e\u6211\u4eec(a)\u5904\u7406\u7684\u662f\u725b\u987f\u8fed\u4ee3\u65b9\u6cd5\uff0c(b)\u4f7f\u7528\u7684\u662f\u4f4d\u79fb\u7684\u589e\u91cf\u516c\u5f0f\uff0c\u4ee5\u53ca(c)\u5c06\u7ea6\u675f\u6761\u4ef6\u5e94\u7528\u4e8e\u589e\u91cf\u4f4d\u79fb\u573a\uff0c\u6240\u4ee5\u5bf9\u4f4d\u79fb\u66f4\u65b0\u7684\u4efb\u4f55\u975e\u5747\u8d28\u7ea6\u675f\u6761\u4ef6\u53ea\u5e94\u5728\u7b2c2\u6b21\u8fed\u4ee3\u65f6\u6307\u5b9a\u3002\u7531\u4e8e\u8be5\u8fed\u4ee3\u540e\u7ea6\u675f\u6761\u4ef6\u5c06\u5f97\u5230\u5b8c\u5168\u6ee1\u8db3\uff0c\u56e0\u6b64\u4e0d\u9700\u8981\u505a\u540e\u7eed\u7684\u8d21\u732e\u3002\n\n    const bool apply_dirichlet_bc = (it_nr == 0); \n\n//\u6b64\u5916\uff0c\n//\u5728\u4e00\u4e2a\u65f6\u95f4\u6bb5\u5185\u7684\u7b2c\u4e00\u6b21\u725b\u987f\u8fed\u4ee3\u4e4b\u540e\uff0c\u7ea6\u675f\u6761\u4ef6\u4fdd\u6301\u4e0d\u53d8\uff0c\u53ea\u8981\u4e0d\u6e05\u9664 @p constraints \u5bf9\u8c61\uff0c\u6211\u4eec\u5c31\u4e0d\u9700\u8981\u4fee\u6539\u6216\u91cd\u5efa\u5b83\u4eec\u3002\n\n    if (it_nr > 1) \n      { \n        std::cout << \" --- \" << std::flush; \n        return; \n      } \n\n    std::cout << \" CST \" << std::flush; \n\n    if (apply_dirichlet_bc) \n      { \n\n// \u5728\u725b\u987f\u7b2c2\u6b21\u8fed\u4ee3\u65f6\uff0c\u6211\u4eec\u5e0c\u671b\u5e94\u7528\u4ee3\u8868\u4f4d\u79fb\u589e\u91cf\u7684\u8fb9\u754c\u6761\u4ef6\u7684\u5168\u5957\u975e\u5747\u8d28\u548c\u5747\u8d28\u7ea6\u675f\u3002\u56e0\u4e3a\u4e00\u822c\u6765\u8bf4\uff0c\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u7ea6\u675f\u6761\u4ef6\u53ef\u80fd\u662f\u4e0d\u540c\u7684\uff0c\u6211\u4eec\u9700\u8981\u6e05\u9664\u7ea6\u675f\u77e9\u9635\u5e76\u5b8c\u5168\u91cd\u5efa\u5b83\u3002\u4e00\u4e2a\u4f8b\u5b50\u662f\uff0c\u5982\u679c\u4e00\u4e2a\u8868\u9762\u6b63\u5728\u52a0\u901f\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u4f4d\u79fb\u53d8\u5316\u662f\u4e0d\u6052\u5b9a\u7684\u3002\n\n        constraints.clear(); \n\n// \u4e09\u7ef4\u538b\u75d5\u95ee\u9898\u7684\u8fb9\u754c\u6761\u4ef6\u5982\u4e0b\u3002\u5728-x\u3001-y\u548c-z\u9762\uff08IDs 0,2,4\uff09\u6211\u4eec\u8bbe\u7f6e\u4e86\u4e00\u4e2a\u5bf9\u79f0\u6761\u4ef6\uff0c\u53ea\u5141\u8bb8\u5e73\u9762\u8fd0\u52a8\uff0c\u800c+x\u548c+z\u9762\uff08IDs 1,5\uff09\u65e0\u7275\u5f15\u529b\u3002\u5728\u8fd9\u4e2a\u8bbe\u8ba1\u597d\u7684\u95ee\u9898\u4e2d\uff0c+y\u9762\u7684\u4e00\u90e8\u5206\uff08ID 3\uff09\u88ab\u8bbe\u5b9a\u4e3a\u5728x-\u548cz-\u5206\u91cf\u4e0a\u6ca1\u6709\u8fd0\u52a8\u3002\u6700\u540e\uff0c\u5982\u524d\u6240\u8ff0\uff0c+y\u9762\u7684\u53e6\u4e00\u90e8\u5206\u6709\u4e00\u4e2a\u65bd\u52a0\u7684\u538b\u529b\uff0c\u4f46\u5728x\u548cz\u65b9\u5411\u4e0a\u4e5f\u53d7\u5230\u7ea6\u675f\u3002\n\n// \u5728\u4e0b\u6587\u4e2d\uff0c\u6211\u4eec\u5fc5\u987b\u544a\u8bc9\u51fd\u6570\u63d2\u503c\u7684\u8fb9\u754c\u503c\u5e94\u8be5\u7ea6\u675f\u89e3\u5411\u91cf\u7684\u54ea\u4e9b\u5206\u91cf\uff08\u4e5f\u5c31\u662f\u8bf4\uff0c\u662fx-\u3001y-\u3001z-\u4f4d\u79fb\u8fd8\u662f\u5b83\u4eec\u7684\u7ec4\u5408\uff09\u3002\u8fd9\u662f\u7528ComponentMask\u5bf9\u8c61\u5b8c\u6210\u7684\uff08\u89c1 @ref GlossComponentMask \uff09\uff0c\u5982\u679c\u6211\u4eec\u4e3a\u6709\u9650\u5143\u63d0\u4f9b\u4e00\u4e2a\u6211\u4eec\u5e0c\u671b\u9009\u62e9\u7684\u5206\u91cf\u7684\u63d0\u53d6\u5668\u5bf9\u8c61\uff0c\u6211\u4eec\u53ef\u4ee5\u4ece\u6709\u9650\u5143\u5f97\u5230\u8fd9\u4e9b\u5bf9\u8c61\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u8bbe\u7f6e\u4e86\u8fd9\u6837\u7684\u63d0\u53d6\u5668\u5bf9\u8c61\uff0c\u7136\u540e\u5728\u751f\u6210\u76f8\u5173\u6784\u4ef6\u63a9\u7801\u65f6\u4f7f\u7528\u5b83\u3002\n\n        const FEValuesExtractors::Scalar x_displacement(0); \n        const FEValuesExtractors::Scalar y_displacement(1); \n\n        { \n          const int boundary_id = 0; \n\n          VectorTools::interpolate_boundary_values( \n            dof_handler, \n            boundary_id, \n            Functions::ZeroFunction<dim>(n_components), \n            constraints, \n            fe.component_mask(x_displacement)); \n        } \n        { \n          const int boundary_id = 2; \n\n          VectorTools::interpolate_boundary_values( \n            dof_handler, \n            boundary_id, \n            Functions::ZeroFunction<dim>(n_components), \n            constraints, \n            fe.component_mask(y_displacement)); \n        } \n\n        if (dim == 3) \n          { \n            const FEValuesExtractors::Scalar z_displacement(2); \n\n            { \n              const int boundary_id = 3; \n\n              VectorTools::interpolate_boundary_values( \n                dof_handler, \n                boundary_id, \n                Functions::ZeroFunction<dim>(n_components), \n                constraints, \n                (fe.component_mask(x_displacement) | \n                 fe.component_mask(z_displacement))); \n            } \n            { \n              const int boundary_id = 4; \n\n              VectorTools::interpolate_boundary_values( \n                dof_handler, \n                boundary_id, \n                Functions::ZeroFunction<dim>(n_components), \n                constraints, \n                fe.component_mask(z_displacement)); \n            } \n\n            { \n              const int boundary_id = 6; \n\n              VectorTools::interpolate_boundary_values( \n                dof_handler, \n                boundary_id, \n                Functions::ZeroFunction<dim>(n_components), \n                constraints, \n                (fe.component_mask(x_displacement) | \n                 fe.component_mask(z_displacement))); \n            } \n          } \n        else \n          { \n            { \n              const int boundary_id = 3; \n\n              VectorTools::interpolate_boundary_values( \n                dof_handler, \n                boundary_id, \n                Functions::ZeroFunction<dim>(n_components), \n                constraints, \n                (fe.component_mask(x_displacement))); \n            } \n            { \n              const int boundary_id = 6; \n\n              VectorTools::interpolate_boundary_values( \n                dof_handler, \n                boundary_id, \n                Functions::ZeroFunction<dim>(n_components), \n                constraints, \n                (fe.component_mask(x_displacement))); \n            } \n          } \n      } \n    else \n      { \n\n// \u7531\u4e8e\u6240\u6709\u7684Dirichlet\u7ea6\u675f\u5728\u725b\u987f\u7b2c2\u6b21\u8fed\u4ee3\u540e\u88ab\u5b8c\u5168\u6ee1\u8db3\uff0c\u6211\u4eec\u8981\u786e\u4fdd\u5bf9\u8fd9\u4e9b\u6761\u76ee\u4e0d\u505a\u8fdb\u4e00\u6b65\u7684\u4fee\u6539\u3002\u8fd9\u610f\u5473\u7740\u6211\u4eec\u8981\u5c06\u6240\u6709\u975e\u5747\u8d28\u7684Dirichlet\u7ea6\u675f\u8f6c\u6362\u6210\u5747\u8d28\u7684\u7ea6\u675f\u3002\n\n// \u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u8fd9\u6837\u505a\u7684\u7a0b\u5e8f\u662f\u975e\u5e38\u7b80\u5355\u7684\uff0c\u4e8b\u5b9e\u4e0a\uff0c\u5f53\u53ea\u5e94\u7528\u540c\u8d28\u8fb9\u754c\u6761\u4ef6\u65f6\uff0c\u6211\u4eec\u53ef\u4ee5\uff08\u4e5f\u4f1a\uff09\u89c4\u907f\u4efb\u4f55\u4e0d\u5fc5\u8981\u7684\u64cd\u4f5c\u3002\u5728\u4e00\u4e2a\u66f4\u666e\u904d\u7684\u95ee\u9898\u4e2d\uff0c\u6211\u4eec\u5e94\u8be5\u6ce8\u610f\u60ac\u6302\u8282\u70b9\u548c\u5468\u671f\u6027\u7ea6\u675f\uff0c\u8fd9\u4e5f\u53ef\u80fd\u5f15\u5165\u4e00\u4e9b\u4e0d\u5747\u5300\u6027\u3002\u90a3\u4e48\uff0c\u4e3a\u4e0d\u540c\u7c7b\u578b\u7684\u7ea6\u675f\u4fdd\u7559\u4e0d\u540c\u7684\u5bf9\u8c61\u53ef\u80fd\u662f\u6709\u5229\u7684\uff0c\u4e00\u65e6\u6784\u5efa\u4e86\u540c\u8d28Dirichlet\u7ea6\u675f\uff0c\u5c31\u5c06\u5b83\u4eec\u5408\u5e76\u5728\u4e00\u8d77\u3002\n\n        if (constraints.has_inhomogeneities()) \n          { \n\n// \u7531\u4e8e\u4eff\u751f\u7ea6\u675f\u662f\u5728\u4e0a\u4e00\u6b21\u725b\u987f\u8fed\u4ee3\u4e2d\u5b8c\u6210\u7684\uff0c\u6240\u4ee5\u4e0d\u80fd\u76f4\u63a5\u4fee\u6539\u3002\u6240\u4ee5\u6211\u4eec\u9700\u8981\u5c06\u5b83\u4eec\u590d\u5236\u5230\u53e6\u4e00\u4e2a\u4e34\u65f6\u5bf9\u8c61\uff0c\u5e76\u5728\u90a3\u91cc\u8fdb\u884c\u4fee\u6539\u3002\u4e00\u65e6\u6211\u4eec\u5b8c\u6210\u4e86\uff0c\u6211\u4eec\u5c06\u628a\u5b83\u4eec\u8f6c\u79fb\u56de\u4e3b @p constraints \u5bf9\u8c61\u3002\n\n            AffineConstraints<double> homogeneous_constraints(constraints); \n            for (unsigned int dof = 0; dof != dof_handler.n_dofs(); ++dof) \n              if (homogeneous_constraints.is_inhomogeneously_constrained(dof)) \n                homogeneous_constraints.set_inhomogeneity(dof, 0.0); \n\n            constraints.clear(); \n            constraints.copy_from(homogeneous_constraints); \n          } \n      } \n\n    constraints.close(); \n  } \n// @sect4{Solid::assemble_sc}  \u89e3\u51b3\u6574\u4e2a\u5757\u7cfb\u7edf\u6709\u70b9\u95ee\u9898\uff0c\u56e0\u4e3a\u5bf9 $\\mathsf{\\mathbf{K}}_{ \\widetilde{J} \\widetilde{J}}$ \u5757\u6ca1\u6709\u8d21\u732e\uff0c\u4f7f\u5176\u4e0d\u53ef\u9006\u8f6c\uff08\u5f53\u4f7f\u7528\u8fed\u4ee3\u6c42\u89e3\u5668\u65f6\uff09\u3002\u7531\u4e8e\u538b\u529b\u548c\u6269\u5f20\u53d8\u91cfDOF\u662f\u4e0d\u8fde\u7eed\u7684\uff0c\u6211\u4eec\u53ef\u4ee5\u5c06\u5b83\u4eec\u6d53\u7f29\u6210\u4e00\u4e2a\u8f83\u5c0f\u7684\u4ec5\u6709\u4f4d\u79fb\u7684\u7cfb\u7edf\uff0c\u7136\u540e\u6211\u4eec\u5c06\u5bf9\u5176\u8fdb\u884c\u6c42\u89e3\uff0c\u968f\u540e\u8fdb\u884c\u540e\u5904\u7406\u4ee5\u68c0\u7d22\u51fa\u538b\u529b\u548c\u6269\u5f20\u7684\u89e3\u51b3\u65b9\u6848\u3002\n\n// \u9759\u6001\u51dd\u7ed3\u8fc7\u7a0b\u53ef\u4ee5\u5728\u5168\u5c40\u5c42\u9762\u4e0a\u8fdb\u884c\uff0c\u4f46\u6211\u4eec\u9700\u8981\u5176\u4e2d\u4e00\u4e2a\u5757\u7684\u9006\u5411\u3002\u7136\u800c\uff0c\u7531\u4e8e\u538b\u529b\u548c\u6269\u5f20\u53d8\u91cf\u662f\u4e0d\u8fde\u7eed\u7684\uff0c\u9759\u6001\u51dd\u7ed3\uff08SC\uff09\u64cd\u4f5c\u4e5f\u53ef\u4ee5\u5728\u6bcf\u4e2a\u5355\u5143\u7684\u57fa\u7840\u4e0a\u8fdb\u884c\uff0c\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u53cd\u8f6c\u5c40\u90e8\u5757\u6765\u4ea7\u751f\u5757\u5bf9\u89d2\u7ebf $\\mathsf{\\mathbf{K}}_{\\widetilde{p}\\widetilde{J}}$ \u5757\u7684\u9006\u3002\u6211\u4eec\u53ef\u4ee5\u518d\u6b21\u4f7f\u7528TBB\u6765\u505a\u8fd9\u4ef6\u4e8b\uff0c\u56e0\u4e3a\u6bcf\u4e2a\u64cd\u4f5c\u90fd\u5c06\u662f\u76f8\u4e92\u72ec\u7acb\u7684\u3002\n\n//\u901a\u8fc7WorkStream\u7c7b\u4f7f\u7528TBB\uff0c\u6211\u4eec\u628a\u6bcf\u4e2a\u5143\u7d20\u7684\u8d21\u732e\u96c6\u5408\u8d77\u6765\u5f62\u6210 $ \\mathsf{\\mathbf{K}}_{\\textrm{con}}= \\bigl[ \\mathsf{\\mathbf{K}}_{uu} + \\overline{\\overline{\\mathsf{\\mathbf{K}}}}~ \\bigr]$ \u3002\u7136\u540e\u8fd9\u4e9b\u8d21\u732e\u88ab\u6dfb\u52a0\u5230\u5168\u5c40\u521a\u5ea6\u77e9\u9635\u4e2d\u3002\u9274\u4e8e\u8fd9\u6837\u7684\u63cf\u8ff0\uff0c\u4ee5\u4e0b\u4e24\u4e2a\u51fd\u6570\u5e94\u8be5\u662f\u6e05\u695a\u7684\u3002\n\n  template <int dim> \n  void Solid<dim>::assemble_sc() \n  { \n    timer.enter_subsection(\"Perform static condensation\"); \n    std::cout << \" ASM_SC \" << std::flush; \n\n    PerTaskData_SC per_task_data(dofs_per_cell, \n                                 element_indices_u.size(), \n                                 element_indices_p.size(), \n                                 element_indices_J.size()); \n    ScratchData_SC scratch_data; \n\n    WorkStream::run(dof_handler.active_cell_iterators(), \n                    *this, \n                    &Solid::assemble_sc_one_cell, \n                    &Solid::copy_local_to_global_sc, \n                    scratch_data, \n                    per_task_data); \n\n    timer.leave_subsection(); \n  } \n\n  template <int dim> \n  void Solid<dim>::copy_local_to_global_sc(const PerTaskData_SC &data) \n  { \n    for (unsigned int i = 0; i < dofs_per_cell; ++i) \n      for (unsigned int j = 0; j < dofs_per_cell; ++j) \n        tangent_matrix.add(data.local_dof_indices[i], \n                           data.local_dof_indices[j], \n                           data.cell_matrix(i, j)); \n  } \n\n// \u73b0\u5728\u6211\u4eec\u63cf\u8ff0\u9759\u6001\u51dd\u7ed3\u8fc7\u7a0b\u3002\u6309\u7167\u60ef\u4f8b\uff0c\u6211\u4eec\u5fc5\u987b\u9996\u5148\u627e\u51fa\u8fd9\u4e2a\u5355\u5143\u4e0a\u7684\u81ea\u7531\u5ea6\u6709\u54ea\u4e9b\u5168\u5c40\u6570\u5b57\uff0c\u5e76\u91cd\u7f6e\u4e00\u4e9b\u6570\u636e\u7ed3\u6784\u3002\n\n  template <int dim> \n  void Solid<dim>::assemble_sc_one_cell( \n    const typename DoFHandler<dim>::active_cell_iterator &cell, \n    ScratchData_SC &                                      scratch, \n    PerTaskData_SC &                                      data) \n  { \n    data.reset(); \n    scratch.reset(); \n    cell->get_dof_indices(data.local_dof_indices); \n\n// \u6211\u4eec\u73b0\u5728\u63d0\u53d6\u4e0e\u5f53\u524d\u5355\u5143\u76f8\u5173\u7684DFS\u5bf9\u5168\u5c40\u521a\u5ea6\u77e9\u9635\u7684\u8d21\u732e\u3002  $\\widetilde{p}$ \u548c $\\widetilde{J}$ \u63d2\u503c\u7684\u4e0d\u8fde\u7eed\u6027\u8d28\u610f\u5473\u7740\u5b83\u4eec\u5728\u5168\u5c40\u6c34\u5e73\u4e0a\u6ca1\u6709\u5c40\u90e8\u8d21\u732e\u7684\u8026\u5408\u3002\u800c $\\mathbf{u}$ \u9053\u592b\u5219\u4e0d\u662f\u8fd9\u6837\u3002 \u6362\u53e5\u8bdd\u8bf4\uff0c $\\mathsf{\\mathbf{k}}_{\\widetilde{J} \\widetilde{p}}$ \u3001 $\\mathsf{\\mathbf{k}}_{\\widetilde{p} \\widetilde{p}}$ \u548c $\\mathsf{\\mathbf{k}}_{\\widetilde{J} \\widetilde{p}}$ \uff0c\u5f53\u4ece\u5168\u5c40\u521a\u5ea6\u77e9\u9635\u4e2d\u63d0\u53d6\u65f6\u662f\u5143\u7d20\u8d21\u732e\u3002 \u800c $\\mathsf{\\mathbf{k}}_{uu}$ \u5219\u4e0d\u662f\u8fd9\u79cd\u60c5\u51b5\u3002\n\n// \u6ce8\uff1a\u7528\u5c0f\u5199\u7684\u7b26\u53f7\u8868\u793a\u5143\u7d20\u521a\u5ea6\u77e9\u9635\u3002\n\n// \u76ee\u524d\uff0c\u4e0e\u5f53\u524d\u5143\u7d20\u76f8\u5173\u7684dof\u77e9\u9635\uff08\u677e\u6563\u5730\u8868\u793a\u4e3a $\\mathsf{\\mathbf{k}}$ \uff09\u662f\u8fd9\u6837\u7684\u3002\n// @f{align*}\n//     \\begin{bmatrix}\n//        \\mathsf{\\mathbf{k}}_{uu}  &  \\mathsf{\\mathbf{k}}_{u\\widetilde{p}}\n//        & \\mathbf{0}\n//     \\\\ \\mathsf{\\mathbf{k}}_{\\widetilde{p}u} & \\mathbf{0}  &\n//     \\mathsf{\\mathbf{k}}_{\\widetilde{p}\\widetilde{J}}\n//     \\\\ \\mathbf{0}  &  \\mathsf{\\mathbf{k}}_{\\widetilde{J}\\widetilde{p}}  &\n//     \\mathsf{\\mathbf{k}}_{\\widetilde{J}\\widetilde{J}} \\end{bmatrix}\n//  @f}\n\n// \u6211\u4eec\u73b0\u5728\u9700\u8981\u5bf9\u5176\u8fdb\u884c\u4fee\u6539\uff0c\u4f7f\u5176\u663e\u793a\u4e3a\n// @f{align*}\n//    \\begin{bmatrix}\n//       \\mathsf{\\mathbf{k}}_{\\textrm{con}}   &\n//       \\mathsf{\\mathbf{k}}_{u\\widetilde{p}}    & \\mathbf{0}\n//    \\\\ \\mathsf{\\mathbf{k}}_{\\widetilde{p}u} & \\mathbf{0} &\n//    \\mathsf{\\mathbf{k}}_{\\widetilde{p}\\widetilde{J}}^{-1}\n//    \\\\ \\mathbf{0} & \\mathsf{\\mathbf{k}}_{\\widetilde{J}\\widetilde{p}} &\n//    \\mathsf{\\mathbf{k}}_{\\widetilde{J}\\widetilde{J}} \\end{bmatrix}\n// @f}\n// with $\\mathsf{\\mathbf{k}}_{\\textrm{con}} = \\bigl[\n// \\mathsf{\\mathbf{k}}_{uu} +\\overline{\\overline{\\mathsf{\\mathbf{k}}}}~\n// \\bigr]$ where $               \\overline{\\overline{\\mathsf{\\mathbf{k}}}}\n// \\dealcoloneq \\mathsf{\\mathbf{k}}_{u\\widetilde{p}}\n// \\overline{\\mathsf{\\mathbf{k}}} \\mathsf{\\mathbf{k}}_{\\widetilde{p}u}\n// $\n// and\n// $\n//    \\overline{\\mathsf{\\mathbf{k}}} =\n//     \\mathsf{\\mathbf{k}}_{\\widetilde{J}\\widetilde{p}}^{-1}\n//     \\mathsf{\\mathbf{k}}_{\\widetilde{J}\\widetilde{J}}\n//    \\mathsf{\\mathbf{k}}_{\\widetilde{p}\\widetilde{J}}^{-1}\n// $.\n\n// \u5728\u8fd9\u4e00\u70b9\u4e0a\uff0c\u6211\u4eec\u9700\u8981\u6ce8\u610f\u5230\u5168\u5c40\u6570\u636e\u5df2\u7ecf\u5b58\u5728\u4e8e $\\mathsf{\\mathbf{K}}_{uu}$  ,  $\\mathsf{\\mathbf{K}}_{\\widetilde{p} \\widetilde{J}}$  \u548c  $\\mathsf{\\mathbf{K}}_{\\widetilde{J} \\widetilde{p}}$  \u5b50\u5757\u4e2d\u3002 \u56e0\u6b64\uff0c\u5982\u679c\u6211\u4eec\u8981\u4fee\u6539\u5b83\u4eec\uff0c\u6211\u4eec\u5fc5\u987b\u8003\u8651\u5230\u5df2\u7ecf\u5b58\u5728\u7684\u6570\u636e\uff08\u4e5f\u5c31\u662f\u8bf4\uff0c\u5982\u679c\u9700\u8981\u7684\u8bdd\uff0c\u7b80\u5355\u5730\u6dfb\u52a0\u5230\u5b83\u6216\u5220\u9664\u5b83\uff09\u3002 \u7531\u4e8ecopy_local_to_global\u64cd\u4f5c\u662f\u4e00\u4e2a \"+=\"\u64cd\u4f5c\uff0c\u6211\u4eec\u9700\u8981\u8003\u8651\u5230\u8fd9\u4e00\u70b9\n\n// \u7279\u522b\u662f\u5bf9\u4e8e $\\mathsf{\\mathbf{K}}_{uu}$ \u5757\uff0c\u8fd9\u610f\u5473\u7740\u4ece\u5468\u56f4\u7684\u5355\u5143\u683c\u4e2d\u52a0\u5165\u4e86\u8d21\u732e\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u64cd\u4f5c\u8fd9\u4e2a\u5757\u65f6\u9700\u8981\u5c0f\u5fc3\u3002 \u6211\u4eec\u4e0d\u80fd\u76f4\u63a5\u64e6\u9664\u5b50\u5757\u3002\n\n// \u6211\u4eec\u5c06\u91c7\u7528\u8fd9\u79cd\u7b56\u7565\u6765\u83b7\u5f97\u6211\u4eec\u60f3\u8981\u7684\u5b50\u5757\u3002\n\n\n\n// -  $ {\\mathsf{\\mathbf{k}}}_{\\textrm{store}}$  : \u7531\u4e8e\u6211\u4eec\u4e0d\u80fd\u8bbf\u95ee $\\mathsf{\\mathbf{k}}_{uu}$ \uff0c\u4f46\u6211\u4eec\u77e5\u9053\u5b83\u7684\u8d21\u732e\u88ab\u6dfb\u52a0\u5230\u5168\u5c40 $\\mathsf{\\mathbf{K}}_{uu}$ \u77e9\u9635\u4e2d\uff0c\u6211\u4eec\u53ea\u60f3\u6dfb\u52a0\u5143\u7d20\u660e\u667a\u7684\u9759\u6001\u51dd\u7ed3 $\\overline{\\overline{\\mathsf{\\mathbf{k}}}}$  \u3002\n\n\n\n// -  $\\mathsf{\\mathbf{k}}^{-1}_{\\widetilde{p} \\widetilde{J}}$  : \u7c7b\u4f3c\u5730\uff0c $\\mathsf{\\mathbf{k}}_{\\widetilde{p} \\widetilde{J}}$ \u5b58\u5728\u4e8e\u5b50\u5757\u4e2d\u3002\u7531\u4e8e\u590d\u5236\u64cd\u4f5c\u662f\u4e00\u4e2a+=\u64cd\u4f5c\uff0c\u6211\u4eec\u9700\u8981\u51cf\u53bb\u73b0\u6709\u7684 $\\mathsf{\\mathbf{k}}_{\\widetilde{p} \\widetilde{J}}$ \u5b50\u77e9\u9635\uff0c\u6b64\u5916\u8fd8\u9700\u8981 \"\u6dfb\u52a0 \"\u6211\u4eec\u60f3\u8981\u66ff\u6362\u5b83\u7684\u4e1c\u897f\u3002\n\n\n\n// -  $\\mathsf{\\mathbf{k}}^{-1}_{\\widetilde{J} \\widetilde{p}}$  : \u7531\u4e8e\u5168\u5c40\u77e9\u9635\u662f\u5bf9\u79f0\u7684\uff0c\u8fd9\u4e2a\u5757\u548c\u4e0a\u9762\u90a3\u4e2a\u5757\u662f\u4e00\u6837\u7684\uff0c\u6211\u4eec\u53ef\u4ee5\u7b80\u5355\u5730\u7528 $\\mathsf{\\mathbf{k}}^{-1}_{\\widetilde{p} \\widetilde{J}}$ \u6765\u4ee3\u66ff\u8fd9\u4e2a\u5757\u3002\n\n// \u6211\u4eec\u9996\u5148\u4ece\u7cfb\u7edf\u77e9\u9635\u4e2d\u63d0\u53d6\u5143\u7d20\u6570\u636e\u3002\u56e0\u6b64\uff0c\u9996\u5148\u6211\u4eec\u5f97\u5230\u5355\u5143\u683c\u7684\u6574\u4e2a\u5b50\u5757\uff0c\u7136\u540e\u63d0\u53d6 $\\mathsf{\\mathbf{k}}$ \u4f5c\u4e3a\u4e0e\u5f53\u524d\u5143\u7d20\u76f8\u5173\u7684\u9053\u592b\u3002\n\n    data.k_orig.extract_submatrix_from(tangent_matrix, \n                                       data.local_dof_indices, \n                                       data.local_dof_indices); \n\n//\u63a5\u4e0b\u6765\u662f $\\mathsf{\\mathbf{k}}_{ \\widetilde{p} u}$ \u7684\u5c40\u90e8\u77e9\u9635 \n// $\\mathsf{\\mathbf{k}}_{ \\widetilde{p} \\widetilde{J}}$  \u548c  $\\mathsf{\\mathbf{k}}_{ \\widetilde{J} \\widetilde{J}}$  \u7684\u5c40\u90e8\u77e9\u9635\u3002\n\n    data.k_pu.extract_submatrix_from(data.k_orig, \n                                     element_indices_p, \n                                     element_indices_u); \n    data.k_pJ.extract_submatrix_from(data.k_orig, \n                                     element_indices_p, \n                                     element_indices_J); \n    data.k_JJ.extract_submatrix_from(data.k_orig, \n                                     element_indices_J, \n                                     element_indices_J); \n\n// \u4e3a\u4e86\u5f97\u5230 $\\mathsf{\\mathbf{k}}_{\\widetilde{p} \\widetilde{J}}$ \u7684\u9006\u503c\uff0c\u6211\u4eec\u76f4\u63a5\u5c06\u5176\u53cd\u8f6c\u3002 \u7531\u4e8e $\\mathsf{\\mathbf{k}}_{\\widetilde{p} \\widetilde{J}}$ \u662f\u5757\u72b6\u5bf9\u89d2\u7ebf\uff0c\u6240\u4ee5\u8fd9\u4e2a\u64cd\u4f5c\u76f8\u5bf9\u4fbf\u5b9c\u3002\n\n    data.k_pJ_inv.invert(data.k_pJ); \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u53ef\u4ee5\u5c06\u51dd\u7ed3\u9879\u6dfb\u52a0\u5230 $\\mathsf{\\mathbf{k}}_{uu}$ \u5757\u4e2d\uff0c\u5e76\u5c06\u5176\u653e\u5165\u5355\u5143\u683c\u5c40\u90e8\u77e9\u9635 \n    // $ \n    // \\mathsf{\\mathbf{A}}\n    // =\n    // \\mathsf{\\mathbf{k}}^{-1}_{\\widetilde{p} \\widetilde{J}}\n    // \\mathsf{\\mathbf{k}}_{\\widetilde{p} u}\n    // $  \u4e2d\u3002\n\n    data.k_pJ_inv.mmult(data.A, data.k_pu); \n//       \n      // $\n      // \\mathsf{\\mathbf{B}}\n      // =\n      // \\mathsf{\\mathbf{k}}^{-1}_{\\widetilde{J} \\widetilde{J}}\n      // \\mathsf{\\mathbf{k}}^{-1}_{\\widetilde{p} \\widetilde{J}}\n      // \\mathsf{\\mathbf{k}}_{\\widetilde{p} u}\n      // $  \n    data.k_JJ.mmult(data.B, data.A); \n// \n    // $\n    // \\mathsf{\\mathbf{C}}\n    // =\n    // \\mathsf{\\mathbf{k}}^{-1}_{\\widetilde{J} \\widetilde{p}}\n    // \\mathsf{\\mathbf{k}}^{-1}_{\\widetilde{J} \\widetilde{J}}\n    // \\mathsf{\\mathbf{k}}^{-1}_{\\widetilde{p} \\widetilde{J}}\n    // \\mathsf{\\mathbf{k}}_{\\widetilde{p} u}\n    // $  \n    data.k_pJ_inv.Tmmult(data.C, data.B); \n// \n    // $\n    // \\overline{\\overline{\\mathsf{\\mathbf{k}}}}\n    // =\n    // \\mathsf{\\mathbf{k}}_{u \\widetilde{p}}\n    // \\mathsf{\\mathbf{k}}^{-1}_{\\widetilde{J} \\widetilde{p}}\n    // \\mathsf{\\mathbf{k}}^{-1}_{\\widetilde{J} \\widetilde{J}}\n    // \\mathsf{\\mathbf{k}}^{-1}_{\\widetilde{p} \\widetilde{J}}\n    // \\mathsf{\\mathbf{k}}_{\\widetilde{p} u}\n    // $  \n    data.k_pu.Tmmult(data.k_bbar, data.C); \n    data.k_bbar.scatter_matrix_to(element_indices_u, \n                                  element_indices_u, \n                                  data.cell_matrix); \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u5c06 $\\mathsf{\\mathbf{k}}^{-1}_{ \\widetilde{p} \\widetilde{J}}$ \u653e\u5728 $\\mathsf{\\mathbf{k}}_{ \\widetilde{p} \\widetilde{J}}$ \u5757\u4e2d\u8fdb\u884c\u540e\u5904\u7406\u3002 \u518d\u6b21\u6ce8\u610f\uff0c\u6211\u4eec\u9700\u8981\u5220\u9664\u90a3\u91cc\u5df2\u7ecf\u5b58\u5728\u7684\u8d21\u732e\u3002\n\n    data.k_pJ_inv.add(-1.0, data.k_pJ); \n    data.k_pJ_inv.scatter_matrix_to(element_indices_p, \n                                    element_indices_J, \n                                    data.cell_matrix); \n  } \n// @sect4{Solid::solve_linear_system}  \u6211\u4eec\u73b0\u5728\u62e5\u6709\u6240\u6709\u5fc5\u8981\u7684\u7ec4\u4ef6\uff0c\u53ef\u4ee5\u4f7f\u7528\u4e24\u79cd\u53ef\u80fd\u7684\u65b9\u6cd5\u4e4b\u4e00\u6765\u89e3\u51b3\u7ebf\u6027\u5316\u7cfb\u7edf\u3002\u7b2c\u4e00\u79cd\u662f\u5728\u5143\u7d20\u5c42\u9762\u4e0a\u8fdb\u884c\u9759\u6001\u51dd\u7ed3\uff0c\u8fd9\u9700\u8981\u5bf9\u5207\u7ebf\u77e9\u9635\u548cRHS\u5411\u91cf\u8fdb\u884c\u4e00\u4e9b\u6539\u52a8\u3002\u53e6\u5916\uff0c\u4e5f\u53ef\u4ee5\u901a\u8fc7\u5728\u5168\u5c40\u5c42\u9762\u4e0a\u8fdb\u884c\u51dd\u7ed3\u6765\u89e3\u51b3\u5168\u5757\u7cfb\u7edf\u3002\u4e0b\u9762\u6211\u4eec\u5c06\u5b9e\u73b0\u8fd9\u4e24\u79cd\u65b9\u6cd5\u3002\n\n  template <int dim> \n  std::pair<unsigned int, double> \n  Solid<dim>::solve_linear_system(BlockVector<double> &newton_update) \n  { \n    unsigned int lin_it  = 0; \n    double       lin_res = 0.0; \n\n    if (parameters.use_static_condensation == true) \n      { \n\n// \u9996\u5148\uff0c\u8fd9\u91cc\u662f\u4f7f\u7528\u5207\u7ebf\u77e9\u9635\u7684\uff08\u6c38\u4e45\uff09\u589e\u91cf\u7684\u65b9\u6cd5\u3002\u5bf9\u4e8e\u4e0b\u9762\u7684\u5185\u5bb9\uff0c\u56de\u987e\u4e00\u4e0b\n// @f{align*}\n//   \\mathsf{\\mathbf{K}}_{\\textrm{store}}\n// \\dealcoloneq\n//   \\begin{bmatrix}\n//       \\mathsf{\\mathbf{K}}_{\\textrm{con}}      &\n//       \\mathsf{\\mathbf{K}}_{u\\widetilde{p}}    & \\mathbf{0}\n//   \\\\  \\mathsf{\\mathbf{K}}_{\\widetilde{p}u}    &       \\mathbf{0} &\n//   \\mathsf{\\mathbf{K}}_{\\widetilde{p}\\widetilde{J}}^{-1}\n//   \\\\  \\mathbf{0}      &\n//   \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{p}}                &\n//   \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{J}} \\end{bmatrix} \\, .\n//  @f}\n//  \u548c\n//  @f{align*}\n//               d \\widetilde{\\mathsf{\\mathbf{p}}}\n//               & =\n//               \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{p}}^{-1}\n//               \\bigl[\n//                        \\mathsf{\\mathbf{F}}_{\\widetilde{J}}\n//                        -\n//                        \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{J}}\n//                        d \\widetilde{\\mathsf{\\mathbf{J}}} \\bigr]\n//               \\\\ d \\widetilde{\\mathsf{\\mathbf{J}}}\n//               & =\n//               \\mathsf{\\mathbf{K}}_{\\widetilde{p}\\widetilde{J}}^{-1}\n//               \\bigl[\n//                       \\mathsf{\\mathbf{F}}_{\\widetilde{p}}\n//                       - \\mathsf{\\mathbf{K}}_{\\widetilde{p}u} d\n//                       \\mathsf{\\mathbf{u}} \\bigr]\n//                \\\\ \\Rightarrow d \\widetilde{\\mathsf{\\mathbf{p}}}\n//               &= \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{p}}^{-1}\n//               \\mathsf{\\mathbf{F}}_{\\widetilde{J}}\n//               -\n//               \\underbrace{\\bigl[\\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{p}}^{-1}\n//               \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{J}}\n//               \\mathsf{\\mathbf{K}}_{\\widetilde{p}\\widetilde{J}}^{-1}\\bigr]}_{\\overline{\\mathsf{\\mathbf{K}}}}\\bigl[\n//               \\mathsf{\\mathbf{F}}_{\\widetilde{p}}\n//               - \\mathsf{\\mathbf{K}}_{\\widetilde{p}u} d\n//               \\mathsf{\\mathbf{u}} \\bigr]\n//   @f}\n  // \uff0c\u4ece\u800c\n  // @f[\n  //             \\underbrace{\\bigl[ \\mathsf{\\mathbf{K}}_{uu} +\n  //             \\overline{\\overline{\\mathsf{\\mathbf{K}}}}~ \\bigr]\n  //             }_{\\mathsf{\\mathbf{K}}_{\\textrm{con}}} d\n  //             \\mathsf{\\mathbf{u}}\n  //             =\n  //         \\underbrace{\n  //             \\Bigl[\n  //             \\mathsf{\\mathbf{F}}_{u}\n  //                     - \\mathsf{\\mathbf{K}}_{u\\widetilde{p}} \\bigl[\n  //                     \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{p}}^{-1}\n  //                     \\mathsf{\\mathbf{F}}_{\\widetilde{J}}\n  //                     -\n  //                     \\overline{\\mathsf{\\mathbf{K}}}\\mathsf{\\mathbf{F}}_{\\widetilde{p}}\n  //                     \\bigr]\n  //             \\Bigr]}_{\\mathsf{\\mathbf{F}}_{\\textrm{con}}}\n  // @f]\n  // \u5176\u4e2d\n  // @f[\n  //             \\overline{\\overline{\\mathsf{\\mathbf{K}}}} \\dealcoloneq\n  //                     \\mathsf{\\mathbf{K}}_{u\\widetilde{p}}\n  //                     \\overline{\\mathsf{\\mathbf{K}}}\n  //                     \\mathsf{\\mathbf{K}}_{\\widetilde{p}u} \\, .\n  // @f]\n\n// \u5728\u9876\u90e8\uff0c\u6211\u4eec\u5206\u914d\u4e86\u4e24\u4e2a\u4e34\u65f6\u5411\u91cf\u6765\u5e2e\u52a9\u8fdb\u884c\u9759\u6001\u51dd\u7ed3\uff0c\u5e76\u5206\u914d\u4e86\u53d8\u91cf\u6765\u5b58\u50a8\u7ebf\u6027\u6c42\u89e3\u5668\u7684\u8fed\u4ee3\u6b21\u6570\u548c\uff08\u5e0c\u671b\u6536\u655b\u7684\uff09\u6b8b\u5dee\u3002\n\n        BlockVector<double> A(dofs_per_block); \n        BlockVector<double> B(dofs_per_block); \n\n// \u5728\u8fd9\u4e2a\u51fd\u6570\u7684\u7b2c\u4e00\u6b65\uff0c\u6211\u4eec\u6c42\u89e3\u589e\u91cf\u4f4d\u79fb  $d\\mathbf{u}$  \u3002 \u4e3a\u6b64\uff0c\u6211\u4eec\u8fdb\u884c\u9759\u6001\u6d53\u7f29\uff0c\u4f7f \n    // $\\mathsf{\\mathbf{K}}_{\\textrm{con}}\n    // = \\bigl[ \\mathsf{\\mathbf{K}}_{uu} +\n    // \\overline{\\overline{\\mathsf{\\mathbf{K}}}}~ \\bigr]$ \uff0c\u5e76\u5c06 $\\mathsf{\\mathbf{K}}^{-1}_{\\widetilde{p} \\widetilde{J}}$ \u653e\u5728\u539f $\\mathsf{\\mathbf{K}}_{\\widetilde{p} \\widetilde{J}}$ \u5757\u4e2d\u3002\u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u5236\u4f5c $\\mathsf{\\mathbf{K}}_{\\textrm{store}}$  \u3002\n\n        { \n          assemble_sc(); \n\n//  \n    //  $\n    //   \\mathsf{\\mathbf{A}}_{\\widetilde{J}}\n    //   =\n    //           \\mathsf{\\mathbf{K}}^{-1}_{\\widetilde{p} \\widetilde{J}}\n    //           \\mathsf{\\mathbf{F}}_{\\widetilde{p}}\n    //   $ \n          tangent_matrix.block(p_dof, J_dof) \n            .vmult(A.block(J_dof), system_rhs.block(p_dof)); \n\n      // $\n      // \\mathsf{\\mathbf{B}}_{\\widetilde{J}}\n      // =\n      // \\mathsf{\\mathbf{K}}_{\\widetilde{J} \\widetilde{J}}\n      // \\mathsf{\\mathbf{K}}^{-1}_{\\widetilde{p} \\widetilde{J}}\n      // \\mathsf{\\mathbf{F}}_{\\widetilde{p}}\n      // $  \n          tangent_matrix.block(J_dof, J_dof) \n            .vmult(B.block(J_dof), A.block(J_dof)); \n// \n      // $\n      // \\mathsf{\\mathbf{A}}_{\\widetilde{J}}\n      // =\n      // \\mathsf{\\mathbf{F}}_{\\widetilde{J}}\n      // -\n      // \\mathsf{\\mathbf{K}}_{\\widetilde{J} \\widetilde{J}}\n      // \\mathsf{\\mathbf{K}}^{-1}_{\\widetilde{p} \\widetilde{J}}\n      // \\mathsf{\\mathbf{F}}_{\\widetilde{p}}\n      // $  \n          A.block(J_dof) = system_rhs.block(J_dof); \n          A.block(J_dof) -= B.block(J_dof); \n//    \n      // $\n      // \\mathsf{\\mathbf{A}}_{\\widetilde{J}}\n      // =\n      // \\mathsf{\\mathbf{K}}^{-1}_{\\widetilde{J} \\widetilde{p}}\n      // [\n      // \\mathsf{\\mathbf{F}}_{\\widetilde{J}}\n      // -\n      // \\mathsf{\\mathbf{K}}_{\\widetilde{J} \\widetilde{J}}\n      // \\mathsf{\\mathbf{K}}^{-1}_{\\widetilde{p} \\widetilde{J}}\n      // \\mathsf{\\mathbf{F}}_{\\widetilde{p}}\n      // ]\n      // $  \n          tangent_matrix.block(p_dof, J_dof) \n            .Tvmult(A.block(p_dof), A.block(J_dof)); \n// \n      // $\n      // \\mathsf{\\mathbf{A}}_{u}\n      // =\n      // \\mathsf{\\mathbf{K}}_{u \\widetilde{p}}\n      // \\mathsf{\\mathbf{K}}^{-1}_{\\widetilde{J} \\widetilde{p}}\n      // [\n      // \\mathsf{\\mathbf{F}}_{\\widetilde{J}}\n      // -\n      // \\mathsf{\\mathbf{K}}_{\\widetilde{J} \\widetilde{J}}\n      // \\mathsf{\\mathbf{K}}^{-1}_{\\widetilde{p} \\widetilde{J}}\n      // \\mathsf{\\mathbf{F}}_{\\widetilde{p}}\n      // ]\n      // $  \n          tangent_matrix.block(u_dof, p_dof) \n            .vmult(A.block(u_dof), A.block(p_dof)); \n// \n      // $\n      // \\mathsf{\\mathbf{F}}_{\\text{con}}\n      // =\n      // \\mathsf{\\mathbf{F}}_{u}\n      // -\n      // \\mathsf{\\mathbf{K}}_{u \\widetilde{p}}\n      // \\mathsf{\\mathbf{K}}^{-1}_{\\widetilde{J} \\widetilde{p}}\n      // [\n      // \\mathsf{\\mathbf{F}}_{\\widetilde{J}}\n      // -\n      // \\mathsf{\\mathbf{K}}_{\\widetilde{J} \\widetilde{J}}\n      // \\mathsf{\\mathbf{K}}^{-1}_{\\widetilde{p} \\widetilde{J}}\n      // \\mathsf{\\mathbf{F}}_{\\widetilde{p}}\n      // ]\n      // $  \n          system_rhs.block(u_dof) -= A.block(u_dof); \n\n          timer.enter_subsection(\"Linear solver\"); \n          std::cout << \" SLV \" << std::flush; \n          if (parameters.type_lin == \"CG\") \n            { \n              const auto solver_its = static_cast<unsigned int>( \n                tangent_matrix.block(u_dof, u_dof).m() * \n                parameters.max_iterations_lin); \n              const double tol_sol = \n                parameters.tol_lin * system_rhs.block(u_dof).l2_norm(); \n\n              SolverControl solver_control(solver_its, tol_sol); \n\n              GrowingVectorMemory<Vector<double>> GVM; \n              SolverCG<Vector<double>> solver_CG(solver_control, GVM); \n\n// \u6211\u4eec\u9ed8\u8ba4\u9009\u62e9\u4e86SSOR\u9884\u5904\u7406\u7a0b\u5e8f\uff0c\u56e0\u4e3a\u5728\u5355\u7ebf\u7a0b\u673a\u5668\u4e0a\uff0c\u5b83\u4f3c\u4e4e\u4e3a\u8fd9\u4e2a\u95ee\u9898\u63d0\u4f9b\u4e86\u6700\u5feb\u7684\u6c42\u89e3\u5668\u6536\u655b\u7279\u6027\u3002 \u7136\u800c\uff0c\u5bf9\u4e8e\u4e0d\u540c\u7684\u95ee\u9898\u89c4\u6a21\uff0c\u8fd9\u53ef\u80fd\u4e0d\u662f\u771f\u7684\u3002\n\n              PreconditionSelector<SparseMatrix<double>, Vector<double>> \n                preconditioner(parameters.preconditioner_type, \n                               parameters.preconditioner_relaxation); \n              preconditioner.use_matrix(tangent_matrix.block(u_dof, u_dof)); \n\n              solver_CG.solve(tangent_matrix.block(u_dof, u_dof), \n                              newton_update.block(u_dof), \n                              system_rhs.block(u_dof), \n                              preconditioner); \n\n              lin_it  = solver_control.last_step(); \n              lin_res = solver_control.last_value(); \n            } \n          else if (parameters.type_lin == \"Direct\") \n            { \n\n// \u5426\u5219\uff0c\u5982\u679c\u95ee\u9898\u8db3\u591f\u5c0f\uff0c\u53ef\u4ee5\u5229\u7528\u76f4\u63a5\u6c42\u89e3\u5668\u3002\n\n              SparseDirectUMFPACK A_direct; \n              A_direct.initialize(tangent_matrix.block(u_dof, u_dof)); \n              A_direct.vmult(newton_update.block(u_dof), \n                             system_rhs.block(u_dof)); \n\n              lin_it  = 1; \n              lin_res = 0.0; \n            } \n          else \n            Assert(false, ExcMessage(\"Linear solver type not implemented\")); \n\n          timer.leave_subsection(); \n        } \n\n// \u73b0\u5728\u6211\u4eec\u6709\u4e86\u4f4d\u79fb\u66f4\u65b0\uff0c\u5c06\u7ea6\u675f\u5206\u914d\u56de\u725b\u987f\u66f4\u65b0\u3002\n\n        constraints.distribute(newton_update); \n\n        timer.enter_subsection(\"Linear solver postprocessing\"); \n        std::cout << \" PP \" << std::flush; \n\n// \u89e3\u51b3\u4f4d\u79fb\u95ee\u9898\u540e\u7684\u4e0b\u4e00\u6b65\u662f\u8fdb\u884c\u540e\u5904\u7406\uff0c\u4ece\u7f6e\u6362\u4e2d\u5f97\u5230\u6269\u5f20\u89e3\u3002     \n    // $\n    //  d \\widetilde{\\mathsf{\\mathbf{J}}}\n    //   = \\mathsf{\\mathbf{K}}_{\\widetilde{p}\\widetilde{J}}^{-1} \\bigl[\n    //    \\mathsf{\\mathbf{F}}_{\\widetilde{p}}\n    //  - \\mathsf{\\mathbf{K}}_{\\widetilde{p}u} d \\mathsf{\\mathbf{u}}\n    //   \\bigr]\n    // $  \n        { \n// \n      // $\n      // \\mathsf{\\mathbf{A}}_{\\widetilde{p}}\n      // =\n      // \\mathsf{\\mathbf{K}}_{\\widetilde{p}u} d \\mathsf{\\mathbf{u}}\n      // $  \n          tangent_matrix.block(p_dof, u_dof) \n            .vmult(A.block(p_dof), newton_update.block(u_dof)); \n// \n      // $\n      // \\mathsf{\\mathbf{A}}_{\\widetilde{p}}\n      // =\n      // -\\mathsf{\\mathbf{K}}_{\\widetilde{p}u} d \\mathsf{\\mathbf{u}}\n      // $  \n          A.block(p_dof) *= -1.0; \n// \n      // $\n      // \\mathsf{\\mathbf{A}}_{\\widetilde{p}}\n      // =\n      // \\mathsf{\\mathbf{F}}_{\\widetilde{p}}\n      // -\\mathsf{\\mathbf{K}}_{\\widetilde{p}u} d \\mathsf{\\mathbf{u}}\n      // $  \n          A.block(p_dof) += system_rhs.block(p_dof); \n// \n      // $\n      // d\\mathsf{\\mathbf{\\widetilde{J}}}\n      // =\n      // \\mathsf{\\mathbf{K}}^{-1}_{\\widetilde{p}\\widetilde{J}}\n      // [\n      // \\mathsf{\\mathbf{F}}_{\\widetilde{p}}\n      // -\\mathsf{\\mathbf{K}}_{\\widetilde{p}u} d \\mathsf{\\mathbf{u}}\n      // ]\n      // $  \n          tangent_matrix.block(p_dof, J_dof) \n            .vmult(newton_update.block(J_dof), A.block(p_dof)); \n        } \n\n// \u6211\u4eec\u5728\u6b64\u786e\u4fdd\u4efb\u4f55\u8fea\u91cc\u5e0c\u7279\u7ea6\u675f\u90fd\u5206\u5e03\u5728\u66f4\u65b0\u7684\u89e3\u51b3\u65b9\u6848\u4e0a\u3002\n\n        constraints.distribute(newton_update); \n\n// \u6700\u540e\u6211\u4eec\u7528\u4ee3\u5165\u6cd5\u6c42\u89e3\u538b\u529b\u7684\u66f4\u65b0\u3002     \n    // $\n    // d \\widetilde{\\mathsf{\\mathbf{p}}}\n    //  =\n    // \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{p}}^{-1}\n    // \\bigl[\n    //  \\mathsf{\\mathbf{F}}_{\\widetilde{J}}\n    //   - \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{J}}\n    // d \\widetilde{\\mathsf{\\mathbf{J}}}\n    // \\bigr]\n    // $  \n        { \n// \n      // $\n      // \\mathsf{\\mathbf{A}}_{\\widetilde{J}}\n      //  =\n      // \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{J}}\n      // d \\widetilde{\\mathsf{\\mathbf{J}}}\n      // $  \n          tangent_matrix.block(J_dof, J_dof) \n            .vmult(A.block(J_dof), newton_update.block(J_dof)); \n// \n      // $\n      // \\mathsf{\\mathbf{A}}_{\\widetilde{J}}\n      //  =\n      // -\\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{J}}\n      // d \\widetilde{\\mathsf{\\mathbf{J}}}\n      // $  \n          A.block(J_dof) *= -1.0; \n// \n      // $\n      // \\mathsf{\\mathbf{A}}_{\\widetilde{J}}\n      //  =\n      // \\mathsf{\\mathbf{F}}_{\\widetilde{J}}\n      // -\n      // \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{J}}\n      // d \\widetilde{\\mathsf{\\mathbf{J}}}\n      // $  \n          A.block(J_dof) += system_rhs.block(J_dof); \n\n//\u548c\n//\u6700\u540e....      \n\n  //  $\n  //   d \\widetilde{\\mathsf{\\mathbf{p}}}\n  //    =\n  //   \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{p}}^{-1}\n  //   \\bigl[\n  //    \\mathsf{\\mathbf{F}}_{\\widetilde{J}}\n  //     - \\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{J}}\n  //   d \\widetilde{\\mathsf{\\mathbf{J}}}\n  //   \\bigr]\n  //   $  \n          tangent_matrix.block(p_dof, J_dof) \n            .Tvmult(newton_update.block(p_dof), A.block(J_dof)); \n        } \n\n// \u6211\u4eec\u73b0\u5728\u5df2\u7ecf\u5230\u4e86\u7ec8\u70b9\uff0c\u6240\u4ee5\u6211\u4eec\u5c06\u6240\u6709\u53d7\u9650\u7684\u9053\u592b\u5206\u914d\u5230\u725b\u987f\u66f4\u65b0\u4e2d\u3002\n\n        constraints.distribute(newton_update); \n\n        timer.leave_subsection(); \n      } \n    else \n      { \n        std::cout << \" ------ \" << std::flush; \n\n        timer.enter_subsection(\"Linear solver\"); \n        std::cout << \" SLV \" << std::flush; \n\n        if (parameters.type_lin == \"CG\") \n          { \n\n// \u5728\u5c40\u90e8\u6c34\u5e73\u4e0a\u624b\u52a8\u51dd\u7ed3\u6269\u5f20\u548c\u538b\u529b\u573a\uff0c\u4ee5\u53ca\u968f\u540e\u7684\u540e\u5904\u7406\uff0c\u9700\u8981\u82b1\u8d39\u76f8\u5f53\u5927\u7684\u52aa\u529b\u624d\u80fd\u5b9e\u73b0\u3002\u7b80\u800c\u8a00\u4e4b\uff0c\u6211\u4eec\u5fc5\u987b\u4ea7\u751f\u9006\u77e9\u9635 $\\mathsf{\\mathbf{K}}_{\\widetilde{p}\\widetilde{J}}^{-1}$ \uff0c\u5e76\u5c06\u5176\u6c38\u4e45\u5199\u5165\u5168\u5c40\u5207\u7ebf\u77e9\u9635\u4e2d\u3002\u7136\u540e\u6211\u4eec\u5bf9 $\\mathsf{\\mathbf{K}}_{uu}$ \u8fdb\u884c\u6c38\u4e45\u4fee\u6539\uff0c\u4ea7\u751f $\\mathsf{\\mathbf{K}}_{\\textrm{con}}$ \u3002\u8fd9\u6d89\u53ca\u5230\u5bf9\u5207\u7ebf\u77e9\u9635\u7684\u5c40\u90e8\u5b50\u5757\u7684\u63d0\u53d6\u548c\u64cd\u4f5c\u3002\u5728\u5bf9\u4f4d\u79fb\u8fdb\u884c\u6c42\u89e3\u540e\uff0c\u5bf9\u6269\u5f20\u548c\u538b\u529b\u8fdb\u884c\u6c42\u89e3\u6240\u9700\u7684\u5404\u4e2a\u77e9\u9635-\u5411\u91cf\u64cd\u4f5c\u88ab\u4ed4\u7ec6\u5730\u6267\u884c\u3002\u5c06\u8fd9\u4e9b\u4f17\u591a\u7684\u6b65\u9aa4\u4e0e\u4f7f\u7528LinearOperator\u7c7b\u63d0\u4f9b\u7684\u529f\u80fd\u8fdb\u884c\u7684\u66f4\u7b80\u5355\u3001\u66f4\u900f\u660e\u7684\u5b9e\u73b0\u5f62\u6210\u5bf9\u6bd4\u3002\n\n// \u4e3a\u4e86\u4fbf\u4e8e\u4ee5\u540e\u4f7f\u7528\uff0c\u6211\u4eec\u4e3aRHS\u5411\u91cf\u4e2d\u7684\u5757\u5b9a\u4e49\u4e86\u4e00\u4e9b\u522b\u540d\n\n            const Vector<double> &f_u = system_rhs.block(u_dof); \n            const Vector<double> &f_p = system_rhs.block(p_dof); \n            const Vector<double> &f_J = system_rhs.block(J_dof); \n\n// ... \u5bf9\u4e8e\u725b\u987f\u66f4\u65b0\u5411\u91cf\u4e2d\u7684\u5757\u3002\n\n            Vector<double> &d_u = newton_update.block(u_dof); \n            Vector<double> &d_p = newton_update.block(p_dof); \n            Vector<double> &d_J = newton_update.block(J_dof); \n\n// \u6211\u4eec\u5c06\u5229\u7528\u7cfb\u7edf\u7684\u5bf9\u79f0\u6027\uff0c\u6240\u4ee5\u4e0d\u662f\u6240\u6709\u7684\u5757\u90fd\u9700\u8981\u3002\n\n            const auto K_uu = \n              linear_operator(tangent_matrix.block(u_dof, u_dof)); \n            const auto K_up = \n              linear_operator(tangent_matrix.block(u_dof, p_dof)); \n            const auto K_pu = \n              linear_operator(tangent_matrix.block(p_dof, u_dof)); \n            const auto K_Jp = \n              linear_operator(tangent_matrix.block(J_dof, p_dof)); \n            const auto K_JJ = \n              linear_operator(tangent_matrix.block(J_dof, J_dof)); \n\n// \u7136\u540e\u6211\u4eec\u6784\u5efa\u4e00\u4e2aLinearOperator\uff0c\u4ee3\u8868\uff08\u65b9\u5f62\u5757\uff09 $\\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{p}}$ \u7684\u9006\u3002\u7531\u4e8e\u5b83\u662f\u5bf9\u89d2\u7ebf\u7684\uff08\u6216\u8005\uff0c\u5f53\u4f7f\u7528\u9ad8\u9636\u5206\u89e3\u65f6\uff0c\u51e0\u4e4e\u662f\u5bf9\u89d2\u7ebf\u7684\uff09\uff0c\u6240\u4ee5\u96c5\u53ef\u6bd4\u9884\u5904\u7406\u5668\u662f\u5408\u9002\u7684\u3002\n\n            PreconditionSelector<SparseMatrix<double>, Vector<double>> \n              preconditioner_K_Jp_inv(\"jacobi\"); \n            preconditioner_K_Jp_inv.use_matrix( \n              tangent_matrix.block(J_dof, p_dof)); \n            ReductionControl solver_control_K_Jp_inv( \n              static_cast<unsigned int>(tangent_matrix.block(J_dof, p_dof).m() * \n                                        parameters.max_iterations_lin), \n              1.0e-30, \n              parameters.tol_lin); \n            SolverSelector<Vector<double>> solver_K_Jp_inv; \n            solver_K_Jp_inv.select(\"cg\"); \n            solver_K_Jp_inv.set_control(solver_control_K_Jp_inv); \n            const auto K_Jp_inv = \n              inverse_operator(K_Jp, solver_K_Jp_inv, preconditioner_K_Jp_inv); \n\n// \u73b0\u5728\u6211\u4eec\u53ef\u4ee5\u6784\u5efa $\\mathsf{\\mathbf{K}}_{\\widetilde{J}\\widetilde{p}}^{-1}$ \u7684\u90a3\u4e2a\u8f6c\u7f6e\u548c\u4e00\u4e2a\u7ebf\u6027\u7b97\u5b50\uff0c\u5b83\u4ee3\u8868\u4e86\u6d53\u7f29\u7684\u64cd\u4f5c $\\overline{\\mathsf{\\mathbf{K}}}$ \u548c $\\overline{\\overline{\\mathsf{\\mathbf{K}}}}$ \u4ee5\u53ca\u6700\u540e\u7684\u589e\u5f3a\u77e9\u9635 $\\mathsf{\\mathbf{K}}_{\\textrm{con}}$  \u3002  \u8bf7\u6ce8\u610f\uff0cschur_complement()\u7b97\u5b50\u5728\u8fd9\u91cc\u4e5f\u80fd\u6d3e\u4e0a\u7528\u573a\uff0c\u4f46\u4e3a\u4e86\u6e05\u695a\u8d77\u89c1\uff0c\u4e5f\u4e3a\u4e86\u5c55\u793a\u7ebf\u6027\u6c42\u89e3\u65b9\u6848\u7684\u8868\u8ff0\u548c\u5b9e\u73b0\u4e4b\u95f4\u7684\u76f8\u4f3c\u6027\uff0c\u6211\u4eec\u5c06\u624b\u52a8\u6267\u884c\u8fd9\u4e9b\u64cd\u4f5c\u3002\n\n            const auto K_pJ_inv     = transpose_operator(K_Jp_inv); \n            const auto K_pp_bar     = K_Jp_inv * K_JJ * K_pJ_inv; \n            const auto K_uu_bar_bar = K_up * K_pp_bar * K_pu; \n            const auto K_uu_con     = K_uu + K_uu_bar_bar; \n\n// \u6700\u540e\uff0c\u6211\u4eec\u5b9a\u4e49\u4e86\u4e00\u4e2a\u589e\u5f3a\u521a\u5ea6\u77e9\u9635\u7684\u9006\u8fd0\u7b97\uff0c\u5373  $\\mathsf{\\mathbf{K}}_{\\textrm{con}}^{-1}$  \u3002\u8bf7\u6ce8\u610f\uff0c\u589e\u5f3a\u521a\u5ea6\u77e9\u9635\u7684\u9884\u5904\u7406\u7a0b\u5e8f\u4e0e\u6211\u4eec\u4f7f\u7528\u9759\u6001\u51dd\u7ed3\u7684\u60c5\u51b5\u4e0d\u540c\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u9884\u5904\u7406\u7a0b\u5e8f\u662f\u57fa\u4e8e\u672a\u4fee\u6539\u7684 $\\mathsf{\\mathbf{K}}_{uu}$ \uff0c\u800c\u5728\u7b2c\u4e00\u79cd\u65b9\u6cd5\u4e2d\uff0c\u6211\u4eec\u5b9e\u9645\u4e0a\u4fee\u6539\u4e86\u8fd9\u4e2a\u5b50\u5757\u7684\u6761\u76ee\u3002\u7136\u800c\uff0c\u7531\u4e8e $\\mathsf{\\mathbf{K}}_{\\textrm{con}}$ \u548c $\\mathsf{\\mathbf{K}}_{uu}$ \u5728\u540c\u4e00\u7a7a\u95f4\u64cd\u4f5c\uff0c\u5b83\u5bf9\u8fd9\u4e2a\u95ee\u9898\u4ecd\u7136\u8db3\u591f\u3002\n\n            PreconditionSelector<SparseMatrix<double>, Vector<double>> \n              preconditioner_K_con_inv(parameters.preconditioner_type, \n                                       parameters.preconditioner_relaxation); \n            preconditioner_K_con_inv.use_matrix( \n              tangent_matrix.block(u_dof, u_dof)); \n            ReductionControl solver_control_K_con_inv( \n              static_cast<unsigned int>(tangent_matrix.block(u_dof, u_dof).m() * \n                                        parameters.max_iterations_lin), \n              1.0e-30, \n              parameters.tol_lin); \n            SolverSelector<Vector<double>> solver_K_con_inv; \n            solver_K_con_inv.select(\"cg\"); \n            solver_K_con_inv.set_control(solver_control_K_con_inv); \n            const auto K_uu_con_inv = \n              inverse_operator(K_uu_con, \n                               solver_K_con_inv, \n                               preconditioner_K_con_inv); \n\n// \u73b0\u5728\u6211\u4eec\u53ef\u4ee5\u5bf9\u4f4d\u79fb\u573a\u8fdb\u884c\u6c42\u89e3\u4e86\u3002  \u6211\u4eec\u53ef\u4ee5\u5d4c\u5957\u7ebf\u6027\u8fd0\u7b97\uff0c\u7ed3\u679c\u7acb\u5373\u5199\u5165\u725b\u987f\u66f4\u65b0\u5411\u91cf\u4e2d\u3002  \u5f88\u660e\u663e\uff0c\u8fd9\u4e2a\u5b9e\u73b0\u5bc6\u5207\u6a21\u4eff\u4e86\u4ecb\u7ecd\u4e2d\u6240\u8bf4\u7684\u63a8\u5bfc\u3002\n\n            d_u = \n              K_uu_con_inv * (f_u - K_up * (K_Jp_inv * f_J - K_pp_bar * f_p)); \n\n            timer.leave_subsection(); \n\n// \u9700\u8981\u5bf9\u6269\u5f20\u573a\u548c\u538b\u529b\u573a\u8fdb\u884c\u540e\u5904\u7406\u7684\u64cd\u4f5c\uff0c\u4e5f\u540c\u6837\u5bb9\u6613\u8868\u8fbe\u3002\n\n            timer.enter_subsection(\"Linear solver postprocessing\"); \n            std::cout << \" PP \" << std::flush; \n\n            d_J = K_pJ_inv * (f_p - K_pu * d_u); \n            d_p = K_Jp_inv * (f_J - K_JJ * d_J); \n\n            lin_it  = solver_control_K_con_inv.last_step(); \n            lin_res = solver_control_K_con_inv.last_value(); \n          } \n        else if (parameters.type_lin == \"Direct\") \n          { \n\n// \u7528\u76f4\u63a5\u6c42\u89e3\u5668\u6c42\u89e3\u5168\u5757\u7cfb\u7edf\u3002\u7531\u4e8e\u5b83\u662f\u76f8\u5bf9\u7a33\u5065\u7684\uff0c\u5b83\u53ef\u80fd\u5bf9\u56e0\u96f6 $\\mathsf{\\mathbf{K}}_{ \\widetilde{J} \\widetilde{J}}$ \u5757\u7684\u5b58\u5728\u800c\u4ea7\u751f\u7684\u95ee\u9898\u514d\u75ab\u3002\n\n            SparseDirectUMFPACK A_direct; \n            A_direct.initialize(tangent_matrix); \n            A_direct.vmult(newton_update, system_rhs); \n\n            lin_it  = 1; \n            lin_res = 0.0; \n\n            std::cout << \" -- \" << std::flush; \n          } \n        else \n          Assert(false, ExcMessage(\"Linear solver type not implemented\")); \n\n        timer.leave_subsection(); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u518d\u6b21\u786e\u4fdd\u4efb\u4f55Dirichlet\u7ea6\u675f\u90fd\u5206\u5e03\u5728\u66f4\u65b0\u7684\u89e3\u51b3\u65b9\u6848\u4e0a\u3002\n\n        constraints.distribute(newton_update); \n      } \n\n    return std::make_pair(lin_it, lin_res); \n  } \n// @sect4{Solid::output_results}  \u8fd9\u91cc\u6211\u4eec\u4ecb\u7ecd\u5982\u4f55\u5c06\u7ed3\u679c\u5199\u5165\u6587\u4ef6\uff0c\u4ee5\u4fbf\u7528ParaView\u6216Visi\u6765\u67e5\u770b\u3002\u8be5\u65b9\u6cd5\u4e0e\u4ee5\u524d\u7684\u6559\u7a0b\u4e2d\u7684\u65b9\u6cd5\u7c7b\u4f3c\uff0c\u56e0\u6b64\u5c06\u4e0d\u4f5c\u8be6\u7ec6\u8ba8\u8bba\u3002\n\n  template <int dim> \n  void Solid<dim>::output_results() const \n  { \n    DataOut<dim> data_out; \n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      data_component_interpretation( \n        dim, DataComponentInterpretation::component_is_part_of_vector); \n    data_component_interpretation.push_back( \n      DataComponentInterpretation::component_is_scalar); \n    data_component_interpretation.push_back( \n      DataComponentInterpretation::component_is_scalar); \n\n    std::vector<std::string> solution_name(dim, \"displacement\"); \n    solution_name.emplace_back(\"pressure\"); \n    solution_name.emplace_back(\"dilatation\"); \n\n    DataOutBase::VtkFlags output_flags; \n    output_flags.write_higher_order_cells = true; \n    data_out.set_flags(output_flags); \n\n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution_n, \n                             solution_name, \n                             DataOut<dim>::type_dof_data, \n                             data_component_interpretation); \n\n// \u7531\u4e8e\u6211\u4eec\u5904\u7406\u7684\u662f\u4e00\u4e2a\u5927\u7684\u53d8\u5f62\u95ee\u9898\uff0c\u5982\u679c\u80fd\u5728\u4e00\u4e2a\u4f4d\u79fb\u7684\u7f51\u683c\u4e0a\u663e\u793a\u7ed3\u679c\u5c31\u66f4\u597d\u4e86!  \u4e0eDataOut\u7c7b\u76f8\u8fde\u7684MappingQEulerian\u7c7b\u63d0\u4f9b\u4e86\u4e00\u4e2a\u63a5\u53e3\uff0c\u901a\u8fc7\u8be5\u63a5\u53e3\u53ef\u4ee5\u5b9e\u73b0\u8fd9\u4e00\u76ee\u7684\uff0c\u800c\u4e0d\u9700\u8981\u6211\u4eec\u81ea\u5df1\u7269\u7406\u5730\u79fb\u52a8\u4e09\u89d2\u6d4b\u91cf\u5bf9\u8c61\u4e2d\u7684\u7f51\u683c\u70b9\u3002 \u6211\u4eec\u9996\u5148\u9700\u8981\u5c06\u89e3\u51b3\u65b9\u6848\u590d\u5236\u5230\u4e00\u4e2a\u4e34\u65f6\u77e2\u91cf\uff0c\u7136\u540e\u521b\u5efa\u6b27\u62c9\u6620\u5c04\u3002\u6211\u4eec\u8fd8\u5411DataOut\u5bf9\u8c61\u6307\u5b9a\u4e86\u591a\u9879\u5f0f\u7684\u5ea6\u6570\uff0c\u4ee5\u4fbf\u5728\u4f7f\u7528\u9ad8\u9636\u591a\u9879\u5f0f\u65f6\u4ea7\u751f\u4e00\u4e2a\u66f4\u7cbe\u7ec6\u7684\u8f93\u51fa\u6570\u636e\u96c6\u3002\n\n    Vector<double> soln(solution_n.size()); \n    for (unsigned int i = 0; i < soln.size(); ++i) \n      soln(i) = solution_n(i); \n    MappingQEulerian<dim> q_mapping(degree, dof_handler, soln); \n    data_out.build_patches(q_mapping, degree); \n\n    std::ofstream output(\"solution-\" + std::to_string(dim) + \"d-\" + \n                         std::to_string(time.get_timestep()) + \".vtu\"); \n    data_out.write_vtu(output); \n  } \n\n} // namespace Step44 \n// @sect3{Main function}  \u6700\u540e\u6211\u4eec\u63d0\u4f9b\u4e86\u4e3b\u8981\u7684\u9a71\u52a8\u51fd\u6570\uff0c\u5b83\u770b\u8d77\u6765\u4e0e\u5176\u4ed6\u6559\u7a0b\u6ca1\u6709\u4ec0\u4e48\u4e0d\u540c\u3002\n\nint main() \n{ \n  using namespace Step44; \n\n  try \n    { \n      const unsigned int dim = 3; \n      Solid<dim>         solid(\"parameters.prm\"); \n      solid.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\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\n\n", "meta": {"hexsha": "1b03320425a56551153102f3e05555a4590f30b0", "size": 100245, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-44/step-44.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-44/step-44.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-44/step-44.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.4347826087, "max_line_length": 590, "alphanum_fraction": 0.5868921143, "num_tokens": 36248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757312, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5050550165045523}}
{"text": "//\n//  Copyright (c) 2016, Guillaume GODIN\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//     * 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 Institue of Cancer Research.\n//       nor the names of its contributors may be used to endorse or promote\n//       products derived from this software without specific prior written\n//       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 FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (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// for build & set RDBASE! => export RDBASE=/Users/GVALMTGG/Github/rdkit_mine/\n\n#include <GraphMol/RDKitBase.h>\n\n#include \"WHIM.h\"\n#include \"MolData3Ddescriptors.h\"\n\n#include <math.h>\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\nusing namespace Eigen;\n\nnamespace RDKit {\nnamespace Descriptors {\nnamespace {\n\nMolData3Ddescriptors moldata3D;\n\ndouble roundn(double in, int factor) {\n  return round(in * pow(10., factor)) / pow(10., factor);\n}\n\nMatrixXd GetCenterMatrix(MatrixXd &Mat) {\n  VectorXd v = Mat.colwise().mean();\n  MatrixXd X = Mat.rowwise() - v.transpose();\n  return X;\n}\n\nMatrixXd GetCovMatrix(MatrixXd &X, MatrixXd &Weigth, double weigth) {\n  return X.transpose() * Weigth * X / weigth;\n}\n\nJacobiSVD<MatrixXd> *getSVD(MatrixXd &Mat) {\n  JacobiSVD<MatrixXd> *svd =\n      new JacobiSVD<MatrixXd>(Mat, ComputeThinU | ComputeThinV);\n  return svd;\n}\n\nstd::vector<double> getWhimD(std::vector<double> weigthvector,\n                             MatrixXd MatOrigin, int numAtoms, double th) {\n  double *weigtharray = &weigthvector[0];\n\n  Map<VectorXd> Weigth(weigtharray, numAtoms);\n\n  MatrixXd WeigthMat = Weigth.asDiagonal();\n\n  double weigth = WeigthMat.diagonal().sum();\n\n  MatrixXd Xmean = GetCenterMatrix(MatOrigin);\n\n  MatrixXd covmat = GetCovMatrix(Xmean, WeigthMat, weigth);\n\n  JacobiSVD<MatrixXd> *svd = getSVD(covmat);\n\n  std::vector<double> w(18);\n  // prepare data for Whim parameter computation\n\n  const double *SingVal = svd->singularValues().data();\n  MatrixXd Scores = Xmean * svd->matrixV();  //  V is similar\n\n  // compute parameters\n  w[0] = SingVal[0];\n  w[1] = SingVal[1];\n  w[2] = SingVal[2];\n  w[3] = SingVal[0] + SingVal[1] + SingVal[2];  // T\n  w[4] = SingVal[0] * SingVal[1] + SingVal[0] * SingVal[2] +\n         SingVal[1] * SingVal[2];                              // A\n  w[5] = w[3] + w[4] + SingVal[0] * SingVal[1] * SingVal[2];   // V\n  w[6] = SingVal[0] / (SingVal[0] + SingVal[1] + SingVal[2]);  // P1\n  w[7] = SingVal[1] / (SingVal[0] + SingVal[1] + SingVal[2]);  // p2\n  w[8] = SingVal[2] / (SingVal[0] + SingVal[1] + SingVal[2]);  // P3\n\n  double res = 0.0;\n  for (int i = 0; i < 3; i++) {\n    res += std::abs(w[i] / w[3] - 1.0 / 3.0);\n  }\n\n  w[9] = 3.0 / 4.0 * res;  // K\n\n  // center original matrix\n  VectorXd v1 = Scores.col(0);\n  VectorXd v2 = Scores.col(1);\n  VectorXd v3 = Scores.col(2);\n\n  //  inverse of the kurtosis\n  if (v1.array().pow(4).sum() > 0) {\n    w[10] = numAtoms * pow(w[0], 2) / v1.array().pow(4).sum();  // E1\n  } else {\n    w[10] = 0.0;\n  }\n\n  if (v2.array().pow(4).sum() > 0) {\n    w[11] = numAtoms * pow(w[1], 2) / v2.array().pow(4).sum();  // E2\n  } else {\n    w[11] = 0.0;\n  }\n\n  if (v3.array().pow(4).sum() > 0) {\n    w[12] = numAtoms * pow(w[2], 2) / v3.array().pow(4).sum();  // E3\n  } else {\n    w[12] = 0.0;\n  }\n\n  w[13] = (w[10] + w[11] + w[12]) / 3.0;  // mean total density of the atoms\n                                          // called D is used on Dragon 6 not\n                                          // just the sum!\n\n  // check if the molecule is fully symmetrical \"like CH4\" using Canonical Rank\n  // Index and/or Sphericity !\n\n  double gamma[3];  // Gamma values\n  double nAT = (double)numAtoms;\n\n  // check if two atoms are symetric versus the new axis ie newx,newy,newz a\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < numAtoms; j++) {\n      Scores(j, i) = roundn(Scores(j, i),\n                            3);  // round the matrix! same as eigen tolerance !\n    }\n  }\n  \n\t  \n//\u00a0we should take into account atoms that are in the axis too!!! which is not trivial\n  for (int i = 0; i < 3; i++) {\n    std::vector<double> Symetric(2*numAtoms, 0.0);\n    double ns = 0.0;\n    double na = 0.0;\n    for (int j = 0; j < numAtoms; j++) {\n      bool amatch = false;\n      for (int k = 0; k < numAtoms; k++) {\n\t      if (j==k) {\n          continue;\n        }\n\t      if (std::abs(Scores(j, i) + Scores(k, i)) <= th) {\n\t\t      // those that are close opposite & not close to the axis!\n\t        ns += 1;  // check only once the symetric none null we need to add +2!\n\t\t      // (reduce the loop duration)\n\t\t      amatch = true;\n\t\t      Symetric[j]=1.0;\n\t\t      Symetric[j+numAtoms]=2.0;\n\t\t      Symetric[k]=1.0;\n\t\t      Symetric[k+numAtoms]=2.0;\n\t\t      break;\n        }\n      }\n      if (!amatch) {\n        na +=1;\n        Symetric[j]=0.0;\n        Symetric[j+numAtoms]=std::abs(Scores(j, i));\n      }\n    }\n    // take into account the atoms close to the axis\n    for (int aj = 0; aj < numAtoms; aj++) {\n\t    if (Symetric[aj+numAtoms]<th && Symetric[aj]<1.0) {\n\t\t    ns +=1;\n        na -=1;\t\n      }\n    }\n    gamma[i] = 0.0;\n    double gammainv=1.0;\n    if (ns == 0) {\n      gammainv = 1.0 - (na / nAT) * log(1.0 / nAT) / log(2.);  \n    }\n    if (ns > 0) {\n      gammainv = 1.0 - ((ns / nAT) * log(ns / nAT) / log(2.) +\n                       (na / nAT) * log(1.0 / nAT) / log(2.));   \n    }\n    gamma[i]=1.0/gammainv;\n  }\n  w[14] = gamma[0];  // G1\n  w[15] = gamma[1];  // G2\n  w[16] = gamma[2];  // G3\n  w[17] = pow(gamma[0] * gamma[1] * gamma[2], 1.0 / 3.0);\n  delete svd;\n\n  return w;\n}\n\nvoid GetWHIMs(const Conformer &conf, std::vector<double> &result,\n              double *Vpoints, double th) {\n  std::vector<double> wu(18);\n  std::vector<double> wm(18);\n  std::vector<double> wv(18);\n  std::vector<double> we(18);\n  std::vector<double> wp(18);\n  std::vector<double> wi(18);\n  std::vector<double> ws(18);\n\n  int numAtoms = conf.getNumAtoms();\n  Map<MatrixXd> matorigin(Vpoints, 3, numAtoms);\n  MatrixXd MatOrigin = matorigin.transpose();\n  std::vector<double> weigthvector;\n\n  // intermediate 18 values stored in this order per weighted vector :\n  // \"L1\",\"L2\",\"L3\",\"T\",\"A\",\"V\",\"P1\",\"P2\",\"P3\",\"K\",\"E1\",\"E2\",\"E3\",\"D\",\"G1\",\"G2\",\"G3\",\"G\"\n  weigthvector = moldata3D.GetUn(numAtoms);\n  wu = getWhimD(weigthvector, MatOrigin, numAtoms, th);\n\n  weigthvector = moldata3D.GetRelativeMW(conf.getOwningMol());\n  wm = getWhimD(weigthvector, MatOrigin, numAtoms, th);\n\n  weigthvector = moldata3D.GetRelativeVdW(conf.getOwningMol());\n  wv = getWhimD(weigthvector, MatOrigin, numAtoms, th);\n\n  weigthvector = moldata3D.GetRelativeENeg(conf.getOwningMol());\n  we = getWhimD(weigthvector, MatOrigin, numAtoms, th);\n\n  weigthvector = moldata3D.GetRelativePol(conf.getOwningMol());\n  wp = getWhimD(weigthvector, MatOrigin, numAtoms, th);\n\n  weigthvector = moldata3D.GetRelativeIonPol(conf.getOwningMol());\n  wi = getWhimD(weigthvector, MatOrigin, numAtoms, th);\n\n  weigthvector = moldata3D.GetIState(conf.getOwningMol());\n  ws = getWhimD(weigthvector, MatOrigin, numAtoms, th);\n\n  result.clear();\n  result.resize(126);\n\n  for (int i = 0; i < 18; i++) {\n    result[i + 18 * 0] = wu[i];\n    result[i + 18 * 1] = wm[i];\n    result[i + 18 * 2] = wv[i];\n    result[i + 18 * 3] = we[i];\n    result[i + 18 * 4] = wp[i];\n    result[i + 18 * 5] = wi[i];\n    result[i + 18 * 6] = ws[i];\n  }\n  wu.clear();\n  wm.clear();\n  wv.clear();\n  we.clear();\n  wp.clear();\n  wi.clear();\n  ws.clear();\n}\n\nvoid getWHIM(const ROMol &mol, std::vector<double> &res, int confId,\n             double th) {\n  int numAtoms = mol.getNumAtoms();\n  const Conformer &conf = mol.getConformer(confId);\n  double *Vpoints = new double[3 * numAtoms];\n\n  for (int i = 0; i < numAtoms; ++i) {\n    Vpoints[3 * i] = conf.getAtomPos(i).x;\n    Vpoints[3 * i + 1] = conf.getAtomPos(i).y;\n    Vpoints[3 * i + 2] = conf.getAtomPos(i).z;\n  }\n\n  std::vector<double> w(126);\n  GetWHIMs(conf, w, Vpoints, th);\n  delete [] Vpoints;\n\n  // Dragon extract only this list in this order : L1 L2 L3 P1 P2 G1 G2 G3 E1 E2\n  // E3\n  int map1[11] = {0, 1, 2, 6, 7, 14, 15, 16, 10, 11, 12};\n\n  for (int k = 0; k < 7; k++) {\n    for (int i = 0; i < 11; i++) {\n      res[i + 11 * k] = roundn(w[map1[i] + 18 * k], 3);\n    }\n  }\n\n  for (int i = 0; i < 2; i++) {\n    res[i + 13 * 7] = roundn(w[17 + 18 * i], 3);  // 92  93 for Gu  Gm\n  }\n\n  for (int i = 0; i < 7; i++) {\n    res[i + 11 * 7] =\n        roundn(w[3 + 18 * i],\n               3);  // 78  79  80  81  82  83  84  for Tu  Tm  Tv  Te  Tp  Ti Ts\n    res[i + 12 * 7] =\n        roundn(w[4 + 18 * i],\n               3);  // 85  86  87  88  89  90  91  for Tu  Am  Av  Ae  Ap  Ai As\n    res[i + 13 * 7 + 2] =\n        roundn(w[9 + 18 * i],\n               3);  // 94  95  96  97  98  99  100 for Ku  Km  Kv  Ke  Kp  Ki Ks\n    res[i + 14 * 7 + 2] =\n        roundn(w[13 + 18 * i],\n               3);  // 101 102 103 104 105 106 107 for Du  Dm  Dv  De  Dp  Di Ds\n    res[i + 15 * 7 + 2] =\n        roundn(w[5 + 18 * i],\n               3);  // 108 109 110 111 112 113 114 for Vu  Vm  Vv  Ve  Vp  Vi Vs\n  }\n}\n\n}  // end of anonymous namespace\n\nvoid WHIM(const ROMol &mol, std::vector<double> &res, int confId, double th) {\n  PRECONDITION(mol.getNumConformers() >= 1, \"molecule has no conformers\")\n  // Dragon final list is: L1u L2u L3u P1u P2u G1u G2u G3u E1u E2u E3u L1m L2m\n  // L3m P1m P2m G1m G2m G3m E1m E2m E3m L1v L2v L3v P1v P2v G1v G2v G3v E1v E2v\n  // E3v L1e L2e L3e P1e P2e G1e G2e G3e E1e E2e E3e L1p L2p L3p P1p P2p G1p G2p\n  // G3p E1p E2p E3p L1i L2i L3i P1i P2i G1i G2i G3i E1i E2i E3i L1s L2s L3s P1s\n  // P2s G1s G2s G3s E1s E2s E3s Tu  Tm  Tv  Te  Tp  Ti  Ts  Au  Am  Av  Ae  Ap\n  // Ai  As  Gu  Gm  Ku  Km  Kv  Ke  Kp  Ki  Ks  Du  Dm  Dv  De  Dp  Di  Ds  Vu\n  // Vm  Vv  Ve  Vp  Vi  Vs\n\n  res.clear();\n  res.resize(114);\n  getWHIM(mol, res, confId, th);\n}\n}  // end of Descriptors namespace\n}  // end of RDKit namespace\n", "meta": {"hexsha": "0f4131a58855a995d8ee50c61735edcee3a0c822", "size": 11019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/Descriptors/WHIM.cpp", "max_stars_repo_name": "docking-org/rdk", "max_stars_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_stars_repo_licenses": ["PostgreSQL"], "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/GraphMol/Descriptors/WHIM.cpp", "max_issues_repo_name": "docking-org/rdk", "max_issues_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_issues_repo_licenses": ["PostgreSQL"], "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/GraphMol/Descriptors/WHIM.cpp", "max_forks_repo_name": "docking-org/rdk", "max_forks_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_forks_repo_licenses": ["PostgreSQL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6973293769, "max_line_length": 88, "alphanum_fraction": 0.5890734186, "num_tokens": 3951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.505055013962949}}
{"text": "//\n// Copyright (c) 2016,2018 CNRS\n//\n\n#include \"pinocchio/spatial/se3.hpp\"\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/dynamics.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n#include \"pinocchio/utils/timer.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE ( test_FD )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model,true);\n  pinocchio::Data data(model);\n  \n  VectorXd q = VectorXd::Ones(model.nq);\n  q.segment <4> (3).normalize();\n  \n  pinocchio::computeJointJacobians(model, data, q);\n  \n  VectorXd v = VectorXd::Ones(model.nv);\n  VectorXd tau = VectorXd::Zero(model.nv);\n  \n  const std::string RF = \"rleg6_joint\";\n  const std::string LF = \"lleg6_joint\";\n  \n  Data::Matrix6x J_RF (6, model.nv);\n  J_RF.setZero();\n  getJointJacobian(model, data, model.getJointId(RF), LOCAL, J_RF);\n  Data::Matrix6x J_LF (6, model.nv);\n  J_LF.setZero();\n  getJointJacobian(model, data, model.getJointId(LF), LOCAL, J_LF);\n  \n  Eigen::MatrixXd J (12, model.nv);\n  J.setZero();\n  J.topRows<6> () = J_RF;\n  J.bottomRows<6> () = J_LF;\n  \n  Eigen::VectorXd gamma (VectorXd::Ones(12));\n  \n  Eigen::MatrixXd H(J.transpose());\n  \n  pinocchio::forwardDynamics(model, data, q, v, tau, J, gamma, 0.,true);\n  data.M.triangularView<Eigen::StrictlyLower>() = data.M.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  MatrixXd Minv (data.M.inverse());\n  MatrixXd JMinvJt (J * Minv * J.transpose());\n  \n  Eigen::MatrixXd G_ref(J.transpose());\n  cholesky::Uiv(model, data, G_ref);\n  for(int k=0;k<model.nv;++k) G_ref.row(k) /= sqrt(data.D[k]);\n    Eigen::MatrixXd H_ref(G_ref.transpose() * G_ref);\n    BOOST_CHECK(H_ref.isApprox(JMinvJt,1e-12));\n  \n  VectorXd lambda_ref = -JMinvJt.inverse() * (J*Minv*(tau - data.nle) + gamma);\n  BOOST_CHECK(data.lambda_c.isApprox(lambda_ref, 1e-12));\n    \n  VectorXd a_ref = Minv*(tau - data.nle + J.transpose()*lambda_ref);\n  \n  Eigen::VectorXd dynamics_residual_ref (data.M * a_ref + data.nle - tau - J.transpose()*lambda_ref);\n  BOOST_CHECK(dynamics_residual_ref.norm() <= 1e-11); // previously 1e-12, may be due to numerical approximations, i obtain 2.03e-12\n\n  Eigen::VectorXd constraint_residual (J * data.ddq + gamma);\n  BOOST_CHECK(constraint_residual.norm() <= 1e-12);\n  \n  Eigen::VectorXd dynamics_residual (data.M * data.ddq + data.nle - tau - J.transpose()*data.lambda_c);\n  BOOST_CHECK(dynamics_residual.norm() <= 1e-12);\n  \n}\n\nBOOST_AUTO_TEST_CASE ( test_FD_with_damping )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model,true);\n  pinocchio::Data data(model);\n  \n  VectorXd q = VectorXd::Ones(model.nq);\n  q.segment <4> (3).normalize();\n  \n  pinocchio::computeJointJacobians(model, data, q);\n  \n  VectorXd v = VectorXd::Ones(model.nv);\n  VectorXd tau = VectorXd::Zero(model.nv);\n  \n  const std::string RF = \"rleg6_joint\";\n  \n  Data::Matrix6x J_RF (6, model.nv);\n  J_RF.setZero();\n  getJointJacobian(model, data, model.getJointId(RF), LOCAL, J_RF);\n\n  Eigen::MatrixXd J (12, model.nv);\n  J.setZero();\n  J.topRows<6> () = J_RF;\n  J.bottomRows<6> () = J_RF;\n  \n  Eigen::VectorXd gamma (VectorXd::Ones(12));\n\n  // Forward Dynamics with damping\n  pinocchio::forwardDynamics(model, data, q, v, tau, J, gamma, 1e-12,true);\n\n  // Matrix Definitions\n  Eigen::MatrixXd H(J.transpose());\n  data.M.triangularView<Eigen::StrictlyLower>() =\n    data.M.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  MatrixXd Minv (data.M.inverse());\n  MatrixXd JMinvJt (J * Minv * J.transpose());\n\n  // Check that JMinvJt is correctly formed\n  Eigen::MatrixXd G_ref(J.transpose());\n  cholesky::Uiv(model, data, G_ref);\n  for(int k=0;k<model.nv;++k) G_ref.row(k) /= sqrt(data.D[k]);\n  Eigen::MatrixXd H_ref(G_ref.transpose() * G_ref);\n  BOOST_CHECK(H_ref.isApprox(JMinvJt,1e-12));\n\n  // Actual Residuals\n  Eigen::VectorXd constraint_residual (J * data.ddq + gamma);  \n  Eigen::VectorXd dynamics_residual (data.M * data.ddq + data.nle - tau - J.transpose()*data.lambda_c);\n  BOOST_CHECK(constraint_residual.norm() <= 1e-9);\n  BOOST_CHECK(dynamics_residual.norm() <= 1e-12);\n}\n\nBOOST_AUTO_TEST_CASE ( test_ID )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model,true);\n  pinocchio::Data data(model);\n  \n  VectorXd q = VectorXd::Ones(model.nq);\n  q.segment <4> (3).normalize();\n  \n  pinocchio::computeJointJacobians(model, data, q);\n  \n  VectorXd v_before = VectorXd::Ones(model.nv);\n  \n  const std::string RF = \"rleg6_joint\";\n  const std::string LF = \"lleg6_joint\";\n  \n  Data::Matrix6x J_RF (6, model.nv);\n  J_RF.setZero();\n  getJointJacobian(model, data, model.getJointId(RF), LOCAL, J_RF);\n  Data::Matrix6x J_LF (6, model.nv);\n  J_LF.setZero();\n  getJointJacobian(model, data, model.getJointId(LF), LOCAL, J_LF);\n  \n  Eigen::MatrixXd J (12, model.nv);\n  J.setZero();\n  J.topRows<6> () = J_RF;\n  J.bottomRows<6> () = J_LF;\n  \n  const double r_coeff = 1.;\n  \n  Eigen::MatrixXd H(J.transpose());\n  \n  pinocchio::impulseDynamics(model, data, q, v_before, J, r_coeff, true);\n  data.M.triangularView<Eigen::StrictlyLower>() = data.M.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  MatrixXd Minv (data.M.inverse());\n  MatrixXd JMinvJt (J * Minv * J.transpose());\n  \n  Eigen::MatrixXd G_ref(J.transpose());\n  cholesky::Uiv(model, data, G_ref);\n  for(int k=0;k<model.nv;++k) G_ref.row(k) /= sqrt(data.D[k]);\n  Eigen::MatrixXd H_ref(G_ref.transpose() * G_ref);\n  BOOST_CHECK(H_ref.isApprox(JMinvJt,1e-12));\n  \n  VectorXd lambda_ref = JMinvJt.inverse() * (-r_coeff * J * v_before - J * v_before);\n  BOOST_CHECK(data.impulse_c.isApprox(lambda_ref, 1e-12));\n  \n  VectorXd v_after_ref = Minv*(data.M * v_before + J.transpose()*lambda_ref);\n  \n  Eigen::VectorXd constraint_residual (J * data.dq_after + r_coeff * J * v_before);\n  BOOST_CHECK(constraint_residual.norm() <= 1e-12);\n  \n  Eigen::VectorXd dynamics_residual (data.M * data.dq_after - data.M * v_before - J.transpose()*data.impulse_c);\n  BOOST_CHECK(dynamics_residual.norm() <= 1e-12);\n}\n\nBOOST_AUTO_TEST_CASE (timings_fd_llt)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model,true);\n  pinocchio::Data data(model);\n  \n#ifdef NDEBUG\n#ifdef _INTENSE_TESTING_\n  const size_t NBT = 1000*1000;\n#else\n  const size_t NBT = 100;\n#endif\n  \n#else\n  const size_t NBT = 1;\n  std::cout << \"(the time score in debug mode is not relevant)  \" ;\n#endif // ifndef NDEBUG\n  \n  VectorXd q = VectorXd::Ones(model.nq);\n  q.segment <4> (3).normalize();\n  \n  pinocchio::computeJointJacobians(model, data, q);\n  \n  VectorXd v = VectorXd::Ones(model.nv);\n  VectorXd tau = VectorXd::Zero(model.nv);\n  \n  const std::string RF = \"rleg6_joint\";\n  const std::string LF = \"lleg6_joint\";\n  \n  Data::Matrix6x J_RF (6, model.nv);\n  getJointJacobian(model, data, model.getJointId(RF), LOCAL, J_RF);\n  Data::Matrix6x J_LF (6, model.nv);\n  getJointJacobian(model, data, model.getJointId(LF), LOCAL, J_LF);\n  \n  Eigen::MatrixXd J (12, model.nv);\n  J.topRows<6> () = J_RF;\n  J.bottomRows<6> () = J_LF;\n  \n  Eigen::VectorXd gamma (VectorXd::Ones(12));\n  \n  model.lowerPositionLimit.head<7>().fill(-1.);\n  model.upperPositionLimit.head<7>().fill( 1.);\n  \n  q = pinocchio::randomConfiguration(model);\n  \n  PinocchioTicToc timer(PinocchioTicToc::US); timer.tic();\n  SMOOTH(NBT)\n  {\n    pinocchio::forwardDynamics(model, data, q, v, tau, J, gamma, 0., true);\n  }\n  timer.toc(std::cout,NBT);\n  \n}\n\nBOOST_AUTO_TEST_SUITE_END ()\n", "meta": {"hexsha": "ed68ec05b359dd74b9d9c6869937641829a89a28", "size": 7854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/dynamics.cpp", "max_stars_repo_name": "matthieuvigne/pinocchio", "max_stars_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "unittest/dynamics.cpp", "max_issues_repo_name": "matthieuvigne/pinocchio", "max_issues_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "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/dynamics.cpp", "max_forks_repo_name": "matthieuvigne/pinocchio", "max_forks_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 30.560311284, "max_line_length": 132, "alphanum_fraction": 0.6892029539, "num_tokens": 2420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5050516981593185}}
{"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 \"algorithms/util/RTPGHI.hpp\"\n#include \"algorithms/util/PeakDetection.hpp\"\n#include \"algorithms/public/DataSetIdSequence.hpp\"\n#include \"algorithms/util/DistanceFuncs.hpp\"\n#include \"algorithms/public/STFT.hpp\"\n#include \"algorithms/public/KDTree.hpp\"\n#include \"algorithms/public/MelBands.hpp\"\n#include \"algorithms/util/AlgorithmUtils.hpp\"\n#include \"algorithms/util/FluidEigenMappings.hpp\"\n#include \"algorithms/GraphPlayUtils.hpp\"\n#include \"data/TensorTypes.hpp\"\n#include \"data/FluidDataSet.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <vector>\n#include <fstream>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass GraphLoop {\n\npublic:\n  using  MatrixXd = Eigen::MatrixXd;\n  using DataSet = FluidDataSet<std::string, double, 1>;\n\n  void init(RealVectorView audio, index sampleRate,\n            index windowSize, index fftSize, index hopSize, index numBands,\n            index distance, double threshold, bool quantize, RealVectorView output) {\n    using namespace Eigen;\n    using namespace _impl;\n    using namespace std;\n\n    mWindowSize = windowSize;\n    mFFTSize = fftSize;\n    mHopSize = hopSize;\n    mFrameSize = (mFFTSize / 2) + 1;\n    mThreshold = threshold;\n    mBeat = 0;\n\n\n    STFT stft = STFT(mWindowSize, mFFTSize, mHopSize);\n    mLength = std::floor((audio.size() + mHopSize) / mHopSize);\n    mSpectrogram = ComplexMatrix(mLength, mFrameSize);\n    stft.process(audio, mSpectrogram);\n    mMagnitude = RealMatrix(mLength, mFrameSize);\n    stft.magnitude(mSpectrogram, mMagnitude);\n    mDM = mUtils.computeDM(mMagnitude, numBands, sampleRate, windowSize,\n                           fftSize, distance);\n    mDM.diagonal().setZero();\n\n    MatrixXd sim = 1 - mDM.array();\n    ArrayXd beatSpectrum = ArrayXd::Zero(mLength);\n    for(index i = 0; i < mLength; i++){\n      beatSpectrum(i) = sim.diagonal(i).sum() / (mLength - i);\n    }\n    PeakDetection pd;\n    auto bsPeaks = pd.process(beatSpectrum.segment(1,lrint(beatSpectrum.size()/2)), 3, 0, false, true);\n    mBeat = bsPeaks[0].first;\n    if(bsPeaks.size() > 1 && bsPeaks[1].first < mBeat)mBeat = bsPeaks[1].first;\n    if(bsPeaks.size() > 2 && bsPeaks[2].first < mBeat)mBeat = bsPeaks[2].first;\n    mFilter.init(5);\n    ArrayXd odf = mDM.diagonal(1).array();\n    for(index i = 0; i < odf.size(); i++){\n      odf(i) = odf(i) - mFilter.processSample(odf(i));\n    }\n    auto onsets = mPD.process(odf, 0, 0.1, false, false);\n    mOnsets = Eigen::VectorXi::Zero(mLength);\n    for(index i = 0; i < onsets.size(); i++){\n      mOnsets(onsets[i].first) = 1;\n    }\n    mLoop = RealVector{0, static_cast<double>(mLength)};\n    fit(threshold, quantize);\n    output(0)  = mLoop(0);\n    output(1)  = mLoop(1);\n    output(2)  = mBeat;\n    output(3)  = mNumLinks;\n    mInitialized = true;\n  }\n\n  void fit(double threshold, bool quantize){\n    index stride = quantize?mBeat:1;\n    algorithm::DataSetIdSequence seq(\"\", 0, 0);\n    mDataSet = DataSet(2);\n    for(index i = 0; i <mLength; i++){\n      for(index j = i + stride; j < mDM.rows(); j+=stride){\n        if(mDM(i,j) < threshold || (quantize && mOnsets(i) > 0)){\n          RealVector tmp{\n            static_cast<double>(i),\n            static_cast<double>(j)\n          };\n          mDataSet.add(seq.next(),tmp);\n        }\n      }\n    }\n    mTree = KDTree(mDataSet);\n    mNumLinks = mTree.size();\n  }\n\n  void findLoop(){\n    RealVector tmpPoint(2);\n    auto query = RealVector { static_cast<double>(mStartFrame), static_cast<double>(mEndFrame)};\n    auto nearest = mTree.kNearest(query, 1);\n    auto nearestIds = nearest.getIds();\n    if(nearestIds.size() > 0){\n      mDataSet.get(nearestIds(0), mLoop);\n    }\n\n  }\n\n  void processFrame(ComplexVectorView out, double start, double end, RealVectorView output) {\n    using namespace Eigen;\n    using namespace _impl;\n    index startFrame = lrint(start * mSpectrogram.rows());\n    index endFrame = lrint(end * mSpectrogram.rows());\n    if(startFrame != mStartFrame || endFrame != mEndFrame){\n      mStartFrame = startFrame;\n      mEndFrame = endFrame;\n      findLoop();\n    }\n    out = mSpectrogram.row(mPos);\n    mPos = (mPos + 1) % mSpectrogram.rows();\n    if(mPos >= mLoop(1))mPos = mLoop(0);\n    output(0)  = mLoop(0);\n    output(1)  = mLoop(1);\n    output(2)  = mBeat;\n    output(3)  = mNumLinks;\n  }\n\n  bool initialized(){\n    return mInitialized;\n  }\n\n  index mWindowSize;\n  index mHopSize;\n  index mFFTSize;\n\nprivate:\n  index mFrameSize;\n  GraphPlayUtils mUtils;\n  RealVector mLoop;\n  ComplexMatrix mSpectrogram;\n  RealMatrix mMagnitude;\n  RealMatrix mMelSpectrogram;\n  Eigen::VectorXi mOnsets;\n  KDTree mTree;\n  MatrixXd mDM;\n  DataSet mDataSet;\n  bool mInitialized{false};\n  int mPos{0};\n  index mLength;\n  index mBeat;\n  index mStartFrame;\n  index mEndFrame;\n  double mThreshold;\n  index mNumLinks;\n  MedianFilter mFilter;\n  PeakDetection mPD;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "6f5c26ee2d3de957b7d55e07d96d9585872b05a2", "size": 5287, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/GraphLoop.hpp", "max_stars_repo_name": "flucoma/graph_loop_grain", "max_stars_repo_head_hexsha": "db9bbc603412d44a49b0d882bc3fdb604aeb63d1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-06-05T10:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T10:40:25.000Z", "max_issues_repo_path": "include/algorithms/GraphLoop.hpp", "max_issues_repo_name": "flucoma/graph_loop_grain", "max_issues_repo_head_hexsha": "db9bbc603412d44a49b0d882bc3fdb604aeb63d1", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/GraphLoop.hpp", "max_forks_repo_name": "flucoma/graph_loop_grain", "max_forks_repo_head_hexsha": "db9bbc603412d44a49b0d882bc3fdb604aeb63d1", "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.3850574713, "max_line_length": 103, "alphanum_fraction": 0.6667297144, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5050516902617918}}
{"text": "#define BOOST_TEST_NO_LIB\n#include <boost/test/auto_unit_test.hpp>\n\n#include \"coconut/pulp/math/homogeneous.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(PulpMathHomogeneousCoordsTestSuite);\n\nBOOST_AUTO_TEST_CASE(HomogeneousCoordsConstructibleFromVec4) {\n\tconst auto h = HomogeneousCoordinates({ 1.0f, 2.0f, 3.0f, 4.0f });\n\tBOOST_CHECK_EQUAL(h, Vec4(1.0f, 2.0f, 3.0f, 4.0f));\n}\n\nBOOST_AUTO_TEST_CASE(HomogeneousCoordsConstructibleFromVec3Point) {\n\tconst auto h = HomogeneousPoint({ 1.0f, 2.0f, 3.0f });\n\tBOOST_CHECK_EQUAL(h, Vec4(1.0f, 2.0f, 3.0f, 1.0f));\n}\n\nBOOST_AUTO_TEST_CASE(HomogeneousCoordsConstructibleFromVec3Vector) {\n\tconst auto h = HomogeneousVector({ 1.0f, 2.0f, 3.0f });\n\tBOOST_CHECK_EQUAL(h, Vec4(1.0f, 2.0f, 3.0f, 0.0f));\n}\n\nBOOST_AUTO_TEST_CASE(CanObtain3dImageOfHomogeneousCoordinates) {\n\tconst auto p = HomogeneousPoint({ 1.0f, 2.0f, 3.0f });\n\tconst auto v = HomogeneousVector({ 1.0f, 2.0f, 3.0f });\n\tconst auto h = HomogeneousCoordinates({ 3.0f, 3.0f, 3.0f, 3.0f });\n\n\tBOOST_CHECK_EQUAL(p.to3dSpace(), Vec3(1.0f, 2.0f, 3.0f));\n\tBOOST_CHECK_EQUAL(v.to3dSpace(), Vec3(1.0f, 2.0f, 3.0f));\n\tBOOST_CHECK_EQUAL(h.to3dSpace(), Vec3(1.0f, 1.0f, 1.0f));\n}\n\nBOOST_AUTO_TEST_SUITE_END(/* PulpMathHomogeneousCoordsTestSuite */);\nBOOST_AUTO_TEST_SUITE_END(/* PulpMathTestSuite */);\nBOOST_AUTO_TEST_SUITE_END(/* PulpTestSuite */);\n\n} // namespace anonymous\n", "meta": {"hexsha": "dc75bb75285b7d1ea10225df60e1c5d937266ff7", "size": 1548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "coconut-pulp-math/src/test/c++/coconut/pulp/math/homogeneous.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/homogeneous.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/homogeneous.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": 33.652173913, "max_line_length": 68, "alphanum_fraction": 0.7532299742, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5049862550813491}}
{"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#define BOOST_TEST_MODULE TestTransformIterator\n#include <boost/test/unit_test.hpp>\n\n#include <iterator>\n\n#include <boost/type_traits.hpp>\n#include <boost/static_assert.hpp>\n\n#include <boost/compute/types.hpp>\n#include <boost/compute/functional.hpp>\n#include <boost/compute/algorithm/copy.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/iterator/buffer_iterator.hpp>\n#include <boost/compute/iterator/transform_iterator.hpp>\n\n#include \"check_macros.hpp\"\n#include \"context_setup.hpp\"\n\nBOOST_AUTO_TEST_CASE(value_type)\n{\n    using boost::compute::float4_;\n\n    BOOST_STATIC_ASSERT((\n        boost::is_same<\n            boost::compute::transform_iterator<\n                boost::compute::buffer_iterator<float>,\n                boost::compute::sqrt<float>\n            >::value_type,\n            float\n        >::value\n    ));\n    BOOST_STATIC_ASSERT((\n        boost::is_same<\n            boost::compute::transform_iterator<\n                boost::compute::buffer_iterator<float4_>,\n                boost::compute::length<float4_>\n            >::value_type,\n            float\n        >::value\n    ));\n}\n\nBOOST_AUTO_TEST_CASE(copy)\n{\n    int data[] = { 1, -2, 3, -4, 5 };\n    boost::compute::vector<int> a(data, data + 5, queue);\n\n    boost::compute::vector<int> b(5, context);\n    boost::compute::copy(\n        boost::compute::make_transform_iterator(\n            a.begin(),\n            boost::compute::abs<int>()\n        ),\n        boost::compute::make_transform_iterator(\n            a.end(),\n            boost::compute::abs<int>()\n        ),\n        b.begin(),\n        queue\n    );\n    CHECK_RANGE_EQUAL(int, 5, b, (1, 2, 3, 4, 5));\n}\n\nBOOST_AUTO_TEST_CASE(copy_abs_doctest)\n{\n    int data[] = { -1, -2, -3, -4 };\n    boost::compute::vector<int> input(data, data + 4, queue);\n    boost::compute::vector<int> output(4, context);\n\n//! [copy_abs]\n// use abs() from boost.compute\nusing boost::compute::abs;\n\n// copy the absolute value for each element in input to output\nboost::compute::copy(\n    boost::compute::make_transform_iterator(input.begin(), abs<int>()),\n    boost::compute::make_transform_iterator(input.end(), abs<int>()),\n    output.begin(),\n    queue\n);\n//! [copy_abs]\n\n    CHECK_RANGE_EQUAL(int, 4, output, (1, 2, 3, 4));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3ef55651fec1f524a67ddad36976c8d6507d1239", "size": 2729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_transform_iterator.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": "2021-01-31T17:12:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T17:12:33.000Z", "max_issues_repo_path": "test/test_transform_iterator.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": "test/test_transform_iterator.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.1340206186, "max_line_length": 79, "alphanum_fraction": 0.5983876878, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5049862507505115}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <algorithm>\n#include <memory>\n#include \"../mean_curvature_solver.h\"\n#include \"../utilities.h\"\n#include \"../uniform_lb_operator.h\"\n#include \"../cotangent_lb_operator.h\"\n\nusing SolverPtrT = std::unique_ptr<mcurv::MeanCurvatureSolver>;\n\nchar *getCmdOption(char **begin, char **end, const std::string &option) {\n    char **itr = std::find(begin, end, option);\n    if (itr != end && ++itr != end) {\n        return *itr;\n    }\n    return 0;\n}\n\nbool cmdOptionExists(char **begin, char **end, const std::string &option) {\n    return std::find(begin, end, option) != end;\n}\n\nvoid printHelpMessage() {\n    std::cout << \"The app usage: ./MeanCurvatureApp -i path1 -o path2 -c\\n\";\n    std::cout << \"-i  Path to .off file.\\n\";\n    std::cout << \"-o  Path to user's output file.\\n\";\n    std::cout << \"-c  (OPTIONAL) If specified cotangent Laplace-Beltrami operator will be used. Otherwise the uniform one.\\n\";\n}\n\nint main(int argc, char **argv) {\n    // If requested - print help information\n    if (cmdOptionExists(argv, argv + argc, \"-h\") ||\n        cmdOptionExists(argv, argv + argc, \"--help\")) {\n        printHelpMessage();\n        return 0;\n    }\n\n    // If input and output flags are not present - error\n    if (!cmdOptionExists(argv, argv + argc, \"-i\") ||\n        !cmdOptionExists(argv, argv + argc, \"-o\")) {\n        printHelpMessage();\n        return 1;\n    }\n\n    std::string inputFileName(getCmdOption(argv, argv + argc, \"-i\"));\n    std::string outputFileName (getCmdOption(argv, argv + argc, \"-o\"));\n\n    // Load appropriate solver\n    SolverPtrT solverPtr;\n    if (cmdOptionExists(argv, argv + argc, \"-c\")) {\n        solverPtr = SolverPtrT(\n                new mcurv::MeanCurvatureSolver(mcurv::cotangentLBOperatorStrategy));\n    } else {\n        solverPtr = SolverPtrT(\n                new mcurv::MeanCurvatureSolver(mcurv::uniformLBOperatorStrategy));\n    }\n\n    // Calculate the solution\n    Eigen::MatrixXd solution;\n    solverPtr->Execute(solution, inputFileName);\n\n    // Save to specified file\n    mcurv::dumpMatrixXdToFile(solution, outputFileName);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "6b7150100b4b78be98b058fe511c1486b5627949", "size": 2124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/app/main.cpp", "max_stars_repo_name": "dybiszb/MeanCurvatureLibrary", "max_stars_repo_head_hexsha": "b168911ef6bf08b283e7a225cc006b850fe26400", "max_stars_repo_licenses": ["MIT"], "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/app/main.cpp", "max_issues_repo_name": "dybiszb/MeanCurvatureLibrary", "max_issues_repo_head_hexsha": "b168911ef6bf08b283e7a225cc006b850fe26400", "max_issues_repo_licenses": ["MIT"], "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": "code/app/main.cpp", "max_forks_repo_name": "dybiszb/MeanCurvatureLibrary", "max_forks_repo_head_hexsha": "b168911ef6bf08b283e7a225cc006b850fe26400", "max_forks_repo_licenses": ["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.7826086957, "max_line_length": 126, "alphanum_fraction": 0.6355932203, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5049862506054446}}
{"text": "#include <gtest/gtest.h>\n\n#include <Eigen/Eigen>\n#include <boost/filesystem.hpp>\n\n#include <CppADCodeGenEigenPy/ADModel.h>\n#include <CppADCodeGenEigenPy/CompiledModel.h>\n#include <CppADCodeGenEigenPy/Util.h>\n\n#include \"testing/models/ParameterizedTestModel.h\"\n\nnamespace CppADCodeGenEigenPy {\nnamespace ParameterizedModelTest {\n\nclass ParameterizedTestModelFixture : public ::testing::Test {\n   protected:\n    using Vector = CompiledModel<Scalar>::Vector;\n    using Matrix = CompiledModel<Scalar>::Matrix;\n\n    static void SetUpTestSuite() {\n        // Compile and load our model\n        boost::filesystem::create_directories(DIRECTORY_PATH);\n        ad_model_ptr_.reset(new ParameterizedTestModel<Scalar>());\n        ad_model_ptr_->compile(MODEL_NAME, DIRECTORY_PATH,\n                               DerivativeOrder::Second);\n        compiled_model_ptr_.reset(\n            new CompiledModel<Scalar>(MODEL_NAME, LIB_GENERIC_PATH));\n    }\n\n    static void TearDownTestSuite() {\n        // Delete the compiled shared object.\n        boost::filesystem::remove_all(DIRECTORY_PATH);\n    }\n\n    static std::unique_ptr<ADModel<Scalar>> ad_model_ptr_;\n    static std::unique_ptr<CompiledModel<Scalar>> compiled_model_ptr_;\n};\n\nstd::unique_ptr<ADModel<Scalar>>\n    ParameterizedTestModelFixture::ad_model_ptr_ = nullptr;\nstd::unique_ptr<CompiledModel<Scalar>>\n    ParameterizedTestModelFixture::compiled_model_ptr_ = nullptr;\n\nTEST_F(ParameterizedTestModelFixture, Evaluation) {\n    Vector input = 2 * Vector::Ones(NUM_INPUT);\n    Vector parameters = Vector::Ones(NUM_INPUT);\n\n    Vector output_expected = evaluate<Scalar>(input, parameters);\n    Vector output_actual = compiled_model_ptr_->evaluate(input, parameters);\n    EXPECT_TRUE(output_actual.isApprox(output_expected))\n        << \"Function evaluation is incorrect.\";\n\n    // if I forget to pass the parameters, I should get a runtime error\n    EXPECT_THROW(compiled_model_ptr_->evaluate(input), std::runtime_error)\n        << \"Missing parameters did not throw error.\";\n}\n\nTEST_F(ParameterizedTestModelFixture, Jacobian) {\n    Vector input = 2 * Vector::Ones(NUM_INPUT);\n    Vector parameters = Vector::Ones(NUM_INPUT);\n\n    // note Jacobian of scalar function is a row vector, hence the transpose\n    Matrix P = Matrix::Zero(NUM_INPUT, NUM_INPUT);\n    P.diagonal() << parameters;\n    Matrix J_expected = input.transpose() * P;\n    Matrix J_actual = compiled_model_ptr_->jacobian(input, parameters);\n    EXPECT_TRUE(J_actual.isApprox(J_expected)) << \"Jacobian is incorrect.\";\n\n    EXPECT_THROW(compiled_model_ptr_->jacobian(input), std::runtime_error)\n        << \"Missing parameters did not throw error.\";\n}\n\nTEST_F(ParameterizedTestModelFixture, Hessian) {\n    Vector input = 2 * Vector::Ones(NUM_INPUT);\n    Vector parameters = Vector::Ones(NUM_INPUT);\n\n    Matrix H_expected = Matrix::Zero(NUM_INPUT, NUM_INPUT);\n    H_expected.diagonal() << parameters;\n    Matrix H_actual = compiled_model_ptr_->hessian(input, parameters, 0);\n    EXPECT_TRUE(H_actual.isApprox(H_expected)) << \"Hessian is incorrect.\";\n    EXPECT_THROW(compiled_model_ptr_->hessian(input, 0), std::runtime_error)\n        << \"Missing parameters did not throw error.\";\n}\n\n}  // namespace ParameterizedModelTest\n}  // namespace CppADCodeGenEigenPy\n", "meta": {"hexsha": "5afcab0ddb725bdd380a44ec342826373a74c01d", "size": 3262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cpp_tests/ParameterizedModelTest.cpp", "max_stars_repo_name": "adamheins/CppADCodeGenEigenPy", "max_stars_repo_head_hexsha": "4f85ca831cc554484bbff946e2ffdf2c3e90db81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-11-02T16:37:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:39:30.000Z", "max_issues_repo_path": "tests/cpp_tests/ParameterizedModelTest.cpp", "max_issues_repo_name": "adamheins/CppADCodeGenEigenPy", "max_issues_repo_head_hexsha": "4f85ca831cc554484bbff946e2ffdf2c3e90db81", "max_issues_repo_licenses": ["MIT"], "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/cpp_tests/ParameterizedModelTest.cpp", "max_forks_repo_name": "adamheins/CppADCodeGenEigenPy", "max_forks_repo_head_hexsha": "4f85ca831cc554484bbff946e2ffdf2c3e90db81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-17T23:52:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T23:52:00.000Z", "avg_line_length": 37.4942528736, "max_line_length": 76, "alphanum_fraction": 0.7290006131, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.504986246322963}}
{"text": "/**************************************************************************\n * @file:  UuidTests.cpp\n * @brief:\n *\n * Copyright (c) 2021 O-Net Technologies (Group) Limited.\n **************************************************************************/\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\nTEST(EigenTests, MultiTypeVectors)\n{\n    Eigen::Vector4f v4f(12.1, 12.2, 12.3, 12.4);\n    Eigen::Vector3i v3i(0, -1, 2);\n    Eigen::Vector2d v2d(1.0, 1.5);\n}\n", "meta": {"hexsha": "fe993147fd9bff7d8acb3e6502be0407977488e5", "size": 458, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/common/EigenTests.cpp", "max_stars_repo_name": "o-netusa/cppbase", "max_stars_repo_head_hexsha": "a74c2b1a7eb33fb6cdd7fd54d90f58ae588d269e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-07-24T18:42:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T15:36:28.000Z", "max_issues_repo_path": "tests/common/EigenTests.cpp", "max_issues_repo_name": "o-netusa/cppbase", "max_issues_repo_head_hexsha": "a74c2b1a7eb33fb6cdd7fd54d90f58ae588d269e", "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/common/EigenTests.cpp", "max_forks_repo_name": "o-netusa/cppbase", "max_forks_repo_head_hexsha": "a74c2b1a7eb33fb6cdd7fd54d90f58ae588d269e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-24T17:47:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T02:47:49.000Z", "avg_line_length": 25.4444444444, "max_line_length": 76, "alphanum_fraction": 0.423580786, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5049477379568892}}
{"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 machine learning\n    tools for sequence labeling in the dlib C++ Library.  \n    \n    The general problem addressed by these tools is the following.  \n    Suppose you have a set of sequences of some kind and you want to \n    learn to predict a label for each element of a sequence.  So for \n    example, you might have a set of English sentences where each \n    word is labeled with its part of speech and you want to learn a \n    model which can predict the part of speech for each word in a new \n    sentence.  \n    \n    Central to these tools is the sequence_labeler object.  It is the\n    object which represents the label prediction model. In particular,\n    the model used by this object is the following.  Given an input \n    sequence x, predict an output label sequence y such that:\n        y == argmax_y dot(weight_vector, PSI(x,y))\n    where PSI() is supplied by the user and defines the form of the \n    model.  In this example program we will define it such that we \n    obtain a simple Hidden Markov Model.  However, it's possible to \n    define much more sophisticated models.  You should take a look \n    at the following papers for a few examples:\n        - Hidden Markov Support Vector Machines by \n          Y. Altun, I. Tsochantaridis, T. Hofmann\n        - Shallow Parsing with Conditional Random Fields by \n          Fei Sha and Fernando Pereira\n\n\n\n    In the remainder of this example program we will show how to\n    define your own PSI(), as well as how to learn the \"weight_vector\"\n    parameter.  Once you have these two items you will be able to\n    use the sequence_labeler to predict the labels of new sequences.\n*/\n\n\n#include <iostream>\n#include <dlib/svm_threaded.h>\n#include <dlib/rand.h>\n\nusing namespace std;\nusing namespace dlib;\n\n\n/*\n    In this example we will be working with a Hidden Markov Model where\n    the hidden nodes and observation nodes both take on 3 different states. \n    The task will be to take a sequence of observations and predict the state\n    of the corresponding hidden nodes.  \n*/\n\nconst unsigned long num_label_states = 3; \nconst unsigned long num_sample_states = 3;\n\n// ----------------------------------------------------------------------------------------\n\nclass feature_extractor\n{\n    /*\n        This object is where you define your PSI().  To ensure that the argmax_y\n        remains a tractable problem, the PSI(x,y) vector is actually a sum of vectors, \n        each derived from the entire input sequence x but only part of the label\n        sequence y.  This allows the argmax_y to be efficiently solved using the \n        well known Viterbi algorithm.  \n    */\n\npublic:\n    // This defines the type used to represent the observed sequence.  You can use \n    // any type here so long as it has a .size() which returns the number of things\n    // in the sequence.  \n    typedef std::vector<unsigned long> sequence_type; \n\n    unsigned long num_features() const\n    /*!\n        ensures\n            - returns the dimensionality of the PSI() feature vector.  \n    !*/\n    {\n        // Recall that we are defining a HMM.  So in this case the PSI() vector \n        // should have the same dimensionality as the number of parameters in the HMM.  \n        return num_label_states*num_label_states + num_label_states*num_sample_states;\n    }\n\n    unsigned long order() const \n    /*!\n        ensures\n            - This object represents a Markov model on the output labels.\n              This parameter defines the order of the model.  That is, this \n              value controls how many previous label values get to be taken \n              into consideration when performing feature extraction for a\n              particular element of the input sequence.  Note that the runtime\n              of the algorithm is exponential in the order.  So don't make order\n              very large.\n    !*/\n    { \n        // In this case we are using a HMM model that only looks at the \n        // previous label. \n        return 1; \n    }\n\n    unsigned long num_labels() const \n    /*!\n        ensures\n            - returns the number of possible output labels.\n    !*/\n    { \n        return num_label_states; \n    }\n\n    template <typename feature_setter, typename EXP>\n    void get_features (\n        feature_setter& set_feature,\n        const sequence_type& x,\n        const matrix_exp<EXP>& y,\n        unsigned long position\n    ) const\n    /*!\n        requires\n            - EXP::type == unsigned long\n              (i.e. y contains unsigned longs)\n            - position < x.size()\n            - y.size() == min(position, order) + 1\n            - is_vector(y) == true\n            - max(y) < num_labels() \n            - set_feature is a function object which allows expressions of the form:\n                - set_features((unsigned long)feature_index, (double)feature_value);\n                - set_features((unsigned long)feature_index);\n        ensures\n            - for all valid i:\n                - interprets y(i) as the label corresponding to x[position-i]\n            - This function computes the part of PSI() corresponding to the x[position]\n              element of the input sequence.  Moreover, this part of PSI() is returned as \n              a sparse vector by invoking set_feature().  For example, to set the feature \n              with an index of 55 to the value of 1 this method would call:\n                set_feature(55);\n              Or equivalently:\n                set_feature(55,1);\n              Therefore, the first argument to set_feature is the index of the feature \n              to be set while the second argument is the value the feature should take.\n              Additionally, note that calling set_feature() multiple times with the same \n              feature index does NOT overwrite the old value, it adds to the previous \n              value.  For example, if you call set_feature(55) 3 times then it will\n              result in feature 55 having a value of 3.\n            - This function only calls set_feature() with feature_index values < num_features()\n    !*/\n    {\n        // Again, the features below only define a simple HMM.  But in general, you can \n        // use a wide variety of sophisticated feature extraction methods here.\n\n        // Pull out an indicator feature for the type of transition between the\n        // previous label and the current label.\n        if (y.size() > 1)\n            set_feature(y(1)*num_label_states + y(0));\n\n        // Pull out an indicator feature for the type of observed node given \n        // the current label.\n        set_feature(num_label_states*num_label_states +\n                    y(0)*num_sample_states + x[position]);\n    }\n};\n\n// We need to define serialize() and deserialize() for our feature extractor if we want \n// to be able to serialize and deserialize our learned models.  In this case the \n// implementation is empty since our feature_extractor doesn't have any state.  But you \n// might define more complex feature extractors which have state that needs to be saved.\nvoid serialize(const feature_extractor&, std::ostream&) {}\nvoid deserialize(feature_extractor&, std::istream&) {}\n\n// ----------------------------------------------------------------------------------------\n\nvoid make_dataset (\n    const matrix<double>& transition_probabilities,\n    const matrix<double>& emission_probabilities,\n    std::vector<std::vector<unsigned long> >& samples,\n    std::vector<std::vector<unsigned long> >& labels,\n    unsigned long dataset_size\n);\n/*!\n    requires\n        - transition_probabilities.nr() == transition_probabilities.nc()\n        - transition_probabilities.nr() == emission_probabilities.nr()\n        - The rows of transition_probabilities and emission_probabilities must sum to 1.\n          (i.e. sum_cols(transition_probabilities) and sum_cols(emission_probabilities)\n          must evaluate to vectors of all 1s.)\n    ensures\n        - This function randomly samples a bunch of sequences from the HMM defined by \n          transition_probabilities and emission_probabilities. \n        - The HMM is defined by:\n            - The probability of transitioning from hidden state H1 to H2 \n              is given by transition_probabilities(H1,H2).\n            - The probability of a hidden state H producing an observed state\n              O is given by emission_probabilities(H,O).\n        - #samples.size() == #labels.size() == dataset_size\n        - for all valid i:\n            - #labels[i] is a randomly sampled sequence of hidden states from the\n              given HMM.  #samples[i] is its corresponding randomly sampled sequence\n              of observed states.\n!*/\n\n// ----------------------------------------------------------------------------------------\n\n\n\n#if defined(BUILD_MONOLITHIC)\n#define main(cnt, arr)      dlib_sequence_labeler_ex_main(cnt, arr)\n#endif\n\nint main(int argc, const char** argv)\n{\n    // We need a dataset to test the machine learning algorithms.  So we are going to \n    // define a HMM based on the following two matrices and then randomly sample a\n    // set of data from it.  Then we will see if the machine learning method can\n    // recover the HMM model from the training data. \n\n\n    matrix<double> transition_probabilities(num_label_states, num_label_states);\n    transition_probabilities = 0.05, 0.90, 0.05,\n                               0.05, 0.05, 0.90,\n                               0.90, 0.05, 0.05;\n\n    matrix<double> emission_probabilities(num_label_states,num_sample_states);\n    emission_probabilities = 0.5, 0.5, 0.0,\n                             0.0, 0.5, 0.5,\n                             0.5, 0.0, 0.5;\n\n    std::vector<std::vector<unsigned long> > samples;\n    std::vector<std::vector<unsigned long> > labels;\n    // sample 1000 labeled sequences from the HMM.\n    make_dataset(transition_probabilities,emission_probabilities, \n                 samples, labels, 1000);\n\n    // print out some of the randomly sampled sequences\n    for (int i = 0; i < 10; ++i)\n    {\n        cout << \"hidden states:   \" << trans(mat(labels[i]));\n        cout << \"observed states: \" << trans(mat(samples[i]));\n        cout << \"******************************\" << endl;\n    }\n\n    // Next we use the structural_sequence_labeling_trainer to learn our\n    // prediction model based on just the samples and labels.\n    structural_sequence_labeling_trainer<feature_extractor> trainer;\n    // This is the common SVM C parameter.  Larger values encourage the\n    // trainer to attempt to fit the data exactly but might overfit. \n    // In general, you determine this parameter by cross-validation.\n    trainer.set_c(4);\n    // This trainer can use multiple CPU cores to speed up the training.  \n    // So set this to the number of available CPU cores. \n    trainer.set_num_threads(4);\n\n\n    // Learn to do sequence labeling from the dataset\n    sequence_labeler<feature_extractor> labeler = trainer.train(samples, labels);\n\n    // Test the learned labeler on one of the training samples.  In this\n    // case it will give the correct sequence of labels.\n    std::vector<unsigned long> predicted_labels = labeler(samples[0]);\n    cout << \"true hidden states:      \"<< trans(mat(labels[0]));\n    cout << \"predicted hidden states: \"<< trans(mat(predicted_labels));\n\n\n\n    // We can also do cross-validation.  The confusion_matrix is defined as:\n    //  - confusion_matrix(T,P) == the number of times a sequence element with label T \n    //    was predicted to have a label of P.\n    // So if all predictions are perfect then only diagonal elements of this matrix will\n    // be non-zero. \n    matrix<double> confusion_matrix;\n    confusion_matrix = cross_validate_sequence_labeler(trainer, samples, labels, 4);\n    cout << \"\\ncross-validation: \" << endl;\n    cout << confusion_matrix;\n    cout << \"label accuracy: \"<< sum(diag(confusion_matrix))/sum(confusion_matrix) << endl;\n\n    // In this case, the label accuracy is about 88%.  At this point, we want to know if\n    // the machine learning method was able to recover the HMM model from the data.  So\n    // to test this, we can load the true HMM model into another sequence_labeler and \n    // test it out on the data and compare the results.  \n\n    matrix<double,0,1> true_hmm_model_weights = log(join_cols(reshape_to_column_vector(transition_probabilities),\n                                                              reshape_to_column_vector(emission_probabilities)));\n    // With this model, labeler_true will predict the most probable set of labels\n    // given an input sequence.  That is, it will predict using the equation:\n    //    y == argmax_y dot(true_hmm_model_weights, PSI(x,y))\n    sequence_labeler<feature_extractor> labeler_true(true_hmm_model_weights); \n\n    confusion_matrix = test_sequence_labeler(labeler_true, samples, labels);\n    cout << \"\\nTrue HMM model: \" << endl;\n    cout << confusion_matrix;\n    cout << \"label accuracy: \"<< sum(diag(confusion_matrix))/sum(confusion_matrix) << endl;\n\n    // Happily, we observe that the true model also obtains a label accuracy of 88%.\n\n\n\n\n\n\n    // Finally, the labeler can be serialized to disk just like most dlib objects.\n    serialize(\"labeler.dat\") << labeler;\n\n    // recall from disk\n    deserialize(\"labeler.dat\") >> labeler;\n}\n\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n//              Code for creating a bunch of random samples from our HMM.\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n\nvoid sample_hmm (\n    dlib::rand& rnd,\n    const matrix<double>& transition_probabilities,\n    const matrix<double>& emission_probabilities,\n    unsigned long previous_label,\n    unsigned long& next_label,\n    unsigned long& next_sample\n)\n/*!\n    requires\n        - previous_label < transition_probabilities.nr()\n        - transition_probabilities.nr() == transition_probabilities.nc()\n        - transition_probabilities.nr() == emission_probabilities.nr()\n        - The rows of transition_probabilities and emission_probabilities must sum to 1.\n          (i.e. sum_cols(transition_probabilities) and sum_cols(emission_probabilities)\n          must evaluate to vectors of all 1s.)\n    ensures\n        - This function randomly samples the HMM defined by transition_probabilities\n          and emission_probabilities assuming that the previous hidden state\n          was previous_label. \n        - The HMM is defined by:\n            - P(next_label |previous_label) == transition_probabilities(previous_label, next_label)\n            - P(next_sample|next_label)     == emission_probabilities  (next_label,     next_sample)\n        - #next_label == the sampled value of the hidden state\n        - #next_sample == the sampled value of the observed state\n!*/\n{\n    // sample next_label\n    double p = rnd.get_random_double();\n    for (long c = 0; p >= 0 && c < transition_probabilities.nc(); ++c)\n    {\n        next_label = c;\n        p -= transition_probabilities(previous_label, c);\n    }\n\n    // now sample next_sample\n    p = rnd.get_random_double();\n    for (long c = 0; p >= 0 && c < emission_probabilities.nc(); ++c)\n    {\n        next_sample = c;\n        p -= emission_probabilities(next_label, c);\n    }\n}\n\n// ----------------------------------------------------------------------------------------\n\nvoid make_dataset (\n    const matrix<double>& transition_probabilities,\n    const matrix<double>& emission_probabilities,\n    std::vector<std::vector<unsigned long> >& samples,\n    std::vector<std::vector<unsigned long> >& labels,\n    unsigned long dataset_size\n)\n{\n    samples.clear();\n    labels.clear();\n\n    dlib::rand rnd;\n\n    // now randomly sample some labeled sequences from our Hidden Markov Model\n    for (unsigned long iter = 0; iter < dataset_size; ++iter)\n    {\n        const unsigned long sequence_size = rnd.get_random_32bit_number()%20+3;\n        std::vector<unsigned long> sample(sequence_size);\n        std::vector<unsigned long> label(sequence_size);\n\n        unsigned long previous_label = rnd.get_random_32bit_number()%num_label_states;\n        for (unsigned long i = 0; i < sample.size(); ++i)\n        {\n            unsigned long next_label = 0, next_sample = 0;\n            sample_hmm(rnd, transition_probabilities, emission_probabilities, \n                       previous_label, next_label, next_sample);\n\n            label[i] = next_label;\n            sample[i] = next_sample;\n\n            previous_label = next_label;\n        }\n\n        samples.push_back(sample);\n        labels.push_back(label);\n    }\n}\n\n// ----------------------------------------------------------------------------------------\n\n", "meta": {"hexsha": "b12d93b0355175d536983897f198c64863d2cb4a", "size": 16978, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/sequence_labeler_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/sequence_labeler_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/sequence_labeler_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": 42.5513784461, "max_line_length": 113, "alphanum_fraction": 0.6288726587, "num_tokens": 3597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5049477329739956}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \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#include <boost/config.hpp>\n\n#include <algorithm>\n#include <vector>\n#include <utility>\n#include <iostream>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/reverse_graph.hpp>\n#include <boost/graph/graph_utility.hpp>\n\nint\nmain()\n{\n  using namespace boost;\n  typedef adjacency_list < vecS, vecS, bidirectionalS > Graph;\n\n  Graph G(5);\n  add_edge(0, 2, G);\n  add_edge(1, 1, G);\n  add_edge(1, 3, G);\n  add_edge(1, 4, G);\n  add_edge(2, 1, G);\n  add_edge(2, 3, G);\n  add_edge(2, 4, G);\n  add_edge(3, 1, G);\n  add_edge(3, 4, G);\n  add_edge(4, 0, G);\n  add_edge(4, 1, G);\n\n  std::cout << \"original graph:\" << std::endl;\n  print_graph(G, get(vertex_index, G));\n\n\n  std::cout << std::endl << \"reversed graph:\" << std::endl;\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300  // avoid VC++ bug...\n  reverse_graph<Graph> R(G);\n  print_graph(R, get(vertex_index, G));\n#else\n  print_graph(make_reverse_graph(G), get(vertex_index, G));\n#endif\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "9ccf1875c410026405d8c25c79dc22539fc6ea96", "size": 1340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/graph/example/reverse-graph-eg.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/graph/example/reverse-graph-eg.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/graph/example/reverse-graph-eg.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 25.7692307692, "max_line_length": 73, "alphanum_fraction": 0.597761194, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5049477303845884}}
{"text": "#include <stan/math/rev/mat.hpp>\n#include <gtest/gtest.h>\n#include <boost/numeric/odeint.hpp>\n#include <test/unit/math/rev/mat/functor/util_cvodes_adams.hpp>\n#include <test/unit/math/prim/arr/functor/harmonic_oscillator.hpp>\n#include <test/unit/math/prim/arr/functor/lorenz.hpp>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <string>\n\ntemplate <typename F, typename T_y0, typename T_theta>\nvoid sho_value_test(F harm_osc, std::vector<double>& y0, double t0,\n                    std::vector<double>& ts, std::vector<double>& theta,\n                    std::vector<double>& x, std::vector<int>& x_int) {\n  using stan::math::promote_scalar;\n  using stan::math::var;\n\n  std::vector<std::vector<var> > ode_res_vd = stan::math::integrate_ode_adams(\n      harm_osc, promote_scalar<T_y0>(y0), t0, ts,\n      promote_scalar<T_theta>(theta), x, x_int);\n\n  EXPECT_NEAR(0.995029, ode_res_vd[0][0].val(), 1e-5);\n  EXPECT_NEAR(-0.0990884, ode_res_vd[0][1].val(), 1e-5);\n\n  EXPECT_NEAR(-0.421907, ode_res_vd[99][0].val(), 1e-5);\n  EXPECT_NEAR(0.246407, ode_res_vd[99][1].val(), 1e-5);\n}\n\nvoid sho_finite_diff_test(double t0) {\n  using stan::math::var;\n  harm_osc_ode_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n\n  test_ode_cvode(harm_osc, t0, ts, y0, theta, x, x_int, 1e-8, 1e-4);\n\n  sho_value_test<harm_osc_ode_fun, double, var>(harm_osc, y0, t0, ts, theta, x,\n                                                x_int);\n  sho_value_test<harm_osc_ode_fun, var, double>(harm_osc, y0, t0, ts, theta, x,\n                                                x_int);\n  sho_value_test<harm_osc_ode_fun, var, var>(harm_osc, y0, t0, ts, theta, x,\n                                             x_int);\n}\n\nvoid sho_data_finite_diff_test(double t0) {\n  using stan::math::var;\n  harm_osc_ode_data_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x(3, 1);\n  std::vector<int> x_int(2, 0);\n\n  test_ode_cvode(harm_osc, t0, ts, y0, theta, x, x_int, 1e-8, 1e-4);\n\n  sho_value_test<harm_osc_ode_data_fun, double, var>(harm_osc, y0, t0, ts,\n                                                     theta, x, x_int);\n  sho_value_test<harm_osc_ode_data_fun, var, double>(harm_osc, y0, t0, ts,\n                                                     theta, x, x_int);\n  sho_value_test<harm_osc_ode_data_fun, var, var>(harm_osc, y0, t0, ts, theta,\n                                                  x, x_int);\n}\n\ntemplate <typename T_y0, typename T_theta, typename F>\nvoid sho_error_test(F harm_osc, std::vector<double>& y0, double t0,\n                    std::vector<double>& ts, std::vector<double>& theta,\n                    std::vector<double>& x, std::vector<int>& x_int,\n                    std::string error_msg) {\n  using stan::math::promote_scalar;\n  using stan::math::var;\n\n  EXPECT_THROW_MSG(stan::math::integrate_ode_adams(\n                       harm_osc, promote_scalar<T_y0>(y0), t0, ts,\n                       promote_scalar<T_theta>(theta), x, x_int),\n                   std::invalid_argument, error_msg);\n}\n\n// TODO(carpenter): g++6 failure\nTEST(StanAgradRevOde_integrate_ode, harmonic_oscillator_finite_diff) {\n  sho_finite_diff_test(0);\n  sho_finite_diff_test(2.0);\n  sho_finite_diff_test(-2.0);\n\n  sho_data_finite_diff_test(0);\n  sho_data_finite_diff_test(2.5);\n  sho_data_finite_diff_test(-2.5);\n}\n\nTEST(StanAgradRevOde_integrate_ode, harmonic_oscillator_error) {\n  using stan::math::var;\n  harm_osc_ode_wrong_size_1_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n  double t0 = 0;\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x(3, 1);\n  std::vector<int> x_int(2, 0);\n\n  // aligned error handling with non-stiff case\n  std::string error_msg\n      = \"cvodes_ode_data: dz_dt (3) and states (2) must match in size\";\n\n  sho_error_test<double, var>(harm_osc, y0, t0, ts, theta, x, x_int, error_msg);\n  sho_error_test<var, double>(harm_osc, y0, t0, ts, theta, x, x_int, error_msg);\n  sho_error_test<var, var>(harm_osc, y0, t0, ts, theta, x, x_int, error_msg);\n}\n\n// TODO(Yi Zhang): failure\n// TEST(StanAgradRevOde_integrate_ode, lorenz_finite_diff) {\n//   lorenz_ode_fun lorenz;\n\n//   std::vector<double> y0;\n//   std::vector<double> theta;\n//   double t0;\n//   std::vector<double> ts;\n\n//   t0 = 0;\n\n//   theta.push_back(10.0);\n//   theta.push_back(28.0);\n//   theta.push_back(8.0 / 3.0);\n//   y0.push_back(10.0);\n//   y0.push_back(1.0);\n//   y0.push_back(1.0);\n\n//   std::vector<double> x;\n//   std::vector<int> x_int;\n\n//   for (int i = 0; i < 100; i++)\n//     ts.push_back(0.1 * (i + 1));\n\n//   test_ode_cvode(lorenz, t0, ts, y0, theta, x, x_int, 1e-8, 1e-1);\n// }\n", "meta": {"hexsha": "73a8c832df0f6550d4017d7b7ed69a2cc5d2e93d", "size": 5166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/rev/mat/functor/integrate_ode_adams_rev_test.cpp", "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/unit/math/rev/mat/functor/integrate_ode_adams_rev_test.cpp", "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/unit/math/rev/mat/functor/integrate_ode_adams_rev_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3090909091, "max_line_length": 80, "alphanum_fraction": 0.6209833527, "num_tokens": 1729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5049477279911022}}
{"text": "#include \"hog_detector/interpolation.h\"\n\n#include <gtest/gtest.h>\n#include <ros/ros.h>\n#include <vector>\n#include <boost/scoped_ptr.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nclass LinearInterpTest : public ::testing::Test {\n protected:\n  vector<double> x_;\n  vector<double> y_;\n\n  virtual void SetUp() {\n    x_.clear();\n    y_.clear();\n  }\n};\n\nTEST_F(LinearInterpTest, EmptyInterpolator) {\n  ASSERT_EQ(x_.size(), 0);\n  ASSERT_EQ(y_.size(), 0);\n  EXPECT_DEATH(LinearInterpolator(x_, y_),\n               \".* insufficient number of points for interpolation type\");\n}\n\nTEST_F(LinearInterpTest, SortedInterpolation) {\n  double x[] = {0, 3, 4, 8, 9, 15, 17};\n  double y[] = {1, 6, 9, 23, 15, 14, 18};\n  x_.insert(x_.end(), x, x+7);\n  y_.insert(y_.end(), y, y+7);\n  LinearInterpolator interpolator(x_, y_);\n\n  EXPECT_FLOAT_EQ(interpolator(2.0), 1 + 2.0*5/3);\n  EXPECT_FLOAT_EQ(interpolator(3.5), 7.5);\n  EXPECT_FLOAT_EQ(interpolator(10), 15 - 1.0/6);\n  EXPECT_FLOAT_EQ(interpolator(14), 15 - 5.0/6);\n  EXPECT_FLOAT_EQ(interpolator(16), 16.0);\n}\n\nTEST_F(LinearInterpTest, UnsortedInterpolation) {\n  double x[] = {15, 9, 17, 0, 3, 4, 8};\n  double y[] = {14, 15, 18, 1, 6, 9, 23};\n  x_.insert(x_.end(), x, x+7);\n  y_.insert(y_.end(), y, y+7);\n  LinearInterpolator interpolator(x_, y_);\n\n  EXPECT_FLOAT_EQ(interpolator(2.0), 1 + 2.0*5/3);\n  EXPECT_FLOAT_EQ(interpolator(3.5), 7.5);\n  EXPECT_FLOAT_EQ(interpolator(10), 15 - 1.0/6);\n  EXPECT_FLOAT_EQ(interpolator(14), 15 - 5.0/6);\n  EXPECT_FLOAT_EQ(interpolator(16), 16.0);\n}\n\nTEST_F(LinearInterpTest, IdenticalEntryInterpolation) {\n  double x[] = {0, 3, 3, 4, 8, 9, 15, 17};\n  double y[] = {1, 6, 6, 9, 23, 15, 14, 18};\n  x_.insert(x_.end(), x, x+8);\n  y_.insert(y_.end(), y, y+8);\n  LinearInterpolator interpolator(x_, y_);\n\n  EXPECT_FLOAT_EQ(interpolator(2.0), 1 + 2.0*5/3);\n  EXPECT_FLOAT_EQ(interpolator(3.5), 7.5);\n  EXPECT_FLOAT_EQ(interpolator(10), 15 - 1.0/6);\n  EXPECT_FLOAT_EQ(interpolator(14), 15 - 5.0/6);\n  EXPECT_FLOAT_EQ(interpolator(16), 16.0);\n}\n\nTEST_F(LinearInterpTest, OutOfBounds) {\n  double x[] = {0, 3, 4, 8, 9, 15, 17};\n  double y[] = {1, 6, 9, 23, 15, 14, 18};\n  x_.insert(x_.end(), x, x+7);\n  y_.insert(y_.end(), y, y+7);\n  LinearInterpolator interpolator(x_, y_);\n\n  EXPECT_THROW(interpolator(-3.0), Interpolator::out_of_bounds);\n  EXPECT_THROW(interpolator(22.0), Interpolator::out_of_bounds);\n}\n\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  ros::Time::init();\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "8200ceebc04ebacc8623e5ccd37c9dc7f51611e8", "size": 2499, "ext": "cc", "lang": "C++", "max_stars_repo_path": "hog_detector/test/interpolation_test.cc", "max_stars_repo_name": "MRSD2018/reefbot-1", "max_stars_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hog_detector/test/interpolation_test.cc", "max_issues_repo_name": "MRSD2018/reefbot-1", "max_issues_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hog_detector/test/interpolation_test.cc", "max_forks_repo_name": "MRSD2018/reefbot-1", "max_forks_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "max_forks_repo_licenses": ["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.3977272727, "max_line_length": 74, "alphanum_fraction": 0.6570628251, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5049477279911021}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\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#include <boost/config.hpp>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <utility>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/graph/incremental_components.hpp>\n\n/*\n\n  This example shows how to use the disjoint set data structure\n  to compute the connected components of an undirected, changing\n  graph.\n\n  Sample output:\n\n  An undirected graph:\n  0 <--> 1 4 \n  1 <--> 0 4 \n  2 <--> 5 \n  3 <--> \n  4 <--> 1 0 \n  5 <--> 2 \n\n  representative[0] = 1\n  representative[1] = 1\n  representative[2] = 5\n  representative[3] = 3\n  representative[4] = 1\n  representative[5] = 5\n\n  component 0 contains: 4 1 0 \n  component 1 contains: 3 \n  component 2 contains: 5 2 \n\n */\n\nusing namespace std;\n\nint main(int , char* []) \n{\n  using namespace boost;\n  typedef adjacency_list <vecS, vecS, undirectedS> Graph;\n  typedef graph_traits<Graph>::vertex_descriptor Vertex;\n  typedef graph_traits<Graph>::vertices_size_type size_type;\n\n  const int N = 6;\n  Graph G(N);\n\n  std::vector<size_type> rank(num_vertices(G));\n  std::vector<Vertex> parent(num_vertices(G));\n  typedef size_type* Rank;\n  typedef Vertex* Parent;\n  disjoint_sets<Rank, Parent>  ds(&rank[0], &parent[0]);\n\n  initialize_incremental_components(G, ds);\n  incremental_components(G, ds);\n\n  graph_traits<Graph>::edge_descriptor e;\n  bool flag;\n  boost::tie(e,flag) = add_edge(0, 1, G);\n  ds.union_set(0,1);\n\n  boost::tie(e,flag) = add_edge(1, 4, G);\n  ds.union_set(1,4);\n\n  boost::tie(e,flag) = add_edge(4, 0, G);\n  ds.union_set(4,0);\n\n  boost::tie(e,flag) = add_edge(2, 5, G);\n  ds.union_set(2,5);\n    \n  cout << \"An undirected graph:\" << endl;\n  print_graph(G, get(vertex_index, G));\n  cout << endl;\n    \n  graph_traits<Graph>::vertex_iterator i,end;\n  for (boost::tie(i, end) = vertices(G); i != end; ++i)\n    cout << \"representative[\" << *i << \"] = \" << \n      ds.find_set(*i) << endl;;\n  cout << endl;\n\n  typedef component_index<unsigned int> Components;\n  Components components(&parent[0], &parent[0] + parent.size());\n\n  for (Components::size_type c = 0; c < components.size(); ++c) {\n    cout << \"component \" << c << \" contains: \";\n    Components::value_type::iterator\n      j = components[c].begin(),\n      jend = components[c].end();\n    for ( ; j != jend; ++j)\n      cout << *j << \" \";\n    cout << endl;\n  }\n\n  return 0;\n}\n\n", "meta": {"hexsha": "9e235d2cd92fc94308553cf7f6453199eefd761f", "size": 2826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/incremental_components.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": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T13:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T02:55:10.000Z", "max_issues_repo_path": "libs/graph/example/incremental_components.cpp", "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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/graph/example/incremental_components.cpp", "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": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T14:34:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T08:25:58.000Z", "avg_line_length": 25.9266055046, "max_line_length": 73, "alphanum_fraction": 0.6199575372, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5049355621988892}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/atan.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n\nSTF_CASE_TPL (\" atanreal\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::atan;\n\n  using r_t = decltype(atan(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(atan(bs::Inf<T>()), bs::Pio_2<r_t>(), 0);\n  STF_ULP_EQUAL(atan(bs::Minf<T>()), -bs::Pio_2<r_t>(), 0);\n  STF_ULP_EQUAL(atan(bs::Nan<T>()), bs::Nan<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(atan(bs::Half<T>()), T(4.636476090008061e-01), 0.5);\n  STF_ULP_EQUAL(atan(bs::Mhalf<T>()), T(-4.636476090008061e-01), 0.5);\n  STF_ULP_EQUAL(atan(bs::Mone<T>()), -bs::Pio_4<r_t>(), 0.5);\n  STF_ULP_EQUAL(atan(bs::One<T>()), bs::Pio_4<r_t>(), 0.5);\n  STF_ULP_EQUAL(atan(bs::Zero<T>()), bs::Zero<r_t>(), 0.5);\n}\n", "meta": {"hexsha": "bb5ce8c1130a3af893f97aeb7a14e203ce5db28a", "size": 1521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/atan.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/scalar/atan.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/atan.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "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": 35.3720930233, "max_line_length": 100, "alphanum_fraction": 0.5969756739, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5049355489166261}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <catch2/catch.hpp>\n\ninline void make_first_positive(Eigen::VectorXi& v)\n{\n    for(uint32_t n = 0; n < v.size(); ++n)\n    {\n        if(v(n) == 0)\n        {\n            continue;\n        }\n        if(v(n) < 0)\n        {\n            v *= -1;\n            return;\n        }\n        else\n        {\n            return;\n        }\n    }\n}\n\nstruct hash_vector\n{\n    size_t operator()(const Eigen::VectorXi& v) const\n    {\n        std::size_t seed = v.size();\n        for(uint32_t n = 0; n < v.size(); ++n)\n        {\n            seed ^= abs(v(n)) + 0x9e3779b9 + (seed << 6U) + (seed >> 2U);\n        }\n        return seed;\n    }\n};\n\ninline int powi(int base, unsigned int exp)\n{\n    int res = 1;\n    while(exp != 0U)\n    {\n        if((exp & 1U) != 0U)\n        {\n            res *= base;\n        }\n        exp >>= 1U;\n        base *= base;\n    }\n    return res;\n}\n\ntemplate<typename UINT, template<typename> class Basis>\nEigen::MatrixXd basisMatrix(const Basis<UINT>& basis)\n{\n    Eigen::MatrixXd res = Eigen::MatrixXd::Zero(1U << basis.getN(), basis.getDim());\n    for(unsigned int n = 0; n < basis.getDim(); ++n)\n    {\n        auto bvec = basis.basisVec(n);\n        for(const auto p : bvec)\n        {\n            res(p.first, n) = p.second;\n        }\n    }\n    return res;\n}\n\ntemplate<typename Basis> Eigen::VectorXd flip(Basis&& basis, const Eigen::VectorXd& r)\n{\n    Eigen::VectorXd res(r.size());\n    for(int i = 0; i < r.size(); i++)\n    {\n        res(basis.flip(i)) = r(i);\n    }\n    return res;\n}\n\ninline void TestBasisMatrix(const Eigen::MatrixXd& r)\n{\n    using Catch::WithinAbs;\n    Eigen::MatrixXd id = Eigen::MatrixXd::Identity(r.cols(), r.cols());\n    REQUIRE_THAT((r.transpose() * r - id).cwiseAbs().maxCoeff(), WithinAbs(0.0, 1e-8));\n}\n\nEigen::SparseMatrix<double> getSX();\nEigen::SparseMatrix<std::complex<double>> getSY();\nEigen::SparseMatrix<double> getSZ();\nEigen::SparseMatrix<double> getSXXYY();\nEigen::SparseMatrix<double> getSXX();\nEigen::SparseMatrix<double> getSYY();\nEigen::SparseMatrix<double> getSZZ();\n", "meta": {"hexsha": "21d9698258fb8a884cf21ca3c178af76b90e2cd1", "size": 2089, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/utils.hpp", "max_stars_repo_name": "cecri/ExactDiagonalization", "max_stars_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_stars_repo_licenses": ["MIT"], "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/utils.hpp", "max_issues_repo_name": "cecri/ExactDiagonalization", "max_issues_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_issues_repo_licenses": ["MIT"], "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/utils.hpp", "max_forks_repo_name": "cecri/ExactDiagonalization", "max_forks_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_forks_repo_licenses": ["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.2234042553, "max_line_length": 87, "alphanum_fraction": 0.5404499761, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5049355317871407}}
{"text": "////////////////////////////////////////////////////////////////////////////////////////////////\n////                     Population Dynamics single cell simulations                       /////\n////                          (For predtermined SNAIL levels)\t\t\t\t               /////\n////                Codes adopted from Tripathi et. al. 2020 PLOS Comp Bio                 /////\n////                Modification done by Jain et al., Date: 19th Jan 2022                  /////\n//////////////////////////////////////////////////////////////////////////////////////////////// \n\n#include <iostream>\n#include <cmath>\n#include <ctime>\n#include <random>\n#include <string>\n#include <fstream>\n#include <boost/array.hpp>\n#include <boost/unordered_map.hpp>\n#include <boost/numeric/odeint.hpp>\n\n#define NUMNODES 4\n\ntypedef boost::array<double, NUMNODES> cell_state;\ntypedef boost::unordered_map<int, boost::array<double, NUMNODES>> population;\n\nstd::mt19937 generator; // for random number generation\n\ndouble temp_var[13];  // temp_var hold the value for initialization parameters provided at start \n\n//////////////////////// k combination out of n //////////////////////////////\ndouble nchoosek(int n, int k) \n{\n\tdouble result = 1.0;\n\tdouble result0 = 1.0;\n\n\tfor(int i = 0; i < k; i++)\n\t{\n\t\tresult *= (n - i);\n\t}\n\tfor(int i = 1; i <= k; i++)\n\t{\n\t\tresult0 *= i;\n\t}\n\n\treturn(result / result0);\n}\n///////////////////////////////////////////////////////////////////////////////////\n\n// function to break a string and separate numeral character based on the delimiter\nvoid tokenize(std::string s, std::string del = \" \")\n{\n\tint start = 0;\n\tint end = s.find(del);\n\tint i = 0;\n\twhile (end != -1) {\n\t\t//std::cout << s.substr(start, end - start) << std::endl;\n\t\ttemp_var[i] = std::stod(s.substr(start, end - start));\n\t\t//std::cout << temp_var[i] << std::endl;\n\t\tstart = end + del.size();\n\t\tend = s.find(del, start);\n\t\ti++;\n\t}\n\t//std::cout << s.substr(start, end - start);\n\ttemp_var[i] = std::stod(s.substr(start, end - start));\n\t//std::cout << temp_var[i];\n}\n///////////////////////////////////////////////////////////////////////////////////\n\n/////////////////// EMT core circuit ODEs (updates a cells' state) ////////////////\nvoid EMT_system(const cell_state &x, cell_state &dxdt, double t)\n{\n\tdouble ku200 = 0.05, kmz = 0.5, kz = 0.1;\n\t \n\t// Transcription rate:\n\tdouble gu200 = 2100, gmz = 11, gz = 100;\n\n\t// Hills function threshold :\n\tdouble z0u200 = 220000, z0mz = 25000, s0u200 = 180000, s0mz = 180000, u2000 = 10000;\n\n\t// Cooperativity:\n\tdouble nzu200 = 3, nsu200 = 2, nzmz = 2, nsmz = 2, nu200 = 6;\n\n\t// fold change\n\tdouble lamdazu200 = 0.1, lamdasu200 = 0.1, lamdazmz = 7.5, lamdasmz = 10;\n\n\n\n\tdouble Mu0=1/std::pow((1+x[0]/u2000),nu200);\n\tdouble Mu1=std::pow((x[0]/u2000),1)/std::pow((1+x[0]/u2000),nu200);\n\tdouble Mu2=std::pow((x[0]/u2000),2)/std::pow((1+x[0]/u2000),nu200);\n\tdouble Mu3=std::pow((x[0]/u2000),3)/std::pow((1+x[0]/u2000),nu200);\n\tdouble Mu4=std::pow((x[0]/u2000),4)/std::pow((1+x[0]/u2000),nu200);\n\tdouble Mu5=std::pow((x[0]/u2000),5)/std::pow((1+x[0]/u2000),nu200);\n\tdouble Mu6=std::pow((x[0]/u2000),6)/std::pow((1+x[0]/u2000),nu200);\n\n\n\t\t\n\tdouble Hillszu200=(1+lamdazu200*std::pow((x[2]/z0u200),nzu200))/(1+std::pow((x[2]/z0u200),nzu200));\n\tdouble Hillssu200=(1+lamdasu200*std::pow((x[3]/s0u200),nsu200))/(1+std::pow((x[3]/s0u200),nsu200));\n\tdouble Hillszmz=(1+lamdazmz*std::pow((x[2]/z0mz),nzmz))/(1+std::pow((x[2]/z0mz),nzmz));\n\tdouble Hillssmz=(1+lamdasmz*std::pow((x[3]/s0mz),nsmz))/(1+std::pow((x[3]/s0mz),nsmz));\n\t \n\n\tdxdt[0] = gu200*Hillszu200*Hillssu200-x[1]*(0.005*6*Mu1+2*0.05*15*Mu2+3*0.5*20*Mu3+4*0.5*15*Mu4+5*0.5*6*Mu5+6*0.5*Mu6)-ku200*x[0];\n\tdxdt[1] = gmz*Hillszmz*Hillssmz-x[1]*(0.04*6*Mu1+0.2*15*Mu2+20*Mu3+15*Mu4+6*Mu5+Mu6)-kmz*x[1];\n\tdxdt[2] = gz*x[1]*(Mu0+0.6*6*Mu1+0.3*15*Mu2+0.1*20*Mu3+0.05*15*Mu4+0.05*6*Mu5+0.05*Mu6)-kz*x[2];\n\tdxdt[3] = 0;\n}\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////// to assign phenotypes to cells /////////////////////////\nvoid get_phenotypes(population &P, boost::unordered_map <int, int> &phenotype)\n{\n\tdouble x1 = 193.2, x2 = 208.7, y1 = 243.09, y2 = 90.93;\n\tdouble a1 = y2 - y1, b1 = x1 - x2, c1 = x2*y1 - y2*x1;\n\n\tdouble u1 = 185.12, u2 = 224.67, v1 = 698.395, v2 = 495.802;\n\tdouble a2 = v2 - v1, b2 = u1 - u2, c2 = u2*v1 - v2*u1;\n\n\tdouble x, y, fac1, fac2;\n\tint state = -1;\n\n\tfor(int i = 0; i < P.size(); i++)\n\t{\n\t\tx = P[i][3] / 1e3;\n\t\ty = P[i][1];\n\t\tstate = -1;\n\n\t\tif(x < u1)\n\t\t{\n\t\t\tstate = 0;\n\t\t}\n\t\telse if(x > u2)\n\t\t{\n\t\t\tstate = 2;\n\t\t}\n\n\t\telse\n\t\t{\n\t\t\tfac1 = (a1*x + b1*y + c1) / b1;\n\t\t\tfac2 = (a2*x + b2*y + c2) / b2;\n\t\t\tif(fac2 >= 0)\n\t\t\t{\n\t\t\t\tstate = 2;\n\t\t\t}\n\t\t\telse if(fac1 < 0)\n\t\t\t{\n\t\t\t\tstate = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t\tstate = 1;\n\t\t\t\n\t\t}\n\n\t\tif(state == -1)\n\t\t{\n\t\t\tstd::cout << \"Error in phenotype assignment.\" << \"\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tphenotype[i] = state;\n\t\t}\n\t}\n}\n\n////////////////////////////////////////////////////////////////////////////////////////\n\n//// To initialize cellular states of the initial population\nvoid initialize_Signal_lognormal(population& P, double* pop_fraction, const int pop_size, const double SNAIL)\n{\n\n\t//std::normal_distribution <> dist{ 0.0, 1.0 };\n\n\t\n\n\t//std::vector<int> V[3];\n\n\tint flag = 0;\n\t//const unsigned int N = 100000;\n\tdouble I = SNAIL;\n\t\n\t/*double CV2 = 1.0;\n\tdouble SD = std::sqrt(std::log(CV2 * CV2 + 1.0));\n\tdouble M = 200e3;\n\t*/\n\n\n\tboost::unordered_map <int, int> phenotype;\n\tboost::array<int, 4> count = { 0,0,0,0 };\n\n\tpopulation temp_P, temp_P_vector;\n\tstd::ifstream steady_states, eigen_values;\n\n\tsteady_states.open(\"steady_states.csv\");\n\teigen_values.open(\"eigen_values.csv\");\n\tstd::string line;\n\n// load steady states matrix (save steady_states.csv in working directory)////\n\n\tint num_states = 0;\n\n\twhile(getline(steady_states,line)){\n\t\t\n\t\t//std::cout<<line;\n\t\ttokenize(line,\",\");\n\n\t\tfor(int i = 0; i < NUMNODES; i++){\n\t\t\ttemp_P[num_states][i] = temp_var[i]; \n\t\t}\n\t\t\tnum_states++;\n\t}\n\n\n// to load eigen values matrix (save steady_states.csv in working directory) ////\n\n\tnum_states = 0;\n\n\twhile(getline(eigen_values,line)){\n\t\t\n\t\t//std::cout<<line;\n\t\ttokenize(line,\",\");\n\n\t\tfor(int i = 0; i < NUMNODES; i++){\n\t\t\ttemp_P_vector[num_states][i] = temp_var[i]; \n\t\t}\n\t\t\tnum_states++;\n\t}\n\t///////////////////////////////////////////////////////////////\n\n\tsteady_states.close();\n\teigen_values.close();\n\n\t//////// to initialize cells based on random generated SNAIL levels and population fraction.///\n\t///// The logic is to search for nearest SNAIL value, compared to sampled I, in steady states and eigen values matrices \n\t/// and initialize cells with miR200, mZEB, and ZEB variable vector at that SNAIL value  \n\n\tint first_time = 1, min_indx = 0, selected_P_indx = 0 ;\n\tdouble abs_diff = 0, diff = 0;\n\n\twhile (count[3] < (pop_size))\n\t{\n\n\t\tif(I <= temp_P[temp_P.size()-1][3]){\n\t\t\tfirst_time = 1;\n\t\t\tmin_indx = 0;\n\t\t\tselected_P_indx = 0 ;\n\t\t\tabs_diff = 0;\n\t\t\tdiff = 0;\n\n\t\t\tpopulation selected_P;\n\n\t\t\tfor(int g = 0; g < temp_P.size(); g++){\n\t\t\t\t\n\t\t\t\tif(temp_P[g][3] - I >= 0){\n\t\t\t\t\tabs_diff = temp_P[g][3] - I;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tabs_diff = -(temp_P[g][3] - I);\t\n\t\t\t\t}\n\n\t\t\t\tif(abs_diff<= 100 && temp_P_vector[g][0] < 0 && temp_P_vector[g][1] < 0 && temp_P_vector[g][2] < 0){\n\n\t\t\t\t\tif(first_time==1){\n\t\t\t\t\t\tdiff = abs_diff;\n\t\t\t\t\t\tmin_indx = g;\n\t\t\t\t\t\tfirst_time = 2;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tif(abs_diff < diff)\n\t\t\t\t\t\t\tmin_indx = g;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\telse if(first_time == 2)\n\t\t\t\t{\n\n\t\t\t\tfor(int i = 0; i < NUMNODES; i++){\n\t\t\t\t\tselected_P[selected_P_indx][i] = temp_P[g][i];\n\t\t\t\t\t\n\t\t\t\t\t/*std::cout<< selected_P[selected_P_indx][i] << \" \";\n\n\t\t\t\t\tif(i ==  NUMNODES-1)\n\t\t\t\t\t\tstd::cout<<\"\\n\";*/\t\t\t\t\n\n\t\t\t\t}\n\n\t\t\t\tselected_P_indx++;\n\t\t\t\tfirst_time = 1;\n\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\tget_phenotypes(selected_P,phenotype);\n\t\t\t/*std::cout << selected_P.size() << \"\\n\";\n\n\t\t\tfor(int i = 0; i < phenotype.size(); i++){\n\t\t\t\tstd::cout<<phenotype[i] << \"\\n\";\n\t\t\t}*/ \n\n\t\t\tfor(int i = 0; i < selected_P.size();i++){\n\n\t\t\t\tif (phenotype[i] == 0 && count[0] < pop_size * pop_fraction[0]) {\t\n\t\t\t\t\tfor(int j = 0; j < NUMNODES; j++){\n\t\t\t\t\t\tP[count[3]][j] = selected_P[i][j];\n\t\t\t\t\t\t\n\t\t\t\t\t\t/*std::cout<< selected_P[i][j] << \" \";\n\n\t\t\t\t\t\tif(j ==  NUMNODES-1)\n\t\t\t\t\t\t\tstd::cout<<\"\\n\";*/\n\t\t\t\t\t}\n\t\t\t\t\tcount[0]++;\n\t\t\t\t\t\n\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse if (phenotype[i] == 1 && count[1] < pop_size * pop_fraction[1]){\n\t\t\t\t\tfor(int j = 0; j < NUMNODES; j++){\n\t\t\t\t\t\tP[count[3]][j] = selected_P[i][j];\n\n\t\t\t\t\t\t/*std::cout<< selected_P[i][j] << \" \";\n\n\t\t\t\t\t\tif(j ==  NUMNODES-1)\n\t\t\t\t\t\t\tstd::cout<<\"\\n\";*/\n\n\t\t\t\t\t}\n\t\t\t\t\tcount[1]++;\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse if (phenotype[i] == 2 && count[2] < pop_size * pop_fraction[2]){\n\t\t\t\t\tfor(int j = 0; j < NUMNODES; j++){\n\t\t\t\t\t\tP[count[3]][j] = selected_P[i][j];\n\t\t\t\t\t\t/*std::cout<< selected_P[i][j] << \" \";\n\n\t\t\t\t\t\tif(j ==  NUMNODES-1)\n\t\t\t\t\t\t\tstd::cout<<\"\\n\";*/\n\t\t\t\t\t}\n\t\t\t\t\tcount[2]++;\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\tcount[3] = count[0] + count[1] + count[2];\n\n\t\t\t}\n\t\t\t\n\n\t\t\tselected_P.clear();\n\t\t\tphenotype.clear();\n\t\t}\n\t}\n\t/////////////////////////////////////////////////////////////////////////////////////////////////////\n\t\n}\n\n\n///// uniform sampling a cell from a subpopulation////////////////\nint get_sample(boost::unordered_map <int, int> &phenotype, int pid)\n{\n\tstd::vector<int> V;\n\tint count = 0;\n\tfor(int i = 0; i < phenotype.size(); i++)\n\t{\n\t\tif(phenotype[i] == pid)\n\t\t{\n\t\t\tV.push_back(i);\n\t\t\tcount += 1;\n\t\t}\n\t}\n\n\tstd::uniform_int_distribution<int> distribution(0, count - 1);\n\n\treturn(V[distribution(generator)]);\n}\n//////////////////////////////////////////////////////////////////////\n\n\n////////////////// adding duplication and partitioning noise/fluctuation on cell division ////////// \nvoid add_sym_noise_normal(population &P, int rep_id, int new_id, double * eta, int eta_id)\n{\n\tstd::normal_distribution <> distribution{0, 1};\n\n\tstd::uniform_real_distribution <> distribution_unifrom{0.2, 0.4};\n\t\n\tdouble temp_snail[2];\n\n\tdouble rand_num[2];\n\n\trand_num[0] =  distribution(generator);\n\trand_num[1] =  distribution(generator);\n\n\t//do{\n\tif(eta_id == 0){\n\t        temp_snail[0] = P[rep_id][3] + distribution(generator)*distribution_unifrom(generator)*P[rep_id][3];\n\t        temp_snail[1] = P[rep_id][3] + distribution(generator)*distribution_unifrom(generator)*P[rep_id][3];\n        }\n        else{\n        \ttemp_snail[0] = P[rep_id][3] + rand_num[0]*eta[0]*P[rep_id][3]/2 + rand_num[1]*eta[1]*(2*P[rep_id][3] + rand_num[0]*eta[0]*P[rep_id][3]) ;\n\t        temp_snail[1] = P[rep_id][3] + rand_num[0]*eta[0]*P[rep_id][3]/2 - rand_num[1]*eta[1]*(2*P[rep_id][3] + rand_num[0]*eta[0]*P[rep_id][3]) ;\n        }\n\n        //std::cout << temp_snail[0] << \" \" << temp_snail[1];\n\n\t//}while(temp_snail[0] <= 0.0 || temp_snail[1] <=0.0);\n\n\tP[rep_id][3] = temp_snail[0];\n\tP[new_id][3] = temp_snail[1];\n\n        if(P[rep_id][3] < 0.0)\n        {\n                P[rep_id][3] = 0.0;\n        }\n        if(P[new_id][3] < 0.0)\n        {\n                P[new_id][3] = 0.0;\n        }\n        \n}\n\n/////////////////////////////////////////////////////////////////////////////////\n\n\n////////// sampling a fraction of cells from a subpopulation when overall population size increase 80% of carrying capacity K\nint FACS(population &P, int N, int type_start, std::vector <int> &cell_index)\n{\n\tboost::unordered_map <int, int> phenotype;\n\tget_phenotypes(P, phenotype);\n\tstd::vector<int> usefulIndex;\n\tint count = 0, flag = 1;\n\n\tfor(int i = 0; i < phenotype.size(); i++)\n\t{\n\t\tif(phenotype[i] == type_start)\n\t\t{\n\t\t\tusefulIndex.push_back(i);\n\t\t\tcount += 1;\n\t\t}\n\t}\n\tif(count < N)\n\t{\n\t\tstd::cout << \"Not enough cells of type\" << std::to_string(type_start) << \" present in the culture.\" << \"\\n\";\n\t\tflag = 0;\n\t\treturn(flag);\n\t}\n\n\tstd::uniform_int_distribution<int> distribution(0, usefulIndex.size() - 1);\n\n\tint size = 0;\n\tint index = 0;\n\twhile(size < N)\n\t{\n\t\t//index = usefulIndex[distribution(generator)];\n\t\t\n\t\tindex = usefulIndex[size];\n\t\tcell_index.push_back(index);\n\n\t\t/*sorted_P[size+cell_count] = {0.0, 0.0, 0.0, 0.0};\n\t\tfor(int i = 0; i < NUMNODES; i++)\n\t\t{\n\t\t\tsorted_P[size+cell_count][i] = P[index][i];\n\t\t}*/\n\t\tsize += 1;\n\t}\n\n\treturn(flag);\n}\n///////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n////////////////////////// population dynamics ////////////////////////////////////////////////////////////\nint simulate_normal(population& P, double end_time, double * eta, int eta_id,int frac_id, int sim_type, boost::array <double, 3> GR, int GR_ratio_id, int pop_size, int sim_num, int SNAIL_id)\n{\n\tboost::unordered_map <int, double> update_time;\n\tboost::unordered_map <int, int> phenotype;\n\tboost::array<double, 3> count;\n\t//boost::array<int, 3> cell_count;\n\tstd::vector <int> cell_index;\n\n\tdouble temp_count[3];\n\tdouble day_indx = 1;\n\n\tfor(int i = 0; i < P.size(); i++)\n\t{\n\t\tupdate_time[i] = 0.0;\n\t}\n\n\tint last_index = P.size();\n\n\tget_phenotypes(P, phenotype);\n\n\t//std::cout << GR[0] << \" \" << GR[1] << \" \" << GR[2] << \"\\n\"; \n\n\tboost::array <double, 3> growth;\n\tgrowth[0] = std::log(2) / GR[0];\n\tgrowth[1] = std::log(2) / GR[1];\n\tgrowth[2] = std::log(2) / GR[2];\n\tboost::array<double, 3> r0 = {growth[0], growth[1], growth[2]};\n\tboost::array<double, 3> d0 = {growth[0] / 10.0, growth[1] / 10.0, growth[2] / 10.0};\n\tboost::array<double, 6> rates = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\n\n\n\tint K = 5000;\n\n\tif(sim_type == 1)\n\t{\n\t\tK = 2000;\n\t}\n\n\tfor(int i = 0; i < P.size(); i++)\n\t{\n\t\tif(phenotype[i] == 0)\n\t\t{\n\t\t\tif(P.size() < K)\n\t\t\t{\n\t\t\t\trates[0] += r0[0]*(1 - float(P.size()) / K);\n\t\t\t}\n\t\t\trates[3] += d0[0];\n\t\t}\n\t\telse if(phenotype[i] == 1)\n\t\t{\n\t\t\tif(P.size() < K)\n\t\t\t{\n\t\t\t\trates[1] += r0[1]*(1 - float(P.size()) / K);\n\t\t\t}\n\t\t\trates[4] += d0[1];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(P.size() < K)\n\t\t\t{\n\t\t\t\trates[2] += r0[2]*(1 - float(P.size()) / K);\n\t\t\t}\n\t\t\trates[5] += d0[2];\n\t\t}\n\t}\n\n\tstd::uniform_real_distribution<double> distribution(0.0, 1.0);\n\n\tdouble t = 0.0, a0, dt, p0, p1;\n\tdouble sum_prev, sum_new;\n\tdouble last_updated = 0.0;\n\tint event_id, rep_id, death_id;\n\n\n\tstd::ofstream end_of_day, SNAIL_distribution, mZEB_distribution;\n\n\tif(sim_type == 1){\n\n\t\tcount = {0.0, 0.0, 0.0};\n\t\tfor(int i = 0; i < P.size(); i++)\n\t\t{\n\t\t\tcount[phenotype[i]] += 1.0;\n\t\t}\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tcount[i] = count[i] / P.size();\n\t\t}\n\n\t\t\n\t\t// Below, 'E_frac_spread_Data_20hrs_DT_4_weeks' is the folder name in which output data files will be stored.\n\t\t// Create it in current working directory before running the simulation. \n\t\tend_of_day.open(\"E_frac_spread_Data_20hrs_DT_4_weeks/end_of_day_counts_\" + std::to_string(eta_id) + \"_\" + std::to_string(frac_id) + \"_\" + std::to_string(GR_ratio_id) + \"_\" + std::to_string(SNAIL_id) + \".csv\", std::ios::app);\n\t\t\n\t\t//SNAIL_distribution.open(\"E_frac_spread_SNAIL_dist_20hrs_DT_4_weeks/snail_dist_\" + std::to_string(eta_id) + \"_\" + std::to_string(frac_id) + \"_\" + std::to_string(GR_ratio_id) + \"_\" + std::to_string(SNAIL_id) + \"_\" + std::to_string(sim_num) + \".csv\");\n\n\t\t//mZEB_distribution.open(\"E_frac_spread_ZEB_dist_20hrs_DT_4_weeks/mZEB_dist_\" + std::to_string(eta_id) + \"_\" + std::to_string(frac_id) + \"_\" + std::to_string(GR_ratio_id) + \"_\" + std::to_string(SNAIL_id) + \"_\" + std::to_string(sim_num) + \".csv\");\n\t\t\n\t\t/*for(int i = 0; i < P.size(); i++){\n\t\t\tif(i < P.size() -1){\n\t\t\t\tSNAIL_distribution << P[i][3] << \",\";\n\t\t\t\tmZEB_distribution << P[i][1] << \",\";\n\t\t\t}\n\t\t\telse{\n\t\t\t\tSNAIL_distribution << P[i][3] << \"\\n\";\n\t\t\t\tmZEB_distribution << P[i][1] << \"\\n\";\n\t\t\t}\t\n\t\t}*/\n\t\t//phenotype_switch.open(\"phenotype_switch/end_of_day_counts_\" + std::to_string(eta_id) + \"_\" + std::to_string(frac_id) + \"_\" + std::to_string(GR_ratio_id) + \"_\" + std::to_string(sim_num) + \".csv\", std::ios::app);\n\t}\n\t\n\n\twhile(t <= end_time)\n\t{\n\t\ta0 = 0.0;\n\n\t\tfor(int i = 0; i < 6; i++)\n\t\t{\n\t\t\ta0 += rates[i];\n\t\t}\n\n\t\tp0 = distribution(generator);\n\t\tdt = (1.0 / a0)*std::log(1 / p0);\n\t\tt += dt;\n\n\t\tp1 = distribution(generator);\n\t\tsum_prev = 0.0;\n\t\tsum_new = 0.0;\n\t\tevent_id = -1;\n\n\t\tfor(int i = 0; i < 6; i++)\n\t\t{\n\t\t\tsum_new = sum_prev + rates[i] / a0;\n\t\t\tif(p1 >= sum_prev && p1 < sum_new)\n\t\t\t{\n\t\t\t\tevent_id = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsum_prev = sum_new;\n\t\t}\n\n\t\tif(event_id == 0)\n\t\t{\n\t\t\trep_id = get_sample(phenotype, 0);\n\t\t}\n\t\telse if(event_id == 1)\n\t\t{\n\t\t\trep_id = get_sample(phenotype, 1);\n\t\t}\n\t\telse if(event_id == 2)\n\t\t{\n\t\t\trep_id = get_sample(phenotype, 2);\n\t\t}\n\t\telse if(event_id == 3)\n\t\t{\n\t\t\tdeath_id = get_sample(phenotype, 0);\n\t\t}\n\t\telse if(event_id == 4)\n\t\t{\n\t\t\tdeath_id = get_sample(phenotype, 1);\n\t\t}\n\t\telse if(event_id == 5)\n\t\t{\n\t\t\tdeath_id = get_sample(phenotype, 2);\n\t\t}\n\n\t\tif(event_id < 3)\n\t\t{\t\n\t\t\t\n\t\t\tboost::numeric::odeint::integrate(EMT_system, P[rep_id], 0.0, t - update_time[rep_id], 0.1);\n\t\t\t\n\t\t\tP[last_index] = {0.0, 0.0, 0.0, 0.0};  // last index holds the length of Population Array vector \n\t\t\tfor(int j = 0; j < NUMNODES; j++)\n\t\t\t{\n\t\t\t\tP[last_index][j] = P[rep_id][j];\n\t\t\t}\n\n\t\t\tadd_sym_noise_normal(P, rep_id, last_index, eta, eta_id);\n\n\t\t\tupdate_time[rep_id] = t;\n\t\t\tupdate_time[last_index] = t;\n\t\t\tlast_index += 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor(int j = 0; j < NUMNODES; j++)\n\t\t\t{\n\t\t\t\tP[death_id][j] = P[last_index - 1][j];\n\t\t\t}\n\t\t\tupdate_time[death_id] = update_time[last_index - 1];\n\t\t\tphenotype[death_id] = phenotype[last_index - 1];\n\t\t\tP.erase(last_index - 1);\n\t\t\tupdate_time.erase(last_index - 1);\n\t\t\tphenotype.erase(last_index - 1);\n\t\t\tlast_index -= 1;\n\t\t}\n\n\t\tif(P.size()==0)\n\t\t{\n\t\t\tif(sim_type == 1)\n\t\t\t{\n\t\t\t\tend_of_day.close();\n\t\t\t\t//SNAIL_distribution.close();\n\t\t\t\t//mZEB_distribution.close();\n\t\t\t}\n\t\t\n\t\t\treturn(1);\n\t\t}\n\n\t\tif(true)\n\t\t{\n\t\t\tfor(int i = 0; i < P.size(); i++)\n\t\t\t{\n\t\t\t\tif(t - update_time[i] > 0.0)\n\t\t\t\t{\n\t\t\t\t\tboost::numeric::odeint::integrate(EMT_system, P[i], 0.0, t - update_time[i], 0.1);\n\t\t\t\t}\n\t\t\t\tupdate_time[i] = t;\n\t\t\t}\n\t\t}\n\n\t\tget_phenotypes(P, phenotype);\n\n\n\t\t/// reducing population size by sampling different subpopulations as per their last distribution\n\n\t\tif(P.size() > 0.8 * K && sim_type == 1){\n\n\t\t\tcount = {0.0, 0.0, 0.0};\n\n\t\t\tfor(int i = 0; i < P.size(); i++)\n\t\t\t{\n\t\t\t\tcount[phenotype[i]] += 1.0;\n\t\t\t}\n\n\t\t\tfor(int i = 0; i < 3; i++)\n\t\t\t{\n\t\t\t\tcount[i] = count[i] / P.size();\n\n\t\t\t\tdouble b = 0; // to truncate the double to two decimal places\n\n\t\t\t\tfor (double k = 0; k<=100; k++)\n\t\t\t\t{\n\t\t\t\t\tif(k > 100*count[i])\n\t\t\t\t\t{\n\t\t\t\t\t\tb = 100*count[i] - (k-1);\n\t\t\t\t\t\tcount[i] = count[i] - b/100; \n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//std::cout << count[i] << \"\\n\";\n\n\t\t\t\tint flag = FACS(P,pop_size*count[i],i,cell_index);\n\t\t\t\tif (flag == 0){\n\t\t\t\t\tstd::cout <<\" stopped simulation due to non-availability of cells\\n\";\n\t\t\t\t\treturn(-1);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tstd::sort(cell_index.begin(),cell_index.end());\n\n\t\t\t//for (int i = 0; i< cell_index.size(); i++) std::cout << cell_index[i] << \"\\n\"; \n\t\t\t//std::cout<< cell_index.size()<<\"\\n\";\n\n\t\t\tfor (int i = 0; i < cell_index.size(); i++){\n\t\t\t\t\tif(i != cell_index[i]){\n\t\t\t\t\t\tfor(int j = 0; j < NUMNODES; j++){\n\t\t\t\t\t\t\tP[i][j] = P[cell_index[i]][j];\n\t\t\t\t\t\t\t//std::cout << P[i][j] << \" \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tphenotype[i] = phenotype[cell_index[i]];\n\t\t\t\t\t}\n\t\t\t\t\tupdate_time[i] = t; \n\n\t\t\t\t\t//std::cout<<\"\\n\";\n\t\t\t}\n\t\t\tfor (int i = P.size()-1; i >= cell_index.size(); i--)\n\t\t\t{\n\t\t\t\tP.erase(i);\n\t\t\t\tupdate_time.erase(i);\n\t\t\t\tphenotype.erase(i);\n\t\t\t}\n\t\t\tlast_index = P.size();\n\n\t\t\t/*std::cout << \"\\nsize of the sampled pop is \" << last_index <<\"\\n\";\n\t\t\t\n\t\t\tfor (int i = 0; i < P.size(); i++)\n\t\t\t{\n\t\t\t\tstd::cout << P[i][1] << \" \" << P[i][3] << \"\\n\";\n\t\t\t}*/\n\t\t\t\n\n\t\t\tcell_index.clear();\n\n\t\t}\n\t\t///////////////////////////////////////////////////////////////////////////////////////\n\n\t\t\n\t\tcount = {0.0, 0.0, 0.0};\n\n\t\tfor(int i = 0; i < P.size(); i++)\n\t\t{\n\t\t\tcount[phenotype[i]] += 1.0;\n\t\t}\n\n\t\t/*for(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tcount[i] = count[i] / P.size();\n\t\t}*/\n\n\t\t\n\t\trates = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\n\n\t\tfor(int i = 0; i < P.size(); i++)\n\t\t{\n\t\t\tif(phenotype[i] == 0)\n\t\t\t{\n\t\t\t\tif(P.size() < K)\n\t\t\t\t{\n\t\t\t\t\trates[0] += r0[0]*(1 - float(P.size()) / K);\n\t\t\t\t}\n\t\t\t\trates[3] += d0[0];\n\t\t\t}\n\t\t\telse if(phenotype[i] == 1)\n\t\t\t{\n\t\t\t\tif(P.size() < K)\n\t\t\t\t{\n\t\t\t\t\trates[1] += r0[1]*(1 - float(P.size()) / K);\n\t\t\t\t}\n\t\t\t\trates[4] += d0[1];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(P.size() < K)\n\t\t\t\t{\n\t\t\t\t\trates[2] += r0[2]*(1 - float(P.size()) / K);\n\t\t\t\t}\n\t\t\t\trates[5] += d0[2];\n\t\t\t}\n\t\t}\n\n\t\tif(sim_type == 1)\n\t\t{\n\t\t\t\n\n\t\t\tif (t < 24* day_indx) {\n\t\t\t\ttemp_count[0] = count[0];\n\t\t\t\ttemp_count[1] = count[1];\n\t\t\t\ttemp_count[2] = count[2];\n\t\t\t\t\n\t\t\t}\n\t\t\telse {\n\n\t\t\t\t//std::cout << day_indx << \",\" << temp_count[0] << \",\" << temp_count[1] << \",\" << temp_count[2] << \",\" << P.size() << \"\\n\";\n\t\t\t\n\t\t\t\t//// the phenotypic distribution is stored each day in absolute cell counts ////\n\n\t\t\t\tend_of_day << day_indx << \",\" << temp_count[0] << \",\" << temp_count[1] << \",\" << temp_count[2] << \",\" << (P.size()-1) << \"\\n\";\n\n\t\t\t\t/*if((int(day_indx)%14) == 0){ // save distribution data every four weeks\n\t\t\t\t\tfor(int i = 0; i < P.size(); i++){\n\t\t\t\t\t\tif(i < P.size() -1){\n\t\t\t\t\t\t\tSNAIL_distribution << P[i][3] << \",\";\n\t\t\t\t\t\t\tmZEB_distribution << P[i][1] << \",\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tSNAIL_distribution << P[i][3] << \"\\n\";\n\t\t\t\t\t\t\tmZEB_distribution << P[i][1] << \"\\n\";\n\t\t\t\t\t\t}\t\n\t\t\t\t\t}\n\t\t\t\t}*/\n\t\t\t\t\n\n\t\t\t\tday_indx++;\n\n\t\t\t\ttemp_count[0] = count[0];\n\t\t\t\ttemp_count[1] = count[1];\n\t\t\t\ttemp_count[2] = count[2];\n\n\t\t\t}\n\t\t}\n\t}\n\n\tif(sim_type == 1)\n\t{\n\t\tend_of_day.close();\n\t//\tSNAIL_distribution.close();\n\t//\tmZEB_distribution.close();\n\t}\n\n\treturn(0);\n}\n\n\n\n\n\nint main(int argc, char* argv[])\n{\n\n\ttokenize(argv[1], \"_\"); /// to separate parameters from input string \n\n\tboost::unordered_map <int, int> phenotype;\n\tboost::array <double, 3> GR; // doubling time of the three population\n\tstd::vector <int> cell_index; // used with FACS\n\tint aborted;\n\t\n\tint count[3];\n\n\t// order the input parameter values delimited by '_' as follows:\n// e.g. 1_0.2_0.1_0_1_0_0_0_20_20_20_0_50000\n\tint eta_id = temp_var[0];\n\tdouble eta[2] = { temp_var[1], temp_var[2] };\n\tint frac_id = temp_var[3];\n\tdouble pop_fraction[3] = { temp_var[4], temp_var[5], temp_var[6] };\n\tint GR_ratio_id = temp_var[7];\n\tGR[0] = temp_var[8];\n\tGR[1] = temp_var[9];\n\tGR[2] = temp_var[10];\n\tint SNAIL_id = temp_var[11];\n\tdouble SNAIL = temp_var[12];\n\n\tint sim_num = 1;\n\tint pop_size = 200;\n\tint total_inde_runs = 50;\n\tint time_in_days = 4 * 7 ; // 4 respresent 4 weeks\n\tint file_rows = 0;\n\n\tstd::ifstream csv_file;\n\n\tstd::string line;\n\n\twhile(true){\n\t\t\n\t\t//// check how many runs of data is stored in output file\n\t\tcsv_file.open(\"E_frac_spread_Data_20hrs_DT_32_weeks/end_of_day_counts_\" + std::to_string(eta_id) + \"_\" + std::to_string(frac_id) + \"_\" + \n\t\t\tstd::to_string(GR_ratio_id) + \"_\"  + std::to_string(SNAIL_id) + \".csv\");\n\n\t\t/*if(csv_file.is_open())\n\t\t{\n\t\t\tstd::cout<<\"file is correctly opened\\n\";\n\t\t}*/\n\t\t\n\t\tfile_rows = 0;\t\t\n\t\twhile(getline(csv_file,line)){\n\t\t\tfile_rows++;\n\t\t}\n\n\t\tcsv_file.close();\n\t\t//std::cout << file_rows << \"\\n\";\n\t\t\n\t\t/////////// don't proceed if file has data of required number of runs or incomplete previous simulation data  \n\t\tif(file_rows >= (total_inde_runs * time_in_days) || (file_rows%time_in_days) != 0){\n\t\t\t\n\t\t\tif(file_rows%time_in_days != 0)\n\t\t\t\tstd::cout << \"stopped bacause of already missing data \\n\";\n\t\t\telse if(file_rows > (total_inde_runs * time_in_days))\n\t\t\t\tstd::cout << total_inde_runs * time_in_days << \" enough data already present\\n\";\n\t\t\tbreak;\n\t\t} \n\t\t//////////////////////////////////////////////////////////////////////////////////////\n\t\t\n\t\tgenerator = std::mt19937(std::time(NULL) + file_rows);\n\n\t\tpopulation P;\n\n\t\tinitialize_Signal_lognormal(P, pop_fraction, 1, SNAIL); // initial pop size as 1 for single cell simualtion\n\t\t\n\t\t/*for(int i = 0; i < P.size(); i++){\n\n\t\t\tfor(int j = 0; j < NUMNODES; j++){\n\t\t\t\tstd::cout << P[i][j] << \" \";\n\t\t\t}\n\t\t\tstd::cout<<\"\\n\";\n\t\t}*/\n\n\t\t\n\t\tstd::cout << \"initialization complete for eta id \" << eta_id << \" frac_id \" << frac_id << \" GR ratio id \" << GR_ratio_id << \" SNAIL_id \" << SNAIL_id <<\" and sim num is \" << sim_num << std::endl;\n\n\t\taborted = simulate_normal(P, 24 * time_in_days, eta, eta_id, frac_id, 1, GR, GR_ratio_id, pop_size, sim_num, SNAIL_id);\n\n\t\tif(aborted == 1)\n\t\t{\n\t\t\tstd::cout<<\"the simulation is aborted due to extinction of population\\n\";\n\t\t}else{\n\n\t\t\tstd::cout << \"simulation complete for eta id \" << eta_id << \" frac_id \" << frac_id << \" GR ratio id \" << GR_ratio_id << \" SNAIL_id \" << SNAIL_id <<\" and sim num is \" << sim_num << std::endl;\n\t\t\tsim_num++;\n\t\t}\n\n\t\tP.clear(); \n\t}\n\t\n\n\n\treturn(0);\n\t\n}", "meta": {"hexsha": "81565a1df231d090f59140f60eb93c09acdd26f2", "size": 24296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PD_E_frac_spread_for_specific_SNAIL.cpp", "max_stars_repo_name": "Paras-Jain20/EMT-Population-Dynamics", "max_stars_repo_head_hexsha": "0bc682bbcda2a075b908960ee8e660f8beda4467", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PD_E_frac_spread_for_specific_SNAIL.cpp", "max_issues_repo_name": "Paras-Jain20/EMT-Population-Dynamics", "max_issues_repo_head_hexsha": "0bc682bbcda2a075b908960ee8e660f8beda4467", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PD_E_frac_spread_for_specific_SNAIL.cpp", "max_forks_repo_name": "Paras-Jain20/EMT-Population-Dynamics", "max_forks_repo_head_hexsha": "0bc682bbcda2a075b908960ee8e660f8beda4467", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-21T08:02:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T08:02:12.000Z", "avg_line_length": 25.1511387164, "max_line_length": 252, "alphanum_fraction": 0.5361376358, "num_tokens": 8226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.504923979375103}}
{"text": "#define _USE_MATH_DEFINES\n#include <cmath>\n#include \"Window.h\"\n#include \"godec/ComponentGraph.h\"\n#include <boost/format.hpp>\n#include <iomanip>\n\nnamespace Godec {\n\nWindowComponent::~WindowComponent() {\n}\n\nLoopProcessor* WindowComponent::make(std::string id, ComponentGraphConfig* configPt) {\n    return new WindowComponent(id, configPt);\n}\nstd::string WindowComponent::describeThyself() {\n    return \"Chops incoming audio stream into windowed audio features\";\n}\nWindowComponent::WindowComponent(std::string id, ComponentGraphConfig* configPt) :\n    LoopProcessor(id,configPt) {\n    addInputSlotAndUUID(SlotStreamedAudio, UUID_AudioDecoderMessage);\n\n    std::list<std::string> requiredOutputSlots;\n    requiredOutputSlots.push_back(SlotWindowedAudio);\n    initOutputs(requiredOutputSlots);\n\n    /* initialize sampling parameters for the current waveform */\n    mLowLatency = configPt->get<bool>(\"low_latency\", \"Low-latency mode (assumes never-ending audio, can not be used in offline where utterances end!)\");\n    mSamplingRate = configPt->get<float>(\"sampling_frequency\", \"Source sampling rate\");\n    float local_fRate = configPt->get<float>(\"analysis_frame_step_size\", \"Analysis frame step size\");\n    float local_winDur = configPt->get<float>(\"analysis_frame_size\", \"Analysis frame size in milliseconds\");\n    std::string windowingFunction = configPt->get<std::string>(\"windowing_function\", \"Windowing function (hamming,blackman, rectangle)\");\n    windowSize = (int)round(0.001 * mSamplingRate * local_winDur);    /* points in window */\n    stepSize = (int)round(0.001 * mSamplingRate * local_fRate);     /* points per shift */\n    window = Vector(windowSize);\n    if (windowingFunction == \"hamming\") {\n        for(int idx = 0; idx < windowSize; idx++) {\n            window(idx) = 0.54-0.46*cos(2.0*M_PI/(windowSize-1));\n        }\n    } else if (windowingFunction == \"rectangle\") {\n        window.setConstant(1.0);\n    } else {\n        GODEC_ERR << \"Not implemented yet!\";\n    }\n    zeroMean = AccumCovariance::make(1, Diagonal, true, false);\n\n    mUttReceivedAudio = 0;\n    mUttStartStreamOffset = 0;\n    mAccumAudioOffsetInUtt = 0;\n    mProcessPointerInAccumAudio = 0;\n}\n\nvoid WindowComponent::ProcessMessage(const DecoderMessageBlock& msgBlock) {\n    auto convStateMsg =msgBlock.get<ConversationStateDecoderMessage>(SlotConversationState);\n    auto audioMsg =msgBlock.get<AudioDecoderMessage>(SlotStreamedAudio);\n    if (mSamplingRate != audioMsg->mSampleRate) {\n        GODEC_ERR << getLPId() << \": Expected sampling rate \" << mSamplingRate << \", got \" << audioMsg->mSampleRate << std::endl;\n    }\n\n    float ticksPerSample = audioMsg->mTicksPerSample;\n    const Vector& audio = audioMsg->mAudio;\n    mAccumAudio.conservativeResize(mAccumAudio.size()+audio.size());\n    mAccumAudio.tail(audio.size()) = audio;\n    mUttReceivedAudio += audio.size();\n\n    int audioHoldoff = (mLowLatency || convStateMsg->mLastChunkInUtt) ? 0 : stepSize; // Problem is, we need to keep at least one window of audio around so that the last message can be tagged with the EOM boolean\n    int nFrames = std::max(0.0, floor(((int)mAccumAudio.size() - mProcessPointerInAccumAudio - audioHoldoff) / (double)stepSize));\n    if (nFrames == 0) {\n        if (!convStateMsg->mLastChunkInUtt) return;\n        else if (mLowLatency) GODEC_ERR << \"You ran in low-latency mode but ended the utterance, this is not allowed\";\n        else GODEC_ERR << \"We should never end up here\";\n    }\n\n    Matrix outMat(windowSize, nFrames);\n    std::vector<uint64_t> outTimestamps;\n    int frameIdx = -1;\n\n    Vector rawAudioSnippet(windowSize);\n    while ((mProcessPointerInAccumAudio + stepSize) <= ((int)mAccumAudio.size() - audioHoldoff)) {\n        frameIdx++;\n        mProcessPointerInAccumAudio += stepSize;\n\n        rawAudioSnippet.setZero();\n        int64_t pickupStart = std::max((int64_t)0,mProcessPointerInAccumAudio-windowSize);\n        int64_t pickupSize = mProcessPointerInAccumAudio-pickupStart;\n        rawAudioSnippet.tail(mProcessPointerInAccumAudio-pickupStart) = mAccumAudio.segment(pickupStart, pickupSize);\n\n        zeroMean->reset();\n        zeroMean->addData(rawAudioSnippet);\n        Vector normAudio = zeroMean->normalize(rawAudioSnippet);\n        Vector filteredAudio = window.cwiseProduct(normAudio);\n\n        outMat.col(frameIdx) = filteredAudio;\n        uint64_t frameTimestamp = mUttStartStreamOffset + (int64_t)round(ticksPerSample*(mProcessPointerInAccumAudio+mAccumAudioOffsetInUtt));\n        outTimestamps.push_back(frameTimestamp);\n    }\n\n    if (outTimestamps.size() != nFrames) {\n        GODEC_ERR << \"Number of frames was not estimated correctly. \" << outTimestamps.size() << \" vs \" << nFrames << std::endl;\n    }\n\n    if (convStateMsg->mLastChunkInUtt && outTimestamps.size() > 0) {\n        outTimestamps.back() = convStateMsg->getTime();\n    }\n\n    boost::format fmter(\"WINAUDIO[0:%1%]%%f\");\n    fmter % (windowSize - 1);\n\n    DecoderMessage_ptr featMsg = FeaturesDecoderMessage::create(\n                                     outTimestamps.back(), convStateMsg->mUtteranceId,\n                                     outMat, fmter.str(), outTimestamps);\n    if (audioMsg->getDescriptor(\"vtl_stretch\") != \"\") {\n        (boost::const_pointer_cast<DecoderMessage>(featMsg))->addDescriptor(\"vtl_stretch\", audioMsg->getDescriptor(\"vtl_stretch\"));\n    }\n    pushToOutputs(SlotWindowedAudio, featMsg);\n\n    if (mProcessPointerInAccumAudio > 10*stepSize) {\n        int64_t framesToRemove = mAccumAudio.size()-2*windowSize;\n        mAccumAudio = (Vector)mAccumAudio.tail(mAccumAudio.size()-framesToRemove);\n        mProcessPointerInAccumAudio -= framesToRemove;\n        mAccumAudioOffsetInUtt += framesToRemove;\n    }\n\n    if (convStateMsg->mLastChunkInUtt) {\n        mUttStartStreamOffset = featMsg->getTime()+1;\n        mProcessPointerInAccumAudio = -1;\n        mUttReceivedAudio = 0;\n        mAccumAudioOffsetInUtt = 0;\n        mAccumAudio = Vector();\n    }\n}\n\n}\n", "meta": {"hexsha": "581a4173a6a766b4b41b23806e6d5c7d9e603ed6", "size": 5951, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/core_components/Window.cc", "max_stars_repo_name": "threebrooks/Godec", "max_stars_repo_head_hexsha": "4b70a673f0fa7755a1590fb53eccf16cd1fb9d53", "max_stars_repo_licenses": ["MIT"], "max_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_components/Window.cc", "max_issues_repo_name": "threebrooks/Godec", "max_issues_repo_head_hexsha": "4b70a673f0fa7755a1590fb53eccf16cd1fb9d53", "max_issues_repo_licenses": ["MIT"], "max_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_components/Window.cc", "max_forks_repo_name": "threebrooks/Godec", "max_forks_repo_head_hexsha": "4b70a673f0fa7755a1590fb53eccf16cd1fb9d53", "max_forks_repo_licenses": ["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.4104477612, "max_line_length": 212, "alphanum_fraction": 0.6960174761, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5049239749195024}}
{"text": "/***************************************************************************\n   Copyright 2015 Ufora Inc.\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 GraphUtil_hppml_\n#define GraphUtil_hppml_\n\n/*******\nGraphUtil\n\nutilities for doing computations on graphs whose nodes and edges\nare defined using sets and maps.\n\n********/\n\n#include <set>\n#include <map>\n\n#include <boost/config.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/strong_components.hpp>\n#include <boost/property_map/property_map.hpp>\n\n#include \"../cppml/CPPMLPrettyPrinter.hppml\"\n#include \"../containers/TwoWaySetMap.hpp\"\n\nnamespace  GraphUtil {\n\n/********\n\nComputes the set of edges reachable from a particular node in a directed graph.\n\nIt is not necessary for every node to be a key in inEdges. If it's not there,\nbut it's referred to by another edge, the algorithm assumes it has no outgoing\nedges.\n\n*********/\ntemplate<class T>\nvoid\tcomputeReachableNodes(\n\t\t\t\t\tconst std::map<T, std::set<T> >& inEdges,\n\t\t\t\t\tstd::set<T>& outReachable,\n\t\t\t\t\tconst T& inNode\n\t\t\t\t\t)\n\t{\n\tif (outReachable.find(inNode) == outReachable.end())\n\t\t{\n\t\toutReachable.insert(inNode);\n\n\t\tauto map_it = inEdges.find(inNode);\n\n\t\tif (map_it != inEdges.end())\n\t\t\tfor (auto edge: map_it->second)\n\t\t\t\tcomputeReachableNodes(inEdges, outReachable, edge);\n\t\t}\n\t}\n\ntemplate<class T>\nvoid\tcomputeReachableNodes(\n\t\t\t\t\tconst TwoWaySetMap<T, T>& inEdges,\n\t\t\t\t\tstd::set<T>& outReachable,\n\t\t\t\t\tconst T& inNode\n\t\t\t\t\t)\n\t{\n\tcomputeReachableNodes(inEdges.getKeysToValues(), outReachable, inNode);\n\t}\n\n/*****\n\nFind, in the directed graph \"inEdges\", every group of nodes such that\neach node is reachable from each of the others by a path.  Essentially,\ntwo nodes are in a group together iff there is a cycle that contains them.\n\nnodes that aren't in the edge map don't ever show up in the graph\n\nif includeSingleNodeComponents is set to true, then we include everything.\nIf it's set to false, we filter out nodes that are not themselves part of\nany cycle.\n\nIf onlyIncludeFreeComponents is set to true, then we don't include any\nsubgroups that have external nodes jumping into them.\n\n*****/\ntemplate<class T>\nvoid\tcomputeStronglyConnectedComponents(\n\t\t\t\tconst std::map<T, std::set<T> >& inEdges,\n\t\t\t\tstd::vector<std::set<T> >& outComponents,\n\t\t\t\tbool includeSingleNodeComponents,\n\t\t\t\tbool onlyIncludeFreeComponents\n\t\t\t\t)\n\t{\n\tif (!inEdges.size())\n\t\treturn;\n\tusing namespace boost;\n\tusing namespace std;\n\n\tmap<T, uint32_t> \t\t\t\tnodeToIndex;\n\tmap<uint32_t, T> \t\t\t\tindexToNode;\n\n\tuint32_t ix = 0;\n\tfor (typename map<T, set<T> >::const_iterator\n\t\t\tit = inEdges.begin(); it!= inEdges.end(); ++it)\n\t\t{\n\t\tnodeToIndex[it->first] = ix;\n\t\tindexToNode[ix] = it->first;\n\t\tix++;\n\t\t}\n\n\ttypedef adjacency_list<vecS, vecS, bidirectionalS> Graph;\n\n\tGraph g(nodeToIndex.size());\n\n\t//add any edges that stay within the graph\n\tfor (typename map<T, set<T> >::const_iterator\n\t\t\tnode_it = inEdges.begin(); node_it != inEdges.end(); ++node_it)\n\t\tfor (typename set<T>::const_iterator edge_it = node_it->second.begin();\n\t\t\t\t\t\t\t\t\t\t\tedge_it != node_it->second.end();\n\t\t\t\t\t\t\t\t\t\t\t++edge_it)\n\t\t\t{\n\t\t\ttypename map<T, uint32_t>::iterator  index_it =\n\t\t\t\t\tnodeToIndex.find(*edge_it);\n\n\t\t\tif (index_it != nodeToIndex.end())\n\t\t\t\tadd_edge(nodeToIndex[node_it->first], index_it->second, g);\n\t\t\t}\n\n\tmap<int, int>\tcomponents;\n\n\tboost::associative_property_map< std::map<int, int> >\n\t\t  components_prop_map(components);\n\n\tint totalComponents = strong_components(g, components_prop_map);\n\n\toutComponents.resize(totalComponents);\n\tfor (map<int,int>::iterator  it = components.begin();\n\t\t\t\t\t\t\t\t\t\t\tit != components.end(); ++it)\n\t\t{\n\t\tlassert(it->second >= 0 && it->second < totalComponents);\n\t\toutComponents[it->second].insert(indexToNode[it->first]);\n\t\t}\n\n\tif (onlyIncludeFreeComponents)\n\t\t{\n\t\tset<int> badComponents;\n\n\t\t//for each edge, check which components are being crossed and mark\n\t\t//destination components as 'bad' when they're different\n\n\t\tfor (long k = 0; k < outComponents.size();k++)\n\t\t\tfor (typename set<T>::const_iterator it = outComponents[k].begin();\n\t\t\t\t\tit != outComponents[k].end(); ++it)\n\t\t\t\t{\n\t\t\t\tconst T& node = *it;\n\n\t\t\t\tint componentIndex = components[nodeToIndex[node]];\n\n\t\t\t\ttypename map<T, set<T> >::const_iterator edgeIt = inEdges.find(node);\n\n\t\t\t\tfor (typename set<T>::const_iterator\n\t\t\t\t\t\t\toutgoing_it = edgeIt->second.begin();\n\t\t\t\t\t\t\toutgoing_it != edgeIt->second.end();\n\t\t\t\t\t\t\t++outgoing_it\n\t\t\t\t\t\t\t)\n\t\t\t\t\t{\n\t\t\t\t\tint destComponentIndex = components[nodeToIndex[*outgoing_it]];\n\t\t\t\t\tif (componentIndex != destComponentIndex)\n\t\t\t\t\t\tbadComponents.insert(destComponentIndex);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\tfor (long k = 0; k < outComponents.size();k++)\n\t\t\tif (badComponents.find(k) != badComponents.end())\n\t\t\t\t{\n\t\t\t\tstd::swap(outComponents[k], outComponents.back());\n\t\t\t\toutComponents.resize(outComponents.size() - 1);\n\t\t\t\tk--;\n\t\t\t\t}\n\t\t}\n\tif (!includeSingleNodeComponents)\n\t\tfor (long k = 0; k < outComponents.size();k++)\n\t\t\tif (outComponents[k].size() == 1)\n\t\t\t\t{\n\t\t\t\tconst T& node = *outComponents[k].begin();\n\n\t\t\t\ttypename map<T, set<T> >::const_iterator it = inEdges.find(node);\n\n\t\t\t\tbool mapsToSelf = (it != inEdges.end() &&\n\t\t\t\t\t\t\t\tit->second.find(node) != it->second.end());\n\n\t\t\t\tif (!mapsToSelf)\n\t\t\t\t\t{\n\t\t\t\t\tstd::swap(outComponents[k], outComponents.back());\n\t\t\t\t\toutComponents.resize(outComponents.size() - 1);\n\t\t\t\t\tk--;\n\t\t\t\t\t}\n\t\t\t\t}\n\t}\n\n\ntemplate<class T>\nvoid\tcomputeStronglyConnectedComponents(\n\t\t\t\tconst TwoWaySetMap<T, T>& inEdges,\n\t\t\t\tstd::vector<std::set<T> >& outComponents,\n\t\t\t\tbool includeSingleNodeComponents,\n\t\t\t\tbool onlyIncludeFreeComponents\n\t\t\t\t)\n\t{\n\tcomputeStronglyConnectedComponents(\n\t\tinEdges.getKeysToValues(),\n\t\toutComponents,\n\t\tincludeSingleNodeComponents,\n\t\tonlyIncludeFreeComponents\n\t\t);\n\t}\n\n}\n\n\n\n\n\n#endif\n\n", "meta": {"hexsha": "180fb322d2c46a0ca810b93d04e19a3da7584517", "size": 6375, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ufora/core/math/GraphUtil.hpp", "max_stars_repo_name": "ufora/ufora", "max_stars_repo_head_hexsha": "04db96ab049b8499d6d6526445f4f9857f1b6c7e", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_stars_count": 571.0, "max_stars_repo_stars_event_min_datetime": "2015-11-05T20:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T22:31:09.000Z", "max_issues_repo_path": "ufora/core/math/GraphUtil.hpp", "max_issues_repo_name": "timgates42/ufora", "max_issues_repo_head_hexsha": "04db96ab049b8499d6d6526445f4f9857f1b6c7e", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_issues_count": 218.0, "max_issues_repo_issues_event_min_datetime": "2015-11-05T20:37:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-30T03:53:50.000Z", "max_forks_repo_path": "ufora/core/math/GraphUtil.hpp", "max_forks_repo_name": "timgates42/ufora", "max_forks_repo_head_hexsha": "04db96ab049b8499d6d6526445f4f9857f1b6c7e", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-11-07T21:42:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T03:48:19.000Z", "avg_line_length": 27.2435897436, "max_line_length": 79, "alphanum_fraction": 0.6729411765, "num_tokens": 1593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5048341727998044}}
{"text": "//  (C) Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/math/bindings/rr.hpp>\r\n#include <fstream>\r\n\r\n#include <boost/math/tools/test_data.hpp>\r\n#include <boost/math/special_functions/log1p.hpp>\r\n#include <boost/math/special_functions/expm1.hpp>\r\n\r\nusing namespace boost::math::tools;\r\nusing namespace std;\r\n\r\nstruct data_generator\r\n{\r\n   boost::math::tuple<boost::math::ntl::RR, boost::math::ntl::RR> operator()(boost::math::ntl::RR z)\r\n   {\r\n      return boost::math::make_tuple(boost::math::log1p(z), boost::math::expm1(z));\r\n   }\r\n};\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n   boost::math::ntl::RR::SetPrecision(1000);\r\n   boost::math::ntl::RR::SetOutputPrecision(40);\r\n\r\n   parameter_info<boost::math::ntl::RR> arg1;\r\n   test_data<boost::math::ntl::RR> data;\r\n\r\n   std::cout << \"Welcome.\\n\"\r\n      \"This program will generate spot tests for the log1p and expm1 functions:\\n\\n\";\r\n\r\n   bool cont;\r\n   std::string line;\r\n\r\n   do{\r\n      if(0 == get_user_parameter_info(arg1, \"z\"))\r\n         return 1;\r\n      data.insert(data_generator(), arg1);\r\n\r\n      std::cout << \"Any more data [y/n]?\";\r\n      std::getline(std::cin, line);\r\n      boost::algorithm::trim(line);\r\n      cont = (line == \"y\");\r\n   }while(cont);\r\n\r\n   std::cout << \"Enter name of test data file [default=log1p_expm1_data.ipp]\";\r\n   std::getline(std::cin, line);\r\n   boost::algorithm::trim(line);\r\n   if(line == \"\")\r\n      line = \"log1p_expm1_data.ipp\";\r\n   std::ofstream ofs(line.c_str());\r\n   ofs << std::scientific;\r\n   write_code(ofs, data, \"log1p_expm1_data\");\r\n   \r\n   return 0;\r\n}\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "f39d41c8306a138fc3c85f2158130ddc44489c44", "size": 1757, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/log1p_expm1_data.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/tools/log1p_expm1_data.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/tools/log1p_expm1_data.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": 27.453125, "max_line_length": 101, "alphanum_fraction": 0.6311895276, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5048341598566763}}
{"text": "/* ------------------------------------------------------------------------- */\n/* UMFPACK Version 4.1 (Apr. 30, 2003), Copyright (c) 2003 by Timothy A.     */\n/* Davis.  All Rights Reserved.  See ../README for License.                  */\n/* email: davis@cise.ufl.edu    CISE Department, Univ. of Florida.           */\n/* web: http://www.cise.ufl.edu/research/sparse/umfpack                      */\n/* ------------------------------------------------------------------------- */\n\n\n/***********************************************************************/\n/*         UMFPACK Copyright, License and Availability                 */\n/***********************************************************************/\n/*\n *\n * UMFPACK Version 4.1 (Apr. 30, 2003),  Copyright (c) 2003 by Timothy A.\n * Davis.  All Rights Reserved.\n *\n * UMFPACK License:\n *\n *   Your use or distribution of UMFPACK or any modified version of\n *   UMFPACK implies that you agree to this License.\n *\n *   THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY\n *   EXPRESSED OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.\n *\n *   Permission is hereby granted to use or copy this program, provided\n *   that the Copyright, this License, and the Availability of the original\n *   version is retained on all copies.  User documentation of any code that\n *   uses UMFPACK or any modified version of UMFPACK code must cite the\n *   Copyright, this License, the Availability note, and \"Used by permission.\"\n *   Permission to modify the code and to distribute modified code is granted,\n *   provided the Copyright, this License, and the Availability note are\n *   retained, and a notice that the code was modified is included.  This\n *   software was developed with support from the National Science Foundation,\n *   and is provided to you free of charge.\n *\n * Availability:\n *\n *   http://www.cise.ufl.edu/research/sparse/umfpack\n *\n */\n\n/* Used by permission. */ \n\n\n/* Simple demo program for UMFPACK               */ \n/* from UMFPACK Version 4.1 Quick Start Guide    */\n\n/* modified by Kresimir Fresl, 2003              */\n/* UMFPACK bindings & ublas::compressed_matrix<> */\n\n\n#include <iostream>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_sparse.hpp>\n#include <boost/numeric/bindings/umfpack/umfpack.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nnamespace ublas = boost::numeric::ublas;\nnamespace umf = boost::numeric::bindings::umfpack;\n\nint main() {\n\n  ublas::compressed_matrix<double, ublas::column_major, 0, \n    ublas::unbounded_array<int>, ublas::unbounded_array<double> > A (5,5,12); \n  ublas::vector<double> B (5), X (5);\n\n  A(0,0) = 2.; A(0,1) = 3; \n  A(1,0) = 3.; A(1,2) = 4.; A(1,4) = 6;\n  A(2,1) = -1.; A(2,2) = -3.; A(2,3) = 2.;\n  A(3,2) = 1.;\n  A(4,1) = 4.; A(4,2) = 2.; A(4,4) = 1.; \n\n  B(0) = 8.; B(1) = 45.; B(2) = -3.; B(3) = 3.; B(4) = 19.; \n\n  umf::symbolic_type<double> Symbolic;\n  umf::numeric_type<double> Numeric;\n\n  umf::symbolic (A, Symbolic); \n  umf::numeric (A, Symbolic, Numeric); \n  umf::solve (A, X, B, Numeric);   \n\n  std::cout << X << std::endl;  // output: [5](1,2,3,4,5)\n} \n", "meta": {"hexsha": "50e2d57f2a3c175e6bfde868b7896d82bce251b9", "size": 3134, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/umfpack/test/umfpack_simple.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/umfpack/test/umfpack_simple.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/umfpack/test/umfpack_simple.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": 37.3095238095, "max_line_length": 79, "alphanum_fraction": 0.5797702616, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5048341558645555}}
{"text": "// Copyright (C) 2014 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 <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n\n#include <limits>\n#include <vector>\n\n#include \"gtest/gtest.h\"\n\n#include \"theia/math/util.h\"\n#include \"theia/sfm/pose/sim_transform_partial_rotation.h\"\n#include \"theia/sfm/pose/test_util.h\"\n#include \"theia/test/test_utils.h\"\n#include \"theia/util/random.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\nnamespace {\n\nusing Eigen::AngleAxisd;\nusing Eigen::Matrix3d;\nusing Eigen::Matrix3d;\nusing Eigen::Quaterniond;\nusing Eigen::Vector3d;\n\nRandomNumberGenerator rng(60);\n\n// Tests that the four point pose works correctly by taking the passed\n// points_3d, projecting them to view_1_origins to get image one rays,\n// transforming by (expected_rotation, expected_translation) to get\n// image two rays and then verifying that the FourPointEssentialMatrix\n// function returns (expected_rotation, expected_translation) among its\n// solutions.\n// Noise can be added to the image projections by setting projection_noise.\n// The thresholds for rotation and translation similarity can be controlled\n// by max_rotation_difference and max_difference_between_translation.\n// If projection_noise_std_dev is non-zero then a random noise generator must\n// be passed in rng.\nvoid TestSimTransformResultWithNoise(const Vector3d& axis,\n                                     const Vector3d points_3d[5],\n                                     const Vector3d view_1_origins[5],\n                                     const Vector3d view_2_origins[5],\n                                     double projection_noise_std_dev,\n                                     const Quaterniond& expected_rotation,\n                                     const Vector3d& expected_translation,\n                                     const double expected_scale,\n                                     double max_rotation_difference,\n                                     double max_translation_difference,\n                                     double max_scale_difference) {\n  Vector3d image_one_rays[5];\n  Vector3d image_two_rays[5];\n  Vector3d image_one_origins[5];\n  Vector3d image_two_origins[5];\n\n  for (int i = 0; i < 5; ++i) {\n    image_one_origins[i] = view_1_origins[i];\n    image_one_rays[i] = (points_3d[i] - view_1_origins[i]).normalized();\n\n    image_two_origins[i] =\n        expected_rotation.inverse() *\n        (view_2_origins[i] - expected_translation) / expected_scale;\n    image_two_rays[i] = expected_rotation.inverse() *\n                        (points_3d[i] - view_2_origins[i]).normalized();\n  }\n  if (projection_noise_std_dev) {\n    for (int i = 0; i < 5; ++i) {\n      AddNoiseToRay(projection_noise_std_dev, &rng, &image_one_rays[i]);\n      AddNoiseToRay(projection_noise_std_dev, &rng, &image_two_rays[i]);\n    }\n  }\n  std::vector<Quaterniond> soln_rotations;\n  std::vector<Vector3d> soln_translations;\n  std::vector<double> soln_scales;\n  SimTransformPartialRotation(axis,\n                              image_one_rays,\n                              image_one_origins,\n                              image_two_rays,\n                              image_two_origins,\n                              &soln_rotations,\n                              &soln_translations,\n                              &soln_scales);\n\n  bool matched_transform = false;\n  for (int n = 0; n < soln_rotations.size(); ++n) {\n    const double rotation_difference =\n        expected_rotation.angularDistance(soln_rotations[n]);\n\n    bool matched_rotation = (rotation_difference < max_rotation_difference);\n\n    const double translation_difference =\n        (expected_translation - soln_translations[n]).norm();\n\n    bool matched_translation =\n        (translation_difference < max_translation_difference);\n\n    const double scale_difference =\n        fabs(expected_scale - soln_scales[n]) / expected_scale;\n    const bool matched_scale = (scale_difference < max_scale_difference);\n\n\n    LOG(INFO) << \"Rot diff = \" << rotation_difference;\n    LOG(INFO) << \"Translation diff = \" << translation_difference;\n    LOG(INFO) << \"Scale diff = \" << scale_difference;\n    if (matched_translation && matched_rotation && matched_scale) {\n      matched_transform = true;\n      break;\n    }\n  }\n  EXPECT_TRUE(matched_transform);\n}\n\nTEST(SimTransformPartialRotationTest, Basic) {\n  // Sets up some points in the 3D scene\n  const Vector3d kPoints3D[5] = { Vector3d(-1.0, 3.0, 3.0),\n                                  Vector3d(1.0, -1.0, 2.0),\n                                  Vector3d(2.0, 1.0, 3.0),\n                                  Vector3d(4.0, 3.0, 5.0),\n                                  Vector3d(-2.0, 1.0, -1.0) };\n\n  const Vector3d kImageOneOrigins[5] = { Vector3d(-1.0, 0.0, 0.0),\n                                         Vector3d(0.0, 0.0, 0.0),\n                                         Vector3d(2.0, 0.0, 0.0),\n                                         Vector3d(3.0, 0.0, 0.0),\n                                         Vector3d(4.0, 0.0, 0.0) };\n\n  const Vector3d kImageTwoOrigins[5] = { Vector3d(0.0, 1.0, 0.0),\n                                         Vector3d(0.0, 0.0, 0.0),\n                                         Vector3d(0.0, 2.0, 0.0),\n                                         Vector3d(0.0, 3.0, 0.0),\n                                         Vector3d(0.0, 4.0, 0.0) };\n\n  const Vector3d axis = Vector3d(1.0, 1.0, 1.0).normalized();\n  Quaterniond kExpectedRotation(AngleAxisd(DegToRad(51.0), axis));\n\n  const Vector3d kExpectedTranslation(-2.0, 3.0, -5.0);\n  const double kExpectedScale = 1.7;\n  double kProjectionNoise = 0.0;\n  double kMaxAllowedRotationDifference = 1e-5;\n  double kMaxAllowedTranslationDifference = 1e-4;\n  double kMaxAllowedScaleDifference = 1e-2;\n  TestSimTransformResultWithNoise(axis,\n                                  kPoints3D,\n                                  kImageOneOrigins,\n                                  kImageTwoOrigins,\n                                  kProjectionNoise,\n                                  kExpectedRotation,\n                                  kExpectedTranslation,\n                                  kExpectedScale,\n                                  kMaxAllowedRotationDifference,\n                                  kMaxAllowedTranslationDifference,\n                                  kMaxAllowedScaleDifference);\n}\n\nTEST(SimTransformPartialRotationTest, NoRotation) {\n  // Sets up some points in the 3D scene\n  const Vector3d kPoints3D[5] = { Vector3d(-1.0, 3.0, 3.0),\n                                  Vector3d(1.0, -1.0, 2.0),\n                                  Vector3d(2.0, 2.0, 5.0),\n                                  Vector3d(4.0, 3.0, 5.0) };\n\n  const Vector3d kImageOneOrigins[5] = { Vector3d(-1.0, 0.0, -1.5),\n                                         Vector3d(0.0, 0.0, -1.0),\n                                         Vector3d(2.0, 0.0, 0.0),\n                                         Vector3d(3.0, 0.0, 0.0),\n                                         Vector3d(0.0, 0.0, -2.0) };\n\n  const Vector3d kImageTwoOrigins[5] = { Vector3d(0.0, 1.0, 2.0),\n                                         Vector3d(0.0, 0.0, 0.0),\n                                         Vector3d(0.0, 2.0, 1.0),\n                                         Vector3d(0.0, 3.0, 0.0),\n                                         Vector3d(0.0, 3.0, 1.0) };\n\n  const Vector3d axis = Vector3d(1.0, 1.0, 1.0).normalized();\n  Quaterniond kExpectedRotation(AngleAxisd(DegToRad(0.0), axis));\n\n  const Vector3d kExpectedTranslation(1.0, 1.0, 1.0);\n  const double kExpectedScale = 1.3;\n  double kProjectionNoise = 0.0;\n  double kMaxAllowedRotationDifference = 1e-5;\n  double kMaxAllowedTranslationDifference = 1e-4;\n  double kMaxAllowedScaleDifference = 1e-4;\n  TestSimTransformResultWithNoise(axis,\n                                  kPoints3D,\n                                  kImageOneOrigins,\n                                  kImageTwoOrigins,\n                                  kProjectionNoise,\n                                  kExpectedRotation,\n                                  kExpectedTranslation,\n                                  kExpectedScale,\n                                  kMaxAllowedRotationDifference,\n                                  kMaxAllowedTranslationDifference,\n                                  kMaxAllowedScaleDifference);\n}\n\nTEST(SimTransformPartialRotationTest, NoTranslation) {\n  // Sets up some points in the 3D scene\n  const Vector3d kPoints3D[5] = { Vector3d(-1.0, 3.0, 3.0),\n                                  Vector3d(1.0, -1.0, 2.0),\n                                  Vector3d(2.0, 2.0, 5.0),\n                                  Vector3d(4.0, 3.0, 5.0) };\n\n  const Vector3d kImageOneOrigins[5] = { Vector3d(-1.0, 0.0, -1.5),\n                                         Vector3d(0.0, 0.0, -1.0),\n                                         Vector3d(2.0, 0.0, 0.0),\n                                         Vector3d(3.0, 0.0, 0.0),\n                                         Vector3d(0.0, 0.0, -2.0) };\n\n  const Vector3d kImageTwoOrigins[5] = { Vector3d(0.0, 1.0, 2.0),\n                                         Vector3d(0.0, 0.0, 0.0),\n                                         Vector3d(0.0, 2.0, 1.0),\n                                         Vector3d(0.0, 3.0, 0.0),\n                                         Vector3d(0.0, 3.0, 1.0) };\n\n  const Vector3d axis = Vector3d(1.0, 1.0, 1.0).normalized();\n  Quaterniond kExpectedRotation(AngleAxisd(DegToRad(15.7), axis));\n\n  const Vector3d kExpectedTranslation(0.0, 0.0, 0.0);\n  const double kExpectedScale = 1.3;\n  double kProjectionNoise = 0.0;\n  double kMaxAllowedRotationDifference = 1e-5;\n  double kMaxAllowedTranslationDifference = 1e-4;\n  double kMaxAllowedScaleDifference = 1e-4;\n  TestSimTransformResultWithNoise(axis,\n                                  kPoints3D,\n                                  kImageOneOrigins,\n                                  kImageTwoOrigins,\n                                  kProjectionNoise,\n                                  kExpectedRotation,\n                                  kExpectedTranslation,\n                                  kExpectedScale,\n                                  kMaxAllowedRotationDifference,\n                                  kMaxAllowedTranslationDifference,\n                                  kMaxAllowedScaleDifference);\n}\n\n// Tests a variety of axes, angles and translations with added projection noise.\nTEST(SimTransformPartialRotationTest, NoiseTest) {\n  const Vector3d kPoints3D[5] = { Vector3d(-1.0, 3.0, 3.0),\n                                  Vector3d(1.0, -1.0, 2.0),\n                                  Vector3d(2.0, 1.0, 3.0),\n                                  Vector3d(4.0, 3.0, 5.0) };\n\n  const Vector3d kImageOneOrigins[5] = { Vector3d(-1.0, 0.0, 0.0),\n                                         Vector3d(0.0, 0.0, 0.0),\n                                         Vector3d(2.0, 0.0, 0.0),\n                                         Vector3d(3.0, 0.0, 0.0),\n                                         Vector3d(4.0, 0.0, 0.0) };\n\n  const Vector3d kImageTwoOrigins[5] = { Vector3d(0.0, 1.0, 0.0),\n                                         Vector3d(0.0, 0.0, 0.0),\n                                         Vector3d(0.0, 2.0, 0.0),\n                                         Vector3d(0.0, 3.0, 0.0),\n                                         Vector3d(0.0, 4.0, 0.0) };\n\n  const Vector3d kAxes[5] = { Vector3d(0.0, 0.0, 1.0).normalized(),\n                              Vector3d(1.0, 0.0, 0.0).normalized(),\n                              Vector3d(1.0, 0.0, 1.0).normalized(),\n                              Vector3d(1.0, 1.0, 0.0).normalized(),\n                              Vector3d(1.0, 1.0, 1.0).normalized() };\n\n  const double kAngles[5] = {11.0, 5.0, 2.0, 13.0, 12.0};\n\n  const Vector3d kTranslations[5] = {\n    Vector3d(1.0, 1.0, 1.0), Vector3d(4.0, 5.0, 11.0), Vector3d(1.0, 2.0, 15.0),\n    Vector3d(6.0, 3.0, 2.0), Vector3d(13.0, 1.0, 15.0)\n  };\n\n  const double kScales[5] = { 1.2, 2.9, 10.3, 4.2, 5.3 };\n\n  for (int transform_index = 0;\n       transform_index < THEIA_ARRAYSIZE(kAxes);\n       ++transform_index) {\n    Quaterniond kExpectedRotation(\n        AngleAxisd(DegToRad(kAngles[transform_index]), kAxes[transform_index]));\n\n    const double kProjectionNoise = 1.0 / 512;\n    const double kMaxAllowedRotationDifference = DegToRad(10.0);\n    const double kMaxAllowedTranslationDifference = 3.0;\n    const double kMaxAllowedScaleDifference = 0.15;\n\n    TestSimTransformResultWithNoise(kAxes[transform_index],\n                                    kPoints3D,\n                                    kImageOneOrigins,\n                                    kImageTwoOrigins,\n                                    kProjectionNoise,\n                                    kExpectedRotation,\n                                    kTranslations[transform_index],\n                                    kScales[transform_index],\n                                    kMaxAllowedRotationDifference,\n                                    kMaxAllowedTranslationDifference,\n                                    kMaxAllowedScaleDifference);\n  }\n}\n\n// Tests that the solver degrades gracefully when the passed axis is not exactly\n// correct.\nTEST(SimTransformPartialRotationTest, IncorrectAxisTest) {\n  const Vector3d kPoints3D[5] = { Vector3d(-1.0, 3.0, 3.0),\n                                  Vector3d(1.0, -1.0, 2.0),\n                                  Vector3d(2.0, 1.0, 3.0),\n                                  Vector3d(4.0, 3.0, 5.0) };\n\n  const Vector3d kImageOneOrigins[5] = { Vector3d(-1.0, 0.0, 0.0),\n                                         Vector3d(0.0, 0.0, 0.0),\n                                         Vector3d(2.0, 0.0, 0.0),\n                                         Vector3d(3.0, 0.0, 0.0),\n                                         Vector3d(4.0, 0.0, 0.0) };\n\n  const Vector3d kImageTwoOrigins[5] = { Vector3d(0.0, 1.0, 0.0),\n                                         Vector3d(0.0, 0.0, 0.0),\n                                         Vector3d(0.0, 2.0, 0.0),\n                                         Vector3d(0.0, 3.0, 0.0),\n                                         Vector3d(0.0, 4.0, 0.0) };\n\n  const Vector3d kAxes[5] = {\n      Vector3d(0.0, 0.0, 1.0).normalized(),\n      Vector3d(1.0, 0.0, 0.0).normalized(),\n      Vector3d(1.0, 0.0, 1.0).normalized(),\n      Vector3d(1.0, 1.0, 0.0).normalized(),\n      Vector3d(1.0, 1.0, 1.0).normalized()\n  };\n\n  const double kAngles[5] = {11.0, 5.0, 2.0, 13.0, 12.0};\n\n  const Vector3d kTranslations[5] = {\n      Vector3d(1.0, 1.0, 1.0),\n      Vector3d(4.0, 5.0, 11.0),\n      Vector3d(1.0, 2.0, 15.0),\n      Vector3d(6.0, 3.0, 2.0),\n      Vector3d(13.0, 1.0, 15.0)\n  };\n  const double kScales[5] = { 1.2, 2.9, 10.3, 101.2, 54.3 };\n\n  // The axes are perturbed by these rotation to simulate the axis not being\n  // perfectly known.\n  const Quaterniond kAxisPerturbations[6] = {\n    Quaterniond(AngleAxisd(DegToRad(1.0), Vector3d(1.0, 0, 0))),\n    Quaterniond(AngleAxisd(DegToRad(-1.0), Vector3d(1.0, 0, 0))),\n    Quaterniond(AngleAxisd(DegToRad(1.0), Vector3d(0.0, 1.0, 0))),\n    Quaterniond(AngleAxisd(DegToRad(-1.0), Vector3d(0.0, 1.0, 0))),\n    Quaterniond(AngleAxisd(DegToRad(1.0), Vector3d(0.0, 0.0, 1.0))),\n    Quaterniond(AngleAxisd(DegToRad(-1.0), Vector3d(0.0, 0.0, 1.0)))\n  };\n\n  for (int transform_index = 0;\n       transform_index < THEIA_ARRAYSIZE(kAxes);\n       ++transform_index) {\n    for (int axis_rotation_index = 0;\n         axis_rotation_index < THEIA_ARRAYSIZE(kAxisPerturbations);\n         ++axis_rotation_index) {\n      // Perturbs the axis by the axis perturbation.\n      const Vector3d perturbed_axis =\n          kAxisPerturbations[axis_rotation_index] * kAxes[transform_index];\n      // Uses the perturbed rotation as the expected rotation, but the original\n      // axis is passed as the axis.\n      Quaterniond kExpectedRotation(\n          AngleAxisd(DegToRad(kAngles[transform_index]), perturbed_axis));\n\n      // Tests the ThreePointEssentialMatrix function with fairly large\n      // thresholds on the allowed translation and rotation differences.\n      const double kProjectionNoise = 0.0;\n      const double kMaxAllowedRotationDifference = DegToRad(2.0);\n      const double kMaxAllowedTranslationDifference = 2.0;\n      const double kMaxAllowedScaleDifference = 1e-1;\n\n      TestSimTransformResultWithNoise(perturbed_axis,\n                                      kPoints3D,\n                                      kImageOneOrigins,\n                                      kImageTwoOrigins,\n                                      kProjectionNoise,\n                                      kExpectedRotation,\n                                      kTranslations[transform_index],\n                                      kScales[transform_index],\n                                      kMaxAllowedRotationDifference,\n                                      kMaxAllowedTranslationDifference,\n                                      kMaxAllowedScaleDifference);\n    }\n  }\n}\n\n}  // namespace\n}  // namespace theia\n", "meta": {"hexsha": "1309b8a89e5e95fff779ef51a3c79886d6012260", "size": 18827, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/sim_transform_partial_rotation_test.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/sim_transform_partial_rotation_test.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/sim_transform_partial_rotation_test.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": 45.0406698565, "max_line_length": 80, "alphanum_fraction": 0.5372603176, "num_tokens": 4945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5048341551394806}}
{"text": "//\n// Created by yalavrinenko on 26.09.2021.\n//\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <opencv2/opencv.hpp>\n#include \"../src/pathfinders/legacy/asearch.hpp\"\n#include \"../src/pathfinders/boost_graph/full_linked_graph.hpp\"\n#include <boost/format.hpp>\n#include <iostream>\n\nnamespace std {\n  ostream &operator<<(ostream &os, const pair<int, int> &yt) {\n    os << (boost::format(\"(%d, %d)\") % yt.first % yt.second);\n    return os;\n  }\n}\n\nBOOST_AUTO_TEST_SUITE(AstarTest)\n\nBOOST_AUTO_TEST_CASE(SimpleGraphLoop, * boost::unit_test::tolerance(0.00001)){\n\n  char data[] = {\n      1, 1, 1, 1, 1,\n      1, 1, 1, 1, 1,\n      1, 1, 1, 1, 1,\n      1, 1, 1, 1, 1,\n      1, 1, 1, 1, 1\n  };\n  cv::Mat map {5, 5, CV_8UC1, data};\n\n  trs::full_linked_grid graph{map};\n  auto visitor = trs::full_linked_grid::visitor({4, 4});\n\n  auto path = trs::astar_search<trs::full_linked_grid>::find_path(graph, {2, 2}, {4, 4}, visitor);\n  BOOST_TEST(path.first == std::sqrt(8.0) );\n  BOOST_TEST(path.second.size() == 3);\n\n  std::vector<std::pair<int, int>> eta {{4, 4}, {3, 3}, {2, 2}};\n  BOOST_TEST(path.second == eta, boost::test_tools::per_element());\n}\n\nBOOST_AUTO_TEST_CASE(LinearGraph, * boost::unit_test::tolerance(0.00001)){\n\n  char data[] = {\n      1, 1, 1, 1, 1\n  };\n  cv::Mat map {1, 5, CV_8UC1, data};\n\n  trs::full_linked_grid graph{map};\n  trs::full_linked_grid::vertex_t begin{0, 0}, end{0, 4};\n  auto visitor = trs::full_linked_grid::visitor(end);\n\n  auto path = trs::astar_search<trs::full_linked_grid>::find_path(graph, begin, end, visitor);\n  BOOST_TEST(path.first == 4 );\n  BOOST_TEST(path.second.size() == 5);\n\n  std::vector<std::pair<int, int>> eta {{0, 4}, {0, 3}, {0, 2}, {0, 1}, {0, 0}};\n  BOOST_TEST(path.second == eta, boost::test_tools::per_element());\n}\n\nBOOST_AUTO_TEST_CASE(VerticalGraph, * boost::unit_test::tolerance(0.00001)){\n\n  char data[] = {\n      1,\n      1,\n      1,\n      1,\n      1\n  };\n  cv::Mat map {5, 1, CV_8UC1, data};\n\n  trs::full_linked_grid graph{map};\n  trs::full_linked_grid::vertex_t begin{4, 0}, end{0, 0};\n  auto visitor = trs::full_linked_grid::visitor(end);\n\n  auto path = trs::astar_search<trs::full_linked_grid>::find_path(graph, begin, end, visitor);\n  BOOST_TEST(path.first == 4 );\n  BOOST_TEST(path.second.size() == 5);\n\n  std::vector<std::pair<int, int>> eta {{0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}};\n  BOOST_TEST(path.second == eta, boost::test_tools::per_element());\n}\n\nBOOST_AUTO_TEST_CASE(NoPathGraph, * boost::unit_test::tolerance(0.00001)){\n\n  char data[] = {\n      1, 1, 1, 1,\n      1, 1, 0, 0,\n      1, 1, 0, 0,\n  };\n  cv::Mat map {3, 4, CV_8UC1, data};\n\n  trs::full_linked_grid graph{map};\n  trs::full_linked_grid::vertex_t begin{0, 0}, end{02, 3};\n  auto visitor = trs::full_linked_grid::visitor(end);\n\n  auto path = trs::astar_search<trs::full_linked_grid>::find_path(graph, begin, end, visitor);\n  BOOST_TEST(path.first == -1.0 );\n}\n\nBOOST_AUTO_TEST_CASE(HardPathGraph, * boost::unit_test::tolerance(0.00001)){\n\n  char data[] = {\n      1, 0, 1, 1, 1,\n      1, 1, 1, 1, 0,\n      0, 0, 1, 0, 0,\n      1, 1, 0, 0, 0,\n      1, 1, 1, 1, 1\n  };\n  cv::Mat map {5, 5, CV_8UC1, data};\n\n  trs::full_linked_grid graph{map};\n  trs::full_linked_grid::vertex_t begin{0, 0}, end{4, 4};\n  auto visitor = trs::full_linked_grid::visitor(end);\n\n  auto path = trs::astar_search<trs::full_linked_grid>::find_path(graph, begin, end, visitor);\n  auto s2 = std::sqrt(2.0);\n  BOOST_TEST(path.first == (s2 + s2 + s2 + s2 + 1 + 1) );\n  BOOST_TEST(path.second.size() == 7);\n\n  std::vector<std::pair<int, int>> eta {\n      {4, 4}, {4, 3}, {4, 2},\n      {3, 1},\n      {2, 2},\n      {1, 1},\n      {0, 0}\n  };\n  BOOST_TEST(path.second == eta, boost::test_tools::per_element());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "f63437ecd40f0cd0e48dbb445468d7a986169b8c", "size": 3798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/astar_tests.cpp", "max_stars_repo_name": "yalavrinenko/trash_rogaine_solver", "max_stars_repo_head_hexsha": "88833935419ea340a9e51722da4b4907a502ea38", "max_stars_repo_licenses": ["MIT"], "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/astar_tests.cpp", "max_issues_repo_name": "yalavrinenko/trash_rogaine_solver", "max_issues_repo_head_hexsha": "88833935419ea340a9e51722da4b4907a502ea38", "max_issues_repo_licenses": ["MIT"], "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/astar_tests.cpp", "max_forks_repo_name": "yalavrinenko/trash_rogaine_solver", "max_forks_repo_head_hexsha": "88833935419ea340a9e51722da4b4907a502ea38", "max_forks_repo_licenses": ["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.9264705882, "max_line_length": 98, "alphanum_fraction": 0.6187467088, "num_tokens": 1379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5048341509056685}}
{"text": "#include \"norm_damping.hpp\"\n\n#include <string>\n#include <armadillo>\n#include <yaml-cpp/yaml.h>\n\nNormDamping::NormDamping(const std::string &filenm):\n  Regularization(filenm)\n{\n  YAML::Node config = YAML::LoadFile(filenm);\n  output_file_ = config[\"file_norm\"].as<std::string>();\n\n  this->load();\n}\n\n\nvoid NormDamping::save()\n{\n  Regularization::save(output_file_);\n}\n\n\nvoid NormDamping::cal_fitness()\n{\n  fitness_ = arma::accu(arma::square(umodel_-rmodel_));\n}\n\n\nvoid NormDamping::cal_gradient()\n{\n  gradient_ = 2*(umodel_ - rmodel_);\n}\n", "meta": {"hexsha": "01386de8d01eedbfe5e4546fce916873ca08fb91", "size": 536, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/norm_damping.cc", "max_stars_repo_name": "panlei7/regularization", "max_stars_repo_head_hexsha": "a417e844bfcc841e35f8075918837cc99a276bfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/norm_damping.cc", "max_issues_repo_name": "panlei7/regularization", "max_issues_repo_head_hexsha": "a417e844bfcc841e35f8075918837cc99a276bfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/norm_damping.cc", "max_forks_repo_name": "panlei7/regularization", "max_forks_repo_head_hexsha": "a417e844bfcc841e35f8075918837cc99a276bfc", "max_forks_repo_licenses": ["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.2424242424, "max_line_length": 55, "alphanum_fraction": 0.7014925373, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.504834146913548}}
{"text": "#define BOOST_TEST_MODULE CODATA_2006\n#include <boost/test/included/unit_test.hpp>\n\n#include <cmath>\n#include <tuple>\n\ntypedef std::tuple<float, double, long double> test_types;\n\n#include <triumf/constants/codata_2006.hpp>\n\n// lattice spacing of silicon\n// (1.920155762e-10 \u00b1 5e-18) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(lattice_spacing_of_silicon, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::lattice_spacing_of_silicon<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::lattice_spacing_of_silicon<T>::value() ==\n      static_cast<T>(1.920155762e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::lattice_spacing_of_silicon<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::lattice_spacing_of_silicon<\n                 T>::uncertainty() == static_cast<T>(5e-18));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::lattice_spacing_of_silicon<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::lattice_spacing_of_silicon<\n                    T>::precision()));\n}\n\n// alpha particle-electron mass ratio\n// (7294.2995365 \u00b1 3.1e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_electron_mass_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_electron_mass_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::alpha_particle_electron_mass_ratio<\n                 T>::value() == static_cast<T>(7294.2995365));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_electron_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::alpha_particle_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(3.1e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_electron_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::alpha_particle_electron_mass_ratio<\n          T>::precision()));\n}\n\n// alpha particle mass\n// (6.6446562e-27 \u00b1 3.3e-34) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::alpha_particle_mass<T>::value() ==\n             static_cast<T>(6.6446562e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::alpha_particle_mass<T>::uncertainty() ==\n      static_cast<T>(3.3e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::alpha_particle_mass<T>::precision()));\n}\n\n// alpha particle mass energy equivalent\n// (5.97191917e-10 \u00b1 3e-17) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_mass_energy_equivalent, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::alpha_particle_mass_energy_equivalent<\n          T>::value() == static_cast<T>(5.97191917e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::alpha_particle_mass_energy_equivalent<\n          T>::uncertainty() == static_cast<T>(3e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::alpha_particle_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// alpha particle mass energy equivalent in MeV\n// (3727.379109 \u00b1 9.3e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 alpha_particle_mass_energy_equivalent_in_MeV<T>::value() ==\n             static_cast<T>(3727.379109));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::uncertainty() ==\n      static_cast<T>(9.3e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::precision()));\n}\n\n// alpha particle mass in u\n// (4.001506179127 \u00b1 6.2e-11) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_mass_in_u<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::alpha_particle_mass_in_u<T>::value() ==\n      static_cast<T>(4.001506179127));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::alpha_particle_mass_in_u<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::alpha_particle_mass_in_u<\n                 T>::uncertainty() == static_cast<T>(6.2e-11));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::alpha_particle_mass_in_u<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::alpha_particle_mass_in_u<\n                    T>::precision()));\n}\n\n// alpha particle molar mass\n// (0.004001506179127 \u00b1 6.2e-14) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_molar_mass<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::alpha_particle_molar_mass<T>::value() ==\n      static_cast<T>(0.004001506179127));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::alpha_particle_molar_mass<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::alpha_particle_molar_mass<\n                 T>::uncertainty() == static_cast<T>(6.2e-14));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::alpha_particle_molar_mass<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::alpha_particle_molar_mass<\n                    T>::precision()));\n}\n\n// alpha particle-proton mass ratio\n// (3.97259968951 \u00b1 4.1e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_proton_mass_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::alpha_particle_proton_mass_ratio<\n                 T>::value() == static_cast<T>(3.97259968951));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_proton_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::alpha_particle_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(4.1e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::alpha_particle_proton_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::alpha_particle_proton_mass_ratio<\n          T>::precision()));\n}\n\n// Angstrom star\n// (1.00001498e-10 \u00b1 9e-17) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Angstrom_star, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Angstrom_star<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Angstrom_star<T>::value() ==\n             static_cast<T>(1.00001498e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Angstrom_star<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Angstrom_star<T>::uncertainty() ==\n             static_cast<T>(9e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Angstrom_star<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Angstrom_star<T>::precision()));\n}\n\n// atomic mass constant\n// (1.660538782e-27 \u00b1 8.3e-35) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_mass_constant<T>::value() ==\n             static_cast<T>(1.660538782e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_mass_constant<T>::uncertainty() ==\n      static_cast<T>(8.3e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_mass_constant<T>::precision()));\n}\n\n// atomic mass constant energy equivalent\n// (1.49241783e-10 \u00b1 7.4e-18) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_constant_energy_equivalent, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_constant_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_mass_constant_energy_equivalent<\n          T>::value() == static_cast<T>(1.49241783e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_constant_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_mass_constant_energy_equivalent<\n          T>::uncertainty() == static_cast<T>(7.4e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_constant_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_mass_constant_energy_equivalent<\n          T>::precision()));\n}\n\n// atomic mass constant energy equivalent in MeV\n// (931.494028 \u00b1 2.3e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_constant_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 atomic_mass_constant_energy_equivalent_in_MeV<T>::value() ==\n             static_cast<T>(931.494028));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::uncertainty() ==\n      static_cast<T>(2.3e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::precision()));\n}\n\n// atomic mass unit-electron volt relationship\n// (931494028.0 \u00b1 23.0) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          atomic_mass_unit_electron_volt_relationship<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 atomic_mass_unit_electron_volt_relationship<T>::value() ==\n             static_cast<T>(931494028.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          atomic_mass_unit_electron_volt_relationship<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          atomic_mass_unit_electron_volt_relationship<T>::uncertainty() ==\n      static_cast<T>(23.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          atomic_mass_unit_electron_volt_relationship<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          atomic_mass_unit_electron_volt_relationship<T>::precision()));\n}\n\n// atomic mass unit-hartree relationship\n// (34231777.149 \u00b1 0.049) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_hartree_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_hartree_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_mass_unit_hartree_relationship<\n          T>::value() == static_cast<T>(34231777.149));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_hartree_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_mass_unit_hartree_relationship<\n          T>::uncertainty() == static_cast<T>(0.049));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_hartree_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_mass_unit_hartree_relationship<\n          T>::precision()));\n}\n\n// atomic mass unit-hertz relationship\n// (2.2523427369e+23 \u00b1 320000000000000.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_hertz_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_hertz_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_mass_unit_hertz_relationship<\n          T>::value() == static_cast<T>(2.2523427369e+23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_hertz_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_mass_unit_hertz_relationship<\n          T>::uncertainty() == static_cast<T>(320000000000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_hertz_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_mass_unit_hertz_relationship<\n          T>::precision()));\n}\n\n// atomic mass unit-inverse meter relationship\n// (751300667100000.0 \u00b1 1100000.0) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          atomic_mass_unit_inverse_meter_relationship<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 atomic_mass_unit_inverse_meter_relationship<T>::value() ==\n             static_cast<T>(751300667100000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          atomic_mass_unit_inverse_meter_relationship<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          atomic_mass_unit_inverse_meter_relationship<T>::uncertainty() ==\n      static_cast<T>(1100000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          atomic_mass_unit_inverse_meter_relationship<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          atomic_mass_unit_inverse_meter_relationship<T>::precision()));\n}\n\n// atomic mass unit-joule relationship\n// (1.49241783e-10 \u00b1 7.4e-18) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_joule_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_joule_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_mass_unit_joule_relationship<\n          T>::value() == static_cast<T>(1.49241783e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_joule_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_mass_unit_joule_relationship<\n          T>::uncertainty() == static_cast<T>(7.4e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_joule_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_mass_unit_joule_relationship<\n          T>::precision()));\n}\n\n// atomic mass unit-kelvin relationship\n// (10809527000000.0 \u00b1 19000000.0) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_kelvin_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_kelvin_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_mass_unit_kelvin_relationship<\n          T>::value() == static_cast<T>(10809527000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_kelvin_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_mass_unit_kelvin_relationship<\n          T>::uncertainty() == static_cast<T>(19000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_kelvin_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_mass_unit_kelvin_relationship<\n          T>::precision()));\n}\n\n// atomic mass unit-kilogram relationship\n// (1.660538782e-27 \u00b1 8.3e-35) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_kilogram_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_mass_unit_kilogram_relationship<\n          T>::value() == static_cast<T>(1.660538782e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_mass_unit_kilogram_relationship<\n          T>::uncertainty() == static_cast<T>(8.3e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_mass_unit_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_mass_unit_kilogram_relationship<\n          T>::precision()));\n}\n\n// atomic unit of 1st hyperpolarizability\n// (3.206361533e-53 \u00b1 8.1e-61) C^3 m^3 J^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_1st_hyperpolarizability, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_1st_hyperpolarizability<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_1st_hyperpolarizability<\n          T>::value() == static_cast<T>(3.206361533e-53));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_1st_hyperpolarizability<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_1st_hyperpolarizability<\n          T>::uncertainty() == static_cast<T>(8.1e-61));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_1st_hyperpolarizability<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_1st_hyperpolarizability<\n          T>::precision()));\n}\n\n// atomic unit of 2nd hyperpolarizability\n// (6.23538095e-65 \u00b1 3.1e-72) C^4 m^4 J^-3\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_2nd_hyperpolarizability, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_2nd_hyperpolarizability<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_2nd_hyperpolarizability<\n          T>::value() == static_cast<T>(6.23538095e-65));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_2nd_hyperpolarizability<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_2nd_hyperpolarizability<\n          T>::uncertainty() == static_cast<T>(3.1e-72));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_2nd_hyperpolarizability<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_2nd_hyperpolarizability<\n          T>::precision()));\n}\n\n// atomic unit of action\n// (1.054571628e-34 \u00b1 5.3e-42) J s\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_action, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_action<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_action<T>::value() ==\n      static_cast<T>(1.054571628e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_action<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_action<T>::uncertainty() ==\n      static_cast<T>(5.3e-42));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_action<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_action<T>::precision()));\n}\n\n// atomic unit of charge\n// (1.602176487e-19 \u00b1 4e-27) C\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_charge, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_charge<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_charge<T>::value() ==\n      static_cast<T>(1.602176487e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_charge<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_charge<T>::uncertainty() ==\n      static_cast<T>(4e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_charge<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_charge<T>::precision()));\n}\n\n// atomic unit of charge density\n// (1081202300000.0 \u00b1 27000.0) C m^-3\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_charge_density, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_charge_density<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_charge_density<\n                 T>::value() == static_cast<T>(1081202300000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_charge_density<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_charge_density<\n                 T>::uncertainty() == static_cast<T>(27000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_charge_density<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_charge_density<\n          T>::precision()));\n}\n\n// atomic unit of current\n// (0.00662361763 \u00b1 1.7e-10) A\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_current, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_current<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_current<T>::value() ==\n      static_cast<T>(0.00662361763));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::atomic_unit_of_current<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_current<\n                 T>::uncertainty() == static_cast<T>(1.7e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_current<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_current<T>::precision()));\n}\n\n// atomic unit of electric dipole mom.\n// (8.47835281e-30 \u00b1 2.1e-37) C m\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_dipole_mom, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_dipole_mom<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_electric_dipole_mom<\n                 T>::value() == static_cast<T>(8.47835281e-30));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_dipole_mom<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_electric_dipole_mom<\n                 T>::uncertainty() == static_cast<T>(2.1e-37));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_dipole_mom<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_electric_dipole_mom<\n          T>::precision()));\n}\n\n// atomic unit of electric field\n// (514220632000.0 \u00b1 13000.0) V m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_field, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_field<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_electric_field<\n                 T>::value() == static_cast<T>(514220632000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_field<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_electric_field<\n                 T>::uncertainty() == static_cast<T>(13000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_field<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_electric_field<\n          T>::precision()));\n}\n\n// atomic unit of electric field gradient\n// (9.71736166e+21 \u00b1 240000000000000.0) V m^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_field_gradient, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_field_gradient<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_electric_field_gradient<\n          T>::value() == static_cast<T>(9.71736166e+21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_field_gradient<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_electric_field_gradient<\n          T>::uncertainty() == static_cast<T>(240000000000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_field_gradient<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_electric_field_gradient<\n          T>::precision()));\n}\n\n// atomic unit of electric polarizability\n// (1.6487772536e-41 \u00b1 3.4e-50) C^2 m^2 J^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_polarizability, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_polarizability<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_electric_polarizability<\n          T>::value() == static_cast<T>(1.6487772536e-41));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_polarizability<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_electric_polarizability<\n          T>::uncertainty() == static_cast<T>(3.4e-50));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_polarizability<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_electric_polarizability<\n          T>::precision()));\n}\n\n// atomic unit of electric potential\n// (27.21138386 \u00b1 6.8e-07) V\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_potential, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_potential<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_electric_potential<\n                 T>::value() == static_cast<T>(27.21138386));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_potential<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_electric_potential<\n                 T>::uncertainty() == static_cast<T>(6.8e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_potential<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_electric_potential<\n          T>::precision()));\n}\n\n// atomic unit of electric quadrupole mom.\n// (4.48655107e-40 \u00b1 1.1e-47) C m^2\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_quadrupole_mom, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_quadrupole_mom<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_electric_quadrupole_mom<\n          T>::value() == static_cast<T>(4.48655107e-40));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_quadrupole_mom<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_electric_quadrupole_mom<\n          T>::uncertainty() == static_cast<T>(1.1e-47));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_electric_quadrupole_mom<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_electric_quadrupole_mom<\n          T>::precision()));\n}\n\n// atomic unit of energy\n// (4.35974394e-18 \u00b1 2.2e-25) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_energy, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_energy<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_energy<T>::value() ==\n      static_cast<T>(4.35974394e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_energy<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_energy<T>::uncertainty() ==\n      static_cast<T>(2.2e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_energy<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_energy<T>::precision()));\n}\n\n// atomic unit of force\n// (8.23872206e-08 \u00b1 4.1e-15) N\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_force, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_force<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_force<T>::value() ==\n             static_cast<T>(8.23872206e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_force<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_force<T>::uncertainty() ==\n      static_cast<T>(4.1e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_force<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_force<T>::precision()));\n}\n\n// atomic unit of length\n// (5.2917720859e-11 \u00b1 3.6e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_length, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_length<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_length<T>::value() ==\n      static_cast<T>(5.2917720859e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_length<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_length<T>::uncertainty() ==\n      static_cast<T>(3.6e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_length<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_length<T>::precision()));\n}\n\n// atomic unit of mag. dipole mom.\n// (1.85480183e-23 \u00b1 4.6e-31) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_mag_dipole_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_mag_dipole_mom<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_mag_dipole_mom<\n                 T>::value() == static_cast<T>(1.85480183e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_mag_dipole_mom<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_mag_dipole_mom<\n                 T>::uncertainty() == static_cast<T>(4.6e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_mag_dipole_mom<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_mag_dipole_mom<\n          T>::precision()));\n}\n\n// atomic unit of mag. flux density\n// (235051.7382 \u00b1 0.0059) T\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_mag_flux_density, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_mag_flux_density<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_mag_flux_density<\n                 T>::value() == static_cast<T>(235051.7382));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_mag_flux_density<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_mag_flux_density<\n                 T>::uncertainty() == static_cast<T>(0.0059));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_mag_flux_density<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_mag_flux_density<\n          T>::precision()));\n}\n\n// atomic unit of magnetizability\n// (7.891036433e-29 \u00b1 2.7e-37) J T^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_magnetizability, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_magnetizability<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_magnetizability<\n                 T>::value() == static_cast<T>(7.891036433e-29));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_magnetizability<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_magnetizability<\n                 T>::uncertainty() == static_cast<T>(2.7e-37));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_magnetizability<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_magnetizability<\n          T>::precision()));\n}\n\n// atomic unit of mass\n// (9.10938215e-31 \u00b1 4.5e-38) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_mass<T>::value() ==\n             static_cast<T>(9.10938215e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_mass<T>::uncertainty() ==\n      static_cast<T>(4.5e-38));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_mass<T>::precision()));\n}\n\n// atomic unit of momentum\n// (1.992851565e-24 \u00b1 9.9e-32) kg m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_momentum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_momentum<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_momentum<T>::value() ==\n      static_cast<T>(1.992851565e-24));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::atomic_unit_of_momentum<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_momentum<\n                 T>::uncertainty() == static_cast<T>(9.9e-32));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_momentum<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_momentum<T>::precision()));\n}\n\n// atomic unit of permittivity\n// (1.112650056e-10 \u00b1 0.0) F m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_permittivity, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_permittivity<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_permittivity<T>::value() ==\n      static_cast<T>(1.112650056e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::atomic_unit_of_permittivity<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_permittivity<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::atomic_unit_of_permittivity<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::atomic_unit_of_permittivity<\n                    T>::precision()));\n}\n\n// atomic unit of time\n// (2.418884326505e-17 \u00b1 1.6e-12) 7 s\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_time, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_time<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_time<T>::value() ==\n             static_cast<T>(2.418884326505e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_time<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_time<T>::uncertainty() ==\n      static_cast<T>(1.6e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_time<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_time<T>::precision()));\n}\n\n// atomic unit of velocity\n// (2187691.2541 \u00b1 0.0015) m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_velocity, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_velocity<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::atomic_unit_of_velocity<T>::value() ==\n      static_cast<T>(2187691.2541));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::atomic_unit_of_velocity<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::atomic_unit_of_velocity<\n                 T>::uncertainty() == static_cast<T>(0.0015));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::atomic_unit_of_velocity<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::atomic_unit_of_velocity<T>::precision()));\n}\n\n// Avogadro constant\n// (6.02214179e+23 \u00b1 3e+16) mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Avogadro_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Avogadro_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Avogadro_constant<T>::value() ==\n             static_cast<T>(6.02214179e+23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Avogadro_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Avogadro_constant<T>::uncertainty() ==\n      static_cast<T>(3e+16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Avogadro_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Avogadro_constant<T>::precision()));\n}\n\n// Bohr magneton\n// (9.27400915e-24 \u00b1 2.3e-31) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Bohr_magneton<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Bohr_magneton<T>::value() ==\n             static_cast<T>(9.27400915e-24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Bohr_magneton<T>::uncertainty() ==\n             static_cast<T>(2.3e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Bohr_magneton<T>::precision()));\n}\n\n// Bohr magneton in eV/T\n// (5.7883817555e-05 \u00b1 7.9e-14) eV T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton_in_eV_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton_in_eV_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Bohr_magneton_in_eV_T<T>::value() ==\n      static_cast<T>(5.7883817555e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton_in_eV_T<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Bohr_magneton_in_eV_T<T>::uncertainty() ==\n      static_cast<T>(7.9e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton_in_eV_T<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Bohr_magneton_in_eV_T<T>::precision()));\n}\n\n// Bohr magneton in Hz/T\n// (13996246040.0 \u00b1 350.0) Hz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton_in_Hz_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton_in_Hz_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Bohr_magneton_in_Hz_T<T>::value() ==\n      static_cast<T>(13996246040.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton_in_Hz_T<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Bohr_magneton_in_Hz_T<T>::uncertainty() ==\n      static_cast<T>(350.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton_in_Hz_T<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Bohr_magneton_in_Hz_T<T>::precision()));\n}\n\n// Bohr magneton in inverse meters per tesla\n// (46.6864515 \u00b1 1.2e-06) m^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton_in_inverse_meters_per_tesla, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton_in_inverse_meters_per_tesla<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Bohr_magneton_in_inverse_meters_per_tesla<\n          T>::value() == static_cast<T>(46.6864515));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton_in_inverse_meters_per_tesla<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Bohr_magneton_in_inverse_meters_per_tesla<\n          T>::uncertainty() == static_cast<T>(1.2e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton_in_inverse_meters_per_tesla<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Bohr_magneton_in_inverse_meters_per_tesla<\n          T>::precision()));\n}\n\n// Bohr magneton in K/T\n// (0.6717131 \u00b1 1.2e-06) K T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton_in_K_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton_in_K_T<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Bohr_magneton_in_K_T<T>::value() ==\n             static_cast<T>(0.6717131));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton_in_K_T<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Bohr_magneton_in_K_T<T>::uncertainty() ==\n      static_cast<T>(1.2e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_magneton_in_K_T<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Bohr_magneton_in_K_T<T>::precision()));\n}\n\n// Bohr radius\n// (5.2917720859e-11 \u00b1 3.6e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_radius, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Bohr_radius<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Bohr_radius<T>::value() ==\n             static_cast<T>(5.2917720859e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_radius<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Bohr_radius<T>::uncertainty() ==\n             static_cast<T>(3.6e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Bohr_radius<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Bohr_radius<T>::precision()));\n}\n\n// Boltzmann constant\n// (1.3806504e-23 \u00b1 2.4e-29) J K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Boltzmann_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Boltzmann_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Boltzmann_constant<T>::value() ==\n             static_cast<T>(1.3806504e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Boltzmann_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Boltzmann_constant<T>::uncertainty() ==\n      static_cast<T>(2.4e-29));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Boltzmann_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Boltzmann_constant<T>::precision()));\n}\n\n// Boltzmann constant in eV/K\n// (8.617343e-05 \u00b1 1.5e-10) eV K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Boltzmann_constant_in_eV_K, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Boltzmann_constant_in_eV_K<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Boltzmann_constant_in_eV_K<T>::value() ==\n      static_cast<T>(8.617343e-05));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Boltzmann_constant_in_eV_K<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Boltzmann_constant_in_eV_K<\n                 T>::uncertainty() == static_cast<T>(1.5e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Boltzmann_constant_in_eV_K<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::Boltzmann_constant_in_eV_K<\n                    T>::precision()));\n}\n\n// Boltzmann constant in Hz/K\n// (20836644000.0 \u00b1 36000.0) Hz K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Boltzmann_constant_in_Hz_K, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Boltzmann_constant_in_Hz_K<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Boltzmann_constant_in_Hz_K<T>::value() ==\n      static_cast<T>(20836644000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Boltzmann_constant_in_Hz_K<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Boltzmann_constant_in_Hz_K<\n                 T>::uncertainty() == static_cast<T>(36000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Boltzmann_constant_in_Hz_K<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::Boltzmann_constant_in_Hz_K<\n                    T>::precision()));\n}\n\n// Boltzmann constant in inverse meters per kelvin\n// (69.50356 \u00b1 0.00012) m^-1 K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Boltzmann_constant_in_inverse_meters_per_kelvin,\n                              T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          Boltzmann_constant_in_inverse_meters_per_kelvin<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 Boltzmann_constant_in_inverse_meters_per_kelvin<T>::value() ==\n             static_cast<T>(69.50356));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          Boltzmann_constant_in_inverse_meters_per_kelvin<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          Boltzmann_constant_in_inverse_meters_per_kelvin<T>::uncertainty() ==\n      static_cast<T>(0.00012));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          Boltzmann_constant_in_inverse_meters_per_kelvin<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          Boltzmann_constant_in_inverse_meters_per_kelvin<T>::precision()));\n}\n\n// characteristic impedance of vacuum\n// (376.730313461 \u00b1 0.0) ohm\nBOOST_AUTO_TEST_CASE_TEMPLATE(characteristic_impedance_of_vacuum, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::characteristic_impedance_of_vacuum<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::characteristic_impedance_of_vacuum<\n                 T>::value() == static_cast<T>(376.730313461));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::characteristic_impedance_of_vacuum<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::characteristic_impedance_of_vacuum<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::characteristic_impedance_of_vacuum<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::characteristic_impedance_of_vacuum<\n          T>::precision()));\n}\n\n// classical electron radius\n// (2.8179402894e-15 \u00b1 5.8e-24) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(classical_electron_radius, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::classical_electron_radius<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::classical_electron_radius<T>::value() ==\n      static_cast<T>(2.8179402894e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::classical_electron_radius<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::classical_electron_radius<\n                 T>::uncertainty() == static_cast<T>(5.8e-24));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::classical_electron_radius<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::classical_electron_radius<\n                    T>::precision()));\n}\n\n// Compton wavelength\n// (2.4263102175e-12 \u00b1 3.3e-21) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Compton_wavelength<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Compton_wavelength<T>::value() ==\n             static_cast<T>(2.4263102175e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Compton_wavelength<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Compton_wavelength<T>::uncertainty() ==\n      static_cast<T>(3.3e-21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Compton_wavelength<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Compton_wavelength<T>::precision()));\n}\n\n// Compton wavelength over 2 pi\n// (3.8615926459e-13 \u00b1 5.3e-22) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Compton_wavelength_over_2_pi, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Compton_wavelength_over_2_pi<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Compton_wavelength_over_2_pi<\n                 T>::value() == static_cast<T>(3.8615926459e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Compton_wavelength_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Compton_wavelength_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(5.3e-22));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Compton_wavelength_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Compton_wavelength_over_2_pi<\n          T>::precision()));\n}\n\n// conductance quantum\n// (7.7480917004e-05 \u00b1 5.3e-14) S\nBOOST_AUTO_TEST_CASE_TEMPLATE(conductance_quantum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::conductance_quantum<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::conductance_quantum<T>::value() ==\n             static_cast<T>(7.7480917004e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::conductance_quantum<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::conductance_quantum<T>::uncertainty() ==\n      static_cast<T>(5.3e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::conductance_quantum<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::conductance_quantum<T>::precision()));\n}\n\n// conventional value of Josephson constant\n// (483597900000000.0 \u00b1 0.0) Hz V^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(conventional_value_of_Josephson_constant, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::conventional_value_of_Josephson_constant<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::conventional_value_of_Josephson_constant<\n          T>::value() == static_cast<T>(483597900000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::conventional_value_of_Josephson_constant<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::conventional_value_of_Josephson_constant<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::conventional_value_of_Josephson_constant<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::conventional_value_of_Josephson_constant<\n          T>::precision()));\n}\n\n// conventional value of von Klitzing constant\n// (25812.807 \u00b1 0.0) ohm\nBOOST_AUTO_TEST_CASE_TEMPLATE(conventional_value_of_von_Klitzing_constant, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          conventional_value_of_von_Klitzing_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 conventional_value_of_von_Klitzing_constant<T>::value() ==\n             static_cast<T>(25812.807));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          conventional_value_of_von_Klitzing_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          conventional_value_of_von_Klitzing_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          conventional_value_of_von_Klitzing_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          conventional_value_of_von_Klitzing_constant<T>::precision()));\n}\n\n// Cu x unit\n// (1.00207699e-13 \u00b1 2.8e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Cu_x_unit, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Cu_x_unit<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Cu_x_unit<T>::value() ==\n             static_cast<T>(1.00207699e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Cu_x_unit<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Cu_x_unit<T>::uncertainty() ==\n             static_cast<T>(2.8e-20));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Cu_x_unit<T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::Cu_x_unit<T>::precision()));\n}\n\n// deuteron-electron mag. mom. ratio\n// (-0.0004664345537 \u00b1 3.9e-12)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_electron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_electron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_electron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-0.0004664345537));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_electron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_electron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(3.9e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_electron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::deuteron_electron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// deuteron-electron mass ratio\n// (3670.4829654 \u00b1 1.6e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_electron_mass_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_electron_mass_ratio<\n                 T>::value() == static_cast<T>(3670.4829654));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_electron_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.6e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_electron_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::deuteron_electron_mass_ratio<\n          T>::precision()));\n}\n\n// deuteron g factor\n// (0.8574382308 \u00b1 7.2e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_g_factor<T>::value() ==\n             static_cast<T>(0.8574382308));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::deuteron_g_factor<T>::uncertainty() ==\n      static_cast<T>(7.2e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::deuteron_g_factor<T>::precision()));\n}\n\n// deuteron mag. mom.\n// (4.33073465e-27 \u00b1 1.1e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_mag_mom<T>::value() ==\n             static_cast<T>(4.33073465e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mag_mom<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::deuteron_mag_mom<T>::uncertainty() ==\n      static_cast<T>(1.1e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::deuteron_mag_mom<T>::precision()));\n}\n\n// deuteron mag. mom. to Bohr magneton ratio\n// (0.0004669754556 \u00b1 3.9e-12)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(0.0004669754556));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(3.9e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// deuteron mag. mom. to nuclear magneton ratio\n// (0.8574382308 \u00b1 7.2e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          deuteron_mag_mom_to_nuclear_magneton_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 deuteron_mag_mom_to_nuclear_magneton_ratio<T>::value() ==\n             static_cast<T>(0.8574382308));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          deuteron_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 deuteron_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty() ==\n             static_cast<T>(7.2e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          deuteron_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          deuteron_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n}\n\n// deuteron mass\n// (3.3435832e-27 \u00b1 1.7e-34) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::deuteron_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_mass<T>::value() ==\n             static_cast<T>(3.3435832e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_mass<T>::uncertainty() ==\n             static_cast<T>(1.7e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::deuteron_mass<T>::precision()));\n}\n\n// deuteron mass energy equivalent\n// (3.00506272e-10 \u00b1 1.5e-17) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(3.00506272e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(1.5e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::deuteron_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// deuteron mass energy equivalent in MeV\n// (1875.612793 \u00b1 4.7e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::deuteron_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(1875.612793));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::deuteron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(4.7e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::deuteron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// deuteron mass in u\n// (2.013553212724 \u00b1 7.8e-11) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_mass_in_u<T>::value() ==\n             static_cast<T>(2.013553212724));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::deuteron_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(7.8e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::deuteron_mass_in_u<T>::precision()));\n}\n\n// deuteron molar mass\n// (0.002013553212724 \u00b1 7.8e-14) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_molar_mass<T>::value() ==\n             static_cast<T>(0.002013553212724));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::deuteron_molar_mass<T>::uncertainty() ==\n      static_cast<T>(7.8e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::deuteron_molar_mass<T>::precision()));\n}\n\n// deuteron-neutron mag. mom. ratio\n// (-0.44820652 \u00b1 1.1e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_neutron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_neutron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_neutron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-0.44820652));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_neutron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_neutron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(1.1e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_neutron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::deuteron_neutron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// deuteron-proton mag. mom. ratio\n// (0.307012207 \u00b1 2.4e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_proton_mag_mom_ratio<\n                 T>::value() == static_cast<T>(0.307012207));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(2.4e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::deuteron_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// deuteron-proton mass ratio\n// (1.99900750108 \u00b1 2.2e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::deuteron_proton_mass_ratio<T>::value() ==\n      static_cast<T>(1.99900750108));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::deuteron_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.2e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::deuteron_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::deuteron_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// deuteron rms charge radius\n// (2.1402e-15 \u00b1 2.8e-18) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_rms_charge_radius, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::deuteron_rms_charge_radius<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::deuteron_rms_charge_radius<T>::value() ==\n      static_cast<T>(2.1402e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::deuteron_rms_charge_radius<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::deuteron_rms_charge_radius<\n                 T>::uncertainty() == static_cast<T>(2.8e-18));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::deuteron_rms_charge_radius<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::deuteron_rms_charge_radius<\n                    T>::precision()));\n}\n\n// electric constant\n// (8.854187817e-12 \u00b1 0.0) F m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electric_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electric_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electric_constant<T>::value() ==\n             static_cast<T>(8.854187817e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electric_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electric_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electric_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electric_constant<T>::precision()));\n}\n\n// electron charge to mass quotient\n// (-175882015000.0 \u00b1 4400.0) C kg^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_charge_to_mass_quotient, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_charge_to_mass_quotient<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_charge_to_mass_quotient<\n                 T>::value() == static_cast<T>(-175882015000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_charge_to_mass_quotient<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_charge_to_mass_quotient<\n                 T>::uncertainty() == static_cast<T>(4400.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_charge_to_mass_quotient<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_charge_to_mass_quotient<\n          T>::precision()));\n}\n\n// electron-deuteron mag. mom. ratio\n// (-2143.923498 \u00b1 1.8e-05)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_deuteron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_deuteron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_deuteron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-2143.923498));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_deuteron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_deuteron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(1.8e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_deuteron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_deuteron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron-deuteron mass ratio\n// (0.00027244371093 \u00b1 1.2e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_deuteron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_deuteron_mass_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_deuteron_mass_ratio<\n                 T>::value() == static_cast<T>(0.00027244371093));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_deuteron_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_deuteron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.2e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_deuteron_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_deuteron_mass_ratio<\n          T>::precision()));\n}\n\n// electron g factor\n// (-2.0023193043622 \u00b1 1.5e-12)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_g_factor<T>::value() ==\n             static_cast<T>(-2.0023193043622));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_g_factor<T>::uncertainty() ==\n      static_cast<T>(1.5e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_g_factor<T>::precision()));\n}\n\n// electron gyromag. ratio\n// (176085977000.0 \u00b1 4400.0) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_gyromag_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_gyromag_ratio<T>::value() ==\n      static_cast<T>(176085977000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_gyromag_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_gyromag_ratio<\n                 T>::uncertainty() == static_cast<T>(4400.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_gyromag_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_gyromag_ratio<T>::precision()));\n}\n\n// electron gyromag. ratio over 2 pi\n// (28024.95364 \u00b1 0.0007) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_gyromag_ratio_over_2_pi, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_gyromag_ratio_over_2_pi<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_gyromag_ratio_over_2_pi<\n                 T>::value() == static_cast<T>(28024.95364));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_gyromag_ratio_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_gyromag_ratio_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(0.0007));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_gyromag_ratio_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_gyromag_ratio_over_2_pi<\n          T>::precision()));\n}\n\n// electron mag. mom.\n// (-9.28476377e-24 \u00b1 2.3e-31) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_mag_mom<T>::value() ==\n             static_cast<T>(-9.28476377e-24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mag_mom<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_mag_mom<T>::uncertainty() ==\n      static_cast<T>(2.3e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_mag_mom<T>::precision()));\n}\n\n// electron mag. mom. anomaly\n// (0.00115965218111 \u00b1 7.4e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mag_mom_anomaly, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mag_mom_anomaly<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_mag_mom_anomaly<T>::value() ==\n      static_cast<T>(0.00115965218111));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_mag_mom_anomaly<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_mag_mom_anomaly<\n                 T>::uncertainty() == static_cast<T>(7.4e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_mag_mom_anomaly<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::electron_mag_mom_anomaly<\n                    T>::precision()));\n}\n\n// electron mag. mom. to Bohr magneton ratio\n// (-1.00115965218111 \u00b1 7.4e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(-1.00115965218111));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(7.4e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// electron mag. mom. to nuclear magneton ratio\n// (-1838.28197092 \u00b1 8e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          electron_mag_mom_to_nuclear_magneton_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 electron_mag_mom_to_nuclear_magneton_ratio<T>::value() ==\n             static_cast<T>(-1838.28197092));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          electron_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 electron_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty() ==\n             static_cast<T>(8e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          electron_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          electron_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n}\n\n// electron mass\n// (9.10938215e-31 \u00b1 4.5e-38) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_mass<T>::value() ==\n             static_cast<T>(9.10938215e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_mass<T>::uncertainty() ==\n             static_cast<T>(4.5e-38));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_mass<T>::precision()));\n}\n\n// electron mass energy equivalent\n// (8.18710438e-14 \u00b1 4.1e-21) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(8.18710438e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(4.1e-21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// electron mass energy equivalent in MeV\n// (0.51099891 \u00b1 1.3e-08) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(0.51099891));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(1.3e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// electron mass in u\n// (0.00054857990943 \u00b1 2.3e-13) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_mass_in_u<T>::value() ==\n             static_cast<T>(0.00054857990943));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(2.3e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_mass_in_u<T>::precision()));\n}\n\n// electron molar mass\n// (5.4857990943e-07 \u00b1 2.3e-16) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_molar_mass<T>::value() ==\n             static_cast<T>(5.4857990943e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_molar_mass<T>::uncertainty() ==\n      static_cast<T>(2.3e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_molar_mass<T>::precision()));\n}\n\n// electron-muon mag. mom. ratio\n// (206.7669877 \u00b1 5.2e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_muon_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_muon_mag_mom_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_muon_mag_mom_ratio<T>::value() ==\n      static_cast<T>(206.7669877));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_muon_mag_mom_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_muon_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(5.2e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_muon_mag_mom_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::electron_muon_mag_mom_ratio<\n                    T>::precision()));\n}\n\n// electron-muon mass ratio\n// (0.00483633171 \u00b1 1.2e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_muon_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_muon_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_muon_mass_ratio<T>::value() ==\n      static_cast<T>(0.00483633171));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_muon_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_muon_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.2e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_muon_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::electron_muon_mass_ratio<\n                    T>::precision()));\n}\n\n// electron-neutron mag. mom. ratio\n// (960.9205 \u00b1 0.00023)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_neutron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_neutron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_neutron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(960.9205));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_neutron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_neutron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(0.00023));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_neutron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_neutron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron-neutron mass ratio\n// (0.00054386734459 \u00b1 3.3e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_neutron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_neutron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_neutron_mass_ratio<T>::value() ==\n      static_cast<T>(0.00054386734459));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_neutron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_neutron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(3.3e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_neutron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::electron_neutron_mass_ratio<\n                    T>::precision()));\n}\n\n// electron-proton mag. mom. ratio\n// (-658.2106848 \u00b1 5.4e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_proton_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-658.2106848));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(5.4e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron-proton mass ratio\n// (0.00054461702177 \u00b1 2.4e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_proton_mass_ratio<T>::value() ==\n      static_cast<T>(0.00054461702177));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.4e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::electron_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// electron-tau mass ratio\n// (0.000287564 \u00b1 4.7e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_tau_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_tau_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_tau_mass_ratio<T>::value() ==\n      static_cast<T>(0.000287564));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_tau_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_tau_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(4.7e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_tau_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_tau_mass_ratio<T>::precision()));\n}\n\n// electron to alpha particle mass ratio\n// (0.00013709335557 \u00b1 5.8e-14)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_to_alpha_particle_mass_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_to_alpha_particle_mass_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_to_alpha_particle_mass_ratio<\n          T>::value() == static_cast<T>(0.00013709335557));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_to_alpha_particle_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_to_alpha_particle_mass_ratio<\n          T>::uncertainty() == static_cast<T>(5.8e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_to_alpha_particle_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_to_alpha_particle_mass_ratio<\n          T>::precision()));\n}\n\n// electron to shielded helion mag. mom. ratio\n// (864.058257 \u00b1 1e-05)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_to_shielded_helion_mag_mom_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_to_shielded_helion_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_to_shielded_helion_mag_mom_ratio<\n          T>::value() == static_cast<T>(864.058257));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_to_shielded_helion_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_to_shielded_helion_mag_mom_ratio<\n          T>::uncertainty() == static_cast<T>(1e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_to_shielded_helion_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_to_shielded_helion_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron to shielded proton mag. mom. ratio\n// (-658.2275971 \u00b1 7.2e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_to_shielded_proton_mag_mom_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_to_shielded_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_to_shielded_proton_mag_mom_ratio<\n          T>::value() == static_cast<T>(-658.2275971));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_to_shielded_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_to_shielded_proton_mag_mom_ratio<\n          T>::uncertainty() == static_cast<T>(7.2e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_to_shielded_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_to_shielded_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron volt\n// (1.602176487e-19 \u00b1 4e-27) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::electron_volt<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_volt<T>::value() ==\n             static_cast<T>(1.602176487e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_volt<T>::uncertainty() ==\n             static_cast<T>(4e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_volt<T>::precision()));\n}\n\n// electron volt-atomic mass unit relationship\n// (1.073544188e-09 \u00b1 2.7e-17) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          electron_volt_atomic_mass_unit_relationship<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 electron_volt_atomic_mass_unit_relationship<T>::value() ==\n             static_cast<T>(1.073544188e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          electron_volt_atomic_mass_unit_relationship<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          electron_volt_atomic_mass_unit_relationship<T>::uncertainty() ==\n      static_cast<T>(2.7e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          electron_volt_atomic_mass_unit_relationship<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          electron_volt_atomic_mass_unit_relationship<T>::precision()));\n}\n\n// electron volt-hartree relationship\n// (0.0367493254 \u00b1 9.2e-10) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_hartree_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_hartree_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_volt_hartree_relationship<\n                 T>::value() == static_cast<T>(0.0367493254));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_hartree_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_volt_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(9.2e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_hartree_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_volt_hartree_relationship<\n          T>::precision()));\n}\n\n// electron volt-hertz relationship\n// (241798945400000.0 \u00b1 6000000.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_hertz_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_volt_hertz_relationship<\n                 T>::value() == static_cast<T>(241798945400000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_hertz_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_volt_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(6000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_hertz_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_volt_hertz_relationship<\n          T>::precision()));\n}\n\n// electron volt-inverse meter relationship\n// (806554.465 \u00b1 0.02) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_volt_inverse_meter_relationship<\n          T>::value() == static_cast<T>(806554.465));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_volt_inverse_meter_relationship<\n          T>::uncertainty() == static_cast<T>(0.02));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_volt_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// electron volt-joule relationship\n// (1.602176487e-19 \u00b1 4e-27) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_joule_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_volt_joule_relationship<\n                 T>::value() == static_cast<T>(1.602176487e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_joule_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_volt_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(4e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_joule_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_volt_joule_relationship<\n          T>::precision()));\n}\n\n// electron volt-kelvin relationship\n// (11604.505 \u00b1 0.02) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_kelvin_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_kelvin_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_volt_kelvin_relationship<\n                 T>::value() == static_cast<T>(11604.505));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_kelvin_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::electron_volt_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(0.02));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_kelvin_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_volt_kelvin_relationship<\n          T>::precision()));\n}\n\n// electron volt-kilogram relationship\n// (1.782661758e-36 \u00b1 4.4e-44) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_kilogram_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_volt_kilogram_relationship<\n          T>::value() == static_cast<T>(1.782661758e-36));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::electron_volt_kilogram_relationship<\n          T>::uncertainty() == static_cast<T>(4.4e-44));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::electron_volt_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::electron_volt_kilogram_relationship<\n          T>::precision()));\n}\n\n// elementary charge\n// (1.602176487e-19 \u00b1 4e-27) C\nBOOST_AUTO_TEST_CASE_TEMPLATE(elementary_charge, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::elementary_charge<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::elementary_charge<T>::value() ==\n             static_cast<T>(1.602176487e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::elementary_charge<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::elementary_charge<T>::uncertainty() ==\n      static_cast<T>(4e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::elementary_charge<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::elementary_charge<T>::precision()));\n}\n\n// elementary charge over h\n// (241798945400000.0 \u00b1 6000000.0) A J^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(elementary_charge_over_h, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::elementary_charge_over_h<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::elementary_charge_over_h<T>::value() ==\n      static_cast<T>(241798945400000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::elementary_charge_over_h<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::elementary_charge_over_h<\n                 T>::uncertainty() == static_cast<T>(6000000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::elementary_charge_over_h<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::elementary_charge_over_h<\n                    T>::precision()));\n}\n\n// Faraday constant\n// (96485.3399 \u00b1 0.0024) C mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Faraday_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Faraday_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Faraday_constant<T>::value() ==\n             static_cast<T>(96485.3399));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Faraday_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Faraday_constant<T>::uncertainty() ==\n      static_cast<T>(0.0024));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Faraday_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Faraday_constant<T>::precision()));\n}\n\n// Faraday constant for conventional electric current\n// (96485.3401 \u00b1 0.0048) C_90 mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(\n    Faraday_constant_for_conventional_electric_current, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          Faraday_constant_for_conventional_electric_current<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          Faraday_constant_for_conventional_electric_current<T>::value() ==\n      static_cast<T>(96485.3401));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::\n                        Faraday_constant_for_conventional_electric_current<\n                            T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 Faraday_constant_for_conventional_electric_current<\n                     T>::uncertainty() == static_cast<T>(0.0048));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          Faraday_constant_for_conventional_electric_current<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          Faraday_constant_for_conventional_electric_current<T>::precision()));\n}\n\n// Fermi coupling constant\n// (1.16637e-05 \u00b1 1e-10) GeV^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(Fermi_coupling_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Fermi_coupling_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Fermi_coupling_constant<T>::value() ==\n      static_cast<T>(1.16637e-05));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Fermi_coupling_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Fermi_coupling_constant<\n                 T>::uncertainty() == static_cast<T>(1e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Fermi_coupling_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Fermi_coupling_constant<T>::precision()));\n}\n\n// fine-structure constant\n// (0.0072973525376 \u00b1 5e-12)\nBOOST_AUTO_TEST_CASE_TEMPLATE(fine_structure_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::fine_structure_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::fine_structure_constant<T>::value() ==\n      static_cast<T>(0.0072973525376));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::fine_structure_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::fine_structure_constant<\n                 T>::uncertainty() == static_cast<T>(5e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::fine_structure_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::fine_structure_constant<T>::precision()));\n}\n\n// first radiation constant\n// (3.74177118e-16 \u00b1 1.9e-23) W m^2\nBOOST_AUTO_TEST_CASE_TEMPLATE(first_radiation_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::first_radiation_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::first_radiation_constant<T>::value() ==\n      static_cast<T>(3.74177118e-16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::first_radiation_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::first_radiation_constant<\n                 T>::uncertainty() == static_cast<T>(1.9e-23));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::first_radiation_constant<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::first_radiation_constant<\n                    T>::precision()));\n}\n\n// first radiation constant for spectral radiance\n// (1.191042759e-16 \u00b1 5.9e-24) W m^2 sr^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(first_radiation_constant_for_spectral_radiance, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          first_radiation_constant_for_spectral_radiance<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 first_radiation_constant_for_spectral_radiance<T>::value() ==\n             static_cast<T>(1.191042759e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          first_radiation_constant_for_spectral_radiance<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          first_radiation_constant_for_spectral_radiance<T>::uncertainty() ==\n      static_cast<T>(5.9e-24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          first_radiation_constant_for_spectral_radiance<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          first_radiation_constant_for_spectral_radiance<T>::precision()));\n}\n\n// hartree-atomic mass unit relationship\n// (2.9212622986e-08 \u00b1 4.2e-17) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::hartree_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(2.9212622986e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::hartree_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(4.2e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::hartree_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// hartree-electron volt relationship\n// (27.21138386 \u00b1 6.8e-07) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::hartree_electron_volt_relationship<\n                 T>::value() == static_cast<T>(27.21138386));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::hartree_electron_volt_relationship<\n                 T>::uncertainty() == static_cast<T>(6.8e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::hartree_electron_volt_relationship<\n          T>::precision()));\n}\n\n// Hartree energy\n// (4.35974394e-18 \u00b1 2.2e-25) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(Hartree_energy, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Hartree_energy<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Hartree_energy<T>::value() ==\n             static_cast<T>(4.35974394e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Hartree_energy<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Hartree_energy<T>::uncertainty() ==\n             static_cast<T>(2.2e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Hartree_energy<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Hartree_energy<T>::precision()));\n}\n\n// Hartree energy in eV\n// (27.21138386 \u00b1 6.8e-07) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(Hartree_energy_in_eV, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Hartree_energy_in_eV<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Hartree_energy_in_eV<T>::value() ==\n             static_cast<T>(27.21138386));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Hartree_energy_in_eV<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Hartree_energy_in_eV<T>::uncertainty() ==\n      static_cast<T>(6.8e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Hartree_energy_in_eV<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Hartree_energy_in_eV<T>::precision()));\n}\n\n// hartree-hertz relationship\n// (6579683920722000.0 \u00b1 44000.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_hertz_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::hartree_hertz_relationship<T>::value() ==\n      static_cast<T>(6579683920722000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hartree_hertz_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::hartree_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(44000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hartree_hertz_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::hartree_hertz_relationship<\n                    T>::precision()));\n}\n\n// hartree-inverse meter relationship\n// (21947463.13705 \u00b1 0.00015) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::hartree_inverse_meter_relationship<\n                 T>::value() == static_cast<T>(21947463.13705));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::hartree_inverse_meter_relationship<\n                 T>::uncertainty() == static_cast<T>(0.00015));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::hartree_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// hartree-joule relationship\n// (4.35974394e-18 \u00b1 2.2e-25) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_joule_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::hartree_joule_relationship<T>::value() ==\n      static_cast<T>(4.35974394e-18));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hartree_joule_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::hartree_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(2.2e-25));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hartree_joule_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::hartree_joule_relationship<\n                    T>::precision()));\n}\n\n// hartree-kelvin relationship\n// (315774.65 \u00b1 0.55) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_kelvin_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_kelvin_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::hartree_kelvin_relationship<T>::value() ==\n      static_cast<T>(315774.65));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hartree_kelvin_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::hartree_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(0.55));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hartree_kelvin_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::hartree_kelvin_relationship<\n                    T>::precision()));\n}\n\n// hartree-kilogram relationship\n// (4.85086934e-35 \u00b1 2.4e-42) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_kilogram_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::hartree_kilogram_relationship<\n                 T>::value() == static_cast<T>(4.85086934e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::hartree_kilogram_relationship<\n                 T>::uncertainty() == static_cast<T>(2.4e-42));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hartree_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::hartree_kilogram_relationship<\n          T>::precision()));\n}\n\n// helion-electron mass ratio\n// (5495.8852765 \u00b1 5.2e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::helion_electron_mass_ratio<T>::value() ==\n      static_cast<T>(5495.8852765));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::helion_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::helion_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(5.2e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::helion_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::helion_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// helion mass\n// (5.00641192e-27 \u00b1 2.5e-34) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::helion_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::helion_mass<T>::value() ==\n             static_cast<T>(5.00641192e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::helion_mass<T>::uncertainty() ==\n             static_cast<T>(2.5e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::helion_mass<T>::precision()));\n}\n\n// helion mass energy equivalent\n// (4.49953864e-10 \u00b1 2.2e-17) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::helion_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(4.49953864e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::helion_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(2.2e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::helion_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// helion mass energy equivalent in MeV\n// (2808.391383 \u00b1 7e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::helion_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(2808.391383));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::helion_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(7e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::helion_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// helion mass in u\n// (3.0149322473 \u00b1 2.6e-09) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::helion_mass_in_u<T>::value() ==\n             static_cast<T>(3.0149322473));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::helion_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(2.6e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::helion_mass_in_u<T>::precision()));\n}\n\n// helion molar mass\n// (0.0030149322473 \u00b1 2.6e-12) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::helion_molar_mass<T>::value() ==\n             static_cast<T>(0.0030149322473));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::helion_molar_mass<T>::uncertainty() ==\n      static_cast<T>(2.6e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::helion_molar_mass<T>::precision()));\n}\n\n// helion-proton mass ratio\n// (2.9931526713 \u00b1 2.6e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::helion_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::helion_proton_mass_ratio<T>::value() ==\n      static_cast<T>(2.9931526713));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::helion_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::helion_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.6e-09));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::helion_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::helion_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// hertz-atomic mass unit relationship\n// (4.4398216294e-24 \u00b1 6.4e-33) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hertz_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::hertz_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(4.4398216294e-24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hertz_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::hertz_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(6.4e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hertz_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::hertz_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// hertz-electron volt relationship\n// (4.13566733e-15 \u00b1 1e-22) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_electron_volt_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hertz_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::hertz_electron_volt_relationship<\n                 T>::value() == static_cast<T>(4.13566733e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hertz_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::hertz_electron_volt_relationship<\n                 T>::uncertainty() == static_cast<T>(1e-22));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hertz_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::hertz_electron_volt_relationship<\n          T>::precision()));\n}\n\n// hertz-hartree relationship\n// (1.519829846006e-16 \u00b1 1e-27) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_hartree_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hertz_hartree_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::hertz_hartree_relationship<T>::value() ==\n      static_cast<T>(1.519829846006e-16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hertz_hartree_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::hertz_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(1e-27));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hertz_hartree_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::hertz_hartree_relationship<\n                    T>::precision()));\n}\n\n// hertz-inverse meter relationship\n// (3.335640951e-09 \u00b1 0.0) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_inverse_meter_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hertz_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::hertz_inverse_meter_relationship<\n                 T>::value() == static_cast<T>(3.335640951e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hertz_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::hertz_inverse_meter_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hertz_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::hertz_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// hertz-joule relationship\n// (6.62606896e-34 \u00b1 3.3e-41) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hertz_joule_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::hertz_joule_relationship<T>::value() ==\n      static_cast<T>(6.62606896e-34));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hertz_joule_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::hertz_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(3.3e-41));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hertz_joule_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::hertz_joule_relationship<\n                    T>::precision()));\n}\n\n// hertz-kelvin relationship\n// (4.7992374e-11 \u00b1 8.4e-17) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_kelvin_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hertz_kelvin_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::hertz_kelvin_relationship<T>::value() ==\n      static_cast<T>(4.7992374e-11));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hertz_kelvin_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::hertz_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(8.4e-17));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hertz_kelvin_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::hertz_kelvin_relationship<\n                    T>::precision()));\n}\n\n// hertz-kilogram relationship\n// (7.372496e-51 \u00b1 3.7e-58) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_kilogram_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::hertz_kilogram_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::hertz_kilogram_relationship<T>::value() ==\n      static_cast<T>(7.372496e-51));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hertz_kilogram_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::hertz_kilogram_relationship<\n                 T>::uncertainty() == static_cast<T>(3.7e-58));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::hertz_kilogram_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::hertz_kilogram_relationship<\n                    T>::precision()));\n}\n\n// inverse fine-structure constant\n// (137.035999679 \u00b1 9.4e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_fine_structure_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_fine_structure_constant<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::inverse_fine_structure_constant<\n                 T>::value() == static_cast<T>(137.035999679));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_fine_structure_constant<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::inverse_fine_structure_constant<\n                 T>::uncertainty() == static_cast<T>(9.4e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_fine_structure_constant<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::inverse_fine_structure_constant<\n          T>::precision()));\n}\n\n// inverse meter-atomic mass unit relationship\n// (1.3310250394e-15 \u00b1 1.9e-24) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          inverse_meter_atomic_mass_unit_relationship<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 inverse_meter_atomic_mass_unit_relationship<T>::value() ==\n             static_cast<T>(1.3310250394e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          inverse_meter_atomic_mass_unit_relationship<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          inverse_meter_atomic_mass_unit_relationship<T>::uncertainty() ==\n      static_cast<T>(1.9e-24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          inverse_meter_atomic_mass_unit_relationship<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          inverse_meter_atomic_mass_unit_relationship<T>::precision()));\n}\n\n// inverse meter-electron volt relationship\n// (1.239841875e-06 \u00b1 3.1e-14) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::inverse_meter_electron_volt_relationship<\n          T>::value() == static_cast<T>(1.239841875e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::inverse_meter_electron_volt_relationship<\n          T>::uncertainty() == static_cast<T>(3.1e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::inverse_meter_electron_volt_relationship<\n          T>::precision()));\n}\n\n// inverse meter-hartree relationship\n// (4.55633525276e-08 \u00b1 3e-19) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_hartree_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_hartree_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::inverse_meter_hartree_relationship<\n                 T>::value() == static_cast<T>(4.55633525276e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_hartree_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::inverse_meter_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(3e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_hartree_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::inverse_meter_hartree_relationship<\n          T>::precision()));\n}\n\n// inverse meter-hertz relationship\n// (299792458.0 \u00b1 0.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_hertz_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::inverse_meter_hertz_relationship<\n                 T>::value() == static_cast<T>(299792458.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_hertz_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::inverse_meter_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_hertz_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::inverse_meter_hertz_relationship<\n          T>::precision()));\n}\n\n// inverse meter-joule relationship\n// (1.986445501e-25 \u00b1 9.9e-33) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_joule_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::inverse_meter_joule_relationship<\n                 T>::value() == static_cast<T>(1.986445501e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_joule_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::inverse_meter_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(9.9e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_joule_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::inverse_meter_joule_relationship<\n          T>::precision()));\n}\n\n// inverse meter-kelvin relationship\n// (0.014387752 \u00b1 2.5e-08) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_kelvin_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_kelvin_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::inverse_meter_kelvin_relationship<\n                 T>::value() == static_cast<T>(0.014387752));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_kelvin_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::inverse_meter_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(2.5e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_kelvin_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::inverse_meter_kelvin_relationship<\n          T>::precision()));\n}\n\n// inverse meter-kilogram relationship\n// (2.2102187e-42 \u00b1 1.1e-49) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_kilogram_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::inverse_meter_kilogram_relationship<\n          T>::value() == static_cast<T>(2.2102187e-42));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::inverse_meter_kilogram_relationship<\n          T>::uncertainty() == static_cast<T>(1.1e-49));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_meter_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::inverse_meter_kilogram_relationship<\n          T>::precision()));\n}\n\n// inverse of conductance quantum\n// (12906.4037787 \u00b1 8.8e-06) ohm\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_of_conductance_quantum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_of_conductance_quantum<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::inverse_of_conductance_quantum<\n                 T>::value() == static_cast<T>(12906.4037787));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_of_conductance_quantum<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::inverse_of_conductance_quantum<\n                 T>::uncertainty() == static_cast<T>(8.8e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::inverse_of_conductance_quantum<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::inverse_of_conductance_quantum<\n          T>::precision()));\n}\n\n// Josephson constant\n// (483597891000000.0 \u00b1 12000000.0) Hz V^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Josephson_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Josephson_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Josephson_constant<T>::value() ==\n             static_cast<T>(483597891000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Josephson_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Josephson_constant<T>::uncertainty() ==\n      static_cast<T>(12000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Josephson_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Josephson_constant<T>::precision()));\n}\n\n// joule-atomic mass unit relationship\n// (6700536410.0 \u00b1 330.0) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::joule_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::joule_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(6700536410.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::joule_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::joule_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(330.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::joule_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::joule_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// joule-electron volt relationship\n// (6.24150965e+18 \u00b1 160000000000.0) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_electron_volt_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::joule_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::joule_electron_volt_relationship<\n                 T>::value() == static_cast<T>(6.24150965e+18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::joule_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::joule_electron_volt_relationship<\n                 T>::uncertainty() == static_cast<T>(160000000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::joule_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::joule_electron_volt_relationship<\n          T>::precision()));\n}\n\n// joule-hartree relationship\n// (2.29371269e+17 \u00b1 11000000000.0) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_hartree_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::joule_hartree_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::joule_hartree_relationship<T>::value() ==\n      static_cast<T>(2.29371269e+17));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::joule_hartree_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::joule_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(11000000000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::joule_hartree_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::joule_hartree_relationship<\n                    T>::precision()));\n}\n\n// joule-hertz relationship\n// (1.50919045e+33 \u00b1 7.5e+25) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::joule_hertz_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::joule_hertz_relationship<T>::value() ==\n      static_cast<T>(1.50919045e+33));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::joule_hertz_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::joule_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(7.5e+25));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::joule_hertz_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::joule_hertz_relationship<\n                    T>::precision()));\n}\n\n// joule-inverse meter relationship\n// (5.03411747e+24 \u00b1 2.5e+17) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_inverse_meter_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::joule_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::joule_inverse_meter_relationship<\n                 T>::value() == static_cast<T>(5.03411747e+24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::joule_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::joule_inverse_meter_relationship<\n                 T>::uncertainty() == static_cast<T>(2.5e+17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::joule_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::joule_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// joule-kelvin relationship\n// (7.242963e+22 \u00b1 1.3e+17) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_kelvin_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::joule_kelvin_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::joule_kelvin_relationship<T>::value() ==\n      static_cast<T>(7.242963e+22));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::joule_kelvin_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::joule_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(1.3e+17));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::joule_kelvin_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::joule_kelvin_relationship<\n                    T>::precision()));\n}\n\n// joule-kilogram relationship\n// (1.112650056e-17 \u00b1 0.0) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_kilogram_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::joule_kilogram_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::joule_kilogram_relationship<T>::value() ==\n      static_cast<T>(1.112650056e-17));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::joule_kilogram_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::joule_kilogram_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::joule_kilogram_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::joule_kilogram_relationship<\n                    T>::precision()));\n}\n\n// kelvin-atomic mass unit relationship\n// (9.251098e-14 \u00b1 1.6e-19) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::kelvin_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(9.251098e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::kelvin_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(1.6e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::kelvin_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// kelvin-electron volt relationship\n// (8.617343e-05 \u00b1 1.5e-10) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::kelvin_electron_volt_relationship<\n                 T>::value() == static_cast<T>(8.617343e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::kelvin_electron_volt_relationship<\n                 T>::uncertainty() == static_cast<T>(1.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::kelvin_electron_volt_relationship<\n          T>::precision()));\n}\n\n// kelvin-hartree relationship\n// (3.1668153e-06 \u00b1 5.5e-12) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_hartree_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_hartree_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::kelvin_hartree_relationship<T>::value() ==\n      static_cast<T>(3.1668153e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::kelvin_hartree_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::kelvin_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(5.5e-12));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::kelvin_hartree_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::kelvin_hartree_relationship<\n                    T>::precision()));\n}\n\n// kelvin-hertz relationship\n// (20836644000.0 \u00b1 36000.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_hertz_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::kelvin_hertz_relationship<T>::value() ==\n      static_cast<T>(20836644000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::kelvin_hertz_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::kelvin_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(36000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::kelvin_hertz_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::kelvin_hertz_relationship<\n                    T>::precision()));\n}\n\n// kelvin-inverse meter relationship\n// (69.50356 \u00b1 0.00012) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::kelvin_inverse_meter_relationship<\n                 T>::value() == static_cast<T>(69.50356));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::kelvin_inverse_meter_relationship<\n                 T>::uncertainty() == static_cast<T>(0.00012));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::kelvin_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// kelvin-joule relationship\n// (1.3806504e-23 \u00b1 2.4e-29) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_joule_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::kelvin_joule_relationship<T>::value() ==\n      static_cast<T>(1.3806504e-23));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::kelvin_joule_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::kelvin_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(2.4e-29));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::kelvin_joule_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::kelvin_joule_relationship<\n                    T>::precision()));\n}\n\n// kelvin-kilogram relationship\n// (1.5361807e-40 \u00b1 2.7e-46) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_kilogram_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::kelvin_kilogram_relationship<\n                 T>::value() == static_cast<T>(1.5361807e-40));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::kelvin_kilogram_relationship<\n                 T>::uncertainty() == static_cast<T>(2.7e-46));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kelvin_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::kelvin_kilogram_relationship<\n          T>::precision()));\n}\n\n// kilogram-atomic mass unit relationship\n// (6.02214179e+26 \u00b1 3e+19) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::kilogram_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(6.02214179e+26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::kilogram_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(3e+19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::kilogram_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// kilogram-electron volt relationship\n// (5.60958912e+35 \u00b1 1.4e+28) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::kilogram_electron_volt_relationship<\n          T>::value() == static_cast<T>(5.60958912e+35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::kilogram_electron_volt_relationship<\n          T>::uncertainty() == static_cast<T>(1.4e+28));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::kilogram_electron_volt_relationship<\n          T>::precision()));\n}\n\n// kilogram-hartree relationship\n// (2.06148616e+34 \u00b1 1e+27) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_hartree_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_hartree_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::kilogram_hartree_relationship<\n                 T>::value() == static_cast<T>(2.06148616e+34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_hartree_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::kilogram_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(1e+27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_hartree_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::kilogram_hartree_relationship<\n          T>::precision()));\n}\n\n// kilogram-hertz relationship\n// (1.356392733e+50 \u00b1 6.8e+42) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_hertz_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::kilogram_hertz_relationship<T>::value() ==\n      static_cast<T>(1.356392733e+50));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::kilogram_hertz_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::kilogram_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(6.8e+42));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::kilogram_hertz_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::kilogram_hertz_relationship<\n                    T>::precision()));\n}\n\n// kilogram-inverse meter relationship\n// (4.52443915e+41 \u00b1 2.3e+34) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::kilogram_inverse_meter_relationship<\n          T>::value() == static_cast<T>(4.52443915e+41));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::kilogram_inverse_meter_relationship<\n          T>::uncertainty() == static_cast<T>(2.3e+34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::kilogram_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// kilogram-joule relationship\n// (8.987551787e+16 \u00b1 0.0) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_joule_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::kilogram_joule_relationship<T>::value() ==\n      static_cast<T>(8.987551787e+16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::kilogram_joule_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::kilogram_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::kilogram_joule_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::kilogram_joule_relationship<\n                    T>::precision()));\n}\n\n// kilogram-kelvin relationship\n// (6.509651e+39 \u00b1 1.1e+34) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_kelvin_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_kelvin_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::kilogram_kelvin_relationship<\n                 T>::value() == static_cast<T>(6.509651e+39));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_kelvin_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::kilogram_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(1.1e+34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::kilogram_kelvin_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::kilogram_kelvin_relationship<\n          T>::precision()));\n}\n\n// lattice parameter of silicon\n// (5.43102064e-10 \u00b1 1.4e-17) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(lattice_parameter_of_silicon, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::lattice_parameter_of_silicon<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::lattice_parameter_of_silicon<\n                 T>::value() == static_cast<T>(5.43102064e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::lattice_parameter_of_silicon<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::lattice_parameter_of_silicon<\n                 T>::uncertainty() == static_cast<T>(1.4e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::lattice_parameter_of_silicon<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::lattice_parameter_of_silicon<\n          T>::precision()));\n}\n\n// Loschmidt constant (273.15 K, 101.325 kPa)\n// (2.6867774e+25 \u00b1 4.7e+19) m^-3\nBOOST_AUTO_TEST_CASE_TEMPLATE(Loschmidt_constant_27315_K_101325_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Loschmidt_constant_27315_K_101325_kPa<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Loschmidt_constant_27315_K_101325_kPa<\n          T>::value() == static_cast<T>(2.6867774e+25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Loschmidt_constant_27315_K_101325_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Loschmidt_constant_27315_K_101325_kPa<\n          T>::uncertainty() == static_cast<T>(4.7e+19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Loschmidt_constant_27315_K_101325_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Loschmidt_constant_27315_K_101325_kPa<\n          T>::precision()));\n}\n\n// mag. constant\n// (1.2566370614e-06 \u00b1 0.0) N A^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(mag_constant, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::mag_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::mag_constant<T>::value() ==\n             static_cast<T>(1.2566370614e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::mag_constant<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::mag_constant<T>::uncertainty() ==\n             static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::mag_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::mag_constant<T>::precision()));\n}\n\n// mag. flux quantum\n// (2.067833667e-15 \u00b1 5.2e-23) Wb\nBOOST_AUTO_TEST_CASE_TEMPLATE(mag_flux_quantum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::mag_flux_quantum<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::mag_flux_quantum<T>::value() ==\n             static_cast<T>(2.067833667e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::mag_flux_quantum<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::mag_flux_quantum<T>::uncertainty() ==\n      static_cast<T>(5.2e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::mag_flux_quantum<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::mag_flux_quantum<T>::precision()));\n}\n\n// molar gas constant\n// (8.314472 \u00b1 1.5e-05) J mol^-1 K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_gas_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_gas_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::molar_gas_constant<T>::value() ==\n             static_cast<T>(8.314472));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_gas_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::molar_gas_constant<T>::uncertainty() ==\n      static_cast<T>(1.5e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_gas_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::molar_gas_constant<T>::precision()));\n}\n\n// molar mass constant\n// (0.001 \u00b1 0.0) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_mass_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_mass_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::molar_mass_constant<T>::value() ==\n             static_cast<T>(0.001));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_mass_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::molar_mass_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_mass_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::molar_mass_constant<T>::precision()));\n}\n\n// molar mass of carbon-12\n// (0.012 \u00b1 0.0) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_mass_of_carbon_12, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_mass_of_carbon_12<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::molar_mass_of_carbon_12<T>::value() ==\n      static_cast<T>(0.012));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::molar_mass_of_carbon_12<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::molar_mass_of_carbon_12<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_mass_of_carbon_12<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::molar_mass_of_carbon_12<T>::precision()));\n}\n\n// molar Planck constant\n// (3.9903126821e-10 \u00b1 5.7e-19) J s mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_Planck_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_Planck_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::molar_Planck_constant<T>::value() ==\n      static_cast<T>(3.9903126821e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_Planck_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::molar_Planck_constant<T>::uncertainty() ==\n      static_cast<T>(5.7e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_Planck_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::molar_Planck_constant<T>::precision()));\n}\n\n// molar Planck constant times c\n// (0.11962656472 \u00b1 1.7e-10) J m mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_Planck_constant_times_c, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_Planck_constant_times_c<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::molar_Planck_constant_times_c<\n                 T>::value() == static_cast<T>(0.11962656472));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_Planck_constant_times_c<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::molar_Planck_constant_times_c<\n                 T>::uncertainty() == static_cast<T>(1.7e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_Planck_constant_times_c<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::molar_Planck_constant_times_c<\n          T>::precision()));\n}\n\n// molar volume of ideal gas (273.15 K, 100 kPa)\n// (0.022710981 \u00b1 4e-08) m^3 mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_volume_of_ideal_gas_27315_K_100_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::value() == static_cast<T>(0.022710981));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::uncertainty() == static_cast<T>(4e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::precision()));\n}\n\n// molar volume of ideal gas (273.15 K, 101.325 kPa)\n// (0.022413996 \u00b1 3.9e-08) m^3 mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_volume_of_ideal_gas_27315_K_101325_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::value() ==\n             static_cast<T>(0.022413996));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::uncertainty() ==\n      static_cast<T>(3.9e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::precision()));\n}\n\n// molar volume of silicon\n// (1.20588349e-05 \u00b1 1.1e-12) m^3 mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_volume_of_silicon, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_volume_of_silicon<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::molar_volume_of_silicon<T>::value() ==\n      static_cast<T>(1.20588349e-05));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::molar_volume_of_silicon<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::molar_volume_of_silicon<\n                 T>::uncertainty() == static_cast<T>(1.1e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::molar_volume_of_silicon<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::molar_volume_of_silicon<T>::precision()));\n}\n\n// Mo x unit\n// (1.00209955e-13 \u00b1 5.3e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Mo_x_unit, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Mo_x_unit<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Mo_x_unit<T>::value() ==\n             static_cast<T>(1.00209955e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Mo_x_unit<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Mo_x_unit<T>::uncertainty() ==\n             static_cast<T>(5.3e-20));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Mo_x_unit<T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::Mo_x_unit<T>::precision()));\n}\n\n// muon Compton wavelength\n// (1.173444104e-14 \u00b1 3e-22) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_Compton_wavelength<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::muon_Compton_wavelength<T>::value() ==\n      static_cast<T>(1.173444104e-14));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::muon_Compton_wavelength<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(3e-22));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_Compton_wavelength<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::muon_Compton_wavelength<T>::precision()));\n}\n\n// muon Compton wavelength over 2 pi\n// (1.867594295e-15 \u00b1 4.7e-23) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_Compton_wavelength_over_2_pi, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_Compton_wavelength_over_2_pi<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_Compton_wavelength_over_2_pi<\n                 T>::value() == static_cast<T>(1.867594295e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_Compton_wavelength_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_Compton_wavelength_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(4.7e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_Compton_wavelength_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::muon_Compton_wavelength_over_2_pi<\n          T>::precision()));\n}\n\n// muon-electron mass ratio\n// (206.7682823 \u00b1 5.2e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::muon_electron_mass_ratio<T>::value() ==\n      static_cast<T>(206.7682823));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::muon_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(5.2e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::muon_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::muon_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// muon g factor\n// (-2.0023318414 \u00b1 1.2e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_g_factor, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::muon_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_g_factor<T>::value() ==\n             static_cast<T>(-2.0023318414));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_g_factor<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_g_factor<T>::uncertainty() ==\n             static_cast<T>(1.2e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::muon_g_factor<T>::precision()));\n}\n\n// muon mag. mom.\n// (-4.49044786e-26 \u00b1 1.6e-33) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mag_mom, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::muon_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_mag_mom<T>::value() ==\n             static_cast<T>(-4.49044786e-26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mag_mom<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_mag_mom<T>::uncertainty() ==\n             static_cast<T>(1.6e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::muon_mag_mom<T>::precision()));\n}\n\n// muon mag. mom. anomaly\n// (0.00116592069 \u00b1 6e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mag_mom_anomaly, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mag_mom_anomaly<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_mag_mom_anomaly<T>::value() ==\n             static_cast<T>(0.00116592069));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mag_mom_anomaly<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::muon_mag_mom_anomaly<T>::uncertainty() ==\n      static_cast<T>(6e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mag_mom_anomaly<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::muon_mag_mom_anomaly<T>::precision()));\n}\n\n// muon mag. mom. to Bohr magneton ratio\n// (-0.00484197049 \u00b1 1.2e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(-0.00484197049));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(1.2e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// muon mag. mom. to nuclear magneton ratio\n// (-8.89059705 \u00b1 2.3e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(-8.89059705));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(2.3e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// muon mass\n// (1.8835313e-28 \u00b1 1.1e-35) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::muon_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_mass<T>::value() ==\n             static_cast<T>(1.8835313e-28));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_mass<T>::uncertainty() ==\n             static_cast<T>(1.1e-35));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::muon_mass<T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::muon_mass<T>::precision()));\n}\n\n// muon mass energy equivalent\n// (1.69283351e-11 \u00b1 9.5e-19) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mass_energy_equivalent<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::muon_mass_energy_equivalent<T>::value() ==\n      static_cast<T>(1.69283351e-11));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::muon_mass_energy_equivalent<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(9.5e-19));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::muon_mass_energy_equivalent<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::muon_mass_energy_equivalent<\n                    T>::precision()));\n}\n\n// muon mass energy equivalent in MeV\n// (105.6583668 \u00b1 3.8e-06) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_mass_energy_equivalent_in_MeV<\n                 T>::value() == static_cast<T>(105.6583668));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_mass_energy_equivalent_in_MeV<\n                 T>::uncertainty() == static_cast<T>(3.8e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::muon_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// muon mass in u\n// (0.1134289256 \u00b1 2.9e-09) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_mass_in_u<T>::value() ==\n             static_cast<T>(0.1134289256));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_mass_in_u<T>::uncertainty() ==\n             static_cast<T>(2.9e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::muon_mass_in_u<T>::precision()));\n}\n\n// muon molar mass\n// (0.0001134289256 \u00b1 2.9e-12) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_molar_mass<T>::value() ==\n             static_cast<T>(0.0001134289256));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::muon_molar_mass<T>::uncertainty() ==\n      static_cast<T>(2.9e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::muon_molar_mass<T>::precision()));\n}\n\n// muon-neutron mass ratio\n// (0.1124545167 \u00b1 2.9e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_neutron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_neutron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::muon_neutron_mass_ratio<T>::value() ==\n      static_cast<T>(0.1124545167));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::muon_neutron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_neutron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.9e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_neutron_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::muon_neutron_mass_ratio<T>::precision()));\n}\n\n// muon-proton mag. mom. ratio\n// (-3.183345137 \u00b1 8.5e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_proton_mag_mom_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::muon_proton_mag_mom_ratio<T>::value() ==\n      static_cast<T>(-3.183345137));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::muon_proton_mag_mom_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(8.5e-08));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::muon_proton_mag_mom_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::muon_proton_mag_mom_ratio<\n                    T>::precision()));\n}\n\n// muon-proton mass ratio\n// (0.1126095261 \u00b1 2.9e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::muon_proton_mass_ratio<T>::value() ==\n      static_cast<T>(0.1126095261));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::muon_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.9e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_proton_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::muon_proton_mass_ratio<T>::precision()));\n}\n\n// muon-tau mass ratio\n// (0.0594592 \u00b1 9.7e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_tau_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_tau_mass_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::muon_tau_mass_ratio<T>::value() ==\n             static_cast<T>(0.0594592));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_tau_mass_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::muon_tau_mass_ratio<T>::uncertainty() ==\n      static_cast<T>(9.7e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::muon_tau_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::muon_tau_mass_ratio<T>::precision()));\n}\n\n// natural unit of action\n// (1.054571628e-34 \u00b1 5.3e-42) J s\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_action, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_action<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::natural_unit_of_action<T>::value() ==\n      static_cast<T>(1.054571628e-34));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::natural_unit_of_action<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::natural_unit_of_action<\n                 T>::uncertainty() == static_cast<T>(5.3e-42));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_action<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::natural_unit_of_action<T>::precision()));\n}\n\n// natural unit of action in eV s\n// (6.58211899e-16 \u00b1 1.6e-23) eV s\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_action_in_eV_s, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_action_in_eV_s<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::natural_unit_of_action_in_eV_s<\n                 T>::value() == static_cast<T>(6.58211899e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_action_in_eV_s<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::natural_unit_of_action_in_eV_s<\n                 T>::uncertainty() == static_cast<T>(1.6e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_action_in_eV_s<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::natural_unit_of_action_in_eV_s<\n          T>::precision()));\n}\n\n// natural unit of energy\n// (8.18710438e-14 \u00b1 4.1e-21) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_energy, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_energy<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::natural_unit_of_energy<T>::value() ==\n      static_cast<T>(8.18710438e-14));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::natural_unit_of_energy<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::natural_unit_of_energy<\n                 T>::uncertainty() == static_cast<T>(4.1e-21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_energy<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::natural_unit_of_energy<T>::precision()));\n}\n\n// natural unit of energy in MeV\n// (0.51099891 \u00b1 1.3e-08) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_energy_in_MeV, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_energy_in_MeV<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::natural_unit_of_energy_in_MeV<\n                 T>::value() == static_cast<T>(0.51099891));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_energy_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::natural_unit_of_energy_in_MeV<\n                 T>::uncertainty() == static_cast<T>(1.3e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_energy_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::natural_unit_of_energy_in_MeV<\n          T>::precision()));\n}\n\n// natural unit of length\n// (3.8615926459e-13 \u00b1 5.3e-22) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_length, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_length<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::natural_unit_of_length<T>::value() ==\n      static_cast<T>(3.8615926459e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::natural_unit_of_length<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::natural_unit_of_length<\n                 T>::uncertainty() == static_cast<T>(5.3e-22));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_length<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::natural_unit_of_length<T>::precision()));\n}\n\n// natural unit of mass\n// (9.10938215e-31 \u00b1 4.5e-38) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::natural_unit_of_mass<T>::value() ==\n             static_cast<T>(9.10938215e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::natural_unit_of_mass<T>::uncertainty() ==\n      static_cast<T>(4.5e-38));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::natural_unit_of_mass<T>::precision()));\n}\n\n// natural unit of momentum\n// (2.73092406e-22 \u00b1 1.4e-29) kg m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_momentum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_momentum<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::natural_unit_of_momentum<T>::value() ==\n      static_cast<T>(2.73092406e-22));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::natural_unit_of_momentum<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::natural_unit_of_momentum<\n                 T>::uncertainty() == static_cast<T>(1.4e-29));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::natural_unit_of_momentum<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::natural_unit_of_momentum<\n                    T>::precision()));\n}\n\n// natural unit of momentum in MeV/c\n// (0.51099891 \u00b1 1.3e-08) MeV/c\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_momentum_in_MeV_c, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_momentum_in_MeV_c<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::natural_unit_of_momentum_in_MeV_c<\n                 T>::value() == static_cast<T>(0.51099891));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_momentum_in_MeV_c<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::natural_unit_of_momentum_in_MeV_c<\n                 T>::uncertainty() == static_cast<T>(1.3e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_momentum_in_MeV_c<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::natural_unit_of_momentum_in_MeV_c<\n          T>::precision()));\n}\n\n// natural unit of time\n// (1.288088657e-21 \u00b1 1.8e-30) s\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_time, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_time<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::natural_unit_of_time<T>::value() ==\n             static_cast<T>(1.288088657e-21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_time<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::natural_unit_of_time<T>::uncertainty() ==\n      static_cast<T>(1.8e-30));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_time<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::natural_unit_of_time<T>::precision()));\n}\n\n// natural unit of velocity\n// (299792458.0 \u00b1 0.0) m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_velocity, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::natural_unit_of_velocity<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::natural_unit_of_velocity<T>::value() ==\n      static_cast<T>(299792458.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::natural_unit_of_velocity<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::natural_unit_of_velocity<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::natural_unit_of_velocity<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::natural_unit_of_velocity<\n                    T>::precision()));\n}\n\n// neutron Compton wavelength\n// (1.3195908951e-15 \u00b1 2e-24) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_Compton_wavelength<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_Compton_wavelength<T>::value() ==\n      static_cast<T>(1.3195908951e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::neutron_Compton_wavelength<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(2e-24));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::neutron_Compton_wavelength<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::neutron_Compton_wavelength<\n                    T>::precision()));\n}\n\n// neutron Compton wavelength over 2 pi\n// (2.1001941382e-16 \u00b1 3.1e-25) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_Compton_wavelength_over_2_pi, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_Compton_wavelength_over_2_pi<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_Compton_wavelength_over_2_pi<\n          T>::value() == static_cast<T>(2.1001941382e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_Compton_wavelength_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_Compton_wavelength_over_2_pi<\n          T>::uncertainty() == static_cast<T>(3.1e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_Compton_wavelength_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_Compton_wavelength_over_2_pi<\n          T>::precision()));\n}\n\n// neutron-electron mag. mom. ratio\n// (0.00104066882 \u00b1 2.5e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_electron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_electron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_electron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(0.00104066882));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_electron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_electron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(2.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_electron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_electron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// neutron-electron mass ratio\n// (1838.6836605 \u00b1 1.1e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_electron_mass_ratio<T>::value() ==\n      static_cast<T>(1838.6836605));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::neutron_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.1e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::neutron_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::neutron_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// neutron g factor\n// (-3.82608545 \u00b1 9e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_g_factor<T>::value() ==\n             static_cast<T>(-3.82608545));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_g_factor<T>::uncertainty() ==\n      static_cast<T>(9e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_g_factor<T>::precision()));\n}\n\n// neutron gyromag. ratio\n// (183247185.0 \u00b1 43.0) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_gyromag_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_gyromag_ratio<T>::value() ==\n      static_cast<T>(183247185.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_gyromag_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_gyromag_ratio<T>::uncertainty() ==\n      static_cast<T>(43.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_gyromag_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_gyromag_ratio<T>::precision()));\n}\n\n// neutron gyromag. ratio over 2 pi\n// (29.1646954 \u00b1 6.9e-06) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_gyromag_ratio_over_2_pi, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_gyromag_ratio_over_2_pi<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_gyromag_ratio_over_2_pi<\n                 T>::value() == static_cast<T>(29.1646954));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_gyromag_ratio_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_gyromag_ratio_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(6.9e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_gyromag_ratio_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_gyromag_ratio_over_2_pi<\n          T>::precision()));\n}\n\n// neutron mag. mom.\n// (-9.6623641e-27 \u00b1 2.3e-33) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_mag_mom<T>::value() ==\n             static_cast<T>(-9.6623641e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mag_mom<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_mag_mom<T>::uncertainty() ==\n      static_cast<T>(2.3e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_mag_mom<T>::precision()));\n}\n\n// neutron mag. mom. to Bohr magneton ratio\n// (-0.00104187563 \u00b1 2.5e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(-0.00104187563));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(2.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// neutron mag. mom. to nuclear magneton ratio\n// (-1.91304273 \u00b1 4.5e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(-1.91304273));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(4.5e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// neutron mass\n// (1.674927211e-27 \u00b1 8.4e-35) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::neutron_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_mass<T>::value() ==\n             static_cast<T>(1.674927211e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_mass<T>::uncertainty() ==\n             static_cast<T>(8.4e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_mass<T>::precision()));\n}\n\n// neutron mass energy equivalent\n// (1.505349505e-10 \u00b1 7.5e-18) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(1.505349505e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(7.5e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// neutron mass energy equivalent in MeV\n// (939.565346 \u00b1 2.3e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(939.565346));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(2.3e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// neutron mass in u\n// (1.00866491597 \u00b1 4.3e-10) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_mass_in_u<T>::value() ==\n             static_cast<T>(1.00866491597));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(4.3e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_mass_in_u<T>::precision()));\n}\n\n// neutron molar mass\n// (0.00100866491597 \u00b1 4.3e-13) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_molar_mass<T>::value() ==\n             static_cast<T>(0.00100866491597));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_molar_mass<T>::uncertainty() ==\n      static_cast<T>(4.3e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_molar_mass<T>::precision()));\n}\n\n// neutron-muon mass ratio\n// (8.89248409 \u00b1 2.3e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_muon_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_muon_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_muon_mass_ratio<T>::value() ==\n      static_cast<T>(8.89248409));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::neutron_muon_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_muon_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.3e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_muon_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_muon_mass_ratio<T>::precision()));\n}\n\n// neutron-proton mag. mom. ratio\n// (-0.68497934 \u00b1 1.6e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_proton_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-0.68497934));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(1.6e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// neutron-proton mass ratio\n// (1.00137841918 \u00b1 4.6e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_proton_mass_ratio<T>::value() ==\n      static_cast<T>(1.00137841918));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::neutron_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(4.6e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::neutron_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::neutron_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// neutron-tau mass ratio\n// (0.52874 \u00b1 8.6e-05)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_tau_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_tau_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_tau_mass_ratio<T>::value() ==\n      static_cast<T>(0.52874));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::neutron_tau_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::neutron_tau_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(8.6e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_tau_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_tau_mass_ratio<T>::precision()));\n}\n\n// neutron to shielded proton mag. mom. ratio\n// (-0.68499694 \u00b1 1.6e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_to_shielded_proton_mag_mom_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::value() == static_cast<T>(-0.68499694));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::uncertainty() == static_cast<T>(1.6e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// Newtonian constant of gravitation\n// (6.67428e-11 \u00b1 6.7e-15) m^3 kg^-1 s^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(Newtonian_constant_of_gravitation, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Newtonian_constant_of_gravitation<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Newtonian_constant_of_gravitation<\n                 T>::value() == static_cast<T>(6.67428e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Newtonian_constant_of_gravitation<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Newtonian_constant_of_gravitation<\n                 T>::uncertainty() == static_cast<T>(6.7e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Newtonian_constant_of_gravitation<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Newtonian_constant_of_gravitation<\n          T>::precision()));\n}\n\n// Newtonian constant of gravitation over h-bar c\n// (6.70881e-39 \u00b1 6.7e-43) (GeV/c^2)^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(Newtonian_constant_of_gravitation_over_h_bar_c, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 Newtonian_constant_of_gravitation_over_h_bar_c<T>::value() ==\n             static_cast<T>(6.70881e-39));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::uncertainty() ==\n      static_cast<T>(6.7e-43));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::precision()));\n}\n\n// nuclear magneton\n// (5.05078324e-27 \u00b1 1.3e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::nuclear_magneton<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::nuclear_magneton<T>::value() ==\n             static_cast<T>(5.05078324e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::nuclear_magneton<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::nuclear_magneton<T>::uncertainty() ==\n      static_cast<T>(1.3e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::nuclear_magneton<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::nuclear_magneton<T>::precision()));\n}\n\n// nuclear magneton in eV/T\n// (3.1524512326e-08 \u00b1 4.5e-17) eV T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton_in_eV_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::nuclear_magneton_in_eV_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::nuclear_magneton_in_eV_T<T>::value() ==\n      static_cast<T>(3.1524512326e-08));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::nuclear_magneton_in_eV_T<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::nuclear_magneton_in_eV_T<\n                 T>::uncertainty() == static_cast<T>(4.5e-17));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::nuclear_magneton_in_eV_T<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::nuclear_magneton_in_eV_T<\n                    T>::precision()));\n}\n\n// nuclear magneton in inverse meters per tesla\n// (0.02542623616 \u00b1 6.4e-10) m^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton_in_inverse_meters_per_tesla, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          nuclear_magneton_in_inverse_meters_per_tesla<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 nuclear_magneton_in_inverse_meters_per_tesla<T>::value() ==\n             static_cast<T>(0.02542623616));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          nuclear_magneton_in_inverse_meters_per_tesla<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          nuclear_magneton_in_inverse_meters_per_tesla<T>::uncertainty() ==\n      static_cast<T>(6.4e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          nuclear_magneton_in_inverse_meters_per_tesla<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          nuclear_magneton_in_inverse_meters_per_tesla<T>::precision()));\n}\n\n// nuclear magneton in K/T\n// (0.00036582637 \u00b1 6.4e-10) K T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton_in_K_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::nuclear_magneton_in_K_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::nuclear_magneton_in_K_T<T>::value() ==\n      static_cast<T>(0.00036582637));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::nuclear_magneton_in_K_T<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::nuclear_magneton_in_K_T<\n                 T>::uncertainty() == static_cast<T>(6.4e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::nuclear_magneton_in_K_T<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::nuclear_magneton_in_K_T<T>::precision()));\n}\n\n// nuclear magneton in MHz/T\n// (7.62259384 \u00b1 1.9e-07) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton_in_MHz_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::nuclear_magneton_in_MHz_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::nuclear_magneton_in_MHz_T<T>::value() ==\n      static_cast<T>(7.62259384));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::nuclear_magneton_in_MHz_T<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::nuclear_magneton_in_MHz_T<\n                 T>::uncertainty() == static_cast<T>(1.9e-07));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::nuclear_magneton_in_MHz_T<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::nuclear_magneton_in_MHz_T<\n                    T>::precision()));\n}\n\n// Planck constant\n// (6.62606896e-34 \u00b1 3.3e-41) J s\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Planck_constant<T>::value() ==\n             static_cast<T>(6.62606896e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Planck_constant<T>::uncertainty() ==\n      static_cast<T>(3.3e-41));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Planck_constant<T>::precision()));\n}\n\n// Planck constant in eV s\n// (4.13566733e-15 \u00b1 1e-22) eV s\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_constant_in_eV_s, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_constant_in_eV_s<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Planck_constant_in_eV_s<T>::value() ==\n      static_cast<T>(4.13566733e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Planck_constant_in_eV_s<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Planck_constant_in_eV_s<\n                 T>::uncertainty() == static_cast<T>(1e-22));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_constant_in_eV_s<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Planck_constant_in_eV_s<T>::precision()));\n}\n\n// Planck constant over 2 pi\n// (1.054571628e-34 \u00b1 5.3e-42) J s\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_constant_over_2_pi, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_constant_over_2_pi<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Planck_constant_over_2_pi<T>::value() ==\n      static_cast<T>(1.054571628e-34));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Planck_constant_over_2_pi<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Planck_constant_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(5.3e-42));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Planck_constant_over_2_pi<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::Planck_constant_over_2_pi<\n                    T>::precision()));\n}\n\n// Planck constant over 2 pi in eV s\n// (6.58211899e-16 \u00b1 1.6e-23) eV s\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_constant_over_2_pi_in_eV_s, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_constant_over_2_pi_in_eV_s<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Planck_constant_over_2_pi_in_eV_s<\n                 T>::value() == static_cast<T>(6.58211899e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_constant_over_2_pi_in_eV_s<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Planck_constant_over_2_pi_in_eV_s<\n                 T>::uncertainty() == static_cast<T>(1.6e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_constant_over_2_pi_in_eV_s<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Planck_constant_over_2_pi_in_eV_s<\n          T>::precision()));\n}\n\n// Planck constant over 2 pi times c in MeV fm\n// (197.3269631 \u00b1 4.9e-06) MeV fm\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_constant_over_2_pi_times_c_in_MeV_fm, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          Planck_constant_over_2_pi_times_c_in_MeV_fm<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 Planck_constant_over_2_pi_times_c_in_MeV_fm<T>::value() ==\n             static_cast<T>(197.3269631));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          Planck_constant_over_2_pi_times_c_in_MeV_fm<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          Planck_constant_over_2_pi_times_c_in_MeV_fm<T>::uncertainty() ==\n      static_cast<T>(4.9e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          Planck_constant_over_2_pi_times_c_in_MeV_fm<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          Planck_constant_over_2_pi_times_c_in_MeV_fm<T>::precision()));\n}\n\n// Planck length\n// (1.616252e-35 \u00b1 8.1e-40) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_length, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Planck_length<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Planck_length<T>::value() ==\n             static_cast<T>(1.616252e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_length<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Planck_length<T>::uncertainty() ==\n             static_cast<T>(8.1e-40));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_length<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Planck_length<T>::precision()));\n}\n\n// Planck mass\n// (2.17644e-08 \u00b1 1.1e-12) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Planck_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Planck_mass<T>::value() ==\n             static_cast<T>(2.17644e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Planck_mass<T>::uncertainty() ==\n             static_cast<T>(1.1e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Planck_mass<T>::precision()));\n}\n\n// Planck mass energy equivalent in GeV\n// (1.220892e+19 \u00b1 610000000000000.0) GeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_mass_energy_equivalent_in_GeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_mass_energy_equivalent_in_GeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Planck_mass_energy_equivalent_in_GeV<\n          T>::value() == static_cast<T>(1.220892e+19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_mass_energy_equivalent_in_GeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Planck_mass_energy_equivalent_in_GeV<\n          T>::uncertainty() == static_cast<T>(610000000000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_mass_energy_equivalent_in_GeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Planck_mass_energy_equivalent_in_GeV<\n          T>::precision()));\n}\n\n// Planck temperature\n// (1.416785e+32 \u00b1 7.1e+27) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_temperature, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_temperature<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Planck_temperature<T>::value() ==\n             static_cast<T>(1.416785e+32));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_temperature<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Planck_temperature<T>::uncertainty() ==\n      static_cast<T>(7.1e+27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_temperature<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Planck_temperature<T>::precision()));\n}\n\n// Planck time\n// (5.39124e-44 \u00b1 2.7e-48) s\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_time, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Planck_time<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Planck_time<T>::value() ==\n             static_cast<T>(5.39124e-44));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_time<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Planck_time<T>::uncertainty() ==\n             static_cast<T>(2.7e-48));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Planck_time<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Planck_time<T>::precision()));\n}\n\n// proton charge to mass quotient\n// (95788339.2 \u00b1 2.4) C kg^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_charge_to_mass_quotient, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_charge_to_mass_quotient<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_charge_to_mass_quotient<\n                 T>::value() == static_cast<T>(95788339.2));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_charge_to_mass_quotient<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_charge_to_mass_quotient<\n                 T>::uncertainty() == static_cast<T>(2.4));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_charge_to_mass_quotient<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_charge_to_mass_quotient<\n          T>::precision()));\n}\n\n// proton Compton wavelength\n// (1.3214098446e-15 \u00b1 1.9e-24) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_Compton_wavelength<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_Compton_wavelength<T>::value() ==\n      static_cast<T>(1.3214098446e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::proton_Compton_wavelength<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(1.9e-24));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::proton_Compton_wavelength<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::proton_Compton_wavelength<\n                    T>::precision()));\n}\n\n// proton Compton wavelength over 2 pi\n// (2.1030890861e-16 \u00b1 3e-25) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_Compton_wavelength_over_2_pi, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_Compton_wavelength_over_2_pi<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_Compton_wavelength_over_2_pi<\n          T>::value() == static_cast<T>(2.1030890861e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_Compton_wavelength_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_Compton_wavelength_over_2_pi<\n          T>::uncertainty() == static_cast<T>(3e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_Compton_wavelength_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_Compton_wavelength_over_2_pi<\n          T>::precision()));\n}\n\n// proton-electron mass ratio\n// (1836.15267247 \u00b1 8e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_electron_mass_ratio<T>::value() ==\n      static_cast<T>(1836.15267247));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::proton_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(8e-07));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::proton_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::proton_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// proton g factor\n// (5.585694713 \u00b1 4.6e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_g_factor<T>::value() ==\n             static_cast<T>(5.585694713));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_g_factor<T>::uncertainty() ==\n      static_cast<T>(4.6e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_g_factor<T>::precision()));\n}\n\n// proton gyromag. ratio\n// (267522209.9 \u00b1 7.0) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_gyromag_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_gyromag_ratio<T>::value() ==\n             static_cast<T>(267522209.9));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_gyromag_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_gyromag_ratio<T>::uncertainty() ==\n      static_cast<T>(7.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_gyromag_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_gyromag_ratio<T>::precision()));\n}\n\n// proton gyromag. ratio over 2 pi\n// (42.5774821 \u00b1 1.1e-06) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_gyromag_ratio_over_2_pi, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_gyromag_ratio_over_2_pi<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_gyromag_ratio_over_2_pi<\n                 T>::value() == static_cast<T>(42.5774821));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_gyromag_ratio_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_gyromag_ratio_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(1.1e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_gyromag_ratio_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_gyromag_ratio_over_2_pi<\n          T>::precision()));\n}\n\n// proton mag. mom.\n// (1.410606662e-26 \u00b1 3.7e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_mag_mom<T>::value() ==\n             static_cast<T>(1.410606662e-26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mag_mom<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_mag_mom<T>::uncertainty() ==\n             static_cast<T>(3.7e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_mag_mom<T>::precision()));\n}\n\n// proton mag. mom. to Bohr magneton ratio\n// (0.001521032209 \u00b1 1.2e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(0.001521032209));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(1.2e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// proton mag. mom. to nuclear magneton ratio\n// (2.792847356 \u00b1 2.3e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(2.792847356));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(2.3e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// proton mag. shielding correction\n// (2.5694e-05 \u00b1 1.4e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mag_shielding_correction, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mag_shielding_correction<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_mag_shielding_correction<\n                 T>::value() == static_cast<T>(2.5694e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mag_shielding_correction<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_mag_shielding_correction<\n                 T>::uncertainty() == static_cast<T>(1.4e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mag_shielding_correction<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_mag_shielding_correction<\n          T>::precision()));\n}\n\n// proton mass\n// (1.672621637e-27 \u00b1 8.3e-35) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::proton_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_mass<T>::value() ==\n             static_cast<T>(1.672621637e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_mass<T>::uncertainty() ==\n             static_cast<T>(8.3e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_mass<T>::precision()));\n}\n\n// proton mass energy equivalent\n// (1.503277359e-10 \u00b1 7.5e-18) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(1.503277359e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(7.5e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// proton mass energy equivalent in MeV\n// (938.272013 \u00b1 2.3e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(938.272013));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(2.3e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// proton mass in u\n// (1.00727646677 \u00b1 1e-10) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_mass_in_u<T>::value() ==\n             static_cast<T>(1.00727646677));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(1e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_mass_in_u<T>::precision()));\n}\n\n// proton molar mass\n// (0.00100727646677 \u00b1 1e-13) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_molar_mass<T>::value() ==\n             static_cast<T>(0.00100727646677));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_molar_mass<T>::uncertainty() ==\n      static_cast<T>(1e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_molar_mass<T>::precision()));\n}\n\n// proton-muon mass ratio\n// (8.88024339 \u00b1 2.3e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_muon_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_muon_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_muon_mass_ratio<T>::value() ==\n      static_cast<T>(8.88024339));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::proton_muon_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_muon_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.3e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_muon_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_muon_mass_ratio<T>::precision()));\n}\n\n// proton-neutron mag. mom. ratio\n// (-1.45989806 \u00b1 3.4e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_neutron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_neutron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_neutron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-1.45989806));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_neutron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_neutron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(3.4e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_neutron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_neutron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// proton-neutron mass ratio\n// (0.99862347824 \u00b1 4.6e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_neutron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_neutron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_neutron_mass_ratio<T>::value() ==\n      static_cast<T>(0.99862347824));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::proton_neutron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_neutron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(4.6e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::proton_neutron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::proton_neutron_mass_ratio<\n                    T>::precision()));\n}\n\n// proton rms charge radius\n// (8.768e-16 \u00b1 6.9e-18) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_rms_charge_radius, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_rms_charge_radius<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_rms_charge_radius<T>::value() ==\n      static_cast<T>(8.768e-16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::proton_rms_charge_radius<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::proton_rms_charge_radius<\n                 T>::uncertainty() == static_cast<T>(6.9e-18));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::proton_rms_charge_radius<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::proton_rms_charge_radius<\n                    T>::precision()));\n}\n\n// proton-tau mass ratio\n// (0.528012 \u00b1 8.6e-05)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_tau_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_tau_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_tau_mass_ratio<T>::value() ==\n      static_cast<T>(0.528012));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_tau_mass_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::proton_tau_mass_ratio<T>::uncertainty() ==\n      static_cast<T>(8.6e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::proton_tau_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::proton_tau_mass_ratio<T>::precision()));\n}\n\n// quantum of circulation\n// (0.00036369475199 \u00b1 5e-13) m^2 s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(quantum_of_circulation, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::quantum_of_circulation<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::quantum_of_circulation<T>::value() ==\n      static_cast<T>(0.00036369475199));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::quantum_of_circulation<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::quantum_of_circulation<\n                 T>::uncertainty() == static_cast<T>(5e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::quantum_of_circulation<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::quantum_of_circulation<T>::precision()));\n}\n\n// quantum of circulation times 2\n// (0.000727389504 \u00b1 1e-12) m^2 s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(quantum_of_circulation_times_2, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::quantum_of_circulation_times_2<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::quantum_of_circulation_times_2<\n                 T>::value() == static_cast<T>(0.000727389504));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::quantum_of_circulation_times_2<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::quantum_of_circulation_times_2<\n                 T>::uncertainty() == static_cast<T>(1e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::quantum_of_circulation_times_2<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::quantum_of_circulation_times_2<\n          T>::precision()));\n}\n\n// Rydberg constant\n// (10973731.568527 \u00b1 7.3e-05) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Rydberg_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Rydberg_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Rydberg_constant<T>::value() ==\n             static_cast<T>(10973731.568527));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Rydberg_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Rydberg_constant<T>::uncertainty() ==\n      static_cast<T>(7.3e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Rydberg_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Rydberg_constant<T>::precision()));\n}\n\n// Rydberg constant times c in Hz\n// (3289841960361000.0 \u00b1 22000.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(Rydberg_constant_times_c_in_Hz, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Rydberg_constant_times_c_in_Hz<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Rydberg_constant_times_c_in_Hz<\n                 T>::value() == static_cast<T>(3289841960361000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Rydberg_constant_times_c_in_Hz<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Rydberg_constant_times_c_in_Hz<\n                 T>::uncertainty() == static_cast<T>(22000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Rydberg_constant_times_c_in_Hz<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Rydberg_constant_times_c_in_Hz<\n          T>::precision()));\n}\n\n// Rydberg constant times hc in eV\n// (13.60569193 \u00b1 3.4e-07) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(Rydberg_constant_times_hc_in_eV, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Rydberg_constant_times_hc_in_eV<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Rydberg_constant_times_hc_in_eV<\n                 T>::value() == static_cast<T>(13.60569193));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Rydberg_constant_times_hc_in_eV<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Rydberg_constant_times_hc_in_eV<\n                 T>::uncertainty() == static_cast<T>(3.4e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Rydberg_constant_times_hc_in_eV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Rydberg_constant_times_hc_in_eV<\n          T>::precision()));\n}\n\n// Rydberg constant times hc in J\n// (2.17987197e-18 \u00b1 1.1e-25) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(Rydberg_constant_times_hc_in_J, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Rydberg_constant_times_hc_in_J<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::Rydberg_constant_times_hc_in_J<\n                 T>::value() == static_cast<T>(2.17987197e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Rydberg_constant_times_hc_in_J<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Rydberg_constant_times_hc_in_J<\n                 T>::uncertainty() == static_cast<T>(1.1e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Rydberg_constant_times_hc_in_J<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Rydberg_constant_times_hc_in_J<\n          T>::precision()));\n}\n\n// Sackur-Tetrode constant (1 K, 100 kPa)\n// (-1.1517047 \u00b1 4.4e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(Sackur_Tetrode_constant_1_K_100_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::value() == static_cast<T>(-1.1517047));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::uncertainty() == static_cast<T>(4.4e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::precision()));\n}\n\n// Sackur-Tetrode constant (1 K, 101.325 kPa)\n// (-1.1648677 \u00b1 4.4e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(Sackur_Tetrode_constant_1_K_101325_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::value() == static_cast<T>(-1.1648677));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::uncertainty() == static_cast<T>(4.4e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::precision()));\n}\n\n// second radiation constant\n// (0.014387752 \u00b1 2.5e-08) m K\nBOOST_AUTO_TEST_CASE_TEMPLATE(second_radiation_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::second_radiation_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::second_radiation_constant<T>::value() ==\n      static_cast<T>(0.014387752));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::second_radiation_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::second_radiation_constant<\n                 T>::uncertainty() == static_cast<T>(2.5e-08));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::second_radiation_constant<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::second_radiation_constant<\n                    T>::precision()));\n}\n\n// shielded helion gyromag. ratio\n// (203789473.0 \u00b1 5.6) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_helion_gyromag_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::shielded_helion_gyromag_ratio<\n                 T>::value() == static_cast<T>(203789473.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_helion_gyromag_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::shielded_helion_gyromag_ratio<\n                 T>::uncertainty() == static_cast<T>(5.6));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_helion_gyromag_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::shielded_helion_gyromag_ratio<\n          T>::precision()));\n}\n\n// shielded helion gyromag. ratio over 2 pi\n// (32.43410198 \u00b1 9e-07) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_gyromag_ratio_over_2_pi, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_helion_gyromag_ratio_over_2_pi<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::shielded_helion_gyromag_ratio_over_2_pi<\n          T>::value() == static_cast<T>(32.43410198));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_helion_gyromag_ratio_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::shielded_helion_gyromag_ratio_over_2_pi<\n          T>::uncertainty() == static_cast<T>(9e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_helion_gyromag_ratio_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::shielded_helion_gyromag_ratio_over_2_pi<\n          T>::precision()));\n}\n\n// shielded helion mag. mom.\n// (-1.074552982e-26 \u00b1 3e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_helion_mag_mom<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::shielded_helion_mag_mom<T>::value() ==\n      static_cast<T>(-1.074552982e-26));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::shielded_helion_mag_mom<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::shielded_helion_mag_mom<\n                 T>::uncertainty() == static_cast<T>(3e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_helion_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::shielded_helion_mag_mom<T>::precision()));\n}\n\n// shielded helion mag. mom. to Bohr magneton ratio\n// (-0.001158671471 \u00b1 1.4e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::value() ==\n             static_cast<T>(-0.001158671471));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::uncertainty() ==\n      static_cast<T>(1.4e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::precision()));\n}\n\n// shielded helion mag. mom. to nuclear magneton ratio\n// (-2.127497718 \u00b1 2.5e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_mag_mom_to_nuclear_magneton_ratio,\n                              T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::value() ==\n      static_cast<T>(-2.127497718));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty() ==\n      static_cast<T>(2.5e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n}\n\n// shielded helion to proton mag. mom. ratio\n// (-0.761766558 \u00b1 1.1e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_to_proton_mag_mom_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_helion_to_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::shielded_helion_to_proton_mag_mom_ratio<\n          T>::value() == static_cast<T>(-0.761766558));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_helion_to_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::shielded_helion_to_proton_mag_mom_ratio<\n          T>::uncertainty() == static_cast<T>(1.1e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_helion_to_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::shielded_helion_to_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// shielded helion to shielded proton mag. mom. ratio\n// (-0.7617861313 \u00b1 3.3e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_to_shielded_proton_mag_mom_ratio,\n                              T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 shielded_helion_to_shielded_proton_mag_mom_ratio<T>::value() ==\n             static_cast<T>(-0.7617861313));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::uncertainty() ==\n      static_cast<T>(3.3e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::precision()));\n}\n\n// shielded proton gyromag. ratio\n// (267515336.2 \u00b1 7.3) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_proton_gyromag_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::shielded_proton_gyromag_ratio<\n                 T>::value() == static_cast<T>(267515336.2));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_proton_gyromag_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::shielded_proton_gyromag_ratio<\n                 T>::uncertainty() == static_cast<T>(7.3));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_proton_gyromag_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::shielded_proton_gyromag_ratio<\n          T>::precision()));\n}\n\n// shielded proton gyromag. ratio over 2 pi\n// (42.5763881 \u00b1 1.2e-06) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_gyromag_ratio_over_2_pi, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_proton_gyromag_ratio_over_2_pi<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::shielded_proton_gyromag_ratio_over_2_pi<\n          T>::value() == static_cast<T>(42.5763881));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_proton_gyromag_ratio_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::shielded_proton_gyromag_ratio_over_2_pi<\n          T>::uncertainty() == static_cast<T>(1.2e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_proton_gyromag_ratio_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::shielded_proton_gyromag_ratio_over_2_pi<\n          T>::precision()));\n}\n\n// shielded proton mag. mom.\n// (1.410570419e-26 \u00b1 3.8e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_proton_mag_mom<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::shielded_proton_mag_mom<T>::value() ==\n      static_cast<T>(1.410570419e-26));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::shielded_proton_mag_mom<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::shielded_proton_mag_mom<\n                 T>::uncertainty() == static_cast<T>(3.8e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::shielded_proton_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::shielded_proton_mag_mom<T>::precision()));\n}\n\n// shielded proton mag. mom. to Bohr magneton ratio\n// (0.001520993128 \u00b1 1.7e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::\n                 shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::value() ==\n             static_cast<T>(0.001520993128));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::uncertainty() ==\n      static_cast<T>(1.7e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::precision()));\n}\n\n// shielded proton mag. mom. to nuclear magneton ratio\n// (2.792775598 \u00b1 3e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_mag_mom_to_nuclear_magneton_ratio,\n                              T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::value() ==\n      static_cast<T>(2.792775598));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty() ==\n      static_cast<T>(3e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n}\n\n// speed of light in vacuum\n// (299792458.0 \u00b1 0.0) m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(speed_of_light_in_vacuum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::speed_of_light_in_vacuum<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::speed_of_light_in_vacuum<T>::value() ==\n      static_cast<T>(299792458.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::speed_of_light_in_vacuum<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::speed_of_light_in_vacuum<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::speed_of_light_in_vacuum<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::speed_of_light_in_vacuum<\n                    T>::precision()));\n}\n\n// standard acceleration of gravity\n// (9.80665 \u00b1 0.0) m s^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(standard_acceleration_of_gravity, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::standard_acceleration_of_gravity<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::standard_acceleration_of_gravity<\n                 T>::value() == static_cast<T>(9.80665));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::standard_acceleration_of_gravity<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::standard_acceleration_of_gravity<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::standard_acceleration_of_gravity<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::standard_acceleration_of_gravity<\n          T>::precision()));\n}\n\n// standard atmosphere\n// (101325.0 \u00b1 0.0) Pa\nBOOST_AUTO_TEST_CASE_TEMPLATE(standard_atmosphere, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::standard_atmosphere<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::standard_atmosphere<T>::value() ==\n             static_cast<T>(101325.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::standard_atmosphere<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::standard_atmosphere<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::standard_atmosphere<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::standard_atmosphere<T>::precision()));\n}\n\n// Stefan-Boltzmann constant\n// (5.6704e-08 \u00b1 4e-13) W m^-2 K^-4\nBOOST_AUTO_TEST_CASE_TEMPLATE(Stefan_Boltzmann_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Stefan_Boltzmann_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Stefan_Boltzmann_constant<T>::value() ==\n      static_cast<T>(5.6704e-08));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Stefan_Boltzmann_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::Stefan_Boltzmann_constant<\n                 T>::uncertainty() == static_cast<T>(4e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::Stefan_Boltzmann_constant<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::Stefan_Boltzmann_constant<\n                    T>::precision()));\n}\n\n// tau Compton wavelength\n// (6.9772e-16 \u00b1 1.1e-19) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_Compton_wavelength<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::tau_Compton_wavelength<T>::value() ==\n      static_cast<T>(6.9772e-16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::tau_Compton_wavelength<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(1.1e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_Compton_wavelength<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::tau_Compton_wavelength<T>::precision()));\n}\n\n// tau Compton wavelength over 2 pi\n// (1.11046e-16 \u00b1 1.8e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_Compton_wavelength_over_2_pi, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_Compton_wavelength_over_2_pi<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_Compton_wavelength_over_2_pi<\n                 T>::value() == static_cast<T>(1.11046e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_Compton_wavelength_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_Compton_wavelength_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(1.8e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_Compton_wavelength_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::tau_Compton_wavelength_over_2_pi<\n          T>::precision()));\n}\n\n// tau-electron mass ratio\n// (3477.48 \u00b1 0.57)\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::tau_electron_mass_ratio<T>::value() ==\n      static_cast<T>(3477.48));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::tau_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(0.57));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_electron_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::tau_electron_mass_ratio<T>::precision()));\n}\n\n// tau mass\n// (3.16777e-27 \u00b1 5.2e-31) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::tau_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_mass<T>::value() ==\n             static_cast<T>(3.16777e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_mass<T>::uncertainty() ==\n             static_cast<T>(5.2e-31));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::tau_mass<T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::tau_mass<T>::precision()));\n}\n\n// tau mass energy equivalent\n// (2.84705e-10 \u00b1 4.6e-14) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_mass_energy_equivalent<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::tau_mass_energy_equivalent<T>::value() ==\n      static_cast<T>(2.84705e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::tau_mass_energy_equivalent<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(4.6e-14));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::tau_mass_energy_equivalent<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::tau_mass_energy_equivalent<\n                    T>::precision()));\n}\n\n// tau mass energy equivalent in MeV\n// (1776.99 \u00b1 0.29) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_mass_energy_equivalent_in_MeV<\n                 T>::value() == static_cast<T>(1776.99));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_mass_energy_equivalent_in_MeV<\n                 T>::uncertainty() == static_cast<T>(0.29));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::tau_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// tau mass in u\n// (1.90768 \u00b1 0.00031) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_mass_in_u, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::tau_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_mass_in_u<T>::value() ==\n             static_cast<T>(1.90768));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_mass_in_u<T>::uncertainty() ==\n             static_cast<T>(0.00031));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::tau_mass_in_u<T>::precision()));\n}\n\n// tau molar mass\n// (0.00190768 \u00b1 3.1e-07) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_molar_mass<T>::value() ==\n             static_cast<T>(0.00190768));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_molar_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_molar_mass<T>::uncertainty() ==\n             static_cast<T>(3.1e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::tau_molar_mass<T>::precision()));\n}\n\n// tau-muon mass ratio\n// (16.8183 \u00b1 0.0027)\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_muon_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_muon_mass_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_muon_mass_ratio<T>::value() ==\n             static_cast<T>(16.8183));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_muon_mass_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::tau_muon_mass_ratio<T>::uncertainty() ==\n      static_cast<T>(0.0027));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_muon_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::tau_muon_mass_ratio<T>::precision()));\n}\n\n// tau-neutron mass ratio\n// (1.89129 \u00b1 0.00031)\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_neutron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_neutron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::tau_neutron_mass_ratio<T>::value() ==\n      static_cast<T>(1.89129));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::tau_neutron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::tau_neutron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(0.00031));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_neutron_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::tau_neutron_mass_ratio<T>::precision()));\n}\n\n// tau-proton mass ratio\n// (1.8939 \u00b1 0.00031)\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::tau_proton_mass_ratio<T>::value() ==\n      static_cast<T>(1.8939));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_proton_mass_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::tau_proton_mass_ratio<T>::uncertainty() ==\n      static_cast<T>(0.00031));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::tau_proton_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::tau_proton_mass_ratio<T>::precision()));\n}\n\n// Thomson cross section\n// (6.652458558e-29 \u00b1 2.7e-37) m^2\nBOOST_AUTO_TEST_CASE_TEMPLATE(Thomson_cross_section, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Thomson_cross_section<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Thomson_cross_section<T>::value() ==\n      static_cast<T>(6.652458558e-29));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Thomson_cross_section<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Thomson_cross_section<T>::uncertainty() ==\n      static_cast<T>(2.7e-37));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Thomson_cross_section<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Thomson_cross_section<T>::precision()));\n}\n\n// triton-electron mag. mom. ratio\n// (-0.001620514423 \u00b1 2.1e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_electron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_electron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_electron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-0.001620514423));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_electron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_electron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(2.1e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_electron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::triton_electron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// triton-electron mass ratio\n// (5496.9215269 \u00b1 5.1e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::triton_electron_mass_ratio<T>::value() ==\n      static_cast<T>(5496.9215269));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::triton_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(5.1e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::triton_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::triton_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// triton g factor\n// (5.957924896 \u00b1 7.6e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_g_factor<T>::value() ==\n             static_cast<T>(5.957924896));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::triton_g_factor<T>::uncertainty() ==\n      static_cast<T>(7.6e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::triton_g_factor<T>::precision()));\n}\n\n// triton mag. mom.\n// (1.504609361e-26 \u00b1 4.2e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_mag_mom<T>::value() ==\n             static_cast<T>(1.504609361e-26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mag_mom<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_mag_mom<T>::uncertainty() ==\n             static_cast<T>(4.2e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::triton_mag_mom<T>::precision()));\n}\n\n// triton mag. mom. to Bohr magneton ratio\n// (0.001622393657 \u00b1 2.1e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(0.001622393657));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(2.1e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// triton mag. mom. to nuclear magneton ratio\n// (2.978962448 \u00b1 3.8e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(2.978962448));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(3.8e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// triton mass\n// (5.00735588e-27 \u00b1 2.5e-34) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::triton_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_mass<T>::value() ==\n             static_cast<T>(5.00735588e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_mass<T>::uncertainty() ==\n             static_cast<T>(2.5e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::triton_mass<T>::precision()));\n}\n\n// triton mass energy equivalent\n// (4.50038703e-10 \u00b1 2.2e-17) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(4.50038703e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(2.2e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::triton_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// triton mass energy equivalent in MeV\n// (2808.920906 \u00b1 7e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::triton_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(2808.920906));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::triton_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(7e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::triton_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// triton mass in u\n// (3.0155007134 \u00b1 2.5e-09) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_mass_in_u<T>::value() ==\n             static_cast<T>(3.0155007134));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::triton_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(2.5e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::triton_mass_in_u<T>::precision()));\n}\n\n// triton molar mass\n// (0.0030155007134 \u00b1 2.5e-12) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_molar_mass<T>::value() ==\n             static_cast<T>(0.0030155007134));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::triton_molar_mass<T>::uncertainty() ==\n      static_cast<T>(2.5e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::triton_molar_mass<T>::precision()));\n}\n\n// triton-neutron mag. mom. ratio\n// (-1.55718553 \u00b1 3.7e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_neutron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_neutron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_neutron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-1.55718553));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_neutron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_neutron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(3.7e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_neutron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::triton_neutron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// triton-proton mag. mom. ratio\n// (1.066639908 \u00b1 1e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_proton_mag_mom_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::triton_proton_mag_mom_ratio<T>::value() ==\n      static_cast<T>(1.066639908));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::triton_proton_mag_mom_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(1e-08));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::triton_proton_mag_mom_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::triton_proton_mag_mom_ratio<\n                    T>::precision()));\n}\n\n// triton-proton mass ratio\n// (2.9937170309 \u00b1 2.5e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::triton_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::triton_proton_mass_ratio<T>::value() ==\n      static_cast<T>(2.9937170309));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::triton_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::triton_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.5e-09));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::triton_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::triton_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// unified atomic mass unit\n// (1.660538782e-27 \u00b1 8.3e-35) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(unified_atomic_mass_unit, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::unified_atomic_mass_unit<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::unified_atomic_mass_unit<T>::value() ==\n      static_cast<T>(1.660538782e-27));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::unified_atomic_mass_unit<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2006::unified_atomic_mass_unit<\n                 T>::uncertainty() == static_cast<T>(8.3e-35));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2006::unified_atomic_mass_unit<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2006::unified_atomic_mass_unit<\n                    T>::precision()));\n}\n\n// von Klitzing constant\n// (25812.807557 \u00b1 1.8e-05) ohm\nBOOST_AUTO_TEST_CASE_TEMPLATE(von_Klitzing_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::von_Klitzing_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::von_Klitzing_constant<T>::value() ==\n      static_cast<T>(25812.807557));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::von_Klitzing_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::von_Klitzing_constant<T>::uncertainty() ==\n      static_cast<T>(1.8e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::von_Klitzing_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::von_Klitzing_constant<T>::precision()));\n}\n\n// weak mixing angle\n// (0.22255 \u00b1 0.00056)\nBOOST_AUTO_TEST_CASE_TEMPLATE(weak_mixing_angle, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::weak_mixing_angle<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2006::weak_mixing_angle<T>::value() ==\n             static_cast<T>(0.22255));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::weak_mixing_angle<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::weak_mixing_angle<T>::uncertainty() ==\n      static_cast<T>(0.00056));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::weak_mixing_angle<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::weak_mixing_angle<T>::precision()));\n}\n\n// Wien frequency displacement law constant\n// (58789330000.0 \u00b1 100000.0) Hz K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Wien_frequency_displacement_law_constant, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Wien_frequency_displacement_law_constant<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Wien_frequency_displacement_law_constant<\n          T>::value() == static_cast<T>(58789330000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Wien_frequency_displacement_law_constant<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Wien_frequency_displacement_law_constant<\n          T>::uncertainty() == static_cast<T>(100000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Wien_frequency_displacement_law_constant<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Wien_frequency_displacement_law_constant<\n          T>::precision()));\n}\n\n// Wien wavelength displacement law constant\n// (0.0028977685 \u00b1 5.1e-09) m K\nBOOST_AUTO_TEST_CASE_TEMPLATE(Wien_wavelength_displacement_law_constant, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Wien_wavelength_displacement_law_constant<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Wien_wavelength_displacement_law_constant<\n          T>::value() == static_cast<T>(0.0028977685));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Wien_wavelength_displacement_law_constant<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2006::Wien_wavelength_displacement_law_constant<\n          T>::uncertainty() == static_cast<T>(5.1e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2006::Wien_wavelength_displacement_law_constant<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2006::Wien_wavelength_displacement_law_constant<\n          T>::precision()));\n}\n", "meta": {"hexsha": "0a1a135b7cdb7e21a0e41a8c8101ef7fe24c3d6a", "size": 297248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/codata_2006.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/codata_2006.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/codata_2006.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": 43.7322348095, "max_line_length": 80, "alphanum_fraction": 0.6909550275, "num_tokens": 84893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5047769922684417}}
{"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#include \"toplevelfixture.hpp\"\n#include <boost/make_shared.hpp>\n#include <boost/test/unit_test.hpp>\n#include <ql/currencies/all.hpp>\n#include <ql/indexes/indexmanager.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <qle/cashflows/equitycoupon.hpp>\n#include <qle/cashflows/equitycouponpricer.hpp>\n#include <qle/cashflows/fxlinkedcashflow.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace boost::unit_test_framework;\nusing namespace std;\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(CashFlowTest)\n\nBOOST_AUTO_TEST_CASE(testFXLinkedCashFlow) {\n\n    BOOST_TEST_MESSAGE(\"Testing FX Linked CashFlow\");\n\n    // Test today = 5 Jan 2016\n    Settings::instance().evaluationDate() = Date(5, Jan, 2016);\n    Date today = Settings::instance().evaluationDate();\n\n    Date cfDate1(5, Jan, 2015); // historical\n    Date cfDate2(5, Jan, 2016); // today\n    Date cfDate3(5, Jan, 2017); // future\n\n    Real foreignAmount = 1000000; // 1M\n    boost::shared_ptr<SimpleQuote> sq = boost::make_shared<SimpleQuote>(123.45);\n    Handle<Quote> spot(sq);\n    DayCounter dc = ActualActual();\n    Calendar cal = TARGET();\n    Handle<YieldTermStructure> domYTS(boost::shared_ptr<YieldTermStructure>(new FlatForward(0, cal, 0.005, dc))); // JPY\n    Handle<YieldTermStructure> forYTS(boost::shared_ptr<YieldTermStructure>(new FlatForward(0, cal, 0.03, dc)));  // USD\n    // TODO foreign/domestic vs source/target\n    boost::shared_ptr<FxIndex> fxIndex =\n        boost::make_shared<FxIndex>(\"FX::USDJPY\", 0, USDCurrency(), JPYCurrency(), TARGET(), spot, domYTS, forYTS);\n\n    FXLinkedCashFlow fxlcf1(cfDate1, cfDate1, foreignAmount, fxIndex);\n    FXLinkedCashFlow fxlcf2(cfDate2, cfDate2, foreignAmount, fxIndex);\n    FXLinkedCashFlow fxlcf3(cfDate3, cfDate3, foreignAmount, fxIndex);\n\n    // Add historical and todays fixing\n    fxIndex->addFixing(cfDate1, 112.0);\n    fxIndex->addFixing(cfDate2, sq->value());\n\n    BOOST_TEST_MESSAGE(\"Check historical flow is correct\");\n    BOOST_CHECK_CLOSE(fxlcf1.amount(), 112000000.0, 1e-10);\n\n    BOOST_TEST_MESSAGE(\"Check todays flow is correct\");\n    BOOST_CHECK_CLOSE(fxlcf2.amount(), 123450000.0, 1e-10);\n\n    BOOST_TEST_MESSAGE(\"Check future (expected) flow is correct\");\n    Real fwd = sq->value() * domYTS->discount(cfDate3) / forYTS->discount(cfDate3);\n    BOOST_CHECK_CLOSE(fxlcf3.amount(), foreignAmount * fwd, 1e-10);\n\n    // Now move forward in time, check historical value is still correct\n    Settings::instance().evaluationDate() = Date(1, Feb, 2016);\n    sq->setValue(150.0);\n    domYTS->update();\n    forYTS->update();\n    BOOST_CHECK_CLOSE(fxlcf1.amount(), 112000000.0, 1e-10);\n\n    // check foward quote is still valid\n    fwd = sq->value() * domYTS->discount(cfDate3) / forYTS->discount(cfDate3);\n    BOOST_CHECK_CLOSE(fxlcf3.amount(), foreignAmount * fwd, 1e-10);\n\n    // reset\n    Settings::instance().evaluationDate() = today;\n}\n\nBOOST_AUTO_TEST_CASE(testEquityCoupon) {\n\n    BOOST_TEST_MESSAGE(\"Testing Equity Coupon\");\n\n    // Test today = 5 Jan 2016\n    Settings::instance().evaluationDate() = Date(5, Jan, 2016);\n    Date today = Settings::instance().evaluationDate();\n\n    Date cfDate1(4, Dec, 2015);\n    Date cfDate2(5, Apr, 2016); // future\n    Date fixingDate1(31, Dec, 2015);\n    Date fixingDate2(1, Apr, 2016);\n\n    Real nominal = 1000000; // 1M\n    string eqName = \"SP5\";\n    boost::shared_ptr<SimpleQuote> sq = boost::make_shared<SimpleQuote>(2100);\n    Handle<Quote> spot(sq);\n    DayCounter dc = ActualActual();\n    Calendar cal = TARGET();\n    Natural fixingLag = 2;\n    Real divFactor = 1.0;\n    Handle<YieldTermStructure> dividend(\n        boost::shared_ptr<YieldTermStructure>(new FlatForward(0, cal, 0.01, dc))); // Dividend Curve\n    Handle<YieldTermStructure> equityforecast(\n        boost::shared_ptr<YieldTermStructure>(new FlatForward(0, cal, 0.02, dc))); // Equity Forecast Curve\n\n    boost::shared_ptr<EquityIndex> eqIndex =\n        boost::make_shared<EquityIndex>(eqName, cal, spot, equityforecast, dividend);\n\n    eqIndex->addFixing(cfDate1, 2000);\n    eqIndex->addFixing(fixingDate1, 1980);\n\n    // Price Return coupon\n    EquityCoupon eq1(cfDate2, 1000000, today, cfDate2, 0, eqIndex, dc);\n    // Total Return Coupon\n    EquityCoupon eq2(cfDate2, 1000000, today, cfDate2, 0, eqIndex, dc, true, divFactor);\n    // historical starting coupon\n    EquityCoupon eq3(cfDate2, 1000000, cfDate1, cfDate2, 0, eqIndex, dc);\n    // Total Return Coupon with fixing lag\n    EquityCoupon eq4(cfDate2, 1000000, today, cfDate2, fixingLag, eqIndex, dc, true);\n\n    boost::shared_ptr<EquityCouponPricer> pricer1(new EquityCouponPricer());\n    boost::shared_ptr<EquityCouponPricer> pricer2(new EquityCouponPricer());\n    boost::shared_ptr<EquityCouponPricer> pricer3(new EquityCouponPricer());\n    boost::shared_ptr<EquityCouponPricer> pricer4(new EquityCouponPricer());\n    eq1.setPricer(pricer1);\n    eq2.setPricer(pricer2);\n    eq3.setPricer(pricer3);\n    eq4.setPricer(pricer4);\n\n    // Price Return coupon\n    Time dt = dc.yearFraction(today, cfDate2);\n    Real forward = spot->value() * std::exp((0.02 - 0.01) * dt);\n    Real expectedAmount = nominal * (forward - spot->value()) / spot->value();\n    BOOST_TEST_MESSAGE(\"Check Price Return is correct.\");\n    BOOST_CHECK_CLOSE(eq1.amount(), expectedAmount, 1e-10);\n\n    // Total Return Coupon\n    forward = spot->value() * std::exp((0.02 - 0.01) * dt);\n    Real div = spot->value() * std::exp((0.02) * dt) - forward;\n    expectedAmount = nominal * (forward + divFactor * div - spot->value()) / spot->value();\n    BOOST_TEST_MESSAGE(\"Check Total Return is correct\");\n    BOOST_CHECK_CLOSE(eq2.amount(), expectedAmount, 1e-10);\n\n    // Historical starting Price Return coupon\n    forward = spot->value() * std::exp((0.02 - 0.01) * dt);\n    expectedAmount = nominal * (forward - eqIndex->fixing(cfDate1)) / eqIndex->fixing(cfDate1);\n    BOOST_TEST_MESSAGE(\"Check Historical starting Price Return is correct.\");\n    BOOST_CHECK_CLOSE(eq3.amount(), expectedAmount, 1e-10);\n\n    // Total Return Coupon with fixing lag\n    dt = dc.yearFraction(today, fixingDate2);\n    forward = spot->value() * std::exp(0.02 * dt);\n    expectedAmount = nominal * (forward - eqIndex->fixing(fixingDate1)) / eqIndex->fixing(fixingDate1);\n    BOOST_TEST_MESSAGE(\"Check Total Return fixing lag handling is correct.\");\n    BOOST_CHECK_CLOSE(eq4.amount(), expectedAmount, 1e-10);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "078f4ac3280ef38e85e7a7e7bc66c1e1e9a211d8", "size": 7375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/cashflow.cpp", "max_stars_repo_name": "paul-giltinan/Engine", "max_stars_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "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": "QuantExt/test/cashflow.cpp", "max_issues_repo_name": "paul-giltinan/Engine", "max_issues_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/test/cashflow.cpp", "max_forks_repo_name": "paul-giltinan/Engine", "max_forks_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "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.4325842697, "max_line_length": 120, "alphanum_fraction": 0.7152542373, "num_tokens": 2085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5047769642635008}}
{"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///\n/// Code related to the phonon density fo states (DOS).\n\n#include <qpoint_grid.hpp>\n#include <boost/math/distributions/normal.hpp>\n\nnamespace alma {\n/// Objects of this class handle the contribution of a mode to the\n/// phonon DOS. We use an adaptive Gaussian smearing algorithm\n/// to broaden the isolated modes.\nclass Gaussian_for_DOS {\npublic:\n    /// Average energy.\n    const double mu;\n    /// Standard deviation.\n    const double sigma;\n    /// True if the usual lower bound would be negative.\n    const bool truncated;\n    /// Lower bound to the values that can be considered compatible\n    /// with the average energy.\n    const double lbound;\n    /// Upper bound to the values that can be considered compatible\n    /// with the average energy.\n    const double ubound;\n    /// Constructor.\n    ///\n    /// @param[in] grid - phonon spectrum on a regular grid\n    /// @param[in] iq - q point index\n    /// @param[in] im - branch index\n    /// @param[in] scalebroad - prefactor for the standard\n    /// deviation.\n    Gaussian_for_DOS(const Gamma_grid& grid,\n                     std::size_t iq,\n                     std::size_t im,\n                     double scalebroad)\n        : mu(grid.get_spectrum_at_q(iq).omega(im)),\n          sigma(scalebroad *\n                grid.base_sigma(grid.get_spectrum_at_q(iq).vg.col(im))),\n          truncated(mu - constants::nsigma * sigma < 0.),\n          lbound(truncated ? 0. : mu - constants::nsigma * sigma),\n          ubound(mu + constants::nsigma * sigma) {\n        if ((this->mu == 0.) || (this->sigma == 0.))\n            this->dist = nullptr;\n        else\n            this->dist = std::make_unique<boost::math::normal>(mu, sigma);\n    }\n\n\n    /// Get the amplitude of this contribution at a given frequency.\n    ///\n    /// @param[in] omega - an angular frequency in rad / ps\n    /// @return the value of the Gaussian, normalized to 1 with\n    /// respect to integration over omega.\n    double get_contribution(double omega) const {\n        if (this->dist)\n            return boost::math::pdf(*(this->dist), omega);\n        else\n            return 0.;\n    }\n\n\nprivate:\n    /// Underlying Gaussian distribution object.\n    std::unique_ptr<boost::math::normal> dist;\n};\n} // namespace alma\n", "meta": {"hexsha": "6bf9faa3defcdb76690e2c87c5dae7f5d77beda9", "size": 2878, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dos.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/dos.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/dos.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": 34.2619047619, "max_line_length": 74, "alphanum_fraction": 0.6414176511, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5047769578829757}}
{"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#include <iostream>\nusing std::cout; using std::endl;\n#include <cerrno> // for ::errno\n\n//[policy_eg_2\n\n#include <boost/math/special_functions/gamma.hpp>\nusing boost::math::tgamma;\n\nint main()\n{\n   // using namespace boost::math::policies; // or\n   using boost::math::policies::errno_on_error;\n   using boost::math::policies::make_policy;\n   using boost::math::policies::pole_error;\n   using boost::math::policies::domain_error;\n   using boost::math::policies::overflow_error;\n   using boost::math::policies::evaluation_error;\n\n   errno = 0;\n   std::cout << \"Result of tgamma(30000) is: \"\n      << boost::math::tgamma(\n         30000,\n         make_policy(\n            domain_error<errno_on_error>(),\n            pole_error<errno_on_error>(),\n            overflow_error<errno_on_error>(),\n            evaluation_error<errno_on_error>()\n         )\n      ) << std::endl;\n   // Check errno was set:\n   std::cout << \"errno = \" << errno << std::endl;\n   // and again with evaluation at a pole:\n   std::cout << \"Result of tgamma(-10) is: \"\n      << boost::math::tgamma(\n         -10,\n         make_policy(\n            domain_error<errno_on_error>(),\n            pole_error<errno_on_error>(),\n            overflow_error<errno_on_error>(),\n            evaluation_error<errno_on_error>()\n         )\n      ) << std::endl;\n   // Check errno was set:\n   std::cout << \"errno = \" << errno << std::endl;\n}\n\n//] //[/policy_eg_2]\n\n/*\n\nOutput:\n\n  Result of tgamma(30000) is: 1.#INF\n  errno = 34\n  Result of tgamma(-10) is: 1.#QNAN\n  errno = 33\n*/\n", "meta": {"hexsha": "0ff9f8972c2420a9fbc333090f5e3fefdecaa473", "size": 1789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/policy_eg_2.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_eg_2.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_eg_2.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": 27.5230769231, "max_line_length": 68, "alphanum_fraction": 0.6204583566, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5047769578829756}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef CBR_CONTROL__MPC__CLTV_OCP_LIE_HPP_\n#define CBR_CONTROL__MPC__CLTV_OCP_LIE_HPP_\n\n#include <Eigen/Dense>\n\n#include <autodiff/forward.hpp>\n#include <autodiff/forward/eigen.hpp>\n\n#include <cbr_math/lie/common.hpp>\n#include <cbr_utils/utils.hpp>\n\n#include <limits>\n#include <utility>\n\n#include \"ocp_common.hpp\"\n\nnamespace cbr\n{\n\n/* ---------------------------------------------------------------------------------------------- */\n/*                          Lie group Optimal Control Problem Linearizer                          */\n/* ---------------------------------------------------------------------------------------------- */\n\n/**\n * @brief Linearize a nonlinear control problem defined on a Lie group to a continuous linear time-varying problem\n * @tparam lie_pb_t nonlinear problem on Lie group satisfying interface conditions\n * The difference from linearized trajectory is the Rn state\n *  a(t) = log( Xl(t)^{-1} * X(t) )\n *             <=>\n *  X(t) = Xl(t) * exp (a(t))\n *\n * We have that\n *  \\dot a = [d^r exp_a]^{-1} * f(Xl * exp(a), ul + ue) - [d^l exp_a]^{-1} d^r Xl_t\n * which is a nonlinear system on R^{DoF}. Thus the linearized system is\n *  \\dot a = A(t) a + B(t) u + E(t) for\n *\n *  A(t) = (d/da) [d^r exp_a]^{-1} * f(Xl * exp(a), ul + ue)   at a = 0, ue = 0\n *  B(t) = (d/du) [d^r exp_a]^{-1} * f(Xl * exp(a), ul + ue)   at a = 0, ue = 0\n *  E(t) = [d^r exp_a]^{-1} f(Xl * exp(a), ul + ue) - [d^l exp_a]^{-1} d^r Xl_t  at a = 0, ue = 0\n *\n * Setting to zero:\n *\n *  A(t) = (d/da) [d^r exp_a]^{-1} * f(Xl * exp(a), ul)  at a = 0\n *  B(t) = (d/u) f(Xl, ul)                               at u = ul\n *  E(t) = f(Xl, ul) - d^r Xl_t\n */\ntemplate<typename lie_pb_t>\nclass CltvOcpLie\n{\npublic:\n  using lie_t = typename lie_pb_t::state_t;\n  using input_t = typename lie_pb_t::input_t;\n  using state_t = typename lie_pb_t::deriv_t;     // linearized problem is defined in tangent space\n\n  static constexpr std::size_t nx = state_t::SizeAtCompileTime;\n  static constexpr std::size_t nu = input_t::SizeAtCompileTime;\n\n  using A_t = Eigen::Matrix<double, nx, nx>;\n  using B_t = Eigen::Matrix<double, nx, nu>;\n  using E_t = Eigen::Matrix<double, nx, 1>;\n  using Q_t = Eigen::Matrix<double, nx, nx>;\n  using R_t = Eigen::Matrix<double, nu, nu>;\n\n  // Get return type of problem functions\n  using T_t = std::result_of_t<decltype(&lie_pb_t::get_T)(lie_pb_t)>;\n  using x0_t = std::result_of_t<decltype(&lie_pb_t::get_x0)(lie_pb_t)>;\n  using xlr_t = std::result_of_t<decltype(&lie_pb_t::get_xl)(lie_pb_t, double)>;\n  using ulr_t = std::result_of_t<decltype(&lie_pb_t::get_ul)(lie_pb_t, double)>;\n  using xdr_t = std::result_of_t<decltype(&lie_pb_t::get_xd)(lie_pb_t, double)>;\n  using udr_t = std::result_of_t<decltype(&lie_pb_t::get_ud)(lie_pb_t, double)>;\n  using Qr_t = std::result_of_t<decltype(&lie_pb_t::get_Q)(lie_pb_t, double)>;\n  using QTr_t = std::result_of_t<decltype(&lie_pb_t::get_QT)(lie_pb_t)>;\n  using Rr_t = std::result_of_t<decltype(&lie_pb_t::get_R)(lie_pb_t, double)>;\n\n  // Check return type of problem functions\n  static_assert(\n    std::is_same_v<std::decay_t<T_t>, double>,\n    \"The get_xl method of the problem must return a double.\");\n  static_assert(\n    std::is_same_v<std::decay_t<x0_t>, lie_t>,\n    \"The get_x0 method of the problem must return the group type (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<xlr_t>, lie_t>,\n    \"The get_x0 method of the problem must return the group type (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<ulr_t>, input_t>,\n    \"The get_ul method of the problem must return an nu*1 Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<xdr_t>, lie_t>,\n    \"The get_x0 method of the problem must return the group type (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<udr_t>, input_t>,\n    \"The get_ud method of the problem must return an nu*1 Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<Qr_t>, Q_t>,\n    \"The get_Q method of the problem must return an nx*nx Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<Rr_t>, R_t>,\n    \"The get_R method of the problem must return an nu*nu Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<QTr_t>, Q_t>,\n    \"The get_QT method of the problem must return an nx*nx Eigen::Matrix (or a reference to one).\");\n\n\n  // Check problem dimensions\n  static_assert(nx > 0, \"Number of states must be > 0.\");\n  static_assert(nu > 0, \"Number of inputs must be > 0.\");\n\npublic:\n  CltvOcpLie() = delete;\n  CltvOcpLie(const CltvOcpLie &) = default;\n  CltvOcpLie(CltvOcpLie &&) = default;\n  CltvOcpLie & operator=(const CltvOcpLie &) = default;\n  CltvOcpLie & operator=(CltvOcpLie &&) = default;\n\n  explicit CltvOcpLie(const lie_pb_t & pb)\n  : nl_pb_(pb)\n  {}\n\n  explicit CltvOcpLie(lie_pb_t && pb)\n  : nl_pb_(std::move(pb))\n  {}\n\n  template<typename T1>\n  CltvOcpLie(T1 && pb)\n  : nl_pb_(std::forward<T1>(pb))\n  {}\n\n  void get_x0(Eigen::Ref<state_t> x0) const\n  {\n    x0 = (nl_pb_.get_xl(0.).inverse() * nl_pb_.get_x0()).log();\n  }\n\n  void get_T(double & T) const\n  {\n    T = nl_pb_.get_T();\n  }\n\n  void get_state_lb(double, Eigen::Ref<state_t> state_lb) const\n  {\n    // state bounds not supported for now\n    state_lb.setConstant(-std::numeric_limits<double>::infinity());\n  }\n\n  void get_state_ub(double, Eigen::Ref<state_t> state_ub) const\n  {\n    // state bounds not supported for now\n    state_ub.setConstant(std::numeric_limits<double>::infinity());\n  }\n\n  void get_input_lb(double t, Eigen::Ref<input_t> input_lb) const\n  {\n    nl_pb_.get_input_lb(t, input_lb);\n    input_lb -= nl_pb_.get_ul(t);\n  }\n\n  void get_input_ub(double t, Eigen::Ref<input_t> input_ub) const\n  {\n    nl_pb_.get_input_ub(t, input_ub);\n    input_ub -= nl_pb_.get_ul(t);\n  }\n\n  A_t get_A(double t) const\n  {\n    using lie_ad_t = lie::detail::change_scalar_t<lie_t, autodiff::dual>;\n    using tangent_ad_t = Eigen::Matrix<autodiff::dual, nx, 1>;\n\n    const lie_ad_t xlin = nl_pb_.get_xl(t).template cast<autodiff::dual>();\n    const input_t ulin = nl_pb_.get_ul(t);\n\n    auto fx = [&](const tangent_ad_t & a) -> tangent_ad_t {\n        return lie::dr_expinv<lie_ad_t>(a) * nl_pb_.get_f(xlin * lie_ad_t::exp(a), ulin);\n      };\n\n    tangent_ad_t a = tangent_ad_t::Zero();\n    return autodiff::forward::jacobian(fx, autodiff::wrt(a), autodiff::forward::at(a));\n  }\n\n  B_t get_B(double t) const\n  {\n    using input_ad_t = Eigen::Matrix<autodiff::dual, nu, 1>;\n    using tangent_ad_t = Eigen::Matrix<autodiff::dual, nx, 1>;\n\n    const lie_t xlin = nl_pb_.get_xl(t);\n\n    auto fu = [&](const input_ad_t & u) -> tangent_ad_t {\n        return nl_pb_.get_f(xlin, u);\n      };\n\n    input_ad_t ulin = nl_pb_.get_ul(t);\n    return autodiff::forward::jacobian(fu, autodiff::wrt(ulin), autodiff::forward::at(ulin));\n  }\n\n  E_t get_E(double t) const\n  {\n    const lie_t xlin = nl_pb_.get_xl(t);\n    const input_t ulin = nl_pb_.get_ul(t);\n    const typename lie_t::Tangent xlDot = nl_pb_.get_xldot(t);\n\n    return nl_pb_.get_f(xlin, ulin) - xlDot;\n  }\n\n  Qr_t get_Q(double t) const\n  {\n    return nl_pb_.get_Q(t);\n  }\n\n  QTr_t get_QT() const\n  {\n    return nl_pb_.get_QT();\n  }\n\n  Rr_t get_R(double t) const\n  {\n    return nl_pb_.get_R(t);\n  }\n\n  state_t get_q(double t) const\n  {\n    const xlr_t xl = nl_pb_.get_xl(t);\n    const xdr_t xd = nl_pb_.get_xd(t);\n    const Qr_t Q = nl_pb_.get_Q(t);\n    return (xd.inverse() * xl).log().transpose() * Q;\n  }\n\n  state_t get_qT() const\n  {\n    double T = nl_pb_.get_T();\n    const xlr_t xl = nl_pb_.get_xl(T);\n    const xdr_t xd = nl_pb_.get_xd(T);\n    const QTr_t QT = nl_pb_.get_QT();\n    return (xd.inverse() * xl).log().transpose() * QT;\n  }\n\n  input_t get_r(double t) const\n  {\n    const ulr_t ul = nl_pb_.get_ul(t);\n    const udr_t ud = nl_pb_.get_ud(t);\n    const Rr_t R = nl_pb_.get_R(t);\n    return (ul - ud).transpose() * R;\n  }\n\n  lie_pb_t & problem()\n  {\n    return nl_pb_;\n  }\n\nprotected:\n  lie_pb_t nl_pb_{};\n};\n\n// Class template argument deduction guides\ntemplate<typename T>\nCltvOcpLie(T)->CltvOcpLie<T>;\n\ntemplate<typename T1, typename T2>\nCltvOcpLie(T1, T2)->CltvOcpLie<T1>;\n\n}  // namespace cbr\n\n\n#endif  // CBR_CONTROL__MPC__CLTV_OCP_LIE_HPP_\n", "meta": {"hexsha": "c266f3631571b74a75b4f0c921c984f284571fb4", "size": 8416, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_control/mpc/cltv_ocp_lie.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": "include/cbr_control/mpc/cltv_ocp_lie.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": "include/cbr_control/mpc/cltv_ocp_lie.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": 31.5205992509, "max_line_length": 114, "alphanum_fraction": 0.6406844106, "num_tokens": 2687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857831, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.5047755596994077}}
{"text": "//\n//  Copyright Toon Knapen, Karl Meerbergen\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 \"random.hpp\"\n\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/std_vector.hpp>\n#include <boost/numeric/bindings/blas/blas1.hpp>\n\n#include <vector>\n#include <complex>\n#include <iostream>\n#include <limits>\n#include <cmath>\n\n\n\n// Randomize a vector (using functions from random.hpp)\ntemplate <typename V>\nvoid randomize(V& v) {\n   for (typename V::size_type i=0; i<v.size(); ++i)\n      v[i] = random_value< typename V::value_type >() ;\n} // randomize()\n\n\nfloat abs_sum_value( float const& f ) {\n  using namespace std ;\n  return abs(f) ;\n}\n\ndouble abs_sum_value( double const& f ) {\n  using namespace std ;\n  return abs(f) ;\n}\n\nfloat abs_sum_value( std::complex< float > const& f ) {\n  using namespace std ;\n  return abs(f.real()) + abs(f.imag()) ;\n}\n\ndouble abs_sum_value( std::complex< double > const& f ) {\n  using namespace std ;\n  return abs(f.real()) + abs(f.imag()) ;\n}\n\ntemplate <typename V>\ntypename boost::numeric::bindings::traits::type_traits<typename V::value_type>::real_type abs_sum( V const& v) {\n  typedef typename boost::numeric::bindings::traits::type_traits<typename V::value_type>::real_type real_type ;\n\n  real_type sum( 0.0 ) ;\n  for ( typename V::size_type i=0; i<v.size(); ++i ) {\n    sum += abs_sum_value( v[i] ) ;\n  }\n  return sum ;\n}\n\n\n// Blas operations using one vector.\ntemplate <typename T>\nstruct OneVector {\n  boost::numeric::ublas::vector<T> v_ref_ ;\n\n  // Initialize : set reference vector (ublas)\n  OneVector()\n  : v_ref_( 10 )\n  {\n     randomize(v_ref_);\n  }\n\n  template <typename V>\n  int operator()(V& v) const {\n     using namespace boost::numeric::bindings::blas ;\n\n     typedef typename V::value_type                                                        value_type ;\n     typedef typename boost::numeric::bindings::traits::type_traits<value_type>::real_type real_type ;\n\n     // Copy vector from reference\n     for (typename V::size_type i=0; i<v_ref_.size(); ++i)\n        v[i] = v_ref_(i);\n\n     // Test blas routines and compare with reference\n     real_type nrm = nrm2( v );\n     if ( std::abs(nrm - norm_2(v_ref_)) > std::numeric_limits< real_type >::epsilon() * norm_2(v_ref_)) {\n       std::cout << \"nrm2 : \" << std::abs(nrm - norm_2(v_ref_)) << \" > \" << std::numeric_limits< real_type >::epsilon() * norm_2(v_ref_) << std::endl ;\n       return 255 ;\n     }\n\n     nrm = asum( v );\n     if ( std::abs(nrm - abs_sum(v_ref_)) > std::numeric_limits< real_type >::epsilon() * abs_sum(v_ref_)) {\n       std::cout << \"asum : \" << std::abs(nrm - abs_sum(v_ref_)) << \" > \" << std::numeric_limits< real_type >::epsilon() * abs_sum(v_ref_) << std::endl ;\n       return 255 ;\n     }\n\n     scal( value_type(2.0), v );\n     for (typename V::size_type i=0; i<v_ref_.size(); ++i)\n        if (std::abs( v[i] - real_type(2.0)*v_ref_(i) ) > real_type(2.0)*std::abs(v_ref_(i))) return 255 ;\n\n     return 0;\n  }\n\n  // Return the size of a vector.\n  size_t size() const {return v_ref_.size();}\n};\n\n\n// Operations with two vectors.\ntemplate <typename T, typename V>\nstruct BaseTwoVectorOperations {\n  typedef T                                                                             value_type ;\n  typedef typename boost::numeric::bindings::traits::type_traits<value_type>::real_type real_type ;\n  typedef boost::numeric::ublas::vector<T>                                              ref_vector_type ;\n\n  // Initialize: select the first vector and set the reference vectors (ublas)\n  BaseTwoVectorOperations(V& v, const ref_vector_type& v1_ref, const ref_vector_type& v2_ref)\n  : v_( v )\n  , v1_ref_( v1_ref )\n  , v2_ref_( v2_ref )\n  {}\n\n  // Copy the 2nd reference vector into w.\n  template <typename W>\n  void copy_vector(W& w) const {\n     for (size_t i=0; i<size(); ++i) {\n        w[i] = v2_ref_(i);\n     }\n  } // copy_vector()\n\n  // Get the size of a vector.\n  size_t size() const {return v_.size();}\n\n  // Data members.\n  V&                     v_ ;\n  const ref_vector_type& v1_ref_, v2_ref_ ;\n};\n\n\ntemplate <typename T, typename V>\nstruct TwoVectorOperations { } ;\n\n\ntemplate <typename V>\nstruct TwoVectorOperations< float, V>\n: BaseTwoVectorOperations<float,V> {\n  typedef typename V::value_type                                                        value_type ;\n  typedef typename boost::numeric::bindings::traits::type_traits<value_type>::real_type real_type ;\n  typedef typename BaseTwoVectorOperations<float,V>::ref_vector_type                    ref_vector_type ;\n\n  TwoVectorOperations(V& v, const ref_vector_type& v1_ref, const ref_vector_type& v2_ref)\n  : BaseTwoVectorOperations<float,V>( v, v1_ref, v2_ref )\n  {}\n\n  // Perform the tests of blas functions and compare with reference\n  template <typename W>\n  int operator()(W& w) const {\n     using namespace boost::numeric::bindings::blas ;\n     real_type safety_factor (1.5);\n\n     copy_vector(w);\n\n     // Test blas routines\n     value_type prod = dot( this->v_, w );\n     if ( std::abs(prod - inner_prod( this->v1_ref_, this->v2_ref_ ))\n          > safety_factor*std::numeric_limits< real_type >::epsilon() * std::abs(prod)) return 255 ;\n\n     axpy( value_type(2.0), this->v_, w );\n     for (size_t i=0; i<this->size(); ++i)\n        if ( std::abs(w[i] - (this->v2_ref_(i) + value_type(2.0)*this->v1_ref_(i)))\n          > safety_factor*std::numeric_limits< real_type >::epsilon() * std::abs(w[i])) return 255 ;\n\n     scal( value_type(0.0), w ) ;\n     copy( this->v_, w ) ;\n     for (size_t i=0; i<this->size(); ++i) {\n        if ( std::abs( w[i] - this->v_[i] ) != 0.0 ) return 255 ;\n     }\n\n     return 0;\n  }\n};\n\n\ntemplate <typename V>\nstruct TwoVectorOperations< double, V>\n: BaseTwoVectorOperations<double,V> {\n  typedef typename V::value_type                                                        value_type ;\n  typedef typename boost::numeric::bindings::traits::type_traits<value_type>::real_type real_type ;\n  typedef typename BaseTwoVectorOperations<double,V>::ref_vector_type                   ref_vector_type ;\n\n  TwoVectorOperations(V& v, const ref_vector_type& v1_ref, const ref_vector_type& v2_ref)\n  : BaseTwoVectorOperations<double,V>( v, v1_ref, v2_ref )\n  {}\n\n  // Perform the tests of blas functions and compare with reference\n  template <typename W>\n  int operator()(W& w) const {\n     using namespace boost::numeric::bindings::blas ;\n\n     copy_vector( w );\n\n     // Test blas routines\n     value_type prod = dot( this->v_, w );\n     if ( std::abs(prod - inner_prod( this->v1_ref_, this->v2_ref_ ))\n          > std::numeric_limits< real_type >::epsilon() * std::abs(prod)) return 255 ;\n\n     axpy( value_type(2.0), this->v_, w );\n     for (size_t i=0; i<this->size(); ++i)\n        if ( std::abs(w[i] - (this->v2_ref_(i) + value_type(2.0)*this->v1_ref_(i)))\n          > std::numeric_limits< real_type >::epsilon() * std::abs(w[i])) return 255 ;\n\n     copy_vector( w ) ;\n     scal( value_type(-1.0), w ) ;\n     ::boost::numeric::bindings::blas::copy( this->v_, w ) ;\n     for (size_t i=0; i<this->size(); ++i) {\n        if ( w[i] != this->v_[i] ) return 255 ;\n     }\n\n     return 0;\n  }\n};\n\n\ntemplate <typename V>\nstruct TwoVectorOperations< std::complex<float>, V>\n: BaseTwoVectorOperations< std::complex<float>, V>\n{\n  typedef typename V::value_type                                                        value_type ;\n  typedef typename boost::numeric::bindings::traits::type_traits<value_type>::real_type real_type ;\n  typedef typename BaseTwoVectorOperations<std::complex<float>,V>::ref_vector_type      ref_vector_type ;\n\n  TwoVectorOperations(V& v, const ref_vector_type& v1_ref, const ref_vector_type& v2_ref)\n  : BaseTwoVectorOperations< std::complex<float>, V>( v, v1_ref, v2_ref )\n  {}\n\n  // Perform the tests of blas functions and compare with reference\n  template <typename W>\n  int operator()(W& w) const {\n     using namespace boost::numeric::bindings::blas ;\n     real_type safety_factor (1.5);\n\n     copy_vector( w );\n\n     // Test blas routines\n     value_type prod = dotc( this->v_, w );\n     if ( std::abs(prod - inner_prod( conj(this->v1_ref_), this->v2_ref_ ))\n          > safety_factor*std::numeric_limits< real_type >::epsilon() * std::abs(prod)) return 255 ;\n\n     prod = dotu( this->v_, w );\n     if ( std::abs(prod - inner_prod( this->v1_ref_, this->v2_ref_ ))\n          > safety_factor*std::numeric_limits< real_type >::epsilon() * std::abs(prod)) return 255 ;\n\n     axpy( value_type(2.0), this->v_, w );\n     for (size_t i=0; i<this->size(); ++i)\n        if ( std::abs(w[i] - (this->v2_ref_(i) + value_type(2.0)*this->v1_ref_(i)))\n          > safety_factor*std::numeric_limits< real_type >::epsilon() * std::abs(w[i])) return 255 ;\n\n     scal( value_type(0.0), w ) ;\n     copy( this->v_, w ) ;\n     for (size_t i=0; i<this->size(); ++i) {\n        if ( std::abs( w[i] - this->v_[i] ) != 0.0 ) return 255 ;\n     }\n\n     return 0;\n  }\n};\n\n\ntemplate <typename V>\nstruct TwoVectorOperations< std::complex<double>, V>\n: BaseTwoVectorOperations< std::complex<double>, V>\n{\n  typedef typename V::value_type                                                        value_type ;\n  typedef typename boost::numeric::bindings::traits::type_traits<value_type>::real_type real_type ;\n  typedef typename BaseTwoVectorOperations<std::complex<double>,V>::ref_vector_type     ref_vector_type ;\n\n  TwoVectorOperations(V& v, const ref_vector_type& v1_ref, const ref_vector_type& v2_ref)\n  : BaseTwoVectorOperations< std::complex<double>, V>( v, v1_ref, v2_ref )\n  {}\n\n  // Perform the tests of blas functions and compare with reference\n  template <typename W>\n  int operator()(W& w) const {\n     using namespace boost::numeric::bindings::blas ;\n     real_type safety_factor (1.5);\n\n     copy_vector( w );\n\n     // Test blas routines\n     value_type prod = dotc( this->v_, w );\n     if ( std::abs(prod - inner_prod( conj(this->v1_ref_), this->v2_ref_ ))\n          > safety_factor*std::numeric_limits< real_type >::epsilon() * std::abs(prod)) return 255 ;\n\n     prod = dotu( this->v_, w );\n     if ( std::abs(prod - inner_prod( this->v1_ref_, this->v2_ref_ ))\n          > safety_factor*std::numeric_limits< real_type >::epsilon() * std::abs(prod)) return 255 ;\n\n     axpy( value_type(2.0), this->v_, w );\n     for (size_t i=0; i<this->size(); ++i)\n        if ( std::abs(w[i] - (this->v2_ref_(i) + value_type(2.0)*this->v1_ref_(i)))\n          > safety_factor*std::numeric_limits< real_type >::epsilon() * std::abs(w[i])) return 255 ;\n\n     scal( value_type(0.0), w ) ;\n     copy( this->v_, w ) ;\n     for (size_t i=0; i<this->size(); ++i) {\n        if ( std::abs( w[i] - this->v_[i] ) != 0.0 ) return 255 ;\n     }\n\n     return 0;\n  }\n};\n\n\n// Run the tests for different types of vectors.\ntemplate <typename T, typename F>\nint different_vectors(const F& f) {\n   // Do test for different types of vectors\n   {\n      std::cout << \"  ublas::vector\\n\" ;\n      boost::numeric::ublas::vector< T > v(f.size());\n      if (f( v )) return 255 ;\n   }\n   { \n      std::cout << \"  std::vector\\n\" ;\n      std::vector<T> v_ref(f.size());\n      if (f( v_ref )) return 255 ;\n   }\n   {\n      std::cout << \"  ublas::vector_range\\n\" ;\n      typedef boost::numeric::ublas::vector< T > vector_type ;\n      vector_type v(f.size()*2);\n      boost::numeric::ublas::vector_range< vector_type > vr(v, boost::numeric::ublas::range(1,1+f.size()));\n      if (f( vr )) return 255 ;\n   }\n   {\n      typedef boost::numeric::ublas::matrix< T, boost::numeric::ublas::column_major >  matrix_type ;\n      matrix_type  m(f.size(),f.size()) ;\n\n      std::cout << \"  ublas::matrix_column\\n\" ;\n      boost::numeric::ublas::matrix_column< matrix_type > m_c( m, 2 );\n      if (f( m_c )) return 255 ;\n\n      std::cout << \"  ublas::matrix_row\\n\" ;\n      boost::numeric::ublas::matrix_row< matrix_type > m_r( m, 1 );\n      if (f( m_r )) return 255 ;\n   }\n   return 0;\n} // different_vectors()\n\n\n// This is the functor that selects the first vector of the tests that use two vectors.\ntemplate <typename T>\nstruct TwoVector {\n   TwoVector()\n   : v1_ref_( 10 )\n   , v2_ref_( 10 )\n   {}\n\n   template <typename V>\n   int operator() (V& v) const {\n      for (size_t i=0; i<size(); ++i) v[i] = v1_ref_(i) ;\n      return different_vectors<T,TwoVectorOperations<T,V> >( TwoVectorOperations<T,V>(v, v1_ref_, v2_ref_) ) ;\n   }\n\n   size_t size() const {\n      return v1_ref_.size() ;\n   }\n\n   boost::numeric::ublas::vector<T> v1_ref_ ;\n   boost::numeric::ublas::vector<T> v2_ref_ ;\n}; // TwoVector\n\n\n// Run the test for a specific value_type T.\ntemplate <typename T>\nint do_value_type() {\n   // Tests for functions with one vector argument.\n   std::cout << \" one argument\\n\";\n   if (different_vectors<T,OneVector<T> >(OneVector<T> ())) return 255 ;\n\n   // Tests for functions with two vector arguments.\n   std::cout << \" two arguments\\n\";\n   if (different_vectors<T,TwoVector<T> >(TwoVector<T>())) return 255;\n   return 0;\n} // do_value_type()\n\n\nint main() {\n  // Run regression for Real/Complex\n  std::cout << \"float\\n\"; if (do_value_type<float>() ) return 255 ;\n  std::cout << \"double\\n\"; if (do_value_type<double>() ) return 255 ;\n  std::cout << \"complex<float>\\n\"; if (do_value_type<std::complex<float> >() ) return 255 ;\n  std::cout << \"complex<double>\\n\"; if (do_value_type<std::complex<double> >() ) return 255 ;\n\n  std::cout << \"Regression test successful\\n\" ;\n\n  return 0 ;\n}\n\n\n", "meta": {"hexsha": "f5f22fadbdbf0d586eab3f2543e3268d66c154f9", "size": 13669, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/blas/test/blas1.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/blas/test/blas1.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/blas/test/blas1.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": 33.6674876847, "max_line_length": 153, "alphanum_fraction": 0.6204550443, "num_tokens": 3817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5047438910101266}}
{"text": "/*\n This program is free software; you can redistribute it and/or modify it under\n the terms of the European Union Public Licence - EUPL v.1.1 as published by\n the European Commission.\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 European Union Public Licence - EUPL v.1.1\n for more details.\n\n You should have received a copy of the European Union Public Licence - EUPL v.1.1\n along with this program.\n\n Further information about the European Union Public Licence - EUPL v.1.1 can\n also be found on the world wide web at http://ec.europa.eu/idabc/eupl\n\n*/\n\n/*\n ------ Copyright (C) 2011 STA Steering Board (space.trajectory.analysis AT gmail.com) ----\n*/\n/*\n------------------ Author: Guillermo Ortega  ----------------------------------------\n July 2011\n\n */\n\n#include \"serviceAngleRateUnit.h\"\n\n#include <Eigen/Core>\n\nusing namespace Eigen;\n\n#include \"QDebug\"\n\nDialogServiceAngleRateUnitFrame::DialogServiceAngleRateUnitFrame( QWidget * parent, Qt::WindowFlags f) : QFrame(parent,f)\n{\n    setupUi(this);\n    angleRateUnitWidget = DialogServiceAngleRateUnitFrame::comboBoxAngleRateUnitsChoice;\n    myPastUnits = 0;\n    comboBoxAngleRateUnitsChoice->setCurrentIndex(myPastUnits);\n}\n\nDialogServiceAngleRateUnitFrame::~DialogServiceAngleRateUnitFrame()\n{\n}\n\n\n// Index meaning is as follows:\n// index = 0  is Degree\n// index = 1  is radians\n\n// Matrix coefficients as follows\n// Deg/s->Deg/s  Rad/s->Deg/s\n// Deg/s->Rad/s  Rad/s->Rad/s\n\nstatic double angleRateConversionMatrixCoeffs[4] =\n{1.0,            57.295779513,\n 0.0174532925,   1.0};\n\nstatic const Matrix<double, 2, 2> angleRateConversionMatrix(angleRateConversionMatrixCoeffs);\n\n\ndouble DialogServiceAngleRateUnitFrame::convertAngleRate(int fromAngleRateUnit, int toAngleRateUnit, double angleRate)\n{\n    double finalAngleRate = angleRate * angleRateConversionMatrix(fromAngleRateUnit, toAngleRateUnit);\n    return finalAngleRate;\n}\n\n\n//// Sets the input distance, the output distance and the current index inside the method\nvoid DialogServiceAngleRateUnitFrame::setInputAngleRate(double niceInputAngleRate)\n{\n    myPastAngleRate = niceInputAngleRate;\n}\n\n\n\n// Index meaning is as follows:\n// index = 0  is Kilometers\n// index = 1  is meters\n// index = 2  is centi-meters\n// index = 3  is mili-meters\n// index = 4 is Astronomical Units\nvoid DialogServiceAngleRateUnitFrame::on_comboBoxAngleRateUnitsChoice_currentIndexChanged(int myIndex)\n{\n    myFutureUnits = myIndex;\n    myFutureAngleRate = convertAngleRate(myPastUnits, myFutureUnits, myPastAngleRate);\n    myPastAngleRate = myFutureAngleRate;\n    myPastUnits = myFutureUnits;\n    myRealAngleRateForXMLSchema = convertAngleRate (myPastUnits, 0, myFutureAngleRate);\n}\n\n", "meta": {"hexsha": "0fa1c0d6898ab923ca888740d2d9e5693218642a", "size": 2823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Services/serviceAngleRateUnit.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "sta-src/Services/serviceAngleRateUnit.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "sta-src/Services/serviceAngleRateUnit.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 30.0319148936, "max_line_length": 121, "alphanum_fraction": 0.7495572086, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5047438861841593}}
{"text": "#include <UnitTest++/UnitTest++.h>\n#include <stdexcept>\n#include <iostream>\n#include <cmath>\n#include <limits>\n#include <boost/filesystem.hpp>\n#include <fstream>\n\n#include \"coela_utility/src/string_utils.h\"\n#include \"coela_core/src/ccd_image.h\"\n#include \"coela_analysis/src/psf_generation.h\"\n#include \"coela_analysis/src/psf_fitting_recipes.h\"\n#include \"coela_random/src/random.h\"\n\nusing namespace coela;\nusing namespace std;\n\nSUITE(PsfFitting_recipes)\n{\n\n\n    string test_suite_output_dir= string(UnitTestSuite::GetSuiteName()) + \"_tests/\";\n    TEST(Run_Standard_Suite_Setup) {\n        cout << \"*** \\\"\"<< UnitTestSuite::GetSuiteName() <<\"\\\" unit tests running ***\" <<endl;\n        boost::filesystem::create_directories(test_suite_output_dir);\n    }\n\n    TEST(Gaussian_fitting_recipe) {\n\n        bool output_to_screen=false;\n        PixelRange img_size(1,1,50,50);\n\n        psf_models::GaussianPsfModel g_model(5.0, 1.2);\n\n        vector<unsigned long> seed;\n        seed.push_back(111);\n        seed.push_back(122);\n        seed.push_back(133);\n        seed.push_back(144);\n        seed.push_back(155);\n        seed.push_back(166);\n\n        unuran::StreamWrapper::\n        set_unuran_package_seed(seed, false);\n        unuran::StreamWrapper rns;\n        unuran::UniformRandomVariate urv(10.,40., rns);\n\n        CcdPosition g_model_true_centre(urv(), urv());\n\n        cerr<<\"CCD centre Position: \" <<g_model_true_centre<<endl;\n\n        psf_models::ReferencePsf test_psf_ref_img =\n            psf_models::generate_psf(g_model, img_size,\n                                     CcdPosition(0.0,0.0),\n                                     g_model_true_centre,\n                                     1.0,\n                                     2,\n                                     true, 10.0);\n\n        string filename = test_suite_output_dir +\"gauss_model.fits\";\n        test_psf_ref_img.psf_image.write_to_file(filename);\n\n        PixelIndex peak_pixel = test_psf_ref_img.psf_image.pix.max_PixelIndex();\n        CcdPosition initial_centre_estimate =\n            test_psf_ref_img.psf_image.CCD_grid.corresponding_grid_Position(\n                PixelPosition::centre_of_pixel(peak_pixel));\n\n\n        psf_fitting::least_squares_weighting lsq_weight;\n\n        psf_fitting::Mn2_models::PsfFit<psf_models::GaussianPsfModel>\n        fit_result =\n            psf_fitting::fit_gaussian_model(test_psf_ref_img.psf_image,\n                                            initial_centre_estimate,\n                                            lsq_weight,\n                                            1.8,\n                                            4,\n                                            output_to_screen);\n\n        CHECK_CLOSE(g_model.peak_val, fit_result.model.peak_val, g_model.peak_val * 0.02);\n        CHECK_CLOSE(g_model.sigma_in_CCD_pix, fit_result.model.sigma_in_CCD_pix,\n                    g_model.sigma_in_CCD_pix * 0.025);\n        CHECK_CLOSE(g_model_true_centre.x, fit_result.Position.centre.x, 0.05);\n        CHECK_CLOSE(g_model_true_centre.y, fit_result.Position.centre.y, 0.05);\n\n\n\n    }\n\n}\n", "meta": {"hexsha": "9836b4fad589fcb9891fca20677c38ae12152eea", "size": 3088, "ext": "cc", "lang": "C++", "max_stars_repo_path": "coela_analysis/src/unit_tests/psf_fitting_recipes_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_analysis/src/unit_tests/psf_fitting_recipes_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_analysis/src/unit_tests/psf_fitting_recipes_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": 33.9340659341, "max_line_length": 94, "alphanum_fraction": 0.6055699482, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5047438842590358}}
{"text": "/**********************************************************************************************************************\nThis file is part of the Control Toolbox (https://github.com/ethz-adrl/control-toolbox), copyright by ETH Zurich.\nLicensed under the BSD-2 license (see LICENSE file in main directory)\n**********************************************************************************************************************/\n\n#pragma once\n\n#include <ct/core/core.h>\n#include <memory>\n\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/info_parser.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"CostFunctionQuadratic.hpp\"\n#include \"utility/utilities.hpp\"\n\n#include \"term/TermLoadMacros.hpp\"\n\nnamespace ct {\nnamespace optcon {\n\n/**\n * \\ingroup CostFunction\n *\n * \\brief Cost Function with Auto-Diff support\n *\n * This cost function can work with both, analytical terms as well as\n * auto-diff terms. For analytical terms it will use provided derivatives\n * and for auto-diff terms derivatives will be computed using auto-diff.\n *\n * Unit test \\ref ADTest.cpp illustrates the use of a CostFunctionAD.\n */\ntemplate <size_t STATE_DIM, size_t CONTROL_DIM, typename SCALAR = double>\nclass CostFunctionAD : public CostFunctionQuadratic<STATE_DIM, CONTROL_DIM, SCALAR>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    typedef core::DerivativesCppadJIT<STATE_DIM + CONTROL_DIM + 1, 1> JacCG;\n    typedef typename JacCG::CG_SCALAR CGScalar;\n    typedef Eigen::Matrix<CGScalar, 1, 1> MatrixCg;\n\n    typedef Eigen::Matrix<SCALAR, STATE_DIM, STATE_DIM> state_matrix_t;\n    typedef Eigen::Matrix<SCALAR, CONTROL_DIM, CONTROL_DIM> control_matrix_t;\n    typedef Eigen::Matrix<SCALAR, CONTROL_DIM, STATE_DIM> control_state_matrix_t;\n\n    typedef core::StateVector<STATE_DIM, SCALAR> state_vector_t;\n    typedef core::ControlVector<CONTROL_DIM, SCALAR> control_vector_t;\n    typedef Eigen::Matrix<SCALAR, Eigen::Dynamic, 1> VectorXs;\n    typedef Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> MatrixXs;\n\n    /**\n\t * \\brief Basic constructor\n\t */\n    CostFunctionAD();\n\n    /**\n\t * \\brief Constructor loading function from file\n\t * @param filename config file location\n\t * @param verbose flag enabling printouts\n\t */\n    CostFunctionAD(const std::string& filename, bool verbose = false);\n\n    /**\n\t * Deep-cloning of cost function\n\t * @return base pointer to clone\n\t */\n    CostFunctionAD<STATE_DIM, CONTROL_DIM, SCALAR>* clone() const;\n\n    /**\n\t * \\brief Copy constructor\n\t * @param arg cost function to copy\n\t */\n    CostFunctionAD(const CostFunctionAD& arg);\n\n\n    /**\n\t * \\brief Destructor\n\t */\n    virtual ~CostFunctionAD();\n\n\n    /**\n\t * @brief      Initializes the AD costfunction, generates and compiles\n\t *             source code\n\t */\n    virtual void initialize() override;\n\n    /**\n\t * \\brief Add an intermediate, auto-differentiable term\n\t *\n\t * Use this function to add an auto-differentiable, intermediate term to the cost function.\n\t *\n\t * @param term The term to be added\n\t * @param verbose Flag enabling printouts\n\t * @return\n\t */\n    void addIntermediateADTerm(std::shared_ptr<TermBase<STATE_DIM, CONTROL_DIM, SCALAR, CGScalar>> term,\n        bool verbose = false) override;\n\n    /**\n\t * \\brief Add a final, auto-differentiable term\n\t *\n\t * Use this function to add an auto-differentiable, final term to the cost function.\n\t *\n\t * @param term The term to be added\n\t * @param verbose Flag enabling printouts\n\t * @return\n\t */\n    void addFinalADTerm(std::shared_ptr<TermBase<STATE_DIM, CONTROL_DIM, SCALAR, CGScalar>> term,\n        bool verbose = false) override;\n\n    void setCurrentStateAndControl(const state_vector_t& x, const control_vector_t& u, const SCALAR& t = 0.0) override;\n\n    void loadFromConfigFile(const std::string& filename, bool verbose = false) override;\n\n    SCALAR evaluateIntermediate() override;\n    SCALAR evaluateTerminal() override;\n\n    state_vector_t stateDerivativeIntermediate() override;\n    state_vector_t stateDerivativeTerminal() override;\n\n    control_vector_t controlDerivativeIntermediate() override;\n    control_vector_t controlDerivativeTerminal() override;\n\n    state_matrix_t stateSecondDerivativeIntermediate() override;\n    state_matrix_t stateSecondDerivativeTerminal() override;\n\n    control_matrix_t controlSecondDerivativeIntermediate() override;\n    control_matrix_t controlSecondDerivativeTerminal() override;\n\n    control_state_matrix_t stateControlDerivativeIntermediate() override;\n    control_state_matrix_t stateControlDerivativeTerminal() override;\n\n    std::shared_ptr<TermBase<STATE_DIM, CONTROL_DIM, SCALAR, CGScalar>> getIntermediateADTermById(const size_t id);\n\n    std::shared_ptr<TermBase<STATE_DIM, CONTROL_DIM, SCALAR, CGScalar>> getFinalADTermById(const size_t id);\n\n    std::shared_ptr<TermBase<STATE_DIM, CONTROL_DIM, SCALAR, CGScalar>> getIntermediateADTermByName(\n        const std::string& name);\n\n    std::shared_ptr<TermBase<STATE_DIM, CONTROL_DIM, SCALAR, CGScalar>> getFinalADTermByName(const std::string& name);\n\n\nprivate:\n    MatrixCg evaluateIntermediateCg(const Eigen::Matrix<CGScalar, STATE_DIM + CONTROL_DIM + 1, 1>& stateInputTime);\n    MatrixCg evaluateTerminalCg(const Eigen::Matrix<CGScalar, STATE_DIM + CONTROL_DIM + 1, 1>& stateInputTime);\n\n    //! combined state, control and time vector\n    Eigen::Matrix<SCALAR, STATE_DIM + CONTROL_DIM + 1, 1> stateControlTime_;\n\n    //! intermediate AD terms\n    std::vector<std::shared_ptr<TermBase<STATE_DIM, CONTROL_DIM, SCALAR, CGScalar>>> intermediateTerms_;\n    //! final AD terms\n    std::vector<std::shared_ptr<TermBase<STATE_DIM, CONTROL_DIM, SCALAR, CGScalar>>> finalTerms_;\n\n    //! generated jacobians\n    std::shared_ptr<JacCG> intermediateCostCodegen_;\n    std::shared_ptr<JacCG> finalCostCodegen_;\n\n    //! cppad functions\n    typename JacCG::FUN_TYPE_CG intermediateFun_;\n    typename JacCG::FUN_TYPE_CG finalFun_;\n};\n\n}  // namespace optcon\n}  // namespace ct\n", "meta": {"hexsha": "36372e7b625f6b2e420fca64b48972392859a931", "size": 5936, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ct_optcon/include/ct/optcon/costfunction/CostFunctionAD.hpp", "max_stars_repo_name": "vklemm/control-toolbox", "max_stars_repo_head_hexsha": "f5f8cf9331c0aecd721ff6296154e2a55c72f679", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-01T14:45:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-01T14:45:18.000Z", "max_issues_repo_path": "ct_optcon/include/ct/optcon/costfunction/CostFunctionAD.hpp", "max_issues_repo_name": "deidaraho/control-toolbox", "max_issues_repo_head_hexsha": "f0ccdf4b6c25e02948215fd3bff212d891f0fd69", "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": "ct_optcon/include/ct/optcon/costfunction/CostFunctionAD.hpp", "max_forks_repo_name": "deidaraho/control-toolbox", "max_forks_repo_head_hexsha": "f0ccdf4b6c25e02948215fd3bff212d891f0fd69", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-03T06:28:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T06:28:39.000Z", "avg_line_length": 35.124260355, "max_line_length": 119, "alphanum_fraction": 0.7126010782, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.5047438832833152}}
{"text": "/*\r\n   Copyright (c) Marshall Clow 2013.\r\n\r\n   Distributed under the Boost Software License, Version 1.0. (See accompanying\r\n   file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n    For more information, see http://www.boost.org\r\n*/\r\n\r\n#include <boost/config.hpp>\r\n#include <boost/algorithm/cxx17/transform_reduce.hpp>\r\n\r\n#include \"iterator_test.hpp\"\r\n\r\n#define BOOST_TEST_MAIN\r\n#include <boost/test/unit_test.hpp>\r\n\r\nnamespace ba = boost::algorithm;\r\n\r\ntemplate <class _Tp>\r\nstruct identity\r\n{\r\n    const _Tp& operator()(const _Tp& __x) const { return __x;}\r\n};\r\n\r\ntemplate <class _Tp>\r\nstruct twice\r\n{\r\n  \tconst _Tp operator()(const _Tp& __x) const { return 2 * __x; }\r\n};\r\n\r\n\r\ntemplate <class Iter1, class T, class BOp, class UOp>\r\nvoid\r\ntest_init_bop_uop(Iter1 first1, Iter1 last1, T init, BOp bOp, UOp uOp, T x)\r\n{\r\n    BOOST_CHECK(ba::transform_reduce(first1, last1, init, bOp, uOp) == x);\r\n}\r\n\r\ntemplate <class Iter>\r\nvoid\r\ntest_init_bop_uop()\r\n{\r\n    int ia[]          = {1, 2, 3, 4, 5, 6};\r\n    unsigned sa = sizeof(ia) / sizeof(ia[0]);\r\n\r\n    test_init_bop_uop(Iter(ia), Iter(ia),    0, std::plus<int>(),       identity<int>(),       0);\r\n    test_init_bop_uop(Iter(ia), Iter(ia),    1, std::multiplies<int>(), identity<int>(),       1);\r\n    test_init_bop_uop(Iter(ia), Iter(ia+1),  0, std::multiplies<int>(), identity<int>(),       0);\r\n    test_init_bop_uop(Iter(ia), Iter(ia+1),  2, std::plus<int>(),       identity<int>(),       3);\r\n    test_init_bop_uop(Iter(ia), Iter(ia+2),  0, std::plus<int>(),       identity<int>(),       3);\r\n    test_init_bop_uop(Iter(ia), Iter(ia+2),  3, std::multiplies<int>(), identity<int>(),       6);\r\n    test_init_bop_uop(Iter(ia), Iter(ia+sa), 4, std::multiplies<int>(), identity<int>(),    2880);\r\n    test_init_bop_uop(Iter(ia), Iter(ia+sa), 4, std::plus<int>(),       identity<int>(),      25);\r\n\r\n    test_init_bop_uop(Iter(ia), Iter(ia),    0, std::plus<int>(),       twice<int>(),       0);\r\n    test_init_bop_uop(Iter(ia), Iter(ia),    1, std::multiplies<int>(), twice<int>(),       1);\r\n    test_init_bop_uop(Iter(ia), Iter(ia+1),  0, std::multiplies<int>(), twice<int>(),       0);\r\n    test_init_bop_uop(Iter(ia), Iter(ia+1),  2, std::plus<int>(),       twice<int>(),       4);\r\n    test_init_bop_uop(Iter(ia), Iter(ia+2),  0, std::plus<int>(),       twice<int>(),       6);\r\n    test_init_bop_uop(Iter(ia), Iter(ia+2),  3, std::multiplies<int>(), twice<int>(),      24);\r\n    test_init_bop_uop(Iter(ia), Iter(ia+sa), 4, std::multiplies<int>(), twice<int>(),  184320); // 64 * 2880\r\n    test_init_bop_uop(Iter(ia), Iter(ia+sa), 4, std::plus<int>(),       twice<int>(),      46);\r\n}\r\n\r\nvoid test_transform_reduce_init_bop_uop()\r\n{\r\n\tBOOST_CHECK ( true );\r\n}\r\n\r\ntemplate <class Iter1, class Iter2, class T, class Op1, class Op2>\r\nvoid\r\ntest_init_bop_bop(Iter1 first1, Iter1 last1, Iter2 first2, T init, Op1 op1, Op2 op2, T x)\r\n{\r\n    BOOST_CHECK(ba::transform_reduce(first1, last1, first2, init, op1, op2) == x);\r\n}\r\n\r\ntemplate <class SIter, class UIter>\r\nvoid\r\ntest_init_bop_bop()\r\n{\r\n    int ia[]          = {1, 2, 3, 4, 5, 6};\r\n    unsigned int ua[] = {2, 4, 6, 8, 10,12};\r\n    unsigned sa = sizeof(ia) / sizeof(ia[0]);\r\n    BOOST_CHECK(sa == sizeof(ua) / sizeof(ua[0]));       // just to be sure\r\n\r\n    test_init_bop_bop(SIter(ia), SIter(ia),    UIter(ua), 0, std::plus<int>(), std::multiplies<int>(),       0);\r\n    test_init_bop_bop(UIter(ua), UIter(ua),    SIter(ia), 1, std::multiplies<int>(), std::plus<int>(),       1);\r\n    test_init_bop_bop(SIter(ia), SIter(ia+1),  UIter(ua), 0, std::multiplies<int>(), std::plus<int>(),       0);\r\n    test_init_bop_bop(UIter(ua), UIter(ua+1),  SIter(ia), 2, std::plus<int>(), std::multiplies<int>(),       4);\r\n    test_init_bop_bop(SIter(ia), SIter(ia+2),  UIter(ua), 0, std::plus<int>(), std::multiplies<int>(),      10);\r\n    test_init_bop_bop(UIter(ua), UIter(ua+2),  SIter(ia), 3, std::multiplies<int>(), std::plus<int>(),      54);\r\n    test_init_bop_bop(SIter(ia), SIter(ia+sa), UIter(ua), 4, std::multiplies<int>(), std::plus<int>(), 2099520);\r\n    test_init_bop_bop(UIter(ua), UIter(ua+sa), SIter(ia), 4, std::plus<int>(), std::multiplies<int>(),     186);\r\n}\r\n\r\nvoid test_transform_reduce_init_bop_bop()\r\n{\r\n//  All the iterator categories\r\n    test_init_bop_bop<input_iterator        <const int*>, input_iterator        <const unsigned int*> >();\r\n    test_init_bop_bop<input_iterator        <const int*>, forward_iterator      <const unsigned int*> >();\r\n    test_init_bop_bop<input_iterator        <const int*>, bidirectional_iterator<const unsigned int*> >();\r\n    test_init_bop_bop<input_iterator        <const int*>, random_access_iterator<const unsigned int*> >();\r\n\r\n    test_init_bop_bop<forward_iterator      <const int*>, input_iterator        <const unsigned int*> >();\r\n    test_init_bop_bop<forward_iterator      <const int*>, forward_iterator      <const unsigned int*> >();\r\n    test_init_bop_bop<forward_iterator      <const int*>, bidirectional_iterator<const unsigned int*> >();\r\n    test_init_bop_bop<forward_iterator      <const int*>, random_access_iterator<const unsigned int*> >();\r\n\r\n    test_init_bop_bop<bidirectional_iterator<const int*>, input_iterator        <const unsigned int*> >();\r\n    test_init_bop_bop<bidirectional_iterator<const int*>, forward_iterator      <const unsigned int*> >();\r\n    test_init_bop_bop<bidirectional_iterator<const int*>, bidirectional_iterator<const unsigned int*> >();\r\n    test_init_bop_bop<bidirectional_iterator<const int*>, random_access_iterator<const unsigned int*> >();\r\n\r\n    test_init_bop_bop<random_access_iterator<const int*>, input_iterator        <const unsigned int*> >();\r\n    test_init_bop_bop<random_access_iterator<const int*>, forward_iterator      <const unsigned int*> >();\r\n    test_init_bop_bop<random_access_iterator<const int*>, bidirectional_iterator<const unsigned int*> >();\r\n    test_init_bop_bop<random_access_iterator<const int*>, random_access_iterator<const unsigned int*> >();\r\n\r\n//  just plain pointers (const vs. non-const, too)\r\n    test_init_bop_bop<const int*, const unsigned int *>();\r\n    test_init_bop_bop<const int*,       unsigned int *>();\r\n    test_init_bop_bop<      int*, const unsigned int *>();\r\n    test_init_bop_bop<      int*,       unsigned int *>();\r\n}\r\n\r\ntemplate <class Iter1, class Iter2, class T>\r\nvoid\r\ntest_init(Iter1 first1, Iter1 last1, Iter2 first2, T init, T x)\r\n{\r\n    BOOST_CHECK(ba::transform_reduce(first1, last1, first2, init) == x);\r\n}\r\n\r\ntemplate <class SIter, class UIter>\r\nvoid\r\ntest_init()\r\n{\r\n    int ia[]          = {1, 2, 3, 4, 5, 6};\r\n    unsigned int ua[] = {2, 4, 6, 8, 10,12};\r\n    unsigned sa = sizeof(ia) / sizeof(ia[0]);\r\n    BOOST_CHECK(sa == sizeof(ua) / sizeof(ua[0]));       // just to be sure\r\n\r\n    test_init(SIter(ia), SIter(ia),    UIter(ua), 0,   0);\r\n    test_init(UIter(ua), UIter(ua),    SIter(ia), 1,   1);\r\n    test_init(SIter(ia), SIter(ia+1),  UIter(ua), 0,   2);\r\n    test_init(UIter(ua), UIter(ua+1),  SIter(ia), 2,   4);\r\n    test_init(SIter(ia), SIter(ia+2),  UIter(ua), 0,  10);\r\n    test_init(UIter(ua), UIter(ua+2),  SIter(ia), 3,  13);\r\n    test_init(SIter(ia), SIter(ia+sa), UIter(ua), 0, 182);\r\n    test_init(UIter(ua), UIter(ua+sa), SIter(ia), 4, 186);\r\n}\r\n\r\nvoid test_transform_reduce_init()\r\n{\r\n//  All the iterator categories\r\n    test_init<input_iterator        <const int*>, input_iterator        <const unsigned int*> >();\r\n    test_init<input_iterator        <const int*>, forward_iterator      <const unsigned int*> >();\r\n    test_init<input_iterator        <const int*>, bidirectional_iterator<const unsigned int*> >();\r\n    test_init<input_iterator        <const int*>, random_access_iterator<const unsigned int*> >();\r\n\r\n    test_init<forward_iterator      <const int*>, input_iterator        <const unsigned int*> >();\r\n    test_init<forward_iterator      <const int*>, forward_iterator      <const unsigned int*> >();\r\n    test_init<forward_iterator      <const int*>, bidirectional_iterator<const unsigned int*> >();\r\n    test_init<forward_iterator      <const int*>, random_access_iterator<const unsigned int*> >();\r\n\r\n    test_init<bidirectional_iterator<const int*>, input_iterator        <const unsigned int*> >();\r\n    test_init<bidirectional_iterator<const int*>, forward_iterator      <const unsigned int*> >();\r\n    test_init<bidirectional_iterator<const int*>, bidirectional_iterator<const unsigned int*> >();\r\n    test_init<bidirectional_iterator<const int*>, random_access_iterator<const unsigned int*> >();\r\n\r\n    test_init<random_access_iterator<const int*>, input_iterator        <const unsigned int*> >();\r\n    test_init<random_access_iterator<const int*>, forward_iterator      <const unsigned int*> >();\r\n    test_init<random_access_iterator<const int*>, bidirectional_iterator<const unsigned int*> >();\r\n    test_init<random_access_iterator<const int*>, random_access_iterator<const unsigned int*> >();\r\n\r\n//  just plain pointers (const vs. non-const, too)\r\n    test_init<const int*, const unsigned int *>();\r\n    test_init<const int*,       unsigned int *>();\r\n    test_init<      int*, const unsigned int *>();\r\n    test_init<      int*,       unsigned int *>();\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_main )\r\n{\r\n  test_transform_reduce_init();\r\n  test_transform_reduce_init_bop_uop();\r\n  test_transform_reduce_init_bop_bop();\r\n}\r\n", "meta": {"hexsha": "cd3b25dcd785b602bddbfcab15ff03e2928b2e9a", "size": 9373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/algorithm/test/transform_reduce_test.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/algorithm/test/transform_reduce_test.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/algorithm/test/transform_reduce_test.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": 49.5925925926, "max_line_length": 113, "alphanum_fraction": 0.6412034567, "num_tokens": 2739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.504743868805414}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/test/arithmetic_opts.cpp\n *\n * \\brief Test suite for matrix/vector arithmetic operators.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2012, 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#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublasx/detail/debug.hpp>\n#include <boost/numeric/ublasx/operation/arithmetic_ops.hpp>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\n\nnamespace ublas = ::boost::numeric::ublas;\n\n\nstatic const double tol(1e-5);\n\n\nBOOST_UBLASX_TEST_DEF( scalar_div_real_vector )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Scalar divides Real Vector\");\n\n    typedef double value_type;\n    typedef ublas::vector<value_type> vector_type;\n\n    const ::std::size_t n(4);\n\n    value_type c(2);\n    vector_type v(n);\n\n    vector_type res;\n    vector_type expect(n);\n\n    v(0) = 1;\n    v(1) = 2;\n    v(2) = 3;\n    v(3) = 4;\n\n    for (::std::size_t i = 0; i < n; ++i)\n    {\n        expect(i) = c/v(i);\n    }\n\n    res = c / v;\n\n    BOOST_UBLASX_DEBUG_TRACE(\"c=\" << c);\n    BOOST_UBLASX_DEBUG_TRACE(\"v=\" << v);\n    BOOST_UBLASX_DEBUG_TRACE(\"c / v? \" << res);\n    BOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( scalar_div_real_matrix )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Scalar divides Real Matrix\");\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type> matrix_type;\n\n    const ::std::size_t nr(3);\n    const ::std::size_t nc(4);\n\n    value_type c(2);\n    matrix_type A(nr,nc);\n\n    matrix_type res;\n    matrix_type expect(nr,nc);\n\n    A(0,0) = 1; A(0,1) = 4; A(0,2) = 7; A(0,3) = 10;\n    A(1,0) = 2; A(1,1) = 5; A(1,2) = 8; A(1,3) = 11;\n    A(2,0) = 3; A(2,1) = 6; A(2,2) = 9; A(2,3) = 12;\n\n    for (::std::size_t i = 0; i < nr; ++i)\n    {\n        for (::std::size_t j = 0; j < nc; ++j)\n        {\n            expect(i,j) = c/A(i,j);\n        }\n    }\n\n    res = c / A;\n\n    BOOST_UBLASX_DEBUG_TRACE(\"c=\" << c);\n    BOOST_UBLASX_DEBUG_TRACE(\"A=\" << A);\n    BOOST_UBLASX_DEBUG_TRACE(\"c / A? \" << res);\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( res, expect, nr, nc, tol );\n}\n\n\nint main()\n{\n    BOOST_UBLASX_TEST_BEGIN();\n\n    BOOST_UBLASX_TEST_DO( scalar_div_real_vector );\n    BOOST_UBLASX_TEST_DO( scalar_div_real_matrix );\n\n    BOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "82b0d41676eef762b5eba423a7bf8f33f9438d77", "size": 2554, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/arithmetic_ops.cpp", "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": "libs/numeric/ublasx/test/arithmetic_ops.cpp", "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": "libs/numeric/ublasx/test/arithmetic_ops.cpp", "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": 22.8035714286, "max_line_length": 70, "alphanum_fraction": 0.6276429131, "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5047438688054139}}
{"text": "/*\n * TypeDefs.hpp\n *\n *  Created on: March 18, 2014\n *      Author: P\u00e9ter Fankhauser\n *\t Institute: ETH Zurich, ANYbotics\n */\n\n// Eigen\n#pragma once\n\n#include <Eigen/Core>\n\nnamespace grid_map {\n\n  using Matrix = Eigen::MatrixXf;\n  using DataType = Matrix::Scalar;\n  using Position = Eigen::Vector2d;\n  using Vector = Eigen::Vector2d;\n  using Position3 = Eigen::Vector3d;\n  using Vector3 = Eigen::Vector3d;\n  using Index = Eigen::Array2i;\n  using Size = Eigen::Array2i;\n  using Length = Eigen::Array2d;\n  using Time = uint64_t;\n\n  /*\n   * Interpolations are ordered in the order\n   * of increasing accuracy and computational complexity.\n   * INTER_NEAREST - fastest, but least accurate,\n   * INTER_CUBIC - slowest, but the most accurate.\n   * see:\n   * https://en.wikipedia.org/wiki/Bicubic_interpolation\n   * https://web.archive.org/web/20051024202307/http://www.geovista.psu.edu/sites/geocomp99/Gc99/082/gc_082.htm\n   * for more info. Cubic convolution algorithm is also known as piecewise cubic\n   * interpolation and in general does not guarantee continuous\n   * first derivatives.\n   */\n  enum class InterpolationMethods{\n      INTER_NEAREST, // nearest neighbor interpolation\n      INTER_LINEAR,   // bilinear interpolation\n      INTER_CUBIC_CONVOLUTION, //piecewise bicubic interpolation using convolution algorithm\n      INTER_CUBIC // standard bicubic interpolation\n  };\n\n}  // namespace grid_map\n\n", "meta": {"hexsha": "04a7a36ad044c96351c29d88f1dc9d988d89eef0", "size": 1407, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid_map_core/include/grid_map_core/TypeDefs.hpp", "max_stars_repo_name": "ethz-asl/grid_map", "max_stars_repo_head_hexsha": "b7293f5d379719d2d0b9f1ce047d00f32601487a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 358.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T12:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-04T14:04:53.000Z", "max_issues_repo_path": "grid_map_core/include/grid_map_core/TypeDefs.hpp", "max_issues_repo_name": "ethz-asl/grid_map", "max_issues_repo_head_hexsha": "b7293f5d379719d2d0b9f1ce047d00f32601487a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T11:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-30T14:53:48.000Z", "max_forks_repo_path": "grid_map_core/include/grid_map_core/TypeDefs.hpp", "max_forks_repo_name": "ethz-asl/grid_map", "max_forks_repo_head_hexsha": "b7293f5d379719d2d0b9f1ce047d00f32601487a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 218.0, "max_forks_repo_forks_event_min_datetime": "2015-03-19T04:41:02.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-06T02:36:16.000Z", "avg_line_length": 29.3125, "max_line_length": 111, "alphanum_fraction": 0.7192608387, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5046821233492951}}
{"text": "/*\n * Math.cpp\n *\n *  Created on: Nov 3, 2010\n *      Author: dberrios\n */\n\n#include \"MathHelper.h\"\n#include <boost/numeric/conversion/bounds.hpp>\n#include <boost/limits.hpp>\n#include <cmath>\n#include <algorithm>\n\nnamespace ccmc\n{\n\tint Math::iminloc1d(int * array, long n, int * mask)\n\t{\n\t   long i,loc;\n\t   int min;\n\t   min = std::numeric_limits<int>::max( ); //if highest value possible in array is 99999999999\n\t   for (i=0; i<n; i++)\n\t\t   {\n\t\t\t\t  if( (array[i] < min) && (mask[i] > 0)) {\n\t\t\t\t\t min=array[i];\n\t\t\t\t\t loc=i;\n\t\t\t\t  }\n\t\t   }\n\t   return loc;\n\t}\n\n\n\tint Math::imaxloc1d(int * array, long n, int * mask)\n\t{\n\t   long i,loc;\n\t   int max;\n\t   max = boost::numeric::bounds<int>::lowest(); //if lowest value possible in array is -99999999999\n\t   for (i=0; i<n; i++)\n\t\t   {\n\t\t\t\t  if( (array[i] > max) && (mask[i] > 0)) {\n\t\t\t\t\t max=array[i];\n\t\t\t\t\t loc=i;\n\t\t\t\t  }\n\t\t   }\n\t   return loc;\n\t}\n\n\tint Math::fminloc1d(float * array, long n, int * mask)\n\t{\n\t\tlong i,loc;\n\t\tfloat min;\n\t\tmin = std::numeric_limits<float>::max( ); //if highest value possible in array is 99999999999\n\t\tfor (i=0; i<n; i++)\n\t\t{\n\t\t\tif( (array[i] < min) && (mask[i] > 0))\n\t\t\t{\n\t\t\t\tmin=array[i];\n\t\t\t\tloc=i;\n\t\t\t}\n\t\t}\n\t\treturn loc;\n\t}\n\n\n\tint Math::fmaxloc1d(float * array, long n, int * mask)\n\t{\n\t   long i,loc;\n\t   float max;\n\t   max = boost::numeric::bounds<float>::lowest(); //if lowest value possible in array is -99999999999\n\t   for (i=0; i<n; i++)\n\t\t   {\n\t\t\t\t  if( (array[i] > max) && (mask[i] > 0)) {\n\t\t\t\t\t max=array[i];\n\t\t\t\t\t loc=i;\n\t\t\t\t  }\n\t\t   }\n\t   return loc;\n\t}\n\n\tint Math::dminloc1d(double * array, long n, int * mask)\n\t{\n\t   long i,loc;\n\t   double min;\n\t   min = std::numeric_limits<double>::max( ); //if highest value possible in array is 99999999999\n\t   for (i=0; i<n; i++)\n\t\t   {\n\t\t\t\t  if( (array[i] < min) && (mask[i] > 0)) {\n\t\t\t\t\t min=array[i];\n\t\t\t\t\t loc=i;\n\t\t\t\t  }\n\t\t   }\n\t   return loc;\n\t}\n\n\n\tint Math::dmaxloc1d(double * array, long n, int * mask)\n\t{\n\t   long i,loc;\n\t   double max;\n\t   max = boost::numeric::bounds<double>::lowest(); //if lowest value possible in array is -99999999999\n\t   for (i=0; i<n; i++)\n\t\t   {\n\t\t\t\t  if( (array[i] > max) && (mask[i] > 0)) {\n\t\t\t\t\t max=array[i];\n\t\t\t\t\t loc=i;\n\t\t\t\t  }\n\t\t   }\n\t   return loc;\n\t}\n\n\n\tint Math::ifindmin(int * array, long n)\n\t{\n\t   long i;\n\t   int min;\n\t   min = std::numeric_limits<int>::max( ); //if highest value possible in array is 99999999999\n\t   for (i=0; i<n; i++)\n\t\t   {\n\t\t\t\t  if(array[i] < min)\n\t\t\t\t\t min=array[i];\n\t\t   }\n\t   return min;\n\t}\n\n\tint Math::ifindmax(int * array, long n)\n\t{\n\t   long i;\n\t   int max;\n\t   max = boost::numeric::bounds<int>::lowest(); //if lowest value possible in array is -99999999999\n\t   for (i=0; i<n; i++)\n\t\t   {\n\t\t\t\t  if(array[i] > max)\n\t\t\t\t\t max=array[i];\n\t\t   }\n\t   return max;\n\t}\n\n\tlong Math::lfindmin(long * array, long n)\n\t{\n\t   long i;\n\t   long min;\n\t   min = std::numeric_limits<long>::max( ); //if highest value possible in array is 99999999999\n\t   for (i=0; i<n; i++)\n\t\t   {\n\t\t\t\t  if(array[i] < min)\n\t\t\t\t\t min=array[i];\n\t\t   }\n\t   return min;\n\t}\n\n\tlong Math::lfindmax(long * array, long n)\n\t{\n\t   long i;\n\t   long max;\n\t   max = boost::numeric::bounds<long>::lowest(); //if lowest value possible in array is -99999999999\n\t   for (i=0; i<n; i++)\n\t\t   {\n\t\t\t\t  if(array[i] > max)\n\t\t\t\t\t max=array[i];\n\t\t   }\n\t   return max;\n\t}\n\n\tfloat Math::ffindmin(float * array, long n)\n\t{\n\t   long i;\n\t   float min = std::numeric_limits<float>::max(); //if highest value possible in array is 1.e13\n\t   for (i=0; i<n; i++)\n\t   {\n\t\t\t  min = std::min(array[i], min);\n\n\t   }\n\t   return min;\n\t}\n\n\tfloat Math::ffindmax(float * array, long n)\n\t{\n\t   long i;\n\t   float max = -1.e20;\n\t   max = boost::numeric::bounds<float>::lowest(); //if lowest value possible in array is -1.e13\n\t   for (i=0; i<n; i++)\n\t   {\n\t\t   max = std::max((double)array[i] , (double)max);\n\n\t   }\n\t   return max;\n\t}\n\n\tdouble Math::dfindmin(double * array, long n)\n\t{\n\t   long i;\n\t   double min;\n\t   min = 1.e13; //if highest value possible in array is 1.e13\n\t   for (i=0; i<n; i++)\n\t\t   {\n\t\t\t\t  if(array[i] < min)\n\t\t\t\t\t min=array[i];\n\t\t   }\n\t   return min;\n\t}\n\n\tdouble Math::dfindmax(double * array, long n)\n\t{\n\t   long i;\n\t   double max;\n\t   max = -1.e13; //if lowest value possible in array is -1.e13\n\t   for (i=0; i<n; i++)\n\t\t   {\n\t\t\t\t  if(array[i] > max)\n\t\t\t\t\t max=array[i];\n\t\t   }\n\t   return max;\n\t}\n\n\tvoid Math::convert_xyz_to_rthetaphi(const float& x, const float& y, const float& z,\n\t\t\tfloat * r, float * t, float * p)\n\t{\n\t/*\n\t Converts 3D cartesian coords (x,y,z) into spherical coords (r,theta,phi).\n\t*/\n\n\t      float  piov2,r2,zr,yx;\n\n\t      piov2 = std::acos(0.);\n\n\t      r2 = x*x+y*y+z*z;\n\t      if(r2 > 0.) {\n\t        *r  = std::sqrt(r2);\n\t        zr=z/ (*r);\n\t        *t = acos(zr);\n\t        if(x > 0.) {\n\t          yx=y/x;\n\t          *p = std::atan(yx);\n\t        } else if(x < 0.) {\n\t          yx=y/std::fabs(x);\n\t          *p = 2.*piov2 - atan(yx);\n\t        } else {\n\t          *p = piov2*sign(y);\n\t        }\n\t      } else {\n\t        *r = 0.;\n\t        *t = 0.;\n\t        *p = 0.;\n\t      }\n\t      if(*p < 0.) *p=*p+4.*piov2;               /* pmn testing */\n\t}\n\n\tvoid Math::convert_rthetaphi_to_xyz(const float& r, const float& t, const float& p,\n\t\t\tfloat * x, float * y, float * z)\n\t{\n\t/*\n\t  Converts spherical coords (r,theta,phi) into 3D cartesian coords (x,y,z)\n\t*/\n\n\t      float  sint,cost,sinp,cosp;\n\n\t      sint = std::sin(t);\n\t      cost = std::cos(t);\n\t      sinp = std::sin(p);\n\t      cosp = std::cos(p);\n\n\t      *x = r*sint*cosp;\n\t      *y = r*sint*sinp;\n\t      *z = r*cost;\n\t}\n\n\tint Math::sign(int v)\n\t{\n\t   return v > 0 ? 1 : (v < 0 ? -1 : 0);\n\t}\n\n}\n", "meta": {"hexsha": "75ce11f980068f5c8416d1b33f77aeb77d2c9e8c", "size": 5616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/kameleon/src/ccmc/MathHelper.cpp", "max_stars_repo_name": "alexanderbock/Kameleon-Converter", "max_stars_repo_head_hexsha": "6c2e66bfea60b17a369a3615bc1a623bba100a6f", "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": "ext/kameleon/src/ccmc/MathHelper.cpp", "max_issues_repo_name": "alexanderbock/Kameleon-Converter", "max_issues_repo_head_hexsha": "6c2e66bfea60b17a369a3615bc1a623bba100a6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ext/kameleon/src/ccmc/MathHelper.cpp", "max_forks_repo_name": "alexanderbock/Kameleon-Converter", "max_forks_repo_head_hexsha": "6c2e66bfea60b17a369a3615bc1a623bba100a6f", "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.6470588235, "max_line_length": 103, "alphanum_fraction": 0.5140669516, "num_tokens": 1836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.504682123349295}}
{"text": "#ifndef PEOPLE_TRACKER_HPP\n#define PEOPLE_TRACKER_HPP\n\n#include <vector>\n#include <unordered_map>\n#include <Eigen/Dense>\n#include <boost/optional.hpp>\n#include <opencv2/opencv.hpp>\n\n#include <kkl/alg/data_association.hpp>\n#include <kkl/alg/nearest_neighbor_association.hpp>\n\n#include <hdl_people_tracking/Cluster.h>\n#include <hdl_people_tracking/kalman_tracker.hpp>\n\nnamespace kkl {\n  namespace alg {\n\n/**\n * @brief definition of the distance between tracker and observation for data association\n */\ntemplate<>\nboost::optional<double> distance(const std::shared_ptr<hdl_people_tracking::KalmanTracker>& tracker, const hdl_people_tracking::Cluster& observation) {\n  Eigen::Vector3d pos(observation.centroid.x, observation.centroid.y, observation.centroid.z);\n  double sq_mahalanobis = tracker->squaredMahalanobisDistance(pos);\n\n  // gating\n  if(sq_mahalanobis > pow(3.0, 2) || (tracker->position() - pos).norm() > 1.5) {\n    return boost::none;\n  }\n  return -kkl::math::gaussianProbMul(tracker->position(), tracker->positionCov(), pos);\n}\n  }\n}\n\nnamespace hdl_people_tracking {\n\n/**\n * @brief People tracker\n */\nclass PeopleTracker {\npublic:\n  PeopleTracker(ros::NodeHandle& private_nh) {\n    id_gen = 0;\n    human_radius = private_nh.param<double>(\"human_radius\", 0.4);\n    remove_trace_thresh = private_nh.param<double>(\"remove_trace_thresh\", 1.0);\n\n    data_association.reset(new kkl::alg::NearestNeighborAssociation<KalmanTracker::Ptr, Cluster>());\n//    data_association.reset(new kkl::alg::GlobalNearestNeighborAssociation<KalmanTracker::Ptr, VisualDetection>());\n  }\n\n  /**\n   * @brief predict people states\n   * @param time  current time\n   */\n  void predict(const ros::Time& time) {\n    for(auto& person : people) {\n      person->predict(time);\n    }\n  }\n\n  /**\n   * @brief correct people states\n   * @param time          current time\n   * @param detections    detections\n   */\n  void correct(const ros::Time& time, const std::vector<Cluster>& detections) {\n    // data association\n    std::vector<bool> associated(detections.size(), false);\n    auto associations = data_association->associate(people, detections);\n    for(const auto& assoc : associations) {\n      associated[assoc.observation] = true;\n      const auto& observation = detections[assoc.observation].centroid;\n      Eigen::Vector3d observation_pos(observation.x, observation.y, observation.z);\n      people[assoc.tracker]->correct(time, observation_pos, detections[assoc.observation]);\n    }\n\n    // generate new tracks\n    for(int i=0; i<detections.size(); i++) {\n      if(!associated[i]) {\n        // check if the detection is far from existing tracks\n        const auto& observation = detections[i].centroid;\n        Eigen::Vector3d observation_pos(observation.x, observation.y, observation.z);\n\n        bool close_to_tracker = false;\n        for(const auto& person : people) {\n\n          if((person->position() - observation_pos).norm() < human_radius * 2.0) {\n            close_to_tracker = true;\n            break;\n          }\n        }\n\n        if(close_to_tracker) {\n          continue;\n        }\n\n        // generate a new track\n        KalmanTracker::Ptr tracker(new KalmanTracker(id_gen++, time, observation_pos));\n        people.push_back(tracker);\n      }\n    }\n\n    // remove tracks with large covariance\n    auto remove_loc = std::partition(people.begin(), people.end(), [&](const KalmanTracker::Ptr& tracker) {\n      return tracker->positionCov().trace() < remove_trace_thresh;\n    });\n    removed_people.clear();\n    std::copy(remove_loc, people.end(), std::back_inserter(removed_people));\n    people.erase(remove_loc, people.end());\n  }\n\npublic:\n  long id_gen;                  // track ID which will be assigned to the next new track\n  double human_radius;          // new tracks must be far from existing tracks than this value\n  double remove_trace_thresh;   // tracks with larger covariance trace than this will be removed\n\n  std::vector<KalmanTracker::Ptr> people;\n  std::vector<KalmanTracker::Ptr> removed_people;\n  std::unique_ptr<kkl::alg::DataAssociation<KalmanTracker::Ptr, Cluster>> data_association;\n};\n\n}\n\n#endif // PEOPLE_TRACKER_HPP\n", "meta": {"hexsha": "c1bc83836f29156582cde11882d82c7c38d395e3", "size": 4139, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hdl_people_tracking/people_tracker.hpp", "max_stars_repo_name": "y-lai/hdl_people_tracking", "max_stars_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 207.0, "max_stars_repo_stars_event_min_datetime": "2018-03-10T14:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T07:32:53.000Z", "max_issues_repo_path": "include/hdl_people_tracking/people_tracker.hpp", "max_issues_repo_name": "y-lai/hdl_people_tracking", "max_issues_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2018-02-19T10:50:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T19:44:55.000Z", "max_forks_repo_path": "include/hdl_people_tracking/people_tracker.hpp", "max_forks_repo_name": "y-lai/hdl_people_tracking", "max_forks_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 91.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T09:44:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T01:38:14.000Z", "avg_line_length": 32.8492063492, "max_line_length": 151, "alphanum_fraction": 0.6905049529, "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181876, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.5046794435311219}}
{"text": "#include <string>\n#include \"Decryptor.h\"\n#include \"RSA.h\"\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\nusing namespace Crypto;\nusing std::string;\n\nDecryptor::Decryptor(const PrivateKey *key) : text(\"\"), private_key(key)\n{\n};\n\n\nstring Decryptor::decryptString(CryptoString input)\n{\n  string cypher;\n\n  int256_t tmp;\n  int it;\n  for (it = 0; it < input.size(); it++)\n  {\n    tmp = powm(input[it], private_key->s, private_key->q * private_key->p);\n    cypher.push_back(tmp.convert_to<char>());\n  }\n\n  return cypher;\n}\n\nchar Decryptor::decryptChar(CryptoChar c) const\n{\n  CryptoChar res = powm(c, private_key->s, private_key->q * private_key->p);\n  return res.convert_to<int>();\n}", "meta": {"hexsha": "7a2e41786a9a6491123f1207c7ad4eb5bee4a121", "size": 715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Decryptor.cpp", "max_stars_repo_name": "weniseb/RSA_CPP", "max_stars_repo_head_hexsha": "ea819e30e133205e780df94c17dc5f9236ec9739", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T07:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:03:49.000Z", "max_issues_repo_path": "src/Decryptor.cpp", "max_issues_repo_name": "weniseb/RSA_CPP", "max_issues_repo_head_hexsha": "ea819e30e133205e780df94c17dc5f9236ec9739", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-01-10T13:03:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-22T19:12:02.000Z", "max_forks_repo_path": "src/Decryptor.cpp", "max_forks_repo_name": "weniseb/RSA_CPP", "max_forks_repo_head_hexsha": "ea819e30e133205e780df94c17dc5f9236ec9739", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-25T20:57:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T08:42:35.000Z", "avg_line_length": 21.0294117647, "max_line_length": 76, "alphanum_fraction": 0.6993006993, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.5046631935625326}}
{"text": "#include \"pch.h\"\n#include \"mechanics.h\"\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <vector>\n#include <sstream>\n#include <math.h>\n\ntemplate <typename T> int sgn(T val) {\n\treturn (T(0) < val) - (val < T(0));\n}\n\nclass Suspension\n{\n\n\t// variables\nprivate:\n\t// suffix ref stands for ref, so reference/initial coordinates can be easily\n\t// differentiated from coordinates of the same points during wheel movement\n\t// hardpoints\n\t// LCA\n\tEigen::Vector3f lca1ref;\n\tEigen::Vector3f lca2ref;\n\tEigen::Vector3f lca3ref;\n\n\tEigen::Vector3f uca1ref;\n\tEigen::Vector3f uca2ref;\n\tEigen::Vector3f uca3ref;\n\n\tEigen::Vector3f tr1ref;\n\tEigen::Vector3f tr2ref;\n\n\tEigen::Vector3f wcnref;\n\tEigen::Vector3f spnref;\n\n\n\n\n\tfloat wRadius;     // wheel radius\t\n\tfloat wVert;       // wheel vertical movement\t\n\tfloat wSteer;      // wheel steering movement\t\n\tint vertIncr;      // number of increments between reference position and upmost and downmost\n\tint steerIncr;     // number of increments between reference position and leftmost and rightmost\t\n\tfloat precision;   // precision- at what value has the iterator converged, in percentage- 0...1\n\n\tfloat wheelbase;\n\tfloat cogHeight;\n\n\tfloat driveBias;\n\tfloat brakeBias;\n\n\tint suspPos;      // front or rear suspension 0 for front, 1 for rear\t\n\tint drivePos;     // outboard or inboard drive 0 for outboard, 1 for inboard\t\n\tint brakePos;     // outboard or inboard brakes 0 for outboard, 1 for inboard\n\n\n\t// derived values\n\n\tEigen::Vector3f lca12;\n\tEigen::Vector3f uca12;\n\tEigen::MatrixXf lca3Glob;// (vertIncr * 2 + 1, 3);\n\tEigen::MatrixXf uca3Glob;// (vertIncr * 2 + 1, 3);\n\tEigen::MatrixXf tr1Glob;// (vertIncr * 2 + 1, 3);\n\tEigen::MatrixXf tr2Glob;// (vertIncr * 2 + 1, 3);\n\tEigen::MatrixXf wcnGlob;// (vertIncr * 2 + 1, 3);\n\tEigen::MatrixXf spnGlob;// (vertIncr * 2 + 1, 3);\n\tEigen::MatrixXf cpGlob;// (vertIncr * 2 + 1, 3);\n\n\npublic:\n\n\n\tSuspension(\n\t\tfloat* hps,\n\t\tfloat wRadiusin,\n\t\tfloat wheelbasein, float cogHeightin, float driveBiasin,\n\t\tfloat brakeBiasin, int suspPosin, int drivePosin, int brakePosin,\n\t\tfloat wVertin, float wSteerin,\n\t\tint vertIncrin, int steerIncrin, float precisionin) :\n\t\tlca3Glob(vertIncrin * 2 + 1, 3), uca3Glob(vertIncrin * 2 + 1, 3), \n\t\ttr1Glob(steerIncrin * 2 + 1, 3), \n\t\ttr2Glob((vertIncrin * 2 + 1) * (steerIncrin * 2 + 1), 3), wcnGlob((vertIncrin * 2 + 1) * (steerIncrin * 2 + 1), 3), \n\t\tspnGlob((vertIncrin * 2 + 1) * (steerIncrin * 2 + 1), 3), cpGlob((vertIncrin * 2 + 1) * (steerIncrin * 2 + 1), 3)\n\t{\n\t\tlca1ref << hps[0], hps[1], hps[2];\n\t\tlca2ref << hps[3], hps[4], hps[5];\n\t\tlca3ref << hps[6], hps[7], hps[8];\n\n\t\tuca1ref << hps[9], hps[10], hps[11];\n\t\tuca2ref << hps[12], hps[13], hps[14];\n\t\tuca3ref << hps[15], hps[16], hps[17];\n\n\t\ttr1ref << hps[18], hps[19], hps[20];\n\t\ttr2ref << hps[21], hps[22], hps[23];\n\n\t\twcnref << hps[24], hps[25], hps[26];\n\t\tspnref << hps[27], hps[28], hps[29];\n\n\t\twRadius = wRadiusin;\n\n\t\twheelbase = wheelbasein;\n\t\tcogHeight = cogHeightin;\n\t\tdriveBias = driveBiasin;\n\n\t\tbrakeBias = brakeBiasin;\n\n\t\tsuspPos = suspPosin;\n\t\tdrivePos = drivePosin;\n\t\tbrakePos = brakePosin;\n\n\t\twVert = wVertin;\n\t\twSteer = wSteerin;\n\t\tvertIncr = vertIncrin;\n\t\tsteerIncr = steerIncrin;\n\t\tprecision = precisionin;\n\n\t}\n\n\n\t// FUNCTIONS\nprivate:\n\n\t// place as inputs variables rLCA, rUCA, uca12, lca12, etc. so those can be only temporary\n\t// values and not use up stack memory\n\n\tvoid CalculateConstants(\n\t\tEigen::Matrix3f& _rotLCA, Eigen::Matrix3f& _rotUCA,\n\t\tfloat& _rLCA, float& _rUCA, float& _rCA,\n\t\tEigen::ArrayXf& _zLocLca,\n\t\tfloat& _rST, float& _t_param, float& _rTR,\n\t\tEigen::Vector3f& _wcnlocTRk, Eigen::Vector3f& _spnlocTRk)\n\t{\n\n\t\t// create line connecting lca1 and lca2\n\t\tEigen::ParametrizedLine<float, 3> lca1lca2 = Eigen::ParametrizedLine<float, 3>::Through(lca1ref, lca2ref);\n\n\t\t// local LCA plane for determining max z value of wheel parameters\n\t\tEigen::Vector4f abcd;\n\t\tEigen::Vector3f _tr2prref;\n\n\t\t// z local maximum value\n\t\tfloat zLocHi;\n\t\t// z local minimum value\n\t\tfloat zLocLo;\n\n\t\tlca12 = lca1lca2.projection(lca3ref);\n\t\t_rLCA = lca1lca2.distance(lca3ref);\n\n\t\t// create rotation matrix for LCA cs\n\t\t_rotLCA <<\n\t\t\t(lca1ref - lca2ref).normalized(),\n\t\t\t(lca12 - lca3ref).normalized(),\n\t\t\t((lca1ref - lca2ref).cross(lca12 - lca3ref)).normalized();\n\n\t\t// calculate parameters for plane in LCA cs ax+by+cz+d=0\n\t\tabcd <<\n\t\t\t_rotLCA.row(2)(0),\n\t\t\t_rotLCA.row(2)(1),\n\t\t\t_rotLCA.row(2)(2),\n\t\t\t-_rotLCA.row(2) * (_rotLCA.transpose() * Eigen::Vector3f{ -lca12(0),-lca12(1),lca3ref(2) - wVert - lca12(2) });\n\t\t// calculates z value for upmost movement of wheel for intersection of plane and circle in LCA\n\t\tzLocHi =\n\t\t\t(-abcd(2) * abcd(3) +\n\t\t\t\tabcd(1) * sqrt(abcd(2) * abcd(2) * _rLCA * _rLCA +\n\t\t\t\t\tabcd(1) * abcd(1) * _rLCA * _rLCA -\n\t\t\t\t\tabcd(3) * abcd(3))) /\n\t\t\t(abcd(1) * abcd(1) + abcd(2) * abcd(2));\n\n\t\t// reuses previous parameters for LCA plane, only 4th parameter is changed\n\t\tabcd(3) =\n\t\t\t-_rotLCA.row(2) *\n\t\t\t_rotLCA.transpose() *\n\t\t\tEigen::Vector3f{ -lca12(0), -lca12(1), lca3ref(2) + wVert - lca12(2) };\n\n\t\t// calculates z value for downmost movement of wheel for intersection of plane and circle in LCA\n\t\tzLocLo =\n\t\t\t(-abcd(2) * abcd(3) +\n\t\t\t\tabcd(1) * sqrt(abcd(2) * abcd(2) * _rLCA * _rLCA +\n\t\t\t\t\tabcd(1) * abcd(1) * _rLCA * _rLCA -\n\t\t\t\t\tabcd(3) * abcd(3))) /\n\t\t\t(abcd(1) * abcd(1) + abcd(2) * abcd(2));\n\n\t\t// wheel travel from rebound to bump\n\t\t_zLocLca <<\n\t\t\tEigen::VectorXf::LinSpaced(vertIncr, zLocLo, zLocLo / vertIncr),\n\t\t\t0,\n\t\t\tEigen::VectorXf::LinSpaced(vertIncr, zLocHi / vertIncr, zLocHi);\n\n\n\t\t// create line connecting uca1 and uca2\n\t\tEigen::ParametrizedLine<float, 3> uca1uca2 = Eigen::ParametrizedLine<float, 3>::Through(uca1ref, uca2ref);\n\n\t\tuca12 = uca1uca2.projection(uca3ref);\n\t\t_rUCA = uca1uca2.distance(uca3ref);\n\n\t\t_rCA = (uca3ref - lca3ref).norm();\n\n\t\t// create rotation matrix for UCA cs\n\t\t_rotUCA <<\n\t\t\t(uca1ref - uca2ref).normalized(),\n\t\t\t(uca12 - uca3ref).normalized(),\n\t\t\t((uca1ref - uca2ref).cross(uca12 - uca3ref)).normalized();\n\n\n\t\t// calculate TR2 projection point and rTR\n\t\tEigen::ParametrizedLine<float, 3> lca3uca3 = Eigen::ParametrizedLine<float, 3>::Through(lca3ref, uca3ref);\n\n\t\t_tr2prref = lca3uca3.projection(tr2ref);\n\n\t\t_rST = (tr2ref - _tr2prref).norm();\n\n\t\t_rTR = (tr2ref - tr1ref).norm();\n\n\t\t_t_param = (_tr2prref(2) - lca3ref(2)) / (uca3ref(2) - lca3ref(2));\n\n\n\n\t\tEigen::Matrix3f _rotTRk; // TR rotation matrix defined by TR2ref\n\n\t\tEigen::Vector3f _xCol{ _tr2prref - tr2ref };\n\t\tEigen::Vector3f _zCol{ lca3ref - uca3ref };\n\t\tEigen::Vector3f _yCol{ _zCol.cross(_xCol) };\n\n\n\t\t_rotTRk.col(0) << _xCol / _xCol.norm();\n\t\t_rotTRk.col(1) << _yCol / _yCol.norm();\n\t\t_rotTRk.col(2) << _zCol / _zCol.norm();\n\n\t\t_wcnlocTRk << _rotTRk.transpose() * (wcnref - _tr2prref);\n\t\t_spnlocTRk << _rotTRk.transpose() * (spnref - _tr2prref);\n\t}\n\npublic:\n\n\tvoid CalculateMovement()\n\t{\n\t\tEigen::Matrix3f rotLCA;\n\t\tEigen::Matrix3f rotUCA;\n\t\tEigen::MatrixXf tr2prGlob;\n\t\tfloat rLCA;\n\t\tfloat rUCA;\n\t\tfloat rCA;   // distance between LCA3 and UCA3\n\t\tfloat rST;   // distance between TR2 and UCA3LCA3 axis\n\t\tfloat rTR;   // distance between TR2 and TR1 axis\n\t\tfloat t_param;   // parameter to determine position of TR2pr on uca3lca3 line\n\t\t// coordinates of wcn and spn in TR cs defined by tr2ref\n\t\tEigen::Vector3f wcnlocTRk;\n\t\tEigen::Vector3f spnlocTRk;\n\n\t\tEigen::ArrayXf zLCA3LocLCA(vertIncr * 2 + 1);\n\n\t\tSuspension::CalculateConstants(rotLCA, rotUCA, rLCA, rUCA, rCA, zLCA3LocLCA, rST, t_param, rTR, wcnlocTRk, spnlocTRk);\n\n\n\n\t\tEigen::MatrixXf lca3LocLCA(vertIncr * 2 + 1, 3);\n\n\t\t// populating positions of local LCA3 in a matrix\n\t\tlca3LocLCA.col(0) << Eigen::VectorXf::Zero(vertIncr * 2 + 1);\n\t\tlca3LocLCA.col(1) << -(rLCA * rLCA - zLCA3LocLCA * zLCA3LocLCA).sqrt();\n\t\tlca3LocLCA.col(2) << zLCA3LocLCA;\n\n\n\n\n\t\t// global positions of LCA3 for whole wheel movement\n\t\tlca3Glob = (lca3LocLCA * rotLCA.transpose()).array().rowwise() + lca12.array().transpose();\n\n\n\t\t// global position of UCA3 for whole wheel movement\n\t\tEigen::MatrixXf uca3LocUCA(vertIncr * 2 + 1, 3);\n\t\tEigen::MatrixXf lca3LocUCA(vertIncr * 2 + 1, 3);\n\n\t\tlca3LocUCA = lca3Glob.rowwise() - uca12.transpose();\n\t\tlca3LocUCA = lca3LocUCA * rotUCA;\n\n\n\t\t// temporary values for calculating UCA3 in UCA cs, correspond to chunks of expression in word\n\t\tEigen::ArrayXf temp1UCA3 =\n\t\t\t-rCA * rCA + rUCA * rUCA +\n\t\t\tlca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() +\n\t\t\tlca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() +\n\t\t\tlca3LocUCA.col(2).array() * lca3LocUCA.col(2).array();\n\n\t\tEigen::ArrayXf temp2UCA3 =\n\t\t\t2 * (lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() +\n\t\t\t\tlca3LocUCA.col(2).array() * lca3LocUCA.col(2).array());\n\n\t\tEigen::ArrayXf temp3UCA3 =\n\t\t\t-rCA * rCA * rCA * rCA + 2 * rCA * rCA * rUCA * rUCA +\n\t\t\t2 * rCA * rCA * lca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() +\n\t\t\t2 * rCA * rCA * lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() +\n\t\t\t2 * rCA * rCA * lca3LocUCA.col(2).array() * lca3LocUCA.col(2).array();\n\n\t\tEigen::ArrayXf temp4UCA3 =\n\t\t\t-rUCA * rUCA * rUCA * rUCA -\n\t\t\t2 * rUCA * rUCA * lca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() +\n\t\t\t2 * rUCA * rUCA * lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() +\n\t\t\t2 * rUCA * rUCA * lca3LocUCA.col(2).array() * lca3LocUCA.col(2).array();\n\n\t\tEigen::ArrayXf temp5UCA3 =\n\t\t\t-lca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() -\n\t\t\t2 * lca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() * lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() -\n\t\t\t2 * lca3LocUCA.col(0).array() * lca3LocUCA.col(0).array() * lca3LocUCA.col(2).array() * lca3LocUCA.col(2).array();\n\n\t\tEigen::ArrayXf temp6UCA3 =\n\t\t\t-2 * lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() * lca3LocUCA.col(2).array() * lca3LocUCA.col(2).array() -\n\t\t\tlca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() * lca3LocUCA.col(1).array() -\n\t\t\tlca3LocUCA.col(2).array() * lca3LocUCA.col(2).array() * lca3LocUCA.col(2).array() * lca3LocUCA.col(2).array();\n\n\t\tEigen::ArrayXf temp7UCA3 = (temp3UCA3 + temp4UCA3 + temp5UCA3 + temp6UCA3).sqrt();\n\n\t\tuca3LocUCA.col(0) << Eigen::VectorXf::Zero(vertIncr * 2 + 1);\n\t\tuca3LocUCA.col(1) << (lca3LocUCA.col(1).array() * temp1UCA3 - lca3LocUCA.col(2).array() * temp7UCA3) / temp2UCA3;\n\t\tuca3LocUCA.col(2) << (lca3LocUCA.col(2).array() * temp1UCA3 + lca3LocUCA.col(1).array() * temp7UCA3) / temp2UCA3;\n\n\n\t\tuca3Glob = (uca3LocUCA * rotUCA.transpose()).array().rowwise() + uca12.array().transpose();\n\n\t\t\n\n\t\t// calculating TR2 positions\n\n\t\ttr1Glob.col(0) <<\n\t\t\tEigen::VectorXf::LinSpaced(2 * steerIncr + 1, tr1ref(0), tr1ref(0));\n\t\ttr1Glob.col(1) <<\n\t\t\tEigen::VectorXf::LinSpaced(steerIncr, tr1ref(1) - wSteer, tr1ref(1) - wSteer / steerIncr),\n\t\t\ttr1ref(1),\n\t\t\tEigen::VectorXf::LinSpaced(steerIncr, tr1ref(1) + wSteer / steerIncr, tr1ref(1) + wSteer);\n\t\ttr1Glob.col(2) <<\n\t\t\tEigen::VectorXf::LinSpaced(2 * steerIncr + 1, tr1ref(2), tr1ref(2));\n\n\t\ttr2prGlob = (uca3Glob - lca3Glob) * t_param + lca3Glob;\n\n\n\t\tfor (int i = 0; i < vertIncr * 2 + 1; i++)\n\t\t{\n\t\t\tEigen::Matrix3f rotTR;\n\t\t\tEigen::Vector3f tr2locTR;\n\n\t\t\tEigen::Vector3f xCol{ 30, 0, -30 * (uca3Glob(i, 0) - lca3Glob(i, 0)) / (uca3Glob(i, 2) - lca3Glob(i, 2)) };\n\t\t\tEigen::Vector3f zCol{ (lca3Glob.row(i) - uca3Glob.row(i)).transpose() };\n\t\t\tEigen::Vector3f yCol{ zCol.cross(xCol) };\n\n\n\t\t\trotTR.col(0) << xCol / xCol.norm();\n\t\t\trotTR.col(1) << yCol / yCol.norm();\n\t\t\trotTR.col(2) << zCol / zCol.norm();\n\t\t\tfor (int j = 0; j < steerIncr * 2 + 1; j++)\n\t\t\t{\n\t\t\t\t// calculate local position of TR1\n\t\t\t\tEigen::Vector3f tr1locTR;\n\n\t\t\t\ttr1locTR = -tr2prGlob.row(i) + tr1Glob.row(j);\n\t\t\t\ttr1locTR = rotTR.transpose() * tr1locTR;\n\n\n\t\t\t\t// calculate local position of TR2\n\t\t\t\tfloat temp1TR2 =\n\t\t\t\t\trST * rST - rTR * rTR +\n\t\t\t\t\ttr1locTR(0) * tr1locTR(0) +\n\t\t\t\t\ttr1locTR(1) * tr1locTR(1) +\n\t\t\t\t\ttr1locTR(2) * tr1locTR(2);\n\n\t\t\t\tfloat temp2TR2 = 2 * (tr1locTR(0) * tr1locTR(0) + tr1locTR(1) * tr1locTR(1));\n\n\t\t\t\tfloat temp3TR2 =\n\t\t\t\t\t-rST * rST * rST * rST + 2 * rTR * rTR * rST * rST +\n\t\t\t\t\t2 * rST * rST * tr1locTR(0) * tr1locTR(0) +\n\t\t\t\t\t2 * rST * rST * tr1locTR(1) * tr1locTR(1) -\n\t\t\t\t\t2 * rST * rST * tr1locTR(2) * tr1locTR(2);\n\n\t\t\t\tfloat temp4TR2 =\n\t\t\t\t\t-rTR * rTR * rTR * rTR +\n\t\t\t\t\t2 * rTR * rTR * tr1locTR(0) * tr1locTR(0) +\n\t\t\t\t\t2 * rTR * rTR * tr1locTR(1) * tr1locTR(1) +\n\t\t\t\t\t2 * rTR * rTR * tr1locTR(2) * tr1locTR(2);\n\n\t\t\t\tfloat temp5TR2 =\n\t\t\t\t\t-tr1locTR(0) * tr1locTR(0) * tr1locTR(0) * tr1locTR(0) -\n\t\t\t\t\t2 * tr1locTR(0) * tr1locTR(0) * tr1locTR(1) * tr1locTR(1) -\n\t\t\t\t\t2 * tr1locTR(0) * tr1locTR(0) * tr1locTR(2) * tr1locTR(2);\n\n\t\t\t\tfloat temp6TR2 =\n\t\t\t\t\t-2 * tr1locTR(1) * tr1locTR(1) * tr1locTR(2) * tr1locTR(2) -\n\t\t\t\t\ttr1locTR(1) * tr1locTR(1) * tr1locTR(1) * tr1locTR(1) -\n\t\t\t\t\ttr1locTR(2) * tr1locTR(2) * tr1locTR(2) * tr1locTR(2);\n\n\t\t\t\tfloat temp7TR2 = sgn(wcnref[0] - tr2ref[0]) * std::sqrt(temp3TR2 + temp4TR2 + temp5TR2 + temp6TR2);\n\n\n\n\t\t\t\ttr2locTR(0) = (tr1locTR(0) * temp1TR2 - tr1locTR(1) * temp7TR2) / temp2TR2;\n\t\t\t\ttr2locTR(1) = (tr1locTR(1) * temp1TR2 + tr1locTR(0) * temp7TR2) / temp2TR2;\n\t\t\t\ttr2locTR(2) = 0;\n\n\t\t\t\ttr2Glob.row(i * (2 * steerIncr + 1) + j) << (rotTR * tr2locTR).transpose() + tr2prGlob.row(i);\n\n\n\n\t\t\t\t// calculating WCN and SPN \n\t\t\t\tEigen::Matrix3f _rotTRk; // TR rotation matrix defined by TR2ref\n\n\t\t\t\tEigen::Vector3f _xCol{ tr2prGlob.row(i) - tr2Glob.row(i * (2 * steerIncr + 1) + j) };\n\t\t\t\tEigen::Vector3f _zCol{ lca3Glob.row(i) - uca3Glob.row(i) };\n\t\t\t\tEigen::Vector3f _yCol{ _zCol.cross(_xCol) };\n\n\n\t\t\t\t_rotTRk.col(0) << _xCol / _xCol.norm();\n\t\t\t\t_rotTRk.col(1) << _yCol / _yCol.norm();\n\t\t\t\t_rotTRk.col(2) << _zCol / _zCol.norm();\n\n\t\t\t\twcnGlob.row(i * (2 * steerIncr + 1) + j) << (_rotTRk * wcnlocTRk).transpose() + tr2prGlob.row(i);\n\t\t\t\tspnGlob.row(i * (2 * steerIncr + 1) + j) << (_rotTRk * spnlocTRk).transpose() + tr2prGlob.row(i);\n\n\n\t\t\t\t// CP calculation\n\t\t\t\tfloat temp1cp{ -20 }; // this is actually vector 0,0,-20\n\t\t\t\tEigen::MatrixXf temp2cp((vertIncr * 2 + 1) * (steerIncr * 2 + 1), 3);\n\t\t\t\tEigen::MatrixXf temp3cp((vertIncr * 2 + 1) * (steerIncr * 2 + 1), 3);\n\n\t\t\t\ttemp2cp << spnGlob - wcnGlob;\n\n\t\t\t\ttemp3cp.col(0) << -temp2cp.col(0).array() * temp2cp.col(2).array() * temp1cp;\n\t\t\t\ttemp3cp.col(1) << -temp2cp.col(1).array() * temp2cp.col(2).array() * temp1cp;\n\t\t\t\ttemp3cp.col(2) <<\n\t\t\t\t\ttemp2cp.col(1).array() * temp2cp.col(1).array() * temp1cp +\n\t\t\t\t\ttemp2cp.col(0).array() * temp2cp.col(0).array() * temp1cp;\n\n\t\t\t\ttemp3cp.rowwise().normalize();\n\n\n\t\t\t\tcpGlob << -temp3cp * wRadius + wcnGlob;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid LogToConsole()\n\t{\n\n\t\tstd::cout << \"lca3\\n \" << lca3Glob << \"\\n\";\n\t\tstd::cout << \"\\n\";\n\t\tstd::cout << \"uca3\\n \" << uca3Glob << \"\\n\";\n\t\tstd::cout << \"\\n\";\n\n\t\tstd::cout << \"tr1\\n \" << tr1Glob << \"\\n\";\n\t\tstd::cout << \"\\n\";\n\n\t\tstd::cout << \"tr2\\n \" << tr2Glob << \"\\n\";\n\t\tstd::cout << \"\\n\";\n\n\t\tstd::cout << \"wcn\\n \" << wcnGlob << \"\\n\";\n\t\tstd::cout << \"\\n\";\n\n\t\tstd::cout << \"spn\\n \" << spnGlob << \"\\n\";\n\t\tstd::cout << \"\\n\";\n\n\t\tstd::cout << \"cp\\n \" << cpGlob << \"\\n\";\n\t\tstd::cout << \"\\n\";\n\n\t}\n\n\tfloat ObjFuncModule(float peakWidth, float flatness, float variable, float target)\n\t{\n\t\treturn (float)exp(-1 / peakWidth * pow(abs(variable - target), flatness));\n\t}\n\n\tfloat GetObjFuncScore(float* peakWidth, float* flatness, float* variables, float* targets, float* weightFactors)\n\t{\n\n\t\tfloat objFuncScore = 1.0f;\n\n\t\tfor (int i = 0; i < 21; i++)\n\t\t\tobjFuncScore -= weightFactors[i] * ObjFuncModule(peakWidth[i], flatness[i], variables[i], targets[i]);\n\n\t\treturn objFuncScore;\n\t}\n\n\tfloat GetCamberAngle(int vertPos, int steerPos)\n\t{\n\t\tfloat camberAngle;\n\t\tint L = vertPos * (2 * steerIncr + 1) + steerPos;\n\t\tint R = (2 * vertIncr - vertPos) * (2 * steerIncr + 1) + 2 * steerIncr - steerPos;\n\n\n\t\tEigen::Vector3f wheelAxis{\n\t\t\t-wcnGlob.row(L)(0) + cpGlob.row(L)(0),\n\t\t\t-wcnGlob.row(L)(1) + cpGlob.row(L)(1),\n\t\t\t-wcnGlob.row(L)(2) + cpGlob.row(L)(2)\n\t\t};\n\n\n\t\tEigen::Vector3f groundNormal{\n\t\t\t0,\n\t\t\t-cpGlob.row(R)(2) + cpGlob.row(L)(2),\n\t\t\t-cpGlob.row(R)(1) - cpGlob.row(L)(1)\n\t\t};\n\t\t\n\t\t// calculate plane parallel to ground going through SPN point with respect to which camber is measured\n\t\tfloat temp1_wcnpr =\n\t\t\tspnGlob.row(L)(1) * groundNormal(1)\n\t\t\t+ spnGlob.row(L)(2) * groundNormal(2)\n\t\t\t- wcnGlob.row(L)(1) * groundNormal(1)\n\t\t\t- wcnGlob.row(L)(2) * groundNormal(2);\n\t\tfloat temp2_wcnpr =\n\t\t\tgroundNormal(1) * groundNormal(1) +\n\t\t\tgroundNormal(2) * groundNormal(2);\n\n\t\tEigen::Vector3f wcnpr{\n\t\t\twcnGlob.row(L)(0),\n\t\t\twcnGlob.row(L)(1) + groundNormal(1) * temp1_wcnpr / temp2_wcnpr,\n\t\t\twcnGlob.row(L)(2) + groundNormal(2) * temp1_wcnpr / temp2_wcnpr\n\t\t};\n\n\t\tfloat camber =\n\t\t\t(wcnpr - (Eigen::Vector3f)wcnGlob.row(L)).norm() /\n\t\t\t((Eigen::Vector3f)spnGlob.row(L) -\n\t\t\t\t(Eigen::Vector3f)wcnGlob.row(L)).norm();\n\n\t\t// tests if camber is negative, if it is it returns negative angle\n\t\tif ((wcnpr - (Eigen::Vector3f)wcnGlob.row(L))(2) > 0)\n\t\t{\n\t\t\tcamberAngle = -asin(camber) * 180 / 3.14159f;\n\t\t\treturn camberAngle;\n\t\t}\n\n\t\t// if camber is not negative, returns positive angle\n\t\telse\n\t\t{\n\t\t\tcamberAngle = asin(camber) * 180 / 3.14159f;\n\t\t\treturn camberAngle;\n\t\t}\n\t}\n\n\tfloat GetToeAngle(int vertPos, int steerPos)\n\t{\n\t\tint position = vertPos * (2 * steerIncr + 1) + steerPos;\n\t\t// positive toe angle for toe in and negative for toe out\n\t\tEigen::Vector3d wheelAxis{\n\t\t\t(double)(wcnGlob.row(position)(0) - spnGlob.row(position)(0)),\n\t\t\t(double)(wcnGlob.row(position)(1) - spnGlob.row(position)(1)),\n\t\t\t(double)(wcnGlob.row(position)(2) - spnGlob.row(position)(2))\n\t\t};\n\t\t\t//(Eigen::Vector3d)(wcnGlob.row(position) - spnGlob.row(position));\n\t\tEigen::Vector3d refAxis{\n\t\t\t0.0,\n\t\t\t(double)(wcnGlob.row(position)(1) - spnGlob.row(position)(1)),\n\t\t\t(double)(wcnGlob.row(position)(2) - spnGlob.row(position)(2))\n\t\t};\n\n\t\tif (wcnGlob.row(position)(0) < spnGlob.row(position)(0)) // toe out case\n\t\t\treturn float(-acos(refAxis.norm() / wheelAxis.norm()) * 180.0 / 3.14159);\n\n\t\telse // toe in case\n\t\t\treturn float(acos(refAxis.norm() / wheelAxis.norm()) * 180.0 / 3.14159);\n\t}\n\n\tfloat GetCasterAngle(int vertPos)\n\t{\n\t\tint position = vertPos;\n\t\tfloat casterAngle;\n\t\tfloat caster =\n\t\t\tatan2f(\n\t\t\t\t(lca3Glob.row(position)(0) - uca3Glob.row(position)(0))\n\t\t\t\t, (-uca3Glob.row(position)(2) + lca3Glob.row(position)(2)));\n\n\t\tcasterAngle = caster * 180 / 3.14159f;\n\t\treturn casterAngle;\n\t}\n\n\tfloat GetRollCentreHeight(int vertPos, int steerPos)\n\t{\n\t\tfloat rollCentreHeight;\n\n\t\tint Lv = vertPos;\t\t\t\t\t\t\t// Left wheel only vertical position, UCA3, LCA3 points\n\t\tint Rv = 2 * vertIncr - vertPos;\t\t// Right wheel only vertical position, UCA3, LCA3 points\n\n\t\tint Lvs = vertPos * (2 * steerIncr + 1) + steerPos;\t\t\t\t\t\t\t\t\t  // Left wheel position including vertical and steering movement\n\t\tint Rvs = (2 * vertIncr - vertPos) * (2 * steerIncr + 1) + 2 * steerIncr - steerPos;  // Right wheel position including vertical and steering movement\n\n\n\t\tfloat slopePrecision{ 0.001f }; // if difference between slopes is less than this value, than they are considered parallel\n\n\t\tEigen::Vector3f lca3L{ lca3Glob.row(Lv) };\n\t\tEigen::Vector3f uca3L{ uca3Glob.row(Lv) };\n\t\tEigen::Vector3f cpL{ cpGlob.row(Lvs) };\n\n\t\tEigen::Vector3f lca1R{ lca1ref(0), -lca1ref(1), lca1ref(2) };\n\t\tEigen::Vector3f lca2R{ lca2ref(0), -lca2ref(1), lca2ref(2) };\n\t\tEigen::Vector3f lca3R{ lca3Glob.row(Rv)(0), -lca3Glob.row(Rv)(1), lca3Glob.row(Rv)(2) };\n\n\t\tEigen::Vector3f uca1R{ uca1ref(0), -uca1ref(1), uca1ref(2) };\n\t\tEigen::Vector3f uca2R{ uca2ref(0), -uca2ref(1), uca2ref(2) };\n\t\tEigen::Vector3f uca3R{ uca3Glob.row(Rv)(0), -uca3Glob.row(Rv)(1), uca3Glob.row(Rv)(2) };\n\t\tEigen::Vector3f cpR{ cpGlob.row(Rvs)(0), -cpGlob.row(Rvs)(1), cpGlob.row(Rvs)(2) };\n\n\t\tfloat aLCAL;\n\t\tfloat aUCAL;\n\t\tfloat aLCAR;\n\t\tfloat aUCAR;\n\n\t\tfloat bLCAL;\n\t\tfloat bUCAL;\n\t\tfloat bLCAR;\n\t\tfloat bUCAR;\n\n\t\t// LCA and UCA plane intersection with plane parallel to YZ plane with x coord CPR/2+CPL/2\n\t\t// lambda function that defines first point of intersection line\n\t\tauto intersectionLineCalc = [cpL, cpR](float& aCa, float& bCa, const Eigen::Vector3f& ca1, const Eigen::Vector3f& ca2, const Eigen::Vector3f& ca3)\n\t\t{\n\t\t\t// plane coefficients Ax + By + Cz + D = 0, plane defined by control arm\n\t\t\tfloat A = (-ca1[1] + ca2[1]) * (-ca1[2] + ca3[2]) - (-ca1[1] + ca3[1]) * (-ca1[2] + ca2[2]);\n\t\t\tfloat B = -(-ca1[0] + ca2[0]) * (-ca1[2] + ca3[2]) + (-ca1[0] + ca3[0]) * (-ca1[2] + ca2[2]);\n\t\t\tfloat C = (-ca1[0] + ca2[0]) * (-ca1[1] + ca3[1]) - (-ca1[0] + ca3[0]) * (-ca1[1] + ca2[1]);\n\t\t\tfloat D = -ca1[0] * A - ca1[1] * B - ca1[2] * C;\n\n\t\t\t// intersection plane defined  as x + D2 = 0\n\t\t\tfloat D2 = -(cpL[0] + cpR[0]) / 2;\n\n\t\t\taCa = -B / C;\n\t\t\tbCa = (A * D2 - D) / C;\n\t\t};\n\n\t\tintersectionLineCalc(aLCAL, bLCAL, lca1ref, lca2ref, lca3L);\n\t\tintersectionLineCalc(aUCAL, bUCAL, uca1ref, uca2ref, uca3L);\n\t\tintersectionLineCalc(aLCAR, bLCAR, lca1R, lca2R, lca3R);\n\t\tintersectionLineCalc(aUCAR, bUCAR, uca1R, uca2R, uca3R);\n\n\t\tfloat aICL;\n\t\tfloat aICR;\n\t\tfloat bICL;\n\t\tfloat bICR;\n\n\t\t// CALCULATE LEFT SIDE\n\t\t// case if LEFT LCA and UCA are parallel\n\t\tif (abs(aLCAL - aUCAL) / abs(aLCAL) < precision)\n\t\t{\n\t\t\taICL = aLCAL;\n\t\t\tbICL = cpL(2) - aLCAL * cpL(1);\n\t\t}\n\t\t// case if LEFT LCA and UCA are NOT parallel\n\t\telse\n\t\t{\n\t\t\tfloat ICLz = (aLCAL * bUCAL - aUCAL * bLCAL) / (aLCAL - aUCAL);\n\t\t\tfloat ICLy = (-bLCAL + bUCAL) / (aLCAL - aUCAL);\n\n\t\t\taICL = (ICLz - cpL(2)) / (ICLy - cpL(1));\n\t\t\tbICL = -cpL(1) * aICL + cpL(2);\n\t\t}\n\n\t\t// CALCULATE RIGHT SIDE\n\t\t// case if RIGHT LCA and UCA are parallel\n\t\tif (abs(aLCAR - aUCAR) / abs(aLCAR) < precision)\n\t\t{\n\t\t\taICR = aLCAR;\n\t\t\tbICR = cpR(2) - aLCAR * cpR(1);\n\t\t}\n\t\t// case if RIGHT LCA and UCA are NOT parallel\n\t\telse\n\t\t{\n\t\t\tfloat ICRz = (aLCAR * bUCAR - aUCAR * bLCAR) / (aLCAR - aUCAR);\n\t\t\tfloat ICRy = (-bLCAR + bUCAR) / (aLCAR - aUCAR);\n\n\t\t\taICR = (ICRz - cpR(2)) / (ICRy - cpR(1));\n\t\t\tbICR = -cpR(1) * aICR + cpR(2);\n\t\t}\n\n\t\t// instantenous centre lines are parallel\n\t\tif (abs(aICR - aICL) / abs(aICR) < precision)\n\t\t{\n\t\t\trollCentreHeight = 0;\n\t\t\treturn rollCentreHeight;\n\t\t}\n\n\t\t// instantenous centre lines are NOT parallel\n\t\telse\n\t\t{\n\t\t\tfloat RCy = (bICL - bICR) / (aICR - aICL);\n\t\t\tfloat RCz = aICL * RCy + bICL;\n\n\t\t\trollCentreHeight =\n\t\t\t\t((cpR(1) - cpL(1)) * (cpL(2) - RCz) -\n\t\t\t\t\t(cpL(1) - RCy) * (cpR(2) - cpL(2))) /\n\t\t\t\tsqrt(pow((cpR(2) - cpL(2)), 2) + pow((cpR(1) - cpL(1)), 2));\n\t\t\treturn rollCentreHeight;\n\t\t}\n\t}\n\n\tfloat GetCasterTrail(int vertPos, int steerPos)\n\t{\n\t\tfloat casterTrail;\n\n\n\t\tint Lv = vertPos;\t\t\t\t\t\t\t// Left wheel only vertical position, UCA3, LCA3 points\n\t\tint Rv = 2 * vertIncr - vertPos;\t\t// Right wheel only vertical position, UCA3, LCA3 points\n\n\t\tint Lvs = vertPos * (2 * steerIncr + 1) + steerPos;\t\t\t\t\t\t\t\t\t  // Left wheel position including vertical and steering movement\n\t\tint Rvs = (2 * vertIncr - vertPos) * (2 * steerIncr + 1) + 2 * steerIncr - steerPos;  // Right wheel position including vertical and steering movement\n\n\n\t\t//int Lv = vertPos;\t\t\t\t\t\t\t// Left wheel only vertical position, UCA3, LCA3 points\n\t\t//int Rv = cpGlob.rows() - 1 - vertPos;\t\t// Right wheel only vertical position, UCA3, LCA3 points\n\n\t\t//int Lvs = vertPos * (2 * steerIncr + 1) + steerPos;\t\t\t\t\t\t\t// Left wheel position including vertical and steering movement\n\t\t//int Rvs = (cpGlob.rows() - 1 - vertPos) * (2 * steerIncr + 1) + steerPos;\t\t// Right wheel position including vertical and steering movement\n\n\t\tEigen::Vector3f cpL{ cpGlob.row(Lvs) };\n\t\tEigen::Vector3f cpR{ cpGlob.row(Rvs) };\n\t\tEigen::Vector3f wcn{ wcnGlob.row(Lvs) };\n\t\tEigen::Vector3f spn{ spnGlob.row(Lvs) };\n\t\tEigen::Vector3f lca3L{ lca3Glob.row(Lv) };\n\t\tEigen::Vector3f uca3L{ uca3Glob.row(Lv) };\n\n\t\tEigen::Vector3f grndNormal{\n\t\t\t0,\n\t\t\t-cpR(2) + cpL(2),\n\t\t\t-cpR(1) - cpL(1)\n\t\t};\n\n\t\tfloat wcnpr_temp1 =\n\t\t\tgrndNormal(0) * cpL(0) - grndNormal(0) * wcn(0) +\n\t\t\tgrndNormal(1) * cpL(1) - grndNormal(1) * wcn(1) +\n\t\t\tgrndNormal(2) * cpL(2) - grndNormal(2) * wcn(2);\n\n\t\tfloat wcnpr_temp2 =\n\t\t\tgrndNormal(0) * grndNormal(0) +\n\t\t\tgrndNormal(1) * grndNormal(1) +\n\t\t\tgrndNormal(2) * grndNormal(2);\n\n\t\tEigen::Vector3f wcnpr{\n\t\t\tgrndNormal(0) * wcnpr_temp1 / wcnpr_temp2 + wcn(0),\n\t\t\tgrndNormal(1) * wcnpr_temp1 / wcnpr_temp2 + wcn(1),\n\t\t\tgrndNormal(2) * wcnpr_temp1 / wcnpr_temp2 + wcn(2)\n\t\t};\n\n\t\tfloat spnpr_temp1 =\n\t\t\tgrndNormal(0) * cpL(0) - grndNormal(0) * wcn(0) +\n\t\t\tgrndNormal(1) * cpL(1) - grndNormal(1) * wcn(1) +\n\t\t\tgrndNormal(2) * cpL(2) - grndNormal(2) * wcn(2);\n\n\t\tfloat spnpr_temp2 =\n\t\t\tgrndNormal(0) * grndNormal(0) +\n\t\t\tgrndNormal(1) * grndNormal(1) +\n\t\t\tgrndNormal(2) * grndNormal(2);\n\n\t\tEigen::Vector3f spnpr{\n\t\t\tgrndNormal(0) * spnpr_temp1 / spnpr_temp2 + spn(0),\n\t\t\tgrndNormal(1) * spnpr_temp1 / spnpr_temp2 + spn(1),\n\t\t\tgrndNormal(2) * spnpr_temp1 / spnpr_temp2 + spn(2)\n\t\t};\n\n\t\tfloat l3u3intrs_temp1 =\n\t\t\t-grndNormal(0) * cpL(0) + grndNormal(0) * lca3L(0)\n\t\t\t- grndNormal(1) * cpL(1) + grndNormal(1) * lca3L(1)\n\t\t\t- grndNormal(2) * cpL(2) + grndNormal(2) * lca3L(2);\n\n\t\tfloat l3u3intrs_temp2 =\n\t\t\tgrndNormal(0) * lca3L(0) - grndNormal(0) * uca3L(0) +\n\t\t\tgrndNormal(1) * lca3L(1) - grndNormal(1) * uca3L(1) +\n\t\t\tgrndNormal(2) * lca3L(2) - grndNormal(2) * uca3L(2);\n\n\t\tEigen::Vector3f l3u3intrs{\n\t\t\tlca3L(0) - (lca3L(0) - uca3L(0)) * l3u3intrs_temp1 / l3u3intrs_temp2,\n\t\t\tlca3L(1) - (lca3L(1) - uca3L(1)) * l3u3intrs_temp1 / l3u3intrs_temp2,\n\t\t\tlca3L(2) - (lca3L(2) - uca3L(2)) * l3u3intrs_temp1 / l3u3intrs_temp2\n\t\t};\n\n\t\tfloat caster_trail =\n\t\t\t(l3u3intrs - spnpr).cross(l3u3intrs - wcnpr).norm() / (wcnpr - spnpr).norm();\n\n\n\t\t// positive caster trail\n\t\tif ((l3u3intrs - spnpr).cross(l3u3intrs - wcnpr)(2) > 0)\n\t\t{\n\t\t\tcasterTrail = caster_trail;\n\n\t\t\treturn casterTrail;\n\t\t}\n\n\t\t// negative caster trail\n\t\telse\n\t\t{\n\t\t\tcasterTrail = -caster_trail;\n\t\t\treturn casterTrail;\n\t\t}\n\t}\n\n\tfloat GetScrubRadius(int vertPos, int steerPos)\n\t{\n\t\tfloat scrubRadius;\n\n\t\tint Lv = vertPos;\t\t\t\t\t\t\t// Left wheel only vertical position, UCA3, LCA3 points\n\t\tint Rv = 2 * vertIncr - vertPos;\t\t// Right wheel only vertical position, UCA3, LCA3 points\n\n\t\tint Lvs = vertPos * (2 * steerIncr + 1) + steerPos;\t\t\t\t\t\t\t\t\t  // Left wheel position including vertical and steering movement\n\t\tint Rvs = (2 * vertIncr - vertPos) * (2 * steerIncr + 1) + 2 * steerIncr - steerPos;  // Right wheel position including vertical and steering movement\n\n\t\t//int Lv = vertPos;\t\t\t\t\t\t\t// Left wheel only vertical position, UCA3, LCA3 points\n\t\t//int Rv = cpGlob.rows() - 1 - vertPos;\t\t// Right wheel only vertical position, UCA3, LCA3 points\n\n\t\t//int Lvs = vertPos * (2 * steerIncr + 1) + steerPos;\t\t\t\t\t\t\t// Left wheel position including vertical and steering movement\n\t\t//int Rvs = (cpGlob.rows() - 1 - vertPos) * (2 * steerIncr + 1) + steerPos;\t\t// Right wheel position including vertical and steering movement\n\n\t\tEigen::Vector3f cpL{ cpGlob.row(Lvs) };\n\t\tEigen::Vector3f cpR{ cpGlob.row(Rvs) };\n\t\tEigen::Vector3f wcn{ wcnGlob.row(Lvs) };\n\t\tEigen::Vector3f spn{ spnGlob.row(Lvs) };\n\t\tEigen::Vector3f lca3L{ lca3Glob.row(Lv) };\n\t\tEigen::Vector3f uca3L{ uca3Glob.row(Lv) };\n\n\t\tEigen::Vector3f grndNormal{\n\t\t\t0,\n\t\t\t-cpR(2) + cpL(2),\n\t\t\t-cpR(1) - cpL(1)\n\t\t};\n\n\t\tfloat wcnpr_temp1 =\n\t\t\tgrndNormal(0) * cpL(0) - grndNormal(0) * wcn(0) +\n\t\t\tgrndNormal(1) * cpL(1) - grndNormal(1) * wcn(1) +\n\t\t\tgrndNormal(2) * cpL(2) - grndNormal(2) * wcn(2);\n\n\t\tfloat wcnpr_temp2 =\n\t\t\tgrndNormal(0) * grndNormal(0) +\n\t\t\tgrndNormal(1) * grndNormal(1) +\n\t\t\tgrndNormal(2) * grndNormal(2);\n\n\t\tEigen::Vector3f wcnpr{\n\t\t\tgrndNormal(0) * wcnpr_temp1 / wcnpr_temp2 + wcn(0),\n\t\t\tgrndNormal(1) * wcnpr_temp1 / wcnpr_temp2 + wcn(1),\n\t\t\tgrndNormal(2) * wcnpr_temp1 / wcnpr_temp2 + wcn(2)\n\t\t};\n\n\t\tfloat spnpr_temp1 =\n\t\t\tgrndNormal(0) * cpL(0) - grndNormal(0) * wcn(0) +\n\t\t\tgrndNormal(1) * cpL(1) - grndNormal(1) * wcn(1) +\n\t\t\tgrndNormal(2) * cpL(2) - grndNormal(2) * wcn(2);\n\n\t\tfloat spnpr_temp2 =\n\t\t\tgrndNormal(0) * grndNormal(0) +\n\t\t\tgrndNormal(1) * grndNormal(1) +\n\t\t\tgrndNormal(2) * grndNormal(2);\n\n\t\tEigen::Vector3f spnpr{\n\t\t\tgrndNormal(0) * spnpr_temp1 / spnpr_temp2 + spn(0),\n\t\t\tgrndNormal(1) * spnpr_temp1 / spnpr_temp2 + spn(1),\n\t\t\tgrndNormal(2) * spnpr_temp1 / spnpr_temp2 + spn(2)\n\t\t};\n\n\t\tfloat l3u3intrs_temp1 =\n\t\t\t-grndNormal(0) * cpL(0) + grndNormal(0) * lca3L(0)\n\t\t\t- grndNormal(1) * cpL(1) + grndNormal(1) * lca3L(1)\n\t\t\t- grndNormal(2) * cpL(2) + grndNormal(2) * lca3L(2);\n\n\t\tfloat l3u3intrs_temp2 =\n\t\t\tgrndNormal(0) * lca3L(0) - grndNormal(0) * uca3L(0) +\n\t\t\tgrndNormal(1) * lca3L(1) - grndNormal(1) * uca3L(1) +\n\t\t\tgrndNormal(2) * lca3L(2) - grndNormal(2) * uca3L(2);\n\n\t\tEigen::Vector3f l3u3intrs{\n\t\t\tlca3L(0) - (lca3L(0) - uca3L(0)) * l3u3intrs_temp1 / l3u3intrs_temp2,\n\t\t\tlca3L(1) - (lca3L(1) - uca3L(1)) * l3u3intrs_temp1 / l3u3intrs_temp2,\n\t\t\tlca3L(2) - (lca3L(2) - uca3L(2)) * l3u3intrs_temp1 / l3u3intrs_temp2\n\t\t};\n\n\t\t// scrub radius\n\t\tfloat scrubRadius_temp1 =\n\t\t\t(wcn[0] - spn[0]) * (l3u3intrs[0] - cpL[0]) +\n\t\t\t(wcn[1] - spn[1]) * (l3u3intrs[1] - cpL[1]) +\n\t\t\t(wcn[2] - spn[2]) * (l3u3intrs[2] - cpL[2]);\n\n\t\tfloat scrubRadius_temp2 =\n\t\t\tpow((wcn[0] - spn[0]), 2) +\n\t\t\tpow((wcn[1] - spn[1]), 2) +\n\t\t\tpow((wcn[2] - spn[2]), 2);\n\n\t\tscrubRadius = scrubRadius_temp1 / sqrtf(scrubRadius_temp2);\n\n\t\treturn scrubRadius;\n\n\t}\n\n\tfloat GetKingpinAngle(int vertPos, int steerPos)\n\t{\n\t\tfloat kingpinAngle;\n\n\t\tint Lv = vertPos;\t\t\t\t\t\t\t// Left wheel only vertical position, UCA3, LCA3 points\n\t\tint Rv = 2 * vertIncr - vertPos;\t\t// Right wheel only vertical position, UCA3, LCA3 points\n\n\t\tint Lvs = vertPos * (2 * steerIncr + 1) + steerPos;\t\t\t\t\t\t\t\t\t  // Left wheel position including vertical and steering movement\n\t\tint Rvs = (2 * vertIncr - vertPos) * (2 * steerIncr + 1) + 2 * steerIncr - steerPos;  // Right wheel position including vertical and steering movement\n\n\t\t//int Lv = vertPos;\t\t\t\t\t\t\t// Left wheel only vertical position, UCA3, LCA3 points\n\t\t//int Rv = cpGlob.rows() - 1 - vertPos;\t\t// Right wheel only vertical position, UCA3, LCA3 points\n\n\t\t//int Lvs = vertPos * (2 * steerIncr + 1) + steerPos;\t\t\t\t\t\t\t// Left wheel position including vertical and steering movement\n\t\t//int Rvs = (cpGlob.rows() - 1 - vertPos) * (2 * steerIncr + 1) + steerPos;\t\t// Right wheel position including vertical and steering movement\n\n\t\tEigen::Vector3f cpL{ cpGlob.row(Lvs) };\n\t\tEigen::Vector3f cpR{ cpGlob.row(Rvs) };\n\n\t\tEigen::Vector3f grndNormal{\n\t\t\t0,\n\t\t\t-cpR(2) + cpL(2),\n\t\t\t-cpR(1) - cpL(1)\n\t\t};\n\n\t\tEigen::Vector3f l3u3pr{\n\t\t\t0,\n\t\t\t-uca3Glob.row(Lv)(1) + lca3Glob.row(Lv)(1),\n\t\t\t-uca3Glob.row(Lv)(2) + lca3Glob.row(Lv)(2)\n\t\t};\n\n\t\t// if uca3 is closer to chassis centre then kingpin angle is positive\n\t\tif (abs(uca3Glob.row(Lv)(1)) < abs(lca3Glob.row(Lv)(1)))\n\t\t{\n\t\t\tkingpinAngle = acos(grndNormal.dot(l3u3pr) / grndNormal.norm() / l3u3pr.norm()) * 180.0f / 3.14159f;\n\t\t\treturn kingpinAngle;\n\t\t}\n\t\t// otherwise negative kingpin angle\n\t\telse\n\t\t{\n\t\t\tkingpinAngle = -acos(grndNormal.dot(l3u3pr) / grndNormal.norm() / l3u3pr.norm()) * 180.0f / 3.14159f;\n\t\t\treturn kingpinAngle;\n\n\t\t}\n\t}\n\n\tfloat GetAntiDrive(int vertPos, int steerPos)\n\t{\n\t\tfloat antiDrive;\n\n\t\tint Lv = vertPos;\t\t\t\t\t\t\t// Left wheel only vertical position, UCA3, LCA3 points\n\t\tint Lvs = vertPos * (2 * steerIncr + 1) + steerPos;\t\t\t\t\t\t\t// Left wheel position including vertical and steering movement\n\n\t\tEigen::Vector3f lca3{ lca3Glob.row(Lv) };\n\t\tEigen::Vector3f uca3{ uca3Glob.row(Lv) };\n\t\tEigen::Vector3f cp{ cpGlob.row(Lvs) };\n\t\tEigen::Vector3f wcn{ wcnGlob.row(Lvs) };\n\n\t\tfloat aLCA;\n\t\tfloat aUCA;\n\n\t\tfloat bLCA;\n\t\tfloat bUCA;\n\n\t\t// LCA and UCA plane intersection with plane parallel to YZ plane with x coord CPR/2+CPL/2\n\t\t// lambda function that defines first point of intersection line\n\t\tauto intersectionLineCalc = [cp](float& aCa, float& bCa, const Eigen::Vector3f& ca1, const Eigen::Vector3f& ca2, const Eigen::Vector3f& ca3)\n\t\t{\n\t\t\t// plane coefficients Ax + By + Cz + D = 0, plane defined by control arm\n\t\t\tfloat A = (-ca1[1] + ca2[1]) * (-ca1[2] + ca3[2]) - (-ca1[1] + ca3[1]) * (-ca1[2] + ca2[2]);\n\t\t\tfloat B = -(-ca1[0] + ca2[0]) * (-ca1[2] + ca3[2]) + (-ca1[0] + ca3[0]) * (-ca1[2] + ca2[2]);\n\t\t\tfloat C = (-ca1[0] + ca2[0]) * (-ca1[1] + ca3[1]) - (-ca1[0] + ca3[0]) * (-ca1[1] + ca2[1]);\n\t\t\tfloat D = -ca1[0] * A - ca1[1] * B - ca1[2] * C;\n\n\t\t\t// intersection plane defined  as x + D2 = 0\n\t\t\tfloat D2 = -cp[1];\n\n\t\t\taCa = -A / C;\n\t\t\tbCa = (B * D2 - D) / C;\n\t\t};\n\n\t\tintersectionLineCalc(aLCA, bLCA, lca1ref, lca2ref, lca3);\n\t\tintersectionLineCalc(aUCA, bUCA, uca1ref, uca2ref, uca3);\n\n\t\tfloat tanThetaOutboard;\n\t\tfloat tanThetaInboard;\n\n\t\t// if resulting lines are parallel\n\t\tif (abs(aLCA - aUCA) / abs(aLCA) < precision)\n\t\t{\n\t\t\ttanThetaInboard = aLCA;\n\t\t\ttanThetaOutboard = aLCA;\n\t\t}\n\t\t// if resulting lines are not parallel\n\t\telse\n\t\t{\n\t\t\tfloat ICPtx = (bLCA - bUCA) / (aUCA - aLCA);\n\t\t\tfloat ICPtz = aLCA * ICPtx + bLCA;\n\n\t\t\ttanThetaOutboard = (ICPtz - wcn[2]) / (ICPtx - wcn[0]);\n\t\t\ttanThetaInboard = (ICPtz - cp[2]) / (ICPtx - cp[0]);\n\t\t}\n\n\t\tif (suspPos == 0)  // front suspension\n\t\t{\n\t\t\tif (drivePos == 0)                        // outboard drive\n\t\t\t\tantiDrive = tanThetaOutboard * wheelbase / cogHeight * driveBias * 100;\n\n\t\t\telse if (driveBias == 0)                  // inboard drive\n\t\t\t\tantiDrive = 0;\n\t\t\telse\n\t\t\t\tantiDrive = tanThetaInboard * wheelbase / cogHeight / driveBias * 100;\n\t\t}\n\n\t\telse  // rear suspension\n\t\t{\n\t\t\tif (drivePos == 0)                        // outboard drive\n\t\t\t\tantiDrive = -tanThetaOutboard * wheelbase / cogHeight * driveBias * 100;\n\n\t\t\telse if (driveBias == 0)                  // inboard drive\n\t\t\t\tantiDrive = 0;\n\t\t\telse\n\t\t\t\tantiDrive = -tanThetaInboard * wheelbase / cogHeight / driveBias * 100;\n\t\t}\n\n\t\treturn antiDrive;\n\t}\n\n\tfloat GetAntiBrake(int vertPos, int steerPos)\n\t{\n\t\tfloat antiBrakes;\n\n\t\tint Lv = vertPos;\t\t\t\t\t\t\t// Left wheel only vertical position, UCA3, LCA3 points\n\t\tint Lvs = vertPos * (2 * steerIncr + 1) + steerPos;\t\t\t\t\t\t\t// Left wheel position including vertical and steering movement\n\n\n\n\t\tEigen::Vector3f lca3{ lca3Glob.row(Lv) };\n\t\tEigen::Vector3f uca3{ uca3Glob.row(Lv) };\n\t\tEigen::Vector3f cp{ cpGlob.row(Lvs) };\n\t\tEigen::Vector3f wcn{ wcnGlob.row(Lvs) };\n\n\t\tfloat aLCA;\n\t\tfloat aUCA;\n\n\t\tfloat bLCA;\n\t\tfloat bUCA;\n\n\t\t// LCA and UCA plane intersection with plane parallel to YZ plane with x coord CPR/2+CPL/2\n\t\t// lambda function that defines first point of intersection line\n\t\tauto intersectionLineCalc = [cp](float& aCa, float& bCa, const Eigen::Vector3f& ca1, const Eigen::Vector3f& ca2, const Eigen::Vector3f& ca3)\n\t\t{\n\t\t\t// plane coefficients Ax + By + Cz + D = 0, plane defined by control arm\n\t\t\tfloat A = (-ca1[1] + ca2[1]) * (-ca1[2] + ca3[2]) - (-ca1[1] + ca3[1]) * (-ca1[2] + ca2[2]);\n\t\t\tfloat B = -(-ca1[0] + ca2[0]) * (-ca1[2] + ca3[2]) + (-ca1[0] + ca3[0]) * (-ca1[2] + ca2[2]);\n\t\t\tfloat C = (-ca1[0] + ca2[0]) * (-ca1[1] + ca3[1]) - (-ca1[0] + ca3[0]) * (-ca1[1] + ca2[1]);\n\t\t\tfloat D = -ca1[0] * A - ca1[1] * B - ca1[2] * C;\n\n\t\t\t// intersection plane defined  as x + D2 = 0\n\t\t\tfloat D2 = -cp[1];\n\n\t\t\taCa = -A / C;\n\t\t\tbCa = (B * D2 - D) / C;\n\t\t};\n\n\t\tintersectionLineCalc(aLCA, bLCA, lca1ref, lca2ref, lca3);\n\t\tintersectionLineCalc(aUCA, bUCA, uca1ref, uca2ref, uca3);\n\n\t\tfloat tanThetaOutboard;\n\t\tfloat tanThetaInboard;\n\n\t\t// if resulting lines are parallel\n\t\tif (abs(aLCA - aUCA) / abs(aLCA) < precision)\n\t\t{\n\t\t\ttanThetaInboard = aLCA;\n\t\t\ttanThetaOutboard = aLCA;\n\t\t}\n\t\t// if resulting lines are not parallel\n\t\telse\n\t\t{\n\t\t\tfloat ICPtx = (bLCA - bUCA) / (aUCA - aLCA);\n\t\t\tfloat ICPtz = aLCA * ICPtx + bLCA;\n\n\t\t\ttanThetaOutboard = (ICPtz - wcn[2]) / (ICPtx - wcn[0]);\n\t\t\ttanThetaInboard = (ICPtz - cp[2]) / (ICPtx - cp[0]);\n\t\t}\n\n\t\tif (suspPos == 0)  // front suspension\n\t\t{\n\t\t\tif (brakePos == 0)                        // outboard brakes\n\t\t\t\tantiBrakes = tanThetaOutboard * wheelbase / cogHeight * brakeBias * 100;\n\n\t\t\telse if (brakeBias == 0)                  // inboard brakes\n\t\t\t\tantiBrakes = 0;\n\t\t\telse\n\t\t\t\tantiBrakes = tanThetaInboard * wheelbase / cogHeight / brakeBias * 100;\n\t\t}\n\n\t\telse  // rear suspension\n\t\t{\n\t\t\tif (brakePos == 0)                        // outboard brakes\n\t\t\t\tantiBrakes = -tanThetaOutboard * wheelbase / cogHeight * brakeBias * 100;\n\n\t\t\telse if (brakeBias == 0)                  // inboard brakes\n\t\t\t\tantiBrakes = 0;\n\t\t\telse\n\t\t\t\tantiBrakes = -tanThetaInboard * wheelbase / cogHeight / brakeBias * 100;\n\n\t\t}\n\t\treturn antiBrakes;\n\t}\n\n\tfloat GetHalfTrackChange(int vertPos, int steerPos)\n\t{\n\t\tint position = vertPos * (2 * steerIncr + 1) + steerPos;\n\t\tfloat halfTrackChange;\n\t\t// if current wheelbase or half track is smaller than reference than negative sign, otherwise positive\n\t\thalfTrackChange = cpGlob.row(cpGlob.rows() / 2)[1] - cpGlob.row(position)[1];\n\t\treturn halfTrackChange;\n\t}\n\n\tfloat GetWheelbaseChange(int vertPos, int steerPos)\n\t{\n\t\tint position = vertPos * (2 * steerIncr + 1) + steerPos;\n\n\t\tfloat wheelbaseChange;\n\t\t// if current wheelbase or half track is smaller than reference than negative sign, otherwise positive\n\t\twheelbaseChange = -cpGlob.row(cpGlob.rows() / 2)[0] + cpGlob.row(position)[0];\n\t\treturn wheelbaseChange;\n\t}\n\n\tfloat GetLca3DistanceFromWheelAxis()\n\t{\n\t\treturn CalculateDistancePointToLine(spnref, wcnref, lca3ref);\n\n\t}\n\n\tfloat GetUca3DistanceFromWheelAxis()\n\t{\n\t\treturn CalculateDistancePointToLine(spnref, wcnref, uca3ref);\n\n\t}\n\n\tfloat GetTr2DistanceFromWheelAxis()\n\t{\n\t\treturn CalculateDistancePointToLine(spnref, wcnref, tr2ref);\n\n\t}\n\n\tfloat CalculateDistancePointToLine(const Eigen::Vector3f& linePt1, const Eigen::Vector3f& linePt2, const Eigen::Vector3f& Pt)\n\t{\n\t\tfloat distance;\n\t\tdistance = (Pt - linePt1).cross(Pt - linePt2).norm() / (linePt2 - linePt1).norm();\n\t\treturn distance;\n\t}\n\n\tfloat GetLca3DistanceToWheelCentrePlane()\n\t{\n\t\treturn GetSignedPointToPlaneDistance(wcnref, spnref, lca3ref);\n\t}\n\n\tfloat GetUca3DistanceToWheelCentrePlane()\n\t{\n\t\treturn GetSignedPointToPlaneDistance(wcnref, spnref, uca3ref);\n\t}\n\n\tfloat GetTr2DistanceToWheelCentrePlane()\n\t{\n\t\treturn GetSignedPointToPlaneDistance(wcnref, spnref, tr2ref);\n\t}\n\n\tfloat GetSignedPointToPlaneDistance(const Eigen::Vector3f linePt1, const Eigen::Vector3f& linePt2, const Eigen::Vector3f& Pt)\n\t{\n\t\t/*Calculates distance from point to plane and gives a sign (+ or -) for distance, positive when distanced in direction of plane normal and  negative otherwise, linePt1 is the head of normal vector and linePt2 tail*/\n\t\tfloat distance;\n\t\tfloat A = linePt1[0] - linePt2[0];\n\t\tfloat B = linePt1[1] - linePt2[1];\n\t\tfloat C = linePt1[2] - linePt2[2];\n\t\tfloat D = -linePt1[0] * A - linePt1[1] * B - linePt1[2] * C;\n\n\t\tdistance = (A * Pt[0] + B * Pt[1] + C * Pt[2] + D) / sqrtf(A * A + B * B + C * C);\n\t\treturn distance;\n\t}\n\n\tvoid GetOptimisationCharacteristicsArray(float* characteristicsArray)\n\t{\n\n\t\tcharacteristicsArray[0] = GetCamberAngle(0, 0);\n\t\tcharacteristicsArray[1] = GetCamberAngle(2, 0);\n\t\tcharacteristicsArray[2] = GetToeAngle(0, 0);\n\t\tcharacteristicsArray[3] = GetToeAngle(2, 0);\n\t\tcharacteristicsArray[4] = GetCasterAngle(1);\n\t\tcharacteristicsArray[5] = GetRollCentreHeight(1, 0);\n\t\tcharacteristicsArray[6] = GetCasterTrail(1, 0);\n\t\tcharacteristicsArray[7] = GetScrubRadius(1, 0);\n\t\tcharacteristicsArray[8] = GetKingpinAngle(1, 0);\n\t\tcharacteristicsArray[9] = GetAntiDrive(1, 0);\n\t\tcharacteristicsArray[10] = GetAntiBrake(1, 0);\n\t\tcharacteristicsArray[11] = GetHalfTrackChange(0, 0);\n\t\tcharacteristicsArray[12] = GetHalfTrackChange(2, 0);\n\t\tcharacteristicsArray[13] = GetWheelbaseChange(0, 0);\n\t\tcharacteristicsArray[14] = GetWheelbaseChange(2, 0);\n\t\tcharacteristicsArray[15] = GetLca3DistanceFromWheelAxis();\n\t\tcharacteristicsArray[16] = GetUca3DistanceFromWheelAxis();\n\t\tcharacteristicsArray[17] = GetTr2DistanceFromWheelAxis();\n\t\tcharacteristicsArray[18] = GetLca3DistanceToWheelCentrePlane();\n\t\tcharacteristicsArray[19] = GetUca3DistanceToWheelCentrePlane();\n\t\tcharacteristicsArray[20] = GetTr2DistanceToWheelCentrePlane();\n\n\t}\n\n\tvoid GetMovedHardpoints(float* outputLca3, float* outputUca3, float* outputTr1, float* outputTr2,\n\t\tfloat* outputWcn, float* outputSpn) {\n\t\t\n\t\tfor (int i = 0; i < vertIncr * 2 + 1; i++)\n\t\t{\n\t\t\toutputLca3[i * 3] = lca3Glob.row(i)(0);\n\t\t\toutputLca3[i * 3 + 1] = lca3Glob.row(i)(1);\n\t\t\toutputLca3[i * 3 + 2] = lca3Glob.row(i)(2);\n\t\t\t\n\t\t\toutputUca3[i * 3] = uca3Glob.row(i)(0);\n\t\t\toutputUca3[i * 3 + 1] = uca3Glob.row(i)(1);\n\t\t\toutputUca3[i * 3 + 2] = uca3Glob.row(i)(2);\n\n\t\t\tfor (int j = 0; j < steerIncr * 2 + 1; j++)\n\t\t\t{\n\t\t\t\toutputTr2[(i * (2 * steerIncr + 1) + j) * 3] = tr2Glob.row(i * (2 * steerIncr + 1) + j)(0);\n\t\t\t\toutputTr2[(i * (2 * steerIncr + 1) + j) * 3 + 1] = tr2Glob.row(i * (2 * steerIncr + 1) + j)(1);\n\t\t\t\toutputTr2[(i * (2 * steerIncr + 1) + j) * 3 + 2] = tr2Glob.row(i * (2 * steerIncr + 1) + j)(2);\n\n\t\t\t\toutputWcn[(i * (2 * steerIncr + 1) + j) * 3] = wcnGlob.row(i * (2 * steerIncr + 1) + j)(0);\n\t\t\t\toutputWcn[(i * (2 * steerIncr + 1) + j) * 3 + 1] = wcnGlob.row(i * (2 * steerIncr + 1) + j)(1);\n\t\t\t\toutputWcn[(i * (2 * steerIncr + 1) + j) * 3 + 2] = wcnGlob.row(i * (2 * steerIncr + 1) + j)(2);\n\n\t\t\t\toutputSpn[(i * (2 * steerIncr + 1) + j) * 3] = spnGlob.row(i * (2 * steerIncr + 1) + j)(0);\n\t\t\t\toutputSpn[(i * (2 * steerIncr + 1) + j) * 3 + 1] = spnGlob.row(i * (2 * steerIncr + 1) + j)(1);\n\t\t\t\toutputSpn[(i * (2 * steerIncr + 1) + j) * 3 + 2] = spnGlob.row(i * (2 * steerIncr + 1) + j)(2);\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < steerIncr * 2 + 1; j++)\n\t\t{\n\t\t\toutputTr1[j * 3] = tr1Glob.row(j)(0);\n\t\t\toutputTr1[j * 3 + 1] = tr1Glob.row(j)(1);\n\t\t\toutputTr1[j * 3 + 2] = tr1Glob.row(j)(2);\n\t\t}\n\t}\n};\n\n\nvoid optimisation_obj_res(float* hardpoints, int suspPos, float wRadius,\n\tfloat wheelbase, float cogHeight, float driveBias, float brakeBias,\n\tint drivePos, int brakePos,\n\tfloat wVert, float* peakWidth, float* flatness, float wSteer, int vertIncr, int steerIncr, float precision, float* targetValues,\n\tfloat* weightFactors, float& obj_func_res, float* outputParams)\n{\n\tSuspension susp{\n\n\t\thardpoints,\n\t\twRadius,\n\t\twheelbase, cogHeight, driveBias, brakeBias,\n\t\tsuspPos, drivePos, brakePos,\n\t\twVert, wSteer,\n\t\tvertIncr, steerIncr, precision\n\t};\n\tsusp.CalculateMovement();\n\n\n\tsusp.GetOptimisationCharacteristicsArray(outputParams);\n\tobj_func_res = susp.GetObjFuncScore(peakWidth, flatness, outputParams, targetValues, weightFactors);\n}\n\n\n\nvoid suspension_movement(float* hardpoints, float wRadiusin,\n\tfloat wheelbase, float cogHeight, float frontDriveBias, float frontBrakeBias,\n\tint suspPos, int drivePos, int brakePos,\n\tfloat wVertin, float wSteerin, int vertIncrin, int steerIncrin, float precisionin, \n\n\tfloat* camberAngle, \n\tfloat* toeAngle, \n\tfloat* casterAngle, \n\tfloat* rcHeight, \n\tfloat* casterTrail,\n\tfloat* scrubRadius,\n\tfloat* kingpinAngle,\n\tfloat* antiDrive, \n\tfloat* antiBrake, \n\tfloat* halfTrackChange,\n\tfloat* wheelbaseChange, \n\tfloat* constOutputParams,\n\n\tfloat* outputLca3, \n\tfloat* outputUca3, \n\tfloat* outputTr1, \n\tfloat* outputTr2, \n\tfloat* outputWcn, \n\tfloat* outputSpn)\n{\n\n\tSuspension susp{\n\t\thardpoints,\n\t\twRadiusin,\n\t\twheelbase, cogHeight, frontDriveBias, frontBrakeBias,\n\t\tsuspPos, drivePos, brakePos,\n\t\twVertin, wSteerin,\n\t\tvertIncrin, steerIncrin, precisionin\n\t};\n\n\tsusp.CalculateMovement();\n\n\tsusp.GetMovedHardpoints(outputLca3, outputUca3, outputTr1, outputTr2, outputWcn, outputSpn);\n\tfor (int i = 0; i < vertIncrin * 2 + 1; i++)\n\t{\n\n\t\tfor (int j = 0; j < steerIncrin * 2 + 1; j++)\n\t\t{\n\t\t\tcamberAngle[i * (2 * steerIncrin + 1) + j] = susp.GetCamberAngle(i, j);\n\t\t\ttoeAngle[i * (2 * steerIncrin + 1) + j] = susp.GetToeAngle(i, j);\n\t\t\tcasterAngle[i * (2 * steerIncrin + 1) + j] = susp.GetCasterAngle(i);\n\t\t\trcHeight[i * (2 * steerIncrin + 1) + j] = susp.GetRollCentreHeight(i, j);\n\t\t\tcasterTrail[i * (2 * steerIncrin + 1) + j] = susp.GetCasterTrail(i, j);\n\t\t\tscrubRadius[i * (2 * steerIncrin + 1) + j] = susp.GetScrubRadius(i, j);\n\t\t\tkingpinAngle[i * (2 * steerIncrin + 1) + j] = susp.GetKingpinAngle(i, j);\n\t\t\tantiDrive[i * (2 * steerIncrin + 1) + j] = susp.GetAntiDrive(i, j);\n\t\t\tantiBrake[i * (2 * steerIncrin + 1) + j] = susp.GetAntiBrake(i, j);\n\t\t\thalfTrackChange[i * (2 * steerIncrin + 1) + j] = susp.GetHalfTrackChange(i, j);\n\t\t\twheelbaseChange[i * (2 * steerIncrin + 1) + j] = susp.GetWheelbaseChange(i, j);\n\n\t\t}\n\t}\n\n\tconstOutputParams[0] = susp.GetLca3DistanceFromWheelAxis();\n\tconstOutputParams[1] = susp.GetUca3DistanceFromWheelAxis();\n\tconstOutputParams[2] = susp.GetTr2DistanceFromWheelAxis();\n\tconstOutputParams[3] = susp.GetLca3DistanceToWheelCentrePlane();\n\tconstOutputParams[4] = susp.GetUca3DistanceToWheelCentrePlane();\n\tconstOutputParams[5] = susp.GetTr2DistanceToWheelCentrePlane();\n}\n", "meta": {"hexsha": "f1dc203fa5ca7302190ce1ec4bccb5cec9b94eac", "size": 44211, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mechanicsDLL/mechanics.cpp", "max_stars_repo_name": "brunomraz/FS-BMK", "max_stars_repo_head_hexsha": "793f41d0aebaaa6ce3539b31e82bf179780d05ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-26T16:26:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T16:26:16.000Z", "max_issues_repo_path": "mechanicsDLL/mechanics.cpp", "max_issues_repo_name": "brunomraz/FS-BMK", "max_issues_repo_head_hexsha": "793f41d0aebaaa6ce3539b31e82bf179780d05ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mechanicsDLL/mechanics.cpp", "max_forks_repo_name": "brunomraz/FS-BMK", "max_forks_repo_head_hexsha": "793f41d0aebaaa6ce3539b31e82bf179780d05ca", "max_forks_repo_licenses": ["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.4425113464, "max_line_length": 217, "alphanum_fraction": 0.6434597725, "num_tokens": 17593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5045751095585641}}
{"text": "#include <catch2/catch.hpp>\n\n#include <array>\n\n#include <units/isq/si/speed.h>\n#include <units/isq/si/time.h>\n#include <units/isq/si/length.h>\n#include <units/isq/si/area.h>\n#include <units/generic/dimensionless.h>\n\n#include <boost/hana/tuple.hpp>\n\n#include <codys/codys.hpp>\n\nusing PositionTag = class Position_;\nusing PositionUnit = units::isq::si::length<units::isq::si::metre>;\nusing PositionUnitSq = units::isq::si::area<units::isq::si::square_metre>;\nusing Dimensionless = units::dimensionless<units::one>;\nusing Position = codys::State<PositionTag, PositionUnit>;\nusing VelocityUnit = units::isq::si::speed<units::isq::si::metre_per_second>;\nusing Velocity = codys::State<class Vel_, VelocityUnit>;\n\nusing BasicMotions = codys::System<Position, Velocity>;\n\nTEST_CASE(\"System return right state indices\", \"[System]\")\n{\n  STATIC_REQUIRE(BasicMotions::idx_of<Position>() == 0);\n  STATIC_REQUIRE(BasicMotions::idx_of<Velocity>() == 1);\n}\n\nTEST_CASE(\"State gives self as depends_on\", \"[State]\")\n{\n  STATIC_REQUIRE(std::is_same_v<Position::depends_on, boost::hana::tuple<Position>>);\n}\n\nTEST_CASE(\"State has right unit as type\", \"[State]\")\n{\n  STATIC_REQUIRE(std::is_same_v<Position::Unit, PositionUnit>);\n}\n\nTEST_CASE(\"Derivative has right operand as type\", \"[Derivative]\") \n{\n  static constexpr auto derivative = codys::dot<Position>(Velocity{});\n  STATIC_REQUIRE(std::is_same_v<decltype(derivative)::Operand, Position>);\n}\n\nTEST_CASE(\"Operator Plus yields sum of operands\", \"[Operator]\") \n{\n  static constexpr auto plus = Position{} + Position{};\n  static constexpr std::array values{1.0};\n  using TestSystem = codys::System<Position>;\n\n  static constexpr auto result = plus.template evaluate<TestSystem, 1>(values);\n  STATIC_REQUIRE(result == values[0] + values[0]);\n}\n\nTEST_CASE(\"Operator Plus has same unit as operands\", \"[Operator]\")\n{\n  static constexpr auto plus = Position{} + Position{};\n  STATIC_REQUIRE(std::is_same_v<decltype(plus)::Unit, PositionUnit>);\n}\n\nTEST_CASE(\"Operator Plus has concatination of denepends on\", \"[Operator]\")\n{\n  static constexpr auto plus = Position{} + Position{};\n  static constexpr auto ref_dependands = boost::hana::tuple<Position,Position>();\n  STATIC_REQUIRE(std::is_same_v<decltype(plus)::depends_on, std::remove_cvref_t<decltype(ref_dependands)>>);\n}\n\nTEST_CASE(\"Operator Minus yields substraction of operands\", \"[Operator]\") \n{\n  static constexpr auto minus = Position{} - Position{};\n  static constexpr std::array values{1.0};\n  using TestSystem = codys::System<Position>;\n\n  static constexpr auto result = minus.template evaluate<TestSystem, 1>(values);\n  STATIC_REQUIRE(result == values[0] - values[0]);\n}\n\nTEST_CASE(\"Operator Minus has same unit as operands\", \"[Operator]\")\n{\n  static constexpr auto minus = Position{} - Position{};\n  STATIC_REQUIRE(std::is_same_v<decltype(minus)::Unit, PositionUnit>);\n}\n\nTEST_CASE(\"Operator Minus has concatination of denepends on\", \"[Operator]\")\n{\n  static constexpr auto minus = Position{} - Position{};\n  static constexpr auto ref_dependands = boost::hana::tuple<Position,Position>();\n  STATIC_REQUIRE(std::is_same_v<decltype(minus)::depends_on, std::remove_cvref_t<decltype(ref_dependands)>>);\n}\n\nTEST_CASE(\"Operator Multiply yields multiplication of operands\", \"[Operator]\") \n{\n  static constexpr auto multiply = Position{} * Position{};\n  static constexpr std::array values{2.0};\n  using TestSystem = codys::System<Position>;\n\n  static constexpr auto result = multiply.template evaluate<TestSystem, 1>(values);\n  STATIC_REQUIRE(result == values[0] * values[0]);\n}\n\nTEST_CASE(\"Operator Multiply has unit resulting from multiplying operands\", \"[Operator]\")\n{\n  static constexpr auto multiply = Position{} * Position{};\n  STATIC_REQUIRE(std::is_same_v<decltype(multiply)::Unit, PositionUnitSq>);\n}\n\nTEST_CASE(\"Operator Multiply has concatination of denepends on\", \"[Operator]\")\n{\n  static constexpr auto multiply = Position{} * Position{};\n  static constexpr auto ref_dependands = boost::hana::tuple<Position,Position>();\n  STATIC_REQUIRE(std::is_same_v<decltype(multiply)::depends_on, std::remove_cvref_t<decltype(ref_dependands)>>);\n}\n\nTEST_CASE(\"Operator Divide yields division of operands\", \"[Operator]\") \n{\n  static constexpr auto divide = Position{} / Position{};\n  static constexpr std::array values{2.0};\n  using TestSystem = codys::System<Position>;\n\n  static constexpr auto result = divide.template evaluate<TestSystem, 1>(values);\n  STATIC_REQUIRE(result == values[0] / values[0]);\n}\n\nTEST_CASE(\"Operator Divide has unit resulting from dividing operands\", \"[Operator]\")\n{\n  static constexpr auto divide = Position{} / Position{};\n  STATIC_REQUIRE(std::is_same_v<decltype(divide)::Unit, Dimensionless>);\n}\n\nTEST_CASE(\"Operator Divide has concatination of denepends on\", \"[Operator]\")\n{\n  static constexpr auto divide = Position{} / Position{};\n  static constexpr auto ref_dependands = boost::hana::tuple<Position,Position>();\n  STATIC_REQUIRE(std::is_same_v<decltype(divide)::depends_on, std::remove_cvref_t<decltype(ref_dependands)>>);\n}\n\nTEST_CASE(\"Operator Add to Scalar yields sum of operands\", \"[Operator]\") \n{\n  using namespace units::isq::si::references;\n  static constexpr auto scalar_number = 10.0;\n  static constexpr auto displacement = scalar_number * m;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_sum = displacement + state;\n  static constexpr std::array values{2.0};\n  using TestSystem = codys::System<Position>;\n\n  static constexpr auto result = scalar_sum.template evaluate<TestSystem, 1>(values);\n  STATIC_REQUIRE(result == scalar_number + values[0]);\n}\n\nTEST_CASE(\"Operator Add to Scalar is commutative\", \"[Operator]\") \n{\n  using namespace units::isq::si::references;\n  static constexpr auto scalar_number = 10.0;\n  static constexpr auto displacement = scalar_number * m;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_sum1 = displacement + state;\n  static constexpr auto scalar_sum2 = state + displacement;\n  static constexpr std::array values{2.0};\n  using TestSystem = codys::System<Position>;\n\n  static constexpr auto result1 = scalar_sum1.template evaluate<TestSystem, 1>(values);\n  static constexpr auto result2 = scalar_sum2.template evaluate<TestSystem, 1>(values);\n  STATIC_REQUIRE(result1 == result2);\n}\n\nTEST_CASE(\"Operator Add to Scalar does not change unit\", \"[Operator]\")\n{\n  using namespace units::isq::si::references;\n  static constexpr auto displacement = 10 * m;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_sum = displacement + state;\n  STATIC_REQUIRE(std::is_same_v<decltype(scalar_sum)::Unit, PositionUnit>);\n}\n\nTEST_CASE(\"Operator Add to Scalar does not change dependencies\", \"[Operator]\")\n{\n  using namespace units::isq::si::references;\n  static constexpr auto displacement = 10 * m;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_sum = displacement + state;\n  STATIC_REQUIRE(std::is_same_v<decltype(scalar_sum)::depends_on, decltype(state)::depends_on>);\n}\n\nTEST_CASE(\"Operator Minus with Scalar yields substraction of operands\", \"[Operator]\") \n{\n  using namespace units::isq::si::references;\n  static constexpr auto scalar_number = 10.0;\n  static constexpr auto displacement = scalar_number * m;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_substraction = displacement - state;\n  static constexpr std::array values{2.0};\n  using TestSystem = codys::System<Position>;\n\n  static constexpr auto result = scalar_substraction.template evaluate<TestSystem, 1>(values);\n  STATIC_REQUIRE(result == scalar_number - values[0]);\n}\n\nTEST_CASE(\"Operator Minus with Scalar is commutative\", \"[Operator]\") \n{\n  using namespace units::isq::si::references;\n  static constexpr auto scalar_number = 10.0;\n  static constexpr auto displacement = scalar_number * m;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_substraction1 = displacement - state;\n  static constexpr auto scalar_substraction2 = state - displacement;\n  static constexpr std::array values{2.0};\n  using TestSystem = codys::System<Position>;\n\n  static constexpr auto result1 = scalar_substraction1.template evaluate<TestSystem, 1>(values);\n  static constexpr auto result2 = scalar_substraction2.template evaluate<TestSystem, 1>(values);\n  STATIC_REQUIRE(result1 == -result2);\n}\n\nTEST_CASE(\"Operator Minus with Scalar does not change unit\", \"[Operator]\")\n{\n  using namespace units::isq::si::references;\n  static constexpr auto displacement = 10 * m;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_substraction = displacement - state;\n  STATIC_REQUIRE(std::is_same_v<decltype(scalar_substraction)::Unit, PositionUnit>);\n}\n\nTEST_CASE(\"Operator Minus with Scalar does not change dependencies\", \"[Operator]\")\n{\n  using namespace units::isq::si::references;\n  static constexpr auto displacement = 10 * m;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_substraction = displacement - state;\n  STATIC_REQUIRE(std::is_same_v<decltype(scalar_substraction)::depends_on, decltype(state)::depends_on>);\n}\n\nTEST_CASE(\"Operator Multiply With Scalar yields multiplication of operands\", \"[Operator]\") \n{\n  using namespace units::isq::si::references;\n  static constexpr auto scalar_number = 10.0;\n  static constexpr auto time = scalar_number * s;\n  static constexpr auto state = Velocity{};\n  static constexpr auto scalar_multiply = time * state;\n  static constexpr std::array values{2.0};\n  using TestSystem = codys::System<Velocity>;\n\n  static constexpr auto result = scalar_multiply.template evaluate<TestSystem, 1>(values);\n  STATIC_REQUIRE(result == scalar_number * values[0]);\n}\n\nTEST_CASE(\"Operator Multiply With Scalar is commutative\", \"[Operator]\") \n{\n  using namespace units::isq::si::references;\n  static constexpr auto scalar_number = 10.0;\n  static constexpr auto time = scalar_number * s;\n  static constexpr auto state = Velocity{};\n  static constexpr auto scalar_multiply1 = time * state;\n  static constexpr auto scalar_multiply2 = state * time;\n  static constexpr std::array values{2.0};\n  using TestSystem = codys::System<Velocity>;\n\n  static constexpr auto result1 = scalar_multiply1.template evaluate<TestSystem, 1>(values);\n  static constexpr auto result2 = scalar_multiply2.template evaluate<TestSystem, 1>(values);\n  STATIC_REQUIRE(result1 == result2);\n}\n\nTEST_CASE(\"Operator Multiply With Scalar has unit resulting from multiplying operands\", \"[Operator]\")\n{\n  using namespace units::isq::si::references;\n  static constexpr auto time = 10 * s;\n  static constexpr auto state = Velocity{};\n  static constexpr auto scalar_multiply = time * state;\n  STATIC_REQUIRE(std::is_same_v<decltype(scalar_multiply)::Unit, PositionUnit>);\n}\n\nTEST_CASE(\"Operator Multiply With Scalar does not change dependencies\", \"[Operator]\")\n{\n  using namespace units::isq::si::references;\n  static constexpr auto time = 10 * s;\n  static constexpr auto state = Velocity{};\n  static constexpr auto scalar_multiply = time * state;\n  STATIC_REQUIRE(std::is_same_v<decltype(scalar_multiply)::depends_on, decltype(state)::depends_on>);\n}\n\nTEST_CASE(\"Operator Divide by Scalar yields division of operands\", \"[Operator]\") \n{\n  using namespace units::isq::si::references;\n  static constexpr auto scalar_number = 10.0;\n  static constexpr auto time = scalar_number * s;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_division = state / time;\n  static constexpr std::array values{2.0};\n  using TestSystem = codys::System<Position>;\n\n  static constexpr auto result = scalar_division.template evaluate<TestSystem, 1>(values);\n  STATIC_REQUIRE(result == values[0] / scalar_number);\n}\n\nTEST_CASE(\"Operator Divide by Scalar yields unit from division\", \"[Operator]\")\n{\n  using namespace units::isq::si::references;\n  static constexpr auto time = 10 * s;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_division = state / time;\n  STATIC_REQUIRE(std::is_same_v<decltype(scalar_division)::Unit, VelocityUnit>);\n}\n\nTEST_CASE(\"Operator Divide by Scalar does not change dependencies\", \"[Operator]\")\n{\n  using namespace units::isq::si::references;\n  static constexpr auto time = 10 * s;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_division = state / time;\n  STATIC_REQUIRE(std::is_same_v<decltype(scalar_division)::depends_on, decltype(state)::depends_on>);\n}\n\nTEST_CASE(\"Operator Divide Scalar by State yields division of operands\", \"[Operator]\") \n{\n  using namespace units::isq::si::references;\n  static constexpr auto scalar_number = 10.0;\n  static constexpr auto ref_distance = scalar_number * m;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_division = ref_distance / state;\n  static constexpr std::array values{2.0};\n  using TestSystem = codys::System<Position>;\n\n  static constexpr auto result = scalar_division.template evaluate<TestSystem, 1>(values);\n  STATIC_REQUIRE(result == scalar_number / values[0]);\n}\n\nTEST_CASE(\"Operator Divide Scalar by State yields unit from division\", \"[Operator]\")\n{\n  using namespace units::isq::si::references;\n  static constexpr auto ref_distance = 10.0 * m;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_division = ref_distance / state;\n  STATIC_REQUIRE(std::is_same_v<decltype(scalar_division)::Unit, Dimensionless>);\n}\n\nTEST_CASE(\"Operator Divide Scalar by State does not change dependencies\", \"[Operator]\")\n{\n  using namespace units::isq::si::references;\n  static constexpr auto ref_distance = 10.0 * m;\n  static constexpr auto state = Position{};\n  static constexpr auto scalar_division = ref_distance / state;\n  STATIC_REQUIRE(std::is_same_v<decltype(scalar_division)::depends_on, decltype(state)::depends_on>);\n}", "meta": {"hexsha": "eb0aeb7cc180cb05d0307e452b98188bc30b8da8", "size": 13777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/constexpr_tests.cpp", "max_stars_repo_name": "hansepp/codys", "max_stars_repo_head_hexsha": "987af24cca75745916f4dad03f75a3d0a05586fd", "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/constexpr_tests.cpp", "max_issues_repo_name": "hansepp/codys", "max_issues_repo_head_hexsha": "987af24cca75745916f4dad03f75a3d0a05586fd", "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/constexpr_tests.cpp", "max_forks_repo_name": "hansepp/codys", "max_forks_repo_head_hexsha": "987af24cca75745916f4dad03f75a3d0a05586fd", "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": 39.9333333333, "max_line_length": 112, "alphanum_fraction": 0.749800392, "num_tokens": 3134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5045751046107283}}
{"text": "/*\n * main.cpp\n *\n *  Created on: 26.10.2010\n *      Author: stephaniebayer\n */\n\n\n#include <stdio.h>\n#include <time.h>\n#include <vector>\n#include <fstream>\n\n#include \"G_q.h\"\n#include \"Functions.h\"\n#include \"ElGammal.h\"\n#include \"Cipher_elg.h\"\n#include \"Permutation.h\"\n#include \"Prover.h\"\n#include \"Prover_me.h\"\n#include \"Prover_fft.h\"\n#include \"Prover_toom.h\"\n#include \"Verifier.h\"\n#include \"Verifier_me.h\"\n#include \"Verifier_toom.h\"\n#include <NTL/ZZ.h>\n#include <NTL/mat_ZZ.h>\n\n#include <NTL/matrix.h>\n#include <NTL/vec_vec_ZZ.h>\nNTL_CLIENT\n\n\n G_q G=G_q();// group used for the Pedersen commitment\n G_q H=G_q();// group used for the the encryption\n ElGammal El = ElGammal(); //The class for encryption and decryption\n Pedersen Ped = Pedersen(); //Object which calculates the commitments\n double time_rw_p =0;\n double time_rw_v=0;\n double time_cm =0;\n long m_r=0;//number of rows after reduction\n long mu=0; //number of rows after reduction\n long mu_h=0;//2*mu-1, number of extra elements in the reduction\n\n int shuffle_wo_opti(vector<vector<Cipher_elg>* >* e,vector<vector<Cipher_elg>* >* E, vector<vector<ZZ>*>* R,vector<vector<vector<long>* >* > * pi, vector<long> num, ZZ genq);\n int shuffle_w_opti_me(vector<vector<Cipher_elg>* >* e, vector<vector<Cipher_elg>* >* E, vector<vector<ZZ>*>* R,vector<vector<vector<long>* >* > * pi, vector<long> num);\n int shuffle_w_opti(vector<vector<Cipher_elg>* >* e, vector<vector<Cipher_elg>* >* E, vector<vector<ZZ>*>* R,vector<vector<vector<long>* >* > * pi, vector<long> num, ZZ genq);\n int shuffle_w_toom(vector<vector<Cipher_elg>* >* e, vector<vector<Cipher_elg>* >* E, vector<vector<ZZ>*>* R,vector<vector<vector<long>* >* > * pi, vector<long> num, ZZ genq);\n\n\n int main(){\n\tint i;\n\tvector<long> num; //Containing the number of ciphertexts and the structure of the matrix of the ciphertexts\n\tvector<vector<Cipher_elg>* >* c=0; // contains the original input ciphertexts\n\tvector<vector<Cipher_elg>* >* C=0;//Contains reencryptetd ciphers\n\tvector<vector<vector<long>* >* > * pi=0; //Permutation\n\tvector<vector<ZZ>* >* R=0; //Random elements for reencryption\n\tZZ genq; //generator of Z_q\n\tlong m, n;\n\tdouble tstart,  tstop, ttime, time_p, time_v;\n\tstring file_name;\n\n\ttime_p = 0;\n\ttime_v = 0;\n\tnum=vector<long>(8);\n\tFunctions::read_config(num, genq);\n\n\t \n\t \n\t m = num[1];\n\t n = num[2];\n\n\t Ped = Pedersen(n, G);\n\t Ped.set_omega(num[3], num[7], num[4]);\n\n\tc =new vector<vector<Cipher_elg>* >(m);\n\n\tFunctions::createCipher(c,num);\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tpi = new vector<vector<vector<long>* >* >(m);\n\tPermutation::perm_matrix(pi,n,m);\n\tR = new vector<vector<ZZ>*>(m);\n\tFunctions::randomEl(R,num);\n\tC=new vector<vector<Cipher_elg>* >(m);\n\tFunctions::reencryptCipher(C,c,pi,R,num);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\tcout << \"To shuffle the ciphertexts took \" << ttime << \" second(s).\" << endl;\n\n\tif(num[5]==0){\n\t\tshuffle_wo_opti(c,C,R, pi, num, genq);\n\t}\n\telse if(num[5]==1){\n\t\tcout<<\"Multi-expo version:\"<<endl;\n\t\tshuffle_w_opti_me(c,C,R, pi, num);\n\t}\n\telse if(num[5]==2){\n\t\tcout<<\"FFT:\"<<endl;\n\t\tshuffle_w_opti(c,C,R, pi, num, genq);\n\t} \n\telse if(num[5]==3){\n\t\tcout<<\"Toom-Cook and Interaction:\"<<endl;\n\t\tshuffle_w_toom(c,C,R, pi, num, genq);\n\t}\n\n\tFunctions::delete_vector(c);\n\tFunctions::delete_vector(C);\n\tFunctions::delete_vector(R);\n\tFunctions::delete_vector(pi);\n}\n\n\nint shuffle_wo_opti(vector<vector<Cipher_elg>* >* c, vector<vector<Cipher_elg>* >* C, vector<vector<ZZ>*>* R,vector<vector<vector<long>* >* > * pi, vector<long> num, ZZ genq){\n\tProver* P=0;\n\tVerifier* V=0;\n\tP = new Prover(C,R,pi,num, genq);\n\tV = new Verifier(num);\n\tdouble tstart, tstart_t, tstop,tstop_t, ttime, time_p, time_v;\n\tZZ chal_10,ans_12;\n\tstring file_name, name;\n\tofstream ost;\n\n\ttime_p=0;\n\ttime_v =0;\n\ttime_cm =0;\n\n\ttstart_t = (double)clock()/CLOCKS_PER_SEC;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_1();\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V->round_2(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_3(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V->round_4(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_5(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V->round_6(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_7(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V-> round_8(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tfile_name = P->round_9(file_name);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_p+=ttime;\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tchal_10 = V->round_10(file_name, c, C);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_v+=ttime;\n\n\ttstop_t = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop_t-tstart_t;\n\n\tname = \"shuffle_without_opti_P.txt\";\n\tost.open(name.c_str(),ios::app);\n\tost<< time_p<<endl;\n\tost.close();\n\n\tname = \"shuffle_without_opti_V.txt\";\n\tost.open(name.c_str(),ios::app);\n\tost<< time_v<<endl;\n\tost.close();\n//\tost << \"The shuffle argument took \" << ttime << \" second(s).\" << endl;\n//\tost << \"The prover needed \" <<time_p<<\" in total and \" << \"the verifier needed \"<<time_v<<\" in total\"<<endl;\n//\tost << \"The commitments needed \"<< time_cm<< \"second(s)\";\n\tdelete P;\n\tdelete V;\n\treturn 1;\n}\n\n\nint shuffle_w_opti_me(vector<vector<Cipher_elg>* >* c, vector<vector<Cipher_elg>* >* C, vector<vector<ZZ>*>* R,vector<vector<vector<long>* >* > * pi, vector<long> num){\n\tProver_me* P=0;\n\tVerifier_me* V=0;\n\tdouble tstart, tstart_t, tstop,tstop_t, ttime, time_p, time_v;\n\tZZ chal_10,ans_12;\n\tstring file_name, name;\n\tofstream ost;\n\tP = new Prover_me(C,R,pi,num);\n\tV = new Verifier_me(num);\n\n\ttime_p=0;\n\ttime_v =0;\n\ttstart_t = (double)clock()/CLOCKS_PER_SEC;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_1();\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V->round_2(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_3(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V->round_4(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_5(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V->round_6(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_7(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V-> round_8(file_name);\ntstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_9(file_name);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_p+=ttime;\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\nchal_10 = V->round_10(file_name, c, C);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_v+=ttime;\n\ttstop_t = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop_t-tstart_t;\n\n\n\tname = \"shuffle_with_me_P.txt\";\n\tost.open(name.c_str(),ios::app);\n\tost<< time_p<<endl;\n\tost.close();\n\n\tname = \"shuffle_with_me_V.txt\";\n\tost.open(name.c_str(),ios::app);\n\tost<< time_v<<endl;\n\tost.close();\n/*\tost << \"The optimized shuffle argument took \" << ttime << \" second(s).\" << endl;\n\tost << \"The prover needed \" <<time_p<<\" in total and \"<< \"the verifier needed \"<<time_v<<\" in total\"<<endl;\n\tost << \"The opt. commitments needed \"<< time_cm<< \"second(s)\";\n\tost.close();*/\n\n\tdelete P;\n\tdelete V;\n\n\treturn 1;\n}\n\nint shuffle_w_opti(vector<vector<Cipher_elg>* >* c, vector<vector<Cipher_elg>* >* C, vector<vector<ZZ>*>* R,vector<vector<vector<long>* >* > * pi, vector<long> num, ZZ gen){\n\tProver_fft* P=0;\n\tVerifier_me* V=0;\n\tdouble tstart, tstart_t, tstop,tstop_t, ttime, time_p, time_v;\n\tZZ chal_10,ans_12;\n\tstring file_name, name;\n\tofstream ost;\n\tP = new Prover_fft(C,R,pi,num, gen);\n\tV = new Verifier_me(num);\n\n\ttime_p=0;\n\ttime_v =0;\n\ttstart_t = (double)clock()/CLOCKS_PER_SEC;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_1();\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V->round_2(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_3(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V->round_4(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_5(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V->round_6(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_7(file_name);\n\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V-> round_8(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\n\tfile_name = P->round_9(file_name);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_p+=ttime;\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tchal_10 = V->round_10(file_name, c, C);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_v+=ttime;\n\n\ttstop_t = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop_t-tstart_t;\n\n\tname = \"shuffle_with_FFT_P.txt\";\n\tost.open(name.c_str(),ios::app);\n\tost<< time_p<<endl;\n\tost.close();\n\n\tname = \"shuffle_with_FFT_V.txt\";\n\tost.open(name.c_str(),ios::app);\n\tost<< time_v<<endl;\n\tost.close();\n/*\tost << \"The optimized shuffle argument took \" << ttime << \" second(s).\" << endl;\n\tost << \"The prover needed \" <<time_p<<\" in total and \"<< \"the verifier needed \"<<time_v<<\" in total\"<<endl;\n\tost << \"The opt. commitments needed \"<< time_cm<< \"second(s)\";\n\tost.close();*/\n\n\tdelete P;\n\tdelete V;\n\n\treturn 1;\n}\n\n\nint shuffle_w_toom(vector<vector<Cipher_elg>* >* c, vector<vector<Cipher_elg>* >* C, vector<vector<ZZ>*>* R,vector<vector<vector<long>* >* > * pi, vector<long> num, ZZ gen){\n\n\tProver_toom* P=0;\n\tVerifier_toom* V=0;\n\tdouble tstart, tstart_t, tstop,tstop_t, ttime, time_p, time_v;\n\tZZ chal_10,ans_12;\n\tstring file_name, name;\n\tofstream ost;\n\tmu = 4;\n\tmu_h = 2*mu-1;\n\tm_r = num[1]/mu;\n\tP = new Prover_toom(C,R,pi,num, gen);\n\tV = new Verifier_toom(num);\n\n\n\ttime_p=0;\n\ttime_v =0;\n\ttstart_t = (double)clock()/CLOCKS_PER_SEC;\n\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_1();\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V->round_2(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_3(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V->round_4(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\n\tif(m_r ==4){\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_5(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = V->round_6(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\nfile_name = P->round_7(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_p+=ttime;\n\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tfile_name = V-> round_8(file_name);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\ttime_v+=ttime;\n\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tfile_name = P->round_9(file_name);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_p+=ttime;\n\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tchal_10 = V->round_10(file_name,c,C);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_v+=ttime;\n\t}\n\telse{\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tfile_name = P->round_5_red(file_name);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_p+=ttime;\n\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tfile_name = V->round_6_red(file_name,c);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_v+=ttime;\n\n\t\tm_r=m_r/mu;\n\t/*\twhile(m_r>mu){\n\t\t\tcout<<\"This still needs of programming, but only happen if m=256\";\n\t\t\tm_r=m_r/mu;\n\t\t}*/\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tfile_name = P->round_5_red1(file_name);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_p+=ttime;\n\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tfile_name = V->round_6_red1(file_name);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_v+=ttime;\n\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tfile_name = P->round_7_red(file_name);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_p+=ttime;\n\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tfile_name = V->round_8(file_name);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_v+=ttime;\n\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tfile_name = P->round_9(file_name);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_p+=ttime;\n\n\t\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tchal_10 = V->round_10_red(file_name,c,C);\n\t\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\t\tttime= tstop-tstart;\n\t\ttime_v+=ttime;\n\t}\n\n\ttstop_t = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop_t-tstart_t;\n\n\tname = \"shuffle_with_toom_cook_P.txt\";\n\tost.open(name.c_str(),ios::app);\n\tost<< time_p<<endl;\n\tost.close();\n\n\tname = \"shuffle_with_toom_cook_V.txt\";\n\tost.open(name.c_str(),ios::app);\n\tost<< time_v<<endl;\n\tost.close();\n/*\tost << \"The optimized shuffle argument took \" << ttime << \" second(s).\" << endl;\n\tost << \"The prover needed \" <<time_p<<\" in total and \"<< \"the verifier needed \"<<time_v<<\" in total\"<<endl;\n\tost << \"The opt. commitments  \"<< time_cm<< \"second(s)\";\n\tost.close();*/\n\n\tdelete P;\n\tdelete V;\n\n\treturn 1;\n}\n", "meta": {"hexsha": "e4d5fc67320a0aea71a166cf9bd372d91499d780", "size": 15370, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "3for/verifiable-shuffle", "max_stars_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T14:06:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T08:28:26.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "3for/verifiable-shuffle", "max_issues_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "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": "3for/verifiable-shuffle", "max_forks_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T06:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T15:21:49.000Z", "avg_line_length": 28.7827715356, "max_line_length": 175, "alphanum_fraction": 0.6944697463, "num_tokens": 4878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5045750996628924}}
{"text": "//=======================================================================\n// Copyright (c) 2013 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 scheduling_jobs_on_identical_parallel_machines_test.cpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2013-09-06\n */\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/scheduling.hpp\"\n#include \"test_utils/test_result_check.hpp\"\n\n#include \"paal/greedy/scheduling_jobs_on_identical_parallel_machines/scheduling_jobs_on_identical_parallel_machines.hpp\"\n\n#include <boost/range/numeric.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <vector>\n\nBOOST_AUTO_TEST_CASE(scheduling_jobs_on_identical_parallel_machines) {\n    // sample data\n    int NUMBER_OF_MACHINES = 3;\n    typedef double Time;\n    std::vector<Time> j = { 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1 };\n    std::vector<std::pair<int, decltype(j)::iterator>> result;\n    paal::greedy::scheduling_jobs_on_identical_parallel_machines(\n        NUMBER_OF_MACHINES, j.begin(), j.end(), back_inserter(result),\n        paal::utils::identity_functor());\n    check_jobs(result, j);\n    std::vector<Time> sum_of_machine;\n    sum_of_machine.resize(NUMBER_OF_MACHINES);\n    for (auto job_machine_pair : result) {\n        sum_of_machine[job_machine_pair.first] += *job_machine_pair.second;\n    }\n\n    Time maximumLoad = *boost::max_element(sum_of_machine);\n\n    Time sum_all_loads = boost::accumulate(sum_of_machine, 0.);\n    // print result\n    check_result(maximumLoad, double(sum_all_loads) / NUMBER_OF_MACHINES, 4./3.);\n}\n", "meta": {"hexsha": "ad6ffd5422a147eaacc1c289b5820c2c9940c1cc", "size": 1741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/greedy/scheduling_jobs_on_identical_parallel_machines_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/greedy/scheduling_jobs_on_identical_parallel_machines_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/greedy/scheduling_jobs_on_identical_parallel_machines_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": 35.5306122449, "max_line_length": 120, "alphanum_fraction": 0.6714531878, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604179, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5045411624776232}}
{"text": "/* ----------------------------------------------------------------------------\n * GTDynamics Copyright 2020, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * See LICENSE for the license information\n * -------------------------------------------------------------------------- */\n\n/**\n * @file  main.cpp\n * @brief Spider trajectory optimization with pre-specified footholds.\n * @author: Alejandro Escontrela, Stephanie McCormick, Disha Das, Tarushree\n * Gandhi, Varun Agrawal\n */\n\n#include <CppUnitLite/TestHarness.h>\n#include <gtdynamics/factors/ObjectiveFactors.h>\n#include <gtdynamics/universal_robot/sdf.h>\n#include <gtdynamics/utils/Trajectory.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n\n#include <algorithm>\n#include <boost/algorithm/string/join.hpp>\n#include <boost/optional.hpp>\n#include <fstream>\n#include <iostream>\n#include <utility>\n\nusing std::string;\nusing std::vector;\n\nusing gtsam::Point3;\nusing gtsam::Pose3;\nusing gtsam::Rot3;\nusing gtsam::Vector6;\nusing gtsam::noiseModel::Isotropic;\nusing gtsam::noiseModel::Unit;\n\nusing namespace gtdynamics;\n\n// Returns a Trajectory object for a single spider walk cycle.\nTrajectory getTrajectory(vector<string> links, Robot robot, size_t repeat) {\n  const Point3 contact_in_com(0, 0.19, 0);\n  Phase stationary(40);\n  stationary.addContactPoints(links, contact_in_com);\n\n  Phase odd(20);\n  odd.addContactPoints(\n      {{\"tarsus_1_L1\", \"tarsus_3_L3\", \"tarsus_5_R4\", \"tarsus_7_R2\"}},\n      contact_in_com);\n\n  Phase even(20);\n  even.addContactPoints(\n      {{\"tarsus_2_L2\", \"tarsus_4_L4\", \"tarsus_6_R3\", \"tarsus_8_R1\"}},\n      contact_in_com);\n\n  WalkCycle walk_cycle;\n  walk_cycle.addPhase(stationary);\n  walk_cycle.addPhase(even);\n  walk_cycle.addPhase(stationary);\n  walk_cycle.addPhase(odd);\n\n  Trajectory trajectory(robot, walk_cycle, repeat);\n  return trajectory;\n}\n\nint main(int argc, char **argv) {\n  // Load Stephanie's spider robot.\n  auto robot =\n      CreateRobotFromFile(kSdfPath + string(\"/spider_alt.sdf\"), \"spider\");\n\n  double sigma_dynamics = 1e-5;   // std of dynamics constraints.\n  double sigma_objectives = 1e-6; // std of additional objectives.\n  double sigma_joints = 1.85e-4;  // 1.85e-4\n\n  // Noise models.\n  auto dynamics_model_6 = Isotropic::Sigma(6, sigma_dynamics),\n       dynamics_model_1 = Isotropic::Sigma(1, sigma_dynamics),\n       dynamics_model_1_2 = Isotropic::Sigma(1, sigma_joints),\n       objectives_model_6 = Isotropic::Sigma(6, sigma_objectives),\n       objectives_model_1 = Isotropic::Sigma(1, sigma_objectives);\n\n  // Env parameters.\n  gtsam::Vector3 gravity(0, 0, -9.8);\n  double mu = 1.0;\n\n  OptimizerSetting opt(sigma_dynamics);\n  DynamicsGraph graph_builder(opt, gravity);\n\n  vector<string> links = {\"tarsus_1_L1\", \"tarsus_2_L2\", \"tarsus_3_L3\",\n                          \"tarsus_4_L4\", \"tarsus_5_R4\", \"tarsus_6_R3\",\n                          \"tarsus_7_R2\", \"tarsus_8_R1\"};\n\n  // Create the trajectory, consisting of 3 walk cycles, each consisting of 4\n  // phases: [stationary, odd, stationary, even].\n  auto trajectory = getTrajectory(links, robot, 3);\n\n  // Create multi-phase trajectory factor graph\n  auto collocation = CollocationScheme::Euler;\n  auto graph = trajectory.multiPhaseFactorGraph(graph_builder, collocation, mu);\n\n  // Build the objective factors.\n  double ground_height = 1.0;\n  const Point3 step(0, 0.4, 0);\n  gtsam::NonlinearFactorGraph objectives =\n      trajectory.contactPointObjectives(Isotropic::Sigma(3, 1e-7), step, ground_height);\n\n  // Get final time step.\n  int K = trajectory.getEndTimeStep(trajectory.numPhases() - 1);\n\n  // Add base goal objectives to the factor graph.\n  auto base_link = robot.link(\"body\");\n  for (int k = 0; k <= K; k++) {\n    objectives.add(\n        LinkObjectives(base_link->id(), k)\n            .pose(Pose3(Rot3(), Point3(0, 0.0, 0.5)), Isotropic::Sigma(6, 5e-5))\n            .twist(gtsam::Z_6x1, Isotropic::Sigma(6, 5e-5)));\n  }\n\n  // Add link and joint boundary conditions to FG.\n  trajectory.addBoundaryConditions(&objectives, dynamics_model_6,\n                                   dynamics_model_6, objectives_model_6,\n                                   objectives_model_1, objectives_model_1);\n\n  // Constrain all Phase keys to have duration of 1 /240.\n  const double desired_dt = 1. / 240;\n  trajectory.addIntegrationTimeFactors(&objectives, desired_dt, 1e-30);\n\n  // Add min torque objectives.\n  trajectory.addMinimumTorqueFactors(&objectives, Unit::Create(1));\n\n  // Add prior on hip joint angles (spider specific)\n  auto prior_model = Isotropic::Sigma(1, 1.85e-4);\n  for (auto &&joint : robot.joints())\n    if (joint->name().find(\"hip2\") == 0)\n      for (int k = 0; k <= K; k++)\n        objectives.add(JointObjectives(joint->id(), k).angle(2.5, prior_model));\n\n  // Add objectives to factor graph.\n  graph.add(objectives);\n\n  // Initialize solution.\n  double gaussian_noise = 1e-5;\n  gtsam::Values init_vals =\n      trajectory.multiPhaseInitialValues(gaussian_noise, desired_dt);\n\n  // Optimize!\n  gtsam::LevenbergMarquardtParams params;\n  params.setVerbosityLM(\"SUMMARY\");\n  params.setlambdaInitial(1e10);\n  params.setlambdaLowerBound(1e-7);\n  params.setlambdaUpperBound(1e10);\n  params.setAbsoluteErrorTol(1.0);\n  gtsam::LevenbergMarquardtOptimizer optimizer(graph, init_vals, params);\n  auto results = optimizer.optimize();\n\n  // Write results to traj file\n  trajectory.writeToFile(\"forward_traj.csv\", results);\n\n  return 0;\n}\n", "meta": {"hexsha": "ad4c4bca657ae8ba80b304bda0bbfc082afe61b0", "size": 5503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example_spider_walking/main.cpp", "max_stars_repo_name": "danbarla/GTDynamics", "max_stars_repo_head_hexsha": "0448b359aff9e0e784832666e4048ee01c8b082d", "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/example_spider_walking/main.cpp", "max_issues_repo_name": "danbarla/GTDynamics", "max_issues_repo_head_hexsha": "0448b359aff9e0e784832666e4048ee01c8b082d", "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/example_spider_walking/main.cpp", "max_forks_repo_name": "danbarla/GTDynamics", "max_forks_repo_head_hexsha": "0448b359aff9e0e784832666e4048ee01c8b082d", "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.9691358025, "max_line_length": 88, "alphanum_fraction": 0.6868980556, "num_tokens": 1527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5045411522052141}}
{"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 FIVE_POINT_UTIL_HPP_\n#define FIVE_POINT_UTIL_HPP_\n\n#include <Eigen/Dense>\n\n#include <random>\n#include <vector>\n\nnamespace FivePoint\n{\n\ntemplate <typename FloatType, typename RNG>\nvoid getRandomPose(RNG &rng, FloatType *R, FloatType *t)\n{\n    using std::cos;\n    using std::sin;\n\tstd::uniform_real_distribution<FloatType> urd(0, static_cast<FloatType>(M_PI));\n\tFloatType phi   = 2 * urd(rng);\n\tFloatType theta = urd(rng);\n\tFloatType psi   = 2 * urd(rng);\n\n\tEigen::Map<Eigen::Matrix<FloatType, 3, 3, Eigen::RowMajor> >mR(R);\n\n\tmR(0, 0) = cos(psi) * cos(phi) - cos(theta) * sin(phi) * sin(psi);\n\tmR(0, 1) = cos(psi) * sin(phi) + cos(theta) * cos(phi) * sin(psi);\n\tmR(0, 2) = sin(psi) * sin(theta);\n\tmR(1, 0) = -sin(psi) * cos(phi) - cos(theta) * sin(phi) * cos(psi);\n\tmR(1, 1) = -sin(psi) * sin(phi) + cos(theta) * cos(phi) * cos(psi);\n\tmR(1, 2) = cos(psi) * sin(theta);\n\tmR(2, 0) = sin(theta) * sin(phi);\n\tmR(2, 1) = -sin(theta) * cos(phi);\n\tmR(2, 2) = cos(theta);\n\tt[0] = 0.0;\n\tt[1] = 0.0;\n\tt[2] = 6.0;\n}\n\ntemplate <typename FloatType, typename RNG>\nvoid getRandomPoints(RNG &rng, int n, std::vector<FloatType> &p)\n{\n    using std::cos;\n    using std::sin;\n\tconst FloatType pi = static_cast<FloatType>(M_PI);\n\tstd::uniform_real_distribution<FloatType> urd(0, 1);\n\n\tp.resize(0);\n\tp.reserve(3 * n);\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tFloatType theta = pi * urd(rng), phi = 2 * pi * urd(rng), R = 2 * urd(rng);\n\t\tFloatType X =  sin(theta) * sin(phi) * R;\n\t\tFloatType Y = -sin(theta) * cos(phi) * R;\n\t\tFloatType Z =  cos(theta) * R;\n\n\t\tp.push_back(X);\n\t\tp.push_back(Y);\n\t\tp.push_back(Z);\n\t}\n}\n\ntemplate <typename FloatType>\nvoid getRandomCorrespondences(int n, FloatType *R, FloatType *t, std::vector<FloatType> &pts1, std::vector<FloatType> &pts2)\n{\n\tstd::random_device rd;\n\tstd::mt19937 rng(rd());\n\tFloatType R1[9], R2[9], t1[3], t2[3];\n\tgetRandomPose(rng, R1, t1);\n\tgetRandomPose(rng, R2, t2);\n\n\tstd::vector<FloatType> pts;\n\tgetRandomPoints(rng, n, pts);\n\n\tEigen::Map<Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic> > mP(&(pts[0]), 3, n);\n\tEigen::Matrix<FloatType, 3, 3, Eigen::RowMajor> mR1(R1);\n\tEigen::Matrix<FloatType, 3, 3, Eigen::RowMajor> mR2(R2);\n\tEigen::Matrix<FloatType, 3, 1> mt1(t1);\n\tEigen::Matrix<FloatType, 3, 1> mt2(t2);\n\n\tEigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic> mP1(3, n);\n\tmP1 = (mR1 * mP).colwise() + mt1;\n\tpts1.resize(2*n);\n\tEigen::Map<Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic> > mp1(&(pts1[0]), 2, n);\n\tmp1.row(0) = mP1.row(0).array() / mP1.row(2).array();\n\tmp1.row(1) = mP1.row(1).array() / mP1.row(2).array();\n\n\tEigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic> mP2(3, n);\n\tmP2 = (mR2 * mP).colwise() + mt2;\n\tpts2.resize(2*n);\n\tEigen::Map<Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic> > mp2(&(pts2[0]), 2, n);\n\tmp2.row(0) = mP2.row(0).array() / mP2.row(2).array();\n\tmp2.row(1) = mP2.row(1).array() / mP2.row(2).array();\n\n\tEigen::Map<Eigen::Matrix<FloatType, 3, 3, Eigen::RowMajor> > mR(R);\n\tEigen::Map<Eigen::Matrix<FloatType, 3, 1> > mt(t);\n\tmR = mR2*mR1.transpose();\n\tmt = mt2 - mR*mt1;\n}\n}\n\n#endif // FIVE_POINT_UTIL_HPP_", "meta": {"hexsha": "ce86b5c4741a939e91f6fb5b46873f8a3f54fd2e", "size": 4540, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/FivePointUtil.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/FivePointUtil.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/FivePointUtil.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": 36.6129032258, "max_line_length": 124, "alphanum_fraction": 0.6790748899, "num_tokens": 1470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5045411503131685}}
{"text": "///3\n// ALGOLAB BGL Tutorial 3\n// Flow example demonstrating\n// - breadth first search (BFS) on the residual graph\n\n// Compile and run with one of the following:\n// g++ -std=c++11 -O2 bgl_residual_bfs.cpp -o bgl_residual_bfs ./bgl_residual_bfs\n// g++ -std=c++11 -O2 -I path/to/boost_1_58_0 bgl_residual_bfs.cpp -o bgl_residual_bfs; ./bgl_residual_bfs\n\n// Includes\n// ========\n// STL includes\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <queue>\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/tuple/tuple.hpp>\n\n// BGL graph definitions\n// =====================\n// Graph Type with nested interior edge properties for Flow Algorithms\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// Interior Property Maps\ntypedef traits::vertex_descriptor vertex_desc;\n\ntypedef  boost::graph_traits<graph>::edge_descriptor      edge_desc;\ntypedef  boost::graph_traits<graph>::out_edge_iterator      out_edge_it;\n\n// Custom Edge Adder Class, that holds the references\n// to the graph, capacity map and reverse edge map\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 edge_desc e = boost::add_edge(from, to, G).first;\n    const edge_desc 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\n\nvoid add_if_present(edge_adder & adder, std::vector<int> &present, int n, int u, int i, int j, int c) {\n  if(i >= 0 && j >= 0 && i <= (n-1) && j <= (n-1)) {\n    if(present[i * n + j]) {\n      adder.add_edge(u, i * n + j, c);\n    }\n  }\n}\n\n// Main\nvoid testcase() {\n  // build graph\n  int n;\n  std::cin >> n;\n  graph G(n * n);\n  edge_adder adder(G);\n  // auto rc_map = boost::get(boost::edge_residual_capacity, G);\n  const vertex_desc v_source = boost::add_vertex(G);\n  const vertex_desc v_sink = boost::add_vertex(G);\n  std::vector<int> present(n*n);\n  \n  int sum_present = 0;\n  for(int i = 0; i < n; i++) {\n    for(int j = 0; j < n; j++) {\n      std::cin >> present[i * n + j];\n      if(present[i * n + j]) {\n        sum_present++;\n        if((i + j) % 2 == 0)\n          adder.add_edge(v_source, i * n + j, 1);\n        else\n          adder.add_edge(i * n + j, v_sink, 1);\n      }\n    }\n  }\n  \n  for(int i = 0; i < n; i++) {\n    for(int j = 0; j < n; j++) {\n      int ij = i * n + j;\n      if(present[ij] && (i + j) % 2 == 0) {\n        add_if_present(adder, present, n, ij, (i - 1), j - 2, 1);\n        add_if_present(adder, present, n, ij, (i - 1), j + 2, 1);\n        add_if_present(adder, present, n, ij, (i + 1), j - 2, 1);\n        add_if_present(adder, present, n, ij, (i + 1), j + 2, 1);\n        add_if_present(adder, present, n, ij, (i - 2), j - 1, 1);\n        add_if_present(adder, present, n, ij, (i - 2), j + 1, 1);\n        add_if_present(adder, present, n, ij, (i + 2), j - 1, 1);\n        add_if_present(adder, present, n, ij, (i + 2), j + 1, 1);\n      //   if(i > 0 && j > 1)\n      //     adder.add_edge(ij, (i - 1) * n + j - 2, 1);\n      //   if(i > 0 && j < (n - 2))\n      //     adder.add_edge(ij, (i - 1) * n + j + 2, 1);\n      //   if(i < (n - 1) && j > 1)\n      //     adder.add_edge(ij, (i + 1) * n + j - 2, 1);\n      //   if(i < (n - 1) && j < (n - 2))\n      //     adder.add_edge(ij, (i + 1) * n + j + 2, 1);\n      //   if(i > 1 && j > 0)\n      //     adder.add_edge(ij, (i - 2) * n + j - 1, 1);\n      //   if(i > 1 && j < (n - 1))\n      //     adder.add_edge(ij, (i - 2) * n + j + 1, 1);\n      //   if(i < (n - 2) && j > 0)\n      //     adder.add_edge(ij, (i + 2) * n + j - 1, 1);\n      //   if(i < (n - 2) && j < (n - 1))\n      //     adder.add_edge(ij, (i + 2) * n + j + 1, 1);\n      }\n    }\n  }\n  \n  // for(int i = 0; i < n; i++) {\n  //   // adder.add_edge(v_source, i, 1);\n  //   adder.add_edge(i, v_sink,  std::numeric_limits<int>::max());\n  // }\n  \n  int flow = boost::push_relabel_max_flow(G, v_source, v_sink);\n  // auto c_map = boost::get(boost::edge_capacity, G);\n  // auto rc_map = boost::get(boost::edge_residual_capacity, G);\n  // Find a min cut via maxflow\n  std::cout << sum_present - flow << \"\\n\";\n  // std::cerr << std::endl;\n  // // Retrieve the capacity map and reverse capacity map\n  // const auto c_map = boost::get(boost::edge_capacity, G);\n  // const auto rc_map = boost::get(boost::edge_residual_capacity, G);\n\n  // // Iterate over all the edges to print the flow along them\n  // auto edge_iters = boost::edges(G);\n  // for (auto edge_it = edge_iters.first; edge_it != edge_iters.second; ++edge_it) {\n  //   const edge_desc edge = *edge_it;\n  //   const long flow_through_edge = c_map[edge] - rc_map[edge];\n  //   std::cerr << \"edge from \" << boost::source(edge, G) << \" to \" << boost::target(edge, G)\n  //             << \" runs \" << flow_through_edge\n  //             << \" units of flow (negative for reverse direction). \\n\";\n  // }\n}\n\nint main() {\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": "eea059accf904d33ed8b0b55033da3f6bce92286", "size": 5591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week09-placing_knights/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/week09-placing_knights/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/week09-placing_knights/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.8397435897, "max_line_length": 106, "alphanum_fraction": 0.5637631908, "num_tokens": 1855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5045411503131685}}
{"text": "#include <iostream>\n//\n#include <polyvec/api.hpp>\n#include <polyvec/curve-tracer/bezier_merging.hpp>\n#include <polyvec/curve-tracer/curve_bezier.hpp>\n#include <polyvec/core/log.hpp>\n#include <polyvec/misc.hpp>\n#include <polyvec/utils/num.hpp>\n#include <polyvec/utils/string.hpp>\n#include <polyvec/io/vtk_curve_writer.hpp>\n#include <polyvec/geometry/winding_number.hpp>\n//\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n// These are only required by the second test, i.e., _potrace_merge()\n#include <dev/pdf.hpp>\n#include <polyvec/image-segment/image_segment.hpp>\n#include <polyvec/io/image.hpp>\n#include <polyvec/utils/potrace.hpp>\n\nNAMESPACE_BEGIN()\n\n\n::polyvec::BezierCurve build_bezier(const Eigen::Matrix<double, 2, 4> ctrl) {\n  ::polyvec::BezierCurve bz;\n  bz.set_control_points(ctrl);\n  return bz;\n};\n\n\n\n\nvoid draw_control_polygon(const std::vector<Eigen::Matrix2Xd>& curves) {\n  using namespace polyvec;\n  for (int i = 0; i < (int)curves.size(); ++i) {\n    if (curves[i].cols() == 4) {\n      draw::line(curves[i].col(0), curves[i].col(1),\n                 Style::outline(colors::talking_orange, .1));\n      draw::line(curves[i].col(1), curves[i].col(2),\n                 Style::outline(colors::talking_orange, .1));\n      draw::line(curves[i].col(2), curves[i].col(3),\n                 Style::outline(colors::talking_orange, .1));\n    } else {\n      // draw::line(curves[i].col(0), curves[i].col(1),\n      //            Style::outline(colors::forest_green, .1));\n    }\n  }\n}\n\nvoid draw_curves(const std::vector<Eigen::Matrix2Xd>& curves) {\n  using namespace polyvec;\n  for (int i = 0; i < (int)curves.size(); ++i) {\n    if (curves[i].cols() == 4) {\n      Eigen::Vector3d color =\n          i % 2 == 0 ? colors::talking_orange : colors::enemys_blood;\n      auto bz = build_bezier(curves[i]);\n      auto tess = bz.get_tesselation2();\n      for (int j = 0; j < (int)tess.cols() - 1; ++j)\n        draw::line(tess.col(j), tess.col(j + 1),\n                   Style::outline(color, 7));\n    } else {\n      Eigen::Vector3d color = i % 2 == 0 ? colors::forest_green : colors::green;\n      draw::line(curves[i].col(0), curves[i].col(1), Style::outline(color, 7));\n    }\n  }\n}\n\nvoid draw_curves_fill(const std::vector<Eigen::Matrix2Xd>& curves) {\n  using namespace polyvec;\n  vec<real2> polygon;\n  for (int i = 0; i < (int)curves.size(); ++i) {\n    if (curves[i].cols() == 4) {\n      auto bz = build_bezier(curves[i]);\n      auto tess = bz.get_tesselation2();\n      for (int j = 0; j < (int)tess.cols() - 1; ++j)\n        polygon.push_back(tess.col(j));\n    } else {\n      for (int j = 0; j < (int)curves[i].cols() - 1; ++j)\n           polygon.push_back(curves[i].col(j));\n    } \n  }\n  draw::polygon(polygon, Style::fill(colors::dark_gray));\n}\n\n\nvoid _tiny_merges() {\n  using Mat24 = Eigen::Matrix<double, 2, 4>;\n  using Mat22 = Eigen::Matrix<double, 2, 2>;\n\n  std::vector<Eigen::Matrix2Xd> curves;\n  std::vector<Eigen::Matrix2Xd> curves_merged;\n  std::vector<std::vector<int>> out2in;\n  bool is_circular;\n  double per_curve_cost;\n\n  int dump_counter = 0;\n  auto write_results = [&]() {\n    // Write the unmerged\n    polyvec::VtkCurveWriter writer;\n\n    writer.add_point(curves.back().col(curves.back().cols() - 1));\n\n    for (const Eigen::Matrix2Xd& bzc : curves) {\n      if (bzc.cols() == 4)\n        writer.add_polyline(build_bezier(bzc).get_tesselation2());\n      if (bzc.cols() == 2) writer.add_polyline(bzc);\n      for (int i = 0; i < (int)bzc.cols(); ++i) {\n        writer.add_point(bzc.col(i));\n      }\n    }\n\n    writer.dump(polyfit::StringUtils::fmt(\"test_dump/merge_curves_%04d_%d.vtk\",\n                                          0, dump_counter));\n    writer.clear();\n\n    // Write the merged\n\n    writer.add_point(curves.back().col(curves.back().cols() - 1));\n\n    for (const Eigen::Matrix2Xd& bzc : curves_merged) {\n      if (bzc.cols() == 4)\n        writer.add_polyline(build_bezier(bzc).get_tesselation2());\n      if (bzc.cols() == 2) writer.add_polyline(bzc);\n      for (int i = 0; i < (int)bzc.cols(); ++i) {\n        writer.add_point(bzc.col(i));\n      }\n    }\n\n    writer.dump(polyfit::StringUtils::fmt(\"test_dump/merge_curves_%04d_%d.vtk\",\n                                          1, dump_counter));\n    writer.clear();\n\n    ++dump_counter;\n  };\n\n  auto attempt_merge = [&]() {\n    polyfit::BezierMerging::MergeRecursivelyOptions options;\n    options.distance_tolerance = 1.;\n    options.alpha_max = 0.99; // allow a bigger alpha here so that the merge succeed\n    options.per_bezier_const =per_curve_cost;\n    options.allow_merging_lines = true; // let this work for more testing.\n\n    polyfit::BezierMerging::merge_recursively(\n        curves, is_circular, options,  curves_merged, out2in);\n    printf(\"ATTEMP %d \\n \", dump_counter);\n    for (int i = 0; i < (int)curves_merged.size(); ++i) {\n      printf(\"Curve %d | merged \", i);\n      for (int j = 0; j < (int)out2in[i].size(); ++j)\n        printf(\"%d, \", out2in[i][j]);\n      printf(\" \\n \");\n    }\n\n    write_results();\n  };\n\n  //\n  // First try a single bezier\n  //\n  is_circular = false;\n  curves.clear();\n  curves.push_back(Mat24());\n  curves.back().col(0) << -1, 0;\n  curves.back().col(1) << -0.25, 0.75;\n  curves.back().col(2) << 0.7, 0.3;\n  curves.back().col(3) << 1, 0;\n  attempt_merge();\n\n  //\n  // Now  single bezier with one line before failes\n  //\n  is_circular = false;\n  per_curve_cost = 0.2;\n  curves.clear();\n  //\n  curves.push_back(Mat22());\n  curves.front().col(0) << -2, -1;\n  curves.front().col(1) << -1, 0;\n  //\n  curves.push_back(Mat24());\n  curves.back().col(0) << -1, 0;\n  curves.back().col(1) << -0.25, 0.75;\n  curves.back().col(2) << 0.7, 0.3;\n  curves.back().col(3) << 1, 0;\n  attempt_merge();\n\n  //\n  // Reduce the cost and try again.\n  //\n  is_circular = false;\n  per_curve_cost = 0.10;\n  attempt_merge();\n\n  //\n  //  Now  single bezier with one line before and one after\n  //\n  is_circular = false;\n  per_curve_cost = 0.2;\n  curves.clear();\n  //\n  curves.push_back(Mat22());\n  curves.back().col(0) << -1.5, -0.5;\n  curves.back().col(1) << -1, 0;\n  //\n  curves.push_back(Mat24());\n  curves.back().col(0) << -1, 0;\n  curves.back().col(1) << -0.25, 0.75;\n  curves.back().col(2) << 0.7, 0.3;\n  curves.back().col(3) << 1, 0;\n  //\n  curves.push_back(Mat22());\n  curves.back().col(0) << 1, 0;\n  curves.back().col(1) << 1.5, -0.5;\n  //\n  attempt_merge();\n\n  //\n  // Reduce the cost and try again.\n  //\n  is_circular = false;\n  per_curve_cost = 0.025;\n  attempt_merge();\n\n  //\n  // Same as before just transform\n  //\n  is_circular = false;\n  per_curve_cost = 0.2;\n  curves.clear();\n  curves.push_back(Mat22());\n  curves.back().col(0) << -1.25, -0.25;\n  curves.back().col(1) << -1, 0;\n  //\n  curves.push_back(Mat24());\n  curves.back().col(0) << -1, 0;\n  curves.back().col(1) << -0.25, 0.75;\n  curves.back().col(2) << 0.7, 0.3;\n  curves.back().col(3) << 1, 0;\n  //\n  curves.push_back(Mat22());\n  curves.back().col(0) << 1, 0;\n  curves.back().col(1) << 1.1, -0.1;\n  {\n    Eigen::Matrix2d A;\n    A << -3, 1, 2, -4;\n    Eigen::Vector2d b;\n    b << -1, 4;\n    for (Eigen::Matrix2Xd& bz : curves) {\n      bz = ((A * bz).colwise() + b).eval();\n    }\n  }\n  attempt_merge();\n\n  //\n  // Reduce the cost and try again.\n  //\n  is_circular = false;\n  per_curve_cost = 0.025;\n  attempt_merge();\n\n  //\n  // Now add two beziers\n  //\n  is_circular = false;\n  per_curve_cost = 0.2;\n  curves.clear();\n  //\n  curves.push_back(Mat22());\n  curves.back().col(0) << -1.25, -0.25;\n  curves.back().col(1) << -1, 0;\n  //\n  curves.push_back(Mat24());\n  curves.back().col(0) << -1, 0;  //\n  curves.back().col(1) << -0.6, 0.4;\n  curves.back().col(2) << -0.2, 0.6;  //\n  curves.back().col(3) << 0, 0.6;     //\n  curves.push_back(Mat24());\n  curves.back().col(0) << 0, 0.6;    //\n  curves.back().col(1) << 0.3, 0.6;  //\n  curves.back().col(2) << 0.65, 0.35;\n  curves.back().col(3) << 1, 0;  //\n  //\n  curves.push_back(Mat22());\n  curves.back().col(0) << 1, 0;\n  curves.back().col(1) << 1.1, -0.1;\n\n  {\n    Eigen::Matrix2d A;\n    A << -3, 1, 2, -4;\n    Eigen::Vector2d b;\n    b << -1, 4;\n\n    for (Eigen::Matrix2Xd& bz : curves) {\n      bz = ((A * bz).colwise() + b).eval();\n    }\n  }\n  attempt_merge();\n\n  //\n  // Reduce cost and run again\n  //\n  is_circular = false;\n  per_curve_cost = 0.025;\n  attempt_merge();\n}\n\nvoid _potrace_output_merges(const std::string input_address,\n                            const std::vector<double>& percurve_penalty) {\n  using namespace polyfit;\n  static int dump_id = 0;\n\n  // Read the image\n  IO::Image I;\n  if (!IO::read_image(input_address.c_str(), I)) {\n    printf(\"image not found %s\", input_address.c_str());\n    return;\n  }\n\n  // Get the boundary\n  std::vector<mat2x> boundaries;\n  std::vector<vec4> colors;\n  ImageSegment::expand_and_cleanup(I);\n  ImageSegment::extract_closed_regions(I, boundaries, colors);\n  const mat2x& R =\n      boundaries[ImageSegment::find_binary_color_region(boundaries)];\n\n  // Run the potrace pipeline to get some curves\n  std::vector<Eigen::Matrix2Xd> curves = PotraceUtil::run_pipeline(\n      R, false /* does not really matter */, false /*absolutely don't merge */);\n\n  std::unique_ptr<::polyvec::DevicePDF> pdf;\n\n  //\n  // Draw the image by random colors\n  //\n  pdf.reset(new ::polyvec::DevicePDF(\n      ::polyvec::misc::sfmt(\"test_dump/merge_curves_potrace_%04d.pdf\", dump_id).c_str(),\n      (int)(2 + percurve_penalty.size()), 2));\n\n  draw_curves_fill({R});\n  pdf->draw(0, 0);\n\n  draw_curves(curves);\n  pdf->draw(1, 0);\n\n  draw_curves_fill(curves);\n  pdf->draw(1, 1);\n\n  for (int j = 0; j < (int)percurve_penalty.size(); ++j) {\n    std::vector<Eigen::Matrix2Xd> curves_merged;\n    std::vector<std::vector<int>> out2in;\n\n    polyfit::BezierMerging::MergeRecursivelyOptions options;\n    options.distance_tolerance = 0.3;\n    options.alpha_max = 0.8;\n    options.per_bezier_const =percurve_penalty[j];\n    options.allow_merging_lines = true; // let this work for more testing.\n\n    polyfit::BezierMerging::merge_recursively(\n        curves, true, options, curves_merged, out2in);\n\n    draw_curves(curves_merged);\n    pdf->draw(j+2, 0);\n\n    draw_curves_fill(curves_merged);\n    pdf->draw(j+2, 1);\n  }\n\n  ++dump_id;\n}\n\nvoid _polyfit_output_merges(const std::string input_address,\n                            const std::vector<double>& percurve_penalty) {\n  using namespace polyfit;\n  static int dump_id = 0;\n\n  std::unique_ptr<::polyvec::DevicePDF> pdf;\n\n  //\n  // Draw the image by random colors\n  //\n  pdf.reset(new ::polyvec::DevicePDF(\n      ::polyvec::misc::sfmt(\"test_dump/merge_curves_polyfit_%04d.pdf\", dump_id).c_str(),\n      (int)(1 + percurve_penalty.size()), 2));\n\n  FILE *fl = fopen(input_address.c_str(),\"r\");\n  std::vector<Eigen::Matrix2Xd> curves = BezierMerging::read_curve_sequence(fl);\n  fclose(fl);\n\n  draw_curves(curves);\n  pdf->draw(0, 0);\n\n  draw_curves_fill(curves);\n  pdf->draw(0, 1);\n\n  for (int j = 0; j < (int)percurve_penalty.size(); ++j) {\n    std::vector<Eigen::Matrix2Xd> curves_merged;\n    std::vector<std::vector<int>> out2in;\n\n    polyfit::BezierMerging::MergeRecursivelyOptions options;\n    options.distance_tolerance = 0.3;\n    options.alpha_max = 0.8;\n    options.per_bezier_const =percurve_penalty[j];\n    options.allow_merging_lines = true; // let this work for more testing.\n\n    polyfit::BezierMerging::merge_recursively(\n        curves, true, options, curves_merged, out2in);\n\n    draw_curves(curves_merged);\n    pdf->draw(j+1, 0);\n\n    draw_curves_fill(curves_merged);\n    pdf->draw(j+1, 1);\n  }\n\n  ++dump_id;\n}\n\nNAMESPACE_END()\n\nNAMESPACE_BEGIN(polyvectest)\nNAMESPACE_BEGIN(BezierMerging)\n\nint merge_curves(int, char**) {\n  // ::_polyfit_output_merges(POLYVEC_TEST_PATH \"/bezier_merging/merge_failure_01.txt\", {3});\n  // return EXIT_FAILURE;\n\n  // MINY TESTS\n  ::_tiny_merges();\n\n  // POLYFIT FAILURES\n  ::_polyfit_output_merges(POLYVEC_TEST_PATH \"/bezier_merging/merge_failure_01.txt\", {3});\n\n  // POTRACE\n  #define PREFIX \"/home/hooshi/code/raster2vector-2019/polyvec_data/binary-perfect\"\n  std::vector<double> params_to_test = {1, 2, 3 , 4};\n  // ::_potrace_output_merges(PREFIX \"/castle/32.png\",params_to_test);\n  ::_potrace_output_merges(PREFIX \"/castle/64.png\", params_to_test);\n  // ::_potrace_output_merges(PREFIX \"/apple/32.png\", params_to_test);\n  ::_potrace_output_merges(PREFIX \"/apple/64.png\", params_to_test);\n  // ::_potrace_output_merges(PREFIX \"/plane/32.png\", params_to_test);\n  ::_potrace_output_merges(PREFIX \"/plane/64.png\", params_to_test);\n  ::_potrace_output_merges(PREFIX \"/tabletennis/32.png\", params_to_test);\n  ::_potrace_output_merges(PREFIX \"/tabletennis/64.png\", params_to_test);\n  #undef PREFIX\n\n  return EXIT_FAILURE;\n}\n\nNAMESPACE_END(BezierMerging)\nNAMESPACE_END(polyvectest)\n", "meta": {"hexsha": "2a1bfc1f47d3d3f1b5d681a53cb99678889c8b1a", "size": 12683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/tests/bezier_merging/_merge_curves.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/_merge_curves.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/_merge_curves.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": 28.0597345133, "max_line_length": 93, "alphanum_fraction": 0.6205156509, "num_tokens": 3995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5045411432849181}}
{"text": "/*\n * Bayes++ the Bayesian Filtering Library\n * Copyright (c) 2004 Michael Stevens\n * See accompanying Bayes++.htm for terms and conditions of use.\n *\n * $Id$\n */\n\n/*\n * SLAM : Simultaneous Locatization and Mapping\n *  Kalman filter representing representation of SLAM\n */\n\n\t\t// Bayes++ Bayesian filtering schemes\n#include \"BayesFilter/bayesFlt.hpp\"\n\t\t// Bayes++ SLAM\n#include \"SLAM.hpp\"\n#include \"kalmanSLAM.hpp\"\n#include <iostream>\n#include <boost/numeric/ublas/io.hpp>\n\nnamespace SLAM_filter\n{\n\ntemplate <class Base>\ninline void zero(FM::ublas::matrix_range<Base> A)\n// Zero a matrix_range\n{\t// Note A cannot be a reference\n\ttypedef typename Base::value_type Base_value_type;\n\tFM::noalias(A) = FM::ublas::scalar_matrix<Base_value_type>(A.size1(),A.size2(), Base_value_type());\n}\n\nKalman_SLAM::Kalman_SLAM( Kalman_filter_generator& filter_generator ) :\n\tSLAM(),\n\tfgenerator(filter_generator),\n\tloc(0), full(0)\n{\n\tnL = 0;\n\tnM = 0;\n}\n\nKalman_SLAM::~Kalman_SLAM()\n{\n\tfgenerator.dispose (loc);\n\tfgenerator.dispose (full);\n}\n\nvoid Kalman_SLAM::init_kalman (const FM::Vec& x, const FM::SymMatrix& X)\n{\n\t// TODO maintain map states\n\tnL = x.size();\n\tnM = 0;\n\tif (loc) fgenerator.dispose (loc);\n\tif (full) fgenerator.dispose (full);\n\t\t// generate a location filter for prediction\n\tloc = fgenerator.generate(nL);\n\t\t// generate full filter\n\tfull = fgenerator.generate(nL);\n\t\t// initialise location states\n\tfull->x.sub_range(0,nL) = x;\n\tfull->X.sub_matrix(0,nL,0,nL) = X;\n\tfull->init();\n}\n\nvoid Kalman_SLAM::predict( BF::Linrz_predict_model& lpred )\n{\n\t\t// extract location part of full\n\tloc->x = full->x.sub_range(0,nL);\n\tloc->X = full->X.sub_matrix(0,nL,0,nL);\n\t\t// predict location, independent of map\n\tloc->init();\n\tloc->predict (lpred);\n\tloc->update();\n\t\t// return location to full\n\tfull->x.sub_range(0,nL) = loc->x;\n\tfull->X.sub_matrix(0,nL,0,nL) = loc->X;\n\tfull->init();\n}\n\nvoid Kalman_SLAM::observe( unsigned feature, const Feature_observe& fom, const FM::Vec& z )\n{\n\t// Assume features added sequentially\n\tif (feature >= nM) {\n\t\terror (BF::Logic_exception(\"Observe non existing feature\"));\n\t\treturn;\n\t}\n\t// TODO Implement nonlinear form\n\t// Create a augmented sparse observe model for full states\n\tBF::Linear_uncorrelated_observe_model fullm(full->x.size(), 1);\n\tfullm.Hx.clear();\n\tfullm.Hx.sub_matrix(0,nL, 0,nL) = fom.Hx.sub_matrix(0,nL, 0,nL);\n\tfullm.Hx(0,nL+feature) = fom.Hx(0,nL);\n\tfullm.Zv = fom.Zv;\n\tfull->observe(fullm, z);\n}\n\nvoid Kalman_SLAM::observe_new( unsigned feature, const Feature_observe_inverse& fom, const FM::Vec& z )\n// fom: must have a the special form required for SLAM::obeserve_new\n{\n\t\t// size consistency, single state feature\n\tif (fom.Hx.size1() != 1)\n\t\terror (BF::Logic_exception(\"observation and model size inconsistent\"));\n\t\t\n\t\t// make new filter with additional (uninitialized) feature state\n\tif (feature >= nM)\n\t{\n\t\tnM = feature+1;\t\n\t\tKalman_filter_generator::Filter_type* nf = fgenerator.generate(nL+nM);\n\t\tFM::noalias(nf->x.sub_range(0,full->x.size())) = full->x;\n\t\tFM::noalias(nf->X.sub_matrix(0,full->x.size(),0,full->x.size())) = full->X;\n\n\t\tfgenerator.dispose(full);\n\t\tfull = nf;\n\t}\n\t\t// build augmented location and observation\n\tFM::Vec sz(nL+z.size());\n\tsz.sub_range(0,nL) = full->x.sub_range(0,nL);\n\tsz.sub_range(nL,nL+z.size() )= z;\n\n\t// TODO use named references rather then explict Ha Hb\n\tFM::Matrix Ha (fom.Hx.sub_matrix(0,1, 0,nL) );\n\tFM::Matrix Hb (fom.Hx.sub_matrix(0,1, nL,nL+z.size()) );\n\tFM::Matrix tempHa (1,nL);\n\tFM::Matrix tempHb (1,sz.size());\n\n\t\t// feature covariance with existing location and features\n        // X+ = [0 Ha] X [0 Ha]' + Hb Z Hb'\n        // - zero existing feature covariance\n\tzero( full->X.sub_matrix(0,full->X.size1(), nL+feature,nL+feature+1) );\n\tfull->X.sub_matrix(nL+feature,nL+feature+1,0,nL+nM) = FM::prod(Ha,full->X.sub_matrix(0,nL, 0,nL+nM) );\n\t\t// feature state and variance\n\tfull->x[nL+feature] = fom.h(sz)[0];\n\tfull->X(nL+feature,nL+feature) = ( FM::prod_SPD(Ha,full->X.sub_matrix(0,nL, 0,nL),tempHa) +\n\t\t\t\t\t\t\t\t\t\t\t\t\t  FM::prod_SPD(Hb,fom.Zv,tempHb)\n\t\t\t\t\t\t\t\t\t\t\t\t\t ) (0,0);\n\t\t\n\tfull->init ();\n}\n\nvoid Kalman_SLAM::observe_new( unsigned feature, const FM::Float& t, const FM::Float& T )\n{\n\t\t// Make space in scheme for feature, requires the scheme can deal with resized state\n\tif (feature >= nM)\n\t{\n\t\tKalman_filter_generator::Filter_type* nf = fgenerator.generate(nL+feature+1);\n\t\tFM::noalias(nf->x.sub_range(0,full->x.size())) = full->x;\n\t\tFM::noalias(nf->X.sub_matrix(0,full->x.size(),0,full->x.size())) = full->X;\n\t\tzero( nf->X.sub_matrix(0,nf->X.size1(), nL+nM,nf->X.size2()) );\n\n\t\tnf->x[nL+feature] = t;\n\t\tnf->X(nL+feature,nL+feature) = T;\n\t\tnf->init ();\n\t\tfgenerator.dispose(full);\n\t\tfull = nf;\n\t\tnM = feature+1;\n\t}\n\telse\n\t{\n\t\tfull->x[nL+feature] = t;\n\t\tfull->X(nL+feature,nL+feature) = T;\n\t\tfull->init ();\n\t}\n}\n\nvoid Kalman_SLAM::forget( unsigned feature, bool must_exist )\n{\n\tfull->x[nL+feature] = 0.;\n\t\t\t// ISSUE uBLAS has problems accessing the lower symmetry via a sub_matrix proxy, there two two parts seperately\n\tzero( full->X.sub_matrix(0,nL+feature, nL+feature,nL+feature+1) );\n\tzero( full->X.sub_matrix(nL+feature,nL+feature+1, nL+feature,full->X.size1()) );\n\tfull->init();\n}\n\nvoid Kalman_SLAM::decorrelate( Bayesian_filter::Bayes_base::Float d )\n// Reduce correlation by scaling cross-correlation terms\n{\n\tstd::size_t i,j;\n\tconst std::size_t n = full->X.size1();\n\tfor (i = 1; i < n; ++i)\n\t{\n\t\tFM::SymMatrix::Row Xi(full->X,i);\n\t\tfor (j = 0; j < i; ++j)\n\t\t{\n\t\t\tXi[j] *= d;\n\t\t}\n\t\tfor (j = i+1; j < n; ++j)\n\t\t{\n\t\t\tXi[j] *= d;\n\t\t}\n\t}\n\tfull->init();\n}\n\n}//namespace SLAM\n", "meta": {"hexsha": "1238246444b1e6a69dd23a19a4a5c6434680c633", "size": 5567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SLAM/kalmanSLAM.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": "SLAM/kalmanSLAM.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": "SLAM/kalmanSLAM.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": 28.5487179487, "max_line_length": 114, "alphanum_fraction": 0.6687623496, "num_tokens": 1829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.5045411400407593}}
{"text": "/**\n * @file init_rules_test.cpp\n * @author Marcus Edel\n *\n * Tests for the various weight initialize methods.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/init_rules/kathirvalavakumar_subavathi_init.hpp>\n#include <mlpack/methods/ann/init_rules/nguyen_widrow_init.hpp>\n#include <mlpack/methods/ann/init_rules/oivs_init.hpp>\n#include <mlpack/methods/ann/init_rules/orthogonal_init.hpp>\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n#include <mlpack/methods/ann/init_rules/zero_init.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(InitRulesTest);\n\n// Test the RandomInitialization class with a constant value.\nBOOST_AUTO_TEST_CASE(ConstantInitTest)\n{\n  arma::mat weights;\n  RandomInitialization constantInit(1, 1);\n  constantInit.Initialize(weights, 100, 100);\n\n  bool b = arma::all(arma::vectorise(weights) == 1);\n  BOOST_REQUIRE_EQUAL(b, 1);\n}\n\n// Test the OrthogonalInitialization class.\nBOOST_AUTO_TEST_CASE(OrthogonalInitTest)\n{\n  arma::mat weights;\n  OrthogonalInitialization orthogonalInit;\n  orthogonalInit.Initialize(weights, 100, 200);\n\n  arma::mat orthogonalWeights = arma::eye<arma::mat>(100, 100);\n  weights *= weights.t();\n\n  for (size_t i = 0; i < weights.n_rows; i++)\n    for (size_t j = 0; j < weights.n_cols; j++)\n      BOOST_REQUIRE_SMALL(weights.at(i, j) - orthogonalWeights.at(i, j), 1e-3);\n\n  orthogonalInit.Initialize(weights, 200, 100);\n  weights = weights.t() * weights;\n\n  for (size_t i = 0; i < weights.n_rows; i++)\n    for (size_t j = 0; j < weights.n_cols; j++)\n      BOOST_REQUIRE_SMALL(weights.at(i, j) - orthogonalWeights.at(i, j), 1e-3);\n}\n\n// Test the OrthogonalInitialization class with a non default gain.\nBOOST_AUTO_TEST_CASE(OrthogonalInitGainTest)\n{\n  arma::mat weights;\n\n  const double gain = 2;\n  OrthogonalInitialization orthogonalInit(gain);\n  orthogonalInit.Initialize(weights, 100, 200);\n\n  arma::mat orthogonalWeights = arma::eye<arma::mat>(100, 100);\n  orthogonalWeights *= (gain * gain);\n  weights *= weights.t();\n\n  for (size_t i = 0; i < weights.n_rows; i++)\n    for (size_t j = 0; j < weights.n_cols; j++)\n      BOOST_REQUIRE_SMALL(weights.at(i, j) - orthogonalWeights.at(i, j), 1e-3);\n}\n\n// Test the ZeroInitialization class. If you think about it, it's kind of\n// ridiculous to test the zero init rule. But at least we make sure it\n// builds without any problems.\nBOOST_AUTO_TEST_CASE(ZeroInitTest)\n{\n  arma::mat weights;\n  ZeroInitialization zeroInit;\n  zeroInit.Initialize(weights, 100, 100);\n\n  bool b = arma::all(arma::vectorise(weights) == 0);\n  BOOST_REQUIRE_EQUAL(b, 1);\n}\n\n// Test the KathirvalavakumarSubavathiInitialization class.\nBOOST_AUTO_TEST_CASE(KathirvalavakumarSubavathiInitTest)\n{\n  arma::mat data = arma::randu<arma::mat>(100, 1);\n\n  arma::mat weights;\n  KathirvalavakumarSubavathiInitialization kathirvalavakumarSubavathiInit(\n      data, 1.5);\n  kathirvalavakumarSubavathiInit.Initialize(weights, 100, 100);\n\n  BOOST_REQUIRE_EQUAL(1, 1);\n}\n\n// Test the NguyenWidrowInitialization class.\nBOOST_AUTO_TEST_CASE(NguyenWidrowInitTest)\n{\n  arma::mat weights;\n  NguyenWidrowInitialization nguyenWidrowInit;\n  nguyenWidrowInit.Initialize(weights, 100, 100);\n\n  BOOST_REQUIRE_EQUAL(1, 1);\n}\n\n// Test the OivsInitialization class.\nBOOST_AUTO_TEST_CASE(OivsInitTest)\n{\n  arma::mat weights;\n  OivsInitialization<> oivsInit;\n  oivsInit.Initialize(weights, 100, 100);\n\n  BOOST_REQUIRE_EQUAL(1, 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "5ef4b9929b925a3b2862f6aa460a9d490547d25e", "size": 3513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/init_rules_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/init_rules_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/init_rules_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.7950819672, "max_line_length": 79, "alphanum_fraction": 0.7429547395, "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5045411381487136}}
{"text": "/**\n * Fast map matching.\n *\n * Definition of geometry\n *\n * @author: Can Yang\n * @version: 2017.11.11\n */\n\n#ifndef FMM_GEOMTYPES_HPP\n#define FMM_GEOMTYPES_HPP\n\n#include <ogrsf_frmts.h> // C++ API for GDAL\n#include <boost/geometry.hpp>\n#include <string>\n#include <sstream>\n\nnamespace FMM {\n/**\n * Core data types\n */\nnamespace CORE{\n\n/**\n *  Point class\n */\ntypedef boost::geometry::model::point<double, 2,\n    boost::geometry::cs::cartesian> Point; // Point for rtree box\n/**\n *  Linestring geometry class\n *\n *  This class wraps a boost linestring geometry.\n */\nclass LineString {\npublic:\n  /**\n   * This is the boost geometry linestring class, stored inside the\n   * LineString class.\n   */\n  typedef boost::geometry::model::linestring<Point> linestring_t;\n  /**\n   * Get the x coordinate of i-th point in the line\n   * @param i point index\n   * @return x coordinate\n   */\n  inline double get_x(int i) const{\n    return boost::geometry::get<0>(line.at(i));\n  };\n  /**\n   * Get the y coordinate of i-th point in the line\n   * @param i point index starting from 0 to N-1, where N is the\n   * number of points in the line\n   * @return y coordinate\n   */\n  inline double get_y(int i) const{\n    return boost::geometry::get<1>(line.at(i));\n  };\n  /**\n   * Set x coordinate of i-th point in the line\n   * @param i point index\n   * @param v the value to update the old coordinate\n   */\n  inline void set_x(int i, double v){\n    boost::geometry::set<0>(line.at(i),v);\n  };\n  /**\n   * Set y coordinate of i-th point in the line\n   * @param i point index\n   * @param v the value to update the old coordinate\n   */\n  inline void set_y(int i, double v){\n    boost::geometry::set<1>(line.at(i),v);\n  };\n  /**\n   * Add a point to the end of the current line\n   * @param x x coordinate of the point to add\n   * @param y y coordinate of the point to add\n   */\n  inline void add_point(double x,double y){\n    boost::geometry::append(line, Point(x,y));\n  };\n  /**\n   * Add a point to the end of the current line\n   * @param point the point to be added\n   */\n  inline void add_point(const Point& point){\n    boost::geometry::append(line, point);\n  };\n  /**\n   * Get the i-th point in the line\n   * @param  i point index starting from 0 to N-1\n   * @return The i-th point of the line.\n   *\n   * Note that the point is a copy of the original point.\n   * Manipulating the returned point will not change the\n   * original line.\n   */\n  inline Point get_point(int i) const{\n    return Point(boost::geometry::get<0>(\n      line.at(i)),boost::geometry::get<1>(line.at(i)));\n  };\n  /**\n   * Get a constance reference of the i-th point in the line\n   * @param  i point index\n   * @return  A constant reference to the ith point of line, which\n   * avoids create a new point.\n   */\n  inline const Point &at(int i) const{\n    return line.at(i);\n  }\n  /**\n   * Get the number of points in a line\n   * @return the point number\n   */\n  inline int get_num_points() const{\n    return boost::geometry::num_points(line);\n  };\n  /**\n   * Check if the line is empty or not\n   * @return true if the line is empty, otherwise false\n   */\n  inline bool is_empty(){\n    return boost::geometry::num_points(line)==0;\n  };\n  /**\n   * Remove all points in the current line.\n   */\n  inline void clear(){\n    boost::geometry::clear(line);\n  };\n  /**\n   * Get the length of the line\n   * @return the length value\n   */\n  inline double get_length() const {\n    return boost::geometry::length(line);\n  };\n  /**\n   * Export a string containing WKT representation of the line.\n   * @return The WKT of the line\n   *\n   * Example: LINESTRING (30 10, 10 30, 40 40)\n   */\n  inline std::string export_wkt() const{\n    std::ostringstream ss;\n    ss << boost::geometry::wkt(line);\n    return ss.str();\n  };\n  /**\n   * Export a string containing GeoJSON representation of the line.\n   * @return The GeoJSON of the line\n   */\n  inline std::string export_json() const{\n    std::ostringstream ss;\n    int N = get_num_points();\n    if (N>0){\n      ss << \"{\\\"type\\\":\\\"LineString\\\",\\\"coordinates\\\": [\";\n      for (int i=0;i<N;++i){\n        ss << \"[\" << get_x(i) << \",\" << get_y(i) <<\"]\"\n           << (i==N-1 ? \"\": \",\");\n      }\n      ss << \"]}\";\n    }\n    return ss.str();\n  };\n  /**\n   * Get a const reference to the inner boost geometry linestring\n   * @return const reference to the inner boost geometry linestring\n   */\n  inline const linestring_t &get_geometry_const() const{\n    return line;\n  };\n  /**\n   * Get a reference to the inner boost geometry linestring\n   * @return a reference to the inner boost geometry linestring\n   */\n  linestring_t &get_geometry(){\n    return line;\n  };\n\n  /**\n   * Compare if two linestring are the same.\n   *\n   * It the two lines overlap with each other within a threshold of 1e-6,\n   * they are considered equal. This is used in the test class.\n   *\n   * @param rhs the linestring\n   * @return true if the two lines are equal.\n   */\n  inline bool operator==(const LineString& rhs) const {\n    int N = get_num_points();\n    if (rhs.get_num_points()!=N)\n      return false;\n    bool result = true;\n    for (int i=0;i<N;++i){\n      if (boost::geometry::distance(get_point(i),rhs.get_point(i))>1e-6)\n        result = false;\n    }\n    return result;\n  };\n  /**\n   * Overwrite the operator of << of linestring\n   * @param os an input stream\n   * @param rhs a linestring object\n   * @return the wkt representation of the line will be written to the stream.\n   */\n  friend std::ostream& operator<<(std::ostream& os, const LineString& rhs);\nprivate:\n  linestring_t line;\n}; // LineString\n\nstd::ostream& operator<<(std::ostream& os,const FMM::CORE::LineString& rhs);\n\n/**\n * Convert a OGRLineString to a linestring\n * @param line a pointer to OGRLineString\n * @return a linestring\n */\nLineString ogr2linestring(const OGRLineString *line);\n\n/**\n * Convert a OGRMultiLineString to a linestring.\n *\n * If the multilinestring contains multiple lines, only\n * the first linestring will be converted and returned as\n * a result.\n *\n * This function is used in reading data from shapefile.\n *\n * @param mline a pointer to the OGRMultiLineString\n * @return a linestring.\n *\n */\nLineString ogr2linestring(const OGRMultiLineString *mline);\n\n/**\n * Convert a wkt into a linestring\n * @param  wkt A wkt representation of a line\n * @return  a linestring\n */\nLineString wkt2linestring(const std::string &wkt);\n\n/**\n * Convert a linestring into a OGRLineString\n * @param  line input line\n * @return  A OGRLineString, the caller is responsible for\n * freeing the memory.\n */\nOGRLineString *linestring2ogr(const LineString &line);\n\n/**\n * Convert a point into a OGRPoint\n * @param  p input point\n * @return  A OGRPoint, the caller is responsible for\n * freeing the memory.\n */\nOGRPoint *point2ogr(const Point &p);\n\n}; // CORE\n\n}; // FMM\n\n\n#endif // FMM_GEOMTYPES_HPP\n", "meta": {"hexsha": "a73f236ceaebfc6e24a77f044a16a2a62603e2bf", "size": 6817, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/geometry.hpp", "max_stars_repo_name": "dkondor/fmm", "max_stars_repo_head_hexsha": "4ba187a052efb7df1de40b874d4c976a3f2b21fa", "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/geometry.hpp", "max_issues_repo_name": "dkondor/fmm", "max_issues_repo_head_hexsha": "4ba187a052efb7df1de40b874d4c976a3f2b21fa", "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/geometry.hpp", "max_forks_repo_name": "dkondor/fmm", "max_forks_repo_head_hexsha": "4ba187a052efb7df1de40b874d4c976a3f2b21fa", "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.7245283019, "max_line_length": 78, "alphanum_fraction": 0.6448584421, "num_tokens": 1851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5045411349045549}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef Matrix<float, 1, Dynamic> MatrixType;\ntypedef Map<MatrixType> MapType;\ntypedef Map<const MatrixType> MapTypeConst; // a read-only map\nconst int n_dims = 5;\n\nvoid main() {\n\t{\n\t\tint arr[8];\n\t\tfor (int i = 0; i < 8; i++) {\n\t\t\tarr[i] = i;\n\t\t}\n\n\t\tcout << \"Column-major: \\n\" << Map<Matrix<int, 2, 4>>(arr) << endl;\n\t\tcout << \"Row-major: \\n\" << Map<Matrix<int, 2, 4, RowMajor>>(arr) << endl;\n\t\tcout << \"Row-major using stride: \\n\" << Map<Matrix<int, 2, 4>, Unaligned, Stride<1, 4>>(arr) << endl;\n\t}\n\n\t{\n\t\tMatrixType m1(n_dims), m2(n_dims);\n\t\tm1.setRandom();\n\t\tm2.setRandom();\n\n\t\tfloat * p = &m2(0); // get the addres storing the data for m2\n\t\tMapType m2map(p, m2.size()); //m2map shares data with m2\n\t\tMapTypeConst m2mapconst(p, m2.size()); // a read-only accessor for m2\n\n\t\tcout << \"m1: \\n\" << m1 << endl;\n\t\tcout << \"m2: \\n\" << m2 << endl;\n\t\tcout << \"Squared euclidean distance: \\n\" << (m1 - m2).squaredNorm() << endl;\n\t\tcout << \"Squared euclidean distance, using map: \\n\" << (m1 - m2map).squaredNorm() << endl;\n\t\tm2map(3) = 7; // this will change m2, since they share the same array\n\t\tcout << \"Updated m2: \\n\" << m2 << endl;\n\t\tcout << \"m2 coefficient 2, constant accessor: \\n\" << m2mapconst(2) << endl;\n\n\t}\n\n\t{\n\t\t// changing the mapped array\n\t\tint data[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n\t\tMap<RowVectorXi> v(data, 4);\n\t\tcout << \"The mapped vector v is : \" << v << endl;\n\t\tnew(&v) Map<RowVectorXi>(data + 4, 5);\n\t\tcout << \"Now v is : \" << v << endl;\n\t}\n\n\t{\n\t\t// declare a Map obj without first knowing the mapped array's location in memory\n\t\t//int n_matrices = 4;\n\t\t//Map<Matrix3f> A(NULL);\n\t\t//VectorXf b(n_matrices);\n\t\t//for (int i = 0; i < n_dims; i++) {\n\t\t//\tnew (&A) Map<Matrix3f>(get_matrix_pointer(i));\n\t\t//\tb(i) = A.trace();\n\t\t//}\n\t}\n\n\tsystem(\"pause\");\n}", "meta": {"hexsha": "b747f861a6312c3333626626876c981eebfda997", "size": 1854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/eigen/eigen/map_class/map_class.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/map_class/map_class.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/map_class/map_class.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": 28.96875, "max_line_length": 103, "alphanum_fraction": 0.5954692557, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.5045411313904298}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_SF_CBRT_HPP\n#define BOOST_MATH_SF_CBRT_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/tools/roots.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n\nnamespace boost{ namespace math{\n\nnamespace detail\n{\n\n   template <class T>\n   struct cbrt_functor\n   {\n       cbrt_functor(T const& target) : a(target){}\n       std::tr1::tuple<T, T, T> operator()(T const& z)\n       {\n         T sqr = z * z;\n         return std::tr1::make_tuple(sqr * z - a, 3 * sqr, 6 * z);\n       }\n   private:\n       T a;\n   };\n\ntemplate <class T, class Policy>\nT cbrt_imp(T z, const Policy&)\n{\n   BOOST_MATH_STD_USING\n   int i_exp, sign(1);\n   if(z < 0)\n   {\n      z = -z;\n      sign = -sign;\n   }\n   if(z == 0)\n      return 0;\n\n   frexp(z, &i_exp);\n   T min = static_cast<T>(ldexp(0.5, i_exp/3));\n   T max = static_cast<T>(ldexp(2.0, i_exp/3));\n   T guess = static_cast<T>(ldexp(1.0, i_exp/3));\n   int digits = (policies::digits<T, Policy>()) / 2;\n   return sign * tools::halley_iterate(detail::cbrt_functor<T>(z), guess, min, max, digits);\n}\n\n} // namespace detail\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type cbrt(T z, const Policy& pol)\n{\n   typedef typename tools::promote_args<T>::type result_type;\n   return detail::cbrt_imp(result_type(z), pol);\n}\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type cbrt(T z)\n{\n   return cbrt(z, policies::policy<>());\n}\n\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_SF_CBRT_HPP\n\n\n\n\n", "meta": {"hexsha": "c43f9b625e4b7620aea76e3510847b673302239f", "size": 1733, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/special_functions/cbrt.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": "lshkit/trunk/3rd-party/boost/boost/math/special_functions/cbrt.hpp", "max_issues_repo_name": "mrfarhadi/BinClone", "max_issues_repo_head_hexsha": "035c20ab27ec00935c12ce54fe9c52bba4aaeff2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-11-22T13:14:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T00:56:51.000Z", "max_forks_repo_path": "lshkit/trunk/3rd-party/boost/boost/math/special_functions/cbrt.hpp", "max_forks_repo_name": "mrfarhadi/BinClone", "max_forks_repo_head_hexsha": "035c20ab27ec00935c12ce54fe9c52bba4aaeff2", "max_forks_repo_licenses": ["Apache-2.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": 22.2179487179, "max_line_length": 92, "alphanum_fraction": 0.6485862666, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5045411278763046}}
{"text": "// Copyright Louis Dionne 2016\n// Distributed under the Boost Software License, Version 1.0.\n\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/transform.hpp>\n#include <boost/mpl/vector_c.hpp>\nnamespace mpl = boost::mpl;\n\n\n// sample(dimensions)\n// base dimensions                     M  L  T  I  \u0398  J  N\nusing mass        = mpl::vector_c<int, 1, 0, 0, 0, 0, 0, 0>;\nusing length      = mpl::vector_c<int, 0, 1, 0, 0, 0, 0, 0>;\nusing time        = mpl::vector_c<int, 0, 0, 1, 0, 0, 0, 0>;\nusing charge      = mpl::vector_c<int, 0, 0, 0, 1, 0, 0, 0>;\nusing temperature = mpl::vector_c<int, 0, 0, 0, 0, 1, 0, 0>;\nusing intensity   = mpl::vector_c<int, 0, 0, 0, 0, 0, 1, 0>;\nusing amount      = mpl::vector_c<int, 0, 0, 0, 0, 0, 0, 1>;\n\n// composite dimensions\nusing velocity     = mpl::vector_c<int, 0, 1, -1, 0, 0, 0, 0>; // L/T\nusing acceleration = mpl::vector_c<int, 0, 1, -2, 0, 0, 0, 0>; // L/T\u00b2\nusing force        = mpl::vector_c<int, 1, 1, -2, 0, 0, 0, 0>; // ML/T\u00b2\n// end-sample\n\n// sample(dimensions-compare)\ntemplate <typename A, typename B>\nconstexpr bool compatible = mpl::equal<A, B>::value;\n// end-sample\n\n// sample(quantity)\ntemplate <typename Dimensions>\nstruct quantity {\n  double value_;\n\n  explicit quantity(double v) : value_(v) { }\n\n  template <typename OtherDimensions>\n  explicit quantity(quantity<OtherDimensions> other)\n    : value_(other.value_)\n  {\n    static_assert(compatible<Dimensions, OtherDimensions>,\n      \"Constructing quantities with incompatible dimensions!\");\n  }\n\n  explicit operator double() const { return value_; }\n};\n// end-sample\n\n// sample(dimensions-compose)\ntemplate <typename D1, typename D2>\nauto operator*(quantity<D1> a, quantity<D2> b) {\n  using D = typename mpl::transform<D1, D2, mpl::plus<>>::type;\n  return quantity<D>{static_cast<double>(a) * static_cast<double>(b)};\n}\n\ntemplate <typename D1, typename D2>\nauto operator/(quantity<D1> a, quantity<D2> b) {\n  using D = typename mpl::transform<D1, D2, mpl::minus<>>::type;\n  return quantity<D>{static_cast<double>(a) / static_cast<double>(b)};\n}\n\ntemplate <typename D1, typename D2>\nauto operator+(quantity<D1> a, quantity<D2> b) {\n  static_assert(compatible<D1, D2>,\n    \"Adding quantities with incompatible dimensions!\");\n  return quantity<D1>{static_cast<double>(a) + static_cast<double>(b)};\n}\n\n// etc..\n// end-sample\n\n#if 0\n// sample(usage)\nquantity<mass>         m{10.3};\nquantity<length>       d{3.6};\nquantity<time>         t{2.4};\nquantity<velocity>     v{d / t};\nquantity<acceleration> a{...};\nquantity<force>        f{m * v}; // Compiler error!\nquantity<force>        f{m * a}; // Works as expected\n// end-sample\n#endif\n\nint main() {\n  quantity<mass>         m{10.3};\n  quantity<length>       d{3.6};\n  quantity<time>         t{2.4};\n  quantity<velocity>     v{d / t};\n  quantity<acceleration> a{3.9};\n  quantity<force>        f{m * a};\n\n  quantity<force> f2 = f + f;\n}\n", "meta": {"hexsha": "4b0432e975396f89c657c237cf9c63d7f8aa235c", "size": 2945, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/mpl.dim.cpp", "max_stars_repo_name": "ldionne/meetingcpp-2016", "max_stars_repo_head_hexsha": "8cd555d2d57fef055c9190e46c826f1adf21dd47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2016-11-20T18:01:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-11T16:20:53.000Z", "max_issues_repo_path": "code/mpl.dim.cpp", "max_issues_repo_name": "ldionne/meetingcpp-2016", "max_issues_repo_head_hexsha": "8cd555d2d57fef055c9190e46c826f1adf21dd47", "max_issues_repo_licenses": ["MIT"], "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/mpl.dim.cpp", "max_forks_repo_name": "ldionne/meetingcpp-2016", "max_forks_repo_head_hexsha": "8cd555d2d57fef055c9190e46c826f1adf21dd47", "max_forks_repo_licenses": ["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.3608247423, "max_line_length": 71, "alphanum_fraction": 0.6380305603, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5045286569018308}}
{"text": "#include \"advent.hpp\"\n\n#include <Eigen/Core>\n#include <concepts>\n#include <fstream>\n#include <iostream>\n#include <queue>\n#include <string>\n#include <vector>\n\nusing Eigen::Array;\n\nusing std::ifstream;\nusing std::priority_queue;\nusing std::string;\nusing std::vector;\n\ntemplate<typename T, typename U, typename Cmp = std::less<U>>\nrequires std::equality_comparable<U>\nstruct priority_item {\n    T data;\n    U priority;\n\n    friend auto operator<(priority_item const& lhs, priority_item const& rhs) -> bool {\n        return Cmp{}(lhs.priority, rhs.priority); \n    }\n\n    friend auto operator==(priority_item const& lhs, priority_item const& rhs) -> bool {\n        return lhs.priority == rhs.priority;\n    }\n};\n\nstruct point {\n    i64 x;\n    i64 y;\n    auto operator<=>(const point&) const -> bool = default;\n};\n\nauto day15(int argc, char** argv) -> int\n{\n    // read input\n    if (argc < 2) {\n        fmt::print(\"Error: no input.\");\n        return 1;\n    }\n\n    ifstream infile(argv[1]); // NOLINT\n    string line;\n    std::getline(infile, line);\n\n    const i64 ncol = line.size();\n    const i64 nrow = std::count(std::istreambuf_iterator<char>(infile), std::istreambuf_iterator<char>(), '\\n') + 1;\n    infile.seekg(0); // rewind the input stream\n    Array<i64, -1, -1> map(nrow, ncol);\n\n    i64 row{0};\n    while(std::getline(infile, line)) {\n        std::string str(line);\n        std::transform(str.begin(), str.end(), map.row(row).begin(), [](auto c) { return static_cast<i64>(c - '0'); });\n        ++row;\n    }\n\n    // define a simple A* search\n    using item = priority_item<point, i64, std::greater<>>;\n    decltype(map) costs = map;\n\n    auto astar = [&](auto start, auto end, auto&& cost) {\n        priority_queue<item> q; \n        q.push({start, cost(start)});\n\n        costs.fill(-1);\n        costs(start.x, start.y) = cost(start);\n\n        while (!q.empty()) {\n            auto [p, c] = q.top(); q.pop();\n            if (p == end) {\n                break;\n            }\n            auto [x, y] = p;\n            for (auto i = std::max(0L, x-1); i <= std::min(end.x, x+1); ++i) {\n                for (auto j = std::max(0L, y-1); j <= std::min(end.y, y+1); ++j) {\n                    if ((i == x && j == y) || (i != x && j != y)) {\n                        continue;\n                    }\n                    point next{i, j};\n                    auto new_cost = c + cost(next);\n                    if (costs(i, j) == -1 || new_cost < costs(i, j)) {\n                        costs(i, j) = new_cost;\n                        q.push({next, new_cost});\n                    }\n                }\n            }\n        }\n    };\n\n    // part 1\n    auto cost_p1 = [&](point const& p) { return map(p.x, p.y); };\n    const point s1{0, 0};\n    const point s2{map.rows()-1, map.cols()-1};\n    astar(s1, s2, cost_p1);\n    fmt::print(\"part 1: {}\\n\", costs(s2.x, s2.y) - costs(s1.x, s1.y));\n\n    // part 2\n    constexpr i64 times_larger{5};\n    constexpr i64 wrap{9};\n\n    auto cost_p2 = [&](point const& p) {\n        auto d = p.x / map.rows() + p.y / map.cols();\n        auto x = p.x % map.rows();\n        auto y = p.y % map.cols();\n        auto c = map(x, y) + d;\n        return c > wrap ? c - wrap : c;\n    };\n    costs.resize(map.rows() * times_larger, map.cols() * times_larger);\n    const point s3{costs.rows()-1, costs.cols()-1};\n    astar(s1, s3, cost_p2);\n    fmt::print(\"part 2: {}\\n\", costs(s3.x, s3.y) - costs(s1.x, s1.y));\n\n    return 0;\n}\n", "meta": {"hexsha": "c3e3d32a1e9a78f1ce2c3aa292bc7d263a6e1e6f", "size": 3439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/day15.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/day15.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/day15.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.4214876033, "max_line_length": 119, "alphanum_fraction": 0.5135213725, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577157, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5045286538288045}}
{"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_MANTISSA_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MANTISSA_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-ieee\n    This function object returns the signed mantissa of the input argument.\n\n\n    @par Header <boost/simd/function/mantissa.hpp>\n\n    @par Note\n    The @ref exponent @c e and signed @ref mantissa @c m of a floating\n    point entry @c x are related by\n    \\f$x = m\\times 2^e\\f$, with |m| \\f$\\in[1, 2[\\f$. (Except for zero,\n    for which \\f$m = 0\\f$).\n\n    @see frexp, pow, exponent\n\n\n    @par Example:\n\n      @snippet mantissa.cpp mantissa\n\n    @par Possible output:\n\n      @snippet mantissa.txt mantissa\n\n  **/\n  Value mantissa(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/mantissa.hpp>\n#include <boost/simd/function/simd/mantissa.hpp>\n\n#endif\n", "meta": {"hexsha": "17b01b626efeadb244e5effde6271cf305a9947f", "size": 1252, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/mantissa.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/function/mantissa.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/function/mantissa.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": 24.5490196078, "max_line_length": 100, "alphanum_fraction": 0.5846645367, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5045286516595585}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_IEEE_FUNCTIONS_SIMD_COMMON_MAXMAG_HPP_INCLUDED\n#define BOOST_SIMD_IEEE_FUNCTIONS_SIMD_COMMON_MAXMAG_HPP_INCLUDED\n#include <boost/simd/ieee/functions/maxmag.hpp>\n#include <boost/simd/include/functions/simd/max.hpp>\n#include <boost/simd/include/functions/simd/if_else.hpp>\n#include <boost/simd/include/functions/simd/is_nan.hpp>\n#include <boost/simd/include/functions/simd/abs.hpp>\n#include <boost/simd/include/functions/simd/is_greater.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::maxmag_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<arithmetic_<A0>,X>))((simd_<arithmetic_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return select(gt(boost::simd::abs(a0), boost::simd::abs(a1)), a0, a1);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "85dae6b4e55c6273796e95ec4de3025f1f1f5a85", "size": 1422, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/ieee/include/boost/simd/ieee/functions/simd/common/maxmag.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/ieee/include/boost/simd/ieee/functions/simd/common/maxmag.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/ieee/include/boost/simd/ieee/functions/simd/common/maxmag.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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.8235294118, "max_line_length": 86, "alphanum_fraction": 0.5879043601, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5045286448807738}}
{"text": "#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 <Eigen/Dense>\n#include <vtkPolyDataReader.h>\n#include <vtkPolyDataWriter.h>\n#include <vtkPolyData.h>\n#include <vtkDoubleArray.h>\n#include <vtkSmartPointer.h>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point;\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 Eigen::Vector3d Vector3d;\ntypedef Eigen::VectorXd VectorXd;\ntypedef Eigen::Matrix3d Matrix3d;\ntypedef Eigen::Matrix3Xd Matrix3Xd;\ntypedef Eigen::Map<Matrix3Xd> Map3Xd;\n\nint main(){\n    clock_t t1;\n    t1 = clock();\n    for(auto i=0; i < 10000; ++i){\n        auto reader = vtkSmartPointer<vtkPolyDataReader>::New();\n        reader->SetFileName(\"Bad.vtk\");\n        reader->Update();\n        auto poly = reader->GetOutput();\n        auto N = poly->GetNumberOfPoints();\n        auto pts = (double*) poly->GetPoints()->GetData()->GetVoidPointer(0);\n        Map3Xd points(pts,3,N);\n\n        // Project points to unit sphere\n        points.colwise().normalize();\n\n        // Reset the center of the sphere to origin by translating\n        Vector3d center = points.rowwise().mean();\n        points = points.colwise() - center;\n\n        // Rotate all points so that the point in 0th column is along z-axis\n        Vector3d c = points.col(0);\n        double_t cos_t = c(2);\n        double_t sin_t = std::sqrt( 1 - cos_t*cos_t );\n        Vector3d axis;\n        axis << c(1), -c(0), 0.;\n        Matrix3d rotMat, axis_cross, outer;\n        axis_cross << 0. , -axis(2), axis(1),\n                        axis(2), 0., -axis(0),\n                        -axis(1), axis(0), 0.;\n\n        outer.noalias() = axis*axis.transpose();\n\n        rotMat = cos_t*Matrix3d::Identity() + sin_t*axis_cross + (1-cos_t)*outer;\n        Matrix3Xd rPts(3,N);\n        rPts = rotMat*points; // The points on a sphere rotated\n\n        // Calculate the stereographic projections\n        Vector3d p0;\n        Map3Xd l0( &(rPts(0,1)), 3, N-1 );\n        Matrix3Xd l(3,N-1), proj(3,N-1);\n        p0 << 0,0,-1;\n        c = rPts.col(0);\n        l = (l0.colwise() - c).colwise().normalized();\n        for( auto j=0; j < N-1; ++j ){\n            proj.col(j) = ((p0(2) - l0(2,j))/l(2,j))*l.col(j) + l0.col(j);\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        Delaunay dt( verts.begin(), verts.end() );\n\n        // Write the finite faces of the triangulation to a VTK file\n        vtkNew<vtkCellArray> triangles;\n        for( auto ffi = dt.finite_faces_begin(); ffi != dt.finite_faces_end(); ++ffi){\n            triangles->InsertNextCell(3);\n            for(auto j=2; j >= 0; --j)\n                triangles->InsertCellPoint(ffi->vertex(j)->info());\n        }\n\n        // Iterate over infinite faces\n        Face_circulator fc = dt.incident_faces(dt.infinite_vertex()), done(fc);\n        if (fc != 0) {\n            do{\n                triangles->InsertNextCell(3);\n                for(auto j=2; j >= 0; --j){\n                    auto vh = fc->vertex(j);\n                    auto id = dt.is_infinite(vh)? 0 : vh->info();\n                    triangles->InsertCellPoint(id);\n                }\n            }while(++fc != done);\n        }\n        poly->SetPolys(triangles);\n\n        // Write to VTK file\n        vtkNew<vtkPolyDataWriter> writer;\n        writer->SetFileName(\"StereoMesh.vtk\");\n        writer->SetInputData(poly);\n        writer->Write();\n    }\n    float diff((float)clock() - (float)t1);\n    std::cout << \"Time elapsed : \" << diff / CLOCKS_PER_SEC\n              << \" seconds\" << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "88596c64cb91029b8731a793a662061fd7dd815f", "size": 4047, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "CPP/cgalStereo.cxx", "max_stars_repo_name": "amit112amit/learning-cgal", "max_stars_repo_head_hexsha": "a00b2a559cc9bd38fd041873353423f13406cb01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-01T06:55:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-18T15:54:13.000Z", "max_issues_repo_path": "CPP/cgalStereo.cxx", "max_issues_repo_name": "amit112amit/learning-cgal", "max_issues_repo_head_hexsha": "a00b2a559cc9bd38fd041873353423f13406cb01", "max_issues_repo_licenses": ["MIT"], "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/cgalStereo.cxx", "max_forks_repo_name": "amit112amit/learning-cgal", "max_forks_repo_head_hexsha": "a00b2a559cc9bd38fd041873353423f13406cb01", "max_forks_repo_licenses": ["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.7909090909, "max_line_length": 86, "alphanum_fraction": 0.5871015567, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.5045165607086668}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, 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#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DISTANCE_PYTHAGORAS_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DISTANCE_PYTHAGORAS_HPP\n\n\n#include <boost/mpl/if.hpp>\n#include <boost/type_traits.hpp>\n\n#include <boost/geometry/core/access.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n\n#include <boost/geometry/util/calculation_type.hpp>\n\n\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <size_t I, typename T>\nstruct compute_pythagoras\n{\n    template <typename Point1, typename Point2>\n    static inline T apply(Point1 const& p1, Point2 const& p2)\n    {\n        T const c1 = boost::numeric_cast<T>(get<I-1>(p1));\n        T const c2 = boost::numeric_cast<T>(get<I-1>(p2));\n        T const d = c1 - c2;\n        return d * d + compute_pythagoras<I-1, T>::apply(p1, p2);\n    }\n};\n\ntemplate <typename T>\nstruct compute_pythagoras<0, T>\n{\n    template <typename Point1, typename Point2>\n    static inline T apply(Point1 const&, Point2 const&)\n    {\n        return boost::numeric_cast<T>(0);\n    }\n};\n\n}\n#endif // DOXYGEN_NO_DETAIL\n\n\nnamespace comparable\n{\n\n/*!\n\\brief Strategy to calculate comparable distance between two points\n\\ingroup strategies\n\\tparam Point1 \\tparam_first_point\n\\tparam Point2 \\tparam_second_point\n\\tparam CalculationType \\tparam_calculation\n*/\ntemplate <typename CalculationType = void>\nclass pythagoras\n{\npublic :\n\n    template <typename Point1, typename Point2>\n    struct calculation_type\n        : util::calculation_type::geometric::binary\n          <\n              Point1,\n              Point2,\n              CalculationType\n          >\n    {};\n\n    template <typename Point1, typename Point2>\n    static inline typename calculation_type<Point1, Point2>::type\n    apply(Point1 const& p1, Point2 const& p2)\n    {\n        BOOST_CONCEPT_ASSERT( (concept::ConstPoint<Point1>) );\n        BOOST_CONCEPT_ASSERT( (concept::ConstPoint<Point2>) );\n\n        // Calculate distance using Pythagoras\n        // (Leave comment above for Doxygen)\n\n        assert_dimension_equal<Point1, Point2>();\n\n        return detail::compute_pythagoras\n            <\n                dimension<Point1>::value,\n                typename calculation_type<Point1, Point2>::type\n            >::apply(p1, p2);\n    }\n};\n\n} // namespace comparable\n\n\n/*!\n\\brief Strategy to calculate the distance between two points\n\\ingroup strategies\n\\tparam CalculationType \\tparam_calculation\n\n\\qbk{\n[heading Notes]\n[note Can be used for points with two\\, three or more dimensions]\n[heading See also]\n[link geometry.reference.algorithms.distance.distance_3_with_strategy distance (with strategy)]\n}\n\n*/\ntemplate\n<\n    typename CalculationType = void\n>\nclass pythagoras\n{\npublic :\n\n    template <typename P1, typename P2>\n    struct calculation_type\n        : util::calculation_type::geometric::binary\n          <\n              P1,\n              P2,\n              CalculationType,\n              double,\n              double // promote integer to double\n          >\n    {};\n\n    /*!\n    \\brief applies the distance calculation using pythagoras\n    \\return the calculated distance (including taking the square root)\n    \\param p1 first point\n    \\param p2 second point\n    */\n    template <typename P1, typename P2>\n    static inline typename calculation_type<P1, P2>::type\n    apply(P1 const& p1, P2 const& p2)\n    {\n        // The cast is necessary for MSVC which considers sqrt __int64 as an ambiguous call\n        return std::sqrt\n            (\n                 boost::numeric_cast<typename calculation_type<P1, P2>::type>\n                    (\n                        comparable::pythagoras<CalculationType>::apply(p1, p2)\n                    )\n            );\n    }\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename CalculationType>\nstruct tag<pythagoras<CalculationType> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename CalculationType, typename P1, typename P2>\nstruct return_type<distance::pythagoras<CalculationType>, P1, P2>\n    : pythagoras<CalculationType>::template calculation_type<P1, P2>\n{};\n\n\ntemplate <typename CalculationType>\nstruct comparable_type<pythagoras<CalculationType> >\n{\n    typedef comparable::pythagoras<CalculationType> type;\n};\n\n\ntemplate <typename CalculationType>\nstruct get_comparable<pythagoras<CalculationType> >\n{\n    typedef comparable::pythagoras<CalculationType> comparable_type;\npublic :\n    static inline comparable_type apply(pythagoras<CalculationType> const& )\n    {\n        return comparable_type();\n    }\n};\n\n\ntemplate <typename CalculationType, typename Point1, typename Point2>\nstruct result_from_distance<pythagoras<CalculationType>, Point1, Point2>\n{\nprivate :\n    typedef typename return_type<pythagoras<CalculationType>, Point1, Point2>::type return_type;\npublic :\n    template <typename T>\n    static inline return_type apply(pythagoras<CalculationType> const& , T const& value)\n    {\n        return return_type(value);\n    }\n};\n\n\n// Specializations for comparable::pythagoras\ntemplate <typename CalculationType>\nstruct tag<comparable::pythagoras<CalculationType> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename CalculationType, typename P1, typename P2>\nstruct return_type<comparable::pythagoras<CalculationType>, P1, P2>\n    : comparable::pythagoras<CalculationType>::template calculation_type<P1, P2>\n{};\n\n\n\n\ntemplate <typename CalculationType>\nstruct comparable_type<comparable::pythagoras<CalculationType> >\n{\n    typedef comparable::pythagoras<CalculationType> type;\n};\n\n\ntemplate <typename CalculationType>\nstruct get_comparable<comparable::pythagoras<CalculationType> >\n{\n    typedef comparable::pythagoras<CalculationType> comparable_type;\npublic :\n    static inline comparable_type apply(comparable::pythagoras<CalculationType> const& )\n    {\n        return comparable_type();\n    }\n};\n\n\ntemplate <typename CalculationType, typename Point1, typename Point2>\nstruct result_from_distance<comparable::pythagoras<CalculationType>, Point1, Point2>\n{\nprivate :\n    typedef typename return_type<comparable::pythagoras<CalculationType>, Point1, Point2>::type return_type;\npublic :\n    template <typename T>\n    static inline return_type apply(comparable::pythagoras<CalculationType> const& , T const& value)\n    {\n        return_type const v = value;\n        return v * v;\n    }\n};\n\n\ntemplate <typename Point1, typename Point2>\nstruct default_strategy<point_tag, Point1, Point2, cartesian_tag, cartesian_tag, void>\n{\n    typedef pythagoras<> type;\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::distance\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DISTANCE_PYTHAGORAS_HPP\n", "meta": {"hexsha": "4fe651b16136abcb83784d15dd7ddd76e0e7648d", "size": 7377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "venv/bin/boost/geometry/strategies/cartesian/distance_pythagoras.hpp", "max_stars_repo_name": "NixaSoftware/CVis", "max_stars_repo_head_hexsha": "076a36e1542036d3a8907b7d3b798ccd7e815675", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-02-24T14:48:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T21:37:26.000Z", "max_issues_repo_path": "venv/bin/boost/geometry/strategies/cartesian/distance_pythagoras.hpp", "max_issues_repo_name": "NixaSoftware/CVis", "max_issues_repo_head_hexsha": "076a36e1542036d3a8907b7d3b798ccd7e815675", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-02-25T20:45:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-28T18:05:45.000Z", "max_forks_repo_path": "venv/bin/boost/geometry/strategies/cartesian/distance_pythagoras.hpp", "max_forks_repo_name": "NixaSoftware/CVis", "max_forks_repo_head_hexsha": "076a36e1542036d3a8907b7d3b798ccd7e815675", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2017-11-01T03:30:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-28T21:57:33.000Z", "avg_line_length": 25.6145833333, "max_line_length": 108, "alphanum_fraction": 0.7111291853, "num_tokens": 1747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5044901707967694}}
{"text": "#include <vector>\n#include <Eigen/Core>\n\ntypedef double scalar;\n\n// Dynamic Eigen typedefs\ntypedef Eigen::Matrix<scalar, -1, 1> VectorX;\ntypedef Eigen::Matrix<scalar, 1, -1> RowVectorX;\ntypedef Eigen::Matrix<scalar, -1, -1> MatrixX;\n\n// 3D Eigen typedefs\ntypedef Eigen::Matrix<scalar, 3, 1> Vector3;\ntypedef Eigen::Matrix<scalar, 1, 3> RowVector3;\ntypedef Eigen::Matrix<scalar, 3, 3> Matrix3;\n\n// Vectorfield and Scalarfield typedefs\n#ifdef USE_CUDA\n    #include \"managed_allocator.hpp\"\n    typedef std::vector<Vector3, managed_allocator<Vector3>> vectorfield;\n    typedef std::vector<scalar, managed_allocator<scalar>> scalarfield;\n#else\n    typedef std::vector<Vector3> vectorfield;\n    typedef std::vector<scalar> scalarfield;\n#endif", "meta": {"hexsha": "4f591621fc75fe7146ca22d10c8fe63eff1ba1c1", "size": 736, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/vectorfield.hpp", "max_stars_repo_name": "GPMueller/vectorfield", "max_stars_repo_head_hexsha": "5fc3eedab8c0a381692a5c136037953421c392f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-22T15:02:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-22T15:02:26.000Z", "max_issues_repo_path": "include/vectorfield.hpp", "max_issues_repo_name": "GPMueller/vectorfield", "max_issues_repo_head_hexsha": "5fc3eedab8c0a381692a5c136037953421c392f2", "max_issues_repo_licenses": ["MIT"], "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/vectorfield.hpp", "max_forks_repo_name": "GPMueller/vectorfield", "max_forks_repo_head_hexsha": "5fc3eedab8c0a381692a5c136037953421c392f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-03T01:45:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-29T12:47:04.000Z", "avg_line_length": 30.6666666667, "max_line_length": 73, "alphanum_fraction": 0.7472826087, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5044901651430287}}
{"text": "// This file is a part of the OpenSurgSim project.\n// Copyright 2013, SimQuest Solutions Inc.\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 <gtest/gtest.h>\n\n#include <boost/exception/to_string.hpp>\n\n#include <array>\n\n#include \"SurgSim/Framework/Timer.h\"\n#include \"SurgSim/DataStructures/Grid.h\"\n\nnamespace SurgSim\n{\nnamespace DataStructures\n{\n\n/// This class test the grid timings for a given concentration of elements per cell and a given number of element per\n/// dimension. These two information are embedded in GTest WithParamInterface which takes a\n/// tuple<double = concentrationPerCell, size_t = numElementsPerDimension>\nclass Grid3DPerformanceTests : public ::testing::Test,\n\t\t\t\t\t\t\t   public ::testing::WithParamInterface<std::tuple<double, size_t>>\n{\npublic:\n\ttypedef Eigen::Matrix<size_t, 3, 1> Vector3ui;\n\n\tvirtual void SetUp()\n\t{\n\t\tm_h = 0.1;\n\t\tm_bounds.min().setConstant(-pow(2, 10) / 2.0);\n\t\tm_bounds.max().setConstant(pow(2, 10) / 2.0);\n\t\tm_grid = std::make_shared<Grid<size_t, 3>>(Eigen::Matrix<double, 3, 1>::Constant(m_h), m_bounds);\n\t}\n\n\tvoid addElementsUniformDistribution(const Vector3ui& numElementsPerAxis, double concentrationPerAxis)\n\t{\n\t\tdouble coef = m_h / static_cast<double>(concentrationPerAxis);\n\t\tsize_t elementId = 0;\n\n\t\tfor (size_t x = 0; x < numElementsPerAxis[0]; x++)\n\t\t{\n\t\t\tfor (size_t y = 0; y < numElementsPerAxis[1]; y++)\n\t\t\t{\n\t\t\t\tfor (size_t z = 0; z < numElementsPerAxis[2]; z++)\n\t\t\t\t{\n\t\t\t\t\tSurgSim::Math::Vector3d point(x * coef, y * coef, z * coef);\n\t\t\t\t\tm_grid->addElement(elementId, point);\n\t\t\t\t\telementId++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdouble performTimingTest(double concentrationPerCell, size_t numElementPerDimension)\n\t{\n\t\tSurgSim::Framework::Timer timer;\n\t\tVector3ui numElementsPerAxis = Vector3ui::Constant(numElementPerDimension);\n\t\tdouble concentrationPerAxis = pow(concentrationPerCell, 1.0 / 3.0);\n\n\t\ttimer.start();\n\n\t\t// Clear the grid from all previously added elements and clear the neighbor's list\n\t\tm_grid->reset();\n\t\t// Add all elements in the grid, triggering a dirty flag for the neighbor's list\n\t\taddElementsUniformDistribution(numElementsPerAxis, concentrationPerAxis);\n\t\t// Request any neighbor's list to force all neighbor's lists recalculation\n\t\tm_grid->getNeighbors(0);\n\n\t\ttimer.endFrame();\n\n\t\treturn timer.getCumulativeTime();\n\t}\n\nprotected:\n\t/// Grid size (cells are cubic in this test)\n\tdouble m_h;\n\n\t/// Grid boundary\n\tEigen::AlignedBox<double, 3> m_bounds;\n\n\t/// Grid\n\tstd::shared_ptr<Grid<size_t, 3>> m_grid;\n};\n\nTEST_P(Grid3DPerformanceTests, Grid3DTest)\n{\n\tdouble concentrationPerCell;\n\tsize_t numElementsPerDimension;\n\tstd::tie(concentrationPerCell, numElementsPerDimension) = GetParam();\n\tsize_t numElements = numElementsPerDimension * numElementsPerDimension * numElementsPerDimension;\n\tRecordProperty(\"ElementsPerCell\", boost::to_string(concentrationPerCell));\n\tRecordProperty(\"NumberOfElements\", boost::to_string(numElements));\n\tRecordProperty(\"Duration\", boost::to_string(performTimingTest(concentrationPerCell, numElementsPerDimension)));\n}\n\nINSTANTIATE_TEST_CASE_P(\n\tGrid3D,\n\tGrid3DPerformanceTests,\n\t::testing::Combine(\n\t\t// Concentration per cell is fine between 1 and 3^3, then coarser\n\t\t::testing::Values(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0,\n\t\t\t\t\t\t  18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0,\n\t\t\t\t\t\t  4 * 4 * 4, 5 * 5 * 5, 6 * 6 * 6, 7 * 7 * 7, 8 * 8 * 8, 9 * 9 * 9, 10 * 10 * 10),\n\t\t// Number of elements per dimension\n\t\t::testing::Values(50, 60, 60, 70, 80, 90, 100, 110, 120)));\n\n} // namespace DataStructures\n} // namespace SurgSim\n", "meta": {"hexsha": "9132a412289c7a71a191830f58a943a1f25ffeee", "size": 4115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SurgSim/DataStructures/PerformanceTests/GridPerformanceTest.cpp", "max_stars_repo_name": "dbungert/opensurgsim", "max_stars_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T16:18:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T03:29:11.000Z", "max_issues_repo_path": "SurgSim/DataStructures/PerformanceTests/GridPerformanceTest.cpp", "max_issues_repo_name": "dbungert/opensurgsim", "max_issues_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-12-21T14:54:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T12:38:07.000Z", "max_forks_repo_path": "SurgSim/DataStructures/PerformanceTests/GridPerformanceTest.cpp", "max_forks_repo_name": "dbungert/opensurgsim", "max_forks_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-04-10T19:45:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T17:00:59.000Z", "avg_line_length": 34.0082644628, "max_line_length": 117, "alphanum_fraction": 0.7183475091, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5044901594441378}}
{"text": "#pragma once\n\n#ifdef POLYSOLVE_WITH_AMGCL\n\n////////////////////////////////////////////////////////////////////////////////\n#include <polysolve/LinearSolver.hpp>\n\n#include <Eigen/Core>\n#include <amgcl/backend/builtin.hpp>\n#include <amgcl/make_solver.hpp>\n#include <amgcl/amg.hpp>\n#include <amgcl/coarsening/smoothed_aggregation.hpp>\n#include <amgcl/coarsening/plain_aggregates.hpp>\n#include <amgcl/coarsening/aggregation.hpp>\n#include <amgcl/coarsening/ruge_stuben.hpp>\n#include <amgcl/relaxation/spai0.hpp>\n#include <amgcl/relaxation/gauss_seidel.hpp>\n#include <amgcl/solver/cg.hpp>\n#include <amgcl/solver/bicgstab.hpp>\n#include <amgcl/solver/gmres.hpp>\n#include <amgcl/solver/runtime.hpp>\n#include <amgcl/profiler.hpp>\n#include <amgcl/io/mm.hpp>\n#include <amgcl/relaxation/chebyshev.hpp>\n#include <amgcl/coarsening/runtime.hpp>\n#include <amgcl/relaxation/runtime.hpp>\n#include <amgcl/preconditioner/runtime.hpp>\n#include <amgcl/value_type/static_matrix.hpp>\n// #include <amgcl/backend/vexcl.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <amgcl/adapter/reorder.hpp>\n#include <amgcl/adapter/eigen.hpp>\n#include <amgcl/profiler.hpp>\n#include <memory>\n#include <type_traits>\n\n////////////////////////////////////////////////////////////////////////////////\n//\n// WARNING:\n// The matrix is assumed to be in row-major format, since AMGCL assumes that the\n// outer index is for row. If the matrix is symmetric, you are fine, because CSR\n// and CSC are the same. If the matrix is not symmetric and you pass in a\n// column-major matrix, the solver will actually solve A^T x = b.\n//\n\nnamespace polysolve\n{\n    class LinearSolverAMGCL : public LinearSolver\n    {\n\n    public:\n        LinearSolverAMGCL();\n        ~LinearSolverAMGCL();\n\n    private:\n        POLYSOLVE_DELETE_MOVE_COPY(LinearSolverAMGCL)\n\n    public:\n        //////////////////////\n        // Public interface //\n        //////////////////////\n\n        // Set solver parameters\n        virtual void setParameters(const json &params) override;\n\n        // Retrieve information\n        virtual void getInfo(json &params) const override;\n\n        // Analyze sparsity pattern\n        virtual void analyzePattern(const StiffnessMatrix &A, const int precond_num) override { precond_num_ = precond_num; }\n\n        // Factorize system matrix\n        virtual void factorize(const StiffnessMatrix &A) override;\n\n        // Solve the linear system Ax = b\n        virtual void solve(const Ref<const VectorXd> b, Ref<VectorXd> x) override;\n\n        // Name of the solver type (for debugging purposes)\n        virtual std::string name() const override { return \"AMGCL\"; }\n\n    private:\n        using Backend = amgcl::backend::builtin<double>;\n        using Solver = amgcl::make_solver<\n            amgcl::runtime::preconditioner<Backend>,\n            amgcl::runtime::solver::wrapper<Backend>>;\n        std::unique_ptr<Solver> solver_;\n        json params_;\n        typename Backend::params backend_params_;\n        int precond_num_;\n\n        // Output info\n        size_t iterations_;\n        double residual_error_;\n    };\n} // namespace polysolve\n\n#endif\n", "meta": {"hexsha": "98e733c65057768d83f6fd79a4d0ba6992f1445e", "size": 3106, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/LinearSolverAMGCL.hpp", "max_stars_repo_name": "Pranav-Jain/polysolve", "max_stars_repo_head_hexsha": "aef3adf259c695bfce4c8dcc45d2ed4caa2f3fa2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T12:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:32:10.000Z", "max_issues_repo_path": "src/LinearSolverAMGCL.hpp", "max_issues_repo_name": "Pranav-Jain/polysolve", "max_issues_repo_head_hexsha": "aef3adf259c695bfce4c8dcc45d2ed4caa2f3fa2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-05-30T19:29:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T19:13:13.000Z", "max_forks_repo_path": "src/LinearSolverAMGCL.hpp", "max_forks_repo_name": "Pranav-Jain/polysolve", "max_forks_repo_head_hexsha": "aef3adf259c695bfce4c8dcc45d2ed4caa2f3fa2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-07-07T14:13:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T19:03:01.000Z", "avg_line_length": 31.693877551, "max_line_length": 125, "alphanum_fraction": 0.6567933033, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5044901537452467}}
{"text": "/*\n [auto_generated]\n libs/numeric/odeint/test/implicit_euler.cpp\n\n [begin_description]\n This file tests the implicit Euler stepper.\n [end_description]\n\n Copyright 2010-2011 Mario Mulansky\n Copyright 2010-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// disable checked iterator warning for msvc\n#include <boost/config.hpp>\n#ifdef BOOST_MSVC\n    #pragma warning(disable:4996)\n#endif\n\n#define BOOST_TEST_MODULE odeint_implicit_euler\n\n#include <boost/test/unit_test.hpp>\n\n#include <utility>\n#include <iostream>\n\n#include <boost/numeric/odeint/stepper/implicit_euler.hpp>\n//#include <boost/numeric/odeint/util/ublas_resize.hpp>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\n\ntypedef double value_type;\ntypedef boost::numeric::ublas::vector< value_type > state_type;\ntypedef boost::numeric::ublas::matrix< value_type > matrix_type;\n\n/* use functors, because functions don't work with msvc 10, I guess this is a bug */\nstruct sys\n{\n    void operator()( const state_type &x , state_type &dxdt , const value_type t ) const\n    {\n        dxdt( 0 ) = x( 0 ) + 2 * x( 1 );\n        dxdt( 1 ) = x( 1 );\n    }\n};\n\nstruct jacobi \n{\n    void operator()( const state_type &x , matrix_type &jacobi , const value_type t ) const\n    {\n        jacobi( 0 , 0 ) = 1;\n        jacobi( 0 , 1 ) = 2;\n        jacobi( 1 , 0 ) = 0;\n        jacobi( 1 , 1 ) = 1;\n    }\n};\n\nBOOST_AUTO_TEST_SUITE( implicit_euler_test )\n\nBOOST_AUTO_TEST_CASE( test_euler )\n{\n    implicit_euler< value_type > stepper;\n    state_type x( 2 );\n    x(0) = 0.0; x(1) = 1.0;\n\n    value_type eps = 1E-12;\n\n    /* make_pair doesn't work with function pointers on msvc 10 */\n    stepper.do_step( std::make_pair( sys() , jacobi() ) , x , 0.0 , 0.1 );\n\n    using std::abs;\n\n    // compare with analytic solution of above system\n    BOOST_CHECK_MESSAGE( abs( x(0) - 20.0/81.0 ) < eps , x(0) - 20.0/81.0 );\n    BOOST_CHECK_MESSAGE( abs( x(1) - 10.0/9.0 ) < eps , x(0) - 10.0/9.0 );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "575c896a87d1d8abb6859014a524a8cc52ae92e4", "size": 2195, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/test/implicit_euler.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/test/implicit_euler.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/test/implicit_euler.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": 25.2298850575, "max_line_length": 91, "alphanum_fraction": 0.677904328, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639792, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5044795161186868}}
{"text": "/*\n [auto_generated]\n libs/numeric/odeint/test/rosenbrock4.cpp\n\n [begin_description]\n This file tests the Rosenbrock 4 stepper and its controller and dense output stepper.\n [end_description]\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// disable checked iterator warning for msvc\n#include <boost/config.hpp>\n#ifdef BOOST_MSVC\n    #pragma warning(disable:4996)\n#endif\n\n#define BOOST_TEST_MODULE odeint_rosenbrock4\n\n#include <utility>\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#include <boost/numeric/odeint/stepper/rosenbrock4.hpp>\n#include <boost/numeric/odeint/stepper/rosenbrock4_controller.hpp>\n#include <boost/numeric/odeint/stepper/rosenbrock4_dense_output.hpp>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\n\ntypedef boost::multiprecision::cpp_dec_float_50 value_type;\ntypedef boost::numeric::ublas::vector< value_type > state_type;\ntypedef boost::numeric::ublas::matrix< value_type > matrix_type;\n\n\nstruct sys\n{\n    void operator()( const state_type &x , state_type &dxdt , const value_type &t ) const\n    {\n        dxdt( 0 ) = x( 0 ) + 2 * x( 1 );\n        dxdt( 1 ) = x( 1 );\n    }\n};\n\nstruct jacobi\n{\n    void operator()( const state_type &x , matrix_type &jacobi , const value_type &t , state_type &dfdt ) const\n    {\n        jacobi( 0 , 0 ) = 1;\n        jacobi( 0 , 1 ) = 2;\n        jacobi( 1 , 0 ) = 0;\n        jacobi( 1 , 1 ) = 1;\n        dfdt( 0 ) = 0.0;\n        dfdt( 1 ) = 0.0;\n    }\n};\n\nBOOST_AUTO_TEST_SUITE( rosenbrock4_test )\n\nBOOST_AUTO_TEST_CASE( test_rosenbrock4_stepper )\n{\n    typedef rosenbrock4< value_type > stepper_type;\n    stepper_type stepper;\n\n    typedef stepper_type::state_type state_type;\n    typedef stepper_type::value_type stepper_value_type;\n    typedef stepper_type::deriv_type deriv_type;\n    typedef stepper_type::time_type time_type;\n\n    state_type x( 2 ) , xerr( 2 );\n    x(0) = 0.0; x(1) = 1.0;\n\n    stepper.do_step( std::make_pair( sys() , jacobi() ) , x ,\n                     static_cast<value_type>(0.0) , static_cast<value_type>(0.1) , xerr );\n\n    stepper.do_step( std::make_pair( sys() , jacobi() ) , x ,\n                     static_cast<value_type>(0.0) , static_cast<value_type>(0.1) );\n\n//    using std::abs;\n//    value_type eps = 1E-12;\n//\n//    // compare with analytic solution of above system\n//    BOOST_CHECK_SMALL( abs( x(0) - 20.0/81.0 ) , eps );\n//    BOOST_CHECK_SMALL( abs( x(1) - 10.0/9.0 ) , eps );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_rosenbrock4_controller )\n{\n    typedef rosenbrock4_controller< rosenbrock4< value_type > > stepper_type;\n    stepper_type stepper;\n\n    typedef stepper_type::state_type state_type;\n    typedef stepper_type::value_type stepper_value_type;\n    typedef stepper_type::deriv_type deriv_type;\n    typedef stepper_type::time_type time_type;\n\n    state_type x( 2 );\n    x( 0 ) = 0.0 ; x(1) = 1.0;\n\n    value_type t = 0.0 , dt = 0.01;\n    stepper.try_step( std::make_pair( sys() , jacobi() ) , x , t , dt );\n}\n\nBOOST_AUTO_TEST_CASE( test_rosenbrock4_dense_output )\n{\n    typedef rosenbrock4_dense_output< rosenbrock4_controller< rosenbrock4< value_type > > > stepper_type;\n    typedef rosenbrock4_controller< rosenbrock4< value_type > > controlled_stepper_type;\n    controlled_stepper_type  c_stepper;\n    stepper_type stepper( c_stepper );\n\n    typedef stepper_type::state_type state_type;\n    typedef stepper_type::value_type stepper_value_type;\n    typedef stepper_type::deriv_type deriv_type;\n    typedef stepper_type::time_type time_type;\n    state_type x( 2 );\n    x( 0 ) = 0.0 ; x(1) = 1.0;\n    stepper.initialize( x , 0.0 , 0.1 );\n    std::pair< value_type , value_type > tr = stepper.do_step( std::make_pair( sys() , jacobi() ) );\n    stepper.calc_state( 0.5 * ( tr.first + tr.second ) , x );\n}\n\nBOOST_AUTO_TEST_CASE( test_rosenbrock4_copy_dense_output )\n{\n    typedef rosenbrock4_controller< rosenbrock4< value_type > > controlled_stepper_type;\n    typedef rosenbrock4_dense_output< controlled_stepper_type > stepper_type;\n\n    controlled_stepper_type  c_stepper;\n    stepper_type stepper( c_stepper );\n    stepper_type stepper2( stepper );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "dc295c4738fca60aca3f0d8e957113de671c405f", "size": 4439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/test/rosenbrock4_mp.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/test/rosenbrock4_mp.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/test/rosenbrock4_mp.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 30.8263888889, "max_line_length": 111, "alphanum_fraction": 0.7008335211, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5044795161186867}}
{"text": "#include <Core/Animation/Pose/PoseOperation.hpp>\r\n#include <Eigen/Geometry>\r\n\r\nnamespace Ra {\r\nnamespace Core {\r\nnamespace Animation {\r\n\r\n\r\n\r\nbool compatible( const Pose& p0, const Pose& p1 ) {\r\n    return ( p0.size() == p1.size() );\r\n}\r\n\r\n\r\n\r\nPose relativePose( const Pose& modelPose, const RestPose& restPose )  {\r\n    CORE_ASSERT( compatible( modelPose, restPose ), \" Poses with different size \" );\r\n    Pose T( restPose.size() );\r\n    #pragma omp parallel for\r\n    for( int i = 0; i < int(T.size()); ++i ) {\r\n        T[i] = modelPose[i] * restPose[i].inverse( Eigen::Affine );\r\n    }\r\n    return T;\r\n}\r\n\r\n\r\n\r\nPose applyTransformation(const Pose& pose, const AlignedStdVector<Transform> &transform ) {\r\n    Pose T( std::min( pose.size(), transform.size() ) );\r\n    #pragma omp parallel for\r\n    for( int i = 0; i < int(T.size()); ++i ) {\r\n        T[i] = transform[i] * pose[i];\r\n    }\r\n    return T;\r\n}\r\n\r\n\r\n\r\nPose applyTransformation( const Pose& pose, const Transform& transform ) {\r\n    Pose T( pose.size() );\r\n    #pragma omp parallel for\r\n    for( int i = 0; i < int(T.size()); ++i ) {\r\n        T[i] = transform * pose[i];\r\n    }\r\n    return T;\r\n}\r\n\r\n\r\n\r\nbool areEqual( const Pose &p0, const Pose &p1 ) {\r\n    CORE_ASSERT( compatible( p0, p1 ), \" Poses with different size \" );\r\n    const uint n = p0.size();\r\n    for( uint i = 0; i < n; ++i ) {\r\n        if( !p0[i].isApprox( p1[i]) ) {\r\n            return false;\r\n        }\r\n    }\r\n    return true;\r\n}\r\n\r\nPose interpolatePoses(const Pose& a, const Pose& b, const Scalar t ) {\r\n    CORE_ASSERT( ( a.size() == b.size() ), \"Poses are wrong\");\r\n    CORE_ASSERT( ( ( t >= 0.0 ) && ( t <= 1.0 ) ), \"T is wrong\");\r\n\r\n    const uint size = a.size();\r\n    Pose interpolatedPose( size );\r\n\r\n#pragma omp parallel for\r\n    for ( int i = 0; i < int(size); ++i ) {\r\n        // interpolate between the transforms\r\n        Ra::Core::Transform aTransform = a[i];\r\n        Ra::Core::Transform bTransform = b[i];\r\n\r\n        Ra::Core::Quaternion aRot = Ra::Core::Quaternion( aTransform.rotation() );\r\n        Ra::Core::Quaternion bRot = Ra::Core::Quaternion( bTransform.rotation() );\r\n        Ra::Core::Quaternion interpRot = aRot.slerp(t, bRot);\r\n\r\n        Ra::Core::Vector3 interpTranslation = ( 1.0 - t ) * aTransform.translation() + t * bTransform.translation();\r\n\r\n        Ra::Core::Transform interpolatedTransform;\r\n        interpolatedTransform.linear() = interpRot.toRotationMatrix();\r\n        interpolatedTransform.translation() = interpTranslation;\r\n\r\n        interpolatedPose[i] = interpolatedTransform;\r\n    }\r\n\r\n    return interpolatedPose;\r\n}\r\n\r\nvoid interpolateTransforms( const Ra::Core::Transform& a, const Ra::Core::Transform& b, const Scalar t, Ra::Core::Transform& interpolated ) {\r\n    Ra::Core::Quaternion aRot = Ra::Core::Quaternion( a.rotation() );\r\n    Ra::Core::Quaternion bRot = Ra::Core::Quaternion( b.rotation() );\r\n    Ra::Core::Quaternion interpRot = aRot.slerp( t, bRot );\r\n\r\n    Ra::Core::Vector3 interpTranslation = ( 1.0 - t) * a.translation() + t * b.translation();\r\n\r\n    interpolated.linear() = interpRot.toRotationMatrix();\r\n    interpolated.translation() = interpTranslation;\r\n}\r\n\r\n} // namespace Animation\r\n} // namespace Core\r\n} // namespace Ra\r\n", "meta": {"hexsha": "b7c11f0eab5510d40d0d0f9124c86e639c95cbd4", "size": 3227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Core/Animation/Pose/PoseOperation.cpp", "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/Animation/Pose/PoseOperation.cpp", "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/Animation/Pose/PoseOperation.cpp", "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": 31.0288461538, "max_line_length": 142, "alphanum_fraction": 0.5990083669, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5044795124168859}}
{"text": "#pragma once\n\n#include <memory>\n#include <Eigen/Dense>\n#include <boost/math/distributions/normal.hpp>\n\nnamespace calotypes\n{\n\t\n/*! \\brief Base interface for functions that operate on pairs of data. It must be\n * that kernel(a,b) = kernel(b,a) */\ntemplate <class Data>\nclass KernelFunction\n{\npublic:\n\n\ttypedef std::shared_ptr<KernelFunction> Ptr;\n\ttypedef Data DataType;\n\t\n\tKernelFunction() {}\n\t\n\t/*! \\brief Calculates k(a,b) = k(a - b) */\n\tvirtual double Evaluate( const Data& a, const Data& b ) const \n\t{\n\t\treturn Evaluate( Difference( a, b ) );\n\t}\n\t\n\t/*! \\brief Calculates a - b */\n\tvirtual double Difference( const Data& a, const Data& b ) const = 0;\n\t\n\t/*! \\brief Calculates k(x) */\n\tvirtual double Evaluate( double x ) const { return x; }\n\t\n};\n\n/*! \\brief Pushes a kernel through a Gaussian PDF. Uses boost's implementation. */\ntemplate <class Data>\nclass GaussianKernelAdaptor\n: public KernelFunction<Data>\n{\npublic:\n\t\n\ttypedef std::shared_ptr<GaussianKernelAdaptor> Ptr;\n\t\n\t/*! \\brief Construct a Gaussian kernel with specified standard deviation. */\n\tGaussianKernelAdaptor( typename KernelFunction<Data>::Ptr& k, double s )\n\t: kernel( k ), normal( 0, s ) {}\n\t\n\tvirtual double Difference( const Data& a, const Data& b ) const\n\t{\n\t\treturn kernel->Difference( a, b );\n\t}\n\t\n\tvirtual double Evaluate( double x ) const \n\t{\n\t\treturn boost::math::pdf( normal, x );\n\t}\n\t\nprotected:\n\t\n\t\n\ttypename KernelFunction<Data>::Ptr kernel;\n\tboost::math::normal_distribution<double> normal;\n};\n\n/*! \\brief Computes the positive-definite kernel (Gram) matrix for a given kernel. \n * Assumes kernel(a,a) = 0 and kernel(a,b) = kernel(b,a). */\ntemplate <class Data>\nvoid ComputeGramMatrix( const KernelFunction<Data>& kernel, const std::vector<Data>& data,\n\t\t\t\t\t\tEigen::MatrixXf& K )\n{\n\tunsigned int N = data.size();\n\tK = Eigen::MatrixXf( N, N );\n\t\n\tfor( unsigned int i = 0; i < N; i++ ) \n\t{ \n\t\tK(i,i) = kernel.Evaluate( data[i], data[i] ); \n\t}\n\tfor( unsigned int i = 0; i < N-1; i++ )\n\t{\n\t\tfor( unsigned int j = i+1; j < N; j++ )\n\t\t{\n\t\t\tK(i,j) = kernel.Evaluate( data[i], data[j] );\n\t\t\tK(j,i) = K(i,j);\n\t\t}\n\t}\n}\n\n} // end namespace calotypes\n", "meta": {"hexsha": "7796db9cf69199df6736d4c5aa1d12e11dfbba6f", "size": 2127, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/calotypes/KernelFunctions.hpp", "max_stars_repo_name": "Humhu/calotypes", "max_stars_repo_head_hexsha": "a05a809b3b27983332c24d8fb04cb71f47e96763", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-18T14:59:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-18T14:59:39.000Z", "max_issues_repo_path": "include/calotypes/KernelFunctions.hpp", "max_issues_repo_name": "Humhu/calotypes", "max_issues_repo_head_hexsha": "a05a809b3b27983332c24d8fb04cb71f47e96763", "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/calotypes/KernelFunctions.hpp", "max_forks_repo_name": "Humhu/calotypes", "max_forks_repo_head_hexsha": "a05a809b3b27983332c24d8fb04cb71f47e96763", "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.6333333333, "max_line_length": 90, "alphanum_fraction": 0.6614950635, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5044794995727582}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\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#include <boost/config.hpp>\n#include <iostream>\n#include <iterator>\n#include <vector>\n#include <algorithm>\n#include <utility>\n#include <boost/graph/edge_list.hpp>\n#include <boost/graph/incremental_components.hpp>\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/utility.hpp>\n#include <boost/graph/graph_utility.hpp>\n\n/*\n\n  This example demonstrates the usage of the\n  connected_components_on_edgelist algorithm. This differs from the\n  connect_components algorithm in that the graph object\n  only needs to provide access to the \"list\" of edges (via the\n  edges() function).\n\n  The example graphs come from \"Introduction to\n  Algorithms\", Cormen, Leiserson, and Rivest p. 87 (though we number\n  the vertices from zero instead of one).\n\n  Sample output:\n\n  An undirected graph (edge list):\n  (0,1) (1,4) (4,0) (2,5)\n  Total number of components: 3\n  Vertex 0 is in the component who's representative is 1\n  Vertex 1 is in the component who's representative is 1\n  Vertex 2 is in the component who's representative is 5\n  Vertex 3 is in the component who's representative is 3\n  Vertex 4 is in the component who's representative is 1\n  Vertex 5 is in the component who's representative is 5\n\n  component 0 contains: 4 1 0\n  component 1 contains: 3\n  component 2 contains: 5 2\n\n */\n\nusing namespace std;\nusing boost::tie;\n\nint main(int, char*[])\n{\n    using namespace boost;\n    typedef int Index; // ID of a Vertex\n    typedef pair< Index, Index > Edge;\n    const int N = 6;\n    const int E = 4;\n    Edge edgelist[] = { Edge(0, 1), Edge(1, 4), Edge(4, 0), Edge(2, 5) };\n\n    edge_list< Edge*, Edge, ptrdiff_t, std::random_access_iterator_tag > g(\n        edgelist, edgelist + E);\n    cout << \"An undirected graph (edge list):\" << endl;\n    print_edges(g, identity_property_map());\n    cout << endl;\n\n    disjoint_sets_with_storage<> ds(N);\n    incremental_components(g, ds);\n\n    component_index< int > components(\n        &ds.parents()[0], &ds.parents()[0] + ds.parents().size());\n\n    cout << \"Total number of components: \" << components.size() << endl;\n    for (int k = 0; k != N; ++k)\n        cout << \"Vertex \" << k\n             << \" is in the component who's representative is \"\n             << ds.find_set(k) << endl;\n    cout << endl;\n\n    for (std::size_t i = 0; i < components.size(); ++i)\n    {\n        cout << \"component \" << i << \" contains: \";\n        component_index< int >::component_iterator j = components[i].first,\n                                                   jend = components[i].second;\n        for (; j != jend; ++j)\n            cout << *j << \" \";\n        cout << endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "23340514801e41fd1d17fd91ce44123bdcb7456f", "size": 3055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/components_on_edgelist.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.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": "3rdparty/boost_1_73_0/libs/graph/example/components_on_edgelist.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": "3rdparty/boost_1_73_0/libs/graph/example/components_on_edgelist.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": 32.5, "max_line_length": 79, "alphanum_fraction": 0.6183306056, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5044794904304314}}
{"text": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <stdlib.h>     /* srand, rand */\n#include <time.h>       /* time */\n\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/min.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n\nusing namespace std;\n\n#include \"cDataPoint.h\"\n#include \"KMeans.h\"\n\nvoid KMeans::Add( const vector<double>& p )\n{\n    if( myLocations.size() )\n    {\n        if( myLocations[0]->myDim != p.size() )\n        {\n            throw std::runtime_error(\"Inconsistent data attribute count\");\n        }\n    }\n    myLocations.push_back( dp_t( new cDataPoint( p ) ) );\n}\n\n    void KMeans::Add( cDataPoint& p )\n    {\n        Add( p.d );\n    }\n\ndouble KMeans::TotalDistanceToCluster()\n{\n    double total = 0;\n    for( int kc = 0; kc < myClusterCount; kc++ )\n    {\n        for( int kl = 0; kl < (int)myLocations.size(); kl++ )\n        {\n            if( myAssigns[kl] == kc )\n            {\n                // add distance from location to cluster center it is assigned to\n                total += myClusters[kc].dist( myLocations[ kl ] );\n            }\n        }\n    }\n    return total;\n}\n\nstd::string KMeans::text()\n{\n    stringstream ss;\n    int kc = 0;\n    for( auto& c : myClusters )\n    {\n        ss << \"Cluster \" << kc << \" : \";\n        for( int k = 0; k < (int)myLocations.size(); k++ )\n            if( myAssigns[k] == kc )\n                ss << myLocations[k]->text() << \", \";\n        ss << \"\\n\" << ClusterStats( kc ) << \"\\n\";\n        kc++;\n    }\n    return ss.str();\n}\n\nvoid KMeans::Assign()\n{\n    myAssigns.clear();\n    for( auto& c : myClusters )\n        c.clear();\n\n    for( auto& cl : myLocations )\n    {\n        //cout << \"assigning \" << cl.Text() << \"\\n\";\n        double m = 1000000000000000000000.0;\n        int closest_cluster;\n        for( int si = 0; si < myClusterCount; si++ )\n        {\n            //cout << \"test cluster \" << myClusters[ si ].text() << \"\\n\";\n            double td = myClusters[ si ].dist( cl );\n            if( td < m )\n            {\n                m = td;\n                closest_cluster = si;\n            }\n        }\n        myAssigns.push_back( closest_cluster );\n        myClusters[ closest_cluster ].add( cl );\n    }\n}\n\nvoid KMeans::MoveClustersToMean()\n{\n    for( int ks = 0; ks < myClusterCount; ks++ )\n    {\n        cDataPoint A( myLocations[0]->myDim );\n        int count = 0;\n        for( int kl = 0; kl < (int)myLocations.size(); kl++ )\n        {\n            if( ks == myAssigns[ kl ] )\n            {\n                A = A + *myLocations[ kl ].get();\n                count++;\n            }\n        }\n        //cout << \"cluster \" << ks << \" has \"<< count << \" \" << A.Text() << \"\\n\";\n        if( count )\n            myClusters[ ks ].move( A / count );\n    }\n}\n\nvoid KMeans::Init(\n    int clusterCount,\n    bool frandom )\n{\n    myClusterCount = clusterCount;\n\n    if( myClusterCount > (int)myLocations.size() )\n        throw std::runtime_error(\"KMeans::ClusterCount less locations than clusters\");\n\n    if( frandom )\n        ClusterLocationInitRandom();\n    else\n        ClusterLocationInitIndex();\n}\nvoid KMeans::ClusterLocationInitIndex()\n{\n    myClusters.clear();\n    for( int k = 0; k < myClusterCount; k++ )\n    {\n        int ic = k * (double)myLocations.size()/myClusterCount;\n        //cout << ic <<\" \"<< myLocations[ic].Text() << \", \";\n        myClusters.push_back( cCluster( *myLocations[ic].get() ) );\n    }\n}\nvoid KMeans::ClusterLocationInitRandom()\n{\n    /* initialize random seed: */\n    srand (time(NULL));\n    myClusters.clear();\n    for( int k = 0; k < myClusterCount; k++ )\n    {\n        myClusters.push_back( *myLocations[ rand() % myLocations.size() ].get() );\n    }\n}\n\n\nvoid KMeans::Iter( int max )\n{\n    double dt = 0;\n\n    for( int kiter=0; kiter < max; kiter++ )\n    {\n        // assign locations to nearest cluster\n        Assign();\n\n        // move clusters to mean location of locations assigned\n        MoveClustersToMean();\n\n        double d = TotalDistanceToCluster();\n        if( fabs( dt - d ) < .000001 )\n            break;\n    }\n}\n\nstd::string KMeans::ClusterStats( int cluster )\n{\n    std::stringstream ss;\n    ss << \"Cluster \" << cluster << \" means \";\n    if( 0 > cluster || cluster > (int)myClusters.size())\n        return ss.str();\n    ss << myClusters[ cluster ].text();\n\n    typedef boost::accumulators::accumulator_set<double, boost::accumulators::stats<\n    boost::accumulators::tag::min,\n          boost::accumulators::tag::max,\n          boost::accumulators::tag::mean,\n          boost::accumulators::tag::variance,\n          boost::accumulators::tag::count> >\n          Accumulator_t;\n    vector< Accumulator_t > vac( myLocations[0]->myDim );\n\n\n    for( int k = 0; k < (int)myLocations.size(); k++ )\n    {\n        if( cluster == myAssigns[ k ] )\n        {\n            for( int kd = 0; kd < (int)myLocations[0]->myDim; kd++ )\n            {\n                vac[ kd ]( myLocations[k]->d[kd] );\n            }\n        }\n    }\n\n    ss << \" mins: \";\n    for( int kd = 0; kd < (int)myLocations[0]->myDim; kd++ )\n    {\n        ss << boost::accumulators::min( vac[kd] ) << \", \";\n    }\n    ss << \" maxs: \";\n    for( int kd = 0; kd < (int)myLocations[0]->myDim; kd++ )\n    {\n        ss << boost::accumulators::max( vac[kd] ) << \", \";\n    }\n    ss << \" sds: \";\n    for( int kd = 0; kd < (int)myLocations[0]->myDim; kd++ )\n    {\n        ss << sqrt(boost::accumulators::variance( vac[kd] )) << \", \";\n    }\n    ss << \"\\n\";\n\n    return ss.str();\n}\n\nstd::vector< cCluster >&\nKMeans::clusters()\n{\n    return myClusters;\n}\n\ndouble cCluster::dist( dp_t o )\n{\n    return cDataPoint::dist( myCenter, *o.get() );\n}\nstd::string cCluster::text() const\n{\n    return myCenter.text();\n}\nvoid cCluster::move( const cDataPoint& r )\n{\n    myCenter = r;\n}\ncCluster::cCluster( const cDataPoint& r )\n{\n    myCenter = r;\n}\nvoid cCluster::clear()\n{\n    myPoints.clear();\n}\nvoid cCluster::add( dp_t p )\n{\n    myPoints.push_back( p );\n}\nstd::vector< dp_t >& cCluster::points()\n{\n    return myPoints;\n}\ncDataPoint& cCluster::center()\n{\n    return myCenter;\n}\n\n\n\n\n", "meta": {"hexsha": "c445901444ac30c5ede49dd7bbcd10e5f6ec9f8d", "size": 6269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/KMeans.cpp", "max_stars_repo_name": "JamesBremner/KMeans", "max_stars_repo_head_hexsha": "00cb3ed4ed4aae3b45398797fa24fad12ac13391", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/KMeans.cpp", "max_issues_repo_name": "JamesBremner/KMeans", "max_issues_repo_head_hexsha": "00cb3ed4ed4aae3b45398797fa24fad12ac13391", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/KMeans.cpp", "max_forks_repo_name": "JamesBremner/KMeans", "max_forks_repo_head_hexsha": "00cb3ed4ed4aae3b45398797fa24fad12ac13391", "max_forks_repo_licenses": ["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.927480916, "max_line_length": 86, "alphanum_fraction": 0.5338969533, "num_tokens": 1714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.504479485859268}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-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#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_COMPARE_SPHERICAL_HPP\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_COMPARE_SPHERICAL_HPP\n\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/tags.hpp>\n#include <boost/geometry/strategies/compare.hpp>\n#include <boost/geometry/util/math.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n\nnamespace strategy { namespace compare\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <typename Units>\nstruct shift\n{\n};\n\ntemplate <>\nstruct shift<degree>\n{\n    static inline double full() { return 360.0; }\n    static inline double half() { return 180.0; }\n};\n\ntemplate <>\nstruct shift<radian>\n{\n    static inline double full() { return 2.0 * boost::math::constants::pi<double>(); }\n    static inline double half() { return boost::math::constants::pi<double>(); }\n};\n\n} // namespace detail\n#endif\n\n/*!\n\\brief Compare (in one direction) strategy for spherical coordinates\n\\ingroup strategies\n\\tparam Point point-type\n\\tparam Dimension dimension\n*/\ntemplate <typename CoordinateType, typename Units, typename Compare>\nstruct circular_comparator\n{\n    static inline CoordinateType put_in_range(CoordinateType const& c,\n            double min_border, double max_border)\n    {\n        CoordinateType value = c;\n        while (value < min_border)\n        {\n            value += detail::shift<Units>::full();\n        }\n        while (value > max_border)\n        {\n            value -= detail::shift<Units>::full();\n        }\n        return value;\n    }\n\n    inline bool operator()(CoordinateType const& c1, CoordinateType const& c2)  const\n    {\n        Compare compare;\n\n        // Check situation that one of them is e.g. std::numeric_limits.\n        static const double full = detail::shift<Units>::full();\n        double mx = 10.0 * full;\n        if (c1 < -mx || c1 > mx || c2 < -mx || c2 > mx)\n        {\n            // do normal comparison, using circular is not useful\n            return compare(c1, c2);\n        }\n\n        static const double half = full / 2.0;\n        CoordinateType v1 = put_in_range(c1, -half, half);\n        CoordinateType v2 = put_in_range(c2, -half, half);\n\n        // Two coordinates on a circle are\n        // at max <= half a circle away from each other.\n        // So if it is more, shift origin.\n        CoordinateType diff = geometry::math::abs(v1 - v2);\n        if (diff > half)\n        {\n            v1 = put_in_range(v1, 0, full);\n            v2 = put_in_range(v2, 0, full);\n        }\n\n        return compare(v1, v2);\n    }\n};\n\n}} // namespace strategy::compare\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n// Specialize for the longitude (dim 0)\ntemplate\n<\n    typename Point,\n    template<typename> class CoordinateSystem,\n    typename Units\n>\nstruct strategy_compare<spherical_polar_tag, 1, Point, CoordinateSystem<Units>, 0>\n{\n    typedef typename coordinate_type<Point>::type coordinate_type;\n    typedef strategy::compare::circular_comparator\n        <\n            coordinate_type,\n            Units,\n            std::less<coordinate_type>\n        > type;\n};\n\ntemplate\n<\n    typename Point,\n    template<typename> class CoordinateSystem,\n    typename Units\n>\nstruct strategy_compare<spherical_polar_tag, -1, Point, CoordinateSystem<Units>, 0>\n{\n    typedef typename coordinate_type<Point>::type coordinate_type;\n    typedef strategy::compare::circular_comparator\n        <\n            coordinate_type,\n            Units,\n            std::greater<coordinate_type>\n        > type;\n};\n\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_COMPARE_SPHERICAL_HPP\n", "meta": {"hexsha": "fee1e2b7e1aa566a3221fc7eb4f2f77fd953ec95", "size": 3987, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/boost_1_47_0/boost/geometry/strategies/spherical/compare_circular.hpp", "max_stars_repo_name": "zigaosolin/Raytracer", "max_stars_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T14:37:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-25T07:38:07.000Z", "max_issues_repo_path": "external/boost_1_47_0/boost/geometry/strategies/spherical/compare_circular.hpp", "max_issues_repo_name": "zigaosolin/Raytracer", "max_issues_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2016-01-11T05:20:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T11:37:24.000Z", "max_forks_repo_path": "external/boost_1_47_0/boost/geometry/strategies/spherical/compare_circular.hpp", "max_forks_repo_name": "zigaosolin/Raytracer", "max_forks_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-01-05T15:10:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T04:59:16.000Z", "avg_line_length": 26.0588235294, "max_line_length": 86, "alphanum_fraction": 0.6661650364, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.504449918918817}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <iostream>\n#include <math.h>\n#include <Eigen/Dense>\n#include <float.h>\n#include \"fcm.h\"\n#include \"record.h\"\n\nextern vector<traj_base> traj;\nextern vector<centers_fcm_base> centers_fcm;\n\nFCM::FCM(double m, double epsilon) {\n  m_epsilon = epsilon;\n  m_m = m;\n  m_membership = nullptr;\n  m_data = nullptr;\n  m_cluster_center = nullptr;\n  m_num_clusters = 0;\n  m_num_dimensions = 0;\n}\n\nFCM::~FCM() {\n  if (m_data != nullptr) {\n    delete m_data;\n    m_data = nullptr;\n  }\n\n  if (m_membership != nullptr) {\n    delete m_membership;\n    m_membership = nullptr;\n  }\n\n  if (m_cluster_center != nullptr) {\n    delete m_cluster_center;\n    m_cluster_center = nullptr;\n  }\n}\n\n\ndouble FCM::update_membership() {\n\n  long k, i;\n  float new_uik;\n  double max_diff = 0.0, diff;\n\n  if (m_data == nullptr || m_data->rows() == 0) {\n    throw std::logic_error(\"ERROR: data should not be empty when updating the membership\");\n  }\n\n  if (m_membership == nullptr || m_membership->rows() == 0 || m_membership->rows() != m_data->rows()) {\n    this->init_membership();\n  }\n  if (m_num_clusters == 0) {\n    throw std::logic_error(\"ERROR: the number of clusters should be set\");\n  }\n\n  for (i = 0; i < m_num_clusters; i++) {\n    for (k = 0; k < m_data->rows(); k++) {\n      //cout << \"point: \" << k << \" and cluster\" << i <<endl;\n      //cout << \"\\nwill ask for the new new_uik\"<< endl;\n      new_uik = this->compute_membership_point(i, k);\n      diff = new_uik - (*m_membership)(k, i); // We need the membership inversed which is more natural for us\n      if (diff > max_diff) {\n        max_diff = diff;\n      }\n      (*m_membership)(k, i) = new_uik;\n    }\n  }\n  return max_diff;\n}\n\n\nvoid FCM::compute_centers() {\n  long i, j, k;\n  double numerator, denominator;\n  MatrixXf t;\n  t.resize(m_data->rows(), m_num_clusters);\n  if (m_data == nullptr || m_data->rows() == 0) {\n    throw std::logic_error(\"ERROR: number of rows is zero\");\n    return;\n  }\n  for (i = 0; i < m_data->rows(); i++) { // compute (u^m) for each cluster for each point\n    for (j = 0; j < m_num_clusters; j++) {\n      t(i, j) = float(pow((*m_membership)(i, j), m_m));\n    }\n  }\n  for (j = 0; j < m_num_clusters; j++) { // loop for each cluster\n    for (k = 0; k < m_num_dimensions; k++) { // for each dimension\n      numerator = 0.0;\n      denominator = 0.0;\n      for (i = 0; i < m_data->rows(); i++) {\n        numerator += t(i, j) * (*m_data)(i, k);\n        denominator += t(i, j);\n      }\n      (*m_cluster_center)(j, k) = float(numerator / denominator);\n    }\n  }\n}\n\ndouble FCM::get_dist(long i, long k) {\n  /*\n   * distance which is denoted in the paper as d\n   * k is the data point\n   * i is the cluster center point\n  */\n  //cout<<\"get_dist: point: \"<<k<<\" and cluster \"<<i<<endl;\n  long j;\n  double sqsum = 0.0;\n  if (m_num_clusters == 0) {\n    throw std::logic_error(\"ERROR: number of clusters should not be zero\\n\");\n  }\n  if (m_num_dimensions == 0) {\n    throw std::logic_error(\"ERROR: number of dimensions should not be zero\\n\");\n  }\n  for (j = 0; j < m_num_dimensions; j++) {\n    sqsum += pow(((*m_data)(k, j) - (*m_cluster_center)(i, j)), 2);\n  }\n  return sqrt(sqsum);\n}\n\nfloat FCM::compute_membership_point(long i, long k) {\n  /*\n   * i the cluster\n   * k is the data point\n  */\n  //cout << __func__ <<\"  num of cluster: \"<<m_num_clusters<<endl;\n  long j;\n  double t, seg = 0.0;\n  double exp = 2 / (m_m - 1);\n  double dik, djk;\n  if (m_num_clusters == 0) {\n    throw std::logic_error(\"ERROR: number of clusters should not be zero\\n\");\n  }\n  for (j = 0; j < m_num_clusters; j++) {\n    //std::cout << i << \"  \" << j << \"  \" << k << std::endl;\n    dik = this->get_dist(i, k);\n    djk = this->get_dist(j, k);\n    //std::cout << dik << \"  \" << djk << std::endl;\n    if (djk == 0) {\n      djk = DBL_MIN;\n    }\n    t = dik / djk;\n    t = pow(t, exp);\n    //cout << \"cluster: \" << i << \"data: \" << k << \" - \" << \"t: \"<<t<<endl;\n    seg += t;\n  }\n  //std::cin.get();\n\n  //cout << \"seg: \"<<seg << \" u: \"<<(1.0/seg)<<endl;\n  return float(1.0 / seg);\n}\n\n\nvoid FCM::set_data(MatrixXf *data) {\n  if (m_data != nullptr) {\n    delete m_data;\n  }\n  if (data->rows() == 0) {\n    throw std::logic_error(\"ERROR: seting empty data\");\n  }\n  m_data = data;\n  m_num_dimensions = m_data->cols();\n}\n\nvoid FCM::set_membership(MatrixXf *membership) {\n  if (m_data == 0) {\n    throw std::logic_error(\"ERROR: the data should present before setting up the membership\");\n  }\n  if (m_num_clusters == 0) {\n    if (membership->cols() == 0) {\n      throw std::logic_error(\"ERROR: the number of clusters is 0 and the membership matrix is empty\");\n    }\n    else {\n      this->set_num_clusters(membership->cols());\n    }\n  }\n  if (m_membership != nullptr) {\n    delete m_membership;\n  }\n  m_membership = membership;\n  if (m_membership->rows() == 0) {\n    m_membership->resize(m_data->rows(), m_num_clusters);\n  }\n}\n\nvoid FCM::init_membership() {\n  long i, j;\n  double mem;\n  if (m_num_clusters == 0) {\n    throw std::logic_error(\"ERROR: the number of clusters is 0\");\n  }\n  if (m_data == nullptr) {\n    throw std::logic_error(\"ERROR: the data should present before setting up the membership\");\n  }\n  if (m_membership != nullptr) {\n    delete m_membership;\n  }\n  m_membership = new MatrixXf;\n  m_membership->resize(m_data->rows(), m_num_clusters);\n  mem = 1.0 / m_num_clusters;\n  for (j = 0; j < m_num_clusters; j++) {\n    for (i = 0; i < m_data->rows(); i++) {\n      (*m_membership)(i, j) = float(mem);\n    }\n  }\n}\n\nvoid FCM::set_num_clusters(long num_clusters) {\n  m_num_clusters = num_clusters;\n  if (m_cluster_center) {\n    delete m_cluster_center;\n  }\n  m_cluster_center = new MatrixXf;\n  m_cluster_center->resize(m_num_clusters, m_num_dimensions);\n}\n\nMatrixXf * FCM::get_data() {\n  return m_data;\n}\n\nMatrixXf * FCM::get_membership() {\n  return m_membership;\n}\n\nMatrixXf * FCM::get_cluster_center() {\n  return m_cluster_center;\n}\n\n// DUNN INDEX //\ndouble d_eu_distance(vector<double> v1, vector<double> v2) {\n  double d_eu = 0.0;\n  for (int n = 0; n < v1.size(); ++n)\n    d_eu += pow((v1[n] - v2[n]), 2);\n\n  if (d_eu > 0) return sqrt(d_eu);\n  else return 0.0;\n}\n//-------------------------------------------------------------------\ndouble intra_distance(int i) {\n  double max_dist = 0.0;\n  for (int n = 0; n < traj.size(); ++n)\n    if (traj[n].means_class == i)\n      for (int m = 0; m < traj.size(); ++m)\n        if (traj[m].means_class == i)\n        {\n          vector<double> v1 = { traj[n].average_speed, traj[n].v_max, traj[n].v_min, traj[n].sinuosity };\n          vector<double> v2 = { traj[m].average_speed, traj[m].v_max, traj[m].v_min, traj[m].sinuosity };\n          double dist = d_eu_distance(v1, v2);\n          if (max_dist < dist)\n            max_dist = dist;\n        }\n\n  return max_dist;\n}\n//-------------------------------------------------------------------\ndouble inter_distance(int n, int m) {\n  double min_dist = 1e6;\n  for (auto &t1: traj)\n    if (t1.means_class == n)\n      for (auto &t2:traj)\n        if (t2.means_class == m)\n        {\n          vector<double> v1 = { t1.average_speed, t1.v_max, t1.v_min, t1.sinuosity };\n          vector<double> v2 = { t2.average_speed, t2.v_max, t2.v_min, t2.sinuosity };\n          double dist = d_eu_distance(v1, v2);\n          if (min_dist > dist)\n            min_dist = dist;\n        }\n\n  return min_dist;\n}\n//-------------------------------------------------------------------\ndouble measure_dunn_index() {\n  double num=  1e6;\n  double den = 0.0;\n\n  for (auto &c : centers_fcm) {\n    double intra_dist_ci = intra_distance(c.idx);\n    if (intra_dist_ci > den)\n      den = intra_dist_ci;\n  }\n  std::cout << \"den measured\" << std::endl;\n\n  for (int n=0; n<centers_fcm.size()-1; ++n)\n    for (int m = n + 1; m < centers_fcm.size(); ++m) {\n      double inter_n_m = inter_distance(n, m);\n      if (inter_n_m < num)\n        num = inter_n_m;\n    }\n\n  std::cout << \"num measured \" << std::endl;\n  return (num/den);\n}\n//-------------------------------------------------------------------\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "402ad92e036e0778c5c2648956fec20a152ea388", "size": 8041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/fcm.cpp", "max_stars_repo_name": "physycom/city-pro", "max_stars_repo_head_hexsha": "dc9c4aef61f7bdf186b08722105764a714ab9bfd", "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": "source/fcm.cpp", "max_issues_repo_name": "physycom/city-pro", "max_issues_repo_head_hexsha": "dc9c4aef61f7bdf186b08722105764a714ab9bfd", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/fcm.cpp", "max_forks_repo_name": "physycom/city-pro", "max_forks_repo_head_hexsha": "dc9c4aef61f7bdf186b08722105764a714ab9bfd", "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.3639344262, "max_line_length": 109, "alphanum_fraction": 0.5689590847, "num_tokens": 2440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5044499133633091}}
{"text": "\ufeff#include <armadillo>\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/matrix_proxy.hpp\"\n#include \"viennacl/vector_proxy.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/tools/timer.hpp\"\n#include \"viennacl/forwards.h\"\n#include \"comfi.hpp\"\n\nusing namespace viennacl::linalg;\nusing namespace arma;\n\n\n/* sp_mat comfi::routines::computeRi(const vcl_vec &xn_vcl, const comfi::types::Operators &op) */\n/*{*/\n/*  vec xn(num_of_elem);*/\n/*  viennacl::fast_copy(xn_vcl, xn);*/\n\n/*  const uint nnzp = 12;*/\n/*  umat  Avi = zeros<umat>(nnzp, num_of_grid);*/\n/*  umat  Avj = zeros<umat>(nnzp, num_of_grid);*/\n/*  mat   Avv = zeros<mat> (nnzp, num_of_grid);*/\n\n/*  #pragma omp parallel for schedule(static)*/\n/*  for (uint index=0; index<num_of_grid; index++)*/\n/*  {*/\n/*    // indexing*/\n/*    const unsigned int  i=(index)%nx; // find i and c++ index ii*/\n/*    const unsigned int  j=(index)/nx; //find j and c++ index jj*/\n\n/*    const int           ij=ind(i, j);*/\n/*    int                 ip1j=ind(i+1, j);*/\n/*    int                 im1j=ind(i-1, j);*/\n/*    int                 ijp1=ind(i, j+1);*/\n/*    int                 ijm1=ind(i, j-1);*/\n\n/*    //const double nuin   = mhdsim::sol::nu_in(Nnij, 0.5*(Tpij+Tnij));*/\n/*    //const double nuni   = mhdsim::sol::nu_in(Nnij, 0.5*(Tpij+Tnij))*Npij/Nnij;*/\n/*    const double nuni   = collisionrate;*/\n/*    const double nuin   = nuni*Nnij/Npij;*/\n\n/*    //const double resij = mhdsim::sol::resistivity(Npij, Nnij, Tpij, Tnij);*/\n\n/*    //const double irate = mhdsim::sol::ionization_coeff(Tnij);*/\n/*    //const double rrate = mhdsim::sol::recomb_coeff(Tpij);*/\n\n/*    // collect*/\n/*    Avi.col(index) = vi;*/\n/*    Avj.col(index) = vj;*/\n/*    Avv.col(index) = vv;*/\n/*  }*/\n\n/*  return comfi::util::syncSpMat(Avi, Avj, Avv);*/\n/*}*/\n\nvcl_mat comfi::routines::build_eig_matrix_z(const vcl_mat &xn,\n                                            comfi::types::Context &ctx) {\n  vcl_mat eig_matrix(ctx.num_of_grid(), ctx.num_of_eq);\n  const vcl_mat p_fast = comfi::routines::fast_speed_z(xn, ctx);\n  const vcl_mat GLM_eig = viennacl::scalar_matrix<double>(p_fast.size1(), p_fast.size2(), ctx.c_h()); \n  const vcl_mat V_z = element_fabs(viennacl::linalg::element_div(ctx.v_NVz(xn), ctx.v_Np(xn)));\n  const vcl_mat U_z = element_fabs(viennacl::linalg::element_div(ctx.v_NUz(xn), ctx.v_Nn(xn)));\n  const vcl_mat c_a = viennacl::linalg::element_div(ctx.v_Bz(xn), viennacl::linalg::element_sqrt(ctx.v_Np(xn)));\n  const vcl_mat c_s = comfi::routines::sound_speed_p(xn, ctx);\n  const vcl_mat c_sn = comfi::routines::sound_speed_n(xn, ctx);\n\n  //ctx.v_Np(eig_matrix) = -GLM_eig;\n  ctx.v_Np(eig_matrix) = V_z+p_fast;\n  ctx.v_NVx(eig_matrix) = V_z+p_fast;\n  ctx.v_NVp(eig_matrix) = V_z+c_a;\n  ctx.v_NVz(eig_matrix) = V_z+p_fast;\n  ctx.v_Bx(eig_matrix) = V_z;\n  ctx.v_Bp(eig_matrix) = V_z+c_s;\n  ctx.v_Bz(eig_matrix) = V_z+c_a;\n  ctx.v_Ep(eig_matrix) = V_z+p_fast;\n  ctx.v_Nn(eig_matrix) = U_z+c_sn;\n  ctx.v_NUx(eig_matrix) = U_z+c_sn;\n  ctx.v_NUp(eig_matrix) = U_z+c_sn;\n  ctx.v_NUz(eig_matrix) = U_z+c_sn;\n  ctx.v_En(eig_matrix) = U_z+c_sn;\n  ctx.v_GLM(eig_matrix) = GLM_eig;\n\n  return eig_matrix;\n}\n\nvcl_mat comfi::routines::build_eig_matrix_x(const vcl_mat &xn,\n                                            comfi::types::Context &ctx) {\n  vcl_mat eig_matrix(ctx.num_of_grid(), ctx.num_of_eq);\n  const vcl_mat p_fast = comfi::routines::fast_speed_x(xn, ctx);\n  const vcl_mat GLM_eig = viennacl::scalar_matrix<double>(p_fast.size1(), p_fast.size2(), ctx.c_h()); \n  const vcl_mat V_x = viennacl::linalg::element_div(ctx.v_NVx(xn), ctx.v_Np(xn));\n  const vcl_mat U_x = viennacl::linalg::element_div(ctx.v_NUx(xn), ctx.v_Nn(xn));\n  const vcl_mat c_a = viennacl::linalg::element_div(ctx.v_Bx(xn), viennacl::linalg::element_sqrt(ctx.v_Np(xn)));\n  const vcl_mat c_s = comfi::routines::sound_speed_p(xn, ctx);\n  const vcl_mat c_sn = comfi::routines::sound_speed_n(xn, ctx);\n\n  //ctx.v_Np(eig_matrix) = -GLM_eig;\n  ctx.v_Np(eig_matrix) = V_x+p_fast;\n  ctx.v_NVx(eig_matrix) = V_x-p_fast;\n  ctx.v_NVp(eig_matrix) = V_x-c_a;\n  ctx.v_NVz(eig_matrix) = V_x-c_s;\n  ctx.v_Bx(eig_matrix) = V_x;\n  ctx.v_Bp(eig_matrix) = V_x+c_s;\n  ctx.v_Bz(eig_matrix) = V_x+c_a;\n  ctx.v_Ep(eig_matrix) = V_x+p_fast;\n  ctx.v_Nn(eig_matrix) = U_x+c_sn;\n  ctx.v_NUx(eig_matrix) = U_x-c_sn;\n  ctx.v_NUp(eig_matrix) = U_x;\n  ctx.v_NUz(eig_matrix) = U_x-c_sn;\n  ctx.v_En(eig_matrix) = U_x+c_sn;\n  ctx.v_GLM(eig_matrix) = GLM_eig;\n\n  return eig_matrix;\n}\n\nvcl_mat comfi::routines::Re_MUSCL(const vcl_mat &xn, comfi::types::Context &ctx)\n{\n  const vcl_mat xn_ip1 = comfi::operators::ip1(xn, ctx);\n  const vcl_mat xn_im1 = comfi::operators::im1(xn, ctx);\n  const vcl_mat xn_jp1 = comfi::operators::jp1(xn, ctx);\n  const vcl_mat xn_jm1 = comfi::operators::jm1(xn, ctx);\n\n  const vcl_mat dxn_iph = xn_ip1-xn;\n  const vcl_mat dxn_imh = xn-xn_im1;\n  const vcl_mat dxn_jph = xn_jp1-xn;\n  const vcl_mat dxn_jmh = xn-xn_jm1;\n\n  /*\n  viennacl::ocl::program & fluxl_prog  = viennacl::ocl::current_context().get_program(\"fluxl\");\n  viennacl::ocl::kernel  & fluxl = fluxl_prog.get_kernel(\"fluxl\");\n\n  const vcl_mat r_i   = element_div(dxn_imh, dxn_iph);\n  const vcl_mat r_ip1 = element_div(dxn_iph, (comfi::operators::ip1(xn_ip1, ctx)-xn_ip1));\n  const vcl_mat r_im1 = element_div((xn_im1-comfi::operators::im1(xn_im1, ctx)), dxn_imh);\n  const vcl_mat r_j   = element_div(dxn_jmh, dxn_jph);\n  const vcl_mat r_jp1 = element_div(dxn_jph, (comfi::operators::jp1(xn_jp1, ctx)-xn_jp1));\n  const vcl_mat r_jm1 = element_div((xn_jm1-comfi::operators::jm1(xn_jm1, ctx)), dxn_jmh);\n  vcl_mat phi_i(xn.size1(), xn.size2()), phi_ip1(xn.size1(), xn.size2()), phi_im1(xn.size1(), xn.size2()),\n          phi_j(xn.size1(), xn.size2()), phi_jp1(xn.size1(), xn.size2()), phi_jm1(xn.size1(), xn.size2());\n  viennacl::ocl::enqueue(fluxl(r_i, phi_i,\n                               cl_uint(r_i.size1()*r_i.size2())));\n  viennacl::ocl::enqueue(fluxl(r_ip1, phi_ip1,\n                               cl_uint(r_i.size1()*r_i.size2())));\n  viennacl::ocl::enqueue(fluxl(r_im1, phi_im1,\n                               cl_uint(r_i.size1()*r_i.size2())));\n  viennacl::ocl::enqueue(fluxl(r_j, phi_j,\n                               cl_uint(r_i.size1()*r_i.size2())));\n  viennacl::ocl::enqueue(fluxl(r_jp1, phi_jp1,\n                               cl_uint(r_i.size1()*r_i.size2())));\n  viennacl::ocl::enqueue(fluxl(r_jm1, phi_jm1,\n                               cl_uint(r_i.size1()*r_i.size2())));\n\n  vcl_mat Lxn_iph = xn     + 0.5*element_prod(phi_i, dxn_imh);\n  vcl_mat Lxn_imh = xn_im1 + 0.5*element_prod(phi_im1, dxn_imh);\n  vcl_mat Rxn_iph = xn_ip1 - 0.5*element_prod(phi_ip1, dxn_iph);\n  vcl_mat Rxn_imh = xn     - 0.5*element_prod(phi_i, dxn_iph);\n  vcl_mat Lxn_jph = xn     + 0.5*element_prod(phi_j, dxn_jmh);\n  vcl_mat Lxn_jmh = xn_jm1 + 0.5*element_prod(phi_jm1, dxn_jmh);\n  vcl_mat Rxn_jph = xn_jp1 - 0.5*element_prod(phi_jp1, dxn_jph);\n  vcl_mat Rxn_jmh = xn     - 0.5*element_prod(phi_j, dxn_jph);\n  */\n\n  static const vcl_mat eps = viennacl::scalar_matrix<double>(xn.size1(), xn.size2(), 1.e-100);\n  const vcl_mat r_i   = element_div(dxn_imh, dxn_iph+eps);\n  const vcl_mat r_ip1 = element_div(dxn_iph, (comfi::operators::ip1(xn_ip1, ctx)-xn_ip1)+eps);\n  const vcl_mat r_im1 = element_div((xn_im1-comfi::operators::im1(xn_im1, ctx)), dxn_imh+eps);\n  const vcl_mat r_j   = element_div(dxn_jmh, dxn_jph+eps);\n  const vcl_mat r_jp1 = element_div(dxn_jph, (comfi::operators::jp1(xn_jp1, ctx)-xn_jp1)+eps);\n  const vcl_mat r_jm1 = element_div((xn_jm1-comfi::operators::jm1(xn_jm1, ctx)), dxn_jmh+eps);\n  //extrapolated cell edge variables\n  vcl_mat Lxn_iph = xn     + 0.5*element_prod(comfi::routines::fluxl(r_i), dxn_imh);\n  vcl_mat Lxn_imh = xn_im1 + 0.5*element_prod(comfi::routines::fluxl(r_im1), dxn_imh);\n  vcl_mat Rxn_iph = xn_ip1 - 0.5*element_prod(comfi::routines::fluxl(r_ip1), dxn_iph);\n  vcl_mat Rxn_imh = xn     - 0.5*element_prod(comfi::routines::fluxl(r_i), dxn_iph);\n  vcl_mat Lxn_jph = xn     + 0.5*element_prod(comfi::routines::fluxl(r_j), dxn_jmh);\n  vcl_mat Lxn_jmh = xn_jm1 + 0.5*element_prod(comfi::routines::fluxl(r_jm1), dxn_jmh);\n  vcl_mat Rxn_jph = xn_jp1 - 0.5*element_prod(comfi::routines::fluxl(r_jp1), dxn_jph);\n  vcl_mat Rxn_jmh = xn     - 0.5*element_prod(comfi::routines::fluxl(r_j), dxn_jph);\n  \n   // BOUNDARY CONDITIONS\n  //mhdsim::routines::bottomBC(Lxn_jmh,Rxn_jmh,t,op,bg);\n  //comfi::routines::bottombc_shock_tube(Lxn_jmh, Rxn_jmh, ctx);\n  //comfi::routines::topbc_shock_tube(Lxn_jph, Rxn_jph, ctx);\n  //comfi::routines::topbc_soler(Lxn_jph, Rxn_jph, op);\n  //mhdsim::routines::topbc_driver(Lxn_jph, Rxn_jph, t, op);\n  //comfi::routines::bottombc_soler(Lxn_jmh, Rxn_jmh, op);\n\n  /* // Fast mode speed eigenvalues */\n  /* vcl_mat Leig_iph_p = comfi::routines::fast_speed_x_mat(Lxn_iph, ctx); */\n  /* vcl_mat Reig_iph_p = comfi::routines::fast_speed_x_mat(Rxn_iph, ctx); */\n  /* vcl_mat Leig_jph_p = comfi::routines::fast_speed_z_mat(Lxn_jph, ctx); */\n  /* vcl_mat Reig_jph_p = comfi::routines::fast_speed_z_mat(Rxn_jph, ctx); */\n  /* vcl_mat Leig_imh_p = comfi::routines::fast_speed_x_mat(Lxn_imh, ctx); */\n  /* vcl_mat Reig_imh_p = comfi::routines::fast_speed_x_mat(Rxn_imh, ctx); */\n  /* vcl_mat Leig_jmh_p = comfi::routines::fast_speed_z_mat(Lxn_jmh, ctx); */\n  /* vcl_mat Reig_jmh_p = comfi::routines::fast_speed_z_mat(Rxn_jmh, ctx); */\n\n  /* viennacl::ocl::program & eig_prog  = viennacl::ocl::current_context().get_program(\"element_max\"); */\n  /* viennacl::ocl::kernel  & element_max = eig_prog.get_kernel(\"element_max\"); */\n\n  /* vcl_mat a_imh_p(Leig_iph_p.size1(), Leig_iph_p.size2()); */\n  /* viennacl::ocl::enqueue(element_max(Leig_imh_p, Reig_imh_p, */\n  /*                                    a_imh_p, */\n  /*                                    cl_uint(Leig_imh_p.size1()))); */\n  /* vcl_mat a_iph_p(Leig_iph_p.size1(), Leig_iph_p.size2()); */\n  /* viennacl::ocl::enqueue(element_max(Leig_iph_p, Reig_iph_p, */\n  /*                                    a_iph_p, */\n  /*                                    cl_uint(Leig_iph_p.size1()))); */\n  /* vcl_mat a_jmh_p(Leig_iph_p.size1(), Leig_iph_p.size2()); */\n  /* viennacl::ocl::enqueue(element_max(Leig_jmh_p, Reig_jmh_p, */\n  /*                                    a_jmh_p, */\n  /*                                    cl_uint(Leig_jmh_p.size1()))); */\n  /* vcl_mat a_jph_p(Leig_iph_p.size1(), Leig_iph_p.size2()); */\n  /* viennacl::ocl::enqueue(element_max(Leig_jph_p, Reig_jph_p, */\n  /*                                    a_jph_p, */\n  /*                                    cl_uint(Leig_jph_p.size1()))); */\n  /* Leig_iph_p = element_fabs(element_div(ctx.v_NVx(Lxn_iph), ctx.v_Np(Lxn_iph))); */\n  /* viennacl::ocl::enqueue(element_max(Leig_iph_p, a_iph_p, */\n  /*                                    a_iph_p, */\n  /*                                    cl_uint(Leig_iph_p.size1()))); */\n\n  /* Reig_iph_p = element_fabs(element_div(ctx.v_NVx(Rxn_iph), ctx.v_Np(Rxn_iph))); */\n  /* viennacl::ocl::enqueue(element_max(Reig_iph_p, a_iph_p, */\n  /*                                    a_iph_p, */\n  /*                                    cl_uint(Reig_iph_p.size1()))); */\n  /* Leig_jph_p = element_fabs(element_div(ctx.v_NVz(Lxn_jph), ctx.v_Np(Lxn_jph))); */\n  /* viennacl::ocl::enqueue(element_max(Leig_jph_p, a_jph_p, */\n  /*                                    a_jph_p, */\n  /*                                    cl_uint(Leig_jph_p.size1()))); */\n  /* Reig_jph_p = element_fabs(element_div(ctx.v_NVz(Rxn_jph), ctx.v_Np(Rxn_jph))); */\n  /* viennacl::ocl::enqueue(element_max(Reig_jph_p, a_jph_p, */\n  /*                                    a_jph_p, */\n  /*                                    cl_uint(Reig_jph_p.size1()))); */\n  /* Leig_imh_p = element_fabs(element_div(ctx.v_NVx(Lxn_imh), ctx.v_Np(Lxn_imh))); */\n  /* viennacl::ocl::enqueue(element_max(Leig_imh_p, a_imh_p, */\n  /*                                    a_imh_p, */\n  /*                                    cl_uint(Leig_imh_p.size1()))); */\n  /* Reig_imh_p = element_fabs(element_div(ctx.v_NVx(Rxn_imh), ctx.v_Np(Rxn_imh))); */\n  /* viennacl::ocl::enqueue(element_max(Reig_imh_p, a_imh_p, */\n  /*                                    a_imh_p, */\n  /*                                    cl_uint(Reig_imh_p.size1()))); */\n  /* Leig_jmh_p = element_fabs(element_div(ctx.v_NVz(Lxn_jmh), ctx.v_Np(Lxn_jmh))); */\n  /* viennacl::ocl::enqueue(element_max(Leig_jmh_p, a_jmh_p, */\n  /*                                    a_jmh_p, */\n  /*                                    cl_uint(Leig_jmh_p.size1()))); */\n  /* Reig_jmh_p = element_fabs(element_div(ctx.v_NVz(Rxn_jmh), ctx.v_Np(Rxn_jmh))); */\n  /* viennacl::ocl::enqueue(element_max(Reig_jmh_p, a_jmh_p, */\n  /*                                    a_jmh_p, */\n  /*                                    cl_uint(Reig_jmh_p.size1()))); */\n\n  /* vcl_mat Leig_iph_n = comfi::routines::sound_speed_neutral_mat(Lxn_iph, ctx); */\n  /* vcl_mat Reig_iph_n = comfi::routines::sound_speed_neutral_mat(Rxn_iph, ctx); */\n  /* vcl_mat Leig_jph_n = comfi::routines::sound_speed_neutral_mat(Lxn_jph, ctx); */\n  /* vcl_mat Reig_jph_n = comfi::routines::sound_speed_neutral_mat(Rxn_jph, ctx); */\n  /* vcl_mat Leig_imh_n = comfi::routines::sound_speed_neutral_mat(Lxn_imh, ctx); */\n  /* vcl_mat Reig_imh_n = comfi::routines::sound_speed_neutral_mat(Rxn_imh, ctx); */\n  /* vcl_mat Leig_jmh_n = comfi::routines::sound_speed_neutral_mat(Lxn_jmh, ctx); */\n  /* vcl_mat Reig_jmh_n = comfi::routines::sound_speed_neutral_mat(Rxn_jmh, ctx); */\n\n  /* vcl_mat a_imh_n(Leig_iph_n.size1(), Leig_iph_n.size2()); */\n  /* if (ctx.bc_left != comfi::types::DIMENSIONLESS) { */\n  /*   viennacl::ocl::enqueue(element_max(Leig_imh_n, Reig_imh_n, */\n  /*                                      a_imh_n, */\n  /*                                      cl_uint(Leig_imh_n.size1()))); */\n  /* } */\n  /* vcl_mat a_iph_n(Leig_iph_n.size1(), Leig_iph_n.size2()); */\n  /* if (ctx.bc_right != comfi::types::DIMENSIONLESS) { */\n  /*   viennacl::ocl::enqueue(element_max(Leig_iph_n, Reig_iph_n, */\n  /*                                      a_iph_n, */\n  /*                                      cl_uint(Leig_iph_n.size1()))); */\n  /* } */\n  /* vcl_mat a_jmh_n(Leig_iph_n.size1(), Leig_iph_n.size2()); */\n  /* if (ctx.bc_down != comfi::types::DIMENSIONLESS) { */\n  /*   viennacl::ocl::enqueue(element_max(Leig_jmh_n, Reig_jmh_n, */\n  /*                                      a_jmh_n, */\n  /*                                      cl_uint(Leig_jmh_n.size1()))); */\n  /* } */\n  /* vcl_mat a_jph_n(Leig_iph_n.size1(), Leig_iph_n.size2()); */\n  /* if (ctx.bc_up != comfi::types::DIMENSIONLESS) { */\n  /*   viennacl::ocl::enqueue(element_max(Leig_jph_n, Reig_jph_n, */\n  /*                                      a_jph_n, */\n  /*                                      cl_uint(Leig_jph_n.size1()))); */\n  /* } */\n\n  /* Reig_jph_n = element_fabs(element_div(ctx.v_NUz(Rxn_jph), ctx.v_Nn(Rxn_jph))); */\n  /* viennacl::ocl::enqueue(element_max(Reig_jph_n, a_jph_n, */\n  /*                                    a_jph_n, */\n  /*                                    cl_uint(Reig_jph_n.size1()))); */\n  /* Reig_jmh_n = element_fabs(element_div(ctx.v_NUz(Rxn_jmh), ctx.v_Nn(Rxn_jmh))); */\n  /* viennacl::ocl::enqueue(element_max(Reig_jmh_n, a_jmh_n, */\n  /*                                    a_jmh_n, */\n  /*                                    cl_uint(Reig_jmh_n.size1()))); */\n  /* Reig_imh_n = element_fabs(element_div(ctx.v_NUx(Rxn_imh), ctx.v_Nn(Rxn_imh))); */\n  /* viennacl::ocl::enqueue(element_max(Reig_imh_n, a_imh_n, */\n  /*                                    a_imh_n, */\n  /*                                    cl_uint(Reig_imh_n.size1()))); */\n  /* Reig_iph_n = element_fabs(element_div(ctx.v_NUx(Rxn_iph), ctx.v_Nn(Rxn_iph))); */\n  /* viennacl::ocl::enqueue(element_max(Reig_iph_n, a_iph_n, */\n  /*                                    a_iph_n, */\n  /*                                    cl_uint(Reig_iph_n.size1()))); */\n  /* Leig_jph_n = element_fabs(element_div(ctx.v_NUz(Lxn_jph), ctx.v_Nn(Lxn_jph))); */\n  /* viennacl::ocl::enqueue(element_max(Leig_jph_n, a_jph_n, */\n  /*                                    a_jph_n, */\n  /*                                    cl_uint(Leig_jph_n.size1()))); */\n  /* Leig_jmh_n = element_fabs(element_div(ctx.v_NUz(Lxn_jmh), ctx.v_Nn(Lxn_jmh))); */\n  /* viennacl::ocl::enqueue(element_max(Leig_jmh_n, a_jmh_n, */\n  /*                                    a_jmh_n, */\n  /*                                    cl_uint(Leig_jmh_n.size1()))); */\n  /* Leig_imh_n = element_fabs(element_div(ctx.v_NUx(Lxn_imh), ctx.v_Nn(Lxn_imh))); */\n  /* viennacl::ocl::enqueue(element_max(Leig_imh_n, a_imh_n, */\n  /*                                    a_imh_n, */\n  /*                                    cl_uint(Leig_imh_n.size1()))); */\n  /* Leig_iph_n = element_fabs(element_div(ctx.v_NUx(Lxn_iph), ctx.v_Nn(Lxn_iph))); */\n  /* viennacl::ocl::enqueue(element_max(Leig_iph_n, a_iph_n, */\n  /*                                    a_iph_n, */\n  /*                                    cl_uint(Leig_iph_n.size1()))); */\n\n  const vcl_mat a_imh = element_fabs(build_eig_matrix_x(0.5*(Lxn_imh+Rxn_imh), ctx));\n  const vcl_mat a_iph = element_fabs(build_eig_matrix_x(0.5*(Lxn_iph+Rxn_iph), ctx));\n  const vcl_mat a_jmh = element_fabs(build_eig_matrix_z(0.5*(Lxn_jmh+Rxn_jmh), ctx));\n  const vcl_mat a_jph = element_fabs(build_eig_matrix_z(0.5*(Lxn_jph+Rxn_jph), ctx));\n\n  // LAX-FRIEDRICHS FLUX\n  const vcl_mat Fximh = 0.5*(comfi::routines::Fx(Lxn_imh, xn, ctx)+comfi::routines::Fx(Rxn_imh, xn, ctx))\n                             -element_prod(a_imh, (Rxn_imh-Lxn_imh));\n  const vcl_mat Fxiph = 0.5*(comfi::routines::Fx(Lxn_iph, xn, ctx)+comfi::routines::Fx(Rxn_iph, xn, ctx))\n                             -element_prod(a_iph, (Rxn_iph-Lxn_iph));\n  const vcl_mat Fzjmh = 0.5*(comfi::routines::Fz(Lxn_jmh, xn, ctx)+comfi::routines::Fz(Rxn_jmh, xn, ctx))\n                             -element_prod(a_jmh, (Rxn_jmh-Lxn_jmh));\n  const vcl_mat Fzjph = 0.5*(comfi::routines::Fz(Lxn_jph, xn, ctx)+comfi::routines::Fz(Rxn_jph, xn, ctx))\n                             -element_prod(a_jph, (Rxn_jph-Lxn_jph));\n\n  return -1.0*(Fxiph-Fximh)/ctx.dx\n         -1.0*(Fzjph-Fzjmh)/ctx.dz;\n         //+ prod(op.f2V, v_collission_source)\n         //- prod(op.f2U, v_collission_source)\n         //+ prod(op.f2U, u_collission_source)\n         //- prod(op.f2V, u_collission_source);\n         //+ prod(op.f2V, me_nu_J)\n         //+ prod(op.f2V, vsource)\n         //- prod(op.f2U, me_nu_J)\n         //- prod(op.f2U, vsource)\n         //- prod(op.SG, xn)\n         //+ boundaryconditions\n         //+ prod(op.s2Np, isource)\n         //- prod(op.s2Nn, isource)\n         //+ prod(op.s2Tp, TpdivV)/3.0;\n         //+ prod(op.s2Tn, TndivU)/3.0;\n         //+ prod(op.s2Tp, nuin_dV2)/3.0\n         //+ prod(op.s2Tn, nuni_dV2)/3.0\n         //- two_thirds*prod(op.s2Tn, L)\n         //+ prod(op.f2B, gNpxJxBoverN2) // Hall term source term\n         //- prod(op.f2B,gradrescrossJ);\n}\n\nvcl_mat comfi::routines::computeRHS_RK4(const vcl_mat &xn, comfi::types::Context &ctx)\n{\n  const double dt = ctx.dt();\n  // RK-4\n  const vcl_mat k1 = Re_MUSCL(xn, ctx)*dt; //return xn+k1;\n  //const vcl_mat k2 = Re_MUSCL(xn+0.5*k1,t+0.5*dt,op,bg)*dt;\n  const vcl_mat k2 = Re_MUSCL(xn+0.5*k1, ctx)*dt;\n  //const vcl_mat k3 = Re_MUSCL(xn+0.5*k2,t+0.5*dt,op,bg)*dt;\n  const vcl_mat k3 = Re_MUSCL(xn+0.5*k2, ctx)*dt;\n  //const vcl_mat k4 = Re_MUSCL(xn+k3,t+dt,op,bg)*dt;\n  const vcl_mat k4 = Re_MUSCL(xn+k3, ctx)*dt;\n\n  vcl_mat result = xn + (k1+2.0*k2+2.0*k3+k4)/6.0;\n\n  // GLM exact solution\n  ctx.v_GLM(result) *= std::exp(-ctx.alpha_p*ctx.dt()*ctx.c_h()/ctx.ds);\n\n  return result;\n}\n\nvcl_mat comfi::routines::computeRHS_Euler(const vcl_mat &xn, comfi::types::Context &ctx)\n{\n  // Simple Eulerian Steps\n  vcl_mat result = xn + comfi::routines::Re_MUSCL(xn, ctx)*ctx.dt();\n\n  // GLM exact solution\n  ctx.v_GLM(result) *= std::exp(-ctx.alpha_p*ctx.dt()*ctx.c_h()/ctx.ds);\n\n  return result;\n}\n\n/*\nvcl_vec comfi::routines::computeRHS_BDF2(const vcl_vec &xn,\n                                         const vcl_vec &xn1,\n                                         const vcl_sp_mat &Ri,\n                                         const double alpha,\n                                         const double beta,\n                                         const double dt,\n                                         const double t,\n                                         comfi::types::Operators &op,\n                                         const comfi::types::BgData &bg)\n{\n  // BDF2\n  static double dtn1 = dt;\n\n  const vcl_vec Rin = prod(Ri,xn);\n  const vcl_vec Re = comfi::routines::Re_MUSCL(xn,t,op,bg);\n  const vcl_vec xnpRedt = xn+Re*dt;\n  const vcl_vec result = xnpRedt\n                       + alpha*dt*(((xn-xn1)/dtn1)-Re)\n                       + beta*dt*Rin;\n\n  //GLM\n  const double a = 0.1;\n  vcl_vec glm = prod(op.GLMs,xnpRedt);\n  glm *= std::exp(-a*op.ch/(ds/dt));\n\n  dtn1=dt;\n  return prod(op.ImGLM,result) + prod(op.s2GLM,glm);\n}\n*/\n\nvcl_mat comfi::routines::Fx(const vcl_mat &xn, const vcl_mat &xn_ij, comfi::types::Context &ctx)\n{\n  vcl_mat F = viennacl::zero_matrix<double>(xn.size1(), xn.size2());\n\n  const vcl_mat V_x = element_div(ctx.v_NVx(xn), ctx.v_Np(xn));\n  const vcl_mat U_x = element_div(ctx.v_NUx(xn), ctx.v_Nn(xn));\n  const vcl_mat V_z = element_div(ctx.v_NVz(xn), ctx.v_Np(xn));\n  const vcl_mat U_z = element_div(ctx.v_NUz(xn), ctx.v_Nn(xn));\n  const vcl_mat V_p = element_div(ctx.v_NVp(xn), ctx.v_Np(xn));\n  const vcl_mat U_p = element_div(ctx.v_NUp(xn), ctx.v_Nn(xn));\n\n  // Local speed flux -> quantity*Vz\n  ctx.v_Np(F) = element_prod(ctx.v_Np(xn), V_x);\n  ctx.v_Nn(F) = element_prod(ctx.v_Nn(xn), U_x);\n  ctx.v_NVx(F) = element_prod(ctx.v_NVx(xn), V_x);\n  ctx.v_NVz(F) = element_prod(ctx.v_NVz(xn), V_x);\n  ctx.v_NVp(F) = element_prod(ctx.v_NVp(xn), V_x);\n  ctx.v_NUx(F) = element_prod(ctx.v_NUx(xn), U_x);\n  ctx.v_NUz(F) = element_prod(ctx.v_NUz(xn), U_x);\n  ctx.v_NUp(F) = element_prod(ctx.v_NUp(xn), U_x);\n  ctx.v_Ep(F) = element_prod(ctx.v_Ep(xn), V_x);\n  ctx.v_En(F) = element_prod(ctx.v_En(xn), U_x);\n\n  // Induction VB-BV\n  ctx.v_Bz(F) = element_prod(V_x, ctx.v_Bz(xn)) - element_prod(ctx.v_Bx(xn), V_z);\n  ctx.v_Bp(F) = element_prod(V_x, ctx.v_Bp(xn)) - element_prod(ctx.v_Bx(xn), V_p);\n\n  // General Lagrange Multiplier\n  ctx.v_Bx(F) = ctx.v_GLM(xn);\n\n  // Thermal pressure\n  vcl_mat Pp = comfi::routines::pressure_p(xn, ctx);\n  ctx.v_NVx(F) += Pp;\n  vcl_mat Pn = comfi::routines::pressure_n(xn, ctx);\n  ctx.v_NUx(F) += Pn;\n\n  // Magnetic pressure\n  const vcl_mat pmag = 0.5*(element_prod(ctx.v_Bx(xn), ctx.v_Bx(xn))\n                            + element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn))\n                            + element_prod(ctx.v_Bp(xn), ctx.v_Bp(xn)));\n  ctx.v_NVx(F) += pmag;\n  ctx.v_NVz(F) -= element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn));\n  ctx.v_NVx(F) -= element_prod(ctx.v_Bz(xn), ctx.v_Bx(xn));\n  ctx.v_NVp(F) -= element_prod(ctx.v_Bz(xn), ctx.v_Bp(xn));\n\n  // Energy flux\n  vcl_mat bdotv = element_prod(V_x, ctx.v_Bx(xn)) + element_prod(V_z, ctx.v_Bz(xn)) + element_prod(V_p, ctx.v_Bp(xn));\n  ctx.v_Ep(F) += element_prod(Pp+pmag, V_x) - element_prod(ctx.v_Bx(xn), bdotv);\n  ctx.v_En(F) += element_prod(Pn, U_x);\n\n  // Flux part of GLM\n  ctx.v_GLM(F) = ctx.c_h()*ctx.c_h()*ctx.v_Bx(xn);\n\n  return F;\n}\n\nvcl_mat comfi::routines::Fz(const vcl_mat &xn, const vcl_mat &xn_ij, comfi::types::Context &ctx)\n{\n  vcl_mat F = viennacl::zero_matrix<double>(xn.size1(), xn.size2());\n\n  const vcl_mat V_x = element_div(ctx.v_NVx(xn), ctx.v_Np(xn));\n  const vcl_mat U_x = element_div(ctx.v_NUx(xn), ctx.v_Nn(xn));\n  const vcl_mat V_z = element_div(ctx.v_NVz(xn), ctx.v_Np(xn));\n  const vcl_mat U_z = element_div(ctx.v_NUz(xn), ctx.v_Nn(xn));\n  const vcl_mat V_p = element_div(ctx.v_NVp(xn), ctx.v_Np(xn));\n  const vcl_mat U_p = element_div(ctx.v_NUp(xn), ctx.v_Nn(xn));\n\n  // Local speed flux -> quantity*Vz\n  ctx.v_Np(F) = element_prod(ctx.v_Np(xn), V_z);\n  ctx.v_Nn(F) = element_prod(ctx.v_Nn(xn), U_z);\n  ctx.v_NVx(F) = element_prod(ctx.v_NVx(xn), V_z);\n  ctx.v_NVz(F) = element_prod(ctx.v_NVz(xn), V_z);\n  ctx.v_NVp(F) = element_prod(ctx.v_NVp(xn), V_z);\n  ctx.v_NUx(F) =  element_prod(ctx.v_NUx(xn), U_z);\n  ctx.v_NUz(F) = element_prod(ctx.v_NUz(xn), U_z);\n  ctx.v_NUp(F) = element_prod(ctx.v_NUp(xn), U_z);\n  ctx.v_Ep(F) = element_prod(ctx.v_Ep(xn), V_z);\n  ctx.v_En(F) = element_prod(ctx.v_En(xn), U_z);\n\n  // Induction VB-BV\n  ctx.v_Bx(F) = element_prod(V_z, ctx.v_Bx(xn)) - element_prod(ctx.v_Bz(xn), V_x);\n  ctx.v_Bp(F) = element_prod(V_z, ctx.v_Bp(xn)) - element_prod(ctx.v_Bz(xn), V_p);\n\n  // General Lagrange Multiplier\n  ctx.v_Bz(F) = ctx.v_GLM(xn);\n\n  // Thermal pressure\n  vcl_mat Pp = comfi::routines::pressure_p(xn, ctx);\n  ctx.v_NVz(F) += Pp;\n  vcl_mat Pn = comfi::routines::pressure_n(xn, ctx);\n  ctx.v_NUz(F) += Pn;\n\n  // Magnetic pressure\n  const vcl_mat pmag = 0.5*(element_prod(ctx.v_Bx(xn), ctx.v_Bx(xn))\n                            +element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn))\n                            +element_prod(ctx.v_Bp(xn), ctx.v_Bp(xn)));\n  ctx.v_NVz(F) += pmag;\n  ctx.v_NVz(F) -= element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn));\n  ctx.v_NVx(F) -= element_prod(ctx.v_Bz(xn), ctx.v_Bx(xn));\n  ctx.v_NVp(F) -= element_prod(ctx.v_Bz(xn), ctx.v_Bp(xn));\n\n  // Energy flux\n  vcl_mat bdotv = element_prod(V_x, ctx.v_Bx(xn))\n                  + element_prod(V_z, ctx.v_Bz(xn))\n                  + element_prod(V_p, ctx.v_Bp(xn));\n  ctx.v_Ep(F) += element_prod(Pp+pmag, V_z) - element_prod(ctx.v_Bz(xn), bdotv);\n  ctx.v_En(F) += element_prod(Pn, U_z);\n\n  // Flux part of GLM\n  ctx.v_GLM(F) = ctx.c_h()*ctx.c_h()*ctx.v_Bz(xn);\n\n  return F;\n}\n\nvcl_mat comfi::routines::pressure_n(const vcl_mat &xn, comfi::types::Context &ctx) {\n  vcl_mat Pn = ctx.v_NUx(xn);\n  Pn = element_prod(Pn, ctx.v_NUx(xn));\n  Pn = Pn + element_prod(ctx.v_NUz(xn), ctx.v_NUz(xn));\n  Pn = Pn + element_prod(ctx.v_NUp(xn), ctx.v_NUp(xn));\n  Pn = 0.5*element_div(Pn, ctx.v_Nn(xn));\n  Pn  = element_fabs((ctx.gammamono-1.0)*(ctx.v_En(xn)-Pn));\n  return Pn;\n}\n\nvcl_mat comfi::routines::sound_speed_p(const vcl_mat &xn, comfi::types::Context &ctx) {\n  const vcl_mat Pp = comfi::routines::pressure_p(xn, ctx);\n  return element_sqrt(element_div(ctx.gammamono*Pp, ctx.v_Np(xn)));\n}\n\nvcl_mat comfi::routines::sound_speed_n(const vcl_mat &xn, comfi::types::Context &ctx) {\n  const vcl_mat Pn = comfi::routines::pressure_n(xn, ctx);\n  return element_sqrt(element_div(ctx.gammamono*Pn, ctx.v_Nn(xn)));\n}\n\nvcl_mat comfi::routines::pressure_p(const vcl_mat &xn, comfi::types::Context &ctx)\n{\n  using namespace viennacl::linalg;\n  // Calculate pressures by total energy\n  vcl_mat Pp = ctx.v_NVx(xn);\n  Pp = element_prod(Pp, ctx.v_NVx(xn));\n  Pp = Pp + element_prod(ctx.v_NVz(xn), ctx.v_NVz(xn));\n  Pp = Pp + element_prod(ctx.v_NVp(xn), ctx.v_NVp(xn));\n  Pp = 0.5*element_div(Pp, ctx.v_Np(xn));\n\n  Pp = Pp + 0.5*element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn));\n  Pp = Pp + 0.5*element_prod(ctx.v_Bx(xn), ctx.v_Bx(xn));\n  Pp = Pp + 0.5*element_prod(ctx.v_Bp(xn), ctx.v_Bp(xn));\n\n  Pp = element_fabs((ctx.gammamono-1.0)*(ctx.v_Ep(xn)-Pp));\n\n  return Pp;\n}\n\nvcl_mat comfi::routines::fast_speed_x(const vcl_mat &xn, comfi::types::Context &ctx) {\n  using namespace viennacl::linalg;\n  // Calculate pressures by total energy\n  vcl_mat k_e = element_prod(ctx.v_NVx(xn), ctx.v_NVx(xn));\n  k_e = k_e + element_prod(ctx.v_NVz(xn), ctx.v_NVz(xn));\n  k_e = k_e + element_prod(ctx.v_NVp(xn), ctx.v_NVp(xn));\n  k_e = 0.5*element_div(k_e, ctx.v_Np(xn));\n\n  vcl_mat b_e = 0.5*element_prod(ctx.v_Bx(xn), ctx.v_Bx(xn));\n  b_e = b_e + 0.5*element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn));\n  b_e = b_e + 0.5*element_prod(ctx.v_Bp(xn), ctx.v_Bp(xn));\n\n  const vcl_mat Ep = element_fabs(ctx.v_Ep(xn));\n  const vcl_mat Pp  = element_fabs((ctx.gammamono-1.0)*(Ep - k_e - b_e));\n\n  const vcl_mat cps2 = ctx.gammamono*(element_div(Pp, ctx.v_Np(xn)));\n  const vcl_mat cps = element_sqrt(cps2);\n  const vcl_mat ca2 = element_div(2.0*b_e, ctx.v_Np(xn));\n  const vcl_mat cax = element_div(ctx.v_Bx(xn), element_sqrt(ctx.v_Np(xn)));\n  const vcl_mat cpsca = element_prod(cps, cax);\n  const vcl_mat cpsca2 = element_prod(cpsca, cpsca);\n\n  const vcl_mat cp = 0.5*(element_sqrt(2.0*(cps2 + ca2 + element_sqrt(element_prod(cps2+ca2,cps2+ca2)-4.0*cpsca2))));\n\n  return cp;\n}\n\nvcl_mat comfi::routines::fast_speed_z(const vcl_mat &xn, comfi::types::Context &ctx) {\n  using namespace viennacl::linalg;\n  // Calculate pressures by total energy\n  vcl_mat k_e = element_prod(ctx.v_NVx(xn), ctx.v_NVx(xn));\n  k_e = k_e + element_prod(ctx.v_NVz(xn), ctx.v_NVz(xn));\n  k_e = k_e + element_prod(ctx.v_NVp(xn), ctx.v_NVp(xn));\n  k_e = 0.5*element_div(k_e, ctx.v_Np(xn));\n\n  vcl_mat b_e = 0.5*element_prod(ctx.v_Bx(xn), ctx.v_Bx(xn));\n  b_e = b_e + 0.5*element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn));\n  b_e = b_e + 0.5*element_prod(ctx.v_Bp(xn), ctx.v_Bp(xn));\n\n  const vcl_mat Ep = element_fabs(ctx.v_Ep(xn));\n  const vcl_mat Pp  = element_fabs((ctx.gammamono-1.0)*(Ep - k_e - b_e));\n\n  const vcl_mat cps2 = ctx.gammamono*(element_div(Pp, ctx.v_Np(xn)));\n  const vcl_mat cps = element_sqrt(cps2);\n  const vcl_mat ca2 = element_div(2.0*b_e, ctx.v_Np(xn));\n  const vcl_mat caz = element_div(ctx.v_Bz(xn), element_sqrt(ctx.v_Np(xn)));\n  const vcl_mat cpsca = element_prod(cps, caz);\n  const vcl_mat cpsca2 = element_prod(cpsca, cpsca);\n\n  const vcl_mat cp = 0.5*(element_sqrt(2.0*(cps2 + ca2 + element_sqrt(element_prod(cps2+ca2,cps2+ca2)-4.0*cpsca2))));\n\n  return cp;\n}\n\nvcl_vec comfi::routines::polyval(const arma::vec &p, const vcl_vec &x)\n{\n  vcl_vec b = viennacl::zero_vector<double>(x.size());\n\n  for (int i = 0; i < p.size(); i++)\n  {\n    const vcl_vec a = viennacl::scalar_vector<double>(x.size(), p(i));\n    b = a + element_prod(b, x);\n  }\n\n  return b;\n}\n\nvcl_mat comfi::routines::fluxl(const vcl_mat &r) {\n  static const vcl_mat ones = viennacl::scalar_matrix<double>(r.size1(), r.size2(), 1.0);\n  const vcl_mat r2 = element_prod(r, r);\n  // Ospre\n  return 1.5*element_div(r2+r, r2+r+ones);\n  // Van Albada\n  //return element_div(r2+r, r2+ones);\n  // Van Leer\n  //const vcl_mat absr = element_fabs(r);\n  //return element_div(r+absr, ones+absr);\n}\n\nvoid comfi::routines::bottombc_shock_tube(vcl_mat &Lxn, vcl_mat &Rxn, comfi::types::Context &ctx) {\n  uint ij = inds(0, 0, ctx);\n\n  Rxn(ij, ctx.n_n) = 0.125;\n  Rxn(ij, ctx.n_p) = 0.125;\n  Rxn(ij, ctx.E_p) = 0.1/(ctx.gammamono-1.0);\n  Rxn(ij, ctx.E_n) = 0.1/(ctx.gammamono-1.0);\n  Rxn(ij, ctx.Ux) = 0.0;\n  Rxn(ij, ctx.Uz) = 0.0;\n  Rxn(ij, ctx.Up) = 0.0;\n  Rxn(ij, ctx.Vx) = 0.0;\n  Rxn(ij, ctx.Vz) = 0.0;\n  Rxn(ij, ctx.Vp) = 0.0;\n\n  Lxn(ij, ctx.n_n) = 0.125;\n  Lxn(ij, ctx.n_p) = 0.125;\n  Lxn(ij, ctx.E_p) = 0.1/(ctx.gammamono-1.0);\n  Lxn(ij, ctx.E_n) = 0.1/(ctx.gammamono-1.0);\n  Lxn(ij, ctx.Ux) = 0.0;\n  Lxn(ij, ctx.Uz) = 0.0;\n  Lxn(ij, ctx.Up) = 0.0;\n  Lxn(ij, ctx.Vx) = 0.0;\n  Lxn(ij, ctx.Vz) = 0.0;\n  Lxn(ij, ctx.Vp) = 0.0;\n}\n\nvoid comfi::routines::topbc_shock_tube(vcl_mat &Lxn, vcl_mat &Rxn, comfi::types::Context &ctx) {\n  uint ij = inds(0, ctx.nz-1, ctx);\n\n  Rxn(ij, ctx.n_n) = 1.0;\n  Rxn(ij, ctx.n_p) = 1.0;\n  Rxn(ij, ctx.E_p) = 1.0/(ctx.gammamono-1.0);\n  Rxn(ij, ctx.E_n) = 1.0/(ctx.gammamono-1.0);\n  Rxn(ij, ctx.Ux) = 0.0;\n  Rxn(ij, ctx.Uz) = 0.0;\n  Rxn(ij, ctx.Up) = 0.0;\n  Rxn(ij, ctx.Vx) = 0.0;\n  Rxn(ij, ctx.Vz) = 0.0;\n  Rxn(ij, ctx.Vp) = 0.0;\n\n  Lxn(ij, ctx.n_n) = 1.0;\n  Lxn(ij, ctx.n_p) = 1.0;\n  Lxn(ij, ctx.E_p) = 1.0/(ctx.gammamono-1.0);\n  Lxn(ij, ctx.E_n) = 1.0/(ctx.gammamono-1.0);\n  Lxn(ij, ctx.Ux) = 0.0;\n  Lxn(ij, ctx.Uz) = 0.0;\n  Lxn(ij, ctx.Up) = 0.0;\n  Lxn(ij, ctx.Vx) = 0.0;\n  Lxn(ij, ctx.Vz) = 0.0;\n  Lxn(ij, ctx.Vp) = 0.0;\n}\n\n/*\nvim: tabstop=2\nvim: shiftwidth=2\nvim: smarttab\nvim: expandtab\n*/\n", "meta": {"hexsha": "da62b1ef751ce6aca93bf2ee93566548707d09ef", "size": 31714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/routines.cpp", "max_stars_repo_name": "qalshidi/comfi", "max_stars_repo_head_hexsha": "59835f0ab4f54dea0ecb44405f583c9c06ad21bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-17T22:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-17T22:10:35.000Z", "max_issues_repo_path": "src/routines.cpp", "max_issues_repo_name": "qalshidi/comfi", "max_issues_repo_head_hexsha": "59835f0ab4f54dea0ecb44405f583c9c06ad21bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/routines.cpp", "max_forks_repo_name": "qalshidi/comfi", "max_forks_repo_head_hexsha": "59835f0ab4f54dea0ecb44405f583c9c06ad21bb", "max_forks_repo_licenses": ["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.6676056338, "max_line_length": 118, "alphanum_fraction": 0.6110865864, "num_tokens": 11439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5044499133633091}}
{"text": "/**\n * @file AdaBoost_test.cpp\n * @author Udit Saxena\n *\n * Tests for AdaBoost class.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/adaboost/adaboost.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n#include \"serialization.hpp\"\n\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::adaboost;\nusing namespace mlpack::tree;\nusing namespace mlpack::perceptron;\n\nBOOST_AUTO_TEST_SUITE(AdaBoostTest);\n\n/**\n * This test case runs the AdaBoost.mh algorithm on the UCI Iris dataset.  It\n * checks whether the hamming loss breaches the upperbound, which is provided by\n * ztAccumulator.\n */\nBOOST_AUTO_TEST_CASE(HammingLossBoundIris)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"iris.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset iris.csv!\");\n\n  arma::Mat<size_t> labels;\n  if (!data::Load(\"iris_labels.txt\", labels))\n    BOOST_FAIL(\"Cannot load labels for iris iris_labels.txt\");\n\n  const size_t numClasses = max(labels.row(0)) + 1;\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptronIter iterations.\n  int perceptronIter = 400;\n\n  Perceptron<> p(inputData, labels.row(0), numClasses, perceptronIter);\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 100;\n  double tolerance = 1e-10;\n  AdaBoost<> a(tolerance);\n  double ztProduct = a.Train(inputData, labels.row(0), numClasses, p,\n      iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels;\n  a.Classify(inputData, predictedLabels);\n\n  size_t countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != predictedLabels(i))\n      countError++;\n  double hammingLoss = (double) countError / labels.n_cols;\n\n  // Check that ztProduct is finite.\n  BOOST_REQUIRE_EQUAL(std::isfinite(ztProduct), true);\n  BOOST_REQUIRE_LE(hammingLoss, ztProduct);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on the UCI Iris dataset.  It\n * checks if the error returned by running a single instance of the weak learner\n * is worse than running the boosted weak learner using adaboost.\n */\nBOOST_AUTO_TEST_CASE(WeakLearnerErrorIris)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"iris.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset iris.csv!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"iris_labels.txt\", labels))\n    BOOST_FAIL(\"Cannot load labels for iris iris_labels.txt\");\n\n  const size_t numClasses = max(labels.row(0)) + 1;\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptronIter iterations.\n  int perceptronIter = 400;\n\n  arma::Row<size_t> perceptronPrediction(labels.n_cols);\n  Perceptron<> p(inputData, labels.row(0), numClasses, perceptronIter);\n  p.Classify(inputData, perceptronPrediction);\n\n  size_t countWeakLearnerError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != perceptronPrediction(i))\n      countWeakLearnerError++;\n  double weakLearnerErrorRate = (double) countWeakLearnerError / labels.n_cols;\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 100;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), numClasses, p, iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels;\n  a.Classify(inputData, predictedLabels);\n\n  size_t countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != predictedLabels(i))\n      countError++;\n  double error = (double) countError / labels.n_cols;\n\n  BOOST_REQUIRE_LE(error, weakLearnerErrorRate);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on the UCI Vertebral Column\n * dataset.  It checks whether the hamming loss breaches the upperbound, which\n * is provided by ztAccumulator.\n */\nBOOST_AUTO_TEST_CASE(HammingLossBoundVertebralColumn)\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  const size_t numClasses = max(labels.row(0)) + 1;\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptronIter iterations.\n  size_t perceptronIter = 800;\n  Perceptron<> p(inputData, labels.row(0), numClasses, perceptronIter);\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<> a(tolerance);\n  double ztProduct = a.Train(inputData, labels.row(0), numClasses, p,\n      iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels;\n  a.Classify(inputData, predictedLabels);\n\n  size_t countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != predictedLabels(i))\n      countError++;\n  double hammingLoss = (double) countError / labels.n_cols;\n\n  // Check that ztProduct is finite.\n  BOOST_REQUIRE_EQUAL(std::isfinite(ztProduct), true);\n  BOOST_REQUIRE_LE(hammingLoss, ztProduct);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on the UCI Vertebral Column\n * dataset.  It checks if the error returned by running a single instance of the\n * weak learner is worse than running the boosted weak learner using adaboost.\n */\nBOOST_AUTO_TEST_CASE(WeakLearnerErrorVertebralColumn)\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  const size_t numClasses = max(labels.row(0)) + 1;\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptronIter iterations.\n  size_t perceptronIter = 800;\n\n  Row<size_t> perceptronPrediction(labels.n_cols);\n  Perceptron<> p(inputData, labels.row(0), numClasses, perceptronIter);\n  p.Classify(inputData, perceptronPrediction);\n\n  size_t countWeakLearnerError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != perceptronPrediction(i))\n      countWeakLearnerError++;\n  double weakLearnerErrorRate = (double) countWeakLearnerError / labels.n_cols;\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), numClasses, p, iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels;\n  a.Classify(inputData, predictedLabels);\n\n  size_t countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != predictedLabels(i))\n      countError++;\n  double error = (double) countError / labels.n_cols;\n\n  BOOST_REQUIRE_LE(error, weakLearnerErrorRate);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on non-linearly separable\n * dataset.  It checks whether the hamming loss breaches the upperbound, which\n * is provided by ztAccumulator.\n */\nBOOST_AUTO_TEST_CASE(HammingLossBoundNonLinearSepData)\n{\n  arma::mat inputData;\n  if (!data::Load(\"train_nonlinsep.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset train_nonlinsep.txt!\");\n\n  arma::Mat<size_t> labels;\n  if (!data::Load(\"train_labels_nonlinsep.txt\", labels))\n    BOOST_FAIL(\"Cannot load labels for train_labels_nonlinsep.txt\");\n\n  const size_t numClasses = max(labels.row(0)) + 1;\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptronIter iterations.\n  size_t perceptronIter = 800;\n  Perceptron<> p(inputData, labels.row(0), numClasses, perceptronIter);\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<> a(tolerance);\n  double ztProduct = a.Train(inputData, labels.row(0), numClasses, p,\n      iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels;\n  a.Classify(inputData, predictedLabels);\n\n  size_t countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != predictedLabels(i))\n      countError++;\n  double hammingLoss = (double) countError / labels.n_cols;\n\n  // Check that ztProduct is finite.\n  BOOST_REQUIRE_EQUAL(std::isfinite(ztProduct), true);\n  BOOST_REQUIRE_LE(hammingLoss, ztProduct);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on a non-linearly separable\n * dataset.  It checks if the error returned by running a single instance of the\n * weak learner is worse than running the boosted weak learner using AdaBoost.\n */\nBOOST_AUTO_TEST_CASE(WeakLearnerErrorNonLinearSepData)\n{\n  arma::mat inputData;\n  if (!data::Load(\"train_nonlinsep.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset train_nonlinsep.txt!\");\n\n  arma::Mat<size_t> labels;\n  if (!data::Load(\"train_labels_nonlinsep.txt\", labels))\n    BOOST_FAIL(\"Cannot load labels for train_labels_nonlinsep.txt\");\n\n  const size_t numClasses = max(labels.row(0)) + 1;\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptronIter iterations.\n  size_t perceptronIter = 800;\n\n  Row<size_t> perceptronPrediction(labels.n_cols);\n  Perceptron<> p(inputData, labels.row(0), numClasses, perceptronIter);\n  p.Classify(inputData, perceptronPrediction);\n\n  size_t countWeakLearnerError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != perceptronPrediction(i))\n      countWeakLearnerError++;\n  double weakLearnerErrorRate = (double) countWeakLearnerError / labels.n_cols;\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), numClasses, p, iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels;\n  a.Classify(inputData, predictedLabels);\n\n  size_t countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != predictedLabels(i))\n      countError++;\n  double error = (double) countError / labels.n_cols;\n\n  BOOST_REQUIRE_LE(error, weakLearnerErrorRate);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on the UCI Iris dataset.  It\n * checks whether the Hamming loss breaches the upper bound, which is provided\n * by ztAccumulator.  This uses decision stumps as the weak learner.\n */\nBOOST_AUTO_TEST_CASE(HammingLossIris_DS)\n{\n  arma::mat inputData;\n  if (!data::Load(\"iris.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset iris.csv!\");\n\n  arma::Mat<size_t> labels;\n  if (!data::Load(\"iris_labels.txt\", labels))\n    BOOST_FAIL(\"Cannot load labels for iris_labels.txt\");\n\n  // Define your own weak learner, decision stumps in this case.\n  const size_t numClasses = 3;\n  const size_t inpBucketSize = 6;\n  arma::Row<size_t> labelsvec = labels.row(0);\n  ID3DecisionStump ds(inputData, labelsvec, numClasses, inpBucketSize);\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<ID3DecisionStump> a(tolerance);\n  double ztProduct = a.Train(inputData, labelsvec, numClasses, ds,\n      iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels;\n  a.Classify(inputData, predictedLabels);\n\n  size_t countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != predictedLabels(i))\n      countError++;\n  double hammingLoss = (double) countError / labels.n_cols;\n\n  // Check that ztProduct is finite.\n  BOOST_REQUIRE_EQUAL(std::isfinite(ztProduct), true);\n  BOOST_REQUIRE_LE(hammingLoss, ztProduct);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on a non-linearly separable\n * dataset.  It checks if the error returned by running a single instance of the\n * weak learner is worse than running the boosted weak learner using adaboost.\n * This is for the weak learner: decision stumps.\n */\nBOOST_AUTO_TEST_CASE(WeakLearnerErrorIris_DS)\n{\n  arma::mat inputData;\n  if (!data::Load(\"iris.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset iris.csv!\");\n\n  arma::Mat<size_t> labels;\n  if (!data::Load(\"iris_labels.txt\", labels))\n    BOOST_FAIL(\"Cannot load labels for iris_labels.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, decision stumps in this case.\n  const size_t numClasses = 3;\n  const size_t inpBucketSize = 6;\n  arma::Row<size_t> labelsvec = labels.row(0);\n\n  arma::Row<size_t> dsPrediction(labels.n_cols);\n\n  ID3DecisionStump ds(inputData, labelsvec, numClasses, inpBucketSize);\n  ds.Classify(inputData, dsPrediction);\n\n  size_t countWeakLearnerError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != dsPrediction(i))\n      countWeakLearnerError++;\n  double weakLearnerErrorRate = (double) countWeakLearnerError / labels.n_cols;\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 50;\n  double tolerance = 1e-10;\n\n  AdaBoost<ID3DecisionStump> a(inputData, labelsvec, numClasses, ds,\n      iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels;\n  a.Classify(inputData, predictedLabels);\n\n  size_t countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != predictedLabels(i))\n      countError++;\n  double error = (double) countError / labels.n_cols;\n\n  BOOST_REQUIRE_LE(error, weakLearnerErrorRate);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on the UCI Vertebral Column\n * dataset.  It checks if the error returned by running a single instance of the\n * weak learner is worse than running the boosted weak learner using adaboost.\n * This is for the weak learner: decision stumps.\n */\nBOOST_AUTO_TEST_CASE(HammingLossBoundVertebralColumn_DS)\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  // Define your own weak learner, decision stumps in this case.\n  const size_t numClasses = 3;\n  const size_t inpBucketSize = 6;\n  arma::Row<size_t> labelsvec = labels.row(0);\n\n  ID3DecisionStump ds(inputData, labelsvec, numClasses, inpBucketSize);\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 50;\n  double tolerance = 1e-10;\n\n  AdaBoost<ID3DecisionStump> a(tolerance);\n  double ztProduct = a.Train(inputData, labelsvec, numClasses, ds,\n      iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels;\n  a.Classify(inputData, predictedLabels);\n\n  size_t countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != predictedLabels(i))\n      countError++;\n  double hammingLoss = (double) countError / labels.n_cols;\n\n  // Check that ztProduct is finite.\n  BOOST_REQUIRE_EQUAL(std::isfinite(ztProduct), true);\n  BOOST_REQUIRE_LE(hammingLoss, ztProduct);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on the UCI Vertebral Column\n * dataset.  It checks if the error returned by running a single instance of the\n * weak learner is worse than running the boosted weak learner using adaboost.\n * This is for the weak learner: decision stumps.\n */\nBOOST_AUTO_TEST_CASE(WeakLearnerErrorVertebralColumn_DS)\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  // Define your own weak learner, decision stumps in this case.\n  const size_t numClasses = 3;\n  const size_t inpBucketSize = 6;\n  arma::Row<size_t> dsPrediction(labels.n_cols);\n  arma::Row<size_t> labelsvec = labels.row(0);\n\n  ID3DecisionStump ds(inputData, labelsvec, numClasses, inpBucketSize);\n  ds.Classify(inputData, dsPrediction);\n\n  size_t countWeakLearnerError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != dsPrediction(i))\n      countWeakLearnerError++;\n\n  double weakLearnerErrorRate = (double) countWeakLearnerError / labels.n_cols;\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<ID3DecisionStump> a(inputData, labelsvec, numClasses, ds,\n      iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels;\n  a.Classify(inputData, predictedLabels);\n\n  size_t countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != predictedLabels(i))\n      countError++;\n  double error = (double) countError / labels.n_cols;\n\n  BOOST_REQUIRE_LE(error, weakLearnerErrorRate);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on non-linearly separable\n * dataset.  It checks whether the hamming loss breaches the upperbound, which\n * is provided by ztAccumulator.  This is for the weak learner: decision stumps.\n */\nBOOST_AUTO_TEST_CASE(HammingLossBoundNonLinearSepData_DS)\n{\n  arma::mat inputData;\n  if (!data::Load(\"train_nonlinsep.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset train_nonlinsep.txt!\");\n\n  arma::Mat<size_t> labels;\n  if (!data::Load(\"train_labels_nonlinsep.txt\", labels))\n    BOOST_FAIL(\"Cannot load labels for train_labels_nonlinsep.txt\");\n\n  // Define your own weak learner, decision stumps in this case.\n  const size_t numClasses = 2;\n  const size_t inpBucketSize = 6;\n  arma::Row<size_t> labelsvec = labels.row(0);\n\n  ID3DecisionStump ds(inputData, labelsvec, numClasses, inpBucketSize);\n\n  // Define parameters for Adaboost.\n  size_t iterations = 50;\n  double tolerance = 1e-10;\n\n  AdaBoost<ID3DecisionStump> a(tolerance);\n  double ztProduct = a.Train(inputData, labelsvec, numClasses, ds,\n      iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels;\n  a.Classify(inputData, predictedLabels);\n\n  size_t countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != predictedLabels(i))\n      countError++;\n  double hammingLoss = (double) countError / labels.n_cols;\n\n  // Check that ztProduct is finite.\n  BOOST_REQUIRE_EQUAL(std::isfinite(ztProduct), true);\n  BOOST_REQUIRE_LE(hammingLoss, ztProduct);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on a non-linearly separable\n * dataset.  It checks if the error returned by running a single instance of the\n * weak learner is worse than running the boosted weak learner using adaboost.\n * This for the weak learner: decision stumps.\n */\nBOOST_AUTO_TEST_CASE(WeakLearnerErrorNonLinearSepData_DS)\n{\n  arma::mat inputData;\n  if (!data::Load(\"train_nonlinsep.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset train_nonlinsep.txt!\");\n\n  arma::Mat<size_t> labels;\n  if (!data::Load(\"train_labels_nonlinsep.txt\", labels))\n    BOOST_FAIL(\"Cannot load labels for train_labels_nonlinsep.txt\");\n\n  // Define your own weak learner, decision stumps in this case.\n  const size_t numClasses = 2;\n  const size_t inpBucketSize = 3;\n  arma::Row<size_t> labelsvec = labels.row(0);\n\n  arma::Row<size_t> dsPrediction(labels.n_cols);\n\n  ID3DecisionStump ds(inputData, labelsvec, numClasses, inpBucketSize);\n  ds.Classify(inputData, dsPrediction);\n\n  size_t countWeakLearnerError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != dsPrediction(i))\n      countWeakLearnerError++;\n  double weakLearnerErrorRate = (double) countWeakLearnerError / labels.n_cols;\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 500;\n  double tolerance = 1e-23;\n\n  AdaBoost<ID3DecisionStump > a(inputData, labelsvec, numClasses, ds,\n      iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels;\n  a.Classify(inputData, predictedLabels);\n\n  size_t countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if (labels(i) != predictedLabels(i))\n      countError++;\n  double error = (double) countError / labels.n_cols;\n\n  BOOST_REQUIRE_LE(error, weakLearnerErrorRate);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on the UCI Vertebral Column\n * dataset.  It tests the Classify function and checks for a satisfactory error\n * rate.\n */\nBOOST_AUTO_TEST_CASE(ClassifyTest_VERTEBRALCOL)\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  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptronIter iterations.\n  size_t perceptronIter = 1000;\n\n  arma::mat testData;\n\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\n  if (!data::Load(\"vc2_test_labels.txt\", trueTestLabels))\n    BOOST_FAIL(\"Cannot load labels for vc2_test_labels.txt\");\n\n  const size_t numClasses = max(labels.row(0)) + 1;\n\n  Row<size_t> perceptronPrediction(labels.n_cols);\n  Perceptron<> p(inputData, labels.row(0), numClasses, perceptronIter);\n  p.Classify(inputData, perceptronPrediction);\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 100;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), numClasses, p, iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels1(testData.n_cols),\n                    predictedLabels2(testData.n_cols);\n  arma::mat probabilities;\n\n  a.Classify(testData, predictedLabels1);\n  a.Classify(testData, predictedLabels2, probabilities);\n\n  BOOST_REQUIRE_EQUAL(probabilities.n_cols, testData.n_cols);\n  BOOST_REQUIRE_EQUAL(probabilities.n_rows, numClasses);\n\n  for (size_t i = 0; i < predictedLabels1.n_cols; ++i)\n    BOOST_REQUIRE_EQUAL(predictedLabels1[i], predictedLabels2[i]);\n\n  arma::colvec pRow;\n  arma::uword maxIndex = 0;\n\n  for (size_t i = 0; i < predictedLabels1.n_cols; i++)\n  {\n    pRow = probabilities.unsafe_col(i);\n    pRow.max(maxIndex);\n    BOOST_REQUIRE_EQUAL(predictedLabels1(i), maxIndex);\n    BOOST_REQUIRE_CLOSE(arma::accu(probabilities.col(i)), 1, 1e-5);\n  }\n\n  size_t localError = 0;\n  for (size_t i = 0; i < trueTestLabels.n_cols; i++)\n    if (trueTestLabels(i) != predictedLabels1(i))\n      localError++;\n\n  double lError = (double) localError / trueTestLabels.n_cols;\n  BOOST_REQUIRE_LE(lError, 0.30);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on a non linearly separable\n * dataset.  It tests the Classify function and checks for a satisfactory error\n * rate.\n */\nBOOST_AUTO_TEST_CASE(ClassifyTest_NONLINSEP)\n{\n  arma::mat inputData;\n  if (!data::Load(\"train_nonlinsep.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset train_nonlinsep.txt!\");\n\n  arma::Mat<size_t> labels;\n  if (!data::Load(\"train_labels_nonlinsep.txt\", labels))\n    BOOST_FAIL(\"Cannot load labels for train_labels_nonlinsep.txt\");\n\n  // Define your own weak learner; in this test decision stumps are used.\n  const size_t numClasses = 2;\n  const size_t inpBucketSize = 3;\n  arma::Row<size_t> labelsvec = labels.row(0);\n\n  arma::mat testData;\n\n  if (!data::Load(\"test_nonlinsep.txt\", testData))\n    BOOST_FAIL(\"Cannot load test dataset test_nonlinsep.txt!\");\n\n  arma::Mat<size_t> trueTestLabels;\n\n  if (!data::Load(\"test_labels_nonlinsep.txt\", trueTestLabels))\n    BOOST_FAIL(\"Cannot load labels for test_labels_nonlinsep.txt\");\n\n  arma::Row<size_t> dsPrediction(labels.n_cols);\n\n  ID3DecisionStump ds(inputData, labelsvec, numClasses, inpBucketSize);\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<ID3DecisionStump > a(inputData, labelsvec, numClasses, ds,\n      iterations, tolerance);\n\n  arma::Row<size_t> predictedLabels1(testData.n_cols),\n                    predictedLabels2(testData.n_cols);\n  arma::mat probabilities;\n\n  a.Classify(testData, predictedLabels1);\n  a.Classify(testData, predictedLabels2, probabilities);\n\n  BOOST_REQUIRE_EQUAL(probabilities.n_cols, testData.n_cols);\n\n  for (size_t i = 0; i < predictedLabels1.n_cols; ++i)\n    BOOST_REQUIRE_EQUAL(predictedLabels1[i], predictedLabels2[i]);\n\n  arma::colvec pRow;\n  arma::uword maxIndex = 0;\n\n  for (size_t i = 0; i < predictedLabels1.n_cols; i++)\n  {\n    pRow = probabilities.unsafe_col(i);\n    pRow.max(maxIndex);\n    BOOST_REQUIRE_EQUAL(predictedLabels1(i), maxIndex);\n    BOOST_REQUIRE_CLOSE(arma::accu(probabilities.col(i)), 1, 1e-5);\n  }\n\n  size_t localError = 0;\n  for (size_t i = 0; i < trueTestLabels.n_cols; i++)\n    if (trueTestLabels(i) != predictedLabels1(i))\n      localError++;\n\n  double lError = (double) localError / trueTestLabels.n_cols;\n  BOOST_REQUIRE_LE(lError, 0.30);\n}\n\n/**\n * This test case runs the AdaBoost.mh algorithm on the UCI Iris Dataset.  It\n * trains it on two thirds of the Iris dataset (iris_train.csv), and tests on\n * the remaining third of the dataset (iris_test.csv).  It tests the Classify()\n * function and checks for a satisfactory error rate.\n */\nBOOST_AUTO_TEST_CASE(ClassifyTest_IRIS)\n{\n  arma::mat inputData;\n  if (!data::Load(\"iris_train.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset iris_train.csv!\");\n\n  arma::Mat<size_t> labels;\n  if (!data::Load(\"iris_train_labels.csv\", labels))\n    BOOST_FAIL(\"Cannot load labels for iris_train_labels.csv\");\n  const size_t numClasses = max(labels.row(0)) + 1;\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptronIter iterations.\n  size_t perceptronIter = 800;\n\n  Perceptron<> p(inputData, labels.row(0), numClasses, perceptronIter);\n\n  // Define parameters for AdaBoost.\n  size_t iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), numClasses, p, iterations, tolerance);\n\n  arma::mat testData;\n  if (!data::Load(\"iris_test.csv\", testData))\n    BOOST_FAIL(\"Cannot load test dataset iris_test.csv!\");\n\n  arma::Row<size_t> predictedLabels(testData.n_cols);\n  a.Classify(testData, predictedLabels);\n\n  arma::Mat<size_t> trueTestLabels;\n  if (!data::Load(\"iris_test_labels.csv\", trueTestLabels))\n    BOOST_FAIL(\"Cannot load test dataset iris_test_labels.csv!\");\n\n  arma::Row<size_t> predictedLabels1(testData.n_cols),\n                    predictedLabels2(testData.n_cols);\n  arma::mat probabilities;\n\n  a.Classify(testData, predictedLabels1);\n  a.Classify(testData, predictedLabels2, probabilities);\n\n  BOOST_REQUIRE_EQUAL(probabilities.n_cols, testData.n_cols);\n\n  for (size_t i = 0; i < predictedLabels1.n_cols; ++i)\n    BOOST_REQUIRE_EQUAL(predictedLabels1[i], predictedLabels2[i]);\n\n  arma::colvec pRow;\n  arma::uword maxIndex = 0;\n\n  for (size_t i = 0; i < predictedLabels1.n_cols; i++)\n  {\n    pRow = probabilities.unsafe_col(i);\n    pRow.max(maxIndex);\n    BOOST_REQUIRE_EQUAL(predictedLabels1(i), maxIndex);\n    BOOST_REQUIRE_CLOSE(arma::accu(probabilities.col(i)), 1, 1e-5);\n  }\n\n  size_t localError = 0;\n  for (size_t i = 0; i < trueTestLabels.n_cols; i++)\n    if (trueTestLabels(i) != predictedLabels1(i))\n      localError++;\n  double lError = (double) localError / labels.n_cols;\n  BOOST_REQUIRE_LE(lError, 0.30);\n}\n\n/**\n * Ensure that the Train() function works like it is supposed to, by building\n * AdaBoost on one dataset and then re-training on another dataset.\n */\nBOOST_AUTO_TEST_CASE(TrainTest)\n{\n  // First train on the iris dataset.\n  arma::mat inputData;\n  if (!data::Load(\"iris_train.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset iris_train.csv!\");\n\n  arma::Mat<size_t> labels;\n  if (!data::Load(\"iris_train_labels.csv\", labels))\n    BOOST_FAIL(\"Cannot load labels for iris_train_labels.csv\");\n\n  const size_t numClasses = max(labels.row(0)) + 1;\n\n  size_t perceptronIter = 800;\n  Perceptron<> p(inputData, labels.row(0), numClasses, perceptronIter);\n\n  // Now train AdaBoost.\n  size_t iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), numClasses, p, iterations, tolerance);\n\n  // Now load another dataset...\n  if (!data::Load(\"vc2.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset vc2.csv!\");\n  if (!data::Load(\"vc2_labels.txt\", labels))\n    BOOST_FAIL(\"Cannot load labels for vc2_labels.txt\");\n\n  const size_t newNumClasses = max(labels.row(0)) + 1;\n\n  Perceptron<> p2(inputData, labels.row(0), newNumClasses, perceptronIter);\n\n  a.Train(inputData, labels.row(0), newNumClasses, p2, iterations, tolerance);\n\n  // Load test set to see if it trained on vc2 correctly.\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  // Define parameters for AdaBoost.\n  arma::Row<size_t> predictedLabels(testData.n_cols);\n  a.Classify(testData, predictedLabels);\n\n  int localError = 0;\n  for (size_t i = 0; i < trueTestLabels.n_cols; i++)\n    if (trueTestLabels(i) != predictedLabels(i))\n      localError++;\n\n  double lError = (double) localError / trueTestLabels.n_cols;\n\n  BOOST_REQUIRE_LE(lError, 0.30);\n}\n\nBOOST_AUTO_TEST_CASE(PerceptronSerializationTest)\n{\n  // Build an AdaBoost object.\n  mat data = randu<mat>(10, 500);\n  Row<size_t> labels(500);\n  for (size_t i = 0; i < 250; ++i)\n    labels[i] = 0;\n  for (size_t i = 250; i < 500; ++i)\n    labels[i] = 1;\n\n  Perceptron<> p(data, labels, 2, 800);\n  AdaBoost<> ab(data, labels, 2, p, 50, 1e-10);\n\n  // Now create another dataset to train with.\n  mat otherData = randu<mat>(5, 200);\n  Row<size_t> otherLabels(200);\n  for (size_t i = 0; i < 100; ++i)\n    otherLabels[i] = 1;\n  for (size_t i = 100; i < 150; ++i)\n    otherLabels[i] = 0;\n  for (size_t i = 150; i < 200; ++i)\n    otherLabels[i] = 2;\n\n  Perceptron<> p2(otherData, otherLabels, 3, 500);\n  AdaBoost<> abText(otherData, otherLabels, 3, p2, 50, 1e-10);\n\n  AdaBoost<> abXml, abBinary;\n\n  SerializeObjectAll(ab, abXml, abText, abBinary);\n\n  // Now check that the objects are the same.\n  BOOST_REQUIRE_CLOSE(ab.Tolerance(), abXml.Tolerance(), 1e-5);\n  BOOST_REQUIRE_CLOSE(ab.Tolerance(), abText.Tolerance(), 1e-5);\n  BOOST_REQUIRE_CLOSE(ab.Tolerance(), abBinary.Tolerance(), 1e-5);\n\n  BOOST_REQUIRE_EQUAL(ab.WeakLearners(), abXml.WeakLearners());\n  BOOST_REQUIRE_EQUAL(ab.WeakLearners(), abText.WeakLearners());\n  BOOST_REQUIRE_EQUAL(ab.WeakLearners(), abBinary.WeakLearners());\n\n  for (size_t i = 0; i < ab.WeakLearners(); ++i)\n  {\n    CheckMatrices(ab.WeakLearner(i).Weights(),\n                  abXml.WeakLearner(i).Weights(),\n                  abText.WeakLearner(i).Weights(),\n                  abBinary.WeakLearner(i).Weights());\n\n    CheckMatrices(ab.WeakLearner(i).Biases(),\n                  abXml.WeakLearner(i).Biases(),\n                  abText.WeakLearner(i).Biases(),\n                  abBinary.WeakLearner(i).Biases());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(ID3DecisionStumpSerializationTest)\n{\n  // Build an AdaBoost object.\n  mat data = randu<mat>(10, 500);\n  Row<size_t> labels(500);\n  for (size_t i = 0; i < 250; ++i)\n    labels[i] = 0;\n  for (size_t i = 250; i < 500; ++i)\n    labels[i] = 1;\n\n  ID3DecisionStump p(data, labels, 2, 800);\n  AdaBoost<ID3DecisionStump> ab(data, labels, 2, p, 50, 1e-10);\n\n  // Now create another dataset to train with.\n  mat otherData = randu<mat>(5, 200);\n  Row<size_t> otherLabels(200);\n  for (size_t i = 0; i < 100; ++i)\n    otherLabels[i] = 1;\n  for (size_t i = 100; i < 150; ++i)\n    otherLabels[i] = 0;\n  for (size_t i = 150; i < 200; ++i)\n    otherLabels[i] = 2;\n\n  ID3DecisionStump p2(otherData, otherLabels, 3, 500);\n  AdaBoost<ID3DecisionStump> abText(otherData, otherLabels, 3, p2, 50, 1e-10);\n\n  AdaBoost<ID3DecisionStump> abXml, abBinary;\n\n  SerializeObjectAll(ab, abXml, abText, abBinary);\n\n  // Now check that the objects are the same.\n  BOOST_REQUIRE_CLOSE(ab.Tolerance(), abXml.Tolerance(), 1e-5);\n  BOOST_REQUIRE_CLOSE(ab.Tolerance(), abText.Tolerance(), 1e-5);\n  BOOST_REQUIRE_CLOSE(ab.Tolerance(), abBinary.Tolerance(), 1e-5);\n\n  BOOST_REQUIRE_EQUAL(ab.WeakLearners(), abXml.WeakLearners());\n  BOOST_REQUIRE_EQUAL(ab.WeakLearners(), abText.WeakLearners());\n  BOOST_REQUIRE_EQUAL(ab.WeakLearners(), abBinary.WeakLearners());\n\n  for (size_t i = 0; i < ab.WeakLearners(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(ab.WeakLearner(i).SplitDimension(),\n                        abXml.WeakLearner(i).SplitDimension());\n    BOOST_REQUIRE_EQUAL(ab.WeakLearner(i).SplitDimension(),\n                        abText.WeakLearner(i).SplitDimension());\n    BOOST_REQUIRE_EQUAL(ab.WeakLearner(i).SplitDimension(),\n                        abBinary.WeakLearner(i).SplitDimension());\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "86d74034c487dbd6b75938e51284a1889991948d", "size": 32101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/adaboost_test.cpp", "max_stars_repo_name": "mhmohona/mlpack", "max_stars_repo_head_hexsha": "e2ba6cf75bcacb47d6f3ca9fb31d5cb1e48d095a", "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": "2020-05-21T11:19:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T11:19:48.000Z", "max_issues_repo_path": "src/mlpack/tests/adaboost_test.cpp", "max_issues_repo_name": "mhmohona/mlpack", "max_issues_repo_head_hexsha": "e2ba6cf75bcacb47d6f3ca9fb31d5cb1e48d095a", "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/adaboost_test.cpp", "max_forks_repo_name": "mhmohona/mlpack", "max_forks_repo_head_hexsha": "e2ba6cf75bcacb47d6f3ca9fb31d5cb1e48d095a", "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": 33.1621900826, "max_line_length": 80, "alphanum_fraction": 0.7135914769, "num_tokens": 8838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.5044499078078013}}
{"text": "#include \"WLS.h\"\n#include <stdio.h> \n#include <stdlib.h>\n#include <Eigen/Sparse>\n\nvoid WeightedLeastSquare(cv::Mat& resImg, const cv::Mat& img_guide, const cv::Mat& img_color,\n\tfloat alpha, float lamda)\n{\n\n\tfloat epsilon = 0.0001f;\n\n\tcv::Mat grayImgF = cv::Mat::zeros(img_guide.size(), CV_32FC1);\n\tcv::cvtColor(img_guide, grayImgF, CV_BGR2GRAY);\n\n\tcv::Mat gradWeightX = cv::Mat::zeros(img_guide.size(), CV_32FC1);\n\tcv::Mat gradWeightY = cv::Mat::zeros(img_guide.size(), CV_32FC1);\n\n#pragma omp parallel for\n\tfor (int y = 0; y < img_guide.rows - 1; ++y)\n\t{\n\t\tfor (int x = 0; x < img_guide.cols - 1; ++x)\n\t\t{\n\t\t\tif (x + 1 < img_guide.cols)\n\t\t\t{\n\t\t\t\tfloat gx = grayImgF.at<float>(y, x + 1) - grayImgF.at<float>(y, x);\n\t\t\t\tgradWeightX.at<float>(y, x) = lamda / (pow(abs(gx), alpha) + epsilon);\n\t\t\t}\n\t\t\tif (y + 1 < img_guide.rows)\n\t\t\t{\n\t\t\t\tfloat gy = grayImgF.at<float>(y + 1, x) - grayImgF.at<float>(y, x);\n\t\t\t\tgradWeightY.at<float>(y, x) = lamda / (pow(abs(gy), alpha) + epsilon);\n\t\t\t}\n\t\t}\n\t}\n\t//prepare\n\tint width = img_color.cols;\n\tint height = img_color.rows;\n\tint size = width * height;\n\tint n = width * height;\n\n\t//matrix\t\n\tEigen::SparseMatrix<float> A(n,n);\n\tEigen::VectorXi nnzVec = Eigen::VectorXi::Constant(n, 4 + 1);\n\tEigen::VectorXf bs[3], xs[3];\n\tA.reserve(nnzVec);\n\tbs[0].resize(n);\n\tbs[1].resize(n);\n\tbs[2].resize(n);\n\n\txs[0].resize(n);\n\txs[1].resize(n);\n\txs[2].resize(n);\n\n\n\tfor (int y = 0; y < height; y++)\n\t{\n\t\tfor (int x = 0; x < width; x++)\n\t\t{\n\t\t\tfloat a[5];\n\t\t\ta[0] = a[1] = a[2] = a[3] = a[4] = 0.0f;\n\n\t\t\tint ii = y * width + x;\n\t\t\tif (y - 1 >= 0) // top\n\t\t\t{\n\t\t\t\tconst float gyw = gradWeightY.at<float>(y - 1, x);\n\t\t\t\ta[2] += 1.0f * gyw;\n\t\t\t\ta[0] -= 1.0f * gyw;\n\t\t\t\tA.insert(ii, ii - width) = a[0];\n\t\t\t}\n\t\t\tif (x - 1 >= 0) // left\n\t\t\t{\n\t\t\t\tconst float gxw = gradWeightX.at<float>(y, x - 1);\n\t\t\t\ta[2] += 1.0f * gxw;\n\t\t\t\ta[1] -= 1.0f * gxw;\n\t\t\t\tA.insert(ii, ii - 1) = a[1];\n\t\t\t}\n\t\t\tif (x + 1 < width) // right\n\t\t\t{\n\t\t\t\tconst float gxw = gradWeightX.at<float>(y, x);\n\t\t\t\ta[2] += 1.0f * gxw;\n\t\t\t\ta[3] -= 1.0f * gxw;\n\t\t\t\tA.insert(ii, ii + 1) = a[3];\n\t\t\t}\n\t\t\tif (y + 1 < height) // bottom\n\t\t\t{\n\t\t\t\tconst float gyw = gradWeightY.at<float>(y, x);\n\t\t\t\ta[2] += 1.0f * gyw;\n\t\t\t\ta[4] -= 1.0f * gyw;\n\t\t\t\tA.insert(ii, ii + width) = a[4];\n\t\t\t}\n\n\t\t\t// data term\n\t\t\ta[2] += 1.f;\n\t\t\tA.insert(ii, ii) = a[2];\n\n\t\t\tconst cv::Vec3f& col = img_color.at<cv::Vec3f>(y, x);\n\t\t\txs[0][ii] = 0.0f;\n\t\t\txs[1][ii] = 0.0f;\n\t\t\txs[2][ii] = 0.0f;\n\t\t\tbs[0][ii] = (float)col[0];\t\t\t\n\t\t\tbs[1][ii] = (float)col[1];\n\t\t\tbs[2][ii] = (float)col[2];\n\t\t}\n\t}\n\n#pragma omp parallel for\n\tfor (int ch = 0; ch < 3; ++ch)\n\t{\n\t\tEigen::SimplicialLLT<Eigen::SparseMatrix<float> > solver;\n\t\tsolver.compute(A);\n\t\txs[ch] = solver.solve(bs[ch]);\n\t}\n\n\n\t//paste\t\n\tresImg = cv::Mat(height, width, CV_32FC3);\n\n#pragma omp parallel for\n\tfor (int y = 0; y < height; y++)\n\t{\n\t\tfor (int x = 0; x < width; x++)\n\t\t{\n\t\t\tresImg.at<cv::Vec3f>(y, x) = cv::Vec3f(\n\t\t\t\txs[0][y * width + x],\n\t\t\t\txs[1][y * width + x],\n\t\t\t\txs[2][y * width + x]);\n\n\t\t}\n\t}\n\n}\n", "meta": {"hexsha": "6ecda35d30a78f53ba5541e169eceb4333fabe66", "size": 2999, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "windows/deep_image_analogy/source/WLS.cpp", "max_stars_repo_name": "alonsat/Deep-Image-Analogy-for-videos", "max_stars_repo_head_hexsha": "0334962c02d48c86aa44215820d7e229a6bcd712", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1439.0, "max_stars_repo_stars_event_min_datetime": "2017-05-22T10:33:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T07:30:07.000Z", "max_issues_repo_path": "windows/deep_image_analogy/source/WLS.cpp", "max_issues_repo_name": "alonsat/Deep-Image-Analogy-for-videos", "max_issues_repo_head_hexsha": "0334962c02d48c86aa44215820d7e229a6bcd712", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45.0, "max_issues_repo_issues_event_min_datetime": "2017-05-24T07:57:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:37:29.000Z", "max_forks_repo_path": "windows/deep_image_analogy/source/WLS.cpp", "max_forks_repo_name": "alonsat/Deep-Image-Analogy-for-videos", "max_forks_repo_head_hexsha": "0334962c02d48c86aa44215820d7e229a6bcd712", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 282.0, "max_forks_repo_forks_event_min_datetime": "2017-05-22T12:34:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T00:44:52.000Z", "avg_line_length": 22.7196969697, "max_line_length": 93, "alphanum_fraction": 0.5398466155, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.5044499022522931}}
{"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 <vector>\n#include <benchmark/benchmark.h>\n#include <boost/math/special_functions/logsumexp.hpp>\n#include <boost/math/tools/random_vector.hpp>\n\nusing boost::math::logsumexp;\nusing boost::math::generate_random_vector;\n\ntemplate <typename Real>\nvoid logsumexp_performance(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<Real> test_set = generate_random_vector<Real>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(logsumexp(test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK_TEMPLATE(logsumexp_performance, float)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity()->UseRealTime();\nBENCHMARK_TEMPLATE(logsumexp_performance, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity()->UseRealTime();\nBENCHMARK_TEMPLATE(logsumexp_performance, long double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity()->UseRealTime();\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "8f146a6baded3606ecf981d6a0093b49d85f7dd5", "size": 1221, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reporting/performance/logsumexp_performance.cpp", "max_stars_repo_name": "grlee77/math", "max_stars_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "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": "reporting/performance/logsumexp_performance.cpp", "max_issues_repo_name": "grlee77/math", "max_issues_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "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": "reporting/performance/logsumexp_performance.cpp", "max_forks_repo_name": "grlee77/math", "max_forks_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "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": 37.0, "max_line_length": 128, "alphanum_fraction": 0.7321867322, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6187804267137441, "lm_q1q2_score": 0.5044499020766305}}
{"text": "#ifndef BOOST_GIL_IMAGE_PROCESSING_HESSIAN_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_HESSIAN_HPP\n\n#include <boost/gil/extension/numeric/kernel.hpp>\n#include <boost/gil/image_view.hpp>\n#include <boost/gil/typedefs.hpp>\n#include <stdexcept>\n\nnamespace boost {\nnamespace gil {\n\n/// \\brief Computes Hessian response\n///\n/// Computes Hessian response based on computed entries of Hessian matrix, e.g.\n/// second order derivates in x and y, and derivatives in both x, y. d stands\n/// for derivative, and x or y stand for derivative direction. For example, ddxx\n/// means taking two derivatives (gradients) in horizontal direction. Weights\n/// change perception of surroinding pixels. Additional filtering is strongly\n/// advised.\ntemplate <typename GradientView, typename T, typename Allocator,\n          typename OutputView>\ninline void compute_hessian_responses(\n    GradientView ddxx, GradientView dxdy, GradientView ddyy,\n    const detail::kernel_2d<T, Allocator> &weights, OutputView dst) {\n  if (ddxx.dimensions() != ddyy.dimensions() ||\n      ddyy.dimensions() != dxdy.dimensions() ||\n      dxdy.dimensions() != dst.dimensions() ||\n      weights.center_x() != weights.center_y()) {\n    throw std::invalid_argument(\"dimensions of views are not the same\"\n                                \" or weights don't have equal width and height\"\n                                \" or weights' dimensions are not odd\");\n  }\n  // Use pixel type of output, as values will be written to output\n  using pixel_t =\n      typename std::remove_reference<decltype(std::declval<OutputView>()(\n          0, 0))>::type;\n\n  using channel_t =\n      typename std::remove_reference<decltype(std::declval<pixel_t>().at(\n          std::integral_constant<int, 0>{}))>::type;\n\n  auto center = weights.center_y();\n  for (auto y = center; y < dst.height() - center; ++y) {\n    for (auto x = center; x < dst.width() - center; ++x) {\n      auto ddxx_i = channel_t();\n      auto ddyy_i = channel_t();\n      auto dxdy_i = channel_t();\n      for (typename OutputView::coord_t w_y = 0; w_y < weights.size(); ++w_y) {\n        for (typename OutputView::coord_t w_x = 0; w_x < weights.size();\n             ++w_x) {\n          ddxx_i += ddxx(x + w_x - center, y + w_y - center)\n                        .at(std::integral_constant<int, 0>{}) *\n                    weights.at(w_x, w_y);\n          ddyy_i += ddyy(x + w_x - center, y + w_y - center)\n                        .at(std::integral_constant<int, 0>{}) *\n                    weights.at(w_x, w_y);\n          dxdy_i += dxdy(x + w_x - center, y + w_y - center)\n                        .at(std::integral_constant<int, 0>{}) *\n                    weights.at(w_x, w_y);\n        }\n      }\n      auto determinant = ddxx_i * ddyy_i - dxdy_i * dxdy_i;\n      dst(x, y).at(std::integral_constant<int, 0>{}) = determinant;\n    }\n  }\n}\n\n} // namespace gil\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "6e9b9eb3d47c0d45ebe3dc9177eb61c6c202a4c2", "size": 2875, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/hessian.hpp", "max_stars_repo_name": "sdebionne/gil-reformated", "max_stars_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/gil/image_processing/hessian.hpp", "max_issues_repo_name": "sdebionne/gil-reformated", "max_issues_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/gil/image_processing/hessian.hpp", "max_forks_repo_name": "sdebionne/gil-reformated", "max_forks_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "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.9305555556, "max_line_length": 80, "alphanum_fraction": 0.6212173913, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5044258027155208}}
{"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_DIV_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DIV_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-oerator\n    Function object extending divides\n\n    Calculate the quotient of the two parameters of the same type with or without options.\n\n    @par Semantic\n\n    For any value @c a and @c b of type @c T,\n\n    @code\n    T r = div({option, }a, b);\n    @endcode\n\n    returns the quotient of @c a by @c b respecting to the options specified.\n\n    By default, this functions is equivalent to divides(a, b).\n    Options may be ceil, floor, fix, round, nearbyint (in the namespace booost::simd)\n    and provide the same result as the calls divceil(a, b), divfloor(a, b),\n    divfix(a, b), divround(a, b), divnearbyint(a, b).\n\n    @return The quotient of the two parameters.\n  **/\n  T div(T const& a, T const& b);\n\n  //@overload\n  T div(Option const& o, T const& a, T const& b);\n\n} }\n#endif\n\n#include <boost/simd/function/scalar/div.hpp>\n#include <boost/simd/function/simd/div.hpp>\n\n\n#endif\n", "meta": {"hexsha": "fed2463692d98688da9c93276ed769aa720c347c", "size": 1452, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/div.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/div.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/div.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": 27.3962264151, "max_line_length": 100, "alphanum_fraction": 0.5991735537, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5044257856306394}}
{"text": "#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#include <iostream>\n#include <boost/test/unit_test.hpp>\n\n#include \"Map/ProbabilityValues.h\"\n\nnamespace VISFS {\nnamespace Map {\n\nBOOST_AUTO_TEST_CASE(OddsConversions) {\n    BOOST_CHECK_CLOSE(probabilityFromOdds(odds(kMinProbability)), kMinProbability, 1e-6);\n    BOOST_CHECK_CLOSE(probabilityFromOdds(odds(kMaxProbability)), kMaxProbability, 1e-6);\n    BOOST_CHECK_CLOSE(probabilityFromOdds(odds(0.5)), 0.5, 1e-6);\n}\n\nBOOST_AUTO_TEST_CASE(OddsConversionsCorrespondenceCost) {\n    BOOST_CHECK_CLOSE(probabilityToCorrespondceCost(probabilityFromOdds(odds(correspondenceCostToProbability(kMinCorrespondenceCost)))), kMinCorrespondenceCost, 1e-6);\n    BOOST_CHECK_CLOSE(probabilityToCorrespondceCost(probabilityFromOdds(odds(correspondenceCostToProbability(kMaxCorrespondenceCost)))), kMaxCorrespondenceCost, 1e-6);\n    BOOST_CHECK_CLOSE(probabilityToCorrespondceCost(probabilityFromOdds(odds(correspondenceCostToProbability(0.5)))), 0.5, 1e-6);\n}\n\nBOOST_AUTO_TEST_CASE(ProbabilityValueToCorrespondenceCostValueConversions) {\n    for (uint16_t i = 0; i < 32768; ++i) {\n        BOOST_CHECK_EQUAL(probabilityValueToCorrespondenceCostValue(correspondenceCostValueToProbabilityValue(i)), i);\n        BOOST_CHECK_EQUAL(correspondenceCostValueToProbabilityValue(probabilityValueToCorrespondenceCostValue(i)), i);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(ProbabilityValueToCorrespondenceCostValueConversionsWithUpdateMarker) {\n    for (uint16_t i = 1; i < 32768; ++i) {\n        BOOST_CHECK_EQUAL(probabilityValueToCorrespondenceCostValue(correspondenceCostValueToProbabilityValue(i + kUpdateMarker)), i + kUpdateMarker);\n        BOOST_CHECK_EQUAL(correspondenceCostValueToProbabilityValue(probabilityValueToCorrespondenceCostValue(i + kUpdateMarker)), i + kUpdateMarker);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(ConversionLookUpTable) {\n    BOOST_CHECK_CLOSE(valueToProbability(0), 1.0 - valueToCorrespondenceCost(0), 1e-6);\n    for (uint16_t i = 1; i < 32768; ++i) {\n        BOOST_CHECK_CLOSE(valueToProbability(i), valueToCorrespondenceCost(i), 1e-6);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(CellUpdate) {\n    std::vector<uint16_t> probabilityTable = computeLookupTableToApplyOdds(odds(0.9));\n    std::vector<uint16_t> correspondenceTable = computeLookupTableToApplyCorrespondenceCostOdds(odds(0.9));\n    uint16_t cellPgPreUpdate = 0;\n    uint16_t cellCgPreUpdate = 0;\n    uint16_t cellPgPoseUpdate = probabilityTable[cellPgPreUpdate];\n    uint16_t cellCgPoseUpdate = correspondenceTable[cellCgPreUpdate];\n    double pPost = valueToProbability(cellPgPoseUpdate);\n    double cPost = valueToCorrespondenceCost(cellCgPoseUpdate);\n    BOOST_CHECK_CLOSE(pPost, 1.0 - cPost, 1e-6);\n    int numEvaluations = 5000;\n    for (int iProbability = 0; iProbability < numEvaluations; ++iProbability) {\n        double p = (static_cast<double>(iProbability) / static_cast<double>(numEvaluations)) * (kMaxProbability - kMinProbability) + kMinProbability;\n        cellPgPreUpdate = probabilityToValue(p);\n        cellCgPreUpdate = correspondenceCostToValue(probabilityToCorrespondceCost(p));\n        double pValue = (uClamp(p, kMinProbability, kMaxProbability) - kMinProbability) * (32766.0 / (kMaxProbability - kMinProbability));\n        double cValue = (uClamp(probabilityToCorrespondceCost(p), kMinProbability, kMaxProbability) - kMinProbability)* (32766.0 / (kMaxProbability - kMinProbability));\n        // BOOST_CHECK_CLOSE(cellPgPreUpdate, static_cast<uint16_t>(32768) - cellCgPreUpdate, 1);\n        BOOST_CHECK_EQUAL(static_cast<int>(cellPgPreUpdate), 32768 - static_cast<int>(cellCgPreUpdate));\n        cellPgPoseUpdate = probabilityTable[cellPgPreUpdate];\n        cellCgPoseUpdate = correspondenceTable[cellCgPreUpdate];\n        pPost = valueToProbability(cellPgPoseUpdate);\n        cPost = valueToCorrespondenceCost(cellCgPoseUpdate);\n        BOOST_CHECK_CLOSE(pPost, 1.0 - cPost, 5e-3);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(MultipleCellUpdate) {\n    std::vector<uint16_t> probabilityTable = computeLookupTableToApplyOdds(odds(0.55));\n    std::vector<uint16_t> correspondenceTable = computeLookupTableToApplyCorrespondenceCostOdds(odds(0.55));\n    uint16_t cellPgPostUpdate = probabilityTable[0];\n    uint16_t cellCgPostUpdate = correspondenceTable[0];\n    double pPost = valueToProbability(cellPgPostUpdate);\n    double cPost = valueToCorrespondenceCost(cellCgPostUpdate);\n    BOOST_CHECK_CLOSE(pPost, 1.0 - cPost, 1e-6);\n    int numEvaluations = 5000;\n    for (int iProbability = 0; iProbability < numEvaluations; ++ iProbability) {\n        double p = (static_cast<double>(iProbability) / static_cast<double>(numEvaluations)) * (kMaxProbability - kMinProbability) + kMinProbability;\n        cellPgPostUpdate = probabilityToValue(p) + kUpdateMarker;\n        cellCgPostUpdate = correspondenceCostToValue(probabilityToCorrespondceCost(p)) + kUpdateMarker;\n        for (int iUpdate = 0; iUpdate < 20; ++ iUpdate) {\n            cellPgPostUpdate = probabilityTable[cellPgPostUpdate - kUpdateMarker];\n            cellCgPostUpdate = correspondenceTable[cellCgPostUpdate - kUpdateMarker];\n        }\n        pPost = valueToProbability(cellPgPostUpdate);\n        cPost = valueToCorrespondenceCost(cellCgPostUpdate);\n        BOOST_CHECK_CLOSE(pPost, 1.0 - cPost, 5e-5);\n    }\n\n}\n\nBOOST_AUTO_TEST_CASE(EqualityLookupTableToApplyOdds) {\n    std::vector<uint16_t> probabilityTable = computeLookupTableToApplyOdds(0.3);\n    std::vector<uint16_t> correspondenceTable = computeLookupTableToApplyCorrespondenceCostOdds(0.3);\n\n    for (int i = 0; i < 32768; ++i) {\n        BOOST_CHECK_EQUAL(probabilityTable[i], correspondenceCostValueToProbabilityValue(correspondenceTable[probabilityValueToCorrespondenceCostValue(i)]));\n        BOOST_CHECK_EQUAL(probabilityValueToCorrespondenceCostValue(probabilityTable[correspondenceCostValueToProbabilityValue(i)]), correspondenceTable[i]);\n    }\n}\n\n\n}\n}", "meta": {"hexsha": "8cabbf0aa960079d3bf5ee620c5bd3b44b55b0cb", "size": 5872, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Map/2d/UT4ProbabilityValues/UT4ProbabilityValues.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": "tests/Map/2d/UT4ProbabilityValues/UT4ProbabilityValues.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": "tests/Map/2d/UT4ProbabilityValues/UT4ProbabilityValues.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": 54.3703703704, "max_line_length": 168, "alphanum_fraction": 0.7716280654, "num_tokens": 1573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.50442578023353}}
{"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 <vector>\n\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/InputOutput/matrixTextFileReader.h\"\n\n#include \"Tudat/Mathematics/Interpolators/cubicSplineInterpolator.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n// NOTE: No benchmark data from established software package has been used. Matlab implementation\n// is slightly different than that implemented here, yielding error of at worst 10e-7 compared\n// when using error function, which is used here as test function.\n// However, a Matlab implementation of the same algorithm was found on te Matlab forum,\n// which is used here as benchmark.\n// In addition, the code has been used rather extensively and has been checked for basic\n// characteristics such as continuity.\nBOOST_AUTO_TEST_SUITE( test_cubic_spline_interpolator )\n\n// Test implementation of cubic spline class.\nBOOST_AUTO_TEST_CASE( testCubicSplineInterpolator )\n{\n    // Test 1: Compare with analytical function 2 + 3x + 5x^2.\n    {\n        // Declare and initialize independent variable values.\n        std::vector< double > independentVariables;\n        independentVariables.resize( 6 );\n        independentVariables[ 0 ] = 1.0;\n        independentVariables[ 1 ] = 3.0;\n        independentVariables[ 2 ] = 5.0;\n        independentVariables[ 3 ] = 7.0;\n        independentVariables[ 4 ] = 9.0;\n        independentVariables[ 5 ] = 11.0;\n\n        // Declare and initialize dependent variable values.\n        std::vector< double > dependentVariables;\n        dependentVariables.resize( 6 );\n        dependentVariables[ 0 ] = 10.0;\n        dependentVariables[ 1 ] = 56.0;\n        dependentVariables[ 2 ] = 142.0;\n        dependentVariables[ 3 ] = 268.0;\n        dependentVariables[ 4 ] = 434.0;\n        dependentVariables[ 5 ] = 640.0;\n\n        // Declare and initialize target independent variable value.\n        const double targetIndependentVariableValue = 6.0;\n\n        // Declare and initialize expected result of interpolation from analytical equation.\n        const double analyticalValue = 200.0;\n\n        // Declare cubic spline object and initialize with input data.\n        interpolators::CubicSplineInterpolatorDouble cubicSplineInterpolation(\n                    independentVariables, dependentVariables );\n\n        // Declare interpolated dependent variable value and execute interpolation.\n        const double interpolatedDependentVariableValue = cubicSplineInterpolation.interpolate(\n                    targetIndependentVariableValue );\n\n        // Check if test result match analytical result.\n        BOOST_CHECK_SMALL(  std::fabs( analyticalValue - interpolatedDependentVariableValue )\n                            / analyticalValue,\n                            5.0e-3 );\n    }\n}\n\n// Test exception handling implementation of cubic spline class.\nBOOST_AUTO_TEST_CASE( testCubicSplineInterpolation_exception_empty_vectors )\n{\n    // Test 2: Interpolate with empty vectors.\n    // Declare independent and dependent variable vectors.\n    std::vector< double > independentVariables, dependentVariables;\n\n    // Declare and initialize flag.\n    bool areDependentAndIndependentVariablesInitialized = true;\n\n    // Try to initialize with empty vectors.\n    try\n    {\n        // Declare cubic spline object and initialize with input data.\n        interpolators::CubicSplineInterpolatorDouble cubicSplineInterpolation(\n                    independentVariables, dependentVariables );\n    }\n\n    // Catch the expected runtime error, and set the boolean flag to false.\n    catch ( std::runtime_error )\n    {\n        areDependentAndIndependentVariablesInitialized = false;\n    }\n\n    // Check value of flag.\n    BOOST_CHECK( !areDependentAndIndependentVariablesInitialized );\n}\n\n// Test cubic spline interpolator by comparing to Matlab code posted at\n// http://www.mathworks.com/matlabcentral/newsreader/view_thread/173708.\nBOOST_AUTO_TEST_CASE( test_cubicSplineInterpolator_matlab_forum_compare )\n{\n    using namespace interpolators;\n\n    // Load input data used for generating matlab interpolation.\n    Eigen::MatrixXd inputData = input_output::readMatrixFromFile(\n                input_output::getTudatRootPath( ) +\n                \"Mathematics/Interpolators/UnitTests/interpolator_test_input_data.dat\",\",\" );\n\n    // Put data in STL vectors.\n    std::vector< double > independentVariableValues;\n    std::vector< double > dependentVariableValues;\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    }\n\n    // Create cubic spline interpolator using hunting algorithm.\n    CubicSplineInterpolatorDouble cubicSplineInterpolator(\n                independentVariableValues, dependentVariableValues, huntingAlgorithm );\n\n    // Load points at which interpolator is to be evaluated and data generated by Matlab.\n    Eigen::MatrixXd benchmarkData = input_output::readMatrixFromFile(\n                input_output::getTudatRootPath( ) +\n                \"Mathematics/Interpolators/UnitTests/\"\n                + \"cubic_spline_interpolator_test_output_data.dat\",\n                \",\" );\n\n    // Perform interpolation for required data points.\n    Eigen::VectorXd outputData = Eigen::VectorXd( benchmarkData.rows( ) );\n    for ( int i = 0; i < outputData.rows( ); i++ )\n    {\n        outputData[ i ] = cubicSplineInterpolator.interpolate( benchmarkData( i, 0 ) );\n    }\n\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( benchmarkData.block( 0, 1, benchmarkData.rows( ), 1 ),\n                                       outputData, 1.0e-13 );\n\n    // Create cubic spline interpolator, now using binary search algorithm.\n    cubicSplineInterpolator = CubicSplineInterpolatorDouble(\n                independentVariableValues, dependentVariableValues, binarySearch );\n\n    // Perform interpolation for required data points.\n    outputData = Eigen::VectorXd( benchmarkData.rows( ) );\n    for ( int i = 0; i < outputData.rows( ); i++ )\n    {\n        outputData[ i ] = cubicSplineInterpolator.interpolate( benchmarkData( i, 0 ) );\n    }\n\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( benchmarkData.block( 0, 1, benchmarkData.rows( ), 1 ),\n                                       outputData, 1.0e-13 );\n}\n\n// Test cubic spline interpolator by comparing to Matlab implementation. Note that the two\n// implementations are not identical, since the Matlab implementation imposes zero first\n// derivatives whereas the present implementation imposes zero second derivatives at endpoints.\nBOOST_AUTO_TEST_CASE( test_cubicSplineInterpolator_matlab_compare )\n{\n    using namespace interpolators;\n\n    // Load input data used for generating matlab interpolation.\n    Eigen::MatrixXd inputData = input_output::readMatrixFromFile(\n                input_output::getTudatRootPath( ) +\n                \"Mathematics/Interpolators/UnitTests/interpolator_test_input_data.dat\", \",\" );\n\n    // Put data in STL vectors.\n    std::vector< double > independentVariableValues;\n    std::vector< double > dependentVariableValues;\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    }\n\n    // Create cubic spline interpolator.\n    CubicSplineInterpolatorDouble linearInterpolator(\n                independentVariableValues, dependentVariableValues );\n\n    // Load points at which interpolator is to be evaluated and data generated by Matlab.\n    Eigen::MatrixXd benchmarkData = input_output::readMatrixFromFile(\n                input_output::getTudatRootPath( ) +\n                \"Mathematics/Interpolators/UnitTests/\"\n                + \"cubic_spline_interpolator_approximate_test_output_data.dat\", \",\" );\n\n    // Perform interpolation for required data points.\n    Eigen::VectorXd outputData = Eigen::VectorXd( benchmarkData.rows( ) );\n    for ( int i = 0; i < outputData.rows( ); i++ )\n    {\n        outputData[ i ] = linearInterpolator.interpolate( benchmarkData( i, 0 ) );\n    }\n\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( benchmarkData.block( 0, 1, benchmarkData.rows( ), 1 ),\n                                       outputData, 1.0e-5 );\n}\n\n// Test linear interpolation outside of independent variable range\nBOOST_AUTO_TEST_CASE( test_cubicSplineInterpolator_boundary_case )\n{\n    using namespace interpolators;\n\n    // Load input data used for generating matlab interpolation.\n    Eigen::MatrixXd inputData = input_output::readMatrixFromFile(\n                input_output::getTudatRootPath( ) +\n                \"Mathematics/Interpolators/UnitTests/interpolator_test_input_data.dat\",\",\" );\n\n    // Put data in STL vectors.\n    std::vector< double > independentVariableValues;\n    std::vector< double > dependentVariableValues;\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    }\n\n    // Create linear interpolator using hunting algorithm.\n    double valueOffset = 2.0;\n    double valueBelowMinimumValue = independentVariableValues[ 0 ] - valueOffset;\n    double valueAboveMaximumValue = independentVariableValues[ inputData.rows( ) - 1 ] + valueOffset;\n    double interpolatedValue = TUDAT_NAN, expectedValue = TUDAT_NAN;\n    bool exceptionIsCaught = false;\n\n    for( unsigned int i = 0; i < 5; i++ )\n    {\n        CubicSplineInterpolatorDouble linearInterpolator(\n                    independentVariableValues, dependentVariableValues, huntingAlgorithm,\n                    static_cast< BoundaryInterpolationType >( i ) );\n\n        if( static_cast< BoundaryInterpolationType >( i ) == throw_exception_at_boundary )\n        {\n            try\n            {\n                linearInterpolator.interpolate( valueBelowMinimumValue );\n            }\n            catch( std::runtime_error )\n            {\n                exceptionIsCaught = true;\n            }\n            BOOST_CHECK_EQUAL( exceptionIsCaught, true );\n\n            exceptionIsCaught = false;\n            try\n            {\n                linearInterpolator.interpolate( valueAboveMaximumValue );\n            }\n            catch( std::runtime_error )\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 = linearInterpolator.interpolate( valueBelowMinimumValue );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, dependentVariableValues.at( 0 ), 1.0E-15 );\n\n            interpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, dependentVariableValues.at( inputData.rows( ) - 1 ), 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            interpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );\n            expectedValue = -1.0171383008483266; // computed with MATLAB\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, expectedValue, 1.0E-15 );\n\n            interpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );\n            expectedValue = 1.0171383008483266; // computed with MATLAB\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, expectedValue, 1.0E-15 );\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "f3b03ad49144641896ee8a9ab5c45c1350d65d38", "size": 12301, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/Interpolators/UnitTests/unitTestCubicSplineInterpolator.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/Mathematics/Interpolators/UnitTests/unitTestCubicSplineInterpolator.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/Mathematics/Interpolators/UnitTests/unitTestCubicSplineInterpolator.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": 41.8401360544, "max_line_length": 122, "alphanum_fraction": 0.6810828388, "num_tokens": 2644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5044257797867532}}
{"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_ARCH_COMMON_SIMD_FUNCTION_SINHCOSH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SINHCOSH_HPP_INCLUDED\n\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/arch/common/detail/generic/sinh_kernel.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/detail/constant/maxlog.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/any.hpp>\n#include <boost/simd/function/average.hpp>\n#include <boost/simd/function/bitofsign.hpp>\n#include <boost/simd/function/bitwise_xor.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_greater.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/unary_minus.hpp>\n#include <utility>\n\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( sinhcosh_\n                             , (typename A0, typename X)\n                             , bd::cpu_\n                             , bs::pack_< bd::floating_<A0>, X>\n                             )\n  {\n    using result_t = std::pair<A0, A0>;\n    BOOST_FORCEINLINE result_t operator() ( A0 const& a0) const\n    {\n      //////////////////////////////////////////////////////////////////////////////\n      // if x = abs(a0) is less than 1 sinh is computed using a polynomial(float)\n      // respectively rational(double) approx from cephes.\n      // else according x < Threshold e =  exp(x) or exp(x/2) is respectively\n      // computed\n      // *  in the first case sinh is (e-rec(e))/2 and cosh (e+rec(e))/2\n      // *  in the second     sinh and cosh are (e/2)*e (avoiding undue overflow)\n      // Threshold is Maxlog - Log_2 defined in Maxshlog\n      //////////////////////////////////////////////////////////////////////////////\n      A0 x = bs::abs(a0);\n      auto lt1= is_less(x, One<A0>());\n      A0 bts = bitofsign(a0);\n      A0 s = Zero<A0>();\n      if( bs::any(lt1))\n      {\n        s = detail::sinh_kernel<A0>::compute(x, sqr(x));\n      }\n      auto test1 = is_greater(x, Maxlog<A0>()-Log_2<A0>());\n      A0 fac = if_else(test1, Half<A0>(), One<A0>());\n      A0 tmp = exp(x*fac);\n      A0 tmp1 = Half<A0>()*tmp;\n      A0 rtmp = rec(tmp);\n      A0 r = if_else(test1, tmp1*tmp, tmp1-Half<A0>()*rtmp);\n      return { bitwise_xor(if_else(lt1, s, r), bts), if_else(test1, r, bs::average(tmp, rtmp))};\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "417059d168d1e1a0327d4314e1551a3488b3d01b", "size": 3118, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/sinhcosh.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/arch/common/simd/function/sinhcosh.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/arch/common/simd/function/sinhcosh.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": 38.0243902439, "max_line_length": 100, "alphanum_fraction": 0.5763309814, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.5043475175018886}}
{"text": "/* ----------------------------------------------------------------------------\n * GTDynamics Copyright 2020, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * See LICENSE for the license information\n * -------------------------------------------------------------------------- */\n\n/**\n * @file  testStatics.cpp\n * @brief Test calculations for statics.\n * @author Frank Dellaert\n */\n\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/base/numericalDerivative.h>\n\n#include <boost/bind.hpp>\n#include <cmath>\n\n#include \"gtdynamics/statics/Statics.h\"\n#include \"gtdynamics/universal_robot/RobotModels.h\"\n\nusing namespace gtdynamics;\nusing namespace gtsam;\nconstexpr double kTol = 1e-6;\n\nnamespace example {\nconstexpr double g = 9.8;\nconst Robot robot = gtdynamics::CreateRobotFromFile(\n    kSdfPath + std::string(\"test/four_bar_linkage.sdf\"));\nVector3 gravity(0, 0, -g);\n}  // namespace example\n\nTEST(Statics, GravityWrench1) {\n  using namespace example;\n  const Pose3 wTcom(Rot3(), Point3(1, 0, 0));\n  const double mass = robot.link(\"l1\")->mass();\n  Matrix6 actualH;\n  EXPECT(assert_equal((Vector(6) << 0, 0, 0, 0, 0, -100 * g).finished(),\n                      GravityWrench(gravity, mass, wTcom, actualH), kTol));\n  Matrix6 numericalH = numericalDerivative11<Vector6, Pose3>(\n      boost::bind(&GravityWrench, gravity, mass, _1, boost::none), wTcom);\n  EXPECT(assert_equal(numericalH, actualH, kTol));\n}\n\nTEST(Statics, GravityWrench2) {\n  using namespace example;\n  const Pose3 wTcom(Rot3::Rx(M_PI_2), Point3(1, 0, 0));\n  const double mass = robot.link(\"l2\")->mass();\n  Matrix6 actualH;\n  EXPECT(assert_equal((Vector(6) << 0, 0, 0, 0, -15 * g, 0).finished(),\n                      GravityWrench(gravity, mass, wTcom, actualH), kTol));\n  Matrix6 numericalH = numericalDerivative11<Vector6, Pose3>(\n      boost::bind(&GravityWrench, gravity, mass, _1, boost::none), wTcom);\n  EXPECT(assert_equal(numericalH, actualH, kTol));\n}\n\nTEST(Statics, ResultantWrench) {\n  std::vector<Vector6> wrenches(2);\n  wrenches[0] << 1, 2, 3, 4, 5, 6;\n  wrenches[1] << 6, 5, 4, 3, 2, 1;\n  std::vector<Matrix> actualH(2);\n  EXPECT(assert_equal((Vector(6) << 7, 7, 7, 7, 7, 7).finished(),\n                      ResultantWrench(wrenches, actualH), kTol));\n  Matrix expected(6, 6);\n  expected.setIdentity();\n  EXPECT(assert_equal(expected, actualH[0], kTol));\n  EXPECT(assert_equal(expected, actualH[1], kTol));\n}\n\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n", "meta": {"hexsha": "6dcc1c94bd52789789892b4c9f78b187f6b2b3c3", "size": 2504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testStatics.cpp", "max_stars_repo_name": "mfkiwl/GTDynamics", "max_stars_repo_head_hexsha": "e5121e6a7ba5f8b5778f8934631bd99ea0946997", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-08-09T23:43:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T16:16:37.000Z", "max_issues_repo_path": "tests/testStatics.cpp", "max_issues_repo_name": "mfkiwl/GTDynamics", "max_issues_repo_head_hexsha": "e5121e6a7ba5f8b5778f8934631bd99ea0946997", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 104.0, "max_issues_repo_issues_event_min_datetime": "2021-08-03T14:15:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T08:18:09.000Z", "max_forks_repo_path": "tests/testStatics.cpp", "max_forks_repo_name": "mfkiwl/GTDynamics", "max_forks_repo_head_hexsha": "e5121e6a7ba5f8b5778f8934631bd99ea0946997", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-08-02T17:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T00:43:17.000Z", "avg_line_length": 33.3866666667, "max_line_length": 80, "alphanum_fraction": 0.6409744409, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5043064445666249}}
{"text": "//////////////////////////////////////////////////////////////////////////////////\n// random::poisson_ex::poisson_devroye::detail::q_function::using_sum.hpp       //\n//                                                                              //\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#ifndef BOOST_RANDOM_POISSON_EXT_DEVROYE_DETAIL_Q_FUNCTION_USING_SUM_ER_2010\n#define BOOST_RANDOM_POISSON_EXT_DEVROYE_DETAIL_Q_FUNCTION_USING_SUM_ER_2010\n#include <cmath>\n#include <boost/mpl/bool.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace poisson{\nnamespace devroye{            \nnamespace q{\n\nnamespace sum_method{\n    template<typename T,typename Int,typename P,typename IntT>\n    T fun(const Int& i_mean,const Int& i_y,const P& p,const IntT& converter);\n}\n    struct using_sum{ using_sum(){} };\n\n    template<typename T,typename Int,typename P,typename IntT>\n    T fun(const Int& i_mean,const Int& i_y,const P& p,\n        const IntT& converter,using_sum/*method*/)\n    {\n        return sum_method::fun<T>(i_mean,i_y,p,converter);\n    }\n\nnamespace sum_method{\n\n    template<typename T,typename Int,typename P,typename IntT>\n    T fun(const T& inv,const Int& i_y,const P& p,const IntT& converter,\n        boost::mpl::bool_<false>/*y>0*/)\n    {\n        using namespace boost::math;\n        BOOST_ASSERT(i_y<0);\n        T j, r = IntT::convert( 0 );\n        Int n = -( 1 + i_y ) + 1;\n        for(Int i = 0; i < n; i++){\n            j = IntT::convert( i );\n            r += log1p(- inv * j, p );\n        }\n        return r;\n    }\n\n    template<typename T,typename Int,typename P,typename IntT>\n    T fun(const T& inv,const Int& i_y,const P& p,const IntT& converter,\n        boost::mpl::bool_<true>/*y>0*/)\n    {\n        using namespace boost::math;\n    \n        BOOST_ASSERT(i_y>0);\n        T j , r = IntT::convert( 0 );\n        Int n = 1 + i_y;\n        for(Int i = 1; i < n; i++){\n            j = IntT::convert( i );\n            r -= log1p( inv * j, p );\n        }\n        return r;\n    }\n\n    template<typename T,typename Int,typename P,typename IntT>\n    T fun(const Int& i_mean,const Int& i_y,const P& p,const IntT& converter)\n    {\n        T r = IntT::convert( 0 );\n        if(i_y!=0){\n            T m = IntT::convert( i_mean );\n            T inv = pow( m , -1);\n            typedef boost::mpl::bool_<false> false_;\n            typedef boost::mpl::bool_<true> true_;\n            if(i_y<0) \n                r += sum_method::fun( inv, i_y, p , converter, false_());   \n            if(i_y>0) \n                r += sum_method::fun( inv, i_y, p , converter, true_());   \n        }\n        return r;    \n    }\n\n}// sum_method\n}// q\n}// devroye\n}// poisson\n}// random\n}// boost\n\n#endif\n\n", "meta": {"hexsha": "ea412f92af39dba8018d946c778752ca53369ab2", "size": 3186, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/poisson_ext/devroye/q_function/using_sum.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": "random/boost/random/poisson_ext/devroye/q_function/using_sum.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": "random/boost/random/poisson_ext/devroye/q_function/using_sum.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.8936170213, "max_line_length": 82, "alphanum_fraction": 0.5119271814, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5043064391527979}}
{"text": "/******************************************************************\n * Created by Wei on 3/12/17.\n *\n * This is an implementation of this paper:\n * \"Sparse Inverse Covariance Estimation with the Graphical Lasso\"\n * \n * All names of parameters comply with the notaions in the paper.\n ******************************************************************/\n\n#include \"GraphicalLasso.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <iostream>\n#include <map>\n\n#ifdef BAZEL\n#include \"Models/LinearRegression.hpp\"\n#include \"Models/Model.hpp\"\n#else\n#include \"../Models/LinearRegression.hpp\"\n#include \"../Models/Model.hpp\"\n#endif\n\nusing namespace Eigen;\nusing namespace std;\n\nGraphicalLasso::GraphicalLasso(const unordered_map<string, string>& opts) {\n    try {\n        tolerance = stod(opts.at(\"tolerance\"));\n    } catch(std::out_of_range& oor) {\n        tolerance = default_tolerance;\n    }\n    try {\n        learningRate = stod(opts.at(\"learning_rate\"));\n    } catch(std::out_of_range& oor) {\n        learningRate = default_learning_rate;\n    }\n}\n\n\nGraphicalLasso::GraphicalLasso() {\n    learningRate = default_learning_rate;\n    tolerance = default_tolerance;\n}\n\n\n/*void GraphicalLasso::stop() {\n    shouldStop = true;\n}*/\n\nvoid GraphicalLasso::setTolerance(float tol) {\n    tolerance = tol;\n}\n\nvoid GraphicalLasso::assertReadyToRun() {\n    return;    // there is no data that cannot be inferred\n}\n\n\nvoid GraphicalLasso::setUpRun() {\n    mtx.lock();\n    isRunning = true;\n    progress = 0.0;\n    shouldStop = false;\n}\n\nvoid GraphicalLasso::finishRun() {\n    isRunning = false;\n    progress = 1.0;\n    mtx.unlock();\n}\n\nvoid GraphicalLasso::setLearningRate(float lr) {\n    learningRate = lr;\n}\n\nMatrixXf GraphicalLasso::matrixRaiseToHalf(MatrixXf& matrix) {\n    BDCSVD<MatrixXf> svd(matrix, ComputeThinU | ComputeThinV);\n    MatrixXf D = svd.singularValues().array().sqrt().matrix().asDiagonal();\n    MatrixXf U = svd.matrixU();\n    return U * D * U.transpose();\n}\n\n\n\nvoid GraphicalLasso::run(shared_ptr<LinearRegression> model) {\n    MatrixXf X = model->getX();\n    int num_samples = X.rows();\n    int num_features = X.cols();\n    stdNormalize(X);\n    MatrixXf S = X.transpose() * X / num_samples;\n    MatrixXf W = S;\n    MatrixXf W_inv = Math::getInstance().pseudoInverse(W);\n    MatrixXf W_inv_old = W_inv;\n    float regularizer = model->getL1_reg();\n\n    for (int epoch = 0; epoch < maxIteration; epoch++) {\n        progress = static_cast<float>(epoch) / maxIteration;\n        for (int idx = 0; idx < num_features; idx++) {\n            // partition matrixes into blocks\n            vector<MatrixXf> S_blocks = partitionBlocks(S);\n            MatrixXf W_11 = partitionBlocks(W)[0];\n            MatrixXf W_inv_11 = partitionBlocks(W_inv)[0];\n            \n            // find W_11 ^ (1/2)\n            MatrixXf W_11_half = matrixRaiseToHalf(W_11); \n            MatrixXf b = Math::getInstance().pseudoInverse(W_11_half) * S_blocks[1];\n            \n            // run linear regression with lasso\n            MatrixXf beta = fit(model, W_11_half, b);\n            MatrixXf W_12 = W_11 * beta;\n            \n            // recover W_inv (W_inv corresponds to theta in the paper)\n            float S_22 = S_blocks.back()(0, 0);\n            float W_22 = S_22 + regularizer;\n            float W_inv_22 = 1 / (W_22 - (W_12.transpose() * beta)(0, 0)); \n            MatrixXf W_inv_12 = -W_inv_22 * beta;\n\n            W_inv = composeBlocks(W_inv_11, W_inv_12, W_inv_22);\n            W = composeBlocks(W_11, W_12, W_22);\n            S = composeBlocks(S_blocks[0], S_blocks[1], S_blocks[2](0, 0));\n        }\n        float diff = (W_inv - W_inv_old).norm();\n        if (diff < tolerance) {\n            break;\n        } else {\n            W_inv_old = W_inv;\n        }\n    }\n    for (long col = 0; col < W_inv.cols(); col++) {\n        for (long row = 0; row < W_inv.rows(); row++) {\n            W_inv(row, col) = abs(W_inv(row, col)) < 1e-5 ? 0 : 1;\n        }\n    }\n    model->updateBeta(W_inv);\n}\n\nMatrixXf GraphicalLasso::fit(shared_ptr<LinearRegression> model, MatrixXf& X, MatrixXf& Y) {\n    model->setL1_reg(model->getL1_reg()*10);\n    model->setX(X);\n    model->setY(Y);\n    model->initBeta();\n    float residue = model->cost();\n    VectorXf grad;\n    VectorXf in;\n    long epoch = 0;\n    while (!shouldStop && epoch < maxIteration && residue > tolerance && !shouldStop) {\n        grad = model->proximal_derivative();\n        in = model->getBeta() - learningRate * grad;\n        model->updateBeta(model->proximal_operator(in, learningRate));\n        residue = model->cost();\n        epoch++;\n    }\n    return model->getBeta();\n}\n\nvoid GraphicalLasso::stdNormalize(MatrixXf& matrix) {\n    RowVectorXf mean = matrix.colwise().mean();\n    RowVectorXf std = ((matrix.rowwise() - mean).array().square().colwise().sum() / \n                       (matrix.rows())).sqrt();\n    matrix = (matrix.rowwise() - mean).array().rowwise() / std.array();\n}\n\nvector<MatrixXf> GraphicalLasso::partitionBlocks(MatrixXf& matrix) {\n    int num_rows = matrix.rows();\n    int num_cols = matrix.cols();\n    MatrixXf m_11 = matrix.block(0, 0, num_rows - 1, num_cols - 1);\n    MatrixXf m_12 = matrix.block(0, num_cols - 1, num_rows - 1, 1);\n    MatrixXf m_22 = matrix.block(num_rows - 1, num_cols - 1, 1, 1);\n    return {m_11, m_12, m_22};\n}\n\nMatrixXf GraphicalLasso::composeBlocks(MatrixXf& m_11,\n                                       MatrixXf& m_12,\n                                       float m_22) {\n    int num_rows = m_11.rows() + 1;\n    int num_cols = m_11.cols() + 1;\n    MatrixXf result(num_rows, num_cols);\n    result.block(1, 1, num_rows - 1, num_cols - 1) = m_11;\n    result.block(1, 0, num_rows - 1, 1) = m_12;\n    result.block(0, 1, 1, num_cols - 1) = m_12.transpose();\n    result(0, 0) = m_22;\n    return result;\n}\n", "meta": {"hexsha": "7b910f575bab073bdaefc0b23508f2358bac0361", "size": 5794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Graph/GraphicalLasso.cpp", "max_stars_repo_name": "blengerich/jenkins_test", "max_stars_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T00:36:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-06T16:40:52.000Z", "max_issues_repo_path": "src/Graph/GraphicalLasso.cpp", "max_issues_repo_name": "blengerich/jenkins_test", "max_issues_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2016-11-11T22:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-04T21:55:57.000Z", "max_forks_repo_path": "src/Graph/GraphicalLasso.cpp", "max_forks_repo_name": "blengerich/jenkins_test", "max_forks_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-02-01T09:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T14:40:43.000Z", "avg_line_length": 31.1505376344, "max_line_length": 92, "alphanum_fraction": 0.5950983776, "num_tokens": 1612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5043064337389709}}
{"text": "/*\n\nCopyright (c) 2005-2022, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\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 * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#ifndef FARHADIFARFORCE_HPP_\n#define FARHADIFARFORCE_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n#include \"Exception.hpp\"\n\n#include \"AbstractForce.hpp\"\n#include \"VertexBasedCellPopulation.hpp\"\n\n#include <iostream>\n\n/**\n * A force class for use in Vertex-based simulations. This force is based on the\n * Energy function proposed by Farhadifar et al in  Curr. Biol., 2007, 17, 2095-2104.\n */\n\n\ntemplate<unsigned DIM>\nclass FarhadifarForce : public AbstractForce<DIM>\n{\nfriend class TestForces;\n\nprivate:\n\n    friend class boost::serialization::access;\n    /**\n     * Boost Serialization method for archiving/checkpointing.\n     * Archives the object and its member variables.\n     *\n     * @param archive  The boost archive.\n     * @param version  The current version of this class.\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n        archive & boost::serialization::base_object<AbstractForce<DIM> >(*this);\n        archive & mAreaElasticityParameter;\n        archive & mPerimeterContractilityParameter;\n        archive & mLineTensionParameter;\n        archive & mBoundaryLineTensionParameter;\n    }\n\nprotected:\n\n    /**\n     * The strength of the area term in the model. Corresponds to K_alpha in Farhadifar's paper.\n     */\n    double mAreaElasticityParameter;\n\n    /**\n     * The strength of the perimeter term in the model. Corresponds to Gamma_alpha in Farhadifar's paper.\n     */\n    double mPerimeterContractilityParameter;\n\n    /**\n     * The strength of the line tension term in the model. Lambda_{i,j} in Farhadifar's paper.\n     */\n    double mLineTensionParameter;\n\n    /**\n     * The strength of the line tension at the boundary. This term does correspond to Lambda_{i,j} in Farhadifar's paper.\n     */\n    double mBoundaryLineTensionParameter;\n\n\npublic:\n\n    /**\n     * Constructor.\n     */\n    FarhadifarForce();\n\n    /**\n     * Destructor.\n     */\n    virtual ~FarhadifarForce();\n\n    /**\n     * Overridden AddForceContribution() method.\n     *\n     * Calculates the force on each node in the vertex-based cell population based on the energy function\n     * Farhadifar's model.\n     *\n     * @param rCellPopulation reference to the cell population\n     */\n    virtual void AddForceContribution(AbstractCellPopulation<DIM>& rCellPopulation);\n\n    /**\n     * Get the line tension parameter for the edge between two given nodes.\n     *\n     * @param pNodeA one node\n     * @param pNodeB the other node\n     * @param rVertexCellPopulation reference to the cell population\n     *\n     * @return the line tension parameter for this edge.\n     */\n    virtual double GetLineTensionParameter(Node<DIM>* pNodeA, Node<DIM>* pNodeB, VertexBasedCellPopulation<DIM>& rVertexCellPopulation);\n\n    /**\n     * @return mAreaElasticityParameter\n     */\n    double GetAreaElasticityParameter();\n\n    /**\n     * @return mPerimeterContractilityParameter\n     */\n    double GetPerimeterContractilityParameter();\n\n    /**\n     * @return mLineTensionParameter\n     */\n    double GetLineTensionParameter();\n\n    /**\n     * @return mBoundaryLineTensionParameter\n     */\n    double GetBoundaryLineTensionParameter();\n\n    /**\n     * Set mAreaElasticityParameter.\n     *\n     * @param areaElasticityParameter the new value of mAreaElasticityParameter\n     */\n    void SetAreaElasticityParameter(double areaElasticityParameter);\n\n    /**\n     * Set mPerimeterContractilityParameter.\n     *\n     * @param perimeterContractilityParameter the new value of perimterContractilityParameter\n     */\n    void SetPerimeterContractilityParameter(double perimeterContractilityParameter);\n\n    /**\n     * Set mLineTensionParameter.\n     *\n     * @param lineTensionParameter the new value of mLineTensionParameter\n     */\n    void SetLineTensionParameter(double lineTensionParameter);\n\n    /**\n     * Set mBoundaryLineTensionParameter.\n     *\n     * @param boundaryLineTensionParameter the new value of mBoundaryLineTensionParameter\n     */\n    void SetBoundaryLineTensionParameter(double boundaryLineTensionParameter);\n\n    /**\n     * Overridden OutputForceParameters() method.\n     *\n     * @param rParamsFile the file stream to which the parameters are output\n     */\n    void OutputForceParameters(out_stream& rParamsFile);\n};\n\n#include \"SerializationExportWrapper.hpp\"\nEXPORT_TEMPLATE_CLASS_SAME_DIMS(FarhadifarForce)\n\n#endif /*FARHADIFARFORCE_HPP_*/\n", "meta": {"hexsha": "33db94f99fe583bef2a3ae4a8e44b1397c2d80f1", "size": 6155, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/population/forces/FarhadifarForce.hpp", "max_stars_repo_name": "stu-l/Chaste", "max_stars_repo_head_hexsha": "8efa8b440660553af66804067639f237c855f557", "max_stars_repo_licenses": ["Apache-2.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": "cell_based/src/population/forces/FarhadifarForce.hpp", "max_issues_repo_name": "stu-l/Chaste", "max_issues_repo_head_hexsha": "8efa8b440660553af66804067639f237c855f557", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cell_based/src/population/forces/FarhadifarForce.hpp", "max_forks_repo_name": "stu-l/Chaste", "max_forks_repo_head_hexsha": "8efa8b440660553af66804067639f237c855f557", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5641025641, "max_line_length": 136, "alphanum_fraction": 0.7301380991, "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5043064337389709}}
{"text": "// Expand an orientation set expressed as a set of grids into a set of\n// explicit orientations.\n//\n// Written by Charles Karney\n// Copyright (c) 2006 Sarnoff Corporation. All rights reserved.\n//\n// For more information, see\n//\n//    https://github.com/cffk/orientation\n//\n// Compile with, e.g.,\n//\n//    g++ -O2 -o ExpandSet ExpandSet.cpp\n//\n// Run with\n//\n//   ./ExpandSet [-e] < grid-file > orientation-file\n//\n// If -e is specified, the orientations are written as Euler angles,\n// otherwise they are written as quaternions.  Format of the grid file:\n//\n//     Any number of initial comment lines beginning with #\n//     A line containing \"format grid\"\n//     A line containing: delta sigma ntot ncell nent maxrad coverage\n//     nent lines containing: k l m weight radius mult\n//\n// Here k >= l >= m >= 0.  delta and sigma are used to define the grid.\n// ntot is the total number of orientations, ncell = ntot/24 is the\n// number of orientations per cell of the 48-cell.  maxrad is the\n// covering radius of the set and radius is the radius of the Voronoi\n// cell.  Both are measured in degrees.  coverage is the coverage of the\n// set, i.e., how much overlap there is when caps of radius maxrad are\n// placed at each point; coverage = 1 means no overlap.\n//\n// For each triplet, [k l m], generate mult distinct permutations by\n// changing the order and the signs of the elements.  Each [k l m] is\n// converted to a point in a truncated cube [x y z] =\n// [pind(k/2,delta,sigma) pind(l/2,delta,sigma) pind(m/2,delta,sigma)]\n// Each [x y z] is converted to a unit quaternion via p = [1 x y z]; q =\n// p/|p| to give ncell orientations.  Finally, the 24 rotational cube\n// symmetries are applied to the results to yield ntot = orientations.\n// The weights are normalized such that sum mult weight = sum mult =\n// ncell\n\n// Format of the orientation file\n//\n//     Any number of initial comment lines beginning with #\n//     A line containing \"format quaternion\" or \"format euler\"\n//     A line containing: ntot maxrad coverage\n//     ntot lines containing: q0 q1 q2 q3 weight # for quaternions\n//     ntot lines containing: alpha beta gamma weight # for euler.\n//\n// The weights are normalized such that sum weight = ntot.\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <cassert>\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <string>\n#include <vector>\n// todo: wrap and adapt this code to make numpy array of quats\n\n// Windows doesn't define M_PI in the standard header?\n#if !defined(M_PI)\n#define M_PI 3.1415926535897932384626433832795028841971694\n#endif\n\nnamespace rpxdock {\nnamespace sampling {\nnamespace orientations {\n\nusing namespace std;\n\n// Minimal quaternion class\nclass Quaternion {\n public:\n  double w, x, y, z;\n  Quaternion(double ww = 1, double xx = 0, double yy = 0, double zz = 0)\n      : w(ww), x(xx), y(yy), z(zz) {}\n  void Normalize() {\n    double t = w * w + x * x + y * y + z * z;\n    assert(t > 0);\n    t = 1 / sqrt(t);\n    w *= t;\n    x *= t;\n    y *= t;\n    z *= t;\n    return;\n  }\n  void Canonicalize() {\n    Normalize();\n    // Make first biggest element positive\n    double mag = w;\n    if (abs(x) > abs(mag)) mag = x;\n    if (abs(y) > abs(mag)) mag = y;\n    if (abs(z) > abs(mag)) mag = z;\n    if (mag < 0) {\n      w *= -1;\n      x *= -1;\n      y *= -1;\n      z *= -1;\n    }\n    return;\n  }\n  // a.Times(b) returns a * b\n  Quaternion Times(const Quaternion &q) const {\n    double mw = w * q.w - x * q.x - y * q.y - z * q.z,\n           mx = w * q.x + x * q.w + y * q.z - z * q.y,\n           my = w * q.y + y * q.w + z * q.x - x * q.z,\n           mz = w * q.z + z * q.w + x * q.y - y * q.x;\n    return Quaternion(mw, mx, my, mz);\n  }\n  void Print(ostream &s) const;\n  void PrintEuler(ostream &s) const;\n};\n\n// Class to hold a set of orientations and weights\nclass PackSet {\n public:\n  Quaternion Orientation(size_t i) const { return m_v[i]; }\n  double Weight(size_t i) const { return m_w[i]; }\n  size_t Number() const { return m_v.size(); }\n  void Add(const Quaternion &q, double w = 1) {\n    Quaternion v(q);\n    v.Canonicalize();\n    m_v.push_back(v);\n    m_w.push_back(w);\n  }\n  void Clear() {\n    m_v.clear();\n    m_w.clear();\n  }\n  void Print(ostream &s, bool euler = false, size_t prec = 6) const {\n    for (size_t i = 0; i < Number(); ++i) {\n      if (euler)\n        m_v[i].PrintEuler(s);\n      else\n        m_v[i].Print(s);\n      s << \" \" << fixed << setprecision(prec) << setw(prec + 2) << m_w[i]\n        << endl;\n    }\n  }\n\n private:\n  vector<Quaternion> m_v;\n  vector<double> m_w;\n};\n\n// The triple of grid indices\nclass Triple {\n public:\n  int a, b, c;\n  Triple(int aa, int bb, int cc) : a(aa), b(bb), c(cc) {}\n};\n\n// Generate the permutations and sign changes for a Triple.\nclass Permute {\n public:\n  Permute(Triple x) {\n    assert(x.a >= x.b && x.b >= x.c && x.c >= 0);\n    m_arr.push_back(x);\n    size_t n = 1;\n    // Do the sign changes\n    if (x.a != 0) {\n      for (size_t i = 0; i < n; ++i)\n        m_arr.push_back(Triple(-m_arr[i].a, m_arr[i].b, m_arr[i].c));\n      n *= 2;\n    }\n    if (x.b != 0) {\n      for (size_t i = 0; i < n; ++i)\n        m_arr.push_back(Triple(m_arr[i].a, -m_arr[i].b, m_arr[i].c));\n      n *= 2;\n    }\n    if (x.c != 0) {\n      for (size_t i = 0; i < n; ++i)\n        m_arr.push_back(Triple(m_arr[i].a, m_arr[i].b, -m_arr[i].c));\n      n *= 2;\n    }\n    if (x.a == x.b && x.b == x.c) return;\n    // With at least two distinct indices we can rotate the set thru 3\n    // permuations.\n    for (size_t i = 0; i < n; ++i) {\n      m_arr.push_back(Triple(m_arr[i].b, m_arr[i].c, m_arr[i].a));\n      m_arr.push_back(Triple(m_arr[i].c, m_arr[i].a, m_arr[i].b));\n    }\n    n *= 3;\n    if (x.a == x.b || x.b == x.c) return;\n    // With three distinct indices we can in addition interchange the\n    // first two indices (to yield all 6 permutations of 3 indices).\n    for (size_t i = 0; i < n; ++i) {\n      m_arr.push_back(Triple(m_arr[i].b, m_arr[i].a, m_arr[i].c));\n    }\n    n *= 2;\n  }\n  size_t Number() const { return m_arr.size(); }\n  Triple Member(size_t i) const { return m_arr[i]; }\n\n private:\n  vector<Triple> m_arr;\n};\n\n// The rotational symmetries of the cube.  (Not normalized, since\n// PackSet.Add does this.)\nstatic double CubeSyms[24][4] = {\n    {1, 0, 0, 0},\n    // 180 deg rotations about 3 axes\n    {0, 1, 0, 0},\n    {0, 0, 1, 0},\n    {0, 0, 0, 1},\n    // +/- 120 degree rotations about 4 leading diagonals\n    {1, 1, 1, 1},\n    {1, 1, 1, -1},\n    {1, 1, -1, 1},\n    {1, 1, -1, -1},\n    {1, -1, 1, 1},\n    {1, -1, 1, -1},\n    {1, -1, -1, 1},\n    {1, -1, -1, -1},\n    // +/- 90 degree rotations about 3 axes\n    {1, 1, 0, 0},\n    {1, -1, 0, 0},\n    {1, 0, 1, 0},\n    {1, 0, -1, 0},\n    {1, 0, 0, 1},\n    {1, 0, 0, -1},\n    // 180 degree rotations about 6 face diagonals\n    {0, 1, 1, 0},\n    {0, 1, -1, 0},\n    {0, 1, 0, 1},\n    {0, 1, 0, -1},\n    {0, 0, 1, 1},\n    {0, 0, 1, -1},\n};\n\n// Convert from index to position.  The sinh scaling tries to compensate\n// for the bunching up that occurs when [1 x y z] is projected onto the\n// unit sphere.\ndouble pind(double ind, double delta, double sigma) {\n  return (sigma == 0) ? ind * delta : sinh(sigma * ind * delta) / sigma;\n}\n\nauto read_karney_orientations(std::string file_content) {\n  Eigen::MatrixX4d quats;\n  Eigen::VectorXd cover;\n\n  std::istringstream in(file_content);\n\n  bool euler = false;\n  assert(in.good());\n  string line;\n  while (in.peek() == '#') {\n    getline(in, line);\n    // cout << line << endl;\n  }\n  assert(in.good());\n  getline(in, line);\n  assert(line == \"format grid\");\n  double delta, sigma, maxrad, coverage;\n  size_t ncell, ntot, nent;\n  in >> delta >> sigma >> ntot >> ncell >> nent >> maxrad >> coverage;\n  // Use extra digit of precision with weights and radii.  This also\n  // triggers a memory minimizing expansion.\n  const bool fine = delta < 0.05;\n  quats.resize(ntot, 4);\n  cover.resize(ntot);\n  int quats_i = 0;\n  PackSet s;\n  size_t ncell1 = 0;\n  for (size_t n = 0; n < nent; ++n) {\n    int k, l, m;\n    size_t mult;\n    double r, w;\n    assert(in.good());\n    in >> k >> l >> m >> w >> r >> mult;\n    Permute p(Triple(k, l, m));\n    assert(mult == p.Number());\n    for (size_t i = 0; i < mult; ++i) {\n      Triple t = p.Member(i);\n      s.Add(Quaternion(1.0, pind(0.5 * t.a, delta, sigma),\n                       pind(0.5 * t.b, delta, sigma),\n                       pind(0.5 * t.c, delta, sigma)),\n            w);\n    }\n    ncell1 += mult;\n    if (fine) {\n      // Skip n = 0; that's already included.\n      for (size_t n = 1; n < 24; ++n) {\n        Quaternion q(CubeSyms[n][0], CubeSyms[n][1], CubeSyms[n][2],\n                     CubeSyms[n][3]);\n        for (size_t i = 0; i < mult; ++i)\n          s.Add(q.Times(s.Orientation(i)), s.Weight(i));\n      }\n      // s.Print(cout, euler, fine ? 7 : 6);\n      for (size_t i = 0; i < s.Number(); ++i) {\n        quats(quats_i, 0) = s.Orientation(i).w;\n        quats(quats_i, 1) = s.Orientation(i).x;\n        quats(quats_i, 2) = s.Orientation(i).y;\n        quats(quats_i, 3) = s.Orientation(i).z;\n        cover[quats_i++] = s.Weight(i);\n      }\n      s.Clear();\n    }\n  }\n  assert(in.good());\n  assert(ncell1 == ncell);\n  if (!fine) {\n    size_t nc = s.Number();\n    assert(nc == ncell);\n    for (size_t n = 1; n < 24; ++n) {\n      Quaternion q(CubeSyms[n][0], CubeSyms[n][1], CubeSyms[n][2],\n                   CubeSyms[n][3]);\n      for (size_t i = 0; i < nc; ++i)\n        s.Add(q.Times(s.Orientation(i)), s.Weight(i));\n    }\n    assert(s.Number() == ntot);\n    // s.Print(cout, euler, fine ? 7 : 6);\n    for (size_t i = 0; i < s.Number(); ++i) {\n      quats(quats_i, 0) = s.Orientation(i).w;\n      quats(quats_i, 1) = s.Orientation(i).x;\n      quats(quats_i, 2) = s.Orientation(i).y;\n      quats(quats_i, 3) = s.Orientation(i).z;\n      cover[quats_i++] = s.Weight(i);\n    }\n    s.Clear();\n  }\n  return std::make_tuple(quats, cover);\n}\n\nvoid Quaternion::Print(ostream &s) const {\n  s << fixed << setprecision(9) << setw(12) << w << \" \";\n  s << setw(12) << x << \" \";\n  s << setw(12) << y << \" \";\n  s << setw(12) << z;\n}\n\nvoid Quaternion::PrintEuler(ostream &s) const {\n  // Print out orientation as a set of Euler angles, following the\n  // convention given in\n  //\n  //    http://www.mhl.soton.ac.uk/research/help/Euler/index.html\n  //\n  // Rotation by Euler angles [a,b,c] is defined as rotation by c about\n  // z axis, followed by rotation by b about y axis. followed by\n  // rotation by a about z axis (again).\n  //\n  // Convert to rotation matrix (assume quaternion is already\n  // normalized)\n  double\n      // m00 = 1 - 2*y*y - 2*z*z,\n      m01 = 2 * x * y - 2 * z * w,\n      m02 = 2 * x * z + 2 * y * w,\n      // m10 =     2*x*y + 2*z*w,\n      m11 = 1 - 2 * x * x - 2 * z * z, m12 = 2 * y * z - 2 * x * w,\n      m20 = 2 * x * z - 2 * y * w, m21 = 2 * y * z + 2 * x * w,\n      m22 = 1 - 2 * x * x - 2 * y * y;\n  // Taken from Ken Shoemake, \"Euler Angle Conversion\", Graphics Gems\n  // IV, Academic 1994.\n  //\n  //    http://vered.rose.utoronto.ca/people/david_dir/GEMS/GEMS.html\n  double sy = sqrt(m02 * m02 + m12 * m12);\n  //  double sy = sqrt(m10*m10 + m20*m20);\n  double a, b, c;\n  b = atan2(sy, m22);\n  if (sy > 16 * numeric_limits<double>::epsilon()) {\n    a = atan2(m12, m02);\n    c = atan2(m21, -m20);\n  } else {\n    a = atan2(-m01, m11);\n    c = 0;\n  }\n  s << fixed << setprecision(9) << setw(12) << a << \" \" << setw(12) << b << \" \"\n    << setw(12) << c;\n\n#if !defined(NDEBUG)\n  // Sanity check.  Convert from Euler angles back to a quaternion, q\n  Quaternion q =\n      Quaternion(cos(a / 2), 0, 0, sin(a / 2))\n          .  // a about z\n      Times(Quaternion(cos(b / 2), 0, sin(b / 2), 0)\n                .                                              // b about y\n            Times(Quaternion(cos(c / 2), 0, 0, sin(c / 2))));  // c about z\n  // and check that q is parallel to *this.\n  double t = abs(q.w * w + q.x * x + q.y * y + q.z * z);\n  assert(t > 1 - 16 * numeric_limits<double>::epsilon());\n#endif\n}\n\n}  // namespace orientations\n}  // namespace sampling\n}  // namespace rpxdock", "meta": {"hexsha": "4ca35dd24330145df8d18ef3f649803251ba4b71", "size": 12071, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rpxdock/sampling/_orientations.hpp", "max_stars_repo_name": "quecloud/rpxdock", "max_stars_repo_head_hexsha": "41f7f98f5dacf24fc95897910263a0bec2209e59", "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": "rpxdock/sampling/_orientations.hpp", "max_issues_repo_name": "quecloud/rpxdock", "max_issues_repo_head_hexsha": "41f7f98f5dacf24fc95897910263a0bec2209e59", "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": "rpxdock/sampling/_orientations.hpp", "max_forks_repo_name": "quecloud/rpxdock", "max_forks_repo_head_hexsha": "41f7f98f5dacf24fc95897910263a0bec2209e59", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T20:07:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-13T20:07:52.000Z", "avg_line_length": 30.5594936709, "max_line_length": 79, "alphanum_fraction": 0.559854196, "num_tokens": 3993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5043064337389709}}
{"text": "#include <iostream>\n#include <fstream>\nusing namespace std;\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <Eigen/Geometry>\n#include <boost/format.hpp>  // for formating strings\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/visualization/pcl_visualizer.h>\n\nint main(int argc, char** argv)\n{\n  vector<cv::Mat> colorImgs, depthImgs;                                          // \u5f69\u8272\u56fe\u548c\u6df1\u5ea6\u56fe\n  vector<Eigen::Isometry3d, Eigen::aligned_allocator<Eigen::Isometry3d>> poses;  // \u76f8\u673a\u4f4d\u59ff\n\n  ifstream fin(\"./pose.txt\");\n  if (!fin)\n  {\n    cerr << \"\u8bf7\u5728\u6709pose.txt\u7684\u76ee\u5f55\u4e0b\u8fd0\u884c\u6b64\u7a0b\u5e8f\" << endl;\n    return 1;\n  }\n\n  for (int i = 0; i < 5; i++)\n  {\n    boost::format fmt(\"./%s/%d.%s\");  //\u56fe\u50cf\u6587\u4ef6\u683c\u5f0f\n    colorImgs.push_back(cv::imread((fmt % \"color\" % (i + 1) % \"png\").str()));\n    depthImgs.push_back(cv::imread((fmt % \"depth\" % (i + 1) % \"pgm\").str(), -1));  // \u4f7f\u7528-1\u8bfb\u53d6\u539f\u59cb\u56fe\u50cf\n\n    double data[7] = { 0 };\n    for (auto& d : data)\n      fin >> d;\n    Eigen::Quaterniond q(data[6], data[3], data[4], data[5]);\n    Eigen::Isometry3d T(q);\n    T.pretranslate(Eigen::Vector3d(data[0], data[1], data[2]));\n    poses.push_back(T);\n  }\n\n  // \u8ba1\u7b97\u70b9\u4e91\u5e76\u62fc\u63a5\n  // \u76f8\u673a\u5185\u53c2\n  double cx = 325.5;\n  double cy = 253.5;\n  double fx = 518.0;\n  double fy = 519.0;\n  double depthScale = 1000.0;\n\n  cout << \"\u6b63\u5728\u5c06\u56fe\u50cf\u8f6c\u6362\u4e3a\u70b9\u4e91...\" << endl;\n\n  // \u5b9a\u4e49\u70b9\u4e91\u4f7f\u7528\u7684\u683c\u5f0f\uff1a\u8fd9\u91cc\u7528\u7684\u662fXYZRGB\n  typedef pcl::PointXYZRGB PointT;\n  typedef pcl::PointCloud<PointT> PointCloud;\n\n  // \u65b0\u5efa\u4e00\u4e2a\u70b9\u4e91\n  PointCloud::Ptr pointCloud(new PointCloud);\n  for (int i = 0; i < 5; i++)\n  {\n    cout << \"\u8f6c\u6362\u56fe\u50cf\u4e2d: \" << i + 1 << endl;\n    cv::Mat color = colorImgs[i];\n    cv::Mat depth = depthImgs[i];\n    Eigen::Isometry3d T = poses[i];\n    for (int v = 0; v < color.rows; v++)\n      for (int u = 0; u < color.cols; u++)\n      {\n        unsigned int d = depth.ptr<unsigned short>(v)[u];  // \u6df1\u5ea6\u503c\n        if (d == 0)\n          continue;  // \u4e3a0\u8868\u793a\u6ca1\u6709\u6d4b\u91cf\u5230\n        Eigen::Vector3d point;\n        point[2] = double(d) / depthScale;\n        point[0] = (u - cx) * point[2] / fx;\n        point[1] = (v - cy) * point[2] / fy;\n        Eigen::Vector3d pointWorld = T * point;\n\n        PointT p;\n        p.x = pointWorld[0];\n        p.y = pointWorld[1];\n        p.z = pointWorld[2];\n        p.b = color.data[v * color.step + u * color.channels()];\n        p.g = color.data[v * color.step + u * color.channels() + 1];\n        p.r = color.data[v * color.step + u * color.channels() + 2];\n        pointCloud->points.push_back(p);\n      }\n  }\n\n  pointCloud->is_dense = false;\n  cout << \"\u70b9\u4e91\u5171\u6709\" << pointCloud->size() << \"\u4e2a\u70b9.\" << endl;\n  pcl::io::savePCDFileBinary(\"map.pcd\", *pointCloud);\n  return 0;\n}\n", "meta": {"hexsha": "bf123a8ed59e36a3130982026f170e7e734c4659", "size": 2612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch05/joinMap/joinMap.cpp", "max_stars_repo_name": "Chrislzy1993/slambook", "max_stars_repo_head_hexsha": "4030ee29c8d52121c2b3a52b7a086ab2ecea92d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T01:28:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-04T01:28:14.000Z", "max_issues_repo_path": "ch05/joinMap/joinMap.cpp", "max_issues_repo_name": "Chrislzy1993/slambook", "max_issues_repo_head_hexsha": "4030ee29c8d52121c2b3a52b7a086ab2ecea92d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch05/joinMap/joinMap.cpp", "max_forks_repo_name": "Chrislzy1993/slambook", "max_forks_repo_head_hexsha": "4030ee29c8d52121c2b3a52b7a086ab2ecea92d5", "max_forks_repo_licenses": ["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.3483146067, "max_line_length": 96, "alphanum_fraction": 0.5650842266, "num_tokens": 915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5043064283251434}}
{"text": "#include \"FiniteElementFunction.h\"\n#include \"form/RefElement.h\"\n#include \"tensor/EigenMap.h\"\n\n#include <Eigen/Core>\n\n#include <cassert>\n#include <cstdio>\n\nnamespace tndm {\n\ntemplate <std::size_t D>\nManaged<Matrix<double>>\nFiniteElementFunction<D>::evaluationMatrix(std::vector<std::array<double, D>> const& points) const {\n    return refElement_->evaluateBasisAt(points, {1, 0});\n}\n\ntemplate <std::size_t D>\nManaged<Tensor<double, 3u>> FiniteElementFunction<D>::gradientEvaluationTensor(\n    std::vector<std::array<double, D>> const& points) const {\n    return refElement_->evaluateGradientAt(points, {2, 0, 1});\n}\n\ntemplate <std::size_t D>\nTensorBase<Matrix<double>> FiniteElementFunction<D>::mapResultInfo(std::size_t numPoints) const {\n    return TensorBase<Matrix<double>>(numPoints, numQuantities());\n}\n\ntemplate <std::size_t D>\nvoid FiniteElementFunction<D>::map(std::size_t eleNo, Matrix<double> const& evalMatrix,\n                                   Tensor<double, 2u>& result) const {\n    assert(eleNo < numElements());\n    assert(result.shape(0) == evalMatrix.shape(0));\n    assert(result.shape(1) == numQuantities());\n    assert(evalMatrix.shape(1) == numBasisFunctions());\n\n    auto mat = data_.subtensor(slice{}, slice{}, eleNo);\n    EigenMap(result) = EigenMap(evalMatrix) * EigenMap(mat);\n}\n\ntemplate <std::size_t D>\nTensorBase<Tensor<double, 3u>>\nFiniteElementFunction<D>::gradientResultInfo(std::size_t numPoints) const {\n    return TensorBase<Tensor<double, 3u>>(numPoints, numQuantities(), D);\n}\n\ntemplate <std::size_t D>\nvoid FiniteElementFunction<D>::gradient(std::size_t eleNo, Tensor<double, 3u> const& evalTensor,\n                                        Tensor<double, 3u> const& jInvAtP,\n                                        Tensor<double, 3u>& result) const {\n    assert(eleNo < numElements());\n    assert(result.shape(0) == evalTensor.shape(0));\n    assert(result.shape(1) == numQuantities());\n    assert(result.shape(2) == D);\n    assert(evalTensor.shape(1) == numBasisFunctions());\n    assert(evalTensor.shape(2) == D);\n    assert(jInvAtP.shape(0) == D);\n    assert(jInvAtP.shape(1) == D);\n    assert(jInvAtP.shape(2) == result.shape(0));\n\n    auto mat = data_.subtensor(slice{}, slice{}, eleNo);\n    for (std::ptrdiff_t j = 0; j < evalTensor.shape(2); ++j) {\n        auto d_j = evalTensor.subtensor(slice{}, slice{}, j);\n        auto result_j = result.subtensor(slice{}, slice{}, j);\n        EigenMap(result_j) = EigenMap(d_j) * EigenMap(mat);\n    }\n\n    for (std::ptrdiff_t q = 0; q < result.shape(0); ++q) {\n        auto jInvAtP_q = jInvAtP.subtensor(slice{}, slice{}, q);\n        auto result_q = result.subtensor(q, slice{}, slice{});\n        EigenMap(result_q) = EigenMap(result_q) * EigenMap(jInvAtP_q);\n    }\n}\n\ntemplate <std::size_t D> std::string FiniteElementFunction<D>::name(std::size_t q) const {\n    assert(q < numQuantities());\n    if (!names_.empty()) {\n        return names_[q];\n    }\n    char buf[100];\n    snprintf(buf, sizeof(buf), \"q%lu\", q);\n    return std::string(buf);\n}\n\ntemplate class FiniteElementFunction<1ul>;\ntemplate class FiniteElementFunction<2ul>;\ntemplate class FiniteElementFunction<3ul>;\n\n} // namespace tndm\n", "meta": {"hexsha": "75f2b33bc9fd9ca52a6869526095e8355ab411a0", "size": 3177, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/form/FiniteElementFunction.cpp", "max_stars_repo_name": "NicoSchlw/tandem", "max_stars_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T17:11:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:51:01.000Z", "max_issues_repo_path": "src/form/FiniteElementFunction.cpp", "max_issues_repo_name": "NicoSchlw/tandem", "max_issues_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-05-18T14:51:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T12:56:31.000Z", "max_forks_repo_path": "src/form/FiniteElementFunction.cpp", "max_forks_repo_name": "NicoSchlw/tandem", "max_forks_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-23T08:04:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T12:23:59.000Z", "avg_line_length": 35.3, "max_line_length": 100, "alphanum_fraction": 0.6591123702, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5043064283251434}}
{"text": "/*\n [auto_generated]\n boost/numeric/odeint/stepper/implicit_euler.hpp\n\n [begin_description]\n Impementation of the implicit Euler method. Works with ublas::vector as state type.\n [end_description]\n\n Copyright 2010-2012 Mario Mulansky\n Copyright 2010-2012 Karsten Ahnert\n Copyright 2012 Christoph Koke\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#ifndef BOOST_NUMERIC_ODEINT_STEPPER_IMPLICIT_EULER_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_STEPPER_IMPLICIT_EULER_HPP_INCLUDED\n\n\n#include <iostream>\n#include <utility>\n\n\n#include <boost/numeric/odeint/external/eigen/eigen_resize.hpp>\n#include <boost/numeric/odeint/external/eigen/eigen_algebra.hpp>\n\n#include <boost/numeric/odeint/util/bind.hpp>\n#include <boost/numeric/odeint/util/unwrap_reference.hpp>\n#include <boost/numeric/odeint/stepper/stepper_categories.hpp>\n\n#include <boost/numeric/odeint/util/is_resizeable.hpp>\n#include <boost/numeric/odeint/util/resizer.hpp>\n#include <boost/numeric/odeint/util/state_wrapper.hpp>\n\n\n#include<Eigen/IterativeLinearSolvers>\n#include <Eigen/PardisoSupport>\n#include <Eigen/Sparse>\n#include<Eigen/SparseQR>\n\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\n\n\ntemplate< class ValueType , class Resizer = initially_resizer >\nclass implicit_euler\n{\n\npublic:\n\n    typedef ValueType value_type;\n    typedef value_type time_type;\n    typedef Eigen::Matrix<value_type, Eigen::Dynamic, 1> state_type;\n    typedef state_wrapper< state_type > wrapped_state_type;\n    typedef state_type deriv_type;\n    typedef state_wrapper< deriv_type > wrapped_deriv_type;\n    typedef Eigen::SparseMatrix<value_type> matrix_type;\n    typedef state_wrapper< matrix_type > wrapped_matrix_type;\n    typedef Resizer resizer_type;\n    typedef stepper_tag stepper_category;\n    typedef implicit_euler< ValueType , Resizer > stepper_type;\n\n    implicit_euler( value_type epsilon = 1E-6 )\n    : m_epsilon( epsilon ) \n    { }\n\n\n    template< class System >\n    void do_step( System system , state_type &x , time_type t , time_type dt )\n    {\n        typedef typename odeint::unwrap_reference< System >::type system_type;\n        typedef typename odeint::unwrap_reference< typename system_type::first_type >::type deriv_func_type;\n        typedef typename odeint::unwrap_reference< typename system_type::second_type >::type jacobi_func_type;\n        system_type &sys = system;\n        deriv_func_type &deriv_func = sys.first;\n        jacobi_func_type &jacobi_func = sys.second;\n\n        m_resizer.adjust_size( x , detail::bind( &stepper_type::template resize_impl<state_type> , detail::ref( *this ) , detail::_1 ) );\n\n        t += dt;\n\n        // apply first Newton step\n        deriv_func( x , m_dxdt.m_v , t );\n\n        m_b.m_v = dt * m_dxdt.m_v;\n\n        jacobi_func( x , m_jacobi.m_v  , t );\n        matrix_type m_identity(x.size(), x.size());\n        m_identity.setIdentity();        \n        m_jacobi.m_v *= dt;\n        m_jacobi.m_v -= m_identity;\n        Eigen::PardisoLU<matrix_type> solver(m_jacobi.m_v);\n\n        m_b.m_v = solver.solve(m_b.m_v).eval();\n\n        m_x.m_v = x - m_b.m_v;\n\n        // iterate Newton until some precision is reached\n        // ToDo: maybe we should apply only one Newton step -> linear implicit one-step scheme\n        while(m_b.m_v.squaredNorm() > m_epsilon )\n        {\n            deriv_func( m_x.m_v , m_dxdt.m_v , t );\n            m_b.m_v = x - m_x.m_v + dt*m_dxdt.m_v;\n\n            // simplified version, only the first Jacobian is used\n            //            jacobi( m_x , m_jacobi , t );\n            //            m_jacobi *= dt;\n            //            m_jacobi -= boost::numeric::ublas::identity_matrix< value_type >( x.size() );\n\n            m_b.m_v = solver.solve(m_b.m_v).eval();\n            m_x.m_v -= m_b.m_v;\n        }\n        x = m_x.m_v;\n    }\n\n    template< class StateType >\n    void adjust_size( const StateType &x )\n    {\n        resize_impl( x );\n    }\n\n\nprivate:\n\n    template< class StateIn >\n    bool resize_impl( const StateIn &x )\n    {\n        bool resized = false;\n        resized |= adjust_size_by_resizeability( m_dxdt , x , typename is_resizeable<deriv_type>::type() );\n        resized |= adjust_size_by_resizeability( m_x , x , typename is_resizeable<state_type>::type() );\n        resized |= adjust_size_by_resizeability( m_b , x , typename is_resizeable<deriv_type>::type() );\n        resized |= adjust_size_by_resizeability( m_jacobi , x , typename is_resizeable<matrix_type>::type() );\n        return resized;\n    }\n\nprivate:\n\n    value_type m_epsilon;\n    resizer_type m_resizer;\n    wrapped_deriv_type m_dxdt;\n    wrapped_state_type m_x;\n    wrapped_deriv_type m_b;\n    wrapped_matrix_type m_jacobi;\n};\n\n\n} // odeint\n} // numeric\n} // boost\n\n\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_IMPLICIT_EULER_HPP_INCLUDED\n", "meta": {"hexsha": "b0e82d49529262ddbee05412678cff7dadbe14ee", "size": 4869, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/headers/implicit_euler.hpp", "max_stars_repo_name": "mjdousti/therminator", "max_stars_repo_head_hexsha": "d706ab43ac97a4266ce19618b1e35d4e0245cd5b", "max_stars_repo_licenses": ["Xnet", "X11", "RSA-MD"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-09-26T00:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-09T03:19:38.000Z", "max_issues_repo_path": "src/headers/implicit_euler.hpp", "max_issues_repo_name": "mjdousti/therminator", "max_issues_repo_head_hexsha": "d706ab43ac97a4266ce19618b1e35d4e0245cd5b", "max_issues_repo_licenses": ["Xnet", "X11", "RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/headers/implicit_euler.hpp", "max_forks_repo_name": "mjdousti/therminator", "max_forks_repo_head_hexsha": "d706ab43ac97a4266ce19618b1e35d4e0245cd5b", "max_forks_repo_licenses": ["Xnet", "X11", "RSA-MD"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-08-03T01:41:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-06T18:14:11.000Z", "avg_line_length": 30.6226415094, "max_line_length": 137, "alphanum_fraction": 0.6890531937, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5042554968355749}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// Copyright 2010 Manuel Peinado Gallego                                     //\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#include <ctime>\n#include <algorithm>\n#include <string>\n#include <vector>\n#include <iterator>\n#include <cstdlib>\n#include <boost/bind.hpp>\n#include <libs/assign/v2/speed/tools.h>\n\n// http://code.google.com/p/truffle/source/browse/trunk/include/mpg/TimeIt.h\n// http://code.google.com/p/truffle/source/browse/trunk/include/mpg/Random.h\n\n// http://www.eternallyconfuzzled.com/arts/jsw_art_rand.aspx\ninline double uniform_deviate ( int seed )\n{\n    return seed * ( 1.0 / ( RAND_MAX + 1.0 ) );\n}\ninline int rand(int M, int N) // Range [M..N)\n{\n    return int(M + uniform_deviate(std::rand()) * (N - M));\n}\nchar rand_letter()\n{\n    return char(rand('a', 'z' + 1));\n}\n\nstd::string rand_str(int len)\n{\n    std::string result;\n    std::generate_n(std::back_inserter(result), len, &rand_letter);\n    return result;\n}\n\nstd::vector<int>\nrand_vec(int max_n)\n{\n    std::vector<int> result(\n        (std::size_t)mpg::rand(1, max_n)\n    );\n    std::generate(\n        result.begin(),\n        result.end(),\n        boost::bind(\n            &mpg::rand,\n            0,\n            20\n        )\n    );\n    return result;\n}\n\nnamespace mpg\n{\n    namespace detail\n    {\n        double clock_diff_to_sec(long clock_diff)\n        {\n            return double(clock_diff) / CLOCKS_PER_SEC;\n        }\n\n        template<class Proc>\n        double time_it_impl(Proc proc, int N) // returns time in microseconds\n        {\n            std::clock_t const start = std::clock();\n            for(int i = 0; i < N; ++i)\n                proc();\n            std::clock_t const end = std::clock();\n            if(clock_diff_to_sec(end - start) < .2)\n                return time_it_impl(proc, N * 5);\n            return clock_diff_to_sec(end - start) * (1e6 / N);\n        }\n\n        template<class Proc, class Result>\n        double time_it_impl(Proc proc, Result & result, int N) // returns time in microseconds\n        {\n            std::clock_t const start = std::clock();\n            for(int i = 0; i < N; ++i)\n                result = proc();\n            std::clock_t const end = std::clock();\n            if(clock_diff_to_sec(end - start) < .2)\n                return time_it_impl(proc, result, N * 5);\n            return clock_diff_to_sec(end - start) * (1e6 / N);\n        }\n    }\n\n    template<class Proc>\n    double time_it(Proc proc) // returns time in microseconds\n    {\n        return detail::time_it_impl(proc, 1);\n    }\n\n    template<class Proc, class Result>\n    double time_it(Proc proc, Result & result) // returns time in microseconds\n    {\n        return detail::time_it_impl(proc, result, 1);\n    }\n}\n\nnamespace mpg\n{\n    inline double rand_dbl()\n    {\n        return double(::rand()) / RAND_MAX;\n    }\n\n    inline double rand_dbl(double M, double N)\n    {\n        return M + rand_dbl() * (N - M);\n    }\n\n    // http://www.eternallyconfuzzled.com/arts/jsw_art_rand.aspx\n    inline int rand(int M, int N) // Range (M..N)\n    {\n        return int(M + std::rand() * ( 1.0 / ( RAND_MAX + 1.0 )) * (N - M));\n    }\n\n    inline char rand_letter()\n    {\n        return char(rand('a', 'z' + 1));\n    }\n\n    inline std::string rand_str(int len)\n    {\n        std::string result;\n        result.reserve(len);\n        for(int i = 0; i < len; ++i)\n            result.push_back(rand_letter());\n        return result;\n    }\n}\n\n\n", "meta": {"hexsha": "38f3ed6d74edc2ff689deff592ba87296c98c9f6", "size": 3771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/assign/v2/speed/tools.cpp", "max_stars_repo_name": "rogard/assign_v2", "max_stars_repo_head_hexsha": "8735f57177dbee57514b4e80c498dd4b89f845e5", "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/assign/v2/speed/tools.cpp", "max_issues_repo_name": "rogard/assign_v2", "max_issues_repo_head_hexsha": "8735f57177dbee57514b4e80c498dd4b89f845e5", "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/assign/v2/speed/tools.cpp", "max_forks_repo_name": "rogard/assign_v2", "max_forks_repo_head_hexsha": "8735f57177dbee57514b4e80c498dd4b89f845e5", "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.1294964029, "max_line_length": 94, "alphanum_fraction": 0.5295677539, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5042554964089211}}
{"text": "/**\n   \\file gsl_simplex.hpp\n   \\brief a simple wrapper for the GSL_SIMPLEX method\n   \\author Junhua Gu\n */\n\n#ifndef GSL_SIMPLEX_METHOD\n#define GSL_SIMPLEX_METHOD\n#define OPT_HEADER\n#include <core/optimizer.hpp>\n//#include <blitz/array.h>\n#include <vector>\n#include <limits>\n#include <cassert>\n#include <cmath>\n#include <algorithm>\n#include <gsl/gsl_multimin.h>\n#include <iostream>\n\n\nnamespace opt_utilities\n{\n\n  /**\n     \\brief object function of the gsl simplex function\n   */\n  template <typename rT,typename pT>\n  double gsl_func_adapter(const gsl_vector* v,void* params)\n  {\n    pT temp;\n    temp.resize(v->size);\n    for(size_t i=0;i<get_size(temp);++i)\n      {\n\tset_element(temp,i,gsl_vector_get(v,i));\n      }\n    return ((func_obj<rT,pT>*)params)->eval(temp);\n  }\n\n\n  /**\n     \\brief wrapper for the gsl simplex optimization method\n     \\tparam return type of the object function\n     \\tparam param type of the object function\n  */\n  template <typename rT,typename pT>\n  class gsl_simplex\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    \n    //typedef blitz::Array<rT,2> array2d_type;\n    \n    \n  private:\n    array1d_type start_point;\n    array1d_type end_point;\n    \n  private:\n    rT threshold;\n  private:\n    rT func(const pT& x)\n    {\n      assert(p_fo!=0);\n      return p_fo->eval(x);\n    }\n\n    const char* do_get_type_name()const\n    {\n      return \"gsl simplex\";\n    }\n  public:\n    gsl_simplex()\n      :threshold(1e-4)\n    {}\n\n    virtual ~gsl_simplex()\n    {\n    };\n\n    gsl_simplex(const gsl_simplex<rT,pT>& rhs)\n      :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)\n    {\n    }\n\n    gsl_simplex<rT,pT>& operator=(const gsl_simplex<rT,pT>& rhs)\n    {\n      threshold=rhs.threshold;\n      p_fo=rhs.p_fo;\n      p_optimizer=rhs.p_optimizer;\n      opt_eq(start_point,rhs.start_point);\n      opt_eq(end_point,rhs.end_point);\n    }\n    \n    opt_method<rT,pT>* do_clone()const\n    {\n      return new gsl_simplex<rT,pT>(*this);\n    }\n    \n    void do_set_start_point(const array1d_type& p)\n    {\n      start_point.resize(get_size(p));\n      opt_eq(start_point,p);\n      \n    }\n\n    array1d_type do_get_start_point()const\n    {\n      return start_point;\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      const gsl_multimin_fminimizer_type *T = \n\tgsl_multimin_fminimizer_nmsimplex;\n      gsl_multimin_fminimizer *s = NULL;\n      gsl_vector *ss, *x;\n      gsl_multimin_function minex_func;\n      \n      size_t iter = 0;\n      int status;\n      double size;\n      \n      /* Starting point */\n      x = gsl_vector_alloc (get_size(start_point));\n      //      gsl_vector_set (x, 0, 5.0);\n      //gsl_vector_set (x, 1, 7.0);\n      for(size_t i=0;i!=get_size(start_point);++i)\n\t{\n\t  gsl_vector_set(x,i,get_element(start_point,i));\n\t}\n\n\n      /* Set initial step sizes to 1 */\n      ss = gsl_vector_alloc (get_size(start_point));\n      gsl_vector_set_all (ss, 1.0);\n\n\n      //foo f;\n      /* Initialize method and iterate */\n      minex_func.n = get_size(start_point);\n      minex_func.f = &gsl_func_adapter<double,std::vector<double> >;\n      minex_func.params = (void *)p_fo;\n      \n      s = gsl_multimin_fminimizer_alloc (T, get_size(start_point));\n      gsl_multimin_fminimizer_set (s, &minex_func, x, ss);\n      \n      do\n\t{\n\t  iter++;\n\t  status = gsl_multimin_fminimizer_iterate(s);\n\t  \n\t  if (status) \n\t    {\n\t      break;\n\t    }\n\t  //std::cerr<<\"threshold=\"<<threshold<<std::endl;\n\t  size = gsl_multimin_fminimizer_size (s);\n\t  status = gsl_multimin_test_size (size, threshold);\n\t  \n\t  if (status == GSL_SUCCESS)\n\t    {\n\t      //printf (\"converged to minimum at\\n\");\n\t    }\n\t  \n\t  //printf (\"%5d %10.3e %10.3ef f() = %7.3f size = %.3f\\n\", \n\t  //iter,\n\t  //gsl_vector_get (s->x, 0), \n\t  //gsl_vector_get (s->x, 1), \n\t  //  s->fval, size);\n\t}\n      while (status == GSL_CONTINUE);\n      \n      /*\n\tfoo f;\n\tgsl_vector_set (x, 0, 0.0);\n\tgsl_vector_set (x, 1, 0.0);\n\tcout<<\"fdsa \";\n\tcout<<gsl_func_adapter<double,vector<double> >(x,(void*)&f)<<endl;;\n\t\n      */\n      \n      end_point.resize(get_size(start_point));\n      for(size_t i=0;i<get_size(start_point);++i)\n\t{\n\t  set_element(end_point,i,gsl_vector_get(s->x,i));\n\t}\n\n      gsl_vector_free(x);\n      gsl_vector_free(ss);\n      gsl_multimin_fminimizer_free (s);\n      \n      \n      return end_point;\n    } \n  };\n  \n}\n\n\n#endif\n//EOF\n", "meta": {"hexsha": "a8a72d1733a6cbeab8befdee677cfe279ee1c627", "size": 4774, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "methods/gsl_simplex/gsl_simplex.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/gsl_simplex/gsl_simplex.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/gsl_simplex/gsl_simplex.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": 20.9385964912, "max_line_length": 68, "alphanum_fraction": 0.6087138668, "num_tokens": 1357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800692021119887, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.5042554921251398}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE ForwardBackward\n#include <boost/test/unit_test.hpp>\n#include <HSMM.hpp>\n#include <ForwardBackward.hpp>\n#include <memory>\n#include <exception>\n#include <set>\n\n#define EPSILON 1e-6\n\nusing namespace arma;\nusing namespace hsmm;\nusing namespace std;\n\nmat transition = {{0.0, 0.1, 0.4, 0.5},\n                  {0.3, 0.0, 0.6, 0.1},\n                  {0.2, 0.2, 0.0, 0.6},\n                  {0.4, 0.4, 0.2, 0.0}};\n\nmat duration = {{0.0, 0.1, 0.4, 0.5},\n                {0.3, 0.0, 0.6, 0.1},\n                {0.2, 0.2, 0.0, 0.6},\n                {0.4, 0.4, 0.2, 0.0}};\n\nint min_duration = 4;\n\nvec pi = {0.25, 0.25, 0.25, 0.25};\n\nint ndurations = duration.n_cols;\n\nint nstates = duration.n_rows;\n\n// Emission parameters.\nvec means = {0, 5, 10, 15};\nvec std_devs =  {0.5, 1.0, 0.1, 2.0};\n\nBOOST_AUTO_TEST_CASE( ForwardBackwardWithLabels ) {\n    shared_ptr<AbstractEmission> ptr_emission(new DummyGaussianEmission(\n            means, std_devs));\n    HSMM dhsmm(ptr_emission, transition, pi, duration, min_duration);\n    ivec hiddenStates, hiddenDurations;\n    int nSampledSegments = 50;\n    field<mat> samples = dhsmm.sampleSegments(nSampledSegments, hiddenStates,\n            hiddenDurations);\n    int nobs = samples.n_elem;\n\n    // Output parameters of the Forward-Backward algorithm.\n    mat alpha(nstates, nobs, fill::zeros);\n    mat beta(nstates, nobs, fill::zeros);\n    mat alpha_s(nstates, nobs, fill::zeros);\n    mat beta_s(nstates, nobs, fill::zeros);\n    vec beta_s_0(nstates, fill::zeros);\n    cube eta(nstates, ndurations, nobs, fill::zeros);\n    cube zeta(nstates, nstates, nobs - 1, fill::zeros);\n\n    cube logpdf = dhsmm.computeEmissionsLogLikelihood(samples);\n    Labels full_labels;\n    Labels sparse_labels;\n    set<int> sparse_segment_ids = {10, 30, 40, 45};\n\n    // Required for generating the runs of unobserved segments.\n    vector<pair<int, int>> seq_unobserved_segments;\n    int starting_unobserved_segment_idx = 0;\n\n    int current_idx = 0;\n    double expected_llikelihood_fulllabels = 0;\n    for(int i = 0; i < nSampledSegments; i++) {\n        int hs = hiddenStates(i);\n        int d = hiddenDurations(i);\n        expected_llikelihood_fulllabels += logpdf(hs, current_idx,\n                d - min_duration) + log(duration(hs, d - min_duration));\n        if (i == 0)\n            expected_llikelihood_fulllabels += log(pi(hs));\n        else\n            expected_llikelihood_fulllabels += log(transition(hiddenStates(\n                            i - 1), hs));\n        int starting_idx = current_idx;\n        current_idx += d;\n        int ending_idx = current_idx - 1;\n        full_labels.setLabel(ending_idx, d, hs);\n        if (sparse_segment_ids.find(i) != sparse_segment_ids.end()) {\n            sparse_labels.setLabel(ending_idx, d, hs);\n            seq_unobserved_segments.push_back(make_pair(\n                    starting_unobserved_segment_idx, starting_idx - 1));\n            starting_unobserved_segment_idx = ending_idx + 1;\n        }\n    }\n    seq_unobserved_segments.push_back(make_pair(starting_unobserved_segment_idx,\n                current_idx - 1));\n\n    // Testing with full labels.\n    logsFB(log(transition), log(pi), log(duration), logpdf, full_labels,\n            alpha, beta, alpha_s, beta_s, beta_s_0, eta, zeta, min_duration,\n            nobs);\n    eta = exp(eta);\n    zeta = exp(zeta);\n    double llikelihood = logsumexp(alpha.col(nobs - 1));\n\tBOOST_CHECK(fabs(llikelihood - expected_llikelihood_fulllabels) < EPSILON);\n    current_idx = 0;\n    for(int i = 0; i < nSampledSegments - 1; i++) {\n        int hs = hiddenStates(i);\n        int next_hs = hiddenStates(i + 1);\n        int d = hiddenDurations(i);\n        current_idx += d;\n\n        // Checking that the observed transitions have probability one and the\n        // rest have zero probability.\n        for(int j = 0; j < nstates; j++)\n            for(int k = 0; k < nstates; k++)\n                if (j == hs && k == next_hs)\n                    BOOST_CHECK(fabs(zeta(j, k, current_idx - 1) - 1.0) < EPSILON);\n                else\n                    BOOST_CHECK(fabs(zeta(j, k, current_idx - 1) - 0.0) < EPSILON);\n    }\n\n    // Testing with sparse labels.\n    logsFB(log(transition), log(pi), log(duration), logpdf, sparse_labels,\n            alpha, beta, alpha_s, beta_s, beta_s_0, eta, zeta, min_duration,\n            nobs);\n    eta = exp(eta);\n    zeta = exp(zeta);\n    for(auto p : seq_unobserved_segments) {\n        double sum_starting = 0;\n        double sum_ending = 0;\n        int start_seg = p.first;\n        int end_seg = p.second;\n        for(int i = 0; i < nstates; i++)\n            for(int d = 0; d < ndurations; d++) {\n                sum_starting += eta(i, d, start_seg + min_duration + d - 1);\n                sum_ending += eta(i, d, end_seg);\n            }\n\n        // There must be a segment which explains the starting part of an\n        // unobserved run.\n        BOOST_CHECK(fabs(sum_starting - 1.0) < EPSILON);\n\n        // The same applies for the ending part.\n        BOOST_CHECK(fabs(sum_ending - 1.0) < EPSILON);\n    }\n\n    current_idx = 0;\n    for(int i = 0; i < nSampledSegments; i++) {\n        int hs = hiddenStates(i);\n        int d = hiddenDurations(i);\n        int starting_idx = current_idx;\n        current_idx += d;\n        int ending_idx = current_idx - 1;\n        if (sparse_segment_ids.find(i) != sparse_segment_ids.end()) {\n\n            // Checking that the provided labels apper as ones in eta.\n            BOOST_CHECK(fabs(eta(hs, d - min_duration, ending_idx) - 1) <\n                    EPSILON);\n            for(int j = 0; j < nstates; j++) {\n\n                double sum_eta_last = 0;\n                double sum_eta_first = 0;\n                for(int k = 0; k < ndurations; k++) {\n                    sum_eta_last += eta(j, k, starting_idx - 1);\n                    sum_eta_first += eta(j, k, ending_idx + 1);\n                }\n\n                // Checking that the expected transition from an unobserved\n                // state to an observed one (or viceversa) is equal to the\n                // expected value of being in the unobserved state.\n                BOOST_CHECK(fabs(sum_eta_last - zeta(j, hs, starting_idx - 1))\n                        < EPSILON);\n                BOOST_CHECK(fabs(sum_eta_first - zeta(hs, j, ending_idx + 1))\n                        < EPSILON);\n\n                // Checking that unfeasible transitions have 0 posterior mass.\n                for(int k = 0; k < nstates; k++)\n                    if (k != hs)\n                        BOOST_CHECK(zeta(j, k, starting_idx - 1) < EPSILON &&\n                                zeta(k, j, ending_idx + 1) < EPSILON);\n\n            }\n        }\n    }\n\n    // Checking that the expected number of segments in the observation\n    // sequence is equal to the actual value. This is expected because\n    // the actual parameters are used for inference.\n    BOOST_CHECK(fabs(accu(eta) - nSampledSegments) < EPSILON);\n}\n\nBOOST_AUTO_TEST_CASE( LogSumExp ) {\n    int n = 10;\n    vec ones_v = ones<vec>(n);\n    double sum = exp(logsumexp(log(ones_v)));\n    BOOST_CHECK(fabs(sum - n) < EPSILON);\n    int nzeros = 3;\n    ones_v.subvec(0, nzeros - 1).fill(0.0);\n    sum = exp(logsumexp(log(ones_v)));\n    BOOST_CHECK(fabs(sum - (n-nzeros)) < EPSILON);\n}\n\n", "meta": {"hexsha": "79818fea61e7ab4645200d8a5a2b75bd70893791", "size": 7300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/FB_test.cpp", "max_stars_repo_name": "DiegoAE/BOSD", "max_stars_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-05-03T05:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:14:31.000Z", "max_issues_repo_path": "tests/FB_test.cpp", "max_issues_repo_name": "DiegoAE/BOSD", "max_issues_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T15:29:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T10:14:54.000Z", "max_forks_repo_path": "tests/FB_test.cpp", "max_forks_repo_name": "DiegoAE/BOSD", "max_forks_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T07:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T07:44:09.000Z", "avg_line_length": 36.8686868687, "max_line_length": 83, "alphanum_fraction": 0.5826027397, "num_tokens": 1997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5042554912718334}}
{"text": "\ufeff//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// See LICENSE file in the project root for full license information.\n//\n\n#include \"RefFakeQuantizationFloat32Workload.hpp\"\n\n#include \"RefWorkloadUtils.hpp\"\n\n#include \"Profiling.hpp\"\n\n#include <boost/numeric/conversion/cast.hpp>\n\nnamespace armnn\n{\n\nvoid FakeQuantization(const float* inputData, float* outputData, uint32_t numElements, float min, float max)\n{\n    float scale = (max - min) / 255.f;\n    int32_t offset = boost::numeric_cast<int32_t>((-min * 255.f) / (max - min));\n\n    for (uint32_t i = 0; i < numElements; i++)\n    {\n        outputData[i] = static_cast<float>(armnn::Quantize<uint8_t>(inputData[i], scale, offset));\n    }\n\n}\n\nvoid RefFakeQuantizationFloat32Workload::Execute() const\n{\n    ARMNN_SCOPED_PROFILING_EVENT(Compute::CpuRef, \"RefFakeQuantizationFloat32Workload_Execute\");\n\n    const TensorInfo& inputInfo = GetTensorInfo(m_Data.m_Inputs[0]);\n\n    const float* inputData = GetInputTensorDataFloat(0, m_Data);\n    float* outputData = GetOutputTensorDataFloat(0, m_Data);\n    FakeQuantization(inputData, outputData, inputInfo.GetNumElements(),\n                     m_Data.m_Parameters.m_Min,\n                     m_Data.m_Parameters.m_Max);\n}\n\n} //namespace armnn\n", "meta": {"hexsha": "483fa7e00ee78d6be7f47f76c9542233a77fdcae", "size": 1242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/armnn/backends/RefWorkloads/RefFakeQuantizationFloat32Workload.cpp", "max_stars_repo_name": "KevinRodrigues05/armnn_caffe2_parser", "max_stars_repo_head_hexsha": "c577f2c6a3b4ddb6ba87a882723c53a248afbeba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-19T08:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-19T08:44:28.000Z", "max_issues_repo_path": "src/armnn/backends/RefWorkloads/RefFakeQuantizationFloat32Workload.cpp", "max_issues_repo_name": "KevinRodrigues05/armnn_caffe2_parser", "max_issues_repo_head_hexsha": "c577f2c6a3b4ddb6ba87a882723c53a248afbeba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/armnn/backends/RefWorkloads/RefFakeQuantizationFloat32Workload.cpp", "max_forks_repo_name": "KevinRodrigues05/armnn_caffe2_parser", "max_forks_repo_head_hexsha": "c577f2c6a3b4ddb6ba87a882723c53a248afbeba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-11T05:58:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-11T05:58:56.000Z", "avg_line_length": 28.8837209302, "max_line_length": 108, "alphanum_fraction": 0.7093397746, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839874, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5042554908451796}}
{"text": "#include <iostream>\n#include <vector>\n#include <functional>\n#include <cassert>\n#include <cmath>\n#include <chrono>\n#include <NTL/matrix.h>\n#include <NTL/ZZ_pX.h> // includes ZZ_p.h and ZZ.h as well\n\nusing std::vector;\nusing namespace std::chrono;\nusing NTL::Mat;\nusing NTL::ZZ_p;\nusing NTL::ZZ_pX;\nusing NTL::ZZ;\n\n\n// TODO: add return type to final algorithm\n\n// Reference: https://www.dropbox.com/home/urop2019/literature?preview=Bostan%2C+Gaudry%2C+Schost+-+Linear+recurrences+with+polynomial+coefficients+and+application+to+integer+factorization+and+Cartier-Manin+operator.pdf\n// Page 1781 (Lemma 1)\nvoid invert_all(vector<ZZ_p> &out, vector<ZZ_p> &a);\n// Page 1781 (Lemma 2)\nvoid find_delta(vector<ZZ_p> &out, ZZ &p);\nvoid find_delta(vector<ZZ_p> &out, ZZ &p, ZZ_p &a);\n// Page 1784-5 (Theorem 5)\nvoid shift_values(vector<ZZ_p> &out, vector<ZZ_p> &values, ZZ_p &a, ZZ_p &b, ZZ &p);\nvoid shift_values(vector<Mat<ZZ_p>> &out, vector<Mat<ZZ_p>> &values, ZZ_p &a, ZZ_p &b, ZZ &p);\n// Page 1786-8 (Section 4)\nvoid multieval_prod(vector<Mat<ZZ_p>> &out, std::function<void (Mat<ZZ_p>&, ZZ_p&)> A, ZZ &p);\nvoid multieval_prod(vector<Mat<ZZ_p>> &out, ZZ_p &k, std::function<void (Mat<ZZ_p>&, ZZ_p&)> A, ZZ &p);\n// Page 1792 (Equation (5))\nvoid matrix_factorial(Mat<ZZ_p> &out, long n, std::function<void (Mat<ZZ_p>&, ZZ_p&)> A, ZZ &p);\n// Following functions for testing:\n// matrix definition\nvoid A(Mat<ZZ_p> &out, ZZ_p &x);\n// print contents of a vector\ntemplate <typename T>\nvoid print(vector<T> vec);\n\n\n/*\n * Evaluate M(x), returned in out\n */\nvoid A(Mat<ZZ_p> &out, ZZ_p &x){\n    ZZ_p zero;\n    zero.init(x.modulus());\n    zero = 0;\n    ZZ_p one;\n    one.init(x.modulus());\n    one = 1;\n    /*out.SetDims(2, 2);\n    out.put(0, 0, x+1);\n    out.put(0, 1, zero);\n    out.put(1, 0, one);\n    out.put(1, 1, one);\n    */\n    out.SetDims(1, 1);\n    out.put(0, 0, x);\n\n}\n\nint main(){\n    std::function<void (Mat<ZZ_p>&, ZZ_p&)> A_func = A;\n\n    Mat<ZZ_p> answer;\n    for(long i = 1073741824; i <= 1073741824; i*=2){\n        ZZ p;\n        NextPrime(p, ZZ(i));\n        long p1;\n        conv(p1, p-1);\n        mul(p, p, p);\n        uint64_t start = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n        matrix_factorial(answer, p1, A_func, p);\n        uint64_t time = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count() - start;\n\n        std::cout << \"final answer: \" << answer << std::endl;\n        //std::cout << time << \", \";\n    }\n    std::cout << std::endl;\n    \n}\n\ntemplate<typename T>\nvoid print(vector<T> vec){\n    for(long i = 0; i < vec.size(); i++){\n        std::cout << vec[i];\n        if(i < vec.size()-1){\n            std::cout << \", \";\n        }\n    }\n    std::cout << std::endl;\n}\n\n/* \n * Steps:\n * [DONE] Create function that take inputs a0, a1, ..., an-1 and outputs 1/a0, ..., 1/an-1\n * [DONE] Create function that takes input d and outputs 1/prod(0-j), 1/prod(1-j), ..., 1/prod(d-j)\n * [DONE] Create function that takes input a, d and outputs prod(a+0-j), prod(a+1-j), ..., prod(a+d-j)\n * [DONE] Create function that take inputs M(a), M(a+b), ..., M(a+kb) and outputs M(a+i), M(a+b+i), ..., M(a+kb+i)\n * [DONE] Create function to calculate M_k(0), M_k(k), ..., M_k(k^2)\n * [DONE] Create main function to calculate M(1)...M(k^2) = M_k(0)M_k(k)...M_k(k^2-k)\n */\n\n\n/*\n * Takes a list of elements a and returns their inversions mod p\n */\nvoid invert_all(vector<ZZ_p> &out, vector<ZZ_p> &a){\n    assert(out.size() == a.size());\n\n    long n = a.size();\n    vector<ZZ_p> inverses(n);\n\n    vector<ZZ_p> accum_prod(n); // a0, a0a1, ..., a0a1...an-1\n\n    accum_prod[0] = a[0];\n    for(long i = 1; i < n; i++){\n        mul(accum_prod[i], accum_prod[i-1], a[i]);\n    }\n\n    inv(accum_prod[n-1], accum_prod[n-1]);\n    for(long i = n-1; i > 0; i--){\n        mul(inverses[i], accum_prod[i], accum_prod[i-1]); // 1/ai = 1/(a1...ai) * a1...a(i-1)\n        mul(accum_prod[i-1], accum_prod[i], a[i]); // a1...a(i-1) -> 1/(a1...a(i-1))\n    }\n    inverses[0] = accum_prod[0];\n    \n    out = inverses;\n}\n\n/*\n * d = out.size()-1;\n * Returns 1/delta(i, d) = 1/prod(i-j) where the product goes from j=0 to d skipping i.\n */\nvoid find_delta(vector<ZZ_p> &out, ZZ &p){\n    long d = out.size() - 1;\n    vector<ZZ_p> ints(d);\n    for(long i = 0; i < ints.size(); i++){\n        ints[i].init(p);\n        ints[i] = i+1;\n    }\n    vector<ZZ_p> inv_ints(d);\n    invert_all(inv_ints, ints);\n    \n    vector<ZZ_p> deltas(d+1);\n    deltas[0] = inv_ints[0]; // = 1\n    for(long i = 1; i < inv_ints.size(); i++){\n        mul(deltas[0], deltas[0], inv_ints[i]);\n    } // deltas[0] = 1/d!\n    \n    if(d%2 == 1){\n        deltas[0] = -deltas[0]; // deltas[0] = 1/((-1)^d*d!)\n    }\n\n    for(long i = 1; i < deltas.size(); i++){\n        mul(deltas[i], deltas[i-1], i-1-d);\n        mul(deltas[i], deltas[i], inv_ints[i-1]);\n    }\n\n    out = deltas;\n}\n\n/*\n * d = out.size()-1;\n * Returns Delta(a, i, d) = prod(a+i-j) where the product goes from j=0 to d.\n */\nvoid find_delta(vector<ZZ_p> &out, ZZ_p &a, ZZ &p){\n    long d = out.size() - 1;\n\n    vector<ZZ_p> ints(d);\n    for(long i = 0; i < ints.size(); i++){\n        ints[i].init(p);\n        ints[i] = a-d+i;\n    }\n    vector<ZZ_p> inv_ints(d);\n    invert_all(inv_ints, ints);\n    \n    vector<ZZ_p> Deltas(d+1);\n    Deltas[0] = a;\n    for(long i = 0; i < inv_ints.size(); i++){\n        mul(Deltas[0], Deltas[0], ints[i]);\n    } // Deltas[0] = (a-d)...(a-1)(a)\n    for(long i = 1; i < Deltas.size(); i++){\n        mul(Deltas[i], Deltas[i-1], a+i);\n        mul(Deltas[i], Deltas[i], inv_ints[i-1]);\n    }\n\n    out = Deltas;\n}\n\n/*\n * Takes in the values of polynomials F(r), F(r+b), ..., F(r+db) and outputs F(r+a), F(r+b+a), ... F(r+db+a)\n * Requires deg(F) <= d to work mathematically, since it will interpolate based on the given evaluations of F.\n */\nvoid shift_values(vector<ZZ_p> &out, vector<ZZ_p> &values, ZZ_p &a, ZZ_p &b, ZZ &p){\n    assert(out.size() == values.size());\n\n    long d = values.size() - 1;\n    vector<ZZ_p> P(d+1);\n    find_delta(P, p);\n    \n    ZZ_pX Px;\n    for(long i = 0; i < values.size(); i++){\n        mul(P[i], P[i], values[i]);\n        SetCoeff(Px, i, P[i]);\n    }\n\n    ZZ_p shift;\n    shift.init(p);\n    inv(shift, b);\n    mul(shift, shift, a); // shift = a/b\n\n    vector<ZZ_p> S(2*d+1);\n    for(long i = 0; i < S.size(); i++){\n        S[i] = shift + i - d;\n    }\n    invert_all(S, S);\n\n    ZZ_pX Sx;\n    for(long i = 0; i < S.size(); i++){\n        SetCoeff(Sx, i, S[i]);\n    }   \n\n    ZZ_pX PS;\n    mul(PS, Px, Sx);\n\n    find_delta(out, shift, p);\n    for(long i = 0; i < out.size(); i++){\n        mul(out[i], out[i], coeff(PS, i+d));\n    }\n}\n\n/*\n * Takes in the values of matrices of polynomials M(r), M(r+b), ..., M(r+db) and outputs M(r+a), M(r+b+a), ... M(r+db+a)\n * Requires the maximal degree of any element of M(x) to be <= d to successfully interpolate\n */\nvoid shift_values(vector<Mat<ZZ_p>> &out, vector<Mat<ZZ_p>> &values, ZZ_p &a, ZZ_p &b, ZZ &p){\n    assert(out.size() == values.size());\n    assert(values[0].NumRows() == values[0].NumCols());\n    for(long i = 0; i < out.size(); i++){\n        assert(values[i].NumRows() == values[0].NumRows());\n        assert(values[i].NumCols() == values[0].NumCols());\n        out[i].SetDims(values[0].NumRows(), values[0].NumCols());\n    } \n\n    for(long row = 0; row < values[0].NumRows(); row++){\n        for(long col = 0; col < values[0].NumCols(); col++){\n            vector<ZZ_p> vals(values.size());\n            for(long i = 0; i < values.size(); i++){\n                vals[i] = values[i].get(row, col);\n            }\n            vector<ZZ_p> shifted_vals(vals.size());\n            shift_values(shifted_vals, vals, a, b, p);\n            for(long i = 0; i < shifted_vals.size(); i++){\n                out[i].put(row, col, shifted_vals[i]);\n            }\n        }\n    }\n}\n\n/*\n * k := out.size()-1\n * Calculates M_k(x) at 0, k, ..., k^2 recursively\n * M_k(x) = M(x+1)M(x+2)...M(x+k)\n * To calculate M_m(x) at 0, k, ..., mk, use the value M_m/2(x) at 0, k, ..., (m/2)k\n */\nvoid multieval_prod(vector<Mat<ZZ_p>> &out, std::function<void (Mat<ZZ_p>&, ZZ_p&)> A, ZZ &p){\n    ZZ_p kp;\n    kp.init(p);\n    kp = out.size()-1;\n    multieval_prod(out, kp, A, p);\n}\n/*\n * m := out.size()-1\n */\nvoid multieval_prod(vector<Mat<ZZ_p>> &out, ZZ_p &k, std::function<void (Mat<ZZ_p>&, ZZ_p&)> A, ZZ &p){\n    long m = out.size()-1;\n    \n    if(m == 1){\n        ZZ_p one;\n        one.init(p);\n        one = 1;\n        ZZ_p kone = k+1;\n        A(out[0], one);\n        A(out[1], kone);\n        return;\n    }\n\n    vector<Mat<ZZ_p>> lower_layer(m/2+1);\n    multieval_prod(lower_layer, k, A, p);\n   \n    vector<Mat<ZZ_p>> ll_extend(lower_layer.size());\n    ZZ_p m21k = k*(m/2+1);\n    shift_values(ll_extend, lower_layer, m21k, k, p);\n\n    vector<Mat<ZZ_p>> ll_total;\n    ll_total.reserve(lower_layer.size() + ll_extend.size());\n    ll_total.insert(ll_total.end(), lower_layer.begin(), lower_layer.end());\n    ll_total.insert(ll_total.end(), ll_extend.begin(), ll_extend.end());\n\n    vector<Mat<ZZ_p>> ll_shift(ll_total.size());\n    ZZ_p m2;\n    m2.init(p);\n    m2 = m/2;\n    shift_values(ll_shift, ll_total, m2, k, p);\n\n    for(long i = 0; i < out.size(); i++){\n        mul(out[i], ll_shift[i], ll_total[i]);\n    }\n    if(m % 2 == 1){\n        for(long i = 0; i < out.size(); i++){\n            ZZ_p ikm = k*i + m;\n            Mat<ZZ_p> extra;\n            A(extra, ikm);\n            mul(out[i], extra, out[i]);\n        }\n    }\n\n}\n\n/*\n * Calculate M(1)M(2)...M(n) mod p\n */\nvoid matrix_factorial(Mat<ZZ_p> &out, long n, std::function<void (Mat<ZZ_p>&, ZZ_p&)> A, ZZ &p){\n    long rtn = sqrt(n);\n    \n    vector<Mat<ZZ_p>> seg_prods(rtn+1);\n    multieval_prod(seg_prods, A, p);\n\n    if(n < rtn*rtn + rtn){\n        for(long i = seg_prods.size()-2; i > 0; i--){\n            mul(seg_prods[i-1], seg_prods[i], seg_prods[i-1]);\n        }\n        for(long i = rtn*rtn+1; i <= n; i++){\n            Mat<ZZ_p> extra;\n            ZZ_p x;\n            x.init(p);\n            x = i;\n            A(extra, x);\n            mul(seg_prods[0], extra, seg_prods[0]);\n        }\n    }\n    else{\n        for(long i = seg_prods.size()-1; i > 0; i--){\n            mul(seg_prods[i-1], seg_prods[i], seg_prods[i-1]);\n        }\n        for(long i = rtn*rtn+rtn+1; i <= n; i++){\n            Mat<ZZ_p> extra;\n            ZZ_p x;\n            x.init(p);\n            x = i;\n            A(extra, x);\n            mul(seg_prods[0], extra, seg_prods[0]);\n        }\n    }\n    out = seg_prods[0];\n}\n\n", "meta": {"hexsha": "aaaef9bb14ec3988ce9891f06c8690a46d8b4fb8", "size": 10489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "archives/check_general.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/check_general.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/check_general.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": 29.1361111111, "max_line_length": 219, "alphanum_fraction": 0.5395175899, "num_tokens": 3497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5042554861347451}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <k52/dsp/transform/inverse_fourier_transform.h>\n#include <k52/dsp/transform/fourier_transform.h>\n\n#include  <k52/common/constants.h>\n\n#include <cmath>\n#include <list>\n\n#include \"../boost_test_tools_extensions.h\"\n\nusing k52::common::Constants;\nusing k52::dsp::FourierTransform;\nusing k52::dsp::IFourierTransform;\nusing k52::dsp::InverseFourierTransform;\n\nstruct InverseFourierTransformTestFixture\n{\n    InverseFourierTransformTestFixture() :\n            ift(IFourierTransform::shared_ptr(new FourierTransform()))\n    {}\n\n    InverseFourierTransform ift;\n    FourierTransform ft;\n};\n\nBOOST_FIXTURE_TEST_SUITE(inverse_fourier_transform_tests, InverseFourierTransformTestFixture);\n\nvoid test_inverse_fourier_transform(\n        const FourierTransform& ft,\n        const InverseFourierTransform& ift,\n        const std::vector< std::complex <double > >& samples)\n{\n    //Test\n    std::vector< std::complex <double > > result = ift.Transform(ft.Transform(samples));\n\n    //Check\n    BOOST_REQUIRE_EQUAL(samples.size(), result.size());\n\n    for (size_t n = 0; n < samples.size(); ++n)\n    {\n        CheckComplexEqual(samples[n], result[n]);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n    //Prepare\n    std::vector< std::complex <double > > zeros(10);\n\n    test_inverse_fourier_transform(ft, ift, zeros);\n}\n\nBOOST_AUTO_TEST_CASE(simple_impulse)\n{\n    //Prepare\n    std::vector< std::complex <double > > impulse_samples(4);\n    impulse_samples[0] = 1;\n\n    test_inverse_fourier_transform(ft, ift, impulse_samples);\n}\n\nBOOST_AUTO_TEST_CASE(impulse)\n{\n    //Prepare\n    std::vector< std::complex <double > > impulse_samples(11);\n    impulse_samples[2] = 1;\n\n    test_inverse_fourier_transform(ft, ift, impulse_samples);\n}\n\nBOOST_AUTO_TEST_CASE(ladder)\n{\n    std::vector< std::complex <double > > ladder_samples(9);\n    for (size_t n = 0; n < ladder_samples.size(); ++n)\n    {\n        ladder_samples[n] = n;\n    }\n    test_inverse_fourier_transform(ft, ift, ladder_samples);\n}\n\nBOOST_AUTO_TEST_CASE(complex)\n{\n    std::vector< std::complex <double > > complex_samples(14);\n    for (size_t n = 0; n < complex_samples.size(); ++n)\n    {\n        complex_samples[n] = (double)n * Constants::ImaginaryUnit;\n    }\n    test_inverse_fourier_transform(ft, ift, complex_samples);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "dfc629b2f7e11b101b3f844404021b8735cf9d9c", "size": 2329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/unit_tests/dsp/inverse_fourier_transform.test.cpp", "max_stars_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_stars_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2016-04-14T07:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-22T22:03:20.000Z", "max_issues_repo_path": "src/unit_tests/dsp/inverse_fourier_transform.test.cpp", "max_issues_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_issues_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2016-04-05T08:49:05.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-29T07:09:00.000Z", "max_forks_repo_path": "src/unit_tests/dsp/inverse_fourier_transform.test.cpp", "max_forks_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_forks_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-16T07:53:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-12T21:31:51.000Z", "avg_line_length": 25.0430107527, "max_line_length": 94, "alphanum_fraction": 0.7028767711, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5042554857080919}}
{"text": "/**\n * @file   work.cpp\n * @author ALIKAWA Hidehisa <alleyhide@gmail.com>\n * @date   2018/09/01\n \n * \n * @brief  for the experimental tests of gweyl\n * \n * Released under the MIT license\n */\n#include <iostream>\n#include <boost/assign.hpp>\n\n#include \"gweyl.hpp\"\n\nusing namespace gweyl;\n\nstruct RepresentationTheory {\n    IrreducibleRepresentation rep;\n    std::vector<matrix> PositiveSingleRootVectorAction;\n    std::vector<matrix> NegativeSingleRootVectorAction;\n    bool calculated{false};\n};\n\nstd::vector<RepresentationTheory> g_RepresentationTheory_A1;\n\n\n\n\nint main(int argc, char** argv){\n\n    std::cout << \"Hello gweyl!\" << std::endl;\n    \n    try {\n        // L(pi_1)\n        NumberVector nv1(1);\n        nv1(0) = 1;\n        VectorRootSpace v1(Type::A, nv1, Coordinate::fundamental);\n        IrreducibleRepresentation rep1(v1);\n\n        int m = rep1.dimension();\n        std::cout << \"A1 pi_1 dimension \" << std::to_string(m) << std::endl;\n        \n        RepresentationTheory repth1;\n        repth1.rep = rep1;\n\n        matrix E1p(m,m);\n        E1p(0,1) = 1;\n        repth1.PositiveSingleRootVectorAction.push_back(E1p);\n        \n        matrix E1m(m,m);\n        E1p(1,0) = 1;\n        repth1.NegativeSingleRootVectorAction.push_back(E1m);\n\n        repth1.calculated = true;\n\n        g_RepresentationTheory_A1.push_back(repth1);\n\n    }catch (std::exception &e){\n        std::cout << \"Error\\n what(): \";\n        std::cout << e.what();\n        std::cout << std::endl;\n        return -1;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "e0955d5cfb3d8f8270fb5cb8cc442e043ba75281", "size": 1515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/work.cpp", "max_stars_repo_name": "alleyhide/gweyl", "max_stars_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/work.cpp", "max_issues_repo_name": "alleyhide/gweyl", "max_issues_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/work.cpp", "max_forks_repo_name": "alleyhide/gweyl", "max_forks_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2794117647, "max_line_length": 76, "alphanum_fraction": 0.6099009901, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.5042554852814383}}
{"text": "#include <boost/config.hpp>\n#include <boost/version.hpp>\n\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#include <iostream>\n#include <fstream>\n\n#include <CGAL/IO/WKT.h>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n\n#include <vector>\n#include <deque>\n\n//typedef CGAL::Simple_cartesian<CGAL::Gmpq> Kernel;\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;\n\n\nint main(int argc, char* argv[])\n{\n  typedef CGAL::Polygon_with_holes_2<Kernel> Polygon;\n  typedef std::deque<Polygon> MultiPolygon;\n\n  {\n    std::ifstream is((argc>1)?argv[1]:\"data/polygons.wkt\");\n    std::list<Polygon> polys;\n    do\n      {\n        Polygon p;\n        CGAL::read_polygon_WKT(is, p);\n        if(!p.outer_boundary().is_empty())\n          polys.push_back(p);\n      }while(is.good() && !is.eof());\n    for(Polygon p : polys)\n      std::cout<<p<<std::endl;\n  }\n  \n  {\n    std::ifstream  is((argc>2)?argv[2]:\"data/multipolygon.wkt\");\n    MultiPolygon mp;\n    CGAL::read_multi_polygon_WKT(is, mp);\n    for(Polygon p : mp)\n      std::cout<<p<<std::endl;\n  }\n  return 0;\n}\n#else\nint main()\n{\n  return 0;\n}\n#endif\n", "meta": {"hexsha": "fa25a9bd61f85680f547375e28685f2d67ce0bb9", "size": 1178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/examples/Stream_support/Polygon_WKT.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/Stream_support/Polygon_WKT.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/Stream_support/Polygon_WKT.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": 21.4181818182, "max_line_length": 75, "alphanum_fraction": 0.6536502547, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839876, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5042554741539552}}
{"text": "#include <boost/random/triangle_distribution.hpp>\n", "meta": {"hexsha": "ffc9876f6a01854d73b5761786ae1470b2979344", "size": 50, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_triangle_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_triangle_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_triangle_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.0, "max_line_length": 49, "alphanum_fraction": 0.84, "num_tokens": 9, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5042554741539551}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2020 Baidyanath Kundu, Haldia, 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//[to_wkt\n//` Shows the usage of to_wkt\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\nint main()\n{\n    namespace geom = boost::geometry;\n    typedef geom::model::d2::point_xy<double> point_type;\n\n    point_type point = geom::make<point_type>(3, 2);\n    geom::model::polygon<point_type> polygon;\n    geom::append(geom::exterior_ring(polygon), geom::make<point_type>(0, 0));\n    geom::append(geom::exterior_ring(polygon), geom::make<point_type>(0, 4));\n    geom::append(geom::exterior_ring(polygon), geom::make<point_type>(4, 4));\n    geom::append(geom::exterior_ring(polygon), geom::make<point_type>(4, 0));\n    geom::append(geom::exterior_ring(polygon), geom::make<point_type>(0, 0));\n\n    std::cout << boost::geometry::to_wkt(point) << std::endl;\n    std::cout << boost::geometry::to_wkt(polygon) << std::endl;\n\n    point_type point_frac = geom::make<point_type>(3.141592654, 27.18281828);\n    geom::model::polygon<point_type> polygon_frac;\n    geom::append(geom::exterior_ring(polygon_frac), geom::make<point_type>(0.00000, 0.00000));\n    geom::append(geom::exterior_ring(polygon_frac), geom::make<point_type>(0.00000, 4.00001));\n    geom::append(geom::exterior_ring(polygon_frac), geom::make<point_type>(4.00001, 4.00001));\n    geom::append(geom::exterior_ring(polygon_frac), geom::make<point_type>(4.00001, 0.00000));\n    geom::append(geom::exterior_ring(polygon_frac), geom::make<point_type>(0.00000, 0.00000));\n\n    std::cout << boost::geometry::to_wkt(point_frac, 3) << std::endl;\n    std::cout << boost::geometry::to_wkt(polygon_frac, 3) << std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[to_wkt_output\n/*`\nOutput:\n[pre\nPOINT(3 2)\nPOLYGON((0 0,0 4,4 4,4 0,0 0))\nPOINT(3.14 27.2)\nPOLYGON((0 0,0 4,4 4,4 0,0 0))\n]\n\n\n*/\n//]\n", "meta": {"hexsha": "fc04b51b6f3adfc0f1adca9e7f811f3e2773408e", "size": 2145, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/geometry/doc/src/examples/io/to_wkt.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/geometry/doc/src/examples/io/to_wkt.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/geometry/doc/src/examples/io/to_wkt.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 33.0, "max_line_length": 94, "alphanum_fraction": 0.6941724942, "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105720171531, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5042443860612374}}
{"text": "// ----------------------------------------------------------------------------\n// -                        Open3D: www.open3d.org                            -\n// ----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2018 www.open3d.org\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\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n// ----------------------------------------------------------------------------\n\n#include \"TransformationEstimation.h\"\n\n#include <Eigen/Geometry>\n#include <Core/Geometry/PointCloud.h>\n#include <Core/Utility/Eigen.h>\n\nnamespace open3d{\n\ndouble TransformationEstimationPointToPoint::ComputeRMSE(\n        const PointCloud &source, const PointCloud &target,\n        const CorrespondenceSet &corres) const\n{\n    if (corres.empty()) return 0.0;\n    double err = 0.0;\n    for (const auto &c : corres) {\n        err += (source.points_[c[0]] - target.points_[c[1]]).squaredNorm();\n    }\n    return std::sqrt(err / (double)corres.size());\n}\n\nEigen::Matrix4d TransformationEstimationPointToPoint::ComputeTransformation(\n        const PointCloud &source, const PointCloud &target,\n        const CorrespondenceSet &corres) const\n{\n    if (corres.empty()) return Eigen::Matrix4d::Identity();\n    Eigen::MatrixXd source_mat(3, corres.size());\n    Eigen::MatrixXd target_mat(3, corres.size());\n    for (size_t i = 0; i < corres.size(); i++) {\n        source_mat.block<3, 1>(0, i) = source.points_[corres[i][0]];\n        target_mat.block<3, 1>(0, i) = target.points_[corres[i][1]];\n    }\n    return Eigen::umeyama(source_mat, target_mat, with_scaling_);\n}\n\ndouble TransformationEstimationPointToPlane::ComputeRMSE(\n        const PointCloud &source, const PointCloud &target,\n        const CorrespondenceSet &corres) const\n{\n    if (corres.empty() || target.HasNormals() == false) return 0.0;\n    double err = 0.0, r;\n    for (const auto &c : corres) {\n        r = (source.points_[c[0]] - target.points_[c[1]]).dot(\n                target.normals_[c[1]]);\n        err += r * r;\n    }\n    return std::sqrt(err / (double)corres.size());\n}\n\nEigen::Matrix4d TransformationEstimationPointToPlane::ComputeTransformation(\n        const PointCloud &source, const PointCloud &target,\n        const CorrespondenceSet &corres) const\n{\n    if (corres.empty() || target.HasNormals() == false)\n        return Eigen::Matrix4d::Identity();\n\n    auto compute_jacobian_and_residual = [&]\n            (int i, Eigen::Vector6d &J_r, double &r) {\n        const Eigen::Vector3d &vs = source.points_[corres[i][0]];\n        const Eigen::Vector3d &vt = target.points_[corres[i][1]];\n        const Eigen::Vector3d &nt = target.normals_[corres[i][1]];\n        r = (vs - vt).dot(nt);\n        J_r.block<3, 1>(0, 0) = vs.cross(nt);\n        J_r.block<3, 1>(3, 0) = nt;\n    };\n\n    Eigen::Matrix6d JTJ;\n    Eigen::Vector6d JTr;\n    std::tie(JTJ, JTr) = ComputeJTJandJTr<Eigen::Matrix6d, Eigen::Vector6d>(\n            compute_jacobian_and_residual, (int)corres.size());\n\n    bool is_success;\n    Eigen::Matrix4d extrinsic;\n    std::tie(is_success, extrinsic) =\n            SolveJacobianSystemAndObtainExtrinsicMatrix(JTJ, JTr);\n\n    return is_success ? extrinsic : Eigen::Matrix4d::Identity();\n}\n\n}    // namespace open3d\n", "meta": {"hexsha": "3e430ef998e3e06aebc6744e22b1f79cec149c78", "size": 4250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Core/Registration/TransformationEstimation.cpp", "max_stars_repo_name": "sjchoi86/Open3D", "max_stars_repo_head_hexsha": "d993d21ff650227c736b08b0e7028f4c5ce16830", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-11T05:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T05:24:08.000Z", "max_issues_repo_path": "src/Core/Registration/TransformationEstimation.cpp", "max_issues_repo_name": "panluDreamer/Open3D", "max_issues_repo_head_hexsha": "d993d21ff650227c736b08b0e7028f4c5ce16830", "max_issues_repo_licenses": ["MIT"], "max_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/Registration/TransformationEstimation.cpp", "max_forks_repo_name": "panluDreamer/Open3D", "max_forks_repo_head_hexsha": "d993d21ff650227c736b08b0e7028f4c5ce16830", "max_forks_repo_licenses": ["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.0943396226, "max_line_length": 80, "alphanum_fraction": 0.6331764706, "num_tokens": 1043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5042443810331434}}
{"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/four_point_homography.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <glog/logging.h>\n#include <vector>\n\n#include \"theia/sfm/pose/util.h\"\n\nnamespace theia {\nusing Eigen::Map;\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\n\nnamespace {\n\ninline Matrix<double, 2, 9> CreateActionConstraint(const Vector2d& img1_point,\n                                                   const Vector2d& img2_point) {\n  Matrix<double, 2, 9> constraint;\n  constraint << Eigen::RowVector3d::Zero(), -img1_point.transpose(), -1.0,\n      img1_point.transpose() * img2_point.y(), img2_point.y(),\n      img1_point.transpose(), 1.0, Eigen::RowVector3d::Zero(),\n      -img1_point.transpose() * img2_point.x(), -img2_point.x();\n\n  return constraint;\n}\n\n}  // namespace\n\n// Normalized DLT method to compute the homography H that maps image points in\n// image_1 to image_2 via x' = Hx (where x is in image 1 and x' is in image\n// 2). The DLT algorithm implemented is from Algorithm 4.2 in Hartley and\n// Zisserman (page 109).\nbool FourPointHomography(const std::vector<Vector2d>& image_1_points,\n                         const std::vector<Vector2d>& image_2_points,\n                         Matrix3d* homography) {\n  CHECK_GE(image_1_points.size(), 4);\n  CHECK_EQ(image_1_points.size(), image_2_points.size());\n\n  // Normalize the image points.\n  std::vector<Vector2d> norm_image_1_points, norm_image_2_points;\n  Matrix3d norm_image_1_mat, norm_image_2_mat;\n  NormalizeImagePoints(image_1_points, &norm_image_1_points, &norm_image_1_mat);\n  NormalizeImagePoints(image_2_points, &norm_image_2_points, &norm_image_2_mat);\n\n  // Create the constraint matrix based on x' = Hx (Eq. 4.1 in Hartley and\n  // Zisserman).\n  Matrix<double, Eigen::Dynamic, 9> action_matrix(\n      2 * image_1_points.size(), 9);\n  for (int i = 0; i < image_1_points.size(); i++) {\n    action_matrix.block<2, 9>(2 * i, 0) =\n        CreateActionConstraint(norm_image_1_points[i], norm_image_2_points[i]);\n  }\n\n  const Matrix<double, 9, 1> null_vector =\n      (action_matrix.transpose() * action_matrix).jacobiSvd(Eigen::ComputeFullV)\n          .matrixV().rightCols<1>();\n\n  *homography = norm_image_2_mat.inverse() *\n                Eigen::Map<const Matrix3d>(null_vector.data()).transpose() *\n                norm_image_1_mat;\n  return true;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "b134251bee2755a713cbca7ec8c9a96ade0d6fd7", "size": 4227, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/four_point_homography.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/four_point_homography.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/four_point_homography.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": 40.6442307692, "max_line_length": 80, "alphanum_fraction": 0.7127986752, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5042443810331433}}
{"text": "#include \"ros/ros.h\"\n#include \"geometry_msgs/PoseStamped.h\"\n#include \"nav_msgs/Path.h\"\n#include \"geometry_msgs/Point32.h\"\n#include \"sensor_msgs/PointCloud.h\"\n#include <opencv2/opencv.hpp>\n#include <Eigen/Dense>\n#include <chrono>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n/**\n *  \u8be5\u6587\u4ef6\u662f\u6ca1\u6709\u5220\u9664\u6ce8\u91ca\u7684\u6700\u7ec8\u7248 camera-line-tracking\n *\n *  @author: panguoping\n *  @version: v1.0\n *\n *\n *\n * */\n\n\n\n/** \u53c2\u6570\u5b9a\u4e49 **/\nconst float fx = 760.4862674784594; // \u76f8\u673a\u5185\u53c2\nconst float fy = 761.4971958529285;\nconst float cx = 631.6715834996345;\nconst float cy = 329.3054436037627;\n\nconst float y = 129.5585;   // \u56fa\u5b9a\u76f8\u673a\u79bb\u5730\u9762\u9ad8\u5ea6\uff0c\u5355\u4f4dmm\uff0c\u901a\u8fc7\u8ba1\u7b97\u5f97\u5230\uff0c\u4e0d\u4e00\u5b9a\u51c6\n\nfloat offset;\nfloat thetaX;\nfloat thetaY;\nfloat scale;\nint imgWidth;  // \u56fe\u7247\u5927\u5c0f\nint imgHeight;\nfloat up_rate;\nfloat down_rate;\nint sizeThres;\n\nros::Publisher pathpub;\nros::Publisher leftpoint;\nros::Publisher rightpoint;\n\n/** \u5c06\u56fe\u7247\u4e2d\u7684 \u70b9uv \u8f6c\u5316\u4e3a \u73b0\u5b9e\u5750\u6807\u4e2d\u7684 \u70b9xy **/\ncv::Point3f getXYZ(cv::Point2f& point){\n    cv::Point3f point3d;\n    point3d.x = (fy * y/(point.y-cy))/scale;\n    point3d.y = (-(point.x-cx)*point3d.x/fx);\n    point3d.z = 0.0;\n    // std::cout<<point3d<<std::endl;\n    return point3d;\n}\n\n/** \u5c06\u4e8c\u7ef4\u8fb9\u7ebf\u8f6c\u5316\u4e3a\u4e09\u7ef4\u8fb9\u7ebf **/\nvoid transTo3D(vector<cv::Point2f>& uv,vector<cv::Point3f>& posearray){\n    for(auto p:uv){\n        cv::Point3f pose = getXYZ(p);\n        posearray.push_back(pose);\n    }\n}\n\n/** \u65b9\u6cd5\u4e00\uff1a\u753b\u51fa\u4e2d\u95f4\u7ebf **/\nvoid pubMiddleline(vector<cv::Point2f>& uvLeft,vector<cv::Point2f>& uvRight){\n    vector<cv::Point3f> xyLeft,xyRight;\n    sensor_msgs::PointCloud path;\n    transTo3D(uvLeft,xyLeft);\n    transTo3D(uvRight,xyRight);\n//    std::cout<<xyLeft<<std::endl;\n//    std::cout<<xyRight<<std::endl;\n\n    // \u9009\u62e9\u6700\u957fsize\uff0c\u5c06\u5934\u90e8\u591a\u51fa\u70b9\u53bb\u6389\n    ROS_INFO(\"int two middle\");\n    bool lbigthanr = xyLeft.size() > xyRight.size() ? true:false;   \n    int ir = 0;\n    int il = 0;\n    if(lbigthanr){\n        path.points.resize(xyLeft.size());\n        while(il<xyLeft.size()&&abs(xyLeft[il].x-xyRight[ir].x)>thetaX){\n            ++il;\n        }\n    } else{\n        path.points.resize(xyRight.size());\n        while(ir<xyRight.size()&&abs(xyLeft[il].x-uvRight[ir].x)>thetaX){\n            ++ir;\n        }\n    }\n    // \u751f\u6210\u5de6\u53f3\u8fb9\u7ebf\u548c\u4e2d\u7ebf\n    int k = 0;\n    sensor_msgs::PointCloud pcLeft;\n    pcLeft.header.stamp = ros::Time::now();\n    pcLeft.header.frame_id = \"camera\";\n    pcLeft.points.resize(uvLeft.size());\n\n    sensor_msgs::PointCloud pcRight;\n    pcRight.header.stamp = ros::Time::now();\n    pcRight.header.frame_id = \"camera\";\n    pcRight.points.resize(uvRight.size());\n    int i = 0;\n    //size\u9700\u8981\u5f3a\u5236\u8f6c\u6362\n    for(i,k,ir,il; il<int(xyLeft.size()-5)&&ir<int(uvRight.size()-5);++ir,++il){    \n        pcLeft.points[i].x = xyLeft[i].x;\n        pcLeft.points[i].y = xyLeft[i].y;\n        pcLeft.points[i].z = 0.0;\n        pcRight.points[i].x = xyRight[i].x;\n        pcRight.points[i].y = xyRight[i].y;\n        pcRight.points[i].z = 0.0;\n        ++i;\n        if(abs(xyLeft[il].x-uvRight[ir].x)>thetaX   // \u5de6\u53f3\u8fb9\u7ebf\u7eb5\u5411\u8ddd\u79bb\u4e0d\u8d85\u8fc7thetaX,\u5426\u5219\u820d\u5f03\n//           && abs(xyLeft[il+1].y-xyLeft[il].y)>thetaY\n//           && abs(xyRight[ir+1].y-xyRight[ir].y)>thetaY\n           )\n            continue;\n        ROS_INFO(\"yes\");\n\n        path.points[k].x = (xyLeft[il].x+xyRight[ir].x)/2;\n        path.points[k].y = (xyLeft[il].y+xyRight[ir].y)/2;\n        path.points[k].z = 0.0;\n        ++k;\n\n    }\n\n    // \u53d1\u5e03\u4fe1\u606f\n    ROS_INFO(\"pathpose:%d\",path.points.size());\n    path.header.stamp = ros::Time::now();\n    path.header.frame_id = \"camera\";\n    pathpub.publish(path);\n    leftpoint.publish(pcLeft);\n    rightpoint.publish(pcRight);\n    ROS_INFO(\"publish successfully\");\n\n\n}\n\n/** \u65b9\u6cd5\u4e8c\uff1a\u4e0d\u820d\u5f03\u7eb5\u5411\u8ddd\u79bb\u70b9\uff0c\u76f4\u63a5+\u3001-\u504f\u79fb\u91cf\u79fb\u5230\u4e2d\u592e\u4f4d\u7f6e**/\nvoid pubMiddlelinePro(vector<cv::Point2f>& uvLeft,vector<cv::Point2f>& uvRight){\n    // 1.\u5c06\u6570\u636e\u8f6c\u5316\u4e3a\u4e09\u7ef4\u5750\u6807\u7cfb\u4e0b\n    vector<cv::Point3f> xyLeft,xyRight;\n    ROS_INFO(\"int two middle\");\n    transTo3D(uvLeft,xyLeft);\n    transTo3D(uvRight,xyRight);\n\n    // 2.\u5efa\u7acb\u5de6\u53f3\u70b9\u4e91\n\n    sensor_msgs::PointCloud pcLeft;\n    pcLeft.header.stamp = ros::Time::now();\n    pcLeft.header.frame_id = \"camera\";\n    pcLeft.points.resize(uvLeft.size());\n\n    sensor_msgs::PointCloud pcRight;\n    pcRight.header.stamp = ros::Time::now();\n    pcRight.header.frame_id = \"camera\";\n    pcRight.points.resize(uvRight.size());\n\n    int size = uvLeft.size()>=uvRight.size() ? int(uvLeft.size()):int(uvRight.size());\n    sensor_msgs::PointCloud path;\n    path.points.resize(uvLeft.size()+uvRight.size());\n\n    // 3.\u5de6\u4e2d\u53f3\u5f80\u4e0b\u8d70\n    int r = 0;\n    int l = 0;\n    int m = 0;\n    int pline = imgHeight * 2 / 3 - 10;\n    for(int i = pline;i<imgHeight;++i){\n        // ROS_INFO(\"%d\",i);\n        // float z = ((fy * y)/(i - cy))/scale;\n        ROS_INFO(\"lz:%f rz:%f\",xyLeft[l].x,xyRight[r].x);\n        if(l<xyLeft.size()&&r<xyRight.size()&&xyLeft[l].x==xyRight[r].x){   //\u5f53\u4e24\u8005\u76f8\u7b49\u65f6\n            ROS_INFO(\"Equal!\");\n            path.points[m].x = xyRight[r].x;\n            path.points[m].y = (xyLeft[l].y+xyRight[r].y)/2;\n            path.points[m].z = 0.0;\n            pcLeft.points[l].x = xyLeft[l].x;\n            pcLeft.points[l].y = xyLeft[l].y;\n            pcLeft.points[l].z = 0.0;\n            pcRight.points[r].x = xyRight[r].x;\n            pcRight.points[r].y = xyRight[r].y;\n            pcRight.points[r].z = 0.0;\n            ++l;\n            ++r;\n            ++m;\n        }\n        else if(xyRight[r].x > xyLeft[l].x){    //\u82e5\u53f3\u8ddd\u79bb\u5927\u4e8e\u5de6\n            ROS_INFO(\"r bigthan l\");\n            if(r<xyRight.size()){\n                path.points[m].x = xyRight[r].x;\n                path.points[m].y = xyRight[r].y - offset;\n                path.points[m].z = 0.0;\n                pcRight.points[r].x = xyRight[r].x;\n                pcRight.points[r].y = xyRight[r].y;\n                pcRight.points[r].z = 0.0;\n                ++r;\n                ++m;\n            }\n        }\n        else if(xyLeft[l].x>xyRight[r].x){  //\u82e5\u5de6\u8ddd\u79bb\u5927\u4e8e\u53f3\n                ROS_INFO(\"l bigthan r\");\n                if(l<xyLeft.size()){\n                path.points[m].x = xyLeft[l].x;\n                path.points[m].y = xyLeft[l].y + offset;\n                path.points[m].z = 0.0;\n                pcLeft.points[l].x = xyLeft[l].x;\n                pcLeft.points[l].y = xyLeft[l].y;\n                pcLeft.points[l].z = 0.0;\n                ++l;\n                ++m;\n            }\n        }\n\n    }\n\n    ROS_INFO(\"pathpose:%d\",path.points.size());\n    path.header.stamp = ros::Time::now();\n    path.header.frame_id = \"camera\";\n    pathpub.publish(path);\n    leftpoint.publish(pcLeft);\n    rightpoint.publish(pcRight);\n    ROS_INFO(\"publish successfully\");\n\n\n}\n\n/** \u914d\u5408\u65b9\u6cd5\u4e00\u3001\u4e8c\uff1a\u5904\u7406\u5355\u8fb9\u60c5\u51b5 **/\nvoid pubMiddleline(vector<cv::Point2f>& uv){\n    vector<cv::Point3f> xy;\n    sensor_msgs::PointCloud path;\n    transTo3D(uv,xy);\n    path.points.resize(xy.size());\n    int i = 0;\n    for(auto p:xy){\n        if(p.y>0){\n            path.points[i].x = p.x;\n            path.points[i].y = p.y-offset;\n            path.points[i].z = 0.0;\n            ++i;\n        }\n        else if(p.y<0){\n            path.points[i].x = p.x;\n            path.points[i].y = p.y+offset;\n            path.points[i].z = 0.0;\n            ++i;\n        }\n\n    }\n    ROS_INFO(\"pathpose:%d\",path.points.size());\n    path.header.stamp = ros::Time::now();\n    path.header.frame_id = \"camera\";\n    pathpub.publish(path);\n    ROS_INFO(\"publish successfully\");\n}\n\n/** \u65b9\u6cd5\u56db\uff1a\u6df7\u5408\u5904\u7406\u4e0d\u5206\u5355\u53cc\u8fb9\u7ebf **/\nvoid pubMiddlelineCombine(vector<cv::Point2f>& uvLeft,vector<cv::Point2f>& uvRight){\n    \n    // 1.\u5c06\u6570\u636e\u8f6c\u5316\u4e3a\u4e09\u7ef4\u5750\u6807\u7cfb\u4e0b\n    vector<cv::Point3f> xyLeft,xyRight;\n    ROS_INFO(\"int two middle\");\n    transTo3D(uvLeft,xyLeft);\n    transTo3D(uvRight,xyRight);\n\n    // 2.\u53c2\u6570\u5b9a\u4e49\n    int r = 0;\n    int l = 0;\n    float max_distance = 0;\n    sensor_msgs::PointCloud pc;\n    pc.header.stamp = ros::Time::now();\n    pc.header.frame_id = \"camera\";\n    \n    float lastparallel = 0; // \u8bb0\u5f55\u4e0a\u4e00\u70b9\u7684\u6a2a\u5411\u5750\u6807\n    bool init = 0;\n\n    // \u8ba1\u7b97\u4e2d\u7ebf\uff0c\u53ea\u8981\u6709\u4e00\u8fb9\u7ebf\u7684\u70b9\u90fd\u7528\u5b8c\u4e86\u5c31\u9000\u51fa\u5faa\u73af\n    while (l<xyLeft.size() && r<xyRight.size())\n    {\n        // ROS_INFO(\"l: %d, r:%d\",l,r);\n        // 1.\u521d\u59cb\u5316\n        if(!init){\n            lastparallel =( xyLeft[l].y + xyRight[r].y )/2;\n            init = 1;\n            continue;\n        }\n        // 2.\u4e24\u8fb9\u7ebf\u7eb5\u5411\u8ddd\u79bb\u76f8\u7b49\u65f6\n        if(xyLeft[l].x == xyRight[r].x){\n            if(xyLeft[l].x > max_distance)\n                max_distance = xyLeft[l].x;\n            float tmp = ( xyLeft[l].y + xyRight[r].y )/2;\n            if(abs(tmp - lastparallel)>0.1){// \u4e0e\u4e0a\u4e00\u70b9\u6a2a\u5750\u6807\u7684\u504f\u5dee\n                l++;\n                r++;\n                continue;\n            }\n            geometry_msgs::Point32 p;\n            p.x = xyLeft[l].x;\n            p.y = tmp;\n            p.z = 0.0;\n            pc.points.push_back(p);\n            l++;\n            r++;\n            lastparallel = tmp;\n        }\n        // 3.\u5de6\u8fb9\u7ebf\u7eb5\u5411\u8ddd\u79bb\u5927\u4e8e\u53f3\u8fb9\u7ebf\n        else if(xyLeft[l].x > xyRight[r].x){\n            if(xyLeft[l].x > max_distance)\n                max_distance = xyLeft[l].x;\n            float tmp = xyLeft[l].y - offset;\n            // cout<<\"LEFT:\"<<tmp<<endl;\n\n            if(abs(tmp - lastparallel)>0.1){\n                l++;\n                continue;\n            }\n            geometry_msgs::Point32 p;\n            p.x = xyLeft[l].x;\n            p.y = tmp;\n            p.z = 0.0;\n            pc.points.push_back(p);\n            l++;\n            lastparallel = tmp;\n        }\n        // 4.\u53f3\u8fb9\u7ebf\u7eb5\u5411\u8ddd\u79bb\u5927\u4e8e\u5de6\u8fb9\u7ebf\n        else{\n            if(xyRight[l].x > max_distance)\n                max_distance = xyRight[l].x;\n            // cout<<\"RIGHT:\"<<xyRight[r].y<<endl;\n            float tmp = xyRight[r].y + offset;\n            // cout<<\"RIGHT:\"<<tmp<<endl;\n            if(abs(tmp - lastparallel)>0.1){\n                r++;\n                continue;\n            }\n            geometry_msgs::Point32 p;\n            p.x = xyRight[r].x;\n            p.y = tmp;\n            p.z = 0.0;\n            pc.points.push_back(p);\n            r++;\n            lastparallel = tmp;\n        }\n\n    }\n    // ROS_INFO(\"OUT1\");\n    // \u5c06\u53e6\u4e00\u8fb9\u5269\u4e0b\u7684\u8f68\u8ff9\u70b9\u52a0\u5165\n    // while (l<xyLeft.size())\n    // {\n    //     if(xyLeft[l].x > max_distance)\n    //         max_distance = xyLeft[l].x;\n    //     float tmp = xyLeft[l].y - offset;\n        \n    //     geometry_msgs::Point32 p;\n    //     p.x = xyLeft[l].x;\n    //     p.y = tmp;\n    //     p.z = 0.0;\n    //     pc.points.push_back(p);\n    //     l++;\n    // }\n    \n    // while (r<xyRight.size())\n    // {\n    //     if(xyRight[r].x > max_distance)\n    //         max_distance = xyRight[r].x;\n    //     // cout<<\"RIGHT BEFORT:\"<<xyRight[r].y<<endl;\n    //     float tmp = xyRight[r].y + offset;\n    //     // cout<<\"RIGHT AFTER:\"<<tmp<<endl;\n    //     geometry_msgs::Point32 p;\n    //     p.x = xyRight[r].x;\n    //     p.y = tmp;\n    //     p.z = 0.0;\n    //     pc.points.push_back(p);\n    //     r++;\n    // }\n    // ROS_INFO(\"OUT2\");\n    ROS_INFO(\"MAX DISTANCE %f\",max_distance);\n\n    pathpub.publish(pc);\n}\n\n/** \u8f6c\u6362\u5230lab\u8272\u57df **/\nvoid binaryFromLab(cv::Mat & frame,cv::Mat & binary){\n    cv::Mat lab;\n    cv::cvtColor(frame,lab,CV_RGB2Lab);\n    cv::Mat lab_1;\n    vector<cv::Mat> channels;\n    cv::split(lab,channels);\n    lab_1 = channels.at(1);\n    double max;\n    double min;\n    cv::minMaxLoc(lab_1,&min,&max);\n    float thres = max - min;\n    for(int i = 0;i<frame.rows;++i){\n        uchar* datalab = lab_1.ptr<uchar>(i);\n        uchar* databinary = binary.ptr<uchar>(i);\n        for(int j = 0;j<frame.cols;++j){\n            if((datalab[j] - min)/thres<0.2){\n                databinary[j] = 255;\n            }\n            else{\n                databinary[j] = 0;\n            }\n        }\n    }\n\n}\n\n\n/** cmyk\u8272\u57df **/\nvoid binaryFromCMYK(cv::Mat & frame,cv::Mat & binary){\n    for(int i = 0;i<frame.rows;++i){\n        uchar* dataframe = frame.ptr<uchar>(i);\n        uchar* datagray = binary.ptr<uchar>(i);\n        for(int j = 0;j<frame.cols;++j){\n            uchar c = 255 - dataframe[j*3+2];\n            uchar m = 255 - dataframe[j*3+2];\n            uchar y = 255 - dataframe[j*3+2];\n            uchar K = min(min(c,m),y);\n            if(K == 255){\n                datagray[j] = 0;\n                continue;\n            }\n            uchar C = (uchar)((c - K)*255.0 / (255 - K));\n            uchar M = (uchar)((m - K)*255.0 / (255 - K));\n            uchar Y = (uchar)((y - K)*255.0 / (255 - K));\n            if(Y>150){\n                datagray[j] = 255;\n            }\n            else{\n                datagray[j] = 0;\n            }\n        }\n    }\n}\n\n\n\nint main(int argc ,char **argv){\n    ros::init(argc,argv,\"linktracking\");\n    ros::NodeHandle nh(\"~\");\n    pathpub = nh.advertise<sensor_msgs::PointCloud>(\"path\",1);\n    leftpoint = nh.advertise<sensor_msgs::PointCloud>(\"leftpath\",1);\n    rightpoint = nh.advertise<sensor_msgs::PointCloud>(\"rightpath\",1);\n    string video;\n    nh.param<string>(\"video\",video,\"../dataset/test.mp4\");\n    nh.param<float>(\"offset\",offset,0.45);\n    nh.param<float>(\"thetaX\",thetaX,0.2);\n    nh.param<float>(\"thetaY\",thetaY,0.1);\n    nh.param<float>(\"scale\",scale,1000.0);\n    nh.param<int>(\"imgWidth\",imgWidth,1280);\n    nh.param<int>(\"imgHeight\",imgHeight,720);\n    nh.param<float>(\"up_rate\",up_rate,0.5);\n    nh.param<float>(\"down_rate\",down_rate,0.9);\n    nh.param<int>(\"size_thres\",sizeThres,10);\n\n    ROS_INFO(\"offset : %f\",offset);\n    ROS_INFO(\"thetaX : %f\",thetaY);\n    ROS_INFO(\"thetaY : %f\",thetaX);\n    ROS_INFO(\"scale : %f\",scale);\n    ROS_INFO(\"imgWidth : %d\",imgWidth);\n    ROS_INFO(\"imgHeight : %d\",imgHeight);\n\n    /** 1.\u83b7\u5f97\u89c6\u9891\u6570\u636e **/\n    cv::VideoCapture cap = cv::VideoCapture(video);\n    cap.set(CV_CAP_PROP_FRAME_WIDTH, imgWidth);\n    cap.set(CV_CAP_PROP_FRAME_HEIGHT, imgHeight);\n    cap.set(cv::CAP_PROP_FPS,30);\n\n    ROS_INFO(\"%s\",video.c_str());\n    cv::Mat frame;\n    cv::Mat gray;\n    cv::Mat binary;\n    \n    if(!cap.isOpened()){\n        ROS_INFO(\"Don't load the Image!\");\n        return 1;\n    }\n\n\n    while (ros::ok()&&cap.isOpened()) {\n        /** 2.\u83b7\u5f97\u5e27\u5e76\u4e8c\u503c\u5316 **/\n        cap.read(frame);\n        if(!frame.data){\n            ROS_INFO(\"Don't get this the frame\");\n            break;\n        }\n        \n        // method 1:\u8f6c\u5230lab\u8272\u57df\n        // cv::Mat binary(frame.rows,frame.cols, CV_8UC1);\n        // binaryFromLab(frame,binary);\n        // cv::dilate(binary,binary,11);\n        \n        // method 2:\u81ea\u9002\u5e94\u4e8c\u503c\u5316\n        cv::cvtColor(frame, gray, CV_RGB2GRAY);\n        cv::threshold(gray, binary, 150, 255, CV_THRESH_BINARY);\n        cv::erode(binary, binary, cv::Mat(), cv::Point(-1, -1), 2);\n        cv::dilate(binary,binary,11);\n        \n        // cv::Sobel(gray,binary,-1,0,1);\n        //cv::erode(binary, binary, cv::Mat(), cv::Point(-1, -1), 2);\n        \n        // method 3:\u9002\u5e94\u6027\u4e8c\u503c\u5316\n        // cv::adaptiveThreshold(frame,binary,255,CV_ADAPTIVE_THRESH_MEAN_C,CV_THRESH_BINARY,11,2);\n        // cv::erode(binary, binary, cv::Mat(), cv::Point(-1, -1), 2);\n        // cv::imshow(\"show\", binary);\n        // cv::waitKey(0);\n\n\n        /** 3.\u83b7\u5f97\u4e24\u8fb9\u8f68\u8ff9\u70b9 **/\n        int vline = binary.cols / 2;\n        int pline = binary.rows * 2 / 3 - 10;\n        vector<cv::Point2f> uvRight;\n        vector<cv::Point2f> uvLeft;\n        // right side\n        for (int i = int(imgHeight*up_rate); i < int(imgHeight*down_rate)-1; ++i) {\n            uchar *data = binary.ptr<uchar>(i);\n            for (int j = vline; j < binary.cols - 1; ++j) {\n                if (data[j] == 0 && data[j + 1] == 255) {\n                    data[j] = 150;\n                    data[j+1] = 150;\n                    data[j+2] = 150;\n                    data[j+3] = 150;\n                    data[j+4] = 150;\n                    data[j+5] = 150;\n                    data[j+6] = 150;\n                    data[j+7] = 150;\n                    data[j+8] = 150;\n                    data[j+9] = 150;\n                    data[j+10] = 150;\n                    uvRight.push_back(cv::Point2f(j, i));\n                    break;\n                }\n            }\n        }\n        // left side\n        for (int i = int(imgHeight*up_rate); i < int(imgHeight*down_rate)-1; ++i) {\n            uchar *data = binary.ptr<uchar>(i);\n            for (int j = vline; j > 0; --j) {\n                if (data[j] == 0 && data[j - 1] == 255) {\n                    data[j] = 150;\n                    data[j-1] = 150;\n                    data[j-2] = 150;\n                    data[j-3] = 150;\n                    data[j-4] = 150;\n                    data[j-5] = 150;\n                    data[j-6] = 150;\n                    data[j-7] = 150;\n                    data[j-8] = 150;\n                    data[j-9] = 150;\n                    data[j-10] = 150;\n                    uvLeft.push_back(cv::Point2f(j, i));\n                    break;\n                }\n            }\n        }\n        // for (int i = pline; i < imgHeight; ++i) {\n        //     uchar *data = binary.ptr<uchar>(i);\n        //     for (int j = 0; j<imgWidth; ++j) {\n        //         if (data[j] == 0 && data[j + 1] == 255) {\n        //             data[j] = 150;\n        //             data[j+1] = 150;\n        //             data[j+2] = 150;\n        //             data[j+3] = 150;\n        //             data[j+4] = 150;\n        //             data[j+5] = 150;\n        //             data[j+6] = 150;\n        //             data[j+7] = 150;\n        //             data[j+8] = 150;\n        //             data[j+9] = 150;\n        //             data[j+10] = 150;\n        //             uvLeft.push_back(cv::Point2f(j, i));\n        //             break;\n        //         }\n        //     }\n        // }\n        cv::imshow(\"frame\",binary);\n        cv::waitKey(0);\n        \n\n        /** 4.\u7ed8\u5236\u4e24\u8fb9\u7ebf **/\n        ROS_INFO(\"right.size = %d,left.size = %d\",uvRight.size(),uvLeft.size());\n    \n        // if(uvLeft.size()>0&&uvRight.size()>0){\n        //     pubMiddlelinePro(uvLeft,uvRight);\n        // }\n        // else if(uvLeft.size()>0){\n        //     pubMiddleline(uvLeft);\n        // }\n        // else if(uvRight.size()>0){\n        //     pubMiddleline(uvRight);\n        // }\n        if(uvRight.size()>sizeThres && uvLeft.size()>sizeThres)\n            pubMiddlelineCombine(uvLeft,uvRight);\n        else if(uvRight.size()>=uvLeft.size()&&uvRight.size()>sizeThres)\n            pubMiddleline(uvRight);\n        else if(uvLeft.size()>uvRight.size()&&uvLeft.size()>sizeThres)\n            pubMiddleline(uvLeft);\n            \n\n    }\n    cv::destroyAllWindows();\n    cap.release();\n    return 0;\n}", "meta": {"hexsha": "04fe3e4765d5b74ef3856f482c03d761a97d1a38", "size": 18066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lineTrack-2/src/cameraTest_v1.0.cpp", "max_stars_repo_name": "GuoPingPan/LinearTracking_Huawei", "max_stars_repo_head_hexsha": "499e16448081421766df66614551750c1cb71a1d", "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": "lineTrack-2/src/cameraTest_v1.0.cpp", "max_issues_repo_name": "GuoPingPan/LinearTracking_Huawei", "max_issues_repo_head_hexsha": "499e16448081421766df66614551750c1cb71a1d", "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": "lineTrack-2/src/cameraTest_v1.0.cpp", "max_forks_repo_name": "GuoPingPan/LinearTracking_Huawei", "max_forks_repo_head_hexsha": "499e16448081421766df66614551750c1cb71a1d", "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.0099667774, "max_line_length": 99, "alphanum_fraction": 0.4898704749, "num_tokens": 5602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.504244370976955}}
{"text": "/*\n * Software License Agreement (Apache License)\n *\n * Copyright (c) 2014, Southwest Research Institute\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\n#include <gtest/gtest.h>\n#include <yaml-cpp/yaml.h>\n#include <fstream>\n#include <iostream>\n\n#include <Eigen/Geometry>\n#include <Eigen/Core>\n#include <industrial_extrinsic_cal/ceres_costs_utils.hpp>\n\nusing namespace industrial_extrinsic_cal;\n\n\nPoint3d xformPoint(Point3d &original_point, double &ax, double &ay, double &az, double &x, double&y, double &z);\n\n\nclass Observation\n{\npublic:\n  Observation()\n  {\n    point_id = 0;\n    image_loc_x = 0.0;\n    image_loc_y = 0.0;\n  };\n  ~Observation(){};\n  int point_id;\n  double image_loc_x;\n  double image_loc_y;\n};\n\nObservation projectPoint(CameraParameters C, Point3d P)\n{\n  double p[3];\n  double pt[3];\n  pt[0] = P.x;\n  pt[1] = P.y;\n  pt[2] = P.z;\n\n  /* transform point into camera frame */\n  /* note, camera transform takes points from camera frame into world frame */\n  ceres::AngleAxisRotatePoint(C.angle_axis, pt, p);\n\n  p[0] += C.position[0];\n  p[1] += C.position[1];\n  p[2] += C.position[2];\n\n  double xp = p[0] / p[2];\n  double yp = p[1] / p[2];\n\n  double r2 = xp * xp + yp * yp;\n  double r4 = r2 * r2;\n  double r6 = r2 * r4;\n\n  double xp2 = xp * xp; /* temporary variables square of others */\n  double yp2 = yp * yp;\n\n  /* apply the distortion coefficients to refine pixel location */\n  double xpp = xp + C.distortion_k1 * r2 * xp \n    + C.distortion_k2 * r4 * xp  \n    + C.distortion_k3 * r6 * xp  \n    + C.distortion_p2 * (r2 + 2 * xp2) \n    + C.distortion_p1 * xp * yp * 2.0;\n  double ypp = yp + C.distortion_k1 * r2 * yp \n    + C.distortion_k2 * r4 * yp \n    + C.distortion_k3 * r6 * yp \n    + C.distortion_p1 * (r2 + 2 * yp2) \n    + C.distortion_p2 * xp * yp * 2.0;\n\n  /* perform projection using focal length and camera center into image plane */\n  Observation O;\n  O.point_id = 0;\n  O.image_loc_x = C.focal_length_x * xpp + C.center_x;\n  O.image_loc_y = C.focal_length_y * ypp + C.center_y;\n\n  return (O);\n}\n\n// GLOBAL VARIABLES FOR TESTING\nstd::vector<Point3d> created_points;\ndouble aa[3]; // angle axis known/set\ndouble p[3]; // point rotated known/set\nstd::vector<Point3d> transformed_points;\nstd::vector<Observation> observations;\nCameraParameters C;\n\nTEST(IndustrialExtrinsicCalCeresSuite, rotationProduct)\n{\n  double R1[9];\n  double R2[9];\n  double R3[9];\n  double R1p[9];\n  double R2p[9];\n\n  // create 2 poses, one the inverse of the other\n  // multiply them and see if we get identity\n  Pose6d P1, P2;\n  P1.setAngleAxis(.1, .2, 3.0);\n  P2 = P1.getInverse();\n  ceres::AngleAxisToRotationMatrix(P1.pb_aa,R1);\n  ceres::AngleAxisToRotationMatrix(P2.pb_aa,R2);\n  rotationProduct(R1,  R2,  R3);\n  // NOTE, this should work regardless of row/column major snaffos\n  for(int i=0; i<3; i++){\n    for(int j=0; j<3; j++){\n      if(i==j){\n\tASSERT_NEAR( 1.0, R3[i+3*j], .001);\n      }\n      else{\n\tASSERT_NEAR( 0.0, R3[i+3*j], .001);\n      }\n    }\n  }\n}\nTEST(IndustrialExtrinsicCalCeresSuite, extractCameraIntrinsics)\n{\n  C.angle_axis[0]=0.0;\n  C.angle_axis[1]=0.0;\n  C.angle_axis[2]=0.0;\n  C.position[0]=0.0;\n  C.position[1]=0.0;\n  C.position[2]=0.0;\n  C.focal_length_x=525;\n  C.focal_length_y=525;\n  C.center_x=320;\n  C.center_y=240;\n  C.distortion_k1=0.01;\n  C.distortion_k2=0.02;\n  C.distortion_k3=0.03;\n  C.distortion_p1=0.01;\n  C.distortion_p2=0.01;\n\n  double intrinsics[9];\n  intrinsics[0] = C.focal_length_x;\n  intrinsics[1] = C.focal_length_y;\n  intrinsics[2] = C.center_x;\n  intrinsics[3] = C.center_y;\n  intrinsics[4] = C.distortion_k1;\n  intrinsics[5] = C.distortion_k2;\n  intrinsics[6] = C.distortion_k3;\n  intrinsics[7] = C.distortion_p1;\n  intrinsics[8] = C.distortion_p2;\n\n  double fx, fy, cx, cy, k1, k2, k3, p1, p2;\n  extractCameraIntrinsics(C.pb_intrinsics, fx, fy, cx, cy, k1, k2, k3, p1, p2);\n\n  ASSERT_NEAR(C.focal_length_x, fx, .00001);\n  ASSERT_NEAR(C.focal_length_y, fy, .00001);\n  ASSERT_NEAR(C.center_x, cx, .00001);\n  ASSERT_NEAR(C.center_y, cy, .00001);\n  ASSERT_NEAR(C.distortion_k1, k1, .00001);\n  ASSERT_NEAR(C.distortion_k2, k2, .00001);\n  ASSERT_NEAR(C.distortion_k3, k3, .00001);\n  ASSERT_NEAR(C.distortion_p1, p1, .00001);\n  ASSERT_NEAR(C.distortion_p2, p2, .00001);\n}\nTEST(IndustrialExtrinsicCalCeresSuite, rotationInverse)\n{\n  double R1[9], R2[9];\n  double angle_axis[3];\n  angle_axis[0] = .1;\n  angle_axis[1] = -3.0;\n  angle_axis[2] = .5;\n  ceres::AngleAxisToRotationMatrix(angle_axis, R1);\n  rotationInverse(R1, R2);\n  for(int i=0; i<3; i++){\n    for(int j=0; j<3; j++){\n      int index1 = i*3+j;\n      int index2 = i+j*3;\n      ASSERT_NEAR(R1[index1],R2[index2], .00001);\n    }\n  }\n}\nTEST(IndustrialExtrinsicCalCeresSuite, transformPoint)\n{\n  double point[3], tx[3];\n  tx[0] = 15.0;\n  tx[1] = 30.0;\n  tx[2] = 23;\n  point[0] = 10.0; \n  point[1] = -35;\n  point[2] = -100;\n  double angle_axis[3];\n  angle_axis[0] = .1;\n  angle_axis[1] = -3.0;\n  angle_axis[2] = .5;\n  double t_point[3];\n  transformPoint(angle_axis, tx, point, t_point);\n\n  Pose6d pose;\n  pose.setAngleAxis(angle_axis[0], angle_axis[1], angle_axis[2]);\n  pose.setOrigin(tx[0],tx[1],tx[2]);\n\n  // invert transformation and apply\n  Pose6d posei = pose.getInverse();\n  angle_axis[0] = posei.ax;\n  angle_axis[1] = posei.ay;\n  angle_axis[2] = posei.az;\n  tx[0] = posei.x;\n  tx[1] = posei.y;\n  tx[2] = posei.z;\n  double tt_point[3];\n  transformPoint(angle_axis, tx, t_point, tt_point);\n  ASSERT_NEAR(tt_point[0], point[0], .00001);\n  ASSERT_NEAR(tt_point[1], point[1], .00001);\n  ASSERT_NEAR(tt_point[2], point[2], .00001);\n}\n\nTEST(IndustrialExtrinsicCalCeresSuite, poseTransformPoint)\n{\n  Pose6d pose;\n  Pose6d posei;\n  double point[3];\n  point[0] = 10.0; \n  point[1] = -35;\n  point[2] = -100;\n  pose.setAngleAxis(1.2, 2.2, 3.3);\n  pose.setOrigin(1.2, 2.2, 3.3);\n  posei  = pose.getInverse();\n  \n  double t_point[3];\n  double tt_point[3];\n  poseTransformPoint(pose, point, t_point);\n  poseTransformPoint(posei, t_point, tt_point);\n  ASSERT_NEAR(tt_point[0], point[0], .00001);\n  ASSERT_NEAR(tt_point[1], point[1], .00001);\n  ASSERT_NEAR(tt_point[2], point[2], .00001);\n  \n}\n\nTEST(IndustrialExtrinsicCalCeresSuite, transformPoint3d)\n{\n  double  tx[3];\n  tx[0] = 15.0;\n  tx[1] = 30.0;\n  tx[2] = 23;\n  Point3d point;\n  point.x = 10.0; \n  point.y = -35;\n  point.z = -100;\n  double angle_axis[3];\n  angle_axis[0] = .1;\n  angle_axis[1] = -3.0;\n  angle_axis[2] = .5;\n  double t_point[3];\n  transformPoint3d(angle_axis, tx, point, t_point);\n  Point3d t_point3d;\n  t_point3d.x = t_point[0];\n  t_point3d.y = t_point[1];\n  t_point3d.z = t_point[2];\n\n  Pose6d pose;\n  pose.setAngleAxis(angle_axis[0], angle_axis[1], angle_axis[2]);\n  pose.setOrigin(tx[0],tx[1],tx[2]);\n\n  // invert transformation and apply\n  Pose6d posei = pose.getInverse();\n  angle_axis[0] = posei.ax;\n  angle_axis[1] = posei.ay;\n  angle_axis[2] = posei.az;\n  tx[0] = posei.x;\n  tx[1] = posei.y;\n  tx[2] = posei.z;\n\n  double tt_point[3];\n  transformPoint3d(angle_axis, tx, t_point3d, tt_point);\n  ASSERT_NEAR(tt_point[0], point.x, .00001);\n  ASSERT_NEAR(tt_point[1], point.y, .00001);\n  ASSERT_NEAR(tt_point[2], point.z, .00001);\n  \n}\nTEST(IndustrialExtrinsicCalCeresSuite, poseRotationMatrix)\n{\n  Pose6d pose;\n  double ax = .5; // must use small values to avoid alternate solutions\n  double ay = .23;\n  double az = .45;\n  pose.setAngleAxis(ax, ay, az);\n  pose.setOrigin(11.5, 21.5, 31.5);\n  double R[9];\n  poseRotationMatrix(pose, R);\n  double aa[3];\n  ceres::RotationMatrixToAngleAxis(R, aa);\n  ASSERT_NEAR(aa[0], ax, .00001);\n  ASSERT_NEAR(aa[1], ay, .00001);\n  ASSERT_NEAR(aa[2], az, .00001);\n}\n\nTEST(IndustrialExtrinsicCalCeresSuite, cameraPntResidualDist)\n{\n}\n\nTEST(IndustrialExtrinsicCalCeresSuite, cameraCircResidualDist)\n{\n}\nTEST(IndustrialExtrinsicCalCeresSuite, cameraCircResidual)\n{\n}\n// used for intrinsic cal \n// Camera may move to several locations (multiple extrinsics)\n// target has no transform, origin is origin of target, single static target\n// points are known, no calibraition of the target itself\nTEST(IndustrialExtrinsicCalCeresSuite, CircleCameraReprjErrorWithDistortion)\n{\n}\n// used for extrinsic cal of camera on robot with target on ground\n// finds transform from link to camera, and transform from robot to target\n// should have multiple images from different robot locations\nTEST(IndustrialExtrinsicCalCeresSuite, LinkCameraCircleTargetReprjError)\n{\n}\n\n\nTEST(IndustrialExtrinsicCalCeresSuite, create_points)\n{\n  Point3d x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20;\n  x1.pb[0]=1.0;x1.pb[1]=1.0;x1.pb[2]=1;\n  created_points.push_back(x1);\n  x2.pb[0]=0;x2.pb[1]=0;x2.pb[2]=0.01;\n  created_points.push_back(x2);\n  x3.pb[0]=0.65;x3.pb[1]=0.94;x3.pb[2]=0.01;\n  created_points.push_back(x3);\n  x4.pb[0]=0.2;x4.pb[1]=0.3;x4.pb[2]=0.01;\n  created_points.push_back(x4);\n  x5.pb[0]=0.372;x5.pb[1]=0.4;x5.pb[2]=0.4;\n  created_points.push_back(x5);\n  x6.pb[0]=0.3762;x6.pb[1]=0.8;x6.pb[2]=0.3;\n  created_points.push_back(x6);\n  x7.pb[0]=0.4;x7.pb[1]=0.389;x7.pb[2]=0.4;\n  created_points.push_back(x7);\n  x8.pb[0]=0.431;x8.pb[1]=0.7;x8.pb[2]=0.7;\n  created_points.push_back(x8);\n  x9.pb[0]=0.535;x9.pb[1]=0.9;x9.pb[2]=0.01;\n  created_points.push_back(x9);\n  x10.pb[0]=0.596;x10.pb[1]=1;x10.pb[2]=1.0;\n  created_points.push_back(x10);\n  x11.pb[0]=0.24;x11.pb[1]=1.0;x11.pb[2]=0.01;\n  created_points.push_back(x11);\n  x12.pb[0]=0.673;x12.pb[1]=1.7;x12.pb[2]=0.8;\n  created_points.push_back(x12);\n  x13.pb[0]=0.552;x13.pb[1]=1.15;x13.pb[2]=0.01;\n  created_points.push_back(x13);\n  x14.pb[0]=0.56;x14.pb[1]=0.81;x14.pb[2]=0.01;\n  created_points.push_back(x14);\n  x15.pb[0]=.70;x15.pb[1]=1.10;x15.pb[2]=0.01;\n  created_points.push_back(x15);\n  x16.pb[0]=0.3762;x16.pb[1]=0.02435;x16.pb[2]=0.3;\n  created_points.push_back(x16);\n  x17.pb[0]=0.0234;x17.pb[1]=0.389;x17.pb[2]=0.132;\n  created_points.push_back(x17);\n  x18.pb[0]=0.431;x18.pb[1]=0.245;x18.pb[2]=0.0235;\n  created_points.push_back(x18);\n  x19.pb[0]=0.535;x19.pb[1]=0.673;x19.pb[2]=0.01;\n  created_points.push_back(x19);\n  x20.pb[0]=0.76;x20.pb[1]=0.453;x20.pb[2]=1.0;\n  created_points.push_back(x20);\n  std::cout<<\"Original Point 1: \"<<x1.pb[0]<<\" \"<<x1.pb[1]<<\" \"<<x1.pb[2]<<std::endl;\n\n  //create known transform\n  aa[0] = 2.7;\n  aa[1] = 0.3;\n  aa[2] = 0.1;\n  p[0]=0.2;\n  p[1]=0.4;\n  p[2]=0.5;\n\n  // initialize the camera parameters\n  C.angle_axis[0]=0.0;\n  C.angle_axis[1]=0.0;\n  C.angle_axis[2]=0.0;\n  C.position[0]=0.0;\n  C.position[1]=0.0;\n  C.position[2]=0.0;\n  C.focal_length_x=525;\n  C.focal_length_y=525;\n  C.center_x=320;\n  C.center_y=240;\n  C.distortion_k1=0.01;\n  C.distortion_k2=0.02;\n  C.distortion_k3=0.03;\n  C.distortion_p1=0.01;\n  C.distortion_p2=0.01;\n\n  // transform points, and then project into image plane\n  Point3d t_point;\n  Observation o_point;\n  for (int i=0; i<created_points.size();i++)\n    {\n      t_point = xformPoint(created_points.at(i), aa[0], aa[1], aa[2], p[0], p[1], p[2]);\n      o_point = projectPoint(C,t_point);\n      transformed_points.push_back(t_point);\n      observations.push_back(o_point);\n    }\n}\n\nTEST(IndustrialExtrinsicCalCeresSuite, points_costfunction)\n{\n  //create known transform to move created points to transformed points\n  aa[0] = 2.7;\n  aa[1] = 0.3;\n  aa[2] = 0.1;\n  p[0]=0.2;\n  p[1]=0.4;\n  p[2]=0.5;\n\n  // initialize the camera parameters\n  C.angle_axis[0]=0.0;\n  C.angle_axis[1]=0.0;\n  C.angle_axis[2]=0.0;\n  C.position[0]=0.0;\n  C.position[1]=0.0;\n  C.position[2]=0.0;\n  C.focal_length_x=525;\n  C.focal_length_y=525;\n  C.center_x=320;\n  C.center_y=240;\n  C.distortion_k1=0.01;\n  C.distortion_k2=0.02;\n  C.distortion_k3=0.03;\n  C.distortion_p1=0.01;\n  C.distortion_p2=0.01;\n\n  // transform points, and then project into image plane\n  Point3d t_point;\n  Observation o_point;\n  for (int i=0; i<created_points.size();i++)\n    {\n      t_point = xformPoint(created_points.at(i), aa[0], aa[1], aa[2], p[0], p[1], p[2]);\n      o_point = projectPoint(C,t_point);\n      transformed_points.push_back(t_point);\n      observations.push_back(o_point);\n    }\n\n  double extrinsics[6];\n  extrinsics[0] = C.angle_axis[0];\n  extrinsics[1] = C.angle_axis[1];\n  extrinsics[2] = C.angle_axis[2];\n  extrinsics[3] = C.position[0];\n  extrinsics[4] = C.position[1];\n  extrinsics[5] = C.position[2];\n  \n  double intrinsics[9];\n  intrinsics[0] = C.focal_length_x;\n  intrinsics[1] = C.focal_length_y;\n  intrinsics[2] = C.center_x;\n  intrinsics[3] = C.center_y;\n  intrinsics[4] = C.distortion_k1;\n  intrinsics[5] = C.distortion_k2;\n  intrinsics[6] = C.distortion_k3;\n  intrinsics[7] = C.distortion_p1;\n  intrinsics[8] = C.distortion_p2;\n  ceres::Problem problem;\n  // when points, extrinsics, and intrinsics are not perturbed, there should be very little re-projection error\n  for (int j = 0; j < transformed_points.size(); ++j)\n    {\n      double ox = observations[j].image_loc_x;\n      double oy = observations[j].image_loc_y;\n      ceres::CostFunction* cost_function = CameraReprjErrorWithDistortion::Create(ox, oy);\n      problem.AddResidualBlock(cost_function, NULL, extrinsics, intrinsics, transformed_points[j].pb);\n      double residual[2];\n      CameraReprjErrorWithDistortion CFC(ox, oy);\n      CFC(extrinsics, intrinsics, transformed_points[j].pb, residual);\n      // no reprojection error should be observed\n      ASSERT_NEAR(0.0, residual[0], .1);\n      ASSERT_NEAR(0.0, residual[1], .1);\n    }\n\n  // optimization should therefore not do anything either\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::DENSE_SCHUR;\n  options.minimizer_progress_to_stdout = false;\n  options.max_num_iterations = 1000;\n  \n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n  \n  // no changes due to optimization\n  ASSERT_NEAR(C.angle_axis[0], extrinsics[0], .1);\n  ASSERT_NEAR(C.angle_axis[1], extrinsics[1], .1);\n  ASSERT_NEAR(C.angle_axis[2], extrinsics[2], .1);\n  ASSERT_NEAR(C.position[0], extrinsics[3], .1);\n  ASSERT_NEAR(C.position[1], extrinsics[4], .1);\n  ASSERT_NEAR(C.position[2], extrinsics[5], .1);\n\n  ASSERT_NEAR(C.focal_length_x, intrinsics[0], .1);\n  ASSERT_NEAR(C.focal_length_y, intrinsics[1], .1);\n  ASSERT_NEAR(C.center_x, intrinsics[2], .1);\n  ASSERT_NEAR(C.center_y, intrinsics[3], .1);\n  ASSERT_NEAR(C.distortion_k1, intrinsics[4], .1);\n  ASSERT_NEAR(C.distortion_k2, intrinsics[5], .1);\n  ASSERT_NEAR(C.distortion_k3, intrinsics[6], .1);\n  ASSERT_NEAR(C.distortion_p1, intrinsics[7], .1);\n  ASSERT_NEAR(C.distortion_p2, intrinsics[8], .1);\n\n}\n\n\nTEST(IndustrialExtrinsicCalCeresSuite, circle_cost)\n{\n  //create known transform to move created points to transformed points\n  aa[0] = 2.7;\n  aa[1] = 0.3;\n  aa[2] = 0.1;\n  p[0]=0.2;\n  p[1]=0.4;\n  p[2]=0.5;\n\n  // initialize the camera parameters\n  C.angle_axis[0]=0.0;\n  C.angle_axis[1]=0.0;\n  C.angle_axis[2]=0.0;\n  C.position[0]=0.0;\n  C.position[1]=0.0;\n  C.position[2]=0.0;\n  C.focal_length_x=525;\n  C.focal_length_y=525;\n  C.center_x=320;\n  C.center_y=240;\n  C.distortion_k1=0.01;\n  C.distortion_k2=0.02;\n  C.distortion_k3=0.03;\n  C.distortion_p1=0.01;\n  C.distortion_p2=0.01;\n\n  // transform points, and then project into image plane\n  Point3d t_point;\n  Observation o_point;\n  for (int i=0; i<created_points.size();i++)\n    {\n      t_point = xformPoint(created_points.at(i), aa[0], aa[1], aa[2], p[0], p[1], p[2]);\n      o_point = projectPoint(C,t_point);\n      transformed_points.push_back(t_point);\n      observations.push_back(o_point);\n    }\n\n  double extrinsics[6];\n  extrinsics[0] = C.angle_axis[0];\n  extrinsics[1] = C.angle_axis[1];\n  extrinsics[2] = C.angle_axis[2];\n  extrinsics[3] = C.position[0];\n  extrinsics[4] = C.position[1];\n  extrinsics[5] = C.position[2];\n  \n  double intrinsics[9];\n  intrinsics[0] = C.focal_length_x;\n  intrinsics[1] = C.focal_length_y;\n  intrinsics[2] = C.center_x;\n  intrinsics[3] = C.center_y;\n  intrinsics[4] = C.distortion_k1;\n  intrinsics[5] = C.distortion_k2;\n  intrinsics[6] = C.distortion_k3;\n  intrinsics[7] = C.distortion_p1;\n  intrinsics[8] = C.distortion_p2;\n  ceres::Problem problem;\n  // when points, extrinsics, and intrinsics are not perturbed, there should be very little re-projection error\n  for (int j = 0; j < transformed_points.size(); ++j)\n    {\n      double ox = observations[j].image_loc_x;\n      double oy = observations[j].image_loc_y;\n      ceres::CostFunction* cost_function = CameraReprjErrorWithDistortion::Create(ox, oy);\n      problem.AddResidualBlock(cost_function, NULL, extrinsics, intrinsics, transformed_points[j].pb);\n      double residual[2];\n      CameraReprjErrorWithDistortion CFC(ox, oy);\n      CFC(extrinsics, intrinsics, transformed_points[j].pb, residual);\n      // no reprojection error should be observed\n      ASSERT_NEAR(0.0, residual[0], .1);\n      ASSERT_NEAR(0.0, residual[1], .1);\n    }\n\n  // optimization should therefore not do anything either\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::DENSE_SCHUR;\n  options.minimizer_progress_to_stdout = false;\n  options.max_num_iterations = 1000;\n  \n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n  \n  // no changes due to optimization\n  ASSERT_NEAR(C.angle_axis[0], extrinsics[0], .1);\n  ASSERT_NEAR(C.angle_axis[1], extrinsics[1], .1);\n  ASSERT_NEAR(C.angle_axis[2], extrinsics[2], .1);\n  ASSERT_NEAR(C.position[0], extrinsics[3], .1);\n  ASSERT_NEAR(C.position[1], extrinsics[4], .1);\n  ASSERT_NEAR(C.position[2], extrinsics[5], .1);\n\n  ASSERT_NEAR(C.focal_length_x, intrinsics[0], .1);\n  ASSERT_NEAR(C.focal_length_y, intrinsics[1], .1);\n  ASSERT_NEAR(C.center_x, intrinsics[2], .1);\n  ASSERT_NEAR(C.center_y, intrinsics[3], .1);\n  ASSERT_NEAR(C.distortion_k1, intrinsics[4], .1);\n  ASSERT_NEAR(C.distortion_k2, intrinsics[5], .1);\n  ASSERT_NEAR(C.distortion_k3, intrinsics[6], .1);\n  ASSERT_NEAR(C.distortion_p1, intrinsics[7], .1);\n  ASSERT_NEAR(C.distortion_p2, intrinsics[8], .1);\n\n}\n\n\n\nPoint3d xformPoint(Point3d &original_point, double &ax, double &ay, double &az, double &x, double&y, double &z)\n{\n  //std::cout<<\"ange axis inputs ax, ay, az: \"<<ax<<\", \"<<ay<<\", \"<<az<<std::endl;\n  Eigen::Matrix3f m_ceres;\n  Eigen::Matrix3f m_eigen;\n  m_eigen = Eigen::AngleAxisf(ax, Eigen::Vector3f::UnitX())\n    * Eigen::AngleAxisf(ay, Eigen::Vector3f::UnitY())\n    * Eigen::AngleAxisf(az, Eigen::Vector3f::UnitZ());\n  //std::cout<<\"m_eigen : \"<<std::endl<< m_eigen <<std::endl;\n  double aa[3]; // angle axis\n  double p[3]; // point rotated\n  aa[0] = ax;\n  aa[1] = ay;\n  aa[2] = az;\n  Eigen::Vector3f orig_point(original_point.pb[0], original_point.pb[1], original_point.pb[2]);\n  //std::cout<<\"within transformPoint, original point Vector3f x, y, z: \"<<orig_point.x()<<\", \"<<orig_point.y()<<\", \"<<orig_point.z()<<std::endl;\n\n  double R[9];\n  ceres::AngleAxisToRotationMatrix(aa, R);\n  m_ceres << R[0], R[1],R[2],\n    R[3], R[4], R[5],\n    R[6], R[7], R[8];\n  //std::cout<<\"m_ceres : \"<<std::endl<< m_ceres <<std::endl;\n  Eigen::Vector3f rot_point=m_ceres*orig_point;\n  //std::cout<<\"within transformPoint, rotated point Vector3f x, y, z: \"<<rot_point.x()<<\", \"<<rot_point.y()<<\", \"<<rot_point.z()<<std::endl;\n  double xp1 = rot_point.x() + x; // point rotated and translated\n  double yp1 = rot_point.y() + y;\n  double zp1 = rot_point.z() + z;\n  //std::cout<<\"within transformPoint, original point double x, y, z: \"<<xp1<<\", \"<<yp1<<\", \"<<zp1<<std::endl;\n  Point3d t_point;\n  t_point.pb[0]=xp1;t_point.pb[1]=yp1;t_point.pb[2]=zp1;\n  //std::cout<<\"within transformPoint, t_point x, y, z: \"<<t_point.pb[0]<<\", \"<<t_point.pb[1]<<\", \"<<t_point.pb[2]<<std::endl;\n  return t_point;\n}\n\n// Run all the tests that were declared with TEST()\nint main(int argc, char **argv)\n{\n  //ros::init(argc, argv, \"test\");\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n\n}\n", "meta": {"hexsha": "60fdcc1bf20ffdcf748cd537e9a3f420a2ce52b2", "size": 20208, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "industrial_extrinsic_cal/test/ceres_utest.cpp", "max_stars_repo_name": "ntrlmt/industrial_calibration", "max_stars_repo_head_hexsha": "b144dddd3a81c768a079f8f2a0120f11e9917026", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-05T12:42:04.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-05T12:42:04.000Z", "max_issues_repo_path": "industrial_extrinsic_cal/test/ceres_utest.cpp", "max_issues_repo_name": "ntrlmt/industrial_calibration", "max_issues_repo_head_hexsha": "b144dddd3a81c768a079f8f2a0120f11e9917026", "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": "industrial_extrinsic_cal/test/ceres_utest.cpp", "max_forks_repo_name": "ntrlmt/industrial_calibration", "max_forks_repo_head_hexsha": "b144dddd3a81c768a079f8f2a0120f11e9917026", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-10-17T14:31:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T04:23:03.000Z", "avg_line_length": 30.479638009, "max_line_length": 145, "alphanum_fraction": 0.671763658, "num_tokens": 6982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5042443586692963}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/eye.hpp\n *\n * \\brief The \\c eye operation.\n *\n * The \\c eye operation creates an identity matrix.\n * This operation takes inspiration from the MATLAB's \\e eye function\n * and the Mathematica's \\e IdentityMatrix function.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2021, 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_UBLAS_EYE_HPP\n#define BOOST_NUMERIC_UBLAS_EYE_HPP\n\n//#include <boost/numeric/ublas/fwd.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <cstddef>\n#include <memory>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n#if __cplusplus > 199711L\n// C++0x allows default template parameters for functions\n\n/**\n * \\brief Create an unmutable identity square matrix.\n *\n * \\tparam ValueT The type of object stored in the matrix (like double, float, complex, etc...).\n *  By default, an integral type is used.\n * \\tparam AllocT An allocator for storing the zeros and one elements.\n *  By default, a standard allocator is used.\n *\n * \\param n The number of rows and columns of the resulting identity matrix.\n * \\return An unmutable n-by-n identity matrix.\n */\ntemplate<typename ValueT = int, // The same default value used by the `identity_matrix` type.\n         typename AllocT = std::allocator<ValueT> > // The same default allocator used by the `identity_matrix` type.\nBOOST_UBLAS_INLINE\nidentity_matrix<ValueT,AllocT> eye(std::size_t n)\n{\n    return identity_matrix<ValueT,AllocT>(n);\n}\n\n/**\n * \\brief Create an unmutable identity rectangular matrix.\n *\n * \\tparam ValueT The type of object stored in the matrix (like double, float, complex, etc...)\n *  By default, an integral type is used.\n * \\tparam AllocT An allocator for storing the zeros and one elements.\n *  By default, a standard allocator is used.\n *\n * \\param nr The number of rows of the resulting identity matrix.\n * \\param nc The number of columns of the resulting identity matrix.\n * \\return An unmutable nr-by-nc identity matrix.\n */\ntemplate<typename ValueT = int, // The same default value used by the `identity_matrix` type.\n         typename AllocT = std::allocator<ValueT> > // The same default allocator used by the `identity_matrix` type.\nBOOST_UBLAS_INLINE\nidentity_matrix<ValueT,AllocT> eye(std::size_t nr, std::size_t nc)\n{\n    return identity_matrix<ValueT,AllocT>(nr, nc);\n}\n\n#else // __cplusplus\n\n// C++98 does not allow default template parameters for functions\n\n/**\n * \\brief Create an unmutable identity square matrix.\n *\n * \\tparam ValueT The type of object stored in the matrix (like double, float, complex, etc...).\n * \\tparam AllocT An allocator for storing the zeros and one elements.\n *\n * \\param n The number of rows and columns of the resulting identity matrix.\n * \\return An unmutable n-by-n identity matrix.\n */\ntemplate<typename ValueT,\n         typename AllocT>\nBOOST_UBLAS_INLINE\nidentity_matrix<ValueT,AllocT> eye(std::size_t n)\n{\n    return identity_matrix<ValueT,AllocT>(n);\n}\n\n/**\n * \\brief Create an unmutable identity square matrix with a default allocator.\n *\n * \\tparam ValueT The type of object stored in the matrix (like double, float, complex, etc...).\n *\n * \\param n The number of rows and columns of the resulting identity matrix.\n * \\return An unmutable n-by-n identity matrix.\n */\ntemplate<typename ValueT>\nBOOST_UBLAS_INLINE\nidentity_matrix<ValueT> eye(std::size_t n)\n{\n    return identity_matrix<ValueT>(n);\n}\n\n/**\n * \\brief Create an unmutable identity rectangular matrix.\n *\n * \\tparam ValueT The type of object stored in the matrix (like double, float, complex, etc...)\n *  By default, an integral type is used.\n * \\tparam AllocT An allocator for storing the zeros and one elements.\n *  By default, a standard allocator is used.\n *\n * \\param nr The number of rows of the resulting identity matrix.\n * \\param nc The number of columns of the resulting identity matrix.\n * \\return An unmutable nr-by-nc identity matrix.\n */\ntemplate<typename ValueT,\n         typename AllocT>\nBOOST_UBLAS_INLINE\nidentity_matrix<ValueT,AllocT> eye(std::size_t nr, std::size_t nc)\n{\n    return identity_matrix<ValueT,AllocT>(nr, nc);\n}\n\n/**\n * \\brief Create an unmutable identity rectangular matrix with a default allocator.\n *\n * \\tparam ValueT The type of object stored in the matrix (like double, float, complex, etc...)\n *  By default, an integral type is used.\n *\n * \\param nr The number of rows of the resulting identity matrix.\n * \\param nc The number of columns of the resulting identity matrix.\n * \\return An unmutable nr-by-nc identity matrix.\n */\ntemplate<typename ValueT>\nBOOST_UBLAS_INLINE\nidentity_matrix<ValueT> eye(std::size_t nr, std::size_t nc)\n{\n    return identity_matrix<ValueT>(nr, nc);\n}\n\n#endif // __cplusplus\n\n/**\n * \\brief Create an unmutable identity square matrix with default value type and allocator.\n *\n * \\param n The number of rows and columns of the resulting identity matrix.\n * \\return An unmutable n-by-n identity matrix.\n */\nBOOST_UBLAS_INLINE\nidentity_matrix<> eye(std::size_t n)\n{\n    return identity_matrix<>(n);\n}\n\n/**\n * \\brief Create an unmutable identity rectangular matrix with default value type and allocator.\n *\n * \\param nr The number of rows of the resulting identity matrix.\n * \\param nc The number of columns of the resulting identity matrix.\n * \\return An unmutable nr-by-nc identity matrix.\n */\nBOOST_UBLAS_INLINE\nidentity_matrix<> eye(std::size_t nr, std::size_t nc)\n{\n    return identity_matrix<>(nr, nc);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_EYE_HPP\n", "meta": {"hexsha": "661d1d34d68d1d5fe8bf8636f5827f775c069fa7", "size": 5868, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/eye.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/eye.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/eye.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": 32.0655737705, "max_line_length": 117, "alphanum_fraction": 0.7339809134, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.50422637192879}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\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// Example: Custom coordinate system example\n\n#include <iostream>\n\n#include <boost/geometry/geometry.hpp>\n\n// 1: declare a coordinate system. For example for Mars\n//    Like for the Earth, we let the use choose between degrees or radians\n//    (Unfortunately, in real life Mars has two coordinate systems:\n//     http://planetarynames.wr.usgs.gov/Page/MARS/system)\ntemplate<typename DegreeOrRadian>\nstruct martian\n{\n    typedef DegreeOrRadian units;\n};\n\n// 2: give it also a family\nstruct martian_tag;\n\n// 3: register to which coordinate system family it belongs to\n//    this must be done in namespace boost::geometry::traits\nnamespace boost { namespace geometry { namespace traits\n{\n\ntemplate <typename DegreeOrRadian>\nstruct cs_tag<martian<DegreeOrRadian> >\n{\n    typedef martian_tag type;\n};\n\n}}} // namespaces\n\n\n// NOTE: if the next steps would not be here,\n// compiling a distance function call with martian coordinates\n// would result in a MPL assertion\n\n// 4: so register a distance strategy as its default strategy\nnamespace boost { namespace geometry { namespace strategy { namespace distance { namespace services\n{\n\ntemplate <typename Point1, typename Point2>\nstruct default_strategy<point_tag, point_tag, Point1, Point2, martian_tag, martian_tag>\n{\n    typedef haversine<double> type;\n};\n\n}}}}} // namespaces\n\n// 5: not worked out. To implement a specific distance strategy for Mars,\n//    e.g. with the Mars radius given by default,\n//    you will have to implement (/register) several other metafunctions:\n//      tag, return_type, similar_type, comparable_type,\n//    and structs:\n//      get_similar, get_comparable, result_from_distance\n//   See e.g. .../boost/geometry/extensions/gis/geographic/strategies/andoyer.hpp\n\nint main()\n{\n    typedef boost::geometry::model::point\n        <\n            double, 2, martian<boost::geometry::degree>\n        > mars_point;\n\n    // Declare two points\n    // (Source: http://nssdc.gsfc.nasa.gov/planetary/mars_mileage_guide.html)\n    // (Other sources: Wiki and Google give slightly different coordinates, resulting\n    //  in other distance, 20 km off)\n    mars_point viking1(-48.23, 22.54); // Viking 1 landing site in Chryse Planitia\n    mars_point pathfinder(-33.55, 19.33); // Pathfinder landing site in Ares Vallis\n\n    double d = boost::geometry::distance(viking1, pathfinder); // Distance in radians on unit-sphere\n\n    // Using the Mars mean radius\n    // (Source: http://nssdc.gsfc.nasa.gov/planetary/factsheet/marsfact.html)\n    std::cout << \"Distance between Viking1 and Pathfinder landing sites: \"\n        << d * 3389.5 << \" km\" << std::endl;\n\n    // We would get 832.616 here, same order as the 835 (rounded on 5 km) listed\n    // on the mentioned site\n\n#ifdef OPTIONALLY_ELLIPSOIDAL\n    // Optionally the distance can be calculated more accurate by an Ellipsoidal approach,\n    // giving 834.444 km\n    d = boost::geometry::distance(viking1, pathfinder,\n        boost::geometry::strategy::distance::andoyer<mars_point>\n            (boost::geometry::srs::spheroid<double>(3396.2, 3376.2)));\n    std::cout << \"Ellipsoidal distance: \" << d << \" km\" << std::endl;\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "3a802cc79f905cc367d280147ff85f9a93da81a5", "size": 3583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/geometry/example/c10_custom_cs_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/geometry/example/c10_custom_cs_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/geometry/example/c10_custom_cs_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": 34.786407767, "max_line_length": 100, "alphanum_fraction": 0.7125313983, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5042263713978299}}
{"text": "#ifndef CANNON_GEOM_TRAJECTORY\n#define CANNON_GEOM_TRAJECTORY \n\n/*!\n * \\file cannon/geom/trajectory.hpp\n * \\brief File containing Trajectory class definition.\n */\n\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include <cannon/utils/class_forward.hpp>\n\nusing namespace Eigen;\n\nnamespace cannon {\n\n  namespace math {\n    CANNON_CLASS_FORWARD(MultiSpline);\n  }\n\n  using namespace cannon::math;\n\n  namespace geom {\n\n    /*!\n     * \\brief Class representing a time-parameterized trajectory. \n     */\n    class Trajectory {\n      public:\n        \n        /*!\n         * \\brief Default constructor.\n         */\n        Trajectory();\n\n        /*!\n         * \\brief Constructor taking vector of states and times.\n         */\n        Trajectory(const std::vector<VectorXd> &states,\n                   const std::vector<double> times);\n\n        /*!\n         * \\brief Get the state of this trajectory at the input time. This\n         * trajectory is treated as a piecewise-linear function over time.\n         *\n         * \\param t The time to evaluate the trajectory at.\n         *\n         * \\returns The linearly interpolated state of this trajectory at the\n         * input time.\n         */\n        VectorXd operator()(double t) const;\n\n        /*!\n         * \\brief Add a new state at the end of this trajectory, at the input\n         * time.\n         *\n         * \\param state The state to add.\n         * \\param time The time for the new state. Should be greater than any\n         * time in the trajectory so far.\n         */\n        void push_back(const Ref<const VectorXd>& state, double time);\n\n        /*!\n         * \\brief Get the length (total time) of this trajectory.\n         *\n         * \\returns Length of trajectory.\n         */\n        double length() const;\n\n        /*!\n         * \\brief Get the size (number of states) in this trajectory.\n         *\n         * \\returns Trajectory size.\n         */\n        size_t size() const;\n\n        /*!\n         * \\brief Get a spline that interpolates this trajectory.\n         *\n         * \\returns A spline which smoothly interpolates this trajectory.\n         */\n        MultiSpline interp() const;\n\n        /*!\n         * \\brief Save this trajectory to a file.\n         *\n         * \\param path The path to save this trajectory to.\n         */\n        void save(const std::string& path);\n\n        /*!\n         * \\brief Load a trajectory from a file. Overwrites any existing points\n         * in this trajectory.\n         *\n         * \\param path The path to load a trajectory from.\n         */\n        void load(const std::string& path);\n\n      private:\n\n        /*!\n         * \\brief Find the closest idx such that times_[idx] <= t\n         *\n         * \\param t Input value to locate\n         *\n         * \\returns Index of closest time\n         */\n        unsigned int find_closest_t_(double t) const;\n\n        std::vector<VectorXd> states_; //!< States in trajectory\n        std::vector<double> times_; //!< Times for states in trajectory\n\n    };\n\n    /*!\n     * \\brief Class representing a time-parameterized trajectory with controls. \n     */\n    class ControlledTrajectory {\n      public:\n        \n        /*!\n         * \\brief Default constructor.\n         */\n        ControlledTrajectory();\n\n        /*!\n         * \\brief Constructor taking vector of states, vector of controls, and times.\n         */\n        ControlledTrajectory(const std::vector<VectorXd> &states,\n                             const std::vector<VectorXd> &controls,\n                             const std::vector<double> times);\n\n        /*!\n         * \\brief Get the trajectory of states from this controlled trajectory.\n         *\n         * \\returns A trajectory of the states making up this controlled trajectory.\n         */\n        Trajectory state_traj() const;\n\n        /*!\n         * \\brief Get the state and control of this controlled trajectory at the\n         * input time. This trajectory is treated as a piecewise-linear function\n         * over time.\n         *\n         * \\param t The time to evaluate the trajectory at.\n         *\n         * \\returns A pair containing the linearly interpolated state and\n         * control of this trajectory at the input time.\n         */\n        std::pair<VectorXd, VectorXd> operator()(double t) const;\n\n        /*!\n         * \\brief Add a new state and control at the end of this trajectory, at\n         * the input time.\n         *\n         * \\param state The state to add.\n         * \\param control The control to add.\n         * \\param time The time for the new state. Should be greater than any\n         * time in the trajectory so far.\n         */\n        void push_back(const Ref<const VectorXd> &state,\n                       const Ref<const VectorXd> &control, double time);\n\n        /*!\n         * \\brief Get the length (total time) of this trajectory.\n         *\n         * \\returns Length of trajectory.\n         */\n        double length() const;\n\n        /*!\n         * \\brief Get the size (number of states) of this trajectory.\n         *\n         * \\returns Trajectory size.\n         */\n        size_t size() const;\n\n        /*!\n         * \\brief Save this trajectory to a file.\n         *\n         * \\param path The path to save this trajectory to.\n         */\n        void save(const std::string& path);\n\n        /*!\n         * \\brief Load a trajectory from a file. Overwrites any existing points\n         * in this trajectory.\n         *\n         * \\param path The path to load a trajectory from.\n         */\n        void load(const std::string& path);\n\n      private:\n\n        /*!\n         * \\brief Find the closest idx such that times_[idx] <= t\n         *\n         * \\param t Input value to locate\n         *\n         * \\returns Index of closest time\n         */\n        unsigned int find_closest_t_(double t) const;\n\n\n        std::vector<VectorXd> states_; //!< States in trajectory\n        std::vector<VectorXd> controls_; //!< Controls in trajectory\n        std::vector<double> times_; //!< Times for states in trajectory\n\n    };\n\n  }\n}\n\n#endif /* ifndef CANNON_GEOM_TRAJECTORY */\n", "meta": {"hexsha": "d27371f46110fafa6b214d0a9f0ab5315a851716", "size": 6089, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/geom/trajectory.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/geom/trajectory.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/geom/trajectory.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": 28.0599078341, "max_line_length": 85, "alphanum_fraction": 0.5569058959, "num_tokens": 1264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5042263667791251}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2016-2017, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_TEST_DISTANCE_GEO_COMMON_HPP\n#define BOOST_GEOMETRY_TEST_DISTANCE_GEO_COMMON_HPP\n\n#include <iostream>\n#include <string>\n\n#include <boost/mpl/assert.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/type_traits/is_same.hpp>\n\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/segment.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/ring.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/multi_point.hpp>\n#include <boost/geometry/geometries/multi_linestring.hpp>\n#include <boost/geometry/geometries/multi_polygon.hpp>\n\n#include <boost/geometry/io/wkt/write.hpp>\n#include <boost/geometry/io/dsv/write.hpp>\n\n#include <boost/geometry/algorithms/num_interior_rings.hpp>\n#include <boost/geometry/algorithms/distance.hpp>\n\n#include <boost/geometry/strategies/strategies.hpp>\n\n#include <from_wkt.hpp>\n#include <string_from_type.hpp>\n\n#include \"distance_brute_force.hpp\"\n\nnamespace bg = ::boost::geometry;\n\n//===================================================================\n//tag dispatching for swaping arguments in segments\n\ntemplate <typename Tag> struct dispatch\n{\n    template <typename T>\n    static inline T swap(T const& t)\n    {\n        return t;\n    }\n};\n\n// Specialization for segments\ntemplate <> struct dispatch<boost::geometry::segment_tag>\n{\n    template <typename Segment>\n    static inline Segment swap(Segment const& s)\n    {\n        Segment s_swaped;\n\n        bg::set<0, 0>(s_swaped, bg::get<1, 0>(s));\n        bg::set<0, 1>(s_swaped, bg::get<1, 1>(s));\n        bg::set<1, 0>(s_swaped, bg::get<0, 0>(s));\n        bg::set<1, 1>(s_swaped, bg::get<0, 1>(s));\n\n        return s_swaped;\n    }\n};\n\n//========================================================================\n\n\ntemplate <typename T>\nstruct check_equal\n{\n    template <typename Value, typename = void>\n    struct equal_to\n    {\n        static inline void apply(Value const& x, Value const& y)\n        {\n            BOOST_CHECK(x == y);\n        }\n    };\n\n    template <typename Dummy>\n    struct equal_to<double, Dummy>\n    {\n        static inline void apply(double x, double y)\n        {\n            BOOST_CHECK_CLOSE(x, y, 0.001);\n        }\n    };\n\n    template <typename Geometry1, typename Geometry2>\n    static inline void apply(std::string const& /*case_id*/,\n                             std::string const& /*subcase_id*/,\n                             Geometry1 const& /*geometry1*/,\n                             Geometry2 const& /*geometry2*/,\n                             T const& detected,\n                             T const& expected)\n    {\n        equal_to<T>::apply(expected, detected);\n    }\n};\n\n//========================================================================\n\ntemplate\n<\n    typename Geometry1, typename Geometry2,\n    int id1 = bg::geometry_id<Geometry1>::value,\n    int id2 = bg::geometry_id<Geometry2>::value\n>\nstruct test_distance_of_geometries\n    : public test_distance_of_geometries<Geometry1, Geometry2, 0, 0>\n{};\n\n\ntemplate <typename Geometry1, typename Geometry2>\nstruct test_distance_of_geometries<Geometry1, Geometry2, 0, 0>\n{\n    template <typename DistanceType, typename Strategy>\n    static inline\n    void apply(std::string const& case_id,\n               std::string const& wkt1,\n               std::string const& wkt2,\n               DistanceType const& expected_distance,\n               Strategy const& strategy,\n               bool test_reversed = true,\n               bool swap_geometry_args = false)\n    {\n        Geometry1 geometry1 = from_wkt<Geometry1>(wkt1);\n        Geometry2 geometry2 = from_wkt<Geometry2>(wkt2);\n\n        apply(case_id, geometry1, geometry2,\n              expected_distance,\n              strategy, test_reversed, swap_geometry_args);\n    }\n\n\n    template\n    <\n        typename DistanceType,\n        typename Strategy\n    >\n    static inline\n    void apply(std::string const& case_id,\n               Geometry1 const& geometry1,\n               Geometry2 const& geometry2,\n               DistanceType const& expected_distance,\n               Strategy const& strategy,\n               bool test_reversed = true,\n               bool swap_geometry_args = false)\n    {\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\n        std::cout << \"case ID: \" << case_id << \"; \"\n                  << \"G1: \" << bg::wkt(geometry1)\n                  << \" - \"\n                  << \"G2: \" << bg::wkt(geometry2)\n                  << std::endl;\n#endif\n        namespace services = bg::strategy::distance::services;\n\n        using bg::unit_test::distance_brute_force;\n\n        typedef typename bg::default_distance_result\n            <\n                Geometry1, Geometry2\n            >::type default_distance_result;\n\n        typedef typename services::return_type\n            <\n                Strategy, Geometry1, Geometry2\n            >::type distance_result_from_strategy;\n\n        static const bool same_regular = boost::is_same\n            <\n                default_distance_result,\n                distance_result_from_strategy\n            >::type::value;\n\n        BOOST_CHECK(same_regular);\n\n        // check distance with passed strategy\n        distance_result_from_strategy dist =\n            bg::distance(geometry1, geometry2, strategy);\n\n        check_equal\n            <\n                distance_result_from_strategy\n            >::apply(case_id, \"a\", geometry1, geometry2,\n                     dist, expected_distance);\n\n        // check against the comparable distance computed in a\n        // brute-force manner\n        default_distance_result dist_brute_force\n            = distance_brute_force(geometry1, geometry2, strategy);\n\n        check_equal\n            <\n                default_distance_result\n            >::apply(case_id, \"b\", geometry1, geometry2,\n                     dist_brute_force, expected_distance);\n\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\n        std::cout << string_from_type<typename bg::coordinate_type<Geometry1>::type>::name()\n                  << string_from_type<typename bg::coordinate_type<Geometry2>::type>::name()\n                  << \" -> \"\n                  << string_from_type<default_distance_result>::name()\n                  << std::endl;\n        std::cout << \"expected distance = \"\n                  << expected_distance << \" ; \"\n                  << std::endl;\n        std::cout << \"distance = \"\n                  << dist << \" ; \"\n                  << std::endl;\n\n        if ( !test_reversed )\n        {\n            std::cout << std::endl;\n        }\n#endif\n\n        if ( test_reversed )\n        {\n            // check distance with given strategy\n            dist = bg::distance(geometry2, geometry1, strategy);\n\n            check_equal\n                <\n                    default_distance_result\n                >::apply(case_id, \"ra\", geometry2, geometry1,\n                         dist, expected_distance);\n\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\n            std::cout << \"distance[reversed args] = \"\n                      << dist\n                      << std::endl;\n#endif\n        }\n\n        if (swap_geometry_args)\n        {\n            Geometry1 g1 = dispatch\n                <\n                    typename boost::geometry::tag<Geometry1>::type\n                >::swap(geometry1);\n\n            Geometry2 g2 = dispatch\n                <\n                    typename boost::geometry::tag<Geometry2>::type\n                >::swap(geometry2);\n\n            // check distance with given strategy\n            dist = bg::distance(g1, g2, strategy);\n\n            check_equal\n                <\n                    default_distance_result\n                >::apply(case_id, \"swap\", g1, g2,\n                         dist, expected_distance);\n\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\n            std::cout << \"distance[swap geometry args] = \"\n                      << dist\n                      << std::endl;\n            std::cout << std::endl;\n#endif\n         }\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\n            std::cout << std::endl;\n#endif\n\n    }\n};\n\n\n//========================================================================\n\n\ntemplate <typename Geometry1, typename Geometry2, typename Strategy>\nvoid test_empty_input(Geometry1 const& geometry1,\n                      Geometry2 const& geometry2,\n                      Strategy const& strategy)\n{\n    try\n    {\n        bg::distance(geometry1, geometry2);\n    }\n    catch(bg::empty_input_exception const& )\n    {\n        return;\n    }\n    BOOST_CHECK_MESSAGE(false,\n                        \"A empty_input_exception should have been thrown\");\n\n    try\n    {\n        bg::distance(geometry2, geometry1);\n    }\n    catch(bg::empty_input_exception const& )\n    {\n        return;\n    }\n    BOOST_CHECK_MESSAGE(false,\n                        \"A empty_input_exception should have been thrown\");\n\n    try\n    {\n        bg::distance(geometry1, geometry2, strategy);\n    }\n    catch(bg::empty_input_exception const& )\n    {\n        return;\n    }\n    BOOST_CHECK_MESSAGE(false,\n                        \"A empty_input_exception should have been thrown\");\n\n    try\n    {\n        bg::distance(geometry2, geometry1, strategy);\n    }\n    catch(bg::empty_input_exception const& )\n    {\n        return;\n    }\n    BOOST_CHECK_MESSAGE(false,\n                        \"A empty_input_exception should have been thrown\");\n}\n\n#endif // BOOST_GEOMETRY_TEST_DISTANCE_GEO_COMMON_HPP\n", "meta": {"hexsha": "a81af7ad1ba7cccddf12093e6d57a38d9b67c40e", "size": 9797, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/distance/test_distance_geo_common.hpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "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": "test/algorithms/distance/test_distance_geo_common.hpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "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": "test/algorithms/distance/test_distance_geo_common.hpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "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": 28.9852071006, "max_line_length": 92, "alphanum_fraction": 0.566499949, "num_tokens": 2064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5042263586036361}}
{"text": "/*\n * Copyright Andrey Semashev 2020\n *\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/*!\n * \\file bit_ops.hpp\n *\n * This header includes all algorithms for bit operations.\n */\n\n#ifndef BOOST_BIT_OPS_HPP_INCLUDED_\n#define BOOST_BIT_OPS_HPP_INCLUDED_\n\n#include <boost/bit_ops/pow2.hpp>\n#include <boost/bit_ops/counting.hpp>\n#include <boost/bit_ops/rotating.hpp>\n\n#endif // BOOST_BIT_OPS_HPP_INCLUDED_\n", "meta": {"hexsha": "e18005d80f44a2caf537b72caf120affe7287ec3", "size": 515, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/bit_ops.hpp", "max_stars_repo_name": "Lastique/bit_ops", "max_stars_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops.hpp", "max_issues_repo_name": "Lastique/bit_ops", "max_issues_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops.hpp", "max_forks_repo_name": "Lastique/bit_ops", "max_forks_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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.4090909091, "max_line_length": 61, "alphanum_fraction": 0.759223301, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.504226358603636}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Hidekazu Ikeno\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\n * THE SOFTWARE.\n */\n\n///\n/// \\file prony_like_method_common.hpp\n///\n#ifndef MXPFIT_PRONY_LIKE_METHOD_COMMON_HPP\n#define MXPFIT_PRONY_LIKE_METHOD_COMMON_HPP\n\n#include <cassert>\n#include <type_traits>\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\n#include <mxpfit/exponential_sum.hpp>\n#include <mxpfit/matrix_free_gemv.hpp>\n#include <mxpfit/vandermonde_least_squares.hpp>\n\nnamespace mxpfit\n{\n\nnamespace detail\n{\n\n/// \\internal\n/// Select roots of Prony polynomials on the unit disk\ntemplate <typename T>\nstruct prony_roots_on_unit_disk\n{\n    using Scalar        = T;\n    using RealScalar    = typename Eigen::NumTraits<Scalar>::Real;\n    using ComplexScalar = std::complex<RealScalar>;\n    using Index         = Eigen::Index;\n\n    using Vector        = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using RealVector    = Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>;\n    using ComplexVector = Eigen::Matrix<ComplexScalar, Eigen::Dynamic, 1>;\n\n    enum\n    {\n        IsComplex = Eigen::NumTraits<Scalar>::IsComplex,\n    };\n\n    /// \\param z  array of roots to be filtered\n    /// \\param tolerance  small real number to acceptable tolerance for the\n    //                    mangnitude of roots.\n    static ComplexVector compute(const Eigen::Ref<const ComplexVector>& z,\n                                 RealScalar tolerance)\n    {\n        using Eigen::numext::abs;\n        using Eigen::numext::imag;\n        static const auto eps     = Eigen::NumTraits<RealScalar>::epsilon();\n        constexpr const auto zero = RealScalar();\n        constexpr const auto one  = RealScalar(1);\n\n        // Count the number of roots insize unit disk\n        Index count = 0;\n        for (Index i = 0; i < z.size(); ++i)\n        {\n            const auto abs_zi = abs(z(i));\n            if (abs_zi <= one + tolerance)\n            {\n                if (IsComplex)\n                {\n                    ++count;\n                }\n                else\n                {\n                    // Discard negative real z(i).\n                    const auto xi = real(z(i));\n                    const auto yi = imag(z(i));\n                    if (!(abs(yi) < eps && xi < zero))\n                    {\n                        ++count;\n                    }\n                }\n            }\n        }\n\n        ComplexVector ret(count);\n        Index n = 0;\n        for (Index i = 0; i < z.size(); ++i)\n        {\n            const auto abs_zi = abs(z(i));\n            if (abs_zi <= one + tolerance)\n            {\n                if (IsComplex)\n                {\n                    ret(n) = z(i);\n                    ++n;\n                }\n                else\n                {\n                    // Discard negative real z(i).\n                    const auto xi = real(z(i));\n                    const auto yi = imag(z(i));\n                    if (!(abs(yi) < eps && xi < zero))\n                    {\n                        ret(n) = z(i);\n                        ++n;\n                    }\n                }\n            }\n        }\n\n        return ret;\n    }\n};\n\n/// \\internal\n///\n/// Solve overdetermined linear system\n///\n/// \\f[\n///    V\\boldsymbol{x} = \\boldsymbol{b}\n/// \\f]\n///\n/// to compute weights of the exponential sum approximation, where \\f$V\\f$ is a\n/// column Vandermonde matrix constructed from roots of a Prony polynomial.\n///\n/// \\param[in] prony_roots  roots of a Prony polynomial\n/// \\param[in] rhs   a sequence of function/data values on uniform grid\n/// \\param[out] dst  the solution of overdetermined Vandermonde system\n/// \\param[in] eps      a prescribed accuracy required for the least-squares\n/// \\param[in] max_iter maximum number of iterations for CGLS linear solver\n///\ntemplate <typename VecNodes, typename VecRHS, typename VecDest, typename RealT>\nvoid solve_overdetermined_vandermonde(\n    const Eigen::DenseBase<VecNodes>& prony_roots,\n    const Eigen::MatrixBase<VecRHS>& rhs, Eigen::DenseBase<VecDest>& dst,\n    RealT eps, Eigen::Index max_iter)\n{\n    EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecNodes);\n    EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecRHS);\n    EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecDest);\n\n    assert(prony_roots.size() == dst.size());\n\n    using Scalar          = typename VecNodes::Scalar; // usually complex type\n    using VandermondeGEMV = MatrixFreeGEMV<VandermondeMatrix<Scalar>>;\n\n    // --- Solve with CGLS method.\n    VandermondeMatrix<Scalar> matV(rhs.size(), prony_roots);\n    VandermondeGEMV opV(matV);\n    VandermondeLeastSquaresSolver<Scalar> solver(opV);\n    solver.setTolerance(eps);\n    solver.setMaxIterations(max_iter);\n\n    //\n    // We need cast the scalar type of RHS vector as the VecRHS::Scalar might be\n    // different from VecNodes::Scalar. We should be consider the following\n    // case:\n    //\n    // VecNodes::Scalar -> complex type\n    // VecRHS::Scalar   -> real type\n    //\n    dst = solver.solve(rhs.template cast<Scalar>());\n\n    if (solver.info() == Eigen::NoConvergence)\n    {\n        //\n        // CGLS did not converge.\n        // Fall back to least-squares with dense QR factorization.\n        //\n        auto denseV = matV.toDenseMatrix();\n        dst = denseV.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV)\n                  .solve(rhs.template cast<Scalar>());\n    }\n\n    return;\n}\n\n/// \\internal\n///\n/// ### gen_prony_like_method_result\n///\n/// Generate and manipulate a result (an exponential sum) of Prony-like method.\n///\n\ntemplate <typename T>\nstruct gen_prony_like_method_result;\n\ntemplate <typename T>\nstruct gen_prony_like_method_result\n{\n    using Real       = T;\n    using Complex    = std::complex<Real>;\n    using ResultType = ExponentialSum<Complex, Complex>;\n\n    template <typename ArrayZ, typename ArrayW>\n    static ResultType\n    create(const Eigen::ArrayBase<ArrayZ>& z, // exp(-exponents)\n           const Eigen::ArrayBase<ArrayW>& w, // weights\n           Real x0, Real delta)\n    {\n        using Index = Eigen::Index;\n\n        using Eigen::numext::abs;\n        using Eigen::numext::conj;\n        using Eigen::numext::exp;\n        using Eigen::numext::imag;\n        using Eigen::numext::log;\n        using Eigen::numext::real;\n\n        static const auto eps     = Eigen::NumTraits<Real>::epsilon();\n        static const auto pi      = 4 * Eigen::numext::atan(Real(1));\n        constexpr const auto zero = Real();\n        constexpr const auto half = Real(0.5);\n\n        //-------------------------------------------------------------------------\n        // The exponents are obtained as a_i = -log(z_i), where {z_i} are the\n        // roots of the Prony polynomial.\n        //\n        // Some z_i might be real and negative: in this case, the corresponding\n        // parameter a_i becomes a complex, i.e, a_i = -ln|z_i|+i \\pi.\n        // However, its complex conjugate a_i^* is not included in the final\n        // exponential sum approximation which makes the approximated function\n        // non-real. Thus, we disregards those terms.\n        //-------------------------------------------------------------------------\n\n        // Count negative, real-valued Prony roots\n        Index count = 0;\n        for (Index i = 0; i < z.size(); ++i)\n        {\n            const auto xi = real(z(i));\n            const auto yi = imag(z(i));\n            if (xi < zero && abs(yi) < eps)\n            {\n                ++count;\n            }\n        }\n\n        if (count)\n        {\n            // Found negative real roots.\n            ResultType ret(z.size() + count);\n\n            Index n = 0;\n            for (Index i = 0; i < z.size(); ++i)\n            {\n                const auto xi = real(z(i));\n                const auto yi = imag(z(i));\n                if (xi < zero && abs(yi) < eps)\n                {\n                    // Log(z) = -log(xi) + i pi\n                    const auto an       = Complex(-log(-xi), -pi) / delta;\n                    ret.exponent(n)     = an;\n                    ret.exponent(n + 1) = conj(an);\n\n                    const auto wn     = half * w(i) * exp(-x0 * an);\n                    ret.weight(n)     = wn;\n                    ret.weight(n + 1) = conj(wn);\n\n                    n += 2;\n                }\n                else\n                {\n                    const auto an   = -log(z(i)) / delta;\n                    ret.exponent(n) = an;\n                    ret.weight(n)   = w(i) * exp(-x0 * an);\n\n                    ++n;\n                }\n            }\n\n            return ret;\n        }\n        else\n        {\n            ResultType ret(z.size());\n            ret.exponents() = -z.log() / delta;\n            if (x0 == Real())\n            {\n                ret.weights() = w; // Don't forget to copy weights\n            }\n            else\n            {\n                ret.weights() = w * (-x0 * ret.exponents()).exp();\n            }\n            return ret;\n        }\n    }\n};\n\ntemplate <typename T>\nstruct gen_prony_like_method_result<std::complex<T>>\n{\n    using Real       = T;\n    using Complex    = std::complex<Real>;\n    using ResultType = ExponentialSum<Complex, Complex>;\n\n    template <typename ArrayZ, typename ArrayW>\n    static ResultType\n    create(const Eigen::ArrayBase<ArrayZ>& z, // exp(-exponents)\n           const Eigen::ArrayBase<ArrayW>& w, // weights\n           Real x0, Real delta)\n    {\n        ResultType ret(z.size());\n        ret.exponents() = -z.log() / delta;\n        if (x0 == Real())\n        {\n            ret.weights() = w; // Don't forget to copy weights\n        }\n        else\n        {\n            ret.weights() = w * (-x0 * ret.exponents()).exp();\n        }\n\n        return ret;\n    }\n};\n\n} // namespace detail\n} // namespace mxpfit\n\n#endif /* MXPFIT_PRONY_LIKE_METHOD_COMMON_HPP */\n", "meta": {"hexsha": "c62581dd5e86e6944241a4db994f5fa102ed38b5", "size": 10754, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/prony_like_method_common.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/prony_like_method_common.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/prony_like_method_common.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.7227138643, "max_line_length": 83, "alphanum_fraction": 0.5444485773, "num_tokens": 2480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5042143140579726}}
{"text": "/*\n//@HEADER\n// ************************************************************************\n//\n// qr_eigen_dense_out_of_place_impl.hpp\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#ifndef QR_IMPL_EIGEN_QR_EIGEN_DENSE_OUT_OF_PLACE_IMPL_HPP_\n#define QR_IMPL_EIGEN_QR_EIGEN_DENSE_OUT_OF_PLACE_IMPL_HPP_\n\n#include <Eigen/QR>\n\nnamespace pressio{ namespace qr{ namespace impl{\n\ntemplate< typename MatrixType, typename R_t>\nclass QRHouseholderDenseEigenMatrix<\n  MatrixType, R_t,\n  ::pressio::mpl::enable_if_t<\n    ::pressio::is_dense_matrix_eigen<MatrixType>::value\n    >\n  >\n{\npublic:\n  using sc_t\t       = typename ::pressio::Traits<MatrixType>::scalar_type;\n  using Q_type = Eigen::Matrix<sc_t, Eigen::Dynamic, Eigen::Dynamic>;\n  using factorizer_t = Eigen::HouseholderQR<MatrixType>;\n\nprivate:\n  mutable std::shared_ptr<Q_type> Qmat_\t     = {};\n  mutable std::shared_ptr<factorizer_t> fct_ = {};\n\npublic:\n  QRHouseholderDenseEigenMatrix() = default;\n  ~QRHouseholderDenseEigenMatrix() = default;\n\n  void computeThinOutOfPlace(const MatrixType & A)\n  {\n    const auto rows = A.rows();\n    const auto cols = A.cols();\n    fct_ = std::make_shared<factorizer_t>(A);\n\n    if (!Qmat_ or (Qmat_->rows()!=rows and Qmat_->cols()!=cols)){\n      Qmat_ = std::make_shared<Q_type>(rows,cols);\n      Qmat_->setZero();\n    }\n\n    *Qmat_ = fct_->householderQ() * Q_type::Identity(rows,cols);\n  }\n\n  template < typename VectorInType, typename VectorOutType>\n  void applyQTranspose(const VectorInType & vecIn, VectorOutType & vecOut) const\n  {\n    constexpr auto beta  = ::pressio::utils::Constants<sc_t>::zero();\n    constexpr auto alpha = ::pressio::utils::Constants<sc_t>::one();\n    ::pressio::ops::product(::pressio::transpose(), alpha, *this->Qmat_, vecIn, beta, vecOut);\n  }\n\n  template < typename VectorInType, typename VectorOutType>\n  void applyRTranspose(const VectorInType & vecIn, VectorOutType & y) const\n  {\n    // y = R^T vecIn\n    auto vecSize = ::pressio::ops::extent(y, 0);\n    auto & Rm = fct_->matrixQR().block(0,0,vecSize,vecSize).template triangularView<Eigen::Upper>();\n    y = Rm.transpose() * vecIn;\n  }\n\n  template <typename VectorType>\n  void doLinSolve(const VectorType & rhs, VectorType & y)const\n  {\n    auto vecSize = ::pressio::ops::extent(y, 0);\n    auto & Rm = fct_->matrixQR().block(0,0,vecSize,vecSize).\n      template triangularView<Eigen::Upper>();\n    y = Rm.solve(rhs);\n  }\n\n  const Q_type & QFactor() const {\n    return *this->Qmat_;\n  }\n};\n\n}}} // end namespace pressio::qr::impl\n#endif  // QR_IMPL_EIGEN_QR_EIGEN_DENSE_OUT_OF_PLACE_IMPL_HPP_\n", "meta": {"hexsha": "95e77cbf43c94c33f2e65c98a762028441add82f", "size": 4517, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tpls/pressio/include/pressio/qr/impl/eigen/qr_eigen_dense_out_of_place_impl.hpp", "max_stars_repo_name": "fnrizzi/pressio-demoapps", "max_stars_repo_head_hexsha": "6ff10bbcf4d526610580940753c9620725bff1ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2019-11-11T13:17:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:31:31.000Z", "max_issues_repo_path": "tpls/pressio/include/pressio/qr/impl/eigen/qr_eigen_dense_out_of_place_impl.hpp", "max_issues_repo_name": "fnrizzi/pressio-demoapps", "max_issues_repo_head_hexsha": "6ff10bbcf4d526610580940753c9620725bff1ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 303.0, "max_issues_repo_issues_event_min_datetime": "2019-09-30T10:15:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T08:24:04.000Z", "max_forks_repo_path": "tpls/pressio/include/pressio/qr/impl/eigen/qr_eigen_dense_out_of_place_impl.hpp", "max_forks_repo_name": "fnrizzi/pressio-demoapps", "max_forks_repo_head_hexsha": "6ff10bbcf4d526610580940753c9620725bff1ba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-07-07T03:32:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T05:21:42.000Z", "avg_line_length": 36.4274193548, "max_line_length": 100, "alphanum_fraction": 0.6931591764, "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5042143015563503}}
{"text": "#include <boost/hana.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n#include <complex>\n#include \"../include/AlgorithmFactory.h\"\n#include <iostream>\n#include <memory>\n\n#include \"../include/basic/SineCosine.h\"\n#include \"../include/basic/Ceil.h\"\n#include \"../include/basic/Floor.h\"\n#include \"../include/basic/Round.h\"\n\nnamespace constants = boost::math::constants;\nnamespace hana = boost::hana;\nnamespace jb = jeanbaptiste;\nnamespace jbo = jeanbaptiste::options;\nnamespace jw = jeanbaptiste::windowing;\n\nint main()\n{\n    std::array<std::complex<double>, 16> complexData =\n    {\n        std::complex<double>(-1.0f, 0.0f),\n\t\tstd::complex<double>(-1.0f, 0.0f),\n\t\tstd::complex<double>(-1.0f, 0.0f),\n\t\tstd::complex<double>(-1.0f, 0.0f),\n\t\tstd::complex<double>( 1.0f, 0.0f),\n\t\tstd::complex<double>( 1.0f, 0.0f),\n\t\tstd::complex<double>( 1.0f, 0.0f),\n\t\tstd::complex<double>( 1.0f, 0.0f),\n\t\tstd::complex<double>(-1.0f, 0.0f),\n\t\tstd::complex<double>(-1.0f, 0.0f),\n\t\tstd::complex<double>(-1.0f, 0.0f),\n\t\tstd::complex<double>(-1.0f, 0.0f),\n\t\tstd::complex<double>( 1.0f, 0.0f),\n\t\tstd::complex<double>( 1.0f, 0.0f),\n\t\tstd::complex<double>( 1.0f, 0.0f),\n\t\tstd::complex<double>( 1.0f, 0.0f)\n    };\n\n    jb::AlgorithmFactory<1, 6, jbo::Radix_2, jbo::Decimation_In_Frequency, jbo::Direction_Forward, \n       jbo::Window_None, jbo::Normalization_Square_Root, std::complex<double>> algorithmFactory;\n\n\tconstexpr auto stage = 4;\n    auto algorithm = algorithmFactory.getAlgorithm(stage);\n    algorithm->operator()(&complexData[0]);\n\n\tstd::cout << \"Selected algorithm - stage: \" << stage << \", samples: \" << algorithm->numberOfSamples() << \", frequencies: \" << algorithm->numberOfFrequencies() << \"\\n\\n\";\n\n\tstd::cout << \"Applying FFT:\\n\";\n    for (auto value : complexData)\n       std::cout << std::setw(10) << std::setprecision(5) << value.real() << \"\\t\" << value.imag() << \"I\\n\";\n\n\tstd::cout << \"\\nApplying iFFT:\\n\";\n\tjb::AlgorithmFactory<1, 6, jbo::Radix_2, jbo::Decimation_In_Frequency, jbo::Direction_Backward, \n       jbo::Window_None, jbo::Normalization_Square_Root, std::complex<double>> iAlgorithmFactory;\n\n\tauto iAlgorithm = iAlgorithmFactory.getAlgorithm(stage);\n    iAlgorithm->operator()(&complexData[0]);\n\n    for (auto value : complexData)\n       std::cout << std::setw(10) << std::setprecision(5) << value.real() << \"\\t\" << value.imag() << \"I\\n\";\n\n    std::cin.get();\n\n     return 0;\n}", "meta": {"hexsha": "6e044e9bbcb11454e33246817b7943862919ef5d", "size": 2397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "JeanBaptiste/src/jeanbaptiste.cpp", "max_stars_repo_name": "JoergWarthemann/jeanbaptiste", "max_stars_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "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": "JeanBaptiste/src/jeanbaptiste.cpp", "max_issues_repo_name": "JoergWarthemann/jeanbaptiste", "max_issues_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "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": "JeanBaptiste/src/jeanbaptiste.cpp", "max_forks_repo_name": "JoergWarthemann/jeanbaptiste", "max_forks_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "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.25, "max_line_length": 170, "alphanum_fraction": 0.6562369629, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5042108360702654}}
{"text": "\n// g++-4.4 bench_gemm.cpp -I .. -O2 -DNDEBUG -lrt -fopenmp && OMP_NUM_THREADS=2  ./a.out\n// icpc bench_gemm.cpp -I .. -O3 -DNDEBUG -lrt -openmp  && OMP_NUM_THREADS=2  ./a.out\n\n// Compilation options:\n// \n// -DSCALAR=std::complex<double>\n// -DSCALARA=double or -DSCALARB=double\n// -DHAVE_BLAS\n// -DDECOUPLED\n//\n\n#include <iostream>\n#include <Eigen/Core>\n#include <bench/BenchTimer.h>\n\nusing namespace std;\nusing namespace Eigen;\n\n#ifndef SCALAR\n// #define SCALAR std::complex<float>\n#define SCALAR float\n#endif\n\n#ifndef SCALARA\n#define SCALARA SCALAR\n#endif\n\n#ifndef SCALARB\n#define SCALARB SCALAR\n#endif\n\ntypedef SCALAR Scalar;\ntypedef NumTraits<Scalar>::Real RealScalar;\ntypedef Matrix<SCALARA,Dynamic,Dynamic> A;\ntypedef Matrix<SCALARB,Dynamic,Dynamic> B;\ntypedef Matrix<Scalar,Dynamic,Dynamic> C;\ntypedef Matrix<RealScalar,Dynamic,Dynamic> M;\n\n#ifdef HAVE_BLAS\n\nextern \"C\" {\n  #include <Eigen/src/misc/blas.h>\n}\n\nstatic float fone = 1;\nstatic float fzero = 0;\nstatic double done = 1;\nstatic double szero = 0;\nstatic std::complex<float> cfone = 1;\nstatic std::complex<float> cfzero = 0;\nstatic std::complex<double> cdone = 1;\nstatic std::complex<double> cdzero = 0;\nstatic char notrans = 'N';\nstatic char trans = 'T';  \nstatic char nonunit = 'N';\nstatic char lower = 'L';\nstatic char right = 'R';\nstatic int intone = 1;\n\nvoid blas_gemm(const MatrixXf& a, const MatrixXf& b, MatrixXf& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  sgemm_(&notrans,&notrans,&M,&N,&K,&fone,\n         const_cast<float*>(a.data()),&lda,\n         const_cast<float*>(b.data()),&ldb,&fone,\n         c.data(),&ldc);\n}\n\nEIGEN_DONT_INLINE void blas_gemm(const MatrixXd& a, const MatrixXd& b, MatrixXd& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  dgemm_(&notrans,&notrans,&M,&N,&K,&done,\n         const_cast<double*>(a.data()),&lda,\n         const_cast<double*>(b.data()),&ldb,&done,\n         c.data(),&ldc);\n}\n\nvoid blas_gemm(const MatrixXcf& a, const MatrixXcf& b, MatrixXcf& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  cgemm_(&notrans,&notrans,&M,&N,&K,(float*)&cfone,\n         const_cast<float*>((const float*)a.data()),&lda,\n         const_cast<float*>((const float*)b.data()),&ldb,(float*)&cfone,\n         (float*)c.data(),&ldc);\n}\n\nvoid blas_gemm(const MatrixXcd& a, const MatrixXcd& b, MatrixXcd& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  zgemm_(&notrans,&notrans,&M,&N,&K,(double*)&cdone,\n         const_cast<double*>((const double*)a.data()),&lda,\n         const_cast<double*>((const double*)b.data()),&ldb,(double*)&cdone,\n         (double*)c.data(),&ldc);\n}\n\n\n\n#endif\n\nvoid matlab_cplx_cplx(const M& ar, const M& ai, const M& br, const M& bi, M& cr, M& ci)\n{\n  cr.noalias() += ar * br;\n  cr.noalias() -= ai * bi;\n  ci.noalias() += ar * bi;\n  ci.noalias() += ai * br;\n  // [cr ci] += [ar ai] * br + [-ai ar] * bi\n}\n\nvoid matlab_real_cplx(const M& a, const M& br, const M& bi, M& cr, M& ci)\n{\n  cr.noalias() += a * br;\n  ci.noalias() += a * bi;\n}\n\nvoid matlab_cplx_real(const M& ar, const M& ai, const M& b, M& cr, M& ci)\n{\n  cr.noalias() += ar * b;\n  ci.noalias() += ai * b;\n}\n\ntemplate<typename A, typename B, typename C>\nEIGEN_DONT_INLINE void gemm(const A& a, const B& b, C& c)\n{\n c.noalias() += a * b;\n}\n\nint main(int argc, char ** argv)\n{\n  std::ptrdiff_t l1 = internal::queryL1CacheSize();\n  std::ptrdiff_t l2 = internal::queryTopLevelCacheSize();\n  std::cout << \"L1 cache size     = \" << (l1>0 ? l1/1024 : -1) << \" KB\\n\";\n  std::cout << \"L2/L3 cache size  = \" << (l2>0 ? l2/1024 : -1) << \" KB\\n\";\n  typedef internal::gebp_traits<Scalar,Scalar> Traits;\n  std::cout << \"Register blocking = \" << Traits::mr << \" x \" << Traits::nr << \"\\n\";\n\n  int rep = 1;    // number of repetitions per try\n  int tries = 2;  // number of tries, we keep the best\n\n  int s = 2048;\n  int m = s;\n  int n = s;\n  int p = s;\n  int cache_size1=-1, cache_size2=l2, cache_size3 = 0;\n\n  bool need_help = false;\n  for (int i=1; i<argc;)\n  {\n    if(argv[i][0]=='-')\n    {\n      if(argv[i][1]=='s')\n      {\n        ++i;\n        s = atoi(argv[i++]);\n        m = n = p = s;\n        if(argv[i][0]!='-')\n        {\n          n = atoi(argv[i++]);\n          p = atoi(argv[i++]);\n        }\n      }\n      else if(argv[i][1]=='c')\n      {\n        ++i;\n        cache_size1 = atoi(argv[i++]);\n        if(argv[i][0]!='-')\n        {\n          cache_size2 = atoi(argv[i++]);\n          if(argv[i][0]!='-')\n            cache_size3 = atoi(argv[i++]);\n        }\n      }\n      else if(argv[i][1]=='t')\n      {\n        ++i;\n        tries = atoi(argv[i++]);\n      }\n      else if(argv[i][1]=='p')\n      {\n        ++i;\n        rep = atoi(argv[i++]);\n      }\n    }\n    else\n    {\n      need_help = true;\n      break;\n    }\n  }\n\n  if(need_help)\n  {\n    std::cout << argv[0] << \" -s <matrix sizes> -c <cache sizes> -t <nb tries> -p <nb repeats>\\n\";\n    std::cout << \"   <matrix sizes> : size\\n\";\n    std::cout << \"   <matrix sizes> : rows columns depth\\n\";\n    return 1;\n  }\n\n#if EIGEN_VERSION_AT_LEAST(3,2,90)\n  if(cache_size1>0)\n    setCpuCacheSizes(cache_size1,cache_size2,cache_size3);\n#endif\n  \n  A a(m,p); a.setRandom();\n  B b(p,n); b.setRandom();\n  C c(m,n); c.setOnes();\n  C rc = c;\n\n  std::cout << \"Matrix sizes = \" << m << \"x\" << p << \" * \" << p << \"x\" << n << \"\\n\";\n  std::ptrdiff_t mc(m), nc(n), kc(p);\n  internal::computeProductBlockingSizes<Scalar,Scalar>(kc, mc, nc);\n  std::cout << \"blocking size (mc x kc) = \" << mc << \" x \" << kc << \"\\n\";\n\n  C r = c;\n\n  // check the parallel product is correct\n  #if defined EIGEN_HAS_OPENMP\n  Eigen::initParallel();\n  int procs = omp_get_max_threads();\n  if(procs>1)\n  {\n    #ifdef HAVE_BLAS\n    blas_gemm(a,b,r);\n    #else\n    omp_set_num_threads(1);\n    r.noalias() += a * b;\n    omp_set_num_threads(procs);\n    #endif\n    c.noalias() += a * b;\n    if(!r.isApprox(c)) std::cerr << \"Warning, your parallel product is crap!\\n\\n\";\n  }\n  #elif defined HAVE_BLAS\n    blas_gemm(a,b,r);\n    c.noalias() += a * b;\n    if(!r.isApprox(c)) {\n      std::cout << (r  - c).norm() << \"\\n\";\n      std::cerr << \"Warning, your product is crap!\\n\\n\";\n    }\n  #else\n    if(1.*m*n*p<2000.*2000*2000)\n    {\n      gemm(a,b,c);\n      r.noalias() += a.cast<Scalar>() .lazyProduct( b.cast<Scalar>() );\n      if(!r.isApprox(c)) {\n        std::cout << (r  - c).norm() << \"\\n\";\n        std::cerr << \"Warning, your product is crap!\\n\\n\";\n      }\n    }\n  #endif\n\n  #ifdef HAVE_BLAS\n  BenchTimer tblas;\n  c = rc;\n  BENCH(tblas, tries, rep, blas_gemm(a,b,c));\n  std::cout << \"blas  cpu         \" << tblas.best(CPU_TIMER)/rep  << \"s  \\t\" << (double(m)*n*p*rep*2/tblas.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << tblas.total(CPU_TIMER)  << \"s)\\n\";\n  std::cout << \"blas  real        \" << tblas.best(REAL_TIMER)/rep << \"s  \\t\" << (double(m)*n*p*rep*2/tblas.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << tblas.total(REAL_TIMER) << \"s)\\n\";\n  #endif\n\n  BenchTimer tmt;\n  c = rc;\n  BENCH(tmt, tries, rep, gemm(a,b,c));\n  std::cout << \"eigen cpu         \" << tmt.best(CPU_TIMER)/rep  << \"s  \\t\" << (double(m)*n*p*rep*2/tmt.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << tmt.total(CPU_TIMER)  << \"s)\\n\";\n  std::cout << \"eigen real        \" << tmt.best(REAL_TIMER)/rep << \"s  \\t\" << (double(m)*n*p*rep*2/tmt.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << tmt.total(REAL_TIMER) << \"s)\\n\";\n\n  #ifdef EIGEN_HAS_OPENMP\n  if(procs>1)\n  {\n    BenchTimer tmono;\n    omp_set_num_threads(1);\n    Eigen::setNbThreads(1);\n    c = rc;\n    BENCH(tmono, tries, rep, gemm(a,b,c));\n    std::cout << \"eigen mono cpu    \" << tmono.best(CPU_TIMER)/rep  << \"s  \\t\" << (double(m)*n*p*rep*2/tmono.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << tmono.total(CPU_TIMER)  << \"s)\\n\";\n    std::cout << \"eigen mono real   \" << tmono.best(REAL_TIMER)/rep << \"s  \\t\" << (double(m)*n*p*rep*2/tmono.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << tmono.total(REAL_TIMER) << \"s)\\n\";\n    std::cout << \"mt speed up x\" << tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER)  << \" => \" << (100.0*tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER))/procs << \"%\\n\";\n  }\n  #endif\n  \n  if(1.*m*n*p<30*30*30)\n  {\n      BenchTimer tmt;\n      c = rc;\n      BENCH(tmt, tries, rep, c.noalias()+=a.lazyProduct(b));\n      std::cout << \"lazy cpu         \" << tmt.best(CPU_TIMER)/rep  << \"s  \\t\" << (double(m)*n*p*rep*2/tmt.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << tmt.total(CPU_TIMER)  << \"s)\\n\";\n      std::cout << \"lazy real        \" << tmt.best(REAL_TIMER)/rep << \"s  \\t\" << (double(m)*n*p*rep*2/tmt.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << tmt.total(REAL_TIMER) << \"s)\\n\";\n  }\n  \n  #ifdef DECOUPLED\n  if((NumTraits<A::Scalar>::IsComplex) && (NumTraits<B::Scalar>::IsComplex))\n  {\n    M ar(m,p); ar.setRandom();\n    M ai(m,p); ai.setRandom();\n    M br(p,n); br.setRandom();\n    M bi(p,n); bi.setRandom();\n    M cr(m,n); cr.setRandom();\n    M ci(m,n); ci.setRandom();\n    \n    BenchTimer t;\n    BENCH(t, tries, rep, matlab_cplx_cplx(ar,ai,br,bi,cr,ci));\n    std::cout << \"\\\"matlab\\\" cpu    \" << t.best(CPU_TIMER)/rep  << \"s  \\t\" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << t.total(CPU_TIMER)  << \"s)\\n\";\n    std::cout << \"\\\"matlab\\\" real   \" << t.best(REAL_TIMER)/rep << \"s  \\t\" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << t.total(REAL_TIMER) << \"s)\\n\";\n  }\n  if((!NumTraits<A::Scalar>::IsComplex) && (NumTraits<B::Scalar>::IsComplex))\n  {\n    M a(m,p);  a.setRandom();\n    M br(p,n); br.setRandom();\n    M bi(p,n); bi.setRandom();\n    M cr(m,n); cr.setRandom();\n    M ci(m,n); ci.setRandom();\n    \n    BenchTimer t;\n    BENCH(t, tries, rep, matlab_real_cplx(a,br,bi,cr,ci));\n    std::cout << \"\\\"matlab\\\" cpu    \" << t.best(CPU_TIMER)/rep  << \"s  \\t\" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << t.total(CPU_TIMER)  << \"s)\\n\";\n    std::cout << \"\\\"matlab\\\" real   \" << t.best(REAL_TIMER)/rep << \"s  \\t\" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << t.total(REAL_TIMER) << \"s)\\n\";\n  }\n  if((NumTraits<A::Scalar>::IsComplex) && (!NumTraits<B::Scalar>::IsComplex))\n  {\n    M ar(m,p); ar.setRandom();\n    M ai(m,p); ai.setRandom();\n    M b(p,n);  b.setRandom();\n    M cr(m,n); cr.setRandom();\n    M ci(m,n); ci.setRandom();\n    \n    BenchTimer t;\n    BENCH(t, tries, rep, matlab_cplx_real(ar,ai,b,cr,ci));\n    std::cout << \"\\\"matlab\\\" cpu    \" << t.best(CPU_TIMER)/rep  << \"s  \\t\" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << t.total(CPU_TIMER)  << \"s)\\n\";\n    std::cout << \"\\\"matlab\\\" real   \" << t.best(REAL_TIMER)/rep << \"s  \\t\" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << t.total(REAL_TIMER) << \"s)\\n\";\n  }\n  #endif\n\n  return 0;\n}\n\n", "meta": {"hexsha": "dccab96a8bb51290666fa0761e6a45f998ba5cc7", "size": 10885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen-3.3.9/bench/bench_gemm.cpp", "max_stars_repo_name": "hporro/grafica_cpp", "max_stars_repo_head_hexsha": "1427bb6e8926b44be474b906e9f52cca77b3df9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1883.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:33:37.000Z", "max_issues_repo_path": "third_party/eigen-3.3.9/bench/bench_gemm.cpp", "max_issues_repo_name": "hporro/grafica_cpp", "max_issues_repo_head_hexsha": "1427bb6e8926b44be474b906e9f52cca77b3df9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 272.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T09:53:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T08:04:33.000Z", "max_forks_repo_path": "third_party/eigen-3.3.9/bench/bench_gemm.cpp", "max_forks_repo_name": "hporro/grafica_cpp", "max_forks_repo_head_hexsha": "1427bb6e8926b44be474b906e9f52cca77b3df9d", "max_forks_repo_licenses": ["MIT"], "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": 31.8274853801, "max_line_length": 187, "alphanum_fraction": 0.5557188792, "num_tokens": 3789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5042108241924483}}
{"text": "/* test_negative_binomial_distribution.cpp\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 * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/negative_binomial_distribution.hpp>\r\n#include <limits>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::negative_binomial_distribution<>\r\n#define BOOST_RANDOM_ARG1 k\r\n#define BOOST_RANDOM_ARG2 p\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1\r\n#define BOOST_RANDOM_ARG2_DEFAULT 0.5\r\n#define BOOST_RANDOM_ARG1_VALUE 10\r\n#define BOOST_RANDOM_ARG2_VALUE 0.25\r\n\r\n#define BOOST_RANDOM_DIST0_MIN 0\r\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<int>::max)()\r\n#define BOOST_RANDOM_DIST1_MIN 0\r\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<int>::max)()\r\n#define BOOST_RANDOM_DIST2_MIN 0\r\n#define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<int>::max)()\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS\r\n#define BOOST_RANDOM_TEST1_MIN 0\r\n#define BOOST_RANDOM_TEST1_MAX 10\r\n\r\n#define BOOST_RANDOM_TEST2_PARAMS (100, 0.5)\r\n#define BOOST_RANDOM_TEST2_MIN 50\r\n\r\n#include \"test_distribution.ipp\"\r\n", "meta": {"hexsha": "c14bd5d2bdf7acfe1873edccdb72f83c4e7a739c", "size": 1165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_negative_binomial_distribution.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_negative_binomial_distribution.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_negative_binomial_distribution.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 30.6578947368, "max_line_length": 82, "alphanum_fraction": 0.7896995708, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624586752076, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5042108057829194}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_FAST_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_FAST_HYPOT_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/fast_hypot.hpp>\n#include <boost/simd/include/functions/simd/sqrt.hpp>\n#include <boost/simd/include/functions/simd/sqr.hpp>\n#include <boost/simd/include/functions/simd/fma.hpp>\n#include <boost/simd/include/functions/simd/multiplies.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( fast_hypot_, tag::cpu_\n                                    , (A0)\n                                    , (generic_< floating_<A0> >)\n                                      (generic_< floating_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return boost::simd::sqrt(boost::simd::fma(a0, a0, sqr(a1)));\n    }\n  };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "5782a00f75c9ddb01e43d465b05e03d289fc7fbe", "size": 1423, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/generic/fast_hypot.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/generic/fast_hypot.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/generic/fast_hypot.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 38.4594594595, "max_line_length": 80, "alphanum_fraction": 0.5523541813, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5040870048884967}}
{"text": "#include \"../../includes/SpecialFunc.h\"\n#include \"../../includes/utils.h\"\n#include \"../../includes/BaseClass.h\"\n#include <iostream>\n\n#include <stdio.h>\n#include <tgmath.h>\n#include <math.h>\n#include <complex.h>\n#include <boost/math/quadrature/trapezoidal.hpp>\n\n#include <pybind11/pybind11.h>\n#include <pybind11/complex.h>\n#include <pybind11/numpy.h>\n#include <pybind11/stl.h>\n\nnamespace py = pybind11;\n\ntypedef std::vector<double> Vec;\ntypedef std::complex<double> complex128;\ntypedef std::vector<complex128> iVec;\ntypedef py::array_t<double> ndarray;\ntypedef py::array_t<complex128> Cndarray;\n#define J complex128(0.0,1.0)\n\n#define EPS 1e-10\n#define Correction 1.//2.*exp(J*1.0472351410849077)\n\nusing boost::math::quadrature::trapezoidal;\nusing boost::math::constants::two_pi;\nusing boost::math::constants::pi;\n\n\nstruct argument\n  {\n  int n, m;\n  double r, rhon, angle, s, R0, w0, xi, k;\n  complex128 Q, beta;\n  Vec Offset;\n} args, args0 ;\n\n\n\ntemplate <typename func_type>\ncomplex128 simpson_rule(func_type f,\n                        double a,\n                        double b,\n                        int n // Number of intervals\n                        )\n{\n    double h = (b - a) / n;\n\n    // Internal sample points, there should be n - 1 of them\n    complex128 sum_odds = 0.0;\n    for (int i = 1; i < n; i += 2)\n    {\n        sum_odds += f(a + i * h);\n    }\n    complex128 sum_evens = 0.0;\n    for (int i = 2; i < n; i += 2)\n    {\n        sum_evens += f(a + i * h);\n    }\n\n    return (f(a) + f(b) + 2. * sum_evens + 4. * sum_odds) * h / 3.;\n}\n\n\n\niVec\nQ_(double r,\n  Vec    theta,\n  double w0,\n  Vec    Offset,\n  double k)\n{\n   iVec result;\n   for (auto const& angle: theta)\n   {\n     result.push_back(1./( 2. * ( r * cos(angle) - Offset[2]/k )/(k * w0*w0 ) - J ) ) ;\n   }\n   return result;\n}\n\n\n\ncomplex128\nQ(double r,\n  double theta,\n  double w0,\n  Vec    Offset,\n  double k)\n{\n  return 1./( 2. * ( r * cos(theta) - Offset[2]/k)/(k * w0*w0 ) - J )  ;\n}\n\n\ncomplex128\nImSimpson(int m, complex128 beta)\n{\n auto func = [=](double angle){return exp( beta * cos(angle)  - J *  (double)m * angle) ;};\n\n complex128 integral = simpson_rule(func,  0.0, two_pi<double>(), 1000);\n\n return 1./( two_pi<double>()) * integral;\n}\n\ncomplex128\nImTrapz(int m, complex128 beta)\n{\n auto func = [=](double angle)->complex128{return exp( beta * cos(angle)  - J *  (double)m * angle) ;};\n\n complex128 integral = trapezoidal(func, 0.0, two_pi<double>(), EPS);\n\n return 1./( two_pi<double>()) * integral;\n}\n\n\n\ncomplex128\nImHat(double     m,\n      complex128 beta,\n      double     xi)\n{\n  return ImTrapz(m, beta) * exp(-beta - J * m * xi ) ;\n}\n\n\n\n\ncomplex128\nI_0(argument arg)\n{\n\n  complex128 term0 = pow(-J, arg.n) * arg.rhon*arg.rhon,\n             term1 = (2. * (double)arg.n + 1.) * _Psi(0,arg.n, arg.rhon),\n             term2 = exp(-J * arg.Offset[2]);\n\n  return term0 / term1 * term2;\n}\n\ncomplex128 I_2(argument arg){ return (2. * arg.Q * arg.s*arg.s * arg.rhon * cos(arg.angle) - 1. ) * sin(arg.angle); }\n\ncomplex128 I_3(argument arg){ return 4. * arg.Q * arg.s*arg.s * arg.Offset[0] * cos(arg.angle); }\n\ncomplex128 I_4(argument arg){ return 4. * arg.Q * arg.s*arg.s * arg.Offset[1] * cos(arg.angle); }\n\ncomplex128\nI_1(argument arg)\n{\n  complex128 term0 = J * arg.Q * arg.s*arg.s * pow(arg.R0 - arg.rhon * sin(arg.angle), 2. ),\n             term2 = J * arg.rhon * cos(arg.angle),\n             term3 = NPnm(arg.n, abs(arg.m), cos(arg.angle)) * sin(arg.angle) ;\n\n  return arg.Q * exp(term0 + term2 ) * term3;\n}\n\n\n\n\n\n\ncomplex128\nBnm_integrand(double angle, argument args0)\n{\n  if (abs(args0.m) >args0.n){return 0;}\n\n  args0.Q = Q(args0.r, angle, args0.w0, args0.Offset, args0.k);\n\n  args0.angle = angle;\n\n  complex128 beta = -2. * J * args0.Q * args0.s*args0.s * args0.R0 * args0.rhon * sin(angle);\n\n  complex128 term0 =  ImHat(args0.m+1, beta, args0.xi) - ImHat(args0.m-1, beta, args0.xi);\n\n  term0 *= I_2(args0);\n\n  term0 -= (I_4(args0) * ImHat(args0.m, beta, args0.xi));\n\n  term0 *= I_1(args0);\n\n  return term0;\n\n}\n\n\n\n\ncomplex128\nAnm_integrand(double angle, argument args0)\n{\n  if (abs(args0.m) >args0.n){return 0;}\n\n  args0.Q = Q(args0.r, angle, args0.w0, args0.Offset, args0.k);\n\n  args0.angle = angle;\n\n  complex128 beta = -2. * J * args0.Q * args0.s*args0.s * args0.R0 * args0.rhon * sin(angle);\n\n  complex128 term0 =  ImHat(args0.m+1, beta, args0.xi) + ImHat(args0.m-1, beta, args0.xi);\n\n  term0 *= I_2(args0);\n\n  term0 -= (I_3(args0) * ImHat(args0.m, beta, args0.xi));\n\n  term0 *= I_1(args0);\n\n  return term0;\n\n}\n\n\n\ncomplex128\nAnm(int    n,\n    int    m,\n    double k,\n    double w0,\n    Vec    Offset,\n    double Tolerance)\n{\n  argument args0;\n           args0.n      = n;\n           args0.m      = m;\n           args0.rhon   = (n + 0.5);\n           args0.Offset = Offset;\n           args0.k      = k;\n           args0.R0     = sqrt(Offset[0]*Offset[0] + Offset[1]*Offset[1]);\n           args0.xi     = acos(Offset[0]/args0.R0);\n           args0.s      = 1./(k*w0);\n           args0.w0     = w0;\n           args0.r      = args.rhon/k;\n\n  auto func_ = [=](double angle)->complex128 {return Anm_integrand(angle, args0);};\n\n  return -trapezoidal(func_, 0.0, pi<double>(),Tolerance) * I_0(args0) * Correction;\n\n}\n\n\n\ncomplex128\nBnm(int n,\n    int m,\n    double k,\n    double w0,\n    Vec Offset,\n    double Tolerance)\n{\n  argument args0;\n           args0.n      = n;\n           args0.m      = m;\n           args0.rhon   = (n + 0.5);\n           args0.Offset = Offset;\n           args0.k      = k;\n           args0.R0     = sqrt(Offset[0]*Offset[0] + Offset[1]*Offset[1]);\n           args0.xi     = acos(Offset[0]/args0.R0);\n           args0.s      = 1./(k*w0);\n           args0.w0     = w0;\n           args0.r      = args.rhon/k;\n\n  auto func_ = [=](double angle)->complex128 {return Bnm_integrand(angle, args0);};\n\n  return -trapezoidal(func_, 0.0, pi<double>(),Tolerance) * I_0(args0) * Correction;\n\n}\n\n\n\nstd::tuple<ndarray,Cndarray>\nPyAnm_integrand(int    n,\n                int    m,\n                int    sampling,\n                double k,\n                double w0,\n                Vec    Offset,\n                double Tolerance)\n{\n\n argument args0;\n          args0.n      = n;\n          args0.m      = m;\n          args0.rhon   = (n + 0.5);\n          args0.Offset = Offset;\n          args0.k      = k;\n          args0.R0     = sqrt(Offset[0]*Offset[0] + Offset[1]*Offset[1]);\n          args0.xi     = acos(Offset[0]/args0.R0);\n          args0.s      = 1./(k*w0);\n          args0.w0     = w0;\n          args0.r      = args.rhon/k;\n\n  Cndarray _Anm = Cndarray(sampling);\n  auto _Anm_data = _Anm.mutable_data();\n\n  Cndarray Angle = Cndarray(sampling);\n  auto Angle_data = Angle.mutable_data();\n\n  Vec X = Linspace( 0.0, pi<double>(),sampling);\n\n  for (auto i=0; i<sampling;i++)\n  {\n    _Anm_data[i] = Anm_integrand(X[i], args);\n    Angle_data[i] = X[i];\n  }\n  return std::make_tuple(Angle, _Anm);\n}\n\n\nstd::tuple<ndarray,Cndarray>\nPyBnm_integrand(int    n,\n                int    m,\n                int    sampling,\n                double k,\n                double w0,\n                Vec    Offset,\n                double Tolerance)\n{\n\n  argument args0;\n           args0.n      = n;\n           args0.m      = m;\n           args0.rhon   = (n + 0.5);\n           args0.Offset = Offset;\n           args0.k      = k;\n           args0.R0     = sqrt(Offset[0]*Offset[0] + Offset[1]*Offset[1]);\n           args0.xi     = acos(Offset[0]/args0.R0);\n           args0.s      = 1./(k*w0);\n           args0.w0     = w0;\n           args0.r      = args.rhon/k;\n\n   Cndarray _Bnm = Cndarray(sampling);\n   auto _Bnm_data = _Bnm.mutable_data();\n\n   Cndarray Angle = Cndarray(sampling);\n   auto Angle_data = Angle.mutable_data();\n\n   Vec X = Linspace( 0.0, pi<double>(),sampling);\n\n   for (auto i=0; i<sampling;i++)\n   {\n     _Bnm_data[i] = Bnm_integrand(X[i], args);\n     Angle_data[i] = X[i];\n   }\n   return std::make_tuple(Angle, _Bnm);\n }\n\n\n\n\n\nPYBIND11_MODULE(GaussianBeam, module) {\n    module.doc() = \"Generalized Lorenz-Mie Theory (GLMT) c++ binding module for light scattering from a spherical scatterer\";\n\n    module.def(\"Anm\",\n               &Anm,\n               py::arg(\"n\"),\n               py::arg(\"m\"),\n               py::arg(\"k\"),\n               py::arg(\"w0\"),\n               py::arg(\"Offset\"),\n               py::arg(\"Tolerance\") = 1e-8,\n               \"Compute Anm\");\n\n\n     module.def(\"Anm_integrand\",\n                &PyAnm_integrand,\n                py::arg(\"n\"),\n                py::arg(\"m\"),\n                py::arg(\"sampling\"),\n                py::arg(\"k\"),\n                py::arg(\"w0\"),\n                py::arg(\"Offset\"),\n                py::arg(\"Tolerance\") = 1e-8,\n                \"Compute Anm integrand as a function of theta\");\n\n\n\n    module.def(\"Bnm\",\n               &Bnm,\n               py::arg(\"n\"),\n               py::arg(\"m\"),\n               py::arg(\"k\"),\n               py::arg(\"w0\"),\n               py::arg(\"Offset\"),\n               py::arg(\"Tolerance\") = 1e-8,\n               \"Compute Bnm\");\n\n\n     module.def(\"Bnm_integrand\",\n                &PyBnm_integrand,\n                py::arg(\"n\"),\n                py::arg(\"m\"),\n                py::arg(\"sampling\"),\n                py::arg(\"k\"),\n                py::arg(\"w0\"),\n                py::arg(\"Offset\"),\n                py::arg(\"Tolerance\") = 1e-8,\n                \"Compute Bnm integrand as a function of theta\");\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//-\n", "meta": {"hexsha": "f3032683b1e975b20ebc261a64d47361c30376d8", "size": 9391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PyMieSim/GLMT/cpp/GaussianBeam.cpp", "max_stars_repo_name": "paaube/PyMieSim", "max_stars_repo_head_hexsha": "074e58cfe9b42ef51f3b03aaad6e56ca341099a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PyMieSim/GLMT/cpp/GaussianBeam.cpp", "max_issues_repo_name": "paaube/PyMieSim", "max_issues_repo_head_hexsha": "074e58cfe9b42ef51f3b03aaad6e56ca341099a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyMieSim/GLMT/cpp/GaussianBeam.cpp", "max_forks_repo_name": "paaube/PyMieSim", "max_forks_repo_head_hexsha": "074e58cfe9b42ef51f3b03aaad6e56ca341099a5", "max_forks_repo_licenses": ["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.6289156627, "max_line_length": 125, "alphanum_fraction": 0.5264615057, "num_tokens": 2888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5040611647279385}}
{"text": "#pragma once\n\n#include <boost/array.hpp>\n#include <mhe_estimator/CanData.h>\n#include <mhe_estimator/ArticulatedAngles.h>\n#include \"ackermann_msgs/AckermannDrive.h\"\n#include <tf/tf.h>\n\n\nnamespace mhe_estimator\n{\n    using namespace ast;\n\n    typedef double Real;\n    typedef boost::array<Real, 6> Vec6;\n    typedef boost::array<Real, 5> Vec5;\n    typedef boost::array<Real, 4> Vec4;\n    typedef boost::array<Real, 3> Vec3;\n    typedef boost::array<Real, 2> Vec2;\n\n\n    struct CarParams\n    {\n        bool moveGuidancePoint, respectSteeringLimits;    \n        Real L, L1, Lh1, L2, Lh2;\n        Real steeringLimit, trailer1Limit, trailer2Limit, LinearVelLimit, SteeringVelLimit;\n        Real upperTh, lowerTh, upperX, lowerX, upperY, lowerY;\n        Real TrailerNumber;\n    };\n\n    struct MheParams\n    {\n        bool mheActive, WeightedActive, covarianceFromTopicStamp, perceptionGPS;\n        Real loopRate;   \n        Real noiseVariancePos, noiseVarianceTh, noiseVariancesteering, noiseVarianceTrailer1;\n        Real noiseVarianceTrailer2, noiseVarianceLinearVel, noiseVarianceSteeringVel;\n        Real WeightPos, WeightTh, WeightSteering, WeightTrailer1, WeightTrailer2;\n           \n    };\n    \n    inline int sign(Real val)\n    {\n      return (0 < val) - (val < 0);\n    }\n    \n    inline Real sat(Real x, Real lim)\n    {\n      if(x > lim)\n        return lim;\n      else if(x < -lim)\n        return - lim;\n      else\n        return x;\n    }\n    \n    inline double continuousAngle(Real angle, Real lastAngle)\n    {\n        auto dAngle = fmod(angle, 2*M_PI) - fmod(lastAngle, 2*M_PI);\n\n        if (dAngle > M_PI)\n            return lastAngle + dAngle - 2.0 * M_PI;\n        else if (dAngle < -M_PI)\n            return lastAngle + dAngle + 2.0 * M_PI;\n        else\n            return lastAngle + dAngle;\n    }\n    //Kinematics\n    inline Vec3 RDCarKinematicsGPFront(const CarParams& params,const  Vec3& q,const ackermann_msgs::AckermannDrive& u)\n    {   \n        Vec3 dq;\n        Real vF = u.speed / cos(u.steering_angle);\n\n        dq[0] = u.speed*(1/params.L)*tan(u.steering_angle);\n        dq[1] = vF*cos(u.steering_angle + q[0]);\n        dq[2] = vF*sin(u.steering_angle + q[0]);\n        return dq;\n    }\n\n    inline Vec3 RDCarKinematicsGPRear(const CarParams& params,const Vec3& q,const ackermann_msgs::AckermannDrive& u)\n    {\n        Vec3 dq;\n        dq[0] = u.speed*(1/params.L)*tan(u.steering_angle);\n        dq[1] = u.speed*cos(q[0]);\n        dq[2] = u.speed*sin(q[0]);\n        return dq;\n    }\n\n    inline Vec4 OneTrailerKinematicsGPFront(const CarParams& params,const Vec4& q,const ackermann_msgs::AckermannDrive& u, bool brakeOnSingularity = true)\n    {\n        \n        Vec4 dq;\n        Real k1 = (1/params.L1)*tan(q[0] - atan((params.Lh1/params.L)*tan(u.steering_angle)));\n        dq[0] = u.speed * (sin(q[0])/params.Lh1 - (1 + (params.L1/params.Lh1)*cos(q[0]))*k1);\n        dq[1] = u.speed * ( -(params.L1/params.Lh1)*cos(q[0])*k1 + sin(q[0])/params.Lh1 );\n        dq[2] = u.speed * cos(q[1]) * ( params.L1*sin(q[0])*k1 + cos(q[0]) );\n        dq[3] = u.speed * sin(q[1]) * ( params.L1*sin(q[0])*k1 + cos(q[0]) );\n        return dq;\n    }\n\n    inline Vec4 OneTrailerKinematicsGPRear(const CarParams& params,const Vec4& q,const ackermann_msgs::AckermannDrive& u, bool brakeOnSingularity = true)\n    {\n        Vec4 dq;\n        Real k1 = (1/params.L1)*tan(q[0] - atan((params.Lh1/params.L)*tan(u.steering_angle)));\n\n\n        dq[0] = u.speed * (sin(q[0])/params.Lh1 - (1 + (params.L1/params.Lh1)*cos(q[0]))*k1);\n        dq[1] = u.speed*k1;\n        dq[2] = u.speed*cos(q[1]);\n        dq[3] = u.speed*sin(q[1]);\n        return dq;\n    }\n\n    template <class T>\n    void singleParamIn(T& ParamVar,std::string& paramName,ast::ros::NodeHandle& nh)\n    {\n        if (nh.hasParam(paramName))\n        {\n        nh.getParam(paramName,ParamVar);\n        ROS_INFO_STREAM(\"\"<<paramName<<\" = \"<<ParamVar<<\"\");\n        }else\n        {\n        ROS_WARN_STREAM(\"parameter: \" << paramName << \" could not be found\");\n        }\n    }\n\n    void ParamsIn(mhe_estimator::CarParams& carParams,mhe_estimator::MheParams& mheParams,ast::ros::NodeHandle& nh)\n    {\n        std::string paramName;\n\n        paramName = \"/mhe_estimator/mheParam/mheActive\";\n        singleParamIn(mheParams.mheActive,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/WeightedActive\";\n        singleParamIn(mheParams.WeightedActive,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/loopRate\";\n        singleParamIn(mheParams.loopRate,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/perceptionGPS\";\n        singleParamIn(mheParams.perceptionGPS,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/covarianceFromTopicStamp\";\n        singleParamIn(mheParams.covarianceFromTopicStamp,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/noiseVariancePos\";\n        singleParamIn(mheParams.noiseVariancePos,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/noiseVarianceTh\";\n        singleParamIn(mheParams.noiseVarianceTh,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/noiseVariancesteering\";\n        singleParamIn(mheParams.noiseVariancesteering,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/noiseVarianceTrailer1\";\n        singleParamIn(mheParams.noiseVarianceTrailer1,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/noiseVarianceTrailer2\";\n        singleParamIn(mheParams.noiseVarianceTrailer2,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/noiseVarianceLinearVel\";\n        singleParamIn(mheParams.noiseVarianceLinearVel,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/noiseVarianceSteeringVel\";\n        singleParamIn(mheParams.noiseVarianceSteeringVel,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/WeightPos\";\n        singleParamIn(mheParams.WeightPos,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/WeightTh\";\n        singleParamIn(mheParams.WeightTh,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/WeightSteering\";\n        singleParamIn(mheParams.WeightSteering,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/WeightTrailer1\";\n        singleParamIn(mheParams.WeightTrailer1,paramName,nh);\n\n        paramName = \"/mhe_estimator/mheParam/WeightTrailer2\";\n        singleParamIn(mheParams.WeightTrailer2,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/WagonNumbers\";\n        singleParamIn(carParams.TrailerNumber,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/L\";\n        singleParamIn(carParams.L,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/L1\";\n        singleParamIn(carParams.L1,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/Lh1\";\n        singleParamIn(carParams.Lh1,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/L2\";\n        singleParamIn(carParams.L2,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/Lh2\";\n        singleParamIn(carParams.Lh2,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/steeringLimit\";\n        singleParamIn(carParams.steeringLimit,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/trailer1Limit\";\n        singleParamIn(carParams.trailer1Limit,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/trailer2Limit\";\n        singleParamIn(carParams.trailer2Limit,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/LinearVelLimit\";\n        singleParamIn(carParams.LinearVelLimit,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/SteeringVelLimit\";\n        singleParamIn(carParams.SteeringVelLimit,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/moveGuidancePoint\";\n        singleParamIn(carParams.moveGuidancePoint,paramName,nh);\n        \n        paramName = \"/mhe_estimator/carParam/respectSteeringLimits\";\n        singleParamIn(carParams.respectSteeringLimits,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/upperTh\";\n        singleParamIn(carParams.upperTh,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/lowerTh\";\n        singleParamIn(carParams.lowerTh,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/upperX\";\n        singleParamIn(carParams.upperX,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/lowerX\";\n        singleParamIn(carParams.lowerX,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/upperY\";\n        singleParamIn(carParams.upperY,paramName,nh);\n\n        paramName = \"/mhe_estimator/carParam/lowerY\";\n        singleParamIn(carParams.lowerY,paramName,nh);\n    \n        ROS_INFO_STREAM(\"End of receiving parameters\");\n\n    }\n\n\n}\n", "meta": {"hexsha": "3529c5e68143b7d24fc66d460b668e1b5f36dcf2", "size": 8617, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mhe_estimator/kinematics.hpp", "max_stars_repo_name": "crt-adas/mhe_estimator", "max_stars_repo_head_hexsha": "e96669c84c1eae76d13f03b2f5123e099419f2c7", "max_stars_repo_licenses": ["MIT"], "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/mhe_estimator/kinematics.hpp", "max_issues_repo_name": "crt-adas/mhe_estimator", "max_issues_repo_head_hexsha": "e96669c84c1eae76d13f03b2f5123e099419f2c7", "max_issues_repo_licenses": ["MIT"], "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/mhe_estimator/kinematics.hpp", "max_forks_repo_name": "crt-adas/mhe_estimator", "max_forks_repo_head_hexsha": "e96669c84c1eae76d13f03b2f5123e099419f2c7", "max_forks_repo_licenses": ["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.3155737705, "max_line_length": 154, "alphanum_fraction": 0.6600905187, "num_tokens": 2340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5040611594540049}}
{"text": "#include <gtest/gtest.h>\n\n#include \"scheme/numeric/util.hh\"\n\n#include \"scheme/nest/pmap/Rotation1DMap.hh\"\n#include \"scheme/nest/NEST.hh\"\n\n#include <Eigen/Dense>\n#include <random>\n\n#include <boost/lexical_cast.hpp>\n\n#include <fstream>\n\nnamespace scheme { namespace nest { namespace pmap { namespace test {\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl;\n\nVector3d get_axis( Matrix3d const & m ){\n\tAngleAxisd aa( m );\n\tif( aa.axis().dot( Vector3d(1,1,1) ) < 0 ) return -aa.axis();\n\telse                                       return  aa.axis();\n}\ndouble get_angle( Matrix3d const & m ){\n\tAngleAxisd aa( m );\n\tif( aa.axis().dot( Vector3d(1,1,1) ) < 0 ) return -aa.angle();\n\telse                                       return  aa.angle();\n}\n\nTEST( Rotation1DMap , flip_test ){\n\n\t{\n\t\tNEST<1,Matrix3d,Rotation1DMap> nest;\n\t\tVector3d axis(1,0,0), flip(0,1,0);\n\t\tnest.set_axis( axis );\n\t\tnest.set_flip_axis( flip );\n\t\t{ Matrix3d m = nest.set_and_get(0,0); ASSERT_DOUBLE_EQ(  0.0     , get_angle(m) );                                               }\n\t\t{ Matrix3d m = nest.set_and_get(1,0); ASSERT_DOUBLE_EQ(  M_PI    , get_angle(m) ); ASSERT_GE( get_axis(m).dot( flip ), 0.9999 ); }\n\t\t{ Matrix3d m = nest.set_and_get(0,1); ASSERT_DOUBLE_EQ( -M_PI/2.0, get_angle(m) ); ASSERT_GE( get_axis(m).dot( axis ), 0.9999 ); }\n\t\t{ Matrix3d m = nest.set_and_get(1,1); ASSERT_DOUBLE_EQ(  M_PI/2.0, get_angle(m) ); ASSERT_GE( get_axis(m).dot( axis ), 0.9999 ); }\n\t\t{\n\t\t\tMatrix3d m = nest.set_and_get(2,1);\n\t\t\tASSERT_DOUBLE_EQ(  M_PI    , get_angle(m) );\n\t\t\tASSERT_GE( get_axis(m).dot( Vector3d(0,sqrt(2)/2,-sqrt(2)/2) ), 0.9999 );\n\t\t}\n\t\t{\n\t\t\tMatrix3d m = nest.set_and_get(3,1);\n\t\t\tASSERT_DOUBLE_EQ(  M_PI, get_angle(m) );\n\t\t\tASSERT_GE( get_axis(m).dot( Vector3d(0,sqrt(2)/2,sqrt(2)/2) ), 0.9999 );\n\t\t}\n\t\t#ifndef NDEBUG\n\t\t#ifndef CXX14\n\t\tASSERT_DEATH( nest.set_and_get(4,1), \".*\" );\n\t\t#endif\n\t\t#endif\n\t}\n\n}\n\nTEST( Rotation1DMap , basic_test ){\n\n\t{\n\t\tNEST<1,Matrix3d,Rotation1DMap> nest;\n\t\tVector3d axis(1,0,0); nest.set_axis( axis );\n\t\t{ Matrix3d m = nest.set_and_get(0,0); ASSERT_DOUBLE_EQ(  0.0     , get_angle(m) );                                               }\n\t\t{ Matrix3d m = nest.set_and_get(0,1); ASSERT_DOUBLE_EQ( -M_PI/2.0, get_angle(m) ); ASSERT_GE( get_axis(m).dot( axis ), 0.9999 ); }\n\t\t{ Matrix3d m = nest.set_and_get(1,1); ASSERT_DOUBLE_EQ(  M_PI/2.0, get_angle(m) ); ASSERT_GE( get_axis(m).dot( axis ), 0.9999 ); }\n\t}\n\t{\n\t\tNEST<1,Matrix3d,Rotation1DMap> nest;\n\t\tVector3d axis(1,1,1); nest.set_axis( axis );\n\t\t{ Matrix3d m = nest.set_and_get(0,0); ASSERT_DOUBLE_EQ(  0.0     , get_angle(m) );                                               }\n\t\t{ Matrix3d m = nest.set_and_get(0,1); ASSERT_DOUBLE_EQ( -M_PI/2.0, get_angle(m) ); ASSERT_GE( get_axis(m).dot( axis ), 0.9999 ); }\n\t\t{ Matrix3d m = nest.set_and_get(1,1); ASSERT_DOUBLE_EQ(  M_PI/2.0, get_angle(m) ); ASSERT_GE( get_axis(m).dot( axis ), 0.9999 ); }\n\t}\n\t{\n\t\tNEST<1,Matrix3d,Rotation1DMap> nest(0,M_PI,1);\n\t\tVector3d axis(1,1,1); nest.set_axis( axis );\n\t\t{ Matrix3d m = nest.set_and_get(0,0); ASSERT_DOUBLE_EQ(    M_PI/2.0, get_angle(m) ); ASSERT_GE( get_axis(m).dot( axis ), 0.9999 ); }\n\t\t{ Matrix3d m = nest.set_and_get(0,1); ASSERT_DOUBLE_EQ(    M_PI/4.0, get_angle(m) ); ASSERT_GE( get_axis(m).dot( axis ), 0.9999 ); }\n\t\t{ Matrix3d m = nest.set_and_get(1,1); ASSERT_DOUBLE_EQ(  3*M_PI/4.0, get_angle(m) ); ASSERT_GE( get_axis(m).dot( axis ), 0.9999 ); }\n\t}\n\n\n}\n\n\nTEST( Rotation1DMap , lookup ){\n\tint NITER = 1000;\n\t#ifdef NDEBUG\n\tNITER *= 30;\n\t#endif\n\n\tNEST<1,Matrix3d,Rotation1DMap> nest;\n\t// cout << nest.get_index( Matrix3d::Identity(), 0 ) << endl;\n\n\tNestBase<> *nestp = new NEST<1,Matrix3d,Rotation1DMap>();\n\tMatrix3d m = Matrix3d::Identity();\n\tASSERT_EQ( 0, nestp->virtual_get_index( &m , 0 ) );\n\n\tstd::mt19937 rng(0);\n\tstd::normal_distribution<> gauss;\n\tstd::uniform_real_distribution<> uniform;\n\tfor(int i = 0; i < NITER; ++i){\n\t\tVector3d axis( gauss(rng), gauss(rng), gauss(rng) );\n\t\taxis.normalize();\n\t\tnest.set_axis(axis);\n\t\tnest.lb = uniform(rng) * 2*M_PI - M_PI;\n\t\tnest.ub = nest.lb + uniform(rng) * (2*M_PI-nest.lb-M_PI);\n\t\tBOOST_VERIFY( -M_PI <= nest.lb && nest.lb <= M_PI );\n\t\tBOOST_VERIFY( -M_PI <= nest.ub && nest.ub <= M_PI );\n\t\tBOOST_VERIFY( nest.lb < nest.ub );\n\t\tnest.nside = (uint64_t)(3*uniform(rng)+1.0);\n\n\t\tfor(int resl = 0; resl < 5; ++resl){\n\t\t\tfor(uint64_t index = 0; index < nest.size(resl); ++index){\n\t\t\t\tMatrix3d m = nest.set_and_get(index,resl);\n\t\t\t\tASSERT_EQ( nest.get_index(m,resl), index );\n\t\t\t}\n\t\t}\n\n\n\t}\n}\n\nTEST( Rotation1DMap , lookup_flip ){\n\tint NITER = 1000;\n\t#ifdef NDEBUG\n\tNITER *= 30;\n\t#endif\n\n\tNEST<1,Matrix3d,Rotation1DMap> nest;\n\t// cout << nest.get_index( Matrix3d::Identity(), 0 ) << endl;\n\n\tNestBase<> *nestp = new NEST<1,Matrix3d,Rotation1DMap>();\n\tMatrix3d m = Matrix3d::Identity();\n\tASSERT_EQ( 0, nestp->virtual_get_index( &m , 0 ) );\n\n\tstd::mt19937 rng(0);\n\tstd::normal_distribution<> gauss;\n\tstd::uniform_real_distribution<> uniform;\n\tfor(int i = 0; i < NITER; ++i){\n\t\tVector3d axis( gauss(rng), gauss(rng), gauss(rng) );\n\t\taxis.normalize();\n\t\tnest.set_axis(axis);\n\t\tnest.set_flip_axis( axis.cross( Vector3d( gauss(rng), gauss(rng), gauss(rng) ) ) );\n\t\tnest.lb = uniform(rng) * 2*M_PI - M_PI;\n\t\tnest.ub = nest.lb + uniform(rng) * (2*M_PI-nest.lb-M_PI);\n\t\tBOOST_VERIFY( -M_PI <= nest.lb && nest.lb <= M_PI );\n\t\tBOOST_VERIFY( -M_PI <= nest.ub && nest.ub <= M_PI );\n\t\tBOOST_VERIFY( nest.lb < nest.ub );\n\t\tnest.nside = (uint64_t)(3*uniform(rng)+1.0);\n\n\t\tfor(int resl = 0; resl < 5; ++resl){\n\t\t\tfor(uint64_t index = 0; index < nest.size(resl); ++index){\n\t\t\t\tMatrix3d m = nest.set_and_get(index,resl);\n\t\t\t\tASSERT_EQ( nest.get_index(m,resl), index );\n\t\t\t}\n\t\t}\n\n\n\t}\n}\n\n}}}}\n", "meta": {"hexsha": "c6690e6896cd693f7d28d16e70b1b8054d417da1", "size": 5682, "ext": "cc", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/nest/pmap/Rotation1DMap.gtest.cc", "max_stars_repo_name": "YaoYinYing/rifdock", "max_stars_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T01:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:16:08.000Z", "max_issues_repo_path": "schemelib/scheme/nest/pmap/Rotation1DMap.gtest.cc", "max_issues_repo_name": "YaoYinYing/rifdock", "max_issues_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-30T17:45:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:02:44.000Z", "max_forks_repo_path": "schemelib/scheme/nest/pmap/Rotation1DMap.gtest.cc", "max_forks_repo_name": "YaoYinYing/rifdock", "max_forks_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T01:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:56:17.000Z", "avg_line_length": 33.8214285714, "max_line_length": 134, "alphanum_fraction": 0.6224920803, "num_tokens": 1976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5040611594540049}}
{"text": "#include <iostream>\n#include <optional>\n\n#include <boost/asio.hpp>\n\n#include \"vdf.h\"\n\n\nusing namespace std;\n\n\nint gcd_base_bits = 50;\nint gcd_128_max_iter = 3;\n\n\nstruct vdf_result {\n    // TODO?: add D, T\n    form y;\n    form p;\n};\n\nstruct bluebox_request {\n    integer discriminant;\n    uint64_t iterations;\n};\n\n\nvoid repeated_square_1weso(const integer& D, uint64_t T, WesolowskiCallback* weso) {\n    vdf_original vdfo;\n    integer L = root(-D, 4);\n    form x = form::generator(D);\n\n    uint64_t num_iterations = 0;\n    while (num_iterations <= T) {\n        uint64 batch_size = checkpoint_interval;\n\n        square_state_type square_state;\n        square_state.pairindex = 0;\n\n        // Overall throughput for blueboxing significantly increases if we run\n        // one single-threaded worker per CPU (hyper-)thread, instead of one\n        // dual-threaded worker per every two CPU (hyper-)threads.\n        uint64 actual_iterations = repeated_square_fast_single_thread(square_state, x, D, L, num_iterations, batch_size, weso);\n        if (actual_iterations == ~uint64(0)) {\n            // Corruption; f is unchanged. Do the entire batch with the slow\n            // algorithm.\n            repeated_square_original(vdfo, x, D, L, num_iterations, batch_size, weso);\n            actual_iterations = batch_size;\n        } else if (actual_iterations < batch_size) {\n            // The fast algorithm terminated prematurely for whatever reason. f\n            // is still valid. It might terminate prematurely again (e.g. gcd\n            // quotient too large), so do one iteration of the slow algorithm.\n            // This will also reduce f if the fast algorithm terminated because\n            // it was too big.\n            repeated_square_original(vdfo, x, D, L, num_iterations + actual_iterations, 1, weso);\n            actual_iterations += 1;\n        }\n        num_iterations += actual_iterations;\n    }\n}\n\nform prove_1weso(integer D, uint64_t T, form y, form* intermediates) {\n    form x = form::generator(D);\n\n    // OneWesolowskiProver(Segment(0, T, x, y), D, intermediates, stopped)\n    uint32_t k;\n    uint32_t l;\n    if (T >= (1 << 16)) {\n        ApproximateParameters(T, k, l);\n    } else {\n        k = 10;\n        l = 1;\n    }\n\n    // GenerateProof()\n    uint64_t k1 = k / 2;\n    uint64_t k0 = k - k1;\n\n    PulmarkReducer reducer;\n\n    integer B = GetB(D, x, y);\n    integer L = root(-D, 4);\n    form id = form::identity(D);\n    form p = id;\n\n    for (int64_t j = l - 1; j >= 0; j--) {\n        p = FastPowFormNucomp(p, D, integer(1 << k), L, reducer);\n\n        vector<form> ys((1 << k));\n        for (uint64_t i = 0; i < (1 << k); i++) {\n            ys[i] = id;\n        }\n\n        uint64_t limit = T / (k * l);\n        if (T % (k * l)) {\n            limit++;\n        }\n\n        for (uint64_t i = 0; i < limit; i++) {\n            if (T >= k * (i * l + j + 1)) {\n                // uint64_t b = GetBlock(i*l + j, k, T, B);\n                integer res = FastPow(2, T - k * (i*l + j + 1), B);\n                mpz_mul_2exp(res.impl, res.impl, k);\n                res = res / B;\n                auto res_vector = res.to_vector();  // @@ smells\n                uint64_t b = res_vector.empty() ? 0 : res_vector[0];\n\n                nucomp_form(ys[b], ys[b], intermediates[i], D, L);\n            }\n        }\n\n        for (uint64_t b1 = 0; b1 < (1 << k1); b1++) {\n            form z = id;\n            for (uint64_t b0 = 0; b0 < (1 << k0); b0++) {\n                nucomp_form(z, z, ys[b1 * (1 << k0) + b0], D, L);\n            }\n            z = FastPowFormNucomp(z, D, integer(b1 * (1 << k0)), L, reducer);\n            nucomp_form(p, p, z, D, L);\n        }\n\n        for (uint64_t b0 = 0; b0 < (1 << k0); b0++) {\n            form z = id;\n            for (uint64_t b1 = 0; b1 < (1 << k1); b1++) {\n                nucomp_form(z, z, ys[b1 * (1 << k0) + b0], D, L);\n            }\n            z = FastPowFormNucomp(z, D, integer(b0), L, reducer);\n            nucomp_form(p, p, z, D, L);\n        }\n    }\n    reducer.reduce(p);\n\n    return p;\n}\n\nvdf_result vdf_1weso(integer& D, uint64_t T) {\n    cout << \"[vdf] Computing repeated square x^2^\" << T << \".\" << endl << flush;\n\n    form x = form::generator(D);\n    cout << \"[vdf] Base: x.c=\" << x.c.impl << endl;\n    OneWesolowskiCallback weso_cb(D, x, T);\n    auto t0 = chrono::high_resolution_clock::now();\n    repeated_square_1weso(D, T, &weso_cb);\n    auto t1 = chrono::high_resolution_clock::now();\n    auto td = chrono::duration<double>(t1 - t0).count();\n    form y = weso_cb.result;\n    form *intermediates = weso_cb.forms.get();  // @@ copy/ref, lifetime = weso_cb\n    cout << \"[vdf] Result: y.a=\" << y.a.impl << \" y.b=\" << y.b.impl << endl;\n    if (td > 0) {\n        uint32_t kips = T / td / 1000;\n        cout << \"[vdf] Computed repeated square. kips=\" << kips << endl << flush;\n    } else {\n        cout << \"[vdf] Computed repeated square. Too fast for kIPS calculation.\" << endl << flush;\n    }\n\n    cout << \"[vdf] Starting to compute Wesolowski proof.\" << endl << flush;\n    form p = prove_1weso(D, T, y, intermediates);\n    cout << \"[vdf] Proof: p.a=\" << p.a.impl << \" p.b=\" << p.b.impl << endl;\n    cout << \"[vdf] Finished computing Wesolowski proof.\" << endl << flush;\n\n    return vdf_result{y, p};\n}\n\nstring create_response(integer discriminant, uint64_t iterations, form y, form p) {\n    int witness_type = 0;\n    int discriminant_bits = discriminant.num_bits();\n    // = res[BQFC_FORM_SIZE]; reduce + bqfc_serialize(res, a, b, discriminant_bits);\n    // ~ core operator: bqfc_compress(a, b) -> a, t, g, b0, b_sign\n    std::vector<uint8_t> y_serialized = SerializeForm(y, discriminant_bits);;\n    std::vector<uint8_t> p_serialized = SerializeForm(p, discriminant_bits);;\n\n    std::vector<uint8_t> bytes;\n    uint8_t int64_bytes[8];\n\n    // Writes the number of iterations\n    Int64ToBytes(int64_bytes, iterations);\n    VectorAppendArray(bytes, int64_bytes, sizeof(int64_bytes));\n\n    // Writes the y, with prepended size\n    Int64ToBytes(int64_bytes, y_serialized.size());\n    VectorAppendArray(bytes, int64_bytes, sizeof(int64_bytes));\n    VectorAppend(bytes, y_serialized);\n\n    // Writes the witness type\n    bytes.push_back(witness_type);\n\n    // Writes the proof\n    VectorAppend(bytes, p_serialized);\n\n    return BytesToStr(bytes);\n}\n\ntcp::socket connect_client(boost::asio::io_context& io_context, string host, string port) {\n    tcp::socket socket(io_context);\n    tcp::resolver resolver(io_context);\n    boost::asio::connect(socket, resolver.resolve(host, port, boost::asio::ip::resolver_base::address_configured));\n    return socket;\n}\n\nbluebox_request read_request(tcp::socket &socket, const optional<string> client_id) {\n    char buffer[1024];\n    uint64_t size;\n\n    cout << \"[net] Reading request.\" << endl;\n\n    memset(buffer, 0, sizeof(buffer));\n    boost::asio::read(socket, boost::asio::buffer(buffer, 1));\n    // cout << \"[net] Prover type: \" << buffer[0] << endl;\n    assert (buffer[0] == 'S');\n\n    memset(buffer, 0, sizeof(buffer));\n    boost::asio::read(socket, boost::asio::buffer(buffer, 3));\n    size = stoull(buffer);\n    // cout << \"[net] Discriminant size: \" << size << endl;\n\n    memset(buffer, 0, sizeof(buffer));\n    boost::asio::read(socket, boost::asio::buffer(buffer, size));\n    integer discriminant(buffer);\n    cout << \"[net] Discriminant: D=\" << discriminant.impl << endl;\n\n    memset(buffer, 0, sizeof(buffer));\n    boost::asio::read(socket, boost::asio::buffer(buffer, 1));\n    size = buffer[0];\n\n    memset(buffer, 0, sizeof(buffer));\n    boost::asio::read(socket, boost::asio::buffer(buffer, size));\n    // initial_form is not used for blueboxing. TODO: debug print nevertheless\n\n    if (client_id) {\n        string id = client_id.value();\n        assert (id.size() < 256);\n        uint8_t len = id.size();\n        boost::asio::write(socket, boost::asio::buffer(\"ID\", 2));\n        boost::asio::write(socket, boost::asio::buffer(&len, 1));\n        boost::asio::write(socket, boost::asio::buffer(id, len));\n    } else {\n        boost::asio::write(socket, boost::asio::buffer(\"OK\", 2));\n    }\n\n    memset(buffer, 0, sizeof(buffer));\n    boost::asio::read(socket, boost::asio::buffer(buffer, 2));\n    size = stoull(buffer);\n    // cout << \"[net] Iterations size: \" << size << endl;\n\n    memset(buffer, 0, sizeof(buffer));\n    boost::asio::read(socket, boost::asio::buffer(buffer, size));\n    uint64_t iterations = stoull(buffer);\n    cout << \"[net] Iterations: T=\" << iterations << endl;\n\n    return bluebox_request{discriminant, iterations};\n}\n\nvoid interact_ping(tcp::socket& socket) {\n    cout << \"[net] Sending PING.\" << endl;\n    boost::asio::write(socket, boost::asio::buffer(\"PING\", 4));\n\n    char buffer[1024];\n    boost::asio::read(socket, boost::asio::buffer(buffer, 4));\n    assert (strncmp(buffer, \"PONG\", 4) == 0);\n    cout << \"[net] Received PONG.\" << endl;\n}\n\nvoid write_response(tcp::socket& socket, string& res) {\n    uint8_t res_size[4];\n    Int32ToBytes(res_size, res.size());\n    boost::asio::write(socket, boost::asio::buffer(res_size, 4));\n    boost::asio::write(socket, boost::asio::buffer(res.c_str(), res.size()));\n\n    cout << \"[net] Sending STOP.\" << endl;\n    boost::asio::write(socket, boost::asio::buffer(\"STOP\", 4));\n\n    cout << \"[net] Waiting for ACK.\" << endl;\n    char buffer[1024];\n    boost::asio::read(socket, boost::asio::buffer(buffer, 3));\n    assert (strncmp(buffer, \"ACK\", 3) == 0);\n\n    cout << \"[net] Sent response.\" << endl;\n}\n\nvoid dump_response(string &res) {\n    uint8_t res_size[4];\n    Int32ToBytes(res_size, res.size());\n\n    cout << \"[net] Response: size=0x\";\n    {\n        auto flags = cout.flags();\n        cout << hex << setfill('0')\n            << setw(2) << +res_size[0]\n            << setw(2) << +res_size[1]\n            << setw(2) << +res_size[2]\n            << setw(2) << +res_size[3];\n        cout.flags(flags);\n    }\n    cout << \" data=\" << res << endl;\n}\n\nint run_vdf(int argc, char *argv[]) {\n    integer D(argv[2]);\n    uint64_t T = atoi(argv[3]);\n\n    cout << \"Discriminant: D=\" << D.impl << endl;\n    cout << \"Iterations: T=\" << T << endl;\n\n    vdf_result r = vdf_1weso(D, T);\n\n    string res = create_response(D, T, r.y, r.p);\n    dump_response(res);\n\n    return 0;\n}\n\nint run_client(int argc, char *argv[]) {\n    auto host = argv[2];\n    auto port = argv[3];\n    auto client_id = argc > 3 ? optional<string>{argv[4]} : nullopt;\n\n    boost::asio::io_context io_context;\n    tcp::socket socket = connect_client(io_context, host, port);\n\n    bluebox_request req = read_request(socket, client_id);\n\n    future<vdf_result> vdf_future = async(vdf_1weso, ref(req.discriminant), req.iterations);\n    future_status vdf_status;\n    do {\n        switch (vdf_status = vdf_future.wait_for(chrono::minutes(3)); vdf_status) {\n            case future_status::timeout: interact_ping(socket); break;\n        }\n    } while (vdf_status != future_status::ready);\n    vdf_result r = vdf_future.get();\n\n    string res = create_response(req.discriminant, req.iterations, r.y, r.p);\n    dump_response(res);\n\n    write_response(socket, res);\n\n    return 0;\n}\n\nint main(int argc, char *argv[]) try {\n    if (argc < 3 || (argv[1][0] != 'p' && argv[1][0] != 'c')) {\n        cerr << \"Usage: \" << argv[0] << \" <mode> <args>\" << endl;\n        cerr << \"  \" << argv[0] << \" p <discriminant> <iterations>\" << endl;\n        cerr << \"  \" << argv[0] << \" c <host> <port> [<client_id>]\" << endl;\n        return 64;\n    }\n\n    init_gmp();\n    if (hasAVX2()) {\n        gcd_base_bits = 63;\n        gcd_128_max_iter = 2;\n    }\n    set_rounding_mode();\n\n    switch (argv[1][0]) {\n    case 'p':\n        return run_vdf(argc, argv);\n    case 'c':\n        return run_client(argc, argv);\n    }\n    cerr << \"nyi\" << endl;\n    return 64;\n} catch (exception &e) {\n    cerr << \"[cli] Exception: \" << e.what() << endl;\n    return 1;\n}\n\n// TODO: better cli parsing\n// TODO: progress! (bar?), new proto\n// TODO: proper logging?\n// TODO: looped client? (would make timelord-launcher obsolete)\n", "meta": {"hexsha": "23323dfd64d5c19f462954cf882cb7d4099f00b8", "size": 12001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bluebox_client.cpp", "max_stars_repo_name": "xchdata/chiavdf", "max_stars_repo_head_hexsha": "8f573cac981694ebb9444adb12dc04650a82894c", "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/bluebox_client.cpp", "max_issues_repo_name": "xchdata/chiavdf", "max_issues_repo_head_hexsha": "8f573cac981694ebb9444adb12dc04650a82894c", "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/bluebox_client.cpp", "max_forks_repo_name": "xchdata/chiavdf", "max_forks_repo_head_hexsha": "8f573cac981694ebb9444adb12dc04650a82894c", "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.4351351351, "max_line_length": 127, "alphanum_fraction": 0.5829514207, "num_tokens": 3412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5040105728637841}}
{"text": "#include \"solvers/SolverBoxBPP.h\"\n\n#include \"rigidbody/RigidBodySystem.h\"\n#include \"rigidbody/RigidBody.h\"\n#include \"contact/Contact.h\"\n\n#include <Eigen/Dense>\n\nnamespace\n{\n    enum eIndexSet { kFree = 0, kLower, kUpper, kIgnore };\n\n    static inline void multAndSub(const JBlock& G, const Eigen::Vector3f& x, const Eigen::Vector3f& y, const float a, Eigen::Ref<Eigen::VectorXf> b)\n    {\n            b -= a * G.col(0) * x(0);\n            b -= a * G.col(1) * x(1);\n            b -= a * G.col(2) * x(2);\n            b -= a * G.col(3) * y(0);\n            b -= a * G.col(4) * y(1);\n            b -= a * G.col(5) * y(2);\n    }\n\n    static inline unsigned int initContacts(std::vector<Contact*>& contacts)\n    {\n        // Count the number of constraint rows\n        // and assign each contact an index.\n        //\n        unsigned int rows = 0;\n        for(auto c : contacts)\n        {\n            c->index = rows;\n            rows += c->J0.rows();\n        }\n\n        return rows;\n    }\n\n    // Update the box bounds, lower and upper, of the constraint impulses.\n    // The value in Contact::lambda is used for updating the bounds.\n    //\n    static inline void updateBounds(std::vector<Contact*>& contacts, Eigen::VectorXf& lower, Eigen::VectorXf& upper)\n    {\n        for(auto c : contacts)\n        {\n            const unsigned int dim = c->J0.rows();\n            // Non-interpenetration row.\n            //\n            lower(c->index) = 0.0f;\n            upper(c->index) = std::numeric_limits<float>::max();\n\n            // Friction rows.\n            // Compute the box bounds as [-mu*lambda_n, mu*lambda_n]\n            // which is an approximation of the isotropic Coulomb friction cone.\n            //\n            for(unsigned int i = 1; i < dim; ++i)\n            {\n                lower(c->index + i) = -c->mu * c->lambda(0);\n                upper(c->index + i) = c->mu * c->lambda(0);\n            }\n        }\n    }\n\n    // Build the rhs vector of the Schur complement linear system.\n    //\n    static inline void buildRHS(const std::vector<Contact*>& contacts, float h, Eigen::VectorXf& b)\n    {\n        for(auto c : contacts)\n        {\n            const float gamma = h * c->k / (h * c->k + c->b); // error reduction parameter\n            const unsigned int dim = c->J0.rows();\n            b.segment(c->index, dim) = -gamma * c->phi / h;\n\n            multAndSub(c->J0, c->body0->xdot, c->body0->omega, 1.0f, b.segment(c->index, dim));\n            multAndSub(c->J1, c->body1->xdot, c->body1->omega, 1.0f, b.segment(c->index, dim));\n\n            if( !c->body0->fixed )\n            {\n                multAndSub(c->J0Minv, c->body0->f, c->body0->tau, h, b.segment(c->index, dim));\n            }\n            if( !c->body1->fixed )\n            {\n                multAndSub(c->J1Minv, c->body1->f, c->body1->tau, h, b.segment(c->index, dim));\n            }\n        }\n    }\n\n    // Build the Schur complement system using the contact constraints.\n    //\n    static inline void buildMatrix(const std::vector<Contact*>& contacts, float h, Eigen::MatrixXf& A)\n    {\n        for(auto c : contacts)\n        {\n            const unsigned int dim = c->J0.rows();\n            const float eps = 1.0f / (h * h * c->k + h * c->b);    // constraint force mixing\n\n            A.block(c->index, c->index, dim, dim) = 1e-10f * Eigen::MatrixXf::Identity(dim, dim);\n            A(c->index, c->index) += eps;\n\n            if( !c->body0->fixed )\n            {\n                A.block(c->index, c->index, dim, dim) += c->J0Minv * c->J0.transpose();\n                for(auto cc : c->body0->contacts)\n                {\n                    if( cc != c )\n                    {\n                        const int ddim = c->J0.rows();\n                        if( cc->body0 == c->body0 )\n                        {\n                            A.block(c->index, cc->index, dim, ddim) += c->J0Minv * cc->J0.transpose();\n                        }\n                        else\n                        {\n                            A.block(c->index, cc->index, dim, ddim) += c->J0Minv * cc->J1.transpose();\n                        }\n                    }\n                }\n            }\n\n\n            if( !c->body1->fixed )\n            {\n                A.block(c->index, c->index, dim, dim) += c->J1Minv * c->J1.transpose();\n\n                for(auto cc : c->body1->contacts)\n                {\n                    if( cc != c )\n                    {\n                        const int ddim = c->J1.rows();\n                        if( cc->body0 == c->body1 )\n                        {\n                            A.block(c->index, cc->index, dim, ddim) += c->J1Minv * cc->J0.transpose();\n                        }\n                        else\n                        {\n                            A.block(c->index, cc->index, dim, ddim) += c->J1Minv * cc->J1.transpose();\n                        }\n                    }\n                }\n            }\n        }\n\n    }\n\n    // Pivoting rules.\n    // The index set is updates based on the LCP variables x and v.\n    // Specifically, 'free' variables are pivoted to the 'tight' set if the lower or upper bounds are violated.\n    // Similarly, 'tight' variables are pivoted to the 'free' set if the residual velocity v has the wrong sign.\n    // \n    static inline unsigned int pivot(Eigen::VectorXi& idx, Eigen::VectorXf& x, const Eigen::VectorXf& l, const Eigen::VectorXf& u, const Eigen::VectorXf& v)\n    {\n        static const float tol = 1e-5f;\n        unsigned int numPivots = 0;\n        const unsigned int n = idx.rows();\n        for (unsigned int j = 0; j < n; ++j)\n        {\n            // By default, assume all variables belong to the 'free' set.\n            //\n            int new_idx = kFree;  \n\n            if (idx[j] == kIgnore) continue;\n\n            if(idx[j] == kFree && x[j] <= l[j])     // case: free variable, lower bound\n            {\n                new_idx = kLower;\n            }\n            else if(idx[j] == kFree && x[j] >= u[j])  // case: free variable, upper bound\n            {\n                new_idx = kUpper;\n            }\n            else if(idx[j] == kLower && v[j] > -tol)    // case: lower tight variable, +ve velocity\n            {\n                new_idx = kLower;\n            }\n            else if(idx[j] == kUpper && v[j] < tol)     // case: upper tight variable, -ve velocity\n            {\n                new_idx = kUpper;\n            }\n\n            if(new_idx != idx[j])\n            {\n                ++numPivots;\n                idx[j] = new_idx;\n            }\n        }\n        return numPivots;\n    }\n\n    // Returns the indices of tight variables in tightIdx.\n    //\n    static inline unsigned int tightIndices(const Eigen::VectorXi& idx, std::vector<int>& tightIdx)\n    {\n        const unsigned int n = idx.rows();\n        unsigned int numTight = 0;\n        tightIdx.clear();\n        for(unsigned int i = 0; i < n; ++i)\n        {\n            if( idx[i] == kLower || idx[i] == kUpper )\n            {\n                ++numTight;\n                tightIdx.push_back(i);\n            }\n        }\n        return numTight;\n    }\n\n    // Returns the indices of free variables in freeIdx.\n    //\n    static inline unsigned int freeIndices(const Eigen::VectorXi& idx, std::vector<int>& freeIdx)\n    {\n        const unsigned int n = idx.rows();\n        unsigned int numFree = 0;\n        freeIdx.clear();\n        for(unsigned int i = 0; i < n; ++i)\n        {\n            if( idx[i] == kFree )\n            {\n                ++numFree;\n                freeIdx.push_back(i);\n            }\n        }\n        return numFree;\n    }\n\n    // Solve the principal sub-problem comprising the free variables:\n    //      Aff * xf = bf - Aft * xt\n    // \n    //  where Aff is the sub-matrix of free variables, bf are the corresponding entries in the rhs vector,\n    //  Aft is the sub-matrix that couples the tight variables and the free variables, and \n    //  xt are the tight variables whose values is determined by the lower and upper bounds (l and u).\n    //\n    // Inputs: \n    //    A - the lead matrix\n    //    b - the rhs vector\n    //    idx - the index set of all variables\n    //    l - the lower bounds\n    //    u - the upper bounds\n    //\n    // Outputs:\n    //    x - the solution of constraint impulses (free and tight variables)\n    //\n    static inline void solvePrincipalSubproblem(const Eigen::MatrixXf& A,\n                                                const Eigen::VectorXf& b,\n                                                const Eigen::VectorXi& idx,\n                                                const Eigen::VectorXf& l,\n                                                const Eigen::VectorXf& u,\n                                                Eigen::VectorXf& x)\n    {\n        std::vector<int> freeIdx, tightIdx;\n        const unsigned int numTight = tightIndices(idx, tightIdx);\n        const unsigned int numFree = freeIndices(idx, freeIdx);\n        if( numFree > 0 )\n        {\n            Eigen::MatrixXf Aff(numFree, numFree);\n            Eigen::VectorXf bf(numFree);\n\n            // Build sub-matrix using free indices\n            //\n            for(unsigned int j = 0; j < numFree; ++j)\n            {\n                for(unsigned int i = 0; i < numFree; ++i)\n                {\n                    Aff(i,j) = A(freeIdx[i], freeIdx[j]);\n                }\n            }\n\n            // Build rhs vector using free indices\n            //\n            for (unsigned int i = 0; i < numFree; ++i)\n            {\n                bf(i) = b(freeIdx[i]);\n            }\n\n            // Update rhs vector with impulses from tight indices\n            //  e.g.     bf -= A_ft * x_t\n            //\n            for(unsigned int j = 0; j < numTight; ++j)\n            {\n                for(unsigned int i = 0; i < numFree; ++i)\n                {\n                    if( idx[tightIdx[j]] == kLower )\n                    {\n                        bf(i) -= A(freeIdx[i], tightIdx[j]) * l(tightIdx[j]);\n                    }\n                    else if( idx[tightIdx[j]] == kUpper )\n                    {\n                        bf(i) -= A(freeIdx[i], tightIdx[j]) * u(tightIdx[j]);\n                    }\n                }\n            }\n\n            // Cholesky solve for the principal sub-problem.\n            //\n            Eigen::LDLT<Eigen::MatrixXf> ldlt(Aff);\n            const Eigen::VectorXf xf = ldlt.solve(bf);\n\n            // Update free variables with the solution\n            for(unsigned int i = 0; i < numFree; ++i)\n            {\n                x(freeIdx[i]) = xf(i);\n            }\n\n            // Update tight variables with values from lower/upper bounds.\n            //\n            for(unsigned int i = 0; i < numTight; ++i)\n            {\n                if( idx[tightIdx[i]] == kLower )\n                {\n                    x(tightIdx[i]) = l(tightIdx[i]);\n                }\n                else if( idx[tightIdx[i]] == kUpper )\n                {\n                    x(tightIdx[i]) = u(tightIdx[i]);\n                }\n            }\n        }\n\n    }\n\n    static inline void updateContacts(const Eigen::VectorXf& x, std::vector<Contact*>& contacts)\n    {\n        // Distribute impulses to the contacts\n        //\n        for(auto c : contacts)\n        {\n            const unsigned int dim = c->J0.rows();\n            c->lambda = x.segment(c->index, dim);\n        }\n    }\n\n}\n\n\nSolverBoxBPP::SolverBoxBPP(RigidBodySystem* _rigidBodySystem) : Solver(_rigidBodySystem)\n{\n\n}\n\nvoid SolverBoxBPP::solve(float h)\n{\n    auto contacts = m_rigidBodySystem->getContacts();\n\n    const unsigned int numContacts = contacts.size();\n    if( numContacts > 0 )\n    {\n        const unsigned int dim = initContacts(contacts);\n\n        Eigen::MatrixXf A = Eigen::MatrixXf::Zero(dim,dim);\n        Eigen::VectorXf b = Eigen::VectorXf::Zero(dim);\n        Eigen::VectorXf x = Eigen::VectorXf::Zero(dim);\n\n        // Update box bounds.\n        //\n        Eigen::VectorXf lower = Eigen::VectorXf::Zero(dim);\n        Eigen::VectorXf upper = Eigen::VectorXf::Zero(dim);\n\n\t\tupdateBounds(contacts, lower, upper);\n\n\t\t// Initialize the index set.\n        // All variables are initially set to 'free'.\n        //\n\t\tEigen::VectorXi idx = Eigen::VectorXi::Constant(dim, kFree);\n\n\t\t// Ignore variables where lower and upper are zero.\n\t\t//\n\t\tfor (int i = 0; i < dim; ++i)\n\t\t{\n\t\t\tstatic const float tol = 1e-5f;\n\t\t\tif (std::abs(upper(i)) < tol && std::abs(lower(i) < tol))\n\t\t\t\tidx(i) = kIgnore;\n\t\t}\n\n        // Construct the lead matrix and rhs vector.\n        //\n        buildMatrix(contacts, h, A);\n        buildRHS(contacts, h, b);\n\n        // Perform an initial solve to update friction box bounds.\n        // \n        solvePrincipalSubproblem(A, b, idx, lower, upper, x);\n        updateContacts(x, contacts);\n        updateBounds(contacts, lower, upper);\n        idx.setConstant(kFree);\n\n        // Block pivoting iterations.\n        //\n        for(unsigned int iter = 0; iter < m_maxIter; ++iter)\n        {\n            // Solve the principal sub-problem:\n            //    Aff * xf = bf - Aft * xt\n            //\n            solvePrincipalSubproblem(A, b, idx, lower, upper, x);\n\n            // Compute residual velocity v.\n            //\n            const Eigen::VectorXf v = A*x - b;\n\n            // Pivot.\n            // \n            const int numPivots = pivot(idx, x, lower, upper, v);\n            if( numPivots == 0 )\n                break;      // Done\n        }\n\n        updateContacts(x, contacts);\n        updateBounds(contacts, lower, upper);\n    }\n}\n\n", "meta": {"hexsha": "fd76ba996403b89678bcfd2e6bceb8946ceb4e9f", "size": 13491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/SolverBoxBPP.cpp", "max_stars_repo_name": "sheldona/contactFrictionSim", "max_stars_repo_head_hexsha": "40374728b863c488d5fb780a90fc1feafe320fed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2022-03-14T03:51:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T17:47:44.000Z", "max_issues_repo_path": "src/solvers/SolverBoxBPP.cpp", "max_issues_repo_name": "sheldona/contactFrictionSim", "max_issues_repo_head_hexsha": "40374728b863c488d5fb780a90fc1feafe320fed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solvers/SolverBoxBPP.cpp", "max_forks_repo_name": "sheldona/contactFrictionSim", "max_forks_repo_head_hexsha": "40374728b863c488d5fb780a90fc1feafe320fed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-03-24T10:55:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:08:16.000Z", "avg_line_length": 32.9853300733, "max_line_length": 156, "alphanum_fraction": 0.4694240605, "num_tokens": 3344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5040105608805}}
{"text": "    // KALMANFILTER3D_UPDATE - updates a EKF with 9 state variables\n    // Called each time a new mobile-to-anchor measurement is available\n\n    // INPUTS:\n    // X - the 9x1 a priori state vector - [x,xdot,ax_bias,y,ydot,ay_bias,z,zdot,az_bias]'\n    // P - the 9x9 a priori covariance matrix\n    // T - the delta time between updates\n    // tao_acc - variance of acceleratmetor's gaussian noise\n    // tao_bias - variance of acceleratmetor bias's noise\n    // sigma_r - the estimated standard deviation of the new range measurement\n    // r_meas - the actual range measurement\n    // OUTPUTS:\n    // X - the new state vector estimate\n    // P - the new covariance matrix estimate\n    // error - the difference between the range measurement and the estimated\n    // range measurement (perhaps useful for outlier filtering.)\n\n    // determine whether to perform filter using SNR\n    // According to experiments on 2017-03-24,\n    // Time Domain UWB range info have incorrect vPeak when satuatured,\n    // probably because of Int16 overflow\n    // float SNR = 20 * std::log( range_info.vPeak / ( range_info.noise + 0.1) );\n    //   if(SNR < m_snr_threshold){\n    //       //ROS_WARN(\"Anchor %d SNR %f too small, discard.\", anchor_id, SNR);\n    //       return false;\n    //   }\n    // X(0) = m_position.point.x;\n    // X(1) = m_velocity.point.x;\n    // X(2) = m_acc_bias.point.x;\n    // X(3) = m_position.point.y;\n    // X(4) = m_velocity.point.y;\n    // X(5) = m_acc_bias.point.y;\n    // X(6) = m_position.point.z;\n    // X(7) = m_velocity.point.z;\n    // X(8) = m_acc_bias.point.z;\n\n    // ------------------------------------------------------------------\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <bits/stdc++.h>\n#include <ros/ros.h>\n#include <math.h>\n#include <stdio.h>\n#include <dwm1001/anchor.h> \n#include <sensor_msgs/Imu.h>\n#include \"std_msgs/MultiArrayLayout.h\"\n#include \"std_msgs/MultiArrayDimension.h\"\n#include \"std_msgs/Float32MultiArray.h\"\n#include \"geometry_msgs/Vector3Stamped.h\"\n#include \"geometry_msgs/PoseStamped.h\"\n#include \"mavros_msgs/Altitude.h\"\n#include \"sensor_msgs/Range.h\"\n#include \"geometry_msgs/TwistStamped.h\"\n\n// Declarations\ndouble r_pred;\n//int count =0 ;\nEigen::MatrixXd H(1,9);\ndouble R;\nEigen::VectorXd K(9);\ndouble error,error_threshold;\ndouble precisionRangeErrEst,precisionRangeMm;\n//\n//geometry_msgs::Vector3Stamped pose;\ngeometry_msgs::PoseStamped pose;\ngeometry_msgs::PoseStamped imu_msg;\nfloat ax,ay,az; \nEigen::Quaternionf q;\nEigen::Quaternionf q_;\nEigen::MatrixXf R_mat(3,3);\nEigen::MatrixXf imuacc(3,1);\nEigen::MatrixXf acc(3,1);\n//\nEigen::VectorXd X(9);\nEigen::VectorXd X_p(9);\nEigen::VectorXd X_e(9);\nEigen::MatrixXd F(9,9);\nEigen::MatrixXd block_F(3,3);\nEigen::MatrixXd Q(9,9);\nEigen::VectorXd u(9);\nEigen::MatrixXd B(9,9);\nEigen::MatrixXd P(9,9);\nEigen::MatrixXd P_p(9,9);\nEigen::MatrixXd M(9,9);\nEigen::MatrixXd block_B(3,3);\nEigen::MatrixXd block_Q(3,3);\n\ndouble r_vel;\nEigen::MatrixXd r_meas_vel(3,1);\nEigen::MatrixXd r_pred_vel(3,1);\nEigen::MatrixXd H_vel(3,9);\nEigen::MatrixXd R_vel(3,3);\nEigen::MatrixXd K_vel(9,3);\nEigen::MatrixXd P_p_vel(9,9);\nEigen::VectorXd X_p_vel(9);\n\ndouble tao_acc;\ndouble tao_bias,error_1;\ndouble sigma_r,sigma_a,r_meas;\ndouble T,yaw_off,yaw,yaw_rad;\ndouble m_R_scale;\ndouble m_last_range_time;\nstd_msgs::Float32MultiArray output;\n\ndouble m_kalman_sigma_a,T_sq,m_tao_acc_sqrt,m_tao_bias_sqrt,T_cub,m_z_damping_factor,m_Q_scale;\ndouble m_snr_threshold;\ndouble x,y,z;\ndouble ax_,ay_;\n\ndouble r_h,h_offset,h_meas;\nEigen::VectorXd X_h(9);\nEigen::MatrixXd P_h(9,9);\nEigen::VectorXd K_h(9);\nEigen::MatrixXd H_h(1,9);\nEigen::MatrixXd nine_cov = Eigen::MatrixXd::Identity(9,9);\ndouble trans_x,trans_y;\nEigen::MatrixXf rpy(3,1);\nint set_=0,set_p=0;\n\nvoid setState(Eigen::VectorXd Y)\n{\n    X = Y;\n}\nvoid setCovariance(Eigen::MatrixXd S)\n{\n    P = S;\n}\n\n\n\nvoid param(ros::NodeHandle& nh)\n{\n    nh.getParam(\"KalmanFilter/start_x\", x);\n    nh.getParam(\"KalmanFilter/start_y\", y);\n    nh.getParam(\"KalmanFilter/start_z\", z);\n    nh.getParam(\"KalmanFilter/error_threshold\", error_threshold);\n    nh.getParam(\"KalmanFilter/m_R_scale\", m_R_scale);\n    nh.getParam(\"KalmanFilter/precisionRangeErrEst\", precisionRangeErrEst);\n    nh.getParam(\"KalmanFilter/m_kalman_sigma_a\", m_kalman_sigma_a);\n    nh.getParam(\"KalmanFilter/precisionRangeMm\", precisionRangeMm);\n    nh.getParam(\"KalmanFilter/m_tao_acc_sqrt\", m_tao_acc_sqrt);\n    nh.getParam(\"KalmanFilter/m_tao_bias_sqrt\", m_tao_bias_sqrt );\n    nh.getParam(\"KalmanFilter/m_z_damping_factor\", m_z_damping_factor);\n    nh.getParam(\"KalmanFilter/m_Q_scale\", m_Q_scale);\n    nh.getParam(\"KalmanFilter/r_h\", r_h);\n    nh.getParam(\"KalmanFilter/r_vel\", r_vel);\n    nh.getParam(\"KalmanFilter/trans_x\", trans_x);\n    nh.getParam(\"KalmanFilter/trans_y\", trans_y);\n    nh.getParam(\"KalmanFilter/yaw_offset\", yaw_off);\n}\n\nvoid Initialize(ros::NodeHandle& nh)\n{\n \n    int static count_ =0 ;\n    if(count_ == 0)\n    {   param(nh);\n        count_++; }\n    else{\n    std::string pose_topic(\"initialize\");\n    // nav_msgs::Path edge;\n    // sharedEdge = ros::topic::waitForMessage<nav_msgs::Path>(\"/path_planned/edge\",create_path);\n    // if(sharedEdge != NULL){\n    // edge = *sharedEdge;\n    // }\n    boost::shared_ptr<dwm1001::anchor const> final_msg;\n    ros::Duration one_second(0.5);\n    final_msg = ros::topic::waitForMessage<dwm1001::anchor>(pose_topic,nh,one_second);\n    if(final_msg != NULL){\n    //p_msg  = *final_msg ;\n    x = final_msg->x;\n    y = final_msg->y;    \n    z = final_msg->z;\n    }\n\n    }\n    //ROS_WARN(\"m_Q_scale %f\", m_Q_scale);\n    // ROS_WARN(\"x %f\", x);\n\n    \n    nine_cov(0,0) = 0.001;\n    nine_cov(3,3) = 0.001;\n    nine_cov(6,6) = 0.001;\n    // set cov of vel\n    nine_cov(1,1) = 0.01;\n    nine_cov(4,4) = 0.01;\n    nine_cov(7,7) = 0.01;\n    // set cov of acc_bias\n    nine_cov(2,2) = 0.1;\n    nine_cov(5,5) = 0.1;\n    nine_cov(8,8) = 0.1;\n    setCovariance(nine_cov);\n    X<<x,0,0,y,0,0,z,0,0;\n    m_last_range_time = ros::Time::now().toSec();\n    H_h << 0, 0, 0,\n           0, 0, 0,\n           1, 0, 0;\n    H_vel << 0, 1, 0, 0, 0, 0, 0, 0, 0,\n             0, 0, 0, 0, 1, 0, 0, 0, 0,\n             0, 0, 0, 0, 0, 0, 0, 1, 0;\n\n\n\n}\n\nvoid Initialize_2()\n{\n \n \n    std::string pose_topic(\"initialize\");\n    boost::shared_ptr<dwm1001::anchor const> final_msg;\n    ros::Duration one_second(0.5);\n    final_msg = ros::topic::waitForMessage<dwm1001::anchor>(pose_topic,one_second);\n    if(final_msg != NULL){\n    //p_msg  = *final_msg ;\n    x = final_msg->x;\n    y = final_msg->y;    \n    z = final_msg->z;\n    }\n    ROS_WARN(\"initialized\");\n    //ROS_WARN(\"m_Q_scale %f\", m_Q_scale);\n    // ROS_WARN(\"x %f\", x);\n/*\n    Eigen::MatrixXd nine_cov = Eigen::MatrixXd::Identity(9,9);\n    nine_cov(0,0) = 0.001;\n    nine_cov(3,3) = 0.001;\n    nine_cov(6,6) = 0.001;\n    // set cov of vel\n    nine_cov(1,1) = 0.01;\n    nine_cov(4,4) = 0.01;\n    nine_cov(7,7) = 0.01;\n    // set cov of acc_bias\n    nine_cov(2,2) = 0.1;\n    nine_cov(5,5) = 0.1;\n    nine_cov(8,8) = 0.1;*/\n    setCovariance(nine_cov);\n    X<<x,0,0,y,0,0,z,0,0;\n    m_last_range_time = ros::Time::now().toSec();\n\n}\n\nvoid correction_step(const dwm1001::anchor::ConstPtr& msg)\n{   \n    r_pred = std::sqrt( std::pow(X(0) - msg->x, 2) +\n                        std::pow(X(3) - msg->y, 2) +\n                        std::pow(X(6) - msg->z, 2) ) + 1e-5;\n  \n    r_meas = msg->range;\n    // H is the linearized measurement matrix\n    H << (X(0) - msg->x)/r_pred, 0, 0,\n         (X(3) - msg->y)/r_pred, 0, 0,\n         (X(6) - msg->z)/r_pred, 0, 0;\n\n    // K is the Kalman Gain\n    sigma_r = double(precisionRangeErrEst) / 1000.0;\n    R = std::pow(sigma_r,2) * m_R_scale;\n    //ROS_WARN(\"runing\");\n    K= P*H.transpose() / ( (H*P*H.transpose())(0,0) + R );\n    // Update P for the a posteriori covariance matrix\n    //std::cout<<K(6)<<'\\n';\n\n    P_p = ( Eigen::MatrixXd::Identity(9,9) - K*H ) * P;\n    // Return the measurement innovation\n    error_1 = std::fabs(r_meas - r_pred);\n    // Update the state\n    X_p = X + K * (r_meas - r_pred);\n    // decide to take the range info or not.\n    if(error_1 < error_threshold){\n        //ROS_WARN(\"\\n sucess too large: %f\", error);\n        setState(X_p);\n        setCovariance(P_p);\n        //set_= 0;\n        return ;\n    } else {\n\n        ROS_WARN(\"Anchor id , Update too large: predicted %f measured-- %f\", r_pred, r_meas);\n        std::cout << msg->device_id << \"\\n\";\n        set_=set_+1;\n        if(set_>5)\n            {Initialize_2();\n              set_=0;\n            }\n        return ;\n    }\n\n}\n\n\n\nvoid convert_NED(sensor_msgs::Imu imu)\n{\n            int static count_ =0 ;\n    if(count_ == 0)\n       {ROS_WARN(\"<--------imu_step---------->\");\n        count_++; }\n    //conerts the acceleration from body frame to earth frame(NED) \n    q = Eigen::Quaternionf(imu.orientation.w, imu.orientation.x, imu.orientation.y, imu.orientation.z);\n    R_mat= q.toRotationMatrix();\n    //rpy = q.toRotationMatrix().eulerAngles(0, 1, 2);\n    //ROS_WARN(\"%f\",rpy(2,0)*180/3.14);\n    //yaw = rpy(2,0) - (yaw_off*0.017454);\n\n    ax=imu.linear_acceleration.x;\n    ay=imu.linear_acceleration.y;\n    az=imu.linear_acceleration.z;\n    imuacc << ax,ay,az;\n    acc= R_mat*imuacc ;\n    imu_msg.pose.orientation.w = imu.orientation.w;\n    imu_msg.pose.orientation.x = imu.orientation.x;\n    imu_msg.pose.orientation.y = imu.orientation.y;\n    imu_msg.pose.orientation.z = imu.orientation.z;\n\n}\n\n\nvoid prediction_step(const sensor_msgs::Imu::ConstPtr& msg)\n{\n    convert_NED(*msg);  \n    ax=acc(0,0);\n    ay=acc(1,0);\n    az=acc(2,0)-9.8;\n    \n    // yaw_rad = 0.0174533*yaw_off;\n    // ax_= ax*std::cos(yaw_rad) + ay*std::sin(yaw_rad);\n    // ay_=-ax*std::sin(yaw_rad) + ay*std::cos(yaw_rad);\n    //ROS_WARN(\"Acceleration:## %f, ## %f, ## %f\", ax,ay,az);\n    T = msg->header.stamp.toSec() - m_last_range_time;\n    if(T>1){\n        T = 1;\n    } else if(T<0){\n        T = 0.02;\n    }\n    \n    sigma_a = m_kalman_sigma_a;\n   // r_meas = double(precisionRangeMm) / 1000.0;\n    \n    T_sq = std::pow(T,2);\n    T_cub = std::pow(T,3);\n\n    // F is a 9x9 State Transition Matrix\n    F = Eigen::MatrixXd::Zero(9,9);\n\n    block_F << 1, T, -T_sq/2.0,\n               0, 1, -T,\n               0, 0, 1;\n    F.block<3,3>(0,0) = block_F;\n    F.block<3,3>(3,3) = block_F;\n    F.block<3,3>(6,6) = block_F;\n\n    // Q is the acceleration model\n    tao_acc = m_tao_acc_sqrt * m_tao_acc_sqrt;\n    tao_bias = m_tao_bias_sqrt * m_tao_bias_sqrt;\n    Q = Eigen::MatrixXd::Zero(9,9);\n    \n    block_Q << (T_cub*tao_acc/3.0)+(T_cub*T_sq)*tao_bias/20.0, (T_sq*tao_acc/2)+(T_sq*T_sq)*tao_bias/8.0  ,-T_cub*tao_bias/6,\n               (T_sq*tao_acc/2.0)+(T_sq*T_sq)*tao_bias/8.0 ,   T*tao_acc+(T_cub*tao_bias/3)               ,-T_sq*tao_bias/2,\n               -T_cub*tao_bias/6.0,                         -T_sq*tao_bias/2                          ,T*tao_bias         ;\n    Q.block<3,3>(0,0) = block_Q;\n    Q.block<3,3>(3,3) = block_Q;\n    Q.block<3,3>(6,6) = block_Q * m_z_damping_factor;\n    Q *= m_Q_scale;\n    //std::cout << block_Q*m_Q_scale << '\\n'<<'\\n';\n    //ROS_WARN(\"covariance:## %f, ## %f, ## %f\",(T_cub*tao_acc/3.0)+(T_cub*T_sq)*tao_bias/20.0 , T*tao_acc+(T_cub*tao_bias/3), T*tao_bias);\n   \n    u << ax, 0, 0,\n         ay, 0, 0,\n         az, 0, 0;\n    B = Eigen::MatrixXd::Zero(9,9);\n\n    block_B << T_sq/2.0,  0,  0,\n               T      ,  0,  0,\n               0      ,  0,  0;\n    B.block<3,3>(0,0) = block_B;\n    B.block<3,3>(3,3) = block_B;\n    B.block<3,3>(6,6) = block_B;\n\n    // X is the predicted state vector and the predicted covariance matrix\n    X_e = F*X + B * u;\n    //if(count%250 == 0)\n    //std::cout << P << '\\n'<<'\\n';\n    // M is the predicted covariance matrix\n    M = F*P*F.transpose() + Q;\n\n    // time update\n    m_last_range_time = msg->header.stamp.toSec();\n    //ROS_WARN(\"runing---12\");\n    error = X.squaredNorm()-X_e.squaredNorm();\n    //ROS_WARN(\"predicted %f#%f$%f\",X_e(0),X_e(3),X_e(6));\n    if(isnan(X(0))==1)\n        {Initialize_2();\n            return;}\n    if(error < error_threshold){\n        //ROS_WARN(\"\\n sucess too large: %f\", error);\n        set_p=0;\n        setState(X_e);\n        setCovariance(M);\n        return ;\n    } else {\n\n        ROS_WARN(\"\\n Estimate too large: %f\", error);\n       set_p=set_p+1;\n        if(set_p>5)\n            {Initialize_2();\n             set_p=0;\n            }\n        return ;\n    }\n\n}\n\n\nvoid anchor1_cb(const dwm1001::anchor::ConstPtr& msg)\n{\n    correction_step(msg);\n    //ROS_WARN(\"runing\");\n}\nvoid anchor2_cb(const dwm1001::anchor::ConstPtr& msg)\n{\n    correction_step(msg);\n}\nvoid anchor3_cb(const dwm1001::anchor::ConstPtr& msg)\n{\n    correction_step(msg);\n}\nvoid anchor4_cb(const dwm1001::anchor::ConstPtr& msg)\n{\n    correction_step(msg);\n}\n// void anchor5_cb(const dwm1001::anchor::ConstPtr& msg)\n// {\n//  correction_step(msg);\n// }\n// void anchor6_cb(const dwm1001::anchor::ConstPtr& msg)\n// {\n//  correction_step(msg);\n// }\n//x,y,z,error_threshold,sigma_r,m_R_scale,precisionRangeErrEst,m_kalman_sigma_a,precisionRangeMm,\n//m_tao_acc_sqrt,m_tao_bias_sqrt,m_z_damping_factor,m_Q_scale\nvoid correction_step_vel(const geometry_msgs::TwistStamped::ConstPtr& msg)\n{\n        int static count_ =0 ;\n    if(count_ == 0)\n       {ROS_WARN(\"<--------velocity_step---------->\");\n        count_++; }\n\n    r_pred_vel << X(1),X(4),X(7);\n\n    r_meas_vel << msg->twist.linear.x,msg->twist.linear.y,msg->twist.linear.z;\n    // K is the Kalman Gain\n    R_vel = Eigen::MatrixXd::Identity(3,3) * (r_vel*r_vel);\n    //ROS_WARN(\"R_matrix:## %f\",R);\n    R_vel = (H_vel * P * H_vel.transpose()) + R_vel ;\n    K_vel = P * H_vel.transpose() * R_vel.inverse();\n    // Update P for the a posteriori covariance matrix\n    P_p_vel = ( Eigen::MatrixXd::Identity(9,9) - K_vel * H_vel ) * P;\n    // Update the state\n    X_p_vel = X + K_vel * (r_meas_vel - r_pred_vel);\n    // decide to take the range info or not.\n        //ROS_WARN(\"\\n sucess velocity: %f\", );\n\n        setState(X_p_vel);\n        setCovariance(P_p_vel);\n        return ;\n\n}\n\nvoid height_cb(const sensor_msgs::Range::ConstPtr& msg)\n{\n    int static count_ =0 ;\n    if(count_ == 0)\n       {ROS_WARN(\"<--------height_step---------->\");\n        count_++; }\n\n    h_meas = msg->range;\n    // K is the Kalman Gain\n    r_h = r_h*r_h;\n    //ROS_WARN(\"R_matrix:## %f\",R);\n\n   K_h = P*H_h.transpose() / ( (H_h*P*H_h.transpose())(0,0) + r_h );\n\n    // K is the Kalman Gain\n    // Update P for the a posteriori covariance matrix\n    \n\n    P_h = ( Eigen::MatrixXd::Identity(9,9) - K_h*H_h ) * P;\n    // Return the measurement innovation\n    // Update the state\n    X_h = X + K_h * (h_meas - X(6));\n    //std::cout<<K_h<<\"--\"<<h_meas<<\"---\"<<X_h(6)<<'\\n';\n        //ROS_WARN(\"\\n height: %f\", msg->local);\n        setState(X_h);\n        setCovariance(P_h);\n     \n    \n}\n\n\n\n\nint main(int argc, char** argv){\n\n    ros::init(argc,argv,\"KalmanFilter\");\n    ros::NodeHandle nh;\n    //Initializinging the parameters\n    Initialize(nh);\n  \n    //Subscriber and Publisher for the data. remapped in the launch file to the topic required\n    ros::Subscriber Imu=nh.subscribe(\"imu\",100,prediction_step);\n    ros::Subscriber anchor_1 = nh.subscribe(\"anchor_1\",10,anchor1_cb);\n    ros::Subscriber anchor_2 = nh.subscribe(\"anchor_2\",10,anchor2_cb);\n    ros::Subscriber anchor_3 = nh.subscribe(\"anchor_3\",10,anchor3_cb);\n    ros::Subscriber anchor_4 = nh.subscribe(\"anchor_4\",10,anchor4_cb);\n    // ros::Subscriber anchor_5 = nh.subscribe(\"anchor_5\",10,anchor5_cb);\n    // ros::Subscriber anchor_6 = nh.subscribe(\"anchor_6\",10,anchor6_cb);\n    ros::Subscriber height_sb = nh.subscribe(\"height\",10,height_cb);\n    ros::Subscriber velocity_sb = nh.subscribe(\"velocity\",10,correction_step_vel);\n\n    ros::Publisher fused = nh.advertise<std_msgs::Float32MultiArray>(\"Filtered_data\", 100);\n    ros::Publisher fused_pose = nh.advertise<geometry_msgs::PoseStamped>(\"Filtered_pose\", 10);\n    \n    ros::Rate loop_rate(50);\n    while(ros::ok()){\n        //param(nh);\n  //    output.data.clear();\n        // for (int i = 0; i < 9; i++)\n        //  output.data.push_back(X(i));\n        \n        pose.header.stamp = ros::Time::now();\n        pose.header.frame_id = \"base\";\n\n        pose.pose.position.x=X(0)+trans_x;\n        pose.pose.position.y=X(3)+trans_y;\n        pose.pose.position.z=X(6);\n        pose.pose.orientation = imu_msg.pose.orientation;\n\n        \n        //q_ = Eigen::AngleAxisf(rpy(0,0), Eigen::Vector3f::UnitX())*Eigen::AngleAxisf(rpy(1,0), Eigen::Vector3f::UnitY())*Eigen::AngleAxisf(yaw, Eigen::Vector3f::UnitZ());\n        \n        // pose.pose.orientation.w = q_.w();\n        // pose.pose.orientation.x = q_.x();\n        // pose.pose.orientation.y = q_.y();\n        // pose.pose.orientation.z = q_.z();\n        //fused.publish(output);\n        fused_pose.publish(pose);\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n    return 0;\n}       \n\n", "meta": {"hexsha": "be40132a4e2c08b64654677aa8f3e04b0b7a2be1", "size": 16870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gazebo_sim/gps_denied/src/ekf.cpp", "max_stars_repo_name": "naveenbiitk/State_Estimation", "max_stars_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-05T06:19:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-05T06:19:20.000Z", "max_issues_repo_path": "gazebo_sim/gps_denied/src/ekf.cpp", "max_issues_repo_name": "naveenbiitk/State_Estimation", "max_issues_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gazebo_sim/gps_denied/src/ekf.cpp", "max_forks_repo_name": "naveenbiitk/State_Estimation", "max_forks_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_forks_repo_licenses": ["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.5615942029, "max_line_length": 172, "alphanum_fraction": 0.6069946651, "num_tokens": 5373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5040014380042014}}
{"text": "// Copyright (c) 2020 fortiss GmbH\n//\n// Authors: Julian Bernhard, Klemens Esterle, Patrick Hart and\n// 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 BARK_MODELS_EXECUTION_MPC_COST_FUNCTOR_HPP_\n#define BARK_MODELS_EXECUTION_MPC_COST_FUNCTOR_HPP_\n\n#include <Eigen/Dense>\n#include <iostream>\n#include \"bark/models/execution/mpc/common.hpp\"\n\nnamespace bark {\nnamespace models {\nnamespace execution {\nusing namespace bark::models::dynamic;\n\ntemplate <typename T>\ninline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> KinematicModel(\n    T const* const* parameters,\n    bark::models::dynamic::Trajectory desired_trajectory,\n    const OptimizationSettings& optimization_settings) {\n  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> traj =\n      desired_trajectory.cast<T>();\n\n  // TODO: Lf als Parameter\n  T Lf = T(2.6);\n\n  for (int i = 1; i < optimization_settings.num_optimization_steps; i++) {\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> f_dot(1, 5);\n\n    // fill matrix\n    f_dot << T(1),  // (0) t' = 1\n        traj(i - 1, StateDefinition::VEL_POSITION) *\n            cos(traj(\n                i - 1,\n                StateDefinition::THETA_POSITION)),  // (1) x_dot = v*cos(psi)\n        traj(i - 1, StateDefinition::VEL_POSITION) *\n            sin(traj(\n                i - 1,\n                StateDefinition::THETA_POSITION)),  // (2) y_dot = v*sin(psi)\n        tan(parameters[1][i - 1]) / Lf,  // (3) theta_dot = tan(delta)/Lf\n        parameters[0][i - 1];            // (4) v_dot = a\n\n    traj.block(i, 0, 1, 5) =\n        traj.block(i - 1, 0, 1, 5) + T(optimization_settings.dt) * f_dot;\n  }\n  return traj;\n}\n\nstruct CostFunctor {\n  template <typename T>\n  bool operator()(T const* const* parameters, T* residual) {\n    // initialize\n    T cost = T(0.0);\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> traj = KinematicModel(\n        parameters, desired_discrete_states_, optimization_settings_);\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> desired_discrete_states =\n        desired_discrete_states_.cast<T>();\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> weights =\n        weights_.cast<T>();\n\n    // offsets\n    for (int i = 0; i < optimization_settings_.num_optimization_steps - 1;\n         i++) {\n      T xDiff, yDiff, thetaDiff, velDiff;\n      xDiff = traj(i, StateDefinition::X_POSITION) -\n              desired_discrete_states(i, StateDefinition::X_POSITION);\n      yDiff = traj(i, StateDefinition::Y_POSITION) -\n              desired_discrete_states(i, StateDefinition::Y_POSITION);\n      thetaDiff = traj(i, StateDefinition::THETA_POSITION) -\n                  desired_discrete_states(i, StateDefinition::THETA_POSITION);\n      velDiff = traj(i, StateDefinition::VEL_POSITION) -\n                desired_discrete_states(i, StateDefinition::VEL_POSITION);\n\n      cost += weights(i, StateDefinition::X_POSITION) * xDiff * xDiff;\n      cost += weights(i, StateDefinition::Y_POSITION) * yDiff * yDiff;\n      cost +=\n          weights(i, StateDefinition::THETA_POSITION) * thetaDiff * thetaDiff;\n      cost += weights(i, StateDefinition::VEL_POSITION) * velDiff * velDiff;\n    }\n\n    // differential values\n    // TODO(@all): seperate weights\n    T weights_acc = T(1e1);\n    T weights_delta = T(1);\n    for (int i = 0; i < optimization_settings_.num_optimization_steps - 1;\n         i++) {\n      cost +=\n          weights_acc * parameters[0][i] * parameters[0][i];  // acceleration\n      cost += weights_delta * parameters[1][i] * parameters[1][i];  // steering\n    }\n\n    residual[0] = cost / (weights.sum() +\n                          (weights_acc + weights_delta) *\n                              T(optimization_settings_.num_optimization_steps));\n    return true;\n  }\n\n  bool set_desired_states(\n      const bark::models::dynamic::Trajectory& desired_states) {\n    desired_discrete_states_ = desired_states;\n    return true;\n  }\n\n  bool set_optimization_settings(\n      const OptimizationSettings& optimization_settings) {\n    optimization_settings_ = optimization_settings;\n    return true;\n  }\n\n  bool set_weights(\n      const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> weights) {\n    weights_ = weights;\n    return true;\n  }\n\n  bark::models::dynamic::Trajectory desired_discrete_states_;\n  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> weights_;\n  OptimizationSettings optimization_settings_;\n};\n\n}  // namespace execution\n}  // namespace models\n}  // namespace bark\n\n#endif  // BARK_MODELS_EXECUTION_MPC_COST_FUNCTOR_HPP_\n", "meta": {"hexsha": "d5d2e582b0e0dbf74005dfd7838bba1fef830053", "size": 4587, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bark/models/execution/mpc/cost_functor.hpp", "max_stars_repo_name": "RdecKa/bark", "max_stars_repo_head_hexsha": "4aa4c901417e3a2c97050894ec61fcb57cc94e6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 174.0, "max_stars_repo_stars_event_min_datetime": "2019-04-03T11:37:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T09:14:38.000Z", "max_issues_repo_path": "bark/models/execution/mpc/cost_functor.hpp", "max_issues_repo_name": "RdecKa/bark", "max_issues_repo_head_hexsha": "4aa4c901417e3a2c97050894ec61fcb57cc94e6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 192.0, "max_issues_repo_issues_event_min_datetime": "2019-04-05T09:41:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T14:14:28.000Z", "max_forks_repo_path": "bark/models/execution/mpc/cost_functor.hpp", "max_forks_repo_name": "RdecKa/bark", "max_forks_repo_head_hexsha": "4aa4c901417e3a2c97050894ec61fcb57cc94e6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2019-04-05T13:22:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T07:03:41.000Z", "avg_line_length": 35.0152671756, "max_line_length": 80, "alphanum_fraction": 0.6533682145, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5040014380042014}}
{"text": "/*  _______________________________________________________________________\n\n    PECOS: Parallel Environment for Creation Of Stochastics\n    Copyright (c) 2011, Sandia National Laboratories.\n    This software is distributed under the GNU Lesser General Public License.\n    For more information, see the README file in the top Pecos directory.\n    _______________________________________________________________________ */\n\n//- Class:\t RandomVariable\n//- Description: \n//- Owner:       Mike Eldred\n//- Revised by:  \n//- Version:\n\n#ifndef RANDOM_VARIABLE_HPP\n#define RANDOM_VARIABLE_HPP\n\n#include \"pecos_data_types.hpp\"\n#include <boost/math/distributions.hpp>\n#include <boost/math/special_functions/sqrt1pm1.hpp> // includes expm1,log1p\n\nnamespace bmth = boost::math;\nnamespace bmp  = bmth::policies;\n\n\nnamespace Pecos {\n\n// -----------------------------------\n// Non-default boost math/policy types\n// -----------------------------------\n\n// continuous random variable types:\ntypedef bmth::\n  normal_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  normal_dist;\ntypedef bmth::\n  lognormal_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  lognormal_dist;\ntypedef bmth::\n  triangular_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  triangular_dist;\ntypedef bmth::\n  exponential_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  exponential_dist;\ntypedef bmth::\n  beta_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  beta_dist;\ntypedef bmth::\n  gamma_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  gamma_dist;\ntypedef bmth::\n  inverse_gamma_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  inv_gamma_dist;\ntypedef bmth::\n  extreme_value_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  extreme_value_dist;\ntypedef bmth::\n  weibull_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  weibull_dist;\n// discrete random variable types:\ntypedef bmth::\n  poisson_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  poisson_dist;\ntypedef bmth::\n  binomial_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  binomial_dist;\ntypedef bmth::\n  negative_binomial_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  negative_binomial_dist;\ntypedef bmth::\n  geometric_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  geometric_dist;\ntypedef bmth::\n  hypergeometric_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  hypergeometric_dist;\n// distributions used in statistical utilities (e.g., confidence intervals):\ntypedef bmth::\n  chi_squared_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  chi_squared_dist;\ntypedef bmth::\n  students_t_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  students_t_dist;\ntypedef bmth::\n  fisher_f_distribution< Real,\n                       bmp::policy< bmp::overflow_error<bmp::ignore_error> > >\n  fisher_f_dist;\n\n\n/// base class for random variable hierarchy\n\n/** This class enables cdf(), ccdf(), inverse_cdf(), inverse_ccdf(),\n    pdf(), pdf_gradient(), pdf_hessian(), and related random variable\n    utilities from contained distribution parameters. */\n\n// ExtremeValueBase: Gumbel, Frechet, Weibull -> alpha, beta, no bounds\n// EmpiricalBase: histogram bin, KDE, ...\n\nclass RandomVariable\n{\npublic:\n\n  //\n  //- Heading: Constructors, destructor, and operator=\n  //\n\n  /// default constructor\n  RandomVariable();\n  /// standard constructor for envelope\n  RandomVariable(short ran_var_type);\n  /// copy constructor\n  RandomVariable(const RandomVariable& ran_var);\n\n  /// destructor\n  virtual ~RandomVariable();\n\n  /// assignment operator\n  RandomVariable operator=(const RandomVariable& ran_var);\n\n  //\n  //- Heading: Virtual functions\n  //\n\n  /// return the cumulative distribution function value of the random\n  /// variable at x\n  virtual Real cdf(Real x) const;\n  /// return the x value corresponding to a cumulative probability\n  virtual Real inverse_cdf(Real p_cdf) const;\n\n  /// return the complementary cumulative distribution function value\n  /// of the random variable at x\n  virtual Real ccdf(Real x) const;\n  /// return the x value corresponding to a complementary cumulative probability\n  virtual Real inverse_ccdf(Real p_ccdf) const;\n\n  /// return the value of the random variable's probability density\n  /// function at x\n  virtual Real pdf(Real x) const;\n  /// return the gradient of the random variable's probability density\n  /// function at x\n  virtual Real pdf_gradient(Real x) const;\n  /// return the hessian of the random variable's probability density\n  /// function at x\n  virtual Real pdf_hessian(Real x) const;\n  /// return the value of the natural log of the random variable's probability\n  /// density function at x (useful for calculations of log density in Bayesian\n  /// methods)\n  virtual Real log_pdf(Real x) const;\n  /// return the gradient of the natural log of the random variable's\n  /// probability density function at x (useful for defining MCMC proposal\n  /// distributions in Bayesian methods)\n  virtual Real log_pdf_gradient(Real x) const;\n  /// return the Hessian of the natural log of the random variable's probability\n  /// density function at x (useful for defining MCMC proposal distributions in\n  /// Bayesian methods)\n  virtual Real log_pdf_hessian(Real x) const;\n\n  /// return the value of a standardized random variable's probability density\n  /// function at x\n  virtual Real standard_pdf(Real z) const;\n  /// return the natural log of a standardized random variable's probability\n  /// density function at x (useful for calculations of log density in\n  /// Bayesian methods)\n  virtual Real log_standard_pdf(Real z) const;\n  /// return the gradient of the natural log of a standardized random\n  /// variable's probability density function at x (useful for\n  /// calculations of log density in Bayesian methods)\n  virtual Real log_standard_pdf_gradient(Real z) const;\n  /// return the Hessian of the natural log of a standardized random\n  /// variable's probability density function at x (useful for\n  /// calculations of log density in Bayesian methods)\n  virtual Real log_standard_pdf_hessian(Real z) const;\n\n  /// scale variable value x from current to standardized distribution\n  virtual Real to_standard(Real x) const;\n  /// scale variable value z from standardized to current distribution\n  virtual Real from_standard(Real z) const;\n\n  /// return the value of the named distribution parameter\n  virtual Real parameter(short dist_param) const;\n  /// update the value of the named distribution parameter\n  virtual void parameter(short dist_param, Real val);\n\n  /// return the distribution mean\n  virtual Real mean() const;\n  /// return the distribution mode\n  virtual Real median() const;\n  /// return the distribution mode\n  virtual Real mode() const;\n  /// return the distribution variance\n  virtual Real standard_deviation() const;\n  /// return the distribution variance\n  virtual Real variance() const;\n\n  /// return the distribution mean and standard deviation as a pair\n  /** default is only overridden when more efficient to compute together */\n  virtual RealRealPair moments() const;\n  /// return the distribution lower and upper bounds as a pair\n  virtual RealRealPair bounds() const;\n\n  /// compute the coefficient of variation (used to compute selected\n  /// correlation warping factors); defined for semi-infinite distributions\n  /// with nonzero mean (lognormal, exponential, gamma, frechet, weibull)\n  /** default is only overridden when more efficient to compute together */\n  virtual Real coefficient_of_variation() const;\n  /// compute the warping factor for correlation between the current\n  /// variable and the one passed in (used in NatafTransformation)\n  virtual Real correlation_warping_factor(const RandomVariable& rv,\n\t\t\t\t\t  Real corr) const;\n\n  /// compute the design Jacobian from differentiating the X->Z mapping with\n  /// respect to the distibution parameter s\n  virtual Real dx_ds(short dist_param, short u_type, Real x, Real z) const;\n  /// compute the mapping-specific factor that is multiplied by dz/ds for\n  /// contributions to the dx/ds design Jacobian in the case of correlated\n  /// random variables (dz/ds is evaluated numerically and multiplied by\n  /// this analytic factor)\n  virtual Real dz_ds_factor(short u_type, Real x, Real z) const;\n\n  //\n  //- Heading: Member functions\n  //\n\n  /// set ranVarType\n  void type(short ran_var_type);\n  /// get ranVarType\n  short type() const;\n\n  /// returns ranVarRep for access to derived class member functions\n  /// that are not mapped to the base level\n  RandomVariable* random_variable_rep() const;\n\nprotected:\n\n  //\n  //- Heading: Constructors\n  //\n\n  /// constructor initializes the base class part of letter classes\n  /// (BaseConstructor overloading avoids infinite recursion in the\n  /// derived class constructors - Coplien, p. 139)\n  RandomVariable(BaseConstructor);\n\n  //\n  //- Heading: Member functions\n  //\n\n  //\n  //- Heading: Data\n  //\n\n  /// enumeration value indicating type of random variable\n  short ranVarType;\n\nprivate:\n\n  //\n  //- Heading: Member functions\n  //\n\n  /// Used only by the standard envelope constructor to initialize\n  /// ranVarRep to the appropriate derived type.\n  RandomVariable* get_random_variable(short ran_var_type);\n\n  //\n  //- Heading: Data members\n  //\n\n  /// pointer to the letter (initialized only for the envelope)\n  RandomVariable* ranVarRep;\n  /// number of objects sharing ranVarRep\n  int referenceCount;\n};\n\n\ninline void RandomVariable::type(short ran_var_type)\n{\n  if (ranVarRep) ranVarRep->ranVarType = ran_var_type;\n  else           ranVarType = ran_var_type;\n}\n\n\ninline short RandomVariable::type() const\n{ return (ranVarRep) ? ranVarRep->ranVarType : ranVarType; }\n\n\ninline RandomVariable* RandomVariable::random_variable_rep() const\n{ return ranVarRep; }\n\n} // namespace Pecos\n\n#endif\n", "meta": {"hexsha": "dc13e274d6c549b2f3609dc3ffc6cf8ac207467e", "size": 10520, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dakota-6.3.0.Windows.x86/include/RandomVariable.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/RandomVariable.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/RandomVariable.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": 34.1558441558, "max_line_length": 80, "alphanum_fraction": 0.7132129278, "num_tokens": 2309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5040014293434997}}
{"text": "/**\n* @Author: Marcel Ruhf <marcelruhf>\n* @Email:  m.ruhf@protonmail.ch\n* @Project: SoccerRL\n* @Filename: Functions.cpp\n* @License: Licensed under the Apache 2.0 license (see LICENSE.md)\n* @Copyright: Copyright (c) 2017 Marcel Ruhf\n*/\n\n#include <cmath>\n#include <string>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/optional.hpp>\n#include <opencv2/opencv.hpp>\n#include <MarkerFinder.hpp>\n#include <RobotTracker.hpp>\n#include <BallTracker.hpp>\n#include <Constants.hpp>\n#include <Functions.hpp>\n\nnamespace mr\n{\n    template <typename T>\n    int signum(T val) {\n        return (T(0) < val) - (val < T(0));\n    }\n\n    double distEuclidPixels(cv::Point2f p1, cv::Point2f p2)\n    {\n        return std::sqrt(std::pow(p2.x - p1.x, 2) + std::pow(p2.y - p1.y, 2));\n    }\n\n    double distEuclidMM(cv::Point2f p1, cv::Point2f p2)\n    {\n        double distPx = distEuclidPixels(p1, p2);\n        return (distPx / PIXELS_PER_MM);\n    }\n\n    boost::optional<cv::Point2f> initialize_goal_centre(const cv::Mat& frame)\n    {\n        MarkerFinder marker;\n        marker.preprocess(frame);\n        boost::optional<std::vector<cv::Point2f>> goalCentreCorners = marker.getCorners(GOAL_CENTRE_MARKER_ID);\n        if (goalCentreCorners)\n        {\n            cv::Moments mu = cv::moments(*goalCentreCorners, true);\n            return cv::Point2f(mu.m10/mu.m00, mu.m01/mu.m00);\n        }\n        return boost::optional<cv::Point2f>{};\n    }\n\n    void get_vars(int vars_array[4], const cv::Mat& src, RobotTracker& robot, BallTracker& ball)\n    {\n        //double len1 = std::hypot(robot_centroid.x, robot_centroid.y);\n        //double len2 = std::hypot(ball_centroid.x, ball_centroid.y);\n        //double dot = robot_centroid.ddot(ball_centroid);\n        //double a = dot/(len1*len2);\n        //double arb = acos(a) / (180 * 3.141592653589793);\n        //root.add(\"arb\", arb);\n\n        // Determine distance between robot and ball in terms of the X axis\n        robot.preprocess(src);\n        ball.setImage(src);\n        boost::optional<cv::Point2f> robot_centroid = robot.getCentrePoint();\n        boost::optional<cv::Point2f> ball_centroid = ball.getCentrePoint();\n        int ball_velocity = ball.getVelocity();\n        if (!ball_centroid || !robot_centroid)\n        {\n            vars_array = {0};\n        }\n        else\n        {\n            double drbx     = (ball_centroid->x - robot_centroid->x) / PIXELS_PER_MM;\n            vars_array[0]   = static_cast<int>(std::round(drbx));\n            vars_array[1]   = static_cast<int>(std::round(ball_velocity));\n            vars_array[2]   = static_cast<int>(std::round(ball_centroid->x));\n            vars_array[3]   = static_cast<int>(std::round(ball_centroid->y));\n        }\n    }\n}", "meta": {"hexsha": "3af1c2b98d615dad653eaec893734414bc187b8c", "size": 2767, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tracker/src/Functions.cpp", "max_stars_repo_name": "marcelruhf/SoccerRL", "max_stars_repo_head_hexsha": "afc9dcacf97ee2f3cc959329bd01d3f7fd815397", "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": "Tracker/src/Functions.cpp", "max_issues_repo_name": "marcelruhf/SoccerRL", "max_issues_repo_head_hexsha": "afc9dcacf97ee2f3cc959329bd01d3f7fd815397", "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": "Tracker/src/Functions.cpp", "max_forks_repo_name": "marcelruhf/SoccerRL", "max_forks_repo_head_hexsha": "afc9dcacf97ee2f3cc959329bd01d3f7fd815397", "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.1604938272, "max_line_length": 111, "alphanum_fraction": 0.6223346585, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5039985570867598}}
{"text": "#include <boost/math/special_functions/legendre.hpp>\n", "meta": {"hexsha": "14a4adf2e10e1ab71205c3dc8b0393dced68ad7a", "size": 53, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_legendre.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_legendre.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_legendre.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.5, "max_line_length": 52, "alphanum_fraction": 0.8301886792, "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5039985522722633}}
{"text": "#include <iostream>\n#include <complex>\n#include <cmath>\n#include <Eigen/Dense>\n#include \"mex.h\"\n#include <unsupported/Eigen/MatrixFunctions>\n#include <vector>\n\ntypedef Eigen::Matrix<double, 2, 5> Matrix2x5d;\ntypedef Eigen::Matrix<double, 5, 5> Matrix5d;\n\nMatrix5d F;\nMatrix5d V;\nMatrix2x5d J;\n\nstd::complex<double> dmdT1;\nstd::complex<double> dmdT2;\nstd::complex<double> dmdM0;\nstd::complex<double> dmdB0;\nstd::complex<double> dmdP0;\nconst std::complex<double> i1(0.0, 1.0);\nconst double PI = 3.14159265358979323846;\nEigen::Matrix4d Rz; \nEigen::Matrix4d dRz;\nEigen::Matrix4d Rx; \nEigen::Matrix4d E; \nEigen::Matrix4d dEdT1; \nEigen::Matrix4d dEdT2; \nEigen::Matrix4d dEdM0;\n\n\nvoid update_Rz(double p);\n\nvoid update_dRz(double p, double dp);\n\nvoid update_Rx(double a);\n\nvoid update_E(double R1, double R2, double TR, double M0);\n\nvoid update_dEdT1(double R1, double TR, double M0);\n\nvoid update_dEdT2(double R2, double TR);\n\nvoid update_dEdM0(double R1, double TR);\n\nvoid add2FIM();\n\n\n//Main Function that generates the EPG states given the acquisition parameters\nvoid mex_isochromat_CRLB_theta(double *signal_real, double *signal_imag, double *dmdT1_real, double *dmdT1_imag, double *dmdT2_real, double *dmdT2_imag, double *Mz, double *rCRLB, double *N, double *theta, double *RF, double *TRssfp, double *T1, double *T2, double *M0, double *B0, double *phi0)\n{\n\n    double R1 = 1 / T1[0];\n\tdouble R2 = 1 / T2[0];\n\n\tint length = (int) N[0];\n\n    ///// MEMORY ALLOCATION AND INITIALIZATION\t\n    // signal vectors\n    Eigen::Vector4d Mplus(0, 0, 0, 1);  //Magnetization vector after the RF excitation\n    Eigen::Vector4d Mminus(0, 0, 0, 1); //Magnetization vector before the RF excitation\n    Mminus(2) = M0[0];\n\n    Eigen::VectorXd aux_FA(length);\n    aux_FA.setZero();\n    Eigen::VectorXd TR(length);\n    TR.setOnes();\n    TR *= TRssfp[0];\n    Eigen::VectorXd TE(length);\n    TE.setOnes();\n    TE *= TRssfp[0]/2.0;\n    \n    // rotation and relaxation matrices\n    Rz.setZero(); \n    Rz(2,2) = 1;\n    Rz(3,3) = 1;\n    \n    Rx.setZero(); \n    Rx(0,0) = 1;\n    Rx(3,3) = 1;\n    \n    E.setZero();\n    E(3,3) = 1;\n    dEdT1.setZero();\n    dEdT2.setZero();\n    dEdM0.setZero();\n    \n    // for CRLB calculation\n    F.setZero();\n    \n    Eigen::Vector4d Mplus_dOdT1(0, 0, 0, 0);\n    Eigen::Vector4d Mminus_dOdT1(0, 0, 0, 0);\n    Eigen::Vector4d Mplus_dOdT2(0, 0, 0, 0);\n    Eigen::Vector4d Mminus_dOdT2(0, 0, 0, 0);\n    Eigen::Vector4d Mplus_dOdM0(0, 0, 0, 0);\n    Eigen::Vector4d Mminus_dOdM0(0, 0, 0, 0);\n    Mminus_dOdM0(2) = M0[0];\n    Eigen::Vector4d Mplus_dOdB0(0, 0, 0, 0);\n    Eigen::Vector4d Mminus_dOdB0(0, 0, 0, 0);\n    Eigen::Vector4d Mplus_dOdP0(0, 0, 0, 0);\n    Eigen::Vector4d Mminus_dOdP0(0, 0, 0, 0);  \n \n    double FPangle;\n         \n    /////ISOCHROMAT DYNAMICS SIMULATION\n    for (int j=0; j<length; j++){\n\n        //transformation from theta to alpha\n        if (j==0) {aux_FA(j) = theta[j];}\n        else {aux_FA(j) = theta[j] + theta[j-1];}\n\n        //apply rotations\n        update_Rz(-RF[j]); update_Rx(aux_FA(j));\n        Mplus = Rx * Rz * Mminus; \n        Mplus_dOdT1 = Rx * Rz * Mminus_dOdT1; \n        Mplus_dOdT2 = Rx * Rz * Mminus_dOdT2; \n        Mplus_dOdM0 = Rx * Rz * Mminus_dOdM0;\n        Mplus_dOdB0 = Rx * Rz * Mminus_dOdB0;\n        Mplus_dOdP0 = Rx * Rz * Mminus_dOdP0;\n        update_Rz(RF[j]);\n        Mplus = Rz * Mplus;\n        Mplus_dOdT1 = Rz * Mplus_dOdT1; \n        Mplus_dOdT2 = Rz * Mplus_dOdT2; \n        Mplus_dOdM0 = Rz * Mplus_dOdM0;      \n        Mplus_dOdB0 = Rz * Mplus_dOdB0;\n        Mplus_dOdP0 = Rz * Mplus_dOdP0;\n\n        //CRLB calculation\n        FPangle = 2*PI*B0[0] * TE(j) * pow(10.0,-3.0);\n        update_Rz(FPangle + phi0[0]);\n        Mminus       = Rz * Mplus;\n        Mminus_dOdT1 = Rz * Mplus_dOdT1; \n        Mminus_dOdT2 = Rz * Mplus_dOdT2; \n        Mminus_dOdM0 = Rz * Mplus_dOdM0;       \n        \n        update_dRz(FPangle + phi0[0], 2*PI*TE(j)*pow(10.0,-3.0) );       \n        Mminus_dOdB0 = dRz * Mplus + Rz * Mplus_dOdB0;\n        \n        update_dRz(FPangle + phi0[0], 1.0);\n        Mminus_dOdP0 = dRz * Mplus + Rz * Mplus_dOdP0;\n        \n        dmdT1 = exp(-R2 * TE(j)) * (Mminus_dOdT1(0) + i1*Mminus_dOdT1(1)); \n        dmdT2 = TE(j) * exp(-R2 * TE(j)) * pow(R2,2) * (Mminus(0) + i1*Mminus(1)) + exp(-R2 * TE(j)) * (Mminus_dOdT2(0) + i1*Mminus_dOdT2(1));\n        dmdM0 = exp(-R2 * TE(j)) * (Mminus_dOdM0(0) + i1*Mminus_dOdM0(1));\n        dmdB0 = exp(-R2 * TE(j)) * (Mminus_dOdB0(0) + i1*Mminus_dOdB0(1)); \n        dmdP0 = exp(-R2 * TE(j)) * (Mminus_dOdP0(0) + i1*Mminus_dOdP0(1));\n        \n        add2FIM(); \n\n        signal_real[j] = exp(-R2 * TE(j)) * Mminus(0);\n        signal_imag[j] = exp(-R2 * TE(j)) * Mminus(1);\n        dmdT1_real[j]  = dmdT1.real();\n        dmdT1_imag[j]  = dmdT1.imag();\n        dmdT2_real[j]  = dmdT2.real();\n        dmdT2_imag[j]  = dmdT2.imag();\n        Mz[j] = Mminus(2) * exp(-R1 * TR(j)) + (1 - exp(-R1 * TR(j))) * std::abs(M0[0]);\n\n        //apply relaxation\n        update_E(R1, R2, TR(j), std::abs(M0[0]));\n    \tupdate_dEdT1(R1, TR(j), std::abs(M0[0]));\n        update_dEdT2(R2, TR(j));\n        update_dEdM0(R1, TR(j));\n        Mminus = E * Mplus;\n        Mminus_dOdT1 = E * Mplus_dOdT1 + dEdT1 * Mplus;\n        Mminus_dOdT2 = E * Mplus_dOdT2 + dEdT2 * Mplus;\n        Mminus_dOdM0 = E * Mplus_dOdM0 + dEdM0 * Mplus;\n        Mminus_dOdB0 = E * Mplus_dOdB0;\n        Mminus_dOdP0 = E * Mplus_dOdP0;\n\n        //apply rotation due to free precession\n        FPangle = 2*PI*B0[0] * TR(j) * pow(10.0,-3.0);\n        update_Rz(FPangle);\n        update_dRz(FPangle, 2*PI*TR(j)*pow(10.0,-3.0) );\n        Mminus = Rz * Mminus;\n        Mminus_dOdT1 = Rz * Mminus_dOdT1; \n        Mminus_dOdT2 = Rz * Mminus_dOdT2; \n        Mminus_dOdM0 = Rz * Mminus_dOdM0;       \n        Mminus_dOdB0 = dRz * E * Mplus + Rz * Mminus_dOdB0;\n        Mminus_dOdP0 = Rz * Mminus_dOdP0;\n\n}\n\n    V = F.inverse();\n    rCRLB[0] = V(0,0);\n    rCRLB[1] = V(1,1);\n    rCRLB[2] = V(2,2);\n    rCRLB[3] = V(3,3);\n    rCRLB[4] = V(4,4);\n}\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n    /* Declare arrays necessary to compute signals */ \n    double *N;         //units []\n    double *theta;     //units [rad]\n    double *RF;        //units [rad]\n    double *TRssfp;    //units [ms]\n    double *T1;        //units [ms]\n    double *T2;        //units [ms]\n    double *M0;        //a.u.\n    double *B0;        //units [Hz]\n    double *phi0;      //units [rad]\n\n    double *signal_real;\n    double *signal_imag;\n    double *dmdT1_real;\n    double *dmdT1_imag;   \n    double *dmdT2_real;\n    double *dmdT2_imag;     \n    double *Mz;\n    double *rCRLB;\n\n    /* Check for proper number of arguments */\n        \n    /* Create pointers to the inputs */\n    N      = mxGetPr(prhs[0]);\n    theta  = mxGetPr(prhs[1]); \n    RF     = mxGetPr(prhs[2]); \n    TRssfp = mxGetPr(prhs[3]);\n    T1     = mxGetPr(prhs[4]); \n    T2     = mxGetPr(prhs[5]);\n    M0     = mxGetPr(prhs[6]);\n    B0     = mxGetPr(prhs[7]);\n    phi0   = mxGetPr(prhs[8]);\n\n    /* Create pointers to the outputs */\n    plhs[0] = mxCreateDoubleMatrix((mwSize)*N, 1, mxCOMPLEX);\n    plhs[1] = mxCreateDoubleMatrix((mwSize)*N, 1, mxCOMPLEX);    \n    plhs[2] = mxCreateDoubleMatrix((mwSize)*N, 1, mxCOMPLEX);\n    plhs[3] = mxCreateDoubleMatrix((mwSize)*N, 1, mxREAL);\n    plhs[4] = mxCreateDoubleMatrix(1, 5, mxREAL);\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    dmdT1_real  = mxGetPr(plhs[1]);\n    dmdT1_imag  = mxGetPi(plhs[1]);\n    dmdT2_real  = mxGetPr(plhs[2]);\n    dmdT2_imag  = mxGetPi(plhs[2]);\n    Mz          = mxGetPr(plhs[3]);\n    rCRLB       = mxGetPr(plhs[4]);\n       \n    /* Call the computational routine */\n    mex_isochromat_CRLB_theta(signal_real, signal_imag, dmdT1_real, dmdT1_imag, dmdT2_real, dmdT2_imag, Mz, rCRLB, N, theta, RF, TRssfp, T1, T2, M0, B0, phi0);\n\n}\n\n/////AUXILIAR FUNCTIONS\n//Update augmented rotation matrix around z-axis\nvoid update_Rz(double p)\n{\n    Rz(0,0) = cos(p);\n    Rz(0,1) = -sin(p);\n    Rz(1,0) = sin(p);\n    Rz(1,1) = cos(p);\n}\n\n//Update derivative of the augmented rotation matrix around z-axis\nvoid update_dRz(double p, double dp)\n{\n    dRz(0,0) = -dp * sin(p);\n    dRz(0,1) = -dp * cos(p);\n    dRz(1,0) =  dp * cos(p);\n    dRz(1,1) = -dp * sin(p);\n}\n\n//Update augmented rotation matrix around x-axis\nvoid update_Rx(double a)\n{\n    Rx(1,1) = cos(a);\n    Rx(1,2) = sin(a);\n    Rx(2,1) = -sin(a);\n    Rx(2,2) = cos(a);\n}\n\n//Update augmented relaxation matrix and its derivatives\nvoid update_E(double R1, double R2, double TR, double M0)\n{\n\tE(0,0) = exp(-R2 * TR);\n\tE(1,1) = exp(-R2 * TR);\n\tE(2,2) = exp(-R1 * TR);\n\tE(2,3) = (1 - exp(-R1 * TR)) * M0;\n}\n\nvoid update_dEdT1(double R1, double TR, double M0)\n{\n    dEdT1(2,2) = TR * exp(-R1 * TR) * pow(R1,2.0);\n    dEdT1(2,3) = -dEdT1(2,2) * M0;\n}\n\nvoid update_dEdT2(double R2, double TR)\n{\n    dEdT2(0,0) = TR * exp(-R2 * TR) * pow(R2,2.0);\n    dEdT2(1,1) = dEdT2(0,0);\n}\n\nvoid update_dEdM0(double R1, double TR)\n{\n    dEdM0(2,3) = 1 - exp(-R1 * TR);\n}\n\n//Update Fisher Information Matrix\nvoid add2FIM()\n{\n    J(0,0) = dmdT1.real();\n    J(1,0) = dmdT1.imag();\n    J(0,1) = dmdT2.real();\n    J(1,1) = dmdT2.imag(); \n    J(0,2) = dmdM0.real();\n    J(1,2) = dmdM0.imag();  \n    J(0,3) = dmdB0.real();\n    J(1,3) = dmdB0.imag();\n    J(0,4) = dmdP0.real();\n    J(1,4) = dmdP0.imag();\n    F += J.transpose() * J;\n}\n\n\n\n\n\n", "meta": {"hexsha": "d7274b99fd42f00c505231632c9e6997cf381ae3", "size": 9527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "library/cppAnalysis_acq_set_balancedMRF.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/cppAnalysis_acq_set_balancedMRF.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/cppAnalysis_acq_set_balancedMRF.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": 29.4043209877, "max_line_length": 295, "alphanum_fraction": 0.5801406529, "num_tokens": 3744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5039985522722633}}
{"text": "/**\n* This file is part of CubeSLAM\n*\n* Copyright (C) 2018  Shichao Yang (Carnegie Mellon Univ)\n*/\n\n#include \"Thirdparty/g2o/g2o/types/types_six_dof_expmap.h\"\n#include \"detect_3d_cuboid/matrix_utils.h\"\n\n#include \"g2o_Object.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <math.h>\n#include <algorithm> // std::swap\n\nnamespace g2o\n{\n\nusing namespace Eigen;\nusing namespace std;\n\nSE3Quat exptwist_norollpitch(const Vector6d &update)\n{\n    Vector3d omega;\n    for (int i = 0; i < 3; i++)\n        omega[i] = update[i];\n    Vector3d upsilon;\n    for (int i = 0; i < 3; i++)\n        upsilon[i] = update[i + 3];\n\n    double theta = omega.norm();\n    Matrix3d Omega = skew(omega);\n\n    Matrix3d R;\n    R << cos(omega(2)), -sin(omega(2)), 0,\n        sin(omega(2)), cos(omega(2)), 0,\n        0, 0, 1;\n\n    Matrix3d V;\n    if (theta < 0.00001)\n    {\n        V = R;\n    }\n    else\n    {\n        Matrix3d Omega2 = Omega * Omega;\n\n        V = (Matrix3d::Identity() + (1 - cos(theta)) / (theta * theta) * Omega + (theta - sin(theta)) / (pow(theta, 3)) * Omega2);\n    }\n\n    return SE3Quat(Quaterniond(R), V * upsilon);\n}\n\nvoid VertexCuboid::oplusImpl(const double *update_)\n{\n    Eigen::Map<const Vector9d> update(update_);\n\n    g2o::cuboid newcube;\n    if (whether_fixrotation)\n    {\n        newcube.pose.setTranslation(_estimate.pose.translation() + update.segment<3>(3));\n    }\n    else if (whether_fixrollpitch) //NOTE this only works for cuboid already has parallel to ground. otherwise update_z will also change final RPY\n    {\n        Vector9d update2 = update;\n        update2(0) = 0;\n        update2(1) = 0;\n        newcube.pose = _estimate.pose * exptwist_norollpitch(update2.head<6>()); //NOTE object pose is from object to world!!!!\n    }\n    else\n        newcube.pose = _estimate.pose * SE3Quat::exp(update.head<6>());\n\n    if (whether_fixheight) // use previous height\n        newcube.setTranslation(Vector3d(newcube.translation()(0), _estimate.translation()(1), newcube.translation()(2)));\n\n    if (fixedscale(0) > 0) // if fixed scale is set, use it.\n        newcube.scale = fixedscale;\n    else\n        newcube.scale = _estimate.scale + update.tail<3>();\n\n    setEstimate(newcube);\n}\n\n// similar as above\nvoid VertexCuboidFixScale::oplusImpl(const double *update_)\n{\n    Eigen::Map<const Vector6d> update(update_);\n\n    g2o::cuboid newcube;\n    if (whether_fixrotation)\n    {\n        newcube.pose.setRotation(_estimate.pose.rotation());\n        newcube.pose.setTranslation(_estimate.pose.translation() + update.tail<3>());\n    }\n    else if (whether_fixrollpitch)\n    {\n        Vector6d update2 = update;\n        update2(0) = 0;\n        update2(1) = 0;\n        newcube.pose = _estimate.pose * exptwist_norollpitch(update2);\n    }\n    else\n        newcube.pose = _estimate.pose * SE3Quat::exp(update);\n\n    if (whether_fixheight)\n        newcube.setTranslation(Vector3d(newcube.translation()(0), _estimate.translation()(1), newcube.translation()(2)));\n\n    if (fixedscale(0) > 0)\n        newcube.scale = fixedscale;\n    else\n        newcube.scale = _estimate.scale;\n\n    setEstimate(newcube);\n}\n\nvoid EdgeSE3CuboidFixScaleProj::computeError()\n{\n    const VertexSE3Expmap *SE3Vertex = dynamic_cast<const VertexSE3Expmap *>(_vertices[0]);              //  world to camera pose\n    const VertexCuboidFixScale *cuboidVertex = dynamic_cast<const VertexCuboidFixScale *>(_vertices[1]); //  object pose to world\n\n    SE3Quat cam_pose_Tcw = SE3Vertex->estimate();\n    cuboid global_cube = cuboidVertex->estimate();\n\n    Vector4d rect_project = global_cube.projectOntoImageBbox(cam_pose_Tcw, Kalib); // center, width, height\n    _error = rect_project - _measurement;\n}\n\ndouble EdgeSE3CuboidFixScaleProj::get_error_norm()\n{\n    computeError();\n    return _error.norm();\n}\n\nvoid EdgeSE3CuboidProj::computeError()\n{\n    const VertexSE3Expmap *SE3Vertex = dynamic_cast<const VertexSE3Expmap *>(_vertices[0]); //  world to camera pose\n    const VertexCuboid *cuboidVertex = dynamic_cast<const VertexCuboid *>(_vertices[1]);    //  object pose to world\n\n    SE3Quat cam_pose_Tcw = SE3Vertex->estimate();\n    cuboid global_cube = cuboidVertex->estimate();\n\n    Vector4d rect_project = global_cube.projectOntoImageBbox(cam_pose_Tcw, Kalib); // center, width, height\n\n    _error = rect_project - _measurement;\n}\n\ndouble EdgeSE3CuboidProj::get_error_norm()\n{\n    computeError();\n    return _error.norm();\n}\n\nvoid EdgeDynamicPointCuboidCamera::computeError()\n{\n    const VertexSE3Expmap *SE3Vertex = dynamic_cast<const VertexSE3Expmap *>(_vertices[0]);              // world to camera pose\n    const VertexCuboidFixScale *cuboidVertex = dynamic_cast<const VertexCuboidFixScale *>(_vertices[1]); // object to world pose\n    const VertexSBAPointXYZ *pointVertex = dynamic_cast<const VertexSBAPointXYZ *>(_vertices[2]);        // point to object pose\n\n    Vector3d localpt = SE3Vertex->estimate() * (cuboidVertex->estimate().pose * pointVertex->estimate());\n\n    Vector2d projected = Vector2d(Kalib(0, 2) + Kalib(0, 0) * localpt(0) / localpt(2), Kalib(1, 2) + Kalib(1, 1) * localpt(1) / localpt(2));\n    _error = _measurement - projected;\n}\n\nvoid EdgeDynamicPointCuboidCamera::linearizeOplus()\n{\n    const VertexSE3Expmap *SE3Vertex = dynamic_cast<const VertexSE3Expmap *>(_vertices[0]);              // world to camera pose\n    const VertexCuboidFixScale *cuboidVertex = dynamic_cast<const VertexCuboidFixScale *>(_vertices[1]); // object to world pose\n    const VertexSBAPointXYZ *pointVertex = dynamic_cast<const VertexSBAPointXYZ *>(_vertices[2]);        // point to object pose\n\n    Vector3d objectpt = pointVertex->estimate();\n    SE3Quat combinedT = SE3Vertex->estimate() * cuboidVertex->estimate().pose;\n    Vector3d camerapt = combinedT * objectpt;\n\n    double fx = Kalib(0, 0);\n    double fy = Kalib(1, 1);\n\n    double x = camerapt[0];\n    double y = camerapt[1];\n    double z = camerapt[2];\n    double z_2 = z * z;\n\n    Matrix<double, 2, 3> projptVscamerapt; //2d projected pixel / 3D local camera pt\n    projptVscamerapt(0, 0) = fx / z;\n    projptVscamerapt(0, 1) = 0;\n    projptVscamerapt(0, 2) = -x * fx / z_2;\n\n    projptVscamerapt(1, 0) = 0;\n    projptVscamerapt(1, 1) = fy / z;\n    projptVscamerapt(1, 2) = -y * fy / z_2;\n\n    // jacobian of point\n    _jacobianOplus[2] = -projptVscamerapt * combinedT.rotation().toRotationMatrix();\n\n    // jacobian of camera\n    _jacobianOplus[0](0, 0) = x * y / z_2 * fx;\n    _jacobianOplus[0](0, 1) = -(1 + (x * x / z_2)) * fx;\n    _jacobianOplus[0](0, 2) = y / z * fx;\n    _jacobianOplus[0](0, 3) = -1. / z * fx;\n    _jacobianOplus[0](0, 4) = 0;\n    _jacobianOplus[0](0, 5) = x / z_2 * fx;\n\n    _jacobianOplus[0](1, 0) = (1 + y * y / z_2) * fy;\n    _jacobianOplus[0](1, 1) = -x * y / z_2 * fy;\n    _jacobianOplus[0](1, 2) = -x / z * fy;\n    _jacobianOplus[0](1, 3) = 0;\n    _jacobianOplus[0](1, 4) = -1. / z * fy;\n    _jacobianOplus[0](1, 5) = y / z_2 * fy;\n\n    // jacobian of object pose.   obj twist  [angle position]\n    Matrix<double, 3, 6> skewjaco;\n    skewjaco.leftCols<3>() = -skew(objectpt);\n    skewjaco.rightCols<3>() = Matrix3d::Identity();\n    _jacobianOplus[1] = _jacobianOplus[2] * skewjaco; //2*6\n    if (cuboidVertex->whether_fixrollpitch)           //zero gradient for roll/pitch\n    {\n        _jacobianOplus[1](0, 0) = 0;\n        _jacobianOplus[1](0, 1) = 0;\n        _jacobianOplus[1](1, 0) = 0;\n        _jacobianOplus[1](1, 1) = 0;\n    }\n    if (cuboidVertex->whether_fixrotation)\n    {\n        _jacobianOplus[1](0, 0) = 0;\n        _jacobianOplus[1](0, 1) = 0;\n        _jacobianOplus[1](1, 0) = 0;\n        _jacobianOplus[1](1, 1) = 0;\n        _jacobianOplus[1](0, 2) = 0;\n        _jacobianOplus[1](1, 2) = 0;\n    }\n}\n\nVector2d EdgeDynamicPointCuboidCamera::computeError_debug()\n{\n    computeError();\n    return _error;\n}\n\nvoid EdgeObjectMotion::computeError()\n{\n    const VertexCuboidFixScale *cuboidVertexfrom = dynamic_cast<const VertexCuboidFixScale *>(_vertices[0]);   // object to world pose\n    const VertexCuboidFixScale *cuboidVertexto = dynamic_cast<const VertexCuboidFixScale *>(_vertices[1]);     // object to world pose\n    const VelocityPlanarVelocity *velocityVertex = dynamic_cast<const VelocityPlanarVelocity *>(_vertices[2]); // object to world pose\n\n    if (cuboidVertexfrom == nullptr || cuboidVertexto == nullptr || velocityVertex == nullptr)\n        cout << \"Bad casting when compute Edge motion error!!!!!!!!!!!!!\" << endl;\n\n    // predict motion x y yaw and compute measurement.\n    SE3Quat posefrom = cuboidVertexfrom->estimate().pose;\n    double yaw_from = posefrom.toXYZPRYVector()(5);\n\n    SE3Quat poseto = cuboidVertexto->estimate().pose;\n    double yaw_to = poseto.toXYZPRYVector()(5);\n\n    Vector2d velocity = velocityVertex->estimate(); //v w   linear velocity and steer angle\n\n    const double vehicle_length = 2.71; // front and back wheels distance\n    // vehicle motion model is applied to back wheel center\n    Vector3d trans_back_pred = posefrom.translation() + (velocity(0) * delta_t - vehicle_length * 0.5) * Vector3d(cos(yaw_from), sin(yaw_from), 0);\n    double yaw_pred = yaw_from + tan(velocity(1)) * delta_t / vehicle_length * velocity(0);\n\n    // as mentioned in paper: my object frame is at the center. the motion model applies to back wheen center. have offset.\n    Vector3d trans_pred = trans_back_pred + vehicle_length * 0.5 * Vector3d(cos(yaw_pred), sin(yaw_pred), 0);\n\n    _error = Vector3d(poseto.translation()[0], poseto.translation()[1], yaw_to) - Vector3d(trans_pred(0), trans_pred(1), yaw_pred);\n    if (_error[2] > 2.0 * M_PI)\n        _error[2] -= 2.0 * M_PI;\n    if (_error[2] < -2.0 * M_PI)\n        _error[2] += 2.0 * M_PI;\n}\n\nVector3d EdgeObjectMotion::computeError_debug()\n{\n    computeError();\n    return _error;\n}\n\nVector3d cuboid::point_boundary_error(const Vector3d &world_point, const double max_outside_margin_ratio, double point_scale) const\n{\n    // transform the point to local object frame  TODO actually can compute gradient analytically...\n    Vector3d local_pt = point_scale * (this->pose.inverse() * world_point).cwiseAbs(); // change global point to local cuboid body frame.  make it positive.\n    Vector3d error;\n\n    // if point is within the cube, error=0, otherwise penalty how far it is outside cube\n    for (int i = 0; i < 3; i++)\n    {\n        if (local_pt(i) < this->scale(i))\n            error(i) = 0;\n        else if (local_pt(i) < (max_outside_margin_ratio + 1) * this->scale(i))\n            error(i) = local_pt(i) - this->scale(i);\n        else\n            error(i) = max_outside_margin_ratio * this->scale(i); // if points two far, give a constant error, don't optimize.\n    }\n\n    return error;\n}\n\nvoid EdgePointCuboidOnlyObject::computeError()\n{\n    const VertexCuboid *cuboidVertex = dynamic_cast<const VertexCuboid *>(_vertices[0]); // world to camera pose\n\n    _error.setZero();\n\n    const g2o::cuboid &estimate_cube = cuboidVertex->estimate();\n\n    Vector3d point_edge_error;\n    point_edge_error.setZero();\n    for (size_t i = 0; i < object_points.size(); i++) // use abs  otherwise   pos neg will counteract by different pts.     maybe each edge one pt?\n        point_edge_error += estimate_cube.point_boundary_error(object_points[i], max_outside_margin_ratio).cwiseAbs();\n    if (object_points.size() > 0)\n        point_edge_error = point_edge_error / object_points.size();\n\n    point_edge_error = point_edge_error.array() / estimate_cube.scale.array(); //scale it\n\n    // add prior shape dimension error?\n    double prior_weight = 0.2;\n    Vector3d prior_shape_error = estimate_cube.scale; // setZero?  or penalize large box! or set a range?\n    if (prior_object_half_size(0) > 0)                // if prior shape is being set, such as KITTI, then give large weight for shape error\n    {\n        prior_weight = 50.0;\n        prior_shape_error = ((estimate_cube.scale - prior_object_half_size).array() / prior_object_half_size.array()).cwiseAbs();\n    }\n\n    _error = 1.0 * point_edge_error + prior_weight * prior_shape_error;\n}\n\nVector3d EdgePointCuboidOnlyObject::computeError_debug()\n{\n    computeError();\n    return _error;\n}\n\n// similar as above\nvoid EdgePointCuboidOnlyObjectFixScale::computeError()\n{\n    const VertexCuboidFixScale *cuboidVertex = dynamic_cast<const VertexCuboidFixScale *>(_vertices[0]); // world to camera pose\n\n    _error.setZero();\n\n    const g2o::cuboid &estimate_cube = cuboidVertex->estimate();\n\n    Vector3d point_edge_error;\n    point_edge_error.setZero();\n    for (size_t i = 0; i < object_points.size(); i++)\n        point_edge_error += estimate_cube.point_boundary_error(object_points[i], max_outside_margin_ratio).cwiseAbs();\n    if (object_points.size() > 0)\n        point_edge_error = point_edge_error / object_points.size();\n\n    point_edge_error = point_edge_error.array() / estimate_cube.scale.array();\n\n    _error = 1.0 * point_edge_error;\n}\n\nvoid EdgePointCuboid::computeError()\n{\n    const VertexSBAPointXYZ *pointVertex = dynamic_cast<const VertexSBAPointXYZ *>(_vertices[0]); // point position\n    const VertexCuboid *cuboidVertex = dynamic_cast<const VertexCuboid *>(_vertices[1]);          //  object pose to world\n    const g2o::cuboid estimate_cube = cuboidVertex->estimate();\n\n    Vector3d point_edge_error = estimate_cube.point_boundary_error(pointVertex->estimate(), max_outside_margin_ratio).cwiseAbs(); // abs to add shape error\n    point_edge_error = point_edge_error.array() / estimate_cube.scale.array();\n\n    // add prior shape dimension error?\n    double prior_weight = 0.2;\n    Vector3d prior_shape_error = estimate_cube.scale; // setZero?  or penalize large box! or set a range?\n    _error = 1.0 * point_edge_error + prior_weight * prior_shape_error;\n}\n\nvoid EdgePointCuboidFixScale::computeError()\n{\n    const VertexSBAPointXYZ *pointVertex = dynamic_cast<const VertexSBAPointXYZ *>(_vertices[0]);        // point position\n    const VertexCuboidFixScale *cuboidVertex = dynamic_cast<const VertexCuboidFixScale *>(_vertices[1]); //  object pose to world\n    const g2o::cuboid estimate_cube = cuboidVertex->estimate();\n\n    Vector3d point_edge_error = estimate_cube.point_boundary_error(pointVertex->estimate(), max_outside_margin_ratio).cwiseAbs(); // abs to add shape error\n    point_edge_error = point_edge_error.array() / estimate_cube.scale.array();\n\n    _error = 1.0 * point_edge_error;\n}\n\nvoid UnaryLocalPoint::computeError()\n{\n    // transform the point to local object frame\n    const VertexSBAPointXYZ *pointVertex = dynamic_cast<const VertexSBAPointXYZ *>(_vertices[0]); // point position\n    Vector3d local_pt = pointVertex->estimate().cwiseAbs();                                       // make it positive.\n    Vector3d point_edge_error;\n\n    // if point is within the cube, point_edge_error=0, otherwise penalty how far it is outside cube\n    for (int i = 0; i < 3; i++)\n    {\n        if (local_pt(i) < objectscale(i))\n            point_edge_error(i) = 0;\n        else if (local_pt(i) < (max_outside_margin_ratio + 1) * objectscale(i))\n            point_edge_error(i) = local_pt(i) - objectscale(i);\n        else\n            point_edge_error(i) = max_outside_margin_ratio * objectscale(i); // if points two far, give a constant error, don't optimize.\n    }\n\n    _error = point_edge_error.array() / objectscale.array();\n}\n\n} // namespace g2o", "meta": {"hexsha": "f3b20d5e246c3f83ab8cec4ddbd05db6755826aa", "size": 15302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "orb_object_slam/src/g2o_Object.cpp", "max_stars_repo_name": "Aceralon/cube_slam", "max_stars_repo_head_hexsha": "1687e7cca6e77c96a507655c8dd6c1e7653535ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 619.0, "max_stars_repo_stars_event_min_datetime": "2018-10-31T00:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:25:41.000Z", "max_issues_repo_path": "orb_object_slam/src/g2o_Object.cpp", "max_issues_repo_name": "Aceralon/cube_slam", "max_issues_repo_head_hexsha": "1687e7cca6e77c96a507655c8dd6c1e7653535ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2019-03-19T03:05:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T03:57:44.000Z", "max_forks_repo_path": "orb_object_slam/src/g2o_Object.cpp", "max_forks_repo_name": "Aceralon/cube_slam", "max_forks_repo_head_hexsha": "1687e7cca6e77c96a507655c8dd6c1e7653535ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 207.0, "max_forks_repo_forks_event_min_datetime": "2018-10-31T02:02:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:25:36.000Z", "avg_line_length": 37.8762376238, "max_line_length": 156, "alphanum_fraction": 0.6732453274, "num_tokens": 4449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5039985522722633}}
{"text": "#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n\n#include \"roadnet.hpp\"\n\nusing namespace dubins_traffic;\n\n\nint main()\n{\n    Eigen::Vector3d transform( 1.0, 0.0, 1.6 );\n    dubins_traffic::RoadNetwork rd( 2.0, transform, 2, 3 );\n    std::cout << rd << std::endl;\n\n    double x, y;\n    rd.map_point( 0, 0, x, y );\n    std::cerr << \"(0, 0) -> (\" << x << \", \" << y << \")\" << std::endl;\n\n    rd.map_point( 1, 2, x, y );\n    std::cerr << \"(1, 2) -> (\" << x << \", \" << y << \")\" << std::endl;\n\n    for (size_t idx = 0; idx < rd.number_of_segments(); idx++)\n        std::cerr << rd.mapped_segment( idx ).transpose() << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "a9d7e38ace670c0b6a49bdce99453de78e4ab36c", "size": 651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "domains/dubins_traffic/dubins_traffic_utils/examples/standalone/helloroadnet.cpp", "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/dubins_traffic/dubins_traffic_utils/examples/standalone/helloroadnet.cpp", "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/dubins_traffic/dubins_traffic_utils/examples/standalone/helloroadnet.cpp", "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": 23.25, "max_line_length": 71, "alphanum_fraction": 0.5268817204, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5039985522722633}}
{"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_ARCH_COMMON_SIMD_FUNCTION_SINC_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SINC_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/sin.hpp>\n\n#if !defined(BOOST_SIMD_NO_DENORMALS)\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/is_less.hpp>\n#endif\n\n#if !defined(BOOST_SIMD_NO_INFINITIES)\n#include <boost/simd/function/if_zero_else.hpp>\n#include <boost/simd/function/is_inf.hpp>\n#endif\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF( sinc_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        A0 r1 =  bs::sin(a0)/a0;\n        #if !defined(BOOST_SIMD_NO_DENORMALS)\n        r1 = bs::if_else ( bs::is_less(bs::abs(a0), bs::Eps<A0>())\n                          , bs::One<A0>()\n                          , r1\n                          );\n        #else\n        r1 = bs::if_else(bs::is_eqz(a0), bs::One<A0>(), r1);\n        #endif\n        #if !defined(BOOST_SIMD_NO_INFINITIES)\n        r1 = bs::if_zero_else(bs::is_inf(a0), r1);\n        #endif\n        return r1;\n      }\n   };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "b4318004a0aa1c7bfa7e799df9340f46f96ac9e3", "size": 2042, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/sinc.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/arch/common/simd/function/sinc.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/arch/common/simd/function/sinc.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.90625, "max_line_length": 100, "alphanum_fraction": 0.5533790402, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.503978013096726}}
{"text": "#include <iostream>\n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/eigen.h>\n#include <pybind11/numpy.h>\n\n#include <Eigen/Core>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/eigen.hpp>\n// #include <cuda_runtime.h>\n\nnamespace py = pybind11;\nusing namespace std;\n\nusing Eigen::Dynamic;\nusing Eigen::RowMajor;\nusing Eigen::Unaligned;\n\n\nconst double DEGREE2RADIAN = M_PI / 180.0;\n\nvoid process_image(\n    const cv::Mat &pano,\n    cv::Mat &pers,\n    const cv::Mat_<double> &rot,\n    const cv::Mat_<double> &K);\n\n/*\n Create instrinsic parameter\n */\ncv::Mat_<double> get_intrinsic_param(cv::Size &size_per)\n{\n    double fov = 90.0 * DEGREE2RADIAN;\n    double focal_length = (double)size_per.width/(2. * tan(fov / 2.));\n    cv::Mat_<double> K = (\n        cv::Mat_<double>(3, 3) << \n        focal_length, 0., (double)size_per.width/2.,\n        0., focal_length, (double)size_per.height/2.,\n        0., 0., 1.);\n    return K;\n}\n\n/*\n Get rotation matrix from the direction given\n - Input: an array of double (3 rotation angles)\n - Output: rotation matrix\n */\ncv::Mat_<double> angle2RotMat(array<double, 3> &rot_angle)\n{\n\tcv::Mat_<double> Th2c_key = (cv::Mat_<double>(3,3) << \n\t\t1., 0., 0.,\n\t\t0., cos(rot_angle[0]), sin(rot_angle[0]),\n\t\t0., -sin(rot_angle[0]), cos(rot_angle[0])) \n\t\t*(cv::Mat_<double>(3,3) <<\n\t\tcos(rot_angle[1]), 0., -sin(rot_angle[1]),\n\t\t0., 1., 0.,\n\t\tsin(rot_angle[1]), 0., cos(rot_angle[1]))\n\t\t*(cv::Mat_<double>(3,3) <<\n        cos(rot_angle[2]), sin(rot_angle[2]), \t0.,\n\t\t-sin(rot_angle[2]), cos(rot_angle[2]), \t0.,\n\t\t0., 0., 1.);\n    return Th2c_key;\n}\n\n/*\n Get x, y pixel location of panorama image \n from theta (rotation around y-axis) and \n phi (rotation around x-axis)\n */\ncv::Mat get_image(\n    array<Eigen::Matrix<unsigned char, Dynamic, Dynamic, RowMajor>, 3> &src,\n    array<double, 3> &angles)\n{\n    cv::Mat rgb[3];\n    cv::Mat im_pano(src[0].rows(), src[0].cols(), CV_8UC3);\n    for (int i=0; i<src.size(); i++)\n    {\n        cv::Mat channel(src[i].rows(), src[i].cols(), CV_8UC1, src[i].data());\n        rgb[i] = channel;\n    }\n    cv::merge(rgb, 3, im_pano);\n\n    // Get intrinsic parameter:\n    const int height = 360; // (int)im_pano.rows/4;\n    const int width = 640; // (int)im_pano.cols/4;\n    cv::Size size_per = cv::Size(width, height);\n    cv::Mat_<double> K = get_intrinsic_param(size_per);\n    //cout << \"Intrinsic Param: \" << K << endl;\n\n    cv::Mat_<double> rotation = angle2RotMat(angles); // make it front for now\n    //cout << \"Rotation Matrix: \" << rotation << endl;\n\n    // Create perspective image\n    cv::Mat im_perspective = cv::Mat::zeros(cv::Size(width, height), CV_8UC3);\n    process_image(im_pano, im_perspective, K, rotation);\n    \n    return im_perspective;\n}\n\nPYBIND11_MODULE(extension, m)\n{\n    m.def(\"get_image\", &get_image);\n\n    // Cuffer protocol for return value\n    py::class_<cv::Mat>(m, \"Image\", py::buffer_protocol())\n        .def_buffer([](cv::Mat& im) -> py::buffer_info{\n            return py::buffer_info(\n                // pointer to buffer\n                im.data,\n                //size of one scalar\n                sizeof(unsigned char),\n                // Python struct-style format descriptor\n                py::format_descriptor<unsigned char>::format(),\n                // Number of dimensions\n                3,\n                // Buffer dimensions\n                { im.rows, im.cols, im.channels() },\n                // Strides (in bytes) for each index\n                {\n                    sizeof(unsigned char) * im.channels() * im.cols,\n                    sizeof(unsigned char) * im.channels(),\n                    sizeof(unsigned char)\n                }\n            );\n        });\n}", "meta": {"hexsha": "4ad0997e4eb894e2ce2b1a33e29824f9e844e4df", "size": 3702, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fooling-around/main.cpp", "max_stars_repo_name": "haruishi43/cuda-programming", "max_stars_repo_head_hexsha": "c393f43614548099999068cc96cb5559c0e29bfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fooling-around/main.cpp", "max_issues_repo_name": "haruishi43/cuda-programming", "max_issues_repo_head_hexsha": "c393f43614548099999068cc96cb5559c0e29bfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fooling-around/main.cpp", "max_forks_repo_name": "haruishi43/cuda-programming", "max_forks_repo_head_hexsha": "c393f43614548099999068cc96cb5559c0e29bfd", "max_forks_repo_licenses": ["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.1496062992, "max_line_length": 78, "alphanum_fraction": 0.5853592653, "num_tokens": 1066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.503978013096726}}
{"text": "#ifndef __TERM_SIMPLIFIER_HPP__\n#define __TERM_SIMPLIFIER_HPP__\n\n#include <crab/common/types.hpp>\n#include <boost/optional.hpp>\n\n/* \n   Simplifiers for table terms after giving meaning to functors.\n*/\n\nnamespace crab {\n  namespace domains {\n    namespace term {\n\n        // Common API to simplifiers\n        template < class Num, class Ftor>\n        class Simplifier \n        {\n         protected:\n          \n          typedef term_table <Num, Ftor> term_table_t;\n          typedef typename term_table_t::term_id_t term_id_t;\n\n          term_table_t  &_ttbl;\n          \n         public:\n\n          Simplifier (term_table_t &term_table): _ttbl(term_table) {}\n          virtual void simplify () = 0;\n\n          // This should not modify the term table\n          // FIXME: cannot make const the method without changing\n          // constness of other methods.\n          virtual boost::optional<term_id_t> simplify_term (term_id_t t) = 0;\n\n        };\n\n        // Trivial simplifier by giving standard mathematical meaning\n        // to arithmetic operators assuming that conmutativity,\n        // associativity etc properties hold as expected.\n        template < class Num>\n        class NumSimplifier: Simplifier<Num, binary_operation_t > \n        {\n          typedef Simplifier<Num, binary_operation_t> simplifier_t;\n          \n          typedef term_table <Num, binary_operation_t> term_table_t;\n          typedef typename term_table_t::term_id_t term_id_t;\n          typedef typename term_table_t::term_t term_t;\n\n          // Simplify term f(left,right)\n          boost::optional<term_id_t>\n          simplify_term (binary_operation_t f, term_id_t left, term_id_t right)\n          {\n            // Only consider these two rules:\n            //   '/'('*'(x,y),x) = y\n            //   '/'('*'(x,y),y) = x\n            switch (f)\n            {\n              case BINOP_SDIV:\n              case BINOP_UDIV:\n                {\n                  term_t* tleft  = this->_ttbl.get_term_ptr (left);\n                  term_t* tright = this->_ttbl.get_term_ptr (right);\n\n                  if ((tleft->kind () == TERM_APP) && term_ftor(tleft) == BINOP_MUL)\n                  {\n                    std::vector<term_id_t>& args(term_args(tleft));\n                    assert(args.size() == 2);\n                    term_t* tl = this->_ttbl.get_term_ptr (args[0]);\n                    term_t* tr = this->_ttbl.get_term_ptr (args[1]);\n                    \n                    if (tl == tright) return args[1];\n                    if (tr == tright) return args[0];\n                  }\n                }\n              default:  return boost::optional<term_id_t> ();\n            }\n          }\n\n         public:\n          \n          NumSimplifier (term_table_t &term_table): simplifier_t (term_table) {}\n          \n          void simplify () {}\n          \n          boost::optional<term_id_t> simplify_term (term_id_t t) \n          {\n            if (term_t* tt = this->_ttbl.get_term_ptr (t))\n            {\n              if (tt->kind () == TERM_APP)\n              {\n                std::vector<term_id_t>& args(term_args(tt));\n                assert(args.size() == 2);\n                \n                return simplify_term (term_ftor (tt), args[0], args[1]);\n              }\n            }\n            return boost::optional<term_id_t>();\n          }\n          \n        };\n\n     } //end namespace term\n  } //end namespace domains\n} // end namespace crab\n#endif\n", "meta": {"hexsha": "16fe5d62e3fa15ab36a3c9257a1d1b951b1ebba3", "size": 3437, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/term/simplify.hpp", "max_stars_repo_name": "DavidFarago/crab", "max_stars_repo_head_hexsha": "c5fba9a132afea11c10f2790d232d192b2d0ae9c", "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/crab/domains/term/simplify.hpp", "max_issues_repo_name": "DavidFarago/crab", "max_issues_repo_head_hexsha": "c5fba9a132afea11c10f2790d232d192b2d0ae9c", "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/crab/domains/term/simplify.hpp", "max_forks_repo_name": "DavidFarago/crab", "max_forks_repo_head_hexsha": "c5fba9a132afea11c10f2790d232d192b2d0ae9c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-01T12:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-01T12:33:53.000Z", "avg_line_length": 32.1214953271, "max_line_length": 84, "alphanum_fraction": 0.5245853942, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6334102636778403, "lm_q1q2_score": 0.503978013096726}}
{"text": "#include <cucumber-cpp/autodetect.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/format.hpp>\n\nusing std::string;\nusing cucumber::ScenarioScope;\n\nnamespace {\n\n    bool isCloseEnough(double value, double expected) {\n        return (std::abs(value - expected) > 0.00001);\n    }\n\n    void verifyEqual(double value, double expected) {\n        if (isCloseEnough(value, expected)) {\n            throw (boost::format(\"Value %1% not equal to %2%\") % value % expected).str();\n        }\n    }\n\n    void verifyNotEqual(double value, double expected) {\n        if (!isCloseEnough(value, expected)) {\n            throw (boost::format(\"Value %1% equal to %2%\") % value % expected).str();\n        }\n    }\n}\n\nGIVEN(\"^a calculator\") {\n    // nothing to do\n}\n\nWHEN(\"^the calculator computes PI$\") {\n    ScenarioScope<RpnCalculator> calc;\n    calc->pi();\n}\n\nWHEN(\"^the calculator adds up ([\\\\d\\\\.]+) and ([\\\\d\\\\.]+)$\") {\n    REGEX_PARAM(string, n1);\n    REGEX_PARAM(string, n2);\n\n    ScenarioScope<RpnCalculator> calc;\n    calc->push(n1);\n    calc->push(n2);\n    calc->push(\"+\");\n}\n\nWHEN(\"^the calculator adds up \\\"([^\\\"]*)\\\" and \\\"([^\\\"]*)\\\"$\") {\n    REGEX_PARAM(string, n1);\n    REGEX_PARAM(string, n2);\n\n    ScenarioScope<RpnCalculator> calc;\n    calc->push(n1);\n    calc->push(n2);\n    calc->push(\"+\");\n}\n\nWHEN(\"^the calculator adds up \\\"([^\\\"]*)\\\", \\\"([^\\\"]*)\\\" and \\\"([^\\\"]*)\\\"$\") {\n    REGEX_PARAM(string, n1);\n    REGEX_PARAM(string, n2);\n    REGEX_PARAM(string, n3);\n\n    ScenarioScope<RpnCalculator> calc;\n    calc->push(n1);\n    calc->push(n2);\n    calc->push(n3);\n    calc->push(\"+\");\n    calc->push(\"+\");\n}\n\nWHEN(\"^the calculator adds up the following numbers:$\") {\n    REGEX_PARAM(string, numberString);\n\n    ScenarioScope<RpnCalculator> calc;\n    vector<string> numbers;\n    boost::split(numbers, numberString,boost::is_any_of(\"\\n\"));\n\n    for (size_t i=0; i < numbers.size(); ++i) {\n        calc->push(numbers[i]);\n        if (i != 0) {\n            calc->push(\"+\");\n        }\n    }\n}\n\nTHEN(\"^the calculator returns PI$\") {\n    ScenarioScope<RpnCalculator> calc;\n    verifyEqual(calc->value(), boost::math::constants::pi<double>());\n}\n\nTHEN(\"^the calculator returns \\\"([^\\\"]*)\\\"$\") {\n    REGEX_PARAM(double, expected);\n\n    ScenarioScope<RpnCalculator> calc;\n    verifyEqual(calc->value(), expected);\n}\n\nTHEN(\"^the calculator does not return ([\\\\d\\\\.]+)$\") {\n    REGEX_PARAM(double, expected);\n\n    ScenarioScope<RpnCalculator> calc;\n    double value = calc->value();\n    verifyNotEqual(calc->value(), expected);\n}\n\n", "meta": {"hexsha": "b88a8f9f5b41c0f22c0045d8508fe4d02839f3ee", "size": 2569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "features/step_definitions/RpnCalculatorSteps.cpp", "max_stars_repo_name": "d-led/cucumber-cpp", "max_stars_repo_head_hexsha": "e6de073733fcacc99db6518ed73e8cb474121d07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "features/step_definitions/RpnCalculatorSteps.cpp", "max_issues_repo_name": "d-led/cucumber-cpp", "max_issues_repo_head_hexsha": "e6de073733fcacc99db6518ed73e8cb474121d07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "features/step_definitions/RpnCalculatorSteps.cpp", "max_forks_repo_name": "d-led/cucumber-cpp", "max_forks_repo_head_hexsha": "e6de073733fcacc99db6518ed73e8cb474121d07", "max_forks_repo_licenses": ["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.4666666667, "max_line_length": 89, "alphanum_fraction": 0.5963409887, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5039227978198875}}
{"text": "// Copyright (c) 2018 Graphcore Ltd. All rights reserved.\n#define BOOST_TEST_MODULE NumpyBroadcastShape\n\n#include <sstream>\n\n#include <boost/test/unit_test.hpp>\n#include <popart/error.hpp>\n#include <popart/tensorinfo.hpp>\n\nstruct BroadcastTestCase {\n  std::vector<int64_t> a_shape;\n  std::vector<int64_t> b_shape;\n  std::vector<int64_t> result_shape;\n};\n\n// clang-format off\nstatic const BroadcastTestCase test_cases[] = {\n    // Test cases taken from\n    // https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html#general-broadcasting-rules\n    {{   256, 256, 3}, {       3}, {   256, 256, 3}},\n    {{8,   1,   6, 1}, {7,  1, 5}, {8,   7,   6, 5}},\n    {{          5, 4}, {       1}, {          5, 4}},\n    {{          5, 4}, {       4}, {          5, 4}},\n    {{    15,   3, 5}, {15, 1, 5}, {    15,   3, 5}},\n    {{    15,   3, 5}, {    3, 5}, {    15,   3, 5}},\n    {{    15,   3, 5}, {    3, 1}, {    15,   3, 5}},\n\n    // Test cases taken from\n    // https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md\n    {{2, 3, 4, 5}, {/* scalar */}, {2, 3, 4, 5}},\n    {{2, 3, 4, 5}, {           5}, {2, 3, 4, 5}},\n    {{      4, 5}, {  2, 3, 4, 5}, {2, 3, 4, 5}},\n    {{   1, 4, 5}, {  2, 3, 1, 1}, {2, 3, 4, 5}},\n    {{   3, 4, 5}, {  2, 1, 1, 1}, {2, 3, 4, 5}}\n};\n// clang-format on\n\nBOOST_AUTO_TEST_CASE(NumpyBroadcastShape) {\n  for (const auto &test_case : test_cases) {\n    BOOST_TEST(popart::npBroadcastable(test_case.a_shape, test_case.b_shape));\n\n    const auto new_shape = popart::npOut(test_case.a_shape, test_case.b_shape);\n    BOOST_TEST(new_shape == test_case.result_shape,\n               boost::test_tools::per_element());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(NumpyBroadcastTensorInfo) {\n  for (const auto &test_case : test_cases) {\n    BOOST_TEST(popart::npBroadcastable(\n        popart::TensorInfo(popart::DataType::FLOAT16, test_case.a_shape),\n        popart::TensorInfo(popart::DataType::FLOAT16, test_case.b_shape)));\n\n    const auto new_tensor = popart::npOut(\n        popart::TensorInfo(popart::DataType::FLOAT16, test_case.a_shape),\n        popart::TensorInfo(popart::DataType::FLOAT16, test_case.b_shape));\n    BOOST_TEST(new_tensor.shape() == test_case.result_shape,\n               boost::test_tools::per_element());\n    BOOST_TEST(new_tensor.dataType() == popart::DataType::FLOAT16);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(NumpyBroadcastTensoInfoDataTypeMismatch) {\n  for (const auto &test_case : test_cases) {\n    BOOST_TEST(!popart::npBroadcastable(\n        popart::TensorInfo(popart::DataType::FLOAT16, test_case.a_shape),\n        popart::TensorInfo(popart::DataType::INT32, test_case.b_shape)));\n\n    const size_t ERR_LEN = 500;\n\n    const auto addShape = [&](const std::vector<int64_t> &shape,\n                              std::ostream &os) {\n      auto it = shape.begin();\n      if (it == shape.end()) {\n        return;\n      }\n\n      while (true) {\n        os << *it;\n        it++;\n        if (it == shape.end()) {\n          return;\n        }\n        os << \" \";\n      }\n    };\n\n    const auto predicate = [&](popart::error e) {\n      std::ostringstream errm;\n      errm << \"np broadcasting failed, incompatible types FLOAT16 and INT32 \";\n      errm << \"(shapes [\";\n      addShape(test_case.a_shape, errm);\n      errm << \"] and [\";\n      addShape(test_case.b_shape, errm);\n      errm << \"])\";\n\n      return e.what() == errm.str();\n    };\n\n    BOOST_CHECK_EXCEPTION(\n        popart::npOut(\n            popart::TensorInfo(popart::DataType::FLOAT16, test_case.a_shape),\n            popart::TensorInfo(popart::DataType::INT32, test_case.b_shape)),\n        popart::error,\n        predicate);\n  }\n}\n\nstruct BroadcastBackwardTestCase {\n  std::vector<int64_t> in_shape;\n  std::vector<int64_t> out_shape;\n  std::vector<int64_t> result_axes;\n};\n\n// clang-format off\nstatic const BroadcastBackwardTestCase backward_test_cases[] = {\n    {{7, 2, 3, 4, 5, 6}, {7, 2, 3, 4, 5, 6}, {                }},\n    {{2, 3, 4, 5, 6   }, {7, 2, 3, 4, 5, 6}, {0               }},\n    {{3, 4, 5, 6      }, {7, 2, 3, 4, 5, 6}, {0, 1            }},\n    {{4, 5, 6         }, {7, 2, 3, 4, 5, 6}, {0, 1, 2         }},\n    {{5, 6            }, {7, 2, 3, 4, 5, 6}, {0, 1, 2, 3      }},\n    {{6               }, {7, 2, 3, 4, 5, 6}, {0, 1, 2, 3, 4   }},\n    {{                }, {7, 2, 3, 4, 5, 6}, {0, 1, 2, 3, 4, 5}},\n    {{1, 1, 1, 1, 1, 1}, {7, 2, 3, 4, 5, 6}, {0, 1, 2, 3, 4, 5}},\n    {{1, 1, 1, 1, 1, 6}, {7, 2, 3, 4, 5, 6}, {0, 1, 2, 3, 4   }},\n    {{1, 1, 1, 1, 5, 6}, {7, 2, 3, 4, 5, 6}, {0, 1, 2, 3      }},\n    {{1, 1, 1, 4, 5, 6}, {7, 2, 3, 4, 5, 6}, {0, 1, 2         }},\n    {{1, 1, 3, 4, 5, 6}, {7, 2, 3, 4, 5, 6}, {0, 1            }},\n    {{1, 2, 3, 4, 5, 6}, {7, 2, 3, 4, 5, 6}, {0               }},\n    {{7, 2, 3, 4, 5, 6}, {7, 2, 3, 4, 5, 6}, {                }},\n\n    // Test cases taken from\n    // https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html#general-broadcasting-rules\n    {{   256, 256, 3}, {   256, 256, 3}, {    }},\n    {{8,   1,   6, 1}, {8,   7,   6, 5}, {1, 3}},\n    {{             3}, {   256, 256, 3}, {0, 1}},\n    {{     7,   1, 5}, {8,   7,   6, 5}, {0, 2}},\n    {{             1}, {          5, 4}, {0, 1}},\n    {{             4}, {          5, 4}, {   0}},\n    {{    15,   1, 5}, {    15,   3, 5}, {   1}},\n    {{          3, 5}, {    15,   3, 5}, {   0}},\n    {{          3, 1}, {    15,   3, 5}, {0, 2}},\n\n    // Test cases taken from\n    // https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md\n    {{        4, 5}, {2, 3, 4, 5}, {      0, 1}},\n    {{     1, 4, 5}, {2, 3, 4, 5}, {      0, 1}},\n    {{     3, 4, 5}, {2, 3, 4, 5}, {         0}},\n    {{/* scalar */}, {2, 3, 4, 5}, {0, 1, 2, 3}},\n    {{           5}, {2, 3, 4, 5}, {   0, 1, 2}},\n    {{  2, 3, 1, 1}, {2, 3, 4, 5}, {      2, 3}},\n    {{  2, 1, 1, 1}, {2, 3, 4, 5}, {   1, 2, 3}}\n\n};\n// clang-format on\n\nBOOST_AUTO_TEST_CASE(NumpyBroadcastBackwardShape) {\n  for (const auto &test_case : backward_test_cases) {\n    const auto axes =\n        popart::npReductionAxis(test_case.in_shape, test_case.out_shape);\n    BOOST_TEST(axes == test_case.result_axes, boost::test_tools::per_element());\n  }\n}\n\nstruct ExceptionTestCase {\n  std::string name;\n  std::vector<int64_t> a_shape;\n  std::vector<int64_t> b_shape;\n  std::string msg;\n};\n\n// clang-format off\nExceptionTestCase exception_test_cases[] = {\n    {\"\"   , {   3}, {   4}, \"np broadcasting failed, frames [3] and [4] are not aligned\"},\n    {\"\"   , {1, 3}, {   4}, \"np broadcasting failed, frames [1, 3] and [4] are not aligned\"},\n    {\"\"   , {4, 3}, {   4}, \"np broadcasting failed, frames [4, 3] and [4] are not aligned\"},\n    {\"foo\", {   3}, {   4}, \"np broadcasting failed on 'foo', frames [3] and [4] are not aligned\"},\n    {\"foo\", {1, 3}, {   4}, \"np broadcasting failed on 'foo', frames [1, 3] and [4] are not aligned\"},\n    {\"foo\", {4, 3}, {   4}, \"np broadcasting failed on 'foo', frames [4, 3] and [4] are not aligned\"},\n    {\"\"   , {   3}, {3, 4}, \"np broadcasting failed, frames [3] and [3, 4] are not aligned\"},\n    {\"\"   , {   3}, {1, 4}, \"np broadcasting failed, frames [3] and [1, 4] are not aligned\"},\n    {\"\"   , {   3}, {   4}, \"np broadcasting failed, frames [3] and [4] are not aligned\"},\n    {\"foo\", {   3}, {3, 4}, \"np broadcasting failed on 'foo', frames [3] and [3, 4] are not aligned\"},\n    {\"foo\", {   3}, {1, 4}, \"np broadcasting failed on 'foo', frames [3] and [1, 4] are not aligned\"},\n    {\"foo\", {   3}, {   4}, \"np broadcasting failed on 'foo', frames [3] and [4] are not aligned\"},\n};\n// clang-format on\n\nBOOST_AUTO_TEST_CASE(NumpyBroadcastException) {\n  for (const auto &test_case : exception_test_cases) {\n    const auto predicate = [&](popart::error e) {\n      return test_case.msg == e.what();\n    };\n\n    BOOST_TEST(!popart::npBroadcastable(test_case.a_shape, test_case.b_shape));\n\n    BOOST_CHECK_EXCEPTION(\n        popart::npOut(test_case.a_shape, test_case.b_shape, test_case.name),\n        popart::error,\n        predicate);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(NumpyBroadcastTensorInfoShapeException) {\n  for (const auto &test_case : exception_test_cases) {\n\n    // Skip tests with a debug name as not supported for TensorInfo use\n    if (test_case.name != \"\") {\n      continue;\n    }\n\n    const auto predicate = [&](popart::error e) {\n      return test_case.msg == e.what();\n    };\n\n    BOOST_TEST(!popart::npBroadcastable(\n        popart::TensorInfo(popart::DataType::FLOAT16, test_case.a_shape),\n        popart::TensorInfo(popart::DataType::FLOAT16, test_case.b_shape)));\n\n    BOOST_CHECK_EXCEPTION(\n        popart::npOut(\n            popart::TensorInfo(popart::DataType::FLOAT16, test_case.a_shape),\n            popart::TensorInfo(popart::DataType::FLOAT16, test_case.b_shape)),\n        popart::error,\n        predicate);\n  }\n}", "meta": {"hexsha": "c35096f4475c213fba91f19b1d12568cc3b98b47", "size": 8727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/integration/numpybroadcastshapetest.cpp", "max_stars_repo_name": "gglin001/popart", "max_stars_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_stars_repo_licenses": ["MIT"], "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/integration/numpybroadcastshapetest.cpp", "max_issues_repo_name": "gglin001/popart", "max_issues_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_issues_repo_licenses": ["MIT"], "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/integration/numpybroadcastshapetest.cpp", "max_forks_repo_name": "gglin001/popart", "max_forks_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_forks_repo_licenses": ["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.4449339207, "max_line_length": 102, "alphanum_fraction": 0.5235476109, "num_tokens": 3169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5039227884878278}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_math/blob/master/LICENSE\n\n#ifndef CBR_MATH__INTERP__PIECEWISE_CONSTANT_HPP_\n#define CBR_MATH__INTERP__PIECEWISE_CONSTANT_HPP_\n\n#include <Eigen/Dense>\n\n#include <utility>\n#include <vector>\n#include <array>\n\n#include \"piecewise_poly.hpp\"\n\nnamespace cbr\n{\n\nclass PiecewiseConstant\n{\nprotected:\n  using row_t = Eigen::Matrix<double, 1, Eigen::Dynamic>;\n  using matrix_t = Eigen::MatrixXd;\n\npublic:\n  /**\n   * @brief Create a scalar-valued piecewise constant polynomial\n   *\n   * @tparam T1 PiecewisePoly::row_t\n   * @tparam T2 PiecewisePoly::row_t\n   * @param x sorted breakpoints\n   * @param y values\n   *\n   * The resulting function f is s.t.\n   *  f(t) = y[i] if x[i] <= t < x[i+1]\n   *  f(t) = y[0] if t < x[0]\n   *  f(t) = y[x.size() - 1] if t >= x[x.size() - 1]\n   */\n  template<typename T1, typename T2>\n  static PiecewisePoly fit(\n    T1 && x,\n    const Eigen::DenseBase<T2> & y)\n  {\n    static_assert(is_eigen_dense_v<T1>, \"x must be an Eigen::DenseBase object.\");\n\n    // add a dummy datapoint at the end\n    const auto newsize = x.size() + 1;\n    row_t x_ext(newsize);\n    x_ext << x, x(x.size() - 1) + 1;\n    row_t y_ext(newsize);\n    y_ext << y, y(y.cols() - 1);\n\n    auto coeffs = generateCoeffs(x_ext, y_ext);\n    return PiecewisePoly(std::move(x_ext), std::move(coeffs));\n  }\n\n  /**\n   * @brief Create a vector-valued piecewise constant polynomial\n   *\n   * @tparam T1 PiecewisePoly::row_t\n   * @tparam T2 PiecewisePoly::matrix_t or container_t<PiecewisePoly::row_t>\n   * @param x sorted breakpoints\n   * @param y values\n   *\n   * The resulting function f is s.t.\n   *  f(t) = y[i] if x[i] <= t < x[i+1]\n   *  f(t) = y[0] if t < x[0]\n   *  f(t) = y[x.size() - 1] if t >= x[x.size() - 1]\n   */\n  template<typename T1, typename T2>\n  static PiecewisePolyND fitND(\n    T1 && x,\n    const T2 & ys)\n  {\n    static_assert(is_eigen_dense_v<T1>, \"x must be an Eigen::DenseBase object.\");\n\n    if (x.size() == 0) {\n      throw std::invalid_argument(\"x must be non-empty\");\n    }\n\n    // add a dummy datapoint at the end\n    const auto newsize = x.size() + 1;\n    row_t x_ext(newsize);\n    x_ext << x, x(x.size() - 1) + 1;\n\n    std::vector<matrix_t> coefLists;\n\n    if constexpr (is_eigen_dense_v<T2>) {\n      if (ys.rows() < 1) {\n        throw std::invalid_argument(\"Dimension of the data must be > 0.\");\n      }\n\n      if (ys.cols() != x.size()) {\n        throw std::invalid_argument(\"The number of columns of ys must be equal to the size of x.\");\n      }\n\n      // add a dummy datapoint at the end\n      matrix_t ys_ext(ys.rows(), newsize);\n      ys_ext << ys, ys.col(ys.cols() - 1);\n\n      coefLists.reserve(static_cast<std::size_t>(ys_ext.rows()));\n\n      for (Eigen::Index i = 0; i < ys_ext.rows(); i++) {\n        coefLists.push_back(generateCoeffs(x_ext, ys_ext.row(i)));\n      }\n    } else {\n      static_assert(\n        is_eigen_dense_v<typename T2::value_type>&& T2::value_type::IsVectorAtCompileTime,\n        \"ys must be a container of Eigen::DenseBase vector objects\");\n\n      if (ys.size() < 1) {\n        throw std::invalid_argument(\"Dimension of the data must be > 0.\");\n      }\n\n      coefLists.reserve(ys.size());\n\n      for (auto & y : ys) {\n        // add a dummy datapoint at the end\n        row_t y_ext(newsize);\n        y_ext << y, y(y.size() - 1);\n        coefLists.push_back(generateCoeffs(x_ext, std::move(y_ext)));\n      }\n    }\n\n    return PiecewisePolyND(std::move(x_ext), std::move(coefLists));\n  }\n\nprotected:\n  template<typename T1, typename T2>\n  static matrix_t generateCoeffs(\n    const Eigen::DenseBase<T1> & x,\n    const Eigen::DenseBase<T2> & y)\n  {\n    static_assert(\n      T1::IsVectorAtCompileTime && T2::IsVectorAtCompileTime,\n      \"x and y must be vectors.\");\n\n    if (x.size() != y.size()) {\n      throw std::invalid_argument(\"Each element of ys must have the same size as x.\");\n    }\n\n    Eigen::Index nj = x.size() - 1;\n    matrix_t coeffs(1, nj);\n\n    for (Eigen::Index i = 0; i < nj; i++) {\n      coeffs(0, i) = y[i];\n    }\n\n    return coeffs;\n  }\n};\n\n}  // namespace cbr\n\n#endif  // CBR_MATH__INTERP__PIECEWISE_CONSTANT_HPP_\n", "meta": {"hexsha": "ecef9c9f9d172fece4b2d90dfc11406a340d6ea7", "size": 4152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_math/interp/piecewise_constant.hpp", "max_stars_repo_name": "yamaha-bps/cbr_math", "max_stars_repo_head_hexsha": "cf1ad7d4661f4b0063d07e00a4e0052454518931", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T17:41:16.000Z", "max_issues_repo_path": "include/cbr_math/interp/piecewise_constant.hpp", "max_issues_repo_name": "yamaha-bps/cbr_math", "max_issues_repo_head_hexsha": "cf1ad7d4661f4b0063d07e00a4e0052454518931", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cbr_math/interp/piecewise_constant.hpp", "max_forks_repo_name": "yamaha-bps/cbr_math", "max_forks_repo_head_hexsha": "cf1ad7d4661f4b0063d07e00a4e0052454518931", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6153846154, "max_line_length": 99, "alphanum_fraction": 0.6112716763, "num_tokens": 1260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.503922784448847}}
{"text": "/*    This file is part of the Gudhi Library. The Gudhi library \n *    (Geometric Understanding in Higher Dimensions) is a generic C++ \n *    library for computational topology.\n *\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2014  INRIA Saclay (France)\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#include <gudhi/reader_utils.h>\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/distance_functions.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Persistent_cohomology.h>\n\n#include <boost/program_options.hpp>\n\n#include <string>\n\nusing namespace Gudhi;\nusing namespace Gudhi::persistent_cohomology;\n\ntypedef int Vertex_handle;\ntypedef double Filtration_value;\n\nvoid program_options(int argc, char * argv[]\n                     , std::string & simplex_tree_file\n                     , std::string & output_file\n                     , int & p\n                     , Filtration_value & min_persistence);\n\nint main(int argc, char * argv[]) {\n  std::string simplex_tree_file;\n  std::string output_file;\n  int p;\n  Filtration_value min_persistence;\n\n  program_options(argc, argv, simplex_tree_file, output_file, p, min_persistence);\n\n  std::cout << \"Simplex_tree from file=\" << simplex_tree_file.c_str() << \" - output_file=\" << output_file.c_str()\n      << std::endl;\n  std::cout << \"     - p=\" << p << \" - min_persistence=\" << min_persistence << std::endl;\n\n  // Read the list of simplices from a file.\n  Simplex_tree<> simplex_tree;\n\n  std::ifstream simplex_tree_stream(simplex_tree_file);\n  simplex_tree_stream >> simplex_tree;\n\n  std::cout << \"The complex contains \" << simplex_tree.num_simplices() << \" simplices\" << std::endl;\n  std::cout << \"   - dimension \" << simplex_tree.dimension() << std::endl;\n\n  /*\n  std::cout << std::endl << std::endl << \"Iterator on Simplices in the filtration, with [filtration value]:\" << std::endl;\n  for( auto f_simplex : simplex_tree.filtration_simplex_range() )\n  { std::cout << \"   \" << \"[\" << simplex_tree.filtration(f_simplex) << \"] \";\n  for( auto vertex : simplex_tree.simplex_vertex_range(f_simplex) )\n  { std::cout << vertex << \" \"; }\n  std::cout << std::endl;\n  }*/\n\n  // Sort the simplices in the order of the filtration\n  simplex_tree.initialize_filtration();\n\n  // Compute the persistence diagram of the complex\n  Persistent_cohomology< Simplex_tree<>, Field_Zp > pcoh(simplex_tree);\n  // initializes the coefficient field for homology\n  pcoh.init_coefficients(p);\n\n  pcoh.compute_persistent_cohomology(min_persistence);\n\n  // Output the diagram in output_file\n  if (output_file.empty()) {\n    pcoh.output_diagram();\n  } else {\n    std::ofstream out(output_file);\n    pcoh.output_diagram(out);\n    out.close();\n  }\n\n  return 0;\n}\n\nvoid program_options(int argc, char * argv[]\n                     , std::string & simplex_tree_file\n                     , std::string & output_file\n                     , int & p\n                     , Filtration_value & min_persistence) {\n  namespace po = boost::program_options;\n  po::options_description hidden(\"Hidden options\");\n  hidden.add_options()\n      (\"input-file\", po::value<std::string>(&simplex_tree_file),\n       \"Name of file containing a simplex set. Format is one simplex per line (cf. reader_utils.h - read_simplex): Dim1 X11 X12 ... X1d Fil1  \");\n\n  po::options_description visible(\"Allowed options\", 100);\n  visible.add_options()\n      (\"help,h\", \"produce help message\")\n      (\"output-file,o\", po::value<std::string>(&output_file)->default_value(std::string()),\n       \"Name of file in which the persistence diagram is written. Default print in std::cout\")\n      (\"field-charac,p\", po::value<int>(&p)->default_value(11),\n       \"Characteristic p of the coefficient field Z/pZ for computing homology.\")\n      (\"min-persistence,m\", po::value<Filtration_value>(&min_persistence),\n       \"Minimal lifetime of homology feature to be recorded. Default is 0\");\n\n  po::positional_options_description pos;\n  pos.add(\"input-file\", 1);\n\n  po::options_description all;\n  all.add(visible).add(hidden);\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).\n            options(all).positional(pos).run(), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\") || !vm.count(\"input-file\")) {\n    std::cout << std::endl;\n    std::cout << \"Compute the persistent homology with coefficient field Z/pZ \\n\";\n    std::cout << \"of a Rips complex defined on a set of input points.\\n \\n\";\n    std::cout << \"The output diagram contains one bar per line, written with the convention: \\n\";\n    std::cout << \"   p   dim b d \\n\";\n    std::cout << \"where dim is the dimension of the homological feature,\\n\";\n    std::cout << \"b and d are respectively the birth and death of the feature and \\n\";\n    std::cout << \"p is the characteristic of the field Z/pZ used for homology coefficients.\" << std::endl << std::endl;\n\n    std::cout << \"Usage: \" << argv[0] << \" [options] input-file\" << std::endl << std::endl;\n    std::cout << visible << std::endl;\n    std::abort();\n  }\n}\n", "meta": {"hexsha": "eafa3fd5a7766a1bd05210b72efd3d4c8e11f2e4", "size": 5622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/graph-lib/homology/Gudhi/example/Persistent_cohomology/persistence_from_file.cpp", "max_stars_repo_name": "mitxael/SSHIVA", "max_stars_repo_head_hexsha": "2cdcadb2ba49cc47d0860b88378e11a67b2cb8ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-04-12T11:19:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-12T11:19:50.000Z", "max_issues_repo_path": "src/graph-lib/homology/Gudhi/example/Persistent_cohomology/persistence_from_file.cpp", "max_issues_repo_name": "mitxael/SSHIVA", "max_issues_repo_head_hexsha": "2cdcadb2ba49cc47d0860b88378e11a67b2cb8ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graph-lib/homology/Gudhi/example/Persistent_cohomology/persistence_from_file.cpp", "max_forks_repo_name": "mitxael/SSHIVA", "max_forks_repo_head_hexsha": "2cdcadb2ba49cc47d0860b88378e11a67b2cb8ed", "max_forks_repo_licenses": ["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.0416666667, "max_line_length": 145, "alphanum_fraction": 0.6666666667, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5039227717048553}}
{"text": "#include <fstream>\n#include <vector>\n#include <map>\n#include <limits>\n#include <cmath>\n#include <cstdio>\n#include \"boost/tuple/tuple.hpp\" //<boost/tuple/tuple.hpp>\n#include \"boost/foreach.hpp\" // <boost/foreach.hpp>\n#include <armadillo>\n\n#ifndef MLMATH\n#define MLMATH\n\n#include \"MLMath.h\"\n\n#endif\n\n// Warn about use of deprecated functions.\n#define GNUPLOT_DEPRECATE_WARN\n//#include \"plot.h\"\n\n#ifndef M_PI\n#\tdefine M_PI 3.14159265358979323846\n#endif\n\n// http://stackoverflow.com/a/1658429\n#ifdef _WIN32\n\t#include <windows.h>\n\tinline void mysleep(unsigned millis) {\n\t\t::Sleep(millis);\n\t}\n#else\n\t#include <unistd.h>\n\tinline void mysleep(unsigned millis) {\n\t\t::usleep(millis * 1000);\n\t}\n#endif\n\nvoid pause_if_needed() {\n#ifdef _WIN32\n\t// For Windows, prompt for a keystroke before the Gnuplot object goes out of scope so that\n\t// the gnuplot window doesn't get closed.\n\tstd::cout << \"Press enter to exit.\" << std::endl;\n\tstd::cin.get();\n#endif\n}\n\n// Tell MSVC to not warn about using fopen.\n// http://stackoverflow.com/a/4805353/1048959\n#if defined(_MSC_VER) && _MSC_VER >= 1400\n#pragma warning(disable:4996)\n#endif\n\nusing namespace std;\nusing namespace arma;\n\nvoid demo_basic() {\n\tGnuplot gp;\n\t// For debugging or manual editing of commands:\n\t//Gnuplot gp(std::fopen(\"plot.gnu\"));\n\t// or\n\t//Gnuplot gp(\"tee plot.gnu | gnuplot -persist\");\n\n\tstd::vector<std::pair<double, double> > xy_pts_A;\n\tfor(double x=-2; x<2; x+=0.01) {\n\t\tdouble y = x*x*x;\n\t\txy_pts_A.push_back(std::make_pair(x, y));\n\t}\n\n\n\n\tstd::vector<std::pair<double, double> > xy_pts_B;\n\tfor(double alpha=0; alpha<1; alpha+=1.0/24.0) {\n\t\tdouble theta = alpha*2.0*3.14159;\n\t\txy_pts_B.push_back(std::make_pair(cos(theta), sin(theta)));\n\t}\n\n\tgp << \"set xrange [-2:2]\\nset yrange [-2:2]\\n\";\n\tgp << \"plot '-' with lines title 'cubic', '-' with points title 'circle'\\n\";\n\tgp.send1d(xy_pts_A);\n\tgp.send1d(xy_pts_B);\n\n\tpause_if_needed();\n}\n\nvoid demo_binary() {\n\tGnuplot gp;\n\n\tstd::vector<std::pair<double, double> > xy_pts_A;\n\tfor(double x=-2; x<2; x+=0.01) {\n\t\tdouble y = x*x;\n\t\txy_pts_A.push_back(std::make_pair(x, y));\n\t}\n\n\t// std::vector<std::pair<double, double> > xy_pts_B;\n\t// for(double alpha=0; alpha<1; alpha+=1.0/24.0) {\n\t// \tdouble theta = alpha*2.0*3.14159;\n\t// \txy_pts_B.push_back(std::make_pair(cos(theta), sin(theta)));\n\t// }\n\n\tgp << \"set xrange [-2:2]\\nset yrange [-2:2]\\n\";\n\tgp << \"plot '-' binary\" << gp.binFmt1d(xy_pts_A, \"record\") << \"with lines title 'cubic'\\n\";\n\t\t//<< \"'-' binary\" << gp.binFmt1d(xy_pts_B, \"record\") << \"with points title 'circle'\\n\";\n\tgp.sendBinary1d(xy_pts_A);\n\t//gp.sendBinary1d(xy_pts_B);\n\n\tpause_if_needed();\n}\n\nvoid demo_animation() {\n  #ifdef _WIN32\n  \t// No animation demo for Windows.  The problem is that every time the plot\n  \t// is updated, the gnuplot window grabs focus.  So you can't ever focus the\n  \t// terminal window to press Ctrl-C.  The only way to quit is to right-click\n  \t// the terminal window on the task bar and close it from there.  Other than\n  \t// that, it seems to work.\n  \tstd::cout << \"Sorry, the animation demo doesn't work in Windows.\" << std::endl;\n  \treturn;\n  #endif\n\n\tGnuplot gp;\n\n\tstd::cout << \"Press Ctrl-C to quit (closing gnuplot window doesn't quit).\" << std::endl;\n\n\t//gp << \"set yrange [0:100]\\n\";\n  //gp << \"set xrange [0:10]\\n\";\n\n  //default for default animation\n  gp << \"set yrange [-1:1]\\n\";\n\n\tconst int N = 100;\n\tstd::vector<double> pts(N);\n  std::vector<double> pts2(N);\n\n\tdouble theta = 0;\n\n\twhile(1) {\n\n\t\tfor(int i=0; i<N; i++) {\n\t\t\tdouble alpha = (double(i)/N-0.5) * 10;\n\n      //default animations\n\t\t\tpts[i] = sin(alpha*8.0 + theta) * exp(-alpha*alpha/2.0);\n      pts2[i] = sin(alpha*100.0 + theta) * exp(-alpha*alpha/2.0);\n\n      //pts[i] = pow(i,2) + 1;\n      //pts2[i] = i;\n\t\t}\n\n\t\t//gp << \"plot '-' binary\" << gp.binFmt1d(pts, \"array\") << \"with lines notitle\\n\";\n\n    //gp << \"plot '-' binary\" << gp.binFmt1d(pts, \"array\") << \"with lines notitle\\n\";\n\n\n    //working double plot\n    gp << \"plot '-' binary\" << gp.binFmt1d(pts, \"array\")\n\t\t<< \"with lines notitle, '-' binary\" << gp.binFmt1d(pts2, \"array\")\n\t\t<< \"with lines notitle\\n\";\n\n    // gp << \"plot '-' binary\" << gp.binFmt1d(pts, \"array\") << \"with lines notitle, '-' binary\" << gp.binFmt1d(pts2,\"array\") << \"with lines notitle\\n\";\n\n\n\n    //<< \"'-' binary\" << gp.binFmt1d(pts2, \"record\") << \"with points title 'circle'\\n\";\n\n    //gp << \"set xrange [-2:2]\\nset yrange [-2:2]\\n\";\n  \t//gp << \"plot '-' with lines title 'cubic', '-' with points title 'circle'\\n\";\n  \t//gp.send1d(xy_pts_A);\n  \t//gp.send1d(xy_pts_B);\n\n\n\t\tgp.sendBinary1d(pts);\n    gp.sendBinary1d(pts2);\n\t\tgp.flush();\n\n\t\ttheta += 0.2;\n\t\tmysleep(100);\n\t}\n\n}\n\nvoid demo_contour(){\n\n  Gnuplot gp;\n\n\n\tgp << \"set samples 20\\nset isosamples 21\\nset xlabel 'X axis'\\nset ylabel 'Y axis'\\n\"<<\n  \"set zlabel 'Z '' offset 1, 0\\nset view 60, 30, 0.85, 1.1\\nset key at screen 1.0, 0.9\\n\"<<\n  \"set style textbox opaque noborder margins 0.5, 0.5\\n\";\n\n  gp << \"set title 'contour plot'\\nset contour\\n\";\n  gp << \"splot x*y\\n\";\n\n\t//gp << \"plot '-' with lines title 'cubic', '-' with points title 'circle'\\n\";\n\t//gp.send1d(xy_pts_A);\n\t//gp.send1d(xy_pts_B);\n\n\t//gp << \"pause -1\\n\";\n\n\n}\n\nvoid callthis(){\n  cout <<  \"called this\" <<  endl;\n  // demo_binary();\n  demo_animation();\n  //demo_contour();\n  //rm demo_basic();\n}\n\n\ntemplate<class T>\nvoid Plotter<T>::plotInputOutputScatter(arma::mat &hypotheses){\n\n\tcout << \"***Plotting Input Output***\" << endl <<  endl;\n\n\n\tcout << &hypotheses << endl << endl;\n\tcout << hypotheses << endl << endl;\n\n\n\t#ifdef _WIN32\n  \tstd::cout << \"Sorry, the animation demo doesn't work in Windows.\" << std::endl;\n  \treturn;\n  #endif\n\n\n\tGnuplot gp,gp2;\n\tmat x = *this->x;\n\tmat y = *this->y;\n\tmat both;\n\tconst int N = 100;\n\tstd::vector<double> pts(N);\n\n\n\tgp << \"set xrange [0:50]\\nset yrange [0:50]\\n\";\n\n\n\n\nwhile(1) {\n\n\t\tfor(int i=0; i<N; i++) {\n      //default animations\n\t\t\t//\ti * x + 1\n\t\t\tdouble insideSum = 0;\n\t\t\t//cout << \"hypotheses\" << endl;\n\t\t\t//cout << hypotheses << endl;\n\n\t\t\tfor(int j = 0; j < hypotheses.n_rows; j++){\n\t\t\t\tinsideSum += ( hypotheses(j,0) ) * i;\n\t\t\t\t//cout << \"--insideSum \"<< j << \" value: \" << hypotheses(j,0) <<\"--\" << endl;\n\t\t\t\t//cout << insideSum << endl;\n\t\t\t}\n\n\t\t\t//theta + theta * i\n\n\n\n\t\t\tpts[i] = insideSum;\n\t\t\t//cout << pts[i] << endl;\n\n\t\t}\n\n    //working double plot\n    // gp << \"plot '-' binary\" << gp.binFmt1d(pts, \"array\") << \"with lines notitle\";\n\n\t\t//////////\n\n\t\t//cout << \" ---- plotting input and output ----\" << endl;\n\t\t//cout << x << endl;\n\t\t//cout << y << endl;\n\t\t//cout << \" ---- end plotting input and output ----\" << endl;\n\n\t\tfor(int i = 0; i < x.n_rows; i++){\n\t\t\tmat xt = x;\n\t\t\t//remove identity column\n\t\t\t//xt.shed_col(0);\n\t\t\tmat yt = y;\n\t\t\tboth = join_rows(xt,yt);\n\t\t\tboth.save(\"scatter.dat\", raw_ascii);\n\t\t}\n\n\t\t//cout << \"------- Points -----\" << endl;\n\t\t//cout << both << endl;\n\n\t\t//gp << \"set xrange [-10:10]\\nset yrange [-10:10]\\n\";\n\n\t\t//gp << \"set data style points\\n\";\n\t\t//gp << \"plot '-' with lines title 'cubic', '-' with points title 'circle'\\n\";\n\t\t//gp << \"plot \" << gp.binFmt1d(xy_pts_A, \"record\") << \" using 1:2 with points\\n\";\n\n\t\tgp << \"plot '-' binary\"\n\t\t<< gp.binFmt1d(pts, \"array\")\n\t\t<< \"with lines notitle, 'scatter.dat' \\n\";\n\n\t\t//gp << \"plot 'scatter.dat' \\n\";\n\n\t\tpause_if_needed();\n\n\t\tgp.sendBinary1d(pts);\n\t\tgp.flush();\n\n\t\tmysleep(50);\n\n}//while end\n\n\n\t\t///////animations\n\n\n}\n\nvoid demo_3d(){\n\n\tGnuplot gp;\n\n\tstd::cout << \"Press Ctrl-C to quit (closing gnuplot window doesn't quit).\" << std::endl;\n\n\t//gp << \"set yrange [0:100]\\n\";\n  //gp << \"set xrange [0:10]\\n\";\n\n  //default for default animation\n  //gp << \"set yrange [-1:1]\\n\";\n\n\tconst int N = 100;\n\tstd::vector<double> pts(N);\n  std::vector<double> pts2(N);\n\n\tdouble theta = 0;\n\n\twhile(1) {\n\n\t\tfor(int i=0; i<N; i++) {\n\t\t\tdouble alpha = (double(i)/N-0.5) * 10;\n\n      //default animations\n\t\t\tpts[i] = sin(alpha*8.0 + theta) * exp(-alpha*alpha/2.0);\n\n      //pts[i] = pow(i,2) + 1;\n      //pts2[i] = i;\n\t\t}\n\n    //working double plot\n    // gp << \"plot '-' binary\" << gp.binFmt1d(pts, \"array\")\n\t\t// << \"with lines notitle, '-' binary\" << gp.binFmt1d(pts2, \"array\")\n\t\t// << \"with lines notitle\\n\";\n\n\t\t//gp << \"set xrange [-10:10]\\nset yrange [-10:10]\\nset zrange[-10:10]\\nset cbrange[-10:10]\\n\";\n\n\n\t\tgp << \"set samples 20\\nset isosamples 21\\nset xlabel 'Theta_1'\\nset ylabel 'Theta_2'\\n\"\n\t\t<< \"set zlabel 'J'\\nset view 60, 30, 0.85, 1.1\\nset key at screen 1.0, 0.9\\n\"\n\t\t<< \"set style textbox opaque noborder margins 0.5, 0.5\\n\";\n\n\t  gp << \"set title 'Gradient Descent'\\nset pm3d\\n\";\n\n\n\t\tgp << \"unset surface\\n\";\n\n\t\t//\t\t\t\t\t\t\t\t\t\t\t\t  h(x)\t\t\t\t\t\ty\n\t  //gp << \"splot (  (1/(2*3)) * ( ( ((x*0.8)+(y*0.5)) - (x**3) )**2 )  )  \\n\";\n\n\t\t//gp << \"splot \" << gp.binFmt1d(pts, \"array\") << \"  \\n\";\n\t\tgp << \"splot (1/1)*( ( ((x*1.8)+(y*1.5)) - (0.02) )**2 )  \\n\";\n\n\n\n\t\t//gp.sendBinary1d(pts);\n\t\tgp.flush();\n\n\t\ttheta += 0.2;\n\t\tmysleep(1000);\n\t}\n\n\n\n\n}\n\n\n\nvoid demo_3d2(){\n\n  Gnuplot gp;\n\n\t//gp << \"set xrange [-10:10]\\nset yrange [-10:10]\\nset zrange[-10:10]\\nset cbrange[-10:10]\\n\";\n\n\tgp << \"set samples 20\\nset isosamples 21\\nset xlabel 'Theta_1'\\nset ylabel 'Theta_2'\\n\"<<\n  \"set zlabel 'J'\\nset view 60, 30, 0.85, 1.1\\nset key at screen 1.0, 0.9\\n\"<<\n  \"set style textbox opaque noborder margins 0.5, 0.5\\n\";\n\n  gp << \"set title 'Gradient Descent'\\nset pm3d\\n\";\n\n\t//gp << \"set border 4095 front lt black linewidth 1.000 dashtype solid\\n\";\n\t//gp << \"set pm3d implicit at s\\nset pm3d scansbackward\\n\";\n\tgp << \"unset surface\\n\";\n\n\t//\t\t\t\t\t\t\t\t\t\t\t\t  h(x)\t\t\t\t\t\ty\n  //gp << \"splot (  (1/(2*3)) * ( ( ((x*0.8)+(y*0.5)) - (x**3) )**2 )  )  \\n\";\n\n\tgp << \"splot (1/1)*( ( ((x*1.8)+(y*1.5)) - (0.02) )**2 )  \\n\";\n\n\t//gp << \"splot x*y**2 \\n\";\n\n\t//gp << \"plot '-' with lines title 'cubic', '-' with points title 'circle'\\n\";\n\t//gp.send1d(xy_pts_A);\n\t//gp.send1d(xy_pts_B);\n\n\t//gp << \"pause -1\\n\";\n\n\n\n}\n", "meta": {"hexsha": "b7712b581d00cdf768f6fab672bd65804931dfc9", "size": 9771, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "plot.tpp", "max_stars_repo_name": "Jovonni/RealTimeMLLib", "max_stars_repo_head_hexsha": "2155c80cafbee273c04a3e6c30d6ac4b425b7968", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-03-15T16:50:26.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-06T01:54:05.000Z", "max_issues_repo_path": "plot.tpp", "max_issues_repo_name": "Jovonni/RealTimeMLLib", "max_issues_repo_head_hexsha": "2155c80cafbee273c04a3e6c30d6ac4b425b7968", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plot.tpp", "max_forks_repo_name": "Jovonni/RealTimeMLLib", "max_forks_repo_head_hexsha": "2155c80cafbee273c04a3e6c30d6ac4b425b7968", "max_forks_repo_licenses": ["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.5445783133, "max_line_length": 151, "alphanum_fraction": 0.5874526661, "num_tokens": 3414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5039227670388255}}
{"text": "/**\n * This file implements the partial widths for the `SimpleRhNeutrino` model.\n */\n\n#include \"storm/constants.hpp\"\n#include \"storm/rambo.hpp\"\n#include \"storm/simple.hpp\"\n#include \"storm/types.hpp\"\n#include <Pythia8/Basics.h>\n#include <algorithm>\n#include <array>\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n#include <cmath>\n#include <cstddef>\n#include <functional>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_math.h>\n#include <locale>\n#include <numeric>\n#include <stdexcept>\n#include <utility>\n\nnamespace storm {\n\n//=========================\n//---- Two-Body Widths ----\n//=========================\n\nauto width_vr_to_vl_h(double mvr, double theta, int /*genl*/) -> double {\n  if (mvr < kHIGGS_MASS) {\n    return 0.0;\n  }\n  return ((-pow(kHIGGS_MASS, 2) + pow(mvr, 2)) * pow(theta, 2) *\n          std::abs(pow(kHIGGS_MASS, 2) - pow(mvr, 2))) /\n         (16. * mvr * M_PI * pow(kHIGGS_VEV, 2));\n}\n\nauto width_vr_to_vl_z(double mvr, double theta, int /*genl*/) -> double {\n  if (mvr < kZ_BOSON_MASS) {\n    return 0.0;\n  }\n  return (((pow(mvr, 4) + pow(mvr, 2) * pow(kZ_BOSON_MASS, 2) -\n            2 * pow(kZ_BOSON_MASS, 4)) *\n           kALPHA_EM * pow(theta, 2) *\n           std::abs(pow(mvr, 2) - pow(kZ_BOSON_MASS, 2))) /\n          (16.0 * pow(kCOS_THETA_WEAK, 2) * pow(mvr, 3) *\n           pow(kZ_BOSON_MASS, 2) * pow(kSIN_THETA_WEAK, 2)));\n}\n\nauto width_vr_to_l_w(double mvr, double theta, int genl) -> double {\n\n  if (genl < 0 || genl > 2) {\n    // throw std::invalid_argument(\n    //    \"Invalid generation passed to width_vr_l_w. Use 0, 1 or 2.\");\n    return 0.0;\n  }\n\n  const double ml = kLEPTON_MASSES.at(genl);\n\n  if (mvr < ml + kW_BOSON_MASS) {\n    return 0.0;\n  }\n\n  return (std::sqrt((ml - mvr - kW_BOSON_MASS) * (ml + mvr - kW_BOSON_MASS) *\n                    (ml - mvr + kW_BOSON_MASS) * (ml + mvr + kW_BOSON_MASS)) *\n          (pow(pow(ml, 2) - pow(mvr, 2), 2) +\n           (pow(ml, 2) + pow(mvr, 2)) * pow(kW_BOSON_MASS, 2) -\n           2 * pow(kW_BOSON_MASS, 4)) *\n          kALPHA_EM * pow(theta, 2)) /\n         (16. * pow(mvr, 3) * pow(kW_BOSON_MASS, 2) * pow(kSIN_THETA_WEAK, 2));\n}\n\n//===========================\n//---- Three-Body Widths ----\n//===========================\n\n/**\n * Compute the integration bounds on the Mandelstam variable `s` for three-body\n * phase-space integration.\n * @param m Mass of the decaying particle.\n * @param m1 Mass of final state particle 1.\n * @param m2 Mass of final state particle 2.\n * @param m3 Mass of final state particle 3.\n */\ninline static auto compute_s_bounds(double m, double m1, double m2, double m3)\n    -> std::pair<double, double> {\n  return std::make_pair(pow(m2 + m3, 2), pow(m - m1, 2));\n}\n\n/**\n * Compute the integration bounds on the mandelstam variable t.\n */\ninline static auto compute_t_bounds(double s, double m, double m1, double m2,\n                                    double m3) -> std::pair<double, double> {\n  const double t1 = (pow(m1, 2) * pow(m2, 2) - pow(m1, 2) * pow(m3, 2) +\n                     pow(m1, 2) * s + pow(m2, 2) * s + pow(m3, 2) * s -\n                     pow(s, 2) + pow(m, 2) * (-pow(m2, 2) + pow(m3, 2) + s) -\n                     sqrt(pow(m, 4) + pow(pow(m1, 2) - s, 2) -\n                          2 * pow(m, 2) * (pow(m1, 2) + s)) *\n                         sqrt(pow(m2, 4) + pow(pow(m3, 2) - s, 2) -\n                              2 * pow(m2, 2) * (pow(m3, 2) + s))) /\n                    (2. * s);\n  const double t2 = (pow(m1, 2) * pow(m2, 2) - pow(m1, 2) * pow(m3, 2) +\n                     pow(m1, 2) * s + pow(m2, 2) * s + pow(m3, 2) * s -\n                     pow(s, 2) + pow(m, 2) * (-pow(m2, 2) + pow(m3, 2) + s) +\n                     sqrt(pow(m, 4) + pow(pow(m1, 2) - s, 2) -\n                          2 * pow(m, 2) * (pow(m1, 2) + s)) *\n                         sqrt(pow(m2, 4) + pow(pow(m3, 2) - s, 2) -\n                              2 * pow(m2, 2) * (pow(m3, 2) + s))) /\n                    (2. * s);\n  return (t1 < t2) ? std::make_pair(t1, t2) : std::make_pair(t2, t1);\n}\n\n/**\n * Compute a three-body decay width given the squared matrix element, mass of\n * the decaying particle and final-state particle masses using RAMBO.\n */\nstatic auto compute_width_3body(const SquaredMatrixElement &msqrd,\n                                const double m, std::vector<double> fsp_masses,\n                                size_t num_events)\n    -> std::pair<double, double> {\n\n  if (m < std::accumulate(fsp_masses.begin(), fsp_masses.end(), 0.0)) {\n    return std::make_pair(0.0, 0.0);\n  }\n\n  Rambo rambo{std::move(fsp_masses), m, msqrd};\n  const auto width = rambo.compute_width(num_events);\n  return width;\n}\n\n/**\n * Compute a three-body decay width given a function for the\n * partially-integrated (over Mandelstam variable `t`).\n */\nstatic auto compute_width_3body_quad(gsl_function *integrand, const double m,\n                                     std::array<double, 3> fsp_masses)\n    -> std::pair<double, double> {\n\n  if (m < std::accumulate(fsp_masses.begin(), fsp_masses.end(), 0.0)) {\n    return std::make_pair(0.0, 0.0);\n  }\n\n  gsl_set_error_handler_off();\n\n  auto [s_low, s_high] =\n      compute_s_bounds(m, fsp_masses[0], fsp_masses[1], fsp_masses[2]);\n\n  // Break-points for integration\n  std::vector<double> bpts;\n  bpts.reserve(5);\n  bpts.push_back(s_low);\n  // If MW^2, MZ^2 or MH^2 is in the integration interval, add them to\n  // break-points\n  const double mw2 = kW_BOSON_MASS * kW_BOSON_MASS;\n  const double mz2 = kZ_BOSON_MASS * kZ_BOSON_MASS;\n  const double mh2 = kHIGGS_MASS * kHIGGS_MASS;\n  if (s_low < mw2 && mw2 < s_high) {\n    bpts.push_back(mw2);\n  }\n  if (s_low < mz2 && mz2 < s_high) {\n    bpts.push_back(mz2);\n  }\n  if (s_low < mh2 && mh2 < s_high) {\n    bpts.push_back(mh2);\n  }\n  bpts.push_back(s_high);\n\n  gsl_integration_workspace *w = gsl_integration_workspace_alloc(1000);\n\n  double integral = 0.0;\n  double error = 0.0;\n  gsl_integration_qagp(integrand, bpts.data(), bpts.size(), 0.0, 1e-7, 1000, w,\n                       &integral, &error);\n\n  const double pf = 1.0 / (32.0 * pow(2.0 * M_PI * m, 3));\n  return std::make_pair(std::abs(integral * pf), error * pf);\n}\n\n/**\n * Compute the partial width for a right-handed neutrino to decay into an active\n * neutrino and two up-type quarks.\n * @param mvr Mass of the RH neutrino.\n * @param theta Mixing angle between active and RH neutrino.\n * @param genl Generation of the lepton.\n * @param genq Generation of the down-type quarks.\n * @returns The width and an error estimate.\n */\nauto width_vr_to_vl_u_u(double mvr, double theta, int genl, int genq)\n    -> double {\n  const double mu = kUP_QUARK_MASSES.at(genq);\n  // auto msqrd = [mvr, theta, genq](const std::vector<Pythia8::Vec4> &momenta)\n  // {\n  //  return msqrd_vr_to_vl_u_u(momenta, mvr, theta, genq);\n  //};\n  // auto msqrd = [mvr, theta, genl, genq](double s) {\n  //  return partialy_integrated_msqrd_vr_to_vl_u_u(s, mvr, theta, genl, genq);\n  //};\n\n  PartiallyIntegratedMsqrdParams params{mvr, theta, genl, genq};\n\n  gsl_function integrand;\n  integrand.function = &partialy_integrated_msqrd_vr_to_vl_u_u;\n  integrand.params = &params;\n\n  return compute_width_3body_quad(&integrand, mvr, {0.0, mu, mu}).first;\n}\n\n/**\n * Compute the partial width for a right-handed neutrino to decay into an active\n * neutrino and two down-type quarks.\n * @param mvr Mass of the RH neutrino.\n * @param theta Mixing angle between active and RH neutrino.\n * @param genl Generation of the lepton.\n * @param genq Generation of the up-type quarks.\n * @returns The width and an error estimate.\n */\nauto width_vr_to_vl_d_d(double mvr, double theta, int genl, int genq)\n    -> double {\n  const double md = kDOWN_QUARK_MASSES.at(genq);\n  // auto msqrd = [mvr, theta, genq](const std::vector<Pythia8::Vec4> &momenta)\n  // {\n  //  return msqrd_vr_to_vl_d_d(momenta, mvr, theta, genq);\n  //};\n  // return compute_width_3body(msqrd, mvr, {0.0, md, md}, nevents);\n\n  // auto msqrd = [mvr, theta, genl, genq](double s) {\n  //  return partialy_integrated_msqrd_vr_to_vl_u_u(s, mvr, theta, genl, genq);\n  //};\n\n  PartiallyIntegratedMsqrdParams params{mvr, theta, genl, genq};\n\n  gsl_function integrand;\n  integrand.function = &partialy_integrated_msqrd_vr_to_vl_d_d;\n  integrand.params = &params;\n\n  return compute_width_3body_quad(&integrand, mvr, {0.0, md, md}).first;\n}\n\n/**\n * Compute the partial width for a right-handed neutrino to decay into a charged\n * lepton, an up-type quark and a down-type quark.\n * @param mvr Mass of the RH neutrino.\n * @param theta Mixing angle between active and RH neutrino.\n * @param genl Generation of the lepton.\n * @param genq Generation of the quarks.\n * @returns The width and an error estimate.\n */\nauto width_vr_to_l_u_d(double mvr, double theta, int genl, int genq) -> double {\n  const double ml = kLEPTON_MASSES.at(genl);\n  const double mu = kUP_QUARK_MASSES.at(genq);\n  const double md = kDOWN_QUARK_MASSES.at(genq);\n  // auto msqrd = [mvr, theta, genl,\n  //              genq](const std::vector<Pythia8::Vec4> &momenta) {\n  //  return msqrd_vr_to_l_u_d(momenta, mvr, theta, genl, genq);\n  //};\n  // return compute_width_3body(msqrd, mvr, {ml, mu, md}, nevents);\n\n  // auto msqrd = [mvr, theta, genl, genq](double s) {\n  //  return partialy_integrated_msqrd_vr_to_l_u_d(s, mvr, theta, genl, genq);\n  //};\n\n  PartiallyIntegratedMsqrdParams params{mvr, theta, genl, genq};\n\n  gsl_function integrand;\n  integrand.function = &partialy_integrated_msqrd_vr_to_vl_d_d;\n  integrand.params = &params;\n\n  return compute_width_3body_quad(&integrand, mvr, {ml, mu, md}).first;\n}\n\n/**\n * Compute the partial width for a right-handed neutrino to decay into an active\n * neutrino, and two charged leptons with different generations than neutrino.\n * @param mvr Mass of the RH neutrino.\n * @param theta Mixing angle between active and RH neutrino.\n * @param genl Generation of the neutrino.\n * @param genlp Generation of charged leptons.\n * @returns The width.\n */\nauto width_vr_to_vl_lp_lp(double mvr, double theta, int genl, int genlp)\n    -> double {\n\n  const double mlp = kLEPTON_MASSES.at(genlp);\n\n  PartiallyIntegratedMsqrdParams params{mvr, theta, genl, genlp};\n\n  gsl_function integrand;\n  integrand.function = &partialy_integrated_msqrd_vr_to_vl_lp_lp;\n  integrand.params = &params;\n\n  return compute_width_3body_quad(&integrand, mvr, {0.0, mlp, mlp}).first;\n}\n\n/**\n * Compute the partial width for a right-handed neutrino to decay into an active\n * neutrino, and two charged leptons with different generations than neutrino.\n * @param mvr Mass of the RH neutrino.\n * @param theta Mixing angle between active and RH neutrino.\n * @param genl Generation of the neutrino.\n * @param genlp Generation of charged leptons.\n * @returns The width.\n */\nauto width_vr_to_vlp_lp_l(double mvr, double theta, int genl, int genlp)\n    -> double {\n\n  const double ml = kLEPTON_MASSES.at(genl);\n  const double mlp = kLEPTON_MASSES.at(genlp);\n\n  PartiallyIntegratedMsqrdParams params{mvr, theta, genl, genlp};\n\n  gsl_function integrand;\n  integrand.function = &partialy_integrated_msqrd_vr_to_vlp_lp_l;\n  integrand.params = &params;\n\n  return compute_width_3body_quad(&integrand, mvr, {0.0, mlp, ml}).first;\n}\n\n/**\n * Compute the partial width for a right-handed neutrino to decay into an active\n * neutrino, and two charged leptons with of the same generation as neutrino.\n * @param mvr Mass of the RH neutrino.\n * @param theta Mixing angle between active and RH neutrino.\n * @param genl Generation of the final-state leptons.\n * @returns The width.\n */\nauto width_vr_to_vl_l_l(double mvr, double theta, int genl) -> double {\n\n  const double ml = kLEPTON_MASSES.at(genl);\n\n  PartiallyIntegratedMsqrdParams params{mvr, theta, genl, -1};\n\n  gsl_function integrand;\n  integrand.function = &partialy_integrated_msqrd_vr_to_vl_l_l;\n  integrand.params = &params;\n\n  return compute_width_3body_quad(&integrand, mvr, {0.0, ml, ml}).first;\n}\n\n/**\n * Compute the partial width for a right-handed neutrino to decay into a three\n * active neutrinos, all of the same generation.\n * @param mvr Mass of the RH neutrino.\n * @param theta Mixing angle between active and RH neutrino.\n * @param genl Generation of the final-state leptons.\n * @returns The width.\n */\nauto width_vr_to_vl_vl_vl(double mvr, double theta, int /*genl*/) -> double {\n\n  PartiallyIntegratedMsqrdParams params{mvr, theta, -1, -1};\n\n  gsl_function integrand;\n  integrand.function = &partialy_integrated_msqrd_vr_to_vl_vl_vl;\n  integrand.params = &params;\n\n  // Extra factor of 1 / 6 us for identical final state particles.\n  return compute_width_3body_quad(&integrand, mvr, {0.0, 0.0, 0.0}).first / 6.0;\n}\n\n} // namespace storm\n", "meta": {"hexsha": "4d506bd965e5c5ef82a637366e7808c926842bd5", "size": 12668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simple/widths.cpp", "max_stars_repo_name": "LoganAMorrison/Storm", "max_stars_repo_head_hexsha": "b189f276064a904d1792a10249fa3555237e3062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simple/widths.cpp", "max_issues_repo_name": "LoganAMorrison/Storm", "max_issues_repo_head_hexsha": "b189f276064a904d1792a10249fa3555237e3062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simple/widths.cpp", "max_forks_repo_name": "LoganAMorrison/Storm", "max_forks_repo_head_hexsha": "b189f276064a904d1792a10249fa3555237e3062", "max_forks_repo_licenses": ["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.9944751381, "max_line_length": 80, "alphanum_fraction": 0.6455636249, "num_tokens": 4021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.5037495312406753}}
{"text": "//  (C) Copyright Victor Ananyev 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 <random>\n#include <vector>\n#include <boost/math/distributions.hpp>\n#include <benchmark/benchmark.h>\n\n\ntemplate <class Z, template<typename> class dist >\nvoid test_mode_2param(benchmark::State& state)\n{\n    using boost::math::normal_distribution;\n\n    std::random_device rd;\n    std::mt19937_64 mt(rd());\n    std::normal_distribution<Z> noise(0., 1E-6);\n\n    for (auto _ : state)\n    {\n        state.PauseTiming();\n        Z p1 = state.range(0) + noise(mt);\n        Z p2 = state.range(1) + noise(mt);\n        dist<Z> the_dist(p1, p2);\n        state.ResumeTiming();\n        try {\n            benchmark::DoNotOptimize(mode(the_dist));\n        }\n        catch (boost::wrapexcept<boost::math::evaluation_error>& e) {\n            state.SkipWithError(e.what());\n            break;\n        }\n    }\n}\n\n\nstatic void fixed_ratio_2args(benchmark::internal::Benchmark* b, long double left_div_right, std::vector<int64_t> lefts) {\n    for (const long double &left: lefts) {\n        b->Args({static_cast<int64_t>(left), static_cast<int64_t>((left/left_div_right))});\n    }\n}\n\n\nusing boost::math::non_central_chi_squared_distribution;\n\nBENCHMARK_TEMPLATE(test_mode_2param, long double, non_central_chi_squared_distribution)->ArgsProduct({\n    {2, 15, 50},\n    benchmark::CreateRange(4, 1024, /*multi=*/2)\n})->Name(\"fixed_k\");\n\nBENCHMARK_TEMPLATE(test_mode_2param, long double, non_central_chi_squared_distribution)->ArgsProduct({\n    benchmark::CreateRange(4, 4096, /*multi=*/2),\n    {1, 30, 100, 500}\n})->Name(\"fixed_nc\");\n\nBENCHMARK_TEMPLATE(test_mode_2param, long double, non_central_chi_squared_distribution)\n    -> Apply([](benchmark::internal::Benchmark*b) {\n                fixed_ratio_2args(b, 0.05, benchmark::CreateRange(4, 4096, /*multi=*/2));\n    }) -> Name(\"fixed_scale_0_05\");\n\nBENCHMARK_TEMPLATE(test_mode_2param, long double, non_central_chi_squared_distribution)\n    -> Apply([](benchmark::internal::Benchmark*b) {\n                fixed_ratio_2args(b, 0.15, benchmark::CreateRange(4, 4096, /*multi=*/2));\n    }) -> Name(\"fixed_scale_0_15\");\n\nBENCHMARK_TEMPLATE(test_mode_2param, long double, non_central_chi_squared_distribution)\n    -> Apply([](benchmark::internal::Benchmark*b) {\n                fixed_ratio_2args(b, 0.25, benchmark::CreateRange(4, 4096, /*multi=*/2));\n    }) -> Name(\"fixed_scale_0_25\");\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "0ae42f322b79ad2a1639db15b10a2244c6286662", "size": 2568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reporting/performance/test_distributions_mode.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": "reporting/performance/test_distributions_mode.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": "reporting/performance/test_distributions_mode.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": 34.7027027027, "max_line_length": 122, "alphanum_fraction": 0.675623053, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.503749522231201}}
{"text": "#include <boost/python/module.hpp>\n#include <boost/python/def.hpp>\n#include <dials/array_family/reflection_table.h>\n\nnamespace xfel {\nnamespace merging {\nnamespace error_model {\nnamespace sdfac_refine {\n\ntypedef\n scitbx::af::versa<cctbx::miller::index<>, scitbx::af::flex_grid<> > shared_miller;\n\nusing namespace dials::af;\n\nstatic scitbx::af::shared<double>\ncompute_normalized_deviations(reflection_table ISIGI, shared_miller hkl_list) {\n  /*\n   * This formulation of the normalized deviations of a set of intensities and sigmas is similar to that\n   * described in Evans 2011, but includes the nn term as currently implmented by aimless\n   *\n   */\n  SCITBX_ASSERT(ISIGI.contains(\"scaled_intensity\"));\n  SCITBX_ASSERT(ISIGI.contains(\"isigi\"));\n  SCITBX_ASSERT(ISIGI.contains(\"miller_id\"));\n\n  scitbx::af::shared<double>         result(ISIGI.size(), 0);\n  scitbx::af::shared<bool>           accepted(ISIGI.size(), false);\n  scitbx::af::shared<double>         sigmas(ISIGI.size(), 0);\n\n  scitbx::af::shared<double>         isum(hkl_list.size(), 0);\n  scitbx::af::shared<double>         n_accept(hkl_list.size(), 0);\n\n  scitbx::af::const_ref<double>      scaled_intensity = ISIGI[\"scaled_intensity\"];\n  scitbx::af::const_ref<double>      isigi = ISIGI[\"isigi\"];\n  scitbx::af::const_ref<std::size_t> miller_id = ISIGI[\"miller_id\"];\n\n  for (std::size_t i = 0; i < ISIGI.size(); i++) {\n    // scaled intensity (iobs/slope)\n    // corrected sigma (original sigma/slope)\n    accepted[i] = isigi[i] != 0;\n    if (isigi[i] == 0)\n      continue;\n\n    sigmas[i] = scaled_intensity[i] / isigi[i];\n    accepted[i] = sigmas[i] > 0;\n    if (sigmas[i] <= 0)\n      continue;\n\n    isum[miller_id[i]] += scaled_intensity[i];\n    n_accept[miller_id[i]]++;\n  }\n\n  scitbx::af::shared<double> nn(hkl_list.size(), 0);\n  for (std::size_t i = 0; i < hkl_list.size(); i++) {\n    if (n_accept[i] > 0) {\n      nn[i] = std::sqrt((n_accept[i]-1.0)/n_accept[i]);\n    }\n  }\n\n  for (std::size_t i = 0; i < ISIGI.size(); i++) {\n    if (!accepted[i]) continue;\n\n    std::size_t n = n_accept[miller_id[i]];\n    double meanIprime = (isum[miller_id[i]]-scaled_intensity[i]) / (n>1 ? (n-1) : 1);\n    result[i] = nn[miller_id[i]] * (scaled_intensity[i] - meanIprime) / sigmas[i];\n  }\n  return result;\n}\n\nvoid\napply_sd_error_params(reflection_table ISIGI, const double sdfac, const double sdb, const double sdadd, const bool squared_params) {\n  /*\n   * Apply a set of sd params (sdfac, sdb and sdd) to an ISIGI reflection table\n\n   Squared not only uses the squared formulation of sigma', but also fixes 2 bugs:\n   1) Use meanI not meanIprime\n   2) When returning isigi, don't multiply by slope\n\n   If using squared, it is assumed that sdfac, sdb and sdadd have already been squared\n   */\n  SCITBX_ASSERT(ISIGI.contains(\"scaled_intensity\"));\n  SCITBX_ASSERT(ISIGI.contains(\"isigi\"));\n  SCITBX_ASSERT(ISIGI.contains(\"slope\"));\n  SCITBX_ASSERT(ISIGI.contains(\"miller_id\"));\n\n  scitbx::af::const_ref<double>      scaled_intensity = ISIGI[\"scaled_intensity\"];\n  scitbx::af::ref<double>            isigi = ISIGI[\"isigi\"];\n  scitbx::af::const_ref<double>      slope = ISIGI[\"slope\"];\n  scitbx::af::shared<double>         sigmas(ISIGI.size(), 0);\n  scitbx::af::const_ref<std::size_t> miller_id = ISIGI[\"miller_id\"];\n\n  std::size_t max_miller_id = scitbx::af::max(miller_id);\n  scitbx::af::shared<std::size_t>    n_refl(max_miller_id+1, 0);\n  scitbx::af::shared<double>         isum(max_miller_id+1, 0);\n\n  for (std::size_t i = 0; i < ISIGI.size(); i++) {\n    // scaled intensity (iobs/slope)\n    // corrected sigma (original sigma/slope)\n    sigmas[i] = scaled_intensity[i] / isigi[i];\n\n    isum[miller_id[i]] += scaled_intensity[i];\n    n_refl[miller_id[i]]++;\n  }\n\n  double tmp = 0;\n  double sigma_corrected = 0;\n  for (std::size_t i = 0; i < ISIGI.size(); i++) {\n    // apply correction parameters\n    if (squared_params) {\n      // compute meanI, which is the mean of all observations of this hkl\n      double meanI = isum[miller_id[i]] / n_refl[miller_id[i]];\n      tmp = std::pow(sigmas[i],2) + sdb * meanI + sdadd * std::pow(meanI,2);\n    }\n    else {\n      // compute meanIprime, which for each observation, is the mean of all other observations of this hkl\n      double meanIprime = (isum[miller_id[i]]-scaled_intensity[i]) / (n_refl[miller_id[i]]>1 ? (n_refl[miller_id[i]]-1) : 1);\n      tmp = std::pow(sigmas[i],2) + sdb * meanIprime + std::pow(sdadd*meanIprime,2);\n    }\n\n    // avoid rare negatives\n    double minimum = 0.1 * std::pow(sigmas[i],2);\n    if (tmp < minimum)\n      tmp = minimum;\n\n    if (squared_params) {\n      sigma_corrected = std::sqrt(sdfac * tmp);\n      SCITBX_ASSERT(sigma_corrected != 0.0);\n      isigi[i] = scaled_intensity[i] / sigma_corrected;\n    }\n    else {\n      sigma_corrected = sdfac * std::sqrt(tmp);\n      SCITBX_ASSERT(sigma_corrected != 0.0);\n      isigi[i] = scaled_intensity[i] * slope[i]/ sigma_corrected;\n    }\n  }\n}\n\nnamespace boost_python { namespace {\n  void\n  init_module() {\n    using namespace boost::python;\n    def(\"compute_normalized_deviations\", &compute_normalized_deviations);\n    def(\"apply_sd_error_params\", &apply_sd_error_params);\n}\n}}\n}}}} // namespace\n\nBOOST_PYTHON_MODULE(xfel_sdfac_refine_ext)\n{\n  xfel::merging::error_model::sdfac_refine::boost_python::init_module();\n\n}\n", "meta": {"hexsha": "a2440f0c04782a3fec225fc8be75b183857e05b8", "size": 5296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xfel/merging/algorithms/error_model/sdfac_refine_ext.cpp", "max_stars_repo_name": "jbeilstenedmands/cctbx_project", "max_stars_repo_head_hexsha": "c228fb15ab10377f664c39553d866281358195aa", "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": "xfel/merging/algorithms/error_model/sdfac_refine_ext.cpp", "max_issues_repo_name": "jbeilstenedmands/cctbx_project", "max_issues_repo_head_hexsha": "c228fb15ab10377f664c39553d866281358195aa", "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": "xfel/merging/algorithms/error_model/sdfac_refine_ext.cpp", "max_forks_repo_name": "jbeilstenedmands/cctbx_project", "max_forks_repo_head_hexsha": "c228fb15ab10377f664c39553d866281358195aa", "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": 34.614379085, "max_line_length": 132, "alphanum_fraction": 0.6587990937, "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563823, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5037495199788322}}
{"text": "// Copyright  (C)  2007  Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n\n// Version: 1.0\n// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// URL: http://www.orocos.org/kdl\n\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 2.1 of the License, or (at your option) any later version.\n\n// This library 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 GNU\n// Lesser General Public License for more details.\n\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n#ifndef KDL_CHAIN_IKSOLVERVEL_WDLS_HPP\n#define KDL_CHAIN_IKSOLVERVEL_WDLS_HPP\n\n#include \"chainiksolver.hpp\"\n#include \"chainjnttojacsolver.hpp\"\n#include <Eigen/Core>\n\nnamespace KDL\n{\n    /**\n     * Implementation of a inverse velocity kinematics algorithm based\n     * on the weighted pseudo inverse with damped least-square to calculate the velocity\n     * transformation from Cartesian to joint space of a general\n     * KDL::Chain. It uses a svd-calculation based on householders\n     * rotations.\n     *\n     * J# = M_q*Vb*pinv_dls(Db)*Ub'*M_x\n     *\n     * where B = Mx*J*Mq\n     *\n     * and B = Ub*Db*Vb' is the SVD decomposition of B\n     *\n     * Mq and Mx represent, respectively, the joint-space and task-space weighting\n     * matrices.\n     * Please refer to the documentation of setWeightJS(const Eigen::MatrixXd& Mq)\n     * and setWeightTS(const Eigen::MatrixXd& Mx) for details on the effects of\n     * these matrices.\n     *\n     * For more details on Weighted Pseudo Inverse, see :\n     * 1) [Ben Israel 03] A. Ben Israel & T.N.E. Greville.\n     * Generalized Inverses : Theory and Applications,\n     * second edition. Springer, 2003. ISBN 0-387-00293-6.\n     *\n     * 2) [Doty 93] K. L. Doty, C. Melchiorri & C. Boniveto.\n     * A theory of generalized inverses applied to Robotics.\n     * The International Journal of Robotics Research,\n     * vol. 12, no. 1, pages 1-19, february 1993.\n     *\n     *\n     * @ingroup KinematicFamily\n     */\n    class ChainIkSolverVel_wdls : public ChainIkSolverVel\n    {\n    public:\n        /// solution converged but (pseudo)inverse is singular\n        static const int E_CONVERGE_PINV_SINGULAR = +100;\n\n        /**\n         * Constructor of the solver\n         *\n         * @param chain the chain to calculate the inverse velocity\n         * kinematics for\n         * @param eps if a singular value is below this value, its\n         * inverse is set to zero, default: 0.00001\n         * @param maxiter maximum iterations for the svd calculation,\n         * default: 150\n         *\n         */\n\n        explicit ChainIkSolverVel_wdls(const Chain& chain,double eps=0.00001,int maxiter=150);\n        //=ublas::identity_matrix<double>\n        ~ChainIkSolverVel_wdls();\n\n        /**\n         * Find an output joint velocity \\a qdot_out, given a starting joint pose\n         * \\a q_init and a desired cartesian velocity \\a v_in\n         *\n         * @return\n         *  E_NOERROR=svd solution converged in maxiter\n         *  E_SVD_FAILED=svd solution failed\n         *  E_CONVERGE_PINV_SINGULAR=svd solution converged but (pseudo)inverse singular\n         *\n         * @note if E_CONVERGE_PINV_SINGULAR returned then converged and can\n         * continue motion, but have degraded solution\n         *\n         * @note If E_SVD_FAILED returned, then getSvdResult() returns the error\n         * code from the SVD algorithm.\n\t\t */\n        virtual int CartToJnt(const JntArray& q_in, const Twist& v_in, JntArray& qdot_out);\n        /**\n         * not (yet) implemented.\n         *\n         */\n        virtual int CartToJnt(const JntArray& q_init, const FrameVel& v_in, JntArrayVel& q_out){return -1;};\n\n        /**\n         * Set the joint space weighting matrix\n         *\n         * @param weight_js joint space weighting symmetric matrix,\n         * default : identity.  M_q : This matrix being used as a\n         * weight for the norm of the joint space speed it HAS TO BE\n         * symmetric and positive definite. We can actually deal with\n         * matrices containing a symmetric and positive definite block\n         * and 0s otherwise. Taking a diagonal matrix as an example, a\n         * 0 on the diagonal means that the corresponding joints will\n         * not contribute to the motion of the system. On the other\n         * hand, the bigger the value, the most the corresponding\n         * joint will contribute to the overall motion. The obtained\n         * solution q_dot will actually minimize the weighted norm\n         * sqrt(q_dot'*(M_q^-2)*q_dot). In the special case we deal\n         * with, it does not make sense to invert M_q but what is\n         * important is the physical meaning of all this : a joint\n         * that has a zero weight in M_q will not contribute to the\n         * motion of the system and this is equivalent to saying that\n         * it gets an infinite weight in the norm computation.  For\n         * more detailed explanation : vincent.padois@upmc.fr\n         *\n         * @return success/error code\n         */\n        int setWeightJS(const Eigen::MatrixXd& Mq);\n\n        /**\n         * Set the task space weighting matrix\n         *\n         * @param weight_ts task space weighting symmetric matrix,\n         * default: identity M_x : This matrix being used as a weight\n         * for the norm of the error (in terms of task space speed) it\n         * HAS TO BE symmetric and positive definite. We can actually\n         * deal with matrices containing a symmetric and positive\n         * definite block and 0s otherwise. Taking a diagonal matrix\n         * as an example, a 0 on the diagonal means that the\n         * corresponding task coordinate will not be taken into\n         * account (ie the corresponding error can be really big). If\n         * the rank of the jacobian is equal to the number of task\n         * space coordinates which do not have a 0 weight in M_x, the\n         * weighting will actually not impact the results (ie there is\n         * an exact solution to the velocity inverse kinematics\n         * problem). In cases without an exact solution, the bigger\n         * the value, the most the corresponding task coordinate will\n         * be taken into account (ie the more the corresponding error\n         * will be reduced). The obtained solution will minimize the\n         * weighted norm sqrt(|x_dot-Jq_dot|'*(M_x^2)*|x_dot-Jq_dot|).\n         * For more detailed explanation : vincent.padois@upmc.fr\n         *\n         * @return success/error code\n         */\n        int setWeightTS(const Eigen::MatrixXd& Mx);\n\n        /**\n         * Set lambda\n         */\n        void setLambda(const double lambda);\n        /**\n         * Set eps\n         */\n        void setEps(const double eps_in);\n        /**\n         * Set maxIter\n         */\n        void setMaxIter(const int maxiter_in);\n\n        /**\n         * Request the number of singular values of the jacobian that are < eps;\n         * if the number of near zero singular values is > jac.col()-jac.row(),\n         * then the jacobian pseudoinverse is singular\n         */\n        unsigned int getNrZeroSigmas()const {return nrZeroSigmas;};\n\n        /**\n         * Request the minimum of the first six singular values\n         */\n        double getSigmaMin()const {return sigmaMin;};\n\n        /**\n         * Request the six singular values of the Jacobian\n         */\n        int getSigma(Eigen::VectorXd& Sout);\n\n        /**\n         * Request the value of eps\n         */\n        double getEps()const {return eps;};\n\n        /**\n         * Request the value of lambda for the minimum\n         */\n        double getLambda()const {return lambda;};\n\n        /**\n         * Request the scaled value of lambda for the minimum\n         * singular value 1-6\n         */\n        double getLambdaScaled()const {return lambda_scaled;};\n\n        /**\n         * Retrieve the latest return code from the SVD algorithm\n         * @return 0 if CartToJnt() not yet called, otherwise latest SVD result code.\n         */\n        int getSVDResult()const {return svdResult;};\n\n        /// @copydoc KDL::SolverI::strError()\n        virtual const char* strError(const int error) const;\n\n        /// @copydoc KDL::SolverI::updateInternalDataStructures()\n        virtual void updateInternalDataStructures();\n\n    private:\n        const Chain& chain;\n        ChainJntToJacSolver jnt2jac;\n        unsigned int nj;\n        Jacobian jac;\n        Eigen::MatrixXd U;\n        Eigen::VectorXd S;\n        Eigen::MatrixXd V;\n        double eps;\n        int maxiter;\n        Eigen::VectorXd tmp;\n        Eigen::MatrixXd tmp_jac;\n        Eigen::MatrixXd tmp_jac_weight1;\n        Eigen::MatrixXd tmp_jac_weight2;\n        Eigen::MatrixXd tmp_ts;\n        Eigen::MatrixXd tmp_js;\n        Eigen::MatrixXd weight_ts;\n        Eigen::MatrixXd weight_js;\n        double lambda;\n\t\tdouble lambda_scaled;\n\t\tunsigned int nrZeroSigmas ;\n\t\tint svdResult;\n\t\tdouble sigmaMin;\n    };\n}\n#endif\n\n", "meta": {"hexsha": "604048b87e937f7b99ec7608d37c1f6565d3f8f6", "size": 9427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/kdl/kdl/chainiksolvervel_wdls.hpp", "max_stars_repo_name": "Laragervaise/AR-mobile-app-for-robots", "max_stars_repo_head_hexsha": "f8b6581bb21a3956893d6552913cc606cc063992", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-14T12:33:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T07:14:13.000Z", "max_issues_repo_path": "melodic/src/orocos_kinematics_dynamics/orocos_kdl/src/chainiksolvervel_wdls.hpp", "max_issues_repo_name": "disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA", "max_issues_repo_head_hexsha": "3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-08T10:26:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T10:31:11.000Z", "max_forks_repo_path": "melodic/src/orocos_kinematics_dynamics/orocos_kdl/src/chainiksolvervel_wdls.hpp", "max_forks_repo_name": "disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA", "max_forks_repo_head_hexsha": "3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0", "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.4775510204, "max_line_length": 108, "alphanum_fraction": 0.6350906969, "num_tokens": 2266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954683, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5037155812941386}}
{"text": "#include \"sbs/rendering/trackball_rotation_adapter.h\"\n\n#include <Eigen/Geometry>\n\nnamespace sbs {\nnamespace rendering {\nnamespace detail {\n\nstatic Eigen::Vector3d geometric_center(common::dynamic_surface_mesh const& mesh)\n{\n    Eigen::Vector3d mu{0., 0., 0.};\n\n    for (std::size_t vi = 0u; vi < mesh.vertex_count(); ++vi)\n    {\n        auto const& v = mesh.vertex(vi);\n        mu += v.position;\n    }\n\n    mu = mu.array() / mesh.vertex_count();\n    return mu;\n}\n\nstatic void rotate(common::dynamic_surface_mesh& mesh, Eigen::Matrix3d const& rotation)\n{\n    for (std::size_t vi = 0u; vi < mesh.vertex_count(); ++vi)\n    {\n        auto& v            = mesh.mutable_vertex(vi);\n        Eigen::Vector3d& p = v.position;\n        p                  = rotation * p;\n    }\n}\n\nstatic void translate(common::dynamic_surface_mesh& mesh, Eigen::Vector3d const& t)\n{\n    for (std::size_t vi = 0u; vi < mesh.vertex_count(); ++vi)\n    {\n        auto& v = mesh.mutable_vertex(vi);\n        v.position += t;\n    }\n}\n\n} // namespace detail\n\ntrackball_rotation_adapter_t::trackball_rotation_adapter_t(\n    common::dynamic_surface_mesh* mesh,\n    double rotation_speed,\n    double translation_speed)\n    : rotated_mesh_(mesh),\n      rotation_speed_(rotation_speed),\n      translation_speed_(translation_speed),\n      pitch_angle_(0.),\n      yaw_angle_(0.),\n      pitch_axis_({1., 0., 0.}),\n      yaw_axis_({0., 0., 1.})\n{\n}\n\ndouble trackball_rotation_adapter_t::rotation_speed() const\n{\n    return rotation_speed_;\n}\n\nvoid trackball_rotation_adapter_t::set_rotation_speed(double speed)\n{\n    rotation_speed_ = speed;\n}\n\ndouble trackball_rotation_adapter_t::translation_speed() const\n{\n    return translation_speed_;\n}\n\nvoid trackball_rotation_adapter_t::set_translation_speed(double speed)\n{\n    translation_speed_ = speed;\n}\n\nvoid trackball_rotation_adapter_t::rotate(double dx, double dy)\n{\n    yaw_angle_   = rotation_speed_ * dx;\n    pitch_angle_ = rotation_speed_ * dy;\n\n    Eigen::AngleAxisd const yaw(yaw_angle_, yaw_axis_);\n    Eigen::AngleAxisd const pitch(pitch_angle_, pitch_axis_);\n    Eigen::Matrix3d const rotation = pitch.toRotationMatrix() * yaw.toRotationMatrix();\n\n    Eigen::Vector3d const geometric_center = detail::geometric_center(*rotated_mesh_);\n    detail::translate(*rotated_mesh_, -geometric_center);\n    detail::rotate(*rotated_mesh_, rotation);\n    detail::translate(*rotated_mesh_, geometric_center);\n}\n\nvoid trackball_rotation_adapter_t::translate(double dx, double dy)\n{\n    Eigen::Vector3d const t            = dx * pitch_axis_ + dy * yaw_axis_;\n    Eigen::Vector3d const displacement = translation_speed_ * t;\n    detail::translate(*rotated_mesh_, displacement);\n}\n\nvoid trackball_rotation_adapter_t::set_pitch_axis(Eigen::Vector3d const& pitch_axis)\n{\n    pitch_axis_ = pitch_axis.normalized();\n}\n\nvoid trackball_rotation_adapter_t::set_yaw_axis(Eigen::Vector3d const& yaw_axis)\n{\n    yaw_axis_ = yaw_axis.normalized();\n}\n\ncommon::dynamic_surface_mesh* trackball_rotation_adapter_t::mesh() const\n{\n    return rotated_mesh_;\n}\n\ncommon::dynamic_surface_mesh* trackball_rotation_adapter_t::mesh()\n{\n    return rotated_mesh_;\n}\n\n} // namespace rendering\n} // namespace sbs", "meta": {"hexsha": "76026534b3c3ce55c055bf76b4e794ac22ffb162", "size": 3183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rendering/trackball_rotation_adapter.cpp", "max_stars_repo_name": "Q-Minh/soft-body-simulator", "max_stars_repo_head_hexsha": "f41640945df989d8c91d99e8f2e86d6af90211f6", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T01:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T17:35:49.000Z", "max_issues_repo_path": "src/rendering/trackball_rotation_adapter.cpp", "max_issues_repo_name": "Q-Minh/soft-body-simulator", "max_issues_repo_head_hexsha": "f41640945df989d8c91d99e8f2e86d6af90211f6", "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/rendering/trackball_rotation_adapter.cpp", "max_forks_repo_name": "Q-Minh/soft-body-simulator", "max_forks_repo_head_hexsha": "f41640945df989d8c91d99e8f2e86d6af90211f6", "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.305785124, "max_line_length": 87, "alphanum_fraction": 0.7034244423, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.503715578726186}}
{"text": "/******************************************************************************\n\n  This source file is part of the Avogadro project.\n\n  Copyright 2012-2014 Kitware, Inc.\n\n  This source code is released under the New BSD License, (the \"License\").\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n\n******************************************************************************/\n\n#include \"camera.h\"\n\n#include <Eigen/LU>\n\n#include <cmath>\n\nnamespace Avogadro {\nnamespace Rendering {\n\nCamera::Camera()\n  : m_width(0), m_height(0), m_projectionType(Perspective),\n    m_orthographicScale(1.0), m_data(new EigenData)\n{\n  m_data->projection.setIdentity();\n  m_data->modelView.setIdentity();\n}\n\nCamera::Camera(const Camera& o)\n  : m_width(o.m_width), m_height(o.m_height),\n    m_projectionType(o.m_projectionType),\n    m_orthographicScale(o.m_orthographicScale), m_data(new EigenData(*o.m_data))\n{}\n\nCamera& Camera::operator=(const Camera& o)\n{\n  if (this != &o) {\n    m_width = o.m_width;\n    m_height = o.m_height;\n    m_projectionType = o.m_projectionType;\n    m_orthographicScale = o.m_orthographicScale;\n    m_data = std::move(std::unique_ptr<EigenData>(new EigenData(*o.m_data)));\n  }\n\n  return *this;\n}\n\nCamera::~Camera() {}\n\nvoid Camera::translate(const Vector3f& translate_)\n{\n  m_data->modelView.translate(translate_);\n}\n\nvoid Camera::preTranslate(const Vector3f& translate_)\n{\n  m_data->modelView.pretranslate(translate_);\n}\n\nvoid Camera::rotate(float angle, const Vector3f& axis)\n{\n  m_data->modelView.rotate(Eigen::AngleAxisf(angle, axis));\n}\n\nvoid Camera::preRotate(float angle, const Vector3f& axis)\n{\n  m_data->modelView.prerotate(Eigen::AngleAxisf(angle, axis));\n}\n\nvoid Camera::scale(float s)\n{\n  if (m_projectionType == Perspective)\n    m_data->modelView.scale(s);\n  else\n    m_orthographicScale *= s;\n}\n\nvoid Camera::lookAt(const Vector3f& eye, const Vector3f& center,\n                    const Vector3f& up)\n{\n  Vector3f f = (center - eye).normalized();\n  Vector3f u = up.normalized();\n  Vector3f s = f.cross(u).normalized();\n  u = s.cross(f);\n\n  m_data->modelView.setIdentity();\n  m_data->modelView(0, 0) = s.x();\n  m_data->modelView(0, 1) = s.y();\n  m_data->modelView(0, 2) = s.z();\n  m_data->modelView(1, 0) = u.x();\n  m_data->modelView(1, 1) = u.y();\n  m_data->modelView(1, 2) = u.z();\n  m_data->modelView(2, 0) = -f.x();\n  m_data->modelView(2, 1) = -f.y();\n  m_data->modelView(2, 2) = -f.z();\n  m_data->modelView(0, 3) = -s.dot(eye);\n  m_data->modelView(1, 3) = -u.dot(eye);\n  m_data->modelView(2, 3) = f.dot(eye);\n}\n\nfloat Camera::distance(const Vector3f& point) const\n{\n  return (m_data->modelView * point).norm();\n}\n\nVector3f Camera::project(const Vector3f& point) const\n{\n  Eigen::Matrix4f mvp =\n    m_data->projection.matrix() * m_data->modelView.matrix();\n  Vector4f tPoint(point.x(), point.y(), point.z(), 1.0f);\n  tPoint = mvp * tPoint;\n  Vector3f result(\n    static_cast<float>(m_width) * (tPoint.x() / tPoint.w() + 1.0f) / 2.0f,\n    static_cast<float>(m_height) * (tPoint.y() / tPoint.w() + 1.0f) / 2.0f,\n    (tPoint.z() / tPoint.w() + 1.0f) / 2.0f);\n  return result;\n}\n\nVector3f Camera::unProject(const Vector3f& point) const\n{\n  Eigen::Matrix4f mvp =\n    m_data->projection.matrix() * m_data->modelView.matrix();\n  Vector4f result(\n    2.0f * point.x() / static_cast<float>(m_width) - 1.0f,\n    2.0f * (static_cast<float>(m_height) - point.y()) /\n        static_cast<float>(m_height) -\n      1.0f,\n    2.0f * point.z() - 1.0f, 1.0f);\n  result = mvp.matrix().inverse() * result;\n  return Vector3f(result.x() / result.w(), result.y() / result.w(),\n                  result.z() / result.w());\n}\n\nVector3f Camera::unProject(const Vector2f& point,\n                           const Vector3f& reference) const\n{\n  return unProject(Vector3f(point.x(), point.y(), project(reference).z()));\n}\n\nvoid Camera::calculatePerspective(float fieldOfView, float aspectRatio,\n                                  float zNear, float zFar)\n{\n  m_data->projection.setIdentity();\n  float f = 1.0f / std::tan(fieldOfView * float(M_PI) / 360.0f);\n  m_data->projection(0, 0) = f / aspectRatio;\n  m_data->projection(1, 1) = f;\n  m_data->projection(2, 2) = (zNear + zFar) / (zNear - zFar);\n  m_data->projection(2, 3) = (2.0f * zFar * zNear) / (zNear - zFar);\n  m_data->projection(3, 2) = -1;\n  m_data->projection(3, 3) = 0;\n}\n\nvoid Camera::calculatePerspective(float fieldOfView, float zNear, float zFar)\n{\n  calculatePerspective(\n    fieldOfView, static_cast<float>(m_width) / static_cast<float>(m_height),\n    zNear, zFar);\n}\n\nvoid Camera::calculateOrthographic(float left, float right, float bottom,\n                                   float top, float zNear, float zFar)\n{\n  left *= m_orthographicScale;\n  right *= m_orthographicScale;\n  bottom *= m_orthographicScale;\n  top *= m_orthographicScale;\n  m_data->projection.setIdentity();\n  m_data->projection(0, 0) = 2.0f / (right - left);\n  m_data->projection(0, 3) = -(right + left) / (right - left);\n  m_data->projection(1, 1) = 2.0f / (top - bottom);\n  m_data->projection(1, 3) = -(top + bottom) / (top - bottom);\n  m_data->projection(2, 2) = -2.0f / (zFar - zNear);\n  m_data->projection(2, 3) = -(zFar + zNear) / (zFar - zNear);\n  m_data->projection(3, 3) = 1;\n}\n\nvoid Camera::setViewport(int w, int h)\n{\n  m_width = w;\n  m_height = h;\n}\n\nvoid Camera::setProjection(const Eigen::Affine3f& transform)\n{\n  m_data->projection = transform;\n}\n\nvoid Camera::setModelView(const Eigen::Affine3f& transform)\n{\n  m_data->modelView = transform;\n}\n\n} // namespace Rendering\n} // namespace Avogadro\n", "meta": {"hexsha": "edf92ae4096afa5126c476781fe6b2ac180d529a", "size": 5806, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "avogadro/rendering/camera.cpp", "max_stars_repo_name": "serk12/avogadrolibs", "max_stars_repo_head_hexsha": "f2dd0fda7e0d2ca4a0586354ea253cc05242f022", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 244.0, "max_stars_repo_stars_event_min_datetime": "2015-09-09T15:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:44:21.000Z", "max_issues_repo_path": "avogadro/rendering/camera.cpp", "max_issues_repo_name": "serk12/avogadrolibs", "max_issues_repo_head_hexsha": "f2dd0fda7e0d2ca4a0586354ea253cc05242f022", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 670.0, "max_issues_repo_issues_event_min_datetime": "2015-05-08T18:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T19:47:08.000Z", "max_forks_repo_path": "avogadro/rendering/camera.cpp", "max_forks_repo_name": "serk12/avogadrolibs", "max_forks_repo_head_hexsha": "f2dd0fda7e0d2ca4a0586354ea253cc05242f022", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 129.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T01:18:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T08:50:25.000Z", "avg_line_length": 29.03, "max_line_length": 80, "alphanum_fraction": 0.6424388564, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.503715578726186}}
{"text": "//  (C) Copyright 2006 Eric Niebler, Olivier Gygi.\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// Test case for tail_mean.hpp\n\n#include <boost/random.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/numeric/functional/vector.hpp>\n#include <boost/accumulators/numeric/functional/complex.hpp>\n#include <boost/accumulators/numeric/functional/valarray.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/tail_mean.hpp>\n#include <boost/accumulators/statistics/tail_quantile.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace boost::accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    // tolerance in %\n    double epsilon = 1;\n\n    std::size_t n = 100000; // number of MC steps\n    std::size_t c =  10000; // cache size\n\n    typedef accumulator_set<double, stats<tag::non_coherent_tail_mean<right>, tag::tail_quantile<right> > > accumulator_t_right1;\n    typedef accumulator_set<double, stats<tag::non_coherent_tail_mean<left>, tag::tail_quantile<left> > > accumulator_t_left1;\n    typedef accumulator_set<double, stats<tag::coherent_tail_mean<right>, tag::tail_quantile<right> > > accumulator_t_right2;\n    typedef accumulator_set<double, stats<tag::coherent_tail_mean<left>, tag::tail_quantile<left> > > accumulator_t_left2;\n\n    accumulator_t_right1 acc0( right_tail_cache_size = c );\n    accumulator_t_left1 acc1( left_tail_cache_size = c );\n    accumulator_t_right2 acc2( right_tail_cache_size = c );\n    accumulator_t_left2 acc3( left_tail_cache_size = c );\n\n    // a random number generator\n    boost::lagged_fibonacci607 rng;\n\n    for (std::size_t i = 0; i < n; ++i)\n    {\n        double sample = rng();\n        acc0(sample);\n        acc1(sample);\n        acc2(sample);\n        acc3(sample);\n    }\n\n    // check uniform distribution\n    BOOST_CHECK_CLOSE( non_coherent_tail_mean(acc0, quantile_probability = 0.95), 0.975, epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_tail_mean(acc0, quantile_probability = 0.975), 0.9875, epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_tail_mean(acc0, quantile_probability = 0.99), 0.995, epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_tail_mean(acc0, quantile_probability = 0.999), 0.9995, epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_tail_mean(acc1, quantile_probability = 0.05), 0.025, 5*epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_tail_mean(acc1, quantile_probability = 0.025), 0.0125, 6*epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_tail_mean(acc1, quantile_probability = 0.01), 0.005, 8*epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_tail_mean(acc1, quantile_probability = 0.001), 0.0005, 25*epsilon );\n    BOOST_CHECK_CLOSE( tail_mean(acc2, quantile_probability = 0.95), 0.975, epsilon );\n    BOOST_CHECK_CLOSE( tail_mean(acc2, quantile_probability = 0.975), 0.9875, epsilon );\n    BOOST_CHECK_CLOSE( tail_mean(acc2, quantile_probability = 0.99), 0.995, epsilon );\n    BOOST_CHECK_CLOSE( tail_mean(acc2, quantile_probability = 0.999), 0.9995, epsilon );\n    BOOST_CHECK_CLOSE( tail_mean(acc3, quantile_probability = 0.05), 0.025, 5*epsilon );\n    BOOST_CHECK_CLOSE( tail_mean(acc3, quantile_probability = 0.025), 0.0125, 6*epsilon );\n    BOOST_CHECK_CLOSE( tail_mean(acc3, quantile_probability = 0.01), 0.005, 8*epsilon );\n    BOOST_CHECK_CLOSE( tail_mean(acc3, quantile_probability = 0.001), 0.0005, 25*epsilon );\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"tail_mean test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n\n", "meta": {"hexsha": "5132eb2471db2aef47ccf26d6e8357eac5c30ca2", "size": 3976, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/accumulators/test/tail_mean.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/accumulators/test/tail_mean.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/accumulators/test/tail_mean.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": 45.7011494253, "max_line_length": 129, "alphanum_fraction": 0.7120221328, "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5036666055806814}}
{"text": "#include <boost/math/fft.hpp>\n#include <boost/math/fft/bsl_backend.hpp>\n\n#include <complex>\n#include <vector>\n#include <array>\n\nvoid compile_test()\n{   \n    // test same type of iterator\n    std::vector<int> A(3);\n    std::vector<double> B(A.size());\n    \n    // fails static_assert: D and A types are different\n    boost::math::fft::dft(A.begin(),A.end(),B.begin());\n}\n\nint main()\n{\n    compile_test();\n    return 0;\n}\n", "meta": {"hexsha": "5cac6b1dc57ada0c5336df27140722b0e8a00f2c", "size": 420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fft_compile-fail.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/fft_compile-fail.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "test/fft_compile-fail.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 18.2608695652, "max_line_length": 55, "alphanum_fraction": 0.6285714286, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562643, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5036666004005015}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_FUNCTIONS_SCALAR_MNORMFRO_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_SCALAR_MNORMFRO_HPP_INCLUDED\n#include <nt2/linalg/functions/mnormfro.hpp>\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/colon.hpp>\n#include <nt2/include/functions/ismatrix.hpp>\n#include <nt2/include/functions/norm2.hpp>\n#include <nt2/core/container/dsl.hpp>\n#include <nt2/core/container/colon/colon.hpp>\n#include <nt2/linalg/options.hpp>\n#include <nt2/sdk/meta/as_real.hpp>\n#include <nt2/core/container/dsl/forward.hpp>\n#include <boost/assert.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( mnormfro_, tag::cpu_\n                            , (A0)\n                            , (scalar_<unspecified_<A0> >)\n                            )\n  {\n    typedef typename meta::as_real<A0>::type result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      return nt2::abs(a0);\n    }\n\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( mnormfro_, tag::cpu_\n                            , (A0)\n                            , ((ast_<A0, nt2::container::domain>))\n                            )\n  {\n    typedef typename A0::value_type                   type_t;\n    typedef typename meta::as_real<type_t>::type result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      BOOST_ASSERT_MSG(nt2::ismatrix(a0), \"a0 is not a matrix\");\n      return norm2(a0(nt2::_));\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "2e9c807a920155169b02111123b65f82b9dfc004", "size": 1913, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/scalar/mnormfro.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/linalg/include/nt2/linalg/functions/scalar/mnormfro.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/linalg/include/nt2/linalg/functions/scalar/mnormfro.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 34.7818181818, "max_line_length": 80, "alphanum_fraction": 0.5682174595, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5036665952203213}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE test_fft\n#include <boost/test/unit_test.hpp>\n#include <complex>\n#include <stdexcept> \n#include <vector>\n#include <iostream>\n#include <string>\n#include \"../fft.hpp\"\n\ntemplate <typename T> \nstd::vector<std::complex<T> > make_complex(const std::vector<T>& real_values,\n                                           const std::vector<T>& imag_values) {\n    auto n = real_values.size();\n    if (imag_values.size() != n) throw std::runtime_error(\"Size mismatch\");\n    std::vector<std::complex<T> > res;\n    res.reserve(n);\n    for (size_t i = 0; i < n; i++) {\n        res.push_back(std::complex<T>(real_values[i], imag_values[i]));\n    }\n    return res;\n}\n\ntemplate <typename T>\nvoid check_close_complex_vector(const std::vector<std::complex<T> >& v1,\n                                const std::vector<std::complex<T> >& v2) {\n    auto n = v1.size();\n    if (v2.size() != n) throw std::runtime_error(\"Size mismatch\");\n    for (size_t i = 0; i < n; i++) {\n        const T TOLERANCE = 1e-3;\n        const T real_diff = std::abs(v1[i].real()-v2[i].real()); \n        const T imag_diff = std::abs(v1[i].imag()-v2[i].imag());\n        \n        if (real_diff >= TOLERANCE) {\n            std::cout << \"real failes at \" << i << \" : \" << v1[i].real() << \" vs. \" << v2[i].real() << std::endl;\n        }\n        if (imag_diff >= TOLERANCE) {\n            std::cout << \"imag fails at \" << i << \" : \" << v1[i].imag() << \" vs. \" << v2[i].imag() << std::endl;\n        }\n        \n        BOOST_REQUIRE(real_diff < TOLERANCE);\n        BOOST_REQUIRE(imag_diff < TOLERANCE);\n    }\n}\n\ntemplate <typename T>\nvoid check_close_vector(const std::vector<T>& x, const std::vector<T>& y) {\n    auto n = x.size();\n    if (n != y.size()) throw std::runtime_error(\"Size mismatch\");\n    for (size_t i = 0; i < n; i++) {\n        BOOST_CHECK_CLOSE(x[i], y[i], 0.01f);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(FFT_convolve1) {\n    std::vector<float> x{1.0f, 2.0f, 3.0f};\n    std::vector<float> h{1.0f};\n    std::vector<float> desired_res{1.0f, 2.0f, 3.0f};\n\n    auto res = fft_conv(x, h);\n    BOOST_REQUIRE(res.size() == x.size());\n    check_close_vector(res, desired_res);\n}\n\nBOOST_AUTO_TEST_CASE(FFT_convolve2) {\n    std::vector<float> x{1.0f, 2.0f, 3.0f, -0.23f, 0.001f, 32.3f, 4.0f};\n    std::vector<float> h{-0.33f, 0.9f, -0.002f, 1.1f, 2.3f};\n    \n    std::vector<float> desired_res{-0.33f, 0.24f, 0.808f, 3.8719f, 4.28667f,\n        -2.75764f, 34.396998f, 3.0075f, 35.5243f, 78.69f, 9.2f};\n\n    auto res = fft_conv(x, h);\n    BOOST_REQUIRE(res.size() == (x.size() + h.size() - 1));\n    check_close_vector(res, desired_res);\n}\n\nBOOST_AUTO_TEST_CASE(TestNextPowerOfTwo) {\n    BOOST_CHECK_EQUAL(next_power_of_two(1), 1);\n    BOOST_CHECK_EQUAL(next_power_of_two(2), 2);\n    BOOST_CHECK_EQUAL(next_power_of_two(3), 4);\n    BOOST_CHECK_EQUAL(next_power_of_two(4), 4);\n    BOOST_CHECK_EQUAL(next_power_of_two(5), 8);\n    BOOST_CHECK_EQUAL(next_power_of_two(7), 8);\n    BOOST_CHECK_EQUAL(next_power_of_two(8), 8);\n    BOOST_CHECK_EQUAL(next_power_of_two(15), 16);\n    BOOST_CHECK_EQUAL(next_power_of_two(16), 16);\n    BOOST_CHECK_EQUAL(next_power_of_two(32767), 32768);\n    BOOST_CHECK_EQUAL(next_power_of_two(65535), 65536);\n    BOOST_CHECK_EQUAL(next_power_of_two(65536), 65536);\n}\n", "meta": {"hexsha": "7585709766079378c27779477395af86d2c73bbe", "size": 3279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/unittest/test_fft.cpp", "max_stars_repo_name": "sigurdstorve/OpenBCSim", "max_stars_repo_head_hexsha": "500025c1b63bc6ff083cbd649771d1b98e3f7314", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2016-05-27T13:09:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T07:08:47.000Z", "max_issues_repo_path": "src/core/unittest/test_fft.cpp", "max_issues_repo_name": "rojsc/OpenBCSim", "max_issues_repo_head_hexsha": "53773172974ad42fc3faceb7b36611573abf1c4c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 63.0, "max_issues_repo_issues_event_min_datetime": "2015-09-10T11:22:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-21T14:52:39.000Z", "max_forks_repo_path": "src/core/unittest/test_fft.cpp", "max_forks_repo_name": "rojsc/OpenBCSim", "max_forks_repo_head_hexsha": "53773172974ad42fc3faceb7b36611573abf1c4c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T14:52:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T15:52:28.000Z", "avg_line_length": 36.032967033, "max_line_length": 113, "alphanum_fraction": 0.6108569686, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5036665934680897}}
{"text": "//  (C) Copyright 2006 Eric Niebler, Olivier Gygi.\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// Test case for tail_variate_means.hpp\n\n#include <boost/random.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/numeric/functional/vector.hpp>\n#include <boost/accumulators/numeric/functional/complex.hpp>\n#include <boost/accumulators/numeric/functional/valarray.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/variates/covariate.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/tail_variate_means.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace boost::accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    std::size_t c = 5; // cache size\n\n    typedef double variate_type;\n    typedef std::vector<variate_type> variate_set_type;\n\n    typedef accumulator_set<double, stats<tag::tail_variate_means<right, variate_set_type, tag::covariate1>(relative)> > accumulator_t1;\n    typedef accumulator_set<double, stats<tag::tail_variate_means<right, variate_set_type, tag::covariate1>(absolute)> > accumulator_t2;\n    typedef accumulator_set<double, stats<tag::tail_variate_means<left, variate_set_type, tag::covariate1>(relative)> > accumulator_t3;\n    typedef accumulator_set<double, stats<tag::tail_variate_means<left, variate_set_type, tag::covariate1>(absolute)> > accumulator_t4;\n\n    accumulator_t1 acc1( right_tail_cache_size = c );\n    accumulator_t2 acc2( right_tail_cache_size = c );\n    accumulator_t3 acc3( left_tail_cache_size = c );\n    accumulator_t4 acc4( left_tail_cache_size = c );\n\n    variate_set_type cov1, cov2, cov3, cov4, cov5;\n    double c1[] = { 10., 20., 30., 40. }; // 100\n    double c2[] = { 26.,  4., 17.,  3. }; // 50\n    double c3[] = { 46., 64., 40., 50. }; // 200\n    double c4[] = {  1.,  3., 70.,  6. }; // 80\n    double c5[] = {  2.,  2.,  2., 14. }; // 20\n    cov1.assign(c1, c1 + sizeof(c1)/sizeof(variate_type));\n    cov2.assign(c2, c2 + sizeof(c2)/sizeof(variate_type));\n    cov3.assign(c3, c3 + sizeof(c3)/sizeof(variate_type));\n    cov4.assign(c4, c4 + sizeof(c4)/sizeof(variate_type));\n    cov5.assign(c5, c5 + sizeof(c5)/sizeof(variate_type));\n\n    acc1(100., covariate1 = cov1);\n    acc1( 50., covariate1 = cov2);\n    acc1(200., covariate1 = cov3);\n    acc1( 80., covariate1 = cov4);\n    acc1( 20., covariate1 = cov5);\n\n    acc2(100., covariate1 = cov1);\n    acc2( 50., covariate1 = cov2);\n    acc2(200., covariate1 = cov3);\n    acc2( 80., covariate1 = cov4);\n    acc2( 20., covariate1 = cov5);\n\n    acc3(100., covariate1 = cov1);\n    acc3( 50., covariate1 = cov2);\n    acc3(200., covariate1 = cov3);\n    acc3( 80., covariate1 = cov4);\n    acc3( 20., covariate1 = cov5);\n\n    acc4(100., covariate1 = cov1);\n    acc4( 50., covariate1 = cov2);\n    acc4(200., covariate1 = cov3);\n    acc4( 80., covariate1 = cov4);\n    acc4( 20., covariate1 = cov5);\n\n    // check relative risk contributions\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc1, quantile_probability = 0.7).begin()     ), 14./75. ); // (10 + 46) / 300 = 14/75\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc1, quantile_probability = 0.7).begin() + 1),  7./25. ); // (20 + 64) / 300 =  7/25\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc1, quantile_probability = 0.7).begin() + 2),  7./30. ); // (30 + 40) / 300 =  7/30\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc1, quantile_probability = 0.7).begin() + 3),  3./10. ); // (40 + 50) / 300 =  3/10\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc3, quantile_probability = 0.3).begin()    ), 14./35. ); // (26 +  2) /  70 = 14/35\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc3, quantile_probability = 0.3).begin() + 1),  3./35. ); // ( 4 +  2) /  70 =  3/35\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc3, quantile_probability = 0.3).begin() + 2), 19./70. ); // (17 +  2) /  70 = 19/70\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc3, quantile_probability = 0.3).begin() + 3), 17./70. ); // ( 3 + 14) /  70 = 17/70\n\n    // check absolute risk contributions\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc2, quantile_probability = 0.7).begin()    ), 28 ); // (10 + 46) / 2 = 28\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc2, quantile_probability = 0.7).begin() + 1), 42 ); // (20 + 64) / 2 = 42\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc2, quantile_probability = 0.7).begin() + 2), 35 ); // (30 + 40) / 2 = 35\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc2, quantile_probability = 0.7).begin() + 3), 45 ); // (40 + 50) / 2 = 45\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc4, quantile_probability = 0.3).begin()    ), 14 ); // (26 +  2) / 2 = 14\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc4, quantile_probability = 0.3).begin() + 1),  3 ); // ( 4 +  2) / 2 =  3\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc4, quantile_probability = 0.3).begin() + 2),9.5 ); // (17 +  2) / 2 =  9.5\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc4, quantile_probability = 0.3).begin() + 3),8.5 ); // ( 3 + 14) / 2 =  8.5\n\n    // check relative risk contributions\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc1, quantile_probability = 0.9).begin()    ), 23./100. ); // 46/200 = 23/100\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc1, quantile_probability = 0.9).begin() + 1),  8./25.  ); // 64/200 =  8/25\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc1, quantile_probability = 0.9).begin() + 2),  1./5.   ); // 40/200 =  1/5\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc1, quantile_probability = 0.9).begin() + 3),  1./4.   ); // 50/200 =  1/4\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc3, quantile_probability = 0.1).begin()    ),  1./10.  ); //  2/ 20 =  1/10\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc3, quantile_probability = 0.1).begin() + 1),  1./10.  ); //  2/ 20 =  1/10\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc3, quantile_probability = 0.1).begin() + 2),  1./10.  ); //  2/ 20 =  1/10\n    BOOST_CHECK_EQUAL( *(relative_tail_variate_means(acc3, quantile_probability = 0.1).begin() + 3),  7./10.  ); // 14/ 20 =  7/10\n\n    // check absolute risk contributions\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc2, quantile_probability = 0.9).begin()    ), 46 ); // 46\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc2, quantile_probability = 0.9).begin() + 1), 64 ); // 64\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc2, quantile_probability = 0.9).begin() + 2), 40 ); // 40\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc2, quantile_probability = 0.9).begin() + 3), 50 ); // 50\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc4, quantile_probability = 0.1).begin()    ),  2 ); //  2\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc4, quantile_probability = 0.1).begin() + 1),  2 ); //  2\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc4, quantile_probability = 0.1).begin() + 2),  2 ); //  2\n    BOOST_CHECK_EQUAL( *(tail_variate_means(acc4, quantile_probability = 0.1).begin() + 3), 14 ); // 14\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"tail_variate_means test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n\n", "meta": {"hexsha": "6d0031999bfb38ff9a3359fbbee468d93f318ea9", "size": 7624, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/accumulators/test/tail_variate_means.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/accumulators/test/tail_variate_means.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/accumulators/test/tail_variate_means.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": 57.7575757576, "max_line_length": 139, "alphanum_fraction": 0.6543809024, "num_tokens": 2521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5036665882879098}}
{"text": "#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing namespace Eigen;\n\n#include <pangolin/pangolin.h>\n\nstruct RotationMatrix {\n  Matrix3d matrix = Matrix3d::Identity();\n};\n\nostream &operator<<(ostream &out, const RotationMatrix &r) {\n  out.setf(ios::fixed);\n  Matrix3d matrix = r.matrix;\n  out << '=';\n  out << \"[\" << setprecision(2) << matrix(0, 0) << \",\" << matrix(0, 1) << \",\" << matrix(0, 2) << \"],\"\n      << \"[\" << matrix(1, 0) << \",\" << matrix(1, 1) << \",\" << matrix(1, 2) << \"],\"\n      << \"[\" << matrix(2, 0) << \",\" << matrix(2, 1) << \",\" << matrix(2, 2) << \"]\";\n  return out;\n}\n\nistream &operator>>(istream &in, RotationMatrix &r) {\n  return in;\n}\n\nstruct TranslationVector {\n  Vector3d trans = Vector3d(0, 0, 0);\n};\n\nostream &operator<<(ostream &out, const TranslationVector &t) {\n  out << \"=[\" << t.trans(0) << ',' << t.trans(1) << ',' << t.trans(2) << \"]\";\n  return out;\n}\n\nistream &operator>>(istream &in, TranslationVector &t) {\n  return in;\n}\n\nstruct QuaternionDraw {\n  Quaterniond q;\n};\n\nostream &operator<<(ostream &out, const QuaternionDraw quat) {\n  auto c = quat.q.coeffs();\n  out << \"=[\" << c[0] << \",\" << c[1] << \",\" << c[2] << \",\" << c[3] << \"]\";\n  return out;\n}\n\nistream &operator>>(istream &in, const QuaternionDraw quat) {\n  return in;\n}\n\nint main(int argc, char **argv) {\n  pangolin::CreateWindowAndBind(\"visualize geometry\", 1000, 600);\n  glEnable(GL_DEPTH_TEST);\n  pangolin::OpenGlRenderState s_cam(\n    pangolin::ProjectionMatrix(1000, 600, 420, 420, 500, 300, 0.1, 1000),\n    pangolin::ModelViewLookAt(3, 3, 3, 0, 0, 0, pangolin::AxisY)\n  );\n\n  const int UI_WIDTH = 500;\n\n  pangolin::View &d_cam = pangolin::CreateDisplay().\n    SetBounds(0.0, 1.0, pangolin::Attach::Pix(UI_WIDTH), 1.0, -1000.0f / 600.0f).\n    SetHandler(new pangolin::Handler3D(s_cam));\n\n  // ui\n  pangolin::Var<RotationMatrix> rotation_matrix(\"ui.R\", RotationMatrix());\n  pangolin::Var<TranslationVector> translation_vector(\"ui.t\", TranslationVector());\n  pangolin::Var<TranslationVector> euler_angles(\"ui.rpy\", TranslationVector());\n  pangolin::Var<QuaternionDraw> quaternion(\"ui.q\", QuaternionDraw());\n  pangolin::CreatePanel(\"ui\").SetBounds(0.0, 1.0, 0.0, pangolin::Attach::Pix(UI_WIDTH));\n\n  while (!pangolin::ShouldQuit()) {\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n    d_cam.Activate(s_cam);\n\n    pangolin::OpenGlMatrix matrix = s_cam.GetModelViewMatrix();\n    Matrix<double, 4, 4> m = matrix;\n\n    RotationMatrix R;\n    for (int i = 0; i < 3; i++)\n      for (int j = 0; j < 3; j++)\n        R.matrix(i, j) = m(j, i);\n    rotation_matrix = R;\n\n    TranslationVector t;\n    t.trans = Vector3d(m(0, 3), m(1, 3), m(2, 3));\n    t.trans = -R.matrix * t.trans;\n    translation_vector = t;\n\n    TranslationVector euler;\n    euler.trans = R.matrix.eulerAngles(2, 1, 0);\n    euler_angles = euler;\n\n    QuaternionDraw quat;\n    quat.q = Quaterniond(R.matrix);\n    quaternion = quat;\n\n    glColor3f(1.0, 1.0, 1.0);\n\n    pangolin::glDrawColouredCube();\n    // draw the original axis\n    glLineWidth(3);\n    glColor3f(0.8f, 0.f, 0.f);\n    glBegin(GL_LINES);\n    glVertex3f(0, 0, 0);\n    glVertex3f(10, 0, 0);\n    glColor3f(0.f, 0.8f, 0.f);\n    glVertex3f(0, 0, 0);\n    glVertex3f(0, 10, 0);\n    glColor3f(0.2f, 0.2f, 1.f);\n    glVertex3f(0, 0, 0);\n    glVertex3f(0, 0, 10);\n    glEnd();\n\n    pangolin::FinishFrame();\n  }\n}\n", "meta": {"hexsha": "f68fa078545de5b9cabde4a02ca2d38bf455ad6b", "size": 3394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/visualizeGeometry/visualizeGeometry.cpp", "max_stars_repo_name": "RingWong/slambook2", "max_stars_repo_head_hexsha": "c5366b6fc9f8117f938e501bad1034a279909f39", "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": "ch3/visualizeGeometry/visualizeGeometry.cpp", "max_issues_repo_name": "Ewenwan/slambook2", "max_issues_repo_head_hexsha": "af90f73a60daa21b0ac05c97218fc5676b05864e", "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": "ch3/visualizeGeometry/visualizeGeometry.cpp", "max_forks_repo_name": "Ewenwan/slambook2", "max_forks_repo_head_hexsha": "af90f73a60daa21b0ac05c97218fc5676b05864e", "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": 26.9365079365, "max_line_length": 101, "alphanum_fraction": 0.6116676488, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.503666581355498}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/*\n *   File \"gmm_b_tapenade_generated.c\" is generated by Tapenade 3.14 (r7259) from this file.\n *   To reproduce such a generation you can use Tapenade CLI\n *   (can be downloaded from http://www-sop.inria.fr/tropics/tapenade/downloading.html)\n *\n *   Firstly, add a type declaration of Wishart to the content of this file (Tapenade can't process a file\n *   with unknown types). You can both take this declaration from the file \"<repo root>/src/cpp/shared/defs.h\" or\n *   copypaste the following lines removing asterisks:\n *\n *   typedef struct\n *   {\n *       double gamma;\n *       int m;\n *   } Wishart;\n *\n *   After Tapenade CLI installing use the next command to generate a file:\n *\n *      tapenade -b -o gmm_tapenade -head \"gmm_objective(err)/(alphas means icf)\" gmm.c\n *\n *   This will produce a file \"gmm_tapenade_b.c\" which content will be the same as the content of \"gmm_b_tapenade_generated.c\",\n *   except one-line header and a Wishart typedef (which should be removed). Moreover a log-file \"gmm_tapenade_b.msg\" will be produced.\n *\n *   NOTE: the code in \"gmm_b_tapenade_generated.c\" is wrong and won't work.\n *         REPAIRED SOURCE IS STORED IN THE FILE \"gmm_b.c\".\n *         You can either use diff tool or read \"gmm_b.c\" header to figure out what changes was performed to fix the code.\n *\n *   NOTE: you can also use Tapenade web server (http://tapenade.inria.fr:8080/tapenade/index.jsp)\n *         for generating but result can be slightly different.\n */\n#include \"../adbench/gmm.h\"\nextern \"C\" {\n#include \"gmm.h\"\n\n/* ==================================================================== */\n/*                                UTILS                                 */\n/* ==================================================================== */\n\n// This throws error on n<1\ndouble arr_max(int n, double const* x)\n{\n    int i;\n    double m = x[0];\n    for (i = 1; i < n; i++)\n    {\n        if (m < x[i])\n        {\n            m = x[i];\n        }\n    }\n\n    return m;\n}\n\n\n\n// sum of component squares\ndouble sqnorm(int n, double const* x)\n{\n    int i;\n    double res = x[0] * x[0];\n    for (i = 1; i < n; i++)\n    {\n        res = res + x[i] * x[i];\n    }\n\n    return res;\n}\n\n\n\n// out = a - b\nvoid subtract(\n    int d,\n    double const* x,\n    double const* y,\n    double* out\n)\n{\n    int id;\n    for (id = 0; id < d; id++)\n    {\n        out[id] = x[id] - y[id];\n    }\n}\n\n\ndouble log_sum_exp(int n, double const* x)\n{\n    int i;\n    double mx = arr_max(n, x);\n    double semx = 0.0;\n\n    for (i = 0; i < n; i++)\n    {\n        semx = semx + exp(x[i] - mx);\n    }\n\n    return log(semx) + mx;\n}\n\n\n__attribute__((const))\ndouble log_gamma_distrib(double a, double p)\n{\n    int j;\n    double out = 0.25 * p * (p - 1) * log(PI);\n\n    for (j = 1; j <= p; j++)\n    {\n        out = out + lgamma(a + 0.5 * (1 - j));\n    }\n\n    return out;\n}\n\n\n\n/* ======================================================================== */\n/*                                MAIN LOGIC                                */\n/* ======================================================================== */\n\ndouble log_wishart_prior(\n    int p,\n    int k,\n    Wishart wishart,\n    double const* sum_qs,\n    double const* Qdiags,\n    double const* icf\n)\n{\n    int ik;\n    int n = p + wishart.m + 1;\n    int icf_sz = p * (p + 1) / 2;\n\n    double C = n * p * (log(wishart.gamma) - 0.5 * log(2)) - log_gamma_distrib(0.5 * n, p);\n\n    double out = 0;\n    for (ik = 0; ik < k; ik++)\n    {\n        double frobenius = sqnorm(p, &Qdiags[ik * p]) + sqnorm(icf_sz - p, &icf[ik * icf_sz + p]);\n        out = out + 0.5 * wishart.gamma * wishart.gamma * (frobenius) - wishart.m * sum_qs[ik];\n    }\n\n    return out - k * C;\n}\n\n\n\nvoid preprocess_qs(\n    int d,\n    int k,\n    double const* icf,\n    double* sum_qs,\n    double* Qdiags\n)\n{\n    int ik, id;\n    int icf_sz = d * (d + 1) / 2;\n    for (ik = 0; ik < k; ik++)\n    {\n        sum_qs[ik] = 0.;\n        for (id = 0; id < d; id++)\n        {\n            double q = icf[ik * icf_sz + id];\n            sum_qs[ik] = sum_qs[ik] + q;\n            Qdiags[ik * d + id] = exp(q);\n        }\n    }\n}\n\n\n\nvoid Qtimesx(\n    int d,\n    double const* Qdiag,\n    double const* ltri, // strictly lower triangular part\n    double const* x,\n    double* out\n)\n{\n    int i, j;\n    for (i = 0; i < d; i++)\n    {\n        out[i] = Qdiag[i] * x[i];\n    }\n\n    //caching lparams as scev doesn't replicate index calculation\n    // todo note changing to strengthened form\n    //int Lparamsidx = 0;\n    for (i = 0; i < d; i++)\n    {\n    \tint Lparamsidx = i*(2*d-i-1)/2;\n        for (j = i + 1; j < d; j++)\n        {\n            // and this x\n            out[j] = out[j] + ltri[Lparamsidx] * x[i];\n            Lparamsidx++;\n        }\n    }\n}\n\n\n\nvoid gmm_objective(\n    int d,\n    int k,\n    int n,\n    double const* __restrict alphas,\n    double const* __restrict means,\n    double const* __restrict icf,\n    double const* __restrict x,\n    Wishart wishart,\n    double* __restrict err\n)\n{\n    #define int int64_t\n    int ix, ik;\n    const double CONSTANT = -n * d * 0.5 * log(2 * PI);\n    int icf_sz = d * (d + 1) / 2;\n\n    double* Qdiags = (double*)malloc(d * k * sizeof(double));\n    double* sum_qs = (double*)malloc(k * sizeof(double));\n    double* xcentered = (double*)malloc(d * sizeof(double));\n    double* Qxcentered = (double*)malloc(d * sizeof(double));\n    double* main_term = (double*)malloc(k * sizeof(double));\n\n    preprocess_qs(d, k, icf, &sum_qs[0], &Qdiags[0]);\n\n    double slse = 0.;\n    for (ix = 0; ix < n; ix++)\n    {\n        for (ik = 0; ik < k; ik++)\n        {\n            subtract(d, &x[ix * d], &means[ik * d], &xcentered[0]);\n            Qtimesx(d, &Qdiags[ik * d], &icf[ik * icf_sz + d], &xcentered[0], &Qxcentered[0]);\n            // two caches for qxcentered at idx 0 and at arbitrary index\n            main_term[ik] = alphas[ik] + sum_qs[ik] - 0.5 * sqnorm(d, &Qxcentered[0]);\n        }\n\n        // storing cmp for max of main_term\n        // 2 x (0 and arbitrary) storing sub to exp\n        // storing sum for use in log\n        slse = slse + log_sum_exp(k, &main_term[0]);\n    }\n\n    //storing cmp of alphas\n    double lse_alphas = log_sum_exp(k, alphas);\n\n    *err = CONSTANT + slse - n * lse_alphas + log_wishart_prior(d, k, wishart, &sum_qs[0], &Qdiags[0], icf);\n\n    free(Qdiags);\n    free(sum_qs);\n    free(xcentered);\n    free(Qxcentered);\n    free(main_term);\n    #undef int\n}\n\nextern int enzyme_const;\nextern int enzyme_dup;\nextern int enzyme_dupnoneed;\nvoid __enzyme_autodiff(...) noexcept;\n\n// *      tapenade -b -o gmm_tapenade -head \"gmm_objective(err)/(alphas means icf)\" gmm.c\nvoid dgmm_objective(int d, int k, int n, const double *alphas, double *\n        alphasb, const double *means, double *meansb, const double *icf,\n        double *icfb, const double *x, Wishart wishart, double *err, double *\n        errb) {\n    __enzyme_autodiff(\n            gmm_objective,\n            enzyme_const, d,\n            enzyme_const, k,\n            enzyme_const, n,\n            enzyme_dup, alphas, alphasb,\n            enzyme_dup, means, meansb,\n            enzyme_dup, icf, icfb,\n            enzyme_const, x,\n            enzyme_const, wishart,\n            enzyme_dupnoneed, err, errb);\n}\n\n}\n\n\n// ! Tapenade\nextern \"C\" {\n\n#include <adBuffer.h>\n\n/*\n  Differentiation of arr_max in reverse (adjoint) mode:\n   gradient     of useful results: *x arr_max\n   with respect to varying inputs: *x\n   Plus diff mem management of: x:in\n\n ====================================================================\n                                UTILS\n ==================================================================== */\n// This throws error on n<1\nvoid arr_max_b(int n, const double *x, double *xb, double arr_maxb) {\n    int i;\n    double m = x[0];\n    double mb = 0.0;\n    int branch;\n    double arr_max;\n    for (i = 1; i < n; ++i)\n        if (m < x[i]) {\n            m = x[i];\n            pushControl1b(1);\n        } else\n            pushControl1b(0);\n    mb = arr_maxb;\n    for (i = n-1; i > 0; --i) {\n        popControl1b(&branch);\n        if (branch != 0) {\n            xb[i] = xb[i] + mb;\n            mb = 0.0;\n        }\n    }\n    xb[0] = xb[0] + mb;\n}\n\n/* ====================================================================\n                                UTILS\n ==================================================================== */\n// This throws error on n<1\ndouble arr_max_nodiff(int n, const double *x) {\n    int i;\n    double m = x[0];\n    for (i = 1; i < n; ++i)\n        if (m < x[i])\n            m = x[i];\n    return m;\n}\n\n/*\n  Differentiation of sqnorm in reverse (adjoint) mode:\n   gradient     of useful results: *x sqnorm\n   with respect to varying inputs: *x\n   Plus diff mem management of: x:in\n*/\n// sum of component squares\nvoid sqnorm_b(int n, const double *x, double *xb, double sqnormb) {\n    int i;\n    double res = x[0]*x[0];\n    double resb = 0.0;\n    double sqnorm;\n    resb = sqnormb;\n    for (i = n-1; i > 0; --i)\n        xb[i] = xb[i] + 2*x[i]*resb;\n    xb[0] = xb[0] + 2*x[0]*resb;\n}\n\n// sum of component squares\ndouble sqnorm_nodiff(int n, const double *x) {\n    int i;\n    double res = x[0]*x[0];\n    for (i = 1; i < n; ++i)\n        res = res + x[i]*x[i];\n    return res;\n}\n\n/*\n  Differentiation of subtract in reverse (adjoint) mode:\n   gradient     of useful results: *out *y\n   with respect to varying inputs: *out *y\n   Plus diff mem management of: out:in y:in\n*/\n// out = a - b\nvoid subtract_b(int d, const double *x, const double *y, double *yb, double *\n        out, double *outb) {\n    int id;\n    for (id = d-1; id > -1; --id) {\n        yb[id] = yb[id] - outb[id];\n        outb[id] = 0.0;\n    }\n}\n\n// out = a - b\nvoid subtract_nodiff(int d, const double *x, const double *y, double *out) {\n    int id;\n    for (id = 0; id < d; ++id)\n        out[id] = x[id] - y[id];\n}\n\n/*\n  Differentiation of log_sum_exp in reverse (adjoint) mode:\n   gradient     of useful results: *x log_sum_exp\n   with respect to varying inputs: *x\n   Plus diff mem management of: x:in\n*/\nvoid log_sum_exp_b(int n, const double *x, double *xb, double log_sum_expb) {\n    int i;\n    double mx;\n    double mxb;\n    double tempb;\n    double log_sum_exp;\n    mx = arr_max_nodiff(n, x);\n    double semx = 0.0;\n    double semxb = 0.0;\n    for (i = 0; i < n; ++i)\n        semx = semx + exp(x[i] - mx);\n    semxb = log_sum_expb/semx;\n    mxb = log_sum_expb;\n    for (i = n-1; i > -1; --i) {\n        tempb = exp(x[i]-mx)*semxb;\n        xb[i] = xb[i] + tempb;\n        mxb = mxb - tempb;\n    }\n    arr_max_b(n, x, xb, mxb);\n}\n\ndouble log_sum_exp_nodiff(int n, const double *x) {\n    int i;\n    double mx;\n    mx = arr_max_nodiff(n, x);\n    double semx = 0.0;\n    for (i = 0; i < n; ++i)\n        semx = semx + exp(x[i] - mx);\n    return log(semx) + mx;\n}\n\ndouble log_gamma_distrib_nodiff(double a, double p) {\n    int j;\n    /* TFIX */\n    double out = 0.25*p*(p-1)*log(PI);\n    double arg1;\n    float result1;\n    for (j = 1; j < p+1; ++j) {\n        arg1 = a + 0.5*(1-j);\n        result1 = lgamma(arg1);\n        out = out + result1;\n    }\n    return out;\n}\n\n/*\n  Differentiation of log_wishart_prior in reverse (adjoint) mode:\n   gradient     of useful results: log_wishart_prior\n   with respect to varying inputs: *Qdiags *sum_qs *icf\n   Plus diff mem management of: Qdiags:in sum_qs:in icf:in\n\n ========================================================================\n                                MAIN LOGIC\n ======================================================================== */\nvoid log_wishart_prior_b(int p, int k, Wishart wishart, const double *sum_qs,\n        double *sum_qsb, const double *Qdiags, double *Qdiagsb, const double *\n        icf, double *icfb, double log_wishart_priorb) {\n    int ik;\n    int n = p + wishart.m + 1;\n    int icf_sz = p*(p+1)/2;\n    double C;\n    float arg1;\n    double result1;\n    double out = 0;\n    double outb = 0.0;\n    double log_wishart_prior;\n    for (ik = 0; ik < k; ++ik) {\n        double frobenius;\n        double result1;\n        int arg1;\n        double result2;\n    }\n    outb = log_wishart_priorb;\n    for (ik = 0; ik < k * p; ik++) /* TFIX */\n        Qdiagsb[ik] = 0.0;\n    for (ik = 0; ik < k; ik++) /* TFIX */\n        sum_qsb[ik] = 0.0;\n    for (ik = 0; ik < k * icf_sz; ik++) /* TFIX */\n        icfb[ik] = 0.0;\n    for (ik = k-1; ik > -1; --ik) {\n        double frobenius;\n        double frobeniusb;\n        double result1;\n        double result1b;\n        int arg1;\n        double result2;\n        double result2b;\n        frobeniusb = wishart.gamma*wishart.gamma*0.5*outb;\n        sum_qsb[ik] = sum_qsb[ik] - wishart.m*outb;\n        result1b = frobeniusb;\n        result2b = frobeniusb;\n        arg1 = icf_sz - p;\n        sqnorm_b(arg1, &(icf[ik*icf_sz + p]), &(icfb[ik*icf_sz + p]), result2b\n                );\n        sqnorm_b(p, &(Qdiags[ik*p]), &(Qdiagsb[ik*p]), result1b);\n    }\n}\n\n/* ========================================================================\n                                MAIN LOGIC\n ======================================================================== */\ndouble log_wishart_prior_nodiff(int p, int k, Wishart wishart, const double *\n        sum_qs, const double *Qdiags, const double *icf) {\n    int ik;\n    int n = p + wishart.m + 1;\n    int icf_sz = p*(p+1)/2;\n    double C;\n    float arg1;\n    double result1;\n    arg1 = 0.5*n;\n    result1 = log_gamma_distrib_nodiff(arg1, p);\n    C = n*p*(log(wishart.gamma)-0.5*log(2)) - result1;\n    double out = 0;\n    for (ik = 0; ik < k; ++ik) {\n        double frobenius;\n        double result1;\n        int arg1;\n        double result2;\n        result1 = sqnorm_nodiff(p, &(Qdiags[ik*p]));\n        arg1 = icf_sz - p;\n        result2 = sqnorm_nodiff(arg1, &(icf[ik*icf_sz + p]));\n        frobenius = result1 + result2;\n        out = out + 0.5*wishart.gamma*wishart.gamma*frobenius - wishart.m*\n            sum_qs[ik];\n    }\n    return out - k*C;\n}\n\n/*\n  Differentiation of preprocess_qs in reverse (adjoint) mode:\n   gradient     of useful results: *Qdiags *sum_qs *icf\n   with respect to varying inputs: *icf\n   Plus diff mem management of: Qdiags:in sum_qs:in icf:in\n*/\nvoid preprocess_qs_b(int d, int k, const double *icf, double *icfb, double *\n        sum_qs, double *sum_qsb, double *Qdiags, double *Qdiagsb) {\n    int ik, id;\n    int icf_sz = d*(d+1)/2;\n    for (ik = 0; ik < k; ++ik)\n        for (id = 0; id < d; ++id) {\n            double q = icf[ik*icf_sz + id];\n            pushReal8(q);\n        }\n    for (ik = k-1; ik > -1; --ik) {\n        for (id = d-1; id > -1; --id) {\n            double q;\n            double qb = 0.0;\n            popReal8(&q);\n            qb = exp(q)*Qdiagsb[ik*d+id];\n            Qdiagsb[ik*d + id] = 0.0;\n            qb = qb + sum_qsb[ik];\n            icfb[ik*icf_sz + id] = icfb[ik*icf_sz + id] + qb;\n        }\n        sum_qsb[ik] = 0.0;\n    }\n}\n\nvoid preprocess_qs_nodiff(int d, int k, const double *icf, double *sum_qs,\n        double *Qdiags) {\n    int ik, id;\n    int icf_sz = d*(d+1)/2;\n    for (ik = 0; ik < k; ++ik) {\n        sum_qs[ik] = 0.;\n        for (id = 0; id < d; ++id) {\n            double q = icf[ik*icf_sz + id];\n            sum_qs[ik] = sum_qs[ik] + q;\n            Qdiags[ik*d + id] = exp(q);\n        }\n    }\n}\n\n/*\n  Differentiation of Qtimesx in reverse (adjoint) mode:\n   gradient     of useful results: *out *Qdiag *x *ltri\n   with respect to varying inputs: *out *Qdiag *x *ltri\n   Plus diff mem management of: out:in Qdiag:in x:in ltri:in\n*/\nvoid Qtimesx_b(int d, const double *Qdiag, double *Qdiagb, const double *ltri,\n        double *ltrib, const double *x, double *xb, double *out, double *outb)\n{\n    // strictly lower triangular part\n    int i, j;\n    int adFrom;\n    int Lparamsidx = 0;\n    for (i = 0; i < d; ++i) {\n        adFrom = i + 1;\n        for (j = adFrom; j < d; ++j)\n            Lparamsidx++;\n        pushInteger4(adFrom);\n    }\n    for (i = d-1; i > -1; --i) {\n        popInteger4(&adFrom);\n        for (j = d-1; j > adFrom-1; --j) {\n            --Lparamsidx;\n            ltrib[Lparamsidx] = ltrib[Lparamsidx] + x[i]*outb[j];\n            xb[i] = xb[i] + ltri[Lparamsidx]*outb[j];\n        }\n    }\n    for (i = d-1; i > -1; --i) {\n        Qdiagb[i] = Qdiagb[i] + x[i]*outb[i];\n        xb[i] = xb[i] + Qdiag[i]*outb[i];\n        outb[i] = 0.0;\n    }\n}\n\nvoid Qtimesx_nodiff(int d, const double *Qdiag, const double *ltri, const\n        double *x, double *out) {\n    // strictly lower triangular part\n    int i, j;\n    for (i = 0; i < d; ++i)\n        out[i] = Qdiag[i]*x[i];\n    int Lparamsidx = 0;\n    for (i = 0; i < d; ++i)\n        for (j = i+1; j < d; ++j) {\n            out[j] = out[j] + ltri[Lparamsidx]*x[i];\n            Lparamsidx++;\n        }\n}\n\n/*\n  Differentiation of gmm_objective in reverse (adjoint) mode:\n   gradient     of useful results: *err\n   with respect to varying inputs: *err *means *icf *alphas\n   RW status of diff variables: *err:in-out *means:out *icf:out\n                *alphas:out\n   Plus diff mem management of: err:in means:in icf:in alphas:in\n*/\nvoid gmm_objective_b(int d, int k, int n, const double *alphas, double *\n        alphasb, const double *means, double *meansb, const double *icf,\n        double *icfb, const double *x, Wishart wishart, double *err, double *\n        errb) {\n    int ix, ik;\n    /* TFIX */\n    const double CONSTANT = -n*d*0.5*log(2*PI);\n    int icf_sz = d*(d+1)/2;\n    double *Qdiags;\n    double *Qdiagsb;\n    double result1;\n    double result1b;\n    int ii1;\n    Qdiagsb = (double *)malloc(d*k*sizeof(double));\n    for (ii1 = 0; ii1 < d*k; ++ii1)\n        Qdiagsb[ii1] = 0.0;\n    Qdiags = (double *)malloc(d*k*sizeof(double));\n    double *sum_qs;\n    double *sum_qsb;\n    sum_qsb = (double *)malloc(k*sizeof(double));\n    for (ii1 = 0; ii1 < k; ++ii1)\n        sum_qsb[ii1] = 0.0;\n    sum_qs = (double *)malloc(k*sizeof(double));\n    double *xcentered;\n    double *xcenteredb;\n    xcenteredb = (double *)malloc(d*sizeof(double));\n    for (ii1 = 0; ii1 < d; ++ii1)\n        xcenteredb[ii1] = 0.0;\n    xcentered = (double *)malloc(d*sizeof(double));\n    double *Qxcentered;\n    double *Qxcenteredb;\n    Qxcenteredb = (double *)malloc(d*sizeof(double));\n    for (ii1 = 0; ii1 < d; ++ii1)\n        Qxcenteredb[ii1] = 0.0;\n    Qxcentered = (double *)malloc(d*sizeof(double));\n    double *main_term;\n    double *main_termb;\n    main_termb = (double *)malloc(k*sizeof(double));\n    for (ii1 = 0; ii1 < k; ++ii1)\n        main_termb[ii1] = 0.0;\n    main_term = (double *)malloc(k*sizeof(double));\n    preprocess_qs_nodiff(d, k, icf, &(sum_qs[0]), &(Qdiags[0]));\n    double slse = 0.;\n    double slseb = 0.0;\n    for (ix = 0; ix < n; ++ix)\n        for (ik = 0; ik < k; ++ik) {\n            pushReal8Array(xcentered, d); /* TFIX */\n            subtract_nodiff(d, &(x[ix*d]), &(means[ik*d]), &(xcentered[0]));\n            pushReal8Array(Qxcentered, d); /* TFIX */\n            Qtimesx_nodiff(d, &(Qdiags[ik*d]), &(icf[ik*icf_sz + d]), &(\n                           xcentered[0]), &(Qxcentered[0]));\n            result1 = sqnorm_nodiff(d, &(Qxcentered[0]));\n            pushReal8(main_term[ik]);\n            main_term[ik] = alphas[ik] + sum_qs[ik] - 0.5*result1;\n        }\n    double lse_alphas;\n    double lse_alphasb;\n    slseb = *errb;\n    lse_alphasb = -(n*(*errb));\n    result1b = *errb;\n    *errb = 0.0;\n    log_wishart_prior_b(d, k, wishart, &(sum_qs[0]), &(sum_qsb[0]), &(Qdiags[0\n                        ]), &(Qdiagsb[0]), icf, icfb, result1b);\n    for (ii1 = 0; ii1 < k; ii1++) /* TFIX */\n        alphasb[ii1] = 0.0;\n    log_sum_exp_b(k, alphas, alphasb, lse_alphasb);\n    for (ii1 = 0; ii1 < d * k; ii1++) /* TFIX */\n        meansb[ii1] = 0.0;\n    for (ix = n-1; ix > -1; --ix) {\n        result1b = slseb;\n        log_sum_exp_b(k, &(main_term[0]), &(main_termb[0]), result1b);\n        for (ik = k-1; ik > -1; --ik) {\n            popReal8(&(main_term[ik]));\n            alphasb[ik] = alphasb[ik] + main_termb[ik];\n            sum_qsb[ik] = sum_qsb[ik] + main_termb[ik];\n            result1b = -(0.5*main_termb[ik]);\n            main_termb[ik] = 0.0;\n            sqnorm_b(d, &(Qxcentered[0]), &(Qxcenteredb[0]), result1b);\n            popReal8Array(Qxcentered, d); /* TFIX */\n            Qtimesx_b(d, &(Qdiags[ik*d]), &(Qdiagsb[ik*d]), &(icf[ik*icf_sz +\n                      d]), &(icfb[ik*icf_sz + d]), &(xcentered[0]), &(\n                      xcenteredb[0]), &(Qxcentered[0]), &(Qxcenteredb[0]));\n            popReal8Array(xcentered, d); /* TFIX */\n            subtract_b(d, &(x[ix*d]), &(means[ik*d]), &(meansb[ik*d]), &(\n                       xcentered[0]), &(xcenteredb[0]));\n        }\n    }\n    preprocess_qs_b(d, k, icf, icfb, &(sum_qs[0]), &(sum_qsb[0]), &(Qdiags[0])\n                    , &(Qdiagsb[0]));\n    free(main_term);\n    free(main_termb);\n    free(Qxcentered);\n    free(Qxcenteredb);\n    free(xcentered);\n    free(xcenteredb);\n    free(sum_qs);\n    free(sum_qsb);\n    free(Qdiags);\n    free(Qdiagsb);\n}\n}\n\n\n//! Adept\n#include <adept_source.h>\n#include <adept.h>\n#include <adept_arrays.h>\nusing adept::adouble;\nusing adept::aVector;\n\nnamespace adeptTest {\n\n    // out = a - b\ntemplate<typename T1, typename T2, typename T3>\nvoid subtract(int d,\n    const T1* const x,\n    const T2* const y,\n    T3* out)\n{\n    for (int id = 0; id < d; id++)\n    {\n        out[id] = x[id] - y[id];\n    }\n}\n\ntemplate<typename T>\nT sqnorm(int n, const T* const x)\n{\n    T res = x[0] * x[0];\n    for (int i = 1; i < n; i++)\n        res = res + x[i] * x[i];\n    return res;\n}\n\n// This throws error on n<1\ntemplate<typename T>\nT arr_max(int n, const T* const x)\n{\n    T m = x[0];\n    for (int i = 1; i < n; i++)\n    {\n        if (m < x[i])\n            m = x[i];\n    }\n    return m;\n}\n\n    template<typename T>\nvoid gmm_objective(int d, int k, int n, const T* const alphas, const T* const means,\n    const T* const icf, const double* const x, Wishart wishart, T* err);\n\n// split of the outer loop over points\ntemplate<typename T>\nvoid gmm_objective_split_inner(int d, int k,\n    const T* const alphas,\n    const T* const means,\n    const T* const icf,\n    const double* const x,\n    Wishart wishart,\n    T* err);\n// other terms which are outside the loop\ntemplate<typename T>\nvoid gmm_objective_split_other(int d, int k, int n,\n    const T* const alphas,\n    const T* const means,\n    const T* const icf,\n    Wishart wishart,\n    T* err);\n\ntemplate<typename T>\nT logsumexp(int n, const T* const x);\n\n// p: dim\n// k: number of components\n// wishart parameters\n// sum_qs: k sums of log diags of Qs\n// Qdiags: d*k\n// icf: (p*(p+1)/2)*k inverse covariance factors\ntemplate<typename T>\nT log_wishart_prior(int p, int k,\n    Wishart wishart,\n    const T* const sum_qs,\n    const T* const Qdiags,\n    const T* const icf);\n\ntemplate<typename T>\nvoid preprocess_qs(int d, int k,\n    const T* const icf,\n    T* sum_qs,\n    T* Qdiags);\n\ntemplate<typename T>\nvoid Qtimesx(int d,\n    const T* const Qdiag,\n    const T* const ltri, // strictly lower triangular part\n    const T* const x,\n    T* out);\n\n////////////////////////////////////////////////////////////\n//////////////////// Definitions ///////////////////////////\n////////////////////////////////////////////////////////////\n\ntemplate<typename T>\nT logsumexp(int n, const T* const x)\n{\n    T mx = arr_max(n, x);\n    T semx = 0.;\n    for (int i = 0; i < n; i++)\n    {\n        semx = semx + exp(x[i] - mx);\n    }\n    return log(semx) + mx;\n}\n\ntemplate<typename T>\nT log_wishart_prior(int p, int k,\n    Wishart wishart,\n    const T* const sum_qs,\n    const T* const Qdiags,\n    const T* const icf)\n{\n    int n = p + wishart.m + 1;\n    int icf_sz = p * (p + 1) / 2;\n\n    double C = n * p * (log(wishart.gamma) - 0.5 * log(2)) - log_gamma_distrib(0.5 * n, p);\n\n    T out = 0;\n    for (int ik = 0; ik < k; ik++)\n    {\n        T frobenius = sqnorm(p, &Qdiags[ik * p]) + sqnorm(icf_sz - p, &icf[ik * icf_sz + p]);\n        out = out + 0.5 * wishart.gamma * wishart.gamma * (frobenius)\n            -wishart.m * sum_qs[ik];\n    }\n\n    return out - k * C;\n}\n\ntemplate<typename T>\nvoid preprocess_qs(int d, int k,\n    const T* const icf,\n    T* sum_qs,\n    T* Qdiags)\n{\n    int icf_sz = d * (d + 1) / 2;\n    for (int ik = 0; ik < k; ik++)\n    {\n        sum_qs[ik] = 0.;\n        for (int id = 0; id < d; id++)\n        {\n            T q = icf[ik * icf_sz + id];\n            sum_qs[ik] = sum_qs[ik] + q;\n            Qdiags[ik * d + id] = exp(q);\n        }\n    }\n}\n\ntemplate<typename T>\nvoid Qtimesx(int d,\n    const T* const Qdiag,\n    const T* const ltri, // strictly lower triangular part\n    const T* const x,\n    T* out)\n{\n    for (int id = 0; id < d; id++)\n        out[id] = Qdiag[id] * x[id];\n\n    int Lparamsidx = 0;\n    for (int i = 0; i < d; i++)\n    {\n        for (int j = i + 1; j < d; j++)\n        {\n            out[j] = out[j] + ltri[Lparamsidx] * x[i];\n            Lparamsidx++;\n        }\n    }\n}\n\ntemplate<typename T>\nvoid gmm_objective(int d, int k, int n,\n    const T* const alphas,\n    const T* const means,\n    const T* const icf,\n    const double* const x,\n    Wishart wishart,\n    T* err)\n{\n    const double CONSTANT = -n * d * 0.5 * log(2 * PI);\n    int icf_sz = d * (d + 1) / 2;\n\n    vector<T> Qdiags(d * k);\n    vector<T> sum_qs(k);\n    vector<T> xcentered(d);\n    vector<T> Qxcentered(d);\n    vector<T> main_term(k);\n\n    preprocess_qs(d, k, icf, &sum_qs[0], &Qdiags[0]);\n\n    T slse = 0.;\n    for (int ix = 0; ix < n; ix++)\n    {\n        for (int ik = 0; ik < k; ik++)\n        {\n            subtract(d, &x[ix * d], &means[ik * d], &xcentered[0]);\n            Qtimesx(d, &Qdiags[ik * d], &icf[ik * icf_sz + d], &xcentered[0], &Qxcentered[0]);\n\n            main_term[ik] = alphas[ik] + sum_qs[ik] - 0.5 * sqnorm(d, &Qxcentered[0]);\n        }\n        slse = slse + logsumexp(k, &main_term[0]);\n    }\n\n    T lse_alphas = logsumexp(k, alphas);\n\n    *err = CONSTANT + slse - n * lse_alphas;\n\n    *err = *err + log_wishart_prior(d, k, wishart, &sum_qs[0], &Qdiags[0], icf);\n}\n\ntemplate<typename T>\nvoid gmm_objective_split_inner(int d, int k,\n    const T* const alphas,\n    const T* const means,\n    const T* const icf,\n    const double* const x,\n    Wishart wishart,\n    T* err)\n{\n    int icf_sz = d * (d + 1) / 2;\n\n    T* Ldiag = new T[d];\n    T* xcentered = new T[d];\n    T* mahal = new T[d];\n    T* lse = new T[k];\n\n    for (int ik = 0; ik < k; ik++)\n    {\n        int icf_off = ik * icf_sz;\n        T sumlog_Ldiag(0.);\n        for (int id = 0; id < d; id++)\n        {\n            sumlog_Ldiag = sumlog_Ldiag + icf[icf_off + id];\n            Ldiag[id] = exp(icf[icf_off + id]);\n        }\n\n        for (int id = 0; id < d; id++)\n        {\n            xcentered[id] = x[id] - means[ik * d + id];\n            mahal[id] = Ldiag[id] * xcentered[id];\n        }\n        int Lparamsidx = d;\n        for (int i = 0; i < d; i++)\n        {\n            for (int j = i + 1; j < d; j++)\n            {\n                mahal[j] = mahal[j] + icf[icf_off + Lparamsidx] * xcentered[i];\n                Lparamsidx++;\n            }\n        }\n        T sqsum_mahal(0.);\n        for (int id = 0; id < d; id++)\n        {\n            sqsum_mahal = sqsum_mahal + mahal[id] * mahal[id];\n        }\n\n        lse[ik] = alphas[ik] + sumlog_Ldiag - 0.5 * sqsum_mahal;\n    }\n\n    *err = logsumexp(k, lse);\n\n    delete[] mahal;\n    delete[] xcentered;\n    delete[] Ldiag;\n    delete[] lse;\n}\n\ntemplate<typename T>\nvoid gmm_objective_split_other(int d, int k, int n,\n    const T* const alphas,\n    const T* const means,\n    const T* const icf,\n    Wishart wishart,\n    T* err)\n{\n    const double CONSTANT = -n * d * 0.5 * log(2 * PI);\n\n    T lse_alphas = logsumexp(k, alphas);\n\n    T* sum_qs = new T[k];\n    T* Qdiags = new T[d * k];\n    preprocess_qs(d, k, icf, sum_qs, Qdiags);\n    *err = CONSTANT - n * lse_alphas + log_wishart_prior(d, k, wishart, sum_qs, Qdiags, icf);\n    delete[] sum_qs;\n    delete[] Qdiags;\n}\n\n};\n\nvoid adept_dgmm_objective(int d, int k, int n, const double *alphas, double *\n        alphasb, const double *means, double *meansb, const double *icf,\n        double *icfb, const double *x, Wishart wishart, double *err, double *\n        errb) {\n\n  int icf_sz = d*(d + 1) / 2;\n  int Jrows = 1;\n  int Jcols = (k*(d + 1)*(d + 2)) / 2;\n\n  adept::Stack stack;\n  adouble *aalphas = new adouble[k];\n  adouble *ameans = new adouble[d*k];\n  adouble *aicf = new adouble[icf_sz*k];\n\n      adept::set_values(aalphas, k, alphas);\n      adept::set_values(ameans, d*k, means);\n      adept::set_values(aicf, icf_sz*k, icf);\n\n      stack.new_recording();\n      adouble aerr;\n\n      adeptTest::gmm_objective(d, k, n, aalphas, ameans,\n          aicf, x, wishart, &aerr);\n      aerr.set_gradient(1.); // only one J row here\n\n      stack.compute_adjoint();\n\n      adept::get_gradients(aalphas, k, alphasb);\n      adept::get_gradients(ameans, d*k, meansb);\n      adept::get_gradients(aicf, icf_sz*k, icfb);\n\n  delete[] aalphas;\n  delete[] ameans;\n  delete[] aicf;\n}\n", "meta": {"hexsha": "866059217b96a5533719b244fc6a2a397c0e98b7", "size": 28935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enzyme/benchmarks/gmm/gmm.cpp", "max_stars_repo_name": "anandijain/Enzyme", "max_stars_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 674.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T17:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T11:18:11.000Z", "max_issues_repo_path": "enzyme/benchmarks/gmm/gmm.cpp", "max_issues_repo_name": "anandijain/Enzyme", "max_issues_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2020-10-07T00:47:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T16:46:58.000Z", "max_forks_repo_path": "enzyme/benchmarks/gmm/gmm.cpp", "max_forks_repo_name": "anandijain/Enzyme", "max_forks_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T14:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:51:07.000Z", "avg_line_length": 27.4786324786, "max_line_length": 135, "alphanum_fraction": 0.5202695697, "num_tokens": 9359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5036665761753181}}
{"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#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/dir.hpp>\n#include <dpMM/cat.hpp>\n#include <dpMM/niw.hpp>\n#include <dpMM/iw.hpp>\n#include <dpMM/normal.hpp>\n\n#include <omp.h>\n\n//#include <dpMM/matrix.h>\n//#include <dpMM/mex.h>\n//#include <dpMM/helperMEX.h>\n//#include <dpMM/debugMEX.h>\n\n#include \"gsl/gsl_rng.h\"\n#include \"gsl/gsl_randist.h\"\n#include \"gsl/gsl_permutation.h\"\n#include \"gsl/gsl_cdf.h\"\n\n//#include \"dpmmSubclusters/common.h\"\n//\n//#include \"dpmmSubclusters/niw_sampled.h\"\n////#include \"dpmmSubclusters/cluster_sampledT.cpp\"\n//#include \"dpmmSubclusters/linkedList.cpp\"\n//\n////#include \"dpmmSubclusters/reduction_array.h\"\n////#include \"dpmmSubclusters/reduction_array2.h\"\n//#include \"dpmmSubclusters/linear_algebra.h\"\n////#include \"dpmmSubclusters/sample_categorical.h\"\n////#include \"dpmmSubclusters/niw_sampled.h\"\n\n#include <dpMM/vmfPriorFull.hpp>\n#include <dpMM/vmf.hpp>\n\nusing std::cout;\nusing std::endl;\n\nBOOST_AUTO_TEST_CASE( dir_test)\n{\n  cout<<\"----------------------- dir ----------------------\"<<endl;\n  VectorXd alpha(3);\n  alpha << 1.0,100.0,1.0;\n\n  boost::mt19937 rndGen(1);\n  Dir<Cat<double>,double> dir(alpha,&rndGen);\n  VectorXd piPdf = dir.sample().pdf();\n\n  BOOST_CHECK_EQUAL(piPdf.size(),alpha.size());\n\n  cout<<\"-- sampling a bit\"<<endl;\n  cout<<\"alpha=\"<<alpha.transpose()<<endl;\n  for(uint32_t t=0; t<10; ++t)\n    cout<<\"piPdf=\"<<dir.sample().pdf().transpose()<<endl;\n\n  boost::mt19937 rndGen2(1);\n  Dir<Catd,double> dir2(alpha,&rndGen2);\n  VectorXd piPdf2 = dir2.sample().pdf();\n  BOOST_CHECK_EQUAL(piPdf,piPdf2);\n\n  Dir<Catd,double> dir3(dir);\n  VectorXd piPdf3 = dir3.sample().pdf();\n  BOOST_CHECK_EQUAL(piPdf.size(),piPdf3.size());\n\n  VectorXf alphaf = alpha.cast<float>();\n  Dir<Catf,float> dirf(alphaf,&rndGen);\n}\n\nBOOST_AUTO_TEST_CASE( cat_test)\n{\n  cout<<\"----------------------- cat ----------------------\"<<endl;\n  VectorXd pdf(3);\n  pdf << 0.5,0.25,0.25;\n\n  boost::mt19937 rndGen(1);\n  Cat<double> cat(pdf,&rndGen);\n  double z1 = cat.sample();\n  boost::mt19937 rndGen2(1);\n  Cat<double> cat2(pdf,&rndGen2);\n  double z2 = cat2.sample();\n  BOOST_CHECK_EQUAL(z1,z2);\n\n  Cat<double> cat3(cat);\n  double z3 = cat3.sample();\n\n  BOOST_CHECK_EQUAL(cat.pdf_.size(), cat3.pdf_.size());\n\n\n  VectorXu z(1000);\n  cat.sample(z);\n  cout<<\"-- sampling a bit\"<<endl;\n  cout<<\"pdf=\"<<pdf.transpose()<<endl;\n  cout<<\"z=\"<<z.transpose()<<endl;\n\n  VectorXd pdfEmp = Cat<double>(z,&rndGen).pdf();\n  BOOST_CHECK_EQUAL(pdfEmp.size(), cat.pdf().size());\n  cout<<\"pdf from counts=\"<<pdfEmp.transpose()<<endl;\n\n  VectorXf pdff = pdf.cast<float>();\n  Cat<float> catf(pdff,&rndGen);\n}\n\nBOOST_AUTO_TEST_CASE(iw_test)\n{\n  cout<<\"----------------------- iw ----------------------\"<<endl;\n\n  MatrixXd Delta(3,3);\n  Delta << 1.0,0.0,0.0,\n        0.0,1.0,0.0,\n        0.0,0.0,1.0;\n  double nu = 100.0;\n\n  boost::mt19937 rndGen(1);\n  IW<double> iw(Delta,nu,&rndGen);\n\n  for(uint32_t t=0; t<10; ++t)\n  {\n    MatrixXd Sigma = iw.sample();\n    cout<<\"Delta=\\n\"<<iw.Delta_<<endl;\n    cout<<\"Sigma=\\n\"<<Sigma<<endl;\n    cout<<\"logPdf=\"<<iw.logPdf(Sigma)<<endl;\n  }\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE( gauss_test)\n{\n  cout<<\"----------------------- gauss ----------------------\"<<endl;\n\n  MatrixXd Sigma(3,3);\n  Sigma << 1.0,0.0,0.0,\n        0.0,1.0,0.0,\n        0.0,0.0,1.0;\n  VectorXd mu(3);\n  mu << 1.0,1.0,1.0;\n\n  boost::mt19937 rndGen(1);\n  Normal<double> normal(mu,Sigma,&rndGen);\n\n  VectorXd x(3);\n  x << 1.0,1.0,1.0;\n  cout << normal.logPdf(x) <<endl;\n  x << 1.0,1.0,0.0;\n  cout << normal.logPdf(x) <<endl;\n  double a = normal.logPdf(x);\n  x << 0.0,1.0,1.0;\n  BOOST_CHECK_EQUAL(a,normal.logPdf(x));\n  cout << normal.logPdf(x) <<endl;\n  x << 0.0,0.0,0.0;\n  cout << normal.logPdf(x) <<endl;\n  BOOST_CHECK(a>normal.logPdf(x));\n\n\n  Sigma << 5.0,0.0,0.0,\n        0.0,1.0,0.0,\n        0.0,0.0,0.1;\n  mu << 1.0,1.0,0.0;\n  Normal<double> normalA(mu,Sigma,&rndGen);\n  for (uint32_t i=0; i<100; ++i)\n  {\n    x = normalA.sample();\n    cout<<\"x=\"<<x.transpose()<<\" logPdf=\"<<normalA.logPdf(x)<<endl;\n  }\n\n  cout<<\"small variance and far away data\"<<endl;\n  MatrixXd Sigma2D(2,2);\n  VectorXd mu2D(2);\n  VectorXd x2D(2);\n  Sigma2D << 1.0e-12,0.0,\n        0.0,1.0e-12;\n  mu2D << 0.0,0.0;\n  x2D << M_PI*0.5,0.0; // 90 degree away\n  Normal<double> normalS(mu2D,Sigma2D,&rndGen);\n  cout<<\" logPDf \"<<normalS.logPdf(x2D)<<endl;\n\n// check the sufficient statistics machinery\n  VectorXd SS(13);\n  SS <<                      120,\n         -18.3223543707169,\n          5.02645593390708,\n       -0.0572298238878314,\n          2.79777673293449,\n        -0.767573133190367,\n       0.00873808845092194,\n        -0.767573133190367,\n         0.210748312679343,\n      -0.00239897955468155,\n       0.00873808845092194,\n      -0.00239897955468155,\n      2.73160817868802e-05;\n\n  double count = SS(0);\n  Matrix<double,Dynamic,1> mean(3);\n  if(count>0)\n\t  mean = SS.middleRows(1,3)/count;\n  else\n\t  mean = Matrix<double,Dynamic,1>::Zero(3); //this should not matter since everything gets multiplied by 0 counts\n\n  cout<<\"SS \"<<SS.transpose()<<endl;\n  cout<<\"count \"<<count<<endl;\n  cout<<\"xSum \"<<SS.middleRows(1,3).transpose()<<endl;\n  cout<<\"mean \"<<mean.transpose()<<endl;\n\n  double* datPtr = const_cast<double*>(&(SS.data()[(3+1)]));\n  Matrix<double,Dynamic,Dynamic> scatter = \n    Map<Matrix<double,Dynamic,Dynamic> >(datPtr,3,3);\n  cout<<\"outerSum \"<<scatter<<endl;\n  scatter -= (mean*mean.transpose())*count;\n  cout<<\"scatter \"<<endl<<scatter<<endl;\n\n  Sigma << 0.0314229552991203,      -0.00429368708799009,\n        -0.000853036009326598,\n        -0.00429368708799009 ,       0.0292337474264411,\n        -5.82413154649128e-05,\n        -0.000853036009326598 ,    -5.82413154649128e-05,\n        0.000564454579403038;\n  cout<<\"Sigma \"<<endl<<Sigma<<endl;\n  mu <<  -0.04866953611, -0.02217239974,-0.02938455595 ;\n  cout<<\"mu \"<<mu.transpose()<<endl;\n  Normal<double> g(mu, Sigma,&rndGen);\n  cout<<\"logPdf      : \"<< g.logPdf(scatter,mean,count)<<endl;\n  cout<<\"logPdfSlower: \"<< g.logPdfSlower(scatter,mean,count)<<endl;\n  cout<<\"logDetSigma : \"<< g.logDetSigma()<<endl;\n\n}\n\n\nBOOST_AUTO_TEST_CASE( vMF_test)\n{\n  cout<<\"----------------------- vMF ----------------------\"<<endl;\n\n  VectorXd m0(3);\n  m0 << 0.0,0.0,1.0;\n  double t0 = 0.01;\n  double a0 = 2.0;\n  double b0 = 1.7;\n\n  boost::mt19937 rndGen(1);\n  vMFpriorFull<double> vMFprior(m0,t0,a0,b0,&rndGen);\n\n  MatrixXd x(3,100);\n  for(uint32_t i=0; i<100; ++i)\n    x(0,i) = 1.0;\n  VectorXu z(100); z.fill(0);\n  uint32_t k = 0;\n\n  vMFprior.getSufficientStatistics(x,z,k);\n\n  for(uint32_t i = 0; i < 10;++i)\n  {\n    cout<<\" -- \"<<endl;\n    vMF<double> vmf =  vMFprior.sample();\n    vmf.print();\n//    for(uint32_t j=0;j<10; ++j)\n//    {\n     vmf = vMFprior.sampleFromPosterior(vmf);\n    vmf.print();\n//      cout<<\" j=\"<<j<<\" logPdf = \"<<vMFprior.logPdf\n//    }\n  }\n\n}\n\n//BOOST_AUTO_TEST_CASE( niw_test) { cout<<\"----------------------- niw\n//----------------------\"<<endl;\n//\n//  uint32_t D =3;\n//  MatrixXd Delta(D,D);\n//  Delta << 1.0,0.0,0.0,\n//        0.0,1.0,0.0,\n//        0.0,0.0,1.0;\n//  VectorXd theta(D);\n//  theta << 1.0,1.0,1.0;\n//  double nu = 100.0;\n//  double kappa = 100.0;\n//\n//  boost::mt19937 rndGen(1);\n//  NIW<double> niw(Delta,theta,nu,kappa,&rndGen);\n//\n//  for(uint32_t t=0; t<10; ++t)\n//  {\n//    Normal<double> Norm = niw.sample();\n//\tNorm.print();\n//    cout<<\"logPdf=\"<<niw.logPdf(Norm)<<endl;\n//  }\n//  cout<<\" comparing NIW against Jasons implementation ------\"<<endl;\n//  niw.print();\n//\n//  uint32_t N=80;\n//  uint32_t K=1;\n//  VectorXu z(N);\n//  shared_ptr<MatrixXd> spx(new MatrixXd(D,N));\n//  cout<<\"true mus:\"<<endl<<sampleClusters<double>(*spx, z, K)<<endl;\n//\n//  double count = N;\n//  MatrixXd Outer(D,D); Outer.setZero();\n//  VectorXd sum(D); sum.setZero();\n//  for(uint32_t i=0; i<N; ++i)\n//  {\n//    sum += spx->col(i);\n//    Outer += spx->col(i)*spx->col(i).transpose();\n//  }\n//  cout<<\"Outer\"<<endl<<Outer<<endl;\n//  cout<<\"sum\"<<endl<<sum<<endl;\n//  cout<<\"1/N*sum*sum.T\"<<endl<<sum*sum.transpose()/count<<endl;\n//  cout<<\"sum*sum.T\"<<endl<<sum*sum.transpose()<<endl;\n//  MatrixXd Scatter = Outer - sum*sum.transpose() / count;\n//  VectorXd mean = sum/count;\n//  cout<<\"Scatter\"<<endl<<Scatter<<endl;\n//\n//  niw.scatter() = Scatter;\n//  niw.mean() = mean;\n//  niw.count() = count;\n//\n//  cout<<\"--- Julians posterior:\"<<endl;\n//  niw.posterior().print();\n//\n//  cout<<\"--- Julians posterior direct:\"<<endl;\n//  niw.posterior(*spx,z,0).print();\n//\n//\n//  MatrixXd DeltaOverNu(Delta);\n//  DeltaOverNu /= nu;\n//  VectorXd thetaOverKappa(theta);\n////  thetaOverKappa /= kappa;\n//  niw_sampled niwJason(3,kappa,nu,thetaOverKappa.data(),DeltaOverNu.data());\n//  niwJason.set_stats(count,sum.data(),Outer.data());\n//  niwJason.update_posteriors();\n//\n//  Map<MatrixXd> DeltaPost(niwJason.Delta,D,D);\n//  Map<VectorXd> thetaPost(niwJason.theta,D);\n//  cout<<\"--- Jason posterior:\"<<endl;\n//  cout<<\"nu=\"<<niwJason.nu<<\" kappa=\"<<niwJason.kappa<<endl;\n//  cout<<\"delta\"<<endl<<DeltaPost<<endl;\n//  cout<<\"theta \"<<thetaPost.transpose()<<endl;\n//  cout<<\"--- Jasons adapted to julians:\"<<endl;\n//  cout<<\"delta\"<<endl<<DeltaPost*niwJason.nu<<endl;\n//  cout<<\"theta \"<<thetaPost.transpose()*niwJason.kappa<<endl;\n//\n//  cout<<\" ----- marginal probability of data under NIW\"<<endl;\n//  cout<<\" Julian: \"<<niw.logPdfMarginalized()<<endl;\n//  cout<<\" Jason:  \"<<niwJason.data_loglikelihood_marginalized()<<endl;\n//\n//  BOOST_CHECK(fabs(niw.logPdfMarginalized() - niwJason.data_loglikelihood_marginalized())<1e-3);\n//\n//  cout<<\"------------------ merge test -----------------------\"<<endl;\n//\n//  NIW<double> niwB(Delta,theta,nu,kappa,&rndGen);\n//\n//  double countB = 1000;\n//  MatrixXd OuterB(D,D);\n//  OuterB<< 10,0,0,\n//          0,100,0,\n//          0,0,10;\n//  VectorXd sumB(D);\n//    sumB << 1,10,0;\n//  MatrixXd ScatterB = OuterB ;//- count*sum*sum.transpose();\n//  VectorXd meanB = sumB/countB;\n//  cout<<\"Scatter\"<<endl<<ScatterB<<endl;\n//\n//  niwB.scatter() = ScatterB;\n//  niwB.mean() = meanB;\n//  niwB.count() = countB;\n//\n//  NIW<double>* niwBmerged = niwB.merge(niw);\n//  cout<<\"--- Julians posterior after merge:\"<<endl;\n//  niwBmerged->posterior().print();\n//\n//  MatrixXd DeltaOverNuB(Delta);\n//  DeltaOverNuB /= nu;\n//  VectorXd thetaOverKappaB(theta);\n////  thetaOverKappa /= kappa;\n//  niw_sampled niwJasonB(3,kappa,nu,thetaOverKappaB.data(),DeltaOverNuB.data());\n//  niwJasonB.set_stats(countB,sumB.data(),OuterB.data());\n//  niwJasonB.update_posteriors();\n//  Map<MatrixXd> DeltaPostB(niwJasonB.Delta,D,D);\n//  Map<VectorXd> thetaPostB(niwJasonB.theta,D);\n//\n//  niwJasonB.merge_with(niwJason, false);\n////  niwJasonB.update_posteriors();\n//  cout<<\"--- Jason posterior after merge:\"<<endl;\n//  cout<<\"nu=\"<<niwJasonB.nu<<\" kappa=\"<<niwJasonB.kappa<<endl;\n//  cout<<\"delta\"<<endl<<DeltaPostB<<endl;\n//  cout<<\"theta \"<<thetaPostB.transpose()<<endl;\n//  cout<<\"--- Jasons adapted to julians:\"<<endl;\n//  cout<<\"delta\"<<endl<<DeltaPostB*niwJasonB.nu<<endl;\n//  cout<<\"theta \"<<thetaPostB.transpose()*niwJasonB.kappa<<endl;\n//\n//  cout<<\" ------------------- sampling ----------------------------\"<<endl;\n//  for(uint32_t t=0; t<5; ++t)\n//  {\n//    cout<<\"Jason:\"<<endl;\n//    niwJasonB.sample();\n//    Map<MatrixXd> jasonCov(niwJasonB.param.cov,D,D);\n//    Map<VectorXd> jasonMean(niwJasonB.param.mean,D);\n//    cout<<jasonMean.transpose()<<endl;\n//    cout<<jasonCov<<endl;\n//    cout<<\"Julian:\"<<endl;\n//    Normal<double> normB = niwB.posterior().sample();\n//    normB.print();\n//\n//    //cout<<normB.mu_.transpose()<<endl;\n//    //cout<<normB.Sigma_<<endl;\n//  }\n//}\n", "meta": {"hexsha": "b306667ece4600f16c84da19c70ef36ddc359be4", "size": 11810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/distributions.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/distributions.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/distributions.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": 28.4578313253, "max_line_length": 114, "alphanum_fraction": 0.6033869602, "num_tokens": 3973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5036350886631721}}
{"text": "#define BOOST_TEST_MODULE TEST_PARAMS\n\n#include <dynet/dynet.h>\n#include <dynet/expr.h>\n#include <dynet/model.h>\n#include <boost/test/unit_test.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <iostream>\n#include <fstream>\n\n#include <stdexcept>\n\nusing namespace dynet;\nusing namespace dynet::expr;\nusing namespace std;\n\nstruct ParamsTest {\n    ParamsTest() {\n        // initialize if necessary\n        if (default_device == nullptr) {\n            for (auto x : {\"ParamsTest\", \"--dynet-mem\", \"512\"}) {\n                av.push_back(strdup(x));\n            }\n            char **argv = &av[0];\n            int argc = av.size();\n            dynet::initialize(argc, argv);\n        }\n        gain = 2.0;\n        epsilon = 1e-6; \n        d = dynet::Dim({10, 10});\n    }\n    ~ParamsTest() {\n        for (auto x : av) free(x);\n    }\n\n\n    float gain, epsilon;\n    dynet::Dim d;\n    std::vector<char*> av;\n};\n\n// define the test suite\nBOOST_FIXTURE_TEST_SUITE(params_test, ParamsTest);\n\nBOOST_AUTO_TEST_CASE( init_saxe ) {\n    dynet::Model mod;\n    // Random orthogonal matrix scaled by gain\n    dynet::Parameter saxe_p = mod.add_parameters({10, 10}, ParameterInitSaxe(gain));\n    // gain^2 * identity matrix\n    dynet::Parameter identity_p = mod.add_parameters({10, 10}, ParameterInitIdentity());\n    // Initialize graph\n    dynet::ComputationGraph cg;\n    dynet::Expression saxe = dynet::parameter(cg, saxe_p);\n    dynet::Expression identity = dynet::parameter(cg, identity_p);\n    // check that the matrix is indeed orthogonal\n    dynet::Expression diff_expr_left = dynet::squared_norm(dynet::transpose(saxe) * saxe - (gain * gain) * identity);\n    dynet::Expression diff_expr_right = dynet::squared_norm(saxe * dynet::transpose(saxe) - (gain * gain) * identity);\n    float diff = dynet::as_scalar(cg.forward((diff_expr_left + diff_expr_right) / 2.0));\n    // Leave a margin of error of epsilon=10^-6\n    BOOST_CHECK_LT(diff, epsilon);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e6e18d2f7cb489580a0d8dcf710127602737b549", "size": 2010, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/test-params.cc", "max_stars_repo_name": "cherryc/dynet", "max_stars_repo_head_hexsha": "54bf3fa04f55f0730a9a21b5708e94dc153394da", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-10T17:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-10T17:40:09.000Z", "max_issues_repo_path": "tests/test-params.cc", "max_issues_repo_name": "cherryc/dynet", "max_issues_repo_head_hexsha": "54bf3fa04f55f0730a9a21b5708e94dc153394da", "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/test-params.cc", "max_forks_repo_name": "cherryc/dynet", "max_forks_repo_head_hexsha": "54bf3fa04f55f0730a9a21b5708e94dc153394da", "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.9230769231, "max_line_length": 118, "alphanum_fraction": 0.6517412935, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5036350863590491}}
{"text": "// ROS includes\n#include \"ros/ros.h\"\n#include \"ros/assert.h\"\n#include \"dynamic_reconfigure/server.h\"\n#include \"create_driver/vicon_driver.h\"\n#include \"geometry_msgs/Twist.h\"\n\n// Library includes\n#include <string>\n#include <vector>\n#include <map>\n#include <Eigen/Core>\n#include <Eigen/LU>\n\n// Local Package includes\n#include \"to_velocity_tracking/ControlVariablesConfig.h\"\n#include \"to_velocity_tracking/ControlMsgs.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n// Constants\nconst double PI = 3.1415926535;\nconst double wmax = 8;\n\n// Dynamic reconfigure variables\ndouble k = 0.5; // linear velocity gain\ndouble ktheta = 5.0; // angular velocity gain\nbool power = true;\ndouble epsilon = 0.25;\nbool u_switch = true;\n\nvoid reconfigureCallback(to_velocity_tracking::ControlVariablesConfig &config, uint32_t level) {\n\tk = config.k;\n\tktheta = config.ktheta;\n\tpower = config.power;\n\tepsilon = config.epsilon;\n\tu_switch = config.u_switch;\n}\n\nint main(int argc, char **argv)\n{\n\t// ROS Initalization\n\tros::init(argc, argv, \"control\");\n\t\n\tros::NodeHandle n;\n\tros::NodeHandle private_n(\"~\");\n\t\n\t// ROS Parameters\n\n\t// List of robot names\n\tvector<string> robot_names;\n\tXmlRpc::XmlRpcValue robot_list;\n\tprivate_n.getParam(\"robot_list\", robot_list);\n\tROS_ASSERT(robot_list.getType() == XmlRpc::XmlRpcValue::TypeArray);\n\n\tfor (int i = 0; i < robot_list.size(); i++) \n\t{\n\t\tROS_ASSERT(robot_list[i].getType() == XmlRpc::XmlRpcValue::TypeString);\n\t\trobot_names.push_back(static_cast<string>(robot_list[i]));\n\t}\n\n\t// Number of robots\n\tconst int num_robots = robot_names.size();\n\n\t// Robot name\n\tstring robot_name;\n\tprivate_n.param<std::string>(\"robotname\", robot_name, \"defaultname\");\n\n\tint index = find(robot_names.begin(), robot_names.end(), robot_name) - robot_names.begin();\n\n\t// ROS Dynamic Reconfigure\n\n\tdynamic_reconfigure::Server<to_velocity_tracking::ControlVariablesConfig> server;\n  \tdynamic_reconfigure::Server<to_velocity_tracking::ControlVariablesConfig>::CallbackType f;\n  \tf = boost::bind(&reconfigureCallback, _1, _2);\n \tserver.setCallback(f);\n\n\t// ROS Subscribers\n\tmap<string, create_driver::ViconStream> vicon;\n\tvector<string>::iterator name_it;\n\tvector<ros::Subscriber> sub;\n\tfor (name_it = robot_names.begin(); name_it != robot_names.end(); name_it++)\n\t{\n\t\tvicon.insert(pair<string, create_driver::ViconStream>(*name_it, create_driver::ViconStream()));\n\t\tsub.push_back(n.subscribe(\"/\" + *name_it + \"/tf\", 10, &create_driver::ViconStream::callback, &vicon[*name_it]));\n\t}\n\n\n\t// ROS Publishers\n\tros::Publisher vel = n.advertise<geometry_msgs::Twist>(\"cmd_vel\", 10);\n\n\tros::Publisher dia = n.advertise<to_velocity_tracking::ControlMsgs>(\"dia\", 10);\n\n\t// ROS loop\n\tros::Rate loop_rate(250); // 250 Hz\n\t\n\twhile (ros::ok())\n\t{\n\t\t// Retrieve Vicon Data\n\t\tros::spinOnce();\n\n\t\t/* An instance of this code is run on each robot in the formation.\n\t\t *\n\t\t * You can access each robot's position and oreintation through the following statements:\n\t\t * vicon[robot_names[i]].x()\n\t\t * vicon[robot_names[i]].y()\n\t\t * vicon[robot_names[i]].theta()\n\t\t * \n\t\t * The index of the robot running the instance of the code is contain in the \"index\" \n\t\t * variable. For example, if you wanted to get the distance of this robot from all of its\n\t\t * neighbors you could run the following:\n\t\t * double dist[num_robots];\n\t\t * for (int i = 0; i < num_robots; i++) {\n\t\t * \t\tdist[i] = sqrt(pow(vicon[robot_names[i]].x() - vicon[robot_names[index]].x(),2) \n\t\t * \t\t\t\t     + pow(vicon[robot_names[i]].y() - vicon[robot_names[index]].y(),2));\n\t\t * }\n\t\t */\n\t\tdouble ux = 0;\n\t\tdouble uy = 0;\n\n\t\tif (u_switch) {\n\t\t\tux = 1;\n\t\t\tuy = 1;\n\t\t} else {\n\t\t\tux = -1;\n\t\t\tuy = -1;\n\t\t}\n\n\t\tdouble thetad = atan2(uy, ux);\n\t\tdouble theta = vicon[robot_name].theta();\n\t\tdouble etheta = theta - thetad;\n\n\t\tdouble v = k*1000*cos(etheta)*sqrt(pow(ux,2) + pow(uy,2)); // linear velocity output\n\t\tdouble w = -ktheta*etheta; // angular velocity output\n\n\n\n\t\tif (fabs(etheta) > epsilon){\n\t\t\tv = 0;\n\t\t\tw = (etheta > 0) ? -wmax : wmax;\t\t\t\n\t\t}\n\t\t\n\t\tif ( power ) {\n\t\t// Send wheel velocities to driver\n\t\t\tgeometry_msgs::Twist msg;\n\t\t\tmsg.linear.x = v;\n\t\t\tmsg.linear.y = 0;\n\t\t\tmsg.linear.z = 0;\n\t\t\tmsg.angular.x = 0;\n\t\t\tmsg.angular.y = 0;\n\t\t\tmsg.angular.z = w;\n\t\t\tvel.publish(msg);\n\t\t} else {\n\t\t\tgeometry_msgs::Twist msg;\n\t\t\tmsg.linear.x = 0;\n\t\t\tmsg.linear.y = 0;\n\t\t\tmsg.linear.z = 0;\n\t\t\tmsg.angular.x = 0;\n\t\t\tmsg.angular.y = 0;\n\t\t\tmsg.angular.z = 0;\n\t\t\tvel.publish(msg);\n\t\t}\t\t\n\n\t\tto_velocity_tracking::ControlMsgs dmsg; \n\t\tdmsg.theta = theta;\n\n\t\tdia.publish(dmsg);\n\n\t\tloop_rate.sleep();\n\t}\n\t\n\treturn 0;\n}", "meta": {"hexsha": "6d79a1171a22a63f94fdee5392f9285b498e0f50", "size": 4536, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/to_velocity_tracking/src/control_node.cpp", "max_stars_repo_name": "rsthomp/UTDchess-RospyXbee", "max_stars_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-03T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-03T01:52:06.000Z", "max_issues_repo_path": "src/to_velocity_tracking/src/control_node.cpp", "max_issues_repo_name": "RachaelT/UTDchess-RospyXbee", "max_issues_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/to_velocity_tracking/src/control_node.cpp", "max_forks_repo_name": "RachaelT/UTDchess-RospyXbee", "max_forks_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0689655172, "max_line_length": 114, "alphanum_fraction": 0.6801146384, "num_tokens": 1310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5036350837450364}}
{"text": "//===----------------------------------------------------------------------===//\r\n//\r\n//                     The LLVM Compiler Infrastructure\r\n//\r\n// This file is dual licensed under the MIT and the University of Illinois Open\r\n// Source Licenses. See LICENSE.TXT for details.\r\n//\r\n//===----------------------------------------------------------------------===//\r\n//  Adaptation to Boost of the libcxx\r\n//  Copyright 2010 Vicente J. Botet Escriba\r\n//  Distributed under the Boost Software License, Version 1.0.\r\n//  See http://www.boost.org/LICENSE_1_0.txt\r\n\r\n// duration\r\n// Test nested types\r\n\r\n// typedef Rep rep;\r\n// typedef Period period;\r\n\r\n#include <boost/chrono/duration.hpp>\r\n#include <boost/type_traits.hpp>\r\n#if !defined(BOOST_NO_STATIC_ASSERT)\r\n#define NOTHING \"\"\r\n#endif\r\n\r\ntypedef boost::chrono::duration<long, boost::ratio<3, 2> > D;\r\nBOOST_CHRONO_STATIC_ASSERT((boost::is_same<D::rep, long>::value), NOTHING, ());\r\nBOOST_CHRONO_STATIC_ASSERT((boost::is_same<D::period, boost::ratio<3, 2> >::value), NOTHING, ());\r\n", "meta": {"hexsha": "fde65161935cf3cddc40e302e57bd468d1e84580", "size": 1030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/chrono/test/duration/types_pass.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/chrono/test/duration/types_pass.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/chrono/test/duration/types_pass.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.5172413793, "max_line_length": 98, "alphanum_fraction": 0.5815533981, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5036350837450364}}
{"text": "#ifndef CUAUV_SIM_ENTITY_H\n#define CUAUV_SIM_ENTITY_H\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace cuauv {\nnamespace fishbowl {\n\ntypedef Eigen::DiagonalMatrix<double, 3> inertia_tensor;\n\n/**\n * Entity represents an entity in a World.\n */\nclass entity {\npublic:\n    /**\n     * Constructs a new entity.\n     *\n     * @param m Mass.\n     * @param r Radius.\n     * @param I Inertia tensor, in the body frame.\n     * @param btom_rq Body to model frame rotation quaternion. Undefined behavior if not normalized.\n     */\n    entity(double m, double r, const inertia_tensor& I, const Eigen::Quaterniond& btom_rq);\n\n    double get_m() const; //!< Mass.\n    double get_r() const; //!< Radius.\n    inertia_tensor get_I() const; //!< Inertia tensor, in the body frame.\n\n    Eigen::Vector3d x { 0, 0, 0 }; //!< Position.\n    Eigen::Vector3d v { 0, 0, 0 }; //!< Translational velocity, in the world frame.\n    Eigen::Vector3d a { 0, 0, 0 }; //!< Translational acceleration in the previous timestep, in the world frame.\n\n    Eigen::Vector3d xp { 0, 0, 0 }; //!< Position, in the previous timestep. Initially 0.\n\n    /**\n     * Orientation, of the body relative to the world frame.\n     * To convert to the orientation of the model relative to the world frame, use\n     * <tt>q * body_rm_inv</tt>\n     * Behavior is undefined if q is not a unit quaternion.\n     */\n    Eigen::Quaterniond q { 1, 0, 0, 0 };\n    Eigen::Vector3d w { 0, 0, 0 }; //!< Angular velocity, in the body frame.\n    Eigen::Vector3d t { 0, 0, 0 }; //<! Torque, in the body frame, in the previous timestep.\n\n    bool corporeal = true; //!< True iff forces and engines should affect this entity.\n\n    /**\n     * The rotation matrix from the body frame to the model frame.\n     * We precompute the matrix because it is more efficient for rotation\n     * operations, according to Eigen's documentation.\n     * @see http://eigen.tuxfamily.org/dox/classEigen_1_1Quaternion.html\n     */\n    Eigen::Matrix3d get_btom_rm() const;\n    Eigen::Matrix3d get_mtob_rm() const;\n\n    // Utility functions.\n\n    inertia_tensor get_Ir() const; //!< The reciprocal of the inertia tensor, in the body frame.\n    Eigen::Quaterniond get_model_q() const; //!< Orientation, of the model relative to the world frame.\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n    double m;\n    double r;\n    inertia_tensor I;\n    inertia_tensor Ir;\n    Eigen::Quaterniond btom_rq;\n    Eigen::Matrix3d btom_rm;\n    Eigen::Matrix3d mtob_rm;\n    Eigen::Quaterniond model_q;\n};\n\n} // namespace fishbowl\n} // namespace cuauv\n\n#endif // CUAUV_SIM_ENTITY_H\n", "meta": {"hexsha": "f98df4fc258bdf3e3f9e11c34b7e29391bf24aa4", "size": 2581, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fishbowl/entity.hpp", "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/entity.hpp", "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/entity.hpp", "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.2625, "max_line_length": 112, "alphanum_fraction": 0.6698953894, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5036350788269007}}
{"text": "#ifndef _CNF_SIMPLE_HPP\n#define _CNF_SIMPLE_HPP\n\n#include <iostream>\n#include <vector>\n#include <map>\n#include <set>\n#include <gmpxx.h>\n#include <string>\n#include <fstream>\n#include <cstdlib>\n#include <array>\n#include <tuple>\n#include <ctime>\n#include <boost/multiprecision/gmp.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string.hpp>\n\n// debug parameter\n#define DEBUG 1\n\n// type definitions for matrix, sparse matrix and sparse vector\ntypedef std::set<boost::multiprecision::mpz_int> s_vector;\ntypedef std::map<int, s_vector> s_matrix;\ntypedef std::vector<std::vector<int>> matrix;\n\n// node structure for the Tree structure\nstruct Node {\n  int              idx;   // index (line of CNF matrix)\n  int              value; // value (0 or 1)\n  std::vector<int> alpha; // vector of alpha_i for the node\n  Node            *left;  // left child\n  Node            *right; // right child\n};\n\n// Tree structure used by compute_all_h_fasy\nstruct Tree {\n  Node *root;                  // root node\n  std::string id_cnf;          // the id of the problem (typically the filename)\n  \n  Tree(std::string an_id);\n  ~Tree();\n  void destroy_tree(Node *leaf);          \n  void create_tree(s_matrix &H, int n_litterals);\n  int create_children(Node *cur_node, s_matrix &H, int n_litterals);\n};   \n\n// split a string into a 2-uple (id, s_vector)\nstd::tuple<int, s_vector> split(const std::string &msg, const std::string &separators);\n\n// removing a file\nvoid remove_file(std::string filename);\n\n// create a cnf matrix from an input file\nmatrix read_input(std::string filename);\n\n// create a sparse vector from an input file\nstd::tuple<int, s_vector> read_input_vector(std::string filename);\n\n// create a sparse matrix from an input  file\ns_matrix read_input_matrix(std::string filename);\n\n// compute the matrics F, G and H for a clause of a cnf matrix  \nstd::tuple<int, s_matrix, s_matrix, s_matrix> compute_FGH(matrix const &matrix_cnf, int clause);\n\n// given the indexes of 3 litterals, compute the associated index \nboost::multiprecision::mpz_int compute_index3(int index_1, int index_2, int index_3, int n_litterals);\n\n// compute a given row of matrix D telling wich alpha_k are present the row (OK!)\nstd::vector<int> D_fnct(boost::multiprecision::mpz_int row, int n_litterals);\n\n// add an element to a binary matrix/vector\nvoid add_elem_vector(s_vector &v, boost::multiprecision::mpz_int val);\nvoid add_elem_matrix(s_matrix &matrix, int row, boost::multiprecision::mpz_int col);\n\n// printing sparse matrices and (sparse) vectors\nvoid print_matrix_s(s_matrix const &M);\nvoid print_vector_s(s_vector const &v);\nvoid print_vector(std::vector<int> const &v, unsigned int start = 0);\n\n// saving a sparse matrix/vector in a file\nvoid save_matrix_s(s_matrix const &M, std::string filename);\nvoid save_vector(std::vector<int> const &v, unsigned int start = 0, std::string filename = \"sol\");\n\n// simplifies a binary matrix/vector\ns_matrix simplify_matrix_sparse(s_matrix &matrix_in, int n_litterals, int cur_litteral);\ns_vector simplify_vector_sparse(s_matrix &matrix_in, s_vector &vector_in, int cur_row, int n_litterals);\n\n// create a matrix from a vector\ns_matrix generate_matrix(s_vector &v, int row);\n\n// remove a row in the matrix M\nvoid remove_row_in_M(s_matrix &M, int row);\n\n// copy a vector in a given row of M\nvoid copy_vector_in_M(s_matrix &M, s_vector &v, int row);\n\n// copy a given row of M in row\ns_vector copy_row_in_v(s_matrix &M, int row);\n\n// check if a sparse vector is empty\nbool is_null(s_vector const &v);\n\n// check if 2 vectors are equals component-wise\nbool is_equal(std::vector<int> const &v_1, const std::vector<int> &v_2);\n\n// return the number of ones in a given row of a sparse matrix\nsize_t count_ones_vector(s_matrix &matrix_in, int cur_row);\n\n// compute the vectors I_0 and I_1 from I\nstd::tuple<s_vector, s_vector> compute_I0_I1(s_vector &I, int n_litterals, int alpha_k);\n\n// from a given binary vector and the number of litterals, return the index in the D matrix\nboost::multiprecision::mpz_int compute_index_vect2(std::vector<int> const &v, int n_litterals);\n\n// adding two binary vectors\nvoid add(s_vector &v_1, s_vector &v_2);\ns_vector add_out(s_vector const &v_1, s_vector const &v_2);\n\n// component wise binary vector operation (if v_2[1] then out[i] = 1 else out[i] = v_1[i])\nstd::vector<int> mult(std::vector<int> const &v_1, std::vector<int> const &v_2);\n\n// adding two binary matrices\ns_matrix add_matrix(s_matrix const &M_1, s_matrix const &M_2);\n\n// multiply a vector with another one using the matrix D representing the binary vectors\ns_vector mult_mat_vec(s_vector &v1, s_vector &v2, int n_litterals);\n\n// return the maximum k of the alpha_i in a vector v\nint get_highest_alpha_k(s_vector &v, int n_litterals);\n\n// merges 2 clauses using the matrics H, F and G.\nbool merge(s_matrix &H1, s_matrix &H2, s_matrix &F1, s_matrix &F2, s_matrix &G1, \n           s_matrix &G2, std::vector<int> &row_constraint, int id_new_constraint,\n           int *lev_rec, int n_litterals);\n\n// given an index and the number of litterals, generate the associated binary vector alpha                      \nstd::vector<int> generate_alpha(int n_litterals, boost::multiprecision::mpz_int x);\n\n// returns the output of H for a given vector alpha\nstd::vector<int> h_vector(s_matrix &H, int n_litterals, std::vector<int> &alpha);\n\n// compute the value of a row of H when we replace the alpha_i by some values, i.e. for a given vector alpha\nint compute_h_i(std::vector<int> &v_alpha, s_vector &row_H, int n_litterals);\n\n// compute every solution of a matrix H\nvoid compute_all_h(s_matrix &H, int n_litterals);\n// efficiently compute every solution of a matrix H using a tree structure\nvoid compute_all_h_fast(s_matrix &H, int n_litterals, std::string filename);\n\n// deterniming a\nvoid merge_matrices(std::string filename);\n\n// mergin a CNF matrix H with a line (vector) of another CNF matrix\nvoid merge_matrix_vector(std::string filename_matrix, std::string filename_vector);\n\n// compute the max litteral in the remaining clauses\nstd::vector<int> compute_max_lit_remaining_clauses(matrix &input_matrix);\n\n// print the alpha in a row of a matrix\nvoid print_alphas(s_matrix &matrix_in, int cur_row, int n_litterals);\n\n#endif\n\n", "meta": {"hexsha": "1788e3b1b7b359e9161784577c616f9082566c28", "size": 6270, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "algo/cnf.hpp", "max_stars_repo_name": "3cnf/descriptor-solver", "max_stars_repo_head_hexsha": "f76a795c16c8b024841600402da2f3f7ee6fdee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algo/cnf.hpp", "max_issues_repo_name": "3cnf/descriptor-solver", "max_issues_repo_head_hexsha": "f76a795c16c8b024841600402da2f3f7ee6fdee1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algo/cnf.hpp", "max_forks_repo_name": "3cnf/descriptor-solver", "max_forks_repo_head_hexsha": "f76a795c16c8b024841600402da2f3f7ee6fdee1", "max_forks_repo_licenses": ["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.7710843373, "max_line_length": 112, "alphanum_fraction": 0.7397129187, "num_tokens": 1644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5036350689906293}}
{"text": "/** \\file   cmr_t1_mapping.cpp\n    \\brief  Implement CMR T1 mapping for 2D acquisition\n    \\author Hui Xue\n*/\n\n#include \"cmr_t1_mapping.h\"\n#include \"log.h\"\n\n#include \"hoNDArray_reductions.h\"\n#include \"hoNDArray_elemwise.h\"\n#include \"hoNDArray_math.h\"\n\n#include \"simplexLagariaSolver.h\"\n#include \"twoParaExpRecoveryOperator.h\"\n#include \"curveFittingCostFunction.h\"\n\n#include <boost/math/special_functions/sign.hpp>\n\nnamespace Gadgetron { \n\ntemplate <typename T> \nCmrT1SRMapping<T>::CmrT1SRMapping() : BaseClass()\n{\n    max_iter_ = 150;\n    max_fun_eval_ = 1000;\n    thres_fun_ = 1e-4;\n\n    // maximal allowed T1\n    max_map_value_ = 2500;\n}\n\ntemplate <typename T> \nCmrT1SRMapping<T>::~CmrT1SRMapping()\n{\n}\n\ntemplate <typename T>\nvoid CmrT1SRMapping<T>::get_initial_guess(const VectorType& ti, const VectorType& yi, VectorType& guess)\n{\n    if (guess.size() != this->get_num_of_paras())\n    {\n        guess.resize(this->get_num_of_paras(), 0);\n    }\n\n    guess[0] = 500;\n    guess[1] = 1200;\n\n    // A\n    if(!yi.empty()) guess[0] = *std::max_element(yi.begin(), yi.end());\n\n    // T1\n    if (!ti.empty()) guess[1] = ti[ti.size() / 2];\n}\n\ntemplate <typename T>\nvoid CmrT1SRMapping<T>::compute_map(const VectorType& ti, const VectorType& yi, const VectorType& guess, VectorType& bi, T& map_v)\n{\n    try\n    {\n        bi = guess;\n        map_v = 0;\n\n        typedef Gadgetron::twoParaExpRecoveryOperator< std::vector<T> > SignalType;\n        typedef Gadgetron::leastSquareErrorCostFunction< std::vector<T> > CostType;\n\n        // define solver\n        Gadgetron::simplexLagariaSolver< VectorType, SignalType, CostType > solver;\n\n        // define signal model\n        SignalType t1_sr;\n\n        // define cost function\n        CostType lse;\n\n        solver.signal_model_ = &t1_sr;\n        solver.cf_ = &lse;\n\n        solver.max_iter_ = max_iter_;\n        solver.max_fun_eval_ = max_fun_eval_;\n        solver.thres_fun_ = thres_fun_;\n\n        solver.x_ = ti;\n        solver.y_ = yi;\n\n        solver.solve(bi, guess);\n\n        if (bi[0] > 0 && bi[1] > 0)\n        {\n            map_v = bi[1];\n            if (map_v >= max_map_value_) map_v = hole_marking_value_;\n            if (map_v <= min_map_value_) map_v = hole_marking_value_;\n        }\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Exceptions happened in CmrT1SRMapping<T>::compute_map(...) ... \");\n    }\n}\n\ntemplate <typename T>\nvoid CmrT1SRMapping<T>::compute_sd(const VectorType& ti, const VectorType& yi, const VectorType& bi, VectorType& sd, T& map_sd)\n{\n    try\n    {\n        sd.clear();\n        sd.resize(bi.size(), 0);\n\n        map_sd = 0;\n\n        typedef Gadgetron::twoParaExpRecoveryOperator< std::vector<T> > SignalType;\n        SignalType t1_sr;\n\n        // compute fitting values\n        VectorType y;\n        t1_sr.magnitude(ti, bi, y);\n\n        // compute residual\n        VectorType res(y), abs_res(y);\n\n        size_t num = ti.size();\n        size_t N = this->get_num_of_paras();\n\n        size_t n;\n        for (n = 0; n < num; n++)\n        {\n            res[n] = y[n] - yi[n];\n            abs_res[n] = std::abs(res[n]);\n        }\n\n        hoNDArray<T> grad;\n        grad.create(N, num);\n        Gadgetron::clear(grad);\n\n        VectorType gradVec(N);\n        for (n = 0; n < num; n++)\n        {\n            t1_sr.gradient(ti[n], bi, gradVec);\n            memcpy(grad.begin() + n*N, &gradVec[0], sizeof(T)*N);\n        }\n\n        GADGET_CATCH_THROW(this->compute_sd_impl(ti, yi, bi, abs_res, grad, sd));\n\n        map_sd = sd[1];\n        if (map_sd > max_map_value_) map_sd = this->hole_marking_value_;\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Exceptions happened in CmrT1SRMapping<T>::compute_map(...) ... \");\n    }\n}\n\ntemplate <typename T>\nsize_t CmrT1SRMapping<T>::get_num_of_paras() const\n{\n    return 2; // A and T1\n}\n\n// ------------------------------------------------------------\n// Instantiation\n// ------------------------------------------------------------\n\ntemplate class EXPORTCMR CmrT1SRMapping< float >;\n\n}\n", "meta": {"hexsha": "b32d75c9d14f08ef54c3e9005ba98895d4f2dfdd", "size": 4002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolboxes/cmr/cmr_t1_mapping.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "toolboxes/cmr/cmr_t1_mapping.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolboxes/cmr/cmr_t1_mapping.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["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.2545454545, "max_line_length": 130, "alphanum_fraction": 0.5802098951, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5035921741455461}}
{"text": "//Author: Dr. Shantanu Shahane\n#ifndef __coefficient_computations_H\n#define __coefficient_computations_H\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <float.h>\n#include <string.h>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include \"class.hpp\"\n#include <unistd.h>\n#include <limits.h>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/SparseExtra>\n#include <Eigen/SparseLU>\n#include <Eigen/OrderingMethods>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Spectra/GenEigsSolver.h>\n#include <Spectra/MatOp/SparseGenMatProd.h>\n#include <Spectra/GenEigsRealShiftSolver.h>\n#include <Spectra/MatOp/SparseGenRealShiftSolve.h>\nusing namespace std;\n\nvoid shifting_scaling(vector<double> &vert, double *scale, int dim);\n\nvoid shifting_scaling(double *xyz_interp, vector<double> &vert, double *scale, int dim);\n\nvoid calc_PHS_RBF_grad_laplace_single_vert_A(vector<double> &vert, PARAMETERS &parameters, Eigen::MatrixXd &A, double *scale);\n\nvoid calc_PHS_RBF_grad_laplace_single_vert_grad_x_rhs(vector<double> &vert, PARAMETERS &parameters, Eigen::MatrixXd &rhs, double *scale, vector<int> &central_vert_list);\n\nvoid calc_PHS_RBF_interp_single_vert_rhs(double *xyz_interp, vector<double> &vert, PARAMETERS &parameters, Eigen::VectorXd &rhs);\n\nvoid calc_PHS_RBF_grad_laplace_single_vert_grad_y_rhs(vector<double> &vert, PARAMETERS &parameters, Eigen::MatrixXd &rhs, double *scale, vector<int> &central_vert_list);\n\nvoid calc_PHS_RBF_grad_laplace_single_vert_grad_z_rhs(vector<double> &vert, PARAMETERS &parameters, Eigen::MatrixXd &rhs, double *scale, vector<int> &central_vert_list);\n\nvoid calc_PHS_RBF_grad_laplace_single_vert_laplacian_rhs(vector<double> &vert, PARAMETERS &parameters, Eigen::MatrixXd &rhs, double *scale, vector<int> &central_vert_list);\n\ndouble calc_PHS_RBF_grad_laplace_single_vert(vector<double> &vert, PARAMETERS &parameters, Eigen::MatrixXd &laplacian, Eigen::MatrixXd &grad_x, Eigen::MatrixXd &grad_y, Eigen::MatrixXd &grad_z, double *scale, vector<int> &central_vert_list);\n\nvoid calc_cloud_points_slow(vector<vector<int>> &cloud_points, vector<double> &xyz_probe, POINTS &points, PARAMETERS &parameters);\n\nvoid calc_cloud_points_slow_periodic_bc(vector<vector<int>> &cloud_points, vector<double> &xyz_probe, POINTS &points, PARAMETERS &parameters, vector<vector<int>> &periodic_bc_section);\n\nEigen::SparseMatrix<double, Eigen::RowMajor> calc_interp_matrix(vector<double> &xyz_probe, POINTS &points, PARAMETERS &parameters);\n\n#endif", "meta": {"hexsha": "156516c1e57dcac2a94da62096fcae8b4144b705", "size": 2543, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "header_files/coefficient_computations.hpp", "max_stars_repo_name": "shahaneshantanu/memphys", "max_stars_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "header_files/coefficient_computations.hpp", "max_issues_repo_name": "shahaneshantanu/memphys", "max_issues_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "header_files/coefficient_computations.hpp", "max_forks_repo_name": "shahaneshantanu/memphys", "max_forks_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-07T00:32:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:32:37.000Z", "avg_line_length": 47.9811320755, "max_line_length": 241, "alphanum_fraction": 0.8025953598, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6370308082623216, "lm_q1q2_score": 0.5035921678580136}}
{"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_GIVENS_INCLUDE\n#define MTL_MATRIX_GIVENS_INCLUDE\n\n#include <cmath>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/operation/householder.hpp>\n#include <boost/numeric/mtl/operation/rank_one_update.hpp>\n#include <boost/numeric/mtl/operation/trans.hpp>\n\nnamespace mtl { namespace matrix {\n\n/// Given's transformator\n/** Requires Hessenberg form, i.e. for transformations near the diagonal.\n    For general form use qr_givens.\n    \\sa qr_givens. **/\ntemplate <typename Matrix>\nclass givens\n{\n    typedef typename Collection<Matrix>::value_type   value_type;\n    typedef typename Collection<Matrix>::size_type    size_type;\n\n  public:\n    /// Re-set the rotation parameters \\p a and \\p b\n    void set_rotation(value_type a, value_type b)\n    {\n\tusing std::abs;\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 / b;\n\t    s= one / sqrt(one + t*t);\n\t    c= s * t;\n\t} else {\n\t    t= -b / a;\n\t    c= one / sqrt(one + t*t);\n\t    s= c * t;\n\t}\n\tG= c, s,\n\t  -s, c;\n    }\n\n\n    /// Constructor takes %matrix \\p H to be transformed and the rotation parameters \\p a and \\p b\n    givens(Matrix& H, value_type a, value_type b) : H(H), G(2, 2)\n    {\tset_rotation(a, b);    }\n\n    /// Given's transformation of \\p H with \\p G regarding column \\p k\n    Matrix& trafo(const Matrix& G, size_type k)\n    {\n\t    irange r(k,k+2);\n\t    // trans(H[r][ind])*= G; H[ind][r]*= G; // most compact form but does not work yet\n\t    \n\t    Matrix col_block(H[r][iall]), col_perm(trans(G) * col_block);\n\t    H[r][iall]= col_perm; \n\t    Matrix row_perm(H[iall][r] * G);\n\t    H[iall][r]= row_perm;\n\n\t    return H;\n    }\n\n    /// Given's transformation of \\p H regarding column \\p k\n    Matrix& trafo(size_type k)\n    {\n\treturn trafo(G, k);\n    }\n\n  private:\n    Matrix&    H, G;\n    value_type c, s;\n};\n\n}// namespace matrix\n\n\nnamespace vector {\n\n/// Given's transformator on %vector (swap a*line(k) with b*line(k+1) )\ntemplate <typename Vector>\nclass givens\n{\n    typedef typename Collection<Vector>::value_type   value_type;\n    typedef typename Collection<Vector>::size_type    size_type;\n\n  public:\n    /// Constructor takes %vector \\p v to be transformed and the rotation parameters \\p a and \\p b\n    givens(Vector& v, value_type a, value_type b) : v(v), a(a), b(b)\n    {  }\n\n    /// Given's transformation of \\p v with \\p a and \\p b regarding column \\p k\n    Vector& trafo(size_type k)\n    {\n\t    value_type w1(0), w2(0);\n\t    w1= a*v[k] - b*v[k+1]; //given's rotation on solution\n            w2= b*v[k] + a*v[k+1]; //rotation on vector\n            v[k]= w1;\n            v[k+1]= w2;\n\n\t    return v;\n    }\n\n  private:\n    Vector&    v;\n    value_type a, b;\n};\n\n}// namespace vector\n\n\n} // namespace mtl\n\n#endif // MTL_MATRIX_GIVENS_INCLUDE\n", "meta": {"hexsha": "228f541aa99f3024ea6b0797ac1c3ea0f649a4e4", "size": 3438, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/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/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/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": 26.4461538462, "max_line_length": 98, "alphanum_fraction": 0.6375799884, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5035921632505057}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\n#include <array>\n\nnamespace wmtk {\ndouble harmonic_tet_energy(const std::array<double, 12>& T);\nvoid harmonic_tet_jacobian(const std::array<double, 12>& T, Eigen::Vector3d& result_0);\n} // namespace wmtk\n", "meta": {"hexsha": "313c323bd93c8e4dbd41ba086b1cf6626cb0e6bb", "size": 241, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/wmtk/utils/EnergyHarmonicTet.hpp", "max_stars_repo_name": "wildmeshing/wildmeshing-toolkit", "max_stars_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T08:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:19:41.000Z", "max_issues_repo_path": "src/wmtk/utils/EnergyHarmonicTet.hpp", "max_issues_repo_name": "wildmeshing/wildmeshing-toolkit", "max_issues_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 86.0, "max_issues_repo_issues_event_min_datetime": "2021-12-03T01:46:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T19:33:17.000Z", "max_forks_repo_path": "src/wmtk/utils/EnergyHarmonicTet.hpp", "max_forks_repo_name": "wildmeshing/wildmeshing-toolkit", "max_forks_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-26T08:29:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T22:10:42.000Z", "avg_line_length": 21.9090909091, "max_line_length": 87, "alphanum_fraction": 0.7427385892, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5035921632505056}}
{"text": "// ----------------------------------------------------------------------------\n// -                        Open3D: www.open3d.org                            -\n// ----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2018 www.open3d.org\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\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n// ----------------------------------------------------------------------------\n\n#include <algorithm>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <cmath>\n\n#include \"Open3D/Camera/PinholeCameraIntrinsic.h\"\n#include \"Open3D/Geometry/Image.h\"\n\nnamespace open3d {\nnamespace geometry {\n\nstd::shared_ptr<Image> Image::CreateDepthToCameraDistanceMultiplierFloatImage(\n        const camera::PinholeCameraIntrinsic &intrinsic) {\n    auto fimage = std::make_shared<Image>();\n    fimage->Prepare(intrinsic.width_, intrinsic.height_, 1, 4);\n    float ffl_inv[2] = {\n            1.0f / (float)intrinsic.GetFocalLength().first,\n            1.0f / (float)intrinsic.GetFocalLength().second,\n    };\n    float fpp[2] = {\n            (float)intrinsic.GetPrincipalPoint().first,\n            (float)intrinsic.GetPrincipalPoint().second,\n    };\n    std::vector<float> xx(intrinsic.width_);\n    std::vector<float> yy(intrinsic.height_);\n    for (int j = 0; j < intrinsic.width_; j++) {\n        xx[j] = (j - fpp[0]) * ffl_inv[0];\n    }\n    for (int i = 0; i < intrinsic.height_; i++) {\n        yy[i] = (i - fpp[1]) * ffl_inv[1];\n    }\n    for (int i = 0; i < intrinsic.height_; i++) {\n        float *fp =\n                (float *)(fimage->data_.data() + i * fimage->BytesPerLine());\n        for (int j = 0; j < intrinsic.width_; j++, fp++) {\n            *fp = sqrtf(xx[j] * xx[j] + yy[i] * yy[i] + 1.0f);\n        }\n    }\n    return fimage;\n}\n\nstd::shared_ptr<Image> Image::CreateWeightImage(\n        const camera::PinholeCameraIntrinsic &intrinsic) const {\n\n    auto output = std::make_shared<Image>();\n\n\n    output->Prepare(intrinsic.width_, intrinsic.height_, 1, 4);\n    auto focal_length = intrinsic.GetFocalLength();\n    auto principal_point = intrinsic.GetPrincipalPoint();\n\n    #ifdef _OPENMP\n    #ifdef _WIN32\n    #pragma omp parallel for schedule(static)\n    #else\n    #pragma omp parallel for collapse(2) schedule(static)\n    #endif\n    #endif\n    for (int i = 0; i < output->height_; i++) {\n        for (int j = 0; j < output->width_; j++) {\n            float *p = output->PointerAt<float>(j, i);\n            float *ip = PointerAt<float>(j, i);\n            double weight = 0.0;  \n\n            if (*ip > 0) {\n                if(i > 0 && j > 0 && i < output->height_-1 && j < output->width_-1){\n\n                    // computing normalized vertex\n                    double z = (double)(*ip);\n                    double x = (j - principal_point.first) * z / focal_length.first;\n                    double y =\n                            (i - principal_point.second) * z / focal_length.second;\n                    Eigen::Vector3d point = Eigen::Vector3d(x, y, z);\n                    Eigen::Vector3d v_norm = point.normalized();\n\n                    //computing normalized normal\n                    float *dx1 = PointerAt<float>(j+1, i);\n                    float *dx2 = PointerAt<float>(j-1, i);\n\n                    float *dy1 = PointerAt<float>(j, i+1);\n                    float *dy2 = PointerAt<float>(j, i-1);\n\n                    double dzdx = (((double)*dx1 - (double)*dx2)/2.0)*1000.0;\n                    double dzdy = (((double)*dy1 - (double)*dy2)/2.0)*1000.0;\n\n                    Eigen::Vector3d normal = Eigen::Vector3d(-dzdx, -dzdy, 1.0);\n                    Eigen::Vector3d n_norm = normal.normalized();\n\n                    // Eigen::Vector3d captureDir = Eigen::Vector3d(0, 0, 1.0);\n\n                    // double w1 = abs(captureDir.dot(n_norm));\n                    // double w2 = abs(captureDir.dot(v_norm));\n                    \n                    // weight = w1;\n                    // weight = w2;\n                    double w = abs(n_norm.dot(v_norm));\n                    weight = w * w;\n                    \n                    // // Adding gaussian weight centering at principle point\n                    // double w = (double)output->width_/2.0;\n                    // double h = (double)output->height_/2.0;\n                    // double w_x = ((double)j - w)/w ;\n                    // double w_y = ((double)i - h)/h;\n\n                    // double d = sqrt(w_x * w_x + w_y * w_y);  \n                    // weight = exp(-((d*d)/(2.0))); // assuming mu = 0 and sigma = 1.0\n                }\n                else{\n                    weight = 1.0f; // if this weight is set to 0, some of the points are missing in final integrated reconstruction. Therefore assigning it 1.0\n                }\n\n            }\n            *p = (float)weight;\n        }\n    }\n    return output;\n}\n\nstd::shared_ptr<Image> Image::CreateFloatImage(\n        Image::ColorToIntensityConversionType type /* = WEIGHTED*/) const {\n    auto fimage = std::make_shared<Image>();\n    if (IsEmpty()) {\n        return fimage;\n    }\n    fimage->Prepare(width_, height_, 1, 4);\n    for (int i = 0; i < height_ * width_; i++) {\n        float *p = (float *)(fimage->data_.data() + i * 4);\n        const uint8_t *pi =\n                data_.data() + i * num_of_channels_ * bytes_per_channel_;\n        if (num_of_channels_ == 1) {\n            // grayscale image\n            if (bytes_per_channel_ == 1) {\n                *p = (float)(*pi) / 255.0f;\n            } else if (bytes_per_channel_ == 2) {\n                const uint16_t *pi16 = (const uint16_t *)pi;\n                *p = (float)(*pi16);\n            } else if (bytes_per_channel_ == 4) {\n                const float *pf = (const float *)pi;\n                *p = *pf;\n            }\n        } else if (num_of_channels_ == 3) {\n            if (bytes_per_channel_ == 1) {\n                if (type == Image::ColorToIntensityConversionType::Equal) {\n                    *p = ((float)(pi[0]) + (float)(pi[1]) + (float)(pi[2])) /\n                         3.0f / 255.0f;\n                } else if (type ==\n                           Image::ColorToIntensityConversionType::Weighted) {\n                    *p = (0.2990f * (float)(pi[0]) + 0.5870f * (float)(pi[1]) +\n                          0.1140f * (float)(pi[2])) /\n                         255.0f;\n                }\n            } else if (bytes_per_channel_ == 2) {\n                const uint16_t *pi16 = (const uint16_t *)pi;\n                if (type == Image::ColorToIntensityConversionType::Equal) {\n                    *p = ((float)(pi16[0]) + (float)(pi16[1]) +\n                          (float)(pi16[2])) /\n                         3.0f;\n                } else if (type ==\n                           Image::ColorToIntensityConversionType::Weighted) {\n                    *p = (0.2990f * (float)(pi16[0]) +\n                          0.5870f * (float)(pi16[1]) +\n                          0.1140f * (float)(pi16[2]));\n                }\n            } else if (bytes_per_channel_ == 4) {\n                const float *pf = (const float *)pi;\n                if (type == Image::ColorToIntensityConversionType::Equal) {\n                    *p = (pf[0] + pf[1] + pf[2]) / 3.0f;\n                } else if (type ==\n                           Image::ColorToIntensityConversionType::Weighted) {\n                    *p = (0.2990f * pf[0] + 0.5870f * pf[1] + 0.1140f * pf[2]);\n                }\n            }\n        }\n    }\n    return fimage;\n}\n\ntemplate <typename T>\nstd::shared_ptr<Image> Image::CreateImageFromFloatImage() const {\n    auto output = std::make_shared<Image>();\n    if (num_of_channels_ != 1 || bytes_per_channel_ != 4) {\n        utility::LogError(\n                \"[CreateImageFromFloatImage] Unsupported image format.\");\n    }\n\n    output->Prepare(width_, height_, num_of_channels_, sizeof(T));\n    const float *pi = (const float *)data_.data();\n    T *p = (T *)output->data_.data();\n    for (int i = 0; i < height_ * width_; i++, p++, pi++) {\n        if (sizeof(T) == 1) *p = static_cast<T>(*pi * 255.0f);\n        if (sizeof(T) == 2) *p = static_cast<T>(*pi);\n    }\n    return output;\n}\n\ntemplate std::shared_ptr<Image> Image::CreateImageFromFloatImage<uint8_t>()\n        const;\ntemplate std::shared_ptr<Image> Image::CreateImageFromFloatImage<uint16_t>()\n        const;\n\nImagePyramid Image::CreatePyramid(size_t num_of_levels,\n                                  bool with_gaussian_filter /*= true*/) const {\n    std::vector<std::shared_ptr<Image>> pyramid_image;\n    pyramid_image.clear();\n    if ((num_of_channels_ != 1) || (bytes_per_channel_ != 4)) {\n        utility::LogError(\"[CreateImagePyramid] Unsupported image format.\");\n    }\n\n    for (size_t i = 0; i < num_of_levels; i++) {\n        if (i == 0) {\n            std::shared_ptr<Image> input_copy_ptr = std::make_shared<Image>();\n            *input_copy_ptr = *this;\n            pyramid_image.push_back(input_copy_ptr);\n        } else {\n            if (with_gaussian_filter) {\n                // https://en.wikipedia.org/wiki/Pyramid_(image_processing)\n                auto level_b = pyramid_image[i - 1]->Filter(\n                        Image::FilterType::Gaussian3);\n                auto level_bd = level_b->Downsample();\n                pyramid_image.push_back(level_bd);\n            } else {\n                auto level_d = pyramid_image[i - 1]->Downsample();\n                pyramid_image.push_back(level_d);\n            }\n        }\n    }\n    return pyramid_image;\n}\n\n}  // namespace geometry\n}  // namespace open3d\n", "meta": {"hexsha": "fa1e6400bbed440586b4969a7c63865253973a3c", "size": 10555, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Open3D/Geometry/ImageFactory.cpp", "max_stars_repo_name": "bkanchan6/Open3D", "max_stars_repo_head_hexsha": "ec2f37dbc9942c66e9e04129056b4ccdf40f8d8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Open3D/Geometry/ImageFactory.cpp", "max_issues_repo_name": "bkanchan6/Open3D", "max_issues_repo_head_hexsha": "ec2f37dbc9942c66e9e04129056b4ccdf40f8d8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Open3D/Geometry/ImageFactory.cpp", "max_forks_repo_name": "bkanchan6/Open3D", "max_forks_repo_head_hexsha": "ec2f37dbc9942c66e9e04129056b4ccdf40f8d8c", "max_forks_repo_licenses": ["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.7528957529, "max_line_length": 159, "alphanum_fraction": 0.5185220275, "num_tokens": 2629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5035921569629734}}
{"text": "#include <iostream>\n#include <array>\n#include <mtao/algebra/horner_evaluation.hpp>\n#include \"mtao/geometry/grid/grid_utils.h\"\n#include <Eigen/Dense>\n#include <iterator>\n\n\n\nint main() {\n    std::array<int,3> coeffs{{1,1,0}};\n    for(int i = 0; i < 10; ++i) {\n        std::cout << mtao::algebra::horner_evaluate(i,coeffs) << std::endl;\n    }\n    {\n        std::array<int,2> coeffs{{3,4}};\n        for(int i = 0; i < coeffs[0]; ++i) {\n            for(int j = 0; j < coeffs[1]; ++j) {\n                std::cout << mtao::algebra::horner_rowminor_index(std::array<int,2>{{i,j}},coeffs) << \" \";\n            }\n            std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl << std::endl;\n    {\n        std::array<int,2> coeffs{{3,4}};\n        for(int i = 0; i < coeffs[0]; ++i) {\n            for(int j = 0; j < coeffs[1]; ++j) {\n                std::cout << mtao::algebra::horner_rowmajor_index(std::array<int,2>{{i,j}},coeffs) << \" \";\n            }\n            std::cout << std::endl;\n        }\n    }\n    {\n        std::array<int,3> coeffs{{3,4,5}};\n        for(int i = 0; i < coeffs[0]; ++i) {\n            for(int j = 0; j < coeffs[1]; ++j) {\n                for(int k = 0; k < coeffs[2]; ++k) {\n                    std::cout << mtao::algebra::horner_rowminor_index(std::array<int,3>{{i,j,k}},coeffs) << \" \";\n                }\n                std::cout << std::endl;\n            }\n            std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl << std::endl;\n    {\n        std::array<int,3> coeffs{{3,4,5}};\n        for(int i = 0; i < coeffs[0]; ++i) {\n            for(int j = 0; j < coeffs[1]; ++j) {\n                for(int k = 0; k < coeffs[2]; ++k) {\n                    std::cout << mtao::algebra::horner_rowmajor_index(std::array<int,3>{{i,j,k}},coeffs) << \" \";\n                }\n                std::cout << std::endl;\n            }\n            std::cout << std::endl;\n        }\n    }\n\n    {\n        Eigen::Matrix<int,3,4,Eigen::ColMajor> A;\n        for(int i = 0; i < A.rows(); ++i) {\n            for(int j = 0; j < A.cols(); ++j) {\n                A(i,j) = &A(i,j) - A.data();\n\n            }\n        }\n        std::array<int,2> coeffs{{3,4}};\n        for(int i = 0; i < coeffs[0]; ++i) {\n            for(int j = 0; j < coeffs[1]; ++j) {\n                std::cout << mtao::algebra::horner_rowminor_index(std::array<int,2>{{i,j}},coeffs) << \":\" << A(i,j) << \" \";\n            }\n            std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl << std::endl;\n    {\n        Eigen::Matrix<int,3,4,Eigen::RowMajor> A;\n        for(int i = 0; i < A.rows(); ++i) {\n            for(int j = 0; j < A.cols(); ++j) {\n                A(i,j) = &A(i,j) - A.data();\n\n            }\n        }\n        std::array<int,2> coeffs{{3,4}};\n        for(int i = 0; i < coeffs[0]; ++i) {\n            for(int j = 0; j < coeffs[1]; ++j) {\n                std::cout << mtao::algebra::horner_rowmajor_index(std::array<int,2>{{i,j}},coeffs)  << \":\" << A(i,j) << \" \";\n            }\n            std::cout << std::endl;\n        }\n    }\n\n\n    auto arrstr = [](auto&& idx) {\n        using ArrType = mtao::types::remove_cvref_t<decltype(idx)>;\n        using VT = typename ArrType::value_type;\n        std::stringstream ss;\n        \n        std::copy(idx.begin(),idx.end(),std::ostream_iterator<VT>(ss,\",\"));\n        return ss.str();\n\n    };\n\n    using namespace mtao::algebra;\n    auto test_inversing = [&](auto&& coeffs) {\n        std::cout << \"Minor\" << coeffs.size() << std::endl;\n        mtao::geometry::grid::utils::multi_loop(coeffs,[&](auto&& ij) {\n                int idx = horner_rowminor_index(ij,coeffs);\n                auto arr = horner_rowminor_inverse_index(idx,coeffs);\n                std::cout << arrstr(ij) << \" => \" << idx << \" => \" << arrstr(arr) << std::endl;\n                assert(ij == arr);\n                });\n        std::cout << std::endl;\n        std::cout << \"Major\" << coeffs.size() << std::endl;\n        mtao::geometry::grid::utils::multi_loop(coeffs,[&](auto&& ij) {\n                int idx = horner_rowmajor_index(ij,coeffs);\n                auto arr = horner_rowmajor_inverse_index(idx,coeffs);\n                std::cout << arrstr(ij) << \" => \" << idx << \" => \" << arrstr(arr) << std::endl;\n                assert(ij == arr);\n                });\n    };\n    test_inversing(std::array<int,2>{{3,4}});\n    std::cout << std::endl;\n    std::cout << std::endl;\n    test_inversing(std::array<int,3>{{3,4,5}});\n    std::cout << std::endl;\n    std::cout << std::endl;\n    test_inversing(std::array<int,4>{{3,4,5,7}});\n\n\n\n\n}\n", "meta": {"hexsha": "31dafa94bb5e8c155e6811ae823325291a2d65d5", "size": 4557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/horner_evaluation_test.cpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/horner_evaluation_test.cpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "tests/horner_evaluation_test.cpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7555555556, "max_line_length": 124, "alphanum_fraction": 0.4450296248, "num_tokens": 1381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5035921515154532}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_CORRECT_FMA_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_CORRECT_FMA_HPP_INCLUDED\n#include <boost/simd/arithmetic/functions/correct_fma.hpp>\n#include <boost/simd/include/functions/simd/two_prod.hpp>\n#include <boost/simd/include/functions/simd/two_add.hpp>\n#include <boost/simd/include/functions/simd/plus.hpp>\n#include <boost/simd/include/functions/simd/multiplies.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::correct_fma_, tag::cpu_\n                                   , (A0)\n                                   , (generic_< integer_<A0> >)\n                                     (generic_< integer_<A0> >)\n                                     (generic_< integer_<A0> >)\n                                   )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(3)\n    {\n      return a0*a1+a2;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::correct_fma_, tag::cpu_\n                                   , (A0)\n                                   , (generic_< floating_<A0> >)\n                                     (generic_< floating_<A0> >)\n                                     (generic_< floating_<A0> >)\n                                   )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(3)\n    {\n      result_type p, rp, s, rs;\n      two_prod(a0, a1, p, rp);\n      two_add(p, a2, s, rs);\n      return s+(rp+rs);\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "26122f242c50c1d00bbeb021b6938ee1f25454b9", "size": 2023, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/generic/correct_fma.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/generic/correct_fma.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/generic/correct_fma.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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": 37.462962963, "max_line_length": 80, "alphanum_fraction": 0.5130993574, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5035921515154532}}
{"text": "#include <iostream>\n//#include <unordered_map>\n#include <vector>\n#include <algorithm>\n\n// Check for alternative Multiprecision Implementation from boost\n#if defined(CPP_INT)\n    // alternative cpp_int (~4x slower than GMP)\n    // no external linking required\n    // use compile command with \"-DCPP_INT\"\n    #include <boost/multiprecision/cpp_int.hpp>\n    using boost_mp_int = boost::multiprecision::cpp_int;\n#elif defined(TOM_INT)\n    // alternative libtommath (~50x slower than GMP)\n    // use compile command with \"-DTOM_INT -ltommath\"\n    #include <boost/multiprecision/tommath.hpp>\n    using boost_mp_int = boost::multiprecision::tom_int;\n#else\n    // Default GMP (fastest)\n    // use compile command with \"-lgmp\"\n    #include <boost/multiprecision/gmp.hpp>\n    using boost_mp_int = boost::multiprecision::mpz_int;\n#endif\n\n#include <limits>\n#include <cstdlib>\n#include <cassert>\nusing namespace std;\nusing namespace boost::multiprecision;\n\n// Efficient Multiplicative Persistence checker by Hans Loeblich\n// This represents large numbers as a collection of digit counts\n// for [0:9]\n// Multiplying digits is done by taking each digit to the power of its\n// given count, and multiplying the resulting powers together.\n//\n// Powers are calculated and cached up to the max specified lengths\n// before doing any checks.  This makes each persistence check\n// boil down to some fast lookups of powers, and then a few\n// multiplications depending on which digits are present.\n//\n// Inspired by the NumberPhile video about 277777788888899\n// https://www.youtube.com/watch?v=Wim9WJeDTHQ\n\nclass digit_bag {\npublic:\n    typedef array<vector<boost_mp_int>, 10> pow_cache_t;\n    typedef vector<size_t> rule_prefix_t; // the prefix for a rule\n    typedef vector<size_t> rule_tail_digits_t; // list of possible digits for tail\n    typedef pair<rule_prefix_t,rule_tail_digits_t> rule_t;\n    typedef vector<rule_t> rules_t;\n    typedef array<size_t, 10> digits_t;\n\n    digit_bag(size_t length) : size(length), rule_it(rules.begin()), digits(), result_str(length+1,'\\0') {\n        init_rule(*rule_it);\n    }\n    digit_bag(digit_bag&&) = delete;\n    digit_bag& operator=(digit_bag&&) = delete;\t\n    digit_bag(const digit_bag&) = delete;\n    digit_bag& operator=(const digit_bag&) = delete;\n\n    // use a fast lookup table for powers of each digit up to max length\n    // ignore 0 and 1\n    static void init_cache(size_t max) {\n        boost_mp_int power;\n        for(size_t i = 2; i < 10; ++i) {\n            boost_mp_int base = i;\n            for(size_t p = 0; p <= max; ++p) {\n                power = pow(base, p);\n                cache[i].push_back(power);\n            }\n        }\n    }\n\n    // when iterating to a new rule,\n    // initialize digits based on lowest number in the rule\n    inline void init_rule(const rule_t& rule) {\n        // reset digit counts\n        for(auto &d : digits) d = 0;\n        // initialize head\n        for(const size_t di : rule.first) digits[di]++;\n        // set remaining digits to first option in tail_digits\n        digits[rule.second[0]] += size - rule.first.size();\n    }\n\n    // check every combination of given length\n    // starting from digits already in bag\n    pair<digits_t, size_t> check_all() {\n        digits_t current_max;\n        size_t current_max_count = 0;\n        do {\n            size_t count = persistence();\n            if (count > current_max_count) {\n                current_max_count = count;\n                current_max = digits;\n            }\n        } while(next());\n        return make_pair(current_max,current_max_count);\n    }\n\n    // check persitence of current digits\n    // assumes input is already length > 1\n    size_t persistence() const {\n        result = 1;\n        for (size_t i=2; i<10; ++i) {\n            if (digits[i]) {\n                result *= cache[i][digits[i]];\n            }\n        }\n        size_t mult_count = 1;\n\n        while (true) {\n            digits_t new_digits{0,0,0,0,0,0,0,0,0,0};\n            constexpr const size_t CH_ZERO = '0';\n            // convert result to string and count digits of each type\n        #if !defined(CPP_INT) && !defined(TOM_INT)\n            // Minor optimization (~2%) for GMP string conversion\n            mpz_get_str(&result_str[0], 10, result.backend().data());\n            if (result_str[1] == '\\0') { // single digit result\n                return mult_count;\n            }\n            for(size_t ch : result_str) {\n                if (ch == '\\0') break;\n                size_t di = ch - CH_ZERO; // turn character into numeric digit\n                if (di == 0) {\n                    return mult_count+1;\n                }\n                ++new_digits[di];\n            }\n        #else\n            // Generic std::string check\n            result_str = result.str();\n            if (result_str.size() == 1) { // single digit result\n                return mult_count;\n            }\n            for(size_t ch : result_str) {\n                size_t di = ch-'0'; // turn character into numeric digit\n                if (di == 0) {\n                    return mult_count+1;\n                }\n                ++new_digits[di];\n            }\n        #endif\n            // we can't check this inside the loop in case there is a zero also,\n            // we would return 1 higher than expected\n            if (new_digits[5] && (new_digits[2] || new_digits[4] || new_digits[6] || new_digits[8])) {\n                return mult_count+2;\n            }\n\n            result = 1;\n            for (size_t i=2; i<10; ++i) {\n                if (new_digits[i]) {\n                    result *= cache[i][new_digits[i]];\n                }\n            }\n            ++mult_count;\n        }\n    }\n\n    // get the next set of digits, in ascending order based on rules\n    inline bool next() noexcept {\n        const rule_prefix_t &head = rule_it->first;\n        const rule_tail_digits_t &tail_digits = rule_it->second;\n        const size_t last_digit = tail_digits[tail_digits.size()-1];\n        if (digits[last_digit] == size - head.size()) {\n            rule_it++;\n            if (rule_it == rules.end()) return false;\n            init_rule(*rule_it);\n            return true;\n        } else {\n            const size_t tds = tail_digits.size();\n            if (tds >= 2) {\n                for(size_t ti=tds-2; ti>=0; --ti) {\n                    const size_t di = tail_digits[ti];\n                    if (digits[di]) {\n                        const size_t di2 = tail_digits[ti+1];\n                        digits[di]--;\n                        digits[di2]++;\n                        for(size_t ji2=ti+2; ji2<tds; ++ji2) {\n                            const size_t di3 = tail_digits[ji2];\n                            digits[di2] += digits[di3];\n                            digits[di3] = 0;\n                        }\n                        return true;\n                    }\n                }\n                //assert(false && \"where the digits go?\");\n            } else {\n                rule_it++;\n                if (rule_it == rules.end()) return false;\n                init_rule(*rule_it);\n                return true;\n            }\n        }\n    }\n\n    inline const digits_t& getDigits() const {\n        return digits;\n    }\n\nprivate:\n    static const rules_t rules;\n    static pow_cache_t cache;\n\n    size_t size;\n    rules_t::const_iterator rule_it;\n    digits_t digits;\n    mutable string result_str;\n    mutable boost_mp_int result;\n};\n\nostream& operator<<(ostream &out, const digit_bag::digits_t &digits)\n{\n    out << \"{ \" << digits[0];\n    for (size_t i = 1; i<10; ++i) cout << \", \" << digits[i];\n    cout << \" }\";\n    return out;\n}\n\n// https://oeis.org/A003001\n// Summarizing, a term a(n) for n > 2 consists of 7's, 8's and 9's\n// with a prefix of one of the following sets of digits:\n// {{}, {2}, {3}, {4}, {6}, {2,6}, {3,5}, {5, 5,...}}\n// [Amended by Kohei Sakai, May 27 2017]\n\n// Rules are listed to generate numbers in ascending order\nconst digit_bag::rules_t digit_bag::rules{\n    {{2,6},{7,8,9}},\n    {{2},  {7,8,9}},\n    {{3,5},{7,8,9}},\n    {{3},  {7,8,9}},\n    {{4},  {7,8,9}},\n    {{5},  {5,7,9}},\n    {{6},  {7,8,9}},\n    {{ },  {7,8,9}}\n};\ndigit_bag::pow_cache_t digit_bag::cache;\n\n\n\nint main(int argc, char** argv) {\n    if (argc < 3 || argc > 4) {\n        cout << \"Search for the smallest numbers with the highest multiplicative persistence for base10 numbers with lengths in the range of [START:END)\\n\";\n        cout << \"   Or in other words: START < log10(number) < END\\n\";\n        cout << \"usage: multper START END [MAX]\\n\";\n        cout << \"   START   range lower bound(inclusive).  START must be >= 2\\n\";\n        cout << \"   END     range upper bound(exclusive)\\n\";\n        cout << \"   MAX     (optional) sets the maximum persistence to treat specially(default=0 regardless of START length)\\n\";\n        cout << \"     Any number found with persistence greater than MAX will print a line starting with \\\"NEW MAX\\\", with empty lines before/after for visibility.\\n\";\n        cout << \"     Otherwise print a single line for each length indicating the best match (smallest number with highest persistence for that length)\\n\";\n        return 1;\n    }\n\n    const size_t START = stoul(argv[1]);\n    assert(START>=2 && \"\");\n    const size_t END = stoul(argv[2]);\n    size_t max_count = 0;\n    if (argc == 4) {\n        max_count = stoul(argv[3]);\n    }\n\n    //cout << \"Initializing lookup...\"; cout.flush();\n    digit_bag::init_cache(END);\n    //cout << \"Done.\" << endl;\n\n    for(size_t length=START; length<END; ++length) {\n        digit_bag bag(length);\n        pair<digit_bag::digits_t, size_t> current_max = bag.check_all();\n        if (current_max.second > max_count) {\n            max_count = current_max.second;\n            cout << endl << \"NEW MAX \" << max_count << \" persistence for \" << length << \" digits: \" << current_max.first << endl << endl;\n        } else {\n            cout << current_max.second << \" best persistence for \" << length << \" digits: \" << current_max.first << endl;\n        }\n    }\n    return 0;\n}\n", "meta": {"hexsha": "61e66fb664dd095abb5349f56fbeacbb0af50096", "size": 10034, "ext": "cc", "lang": "C++", "max_stars_repo_path": "multiplicative_persistence.cc", "max_stars_repo_name": "thehans/multper", "max_stars_repo_head_hexsha": "a637ee9fb1625a250ed6c1c6ca691dd5586e62f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multiplicative_persistence.cc", "max_issues_repo_name": "thehans/multper", "max_issues_repo_head_hexsha": "a637ee9fb1625a250ed6c1c6ca691dd5586e62f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multiplicative_persistence.cc", "max_forks_repo_name": "thehans/multper", "max_forks_repo_head_hexsha": "a637ee9fb1625a250ed6c1c6ca691dd5586e62f0", "max_forks_repo_licenses": ["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.0935251799, "max_line_length": 167, "alphanum_fraction": 0.5624875424, "num_tokens": 2474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5035921506754409}}
{"text": "#define BOOST_TEST_MODULE SplineTest\n/*\n * ########################################################################\n * The contents of this file is free and unencumbered software released into the\n * public domain. For more information, please refer to <http://unlicense.org/>\n * ########################################################################\n */\n\n#include <okruz/bspline/BSplineGenerator.h>\n#include <okruz/bspline/Core.h>\n#include <okruz/bspline/integration/analytical.h>\n#include <okruz/bspline/integration/numerical.h>\n\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\nusing okruz::bspline::BSplineGenerator;\nusing okruz::bspline::Spline;\n\nusing namespace okruz::bspline::support;\nusing namespace okruz::bspline;\n\ntemplate <typename T>\nSpline<T, 0> getOne(const Grid<T> &grid) {\n  T onet = static_cast<T>(1);\n  Support support(grid, Construction::WHOLE_GRID);\n  std::vector<std::array<T, 1>> coeffs(support.size() - 1, {onet});\n  return Spline<T, 0>(std::move(support), std::move(coeffs));\n}\n\ntemplate <typename T, size_t order>\nvoid testIntegration(T tol) {\n  using namespace okruz::bspline::integration;\n\n  using Spline = okruz::bspline::Spline<T, order>;\n  using Spline0 = okruz::bspline::Spline<T, 0>;\n  const BSplineGenerator generator(std::vector<T>{\n      -7.0l,  -6.85l, -6.55l, -6.3l, -6.0l, -5.75l, -5.53l, -5.2l,\n      -4.75l, -4.5l,  -3.0l,  -2.5l, -1.5l, -1.0l,  0.0l,   0.5l,\n      1.5l,   2.5l,   3.5l,   4.0l,  4.35l, 4.55l,  4.95l,  5.4l,\n      5.7l,   6.1l,   6.35l,  6.5l,  6.85l, 7.0l});\n\n  const std::vector<Spline> splines =\n      generator.template generateBSplines<order + 1>();\n  const Spline0 one = getOne(generator.getGrid());\n\n  const auto f1 = [](const T & /*x*/) { return static_cast<T>(1); };\n  const auto fx = [](const T &x) { return x; };\n\n  integration::ScalarProduct sp;\n  integration::BilinearForm bfx{operators::X<1>{}};\n  integration::BilinearForm bfx2{operators::X<2>{}};\n  integration::BilinearForm bfx_dx{operators::X<1>{} * operators::Dx<1>{}};\n  integration::BilinearForm bfdx{operators::Dx<1>{}};\n  integration::BilinearForm bfdx2{operators::Dx<2>{}};\n  integration::BilinearForm bfx2_dx2{operators::X<2>{} * operators::Dx<2>{}};\n\n  for (const auto &s1 : splines) {\n    for (const auto &s2 : splines) {\n      auto s2dx2 = s2.dx2();\n      BOOST_CHECK_SMALL(overlap<T>(s1, s2) - integrate<T>(s1 * s2), tol);\n      BOOST_CHECK_SMALL(overlap<T>(s1, s2) - sp.integrate(s1, s2), tol);\n      BOOST_CHECK_SMALL(overlap<T>(s1, s2) - overlap<T>(one, s1 * s2), tol);\n      BOOST_CHECK_SMALL(overlap<T>(s1, s2.timesx()) - integrate_x<T>(s1, s2),\n                        tol);\n      BOOST_CHECK_SMALL(overlap<T>(s1.timesx(), s2) - integrate_x<T>(s1, s2),\n                        tol);\n      BOOST_CHECK_SMALL(bfx.integrate(s1, s2) - integrate_x<T>(s1, s2), tol);\n      BOOST_CHECK_SMALL(\n          overlap<T>(s1, s2.timesx().timesx()) - integrate_x2<T>(s1, s2),\n          static_cast<T>(5) * tol);\n      BOOST_CHECK_SMALL(bfx2.integrate(s1, s2) - integrate_x2<T>(s1, s2),\n                        static_cast<T>(5) * tol);\n      BOOST_CHECK_SMALL(\n          overlap<T>(s1.timesx(), s2.timesx()) - integrate_x2<T>(s1, s2),\n          static_cast<T>(5) * tol);\n      BOOST_CHECK_SMALL(\n          overlap<T>(s1.timesx().timesx(), s2) - integrate_x2<T>(s1, s2),\n          static_cast<T>(5) * tol);\n      BOOST_CHECK_SMALL(overlap<T>(s1, s2.dx()) - integrate_dx<T>(s1, s2), tol);\n      BOOST_CHECK_SMALL(bfdx.integrate(s1, s2) - integrate_dx<T>(s1, s2), tol);\n      BOOST_CHECK_SMALL(\n          overlap<T>(s1.timesx(), s2.dx()) - integrate_x_dx<T>(s1, s2), tol);\n      BOOST_CHECK_SMALL(bfx_dx.integrate(s1, s2) - integrate_x_dx<T>(s1, s2),\n                        static_cast<T>(2) * tol);\n      BOOST_CHECK_SMALL(overlap<T>(s1, s2.dx().dx()) - integrate_dx2<T>(s1, s2),\n                        tol);\n      BOOST_CHECK_SMALL(overlap<T>(s1, s2dx2) - integrate_dx2<T>(s1, s2), tol);\n      BOOST_CHECK_SMALL(bfdx2.integrate(s1, s2) - integrate_dx2<T>(s1, s2),\n                        tol);\n      BOOST_CHECK_SMALL(\n          overlap<T>(s1.timesx(), s2.dx().dx()) - integrate_x_dx2<T>(s1, s2),\n          static_cast<T>(11) * tol);\n      BOOST_CHECK_SMALL(\n          overlap<T>(s1, s2.dx().dx().timesx()) - integrate_x_dx2<T>(s1, s2),\n          static_cast<T>(8) * tol);\n      BOOST_CHECK_SMALL(overlap<T>(s1.timesx().timesx(), s2.dx().dx()) -\n                            integrate_x2_dx2<T>(s1, s2),\n                        static_cast<T>(60) * tol);\n      BOOST_CHECK_SMALL(overlap<T>(s1, s2.dx().dx().timesx().timesx()) -\n                            integrate_x2_dx2<T>(s1, s2),\n                        static_cast<T>(60) * tol);\n      BOOST_CHECK_SMALL(\n          overlap<T>(s1, s2dx2.timesx().timesx()) - integrate_x2_dx2<T>(s1, s2),\n          static_cast<T>(60) * tol);\n      BOOST_CHECK_SMALL(\n          bfx2_dx2.integrate(s1, s2) - integrate_x2_dx2<T>(s1, s2),\n          static_cast<T>(100) * tol);\n      BOOST_CHECK_SMALL(overlap<T>(s1, s2) - integrate<2 * order>(f1, s1, s2),\n                        static_cast<T>(10) * tol);\n      BOOST_CHECK_SMALL(\n          integrate_x<T>(s1, s2) - integrate<2 * order>(fx, s1, s2),\n          static_cast<T>(10) * tol);\n    }\n\n    auto s1_d_order = s1.template dx<order>();\n    BOOST_TEST(!s1_d_order.isZero());\n\n    auto s1_d_orderp1 = s1.template dx<order + 1>();\n    BOOST_CHECK_SMALL(integrate<T>(s1_d_orderp1), tol);\n    BOOST_TEST(s1_d_orderp1.isZero());\n\n    auto s1_d_orderp2 = s1.template dx<order + 2>();\n    BOOST_CHECK_SMALL(integrate<T>(s1_d_orderp2), tol);\n    BOOST_TEST(s1_d_orderp2.isZero());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(TestIntegration) {\n  constexpr double TOL = 1.0e-15;\n  testIntegration<double, 2>(TOL);\n  testIntegration<double, 3>(TOL);\n  testIntegration<double, 4>(TOL);\n  testIntegration<double, 5>(TOL);\n  testIntegration<double, 6>(TOL);\n  testIntegration<double, 7>(TOL);\n  testIntegration<double, 8>(TOL);\n  testIntegration<double, 9>(TOL);\n  testIntegration<double, 10>(TOL);\n\n  if constexpr (sizeof(long double) != sizeof(double)) {\n    constexpr long double TOLL = 1.0e-18l;\n    testIntegration<long double, 2>(TOLL);\n    testIntegration<long double, 3>(TOLL);\n    testIntegration<long double, 4>(TOLL);\n    testIntegration<long double, 5>(TOLL);\n    testIntegration<long double, 6>(TOLL);\n    testIntegration<long double, 7>(TOLL);\n    testIntegration<long double, 8>(TOLL);\n    testIntegration<long double, 9>(TOLL);\n    testIntegration<long double, 10>(TOLL);\n  }\n}\n\ntemplate <typename T, size_t order>\nT lc(T x, const std::vector<T> &coeffs,\n     const std::vector<okruz::bspline::Spline<T, order>> &splines) {\n  T ret = static_cast<T>(0);\n  for (size_t i = 0; i < coeffs.size(); i++) {\n    ret += coeffs.at(i) * splines.at(i)(x);\n  }\n  return ret;\n}\n\ntemplate <typename T, size_t order>\nvoid testArithmetic(T tol) {\n  std::cout.precision(20);\n  static_assert(order >= 2, \"For this test, order must be at least 2\");\n  using Spline = okruz::bspline::Spline<T, order>;\n  using Spline6 = okruz::bspline::Spline<T, 2 * order>;\n  using Spline0 = okruz::bspline::Spline<T, 0>;\n  using Spline1 = okruz::bspline::Spline<T, order - 2>;\n\n  BSplineGenerator<T> generator(std::vector<T>{\n      -7.0l,  -6.85l, -6.55l, -6.3l, -6.0l, -5.75l, -5.53l, -5.2l,\n      -4.75l, -4.5l,  -3.0l,  -2.5l, -1.5l, -1.0l,  0.0l,   0.5l,\n      1.5l,   2.5l,   3.5l,   4.0l,  4.35l, 4.55l,  4.95l,  5.4l,\n      5.7l,   6.1l,   6.35l,  6.5l,  6.85l, 7.0l});\n\n  const std::vector<Spline> splines =\n      generator.template generateBSplines<order + 1>();\n  const Spline0 one = getOne(generator.getGrid());\n\n  const std::vector<T> lcCoeffs{1, 2, 3, 4, 3};\n  const std::vector<Spline> lcSplines{\n      splines[0], splines[1], splines[splines.size() / 2],\n      splines[splines.size() - 2], splines[splines.size() - 1]};\n  Spline slc = okruz::bspline::linearCombination(\n      lcCoeffs.begin(), lcCoeffs.end(), lcSplines.begin(), lcSplines.end());\n\n  for (T x = slc.front(); x <= slc.back(); x += 0.01L) {\n    BOOST_CHECK_SMALL(slc(x) - lc(x, lcCoeffs, lcSplines),\n                      static_cast<T>(10) * tol);\n  }\n\n  for (const auto &s : splines) {\n    Spline s2 = s * static_cast<T>(2);\n    Spline sm = -s;\n    Spline6 sprod = s * s;\n    Spline s22 = s;\n    s22 *= static_cast<T>(2);\n    Spline shalf = s / static_cast<T>(2);\n    Spline shalf2 = s;\n    shalf2 /= static_cast<T>(2);\n    Spline s5half = s2 + shalf;\n    Spline s5half2 = s2;\n    s5half2 += shalf;\n    Spline s3half = s2 - shalf;\n    Spline s3half2 = s2;\n    s3half2 -= shalf;\n    Spline splusone = s + one;\n    Spline1 sdx2 = s.dx().dx();\n    Spline1 sdx22 = s.dx2();\n    Spline sdx0 = s.template dx<0>();\n\n    for (T x = s.front(); x <= s.back(); x += 0.01L) {\n      BOOST_CHECK_SMALL(sm(x) + s(x), tol);\n      BOOST_CHECK_SMALL(s2(x) - static_cast<T>(2) * s(x), tol);\n      BOOST_CHECK_SMALL(s22(x) - static_cast<T>(2) * s(x),\n                        tol);  // Tests *= operator\n      BOOST_CHECK_SMALL(shalf(x) - s(x) / static_cast<T>(2),\n                        tol);  // Tests / operator\n      BOOST_CHECK_SMALL(shalf2(x) - s(x) / static_cast<T>(2),\n                        tol);  // Tests /= operator\n      BOOST_CHECK_SMALL(\n          s5half(x) - static_cast<T>(5) * s(x) / static_cast<T>(2),\n          tol);  // Tests + operator\n      BOOST_CHECK_SMALL(\n          s5half2(x) - static_cast<T>(5) * s(x) / static_cast<T>(2),\n          tol);  // Tests += operator\n      BOOST_CHECK_SMALL(\n          s3half(x) - static_cast<T>(3) * s(x) / static_cast<T>(2),\n          tol);  // Tests - operator\n      BOOST_CHECK_SMALL(\n          s3half2(x) - static_cast<T>(3) * s(x) / static_cast<T>(2),\n          tol);  // Tests -= operator\n      BOOST_CHECK_SMALL(splusone(x) - s(x) - static_cast<T>(1),\n                        tol);                      // Tests + operator\n      BOOST_CHECK_SMALL(sdx2(x) - sdx22(x), tol);  // Tests dx method\n      BOOST_CHECK_SMALL(s(x) - sdx0(x), tol);      // Tests dx method\n    }\n  }\n  BOOST_TEST(static_cast<T>(1) == one(one.front()));\n  BOOST_TEST(static_cast<T>(1) == one(one.back()));\n}\n\nBOOST_AUTO_TEST_CASE(TestArithmetic) {\n  constexpr double TOL = 1.0e-15;\n  testArithmetic<double, 2>(TOL);\n  testArithmetic<double, 3>(TOL);\n  testArithmetic<double, 4>(TOL);\n  testArithmetic<double, 5>(TOL);\n  testArithmetic<double, 6>(TOL);\n  testArithmetic<double, 7>(TOL);\n  testArithmetic<double, 8>(TOL);\n  testArithmetic<double, 9>(TOL);\n  testArithmetic<double, 10>(TOL);\n\n  if constexpr (sizeof(long double) != sizeof(double)) {\n    constexpr long double TOLL = 1.0e-18l;\n    testArithmetic<long double, 2>(TOLL);\n    testArithmetic<long double, 3>(TOLL);\n    testArithmetic<long double, 4>(TOLL);\n    testArithmetic<long double, 5>(TOLL);\n    testArithmetic<long double, 6>(TOLL);\n    testArithmetic<long double, 7>(TOLL);\n    testArithmetic<long double, 8>(TOLL);\n    testArithmetic<long double, 9>(TOLL);\n    testArithmetic<long double, 10>(TOLL);\n  }\n}\n", "meta": {"hexsha": "fe279da68ffe4dfa445788ccc7d5259d28c20699", "size": 10997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/okruz/bspline/spline-test.cpp", "max_stars_repo_name": "okruz/BSplinebasis", "max_stars_repo_head_hexsha": "2dd31b9e48730966d3097035b5bed2f7dbbbe46b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T17:30:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T17:30:17.000Z", "max_issues_repo_path": "tests/okruz/bspline/spline-test.cpp", "max_issues_repo_name": "okruz/BSplinebasis", "max_issues_repo_head_hexsha": "2dd31b9e48730966d3097035b5bed2f7dbbbe46b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-11-15T20:50:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T20:32:44.000Z", "max_forks_repo_path": "tests/okruz/bspline/spline-test.cpp", "max_forks_repo_name": "okruz/BSplinebasis", "max_forks_repo_head_hexsha": "2dd31b9e48730966d3097035b5bed2f7dbbbe46b", "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": 40.4301470588, "max_line_length": 80, "alphanum_fraction": 0.5990724743, "num_tokens": 3598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5035921452279207}}
{"text": "#include \"laplacian_inpainting.h\"\n\n#include <mutex>\n\n#define EIGEN_STACK_ALLOCATION_LIMIT 0\n#include <Eigen/Sparse>\n\n#include <tbb/parallel_for.h>\n#include <tbb/task_group.h>\n\nnamespace possumwood {\nnamespace opencv {\n\nnamespace {\n\nclass Triplets;\n\nclass Row {\n  public:\n\tRow() = default;\n\n\tvoid addValue(int64_t row, int64_t col, double value) {\n\t\tif(value != 0.0)\n\t\t\tm_values[(row << 32) + col] += value;\n\t}\n\n  private:\n\tRow(const Row&) = delete;\n\tRow& operator=(const Row&) = delete;\n\n\tstd::map<int64_t, double> m_values;\n\n\tfriend class Triplets;\n};\n\nclass Triplets {\n  public:\n\tTriplets(int rows, int cols) : m_rowCount(0), m_rows(rows), m_cols(cols) {\n\t}\n\n\tvoid addRow(const Row& r) {\n\t\tfor(auto& v : r.m_values) {\n\t\t\tint32_t row = v.first >> 32;\n\t\t\tint32_t col = v.first & 0xffffffff;\n\n\t\t\tassert(row < m_rows);\n\t\t\tassert(col < m_cols);\n\n\t\t\tm_triplets.push_back(Eigen::Triplet<double>(m_rowCount, row * m_cols + col, v.second));\n\t\t}\n\n\t\t++m_rowCount;\n\t}\n\n\tstd::size_t rows() const {\n\t\treturn m_rowCount;\n\t}\n\n\tconst std::vector<Eigen::Triplet<double>>& triplets() const {\n\t\treturn m_triplets;\n\t}\n\n  private:\n\tstd::vector<Eigen::Triplet<double>> m_triplets;\n\n\tint m_rowCount, m_rows, m_cols;\n\n\tfriend class Row;\n};\n\nstatic const cv::Mat kernel = (cv::Mat_<double>(3, 3) << 0.0, -1.0, 0.0, -1.0, 4.0, -1.0, 0.0, -1.0, 0.0);\n\n// static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<\n// \t-1.0, -1.0, -1.0,\n// \t-1.0,  8.0, -1.0,\n// \t-1.0, -1.0, -1.0\n// );\n\n// static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<\n// \t-1.0, -2.0, -1.0,\n// \t-2.0, 12.0, -2.0,\n// \t-1.0, -2.0, -1.0\n// );\n\n// static const cv::Mat kernel = (cv::Mat_<double>(5,5) <<\n// \t 0.0,  0.0,  1.0,  0.0,  0.0,\n// \t 0.0,  2.0, -8.0,  2.0,  0.0,\n// \t 1.0, -8.0, 20.0, -8.0,  1.0,\n// \t 0.0,  2.0, -8.0,  2.0,  0.0,\n// \t 0.0,  0.0,  1.0,  0.0,  0.0\n// );\n\nfloat buildMatrices(const cv::Mat& image, const cv::Mat& mask, Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b) {\n\tTriplets triplets(image.rows, image.cols);\n\tstd::vector<double> values;\n\n\tstd::size_t validCtr = 0, interpolatedCtr = 0;\n\n\tfor(int y = 0; y < image.rows; ++y)\n\t\tfor(int x = 0; x < image.cols; ++x) {\n\t\t\tRow row;\n\n\t\t\t// masked and/or edge\n\t\t\tif(mask.at<unsigned char>(y, x) > 128) {\n\t\t\t\tvalues.push_back(0.0f);\n\n\t\t\t\t// convolution\n\t\t\t\tfor(int yi = 0; yi < kernel.rows; ++yi)\n\t\t\t\t\tfor(int xi = 0; xi < kernel.cols; ++xi) {\n\t\t\t\t\t\tint ypos = y + yi - kernel.rows / 2;\n\t\t\t\t\t\tint xpos = x + xi - kernel.cols / 2;\n\n\t\t\t\t\t\t// handling of edges - \"clip\" (or \"mirror\", commented out for now)\n\t\t\t\t\t\tif(ypos < 0)\n\t\t\t\t\t\t\t// ypos = -ypos;\n\t\t\t\t\t\t\typos = 0;\n\t\t\t\t\t\tif(ypos >= image.rows)\n\t\t\t\t\t\t\t// ypos = (image.rows-1) - (ypos-image.rows);\n\t\t\t\t\t\t\typos = image.rows - 1;\n\n\t\t\t\t\t\tif(xpos < 0)\n\t\t\t\t\t\t\t// xpos = -xpos;\n\t\t\t\t\t\t\txpos = 0;\n\t\t\t\t\t\tif(xpos >= image.cols)\n\t\t\t\t\t\t\t// xpos = (image.cols-1) - (xpos-image.cols);\n\t\t\t\t\t\t\txpos = image.cols - 1;\n\n\t\t\t\t\t\trow.addValue(ypos, xpos, kernel.at<double>(yi, xi));\n\t\t\t\t\t}\n\n\t\t\t\t++interpolatedCtr;\n\t\t\t}\n\n\t\t\t// non-masked\n\t\t\tif(mask.at<unsigned char>(y, x) <= 128) {\n\t\t\t\tvalues.push_back(image.at<float>(y, x));\n\t\t\t\trow.addValue(y, x, 1);\n\n\t\t\t\t++validCtr;\n\t\t\t}\n\n\t\t\ttriplets.addRow(row);\n\t\t}\n\n\t// initialise the sparse matrix\n\tA = Eigen::SparseMatrix<double>(triplets.rows(), image.rows * image.cols);\n\tA.setFromTriplets(triplets.triplets().begin(), triplets.triplets().end());\n\n\t// and the \"b\" vector\n\tassert(values.size() == triplets.rows());\n\tb = Eigen::VectorXd(values.size());\n\tfor(std::size_t i = 0; i < values.size(); ++i)\n\t\tb[i] = values[i];\n\n\treturn (float)validCtr / ((float)validCtr + (float)interpolatedCtr);\n}\n\ndependency_graph::State solve(const cv::Mat& input, const cv::Mat& mask, std::vector<float>& output) {\n\tassert(input.rows == mask.rows);\n\tassert(input.cols == mask.cols);\n\tassert(input.type() == CV_32FC1);\n\tassert(mask.type() == CV_8UC1);\n\n\toutput = std::vector<float>(input.rows * input.cols, 0.0f);\n\n\tEigen::SparseMatrix<double> A;\n\tEigen::VectorXd b, tmp;\n\n\tdependency_graph::State state;\n\n\tconst float ratio = buildMatrices(input, mask, A, b);\n\n\tif(ratio > 0.003) {\n\t\tconst char* stage = \"solver construction\";\n\n\t\tEigen::SparseLU<Eigen::SparseMatrix<double> /*, Eigen::NaturalOrdering<int>*/> chol(A);\n\n\t\tif(chol.info() == Eigen::Success) {\n\t\t\tstage = \"analyze pattern\";\n\n\t\t\tchol.analyzePattern(A);\n\n\t\t\tif(chol.info() == Eigen::Success) {\n\t\t\t\tstage = \"factorize\";\n\n\t\t\t\tchol.factorize(A);\n\n\t\t\t\tif(chol.info() == Eigen::Success) {\n\t\t\t\t\tstage = \"solve\";\n\n\t\t\t\t\ttmp = chol.solve(b);\n\n\t\t\t\t\tassert(tmp.size() == input.rows * input.cols);\n\t\t\t\t\tfor(int i = 0; i < tmp.size(); ++i) {\n\t\t\t\t\t\tconst int row = i / input.cols;\n\t\t\t\t\t\tconst int col = i % input.cols;\n\t\t\t\t\t\tconst int index = row * mask.cols + col;\n\n\t\t\t\t\t\tassert((std::size_t)index < output.size());\n\t\t\t\t\t\toutput[index] = tmp[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(chol.info() == Eigen::NumericalIssue)\n\t\t\tstate.addWarning(\"Decomposition failed - Eigen::NumericalIssue at stage \" + std::string(stage));\n\t\telse if(chol.info() == Eigen::NoConvergence)\n\t\t\tstate.addWarning(\"Decomposition failed - Eigen::NoConvergence at stage \" + std::string(stage));\n\t\telse if(chol.info() == Eigen::InvalidInput)\n\t\t\tstate.addWarning(\"Decomposition failed - Eigen::InvalidInput at stage \" + std::string(stage));\n\t\telse if(chol.info() != Eigen::Success)\n\t\t\tstate.addWarning(\"Decomposition failed - unknown error at stage \" + std::string(stage));\n\t}\n\n\treturn state;\n}\n\n}  // namespace\n\ndependency_graph::State inpaint(const std::vector<cv::Mat>& inputs,\n                                const std::vector<cv::Mat>& masks,\n                                std::vector<cv::Mat>& result) {\n\tif(inputs.size() != masks.size() || inputs.empty() || masks.empty())\n\t\tthrow std::runtime_error(\"Laplacian inpainting - number of inputs and masks has to match.\");\n\n\tfor(std::size_t i = 0; i < inputs.size(); ++i) {\n\t\tif(inputs[i].depth() != CV_32F)\n\t\t\tthrow std::runtime_error(\"Laplacian inpainting - input image type has to be CV_32F.\");\n\t\tif(masks[i].depth() != CV_8U || masks[i].type() != masks[0].type())\n\t\t\tthrow std::runtime_error(\"Laplacian inpainting - mask image type has to be CV_8UC1 or CV_8UC3.\");\n\t\tif(inputs[i].empty() || masks[i].empty())\n\t\t\tthrow std::runtime_error(\"Laplacian inpainting - empty input image and/or mask.\");\n\t\tif(inputs[i].size != masks[i].size || inputs[i].size != inputs[0].size)\n\t\t\tthrow std::runtime_error(\"Laplacian inpainting - input and mask image size have to match.\");\n\t}\n\n\t// split the inputs and masks per channel\n\tstd::vector<cv::Mat> inputs_1ch, masks_1ch;\n\n\tfor(std::size_t i = 0; i < inputs.size(); ++i) {\n\t\tstd::vector<cv::Mat> i_tmp, m_tmp;\n\n\t\tcv::split(inputs[i], i_tmp);\n\t\tcv::split(masks[i], m_tmp);\n\n\t\twhile(m_tmp.size() < i_tmp.size())\n\t\t\tm_tmp.push_back(m_tmp.back());\n\n\t\tinputs_1ch.insert(inputs_1ch.end(), i_tmp.begin(), i_tmp.end());\n\t\tmasks_1ch.insert(masks_1ch.end(), m_tmp.begin(), m_tmp.end());\n\t}\n\n\tstd::vector<std::vector<float>> x(inputs_1ch.size(), std::vector<float>(inputs[0].rows * inputs[0].cols, 0.0f));\n\n\tdependency_graph::State state;\n\n\ttbb::task_group tasks;\n\tstd::mutex state_mutex;\n\n\tfor(std::size_t channel = 0; channel < inputs_1ch.size(); ++channel) {\n\t\ttasks.run([channel, &inputs_1ch, &masks_1ch, &x, &state, &state_mutex]() {\n\t\t\tconst dependency_graph::State currentState = solve(inputs_1ch[channel], masks_1ch[channel], x[channel]);\n\n\t\t\tstd::lock_guard<std::mutex> guard(state_mutex);\n\t\t\tstate.append(currentState);\n\t\t});\n\t}\n\n\ttasks.wait();\n\n\tresult = std::vector<cv::Mat>();\n\n\tint channel = 0;\n\tfor(auto& in : inputs) {\n\t\tcv::Mat tmp = cv::Mat::zeros(in.rows, in.cols, in.type());\n\n\t\ttbb::parallel_for(0, tmp.rows, [&](int yi) {\n\t\t\tfor(int xi = 0; xi < tmp.cols; ++xi)\n\t\t\t\tfor(int c = 0; c < in.channels(); ++c)\n\t\t\t\t\ttmp.ptr<float>(yi, xi)[c] = x[c + channel][yi * tmp.cols + xi];\n\t\t});\n\n\t\tchannel += in.channels();\n\t\tresult.push_back(tmp);\n\t}\n\n\treturn state;\n}\n\n}  // namespace opencv\n}  // namespace possumwood\n", "meta": {"hexsha": "aeda2395bd49a1a1db933006def3f01bb1cef43a", "size": 7888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plugins/opencv/laplacian_inpainting.cpp", "max_stars_repo_name": "martin-pr/possumwood", "max_stars_repo_head_hexsha": "0ee3e0fe13ef27cf14795a79fb497e4d700bef63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 232.0, "max_stars_repo_stars_event_min_datetime": "2017-10-09T11:45:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T11:14:46.000Z", "max_issues_repo_path": "src/plugins/opencv/laplacian_inpainting.cpp", "max_issues_repo_name": "martin-pr/possumwood", "max_issues_repo_head_hexsha": "0ee3e0fe13ef27cf14795a79fb497e4d700bef63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26.0, "max_issues_repo_issues_event_min_datetime": "2019-01-20T21:38:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T03:57:17.000Z", "max_forks_repo_path": "src/plugins/opencv/laplacian_inpainting.cpp", "max_forks_repo_name": "martin-pr/possumwood", "max_forks_repo_head_hexsha": "0ee3e0fe13ef27cf14795a79fb497e4d700bef63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 33.0, "max_forks_repo_forks_event_min_datetime": "2017-10-26T19:20:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T11:21:43.000Z", "avg_line_length": 26.9215017065, "max_line_length": 116, "alphanum_fraction": 0.6130831643, "num_tokens": 2539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5035921397804006}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \r\n//\r\n// This file is part of the Boost Graph Library\r\n//\r\n// You should have received a copy of the License Agreement for the\r\n// Boost Graph Library along with the software; see the file LICENSE.\r\n// If not, contact Office of Research, Indiana University,\r\n// Bloomington, IN 47405.\r\n//\r\n// Permission to modify the code and to distribute the code is\r\n// granted, provided the text of this NOTICE is retained, a notice if\r\n// the code was modified is included with the above COPYRIGHT NOTICE\r\n// and with the COPYRIGHT NOTICE in the LICENSE file, and that the\r\n// LICENSE file is distributed with the modified code.\r\n//\r\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\r\n// By way of example, but not limitation, Licensor MAKES NO\r\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\r\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\r\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\r\n// OR OTHER RIGHTS.\r\n//=======================================================================\r\n#include <boost/config.hpp>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/graph/graphviz.hpp>\r\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\r\n\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  GraphvizGraph g_dot;\r\n  read_graphviz(\"figs/telephone-network.dot\", g_dot);\r\n\r\n  typedef adjacency_list < vecS, vecS, undirectedS, no_property,\r\n    property < edge_weight_t, int > > Graph;\r\n  Graph g(num_vertices(g_dot));\r\n  property_map < GraphvizGraph, edge_attribute_t >::type\r\n    edge_attr_map = get(edge_attribute, g_dot);\r\n  graph_traits < GraphvizGraph >::edge_iterator ei, ei_end;\r\n  for (tie(ei, ei_end) = edges(g_dot); ei != ei_end; ++ei) {\r\n    int weight = lexical_cast < int >(edge_attr_map[*ei][\"label\"]);\r\n    property < edge_weight_t, int >edge_property(weight);\r\n    add_edge(source(*ei, g_dot), target(*ei, g_dot), edge_property, g);\r\n  }\r\n\r\n  std::vector < graph_traits < Graph >::edge_descriptor > mst;\r\n  kruskal_minimum_spanning_tree(g, std::back_inserter(mst));\r\n\r\n  property_map < Graph, edge_weight_t >::type weight = get(edge_weight, g);\r\n  int total_weight = 0;\r\n  for (int e = 0; e < mst.size(); ++e)\r\n    total_weight += get(weight, mst[e]);\r\n  std::cout << \"total weight: \" << total_weight << std::endl;\r\n\r\n  typedef graph_traits < Graph >::vertex_descriptor Vertex;\r\n  for (int i = 0; i < mst.size(); ++i) {\r\n    Vertex u = source(mst[i], g), v = target(mst[i], g);\r\n    edge_attr_map[edge(u, v, g_dot).first][\"color\"] = \"black\";\r\n  }\r\n  std::ofstream out(\"figs/telephone-mst-kruskal.dot\");\r\n  graph_property < GraphvizGraph, graph_edge_attribute_t >::type &\r\n    graph_edge_attr_map = get_property(g_dot, graph_edge_attribute);\r\n  graph_edge_attr_map[\"color\"] = \"gray\";\r\n  graph_edge_attr_map[\"style\"] = \"bold\";\r\n  write_graphviz(out, g_dot);\r\n\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "6ce337bbf59b165af1e58b426bd61219489fd5d1", "size": 3065, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/graph/example/kruskal-telephone.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/graph/example/kruskal-telephone.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/libs/graph/example/kruskal-telephone.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9863013699, "max_line_length": 76, "alphanum_fraction": 0.6704730832, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5035688988142939}}
{"text": "/**\n * @file fixed_point.cpp\n * @author Salvatore Cardamone\n * @brief Unit test for FixedPoint class.\n */\n#define BOOST_TEST_MODULE FixedPointTest\n#include <random>\n#include <boost/test/included/unit_test.hpp>\n#include \"utilities/fixed_point.hpp\"\n\n/**\n * This case tests construction using all datatypes used for storage of the\n * fixed point representation, and simultaneously minimum and maximum values for\n * the associated representation.\n */\nBOOST_AUTO_TEST_CASE( constructors ) {\n\n  // Q4.4 representation, unsigned\n  tycheplusplus::FixedPoint<unsigned char,4> us_char(15.0);\n  BOOST_CHECK_EQUAL(us_char.AsDouble(), 15.0);\n  // Q3.4 representation, signed\n  tycheplusplus::FixedPoint<signed char,4> char_pos( 7.0);\n  tycheplusplus::FixedPoint<signed char,4> char_neg(-7.0);\n  BOOST_CHECK_EQUAL(char_pos.AsDouble(),  7.0);\n  BOOST_CHECK_EQUAL(char_neg.AsDouble(), -7.0);\n\n  // Q8.8 representation, unsigned\n  tycheplusplus::FixedPoint<unsigned short,8> us_short(255.0);\n  BOOST_CHECK_EQUAL(us_short.AsDouble(), 255.0);\n  // Q7.8 representation, signed\n  tycheplusplus::FixedPoint<signed short,8> short_pos( 127.0);\n  tycheplusplus::FixedPoint<signed short,8> short_neg(-127.0);\n  BOOST_CHECK_EQUAL(short_pos.AsDouble(),  127.0);\n  BOOST_CHECK_EQUAL(short_neg.AsDouble(), -127.0);\n\n  // Q16.16 representation, unsigned\n  tycheplusplus::FixedPoint<unsigned int,16> us_int(65535.0);\n  BOOST_CHECK_EQUAL(us_int.AsDouble(), 65535.0);\n  // Q15.16 representation, signed\n  tycheplusplus::FixedPoint<signed int,16> int_pos( 32767.0);\n  tycheplusplus::FixedPoint<signed int,16> int_neg(-32767.0);\n  BOOST_CHECK_EQUAL(int_pos.AsDouble(),  32767.0);\n  BOOST_CHECK_EQUAL(int_neg.AsDouble(), -32767.0);\n\n  // Q32.32 representation, unsigned\n  tycheplusplus::FixedPoint<unsigned long int,32> us_long(4294967296.0);\n  BOOST_CHECK_EQUAL(us_long.AsDouble(), 4294967296.0);\n  // Q31.32 representation, signed\n  tycheplusplus::FixedPoint<signed long int,32> long_pos( 2147483647.0);\n  tycheplusplus::FixedPoint<signed long int,32> long_neg(-2147483647.0);\n  BOOST_CHECK_EQUAL(long_pos.AsDouble(),  2147483647.0);\n  BOOST_CHECK_EQUAL(long_neg.AsDouble(), -2147483647.0);\n\n}\n\nBOOST_AUTO_TEST_CASE( addition ) {\n\n  tycheplusplus::FixedPoint<unsigned char,4> a(5.0), b(6.0);\n  auto c = a + b;\n  BOOST_CHECK_EQUAL(c.AsDouble(), 11.0);\n\n}\n\n/**\n * Test the exponential functionality, both signed and unsigned with positive\n * and negative arguments.\n */\nBOOST_AUTO_TEST_CASE( exponential ) {\n\n  constexpr int n_samples = 2048;\n\n  // We'll use the Mersenne Twister for our PRNG\n  std::random_device rd;\n  std::mt19937 gen(rd());\n\n  std::uniform_real_distribution<double> us_char_dist(0.0, 1.0);\n  for (auto i = 0; i < n_samples; ++i) {\n    auto val = us_char_dist(gen);\n    tycheplusplus::FixedPoint<unsigned char,4,4> arg(val);\n    auto exp_result = exp(arg);\n    auto diff = fabs(exp_result.AsDouble() - exp(val));\n    BOOST_CHECK_SMALL(diff, 1.0);\n  }\n\n  std::uniform_real_distribution<double> us_short_dist(0.0, 2.0);\n  for (auto i = 0; i < n_samples; ++i) {\n    auto val = us_short_dist(gen);\n    tycheplusplus::FixedPoint<unsigned short,8,8> arg(val);\n    auto exp_result = exp(arg);\n    auto diff = fabs(exp_result.AsDouble() - exp(val));\n    BOOST_CHECK_SMALL(diff, 0.2);\n  }\n\n  std::uniform_real_distribution<double> us_int_dist(0.0, 3.0);\n  for (auto i = 0; i < n_samples; ++i) {\n    auto val = us_int_dist(gen);\n    tycheplusplus::FixedPoint<unsigned int,16,16> arg(val);\n    auto exp_result = exp(arg);\n    auto diff = fabs(exp_result.AsDouble() - exp(val));\n    BOOST_CHECK_SMALL(diff, 0.01);\n  }\n\n  std::uniform_real_distribution<double> us_long_dist(0.0, 4.0);\n  for (auto i = 0; i < n_samples; ++i) {\n    auto val = us_long_dist(gen);\n    tycheplusplus::FixedPoint<unsigned long,32,32> arg(val);\n    auto exp_result = exp(arg);\n    auto diff = fabs(exp_result.AsDouble() - exp(val));\n    BOOST_CHECK_SMALL(diff, 0.0000001);\n  }\n\n}\n", "meta": {"hexsha": "9c4fdfc79c2be44029e54893054df88d219ad831", "size": 3925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fixed_point.cpp", "max_stars_repo_name": "savcardamone/tyche-", "max_stars_repo_head_hexsha": "ea89edea89a607291e4fe0ba738d75522f54dc1a", "max_stars_repo_licenses": ["MIT"], "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/fixed_point.cpp", "max_issues_repo_name": "savcardamone/tyche-", "max_issues_repo_head_hexsha": "ea89edea89a607291e4fe0ba738d75522f54dc1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-28T13:30:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-29T10:30:33.000Z", "max_forks_repo_path": "test/fixed_point.cpp", "max_forks_repo_name": "savcardamone/tyche", "max_forks_repo_head_hexsha": "ea89edea89a607291e4fe0ba738d75522f54dc1a", "max_forks_repo_licenses": ["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.7345132743, "max_line_length": 80, "alphanum_fraction": 0.716433121, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5035688926553462}}
{"text": "//  Copyright (c) 2018 Cem Bassoy\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Fraunhofer and Google in producing this work\n//  which started as a Google Summer of Code project.\n//\n\n\n\n#include <boost/numeric/ublas/tensor/operators_comparison.hpp>\n#include <boost/numeric/ublas/tensor/operators_arithmetic.hpp>\n#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include \"utility.hpp\"\n\n\nBOOST_AUTO_TEST_SUITE(test_tensor_comparison/*, * boost::unit_test::depends_on(\"test_tensor\")*/)\n\nusing double_extended = boost::multiprecision::cpp_bin_float_double_extended;\n\nusing test_types = zip<int,float,double_extended>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\nstruct fixture {\n  using extents_type = boost::numeric::ublas::extents<>;\n  fixture()\n    : extents{\n        //                extents_type{},    // 0\n        extents_type{1,1}, // 1\n        extents_type{1,2}, // 2\n        extents_type{2,1}, // 3\n        extents_type{2,3}, // 4\n        extents_type{2,3,1}, // 5\n        extents_type{4,1,3}, // 6\n        extents_type{1,2,3}, // 7\n        extents_type{4,2,3}, // 8\n        extents_type{4,2,3,5}} // 9\n  {\n  }\n  std::vector<extents_type> extents;\n};\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_comparison, value,  test_types, fixture)\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_type  = typename value::first_type;\n  using layout_type = typename value::second_type;\n  using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n\n  auto check = [](auto const& e)\n  {\n    auto t  = tensor_type (e);\n    auto t2 = tensor_type (e);\n    auto v  = value_type  {};\n\n    std::iota(t.begin(), t.end(), v);\n    std::iota(t2.begin(), t2.end(), v+2);\n\n    BOOST_CHECK( t == t  );\n    BOOST_CHECK( t != t2 );\n\n    if(t.empty())\n      return;\n\n    BOOST_CHECK(!(t < t));\n    BOOST_CHECK(!(t > t));\n    BOOST_CHECK( t < t2 );\n    BOOST_CHECK( t2 > t );\n    BOOST_CHECK( t <= t );\n    BOOST_CHECK( t >= t );\n    BOOST_CHECK( t <= t2 );\n    BOOST_CHECK( t2 >= t );\n    BOOST_CHECK( t2 >= t2 );\n    BOOST_CHECK( t2 >= t );\n  };\n\n  for(auto const& e : extents)\n    check(e);\n\n  auto e0 = extents.at(0);\n  auto e1 = extents.at(1);\n  auto e2 = extents.at(2);\n\n\n  auto b = false;\n  BOOST_CHECK_NO_THROW ( b = (tensor_type(e0) == tensor_type(e0)));\n  BOOST_CHECK_NO_THROW ( b = (tensor_type(e1) == tensor_type(e2)));\n  BOOST_CHECK_NO_THROW ( b = (tensor_type(e0) == tensor_type(e2)));\n  BOOST_CHECK_NO_THROW ( b = (tensor_type(e1) != tensor_type(e2)));\n\n  BOOST_CHECK_THROW    ( b = (tensor_type(e1) >= tensor_type(e2)), std::runtime_error  );\n  BOOST_CHECK_THROW    ( b = (tensor_type(e1) <= tensor_type(e2)), std::runtime_error  );\n  BOOST_CHECK_THROW    ( b = (tensor_type(e1) <  tensor_type(e2)), std::runtime_error  );\n  BOOST_CHECK_THROW    ( b = (tensor_type(e1) >  tensor_type(e2)), std::runtime_error  );\n\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_comparison_with_tensor_expressions, value,  test_types, fixture)\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_type  = typename value::first_type;\n  using layout_type = typename value::second_type;\n  using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n\n  auto check = [](auto const& e)\n  {\n    auto t  = tensor_type (e);\n    auto t2 = tensor_type (e);\n    auto v  = value_type  {};\n\n    std::iota(t.begin(), t.end(), v);\n    std::iota(t2.begin(), t2.end(), v+2);\n\n    BOOST_CHECK( t == t  );\n    BOOST_CHECK( t != t2 );\n\n    if(t.empty())\n      return;\n\n    BOOST_CHECK( !(t < t) );\n    BOOST_CHECK( !(t > t) );\n    BOOST_CHECK( t < (t2+t) );\n    BOOST_CHECK( (t2+t) > t );\n    BOOST_CHECK( t <= (t+t) );\n    BOOST_CHECK( (t+t2) >= t );\n    BOOST_CHECK( (t2+t2+2) >= t);\n    BOOST_CHECK( 2*t2 > t );\n    BOOST_CHECK( t < 2*t2 );\n    BOOST_CHECK( 2*t2 > t);\n    BOOST_CHECK( 2*t2 >= t2 );\n    BOOST_CHECK( t2 <= 2*t2);\n    BOOST_CHECK( 3*t2 >= t );\n\n  };\n\n  for(auto const& e : extents)\n    check(e);\n\n  auto e0 = extents.at(0);\n  auto e1 = extents.at(1);\n  auto e2 = extents.at(2);\n\n  auto b = false;\n  BOOST_CHECK_NO_THROW (b = tensor_type(e0) == (tensor_type(e0) + tensor_type(e0))  );\n  BOOST_CHECK_NO_THROW (b = tensor_type(e1) == (tensor_type(e2) + tensor_type(e2))  );\n  BOOST_CHECK_NO_THROW (b = tensor_type(e0) == (tensor_type(e2) + 2) );\n  BOOST_CHECK_NO_THROW (b = tensor_type(e1) != (2 + tensor_type(e2)) );\n\n  BOOST_CHECK_NO_THROW (b = (tensor_type(e0) + tensor_type(e0)) == tensor_type(e0) );\n  BOOST_CHECK_NO_THROW (b = (tensor_type(e2) + tensor_type(e2)) == tensor_type(e1) );\n  BOOST_CHECK_NO_THROW (b = (tensor_type(e2) + 2)               == tensor_type(e0) );\n  BOOST_CHECK_NO_THROW (b = (2 + tensor_type(e2))               != tensor_type(e1) );\n\n  BOOST_CHECK_THROW    (b = tensor_type(e1) >= (tensor_type(e2) + tensor_type(e2)), std::runtime_error  );\n  BOOST_CHECK_THROW    (b = tensor_type(e1) <= (tensor_type(e2) + tensor_type(e2)), std::runtime_error  );\n  BOOST_CHECK_THROW    (b = tensor_type(e1) <  (tensor_type(e2) + tensor_type(e2)), std::runtime_error  );\n  BOOST_CHECK_THROW    (b = tensor_type(e1) >  (tensor_type(e2) + tensor_type(e2)), std::runtime_error  );\n\n  BOOST_CHECK_THROW    (b = tensor_type(e1) >= (tensor_type(e2) + 2), std::runtime_error  );\n  BOOST_CHECK_THROW    (b = tensor_type(e1) <= (2 + tensor_type(e2)), std::runtime_error  );\n  BOOST_CHECK_THROW    (b = tensor_type(e1) <  (tensor_type(e2) + 3), std::runtime_error  );\n  BOOST_CHECK_THROW    (b = tensor_type(e1) >  (4 + tensor_type(e2)), std::runtime_error  );\n\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_comparison_with_scalar, value,  test_types, fixture)\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_type  = typename value::first_type;\n  using layout_type = typename value::second_type;\n  using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n\n  auto check = [](auto const& e)\n  {\n\n    BOOST_CHECK( tensor_type(e,value_type{2}) == tensor_type(e,value_type{2})  );\n    BOOST_CHECK( tensor_type(e,value_type{2}) != tensor_type(e,value_type{1})  );\n\n    if(ublas::empty(e))\n      return;\n\n    BOOST_CHECK( !(tensor_type(e,2) <  2) );\n    BOOST_CHECK( !(tensor_type(e,2) >  2) );\n    BOOST_CHECK(  (tensor_type(e,2) >= 2) );\n    BOOST_CHECK(  (tensor_type(e,2) <= 2) );\n    BOOST_CHECK(  (tensor_type(e,2) == 2) );\n    BOOST_CHECK(  (tensor_type(e,2) != 3) );\n\n    BOOST_CHECK( !(2 >  tensor_type(e,2)) );\n    BOOST_CHECK( !(2 <  tensor_type(e,2)) );\n    BOOST_CHECK(  (2 <= tensor_type(e,2)) );\n    BOOST_CHECK(  (2 >= tensor_type(e,2)) );\n    BOOST_CHECK(  (2 == tensor_type(e,2)) );\n    BOOST_CHECK(  (3 != tensor_type(e,2)) );\n\n    BOOST_CHECK( !( tensor_type(e,2)+3 <  5) );\n    BOOST_CHECK( !( tensor_type(e,2)+3 >  5) );\n    BOOST_CHECK(  ( tensor_type(e,2)+3 >= 5) );\n    BOOST_CHECK(  ( tensor_type(e,2)+3 <= 5) );\n    BOOST_CHECK(  ( tensor_type(e,2)+3 == 5) );\n    BOOST_CHECK(  ( tensor_type(e,2)+3 != 6) );\n\n\n    BOOST_CHECK( !( 5 >  tensor_type(e,2)+3) );\n    BOOST_CHECK( !( 5 <  tensor_type(e,2)+3) );\n    BOOST_CHECK(  ( 5 >= tensor_type(e,2)+3) );\n    BOOST_CHECK(  ( 5 <= tensor_type(e,2)+3) );\n    BOOST_CHECK(  ( 5 == tensor_type(e,2)+3) );\n    BOOST_CHECK(  ( 6 != tensor_type(e,2)+3) );\n\n\n    BOOST_CHECK( !( tensor_type(e,2)+tensor_type(e,3) <  5) );\n    BOOST_CHECK( !( tensor_type(e,2)+tensor_type(e,3) >  5) );\n    BOOST_CHECK(  ( tensor_type(e,2)+tensor_type(e,3) >= 5) );\n    BOOST_CHECK(  ( tensor_type(e,2)+tensor_type(e,3) <= 5) );\n    BOOST_CHECK(  ( tensor_type(e,2)+tensor_type(e,3) == 5) );\n    BOOST_CHECK(  ( tensor_type(e,2)+tensor_type(e,3) != 6) );\n\n\n    BOOST_CHECK( !( 5 >  tensor_type(e,2)+tensor_type(e,3)) );\n    BOOST_CHECK( !( 5 <  tensor_type(e,2)+tensor_type(e,3)) );\n    BOOST_CHECK(  ( 5 >= tensor_type(e,2)+tensor_type(e,3)) );\n    BOOST_CHECK(  ( 5 <= tensor_type(e,2)+tensor_type(e,3)) );\n    BOOST_CHECK(  ( 5 == tensor_type(e,2)+tensor_type(e,3)) );\n    BOOST_CHECK(  ( 6 != tensor_type(e,2)+tensor_type(e,3)) );\n\n  };\n\n  for(auto const& e : extents)\n    check(e);\n\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "b6aeb191a5dc3f25d0cf6440db6ce18dd5ddd25b", "size": 8310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_operators_comparison.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_operators_comparison.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_operators_comparison.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 33.6437246964, "max_line_length": 145, "alphanum_fraction": 0.6282791817, "num_tokens": 2587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5035688893880527}}
{"text": "// This file is part of KWIVER, and is distributed under the\n// OSI-approved BSD 3-Clause License. See top-level LICENSE file or\n// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.\n\n/**\n * \\file\n * \\brief Homography and derived class functionality regression tests\n */\n\n#include <test_eigen.h>\n\n#include <vital/exceptions/math.h>\n#include <vital/types/homography.h>\n#include <vital/types/homography_f2f.h>\n\n#include <Eigen/LU>\n\n// ----------------------------------------------------------------------------\nint main(int argc, char** argv)\n{\n  ::testing::InitGoogleTest( &argc, argv );\n  return RUN_ALL_TESTS();\n}\n\n// ----------------------------------------------------------------------------\ntemplate <typename T>\nclass homography : public ::testing::Test\n{\n};\n\nusing types = ::testing::Types<float, double>;\nTYPED_TEST_CASE(homography, types);\n\n// ----------------------------------------------------------------------------\n// Test invert function Eigen::Matrix derived classes\nTYPED_TEST(homography, inversion)\n{\n  using homography_t = typename kwiver::vital::homography_<TypeParam>;\n\n  homography_t invertible;\n  homography_t expected_result;\n  homography_t noninvertable;\n  homography_t ni_result;\n\n  invertible.get_matrix() << 1, 1, 2,\n                             3, 4, 5,\n                             6, 7, 9;\n  expected_result.get_matrix() << -0.5, -2.5,  1.5,\n                                  -1.5,  1.5, -0.5,\n                                   1.5,  0.5, -0.5;\n\n  homography_t h_inverse( *invertible.inverse() );\n  EXPECT_MATRIX_EQ( expected_result.matrix(), h_inverse.matrix() );\n\n  noninvertable.get_matrix() << 1, 2, 3,\n                                4, 5, 6,\n                                7, 8, 9;\n  bool is_invertible;\n  noninvertable.get_matrix().computeInverseWithCheck(\n    ni_result.get_matrix(), is_invertible );\n  EXPECT_FALSE( is_invertible );\n}\n\n// ----------------------------------------------------------------------------\n// Test mapping a point for a homography/point data type\nTYPED_TEST(homography, map_point_zero_div)\n{\n  using homography_t = typename kwiver::vital::homography_<TypeParam>;\n  using vector_t = typename Eigen::Matrix<TypeParam, 2, 1>;\n\n  vector_t test_p{ 1, 1 };\n  TypeParam e = Eigen::NumTraits<TypeParam>::dummy_precision();\n\n  // Where [2,2] = 0\n  homography_t h_0;\n  h_0.get_matrix() << 1.0, 0.0, 1.0,\n                      0.0, 1.0, 1.0,\n                      0.0, 0.0, 0.0;\n  EXPECT_THROW(\n    h_0.map_point( test_p ),\n    kwiver::vital::point_maps_to_infinity )\n    << \"Applying point to matrix with 0-value lower-right corner\";\n\n  // Where [2,2] = e, which is the approximately-zero threshold\n  homography_t h_e;\n  h_e.get_matrix() << 1.0, 0.0, 1.0,\n                      0.0, 1.0, 1.0,\n                      0.0, 0.0,  e ;\n  EXPECT_THROW(\n    h_e.map_point( test_p ),\n    kwiver::vital::point_maps_to_infinity )\n    << \"Applying point to matrix with e-value lower-right corner\";\n\n  // Where [2,2] = 0.5, which should be valid.\n  homography_t h_half;\n  h_half.get_matrix() << 1.0, 0.0, 1.0,\n                         0.0, 1.0, 1.0,\n                         0.0, 0.0, 0.5;\n  EXPECT_MATRIX_NEAR( ( vector_t{ 4, 4 } ), h_half.map_point( test_p ), e );\n}\n\n// ----------------------------------------------------------------------------\nTYPED_TEST(homography, map_point)\n{\n  using homography_t = typename kwiver::vital::homography_<TypeParam>;\n  using vector_t = typename Eigen::Matrix<TypeParam, 2, 1>;\n\n  // Identity transformation\n  homography_t h;\n  vector_t p{ static_cast<TypeParam>( 2.2 ), static_cast<TypeParam>( 5.5 ) };\n  EXPECT_EQ( p, h.map_point( p ) );\n}\n\n// ----------------------------------------------------------------------------\nTEST(f2f_homography, inversion)\n{\n  // Testing from and to frame swapping during inversion\n  kwiver::vital::matrix_3x3d i{ kwiver::vital::matrix_3x3d::Identity() };\n  kwiver::vital::f2f_homography h{ i, 0, 10 };\n  kwiver::vital::f2f_homography h_inv = h.inverse();\n\n  EXPECT_EQ( 10, h_inv.from_id() );\n  EXPECT_EQ( 0, h_inv.to_id() );\n}\n", "meta": {"hexsha": "c8e205bf86a3f5607c355371e40cbabf3bcc7bb6", "size": 4062, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vital/tests/test_homography.cxx", "max_stars_repo_name": "mwoehlke-kitware/kwiver", "max_stars_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 176.0, "max_stars_repo_stars_event_min_datetime": "2015-07-31T23:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T23:42:44.000Z", "max_issues_repo_path": "vital/tests/test_homography.cxx", "max_issues_repo_name": "mwoehlke-kitware/kwiver", "max_issues_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1276.0, "max_issues_repo_issues_event_min_datetime": "2015-05-03T01:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:32:20.000Z", "max_forks_repo_path": "vital/tests/test_homography.cxx", "max_forks_repo_name": "mwoehlke-kitware/kwiver", "max_forks_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2015-01-25T05:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T14:59:37.000Z", "avg_line_length": 32.496, "max_line_length": 79, "alphanum_fraction": 0.5566223535, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5035688799618114}}
{"text": "#ifndef RAYCASTING_HPP_OLVFBMND\n#define RAYCASTING_HPP_OLVFBMND\n\n#include <Eigen/Core>\n\n#include <pcl_util/point_types.hpp>\n\n#include \"scrollgrid/grid_types.hpp\"\n#include \"scrollgrid/box.hpp\"\n#include \"scrollgrid/ray.hpp\"\n#include \"scrollgrid/scrollgrid3.hpp\"\n#include \"scrollgrid/dense_array3.hpp\"\n\nnamespace ca\n{\n\n/**\n * Axis-aligned bounding box intersection test.\n * Reference:\n * An Efficient and Robust Ray\u2013Box Intersection Algorithm, Williams et al. 2004\n */\ntemplate<typename Scalar>\nbool aabb_ray_intersect(const ca::scrollgrid::Box<Scalar, 3>& box,\n                        ca::scrollgrid::Ray3<Scalar> &r) {\n  Scalar tmin = (box.bound(r.sign[0]).x() - r.origin.x()) * r.invdir.x();\n  Scalar tmax = (box.bound(1-r.sign[0]).x() - r.origin.x()) * r.invdir.x();\n\n  Scalar tymin = (box.bound(r.sign[1]).y() - r.origin.y()) * r.invdir.y();\n  Scalar tymax = (box.bound(1-r.sign[1]).y() - r.origin.y()) * r.invdir.y();\n\n  if ((tmin > tymax) || (tymin > tmax)) return false;\n  if (tymin > tmin) tmin = tymin;\n  if (tymax < tmax) tmax = tymax;\n\n  Scalar tzmin = (box.bound(r.sign[2]).z() - r.origin.z()) * r.invdir.z();\n  Scalar tzmax = (box.bound(1-r.sign[2]).z() - r.origin.z()) * r.invdir.z();\n\n  if ((tmin > tzmax) || (tzmin > tmax)) return false;\n  if (tzmin > tmin) tmin = tzmin;\n  if (tzmax < tmax) tmax = tzmax;\n  if (tmin > r.tmin) r.tmin = tmin;\n  if (tmax < r.tmax) r.tmax = tmax;\n  return true;\n}\n\n/**\n * Trace a straight line from start_pos to end_pos.\n * At each step fun(i, j, k) is called.\n *\n * NOTE start_pos and end_pos should be inside the grid\n *\n * Reference: graphics gems article\n * TODO consider DDA-type raytracing.\n */\ntemplate<class TraceFunctor>\nvoid bresenham_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);\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);\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);\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\n/**\n * Simply increment a counter in densearray3 for each step along the way.\n */\ntemplate<class GridScalar, class ArrayScalar>\nvoid bresenham_trace_simple(const Vec3Ix& start_pos,\n                            const Vec3Ix& end_pos,\n                            const ca::ScrollGrid3<GridScalar>& grid3,\n                            ca::DenseArray3<ArrayScalar>& 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    for (int decy=ay-dx, decz=az-dx;\n         ;\n         x+=sx, decy+=ay, decz+=az) {\n      mem_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n      array3[mem_ix] += 1;\n      //array3[mem_ix] = ray_ctr++;\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      mem_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n      array3[mem_ix] += 1;\n      //array3[mem_ix] = ray_ctr++;\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      grid_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n      array3[mem_ix] += 1;\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\n\n}\n#endif /* end of include guard: RAYCASTING_HPP_OLVFBMND */\n", "meta": {"hexsha": "c9ee0cd1a1daab10570dc672dfa7d94363c75abe", "size": 6088, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dependency/scrollgrid/include/scrollgrid/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/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/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": 22.6319702602, "max_line_length": 79, "alphanum_fraction": 0.4806176084, "num_tokens": 2161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925402, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5035334768525763}}
{"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\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\nconst int vertexIdx = 0; // Arbitrary index id\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->u << \" \" << e->v << \" (\" << (*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 << \",\" << 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 = 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\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 IsLocallyDelaunay(CGALPoint* p, CGALPoint* q, CGALPoint* r, CGALPoint* t) {\r\n\tif (SHOW_DEBUG) {\r\n\t\t//std::cout << \"(\" << (*p) << \") (\" << (*q) << \") (\" << (*r) << \") (\" << (*t) << \")\" << std::endl;\r\n\t}\r\n\tCGALCircle c(*p, *q, *r);\r\n\tCGAL::Bounded_side side = c.bounded_side(*t);\r\n\r\n\t// We consider ON_BOUNDARY because if a constraint edge is on the boundary and the DT flip of quadrilateral has the same total angle, i.e. both\r\n\t// flips are DT, then we have to record the constraint so that the CDT picks the right flip in the subgraph check.\r\n\treturn side == CGAL::Bounded_side::ON_UNBOUNDED_SIDE;\r\n\t\r\n\t// v is outside or on the circumcircle of f\r\n\t// return side == CGAL::Bounded_side::ON_UNBOUNDED_SIDE\r\n\t\t//|| side == CGAL::Bounded_side::ON_BOUNDARY;\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* newConstraintSetFromCt(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\t\tCGALSegment segement = cdt->segment(cgal_e);\r\n\t\t\r\n\t\t/*CGALPoint cgal_u = segement.point(0);\r\n\t\tdouble uxpos = CGAL::to_double(cgal_u.x());\r\n\t\tdouble uypos = CGAL::to_double(cgal_u.y());\r\n\r\n\t\tCGALPoint cgal_v = segement.point(1);\r\n\t\tdouble vxpos = CGAL::to_double(cgal_v.x());\r\n\t\tdouble vypos = CGAL::to_double(cgal_v.y());*/\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\nEdgeVector* convertCdtToGraph(VertexVector* vertices, CDT* cdt) {\r\n\tEdgeVector* edgeVec = new EdgeVector();\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\nvoid computeNonLocallyDelaunay(\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) = newConstraintSetFromCt(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 Delaunay edges\r\n\tstart = boost::chrono::high_resolution_clock::now();\r\n\tboost::unordered_set<TriEdge>* S = new boost::unordered_set<TriEdge>();\r\n\r\n\tTriVertexHandle infiniteVertex = cdt->infinite_vertex();\r\n\tTriFaceHandle infiniteFace = cdt->infinite_face();\r\n\tint edgeCount = 0;\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\tTriVertexHandle v0f0 = f0->vertex(f0->cw(eIndex));\r\n\t\t\tTriVertexHandle v1f0 = f0->vertex(f0->ccw(eIndex));\r\n\r\n\t\t\t//std::cout << eIndex << std::endl;\r\n\t\t\tstd::cout << (*handlesToIndex)[v0f0] << \" \" << (*handlesToIndex)[v1f0] << \" (\" << *v0f0 << \") (\" << *v1f0 << \") \" << (*handlesToIndex)[opp0] << \" (\" << *opp0 << \")\" << std::endl;\r\n\t\t}\r\n\r\n\t\tbool addToS = false;\r\n\r\n\t\tif (opp0 != infiniteVertex && f1 != infiniteFace) {\r\n\t\t\tTriVertexHandle pH = f1->vertex(0);\r\n\t\t\tTriVertexHandle qH = f1->vertex(1);\r\n\t\t\tTriVertexHandle rH = f1->vertex(2);\r\n\r\n\t\t\tif (pH != infiniteVertex && qH != infiniteVertex && rH != infiniteVertex) {\r\n\t\t\t\tCGALPoint p = pH->point();\r\n\t\t\t\tCGALPoint q = qH->point();\r\n\t\t\t\tCGALPoint r = rH->point();\r\n\t\t\t\tCGALPoint t = opp0->point();\r\n\t\t\t\tif (!IsLocallyDelaunay(&p, &q, &r, &t)) {\r\n\t\t\t\t\taddToS = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (opp1 != infiniteVertex && f0 != infiniteFace) {\r\n\t\t\tTriVertexHandle pH = f0->vertex(0);\r\n\t\t\tTriVertexHandle qH = f0->vertex(1);\r\n\t\t\tTriVertexHandle rH = f0->vertex(2);\r\n\r\n\t\t\tif (pH != infiniteVertex && qH != infiniteVertex && rH != infiniteVertex) {\r\n\t\t\t\tCGALPoint p = pH->point();\r\n\t\t\t\tCGALPoint q = qH->point();\r\n\t\t\t\tCGALPoint r = rH->point();\r\n\t\t\t\tCGALPoint t = opp1->point();\r\n\t\t\t\tif (!IsLocallyDelaunay(&p, &q, &r, &t)) {\r\n\t\t\t\t\taddToS = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (addToS) {\r\n\t\t\tS->emplace(e);\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(\"computeNonLocallyDelaunay 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\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\tbool result = true;\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\tstd::cout << \"b contains edge not in a: \" << CGAL::to_double(exactWeight) << \"(\" << edge->u << \",\" << edge->v << \")\" << \" (\" << *u << \") (\" << *v << \")\" << std::endl;\r\n\t\t\tresult = false;\r\n\t\t}\r\n\t}\r\n\r\n\treturn result;\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\r\n\t//sortByXY(ev_cdtS);\r\n\t//printGDFGraph(\"D:\\\\g\\\\results\\\\graph examples\\\\CDT_exact_DC\\\\CdtS.gdf\", vertices, ev_cdtS);\r\n\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\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\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\tcreateRandomMediumLengthPlaneForest(1000, 1000, 100, &vertices, &edges);\r\n\t\t//createRandomNearTriangulation(1000, 1000, 100, &vertices, &edges);\r\n\t}\r\n\telse {\r\n\t\t// Load graph from file\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/*vertices = new VertexVector();\r\n\tvertices->push_back(new CGALPoint(0, 0));\r\n\tvertices->push_back(new CGALPoint(1, 0));\r\n\tvertices->push_back(new CGALPoint(2, 0));\r\n\r\n\tedges = new EdgeVector();\r\n\tedges->push_back(new SimpleEdge(0, 1, 0));\r\n\tedges->push_back(new SimpleEdge(1, 2, 0));\r\n\tedges->push_back(new SimpleEdge(2, 0, 0));*/\r\n\r\n\t// Compute CT(V, E)\r\n\tEdgeVector* NewEdges;\r\n\tEdgeVector* cdtS;\r\n\tcomputeNonLocallyDelaunay(vertices, edges, &NewEdges, &cdtS);\r\n\tEdgeVector* S = intersectInputSetWithConstraintSet(NewEdges, cdtS);\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\\\\CDT_exact_Med\\\\Edges.gdf\", vertices, edges);\r\n\t//printGDFGraph(\"D:\\\\g\\\\results\\\\graph examples\\\\CDT_exact_Med\\\\NewEdges.gdf\", vertices, NewEdges);\r\n\t//printGDFGraph(\"D:\\\\g\\\\results\\\\graph examples\\\\CDT_exact_Med\\\\S.gdf\", vertices, S);\r\n\r\n\tif (SHOW_DEBUG) {\r\n\t\tprintGraph(\"computeNonLocallyDelaunay\", vertices, cdtS, false);\r\n\t\tprintGraph(\"S\", vertices, S, false);\r\n\t}\r\n\r\n\t// Validatation:\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)\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\tdeleteEdgeVector(S);\r\n\tdeleteEdgeVector(cdtS);\r\n\tdeleteEdgeVector(NewEdges);\r\n\tdeleteEdgeVector(edges);\r\n\tdeleteVerticesVector(vertices);\r\n\t\r\n\treturn 0;\r\n}", "meta": {"hexsha": "b2fae57453cc793dd4eb9183e00764073409133c", "size": 15795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cdt.cpp", "max_stars_repo_name": "eduong/cgal_cdt", "max_stars_repo_head_hexsha": "6f6fc3b3e407ec5bf5fd4a95049d4d979a791d2c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-28T10:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-28T10:33:28.000Z", "max_issues_repo_path": "src/cdt.cpp", "max_issues_repo_name": "eduong/cgal_cdt", "max_issues_repo_head_hexsha": "6f6fc3b3e407ec5bf5fd4a95049d4d979a791d2c", "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/cdt.cpp", "max_forks_repo_name": "eduong/cgal_cdt", "max_forks_repo_head_hexsha": "6f6fc3b3e407ec5bf5fd4a95049d4d979a791d2c", "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": 34.0409482759, "max_line_length": 182, "alphanum_fraction": 0.6454574232, "num_tokens": 4800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5035334476288946}}
{"text": "/*\nCopyright 2017 Jiawei Chiu\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 <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n\n#include \"base.h\"\n\nDEFINE_string(train_filename,\n              \"/usr/local/google/home/jiawei/cfgpu/riftbolt/ml-1m/train.txt\",\n              \"Filename for training dataset.\");\nDEFINE_string(test_filename,\n              \"/usr/local/google/home/jiawei/cfgpu/riftbolt/ml-1m/test.txt\",\n              \"Filename for training dataset.\");\n\nDEFINE_int32(log_every_sec, 2, \"Report test error every this many seconds.\");\n\nDEFINE_string(output_filename, \"\", \"Output file for stats.\");\n\nDEFINE_double(learning_rate, 0.005, \"Learning rate for SGD.\");\n\nDEFINE_double(lambda, 0.1, \"Lambda for SGD, used for regularization.\");\n\nDEFINE_int32(k, 32, \"Number of columns for U and V that we want to recover.\");\n\nDEFINE_int32(rng_seed, 3255245, \"Seed for rng.\");\n\nDEFINE_double(max_time, 100000, \"Maximum time in seconds.\");\n\nnamespace gi {\n\ntypedef float FloatType;\n\nusing Eigen::MatrixBase;\n\ntypedef Eigen::MatrixXd Mat;\ntypedef Eigen::Map<Mat> MatMap;\ntypedef Eigen::VectorXd Vec;\ntypedef Eigen::Map<Vec> VecMap;\n\ntypedef Eigen::SparseMatrix<FloatType, Eigen::RowMajor> SpMat;\ntypedef Eigen::Triplet<FloatType> Triplet;\n\nclass RngHelper {\npublic:\n  RngHelper();\n  RngHelper(uint_fast32_t seed);\n  FloatType Normal();\n  void Normal(Mat &m);\n  FloatType Uniform();\n  void Uniform(Mat &m);\n\n  static RngHelper &Get();\n\nprivate:\n  std::mt19937 rng_;\n  std::normal_distribution<FloatType> normal_dist_;\n  std::uniform_real_distribution<FloatType> uniform_dist_;\n};\n\nRngHelper::RngHelper() : RngHelper(FLAGS_rng_seed) {}\n\nRngHelper::RngHelper(uint_fast32_t seed) : rng_(seed) {}\n\nFloatType RngHelper::Normal() { return normal_dist_(rng_); }\n\nvoid RngHelper::Normal(Mat &m) {\n  int size = m.rows() * m.cols();\n  for (int i = 0; i < size; ++i) {\n    m.data()[i] = Normal();\n  }\n}\n\nFloatType RngHelper::Uniform() { return uniform_dist_(rng_); }\n\nvoid RngHelper::Uniform(Mat &m) {\n  int size = m.rows() * m.cols();\n  for (int i = 0; i < size; ++i) {\n    m.data()[i] = Uniform();\n  }\n}\n\nRngHelper &RngHelper::Get() {\n  static RngHelper rng_helper;\n  return rng_helper;\n}\n\nSpMat NewSpMat(const string &filename) {\n  ifstream is(filename);\n\n  // Read in matrix in CSR format.\n  int m;\n  int n;\n  int nnz;\n  CHECK(is >> m >> n >> nnz);\n  vector<FloatType> value(nnz);\n  vector<int> row_ind(m + 1);\n  vector<int> col(nnz);\n  for (int i = 0; i < nnz; ++i) {\n    CHECK(is >> value[i]);\n  }\n  for (int i = 0; i < nnz; ++i) {\n    CHECK(is >> col[i]);\n  }\n  for (int i = 0; i <= m; ++i) {\n    CHECK(is >> row_ind[i]);\n  }\n\n  // Convert to triplets.\n  vector<Triplet> triplets;\n  for (int i = 0; i < m; ++i) {\n    for (int j = row_ind[i]; j < row_ind[i + 1]; ++j) {\n      triplets.emplace_back(i, col[j], value[j]);\n    }\n  }\n\n  // Create our sparse matrix.\n  SpMat out(m, n);\n  out.reserve(nnz);\n  out.setFromTriplets(triplets.begin(), triplets.end());\n  out.makeCompressed();\n\n  // Verify that the matrix built matches the input we get.\n  CHECK_EQ(out.nonZeros(), nnz);\n  CHECK_EQ(out.outerSize(), m);\n  CHECK_EQ(out.innerSize(), n);\n  for (int i = 0; i <= m; ++i) {\n    CHECK_EQ(out.outerIndexPtr()[i], row_ind[i]);\n  }\n  for (int i = 0; i < nnz; ++i) {\n    CHECK_EQ(out.innerIndexPtr()[i], col[i]);\n    CHECK_EQ(out.valuePtr()[i], value[i]);\n  }\n\n  LOG(INFO) << \"Read \" << nnz << \" entries from \" << filename << \"\\n\";\n  return out;\n}\n\nFloatType Square(FloatType x) { return x * x; }\n\nFloatType RmsError(const SpMat &a, Mat &ut, Mat &vt) {\n  FloatType sum = 0;\n  for (int q = 0; q < a.outerSize(); ++q) {\n    for (SpMat::InnerIterator it(a, q); it; ++it) {\n      const int i = it.row();\n      const int j = it.col();\n      sum += Square(it.value() - ut.col(i).dot(vt.col(j)));\n    }\n  }\n  return sqrt(sum / a.nonZeros());\n}\n\nvoid Main() {\n  CHECK(!FLAGS_output_filename.empty());\n  CHECK(!FLAGS_train_filename.empty());\n  CHECK(!FLAGS_test_filename.empty());\n\n  SpMat a_train = NewSpMat(FLAGS_train_filename);\n  SpMat a_test = NewSpMat(FLAGS_test_filename);\n\n  const int k = FLAGS_k;\n\n  // Dimensions check.\n  const int m = a_train.rows();\n  const int n = a_train.cols();\n  CHECK_EQ(m, a_test.rows());\n  CHECK_EQ(n, a_test.cols());\n\n  RngHelper &rng_helper = RngHelper::Get();\n  Mat ut(k, m);\n  Mat vt(k, n);\n\n  // Extra check for dimensions, to be sure.\n  CHECK_EQ(a_train.rows(), a_train.outerSize());\n  CHECK_EQ(a_train.rows(), ut.cols());\n  CHECK_EQ(a_train.cols(), vt.cols());\n  CHECK_EQ(ut.rows(), vt.rows());\n\n  // Initialize ut, vt with random numbers.\n  rng_helper.Uniform(ut);\n  rng_helper.Uniform(vt);\n  ut /= static_cast<FloatType>(k);\n  vt /= static_cast<FloatType>(k);\n\n  // Collect rmse and timing info over iterations.\n  Timer timer;\n  vector<int> l_iter;\n  vector<FloatType> rmse;\n  vector<double> timing;\n  double time_elapsed = 0;\n\n  for (int iter = 0;; ++iter) {\n    const double elapsed = timer.elapsed();\n    if (elapsed > FLAGS_log_every_sec || iter == 0) {\n      // Get time elapsed.\n      time_elapsed += elapsed;\n      timing.push_back(time_elapsed);\n      l_iter.push_back(iter);\n\n      // Compute error.\n      rmse.push_back(RmsError(a_test, ut, vt));\n\n      // Output.\n      LOG(INFO) << \"Iter: \" << l_iter.back()\n                << \" Time elapsed: \" << timing.back()\n                << \" sec RMSE: \" << rmse.back() << \"\\n\";\n\n      // Reset timer.\n      timer.reset();\n\n      if (timing.back() > FLAGS_max_time) {\n        break;\n      }\n    }\n\n    for (int q = 0; q < a_train.outerSize(); ++q) {\n      for (SpMat::InnerIterator it(a_train, q); it; ++it) {\n        const int i = it.row();\n        const int j = it.col();\n        const FloatType err = it.value() - ut.col(i).dot(vt.col(j));\n        ut.col(i) +=\n            FLAGS_learning_rate * (err * vt.col(j) - FLAGS_lambda * ut.col(i));\n        vt.col(j) +=\n            FLAGS_learning_rate * (err * ut.col(i) - FLAGS_lambda * vt.col(j));\n      }\n    }\n  }\n\n  LOG(INFO) << \"Total time taken: \" << time_elapsed << \"\\n\";\n\n  CHECK_EQ(timing.size(), rmse.size());\n  CHECK_EQ(timing.size(), l_iter.size());\n  ofstream os(FLAGS_output_filename);\n  os << \"iter\\ttime\\trmse\\n\";\n  for (size_t i = 0; i < timing.size(); ++i) {\n    os << l_iter[i] << \"\\t\" << timing[i] << \"\\t\" << rmse[i] << \"\\n\";\n  }\n}\n\n} // namespace gi\n\nint main(int argc, char *argv[]) {\n  google::ParseCommandLineFlags(&argc, &argv, true);\n  google::InitGoogleLogging(argv[0]);\n  google::InstallFailureSignalHandler();\n  gi::Main();\n}", "meta": {"hexsha": "623bcf15038eab53a85473eec1bf0bb276e93b00", "size": 6970, "ext": "cc", "lang": "C++", "max_stars_repo_path": "sgd_main.cc", "max_stars_repo_name": "tinkerstash/gpuimpute", "max_stars_repo_head_hexsha": "185609b9f2a8cfa45ee2054b0404bb03aaa71dad", "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": "sgd_main.cc", "max_issues_repo_name": "tinkerstash/gpuimpute", "max_issues_repo_head_hexsha": "185609b9f2a8cfa45ee2054b0404bb03aaa71dad", "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": "sgd_main.cc", "max_forks_repo_name": "tinkerstash/gpuimpute", "max_forks_repo_head_hexsha": "185609b9f2a8cfa45ee2054b0404bb03aaa71dad", "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.8076923077, "max_line_length": 79, "alphanum_fraction": 0.6308464849, "num_tokens": 1962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5034920848661631}}
{"text": "//\n// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n// Copyright 2021 Pranam Lashkari <plashkari628@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#ifndef BOOST_GIL_IMAGE_PROCESSING_DIFFUSION_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_DIFFUSION_HPP\n\n#include \"boost/gil/detail/math.hpp\"\n#include <boost/gil/algorithm.hpp>\n#include <boost/gil/color_base_algorithm.hpp>\n#include <boost/gil/image.hpp>\n#include <boost/gil/image_view.hpp>\n#include <boost/gil/image_view_factory.hpp>\n#include <boost/gil/pixel.hpp>\n#include <boost/gil/point.hpp>\n#include <boost/gil/typedefs.hpp>\n#include <functional>\n#include <numeric>\n#include <vector>\n\nnamespace boost { namespace gil {\nnamespace conductivity {\nstruct perona_malik_conductivity\n{\n    double kappa;\n    template <typename Pixel>\n    Pixel operator()(Pixel input)\n    {\n        using channel_type = typename channel_type<Pixel>::type;\n        // C++11 doesn't seem to capture members\n        static_transform(input, input, [this](channel_type value) {\n            value /= kappa;\n            return std::exp(-std::abs(value));\n        });\n\n        return input;\n    }\n};\n\nstruct gaussian_conductivity\n{\n    double kappa;\n    template <typename Pixel>\n    Pixel operator()(Pixel input)\n    {\n        using channel_type = typename channel_type<Pixel>::type;\n        // C++11 doesn't seem to capture members\n        static_transform(input, input, [this](channel_type value) {\n            value /= kappa;\n            return std::exp(-value * value);\n        });\n\n        return input;\n    }\n};\n\nstruct wide_regions_conductivity\n{\n    double kappa;\n    template <typename Pixel>\n    Pixel operator()(Pixel input)\n    {\n        using channel_type = typename channel_type<Pixel>::type;\n        // C++11 doesn't seem to capture members\n        static_transform(input, input, [this](channel_type value) {\n            value /= kappa;\n            return 1.0 / (1.0 + value * value);\n        });\n\n        return input;\n    }\n};\n\nstruct more_wide_regions_conductivity\n{\n    double kappa;\n    template <typename Pixel>\n    Pixel operator()(Pixel input)\n    {\n        using channel_type = typename channel_type<Pixel>::type;\n        // C++11 doesn't seem to capture members\n        static_transform(input, input, [this](channel_type value) {\n            value /= kappa;\n            return 1.0 / std::sqrt((1.0 + value * value));\n        });\n\n        return input;\n    }\n};\n} // namespace diffusion\n\n/**\n    \\brief contains discrete approximations of 2D Laplacian operator\n*/\nnamespace laplace_function {\n// The functions assume clockwise enumeration of stencil points, as such\n// NW   North NE          0 1 2      (-1, -1) (0, -1) (+1, -1)\n// West       East   ===> 7   3 ===> (-1, 0)          (+1, 0)\n// SW   South SE          6 5 4      (-1, +1) (0, +1) (+1, +1)\n\n/**\n    \\brief This function makes sure all Laplace functions enumerate\n    values in the same order and direction.\n\n    The first element is difference North West direction, second in North,\n    and so on in clockwise manner. Leave element as zero if it is not\n    to be computed.\n*/\ninline std::array<gil::point_t, 8> get_directed_offsets()\n{\n    return {point_t{-1, -1}, point_t{0, -1}, point_t{+1, -1}, point_t{+1, 0},\n            point_t{+1, +1}, point_t{0, +1}, point_t{-1, +1}, point_t{-1, 0}};\n}\n\ntemplate <typename PixelType>\nusing stencil_type = std::array<PixelType, 8>;\n\n/**\n    \\brief 5 point stencil approximation of Laplacian\n\n    Only main 4 directions are non-zero, the rest are zero\n*/\nstruct stencil_5points\n{\n    double delta_t = 0.25;\n\n    template <typename SubImageView>\n    stencil_type<typename SubImageView::value_type> compute_laplace(SubImageView view,\n                                                                    point_t origin)\n    {\n        auto current = view(origin);\n        stencil_type<typename SubImageView::value_type> stencil;\n        using channel_type = typename channel_type<typename SubImageView::value_type>::type;\n        std::array<gil::point_t, 8> offsets(get_directed_offsets());\n        typename SubImageView::value_type zero_pixel;\n        static_fill(zero_pixel, 0);\n        for (std::size_t index = 0; index < offsets.size(); ++index)\n        {\n            if (index % 2 != 0)\n            {\n                static_transform(view(origin.x + offsets[index].x, origin.y + offsets[index].y),\n                                 current, stencil[index], std::minus<channel_type>{});\n            }\n            else\n            {\n                stencil[index] = zero_pixel;\n            }\n        }\n        return stencil;\n    }\n\n    template <typename Pixel>\n    Pixel reduce(const stencil_type<Pixel>& stencil)\n    {\n        auto first = stencil.begin();\n        auto last = stencil.end();\n        using channel_type = typename channel_type<Pixel>::type;\n        auto result = []() {\n            Pixel zero_pixel;\n            static_fill(zero_pixel, channel_type(0));\n            return zero_pixel;\n        }();\n\n        for (std::size_t index : {1u, 3u, 5u, 7u})\n        {\n            static_transform(result, stencil[index], result, std::plus<channel_type>{});\n        }\n        Pixel delta_t_pixel;\n        static_fill(delta_t_pixel, delta_t);\n        static_transform(result, delta_t_pixel, result, std::multiplies<channel_type>{});\n\n        return result;\n    }\n};\n\n/**\n    \\brief 9 point stencil approximation of Laplacian\n\n    This is full 8 way approximation, though diagonal\n    elements are halved during reduction.\n*/\nstruct stencil_9points_standard\n{\n    double delta_t = 0.125;\n\n    template <typename SubImageView>\n    stencil_type<typename SubImageView::value_type> compute_laplace(SubImageView view,\n                                                                    point_t origin)\n    {\n        stencil_type<typename SubImageView::value_type> stencil;\n        auto out = stencil.begin();\n        auto current = view(origin);\n        using channel_type = typename channel_type<typename SubImageView::value_type>::type;\n        std::array<gil::point_t, 8> offsets(get_directed_offsets());\n        for (auto offset : offsets)\n        {\n            static_transform(view(origin.x + offset.x, origin.y + offset.y), current, *out++,\n                             std::minus<channel_type>{});\n        }\n\n        return stencil;\n    }\n\n    template <typename Pixel>\n    Pixel reduce(const stencil_type<Pixel>& stencil)\n    {\n        using channel_type = typename channel_type<Pixel>::type;\n        auto result = []() {\n            Pixel zero_pixel;\n            static_fill(zero_pixel, channel_type(0));\n            return zero_pixel;\n        }();\n        for (std::size_t index : {1u, 3u, 5u, 7u})\n        {\n            static_transform(result, stencil[index], result, std::plus<channel_type>{});\n        }\n\n        for (std::size_t index : {0u, 2u, 4u, 6u})\n        {\n            Pixel half_pixel;\n            static_fill(half_pixel, channel_type(1 / 2.0));\n            static_transform(stencil[index], half_pixel, half_pixel,\n                             std::multiplies<channel_type>{});\n            static_transform(result, half_pixel, result, std::plus<channel_type>{});\n        }\n\n        Pixel delta_t_pixel;\n        static_fill(delta_t_pixel, delta_t);\n        static_transform(result, delta_t_pixel, result, std::multiplies<channel_type>{});\n\n        return result;\n    }\n};\n} // namespace laplace_function\n\nnamespace brightness_function {\nusing laplace_function::stencil_type;\nstruct identity\n{\n    template <typename Pixel>\n    stencil_type<Pixel> operator()(const stencil_type<Pixel>& stencil)\n    {\n        return stencil;\n    }\n};\n\n// TODO: Figure out how to implement color gradient brightness, as it\n// seems to need dx and dy using sobel or scharr kernels\n\nstruct rgb_luminance\n{\n    using pixel_type = rgb32f_pixel_t;\n    stencil_type<pixel_type> operator()(const stencil_type<pixel_type>& stencil)\n    {\n        stencil_type<pixel_type> output;\n        std::transform(stencil.begin(), stencil.end(), output.begin(), [](const pixel_type& pixel) {\n            float32_t luminance = 0.2126f * pixel[0] + 0.7152f * pixel[1] + 0.0722f * pixel[2];\n            pixel_type result_pixel;\n            static_fill(result_pixel, luminance);\n            return result_pixel;\n        });\n        return output;\n    }\n};\n\n} // namespace brightness_function\n\nenum class matlab_connectivity\n{\n    minimal,\n    maximal\n};\n\nenum class matlab_conduction_method\n{\n    exponential,\n    quadratic\n};\n\ntemplate <typename InputView, typename OutputView>\nvoid classic_anisotropic_diffusion(const InputView& input, const OutputView& output,\n                                   unsigned int num_iter, double kappa)\n{\n    anisotropic_diffusion(input, output, num_iter, laplace_function::stencil_5points{},\n                          brightness_function::identity{},\n                          conductivity::perona_malik_conductivity{kappa});\n}\n\ntemplate <typename InputView, typename OutputView>\nvoid matlab_anisotropic_diffusion(const InputView& input, const OutputView& output,\n                                  unsigned int num_iter, double kappa,\n                                  matlab_connectivity connectivity,\n                                  matlab_conduction_method conduction_method)\n{\n    if (connectivity == matlab_connectivity::minimal)\n    {\n        if (conduction_method == matlab_conduction_method::exponential)\n        {\n            anisotropic_diffusion(input, output, num_iter, laplace_function::stencil_5points{},\n                                  brightness_function::identity{},\n                                  conductivity::gaussian_conductivity{kappa});\n        }\n        else if (conduction_method == matlab_conduction_method::quadratic)\n        {\n            anisotropic_diffusion(input, output, num_iter, laplace_function::stencil_5points{},\n                                  brightness_function::identity{},\n                                  conductivity::gaussian_conductivity{kappa});\n        }\n        else\n        {\n            throw std::logic_error(\"unhandled conduction method found\");\n        }\n    }\n    else if (connectivity == matlab_connectivity::maximal)\n    {\n        if (conduction_method == matlab_conduction_method::exponential)\n        {\n            anisotropic_diffusion(input, output, num_iter, laplace_function::stencil_5points{},\n                                  brightness_function::identity{},\n                                  conductivity::gaussian_conductivity{kappa});\n        }\n        else if (conduction_method == matlab_conduction_method::quadratic)\n        {\n            anisotropic_diffusion(input, output, num_iter, laplace_function::stencil_5points{},\n                                  brightness_function::identity{},\n                                  conductivity::gaussian_conductivity{kappa});\n        }\n        else\n        {\n            throw std::logic_error(\"unhandled conduction method found\");\n        }\n    }\n    else\n    {\n        throw std::logic_error(\"unhandled connectivity found\");\n    }\n}\n\ntemplate <typename InputView, typename OutputView>\nvoid default_anisotropic_diffusion(const InputView& input, const OutputView& output,\n                                   unsigned int num_iter, double kappa)\n{\n    anisotropic_diffusion(input, output, num_iter, laplace_function::stencil_9points_standard{},\n                          brightness_function::identity{}, conductivity::gaussian_conductivity{kappa});\n}\n\n/// \\brief Performs diffusion according to Perona-Malik equation\n///\n/// WARNING: Output channel type must be floating point,\n/// otherwise there will be loss in accuracy which most\n/// probably will lead to incorrect results (input will be unchanged).\n/// Anisotropic diffusion is a smoothing algorithm that respects\n/// edge boundaries and can work as an edge detector if suitable\n/// iteration count is set and grayscale image view is used\n/// as an input\ntemplate <typename InputView, typename OutputView,\n          typename LaplaceStrategy = laplace_function::stencil_9points_standard,\n          typename BrightnessFunction = brightness_function::identity,\n          typename DiffusivityFunction = conductivity::gaussian_conductivity>\nvoid anisotropic_diffusion(const InputView& input, const OutputView& output, unsigned int num_iter,\n                           LaplaceStrategy laplace, BrightnessFunction brightness,\n                           DiffusivityFunction diffusivity)\n{\n    using input_pixel_type = typename InputView::value_type;\n    using pixel_type = typename OutputView::value_type;\n    using channel_type = typename channel_type<pixel_type>::type;\n    using computation_image = image<pixel_type>;\n    const auto width = input.width();\n    const auto height = input.height();\n    const point_t dims(width, height);\n    const auto zero_pixel = []() {\n        pixel_type pixel;\n        static_fill(pixel, static_cast<channel_type>(0));\n\n        return pixel;\n    }();\n    computation_image result_image(width + 2, height + 2, zero_pixel);\n    auto result = view(result_image);\n    computation_image scratch_result_image(width + 2, height + 2, zero_pixel);\n    auto scratch_result = view(scratch_result_image);\n    transform_pixels(input, subimage_view(result, 1, 1, width, height),\n                     [](const input_pixel_type& pixel) {\n                         pixel_type converted;\n                         for (std::size_t i = 0; i < num_channels<pixel_type>{}; ++i)\n                         {\n                             converted[i] = pixel[i];\n                         }\n                         return converted;\n                     });\n\n    for (unsigned int iteration = 0; iteration < num_iter; ++iteration)\n    {\n        for (std::ptrdiff_t relative_y = 0; relative_y < height; ++relative_y)\n        {\n            for (std::ptrdiff_t relative_x = 0; relative_x < width; ++relative_x)\n            {\n                auto x = relative_x + 1;\n                auto y = relative_y + 1;\n                auto stencil = laplace.compute_laplace(result, point_t(x, y));\n                auto brightness_stencil = brightness(stencil);\n                laplace_function::stencil_type<pixel_type> diffusivity_stencil;\n                std::transform(brightness_stencil.begin(), brightness_stencil.end(),\n                               diffusivity_stencil.begin(), diffusivity);\n                laplace_function::stencil_type<pixel_type> product_stencil;\n                std::transform(stencil.begin(), stencil.end(), diffusivity_stencil.begin(),\n                               product_stencil.begin(), [](pixel_type lhs, pixel_type rhs) {\n                                   static_transform(lhs, rhs, lhs, std::multiplies<channel_type>{});\n                                   return lhs;\n                               });\n                static_transform(result(x, y), laplace.reduce(product_stencil),\n                                 scratch_result(x, y), std::plus<channel_type>{});\n            }\n        }\n        using std::swap;\n        swap(result, scratch_result);\n    }\n\n    copy_pixels(subimage_view(result, 1, 1, width, height), output);\n}\n\n}} // namespace boost::gil\n\n#endif\n", "meta": {"hexsha": "eedd50ebb8aeea15aaf962d4380f48395b4ffa0e", "size": 15315, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/diffusion.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/diffusion.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/diffusion.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": 35.6993006993, "max_line_length": 103, "alphanum_fraction": 0.6127326151, "num_tokens": 3318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.503492084866163}}
{"text": "/**\n * @file libfrcima.hpp\n * @author Jorge Ag\u00fcero Zamora\n * @brief Contains the RCIMA and fast-RCIMA methods\n * @version 0.1\n * @date 2021-06-14\n * \n * @copyright Copyright (c) 2021\n * \n */\n#ifndef LIBFRCIMA_H\n#define LIBFRCIMA_H\n\n#define LOW_RANK_APPROX_ITERATIONS 3 //!< amount of iteration to approximate low rank matrix\n\n#include <armadillo>\n#include <vector>\n#include <algorithm>\n\nnamespace frcima\n{\n  using arma::mat;\n  using std::vector;\n\n  extern double _calculated_error; //!< global variable to hold calculated error\n\n  /**\n * @brief calculates rank constrained inverse matrix approximation using RCIMA method\n * \n * @param t_data_x the original source images. The training data is a vector of vectors \n *                  containing a vectorized form of an image\n * @param t_data_c the images with a noise. The training data is a vector of vectors \n *                  containing a vectorized form of an image\n * @param rank desired rank constrain, should be less than the size of training data \n * @return mat rank constrained inverse matrix approximation \n */\n  mat rcima(const vector<vector<double>> &t_data_x, const vector<vector<double>> &t_data_c, const size_t rank);\n\n  /**\n * @brief calculates rank constrained inverse matrix approximation using RCIMA method\n * \n * @param t_data_x the original source images. The training data is an arma::mat  \n *                  where each column is a vectorized form of a training image\n * @param t_data_c the images with a noise applied. The training data is an arma::mat  \n *                  where each column is a vectorized form of a training image\n * @param rank desired rank constrain, should be less than the size of training data \n * @return mat rank constrained inverse matrix approximation \n */\n  mat rcima(const mat &X, const mat &C, const size_t rank);\n\n  /**\n * @brief calculates rank constrained inverse matrix approximation using fast-RCIMA algorithm\n * \n * @param t_data_x the original source images. The training data is a vector of vectors \n *                  containing a vectorized form of an image\n * @param t_data_c the images with noise. The training data is a vector of vectors \n *                  containing a vectorized form of an image\n * @param rank desired rank approximation, should be less than the size of training data\n * @return mat rank constrained inverse matrix approximation\n */\n  mat fast_rcima(const vector<vector<double>> &t_data_x, const vector<vector<double>> &t_data_c, const size_t rank);\n\n  /**\n * @brief calculates rank constrained inverse matrix approximation using fast-RCIMA algorithm\n * \n * @param t_data_x the original source images. The training data is an arma::mat  \n *                  where each column is a vectorized form of a training image\n * @param t_data_c the images with noise. The training data is an arma::mat  \n *                  where each column is a vectorized form of a training image\n * @param rank desired rank approximation, should be less than the size of training data\n * @return mat rank constrained inverse matrix approximation\n */\n  mat fast_rcima(const mat &X, const mat &C, const size_t rank);\n\n}\n\n#endif", "meta": {"hexsha": "99bec9369c12829f4b043de767f3665f00674c7f", "size": 3148, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/libfrcima/include/libfrcima.hpp", "max_stars_repo_name": "h4koo/FSP_ImageDeconvolution", "max_stars_repo_head_hexsha": "724b3c9a1a0a7c45803bd783f61e0363046a2d79", "max_stars_repo_licenses": ["MIT"], "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/libfrcima/include/libfrcima.hpp", "max_issues_repo_name": "h4koo/FSP_ImageDeconvolution", "max_issues_repo_head_hexsha": "724b3c9a1a0a7c45803bd783f61e0363046a2d79", "max_issues_repo_licenses": ["MIT"], "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/libfrcima/include/libfrcima.hpp", "max_forks_repo_name": "h4koo/FSP_ImageDeconvolution", "max_forks_repo_head_hexsha": "724b3c9a1a0a7c45803bd783f61e0363046a2d79", "max_forks_repo_licenses": ["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.8831168831, "max_line_length": 116, "alphanum_fraction": 0.7195044473, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5034920675373258}}
{"text": "/*\n * FullyIndependentTrainingConditional.cpp\n *\n *  Created on: Nov 8, 2016\n *      Author: menhorn\n */\n\n#include <FullyIndependentTrainingConditional.hpp>\n#include <random>\n#include <assert.h>\n#include <algorithm>\n#include <iostream>\n#include <limits.h>\n#include <cmath>\n\n #include <Eigen/Dense>\n\n//--------------------------------------------------------------------------------\nFullyIndependentTrainingConditional::FullyIndependentTrainingConditional(int n,\n\t\tdouble &delta_input) :\n\t\tGaussianProcess(n, delta_input, nullptr) {\n\n}\n//--------------------------------------------------------------------------------\nFullyIndependentTrainingConditional::FullyIndependentTrainingConditional(int n,\n\t\tdouble &delta_input, std::vector<double> gp_parameters_input) :\n\t\tGaussianProcess(n, delta_input, nullptr, gp_parameters_input) {\n\n}\n//--------------------------------------------------------------------------------\ndouble FullyIndependentTrainingConditional::evaluate_kernel ( VectorXd const &x,\n                                          VectorXd const &y )\n{\n  return evaluate_kernel ( x, y, gp_parameters );\n}\n//--------------------------------------------------------------------------------\ndouble FullyIndependentTrainingConditional::evaluate_kernel ( VectorXd const &x,\n                                          VectorXd const &y,\n                                          std::vector<double> const &p )\n{\n  dist = 0e0;\n  for ( int i = 0; i < dim; ++i )\n    dist += pow( (x(i) - y(i)), 2e0) /  p.at( i+1 );\n  kernel_evaluation = exp(-dist / 2e0 );\n  \n  return kernel_evaluation * p.at( 0 ) ;\n}\n\ndouble FullyIndependentTrainingConditional::evaluate_kernel1D_exp_term(double const &x,\n                              double const &y,\n                              double const &l ){\n\treturn exp(-0.5*((x-y)*(x-y))/ l);\n}\n\nvoid FullyIndependentTrainingConditional::derivate_K_u_u_wrt_uik(std::vector<double> const &p,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t int const &i, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t int const &k,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t MatrixXd &deriv_matrix ){\n\tconst int nb_u_nodes = u.rows();\n\tderiv_matrix.resize(nb_u_nodes, nb_u_nodes);\n\tderiv_matrix.setZero();\n\tdouble C = 0;\n\tfor(int j = 0; j < nb_u_nodes; ++j){\n\t\tC = p[0]; //sigma_f^2\n\t\tfor(int d = 0; d < dim; ++d){\n\t\t\tC *= evaluate_kernel1D_exp_term(u(i, d), u(j, d), p[1+d]);\n\t\t}\n\t\tderiv_matrix(i,j) = C * (-1) * (u(i, k)-u(j, k))/p[k+1];\n\t}\n\tfor(int j = 0; j < nb_u_nodes; ++j){\n\t\tderiv_matrix(j,i) = deriv_matrix(i,j);\n\t}\n\t/*//Good\n\tMatrixXd K_u_u_fd1(nb_u_nodes, nb_u_nodes);\n\tMatrixXd K_u_u_fd2(nb_u_nodes, nb_u_nodes);\n\n\tMatrixXd ufd1(nb_u_nodes, dim);\n\tMatrixXd ufd2(nb_u_nodes, dim);\n\tfor(int j = 0; j < nb_u_nodes; ++j){\n\t\tfor(int d = 0; d < dim; ++d){\n\t\t\tufd1(j,d) = u(j,d);\n\t\t\tufd2(j,d) = u(j,d);\n\t\t}\n\t}\n\tufd1(i, k) += 0.1;\n\tufd2(i, k) -= 0.1;\n\tfor (int h = 0; h < nb_u_nodes; ++h) {\n\t\tfor (int j = 0; j < nb_u_nodes; ++j) {\n\t\t\tK_u_u_fd1(h, j) = evaluate_kernel(ufd1.row(h), ufd1.row(j));\n\t\t\tK_u_u_fd2(h, j) = evaluate_kernel(ufd2.row(h), ufd2.row(j));\n\t\t}\n\t}\n\tK_u_u_fd1 = 1.0/0.2 * (K_u_u_fd1-K_u_u_fd2);\n\tstd::cout << \"Kufdot \" << deriv_matrix << std::endl;\n\tstd::cout << \"K_u_f_fd1 \" << K_u_u_fd1 << std::endl;\n\texit(-1);\n\t*/\n}\n\n\nvoid FullyIndependentTrainingConditional::derivate_K_u_f_wrt_uik(std::vector<double> const &p,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t int const &i, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t int const &k,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t MatrixXd &deriv_matrix ){\n\tconst int nb_u_nodes = u.rows();\n\tderiv_matrix.resize(nb_u_nodes, nb_gp_nodes);\n\tderiv_matrix.setZero();\n\tdouble C = 0;\n\tfor(int j = 0; j < nb_gp_nodes; ++j){\n\t\tC = p[0]; //sigma_f^2\n\t\tfor(int d = 0; d < dim; ++d){\n\t\t\tC *= evaluate_kernel1D_exp_term(u(i, d), gp_nodes_eigen(j, d), p[1+d]);\n\t\t}\n\t\tderiv_matrix(i,j) = C * (-1) * (u(i, k)-gp_nodes_eigen(j, k))/p[k+1];\n\t}\n\t\n\t/*Good\n\tMatrixXd K_f_u_fd1(nb_gp_nodes, nb_u_nodes);\n\tMatrixXd K_f_u_fd2(nb_gp_nodes, nb_u_nodes);\n\n\tMatrixXd ufd1(nb_u_nodes, dim);\n\tMatrixXd ufd2(nb_u_nodes, dim);\n\tfor(int j = 0; j < nb_u_nodes; ++j){\n\t\tfor(int d = 0; d < dim; ++d){\n\t\t\tufd1(j,d) = u(j,d);\n\t\t\tufd2(j,d) = u(j,d);\n\t\t}\n\t}\n\tufd1(i, k) += 0.1;\n\tufd2(i, k) -= 0.1;\n\tfor (int h = 0; h < nb_u_nodes; ++h) {\n\t\tfor (int j = 0; j < nb_gp_nodes; ++j) {\n\t\t\tK_f_u_fd1(j, h) = evaluate_kernel(gp_nodes_eigen.row(j), ufd1.row(h));\n\t\t\tK_f_u_fd2(j, h) = evaluate_kernel(gp_nodes_eigen.row(j), ufd2.row(h));\n\t\t}\n\t}\n\tK_f_u_fd1 = 1.0/0.2 * (K_f_u_fd1-K_f_u_fd2);\n\tstd::cout << \"Kufdot \" << deriv_matrix << std::endl;\n\tstd::cout << \"K_f_u_fd1 \" << K_f_u_fd1 << std::endl;\n\texit(-1);\n\t*/\n\t\n}\n\nvoid FullyIndependentTrainingConditional::derivate_K_u_f_wrt_sigmaf(std::vector<double> const &p, \n                                                    MatrixXd &deriv_matrix){\n\tconst int nb_u_nodes = u.rows();\n\tderiv_matrix.resize(nb_u_nodes, nb_gp_nodes);\n\tderiv_matrix.setZero();\n\tdouble C = 0;\n\t//Set up matrix d(K_u_f)/d(sigma_f^2)\n\tfor (int i = 0; i < nb_u_nodes; ++i) {\n\t\tfor (int j = 0; j < nb_gp_nodes; ++j) {\n\t\t\tC = 1.0;\n\t\t\tfor(int d = 0; d < dim; ++d){\n\t\t\t\tC *= evaluate_kernel1D_exp_term(u(i, d), gp_nodes_eigen(j, d), p[1+d]);\n\t\t\t}\n\t\t\tderiv_matrix(i,j) = C;\n\t\t}\n\t}\n\t/*Good\n\tMatrixXd K_f_u_fd1(nb_gp_nodes, nb_u_nodes);\n\tMatrixXd K_f_u_fd2(nb_gp_nodes, nb_u_nodes);\n\n\tstd::vector<double> gpfd1 = gp_parameters;\n\tgpfd1[0] += 0.1; \n\tstd::vector<double> gpfd2 = gp_parameters;\n\tgpfd2[0] -= 0.1;\n\tfor (int h = 0; h < nb_u_nodes; ++h) {\n\t\tfor (int j = 0; j < nb_gp_nodes; ++j) {\n\t\t\tK_f_u_fd1(j, h) = evaluate_kernel(gp_nodes_eigen.row(j), u.row(h), gpfd1);\n\t\t\tK_f_u_fd2(j, h) = evaluate_kernel(gp_nodes_eigen.row(j), u.row(h), gpfd2);\n\t\t}\n\t}\n\tK_f_u_fd1 = 1.0/0.2 * (K_f_u_fd1-K_f_u_fd2);\n\tstd::cout << \"Kufdot \" << deriv_matrix << std::endl;\n\tstd::cout << \"K_u_f_fd1 \" << K_f_u_fd1 << std::endl;\n\texit(-1);\n\t*/\n}\n\nvoid FullyIndependentTrainingConditional::derivate_K_f_f_wrt_sigmaf(std::vector<double> const &p, \n                                                    MatrixXd &deriv_matrix){\n\tderiv_matrix.resize(nb_gp_nodes, nb_gp_nodes);\n\tderiv_matrix.setZero();\n\tdouble C = 0;\n\t//Set up matrix d(K_u_f)/d(sigma_f^2)\n\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\tfor (int j = 0; j < nb_gp_nodes; ++j) {\n\t\t\tC = 1.0;\n\t\t\tfor(int d = 0; d < dim; ++d){\n\t\t\t\tC *= evaluate_kernel1D_exp_term(gp_nodes_eigen(i, d), gp_nodes_eigen(j, d), p[1+d]);\n\t\t\t}\n\t\t\tderiv_matrix(i,j) = C;\n\t\t}\n\t}\n\t/*Good\n\tMatrixXd K_f_f_fd1(nb_gp_nodes, nb_gp_nodes);\n\tMatrixXd K_f_f_fd2(nb_gp_nodes, nb_gp_nodes);\n\n\tstd::vector<double> gpfd1 = gp_parameters;\n\tgpfd1[0] += 0.1; \n\tstd::vector<double> gpfd2 = gp_parameters;\n\tgpfd2[0] -= 0.1;\n\tfor (int h = 0; h < nb_gp_nodes; ++h) {\n\t\tfor (int j = 0; j < nb_gp_nodes; ++j) {\n\t\t\tK_f_f_fd1(j, h) = evaluate_kernel(gp_nodes_eigen.row(j), gp_nodes_eigen.row(h), gpfd1);\n\t\t\tK_f_f_fd2(j, h) = evaluate_kernel(gp_nodes_eigen.row(j), gp_nodes_eigen.row(h), gpfd2);\n\t\t}\n\t}\n\tK_f_f_fd1 = 1.0/0.2 * (K_f_f_fd1-K_f_f_fd2);\n\tstd::cout << \"Kufdot \" << deriv_matrix << std::endl;\n\tstd::cout << \"K_f_f_fd1 \" << K_f_f_fd1 << std::endl;\n\texit(-1);\n\t*/\n}\n\nvoid FullyIndependentTrainingConditional::derivate_K_u_u_wrt_sigmaf(std::vector<double> const &p, \n                                                    MatrixXd &deriv_matrix){\n\tconst int nb_u_nodes = u.rows();\n\tderiv_matrix.resize(nb_u_nodes, nb_u_nodes);\n\tderiv_matrix.setZero();\n\tdouble C = 0;\n\t//Set up matrix d(K_u_f)/d(sigma_f^2)\n\tfor (int i = 0; i < nb_u_nodes; ++i) {\n\t\tfor (int j = 0; j < nb_u_nodes; ++j) {\n\t\t\tC = 1.0;//sigma_f^2\n\t\t\tfor(int d = 0; d < dim; ++d){\n\t\t\t\tC *= evaluate_kernel1D_exp_term(u(i, d), u(j, d), p[1+d]);\n\t\t\t}\n\t\t\tderiv_matrix(i,j) = C;\n\t\t}\n\t}\n\t/*//Good\n\tMatrixXd K_u_u_fd1(nb_u_nodes, nb_u_nodes);\n\tMatrixXd K_u_u_fd2(nb_u_nodes, nb_u_nodes);\n\n\tstd::vector<double> gpfd1 = gp_parameters;\n\tgpfd1[0] += 0.1; \n\tstd::vector<double> gpfd2 = gp_parameters;\n\tgpfd2[0] -= 0.1;\n\tfor (int h = 0; h < nb_u_nodes; ++h) {\n\t\tfor (int j = 0; j < nb_u_nodes; ++j) {\n\t\t\tK_u_u_fd1(j, h) = evaluate_kernel(u.row(j), u.row(h), gpfd1);\n\t\t\tK_u_u_fd2(j, h) = evaluate_kernel(u.row(j), u.row(h), gpfd2);\n\t\t}\n\t}\n\tK_u_u_fd1 = 1.0/0.2 * (K_u_u_fd1-K_u_u_fd2);\n\tstd::cout << \"Kuudot \" << deriv_matrix << std::endl;\n\tstd::cout << \"K_u_u_fd1 \" << K_u_u_fd1 << std::endl;\n\texit(-1);\n\t*/\n}\n\nvoid FullyIndependentTrainingConditional::derivate_K_u_f_wrt_l(std::vector<double> const &p,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t int const &k,\n                                        \t\t\t\t\t\t\tMatrixXd &deriv_matrix){\n\tconst int nb_u_nodes = u.rows();\n\tderiv_matrix.resize(nb_u_nodes, nb_gp_nodes);\n\tderiv_matrix.setZero();\n\tdouble C = 0;\n\t//Set up matrix d(K_u_f)/d(sigma_f^2)\n\tfor (int i = 0; i < nb_u_nodes; ++i) {\n\t\tfor (int j = 0; j < nb_gp_nodes; ++j) {\n\t\t\tC = p[0];\n\t\t\tfor(int d = 0; d < dim; ++d){\n\t\t\t\tC *= evaluate_kernel1D_exp_term(u(i, d), gp_nodes_eigen(j, d), p[1+d]);\n\t\t\t}\n\t\t\tderiv_matrix(i,j) = C * (u(i, k)-gp_nodes_eigen(j, k))*(u(i, k)-gp_nodes_eigen(j, k))/\n\t\t\t\t\t\t\t\t\t\t\t(2*p[k+1]*p[k+1]);\n\t\t}\n\t}\n\t/*//Good\n\tMatrixXd K_f_u_fd1(nb_gp_nodes, nb_u_nodes);\n\tMatrixXd K_f_u_fd2(nb_gp_nodes, nb_u_nodes);\n\n\tstd::vector<double> gpfd1 = gp_parameters;\n\tgpfd1[k+1] += 0.1; \n\tstd::vector<double> gpfd2 = gp_parameters;\n\tgpfd2[k+1] -= 0.1;\n\tfor (int h = 0; h < nb_u_nodes; ++h) {\n\t\tfor (int j = 0; j < nb_gp_nodes; ++j) {\n\t\t\tK_f_u_fd1(j, h) = evaluate_kernel(gp_nodes_eigen.row(j), u.row(h), gpfd1);\n\t\t\tK_f_u_fd2(j, h) = evaluate_kernel(gp_nodes_eigen.row(j), u.row(h), gpfd2);\n\t\t}\n\t}\n\tK_f_u_fd1 = 1.0/0.2 * (K_f_u_fd1-K_f_u_fd2);\n\tstd::cout << \"Kufdot \" << deriv_matrix << std::endl;\n\tstd::cout << \"K_u_f_fd1 \" << K_f_u_fd1 << std::endl;\n\texit(-1);\n\t*/\n}\n\nvoid FullyIndependentTrainingConditional::derivate_K_f_f_wrt_l(std::vector<double> const &p,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t int const &k,\n                                        \t\t\t\t\t\t\tMatrixXd &deriv_matrix){\n\tderiv_matrix.resize(nb_gp_nodes, nb_gp_nodes);\n\tderiv_matrix.setZero();\n\tdouble C = 0;\n\t//Set up matrix d(K_u_f)/d(sigma_f^2)\n\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\tfor (int j = 0; j < nb_gp_nodes; ++j) {\n\t\t\tC = p[0];\n\t\t\tfor(int d = 0; d < dim; ++d){\n\t\t\t\tC *= evaluate_kernel1D_exp_term(gp_nodes_eigen(i, d), gp_nodes_eigen(j, d), p[1+d]);\n\t\t\t}\n\t\t\tderiv_matrix(i,j) = C * (gp_nodes_eigen(i, k)-gp_nodes_eigen(j, k))*\n\t\t\t\t\t\t\t\t\t(gp_nodes_eigen(i, k)-gp_nodes_eigen(j, k))/\n\t\t\t\t\t\t\t\t\t\t\t(2*p[k+1]*p[k+1]);\n\t\t}\n\t}\n\t/*//Good\n\tMatrixXd K_f_f_fd1(nb_gp_nodes, nb_gp_nodes);\n\tMatrixXd K_f_f_fd2(nb_gp_nodes, nb_gp_nodes);\n\n\tstd::vector<double> gpfd1 = gp_parameters;\n\tgpfd1[k+1] += 0.1; \n\tstd::vector<double> gpfd2 = gp_parameters;\n\tgpfd2[k+1] -= 0.1;\n\tfor (int h = 0; h < nb_gp_nodes; ++h) {\n\t\tfor (int j = 0; j < nb_gp_nodes; ++j) {\n\t\t\tK_f_f_fd1(j, h) = evaluate_kernel(gp_nodes_eigen.row(j), gp_nodes_eigen.row(h), gpfd1);\n\t\t\tK_f_f_fd2(j, h) = evaluate_kernel(gp_nodes_eigen.row(j), gp_nodes_eigen.row(h), gpfd2);\n\t\t}\n\t}\n\tK_f_f_fd1 = 1.0/0.2 * (K_f_f_fd1-K_f_f_fd2);\n\tstd::cout << \"Kffdot \" << deriv_matrix << std::endl;\n\tstd::cout << \"K_f_f_fd1 \" << K_f_f_fd1 << std::endl;\n\texit(-1);\n\t*/\n}\n\nvoid FullyIndependentTrainingConditional::derivate_K_u_u_wrt_l(std::vector<double> const &p,\n                                         int const &k,\n                                    MatrixXd &deriv_matrix){\n\tconst int nb_u_nodes = u.rows();\n\tderiv_matrix.resize(nb_u_nodes, nb_u_nodes);\n\tderiv_matrix.setZero();\n\tdouble C = 0;\n\t//Set up matrix d(K_u_f)/d(sigma_f^2)\n\tfor (int i = 0; i < nb_u_nodes; ++i) {\n\t\tfor (int j = 0; j < nb_u_nodes; ++j) {\n\t\t\tC = p[0];\n\t\t\tfor(int d = 0; d < dim; ++d){\n\t\t\t\tC *= evaluate_kernel1D_exp_term(u(i, d), u(j, d), p[1+d]);\n\t\t\t}\n\t\t\tderiv_matrix(i,j) = C * (u(i, k)-u(j, k))*(u(i, k)-u(j, k))/\n\t\t\t\t\t\t\t\t\t\t\t(2*p[k+1]*p[k+1]);\n\t\t}\n\t}\n\t/*//Good\n\tMatrixXd K_u_u_fd1(nb_u_nodes, nb_u_nodes);\n\tMatrixXd K_u_u_fd2(nb_u_nodes, nb_u_nodes);\n\n\tstd::vector<double> gpfd1 = gp_parameters;\n\tgpfd1[k+1] += 0.1; \n\tstd::vector<double> gpfd2 = gp_parameters;\n\tgpfd2[k+1] -= 0.1;\n\tfor (int h = 0; h < nb_u_nodes; ++h) {\n\t\tfor (int j = 0; j < nb_u_nodes; ++j) {\n\t\t\tK_u_u_fd1(j, h) = evaluate_kernel(u.row(j), u.row(h), gpfd1);\n\t\t\tK_u_u_fd2(j, h) = evaluate_kernel(u.row(j), u.row(h), gpfd2);\n\t\t}\n\t}\n\tK_u_u_fd1 = 1.0/0.2 * (K_u_u_fd1-K_u_u_fd2);\n\tstd::cout << \"Kuudot \" << deriv_matrix << std::endl;\n\tstd::cout << \"K_u_u_fd1 \" << K_u_u_fd1 << std::endl;\n\texit(-1);\n\t*/\n}\n\n\nvoid FullyIndependentTrainingConditional::compute_Kuf_and_Kuu() {\n\tint nb_u_nodes = u.rows();\n\t//Set up matrix K_u_f and K_f_u\n\tK_u_f.resize(nb_u_nodes, nb_gp_nodes);\n\tfor (int i = 0; i < nb_u_nodes; ++i) {\n\t\tfor (int j = 0; j < nb_gp_nodes; ++j) {\n\t\t\tK_u_f(i, j) = evaluate_kernel(u.row(i), gp_nodes_eigen.row(j));\n\t\t}\n\t}\n\t//Set up matrix K_u_u\n\tK_u_u.resize(nb_u_nodes, nb_u_nodes);\n\tfor (int i = 0; i < nb_u_nodes; ++i) {\n\t\tfor (int j = 0; j < nb_u_nodes; ++j) {\n\t\t\tK_u_u(i, j) = evaluate_kernel(u.row(i), u.row(j));\n\t\t\tif (i == j)\n\t\t\t\tK_u_u(i, j) += K_u_u_nugget;\n\t\t}\n\t}\n\tLLTofK_u_u.compute(K_u_u);\n}\n\n void FullyIndependentTrainingConditional::compute_Qff(const MatrixXd& K_f_u, VectorXd& diag_Q_f_f) {\n\tint nb_u_nodes = u.rows();\n\tMatrixXd K_u_u_u_f = LLTofK_u_u.solve(K_u_f);\n\n\tdiag_Q_f_f.resize(nb_gp_nodes);\n\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\tdiag_Q_f_f(i) = 0.0;\n\t\tfor (int j = 0; j < nb_u_nodes; ++j) {\n\t\t\tdiag_Q_f_f(i) += (K_f_u(i, j) * K_u_u_u_f(j, i));\n\t\t}\n\t}\n}\n\nvoid FullyIndependentTrainingConditional::compute_Kff(VectorXd& diag_K_f_f) {\n\tdiag_K_f_f.resize(nb_gp_nodes);\n\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\tdiag_K_f_f(i) = evaluate_kernel(gp_nodes_eigen.row(i),\n\t\t\t\tgp_nodes_eigen.row(i));\n\t}\n}\n\nvoid FullyIndependentTrainingConditional::compute_diff_Kff_Qff(const VectorXd& diag_K_f_f,\n\t\tconst VectorXd& diag_Q_f_f, VectorXd& diff_Kff_Qff) {\n\tdiff_Kff_Qff.resize(nb_gp_nodes);\n\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\tdiff_Kff_Qff(i) = (diag_K_f_f(i) - diag_Q_f_f(i));\n\t}\n}\n\nvoid FullyIndependentTrainingConditional::compute_Lambda(const VectorXd& diff_Kff_Qff, const std::vector<double>& noise) {\n\tLambda.resize(nb_gp_nodes);\n\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\tLambda(i) = (diff_Kff_Qff(i) + pow(noise.at(i) / 2e0 + noise_regularization, 2e0));\n\t}\n}\n\nvoid FullyIndependentTrainingConditional::compute_Lambda_times_Kfu(const MatrixXd& K_f_u, MatrixXd& Lambda_K_f_u) {\n\tint nb_u_nodes = u.rows();\n\tLambda_K_f_u.resize(nb_gp_nodes, nb_u_nodes);\n\tfor (int i = 0; i < nb_gp_nodes; i++) {\n\t\tfor (int j = 0; j < nb_u_nodes; j++) {\n\t\t\tLambda_K_f_u(i, j) = ((1.0 / Lambda(i)) * K_f_u(i, j));\n\t\t}\n\t}\n}\n\nvoid FullyIndependentTrainingConditional::compute_KufLambdaKfu(const MatrixXd& Lambda_K_f_u, MatrixXd& K_u_f_Lambda_f_u) {\n\tint nb_u_nodes = u.rows();\n\tK_u_f_Lambda_f_u.resize(nb_u_nodes, nb_u_nodes);\n\tK_u_f_Lambda_f_u = K_u_f * Lambda_K_f_u;\n}\n\nvoid FullyIndependentTrainingConditional::compute_LambdaInvF(VectorXd& LambdaInv_f) {\n\tLambdaInv_f.resize(nb_gp_nodes);\n\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\tLambdaInv_f(i) = 1.0 / Lambda(i) * scaled_function_values[i];\n\t}\n}\n\nvoid FullyIndependentTrainingConditional::compute_LambdaDot(const MatrixXd& Kffdot,\n                                    const MatrixXd& Kufdot,\n                                    const MatrixXd& Kfudot,\n                                    const MatrixXd& Kuudot,\n                                    VectorXd& LambdaDot){\n\tLambdaDot.resize(nb_gp_nodes);\n\tLambdaDot.setZero();\n\tMatrixXd KfudotKuinvKuf = Kfudot * LLTofK_u_u.solve(K_u_f);\n\tMatrixXd K_f_u = K_u_f.transpose();\n\t//MatrixXd KfuKuinvKufdot = K_f_u * LLTofK_u_u.solve(Kufdot);\n\tMatrixXd KfuKuinfKudotKuinvKuf = K_f_u*(LLTofK_u_u.solve(Kuudot*(LLTofK_u_u.solve(K_u_f))));\n\n\tfor(int i = 0; i < nb_gp_nodes; ++i){\n\t\tLambdaDot(i) = Kffdot(i,i) - 2*KfudotKuinvKuf(i,i) + KfuKuinfKudotKuinvKuf(i,i);// - KfuKuinvKufdot(i,i);\n\t}\n\n}\n\nvoid FullyIndependentTrainingConditional::compute_GammaDotDoubleBar(const MatrixXd& Kffdot,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst MatrixXd& Kufdot,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst MatrixXd& Kfudot,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst MatrixXd& Kuudot,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tVectorXd& GammaRes){\n\tGammaRes.resize(nb_gp_nodes);\n\tGammaRes.setZero();\n\tMatrixXd KfudotKuinvKuf = Kfudot * LLTofK_u_u.solve(K_u_f);\n\tMatrixXd K_f_u = K_u_f.transpose();\n\tMatrixXd KfuKuinvKufdot = K_f_u * LLTofK_u_u.solve(Kufdot);\n\tMatrixXd KfuKuinfKudotKuinvKuf = K_f_u*(LLTofK_u_u.solve(Kuudot*(LLTofK_u_u.solve(K_u_f))));\n\t\n\tdouble diag_ii;\n\tfor(int i = 0; i < nb_gp_nodes; ++i){\n\t\tdiag_ii = Kffdot(i,i) - KfudotKuinvKuf(i,i) + KfuKuinfKudotKuinvKuf(i,i) - KfuKuinvKufdot(i,i);\n\t\tGammaRes(i) = 1/Lambda(i) * diag_ii;\n\t}\n\n}\n\nbool FullyIndependentTrainingConditional::test_for_parameter_estimation(const int& nb_values,\n                                                const int& update_interval_length,\n                                                const int& next_update,\n                                                const std::vector<int>& update_at_evaluations){\n\n  bool do_parameter_estimation = GaussianProcess::test_for_parameter_estimation(nb_values, update_interval_length, next_update, update_at_evaluations);\n  if (do_parameter_estimation){\n  \tstd::cout << \"Regular update step.\" << std::endl;\n  \treturn do_parameter_estimation;\n  } \n\n  //check if induced points are still in bounds;\n  IOFormat HeavyFmt(FullPrecision, 0, \", \", \";\\n\", \"\", \"\", \"[\", \"]\");\n  double dist = 0.0;\n  const double constraint_ball_radius_squared = constraint_ball_radius*constraint_ball_radius;\n  for(int i = 0; i < u.rows(); ++i){\n  \tdist = 0.0;\n  \tfor(int j = 0; j < u.cols(); ++j){\n  \t\tdist += (u(i,j)-constraint_ball_center(j))*(u(i,j)-constraint_ball_center(j));\n  \t}\n  \tdist = sqrt(dist);\n\tif(dist > (constraint_ball_radius*1.000001)){\n  \t\tstd::cout << \"Induced point out of bounds! Index: \" << i << \" Radius: \" << constraint_ball_radius << \" Dist: \" << dist << std::endl;\n  \t\tfor(int j = 0; j < u.cols(); ++j){\n  \t\t\tstd::cout << \"u: \" << u(i, j) << \" |c: \" << constraint_ball_center(j) << std::endl;\n  \t\t}\n  \t\tdo_parameter_estimation = true;\n  \t\treturn do_parameter_estimation;\n  \t}\n  }\n  do_parameter_estimation = false;\n\n  return do_parameter_estimation;\n}\n\n//--------------------------------------------------------------------------------\nvoid FullyIndependentTrainingConditional::build(\n\t\tstd::vector<std::vector<double> > const &nodes,\n\t\tstd::vector<double> const &values, std::vector<double> const &noise) {\n\n\tint nb_u_nodes = u.rows();\n\n\tif (nb_u_nodes > 0) {\n\t\tstd::cout << \"FITC build with [\" << nodes.size() << \",\" << nb_u_nodes\n\t\t\t<< \"]\" << std::endl;\n\t\tstd::cout << \"With Parameters: \" << std::endl;\n\t    for ( int i = 0; i < dim+1; ++i )\n\t      std::cout << \"gp_param = \" << gp_parameters[i] << std::endl;\n\t    std::cout << std::endl;\n\t\tnb_gp_nodes = nodes.size();\n\t\tgp_nodes.clear();\n\t\tgp_noise.clear();\n\t\tgp_nodes_eigen.resize(nb_gp_nodes, dim);\n\t\tgp_noise_eigen.resize(nb_gp_nodes);\n\t\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\t\tgp_nodes.push_back(nodes.at(i));\n\t\t\tgp_noise.push_back(noise.at(i));\n\t\t\tfor(int j = 0; j < dim; ++j){\n\t\t\t\tgp_nodes_eigen(i,j) = nodes[i][j];\t\n\t\t\t}\n\t\t\tgp_noise_eigen(i) = noise[i];\n\t\t}\n\n\t\t//Set up matrix K_u_f and K_f_u\n\t\tcompute_Kuf_and_Kuu();\n\t\tMatrixXd K_f_u = K_u_f.transpose();\n\n\t\tVectorXd diag_Q_f_f;\n\t\tcompute_Qff(K_f_u, diag_Q_f_f);\n\n\t\tVectorXd diag_K_f_f;\n\t\tcompute_Kff(diag_K_f_f);\n\n\t\tVectorXd diff_Kff_Qff; //this is different for FITC, DTC, SoR\n\t\tcompute_diff_Kff_Qff(diag_K_f_f, diag_Q_f_f, diff_Kff_Qff);\n\n\t\tcompute_Lambda(diff_Kff_Qff, noise);\n\n\t\tMatrixXd Lambda_K_f_u;\n\t\tcompute_Lambda_times_Kfu(K_f_u, Lambda_K_f_u);\n\n\t\tMatrixXd K_u_f_Lambda_f_u;\n\t\tcompute_KufLambdaKfu(Lambda_K_f_u, K_u_f_Lambda_f_u);\n\n\t\tL_eigen.compute(K_u_u + K_u_f_Lambda_f_u);\n\n\t\tscaled_function_values.clear();\n\t\tscaled_function_values.resize(nb_gp_nodes);\n\t\tfor (int i = 0; i < nb_gp_nodes; i++) {\n\t\t\tscaled_function_values.at(i) = values.at(i);\n\t\t}\n\n\t\tVectorXd LambdaInv_f;\n\t\tcompute_LambdaInvF(LambdaInv_f);\n\n\t\tVectorXd alpha_eigen_rhs = K_u_f * LambdaInv_f;\n\n\t\t//Solve Sigma_not_inv^(-1)*alpha\n\t\talpha_eigen = L_eigen.solve(alpha_eigen_rhs);\n\n\t} else {\n\t\tGaussianProcess::build(nodes, values, noise);\n\t}\n\treturn;\n}\n\n//--------------------------------------------------------------------------------\nvoid FullyIndependentTrainingConditional::update(std::vector<double> const &x,\n\t\tdouble &value, double &noise) {\n\n\tint nb_u_nodes = u.rows();\n\tif (nb_u_nodes > 0) {\n\t\tstd::cout << \"FITC update [\" << gp_nodes.size()+1 << \",\" << nb_u_nodes <<\"]\" << std::endl;\n\t\t//std::cout << \"#Update\" << std::endl;\n\t\tstd::vector<std::vector<double> > temp_nodes;\n\t\ttemp_nodes.resize(gp_nodes.size());\n\t\tstd::vector<double> temp_values;\n\t\tstd::vector<double> temp_noise;\n\t\tfor (int i = 0; i < gp_nodes.size(); ++i) {\n\t\t\tfor (int j = 0; j < gp_nodes.at(i).size(); ++j) {\n\t\t\t\ttemp_nodes.at(i).push_back(gp_nodes.at(i).at(j));\n\t\t\t}\n\t\t\ttemp_values.push_back(scaled_function_values.at(i));\n\t\t\ttemp_noise.push_back(gp_noise.at(i));\n\t\t}\n\t\ttemp_nodes.push_back(x);\n\t\ttemp_noise.push_back(noise);\n\t\ttemp_values.push_back(value);\n\t\t//  scaled_function_values.push_back ( ( value -  min_function_value ) /\n\t\t//                                     ( 5e-1*( max_function_value-min_function_value ) ) - 1e0 );\n\n\t\tthis->build(temp_nodes, temp_values, temp_noise);\n\t} else {\n\t\tGaussianProcess::update(x, value, noise);\n\t}\n\treturn;\n}\n//--------------------------------------------------------------------------------\n\nvoid FullyIndependentTrainingConditional::evaluate(std::vector<double> const &x,\n\t\tdouble &mean, double &variance) {\n\tint nb_u_nodes = u.rows();\n\tif (nb_u_nodes > 0) {\n\t\t//std::cout << \"FITC evalute [\" << gp_nodes_eigen.rows() << \",\" << nb_u_nodes <<\"]\" << std::endl;\n\t\tVectorXd x_eigen;\n\t\tx_eigen.resize(x.size());\n\t\tfor(int i = 0; i < x.size(); ++i){\n\t\t\tx_eigen(i) = x[i];\n\t\t}\n\t\tK0_eigen.resize(nb_u_nodes);\n\t\tfor (int i = 0; i < nb_u_nodes; i++) {\n\t\t\tK0_eigen(i) = evaluate_kernel(x_eigen, u.row(i));\n\t\t}\n\n//\t\tstd::cout << \"alpha= (K_u_u + K_u_f Lambda_inv K_f_u)\\(K_u_f*LambdaInv*f):\" << std::endl;\n//\t\tVectorOperations::print_vector(alpha);\n\t\tmean = K0_eigen.dot(alpha_eigen);\n//\t\tstd::cout << \"mean:\" << mean << std::endl;\n\t\t//std::cout << \"Mean: \" << mean << std::endl;\n\n\t\tdouble variance_term3 = K0_eigen.dot(L_eigen.solve(K0_eigen));\n\n\t\tdouble variance_term2 = K0_eigen.dot(LLTofK_u_u.solve(K0_eigen));\n\t\t/*\n\t\t std::cout << \"Variance: \" << variance << std::endl;\n\t\t std::cout << \"######################################\" << std::endl;\n\t\t evaluate_counter++;\n\t\t assert(evaluate_counter<20*3);\n//\t\t */\n\t\t//exit(-1);\n\n//\t\tstd::cout << \"K**:\" << evaluate_kernel(x,x) << std::endl;\n\t\tvariance = evaluate_kernel(x_eigen,x_eigen)-variance_term2+variance_term3;\n\t\t //std::cout << \"FITC evalute [\" << gp_nodes_eigen.rows() << \",\" << nb_u_nodes <<\"] mean,variance \" << mean << \", \" << variance << std::endl;\n//\t\tstd::cout << \"variance:\" << variance << std::endl;\n\t} else {\n\t\tGaussianProcess::evaluate(x, mean, variance);\n\t}\n\treturn;\n\n}\n\nvoid FullyIndependentTrainingConditional::get_induced_nodes(\n\t\tstd::vector<std::vector<double> > &induced_nodes) const {\n\tinduced_nodes.resize(u.rows());\n\tfor (int i = 0; i < u.rows(); ++i) {\n\t\tfor (int j = 0; j < dim; ++j){\n\t\t\tinduced_nodes[i].push_back(u(i, j));\n\t\t}\n\t}\n\n\treturn;\n}\n\nvoid FullyIndependentTrainingConditional::sample_u(const int& nb_u_nodes) {\n\n\tu.resize(nb_u_nodes, dim);\n\n\tu.setConstant(-1);\n\tstd::vector<int> u_idx_left_over;\n\tstd::vector<int> u_idx_from_active;\n\t//Set distribution for sampling the indices for the u samples\n\tstd::random_device rd;\n\tint random_seed = rd();//1;////rd();\n\tstd::mt19937 random_generator(random_seed);\n\tstd::vector<double> nodes_weights_vector;\n\n\tu.resize(nb_u_nodes, dim);\n\tstd::normal_distribution<double> dis_radius(0.0, 1.0);\n\tstd::uniform_real_distribution<double> dis_unit_radius(0.0, 1.0);\n\tstd::uniform_real_distribution<double> dis_trust_radius(-constraint_ball_radius, constraint_ball_radius);\n\tVectorXd cur_u(dim);\n\tdouble cur_U_i, radius, rand_radius, n_minus_1_angle;\n\tbool not_found_point = true;\n\tfor(int i = 0; i < nb_u_nodes; ++i){\n\t\tnot_found_point = true;\n\t\tradius = -1.0;\n\t\twhile(not_found_point){\n\t\t\tnot_found_point = true;\n\t\t\tradius = 0.0;\n\t\t\tfor(int j = 0; j < dim; ++j){\n\t\t\t\tcur_u(j) = dis_trust_radius(random_generator);\n\t\t\t\tradius += cur_u(j) *cur_u(j);\n\t\t\t}\n\t\t\tradius = sqrt(radius);\n\t\t\tif(radius < constraint_ball_radius){\n\t\t\t\tfor(int j = 0; j < dim; ++j){\n\t\t\t\t\tu(i, j) = cur_u(j) + constraint_ball_center(j);\n\t\t\t\t}\n\t\t\t\tnot_found_point = false;\n\t\t\t}\n\t\t}\n\t}\n\treturn;\n}\n\nvoid FullyIndependentTrainingConditional::clear_u(){\n\tu.resize(0,0);\n}\n\nvoid FullyIndependentTrainingConditional::copy_data_to_members( std::vector< std::vector<double> > const &nodes,\n                                                  std::vector<double> const &values,\n                                                  std::vector<double> const &noise){\n  nb_gp_nodes = nodes.size();\n  gp_nodes.clear();\n  gp_noise.clear();\n\tgp_nodes_eigen.resize(nb_gp_nodes, dim);\n\tgp_noise_eigen.resize(nb_gp_nodes);\n  for ( int i = 0; i < nb_gp_nodes; ++i ) {\n    gp_nodes.push_back ( nodes.at(i) );\n    gp_noise.push_back ( noise.at(i) );\n\tfor(int j = 0; j < dim; ++j){\n\t\tgp_nodes_eigen(i,j) = nodes[i][j];\t\n\t}\n\tgp_noise_eigen(i) = noise[i];\n}\n\n//  auto minmax = std::minmax_element(values.begin(), values.end());\n//  min_function_value = values.at((minmax.first - values.begin()));\n//  max_function_value = values.at((minmax.second - values.begin()));\n\n  L.clear();\n  L.resize( nb_gp_nodes );\n  for ( int i = 0; i < nb_gp_nodes; ++i)\n    L.at(i).resize( i+1 );\n\n  scaled_function_values.resize(nb_gp_nodes);\n  scaled_function_values_eigen.resize(nb_gp_nodes);\n  for ( int i = 0; i < nb_gp_nodes; ++i) {\n    scaled_function_values.at(i) = values.at(i);\n    scaled_function_values_eigen(i) = values.at(i);\n//    scaled_function_values.at(i) = values.at(i) - min_function_value;\n//    scaled_function_values.at(i) /= 5e-1*( max_function_value-min_function_value );\n//    scaled_function_values.at(i) -= 1e0;\n  }\n\n}\n\nvoid FullyIndependentTrainingConditional::set_optimizer(std::vector<double> const &values, nlopt::opt*& local_opt, nlopt::opt*& global_opt){\n\n  optimize_global = true;\n  optimize_local = false;\n\n  int dimp1 = gp_parameters_hp.size();\n\n  lb.resize(dimp1);\n  ub.resize(dimp1);\n  \n  int offset;\n  if(dimp1==1 + dim){\n  \t\tauto minmax = std::minmax_element(values.begin(), values.end());\n\t    min_function_value = values.at((minmax.first - values.begin()));\n\t    max_function_value = fabs(values.at((minmax.second - values.begin())));\n\t    if ( fabs(min_function_value) > max_function_value )\n\t    max_function_value = fabs( min_function_value );\n\t  \t\n\t\t  lb[0] = 1e-3; \n\t\t  ub[0] = 1e3;\n\t\t  lb[0] = max_function_value - 1e2;\n\t\t  if ( lb[0] < 1e-3 ) lb[0] = 1e-3;\n\t\t  ub[0] = max_function_value + 1e2; \n\t\t  if ( ub[0] > 1e3 ) ub[0] = 1e3;\n\t\t  if ( ub[0] <= lb[0]) lb[0] = 1e-3;\n\t\t//if (ub[0] < 1.0) ub[0] = 1.0;\n\t\tdouble delta_threshold = *delta;\n\t\tif (delta_threshold < 1e-2) delta_threshold = 1e-2;\n\t\tfor (int i = 0; i < dim; ++i) {\n\t\t    lb[i+1] = 1e-2 * delta_threshold; // 1e1\n\t\t    ub[i+1] = 2.0 * delta_threshold; // 1e2\n\t\t}\n\t  \tfor (int i = 0; i < dim+1; ++i) {\n  \t\t  if ( gp_parameters_hp[i] <= lb[i] ) {\n  \t\t\tstd::cout << \"LS Too small: \" << gp_parameters_hp[i] << \" for \" << lb[i] << std::endl;\n      \t\tgp_parameters_hp[i] = 1.0001 * lb[i];\n      \t\t}\n\t      if ( gp_parameters_hp[i] >= ub[i] ) {\n\t  \t\t\tstd::cout << \"LS Too big: \" << gp_parameters_hp[i] << \" for \" << ub[i] << std::endl;\n\t      \t\tgp_parameters_hp[i] = 0.9999 * ub[i];\n\t      }\n\t      if ( gp_parameters_hp[i] <= lb[i] ||  gp_parameters_hp[i] >= ub[i]){\n\t\t\tstd::cout << \"LS still in between: \" << gp_parameters_hp[i];\n\t      \tgp_parameters_hp[i] = lb[i] + (ub[i]-lb[i])/0.5;\n\t      \tstd::cout << \"LS fixed: \"<< gp_parameters_hp[i] << std::endl;\n        \t}\n        }\n\t  \t\n  }else{\n\t  if(gp_parameters_hp.size() > u.rows()*dim){ //optimizing also over lengthscale and sigma_f\n\t  \tauto minmax = std::minmax_element(values.begin(), values.end());\n\t    min_function_value = values.at((minmax.first - values.begin()));\n\t    max_function_value = fabs(values.at((minmax.second - values.begin())));\n\t    if ( fabs(min_function_value) > max_function_value )\n\t    max_function_value = fabs( min_function_value );\n\t  \tlb[0] = 1e-3; \n\t\t  ub[0] = 1e3;\n\t\t  lb[0] = max_function_value - 1e2;\n\t\t  if ( lb[0] < 1e-3 ) lb[0] = 1e-3;\n\t\t  ub[0] = max_function_value + 1e2; \n\t\t  if ( ub[0] > 1e3 ) ub[0] = 1e3;\n\t\t  if ( ub[0] <= lb[0]) lb[0] = 1e-3;\n\t\t//if (ub[0] < 1.0) ub[0] = 1.0;\n\t\tdouble delta_threshold = *delta;\n\t\tif (delta_threshold < 1e-2) delta_threshold = 1e-2;\n\t\tfor (int i = 0; i < dim; ++i) {\n\t\t    lb[i+1] = 1e-2 * delta_threshold; // 1e1\n\t\t    ub[i+1] = 2.0 * delta_threshold; // 1e2\n\t\t}\n\t    offset = 1+dim;\n\t  }else{\n\t  \toffset = 0;\n\t  }\n\t  //Set box constraints such that the constraint ball is inside\n\t  std::vector<double> lb_u(dim);\n\t  std::vector<double> ub_u(dim);\n\t  for (int i = 0; i < dim; ++i) {\n\t      lb_u[i] = constraint_ball_center[i] - 1.5*constraint_ball_radius;\n\t      ub_u[i] = constraint_ball_center[i] + 1.5*constraint_ball_radius;\n\t  }\n\t  for (int i = 0; i < dim; ++i) {\n\t\t  for(int j = offset + i*u.rows(); j < offset + (i+1)*u.rows(); ++j){\n\t          lb[j] = lb_u[i];\n\t          ub[j] = ub_u[i];\n\t\t  }\n\t  }\n\n\t  \n\t  if(gp_parameters_hp.size() > u.rows()*dim){//optimizing also over lengthscale and sigma_f\n\t\t  if (gp_parameters_hp[0] < 0e0) {\n\t\t  \tstd::cout << \"In here: \" << gp_parameters_hp[0] << std::endl;\n\t\t    gp_parameters_hp[0] = max_function_value;\n\t\t    for (int i = 1; i < dim+1; ++i) {\n\t\t      gp_parameters_hp[i] = (lb[i]*5e-1 + 5e-1*ub[i]);\n\t\t    }\n\t\t  } else {\n\t\t    for (int i = 0; i < dim+1; ++i) {\n\t\t      if ( gp_parameters_hp[i] <= lb[i] ) {\n\t\t  \t\t\tstd::cout << \"2Too small: \" << gp_parameters_hp[i] << std::endl;\n\t\t      \t\tgp_parameters_hp[i] = 1.0001 * lb[i];\n\t\t      \t}\n\t\t      if ( gp_parameters_hp[i] >= ub[i] ) {\n\t\t  \t\t\tstd::cout << \"2Too big: \" << gp_parameters_hp[i] << std::endl;\n\t\t      \t\tgp_parameters_hp[i] = 0.9999 * ub[i];\n\t\t      }\n\t\t      if ( gp_parameters_hp[i] <= lb[i] ||  gp_parameters_hp[i] >= ub[i]){\n\t\t\t\tstd::cout << \"2still in between: \" << gp_parameters_hp[i];\n\t\t      \tgp_parameters_hp[i] = lb[i] + (ub[i]-lb[i])/0.5;\n\t\t      \tstd::cout << \"2fixed: \"<< gp_parameters_hp[i] << std::endl;\n\t\t      }\n\t\t    }\n\t\t  }\n\t\t}\n\t\t\n\tfor (int i = offset; i < dimp1; ++i) {\n      if ( gp_parameters_hp[i] <= lb[i] ) {\n  \t\t\tstd::cout << \"U Too small: \" << gp_parameters_hp[i] << std::endl;\n      \t\tgp_parameters_hp[i] = 1.0001 * lb[i];\n      \t}\n      if ( gp_parameters_hp[i] >= ub[i] ) {\n  \t\t\tstd::cout << \"U Too big: \" << gp_parameters_hp[i] << std::endl;\n      \t\tgp_parameters_hp[i] = 0.9999 * ub[i];\n      }\n      if ( gp_parameters_hp[i] <= lb[i] ||  gp_parameters_hp[i] >= ub[i]){\n\t\tstd::cout << \"U still in between: \" << gp_parameters_hp[i];\n      \tgp_parameters_hp[i] = lb[i] + (ub[i]-lb[i])/0.5;\n      \tstd::cout << \"U fixed: \"<< gp_parameters_hp[i] << std::endl;\n      }\n    \t}\n\t}\n  \n\n  local_opt = new nlopt::opt(nlopt::LD_MMA, dimp1);\n  global_opt = new nlopt::opt(nlopt::GN_ISRES, dimp1);\n\n  global_opt->set_lower_bounds( lb );\n  global_opt->set_upper_bounds( ub );\n  global_opt->set_maxtime(1.0);\n  //global_opt->set_maxeval(10000);\n\n  local_opt->set_lower_bounds( lb );\n  local_opt->set_upper_bounds( ub );\n  local_opt->set_maxtime(60.0);\n  local_opt->set_maxeval(1000);\n}\n\nvoid FullyIndependentTrainingConditional::run_optimizer(std::vector<double> const &values){\n\tdouble optval;\n\n  int exitflag;\n\n  nlopt::opt* local_opt;\n  nlopt::opt* global_opt;\n\n  set_optimizer(values, local_opt, global_opt);\n\n  int dimp1 = gp_parameters_hp.size();\n\n  std::vector<double> tol(dimp1);\n  for(int i = 0; i < dimp1; ++i){\n  \ttol[i] = 0.0;\n  }\n  if (optimize_global){\n  \t  print = 0;\n \t  std::cout << \"Global optimization\" << std::endl;\n\t  exitflag=-20;\n\t  global_opt->add_inequality_mconstraint(trust_region_constraint, gp_pointer, tol);\n\t  global_opt->set_min_objective( parameter_estimation_objective, gp_pointer);\n\t  exitflag = global_opt->optimize(gp_parameters_hp, optval);\n\n\t  std::cout << \"exitflag = \"<< exitflag<<std::endl;\n  \t  std::cout << \"Function calls: \" << print << std::endl;\n\t  std::cout << \"OPTVAL .... \" << optval << std::endl;\n\t  //for ( int i = 0; i < 1+dim; ++i )\n\t    //std::cout << \"gp_param = \" << gp_parameters_hp[i] << std::endl;\n\t  //std::cout << std::endl;\n  }\n  if (optimize_local){\n  \t  print = 0;\n  \t  std::cout << \"Local optimization\" << std::endl;\n\t  exitflag=-20;\n\t  //try {\n\t  local_opt->add_inequality_mconstraint(trust_region_constraint, gp_pointer, tol);\n\t  local_opt->set_min_objective( parameter_estimation_objective_w_gradients, gp_pointer);\n\t  exitflag = local_opt->optimize(gp_parameters_hp, optval);\n\n\t  std::cout << \"exitflag = \"<< exitflag<<std::endl;\n  \t  std::cout << \"Function calls: \" << print << std::endl;\n\t  std::cout << \"OPTVAL .... \" << optval << std::endl;\n\t  //for ( int i = 0; i < 1+dim; ++i )\n\t    //std::cout << \"gp_param = \" << gp_parameters_hp[i] << std::endl;\n\t  //std::cout << std::endl;\n  }\n  \n  delete local_opt;\n  delete global_opt;\n\n  return;\n}\n\nvoid FullyIndependentTrainingConditional::update_induced_points(){\n  int u_counter;\n  int offset = 1+dim;\n  for (int i = 0; i < dim; ++i) {\n  \t  u_counter = 0;\n  \t  for(int j = offset + i*u.rows(); j < offset + (i+1)*u.rows(); ++j){\n            u(u_counter,i) = gp_parameters[j];\n            u_counter++;\n  \t  }\n  }\n}\n\nvoid FullyIndependentTrainingConditional::estimate_hyper_parameters ( std::vector< std::vector<double> > const &nodes,\n                                                  std::vector<double> const &values,\n                                                  std::vector<double> const &noise ){\n\tthis->estimate_hyper_parameters_ls_only(nodes, values, noise);\n}\n\nvoid FullyIndependentTrainingConditional::estimate_hyper_parameters_all ( std::vector< std::vector<double> > const &nodes,\n                                                  std::vector<double> const &values,\n                                                  std::vector<double> const &noise )\n{\n  if (u.rows() > 0) {\t\n\t  std::cout << \"FITC Estimator\" << std::endl;\n\t  copy_data_to_members(nodes, values, noise);\n\n\t  gp_pointer = this;\n\n\t  sample_u(u.rows());\n\n\t  set_hyperparameters();\n\n\t  run_optimizer(values);\n\n\t  copy_hyperparameters();\n\n\t  for ( int i = 0; i < 1+dim; ++i )\n\t    std::cout << \"gp_param = \" << gp_parameters[i] << std::endl;\n  }else{\n\t\tGaussianProcess::estimate_hyper_parameters(nodes, values, noise);\n  }\n\n  return;\n}\n\nvoid FullyIndependentTrainingConditional::estimate_hyper_parameters_induced_only ( std::vector< std::vector<double> > const &nodes,\n                                                  std::vector<double> const &values,\n                                                  std::vector<double> const &noise )\n{\n  if (u.rows() > 0) {\t\n\t  std::cout << \"FITC Estimator\" << std::endl;\n\t  copy_data_to_members(nodes, values, noise);\n\n\t  gp_pointer = this;\n\n\t  sample_u(u.rows());\n\n\t  set_hyperparameters_induced_only();\n\n\t  run_optimizer(values);\n\n\t  copy_hyperparameters();\n\n\t  for ( int i = 0; i < 1+dim; ++i )\n\t    std::cout << \"gp_param = \" << gp_parameters[i] << std::endl;\n\n  }else{\n\t\tGaussianProcess::estimate_hyper_parameters(nodes, values, noise);\n  }\n\n  return;\n}\nvoid FullyIndependentTrainingConditional::estimate_hyper_parameters_ls_only ( std::vector< std::vector<double> > const &nodes,\n                                                      std::vector<double> const &values,\n                                                      std::vector<double> const &noise ){\n  if (u.rows() > 0) {\t\n\t  std::cout << \"FITC Estimator\" << std::endl;\n\t  copy_data_to_members(nodes, values, noise);\n\n\t  gp_pointer = this;\n\n\t  sample_u(u.rows());\n\n\t  set_hyperparameters_ls_only();\n\n\t  run_optimizer(values);\n\n\t  copy_hyperparameters();\n\n\t  for ( int i = 0; i < 1+dim; ++i )\n\t    std::cout << \"gp_param = \" << gp_parameters[i] << std::endl;\n\n  }else{\n\t\tGaussianProcess::estimate_hyper_parameters(nodes, values, noise);\n  }\n\n  return;\n}\n//--------------------------------------------------------------------------------\n\nvoid FullyIndependentTrainingConditional::set_hyperparameters(){\n  int dimp1 = 1+dim+u.rows()*dim;\t\n  gp_parameters_hp.resize(dimp1);\n  int u_counter;\n  int offset = dim + 1;\n  for (int i = 0; i < dim + 1; ++i){\n  \tgp_parameters_hp[i] = gp_parameters[i];\n  }\n  for (int i = 0; i < dim; ++i) {\n  \t  u_counter = 0;\n  \t  for(int j = offset + i*u.rows(); j < offset + (i+1)*u.rows(); ++j){\n            gp_parameters_hp[j] = u(u_counter,i);    \t\t\n            u_counter++;\n  \t  }\n  }\n  return;\n}\n\nvoid FullyIndependentTrainingConditional::set_hyperparameters_ls_only(){\n  int dimp1 = dim+1;\t\n  gp_parameters_hp.resize(dimp1);\n  for (int i = 0; i < dimp1; ++i){\n  \tgp_parameters_hp[i] = gp_parameters[i];\n  }\n  return;\n}\n\nvoid FullyIndependentTrainingConditional::set_hyperparameters_induced_only(){\n  int dimp1 = u.rows()*dim;\t\n  gp_parameters_hp.resize(dimp1);\n  int u_counter;\n  for (int i = 0; i < dim; ++i) {\n  \t  u_counter = 0;\n  \t  for(int j = i*u.rows(); j < (i+1)*u.rows(); ++j){\n            gp_parameters_hp[j] = u(u_counter,i);    \t\t\n            u_counter++;\n  \t  }\n  }\n  return;\n}\n\nvoid FullyIndependentTrainingConditional::copy_hyperparameters(){\n  int dimp1 = gp_parameters_hp.size();\n  int u_counter;\n  int offset;\n  if(gp_parameters_hp.size()==dim+1){\n\tfor (int i = 0; i < dim + 1; ++i){\n  \t  gp_parameters[i] = gp_parameters_hp[i];\n    }\n  }else{\n\t  if(gp_parameters_hp.size() > u.rows()*dim){//optimizing also over lengthscale and sigma_f, copy them back\n\t    for (int i = 0; i < dim + 1; ++i){\n\t  \t  gp_parameters[i] = gp_parameters_hp[i];\n\t    }\n\t    offset = 1+dim;\n\t  }else{\n\t  \toffset = 0;\n\t  }\n\t  for (int i = 0; i < dim; ++i) {\n\t  \t  u_counter = 0;\n\t  \t  for(int j = offset + i*u.rows(); j < offset + (i+1)*u.rows(); ++j){\n\t        u(u_counter,i) = gp_parameters_hp[j];\n\t        u_counter++;\n\t  \t  }\n\t  }\n  }\n  return;\n}\n\n//--------------------------------------------------------------------------------\ndouble FullyIndependentTrainingConditional::parameter_estimation_objective(std::vector<double> const &x,\n                                                       std::vector<double> &grad,\n                                                       void *data)\n{\n  FullyIndependentTrainingConditional *d = reinterpret_cast<FullyIndependentTrainingConditional*>(data);\n  int offset;\n  std::vector<double> local_params(d->dim+1);\n  if(x.size()==1+d->dim){\n  \t  offset = 0;\n  \t  for(int i = 0; i < local_params.size(); ++i){\n\t  \t\tlocal_params[i] = x[i];\n  \t  }\n  }else{\n\t  if(x.size() > d->u.rows()*d->dim){\n\t  \toffset = 1+d->dim;\n\t  \tfor(int i = 0; i < local_params.size(); ++i){\n\t  \t\tlocal_params[i] = x[i];\n\t  \t}\n\t  }else{\n\t  \toffset = 0;\n\t  \tfor(int i = 0; i < local_params.size(); ++i){\n\t  \t\tlocal_params[i] = d->gp_parameters[i];\n\t  \t}\n\t  }\n\t  int u_counter;\n\t  for (int i = 0; i < d->dim; ++i) {\n\t  \t  u_counter = 0;\n\t  \t  for(int j = offset + i*d->u.rows(); j < offset + (i+1)*d->u.rows(); ++j){\n\t            d->u(u_counter,i) = x[j];\n\t            u_counter++;\n\t  \t  }\n\t  }\n  }\n\n  //Compute Kuf, Kuu\n  //Set up matrix K_u_f and K_f_u\n\tint nb_gp_nodes = d->gp_nodes.size();\n\tint nb_u_nodes = d->u.rows();\n\td->K_u_f.resize(nb_u_nodes, nb_gp_nodes);\n\t//std::cout << d->u.rows() << \" \" << nb_gp_nodes << \" \" << d->gp_nodes_eigen.rows() << std::endl;\n\tfor (int i = 0; i < nb_u_nodes; ++i) {\n\t\tfor (int j = 0; j < nb_gp_nodes; ++j) {\n\t\t\td->K_u_f(i,j) = d->evaluate_kernel(d->u.row(i), d->gp_nodes_eigen.row(j), local_params);\n\t\t}\n\t}\n\tMatrixXd K_f_u = d->K_u_f.transpose();\n\t//std::cout << \"Kuf\\n\" << d->K_u_f << std::endl;\n\n\t//Set up matrix K_u_u\n\td->K_u_u.resize(nb_u_nodes, nb_u_nodes);\n\tfor (int i = 0; i < nb_u_nodes; ++i) {\n\t\tfor (int j = 0; j < nb_u_nodes; ++j) {\n\t\t\td->K_u_u(i,j) = d->evaluate_kernel(d->u.row(i), d->u.row(j), local_params);\n\t\t\tif(i==j)\n\t\t\t\td->K_u_u(i,j) += d->Kuu_opt_nugget;\n\t\t}\n\t}\n\t//std::cout << \"Kuu\\n\" << d->K_u_u << std::endl;\n\td->LLTofK_u_u.compute(d->K_u_u);\n\tMatrixXd K_u_u_u_f = d->LLTofK_u_u.solve(d->K_u_f);\n\n\tVectorXd diag_Q_f_f;\n\tdiag_Q_f_f.resize(nb_gp_nodes);\n\n\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\tdiag_Q_f_f(i) = 0.0;\n\t\tfor (int j = 0; j < nb_u_nodes; ++j) {\n\t\t\tdiag_Q_f_f(i) += (K_f_u(i,j) * K_u_u_u_f(j,i));\n\t\t}\n\t}\n\tVectorXd diag_K_f_f;\n\tdiag_K_f_f.resize(nb_gp_nodes);\n\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\tdiag_K_f_f(i) = d->evaluate_kernel(d->gp_nodes_eigen.row(i),\n\t\t\t\t\t\t\t\t\t d->gp_nodes_eigen.row(i), local_params);\n\t}\n\n\td->Lambda.resize(nb_gp_nodes);\n\t//std::cout << \"noise\\n\" << std::endl;\n\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\td->Lambda(i) = (diag_K_f_f(i) - diag_Q_f_f(i) + pow( d->gp_noise.at(i) / 2e0 + d->noise_regularization, 2e0 ));\n\t}\n\t//std::cout << std::endl;\n\n\tMatrixXd Lambda_K_f_u;\n\tLambda_K_f_u.resize(nb_gp_nodes, nb_u_nodes);\n\tfor(int i = 0; i < nb_gp_nodes; i++){\n\t\tfor(int j = 0; j < nb_u_nodes; j++){\n\t\t\tLambda_K_f_u(i,j) = ((1.0/(d->Lambda(i) + d->Lambda_opt_nugget)) * K_f_u(i,j));\n\t\t}\n\t}\n\tMatrixXd K_u_f_Lambda_f_u;\n\tK_u_f_Lambda_f_u.resize(nb_u_nodes, nb_u_nodes);\n\tK_u_f_Lambda_f_u = d->K_u_f*Lambda_K_f_u;\n\n\tMatrixXd Sigma = d->K_u_u + K_u_f_Lambda_f_u;\n\tfor (int i = 0; i < nb_u_nodes; ++i) {\n\t\t//Sigma(i,i) += nugget;\n\t}\n\td->L_eigen.compute(Sigma);\n\tdouble L12 = 0.0;//-log(d->K_u_u.determinant());\n\tfor (int i = 0; i < d->u.rows(); ++i){\n\t\tL12 += log(d->LLTofK_u_u.vectorD()(i));\n    \t//std::cout << L1 << \"L11-\" << i << std::endl;\n\t}\n\n\tdouble det_Leigen = 0.0;\n\tfor (int i = 0; i < d->u.rows(); ++i){\n\t\tdet_Leigen += log(d->L_eigen.vectorD()(i));\n    \t//std::cout << d->L_eigen.matrixL()(i,i) << \" \" << log(d->L_eigen.matrixL()(i,i)) << \"det_Leigen-\" << i << std::endl;\n\t}\n\n\tdouble L11 = 0.0;\n    //std::cout << L1 << \"L12 \" << std::endl;\n\tfor (int i = 0; i < d->nb_gp_nodes; ++i){\n\t\tL11 += log(d->Lambda(i));\n\t\t//std::cout << \"Lambda: \" << i << \" \" << d->Lambda(i) <<\" \"<<log(d->Lambda(i)) << std::endl;\n\t}\n    double L1 = 0.0;\n\t//L1 = 0.5*L11 + (2*0.5)*det_Leigen + 0.5*det_LeigenD - (2*0.5)*L12 - 0.5*L12D;\n\tL1 = 0.5*L11 + 0.5*det_Leigen - 0.5*L12;\n\n\tMatrixXd Q_f_f = K_f_u*K_u_u_u_f;\n\tfor(int i = 0; i < nb_gp_nodes; i++){\n\t\tQ_f_f(i,i) += d->Lambda(i)+ d->Qff_opt_nugget;\n\t}\n\tLLT<MatrixXd> LLTofQ_f_f(Q_f_f);\n\tdouble L2 = 0.5*d->scaled_function_values_eigen.dot(LLTofQ_f_f.solve(d->scaled_function_values_eigen));\n  \t\n  \t//std::cout << d->scaled_function_values_eigen << std::endl;\n  double result = L1 + L2;\n \n  if (std::isinf(result) || std::isnan(result)){\n  \tstd::cout << \"Result is inf or nan\" << std::endl;\n  \tstd::cout << \"L11 \" << L11 << \" \" << 'x' << std::endl;\n    std::cout << \"L12 \" << L12 << std::endl; //<< \" \" << log(d->K_u_u.determinant()) << std::endl;\n    std::cout << \"L13 \" << det_Leigen << std::endl;// << \" \" << log(Sigma.determinant()) << std::endl;\n    std::cout << L1 << ' ' << L2 << std::endl;\n  \tresult = std::numeric_limits<double>::infinity();\n  \tif(d->Kuu_opt_nugget < d->nugget_max){\n  \t\td->Kuu_opt_nugget *= 10;\n  \t\td->Lambda_opt_nugget *= 10;\n  \t\td->Qff_opt_nugget *= 10;\n  \t}\n  }else{\n  \tif(d->Kuu_opt_nugget > d->nugget_min){\n  \t\td->Kuu_opt_nugget *= 0.1;\n  \t\td->Lambda_opt_nugget *= 0.1;\n  \t\td->Qff_opt_nugget *= 0.1;\n  \t}\n  }\n  if ((d->print%1000)==0){\n\t  //for ( int i = 0; i < d->dim + 1; ++i )\n\t  //  std::cout << \"gp_param = \" << x[i] << std::endl;\n\t  //for(int j = offset; j < offset + d->u.rows(); ++j)\n\t//\t\tstd::cout << \"gp_param = \" << x[j] <<\",\"<<x[j+ d->u.rows()]<< std::endl;\n  \t\n  \t//std::cout << d->print <<\" Objective: \" << L1 << \" \" << L2 << \" \"<< result<< std::endl;\n   }\n\n  d->print++;\n  return result;\n\n}\n\ndouble FullyIndependentTrainingConditional::parameter_estimation_objective_w_gradients(std::vector<double> const &x,\n                                                       std::vector<double> &grad,\n                                                       void *data)\n{\n\n  FullyIndependentTrainingConditional *d = reinterpret_cast<FullyIndependentTrainingConditional*>(data);\n  int offset;\n  std::vector<double> local_params(d->dim+1);\n  if(x.size()==1+d->dim){\n  \t  offset = 0;\n  \t  for(int i = 0; i < local_params.size(); ++i){\n\t  \t\tlocal_params[i] = x[i];\n  \t  }\n  }else{\n\t  if(x.size() > d->u.rows()*d->dim){\n\t  \toffset = 1+d->dim;\n\t  \tfor(int i = 0; i < local_params.size(); ++i){\n\t  \t\tlocal_params[i] = x[i];\n\t  \t}\n\t  }else{\n\t  \toffset = 0;\n\t  \tfor(int i = 0; i < local_params.size(); ++i){\n\t  \t\tlocal_params[i] = d->gp_parameters[i];\n\t  \t}\n\t  }\n\t  int u_counter;\n\t  for (int i = 0; i < d->dim; ++i) {\n\t  \t  u_counter = 0;\n\t  \t  for(int j = offset + i*d->u.rows(); j < offset + (i+1)*d->u.rows(); ++j){\n\t            d->u(u_counter,i) = x[j];\n\t            u_counter++;\n\t  \t  }\n\t  }\n  }\n\n  //Compute Kuf, Kuu\n  //Set up matrix K_u_f and K_f_u\n\tint nb_gp_nodes = d->gp_nodes.size();\n\tint nb_u_nodes = d->u.rows();\n\td->K_u_f.resize(nb_u_nodes, nb_gp_nodes);\n\tfor (int i = 0; i < nb_u_nodes; ++i) {\n\t\tfor (int j = 0; j < nb_gp_nodes; ++j) {\n\t\t\td->K_u_f(i,j) = d->evaluate_kernel(d->u.row(i), d->gp_nodes_eigen.row(j), local_params);\n\t\t}\n\t}\n\tMatrixXd K_f_u = d->K_u_f.transpose();\n\t//std::cout << \"Kuf\\n\" << d->K_u_f << std::endl;\n\n\t//Set up matrix K_u_u\n\td->K_u_u.resize(nb_u_nodes, nb_u_nodes);\n\tfor (int i = 0; i < nb_u_nodes; ++i) {\n\t\tfor (int j = 0; j < nb_u_nodes; ++j) {\n\t\t\td->K_u_u(i,j) = d->evaluate_kernel(d->u.row(i), d->u.row(j), local_params);\n\t\t\tif(i==j)\n\t\t\t\td->K_u_u(i,j) += d->Kuu_opt_nugget;\n\t\t}\n\t}\n\t//std::cout << \"Kuu\\n\" << d->K_u_u << std::endl;\n\td->LLTofK_u_u.compute(d->K_u_u);\n\tMatrixXd K_u_u_u_f = d->LLTofK_u_u.solve(d->K_u_f);\n\n\tVectorXd diag_Q_f_f;\n\tdiag_Q_f_f.resize(nb_gp_nodes);\n\n\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\tdiag_Q_f_f(i) = 0.0;\n\t\tfor (int j = 0; j < nb_u_nodes; ++j) {\n\t\t\tdiag_Q_f_f(i) += (K_f_u(i,j) * K_u_u_u_f(j,i));\n\t\t}\n\t}\n\tVectorXd diag_K_f_f;\n\tdiag_K_f_f.resize(nb_gp_nodes);\n\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\tdiag_K_f_f(i) = d->evaluate_kernel(d->gp_nodes_eigen.row(i),\n\t\t\t\t\t\t\t\t\t d->gp_nodes_eigen.row(i), local_params);\n\t}\n\t/*std::cout << \"diag_K_f_f\\n\" << diag_K_f_f << std::endl;\n\tstd::cout << \"diag_Q_f_f\\n\" << diag_Q_f_f << std::endl;*/\n\n\td->Lambda.resize(nb_gp_nodes);\n\t//std::cout << \"noise\\n\" << std::endl;\n\tfor (int i = 0; i < nb_gp_nodes; ++i) {\n\t\td->Lambda(i) = (diag_K_f_f(i) - diag_Q_f_f(i) + pow( d->gp_noise.at(i) / 2e0 + d->noise_regularization, 2e0 ));\n\t}\n\t//std::cout << std::endl;\n\n\tMatrixXd Lambda_K_f_u;\n\tLambda_K_f_u.resize(nb_gp_nodes, nb_u_nodes);\n\tfor(int i = 0; i < nb_gp_nodes; i++){\n\t\tfor(int j = 0; j < nb_u_nodes; j++){\n\t\t\tLambda_K_f_u(i,j) = ((1.0/(d->Lambda(i) + d->Lambda_opt_nugget)) * K_f_u(i,j));\n\t\t}\n\t}\n\tMatrixXd K_u_f_Lambda_f_u;\n\tK_u_f_Lambda_f_u.resize(nb_u_nodes, nb_u_nodes);\n\tK_u_f_Lambda_f_u = d->K_u_f*Lambda_K_f_u;\n\n\tMatrixXd Sigma = d->K_u_u + K_u_f_Lambda_f_u;\n\tfor (int i = 0; i < nb_u_nodes; ++i) {\n\t\t//Sigma(i,i) += nugget;\n\t}\n\td->L_eigen.compute(Sigma);\n\tdouble L12 = 0.0;//-log(d->K_u_u.determinant());\n\tfor (int i = 0; i < d->u.rows(); ++i){\n\t\tL12 += log(d->LLTofK_u_u.vectorD()(i));\n    \t//std::cout << L1 << \"L11-\" << i << std::endl;\n\t}\n\n\tdouble det_Leigen = 0.0;\n\tfor (int i = 0; i < d->u.rows(); ++i){\n\t\tdet_Leigen += log(d->L_eigen.vectorD()(i));\n    \t//std::cout << d->L_eigen.matrixL()(i,i) << \" \" << log(d->L_eigen.matrixL()(i,i)) << \"det_Leigen-\" << i << std::endl;\n\t}\n\n\tdouble L11 = 0.0;\n    //std::cout << L1 << \"L12 \" << std::endl;\n\tfor (int i = 0; i < d->nb_gp_nodes; ++i){\n\t\tL11 += log(d->Lambda(i));\n\t\t//std::cout << \"Lambda: \" << i << \" \" << d->Lambda(i) <<\" \"<<log(d->Lambda(i)) << std::endl;\n\t}\n    double L1 = 0.0;\n\t//L1 = 0.5*L11 + (2*0.5)*det_Leigen + 0.5*det_LeigenD - (2*0.5)*L12 - 0.5*L12D;\n\tL1 = 0.5*L11 + 0.5*det_Leigen - 0.5*L12;\n\tMatrixXd Q_f_f = K_f_u*K_u_u_u_f;\n\tfor(int i = 0; i < nb_gp_nodes; i++){\n\t\tQ_f_f(i,i) += d->Lambda(i)+ d->Qff_opt_nugget;\n\t}\n\tLLT<MatrixXd> LLTofQ_f_f(Q_f_f);\n\tdouble L2 = 0.5*d->scaled_function_values_eigen.dot(LLTofQ_f_f.solve(d->scaled_function_values_eigen));\n  \t\n  \t//std::cout << d->scaled_function_values_eigen << std::endl;\n  double result = L1 + L2;\n \n  if (std::isinf(result) || std::isnan(result)){\n  \tstd::cout << \"Result is inf or nan\" << std::endl;\n  \tstd::cout << \"L11 \" << L11 << \" \" << 'x' << std::endl;\n    std::cout << \"L12 \" << L12 << std::endl; //<< \" \" << log(d->K_u_u.determinant()) << std::endl;\n    std::cout << \"L13 \" << det_Leigen << std::endl;// << \" \" << log(Sigma.determinant()) << std::endl;\n    std::cout << L1 << ' ' << L2 << std::endl;\n  \tresult = std::numeric_limits<double>::infinity();\n  \tif(d->Kuu_opt_nugget < d->nugget_max){\n  \t\td->Kuu_opt_nugget *= 10;\n  \t\td->Lambda_opt_nugget *= 10;\n  \t\td->Qff_opt_nugget *= 10;\n  \t}\n  }else{\n  \tif(d->Kuu_opt_nugget > d->nugget_min){\n  \t\td->Kuu_opt_nugget *= 0.1;\n  \t\td->Lambda_opt_nugget *= 0.1;\n  \t\td->Qff_opt_nugget *= 0.1;\n  \t}\n  }\n  if ((d->print%1)==0){\n\t  /*for ( int i = 0; i < d->dim + 1; ++i )\n\t    std::cout << \"gp_param = \" << x[i] << std::endl;\n\t  for(int j = offset; j < offset + d->u.rows(); ++j)\n\t\t\tstd::cout << \"gp_param = \" << x[j] <<\",\"<<x[j+ d->u.rows()]<< std::endl;*/\n  \t\n  \t//std::cout << d->print <<\" Objective: \" << L1 << \" \" << L2 << \" \"<< result<< std::endl;\n  }\n\n\t//Gradient computation:\n\tint dim_grad = x.size();\n\tgrad.resize(dim_grad);\n\n\tfor(int i = 0; i < grad.size(); i++){\n\n\t\tMatrixXd Kffdot;\n\t\tMatrixXd Kufdot;\n\t\tMatrixXd Kfudot;\n\t\tMatrixXd Kuudot;\n\t\tVectorXd LambdaDot;\n\t\tif(dim_grad == d->dim + 1){\n\t\t\tif(i == 0){//grad sigma_f\n\t\t\t\td->derivate_K_u_u_wrt_sigmaf(local_params, Kuudot);\n\t\t\t\td->derivate_K_f_f_wrt_sigmaf(local_params, Kffdot);\n\t\t\t\td->derivate_K_u_f_wrt_sigmaf(local_params, Kufdot);\n\t\t\t\tKfudot = Kufdot.transpose();\n\t\t\t}else{//grad length parameter\n\t\t\t\td->derivate_K_u_u_wrt_l(local_params, i-1, Kuudot);\n\t\t\t\td->derivate_K_f_f_wrt_l(local_params, i-1, Kffdot);\n\t\t\t\td->derivate_K_u_f_wrt_l(local_params, i-1, Kufdot);\n\t\t\t\tKfudot = Kufdot.transpose();\n\t\t\t}\n\t\t}else{\n\t\t\tif( dim_grad > d->u.rows()*d->dim){//if we optimize also for sigma_f and lengthscales\n\t\t\t\tif(i == 0){//grad sigma_f\n\t\t\t\t\td->derivate_K_u_u_wrt_sigmaf(local_params, Kuudot);\n\t\t\t\t\td->derivate_K_f_f_wrt_sigmaf(local_params, Kffdot);\n\t\t\t\t\td->derivate_K_u_f_wrt_sigmaf(local_params, Kufdot);\n\t\t\t\t\tKfudot = Kufdot.transpose();\n\t\t\t\t}else if(i > 0 && i < 1 + d->dim){//grad length parameter\n\t\t\t\t\td->derivate_K_u_u_wrt_l(local_params, i-1, Kuudot);\n\t\t\t\t\td->derivate_K_f_f_wrt_l(local_params, i-1, Kffdot);\n\t\t\t\t\td->derivate_K_u_f_wrt_l(local_params, i-1, Kufdot);\n\t\t\t\t\tKfudot = Kufdot.transpose();\n\t\t\t\t}else{//grad u\n\t\t\t\t\tint uidx = (i-offset)%d->u.rows();\n\t\t\t\t\tint udim = (int) ((i-offset)/d->u.rows());\n\t\t\t\t\td->derivate_K_u_u_wrt_uik(local_params, uidx, udim, Kuudot);\n\t\t\t\t\td->derivate_K_u_f_wrt_uik(local_params, uidx, udim, Kufdot);\n\t\t\t\t\tKffdot.resize(nb_gp_nodes, nb_gp_nodes);\n\t\t\t\t\tKffdot.setZero();\n\t\t\t\t\tKfudot = Kufdot.transpose(); \n\t\t\t\t}\n\t\t    }else{\n\t\t    \tint uidx = (i-offset)%d->u.rows();\n\t\t\t\tint udim = (int) ((i-offset)/d->u.rows());\n\t\t\t\td->derivate_K_u_u_wrt_uik(local_params, uidx, udim, Kuudot);\n\t\t\t\td->derivate_K_u_f_wrt_uik(local_params, uidx, udim, Kufdot);\n\t\t\t\tKffdot.resize(nb_gp_nodes, nb_gp_nodes);\n\t\t\t\tKffdot.setZero();\n\t\t\t\tKfudot = Kufdot.transpose(); \n\t\t    }\n\t    }\n\t\td->compute_LambdaDot(Kffdot, Kufdot, Kfudot, Kuudot, LambdaDot);\n\n\t\t//L1-term: dL3/dtheta = d(Lambda+noise^2)/dtheta = tr((Lambda+noise^2)^(-1)*LambdaDot)\n\t\tdouble dL1 = 0.0;\n\t\tVectorXd LambdaInv(nb_gp_nodes);\n\t\tfor(int j = 0; j < nb_gp_nodes; ++j){\n\t\t\tLambdaInv(j) = 1.0/d->Lambda(j);\n\t\t\tdL1 += LambdaInv(j) * LambdaDot(j);\n\t\t}\n\n\t\t//L2-term: dL2/dtheta= tr(Kuu^(-1) * Kuudot)\n\t\tdouble dL2 = d->LLTofK_u_u.solve(Kuudot).trace();\n\n\t\t//L3-term: d(log(det(Kuu+Kuf*(Lambda+noise^2)^(-1)*Kfu)))/dtheta\n\t\tMatrixXd LambdaInvDiag = LambdaInv.asDiagonal();\n\t\tMatrixXd LambdaDotDiag = LambdaDot.asDiagonal();\n\t\tMatrixXd dSigma = Kuudot \n\t\t\t\t\t\t\t+ 2*Kufdot*LambdaInvDiag*K_f_u \n\t\t\t\t\t\t\t- d->K_u_f*LambdaInvDiag*LambdaDotDiag*LambdaInvDiag*K_f_u; \n\t\t\t\t\t\t\t//+ d->K_u_f*LambdaInvDiag*Kfudot;\n\t\tdouble dL3 = (d->L_eigen.solve(dSigma)).trace();\n\n\t\t//L4-term: d(yT*Q*y)/dtheta\n\t\tMatrixXd KfudotKuinvKuf = Kfudot * d->LLTofK_u_u.solve(d->K_u_f);\n\t\tMatrixXd KfuKuinvKufdot = K_f_u * d->LLTofK_u_u.solve(Kufdot);\n\t\tMatrixXd KfuKuinfKudotKuinvKuf = K_f_u*(d->LLTofK_u_u.solve(Kuudot*(d->LLTofK_u_u.solve(d->K_u_f))));\n\t\tMatrixXd dQ = KfudotKuinvKuf - KfuKuinfKudotKuinvKuf + KfuKuinvKufdot + LambdaDotDiag;\n\t\tdouble dL4 = (-1)*d->scaled_function_values_eigen.dot(\n\t\t\t\t\t\tLLTofQ_f_f.solve(dQ*LLTofQ_f_f.solve(\n\t\t\t\t\t\t\td->scaled_function_values_eigen)));\n\n\t\tgrad[i] = 0.5*(dL1 - dL2 + dL3 + dL4);\n\n\n\t\t/*JacobiSVD<MatrixXd> svdKuuInv(d->K_u_u.inverse());\n\t\tdouble condKuu = svdKuuInv.singularValues()(0) \n\t\t    / svdKuuInv.singularValues()(svdKuuInv.singularValues().size()-1);\n\t\tJacobiSVD<MatrixXd> svdQ(Q_f_f.inverse());\n\t\tdouble condQff = svdQ.singularValues()(0) \n\t\t    / svdQ.singularValues()(svdQ.singularValues().size()-1);\n\t\tJacobiSVD<MatrixXd> svdLambdaInv(LambdaInvDiag);\n\t\tdouble condLambda = svdLambdaInv.singularValues()(0) \n\t\t    / svdLambdaInv.singularValues()(svdLambdaInv.singularValues().size()-1);\n\t\tJacobiSVD<MatrixXd> svddQ(dQ);\n\t\tdouble conddQ = svddQ.singularValues()(0) \n\t\t    / svddQ.singularValues()(svddQ.singularValues().size()-1);\n\t\tstd::cout << \"Condition numbers: \\n\";\n\t\tstd::cout << \"Kuuinv: \" << condKuu << \" Qff: \" << condQff \n\t\t\t<< \" LambdaInv: \" << condLambda << \" dQ: \" << conddQ << std::endl;\n\t\t*/\n\t\t//if ((d->print%1)==0){\n\t\t// \tstd::cout << \"Grad: \" << i << \"|\" << 0.5*dL1 << \" + \"<< 0.5*dL2 << \" + \"<< 0.5*dL3 << \" + \"<< 0.5*dL4 << \" = \" << grad[i] << std::endl;\n\t\t//}\n\t\t//exit(-1);\n\t}\n\n  d->print++;\n\n  return result;\n\n}\n\nvoid FullyIndependentTrainingConditional::set_constraint_ball_radius(const double& radius){\n\tconstraint_ball_radius = radius;\n}\n\nvoid FullyIndependentTrainingConditional::set_constraint_ball_center(const std::vector<double>& center){\n\tconstraint_ball_center.resize(center.size());\n\tfor(int i = 0; i < center.size(); ++i){\n\t\tconstraint_ball_center(i) = center[i];\n\t}\n}\n\nvoid FullyIndependentTrainingConditional::trust_region_constraint(unsigned int m, double* c, unsigned int n, const double* x, double* grad,\n                                                     \t\t\tvoid *data){\n\tFullyIndependentTrainingConditional *d = reinterpret_cast<FullyIndependentTrainingConditional*>(data);\n\n\tint offset;\n\tif(m == d->dim + 1){\n\t\tfor (int i = 0; i < d->dim+1; ++i) {\n\t\t\tc[i] = -1;\n\t\t}\n\t}else{\n\t\tif(m > d->u.rows()*d->dim){\n\t\t    offset = 1+d->dim;\n\t\t}else{\n\t\t\toffset = 0;\n\t\t}\n\t\tint u_counter;\n\n\t\tfor (int i = 0; i < offset; ++i) {\n\t\t\tc[i] = -1;\n\t\t}\n\t\tMatrixXd u_intern(d->u.rows(), d->u.cols());\n\t\tfor (int i = 0; i < d->dim; ++i) {\n\t\t  u_counter = 0;\n\t\t  for(int j = offset + i*d->u.rows(); j < offset + (i+1)*d->u.rows(); ++j){\n\t        u_intern(u_counter, i) = x[j];\n\t        u_counter++;\n\t\t  }\n\t\t}\n\t\tVectorXd c_intern(u_intern.rows());\n\t\tVectorXd dist(d->dim);\n\t\tfor (int i = 0; i < u_intern.rows(); ++i) {\n\t\t\tfor (int j = 0; j < d->dim; ++j) {\n\t\t\t\tdist(j) = (u_intern(i, j)-d->constraint_ball_center(j));\n\t\t\t}\n\t    \tc_intern(i) = sqrt( dist.dot(dist) ) - d->constraint_ball_radius;\n\t\t}\n\t\tfor (int i = 0; i < d->dim; ++i) {\n\t\t    u_counter = 0;\n\t\t  \tfor(int j = offset + i*d->u.rows(); j < offset + (i+1)*d->u.rows(); ++j){\n\t\t    c[j] = c_intern(u_counter);\n\t        u_counter++;\n\t\t  \t}\n\t\t}\n\t}\n  \treturn;\n}\n\nvoid FullyIndependentTrainingConditional::decrease_nugget(){\n\tif(K_u_u_nugget > K_u_u_nugget_min){\n\t\tK_u_u_nugget *= 0.1;\n\t}\n\tstd::cout << \"FITC: Decrease nugget to \" << K_u_u_nugget << std::endl;\n  return;\n}\nbool FullyIndependentTrainingConditional::increase_nugget(){\n\tif(K_u_u_nugget <= K_u_u_nugget_max){\n\t\tK_u_u_nugget *= 10;\n\t}\n\tstd::cout << \"FITC: Increase nugget to \" << K_u_u_nugget << std::endl;\n\tif(K_u_u_nugget > K_u_u_nugget_max){\n\t\treturn true;\n\t}\n  return false;\n}", "meta": {"hexsha": "d764a26effc8a61c17742fef6970ea81596dc12d", "size": 55484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/FullyIndependentTrainingConditional.cpp", "max_stars_repo_name": "snowpac/snowpac", "max_stars_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-08-04T20:18:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T23:50:27.000Z", "max_issues_repo_path": "src/FullyIndependentTrainingConditional.cpp", "max_issues_repo_name": "snowpac/snowpac", "max_issues_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "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/FullyIndependentTrainingConditional.cpp", "max_forks_repo_name": "snowpac/snowpac", "max_forks_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "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.5250755287, "max_line_length": 151, "alphanum_fraction": 0.5989294211, "num_tokens": 18444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6619228758499941, "lm_q1q2_score": 0.5034920675373258}}
{"text": "#pragma once\r\n\r\n#include \"Tableau.hpp\"\r\n#include \"Solids.hpp\"\r\n#include \"SM_utils.hpp\"\r\n\r\n#include <Eigen/Dense>\r\n\r\n#include <vector>\r\n#include <stdexcept>\r\n#include <cstddef>\r\n\r\nnamespace AQSystemSolver {\r\n    class ReplacementDict{\r\n    private:\r\n        //which terms have been replaced out of existence\r\n        SM_utils::flat_set<Eigen::Index> columns;\r\n        SM_utils::flat_set<Eigen::Index> columnsNotReplaced;\r\n        SM_utils::IncreasingPQ<Eigen::Index> nextRowToFill;\r\n        std::vector<Eigen::Index> columnToRow;//because columns is not in order, and we always append to our replacement, this tells which column goes to which row\r\n        Tableau<> unsimplifiedReplacement;\r\n        Tableau<> replacement;\r\n        Tableau<> replacementWithoutColumns;\r\n\r\n        void groupTerms(){\r\n            for(auto column : columns){\r\n                replacement.groupTerm<1>(column, columnToRow[column]);\r\n            }\r\n        }\r\n\r\n        [[nodiscard]] auto substituteTerms(){\r\n            bool replacedAnything=false;\r\n            const Tableau<> copyReplacement=replacement;\r\n            for(auto column : columns){\r\n                if(std::any_of(SM_utils::NestingIterator(columnToRow, columns.begin()), SM_utils::NestingIterator(columnToRow, columns.end()), [&](Eigen::Index row) { return replacement.getCoefficient(row, column)!=0; })) {\r\n                    //std::cout<<\"replaced\"<<std::endl<<std::endl;\r\n                    replacedAnything=true;\r\n                    replacement.substituteRowAndCol<true>(copyReplacement, columnToRow[column], copyReplacement, column);\r\n                }\r\n            }\r\n            return replacedAnything;\r\n        }\r\n\r\n        void simplify(){\r\n            do{\r\n                groupTerms();\r\n            } while(substituteTerms());\r\n            //the last substitute terms doesn't change anything so we dont need to regroup terms\r\n            replacementWithoutColumns=replacement.reducedCopy(Eigen::all, columnsNotReplaced);\r\n        }\r\n\r\n        void simplifyFromUnsimplified(){\r\n            replacement=unsimplifiedReplacement;\r\n            simplify();\r\n        }\r\n\r\n        [[nodiscard]] auto addColumn(const Eigen::Index column){\r\n            columnToRow[column]=nextRowToFill.top();\r\n            nextRowToFill.pop();\r\n            columns.insert(column);\r\n            columnsNotReplaced.erase(column);\r\n            return columnToRow[column];\r\n        }\r\n\r\n        void removeColumn(const Eigen::Index column){\r\n            nextRowToFill.push(columnToRow[column]);\r\n            columns.erase(column);\r\n            columnsNotReplaced.insert(column);\r\n        }\r\n\r\n        void solveForTermAndAddToRow(const Eigen::RowVectorXd& rowVect, double constant, Eigen::Index term, Eigen::Index row){\r\n            unsimplifiedReplacement.assignRow(row, rowVect, constant);\r\n            unsimplifiedReplacement.groupTerm<0>(row, term);\r\n            replacement.assignRowFromTableau(row, unsimplifiedReplacement, row);\r\n        }\r\n\r\n        void addSolidInternal(Solid* solid){\r\n            auto columnIt=std::find_if(columnsNotReplaced.begin(), columnsNotReplaced.end(), [&](Eigen::Index term){ return solid->row.coeff(term)!=0.0; });\r\n            if(columnIt==columnsNotReplaced.end()){\r\n                throw std::runtime_error(\"Couldn't find a clean column. This is probably a Gibbs Rule violation.\");\r\n            }\r\n            const Eigen::Index column=*columnIt;\r\n            Eigen::Index row=addColumn(column);\r\n            solid->column=column;\r\n            solveForTermAndAddToRow(solid->row, solid->constant, column, row);\r\n        }\r\n\r\n    public:\r\n        [[nodiscard]] auto size() const {\r\n            assert(static_cast<Eigen::Index>(columns.size())==replacement.rows());\r\n            return columns.size();\r\n        }\r\n        [[nodiscard]] auto cols() const {\r\n            return replacement.cols();\r\n        }\r\n\r\n\r\n\r\n        void addSolid(Solid* solid){\r\n            addSolidInternal(solid);\r\n            //mostly already simplifed, just the last row, but we still have to iterate over all the columns\r\n            simplify();\r\n        }\r\n\r\n\r\n        void removeSolid(Solid* solid){\r\n            removeColumn(solid->column);\r\n\r\n            solid->column=-1;\r\n\r\n            //TODO(SoAsEr) Plug row back in and then simplify\r\n            simplifyFromUnsimplified();\r\n        }\r\n\r\n        void addSolidSystem(const SolidSystem& solidSystem){\r\n            assert(cols()==solidSystem.cols());\r\n            replacement.conservativeResize(replacement.rows()+solidSystem.size(), cols());\r\n            unsimplifiedReplacement.conservativeResize(replacement.rows()+solidSystem.size(), cols());\r\n            for(Solid * solid : solidSystem.getSolidsPresent()) {\r\n                addSolidInternal(solid); //avoid simplifying on every loop\r\n            }\r\n            simplify();\r\n        }\r\n\r\n        [[nodiscard]] auto createReplacedTableau(const /*TableauType*/ auto& orig) const {\r\n            auto replaced=orig.reducedCopy(Eigen::all, columnsNotReplaced);\r\n            if(orig.rows()) [[likely]] {\r\n                for(auto column : columns){\r\n                    replaced.template substituteRowAndCol<false>(replacementWithoutColumns, columnToRow[column], orig, column);\r\n                }\r\n            }\r\n            return replaced;\r\n        }\r\n        \r\n        ReplacementDict(const /*std::ranges::range*/ auto& columns_, const Tableau<>& replacement_):\r\n        columnsNotReplaced{SM_utils::CountingIterator(0), SM_utils::CountingIterator(replacement_.cols())},\r\n        nextRowToFill{0},\r\n        columnToRow(replacement_.cols()),\r\n        unsimplifiedReplacement{replacement_},\r\n        replacement{replacement_}\r\n        {\r\n            Eigen::Index i{0};\r\n            for(const Eigen::Index column: columns_) {\r\n                const Eigen::Index row=addColumn(column);\r\n                assert(replacement_.getCoefficient(i, column)!=0);\r\n                solveForTermAndAddToRow(replacement_.getCoefficients().row(i), replacement_.getConstant(i), column, row);\r\n                ++i;\r\n            }\r\n            simplifyFromUnsimplified();\r\n        }\r\n    };\r\n} //namespace AQSystemSolver", "meta": {"hexsha": "f1445c48f1d7765b5540c803e6f8a4e4fccaab5d", "size": 6155, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReplacementDictionary.hpp", "max_stars_repo_name": "FreeQL/AQSystemSolver", "max_stars_repo_head_hexsha": "3d98837d7cac9c5c0da57ed896a3145ed0c49a97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ReplacementDictionary.hpp", "max_issues_repo_name": "FreeQL/AQSystemSolver", "max_issues_repo_head_hexsha": "3d98837d7cac9c5c0da57ed896a3145ed0c49a97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ReplacementDictionary.hpp", "max_forks_repo_name": "FreeQL/AQSystemSolver", "max_forks_repo_head_hexsha": "3d98837d7cac9c5c0da57ed896a3145ed0c49a97", "max_forks_repo_licenses": ["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.4934210526, "max_line_length": 224, "alphanum_fraction": 0.5922014622, "num_tokens": 1217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5034920675373258}}
{"text": "/* boost random/cauchy_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$\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_CAUCHY_DISTRIBUTION_HPP\n#define BOOST_RANDOM_CAUCHY_DISTRIBUTION_HPP\n\n#include <boost/config/no_tr1/cmath.hpp>\n#include <iostream>\n#include <boost/limits.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/random/detail/config.hpp>\n\nnamespace boost {\n\n#if defined(__GNUC__) && (__GNUC__ < 3)\n// Special gcc workaround: gcc 2.95.x ignores using-declarations\n// in template classes (confirmed by gcc author Martin v. Loewis)\n  using std::tan;\n#endif\n\n// Cauchy distribution: \n\n/**\n * The cauchy distribution is a continuous distribution with two\n * parameters, sigma and median.\n *\n * It has \\f$p(x) = \\frac{\\sigma}{\\pi(\\sigma^2 + (x-m)^2)}\\f$\n */\ntemplate<class RealType = double>\nclass cauchy_distribution\n{\npublic:\n  typedef RealType input_type;\n  typedef RealType result_type;\n\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n  BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer);\n#endif\n\n  /**\n   * Constructs a \\cauchy_distribution with the paramters @c median\n   * and @c sigma.\n   */\n  explicit cauchy_distribution(result_type median_arg = result_type(0), \n                               result_type sigma_arg = result_type(1))\n    : _median(median_arg), _sigma(sigma_arg) { }\n\n  // compiler-generated copy ctor and assignment operator are fine\n\n  /**\n   * Returns: the \"median\" parameter of the distribution\n   */\n  result_type median() const { return _median; }\n  /**\n   * Returns: the \"sigma\" parameter of the distribution\n   */\n  result_type sigma() const { return _sigma; }\n  /**\n   * Effects: Subsequent uses of the distribution do not depend\n   * on values produced by any engine prior to invoking reset.\n   */\n  void reset() { }\n\n  /**\n   * Returns: A random variate distributed according to the\n   * cauchy distribution.\n   */\n  template<class Engine>\n  result_type operator()(Engine& eng)\n  {\n    // Can we have a boost::mathconst please?\n    const result_type pi = result_type(3.14159265358979323846);\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::tan;\n#endif\n    return _median + _sigma * tan(pi*(eng()-result_type(0.5)));\n  }\n\n#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS\n  /**\n   * Writes the parameters of the distribution to a @c std::ostream.\n   */\n  template<class CharT, class Traits>\n  friend std::basic_ostream<CharT,Traits>&\n  operator<<(std::basic_ostream<CharT,Traits>& os, const cauchy_distribution& cd)\n  {\n    os << cd._median << \" \" << cd._sigma;\n    return os;\n  }\n\n  /**\n   * Reads the parameters of the distribution from a @c std::istream.\n   */\n  template<class CharT, class Traits>\n  friend std::basic_istream<CharT,Traits>&\n  operator>>(std::basic_istream<CharT,Traits>& is, cauchy_distribution& cd)\n  {\n    is >> std::ws >> cd._median >> std::ws >> cd._sigma;\n    return is;\n  }\n#endif\n\nprivate:\n  result_type _median, _sigma;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_CAUCHY_DISTRIBUTION_HPP\n", "meta": {"hexsha": "3a7bd0c700024ce89a9ce924c3f727ca6a46b7f7", "size": 3288, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/random/cauchy_distribution.hpp", "max_stars_repo_name": "ksundberg/boost-svn", "max_stars_repo_head_hexsha": "5694e7831f7afc8f6e25d03d0fd375e7be758d0f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-04T17:42:55.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-04T17:43:16.000Z", "max_issues_repo_path": "boost/random/cauchy_distribution.hpp", "max_issues_repo_name": "ksundberg/boost-svn", "max_issues_repo_head_hexsha": "5694e7831f7afc8f6e25d03d0fd375e7be758d0f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/random/cauchy_distribution.hpp", "max_forks_repo_name": "ksundberg/boost-svn", "max_forks_repo_head_hexsha": "5694e7831f7afc8f6e25d03d0fd375e7be758d0f", "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.9508196721, "max_line_length": 81, "alphanum_fraction": 0.704379562, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5034920654272662}}
{"text": "// -----------------------------------------------------------------------\r\n// RTToolbox - DKFZ radiotherapy quantitative evaluation library\r\n//\r\n// Copyright (c) German Cancer Research Center (DKFZ),\r\n// Software development for Integrated Diagnostics and Therapy (SIDT).\r\n// ALL RIGHTS RESERVED.\r\n// See rttbCopyright.txt or\r\n// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html\r\n//\r\n// This software is distributed WITHOUT ANY WARRANTY; without even\r\n// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\r\n// PURPOSE.  See the above copyright notices for more information.\r\n//\r\n//------------------------------------------------------------------------\r\n\r\n#include <boost/make_shared.hpp>\r\n#include <boost/shared_ptr.hpp>\r\n\r\n#include \"litCheckMacros.h\"\r\n\r\n#include \"rttbBaseType.h\"\r\n#include \"rttbDoseAccessorInterface.h\"\r\n#include \"rttbDicomDoseAccessor.h\"\r\n#include \"rttbDicomFileDoseAccessorGenerator.h\"\r\n#include \"rttbArithmetic.h\"\r\n#include \"rttbNullPointerException.h\"\r\n#include \"rttbInvalidParameterException.h\"\r\n#include \"rttbBinaryFunctorAccessor.h\"\r\n\r\nnamespace rttb\r\n{\r\n\tnamespace testing\r\n\t{\r\n\t\ttypedef core::DoseAccessorInterface::Pointer DoseAccessorPointer;\r\n\t\ttypedef  algorithms::BinaryFunctorAccessor<algorithms::arithmetic::doseOp::Add>\r\n\t\tBinaryFunctorAccessorAddType;\r\n\t\ttypedef  algorithms::BinaryFunctorAccessor<algorithms::arithmetic::doseOp::AddWeighted>\r\n\t\tBinaryFunctorAccessorAddWeightedType;\r\n\r\n\t\t/*! @brief BinaryFunctorAccessorTest - tests functors of two accessors\r\n\t\t\t\t1) test constructor\r\n\t\t\t\t2) test getDoseAt\r\n\t\t\t*/\r\n\r\n\t\tint BinaryFunctorAccessorTest(int argc, char* argv[])\r\n\t\t{\r\n\t\t\tPREPARE_DEFAULT_TEST_REPORTING;\r\n\r\n\t\t\tstd::string RTDOSE_FILENAME;\r\n\t\t\tstd::string RTDOSE2_FILENAME;\r\n\r\n\t\t\tif (argc > 1)\r\n\t\t\t{\r\n\t\t\t\tRTDOSE_FILENAME = argv[1];\r\n\t\t\t}\r\n\r\n\t\t\tif (argc > 2)\r\n\t\t\t{\r\n\t\t\t\tRTDOSE2_FILENAME = argv[2];\r\n\t\t\t}\r\n\r\n\r\n\t\t\tDoseAccessorPointer spDoseAccessorNull;\r\n\r\n\t\t\tDoseAccessorPointer spDoseAccessor = io::dicom::DicomFileDoseAccessorGenerator(\r\n\t\t\t        RTDOSE_FILENAME.c_str()).generateDoseAccessor();\r\n\t\t\tDoseAccessorPointer spDoseAccessor2 = io::dicom::DicomFileDoseAccessorGenerator(\r\n\t\t\t        RTDOSE2_FILENAME.c_str()).generateDoseAccessor();\r\n\r\n\t\t\talgorithms::arithmetic::doseOp::Add addOP;\r\n\r\n\t\t\talgorithms::arithmetic::doseOp::AddWeighted addWeightedOP(1.0, 10.0);\r\n\t\t\talgorithms::arithmetic::doseOp::AddWeighted addWeightedTwoOP(2.0, 2.0);\r\n\r\n\r\n\t\t\t//1) Check constructor\r\n\r\n\t\t\tCHECK_THROW_EXPLICIT(BinaryFunctorAccessorAddType(spDoseAccessorNull, spDoseAccessor, addOP),\r\n\t\t\t                     core::NullPointerException);\r\n\t\t\tCHECK_THROW_EXPLICIT(BinaryFunctorAccessorAddType(spDoseAccessor, spDoseAccessorNull, addOP),\r\n\t\t\t                     core::NullPointerException);\r\n\t\t\tCHECK_THROW_EXPLICIT(BinaryFunctorAccessorAddType(spDoseAccessorNull, spDoseAccessorNull,\r\n\t\t\t                     addOP), core::NullPointerException);\r\n\t\t\tCHECK_THROW_EXPLICIT(BinaryFunctorAccessorAddType(spDoseAccessor, spDoseAccessor2, addOP),\r\n\t\t\t                     core::InvalidParameterException);\r\n\r\n\r\n\t\t\tCHECK_NO_THROW(BinaryFunctorAccessorAddType(spDoseAccessor, spDoseAccessor, addOP));\r\n\t\t\tCHECK_NO_THROW(BinaryFunctorAccessorAddWeightedType(spDoseAccessor, spDoseAccessor,\r\n\t\t\t               addWeightedOP));\r\n\r\n\t\t\tauto spBinaryFunctorDoseAccessorAdd = boost::make_shared<BinaryFunctorAccessorAddType>(spDoseAccessor, spDoseAccessor, addOP);\r\n\t\t\tauto spBinaryFunctorDoseAccessorAddWeighted = boost::make_shared<BinaryFunctorAccessorAddWeightedType>(spDoseAccessor, spDoseAccessor, addWeightedOP);\r\n\t\t\tauto spBinaryFunctorDoseAccessorAddWeightedTwo = boost::make_shared<BinaryFunctorAccessorAddWeightedType>(spDoseAccessor, spDoseAccessor, addWeightedTwoOP);\r\n\r\n\t\t\t//2) Test getDoseAt()\r\n\t\t\tint lastIndex = spBinaryFunctorDoseAccessorAdd->getGeometricInfo().getNumberOfVoxels() - 1;\r\n\t\t\tVoxelGridID aId[3] = { 5, 6067, lastIndex };\r\n\t\t\tVoxelGridIndex3D aIndex[3] = {VoxelGridIndex3D(5, 0, 0), VoxelGridIndex3D(37, 0, 2), VoxelGridIndex3D(spBinaryFunctorDoseAccessorAdd->getGeometricInfo().getNumColumns() - 1, spBinaryFunctorDoseAccessorAdd->getGeometricInfo().getNumRows() - 1, spBinaryFunctorDoseAccessorAdd->getGeometricInfo().getNumSlices() - 1)};\r\n\r\n\t\t\tfor (int i = 0; i < 3; ++i)\r\n\t\t\t{\r\n\t\t\t\tCHECK_EQUAL(spBinaryFunctorDoseAccessorAdd->getValueAt(aId[i]), 4.0);\r\n\t\t\t\tCHECK_EQUAL(spBinaryFunctorDoseAccessorAddWeighted->getValueAt(aId[i]), 22.0);\r\n\t\t\t\tCHECK_EQUAL(spBinaryFunctorDoseAccessorAdd->getValueAt(aIndex[i]),\r\n\t\t\t\t            spBinaryFunctorDoseAccessorAdd->getValueAt(aId[i]));\r\n\t\t\t\tCHECK_EQUAL(spBinaryFunctorDoseAccessorAddWeighted->getValueAt(aIndex[i]),\r\n\t\t\t\t            spBinaryFunctorDoseAccessorAddWeighted->getValueAt(aId[i]));\r\n\t\t\t\tCHECK_EQUAL(spBinaryFunctorDoseAccessorAdd->getValueAt(aId[i]) * 2.0,\r\n\t\t\t\t            spBinaryFunctorDoseAccessorAddWeightedTwo->getValueAt(aId[i]));\r\n\t\t\t}\r\n\r\n\t\t\tVoxelGridID aIdInvalid(spBinaryFunctorDoseAccessorAdd->getGeometricInfo().getNumberOfVoxels());\r\n\t\t\tVoxelGridIndex3D aIndexInvalid(spBinaryFunctorDoseAccessorAdd->getGeometricInfo().getNumColumns(),\r\n\t\t\t                               spBinaryFunctorDoseAccessorAdd->getGeometricInfo().getNumRows(),\r\n\t\t\t                               spBinaryFunctorDoseAccessorAdd->getGeometricInfo().getNumSlices());\r\n\t\t\tCHECK_EQUAL(spBinaryFunctorDoseAccessorAdd->getValueAt(aIdInvalid), -1.0);\r\n\t\t\tCHECK_EQUAL(spBinaryFunctorDoseAccessorAdd->getValueAt(aIndexInvalid), -1.0);\r\n\t\t\tCHECK_EQUAL(spBinaryFunctorDoseAccessorAddWeighted->getValueAt(aIdInvalid), -1.0);\r\n\t\t\tCHECK_EQUAL(spBinaryFunctorDoseAccessorAddWeighted->getValueAt(aIndexInvalid), -1.0);\r\n\r\n\t\t\tRETURN_AND_REPORT_TEST_SUCCESS;\r\n\t\t}\r\n\t}\r\n}", "meta": {"hexsha": "301933f10fb7d47da587eb90840d71daf0cb5124", "size": 5681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/algorithms/BinaryFunctorAccessorTest.cpp", "max_stars_repo_name": "MIC-DKFZ/RTTB", "max_stars_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T12:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T17:43:02.000Z", "max_issues_repo_path": "testing/algorithms/BinaryFunctorAccessorTest.cpp", "max_issues_repo_name": "MIC-DKFZ/RTTB", "max_issues_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/algorithms/BinaryFunctorAccessorTest.cpp", "max_forks_repo_name": "MIC-DKFZ/RTTB", "max_forks_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T21:09:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T09:30:49.000Z", "avg_line_length": 45.448, "max_line_length": 319, "alphanum_fraction": 0.7254004577, "num_tokens": 1478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5034920624643998}}
{"text": "#include <NTL/mat_poly_lzz_p.h>\n\n\nNTL_START_IMPL\n\n\nvoid CharPoly(zz_pX& f, const mat_zz_p& M)\n{\n   long n = M.NumRows();\n   if (M.NumCols() != n)\n      LogicError(\"CharPoly: nonsquare matrix\");\n\n   if (n == 0) {\n      set(f);\n      return;\n   }\n\n   zz_p t;\n\n   if (n == 1) {\n      SetX(f);\n      negate(t, M(1, 1));\n      SetCoeff(f, 0, t);\n      return;\n   }\n\n   mat_zz_p H;\n\n   H = M;\n\n   long i, j, m;\n   zz_p u, t1;\n\n   for (m = 2; m <= n-1; m++) {\n      i = m;\n      while (i <= n && IsZero(H(i, m-1)))\n         i++;\n\n      if (i <= n) {\n         t = H(i, m-1);\n         if (i > m) {\n            swap(H(i), H(m));\n            // swap columns i and m\n            for (j = 1; j <= n; j++) \n               swap(H(j, i), H(j, m));\n         }\n\n         for (i = m+1; i <= n; i++) {\n            div(u, H(i, m-1), t);\n            for (j = m; j <= n; j++) {\n               mul(t1, u, H(m, j));\n               sub(H(i, j), H(i, j), t1);\n            }\n\n            for (j = 1; j <= n; j++) {\n               mul(t1, u, H(j, i));\n               add(H(j, m), H(j, m), t1);\n            }\n         }\n      }\n   }\n\n   vec_zz_pX F;\n   F.SetLength(n+1);\n   zz_pX T;\n   T.SetMaxLength(n);\n\n   set(F[0]);\n   for (m = 1; m <= n; m++) {\n      LeftShift(F[m], F[m-1], 1);\n      mul(T, F[m-1], H(m, m));\n      sub(F[m], F[m], T);\n\n      set(t);\n      for (i = 1; i <= m-1; i++) {\n         mul(t, t, H(m-i+1, m-i));\n         mul(t1, t, H(m-i, m));\n         mul(T, F[m-i-1], t1);\n         sub(F[m], F[m], T);\n      }\n   }\n\n   f = F[n];\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "57a87fe8a0bec4e83665d6c2436d71a40b553908", "size": 1531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/mat_poly_lzz_p.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "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": "homomorphic_evaluation/ntl-11.3.2/src/mat_poly_lzz_p.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "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": "LibSource/ExtendedNTL/src/mat_poly_lzz_p.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "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": 17.5977011494, "max_line_length": 47, "alphanum_fraction": 0.3403004572, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5034920603543402}}
{"text": "#include <iostream>\n#include <dlib/matrix.h>\nusing namespace dlib;\nusing namespace std;\nint main() {\n  matrix<double,3,1> y;\n  matrix<double> M(3,3);\n\n  M = 54.2, 7.4, 12.1, 1, 2, 3, 5.9, 0.05, 1;\n  y = 3.5, 1.2, 7.8;\n\n  matrix<double> x = inv(M)*y;\n  cout << \"x: \\n\" << x << endl;\n  cout << \"M*x - y: \\n\" << M*x -y << endl;\n\n  matrix<double,0,1> runtime_sized_column_vector;\n  matrix<double,1,0> runtime_sized_row_vector;\n  runtime_sized_column_vector.set_size(3);\n  x.set_size(3,4);\n  cout << M(0,1) << endl;\n  cout << y(1) << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "523cd82c7aaa3c47086be32695ea7c4bf9bfdab5", "size": 550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/tests/dlib/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/tests/dlib/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/tests/dlib/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": 22.0, "max_line_length": 49, "alphanum_fraction": 0.5963636364, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.5033894933715853}}
{"text": "/**\n * \\copyright\n * Copyright (c) 2015, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include \"fem_ele_std.h\"\n\n#include <Eigen/Eigen>\n\n#include \"rf_mmp_new.h\"\n#include \"rf_pcs.h\"\n\nnamespace FiniteElement\n{\n\nvoid CFiniteElementStd::AssembleTHResidual()\n{\n\tconst unsigned c_dim = dim;\n\tconst int c_nnodes = nnodes;\n\tconst double dt = pcs->Tim->time_step_length;\n\tconst double theta = pcs->m_num->ls_theta;\n\tconst bool hasGravity =\n\t\t(coordinate_system) % 10 == 2 && FluidProp->CheckGravityCalculation();\n\tconst double g_const = hasGravity ? gravity_constant : .0;\n\tconst bool useSUPG = (pcs->m_num->ele_supg_method > 0);\n\tconst bool useLumpedMass = (pcs->m_num->ele_mass_lumping > 0);\n\tconst bool isTransient =\n\t\t(this->pcs->tim_type == FiniteElement::TIM_TRANSIENT);\n\tconst bool isMatrixFlowInactive = pcs->deactivateMatrixFlow;\n\tconst bool isMatrixElement = (MeshElement->GetDimension() == pcs->m_msh->GetMaxElementDim());\n\n\tMatrix t_transform_tensor(3, 3);\n\tif (dim > MediaProp->geo_dimension)\n\t{\n\t\tif (MeshElement->getTransformTensor() == NULL)\n\t\t{\n\t\t\tstd::cout << \"***Error: Geometric dimension in MMP is not \"\n\t\t\t\t\t\t \"consistent with element.\"\n\t\t\t\t\t  << \"\\n\";\n\t\t\texit(0);\n\t\t}\n\t\tt_transform_tensor.LimitSize(dim, dim);\n\t\tMeshElement->getTransformTensor()->GetTranspose(t_transform_tensor);\n\t}\n\n\tEigen::VectorXd nodal_p0(nnodes), nodal_p1(nnodes);\n\tEigen::VectorXd nodal_T0(nnodes), nodal_T1(nnodes);\n\tfor (int i = 0; i < nnodes; i++)\n\t{\n\t\tnodal_p0[i] = pcs->GetNodeValue(nodes[i], idxp0);\n\t\tnodal_p1[i] = pcs->GetNodeValue(nodes[i], idxp1);\n\t\tnodal_T0[i] = pcs->GetNodeValue(nodes[i], idxT0);\n\t\tnodal_T1[i] = pcs->GetNodeValue(nodes[i], idxT1);\n\t}\n\n\t// Calculate matrices\n\tconst int offset_p = 0;\n\tconst int offset_T = c_nnodes;\n\t(*RHS) = 0.0;          // Residual\n\n//#define TH_DEBUG\n#ifdef TH_DEBUG\n\t// for debugging\n\tMass->LimitSize(nnodes, nnodes);\n\tLaplace->LimitSize(nnodes, nnodes);\n\tAdvection->LimitSize(nnodes, nnodes);\n\t(*Mass) = .0;\n\t(*Laplace) = .0;\n\t(*Advection) = .0;\n#endif\n\tdouble* tmp_k_tensor = MediaProp->PermeabilityTensor(Index);\n\tif (c_dim > MediaProp->geo_dimension)\n\t{\n\t\tMatrix local_tensor(c_dim, c_dim), temp_tensor(c_dim, c_dim),\n\t\t\tglobal_tensor(c_dim, c_dim);\n\t\tconst unsigned c_ele_dim = ele_dim;\n\t\tfor (size_t i = 0; i < c_ele_dim; i++)\n\t\t\tfor (size_t j = 0; j < c_ele_dim; j++)\n\t\t\t\tlocal_tensor(i, j) = tmp_k_tensor[j + i * c_ele_dim];\n\t\t// cout << \"K':\" << endl; local_tensor.Write();\n\t\tlocal_tensor.multi(t_transform_tensor, temp_tensor);\n\t\tfor (size_t i = 0; i < c_dim; i++)\n\t\t\tfor (size_t j = 0; j < c_dim; j++)\n\t\t\t\tfor (size_t k = 0; k < c_dim; k++)\n\t\t\t\t\tglobal_tensor(i, j) +=\n\t\t\t\t\t\t(*MeshElement->getTransformTensor())(i, k) *\n\t\t\t\t\t\ttemp_tensor(k, j);\n\t\t// cout << \"K:\" << endl; global_tensor.Write();\n\t\tfor (size_t i = 0; i < c_dim; i++)\n\t\t\tfor (size_t j = 0; j < c_dim; j++)\n\t\t\t\ttmp_k_tensor[c_dim * i + j] = global_tensor(i, j);\n\t}\n\tdouble const* const k_tensor = tmp_k_tensor;\n\tconst double Ss =\n\t\tMediaProp->StorageFunction(Index, unit, theta);\n\tdouble dummy[3] = {};\n\tdouble const* const lambda_tensor =\n\t\tMediaProp->HeatDispersionTensorNew(0, dummy);\n\tEigen::MatrixXd k(c_dim, c_dim);\n\tfor (unsigned i=0; i<c_dim; i++)\n\t\tfor (unsigned j=0; j<c_dim; j++)\n\t\t\tk(i,j) = k_tensor[i*c_dim + j];\n\tEigen::MatrixXd lambda(c_dim, c_dim);\n\tfor (unsigned i=0; i<c_dim; i++)\n\t\tfor (unsigned j=0; j<c_dim; j++)\n\t\t\tlambda(i,j) = lambda_tensor[i*c_dim + j];\n\tEigen::Vector3d vec_g;\n\tvec_g << 0, 0, -g_const;\n\n\t//======================================================================\n\tEigen::VectorXd r_p(c_nnodes), r_T(c_nnodes);\n\tr_p.setZero();\n\tr_T.setZero();\n\n\t//======================================================================\n\t// Mass lumping\n\tif (isTransient && useLumpedMass)\n\t{\n\t\tconst double vol =\n\t\t\tMeshElement->GetVolume() * MeshElement->GetFluxArea();\n\t\t// Center of the reference element\n\t\tSetCenterGP();\n\t\tComputeShapefct(1);\n\t\tdouble const* const c_shapefct = shapefct;\n\t\tEigen::RowVectorXd N(c_nnodes);\n\t\tN.setZero();\n\t\tfor (int i=0; i<c_nnodes; i++)\n\t\t\tN(i) = c_shapefct[i];\n\t\tconst double gp_p1 = N * nodal_p1;\n\t\tconst double gp_T1 = N * nodal_T1;\n\t\tdouble var[3] = {};\n\t\tvar[0] = gp_p1;\n\t\tvar[1] = gp_T1;\n\t\tconst double rhocp = MediaProp->HeatCapacity(Index, theta, this, var);\n\t\tconst double fkt = vol / (double)nnodes;\n\t\tr_T += rhocp * (nodal_T1 - nodal_T0)/dt * fkt;\n\t}\n\n\t//======================================================================\n\t// Loop over Gauss points\n\tint gp_r, gp_s, gp_t;\n\tdouble var[3] = {};\n\tEigen::RowVectorXd N(c_nnodes);\n\tEigen::RowVectorXd W_T(c_nnodes), W_SUPG(c_nnodes);\n\tEigen::MatrixXd dN(c_dim, c_nnodes);\n\tfor (gp = 0; gp < nGaussPoints; gp++)\n\t{\n\t\t//---------------------------------------------------------\n\t\t//  Get local coordinates and weights\n\t\t//  Compute Jacobian matrix and its determinate\n\t\t//---------------------------------------------------------\n\t\tconst double fkt = GetGaussData(gp, gp_r, gp_s, gp_t);\n\t\t// Compute geometry\n\t\tComputeShapefct(1);\n\t\tComputeGradShapefct(1);\n\t\tdouble const* const c_shapefct = shapefct;\n\t\tdouble const* const c_dshapefct = dshapefct;\n\t\tN.setZero();\n\t\tdN.setZero();\n\t\tfor (int i=0; i<c_nnodes; i++)\n\t\t\tN(i) = c_shapefct[i];\n\t\tfor (unsigned i = 0; i < c_dim; i++)\n\t\t\tfor (int j = 0; j < c_nnodes; j++)\n\t\t\t\tdN(i,j) = c_dshapefct[i * c_nnodes + j];\n\t\tW_T = N;\n\n\t\t//---------------------------------------------------------\n\t\t//  Get state variables\n\t\t//---------------------------------------------------------\n\t\tconst double gp_p0 = N * nodal_p0;\n\t\tconst double gp_T0 = N * nodal_T0;\n\t\tconst double gp_p1 = N * nodal_p1;\n\t\tconst double gp_T1 = N * nodal_T1;\n\t\tEigen::VectorXd grad_p1 = dN * nodal_p1;\n\t\tEigen::VectorXd grad_T1 = dN * nodal_T1;\n\n\t\t//---------------------------------------------------------\n\t\t//  Get material properties\n\t\t//---------------------------------------------------------\n\t\tvar[0] = gp_p1;\n\t\tvar[1] = gp_T1;\n\t\t// Fluid properties\n\t\tconst double rho_w = FluidProp->Density(var);\n\t\tconst double vis = FluidProp->Viscosity(var);\n\t\tconst double cp_w = FluidProp->SpecificHeatCapacity(var);\n\t\t// Medium properties\n\t\tconst double rhocp = MediaProp->HeatCapacity(Index, theta, this, var);\n\n\t\t//---------------------------------------------------------\n\t\t//  Set velocity\n\t\t//---------------------------------------------------------\n\t\tEigen::VectorXd grad_h1 = grad_p1;\n\t\tif (hasGravity)\n\t\t\tgrad_h1 -= rho_w * vec_g;\n\t\tEigen::VectorXd q = - k / vis * grad_h1;\n\n\t\t//---------------------------------------------------------\n\t\t//  SUPG coefficients\n\t\t//---------------------------------------------------------\n\t\tif (useSUPG)\n\t\t{\n\t\t\tW_SUPG.setZero();\n\t\t\tdouble supg_tau = 0;\n\t\t\tCalcSUPGWeightingFunction(&q[0], gp, supg_tau, &W_SUPG[0]);\n\t\t\tW_T += supg_tau * W_SUPG;\n\t\t}\n\n\t\t//---------------------------------------------------------\n\t\t//  Assemble Liquid flow equation\n\t\t//  original: N^T*S*N*dp/dt + dN^T*k/mu*dN*p+dN^T*rho*g*z = 0\n\t\t//---------------------------------------------------------\n\t\t// Rp += [1/dt*N^T*Ss*N + theta*dN^T*k/mu*dN]*p1 -\n\t\t// [1/dt*N^T*Ss*N - (1-theta)*dN^T*k/mu*dN]*p0 +\n\t\t// dN^T*k/mu*rho*g*z\n\t\tif (isTransient)\n\t\t{\n\t\t\t// 1/dt*N^T*Ss*(p1-p0)\n\t\t\tr_p.noalias() += N.transpose() * Ss * (gp_p1 - gp_p0)/dt * fkt;\n\t\t}\n\t\t// - dN^T*vel\n\t\tr_p.noalias() += - fkt * dN.transpose() * q;\n\n\t\t//---------------------------------------------------------\n\t\t//  Assemble Heat transport equation\n\t\t//---------------------------------------------------------\n\n\t\t// Rt += [1/dt*N^T*Cp*N + theta*(dN^T*lambda*dN+N^T*Cp_w*dN)]*T1 -\n\t\t// [1/dt*N^T*Cp*N - (1-theta)*(dN^T*lambda*dN+N^T*Cp_w*dN)]*T0\n\t\tif (isTransient && !useLumpedMass)\n\t\t{\n\t\t\tr_T.noalias() += W_T.transpose() * fkt * rhocp * (gp_T1 - gp_T0)/dt;\n\t\t}\n\t\tr_T.noalias() += fkt * dN.transpose() * lambda * grad_T1;\n\t\tr_T.noalias() += fkt * W_T.transpose() * rho_w * cp_w * q.transpose() * grad_T1;\n\t}\n\n\tif (isMatrixElement && isMatrixFlowInactive)\n\t\tr_p.setZero();\n\n\tfor (int i = 0; i < c_nnodes; i++)\n\t{\n\t\t(*RHS)(offset_p + i) = r_p[i];\n\t\t(*RHS)(offset_T + i) = r_T[i];\n\t}\n\n\tif (pcs->scaleEQS)\n\t{\n\t\tfor (int ii = 0; ii < 2; ii++)\n\t\t{\n\t\t\tconst double scale_eqs = pcs->vec_scale_eqs[ii];\n\t\t\tfor (int i = 0; i < c_nnodes; i++)\n\t\t\t\t(*RHS)(ii* c_nnodes + i) *= scale_eqs;\n\t\t}\n\t}\n\n\t// RHS should be - residual\n\t(*RHS) *= -1.;\n\n#ifdef NEW_EQS\n\tfor (size_t ii = 0; ii < pcs->GetPrimaryVNumber(); ii++)\n\t\tfor (long i = 0; i < c_nnodes; i++)\n\t\t\teqs_rhs[NodeShift[ii] + eqs_number[i]] += (*RHS)(i + ii * c_nnodes);\n#endif\n}\n\nvoid CFiniteElementStd::AssembleTHJacobian()\n{\n\tconst unsigned c_dim = dim;\n\tconst int c_nnodes = nnodes;\n\tconst double dt = pcs->Tim->time_step_length;\n\tconst double theta = pcs->m_num->ls_theta;\n\tconst bool hasGravity =\n\t\t(coordinate_system) % 10 == 2 && FluidProp->CheckGravityCalculation();\n\tconst double g_const = hasGravity ? gravity_constant : .0;\n\tconst bool useSUPG = (pcs->m_num->ele_supg_method > 0);\n\tconst bool useLumpedMass = (pcs->m_num->ele_mass_lumping > 0);\n\tconst bool isTransient =\n\t\t(this->pcs->tim_type == FiniteElement::TIM_TRANSIENT);\n\tconst bool isMatrixFlowInactive = pcs->deactivateMatrixFlow;\n\tconst bool isMatrixElement = (MeshElement->GetDimension() == pcs->m_msh->GetMaxElementDim());\n\n\tMatrix t_transform_tensor(3, 3);\n\tif (dim > MediaProp->geo_dimension)\n\t{\n\t\tif (MeshElement->getTransformTensor() == NULL)\n\t\t{\n\t\t\tstd::cout << \"***Error: Geometric dimension in MMP is not \"\n\t\t\t\t\t\t \"consistent with element.\"\n\t\t\t\t\t  << \"\\n\";\n\t\t\texit(0);\n\t\t}\n\t\tt_transform_tensor.LimitSize(dim, dim);\n\t\tMeshElement->getTransformTensor()->GetTranspose(t_transform_tensor);\n\t}\n\n\tEigen::VectorXd nodal_p0(nnodes), nodal_p1(nnodes);\n\tEigen::VectorXd nodal_T0(nnodes), nodal_T1(nnodes);\n\tfor (int i = 0; i < nnodes; i++)\n\t{\n\t\tnodal_p0[i] = pcs->GetNodeValue(nodes[i], idxp0);\n\t\tnodal_p1[i] = pcs->GetNodeValue(nodes[i], idxp1);\n\t\tnodal_T0[i] = pcs->GetNodeValue(nodes[i], idxT0);\n\t\tnodal_T1[i] = pcs->GetNodeValue(nodes[i], idxT1);\n\t}\n\n\t// Calculate matrices\n\tconst int offset_p = 0;\n\tconst int offset_T = c_nnodes;\n\t(*StiffMatrix) = 0.0;  // Jacobian\n\n//#define TH_DEBUG\n#ifdef TH_DEBUG\n\t// for debugging\n\tMass->LimitSize(nnodes, nnodes);\n\tLaplace->LimitSize(nnodes, nnodes);\n\tAdvection->LimitSize(nnodes, nnodes);\n\t(*Mass) = .0;\n\t(*Laplace) = .0;\n\t(*Advection) = .0;\n#endif\n\tdouble* tmp_k_tensor = MediaProp->PermeabilityTensor(Index);\n\tif (c_dim > MediaProp->geo_dimension)\n\t{\n\t\tMatrix local_tensor(c_dim, c_dim), temp_tensor(c_dim, c_dim),\n\t\t\tglobal_tensor(c_dim, c_dim);\n\t\tconst unsigned c_ele_dim = ele_dim;\n\t\tfor (size_t i = 0; i < c_ele_dim; i++)\n\t\t\tfor (size_t j = 0; j < c_ele_dim; j++)\n\t\t\t\tlocal_tensor(i, j) = tmp_k_tensor[j + i * c_ele_dim];\n\t\t// cout << \"K':\" << endl; local_tensor.Write();\n\t\tlocal_tensor.multi(t_transform_tensor, temp_tensor);\n\t\tfor (size_t i = 0; i < c_dim; i++)\n\t\t\tfor (size_t j = 0; j < c_dim; j++)\n\t\t\t\tfor (size_t k = 0; k < c_dim; k++)\n\t\t\t\t\tglobal_tensor(i, j) +=\n\t\t\t\t\t\t(*MeshElement->getTransformTensor())(i, k) *\n\t\t\t\t\t\ttemp_tensor(k, j);\n\t\t// cout << \"K:\" << endl; global_tensor.Write();\n\t\tfor (size_t i = 0; i < c_dim; i++)\n\t\t\tfor (size_t j = 0; j < c_dim; j++)\n\t\t\t\ttmp_k_tensor[c_dim * i + j] = global_tensor(i, j);\n\t}\n\tdouble const* const k_tensor = tmp_k_tensor;\n\tconst double Ss = MediaProp->StorageFunction(Index, unit, theta);\n\tdouble dummy[3] = {};\n\tdouble const* const lambda_tensor =\n\t\tMediaProp->HeatDispersionTensorNew(0, dummy);\n\tEigen::MatrixXd k(c_dim, c_dim);\n\tfor (unsigned i=0; i<c_dim; i++)\n\t\tfor (unsigned j=0; j<c_dim; j++)\n\t\t\tk(i,j) = k_tensor[i*c_dim + j];\n\tEigen::MatrixXd lambda(c_dim, c_dim);\n\tfor (unsigned i=0; i<c_dim; i++)\n\t\tfor (unsigned j=0; j<c_dim; j++)\n\t\t\tlambda(i,j) = lambda_tensor[i*c_dim + j];\n\tEigen::Vector3d vec_g;\n\tvec_g << 0, 0, -g_const;\n\n\t//======================================================================\n\tEigen::MatrixXd J_pp(c_nnodes, c_nnodes), J_pT(c_nnodes, c_nnodes);\n\tEigen::MatrixXd J_Tp(c_nnodes, c_nnodes), J_TT(c_nnodes, c_nnodes);\n\tJ_pp.setZero();\n\tJ_pT.setZero();\n\tJ_Tp.setZero();\n\tJ_TT.setZero();\n\n\t//======================================================================\n\t// Mass lumping\n\tif (isTransient && useLumpedMass)\n\t{\n\t\tconst double vol =\n\t\t\tMeshElement->GetVolume() * MeshElement->GetFluxArea();\n\t\t// Center of the reference element\n\t\tSetCenterGP();\n\t\tComputeShapefct(1);\n\t\tdouble const* const c_shapefct = shapefct;\n\t\tEigen::RowVectorXd N(c_nnodes);\n\t\tN.setZero();\n\t\tfor (int i=0; i<c_nnodes; i++)\n\t\t\tN(i) = c_shapefct[i];\n\t\tconst double gp_p1 = N * nodal_p1;\n\t\tconst double gp_T1 = N * nodal_T1;\n\t\tdouble var[3] = {};\n\t\tvar[0] = gp_p1;\n\t\tvar[1] = gp_T1;\n\t\tconst double rhocp = MediaProp->HeatCapacity(Index, theta, this, var);\n\t\tconst double drho_w_dp = FluidProp->drhodP(var);\n\t\tconst double drho_w_dT = FluidProp->drhodT(var);\n\t\tconst double cp_w = FluidProp->SpecificHeatCapacity(var);\n\t\tconst double porosity = MediaProp->Porosity(Index, theta);\n\t\tconst double drhocp_dp = porosity * cp_w * drho_w_dp;\n\t\tconst double drhocp_dT = porosity * cp_w * drho_w_dT;\n\t\tconst double fkt = vol / (double)nnodes;\n\t\tJ_TT.diagonal().setConstant(1/dt * rhocp * fkt);\n\t\tJ_TT += fkt * drhocp_dT * (nodal_T1 - nodal_T0)/dt * N;\n\t\tJ_Tp += fkt * drhocp_dp * (nodal_T1 - nodal_T0)/dt * N;\n\t}\n\n\t//======================================================================\n\t// Loop over Gauss points\n\tint gp_r, gp_s, gp_t;\n\tdouble var[3] = {};\n\tEigen::RowVectorXd N(c_nnodes);\n\tEigen::MatrixXd dN(c_dim, c_nnodes);\n\tEigen::RowVectorXd W_T(c_nnodes), W_SUPG(c_nnodes);\n\tfor (gp = 0; gp < nGaussPoints; gp++)\n\t{\n\t\t//---------------------------------------------------------\n\t\t//  Get local coordinates and weights\n\t\t//  Compute Jacobian matrix and its determinate\n\t\t//---------------------------------------------------------\n\t\tconst double fkt = GetGaussData(gp, gp_r, gp_s, gp_t);\n\t\t// Compute geometry\n\t\tComputeShapefct(1);\n\t\tComputeGradShapefct(1);\n\t\tdouble const* const c_shapefct = shapefct;\n\t\tdouble const* const c_dshapefct = dshapefct;\n\t\tN.setZero();\n\t\tdN.setZero();\n\t\tfor (int i=0; i<c_nnodes; i++)\n\t\t\tN(i) = c_shapefct[i];\n\t\tfor (unsigned i = 0; i < c_dim; i++)\n\t\t\tfor (int j = 0; j < c_nnodes; j++)\n\t\t\t\tdN(i,j) = c_dshapefct[i * c_nnodes + j];\n\t\tW_T = N;\n\n\t\t//---------------------------------------------------------\n\t\t//  Get state variables\n\t\t//---------------------------------------------------------\n\t\t// const double gp_p0 = N * nodal_p0;\n\t\tconst double gp_T0 = N * nodal_T0;\n\t\tconst double gp_p1 = N * nodal_p1;\n\t\tconst double gp_T1 = N * nodal_T1;\n\t\t//const double gp_dp = gp_p1 - gp_p0;\n\t\tconst double gp_dT = gp_T1 - gp_T0;\n\t\t//Eigen::VectorXd grad_p0 = dN * nodal_p0;\n\t\tEigen::VectorXd grad_p1 = dN * nodal_p1;\n\t\t//Eigen::VectorXd grad_T0 = dN * nodal_T0;\n\t\tEigen::VectorXd grad_T1 = dN * nodal_T1;\n\t\tif (pcs->m_num->nls_jacobian_level == 1)\n\t\t\tgrad_T1.setZero();\n\n\t\t//---------------------------------------------------------\n\t\t//  Get material properties\n\t\t//---------------------------------------------------------\n\t\tvar[0] = gp_p1;\n\t\tvar[1] = gp_T1;\n\t\t// Fluid properties\n\t\tconst double rho_w = FluidProp->Density(var);\n\t\tconst double drho_w_dp = FluidProp->drhodP(var);\n\t\tconst double drho_w_dT = FluidProp->drhodT(var);\n\t\tconst double vis = FluidProp->Viscosity(var);\n\t\tconst double dvis_dp = FluidProp->dViscositydP(var);\n\t\tconst double dvis_dT = FluidProp->dViscositydT(var);\n\t\tconst double cp_w = FluidProp->SpecificHeatCapacity(var);\n\t\t// Medium properties\n\t\tconst double rhocp = MediaProp->HeatCapacity(Index, theta, this, var);\n\t\tconst double porosity = MediaProp->Porosity(Index, theta);\n\t\tconst double drhocp_dp = porosity * cp_w * drho_w_dp; //TODO d(cp)/dp\n\t\tconst double drhocp_dT = porosity * cp_w * drho_w_dT;\n\n\t\t//---------------------------------------------------------\n\t\t//  Set velocity\n\t\t//---------------------------------------------------------\n\t\tEigen::VectorXd grad_h1 = grad_p1;\n\t\tif (hasGravity)\n\t\t\tgrad_h1 -= rho_w * vec_g;\n\t\tEigen::VectorXd q = - k / vis * grad_h1;\n\n\t\t//-----------------------------------------\n\t\t// Derivatives of flow velocity and heat flux\n\t\t//-----------------------------------------\n\t\tEigen::MatrixXd dq_dp = - k / vis * dN;\n\t\tif (hasGravity && drho_w_dp != 0.0)\n\t\t\tdq_dp.noalias() += - k / vis * drho_w_dp * vec_g * N;\n\t\tif (dvis_dp != 0.0)\n\t\t\tdq_dp.noalias() += - dvis_dp / vis * q * N;\n\t\tEigen::MatrixXd dq_dT = - dvis_dT * q * N;\n\t\tif (hasGravity && drho_w_dT != 0.0)\n\t\t\tdq_dT.noalias() += - k / vis * drho_w_dT * vec_g * N;\n\n\t\tEigen::MatrixXd djDiff_dT = - lambda * dN;\n\t\tEigen::MatrixXd djAdv_dT = rhocp * q.transpose() * dN;\n\t\tif (dq_dT.size() > 0)\n\t\t\tdjAdv_dT.noalias() += rhocp * grad_T1.transpose() * dq_dT;\n\t\tif (drho_w_dT != .0)\n\t\t\tdjAdv_dT.noalias() += drhocp_dT * q.transpose() * grad_T1 * N;\n\t\tEigen::MatrixXd djAdv_dp = rhocp * grad_T1.transpose() * dq_dp;\n\t\tif (drho_w_dp != .0)\n\t\t\tdjAdv_dp.noalias() += drhocp_dp * q.transpose() * grad_T1 * N;\n\n\t\t//---------------------------------------------------------\n\t\t//  SUPG coefficients\n\t\t//---------------------------------------------------------\n\t\tif (useSUPG)\n\t\t{\n\t\t\tW_SUPG.setZero();\n\t\t\tdouble supg_tau = 0;\n\t\t\tCalcSUPGWeightingFunction(&q[0], gp, supg_tau, &W_SUPG[0]);\n\t\t\tW_T += supg_tau * W_SUPG;\n\t\t}\n\n\t\t//---------------------------------------------------------\n\t\t//  Assemble Jacobian\n\t\t//---------------------------------------------------------\n\n\t\tif (isTransient)\n\t\t\tJ_pp.noalias() += 1/dt * fkt * N.transpose() * Ss * N;\n\t\tJ_pp.noalias() += - fkt * dN.transpose() * dq_dp;\n\t\tif (dq_dT.size() > 0)\n\t\t\tJ_pT.noalias() += - fkt * dN.transpose() * dq_dT;\n\n\t\tif (isTransient && !useLumpedMass)\n\t\t\tJ_TT.noalias() += 1/dt * W_T.transpose() * (rhocp + gp_dT * drhocp_dT) * N * fkt;\n\t\tJ_TT.noalias() += - dN.transpose() * djDiff_dT * fkt;\n\t\tJ_TT.noalias() += W_T.transpose() * djAdv_dT * fkt;\n\t\tif (isTransient && !useLumpedMass)\n\t\t\tJ_Tp.noalias() += 1/dt * W_T.transpose() * (gp_dT * drhocp_dp) * N * fkt;\n\t\tJ_Tp.noalias() += W_T.transpose() * djAdv_dp * fkt;\n\t}\n\n\tif (isMatrixElement && isMatrixFlowInactive)\n\t{\n\t\tJ_pp.setZero();\n\t\tJ_pT.setZero();\n\t\tJ_Tp.setZero();\n\t}\n\n\tfor (int i=0; i<c_nnodes; i++)\n\t{\n\t\tfor (int j=0; j<c_nnodes; j++)\n\t\t{\n\t\t\t(*StiffMatrix)(offset_p + i, offset_p + j) = J_pp(i, j);\n\t\t\t(*StiffMatrix)(offset_p + i, offset_T + j) = J_pT(i, j);\n\t\t\t(*StiffMatrix)(offset_T + i, offset_p + j) = J_Tp(i, j);\n\t\t\t(*StiffMatrix)(offset_T + i, offset_T + j) = J_TT(i, j);\n\t\t}\n\t}\n\n\tif (pcs->scaleUnknowns || pcs->scaleEQS)\n\t{\n\t\t// scale p by 1e6\n\t\tconst double scale_p =\n\t\t\t1. / pcs->vec_scale_dofs[0] * pcs->vec_scale_eqs[0];\n\t\tfor (long i = 0; i < c_nnodes; i++)\n\t\t\tfor (long j = 0; j < c_nnodes; j++)\n\t\t\t{\n\t\t\t\t(*StiffMatrix)(i, j) *= scale_p;\n\t\t\t\t(*StiffMatrix)(i, j + c_nnodes) *= scale_p;\n\t\t\t\t//\t\t\t\t(*StiffMatrix)(i+c_nnodes,j) *= scale_p;\n\t\t\t}\n\t\t// scale T\n\t\tconst double scale_T =\n\t\t\t1. / pcs->vec_scale_dofs[1] * pcs->vec_scale_eqs[1];\n\t\tfor (long i = 0; i < c_nnodes; i++)\n\t\t\tfor (long j = 0; j < c_nnodes; j++)\n\t\t\t{\n\t\t\t\t(*StiffMatrix)(i + c_nnodes, j) *= scale_T;\n\t\t\t\t(*StiffMatrix)(i + c_nnodes, j + c_nnodes) *= scale_T;\n\t\t\t\t//\t\t\t\t(*StiffMatrix)(i,j+c_nnodes) *= scale_T;\n\t\t\t\t//\t\t\t\t(*StiffMatrix)(i+c_nnodes,j+c_nnodes) *=\n\t\t\t\t// scale_T;\n\t\t\t}\n\t}\n}\n\n}  // end namespace\n\n", "meta": {"hexsha": "9e0f37874a5b56ef1b4dc0fbcf59e3df868b0709", "size": 19267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FEM/fem_ele_std_TH.cpp", "max_stars_repo_name": "norihiro-w/ogs5-egs", "max_stars_repo_head_hexsha": "ed71af0b8410e8ef13302081443c91ca69982ac1", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-03-19T04:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-15T15:56:02.000Z", "max_issues_repo_path": "FEM/fem_ele_std_TH.cpp", "max_issues_repo_name": "norihiro-w/ogs5-egs", "max_issues_repo_head_hexsha": "ed71af0b8410e8ef13302081443c91ca69982ac1", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-06-29T08:57:08.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-04T00:42:51.000Z", "max_forks_repo_path": "FEM/fem_ele_std_TH.cpp", "max_forks_repo_name": "norihiro-w/ogs5-egs", "max_forks_repo_head_hexsha": "ed71af0b8410e8ef13302081443c91ca69982ac1", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-16T10:52:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-16T10:52:58.000Z", "avg_line_length": 33.6247818499, "max_line_length": 94, "alphanum_fraction": 0.5748689469, "num_tokens": 6164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.5033894896953561}}
{"text": "#include <iostream>\n#include <boost/math/common_factor.hpp>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t    long long a,b;\n\t    cin>>a>>b;\n\t    cout<<boost::math::gcd(a,b)<<\" \"<<boost::math::lcm(a,b)<<\"\\n\" ;\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "d8c9fc9c0dd9b6a76dadbc4bfb5498fc7fbe3dcd", "size": 272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "55779652.cpp", "max_stars_repo_name": "arvindbis29/codechef_repo", "max_stars_repo_head_hexsha": "e8d87776de5301267bd7baca568e984f47fd0c20", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-06T16:34:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T16:34:36.000Z", "max_issues_repo_path": "55779652.cpp", "max_issues_repo_name": "arvindbis29/codechef_repo", "max_issues_repo_head_hexsha": "e8d87776de5301267bd7baca568e984f47fd0c20", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-06T17:04:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T17:04:45.000Z", "max_forks_repo_path": "55779652.cpp", "max_forks_repo_name": "arvindbis29/codechef_repo", "max_forks_repo_head_hexsha": "e8d87776de5301267bd7baca568e984f47fd0c20", "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.0, "max_line_length": 68, "alphanum_fraction": 0.5735294118, "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.5033894786666674}}
{"text": "\n#include \"headers/Triangle.hpp\"\n#include \"headers/Object.hpp\"\n#include \"headers/Hittable.hpp\"\n#include <armadillo>\n#include <vector>\n\nusing namespace arma;\nusing namespace std;\n\nTriangle::Triangle (vec triangulo){\n    \n    mat transf;\n    vec kd, ks, aux;\n    \n    transf << triangulo(16) << triangulo(17) << triangulo(18) << triangulo(19) << endr\n\t   << triangulo(20) << triangulo(21) << triangulo(22) << triangulo(23) << endr \n           << triangulo(24) << triangulo(25) << triangulo(26) << triangulo(27) << endr\n           << 0 << 0 << 0 << 1;\n\n    this->setTransf(transf);  \n  \n    aux << triangulo(0) << triangulo(1) << triangulo(2) << 1;\n    aux = transf * aux;\n    aux.shed_row(3);\n     \n    this->setA(aux);\n//    this->setA(triangulo(0) << triangulo(1) << triangulo(2) << 1);\n//    this->setA(transf * this->getA());\n//    this->setA(this->getA().shed_row(3));\n\t\n    aux << triangulo(3) << triangulo(4) << triangulo(5) << 1;\n    aux = transf * aux;\n    aux.shed_row(3);\n     \n    this->setB(aux);\n    \n//    this->setB(triangulo(3) << triangulo(4) << triangulo(5) << 1);\n//    this->setB(transf * this->getB());\n//    this->setB(this->getB().shed_row(3));\n\t\n    aux << triangulo(6) << triangulo(7) << triangulo(8) << 1;\n    aux = transf * aux;\n    aux.shed_row(3);\n     \n    this->setC(aux);\n    \n//    this->setC(triangulo(6) << triangulo(7) << triangulo(8) << 1);\n//    this->setC(transf * this->getC());\n//    this->setC(this->getC().shed_row(3));\n\t\n    kd << triangulo(9) << triangulo(10) << triangulo(11);\n    ks << triangulo(12) << triangulo(13) << triangulo(14);\n    \n    this->setKd(kd);\n    this->setKs(ks);\n        \n    this->setP(triangulo(15));\n    \n    this->setTipo(1);\n\t\n    this->setCentro((this->getA() + this->getB() + this->getC())/3);\n    \n    this->setNormal(cross(this->getB() - this->getA(), this->getC() - this->getA()));\n}\n\nbool Triangle::colide(const vec &d, double &T, const vec &origem){\n    \n    vec tuv;\n    mat matriz1, matriz2;\n\n    matriz1.insert_cols(0, origem-d);\n    matriz1.insert_cols(1, this->B - this->A);\n    matriz1.insert_cols(2, this->C - this->A);\n\t      \n    if ((det(matriz1)>0.000001) || (det(matriz1)<-0.000001)){\n        \n        matriz2 = origem - this->A;\n  \n\ttuv = matriz1.i() * matriz2;\n\n\tif ((tuv(1)>=0) && (tuv(1)<=1) && (tuv(2)>=0) && (tuv(2)<=1) && (tuv(1)+tuv(2)<=1)){\n            \n            T=tuv(0); \n            setNormal(normalise(getNormal()));\n            \n            return true;\n\t}\n    }\n    \n    return false;\n}\n\n\n", "meta": {"hexsha": "0d77f45112b71ed8be39eccdfc8ec3c1984d3fb1", "size": 2496, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "raytracing/Triangle.cpp", "max_stars_repo_name": "arthurflor/RayTracing", "max_stars_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-19T09:38:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T02:04:22.000Z", "max_issues_repo_path": "raytracing/Triangle.cpp", "max_issues_repo_name": "arthurflor23/ray-tracing", "max_issues_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "raytracing/Triangle.cpp", "max_forks_repo_name": "arthurflor23/ray-tracing", "max_forks_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_forks_repo_licenses": ["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.2736842105, "max_line_length": 86, "alphanum_fraction": 0.5380608974, "num_tokens": 840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5033270205004041}}
{"text": "#include <Eigen/Core>\n#include <list>\n#include <map>\n#include <random>\n#include \"rose499/world.hpp\"\n\nnamespace geom = boost::geometry;\n\nusing Point = World::Point;\nusing TaggedPoint = std::pair< Point, int >;\n\nnamespace\n{\n    std::mt19937_64 engine(0x1EA5ECED);\n}\n\nstd::list< Point > planRRT(     World::RTree knownWorld,\n                                double xMax,\n                                double yMax,\n                                Point initialPoint,\n                                double direction,\n                                Point goal,\n                                double radius )\n{\n    std::uniform_real_distribution<> samplerX(0, xMax), samplerY(0, yMax);\n\n    TaggedPoint lastPoint(initialPoint, 0);\n    double closestDist = std::max(xMax, yMax);\n\n    geom::index::rtree< TaggedPoint, geom::index::linear<5, 1> > setPoints;\n    std::map< uint32_t, uint32_t > backEdges;\n    std::vector< TaggedPoint > listPoints;\n    std::vector< TaggedPoint > setNearest;\n    std::vector< std::pair<World::Box, int> > setCollisions;\n\n    setPoints.insert( lastPoint );\n    listPoints.push_back( lastPoint );\n    int indTaggedPoint = 1;\n    while( Eigen::Vector2d( lastPoint.first.get<0>() - goal.get<0>(),\n                            lastPoint.first.get<1>() - goal.get<1>() ).norm() >= radius )\n    {\n        setNearest.clear();\n        setCollisions.clear();\n\n        std::normal_distribution<> importanceSamplerX(goal.get<0>(), closestDist),\n                                   importanceSamplerY(goal.get<1>(), closestDist);\n        auto x = importanceSamplerX(engine);\n        auto y = importanceSamplerY(engine);\n\n      if( x > xMax || x < 0 || y > yMax || y < 0 ) { continue; }\n\n        auto randomPoint = TaggedPoint(Point(x, y), indTaggedPoint);\n        Eigen::Vector2d eigRandomPoint(randomPoint.first.get<0>(), randomPoint.first.get<1>());\n\n        // Just make sure this isn't a crap point that is inside an obstacle.\n        knownWorld.query( geom::index::intersects(randomPoint.first), std::back_inserter(setCollisions));\n\n      if( !setCollisions.empty() ) { continue; }\n\n        // find nearest point in our set\n        setPoints.query( geom::index::nearest(randomPoint.first, 10), std::back_inserter(setNearest) );\n\n        // Filter out points that are either too close OR do not fan out from the source point.\n        auto endSetNearest =\n            std::remove_if(\n                setNearest.begin(),\n                setNearest.end(),\n                [direction, eigRandomPoint, &backEdges, &listPoints]( TaggedPoint nearest ) -> bool {\n                    Eigen::Vector2d eigNearest(nearest.first.get<0>(), nearest.first.get<1>());\n                    Eigen::Vector2d eigFrom(std::cos(direction), std::sin(direction));\n                    Eigen::Vector2d vecLeaving = eigRandomPoint - eigNearest;\n                    Eigen::Vector2d vecEntering = eigFrom;\n\n                    if( nearest.second != 0 )\n                    {\n                        auto fromPoint = listPoints[backEdges[nearest.second]];\n                        eigFrom = Eigen::Vector2d(fromPoint.first.get<0>(), fromPoint.first.get<1>());\n                        vecEntering = eigNearest - eigFrom;\n                    }\n\n                    double proj = vecLeaving.dot(vecEntering) / (vecLeaving.norm() * vecEntering.norm());\n\n                    return (vecLeaving.dot(vecEntering) < 0)\n                        || (std::acos(proj) > std::atan2(1, 1))\n                        ;//|| (vecLeaving.norm() < 1);\n                }\n            );\n        setNearest.erase(endSetNearest, setNearest.end());\n\n      if( setNearest.empty() ) { continue; }\n\n        std::sort(  setNearest.begin(),\n                    setNearest.end(),\n                    [eigRandomPoint](TaggedPoint a, TaggedPoint b) -> bool {\n                        return  (Eigen::Vector2d(a.first.get<0>(), a.first.get<1>()) - eigRandomPoint).squaredNorm()\n                                <\n                                (Eigen::Vector2d(b.first.get<0>(), b.first.get<1>()) - eigRandomPoint).squaredNorm();\n                    } );\n        TaggedPoint nearestPoint = setNearest.front();\n\n        // gotta make sure the path is obstacle free\n        geom::model::segment< World::Point > lineTo(nearestPoint.first, randomPoint.first);\n        knownWorld.query( geom::index::intersects(lineTo), std::back_inserter(setCollisions));\n\n      if( !setCollisions.empty() ) { continue; }\n\n        closestDist = std::min( closestDist,\n                        std::max( std::abs(nearestPoint.first.get<0>() - goal.get<0>()),\n                                  std::abs(nearestPoint.first.get<1>() - goal.get<1>()) )\n                      );\n\n        setPoints.insert(randomPoint);\n        listPoints.push_back(randomPoint);\n        backEdges[randomPoint.second] = nearestPoint.second;\n        indTaggedPoint++;\n        lastPoint = randomPoint;\n    }\n\n    // Build path from back edges\n    std::list< Point > path;\n    int tag = 0;\n    while( (tag = lastPoint.second) != 0 )\n    {\n        path.push_front(lastPoint.first);\n        lastPoint = listPoints[backEdges[tag]];\n    }\n    path.push_front(lastPoint.first);\n    return path;\n}\n", "meta": {"hexsha": "61b14bd0885d5a7aaf36f54d94836db58edbf69b", "size": 5187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/src/plan.cpp", "max_stars_repo_name": "rollends/SE499", "max_stars_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulator/src/plan.cpp", "max_issues_repo_name": "rollends/SE499", "max_issues_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulator/src/plan.cpp", "max_forks_repo_name": "rollends/SE499", "max_forks_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_forks_repo_licenses": ["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.9, "max_line_length": 117, "alphanum_fraction": 0.5552342394, "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545427, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5033270111339148}}
{"text": "\n#include <iostream>\n#include <iomanip>\n#include <Eigen/Dense>\n#include <ctime>\n#include <chrono>\n#include <map>\n#include <random>\n#include <cstdio> // popen\n#include <cstring> // memset\n\n#include \"Neural_Net.hpp\"\n#include \"FNN_Model.hpp\"\n#include \"MNIST_Parser.hpp\"\n#include \"gnuplot_i.hpp\"\n\nint main(int argc, char *argv[])\n{\n\n  /*std::vector<unsigned int> layers;\n  layers.push_back(1);\n  layers.push_back(1);\n  FNN_Model my_net(layers);\n\n  std::vector<Eigen::MatrixXd> weights;\n  std::vector<Eigen::MatrixXd> bias;\n  weights.push_back(Eigen::MatrixXd());\n  weights.push_back(Eigen::MatrixXd::Constant(1, 1, 2.0));\n  bias.push_back(Eigen::MatrixXd());\n  bias.push_back(Eigen::MatrixXd::Constant(1, 1, 2.0));\n  my_net.Manual_Set_FNN(weights, bias);\n  Eigen::MatrixXd input = Eigen::MatrixXd::Constant(1, 1, 1);\n  Eigen::MatrixXd output = Eigen::MatrixXd::Constant(1, 1, 0);\n  Eigen::MatrixXd eval_input = Eigen::MatrixXd::Constant(1, 1, 1);\n  Eigen::MatrixXd eval_output = Eigen::MatrixXd::Constant(1, 1, 0);\n\n  int goOn=1;\n  int ch = 0;\n  while(goOn)\n  {\n    ch = wait_for_key();\n    if (ch == 'q')\n    {\n      goOn = 0;\n      my_net.train_thread.wait();\n    }\n    else if (ch == 'c') {\n      my_net.train(input, output, 300, 1, 0.15, eval_input, eval_output);\n    }\n  }*/\n  \n     MNIST_Parser my_parser;\n     Eigen::MatrixXd train_images(0, 0);\n     Eigen::MatrixXd train_labels(0, 0);\n     Eigen::MatrixXd eval_images(0, 0);\n     Eigen::MatrixXd eval_labels(0, 0);\n     std::cout << \"Reading MNIST data ...\" << std::endl;\n     my_parser.read_train_img(train_images);\n     my_parser.read_train_label(train_labels);\n     my_parser.read_eval_img(eval_images);\n     my_parser.read_eval_label(eval_labels);\n  //std::cout << train_images.col(1) << std::endl; \n\n  std::vector<unsigned int> layers;\n  layers.push_back(784);\n  layers.push_back(30);\n  layers.push_back(10);\n  FNN_Model my_net(layers);\n  std::cout << \"Training Forward Neural Net ...\" << std::endl;\n  my_net.train(train_images, train_labels, 30, 10, 3.0, eval_images, eval_labels);\n  \n  /*\n     std::vector<unsigned int> layers;\n     layers.push_back(2);\n     layers.push_back(3);\n     layers.push_back(1);\n     FNN_Model my_net(layers);\n     my_net.print_FNN();\n     */\n\n\n  return 0;\n}\n\n", "meta": {"hexsha": "7c2ee0fc7f956c7abe9c8f084727153fed814716", "size": 2249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "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": "src/main.cpp", "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": "src/main.cpp", "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": 26.4588235294, "max_line_length": 82, "alphanum_fraction": 0.6602934638, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5033270111339146}}
{"text": "#pragma once\n#include <random>\n#include <boost/range/algorithm_ext/erase.hpp>\n\nstd::mt19937_64 mt_grid(265278465287);\n\n#define PATH_TO_GRID_POINTS_SOURCE \"GRID_POINTS_SOURCE\"\nstd::vector<std::tuple<theta_<double>,phi_<double> > > generate_random_theta_phi();\nstd::vector<std::list<size_t> > get_network(const std::vector<std::tuple<theta_<double>,phi_<double> > >& ps);\n\ninline Vector3D S2R (const std::tuple<theta_<double>,phi_<double> >& p)\n{\n   return Vector3D\n      (\n         std::sin(std::get<theta_<double>>(p).value())*std::cos(std::get<phi_<double> >(p).value()),\n         std::sin(std::get<theta_<double>>(p).value())*std::sin(std::get<phi_<double> >(p).value()),\n         std::cos(std::get<theta_<double>>(p).value())\n      ); \n};\n\nstd::vector<std::tuple<theta_<double>,phi_<double> > > generate_random_theta_phi()\n{\n   {//load it\n      std::vector< std::tuple<theta_<double>,phi_<double> > > loaded_random_points;\n      try\n      {\n         Getline gl(PATH_TO_GRID_POINTS_SOURCE);\n         std::string tmp;\n         while(gl.is_open())\n         {\n            tmp=gl.get();\n            std::vector<std::string> vs;\n            boost::algorithm::split(vs,tmp,boost::is_any_of(\" \"));\n            loaded_random_points.push_back\n               (\n                  {\n                     theta_<double>(boost::lexical_cast<double> (vs.at(0))),\n                     phi_<double>(  boost::lexical_cast<double> (vs.at(1)))\n                  }\n               );\n         }\n      }catch(...)\n      {\n      }\n      if(loaded_random_points.size()==N_GRID_POINTS)\n      {\n         return loaded_random_points;\n      }\n   }\n\n   std::vector< std::tuple<theta_<double>,phi_<double> > > random_points(N_GRID_POINTS);\n   std::uniform_real_distribution<double> dist_theta(0.0,  M_PI);\n   std::uniform_real_distribution<double> dist_phi(  0.0,2*M_PI);\n   for(size_t i=0;i<N_GRID_POINTS;++i)\n   {\n      std::get<theta_<double> >(random_points.at(i)).value() = dist_theta(mt_grid);\n      std::get<phi_<double>   >(random_points.at(i)).value() = dist_phi(mt_grid);\n   }\n\n   const auto LJ = [](const double& distance)->double\n   {\n      const auto res = std::pow(1.0/distance,6);\n      return res;\n   };\n\n   const auto E_system = [&]\n   (\n      bool is_virtual, size_t pos=0, \n      std::tuple<theta_<double>,phi_<double> > p = std::tuple<theta_<double>,phi_<double> >(0.0,0.0)\n   )->double\n   {\n      double E=0.0; \n      for(size_t i=0,size=random_points.size();i<size;++i)\n      for(size_t j=i+1;j<size;++j)\n      {\n         const std::tuple<theta_<double>,phi_<double> >& p_i = (!is_virtual)?(random_points.at(i)):((pos==i)?p:random_points.at(i)); \n         const std::tuple<theta_<double>,phi_<double> >& p_j = (!is_virtual)?(random_points.at(j)):((pos==j)?p:random_points.at(j)); \n         E+=LJ((S2R(p_i)-S2R(p_j)).norm());\n      }\n      return E;\n   };\n\n   constexpr int N_STEP    = 10000*N_GRID_POINTS;\n   constexpr int DOWN_STEP = N_STEP/10;\n   double kT = 1000.0;\n   double kT_=kT/10;\n   double E_current = E_system(false);\n   constexpr double DELTA_THETA =   M_PI/100;\n   constexpr double DELTA_PHI   = 2*M_PI/100;\n   std::uniform_int_distribution<int>     dist_pos(0,N_GRID_POINTS-1);\n   std::uniform_real_distribution<double> dist_delta_theta(-DELTA_THETA,+DELTA_THETA);\n   std::uniform_real_distribution<double> dist_delta_phi(  -DELTA_PHI,  +DELTA_PHI);\n   std::uniform_real_distribution<double> dist_p(0,1.0);\n   int s_=0;\n   for(int s=0;s<N_STEP;++s)\n   {\n      if((s_%DOWN_STEP)==0){s_=0;kT-=kT_;}\n      const int pos = dist_pos(mt_grid);\n      const auto stock = random_points.at(pos);\n      const std::tuple<theta_<double>,phi_<double> > pnew\n         (\n            std::get<theta_<double> >(stock).value()+dist_delta_theta(mt_grid),\n            std::get<phi_<double>   >(stock).value()+dist_delta_phi(mt_grid)\n         );\n      const double E_new = E_system(true,pos,pnew);\n      const double DE    = E_new-E_current;\n      if(DE<=0.0)\n      {\n         random_points.at(pos)=pnew;\n         E_current=E_new;\n      }\n      else\n      {\n         if((std::abs(kT)>0.1)&&(std::exp(-DE/kT)<dist_p(mt_grid)))\n         {\n            random_points.at(pos)=pnew;\n            E_current=E_new;\n         }\n      }\n   }\n   std::ofstream ofs(PATH_TO_GRID_POINTS_SOURCE,std::ios::trunc);\n   boost::format fmt(\"%1.15e %1.15e\\n\");\n   for(auto p : random_points)\n   {\n      ofs<<fmt %(std::get<theta_<double> >(p).value()) %(std::get<phi_<double> >(p).value());\n   }\n   \n   return random_points; \n}\n\nstd::vector<std::list<size_t> > get_network\n(\n   const std::vector<std::tuple<theta_<double>,phi_<double> > >& ps\n)\n{\n   const std::vector<Vector3D> P = [ps]()\n   {\n      std::vector<Vector3D> res;\n      for(size_t i=0,size=ps.size();i<size;++i)\n      {\n         res.push_back(S2R(ps.at(i))); \n      }\n      return res; \n   }();\n   std::list<size_t> marvericks = [&P]()\n   {\n      std::list<size_t> res;\n      for(size_t i=1,size=P.size();i<size;++i)\n      {\n         res.push_back(i);\n      }\n      return res;\n   }();   \n   std::list<std::tuple<size_t,size_t> > graph;\n   const auto find_nearest_neighbor = [&P](size_t pos)\n   {\n      double min = DBL_MAX; \n      size_t min_pos;\n      for(size_t i=0,size=P.size();i<size;++i)\n      {\n         if(pos!=i)\n         {\n            const double distance = (P.at(pos)-P.at(i)).norm2();\n            if(distance<min){min=distance;min_pos=i;}\n         }\n      }\n      return min_pos; \n   };\n   const size_t first_nbr=find_nearest_neighbor(0);\n   graph.push_back(std::tuple<size_t,size_t>(0,first_nbr));\n   graph.push_back(std::tuple<size_t,size_t>(first_nbr,0));\n   boost::remove_erase_if(marvericks, [first_nbr](const auto& x) { return x==first_nbr; });\n\n   const auto find_next_pair = [&graph,&P,&marvericks]()->std::tuple<size_t,size_t>\n   {\n      double min_rad = DBL_MAX;\n      size_t min_pos_g; size_t min_pos_m;\n      for(auto it=graph.begin();it!=graph.end();++it)\n      {\n         const Vector3D& pg = P.at(std::get<0>(*it));\n         for(auto it2=marvericks.begin();it2!=marvericks.end();++it2)\n         {\n            const Vector3D& pm = P.at(*it2);    \n            const double d2 = (pg-pm).norm2();\n            const double rad = \n            std::acos(1.0-d2*0.5)+((std::sqrt(d2)>std::sqrt(2.0))?M_PI:0);\n            if(min_rad>rad)\n            {\n               min_rad=rad;\n               min_pos_g=std::get<0>(*it);\n               min_pos_m=*it2;\n            }\n         }\n      }\n      return {min_pos_g,min_pos_m}; \n   };\n   \n   while(!marvericks.empty())\n   {\n      const auto [i,j] = find_next_pair();\n      graph.push_back(std::tuple<size_t,size_t>(i,j)); \n      graph.push_back(std::tuple<size_t,size_t>(j,i)); \n      boost::remove_erase_if(marvericks, [j=j](const auto& x) { return x==j; });\n   }\n   \n   std::vector<std::list<size_t> > result;\n   for(size_t i=0,size=P.size();i<size;++i)\n   {\n      std::list<size_t> nbrs;\n      for(auto it=graph.begin();it!=graph.end();++it)\n      {\n         if(i==std::get<0>(*it)){nbrs.push_back(std::get<1>(*it));}   \n      }\n      result.push_back(nbrs);\n   }\n\n   return result;\n}\n\n", "meta": {"hexsha": "39b4ad68afd5434f8de7a36b42edafac639ccb72", "size": 7077, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid.hpp", "max_stars_repo_name": "tsubupiyo/bubble", "max_stars_repo_head_hexsha": "cf5a0da9ecd1ff52d6e53356670ccd779e95a41b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grid.hpp", "max_issues_repo_name": "tsubupiyo/bubble", "max_issues_repo_head_hexsha": "cf5a0da9ecd1ff52d6e53356670ccd779e95a41b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid.hpp", "max_forks_repo_name": "tsubupiyo/bubble", "max_forks_repo_head_hexsha": "cf5a0da9ecd1ff52d6e53356670ccd779e95a41b", "max_forks_repo_licenses": ["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.1681818182, "max_line_length": 133, "alphanum_fraction": 0.5752437474, "num_tokens": 2054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5033270064506695}}
{"text": "#include \"KMC/integrals.hpp\"\n#include \"KMC/lookup_table.hpp\"\n#include \"KMC/lut_filler_fdep.hpp\"\n#include \"catch.hpp\"\n#include \"test_helpers.hpp\"\n\n#include <cmath>\n#include <cstdio>\n#include <iostream>\n#include <string>\n\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n\nTEST_CASE(\"Fdep lookup table filler upper bound test\", \"[upper_bound]\") {\n    // Assemble\n    const double D = 0.024;\n    const double e_fact = .5;\n    const double fdep_length = .01;\n    const double freelength = 0.05;\n\n    LUTFillerFdep lut_filler(256, 256);\n    SECTION(\"Test SOFT spring\") {\n        const double M = 0.1 / 0.00411;\n        lut_filler.Init(M, e_fact, fdep_length, freelength, D);\n        REQUIRE(D * lut_filler.getUpperBound() ==\n                Approx(1.300682719937549).epsilon(1e-8));\n    }\n    SECTION(\"Test MEDIUM spring\") {\n        const double M = 1. / 0.00411;\n        lut_filler.Init(M, e_fact, fdep_length, freelength, D);\n        REQUIRE(D * lut_filler.getUpperBound() ==\n                Approx(0.4596382883076154).epsilon(1e-8));\n    }\n    SECTION(\"Test STIFF spring\") {\n        const double M = 10. / 0.00411;\n        lut_filler.Init(M, e_fact, fdep_length, freelength, D);\n        REQUIRE(D * lut_filler.getUpperBound() ==\n                Approx(0.1946667540747286).epsilon(1e-8));\n    }\n}\n\nTEST_CASE(\"Fdep lookup table Lookup method test \", \"[lookup]\") {\n\n    const double D = 0.024;\n    const double e_fact = .5;\n    const double fdep_length = .01;\n    const double freelength = 0.05;\n    LUTFillerFdep lut_filler(256, 256);\n\n    double distPerp = 0;\n    SECTION(\"Test SOFT spring\") {\n        constexpr double errTol = 1e-4;\n        const double M = 0.1 / 0.00411;\n\n        lut_filler.Init(M, e_fact, fdep_length, freelength, D);\n        LookupTable LUT(&lut_filler);\n        const double lUB = LUT.getLUCutoff();\n\n        distPerp = 0.04;\n        for (double fact = 0.1; fact <= 1; fact += 0.1) {\n            CHECK(LUT.Lookup(distPerp, fact * lUB) ==\n                  Approx(fdep_integral(distPerp, 0, fact * lUB, M, e_fact,\n                                       fdep_length, freelength))\n                      .epsilon(errTol));\n            // Approx(D * fdep_integral(distPerp / D, 0, fact * lUB / D,\n            // M * D * D, e_fact, fdep_length / D,\n            // freelength / D))\n            //.epsilon(errTol));\n        }\n        // (\"distPerp = 0.1 > D+ell0, single peaked\")\n        distPerp = 0.06;\n        for (double fact = 0.1; fact <= 1; fact += 0.1) {\n            CHECK(LUT.Lookup(distPerp, fact * lUB) ==\n                  Approx(fdep_integral(distPerp, 0, fact * lUB, M, e_fact,\n                                       fdep_length, freelength))\n                      .epsilon(errTol));\n        }\n        // (\"distPerp = 0.06 < D+ell0, double peaked\")\n        distPerp = 0.1;\n        for (double fact = 0.1; fact <= 1; fact += 0.1) {\n            CHECK(LUT.Lookup(distPerp, fact * lUB) ==\n                  Approx(fdep_integral(distPerp, 0, fact * lUB, M, e_fact,\n                                       fdep_length, freelength))\n                      .epsilon(errTol));\n        }\n    }\n\n    SECTION(\"Test MEDIUM spring\") {\n        constexpr double errTol = 1e-4;\n        const double M = 1.0 / (0.00411);\n\n        lut_filler.Init(M, e_fact, fdep_length, freelength, D);\n        LookupTable LUT(&lut_filler);\n        const double lUB = LUT.getLUCutoff();\n\n        distPerp = 0.04;\n        for (double fact = 0.1; fact <= 1; fact += 0.1) {\n            CHECK(LUT.Lookup(distPerp, fact * lUB) ==\n                  Approx(fdep_integral(distPerp, 0, fact * lUB, M, e_fact,\n                                       fdep_length, freelength))\n                      .epsilon(errTol));\n        }\n        // (\"distPerp = 0.1 > D+ell0, single peaked\")\n        distPerp = 0.06;\n        for (double fact = 0.1; fact <= 1; fact += 0.1) {\n            CHECK(LUT.Lookup(distPerp, fact * lUB) ==\n                  Approx(fdep_integral(distPerp, 0, fact * lUB, M, e_fact,\n                                       fdep_length, freelength))\n                      .epsilon(errTol));\n        }\n        // (\"distPerp = 0.06 < D+ell0, double peaked\")\n        distPerp = 0.1;\n        for (double fact = 0.1; fact <= 1; fact += 0.1) {\n            CHECK(LUT.Lookup(distPerp, fact * lUB) ==\n                  Approx(fdep_integral(distPerp, 0, fact * lUB, M, e_fact,\n                                       fdep_length, freelength))\n                      .epsilon(errTol));\n        }\n    }\n\n    SECTION(\"Test STIFF spring\") {\n        constexpr double errTol = 1e-4;\n        const double M = 10 / (0.00411);\n\n        lut_filler.Init(M, e_fact, fdep_length, freelength, D);\n        LookupTable LUT(&lut_filler);\n        const double lUB = LUT.getLUCutoff();\n\n        distPerp = 0.04;\n        for (double fact = 0.1; fact <= 1; fact += 0.1) {\n            CHECK(LUT.Lookup(distPerp, fact * lUB) ==\n                  Approx(fdep_integral(distPerp, 0, fact * lUB, M, e_fact,\n                                       fdep_length, freelength))\n                      .epsilon(errTol));\n        }\n        // (\"distPerp = 0.1 > D+ell0, single peaked\")\n        distPerp = 0.06;\n        for (double fact = 0.1; fact <= 1; fact += 0.1) {\n            CHECK(LUT.Lookup(distPerp, fact * lUB) ==\n                  Approx(fdep_integral(distPerp, 0, fact * lUB, M, e_fact,\n                                       fdep_length, freelength))\n                      .epsilon(errTol));\n        }\n        // (\"distPerp = 0.06 < D+ell0, double peaked\")\n        distPerp = 0.1;\n        for (double fact = 0.1; fact <= 1; fact += 0.1) {\n            CHECK(LUT.Lookup(distPerp, fact * lUB) ==\n                  Approx(fdep_integral(distPerp, 0, fact * lUB, M, e_fact,\n                                       fdep_length, freelength))\n                      .epsilon(errTol));\n        }\n    }\n}\n\n/*\n *TEST_CASE(\"Lookup table test manual medium spring REL error\", \"[lookup]\")\n *{\n *    // integrated by mathematica\n *    LookupTable LUT(&lut_filler);\n *    const double D = 0.024;\n *    constexpr double errTol = RELTOL;\n *\n *    double distPerp = 0;\n *    lut_filler.Init(1.0 / (2 * 0.00411), 0.05 + D, D);\n *\n *    distPerp = 0.2;\n *    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n *    CHECK(relError(LUT.Lookup(distPerp, 0.5 * D) / D, 0.0722077) <\n *errTol); CHECK(relError(LUT.Lookup(distPerp, 1.0 * D) / D, 0.142839) <\n *errTol); CHECK(relError(LUT.Lookup(distPerp, 1.5 * D) / D, 0.210412) <\n *errTol); CHECK(relError(LUT.Lookup(distPerp, 2.0 * D) / D, 0.273623) <\n *errTol); CHECK(relError(LUT.Lookup(distPerp, 3.0 * D) / D, 0.383039) <\n *errTol); CHECK(relError(LUT.Lookup(distPerp, 4.0 * D) / D, 0.466375) <\n *errTol); CHECK(relError(LUT.Lookup(distPerp, 5.0 * D) / D, 0.523889) <\n *errTol); CHECK(relError(LUT.Lookup(distPerp, 6.0 * D) / D, 0.55967) <\n *errTol);\n *\n *    distPerp = 0.08;\n *    // \"distPerp = 0.08 > D+ell0, single peaked\"/D,\n *    CHECK(relError(LUT.Lookup(distPerp, 0.5 * D) / D, 0.497588) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 1.0 * D) / D, 0.993608) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 1.5 * D) / D, 1.48554) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 2.0 * D) / D, 1.96929) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 3.0 * D) / D, 2.88784) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 4.0 * D) / D, 3.6925) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 5.0 * D) / D, 4.3332) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 6.0 * D) / D, 4.78986) < errTol);\n *\n *    distPerp = 0.06;\n *    // \"distPerp = 0.06 < D+ell0, double peaked\"/D,\n *    CHECK(relError(LUT.Lookup(distPerp, 0.5 * D) / D, 0.488864) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 1.0 * D) / D, 0.981139) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 1.5 * D) / D, 1.47815) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 2.0 * D) / D, 1.97788) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 3.0 * D) / D, 2.96052) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 4.0 * D) / D, 3.85857) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 5.0 * D) / D, 4.59864) < errTol);\n *    CHECK(relError(LUT.Lookup(distPerp, 6.0 * D) / D, 5.14058) < errTol);\n *}\n */\n\n/*\n *TEST_CASE(\"REVERSE Lookup table test manual medium spring REL error\",\n *          \"[REVERSE lookup]\") {\n *    // integrated by mathematica\n *    LookupTable LUT(&lut_filler);\n *    const double D = 0.024;\n *\n *    double distPerp = 0;\n *    lut_filler.Init(1.0 / (2 * 0.00411), 0.05 + D, D);\n *\n *    double tol = RELTOL * REVERSEFAC;\n *\n *    distPerp = 0.1;\n *    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n *    CHECK(relError(LUT.ReverseLookup(distPerp, D * 0) / D, 0.0) < tol);\n *    CHECK(relError(LUT.ReverseLookup(distPerp, D * 0.0460519) / D, 0.05) <\n *tol); CHECK(relError(LUT.ReverseLookup(distPerp, D * 0.322128) / D, 0.35)\n *< tol); CHECK(relError(LUT.ReverseLookup(distPerp, D * 0.459824) / D, 0.5)\n *< tol); CHECK(relError(LUT.ReverseLookup(distPerp, D * 0.915356) / D, 1.0)\n *< tol); CHECK(relError(LUT.ReverseLookup(distPerp, D * 1.36196) / D, 1.5)\n *< tol); CHECK(relError(LUT.ReverseLookup(distPerp, D * 1.79446) / D, 2.0)\n *< tol); CHECK(relError(LUT.ReverseLookup(distPerp, D * 2.20718) / D, 2.5)\n *< tol); CHECK(relError(LUT.ReverseLookup(distPerp, D * 3.27015) / D, 4.0)\n *< tol); CHECK(relError(LUT.ReverseLookup(distPerp, D * 3.79115) / D, 5.0)\n *< tol); CHECK(relError(LUT.ReverseLookup(distPerp, D * 4.15242) / D, 6.0)\n *< tol);\n *    // CHECK(relError(LUT.ReverseLookup(distPerp / D, 4.37561), 7.0) <\n *tol);\n *}\n */\n\n/*\n *TEST_CASE(\"REVERSE Lookup table test\", \"[REVERSE lookup]\") {\n *    const double D = 0.024;\n *    const double e_fact = .5;\n *    const double fdep_length = .01;\n *    const double freelength = 0.05;\n *    const double ell0 = freelength / D;\n *\n *    SECTION(\"Test SOFT spring\") {\n *        const double M = 0.1 / (2 * 0.00411);\n *\n *        LookupTable LUT(&lut_filler);\n *        lut_filler.Init(M, e_fact, fdep_length, freelength, D);\n *\n *        double distPerp = 0;\n *        distPerp = 0.2;\n *        // (\"distPerp = 0.2 > D+ell0, single peaked\")\n *        for (double sbound = 0; sbound < LUT.getNonDsbound() / 2;\n *             sbound += 0.2) {\n *            double val = fdep_integral(distPerp / D, 0, sbound / D, e_fact,\n *                                       fdep_length / D, M * D * D, ell0);\n *            CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n *                            REVERSEFAC));\n *        }\n *        // (\"distPerp = 0.1 > D+ell0, single peaked\")\n *        distPerp = 0.1;\n *        for (double sbound = 0; sbound < LUT.getNonDsbound() / 2;\n *             sbound += 0.2) {\n *            double val = fdep_integral(distPerp / D, 0, sbound / D, e_fact,\n *                                       fdep_length / D, M * D * D, ell0);\n *            CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n *                            REVERSEFAC));\n *        }\n *        // (\"distPerp = 0.06 < D+ell0, double peaked\")\n *        distPerp = 0.06;\n *        for (double sbound = 0; sbound < LUT.getNonDsbound() / 2;\n *             sbound += 0.2) {\n *            double val = fdep_integral(distPerp / D, 0, sbound / D, e_fact,\n *                                       fdep_length / D, M * D * D, ell0);\n *            CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n *                            REVERSEFAC));\n *        }\n *    }\n *\n *    SECTION(\"Test MEDIUM spring\") {\n *        const double M = 1.0 / (2 * 0.00411);\n *\n *        LookupTable LUT(&lut_filler);\n *        lut_filler.Init(M, e_fact, fdep_length, freelength, D);\n *\n *        double distPerp = 0;\n *        distPerp = 0.2;\n *        // (\"distPerp = 0.2 > D+ell0, single peaked\")\n *        for (double sbound = 0; sbound < LUT.getNonDsbound() / 3;\n *             sbound += 0.2) {\n *            double val = fdep_integral(distPerp / D, 0, sbound / D, e_fact,\n *                                       fdep_length / D, M * D * D, ell0);\n *            CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound *\n *D));\n *        }\n *        // (\"distPerp = 0.1 > D+ell0, single peaked\")\n *        distPerp = 0.1;\n *        for (double sbound = 0; sbound < LUT.getNonDsbound() / 2;\n *             sbound += 0.2) {\n *            double val = fdep_integral(distPerp / D, 0, sbound / D, e_fact,\n *                                       fdep_length / D, M * D * D, ell0);\n *            CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound *\n *D));\n *        }\n *        // (\"distPerp = 0.06 < D+ell0, double peaked\")\n *        distPerp = 0.06;\n *        for (double sbound = 0; sbound < LUT.getNonDsbound() / 2;\n *             sbound += 0.2) {\n *            double val = fdep_integral(distPerp / D, 0, sbound / D, e_fact,\n *                                       fdep_length / D, M * D * D, ell0);\n *            CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound *\n *D));\n *        }\n *    }\n *\n *    SECTION(\"Test STIFF spring\") {\n *        const double M = 10 / (2 * 0.00411);\n *\n *        LookupTable LUT(&lut_filler);\n *        lut_filler.Init(M, e_fact, fdep_length, freelength, D);\n *\n *        double distPerp = 0;\n *        distPerp = 0.1;\n *        for (double sbound = 0; sbound < LUT.getNonDsbound() / 2;\n *             sbound += 0.1) {\n *            double val = fdep_integral(distPerp / D, 0, sbound / D, e_fact,\n *                                       fdep_length / D, M * D * D, ell0);\n *            CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n *                            REVERSEFAC));\n *        }\n *        // (\"distPerp = 0.06 < D+ell0, double peaked\")\n *        distPerp = 0.06;\n *        for (double sbound = 0; sbound < LUT.getNonDsbound() / 2;\n *             sbound += 0.1) {\n *            double val = fdep_integral(distPerp / D, 0, sbound / D, e_fact,\n *                                       fdep_length / D, M * D * D, ell0);\n *            CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n *                            REVERSEFAC));\n *        }\n *    }\n *}\n */\n\n/*\n *TEST_CASE(\"REVERSE binary Lookup test\", \"[REVERSE binary]\") {\n *\n *    const double D = 0.024;\n *    const double e_fact = .5;\n *    const double fdep_length = .01;\n *    const double freelength = 0.05;\n *    const double ell0 = freelength / D;\n *\n *    LookupTable LUT(&lut_filler);\n *\n *    double rowIndexMax = LUT.distPerpGridNumber;\n *    double colIndexMax = LUT.sboundGridNumber;\n *    double distPerpSpacing;\n *\n *    SECTION(\"Soft spring\") {\n *        const double M = .1 / (2 * 0.00411);\n *        lut_filler.Init(M, e_fact, fdep_length, freelength, D);\n *\n *        distPerpSpacing = LUT.distPerpGridSpacing;\n *        for (int i = 0; i < rowIndexMax - 2; ++i) {\n *            double C0 = LUT.table[LUT.getTableIndex(i, colIndexMax - 1)] * D;\n *            double C1 =\n *                LUT.table[LUT.getTableIndex(i + 1, colIndexMax - 1)] * D;\n *            double Cavg = .5 * (C0 + C1);\n *            double distPerpAvg = distPerpSpacing * (i + .5) * D;\n *            double sbound = LUT.ReverseLookup(distPerpAvg, Cavg);\n *            double Cfdep_integral =\n *                fdep_integral(distPerpAvg / D, 0, sbound, M * D * D, ell0) *\n *D; CHECK(errorPass(Cfdep_integral, Cavg));\n *        }\n *    }\n *\n *    SECTION(\"Medium spring\") {\n *        const double M = .1 / (2 * 0.00411);\n *        lut_filler.Init(M, e_fact, fdep_length, freelength, D);\n *\n *        distPerpSpacing = LUT.distPerpGridSpacing;\n *        distPerpSpacing = LUT.distPerpGridSpacing;\n *        for (int i = 0; i < rowIndexMax - 2; ++i) {\n *            double C0 = LUT.table[LUT.getTableIndex(i, colIndexMax - 1)] * D;\n *            double C1 =\n *                LUT.table[LUT.getTableIndex(i + 1, colIndexMax - 1)] * D;\n *            double Cavg = .5 * (C0 + C1);\n *            double distPerpAvg = distPerpSpacing * (i + .5) * D;\n *            double sbound = LUT.ReverseLookup(distPerpAvg, Cavg);\n *            double Cfdep_integral =\n *                fdep_integral(distPerpAvg / D, 0, sbound, M * D * D, ell0) *\n *D; CHECK(errorPass(Cfdep_integral, Cavg));\n *        }\n *    }\n *\n *    SECTION(\"Stiff spring\") {\n *        alpha = 10. / (2 * 0.00411);\n *        M = alpha * D * D;\n *        lut_filler.Init(alpha, freelength, D);\n *        distPerpSpacing = LUT.distPerpGridSpacing;\n *        for (int i = 0; i < rowIndexMax - 2; ++i) {\n *            double C0 = LUT.table[LUT.getTableIndex(i, colIndexMax - 1)] * D;\n *            double C1 =\n *                LUT.table[LUT.getTableIndex(i + 1, colIndexMax - 1)] * D;\n *            double Cavg = .5 * (C0 + C1);\n *            double distPerpAvg = distPerpSpacing * (i + .5) * D;\n *            double sbound = LUT.ReverseLookup(distPerpAvg, Cavg);\n *            double Cfdep_integral =\n *                fdep_integral(distPerpAvg / D, 0, sbound / D, M, ell0) * D;\n *            CHECK(errorPass(Cfdep_integral, Cavg));\n *        }\n *    }\n *}\n *\n *TEST_CASE(\"Test the calculation of binding volume.\", \"[bind volume]\") {\n *    const double D = 0.024;\n *    const double freelength = 0.05;\n *    const double ell0 = freelength;\n *    double alpha = 1. / (2 * 0.00411);\n *\n *    for (double i = 0.1; i < 1.0; i += .1) {\n *        LookupTable LUT(&lut_filler);\n *        lut_filler.Init(alpha * i, freelength, D);\n *        LUT.calcBindVol();\n *        double bind_vol =\n *            fdep_bind_vol_integral(0, LUT.getLUCutoff(), i * alpha, ell0);\n *        REQUIRE(LUT.getBindVolume() == Approx(bind_vol).epsilon(1e-8));\n *    }\n *}\n */\n", "meta": {"hexsha": "d3a5bf865633ccda9a8574a6871d813fbf08d290", "size": 17622, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/fdep_lookup_test.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": "tests/fdep_lookup_test.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": "tests/fdep_lookup_test.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": 41.1728971963, "max_line_length": 79, "alphanum_fraction": 0.5263874702, "num_tokens": 5661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5032712509357324}}
{"text": "/* Copyright (c) 2017, United States Government, as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * \n * All rights reserved.\n * \n * The Astrobee platform is licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with the\n * License. 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, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n#include <Eigen/Eigenvalues> \n\n#include <vector>\n#include <iostream>\n//#include <ros/ros.h>\n\nusing namespace Eigen;\n\nint compute_delta_state_and_cov(float* residual_in, int error_in, float* H_in,\n        int H_rows, int H_cols, unsigned int augs_bitmask, float* R_mat_in, float* P_in,\n        float* delta_state_out_out, float* P_out_out) {\n  //struct timeval secs1, secs2;\n  //gettimeofday(&secs1, 0);\n  Map<MatrixXf> H_full(H_in, H_rows, H_cols);\n  Map<VectorXf> residual_full(residual_in, H_rows);\n  Map<MatrixXf> R_mat_full(R_mat_in, H_rows, H_rows);\n  Map<MatrixXf> P(P_in, H_cols, H_cols);\n  Map<VectorXf> delta_state_out(delta_state_out_out, H_cols);\n  Map<MatrixXf> P_out(P_out_out, H_cols, H_cols);\n\n  if (error_in) {\n    delta_state_out.setZero();\n    P_out = P;\n    //ROS_INFO(\"compute_delta_state stop 1\");\n    return 1;\n  }\n\n  std::vector<int> used_augs;\n  for (int i = 0; i < (H_cols - 15) / 6; i++)\n    if (augs_bitmask & (1 << i))\n      used_augs.push_back(i);\n  VectorBlock<Map<VectorXf> > residual = residual_full.segment(0, used_augs.size() * 6);\n  Block<Map<MatrixXf> > R_mat = R_mat_full.block(0, 0, used_augs.size() * 6, used_augs.size() * 6);\n  Block<Map<MatrixXf> > reduced_H = H_full.block(0, 0, used_augs.size() * 6, used_augs.size() * 6);\n  MatrixXf reduced_P(used_augs.size() * 6, used_augs.size() * 6);\n  for (int i = 0; i < used_augs.size(); i++)\n    for (int j = 0; j < used_augs.size(); j++)\n      reduced_P.block<6, 6>(6 * i, 6 * j) = P.block<6, 6>(15 + 6 * used_augs[i], 15 + 6 * used_augs[j]);\n  MatrixXf reduced_cols_P(H_cols, used_augs.size() * 6);\n  for (int i = 0; i < used_augs.size(); i++)\n    reduced_cols_P.block(0, 6 * i, H_cols, 6) = P.block(0, 15 + 6 * used_augs[i], H_cols, 6);\n  //gettimeofday(&secs2, 0);\n  //ROS_INFO(\"compute_delta_state %d create Ps\", (((secs2.tv_sec - secs1.tv_sec) * 1000) + (secs2.tv_usec - secs1.tv_usec)));\n  //secs1 = secs2;\n\n  MatrixXf T(reduced_cols_P.rows(), reduced_H.rows()), S(reduced_H.rows(), reduced_H.rows());\n  T.noalias() = reduced_cols_P * reduced_H.transpose();\n  //gettimeofday(&secs2, 0);\n  //ROS_INFO(\"compute_delta_state %d multiplies0\", (((secs2.tv_sec - secs1.tv_sec) * 1000) + (secs2.tv_usec - secs1.tv_usec)));\n  //secs1 = secs2;\n  S.triangularView<Lower>() = reduced_H * reduced_P * reduced_H.transpose();\n  S.triangularView<Lower>() += R_mat;\n  //gettimeofday(&secs2, 0);\n  //ROS_INFO(\"compute_delta_state %d multiplies1\", (((secs2.tv_sec - secs1.tv_sec) * 1000) + (secs2.tv_usec - secs1.tv_usec)));\n  //secs1 = secs2;\n\n  LDLT<MatrixXf,Lower> chol(S);\n  if (chol.info() != Success) {\n    fprintf(stderr, \"S not positive definite.\\n\");\n    delta_state_out.setZero();\n    P_out = P;\n    //ROS_INFO(\"compute_delta_state stop 2\");\n    return 1;\n  }\n  //gettimeofday(&secs2, 0);\n  //ROS_INFO(\"compute_delta_state %d cholesky\", (((secs2.tv_sec - secs1.tv_sec) * 1000) + (secs2.tv_usec - secs1.tv_usec)));\n  //secs1 = secs2;\n  MatrixXf sinv = MatrixXf::Identity(S.cols(), S.cols());\n  chol.solveInPlace(sinv);\n  //gettimeofday(&secs2, 0);\n  //ROS_INFO(\"compute_delta_state %d inverse\", (((secs2.tv_sec - secs1.tv_sec) * 1000) + (secs2.tv_usec - secs1.tv_usec)));\n  //secs1 = secs2;\n  \n  MatrixXf K;\n  K.noalias() = T * sinv.selfadjointView<Lower>();\n  delta_state_out.noalias() = K * residual;\n  //gettimeofday(&secs2, 0);\n  //ROS_INFO(\"compute_delta_state %d multiplies2\", (((secs2.tv_sec - secs1.tv_sec) * 1000) + (secs2.tv_usec - secs1.tv_usec)));\n  //secs1 = secs2;\n\n  // F = I - KH; P = FPF' + KRK';\n  // P = P - (KHP)' - KHP + K(HPH' + R)K'\n  // P = P - KHP\n  P_out.triangularView<Lower>() = P - K * T.transpose(); // P - KHP\n  P_out.triangularView<StrictlyUpper>() = P_out.transpose();\n  //P_out.noalias() = 0.5 * (P_out + P_out.transpose());\n\n  //gettimeofday(&secs2, 0);\n  //ROS_INFO(\"compute_delta_state %d %d stop 0\", (((secs2.tv_sec - secs1.tv_sec) * 1000) + (secs2.tv_usec - secs1.tv_usec)), H_rows);\n  return 0;\n}\n", "meta": {"hexsha": "70f90b275d7753c7cf13d808c32fbc5b02d0b8ab", "size": 4729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gnc/matlab/cxx_functions/src/compute_delta_state_and_cov.cpp", "max_stars_repo_name": "Robo0603179/astrobee", "max_stars_repo_head_hexsha": "19e58806c63cddd9046342c7fa2ac7808f40ad3c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 629.0, "max_stars_repo_stars_event_min_datetime": "2017-08-31T23:09:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:55:40.000Z", "max_issues_repo_path": "gnc/matlab/cxx_functions/src/compute_delta_state_and_cov.cpp", "max_issues_repo_name": "Robo0603179/astrobee", "max_issues_repo_head_hexsha": "19e58806c63cddd9046342c7fa2ac7808f40ad3c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 269.0, "max_issues_repo_issues_event_min_datetime": "2018-05-05T12:31:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:04:11.000Z", "max_forks_repo_path": "gnc/matlab/cxx_functions/src/compute_delta_state_and_cov.cpp", "max_forks_repo_name": "Robo0603179/astrobee", "max_forks_repo_head_hexsha": "19e58806c63cddd9046342c7fa2ac7808f40ad3c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 248.0, "max_forks_repo_forks_event_min_datetime": "2017-08-31T23:20:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T22:29:16.000Z", "avg_line_length": 42.2232142857, "max_line_length": 133, "alphanum_fraction": 0.6675829985, "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5032712459359194}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Peter Caspers\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 <ql/experimental/volatility/noarbsabr.hpp>\n\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/math/modifiedbessel.hpp>\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/functional/hash.hpp>\n\nnamespace QuantLib {\n\nclass NoArbSabrModel::integrand {\n    const NoArbSabrModel* model;\n    Real strike;\n  public:\n    integrand(const NoArbSabrModel* model, Real strike)\n    : model(model), strike(strike) {}\n    Real operator()(Real f) const {\n        return std::max(f - strike, 0.0) * model->p(f);\n    }\n};\n\nclass NoArbSabrModel::p_integrand {\n    const NoArbSabrModel* model;\n  public:\n    explicit p_integrand(const NoArbSabrModel* model)\n    : model(model) {}\n    Real operator()(Real f) const {\n        return model->p(f);\n    }\n};\n\nNoArbSabrModel::NoArbSabrModel(const Real expiryTime, const Real forward,\n                               const Real alpha, const Real beta, const Real nu,\n                               const Real rho)\n    : expiryTime_(expiryTime), externalForward_(forward), alpha_(alpha),\n      beta_(beta), nu_(nu), rho_(rho), forward_(forward),\n      numericalForward_(forward) {\n\n    QL_REQUIRE(expiryTime > 0.0 && expiryTime <= detail::NoArbSabrModel::expiryTime_max,\n               \"expiryTime (\" << expiryTime << \") out of bounds\");\n    QL_REQUIRE(forward > 0.0, \"forward (\" << forward << \") must be positive\");\n    QL_REQUIRE(beta >= detail::NoArbSabrModel::beta_min && beta <= detail::NoArbSabrModel::beta_max,\n               \"beta (\" << beta << \") out of bounds\");\n    Real sigmaI = alpha * std::pow(forward, beta - 1.0);\n    QL_REQUIRE(sigmaI >= detail::NoArbSabrModel::sigmaI_min &&\n                   sigmaI <= detail::NoArbSabrModel::sigmaI_max,\n               \"sigmaI = alpha*forward^(beta-1.0) (\"\n                   << sigmaI << \") out of bounds, alpha=\" << alpha\n                   << \" beta=\" << beta << \" forward=\" << forward);\n    QL_REQUIRE(nu >= detail::NoArbSabrModel::nu_min && nu <= detail::NoArbSabrModel::nu_max,\n               \"nu (\" << nu << \") out of bounds\");\n    QL_REQUIRE(rho >= detail::NoArbSabrModel::rho_min && rho <= detail::NoArbSabrModel::rho_max,\n               \"rho (\" << rho << \") out of bounds\");\n\n    // determine a region sufficient for integration in the normal case\n\n    fmin_ = fmax_ = forward_;\n    for (Real tmp = p(fmax_);\n         tmp > std::max(detail::NoArbSabrModel::i_accuracy / std::max(1.0, fmax_ - fmin_),\n                        detail::NoArbSabrModel::density_threshold);\n         tmp = p(fmax_)) {\n        fmax_ *= 2.0;\n    }\n    for (Real tmp = p(fmin_);\n         tmp > std::max(detail::NoArbSabrModel::i_accuracy / std::max(1.0, fmax_ - fmin_),\n                        detail::NoArbSabrModel::density_threshold);\n         tmp = p(fmin_)) {\n        fmin_ *= 0.5;\n    }\n    fmin_ = std::max(detail::NoArbSabrModel::strike_min, fmin_);\n\n    QL_REQUIRE(fmax_ > fmin_, \"could not find a reasonable integration domain\");\n\n    integrator_ =\n        ext::make_shared<GaussLobattoIntegral>(\n            detail::NoArbSabrModel::i_max_iterations, detail::NoArbSabrModel::i_accuracy);\n\n    detail::D0Interpolator d0(forward_, expiryTime_, alpha_, beta_, nu_, rho_);\n    absProb_ = d0();\n\n    try {\n        Brent b;\n        Real start = std::sqrt(externalForward_ - detail::NoArbSabrModel::strike_min);\n        Real tmp =\n            b.solve(boost::lambda::bind(&NoArbSabrModel::forwardError, this,\n                                        boost::lambda::_1),\n                    detail::NoArbSabrModel::forward_accuracy, start,\n                    std::min(detail::NoArbSabrModel::forward_search_step, start / 2.0));\n        forward_ = tmp * tmp + detail::NoArbSabrModel::strike_min;\n    } catch (Error&) {\n        // fall back to unadjusted forward\n        forward_ = externalForward_;\n    }\n\n    Real d = forwardError(std::sqrt(forward_ - detail::NoArbSabrModel::strike_min));\n    numericalForward_ = d + externalForward_;\n}\n\nReal NoArbSabrModel::optionPrice(const Real strike) const {\n    if (p(std::max(forward_, strike)) < detail::NoArbSabrModel::density_threshold)\n        return 0.0;\n    return (1.0 - absProb_) *\n        ((*integrator_)(integrand(this, strike),\n                        strike, std::max(fmax_, 2.0 * strike)) /\n            numericalIntegralOverP_);\n}\n\nReal NoArbSabrModel::digitalOptionPrice(const Real strike) const {\n    if (strike < QL_MIN_POSITIVE_REAL)\n        return 1.0;\n    if (p(std::max(forward_, strike)) < detail::NoArbSabrModel::density_threshold)\n        return 0.0;\n    return (1.0 - absProb_)\n        * ((*integrator_)(p_integrand(this),\n                          strike, std::max(fmax_, 2.0 * strike)) /\n           numericalIntegralOverP_);\n}\n\nReal NoArbSabrModel::forwardError(const Real forward) const {\n    forward_ = forward * forward + detail::NoArbSabrModel::strike_min;\n    numericalIntegralOverP_ = (*integrator_)(p_integrand(this),\n                                             fmin_, fmax_);\n    return optionPrice(0.0) - externalForward_;\n}\n\nReal NoArbSabrModel::p(const Real f) const {\n\n    if (f < detail::NoArbSabrModel::density_lower_bound ||\n        forward_ < detail::NoArbSabrModel::density_lower_bound)\n        return 0.0;\n\n    Real fOmB = std::pow(f, 1.0 - beta_);\n    Real FOmB = std::pow(forward_, 1.0 - beta_);\n\n    Real zf = fOmB / (alpha_ * (1.0 - beta_));\n    Real zF = FOmB / (alpha_ * (1.0 - beta_));\n    Real z = zF - zf;\n\n    // Real JzF = std::sqrt(1.0 - 2.0 * rho_ * nu_ * zF + nu_ * nu_ * zF * zF);\n    Real Jmzf = std::sqrt(1.0 + 2.0 * rho_ * nu_ * zf + nu_ * nu_ * zf * zf);\n    Real Jz = std::sqrt(1.0 - 2.0 * rho_ * nu_ * z + nu_ * nu_ * z * z);\n\n    Real xz = std::log((Jz - rho_ + nu_ * z) / (1.0 - rho_)) / nu_;\n    Real Bp_B = beta_ / FOmB;\n    // Real Bpp_B = beta_ * (2.0 * beta_ - 1.0) / (FOmB * FOmB);\n    Real kappa1 = 0.125 * nu_ * nu_ * (2.0 - 3.0 * rho_ * rho_) -\n                  0.25 * rho_ * nu_ * alpha_ * Bp_B;\n    // Real kappa2 = alpha_ * alpha_ * (0.25 * Bpp_B - 0.375 * Bp_B * Bp_B);\n    Real gamma = 1.0 / (2.0 * (1.0 - beta_));\n    Real sqrtOmR = std::sqrt(1.0 - rho_ * rho_);\n    Real h = 0.5 * beta_ * rho_ / ((1.0 - beta_) * Jmzf * Jmzf) *\n             (nu_ * zf * std::log(zf * Jz / zF) +\n              (1 + rho_ * nu_ * zf) / sqrtOmR *\n                  (std::atan((nu_ * z - rho_) / sqrtOmR) +\n                   std::atan(rho_ / sqrtOmR)));\n\n    Real res =\n        std::pow(Jz, -1.5) / (alpha_ * std::pow(f, beta_) * expiryTime_) *\n        std::pow(zf, 1.0 - gamma) * std::pow(zF, gamma) *\n        std::exp(-(xz * xz) / (2.0 * expiryTime_) +\n                 (h + kappa1 * expiryTime_)) *\n        modifiedBesselFunction_i_exponentiallyWeighted(gamma,\n                                                       zF * zf / expiryTime_);\n    return res;\n}\n\nnamespace detail {\n\nusing namespace boost::assign;\n\nD0Interpolator::D0Interpolator(const Real forward, const Real expiryTime,\n                               const Real alpha, const Real beta, const Real nu,\n                               const Real rho)\n    : forward_(forward), expiryTime_(expiryTime), alpha_(alpha), beta_(beta),\n      nu_(nu), rho_(rho), gamma_(1.0 / (2.0 * (1.0 - beta_))) {\n\n    sigmaI_ = alpha_ * std::pow(forward_, beta_ - 1.0);\n\n    tauG_ += 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0,\n        3.25, 3.5, 3.75, 4.0, 4.25, 4.5, 4.75, 5.0, 5.25, 5.5, 5.75, 6.0, 6.25,\n        6.5, 6.75, 7.0, 7.25, 7.5, 7.75, 8.0, 8.25, 8.5, 8.75, 9.0, 9.25, 9.5,\n        9.75, 10.0, 10.25, 10.5, 10.75, 11.0, 11.25, 11.5, 11.75, 12.0, 12.25,\n        12.5, 12.75, 13.0, 13.25, 13.5, 13.75, 14.0, 14.25, 14.5, 14.75, 15.0,\n        15.25, 15.5, 15.75, 16.0, 16.25, 16.5, 16.75, 17.0, 17.25, 17.5, 17.75,\n        18.0, 18.25, 18.5, 18.75, 19.0, 19.25, 19.5, 19.75, 20.0, 20.25, 20.5,\n        20.75, 21.0, 21.25, 21.5, 21.75, 22.0, 22.25, 22.5, 22.75, 23.0, 23.25,\n        23.5, 23.75, 24.0, 24.25, 24.5, 24.75, 25.0, 25.25, 25.5, 25.75, 26.0,\n        26.25, 26.5, 26.75, 27.0, 27.25, 27.5, 27.75, 28.0, 28.25, 28.5, 28.75,\n        29.0, 29.25, 29.5, 29.75, 30.0;\n\n    sigmaIG_ += 1.0, 0.8, 0.7, 0.6, 0.5, 0.45, 0.4, 0.35, 0.3, 0.27, 0.24, 0.21,\n        0.18, 0.15, 0.125, 0.1, 0.075, 0.05;\n\n    rhoG_ += 0.75, 0.50, 0.25, 0.00, -0.25, -0.50, -0.75;\n\n    nuG_ += 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8;\n\n    betaG_ += 0.01, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9;\n}\n\nReal D0Interpolator::operator()() const {\n\n    // we do not need to check the indices here, because this is already\n    // done in the NoArbSabr constructor\n\n    Size tauInd = std::upper_bound(tauG_.begin(), tauG_.end(), expiryTime_) -\n                                   tauG_.begin();\n    if (tauInd == tauG_.size())\n        --tauInd; // tau at upper bound\n    Real expiryTimeTmp = expiryTime_;\n    if (tauInd == 0) {\n        ++tauInd;\n        expiryTimeTmp = tauG_.front();\n    }\n    Real tauL = (expiryTimeTmp - tauG_[tauInd - 1]) /\n                (tauG_[tauInd] - tauG_[tauInd - 1]);\n\n    int sigmaIInd =\n        sigmaIG_.size() -\n        (std::upper_bound(sigmaIG_.rbegin(), sigmaIG_.rend(), sigmaI_) -\n         sigmaIG_.rbegin());\n    if (sigmaIInd == 0)\n        ++sigmaIInd; // sigmaI at upper bound\n    Real sigmaIL = (sigmaI_ - sigmaIG_[sigmaIInd - 1]) /\n                   (sigmaIG_[sigmaIInd] - sigmaIG_[sigmaIInd - 1]);\n\n    int rhoInd =\n        rhoG_.size() -\n        (std::upper_bound(rhoG_.rbegin(), rhoG_.rend(), rho_) - rhoG_.rbegin());\n    if (rhoInd == 0) {\n        rhoInd++;\n    }\n    if (rhoInd == static_cast<int>(rhoG_.size())) {\n        rhoInd--;\n    }\n    Real rhoL =\n        (rho_ - rhoG_[rhoInd - 1]) / (rhoG_[rhoInd] - rhoG_[rhoInd - 1]);\n\n    // for nu = 0 we know phi = 0.5*z_F^2\n    Size nuInd = std::upper_bound(nuG_.begin(), nuG_.end(), nu_) - nuG_.begin();\n    if (nuInd == nuG_.size())\n        --nuInd; // nu at upper bound\n    Real tmpNuG = nuInd > 0 ? nuG_[nuInd - 1] : 0.0;\n    Real nuL = (nu_ - tmpNuG) / (nuG_[nuInd] - tmpNuG);\n\n    // for beta = 1 we know phi = 0.0\n    Size betaInd =\n        std::upper_bound(betaG_.begin(), betaG_.end(), beta_) - betaG_.begin();\n    Real tmpBetaG;\n    if (betaInd == betaG_.size())\n        tmpBetaG = 1.0;\n    else\n        tmpBetaG = betaG_[betaInd];\n    Real betaL =\n        (beta_ - betaG_[betaInd - 1]) / (tmpBetaG - betaG_[betaInd - 1]);\n\n    Real phiRes = 0.0;\n    for (int iTau = -1; iTau <= 0; ++iTau) {\n        for (int iSigma = -1; iSigma <= 0; ++iSigma) {\n            for (int iRho = -1; iRho <= 0; ++iRho) {\n                for (int iNu = -1; iNu <= 0; ++iNu) {\n                    for (int iBeta = -1; iBeta <= 0; ++iBeta) {\n                        Real phiTmp;\n                        if (iNu == -1 && nuInd == 0) {\n                            phiTmp =\n                                0.5 /\n                                (sigmaI_ * sigmaI_ * (1.0 - beta_) *\n                                 (1.0 - beta_)); // this is 0.5*z_F^2, see above\n                        } else {\n                            if (iBeta == 0 && betaInd == betaG_.size()) {\n                                phiTmp =\n                                    phi(detail::NoArbSabrModel::tiny_prob);\n                            } else {\n                                int ind = (tauInd + iTau +\n                                           (sigmaIInd + iSigma +\n                                            (rhoInd + iRho +\n                                             (nuInd + iNu + ((betaInd + iBeta) *\n                                                             nuG_.size())) *\n                                                 rhoG_.size()) *\n                                                sigmaIG_.size()) *\n                                               tauG_.size());\n                                QL_REQUIRE(ind >= 0 && ind < 1209600,\n                                           \"absorption matrix index (\"\n                                               << ind << \") invalid\");\n                                phiTmp = phi((Real)sabrabsprob[ind] /\n                                             detail::NoArbSabrModel::nsim);\n                            }\n                        }\n                        phiRes += phiTmp * (iTau == -1 ? (1.0 - tauL) : tauL) *\n                                  (iSigma == -1 ? (1.0 - sigmaIL) : sigmaIL) *\n                                  (iRho == -1 ? (1.0 - rhoL) : rhoL) *\n                                  (iNu == -1 ? (1.0 - nuL) : nuL) *\n                                  (iBeta == -1 ? (1.0 - betaL) : betaL);\n                    }\n                }\n            }\n        }\n    }\n    return d0(phiRes);\n}\n\nReal D0Interpolator::phi(const Real d0) const {\n    if (d0 < 1e-14)\n        return detail::NoArbSabrModel::phiByTau_cutoff * expiryTime_;\n    return boost::math::gamma_q_inv(gamma_, d0) * expiryTime_;\n}\n\nReal D0Interpolator::d0(const Real phi) const {\n    return boost::math::gamma_q(gamma_, std::max(0.0, phi / expiryTime_));\n}\n\n} // namespace detail\n\n} // namespace QuantLib\n", "meta": {"hexsha": "cb28258bd4d0e3a03838b999f8b0c31f8e49aca7", "size": 13845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/volatility/noarbsabr.cpp", "max_stars_repo_name": "tlapfai/My-Quantlib", "max_stars_repo_head_hexsha": "9e24dafd8c849659d3a9b4b432abf854441ab825", "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": "ql/experimental/volatility/noarbsabr.cpp", "max_issues_repo_name": "tlapfai/My-Quantlib", "max_issues_repo_head_hexsha": "9e24dafd8c849659d3a9b4b432abf854441ab825", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/volatility/noarbsabr.cpp", "max_forks_repo_name": "tlapfai/My-Quantlib", "max_forks_repo_head_hexsha": "9e24dafd8c849659d3a9b4b432abf854441ab825", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T02:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T02:04:10.000Z", "avg_line_length": 41.0830860534, "max_line_length": 100, "alphanum_fraction": 0.525749368, "num_tokens": 4451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324587033253, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5032712459359194}}
{"text": "//----------------------------------------------------------------------------\n/** @file SgStatisticsTest.cpp\n    Unit tests for SgStatistics.\n*/\n//----------------------------------------------------------------------------\n\n#include \"SgSystem.h\"\n\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include \"SgStatistics.h\"\n\nusing namespace std;\n\n//----------------------------------------------------------------------------\n\nnamespace {\n\n//----------------------------------------------------------------------------\n\nBOOST_AUTO_TEST_CASE(SgStatisticsBaseTest_CheckAddRemoveCount)\n{\n    SgStatisticsBase<double,double> statistics;\n    statistics.Add(2., 1.);\n    BOOST_CHECK_CLOSE(statistics.Mean(), 2., 0.1);\n    statistics.Add(5., 0.5);\n    BOOST_CHECK_CLOSE(statistics.Mean(), 3., 0.1);\n    statistics.Add(1., 1.5);\n    BOOST_CHECK_CLOSE(statistics.Mean(), 2., 0.1);\n    statistics.Remove(0.5, 2.0);\n    BOOST_CHECK_CLOSE(statistics.Mean(), 5., 0.1);\n\n    SgStatisticsBase<double,std::size_t> stat;\n    stat.Add(0.0, 1);\n    stat.Add(1.0, 2);\n    stat.Add(0.5, 4);\n    BOOST_CHECK_EQUAL(stat.Count(), 7u);\n    BOOST_CHECK_CLOSE(stat.Mean(), 4.0 / 7.0, 0.001);\n\n    stat.Remove(1.5, 2);\n    BOOST_CHECK_EQUAL(stat.Count(), 5u);\n    BOOST_CHECK_CLOSE(stat.Mean(), 1.0 / 5.0, 0.001);\n    \n    stat.Remove(0.1, 3);\n    BOOST_CHECK_EQUAL(stat.Count(), 2u);\n    BOOST_CHECK_CLOSE(stat.Mean(), 0.7 / 2, 0.001);\n\n    stat.Remove(0.35, 2);\n    BOOST_CHECK(! stat.IsDefined());\n}\n\nBOOST_AUTO_TEST_CASE(SgStatisticsBaseTest_CheckRemove)\n{\n    SgStatisticsBase<double,std::size_t> stat;\n    stat.Add(2.0);\n    stat.Remove(2.0);\n    BOOST_CHECK(! stat.IsDefined());\n\n    stat.Add(2.0);\n    stat.Add(1.0);\n    stat.Remove(1.0);\n    BOOST_CHECK_EQUAL(stat.Count(), 1u);\n    BOOST_CHECK_CLOSE(stat.Mean(), 2.0, 0.001);\n\n    stat.Add(1.0);\n    stat.Add(3.0);\n    stat.Add(6.0);\n    stat.Remove(3.0);\n    BOOST_CHECK_EQUAL(stat.Count(), 3u);\n    BOOST_CHECK_CLOSE(stat.Mean(), 3.0, 0.001);\n}\n\n//----------------------------------------------------------------------------\n\nBOOST_AUTO_TEST_CASE(SgStatisticsTest_Basics)\n{\n    typedef SgStatistics<double,std::size_t> Statistics;\n\n    Statistics statistics;\n    statistics.Add(1.0);\n    statistics.Add(2.0);\n    statistics.Add(3.0);\n    BOOST_CHECK_EQUAL(statistics.Count(), 3u);\n    BOOST_CHECK_CLOSE(statistics.Mean(), 2., 0.1);\n    BOOST_CHECK_CLOSE(statistics.Deviation(), 0.816, 0.1);\n\n    Statistics statistics2;\n    statistics2.Add(-1.0);\n    statistics2.Add(2.5);\n    statistics2.Add(2.5);\n    statistics2.Add(2.7);\n    BOOST_CHECK_EQUAL(statistics2.Count(), 4u);\n    BOOST_CHECK_CLOSE(statistics2.Mean(), 1.675, 0.1);\n    BOOST_CHECK_CLOSE(statistics2.Deviation(), 1.547, 0.1);\n}\n\n//----------------------------------------------------------------------------\n\nBOOST_AUTO_TEST_CASE(SgHistogramTest_Basics)\n{\n    typedef SgHistogram<double,std::size_t> Histogram;\n    Histogram histo(-2, 6, 4);\n    histo.Add(-0.5);\n    histo.Add(-1);\n    histo.Add(5);\n    BOOST_CHECK_EQUAL(histo.Count(), 3u);\n    BOOST_CHECK_EQUAL(histo.Count(0), 2u);\n    BOOST_CHECK_EQUAL(histo.Count(1), 0u);\n    BOOST_CHECK_EQUAL(histo.Count(2), 0u);\n    BOOST_CHECK_EQUAL(histo.Count(3), 1u);\n}\n\n//----------------------------------------------------------------------------\n\n} // namespace\n\n", "meta": {"hexsha": "b2fb0b5153c8616f5c35edf3142b604b21a8b9aa", "size": 3353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fuego-0.4/smartgame/test/SgStatisticsTest.cpp", "max_stars_repo_name": "MisterTea/HyperNEAT", "max_stars_repo_head_hexsha": "516fef725621991ee709eb9b4afe40e0ce82640d", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "fuego-0.4/smartgame/test/SgStatisticsTest.cpp", "max_issues_repo_name": "afcarl/HyperNEAT", "max_issues_repo_head_hexsha": "516fef725621991ee709eb9b4afe40e0ce82640d", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "fuego-0.4/smartgame/test/SgStatisticsTest.cpp", "max_forks_repo_name": "afcarl/HyperNEAT", "max_forks_repo_head_hexsha": "516fef725621991ee709eb9b4afe40e0ce82640d", "max_forks_repo_licenses": ["BSD-3-Clause"], "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.6581196581, "max_line_length": 78, "alphanum_fraction": 0.5568147927, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.5031648054964664}}
{"text": "/*\n    Copyright 2013 Adobe\n    Distributed under the Boost Software License, Version 1.0.\n    (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*/\n/**************************************************************************************************/\n\n#ifndef ADOBE_ALGORITHM_SET_HPP\n#define ADOBE_ALGORITHM_SET_HPP\n\n#include <adobe/config.hpp>\n\n#include <boost/range/begin.hpp>\n#include <boost/range/end.hpp>\n\n#include <algorithm>\n#include <functional>\n\n/**************************************************************************************************/\n\nnamespace adobe {\n\n/**************************************************************************************************/\n/*!\n\\defgroup set set operations on sorted ranges\n\\ingroup sorting\n\n\\see\n    - STL documentation for \\ref stldoc_includes\n    - STL documentation for \\ref stldoc_set_union\n    - STL documentation for \\ref stldoc_set_intersection\n    - STL documentation for \\ref stldoc_set_difference\n    - STL documentation for \\ref stldoc_set_symmetric_difference\n*/\n/**************************************************************************************************/\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputRange1, class InputRange2>\ninline bool includes(const InputRange1& range1, const InputRange2& range2) {\n    return std::includes(boost::begin(range1), boost::end(range1), boost::begin(range2),\n                         boost::end(range2));\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputIterator1, class InputIterator2, class Compare>\ninline bool includes(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2,\n                     InputIterator2 last2, Compare comp) {\n    return std::includes(first1, last1, first2, last2,\n                         std::bind(comp, std::placeholders::_1, std::placeholders::_2));\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputRange1, class InputRange2, class Compare>\ninline bool includes(const InputRange1& range1, const InputRange2& range2, Compare comp) {\n    return adobe::includes(boost::begin(range1), boost::end(range1), boost::begin(range2),\n                           boost::end(range2), comp);\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputRange1, class InputRange2, class OutputIterator>\ninline OutputIterator set_union(const InputRange1& range1, const InputRange2& range2,\n                                OutputIterator result) {\n    return std::set_union(boost::begin(range1), boost::end(range1), boost::begin(range2),\n                          boost::end(range2), result);\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputIterator1, class InputIterator2, class OutputIterator, class Compare>\ninline OutputIterator set_union(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2,\n                                InputIterator2 last2, OutputIterator result, Compare comp) {\n    return std::set_union(first1, last1, first2, last2, result,\n                          std::bind(comp, std::placeholders::_1, std::placeholders::_2));\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputRange1, class InputRange2, class OutputIterator, class Compare>\ninline OutputIterator set_union(const InputRange1& range1, const InputRange2& range2,\n                                OutputIterator result, Compare comp) {\n    return adobe::set_union(boost::begin(range1), boost::end(range1), boost::begin(range2),\n                            boost::end(range2), result, comp);\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputRange1, class InputRange2, class OutputIterator>\ninline OutputIterator set_intersection(const InputRange1& range1, const InputRange2& range2,\n                                       OutputIterator result) {\n    return std::set_intersection(boost::begin(range1), boost::end(range1), boost::begin(range2),\n                                 boost::end(range2), result);\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputIterator1, class InputIterator2, class OutputIterator, class Compare>\ninline OutputIterator set_intersection(InputIterator1 first1, InputIterator1 last1,\n                                       InputIterator2 first2, InputIterator2 last2,\n                                       OutputIterator result, Compare comp) {\n    return std::set_intersection(first1, last1, first2, last2, result,\n                                 std::bind(comp, std::placeholders::_1, std::placeholders::_2));\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputRange1, class InputRange2, class OutputIterator, class Compare>\ninline OutputIterator set_intersection(const InputRange1& range1, const InputRange2& range2,\n                                       OutputIterator result, Compare comp) {\n    return adobe::set_intersection(boost::begin(range1), boost::end(range1), boost::begin(range2),\n                                   boost::end(range2), result, comp);\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputRange1, class InputRange2, class OutputIterator>\ninline OutputIterator set_difference(const InputRange1& range1, const InputRange2& range2,\n                                     OutputIterator result) {\n    return std::set_difference(boost::begin(range1), boost::end(range1), boost::begin(range2),\n                               boost::end(range2), result);\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputIterator1, class InputIterator2, class OutputIterator, class Compare>\ninline OutputIterator set_difference(InputIterator1 first1, InputIterator1 last1,\n                                     InputIterator2 first2, InputIterator2 last2,\n                                     OutputIterator result, Compare comp) {\n    return std::set_difference(first1, last1, first2, last2, result,\n                               std::bind(comp, std::placeholders::_1, std::placeholders::_2));\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputRange1, class InputRange2, class OutputIterator, class Compare>\ninline OutputIterator set_difference(const InputRange1& range1, const InputRange2& range2,\n                                     OutputIterator result, Compare comp) {\n    return adobe::set_difference(boost::begin(range1), boost::end(range1), boost::begin(range2),\n                                 boost::end(range2), result, comp);\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputRange1, class InputRange2, class OutputIterator>\ninline OutputIterator set_symmetric_difference(const InputRange1& range1, const InputRange2& range2,\n                                               OutputIterator result) {\n    return std::set_symmetric_difference(boost::begin(range1), boost::end(range1),\n                                         boost::begin(range2), boost::end(range2), result);\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputIterator1, class InputIterator2, class OutputIterator, class Compare>\ninline OutputIterator set_symmetric_difference(InputIterator1 first1, InputIterator1 last1,\n                                               InputIterator2 first2, InputIterator2 last2,\n                                               OutputIterator result, Compare comp) {\n    return std::set_symmetric_difference(\n        first1, last1, first2, last2, result,\n        std::bind(comp, std::placeholders::_1, std::placeholders::_2));\n}\n\n/*!\n    \\ingroup set\n\n    \\brief set implementation\n*/\ntemplate <class InputRange1, class InputRange2, class OutputIterator, class Compare>\ninline OutputIterator set_symmetric_difference(const InputRange1& range1, const InputRange2& range2,\n                                               OutputIterator result, Compare comp) {\n    return adobe::set_symmetric_difference(boost::begin(range1), boost::end(range1),\n                                           boost::begin(range2), boost::end(range2), result, comp);\n}\n\n/**************************************************************************************************/\n\n} // namespace adobe\n\n/**************************************************************************************************/\n\n#endif\n\n/**************************************************************************************************/\n", "meta": {"hexsha": "0a29610546d72184f531e05db301f02db7d24a1e", "size": 8486, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "adobe/algorithm/set.hpp", "max_stars_repo_name": "jaredwy/adobe_source_libraries", "max_stars_repo_head_hexsha": "b71f5d08ab10396e9d2ba5e73861ca018f899a2d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 252.0, "max_stars_repo_stars_event_min_datetime": "2015-01-09T13:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:02:01.000Z", "max_issues_repo_path": "adobe/algorithm/set.hpp", "max_issues_repo_name": "etiennemlb/adobe_source_libraries", "max_issues_repo_head_hexsha": "5ced8bf61fbb487e9a2c6fa3ea7abc2687448c3b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2015-05-04T23:49:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T18:31:51.000Z", "max_forks_repo_path": "adobe/algorithm/set.hpp", "max_forks_repo_name": "etiennemlb/adobe_source_libraries", "max_forks_repo_head_hexsha": "5ced8bf61fbb487e9a2c6fa3ea7abc2687448c3b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-06-09T07:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T17:35:05.000Z", "avg_line_length": 37.3832599119, "max_line_length": 100, "alphanum_fraction": 0.6016969126, "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5031647999179878}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 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#include <boost/simd/function/scalar/maxmag.hpp>\n#include <simd_test.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/two.hpp>\n\nSTF_CASE_TPL (\" maxmag real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n\n  using bs::maxmag;\n  // return type conformity test\n  STF_EXPR_IS(maxmag(T(),T()), T);\n\n  // specific values tests\n#ifndef STF_NO_INVALIDS\n  STF_EQUAL(maxmag(bs::Inf<T>(),  bs::Inf<T>()),  bs::Inf<T>());\n  STF_EQUAL(maxmag(bs::Minf<T>(), bs::Minf<T>()), bs::Minf<T>());\n  STF_IEEE_EQUAL(maxmag(bs::Nan<T>(),  bs::Nan<T>()),  bs::Nan<T>());\n#endif\n  STF_EQUAL(maxmag(bs::Mone<T>(), bs::Mone<T>()), bs::Mone<T>());\n  STF_EQUAL(maxmag(bs::One<T>(),  bs::One<T>()),  bs::One<T>());\n  STF_EQUAL(maxmag(bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n  STF_EQUAL(maxmag(bs::Nan<T>(),  bs::One<T>()),  bs::One<T>());\n  STF_IEEE_EQUAL(maxmag(bs::One<T>(),  bs::Nan<T>()),  bs::Nan<T>());\n  STF_EQUAL(maxmag(bs::One<T>(),  bs::Two<T>()),  bs::Two<T>());\n  STF_EQUAL(maxmag(bs::Two<T>(),  bs::One<T>()),  bs::Two<T>());\n  STF_EQUAL(maxmag(-bs::Two<T>(),  bs::One<T>()),  -bs::Two<T>());\n} // end of test for floating_\n\nSTF_CASE_TPL (\" maxmag unsigned int\",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n\n  using bs::maxmag;\n  // return type conformity test\n  STF_EXPR_IS(maxmag(T(),T()), T);\n\n  // specific values tests\n  STF_EQUAL(maxmag(bs::One<T>(),  bs::One<T>()),  bs::One<T>());\n  STF_EQUAL(maxmag(bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n  STF_EQUAL(maxmag(bs::One<T>(),  bs::Zero<T>()), bs::One<T>());\n  STF_EQUAL(maxmag(bs::Zero<T>(), bs::One<T>()),  bs::One<T>());\n} // end of test for unsigned_int_\n\nSTF_CASE_TPL (\" maxmag signed int\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n\n  using bs::maxmag;\n  // return type conformity test\n  STF_EXPR_IS(maxmag(T(),T()), T);\n\n  // specific values tests\n  STF_EQUAL(maxmag(bs::Mone<T>(), bs::Mone<T>()), bs::Mone<T>());\n  STF_EQUAL(maxmag(bs::One<T>(),  bs::One<T>()),  bs::One<T>());\n  STF_EQUAL(maxmag(bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n  STF_EQUAL(maxmag(bs::One<T>(),  bs::Zero<T>()), bs::One<T>());\n  STF_EQUAL(maxmag(bs::Zero<T>(), bs::One<T>()),  bs::One<T>());\n  STF_EQUAL(maxmag(bs::Mone<T>(), bs::Zero<T>()), bs::Mone<T>());\n  STF_EQUAL(maxmag(bs::Zero<T>(), bs::Mone<T>()), bs::Mone<T>());\n} // end of test for signed_int_\n", "meta": {"hexsha": "472b96348d6e57548a86a2613674a10a1bec59ea", "size": 2988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/maxmag.cpp", "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": "test/function/scalar/maxmag.cpp", "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": "test/function/scalar/maxmag.cpp", "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": 38.8051948052, "max_line_length": 100, "alphanum_fraction": 0.5799866131, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5031647903980695}}
{"text": "// Copyright (c) Dietmar Wolz.\r\n//\r\n// This source code is licensed under the MIT license found in the\r\n// LICENSE file in the root directory.\r\n\r\n// Eigen based implementation of differential evolution using onl the DE/best/1 strategy.\r\n// Uses two deviations from the standard DE algorithm:\r\n// a) temporal locality introduced in \r\n// https://www.researchgate.net/publication/309179699_Differential_evolution_for_protein_folding_optimization_based_on_a_three-dimensional_AB_off-lattice_model\r\n// b) reinitialization of individuals based on their age. \r\n// requires https://github.com/imneme/pcg-cpp\r\n\r\n#include <Eigen/Core>\r\n#include <iostream>\r\n#include <float.h>\r\n#include <ctime>\r\n#include <random>\r\n#include \"pcg_random.hpp\"\r\n\r\nusing namespace std;\r\n\r\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1> vec;\r\ntypedef Eigen::Matrix<int, Eigen::Dynamic, 1> ivec;\r\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat;\r\n\r\ntypedef double (*callback_type)(int, double[]);\r\n\r\nnamespace differential_evolution {\r\n\r\nstatic uniform_real_distribution<> distr_01 = std::uniform_real_distribution<>(0, 1);\r\n\r\nstatic vec zeros(int n) {\r\n\treturn  Eigen::MatrixXd::Zero(n, 1);\r\n}\r\n\r\nstatic Eigen::MatrixXd uniform(int dx, int dy, pcg64& rs) {\r\n\treturn Eigen::MatrixXd::NullaryExpr( dx, dy, [&](){return distr_01(rs);});\r\n}\r\n\r\nstatic Eigen::MatrixXd uniformVec(int dim, pcg64& rs) {\r\n\treturn Eigen::MatrixXd::NullaryExpr( dim, 1, [&](){return distr_01(rs);});\r\n}\r\n\r\nint index_max(vec& v) {\r\n\tdouble maxv = DBL_MIN;\r\n\tint mi = -1;\r\n\tfor (int i = 0; i < v.size(); i++) {\r\n\t\tif (v[i] > maxv) {\r\n\t\t\tmi = i;\r\n\t\t\tmaxv = v[i];\r\n\t\t}\r\n\t}\r\n\treturn mi;\r\n}\r\n\r\nint index_min(vec& v) {\r\n\tdouble minv = DBL_MAX;\r\n\tint mi = -1;\r\n\tfor (int i = 0; i < v.size(); i++) {\r\n\t\tif (v[i] < minv) {\r\n\t\t\tmi = i;\r\n\t\t\tminv = v[i];\r\n\t\t}\r\n\t}\r\n\treturn mi;\r\n}\r\n\r\nstruct IndexVal {\r\n    int index;\r\n    double val;\r\n};\r\n\r\nbool compareIndexVal(IndexVal i1, IndexVal i2) {\r\n    return (i1.val < i2.val);\r\n}\r\n\r\nivec sort_index(const vec& x) {\r\n\tint size = x.size();\r\n\tIndexVal ivals[size];\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\tivals[i].index = i;\r\n\t\tivals[i].val = x[i];\r\n\t}\r\n\tstd::sort(ivals, ivals+size, compareIndexVal);\r\n\treturn Eigen::MatrixXi::NullaryExpr( size, 1, [&ivals](int i){return ivals[i].index;});\r\n}\r\n\r\n// wrapper around the fittness function, scales according to boundaries\r\n\r\nclass Fittness {\r\n\r\npublic:\r\n\r\n    Fittness(callback_type pfunc, const vec& lower_limit,\r\n            const vec& upper_limit) {\r\n        func = pfunc;\r\n        lower = lower_limit;\r\n        upper = upper_limit;\r\n        evaluationCounter = 0;\r\n        if (lower.size() > 0) // bounds defined\r\n            scale = (upper - lower);\r\n    }\r\n\r\n    vec getClosestFeasible(const vec& X) const {\r\n        if (lower.size() > 0) {\r\n        \treturn X.cwiseMin(1.0).cwiseMax(0.0);\r\n        }\r\n        return X;\r\n    }\r\n\r\n    double eval(const vec& X) {\r\n        int n = X.size();\r\n        double parg[n];\r\n        for (int i = 0; i < n; i++)\r\n            parg[i] = X(i);\r\n        double res = func(n, parg);\r\n        evaluationCounter++;\r\n        return res;\r\n    }\r\n\r\n    double value(const vec& X) {\r\n        if (lower.size() > 0)\r\n            return eval(decode(X));\r\n        else\r\n            return eval(X);\r\n    }\r\n\r\n\tvec decode(const vec& X) const {\r\n\t\tif (lower.size() > 0)\r\n\t\t\treturn (X.array() * scale.array()).matrix() + lower;\r\n\t\telse\r\n\t\t\treturn X;\r\n\t}\r\n\r\n    vec encode(const vec& X) const {\r\n        if (lower.size() > 0)\r\n        \treturn (X - lower).array() / scale.array();\r\n        else\r\n            return X;\r\n    }\r\n\r\n    int getEvaluations() {\r\n        return evaluationCounter;\r\n    }\r\n\r\nprivate:\r\n   callback_type func;\r\n   vec lower;\r\n   vec upper;\r\n   long evaluationCounter;\r\n   vec scale;\r\n};\r\n\r\nclass DeOptimizer {\r\n\r\npublic:\r\n\r\n    DeOptimizer(long runid_, Fittness* fitfun_, int dim_, int seed_, int popsize_, \r\n            int maxEvaluations_, double keep_,  \r\n            double stopfitness_, double F_, double CR_) {\r\n        // runid used to identify a specific run\r\n        runid = runid_;\r\n        // fitness function to minimize\r\n        fitfun = fitfun_;\r\n        // Number of objective variables/problem dimension\r\n        dim = dim_;\r\n        // Population size\r\n        if (popsize_ > 0)\r\n            popsize = popsize_;\r\n        else\r\n            popsize = 15*dim;\r\n        // termination criteria\r\n        // maximal number of evaluations allowed.\r\n        maxEvaluations = maxEvaluations_;\r\n        // keep best young after each iteration.\r\n        keep = keep_;\r\n        // Limit for fitness value.\r\n        stopfitness = stopfitness_;\r\n        F = F_;\r\n        CR = CR_;\r\n        // Number of iterations already performed.\r\n        iterations = 0;\r\n        bestValue = DBL_MAX;\r\n        // stop criteria\r\n        stop = 0;\r\n        //std::random_device rd;\r\n        rs = new pcg64(seed_);\r\n        init();\r\n    }\r\n\r\n    ~DeOptimizer() {\r\n    \tdelete rs;\r\n    }\r\n\r\n    double rnd01() {\r\n        return distr_01(*rs);\r\n    }\r\n \r\n    double rnd02() {\r\n        double rnd = distr_01(*rs);\r\n        return rnd*rnd;\r\n    }\r\n\r\n    int rndInt(int max) {\r\n        return (int) (max*distr_01(*rs));\r\n    } \r\n\r\n    void doOptimize() {\r\n    \r\n        // -------------------- Generation Loop --------------------------------\r\n\r\n        for (iterations = 1; fitfun->getEvaluations() < maxEvaluations; iterations++) {\r\n            for (int k = 0; k < popsize; k++) {\r\n                vec xi = popX.col(k);\r\n                vec xb = popX.col(bestI);\r\n                int r1, r2;\r\n                do { r1 = rndInt(popsize); } while (r1 == k);\r\n                do { r2 = rndInt(popsize); } while (r2 == k || r2 == r1);\r\n                int jr = rndInt(dim);\r\n                vec ui = vec(xi);\r\n                for (int j = 0; j < dim; j++) {\r\n                    if (j == jr || rnd01() < CR) \r\n                        //ui[j] = base[j] + F*(popX(j,r1) - popX(j,r2));       \r\n                        ui[j] = xb[j] + F*(popX(j,r1) - popX(j,r2));       \r\n                }\r\n                ui = fitfun->getClosestFeasible(ui);\r\n \r\n                double eu = fitfun->value(ui); \r\n                if (!isfinite(eu)) {\r\n                    stop = -1;\r\n                    return;\r\n                }\r\n                if (eu < popY[k]) {\r\n                    // temporal locality\r\n                    vec uis = xb + ((ui - xi)*0.5);\r\n                    uis = fitfun->getClosestFeasible(uis);\r\n                    double eus = fitfun->value(uis); \r\n                    if (!isfinite(eus)) {\r\n                        stop = -1;\r\n                        return;\r\n                    }\r\n                    if (eus < eu) {\r\n                        popX.col(k) = uis;\r\n                        popY(k) = eus;\r\n                    } else {\r\n                        popX.col(k) = ui;\r\n                        popY(k) = eu;\r\n                    }\r\n                    popIter[k] = iterations;\r\n                    if (popY[k] < popY[bestI]) {\r\n                        bestI = k;\r\n                        if (popY(bestI) < bestValue) {\r\n                            bestValue = popY[bestI];\r\n                            bestX = popX.col(bestI);\r\n                            if (isfinite(stopfitness) && bestValue < stopfitness) {\r\n                                stop = 1;\r\n                                return;\r\n                            }         \r\n                        }\r\n                    }    \r\n                 }  \r\n                 else {\r\n                    // reinitialize individual\r\n                    if (keep * rnd02() + 3 < iterations - popIter[k]) { \r\n                        popX.col(k) = uniformVec(dim, *rs);\r\n                        popY[k] = fitfun->value(popX.col(k)); // compute fitness\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n \r\n    void init() {\r\n        popX = uniform(dim, popsize, *rs);\r\n        popY = vec(popsize);\r\n        for (int i = 0; i < popsize; i++)\r\n            popY[i] = fitfun->value(popX.col(i)); // compute fitness\r\n        bestI = index_min(popY);\r\n        bestX = popX.col(bestI);\r\n        popIter = zeros(popsize);\r\n    }\r\n    \r\n    vec getBestX() {\r\n        return bestX;\r\n    }\r\n\r\n    double getBestValue() {\r\n        return bestValue;\r\n    }\r\n\r\n    double getIterations() {\r\n        return iterations;\r\n    }\r\n\r\n    double getStop() {\r\n        return stop;\r\n    }\r\n\r\nprivate:\r\n      long runid;\r\n      Fittness* fitfun;\r\n      int popsize; // population size\r\n      int dim;\r\n      int maxEvaluations;\r\n      double keep;\r\n      double stopfitness;\r\n      int iterations;\r\n      double guessValue;\r\n      vec guess;\r\n      double bestValue;\r\n      vec bestX;\r\n      int bestI;\r\n      int stop;\r\n      double F;\r\n      double CR;\r\n      pcg64* rs;\r\n      mat popX;\r\n      vec popY;\r\n      vec popIter;\r\n};\r\n\r\n// see https://cvstuff.wordpress.com/2014/11/27/wraping-c-code-with-python-ctypes-memory-and-pointers/\r\n\r\n}\r\n\r\nusing namespace differential_evolution;\r\n\r\nextern \"C\" {\r\n    double* optimizeDE_C(long runid, callback_type func, int dim, int seed,\r\n            double *lower, double *upper, int maxEvals, double keep,\r\n            double stopfitness, int popsize, double F, double CR) {\r\n        int n = dim;\r\n        double *res = new double[n + 4];\r\n        vec lower_limit(n), upper_limit(n);\r\n        bool useLimit = false;\r\n        for (int i = 0; i < n; i++) {\r\n            lower_limit[i] = lower[i];\r\n            upper_limit[i] = upper[i];\r\n            useLimit |= (lower[i] != 0);\r\n            useLimit |= (upper[i] != 0);\r\n        }\r\n        if (useLimit == false) {\r\n            lower_limit.resize(0);\r\n            upper_limit.resize(0);\r\n        } \r\n        Fittness fitfun(func, lower_limit, upper_limit);\r\n        DeOptimizer opt(\r\n            runid,\r\n            &fitfun,\r\n            dim,\r\n            seed,\r\n            popsize,\r\n            maxEvals,\r\n            keep,\r\n            stopfitness,\r\n            F,\r\n            CR);\r\n        try {\r\n            opt.doOptimize();\r\n            vec bestX = fitfun.decode(opt.getBestX());\r\n            double bestY = opt.getBestValue();\r\n            for (int i = 0; i < n; i++)\r\n                res[i] = bestX[i];\r\n            res[n] = bestY;\r\n            res[n+1] = fitfun.getEvaluations();\r\n            res[n+2] = opt.getIterations();\r\n            res[n+3] = opt.getStop();\r\n            return res;\r\n        } catch (std::exception& e) {\r\n            cout << e.what() << endl;\r\n            return res;\r\n        }\r\n    }\r\n}\r\n", "meta": {"hexsha": "00978e6a3962da9cffd39da21b0607c69c003cd1", "size": 10543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_fcmaescpp/deoptimizer.cpp", "max_stars_repo_name": "MingchengZuo/fast-cma-es", "max_stars_repo_head_hexsha": "ada34f50b93d52493d768ad67addaf915f9e0d2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-07T08:43:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T08:43:49.000Z", "max_issues_repo_path": "_fcmaescpp/deoptimizer.cpp", "max_issues_repo_name": "MingchengZuo/fast-cma-es", "max_issues_repo_head_hexsha": "ada34f50b93d52493d768ad67addaf915f9e0d2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_fcmaescpp/deoptimizer.cpp", "max_forks_repo_name": "MingchengZuo/fast-cma-es", "max_forks_repo_head_hexsha": "ada34f50b93d52493d768ad67addaf915f9e0d2f", "max_forks_repo_licenses": ["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.1146666667, "max_line_length": 160, "alphanum_fraction": 0.4793701982, "num_tokens": 2568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5031647825151907}}
{"text": "#include <iostream>\n\n#include <Eigen/Geometry>\n\n#include \"pnp_solver.h\"\n#include \"params_config.h\"\n\nnamespace fast_p3p\n{\n\nP3PSolver::P3PSolver(const std::vector<Eigen::Vector3d> &v_bearings,\n                     const std::vector<cv::Point2d> &v_keypoints,\n                     const std::vector<Eigen::Vector3d> &v_map_points,\n                     const Eigen::Matrix3d &intrinsicMatrix,\n                     const int img_width,\n                     const int img_height) : best_inlier_nb_(0),\n                                             best_reprojection_error_(std::numeric_limits<double>::max()),\n                                             img_width_(img_width),\n                                             img_height_(img_height)\n{\n    // assert(v_bearing_points.size() == v_map_points.size() && v_bearing_points.size() > 3);\n\n    assert(v_keypoints.size() == v_bearings.size() && v_bearings.size() > 3);\n\n    total_correspondeces_nb_ = v_bearings.size();\n\n    // std::cout << \"2D keypoints size : \" << v_keypoints.size() << \"\\n\";\n    // std::cout << \"Map points size : \" << v_map_points.size() << \"\\n\";\n    // std::cout << \"image width : \" << img_width_ << \"\\n\";\n    // std::cout << \"image height : \" << img_height_ << \"\\n\";\n\n    v_bearing_set_ = v_bearings;\n    v_keypoint_set_ = v_keypoints;\n    v_map_point_set_ = v_map_points;\n\n    if (intrinsicMatrix.hasNaN())\n    {\n        ERROR_STREAM(\"[P3PSolver] Invalid intrinsic Matrix!\");\n    }\n    else\n    {\n        cam_intrinsic_ = intrinsicMatrix;\n    }\n\n    // debug the projected keypoints\n    // std::string img_path = \"/home/ziqianbai/Projects/vlab/3d_marker_localizer/build/20200402/undist_low/undist_20200402-224626-551d194e_i0_0.jpg\";\n    // debug_img_mat_ = cv::imread(img_path);\n}\n\nP3PSolver::~P3PSolver()\n{\n    // std::string out_img_path = \"/home/ziqianbai/Projects/vlab/3d_marker_localizer/build/20200402/undist_low/undist_20200402-224626-551d194e_i0_0_projected.jpg\";\n    // cv::imwrite(out_img_path, debug_img_mat_);\n}\n\nvoid P3PSolver::solveQuarticPolynomial(const std::array<double, 5> &coeffs,\n                                       std::array<double, 4> &real_roots)\n{\n    const double a = coeffs[0];\n    const double b = coeffs[1] / a;\n    const double c = coeffs[2] / a;\n    const double d = coeffs[3] / a;\n    const double e = coeffs[4] / a;\n\n    const std::complex<double> Q1 = c * c - 3. * b * d + 12. * e;\n    const std::complex<double> Q2 = 2. * c * c * c - 9. * b * c * d + 27. * d * d + 27. * b * b * e - 72. * c * e;\n    const std::complex<double> Q3 = 8. * b * c - 16. * d - 2. * b * b * b;\n    const std::complex<double> Q4 = 3. * b * b - 8. * c;\n\n    auto complex_cbrt = [](const std::complex<double> &z) -> std::complex<double> { return pow(z, 1. / 3.); };\n    const std::complex<double> Q5 = complex_cbrt(Q2 / 2. + sqrt(Q2 * Q2 / 4. - Q1 * Q1 * Q1));\n    const std::complex<double> Q6 = (Q1 / Q5 + Q5) / 3.;\n    const std::complex<double> Q7 = 2. * sqrt(Q4 / 12. + Q6);\n\n    real_roots = {{(-b - Q7 - sqrt(4. * Q4 / 6. - 4. * Q6 - Q3 / Q7)).real() / 4.,\n                   (-b - Q7 + sqrt(4. * Q4 / 6. - 4. * Q6 - Q3 / Q7)).real() / 4.,\n                   (-b + Q7 - sqrt(4. * Q4 / 6. - 4. * Q6 + Q3 / Q7)).real() / 4.,\n                   (-b + Q7 + sqrt(4. * Q4 / 6. - 4. * Q6 + Q3 / Q7)).real() / 4.}};\n}\n\nvoid P3PSolver::polishQuarticPolynomialRoots(const std::array<double, 5> &coeffs,\n                                             std::array<double, 4> &roots,\n                                             const int iterations)\n{\n    for (int i = 0; i < iterations; ++i)\n    {\n        for (auto &root : roots)\n        {\n            const double error =\n                coeffs[4] + root * (coeffs[3] + root * (coeffs[2] + root * (coeffs[1] + root * coeffs[0])));\n\n            const double derivative =\n                coeffs[3] + root * (2 * coeffs[2] + root * ((4 * coeffs[0] * root + 3 * coeffs[1])));\n\n            root -= error / derivative;\n        }\n    }\n}\n\nvoid P3PSolver::solveAP3P(const Eigen::MatrixXd &bearing_vectors,\n                          const Eigen::MatrixXd &world_points,\n                          std::vector<Eigen::Matrix4d> &solutions)\n{\n    assert(bearing_vectors.cols() >= 3 && world_points.cols() >= 3);\n    const Eigen::Vector3d w1 = world_points.col(0);\n    const Eigen::Vector3d w2 = world_points.col(1);\n    const Eigen::Vector3d w3 = world_points.col(2);\n\n    const Eigen::Vector3d b1 = bearing_vectors.col(0);\n    const Eigen::Vector3d b2 = bearing_vectors.col(1);\n    const Eigen::Vector3d b3 = bearing_vectors.col(2);\n\n    // calculate k1, k2, k3\n    const Eigen::Vector3d u0 = w1 - w2;\n    const double nu0 = u0.norm();\n    const Eigen::Vector3d k1 = u0.normalized();\n    Eigen::Vector3d k3 = b1.cross(b2);\n    const double nk3 = k3.norm();\n    k3 = k3.normalized();\n\n    const Eigen::Vector3d tz = b1.cross(k3);\n    // ui, vi\n    const Eigen::Vector3d v1 = b1.cross(b3);\n    const Eigen::Vector3d v2 = b2.cross(b3);\n\n    const Eigen::Vector3d u1 = w1 - w3;\n    // coefficients related terms\n    const double u1k1 = u1.dot(k1);\n    const double k3b3 = k3.dot(b3);\n    // f1i\n    double f11 = k3b3;\n    double f13 = k3.dot(v1);\n    const double f15 = -u1k1 * f11;\n    // delta\n    const Eigen::Vector3d nl = u1.cross(k1).normalized();\n    const double delta = u1.cross(k1).norm();\n    f11 *= delta;\n    f13 *= delta;\n    // f2i\n    const double u2k1 = u1k1 - nu0;\n    double f21 = tz.dot(v2);\n    double f22 = nk3 * k3b3;\n    double f23 = k3.dot(v2);\n    const double f24 = u2k1 * f22;\n    const double f25 = -u2k1 * f21;\n    f21 *= delta;\n    f22 *= delta;\n    f23 *= delta;\n    const double g1 = f13 * f22;\n    const double g2 = f13 * f25 - f15 * f23;\n    const double g3 = f11 * f23 - f13 * f21;\n    const double g4 = -f13 * f24;\n    const double g5 = f11 * f22;\n    const double g6 = f11 * f25 - f15 * f21;\n    const double g7 = -f15 * f24;\n    const std::array<double, 5> coeffs = {{g5 * g5 + g1 * g1 + g3 * g3, 2 * (g5 * g6 + g1 * g2 + g3 * g4),\n                                           g6 * g6 + 2 * g5 * g7 + g2 * g2 + g4 * g4 - g1 * g1 - g3 * g3,\n                                           2 * (g6 * g7 - g1 * g2 - g3 * g4), g7 * g7 - g2 * g2 - g4 * g4}};\n    std::array<double, 4> s;\n    solveQuarticPolynomial(coeffs, s);\n    polishQuarticPolynomialRoots(coeffs, s);\n\n    const Eigen::Vector3d temp = k1.cross(nl);\n\n    Eigen::Matrix3d Ck1nl;\n    Ck1nl << k1, nl, temp;\n\n    Eigen::Matrix3d Cb1k3tzT;\n    Cb1k3tzT << b1.transpose(), k3.transpose(), tz.transpose();\n\n    const Eigen::Vector3d b3p = b3 * (delta / k3b3);\n\n    for (const auto ctheta1p : s)\n    {\n        if (std::abs(ctheta1p) > 1)\n            continue;\n        const double stheta1p = ((k3b3 > 0) ? 1 : -1) * sqrt(1 - ctheta1p * ctheta1p);\n        const double ntheta3 = stheta1p / ((g5 * ctheta1p + g6) * ctheta1p + g7);\n        const double ctheta3 = (g1 * ctheta1p + g2) * ntheta3;\n        const double stheta3 = (g3 * ctheta1p + g4) * ntheta3;\n\n        Eigen::Matrix3d C13;\n        C13 << ctheta3, 0.0, -stheta3, stheta1p * stheta3, ctheta1p, stheta1p * ctheta3, ctheta1p * stheta3, -stheta1p,\n            ctheta1p * ctheta3;\n\n        const Eigen::Matrix3d R = (Ck1nl * C13) * Cb1k3tzT;\n        // R' * p3\n        const Eigen::Vector3d rp3 = R.transpose() * w3;\n        Eigen::Matrix4d T;\n        T.setIdentity();\n        T.block<3, 3>(0, 0) = R.transpose();\n        Eigen::Vector3d t = (b3p * stheta1p) - rp3;\n        T.block<3, 1>(0, 3) = t;\n        solutions.emplace_back(T);\n    }\n}\n\n// still use pixel error as reprojection error to evcaluate solution\nint P3PSolver::evaluateSolutions(const Eigen::Matrix4d &solution,\n                                 std::map<int, int> &valid_matches,\n                                 double &mean_reprojection_error)\n{\n    int valid_measurement = initialMeasurement();\n\n    valid_matches.clear();\n    for (size_t i = 0; i < v_map_point_set_.size(); ++i)\n    {\n        valid_matches[i] = -1;\n    }\n\n    mean_reprojection_error = 0.0;\n\n    double eps = std::numeric_limits<double>::epsilon();\n    const double img_left_bound = ParamsConfig::GetImageBound();\n    const double img_right_bound = img_width_ - img_left_bound;\n    const double img_up_bound = ParamsConfig::GetImageBound();\n    const double img_bottom_bound = img_height_ - img_up_bound;\n\n    for (size_t i = 0; i < v_map_point_set_.size(); ++i)\n    {\n\n        Eigen::Vector3d map_point = v_map_point_set_[i];\n\n        Eigen::Vector3d proj_point = (solution * map_point.homogeneous()).hnormalized();\n        if (proj_point[2] <= eps)\n        {\n            continue;\n        }\n\n        Eigen::Vector3d img_point = cam_intrinsic_ * proj_point;\n        double img_x = img_point[0] / img_point[2];\n        double img_y = img_point[1] / img_point[2];\n\n        if (img_left_bound < img_x && img_x < img_right_bound &&\n            img_up_bound < img_y && img_y < img_bottom_bound)\n        {\n            for (size_t j = 0; j < v_keypoint_set_.size(); ++j)\n            {\n                double x_err = (img_x - v_keypoint_set_[j].x);\n                double y_err = (img_y - v_keypoint_set_[j].y);\n                double dist = std::sqrt(x_err * x_err + y_err * y_err);\n                if (dist < reproject_err_thre_)\n                {\n                    valid_matches[i] = j;\n                    valid_measurement += 1;\n                    mean_reprojection_error += dist;\n\n                    // {\n                    //     const cv::Scalar color(0, 0, 255);\n                    //     cv::line(debug_img_mat_, cv::Point(img_x - 20, img_y), cv::Point(img_x + 20, img_y),\n                    //              color, 1);\n                    //     cv::line(debug_img_mat_, cv::Point(img_x, img_y - 20), cv::Point(img_x, img_y + 20),\n                    //              color, 1);\n                    // }\n                }\n            }\n        }\n    }\n\n    // valid_measurement must fall into [0, v_keypoint_set_.size()]\n    if (valid_measurement == 0 || valid_measurement > static_cast<int>(v_keypoint_set_.size()))\n    {\n        valid_measurement = 0;\n        mean_reprojection_error = std::numeric_limits<double>::max();\n    }\n    else\n    {\n        mean_reprojection_error /= valid_measurement;\n    }\n\n    return valid_measurement;\n}\n\nbool P3PSolver::calcTransform(const std::vector<unsigned int> &sample_kpt_indices,\n                              const std::vector<unsigned int> &sample_map_indices)\n{\n    assert(sample_kpt_indices.size() > 2 && sample_kpt_indices.size() == sample_map_indices.size());\n\n    Eigen::MatrixXd bearing_mat(3, 3);\n    Eigen::MatrixXd world_mat(3, 3);\n    for (int i = 0; i < 3; ++i)\n    {\n        if (sample_kpt_indices[i] >= v_bearing_set_.size() || sample_map_indices[i] >= v_map_point_set_.size())\n        {\n            ERROR_STREAM(\"[calcTransform] Invalid sample indices!\");\n            return false;\n        }\n\n        bearing_mat.col(i) = v_bearing_set_[sample_kpt_indices[i]];\n        world_mat.col(i) = v_map_point_set_[sample_map_indices[i]];\n    }\n\n    // although AP3P is more robust to amgubility\n    // we still judge degenerate conditions:\n    // 1. colinear\n    // 2. 2 points\n    {\n        const double eps = std::numeric_limits<double>::epsilon();\n        double len01 = (world_mat.col(0) - world_mat.col(1)).norm();\n        double len12 = (world_mat.col(1) - world_mat.col(2)).norm();\n        double len02 = (world_mat.col(2) - world_mat.col(0)).norm();\n        // 2 point\n        if (len01 <= eps || len02 <= eps || len12 <= eps)\n        {\n            ERROR_STREAM(\"[P3PSolver::calcTransform] Invalid world map points!\");\n            return false;\n        }\n        // colinear, using heron's formula\n        double p = 0.5 * (len01 + len02 + len12);\n        double area = std::sqrt(p * (p - len01) * (p - len02) * (p - len12));\n        if (area <= eps)\n        {\n            ERROR_STREAM(\"[P3PSolver::calcTransform] Invalid world map points' area!\");\n            return false;\n        }\n    }\n\n    std::vector<Eigen::Matrix4d> solutions;\n    solveAP3P(bearing_mat, world_mat, solutions);\n    if (solutions.empty())\n    {\n        // ERROR_STREAM(\"[P3PSolver::calcTransform] Fail to solve relative pose from P3P!\");\n        return false;\n    }\n\n    best_inlier_nb_ = 0;\n    // check each solutions to avoid amgubility\n    for (size_t i = 0; i < solutions.size(); ++i)\n    {\n        // evaluate each solution on the whole input matches\n        Eigen::Matrix4d T = solutions[i];\n        if (T.hasNaN())\n            continue;\n\n        std::map<int, int> inlier_matches;\n        double mean_reproject_error = 0.0;\n        int measure = evaluateSolutions(T, inlier_matches, mean_reproject_error);\n        if (measure < minimalDataNumber())\n            continue;\n\n        if (measure > best_inlier_nb_ || (measure == best_inlier_nb_ && mean_reproject_error < best_reprojection_error_))\n        {\n            T_cw_ = T;\n            best_inlier_nb_ = measure;\n            best_reprojection_error_ = mean_reproject_error;\n            best_valid_matches_.swap(inlier_matches);\n            // DEBUG_STREAM(\"[calcTransform] best_inlier_num: \" << best_inlier_nb_);\n            // DEBUG_STREAM(\"[calcTransform] best_mean_reprojection_error: \" << best_reprojection_error_);\n        }\n    }\n\n    return true;\n}\n\nint P3PSolver::validateData(std::map<int, int> &inlier_matches)\n{\n    if (best_inlier_nb_ > 0)\n    {\n        inlier_matches.swap(best_valid_matches_);\n        return best_inlier_nb_;\n    }\n\n    for (size_t i = 0; i < v_map_point_set_.size(); ++i)\n    {\n        inlier_matches[i] = -1;\n    }\n    return worstMeasurement();\n}\n\n} // namespace fast_p3p\n", "meta": {"hexsha": "b18694d9d2d9b6b67cdfe2a7eb4c6e0e292c9f8f", "size": 13602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pnp_solver.cpp", "max_stars_repo_name": "alibaba/multiple-cameras-and-3D-LiDARs-extrinsic-calibration", "max_stars_repo_head_hexsha": "349bc8b954506721583b3571568fb8e23c2f1e83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2021-09-06T02:25:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T12:03:13.000Z", "max_issues_repo_path": "src/pnp_solver.cpp", "max_issues_repo_name": "alibaba/multiple-cameras-and-3D-LiDARs-extrinsic-calibration", "max_issues_repo_head_hexsha": "349bc8b954506721583b3571568fb8e23c2f1e83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pnp_solver.cpp", "max_forks_repo_name": "alibaba/multiple-cameras-and-3D-LiDARs-extrinsic-calibration", "max_forks_repo_head_hexsha": "349bc8b954506721583b3571568fb8e23c2f1e83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T22:30:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:43:24.000Z", "avg_line_length": 36.6630727763, "max_line_length": 163, "alphanum_fraction": 0.5602852522, "num_tokens": 4033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5030968448063556}}
{"text": "#include <stan/math/prim/mat.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n\nTEST(ProbDistributionsLkjCorr, testIdentity_0) {\n  boost::random::mt19937 rng;\n  unsigned int K = 4;\n  Eigen::MatrixXd Sigma(K, K);\n  Sigma.setZero();\n  Sigma.diagonal().setOnes();\n  double eta = stan::math::uniform_rng(0, 2, rng);\n  double f = stan::math::do_lkj_constant(eta, K);\n  EXPECT_FLOAT_EQ(f, stan::math::lkj_corr_log(Sigma, eta));\n  eta = 1.0;\n  f = stan::math::do_lkj_constant(eta, K);\n  EXPECT_FLOAT_EQ(f, stan::math::lkj_corr_log(Sigma, eta));\n}\n\nTEST(ProbDistributionsLkjCorr, testHalf_0) {\n  boost::random::mt19937 rng;\n  unsigned int K = 4;\n  Eigen::MatrixXd Sigma(K, K);\n  Sigma.setConstant(0.5);\n  Sigma.diagonal().setOnes();\n  double eta = stan::math::uniform_rng(0, 2, rng);\n  double f = stan::math::do_lkj_constant(eta, K);\n  EXPECT_FLOAT_EQ(f + (eta - 1.0) * log(0.3125),\n                  stan::math::lkj_corr_log(Sigma, eta));\n  eta = 1.0;\n  f = stan::math::do_lkj_constant(eta, K);\n  EXPECT_FLOAT_EQ(f, stan::math::lkj_corr_log(Sigma, eta));\n}\n\nTEST(ProbDistributionsLkjCorr, Sigma_0) {\n  boost::random::mt19937 rng;\n  unsigned int K = 4;\n  Eigen::MatrixXd Sigma(K, K);\n  Sigma.setZero();\n  Sigma.diagonal().setOnes();\n  double eta = stan::math::uniform_rng(0, 2, rng);\n  EXPECT_NO_THROW(stan::math::lkj_corr_log(Sigma, eta));\n\n  EXPECT_THROW(stan::math::lkj_corr_log(Sigma, -eta), std::domain_error);\n\n  Sigma = Sigma * -1.0;\n  EXPECT_THROW(stan::math::lkj_corr_log(Sigma, eta), std::domain_error);\n  Sigma = Sigma * (0.0 / 0.0);\n  EXPECT_THROW(stan::math::lkj_corr_log(Sigma, eta), std::domain_error);\n\n  Sigma.setConstant(0.5);\n  Sigma.diagonal().setOnes();\n  EXPECT_THROW(stan::math::lkj_corr_cholesky_log(Sigma, eta),\n               std::domain_error);\n}\n\nTEST(ProbDistributionsLKJCorr, error_check) {\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::lkj_corr_cholesky_rng(5, 1.0, rng));\n  EXPECT_NO_THROW(stan::math::lkj_corr_rng(5, 1.0, rng));\n\n  EXPECT_THROW(stan::math::lkj_corr_cholesky_rng(5, -1.0, rng),\n               std::domain_error);\n  EXPECT_THROW(stan::math::lkj_corr_rng(5, -1.0, rng), std::domain_error);\n}\n\nTEST(ProbDistributionsLKJCorr, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int N = 10000;\n  int K = stan::math::round(2 * std::pow(N, 0.4));\n  boost::math::beta_distribution<> dist(2.5, 2.5);\n  boost::math::chi_squared mydist(K - 1);\n\n  double loc[K - 1];\n  for (int i = 1; i < K; i++)\n    loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));\n\n  int count = 0;\n  int bin[K];\n  double expect[K];\n  for (int i = 0; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N / K;\n  }\n\n  while (count < N) {\n    double a = 0.5 * (1.0 + stan::math::lkj_corr_rng(5, 1.0, rng)(3, 4));\n    int i = 0;\n    while (i < K - 1 && a > loc[i])\n      ++i;\n    ++bin[i];\n    count++;\n  }\n\n  double chi = 0;\n\n  for (int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsLkjCorrCholesky, testIdentity) {\n  boost::random::mt19937 rng;\n  unsigned int K = 4;\n  Eigen::MatrixXd Sigma(K, K);\n  Sigma.setZero();\n  Sigma.diagonal().setOnes();\n  double eta = stan::math::uniform_rng(0, 2, rng);\n  double f = stan::math::do_lkj_constant(eta, K);\n  EXPECT_FLOAT_EQ(f, stan::math::lkj_corr_cholesky_log(Sigma, eta));\n  eta = 1.0;\n  f = stan::math::do_lkj_constant(eta, K);\n  EXPECT_FLOAT_EQ(f, stan::math::lkj_corr_cholesky_log(Sigma, eta));\n}\n\nTEST(ProbDistributionsLkjCorrCholesky, testHalf) {\n  boost::random::mt19937 rng;\n  unsigned int K = 4;\n  Eigen::MatrixXd Sigma(K, K);\n  Sigma.setConstant(0.5);\n  Sigma.diagonal().setOnes();\n  Eigen::MatrixXd L = Sigma.llt().matrixL();\n  double eta = stan::math::uniform_rng(0, 2, rng);\n  double f = stan::math::do_lkj_constant(eta, K);\n  EXPECT_FLOAT_EQ(stan::math::lkj_corr_log(Sigma, eta) - 0.4904146,\n                  stan::math::lkj_corr_cholesky_log(L, eta));\n  eta = 1.0;\n  f = stan::math::do_lkj_constant(eta, K);\n  EXPECT_FLOAT_EQ(f - 0.4904146, stan::math::lkj_corr_cholesky_log(L, eta));\n}\n", "meta": {"hexsha": "a1bbfc0cb38db287c2e6e7f7a0b972e2e1e42267", "size": 4153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/mat/prob/lkj_corr_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/prim/mat/prob/lkj_corr_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/prim/mat/prob/lkj_corr_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": 31.4621212121, "max_line_length": 76, "alphanum_fraction": 0.6518179629, "num_tokens": 1437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370423, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5030968404680679}}
{"text": "// TRENTO: Reduced Thickness Event-by-event Nuclear Topology\n// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland\n// MIT License\n\n#include \"nucleus.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <utility>\n\n#include <boost/math/constants/constants.hpp>\n#ifdef TRENTO_HDF5\n// include multi_array for use with ManualNucleus\n#ifdef NDEBUG\n#define BOOST_DISABLE_ASSERTS\n#endif\n#include <boost/multi_array.hpp>\n#endif\n\n#include \"hdf5_utils.h\"\n#include \"random.h\"\n\nnamespace trento {\n\nNucleusPtr Nucleus::create(const std::string& species, double nucleon_dmin) {\n  // W-S params ref. in header\n  // XXX: remember to add new species to the help output in main() and the readme\n  if (species == \"p\")\n    return NucleusPtr{new Proton{}};\n  else if (species == \"d\")\n    return NucleusPtr{new Deuteron{}};\n  else if (species == \"Cu\")\n    return NucleusPtr{new WoodsSaxonNucleus{\n       63, 4.20, 0.596, 0.0, nucleon_dmin\n    }};\n  else if (species == \"Cu2\")\n    return NucleusPtr{new DeformedWoodsSaxonNucleus{\n       63, 4.20, 0.596, 0.162, -0.006, nucleon_dmin\n    }};\n  else if (species == \"O\")\n      return NucleusPtr{new WoodsSaxonNucleus{\n              16, 2.608, 0.513, -0.051, nucleon_dmin\n      }};\n  else if (species == \"Xe\")\n    return NucleusPtr{new WoodsSaxonNucleus{\n      129, 5.36, 0.590, 0.0, nucleon_dmin\n    }};\n  else if (species == \"Xe2\")\n    return NucleusPtr{new DeformedWoodsSaxonNucleus{\n      129, 5.36, 0.590, 0.162, -0.003, nucleon_dmin\n    }};\n  else if (species == \"XeTri\")\n    return NucleusPtr{new DeformedWoodsSaxonNucleus{\n     129, 5.60, 0.49, 0.21, 0.0, nucleon_dmin\n    }};\n    else if (species == \"XeALICE\")\n    return NucleusPtr{new DeformedWoodsSaxonNucleus{\n     129, 5.36, 0.590, 0.18, 0.0, nucleon_dmin\n    }};\n  else if (species == \"Au\")\n    return NucleusPtr{new WoodsSaxonNucleus{\n      197, 6.38, 0.535, 0.0, nucleon_dmin\n    }};\n  else if (species == \"Au2\")\n    return NucleusPtr{new DeformedWoodsSaxonNucleus{\n      197, 6.38, 0.535, -0.131, -0.031, nucleon_dmin\n    }};\n  else if (species == \"Pb\")\n    return NucleusPtr{new WoodsSaxonNucleus{\n      208, 6.62, 0.546, 0.0, nucleon_dmin\n    }};\n  else if (species == \"PbTri\")\n    return NucleusPtr{new WoodsSaxonNucleus{\n      208, 6.65, 0.54, 0.0, nucleon_dmin\n    }};\n  else if (species == \"U\")\n    return NucleusPtr{new DeformedWoodsSaxonNucleus{\n      238, 6.81, 0.600, 0.280, 0.093, nucleon_dmin\n    }};\n  else if (species == \"U2\")\n    return NucleusPtr{new DeformedWoodsSaxonNucleus{\n      238, 6.86, 0.420, 0.265, 0.000, nucleon_dmin\n    }};\n  else if (species == \"U3\")\n    return NucleusPtr{new DeformedWoodsSaxonNucleus{\n      238, 6.67, 0.440, 0.280, 0.093, nucleon_dmin\n    }};\n  // Read nuclear configurations from HDF5.\n  else if (hdf5::filename_is_hdf5(species)) {\n#ifdef TRENTO_HDF5\n    return ManualNucleus::create(species);\n#else\n    throw std::invalid_argument{\"HDF5 output was not compiled\"};\n#endif  // TRENTO_HDF5\n  }\n  else\n    throw std::invalid_argument{\"unknown projectile species: \" + species};\n}\n\nNucleus::Nucleus(std::size_t A) : nucleons_(A), offset_(0) {}\n\nvoid Nucleus::sample_nucleons(double offset) {\n  offset_ = offset;\n  sample_nucleons_impl();\n}\n\nvoid Nucleus::set_nucleon_position(\n    NucleonData& nucleon, double x, double y, double z) {\n  nucleon.set_position(x + offset_, y, z);\n}\n\nProton::Proton() : Nucleus(1) {}\n\n/// Always zero.\ndouble Proton::radius() const {\n  return 0.;\n}\n\n/// Always place the nucleon at the origin.\nvoid Proton::sample_nucleons_impl() {\n  set_nucleon_position(*begin(), 0., 0., 0.);\n}\n\n// Without loss of generality, let the internal a_ parameter be the minimum of\n// the given (a, b) and the internal b_ be the maximum.\nDeuteron::Deuteron(double a, double b)\n    : Nucleus(2),\n      a_(std::fmin(a, b)),\n      b_(std::fmax(a, b))\n{}\n\ndouble Deuteron::radius() const {\n  // The quantile function for the exponential distribution exp(-2*a*r) is\n  // -log(1-q)/(2a).  Return the 99% quantile.\n  return -std::log(.01)/(2*a_);\n}\n\nvoid Deuteron::sample_nucleons_impl() {\n  // Sample the inter-nucleon radius using rejection sampling with an envelope\n  // function.  The Hulth\u00e9n wavefunction including the r^2 Jacobian expands to\n  // three exponential terms:  exp(-2*a*r) + exp(-2*b*r) - 2*exp(-(a+b)*r).\n  // This does not have a closed-form inverse CDF, however we can easily sample\n  // exponential numbers from the term that falls off the slowest, i.e.\n  // exp(-2*min(a,b)*r).  In the ctor initializer list the \"a\" parameter is\n  // always set to the minimum, so we should sample from exp(-2*a*r).\n  double r, prob;\n  do {\n    // Sample a uniform random number, u = exp(-2*a*r).\n    auto u = random::canonical<double>();\n    // Invert to find the actual radius.\n    r = -std::log(u) / (2*a_);\n    // The acceptance probability is now the radial wavefunction over the\n    // envelope function, both evaluated at the proposal radius r.\n    // Conveniently, the envelope evaluated at r is just the uniform random\n    // number u.\n    prob = std::pow(std::exp(-a_*r) - std::exp(-b_*r), 2) / u;\n  } while (prob < random::canonical<double>());\n\n  // Now sample spherical rotation angles.\n  auto cos_theta = random::cos_theta<double>();\n  auto phi = random::phi<double>();\n\n  // And compute the Cartesian coordinates of one nucleon.\n  auto r_sin_theta = r * std::sqrt(1. - cos_theta*cos_theta);\n  auto x = r_sin_theta * std::cos(phi);\n  auto y = r_sin_theta * std::sin(phi);\n  auto z = r * cos_theta;\n\n  // Place the first nucleon at the sampled coordinates.\n  set_nucleon_position(*begin(), x, y, z);\n  // Place the second nucleon opposite to the first.\n  set_nucleon_position(*std::next(begin()), -x, -y, -z);\n}\n\nMinDistNucleus::MinDistNucleus(std::size_t A, double dmin)\n    : Nucleus(A),\n      dminsq_(dmin*dmin)\n{}\n\nbool MinDistNucleus::is_too_close(const_iterator nucleon) const {\n  if (dminsq_ < 1e-10)\n    return false;\n  for (const_iterator nucleon2 = begin(); nucleon2 != nucleon; ++nucleon2) {\n    auto dx = nucleon->x() - nucleon2->x();\n    auto dy = nucleon->y() - nucleon2->y();\n    auto dz = nucleon->z() - nucleon2->z();\n    if (dx*dx + dy*dy + dz*dz < dminsq_)\n      return true;\n  }\n  return false;\n}\n\n// Extend the W-S dist out to R + 10a; for typical values of (R, a), the\n// probability of sampling a nucleon beyond this radius is O(10^-5).\nWoodsSaxonNucleus::WoodsSaxonNucleus(\n    std::size_t A, double R, double a, double w, double dmin)\n    : MinDistNucleus(A, dmin),\n      R_(R),\n      a_(a),\n      woods_saxon_dist_(1000, 0., R + 10.*a,\n        [R, a, w](double r) { return r*r*(1+w*(r/R)*(r/R))/(1.+std::exp((r-R)/a)); })\n{}\n\n/// Return something a bit smaller than the true maximum radius.  The\n/// Woods-Saxon distribution falls off very rapidly (exponentially), and since\n/// this radius determines the impact parameter range, the true maximum radius\n/// would cause far too many events with zero participants.\ndouble WoodsSaxonNucleus::radius() const {\n  return R_ + 3.*a_;\n}\n\n/// Sample Woods-Saxon nucleon positions.\nvoid WoodsSaxonNucleus::sample_nucleons_impl() {\n  // When placing nucleons with a minimum distance criterion, resample spherical\n  // angles until the nucleon is not too close to a previously sampled nucleon,\n  // but do not resample radius -- this could modify the Woods-Saxon dist.\n\n  // Because of the r^2 Jacobian, there is less available space at smaller\n  // radii.  Therefore, pre-sample all radii first, sort them, and then place\n  // nucleons starting with the smallest radius and working outwards.  This\n  // dramatically reduces the chance that a nucleon cannot be placed.\n  std::vector<double> radii(size());\n  for (auto&& r : radii)\n    r = woods_saxon_dist_(random::engine);\n  std::sort(radii.begin(), radii.end());\n\n  // Place each nucleon at a pre-sampled radius.\n  auto r_iter = radii.cbegin();\n  for (iterator nucleon = begin(); nucleon != end(); ++nucleon) {\n    // Get radius and advance iterator.\n    auto& r = *r_iter++;\n\n    // Sample angles until the minimum distance criterion is satisfied.\n    auto ntries = 0;\n    do {\n      // Sample isotropic spherical angles.\n      auto cos_theta = random::cos_theta<double>();\n      auto phi = random::phi<double>();\n\n      // Convert to Cartesian coordinates.\n      auto r_sin_theta = r * std::sqrt(1. - cos_theta*cos_theta);\n      auto x = r_sin_theta * std::cos(phi);\n      auto y = r_sin_theta * std::sin(phi);\n      auto z = r * cos_theta;\n\n      set_nucleon_position(*nucleon, x, y, z);\n\n      // Retry sampling a reasonable number of times.  If a nucleon cannot be\n      // placed, give up and leave it at its last sampled position.  Some\n      // approximate numbers for Pb nuclei:\n      //\n      //   dmin = 0.5 fm, < 0.001% of nucleons cannot be placed\n      //          1.0 fm, ~0.005%\n      //          1.5 fm, ~0.1%\n      //          1.73 fm, ~1%\n    } while (++ntries < 1000 && is_too_close(nucleon));\n  }\n  // XXX: re-center nucleon positions?\n}\n\n// Set rmax like the non-deformed case (R + 10a), but for the maximum\n// \"effective\" radius.  The numerical coefficients for beta2 and beta4 are the\n// approximate values of Y20 and Y40 at theta = 0.\nDeformedWoodsSaxonNucleus::DeformedWoodsSaxonNucleus(\n    std::size_t A, double R, double a, double beta2, double beta4, double dmin)\n    : MinDistNucleus(A, dmin),\n      R_(R),\n      a_(a),\n      beta2_(beta2),\n      beta4_(beta4),\n      rmax_(R*(1. + .63*std::fabs(beta2) + .85*std::fabs(beta4)) + 10.*a)\n{}\n\n/// Return something a bit smaller than the true maximum radius.  The\n/// Woods-Saxon distribution falls off very rapidly (exponentially), and since\n/// this radius determines the impact parameter range, the true maximum radius\n/// would cause far too many events with zero participants.\ndouble DeformedWoodsSaxonNucleus::radius() const {\n  return rmax_ - 7.*a_;\n}\n\ndouble DeformedWoodsSaxonNucleus::deformed_woods_saxon_dist(\n    double r, double cos_theta) const {\n  auto cos_theta_sq = cos_theta*cos_theta;\n\n  // spherical harmonics\n  using math::double_constants::one_div_root_pi;\n  auto Y20 = std::sqrt(5)/4. * one_div_root_pi * (3.*cos_theta_sq - 1.);\n  auto Y40 = 3./16. * one_div_root_pi *\n             (35.*cos_theta_sq*cos_theta_sq - 30.*cos_theta_sq + 3.);\n\n  // \"effective\" radius\n  auto Reff = R_ * (1. + beta2_*Y20 + beta4_*Y40);\n\n  return 1. / (1. + std::exp((r - Reff) / a_));\n}\n\n/// Sample deformed Woods-Saxon nucleon positions.\nvoid DeformedWoodsSaxonNucleus::sample_nucleons_impl() {\n  // The deformed W-S distribution is defined so the symmetry axis is aligned\n  // with the Z axis, so e.g. the long axis of uranium coincides with Z.\n  //\n  // After sampling positions, they must be randomly rotated.  In general this\n  // requires three Euler rotations, but in this case we only need two\n  // because there is no use in rotating about the nuclear symmetry axis.\n  //\n  // The two rotations are:\n  //  - a polar \"tilt\", i.e. rotation about the X axis\n  //  - an azimuthal \"spin\", i.e. rotation about the original Z axis\n\n  // \"tilt\" angle\n  const auto cos_a = random::cos_theta<double>();\n  const auto sin_a = std::sqrt(1. - cos_a*cos_a);\n\n  // \"spin\" angle\n  const auto angle_b = random::phi<double>();\n  const auto cos_b = std::cos(angle_b);\n  const auto sin_b = std::sin(angle_b);\n\n  // Pre-sample and sort (r, cos_theta) points from the deformed W-S dist.\n  // See comments in WoodsSaxonNucleus (above) for rationale.\n  struct Sample {\n    double r, cos_theta;\n  };\n\n  std::vector<Sample> samples(size());\n\n  for (auto&& sample : samples) {\n    // Sample (r, cos_theta) using a standard rejection method.\n    // Remember to include the phase-space factors.\n    do {\n      sample.r = rmax_ * std::cbrt(random::canonical<double>());\n      sample.cos_theta = random::cos_theta<double>();\n    } while (\n      random::canonical<double>() >\n      deformed_woods_saxon_dist(sample.r, sample.cos_theta)\n    );\n  }\n\n  // Sort by radius.  Could also sort by e.g. the perpendicular distance from\n  // the z-axis, or by descending W-S density.  Empirically, radius leads to the\n  // smallest failure rate.\n  std::sort(\n    samples.begin(), samples.end(),\n    [](const Sample& a, const Sample& b) {\n      return a.r < b.r;\n    }\n  );\n\n  // Place each nucleon at a pre-sampled (r, cos_theta).\n  auto sample = samples.cbegin();\n  for (iterator nucleon = begin(); nucleon != end(); ++nucleon, ++sample) {\n    auto& r = sample->r;\n    auto& cos_theta = sample->cos_theta;\n\n    auto r_sin_theta = r * std::sqrt(1. - cos_theta*cos_theta);\n    auto z = r * cos_theta;\n\n    // Sample azimuthal angle until the minimum distance criterion is satisfied.\n    auto ntries = 0;\n    do {\n      // Choose azimuthal angle.\n      auto phi = random::phi<double>();\n\n      // Convert to Cartesian coordinates.\n      auto x = r_sin_theta * std::cos(phi);\n      auto y = r_sin_theta * std::sin(phi);\n\n      // Rotate.\n      // The rotation formula was derived by composing the \"tilt\" and \"spin\"\n      // rotations described above.\n      auto x_rot = x*cos_b - y*cos_a*sin_b + z*sin_a*sin_b;\n      auto y_rot = x*sin_b + y*cos_a*cos_b - z*sin_a*cos_b;\n      auto z_rot =           y*sin_a       + z*cos_a;\n\n      set_nucleon_position(*nucleon, x_rot, y_rot, z_rot);\n\n      // In addition to resampling phi, flip the z-coordinate each time.  This\n      // works because the deformed WS dist is symmetric in z.  Effectively\n      // doubles the available space for the nucleon.\n      z *= -1;\n\n      // Retry a reasonable number of times.  Unfortunately the failure rate is\n      // worse than non-deformed sampling because there is less freedom to place\n      // each nucleon.  Some approximate numbers for U nuclei:\n      //\n      //   dmin = 0.5 fm, < 0.001% of nucleons cannot be placed\n      //          1.0 fm, ~0.03%\n      //          1.3 fm, ~0.3%\n      //          1.5 fm, ~1.2%\n    } while (++ntries < 1000 && is_too_close(nucleon));\n  }\n}\n\n#ifdef TRENTO_HDF5\n\nnamespace {\n\n// Read a slice of an HDF5 dataset into a boost::multi_array.\ntemplate <typename T, std::size_t FileDims, std::size_t MemDims>\nboost::multi_array<T, MemDims>\nread_dataset(\n    const H5::DataSet& dataset,\n    const std::array<hsize_t, FileDims>& count,\n    const std::array<hsize_t, FileDims>& start,\n    const std::array<hsize_t, MemDims>& shape) {\n  boost::multi_array<T, MemDims> array{shape};\n  auto filespace = dataset.getSpace();\n  filespace.selectHyperslab(H5S_SELECT_SET, count.data(), start.data());\n  auto memspace = hdf5::make_dataspace(shape);\n\n  dataset.read(array.data(), hdf5::type<T>(), memspace, filespace);\n\n  return array;\n}\n\n}  // unnamed namespace\n\nstd::unique_ptr<ManualNucleus> ManualNucleus::create(const std::string& path) {\n  auto file = hdf5::try_open_file(path);\n\n  // Check that there is a single dataset in the file.\n  // Might relax this constraint in the future.\n  if (file.getNumObjs() != 1)\n    throw std::invalid_argument{\n      \"file '\" + path + \"' must contain exactly one object\"\n    };\n\n  auto name = file.getObjnameByIdx(0);\n#if H5_VERSION_GE(1, 8, 13)\n  if (file.childObjType(name) != H5O_TYPE_DATASET)  // added v1.8.13\n#else\n  if (file.getObjTypeByIdx(0) != H5G_DATASET)  // deprecated fall back\n#endif\n    throw std::invalid_argument{\n      \"object '\" + name + \"' in file '\" + path + \"' is not a dataset\"\n    };\n\n  // Make dataset object in a unique_ptr for eventual passing to ctor.\n  auto dataset = std::unique_ptr<H5::DataSet>{\n    new H5::DataSet{file.openDataSet(name)}\n  };\n\n  // Verify that the dataset has the correct dimensionality and shape.\n  std::array<hsize_t, 3> shape;\n  auto ndim = dataset->getSpace().getSimpleExtentDims(shape.data());\n\n  if (ndim != 3)\n    throw std::invalid_argument{\n      \"dataset '\" + name + \"' in file '\" + path + \"' has \" +\n      std::to_string(ndim) + \" dimensions (need 3)\"\n    };\n\n  if (shape[2] != 3)\n    throw std::invalid_argument{\n      \"dataset '\" + name + \"' in file '\" + path + \"' has \" +\n      std::to_string(shape[2]) + \" columns (need 3)\"\n    };\n\n  // Deduce number of configs and number of nucleons (A) from the shape.\n  const auto& nconfigs = shape[0];\n  const auto& A = shape[1];\n\n  // Estimate the max radius from at least 500 nucleon positions.\n  auto n = std::min(500/A + 1, nconfigs);\n  std::array<hsize_t, 3> count = {n, A, 3};\n  std::array<hsize_t, 3> start = {0, 0, 0};\n  std::array<hsize_t, 2> shape_n = {n*A, 3};\n  auto positions = read_dataset<float>(*dataset, count, start, shape_n);\n\n  auto rmax_sq = 0.;\n\n  for (const auto& position : positions) {\n    auto& x = position[0];\n    auto& y = position[1];\n    auto& z = position[2];\n    auto r_sq = x*x + y*y + z*z;\n    if (r_sq > rmax_sq)\n      rmax_sq = r_sq;\n  }\n\n  auto rmax = std::sqrt(rmax_sq);\n\n  return std::unique_ptr<ManualNucleus>{\n    new ManualNucleus{std::move(dataset), nconfigs, A, rmax}\n  };\n}\n\nManualNucleus::ManualNucleus(std::unique_ptr<H5::DataSet> dataset,\n                             std::size_t nconfigs, std::size_t A, double rmax)\n    : Nucleus(A),\n      dataset_(std::move(dataset)),\n      rmax_(rmax),\n      index_dist_(0, nconfigs - 1)\n{}\n\nManualNucleus::~ManualNucleus() = default;\n\ndouble ManualNucleus::radius() const {\n  return rmax_;\n}\n\nvoid ManualNucleus::sample_nucleons_impl() {\n  // Sample Euler rotation angles.\n  // First is an azimuthal spin about the Z axis.\n  const auto angle_1 = random::phi<double>();\n  const auto c1 = std::cos(angle_1);\n  const auto s1 = std::sin(angle_1);\n  // Then a polar tilt about the original X axis, uniform in cos(theta).\n  const auto c2 = random::cos_theta<double>();\n  const auto s2 = std::sqrt(1. - c2*c2);\n  // Finally another azimuthal spin about the original Z axis.\n  const auto angle_3 = random::phi<double>();\n  const auto c3 = std::cos(angle_3);\n  const auto s3 = std::sin(angle_3);\n\n  // Choose and read a random config from the dataset.\n  std::array<hsize_t, 3> count = {1, size(), 3};\n  std::array<hsize_t, 3> start = {index_dist_(random::engine), 0, 0};\n  std::array<hsize_t, 2> shape = {size(), 3};\n  const auto positions = read_dataset<float>(*dataset_, count, start, shape);\n\n  // Loop over positions and nucleons.\n  auto positions_iter = positions.begin();\n  for (iterator nucleon = begin(); nucleon != end(); ++nucleon) {\n    // Extract position vector and increment iterator.\n    auto position = *positions_iter++;\n    auto& x = position[0];\n    auto& y = position[1];\n    auto& z = position[2];\n\n    // Rotate.\n    auto x_rot = x*(c1*c3 - c2*s1*s3) - y*(c3*s1 + c1*c2*s3) + z*s2*s3;\n    auto y_rot = x*(c1*s3 + c2*c3*s1) - y*(s1*s3 - c1*c2*c3) - z*c3*s2;\n    auto z_rot = x*s1*s2              + y*c1*s2              + z*c2;\n\n    set_nucleon_position(*nucleon, x_rot, y_rot, z_rot);\n  }\n}\n\n#endif  // TRENTO_HDF5\n\n}  // namespace trento\n", "meta": {"hexsha": "0f69be7d67a421c7bb98d8cbded1dd987dcd5b45", "size": 18759, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/nucleus.cxx", "max_stars_repo_name": "ISOQUANT-C06/trento", "max_stars_repo_head_hexsha": "eb4333d16215ea423a0e318008ee3c6c5bb3b4f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nucleus.cxx", "max_issues_repo_name": "ISOQUANT-C06/trento", "max_issues_repo_head_hexsha": "eb4333d16215ea423a0e318008ee3c6c5bb3b4f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nucleus.cxx", "max_forks_repo_name": "ISOQUANT-C06/trento", "max_forks_repo_head_hexsha": "eb4333d16215ea423a0e318008ee3c6c5bb3b4f0", "max_forks_repo_licenses": ["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.2943327239, "max_line_length": 85, "alphanum_fraction": 0.653393038, "num_tokens": 5672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5030968404680678}}
{"text": "/*\nCopyright (c) 2013 Daniel Stahlke\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\nall copies 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\nTHE SOFTWARE.\n*/\n\n// This demonstrates all sorts of data types that can be plotted using send2d().  It is not\n// meant as a first tutorial; for that see example-misc.cc or the project wiki.\n\n#define USE_CXX (__cplusplus >= 201103)\n\n#include <vector>\n#include <complex>\n#include <cmath>\n\n#include <boost/tuple/tuple.hpp>\n#include <boost/array.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/irange.hpp>\n#include <boost/bind.hpp>\n\n#ifdef USE_ARMA\n#include <armadillo>\n#endif\n\n#ifdef USE_BLITZ\n#include <blitz/array.h>\n#endif\n\n#include \"gnuplot-iostream.h\"\n\n#ifndef M_PI\n#\tdefine M_PI 3.14159265358979323846\n#endif\n\n// The number of axial points of the torus.\nconst int num_u = 10;\n// The total number of longitudinal points of the torus.  This is set at the beginning of\n// main().\nint num_v_total;\n\n// This doesn't have to be a template.  It's just a template to show that such things are\n// possible.\ntemplate <typename T>\nstruct MyTriple {\n\tMyTriple() : x(0), y(0), z(0) { }\n\tMyTriple(T _x, T _y, T _z) : x(_x), y(_y), z(_z) { }\n\n\tT x, y, z;\n};\n\n// Tells gnuplot-iostream how to print objects of class MyTriple.\nnamespace gnuplotio {\n\ttemplate<typename T>\n\tstruct BinfmtSender<MyTriple<T> > {\n\t\tstatic void send(std::ostream &stream) {\n\t\t\tBinfmtSender<T>::send(stream);\n\t\t\tBinfmtSender<T>::send(stream);\n\t\t\tBinfmtSender<T>::send(stream);\n\t\t}\n\t};\n\n\ttemplate <typename T>\n\tstruct BinarySender<MyTriple<T> > {\n\t\tstatic void send(std::ostream &stream, const MyTriple<T> &v) {\n\t\t\tBinarySender<T>::send(stream, v.x);\n\t\t\tBinarySender<T>::send(stream, v.y);\n\t\t\tBinarySender<T>::send(stream, v.z);\n\t\t}\n\t};\n\n\t// We don't use text mode in this demo.  This is just here to show how it would go.\n\ttemplate<typename T>\n\tstruct TextSender<MyTriple<T> > {\n\t\tstatic void send(std::ostream &stream, const MyTriple<T> &v) {\n\t\t\tTextSender<T>::send(stream, v.x);\n\t\t\tstream << \" \";\n\t\t\tTextSender<T>::send(stream, v.y);\n\t\t\tstream << \" \";\n\t\t\tTextSender<T>::send(stream, v.z);\n\t\t}\n\t};\n}\n\nMyTriple<double> get_point(int u, int v) {\n\tdouble a = 2.0*M_PI*u/(num_u-1);\n\tdouble b = 2.0*M_PI*v/(num_v_total-1);\n\tdouble z = 0.3*std::cos(a);\n\tdouble r = 1 + 0.3*std::sin(a);\n\tdouble x = r * std::cos(b);\n\tdouble y = r * std::sin(b);\n\treturn MyTriple<double>(x, y, z);\n}\n\nint main() {\n\tGnuplot gp;\n\t// for debugging, prints to console\n\t//Gnuplot gp(stdout);\n\n\tint num_examples = 7;\n#ifdef USE_ARMA\n\tnum_examples += 3;\n#endif\n#ifdef USE_BLITZ\n\tnum_examples += 3;\n#endif\n\n\tint num_v_each = 50 / num_examples + 1;\n\n\tnum_v_total = (num_v_each-1) * num_examples + 1;\n\tint shift = 0;\n\n\tgp << \"set zrange [-1:1]\\n\";\n\tgp << \"set hidden3d nooffset\\n\";\n\n\t// I use temporary files rather than stdin because the syntax ends up being easier when\n\t// plotting several datasets.  With the stdin method you have to give the full plot\n\t// command, then all the data.  But I would rather give the portion of the plot command for\n\t// the first dataset, then give the data, then the command for the second dataset, then the\n\t// data, etc.\n\n\tgp << \"splot \";\n\n\t{\n\t\tstd::vector<std::vector<MyTriple<double> > > pts(num_u);\n\t\tfor(int u=0; u<num_u; u++) {\n\t\t\tpts[u].resize(num_v_each);\n\t\t\tfor(int v=0; v<num_v_each; v++) {\n\t\t\t\tpts[u][v] = get_point(u, v+shift);\n\t\t\t}\n\t\t}\n\t\tgp << gp.binFile2d(pts, \"record\") << \"with lines title 'vec of vec of MyTriple'\";\n\t}\n\n\tgp << \", \";\n\tshift += num_v_each-1;\n\n\t{\n\t\tstd::vector<std::vector<boost::tuple<double,double,double> > > pts(num_u);\n\t\tfor(int u=0; u<num_u; u++) {\n\t\t\tpts[u].resize(num_v_each);\n\t\t\tfor(int v=0; v<num_v_each; v++) {\n\t\t\t\tpts[u][v] = boost::make_tuple(\n\t\t\t\t\tget_point(u, v+shift).x,\n\t\t\t\t\tget_point(u, v+shift).y,\n\t\t\t\t\tget_point(u, v+shift).z\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tgp << gp.binFile2d(pts, \"record\") << \"with lines title 'vec of vec of boost::tuple'\";\n\t}\n\n\tgp << \", \";\n\tshift += num_v_each-1;\n\n\t{\n\t\tstd::vector<std::vector<double> > x_pts(num_u);\n\t\tstd::vector<std::vector<double> > y_pts(num_u);\n\t\tstd::vector<std::vector<double> > z_pts(num_u);\n\t\tfor(int u=0; u<num_u; u++) {\n\t\t\tx_pts[u].resize(num_v_each);\n\t\t\ty_pts[u].resize(num_v_each);\n\t\t\tz_pts[u].resize(num_v_each);\n\t\t\tfor(int v=0; v<num_v_each; v++) {\n\t\t\t\tx_pts[u][v] = get_point(u, v+shift).x;\n\t\t\t\ty_pts[u][v] = get_point(u, v+shift).y;\n\t\t\t\tz_pts[u][v] = get_point(u, v+shift).z;\n\t\t\t}\n\t\t}\n\t\tgp << gp.binFile2d(boost::make_tuple(x_pts, y_pts, z_pts), \"record\") <<\n\t\t\t\"with lines title 'boost::tuple of vec of vec'\";\n\t}\n\n\tgp << \", \";\n\tshift += num_v_each-1;\n\n\t{\n\t\tstd::vector<boost::tuple<\n\t\t\t\tstd::vector<double>,\n\t\t\t\tstd::vector<double>,\n\t\t\t\tstd::vector<double>\n\t\t\t> > pts;\n\t\tfor(int u=0; u<num_u; u++) {\n\t\t\tstd::vector<double> x_pts(num_v_each);\n\t\t\tstd::vector<double> y_pts(num_v_each);\n\t\t\tstd::vector<double> z_pts(num_v_each);\n\t\t\tfor(int v=0; v<num_v_each; v++) {\n\t\t\t\tx_pts[v] = get_point(u, v+shift).x;\n\t\t\t\ty_pts[v] = get_point(u, v+shift).y;\n\t\t\t\tz_pts[v] = get_point(u, v+shift).z;\n\t\t\t}\n\t\t\tpts.push_back(boost::make_tuple(x_pts, y_pts, z_pts));\n\t\t}\n\t\tgp << gp.binFile2d(pts, \"record\") <<\n\t\t\t\"with lines title 'vec of boost::tuple of vec'\";\n\t}\n\n\tgp << \", \";\n\tshift += num_v_each-1;\n\n\t{\n\t\tstd::vector<std::vector<double> > x_pts(num_u);\n\t\tstd::vector<std::vector<std::pair<double, double> > > yz_pts(num_u);\n\t\tfor(int u=0; u<num_u; u++) {\n\t\t\tx_pts[u].resize(num_v_each);\n\t\t\tyz_pts[u].resize(num_v_each);\n\t\t\tfor(int v=0; v<num_v_each; v++) {\n\t\t\t\tx_pts [u][v] = get_point(u, v+shift).x;\n\t\t\t\tyz_pts[u][v] = std::make_pair(\n\t\t\t\t\tget_point(u, v+shift).y,\n\t\t\t\t\tget_point(u, v+shift).z);\n\t\t\t}\n\t\t}\n\t\tgp << gp.binFile2d(std::make_pair(x_pts, yz_pts), \"record\") <<\n\t\t\t\"with lines title 'pair(vec(vec(dbl)),vec(vec(pair(dbl,dbl))))'\";\n\t}\n\n\tgp << \", \";\n\tshift += num_v_each-1;\n\n\t{\n\t\tstd::vector<std::vector<std::vector<double> > > pts(num_u);\n\t\tfor(int u=0; u<num_u; u++) {\n\t\t\tpts[u].resize(num_v_each);\n\t\t\tfor(int v=0; v<num_v_each; v++) {\n\t\t\t\tpts[u][v].resize(3);\n\t\t\t\tpts[u][v][0] = get_point(u, v+shift).x;\n\t\t\t\tpts[u][v][1] = get_point(u, v+shift).y;\n\t\t\t\tpts[u][v][2] = get_point(u, v+shift).z;\n\t\t\t}\n\t\t}\n\t\tgp << gp.binFile2d(pts, \"record\") << \"with lines title 'vec vec vec'\";\n\t}\n\n\tgp << \", \";\n\tshift += num_v_each-1;\n\n\t{\n\t\tstd::vector<std::vector<std::vector<double> > > pts(3);\n\t\tfor(int i=0; i<3; i++) pts[i].resize(num_u);\n\t\tfor(int u=0; u<num_u; u++) {\n\t\t\tfor(int i=0; i<3; i++) pts[i][u].resize(num_v_each);\n\t\t\tfor(int v=0; v<num_v_each; v++) {\n\t\t\t\tpts[0][u][v] = get_point(u, v+shift).x;\n\t\t\t\tpts[1][u][v] = get_point(u, v+shift).y;\n\t\t\t\tpts[2][u][v] = get_point(u, v+shift).z;\n\t\t\t}\n\t\t}\n\t\tgp << gp.binFile2d_colmajor(pts, \"record\") << \"with lines title 'vec vec vec (colmajor)'\";\n\t}\n\n#ifdef USE_ARMA\n\tgp << \", \";\n\tshift += num_v_each-1;\n\n\t{\n\t\tarma::cube pts(num_u, num_v_each, 3);\n\t\tfor(int u=0; u<num_u; u++) {\n\t\t\tfor(int v=0; v<num_v_each; v++) {\n\t\t\t\tpts(u, v, 0) = get_point(u, v+shift).x;\n\t\t\t\tpts(u, v, 1) = get_point(u, v+shift).y;\n\t\t\t\tpts(u, v, 2) = get_point(u, v+shift).z;\n\t\t\t}\n\t\t}\n\t\tgp << gp.file2d(pts) << \"with lines title 'arma::cube(U*V*3)'\";\n\t}\n\n\tgp << \", \";\n\tshift += num_v_each-1;\n\n\t{\n\t\tarma::cube pts(3, num_u, num_v_each);\n\t\tfor(int u=0; u<num_u; u++) {\n\t\t\tfor(int v=0; v<num_v_each; v++) {\n\t\t\t\tpts(0, u, v) = get_point(u, v+shift).x;\n\t\t\t\tpts(1, u, v) = get_point(u, v+shift).y;\n\t\t\t\tpts(2, u, v) = get_point(u, v+shift).z;\n\t\t\t}\n\t\t}\n\t\tgp << gp.binFile2d_colmajor(pts, \"record\") << \"with lines title 'arma::cube(3*U*V) (colmajor)'\";\n\t}\n\n\tgp << \", \";\n\tshift += num_v_each-1;\n\n\t{\n\t\tarma::field<MyTriple<double> > pts(num_u, num_v_each);\n\t\tfor(int u=0; u<num_u; u++) {\n\t\t\tfor(int v=0; v<num_v_each; v++) {\n\t\t\t\tpts(u, v) = get_point(u, v+shift);\n\t\t\t}\n\t\t}\n\t\tgp << gp.binFile2d(pts, \"record\") << \"with lines title 'arma::field'\";\n\t}\n#endif\n\n#ifdef USE_BLITZ\n\tgp << \", \";\n\tshift += num_v_each-1;\n\n\t{\n\t\tblitz::Array<blitz::TinyVector<double, 3>, 2> pts(num_u, num_v_each);\n\t\tfor(int u=0; u<num_u; u++) {\n\t\t\tfor(int v=0; v<num_v_each; v++) {\n\t\t\t\tpts(u, v)[0] = get_point(u, v+shift).x;\n\t\t\t\tpts(u, v)[1] = get_point(u, v+shift).y;\n\t\t\t\tpts(u, v)[2] = get_point(u, v+shift).z;\n\t\t\t}\n\t\t}\n\t\tgp << gp.binFile2d(pts, \"record\") << \"with lines title 'blitz::Array<blitz::TinyVector<double, 3>, 2>'\";\n\t}\n\n\tgp << \", \";\n\tshift += num_v_each-1;\n\n\t{\n\t\tblitz::Array<double, 3> pts(num_u, num_v_each, 3);\n\t\tfor(int u=0; u<num_u; u++) {\n\t\t\tfor(int v=0; v<num_v_each; v++) {\n\t\t\t\tpts(u, v, 0) = get_point(u, v+shift).x;\n\t\t\t\tpts(u, v, 1) = get_point(u, v+shift).y;\n\t\t\t\tpts(u, v, 2) = get_point(u, v+shift).z;\n\t\t\t}\n\t\t}\n\t\tgp << gp.binFile2d(pts, \"record\") << \"with lines title 'blitz<double>(U*V*3)'\";\n\t}\n\n\tgp << \", \";\n\tshift += num_v_each-1;\n\n\t{\n\t\tblitz::Array<double, 3> pts(3, num_u, num_v_each);\n\t\tfor(int u=0; u<num_u; u++) {\n\t\t\tfor(int v=0; v<num_v_each; v++) {\n\t\t\t\tpts(0, u, v) = get_point(u, v+shift).x;\n\t\t\t\tpts(1, u, v) = get_point(u, v+shift).y;\n\t\t\t\tpts(2, u, v) = get_point(u, v+shift).z;\n\t\t\t}\n\t\t}\n\t\tgp << gp.binFile2d_colmajor(pts, \"record\") << \"with lines title 'blitz<double>(3*U*V) (colmajor)'\";\n\t}\n#endif\n\n\tgp << std::endl;\n\n\tstd::cout << shift+num_v_each << \",\" << num_v_total << std::endl;\n\tassert(shift+num_v_each == num_v_total);\n\n#ifdef _WIN32\n\t// For Windows, prompt for a keystroke before the Gnuplot object goes out of scope so that\n\t// the gnuplot window doesn't get closed.\n\tstd::cout << \"Press enter to exit.\" << std::endl;\n\tstd::cin.get();\n#endif\n\n\treturn 0;\n}\n", "meta": {"hexsha": "aaca3a9dd027c31bf628efe07f9d7c3fb3fd7480", "size": 10299, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/external_library/gnuplot-iostream/example-data-2d.cc", "max_stars_repo_name": "ecbaum/ugpm", "max_stars_repo_head_hexsha": "3ab6ff2dbc59642e0e9739f5f4647a906f19e333", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2021-06-16T01:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T19:09:03.000Z", "max_issues_repo_path": "src/external_library/gnuplot-iostream/example-data-2d.cc", "max_issues_repo_name": "ecbaum/ugpm", "max_issues_repo_head_hexsha": "3ab6ff2dbc59642e0e9739f5f4647a906f19e333", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-10-13T07:50:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T11:48:52.000Z", "max_forks_repo_path": "src/external_library/gnuplot-iostream/example-data-2d.cc", "max_forks_repo_name": "ecbaum/ugpm", "max_forks_repo_head_hexsha": "3ab6ff2dbc59642e0e9739f5f4647a906f19e333", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2021-06-21T06:13:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T15:36:44.000Z", "avg_line_length": 27.5374331551, "max_line_length": 106, "alphanum_fraction": 0.62705117, "num_tokens": 3495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.5030968308111702}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2016-2017 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\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#ifndef BOOST_GEOMETRY_FORMULAS_MAXIMUM_LATITUDE_HPP\n#define BOOST_GEOMETRY_FORMULAS_MAXIMUM_LATITUDE_HPP\n\n\n#include <boost/geometry/formulas/flattening.hpp>\n#include <boost/geometry/formulas/spherical.hpp>\n\n#include <boost/mpl/assert.hpp>\n\n\nnamespace boost { namespace geometry { namespace formula\n{\n\n/*!\n\\brief Algorithm to compute the vertex latitude of a geodesic segment. Vertex is\na point on the geodesic that maximizes (or minimizes) the latitude.\n\\author See\n    [Wood96] Wood - Vertex Latitudes on Ellipsoid Geodesics, SIAM Rev., 38(4),\n             637\u2013644, 1996\n*/\n\ntemplate <typename CT>\nclass vertex_latitude_on_sphere\n{\n\npublic:\n    template<typename T1, typename T2>\n    static inline CT apply(T1 const& lat1,\n                           T2 const& alp1)\n    {\n        return std::acos( math::abs(cos(lat1) * sin(alp1)) );\n    }\n};\n\ntemplate <typename CT>\nclass vertex_latitude_on_spheroid\n{\n\npublic:\n/*\n * formula based on paper\n *   [Wood96] Wood - Vertex Latitudes on Ellipsoid Geodesics, SIAM Rev., 38(4),\n *            637\u2013644, 1996\n    template <typename T1, typename T2, typename Spheroid>\n    static inline CT apply(T1 const& lat1,\n                           T2 const& alp1,\n                           Spheroid const& spheroid)\n    {\n        CT const f = formula::flattening<CT>(spheroid);\n\n        CT const e2 = f * (CT(2) - f);\n        CT const sin_alp1 = sin(alp1);\n        CT const sin2_lat1 = math::sqr(sin(lat1));\n        CT const cos2_lat1 = CT(1) - sin2_lat1;\n\n        CT const e2_sin2 = CT(1) - e2 * sin2_lat1;\n        CT const cos2_sin2 = cos2_lat1 * math::sqr(sin_alp1);\n        CT const vertex_lat = std::asin( math::sqrt((e2_sin2 - cos2_sin2)\n                                                    / (e2_sin2 - e2 * cos2_sin2)));\n        return vertex_lat;\n    }\n*/\n\n    // simpler formula based on Clairaut relation for spheroids\n    template <typename T1, typename T2, typename Spheroid>\n    static inline CT apply(T1 const& lat1,\n                           T2 const& alp1,\n                           Spheroid const& spheroid)\n    {\n        CT const f = formula::flattening<CT>(spheroid);\n\n        CT const one_minus_f = (CT(1) - f);\n\n        //get the reduced latitude\n        CT const bet1 = atan( one_minus_f * tan(lat1) );\n\n        //apply Clairaut relation\n        CT const betv =  vertex_latitude_on_sphere<CT>::apply(bet1, alp1);\n\n        //return the spheroid latitude\n        return atan( tan(betv) / one_minus_f );\n    }\n\n    /*\n    template <typename T>\n    inline static void sign_adjustment(CT lat1, CT lat2, CT vertex_lat, T& vrt_result)\n    {\n        // signbit returns a non-zero value (true) if the sign is negative;\n        // and zero (false) otherwise.\n        bool sign = std::signbit(std::abs(lat1) > std::abs(lat2) ? lat1 : lat2);\n\n        vrt_result.north = sign ? std::max(lat1, lat2) : vertex_lat;\n        vrt_result.south = sign ? vertex_lat * CT(-1) : std::min(lat1, lat2);\n    }\n\n    template <typename T>\n    inline static bool vertex_on_segment(CT alp1, CT alp2, CT lat1, CT lat2, T& vrt_result)\n    {\n        CT const half_pi = math::pi<CT>() / CT(2);\n\n        // if the segment does not contain the vertex of the geodesic\n        // then return the endpoint of max (min) latitude\n        if ((alp1 < half_pi && alp2 < half_pi)\n                || (alp1 > half_pi && alp2 > half_pi))\n        {\n            vrt_result.north = std::max(lat1, lat2);\n            vrt_result.south = std::min(lat1, lat2);\n            return false;\n        }\n        return true;\n    }\n    */\n};\n\n\ntemplate <typename CT, typename CS_Tag>\nstruct vertex_latitude\n{\n    BOOST_MPL_ASSERT_MSG\n         (\n             false, NOT_IMPLEMENTED_FOR_THIS_COORDINATE_SYSTEM, (types<CS_Tag>)\n         );\n\n};\n\ntemplate <typename CT>\nstruct vertex_latitude<CT, spherical_equatorial_tag>\n        : vertex_latitude_on_sphere<CT>\n{};\n\ntemplate <typename CT>\nstruct vertex_latitude<CT, geographic_tag>\n        : vertex_latitude_on_spheroid<CT>\n{};\n\n\n}}} // namespace boost::geometry::formula\n\n#endif // BOOST_GEOMETRY_FORMULAS_MAXIMUM_LATITUDE_HPP\n", "meta": {"hexsha": "92822e01a384ee2ea4873fa77de2540c096656e4", "size": 4485, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/formulas/vertex_latitude.hpp", "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": "boost/geometry/formulas/vertex_latitude.hpp", "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": "boost/geometry/formulas/vertex_latitude.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 29.701986755, "max_line_length": 91, "alphanum_fraction": 0.6309921962, "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5030968275922042}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Robert Rosolek\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 fractional_winner_determination_in_MUCA_test_utils.hpp\n * @brief\n * @author Robert Rosolek\n * @version 1.0\n * @date 2014-06-12\n */\n#ifndef PAAL_FRACTIONAL_WINNER_DETERMINATION_IN_MUCA_TEST_UTILS_HPP\n#define PAAL_FRACTIONAL_WINNER_DETERMINATION_IN_MUCA_TEST_UTILS_HPP\n\n#include \"paal/auctions/auction_components.hpp\"\n#include \"paal/auctions/auction_traits.hpp\"\n#include \"paal/auctions/fractional_winner_determination_in_MUCA/fractional_winner_determination_in_MUCA.hpp\"\n#include \"paal/auctions/xor_bids.hpp\"\n#include \"paal/lp/glp.hpp\"\n#include \"paal/utils/make.hpp\"\n#include \"paal/utils/type_functions.hpp\"\n\n#include <boost/function_output_iterator.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <iterator>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n\ntemplate <\n   class Bidders,\n   class Items,\n   class GetBids,\n   class GetValue,\n   class GetItems,\n   class GetCopiesNum,\n   class ItemToLpIdMap\n>\nvoid check_fractional_determine_winners_in_demand_query_auction(\n   Bidders&& bidders,\n   Items&& items,\n   GetBids get_bids,\n   GetValue get_value,\n   GetItems get_items,\n   GetCopiesNum get_copies_num,\n   double opt,\n   ItemToLpIdMap item_to_id,\n   double eps\n) {\n\n    namespace pa = paal::auctions;\n\n    auto auction = pa::make_xor_bids_to_demand_query_auction(\n            std::forward<Bidders>(bidders),\n            std::forward<Items>(items),\n            get_bids,\n            get_value,\n            get_items,\n            get_copies_num\n            );\n\n\n    using Traits = pa::demand_query_auction_traits<decltype(auction)>;\n    using Bidder = typename Traits::bidder_val_t;\n    using Item = typename Traits::item_val_t;\n    using ItemsBundle = typename Traits::items_t;\n    using Assignment = std::tuple<Bidder, ItemsBundle, double>;\n\n    auto valuation = pa::make_xor_bids_to_value_query_auction(\n            // TODO these arguments are copy paste, maybe we need xor_bids_auction_components?\n            std::forward<Bidders>(bidders),\n            std::forward<Items>(items),\n            get_bids,\n            get_value,\n            get_items,\n            get_copies_num\n            );\n\n    double social_welfare = 0;\n    std::unordered_map<Bidder, double> bidder_count;\n    std::unordered_map<Item, double> item_count;\n    pa::fractional_determine_winners_in_demand_query_auction(\n            auction,\n            boost::iterators::make_function_output_iterator([&](Assignment a)\n            {\n                auto bidder = std::get<0>(a);\n                auto& items = std::get<1>(a);\n                auto frac = std::get<2>(a);\n                auto item_set = paal::make_unordered_set(items);\n                social_welfare += frac * valuation.template call<pa::value_query>(bidder, item_set);\n                for (auto const & item: items) {\n                    auto cnt = item_count[item] += frac;\n                    BOOST_CHECK_LE(cnt, get_copies_num(item) + eps);\n                }\n                auto cnt = bidder_count[bidder] += frac;\n                BOOST_CHECK_LE(cnt, 1 + eps);\n            }),\n            item_to_id,\n            eps\n            );\n\n    BOOST_CHECK_CLOSE(opt, social_welfare, eps);\n}\n\ntemplate<\nclass Bidders,\n      class Items,\n      class GetBids,\n      class GetValue,\n      class GetItems,\n      class GetCopiesNum\n      >\nvoid check_fractional_determine_winners_in_demand_query_auction(\n        Bidders&& bidders,\n        Items&& items,\n        GetBids get_bids,\n        GetValue get_value,\n        GetItems get_items,\n        GetCopiesNum get_copies_num,\n        double opt,\n        double epsilon = 1e-8\n        ) {\n    using ItemVal = paal::range_to_elem_t<Items>;\n    using PriceMap = std::unordered_map<ItemVal, paal::lp::col_id>;\n\n    PriceMap map;\n    check_fractional_determine_winners_in_demand_query_auction(\n            std::forward<Bidders>(bidders),\n            std::forward<Items>(items),\n            get_bids,\n            get_value,\n            get_items,\n            get_copies_num,\n            opt,\n            boost::make_assoc_property_map(map),\n            epsilon\n            );\n}\n\n#endif /* PAAL_FRACTIONAL_WINNER_DETERMINATION_IN_MUCA_TEST_UTILS_HPP */\n", "meta": {"hexsha": "60483b923b234d702ce16c5c06aa9869e59c8e01", "size": 4572, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/test_utils/fractional_winner_determination_in_MUCA_test_utils.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": "test/test_utils/fractional_winner_determination_in_MUCA_test_utils.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": "test/test_utils/fractional_winner_determination_in_MUCA_test_utils.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": 31.1020408163, "max_line_length": 108, "alphanum_fraction": 0.6305774278, "num_tokens": 1086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5030968222040944}}
{"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_TWO_PROD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_TWO_PROD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-arithmetic\n    This function object computes two reals of the type of the inputs\n    (in an std::pair)  @c r0 and @c r1 such that:\n\n    @code\n    r0 = x * y\n    r1 = r0 -(x * y)\n    @endcode\n\n    using perfect arithmetic.\n\n    Its main usage is to be able to compute\n    prod of reals and the residual error using IEEE 754 arithmetic.\n\n\n    @par Header <boost/simd/function/two_prod.hpp>\n\n    @par Example:\n\n      @snippet two_prod.cpp two_prod\n\n    @par Possible output:\n\n      @snippet two_prod.txt two_prod\n\n\n  **/\n  std::pair<Value, Value> two_prod(Value const& x, Value const& y);\n\n} }\n#endif\n\n#include <boost/simd/function/scalar/two_prod.hpp>\n#include <boost/simd/function/simd/two_prod.hpp>\n\n#endif\n", "meta": {"hexsha": "20f1b7af5c8031d37d292a8b1db8306626614162", "size": 1290, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/two_prod.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/function/two_prod.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/function/two_prod.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": 23.0357142857, "max_line_length": 100, "alphanum_fraction": 0.5914728682, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5030063785375002}}
{"text": "#include <mi4/Kdtree.hpp>\n#include <Eigen/Dense>\n#include <vector>\n#include <iostream>\nint main ( int argc, char** argv )\n{\n\n        std::vector<Eigen::Vector3d> p;\n\n        for ( int i = 0 ; i < 10000 ; i++ ) {\n                double x = ( rand() % 2001 - 1000 ) * 0.001;\n                double y = ( rand() % 2001 - 1000 ) * 0.001;\n                double z = ( rand() % 2001 - 1000 ) * 0.001;\n                p.push_back ( Eigen::Vector3d ( x, y, z ) );\n        }\n\n        mi4::Kdtree<Eigen::Vector3d> kdtree ( p ) ;\n\n        Eigen::Vector3d v ( 0.1, 0.1, 0.1 ) ;\n        std::list<Eigen::Vector3d> result;\n\n        kdtree.find ( v, 0.1, result, true );\n\n        for ( std::list<Eigen::Vector3d>::iterator iter = result.begin(); iter != result.end() ; ++iter ) {\n                Eigen::Vector3d& v0 = *iter;\n                Eigen::Vector3d d = *iter - v;\n                double sqrtDist = d.x() * d.x() + d.y() * d.y() + d.z() * d.z();\n                std::cerr << v0.x() << \" \" << v0.y() << \" \" << v0.z() << \"\\t \" << sqrtDist << std::endl;\n        }\n\n        return 0;\n}\n", "meta": {"hexsha": "c53b61b610ac8b196b3332a2885187647aff4103", "size": 1074, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/kdtree0.cpp", "max_stars_repo_name": "tmichi/mi4", "max_stars_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_stars_repo_licenses": ["MIT"], "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/kdtree0.cpp", "max_issues_repo_name": "tmichi/mi4", "max_issues_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-28T02:28:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-28T03:00:24.000Z", "max_forks_repo_path": "examples/kdtree0.cpp", "max_forks_repo_name": "tmichi/mi4", "max_forks_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_forks_repo_licenses": ["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.5454545455, "max_line_length": 107, "alphanum_fraction": 0.4497206704, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5030063711024613}}
{"text": "/* boost random/additive_combine.hpp header file\r\n *\r\n * Copyright Jens Maurer 2000-2001\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: additive_combine.hpp 60755 2010-03-22 00:45:06Z steven_watanabe $\r\n *\r\n * Revision history\r\n *  2001-02-18  moved to individual header files\r\n */\r\n\r\n#ifndef BOOST_RANDOM_ADDITIVE_COMBINE_HPP\r\n#define BOOST_RANDOM_ADDITIVE_COMBINE_HPP\r\n\r\n#include <iostream>\r\n#include <algorithm> // for std::min and std::max\r\n#include <boost/config.hpp>\r\n#include <boost/cstdint.hpp>\r\n#include <boost/random/detail/config.hpp>\r\n#include <boost/random/linear_congruential.hpp>\r\n\r\nnamespace boost {\r\nnamespace random {\r\n\r\n/**\r\n * An instantiation of class template \\additive_combine model a\r\n * \\pseudo_random_number_generator. It combines two multiplicative\r\n * \\linear_congruential number generators, i.e. those with @c c = 0.\r\n * It is described in\r\n *\r\n *  @blockquote\r\n *  \"Efficient and Portable Combined Random Number Generators\", Pierre L'Ecuyer,\r\n *  Communications of the ACM, Vol. 31, No. 6, June 1988, pp. 742-749, 774\r\n *  @endblockquote\r\n *\r\n * The template parameters MLCG1 and MLCG2 shall denote two different\r\n * \\linear_congruential number generators, each with c = 0. Each invocation\r\n * returns a random number X(n) := (MLCG1(n) - MLCG2(n)) mod (m1 - 1), where\r\n * m1 denotes the modulus of MLCG1. \r\n *\r\n * The template parameter @c val is the validation value checked by validation.\r\n */\r\ntemplate<class MLCG1, class MLCG2,\r\n#ifndef BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS\r\n  typename MLCG1::result_type \r\n#else\r\n  int32_t\r\n#endif\r\n  val>\r\nclass additive_combine\r\n{\r\npublic:\r\n  typedef MLCG1 first_base;\r\n  typedef MLCG2 second_base;\r\n  typedef typename MLCG1::result_type result_type;\r\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\r\n  static const bool has_fixed_range = true;\r\n  static const result_type min_value = 1;\r\n  static const result_type max_value = MLCG1::max_value-1;\r\n#else\r\n  enum { has_fixed_range = false };\r\n#endif\r\n  /**\r\n   * Returns: The smallest value that the generator can produce\r\n   */\r\n  result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return 1; }\r\n  /**\r\n   * Returns: The largest value that the generator can produce\r\n   */\r\n  result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return (_mlcg1.max)()-1; }\r\n\r\n  /**\r\n   * Constructs an \\additive_combine generator using the\r\n   * default constructors of the two base generators.\r\n   */\r\n  additive_combine() : _mlcg1(), _mlcg2() { }\r\n  /**\r\n   * Constructs an \\additive_combine generator, using aseed as\r\n   * the constructor argument for both base generators.\r\n   */\r\n  explicit additive_combine(result_type aseed)\r\n    : _mlcg1(aseed), _mlcg2(aseed) { }\r\n  /**\r\n   * Constructs an \\additive_combine generator, using\r\n   * @c seed1 and @c seed2 as the constructor argument to\r\n   * the first and second base generators, respectively.\r\n   */\r\n  additive_combine(typename MLCG1::result_type seed1, \r\n                   typename MLCG2::result_type seed2)\r\n    : _mlcg1(seed1), _mlcg2(seed2) { }\r\n  /**\r\n   * Contructs an \\additive_combine generator with\r\n   * values from the range defined by the input iterators first\r\n   * and last.  first will be modified to point to the element\r\n   * after the last one used.\r\n   *\r\n   * Throws: @c std::invalid_argument if the input range is too small.\r\n   *\r\n   * Exception Safety: Basic\r\n   */\r\n  template<class It> additive_combine(It& first, It last)\r\n    : _mlcg1(first, last), _mlcg2(first, last) { }\r\n\r\n  /**\r\n   * Seeds an \\additive_combine generator using the default\r\n   * seeds of the two base generators.\r\n   */\r\n  void seed()\r\n  {\r\n    _mlcg1.seed();\r\n    _mlcg2.seed();\r\n  }\r\n\r\n  /**\r\n   * Seeds an \\additive_combine generator, using @c aseed as the\r\n   * seed for both base generators.\r\n   */\r\n  void seed(result_type aseed)\r\n  {\r\n    _mlcg1.seed(aseed);\r\n    _mlcg2.seed(aseed);\r\n  }\r\n\r\n  /**\r\n   * Seeds an \\additive_combine generator, using @c seed1 and @c seed2 as\r\n   * the seeds to the first and second base generators, respectively.\r\n   */\r\n  void seed(typename MLCG1::result_type seed1,\r\n            typename MLCG2::result_type seed2)\r\n  {\r\n    _mlcg1.seed(seed1);\r\n    _mlcg2.seed(seed2);\r\n  }\r\n\r\n  /**\r\n   * Seeds an \\additive_combine generator with\r\n   * values from the range defined by the input iterators first\r\n   * and last.  first will be modified to point to the element\r\n   * after the last one used.\r\n   *\r\n   * Throws: @c std::invalid_argument if the input range is too small.\r\n   *\r\n   * Exception Safety: Basic\r\n   */\r\n  template<class It> void seed(It& first, It last)\r\n  {\r\n    _mlcg1.seed(first, last);\r\n    _mlcg2.seed(first, last);\r\n  }\r\n\r\n  /**\r\n   * Returns: the next value of the generator\r\n   */\r\n  result_type operator()() {\r\n    result_type z = _mlcg1() - _mlcg2();\r\n    if(z < 1)\r\n      z += MLCG1::modulus-1;\r\n    return z;\r\n  }\r\n\r\n  static bool validation(result_type x) { return val == x; }\r\n\r\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\r\n\r\n#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS\r\n  /**\r\n   * Writes the state of an \\additive_combine generator to a @c\r\n   * std::ostream.  The textual representation of an \\additive_combine\r\n   * generator is the textual representation of the first base\r\n   * generator followed by the textual representation of the\r\n   * second base generator.\r\n   */\r\n  template<class CharT, class Traits>\r\n  friend std::basic_ostream<CharT,Traits>&\r\n  operator<<(std::basic_ostream<CharT,Traits>& os, const additive_combine& r)\r\n  { os << r._mlcg1 << \" \" << r._mlcg2; return os; }\r\n\r\n  /**\r\n   * Reads the state of an \\additive_combine generator from a\r\n   * @c std::istream.\r\n   */\r\n  template<class CharT, class Traits>\r\n  friend std::basic_istream<CharT,Traits>&\r\n  operator>>(std::basic_istream<CharT,Traits>& is, additive_combine& r)\r\n  { is >> r._mlcg1 >> std::ws >> r._mlcg2; return is; }\r\n#endif\r\n\r\n  /**\r\n   * Returns: true iff the two \\additive_combine generators will\r\n   * produce the same sequence of values.\r\n   */\r\n  friend bool operator==(const additive_combine& x, const additive_combine& y)\r\n  { return x._mlcg1 == y._mlcg1 && x._mlcg2 == y._mlcg2; }\r\n  /**\r\n   * Returns: true iff the two \\additive_combine generators will\r\n   * produce different sequences of values.\r\n   */\r\n  friend bool operator!=(const additive_combine& x, const additive_combine& y)\r\n  { return !(x == y); }\r\n#else\r\n  // Use a member function; Streamable concept not supported.\r\n  bool operator==(const additive_combine& rhs) const\r\n  { return _mlcg1 == rhs._mlcg1 && _mlcg2 == rhs._mlcg2; }\r\n  bool operator!=(const additive_combine& rhs) const\r\n  { return !(*this == rhs); }\r\n#endif\r\n\r\nprivate:\r\n  MLCG1 _mlcg1;\r\n  MLCG2 _mlcg2;\r\n};\r\n\r\n} // namespace random\r\n\r\n/**\r\n * The specialization \\ecuyer1988 was suggested in\r\n *\r\n *  @blockquote\r\n *  \"Efficient and Portable Combined Random Number Generators\", Pierre L'Ecuyer,\r\n *  Communications of the ACM, Vol. 31, No. 6, June 1988, pp. 742-749, 774\r\n *  @endblockquote\r\n */\r\ntypedef random::additive_combine<\r\n    random::linear_congruential<int32_t, 40014, 0, 2147483563, 0>,\r\n    random::linear_congruential<int32_t, 40692, 0, 2147483399, 0>,\r\n  2060321752> ecuyer1988;\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_RANDOM_ADDITIVE_COMBINE_HPP\r\n", "meta": {"hexsha": "3e8b0c312d7288f3258b58627ed6ad1df55f43a0", "size": 7450, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/random/additive_combine.hpp", "max_stars_repo_name": "davidov541/MiniC", "max_stars_repo_head_hexsha": "d3b16a1568b97a4d801880b110a8be04fe848adb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-04-15T16:58:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T13:58:14.000Z", "max_issues_repo_path": "LibsExternes/Includes/boost/random/additive_combine.hpp", "max_issues_repo_name": "benkaraban/anima-games-engine", "max_issues_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-04-15T17:11:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T14:08:52.000Z", "max_forks_repo_path": "LibsExternes/Includes/boost/random/additive_combine.hpp", "max_forks_repo_name": "benkaraban/anima-games-engine", "max_forks_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-05-07T14:41:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T12:19:58.000Z", "avg_line_length": 31.7021276596, "max_line_length": 89, "alphanum_fraction": 0.6810738255, "num_tokens": 2012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5030063686100283}}
{"text": "//\n// Copyright 1997, 1998, 1999 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Jeremy G. Siek, Lie-Quan Lee\n//\n// This file is part of the Matrix Template Library\n//\n// You should have received a copy of the License Agreement for the\n// Matrix Template Library along with the software;  see the\n// file LICENSE.  If not, contact Office of Research, University of Notre\n// Dame, Notre Dame, IN  46556.\n//\n// Permission to modify the code and to distribute modified code is\n// granted, provided the text of this NOTICE is retained, a notice that\n// the code was modified is included with the above COPYRIGHT NOTICE and\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n// file is distributed with the modified code.\n//\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n// By way of example, but not limitation, Licensor MAKES NO\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n// OR OTHER RIGHTS.\n//\n\n#include <iostream>\n#include <mtl/matrix.h>\n\nint\nmain()\n{\n#ifdef MTL_DISABLE_BLOCKING\n  std::cout << \"Static blocking unsupported for this compiler\" << std::endl;\n#else\n  using namespace mtl;\n  //begin\n  const int M = 4;\n  const int N = 4;\n  typedef matrix<double,\n                 rectangle<>, \n                 dense<>, \n                 column_major >::type Matrix;\n  Matrix A(M,N);\n\n  for (int i = 0; i < M; ++i)\n    for (int j = 0; j < N; ++j)\n      A(i, j) = i * N + j;\n  print_all_matrix(A);\n\n  block_view<Matrix,2,2>::type\n                     bA = blocked(A, blk<2,2>());\n  print_partitioned_matrix(bA);\n\n  block_view<Matrix>::type cA = blocked(A, 2, 2);\n  print_partitioned_by_column(cA);\n  //end\n  return 0;\n#endif\n}\n", "meta": {"hexsha": "9912a675079ef63aa51d59050a9fcadc0f6c73c7", "size": 1851, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/blocked_matrix.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/tools/mtl-2.0/contrib/examples/blocked_matrix.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/tools/mtl-2.0/contrib/examples/blocked_matrix.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": 30.85, "max_line_length": 76, "alphanum_fraction": 0.6839546191, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5030063562112537}}
{"text": "/*\n * pyramid.hpp\n *\n *  Created on: Apr 10, 2019\n *      Author: Gregory Kramida\n *   Copyright: 2019 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//Standard library\n#include <vector>\n#include <memory>\n\n//Libraries\n#include <Eigen/Dense>\n\n//local\n#include \"../../math/resampling.hpp\"\n\nnamespace nonrigid_optimization {\nnamespace hierarchical{\n\n/**\n * A pyramid representation of a discrete scalar field\n */\ntemplate <typename Container>\nclass Pyramid{\npublic:\n\tPyramid(Container field, int maximum_chunk_size=8, math::DownsamplingStrategy downsampling_strategy\n\t\t\t= math::DownsamplingStrategy::AVERAGE);\n\n\tconst Container& get_level(int i_level) const;\n\tsize_t get_level_count() const;\nprivate:\n\tstd::vector<Container> levels;\n};\n\n} //namespace hierarchical\n} //namespace nonrigid_optimization\n", "meta": {"hexsha": "8af9a69308051c2fe52cf33aaaa22438e5c8ebd4", "size": 1357, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/nonrigid_optimization/hierarchical/pyramid.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/nonrigid_optimization/hierarchical/pyramid.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/nonrigid_optimization/hierarchical/pyramid.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": 25.6037735849, "max_line_length": 100, "alphanum_fraction": 0.7369196758, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5030063537399505}}
{"text": "#include <vector>\n#include <iostream>\n#include <eigen3/Eigen/Sparse>\n#include <eigen3/Eigen/IterativeLinearSolvers>\n// #include <eigen3/Eigen/Core>\n// #include <eigen3/Eigen/SparseCore>\n// #include <Eigen/SparseCholesky>\n// #include<Eigen/SparseLU> \n// #include<Eigen/SparseQR>\n// #include <Eigen/IterativeLinearSolvers>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(){\n    typedef Eigen::Triplet<double> T;\n    typedef Eigen::SparseMatrix<double> SpMat;\n\n    Eigen::SparseMatrix<std::complex<float> > complex_mat(1000,2000);\n    Eigen::SparseMatrix<double> mat(1000,2000); \n    \n    cout << \"Sparse matrix sizes\" << endl;\n    cout << mat.rows();\n    cout << mat.cols();\n    cout << mat.innerSize();\n    cout << mat.outerSize();\n    cout << mat.nonZeros();\n\n    // use triplet to fill in sparse matrix\n    vector<T> triplet_list; \n    for (int i = 0;i<1000;i=i+100){\n        triplet_list.push_back(T(i, i, i));\n    }\n\n    mat.setFromTriplets(triplet_list.begin(), triplet_list.end());\n    \n    cout << \"Sparse Matrix entries after initialization\" << endl;\n    for (int k=0; k<mat.outerSize(); ++k)\n        for (SparseMatrix<double>::InnerIterator it(mat,k); it; ++it)\n        {\n            cout << it.value() << endl;\n            cout << it.row() << endl;   // row index\n            cout << it.col() << endl;   // col index (here it is equal to k)\n            cout << it.index() << endl; // inner index, here it is equal to it.row()\n        }\n\n    // Supported operators and functions \n    // sparse matrices cannot offer the same level of flexibility than dense matrices\n    mat.transpose();\n    mat.adjoint();\n\n    mat.pruned();\n    double ref = 1e-8;\n    mat.pruned(ref);\n    \n\n    // // Eigen Sparse matrix solver \n    // SparseMatrix<double> A;\n    // // fill A\n    // VectorXd b, x;\n    // // fill b\n    // // solve Ax = b\n    // ConjugateGradient<SparseMatrix<double> > solver;\n    // solver.compute(A);\n    // if(solver.info()!=Success) {\n    // // decomposition failed\n    // return;\n    // }\n    // x = solver.solve(b);\n    // if(solver.info()!=Success) {\n    // // solving failed\n    // return;\n    // }\n    // // solve for another right hand side:\n    // x = solver.solve(b);\n\n    \n\n    return 0;\n}", "meta": {"hexsha": "13be3488b871963a22333684de32ff94e83a2ff6", "size": 2219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Eigen/eigen_sparse.cpp", "max_stars_repo_name": "shen338/MySLAM", "max_stars_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_stars_repo_licenses": ["MIT"], "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/eigen_sparse.cpp", "max_issues_repo_name": "shen338/MySLAM", "max_issues_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_issues_repo_licenses": ["MIT"], "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/eigen_sparse.cpp", "max_forks_repo_name": "shen338/MySLAM", "max_forks_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_forks_repo_licenses": ["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.7375, "max_line_length": 85, "alphanum_fraction": 0.5935105904, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5030063487762148}}
{"text": "#ifndef ALEPH_GEOMETRY_TANGENT_SPACE_HH__\n#define ALEPH_GEOMETRY_TANGENT_SPACE_HH__\n\n#include <aleph/config/Eigen.hh>\n\n#include <aleph/geometry/BruteForce.hh>\n#include <aleph/geometry/FLANN.hh>\n\n#include <aleph/geometry/distances/Euclidean.hh>\n\n#include <aleph/math/AlgebraicSphere.hh>\n#include <aleph/math/KahanSummation.hh>\n\n#ifdef ALEPH_WITH_EIGEN\n  #include <Eigen/Core>\n  #include <Eigen/Cholesky>\n  #include <Eigen/Eigenvalues>\n  #include <Eigen/SVD>\n#endif\n\n#include <cassert>\n\n#include <set>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace geometry\n{\n\nnamespace detail\n{\n\n/**\n  Model of a smooth decreasing weight function according to the\n  original paper *Algebraic Point Set Surfaces* by Guennebaud &\n  Gross.\n*/\n\ntemplate <class T> T phi( T x )\n{\n  return x < 1 ? std::pow( 1 - x*x, T(4) ) : T();\n}\n\n} // namespace detail\n\n#ifdef ALEPH_WITH_EIGEN\n\n// Previous versions of Eigen have a bug that occurs when mixing dynamic\n// and fixed-sized vectors:\n//\n//   http://eigen.tuxfamily.org/bz/show_bug.cgi?id=654\n//\n// Until a workaround has been identified, tangent space estimation will\n// not be enabled for older versions.\n#if EIGEN_VERSION_AT_LEAST(3,3,0)\n\nclass TangentSpace\n{\npublic:\n  using T        = double;\n\n  using Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n  using Vector = Eigen::Matrix<T, 1, Eigen::Dynamic>;\n\n  using Sphere = math::AlgebraicSphere<T>;\n\n#if EIGEN_VERSION_AT_LEAST(3,3,0)\n  using Index = Eigen::Index;\n#else\n  using Index = typename Matrix::Index;\n#endif\n\n  struct LocalTangentSpace\n  {\n    Matrix tangents;\n    Vector normal;\n    Vector position;\n\n    T localFeatureSize;\n    std::vector<std::size_t> indices;\n  };\n\n  template <class Container> std::vector<T> operator()( const Container& container, unsigned k )\n  {\n    std::vector<double> curvature;\n    curvature.reserve( container.size() );\n\n    auto lts     = localTangentSpaces( container, k );\n    auto spheres = fitSpheresWithoutNormals( container, lts );\n\n    std::transform( spheres.begin(), spheres.end(), std::back_inserter( curvature ),\n      [] ( const Sphere& sphere )\n      {\n        return sphere.meanCurvature();\n      }\n    );\n\n    return curvature;\n  }\n\nprivate:\n\n  /**\n    Given a container and a number for determining the local\n    neighbourhood of points, this function estimates (!) the\n    tangent space structure around every point, resulting in\n    a set of normal vectors and tangent vectors.\n\n    @param container Container\n    @param k         Local neighbourhood size\n  */\n\n  template <class Container> std::vector<LocalTangentSpace> localTangentSpaces( const Container& container, unsigned k )\n  {\n    using ElementType = typename Container::ElementType;\n    using Distance    = distances::Euclidean<ElementType>;\n\n#ifdef ALEPH_WITH_FLANN\n    using NearestNeighbours = FLANN<Container, Distance>;\n#else\n    using NearestNeighbours = BruteForce<Container, Distance>;\n#endif\n\n    NearestNeighbours nearestNeighbours( container );\n    using IndexType = typename NearestNeighbours::IndexType;\n\n    std::vector< std::vector<IndexType> > indices;\n    std::vector< std::vector<ElementType> > distances;\n\n    nearestNeighbours.neighbourSearch( k,\n                                       indices,\n                                       distances );\n\n    std::vector<LocalTangentSpace> localTangentSpaces;\n\n    auto n = container.size();\n    auto d = container.dimension();\n\n    for( std::size_t i = 0; i < n; i++ )\n    {\n      // This coordinate matrix will contain the differences to the\n      // centroid coordinate. The matrix will be transformed via an\n      // SVD.\n      Matrix M = Matrix::Zero( Index(k), Index(d) );\n\n      // Centroid calculation ------------------------------------------\n\n      Vector centroid  = Vector::Zero(1, Index(d) );\n\n      for( std::size_t j = 0; j < indices[i].size(); j++ )\n      {\n        auto&& neighbourIndex = indices[i][j];\n        auto v                = getPosition( container, neighbourIndex );\n\n        centroid          += v;\n        M.row( Index(j) )  = v;\n      }\n\n      centroid /= static_cast<T>( indices.size() );\n\n      // Coordinate matrix setup ---------------------------------------\n\n      M = M.rowwise() - centroid;\n\n      Eigen::JacobiSVD<Matrix> svd( M, Eigen::ComputeThinV );\n\n      LocalTangentSpace lts;\n      lts.tangents = Matrix::Zero( Index(d), Index(d - 1) );\n\n      // The singular vectors of all but the *smallest* singular value\n      // form the tangential directions of the tangent space.\n\n      auto&& V = svd.matrixV();\n\n      // Actual or \"effective\" dimensionality of the input data. If the\n      // matrix is rectangular (and most input matrices will be), there\n      // is not a full system of singular vectors available.\n      auto dEffective  = std::min( Index(d-1), Index(k-1) );\n\n      for( Index j = 0; j < dEffective; j++ )\n        lts.tangents.col(j) = V.col(j);\n\n      lts.normal           = V.col( dEffective  ).normalized();\n      lts.position         = getPosition( container, i );\n      lts.indices          = indices[i];\n\n      // Take the *maximum distance* in which we can find all of the\n      // neighbours as a *rough*  approximation to the local feature\n      // size.\n      lts.localFeatureSize\n        = distances[i].empty() == false ?\n            *std::max_element( distances[i].begin(), distances[i].end() )\n          : T();\n\n      localTangentSpaces.push_back( lts );\n\n      // TODO:\n      //\n      // 1. Calculate raw approximation (reconstruction) error by\n      //    assessing how well the space fits the original data\n      //\n      // 2. Make normal orientation consistent. I am unsure as to\n      //    whether this will improve the results or not.\n    }\n\n    propagateOrientation( localTangentSpaces );\n    return localTangentSpaces;\n  }\n\n  template <class Container>\n    std::vector<Sphere> fitSpheres( const Container& container,\n                                    const std::vector<LocalTangentSpace>& localTangentSpaces )\n  {\n    using namespace detail;\n\n    std::vector<Sphere> spheres;\n    spheres.reserve( container.size() );\n\n    for( auto&& lts : localTangentSpaces )\n    {\n      auto d   = Index( container.dimension() );\n      Matrix A = Matrix::Zero( d+2, d+2 );\n      Vector b = Vector::Zero( 1,   d+2 );\n\n      auto&& indices = lts.indices;\n\n      // Pre-processing --------------------------------------------------\n      //\n      // Choose a value for the beta parameter, based on the weighted\n      // neighbourhood sizes of *all* points. This requires iterating\n      // over all points prior to calculating anything else.\n\n      T beta = T();\n\n      {\n        std::vector<T> W;\n        std::vector<T> H;\n        W.reserve( container.size() );\n        H.reserve( container.size() );\n\n        for( auto&& index : indices )\n        {\n          auto&& neighbour = getPosition( container, index );\n          W.emplace_back( phi( ( lts.position - neighbour ).norm() / lts.localFeatureSize ) );\n          H.emplace_back( lts.localFeatureSize );\n        }\n\n        // Sum of weights *before* applying the local feature size\n        // multiplier; we need to save this result because it will\n        // be required below.\n        auto ws = math::accumulate_kahan_sorted( W.begin(), W.end(), T() );\n\n        // Apply weights to local feature size estimates; afterwards we\n        // can finally obtain the scaling factor from this weighted sum\n        for( std::size_t i = 0; i < W.size(); i++ )\n          W[i] = W[i] * H[i];\n\n        // TODO: make initial guess for beta (10e6) configurable?\n        auto h = math::accumulate_kahan_sorted( W.begin(), W.end(), T() ) / ws;\n        beta   = 10e6 * h * h;\n      }\n\n      Index k  = Index( indices.size() );\n      Matrix W = Matrix::Zero( (d+1)*k, (d+1)*k );\n      Matrix D = Matrix::Zero( (d+1)*k, (d+2)   );\n      Matrix c = Matrix::Zero( (d+1)*k, 1       );\n\n      {\n        Index i = Index();\n\n        for( auto&& index : indices )\n        {\n          auto neighbour       = getPosition( container, index );\n          auto w               = phi( ( lts.position - neighbour ).norm() / lts.localFeatureSize );\n          W( i*(d+1),i*(d+1) ) = w;\n\n          for( Index(j) = 0; j < d; j++ )\n          {\n            assert( W( i*(d+1)+j+1, i*(d+1)+j+1 ) == 0 );\n            W( i*(d+1)+j+1, i*(d+1)+j+1 ) = beta * w;\n          }\n\n          ++i;\n        }\n      }\n\n      {\n        Index i = Index();\n\n        for( auto&& index : indices )\n        {\n          auto neighbour       = getPosition( container, index );\n          D( i*(d+1), 0 )      = 1.0;\n\n          for( Index(j) = 0; j < d; j++ )\n            D( i*(d+1), j+1 ) = neighbour(j);\n\n          D( i*(d+1), d+1) = neighbour * neighbour.transpose();\n\n          for( Index(j) = 0; j < d; j++ )\n          {\n            D( i*(d+1)+j+1, j+1 ) = 1;\n            D( i*(d+1)+j+1, d+1 ) = 2 * neighbour(j);\n            c( i*(d+1)+j+1, 0   ) = localTangentSpaces.at(index).normal(j);\n          }\n\n          ++i;\n        }\n      }\n\n      for( auto&& index : indices )\n      {\n        auto neighbour           = getPosition( container, index );\n        auto squaredNeigbourNorm = neighbour.squaredNorm();\n        auto w                   = phi( ( lts.position - neighbour ).norm() / lts.localFeatureSize );\n\n        A(   0,   0) += w;\n        A( d+1,   0) += w * squaredNeigbourNorm;\n        A( d+1, d+1) += w * squaredNeigbourNorm * squaredNeigbourNorm;\n\n        for( Index(i) = 1; i < d+1; i++ )\n        {\n          A(  i,   i) += w * ( neighbour(i-1)*neighbour(i-1) + 1 ) * beta;\n          A(  i,   0) += w * ( neighbour(i-1) );\n          A(d+1,   i) += w * ( neighbour(i-1)*squaredNeigbourNorm + 2 * beta * neighbour(i-1) );\n          A(d+1, d+1) += w * ( 4*neighbour(i-1)*neighbour(i-1) ) * beta;\n\n          // re-establish symmetry\n          A(  0,   i)  = A(i,0);\n          A(  i, d+1)  = A(d+1, i);\n\n          b(i  ) +=       beta * w * localTangentSpaces.at(index).normal(i-1);\n          b(d+1) += 2.0 * beta * w * localTangentSpaces.at(index).normal(i-1) * neighbour(i-1);\n\n          for( Index(j) = i+1; j < d+1; j++ )\n          {\n            A(j, i) += w * neighbour(i-1) * neighbour(j-1);\n            A(i, j)  = A(j,i);\n          }\n        }\n\n        // re-establish symmetry\n        A(0, d+1) = A(d+1, 0);\n      }\n\n      // Solve the linear system ---------------------------------------\n      //\n      // The solution of the system Ax = b is used to obtain the\n      // coefficients of the algebraic sphere.\n\n      using Solver = Eigen::LDLT<Matrix>;\n      Solver solver(A);\n\n      Vector u = solver.solve( b.transpose() );\n\n      spheres.emplace_back( Sphere( u.data(), u.data() + u.size() ) );\n    }\n\n    return spheres;\n  }\n\n  template <class Container>\n    std::vector<Sphere> fitSpheresWithoutNormals( const Container& container,\n                                                  const std::vector<LocalTangentSpace>& localTangentSpaces )\n  {\n    using namespace detail;\n\n    std::vector<Sphere> spheres;\n    spheres.reserve( container.size() );\n\n    for( auto&& lts : localTangentSpaces )\n    {\n      auto&& indices = lts.indices;\n      auto d         = Index( container.dimension() );\n      auto k         = Index( indices.size() );\n\n      Matrix W = Matrix::Zero(k,k  );\n      Matrix D = Matrix::Zero(k,d+2);\n      Matrix C = Matrix::Identity(d+2,d+2);\n\n      C(0  ,  0) =  0;\n      C(0  ,d+1) = -2;\n      C(d+1,  0) = -2;\n      C(d+1,d+1) =  0;\n\n      {\n        Index i = Index();\n        for( auto&& index : indices )\n        {\n          auto neighbour = getPosition( container, index );\n          W(i,  i)       = phi( ( lts.position - neighbour ).norm() / lts.localFeatureSize );\n          D(i,  0)       = 1;\n          D(i,d+1)       = neighbour * neighbour.transpose();\n\n          for( Index j = 0; j < d; j++ )\n            D(i,j+1) = neighbour(j);\n\n          ++i;\n        }\n      }\n\n      // Solve the linear system ---------------------------------------\n      //\n      // The solution of the system Ax = b is used to obtain the\n      // coefficients of the algebraic sphere.\n\n      using Solver = Eigen::GeneralizedEigenSolver<Matrix>;\n      Solver solver;\n      solver.compute( D.transpose() * W * D, C );\n\n      auto eigenvalues = solver.eigenvalues();\n      Vector u         = Vector::Zero( 1, d+2 );\n\n      for( Index i = 0; i < d+2; i++ )\n      {\n        if( eigenvalues(i).real() > 0 && eigenvalues(i).imag() == 0 )\n        {\n          u = solver.eigenvectors().real().col(i);\n          break;\n        }\n      }\n\n      spheres.emplace_back( Sphere( u.data(), u.data() + u.size() ) );\n    }\n\n    return spheres;\n  }\n\n\n  void propagateOrientation( std::vector<LocalTangentSpace>& localTangentSpaces )\n  {\n    using Edge = std::pair<std::size_t, std::size_t>;\n\n    std::set<Edge> edges;\n    for( std::size_t i = 0; i < localTangentSpaces.size(); i++ )\n    {\n      for( auto&& index : localTangentSpaces.at(i).indices )\n      {\n        if( i < index )\n          edges.insert( std::make_pair(i,index) );\n        else\n          edges.insert( std::make_pair(index,i) );\n      }\n    }\n\n    for( auto&& edge : edges )\n    {\n      auto i    = edge.first;\n      auto&& ni = localTangentSpaces.at(i).normal;\n      auto j    = edge.second;\n      auto&& nj = localTangentSpaces.at(j).normal;\n\n      if( ni * nj.transpose() < 0 )\n        nj = -nj;\n    }\n  }\n\n  /**\n    Auxiliary function for extracting and converting a position from\n    a given container, storing it as a (mathematical) vector.\n  */\n\n  template <class Container> Vector getPosition( const Container& container, std::size_t i )\n  {\n    auto d   = container.dimension();\n    auto p   = container[i];\n    Vector v = Vector::Zero(1, Index(d) );\n\n    // copy (and transform!) the vector; there's an implicit type\n    // conversion going on here\n    for( std::size_t l = 0; l < d; l++ )\n      v( Index(l) ) = p[l];\n\n    return v;\n  }\n};\n\n#endif\n\n#endif\n\n} // namespace geometry\n\n} // namespace aleph\n\n#endif\n", "meta": {"hexsha": "ce4aad339c685a74d29157766319fdfa8c545c64", "size": 13932, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/aleph/geometry/TangentSpace.hh", "max_stars_repo_name": "maexlich/Aleph", "max_stars_repo_head_hexsha": "772244ec0cf64250a20579b349deb02523ca3fc7", "max_stars_repo_licenses": ["MIT"], "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/aleph/geometry/TangentSpace.hh", "max_issues_repo_name": "maexlich/Aleph", "max_issues_repo_head_hexsha": "772244ec0cf64250a20579b349deb02523ca3fc7", "max_issues_repo_licenses": ["MIT"], "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/aleph/geometry/TangentSpace.hh", "max_forks_repo_name": "maexlich/Aleph", "max_forks_repo_head_hexsha": "772244ec0cf64250a20579b349deb02523ca3fc7", "max_forks_repo_licenses": ["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.490797546, "max_line_length": 120, "alphanum_fraction": 0.5540482343, "num_tokens": 3691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.502990252650031}}
{"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_ACSC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACSC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the inverse cosecant in radian: \\f$\\arcsin(1/x)\\f$.\n\n    @par Header <boost/simd/function/acsc.hpp>\n\n    @see acscd, acscpi, asin, asin, sin, rec\n\n    @par Example:\n\n      @snippet acsc.cpp acsc\n\n    @par Possible output:\n\n      @snippet acsc.txt acsc\n\n  **/\n  IEEEValue acsc(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acsc.hpp>\n#include <boost/simd/function/simd/acsc.hpp>\n\n#endif\n", "meta": {"hexsha": "f7c74dc0eb352b8569a73e52c7e28a41d06f5082", "size": 1031, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acsc.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/function/acsc.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/function/acsc.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": 23.976744186, "max_line_length": 100, "alphanum_fraction": 0.574199806, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.5029902442353132}}
{"text": "/*!\n * @file     double_integrator.cpp\n * @author   Giuseppe Rizzi\n * @date     23.07.2020\n * @version  1.0\n * @brief    description\n */\n\n#include <Eigen/Dense>\n#include <array>\n#include <chrono>\n#include \"mppi/controller/mppi.h\"\n\nusing namespace Eigen;\nusing namespace mppi;\n\n// Simple dynamics class representing a point mass subject to a force\nclass DoubleIntegratorDynamics : public DynamicsBase {\n public:\n  DoubleIntegratorDynamics() {\n    A << 0.0, 1.0, 0.0, 0.0;\n    B << 0.0, 1.0;\n    x << 0.0, 0.0;\n  };\n  ~DoubleIntegratorDynamics() = default;\n\n  size_t get_input_dimension() override { return 1; }\n  size_t get_state_dimension() override { return 2; }\n\n  dynamics_ptr create() override { return mppi::DynamicsBase::dynamics_ptr(); }\n  dynamics_ptr clone() const override {\n    return std::make_shared<DoubleIntegratorDynamics>(*this);\n  }\n\n  void reset(const observation_t& xr) override { x = xr; }\n\n  observation_t step(const input_t& u, const double dt) override {\n    x += (A * x + B * u) * dt;\n    return x;\n  }\n\n  // does not make sense, just to test this function is used properly in the\n  // control loop\n  input_t get_zero_input(const observation_t& x) override {\n    return input_t::Ones(1) * x(0);\n  }\n\n private:\n  Eigen::Vector2d x;\n  Eigen::Matrix<double, 2, 2> A;\n  Eigen::Matrix<double, 2, 1> B;\n};\n\n// Simple cost class driving the point mass to 1\nclass DoubleIntegratorCost : public CostBase {\n public:\n  DoubleIntegratorCost() = default;\n  ~DoubleIntegratorCost() = default;\n  cost_ptr create() override { return mppi::CostBase::cost_ptr(); }\n  cost_ptr clone() const override { return mppi::CostBase::cost_ptr(); }\n  cost_t compute_cost(const observation_t& x, const reference_t& r,\n                      const double t) {\n    return w * (x(0) - 1.0) * (x(0) - 1.0);\n  }\n\n private:\n  double w = 10;\n};\n", "meta": {"hexsha": "df0875a24b7eabdc3dd989c55d2840ea20ee2bf2", "size": 1832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mppi/unittest/double_integrator.cpp", "max_stars_repo_name": "ethz-asl/mppi_mobile_manipulation", "max_stars_repo_head_hexsha": "1ec4b792f05b9cab97f149d41ad97573a77fc749", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-06T17:44:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T13:22:56.000Z", "max_issues_repo_path": "mppi/unittest/double_integrator.cpp", "max_issues_repo_name": "ethz-asl/mppi_mobile_manipulation", "max_issues_repo_head_hexsha": "1ec4b792f05b9cab97f149d41ad97573a77fc749", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mppi/unittest/double_integrator.cpp", "max_forks_repo_name": "ethz-asl/mppi_mobile_manipulation", "max_forks_repo_head_hexsha": "1ec4b792f05b9cab97f149d41ad97573a77fc749", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-04-20T12:27:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-23T02:38:25.000Z", "avg_line_length": 26.5507246377, "max_line_length": 79, "alphanum_fraction": 0.6664847162, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5029889830684361}}
{"text": "/*\n * Copyright (c) Contributors to the Open 3D Engine Project.\n * For complete copyright and license terms please see the LICENSE at the root of this distribution.\n *\n * SPDX-License-Identifier: Apache-2.0 OR MIT\n *\n */\n\n#include <NumericalMethods_precompiled.h>\n#include <NumericalMethods/Eigenanalysis.h>\n#include <NumericalMethods/Optimization.h>\n#include <Optimization/SolverBFGS.h>\n#include <Eigenanalysis/Solver3x3.h>\n\nnamespace NumericalMethods\n{\n    namespace Optimization\n    {\n        SolverResult SolverBFGS(const Function& function, const AZStd::vector<double>& initialGuess)\n        {\n            return MinimizeBFGS(function, initialGuess);\n        }\n    }\n\n    namespace Eigenanalysis\n    {\n        SolverResult<Real, 3> Solver3x3RealSymmetric(const SquareMatrix<Real, 3>& matrix)\n        {\n            // The matrix must be symmetric.\n            if (matrix[0][1] == matrix[1][0] && matrix[0][2] == matrix[2][0] && matrix[1][2] == matrix[2][1])\n            {\n                return NonIterativeSymmetricEigensolver3x3(\n                    matrix[0][0], matrix[0][1], matrix[0][2],\n                                  matrix[1][1], matrix[1][2],\n                                                matrix[2][2]\n                );\n            }\n            else\n            {\n                return SolverResult<Real, 3>{SolverOutcome::FailureInvalidInput};\n            }\n        }\n    }\n} // namespace NumericalMethods\n", "meta": {"hexsha": "1275291dc4b1a30bf7f03827f23cd5e626a8c9a4", "size": 1429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gems/PhysX/Code/NumericalMethods/Source/NumericalMethods.cpp", "max_stars_repo_name": "Schneidex69/o3de", "max_stars_repo_head_hexsha": "d9ec159f0e07ff86957e15212232413c4ff4d1dc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-19T23:54:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-19T23:54:05.000Z", "max_issues_repo_path": "Gems/PhysX/Code/NumericalMethods/Source/NumericalMethods.cpp", "max_issues_repo_name": "Schneidex69/o3de", "max_issues_repo_head_hexsha": "d9ec159f0e07ff86957e15212232413c4ff4d1dc", "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": "Gems/PhysX/Code/NumericalMethods/Source/NumericalMethods.cpp", "max_forks_repo_name": "Schneidex69/o3de", "max_forks_repo_head_hexsha": "d9ec159f0e07ff86957e15212232413c4ff4d1dc", "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": 31.7555555556, "max_line_length": 109, "alphanum_fraction": 0.5787263821, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.502988983068436}}
{"text": "#ifndef _REGISTRATION_HPP_\n#define _REGISTRATION_HPP_\n\n#include <ros/ros.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <nav_msgs/Odometry.h>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Eigenvalues>\n\n//\u305d\u306e\u5834\u3067\u306e\u6bd4\u8f03\nEigen::Matrix4f registration_icp(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_tgt, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_src);\nEigen::Matrix4f registration_icp_I(pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_tgt, pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_src);\n\nEigen::Matrix4f registration_icp_vis(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_tgt, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_src,  pcl::PointCloud<pcl::PointXYZ>::Ptr &cloud);\n\nEigen::Matrix4f registration_ndt(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_tgt, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_src);\nEigen::Matrix4f registration_ndt_vis(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_tgt, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_src, pcl::PointCloud<pcl::PointXYZ>::Ptr &cloud);\n\n\n//map\u3092\u5143\u306b\u7b97\u51fa\nEigen::Matrix4f map_icp_vis(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_tgt, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_src, pcl::PointCloud<pcl::PointXYZ>::Ptr &cloud,nav_msgs::Odometry odo);\n\nEigen::Matrix4f map_ndt_vis(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_tgt, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_src, pcl::PointCloud<pcl::PointXYZ>::Ptr &cloud,nav_msgs::Odometry odo);\n\n#endif\n\n\n", "meta": {"hexsha": "2ac3c50e5663484d487f6b8a6200871877b15fd1", "size": 1394, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "local_tool/include/local_tool/registration.hpp", "max_stars_repo_name": "karrykarry/kari_localization", "max_stars_repo_head_hexsha": "e81e1fda587958e87771e149b5ca3769eae891fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "local_tool/include/local_tool/registration.hpp", "max_issues_repo_name": "karrykarry/kari_localization", "max_issues_repo_head_hexsha": "e81e1fda587958e87771e149b5ca3769eae891fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "local_tool/include/local_tool/registration.hpp", "max_forks_repo_name": "karrykarry/kari_localization", "max_forks_repo_head_hexsha": "e81e1fda587958e87771e149b5ca3769eae891fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.4666666667, "max_line_length": 189, "alphanum_fraction": 0.7733142037, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.502988983068436}}
{"text": "#ifndef __TWIST_CONTROLLER__\n#define __TWIST_CONTROLLER__\n\n#include <kdl/kdl.hpp>\n#include <kdl/frames.hpp>\n#include <Eigen/Dense>\n#include <iostream>\n\nnamespace cartesian_controllers{\n\n/**\n  Implements a pose controller that outputs a control twist.\n**/\nclass TwistController{\npublic:\n  TwistController(const Eigen::Matrix<double, 6, 1> &twist_gains);\n  ~TwistController();\n\n  /**\n    Return a twist proportional to the pose error between the two given frames.\n\n    @param current The present frame.\n    @param reference The reference frame.\n    @return A value proportional to the error \"reference - current\".\n  **/\n  KDL::Twist computeError(const KDL::Frame &current, const KDL::Frame &reference);\nprivate:\n  Eigen::Matrix<double, 6, 1> gains_;\n\n  /**\n    Computes the angle and axis rotation required to rotate v1 along v2.\n\n    @param v1\n    @param v2\n    @return The angle axis rotation.\n  **/\n  Eigen::AngleAxisd getAngleAxis(const Eigen::Vector3d &v1, const Eigen::Vector3d &v2);\n};\n}\n\n#endif\n", "meta": {"hexsha": "2fd2381957a708d5e33983467bcb408f2acdac1e", "size": 1001, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pr2_cartesian_controllers/include/utils/TwistController.hpp", "max_stars_repo_name": "diogoalmeida/pr2_controller_framework", "max_stars_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pr2_cartesian_controllers/include/utils/TwistController.hpp", "max_issues_repo_name": "diogoalmeida/pr2_controller_framework", "max_issues_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pr2_cartesian_controllers/include/utils/TwistController.hpp", "max_forks_repo_name": "diogoalmeida/pr2_controller_framework", "max_forks_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_forks_repo_licenses": ["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.8333333333, "max_line_length": 87, "alphanum_fraction": 0.7202797203, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5029864027283306}}
{"text": "// Copyright (c) 2020 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 <gsl/gsl_interp.h>\n#include <Eigen/Core>\n#include <functional>\n#include <memory>\n#include \"pyinterp/detail/broadcast.hpp\"\n#include \"pyinterp/detail/gsl/accelerator.hpp\"\n\nnamespace pyinterp::detail::gsl {\n\n/// Interpolate a 1-D function\nclass Interpolate1D {\n public:\n  /// Interpolate a 1-D function\n  ///\n  /// @param size Size of workspace\n  /// @param type fitting model\n  /// @param acc Accelerator\n  Interpolate1D(const size_t size, const gsl_interp_type* type, Accelerator acc)\n      : workspace_(\n            std::unique_ptr<gsl_interp, std::function<void(gsl_interp*)>>(\n                gsl_interp_alloc(type, size),\n                [](gsl_interp* ptr) { gsl_interp_free(ptr); })),\n        acc_(std::move(acc)) {}\n\n  /// Returns the name of the interpolation type used\n  [[nodiscard]] inline auto name() const noexcept -> std::string {\n    return gsl_interp_name(workspace_.get());\n  }\n\n  /// Return the minimum number of points required by the interpolation\n  [[nodiscard]] inline auto min_size() const noexcept -> size_t {\n    return gsl_interp_min_size(workspace_.get());\n  }\n\n  /// Return the interpolated value of y for a given point x\n  inline auto interpolate(const Eigen::VectorXd& xa, const Eigen::VectorXd& ya,\n                          const double x) -> double {\n    init(xa, ya);\n    return gsl_interp_eval(workspace_.get(), xa.data(), ya.data(), x, acc_);\n  }\n\n  /// Return the derivative d of an interpolated function for a given point x\n  inline auto derivative(const Eigen::VectorXd& xa, const Eigen::VectorXd& ya,\n                         const double x) -> double {\n    init(xa, ya);\n    return gsl_interp_eval_deriv(workspace_.get(), xa.data(), ya.data(), x,\n                                 acc_);\n  }\n\n  /// Return the second derivative d of an interpolated function for a given\n  /// point x\n  inline auto second_derivative(const Eigen::VectorXd& xa,\n                                const Eigen::VectorXd& ya, const double x)\n      -> double {\n    init(xa, ya);\n    return gsl_interp_eval_deriv2(workspace_.get(), xa.data(), ya.data(), x,\n                                  acc_);\n  }\n\n  /// Return the numerical integral result of an interpolated function over the\n  /// range [a, b],\n  inline auto integral(const Eigen::VectorXd& xa, const Eigen::VectorXd& ya,\n                       const double a, const double b) -> double {\n    init(xa, ya);\n    return gsl_interp_eval_integ(workspace_.get(), xa.data(), ya.data(), a, b,\n                                 acc_);\n  }\n\n private:\n  std::unique_ptr<gsl_interp, std::function<void(gsl_interp*)>> workspace_;\n  Accelerator acc_;\n\n  /// Initializes the interpolation object\n  void init(const Eigen::VectorXd& xa, const Eigen::VectorXd& ya) {\n    acc_.reset();\n    gsl_interp_init(workspace_.get(), xa.data(), ya.data(), xa.size());\n  }\n};\n\n}  // namespace pyinterp::detail::gsl\n", "meta": {"hexsha": "1353ca8eab53b6da6491751225b5b7757ab865cb", "size": 3033, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/detail/gsl/interpolate1d.hpp", "max_stars_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_stars_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-19T14:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-19T14:54:23.000Z", "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/detail/gsl/interpolate1d.hpp", "max_issues_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_issues_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/gsl/interpolate1d.hpp", "max_forks_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_forks_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "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.2674418605, "max_line_length": 80, "alphanum_fraction": 0.6383119024, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5029863971180323}}
{"text": "// Copyright PinaPL\n//\n// cell.hpp\n// PinaPL\n//\n#ifndef CELL_HPP\n#define CELL_HPP\n\n#include <math.h>\n#include <Eigen/Dense>\n#include <vector>\n\n#include \"weights.hpp\"\n\nclass Cell {\n public:\n    Weights* weights;\n    std::vector<Eigen::MatrixXd> inputs;\n    // std::vector<Eigen::MatrixXd> forget_gate_out;\n    std::vector<Eigen::MatrixXd> input_gate_out;\n    std::vector<Eigen::MatrixXd> input_block_out;\n    std::vector<Eigen::MatrixXd> output_gate_out;\n    std::vector<Eigen::MatrixXd> cell_state;\n    std::vector<Eigen::MatrixXd> cell_out;\n\n    std::vector<Eigen::MatrixXd> delta_cell_out;                // dy\n    std::vector<Eigen::MatrixXd> delta_output_gate_out;         // do\n    std::vector<Eigen::MatrixXd> delta_cell_state;              // dc\n    // std::vector<Eigen::MatrixXd> delta_forget_gate_out;      // df\n    std::vector<Eigen::MatrixXd> delta_input_gate_out;          // di\n    std::vector<Eigen::MatrixXd> delta_input_block_out;         // dz\n\n    explicit Cell(Weights* weights);\n    void compute(Eigen::MatrixXd* input);\n    Eigen::MatrixXd compute_gate_gradient(Eigen::MatrixXd* deltas, int time);\n    void compute_weight_gradient();\n    void update_weights(double lambda);\n    void reset();\n};\n#endif\n", "meta": {"hexsha": "a8e9e1568548612874c24b42cd2cc43765b3fec6", "size": 1225, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell.hpp", "max_stars_repo_name": "supelec-lstm/PinaPL_lstm", "max_stars_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cell.hpp", "max_issues_repo_name": "supelec-lstm/PinaPL_lstm", "max_issues_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cell.hpp", "max_forks_repo_name": "supelec-lstm/PinaPL_lstm", "max_forks_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_forks_repo_licenses": ["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.8780487805, "max_line_length": 77, "alphanum_fraction": 0.6726530612, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5029863915077337}}
{"text": "#include <boost/lexical_cast.hpp>\n\n#include \"Chi2.hh\"\n\nusing namespace Eigen;\n\nvoid Chi2::add(SingleOutput &theory, SingleOutput &data, SingleOutput &errors) {\n  t_[\"chi2\"].input(theory);\n  t_[\"chi2\"].input(data);\n  t_[\"chi2\"].input(errors);\n}\n\nvoid Chi2::checkTypes(TypesFunctionArgs fargs) {\n  auto& args=fargs.args;\n  auto& rets=fargs.rets;\n  if (args.size()%3 != 0) {\n    throw args.undefined();\n  }\n  for (size_t i = 0; i < args.size(); i+=3) {\n    auto& theory = args[i+0];\n    auto& data   = args[i+1];\n    auto& errors = args[i+2];\n    if (theory.shape.size() != 1) {\n      throw rets.error(rets[0], \"non-vector theory\");\n    }\n    if (data.shape != theory.shape) {\n      throw rets.error(rets[0], \"data and theory have different shape\");\n    }\n\n    switch(errors.shape.size()){\n      case 1:\n        /// Errors: uncorrelated uncertainties (first power)\n        break;\n      case 2:\n        /// Errors: L - lower triangular decomposition of covariance matrix\n        if (errors.shape[0] != errors.shape[1]) {\n          throw rets.error(rets[0], \"incompatible covmat shape\");\n        }\n        break;\n      default:\n        throw rets.error(rets[0], \"invalid dimension (errors input)\");\n        break;\n    }\n\n    if (errors.shape[0] != theory.shape[0]) {\n      throw rets.error(rets[0], \"errors are unconsistent with data\");\n    }\n  }\n  rets[0] = DataType().points().shape(1);\n}\n\nvoid Chi2::calculateChi2(FunctionArgs fargs) {\n  auto& args=fargs.args;\n  double res=0.0;\n  for (size_t i = 0; i < args.size(); i+=3) {\n    VectorXd diff = args[i+0].vec - args[i+1].vec;\n    auto& errors = args[i+2];\n    switch(errors.type.shape.size()){\n      case 1:\n        diff.array()/=errors.arr;\n        break;\n      case 2:\n        errors.mat.triangularView<Eigen::Lower>().solveInPlace(diff);\n        break;\n      default:\n        break;\n    }\n    res += diff.array().square().sum();\n  }\n  fargs.rets[0].arr(0)=res;\n}\n", "meta": {"hexsha": "f55edf6db57b51799d046ea706b05d29a7b6eb3b", "size": 1914, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/stats/Chi2.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/stats/Chi2.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/stats/Chi2.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.5833333333, "max_line_length": 80, "alphanum_fraction": 0.5867293626, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5029863858974349}}
{"text": "#define BOOST_TEST_MODULE lue core time point\n#include <boost/test/unit_test.hpp>\n#include \"lue/core/time.hpp\"\n\n\nBOOST_AUTO_TEST_CASE(seconds)\n{\n    namespace ldm = lue::data_model;\n\n    // Time point at 6 ticks in a clock with a tick period of 10 seconds,\n    // so the point is located at 60 seconds\n    std::size_t const nr_seconds_per_tick = 10;\n    std::size_t const nr_ticks = 6;\n\n    using TickPeriod = ldm::time::TickPeriod<ldm::time::Second>;\n    using Clock = ldm::time::Clock<TickPeriod>;\n    using Duration = Clock::Duration;\n    using TimePoint = ldm::time::TimePoint<Clock>;\n\n    TickPeriod tick_period{nr_seconds_per_tick};\n    Clock clock{ldm::time::Epoch{}, tick_period};\n    Duration duration{nr_ticks};\n    TimePoint time_point{duration};\n\n    BOOST_CHECK(time_point.duration() == duration);\n}\n\n\nBOOST_AUTO_TEST_CASE(days)\n{\n    namespace ldm = lue::data_model;\n\n    // Types for tracking days\n    using TickPeriod = ldm::time::TickPeriod<ldm::time::Day>;\n    using Clock = ldm::time::Clock<TickPeriod>;\n    using Duration = Clock::Duration;\n    using TimePoint = ldm::time::TimePoint<Clock>;\n\n    // Clock with a resolution of 2 days\n    TickPeriod tick_period{2};\n    Clock clock(ldm::time::Epoch{}, tick_period);\n\n    // Select day 6 (3 * 2 days)\n    Duration duration{3};\n    TimePoint day_6{duration};\n\n    BOOST_CHECK_EQUAL(clock.nr_units(day_6), 6);\n}\n", "meta": {"hexsha": "86f157e8ed0727b4795ccbe8c69974e15c0f9271", "size": 1378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/data_model/cxx/test/core/time/time_point_test.cpp", "max_stars_repo_name": "computationalgeography/lue", "max_stars_repo_head_hexsha": "71993169bae67a9863d7bd7646d207405dc6f767", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-26T22:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T10:28:48.000Z", "max_issues_repo_path": "source/data_model/cxx/test/core/time/time_point_test.cpp", "max_issues_repo_name": "pcraster/lue", "max_issues_repo_head_hexsha": "e64c18f78a8b6d8a602b7578a2572e9740969202", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 262.0, "max_issues_repo_issues_event_min_datetime": "2016-08-11T10:12:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-13T18:09:16.000Z", "max_forks_repo_path": "source/data_model/cxx/test/core/time/time_point_test.cpp", "max_forks_repo_name": "computationalgeography/lue", "max_forks_repo_head_hexsha": "71993169bae67a9863d7bd7646d207405dc6f767", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-11T09:49:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T09:49:41.000Z", "avg_line_length": 28.1224489796, "max_line_length": 73, "alphanum_fraction": 0.6930333817, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5029863858974349}}
{"text": "//#include <lapacke.h>\n#include <stdio.h>\n#include <Eigen/Dense>\n#include <stdexcept>\n#include <iostream>\n\nchar lower = 'L';\n\n// TODO, remove dependency on lapacke.h\nextern \"C\" void dpotrf_(char *uplo, int *n, double *a, int *lda, int *info);\nextern \"C\" void dpotrs_(char *uplo, int* n, int* nrhs, double* A, int* lda, double* B, int* ldb, int* info);\n\nvoid chol_decomp(double* A, int n) {\n  int info;\n  dpotrf_(&lower, &n, A, &n, &info);\n  if(info != 0){ throw std::runtime_error(\"c++ error: Cholesky decomp failed\"); }\n}\n\nvoid chol_decomp(Eigen::MatrixXd & A) {\n  int info, n = A.rows();\n  dpotrf_(&lower, &n, A.data(), &n, &info);\n  if(info != 0) {\n    throw std::runtime_error(\n        std::string(\"c++ error: Cholesky decomp failed (for \")\n        + std::to_string(n)\n        + \" x \"\n        + std::to_string(n)\n        + \" eigen matrix)\");\n  }\n}\n\nvoid chol_solve(double* A, int n, double* B, int nrhs) {\n  int info;\n  dpotrs_(&lower, &n, &nrhs, A, &n, B, &n, &info);\n  if(info != 0){ throw std::runtime_error(\"c++ error: Cholesky solve failed\");}\n}\n\nvoid chol_solve(Eigen::MatrixXd & A, Eigen::MatrixXd & B) {\n  if (A.rows() != B.rows()) {throw std::runtime_error(\"A.rows() must equal B.rows()\");}\n  int info;\n  int n    = A.rows();\n  int nrhs = B.cols();\n  dpotrs_(&lower, &n, &nrhs, A.data(), &n, B.data(), &n, &info);\n  if(info != 0){ throw std::runtime_error(\"c++ error: Cholesky solve failed (for eigen matrix)\");}\n}\n\n/** solves A * X' = B' for X in place */\nvoid chol_solve_t(Eigen::MatrixXd & A, Eigen::MatrixXd & B) {\n  if (A.rows() != B.cols()) {throw std::runtime_error(\"A.rows() must equal B.cols()\");}\n  B.transposeInPlace();\n  chol_solve(A, B);\n  B.transposeInPlace();\n}\n\n", "meta": {"hexsha": "5eb62e2aea33a1ceaba1942bcc056b2f03af0323", "size": 1691, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/macau-cpp/chol.cpp", "max_stars_repo_name": "edebrouwer/macau", "max_stars_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2016-02-27T22:18:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:17:39.000Z", "max_issues_repo_path": "lib/macau-cpp/chol.cpp", "max_issues_repo_name": "edebrouwer/macau", "max_issues_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-05-23T14:14:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-16T08:12:40.000Z", "max_forks_repo_path": "lib/macau-cpp/chol.cpp", "max_forks_repo_name": "edebrouwer/macau", "max_forks_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T12:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T15:05:59.000Z", "avg_line_length": 30.7454545455, "max_line_length": 108, "alphanum_fraction": 0.6026020106, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5029863858974349}}
{"text": "#include <HMMlib/hmm_table.hpp>\n#include <HMMlib/hmm_vector.hpp>\n#include <HMMlib/hmm.hpp>\n\n#include <iostream>\n#include <stdio.h>\n#include <string.h>\n#include <vector>\n#include <stdlib.h>\n\n#include \"KFoldCrossValidation.h\"\n\n#include <dlib/clustering.h>\n#include <dlib/rand.h>\n\n#include \"Model/GestureFinger.h\"\n#include \"Model/GestureFrame.h\"\n#include \"Model/GestureHand.h\"\n#include \"Model/Vertex.h\"\n\n#include \"StorageDriver/BinaryFileStorageDriver.h\"\n#include \"StorageDriver/GestureStorageDriver.h\"\n\n#include \"PathUtil.h\"\n\n#include \"preprocess/LMpre.h\"\n\n#include \"HMM/HMMClass.h\"\n\nusing namespace hmmlib;\nusing namespace std;\n\n#define MAX_FINGER_COUNT 5\n\n// Should return a list of centroids (multiple per each class)\nvoid kmeans(std::vector<std::vector<double> > data, int classCounter = 13,\n\t\tint maxCentroidsPerOneClass = 8, double kernelParam = 0.1, double error = 0.01) {\n\ttypedef dlib::matrix<double> sample_type;\n\ttypedef dlib::radial_basis_kernel<sample_type> kernel_type;\n\n\t// The first argument to the constructor is the kernel we wish to\n\t// use.\n\t// The second is a parameter that determines the numerical accuracy with which\n\t// the object will perform part of the learning algorithm.  Generally, smaller values\n\t// give better results but cause the algorithm to attempt to use more dictionary vectors\n\t// (and thus run slower and use more memory).\n\t// The third argument, however, is the\n\t// maximum number of dictionary vectors a kcentroid is allowed to use.  So you can use\n\t// it to control the runtime complexity.\n\tdlib::kcentroid<kernel_type> kc(kernel_type(kernelParam), error, maxCentroidsPerOneClass);\n\n\t// Now we make an instance of the kkmeans object and tell it to use kcentroid objects\n\t// that are configured with the parameters from the kc object we defined above.\n\tdlib::kkmeans<kernel_type> kmeans(kc);\n\n\tstd::vector<sample_type> samples;\n\tstd::vector<sample_type> initial_centers;\n\n\t// Copying to compatible type\n\tfor (int i = 0; i < data.size(); i++) {\n\t\tsample_type m;\n\t\tm.set_size(data[i].size(),1);\n\n\t\tfor (int j = 0; j < data[i].size(); j++) {\n\t\t\tm(j) = data[i][j];\n\t\t}\n\t\tsamples.push_back(m);\n\t}\n\n\t// tell the kkmeans object we made that we want to run k-means with k set to 13.\n\t// (i.e. we want 13 clusters)\n\tkmeans.set_number_of_centers(classCounter);\n\n\t// You need to pick some initial centers for the k-means algorithm.  So here\n\t// we will use the dlib::pick_initial_centers() function which tries to find\n\t// n points that are far apart (basically).\n\tpick_initial_centers(classCounter, initial_centers, samples, kmeans.get_kernel());\n\n\t// now run the k-means algorithm on our set of samples.\n\tkmeans.train(samples, initial_centers);\n\n\t// To test one example:\n\t// label = test(samples[i])\n\n\t// Now print out how many dictionary vectors each center used.  Note that\n\t// the maximum number of 8 was reached.  If you went back to the kcentroid\n\t// constructor and changed the 8 to some bigger number you would see that these\n\t// numbers would go up.  However, 8 is all we need to correctly cluster this dataset.\n\tfor (int i = 0; i < classCounter; i++) {\n\t\tcout << \"num dictionary vectors for center \" << i<<\" : \"\n\t\t\t\t<< kmeans.get_kcentroid(i).dictionary_size() << endl;\n\t}\n}\n\n// Should return a list of centroids (1 per class)\nvoid kmeansSimple(std::vector<std::vector<double> > *data, int count,\n\t\tvector< vector<double> > &centroids, int classCounter = 13) {\n\n\ttypedef dlib::matrix<double> sample_type;\n\n\tstd::vector<sample_type> samples;\n\tstd::vector<sample_type> initial_centers;\n\n\t// Copying to compatible type\n\tfor (int k=0;k<count;k++)\n\t{\n\t\tfor (int i = 0; i < data[k].size(); i++) {\n\t\t\tsample_type m;\n\t\t\tm.set_size(data[k][i].size(),1);\n\n\t\t\tfor (int j = 0; j < data[k][i].size(); j++) {\n\t\t\t\tm(j) = data[k][i][j];\n\t\t\t}\n\t\t\tsamples.push_back(m);\n\t\t}\n\t}\n\n\ttypedef dlib::radial_basis_kernel<sample_type> kernel_type;\n\tpick_initial_centers(classCounter, initial_centers, samples, kernel_type(0.1));\n\tdlib::find_clusters_using_kmeans(samples, initial_centers);\n\n\tofstream kmeanscentroids;\n\tkmeanscentroids.open(\"centroids.dat\");\n\tfor (int i = 0; i < initial_centers.size(); i++) {\n\t\tkmeanscentroids << i <<\" \" << trans(initial_centers[i]);\n\t\tcentroids.push_back(vector< double >(initial_centers[i].size()));\n\t\tfor (int j = 0; j< initial_centers[i].size(); j++)\n\t\t{\n\t\t//\tcout<<initial_centers[i].size()<<endl;\n\t\t//\tcout<<initial_centers[i](j)<<endl;\n\t\t\tcentroids[i][j] = initial_centers[i](j);\n\t\t}\n\n\t}\n\tkmeanscentroids.close();\n}\n\nvoid readCentroidsFromFile( vector< vector<double> > &centroids )\n{\n\tifstream kmeanscentroids;\n\tkmeanscentroids.open(\"centroids.dat\");\n\tstring line;\n\tdouble val;\n\twhile(!kmeanscentroids.eof()) {\n\t\tkmeanscentroids>>val;\n\t\tif ( val != 0 )\n\t\t{\n\t\t\tvector<double> row;\n\t\t\tfor (int i=0;i<19;i++)\n\t\t\t{\n\t\t\t\tkmeanscentroids>>val;\n\t\t\t\trow.push_back(val);\n\t\t\t}\n\t\t\tcentroids.push_back(row);\n\t\t}\n\t}\n\tkmeanscentroids.close();\n}\n\n\n// Maybe define it differently ?\ndouble similarity(std::vector<double> a, std::vector<double> b)\n{\n\tif (a.size() != b.size())\n\t\treturn 1.0/0.00000001;\n\n\tdouble dist = 0.0;\n\n\tfor (int k = 0; k < a.size(); k++) {\n\t\tdist += pow(a[k] - b[k], 2);\n\t}\n\tif (dist < 0.0001) {\n\t\tdist = 0.0001;\n\t}\n\treturn 10.0 / dist;\n}\n\n// Can return labeled data, but cannot label new examples\nvoid newman_cluster(std::vector<std::vector<double> > data, double eps = 0.0001,\n\t\tunsigned long max_iteration = 2000) {\n\n\t// calculating the similarity measure between examples\n\tstd::vector<dlib::ordered_sample_pair> ord_samples;\n\tfor (int i = 0; i < data.size(); i++) {\n\t\tfor (int j = i+1; j < data.size(); j++) {\n\n\t\t\tdlib::ordered_sample_pair t(i, j, similarity(data[i], data[j]));\n\t\t\tord_samples.push_back(t);\n\t\t}\n\t}\n\tcout<<\"Running newman clustering\"<<endl;\n\tstd::vector<unsigned long> labels;\n\tdlib::newman_cluster(ord_samples, labels, eps, max_iteration);\n\n\n\tsort(labels.begin(), labels.end());\n\tunique(labels.begin(), labels.end());\n\tcout<<\"Newman found :\" <<labels.size() <<\" classes\" << endl;\n}\n\n// Can return labeled, but cannot label new examples\nvoid chinese_whispers(std::vector< std::vector<double> > data, unsigned long numberOfIteration = 100) {\n\t// calculating the similarity measure between examples\n\tstd::vector<dlib::ordered_sample_pair> ord_samples;\n\tfor (int i = 0; i < data.size(); i++) {\n\t\tfor (int j = i + 1; j < data.size(); j++) {\n\n\t\t\tdlib::ordered_sample_pair t(i, j, similarity(data[i], data[j]));\n\t\t\tord_samples.push_back(t);\n\t\t}\n\t}\n\tstd::vector<unsigned long> labels;\n\tdlib::chinese_whispers(ord_samples, labels, numberOfIteration);\n\n\tsort(labels.begin(), labels.end());\n\tunique(labels.begin(), labels.end());\n\tcout<<\"Chinese whispers found :\" <<labels.size() <<\" classes\" << endl;\n}\n\nint getIndexOfClassName(vector<string> &classNames, string name)\n{\n\tfor (int i=0; i<classNames.size(); i++)\n\t{\n\t\tif (classNames[i].compare(name) == 0)\n\t\t\treturn i;\n\t}\n\n\treturn -1;\n}\n\nvoid addAttribute(float attributeValue, int& attributeCounter,\n\t\tvector<double> &attributes) {\n\tattributes.push_back(attributeValue);\n\tattributeCounter++;\n}\n\nvoid fingerCountAttribute(int& fingerCount, int& attributeCounter,\n\t\tvector<double>& result) {\n\taddAttribute(fingerCount, attributeCounter, result);\n}\n\nvoid anglesBetweenFingersAttribute(GestureHand* tempHand, int& fingerCount,\n\t\tint& attributeCounter, vector<double>& result) {\n\n\t// If Hand exists and we have fingers\n\tif (tempHand != NULL && fingerCount > 1) {\n\n\n\t\tvector<float> angles(4, 0.0);\n\n\t\t// For all combinations of finger configurations\n\t\tfor (int i = 0; i < fingerCount; i++) {\n\t\t\tVertex fingerDirection = tempHand->getFinger(i)->getDirection();\n\n\t\t\tfor (int j= i+1 ;j < fingerCount; j++) {\n\t\t\t\tVertex fingerDirection2 = tempHand->getFinger(j)->getDirection();\n\t\t\t\tfloat angle = fingerDirection.dotProduct(fingerDirection);\n\t\t\t\tangles.push_back(angle);// Can be acos if somebody want it\n\t\t\t}\n\t\t}\n\n\t\tsort(angles.begin(), angles.end(), std::greater<float>());\n\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\taddAttribute(angles[i], attributeCounter, result);\n\t\t}\n\t}\n\t// There are no fingers in the captured data\n\telse\n\t{\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\taddAttribute(0.0, attributeCounter, result);\n\t\t}\n\t}\n}\n\nvoid anglesFingersPalmAttribute(GestureHand* tempHand, int& fingerCount,\n\t\tint& attributeCounter, vector<double>& result) {\n\n\t// If Hand exists and we have fingers\n\tif (tempHand != NULL && fingerCount > 1) {\n\n\t\tvector<float> angles(4, 0.0);\n\n\t\t// For all combinations of finger configurations\n\t\tfor (int i = 0; i < fingerCount; i++) {\n\t\t\tVertex fingerDirection = tempHand->getFinger(i)->getDirection();\n\t\t\tfloat angle = fingerDirection.dotProduct(tempHand->getPalmNormal());\n\t\t\tangles.push_back(angle);\t// Can be acos if somebody want it\n\t\t}\n\n\t\tsort(angles.begin(), angles.end(), std::greater<float>());\n\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\taddAttribute(angles[i], attributeCounter, result);\n\t\t}\n\t}\n\t// There are no fingers in the captured data\n\telse {\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\taddAttribute(0.0, attributeCounter, result);\n\t\t}\n\t}\n}\n\nvoid distancesBetweenFingersAttribute(GestureHand* tempHand, int& fingerCount,\n\t\tint& attributeCounter, vector<double>& result) {\n\n\t// If Hand exists and we have fingers\n\tif (tempHand != NULL && fingerCount > 1) {\n\n\n\t\tvector<float> distances(4, 0.0);\n\n\t\t// For all combinations of finger configurations\n\t\tfor (int i = 0; i < fingerCount; i++) {\n\t\t\tVertex tipPosition = tempHand->getFinger(i)->getStabilizedTipPosition();\n\n\t\t\tfor (int j= i+1 ;j < fingerCount; j++) {\n\n\t\t\t\tVertex tipPosition2 = tempHand->getFinger(j)->getStabilizedTipPosition();\n\t\t\t\tfloat dist = (tipPosition - tipPosition2).getMagnitude();\n\t\t\t\tdistances.push_back(dist);\n\t\t\t}\n\t\t}\n\n\t\tsort(distances.begin(), distances.end(), std::greater<float>());\n\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\taddAttribute(distances[i], attributeCounter, result);\n\t\t}\n\t}\n\t// There are no fingers in the captured data\n\telse\n\t{\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\taddAttribute(0.0, attributeCounter, result);\n\t\t}\n\t}\n}\n\nvoid distancesBetweenFingersPalmAttribute(GestureHand* tempHand, int& fingerCount,\n\t\tint& attributeCounter, vector<double>& result) {\n\n\t// If Hand exists and we have fingers\n\tif (tempHand != NULL && fingerCount > 1) {\n\n\t\tvector<float> distances(4, 0.0);\n\n\t\t// For all combinations of finger configurations\n\t\tfor (int i = 0; i < fingerCount; i++) {\n\t\t\tVertex fingerDirection = tempHand->getFinger(i)->getStabilizedTipPosition();\n\t\t\tVertex palmPosition = tempHand->getPalmPosition();\n\t\t\tdistances.push_back((fingerDirection - palmPosition).getMagnitude());\n\t\t}\n\n\t\tsort(distances.begin(), distances.end(), std::greater<float>());\n\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\taddAttribute(distances[i], attributeCounter, result);\n\t\t}\n\t}\n\t// There are no fingers in the captured data\n\telse {\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\taddAttribute(0.0, attributeCounter, result);\n\t\t}\n\t}\n}\n\nvoid handMovementAttribute(GestureHand* tempHand, GestureHand* tempHand2,\n\t\tint& attributeCounter, vector<double>& result) {\n\tif (tempHand == NULL || tempHand2 == NULL) {\n\t\taddAttribute(0.0, attributeCounter,\n\t\t\t\tresult);\n\t\taddAttribute(0.0, attributeCounter,\n\t\t\t\tresult);\n\t\taddAttribute(0.0, attributeCounter,\n\t\t\t\tresult);\n\t} else {\n\t\t//cout<< (tempHand == NULL) <<\" \" << (tempHand2 == NULL) <<endl;\n\t\tVertex palmPos = tempHand->getPalmPosition();\n\t\tVertex palmPos2 = tempHand2->getPalmPosition();\n\n\t\t//cout << palmPos2.getX() << \" \" << palmPos2.getY() << \" \"\n\t\t//\t\t<< palmPos2.getZ() << endl;\n\t\t//cout << palmPos.getX() << \" \" << palmPos.getY() << \" \" << palmPos.getZ()\n\t\t//\t\t<< endl;\n\n\t\taddAttribute(palmPos2.getX() - palmPos.getX(), attributeCounter,\n\t\t\t\tresult);\n\t\taddAttribute(palmPos2.getY() - palmPos.getY(), attributeCounter,\n\t\t\t\tresult);\n\t\taddAttribute(palmPos2.getZ() - palmPos.getZ(), attributeCounter,\n\t\t\t\tresult);\n\t}\n}\n\nvoid handMovement2Attribute(GestureHand* tempHand, GestureHand* tempHand2,\n\t\tint& attributeCounter, vector<double>& result) {\n\tif (tempHand == NULL || tempHand2 == NULL) {\n\t\taddAttribute(0.0, attributeCounter,\n\t\t\t\tresult);\n\t\taddAttribute(0.0, attributeCounter,\n\t\t\t\tresult);\n\t\taddAttribute(0.0, attributeCounter,\n\t\t\t\tresult);\n\t} else {\n\t\tVertex palmPos = tempHand->getPalmPosition();\n\t\tVertex palmPos2 = tempHand2->getPalmPosition();\n\n\t\t//cout << palmPos2.getX() << \" \" << palmPos2.getY() << \" \"\n\t\t//\t\t<< palmPos2.getZ() << endl;\n\t\t//cout << palmPos.getX() << \" \" << palmPos.getY() << \" \" << palmPos.getZ()\n\t\t//\t\t<< endl;\n\t\tVertex directionOfMovement(palmPos2.getX() - palmPos.getX(),\n\t\t\t\tpalmPos2.getY() - palmPos.getY(),\n\t\t\t\tpalmPos2.getZ() - palmPos.getZ());\n\n\t\tVertex normalPalm = tempHand->getPalmNormal();\n\t\tVertex directionPalm = tempHand->getDirection();\n\t\tVertex movementNormalized = directionOfMovement.getNormalized();\n\n\t\taddAttribute(directionOfMovement.getMagnitude(), attributeCounter,\n\t\t\t\tresult);\n\t\taddAttribute(abs(normalPalm.dotProduct(movementNormalized)), attributeCounter,\n\t\t\t\tresult);\n\t\taddAttribute(abs(directionPalm.dotProduct(movementNormalized)), attributeCounter,\n\t\t\t\tresult);\n\t}\n}\n\nvoid handSpeedsAttribute(GestureHand* tempHand, GestureHand* tempHand2,\n\t\tint& attributeCounter, vector<double>& result) {\n\tif (tempHand == NULL || tempHand2 == NULL) {\n\t\taddAttribute(0.0, attributeCounter,\n\t\t\t\tresult);\n\t\taddAttribute(0.0, attributeCounter,\n\t\t\t\tresult);\n\t\taddAttribute(0.0, attributeCounter,\n\t\t\t\tresult);\n\t\taddAttribute(0.0, attributeCounter, result);\n\t} else {\n\t\tint fingerCount = tempHand->getFingerCount();\n\t\tint fingerCount2 = tempHand2->getFingerCount();\n\n\t\tvector<float> speeds(4,0.0);\n\t\tfor (int i=0;i< min(fingerCount, fingerCount2); i++)\n\t\t{\n\t\t\tVertex tipPosition = tempHand->getFinger(i)->getStabilizedTipPosition();\n\t\t\tVertex tipPosition2 = tempHand2->getFinger(i)->getStabilizedTipPosition();\n\t\t\tspeeds[i] = (tipPosition2 - tipPosition).getMagnitude();\n\t\t}\n\t\tsort(speeds.begin(), speeds.end(), std::greater<float>());\n\n\t\tfor (int i=0;i<4;i++)\n\t\t\taddAttribute(speeds[i], attributeCounter,\n\t\t\t\tresult);\n\t}\n}\n\n\n// Computes the feature set\nvector<double> computeFeatureSet(GestureFrame *gestureFrame, GestureFrame *gestureFrame2) {\n\tvector<double> result;\n\n\t// Get the numbe of fingers\n\tGestureHand *tempHand = gestureFrame->getHand(0);\n\tGestureHand *tempHand2 = gestureFrame2->getHand(0);\n\tint fingerCount =\n\t\t\t(tempHand != NULL) ?\n\t\t\t\t\tmin(tempHand->getFingerCount(), MAX_FINGER_COUNT) : 0;\n\tint attributeCounter = 1;\n\n\t// Adding the finger count to the feature set\n\tfingerCountAttribute(fingerCount, attributeCounter, result);\n\n\tint fingerCount2 =\n\t\t\t\t(tempHand2 != NULL) ?\n\t\t\t\t\t\tmin(tempHand2->getFingerCount(), MAX_FINGER_COUNT) : 0;\n\n\t// Adding the finger count to the feature set\n\tfingerCountAttribute(fingerCount2, attributeCounter, result);\n\n\n\t// Adding 4 angles to the palm normal\n\tdistancesBetweenFingersPalmAttribute(tempHand2, fingerCount2, attributeCounter,\n\t\t\tresult);\n\n\t// Adding 4 angles to the palm normal\n\tanglesFingersPalmAttribute(tempHand2, fingerCount2, attributeCounter,\n\t\t\tresult);\n\n\t// Adding the 4 highest angles to the feature set\n\tanglesBetweenFingersAttribute(tempHand2, fingerCount2, attributeCounter,\n\t\t\tresult);\n\n\t// Adding the 4 greatest distances to the feature set\n\tdistancesBetweenFingersAttribute(tempHand2, fingerCount2, attributeCounter,\n\t\t\tresult);\n\t//distancesBetweenFingersAttribute(tempHand, fingerCount2, attributeCounter,\n\t//\t\t\tresult);\n\n\n\t// Hand movement\n\t//handMovementAttribute(tempHand, tempHand2, attributeCounter, result);\n\n\t//\n\thandMovement2Attribute(tempHand, tempHand2, attributeCounter, result);\n\n\t//handSpeedsAttribute(tempHand, tempHand2, attributeCounter, result);\n\n\treturn result;\n}\n\nvoid columnScaling(vector< vector<double > >& data ) {\n\n\tint trainSetSize = data.size();\n\tint featureSize = data[0].size();\n\tdouble ** scaling = new double*[2];\n\tscaling[0] = new double [ featureSize ];\n\tscaling[1] = new double [ featureSize ];\n\n\tfor (int j = 0; j < featureSize; j++) {\n\t\tdouble min_val = data[0][j], max_val = data[0][j];\n\t\tfor (int i = 0; i < trainSetSize; i++) {\n\t\t\tif (data[i][j] < min_val) {\n\t\t\t\tmin_val = data[i][j];\n\t\t\t}\n\t\t\tif (data[i][j] > max_val) {\n\t\t\t\tmax_val = data[i][j];\n\t\t\t}\n\t\t}\n\t\tscaling[0][j] = min_val;\n\t\tscaling[1][j] = max_val - min_val;\n\n\t\tif ( scaling[1][j] > 0.1)\n\t\t{\n\t\t\tfor (int i = 0; i < trainSetSize; i++) {\n\t\t\t\tdata[i][j] = (data[i][j] - scaling[0][j]) / (scaling[1][j]);\n\t\t\t}\n\t\t}\n\t\t}\n\tdelete [] scaling[0];\n\tdelete [] scaling[1];\n\tdelete [] scaling;\n}\n\nvoid readingInputData(string fileName, vector<GestureFrame> &frames) {\n\tGestureStorageDriver* gestureStorageDriver = new BinaryFileStorageDriver();\n\n\tgestureStorageDriver->openConnection(fileName, false);\n\n\tGestureFrame currGestureFrame;\n\twhile (gestureStorageDriver->loadGestureFrame(currGestureFrame)) {\n\t\tframes.push_back(currGestureFrame);\n\t\tcurrGestureFrame.clear();\n\t}\n\tgestureStorageDriver->closeConnection();\n\tdelete gestureStorageDriver;\n}\n\nvoid dataPreparation(int count, vector<GestureFrame> *frames,\n\t\tconst int preprocessingWidth,\n\t\tvector<vector<double> > *dataset) {\n\tfor (int i = 0; i < count; i++) {\n\t\tLMpre::LMpre pre(frames[i], preprocessingWidth);\n\t\tframes[i] = pre.process();\n\t\t//cout<<i<<\" \"<< frames[i].size() << \" \" \t;\n\t\tfor (int j = 0; j < frames[i].size(); j++) {\n\t\t\tvector<double> row;\n\t\t\tint k = (j - 10) >= 0 ? (j-10) : 0;\n\n\t\t\t//cout<<\"(\"<<i<<\", \"<<j<<\")\"<<endl;\n\t\t\trow = computeFeatureSet(&frames[i][j], &frames[i][k]);\n\t\t\tdataset[i].push_back(row);\n\t\t}\n\t\t// Data normalizaion in columns\n\t\t//if ( frames[i].size() != 0)\n\t\t\tcolumnScaling(dataset[i]);\n\n\t\tframes[i].clear();\n\t}\n}\n\n//void saveToEstimateNumbeOfClasses(vector<vector<double> > *dataset, int argc) {\n//\t// Saving for tool\n//\tofstream zapis(\"out.csv\");\n//\tfor (int i = 0; i < argc -1 ; i++) {\n//\t\tif (i == 0) {\n//\t\t\tfor (int j = 0; j < dataset[i].size(); j++) {\n//\t\t\t\tzapis << '\"' << j << '\"' << ';';\n//\t\t\t}\n//\t\t\tzapis << endl;\n//\t\t}\n//\t\tzapis << '\"' << i << '\"' << \";\";\n//\t\tfor (int j = 0; j < dataset[i].size(); j++) {\n//\t\t\tzapis << dataset[i][j] << \";\";\n//\t\t}\n//\t\tzapis << endl;\n//\t}\n//\tzapis.close();\n//\n//\tstd::fstream datasetFile;\n//\tdatasetFile.open(\"DATASET_FILE\", std::fstream::out | std::fstream::trunc);\n//\tfor (int i = 0; i < argc -1; i++) {\n//\t\tint lastElement = dataset[i].size() - 1;\n//\t\tfor (int j = 0; j < lastElement; j++) {\n//\t\t\tdatasetFile << dataset[i][j] << \" \";\n//\t\t}\n//\n//\t\tdatasetFile << dataset[i][lastElement] << \"\\n\";\n//\t}\n//\tdatasetFile.close();\n//}\n\nvoid readConfig(int &preprocessingWidth, int &crossValK, int &K, int &M,\n\t\tint &classNumber, int &readCentroids, double &learningRate,\n\t\tint &iteration_number, int &datasetSize)\n{\n\tifstream in;\n\tin.open(\"config.cfg\");\n\n\tstring tmp;\n\tstring val;\n\n\tgetline(in, tmp);\n\tgetline(in, val);\n\tpreprocessingWidth = atoi(val.c_str());\n\n\tgetline(in, tmp);\n\tgetline(in, val);\n\tcrossValK = atoi(val.c_str());\n\n\tgetline(in, tmp);\n\tgetline(in, val);\n\tK = atoi(val.c_str());\n\n\tgetline(in, tmp);\n\tgetline(in, val);\n\tclassNumber = atoi(val.c_str());\n\tM = classNumber;\n\n\tgetline(in, tmp);\n\tgetline(in, val);\n\treadCentroids = atoi(val.c_str());\n\n\tgetline(in, tmp);\n\tgetline(in, val);\n\tlearningRate = atof(val.c_str());\n\n\tgetline(in, tmp);\n\tgetline(in, val);\n\titeration_number = atoi(val.c_str());\n\n\tgetline(in, tmp);\n\tgetline(in, val);\n\tdatasetSize = atoi(val.c_str());\n\n\tin.close();\n}\n\nint main(int argc, char **argv) {\n\t// Parameters to play with\n\tint preprocessingWidth = 10;\n\tint crossValK = 5;\n\tint K = 10; // number of states in one gesture\n\tint M = 15;\n\tint classNumber = 15; // number of possible observations\n\tint readCentroids = 1; // 0 - calculate using k-means, 1 - read them from file\n\tdouble learningRate = 0.2; // How much do we incorporate new training data into trained model\n\tint iteration_number = 100; // How many learning iterations\n\tint datasetSize = 720;\n\n\t// Read parameters\n\treadConfig(preprocessingWidth, crossValK, K, M, classNumber, readCentroids,\n\t\t\tlearningRate, iteration_number, datasetSize);\n\n\t// Reading data in\n\tvector<GestureFrame> frames[1000];\n\tvector<int> label;\n\n\tfor (int k=0;k<6;k++)\n\t{\n\t\tfor (int i=0;i<4;i++)\n\t\t{\n\t\t\tstring base = \"dataset_new/\";\n\t\t\tif (i == 0)\n\t\t\t\tbase = base + \"kasia/\";\n\t\t\telse if (i == 1)\n\t\t\t\tbase = base + \"kuba/\";\n\t\t\telse if (i == 2)\n\t\t\t\tbase = base + \"michal/\";\n\t\t\telse\n\t\t\t\tbase = base + \"oli/\";\n\n//\t\t\tif ( k == 0)\n//\t\t\t\tbase = base + \"cyfra8/\";\n//\t\t\telse if (k == 1)\n//\t\t\t\tbase = base + \"kolko/\";\n//\t\t\telse if (k == 2)\n//\t\t\t\tbase = base + \"opadanieCalejReki/\";\n//\t\t\telse if (k == 3)\n//\t\t\t\tbase = base + \"pistolet/\";\n//\t\t\telse if (k == 4)\n//\t\t\t\tbase = base + \"swipeOdPrawej/\";\n//\t\t\telse\n//\t\t\t\tbase = base + \"czyszczenie/\";\n\t\t\tif (k == 0)\n\t\t\t\tbase = base + \"123/\";\n\t\t\telse if (k == 1)\n\t\t\t\tbase = base + \"drzwi/\";\n\t\t\telse if (k == 2)\n\t\t\t\tbase = base + \"kolko/\";\n\t\t\telse if (k == 3)\n\t\t\t\tbase = base + \"nozyce/\";\n\t\t\telse if (k == 4)\n\t\t\t\tbase = base + \"pistolet/\";\n\t\t\telse\n\t\t\t\tbase = base + \"przenoszenie/\";\n\t\t\tfor (int j=1;j<31;j++)\n\t\t\t{\n\t\t\t\tstring name = base;\n\t\t\t\tstringstream ss2;\n\t\t\t\tss2 << j;\n\t\t\t\tname = name + ss2.str() + \".lmr\";\n\t\t\t\t//cout<<name<<\" \" << k*120 + i*30 + j-1 << endl;\n\t\t\t\treadingInputData(name, frames[k*120 + i*30 + j-1 ]);\n\t\t\t\t//readingInputData(name, frames[k*30 + j-1 ]);\n\t\t\t\tlabel.push_back(k);\n\t\t\t}\n\n\t\t}\n\n\t}\n\tcout<<\"Ended loading data\" <<endl;\n\n\t// Preprocessing &&\n\t// Saving all possible gestures as feature sets &&\n\t// Scaling\n\tvector<vector<double> > dataset[1000];\n\tdataPreparation(datasetSize, frames, preprocessingWidth, dataset);\n\n\t// Saving for tool to estimate number of classes\n\t//saveToEstimateNumbeOfClasses(dataset, argc);\n\n\tcout << \" k-means \" << endl;\n\tvector< vector<double> > centroids;\n\tif ( readCentroids )\n\t\treadCentroidsFromFile(centroids);\n\telse\n\t\tkmeansSimple(dataset, datasetSize, centroids, classNumber);\n\n\t//cout<<endl<<\"!!!!!!! KMEANS !!!!!!\" << endl;\n\t//kmeans(dataset, 11);\n\t//cout<<endl<<\"!!!!!!! CHINESE WHISPERS !!!!!!\" << endl;\n\t///chinese_whispers(dataset);\n\t//cout<<endl<<\"!!!!!!! NEWMAN CLUSTERING !!!!!!\" << endl;\n\t//newman_cluster(dataset);\n\n\t// Seperating into train/test dataset\n\tstd::vector<sequence> trainDataset[6];\n\tstd::vector<sequence> testDataset;\n\n\t// Finding the longest sequence of observations\n\tint n = 0;\n\tfor (int p=0;p<datasetSize;p++)\n\t{\n\t\tn = max(n, (int)dataset[p].size());\n\t}\n\n\tcout <<\"Seperating data\"<<endl;\n\t// Determine the observation values for all sequences\n\tfor (int p=0;p<datasetSize;p++)\n\t{\n\t\tvector<unsigned int> observationLabels(n, 0.0);\n\t\tfor (int j=0; j <  n;j++)\n\t\t{\n\t\t\t// Fill the rest with the last label\n\t\t\tif ( j >= dataset[p].size() )\n\t\t\t{\n\t\t\t\tobservationLabels[j] = observationLabels[dataset[p].size() - 1];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Calculate the errors to the centroids\n\t\t\t\tdouble best_error = 0.0;\n\t\t\t\tint best_index = -2;\n\t\t\t\tfor (int i = 0; i < centroids.size(); i++) {\n\t\t\t\t\tdouble error = 0.0;\n\t\t\t\t\tfor (int k = 0; k < centroids[i].size(); k++) {\n\t\t\t\t\t\terror += (dataset[p][j][k] - centroids[i][k])\n\t\t\t\t\t\t\t\t* (dataset[p][j][k] - centroids[i][k]);\n\t\t\t\t\t}\n\t\t\t\t\tif (best_error > error || best_index < 0) {\n\t\t\t\t\t\tbest_error = error;\n\t\t\t\t\t\tbest_index = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tobservationLabels[j] = (best_index);\n\t\t\t}\n\t\t}\n\t\t// First 20 used for training\n\t\tif ( p % 30 < 20)\n\t\t\ttrainDataset[p/120].push_back(observationLabels);\n\t\t\t//trainDataset[p/30].push_back(observationLabels);\n\n\t\ttestDataset.push_back(observationLabels);\n\t}\n\tfor(int k=0;k<6;k++)\n\t\tcout<<\"Train: \" << trainDataset[k].size()<<endl;\n\tcout<<\"Test: \"<<testDataset.size()<< \" \" << datasetSize<<endl;\n\tcout<<\"HMM start\"<<endl;\n\n\t// HMM\n\tHMMClass *hmmGesture[6];\n\tHMMClass *bestHmmGesture[6];\n\tdouble bestRecognitionRate = 0;\n\tfor (int k=0;k<10;k++)\n\t{\n\t\tfor (int i=0;i<6;i++)\n\t\t{\n\t\t\tcout<<\"Iteration k=\" <<k<<\"\\tlearning model i=\" << i << \" on \" <<trainDataset[i].size()<< \" samples\";\n\t\t\thmmGesture[i] = new HMMClass(K, n, M);\n\t\t\thmmGesture[i]->train(trainDataset[i],crossValK, iteration_number, learningRate);\n\t\t\tcout<<\" --- Model learnt\" << endl;\n\t\t}\n\n\t\t//HMMClass *hmmGesture = new HMMClass(\"hmmFirstModel.model\");\n\n\t\tvector<int> predictedLabels[6];\n\t\tvector<int> trainLabels[6];\n\t\tfor (int p =0;p<6;p++)\n\t\t{\n\t\t\tfor (int i=0;i<trainDataset[p].size();i++)\n\t\t\t{\n\t\t\t\tdouble error;\n\t\t\t\tint index = -1;\n\t\t\t\tfor (int j=0;j<6;j++)\n\t\t\t\t{\n\t\t\t\t\tdouble loglik = hmmGesture[j]->predict(trainDataset[p][i]);\n\t\t\t\t\tif ( index == -1 || loglik > error)\n\t\t\t\t\t{\n\t\t\t\t\t\terror = loglik;\n\t\t\t\t\t\tindex = j;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpredictedLabels[p].push_back(index);\n\t\t\t\ttrainLabels[p].push_back(p);\n\t\t\t}\n\t\t}\n\n\t\tcout<<\"Counting percentage ...\"<<endl;\n\t\tint counter = 0;\n\t\tint trainSize = 0;\n\t\tfor (int j=0;j<6;j++)\n\t\t{\n\t\t\ttrainSize += trainDataset[j].size();\n\t\t\tfor (int i=0; i< trainDataset[j].size();i++)\n\t\t\t\tif ( predictedLabels[j][i] == trainLabels[j][i])\n\t\t\t\t\tcounter++;\n\t\t}\n\t\tcout<<\"Train recognition rate : \" << counter * 100.0 / trainSize << \" \" << counter <<\" \" << trainSize <<endl;\n\t\t// Evaluate best model\n\t\tvector<int> predicted;\n\t\tfor (int i = 0; i < datasetSize; i++) {\n\t\t\tdouble error;\n\t\t\tint index = -1;\n\t\t\tfor (int j = 0; j < 6; j++) {\n\t\t\t\tdouble loglik = hmmGesture[j]->predict(testDataset[i]);\n\t\t\t\tif (index == -1 || loglik > error) {\n\t\t\t\t\terror = loglik;\n\t\t\t\t\tindex = j;\n\t\t\t\t}\n\t\t\t}\n\t\t\tpredicted.push_back(index);\n\t\t}\n\n\t\tint count = 0;\n\t\tfor (int i = 0; i < datasetSize; i++) {\n//\t\t\tif (i % 30 < 20)\n//\t\t\t\tcout << predictedLabels[i / 30][i % 30] << \" \"\n//\t\t\t\t\t\t<< trainLabels[i / 30][i % 30] << \" \";\n//\t\t\telse\n//\t\t\t\tcout << \" -  - \";\n//\n//\t\t\tcout << predicted[i] << \" \" << label[i] << endl;\n//\n\t\t\tif (predicted[i] == label[i])\n\t\t\t\tcount++;\n\t\t}\n\t\tcout << \"On total recognition rate : \" << count * 100.0 / datasetSize\n\t\t\t\t<< endl;\n\n\n\t\tif ( counter * 100.0 / trainSize > bestRecognitionRate)\n\t\t{\n\t\t\tbestRecognitionRate = counter * 100.0 / trainSize;\n\t\t\tfor (int j=0;j<6;j++)\n\t\t\t{\n\t\t\t\tif (k!=0) delete bestHmmGesture[j];\n\t\t\t\tbestHmmGesture[j] = hmmGesture[j];\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tfor (int j=0;j<6;j++) delete hmmGesture[j];\n\t}\n\n\t// Evaluate best model\n\tvector<int> predictedLabels;\n\tfor (int i = 0; i < datasetSize; i++) {\n\t\tdouble error;\n\t\tint index = -1;\n\t\tfor (int j = 0; j < 6; j++) {\n\t\t\tdouble loglik = bestHmmGesture[j]->predict(testDataset[i]);\n\t\t\tif (index == -1 || loglik > error) {\n\t\t\t\terror = loglik;\n\t\t\t\tindex = j;\n\t\t\t}\n\t\t}\n\t\tpredictedLabels.push_back(index);\n\t}\n\n\tcout << \"Counting percentage ...\" << endl;\n\tint counter = 0;\n\tfor (int i = 0; i < datasetSize; i++)\n\t\tif (predictedLabels[i] == label[i])\n\t\t\tcounter++;\n\tcout<<\"Best total recognition rate : \" << counter * 100.0 / datasetSize << endl;\n\n\t//hmmGesture->show();\n\n\n\n\tfor (int j=0;j<6;j++)\n\t{\n\t\tstring name = \"hmmModel_\";\n\t\tstringstream ss2;\n\t\tss2 << (j+1);\n\t\tname = name + ss2.str() + \".model\";\n\t\tbestHmmGesture[j]->saveModel(name);\n\t\tdelete bestHmmGesture[j];\n\t}\n}\n", "meta": {"hexsha": "c46bb3a679195e9c83b15922a933e923462dc847", "size": 26511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DynamicGestures/dynamicGestureRecognition.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": "DynamicGestures/dynamicGestureRecognition.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": "DynamicGestures/dynamicGestureRecognition.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": 28.053968254, "max_line_length": 111, "alphanum_fraction": 0.6516917506, "num_tokens": 7802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5029863858974349}}
{"text": "#include <geometry.h>\n#include <tiny_math_types.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\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(raycast_plane)\n{\n\n  using std::sqrt;\n\n  typedef tiny::MathTypes<double>   MT;\n  typedef MT::vector3_type          V;\n  typedef MT::real_type             T;\n  typedef MT::value_traits          VT;\n\n\n  V                  const normal = V::make(1.0,1.0,1.0);\n  T                  const offset = norm( normal );\n  geometry::Plane<V> const plane  = geometry::make_plane( unit(normal), offset);\n\n  BOOST_CHECK(geometry::is_valid(plane));\n\n  // Orthogonal hit from back-side\n  {\n    V                const p   = V::make( 0.0, 0.0, 0.0);\n    V                const r   = V::make( 1.0, 1.0, 1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_plane(ray, plane, q, length);\n\n    BOOST_CHECK( hit );\n\n    BOOST_CHECK_CLOSE( length, offset, 0.01);\n    BOOST_CHECK_CLOSE( q(0),  1.0, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  1.0, 0.01);\n    BOOST_CHECK_CLOSE( q(2),  1.0, 0.01);\n  }\n\n  // Orthogonal hit from back-side with front-face only\n  {\n    V                const p   = V::make( 0.0, 0.0, 0.0);\n    V                const r   = V::make( 1.0, 1.0, 1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_plane(ray, plane, q, length, true);\n\n    BOOST_CHECK( !hit );\n  }\n\n  // Orthogonal hit from front-side but with ray origin on back-side\n  {\n    V                const p   = V::make( 0.0, 0.0, 0.0);\n    V                const r   = V::make( -1.0, -1.0, -1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_plane(ray, plane, q, length, true);\n\n    BOOST_CHECK( !hit );\n  }\n\n\n  // Parallel ray and plane\n  {\n    V                const p   = V::make( 0.0, 0.0, 0.0);\n    V                const r   = V::make( -1.0, 1.0, 0.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_plane(ray, plane, q, length);\n\n    BOOST_CHECK( !hit );\n  }\n\n  // Oblique hit\n  {\n    V                const p   = V::make( 2.0, 1.0, 1.0);\n    V                const r   = V::make( -1.0, 0.0, 0.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_plane(ray, plane, q, length);\n\n    BOOST_CHECK( hit );\n\n    BOOST_CHECK_CLOSE( length, 1.0, 0.01);\n    BOOST_CHECK_CLOSE( q(0),  1.0, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  1.0, 0.01);\n    BOOST_CHECK_CLOSE( q(2),  1.0, 0.01);\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "d39e8af32582294198c51bdcf04c132ef1e808c7", "size": 3078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_raycast_plane/geometry_raycast_plane.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_raycast_plane/geometry_raycast_plane.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_raycast_plane/geometry_raycast_plane.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2389380531, "max_line_length": 80, "alphanum_fraction": 0.5477582846, "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.5028865439183865}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2010 Liquidnet Holdings, Inc.\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#ifndef quantlib_test_autocovariances_hpp\n#define quantlib_test_autocovariances_hpp\n\n#include <boost/test/unit_test.hpp>\n\n/* remember to document new and/or updated tests in the Doxygen\n   comment block of the corresponding class */\n\nclass AutocovariancesTest {\n  public:\n    static void testConvolutions();\n    static void testAutoCovariances();\n    static void testAutoCorrelations();\n    static boost::unit_test_framework::test_suite* suite();\n};\n\n/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2010 Liquidnet Holdings, Inc.\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 \"utilities.hpp\"\n#include <ql/math/autocovariance.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\nusing namespace std;\n\nvoid AutocovariancesTest::testConvolutions() {\n    BOOST_TEST_MESSAGE(\"Testing convolutions...\");\n    Array x(10, 1, 1);\n    Array conv(6);\n    convolutions(x.begin(), x.end(), conv.begin(), 5);\n    Real expected[] = { 385, 330, 276, 224, 175, 130 };\n    Array delta = conv - Array(expected, expected+6);\n    if (DotProduct(delta, delta) > 1.0e-6)\n        BOOST_ERROR(\"Convolution: \\n\"\n                    << std::setprecision(4) << std::scientific\n                    << \"    calculated:   \" << conv << \"\\n\"\n                    << \"    expected:     \" << Array(expected, expected+6));\n}\n\nvoid AutocovariancesTest::testAutoCovariances() {\n    BOOST_TEST_MESSAGE(\"Testing auto-covariances...\");\n    Array x(10, 1, 1);\n    Array acovf(6);\n    Real mean = autocovariances(x.begin(), x.end(), acovf.begin(), 5, false);\n    Real expected[] = { 8.25, 6.416667, 4.25, 1.75, -1.08333, -4.25 };\n    if (std::fabs(mean-5.5) > 1.0e-6) {\n        BOOST_ERROR(\"Mean: \\n\"\n                    << \"    calculated:   \" << mean << \"\\n\"\n                    << \"    expected:     \" << 5.5);\n    }\n    Array delta = acovf - Array(expected, expected+6);\n    if (DotProduct(delta, delta) > 1.0e-6)\n        BOOST_ERROR(\"Autocovariances: \\n\"\n                    << std::setprecision(4) << std::scientific\n                    << \"    calculated:   \" << acovf << \"\\n\"\n                    << \"    expected:     \" << Array(expected, expected+6));\n}\n\nvoid AutocovariancesTest::testAutoCorrelations() {\n    BOOST_TEST_MESSAGE(\"Testing auto-correlations...\");\n    Array x(10, 1, 1);\n    Array acorf(6);\n    Real mean = autocorrelations(x.begin(), x.end(), acorf.begin(), 5, true);\n    Real expected[] = { 9.166667, 0.77777778, 0.51515152,\n                        0.21212121, -0.13131313, -0.51515152 };\n    if (std::fabs(mean-5.5) > 1.0e-6) {\n        BOOST_ERROR(\"Mean: \\n\"\n                    << \"    calculated:   \" << mean << \"\\n\"\n                    << \"    expected:     \" << 5.5);\n    }\n    Array delta = acorf - Array(expected, expected+6);\n    if (DotProduct(delta, delta) > 1.0e-6)\n        BOOST_ERROR(\"Autocovariances: \\n\"\n                    << std::setprecision(4) << std::scientific\n                    << \"    calculated:   \" << acorf << \"\\n\"\n                    << \"    expected:     \" << Array(expected, expected+6));\n    delta = x - Array(10, -4.5, 1);\n    if (DotProduct(delta, delta) > 1.0e-6)\n        BOOST_ERROR(\"Centering: \\n\"\n                    << std::setprecision(4) << std::scientific\n                    << \"    calculated:   \" << x << \"\\n\"\n                    << \"    expected:     \" << Array(10, -4.5, 1));\n}\n\ntest_suite* AutocovariancesTest::suite() {\n    test_suite* suite = BOOST_TEST_SUITE(\"auto-covariance tests\");\n    suite->add(QUANTLIB_TEST_CASE(&AutocovariancesTest::testConvolutions));\n    suite->add(QUANTLIB_TEST_CASE(&AutocovariancesTest::testAutoCovariances));\n    suite->add(QUANTLIB_TEST_CASE(&AutocovariancesTest::testAutoCorrelations));\n    return suite;\n}\n\n\n#endif", "meta": {"hexsha": "ecdda3e5cd035864e1036b7a59028c1be6922364", "size": 5209, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite/autocovariances.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": "test-suite/autocovariances.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": "test-suite/autocovariances.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": 40.0692307692, "max_line_length": 79, "alphanum_fraction": 0.6302553273, "num_tokens": 1399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5028865377222489}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2021,\n *  Max Planck Institute for Intelligent Systems (MPI-IS).\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 MPI-IS nor the names\n *     of its contributors may be used to endorse or promote products\n *     derived from this software without specific prior written\n *     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: Andreas Orthey */\n\n#include <ompl/base/spaces/special/KleinBottleStateSpace.h>\n#include <ompl/tools/config/MagicConstants.h>\n#include <cstring>\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n\nusing namespace boost::math::double_constants;  // pi\nusing namespace ompl::base;\n\nKleinBottleStateSampler::KleinBottleStateSampler(const StateSpace *space) : StateSampler(space)\n{\n}\n\nvoid KleinBottleStateSampler::sampleUniform(State *state)\n{\n    bool acceptedSampleFound = false;\n    while (!acceptedSampleFound)\n    {\n        const double u = rng_.uniformReal(0, pi);\n        const double v = rng_.uniformReal(-pi, pi);\n\n        // NOTE: The idea here is that to compute the norm of the gradient at each\n        // point of the surface (i.e. the gradient of the coordinate mapping from\n        //(u,v) to (x,y,z)). To get the norm, we divide by the maximum norm of the\n        // gradient over the whole surface. This gives a number between [0,1]. We\n        // then do rejection sampling, by choosing a random number in [0,1] and\n        // accept if the norm is larger than this random number. Surface elements\n        // with a high curvature will have a small norm and will therefore be\n        // penalized under this method (i.e. rejected more often).\n        // See also: https://mathematica.stackexchange.com/questions/148693/generating-random-points-on-a-kleins-bottle\n\n        // NOTE: Automatic differential via sympy script\n        const double cu = std::cos(u);\n        const double cv = std::cos(v);\n        const double su = std::sin(u);\n        const double sv = std::sin(v);\n        const double cu3 = std::pow(cu, 3);\n        const double cu5 = std::pow(cu, 5);\n        const double cu6 = std::pow(cu, 6);\n        const double cu7 = std::pow(cu, 7);\n        const double cu8 = std::pow(cu, 8);\n\n        const double su2 = std::pow(su, 2);\n        const double su3 = std::pow(su, 3);\n        const double su4 = std::pow(su, 4);\n        const double su5 = std::pow(su, 5);\n        const double su6 = std::pow(su, 6);\n        const double su7 = std::pow(su, 7);\n        const double su8 = std::pow(su, 8);\n\n        const double aprime = (64.0 * su8 - 128.0 * su6 + 60.0 * su4 + 0.4 * su * cv - (1.0 / 6.0) * cu * cv -\n                               0.5 * std::cos(3 * u) * cv);\n\n        const double a = (-aprime * cv + (2.0 / 3.0) * sv * sv * cu * std::cos(2.0 * u));\n\n        const double bprime =\n            ((26 + 2.0 / 3.0) * su7 * cv - 55.0 * su5 * cv - (37 + 1.0 / 3.0) * su3 * cu6 * cv + 28.0 * su3 * cv +\n             (10 + 2.0 / 3.0) * su * cu8 * cv - (10 + 2.0 / 3.0) * su * cu6 * cv - 4.0 * std::sin(2.0 * u) +\n             22.4 * cu7 * cv - 35.2 * cu5 * cv + 12.2 * cu3 * cv + 0.6 * cu * cv);\n\n        const double cprime = ((5 + 1.0 / 3.0) * su5 * cu + 3.2 * su4 - (10 + 2.0 / 3.0) * su3 * cu - 6.4 * su2 +\n                               2.5 * std::sin(2 * u) + 3.0);\n\n        const double b = (((1.0 / 3.0) * std::sin(2.0 * u) + 0.4) * bprime * cu - cprime * aprime * su3);\n\n        const double c = ((5.0 / 6.0) * std::sin(2.0 * u) + 1);\n\n        const double d = (-((1.0 / 3.0) * std::sin(2.0 * u) + 0.4) * bprime * cv +\n                          (2.0 / 3.0) * cprime * su3 * sv * sv * std::cos(2.0 * u));\n\n        double s = std::sqrt(a * a * (0.16 * c * c) + b * b * sv * sv + d * d);\n\n        if (s > gMax_)\n        {\n            OMPL_ERROR(\"Norm of gradient (%.10f) larger than maximum norm (%.10f).\", s, gMax_);\n            throw \"Wrong norm error.\";\n        }\n        s = s / gMax_;\n\n        const double mu = rng_.uniformReal(0, 1);\n        if (mu <= s)\n        {\n            auto *K = state->as<KleinBottleStateSpace::StateType>();\n            K->setUV(u, v);\n            acceptedSampleFound = true;\n        }\n    }\n}\n\nvoid KleinBottleStateSampler::sampleUniformNear(State *state, const State *near, double distance)\n{\n    auto *K = state->as<KleinBottleStateSpace::StateType>();\n    const auto *Knear = near->as<KleinBottleStateSpace::StateType>();\n    K->setU(rng_.uniformReal(Knear->getU() - distance, Knear->getU() + distance));\n    K->setV(rng_.uniformReal(Knear->getV() - distance, Knear->getV() + distance));\n    space_->enforceBounds(state);\n}\n\nvoid KleinBottleStateSampler::sampleGaussian(State *state, const State *mean, double stdDev)\n{\n    auto *K = state->as<KleinBottleStateSpace::StateType>();\n    const auto *Kmean = mean->as<KleinBottleStateSpace::StateType>();\n    K->setU(rng_.gaussian(Kmean->getU(), stdDev));\n    K->setV(rng_.gaussian(Kmean->getV(), stdDev));\n\n    space_->enforceBounds(state);\n}\n\nKleinBottleStateSpace::KleinBottleStateSpace()\n{\n    setName(\"KleinBottle\" + getName());\n    type_ = STATE_SPACE_KLEIN_BOTTLE;\n\n    // We model the Klein bottle as a regular cylinder, but where both ends are\n    // glued inversely together. For more information, check out the\n    // wikipedia article: https://en.wikipedia.org/wiki/Klein_bottle.\n    // Both interpolation and distance computation have to take\n    // the gluing into account when crossing over the boundary.\n    // ------<-------\n    // |            |\n    // |            |\n    // v            v u-dimension (0 to pi)\n    // |            |\n    // |            |\n    // ------>-------\n    //  v-dimension (0 to 2*pi)\n    //\n    //  Gluing:\n    // u=pi+0.001:  0 ----------- -pi pi ---------- 0\n    // u=0       :  -pi ----------- 0 0 ---------- pi\n\n    StateSpacePtr R1(std::make_shared<RealVectorStateSpace>(1));\n    R1->as<RealVectorStateSpace>()->setBounds(0, pi);\n\n    StateSpacePtr SO2(std::make_shared<SO2StateSpace>());\n\n    addSubspace(R1, 1.0);\n    addSubspace(SO2, 1.0);\n\n    lock();\n}\n\nStateSamplerPtr KleinBottleStateSpace::allocDefaultStateSampler() const\n{\n    return std::make_shared<KleinBottleStateSampler>(this);\n}\n\ndouble KleinBottleStateSpace::distance(const State *state1, const State *state2) const\n{\n    const double u1 = state1->as<KleinBottleStateSpace::StateType>()->getU();\n    const double u2 = state2->as<KleinBottleStateSpace::StateType>()->getU();\n\n    const double diffU = u2 - u1;\n\n    if (std::abs(diffU) <= 0.5 * pi)\n    {\n        return CompoundStateSpace::distance(state1, state2);\n    }\n    else\n    {\n        const double d_u = pi - std::abs(diffU);\n\n        const double v1 = state1->as<KleinBottleStateSpace::StateType>()->getV();\n        double v2 = state2->as<KleinBottleStateSpace::StateType>()->getV();\n\n        // reverse v2 (valid for both directions)\n        v2 = (v2 > 0.0 ? pi - v2 : -pi - v2);\n\n        double d_v = std::abs(v2 - v1);\n        d_v = (d_v > pi) ? 2.0 * pi - d_v : d_v;\n\n        double dist = d_u + d_v;\n\n        return dist;\n    }\n}\n\nvoid KleinBottleStateSpace::interpolate(const State *from, const State *to, double t, State *state) const\n{\n    const double u1 = from->as<KleinBottleStateSpace::StateType>()->getU();\n    const double u2 = to->as<KleinBottleStateSpace::StateType>()->getU();\n\n    double diffU = u2 - u1;\n\n    if (std::abs(diffU) <= 0.5 * pi)\n    {\n        // interpolate as if it would be a cylinder\n        CompoundStateSpace::interpolate(from, to, t, state);\n    }\n    else\n    {\n        // Interpolate along u-dimension\n        if (diffU > 0.0)\n        {\n            diffU = pi - diffU;\n        }\n        else\n        {\n            diffU = -pi - diffU;\n        }\n\n        double u = u1 - diffU * t;\n\n        bool crossed = false;\n        if (u > pi)\n        {\n            u -= pi;\n            crossed = true;\n        }\n        else if (u < 0.0)\n        {\n            u += pi;\n            crossed = true;\n        }\n\n        state->as<KleinBottleStateSpace::StateType>()->setU(u);\n\n        double v1 = from->as<KleinBottleStateSpace::StateType>()->getV();\n        double v2 = to->as<KleinBottleStateSpace::StateType>()->getV();\n\n        // If we crossed the gluing, we need to invert the \"from\"-state, otherwise\n        // we need to invert the \"to\"-state (similar to default SO2 interpolation)\n        if (crossed)\n        {\n            v1 = (v1 > 0.0 ? pi - v1 : -pi - v1);\n        }\n        else\n        {\n            v2 = (v2 > 0.0 ? pi - v2 : -pi - v2);\n        }\n\n        double diffV = v2 - v1;\n        double v = 0;\n\n        if (std::abs(diffV) <= pi)\n        {\n            v = v1 + diffV * t;\n        }\n        else\n        {\n            if (diffV > 0.0)\n                diffV = 2.0 * pi - diffV;\n            else\n                diffV = -2.0 * pi - diffV;\n            v = v1 - diffV * t;\n\n            if (v > pi)\n                v -= 2.0 * pi;\n            else if (v < -pi)\n                v += 2.0 * pi;\n        }\n\n        state->as<KleinBottleStateSpace::StateType>()->setV(v);\n    }\n}\n\nState *KleinBottleStateSpace::allocState() const\n{\n    auto *state = new StateType();\n    allocStateComponents(state);\n    return state;\n}\n\nEigen::Vector3f KleinBottleStateSpace::toVector(const State *state) const\n{\n    // Formula from https://en.wikipedia.org/wiki/Klein_bottle#Bottle_shape\n    const auto *s = state->as<KleinBottleStateSpace::StateType>();\n    const float u = s->getU();\n    const float v = s->getV() + pi;  // NOTE: SO2 state space has bounds [-pi, +pi]\n\n    assert(u >= 0.0);\n    assert(u <= pi);\n    assert(v >= 0.0);\n    assert(v <= 2 * pi);\n\n    double cu = std::cos(u);\n    double cv = std::cos(v);\n    double su = std::sin(u);\n    double sv = std::sin(v);\n    double cu2 = std::pow(cu, 2);\n    double cu3 = std::pow(cu, 3);\n    double cu4 = std::pow(cu, 4);\n    double cu5 = std::pow(cu, 5);\n    double cu6 = std::pow(cu, 6);\n    double cu7 = std::pow(cu, 7);\n\n    double a = 3 * cv - 30 * su + 90 * cu4 * su - 60 * cu6 * su + 5 * cu * cv * su;\n\n    Eigen::Vector3f q;\n    q[0] = -2.0 / 15.0 * cu * a;\n\n    double b = 3 * cv - 3 * cu2 * cv - 48 * cu4 * cv + 48 * cu6 * cv - 60 * su + 5 * cu * cv * su - 5 * cu3 * cv * su -\n               80 * cu5 * cv * su + 80 * cu7 * cv * su;\n\n    q[1] = -1.0 / 15.0 * su * b;\n\n    q[2] = 2.0 / 15.0 * (3 + 5 * cu * su) * sv;\n\n    return q;\n}\n", "meta": {"hexsha": "5c70f47d38b9f7d7785302d3da1db2ac78c82476", "size": 11778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/base/spaces/special/src/KleinBottleStateSpace.cpp", "max_stars_repo_name": "kopernikusauto/ompl", "max_stars_repo_head_hexsha": "528f02cdc5ac785ba24e1dbdf1cf621a17020b7b", "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/spaces/special/src/KleinBottleStateSpace.cpp", "max_issues_repo_name": "kopernikusauto/ompl", "max_issues_repo_head_hexsha": "528f02cdc5ac785ba24e1dbdf1cf621a17020b7b", "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/spaces/special/src/KleinBottleStateSpace.cpp", "max_forks_repo_name": "kopernikusauto/ompl", "max_forks_repo_head_hexsha": "528f02cdc5ac785ba24e1dbdf1cf621a17020b7b", "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.7433628319, "max_line_length": 119, "alphanum_fraction": 0.5638478519, "num_tokens": 3472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5028865324152979}}
{"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_MLOGTWO2NMB_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_MLOGTWO2NMB_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    Generates constant Mlogtwo2nmb.\n\n    @par Semantic:\n\n    @code\n    T r = Mlogtwo2nmb<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n      r =  -log(exp2(T(Nbmantissabits<T>())));\n    @endcode\n\n\n**/\n  template<typename T> T Mlogtwo2nmb();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Generates constant Mlogtwo2nmb.\n\n      Generate the  constant mlogtwo2nmb.\n\n      @return The Mlogtwo2nmb constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::mlogtwo2nmb_> mlogtwo2nmb = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/mlogtwo2nmb.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": "33e95325fc39a0de34019880225edd6edd379952", "size": 1357, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/mlogtwo2nmb.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/mlogtwo2nmb.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/mlogtwo2nmb.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": 22.2459016393, "max_line_length": 100, "alphanum_fraction": 0.6005895357, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5028865324152978}}
{"text": "//\n// \tCopyright (c) 2020, Amit Singh, amitsingh19975@gmail.com\n// \tCopyright (c) 2021, Cem Bassoy, cem.bassoy@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n\n#include <boost/numeric/ublas/tensor/tensor.hpp>\n#include <boost/numeric/ublas/tensor/extents.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"utility.hpp\"\n\n#include <cstdlib>\n#include <functional>\n#include <tuple>\n\nBOOST_AUTO_TEST_SUITE(test_tensor_static_rank_expression)\n\nusing test_types = zip<int,float,std::complex<float>>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\n\n\n\nstruct fixture\n{\n  template<size_t N>\n  using extents_t = boost::numeric::ublas::extents<N>;\n\n  static constexpr auto extents =\n    std::make_tuple(\n//      extents_t<0>       {},\n      extents_t<2>    {1,1},\n      extents_t<2>    {1,2},\n      extents_t<2>    {2,1},\n      extents_t<2>    {2,3},\n      extents_t<3>  {2,3,1},\n      extents_t<3>  {4,1,3},\n      extents_t<3>  {1,2,3},\n      extents_t<3>  {4,2,3},\n      extents_t<4>{4,2,3,5} );\n};\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_static_rank_expression_retrieve_extents, value,  test_types, fixture)\n{\n  namespace ublas  = boost::numeric::ublas;\n  using value_t  = typename value::first_type;\n  using layout_t = typename value::second_type;\n\n  auto uplus1 = [](auto const& a){return a + value_t(1); };\n  auto uplus2 = [](auto const& a){return value_t(2) + a; };\n  auto bplus  = std::plus <value_t>{};\n  auto bminus = std::minus<value_t>{};\n\n  for_each_in_tuple(extents, [&](auto const& /*unused*/, auto const& e){\n\n\n\n    static constexpr auto size = std::tuple_size_v<std::decay_t<decltype(e)>>;\n    using tensor_t = ublas::tensor_static_rank<value_t, size, layout_t>;\n\n\n    auto t = tensor_t(e);\n    auto v = value_t{};\n    for(auto& tt: t){ tt = v; v+=value_t{1}; }\n\n\n    BOOST_CHECK( ublas::detail::retrieve_extents( t ) == e );\n\n    // uexpr1 = t+1\n    // uexpr2 = 2+t\n    auto uexpr1 = ublas::detail::make_unary_tensor_expression<tensor_t>( t, uplus1 );\n    auto uexpr2 = ublas::detail::make_unary_tensor_expression<tensor_t>( t, uplus2 );\n\n    BOOST_CHECK( ublas::detail::retrieve_extents( uexpr1 ) == e );\n    BOOST_CHECK( ublas::detail::retrieve_extents( uexpr2 ) == e );\n\n    // bexpr_uexpr = (t+1) + (2+t)\n    auto bexpr_uexpr = ublas::detail::make_binary_tensor_expression<tensor_t>( uexpr1, uexpr2, bplus );\n\n    BOOST_CHECK( ublas::detail::retrieve_extents( bexpr_uexpr ) == e );\n\n\n    // bexpr_bexpr_uexpr = ((t+1) + (2+t)) - t\n    auto bexpr_bexpr_uexpr = ublas::detail::make_binary_tensor_expression<tensor_t>( bexpr_uexpr, t, bminus );\n\n    BOOST_CHECK( ublas::detail::retrieve_extents( bexpr_bexpr_uexpr ) == e );\n\n  });\n\n  for_each_in_tuple(extents, [&](auto I, auto const& e1){\n\n\n    if ( I >= std::tuple_size_v<decltype(extents)> - 1 ){\n      return;\n    }\n\n    constexpr auto size1 = std::tuple_size_v<std::decay_t<decltype(e1)>>;\n    using tensor_type1 = ublas::tensor_static_rank<value_t, size1, layout_t>;\n\n    for_each_in_tuple(extents, [&,I](auto J, auto const& e2){\n\n      if( J != I + 1 ){\n        return;\n      }\n\n      static constexpr auto size1 = std::tuple_size_v<std::decay_t<decltype(e1)>>;\n      static constexpr auto size2 = std::tuple_size_v<std::decay_t<decltype(e2)>>;\n      using tensor_type2 = ublas::tensor_static_rank<value_t, size2, layout_t>;\n\n      auto v = value_t{};\n\n      tensor_type1 t1(e1);\n      for(auto& tt: t1){ tt = v; v+=value_t{1}; }\n\n      tensor_type2 t2(e2);\n      for(auto& tt: t2){ tt = v; v+=value_t{2}; }\n\n      BOOST_CHECK( ublas::detail::retrieve_extents( t1 ) != ublas::detail::retrieve_extents( t2 ) );\n\n      // uexpr1 = t1+1\n      // uexpr2 = 2+t2\n      auto uexpr1 = ublas::detail::make_unary_tensor_expression<tensor_type1>( t1, uplus1 );\n      auto uexpr2 = ublas::detail::make_unary_tensor_expression<tensor_type2>( t2, uplus2 );\n\n      BOOST_CHECK( ublas::detail::retrieve_extents( t1 )     == ublas::detail::retrieve_extents( uexpr1 ) );\n      BOOST_CHECK( ublas::detail::retrieve_extents( t2 )     == ublas::detail::retrieve_extents( uexpr2 ) );\n      BOOST_CHECK( ublas::detail::retrieve_extents( uexpr1 ) != ublas::detail::retrieve_extents( uexpr2 ) );\n\n      if constexpr( size1 == size2 ){\n        // bexpr_uexpr = (t1+1) + (2+t2)\n        auto bexpr_uexpr = ublas::detail::make_binary_tensor_expression<tensor_type1>( uexpr1, uexpr2, bplus );\n\n        BOOST_CHECK( ublas::detail::retrieve_extents( bexpr_uexpr ) == ublas::detail::retrieve_extents(t1) );\n\n\n        // bexpr_bexpr_uexpr = ((t1+1) + (2+t2)) - t2\n        auto bexpr_bexpr_uexpr1 = ublas::detail::make_binary_tensor_expression<tensor_type1>( bexpr_uexpr, t2, bminus );\n\n        BOOST_CHECK( ublas::detail::retrieve_extents( bexpr_bexpr_uexpr1 ) == ublas::detail::retrieve_extents(t2) );\n\n\n        // bexpr_bexpr_uexpr = t2 - ((t1+1) + (2+t2))\n        auto bexpr_bexpr_uexpr2 = ublas::detail::make_binary_tensor_expression<tensor_type1>( t2, bexpr_uexpr, bminus );\n\n        BOOST_CHECK( ublas::detail::retrieve_extents( bexpr_bexpr_uexpr2 ) == ublas::detail::retrieve_extents(t2) );\n      }\n\n    });\n  });\n}\n\n\n\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_static_rank_expression_all_extents_equal, value,  test_types, fixture)\n{\n  namespace ublas  = boost::numeric::ublas;\n  using value_t  = typename value::first_type;\n  using layout_t = typename value::second_type;\n\n  auto uplus1 = [](auto const& a){return a + value_t(1); };\n  auto uplus2 = [](auto const& a){return value_t(2) + a; };\n  auto bplus  = std::plus <value_t>{};\n  auto bminus = std::minus<value_t>{};\n\n  for_each_in_tuple(extents, [&](auto const& /*unused*/, auto& e){\n    static constexpr auto size = std::tuple_size_v<std::decay_t<decltype(e)>>;\n    using tensor_t = ublas::tensor_static_rank<value_t, size, layout_t>;\n\n\n    auto t = tensor_t(e);\n    auto v = value_t{};\n    for(auto& tt: t){ tt = v; v+=value_t{1}; }\n\n\n    BOOST_CHECK( ublas::detail::all_extents_equal( t , e ) );\n\n\n    // uexpr1 = t+1\n    // uexpr2 = 2+t\n    auto uexpr1 = ublas::detail::make_unary_tensor_expression<tensor_t>( t, uplus1 );\n    auto uexpr2 = ublas::detail::make_unary_tensor_expression<tensor_t>( t, uplus2 );\n\n    BOOST_CHECK( ublas::detail::all_extents_equal( uexpr1, e ) );\n    BOOST_CHECK( ublas::detail::all_extents_equal( uexpr2, e ) );\n\n    // bexpr_uexpr = (t+1) + (2+t)\n    auto bexpr_uexpr = ublas::detail::make_binary_tensor_expression<tensor_t>( uexpr1, uexpr2, bplus );\n\n    BOOST_CHECK( ublas::detail::all_extents_equal( bexpr_uexpr, e ) );\n\n\n    // bexpr_bexpr_uexpr = ((t+1) + (2+t)) - t\n    auto bexpr_bexpr_uexpr = ublas::detail::make_binary_tensor_expression<tensor_t>( bexpr_uexpr, t, bminus );\n\n    BOOST_CHECK( ublas::detail::all_extents_equal( bexpr_bexpr_uexpr , e ) );\n\n  });\n\n\n  for_each_in_tuple(extents, [&](auto I, auto& e1){\n\n    if ( I >= std::tuple_size_v<decltype(extents)> - 1){\n      return;\n    }\n\n    static constexpr auto size1 = std::tuple_size_v<std::decay_t<decltype(e1)>>;\n    using tensor_type1 = ublas::tensor_static_rank<value_t, size1, layout_t>;\n\n    for_each_in_tuple(extents, [&](auto J, auto& e2){\n\n      if( J != I + 1 ){\n        return;\n      }\n\n\n      static constexpr auto size2 = std::tuple_size_v<std::decay_t<decltype(e2)>>;\n      using tensor_type2 = ublas::tensor_static_rank<value_t, size2, layout_t>;\n\n      auto v = value_t{};\n\n      tensor_type1 t1(e1);\n      for(auto& tt: t1){ tt = v; v+=value_t{1}; }\n\n      tensor_type2 t2(e2);\n      for(auto& tt: t2){ tt = v; v+=value_t{2}; }\n\n      BOOST_CHECK( ublas::detail::all_extents_equal( t1, ublas::detail::retrieve_extents(t1) ) );\n      BOOST_CHECK( ublas::detail::all_extents_equal( t2, ublas::detail::retrieve_extents(t2) ) );\n\n      // uexpr1 = t1+1\n      // uexpr2 = 2+t2\n      auto uexpr1 = ublas::detail::make_unary_tensor_expression<tensor_type1>( t1, uplus1 );\n      auto uexpr2 = ublas::detail::make_unary_tensor_expression<tensor_type2>( t2, uplus2 );\n\n      BOOST_CHECK( ublas::detail::all_extents_equal( uexpr1, ublas::detail::retrieve_extents(uexpr1) ) );\n      BOOST_CHECK( ublas::detail::all_extents_equal( uexpr2, ublas::detail::retrieve_extents(uexpr2) ) );\n\n      if constexpr( size1 == size2 ){\n        // bexpr_uexpr = (t1+1) + (2+t2)\n        auto bexpr_uexpr = ublas::detail::make_binary_tensor_expression<tensor_type1>( uexpr1, uexpr2, bplus );\n\n        BOOST_CHECK( ! ublas::detail::all_extents_equal( bexpr_uexpr, ublas::detail::retrieve_extents( bexpr_uexpr  ) ) );\n\n        // bexpr_bexpr_uexpr = ((t1+1) + (2+t2)) - t2\n        auto bexpr_bexpr_uexpr1 = ublas::detail::make_binary_tensor_expression<tensor_type1>( bexpr_uexpr, t2, bminus );\n\n        BOOST_CHECK( ! ublas::detail::all_extents_equal( bexpr_bexpr_uexpr1, ublas::detail::retrieve_extents( bexpr_bexpr_uexpr1  ) ) );\n\n        // bexpr_bexpr_uexpr = t2 - ((t1+1) + (2+t2))\n        auto bexpr_bexpr_uexpr2 = ublas::detail::make_binary_tensor_expression<tensor_type1>( t2, bexpr_uexpr, bminus );\n\n        BOOST_CHECK( ! ublas::detail::all_extents_equal( bexpr_bexpr_uexpr2, ublas::detail::retrieve_extents( bexpr_bexpr_uexpr2  ) ) );\n\n\n        // bexpr_uexpr2 = (t1+1) + t2\n        auto bexpr_uexpr2 = ublas::detail::make_binary_tensor_expression<tensor_type1>( uexpr1, t2, bplus );\n        BOOST_CHECK( ! ublas::detail::all_extents_equal( bexpr_uexpr2, ublas::detail::retrieve_extents( bexpr_uexpr2  ) ) );\n\n\n        // bexpr_uexpr2 = ((t1+1) + t2) + t1\n        auto bexpr_bexpr_uexpr3 = ublas::detail::make_binary_tensor_expression<tensor_type1>( bexpr_uexpr2, t1, bplus );\n        BOOST_CHECK( ! ublas::detail::all_extents_equal( bexpr_bexpr_uexpr3, ublas::detail::retrieve_extents( bexpr_bexpr_uexpr3  ) ) );\n\n        // bexpr_uexpr2 = t1 + (((t1+1) + t2) + t1)\n        auto bexpr_bexpr_uexpr4 = ublas::detail::make_binary_tensor_expression<tensor_type1>( t1, bexpr_bexpr_uexpr3, bplus );\n        BOOST_CHECK( ! ublas::detail::all_extents_equal( bexpr_bexpr_uexpr4, ublas::detail::retrieve_extents( bexpr_bexpr_uexpr4  ) ) );\n      }\n\n    });\n  });\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a1e06885b1caa217c6bdc3fd352e41d113b0bc1b", "size": 10281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_fixed_rank_expression_evaluation.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_fixed_rank_expression_evaluation.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_fixed_rank_expression_evaluation.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 35.6979166667, "max_line_length": 149, "alphanum_fraction": 0.6669584671, "num_tokens": 3191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5028865324152978}}
{"text": "// Copyright (C) 2004 Jeremy Siek <jsiek@cs.indiana.edu>\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#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/transitive_closure.hpp>\n#include <iostream>\nusing namespace std;\n\nusing namespace boost;\ntypedef adjacency_list<> graph_t;\n\nint main(int argc, char *argv[]) {\n  graph_t g(5),g_TC;\n\n  add_edge(0,2,g);\n  add_edge(1,0,g);\n  add_edge(1,2,g);\n  add_edge(1,4,g);\n  add_edge(3,0,g);\n  add_edge(3,2,g);\n  add_edge(4,2,g);\n  add_edge(4,3,g);\n\n  transitive_closure(g,g_TC);\n\n  cout << \"original graph: 0->2, 1->0, 1->2, 1->4, 3->0, 3->2, 4->2, 4->3\"\n       << endl;\n  cout << \"transitive closure: \";\n  graph_t::edge_iterator i,iend;\n  for(boost::tie(i,iend) = edges(g_TC);i!=iend;++i) {\n    cout << source(*i,g_TC) << \"->\" << target(*i,g_TC) << \" \";\n  }\n  cout << endl;\n}\n", "meta": {"hexsha": "60da1d8683303a1514770f8a6b5f2e6b6cfda028", "size": 985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/graph/test/transitive_closure_test2.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/graph/test/transitive_closure_test2.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/graph/test/transitive_closure_test2.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": 26.6216216216, "max_line_length": 74, "alphanum_fraction": 0.6517766497, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5028865206158133}}
{"text": "#ifndef HBasisForSurrogateModelBaseClass\n#define HBasisForSurrogateModelBaseClass\n\n#include \"BlackBoxData.hpp\"\n#include <Eigen/Dense>\n#include <vector>\n#include <iostream>\n\n//! Base class for definiton of basis for surrogate models\n/*!\n Defines the required structure of basis for surrogate models to work with NOWPAC\n*/\nclass BasisForSurrogateModelBaseClass {\n  protected:\n    //! Number of arguments of surrogate model\n    int dim;\n    //! Number of basic basis functions\n    /*!  \n     Number of basis function, for example quadratic monomials, \n     for surrogate basis functions\n    */\n    int nb_basis_functions;\n    //! Coefficients of surrogate basis functions in terms of basic basis function\n    std::vector<Eigen::VectorXd> basis_coefficients;\n  public:\n    //! Constructor\n    /*! \n     Constructor to set number of arguments (dimension) of the basis\n     \\param n Number of arguments (dimension)\n    */\n    BasisForSurrogateModelBaseClass ( int n ) : dim ( n ) { };\n    //! Destructor\n    ~BasisForSurrogateModelBaseClass ( ) { };\n    //! Function to compute the basis coefficients for the basis functions\n    /*!\n     Function to compute the basis coefficients for the basis functions\n     \\param x vector vectors of nodes x[0], ..., x[n] contain the interpolation nodes\n    */\n    virtual void compute_basis_coefficients ( std::vector< std::vector<double> > const& ) = 0;\n    //! Function to evaluate the basis functions\n    /*!\n     Function to evaluate the basis functions. It returns a vector of basis values at\n     the point x.\n     \\param x point x at which the basis functions are evaluated\n     \\returns the values of all basis functions evaluated at point x\n    */\n    virtual std::vector<double> &evaluate ( std::vector<double> const& ) = 0;\n    //! Returns the value of a basis function at zero\n    /*!\n     Returns the value of basis function i at zero\n     \\param i number of basis function whose value is queried\n     \\returns the value of the basis function i at zero\n    */\n    virtual double &value ( int ) = 0;\n    //! Returns the gradient of a basis function zero\n    /*!\n     Returns the gradient of basis function i at zero\n     \\param i number of basis function whose gradient at zero is queried\n     \\returns the gradient of the basis function i at zero\n    */\n    virtual std::vector<double> &gradient ( int ) = 0;\n    //! Returns the Hessian matrix of a basis function zero\n    /*!\n     Returns the Hessian matrix of basis function i at zero\n     \\param i number of basis function whose Hessian matrix at zero is queried\n     \\returns the Hessian matrix of the basis function i at zero\n    */\n    virtual std::vector< std::vector<double> > &hessian ( int ) = 0;\n    //! Function to evaluate a basis function \n    /*!\n     Function to evaluate the i-th basis function. It returns the value of the i-th \n     basis function.\n     \\param x point x at which the i-th basis function are evaluated\n     \\param i number of basis function to be evaluated\n     \\returns the value of the i-th bais function at point x\n    */\n    virtual double evaluate ( std::vector<double> const&, int) = 0;\n    //! Function to query the dimension of the domain the basis functions \n    /*! \n     Function to query the dimension of the domain the basis functions\n     \\returns the dimension of the domain\n    */\n    int dimension ( ) { return dim; }\n};\n\n#endif\n", "meta": {"hexsha": "2eac8b782b00e8a1740534c39b8040a541ef229d", "size": 3376, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/BasisForSurrogateModelBaseClass.hpp", "max_stars_repo_name": "snowpac/snowpac", "max_stars_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-08-04T20:18:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T23:50:27.000Z", "max_issues_repo_path": "include/BasisForSurrogateModelBaseClass.hpp", "max_issues_repo_name": "snowpac/snowpac", "max_issues_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "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/BasisForSurrogateModelBaseClass.hpp", "max_forks_repo_name": "snowpac/snowpac", "max_forks_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "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.8045977011, "max_line_length": 94, "alphanum_fraction": 0.6901658768, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.50288650940912}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Peter Caspers\n Copyright (C) 2015 Roland Lichters\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 betaeta.hpp\n    \\brief Hagan / Woodward beta-eta model\n*/\n\n#ifndef quantlib_model_betaeta_hpp\n#define quantlib_model_betaeta_hpp\n\n#include <ql/experimental/models/betaetacore.hpp>\n#include <ql/models/model.hpp>\n#include <ql/indexes/iborindex.hpp>\n#include <ql/indexes/swapindex.hpp>\n#include <ql/instruments/vanillaswap.hpp>\n\n#include <boost/unordered_map.hpp>\n\nnamespace QuantLib {\n\n/*! cf. Hagan, Woodward: Markov interest rate models,\n    Applied Mathematical Finance 6, 233\u2013260 (1999)\n\n    We assume a reflecting barrier at x = -1/beta (cf.\n    the last paragraph on p. 241).\n\n    We assume a piecewise constant reversion \\kappa and\n    set \\lambda(t) := (1-exp(-\\kappa*t))/\\kappa\n    note that these are effective (integrated) rather\n    than forward-forward reversions though\n*/\n\n// TODO there is a big overlap with the Gaussian1d model interface\n// refactor this, i.e. create a common base class and build the\n// engines on top of this\n\nclass BetaEta : public TermStructureConsistentModel,\n                public CalibratedModel,\n                public LazyObject {\n  public:\n    // constant mean reversion\n    BetaEta(const Handle<YieldTermStructure> &termStructure,\n            const std::vector<Date> &volstepdates,\n            const std::vector<Real> &volatilities, const Real reversion,\n            const Real beta, const Real eta);\n    // piecewise mean reversion (with same step dates as volatilities)\n    BetaEta(const Handle<YieldTermStructure> &termStructure,\n            const std::vector<Date> &volstepdates,\n            const std::vector<Real> &volatilities,\n            const std::vector<Real> &reversions, const Real beta,\n            const Real eta);\n    // constant mean reversion with floating model data\n    BetaEta(const Handle<YieldTermStructure> &termStructure,\n            const std::vector<Date> &volstepdates,\n            const std::vector<Handle<Quote> > &volatilities,\n            const Handle<Quote> reversion, const Handle<Quote> beta,\n            const Handle<Quote> eta);\n    // piecewise mean reversion with floating model data\n    BetaEta(const Handle<YieldTermStructure> &termStructure,\n            const std::vector<Date> &volstepdates,\n            const std::vector<Handle<Quote> > &volatilities,\n            const std::vector<Handle<Quote> > &reversions,\n            const Handle<Quote> beta, const Handle<Quote> eta);\n\n    const Real numeraire(const Time t, const Real x = 0.0,\n                         const Handle<YieldTermStructure> &yts =\n                             Handle<YieldTermStructure>()) const;\n\n    const Real zerobond(const Time T, const Time t = 0.0, const Real x = 0.0,\n                        const Handle<YieldTermStructure> &yts =\n                            Handle<YieldTermStructure>()) const;\n\n    const Real numeraire(const Date &referenceDate, const Real y = 0.0,\n                         const Handle<YieldTermStructure> &yts =\n                             Handle<YieldTermStructure>()) const;\n    const Real zerobond(const Date &maturity,\n                        const Date &referenceDate = Null<Date>(),\n                        const Real x = 0.0,\n                        const Handle<YieldTermStructure> &yts =\n                            Handle<YieldTermStructure>()) const;\n\n    const Real forwardRate(const Date &fixing,\n                           const Date &referenceDate = Null<Date>(),\n                           const Real x = 0.0,\n                           boost::shared_ptr<IborIndex> iborIdx =\n                               boost::shared_ptr<IborIndex>()) const;\n\n    const Real swapRate(const Date &fixing, const Period &tenor,\n                        const Date &referenceDate = Null<Date>(),\n                        const Real x = 0.0,\n                        boost::shared_ptr<SwapIndex> swapIdx =\n                            boost::shared_ptr<SwapIndex>()) const;\n\n    const Real swapAnnuity(const Date &fixing, const Period &tenor,\n                           const Date &referenceDate = Null<Date>(),\n                           const Real x = 0.0,\n                           boost::shared_ptr<SwapIndex> swapIdx =\n                               boost::shared_ptr<SwapIndex>()) const;\n\n    const Array &reversion() const { return reversion_.params(); }\n    const Array &volatility() const { return sigma_.params(); }\n    const Real beta() const { return pBeta_.params()[0]; }\n    const Real eta() const { return pEta_.params()[0]; }\n\n    /*! Generates a grid of values for the state variable $x$\n       at time $T$ conditional on $x(t)=x$, covering stdDevs\n       standard deviations assuming an approximate variance\n       $\\int_t^T \\alpha^2$ for $x$. The grid consists of\n       2*gridPoints+1 points */\n    const Disposable<Array> xGrid(const Real stdDevs, const int gridPoints,\n                                  const Real T = 1.0, const Real t = 0,\n                                  const Real x = 0) const;\n\n    /*! integrates f against the conditional density $x(t)|x(t0)=x0$\n        covering stdDevs approximate standard deviations in the same\n        sense as in the xGrid implementation */\n    const Real integrate(const Real stdDevs,\n                         const boost::function<Real(Real)> &f, const Real t0,\n                         const Real x0, const Real t) const;\n\n    /*! for testing purposes we can switch off the usage of tabulated values */\n    const void useTabulation(const bool useTabulation) {\n        if (useTabulation_ != useTabulation) {\n            useTabulation_ = useTabulation;\n            update();\n        }\n    }\n\n    // calibration constraints\n    // TODO what is of practical use here ?\n\n    Disposable<std::vector<bool> > MoveVolatility(Size i) {\n        QL_REQUIRE(i < volatilities_.size(),\n                   \"volatility with index \" << i << \" does not exist (0...\"\n                                            << volatilities_.size() - 1 << \")\");\n        std::vector<bool> res(reversions_.size() + volatilities_.size() + 2,\n                              true);\n        res[reversions_.size() + i] = false;\n        return res;\n    }\n\n    // With fixed reversion, beta and eta calibrate the volatilities\n    // one by one to the given helpers. The same comments as in the\n    // corresonding method in Gsr hold.\n    void calibrateVolatilitiesIterative(\n        const std::vector<boost::shared_ptr<CalibrationHelper> > &helpers,\n        OptimizationMethod &method, const EndCriteria &endCriteria,\n        const Constraint &constraint = Constraint(),\n        const std::vector<Real> &weights = std::vector<Real>()) {\n\n        for (Size i = 0; i < helpers.size(); i++) {\n            std::vector<boost::shared_ptr<CalibrationHelper> > h(1, helpers[i]);\n            calibrate(h, method, endCriteria, constraint, weights,\n                      MoveVolatility(i));\n        }\n    }\n\n  private:\n    void generateArguments() { notifyObservers(); }\n\n    // see Gaussian1dModel\n\n    struct CachedSwapKey {\n        const boost::shared_ptr<SwapIndex> index;\n        const Date fixing;\n        const Period tenor;\n        const bool operator==(const CachedSwapKey &o) const {\n            return index->name() == o.index->name() && fixing == o.fixing &&\n                   tenor == o.tenor;\n        }\n    };\n\n    struct CachedSwapKeyHasher\n        : std::unary_function<CachedSwapKey, std::size_t> {\n        std::size_t operator()(CachedSwapKey const &x) const {\n            std::size_t seed = 0;\n            boost::hash_combine(seed, x.index->name());\n            boost::hash_combine(seed, x.fixing.serialNumber());\n            boost::hash_combine(seed, x.tenor.length());\n            boost::hash_combine(seed, x.tenor.units());\n            return seed;\n        }\n    };\n\n    typedef boost::unordered_map<CachedSwapKey, boost::shared_ptr<VanillaSwap>,\n                                 CachedSwapKeyHasher> CacheType;\n\n    mutable CacheType swapCache_;\n\n    // retrieve underlying swap from cache if possible, otherwise\n    // create it and store it in the cache\n    boost::shared_ptr<VanillaSwap>\n    underlyingSwap(const boost::shared_ptr<SwapIndex> &index,\n                   const Date &expiry, const Period &tenor) const {\n\n        CachedSwapKey k = {index, expiry, tenor};\n        CacheType::iterator i = swapCache_.find(k);\n        if (i == swapCache_.end()) {\n            boost::shared_ptr<VanillaSwap> underlying =\n                index->clone(tenor)->underlyingSwap(expiry);\n            swapCache_.insert(std::make_pair(k, underlying));\n            return underlying;\n        }\n        return i->second;\n    }\n\n    void update() { LazyObject::update(); }\n\n    void performCalculations() const {\n        evaluationDate_ = Settings::instance().evaluationDate();\n        enforcesTodaysHistoricFixings_ =\n            Settings::instance().enforcesTodaysHistoricFixings();\n        updateTimes();\n    }\n\n    void updateTimes() const;\n    void updateVolatility();\n    void updateReversion();\n    void updateBeta();\n    void updateEta();\n\n    void initialize();\n\n    Parameter &reversion_, &sigma_, &pBeta_, &pEta_;\n    std::vector<Handle<Quote> > volatilities_;\n    std::vector<Handle<Quote> > reversions_;\n    Handle<Quote> beta_;\n    Handle<Quote> eta_;\n    mutable Real betaLink_, etaLink_; // redundant, just used as a link to\n                                      // the core computation class\n\n    std::vector<Date> volstepdates_; // these are shared between volatilities\n                                     // and reversions in case of piecewise\n                                     // reversions\n    mutable std::vector<Time> volsteptimes_;\n    mutable Array volsteptimesArray_; // redundant, just used as a link to\n                                      // the core computation class\n\n    mutable Date evaluationDate_;\n    mutable bool enforcesTodaysHistoricFixings_;\n\n    boost::shared_ptr<BetaEtaCore> core_;\n    boost::shared_ptr<Integrator> integrator_, integrator2_;\n\n    class integrand {\n      public:\n        integrand(const Real t0, const Real x0, const Real t,\n                  const boost::function<Real(Real)> &f, const BetaEtaCore &core)\n            : t0_(t0), x0_(x0), t_(t), f_(f), core_(core) {}\n        Real operator()(Real x) const {\n            return f_(x) * core_.p(t0_, x0_, t_, x);\n        }\n\n      private:\n        const Real t0_, x0_, t_;\n        const boost::function<Real(Real)> &f_;\n        const BetaEtaCore &core_;\n    };\n    friend class integrand;\n\n    bool useTabulation_; // for testing, normally it should be true\n\n    struct VolatilityObserver : public Observer {\n        VolatilityObserver(BetaEta *p) : p_(p) {}\n        void update() { p_->updateVolatility(); }\n        BetaEta *p_;\n    };\n    struct ReversionObserver : public Observer {\n        ReversionObserver(BetaEta *p) : p_(p) {}\n        void update() { p_->updateReversion(); }\n        BetaEta *p_;\n    };\n    struct BetaObserver : public Observer {\n        BetaObserver(BetaEta *p) : p_(p) {}\n        void update() { p_->updateBeta(); }\n        BetaEta *p_;\n    };\n    struct EtaObserver : public Observer {\n        EtaObserver(BetaEta *p) : p_(p) {}\n        void update() { p_->updateEta(); }\n        BetaEta *p_;\n    };\n\n    boost::shared_ptr<VolatilityObserver> volatilityObserver_;\n    boost::shared_ptr<ReversionObserver> reversionObserver_;\n    boost::shared_ptr<BetaObserver> betaObserver_;\n    boost::shared_ptr<EtaObserver> etaObserver_;\n};\n\n// implementation\n\ninline const Real\nBetaEta::numeraire(const Date &referenceDate, const Real x,\n                   const Handle<YieldTermStructure> &yts) const {\n\n    return numeraire(termStructure()->timeFromReference(referenceDate), x, yts);\n}\n\ninline const Real\nBetaEta::zerobond(const Date &maturity, const Date &referenceDate, const Real x,\n                  const Handle<YieldTermStructure> &yts) const {\n\n    return zerobond(termStructure()->timeFromReference(maturity),\n                    referenceDate != Null<Date>()\n                        ? termStructure()->timeFromReference(referenceDate)\n                        : 0.0,\n                    x, yts);\n}\n\ninline const Real BetaEta::integrate(const Real stdDevs,\n                                     const boost::function<Real(Real)> &f,\n                                     const Real t0, const Real x0,\n                                     const Real t) const {\n    Real s = std::sqrt(core_->tau(t0, t));\n    integrand phi(t0, x0, t, f, *core_);\n    Real result;\n    // left integration bound should be greater or equal to barrier\n    Real a = std::max(x0 - stdDevs * s, -1.0 / beta_->value());\n    Real b = x0 + stdDevs * s;\n    try {\n        result = (*integrator_)(phi, a, b);\n    } catch (QuantLib::Error) {\n        result = (*integrator2_)(phi, a, b);\n    }\n\n    // singular term\n\n    result +=\n        core_->prob_y_0(t0, x0, t, useTabulation_) * f(-1.0 / beta_->value());\n    return result;\n}\n\n} // namespace QuantLib\n\n#endif\n", "meta": {"hexsha": "f5a5fb272bef21b7c75d2d0c0ce5e231a3f0dbe7", "size": 13722, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/betaeta.hpp", "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": "ql/experimental/models/betaeta.hpp", "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": "ql/experimental/models/betaeta.hpp", "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": 38.8725212465, "max_line_length": 80, "alphanum_fraction": 0.6058883545, "num_tokens": 3194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5028801422226615}}
{"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 <cstdint>\n#include <cinttypes>\n#include <boost/math/ccmath/div.hpp>\n#include <boost/math/tools/is_constant_evaluated.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\ntemplate <typename Z>\nconstexpr void test()\n{\n    constexpr auto test_val1 = boost::math::ccmath::div(Z(1), Z(1));\n    static_assert(test_val1.quot == Z(1));\n    static_assert(test_val1.rem == Z(0));\n\n    constexpr auto test_val2 = boost::math::ccmath::div(Z(1'000'000), Z(3));\n    static_assert(test_val2.quot == Z(333'333));\n    static_assert(test_val2.rem == Z(1));\n}\n\n#if !defined(BOOST_MATH_NO_CONSTEXPR_DETECTION) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\nint main()\n{\n    test<int>();\n    test<long>();\n    test<long long>();\n    test<std::intmax_t>();\n\n    test<std::int32_t>();\n    test<std::int64_t>();\n    test<std::uint32_t>();\n\n    test<boost::multiprecision::int128_t>();\n    test<boost::multiprecision::int256_t>();\n    test<boost::multiprecision::int512_t>();\n\n    return 0;\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "b3319f43a4b4cb27f8cccad7155148610ee56239", "size": 1247, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ccmath_div_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/ccmath_div_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/ccmath_div_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": 25.9791666667, "max_line_length": 96, "alphanum_fraction": 0.6816359262, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5028801367546407}}
{"text": "//\n// Copyright (c) 2015-2018 CNRS\n//\n\n#include \"pinocchio/spatial/fwd.hpp\"\n#include \"pinocchio/spatial/se3.hpp\"\n#include \"pinocchio/multibody/visitor.hpp\"\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/compute-all-terms.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n#include \"pinocchio/utils/timer.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n\n//#define __SSE3__\n#include <fenv.h>\n#ifdef __SSE3__\n#include <pmmintrin.h>\n#endif\n\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE ( test_against_algo )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model; buildModels::humanoidRandom(model);\n  pinocchio::Data data(model); data.M.fill (0.);\n  pinocchio::Data data_other(model); data_other.M.fill (0.);\n\n  VectorXd q (VectorXd::Random(model.nq));\n  VectorXd v (VectorXd::Random(model.nv));\n\n  // -------\n  q.setZero ();\n  v.setZero ();\n\n  computeAllTerms(model,data,q,v);\n\n  nonLinearEffects(model,data_other,q,v);\n  crba(model,data_other,q);\n  getJacobianComFromCrba(model, data_other);\n  computeJointJacobians(model,data_other,q);\n  centerOfMass(model, data_other, q, v, true);\n  kineticEnergy(model, data_other, q, v, true);\n  potentialEnergy(model, data_other, q, true);\n\n  BOOST_CHECK (data.nle.isApprox(data_other.nle, 1e-12));\n  BOOST_CHECK (Eigen::MatrixXd(data.M.triangularView<Eigen::Upper>())\n              .isApprox(Eigen::MatrixXd(data_other.M.triangularView<Eigen::Upper>()), 1e-12));\n  BOOST_CHECK (data.J.isApprox(data_other.J, 1e-12));\n  BOOST_CHECK (data.Jcom.isApprox(data_other.Jcom, 1e-12));\n  \n  for (int k=0; k<model.njoints; ++k)\n  {\n    BOOST_CHECK (data.com[(size_t)k].isApprox(data_other.com[(size_t)k], 1e-12));\n    BOOST_CHECK (data.vcom[(size_t)k].isApprox(data_other.vcom[(size_t)k], 1e-12));\n    BOOST_CHECK_CLOSE(data.mass[(size_t)k], data_other.mass[(size_t)k], 1e-12);\n  }\n  \n  BOOST_CHECK_CLOSE(data.kinetic_energy, data_other.kinetic_energy, 1e-12);\n  BOOST_CHECK_CLOSE(data.potential_energy, data_other.potential_energy, 1e-12);\n\n  // -------\n  q.setZero ();\n  v.setOnes ();\n\n  computeAllTerms(model,data,q,v);\n\n  nonLinearEffects(model,data_other,q,v);\n  crba(model,data_other,q);\n  getJacobianComFromCrba(model, data_other);\n  computeJointJacobians(model,data_other,q);\n  centerOfMass(model, data_other, q, v, true);\n  kineticEnergy(model, data_other, q, v, true);\n  potentialEnergy(model, data_other, q, true);\n\n  BOOST_CHECK (data.nle.isApprox(data_other.nle, 1e-12));\n  BOOST_CHECK (Eigen::MatrixXd(data.M.triangularView<Eigen::Upper>())\n              .isApprox(Eigen::MatrixXd(data_other.M.triangularView<Eigen::Upper>()), 1e-12));\n  BOOST_CHECK (data.J.isApprox(data_other.J, 1e-12));\n  BOOST_CHECK (data.Jcom.isApprox(data_other.Jcom, 1e-12));\n  \n  for (int k=0; k<model.njoints; ++k)\n  {\n    BOOST_CHECK (data.com[(size_t)k].isApprox(data_other.com[(size_t)k], 1e-12));\n    BOOST_CHECK (data.vcom[(size_t)k].isApprox(data_other.vcom[(size_t)k], 1e-12));\n    BOOST_CHECK_CLOSE(data.mass[(size_t)k], data_other.mass[(size_t)k], 1e-12);\n  }\n  \n  BOOST_CHECK_CLOSE(data.kinetic_energy, data_other.kinetic_energy, 1e-12);\n  BOOST_CHECK_CLOSE(data.potential_energy, data_other.potential_energy, 1e-12);\n\n//   -------\n  q.setOnes ();\n  q.segment<4> (3).normalize();\n  v.setOnes ();\n\n  computeAllTerms(model,data,q,v);\n\n  nonLinearEffects(model,data_other,q,v);\n  crba(model,data_other,q);\n  getJacobianComFromCrba(model, data_other);\n  computeJointJacobians(model,data_other,q);\n  centerOfMass(model, data_other, q, v, true);\n  kineticEnergy(model, data_other, q, v, true);\n  potentialEnergy(model, data_other, q, true);\n\n  BOOST_CHECK (data.nle.isApprox(data_other.nle, 1e-12));\n  BOOST_CHECK (Eigen::MatrixXd(data.M.triangularView<Eigen::Upper>())\n              .isApprox(Eigen::MatrixXd(data_other.M.triangularView<Eigen::Upper>()), 1e-12));\n  BOOST_CHECK (data.J.isApprox(data_other.J, 1e-12));\n  BOOST_CHECK (data.Jcom.isApprox(data_other.Jcom, 1e-12));\n  \n  for (int k=0; k<model.njoints; ++k)\n  {\n    BOOST_CHECK (data.com[(size_t)k].isApprox(data_other.com[(size_t)k], 1e-12));\n    BOOST_CHECK (data.vcom[(size_t)k].isApprox(data_other.vcom[(size_t)k], 1e-12));\n    BOOST_CHECK_CLOSE(data.mass[(size_t)k], data_other.mass[(size_t)k], 1e-12);\n  }\n  \n  BOOST_CHECK_CLOSE(data.kinetic_energy, data_other.kinetic_energy, 1e-12);\n  BOOST_CHECK_CLOSE(data.potential_energy, data_other.potential_energy, 1e-12);\n\n  // -------\n  q.setRandom ();\n  q.segment<4> (3).normalize();\n  v.setRandom ();\n\n  computeAllTerms(model,data,q,v);\n\n  nonLinearEffects(model,data_other,q,v);\n  crba(model,data_other,q);\n  getJacobianComFromCrba(model, data_other);\n  computeJointJacobians(model,data_other,q);\n  centerOfMass(model, data_other, q, v, true);\n  kineticEnergy(model, data_other, q, v, true);\n  potentialEnergy(model, data_other, q, true);\n\n  BOOST_CHECK (data.nle.isApprox(data_other.nle, 1e-12));\n  BOOST_CHECK (Eigen::MatrixXd(data.M.triangularView<Eigen::Upper>())\n              .isApprox(Eigen::MatrixXd(data_other.M.triangularView<Eigen::Upper>()), 1e-12));\n  BOOST_CHECK (data.J.isApprox(data_other.J, 1e-12));\n  BOOST_CHECK (data.Jcom.isApprox(data_other.Jcom, 1e-12));\n  \n  for (int k=0; k<model.njoints; ++k)\n  {\n    BOOST_CHECK (data.com[(size_t)k].isApprox(data_other.com[(size_t)k], 1e-12));\n    BOOST_CHECK (data.vcom[(size_t)k].isApprox(data_other.vcom[(size_t)k], 1e-12));\n    BOOST_CHECK_CLOSE(data.mass[(size_t)k], data_other.mass[(size_t)k], 1e-12);\n  }\n  \n  BOOST_CHECK_CLOSE(data.kinetic_energy, data_other.kinetic_energy, 1e-12);\n  BOOST_CHECK_CLOSE(data.potential_energy, data_other.potential_energy, 1e-12);\n}\n\nBOOST_AUTO_TEST_SUITE_END ()\n", "meta": {"hexsha": "04a29571127e90447b988cd5bf395b6eb7d3810d", "size": 5854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/compute-all-terms.cpp", "max_stars_repo_name": "andreadelprete/pinocchio", "max_stars_repo_head_hexsha": "6fa1c7d5502629ee126f84f1a05471815fba30f4", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "unittest/compute-all-terms.cpp", "max_issues_repo_name": "andreadelprete/pinocchio", "max_issues_repo_head_hexsha": "6fa1c7d5502629ee126f84f1a05471815fba30f4", "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/compute-all-terms.cpp", "max_forks_repo_name": "andreadelprete/pinocchio", "max_forks_repo_head_hexsha": "6fa1c7d5502629ee126f84f1a05471815fba30f4", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 35.265060241, "max_line_length": 94, "alphanum_fraction": 0.7186539119, "num_tokens": 1776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5028801312866196}}
{"text": "#include <gauss_msgs/CheckConflicts.h>\n#include <gauss_msgs/Circle.h>\n#include <gauss_msgs/NewDeconfliction.h>\n#include <gauss_msgs/ReadIcao.h>\n#include <gauss_msgs/ReadOperation.h>\n#include <gauss_msgs/Waypoint.h>\n#include <geometry_msgs/Polygon.h>\n#include <geometry_msgs/Vector3.h>\n#include <ros/ros.h>\n#include <tactical_deconfliction/path_finder.h>\n#include <visualization_msgs/Marker.h>\n#include <visualization_msgs/MarkerArray.h>\n\n#include <Eigen/Eigen>\n\ndouble safety_distance_;\nbool actual_wp_on_merge_;\nros::Publisher visualization_pub_;\n\nstd::vector<Eigen::Vector3f> perpendicularSeparationVector(const gauss_msgs::Waypoint &_pA, const gauss_msgs::Waypoint &_pB, const double &_op_vol_A, const double &_op_vol_B) {\n    std::vector<Eigen::Vector3f> out_avoid_vector;\n    Eigen::Vector3f p_a, p_b, unit_vec_ab, unit_vec_ba, avoid_vector_a, avoid_vector_b;\n    p_a = Eigen::Vector3f(_pA.x, _pA.y, _pA.z);\n    p_b = Eigen::Vector3f(_pB.x, _pB.y, _pB.z);\n\n    unit_vec_ab = (p_a - p_b) / (p_a - p_b).norm();\n    unit_vec_ba = (p_b - p_a) / (p_b - p_a).norm();\n\n    double distance_to_avoid;\n    double distance_between_points = (p_a - p_b).norm();\n    double distance_operational_volumes = _op_vol_A + _op_vol_B;\n    if (safety_distance_ >= distance_operational_volumes) {\n        distance_to_avoid = safety_distance_;\n    } else {\n        distance_to_avoid = distance_operational_volumes;\n    }\n    distance_to_avoid -= distance_between_points;\n    double extra_safety_margin = 1.1;  // Increase 10% the distance\n    distance_to_avoid *= extra_safety_margin;\n\n    avoid_vector_a = -unit_vec_ba * distance_to_avoid;\n    avoid_vector_b = -unit_vec_ab * distance_to_avoid;\n\n    out_avoid_vector.push_back(avoid_vector_a);\n    out_avoid_vector.push_back(avoid_vector_b);\n\n    return out_avoid_vector;\n}\n\nstd::vector<gauss_msgs::Waypoint> applySeparation(const Eigen::Vector3f &_avoid_vector, const std::vector<gauss_msgs::Waypoint> &_extremes) {\n    // TODO: Check why _extremes has repeated elements.\n    std::vector<gauss_msgs::Waypoint> out_waypoints;\n    gauss_msgs::Waypoint pA, pB;  // (pA) ------------------- (pB)\n    pA = _extremes.front();\n    pB = _extremes.back();\n\n    for (auto wp : _extremes) {\n        wp.x = wp.x + _avoid_vector[0];\n        wp.y = wp.y + _avoid_vector[1];\n        wp.z = wp.z + _avoid_vector[2];\n        out_waypoints.push_back(wp);\n    }\n\n    return out_waypoints;\n}\n\nvoid checkGroundCollision(const std::vector<gauss_msgs::Waypoint> &_solution, const double &_operational_volume) {\n    for (auto wp : _solution) {\n        ROS_ERROR_COND(wp.z - _operational_volume <= 0.0, \"[Tactical] Proposed solution hits the ground. Waypoint height is [%.2f].\", wp.z);\n    }\n}\n\ngeometry_msgs::Polygon circleToPolygon(double &_x, double &_y, double &_radius, double _nVertices = 9) {\n    geometry_msgs::Polygon out_polygon;\n    Eigen::Vector2d centerToVertex(_radius, 0.0), centerToVertexTemp;\n    for (int i = 0; i < _nVertices; i++) {\n        double theta = i * 2 * M_PI / (_nVertices - 1);\n        Eigen::Rotation2D<double> rot2d(theta);\n        centerToVertexTemp = rot2d.toRotationMatrix() * centerToVertex;\n        geometry_msgs::Point32 temp_point;\n        temp_point.x = _x + centerToVertexTemp[0];\n        temp_point.y = _y + centerToVertexTemp[1];\n        out_polygon.points.push_back(temp_point);\n    }\n\n    return out_polygon;\n}\n\n// nvert        - Number of vertices in the polygon. Whether to repeat the first vertex at the end is discussed below.\n// vertx, verty\t- Arrays containing the x- and y-coordinates of the polygon's vertices.\n// testx, testy\t- X&Y coordinate of the test point.\n// [https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html]\nint pointInPolygon(int nvert, std::vector<float> &vertx, std::vector<float> &verty, float testx, float testy) {\n    int i, j, c = 0;\n    for (i = 0, j = nvert - 1; i < nvert; j = i++) {\n        if (((verty.at(i) > testy) != (verty.at(j) > testy)) &&\n            (testx < (vertx.at(j) - vertx.at(i)) * (testy - verty.at(i)) / (verty.at(j) - verty.at(i)) + vertx.at(i)))\n            c = !c;\n    }\n    return c;\n}\n\ndouble signedArea(const geometry_msgs::Polygon &p) {\n    double A = 0;\n    //========================================================//\n    // Assumes:                                               //\n    //    N+1 vertices:   p[0], p[1], ... , p[N-1], p[N]      //\n    //    Closed polygon: p[0] = p[N]                         //\n    // Returns:                                               //\n    //    Signed area: +ve if anticlockwise, -ve if clockwise //\n    //========================================================//\n    int N = p.points.size() - 1;\n    for (int i = 0; i < N; i++) A += p.points.at(i).x * p.points.at(i + 1).y - p.points.at(i + 1).x * p.points.at(i).y;\n    A *= 0.5;\n    return A;\n}\n\ngeometry_msgs::Polygon decreasePolygon(const geometry_msgs::Polygon &p, double thickness) {\n    //=====================================================//\n    // Assumes:                                            //\n    //    N+1 vertices:   p[0], p[1], ... , p[N-1], p[N]   //\n    //    Closed polygon: p[0] = p[N]                      //\n    //    No zero-length sides                             //\n    // Returns (by reference, as a parameter):             //\n    //    Internal poly:  q[0], q[1], ... , q[N-1], q[N]   //\n    //=====================================================//\n    geometry_msgs::Polygon q;\n    int N = p.points.size() - 1;\n    q.points.resize(N + 1);\n    double a, b, A, B, d, cross;\n    double displacement = thickness;\n    if (signedArea(p) < 0) displacement = -displacement;  // Detects clockwise order\n    // Unit vector (a,b) along last edge\n    a = p.points.at(N).x - p.points.at(N - 1).x;\n    b = p.points.at(N).y - p.points.at(N - 1).y;\n    d = sqrt(a * a + b * b);\n    a /= d;\n    b /= d;\n    for (int i = 0; i < N; i++) {  // Loop round the polygon, dealing with successive intersections of lines\n        // Unit vector (A,B) along previous edge\n        A = a;\n        B = b;\n        // Unit vector (a,b) along next edge\n        a = p.points.at(i + 1).x - p.points.at(i).x;\n        b = p.points.at(i + 1).y - p.points.at(i).y;\n        d = sqrt(a * a + b * b);\n        a /= d;\n        b /= d;\n        // New vertex\n        cross = A * b - a * B;\n        const double SMALL = 1.0e-10;\n        if (abs(cross) < SMALL) {  // Degenerate cases: 0 or 180 degrees at vertex\n            q.points.at(i).x = p.points.at(i).x - displacement * b;\n            q.points.at(i).y = p.points.at(i).y + displacement * a;\n        } else {  // Usual case\n            q.points.at(i).x = p.points.at(i).x + displacement * (a - A) / cross;\n            q.points.at(i).y = p.points.at(i).y + displacement * (b - B) / cross;\n        }\n    }\n    // Close the inside polygon\n    q.points.at(N) = q.points.at(0);\n\n    return q;\n}\n\nbool pointInCircle(const geometry_msgs::Point &_point, const gauss_msgs::Geofence &_geofence) {\n    if (!_geofence.cylinder_shape) {\n        ROS_ERROR(\"[Tactical] pointInCircle function: This is not a cylinder!\");\n        return false;\n    }\n    if (sqrt(pow(_point.x - _geofence.circle.x_center, 2) + pow(_point.y - _geofence.circle.y_center, 2)) <= _geofence.circle.radius) {\n        return true;\n    } else {\n        return false;\n    }\n}\n\nstd::vector<double> findGridBorders(geometry_msgs::Polygon &_polygon, geometry_msgs::Point _init_point, geometry_msgs::Point _goal_point, double _operational_volume) {\n    geometry_msgs::Point obs_min, obs_max, out_point;\n    std::vector<float> vert_x, vert_y;\n    for (int i = 0; i < _polygon.points.size(); i++) {\n        vert_x.push_back(_polygon.points.at(i).x);\n        vert_y.push_back(_polygon.points.at(i).y);\n    }\n    vert_x.push_back(_init_point.x);\n    vert_y.push_back(_init_point.y);\n    vert_x.push_back(_goal_point.x);\n    vert_y.push_back(_goal_point.y);\n\n    obs_min.x = *std::min_element(vert_x.begin(), vert_x.end());\n    obs_min.y = *std::min_element(vert_y.begin(), vert_y.end());\n    obs_max.x = *std::max_element(vert_x.begin(), vert_x.end());\n    obs_max.y = *std::max_element(vert_y.begin(), vert_y.end());\n\n    std::vector<double> out_grid_borders;\n    out_grid_borders.push_back(obs_min.x - 5 * _operational_volume);\n    out_grid_borders.push_back(obs_min.y - 5 * _operational_volume);\n    out_grid_borders.push_back(obs_max.x + 5 * _operational_volume);\n    out_grid_borders.push_back(obs_max.y + 5 * _operational_volume);\n\n    return out_grid_borders;\n}\n\ngeometry_msgs::Point translateToPoint(const gauss_msgs::Waypoint &wp) {\n    geometry_msgs::Point p;\n    p.x = wp.x;\n    p.y = wp.y;\n    p.z = wp.z;\n    return p;\n}\n\nnav_msgs::Path translateToPath(const gauss_msgs::WaypointList &_wp_list) {\n    nav_msgs::Path out_path;\n    for (auto wp : _wp_list.waypoints) {\n        geometry_msgs::PoseStamped temp_wp;\n        temp_wp.pose.position.x = wp.x;\n        temp_wp.pose.position.y = wp.y;\n        temp_wp.pose.position.z = wp.z;\n        temp_wp.header.stamp = wp.stamp;\n        out_path.poses.push_back(temp_wp);\n    }\n    return out_path;\n}\n\nstd::vector<gauss_msgs::Waypoint> pathAStartToWPVector(const nav_msgs::Path &_path, const std::vector<double> &_times) {\n    std::vector<gauss_msgs::Waypoint> out_wp_vector;\n    ROS_ERROR_COND(_path.poses.size() != _times.size(), \"[Tactical] A Start solution must have the same amount of waypoints (space[%d] and time[%d])!\", _path.poses.size(), _times.size());\n    for (int i = 0; i < _path.poses.size(); i++) {\n        gauss_msgs::Waypoint temp_wp;\n        temp_wp.x = _path.poses.at(i).pose.position.x;\n        temp_wp.y = _path.poses.at(i).pose.position.y;\n        temp_wp.z = _path.poses.at(i).pose.position.z;\n        temp_wp.stamp = ros::Time(_times.at(i));  // !Careful\n        out_wp_vector.push_back(temp_wp);\n    }\n    return out_wp_vector;\n}\n\nstd::vector<gauss_msgs::Waypoint> findAlternativePathRadial(gauss_msgs::Waypoint &_p_init, gauss_msgs::Waypoint &_p_end, gauss_msgs::Geofence &_geofence, gauss_msgs::ConflictiveOperation &_conflictive_operation, const geometry_msgs::Vector3 &_init_vector, const geometry_msgs::Vector3 &_final_vector, double _safety_margin) {\n    std::vector<gauss_msgs::Waypoint> out;\n    auto init_angle = atan2(_init_vector.y, _init_vector.x);\n    auto final_angle = atan2(_final_vector.y, _final_vector.x);\n    auto delta_angle = atan2(sin(final_angle - init_angle), cos(final_angle - init_angle));\n    auto arc_lenght = _geofence.circle.radius * std::fabs(delta_angle);\n    float min_solution_segment_lenght = 100.0;  // [m] TODO: as a param?\n    int segment_count = static_cast<int>(std::max(2.0, std::floor(arc_lenght / min_solution_segment_lenght)));\n    auto step_angle = delta_angle / segment_count;\n    auto z_step = (_p_end.z - _p_init.z) / segment_count;\n    double t_step;\n    if (_p_init.mandatory) {                                                            //* Geofence intrusion if mandatory is true\n        t_step = (_p_end.stamp.toSec() - _p_init.stamp.toSec()) / (segment_count + 1);  // We need to take another segment into account.\n        _p_init.stamp.fromSec(_p_init.stamp.toSec() + t_step);                          // That segment is from the current position to the closest exit wp\n    } else {                                                                            //* Geofence Conflict if mandatory is false\n        t_step = (_p_end.stamp.toSec() - _p_init.stamp.toSec()) / segment_count;\n    }\n    for (int i = 0; i < segment_count + 1; i++) {\n        auto i_angle = init_angle + i * step_angle;\n        gauss_msgs::Waypoint wp;\n        wp.x = _geofence.circle.x_center + (_geofence.circle.radius + _safety_margin) * cos(i_angle);\n        wp.y = _geofence.circle.y_center + (_geofence.circle.radius + _safety_margin) * sin(i_angle);\n        wp.z = _p_init.z + i * z_step;\n        wp.stamp.fromSec(_p_init.stamp.toSec() + i * t_step);\n        out.push_back(wp);\n    }\n\n    return out;\n}\n\nstd::vector<gauss_msgs::Waypoint> findAlternativePathAStar(geometry_msgs::Point &_p_init, geometry_msgs::Point &_p_end, ros::Time &_t_init, ros::Time &_t_end, gauss_msgs::Geofence &_geofence, gauss_msgs::ConflictiveOperation &_conflictive_operation) {\n    // Setup polygon geofence according on its shape\n    geometry_msgs::Polygon polygon_geofence;\n    if (_geofence.cylinder_shape) {\n        polygon_geofence = circleToPolygon(_geofence.circle.x_center, _geofence.circle.y_center, _geofence.circle.radius);\n    } else {\n        for (int i = 0; i < _geofence.polygon.x.size(); i++) {\n            geometry_msgs::Point32 temp_points;\n            temp_points.x = _geofence.polygon.x.at(i);\n            temp_points.y = _geofence.polygon.y.at(i);\n            polygon_geofence.points.push_back(temp_points);\n        }\n    }\n    // Inflate polygon to take operational volume into account\n    if (!_geofence.cylinder_shape) polygon_geofence.points.push_back(polygon_geofence.points.front());\n    geometry_msgs::Polygon inflated_geofence = decreasePolygon(polygon_geofence, -_conflictive_operation.operational_volume * 1.5);\n    if (!_geofence.cylinder_shape) inflated_geofence.points.pop_back();\n    // Get borders of a local greed for the A* path finder\n    geometry_msgs::Point p_min_local_grid, p_max_local_grid;\n    std::vector<double> grid_borders = findGridBorders(inflated_geofence, _p_init, _p_end, _conflictive_operation.operational_volume);\n    p_min_local_grid.x = grid_borders[0];\n    p_min_local_grid.y = grid_borders[1];\n    p_max_local_grid.x = grid_borders[2];\n    p_max_local_grid.y = grid_borders[3];\n    nav_msgs::Path estimated_traj_path = translateToPath(_conflictive_operation.estimated_trajectory);\n    // Use A* path finder to get an alternative path\n    PathFinder path_finder(estimated_traj_path, _p_init, _p_end, inflated_geofence, p_min_local_grid, p_max_local_grid);\n    nav_msgs::Path a_star_path = path_finder.findNewPath();\n    // Fix times\n    std::vector<double> interp_times, a_star_times;\n    interp_times.push_back(_t_init.toSec());\n    interp_times.push_back(_t_end.toSec());\n    a_star_times = path_finder.interpWaypointList(interp_times, a_star_path.poses.size() - 1);\n    a_star_times.push_back(_t_end.toSec());\n\n    return pathAStartToWPVector(a_star_path, a_star_times);\n}\n\nstd::vector<gauss_msgs::Waypoint> mergeSolutionWithFlightPlan(std::vector<gauss_msgs::Waypoint> &_solution, gauss_msgs::WaypointList &_flight_plan, gauss_msgs::Waypoint &_actual_wp, const uint8_t &_threat_type) {\n    std::vector<gauss_msgs::Waypoint> out_merged_solution;\n    bool do_once = true;\n    if (actual_wp_on_merge_) out_merged_solution.push_back(_actual_wp);  // Insert the actual wp\n    for (auto fp_wp : _flight_plan.waypoints) {\n        if (_flight_plan.waypoints.front().stamp <= fp_wp.stamp) {              // Do nothing before current wp. Current wp (it is refered to flight plan) is equal than flight_plan_updated[0]\n            if (fp_wp.stamp <= _solution.front().stamp && _threat_type != 5) {  // Between current wp and first wp of the solution if threat type is not GEOFENCE INTRUSION\n                out_merged_solution.push_back(fp_wp);\n            } else if (do_once && _solution.back().stamp < fp_wp.stamp) {  // Insert all the solution wps\n                for (auto solution_wp : _solution) {\n                    out_merged_solution.push_back(solution_wp);\n                }\n                out_merged_solution.push_back(fp_wp);  // Insert the wp after the solution\n                do_once = false;\n            } else if (_solution.back().stamp < fp_wp.stamp) {  // Insert the remaining wps of the flight plan\n                out_merged_solution.push_back(fp_wp);\n            }\n        }\n    }\n    return out_merged_solution;\n}\n\nstd::vector<gauss_msgs::Waypoint> delayFlightPlan(std::vector<gauss_msgs::Waypoint> &_segment, gauss_msgs::WaypointList &_flight_plan, gauss_msgs::Waypoint &_actual_wp) {\n    std::vector<gauss_msgs::Waypoint> out_merged_solution;\n    bool do_once = true;\n    double safety_margin = 1.5;\n    double dtime = (_segment.back().stamp.sec - _segment.front().stamp.sec) * safety_margin;\n    if (actual_wp_on_merge_) out_merged_solution.push_back(_actual_wp);  // Insert the actual wp\n    for (auto fp_wp : _flight_plan.waypoints) {\n        if (_flight_plan.waypoints.front().stamp <= fp_wp.stamp) {  // Do nothing before current wp. Current wp (it is refered to flight plan) is equal than flight_plan_updated[0]\n            if (fp_wp.stamp <= _segment.front().stamp) {            // Between current wp and first wp of the solution\n                out_merged_solution.push_back(fp_wp);\n            } else if (do_once && _segment.back().stamp < fp_wp.stamp) {  // Insert all the solution wps\n                for (auto segment_wp : _segment) {\n                    segment_wp.stamp.fromSec(segment_wp.stamp.toSec() + dtime);\n                    out_merged_solution.push_back(segment_wp);\n                }\n                fp_wp.stamp.fromSec(fp_wp.stamp.toSec() + dtime);\n                out_merged_solution.push_back(fp_wp);  // Insert the wp after the solution\n                do_once = false;\n            } else if (_segment.back().stamp < fp_wp.stamp) {  // Insert the remaining wps of the flight plan\n                fp_wp.stamp.fromSec(fp_wp.stamp.toSec() + dtime);\n                out_merged_solution.push_back(fp_wp);\n            }\n        }\n    }\n\n    return out_merged_solution;\n}\n\nvisualization_msgs::Marker createMarkerSpheres(const gauss_msgs::Waypoint &_p_at_t_min_first, const gauss_msgs::Waypoint &_p_at_t_min_second) {\n    std_msgs::ColorRGBA white;\n    white.r = 1.0;\n    white.g = 1.0;\n    white.b = 1.0;\n    white.a = 1.0;\n\n    visualization_msgs::Marker marker_spheres;\n    marker_spheres.header.stamp = ros::Time::now();\n    marker_spheres.header.frame_id = \"map\";\n    marker_spheres.ns = \"avoid_points\";\n    marker_spheres.id = 0;\n    marker_spheres.type = visualization_msgs::Marker::SPHERE_LIST;\n    marker_spheres.action = visualization_msgs::Marker::ADD;\n    marker_spheres.pose.orientation.w = 1;\n    marker_spheres.scale.x = 5.0;\n    marker_spheres.scale.y = 5.0;\n    marker_spheres.scale.z = 5.0;\n    marker_spheres.lifetime = ros::Duration(5.0);\n    marker_spheres.points.push_back(translateToPoint(_p_at_t_min_first));\n    marker_spheres.colors.push_back(white);\n    marker_spheres.points.push_back(translateToPoint(_p_at_t_min_second));\n    marker_spheres.colors.push_back(white);\n    return marker_spheres;\n}\n\nvisualization_msgs::Marker createMarkerLines(const std::vector<gauss_msgs::Waypoint> &_solution) {\n    std_msgs::ColorRGBA blue;\n    blue.b = 1.0;\n    blue.a = 1.0;\n    static int sol_count = 0;\n\n    visualization_msgs::Marker marker_lines;\n    marker_lines.header.stamp = ros::Time::now();\n    marker_lines.header.frame_id = \"map\";\n    marker_lines.ns = \"lines_\" + std::to_string(sol_count);\n    sol_count++;\n    marker_lines.id = 1;\n    marker_lines.type = visualization_msgs::Marker::LINE_STRIP;\n    marker_lines.action = visualization_msgs::Marker::ADD;\n    marker_lines.pose.orientation.w = 1;\n    marker_lines.scale.x = 5.0;\n    marker_lines.color = blue;\n    marker_lines.lifetime = ros::Duration(5.0);\n\n    for (auto wp : _solution) {\n        marker_lines.points.push_back(translateToPoint(wp));\n    }\n\n    return marker_lines;\n}\n\nbool deconflictCB(gauss_msgs::NewDeconfliction::Request &req, gauss_msgs::NewDeconfliction::Response &res) {\n    ROS_INFO(\"[Tactical] Threat to solve [%d, %d]\", req.threat.threat_id, req.threat.threat_type);\n    switch (req.threat.threat_type) {\n        case req.threat.LOSS_OF_SEPARATION: {\n            std::vector<std::vector<gauss_msgs::Waypoint>> segments_first_second;\n            segments_first_second.push_back(req.threat.loss_conflictive_segments.segment_first);\n            segments_first_second.push_back(req.threat.loss_conflictive_segments.segment_second);\n            std::vector<gauss_msgs::Waypoint> points_at_t_min;\n            points_at_t_min.push_back(req.threat.loss_conflictive_segments.point_at_t_min_segment_first);\n            points_at_t_min.push_back(req.threat.loss_conflictive_segments.point_at_t_min_segment_second);\n            ROS_ERROR_COND(req.threat.conflictive_operations.size() != 2, \"[Tactical] Deconflictive server should receive 2 conflictive operations to solve LOSS OF SEPARATION!\");\n            // Calculate a vector to separate perpendiculary one trajectory\n            std::vector<Eigen::Vector3f> avoid_vectors = perpendicularSeparationVector(points_at_t_min.front(), points_at_t_min.back(), req.threat.conflictive_operations.front().operational_volume, req.threat.conflictive_operations.back().operational_volume);\n            // Solution applying separation to one operation\n            double fake_value = 1.0;\n            for (int i = 0; i < 2; i++) {\n                gauss_msgs::DeconflictionPlan possible_solution;\n                possible_solution.maneuver_type = 8;\n                possible_solution.cost = possible_solution.riskiness = fake_value;\n                possible_solution.uav_id = req.threat.conflictive_operations.at(i).uav_id;\n                std::vector<gauss_msgs::Waypoint> temp_solution = applySeparation(avoid_vectors.at(i), segments_first_second.at(i));\n                // TODO: Should another alternative be proposed if the current one hits the ground?\n                checkGroundCollision(temp_solution, req.threat.conflictive_operations.at(i).operational_volume);\n                // TODO: Who should do the merge?\n                possible_solution.waypoint_list = mergeSolutionWithFlightPlan(temp_solution, req.threat.conflictive_operations.at(i).flight_plan_updated, req.threat.conflictive_operations.at(i).actual_wp, req.threat.threat_type);\n                res.deconfliction_plans.push_back(possible_solution);\n            }\n            // !Solution delaying one operation\n            fake_value = 5.0;\n            for (int i = 0; i < 2; i++) {\n                gauss_msgs::DeconflictionPlan possible_solution;\n                possible_solution.maneuver_type = 8;  // !Should be another maneuver type?\n                possible_solution.cost = possible_solution.riskiness = fake_value;\n                possible_solution.uav_id = req.threat.conflictive_operations.at(i).uav_id;\n                std::vector<gauss_msgs::Waypoint> temp_solution = segments_first_second.at(i);\n                possible_solution.waypoint_list = delayFlightPlan(segments_first_second.at(i), req.threat.conflictive_operations.at(i).flight_plan_updated, req.threat.conflictive_operations.at(i).actual_wp);\n                res.deconfliction_plans.push_back(possible_solution);\n            }\n            // Visualize \"space\" results\n            visualization_msgs::MarkerArray marker_array;\n            visualization_msgs::Marker marker_spheres = createMarkerSpheres(req.threat.loss_conflictive_segments.point_at_t_min_segment_first, req.threat.loss_conflictive_segments.point_at_t_min_segment_second);\n            marker_array.markers.push_back(marker_spheres);\n            for (int i = 0; i < 2; i++) marker_array.markers.push_back(createMarkerLines(res.deconfliction_plans[i].waypoint_list));\n            visualization_pub_.publish(marker_array);\n        } break;\n        case req.threat.GEOFENCE_CONFLICT: {\n            ROS_ERROR_COND(req.threat.conflictive_geofences.size() != 1, \"[Tactical] Deconflictive server should receive 1 geofence to solve GEOFENCE CONFLICT!\");\n            // * Assume inputs from monitoring\n            // // TODO: Check if init and end points have to be further apart from the geofence!\n            geometry_msgs::Point p_init_conflict, p_end_conflict;\n            p_init_conflict.x = req.threat.geofence_conflictive_segments.first_contiguous_segment.front().x;\n            p_init_conflict.y = req.threat.geofence_conflictive_segments.first_contiguous_segment.front().y;\n            p_init_conflict.z = req.threat.geofence_conflictive_segments.first_contiguous_segment.front().z;\n            p_end_conflict.x = req.threat.geofence_conflictive_segments.first_contiguous_segment.back().x;\n            p_end_conflict.y = req.threat.geofence_conflictive_segments.first_contiguous_segment.back().y;\n            p_end_conflict.z = req.threat.geofence_conflictive_segments.first_contiguous_segment.back().z;\n            ros::Time t_init_conflict = req.threat.geofence_conflictive_segments.first_contiguous_segment.front().stamp;\n            ros::Time t_end_conflict = req.threat.geofence_conflictive_segments.first_contiguous_segment.back().stamp;\n            const double safety_margin = req.threat.conflictive_operations.front().operational_volume * 2.0;\n\n            double fake_value = 1.0;\n            gauss_msgs::DeconflictionPlan possible_solution;\n            // [1] Ruta a mi destino evitando una geofence\n            // Just do it if end point is outside the geofence\n            if (!pointInCircle(p_end_conflict, req.threat.conflictive_geofences.front())) {\n                possible_solution.maneuver_type = 1;\n                possible_solution.uav_id = req.threat.uav_ids.front();\n                possible_solution.cost = possible_solution.riskiness = fake_value;\n                // std::vector<gauss_msgs::Waypoint> temp_solution = findAlternativePathAStar(p_init_conflict, p_end_conflict, t_init_conflict, t_end_conflict, req.threat.conflictive_geofences.front(), req.threat.conflictive_operations.front());\n                std::vector<gauss_msgs::Waypoint> temp_solution = findAlternativePathRadial(req.threat.geofence_conflictive_segments.first_contiguous_segment.front(), req.threat.geofence_conflictive_segments.first_contiguous_segment.back(), req.threat.conflictive_geofences.front(), req.threat.conflictive_operations.front(), req.threat.geofence_conflictive_segments.crossing_0_out_vector, req.threat.geofence_conflictive_segments.crossing_1_out_vector, safety_margin);\n                possible_solution.waypoint_list = mergeSolutionWithFlightPlan(temp_solution, req.threat.conflictive_operations.front().flight_plan_updated, req.threat.conflictive_operations.front().actual_wp, req.threat.threat_type);\n                res.deconfliction_plans.push_back(possible_solution);\n            }\n            // [3] Ruta que me manda devuelta a casa\n            possible_solution.maneuver_type = 3;\n            possible_solution.waypoint_list.clear();\n            possible_solution.uav_id = req.threat.uav_ids.front();\n            possible_solution.cost = possible_solution.riskiness = fake_value * 2;\n            possible_solution.waypoint_list.push_back(req.threat.conflictive_operations.front().estimated_trajectory.waypoints.front());\n            possible_solution.waypoint_list.push_back(req.threat.conflictive_operations.front().flight_plan.waypoints.front());\n            res.deconfliction_plans.push_back(possible_solution);\n        } break;\n        case req.threat.GEOFENCE_INTRUSION: {\n            ROS_ERROR_COND(req.threat.conflictive_geofences.size() != 1, \"[Tactical] Deconflictive server should receive 1 geofence to solve GEOFENCE INTRUSION!\");\n            // * Assume inputs from monitoring\n            // // TODO: Check if init and end points have to be further apart from the geofence!\n            geometry_msgs::Point p_init_conflict, p_end_conflict;\n            const double safety_margin = req.threat.conflictive_operations.front().operational_volume * 2.0;\n            p_init_conflict.x = req.threat.geofence_conflictive_segments.closest_exit_wp.x;\n            p_init_conflict.y = req.threat.geofence_conflictive_segments.closest_exit_wp.y;\n            p_init_conflict.z = req.threat.geofence_conflictive_segments.closest_exit_wp.z;\n            p_end_conflict.x = req.threat.geofence_conflictive_segments.all_segments.back().x;\n            p_end_conflict.y = req.threat.geofence_conflictive_segments.all_segments.back().y;\n            p_end_conflict.z = req.threat.geofence_conflictive_segments.all_segments.back().z;\n            ros::Time t_init_conflict = req.threat.geofence_conflictive_segments.closest_exit_wp.stamp;\n            ros::Time t_end_conflict = req.threat.geofence_conflictive_segments.all_segments.back().stamp;\n\n            double fake_value = 0.0;\n            gauss_msgs::DeconflictionPlan possible_solution;\n            possible_solution.uav_id = req.threat.conflictive_operations.front().uav_id;\n            // [6] Ruta a mi destino saliendo lo antes posible de la geofence\n            // Just do it if end point is outside the geofence\n            if (!pointInCircle(p_end_conflict, req.threat.conflictive_geofences.front())) {\n                possible_solution.maneuver_type = 1;\n                possible_solution.uav_id = req.threat.uav_ids.front();\n                possible_solution.cost = possible_solution.riskiness = fake_value;\n                // std::vector<gauss_msgs::Waypoint> temp_solution = findAlternativePathAStar(p_init_conflict, p_end_conflict, t_init_conflict, t_end_conflict, req.threat.conflictive_geofences.front(), req.threat.conflictive_operations.front());\n                req.threat.geofence_conflictive_segments.closest_exit_wp.stamp = req.threat.conflictive_operations.front().actual_wp.stamp;\n                std::vector<gauss_msgs::Waypoint> temp_solution = findAlternativePathRadial(req.threat.geofence_conflictive_segments.closest_exit_wp, req.threat.geofence_conflictive_segments.all_segments.back(), req.threat.conflictive_geofences.front(), req.threat.conflictive_operations.front(), req.threat.geofence_conflictive_segments.crossing_0_out_vector, req.threat.geofence_conflictive_segments.crossing_1_out_vector, safety_margin);\n                possible_solution.waypoint_list = mergeSolutionWithFlightPlan(temp_solution, req.threat.conflictive_operations.front().flight_plan_updated, req.threat.conflictive_operations.front().actual_wp, req.threat.threat_type);\n                res.deconfliction_plans.push_back(possible_solution);\n            }\n            // [2] Ruta a mi destino por el camino mas corto\n            possible_solution.maneuver_type = 2;\n            possible_solution.waypoint_list.clear();\n            possible_solution.uav_id = req.threat.uav_ids.front();\n            possible_solution.cost = possible_solution.riskiness = fake_value * 2;\n            possible_solution.waypoint_list.push_back(req.threat.conflictive_operations.front().estimated_trajectory.waypoints.front());\n            possible_solution.waypoint_list.push_back(req.threat.conflictive_operations.front().flight_plan.waypoints.back());\n            res.deconfliction_plans.push_back(possible_solution);\n            // [3] Ruta que me manda de vuelta a casa\n            possible_solution.maneuver_type = 3;\n            possible_solution.waypoint_list.clear();\n            possible_solution.uav_id = req.threat.uav_ids.front();\n            possible_solution.cost = possible_solution.riskiness = fake_value * 3;\n            possible_solution.waypoint_list.push_back(req.threat.conflictive_operations.front().estimated_trajectory.waypoints.front());\n            possible_solution.waypoint_list.push_back(req.threat.conflictive_operations.front().flight_plan.waypoints.front());\n            res.deconfliction_plans.push_back(possible_solution);\n            // [?] Ruta a un landing spot\n            possible_solution.maneuver_type = 3;\n            possible_solution.waypoint_list.clear();\n            possible_solution.uav_id = req.threat.uav_ids.front();\n            possible_solution.cost = possible_solution.riskiness = fake_value * 1;  // ! Forcing this solution to be selected\n            possible_solution.waypoint_list.push_back(req.threat.conflictive_operations.front().estimated_trajectory.waypoints.front());\n            req.threat.conflictive_operations.front().landing_spots.waypoints.front().stamp.fromSec(ros::Time::now().toSec() + 360.0);\n            possible_solution.waypoint_list.push_back(req.threat.conflictive_operations.front().landing_spots.waypoints.front());\n            res.deconfliction_plans.push_back(possible_solution);\n            visualization_msgs::MarkerArray marker_array;\n            for (auto i : res.deconfliction_plans) marker_array.markers.push_back(createMarkerLines(i.waypoint_list));\n            visualization_pub_.publish(marker_array);\n        } break;\n        case req.threat.UAS_OUT_OV: {\n            ROS_ERROR_COND(req.threat.conflictive_operations.size() != 1, \"[Tactical] Deconflictive server should receive 1 conflictive operations to solve UAS OUT OV!\");\n            gauss_msgs::DeconflictionPlan possible_solution;\n            possible_solution.uav_id = req.threat.conflictive_operations.front().uav_id;\n            // [9] Ruta para volver lo antes posible al flight geometry y seguir el plan de vuelo.\n            // TODO: Should we use the same strategy described in ConflictSolver.cpp?\n\n            // [10] Ruta para seguir con el plan de vuelo, da igual que est\u00e9 m\u00e1s tiempo fuera del Operational Volume.\n            possible_solution.maneuver_type = 10;\n            possible_solution.waypoint_list.clear();\n            possible_solution.waypoint_list.push_back(req.threat.conflictive_operations.front().estimated_trajectory.waypoints.back());\n            // ! current wp + 1 or just current wp?\n            possible_solution.waypoint_list.push_back(req.threat.conflictive_operations.front().flight_plan.waypoints.at(req.threat.conflictive_operations.front().current_wp + 1));\n            res.deconfliction_plans.push_back(possible_solution);\n        } break;\n        case req.threat.GNSS_DEGRADATION: {\n            ROS_ERROR_COND(req.threat.conflictive_operations.size() != 1, \"[Tactical] Deconflictive server should receive 1 conflictive operations to solve GNSS DEGRADATION!\");\n            // [5] Ruta que aterrice en un landing spot\n            for (auto landing_wp : req.threat.conflictive_operations.front().landing_spots.waypoints) {\n                gauss_msgs::DeconflictionPlan possible_solution;\n                possible_solution.uav_id = req.threat.conflictive_operations.front().uav_id;\n                possible_solution.maneuver_type = 5;\n                possible_solution.waypoint_list.push_back(req.threat.conflictive_operations.front().estimated_trajectory.waypoints.front());\n                possible_solution.waypoint_list.push_back(landing_wp);\n                res.deconfliction_plans.push_back(possible_solution);\n            }\n        } break;\n        case req.threat.LACK_OF_BATTERY: {\n            ROS_ERROR_COND(req.threat.conflictive_operations.size() != 1, \"[Tactical] Deconflictive server should receive 1 conflictive operations to solve LACK OF BATTERY!\");\n            // [5] Ruta que aterrice en un landing spot\n            for (auto landing_wp : req.threat.conflictive_operations.front().landing_spots.waypoints) {\n                gauss_msgs::DeconflictionPlan possible_solution;\n                possible_solution.uav_id = req.threat.conflictive_operations.front().uav_id;\n                possible_solution.maneuver_type = 5;\n                possible_solution.waypoint_list.push_back(req.threat.conflictive_operations.front().estimated_trajectory.waypoints.front());\n                possible_solution.waypoint_list.push_back(landing_wp);\n                res.deconfliction_plans.push_back(possible_solution);\n            }\n        } break;\n        default:\n            break;\n    }\n\n    res.message = \"Conflict solved\";\n    res.success = true;\n    return res.success;\n}\n\nint main(int argc, char **argv) {\n    ros::init(argc, argv, \"tactical_deconfliction\");\n\n    ros::NodeHandle nh;\n    nh.param(\"safetyDistance\", safety_distance_, 10.0);\n    nh.param(\"actual_wp_on_merge\", actual_wp_on_merge_, true);\n\n    ros::ServiceServer deconflict_server = nh.advertiseService(\"/gauss/new_tactical_deconfliction\", deconflictCB);\n    ros::ServiceClient check_client = nh.serviceClient<gauss_msgs::CheckConflicts>(\"/gauss/check_conflicts\");\n\n    auto visualization_topic_url = \"/gauss/visualize_tactical\";\n\n    visualization_pub_ = nh.advertise<visualization_msgs::MarkerArray>(visualization_topic_url, 1);\n\n    ros::Rate rate(1);  // [Hz]\n    while (ros::ok()) {\n        ros::spinOnce();\n        rate.sleep();\n    }\n\n    ros::spin();\n    return 0;\n}\n", "meta": {"hexsha": "22d9270e8976652db4fe67eda393902554cd4c54", "size": 36131, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "usp_nodes/tactical_deconfliction/src/tactical_deconfliction.cpp", "max_stars_repo_name": "hecperleo/gauss", "max_stars_repo_head_hexsha": "20ece37af00455ee760dcef1d583300eaa347a1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T16:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T05:06:49.000Z", "max_issues_repo_path": "usp_nodes/tactical_deconfliction/src/tactical_deconfliction.cpp", "max_issues_repo_name": "hecperleo/gauss", "max_issues_repo_head_hexsha": "20ece37af00455ee760dcef1d583300eaa347a1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-10T10:24:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T10:24:20.000Z", "max_forks_repo_path": "usp_nodes/tactical_deconfliction/src/tactical_deconfliction.cpp", "max_forks_repo_name": "hecperleo/gauss", "max_forks_repo_head_hexsha": "20ece37af00455ee760dcef1d583300eaa347a1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-25T12:50:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T11:14:21.000Z", "avg_line_length": 58.1819645733, "max_line_length": 469, "alphanum_fraction": 0.6784478702, "num_tokens": 8867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5028599432159376}}
{"text": "//######################################################################\n//#   Refiner Module \n//#   \n//#   Copyright (C) 2020 Siemens AG\n//#   SPDX-License-Identifier: MIT\n//#   Author 2020: This module has been developed by \n//#                Roman Kaskman under supervision of Slobodan Ilic\n//#######################################################################\n\n#include <opencv/cv.hpp>\n#include \"optimizer.h\"\n#include \"ceres/ceres.h\"\n#include \"ceres/rotation.h\"\n#include \"util.h\"\n#include <Eigen/Dense>\n#include \"correspondence_finder.h\"\n#include \"frame_payload.h\"\n#include <utility>\n\n#define GLOG_NO_ABBREVIATED_SEVERITIES\n\nusing namespace ceres;\nusing namespace std;\n\nusing ceres::AutoDiffCostFunction;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solver;\nusing ceres::Solve;\n\nstruct ModelPoseFunctor {\n\tModelPoseFunctor(Eigen::Vector2d pixel_point,  Eigen::Vector3d world_point, Eigen::Matrix3d intrinsics,\n\t\tdouble* scene_inverse_angle_axis, double* scene_pose_inverse_translation, Eigen::Vector2d rgb_edge_normal, double std_dev)\n\t\t:pixel_point(std::move(pixel_point)), world_point(std::move(world_point)), intrinsics(std::move(intrinsics)),\n\t\tscene_inverse_angle_axis(scene_inverse_angle_axis), scene_pose_inverse_translation(scene_pose_inverse_translation),\n\t\trgb_edge_normal(std::move(rgb_edge_normal)), std_dev(std_dev) {}\n\n\ttemplate <typename T>  bool operator()(const T* const rotation_to_optimize, const T* const translation_to_optimize, T* residual) const {\n\n\t\tT p[3];\n\n\t\tp[0] = T(world_point[0]);\n\t\tp[1] = T(world_point[1]);\n\t\tp[2] = T(world_point[2]);\n\n\t\tceres::AngleAxisRotatePoint(rotation_to_optimize, p, p);\n\n\t\tp[0] += translation_to_optimize[0];\n\t\tp[1] += translation_to_optimize[1];\n\t\tp[2] += translation_to_optimize[2];\n\n\t\tT scene_inverse_angle_axis_t[3];\n\t\tscene_inverse_angle_axis_t[0] = T(scene_inverse_angle_axis[0]);\n\t\tscene_inverse_angle_axis_t[1] = T(scene_inverse_angle_axis[1]);\n\t\tscene_inverse_angle_axis_t[2] = T(scene_inverse_angle_axis[2]);\n\n\t\tceres::AngleAxisRotatePoint(scene_inverse_angle_axis_t, p, p);\n\n\t\tT scene_inverse_translation_t[3];\n\t\tscene_inverse_translation_t[0] = T(scene_pose_inverse_translation[0]);\n\t\tscene_inverse_translation_t[1] = T(scene_pose_inverse_translation[1]);\n\t\tscene_inverse_translation_t[2] = T(scene_pose_inverse_translation[2]);\n\n\t\tp[0] += scene_inverse_translation_t[0];\n\t\tp[1] += scene_inverse_translation_t[1];\n\t\tp[2] += scene_inverse_translation_t[2];\n\n\t\tT predicted_x = ((T(intrinsics(0, 0))*p[0]) / p[2]) + T(intrinsics(0, 2));\n\t\tT predicted_y = ((T(intrinsics(1, 1))*p[1]) / p[2]) + T(intrinsics(1, 2));\n\n\t\tresidual[0] = ((predicted_x - T(pixel_point[0])) * T(rgb_edge_normal[0]) + \n\t\t\t(predicted_y - T(pixel_point[1])) * T(rgb_edge_normal[1])) / T(std_dev);\n\t\treturn true;\n\t}\n\n\tEigen::Vector2d pixel_point;\n\tEigen::Vector3d world_point;\n\n\tEigen::Matrix3d intrinsics;\n\tdouble* scene_inverse_angle_axis;\n\tdouble* scene_pose_inverse_translation;\n\tEigen::Vector2d rgb_edge_normal;\n\tdouble std_dev;\n};\n\n\nEigen::Matrix4d optimize_model_pose(const vector<FramePayload> &frame_payloads, const Eigen::Matrix4d &model_pose, const Eigen::Matrix3d &intrinsics, double residuals_std_dev)\n{\n\tdouble* angle_axis_to_optimize = new double[3];\n\tdouble* translation_to_optimize = new double[3];\n\n\tEigen::Matrix3d model_rotation = model_pose.block<3, 3>(0, 0);\n\tEigen::Vector3d model_translation = model_pose.block<3, 1>(0, 3);\n\n\tceres::RotationMatrixToAngleAxis(model_rotation.data(), angle_axis_to_optimize);\n\tmemcpy(translation_to_optimize, model_translation.data(), 3 * sizeof(double));\n\n\tstd::cout << \"angle axis : \" << angle_axis_to_optimize[0]\n\t\t<< \" -> \" << angle_axis_to_optimize[1]\n\t\t<< \" -> \" << angle_axis_to_optimize[2]\n\t\t<< \", translation \" << translation_to_optimize[0]\n\t\t<< \" -> \" << translation_to_optimize[1]\n\t\t<< \" -> \" << translation_to_optimize[2] << \"\\n\";\n\n\tProblem problem;\n\n\tvector<double*> angle_axis_scene_invere_rotations;\n\tvector<double*> scene_invere_translations;\n\tcout << \"Residuals std dev: \" << residuals_std_dev << endl;\n\n\tfor (const FramePayload &payload : frame_payloads)\n\t{\n\t\tconst Correspondence &correspondence = payload.correspondence;\n\n\t\tEigen::Matrix4d scene_pose_inverse = payload.scene_pose.inverse();\n\n\t\tEigen::Matrix3d scene_pose_inverse_rotation = scene_pose_inverse.block<3, 3>(0, 0);\n\t\tEigen::Vector3d scene_pose_inverse_translation = scene_pose_inverse.block<3, 1>(0, 3);\n\n\t\tdouble* angle_axis_scene_inverse = new double[3];\n\t\tceres::RotationMatrixToAngleAxis(scene_pose_inverse_rotation.data(), angle_axis_scene_inverse);\n\n\t\tdouble* scene_pose_inverse_translation_array = new double[3];\n\t\tmemcpy(scene_pose_inverse_translation_array, scene_pose_inverse_translation.data(), 3 * sizeof(double));\n\n\t\tangle_axis_scene_invere_rotations.push_back(angle_axis_scene_inverse);\n\t\tscene_invere_translations.push_back(scene_pose_inverse_translation_array);\n\n\t\tfor (int i = 0; i < correspondence.get_number_of_correspondences(); i++) {\n\t\t\tauto pixel_point = correspondence.corresponding_points[i].cast<double>();\n\t\t\tauto world_point = correspondence.world_points[i].cast<double>();\n\n\t\t\tEigen::Vector2d rgb_edge_normal = correspondence.get_rgb_normal(i).cast<double>();\n\n\t\t\tCostFunction *cost_function =\n\t\t\t\tnew AutoDiffCostFunction<ModelPoseFunctor, 1, 3, 3>(new ModelPoseFunctor(pixel_point, world_point, intrinsics,\n\t\t\t\t\tangle_axis_scene_inverse, scene_pose_inverse_translation_array,\n\t\t\t\t\trgb_edge_normal, residuals_std_dev));\n\n\t\t\tTukeyLoss* loss_function = new TukeyLoss(4.365);\n\t\t\tproblem.AddResidualBlock(cost_function, loss_function, angle_axis_to_optimize, translation_to_optimize);\n\t\t}\n\t}\n\n\t// run the solver\n\tSolver::Options options;\n\toptions.minimizer_progress_to_stdout = false;\n\toptions.max_num_iterations = 100;\n\tSolver::Summary summary;\n\tceres::Solve(options, &problem, &summary);\n\tstd::cout << summary.BriefReport() << \"\\n\";\n\n\tstd::cout << \"optimized angle axis : \" << angle_axis_to_optimize[0]\n\t\t<< \" -> \" << angle_axis_to_optimize[1]\n\t\t<< \" -> \" << angle_axis_to_optimize[2]\n\t\t<< \", optimized translation \" << translation_to_optimize[0]\n\t\t<< \" -> \" << translation_to_optimize[1]\n\t\t<< \" -> \" << translation_to_optimize[2] << \"\\n\";\n\n\tdouble optimal_rotation_matrix_array[9];\n\tceres::AngleAxisToRotationMatrix(angle_axis_to_optimize, optimal_rotation_matrix_array);\n\n\tEigen::Matrix3d rotation_matrix = Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::ColMajor>>(optimal_rotation_matrix_array);\n\tEigen::Vector3d translation_vector = Eigen::Map<Eigen::Matrix<double, 3, 1, Eigen::ColMajor>>(translation_to_optimize);\n\n\tdelete[] angle_axis_to_optimize;\n\tdelete[] translation_to_optimize;\n\n\tfor (auto &arr : angle_axis_scene_invere_rotations) {\n\t\tdelete[] arr;\n\t}\n\n\tfor (auto &arr : scene_invere_translations) {\n\t\tdelete[] arr;\n\t}\n\n\treturn create_transformation(rotation_matrix, translation_vector);\n}\n", "meta": {"hexsha": "c69dbb2f8961c8945d323c5be0c524ae5c38973d", "size": 6831, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "refiner/src/optimizer.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": "refiner/src/optimizer.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": "refiner/src/optimizer.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": 38.1620111732, "max_line_length": 175, "alphanum_fraction": 0.7372273459, "num_tokens": 1788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5028599388372956}}
{"text": "#include <NTL/ZZ.h>\n#include <vector>\n#include \"constants.h\"\n#include \"generalhelpers.h\"\n\nnamespace CryptoHelpers\n{\n    std::vector<NTL::ZZ> g_roundKeys(4);\n    std::vector<unsigned long long> g_roundKeysInt(4);\n\n    void RoundFunction(NTL::ZZ& input, const NTL::ZZ& key)\n    {\n        input ^= key;\n\n        NTL::ZZ newRightHalf(0);\n\n        for (auto byteIndex = 0u; byteIndex < 4; ++byteIndex)\n        {\n            unsigned char byte = 0;\n            NTL::BytesFromZZ(&byte, (input >> (8 * byteIndex)) & 0xFF, 1);\n            newRightHalf |= SBOX[byte] << (8 * byteIndex);\n        }\n        auto shift = (newRightHalf >> 4) & 0xFFF8000;\n        shift <<= 4;\n        newRightHalf <<= 13;\n        newRightHalf |= shift;\n        newRightHalf = And32Bits(newRightHalf);\n\n        input = 0;\n        input |= newRightHalf;\n    }\n\n    template <typename T>\n    T reverse(T n, size_t b = sizeof(T) * 8)\n    {\n        //        assert(b <= std::numeric_limits<T>::digits);\n\n        T rv = 0;\n\n        for (size_t i = 0; i < b; ++i, n >>= 1)\n            rv = (rv >> 1) | (n & 0x01);\n\n        return rv;\n    }\n\n    void RoundFunction(const unsigned long long& _input, const unsigned long long& key, unsigned long long& result, bool b = true)\n    {\n        auto input = _input ^ key;\n\n        unsigned long long newRightHalf(0);\n\n        for (auto byteIndex = 0u; byteIndex < 4; ++byteIndex)\n        {\n            //newRightHalf <<= 8;\n            newRightHalf |= SBOX[(input >> (8 * byteIndex)) & 0xFF] << (8 * byteIndex);\n        }\n\n        auto shift = newRightHalf & 0xFFF80000;\n        shift >>= 19;\n        newRightHalf <<= 13;\n        newRightHalf |= shift;\n        newRightHalf = (newRightHalf) & 0xFFFFFFFF;\n\n        result = newRightHalf;\n    }\n\n    void GenerateRoundKeys(const NTL::ZZ& key)\n    {\n        g_roundKeys[0] = And32Bits(key);\n        g_roundKeys[1] = And32Bits(key >> 32);\n        g_roundKeys[2] = Xor32Bits(g_roundKeys[0]);\n        g_roundKeys[3] = Xor32Bits(g_roundKeys[1]);\n    }\n\n    void GenerateRoundKeys(const unsigned long long& key)\n    {\n        g_roundKeysInt[0] = (key >> 32) & 0xFFFFFFFF;\n        g_roundKeysInt[1] = key & 0xFFFFFFFF;\n        ReverseBytes(4,g_roundKeysInt[0]);\n        ReverseBytes(4,g_roundKeysInt[1]);\n        g_roundKeysInt[2] = (g_roundKeysInt[1] ^ 0xFFFFFFFF);\n        g_roundKeysInt[3] = (g_roundKeysInt[0] ^ 0xFFFFFFFF);\n    }\n\n    void GenerateKeys(const NTL::ZZ* _key = nullptr)\n    {\n        if (!_key)\n        {\n            auto rand = NTL::GetCurrentRandomStream();\n            std::vector<unsigned char> randomValue(8);\n            rand.get(randomValue.data(), 8);\n            NTL::ZZ key(0);\n            NTL::ZZFromBytes(key, randomValue.data(), 8);\n            GenerateRoundKeys(key);\n            return;\n        }\n        GenerateRoundKeys(*_key);\n    }\n\n    void GenerateKeys(const unsigned long long* _key = nullptr)\n    {\n        if (!_key)\n        {\n            //auto rand = NTL::GetCurrentRandomStream();\n            //std::vector<unsigned char> randomValue(8);\n            //rand.get(randomValue.data(), 8);\n            //NTL::ZZ key(0);\n            //NTL::ZZFromBytes(key, randomValue.data(), 8);\n            //GenerateRoundKeys(key);\n            return;\n        }\n        GenerateRoundKeys(*_key);\n    }\n\n    void Encrypt(const NTL::ZZ & source, NTL::ZZ & target, const NTL::ZZ* key = nullptr)\n    {\n        GenerateKeys(key);\n        auto rightHalf = And32Bits(source);\n        auto leftHalf = And32Bits(source >> 32);\n        target = 0;\n        for (auto roundIndex = 0u; roundIndex < 4; ++roundIndex)\n        {\n            RoundFunction(rightHalf, g_roundKeys[roundIndex]);\n            rightHalf ^= leftHalf;\n            std::swap(rightHalf, leftHalf);\n        }\n\n        std::swap(rightHalf, leftHalf);\n\n        target += 0;\n        target |= rightHalf;\n        target |= leftHalf << 32;\n    }\n\n    void ResetKey()\n    {\n        for (auto& key : g_roundKeys)\n        {\n            key = 0;\n        }\n    }\n\n    \n    void Encrypt(const unsigned long long& source, unsigned long long& target, const unsigned long long* key = nullptr)\n    {\n        GenerateKeys(key);\n\n        auto rightHalf = (source>>32) & 0xFFFFFFFF;\n        auto leftHalf = source & 0xFFFFFFFF;\n        ReverseBytes(4, rightHalf);\n        ReverseBytes(4, leftHalf);\n        std::swap(rightHalf, leftHalf);\n        target = 0;\n        for (auto roundIndex = 0u; roundIndex < 4; ++roundIndex)\n        {\n            auto tmp = 0ull;\n            RoundFunction(rightHalf, g_roundKeysInt[roundIndex], tmp);\n            tmp ^= leftHalf;\n            rightHalf = leftHalf;\n            leftHalf = tmp;\n        }\n\n        std::swap(rightHalf, leftHalf);\n\n        target |= rightHalf<<32;\n        target |= leftHalf;\n        ReverseBytes(8,target);\n    }\n\n}\n", "meta": {"hexsha": "1c68ddc07465c8fe9676343faa2016a678279df9", "size": 4790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lab2/encryption.cpp", "max_stars_repo_name": "mikhaelmurmur/SimpleHash", "max_stars_repo_head_hexsha": "effb2a4da93ce7c59eb36c5057ea868ba02042ac", "max_stars_repo_licenses": ["MIT"], "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/encryption.cpp", "max_issues_repo_name": "mikhaelmurmur/SimpleHash", "max_issues_repo_head_hexsha": "effb2a4da93ce7c59eb36c5057ea868ba02042ac", "max_issues_repo_licenses": ["MIT"], "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/encryption.cpp", "max_forks_repo_name": "mikhaelmurmur/SimpleHash", "max_forks_repo_head_hexsha": "effb2a4da93ce7c59eb36c5057ea868ba02042ac", "max_forks_repo_licenses": ["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.0116959064, "max_line_length": 130, "alphanum_fraction": 0.5411273486, "num_tokens": 1294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.5027658913270917}}
{"text": "#pragma once\n\n#ifdef QP_SOLVER_SPARSE\n#include <Eigen/Sparse>\n#endif\n\n#include <Eigen/Dense>\n#include <limits>\n#include <vector>\n\n#define QP_SOLVER_PRINTING\n\nnamespace qp_solver {\n\n/** Quadratic Problem\n *  minimize        0.5 x' P x + q' x\n *  subject to      l <= A x <= u\n */\ntemplate <typename Scalar = double>\nstruct QuadraticProblem {\n    using Vector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n#ifdef QP_SOLVER_SPARSE\n    using Matrix = Eigen::SparseMatrix<Scalar>;\n    Eigen::Matrix<int, Eigen::Dynamic, 1> P_col_nnz;\n    Eigen::Matrix<int, Eigen::Dynamic, 1> A_col_nnz;\n#else\n    using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n#endif\n    const Matrix *P;\n    const Vector *q;\n    const Matrix *A;\n    const Vector *l;\n    const Vector *u;\n};\n\ntemplate <typename Scalar>\nstruct QPSolverSettings {\n    Scalar rho = 1e-1;          /**< ADMM rho step, 0 < rho */\n    Scalar sigma = 1e-6;        /**< ADMM sigma step, 0 < sigma, (small) */\n    Scalar alpha = 1.0;         /**< ADMM overrelaxation parameter, 0 < alpha < 2,\n                                     values in [1.5, 1.8] give good results (empirically) */\n    Scalar eps_rel = 1e-3;      /**< Relative tolerance for termination, 0 < eps_rel */\n    Scalar eps_abs = 1e-3;      /**< Absolute tolerance for termination, 0 < eps_abs */\n    int max_iter = 1000;        /**< Maximal number of iteration, 0 < max_iter */\n    int check_termination = 25; /**< Check termination after every Nth iteration, 0 (disabled) or 0\n                                   < check_termination */\n    bool warm_start = false;    /**< Warm start solver, reuses previous x,z,y */\n    bool adaptive_rho = false;  /**< Adapt rho to optimal estimate */\n    Scalar adaptive_rho_tolerance =\n        5; /**< Minimal for rho update factor, 1 < adaptive_rho_tolerance */\n    int adaptive_rho_interval = 25; /**< change rho every Nth iteration, 0 < adaptive_rho_interval,\n                                         set equal to check_termination to save computation  */\n    bool verbose = false;\n\n#ifdef QP_SOLVER_PRINTING\n    void print() const {\n        printf(\"ADMM settings:\\n\");\n        printf(\"  sigma %.2e\\n\", sigma);\n        printf(\"  rho %.2e\\n\", rho);\n        printf(\"  alpha %.2f\\n\", alpha);\n        printf(\"  eps_rel %.1e\\n\", eps_rel);\n        printf(\"  eps_abs %.1e\\n\", eps_abs);\n        printf(\"  max_iter %d\\n\", max_iter);\n        printf(\"  adaptive_rho %d\\n\", adaptive_rho);\n        printf(\"  warm_start %d\\n\", warm_start);\n    }\n#endif\n};\n\ntypedef enum { SOLVED, MAX_ITER_EXCEEDED, UNSOLVED, NUMERICAL_ISSUES, UNINITIALIZED } QPSolverStatus;\n\ntemplate <typename Scalar>\nstruct QPSolverInfo {\n    QPSolverStatus status = UNINITIALIZED; /**< Solver status */\n    int iter = 0;                          /**< Number of iterations */\n    int rho_updates = 0;                   /**< Number of rho updates (factorizations) */\n    Scalar rho_estimate = 0;               /**< Last rho estimate */\n    Scalar res_prim = 0;                   /**< Primal residual */\n    Scalar res_dual = 0;                   /**< Dual residual */\n\n#ifdef QP_SOLVER_PRINTING\n    void print() const {\n        printf(\"ADMM info:\\n\");\n        printf(\"  status \");\n        switch (status) {\n            case SOLVED:\n                printf(\"SOLVED\\n\");\n                break;\n            case MAX_ITER_EXCEEDED:\n                printf(\"MAX_ITER_EXCEEDED\\n\");\n                break;\n            case UNSOLVED:\n                printf(\"UNSOLVED\\n\");\n                break;\n            case NUMERICAL_ISSUES:\n                printf(\"NUMERICAL_ISSUES\\n\");\n                break;\n            default:\n                printf(\"UNINITIALIZED\\n\");\n        };\n        printf(\"  iter %d\\n\", iter);\n        printf(\"  rho_updates %d\\n\", rho_updates);\n        printf(\"  rho_estimate %f\\n\", rho_estimate);\n        printf(\"  res_prim %f\\n\", res_prim);\n        printf(\"  res_dual %f\\n\", res_dual);\n    }\n#endif\n};\n\n/**\n *  minimize        0.5 x' P x + q' x\n *  subject to      l <= A x <= u\n *\n *  with:\n *    x element of R^n\n *    Ax element of R^m\n */\ntemplate <typename SCALAR>\nclass QPSolver {\n   public:\n    using Scalar = SCALAR;\n    using QP = QuadraticProblem<Scalar>;\n    using Vector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n#ifdef QP_SOLVER_SPARSE\n    using Matrix = Eigen::SparseMatrix<Scalar, Eigen::ColMajor>;\n    using LinearSolver = Eigen::SimplicialLDLT<Matrix, Eigen::Lower>;\n#else\n    using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using LinearSolver = Eigen::LDLT<Matrix, Eigen::Lower>;\n#endif\n    using Settings = QPSolverSettings<Scalar>;\n    using Info = QPSolverInfo<Scalar>;\n\n    enum { INEQUALITY_CONSTRAINT, EQUALITY_CONSTRAINT, LOOSE_BOUNDS } ConstraintType;\n\n    static constexpr Scalar RHO_MIN = 1e-6;\n    static constexpr Scalar RHO_MAX = 1e+6;\n    static constexpr Scalar RHO_TOL = 1e-4;\n    static constexpr Scalar RHO_EQ_FACTOR = 1e+3;\n    static constexpr Scalar LOOSE_BOUNDS_THRESH = 1e+16;\n    static constexpr Scalar DIV_BY_ZERO_REGUL = std::numeric_limits<Scalar>::epsilon();\n\n    // enforce 16 byte alignment\n    // https://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    /** Constructor */\n    QPSolver() = default;\n\n    /** Setup solver for QP. */\n    void setup(const QP &qp);\n\n    /** Update solver for QP of same size as initial setup. */\n    void update_qp(const QP &qp);\n\n    /** Solve the QP. */\n    void solve(const QP &qp);\n\n    inline const Vector &primal_solution() const { return x; }\n    inline Vector &primal_solution() { return x; }\n\n    inline const Vector &dual_solution() const { return y; }\n    inline Vector &dual_solution() { return y; }\n\n    inline const Settings &settings() const { return settings_; }\n    inline Settings &settings() { return settings_; }\n\n    inline const Info &info() const { return info_; }\n    inline Info &info() { return info_; }\n\n\n    /* Public funcitions for unit testing */\n    static void constr_type_init(const Vector& l, const Vector& u, Eigen::VectorXi &constr_type);\n\n   private:\n    /* Construct the KKT matrix of the form\n     *\n     * [[ P + sigma*I,        A' ],\n     *  [ A,           -1/rho.*I ]]\n     *\n     * If LinearSolver_UpLo parameter is Eigen::Lower, then only the lower\n     * triangular part is constructed to optimize memory.\n     *\n     * Note: For Eigen::ConjugateGradient it is advised to set Upper|Lower for\n     *       best performance.\n     */\n    void construct_KKT_mat(const QP &qp);\n\n    /** KKT matrix value update, assumes same sparsity pattern */\n    void update_KKT_mat(const QP &qp);\n\n    void update_KKT_rho();\n    bool factorize_KKT();\n    bool compute_KKT();\n#ifdef QP_SOLVER_SPARSE\n    void sparse_insert_at(Matrix &dst, int row, int col, const Matrix &src) const\n#endif\n        void form_KKT_rhs(const QP &qp, Vector &rhs);\n\n    void box_projection(Vector &z, const Vector &l, const Vector &u);\n\n    void constr_type_init(const QP &qp);\n    void rho_vec_update(Scalar rho0);\n    void update_state(const QP &qp);\n    Scalar rho_estimate(const Scalar rho0, const QP &qp) const;\n    Scalar eps_prim(const QP &qp) const;\n    Scalar eps_dual(const QP &qp) const;\n    Scalar residual_prim(const QP &qp) const;\n    Scalar residual_dual(const QP &qp) const;\n\n    bool termination_criteria(const QP &qp);\n\n#ifdef QP_SOLVER_PRINTING\n    void print_status(const QP &qp) const;\n#endif\n\n    size_t n;  //< number of variables\n    size_t m;  //< number of constraints\n\n    // Solver state variables\n    int iter;\n    Vector x;  //< primal variable, size n\n    Vector z;  //< additional variable, size m\n    Vector y;  //< dual variable, size m\n    Vector x_tilde;\n    Vector z_tilde;\n    Vector z_prev;\n    Vector rho_vec;\n    Vector rho_inv_vec;\n    Scalar rho;\n\n    Vector rhs;\n    Vector x_tilde_nu;\n\n    // State\n    Scalar res_prim;\n    Scalar res_dual;\n    Scalar max_Ax_z_norm_;\n    Scalar max_Px_ATy_q_norm_;\n\n    Eigen::VectorXi constr_type; /**< constraint type classification */\n\n    Settings settings_;\n    Info info_;\n\n    Matrix kkt_mat;\n    LinearSolver linear_solver;\n};\n\nextern template class QPSolver<double>;\nextern template class QPSolver<float>;\n\n}  // namespace qp_solver\n", "meta": {"hexsha": "553ead4c891bb6ab544067a85dd9d2fdc0170a76", "size": 8219, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/solvers/qp.hpp", "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": "include/solvers/qp.hpp", "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": "include/solvers/qp.hpp", "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": 32.3582677165, "max_line_length": 101, "alphanum_fraction": 0.6220951454, "num_tokens": 2093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5027440343627121}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2009 - 2021 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 * Authors: Katharina Kormann, Martin Kronbichler, Uppsala University, \n * 2009-2012, updated to MPI version with parallel vectors in 2016 \n */ \n\n\n\n// \u9996\u5148\u5305\u62ecdeal.II\u5e93\u4e2d\u7684\u5fc5\u8981\u6587\u4ef6\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/timer.h> \n\n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/la_parallel_vector.h> \n#include <deal.II/lac/precondition.h> \n\n#include <deal.II/fe/fe_q.h> \n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n\n#include <deal.II/multigrid/multigrid.h> \n#include <deal.II/multigrid/mg_transfer_matrix_free.h> \n#include <deal.II/multigrid/mg_tools.h> \n#include <deal.II/multigrid/mg_coarse.h> \n#include <deal.II/multigrid/mg_smoother.h> \n#include <deal.II/multigrid/mg_matrix.h> \n\n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/vector_tools.h> \n\n// \u8fd9\u5305\u62ec\u6709\u6548\u5b9e\u73b0\u65e0\u77e9\u9635\u65b9\u6cd5\u7684\u6570\u636e\u7ed3\u6784\uff0c\u6216\u8005\u7528MatrixFree\u7c7b\u7684\u66f4\u901a\u7528\u7684\u6709\u9650\u5143\u7b97\u5b50\u3002\n\n#include <deal.II/matrix_free/matrix_free.h> \n#include <deal.II/matrix_free/operators.h> \n#include <deal.II/matrix_free/fe_evaluation.h> \n\n#include <iostream> \n#include <fstream> \n\nnamespace Step37 \n{ \n  using namespace dealii; \n\n// \u4e3a\u4e86\u63d0\u9ad8\u6548\u7387\uff0c\u5728\u65e0\u77e9\u9635\u5b9e\u73b0\u4e2d\u8fdb\u884c\u7684\u64cd\u4f5c\u9700\u8981\u5728\u7f16\u8bd1\u65f6\u4e86\u89e3\u5faa\u73af\u957f\u5ea6\uff0c\u8fd9\u4e9b\u957f\u5ea6\u662f\u7531\u6709\u9650\u5143\u7684\u5ea6\u6570\u7ed9\u51fa\u7684\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u6536\u96c6\u4e86\u4e24\u4e2a\u6a21\u677f\u53c2\u6570\u7684\u503c\uff0c\u53ef\u4ee5\u5728\u4ee3\u7801\u4e2d\u7684\u4e00\u4e2a\u5730\u65b9\u6539\u53d8\u3002\u5f53\u7136\uff0c\u6211\u4eec\u53ef\u4ee5\u628a\u6709\u9650\u5143\u7684\u5ea6\u6570\u4f5c\u4e3a\u4e00\u4e2a\u8fd0\u884c\u65f6\u7684\u53c2\u6570\uff0c\u901a\u8fc7\u7f16\u8bd1\u6240\u6709\u53ef\u80fd\u7684\u5ea6\u6570\uff08\u6bd4\u5982\uff0c1\u52306\u4e4b\u95f4\uff09\u7684\u8ba1\u7b97\u6838\uff0c\u5e76\u5728\u8fd0\u884c\u65f6\u9009\u62e9\u5408\u9002\u7684\u6838\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u53ea\u662f\u9009\u62e9\u4e8c\u9636 $Q_2$ \u5143\u7d20\uff0c\u5e76\u9009\u62e9\u7ef4\u5ea63\u4f5c\u4e3a\u6807\u51c6\u3002\n\n  const unsigned int degree_finite_element = 2; \n  const unsigned int dimension             = 3; \n// @sect3{Equation data}  \n\n// \u6211\u4eec\u4e3a\u6cca\u677e\u95ee\u9898\u5b9a\u4e49\u4e86\u4e00\u4e2a\u53ef\u53d8\u7cfb\u6570\u51fd\u6570\u3002\u5b83\u4e0e step-5 \u4e2d\u7684\u51fd\u6570\u7c7b\u4f3c\uff0c\u4f46\u6211\u4eec\u4f7f\u7528 $a(\\mathbf x)=\\frac{1}{0.05 + 2\\|\\bf x\\|^2}$ \u7684\u5f62\u5f0f\uff0c\u800c\u4e0d\u662f\u4e0d\u8fde\u7eed\u7684\u5f62\u5f0f\u3002\u8fd9\u53ea\u662f\u4e3a\u4e86\u8bc1\u660e\u8fd9\u79cd\u5b9e\u73b0\u7684\u53ef\u80fd\u6027\uff0c\u800c\u4e0d\u662f\u5728\u7269\u7406\u4e0a\u6709\u4ec0\u4e48\u610f\u4e49\u3002\u6211\u4eec\u5b9a\u4e49\u7cfb\u6570\u7684\u65b9\u5f0f\u4e0e\u65e9\u671f\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u7684\u51fd\u6570\u76f8\u540c\u3002\u6709\u4e00\u4e2a\u65b0\u7684\u51fd\u6570\uff0c\u5373\u6709\u6a21\u677f\u53c2\u6570 @p value \u7684 @p number. \u65b9\u6cd5\u3002\ntemplate <int dim> \n  class Coefficient : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n\n    template <typename number> \n    number value(const Point<dim, number> &p, \n                 const unsigned int        component = 0) const; \n  }; \n\n// \u8fd9\u5c31\u662f\u4e0a\u9762\u63d0\u5230\u7684\u65b0\u51fd\u6570\u3002\u8bc4\u4f30\u62bd\u8c61\u7c7b\u578b\u7684\u7cfb\u6570  @p number.  \u5b83\u53ef\u80fd\u53ea\u662f\u4e00\u4e2a\u666e\u901a\u7684\u53cc\u6570\uff0c\u4f46\u4e5f\u53ef\u80fd\u662f\u4e00\u4e2a\u6709\u70b9\u590d\u6742\u7684\u7c7b\u578b\uff0c\u6211\u4eec\u79f0\u4e4b\u4e3aVectorizedArray\u3002\u8fd9\u79cd\u6570\u636e\u7c7b\u578b\u672c\u8d28\u4e0a\u662f\u4e00\u4e2a\u77ed\u7684\u53cc\u6570\u6570\u7ec4\uff0c\u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\u90a3\u6837\uff0c\u5b83\u53ef\u4ee5\u5bb9\u7eb3\u51e0\u4e2a\u5355\u5143\u683c\u7684\u6570\u636e\u3002\u4f8b\u5982\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u8bc4\u4f30\u7684\u7cfb\u6570\u4e0d\u662f\u50cf\u901a\u5e38\u90a3\u6837\u5728\u4e00\u4e2a\u7b80\u5355\u7684\u70b9\u4e0a\uff0c\u800c\u662f\u4ea4\u7ed9\u4e00\u4e2aPoint<dim,VectorizedArray<double>>\u70b9\uff0c\u5728AVX\u7684\u60c5\u51b5\u4e0b\uff0c\u5b83\u5b9e\u9645\u4e0a\u662f\u56db\u4e2a\u70b9\u7684\u96c6\u5408\u3002\u4e0d\u8981\u628aVectorizedArray\u4e2d\u7684\u6761\u76ee\u4e0e\u70b9\u7684\u4e0d\u540c\u5750\u6807\u6df7\u6dc6\u3002\u4e8b\u5b9e\u4e0a\uff0c\u6570\u636e\u7684\u5e03\u5c40\u662f\u8fd9\u6837\u7684\uff1a <code>p[0]</code> \u8fd4\u56de\u4e00\u4e2aVectorizedArray\uff0c\u5b83\u53c8\u5305\u542b\u4e86\u7b2c\u4e00\u4e2a\u70b9\u548c\u7b2c\u4e8c\u4e2a\u70b9\u7684x\u5750\u6807\u3002\u4f60\u53ef\u4ee5\u4f7f\u7528\u4f8b\u5982  <code>p[0][j]</code>  \u5355\u72ec\u8bbf\u95ee\u5750\u6807\uff0cj=0,1,2,3\uff0c\u4f46\u5efa\u8bae\u5c3d\u53ef\u80fd\u5728\u4e00\u4e2aVectorizedArray\u4e0a\u5b9a\u4e49\u64cd\u4f5c\uff0c\u4ee5\u4fbf\u5229\u7528\u77e2\u91cf\u64cd\u4f5c\u3002\n\n// \u5728\u51fd\u6570\u7684\u5b9e\u73b0\u4e2d\uff0c\u6211\u4eec\u5047\u8bbe\u6570\u5b57\u7c7b\u578b\u91cd\u8f7d\u4e86\u57fa\u672c\u7684\u7b97\u672f\u8fd0\u7b97\uff0c\u6240\u4ee5\u6211\u4eec\u53ea\u9700\u7167\u5e38\u5199\u4ee3\u7801\u3002\u7136\u540e\uff0c\u57fa\u7c7b\u51fd\u6570 @p value \u662f\u7531\u5e26\u6709\u53cc\u500d\u7c7b\u578b\u7684\u6a21\u677f\u51fd\u6570\u8ba1\u7b97\u51fa\u6765\u7684\uff0c\u4ee5\u907f\u514d\u91cd\u590d\u4ee3\u7801\u3002\n\n  template <int dim> \n  template <typename number> \n  number Coefficient<dim>::value(const Point<dim, number> &p, \n                                 const unsigned int /*component*/) const \n  { \n    return 1. / (0.05 + 2. * p.square()); \n  } \n\n  template <int dim> \n  double Coefficient<dim>::value(const Point<dim> & p, \n                                 const unsigned int component) const \n  { \n    return value<double>(p, component); \n  } \n// @sect3{Matrix-free implementation}  \n\n// \u4e0b\u9762\u8fd9\u4e2a\u540d\u4e3a <code>LaplaceOperator</code> \u7684\u7c7b\uff0c\u5b9e\u73b0\u4e86\u5fae\u5206\u8fd0\u7b97\u7b26\u3002\u5c31\u6240\u6709\u7684\u5b9e\u7528\u76ee\u7684\u800c\u8a00\uff0c\u5b83\u662f\u4e00\u4e2a\u77e9\u9635\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u4f60\u53ef\u4ee5\u5411\u5b83\u8be2\u95ee\u5b83\u7684\u5927\u5c0f\uff08\u6210\u5458\u51fd\u6570  <code>m(), n()</code>  \uff09\uff0c\u4f60\u53ef\u4ee5\u5c06\u5b83\u5e94\u7528\u4e8e\u4e00\u4e2a\u77e2\u91cf\uff08 <code>vmult()</code>  \u51fd\u6570\uff09\u3002\u5f53\u7136\uff0c\u4e0e\u5b9e\u6570\u77e9\u9635\u7684\u533a\u522b\u5728\u4e8e\uff0c\u8fd9\u4e2a\u7c7b\u5b9e\u9645\u4e0a\u5e76\u4e0d\u5b58\u50a8\u77e9\u9635\u7684<i>elements</i>\uff0c\u800c\u53ea\u77e5\u9053\u5982\u4f55\u8ba1\u7b97\u8fd0\u7b97\u5668\u5e94\u7528\u4e8e\u5411\u91cf\u65f6\u7684\u52a8\u4f5c\u3002\n\n// \u63cf\u8ff0\u77e9\u9635\u5927\u5c0f\u7684\u57fa\u7840\u7ed3\u6784\uff0c\u6765\u81eaMatrixFree\u5bf9\u8c61\u7684\u521d\u59cb\u5316\uff0c\u4ee5\u53ca\u901a\u8fc7vmult()\u548cTvmult()\u65b9\u6cd5\u5b9e\u73b0\u77e9\u9635-\u5411\u91cf\u4e58\u79ef\u7684\u5404\u79cd\u63a5\u53e3\uff0c\u662f\u7531\u672c\u7c7b\u6d3e\u751f\u7684 MatrixFreeOperator::Base \u7c7b\u63d0\u4f9b\u7684\u3002\u8fd9\u91cc\u5b9a\u4e49\u7684LaplaceOperator\u7c7b\u53ea\u9700\u8981\u63d0\u4f9b\u51e0\u4e2a\u63a5\u53e3\uff0c\u5373\u901a\u8fc7vmult()\u51fd\u6570\u4e2d\u4f7f\u7528\u7684apply_add()\u65b9\u6cd5\u6765\u5b9e\u73b0\u8fd0\u7b97\u7b26\u7684\u5b9e\u9645\u64cd\u4f5c\uff0c\u4ee5\u53ca\u8ba1\u7b97\u5e95\u5c42\u77e9\u9635\u5bf9\u89d2\u7ebf\u9879\u7684\u65b9\u6cd5\u3002\u6211\u4eec\u9700\u8981\u5bf9\u89d2\u7ebf\u6765\u5b9a\u4e49\u591a\u68af\u5ea6\u5e73\u6ed1\u5668\u3002\u7531\u4e8e\u6211\u4eec\u8003\u8651\u7684\u662f\u4e00\u4e2a\u5177\u6709\u53ef\u53d8\u7cfb\u6570\u7684\u95ee\u9898\uff0c\u6211\u4eec\u8fdb\u4e00\u6b65\u5b9e\u73b0\u4e86\u4e00\u4e2a\u53ef\u4ee5\u586b\u5145\u7cfb\u6570\u503c\u7684\u65b9\u6cd5\u3002\n\n// \u6ce8\u610f\u6587\u4ef6 <code>include/deal.II/matrix_free/operators.h</code> \u5df2\u7ecf\u5305\u542b\u4e86\u901a\u8fc7\u7c7b MatrixFreeOperators::LaplaceOperator. \u5bf9\u62c9\u666e\u62c9\u65af\u7684\u5b9e\u73b0\u3002 \u51fa\u4e8e\u6559\u80b2\u76ee\u7684\uff0c\u672c\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u91cd\u65b0\u5b9e\u73b0\u4e86\u8be5\u8fd0\u7b97\u7b26\uff0c\u89e3\u91ca\u4e86\u5176\u4e2d\u7684\u6210\u5206\u548c\u6982\u5ff5\u3002\n\n// \u8fd9\u4e2a\u7a0b\u5e8f\u5229\u7528\u4e86\u96c6\u6210\u5728deal.II\u4e2d\u7684\u6709\u9650\u5143\u7b97\u5b50\u5e94\u7528\u7684\u6570\u636e\u7f13\u5b58\u3002\u8fd9\u4e2a\u6570\u636e\u7f13\u5b58\u7c7b\u88ab\u79f0\u4e3aMatrixFree\u3002\u5b83\u5305\u542b\u5c40\u90e8\u548c\u5168\u5c40\u81ea\u7531\u5ea6\u4e4b\u95f4\u7684\u6620\u5c04\u4fe1\u606f\uff08Jacobian\uff09\u548c\u7d22\u5f15\u5173\u7cfb\u3002\u5b83\u8fd8\u5305\u542b\u7ea6\u675f\u6761\u4ef6\uff0c\u5982\u6765\u81ea\u60ac\u6302\u8282\u70b9\u6216\u8fea\u91cc\u5207\u7279\u8fb9\u754c\u6761\u4ef6\u7684\u7ea6\u675f\u3002\u6b64\u5916\uff0c\u5b83\u53ef\u4ee5\u5728\u6240\u6709\u5355\u5143\u4e0a\u4ee5%\u5e76\u884c\u65b9\u5f0f\u53d1\u51fa\u4e00\u4e2a\u5faa\u73af\uff0c\u786e\u4fdd\u53ea\u6709\u4e0d\u5171\u4eab\u4efb\u4f55\u81ea\u7531\u5ea6\u7684\u5355\u5143\u88ab\u5904\u7406\uff08\u8fd9\u4f7f\u5f97\u5faa\u73af\u5728\u5199\u5165\u76ee\u6807\u5411\u91cf\u65f6\u662f\u7ebf\u7a0b\u5b89\u5168\u7684\uff09\u3002\u4e0e @ref threads \u6a21\u5757\u4e2d\u63cf\u8ff0\u7684WorkStream\u7c7b\u76f8\u6bd4\uff0c\u8fd9\u662f\u4e00\u4e2a\u66f4\u5148\u8fdb\u7684\u7b56\u7565\u3002\u5f53\u7136\uff0c\u4e3a\u4e86\u4e0d\u7834\u574f\u7ebf\u7a0b\u5b89\u5168\uff0c\u6211\u4eec\u5728\u5199\u8fdb\u7c7b\u5168\u5c40\u7ed3\u6784\u65f6\u5fc5\u987b\u5c0f\u5fc3\u3002\n\n// \u5b9e\u73b0\u62c9\u666e\u62c9\u65af\u7b97\u5b50\u7684\u7c7b\u6709\u4e09\u4e2a\u6a21\u677f\u53c2\u6570\uff0c\u4e00\u4e2a\u662f\u7ef4\u5ea6\uff08\u6b63\u5982\u8bb8\u591adeal.II\u7c7b\u6240\u643a\u5e26\u7684\uff09\uff0c\u4e00\u4e2a\u662f\u6709\u9650\u5143\u7684\u5ea6\u6570\uff08\u6211\u4eec\u9700\u8981\u901a\u8fc7FEEvaluation\u7c7b\u6765\u5b9e\u73b0\u9ad8\u6548\u8ba1\u7b97\uff09\uff0c\u8fd8\u6709\u4e00\u4e2a\u662f\u5e95\u5c42\u6807\u91cf\u7c7b\u578b\u3002\u6211\u4eec\u5e0c\u671b\u5bf9\u6700\u7ec8\u77e9\u9635\u4f7f\u7528 <code>double</code> \u6570\u5b57\uff08\u5373\u53cc\u7cbe\u5ea6\uff0c64\u4f4d\u6d6e\u70b9\uff09\uff0c\u4f46\u5bf9\u591a\u7f51\u683c\u7ea7\u77e9\u9635\u4f7f\u7528\u6d6e\u70b9\u6570\uff08\u5355\u7cbe\u5ea6\uff0c32\u4f4d\u6d6e\u70b9\u6570\u5b57\uff09\uff08\u56e0\u4e3a\u90a3\u53ea\u662f\u4e00\u4e2a\u9884\u5904\u7406\u7a0b\u5e8f\uff0c\u800c\u6d6e\u70b9\u6570\u7684\u5904\u7406\u901f\u5ea6\u662f\u4e24\u500d\uff09\u3002FEEvaluation\u7c7b\u4e5f\u9700\u8981\u4e00\u4e2a\u6a21\u677f\u53c2\u6570\uff0c\u7528\u4e8e\u786e\u5b9a\u4e00\u7ef4\u6b63\u4ea4\u70b9\u7684\u6570\u91cf\u3002\u5728\u4e0b\u9762\u7684\u4ee3\u7801\u4e2d\uff0c\u6211\u4eec\u628a\u5b83\u786c\u7f16\u7801\u4e3a  <code>fe_degree+1</code>  \u3002\u5982\u679c\u6211\u4eec\u60f3\u72ec\u7acb\u4e8e\u591a\u9879\u5f0f\u7a0b\u5ea6\u6765\u6539\u53d8\u5b83\uff0c\u6211\u4eec\u9700\u8981\u6dfb\u52a0\u4e00\u4e2a\u6a21\u677f\u53c2\u6570\uff0c\u5c31\u50cf\u5728  MatrixFreeOperators::LaplaceOperator  \u7c7b\u4e2d\u505a\u7684\u90a3\u6837\u3002\n\n// \u987a\u4fbf\u8bf4\u4e00\u4e0b\uff0c\u5982\u679c\u6211\u4eec\u5728\u540c\u4e00\u4e2a\u7f51\u683c\u548c\u81ea\u7531\u5ea6\u4e0a\u5b9e\u73b0\u4e86\u51e0\u4e2a\u4e0d\u540c\u7684\u64cd\u4f5c\uff08\u6bd4\u5982\u8d28\u91cf\u77e9\u9635\u548c\u62c9\u666e\u62c9\u65af\u77e9\u9635\uff09\uff0c\u6211\u4eec\u5c06\u4e3a\u6bcf\u4e2a\u64cd\u4f5c\u8005\u5b9a\u4e49\u4e24\u4e2a\u50cf\u73b0\u5728\u8fd9\u6837\u7684\u7c7b\uff08\u6765\u81ea\u4e8e MatrixFreeOperators::Base \u7c7b\uff09\uff0c\u5e76\u8ba9\u5b83\u4eec\u90fd\u5f15\u7528\u4e00\u822c\u95ee\u9898\u7c7b\u4e2d\u7684\u540c\u4e00\u4e2aMatrixFree\u6570\u636e\u7f13\u5b58\u3002\u901a\u8fc7 MatrixFreeOperators::Base \u7684\u63a5\u53e3\u8981\u6c42\u6211\u4eec\u53ea\u63d0\u4f9b\u4e00\u7ec4\u6700\u5c0f\u7684\u51fd\u6570\u3002\u8fd9\u4e2a\u6982\u5ff5\u5141\u8bb8\u7f16\u5199\u5177\u6709\u8bb8\u591a\u65e0\u77e9\u9635\u64cd\u4f5c\u7684\u590d\u6742\u5e94\u7528\u4ee3\u7801\u3002\n\n//  @note  \u50a8\u5b58\u7c7b\u578b <code>VectorizedArray<number></code> \u7684\u503c\u9700\u8981\u6ce8\u610f\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u4f7f\u7528deal.II\u8868\u7c7b\uff0c\u5b83\u51c6\u5907\u4ee5\u6b63\u786e\u7684\u5bf9\u9f50\u65b9\u5f0f\u4fdd\u5b58\u6570\u636e\u3002\u7136\u800c\uff0c\u5b58\u50a8\u4f8b\u5982\u4e00\u4e2a <code>std::vector<VectorizedArray<number> ></code> \u662f\u4e0d\u53ef\u80fd\u7528\u77e2\u91cf\u5316\u7684\u3002\u6570\u636e\u4e0e\u5185\u5b58\u5730\u5740\u7684\u8fb9\u754c\u9700\u8981\u4e00\u5b9a\u7684\u5bf9\u9f50\uff08\u57fa\u672c\u4e0a\uff0c\u5728AVX\u7684\u60c5\u51b5\u4e0b\uff0c\u4e00\u4e2a32\u5b57\u8282\u7684VectorizedArray\u9700\u8981\u4ece\u4e00\u4e2a\u80fd\u88ab32\u6574\u9664\u7684\u5185\u5b58\u5730\u5740\u5f00\u59cb\uff09\u3002\u8868\u7c7b\uff08\u4ee5\u53ca\u5b83\u6240\u57fa\u4e8e\u7684AlignedVector\u7c7b\uff09\u786e\u4fdd\u8fd9\u79cd\u5bf9\u9f50\u65b9\u5f0f\u5f97\u5230\u5c0a\u91cd\uff0c\u800c std::vector \u4e00\u822c\u4e0d\u8fd9\u6837\u505a\uff0c\u8fd9\u53ef\u80fd\u4f1a\u5bfc\u81f4\u4e00\u4e9b\u7cfb\u7edf\u5728\u5947\u602a\u7684\u5730\u65b9\u51fa\u73b0\u5206\u6bb5\u6545\u969c\uff0c\u6216\u8005\u5176\u4ed6\u7cfb\u7edf\u7684\u6027\u80fd\u4e0d\u7406\u60f3\u3002\n\n  template <int dim, int fe_degree, typename number> \n  class LaplaceOperator \n    : public MatrixFreeOperators:: \n        Base<dim, LinearAlgebra::distributed::Vector<number>> \n  { \n  public: \n    using value_type = number; \n\n    LaplaceOperator(); \n\n    void clear() override; \n\n    void evaluate_coefficient(const Coefficient<dim> &coefficient_function); \n\n    virtual void compute_diagonal() override; \n\n  private: \n    virtual void apply_add( \n      LinearAlgebra::distributed::Vector<number> &      dst, \n      const LinearAlgebra::distributed::Vector<number> &src) const override; \n\n    void \n    local_apply(const MatrixFree<dim, number> &                   data, \n                LinearAlgebra::distributed::Vector<number> &      dst, \n                const LinearAlgebra::distributed::Vector<number> &src, \n                const std::pair<unsigned int, unsigned int> &cell_range) const; \n\n    void local_compute_diagonal( \n      const MatrixFree<dim, number> &              data, \n      LinearAlgebra::distributed::Vector<number> & dst, \n      const unsigned int &                         dummy, \n      const std::pair<unsigned int, unsigned int> &cell_range) const; \n\n    Table<2, VectorizedArray<number>> coefficient; \n  }; \n\n// \u8fd9\u662f @p LaplaceOperator \u7c7b\u7684\u6784\u9020\u51fd\u6570\u3002\u5b83\u6240\u505a\u7684\u5c31\u662f\u8c03\u7528\u57fa\u7c7b MatrixFreeOperators::Base, \u7684\u9ed8\u8ba4\u6784\u9020\u51fd\u6570\uff0c\u800c\u57fa\u7c7b\u53c8\u662f\u57fa\u4e8eSubscriptor\u7c7b\u7684\uff0c\u5b83\u65ad\u8a00\u8fd9\u4e2a\u7c7b\u5728\u8d85\u51fa\u8303\u56f4\u540e\u4e0d\u4f1a\u88ab\u8bbf\u95ee\uff0c\u6bd4\u5982\u5728\u4e00\u4e2a\u9884\u5904\u7406\u7a0b\u5e8f\u4e2d\u3002\n\n  template <int dim, int fe_degree, typename number> \n  LaplaceOperator<dim, fe_degree, number>::LaplaceOperator() \n    : MatrixFreeOperators::Base<dim, \n                                LinearAlgebra::distributed::Vector<number>>() \n  {} \n\n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::clear() \n  { \n    coefficient.reinit(0, 0); \n    MatrixFreeOperators::Base<dim, LinearAlgebra::distributed::Vector<number>>:: \n      clear(); \n  } \n\n//  @sect4{Computation of coefficient}  \n\n// \u4e3a\u4e86\u521d\u59cb\u5316\u7cfb\u6570\uff0c\u6211\u4eec\u76f4\u63a5\u8d4b\u4e88\u5b83\u4e0a\u9762\u5b9a\u4e49\u7684\u7cfb\u6570\u7c7b\uff0c\u7136\u540e\u9009\u62e9\u5e26\u6709\u77e2\u91cf\u6570\u7684\u65b9\u6cd5 <code>coefficient_function.value</code> \uff08\u7f16\u8bd1\u5668\u53ef\u4ee5\u4ece\u70b9\u6570\u636e\u7c7b\u578b\u4e2d\u63a8\u5bfc\u51fa\u6765\uff09\u3002\u4e0b\u9762\u5c06\u89e3\u91caFEEvaluation\u7c7b\uff08\u53ca\u5176\u6a21\u677f\u53c2\u6570\uff09\u7684\u4f7f\u7528\u3002\n\n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::evaluate_coefficient( \n    const Coefficient<dim> &coefficient_function) \n  { \n    const unsigned int n_cells = this->data->n_cell_batches(); \n    FEEvaluation<dim, fe_degree, fe_degree + 1, 1, number> phi(*this->data); \n\n    coefficient.reinit(n_cells, phi.n_q_points); \n    for (unsigned int cell = 0; cell < n_cells; ++cell) \n      { \n        phi.reinit(cell); \n        for (unsigned int q = 0; q < phi.n_q_points; ++q) \n          coefficient(cell, q) = \n            coefficient_function.value(phi.quadrature_point(q)); \n      } \n  } \n\n//  @sect4{Local evaluation of Laplace operator}  \n\n// \u8fd9\u91cc\u662f\u8fd9\u4e2a\u7c7b\u7684\u4e3b\u8981\u529f\u80fd\uff0c\u77e9\u9635-\u5411\u91cf\u4e58\u79ef\u7684\u8bc4\u4f30\uff08\u6216\u8005\uff0c\u4e00\u822c\u6765\u8bf4\uff0c\u6709\u9650\u5143\u7b97\u5b50\u8bc4\u4f30\uff09\u3002\u8fd9\u662f\u5728\u4e00\u4e2a\u51fd\u6570\u4e2d\u5b8c\u6210\u7684\uff0c\u8be5\u51fd\u6570\u9700\u8981\u56db\u4e2a\u53c2\u6570\uff0cMatrixFree\u5bf9\u8c61\uff0c\u76ee\u6807\u548c\u6e90\u5411\u91cf\uff0c\u4ee5\u53ca\u8981\u5904\u7406\u7684\u5355\u5143\u683c\u8303\u56f4\u3002MatrixFree\u7c7b\u4e2d\u7684\u65b9\u6cd5 <code>cell_loop</code> \u5c06\u5728\u5185\u90e8\u7528\u4e00\u4e9b\u5355\u5143\u683c\u8303\u56f4\u6765\u8c03\u7528\u8fd9\u4e2a\u51fd\u6570\uff0c\u8fd9\u4e9b\u5355\u5143\u683c\u8303\u56f4\u662f\u901a\u8fc7\u68c0\u67e5\u54ea\u4e9b\u5355\u5143\u683c\u53ef\u4ee5\u540c\u65f6\u5de5\u4f5c\u6765\u83b7\u5f97\u7684\uff0c\u8fd9\u6837\u5199\u64cd\u4f5c\u5c31\u4e0d\u4f1a\u5f15\u8d77\u4efb\u4f55\u7ade\u8d5b\u6761\u4ef6\u3002\u8bf7\u6ce8\u610f\uff0c\u5faa\u73af\u4e2d\u4f7f\u7528\u7684\u5355\u5143\u683c\u8303\u56f4\u5e76\u4e0d\u662f\u76f4\u63a5\u6307\u5f53\u524d\u7f51\u683c\u4e2d\u7684\uff08\u6d3b\u52a8\uff09\u5355\u5143\u683c\u6570\u91cf\uff0c\u800c\u662f\u4e00\u4e2a\u5355\u5143\u683c\u6279\u6b21\u7684\u96c6\u5408\u3002 \u6362\u53e5\u8bdd\u8bf4\uff0c\"\u5355\u5143 \"\u53ef\u80fd\u662f\u4e00\u4e2a\u9519\u8bef\u7684\u5f00\u59cb\uff0c\u56e0\u4e3aFEEvaluation\u5c06\u51e0\u4e2a\u5355\u5143\u7684\u6570\u636e\u5206\u7ec4\u5728\u4e00\u8d77\u3002\u8fd9\u610f\u5473\u7740\u5728\u6b63\u4ea4\u70b9\u7684\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u5b9e\u9645\u4e0a\u662f\u5c06\u51e0\u4e2a\u5355\u5143\u7684\u6b63\u4ea4\u70b9\u4f5c\u4e3a\u4e00\u4e2a\u5757\u6765\u770b\u5f85\u3002\u8fd9\u6837\u505a\u662f\u4e3a\u4e86\u5b9e\u73b0\u66f4\u9ad8\u7684\u77e2\u91cf\u5316\u7a0b\u5ea6\u3002 \u8fd9\u79cd \"\u5355\u5143 \"\u6216 \"\u5355\u5143\u6279 \"\u7684\u6570\u91cf\u5b58\u50a8\u5728MatrixFree\u4e2d\uff0c\u53ef\u4ee5\u901a\u8fc7 MatrixFree::n_cell_batches(). \u67e5\u8be2\u3002\u4e0edeal.II\u5355\u5143\u8fed\u4ee3\u5668\u76f8\u6bd4\uff0c\u5728\u8fd9\u4e2a\u7c7b\u4e2d\uff0c\u6240\u6709\u7684\u5355\u5143\u90fd\u88ab\u5e03\u7f6e\u5728\u4e00\u4e2a\u666e\u901a\u7684\u6570\u7ec4\u4e2d\uff0c\u4e0d\u76f4\u63a5\u77e5\u9053\u6c34\u5e73\u6216\u76f8\u90bb\u5173\u7cfb\uff0c\u8fd9\u4f7f\u5f97\u901a\u8fc7\u65e0\u7b26\u53f7\u6574\u6570\u7d22\u5f15\u5355\u5143\u6210\u4e3a\u53ef\u80fd\u3002\n\n// \u62c9\u666e\u62c9\u65af\u8fd0\u7b97\u7b26\u7684\u5b9e\u73b0\u975e\u5e38\u7b80\u5355\u3002\u9996\u5148\uff0c\u6211\u4eec\u9700\u8981\u521b\u5efa\u4e00\u4e2a\u5bf9\u8c61FEEvaluation\uff0c\u5b83\u5305\u542b\u8ba1\u7b97\u6838\uff0c\u5e76\u6709\u6570\u636e\u5b57\u6bb5\u6765\u5b58\u50a8\u4e34\u65f6\u7ed3\u679c\uff08\u4f8b\u5982\uff0c\u5728\u51e0\u4e2a\u5355\u5143\u683c\u96c6\u5408\u7684\u6240\u6709\u6b63\u4ea4\u70b9\u4e0a\u8bc4\u4f30\u7684\u68af\u5ea6\uff09\u3002\u8bf7\u6ce8\u610f\uff0c\u4e34\u65f6\u7ed3\u679c\u4e0d\u4f1a\u4f7f\u7528\u5927\u91cf\u7684\u5185\u5b58\uff0c\u800c\u4e14\u7531\u4e8e\u6211\u4eec\u7528\u5143\u7d20\u987a\u5e8f\u6307\u5b9a\u6a21\u677f\u53c2\u6570\uff0c\u6570\u636e\u88ab\u5b58\u50a8\u5728\u5806\u6808\u4e2d\uff08\u6ca1\u6709\u6602\u8d35\u7684\u5185\u5b58\u5206\u914d\uff09\u3002\u901a\u5e38\uff0c\u53ea\u9700\u8981\u8bbe\u7f6e\u4e24\u4e2a\u6a21\u677f\u53c2\u6570\uff0c\u7ef4\u5ea6\u4f5c\u4e3a\u7b2c\u4e00\u4e2a\u53c2\u6570\uff0c\u6709\u9650\u5143\u7684\u5ea6\u6570\u4f5c\u4e3a\u7b2c\u4e8c\u4e2a\u53c2\u6570\uff08\u8fd9\u7b49\u4e8e\u6bcf\u4e2a\u7ef4\u5ea6\u7684\u81ea\u7531\u5ea6\u6570\u51cf\u53bbFE_Q\u5143\u7d20\u7684\u4e00\u4e2a\uff09\u3002\u7136\u800c\uff0c\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u4e5f\u5e0c\u671b\u80fd\u591f\u4f7f\u7528\u6d6e\u70b9\u6570\u6765\u8ba1\u7b97\u591a\u7f51\u683c\u9884\u5904\u7406\uff0c\u8fd9\u662f\u6700\u540e\u4e00\u4e2a\uff08\u7b2c\u4e94\u4e2a\uff09\u6a21\u677f\u53c2\u6570\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u4e0d\u80fd\u4f9d\u8d56\u9ed8\u8ba4\u7684\u6a21\u677f\u53c2\u6570\uff0c\u56e0\u6b64\u5fc5\u987b\u586b\u5199\u7b2c\u4e09\u548c\u7b2c\u56db\u4e2a\u5b57\u6bb5\u3002\u7b2c\u4e09\u4e2a\u53c2\u6570\u6307\u5b9a\u6bcf\u4e2a\u65b9\u5411\u7684\u6b63\u4ea4\u70b9\u7684\u6570\u91cf\uff0c\u5176\u9ed8\u8ba4\u503c\u7b49\u4e8e\u5143\u7d20\u7684\u5ea6\u6570\u52a01\u3002\u7b2c\u56db\u4e2a\u53c2\u6570\u8bbe\u7f6e\u5206\u91cf\u7684\u6570\u91cf\uff08\u5728PDEs\u7cfb\u7edf\u4e2d\u4e5f\u53ef\u4ee5\u8bc4\u4f30\u77e2\u91cf\u503c\u7684\u51fd\u6570\uff0c\u4f46\u9ed8\u8ba4\u662f\u6807\u91cf\u5143\u7d20\uff09\uff0c\u6700\u540e\u4e00\u4e2a\u53c2\u6570\u8bbe\u7f6e\u6570\u5b57\u7c7b\u578b\u3002\n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5728\u7ed9\u5b9a\u7684\u5355\u5143\u683c\u8303\u56f4\u5185\u5faa\u73af\uff0c\u7136\u540e\u7ee7\u7eed\u8fdb\u884c\u5b9e\u9645\u7684\u5b9e\u73b0\u3002  <ol>  \n// <li>  \u544a\u8bc9FEEvaluation\u5bf9\u8c61\u6211\u4eec\u8981\u5904\u7406\u7684\uff08\u5b8f\uff09\u5355\u5143\u3002   <li>  \u8bfb\u5165\u6e90\u5411\u91cf\u7684\u503c\uff08  @p read_dof_values),  \u5305\u62ec\u7ea6\u675f\u7684\u89e3\u6790\u3002\u8fd9\u5c06\u5b58\u50a8 $u_\\mathrm{cell}$ \uff0c\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0\u3002   <li>  \u8ba1\u7b97\u5355\u5143\u683c\u68af\u5ea6\uff08\u6709\u9650\u5143\u51fd\u6570\u7684\u8bc4\u4ef7\uff09\u3002\u7531\u4e8eFEEvaluation\u53ef\u4ee5\u7ed3\u5408\u503c\u8ba1\u7b97\u548c\u68af\u5ea6\u8ba1\u7b97\uff0c\u5b83\u4f7f\u7528\u4e00\u4e2a\u7edf\u4e00\u7684\u63a5\u53e3\u6765\u5904\u74060\u52302\u9636\u4e4b\u95f4\u7684\u5404\u79cd\u5bfc\u6570\u3002\u6211\u4eec\u53ea\u60f3\u8981\u68af\u5ea6\uff0c\u4e0d\u60f3\u8981\u503c\uff0c\u4e5f\u4e0d\u60f3\u8981\u4e8c\u9636\u5bfc\u6570\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u68af\u5ea6\u69fd\uff08\u7b2c\u4e8c\u69fd\uff09\u4e2d\u5c06\u51fd\u6570\u53c2\u6570\u8bbe\u7f6e\u4e3a\u771f\uff0c\u800c\u5728\u503c\u69fd\uff08\u7b2c\u4e00\u69fd\uff09\u4e2d\u8bbe\u7f6e\u4e3a\u5047\u3002\u8fd8\u6709\u4e00\u4e2a\u7528\u4e8eHessian\u7684\u7b2c\u4e09\u69fd\uff0c\u9ed8\u8ba4\u4e3a\u5047\uff0c\u6240\u4ee5\u4e0d\u9700\u8981\u7ed9\u5b83\u3002\u8bf7\u6ce8\u610f\uff0cFEEvaluation\u7c7b\u5728\u5185\u90e8\u4ee5\u4e00\u79cd\u6709\u6548\u7684\u65b9\u5f0f\u8bc4\u4f30\u5f62\u72b6\u51fd\u6570\uff0c\u4e00\u6b21\u53ea\u5904\u7406\u4e00\u4e2a\u7ef4\u5ea6\uff08\u5982\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\u4f7f\u7528\u5f62\u72b6\u51fd\u6570\u548c\u6b63\u4ea4\u70b9\u7684\u5f20\u91cf\u79ef\u5f62\u5f0f\uff09\u3002\u4e0eFEValues\u4e2d\u4f7f\u7528\u7684\u5728\u6240\u6709\u5c40\u90e8\u81ea\u7531\u5ea6\u548c\u6b63\u4ea4\u70b9\u4e0a\u5faa\u73af\u7684\u5929\u771f\u65b9\u6cd5\u76f8\u6bd4\uff0c\u5728 $d$ \u7ef4\u5ea6\u4e0a\uff0c\u8fd9\u7ed9\u51fa\u4e86\u7b49\u4e8e $\\mathcal O(d^2 (p+1)^{d+1})$ \u7684\u591a\u9879\u5f0f\u5ea6\u6570 $p$ \u7684\u590d\u6742\u5ea6\uff0c\u5e76\u82b1\u8d39\u4e86 $\\mathcal O(d (p+1)^{2d})$  \u3002   <li>  \u63a5\u4e0b\u6765\u662f\u96c5\u5404\u5e03\u53d8\u6362\u7684\u5e94\u7528\uff0c\u4e58\u4ee5\u53d8\u91cf\u7cfb\u6570\u548c\u6b63\u4ea4\u6743\u91cd\u3002FEEvaluation\u6709\u4e00\u4e2a\u8bbf\u95ee\u51fd\u6570 @p get_gradient \uff0c\u53ef\u4ee5\u5e94\u7528Jacobian\u5e76\u8fd4\u56de\u5b9e\u7a7a\u95f4\u4e2d\u7684\u68af\u5ea6\u3002\u7136\u540e\uff0c\u6211\u4eec\u53ea\u9700\u8981\u4e58\u4ee5\uff08\u6807\u91cf\uff09\u7cfb\u6570\uff0c\u5e76\u8ba9\u51fd\u6570 @p submit_gradient \u5e94\u7528\u7b2c\u4e8c\u4e2a\u96c5\u5404\u5e03\u5f0f\uff08\u7528\u4e8e\u6d4b\u8bd5\u51fd\u6570\uff09\u548c\u6b63\u4ea4\u6743\u91cd\u53ca\u96c5\u5404\u5e03\u5f0f\u884c\u5217\u5f0f\uff08JxW\uff09\u3002\u6ce8\u610f\uff0c\u63d0\u4ea4\u7684\u68af\u5ea6\u5b58\u50a8\u5728\u4e0e @p get_gradient. \u4e2d\u8bfb\u53d6\u68af\u5ea6\u7684\u5730\u65b9\u76f8\u540c\u7684\u6570\u636e\u5b57\u6bb5\u4e2d\u3002\u56e0\u6b64\uff0c\u4f60\u9700\u8981\u786e\u4fdd\u5728\u8c03\u7528 @p submit_gradient \u540e\u4e0d\u8981\u518d\u4ece\u540c\u4e00\u6b63\u4ea4\u70b9\u8bfb\u53d6\u8be5\u7279\u5b9a\u6b63\u4ea4\u70b9\u3002\u4e00\u822c\u6765\u8bf4\uff0c\u5f53 @p get_gradient \u88ab\u591a\u6b21\u4f7f\u7528\u65f6\uff0c\u590d\u5236\u5176\u7ed3\u679c\u662f\u4e2a\u597d\u4e3b\u610f\u3002   <li>  \u63a5\u4e0b\u6765\u662f\u5bf9\u6240\u6709\u6d4b\u8bd5\u51fd\u6570\u7684\u6b63\u4ea4\u70b9\u8fdb\u884c\u6c42\u548c\uff0c\u5bf9\u5e94\u4e8e\u5b9e\u9645\u79ef\u5206\u6b65\u9aa4\u3002\u5bf9\u4e8e\u62c9\u666e\u62c9\u65af\u7b97\u5b50\uff0c\u6211\u4eec\u53ea\u662f\u4e58\u4ee5\u68af\u5ea6\uff0c\u6240\u4ee5\u6211\u4eec\u7528\u5404\u81ea\u7684\u53c2\u6570\u96c6\u8c03\u7528\u79ef\u5206\u51fd\u6570\u3002\u5982\u679c\u4f60\u6709\u4e00\u4e2a\u65b9\u7a0b\uff0c\u540c\u65f6\u7528\u6d4b\u8bd5\u51fd\u6570\u7684\u503c\u548c\u68af\u5ea6\u8fdb\u884c\u6d4b\u8bd5\uff0c\u90a3\u4e48\u4e24\u4e2a\u6a21\u677f\u53c2\u6570\u90fd\u9700\u8981\u8bbe\u7f6e\u4e3a\u771f\u3002\u5148\u8c03\u7528\u79ef\u5206\u51fd\u6570\u7684\u503c\uff0c\u518d\u5355\u72ec\u8c03\u7528\u68af\u5ea6\uff0c\u4f1a\u5bfc\u81f4\u9519\u8bef\u7684\u7ed3\u679c\uff0c\u56e0\u4e3a\u7b2c\u4e8c\u6b21\u8c03\u7528\u4f1a\u5728\u5185\u90e8\u8986\u76d6\u7b2c\u4e00\u6b21\u8c03\u7528\u7684\u7ed3\u679c\u3002\u8bf7\u6ce8\u610f\uff0c\u79ef\u5206\u6b65\u9aa4\u7684\u4e8c\u6b21\u5bfc\u6570\u6ca1\u6709\u51fd\u6570\u53c2\u6570\u3002   <li>  \u6700\u7ec8\uff0c\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\u5411\u91cf $v_\\mathrm{cell}$ \u4e2d\u7684\u5c40\u90e8\u8d21\u732e\u9700\u8981\u88ab\u6dfb\u52a0\u5230\u7ed3\u679c\u5411\u91cf\u4e2d\uff08\u5e76\u5e94\u7528\u7ea6\u675f\uff09\u3002\u8fd9\u662f\u901a\u8fc7\u8c03\u7528 @p distribute_local_to_global, \u6765\u5b8c\u6210\u7684\uff0c\u8be5\u51fd\u6570\u4e0eAffineConstraints\u4e2d\u7684\u76f8\u5e94\u51fd\u6570\u540d\u79f0\u76f8\u540c\uff08\u53ea\u662f\u6211\u4eec\u73b0\u5728\u5c06\u5c40\u90e8\u5411\u91cf\u5b58\u50a8\u5728FEEvaluation\u5bf9\u8c61\u4e2d\uff0c\u6b63\u5982\u5c40\u90e8\u548c\u5168\u5c40\u81ea\u7531\u5ea6\u4e4b\u95f4\u7684\u6307\u6570\u4e00\u6837\uff09\u3002   </ol>  \n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::local_apply( \n    const MatrixFree<dim, number> &                   data, \n    LinearAlgebra::distributed::Vector<number> &      dst, \n    const LinearAlgebra::distributed::Vector<number> &src, \n    const std::pair<unsigned int, unsigned int> &     cell_range) const \n  { \n    FEEvaluation<dim, fe_degree, fe_degree + 1, 1, number> phi(data); \n\n    for (unsigned int cell = cell_range.first; cell < cell_range.second; ++cell) \n      { \n        AssertDimension(coefficient.size(0), data.n_cell_batches()); \n        AssertDimension(coefficient.size(1), phi.n_q_points); \n\n        phi.reinit(cell); \n        phi.read_dof_values(src); \n        phi.evaluate(EvaluationFlags::gradients); \n        for (unsigned int q = 0; q < phi.n_q_points; ++q) \n          phi.submit_gradient(coefficient(cell, q) * phi.get_gradient(q), q); \n        phi.integrate(EvaluationFlags::gradients); \n        phi.distribute_local_to_global(dst); \n      } \n  } \n\n// \u8fd9\u4e2a\u51fd\u6570\u5b9e\u73b0\u4e86\u5bf9 Base::apply_add() \u63a5\u53e3\u7684\u6240\u6709\u5355\u5143\u7684\u5faa\u73af\u3002\u8fd9\u662f\u7528MatrixFree\u7c7b\u7684 @p cell_loop \u6765\u5b9e\u73b0\u7684\uff0c\u5b83\u63a5\u53d7\u8fd9\u4e2a\u7c7b\u7684operator()\uff0c\u53c2\u6570\u4e3aMatrixFree, OutVector, InVector, cell_range\u3002\u5f53\u4f7f\u7528MPI\u5e76\u884c\u5316\uff08\u4f46\u6ca1\u6709\u7ebf\u7a0b\uff09\u65f6\uff0c\u5982\u672c\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u6240\u505a\u7684\uff0c\u5355\u5143\u683c\u5faa\u73af\u5bf9\u5e94\u4e8e\u4ee5\u4e0b\u4e09\u884c\u4ee3\u7801\u3002\n\n// \n// @code\n//  src.update_ghost_values();\n//  local_apply(*this->data, dst, src, std::make_pair(0U,\n//                                                    data.n_cell_batches()));\n//  dst.compress(VectorOperation::add);\n//  @endcode\n\n// \u8fd9\u91cc\uff0c\u4e24\u4e2a\u8c03\u7528update_ghost_values()\u548ccompress()\u4e3aMPI\u6267\u884c\u5904\u7406\u5668\u8fb9\u754c\u4e0a\u7684\u6570\u636e\u4ea4\u6362\uff0c\u4e00\u6b21\u7528\u4e8e\u6e90\u5411\u91cf\uff0c\u6211\u4eec\u9700\u8981\u4ece\u8fdc\u7a0b\u5904\u7406\u5668\u62e5\u6709\u7684\u6761\u76ee\u4e2d\u8bfb\u53d6\uff0c\u4e00\u6b21\u7528\u4e8e\u76ee\u7684\u5411\u91cf\uff0c\u6211\u4eec\u5df2\u7ecf\u79ef\u7d2f\u4e86\u90e8\u5206\u6b8b\u4f59\uff0c\u9700\u8981\u6dfb\u52a0\u5230\u6240\u6709\u8005\u5904\u7406\u5668\u7684\u76f8\u5e94\u6761\u76ee\u4e2d\u3002\u7136\u800c\uff0c MatrixFree::cell_loop \u4e0d\u4ec5\u62bd\u8c61\u51fa\u8fd9\u4e24\u4e2a\u8c03\u7528\uff0c\u800c\u4e14\u8fd8\u8fdb\u884c\u4e86\u4e00\u4e9b\u989d\u5916\u7684\u4f18\u5316\u3002\u4e00\u65b9\u9762\uff0c\u5b83\u5c06\u628aupdate_ghost_values()\u548ccompress()\u7684\u8c03\u7528\u62c6\u5f00\uff0c\u4ee5\u5141\u8bb8\u901a\u4fe1\u548c\u8ba1\u7b97\u7684\u91cd\u53e0\u3002\u7136\u540e\u7528\u4e09\u4e2a\u4ee3\u8868\u4ece0\u5230 MatrixFree::n_cell_batches(). \u7684\u5355\u5143\u683c\u8303\u56f4\u7684\u5206\u533a\u6765\u8c03\u7528local_apply\u51fd\u6570\u3002\u53e6\u4e00\u65b9\u9762\uff0ccell_loop\u4e5f\u652f\u6301\u7ebf\u7a0b\u5e76\u884c\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u5355\u5143\u683c\u8303\u56f4\u88ab\u5206\u5272\u6210\u66f4\u5c0f\u7684\u5757\uff0c\u5e76\u4ee5\u4e00\u79cd\u5148\u8fdb\u7684\u65b9\u5f0f\u5b89\u6392\uff0c\u907f\u514d\u4e86\u51e0\u4e2a\u7ebf\u7a0b\u5bf9\u540c\u4e00\u4e2a\u5411\u91cf\u6761\u76ee\u7684\u8bbf\u95ee\u3002\u8fd9\u4e00\u7279\u6027\u5728  step-48  \u4e2d\u6709\u89e3\u91ca\u3002\n\n// \u6ce8\u610f\uff0c\u5728\u5355\u5143\u683c\u5faa\u73af\u4e4b\u540e\uff0c\u53d7\u7ea6\u675f\u7684\u81ea\u7531\u5ea6\u9700\u8981\u518d\u6b21\u88ab\u89e6\u53ca\uff0c\u4ee5\u5b9e\u73b0\u5408\u7406\u7684vmult()\u64cd\u4f5c\u3002\u7531\u4e8e\u88c5\u914d\u5faa\u73af\u4f1a\u81ea\u52a8\u89e3\u51b3\u7ea6\u675f\u95ee\u9898\uff08\u5c31\u50cf AffineConstraints::distribute_local_to_global() \u7684\u8c03\u7528\u4e00\u6837\uff09\uff0c\u5b83\u4e0d\u4f1a\u8ba1\u7b97\u5bf9\u53d7\u7ea6\u675f\u81ea\u7531\u5ea6\u7684\u4efb\u4f55\u8d21\u732e\uff0c\u800c\u662f\u5c06\u5404\u81ea\u7684\u6761\u76ee\u7559\u4e3a\u96f6\u3002\u8fd9\u5c06\u8868\u793a\u4e00\u4e2a\u77e9\u9635\u7684\u53d7\u9650\u81ea\u7531\u5ea6\u7684\u884c\u548c\u5217\u90fd\u662f\u7a7a\u7684\u3002\u7136\u800c\uff0c\u50cfCG\u8fd9\u6837\u7684\u8fed\u4ee3\u6c42\u89e3\u5668\u53ea\u5bf9\u975e\u661f\u5f62\u77e9\u9635\u6709\u6548\u3002\u6700\u7b80\u5355\u7684\u65b9\u6cd5\u662f\u5c06\u77e9\u9635\u4e2d\u5bf9\u5e94\u4e8e\u53d7\u9650\u81ea\u7531\u5ea6\u7684\u5b50\u5757\u8bbe\u7f6e\u4e3a\u540c\u4e00\u77e9\u9635\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u77e9\u9635\u7684\u5e94\u7528\u53ea\u662f\u5c06\u53f3\u4fa7\u5411\u91cf\u7684\u5143\u7d20\u590d\u5236\u5230\u5de6\u4fa7\u3002\u5e78\u8fd0\u7684\u662f\uff0cvmult()\u7684\u5b9e\u73b0 MatrixFreeOperators::Base \u5728apply_add()\u51fd\u6570\u4e4b\u5916\u81ea\u52a8\u4e3a\u6211\u4eec\u505a\u4e86\u8fd9\u4e2a\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u9700\u8981\u5728\u8fd9\u91cc\u91c7\u53d6\u8fdb\u4e00\u6b65\u7684\u884c\u52a8\u3002\n\n// \u5f53\u4f7f\u7528MatrixFree\u548cFEEvaluation\u7684\u7ec4\u5408\u4e0eMPI\u5e76\u884c\u65f6\uff0c\u6709\u4e00\u4e2a\u65b9\u9762\u9700\u8981\u6ce8\u610f&mdash; \u7528\u4e8e\u8bbf\u95ee\u5411\u91cf\u7684\u7d22\u5f15\u3002\u51fa\u4e8e\u6027\u80fd\u7684\u8003\u8651\uff0cMatrixFree\u548cFEEvaluation\u88ab\u8bbe\u8ba1\u4e3a\u5728MPI\u672c\u5730\u7d22\u5f15\u7a7a\u95f4\u4e2d\u8bbf\u95ee\u5411\u91cf\uff0c\u5f53\u4e0e\u591a\u4e2a\u5904\u7406\u5668\u4e00\u8d77\u5de5\u4f5c\u65f6\u4e5f\u662f\u5982\u6b64\u3002\u5728\u672c\u5730\u7d22\u5f15\u7a7a\u95f4\u5de5\u4f5c\u610f\u5473\u7740\u9664\u4e86\u4e0d\u53ef\u907f\u514d\u7684\u95f4\u63a5\u5bfb\u5740\u5916\uff0c\u5728\u5411\u91cf\u8bbf\u95ee\u53d1\u751f\u7684\u5730\u65b9\u4e0d\u9700\u8981\u8fdb\u884c\u7d22\u5f15\u8f6c\u6362\u3002\u7136\u800c\uff0c\u672c\u5730\u7d22\u5f15\u7a7a\u95f4\u662f\u6a21\u7cca\u7684\uff1a\u867d\u7136\u6807\u51c6\u7684\u60ef\u4f8b\u662f\u75280\u548c\u672c\u5730\u5927\u5c0f\u4e4b\u95f4\u7684\u7d22\u5f15\u8bbf\u95ee\u5411\u91cf\u7684\u672c\u5730\u62e5\u6709\u7684\u8303\u56f4\uff0c\u4f46\u5bf9\u4e8e\u91cd\u5f71\u9879\u7684\u7f16\u53f7\u5e76\u4e0d\u90a3\u4e48\u660e\u786e\uff0c\u800c\u4e14\u6709\u4e9b\u968f\u610f\u3002\u5bf9\u4e8e\u77e9\u9635-\u5411\u91cf\u4e58\u79ef\uff0c\u53ea\u6709\u51fa\u73b0\u5728\u672c\u5730\u62e5\u6709\u7684\u5355\u5143\u683c\u4e0a\u7684\u6307\u6570\uff08\u52a0\u4e0a\u90a3\u4e9b\u901a\u8fc7\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u5f15\u7528\u7684\u6307\u6570\uff09\u662f\u5fc5\u8981\u7684\u3002\u7136\u800c\uff0c\u5728deal.II\u4e2d\uff0c\u6211\u4eec\u7ecf\u5e38\u5c06\u91cd\u5f71\u5143\u7d20\u4e0a\u7684\u6240\u6709\u81ea\u7531\u5ea6\u8bbe\u7f6e\u4e3a\u91cd\u5f71\u5411\u91cf\u6761\u76ee\uff0c\u79f0\u4e3a @ref GlossLocallyRelevantDof \"\u672f\u8bed\u8868\u4e2d\u63cf\u8ff0\u7684\u672c\u5730\u76f8\u5173DoF\"\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u5c3d\u7ba1\u6307\u7684\u662f\u540c\u4e00\u4e2a\u5168\u5c40\u7d22\u5f15\uff0c\u4f46\u5728\u4e24\u4e2a\u53ef\u80fd\u7684\u91cd\u5f71\u96c6\u4e2d\uff0c\u91cd\u5f71\u5411\u91cf\u6761\u76ee\u7684MPI\u672c\u5730\u7d22\u5f15\u4e00\u822c\u4f1a\u6709\u6240\u4e0d\u540c\u3002\u4e3a\u4e86\u907f\u514d\u95ee\u9898\uff0cFEEvaluation\u901a\u8fc7\u4e00\u4e2a\u540d\u4e3a LinearAlgebra::distributed::Vector::partitioners_are_compatible. \u7684\u68c0\u67e5\u6765\u68c0\u67e5\u7528\u4e8e\u77e9\u9635-\u5411\u91cf\u4e58\u79ef\u7684\u5411\u91cf\u5206\u533a\u662f\u5426\u786e\u5b9e\u4e0eMatrixFree\u4e2d\u7684\u7d22\u5f15\u5206\u533a\u76f8\u5339\u914d\u3002 \u4e3a\u4e86\u65b9\u4fbf\uff0c MatrixFreeOperators::Base \u7c7b\u5305\u62ec\u4e00\u4e2a\u673a\u5236\u6765\u4f7f\u9b3c\u9b42\u96c6\u9002\u5408\u6b63\u786e\u7684\u5e03\u5c40\u3002\u8fd9\u53d1\u751f\u5728\u5411\u91cf\u7684\u91cd\u5f71\u533a\u57df\uff0c\u6240\u4ee5\u8bf7\u8bb0\u4f4f\uff0c\u5728\u8c03\u7528vmult()\u65b9\u6cd5\u540e\uff0c\u76ee\u6807\u548c\u6e90\u5411\u91cf\u7684\u91cd\u5f71\u533a\u57df\u90fd\u53ef\u80fd\u88ab\u4fee\u6539\u3002\u8fd9\u662f\u5408\u6cd5\u7684\uff0c\u56e0\u4e3a\u5206\u5e03\u5f0fdeal.II\u5411\u91cf\u7684ghost\u533a\u57df\u662f\u4e00\u4e2a\u53ef\u53d8\u7684\u90e8\u5206\uff0c\u5e76\u6309\u9700\u586b\u5145\u3002\u5728\u77e9\u9635-\u5411\u91cf\u4e58\u79ef\u4e2d\u4f7f\u7528\u7684\u5411\u91cf\u5728\u8fdb\u5165vmult()\u51fd\u6570\u65f6\u4e0d\u80fd\u88ab\u91cd\u5f71\uff0c\u6240\u4ee5\u6ca1\u6709\u4fe1\u606f\u4e22\u5931\u3002\n\n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::apply_add( \n    LinearAlgebra::distributed::Vector<number> &      dst, \n    const LinearAlgebra::distributed::Vector<number> &src) const \n  { \n    this->data->cell_loop(&LaplaceOperator::local_apply, this, dst, src); \n  } \n\n// \u4e0b\u9762\u7684\u51fd\u6570\u5b9e\u73b0\u4e86\u7b97\u5b50\u5bf9\u89d2\u7ebf\u7684\u8ba1\u7b97\u3002\u8ba1\u7b97\u65e0\u77e9\u9635\u7b97\u5b50\u8bc4\u4f30\u7684\u77e9\u9635\u9879\uff0c\u7ed3\u679c\u6bd4\u8bc4\u4f30\u7b97\u5b50\u66f4\u590d\u6742\u3002\u4ece\u6839\u672c\u4e0a\u8bf4\uff0c\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u5728<i>all</i>\u5355\u4f4d\u5411\u91cf\u4e0a\u5e94\u7528\u7b97\u5b50\u6765\u83b7\u5f97\u7b97\u5b50\u7684\u77e9\u9635\u8868\u793a\u3002\u5f53\u7136\uff0c\u8fd9\u5c06\u662f\u975e\u5e38\u4f4e\u6548\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u9700\u8981\u8fdb\u884c<i>n</i>\u8fd0\u7b97\u7b26\u7684\u8bc4\u4f30\u6765\u68c0\u7d22\u6574\u4e2a\u77e9\u9635\u3002\u6b64\u5916\uff0c\u8fd9\u79cd\u65b9\u6cd5\u4f1a\u5b8c\u5168\u5ffd\u89c6\u77e9\u9635\u7684\u7a00\u758f\u6027\u3002\u7136\u800c\uff0c\u5bf9\u4e8e\u5355\u4e2a\u5355\u5143\u6765\u8bf4\uff0c\u8fd9\u662f\u4e00\u79cd\u65b9\u6cd5\uff0c\u800c\u4e14\u5b9e\u9645\u4e0a\u6548\u7387\u5e76\u4e0d\u4f4e\uff0c\u56e0\u4e3a\u5355\u5143\u5185\u7684\u6240\u6709\u81ea\u7531\u5ea6\u4e4b\u95f4\u901a\u5e38\u90fd\u5b58\u5728\u7740\u8026\u5408\u3002\n\n// \u6211\u4eec\u9996\u5148\u5c06\u5bf9\u89d2\u7ebf\u5411\u91cf\u521d\u59cb\u5316\u4e3a\u6b63\u786e\u7684\u5e73\u884c\u5e03\u5c40\u3002\u8fd9\u4e2a\u5411\u91cf\u88ab\u5c01\u88c5\u5728\u57fa\u7c7b MatrixFreeOperators::Base. \u4e2dDiagonalMatrix\u7c7b\u578b\u7684\u4e00\u4e2a\u540d\u4e3ainverse_diagonal_entries\u7684\u6210\u5458\u4e2d\uff0c\u8fd9\u4e2a\u6210\u5458\u662f\u4e00\u4e2a\u5171\u4eab\u6307\u9488\uff0c\u6211\u4eec\u9996\u5148\u9700\u8981\u521d\u59cb\u5316\u5b83\uff0c\u7136\u540e\u83b7\u5f97\u4ee3\u8868\u77e9\u9635\u4e2d\u5bf9\u89d2\u7ebf\u6761\u76ee\u7684\u5411\u91cf\u3002\u81f3\u4e8e\u5b9e\u9645\u7684\u5bf9\u89d2\u7ebf\u8ba1\u7b97\uff0c\u6211\u4eec\u518d\u6b21\u4f7f\u7528MatrixFree\u7684cell_loop\u57fa\u7840\u8bbe\u65bd\u6765\u8c03\u7528\u4e00\u4e2a\u540d\u4e3alocal_compute_diagonal()\u7684\u672c\u5730\u5de5\u4f5c\u7a0b\u5e8f\u3002\u7531\u4e8e\u6211\u4eec\u53ea\u5199\u8fdb\u4e00\u4e2a\u5411\u91cf\uff0c\u800c\u6ca1\u6709\u4efb\u4f55\u6e90\u5411\u91cf\uff0c\u6211\u4eec\u7528\u4e00\u4e2a<tt>unsigned int</tt>\u7c7b\u578b\u7684\u5047\u53c2\u6570\u6765\u4ee3\u66ff\u6e90\u5411\u91cf\uff0c\u4ee5\u4fbf\u4e0ecell_loop\u63a5\u53e3\u786e\u8ba4\u3002\u5728\u5faa\u73af\u4e4b\u540e\uff0c\u6211\u4eec\u9700\u8981\u5c06\u53d7Dirichlet\u8fb9\u754c\u6761\u4ef6\u7ea6\u675f\u7684\u5411\u91cf\u6761\u76ee\u8bbe\u7f6e\u4e3a1\uff08\u8981\u4e48\u662fMatrixFree\u5185\u90e8AffineConstraints\u5bf9\u8c61\u63cf\u8ff0\u7684\u8fb9\u754c\u4e0a\u7684\u6761\u76ee\uff0c\u8981\u4e48\u662f\u81ea\u9002\u5e94\u591a\u7f51\u683c\u4e2d\u4e0d\u540c\u7f51\u683c\u5c42\u6b21\u4e4b\u95f4\u7684\u7d22\u5f15\uff09\u3002\u8fd9\u662f\u901a\u8fc7\u51fd\u6570 MatrixFreeOperators::Base::set_constrained_entries_to_one() \u5b8c\u6210\u7684\uff0c\u5e76\u4e0eBase\u7b97\u5b50\u63d0\u4f9b\u7684\u77e9\u9635-\u5411\u91cf\u4e58\u79ef\u4e2d\u7684\u8bbe\u7f6e\u76f8\u5339\u914d\u3002\u6700\u540e\uff0c\u6211\u4eec\u9700\u8981\u53cd\u8f6c\u5bf9\u89d2\u7ebf\u6761\u76ee\uff0c\u8fd9\u662f\u57fa\u4e8eJacobi\u8fed\u4ee3\u7684Chebyshev\u5e73\u6ed1\u5668\u6240\u8981\u6c42\u7684\u5f62\u5f0f\u3002\u5728\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u65ad\u8a00\u6240\u6709\u7684\u6761\u76ee\u90fd\u662f\u975e\u96f6\u7684\uff0c\u56e0\u4e3a\u5b83\u4eec\u5e94\u8be5\u4ece\u79ef\u5206\u4e2d\u83b7\u5f97\u6b63\u7684\u8d21\u732e\uff0c\u6216\u8005\u88ab\u7ea6\u675f\u5e76\u88ab @p set_constrained_entries_to_one() \u4ee5\u4e0b\u7684cell_loop\u5904\u7406\u3002\n\n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::compute_diagonal() \n  { \n    this->inverse_diagonal_entries.reset( \n      new DiagonalMatrix<LinearAlgebra::distributed::Vector<number>>()); \n    LinearAlgebra::distributed::Vector<number> &inverse_diagonal = \n      this->inverse_diagonal_entries->get_vector(); \n    this->data->initialize_dof_vector(inverse_diagonal); \n    unsigned int dummy = 0; \n    this->data->cell_loop(&LaplaceOperator::local_compute_diagonal, \n                          this, \n                          inverse_diagonal, \n                          dummy); \n\n    this->set_constrained_entries_to_one(inverse_diagonal); \n\n    for (unsigned int i = 0; i < inverse_diagonal.locally_owned_size(); ++i) \n      { \n        Assert(inverse_diagonal.local_element(i) > 0., \n               ExcMessage(\"No diagonal entry in a positive definite operator \" \n                          \"should be zero\")); \n        inverse_diagonal.local_element(i) = \n          1. / inverse_diagonal.local_element(i); \n      } \n  } \n\n// \u5728\u672c\u5730\u8ba1\u7b97\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u901a\u8fc7\u5faa\u73af\u672c\u5730\u77e9\u9635\u4e2d\u7684\u6240\u6709\u5217\u6765\u8ba1\u7b97\u5bf9\u89d2\u7ebf\uff0c\u5e76\u5c06\u6761\u76ee1\u653e\u5728<i>i</i>\u69fd\u4e2d\uff0c\u5c06\u6761\u76ee0\u653e\u5728\u6240\u6709\u5176\u4ed6\u69fd\u4e2d\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u4e00\u6b21\u5728\u4e00\u4e2a\u5355\u4f4d\u5411\u91cf\u4e0a\u5e94\u7528\u5355\u5143\u683c\u5fae\u5206\u8fd0\u7b97\u3002\u8c03\u7528 FEEvaluation::evaluate, \u7684\u5185\u90e8\u90e8\u5206\u662f\u5bf9\u6b63\u4ea4\u70b9\u7684\u5faa\u73af\uff0c FEEvalution::integrate, \u5219\u4e0elocal_apply\u51fd\u6570\u5b8c\u5168\u76f8\u540c\u3002\u4e4b\u540e\uff0c\u6211\u4eec\u6311\u51fa\u672c\u5730\u7ed3\u679c\u7684\u7b2c<i>i</i>\u4e2a\u6761\u76ee\uff0c\u5e76\u5c06\u5176\u653e\u5165\u4e00\u4e2a\u4e34\u65f6\u5b58\u50a8\u5668\uff08\u56e0\u4e3a\u6211\u4eec\u5728\u4e0b\u4e00\u6b21\u5faa\u73af\u8fed\u4ee3\u65f6\u8986\u76d6\u4e86 FEEvaluation::get_dof_value() \u540e\u9762\u6570\u7ec4\u4e2d\u7684\u6240\u6709\u6761\u76ee\uff09\u3002\u6700\u540e\uff0c\u4e34\u65f6\u5b58\u50a8\u88ab\u5199\u5230\u76ee\u6807\u5411\u91cf\u4e2d\u3002\u6ce8\u610f\u6211\u4eec\u662f\u5982\u4f55\u4f7f\u7528 FEEvaluation::get_dof_value() \u548c FEEvaluation::submit_dof_value() \u6765\u8bfb\u53d6\u548c\u5199\u5165FEEvaluation\u7528\u4e8e\u79ef\u5206\u7684\u6570\u636e\u5b57\u6bb5\uff0c\u5e76\u5728\u53e6\u4e00\u65b9\u9762\u5199\u5165\u5168\u5c40\u5411\u91cf\u7684\u3002\n\n// \u9274\u4e8e\u6211\u4eec\u53ea\u5bf9\u77e9\u9635\u7684\u5bf9\u89d2\u7ebf\u611f\u5174\u8da3\uff0c\u6211\u4eec\u7b80\u5355\u5730\u6254\u6389\u4e86\u6cbf\u9014\u8ba1\u7b97\u8fc7\u7684\u672c\u5730\u77e9\u9635\u7684\u6240\u6709\u5176\u4ed6\u6761\u76ee\u3002\u867d\u7136\u8ba1\u7b97\u5b8c\u6574\u7684\u5355\u5143\u683c\u77e9\u9635\uff0c\u7136\u540e\u6254\u6389\u9664\u5bf9\u89d2\u7ebf\u4ee5\u5916\u7684\u6240\u6709\u4e1c\u897f\u770b\u8d77\u6765\u5f88\u6d6a\u8d39\uff0c\u4f46\u662f\u6574\u5408\u7684\u6548\u7387\u5f88\u9ad8\uff0c\u6240\u4ee5\u8ba1\u7b97\u5e76\u6ca1\u6709\u82b1\u8d39\u592a\u591a\u65f6\u95f4\u3002\u8bf7\u6ce8\u610f\uff0c\u5bf9\u4e8e\u591a\u9879\u5f0f\u5ea6\u6570\u6765\u8bf4\uff0c\u6bcf\u4e2a\u5143\u7d20\u7684\u7b97\u5b50\u8bc4\u4f30\u7684\u590d\u6742\u5ea6\u662f $\\mathcal O((p+1)^{d+1})$ \uff0c\u6240\u4ee5\u8ba1\u7b97\u6574\u4e2a\u77e9\u9635\u8981\u82b1\u8d39\u6211\u4eec $\\mathcal O((p+1)^{2d+1})$ \u6b21\u64cd\u4f5c\uff0c\u4e0e\u7528FEValues\u8ba1\u7b97\u5bf9\u89d2\u7ebf\u7684\u590d\u6742\u5ea6 $\\mathcal O((p+1)^{2d})$ \u76f8\u5dee\u4e0d\u5927\u3002\u7531\u4e8eFEEvaluation\u4e5f\u7531\u4e8e\u77e2\u91cf\u5316\u548c\u5176\u4ed6\u4f18\u5316\u800c\u5927\u5927\u52a0\u5feb\u4e86\u901f\u5ea6\uff0c\u6240\u4ee5\u7528\u8fd9\u4e2a\u51fd\u6570\u8ba1\u7b97\u5bf9\u89d2\u7ebf\u5b9e\u9645\u4e0a\u662f\u6700\u5feb\u7684\uff08\u7b80\u5355\u7684\uff09\u53d8\u91cf\u3002(\u6709\u53ef\u80fd\u7528 $\\mathcal O((p+1)^{d+1})$ \u64cd\u4f5c\u4e2d\u7684\u548c\u5206\u89e3\u6280\u672f\u6765\u8ba1\u7b97\u5bf9\u89d2\u7ebf\uff0c\u8fd9\u6d89\u53ca\u5230\u7279\u522b\u9002\u5e94\u7684\u5185\u6838&mdash;\u4f46\u662f\u7531\u4e8e\u8fd9\u79cd\u5185\u6838\u53ea\u5728\u7279\u5b9a\u7684\u73af\u5883\u4e0b\u6709\u7528\uff0c\u800c\u5bf9\u89d2\u7ebf\u8ba1\u7b97\u901a\u5e38\u4e0d\u5728\u5173\u952e\u8def\u5f84\u4e0a\uff0c\u6240\u4ee5\u5b83\u4eec\u6ca1\u6709\u5728deal.II\u4e2d\u5b9e\u73b0\u3002)\n\n// \u6ce8\u610f\u5728\u5411\u91cf\u4e0a\u8c03\u7528distribution_local_to_global\u6765\u5c06\u5bf9\u89d2\u7ebf\u6761\u76ee\u7d2f\u79ef\u5230\u5168\u5c40\u77e9\u9635\u7684\u4ee3\u7801\u6709\u4e00\u4e9b\u9650\u5236\u3002\u5bf9\u4e8e\u5e26\u6709\u60ac\u7a7a\u8282\u70b9\u7ea6\u675f\u7684\u64cd\u4f5c\u8005\u6765\u8bf4\uff0c\u5728distribution_local_to_global\u7684\u8c03\u7528\u4e2d\uff0c\u5c06\u4e00\u4e2a\u53d7\u7ea6\u675f\u7684DoF\u7684\u79ef\u5206\u8d21\u732e\u5206\u914d\u7ed9\u5176\u4ed6\u51e0\u4e2a\u6761\u76ee\uff0c\u8fd9\u91cc\u4f7f\u7528\u7684\u5411\u91cf\u63a5\u53e3\u5e76\u4e0d\u5b8c\u5168\u8ba1\u7b97\u5bf9\u89d2\u7ebf\u6761\u76ee\uff0c\u800c\u662f\u5c06\u4e00\u4e9b\u4f4d\u4e8e\u672c\u5730\u77e9\u9635\u5bf9\u89d2\u7ebf\u4e0a\u7684\u8d21\u732e\uff0c\u6700\u7ec8\u5728\u5168\u5c40\u77e9\u9635\u7684\u975e\u5bf9\u89d2\u7ebf\u4f4d\u7f6e\u5806\u79ef\u5230\u5bf9\u89d2\u7ebf\u4e0a\u3002\u5982<a href=\"http:dx.doi.org/10.4208/cicp.101214.021015a\">Kormann (2016), section 5.3</a>\u4e2d\u6240\u89e3\u91ca\u7684\uff0c\u8be5\u7ed3\u679c\u5728\u79bb\u6563\u5316\u7cbe\u5ea6\u4e0a\u662f\u6b63\u786e\u7684\uff0c\u4f46\u5728\u6570\u5b66\u4e0a\u5e76\u4e0d\u5e73\u7b49\u3002\u5728\u8fd9\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u4e2d\uff0c\u4e0d\u4f1a\u53d1\u751f\u4efb\u4f55\u5371\u5bb3\uff0c\u56e0\u4e3a\u5bf9\u89d2\u7ebf\u53ea\u7528\u4e8e\u6ca1\u6709\u60ac\u7a7a\u8282\u70b9\u7ea6\u675f\u51fa\u73b0\u7684\u591a\u7f51\u683c\u6c34\u5e73\u77e9\u9635\u4e2d\u3002\n\n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::local_compute_diagonal( \n    const MatrixFree<dim, number> &             data, \n    LinearAlgebra::distributed::Vector<number> &dst, \n    const unsigned int &, \n    const std::pair<unsigned int, unsigned int> &cell_range) const \n  { \n    FEEvaluation<dim, fe_degree, fe_degree + 1, 1, number> phi(data); \n\n    AlignedVector<VectorizedArray<number>> diagonal(phi.dofs_per_cell); \n\n    for (unsigned int cell = cell_range.first; cell < cell_range.second; ++cell) \n      { \n        AssertDimension(coefficient.size(0), data.n_cell_batches()); \n        AssertDimension(coefficient.size(1), phi.n_q_points); \n\n        phi.reinit(cell); \n        for (unsigned int i = 0; i < phi.dofs_per_cell; ++i) \n          { \n            for (unsigned int j = 0; j < phi.dofs_per_cell; ++j) \n              phi.submit_dof_value(VectorizedArray<number>(), j); \n            phi.submit_dof_value(make_vectorized_array<number>(1.), i); \n\n            phi.evaluate(EvaluationFlags::gradients); \n            for (unsigned int q = 0; q < phi.n_q_points; ++q) \n              phi.submit_gradient(coefficient(cell, q) * phi.get_gradient(q), \n                                  q); \n            phi.integrate(EvaluationFlags::gradients); \n            diagonal[i] = phi.get_dof_value(i); \n          } \n        for (unsigned int i = 0; i < phi.dofs_per_cell; ++i) \n          phi.submit_dof_value(diagonal[i], i); \n        phi.distribute_local_to_global(dst); \n      } \n  } \n\n//  @sect3{LaplaceProblem class}  \n\n// \u8fd9\u4e2a\u7c7b\u662f\u57fa\u4e8e  step-16  \u4e2d\u7684\u4e00\u4e2a\u3002\u7136\u800c\uff0c\u6211\u4eec\u7528\u6211\u4eec\u7684\u65e0\u77e9\u9635\u5b9e\u73b0\u53d6\u4ee3\u4e86SparseMatrix<double>\u7c7b\uff0c\u8fd9\u610f\u5473\u7740\u6211\u4eec\u4e5f\u53ef\u4ee5\u8df3\u8fc7\u7a00\u758f\u6027\u6a21\u5f0f\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u5b9a\u4e49LaplaceOperator\u7c7b\u65f6\uff0c\u5c06\u6709\u9650\u5143\u7684\u5ea6\u6570\u4f5c\u4e3a\u6a21\u677f\u53c2\u6570\uff08\u8be5\u503c\u5728\u6587\u4ef6\u7684\u9876\u90e8\u5b9a\u4e49\uff09\uff0c\u6211\u4eec\u4f7f\u7528\u6d6e\u70b9\u6570\u6765\u8868\u793a\u591a\u7f51\u683c\u7ea7\u77e9\u9635\u3002\n\n// \u8be5\u7c7b\u8fd8\u6709\u4e00\u4e2a\u6210\u5458\u53d8\u91cf\uff0c\u7528\u6765\u8bb0\u5f55\u5728\u6211\u4eec\u771f\u6b63\u53bb\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u4e4b\u524d\u8bbe\u7f6e\u6574\u4e2a\u6570\u636e\u94fe\u7684\u6240\u6709\u8be6\u7ec6\u65f6\u95f4\u3002\u6b64\u5916\uff0c\u8fd8\u6709\u4e00\u4e2a\u8f93\u51fa\u6d41\uff08\u9ed8\u8ba4\u60c5\u51b5\u4e0b\u662f\u7981\u7528\u7684\uff09\uff0c\u53ef\u4ee5\u7528\u6765\u8f93\u51fa\u5404\u4e2a\u8bbe\u7f6e\u64cd\u4f5c\u7684\u7ec6\u8282\uff0c\u800c\u4e0d\u662f\u9ed8\u8ba4\u60c5\u51b5\u4e0b\u53ea\u6253\u5370\u51fa\u7684\u6458\u8981\u3002\n\n// \u7531\u4e8e\u8fd9\u4e2a\u7a0b\u5e8f\u88ab\u8bbe\u8ba1\u6210\u4e0eMPI\u4e00\u8d77\u4f7f\u7528\uff0c\u6211\u4eec\u4e5f\u63d0\u4f9b\u4e86\u901a\u5e38\u7684 @p pcout \u8f93\u51fa\u6d41\uff0c\u53ea\u6253\u5370MPI\u7b49\u7ea7\u4e3a0\u7684\u5904\u7406\u5668\u7684\u4fe1\u606f\u3002\u8fd9\u4e2a\u7a0b\u5e8f\u4f7f\u7528\u7684\u7f51\u683c\u53ef\u4ee5\u662f\u57fa\u4e8ep4est\u7684\u5206\u5e03\u5f0f\u4e09\u89d2\u56fe\uff08\u5728deal.II\u88ab\u914d\u7f6e\u4e3a\u4f7f\u7528p4est\u7684\u60c5\u51b5\u4e0b\uff09\uff0c\u5426\u5219\u5b83\u5c31\u662f\u4e00\u4e2a\u53ea\u5728\u6ca1\u6709MPI\u7684\u60c5\u51b5\u4e0b\u8fd0\u884c\u7684\u4e32\u884c\u7f51\u683c\u3002\n\n  template <int dim> \n  class LaplaceProblem \n  { \n  public: \n    LaplaceProblem(); \n    void run(); \n\n  private: \n    void setup_system(); \n    void assemble_rhs(); \n    void solve(); \n    void output_results(const unsigned int cycle) const; \n\n#ifdef DEAL_II_WITH_P4EST \n    parallel::distributed::Triangulation<dim> triangulation; \n#else \n    Triangulation<dim> triangulation; \n#endif \n\n    FE_Q<dim>       fe; \n    DoFHandler<dim> dof_handler; \n\n    MappingQ1<dim> mapping; \n\n    AffineConstraints<double> constraints;\n    using SystemMatrixType = \n      LaplaceOperator<dim, degree_finite_element, double>; \n    SystemMatrixType system_matrix; \n\n    MGConstrainedDoFs mg_constrained_dofs; \n    using LevelMatrixType = LaplaceOperator<dim, degree_finite_element, float>; \n    MGLevelObject<LevelMatrixType> mg_matrices; \n\n    LinearAlgebra::distributed::Vector<double> solution; \n    LinearAlgebra::distributed::Vector<double> system_rhs; \n\n    double             setup_time; \n    ConditionalOStream pcout; \n    ConditionalOStream time_details; \n  }; \n\n// \u5f53\u6211\u4eec\u521d\u59cb\u5316\u6709\u9650\u5143\u65f6\uff0c\u6211\u4eec\u5f53\u7136\u4e5f\u8981\u4f7f\u7528\u6587\u4ef6\u9876\u90e8\u6307\u5b9a\u7684\u5ea6\u6570\uff08\u5426\u5219\uff0c\u5728\u67d0\u4e9b\u65f6\u5019\u4f1a\u629b\u51fa\u4e00\u4e2a\u5f02\u5e38\uff0c\u56e0\u4e3a\u5728\u6a21\u677f\u5316\u7684LaplaceOperator\u7c7b\u4e2d\u5b9a\u4e49\u7684\u8ba1\u7b97\u5185\u6838\u548cMatrixFree\u8bfb\u51fa\u7684\u6709\u9650\u5143\u4fe1\u606f\u5c06\u4e0d\u5339\u914d\uff09\u3002\u4e09\u89d2\u5f62\u7684\u6784\u9020\u51fd\u6570\u9700\u8981\u8bbe\u7f6e\u4e00\u4e2a\u989d\u5916\u7684\u6807\u5fd7\uff0c\u544a\u8bc9\u7f51\u683c\u8981\u7b26\u5408\u9876\u70b9\u4e0a\u76842:1\u5355\u5143\u5e73\u8861\uff0c\u8fd9\u5bf9\u4e8e\u51e0\u4f55\u591a\u7f51\u683c\u4f8b\u7a0b\u7684\u6536\u655b\u662f\u5fc5\u9700\u7684\u3002\u5bf9\u4e8e\u5206\u5e03\u5f0f\u7f51\u683c\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u7279\u522b\u542f\u7528\u591a\u7f51\u683c\u7684\u5c42\u6b21\u7ed3\u6784\u3002\n\n  template <int dim> \n  LaplaceProblem<dim>::LaplaceProblem() \n    : \n#ifdef DEAL_II_WITH_P4EST \n    triangulation( \n      MPI_COMM_WORLD, \n      Triangulation<dim>::limit_level_difference_at_vertices, \n      parallel::distributed::Triangulation<dim>::construct_multigrid_hierarchy) \n    , \n#else \n    triangulation(Triangulation<dim>::limit_level_difference_at_vertices) \n    , \n#endif \n    fe(degree_finite_element) \n    , dof_handler(triangulation) \n    , setup_time(0.) \n    , pcout(std::cout, Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0) \n    , \n\n// LaplaceProblem\u7c7b\u62e5\u6709\u4e00\u4e2a\u989d\u5916\u7684\u8f93\u51fa\u6d41\uff0c\u7528\u4e8e\u6536\u96c6\u5173\u4e8e\u8bbe\u7f6e\u9636\u6bb5\u7684\u8be6\u7ec6\u65f6\u95f4\u4fe1\u606f\u3002\u8fd9\u4e2a\u6d41\u88ab\u79f0\u4e3atime_details\uff0c\u9ed8\u8ba4\u60c5\u51b5\u4e0b\u901a\u8fc7\u8fd9\u91cc\u6307\u5b9a\u7684 @p false \u53c2\u6570\u88ab\u7981\u7528\u3002\u5bf9\u4e8e\u8be6\u7ec6\u7684\u65f6\u95f4\uff0c\u53bb\u6389 @p false \u53c2\u6570\u53ef\u4ee5\u6253\u5370\u51fa\u6240\u6709\u7684\u7ec6\u8282\u3002\n\n    time_details(std::cout, \n                 false && Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0) \n  {} \n\n//  @sect4{LaplaceProblem::setup_system}  \n\n// \u8bbe\u7f6e\u9636\u6bb5\u4e0e step-16 \u7c7b\u4f3c\uff0c\u7531\u4e8eLaplaceOperator\u7c7b\u7684\u5b58\u5728\u800c\u6709\u76f8\u5173\u7684\u53d8\u5316\u3002\u9996\u5148\u8981\u505a\u7684\u662f\u8bbe\u7f6eDoFHandler\uff0c\u5305\u62ec\u591a\u7f51\u683c\u5c42\u6b21\u7684\u81ea\u7531\u5ea6\uff0c\u4ee5\u53ca\u521d\u59cb\u5316\u60ac\u6302\u8282\u70b9\u7684\u7ea6\u675f\u548c\u540c\u8d28\u4e8c\u5217\u6761\u4ef6\u3002\u7531\u4e8e\u6211\u4eec\u6253\u7b97\u7528MPI\u7684%\u5e76\u884c\u65b9\u5f0f\u4f7f\u7528\u8fd9\u4e2a\u7a0b\u5e8f\uff0c\u6211\u4eec\u9700\u8981\u786e\u4fdd\u7ea6\u675f\u6761\u4ef6\u80fd\u77e5\u9053\u672c\u5730\u76f8\u5173\u7684\u81ea\u7531\u5ea6\uff0c\u5426\u5219\u5728\u4f7f\u7528\u8d85\u8fc7\u51e0\u4ebf\u4e2a\u81ea\u7531\u5ea6\u7684\u65f6\u5019\uff0c\u5b58\u50a8\u4f1a\u7206\u70b8\uff0c\u89c1  step-40  \u3002\n\n// \u4e00\u65e6\u6211\u4eec\u521b\u5efa\u4e86\u591a\u7f51\u683cdof_handler\u548c\u7ea6\u675f\u6761\u4ef6\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u4e3a\u5168\u5c40\u77e9\u9635\u7b97\u5b50\u4ee5\u53ca\u591a\u7f51\u683c\u65b9\u6848\u7684\u6bcf\u4e00\u5c42\u8c03\u7528reinit\u51fd\u6570\u3002\u4e3b\u8981\u7684\u64cd\u4f5c\u662f\u4e3a\u95ee\u9898\u8bbe\u7f6e <code> MatrixFree </code> \u5b9e\u4f8b\u3002 <code>LaplaceOperator</code> \u7c7b\u7684\u57fa\u7c7b\uff0c MatrixFreeOperators::Base, \u88ab\u521d\u59cb\u5316\u4e3a\u4e00\u4e2a\u6307\u5411MatrixFree\u5bf9\u8c61\u7684\u5171\u4eab\u6307\u9488\u3002\u8fd9\u6837\uff0c\u6211\u4eec\u53ef\u4ee5\u5728\u8fd9\u91cc\u7b80\u5355\u5730\u521b\u5efa\u5b83\uff0c\u7136\u540e\u5c06\u5b83\u5206\u522b\u4f20\u9012\u7ed9\u7cfb\u7edf\u77e9\u9635\u548c\u6c34\u5e73\u77e9\u9635\u3002\u4e3a\u4e86\u8bbe\u7f6eMatrixFree\uff0c\u6211\u4eec\u9700\u8981\u6fc0\u6d3bMatrixFree\u7684AdditionalData\u5b57\u6bb5\u4e2d\u7684\u66f4\u65b0\u6807\u5fd7\uff0c\u4f7f\u5176\u80fd\u591f\u5b58\u50a8\u5b9e\u7a7a\u95f4\u4e2d\u7684\u6b63\u4ea4\u70b9\u5750\u6807\uff08\u9ed8\u8ba4\u60c5\u51b5\u4e0b\uff0c\u5b83\u53ea\u7f13\u5b58\u68af\u5ea6\uff08\u53cd\u8f6c\u7f6e\u7684\u96c5\u5404\u5e03\uff09\u548cJxW\u503c\u7684\u6570\u636e\uff09\u3002\u8bf7\u6ce8\u610f\uff0c\u5982\u679c\u6211\u4eec\u8c03\u7528 reinit \u51fd\u6570\u800c\u4e0d\u6307\u5b9a\u7ea7\u522b\uff08\u5373\u7ed9\u51fa  <code>level = numbers::invalid_unsigned_int</code>  \uff09\uff0cMatrixFree \u5c06\u5728\u6d3b\u52a8\u5355\u5143\u4e0a\u6784\u5efa\u4e00\u4e2a\u5faa\u73af\u3002\u5728\u672c\u6559\u7a0b\u4e2d\uff0c\u9664\u4e86MPI\u4e4b\u5916\uff0c\u6211\u4eec\u4e0d\u4f7f\u7528\u7ebf\u7a0b\uff0c\u8fd9\u5c31\u662f\u4e3a\u4ec0\u4e48\u6211\u4eec\u901a\u8fc7\u5c06 MatrixFree::AdditionalData::tasks_parallel_scheme \u8bbe\u7f6e\u4e3a MatrixFree::AdditionalData::none. \u6765\u660e\u786e\u5730\u7981\u7528\u5b83 \u6700\u540e\uff0c\u7cfb\u6570\u88ab\u8bc4\u4f30\uff0c\u5411\u91cf\u88ab\u521d\u59cb\u5316\uff0c\u5982\u4e0a\u6240\u8ff0\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::setup_system() \n  { \n    Timer time; \n    setup_time = 0; \n\n    system_matrix.clear(); \n    mg_matrices.clear_elements(); \n\n    dof_handler.distribute_dofs(fe); \n    dof_handler.distribute_mg_dofs(); \n\n    pcout << \"Number of degrees of freedom: \" << dof_handler.n_dofs() \n          << std::endl; \n\n    IndexSet locally_relevant_dofs; \n    DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs); \n\n    constraints.clear(); \n    constraints.reinit(locally_relevant_dofs); \n    DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n    VectorTools::interpolate_boundary_values( \n      mapping, dof_handler, 0, Functions::ZeroFunction<dim>(), constraints); \n    constraints.close(); \n    setup_time += time.wall_time(); \n    time_details << \"Distribute DoFs & B.C.     (CPU/wall) \" << time.cpu_time() \n                 << \"s/\" << time.wall_time() << \"s\" << std::endl; \n    time.restart(); \n\n    { \n      typename MatrixFree<dim, double>::AdditionalData additional_data; \n      additional_data.tasks_parallel_scheme = \n        MatrixFree<dim, double>::AdditionalData::none; \n      additional_data.mapping_update_flags = \n        (update_gradients | update_JxW_values | update_quadrature_points); \n      std::shared_ptr<MatrixFree<dim, double>> system_mf_storage( \n        new MatrixFree<dim, double>()); \n      system_mf_storage->reinit(mapping, \n                                dof_handler, \n                                constraints, \n                                QGauss<1>(fe.degree + 1), \n                                additional_data); \n      system_matrix.initialize(system_mf_storage); \n    } \n\n    system_matrix.evaluate_coefficient(Coefficient<dim>()); \n\n    system_matrix.initialize_dof_vector(solution); \n    system_matrix.initialize_dof_vector(system_rhs); \n\n    setup_time += time.wall_time(); \n    time_details << \"Setup matrix-free system   (CPU/wall) \" << time.cpu_time() \n                 << \"s/\" << time.wall_time() << \"s\" << std::endl; \n    time.restart(); \n\n// \u63a5\u4e0b\u6765\uff0c\u521d\u59cb\u5316\u6240\u6709\u5c42\u6b21\u4e0a\u7684\u591a\u7f51\u683c\u65b9\u6cd5\u7684\u77e9\u9635\u3002\u6570\u636e\u7ed3\u6784MGConstrainedDoFs\u4fdd\u7559\u4e86\u53d7\u8fb9\u754c\u6761\u4ef6\u7ea6\u675f\u7684\u6307\u6570\u4fe1\u606f\uff0c\u4ee5\u53ca\u4e0d\u540c\u7ec6\u5316\u5c42\u6b21\u4e4b\u95f4\u7684\u8fb9\u7f18\u6307\u6570\uff0c\u5982 step-16 \u6559\u7a0b\u7a0b\u5e8f\u4e2d\u6240\u8ff0\u3002\u7136\u540e\uff0c\u6211\u4eec\u7a7f\u8fc7\u7f51\u683c\u7684\u5404\u4e2a\u5c42\u6b21\uff0c\u5728\u6bcf\u4e2a\u5c42\u6b21\u4e0a\u6784\u5efa\u7ea6\u675f\u548c\u77e9\u9635\u3002\u8fd9\u4e0e\u539f\u59cb\u7f51\u683c\u4e0a\u7684\u7cfb\u7edf\u77e9\u9635\u7684\u6784\u9020\u5bc6\u5207\u76f8\u5173\uff0c\u53ea\u662f\u5728\u8bbf\u95ee\u5c42\u7ea7\u4fe1\u606f\u800c\u4e0d\u662f\u6d3b\u52a8\u5355\u5143\u7684\u4fe1\u606f\u65f6\uff0c\u5728\u547d\u540d\u4e0a\u7565\u6709\u4e0d\u540c\u3002\n\n    const unsigned int nlevels = triangulation.n_global_levels(); \n    mg_matrices.resize(0, nlevels - 1); \n\n    std::set<types::boundary_id> dirichlet_boundary; \n    dirichlet_boundary.insert(0); \n    mg_constrained_dofs.initialize(dof_handler); \n    mg_constrained_dofs.make_zero_boundary_constraints(dof_handler, \n                                                       dirichlet_boundary); \n\n    for (unsigned int level = 0; level < nlevels; ++level) \n      { \n        IndexSet relevant_dofs; \n        DoFTools::extract_locally_relevant_level_dofs(dof_handler, \n                                                      level, \n                                                      relevant_dofs); \n        AffineConstraints<double> level_constraints; \n        level_constraints.reinit(relevant_dofs); \n        level_constraints.add_lines( \n          mg_constrained_dofs.get_boundary_indices(level)); \n        level_constraints.close(); \n\n        typename MatrixFree<dim, float>::AdditionalData additional_data; \n        additional_data.tasks_parallel_scheme = \n          MatrixFree<dim, float>::AdditionalData::none; \n        additional_data.mapping_update_flags = \n          (update_gradients | update_JxW_values | update_quadrature_points); \n        additional_data.mg_level = level; \n        std::shared_ptr<MatrixFree<dim, float>> mg_mf_storage_level( \n          new MatrixFree<dim, float>()); \n        mg_mf_storage_level->reinit(mapping, \n                                    dof_handler, \n                                    level_constraints, \n                                    QGauss<1>(fe.degree + 1), \n                                    additional_data); \n\n        mg_matrices[level].initialize(mg_mf_storage_level, \n                                      mg_constrained_dofs, \n                                      level); \n        mg_matrices[level].evaluate_coefficient(Coefficient<dim>()); \n      } \n    setup_time += time.wall_time(); \n    time_details << \"Setup matrix-free levels   (CPU/wall) \" << time.cpu_time() \n                 << \"s/\" << time.wall_time() << \"s\" << std::endl; \n  } \n\n//  @sect4{LaplaceProblem::assemble_rhs}  \n\n// \u7ec4\u88c5\u51fd\u6570\u975e\u5e38\u7b80\u5355\uff0c\u56e0\u4e3a\u6211\u4eec\u6240\u8981\u505a\u7684\u5c31\u662f\u7ec4\u88c5\u53f3\u4fa7\u3002\u591a\u4e8f\u4e86FEEvaluation\u548c\u6240\u6709\u7f13\u5b58\u5728MatrixFree\u7c7b\u4e2d\u7684\u6570\u636e\uff0c\u6211\u4eec\u4ece MatrixFreeOperators::Base, \u4e2d\u67e5\u8be2\uff0c\u8fd9\u53ef\u4ee5\u5728\u51e0\u884c\u4e2d\u5b8c\u6210\u3002\u7531\u4e8e\u8fd9\u4e2a\u8c03\u7528\u6ca1\u6709\u88ab\u5305\u88f9\u5230 MatrixFree::cell_loop \u4e2d\uff08\u8fd9\u5c06\u662f\u4e00\u4e2a\u66ff\u4ee3\u65b9\u6848\uff09\uff0c\u6211\u4eec\u4e00\u5b9a\u4e0d\u8981\u5fd8\u8bb0\u5728\u88c5\u914d\u7ed3\u675f\u65f6\u8c03\u7528compress()\uff0c\u5c06\u53f3\u624b\u8fb9\u7684\u6240\u6709\u8d21\u732e\u53d1\u9001\u7ed9\u5404\u81ea\u81ea\u7531\u5ea6\u7684\u6240\u6709\u8005\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::assemble_rhs() \n  { \n    Timer time; \n\n    system_rhs = 0; \n    FEEvaluation<dim, degree_finite_element> phi( \n      *system_matrix.get_matrix_free()); \n    for (unsigned int cell = 0; \n         cell < system_matrix.get_matrix_free()->n_cell_batches(); \n         ++cell) \n      { \n        phi.reinit(cell); \n        for (unsigned int q = 0; q < phi.n_q_points; ++q) \n          phi.submit_value(make_vectorized_array<double>(1.0), q); \n        phi.integrate(EvaluationFlags::values); \n        phi.distribute_local_to_global(system_rhs); \n      } \n    system_rhs.compress(VectorOperation::add); \n\n    setup_time += time.wall_time(); \n    time_details << \"Assemble right hand side   (CPU/wall) \" << time.cpu_time() \n                 << \"s/\" << time.wall_time() << \"s\" << std::endl; \n  } \n\n//  @sect4{LaplaceProblem::solve}  \n\n// \u89e3\u51b3\u7684\u8fc7\u7a0b\u4e0e  step-16  \u4e2d\u7c7b\u4f3c\u3002\u6211\u4eec\u5148\u4ece\u8f6c\u79fb\u7684\u8bbe\u7f6e\u5f00\u59cb\u3002\u5bf9\u4e8e LinearAlgebra::distributed::Vector, \u6765\u8bf4\uff0c\u6709\u4e00\u4e2a\u975e\u5e38\u5feb\u901f\u7684\u8f6c\u79fb\u7c7b\uff0c\u53eb\u505aMGTransferMatrixFree\uff0c\u5b83\u7528FEEvaluation\u4e2d\u540c\u6837\u7684\u5feb\u901f\u548c\u56e0\u5b50\u5316\u6838\u5728\u7f51\u683c\u5c42\u4e4b\u95f4\u8fdb\u884c\u63d2\u503c\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::solve() \n  { \n    Timer                            time; \n    MGTransferMatrixFree<dim, float> mg_transfer(mg_constrained_dofs); \n    mg_transfer.build(dof_handler); \n    setup_time += time.wall_time(); \n    time_details << \"MG build transfer time     (CPU/wall) \" << time.cpu_time() \n                 << \"s/\" << time.wall_time() << \"s\\n\"; \n    time.restart(); \n\n// \u4f5c\u4e3a\u4e00\u4e2a\u5e73\u6ed1\u5668\uff0c\u672c\u6559\u7a0b\u7a0b\u5e8f\u4f7f\u7528\u5207\u6bd4\u96ea\u592b\u8fed\u4ee3\uff0c\u800c\u4e0d\u662f step-16 \u4e2d\u7684SOR\u3002\uff08SOR\u5c06\u5f88\u96be\u5b9e\u73b0\uff0c\u56e0\u4e3a\u6211\u4eec\u6ca1\u6709\u660e\u786e\u7684\u77e9\u9635\u5143\u7d20\uff0c\u800c\u4e14\u5f88\u96be\u4f7f\u5176\u5728%\u5e76\u884c\u4e2d\u6709\u6548\u5de5\u4f5c\uff09\u3002 \u5e73\u6ed1\u5668\u662f\u7528\u6211\u4eec\u7684\u6c34\u5e73\u77e9\u9635\u548c\u5207\u6bd4\u96ea\u592b\u5e73\u6ed1\u5668\u7684\u5f3a\u5236\u6027\u9644\u52a0\u6570\u636e\u521d\u59cb\u5316\u7684\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u4e00\u4e2a\u76f8\u5bf9\u8f83\u9ad8\u7684\u5ea6\u6570\uff085\uff09\uff0c\u56e0\u4e3a\u77e9\u9635-\u5411\u91cf\u4e58\u79ef\u662f\u6bd4\u8f83\u4fbf\u5b9c\u7684\u3002\u6211\u4eec\u9009\u62e9\u5728\u5e73\u6ed1\u5668\u4e2d\u5e73\u6ed1\u51fa $[1.2 \\hat{\\lambda}_{\\max}/15,1.2 \\hat{\\lambda}_{\\max}]$ \u7684\u8303\u56f4\uff0c\u5176\u4e2d $\\hat{\\lambda}_{\\max}$ \u662f\u5bf9\u6700\u5927\u7279\u5f81\u503c\u7684\u4f30\u8ba1\uff08\u7cfb\u65701.2\u5728PreconditionChebyshev\u4e2d\u5e94\u7528\uff09\u3002\u4e3a\u4e86\u8ba1\u7b97\u8be5\u7279\u5f81\u503c\uff0cChebyshev\u521d\u59cb\u5316\u6267\u884c\u4e86\u51e0\u6b65\u6ca1\u6709\u9884\u5904\u7406\u7684CG\u7b97\u6cd5\u3002\u7531\u4e8e\u6700\u9ad8\u7684\u7279\u5f81\u503c\u901a\u5e38\u662f\u6700\u5bb9\u6613\u627e\u5230\u7684\uff0c\u800c\u4e14\u4e00\u4e2a\u7c97\u7565\u7684\u4f30\u8ba1\u5c31\u8db3\u591f\u4e86\uff0c\u6211\u4eec\u9009\u62e910\u6b21\u8fed\u4ee3\u3002\u6700\u540e\uff0c\u6211\u4eec\u8fd8\u8bbe\u7f6e\u4e86\u5207\u6bd4\u96ea\u592b\u65b9\u6cd5\u4e2d\u7684\u5185\u90e8\u9884\u5904\u7406\u7c7b\u578b\uff0c\u8fd9\u662f\u4e00\u4e2a\u96c5\u53ef\u6bd4\u8fed\u4ee3\u3002\u8fd9\u7531DiagonalMatrix\u7c7b\u6765\u8868\u793a\uff0c\u8be5\u7c7b\u5f97\u5230\u4e86\u7531\u6211\u4eec\u7684LaplaceOperator\u7c7b\u63d0\u4f9b\u7684\u53cd\u5bf9\u89d2\u7ebf\u6761\u76ee\u3002\n\n// \u5728\u7b2c0\u5c42\uff0c\u6211\u4eec\u4ee5\u4e0d\u540c\u7684\u65b9\u5f0f\u521d\u59cb\u5316\u5e73\u6ed1\u5668\uff0c\u56e0\u4e3a\u6211\u4eec\u60f3\u4f7f\u7528\u5207\u6bd4\u96ea\u592b\u8fed\u4ee3\u4f5c\u4e3a\u6c42\u89e3\u5668\u3002PreconditionChebyshev\u5141\u8bb8\u7528\u6237\u5207\u6362\u5230\u6c42\u89e3\u5668\u6a21\u5f0f\uff0c\u5176\u4e2d\u8fed\u4ee3\u6b21\u6570\u5728\u5185\u90e8\u9009\u62e9\u4e3a\u6b63\u786e\u503c\u3002\u5728\u9644\u52a0\u6570\u636e\u5bf9\u8c61\u4e2d\uff0c\u901a\u8fc7\u5c06\u591a\u9879\u5f0f\u7684\u5ea6\u6570\u9009\u62e9\u4e3a @p numbers::invalid_unsigned_int. \u6765\u6fc0\u6d3b\u8fd9\u4e00\u8bbe\u7f6e\uff0c\u7136\u540e\u7b97\u6cd5\u5c06\u653b\u51fb\u7c97\u7ea7\u77e9\u9635\u4e2d\u6700\u5c0f\u548c\u6700\u5927\u4e4b\u95f4\u7684\u6240\u6709\u7279\u5f81\u503c\u3002\u5207\u6bd4\u96ea\u592b\u5e73\u6ed1\u5668\u7684\u6b65\u6570\u662f\u8fd9\u6837\u9009\u62e9\u7684\uff1a\u5207\u6bd4\u96ea\u592b\u6536\u655b\u4f30\u8ba1\u503c\u4fdd\u8bc1\u5c06\u6b8b\u5dee\u51cf\u5c11\u5230\u53d8\u91cf @p  smoothing_range\u4e2d\u6307\u5b9a\u7684\u6570\u5b57\u3002\u6ce8\u610f\uff0c\u5bf9\u4e8e\u6c42\u89e3\u6765\u8bf4\uff0c @p smoothing_range \u662f\u4e00\u4e2a\u76f8\u5bf9\u7684\u516c\u5dee\uff0c\u5e76\u4e14\u9009\u62e9\u5c0f\u4e8e1\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u9009\u62e9\u4e09\u4e2a\u6570\u91cf\u7ea7\uff0c\u800c\u5f53\u53ea\u5bf9\u9009\u5b9a\u7684\u7279\u5f81\u503c\u8fdb\u884c\u5e73\u6ed1\u65f6\uff0c\u5b83\u662f\u4e00\u4e2a\u5927\u4e8e1\u7684\u6570\u5b57\u3002\n\n// \u4ece\u8ba1\u7b97\u7684\u89d2\u5ea6\u6765\u770b\uff0c\u53ea\u8981\u7c97\u7c92\u5ea6\u9002\u4e2d\uff0cChebyshev\u8fed\u4ee3\u662f\u4e00\u4e2a\u975e\u5e38\u6709\u5438\u5f15\u529b\u7684\u7c97\u7c92\u5ea6\u6c42\u89e3\u5668\u3002\u8fd9\u662f\u56e0\u4e3aChebyshev\u65b9\u6cd5\u53ea\u6267\u884c\u77e9\u9635-\u5411\u91cf\u4e58\u79ef\u548c\u5411\u91cf\u66f4\u65b0\uff0c\u8fd9\u901a\u5e38\u6bd4\u5176\u4ed6\u8fed\u4ee3\u65b9\u6cd5\u4e2d\u6d89\u53ca\u7684\u5185\u79ef\u66f4\u597d\u5730\u5e76\u884c\u5230\u6709\u51e0\u4e07\u4e2a\u6838\u5fc3\u7684\u6700\u5927\u96c6\u7fa4\u89c4\u6a21\u3002\u524d\u8005\u53ea\u6d89\u53ca\u5230\uff08\u7c97\uff09\u7f51\u683c\u4e2d\u90bb\u5c45\u4e4b\u95f4\u7684\u5c40\u90e8\u901a\u4fe1\uff0c\u800c\u540e\u8005\u5219\u9700\u8981\u5728\u6240\u6709\u5904\u7406\u5668\u4e0a\u8fdb\u884c\u5168\u5c40\u901a\u4fe1\u3002\n\n    using SmootherType = \n      PreconditionChebyshev<LevelMatrixType, \n                            LinearAlgebra::distributed::Vector<float>>; \n    mg::SmootherRelaxation<SmootherType, \n                           LinearAlgebra::distributed::Vector<float>> \n                                                         mg_smoother; \n    MGLevelObject<typename SmootherType::AdditionalData> smoother_data; \n    smoother_data.resize(0, triangulation.n_global_levels() - 1); \n    for (unsigned int level = 0; level < triangulation.n_global_levels(); \n         ++level) \n      { \n        if (level > 0) \n          { \n            smoother_data[level].smoothing_range     = 15.; \n            smoother_data[level].degree              = 5; \n            smoother_data[level].eig_cg_n_iterations = 10; \n          } \n        else \n          { \n            smoother_data[0].smoothing_range = 1e-3; \n            smoother_data[0].degree          = numbers::invalid_unsigned_int; \n            smoother_data[0].eig_cg_n_iterations = mg_matrices[0].m(); \n          } \n        mg_matrices[level].compute_diagonal(); \n        smoother_data[level].preconditioner = \n          mg_matrices[level].get_matrix_diagonal_inverse(); \n      } \n    mg_smoother.initialize(mg_matrices, smoother_data); \n\n    MGCoarseGridApplySmoother<LinearAlgebra::distributed::Vector<float>> \n      mg_coarse; \n    mg_coarse.initialize(mg_smoother); \n\n// \u4e0b\u4e00\u6b65\u662f\u8bbe\u7f6e\u60ac\u6302\u8282\u70b9\u60c5\u51b5\u4e0b\u6240\u9700\u7684\u63a5\u53e3\u77e9\u9635\u3002deal.II\u4e2d\u7684\u81ea\u9002\u5e94\u591a\u7f51\u683c\u5b9e\u73b0\u4e86\u4e00\u79cd\u53eb\u505a\u5c40\u90e8\u5e73\u6ed1\u7684\u65b9\u6cd5\u3002\u8fd9\u610f\u5473\u7740\u6700\u7ec6\u7ea7\u522b\u7684\u5e73\u6ed1\u53ea\u8986\u76d6\u56fa\u5b9a\uff08\u6700\u7ec6\uff09\u7f51\u683c\u7ea7\u522b\u6240\u5b9a\u4e49\u7684\u7f51\u683c\u7684\u5c40\u90e8\u90e8\u5206\uff0c\u800c\u5ffd\u7565\u4e86\u8ba1\u7b97\u57df\u4e2d\u7ec8\u7aef\u5355\u5143\u6bd4\u8be5\u7ea7\u522b\u66f4\u7c97\u7684\u90e8\u5206\u3002\u968f\u7740\u8be5\u65b9\u6cd5\u5411\u66f4\u7c97\u7684\u7ea7\u522b\u53d1\u5c55\uff0c\u8d8a\u6765\u8d8a\u591a\u7684\u5168\u5c40\u7f51\u683c\u5c06\u88ab\u8986\u76d6\u3002\u5728\u67d0\u4e2a\u66f4\u7c97\u7684\u5c42\u6b21\u4e0a\uff0c\u6574\u4e2a\u7f51\u683c\u5c06\u88ab\u8986\u76d6\u3002\u7531\u4e8e\u591a\u7f51\u683c\u65b9\u6cd5\u4e2d\u7684\u6240\u6709\u5c42\u6b21\u77e9\u9635\u90fd\u8986\u76d6\u4e86\u7f51\u683c\u4e2d\u7684\u5355\u4e00\u5c42\u6b21\uff0c\u6240\u4ee5\u5728\u5c42\u6b21\u77e9\u9635\u4e0a\u4e0d\u4f1a\u51fa\u73b0\u60ac\u7a7a\u8282\u70b9\u3002\u5728\u591a\u7f51\u683c\u5c42\u4e4b\u95f4\u7684\u754c\u9762\u4e0a\uff0c\u5728\u5e73\u6ed1\u7684\u540c\u65f6\u8bbe\u7f6e\u540c\u8d28Dirichlet\u8fb9\u754c\u6761\u4ef6\u3002\u7136\u800c\uff0c\u5f53\u6b8b\u5dee\u88ab\u8f6c\u79fb\u5230\u4e0b\u4e00\u4e2a\u66f4\u7c97\u7684\u5c42\u6b21\u65f6\uff0c\u9700\u8981\u8003\u8651\u5230\u591a\u7f51\u683c\u754c\u9762\u7684\u8026\u5408\u3002\u8fd9\u662f\u7531\u6240\u8c13\u7684\u754c\u9762\uff08\u6216\u8fb9\u7f18\uff09\u77e9\u9635\u6765\u5b8c\u6210\u7684\uff0c\u5b83\u8ba1\u7b97\u4e86\u88ab\u5177\u6709\u540c\u8d28Dirichlet\u6761\u4ef6\u7684\u5c42\u6b21\u77e9\u9635\u6240\u9057\u6f0f\u7684\u6b8b\u5dee\u90e8\u5206\u3002\u6211\u4eec\u53c2\u8003 @ref mg_paper \"Janssen\u548cKanschat\u7684\u591a\u7f51\u683c\u8bba\u6587 \"\u4ee5\u4e86\u89e3\u66f4\u591a\u7ec6\u8282\u3002\n\n// \u5bf9\u4e8e\u8fd9\u4e9b\u63a5\u53e3\u77e9\u9635\u7684\u5b9e\u73b0\uff0c\u5df2\u7ecf\u6709\u4e00\u4e2a\u9884\u5b9a\u4e49\u7684\u7c7b MatrixFreeOperators::MGInterfaceOperator \uff0c\u5b83\u5c06\u4f8b\u7a0b MatrixFreeOperators::Base::vmult_interface_down() \u548c MatrixFreeOperators::Base::vmult_interface_up() \u5305\u88c5\u5728\u4e00\u4e2a\u5e26\u6709 @p vmult()\u548c @p Tvmult() \u64cd\u4f5c\uff08\u6700\u521d\u662f\u4e3a\u77e9\u9635\u7f16\u5199\u7684\uff0c\u56e0\u6b64\u671f\u5f85\u8fd9\u4e9b\u540d\u5b57\uff09\u7684\u65b0\u7c7b\u4e2d\u3002\u8bf7\u6ce8\u610f\uff0cvmult_interface_down\u662f\u5728\u591a\u7f51\u683cV\u5468\u671f\u7684\u9650\u5236\u9636\u6bb5\u4f7f\u7528\u7684\uff0c\u800cvmult_interface_up\u662f\u5728\u5ef6\u957f\u9636\u6bb5\u4f7f\u7528\u7684\u3002\n\n// \u4e00\u65e6\u63a5\u53e3\u77e9\u9635\u88ab\u521b\u5efa\uff0c\u6211\u4eec\u5b8c\u5168\u6309\u7167 step-16 \u7684\u65b9\u6cd5\u8bbe\u7f6e\u5269\u4f59\u7684\u591a\u7f51\u683c\u9884\u5904\u7406\u57fa\u7840\u8bbe\u65bd\uff0c\u4ee5\u83b7\u5f97\u4e00\u4e2a\u53ef\u4ee5\u5e94\u7528\u4e8e\u77e9\u9635\u7684 @p preconditioner \u5bf9\u8c61\u3002\n\n    mg::Matrix<LinearAlgebra::distributed::Vector<float>> mg_matrix( \n      mg_matrices); \n\n    MGLevelObject<MatrixFreeOperators::MGInterfaceOperator<LevelMatrixType>> \n      mg_interface_matrices; \n    mg_interface_matrices.resize(0, triangulation.n_global_levels() - 1); \n    for (unsigned int level = 0; level < triangulation.n_global_levels(); \n         ++level) \n      mg_interface_matrices[level].initialize(mg_matrices[level]); \n    mg::Matrix<LinearAlgebra::distributed::Vector<float>> mg_interface( \n      mg_interface_matrices); \n\n    Multigrid<LinearAlgebra::distributed::Vector<float>> mg( \n      mg_matrix, mg_coarse, mg_transfer, mg_smoother, mg_smoother); \n    mg.set_edge_matrices(mg_interface, mg_interface); \n\n    PreconditionMG<dim, \n                   LinearAlgebra::distributed::Vector<float>, \n                   MGTransferMatrixFree<dim, float>> \n      preconditioner(dof_handler, mg, mg_transfer); \n\n// \u591a\u7f51\u683c\u7a0b\u5e8f\u7684\u8bbe\u7f6e\u975e\u5e38\u7b80\u5355\uff0c\u4e0e  step-16  \u76f8\u6bd4\uff0c\u5728\u6c42\u89e3\u8fc7\u7a0b\u4e2d\u770b\u4e0d\u51fa\u6709\u4ec0\u4e48\u4e0d\u540c\u3002\u6240\u6709\u7684\u9b54\u6cd5\u90fd\u9690\u85cf\u5728  LaplaceOperator::vmult  \u64cd\u4f5c\u7684\u5b9e\u73b0\u80cc\u540e\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u901a\u8fc7\u6807\u51c6\u8f93\u51fa\u6253\u5370\u51fa\u6c42\u89e3\u65f6\u95f4\u548c\u7d2f\u79ef\u7684\u8bbe\u7f6e\u65f6\u95f4\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5728\u4efb\u4f55\u60c5\u51b5\u4e0b\uff0c\u800c\u8bbe\u7f6e\u64cd\u4f5c\u7684\u8be6\u7ec6\u65f6\u95f4\u53ea\u5728\u6784\u9020\u51fd\u6570\u4e2d\u7684detail_times\u6807\u5fd7\u88ab\u6539\u53d8\u7684\u60c5\u51b5\u4e0b\u6253\u5370\u3002\n\n    SolverControl solver_control(100, 1e-12 * system_rhs.l2_norm()); \n    SolverCG<LinearAlgebra::distributed::Vector<double>> cg(solver_control); \n    setup_time += time.wall_time(); \n    time_details << \"MG build smoother time     (CPU/wall) \" << time.cpu_time() \n                 << \"s/\" << time.wall_time() << \"s\\n\"; \n    pcout << \"Total setup time               (wall) \" << setup_time << \"s\\n\"; \n\n    time.reset(); \n    time.start(); \n    constraints.set_zero(solution); \n    cg.solve(system_matrix, solution, system_rhs, preconditioner); \n\n    constraints.distribute(solution); \n\n    pcout << \"Time solve (\" << solver_control.last_step() << \" iterations)\" \n          << (solver_control.last_step() < 10 ? \"  \" : \" \") << \"(CPU/wall) \" \n          << time.cpu_time() << \"s/\" << time.wall_time() << \"s\\n\"; \n  } \n\n//  @sect4{LaplaceProblem::output_results}  \n\n// \u8fd9\u91cc\u662f\u6570\u636e\u8f93\u51fa\uff0c\u662f  step-5  \u7684\u7b80\u5316\u7248\u672c\u3002\u6211\u4eec\u5bf9\u7ec6\u5316\u8fc7\u7a0b\u4e2d\u4ea7\u751f\u7684\u6bcf\u4e2a\u7f51\u683c\u4f7f\u7528\u6807\u51c6\u7684VTU\uff08=\u538b\u7f29\u7684VTK\uff09\u8f93\u51fa\u3002\u6b64\u5916\uff0c\u6211\u4eec\u8fd8\u4f7f\u7528\u4e86\u4e00\u79cd\u9488\u5bf9\u901f\u5ea6\u800c\u4e0d\u662f\u78c1\u76d8\u4f7f\u7528\u91cf\u8fdb\u884c\u4f18\u5316\u7684\u538b\u7f29\u7b97\u6cd5\u3002\u9ed8\u8ba4\u8bbe\u7f6e\uff08\u9488\u5bf9\u78c1\u76d8\u4f7f\u7528\u8fdb\u884c\u4f18\u5316\uff09\u4f7f\u5f97\u4fdd\u5b58\u8f93\u51fa\u7684\u65f6\u95f4\u662f\u8fd0\u884c\u7ebf\u6027\u6c42\u89e3\u5668\u76844\u500d\uff0c\u800c\u5c06 DataOutBase::VtkFlags::compression_level \u8bbe\u7f6e\u4e3a DataOutBase::VtkFlags::best_speed \u5219\u5c06\u5176\u964d\u4f4e\u5230\u53ea\u6709\u7ebf\u6027\u6c42\u89e3\u7684\u56db\u5206\u4e4b\u4e00\u7684\u65f6\u95f4\u3002\n\n// \u5f53\u7f51\u683c\u8fc7\u5927\u65f6\uff0c\u6211\u4eec\u7981\u7528\u8f93\u51fa\u3002\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e00\u4e2a\u53d8\u79cd\u5df2\u7ecf\u5728\u51e0\u5341\u4e07\u4e2aMPI\u884c\u5217\u4e0a\u8fd0\u884c\uff0c\u7f51\u683c\u5355\u5143\u591a\u8fbe1000\u4ebf\u4e2a\uff0c\u7ecf\u5178\u7684\u53ef\u89c6\u5316\u5de5\u5177\u65e0\u6cd5\u76f4\u63a5\u8bbf\u95ee\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::output_results(const unsigned int cycle) const \n  { \n    Timer time; \n    if (triangulation.n_global_active_cells() > 1000000) \n      return; \n\n    DataOut<dim> data_out; \n\n    solution.update_ghost_values(); \n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \"solution\"); \n    data_out.build_patches(mapping); \n\n    DataOutBase::VtkFlags flags; \n    flags.compression_level = DataOutBase::VtkFlags::best_speed; \n    data_out.set_flags(flags); \n    data_out.write_vtu_with_pvtu_record( \n      \"./\", \"solution\", cycle, MPI_COMM_WORLD, 3); \n\n    time_details << \"Time write output          (CPU/wall) \" << time.cpu_time() \n                 << \"s/\" << time.wall_time() << \"s\\n\"; \n  } \n\n//  @sect4{LaplaceProblem::run}  \n\n// \u8fd0\u884c\u8be5\u7a0b\u5e8f\u7684\u51fd\u6570\u4e0e  step-16  \u4e2d\u7684\u51fd\u6570\u975e\u5e38\u76f8\u4f3c\u3002\u4e0e2D\u76f8\u6bd4\uff0c\u6211\u4eec\u57283D\u4e2d\u505a\u4e86\u5f88\u5c11\u7684\u7ec6\u5316\u6b65\u9aa4\uff0c\u4f46\u4ec5\u6b64\u800c\u5df2\u3002\n\n// \u5728\u8fd0\u884c\u7a0b\u5e8f\u4e4b\u524d\uff0c\u6211\u4eec\u5148\u8f93\u51fa\u4e00\u4e9b\u5173\u4e8e\u68c0\u6d4b\u5230\u7684\u77e2\u91cf\u5316\u6c34\u5e73\u7684\u4fe1\u606f\uff0c\u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\u90a3\u6837\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::run() \n  { \n    { \n      const unsigned int n_vect_doubles = VectorizedArray<double>::size(); \n      const unsigned int n_vect_bits    = 8 * sizeof(double) * n_vect_doubles; \n\n      pcout << \"Vectorization over \" << n_vect_doubles \n            << \" doubles = \" << n_vect_bits << \" bits (\" \n            << Utilities::System::get_current_vectorization_level() << \")\" \n            << std::endl; \n    } \n\n    for (unsigned int cycle = 0; cycle < 9 - dim; ++cycle) \n      { \n        pcout << \"Cycle \" << cycle << std::endl; \n\n        if (cycle == 0) \n          { \n            GridGenerator::hyper_cube(triangulation, 0., 1.); \n            triangulation.refine_global(3 - dim); \n          } \n        triangulation.refine_global(1); \n        setup_system(); \n        assemble_rhs(); \n        solve(); \n        output_results(cycle); \n        pcout << std::endl; \n      }; \n  } \n} // namespace Step37 \n\n//  @sect3{The <code>main</code> function}  \n\n// \u9664\u4e86\u6211\u4eec\u6839\u636e step-40 \u8bbe\u7f6e\u4e86MPI\u6846\u67b6\u5916\uff0c\u4e3b\u51fd\u6570\u4e2d\u6ca1\u6709\u4efb\u4f55\u610f\u5916\u3002\n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      using namespace Step37; \n\n      Utilities::MPI::MPI_InitFinalize mpi_init(argc, argv, 1); \n\n      LaplaceProblem<dimension> laplace_problem; \n      laplace_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\n  return 0; \n} \n\n", "meta": {"hexsha": "eb2c9cc5a8d197d557f40699a8a19931f0667b73", "size": 36184, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-37/step-37.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-37/step-37.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-37/step-37.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.6344086022, "max_line_length": 1184, "alphanum_fraction": 0.6984855185, "num_tokens": 15964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.502744027525802}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n\n#include <array>\n#include <utility>\n\n#include \"hexad.hpp\"\n\nusing ternary::Hexad;\nnamespace bdata = boost::unit_test::data;\n\nstruct HexadFixture\n{\n    HexadFixture() = default;\n    ~HexadFixture() = default;\n\n    Hexad smallPositive { 10 };\n    Hexad smallNegative { -4 };\n\n    Hexad largePositive { 255 };\n    Hexad largeNegative { -321 };\n\n    // Identifiable pattern: +0-+0-\n    Hexad tritPattern { 224 };\n};\n\n// Note that these are low to high\nconstexpr std::array<int, 6> tritsInPattern { -1, 0, 1, -1, 0, 1 };\n\nBOOST_FIXTURE_TEST_SUITE(hexad, HexadFixture)\n\n    BOOST_AUTO_TEST_SUITE(hexad_basic_functions)\n\n    BOOST_AUTO_TEST_CASE(default_constructor)\n    {\n        Hexad h;\n        BOOST_TEST(h.get() == 0);\n        BOOST_TEST(h.value_string() == \"00\");\n    }\n\n    BOOST_AUTO_TEST_CASE(constructor_with_value)\n    {\n        Hexad h { 123 };\n        BOOST_TEST(h.get() == 123);\n    }\n\n    BOOST_AUTO_TEST_CASE(trit_string)\n    {\n        auto a { smallPositive.trit_string() };\n        BOOST_TEST(a.length() == 6);\n        BOOST_TEST(a == \"000+0+\");\n    }\n\n    BOOST_AUTO_TEST_CASE(trit_array)\n    {\n        auto a { smallNegative.trits() };\n        BOOST_TEST(a.size() == 6);\n        BOOST_TEST(a[0] == -1);\n        BOOST_TEST(a[1] == -1);\n        BOOST_TEST(a[2] == 0);\n    }\n    \n    BOOST_AUTO_TEST_CASE(value_string)\n    {\n        BOOST_TEST(smallPositive.value_string() == \"0J\");\n        BOOST_TEST(smallNegative.value_string() == \"0q\");\n        BOOST_TEST(largePositive.value_string() == \"IL\");\n        BOOST_TEST(largeNegative.value_string() == \"yC\");\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n\n    BOOST_AUTO_TEST_SUITE(hexad_operations_arithmetic)\n\n    BOOST_AUTO_TEST_CASE(operation_add)\n    {\n        BOOST_TEST(add(smallPositive, largePositive).get() == smallPositive.get() + largePositive.get());\n        BOOST_TEST(add(smallNegative, largeNegative).get() == smallNegative.get() + largeNegative.get());\n        BOOST_TEST(add(smallPositive, smallNegative).get() == smallPositive.get() + smallNegative.get());\n        BOOST_TEST(add(smallNegative, largePositive).get() == smallNegative.get() + largePositive.get());\n    }\n    \n    BOOST_AUTO_TEST_CASE(operation_subtract)\n    {\n        BOOST_TEST(subtract(smallPositive, largePositive).get() == smallPositive.get() - largePositive.get());\n        BOOST_TEST(subtract(smallNegative, largeNegative).get() == smallNegative.get() - largeNegative.get());\n        BOOST_TEST(subtract(smallPositive, smallNegative).get() == smallPositive.get() - smallNegative.get());\n        BOOST_TEST(subtract(smallNegative, largePositive).get() == smallNegative.get() - largePositive.get());\n    }\n    \n    BOOST_AUTO_TEST_CASE(operation_add_with_carry)\n    {\n        auto r { Hexad::range };\n        BOOST_TEST(add_with_carry(smallPositive, smallNegative).first.get() == smallPositive.get() + smallNegative.get());\n        BOOST_TEST(add_with_carry(largePositive, largePositive).second == 1);\n        BOOST_TEST(add_with_carry(largeNegative, largeNegative).first.get() - r == largeNegative.get() + largeNegative.get());\n    }\n    \n    BOOST_AUTO_TEST_CASE(operation_subtract_with_carry)\n    {\n        BOOST_TEST(subtract_with_carry(smallPositive, smallNegative).first.get() == smallPositive.get() - smallNegative.get());\n        BOOST_TEST(subtract_with_carry(largePositive, largeNegative).second == 1);\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_multiply)\n    {\n        BOOST_TEST(multiply(smallPositive, smallNegative).first.get() == smallPositive.get() * smallNegative.get());\n\n        auto mp { multiply(largePositive, smallPositive) };\n        auto r { Hexad::range };\n        BOOST_TEST(mp.second.get() * r + mp.first.get() == largePositive.get() * smallPositive.get());\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_divide_single_precision)\n    {\n        auto d1 { divide(largePositive, smallPositive) };\n        BOOST_TEST(d1.first.get() == largePositive.get() / smallPositive.get());\n        BOOST_TEST(d1.second.get() == largePositive.get() % smallPositive.get());\n        \n        auto d2 { divide(largePositive, smallNegative) };\n        BOOST_TEST(d2.first.get() == largePositive.get() / smallNegative.get());\n        BOOST_TEST(d2.second.get() == largePositive.get() % smallNegative.get());\n        \n        auto d3 { divide(largeNegative, smallPositive) };\n        BOOST_TEST(d3.first.get() == largeNegative.get() / smallPositive.get());\n        BOOST_TEST(d3.second.get() == largeNegative.get() % smallPositive.get());\n        \n        auto d4 { divide(largeNegative, smallNegative) };\n        BOOST_TEST(d4.first.get() == largeNegative.get() / smallNegative.get());\n        BOOST_TEST(d4.second.get() == largeNegative.get() % smallNegative.get());\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_divide_double_precision)\n    {\n        std::pair<Hexad, Hexad> hh { {0}, {1} };\n        auto hhvalue { hh.second.get() * Hexad::range + hh.first.get() };\n\n        BOOST_TEST(divide(hh, smallPositive).first.get() == hhvalue / smallPositive.get());\n        BOOST_TEST(divide(hh, smallNegative).first.get() == hhvalue / smallNegative.get());\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n\n    BOOST_AUTO_TEST_SUITE(hexad_operations_logical)\n\n    BOOST_AUTO_TEST_CASE(operation_left_shift_single)\n    {\n        auto r { Hexad::range };\n        BOOST_TEST(left_shift(smallPositive).get() == smallPositive.get() * 3);\n        BOOST_TEST(left_shift(largePositive).get() == largePositive.get() * 3 - r);\n        BOOST_TEST(left_shift(largeNegative).get() == largeNegative.get() * 3 + r);\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_right_shift_single)\n    {\n        BOOST_TEST(right_shift(smallPositive).get() == smallPositive.get() / 3);\n        BOOST_TEST(right_shift(largePositive).get() == largePositive.get() / 3);\n        BOOST_TEST(right_shift(largeNegative).get() == largeNegative.get() / 3);\n    }\n    \n\n    BOOST_AUTO_TEST_CASE(operation_left_shift_multiple)\n    {\n        for (auto i = 1u; i <= Hexad::width; ++i)\n        {\n            BOOST_TEST(left_shift(tritPattern, i).second == tritsInPattern[Hexad::width - i]);\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_right_shift_multiple)\n    {\n        for (auto i = 1u; i <= Hexad::width; ++i)\n        {\n            BOOST_TEST(right_shift(tritPattern, i).second == tritsInPattern[i - 1]);\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_left_rotate)\n    {\n        for (auto i = 1u; i <= Hexad::width; ++i)\n        {\n            BOOST_TEST(rotate_left(tritPattern, i).trits()[0] == tritsInPattern[Hexad::width - i]);\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_right_rotate)\n    {\n        for (auto i = 1u; i <= Hexad::width; ++i)\n        {\n            BOOST_TEST(rotate_right(tritPattern, i).trits()[0] == tritsInPattern[i % Hexad::width]);\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_left_rotate_carry)\n    {\n        for (auto i = 1u; i <= Hexad::width; ++i)\n        {\n            BOOST_TEST(rotate_left_carry(tritPattern, 0, i).second == tritsInPattern[Hexad::width - i]);\n            \n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_right_rotate_carry)\n    {\n        for (auto i = 1u; i <= Hexad::width; ++i)\n        {\n            BOOST_TEST(rotate_right_carry(tritPattern, 0, i).second == tritsInPattern[i - 1]);\n            \n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_simple_invert)\n    {\n        BOOST_TEST(invert(smallPositive).get() == -smallPositive.get());\n        BOOST_TEST(invert(largeNegative).get() == -largeNegative.get());\n    }\n    \n    BOOST_AUTO_TEST_CASE(operation_positive_invert)\n    {\n        auto inv1 { positive_invert(smallPositive) };\n        auto inv2 { positive_invert(largeNegative) };\n\n        for (auto i = 0u; i < Hexad::width; ++i)\n        {\n            if (smallPositive.trits()[i] == 1)\n            {\n                BOOST_TEST(inv1.trits()[i] == -1);\n            }\n            else\n            {\n                BOOST_TEST(inv1.trits()[i] == 1);\n            }\n\n            if (largeNegative.trits()[i] == 1)\n            {\n                BOOST_TEST(inv2.trits()[i] == -1);\n            }\n            else\n            {\n                BOOST_TEST(inv2.trits()[i] == 1);\n            }\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_negative_invert)\n    {\n        auto inv1 { negative_invert(smallPositive) };\n        auto inv2 { negative_invert(largeNegative) };\n\n        for (auto i = 0u; i < Hexad::width; ++i)\n        {\n            if (smallPositive.trits()[i] == -1)\n            {\n                BOOST_TEST(inv1.trits()[i] == -1);\n            }\n            else\n            {\n                BOOST_TEST(inv1.trits()[i] == -1);\n            }\n\n            if (largeNegative.trits()[i] == -1)\n            {\n                BOOST_TEST(inv2.trits()[i] == 1);\n            }\n            else\n            {\n                BOOST_TEST(inv2.trits()[i] == -1);\n            }\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_forward_diode)\n    {\n        auto d1 { forward_diode(smallPositive) };\n        auto d2 { forward_diode(largeNegative) };\n\n        for (auto i = 0u; i < Hexad::width; ++i)\n        {\n            if (smallPositive.trits()[i] == 1)\n            {\n                BOOST_TEST(d1.trits()[i] == 1);\n            }\n            else\n            {\n                BOOST_TEST(d1.trits()[i] == 0);\n            }\n\n            if (largeNegative.trits()[i] == 1)\n            {\n                BOOST_TEST(d2.trits()[i] == 1);\n            }\n            else\n            {\n                BOOST_TEST(d2.trits()[i] == 0);\n            }\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_reverse_diode)\n    {\n        auto d1 { reverse_diode(smallPositive) };\n        auto d2 { reverse_diode(largeNegative) };\n\n        for (auto i = 0u; i < Hexad::width; ++i)\n        {\n            if (smallPositive.trits()[i] == -1)\n            {\n                BOOST_TEST(d1.trits()[i] == -1);\n            }\n            else\n            {\n                BOOST_TEST(d1.trits()[i] == 0);\n            }\n\n            if (largeNegative.trits()[i] == -1)\n            {\n                BOOST_TEST(d2.trits()[i] == -1);\n            }\n            else\n            {\n                BOOST_TEST(d2.trits()[i] == 0);\n            }\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_trit_maximum)\n    {\n        auto result1 { trit_maximum(smallPositive, smallNegative) };\n        auto result2 { trit_maximum(largePositive, largeNegative) };\n\n        for (auto i = 0u; i < Hexad::width; ++i)\n        {\n            BOOST_TEST(result1.trits()[i] ==\n                std::max(smallPositive.trits()[i], smallNegative.trits()[i])\n            );\n\n            BOOST_TEST(result2.trits()[i] ==\n                std::max(largePositive.trits()[i], largeNegative.trits()[i])\n            );\n        }\n    }\n    \n    BOOST_AUTO_TEST_CASE(operation_trit_minimum)\n    {\n        auto result1 { trit_minimum(smallPositive, smallNegative) };\n        auto result2 { trit_minimum(largePositive, largeNegative) };\n\n        for (auto i = 0u; i < Hexad::width; ++i)\n        {\n            BOOST_TEST(result1.trits()[i] ==\n                std::min(smallPositive.trits()[i], smallNegative.trits()[i])\n            );\n\n            BOOST_TEST(result2.trits()[i] ==\n                std::min(largePositive.trits()[i], largeNegative.trits()[i])\n            );\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_logical_equality)\n    {\n        auto result1 { logical_equality(smallPositive, smallNegative) };\n        auto result2 { logical_equality(largePositive, largeNegative) };\n\n        for (auto i = 0u; i < Hexad::width; ++i)\n        {\n            BOOST_TEST(result1.trits()[i] ==\n                (smallPositive.trits()[i] == smallNegative.trits()[i] ? 1 : -1)\n            );\n\n            BOOST_TEST(result2.trits()[i] ==\n                (largePositive.trits()[i] == largeNegative.trits()[i] ? 1 : -1)\n            );\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(operation_logical_multiply)\n    {\n        auto result1 { logical_multiply(smallPositive, smallNegative) };\n        auto result2 { logical_multiply(largePositive, largeNegative) };\n\n        for (auto i = 0u; i < Hexad::width; ++i)\n        {\n            BOOST_TEST(result1.trits()[i] ==\n                (smallPositive.trits()[i] * smallNegative.trits()[i])\n            );\n\n            BOOST_TEST(result2.trits()[i] ==\n                (largePositive.trits()[i] * largeNegative.trits()[i])\n            );\n        }\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "dd98e166eb64976d416f43b9c918becd70c6473f", "size": 12574, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/hexad_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/hexad_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/hexad_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": 31.6725440806, "max_line_length": 127, "alphanum_fraction": 0.5680769843, "num_tokens": 3105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5027440170783443}}
{"text": "#define BOOST_TEST_MODULE test_onecellcad\n\n#include <optional>\n\n#include <boost/test/unit_test.hpp>\n\n#include <carl/core/MultivariatePolynomial.h>\n#include <carl/core/Variable.h>\n#include <carl/ran/RealAlgebraicPoint.h>\n\n#include <smtrat-mcsat/explanations/onecellcad/OneCellCAD.h>\n\n/**\n  * References:\n  * [1] Christopher W. Brown and Marek Ko\u0161ta. 2015. Constructing a single cell\n  * in cylindrical algebraic decomposition. J. Symb. Comput. 70, C (September\n  * 2015), 14-48. DOI=http://dx.doi.org/10.1016/j.jsc.2014.09.024\n  */\n\nnamespace {\n  using std::cout;\n  using std::endl;\n  using std::optional;\n  using std::nullopt;\n\n  using smtrat::Rational;\n  using namespace smtrat::mcsat::onecellcad;\n  using carl::Variable;\n  using Poly = carl::MultivariatePolynomial<Rational>;\n\tusing RAN = carl::RealAlgebraicNumber<Rational>;\n\tusing RANPoint = carl::RealAlgebraicPoint<Rational>;\n\nstruct VariableFixture {\n  Variable x = carl::freshRealVariable(\"x\");\n  Variable y = carl::freshRealVariable(\"y\");\n  Variable z = carl::freshRealVariable(\"z\");\n  std::vector<Variable> varOrder {x};\n  std::vector<Variable> varOrder2 {x,y};\n  std::vector<Variable> varOrder3 {x,y,z};\n};\n\nBOOST_FIXTURE_TEST_CASE(polylevel, VariableFixture) {\n  BOOST_TEST_MESSAGE(\"Test polyLevel\");\n\n  BOOST_CHECK(levelOf(varOrder3, Poly(1)) == nullopt);\n  BOOST_CHECK(levelOf(varOrder3, Poly(x) * Rational(0)) == nullopt);\n  BOOST_CHECK(levelOf(varOrder3, Poly(x * y) * Rational(0)) == nullopt);\n  BOOST_CHECK(*levelOf(varOrder3, Poly(x)) == 0);\n  BOOST_CHECK(*levelOf(varOrder3, Poly(y)) == 1);\n  BOOST_CHECK(*levelOf(varOrder3, Poly(x * y)) == 1);\n  BOOST_CHECK(*levelOf(varOrder3, Poly(z)) == 2);\n  BOOST_CHECK(*levelOf(varOrder3, Poly(x * z)) == 2);\n  BOOST_CHECK(*levelOf(varOrder3, Poly(x * y * z)) == 2);\n}\n\nBOOST_FIXTURE_TEST_CASE(cell2d, VariableFixture) {\n  BOOST_TEST_MESSAGE(\"Test 2D example from [1]\");\n  Poly p = Poly(x*x) + Poly(y*y) - Rational(1) ;\n  Poly q = Poly(y*y)*Rational(2) - Poly(x*x) * (Poly(x)*Rational(2) + Rational(3)) ;\n  Poly r = Poly(y) + Poly(x)*Rational(0.5) - Rational(0.5) ;\n  std::vector<Poly> polys {p,q,r};\n\n  RANPoint point { RAN(Rational(-1)/3), RAN(Rational(1)/3) };\n\n  optional<CADCell> c = OneCellCAD(varOrder3,point).createCADCellAroundPoint(polys);\n\n  BOOST_CHECK(c);\n}\n\n} // namespace\n", "meta": {"hexsha": "3b615ca928a3bf454a418157c394c897607c2ac4", "size": 2297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/onecellcad/Test_OneCellCAD.cpp", "max_stars_repo_name": "ths-rwth/smtrat", "max_stars_repo_head_hexsha": "efd83021d5b5fb0e2903b38cd3148a953a1972c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-21T23:02:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T15:15:13.000Z", "max_issues_repo_path": "src/tests/onecellcad/Test_OneCellCAD.cpp", "max_issues_repo_name": "ths-rwth/smtrat", "max_issues_repo_head_hexsha": "efd83021d5b5fb0e2903b38cd3148a953a1972c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-03-16T11:00:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T14:51:57.000Z", "max_forks_repo_path": "src/tests/onecellcad/Test_OneCellCAD.cpp", "max_forks_repo_name": "ths-rwth/smtrat", "max_forks_repo_head_hexsha": "efd83021d5b5fb0e2903b38cd3148a953a1972c0", "max_forks_repo_licenses": ["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.3521126761, "max_line_length": 84, "alphanum_fraction": 0.700043535, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5027440066308865}}
{"text": "#include \"aikido/distance/SE2.hpp\"\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace aikido {\nnamespace distance {\n\n//=============================================================================\nSE2::SE2(std::shared_ptr<statespace::SE2> _space)\n  : mStateSpace(std::move(_space))\n{\n  if (mStateSpace == nullptr)\n    throw std::invalid_argument(\"_space is nullptr.\");\n}\n\n//=============================================================================\nstatespace::ConstStateSpacePtr SE2::getStateSpace() const\n{\n  return mStateSpace;\n}\n\n//=============================================================================\ndouble SE2::distance(\n    const aikido::statespace::StateSpace::State* _state1,\n    const aikido::statespace::StateSpace::State* _state2) const\n{\n  Eigen::VectorXd tangent1;\n  mStateSpace->logMap(\n      static_cast<const statespace::SE2::State*>(_state1), tangent1);\n\n  Eigen::VectorXd tangent2;\n  mStateSpace->logMap(\n      static_cast<const statespace::SE2::State*>(_state2), tangent2);\n\n  Eigen::Vector3d diff;\n\n  // Difference between R^2 positions\n  diff.head<2>() = tangent1.head<2>() - tangent2.head<2>();\n\n  // Difference between angles\n  double angleDiff = tangent1(2) - tangent2(2);\n  angleDiff = std::fmod(std::abs(angleDiff), 2.0 * M_PI);\n  if (angleDiff > M_PI)\n    angleDiff -= 2.0 * M_PI;\n  diff[2] = angleDiff;\n\n  return diff.norm();\n}\n\n} // namespace distance\n} // namespace aikido\n", "meta": {"hexsha": "b7b67ac87c10bc9992897af5526d595d9b3f9c12", "size": 1423, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/distance/SE2.cpp", "max_stars_repo_name": "personalrobotics/r3", "max_stars_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 181.0, "max_stars_repo_stars_event_min_datetime": "2016-04-22T15:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T12:51:08.000Z", "max_issues_repo_path": "src/distance/SE2.cpp", "max_issues_repo_name": "personalrobotics/r3", "max_issues_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 514.0, "max_issues_repo_issues_event_min_datetime": "2016-04-20T04:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T19:46:21.000Z", "max_forks_repo_path": "src/distance/SE2.cpp", "max_forks_repo_name": "personalrobotics/r3", "max_forks_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-03-17T09:53:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:35:05.000Z", "avg_line_length": 27.3653846154, "max_line_length": 79, "alphanum_fraction": 0.5818692902, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5027439997939767}}
{"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/WhiteNoiseAcceleration.h>\n#include <BayesFilters/utils.h>\n\n#include <cmath>\n#include <utility>\n\n#include <Eigen/Cholesky>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nstruct WhiteNoiseAcceleration::ImplData\n{\n    ImplData\n    (\n        const Dim dim,\n        const double sampling_interval,\n        const double tilde_q,\n        const unsigned int seed\n    ) :\n        T_(sampling_interval),\n        tilde_q_(tilde_q),\n        seed_(seed),\n        generator_(std::mt19937_64(seed_)),\n        distribution_(std::normal_distribution<double>(0.0, 1.0)),\n        gauss_rnd_sample_([&] { return (distribution_) (generator_); })\n    {\n        double q11 = 1.0 / 3.0 * std::pow(T_, 3.0);\n        double q2 = 1.0 / 2.0 * std::pow(T_, 2.0);\n\n        Matrix2d F;\n        F << 1.0, T_,\n             0.0, 1.0;\n\n        Matrix2d Q;\n        Q << q11, q2,\n              q2, T_;\n\n        switch (dim)\n        {\n            case Dim::OneD:\n            {\n                F_ = F;\n\n                Q_ = Q;\n\n                break;\n            }\n\n            case Dim::TwoD:\n            {\n                F_ = MatrixXd(4, 4);\n                F_ << F, Matrix2d::Zero(),\n                      Matrix2d::Zero(), F;\n\n                Q_ = MatrixXd(4, 4);\n                Q_ << Q, Matrix2d::Zero(),\n                      Matrix2d::Zero(), Q;\n\n                break;\n            }\n\n            case Dim::ThreeD:\n            {\n                F_ = MatrixXd(6, 6);\n                F_ << F, Matrix2d::Zero(), Matrix2d::Zero(),\n                      Matrix2d::Zero(), F, Matrix2d::Zero(),\n                      Matrix2d::Zero(), Matrix2d::Zero(), F;\n\n                Q_ = MatrixXd(6, 6);\n                Q_ << Q, Matrix2d::Zero(), Matrix2d::Zero(),\n                      Matrix2d::Zero(), Q, Matrix2d::Zero(),\n                      Matrix2d::Zero(), Matrix2d::Zero(), Q;\n\n                break;\n            }\n        }\n\n        Q_ *= tilde_q_;\n\n        LDLT<MatrixXd> chol_ldlt(Q_);\n        sqrt_Q_ = (chol_ldlt.transpositionsP() * MatrixXd::Identity(Q_.rows(), Q_.cols())).transpose() * chol_ldlt.matrixL() * chol_ldlt.vectorD().real().cwiseSqrt().asDiagonal();\n    }\n\n    /**\n     * Sampling interval in [time].\n     */\n    double T_;\n\n    /**\n     * Power spectral density [length]^2/[time]^3.\n     */\n    double tilde_q_;\n\n    /**\n     * State transition matrix.\n     */\n    Eigen::MatrixXd F_;\n\n    /**\n     * Convariance matrix of the additive white noise of the state model.\n     */\n    Eigen::MatrixXd Q_;\n\n    /**\n     * Square root matrix of R_.\n     */\n    Eigen::MatrixXd sqrt_Q_;\n\n    /**\n     * Seed of the random number generator.\n     */\n    unsigned int seed_;\n\n    /**\n     * Random number generator.\n     */\n    std::mt19937_64 generator_;\n\n    /**\n     * Normal distribution for random number generation functions.\n     */\n    std::normal_distribution<double> distribution_;\n\n    /**\n     * Random number generator function from a Normal distribution.\n     * A call to `gauss_rnd_sample_()` returns a double-precision floating point random number.\n     */\n    std::function<double()> gauss_rnd_sample_;\n};\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration\n(\n    const Dim dim,\n    const double sampling_interval,\n    const double tilde_q\n) noexcept :\n    WhiteNoiseAcceleration(dim, sampling_interval, tilde_q, 1)\n{ }\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration\n(\n    const Dim dim,\n    const double sampling_interval,\n    const double tilde_q,\n    const unsigned int seed\n) noexcept :\n    pimpl_(utils::make_unique<ImplData>(dim, sampling_interval, tilde_q, seed))\n{ }\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration(WhiteNoiseAcceleration&& state_model) noexcept = default;\n\n\nWhiteNoiseAcceleration& WhiteNoiseAcceleration::operator=(WhiteNoiseAcceleration&& state_model) noexcept = default;\n\n\nWhiteNoiseAcceleration::~WhiteNoiseAcceleration() noexcept = default;\n\n\nbool WhiteNoiseAcceleration::setProperty(const std::string& property)\n{\n    return false;\n}\n\n\nstd::pair<std::size_t, std::size_t> WhiteNoiseAcceleration::getOutputSize() const\n{\n    return std::make_pair(4, 0);\n}\n\n\nMatrixXd WhiteNoiseAcceleration::getNoiseSample(const std::size_t num)\n{\n    MatrixXd rand_vectors(4, num);\n    for (int i = 0; i < rand_vectors.size(); i++)\n        *(rand_vectors.data() + i) = pimpl_->gauss_rnd_sample_();\n\n    return pimpl_->sqrt_Q_ * rand_vectors;\n}\n\n\nMatrixXd WhiteNoiseAcceleration::getNoiseCovarianceMatrix()\n{\n    return pimpl_->Q_;\n}\n\n\nMatrixXd WhiteNoiseAcceleration::getStateTransitionMatrix()\n{\n    return pimpl_->F_;\n}\n\n\nVectorXd WhiteNoiseAcceleration::getTransitionProbability(const Ref<const MatrixXd>& prev_states, const Ref<const MatrixXd>& cur_states)\n{\n    return utils::multivariate_gaussian_density(prev_states, prev_states.col(0), pimpl_->Q_);\n}\n", "meta": {"hexsha": "3c612b93eadd9536166320b8f5cbe2abda07e158", "size": 5005, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesFilters/src/WhiteNoiseAcceleration.cpp", "max_stars_repo_name": "mfkiwl/bayes-filters-lib", "max_stars_repo_head_hexsha": "8baabba1897bcc5634619fbc048bb5ab17a742da", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T09:02:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T20:01:35.000Z", "max_issues_repo_path": "src/BayesFilters/src/WhiteNoiseAcceleration.cpp", "max_issues_repo_name": "xEnVrE/bayes-filters-lib", "max_issues_repo_head_hexsha": "8baabba1897bcc5634619fbc048bb5ab17a742da", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T07:32:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-20T17:12:08.000Z", "max_forks_repo_path": "src/BayesFilters/src/WhiteNoiseAcceleration.cpp", "max_forks_repo_name": "xEnVrE/bayes-filters-lib", "max_forks_repo_head_hexsha": "8baabba1897bcc5634619fbc048bb5ab17a742da", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2017-05-07T01:47:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T10:15:59.000Z", "avg_line_length": 23.9473684211, "max_line_length": 179, "alphanum_fraction": 0.5958041958, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5027297466108774}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Surface_mesh.h>\n\n#include <CGAL/AABB_tree.h>\n#include <CGAL/AABB_traits.h>\n#include <CGAL/AABB_face_graph_triangle_primitive.h>\n#include <CGAL/optimal_bounding_box.h>\n#include <CGAL/Polygon_mesh_processing/IO/polygon_mesh_io.h>\n\n#include <boost/property_map/function_property_map.hpp>\n\n#include <fstream>\n#include <iostream>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel    K;\ntypedef K::Point_3                                             Point;\ntypedef K::Aff_transformation_3                                Aff_transformation;\n\ntypedef CGAL::Surface_mesh<Point>                              Surface_mesh;\ntypedef boost::graph_traits<Surface_mesh>::vertex_descriptor   vertex_descriptor;\n\nstruct Aff_tr_fct\n{\n  Aff_tr_fct() : m_at(nullptr), m_sm(nullptr) { }\n  Aff_tr_fct(const Aff_transformation& at, const Surface_mesh& sm) : m_at(&at), m_sm(&sm) { }\n\n  Point operator()(const vertex_descriptor v) const { return m_at->transform(m_sm->point(v)); }\n\nprivate:\n  const Aff_transformation* m_at;\n  const Surface_mesh* m_sm;\n};\n\nint main(int argc, char** argv)\n{\n  const char* filename = (argc > 1) ? argv[1] : \"data/pig.off\";\n\n  Surface_mesh sm;\n  if(!CGAL::Polygon_mesh_processing::read_polygon_mesh(filename, sm) || sm.is_empty())\n  {\n    std::cerr << \"Invalid input file.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  // get the transformation that yields the optimal bounding box\n  Aff_transformation at;\n  CGAL::oriented_bounding_box(sm, at);\n\n  // functor to apply the affine transformation to a vertex of the mesh\n  Aff_tr_fct aff_tr_fct(at, sm);\n  auto aff_tr_vpm = boost::make_function_property_map<vertex_descriptor>(aff_tr_fct);\n\n  // rotated AABB tree\n  typedef CGAL::AABB_face_graph_triangle_primitive<Surface_mesh, decltype(aff_tr_vpm)> AABB_face_graph_primitive;\n  typedef CGAL::AABB_traits<K, AABB_face_graph_primitive>                              AABB_face_graph_traits;\n\n  CGAL::AABB_tree<AABB_face_graph_traits> tree(faces(sm).begin(), faces(sm).end(), sm, aff_tr_vpm);\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "176ca6ff53b9dbf5613ebb739da0a8ba34626450", "size": 2111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Optimal_bounding_box/examples/Optimal_bounding_box/rotated_aabb_tree_example.cpp", "max_stars_repo_name": "yemaedahrav/cgal", "max_stars_repo_head_hexsha": "ef771049b173007f2c566375bbd85a691adcee17", "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": "Optimal_bounding_box/examples/Optimal_bounding_box/rotated_aabb_tree_example.cpp", "max_issues_repo_name": "yemaedahrav/cgal", "max_issues_repo_head_hexsha": "ef771049b173007f2c566375bbd85a691adcee17", "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": "Optimal_bounding_box/examples/Optimal_bounding_box/rotated_aabb_tree_example.cpp", "max_forks_repo_name": "szobov/cgal", "max_forks_repo_head_hexsha": "e7b91b92b8c6949e3b62023bdd1e9f3ad8472626", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-05T04:18:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:18:59.000Z", "avg_line_length": 34.606557377, "max_line_length": 113, "alphanum_fraction": 0.7190904784, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262966, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5027297466108773}}
{"text": "#include <igl/per_vertex_normals.h>\n#include <igl/principal_curvature.h>\n#include <igl/avg_edge_length.h>\n#include <igl/massmatrix.h>\n#include <igl/adjacency_list.h>\n#include <igl/per_face_normals.h>\n#include <igl/barycenter.h>\n#include <igl/pinv.h>\n#include <igl/edges.h>\n#include <Eigen/SparseCore>\n#include <igl/adjacency_list.h>\n#include <igl/adjacency_matrix.h>\n#include <igl/per_face_normals.h>\n#include <igl/per_vertex_normals.h>\n#include <igl/avg_edge_length.h>\n#include <igl/edge_flaps.h>\n#include <igl/unique_edge_map.h>\n#include <igl/vertex_triangle_adjacency.h>\n#include <igl/principal_curvature.h>\n#include <igl/collapse_edge.h>\n#include <igl/point_mesh_squared_distance.h>\n#include <igl/C_STR.h>\n#include <igl/flip_edge.h>\n#include <igl/remove_duplicate_vertices.h>\nusing namespace std;\n\nvoid tangential_relaxation(Eigen::MatrixXd & V,Eigen::MatrixXi & F, Eigen::VectorXi & feature,\n        Eigen::MatrixXd & V0 ,Eigen::MatrixXi & F0, Eigen::VectorXd & lambda){\n    using namespace Eigen;\n        MatrixXd Q,P,N,V_projected,V_fixed;\n        VectorXd dblA,sqrD;\n        VectorXi sqrI;\n        std::vector<std::vector<int>> A;\n        Matrix3d I, NN;\n        I.setIdentity();\n        Eigen::MatrixXd SV;\n        Eigen::MatrixXi SVI,SVJ;\n        \n        \n        \n        \n\n        \n        V_fixed = V;\n        \n        int n = V.rows();\n        int m = F.rows();\n\n        //igl::doublearea(V,F,dblA);\n        \n        //std::vector<double> vertex_areas;\n        //vertex_areas.setZero(m);\n        \n        \n        //for (int j = 0; j < m; j++) {\n        //    vertex_areas[F(j,0)] = vertex_areas[F(j,0)] + (abs(dblA(j))/6);\n        //    vertex_areas[F(j,1)] = vertex_areas[F(j,1)] + (abs(dblA(j))/6);\n        //    vertex_areas[F(j,2)] = vertex_areas[F(j,2)] + (abs(dblA(j))/6);\n        //}\n        \n        \n        Eigen::MatrixXd N_before,N_after;\n        igl::adjacency_list(F,A);\n        \n        \n        int num_feat = feature.size();\n        std::vector<bool> is_feature_vertex;\n        is_feature_vertex.resize(n);\n        \n        for (int s = 0; s < num_feat; s++) {\n            is_feature_vertex[feature(s)] = true;\n        }\n        \n        Q.resize(n,3);\n        P.resize(n,3);\n        //           Eigen::MatrixXd N;\n        igl::per_vertex_normals(V,F,N);\n        \n        for(int i = 0; i < n; i++){\n            bool is_feature = is_feature_vertex[i];\n            if (!is_feature) {\n     \n            Eigen::RowVector3d q,p;\n            q.setZero();\n            p.setZero();\n            double denominator = 0.0;\n            for(int j = 0; j < A[i].size(); j++){\n                q = q + (V.row(A[i][j])/A[i].size());\n                // q = q + (V.row(A[i][j])*vertex_areas[A[i][j]]);\n                // std::cout << q << std::endl;\n                // denominator = denominator + vertex_areas[A[i][j]];\n                } // q is )( barycenter?\n            // q = q/denominator;\n            // N.row(i) = N.row(i)/N.row(i).norm();\n            NN = lambda(i)*N.row(i).transpose()*(N.row(i));\n             p = (q.transpose()+(NN*(V.row(i).transpose() - q.transpose()))).transpose();\n            // p = q;\n             // std::cout << N.row(i) << std::endl;\n                \n            V.row(i) = p;\n            \n            // igl::per_face_normals(V_projected,F,Eigen::Vector3d(0,0,0),N_after);\n    //            for (int j = 0; j < m ; j++) {\n    //                if (N_before.row(j).dot(N_after.row(j)) < 0) {\n    //                    // std::cout << \"Avoided face flipping, I think.\" << std::endl;\n    //                    V.row(i) = V_fixed.row(i);\n    //                }\n    //            }\n                \n            }\n        }\n//        igl::remove_duplicate_vertices(V,0,SV,SVI,SVJ);\n//        std::cout << V.rows()-SV.rows() << std::endl;\n        igl::point_mesh_squared_distance(V,V0,F0,sqrD,sqrI,V_projected);\n    \n        \n    V = V_projected;\n//    igl::remove_duplicate_vertices(V,0,SV,SVI,SVJ);\n//    std::cout << V.rows()-SV.rows() << std::endl;\n //   std::cout << \"not projecting!\" << std::endl;\n}\n\n\n// g++ -I/usr/local/libigl/external/eigen -I/usr/local/libigl/include -std=c++11 -framework Accelerate main.cpp remesh_botsch.cpp -o main\n\n", "meta": {"hexsha": "2f07d6ea7eab1c22e08c7cfe16b1c64cf7205182", "size": 4195, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tangential_relaxation.cpp", "max_stars_repo_name": "sgsellan/opening-and-closing-surfaces", "max_stars_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T00:03:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T19:44:35.000Z", "max_issues_repo_path": "src/tangential_relaxation.cpp", "max_issues_repo_name": "sgsellan/opening-and-closing-surfaces", "max_issues_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tangential_relaxation.cpp", "max_forks_repo_name": "sgsellan/opening-and-closing-surfaces", "max_forks_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-27T01:40:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T13:42:16.000Z", "avg_line_length": 33.2936507937, "max_line_length": 137, "alphanum_fraction": 0.5210965435, "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262966, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5027297466108773}}
{"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_CCMATH_MODF_HPP\n#define BOOST_MATH_CCMATH_MODF_HPP\n\n#include <cmath>\n#include <limits>\n#include <type_traits>\n#include <boost/math/tools/is_constant_evaluated.hpp>\n#include <boost/math/ccmath/abs.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/trunc.hpp>\n\nnamespace boost::math::ccmath {\n\nnamespace detail {\n\ntemplate <typename Real>\ninline constexpr Real modf_error_impl(Real x, Real* iptr)\n{\n    *iptr = x;\n    return boost::math::ccmath::abs(x) == Real(0) ? x :\n           x > Real(0) ? Real(0) : -Real(0);\n}\n\ntemplate <typename Real>\ninline constexpr Real modf_nan_impl(Real x, Real* iptr)\n{\n    *iptr = x;\n    return x;\n}\n\ntemplate <typename Real>\ninline constexpr Real modf_impl(Real x, Real* iptr)\n{\n    *iptr = boost::math::ccmath::trunc(x);\n    return (x - *iptr);\n}\n\n} // Namespace detail\n\ntemplate <typename Real>\ninline constexpr Real modf(Real x, Real* iptr)\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))\n    {\n        return boost::math::ccmath::abs(x) == Real(0) ? detail::modf_error_impl(x, iptr) :\n               boost::math::ccmath::isinf(x) ? detail::modf_error_impl(x, iptr) :\n               boost::math::ccmath::isnan(x) ? detail::modf_nan_impl(x, iptr) :\n               boost::math::ccmath::detail::modf_impl(x, iptr);\n    }\n    else\n    {\n        using std::modf;\n        return modf(x, iptr);\n    }\n}\n\ninline constexpr float modff(float x, float* iptr)\n{\n    return boost::math::ccmath::modf(x, iptr);\n}\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline constexpr long double modfl(long double x, long double* iptr)\n{\n    return boost::math::ccmath::modf(x, iptr);\n}\n#endif\n\n} // Namespaces\n\n#endif // BOOST_MATH_CCMATH_MODF_HPP\n", "meta": {"hexsha": "479f6432e8b3b2d4e55f47abad3e7d76635531c9", "size": 1971, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/ccmath/modf.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/ccmath/modf.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/ccmath/modf.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": 25.2692307692, "max_line_length": 90, "alphanum_fraction": 0.6788432268, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5027106729645495}}
{"text": "#include <iostream>\n#include <fstream>\n#include <boost/program_options.hpp>\n#include <random>\n#include <iomanip>\n#include <chrono>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/operation_blocked.hpp>\n#include \"matrix.h\"\n\nnamespace po = boost::program_options;\nusing namespace std;\nstd::uniform_real_distribution<double> urd;\nstd::default_random_engine re;\n\nTmat RandomMatrix(int m, int n) {\n  Tmat mat = newMat(m, n);\n  for (int i = 0; i < m; i += 1) {\n    for (int j = 0; j < n; j += 1) {\n      mat[j][i] = urd(re);\n    }\n  }\n  return mat;\n}\nvoid prikaz1(Tmat &mat) {\n  for (auto &vrstica : mat) {\n    std::cout << \"|\";\n    for (auto &element : vrstica) {\n      std::cout << std::setw(10) << element;\n    }\n    std::cout << \"|\" << std::endl;\n  }\n  std::cout << std::endl;\n}\nboost::numeric::ublas::matrix<double> TmatToBlas(Tmat mat) {\n  int m1 = mat.size();\n  int n1 = mat[0].size();\n  boost::numeric::ublas::matrix<double> bmat(m1, n1);\n  for (int i = 0; i < m1; i += 1) {\n    for (int j = 0; j < n1; j += 1) {\n      bmat(i, j) = mat[i][j];\n    }\n  }\n  return bmat;\n}\n\nboost::numeric::ublas::matrix<double> MultiplicationBlas(boost::numeric::ublas::matrix<double> M1,\n                                                         boost::numeric::ublas::matrix<double> M2) {\n  return boost::numeric::ublas::block_prod<boost::numeric::ublas::matrix<double>, 32>(M1, M2);\n}\n\nenum Method {\n  CLASSIC, CLASSIC_T, RECURSIVE, RECURSIVE_T, SUBCUBIC, BLAS //STRASSEN, BLAS\n};\nstatic map<string, Method> methodMap{\n    {\"classic\",              CLASSIC},\n    {\"classic_transposed\",   CLASSIC_T},\n    {\"recursive\",            RECURSIVE},\n    {\"recursive_transposed\", RECURSIVE_T},\n    {\"subcubic\",             SUBCUBIC},\n    //{\"strassen\",             STRASSEN},\n    {\"blas\",                 BLAS}\n};\n\nint main(int ac, const char **av) {\n  int a, b, c;\n  int repeat;\n  int seed = 2; //totaly random\n  int max_time;\n  Method method;\n  try {\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (\"help\", \"Display this message\")\n        (\"method,m\", po::value<string>()->default_value(\"subcubic\"), \"Method to benchmark \\n\"\n            \"Available methods:\\n\"\n            \"  classic\\n\"\n            \"  classic_transposed\\n\"\n            \"  recursive\\n\"\n            \"  recursive_transposed\\n\"\n            \"  subcubic \\n\"\n            //\"  strassen \\n\"\n            \"  blas \\n\"\n        )\n        (\"a,a\", po::value<int>()->default_value(512), \"A in (A,B)x(B,C) mutiplication  \\n \")\n        (\"b,b\", po::value<int>()->default_value(512), \"B in (A,B)x(B,C) mutiplication  \\n \")\n        (\"c,c\", po::value<int>()->default_value(512), \"C in (A,B)x(B,C) mutiplication  \\n \")\n        (\"repeat,r\", po::value<int>()->default_value(1), \"Number of tests to run\")\n        (\"time,t\", po::value<int>()->default_value(0), \"Repeat test until arg ms elapsed, overrides --repeat \\n \");\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(ac, av, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n      cout << desc << \"\\n\";\n      return 1;\n    }\n\n    if (vm.count(\"method\")) {\n      string m = vm[\"method\"].as<string>();\n      if (methodMap.count(m) > 0) {\n        //cout << \"testing with method \" << m << '\\n';\n        method = methodMap[m];\n      } else {\n        cout << m << \" is not a valid method, use --help for a list of available methods.\";\n        return 1;\n      }\n    } else {\n      cout << \"method was not set!\\n\";\n      return 1;\n    }\n\n    if (vm.count(\"a\")) {\n      a = vm[\"a\"].as<int>();\n      //cout << \"a = \" << a << '\\n';\n\n    } else {\n      cout << \"a was not set!\\n\";\n      return 1;\n    }\n    if (vm.count(\"b\")) {\n      b = vm[\"b\"].as<int>();\n      //cout << \"b = \" << b << '\\n';\n\n    } else {\n      cout << \"b was not set!\\n\";\n      return 1;\n    }\n    if (vm.count(\"c\")) {\n      c = vm[\"c\"].as<int>();\n      // cout << \"c = \" << c << '\\n';\n\n    } else {\n      cout << \"c was not set!\\n\";\n      return 1;\n    }\n\n    if (vm.count(\"time\")) {\n      max_time = vm[\"time\"].as<int>();\n    }\n\n    repeat = vm[\"repeat\"].as<int>();\n    if (max_time == 0) {\n      //cout << \"Number of test: \" << repeat << endl;\n    } else {\n      //cout << \"Testing for \" << max_time << \" ms\" << endl;\n    }\n\n  } catch (std::exception &e) {\n    cerr << e.what();\n  }\n\n\n  //Execute the tests\n  urd = std::uniform_real_distribution<double>(0, 1);\n  re = std::default_random_engine(seed);\n  Tmat m1 = RandomMatrix(b, a);\n  Tmat m2 = RandomMatrix(c, b);\n  boost::numeric::ublas::matrix<double> bm1, bm2;\n\n  std::function<Tmat(Tmat &, Tmat &)> f;\n  auto blas_f = MultiplicationBlas;\n\n  switch (method) {\n    case CLASSIC:f = MultiplicationClassic;\n      break;\n    case CLASSIC_T:f = MultiplicationClassicTransposed;\n      break;\n    case RECURSIVE:f = MultiplicationRecursive;\n      break;\n    case RECURSIVE_T:f = MultiplicationRecursiveTransposed;\n      break;\n    case SUBCUBIC:f = MultiplicationSubcubic;\n      break;\n    //case STRASSEN: f = strassen_mul;\n    //  break;\n    case BLAS :bm1 = TmatToBlas(m1);\n      bm2 = TmatToBlas(m2);\n  }\n  if (max_time == 1) {\n    //placeholder for testing\n    int n = 512;\n    Tmat mat1 = newMat(n, n);\n    Tmat mat2 = newMat(n, n);\n    double konst = 100000000.000002;\n    for (int i = 0; i < n; i += 1) {\n      for (int j = 0; j < n; j += 1) {\n        mat1[i][j] = konst;\n        mat2[i][j] = konst;\n      }\n    }\n    Tmat mat3 = f(mat1, mat2);\n    //prikaz1(mat3);\n    cout << setprecision(24);\n    cout << konst * konst * n << endl << mat3[0][0] << endl;\n    cout << mat3[n / 2][n / 2] - konst * konst * n << endl;\n  } else {\n\n    if (max_time > 0) {\n      int count = 0;\n      std::chrono::time_point<std::chrono::steady_clock> time_start, time_end;\n      auto time_total = std::chrono::milliseconds{0};\n      while (true) {\n        time_start = std::chrono::steady_clock::now();\n        if (method == BLAS) {\n          auto bm3 = blas_f(bm1, bm2);\n        } else {\n          Tmat m3 = f(m1, m2);\n        }\n        time_end = std::chrono::steady_clock::now();\n        auto time_of_test = std::chrono::duration_cast<std::chrono::milliseconds>(time_end - time_start);\n//cout << time_of_test.count() << endl;\n        time_total +=\n            time_of_test;\n        count++;\n        if (time_total.\n            count()\n            > max_time || count > 10000) {\n//cout << \"Total time:\" << time_total.count() << \"ms\" << endl;\n//cout << \"Iteration time:\" << time_total.count() / count << \"ms\" << endl;\n          cout << time_total.\n              count()\n              / count <<\n               endl;\n          break;\n        }\n      }\n    } else {\n\n      std::chrono::time_point<std::chrono::steady_clock> time_start, time_end;\n      time_start = std::chrono::steady_clock::now();\n      if (method == BLAS) {\n        for (\n            int i = 0;\n            i < repeat;\n            ++i) {\n          auto bm3 = blas_f(bm1, bm2);\n        }\n      } else {\n        for (\n            int i = 0;\n            i < repeat;\n            ++i) {\n          Tmat m3 = f(m1, m2);\n        }\n      }\n\n      time_end = std::chrono::steady_clock::now();\n      auto time_total = std::chrono::duration_cast<std::chrono::milliseconds>(time_end - time_start);\n      std::cout << time_total.count() / repeat << endl;\n    }\n  }\n}\n\n\n", "meta": {"hexsha": "e8c86cf0c9368e4bb4e52640376f7c08ee3b2cd7", "size": 7358, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "programi/auto_optimize/newtests.cpp", "max_stars_repo_name": "mihic/clanek-matrike", "max_stars_repo_head_hexsha": "5a35b0a214a0942497443222a08dbb28c8ff95d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-10T07:58:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T07:58:39.000Z", "max_issues_repo_path": "programi/auto_optimize/newtests.cpp", "max_issues_repo_name": "mihic/clanek-matrike", "max_issues_repo_head_hexsha": "5a35b0a214a0942497443222a08dbb28c8ff95d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "programi/auto_optimize/newtests.cpp", "max_forks_repo_name": "mihic/clanek-matrike", "max_forks_repo_head_hexsha": "5a35b0a214a0942497443222a08dbb28c8ff95d9", "max_forks_repo_licenses": ["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.4092664093, "max_line_length": 115, "alphanum_fraction": 0.5281326447, "num_tokens": 2188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5027106633514951}}
{"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   testAHRSFactor.cpp\n * @brief  Unit test for AHRSFactor\n * @author Krunal Chande\n * @author Luca Carlone\n * @author Frank Dellaert\n * @author Varun Agrawal\n */\n\n#include <gtsam/navigation/AHRSFactor.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/base/TestableAssertions.h>\n#include <gtsam/base/numericalDerivative.h>\n#include <gtsam/base/debug.h>\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/bind/bind.hpp>\n#include <list>\n\nusing namespace boost::placeholders;\nusing namespace std;\nusing namespace gtsam;\n\n// Convenience for named keys\nusing symbol_shorthand::X;\nusing symbol_shorthand::V;\nusing symbol_shorthand::B;\n\nVector3 kZeroOmegaCoriolis(0,0,0);\n\n// Define covariance matrices\ndouble accNoiseVar = 0.01;\nconst Matrix3 kMeasuredAccCovariance = accNoiseVar * I_3x3;\n\n//******************************************************************************\nnamespace {\nVector callEvaluateError(const AHRSFactor& factor, const Rot3 rot_i,\n    const Rot3 rot_j, const Vector3& bias) {\n  return factor.evaluateError(rot_i, rot_j, bias);\n}\n\nRot3 evaluateRotationError(const AHRSFactor& factor, const Rot3 rot_i,\n    const Rot3 rot_j, const Vector3& bias) {\n  return Rot3::Expmap(factor.evaluateError(rot_i, rot_j, bias).tail(3));\n}\n\nAHRSFactor::PreintegratedMeasurements evaluatePreintegratedMeasurements(\n    const Vector3& bias, const list<Vector3>& measuredOmegas,\n    const list<double>& deltaTs,\n    const Vector3& initialRotationRate = Vector3::Zero()) {\n  AHRSFactor::PreintegratedMeasurements result(bias, I_3x3);\n\n  list<Vector3>::const_iterator itOmega = measuredOmegas.begin();\n  list<double>::const_iterator itDeltaT = deltaTs.begin();\n  for (; itOmega != measuredOmegas.end(); ++itOmega, ++itDeltaT) {\n    result.integrateMeasurement(*itOmega, *itDeltaT);\n  }\n\n  return result;\n}\n\nRot3 evaluatePreintegratedMeasurementsRotation(\n    const Vector3& bias, const list<Vector3>& measuredOmegas,\n    const list<double>& deltaTs,\n    const Vector3& initialRotationRate = Vector3::Zero()) {\n  return Rot3(\n      evaluatePreintegratedMeasurements(bias, measuredOmegas, deltaTs,\n          initialRotationRate).deltaRij());\n}\n\nRot3 evaluateRotation(const Vector3 measuredOmega, const Vector3 biasOmega,\n    const double deltaT) {\n  return Rot3::Expmap((measuredOmega - biasOmega) * deltaT);\n}\n\nVector3 evaluateLogRotation(const Vector3 thetahat, const Vector3 deltatheta) {\n  return Rot3::Logmap(Rot3::Expmap(thetahat).compose(Rot3::Expmap(deltatheta)));\n}\n\n}\n//******************************************************************************\nTEST( AHRSFactor, PreintegratedMeasurements ) {\n  // Linearization point\n  Vector3 bias(0,0,0); ///< Current estimate of angular rate bias\n\n  // Measurements\n  Vector3 measuredOmega(M_PI / 100.0, 0.0, 0.0);\n  double deltaT = 0.5;\n\n  // Expected preintegrated values\n  Rot3 expectedDeltaR1 = Rot3::RzRyRx(0.5 * M_PI / 100.0, 0.0, 0.0);\n  double expectedDeltaT1(0.5);\n\n  // Actual preintegrated values\n  AHRSFactor::PreintegratedMeasurements actual1(bias, Z_3x3);\n  actual1.integrateMeasurement(measuredOmega, deltaT);\n\n  EXPECT(assert_equal(expectedDeltaR1, Rot3(actual1.deltaRij()), 1e-6));\n  DOUBLES_EQUAL(expectedDeltaT1, actual1.deltaTij(), 1e-6);\n\n  // Integrate again\n  Rot3 expectedDeltaR2 = Rot3::RzRyRx(2.0 * 0.5 * M_PI / 100.0, 0.0, 0.0);\n  double expectedDeltaT2(1);\n\n  // Actual preintegrated values\n  AHRSFactor::PreintegratedMeasurements actual2 = actual1;\n  actual2.integrateMeasurement(measuredOmega, deltaT);\n\n  EXPECT(assert_equal(expectedDeltaR2, Rot3(actual2.deltaRij()), 1e-6));\n  DOUBLES_EQUAL(expectedDeltaT2, actual2.deltaTij(), 1e-6);\n}\n\n//******************************************************************************\nTEST( AHRSFactor, PreintegratedAhrsMeasurementsConstructor ) {\n  Matrix3 gyroscopeCovariance = Matrix3::Ones()*0.4;\n  Vector3 omegaCoriolis(0.1, 0.5, 0.9);\n  PreintegratedRotationParams params(gyroscopeCovariance, omegaCoriolis);\n  Vector3 bias(1.0,2.0,3.0); ///< Current estimate of angular rate bias\n  Rot3 deltaRij(Rot3::RzRyRx(M_PI / 12.0, M_PI / 6.0, M_PI / 4.0));\n  double deltaTij = 0.02;\n  Matrix3 delRdelBiasOmega = Matrix3::Ones()*0.5;\n  Matrix3 preintMeasCov = Matrix3::Ones()*0.2;\n  PreintegratedAhrsMeasurements actualPim(\n    boost::make_shared<PreintegratedRotationParams>(params),\n    bias,\n    deltaTij,\n    deltaRij,\n    delRdelBiasOmega,\n    preintMeasCov);\n  EXPECT(assert_equal(gyroscopeCovariance,\n      actualPim.p().getGyroscopeCovariance(), 1e-6));\n  EXPECT(assert_equal(omegaCoriolis,\n      actualPim.p().getOmegaCoriolis().get(), 1e-6));\n  EXPECT(assert_equal(bias, actualPim.biasHat(), 1e-6));\n  DOUBLES_EQUAL(deltaTij, actualPim.deltaTij(), 1e-6);\n  EXPECT(assert_equal(deltaRij, Rot3(actualPim.deltaRij()), 1e-6));\n  EXPECT(assert_equal(delRdelBiasOmega, actualPim.delRdelBiasOmega(), 1e-6));\n  EXPECT(assert_equal(preintMeasCov, actualPim.preintMeasCov(), 1e-6));\n}\n\n/* ************************************************************************* */\nTEST(AHRSFactor, Error) {\n  // Linearization point\n  Vector3 bias(0.,0.,0.); // Bias\n  Rot3 x1(Rot3::RzRyRx(M_PI / 12.0, M_PI / 6.0, M_PI / 4.0));\n  Rot3 x2(Rot3::RzRyRx(M_PI / 12.0 + M_PI / 100.0, M_PI / 6.0, M_PI / 4.0));\n\n  // Measurements\n  Vector3 measuredOmega;\n  measuredOmega << M_PI / 100, 0, 0;\n  double deltaT = 1.0;\n  AHRSFactor::PreintegratedMeasurements pim(bias, Z_3x3);\n  pim.integrateMeasurement(measuredOmega, deltaT);\n\n  // Create factor\n  AHRSFactor factor(X(1), X(2), B(1), pim, kZeroOmegaCoriolis, boost::none);\n\n  Vector3 errorActual = factor.evaluateError(x1, x2, bias);\n\n  // Expected error\n  Vector3 errorExpected(3);\n  errorExpected << 0, 0, 0;\n  EXPECT(assert_equal(Vector(errorExpected), Vector(errorActual), 1e-6));\n\n  // Expected Jacobians\n  Matrix H1e = numericalDerivative11<Vector3, Rot3>(\n      boost::bind(&callEvaluateError, factor, _1, x2, bias), x1);\n  Matrix H2e = numericalDerivative11<Vector3, Rot3>(\n      boost::bind(&callEvaluateError, factor, x1, _1, bias), x2);\n  Matrix H3e = numericalDerivative11<Vector3, Vector3>(\n      boost::bind(&callEvaluateError, factor, x1, x2, _1), bias);\n\n  // Check rotation Jacobians\n  Matrix RH1e = numericalDerivative11<Rot3, Rot3>(\n      boost::bind(&evaluateRotationError, factor, _1, x2, bias), x1);\n  Matrix RH2e = numericalDerivative11<Rot3, Rot3>(\n      boost::bind(&evaluateRotationError, factor, x1, _1, bias), x2);\n\n  // Actual Jacobians\n  Matrix H1a, H2a, H3a;\n  (void) factor.evaluateError(x1, x2, bias, H1a, H2a, H3a);\n\n  // rotations\n  EXPECT(assert_equal(RH1e, H1a, 1e-5));\n  // 1e-5 needs to be added only when using quaternions for rotations\n\n  EXPECT(assert_equal(H2e, H2a, 1e-5));\n\n  // rotations\n  EXPECT(assert_equal(RH2e, H2a, 1e-5));\n  // 1e-5 needs to be added only when using quaternions for rotations\n\n  EXPECT(assert_equal(H3e, H3a, 1e-5));\n  // 1e-5 needs to be added only when using quaternions for rotations\n}\n\n/* ************************************************************************* */\nTEST(AHRSFactor, ErrorWithBiases) {\n  // Linearization point\n\n  Vector3 bias(0, 0, 0.3);\n  Rot3 x1(Rot3::Expmap(Vector3(0, 0, M_PI / 4.0)));\n  Rot3 x2(Rot3::Expmap(Vector3(0, 0, M_PI / 4.0 + M_PI / 10.0)));\n\n  // Measurements\n  Vector3 measuredOmega;\n  measuredOmega << 0, 0, M_PI / 10.0 + 0.3;\n  double deltaT = 1.0;\n\n  AHRSFactor::PreintegratedMeasurements pim(Vector3(0,0,0),\n      Z_3x3);\n  pim.integrateMeasurement(measuredOmega, deltaT);\n\n  // Create factor\n  AHRSFactor factor(X(1), X(2), B(1), pim, kZeroOmegaCoriolis);\n\n  Vector errorActual = factor.evaluateError(x1, x2, bias);\n\n  // Expected error\n  Vector errorExpected(3);\n  errorExpected << 0, 0, 0;\n  EXPECT(assert_equal(errorExpected, errorActual, 1e-6));\n\n  // Expected Jacobians\n  Matrix H1e = numericalDerivative11<Vector, Rot3>(\n      boost::bind(&callEvaluateError, factor, _1, x2, bias), x1);\n  Matrix H2e = numericalDerivative11<Vector, Rot3>(\n      boost::bind(&callEvaluateError, factor, x1, _1, bias), x2);\n  Matrix H3e = numericalDerivative11<Vector, Vector3>(\n      boost::bind(&callEvaluateError, factor, x1, x2, _1), bias);\n\n  // Check rotation Jacobians\n  Matrix RH1e = numericalDerivative11<Rot3, Rot3>(\n      boost::bind(&evaluateRotationError, factor, _1, x2, bias), x1);\n  Matrix RH2e = numericalDerivative11<Rot3, Rot3>(\n      boost::bind(&evaluateRotationError, factor, x1, _1, bias), x2);\n  Matrix RH3e = numericalDerivative11<Rot3, Vector3>(\n      boost::bind(&evaluateRotationError, factor, x1, x2, _1), bias);\n\n  // Actual Jacobians\n  Matrix H1a, H2a, H3a;\n  (void) factor.evaluateError(x1, x2, bias, H1a, H2a, H3a);\n\n  EXPECT(assert_equal(H1e, H1a));\n  EXPECT(assert_equal(H2e, H2a));\n  EXPECT(assert_equal(H3e, H3a));\n}\n\n//******************************************************************************\nTEST( AHRSFactor, PartialDerivativeExpmap ) {\n  // Linearization point\n  Vector3 biasOmega(0,0,0);\n\n  // Measurements\n  Vector3 measuredOmega;\n  measuredOmega << 0.1, 0, 0;\n  double deltaT = 0.5;\n\n  // Compute numerical derivatives\n  Matrix expectedDelRdelBiasOmega = numericalDerivative11<Rot3, Vector3>(\n      boost::bind(&evaluateRotation, measuredOmega, _1, deltaT), biasOmega);\n\n  const Matrix3 Jr = Rot3::ExpmapDerivative(\n      (measuredOmega - biasOmega) * deltaT);\n\n  Matrix3 actualdelRdelBiasOmega = -Jr * deltaT; // the delta bias appears with the minus sign\n\n  // Compare Jacobians\n  EXPECT(assert_equal(expectedDelRdelBiasOmega, actualdelRdelBiasOmega, 1e-3));\n  // 1e-3 needs to be added only when using quaternions for rotations\n\n}\n\n//******************************************************************************\nTEST( AHRSFactor, PartialDerivativeLogmap ) {\n  // Linearization point\n  Vector3 thetahat;\n  thetahat << 0.1, 0.1, 0; ///< Current estimate of rotation rate bias\n\n  // Measurements\n  Vector3 deltatheta;\n  deltatheta << 0, 0, 0;\n\n  // Compute numerical derivatives\n  Matrix expectedDelFdeltheta = numericalDerivative11<Vector3, Vector3>(\n      boost::bind(&evaluateLogRotation, thetahat, _1), deltatheta);\n\n  const Vector3 x = thetahat; // parametrization of so(3)\n  const Matrix3 X = skewSymmetric(x); // element of Lie algebra so(3): X = x^\n  double normx = x.norm();\n  const Matrix3 actualDelFdeltheta = I_3x3 + 0.5 * X\n      + (1 / (normx * normx) - (1 + cos(normx)) / (2 * normx * sin(normx))) * X\n          * X;\n\n  // Compare Jacobians\n  EXPECT(assert_equal(expectedDelFdeltheta, actualDelFdeltheta));\n\n}\n\n//******************************************************************************\nTEST( AHRSFactor, fistOrderExponential ) {\n  // Linearization point\n  Vector3 biasOmega(0,0,0);\n\n  // Measurements\n  Vector3 measuredOmega;\n  measuredOmega << 0.1, 0, 0;\n  double deltaT = 1.0;\n\n  // change w.r.t. linearization point\n  double alpha = 0.0;\n  Vector3 deltabiasOmega;\n  deltabiasOmega << alpha, alpha, alpha;\n\n  const Matrix3 Jr = Rot3::ExpmapDerivative(\n      (measuredOmega - biasOmega) * deltaT);\n\n  Matrix3 delRdelBiasOmega = -Jr * deltaT; // the delta bias appears with the minus sign\n\n  const Matrix expectedRot = Rot3::Expmap(\n      (measuredOmega - biasOmega - deltabiasOmega) * deltaT).matrix();\n\n  const Matrix3 hatRot =\n      Rot3::Expmap((measuredOmega - biasOmega) * deltaT).matrix();\n  const Matrix3 actualRot = hatRot\n      * Rot3::Expmap(delRdelBiasOmega * deltabiasOmega).matrix();\n\n  // Compare Jacobians\n  EXPECT(assert_equal(expectedRot, actualRot));\n}\n\n//******************************************************************************\nTEST( AHRSFactor, FirstOrderPreIntegratedMeasurements ) {\n  // Linearization point\n  Vector3 bias = Vector3::Zero(); ///< Current estimate of rotation rate bias\n\n  Pose3 body_P_sensor(Rot3::Expmap(Vector3(0, 0.1, 0.1)), Point3(1, 0, 1));\n\n  // Measurements\n  list<Vector3> measuredOmegas;\n  list<double> deltaTs;\n  measuredOmegas.push_back(Vector3(M_PI / 100.0, 0.0, 0.0));\n  deltaTs.push_back(0.01);\n  measuredOmegas.push_back(Vector3(M_PI / 100.0, 0.0, 0.0));\n  deltaTs.push_back(0.01);\n  for (int i = 1; i < 100; i++) {\n    measuredOmegas.push_back(\n        Vector3(M_PI / 100.0, M_PI / 300.0, 2 * M_PI / 100.0));\n    deltaTs.push_back(0.01);\n  }\n\n  // Actual preintegrated values\n  AHRSFactor::PreintegratedMeasurements preintegrated =\n      evaluatePreintegratedMeasurements(bias, measuredOmegas, deltaTs,\n          Vector3(M_PI / 100.0, 0.0, 0.0));\n\n  // Compute numerical derivatives\n  Matrix expectedDelRdelBias =\n      numericalDerivative11<Rot3, Vector3>(\n          boost::bind(&evaluatePreintegratedMeasurementsRotation, _1,\n              measuredOmegas, deltaTs, Vector3(M_PI / 100.0, 0.0, 0.0)), bias);\n  Matrix expectedDelRdelBiasOmega = expectedDelRdelBias.rightCols(3);\n\n  // Compare Jacobians\n  EXPECT(\n      assert_equal(expectedDelRdelBiasOmega, preintegrated.delRdelBiasOmega(), 1e-3));\n  // 1e-3 needs to be added only when using quaternions for rotations\n}\n\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n\n//******************************************************************************\nTEST( AHRSFactor, ErrorWithBiasesAndSensorBodyDisplacement ) {\n\n  Vector3 bias(0, 0, 0.3);\n  Rot3 x1(Rot3::Expmap(Vector3(0, 0, M_PI / 4.0)));\n  Rot3 x2(Rot3::Expmap(Vector3(0, 0, M_PI / 4.0 + M_PI / 10.0)));\n\n  // Measurements\n  Vector3 omegaCoriolis;\n  omegaCoriolis << 0, 0.1, 0.1;\n  Vector3 measuredOmega;\n  measuredOmega << 0, 0, M_PI / 10.0 + 0.3;\n  double deltaT = 1.0;\n\n  const Pose3 body_P_sensor(Rot3::Expmap(Vector3(0, 0.10, 0.10)),\n      Point3(1, 0, 0));\n\n  AHRSFactor::PreintegratedMeasurements pim(Vector3::Zero(), kMeasuredAccCovariance);\n\n  pim.integrateMeasurement(measuredOmega, deltaT);\n\n  // Check preintegrated covariance\n  EXPECT(assert_equal(kMeasuredAccCovariance, pim.preintMeasCov()));\n\n  // Create factor\n  AHRSFactor factor(X(1), X(2), B(1), pim, omegaCoriolis);\n\n  // Expected Jacobians\n  Matrix H1e = numericalDerivative11<Vector, Rot3>(\n      boost::bind(&callEvaluateError, factor, _1, x2, bias), x1);\n  Matrix H2e = numericalDerivative11<Vector, Rot3>(\n      boost::bind(&callEvaluateError, factor, x1, _1, bias), x2);\n  Matrix H3e = numericalDerivative11<Vector, Vector3>(\n      boost::bind(&callEvaluateError, factor, x1, x2, _1), bias);\n\n  // Check rotation Jacobians\n  Matrix RH1e = numericalDerivative11<Rot3, Rot3>(\n      boost::bind(&evaluateRotationError, factor, _1, x2, bias), x1);\n  Matrix RH2e = numericalDerivative11<Rot3, Rot3>(\n      boost::bind(&evaluateRotationError, factor, x1, _1, bias), x2);\n  Matrix RH3e = numericalDerivative11<Rot3, Vector3>(\n      boost::bind(&evaluateRotationError, factor, x1, x2, _1), bias);\n\n  // Actual Jacobians\n  Matrix H1a, H2a, H3a;\n  (void) factor.evaluateError(x1, x2, bias, H1a, H2a, H3a);\n\n  EXPECT(assert_equal(H1e, H1a));\n  EXPECT(assert_equal(H2e, H2a));\n  EXPECT(assert_equal(H3e, H3a));\n}\n//******************************************************************************\nTEST (AHRSFactor, predictTest) {\n  Vector3 bias(0,0,0);\n\n  // Measurements\n  Vector3 measuredOmega;\n  measuredOmega << 0, 0, M_PI / 10.0;\n  double deltaT = 0.2;\n  AHRSFactor::PreintegratedMeasurements pim(bias, kMeasuredAccCovariance);\n  for (int i = 0; i < 1000; ++i) {\n    pim.integrateMeasurement(measuredOmega, deltaT);\n  }\n  // Check preintegrated covariance\n  Matrix expectedMeasCov(3,3);\n  expectedMeasCov = 200*kMeasuredAccCovariance;\n  EXPECT(assert_equal(expectedMeasCov, pim.preintMeasCov()));\n\n  AHRSFactor factor(X(1), X(2), B(1), pim, kZeroOmegaCoriolis);\n\n  // Predict\n  Rot3 x;\n  Rot3 expectedRot = Rot3::Ypr(20*M_PI, 0, 0);\n  Rot3 actualRot = factor.predict(x, bias, pim, kZeroOmegaCoriolis);\n  EXPECT(assert_equal(expectedRot, actualRot, 1e-6));\n\n  // AHRSFactor::PreintegratedMeasurements::predict\n  Matrix expectedH = numericalDerivative11<Vector3, Vector3>(\n      boost::bind(&AHRSFactor::PreintegratedMeasurements::predict,\n          &pim, _1, boost::none), bias);\n\n  // Actual Jacobians\n  Matrix H;\n  (void) pim.predict(bias,H);\n  EXPECT(assert_equal(expectedH, H, 1e-8));\n}\n//******************************************************************************\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/nonlinear/Marginals.h>\n\nTEST (AHRSFactor, graphTest) {\n  // linearization point\n  Rot3 x1(Rot3::RzRyRx(0, 0, 0));\n  Rot3 x2(Rot3::RzRyRx(0, M_PI / 4, 0));\n  Vector3 bias(0,0,0);\n\n  // PreIntegrator\n  Vector3 biasHat(0, 0, 0);\n  AHRSFactor::PreintegratedMeasurements pim(biasHat, kMeasuredAccCovariance);\n\n  // Pre-integrate measurements\n  Vector3 measuredOmega(0, M_PI / 20, 0);\n  double deltaT = 1;\n\n  // Create Factor\n  noiseModel::Base::shared_ptr model = //\n      noiseModel::Gaussian::Covariance(pim.preintMeasCov());\n  NonlinearFactorGraph graph;\n  Values values;\n  for (size_t i = 0; i < 5; ++i) {\n    pim.integrateMeasurement(measuredOmega, deltaT);\n  }\n\n  // pim.print(\"Pre integrated measurementes\");\n  AHRSFactor factor(X(1), X(2), B(1), pim, kZeroOmegaCoriolis);\n  values.insert(X(1), x1);\n  values.insert(X(2), x2);\n  values.insert(B(1), bias);\n  graph.push_back(factor);\n  LevenbergMarquardtOptimizer optimizer(graph, values);\n  Values result = optimizer.optimize();\n  Rot3 expectedRot(Rot3::RzRyRx(0, M_PI / 4, 0));\n  EXPECT(assert_equal(expectedRot, result.at<Rot3>(X(2))));\n}\n\n//******************************************************************************\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n//******************************************************************************\n", "meta": {"hexsha": "828e264f464311a790976aa5e78fc4c689489084", "size": 17869, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/navigation/tests/testAHRSFactor.cpp", "max_stars_repo_name": "acxz/gtsam", "max_stars_repo_head_hexsha": "cd3854a1f6db923d40ecf3ced56bafbe339d1b3c", "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": "gtsam/navigation/tests/testAHRSFactor.cpp", "max_issues_repo_name": "acxz/gtsam", "max_issues_repo_head_hexsha": "cd3854a1f6db923d40ecf3ced56bafbe339d1b3c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/navigation/tests/testAHRSFactor.cpp", "max_forks_repo_name": "acxz/gtsam", "max_forks_repo_head_hexsha": "cd3854a1f6db923d40ecf3ced56bafbe339d1b3c", "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.6970873786, "max_line_length": 94, "alphanum_fraction": 0.6604174828, "num_tokens": 5416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5027106603726355}}
{"text": "/* test_discrete_distribution.cpp\n *\n * Copyright Steven Watanabe 2010\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_discrete_distribution.cpp 83381 2013-03-09 22:55:05Z eric_niebler $\n *\n */\n\n#include <boost/random/discrete_distribution.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/assign/list_of.hpp>\n#include <sstream>\n#include <vector>\n#include \"concepts.hpp\"\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\nusing boost::random::test::RandomNumberDistribution;\nusing boost::random::discrete_distribution;\nBOOST_CONCEPT_ASSERT((RandomNumberDistribution< discrete_distribution<> >));\n\nstruct gen {\n    double operator()(double arg) {\n        if(arg < 100) return 100;\n        else if(arg < 103) return 1;\n        else if(arg < 107) return 2;\n        else if(arg < 111) return 1;\n        else if(arg < 114) return 4;\n        else return 100;\n    }\n};\n\n#define CHECK_PROBABILITIES(actual, expected)       \\\n    do {                                            \\\n        std::vector<double> _actual = (actual);     \\\n        std::vector<double> _expected = (expected); \\\n        BOOST_CHECK_EQUAL_COLLECTIONS(              \\\n            _actual.begin(), _actual.end(),         \\\n            _expected.begin(), _expected.end());    \\\n    } while(false)\n\nusing boost::assign::list_of;\n\nBOOST_AUTO_TEST_CASE(test_constructors) {\n    boost::random::discrete_distribution<> dist;\n    CHECK_PROBABILITIES(dist.probabilities(), list_of(1.0));\n\n#ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n    boost::random::discrete_distribution<> dist_il = { 1, 2, 1, 4 };\n    CHECK_PROBABILITIES(dist_il.probabilities(), list_of(.125)(.25)(.125)(.5));\n#endif\n    std::vector<double> probs = boost::assign::list_of(1.0)(2.0)(1.0)(4.0);\n\n    boost::random::discrete_distribution<> dist_r(probs);\n    CHECK_PROBABILITIES(dist_r.probabilities(), list_of(.125)(.25)(.125)(.5));\n    \n    boost::random::discrete_distribution<> dist_it(probs.begin(), probs.end());\n    CHECK_PROBABILITIES(dist_it.probabilities(), list_of(.125)(.25)(.125)(.5));\n    \n    boost::random::discrete_distribution<> dist_fun(4, 99, 115, gen());\n    CHECK_PROBABILITIES(dist_fun.probabilities(), list_of(.125)(.25)(.125)(.5));\n\n    boost::random::discrete_distribution<> copy(dist);\n    BOOST_CHECK_EQUAL(dist, copy);\n    boost::random::discrete_distribution<> copy_r(dist_r);\n    BOOST_CHECK_EQUAL(dist_r, copy_r);\n\n    boost::random::discrete_distribution<> notpow2(3, 99, 111, gen());\n    BOOST_REQUIRE_EQUAL(notpow2.probabilities().size(), 3u);\n    BOOST_CHECK_CLOSE_FRACTION(notpow2.probabilities()[0], 0.25, 0.00000000001);\n    BOOST_CHECK_CLOSE_FRACTION(notpow2.probabilities()[1], 0.50, 0.00000000001);\n    BOOST_CHECK_CLOSE_FRACTION(notpow2.probabilities()[2], 0.25, 0.00000000001);\n    boost::random::discrete_distribution<> copy_notpow2(notpow2);\n    BOOST_CHECK_EQUAL(notpow2, copy_notpow2);\n}\n\nBOOST_AUTO_TEST_CASE(test_param) {\n    std::vector<double> probs = boost::assign::list_of(1.0)(2.0)(1.0)(4.0);\n    boost::random::discrete_distribution<> dist(probs);\n    boost::random::discrete_distribution<>::param_type param = dist.param();\n    CHECK_PROBABILITIES(param.probabilities(), list_of(.125)(.25)(.125)(.5));\n    boost::random::discrete_distribution<> copy1(param);\n    BOOST_CHECK_EQUAL(dist, copy1);\n    boost::random::discrete_distribution<> copy2;\n    copy2.param(param);\n    BOOST_CHECK_EQUAL(dist, copy2);\n\n    boost::random::discrete_distribution<>::param_type param_copy = param;\n    BOOST_CHECK_EQUAL(param, param_copy);\n    BOOST_CHECK(param == param_copy);\n    BOOST_CHECK(!(param != param_copy));\n    boost::random::discrete_distribution<>::param_type param_default;\n    CHECK_PROBABILITIES(param_default.probabilities(), list_of(1.0));\n    BOOST_CHECK(param != param_default);\n    BOOST_CHECK(!(param == param_default));\n    \n#ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n    boost::random::discrete_distribution<>::param_type\n        parm_il = { 1, 2, 1, 4 };\n    CHECK_PROBABILITIES(parm_il.probabilities(), list_of(.125)(.25)(.125)(.5));\n#endif\n\n    boost::random::discrete_distribution<>::param_type parm_r(probs);\n    CHECK_PROBABILITIES(parm_r.probabilities(), list_of(.125)(.25)(.125)(.5));\n    \n    boost::random::discrete_distribution<>::param_type\n        parm_it(probs.begin(), probs.end());\n    CHECK_PROBABILITIES(parm_it.probabilities(), list_of(.125)(.25)(.125)(.5));\n    \n    boost::random::discrete_distribution<>::param_type\n        parm_fun(4, 99, 115, gen());\n    CHECK_PROBABILITIES(parm_fun.probabilities(), list_of(.125)(.25)(.125)(.5));\n}\n\nBOOST_AUTO_TEST_CASE(test_min_max) {\n    std::vector<double> probs = boost::assign::list_of(1.0)(2.0)(1.0);\n    boost::random::discrete_distribution<> dist;\n    BOOST_CHECK_EQUAL((dist.min)(), 0);\n    BOOST_CHECK_EQUAL((dist.max)(), 0);\n    boost::random::discrete_distribution<> dist_r(probs);\n    BOOST_CHECK_EQUAL((dist_r.min)(), 0);\n    BOOST_CHECK_EQUAL((dist_r.max)(), 2);\n}\n\nBOOST_AUTO_TEST_CASE(test_comparison) {\n    std::vector<double> probs = boost::assign::list_of(1.0)(2.0)(1.0)(4.0);\n    boost::random::discrete_distribution<> dist;\n    boost::random::discrete_distribution<> dist_copy(dist);\n    boost::random::discrete_distribution<> dist_r(probs);\n    boost::random::discrete_distribution<> dist_r_copy(dist_r);\n    BOOST_CHECK(dist == dist_copy);\n    BOOST_CHECK(!(dist != dist_copy));\n    BOOST_CHECK(dist_r == dist_r_copy);\n    BOOST_CHECK(!(dist_r != dist_r_copy));\n    BOOST_CHECK(dist != dist_r);\n    BOOST_CHECK(!(dist == dist_r));\n}\n\nBOOST_AUTO_TEST_CASE(test_streaming) {\n    std::vector<double> probs = boost::assign::list_of(1.0)(2.0)(1.0)(4.0);\n    boost::random::discrete_distribution<> dist(probs);\n    std::stringstream stream;\n    stream << dist;\n    boost::random::discrete_distribution<> restored_dist;\n    stream >> restored_dist;\n    BOOST_CHECK_EQUAL(dist, restored_dist);\n}\n\nBOOST_AUTO_TEST_CASE(test_generation) {\n    std::vector<double> probs = boost::assign::list_of(0.0)(1.0);\n    boost::minstd_rand0 gen;\n    boost::random::discrete_distribution<> dist;\n    boost::random::discrete_distribution<> dist_r(probs);\n    for(int i = 0; i < 10; ++i) {\n        int value = dist(gen);\n        BOOST_CHECK_EQUAL(value, 0);\n        int value_r = dist_r(gen);\n        BOOST_CHECK_EQUAL(value_r, 1);\n        int value_param = dist_r(gen, dist.param());\n        BOOST_CHECK_EQUAL(value_param, 0);\n        int value_r_param = dist(gen, dist_r.param());\n        BOOST_CHECK_EQUAL(value_r_param, 1);\n    }\n}\n", "meta": {"hexsha": "1026456a42ddd061fcefc8f6bb9d931534b5ae82", "size": 6640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_discrete_distribution.cpp", "max_stars_repo_name": "HelloSunyi/boost_1_54_0", "max_stars_repo_head_hexsha": "429fea793612f973d4b7a0e69c5af8156ae2b56e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-01-25T05:31:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T01:50:31.000Z", "max_issues_repo_path": "libs/random/test/test_discrete_distribution.cpp", "max_issues_repo_name": "HelloSunyi/boost_1_54_0", "max_issues_repo_head_hexsha": "429fea793612f973d4b7a0e69c5af8156ae2b56e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/random/test/test_discrete_distribution.cpp", "max_forks_repo_name": "HelloSunyi/boost_1_54_0", "max_forks_repo_head_hexsha": "429fea793612f973d4b7a0e69c5af8156ae2b56e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-28T17:38:16.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-30T05:37:32.000Z", "avg_line_length": 39.2899408284, "max_line_length": 80, "alphanum_fraction": 0.6844879518, "num_tokens": 1771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5027106477807213}}
{"text": "/*!\n * @file\n * Forward declares the @ref Monoid typeclass.\n *\n *\n * @copyright Louis Dionne 2014\n * Distributed under the Boost Software License, Version 1.0.\n *         (See accompanying file LICENSE.md or copy at\n *             http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_MPL11_FWD_MONOID_HPP\n#define BOOST_MPL11_FWD_MONOID_HPP\n\n#include <boost/mpl11/fwd/bool.hpp>\n\n\nnamespace boost { namespace mpl11 {\n    /*!\n     * @ingroup typeclasses\n     * @defgroup Monoid Monoid\n     *\n     * The `Monoid` typeclass is used for datatypes with an associative binary\n     * operation that has an identity.\n     *\n     *\n     * Instances of `Monoid` must satisfy the following laws:\n     *\n        @code\n            plus zero x == x\n            plus x zero == x\n            plus x (plus y z) == plus (plus x y) z\n        @endcode\n     *\n     * The method names refer to the monoid of numbers under addition, but\n     * there are many other instances such as sequences under concatenation.\n     * Some datatypes can be viewed as a monoid in more than one way, e.g.\n     * both addition and multiplication on numbers.\n     *\n     *\n     * ### Methods\n     * `plus` and `zero`\n     *\n     * ### Minimal complete definition\n     * All the methods.\n     *\n     * @{\n     */\n    template <typename Left, typename Right = Left, typename = true_>\n    struct Monoid;\n\n    /*!\n     * Associative operation on a `Monoid`.\n     *\n     * `plus` can be invoked with more than two arguments. Specifically,\n     * `plus<x1, x2, xn...>` is equivalent to `plus<plus<x1, x2>, xn...>`.\n     */\n    template <typename x1, typename x2, typename ...xn>\n    struct plus;\n\n    //! Additive identity for the given `Datatype`.\n    template <typename Datatype>\n    struct zero;\n    //! @}\n}} // end namespace boost::mpl11\n\n#endif // !BOOST_MPL11_FWD_MONOID_HPP\n", "meta": {"hexsha": "fb441279bf78b64544d4e8c58c343c0790ba3577", "size": 1837, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/mpl11/fwd/monoid.hpp", "max_stars_repo_name": "ldionne/mpl11", "max_stars_repo_head_hexsha": "927d4339edc0c0cc41fb65ced2bf19d26bcd4a08", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T03:19:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T06:44:12.000Z", "max_issues_repo_path": "include/boost/mpl11/fwd/monoid.hpp", "max_issues_repo_name": "rbock/mpl11", "max_issues_repo_head_hexsha": "7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-27T22:37:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-06T17:42:07.000Z", "max_forks_repo_path": "include/boost/mpl11/fwd/monoid.hpp", "max_forks_repo_name": "rbock/mpl11", "max_forks_repo_head_hexsha": "7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T00:18:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T03:00:49.000Z", "avg_line_length": 27.0147058824, "max_line_length": 78, "alphanum_fraction": 0.6129559064, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5027106429741942}}
{"text": "#include \"declat.h\"\n\n#include <boost/dynamic_bitset.hpp>\n\n#include \"itemsets.h\"\n#include \"verticaldatabase.h\"\n\nusing boost::dynamic_bitset;\nusing std::vector;\n\nstruct Candidate {\n    int last_item;\n    vector<int> diffset;\n    unsigned int support;\n};\n\nvoid declat_recursive(const vector<int>& prefix,\n                      const vector<Candidate>& p,\n                      unsigned int minsup,\n                      FrequentItemsets& result) {\n    auto size = p.size();\n    for (unsigned int i = 0; i < size; ++i) {\n        // take candidate a from p\n        const Candidate& a = p[i];\n        vector<int> itemset_a = prefix;\n        itemset_a.push_back(a.last_item);\n        result[itemset_a] = a.support;\n\n        // look for frequent itemsets with candidate a as prefix\n        vector<Candidate> pa;\n        for (unsigned int j = i+1; j < size; ++j) {\n            // take candidate b from p\n            const Candidate& b = p[j];\n\n            // new candidate ab\n            Candidate ab;\n            ab.last_item = b.last_item;\n            ab.diffset = itemset_without(b.diffset, a.diffset);\n            ab.support = a.support - ab.diffset.size();\n            if (ab.support >= minsup)\n                pa.emplace_back(ab);\n        }\n\n        // recurse!\n        if ( ! pa.empty())\n            declat_recursive(itemset_a, pa, minsup, result);\n    }\n}\n\nFrequentItemsets declat(const VerticalDatabase& d, unsigned int minsup) {\n    // initial candidates: frequent single-item itemsets\n    vector<Candidate> p;\n    int nItems = d.nItems();\n    for (int i = 0; i < nItems; ++i) {\n        dynamic_bitset<> b = d.bs[i];\n        unsigned int support = b.count();\n        if (support >= minsup)\n            p.push_back({i, diffset_for_single_item(b), support});\n    }\n\n    // run algorithm\n    FrequentItemsets result;\n    vector<int> prefix;\n    declat_recursive(prefix, p, minsup, result);\n\n    return result;\n}\n", "meta": {"hexsha": "52b5dc5c4f90e7bfcbf9eeb8b03a3ad7c100499a", "size": 1910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/declat.cpp", "max_stars_repo_name": "lfritz/data-mining-and-analysis", "max_stars_repo_head_hexsha": "f92aba784f2a8a0e8c02f6b8d3adf5bdf884fed7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/declat.cpp", "max_issues_repo_name": "lfritz/data-mining-and-analysis", "max_issues_repo_head_hexsha": "f92aba784f2a8a0e8c02f6b8d3adf5bdf884fed7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/declat.cpp", "max_forks_repo_name": "lfritz/data-mining-and-analysis", "max_forks_repo_head_hexsha": "f92aba784f2a8a0e8c02f6b8d3adf5bdf884fed7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-06T19:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-06T19:20:37.000Z", "avg_line_length": 28.0882352941, "max_line_length": 73, "alphanum_fraction": 0.5764397906, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.5026910835228855}}
{"text": "/*\n * \n * Copyright (c) Kresimir Fresl Toon Knapen 2003\n *\n * Permission to copy, modify, use and distribute this software \n * for any non-commercial or commercial purpose is granted provided \n * that this license appear on all copies of the software source code.\n *\n * Authors assume no responsibility whatsoever for its use and makes \n * no guarantees about its quality, correctness or reliability.\n *\n * KF acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_PPSV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_PPSV_HPP\n\n#include <boost/numeric/bindings/traits/type_traits.hpp>\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/lapack/lapack.h>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/numeric/bindings/traits/detail/symm_herm_traits.hpp>\n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits/is_same.hpp>\n#endif \n\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace lapack {\n\n    /////////////////////////////////////////////////////////////////////\n    //\n    // system of linear equations A * X = B\n    // with A symmetric or Hermitian positive definite matrix\n    // stored in packed format \n    //\n    /////////////////////////////////////////////////////////////////////\n\n    /*\n     * ppsv() computes the solution to a system of linear equations \n     * A * X = B, where A is an N-by-N symmetric or Hermitian positive \n     * definite matrix stored in packed format and X and B are N-by-NRHS \n     * matrices.\n     *\n     * The Cholesky decomposition is used to factor A as\n     *   A = U^T * U or A = U^H * U,  if UPLO = 'U', \n     *   A = L * L^T or A = L * L^H,  if UPLO = 'L',\n     * where U is an upper triangular matrix and L is a lower triangular\n     * matrix. The factored form of A is then used to solve the system of\n     * equations A * X = B.\n     * \n     * Only upper or lower triangle of the symmetric matrix A is stored,  \n     * packed columnwise in a linear array AP. \n     */\n\n    namespace detail {\n\n      inline \n      void ppsv (char const uplo, int const n, int const nrhs,\n                 float* ap, float* b, int const ldb, int* info) \n      {\n        LAPACK_SPPSV (&uplo, &n, &nrhs, ap, b, &ldb, info);\n      }\n\n      inline \n      void ppsv (char const uplo, int const n, int const nrhs,\n                 double* ap, double* b, int const ldb, int* info) \n      {\n        LAPACK_DPPSV (&uplo, &n, &nrhs, ap, b, &ldb, info);\n      }\n\n      inline \n      void ppsv (char const uplo, int const n, int const nrhs,\n                 traits::complex_f* ap, traits::complex_f* b, int const ldb, \n                 int* info) \n      {\n        LAPACK_CPPSV (&uplo, &n, &nrhs, \n                      traits::complex_ptr (ap), \n                      traits::complex_ptr (b), &ldb, info);\n      }\n\n      inline \n      void ppsv (char const uplo, int const n, int const nrhs,\n                 traits::complex_d* ap, traits::complex_d* b, int const ldb, \n                 int* info) \n      {\n        LAPACK_ZPPSV (&uplo, &n, &nrhs, \n                      traits::complex_ptr (ap), \n                      traits::complex_ptr (b), &ldb, info);\n      }\n\n    }\n\n    template <typename SymmMatrA, typename MatrB>\n    inline\n    int ppsv (SymmMatrA& a, MatrB& b) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmMatrA>::matrix_structure,\n        typename traits::detail::symm_herm_pack_t<\n          typename traits::matrix_traits<SymmMatrA>::value_type\n        >::type\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure, \n        traits::general_t\n      >::value));\n#endif\n\n      int const n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a));\n      assert (n == traits::matrix_size1 (b));\n\n      char uplo = traits::matrix_uplo_tag (a);\n      int info; \n      detail::ppsv (uplo, n, traits::matrix_size2 (b),\n                    traits::matrix_storage (a), \n                    traits::matrix_storage (b), \n                    traits::leading_dimension (b), \n                    &info);\n      return info; \n    }\n\n\n    /*\n     * pptrf() computes the Cholesky factorization of a symmetric\n     * or Hermitian positive definite matrix A in packed storage. \n     * The factorization has the form\n     *   A = U^T * U or A = U^H * U,  if UPLO = 'U', \n     *   A = L * L^T or A = L * L^H,  if UPLO = 'L',\n     * where U is an upper triangular matrix and L is lower triangular.\n     */\n\n    namespace detail {\n\n      inline \n      void pptrf (char const uplo, int const n, float* ap, int* info) {\n        LAPACK_SPPTRF (&uplo, &n, ap, info);\n      }\n\n      inline \n      void pptrf (char const uplo, int const n, double* ap, int* info) {\n        LAPACK_DPPTRF (&uplo, &n, ap, info);\n      }\n\n      inline \n      void pptrf (char const uplo, int const n, \n                  traits::complex_f* ap, int* info) \n      {\n        LAPACK_CPPTRF (&uplo, &n, traits::complex_ptr (ap), info);\n      }\n\n      inline \n      void pptrf (char const uplo, int const n, \n                  traits::complex_d* ap, int* info) \n      {\n        LAPACK_ZPPTRF (&uplo, &n, traits::complex_ptr (ap), info);\n      }\n\n    }\n\n    template <typename SymmMatrA>\n    inline\n    int pptrf (SymmMatrA& a) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmMatrA>::matrix_structure,\n        typename traits::detail::symm_herm_pack_t<\n          typename traits::matrix_traits<SymmMatrA>::value_type\n        >::type\n      >::value));\n#endif\n\n      int const n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a));\n      char uplo = traits::matrix_uplo_tag (a);\n      int info; \n      detail::pptrf (uplo, n, traits::matrix_storage (a), &info);\n      return info; \n    }\n\n\n    /*\n     * pptrs() solves a system of linear equations A*X = B with \n     * a symmetric or Hermitian positive definite matrix A in packed \n     * storage using the Cholesky factorization computed by pptrf().\n     */\n\n    namespace detail {\n\n      inline \n      void pptrs (char const uplo, int const n, int const nrhs,\n                  float const* ap, float* b, int const ldb, int* info) \n      {\n        LAPACK_SPPTRS (&uplo, &n, &nrhs, ap, b, &ldb, info);\n      }\n\n      inline \n      void pptrs (char const uplo, int const n, int const nrhs,\n                  double const* ap, double* b, int const ldb, int* info) \n      {\n        LAPACK_DPPTRS (&uplo, &n, &nrhs, ap, b, &ldb, info);\n      }\n\n      inline \n      void pptrs (char const uplo, int const n, int const nrhs,\n                  traits::complex_f const* ap, \n                  traits::complex_f* b, int const ldb, int* info) \n      {\n        LAPACK_CPPTRS (&uplo, &n, &nrhs, \n                       traits::complex_ptr (ap), \n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n      inline \n      void pptrs (char const uplo, int const n, int const nrhs,\n                  traits::complex_d const* ap, \n                  traits::complex_d* b, int const ldb, int* info) \n      {\n        LAPACK_ZPPTRS (&uplo, &n, &nrhs, \n                       traits::complex_ptr (ap), \n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n    }\n\n    template <typename SymmMatrA, typename MatrB>\n    inline\n    int pptrs (SymmMatrA const& a, MatrB& b) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmMatrA>::matrix_structure,\n        typename traits::detail::symm_herm_pack_t<\n          typename traits::matrix_traits<SymmMatrA>::value_type\n        >::type\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure, \n        traits::general_t\n      >::value));\n#endif\n\n      int const n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a));\n      assert (n == traits::matrix_size1 (b));\n      \n      char uplo = traits::matrix_uplo_tag (a);\n      int info; \n      detail::pptrs (uplo, n, traits::matrix_size2 (b),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                     traits::matrix_storage (a), \n#else\n                     traits::matrix_storage_const (a), \n#endif \n                     traits::matrix_storage (b), \n                     traits::leading_dimension (b), \n                     &info);\n      return info; \n    }\n\n    // TO DO: pptri() \n\n  }\n\n}}}\n\n#endif \n", "meta": {"hexsha": "61bd0ece1a3e46f2c437daf720a7bea9ed937f84", "size": 8672, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/lapack/ppsv.hpp", "max_stars_repo_name": "jiaqiwang969/Kratos-test", "max_stars_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "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": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/lapack/ppsv.hpp", "max_issues_repo_name": "jiaqiwang969/Kratos-test", "max_issues_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "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": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/lapack/ppsv.hpp", "max_forks_repo_name": "jiaqiwang969/Kratos-test", "max_forks_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "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": 31.5345454545, "max_line_length": 77, "alphanum_fraction": 0.5766835793, "num_tokens": 2289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5026910784055145}}
{"text": "#include <gtest/gtest.h>\n#include <stan/math/prim/mat.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <test/unit/math/prim/scal/prob/util.hpp>\n#include <limits>\n#include <vector>\n\nusing stan::math::bernoulli_logit_glm_rng;\n\nTEST(ProbDistributionsBernoulliLogitGlm, vectorized) {\n  //  Test scalar/vector combinations.\n  boost::random::mt19937 rng;\n\n  Eigen::MatrixXd x(2, 3);\n  x << 3.5, -1.5, 0.0, 2.0, 1.0, 3.0;\n\n  double alpha_scalar = 1.0;\n  std::vector<double> alpha{1.0, 3.0};\n  Eigen::VectorXd alpha_vector(2);\n  alpha_vector << 1.0, 3.0;\n  Eigen::RowVectorXd alpha_vector_t(2);\n  alpha_vector_t = alpha_vector;\n\n  double beta_scalar = 2.0;\n  std::vector<double> beta{2.0, 4.5, -1.0};\n  Eigen::VectorXd beta_vector(3);\n  beta_vector << 2.0, 4.5, -1.0;\n  Eigen::RowVectorXd beta_vector_t(3);\n  beta_vector_t = beta_vector;\n\n  // Can't use VectorRNGTestRig since length(alpha) != length(beta) in general.\n\n  EXPECT_NO_THROW(stan::math::bernoulli_logit_glm_rng(x, alpha, beta, rng));\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha_scalar, beta, rng));\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha_vector, beta, rng));\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha_vector_t, beta, rng));\n\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha, beta_scalar, rng));\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha_scalar, beta_scalar, rng));\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha_vector, beta_scalar, rng));\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha_vector_t, beta_scalar, rng));\n\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha, beta_vector, rng));\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha_scalar, beta_vector, rng));\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha_vector, beta_vector, rng));\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha_vector_t, beta_vector, rng));\n\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha, beta_vector_t, rng));\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha_scalar, beta_vector_t, rng));\n  EXPECT_NO_THROW(\n      stan::math::bernoulli_logit_glm_rng(x, alpha_vector, beta_vector_t, rng));\n  EXPECT_NO_THROW(stan::math::bernoulli_logit_glm_rng(x, alpha_vector_t,\n                                                      beta_vector_t, rng));\n}\n\nTEST(ProbDistributionsBernoulliLogitGlm, errorCheck) {\n  // Check errors for nonfinite and wrong sizes.\n  boost::random::mt19937 rng;\n\n  int N = 3;\n  int M = 2;\n  int W = 4;\n\n  Eigen::MatrixXd x = Eigen::MatrixXd::Random(N, M);\n  Eigen::MatrixXd xw1 = Eigen::MatrixXd::Random(W, M);\n  Eigen::MatrixXd xw2 = Eigen::MatrixXd::Random(N, W);\n  Eigen::MatrixXd xw3 = Eigen::MatrixXd::Random(N, M) * NAN;\n  Eigen::VectorXd alpha = Eigen::VectorXd::Random(N, 1);\n  Eigen::VectorXd alphaw1 = Eigen::VectorXd::Random(W, 1);\n  Eigen::VectorXd alphaw2 = Eigen::VectorXd::Random(N, 1) * NAN;\n  Eigen::VectorXd beta = Eigen::VectorXd::Random(M, 1);\n  Eigen::VectorXd betaw1 = Eigen::VectorXd::Random(W, 1);\n  Eigen::VectorXd betaw2 = Eigen::VectorXd::Random(M, 1) * NAN;\n\n  EXPECT_NO_THROW(stan::math::bernoulli_logit_glm_rng(x, alpha, beta, rng));\n  EXPECT_THROW(stan::math::bernoulli_logit_glm_rng(xw1, alpha, beta, rng),\n               std::invalid_argument);\n  EXPECT_THROW(stan::math::bernoulli_logit_glm_rng(xw2, alpha, beta, rng),\n               std::invalid_argument);\n  EXPECT_THROW(stan::math::bernoulli_logit_glm_rng(xw3, alpha, beta, rng),\n               std::domain_error);\n  EXPECT_THROW(stan::math::bernoulli_logit_glm_rng(x, alphaw1, beta, rng),\n               std::invalid_argument);\n  EXPECT_THROW(stan::math::bernoulli_logit_glm_rng(x, alphaw2, beta, rng),\n               std::domain_error);\n  EXPECT_THROW(stan::math::bernoulli_logit_glm_rng(x, alpha, betaw1, rng),\n               std::invalid_argument);\n  EXPECT_THROW(stan::math::bernoulli_logit_glm_rng(x, alpha, betaw2, rng),\n               std::domain_error);\n}\n\nTEST(ProbDistributionsBernoulliLogitGlm, marginalChiSquareGoodnessFitTest) {\n  // Check distribution of result.\n  boost::random::mt19937 rng;\n  Eigen::MatrixXd x(2, 2);\n  x << 3.5, -1.5, 2.0, -1.2;\n  std::vector<double> alpha{2.0, 1.0};\n  std::vector<double> beta{2.0, 4.5};\n\n  //  sage: x = matrix([[3.5, -1.5], [2.0, -1.2]])\n  //  sage: alpha = matrix([[2.0], [1.0]])\n  //  sage: beta = matrix([[2.0], [4.5]])\n  //  sage: z = alpha + x * beta\n  //  sage: z\n  //\n  //  [  2.25000000000000]\n  //  [-0.399999999999999]\n  //  sage: p1 = 1 / (1 + e**(-z[0][0]))\n  //  sage: p2 = 1 / (1 + e**(-z[1][0]))\n  //  sage: p1\n  //  0.904650535100891\n  //  sage: p2\n  //  0.401312339887548\n\n  double p1 = 0.904650535100891;\n  double p2 = 0.401312339887548;\n\n  int N = 10000;\n\n  // First bin is failures, second is successes. Take N samples, take\n  // their first component. Should be (1 - p1) * N failures in the\n  // first bin, or thereabouts. Now take their second\n  // component. Should be (1 - p2) * N failures in the first bin.\n  std::vector<double> bin_boundaries{0.1, 1.1};\n  std::vector<double> proportions1{(1 - p1), p1};\n  std::vector<double> proportions2{(1 - p2), p2};\n\n  std::vector<double> samples1;\n  std::vector<double> samples2;\n  for (int i = 0; i < N; ++i) {\n    std::vector<int> sample\n        = stan::math::bernoulli_logit_glm_rng(x, alpha, beta, rng);\n    samples1.push_back(sample[0]);\n    samples2.push_back(sample[1]);\n  }\n\n  assert_matches_bins(samples1, bin_boundaries, proportions1, 1e-6);\n  assert_matches_bins(samples2, bin_boundaries, proportions2, 1e-6);\n}\n", "meta": {"hexsha": "f5188394df5df4180eb9780c6dd5687de7cf7f70", "size": 5738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/mat/prob/bernoulli_logit_glm_rng_test.cpp", "max_stars_repo_name": "riddell-stan/math", "max_stars_repo_head_hexsha": "d84ee0d991400d6cf4b08a07a4e8d86e0651baea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T14:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-23T14:57:41.000Z", "max_issues_repo_path": "test/unit/math/prim/mat/prob/bernoulli_logit_glm_rng_test.cpp", "max_issues_repo_name": "Capri2014/math", "max_issues_repo_head_hexsha": "d4042bdf8623bba5a1633b557227325a324e32e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-23T19:58:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T12:03:41.000Z", "max_forks_repo_path": "test/unit/math/prim/mat/prob/bernoulli_logit_glm_rng_test.cpp", "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": 37.2597402597, "max_line_length": 80, "alphanum_fraction": 0.676019519, "num_tokens": 1846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5026910764362149}}
{"text": "/**\n * @file nmf_test.cpp\n * @author Mohan Rajendran\n *\n * Test file for NMF class.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/amf/amf.hpp>\n#include <mlpack/methods/amf/init_rules/random_acol_init.hpp>\n#include <mlpack/methods/amf/update_rules/nmf_mult_div.hpp>\n#include <mlpack/methods/amf/update_rules/nmf_als.hpp>\n#include <mlpack/methods/amf/update_rules/nmf_mult_dist.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nBOOST_AUTO_TEST_SUITE(NMFTest);\n\nusing namespace std;\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::amf;\n\n/**\n * Check the if the product of the calculated factorization is close to the\n * input matrix. Default case.\n */\nBOOST_AUTO_TEST_CASE(NMFDefaultTest)\n{\n  mat w = randu<mat>(20, 12);\n  mat h = randu<mat>(12, 20);\n  mat v = w * h;\n  size_t r = 12;\n\n  AMF<> nmf;\n  nmf.Apply(v, r, w, h);\n\n  mat wh = w * h;\n\n  // Make sure reconstruction error is not too high.  5.0% tolerance.\n  BOOST_REQUIRE_SMALL(arma::norm(v - wh, \"fro\") / arma::norm(v, \"fro\"),\n      0.05);\n}\n\n/**\n * Check the if the product of the calculated factorization is close to the\n * input matrix. Random Acol initialization distance minimization update.\n */\nBOOST_AUTO_TEST_CASE(NMFAcolDistTest)\n{\n  mat w = randu<mat>(20, 12);\n  mat h = randu<mat>(12, 20);\n  mat v = w * h;\n  const size_t r = 12;\n\n  SimpleResidueTermination srt(1e-7, 10000);\n  AMF<SimpleResidueTermination,RandomAcolInitialization<> >\n        nmf(srt);\n  nmf.Apply(v, r, w, h);\n\n  mat wh = w * h;\n\n  BOOST_REQUIRE_SMALL(arma::norm(v - wh, \"fro\") / arma::norm(v, \"fro\"),\n      0.015);\n}\n\n/**\n * Check the if the product of the calculated factorization is close to the\n * input matrix. Random initialization divergence minimization update.\n */\nBOOST_AUTO_TEST_CASE(NMFRandomDivTest)\n{\n  mat w = randu<mat>(20, 12);\n  mat h = randu<mat>(12, 20);\n  mat v = w * h;\n  size_t r = 12;\n\n  // Custom tighter tolerance.\n  SimpleResidueTermination srt(1e-8, 10000);\n  AMF<SimpleResidueTermination,\n      RandomInitialization,\n      NMFMultiplicativeDivergenceUpdate> nmf(srt);\n  nmf.Apply(v, r, w, h);\n\n  mat wh = w * h;\n\n  // Make sure reconstruction error is not too high.  1.5% tolerance.\n  BOOST_REQUIRE_SMALL(arma::norm(v - wh, \"fro\") / arma::norm(v, \"fro\"),\n      0.015);\n}\n\n/**\n * Check that the product of the calculated factorization is close to the\n * input matrix.  This uses the random initialization and alternating least\n * squares update rule.\n */\nBOOST_AUTO_TEST_CASE(NMFALSTest)\n{\n  mat w = randu<mat>(20, 12);\n  mat h = randu<mat>(12, 20);\n  mat v = w * h;\n  size_t r = 12;\n\n  SimpleResidueTermination srt(1e-12, 50000);\n  AMF<SimpleResidueTermination, RandomAcolInitialization<>, NMFALSUpdate>\n        nmf(srt);\n  nmf.Apply(v, r, w, h);\n\n  const mat wh = w * h;\n\n  // Make sure reconstruction error is not too high.  8% tolerance.  It seems\n  // like ALS doesn't converge to results that are as good.  It also seems to be\n  // particularly sensitive to initial conditions.\n  BOOST_REQUIRE_SMALL(arma::norm(v - wh, \"fro\") / arma::norm(v, \"fro\"),\n      0.08);\n}\n\n/**\n * Check the if the product of the calculated factorization is close to the\n * input matrix, with a sparse input matrix. Random Acol initialization,\n * distance minimization update.\n */\nBOOST_AUTO_TEST_CASE(SparseNMFAcolDistTest)\n{\n  // We have to ensure that the residues aren't NaNs.  This can happen when a\n  // matrix is created with all zeros in a column or row.\n  double denseResidue = std::numeric_limits<double>::quiet_NaN();\n  double sparseResidue = std::numeric_limits<double>::quiet_NaN();\n\n  mat vp, dvp; // Resulting matrices.\n\n  while (sparseResidue != sparseResidue && denseResidue != denseResidue)\n  {\n    mlpack::math::RandomSeed(std::time(NULL));\n    mat w, h;\n    sp_mat v;\n    v.sprandu(20, 20, 0.3);\n    // Ensure there is at least one nonzero element in every row and column.\n    for (size_t i = 0; i < 20; ++i)\n      v(i, i) += 1e-5;\n    mat dv(v); // Make a dense copy.\n    mat dw, dh;\n    size_t r = 15;\n\n    SimpleResidueTermination srt(1e-10, 10000);\n    AMF<SimpleResidueTermination, RandomAcolInitialization<> > nmf(srt);\n    const size_t seed = mlpack::math::RandInt(1000000);\n    mlpack::math::RandomSeed(seed); // Set random seed so results are the same.\n    nmf.Apply(v, r, w, h);\n    mlpack::math::RandomSeed(seed);\n    nmf.Apply(dv, r, dw, dh);\n\n    // Reconstruct matrices.\n    vp = w * h;\n    dvp = dw * dh;\n\n    denseResidue = arma::norm(v - vp, \"fro\");\n    sparseResidue = arma::norm(dv - dvp, \"fro\");\n  }\n\n  // Make sure the results are about equal for the W and H matrices.\n  BOOST_REQUIRE_SMALL(arma::norm(vp - dvp, \"fro\") / arma::norm(vp, \"fro\"),\n      1e-5);\n}\n\n/**\n * Check that the product of the calculated factorization is close to the\n * input matrix, with a sparse input matrix.  This uses the random\n * initialization and alternating least squares update rule.\n */\nBOOST_AUTO_TEST_CASE(SparseNMFALSTest)\n{\n  // We have to ensure that the residues aren't NaNs.  This can happen when a\n  // matrix is created with all zeros in a column or row.\n  double denseResidue = std::numeric_limits<double>::quiet_NaN();\n  double sparseResidue = std::numeric_limits<double>::quiet_NaN();\n\n  mat vp, dvp; // Resulting matrices.\n\n  while (sparseResidue != sparseResidue && denseResidue != denseResidue)\n  {\n    mlpack::math::RandomSeed(std::time(NULL));\n    mat w, h;\n    sp_mat v;\n    v.sprandu(10, 10, 0.3);\n    // Ensure there is at least one nonzero element in every row and column.\n    for (size_t i = 0; i < 10; ++i)\n      v(i, i) += 1e-5;\n    mat dv(v); // Make a dense copy.\n    mat dw, dh;\n    size_t r = 5;\n\n    SimpleResidueTermination srt(1e-10, 10000);\n    AMF<SimpleResidueTermination, RandomInitialization, NMFALSUpdate> nmf(srt);\n    const size_t seed = mlpack::math::RandInt(1000000);\n    mlpack::math::RandomSeed(seed);\n    nmf.Apply(v, r, w, h);\n    mlpack::math::RandomSeed(seed);\n    nmf.Apply(dv, r, dw, dh);\n\n    // Reconstruct matrices.\n    vp = w * h; // In general vp won't be sparse.\n    dvp = dw * dh;\n\n    denseResidue = arma::norm(v - vp, \"fro\");\n    sparseResidue = arma::norm(dv - dvp, \"fro\");\n  }\n\n  // Make sure the results are about equal for the W and H matrices.\n  BOOST_REQUIRE_SMALL(arma::norm(vp - dvp, \"fro\") / arma::norm(vp, \"fro\"),\n      1e-5);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "605ce39acc014b19ad337a200e339637a5019c32", "size": 6363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/nmf_test.cpp", "max_stars_repo_name": "vj-ug/Contribution-to-mlpack", "max_stars_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T11:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:20.000Z", "max_issues_repo_path": "src/mlpack/tests/nmf_test.cpp", "max_issues_repo_name": "vj-ug/Contribution-to-mlpack", "max_issues_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/nmf_test.cpp", "max_forks_repo_name": "vj-ug/Contribution-to-mlpack", "max_forks_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "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.5953488372, "max_line_length": 80, "alphanum_fraction": 0.672795851, "num_tokens": 1925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5026910764362149}}
{"text": "#pragma once\n\n#include \"Base/TQuaternion.h\"\n\n#include <boost/bind.hpp>\n\n#include \"vector.hpp\"\n#include \"gmres.hpp\"\n#include \"integrate.hpp\"\n\ntemplate<int DIMX, int DIMUC>\nclass Model{\npublic:\n\tstatic const int DimX = DIMX;\n\tstatic const int DimU = DIMUC;\n\n\tusing x_t = vector_t<DIMX>;\t\t///< Vector for a state vector\n    using u_t =  vector_t<DIMUC>;\t///< Vector for a control input\n\tstruct xu_t : vector_t<DIMX + DIMUC>{\t///< Integrated structure for x and u\n\tx_t& x(){ return *(x_t*)this; }\n\tu_t& u(){ return *(u_t*)((double*)this + DIMX); }\n\tconst x_t& x()const{ return *(const x_t*)this; }\n\tconst u_t& u()const{ return *(const u_t*)((const double*)this + DIMX); }\n\t};\n\n\tx_t    x0;\t\t///< Initial state\n\tu_t    u0;\t\t///< Initial input\n\n\tx_t    x;\t\t///< Current state\n\tx_t    x1;\t\t///< State in next step\n\tu_t    u;\t\t///< Control input\n\n\t/*-------------- dPhi/dx -------------- */\n\tvirtual void phix(double t, const x_t& x, x_t& phx1) = 0;\n\n\t/*-------------- State Equation -------------- */\n\tvirtual void xpfunc(double t, const x_t& x, const u_t& u, x_t& xprime) = 0;\n\n\t/*-------------- Costate Equation -------------- */\n\tvirtual void lpfunc(double t, const x_t& lmd, const xu_t& linp, x_t& lprime) = 0; \n\n\t/*-------------- Error in Optimality Condition, Hu -------------- */\n\tvirtual void hufunc(double t, const x_t& x, const x_t& lmd, const u_t& u, u_t& hui) = 0;\n};\n\ntemplate<class MODEL, int N, int KMAX>\nclass Controller{\npublic:\n\tstatic const int DimX = MODEL::DimX;\t//< Dimension of state vector\n\tstatic const int DimU = MODEL::DimU;\t//< Dimension of control input\n\tstatic const int dv   = N;\t\t\t\t//< Number of steps in prediction horizon\n\tstatic const int kmax = KMAX;\t\t\t//< Iteration number of FDGMRES\n\n\tusing controller_t = Controller<MODEL, N, KMAX>;\n\tusing model_t = MODEL;\n    using x_t = typename MODEL::x_t;\n    using u_t = typename MODEL::u_t;\n    using xu_t = typename MODEL::xu_t;\n\n\t/// State sequence\n\tstruct X_t : vector_t<DimX * (N+1)>{\t\n\t\ttemplate<class T> X_t& operator=(const T& v){ assign(v); return *this; }\n\t\tx_t& elem(int i){ return ((x_t*)this)[i]; }\n\t\tconst x_t& elem(int i)const{ return ((const x_t*)this)[i]; }\n\t};\n\t/// Control input sequence\n\tstruct U_t : vector_t<DimU * N>{\n\t\ttemplate<class T> U_t& operator=(const T& v){ this->assign(v); return *this; }\n\t\tu_t& elem(int i){ return ((u_t*)this)[i]; }\n\t\tconst u_t& elem(int i)const { return ((const u_t*)this)[i]; }\n\t};\n\n\tdouble tf;\t\t//< Prediction time\n\tdouble ht;\t\t//< Control period\n\tdouble alpha;\t//< Time constant in case of time-dependent horizon(?)\n\tdouble zeta;\t//< Feedback gain in Eq.9\n\tdouble hdir;\t//< h in Eq.11\n\tdouble rtol;\t//< Tolerance on r for calculating the initial control input\n\tint    dstep;\t//< ?\n\n\tdouble htau;\t//< Period in prediction horizon (=tf/dv)\n\tdouble onemhdir;\t//< 1-hdir\n\tdouble hdirbht;\t\t//< hdir/ht\n\tdouble onemzetahdir; \t//< 1-zeta*hdir\n\tdouble ts;\t\t//< t+hdir\n\tdouble tauf;\t//< Compensated prediction time in prediction horizon\n\n\tx_t x1s;\n\tx_t\tlmd0;\n\tu_t hu0;\n\tX_t xtau;\n\tX_t xtau1;\n\tX_t ltau;\n\tU_t duvec;\n\tU_t utau;\n\tU_t utau1;\n\tU_t hutau;\n\tU_t hutau1;\n\tU_t hutau2;\n\tU_t bvec;\n\t//U_t dutmp;\n\tU_t utautmp;\n\t//U_t ptau; //< PrARX\u30e2\u30c7\u30eb\u306e\u30e2\u30fc\u30c9\u51fa\u529b\u7528\u3000@2018.07.13\n\t\n\tvector_t<dv  +1> tau; \n\tvector_t<kmax+1> errvec;\n\n\tmodel_t*\tmodel;\n\npublic:\n\t// Constructor\n\tController(){}\n\tController(\n               double in_ht,\n               double in_zeta,\n               double in_hdir,\n               double in_tf,\n               double in_alpha,\n               double in_rtol,\n               int in_dstep):\n            ht(in_ht), tf(in_tf), alpha(in_alpha),\n            zeta(in_zeta), hdir(in_hdir),\n            rtol(in_rtol), dstep(in_dstep) {}\n\n\t/*-------------- Initial Conditions -------------- */\n\t/*struct dhu0func{\n\t\tvoid operator()(const u_t& du0, u_t& dhu){\n\t\t\tu_t u;\n\t\t\tu_t hu;\n\n\t\t\tu = *(u_t*)u0 + hdir * du0;\n\t\t\thufunc(tsim0, x0, lmd0, u, hu);\n\t\t\tdhu = (hu - hu0) / hdir;\n\t\t}\n\t};*/\n\n\tvoid init(model_t* m){\n\t\tmodel = m;\n\n\t\tonemhdir     = 1 - hdir / ht;\n\t\thdirbht      = hdir / ht;\n\t\tonemzetahdir = 1 - zeta * hdir;\n\t\n\t\tint i;\n\t\t//double r;\n\t\tvector_t<DimU>   b;\n\t\tvector_t<DimU>   du0;\n\t\tvector_t<DimU+1> erru0;\n\t\tmodel->x = model->x0;\n\t\t// phi_x(x, t)\n\t\tmodel->phix(tsim0, model->x0, lmd0);\n\t\t// Hu( \n\t\tmodel->hufunc(tsim0, model->x0, lmd0, model->u0, hu0);\n\t\t/*\n\t\tdu0.clear();\n\t\tr = hu0.norm();\n\t\ti = 0;\n\n\t\t// 0\u30b9\u30c6\u30c3\u30d7\u306e\u6700\u9069\u5316\u554f\u984c\u3092\u89e3\u304d\uff0c\u6700\u9069\u5165\u529bu0\u3092\u6c42\u3081\u308b\n\t\twhile( r > rtol && i < 100 ){\n\t\t\tb = -hu0;\n\t\t\tnfgmres<dhu0func, u_t, DIMUC>(b, du0, erru0);\n\t\t\t*(u_t*)u0 += du0;\n\t\t\thufunc(tsim0, x0, lmd0, u0, hu0);\n\t\t\tr = hu0.norm();\n\t\t\ti++;\n\t\t}\n\t\t*/\n\t\t// \u5168\u6642\u523b\u306eu\u3092u0\u3067\u57cb\u3081\u308b\n\t\tmodel->u = model->u0;\n\t\tfor(i=0; i<dv; i++){\n\t\t\tutau .elem(i) = model->u;\n\t\t\thutau.elem(i) = hu0;\n\t\t}\n\t\tduvec.clear();\n\t}\n\n\n\t/*-------------- Control Update -------------- */\n\n\t// F(U,x,t)\n\tvoid errfunc(double t, const x_t& x, const U_t& u, U_t& hu)\n\t{\n\t\tint i;\n\t\tdouble taut;\n\t\txu_t linp;\n\n\t\t// Time period in prediction horizon\n\t\t//tauf = tf * (1.0 - exp(-alpha * t));\n\t\ttauf = tf;\n\t\thtau = tauf / dv;\n\n\t\t// Fill the initial state with x given\n\t\txtau.elem(0) = x;\n\t\n\t\t// Calculate state sequence by recursive forward difference calculation(Eq.(1)\uff09\n\t\tx_t xd;\n\t\t//u_t pd;\n\t\tfor(taut = t, i=0; i < dv; taut += htau, i++){\n\t\t\tmodel->xpfunc(taut, xtau.elem(i), u.elem(i), xd);\n\t\t\t//model->xpfunc(taut, xtau.elem(i), u.elem(i), xd, pd);\n\t\t\txtau.elem(i+1) = xtau.elem(i) + htau * xd;\n\t\t\ttau[i] = taut; \n\t\t\t//ptau.elem(i) = pd;\n\t\t}\n\t\ttau[i] = taut; \n\n\t\t// Final condition on the costate lambda\uff08Eq.(7)\uff09\n\t\tmodel->phix(taut, xtau.elem(dv), ltau.elem(dv));\n\n\t\t// Calculate costate sequence by recursive backward difference calculation\uff08Eq.(6)\uff09\n\t\tx_t ld;\n\t\tfor(i = dv-1; i >= 0; i--){\n\t\t\tlinp.x() = xtau.elem(i);\n\t\t\tlinp.u() = u.elem(i);\n\t\t\tmodel->lpfunc(taut, ltau.elem(i+1), linp, ld);\n\t\t\tltau.elem(i) = ltau.elem(i+1) - htau * ld; \n\t\t\ttaut -= htau; \n\t\t\t// Calculate Hu from predicted x and lambda\uff08Eq.(5)\uff09\n\t\t\tmodel->hufunc(taut, xtau.elem(i), ltau.elem(i+1), ((U_t&)u).elem(i), hu.elem(i)); \n\t\t}\n\t}\n\n\tvoid adufunc(const U_t& du, U_t& adu){\n\t\t// U + h dU\n\t\tutau1 = utau + du * hdir;\n\t\t// F(U + hdU, x + h xd, t + h)\n\t\terrfunc(ts, x1s, utau1, hutau2);\n\t\t// F_U dU approx [F(U + h dU, x + h xd, t + h) - F(U, x + h xd, t + h)] / h\n\t\tadu = (hutau2 - hutau1) / hdir;\n\t}\n\tstruct call_adufunc{\n\t\tcontroller_t* ctrl;\n\t\tvoid operator()(const U_t& du, U_t& adu){\n\t\t\tctrl->adufunc(du, adu);\n\t\t}\n\t\tcall_adufunc(controller_t* c):ctrl(c){}\n\t};\n\n\tvoid unew(double t, const x_t& x, const x_t& x1, u_t& u){\n\t\t// t + h\n\t\tts = t + hdir;\n\t\t\n\t\t //\u524d\u9032\u5dee\u5206\u8a08\u7b97\u306e\u305f\u3081\u306bx\u306e\u6642\u9593\u5fae\u5206xd\u304c\u5fc5\u8981\u3060\u304c\uff0c\u5b9f\u969b\u306e\u8a08\u7b97\u3067\u306fxd\u3092\u6c42\u3081\u306a\u3044\u305f\u3081\uff0c\u3053\u3053\u3067\u5dee\u5206\u3067\u8fd1\u4f3c\u3057\u3066\u3044\u308b\n\t\t //xd = (x1 - x) / dt\n\t\t //x1s = x + h xd = x + (x1 - x) * (h/dt) = (h/dt) x1 + (1 - h/dt) x\n\t\tx1s = hdirbht * x1 + x * onemhdir;\n\t\t\n\t\t// F(t, x, u)\n\t\terrfunc(t, x, utau, hutau);\n\n\t\t// F(t + h, x + h xd, u)\n\t\terrfunc(ts, x1s, utau, hutau1);\n\t\t\n\t\t////< x1s = x1 + h xd = x1 + (x1 - x) * (h/dt) = -(h/dt)x + (1 + h/dt)x1 \n\t\t//x1s = -hdirbht * x + x1 * onephdir;\n\n\t\t//// F(t, x1, u)\n\t\t//errfunc(ts, x1, utau, hutau);\n\n\t\t//// F(t + h, x1 + h xd, u)\n\t\t//errfunc(t, x1s, utau, hutau1);\n\n\t\t// b on Eq.(11)\n\t\t// b = As F(U,x,t) - DhF(U,x,t:0,xd,1),\n\t\t// From DhF(U,x,t:0,xd,1) = (F(U, x + h xd, t+h) - F(U,x,t))/h,\n\t\t// b = [(1 + h As) F(U,x,t) - F(U, x + h xd, t+h)] / h\n\t\tbvec = (hutau * onemzetahdir - hutau1) / hdir;\n\n\t\t// Solve F_U Ud = b by GMRES\n\t\t// adufunc is a function that gives A*dU while A is F_U here.\n\t\tnfgmres<call_adufunc, U_t, kmax>(call_adufunc(this), bvec, duvec, errvec);\n\t\t\n\t\t// U += dU * ht;\n\t\tutau += ht * duvec;\n\n\t\t// Limit the control inputs with upper and lower bound\n\t\tfor(int i = 0; i < N; i++)for(int j = 0; j < model->NCar; j++){\n\t\t\tif(utau.elem(i)[j] > model->umax){\n\t\t\t\t\tutau.elem(i)[j] = model->umax;\n\t\t\t}\n\t\t\telse if(utau.elem(i)[j] < model->umin){\n\t\t\t\t\tutau.elem(i)[j] = model->umin;\n\t\t\t}\n\t\t\tduvec = (utau - utautmp)/ht;\n\t\t}\n\t\terrfunc(t,x1,utau,hutau1);\n\t\t\n\t\t//double lim = 1000;\n\t\t//if(abs(hutau1.norm()) > lim){\n\t\t//for(int i = 0; i < N; i++)for(int j = 0; j < modeltmp.NCar; j++){\n\t\t//\tif(xtau.elem(i)[3*j+0] <= modeltmp.Dmin+0.1){\n\t\t//\t\tutau.elem(i)[j] *= utau.elem(i)[j]>0?0.1:1.5;\n\t\t//\t\t//if(utau.elem(i)[j] < modeltmp.umin[j]) utau.elem(i)[j] = modeltmp.umin[j];\n\t\t//\t\t//utau.elem(i)[j] = modeltmp.umin[j];\n\t\t//\t}\n\t\t//\tif(xtau.elem(i)[3*j+0] >= modeltmp.Dmin && abs(utau.elem(i)[2*modeltmp.NCar + j])>lim){\n\t\t//\t\tutau.elem(i)[1*modeltmp.NCar+j] = sqrt(xtau.elem(i)[3*j+0]-modeltmp.Dmin);\t\n\t\t//\t\tutau.elem(i)[2*modeltmp.NCar+j] = modeltmp.s1[j]/(2*modeltmp.sc[j]*utau.elem(i)[1*modeltmp.NCar+j]);\n\t\t//\t}\n\t\t//}\n\t\t//duvec = (utau - utautmp)/ht;\n\t\t//errfunc(t,x1,utau,hutau1);\n\t\t//}\n\n\t\t//// \u3082\u3057\u66f4\u65b0\u3057\u305futau\u3067\u306ehutau\u304c\u66f4\u65b0\u524d\u3088\u308a\u60aa\u5316\u3057\u305f\u5834\u5408\u306f\u623b\u3059\n\t\t//if(hutau1.norm() > hutau.norm()){\n\t\t//\tutau = utautmp;\n\t\t//\tduvec = (utau-utautmp)/ht;\n\t\t//\terrfunc(t,x1,utau,hutau1);\n\t\t//}\n\n\t\t// Apply the first elements of U as actual input u\n\t\tu = utau.elem(0);\n\t\tutautmp = utau;\n\t\t//dutmp = duvec;\n\t}\n\n\tprivate:\n        const double tsim0 = 0.0;\n};\n", "meta": {"hexsha": "2caeb8df1a43988970a188a5317ca391a3cd8f24", "size": 8882, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cacc/packages/common/cgmres_lib/include/cgmres_lib/model.hpp", "max_stars_repo_name": "thori1222/an_hori_project", "max_stars_repo_head_hexsha": "9fca623f76cc2a65611ec57a07de221b29969e58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cacc/packages/common/cgmres_lib/include/cgmres_lib/model.hpp", "max_issues_repo_name": "thori1222/an_hori_project", "max_issues_repo_head_hexsha": "9fca623f76cc2a65611ec57a07de221b29969e58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cacc/packages/common/cgmres_lib/include/cgmres_lib/model.hpp", "max_forks_repo_name": "thori1222/an_hori_project", "max_forks_repo_head_hexsha": "9fca623f76cc2a65611ec57a07de221b29969e58", "max_forks_repo_licenses": ["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.5838509317, "max_line_length": 106, "alphanum_fraction": 0.5704796217, "num_tokens": 3512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6584175139669998, "lm_q1q2_score": 0.5026910744669152}}
{"text": "// Copyright Louis Dionne 2013-2017\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/count_if.hpp>\r\n#include <boost/hana/equal.hpp>\r\n#include <boost/hana/ext/std/integral_constant.hpp>\r\n#include <boost/hana/integral_constant.hpp>\r\n#include <boost/hana/mod.hpp>\r\n#include <boost/hana/not_equal.hpp>\r\n#include <boost/hana/tuple.hpp>\r\n#include <boost/hana/type.hpp>\r\n\r\n#include <type_traits>\r\nnamespace hana = boost::hana;\r\nusing namespace hana::literals;\r\n\r\n\r\nauto is_odd = [](auto x) {\r\n    return x % 2_c != 0_c;\r\n};\r\n\r\nint main() {\r\n    constexpr auto ints = hana::tuple_c<int, 1, 2, 3>;\r\n    BOOST_HANA_CONSTANT_CHECK(hana::count_if(ints, is_odd) == hana::size_c<2>);\r\n\r\n    constexpr auto types = hana::tuple_t<int, char, long, short, char, double>;\r\n    BOOST_HANA_CONSTANT_CHECK(hana::count_if(types, hana::trait<std::is_floating_point>) == hana::size_c<1>);\r\n    BOOST_HANA_CONSTANT_CHECK(hana::count_if(types, hana::equal.to(hana::type_c<char>)) == hana::size_c<2>);\r\n    BOOST_HANA_CONSTANT_CHECK(hana::count_if(types, hana::equal.to(hana::type_c<void>)) == hana::size_c<0>);\r\n}\r\n", "meta": {"hexsha": "04fb6e8d053db2561319e50689e8bcd37afaea9b", "size": 1243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/count_if.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/hana/example/count_if.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/hana/example/count_if.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": 37.6666666667, "max_line_length": 110, "alphanum_fraction": 0.7039420756, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5026910713188443}}
{"text": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/adjacency_matrix.hpp>\n#include <boost/graph/random.hpp>\n\n#include \"range.hpp\"\n\nusing namespace std;\n\ntemplate<class Graph, class Generator>\nGraph random_graph(int n, double p, Generator generator) {\n  Graph g(n);\n  bernoulli_distribution distribution(p);\n  auto trial = bind(distribution, generator);\n  for(int i = 0; i < n; ++i)\n    for(int j = i + 1; j < n; ++j)\n      if(trial()) add_edge(i, j, g);\n  return g;\n}\n\nclass Timing {\n  timespec c_start, c_end;\n  clockid_t c_id;\n  vector<time_t> times;\npublic:\n  Timing(clockid_t id) : c_id(id) {}\n  void start() {\n    clock_gettime(c_id, &c_start);\n  }\n  void stop() {\n    clock_gettime(c_id, &c_end);\n  }\n  void tick() {\n    stop();\n    times.push_back(elapsed());\n    start();\n  }\n  time_t begin() const {\n    return c_start.tv_sec * 1e9 + c_start.tv_nsec;\n  }\n  time_t end() const {\n    return c_end.tv_sec * 1e9 + c_end.tv_nsec;\n  }\n  time_t elapsed() const {\n    return end() - begin();\n  }\n  const vector<time_t>& elems() {\n    return times;\n  }\n  void clear() {\n    times.clear();\n  }\n};\n\ntemplate <class Graph>\nvoid test(string name) {\n  default_random_engine gen;\n  ofstream file(name);\n  Timing t(CLOCK_PROCESS_CPUTIME_ID);\n  for(int n = 100; n <= 1000; n += 100) {\n    cerr << n << endl;\n    for(int j = 0; j < 100; ++j) {\n      auto g = random_graph<Graph>(n, 0.1, gen);\n\n      int foo = 0;\n      t.start();\n      for(auto v : range(vertices(g))) ++foo;\n      t.stop();\n      auto t1 = t.elapsed();\n\n      t.start();\n      for(auto e : range(edges(g))) --foo;\n      t.stop();\n      auto t2 = t.elapsed();\n\n      for(int i = 0; i < 10; ++i) {\n        auto v = random_vertex(g, gen);\n        auto w = random_vertex(g, gen);\n\n        t.start();\n        auto e = edge(v, w, g);\n        t.tick();\n        auto d = out_degree(v, g);\n        t.tick();\n        for(auto x : range(adjacent_vertices(v, g))) --d;\n        t.tick();\n\n        if(e.second) remove_edge(v, w, g);\n\n        t.start();\n        add_edge(v, w, g);\n        t.tick();\n        remove_edge(v, w, g);\n        t.tick();\n\n        if(e.second) add_edge(v, w, g);\n\n        t.start();\n        source(e.first, g);\n        t.tick();\n        target(e.first, g);\n        t.tick();\n\n        assert(d == 0 && foo < 0);\n\n        file << n << ' ' << t1 << ' ' << t2 << ' ';\n        for(auto x : t.elems()) file << x << ' ';\n        file << endl;\n        t.clear();\n      }\n    }\n  }\n  file.close();\n}\n\nint main() {\n  using namespace boost;\n  test<adjacency_list<vecS, vecS, undirectedS>>(\"vec.txt\");\n  test<adjacency_list<listS, vecS, undirectedS>>(\"list.txt\");\n  test<adjacency_list<slistS, vecS, undirectedS>>(\"slist.txt\");\n  test<adjacency_list<setS, vecS, undirectedS>>(\"set.txt\");\n  test<adjacency_list<multisetS, vecS, undirectedS>>(\"multiset.txt\");\n  test<adjacency_list<hash_setS, vecS, undirectedS>>(\"hashset.txt\");\n  test<adjacency_matrix<undirectedS>>(\"matrix.txt\");\n  return 0;\n}\n", "meta": {"hexsha": "4bd663d533c36f775ff353fdfcc9e8538037a824", "size": 3022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "prototype/adjacency.cpp", "max_stars_repo_name": "arekolek/MaxIST", "max_stars_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prototype/adjacency.cpp", "max_issues_repo_name": "arekolek/MaxIST", "max_issues_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prototype/adjacency.cpp", "max_forks_repo_name": "arekolek/MaxIST", "max_forks_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_forks_repo_licenses": ["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.0687022901, "max_line_length": 69, "alphanum_fraction": 0.5655195235, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5026910713188442}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2006 Allen Kuo\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 FRA (Forward Rate Agreement) project from Quantlib.\n\n#ifndef cl_adjoint_fra_portfolio_impl_hpp\n#define cl_adjoint_fra_portfolio_impl_hpp\n#pragma once\n\n#include \"adjointfraportfoliotest.hpp\"\n#include \"utilities.hpp\"\n#include \"adjointtestutilities.hpp\"\n#include \"adjointtestbase.hpp\"\n#include <ql/cashflows/coupon.hpp>\n#include <ql/time/daycounters/thirty360.hpp>\n#include <ql/indexes/ibor/euribor.hpp>\n#include <ql/time/schedule.hpp>\n#include <boost/make_shared.hpp>\n#include <ql/quantlib.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\n#define OUTPUT_FOLDER_NAME \"AdjointFRAPortfolio\"\n\nnamespace\n{\n    enum\n    {\n#if defined CL_GRAPH_GEN\n        // Number of points for dependency plots.\n        pointNo = 50,\n        // Number of points for performance plot.\n        iterNo = 50,\n        // Step for portfolio size for performance testing .\n        step = 1,\n#else\n        // Number of points for dependency plots.\n        pointNo = 1,\n        // Number of points for performance plot.\n        iterNo = 1,\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    struct RateVariation\n    {\n        static std::deque<std::string > get_columns()\n        {\n            static std::deque<std::string > columns =\n            {\n                \"Forward Rate\", \"\"\n            };\n\n            return columns;\n        }\n\n        template <typename stream_type>\n        friend inline stream_type&\n            operator << (stream_type& stm, RateVariation& v)\n        {\n                stm << v.rate_\n                    << \";\" << v.contractValue_\n                    << std::endl;\n                return stm;\n            }\n\n        Real rate_;\n        Real contractValue_;\n    };\n\n    struct FRAPortfolioData\n    {\n        FRAPortfolioData() :\n        euriborTermStructure_()\n        , euribor_(boost::make_shared<Euribor3M>(euriborTermStructure_))\n        , todaysDate_(27, July, 2015)\n        , calendar_(euribor_->fixingCalendar())\n        , fixingDays_(euribor_->fixingDays())\n        , settlementDate_(calendar_.advance(todaysDate_, fixingDays_, Days))\n        , fraDayCounter_(euribor_->dayCounter())\n        , convention_(euribor_->businessDayConvention())\n        , endOfMonth_(euribor_->endOfMonth())\n        , termStructureDayCounter_(ActualActual(ActualActual::ISDA))\n        , fraFwdType_(Position::Long)\n        , fraNotional_(100.0)\n        , quoteHandles_()\n        , fra_()\n        , discountingTermStructure_()\n        , fraTermStructure_()\n        {\n            Settings::instance().evaluationDate() = todaysDate_;\n        }\n\n        // This function creates term structure for Forward Rate Agreements (FRA)\n        // based on values of forward rates. Each forward rate refers to\n        // 3 month term FRA quotes (index refers to months to start) are considered.\n        // Input parameters:\n        //  - FraRate - vector of forward rate for every FRA in portfolio;\n        void createTermStructure(std::vector<Real>& FraRate)\n        {\n            Size n = FraRate.size();\n\n            //Create relinkable handle to rate for Forward Rate Agreement.\n            quoteHandles_.resize(n);\n            for (Size i = 0; i < n; ++i)\n                quoteHandles_[i] = RelinkableHandle<Quote>(boost::make_shared<SimpleQuote>(FraRate[i]));\n\n            // Rate helpers\n            // RateHelpers are built from the above quotes together with\n            // other instrument dependent infos.  Quotes are passed in\n            // relinkable handles which could be relinked to some other\n            // data source later.\n            fra_.resize(n);\n            for (Size i = 0; i < n; ++i)\n                fra_[i] = boost::make_shared<FraRateHelper>(\n                quoteHandles_[i], (i + 1), (i + 4), fixingDays_, calendar_, convention_,\n                endOfMonth_, fraDayCounter_);\n\n            double tolerance = 1.0e-15;\n\n            // Create Forward Rate Agreement curve.\n            fraTermStructure_ = boost::make_shared<PiecewiseYieldCurve<Discount, LogLinear>>(\n                settlementDate_, fra_,\n                termStructureDayCounter_, tolerance);\n\n            // Term structures used for pricing/discounting.\n            discountingTermStructure_.linkTo(fraTermStructure_);\n            euriborTermStructure_.linkTo(fraTermStructure_);\n\n            fraValueDate_.resize(n);\n            fraMaturityDate_.resize(n);\n            for (Size i = 0; i < n; i++)\n            {\n                fraValueDate_[i] = calendar_.advance(\n                    settlementDate_, i + 1, Months,\n                    convention_);\n\n                // Set maturity date (The date on which the notional loan matures).\n                fraMaturityDate_[i] = calendar_.advance(\n                    fraValueDate_[i],  FraTermMonths_, Months,\n                    convention_);\n            }\n        }\n\n        // Adjust term structure with updating fra rate at specified posittion.\n        void adjustTermStructure(Real FraRate, Size position)\n        {\n            quoteHandles_[position] = RelinkableHandle<Quote>(boost::make_shared<SimpleQuote>(FraRate));\n            fra_[position] = boost::make_shared<FraRateHelper>(\n                quoteHandles_[position], (position + 1), (position + 4), fixingDays_, calendar_, convention_,\n                endOfMonth_, fraDayCounter_);\n\n            double tolerance = 1.0e-15;\n\n            // Create Forward Rate Agreement curve.\n            fraTermStructure_ = boost::make_shared<PiecewiseYieldCurve<Discount, LogLinear>>(\n                settlementDate_, fra_,\n                termStructureDayCounter_, tolerance);\n\n            // Term structures used for pricing/discounting.\n            discountingTermStructure_.linkTo(fraTermStructure_);\n            euriborTermStructure_.linkTo(fraTermStructure_);\n        }\n\n        // Create FRA for defined rate.\n        boost::shared_ptr<ForwardRateAgreement> createFRA(Real rate, Size index)\n        {\n            return boost::make_shared<ForwardRateAgreement>(\n                fraValueDate_[index], fraMaturityDate_[index],\n                fraFwdType_, rate,\n                fraNotional_, euribor_,\n                discountingTermStructure_);\n        }\n\n        // Use finite difference to approximate the derivatives\n        // of contract value of each Forward Rate Agreement on forward rate.\n        // dy/dx = (y(x) - y(x-h))/(h)\n        // Input parameters:\n        //  - FraRate - vector of forward rate for every FRA in portfolio;\n        ////  - h - step size for finite difference method;\n        //  - sf_Finite - calculated derivatives.\n        void calculateFinDiff(std::vector<Real>& FraRate, double h, std::vector<Real>& sf_Finite)\n        {\n            Size n = FraRate.size();\n            sf_Finite.resize(n);\n            createTermStructure(FraRate);\n            for (Size i = 0; i < n; i++)\n            {\n                sf_Finite[i] += createFRA(FraRate[i], i)->forwardValue() / h;\n            }\n            for (Size i = 0; i < n; i++)\n            {\n                FraRate[i] -= h;\n                adjustTermStructure(FraRate[i], i);\n                sf_Finite[i] -= createFRA(FraRate[i], i)->forwardValue() / h;\n                FraRate[i] += h;\n            }\n        }\n\n        RelinkableHandle<YieldTermStructure> euriborTermStructure_;\n        boost::shared_ptr<IborIndex> euribor_;\n        Date todaysDate_;\n\n        Calendar calendar_;\n        Integer fixingDays_;\n        Date settlementDate_;\n\n        DayCounter fraDayCounter_;\n        BusinessDayConvention convention_;\n        bool endOfMonth_;\n        DayCounter termStructureDayCounter_;\n\n        Position::Type fraFwdType_;\n        Real fraNotional_;\n        const Integer  FraTermMonths_ = 3;\n        RelinkableHandle<YieldTermStructure> discountingTermStructure_;\n        std::vector<RelinkableHandle<Quote> > quoteHandles_;\n        std::vector<boost::shared_ptr<RateHelper>> fra_;\n\n        std::vector<Date> fraValueDate_;\n        std::vector<Date> fraMaturityDate_;\n        boost::shared_ptr<YieldTermStructure> fraTermStructure_;\n\n    };\n\n\n    struct TestData\n        : public FRAPortfolioData\n    {\n        struct Test\n        : public cl::AdjointTest<Test>\n        {\n            Test(Size size, TestData* data)\n            : size_(size)\n            , data_(data)\n            , fraRate_(size)\n            , totalContractValue_()\n            {\n                setLogger(&data_->outPerform_);\n\n                for (Size i = 0; i < size_; i++)\n                {\n                    fraRate_[i] = 0.030 + i*0.0000001;\n                }\n            }\n\n            Size indepVarNumber() { return size_; }\n\n            Size depVarNumber() { return 1; }\n\n            Size minPerfIteration() { return iterNumFactor; }\n\n            void recordTape()\n            {\n                cl::Independent(fraRate_);\n                calculateTotalContractValue();\n                f_ = std::make_unique<cl::tape_function<double>>(fraRate_, totalContractValue_);\n            }\n\n            // Calculates price of portfolio and each option.\n            void calculateTotalContractValue()\n            {\n                totalContractValue_.resize(1, 0);\n                std::vector<boost::shared_ptr<ForwardRateAgreement>> fraPortfolio(size_, 0);\n                data_->createTermStructure(fraRate_);\n\n                for (Size i = 0; i < size_; i++)\n                {\n                    fraPortfolio[i] = data_->createFRA(fraRate_[i], i);\n                    totalContractValue_.front() += fraPortfolio[i]->forwardValue();\n                }\n            }\n\n            // Calculates derivatives using finite difference method.\n            void calcAnalytical()\n            {\n                double h = 1.0e-6;  // shift for finite diff. method\n                analyticalResults_.resize(size_);\n                data_->calculateFinDiff(fraRate_, h, analyticalResults_);\n            }\n\n            double relativeTol() const { return 1e-5; }\n\n            double absTol() const { return 1e-10; }\n\n            Size size_;\n            TestData* data_;\n            std::vector<cl::tape_double> fraRate_;\n            std::vector<cl::tape_double> totalContractValue_;\n        };\n\n        TestData()\n            : FRAPortfolioData()\n            , outPerform_(OUTPUT_FOLDER_NAME \"//\",\n            { { \"filename\", \"AdjointPerformance\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", \"FRA contract value differentiation performance with respect to forward rates\" }\n        , { \"ylabel\", \"Time (s)\" }\n        , { \"xlabel\", \"Number of forward rates\" }\n        , { \"line_box_width\", \"-5\" }\n        , { \"smooth\", \"default\" }\n        , { \"cleanlog\", \"true\" }\n        })\n            , outAdjoint_(OUTPUT_FOLDER_NAME \"//\",\n            { { \"filename\", \"Adjoint\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", \"FRA contract value adjoint differentiation performance with respect to forward rates\" }\n        , { \"ylabel\", \"Time (s)\" }\n        , { \"xlabel\", \"Number of forward rates\" }\n        , { \"smooth\", \"default\" }\n        , { \"cleanlog\", \"false\" }\n        })\n            , outSize_(OUTPUT_FOLDER_NAME \"//\",\n            { { \"filename\", \"TapeSize\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", \"Tape size dependence on number of forward rates\" }\n        , { \"ylabel\", \"Memory (MB)\" }\n        , { \"xlabel\", \"Number of forward rates\" }\n        , { \"smooth\", \"default\" }\n        , { \"cleanlog\", \"false\" }\n        })\n            , out_(OUTPUT_FOLDER_NAME \"//output\",\n            { { \"filename\", \"Output\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", \"FRA contract value dependence on FRA rate\" }\n        , { \"ylabel\", \"FRA Contract Value\" }\n        , { \"xlabel\", \"FRA Rate\" }\n        , { \"cleanlog\", \"false\" }\n        })\n        {\n        }\n\n        bool makeOutput()\n        {\n            bool ok = true;\n            if (pointNo > 0)\n            {\n                ok &= recordDependencePlot();\n            }\n            ok &= cl::recordPerformance(*this, iterNo, step);\n            return ok;\n        }\n\n        std::shared_ptr<Test> getTest(size_t size)\n        {\n            return std::make_shared<Test>(50 + size, this);\n        }\n\n        // Makes plots for strike sensitivity dependence.\n        bool recordDependencePlot()\n        {\n            std::vector<RateVariation> outData(pointNo);\n            auto test = getTest(pointNo);\n            createTermStructure(test->fraRate_);\n            for (Size i = 0; i < pointNo; i += 10)\n            {\n                boost::shared_ptr<ForwardRateAgreement> fra = createFRA(test->fraRate_[i], i);\n                outData[i] = { test->fraRate_[i], fra->forwardValue() };\n            }\n            out_ << outData;\n            return true;\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    typedef TestData::Test FRAPortfolioTest;\n}\n\n#endif", "meta": {"hexsha": "f02bfe26cbffa3767dc436d5bf7b57a21802b0e6", "size": 13976, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointfraportfolioimpl.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/adjointfraportfolioimpl.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/adjointfraportfolioimpl.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": 35.2929292929, "max_line_length": 109, "alphanum_fraction": 0.5714081282, "num_tokens": 3193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.50268282510592}}
{"text": "//Joseph Lavagna - NO719058\n#include <boost/test/unit_test.hpp>\n#include \"logs.h\"\n#include \"route.h\"\n#include \"track.h\"\n#include \"position.h\"\n\nusing namespace GPS;\n\n\n/*\nDocumentation\n\nIn the following file is a test suite containing numerous tests to check the implementation of the netHeightGain function to make sure all values returned are correct.\n\n*/\n\nBOOST_AUTO_TEST_SUITE (N0719058_netHeightGain)\n\nconst bool isFileName = true;\n\n//Test: Zero Net Elevation\n//Description: The route that I have specified QLHNR are all on the same plane and so the net elevation should equal 0. All positions on the route have an elevation of 38.\nBOOST_AUTO_TEST_CASE( zeroNetElevation )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"N0719058_zeroNetElevation.gpx\", isFileName);\n   BOOST_CHECK_EQUAL( route.totalHeightGain(), 0 );\n}\n\n\n//Test: Positive Net Elevation\n//Description: The route that I have specified WRM have three different positions on different planes with elevation values of 8, 38, 68 and so a positive net elevation of 60. \nBOOST_AUTO_TEST_CASE( positiveNetElevation )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"N0719058_positiveNetElevation.gpx\", isFileName);\n   BOOST_CHECK_EQUAL( route.totalHeightGain(), 60 );\n}\n\n//Test: Negative Net Elevation\n//Description: The route that I have specified MRW have three different positions on different planes with elevations values of 68, 38, 8 and so a negative net elevation of -60. However the implemented function should return 0 if net elevation is negative. \nBOOST_AUTO_TEST_CASE( negativeNetElevation )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"N0719058_negativeNetElevation.gpx\", isFileName);\n   BOOST_CHECK_EQUAL( route.totalHeightGain(), 0 );\n}\n\n\n//Test: Single Elevation\n//Description: The route that I have specified for this test, B, is one single location and so has one single elevation value of 8. And so no net elevation value can be returned.  \nBOOST_AUTO_TEST_CASE( singleElevation )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"N0719058_singleElevation.gpx\", isFileName);\n   BOOST_CHECK_EQUAL( route.totalHeightGain(), 0 );\n}\n\n\n//Test: Increase Negative Elevation\n//Description: The route all has negative values, but is incrementing in value. There fore a positive number should be returned since as the height is increasing.\nBOOST_AUTO_TEST_CASE( increaseNegativeElevation )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"N0719058_increaseNegativeElevation.gpx\", isFileName);\n   BOOST_CHECK_EQUAL( route.totalHeightGain(), 60 );\n}\n\n\n//Test: No Elevation\n//Description: For this test while generating the GPX log file I set the elevation difference between planes to 0. And so the elevation value for each position shouldn't change regardless of planes. The route that I have specified UQMIE all have elevation values of 68 and so a 0 net elevation. \nBOOST_AUTO_TEST_CASE( noElevation )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"N0719058_noElevation.gpx\", isFileName);\n   BOOST_CHECK_EQUAL( route.totalHeightGain(), 0 );\n}\n\n\n//Test: Increase Decrease Elevation\n//Description: The route that I have specified alternates in elevation and reaches the max position. \nBOOST_AUTO_TEST_CASE( increaseDecreaseElevation )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"N0719058_increaseDecreaseElevation.gpx\", isFileName);\n   BOOST_CHECK_EQUAL( route.totalHeightGain(), 60 );\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a6875f902206ed516ef86d4ea3cfcd1978547242", "size": 3413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpx-tests/N0719058_netHeightGain.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/N0719058_netHeightGain.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/N0719058_netHeightGain.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": 40.1529411765, "max_line_length": 295, "alphanum_fraction": 0.7814239672, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5026828207948372}}
{"text": "//\n// Created by nvidia on 6/11/18.\n//\n\n#ifndef SUPERPIXEL_UTILS_HPP\n#define SUPERPIXEL_UTILS_HPP\n\n\n#include <opencv2/opencv.hpp>\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <boost/functional/hash.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_matrix.hpp>\n\nnamespace cove {\n\nconstexpr int SPVEC_SIZE = 7;\nconstexpr int COUT_WIDTH = 7;\ntypedef cv::Vec<double, SPVEC_SIZE> SpVec;\n\ntemplate<typename T>\nvoid printVec(const std::vector<T> &v);\n\n\nSpVec multiply(const SpVec &a, const SpVec &b);\n\nvoid printVecSpVec(const std::vector<SpVec> &v);\n\nvoid printSpVec(const SpVec &v);\n\nstd::vector<int> getTrainingLabels(cv::InputArray _labels, int regionSize, int rows = 1, int cols = 3);\n\nSpVec getParams(cv::InputArray labels, cv::InputArray _frame, int labelVal);\n\nSpVec vecAverage(const std::vector<SpVec> &v);\n\nSpVec vecStdDev(const std::vector<SpVec> &v, const SpVec &mean);\n\nSpVec vecStdDev(const std::vector<SpVec> &v);\n\nextern SpVec weights;\n\ndouble normSsd(const SpVec &v, const SpVec &mean, const SpVec &stdDev);\n\ncv::Matx<double, 2, 3> translateImg(cv::Mat &img, int offsetx, int offsety);\n\ntypedef boost::adjacency_matrix<boost::undirectedS> Graph;\n\nGraph generateGraph(cv::InputArray _labels, unsigned int max);\n\n}\n#endif // SUPERPIXEL_UTILS_HPP", "meta": {"hexsha": "213bb1a025213067dc8af2a4d720ebaaf3d6269c", "size": 1299, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "superpixel-seg/lib/SpVec.hpp", "max_stars_repo_name": "NVIDIA-Jetson/Foursee-Navigation", "max_stars_repo_head_hexsha": "673b4a8bcf5774cf23d2564bada68709d28c850e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2018-11-01T06:05:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T02:48:03.000Z", "max_issues_repo_path": "superpixel-seg/lib/SpVec.hpp", "max_issues_repo_name": "NVIDIA-Jetson/Foursee-Navigation", "max_issues_repo_head_hexsha": "673b4a8bcf5774cf23d2564bada68709d28c850e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-03T18:54:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-03T18:55:37.000Z", "max_forks_repo_path": "superpixel-seg/lib/SpVec.hpp", "max_forks_repo_name": "NVIDIA-Jetson/Foursee-Navigation", "max_forks_repo_head_hexsha": "673b4a8bcf5774cf23d2564bada68709d28c850e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-12-17T10:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T06:45:28.000Z", "avg_line_length": 24.0555555556, "max_line_length": 103, "alphanum_fraction": 0.7498075443, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5026828163871688}}
{"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\ntemplate <typename Vector>\nvoid test(const char* name, const Vector&)\n{\n    std::cout << name << \" is \" << mtl::static_num_rows<Vector>::value << \"x\"\n\t      << mtl::static_num_cols<Vector>::value << \"\\n\";\n\n    if (mtl::static_num_rows<Vector>::value != (mtl::traits::is_row_major<Vector>::value ? 1 : 2))\n\tthrow \"Wrong number of rows\";\n    if (mtl::static_num_cols<Vector>::value != (mtl::traits::is_row_major<Vector>::value ? 2 : 1))\n\tthrow \"Wrong number of columns\";\n    if (mtl::static_size<Vector>::value != 2)\n\tthrow \"Wrong size\";\n}\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    typedef mtl::vec::parameters<tag::col_major, mtl::vec::fixed::dimension<2>, true> col_para;\n    typedef mtl::vec::parameters<tag::row_major, mtl::vec::fixed::dimension<2>, true> row_para;\n    float va[2]= {3., 4.};\n    dense_vector<float, col_para>   v_col(va);\n    dense_vector<float, row_para>   v_row(va);\n\n    test(\"Dense column vector\", v_col);\n    test(\"Dense row vector\", v_row);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "719c01422d3acf3ae3c5205277bd656875d231f7", "size": 1519, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/static_size_vector_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/static_size_vector_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/static_size_vector_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.0, "max_line_length": 98, "alphanum_fraction": 0.6649111257, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5026828162905832}}
{"text": "\n\n\n/* ---------------------------------------------------------------------\n *\n * Copyright (C) 2000 - 2021 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: Wolfgang Bangerth, University of Heidelberg, 2000\n */\n\n\n\n// \u5c31\u50cf\u4ee5\u524d\u7684\u4f8b\u5b50\u4e00\u6837\uff0c\u6211\u4eec\u5fc5\u987b\u5305\u62ec\u51e0\u4e2a\u6587\u4ef6\uff0c\u5176\u4e2d\u7684\u542b\u4e49\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u4e86\u3002\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/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_gmres.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/grid_refinement.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_tools.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 <deal.II/fe/fe_q.h>\n#include <deal.II/grid/grid_out.h>\n\n// \u4e0b\u9762\u4e24\u4e2a\u6587\u4ef6\u63d0\u4f9b\u4e86\u591a\u7ebf\u7a0b\u7a0b\u5e8f\u7684\u7c7b\u548c\u4fe1\u606f\u3002\u5728\u7b2c\u4e00\u4e2a\u6587\u4ef6\u4e2d\uff0c\u58f0\u660e\u4e86\u6211\u4eec\u9700\u8981\u505a\u5e76\u884c\u88c5\u914d\u7684\u7c7b\u548c\u51fd\u6570\uff08\u5373\n// <code>WorkStream</code>\n// \u547d\u540d\u7a7a\u95f4\uff09\u3002\u7b2c\u4e8c\u4e2a\u6587\u4ef6\u6709\u4e00\u4e2a\u7c7bMultithreadInfo\uff0c\u53ef\u4ee5\u7528\u6765\u67e5\u8be2\u7cfb\u7edf\u4e2d\u7684\u5904\u7406\u5668\u6570\u91cf\uff0c\u8fd9\u5728\u51b3\u5b9a\u542f\u52a8\u591a\u5c11\u4e2a\u5e76\u884c\u7ebf\u7a0b\u65f6\u901a\u5e38\u5f88\u6709\u7528\u3002\n\n#include <deal.II/base/work_stream.h>\n#include <deal.II/base/multithread_info.h>\n\n// \u4e0b\u4e00\u4e2a\u65b0\u7684include\u6587\u4ef6\u58f0\u660e\u4e86\u4e00\u4e2a\u57fa\u7c7b <code>TensorFunction</code> \uff0c\u4e0e\n// <code>Function</code> \u7c7b\u4e0d\u4e00\u6837\uff0c\u4f46\u4e0d\u540c\u7684\u662f TensorFunction::value\n// \u8fd4\u56de\u4e00\u4e2a\u5f20\u91cf\u800c\u4e0d\u662f\u4e00\u4e2a\u6807\u91cf\u3002\n\n#include <deal.II/base/tensor_function.h>\n\n#include <deal.II/numerics/error_estimator.h>\n\n// \u8fd9\u662fC++\uff0c\u56e0\u4e3a\u6211\u4eec\u60f3\u628a\u4e00\u4e9b\u8f93\u51fa\u5199\u5165\u78c1\u76d8\u3002\n\n#include <fstream>\n#include <iostream>\n\n// \u6700\u540e\u4e00\u6b65\u548c\u4ee5\u524d\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\n\nnamespace Step9\n{\n  using namespace dealii;\n  // @sect3{Equation data declaration}\n\n  // \u63a5\u4e0b\u6765\u6211\u4eec\u58f0\u660e\u4e00\u4e2a\u63cf\u8ff0\u5e73\u6d41\u573a\u7684\u7c7b\u3002\u5f53\u7136\uff0c\u8fd9\u662f\u4e00\u4e2a\u77e2\u91cf\u573a\uff0c\u6709\u591a\u5c11\u5206\u91cf\u5c31\u6709\u591a\u5c11\u7a7a\u95f4\u7ef4\u5ea6\u3002\u73b0\u5728\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528\u4e00\u4e2a\u4ece\n  // <code>Function</code>\n  // \u57fa\u7c7b\u6d3e\u751f\u51fa\u6765\u7684\u7c7b\uff0c\u5c31\u50cf\u6211\u4eec\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u5bf9\u8fb9\u754c\u503c\u548c\u7cfb\u6570\u6240\u505a\u7684\u90a3\u6837\uff0c\u4f46\u662f\u5728\u5e93\u4e2d\u8fd8\u6709\u53e6\u4e00\u79cd\u53ef\u80fd\u6027\uff0c\u5373\u4e00\u4e2a\u63cf\u8ff0\u5f20\u91cf\u503c\u51fd\u6570\u7684\u57fa\u7c7b\u3002\u8fd9\u6bd4\u91cd\u5199\n  // Function::value()\n  // \u77e5\u9053\u591a\u4e2a\u51fd\u6570\u6210\u5206\u7684\u65b9\u6cd5\u66f4\u65b9\u4fbf\uff1a\u6700\u540e\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u5f20\u91cf\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u59a8\u76f4\u63a5\u4f7f\u7528\u4e00\u4e2a\u8fd4\u56de\u5f20\u91cf\u7684\u7c7b\u3002\n\n  template <int dim>\n  class AdvectionField : public TensorFunction<1, dim>\n  {\n  public:\n    virtual Tensor<1, dim> value(const Point<dim> &p) const override;\n\n    // \u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u5df2\u7ecf\u5728\u591a\u4e2a\u5730\u65b9\u4f7f\u7528\u4e86\u629b\u51fa\u5f02\u5e38\u7684\u65ad\u8a00\u3002\u4f46\u662f\uff0c\u6211\u4eec\u8fd8\u6ca1\u6709\u770b\u5230\u5982\u4f55\u58f0\u660e\u8fd9\u79cd\u5f02\u5e38\u3002\u8fd9\u53ef\u4ee5\u8fd9\u6837\u505a\u3002\n\n    DeclException2(ExcDimensionMismatch,\n                   unsigned int,\n                   unsigned int,\n                   << \"The vector has size \" << arg1 << \" but should have \"\n                   << arg2 << \" elements.\");\n\n    // \u8bed\u6cd5\u53ef\u80fd\u770b\u8d77\u6765\u6709\u70b9\u5947\u602a\uff0c\u4f46\u5f88\u5408\u7406\u3002\u5176\u683c\u5f0f\u57fa\u672c\u5982\u4e0b\uff1a\u4f7f\u7528\u5176\u4e2d\u4e00\u4e2a\u5b8f\u7684\u540d\u79f0\n    // <code>DeclExceptionN</code>, where <code>N</code>\n    // \u8868\u793a\u5f02\u5e38\u5bf9\u8c61\u5e94\u91c7\u53d6\u7684\u9644\u52a0\u53c2\u6570\u7684\u6570\u91cf\u3002\u5728\u672c\u4f8b\u4e2d\uff0c\u7531\u4e8e\u6211\u4eec\u60f3\u5728\u4e24\u4e2a\u5411\u91cf\u7684\u5927\u5c0f\u4e0d\u540c\u65f6\u629b\u51fa\u5f02\u5e38\uff0c\u6211\u4eec\u9700\u8981\u4e24\u4e2a\u53c2\u6570\uff0c\u6240\u4ee5\u6211\u4eec\u4f7f\u7528\n    // <code>DeclException2</code>\n    // \u3002\u7b2c\u4e00\u4e2a\u53c2\u6570\u63cf\u8ff0\u4e86\u5f02\u5e38\u7684\u540d\u79f0\uff0c\u800c\u4e0b\u9762\u7684\u53c2\u6570\u5219\u58f0\u660e\u4e86\u53c2\u6570\u7684\u6570\u636e\u7c7b\u578b\u3002\u6700\u540e\u4e00\u4e2a\u53c2\u6570\u662f\u4e00\u8fde\u4e32\u7684\u8f93\u51fa\u6307\u4ee4\uff0c\u8fd9\u4e9b\u6307\u4ee4\u5c06\u88ab\u8f93\u9001\u5230\n    // <code>std::cerr</code>  \u5bf9\u8c61\u4e2d\uff0c\u56e0\u6b64\u51fa\u73b0\u4e86\u5947\u602a\u7684\u683c\u5f0f\uff0c\u524d\u9762\u662f\n    // <code>@<@<</code>  \u64cd\u4f5c\u7b26\u4e4b\u7c7b\u7684\u3002\u6ce8\u610f\uff0c\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u4f7f\u7528\u540d\u79f0\n    // <code>arg1</code> through <code>argN</code>  \u6765\u8bbf\u95ee\u5728\u6784\u9020\u65f6\uff08\u5373\u5728\n    // <code>Assert</code>  \u8c03\u7528\u4e2d\uff09\u4f20\u9012\u7ed9\u5f02\u5e38\u7684\u53c2\u6570\uff0c\u5176\u4e2d  <code>N</code>\n    // \u662f\u901a\u8fc7\u4f7f\u7528\u5404\u81ea\u7684\u5b8f  <code>DeclExceptionN</code>  \u6765\u5b9a\u4e49\u7684\u53c2\u6570\u6570\u3002\n\n    // \u8981\u4e86\u89e3\u9884\u5904\u7406\u5668\u5982\u4f55\u5c06\u8fd9\u4e2a\u5b8f\u6269\u5c55\u4e3a\u5b9e\u9645\u4ee3\u7801\uff0c\u8bf7\u53c2\u8003\u5f02\u5e38\u7c7b\u7684\u6587\u6863\u3002\u7b80\u800c\u8a00\u4e4b\uff0c\u8fd9\u4e2a\u5b8f\u8c03\u7528\u58f0\u660e\u5e76\u5b9a\u4e49\u4e86\u4e00\u4e2a\u7ee7\u627f\u81ea\n    // ExceptionBase \u7684\u7c7b  <code>ExcDimensionMismatch</code>\n    // \uff0c\u5b83\u5b9e\u73b0\u4e86\u6240\u6709\u5fc5\u8981\u7684\u9519\u8bef\u8f93\u51fa\u529f\u80fd\u3002\n  };\n\n  // \u4e0b\u9762\u7684\u4e24\u4e2a\u51fd\u6570\u5b9e\u73b0\u4e86\u4e0a\u8ff0\u7684\u63a5\u53e3\u3002\u7b2c\u4e00\u4e2a\u7b80\u5355\u5730\u5b9e\u73b0\u4e86\u4ecb\u7ecd\u4e2d\u6240\u63cf\u8ff0\u7684\u51fd\u6570\uff0c\u800c\u7b2c\u4e8c\u4e2a\u4f7f\u7528\u4e86\u540c\u6837\u7684\u6280\u5de7\u6765\u907f\u514d\u8c03\u7528\u865a\u62df\u51fd\u6570\uff0c\u5728\u524d\u9762\u7684\u4f8b\u5b50\u7a0b\u5e8f\u4e2d\u5df2\u7ecf\u4ecb\u7ecd\u8fc7\u4e86\u3002\u6ce8\u610f\u7b2c\u4e8c\u4e2a\u51fd\u6570\u4e2d\u5bf9\u53c2\u6570\u7684\u6b63\u786e\u5927\u5c0f\u7684\u68c0\u67e5\uff0c\u8fd9\u79cd\u68c0\u67e5\u5e94\u8be5\u59cb\u7ec8\u5b58\u5728\u4e8e\u8fd9\u7c7b\u51fd\u6570\u4e2d\uff1b\u6839\u636e\u6211\u4eec\u7684\u7ecf\u9a8c\uff0c\u8bb8\u591a\u751a\u81f3\u5927\u591a\u6570\u7f16\u7a0b\u9519\u8bef\u90fd\u662f\u7531\u4e0d\u6b63\u786e\u7684\u521d\u59cb\u5316\u6570\u7ec4\u3001\u4e0d\u517c\u5bb9\u7684\u51fd\u6570\u53c2\u6570\u7b49\u9020\u6210\u7684\uff1b\u50cf\u672c\u4f8b\u4e2d\u90a3\u6837\u4f7f\u7528\u65ad\u8a00\u53ef\u4ee5\u6d88\u9664\u8bb8\u591a\u8fd9\u6837\u7684\u95ee\u9898\u3002\n\n  template <int dim>\n  Tensor<1, dim> AdvectionField<dim>::value(const Point<dim> &p) const\n  {\n    Tensor<1, dim> value;\n    value[0] = 2;\n    for (unsigned int i = 1; i < dim; ++i)\n      value[i] = 1 + 0.8 * std::sin(8. * numbers::PI * p[0]);\n\n    return value;\n  }\n\n  // \u9664\u4e86\u5e73\u6d41\u573a\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u4e24\u4e2a\u63cf\u8ff0\u6e90\u9879\uff08  <code>right hand side</code>\n  // \uff09\u548c\u8fb9\u754c\u503c\u7684\u51fd\u6570\u3002\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0\uff0c\u6e90\u662f\u4e00\u4e2a\u6e90\u70b9\u9644\u8fd1\u7684\u5e38\u6570\u51fd\u6570\uff0c\u6211\u4eec\u7528\u5e38\u6570\u9759\u6001\u53d8\u91cf\n  // <code>center_point</code>  \u8868\u793a\u3002\u6211\u4eec\u4f7f\u7528\u4e0e\u6211\u4eec\u5728 step-7\n  // \u793a\u4f8b\u7a0b\u5e8f\u4e2d\u6240\u793a\u76f8\u540c\u7684\u6a21\u677f\u6280\u5de7\u6765\u8bbe\u7f6e\u8fd9\u4e2a\u4e2d\u5fc3\u7684\u503c\u3002\u5269\u4e0b\u7684\u5c31\u5f88\u7b80\u5355\u4e86\uff0c\u4e4b\u524d\u5df2\u7ecf\u5c55\u793a\u8fc7\u4e86\u3002\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  private:\n    static const Point<dim> center_point;\n  };\n\n  template <>\n  const Point<1> RightHandSide<1>::center_point = Point<1>(-0.75);\n\n  template <>\n  const Point<2> RightHandSide<2>::center_point = Point<2>(-0.75, -0.75);\n\n  template <>\n  const Point<3> RightHandSide<3>::center_point = Point<3>(-0.75, -0.75, -0.75);\n\n  // \u8fd9\u91cc\u552f\u4e00\u7684\u65b0\u4e1c\u897f\u662f\u6211\u4eec\u68c0\u67e5 <code>component</code>\n  // \u53c2\u6570\u7684\u503c\u3002\u7531\u4e8e\u8fd9\u662f\u4e00\u4e2a\u6807\u91cf\u51fd\u6570\uff0c\u5f88\u660e\u663e\uff0c\u53ea\u6709\u5f53\u6240\u9700\u5206\u91cf\u7684\u7d22\u5f15\u4e3a0\u65f6\u624d\u6709\u610f\u4e49\uff0c\u6240\u4ee5\u6211\u4eec\u65ad\u8a00\u8fd9\u786e\u5b9e\u662f\u8fd9\u6837\u7684\u3002\n  // <code>ExcIndexRange</code>\n  // \u662f\u4e00\u4e2a\u5168\u5c40\u9884\u5b9a\u4e49\u7684\u5f02\u5e38\uff08\u53ef\u80fd\u662f\u6700\u7ecf\u5e38\u4f7f\u7528\u7684\u5f02\u5e38\uff0c\u56e0\u6b64\u6211\u4eec\u8ba9\u5b83\u6210\u4e3a\u5168\u5c40\u7684\uff0c\u800c\u4e0d\u662f\u67d0\u4e2a\u7c7b\u7684\u5c40\u90e8\uff09\uff0c\u5b83\u9700\u8981\u4e09\u4e2a\u53c2\u6570\uff1a\u8d85\u51fa\u5141\u8bb8\u8303\u56f4\u7684\u7d22\u5f15\uff0c\u6709\u6548\u8303\u56f4\u7684\u7b2c\u4e00\u4e2a\u5143\u7d20\u548c\u8d85\u8fc7\u6700\u540e\u4e00\u4e2a\u7684\u5143\u7d20\uff08\u5373\u53c8\u662fC++\u6807\u51c6\u5e93\u4e2d\u7ecf\u5e38\u4f7f\u7528\u7684\u534a\u5f00\u653e\u533a\u95f4\uff09\u3002\n\n  template <int dim>\n  double RightHandSide<dim>::value(const Point<dim> & p,\n                                   const unsigned int component) const\n  {\n    (void)component;\n    Assert(component == 0, ExcIndexRange(component, 0, 1));\n    const double diameter = 0.1;\n    return ((p - center_point).norm_square() < diameter * diameter ?\n              0.1 / std::pow(diameter, dim) :\n              0.0);\n  }\n\n  // \u6700\u540e\u662f\u8fb9\u754c\u503c\uff0c\u8fd9\u53ea\u662f\u4ece <code>Function</code> \u57fa\u7c7b\u6d3e\u751f\u7684\u53e6\u4e00\u4e2a\u7c7b\u3002\n\n  template <int dim>\n  class BoundaryValues : 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  template <int dim>\n  double BoundaryValues<dim>::value(const Point<dim> & p,\n                                    const unsigned int component) const\n  {\n    (void)component;\n    Assert(component == 0, ExcIndexRange(component, 0, 1));\n\n    const double sine_term = std::sin(16. * numbers::PI * p.norm_square());\n    const double weight    = std::exp(5. * (1. - p.norm_square()));\n    return weight * sine_term;\n  }\n  // @sect3{AdvectionProblem class declaration}\n\n  // \u8fd9\u91cc\u662f\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u3002\u5b83\u548c\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u7684\u4e3b\u7c7b\u975e\u5e38\u76f8\u4f3c\uff0c\u6240\u4ee5\u6211\u4eec\u518d\u6b21\u53ea\u5bf9\u5176\u4e0d\u540c\u4e4b\u5904\u8fdb\u884c\u8bc4\u8bba\u3002\n\n  template <int dim>\n  class AdvectionProblem\n  {\n  public:\n    AdvectionProblem();\n    void run();\n\n  private:\n    void setup_system();\n\n    // \u4e0b\u4e00\u7ec4\u51fd\u6570\u5c06\u88ab\u7528\u6765\u7ec4\u88c5\u77e9\u9635\u3002\u7136\u800c\uff0c\u4e0e\u524d\u9762\u7684\u4f8b\u5b50\u4e0d\u540c\uff0c\n    // <code>assemble_system()</code>\n    // \u51fd\u6570\u4e0d\u4f1a\u81ea\u5df1\u505a\u8fd9\u4e9b\u5de5\u4f5c\uff0c\u800c\u662f\u5c06\u5b9e\u9645\u7684\u88c5\u914d\u5de5\u4f5c\u59d4\u6258\u7ed9\u8f85\u52a9\u51fd\u6570\n    // <code>assemble_local_system()</code>  \u548c\n    // <code>copy_local_to_global()</code>\n    // \u3002\u5176\u539f\u7406\u662f\uff0c\u77e9\u9635\u7ec4\u88c5\u53ef\u4ee5\u5f88\u597d\u5730\u5e76\u884c\u5316\uff0c\u56e0\u4e3a\u6bcf\u4e2a\u5355\u5143\u7684\u5c40\u90e8\u8d21\u732e\u7684\u8ba1\u7b97\u5b8c\u5168\u72ec\u7acb\u4e8e\u5176\u4ed6\u5355\u5143\uff0c\u6211\u4eec\u53ea\u9700\u8981\u5728\u5c06\u4e00\u4e2a\u5355\u5143\u7684\u8d21\u732e\u6dfb\u52a0\u5230\u5168\u5c40\u77e9\u9635\u4e2d\u65f6\u8fdb\u884c\u540c\u6b65\u3002\n\n    // \u6211\u4eec\u5728\u8fd9\u91cc\u9009\u62e9\u7684\u5e76\u884c\u5316\u7b56\u7565\u662f\u6587\u6863\u4e2d @ref threads \u6a21\u5757\u4e2d\u8be6\u7ec6\u63d0\u53ca\u7684\u53ef\u80fd\u6027\u4e4b\u4e00\u3002\u5177\u4f53\u6765\u8bf4\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u90a3\u91cc\u8ba8\u8bba\u7684WorkStream\u65b9\u6cd5\u3002\u7531\u4e8e\u8fd9\u4e2a\u6a21\u5757\u6709\u5f88\u591a\u6587\u6863\uff0c\u6211\u4eec\u4e0d\u4f1a\u5728\u8fd9\u91cc\u91cd\u590d\u8bbe\u8ba1\u9009\u62e9\u7684\u7406\u7531\uff08\u4f8b\u5982\uff0c\u5982\u679c\u4f60\u8bfb\u5b8c\u4e0a\u9762\u63d0\u5230\u7684\u6a21\u5757\uff0c\u4f60\u4f1a\u660e\u767d <code>AssemblyScratchData</code> \u548c <code>AssemblyCopyData</code> \u7ed3\u6784\u7684\u76ee\u7684\u662f\u4ec0\u4e48\uff09\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u5c06\u53ea\u8ba8\u8bba\u5177\u4f53\u7684\u5b9e\u73b0\u3002\n\n    // \u5982\u679c\u4f60\u9605\u8bfb\u4e86\u4e0a\u9762\u63d0\u5230\u7684\u9875\u9762\uff0c\u4f60\u4f1a\u53d1\u73b0\u4e3a\u4e86\u4f7f\u6c47\u7f16\u5e76\u884c\u5316\uff0c\u6211\u4eec\u9700\u8981\u4e24\u4e2a\u6570\u636e\u7ed3\u6784--\u4e00\u4e2a\u5bf9\u5e94\u4e8e\u6211\u4eec\u5728\u5c40\u90e8\u96c6\u6210\u8fc7\u7a0b\u4e2d\u9700\u8981\u7684\u6570\u636e\uff08\"scratch\n    // data\"\uff0c\u5373\u6211\u4eec\u53ea\u9700\u8981\u4f5c\u4e3a\u4e34\u65f6\u5b58\u50a8\u7684\u4e1c\u897f\uff09\uff0c\u53e6\u4e00\u4e2a\u662f\u5c06\u4fe1\u606f\u4ece\u5c40\u90e8\u96c6\u6210\u643a\u5e26\u5230\u51fd\u6570\u4e2d\uff0c\u7136\u540e\u5c06\u5c40\u90e8\u8d21\u732e\u6dfb\u52a0\u5230\u5168\u5c40\u77e9\u9635\u7684\u76f8\u5e94\u5143\u7d20\u4e2d\u3002\u5176\u4e2d\u524d\u8005\u901a\u5e38\u5305\u542bFEValues\u548cFEFaceValues\u5bf9\u8c61\uff0c\u800c\u540e\u8005\u5219\u6709\u5c40\u90e8\u77e9\u9635\u3001\u5c40\u90e8\u53f3\u624b\u8fb9\uff0c\u4ee5\u53ca\u5173\u4e8e\u54ea\u4e9b\u81ea\u7531\u5ea6\u751f\u6d3b\u5728\u6211\u4eec\u6b63\u5728\u7ec4\u88c5\u5c40\u90e8\u8d21\u732e\u7684\u5355\u5143\u4e0a\u7684\u4fe1\u606f\u3002\u6709\u4e86\u8fd9\u4e9b\u4fe1\u606f\uff0c\u4e0b\u9762\u7684\u5185\u5bb9\u5e94\u8be5\u662f\u76f8\u5bf9\u4e0d\u8a00\u81ea\u660e\u7684\u3002\n\n    struct AssemblyScratchData\n    {\n      AssemblyScratchData(const FiniteElement<dim> &fe);\n      AssemblyScratchData(const AssemblyScratchData &scratch_data);\n\n      // FEValues\u548cFEFaceValues\u662f\u5f88\u6602\u8d35\u7684\u8bbe\u7f6e\u5bf9\u8c61\uff0c\u6240\u4ee5\u6211\u4eec\u628a\u5b83\u4eec\u5305\u542b\u5728scratch\u5bf9\u8c61\u4e2d\uff0c\u4ee5\u4fbf\u5c3d\u53ef\u80fd\u591a\u7684\u6570\u636e\u5728\u5355\u5143\u683c\u4e4b\u95f4\u88ab\u91cd\u590d\u4f7f\u7528\u3002\n\n      FEValues<dim>     fe_values;\n      FEFaceValues<dim> fe_face_values;\n\n      // \u6211\u4eec\u8fd8\u5b58\u50a8\u4e86\u4e00\u4e9b\u5411\u91cf\uff0c\u6211\u4eec\u5c06\u5728\u6bcf\u4e2a\u5355\u5143\u683c\u4e0a\u586b\u5145\u6570\u503c\u3002\u5728\u901a\u5e38\u60c5\u51b5\u4e0b\uff0c\u8bbe\u7f6e\u8fd9\u4e9b\u5bf9\u8c61\u662f\u5f88\u4fbf\u5b9c\u7684\uff1b\u4f46\u662f\uff0c\u5b83\u4eec\u9700\u8981\u5185\u5b58\u5206\u914d\uff0c\u8fd9\u5728\u591a\u7ebf\u7a0b\u5e94\u7528\u7a0b\u5e8f\u4e2d\u53ef\u80fd\u5f88\u6602\u8d35\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u628a\u5b83\u4eec\u4fdd\u5b58\u5728\u8fd9\u91cc\uff0c\u8fd9\u6837\u5728\u4e00\u4e2a\u5355\u5143\u683c\u4e0a\u7684\u8ba1\u7b97\u5c31\u4e0d\u9700\u8981\u65b0\u7684\u5206\u914d\u3002\n\n      std::vector<double>         rhs_values;\n      std::vector<Tensor<1, dim>> advection_directions;\n      std::vector<double>         face_boundary_values;\n      std::vector<Tensor<1, dim>> face_advection_directions;\n\n      // \u6700\u540e\uff0c\u6211\u4eec\u9700\u8981\u63cf\u8ff0\u8be5\u95ee\u9898\u6570\u636e\u7684\u5bf9\u8c61\u3002\n\n      AdvectionField<dim> advection_field;\n      RightHandSide<dim>  right_hand_side;\n      BoundaryValues<dim> boundary_values;\n    };\n\n    struct AssemblyCopyData\n    {\n      FullMatrix<double>                   cell_matrix;\n      Vector<double>                       cell_rhs;\n      std::vector<types::global_dof_index> local_dof_indices;\n    };\n\n    void assemble_system();\n    void local_assemble_system(\n      const typename DoFHandler<dim>::active_cell_iterator &cell,\n      AssemblyScratchData &                                 scratch,\n      AssemblyCopyData &                                    copy_data);\n    void copy_local_to_global(const AssemblyCopyData &copy_data);\n\n    // \u4e0b\u9762\u7684\u51fd\u6570\u53c8\u548c\u524d\u9762\u7684\u4f8b\u5b50\u4e00\u6837\uff0c\u540e\u9762\u7684\u53d8\u91cf\u4e5f\u662f\u4e00\u6837\u7684\u3002\n\n    void solve();\n    void refine_grid();\n    void output_results(const unsigned int cycle) const;\n\n    Triangulation<dim> triangulation;\n    DoFHandler<dim>    dof_handler;\n\n    FE_Q<dim> fe;\n\n    AffineConstraints<double> hanging_node_constraints;\n\n    SparsityPattern      sparsity_pattern;\n    SparseMatrix<double> system_matrix;\n\n    Vector<double> solution;\n    Vector<double> system_rhs;\n  };\n\n  //  @sect3{GradientEstimation class declaration}\n\n  // \u73b0\u5728\uff0c\u6700\u540e\uff0c\u8fd9\u91cc\u6709\u4e00\u4e2a\u7c7b\uff0c\u5b83\u5c06\u8ba1\u7b97\u6bcf\u4e2a\u5355\u5143\u4e0a\u68af\u5ea6\u7684\u5dee\u5206\u8fd1\u4f3c\u503c\uff0c\u5e76\u4ee5\u7f51\u683c\u5927\u5c0f\u7684\u5e42\u6570\u8fdb\u884c\u6743\u8861\uff0c\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0\u3002\u8fd9\u4e2a\u7c7b\u662f\u5e93\u4e2d\n  // <code>DerivativeApproximation</code>\n  // \u7c7b\u7684\u4e00\u4e2a\u7b80\u5355\u7248\u672c\uff0c\u5b83\u4f7f\u7528\u7c7b\u4f3c\u7684\u6280\u672f\u6765\u83b7\u5f97\u6709\u9650\u5143\u573a\u7684\u68af\u5ea6\u7684\u6709\u9650\u5dee\u5206\u8fd1\u4f3c\u503c\uff0c\u6216\u8005\u66f4\u9ad8\u5bfc\u6570\u3002\n\n  // \u8be5\u7c7b\u6709\u4e00\u4e2a\u516c\u5171\u9759\u6001\u51fd\u6570 <code>estimate</code>\n  // \uff0c\u88ab\u8c03\u7528\u6765\u8ba1\u7b97\u8bef\u5dee\u6307\u6807\u7684\u5411\u91cf\uff0c\u8fd8\u6709\u4e00\u4e9b\u79c1\u6709\u51fd\u6570\uff0c\u5728\u6240\u6709\u6d3b\u52a8\u5355\u5143\u4e0a\u505a\u5b9e\u9645\u5de5\u4f5c\u3002\u5728\u5e93\u7684\u5176\u4ed6\u90e8\u5206\uff0c\u6211\u4eec\u9075\u5faa\u4e00\u4e2a\u975e\u6b63\u5f0f\u7684\u60ef\u4f8b\uff0c\u4f7f\u7528\u6d6e\u70b9\u6570\u5411\u91cf\u4f5c\u4e3a\u8bef\u5dee\u6307\u6807\uff0c\u800c\u4e0d\u662f\u5e38\u89c1\u7684\u53cc\u6570\u5411\u91cf\uff0c\u56e0\u4e3a\u5bf9\u4e8e\u4f30\u8ba1\u503c\u6765\u8bf4\uff0c\u989d\u5916\u7684\u7cbe\u5ea6\u662f\u6ca1\u6709\u5fc5\u8981\u7684\u3002\n\n  // \u9664\u4e86\u8fd9\u4e24\u4e2a\u51fd\u6570\uff0c\u8be5\u7c7b\u8fd8\u58f0\u660e\u4e86\u4e24\u4e2a\u5f02\u5e38\uff0c\u5f53\u4e00\u4e2a\u5355\u5143\u5728\u6bcf\u4e2a\u7a7a\u95f4\u65b9\u5411\u4e0a\u90fd\u6ca1\u6709\u90bb\u5c45\u65f6\uff08\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u4ecb\u7ecd\u4e2d\u63cf\u8ff0\u7684\u77e9\u9635\u5c06\u662f\u5947\u5f02\u7684\uff0c\u4e0d\u80fd\u88ab\u5012\u7f6e\uff09\uff0c\u800c\u53e6\u4e00\u4e2a\u5f02\u5e38\u7528\u4e8e\u66f4\u5e38\u89c1\u7684\u51fd\u6570\u53c2\u6570\u65e0\u6548\u7684\u60c5\u51b5\uff0c\u5373\u4e00\u4e2a\u5927\u5c0f\u9519\u8bef\u7684\u5411\u91cf\u3002\n\n  // \u8fd8\u6709\u4e24\u70b9\u610f\u89c1\uff1a\u9996\u5148\uff0c\u8fd9\u4e2a\u7c7b\u6ca1\u6709\u975e\u9759\u6001\u6210\u5458\u51fd\u6570\u6216\u53d8\u91cf\uff0c\u6240\u4ee5\u8fd9\u4e0d\u662f\u4e00\u4e2a\u771f\u6b63\u7684\u7c7b\uff0c\u800c\u662f\u8d77\u5230\u4e86C++\u4e2d\n  // <code>namespace</code>\n  // \u7684\u4f5c\u7528\u3002\u6211\u4eec\u9009\u62e9\u7c7b\u800c\u4e0d\u662f\u547d\u540d\u7a7a\u95f4\u7684\u539f\u56e0\u662f\uff0c\u8fd9\u79cd\u65b9\u5f0f\u6211\u4eec\u53ef\u4ee5\u58f0\u660e\u79c1\u6709\u7684\u51fd\u6570\u3002\u5982\u679c\u5728\u547d\u540d\u7a7a\u95f4\u7684\u5934\u6587\u4ef6\u4e2d\u58f0\u660e\u4e00\u4e9b\u51fd\u6570\uff0c\u5e76\u5728\u5b9e\u73b0\u6587\u4ef6\u4e2d\u5b9e\u73b0\u8fd9\u4e9b\u51fd\u6570\u548c\u5176\u4ed6\u51fd\u6570\uff0c\u8fd9\u4e5f\u53ef\u4ee5\u7528\u547d\u540d\u7a7a\u95f4\u6765\u5b9e\u73b0\u3002\u6ca1\u6709\u5728\u5934\u6587\u4ef6\u4e2d\u58f0\u660e\u7684\u51fd\u6570\u4ecd\u7136\u5728\u540d\u5b57\u7a7a\u95f4\u4e2d\uff0c\u4f46\u4e0d\u80fd\u4ece\u5916\u90e8\u8c03\u7528\u3002\u7136\u800c\uff0c\u7531\u4e8e\u6211\u4eec\u8fd9\u91cc\u53ea\u6709\u4e00\u4e2a\u6587\u4ef6\uff0c\u5728\u76ee\u524d\u7684\u60c5\u51b5\u4e0b\u4e0d\u53ef\u80fd\u9690\u85cf\u51fd\u6570\u3002\n\n  // \u7b2c\u4e8c\u4e2a\u610f\u89c1\u662f\uff0c\u7ef4\u5ea6\u6a21\u677f\u53c2\u6570\u88ab\u9644\u5728\u51fd\u6570\u4e0a\uff0c\u800c\u4e0d\u662f\u9644\u5728\u7c7b\u672c\u8eab\u3002\u8fd9\u6837\uff0c\u4f60\u5c31\u4e0d\u5fc5\u50cf\u5176\u4ed6\u5927\u591a\u6570\u60c5\u51b5\u4e0b\u90a3\u6837\u81ea\u5df1\u6307\u5b9a\u6a21\u677f\u53c2\u6570\uff0c\u800c\u662f\u7f16\u8bd1\u5668\u53ef\u4ee5\u4ece\u4f5c\u4e3a\u7b2c\u4e00\u4e2a\u53c2\u6570\u4f20\u9012\u7684DoFHandler\u5bf9\u8c61\u7684\u5c3a\u5bf8\u4e2d\u81ea\u884c\u8ba1\u7b97\u51fa\u5176\u503c\u3002\n\n  // \u5728\u5f00\u59cb\u5b9e\u65bd\u4e4b\u524d\uff0c\u8ba9\u6211\u4eec\u4e5f\u6765\u8bc4\u8bba\u4e00\u4e0b\u5e76\u884c\u5316\u7b56\u7565\u3002\u6211\u4eec\u5df2\u7ecf\u5728\u4e0a\u9762\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u7684\u58f0\u660e\u4e2d\u4ecb\u7ecd\u4e86\u4f7f\u7528WorkStream\u6982\u5ff5\u7684\u5fc5\u8981\u6846\u67b6\u3002\u6211\u4eec\u5c06\u5728\u8fd9\u91cc\u518d\u6b21\u4f7f\u7528\u5b83\u3002\u5728\u76ee\u524d\u7684\u60c5\u51b5\u4e0b\uff0c\u8fd9\u610f\u5473\u7740\u6211\u4eec\u5fc5\u987b\u5b9a\u4e49\n  // <ol>  \u3002\n  // <li> \u7c7b\uff0c\u7528\u4e8e\u6293\u53d6\u548c\u590d\u5236\u5bf9\u8c61\uff0c </li>  \u3002\n  // <li>  \u4e00\u4e2a\u5728\u4e00\u4e2a\u5355\u5143\u4e0a\u8fdb\u884c\u5c40\u90e8\u8ba1\u7b97\u7684\u51fd\u6570\uff0c\u4ee5\u53ca </li>\n  // <li>  \u4e00\u4e2a\u5c06\u672c\u5730\u7ed3\u679c\u590d\u5236\u5230\u5168\u5c40\u5bf9\u8c61\u7684\u51fd\u6570\u3002 </li>\n  // </ol>\n  // \u9274\u4e8e\u8fd9\u4e2a\u603b\u4f53\u6846\u67b6\uff0c\u6211\u4eec\u5c06\u7a0d\u5fae\u504f\u79bb\u5b83\u3002\u7279\u522b\u662f\uff0cWorkStream\u4e00\u822c\u662f\u4e3a\u8fd9\u6837\u7684\u60c5\u51b5\u800c\u53d1\u660e\u7684\uff0c\u5373\u6bcf\u4e2a\u5355\u5143\u4e0a\u7684\u5c40\u90e8\u8ba1\u7b97<i>adds</i>\u5230\u4e00\u4e2a\u5168\u5c40\u5bf9\u8c61--\u4f8b\u5982\uff0c\u5728\u7ec4\u88c5\u7ebf\u6027\u7cfb\u7edf\u65f6\uff0c\u6211\u4eec\u5c06\u5c40\u90e8\u8d21\u732e\u6dfb\u52a0\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u4e2d\u3002WorkStream\u7684\u8bbe\u8ba1\u662f\u4e3a\u4e86\u5904\u7406\u591a\u4e2a\u7ebf\u7a0b\u8bd5\u56fe\u540c\u65f6\u8fdb\u884c\u8fd9\u79cd\u6dfb\u52a0\u7684\u6f5c\u5728\u51b2\u7a81\uff0c\u56e0\u6b64\u5fc5\u987b\u63d0\u4f9b\u4e00\u4e9b\u65b9\u6cd5\u6765\u786e\u4fdd\u6bcf\u6b21\u53ea\u6709\u4e00\u4e2a\u7ebf\u7a0b\u53ef\u4ee5\u505a\u8fd9\u4e2a\u3002\u7136\u800c\uff0c\u8fd9\u91cc\u7684\u60c5\u51b5\u7565\u6709\u4e0d\u540c\uff1a\u6211\u4eec\u5355\u72ec\u8ba1\u7b97\u6bcf\u4e2a\u5355\u5143\u7684\u8d21\u732e\uff0c\u4f46\u968f\u540e\u6211\u4eec\u9700\u8981\u505a\u7684\u662f\u5c06\u5b83\u4eec\u653e\u5165\u6bcf\u4e2a\u5355\u5143\u72ec\u6709\u7684\u8f93\u51fa\u5411\u91cf\u4e2d\u7684\u4e00\u4e2a\u5143\u7d20\u3002\u56e0\u6b64\uff0c\u4e0d\u5b58\u5728\u6765\u81ea\u4e24\u4e2a\u5355\u5143\u7684\u5199\u64cd\u4f5c\u53ef\u80fd\u53d1\u751f\u51b2\u7a81\u7684\u98ce\u9669\uff0c\u4e5f\u6ca1\u6709\u5fc5\u8981\u4f7f\u7528WorkStream\u7684\u590d\u6742\u673a\u5236\u6765\u907f\u514d\u51b2\u7a81\u7684\u5199\u64cd\u4f5c\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u8981\u505a\u7684\u5c31\u662f\u8fd9\u6837\u3002\u6211\u4eec\u4ecd\u7136\u9700\u8981\u4e00\u4e2a\u6301\u6709\u4f8b\u5982\n  // FEValues \u5bf9\u8c61\u7684 scratch\n  // \u5bf9\u8c61\u3002\u4f46\u662f\uff0c\u6211\u4eec\u53ea\u521b\u5efa\u4e00\u4e2a\u5047\u7684\u3001\u7a7a\u7684\u62f7\u8d1d\u6570\u636e\u7ed3\u6784\u3002\u540c\u6837\uff0c\u6211\u4eec\u786e\u5b9e\u9700\u8981\u8ba1\u7b97\u672c\u5730\u8d21\u732e\u7684\u51fd\u6570\uff0c\u4f46\u7531\u4e8e\u5b83\u5df2\u7ecf\u53ef\u4ee5\u628a\u7ed3\u679c\u653e\u5230\u6700\u7ec8\u4f4d\u7f6e\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u4e00\u4e2a\u4ece\u672c\u5730\u5230\u5168\u7403\u7684\u62f7\u8d1d\u51fd\u6570\uff0c\u800c\u662f\u7ed9\n  // WorkStream::run() \u51fd\u6570\u4e00\u4e2a\u7a7a\u51fd\u6570\u5bf9\u8c61--\u76f8\u5f53\u4e8e\u4e00\u4e2aNULL\u51fd\u6570\u6307\u9488\u3002\n\n  class GradientEstimation\n  {\n  public:\n    template <int dim>\n    static void estimate(const DoFHandler<dim> &dof,\n                         const Vector<double> & solution,\n                         Vector<float> &        error_per_cell);\n\n    DeclException2(ExcInvalidVectorLength,\n                   int,\n                   int,\n                   << \"Vector has length \" << arg1 << \", but should have \"\n                   << arg2);\n    DeclException0(ExcInsufficientDirections);\n\n  private:\n    template <int dim>\n    struct EstimateScratchData\n    {\n      EstimateScratchData(const FiniteElement<dim> &fe,\n                          const Vector<double> &    solution,\n                          Vector<float> &           error_per_cell);\n      EstimateScratchData(const EstimateScratchData &data);\n\n      FEValues<dim> fe_midpoint_value;\n      std::vector<typename DoFHandler<dim>::active_cell_iterator>\n        active_neighbors;\n\n      const Vector<double> &solution;\n      Vector<float> &       error_per_cell;\n\n      std::vector<double> cell_midpoint_value;\n      std::vector<double> neighbor_midpoint_value;\n    };\n\n    struct EstimateCopyData\n    {};\n\n    template <int dim>\n    static void\n    estimate_cell(const typename DoFHandler<dim>::active_cell_iterator &cell,\n                  EstimateScratchData<dim> &scratch_data,\n                  const EstimateCopyData &  copy_data);\n  };\n\n  //  @sect3{AdvectionProblem class implementation}\n\n  // \u73b0\u5728\u662f\u4e3b\u7c7b\u7684\u5b9e\u73b0\u3002\u6784\u9020\u5668\u3001\u6790\u6784\u5668\u548c\u51fd\u6570 <code>setup_system</code>\n  // \u9075\u5faa\u4e4b\u524d\u4f7f\u7528\u7684\u6a21\u5f0f\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u9700\u8981\u5bf9\u8fd9\u4e09\u4e2a\u51fd\u6570\u8fdb\u884c\u8bc4\u8bba\u3002\n\n  template <int dim>\n  AdvectionProblem<dim>::AdvectionProblem() /* \u7b2c\u4e00\u6b65\uff0c\u7c7b\u6784\u9020\u51fd\u6570 */\n    : dof_handler(triangulation)\n    , fe(5)\n  {}\n\n  template <int dim>\n  void AdvectionProblem<dim>::setup_system()\n  {\n    dof_handler.distribute_dofs(fe);\n    hanging_node_constraints.clear();\n    DoFTools::make_hanging_node_constraints(dof_handler,\n                                            hanging_node_constraints);\n    hanging_node_constraints.close();\n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs());\n    DoFTools::make_sparsity_pattern(dof_handler,\n                                    dsp,\n                                    hanging_node_constraints,\n                                    /*keep_constrained_dofs =  */ false);\n\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  // \u5728\u4e0b\u9762\u7684\u51fd\u6570\u4e2d\uff0c\u77e9\u9635\u548c\u53f3\u624b\u88ab\u7ec4\u88c5\u8d77\u6765\u3002\u6b63\u5982\u4e0a\u9762main\u7c7b\u7684\u6587\u6863\u6240\u8ff0\uff0c\u5b83\u672c\u8eab\u5e76\u4e0d\u505a\u8fd9\u4e2a\uff0c\u800c\u662f\u59d4\u6258\u7ed9\u63a5\u4e0b\u6765\u7684\u51fd\u6570\uff0c\u5229\u7528 @ref threads \u4e2d\u8ba8\u8bba\u7684WorkStream\u6982\u5ff5\u3002\n\n  // \u5982\u679c\u4f60\u770b\u4e86 @ref threads \u6a21\u5757\uff0c\u4f60\u4f1a\u53d1\u73b0\u5e76\u884c\u88c5\u914d\u5e76\u4e0d\u9700\u8981\u5927\u91cf\u7684\u989d\u5916\u4ee3\u7801\uff0c\u53ea\u8981\u4f60\u8ba4\u771f\u5730\u63cf\u8ff0\u4ec0\u4e48\u662f\u4ece\u5934\u5f00\u59cb\u548c\u590d\u5236\u6570\u636e\u5bf9\u8c61\uff0c\u5982\u679c\u4f60\u4e3a\u672c\u5730\u88c5\u914d\u548c\u4ece\u672c\u5730\u8d21\u732e\u5230\u5168\u5c40\u5bf9\u8c61\u7684\u590d\u5236\u64cd\u4f5c\u5b9a\u4e49\u4e86\u5408\u9002\u7684\u51fd\u6570\u3002\u5b8c\u6210\u8fd9\u4e9b\u5de5\u4f5c\u540e\uff0c\u4e0b\u9762\u5c06\u5b8c\u6210\u6240\u6709\u7e41\u91cd\u7684\u5de5\u4f5c\uff0c\u4f7f\u8fd9\u4e9b\u64cd\u4f5c\u5728\u591a\u4e2a\u7ebf\u7a0b\u4e0a\u5b8c\u6210\uff0c\u53ea\u8981\u4f60\u7684\u7cfb\u7edf\u6709\u591a\u5c11\u4e2a\u5185\u6838\u3002\n\n  template <int dim>\n  void AdvectionProblem<dim>::assemble_system()\n  {\n    WorkStream::run(dof_handler.begin_active(),\n                    dof_handler.end(),\n                    *this,\n                    &AdvectionProblem::local_assemble_system,\n                    &AdvectionProblem::copy_local_to_global,\n                    AssemblyScratchData(fe),\n                    AssemblyCopyData());\n  }\n\n  // \u6b63\u5982\u4e0a\u9762\u5df2\u7ecf\u63d0\u5230\u7684\uff0c\u6211\u4eec\u9700\u8981\u6709\u6293\u53d6\u5bf9\u8c61\u6765\u8fdb\u884c\u5c40\u90e8\u8d21\u732e\u7684\u5e76\u884c\u8ba1\u7b97\u3002\u8fd9\u4e9b\u5bf9\u8c61\u5305\u542bFEValues\u548cFEFaceValues\u5bf9\u8c61\uff08\u4ee5\u53ca\u4e00\u4e9b\u6570\u7ec4\uff09\uff0c\u56e0\u6b64\u6211\u4eec\u9700\u8981\u6709\u6784\u9020\u51fd\u6570\u548c\u590d\u5236\u6784\u9020\u51fd\u6570\uff0c\u4ee5\u4fbf\u6211\u4eec\u80fd\u591f\u521b\u5efa\u5b83\u4eec\u3002\u5bf9\u4e8e\u5355\u5143\u9879\uff0c\u6211\u4eec\u9700\u8981\u5f62\u72b6\u51fd\u6570\u7684\u503c\u548c\u68af\u5ea6\u3001\u6b63\u4ea4\u70b9\u4ee5\u786e\u5b9a\u7ed9\u5b9a\u70b9\u7684\u6e90\u5bc6\u5ea6\u548c\u5e73\u6d41\u573a\uff0c\u4ee5\u53ca\u6b63\u4ea4\u70b9\u7684\u6743\u91cd\u4e58\u4ee5\u8fd9\u4e9b\u70b9\u7684\u96c5\u5404\u5e03\u7cfb\u6570\u7684\u884c\u5217\u5f0f\u3002\u76f8\u53cd\uff0c\u5bf9\u4e8e\u8fb9\u754c\u79ef\u5206\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u68af\u5ea6\uff0c\u800c\u662f\u9700\u8981\u5355\u5143\u7684\u6cd5\u5411\u91cf\u3002\u8fd9\u51b3\u5b9a\u4e86\u6211\u4eec\u5fc5\u987b\u5c06\u54ea\u4e9b\u66f4\u65b0\u6807\u5fd7\u4f20\u9012\u7ed9\u7c7b\u7684\u6210\u5458\u7684\u6784\u9020\u51fd\u6570\u3002\n\n  template <int dim>\n  AdvectionProblem<dim>::AssemblyScratchData::AssemblyScratchData(\n    const FiniteElement<dim> &fe)\n    : fe_values(fe,\n                QGauss<dim>(fe.degree + 1),\n                update_values | update_gradients | update_quadrature_points |\n                  update_JxW_values)\n    , fe_face_values(fe,\n                     QGauss<dim - 1>(fe.degree + 1),\n                     update_values | update_quadrature_points |\n                       update_JxW_values | update_normal_vectors)\n    , rhs_values(fe_values.get_quadrature().size())\n    , advection_directions(fe_values.get_quadrature().size())\n    , face_boundary_values(fe_face_values.get_quadrature().size())\n    , face_advection_directions(fe_face_values.get_quadrature().size())\n  {}\n\n  template <int dim>\n  AdvectionProblem<dim>::AssemblyScratchData::AssemblyScratchData(\n    const AssemblyScratchData &scratch_data)\n    : fe_values(scratch_data.fe_values.get_fe(),\n                scratch_data.fe_values.get_quadrature(),\n                update_values | update_gradients | update_quadrature_points |\n                  update_JxW_values)\n    , fe_face_values(scratch_data.fe_face_values.get_fe(),\n                     scratch_data.fe_face_values.get_quadrature(),\n                     update_values | update_quadrature_points |\n                       update_JxW_values | update_normal_vectors)\n    , rhs_values(scratch_data.rhs_values.size())\n    , advection_directions(scratch_data.advection_directions.size())\n    , face_boundary_values(scratch_data.face_boundary_values.size())\n    , face_advection_directions(scratch_data.face_advection_directions.size())\n  {}\n\n  // \u73b0\u5728\uff0c\u8fd9\u5c31\u662f\u505a\u5b9e\u9645\u5de5\u4f5c\u7684\u51fd\u6570\u3002\u5b83\u4e0e\u524d\u9762\u4f8b\u5b50\u7a0b\u5e8f\u4e2d\u7684\n  // <code>assemble_system</code>\n  // \u51fd\u6570\u6ca1\u6709\u4ec0\u4e48\u4e0d\u540c\uff0c\u6240\u4ee5\u6211\u4eec\u5c06\u518d\u6b21\u53ea\u5bf9\u5176\u4e0d\u540c\u4e4b\u5904\u8fdb\u884c\u8bc4\u8bba\u3002\u6570\u5b66\u4e0a\u7684\u4e1c\u897f\u7d27\u8ddf\u6211\u4eec\u5728\u4ecb\u7ecd\u4e2d\u6240\u8bf4\u7684\u3002\n\n  // \u4e0d\u8fc7\uff0c\u8fd9\u91cc\u6709\u4e00\u4e9b\u503c\u5f97\u4e00\u63d0\u7684\u5730\u65b9\u3002\u9996\u5148\uff0c\u6211\u4eec\u628aFEValues\u548cFEFaceValues\u5bf9\u8c61\u79fb\u5230\u4e86ScratchData\u5bf9\u8c61\u4e2d\u3002\u6211\u4eec\u8fd9\u6837\u505a\u662f\u56e0\u4e3a\u6211\u4eec\u6bcf\u6b21\u8fdb\u5165\u8fd9\u4e2a\u51fd\u6570\u65f6\u90fd\u8981\u7b80\u5355\u5730\u521b\u5efa\u4e00\u4e2a\uff0c\u4e5f\u5c31\u662f\u5728\u6bcf\u4e2a\u5355\u5143\u683c\u4e0a\u3002\u73b0\u5728\u53d1\u73b0\uff0cFEValues\u7c7b\u7684\u7f16\u5199\u76ee\u6807\u5f88\u660e\u786e\uff0c\u5c31\u662f\u5c06\u6240\u6709\u4ece\u5355\u5143\u683c\u5230\u5355\u5143\u683c\u4fdd\u6301\u4e0d\u53d8\u7684\u4e1c\u897f\u90fd\u79fb\u5230\u5bf9\u8c61\u7684\u6784\u9020\u4e2d\uff0c\u6bcf\u5f53\u6211\u4eec\u79fb\u5230\u4e00\u4e2a\u65b0\u5355\u5143\u683c\u65f6\uff0c\u53ea\u5728\n  // FEValues::reinit()\n  // \u505a\u5c3d\u53ef\u80fd\u5c11\u7684\u5de5\u4f5c\u3002\u8fd9\u610f\u5473\u7740\u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\u521b\u5efa\u4e00\u4e2a\u8fd9\u6837\u7684\u65b0\u5bf9\u8c61\u662f\u975e\u5e38\u6602\u8d35\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u5fc5\u987b\u4e3a\u6bcf\u4e00\u4e2a\u5355\u5143\u683c\u90fd\u8fd9\u6837\u505a--\u8fd9\u6b63\u662f\u6211\u4eec\u60f3\u901a\u8fc7FEValues\u7c7b\u6765\u907f\u514d\u7684\u4e8b\u60c5\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u6240\u505a\u7684\u662f\u5728\u6293\u53d6\u5bf9\u8c61\u4e2d\u53ea\u521b\u5efa\u4e00\u6b21\uff08\u6216\u5c11\u6570\u51e0\u6b21\uff09\uff0c\u7136\u540e\u5c3d\u53ef\u80fd\u591a\u5730\u91cd\u590d\u4f7f\u7528\u5b83\u3002\n\n  // \u8fd9\u5c31\u5f15\u51fa\u4e86\u4e00\u4e2a\u95ee\u9898\uff1a\u6211\u4eec\u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\u521b\u5efa\u7684\u5176\u4ed6\u5bf9\u8c61\uff0c\u4e0e\u5b83\u7684\u4f7f\u7528\u76f8\u6bd4\uff0c\u5176\u521b\u5efa\u6210\u672c\u5f88\u9ad8\u3002\u4e8b\u5b9e\u4e0a\uff0c\u5728\u51fd\u6570\u7684\u9876\u90e8\uff0c\u6211\u4eec\u58f0\u660e\u4e86\u5404\u79cd\u5404\u6837\u7684\u5bf9\u8c61\u3002\n  // <code>AdvectionField</code>  ,  <code>RightHandSide</code> and\n  // <code>BoundaryValues</code>\n  // \u7684\u521b\u5efa\u6210\u672c\u5e76\u4e0d\u9ad8\uff0c\u6240\u4ee5\u8fd9\u91cc\u6ca1\u6709\u4ec0\u4e48\u5371\u5bb3\u3002\u7136\u800c\uff0c\u5728\u521b\u5efa\n  // <code>rhs_values</code>\n  // \u548c\u4e0b\u9762\u7c7b\u4f3c\u7684\u53d8\u91cf\u65f6\uff0c\u5206\u914d\u5185\u5b58\u901a\u5e38\u8981\u82b1\u8d39\u5927\u91cf\u7684\u65f6\u95f4\uff0c\u800c\u53ea\u662f\u8bbf\u95ee\u6211\u4eec\u5b58\u50a8\u5728\u5176\u4e2d\u7684\uff08\u4e34\u65f6\uff09\u503c\u3002\u56e0\u6b64\uff0c\u8fd9\u4e9b\u5c06\u662f\u79fb\u5165\n  // <code>AssemblyScratchData</code> \u7c7b\u7684\u5019\u9009\u8005\u3002\u6211\u4eec\u5c06\u628a\u8fd9\u4f5c\u4e3a\u4e00\u4e2a\u7ec3\u4e60\u3002\n\n  template <int dim>\n  void AdvectionProblem<dim>::local_assemble_system(\n    const typename DoFHandler<dim>::active_cell_iterator &cell,\n    AssemblyScratchData &                                 scratch_data,\n    AssemblyCopyData &                                    copy_data)\n  {\n    // \u6211\u4eec\u5b9a\u4e49\u4e00\u4e9b\u7f29\u5199\uff0c\u4ee5\u907f\u514d\u4e0d\u5fc5\u8981\u7684\u957f\u884c\u3002\n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell();\n    const unsigned int n_q_points =\n      scratch_data.fe_values.get_quadrature().size();\n    const unsigned int n_face_q_points =\n      scratch_data.fe_face_values.get_quadrature().size();\n\n    // \u6211\u4eec\u58f0\u660e\u5355\u5143\u683c\u77e9\u9635\u548c\u5355\u5143\u683c\u53f3\u4fa7...\n\n    copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n    copy_data.cell_rhs.reinit(dofs_per_cell);\n\n    // ...\u4e00\u4e2a\u6570\u7ec4\uff0c\u7528\u4e8e\u4fdd\u5b58\u6211\u4eec\u76ee\u524d\u6b63\u5728\u5904\u7406\u7684\u5355\u5143\u683c\u7684\u81ea\u7531\u5ea6\u7684\u5168\u5c40\u7d22\u5f15...\n\n    copy_data.local_dof_indices.resize(dofs_per_cell);\n\n    // ...\u7136\u540e\u521d\u59cb\u5316 <code>FEValues</code> \u5bf9\u8c61...\n\n    scratch_data.fe_values.reinit(cell);\n\n    // ... \u83b7\u5f97\u6b63\u4ea4\u70b9\u7684\u53f3\u624b\u8fb9\u548c\u5e73\u6d41\u65b9\u5411\u7684\u6570\u503c...\n\n    scratch_data.advection_field.value_list(\n      scratch_data.fe_values.get_quadrature_points(),\n      scratch_data.advection_directions);\n    scratch_data.right_hand_side.value_list(\n      scratch_data.fe_values.get_quadrature_points(), scratch_data.rhs_values);\n\n    // ... \u8bbe\u7f6e\u6d41\u7ebf\u6269\u6563\u53c2\u6570\u7684\u503c\uff0c\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0...\n\n    const double delta = 0.1 * cell->diameter();\n\n    // ...... \u5e76\u6309\u7167\u4e0a\u9762\u7684\u8ba8\u8bba\uff0c\u96c6\u5408\u5bf9\u7cfb\u7edf\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u5c40\u90e8\u8d21\u732e\u3002\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          // \u522b\u540dAssemblyScratchData\u5bf9\u8c61\uff0c\u4ee5\u9632\u6b62\u884c\u6570\u8fc7\u957f\u3002\n\n          const auto &sd = scratch_data;\n          for (unsigned int j = 0; j < dofs_per_cell; ++j)\n            copy_data.cell_matrix(i, j) +=\n              ((sd.fe_values.shape_value(i, q_point) +           // (phi_i +\n                delta * (sd.advection_directions[q_point] *      // delta beta\n                         sd.fe_values.shape_grad(i, q_point))) * // grad phi_i)\n               sd.advection_directions[q_point] *                // beta\n               sd.fe_values.shape_grad(j, q_point)) *            // grad phi_j\n              sd.fe_values.JxW(q_point);                         // dx\n\n          copy_data.cell_rhs(i) +=\n            (sd.fe_values.shape_value(i, q_point) +           // (phi_i +\n             delta * (sd.advection_directions[q_point] *      // delta beta\n                      sd.fe_values.shape_grad(i, q_point))) * // grad phi_i)\n            sd.rhs_values[q_point] *                          // f\n            sd.fe_values.JxW(q_point);                        // dx\n        }\n\n    // \u9664\u4e86\u6211\u4eec\u73b0\u5728\u5efa\u7acb\u7684\u5355\u5143\u9879\uff0c\u672c\u95ee\u9898\u7684\u53cc\u7ebf\u6027\u5f62\u5f0f\u8fd8\u5305\u542b\u57df\u7684\u8fb9\u754c\u4e0a\u7684\u9879\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5fc5\u987b\u68c0\u67e5\u8fd9\u4e2a\u5355\u5143\u7684\u4efb\u4f55\u4e00\u4e2a\u9762\u662f\u5426\u5728\u57df\u7684\u8fb9\u754c\u4e0a\uff0c\u5982\u679c\u662f\u7684\u8bdd\uff0c\u4e5f\u8981\u628a\u8fd9\u4e2a\u9762\u7684\u8d21\u732e\u96c6\u5408\u8d77\u6765\u3002\u5f53\u7136\uff0c\u53cc\u7ebf\u6027\u5f62\u5f0f\u53ea\u5305\u542b\u6765\u81ea\u8fb9\u754c\n    // <code>inflow</code>\n    // \u90e8\u5206\u7684\u8d21\u732e\uff0c\u4f46\u8981\u627e\u51fa\u672c\u5355\u5143\u7684\u67d0\u4e2a\u9762\u662f\u5426\u5c5e\u4e8e\u6d41\u5165\u8fb9\u754c\u7684\u4e00\u90e8\u5206\uff0c\u6211\u4eec\u5fc5\u987b\u6709\u5173\u4e8e\u6b63\u4ea4\u70b9\u7684\u786e\u5207\u4f4d\u7f6e\u548c\u8be5\u70b9\u7684\u6d41\u52a8\u65b9\u5411\u7684\u4fe1\u606f\uff1b\u6211\u4eec\u4f7f\u7528FEFaceValues\u5bf9\u8c61\u83b7\u5f97\u8fd9\u4e9b\u4fe1\u606f\uff0c\u5e76\u53ea\u5728\u4e3b\u5faa\u73af\u4e2d\u51b3\u5b9a\u67d0\u4e2a\u6b63\u4ea4\u70b9\u662f\u5426\u5728\u6d41\u5165\u8fb9\u754c\u4e0a\u3002\n\n    for (const auto &face : cell->face_iterators())\n      if (face->at_boundary())\n        {\n          // \u597d\u7684\uff0c\u5f53\u524d\u5355\u5143\u683c\u7684\u8fd9\u4e2a\u9762\u662f\u5728\u57df\u7684\u8fb9\u754c\u4e0a\u3002\u5c31\u50cf\u6211\u4eec\u5728\u524d\u9762\u7684\u4f8b\u5b50\u548c\u4e0a\u9762\u7684\u4f8b\u5b50\u4e2d\u4f7f\u7528\u7684\u901a\u5e38\u7684FEValues\u5bf9\u8c61\u4e00\u6837\uff0c\u6211\u4eec\u5fc5\u987b\u91cd\u65b0\u521d\u59cb\u5316\u5f53\u524d\u9762\u7684FEFaceValues\u5bf9\u8c61\u3002\n\n          scratch_data.fe_face_values.reinit(cell, face);\n\n          // \u5bf9\u4e8e\u624b\u5934\u7684\u6b63\u4ea4\u70b9\uff0c\u6211\u4eec\u8981\u6c42\u63d0\u4f9b\u6d41\u5165\u51fd\u6570\u7684\u503c\u548c\u6d41\u52a8\u65b9\u5411\u3002\n\n          scratch_data.boundary_values.value_list(\n            scratch_data.fe_face_values.get_quadrature_points(),\n            scratch_data.face_boundary_values);\n          scratch_data.advection_field.value_list(\n            scratch_data.fe_face_values.get_quadrature_points(),\n            scratch_data.face_advection_directions);\n\n          // \u73b0\u5728\u5faa\u73af\u6240\u6709\u6b63\u4ea4\u70b9\uff0c\u770b\u770b\u8fd9\u4e2a\u9762\u662f\u5728\u8fb9\u754c\u7684\u6d41\u5165\u8fd8\u662f\u6d41\u51fa\u90e8\u5206\u3002\u6cd5\u5411\u91cf\u6307\u5411\u5355\u5143\u5916\uff1a\u7531\u4e8e\u8be5\u9762\u5904\u4e8e\u8fb9\u754c\uff0c\u6cd5\u5411\u91cf\u6307\u5411\u57df\u5916\uff0c\u6240\u4ee5\u5982\u679c\u5e73\u6d41\u65b9\u5411\u6307\u5411\u57df\u5185\uff0c\u5176\u4e0e\u6cd5\u5411\u91cf\u7684\u6807\u91cf\u4e58\u79ef\u4e00\u5b9a\u662f\u8d1f\u7684\uff08\u8981\u77e5\u9053\u4e3a\u4ec0\u4e48\u4f1a\u8fd9\u6837\uff0c\u8bf7\u8003\u8651\u4f7f\u7528\u4f59\u5f26\u7684\u6807\u91cf\u4e58\u79ef\u5b9a\u4e49\uff09\u3002\n\n          for (unsigned int q_point = 0; q_point < n_face_q_points; ++q_point)\n            if (scratch_data.fe_face_values.normal_vector(q_point) *\n                  scratch_data.face_advection_directions[q_point] <\n                0.)\n\n              // \u5982\u679c\u8be5\u9762\u662f\u6d41\u5165\u8fb9\u754c\u7684\u4e00\u90e8\u5206\uff0c\u5219\u4f7f\u7528\u4eceFEFaceValues\u5bf9\u8c61\u4e2d\u83b7\u5f97\u7684\u503c\u548c\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u516c\u5f0f\uff0c\u8ba1\u7b97\u8be5\u9762\u5bf9\u5168\u5c40\u77e9\u9635\u548c\u53f3\u4fa7\u7684\u8d21\u732e\u3002\n\n              for (unsigned int i = 0; i < dofs_per_cell; ++i)\n                {\n                  for (unsigned int j = 0; j < dofs_per_cell; ++j)\n                    copy_data.cell_matrix(i, j) -=\n                      (scratch_data.face_advection_directions[q_point] *\n                       scratch_data.fe_face_values.normal_vector(q_point) *\n                       scratch_data.fe_face_values.shape_value(i, q_point) *\n                       scratch_data.fe_face_values.shape_value(j, q_point) *\n                       scratch_data.fe_face_values.JxW(q_point));\n\n                  copy_data.cell_rhs(i) -=\n                    (scratch_data.face_advection_directions[q_point] *\n                     scratch_data.fe_face_values.normal_vector(q_point) *\n                     scratch_data.face_boundary_values[q_point] *\n                     scratch_data.fe_face_values.shape_value(i, q_point) *\n                     scratch_data.fe_face_values.JxW(q_point));\n                }\n        }\n\n    // \u590d\u5236\u7a0b\u5e8f\u9700\u8981\u7684\u6700\u540e\u4e00\u6761\u4fe1\u606f\u662f\u8fd9\u4e2a\u5355\u5143\u4e0a\u81ea\u7531\u5ea6\u7684\u5168\u5c40\u7d22\u5f15\uff0c\u6240\u4ee5\u6211\u4eec\u6700\u540e\u628a\u5b83\u4eec\u5199\u5230\u672c\u5730\u6570\u7ec4\u4e2d\u3002\n\n    cell->get_dof_indices(copy_data.local_dof_indices);\n  }\n\n  // \u6211\u4eec\u9700\u8981\u5199\u7684\u7b2c\u4e8c\u4e2a\u51fd\u6570\u662f\u5c06\u524d\u4e00\u4e2a\u51fd\u6570\u8ba1\u7b97\u51fa\u7684\u672c\u5730\u8d21\u732e\uff08\u5e76\u653e\u5165AssemblyCopyData\u5bf9\u8c61\uff09\u590d\u5236\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u4fa7\u5411\u91cf\u5bf9\u8c61\u3002\u8fd9\u57fa\u672c\u4e0a\u5c31\u662f\u6211\u4eec\u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\u88c5\u914d\u4e1c\u897f\u65f6\uff0c\u4e00\u76f4\u4f5c\u4e3a\u6700\u540e\u4e00\u5757\u4ee3\u7801\u7684\u5185\u5bb9\u3002\u56e0\u6b64\uff0c\u4e0b\u9762\u7684\u5185\u5bb9\u5e94\u8be5\u662f\u5f88\u660e\u663e\u7684\u3002\n\n  template <int dim>\n  void\n  AdvectionProblem<dim>::copy_local_to_global(const AssemblyCopyData &copy_data)\n  {\n    hanging_node_constraints.distribute_local_to_global(\n      copy_data.cell_matrix,\n      copy_data.cell_rhs,\n      copy_data.local_dof_indices,\n      system_matrix,\n      system_rhs);\n  }\n\n  // \u8fd9\u91cc\u662f\u7ebf\u6027\u6c42\u89e3\u7a0b\u5e8f\u3002\u7531\u4e8e\u7cfb\u7edf\u4e0d\u518d\u50cf\u4ee5\u524d\u7684\u4f8b\u5b50\u90a3\u6837\u662f\u5bf9\u79f0\u6b63\u5b9a\u7684\uff0c\u6211\u4eec\u4e0d\u80fd\u518d\u4f7f\u7528\u5171\u8f6d\u68af\u5ea6\u6cd5\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u66f4\u901a\u7528\u7684\uff0c\u4e0d\u4f9d\u8d56\u77e9\u9635\u7684\u4efb\u4f55\u7279\u6b8a\u5c5e\u6027\u7684\u6c42\u89e3\u5668\uff1aGMRES\u65b9\u6cd5\u3002GMRES\u548c\u5171\u8f6d\u68af\u5ea6\u6cd5\u4e00\u6837\uff0c\u9700\u8981\u4e00\u4e2a\u5408\u9002\u7684\u9884\u5904\u7406\u7a0b\u5e8f\uff1a\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u4e00\u4e2a\u96c5\u53ef\u6bd4\u9884\u5904\u7406\u7a0b\u5e8f\uff0c\u5b83\u5bf9\u8fd9\u4e2a\u95ee\u9898\u6765\u8bf4\u8db3\u591f\u597d\u3002\n\n  template <int dim>\n  void AdvectionProblem<dim>::solve()\n  {\n    SolverControl               solver_control(std::max<std::size_t>(1000,\n                                                       system_rhs.size() / 10),\n                                 1e-10 * system_rhs.l2_norm());\n    SolverGMRES<Vector<double>> solver(solver_control);\n    PreconditionJacobi<SparseMatrix<double>> preconditioner;\n    preconditioner.initialize(system_matrix, 1.0);\n    solver.solve(system_matrix, solution, system_rhs, preconditioner);\n\n    Vector<double> residual(dof_handler.n_dofs());\n\n    system_matrix.vmult(residual, solution);\n    residual -= system_rhs;\n    std::cout << \"   Iterations required for convergence: \"\n              << solver_control.last_step() << '\\n'\n              << \"   Max norm of residual:                \"\n              << residual.linfty_norm() << '\\n';\n\n    hanging_node_constraints.distribute(solution);\n  }\n\n  // \u4e0b\u9762\u7684\u51fd\u6570\u6839\u636e\u4ecb\u7ecd\u4e2d\u63cf\u8ff0\u7684\u6570\u91cf\u6765\u7ec6\u5316\u7f51\u683c\u3002\u5404\u81ea\u7684\u8ba1\u7b97\u662f\u5728\u7c7b\n  // <code>GradientEstimation</code>  \u4e2d\u8fdb\u884c\u7684\u3002\n\n  template <int dim>\n  void AdvectionProblem<dim>::refine_grid()\n  {\n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells());\n\n    GradientEstimation::estimate(dof_handler,\n                                 solution,\n                                 estimated_error_per_cell);\n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation,\n                                                    estimated_error_per_cell,\n                                                    0.3,\n                                                    0.03);\n\n    triangulation.execute_coarsening_and_refinement();\n  }\n\n  // \u8fd9\u4e2a\u51fd\u6570\u4e0e\u7b2c6\u6b65\u4e2d\u7684\u51fd\u6570\u7c7b\u4f3c\uff0c\u4f46\u7531\u4e8e\u6211\u4eec\u4f7f\u7528\u7684\u662f\u9ad8\u9636\u6709\u9650\u5143\uff0c\u6240\u4ee5\u6211\u4eec\u4ee5\u4e0d\u540c\u7684\u65b9\u5f0f\u4fdd\u5b58\u89e3\u51b3\u65b9\u6848\u3002\u50cfVisIt\u548cParaview\u8fd9\u6837\u7684\u53ef\u89c6\u5316\u7a0b\u5e8f\u901a\u5e38\u53ea\u80fd\u7406\u89e3\u4e0e\u8282\u70b9\u76f8\u5173\u7684\u6570\u636e\uff1a\u5b83\u4eec\u4e0d\u80fd\u7ed8\u5236\u4e94\u5ea6\u57fa\u51fd\u6570\uff0c\u8fd9\u5bfc\u81f4\u6211\u4eec\u8ba1\u7b97\u7684\u89e3\u7684\u56fe\u7247\u975e\u5e38\u4e0d\u51c6\u786e\u3002\u4e3a\u4e86\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\uff0c\u6211\u4eec\u4e3a\u6bcf\u4e2a\u5355\u5143\u4fdd\u5b58\u4e86\u591a\u4e2a\n  // <em> \u8865\u4e01 </em> \uff1a\u5728\u4e8c\u7ef4\u4e2d\uff0c\u6211\u4eec\u4e3a\u6bcf\u4e2a\u5355\u5143\u5728VTU\u6587\u4ef6\u4e2d\u4fdd\u5b5864\u4e2a\u53cc\u7ebf\u6027\n  // \"\u5355\u5143\"\uff0c\u5728\u4e09\u7ef4\u4e2d\uff0c\u6211\u4eec\u4fdd\u5b58512\u4e2a\u3002\u6700\u7ec8\u7684\u7ed3\u679c\u662f\uff0c\u53ef\u89c6\u5316\u7a0b\u5e8f\u5c06\u4f7f\u7528\u7acb\u65b9\u4f53\u57fa\u7840\u51fd\u6570\u7684\u7247\u72b6\u7ebf\u6027\u63d2\u503c\uff1a\u8fd9\u6355\u6349\u5230\u4e86\u89e3\u51b3\u65b9\u6848\u7684\u7ec6\u8282\uff0c\u5e76\u4e14\u5728\u5927\u591a\u6570\u5c4f\u5e55\u5206\u8fa8\u7387\u4e0b\uff0c\u770b\u8d77\u6765\u5f88\u5e73\u6ed1\u3002\u6211\u4eec\u5728\u4e00\u4e2a\u5355\u72ec\u7684\u6b65\u9aa4\u4e2d\u4fdd\u5b58\u7f51\u683c\uff0c\u6ca1\u6709\u989d\u5916\u7684\u8865\u4e01\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u6709\u4e86\u7ec6\u80de\u9762\u7684\u89c6\u89c9\u8868\u73b0\u3002\n\n  // 9.1\u7248\u672c\u7684deal.II\u83b7\u5f97\u4e86\u7f16\u5199\u66f4\u9ad8\u7a0b\u5ea6\u591a\u9879\u5f0f\uff08\u5373\u4e3a\u6211\u4eec\u7684\u7247\u72b6\u4e8c\u9879\u5f0f\u89e3\u51b3\u65b9\u6848\u7f16\u5199\u7247\u72b6\u4e8c\u9879\u5f0f\u53ef\u89c6\u5316\u6570\u636e\uff09VTK\u548cVTU\u8f93\u51fa\u7684\u80fd\u529b\uff1a\u7136\u800c\uff0c\u5e76\u975e\u6240\u6709\u6700\u65b0\u7248\u672c\u7684ParaView\u548cViscit\uff08\u622a\u81f32018\u5e74\uff09\u90fd\u80fd\u8bfb\u53d6\u8fd9\u79cd\u683c\u5f0f\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u66f4\u53e4\u8001\u3001\u66f4\u901a\u7528\uff08\u4f46\u6548\u7387\u8f83\u4f4e\uff09\u7684\u65b9\u6cd5\u3002\n\n  template <int dim>\n  void AdvectionProblem<dim>::output_results(const unsigned int cycle) const\n  {\n    {\n      GridOut       grid_out;\n      std::ofstream output(\"grid-\" + std::to_string(cycle) + \".vtu\");\n      grid_out.write_vtu(triangulation, output);\n    }\n\n    {\n      DataOut<dim> data_out;\n      data_out.attach_dof_handler(dof_handler);\n      data_out.add_data_vector(solution, \"solution\");\n      data_out.build_patches(8);\n\n      // VTU\u8f93\u51fa\u53ef\u80fd\u5f88\u6602\u8d35\uff0c\u65e0\u8bba\u662f\u8ba1\u7b97\u8fd8\u662f\u5199\u5165\u78c1\u76d8\u3002\u8fd9\u91cc\u6211\u4eec\u8981\u6c42ZLib\uff0c\u4e00\u4e2a\u538b\u7f29\u5e93\uff0c\u4ee5\u6700\u5927\u9650\u5ea6\u5730\u63d0\u9ad8\u541e\u5410\u91cf\u7684\u65b9\u5f0f\u6765\u538b\u7f29\u6570\u636e\u3002\n\n      DataOutBase::VtkFlags vtk_flags;\n      vtk_flags.compression_level =\n        DataOutBase::VtkFlags::ZlibCompressionLevel::best_speed;\n      data_out.set_flags(vtk_flags);\n\n      std::ofstream output(\"solution-\" + std::to_string(cycle) + \".vtu\");\n      data_out.write_vtu(output);\n    }\n  }\n\n  // ... \u5982\u540c\u4e3b\u5faa\u73af\uff08\u8bbe\u7f6e-\u6c42\u89e3-\u7ec6\u5316\uff09\u4e00\u6837\uff0c\u9664\u4e86\u5faa\u73af\u6b21\u6570\u548c\u521d\u59cb\u7f51\u683c\u4e4b\u5916\u3002\n\n  template <int dim>\n  void AdvectionProblem<dim>::run()\n  {\n    for (unsigned int cycle = 0; cycle < 10; ++cycle)\n      {\n        std::cout << \"Cycle \" << cycle << ':' << std::endl;\n\n        if (cycle == 0)\n          {\n            GridGenerator::hyper_cube(triangulation, -1, 1);\n            triangulation.refine_global(3);\n          }\n        else\n          {\n            refine_grid();\n          }\n\n        std::cout << \"   Number of active cells:              \"\n                  << triangulation.n_active_cells() << std::endl;\n\n        setup_system();\n\n        std::cout << \"   Number of degrees of freedom:        \"\n                  << dof_handler.n_dofs() << std::endl;\n\n        assemble_system();\n        solve();\n        output_results(cycle);\n      }\n  }\n\n  //  @sect3{GradientEstimation class implementation}\n\n  // \u73b0\u5728\u662f <code>GradientEstimation</code> \u7c7b\u7684\u5b9e\u73b0\u3002\u8ba9\u6211\u4eec\u5148\u4e3a\n  // <code>estimate_cell()</code> \u51fd\u6570\u6240\u4f7f\u7528\u7684 <code>EstimateScratchData</code>\n  // \u7c7b\u5b9a\u4e49\u6784\u9020\u51fd\u6570\u3002\n\n  template <int dim>\n  GradientEstimation::EstimateScratchData<dim>::EstimateScratchData(\n    const FiniteElement<dim> &fe,\n    const Vector<double> &    solution,\n    Vector<float> &           error_per_cell)\n    : fe_midpoint_value(fe,\n                        QMidpoint<dim>(),\n                        update_values | update_quadrature_points)\n    , solution(solution)\n    , error_per_cell(error_per_cell)\n    , cell_midpoint_value(1)\n    , neighbor_midpoint_value(1)\n\n  {\n    // \u6211\u4eec\u5206\u914d\u4e00\u4e2a\u5411\u91cf\u6765\u4fdd\u5b58\u4e00\u4e2a\u5355\u5143\u7684\u6240\u6709\u6d3b\u52a8\u90bb\u5c45\u7684\u8fed\u4ee3\u5668\u3002\u6211\u4eec\u4fdd\u7559\u6d3b\u52a8\u90bb\u5c45\u7684\u6700\u5927\u6570\u91cf\uff0c\u4ee5\u907f\u514d\u4ee5\u540e\u7684\u91cd\u65b0\u5206\u914d\u3002\u6ce8\u610f\u8fd9\u4e2a\u6700\u5927\u7684\u6d3b\u52a8\u90bb\u5c45\u6570\u662f\u5982\u4f55\u8ba1\u7b97\u51fa\u6765\u7684\u3002\n\n    active_neighbors.reserve(GeometryInfo<dim>::faces_per_cell *\n                             GeometryInfo<dim>::max_children_per_face);\n  }\n\n  template <int dim>\n  GradientEstimation::EstimateScratchData<dim>::EstimateScratchData(\n    const EstimateScratchData &scratch_data)\n    : fe_midpoint_value(scratch_data.fe_midpoint_value.get_fe(),\n                        scratch_data.fe_midpoint_value.get_quadrature(),\n                        update_values | update_quadrature_points)\n    , solution(scratch_data.solution)\n    , error_per_cell(scratch_data.error_per_cell)\n    , cell_midpoint_value(1)\n    , neighbor_midpoint_value(1)\n  {}\n\n  // \u63a5\u4e0b\u6765\u662f\u5bf9 <code>GradientEstimation</code>\n  // \u7c7b\u7684\u5b9e\u73b0\u3002\u7b2c\u4e00\u4e2a\u51fd\u6570\u9664\u4e86\u5c06\u5de5\u4f5c\u59d4\u6258\u7ed9\u53e6\u4e00\u4e2a\u51fd\u6570\u5916\uff0c\u5e76\u6ca1\u6709\u505a\u4ec0\u4e48\uff0c\u4f46\u5728\u9876\u90e8\u6709\u4e00\u70b9\u8bbe\u7f6e\u3002\n\n  // \u5728\u5f00\u59cb\u5de5\u4f5c\u4e4b\u524d\uff0c\u6211\u4eec\u8981\u68c0\u67e5\u5199\u5165\u7ed3\u679c\u7684\u5411\u91cf\u662f\u5426\u6709\u6b63\u786e\u7684\u5927\u5c0f\u3002\u5728\u7f16\u7a0b\u4e2d\uff0c\u5fd8\u8bb0\u5728\u8c03\u7528\u5904\u6b63\u786e\u786e\u5b9a\u53c2\u6570\u5927\u5c0f\u7684\u9519\u8bef\u662f\u5f88\u5e38\u89c1\u7684\u3002\u56e0\u4e3a\u6ca1\u6709\u53d1\u73b0\u8fd9\u79cd\u9519\u8bef\u6240\u9020\u6210\u7684\u635f\u5931\u5f80\u5f80\u662f\u5fae\u5999\u7684\uff08\u4f8b\u5982\uff0c\u5185\u5b58\u4e2d\u67d0\u4e2a\u5730\u65b9\u7684\u6570\u636e\u635f\u574f\uff0c\u6216\u8005\u662f\u65e0\u6cd5\u91cd\u73b0\u7684\u7ed3\u679c\uff09\uff0c\u6240\u4ee5\u975e\u5e38\u503c\u5f97\u52aa\u529b\u53bb\u68c0\u67e5\u8fd9\u4e9b\u4e1c\u897f\u3002\n\n  template <int dim>\n  void GradientEstimation::estimate(const DoFHandler<dim> &dof_handler,\n                                    const Vector<double> & solution,\n                                    Vector<float> &        error_per_cell)\n  {\n    Assert(\n      error_per_cell.size() == dof_handler.get_triangulation().n_active_cells(),\n      ExcInvalidVectorLength(error_per_cell.size(),\n                             dof_handler.get_triangulation().n_active_cells()));\n\n    WorkStream::run(dof_handler.begin_active(),\n                    dof_handler.end(),\n                    &GradientEstimation::template estimate_cell<dim>,\n                    std::function<void(const EstimateCopyData &)>(),\n                    EstimateScratchData<dim>(dof_handler.get_fe(),\n                                             solution,\n                                             error_per_cell),\n                    EstimateCopyData());\n  }\n\n  // \u8fd9\u91cc\u662f\u901a\u8fc7\u8ba1\u7b97\u68af\u5ea6\u7684\u6709\u9650\u5dee\u5206\u8fd1\u4f3c\u503c\u6765\u4f30\u8ba1\u5c40\u90e8\u8bef\u5dee\u7684\u51fd\u6570\u3002\u8be5\u51fd\u6570\u9996\u5148\u8ba1\u7b97\u5f53\u524d\u5355\u5143\u7684\u6d3b\u52a8\u90bb\u5c45\u5217\u8868\uff0c\u7136\u540e\u4e3a\u6bcf\u4e2a\u90bb\u5c45\u8ba1\u7b97\u4ecb\u7ecd\u4e2d\u63cf\u8ff0\u7684\u6570\u91cf\u3002\u4e4b\u6240\u4ee5\u6709\u8fd9\u6837\u7684\u987a\u5e8f\uff0c\u662f\u56e0\u4e3a\u5728\u5c40\u90e8\u7ec6\u5316\u7f51\u683c\u7684\u60c5\u51b5\u4e0b\uff0c\u8981\u627e\u5230\u4e00\u4e2a\u7ed9\u5b9a\u7684\u90bb\u5c45\u5e76\u4e0d\u662f\u4e00\u8e74\u800c\u5c31\u7684\u4e8b\u60c5\u3002\u539f\u5219\u4e0a\uff0c\u4e00\u4e2a\u4f18\u5316\u7684\u5b9e\u73b0\u53ef\u4ee5\u5728\u4e00\u4e2a\u6b65\u9aa4\u4e2d\u627e\u5230\u90bb\u57df\u548c\u53d6\u51b3\u4e8e\u5b83\u4eec\u7684\u91cf\uff0c\u800c\u4e0d\u662f\u5148\u5efa\u7acb\u4e00\u4e2a\u90bb\u57df\u5217\u8868\uff0c\u7136\u540e\u5728\u7b2c\u4e8c\u6b65\u4e2d\u627e\u5230\u5b83\u4eec\u7684\u8d21\u732e\uff0c\u4f46\u662f\u6211\u4eec\u5f88\u4e50\u610f\u5c06\u6b64\u4f5c\u4e3a\u4e00\u4e2a\u7ec3\u4e60\u3002\u6b63\u5982\u4e4b\u524d\u6240\u8ba8\u8bba\u7684\uff0c\u4f20\u9012\u7ed9 WorkStream::run \u7684\u5de5\u4f5c\u8005\u51fd\u6570\u662f\u5728\u4fdd\u7559\u6240\u6709\u4e34\u65f6\u5bf9\u8c61\u7684 \"scratch \"\u5bf9\u8c61\u4e0a\u5de5\u4f5c\u3002\u8fd9\u6837\uff0c\u6211\u4eec\u5c31\u4e0d\u9700\u8981\u5728\u6bcf\u6b21\u4e3a\u7ed9\u5b9a\u5355\u5143\u8c03\u7528\u5de5\u4f5c\u7684\u51fd\u6570\u5185\u521b\u5efa\u548c\u521d\u59cb\u5316\u90a3\u4e9b\u6602\u8d35\u7684\u5bf9\u8c61\u4e86\u3002\u8fd9\u6837\u7684\u53c2\u6570\u88ab\u4f5c\u4e3a\u7b2c\u4e8c\u4e2a\u53c2\u6570\u4f20\u9012\u3002\u7b2c\u4e09\u4e2a\u53c2\u6570\u662f\u4e00\u4e2a \"copy-data \"\u5bf9\u8c61\uff08\u66f4\u591a\u4fe1\u606f\u89c1 @ref threads \uff09\uff0c\u4f46\u6211\u4eec\u5728\u8fd9\u91cc\u5b9e\u9645\u4e0a\u6ca1\u6709\u4f7f\u7528\u8fd9\u4e9b\u5bf9\u8c61\u3002\u7531\u4e8e WorkStream::run() \u575a\u6301\u4f20\u9012\u4e09\u4e2a\u53c2\u6570\uff0c\u6211\u4eec\u58f0\u660e\u8fd9\u4e2a\u51fd\u6570\u6709\u4e09\u4e2a\u53c2\u6570\uff0c\u4f46\u7b80\u5355\u5730\u5ffd\u7565\u4e86\u6700\u540e\u4e00\u4e2a\u53c2\u6570\u3002\n\n  // \uff08\u4ece\u7f8e\u5b66\u89d2\u5ea6\u770b\uff0c\u8fd9\u662f\u4e0d\u4ee4\u4eba\u6ee1\u610f\u7684\u3002\u5b83\u53ef\u4ee5\u901a\u8fc7\u4f7f\u7528\u4e00\u4e2a\u533f\u540d\uff08lambda\uff09\u51fd\u6570\u6765\u907f\u514d\u3002\u5982\u679c\u4f60\u5141\u8bb8\u7684\u8bdd\uff0c\u8ba9\u6211\u4eec\u5728\u8fd9\u91cc\u5c55\u793a\u4e00\u4e0b\u5982\u4f55\u505a\u3002\u9996\u5148\uff0c\u5047\u8bbe\u6211\u4eec\u5df2\u7ecf\u58f0\u660e\u8fd9\u4e2a\u51fd\u6570\u53ea\u63a5\u53d7\u4e24\u4e2a\u53c2\u6570\uff0c\u7701\u7565\u4e86\u672a\u4f7f\u7528\u7684\u6700\u540e\u4e00\u4e2a\u53c2\u6570\u3002\u73b0\u5728\uff0c\n  // WorkStream::run \u4ecd\u7136\u60f3\u7528\u4e09\u4e2a\u53c2\u6570\u6765\u8c03\u7528\u8fd9\u4e2a\u51fd\u6570\uff0c\u6240\u4ee5\u6211\u4eec\u9700\u8981\u627e\u5230\u4e00\u79cd\u65b9\u6cd5\u6765\n  // \"\u5fd8\u8bb0 \"\u8c03\u7528\u4e2d\u7684\u7b2c\u4e09\u4e2a\u53c2\u6570\u3002\u7b80\u5355\u5730\u50cf\u4e0a\u9762\u90a3\u6837\u628a\u6307\u9488\u4f20\u7ed9 WorkStream::run\n  // \u8fd9\u4e2a\u51fd\u6570\u662f\u505a\u4e0d\u5230\u7684--\u7f16\u8bd1\u5668\u4f1a\u62b1\u6028\u4e00\u4e2a\u58f0\u660e\u4e3a\u6709\u4e24\u4e2a\u53c2\u6570\u7684\u51fd\u6570\u5728\u8c03\u7528\u65f6\u6709\u4e09\u4e2a\u53c2\u6570\u3002\u7136\u800c\uff0c\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u5c06\u4ee5\u4e0b\u5185\u5bb9\u4f5c\u4e3a\u7b2c\u4e09\u4e2a\u53c2\u6570\u4f20\u9012\u7ed9\n  // WorkStream::run(): \u6765\u505a\u5230\u8fd9\u4e00\u70b9\n  // @code\n  //  [](const typename DoFHandler<dim>::active_cell_iterator &cell,\n  //     EstimateScratchData<dim> &                            scratch_data,\n  //     EstimateCopyData &)\n  //  {\n  //    GradientEstimation::estimate_cell<dim>(cell, scratch_data);\n  //  }\n  //  @endcode\n  //  \u8fd9\u5e76\u4e0d\u6bd4\u4e0b\u9762\u5b9e\u73b0\u7684\u89e3\u51b3\u65b9\u6848\u597d\u591a\u5c11\uff1a\u8981\u4e48\u4f8b\u7a0b\u672c\u8eab\u5fc5\u987b\u5e26\u4e09\u4e2a\u53c2\u6570\uff0c\u8981\u4e48\u5b83\u5fc5\u987b\u88ab\u5e26\u4e09\u4e2a\u53c2\u6570\u7684\u4e1c\u897f\u5305\u8d77\u6765\u3002\u6211\u4eec\u4e0d\u4f7f\u7528\u8fd9\u79cd\u65b9\u6cd5\uff0c\u56e0\u4e3a\u5728\u5f00\u59cb\u65f6\u6dfb\u52a0\u672a\u4f7f\u7528\u7684\u53c2\u6570\u66f4\u7b80\u5355\u3002\n\n  // \u73b0\u5728\u6765\u770b\u770b\u7ec6\u8282\u3002\n\n  template <int dim>\n  void GradientEstimation::estimate_cell(\n    const typename DoFHandler<dim>::active_cell_iterator &cell,\n    EstimateScratchData<dim> &                            scratch_data,\n    const EstimateCopyData &)\n  {\n    // \u6211\u4eec\u9700\u8981\u4e3a\u5f20\u91cf <code>Y</code> \u63d0\u4f9b\u7a7a\u95f4\uff0c\u5b83\u662fY\u5411\u91cf\u7684\u5916\u79ef\u4e4b\u548c\u3002\n\n    Tensor<2, dim> Y;\n\n    // \u9996\u5148\u521d\u59cb\u5316  <code>FEValues</code>  \u5bf9\u8c61\uff0c\u4ee5\u53ca  <code>Y</code>  \u5f20\u91cf\u3002\n\n    scratch_data.fe_midpoint_value.reinit(cell);\n\n    // \u73b0\u5728\uff0c\u5728\u6211\u4eec\u7ee7\u7eed\u4e4b\u524d\uff0c\u6211\u4eec\u9996\u5148\u8ba1\u7b97\u5f53\u524d\u5355\u5143\u7684\u6240\u6709\u6d3b\u52a8\u90bb\u5c45\u7684\u5217\u8868\u3002\u6211\u4eec\u9996\u5148\u5728\u6240\u6709\u9762\u4e0a\u8fdb\u884c\u5faa\u73af\uff0c\u770b\u90a3\u91cc\u7684\u90bb\u5c45\u662f\u5426\u5904\u4e8e\u6d3b\u52a8\u72b6\u6001\uff0c\u5982\u679c\u5b83\u4e0e\u672c\u5355\u5143\u5728\u540c\u4e00\u7ea7\u522b\u6216\u66f4\u7c97\u4e00\u7ea7\uff0c\u5c31\u4f1a\u51fa\u73b0\u8fd9\u79cd\u60c5\u51b5\uff08\u6ce8\u610f\uff0c\u4e00\u4e2a\u90bb\u5c45\u53ea\u80fd\u6bd4\u672c\u5355\u5143\u7c97\u4e00\u6b21\uff0c\u56e0\u4e3a\u6211\u4eec\u5728deal.II\u4e2d\u53ea\u5141\u8bb8\u5728\u4e00\u4e2a\u9762\u4e0a\u6709\u4e00\u4e2a\u6700\u5927\u7684\u7ec6\u5316\u5dee\uff09\u3002\u53e6\u5916\uff0c\u90bb\u5c45\u4e5f\u53ef\u80fd\u5728\u540c\u4e00\u7ea7\u522b\uff0c\u5e76\u88ab\u8fdb\u4e00\u6b65\u7ec6\u5316\uff1b\u90a3\u4e48\u6211\u4eec\u5fc5\u987b\u627e\u5230\u5b83\u7684\u54ea\u4e9b\u5b50\u5355\u5143\u4e0e\u5f53\u524d\u5355\u5143\u76f8\u90bb\uff0c\u5e76\u9009\u62e9\u8fd9\u4e9b\u5b50\u5355\u5143\uff08\u6ce8\u610f\uff0c\u5982\u679c\u4e00\u4e2a\u6d3b\u52a8\u5355\u5143\u7684\u90bb\u5c45\u7684\u4e00\u4e2a\u5b50\u5355\u5143\u4e0e\u8fd9\u4e2a\u6d3b\u52a8\u5355\u5143\u76f8\u90bb\uff0c\u90a3\u4e48\u5b83\u672c\u8eab\u5c31\u5fc5\u987b\u662f\u6d3b\u52a8\u7684\uff0c\u8fd9\u662f\u7531\u4e8e\u4e0a\u9762\u63d0\u5230\u7684\u4e00\u4e2a\u7ec6\u5316\u89c4\u5219\uff09\u3002\n\n    // \u5728\u4e00\u4e2a\u7a7a\u95f4\u7ef4\u5ea6\u4e0a\uff0c\u60c5\u51b5\u7565\u6709\u4e0d\u540c\uff0c\u56e0\u4e3a\u5728\u90a3\u91cc\u4e0d\u5b58\u5728\u5355\u4e00\u7ec6\u5316\u89c4\u5219\uff1a\u76f8\u90bb\u7684\u6d3b\u52a8\u5355\u5143\u53ef\u4ee5\u5728\u4efb\u610f\u591a\u7684\u7ec6\u5316\u7ea7\u522b\u4e0a\u6709\u6240\u4e0d\u540c\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u8ba1\u7b97\u53d8\u5f97\u6709\u70b9\u56f0\u96be\uff0c\u4f46\u6211\u4eec\u5c06\u5728\u4e0b\u9762\u89e3\u91ca\u3002\n\n    // \u5728\u5f00\u59cb\u5bf9\u5f53\u524d\u5355\u5143\u7684\u6240\u6709\u90bb\u57df\u8fdb\u884c\u5faa\u73af\u4e4b\u524d\uff0c\u6211\u4eec\u5f53\u7136\u8981\u6e05\u9664\u5b58\u50a8\u6d3b\u52a8\u90bb\u57df\u7684\u8fed\u4ee3\u5668\u7684\u6570\u7ec4\u3002\n\n    scratch_data.active_neighbors.clear();\n    for (const auto face_n : GeometryInfo<dim>::face_indices())\n      if (!cell->at_boundary(face_n))\n        {\n          // \u9996\u5148\u5b9a\u4e49\u9762\u7684\u8fed\u4ee3\u5668\u548c\u90bb\u5c45\u7684\u7f29\u5199\n\n          const auto face     = cell->face(face_n);\n          const auto neighbor = cell->neighbor(face_n);\n\n          // \u7136\u540e\u68c0\u67e5\u90bb\u5c45\u662f\u5426\u662f\u6d3b\u52a8\u7684\u3002\u5982\u679c\u662f\uff0c\u90a3\u4e48\u5b83\u5c31\u5728\u540c\u4e00\u5c42\u6216\u66f4\u7c97\u7684\u4e00\u5c42\uff08\u5982\u679c\u6211\u4eec\u4e0d\u662f\u57281D\u4e2d\uff09\uff0c\u800c\u4e14\u6211\u4eec\u5728\u4efb\u4f55\u60c5\u51b5\u4e0b\u90fd\u4f1a\u5bf9\u5b83\u611f\u5174\u8da3\u3002\n\n          if (neighbor->is_active())\n            scratch_data.active_neighbors.push_back(neighbor);\n          else\n            {\n              // \u5982\u679c\u90bb\u5c45\u6ca1\u6709\u6d3b\u52a8\uff0c\u5219\u68c0\u67e5\u5176\u5b50\u5973\u3002\n\n              if (dim == 1)\n                {\n                  // \u8981\u627e\u5230\u4e0e\u672c\u5355\u5143\u76f8\u90bb\u7684\u5b50\u5355\u5143\uff0c\u5982\u679c\u6211\u4eec\u5728\u672c\u5355\u5143\u7684\u5de6\u8fb9\uff08n==0\uff09\uff0c\u5219\u4f9d\u6b21\u53bb\u627e\u5176\u53f3\u8fb9\u7684\u5b50\u5355\u5143\uff0c\u5982\u679c\u6211\u4eec\u5728\u53f3\u8fb9\uff08n==1\uff09\uff0c\u5219\u4f9d\u6b21\u53bb\u627e\u5de6\u8fb9\u7684\u5b50\u5355\u5143\uff0c\u76f4\u5230\u627e\u5230\u4e00\u4e2a\u6d3b\u52a8\u5355\u5143\u3002\n\n                  auto neighbor_child = neighbor;\n                  while (neighbor_child->has_children())\n                    neighbor_child = neighbor_child->child(face_n == 0 ? 1 : 0);\n\n                  // \u7531\u4e8e\u8fd9\u4f7f\u7528\u4e86\u4e00\u4e9b\u975e\u5fae\u5999\u7684\u51e0\u4f55\u76f4\u89c9\uff0c\u6211\u4eec\u53ef\u80fd\u60f3\u68c0\u67e5\u4e00\u4e0b\u6211\u4eec\u662f\u5426\u505a\u5bf9\u4e86\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u68c0\u67e5\u6211\u4eec\u627e\u5230\u7684\u5355\u5143\u683c\u7684\u90bb\u5c45\u662f\u5426\u786e\u5b9e\u662f\u6211\u4eec\u76ee\u524d\u6b63\u5728\u5904\u7406\u7684\u5355\u5143\u3002\u50cf\u8fd9\u6837\u7684\u68c0\u67e5\u901a\u5e38\u662f\u6709\u7528\u7684\uff0c\u5e76\u4e14\u7ecf\u5e38\u53d1\u73b0\u50cf\u4e0a\u9762\u8fd9\u4e00\u884c\u7684\u7b97\u6cd5\uff08\u4e0d\u7531\u81ea\u4e3b\u5730\u4ea4\u6362\n                  // <code>n==1</code> for <code>n==0</code>\n                  // \u6216\u7c7b\u4f3c\u7684\u7b97\u6cd5\u662f\u5f88\u7b80\u5355\u7684\uff09\u548c\u5e93\u4e2d\u7684\u9519\u8bef\uff08\u4e0a\u9762\u7684\u7b97\u6cd5\u6240\u4f9d\u636e\u7684\u5047\u8bbe\u53ef\u80fd\u662f\u9519\u8bef\u7684\uff0c\u8bb0\u5f55\u9519\u8bef\uff0c\u6216\u8005\u7531\u4e8e\u5e93\u4e2d\u7684\u9519\u8bef\u800c\u88ab\u8fdd\u53cd\uff09\u3002\u539f\u5219\u4e0a\uff0c\u6211\u4eec\u53ef\u4ee5\u5728\u7a0b\u5e8f\u8fd0\u884c\u4e00\u6bb5\u65f6\u95f4\u540e\u5220\u9664\u8fd9\u6837\u7684\u68c0\u67e5\uff0c\u4f46\u662f\u65e0\u8bba\u5982\u4f55\u7559\u4e0b\u5b83\u6765\u68c0\u67e5\u5e93\u4e2d\u6216\u4e0a\u8ff0\u7b97\u6cd5\u4e2d\u7684\u53d8\u5316\u53ef\u80fd\u662f\u4e00\u4ef6\u597d\u4e8b\u3002\n                  // \u8bf7\u6ce8\u610f\uff0c\u5982\u679c\u8fd9\u4e2a\u68c0\u67e5\u5931\u8d25\u4e86\uff0c\u90a3\u4e48\u8fd9\u80af\u5b9a\u662f\u4e00\u4e2a\u65e0\u6cd5\u6062\u590d\u7684\u9519\u8bef\uff0c\u800c\u4e14\u5f88\u53ef\u80fd\u88ab\u79f0\u4e3a\u5185\u90e8\u9519\u8bef\u3002\u56e0\u6b64\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u4e00\u4e2a\u9884\u5b9a\u4e49\u7684\u5f02\u5e38\u7c7b\u6765\u629b\u51fa\u3002\n\n                  Assert(neighbor_child->neighbor(face_n == 0 ? 1 : 0) == cell,\n                         ExcInternalError());\n\n                  // \u5982\u679c\u68c0\u67e5\u6210\u529f\uff0c\u6211\u4eec\u5c31\u628a\u521a\u521a\u53d1\u73b0\u7684\u6d3b\u52a8\u90bb\u5c45\u63a8\u5230\u6211\u4eec\u4fdd\u7559\u7684\u5806\u6808\u4e2d\u3002\n\n                  scratch_data.active_neighbors.push_back(neighbor_child);\n                }\n              else\n\n                // \u5982\u679c\u6211\u4eec\u4e0d\u57281d\u4e2d\uff0c\u6211\u4eec\u6536\u96c6\u6240\u6709 \"\u5728\n                // \"\u5f53\u524d\u9762\u7684\u5b50\u9762\u540e\u9762\u7684\u90bb\u5c45\u5b69\u5b50\uff0c\u7136\u540e\u7ee7\u7eed\u524d\u8fdb\u3002\n\n                for (unsigned int subface_n = 0; subface_n < face->n_children();\n                     ++subface_n)\n                  scratch_data.active_neighbors.push_back(\n                    cell->neighbor_child_on_subface(face_n, subface_n));\n            }\n        }\n\n    // \u597d\u4e86\uff0c\u73b0\u5728\u6211\u4eec\u6709\u4e86\u6240\u6709\u7684\u90bb\u5c45\uff0c\u8ba9\u6211\u4eec\u5f00\u59cb\u5bf9\u4ed6\u4eec\u6bcf\u4e2a\u4eba\u8fdb\u884c\u8ba1\u7b97\u3002\u9996\u5148\uff0c\u6211\u4eec\u505a\u4e00\u4e9b\u9884\u5907\u5de5\u4f5c\uff1a\u627e\u51fa\u5f53\u524d\u5355\u5143\u683c\u7684\u4e2d\u5fc3\u548c\u8be5\u70b9\u7684\u89e3\u51b3\u65b9\u6848\u3002\u540e\u8005\u662f\u4ee5\u6b63\u4ea4\u70b9\u7684\u51fd\u6570\u503c\u5411\u91cf\u7684\u5f62\u5f0f\u5f97\u5230\u7684\uff0c\u5f53\u7136\uff0c\u6b63\u4ea4\u70b9\u53ea\u6709\u4e00\u4e2a\u3002\u540c\u6837\u5730\uff0c\u4e2d\u5fc3\u7684\u4f4d\u7f6e\u662f\u5b9e\u7a7a\u95f4\u4e2d\u7b2c\u4e00\u4e2a\uff08\u4e5f\u662f\u552f\u4e00\u7684\uff09\u6b63\u4ea4\u70b9\u7684\u4f4d\u7f6e\u3002\n\n    const Point<dim> this_center =\n      scratch_data.fe_midpoint_value.quadrature_point(0);\n\n    scratch_data.fe_midpoint_value.get_function_values(\n      scratch_data.solution, scratch_data.cell_midpoint_value);\n\n    // \u73b0\u5728\u5728\u6240\u6709\u6d3b\u52a8\u90bb\u5c45\u4e0a\u5faa\u73af\uff0c\u6536\u96c6\u6211\u4eec\u9700\u8981\u7684\u6570\u636e\u3002\n\n    Tensor<1, dim> projected_gradient;\n    for (const auto &neighbor : scratch_data.active_neighbors)\n      {\n        // \u7136\u540e\u5f97\u5230\u90bb\u8fd1\u5355\u5143\u7684\u4e2d\u5fc3\u548c\u8be5\u70b9\u7684\u6709\u9650\u5143\u51fd\u6570\u503c\u3002\u6ce8\u610f\uff0c\u4e3a\u4e86\u83b7\u5f97\u8fd9\u4e9b\u4fe1\u606f\uff0c\u6211\u4eec\u5fc5\u987b\u91cd\u65b0\u521d\u59cb\u5316\u76f8\u90bb\u5355\u5143\u7684\n        // <code>FEValues</code> \u5bf9\u8c61\u3002\n\n        scratch_data.fe_midpoint_value.reinit(neighbor);\n        const Point<dim> neighbor_center =\n          scratch_data.fe_midpoint_value.quadrature_point(0);\n\n        scratch_data.fe_midpoint_value.get_function_values(\n          scratch_data.solution, scratch_data.neighbor_midpoint_value);\n\n        // \u8ba1\u7b97\u8fde\u63a5\u4e24\u4e2a\u5355\u5143\u683c\u4e2d\u5fc3\u7684\u5411\u91cf <code>y</code>\n        // \u3002\u6ce8\u610f\uff0c\u4e0e\u4ecb\u7ecd\u4e0d\u540c\uff0c\u6211\u4eec\u7528 <code>y</code>\n        // \u8868\u793a\u5f52\u4e00\u5316\u7684\u5dee\u5206\u5411\u91cf\uff0c\u56e0\u4e3a\u8fd9\u662f\u5728\u8ba1\u7b97\u4e2d\u968f\u5904\u53ef\u89c1\u7684\u6570\u91cf\u3002\n\n        Tensor<1, dim> y        = neighbor_center - this_center;\n        const double   distance = y.norm();\n        y /= distance;\n\n        // \u7136\u540e\u628a\u8fd9\u4e2a\u5355\u5143\u683c\u5bf9Y\u77e9\u9635\u7684\u8d21\u732e\u52a0\u8d77\u6765...\n\n        for (unsigned int i = 0; i < dim; ++i)\n          for (unsigned int j = 0; j < dim; ++j)\n            Y[i][j] += y[i] * y[j];\n\n        // ...\u5e76\u66f4\u65b0\u5dee\u989d\u5546\u6570\u4e4b\u548c\u3002\n\n        projected_gradient += (scratch_data.neighbor_midpoint_value[0] -\n                               scratch_data.cell_midpoint_value[0]) /\n                              distance * y;\n      }\n\n    // \u5982\u679c\u73b0\u5728\uff0c\u5728\u6536\u96c6\u4e86\u6765\u81ea\u90bb\u5c45\u7684\u6240\u6709\u4fe1\u606f\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u786e\u5b9a\u5f53\u524d\u5355\u5143\u7684\u68af\u5ea6\u7684\u8fd1\u4f3c\u503c\uff0c\u90a3\u4e48\u6211\u4eec\u9700\u8981\u7ecf\u8fc7\u8de8\u8d8a\u6574\u4e2a\u7a7a\u95f4\u7684\u5411\u91cf\n    // <code>y</code>\n    // \uff0c\u5426\u5219\u6211\u4eec\u5c31\u4e0d\u4f1a\u6709\u68af\u5ea6\u7684\u6240\u6709\u6210\u5206\u3002\u8fd9\u53ef\u4ee5\u901a\u8fc7\u77e9\u9635\u7684\u53ef\u9006\u6027\u6765\u8bf4\u660e\u3002\n\n    // \u5982\u679c\u77e9\u9635\u4e0d\u53ef\u9006\uff0c\u90a3\u4e48\u5f53\u524d\u5355\u5143\u7684\u6d3b\u52a8\u90bb\u5c45\u6570\u91cf\u4e0d\u8db3\u3002\u4e0e\u4e4b\u524d\u6240\u6709\u7684\u60c5\u51b5\uff08\u6211\u4eec\u63d0\u51fa\u4e86\u5f02\u5e38\uff09\u76f8\u6bd4\uff0c\u8fd9\u4e0d\u662f\u4e00\u4e2a\u7f16\u7a0b\u9519\u8bef\uff1a\u8fd9\u662f\u4e00\u4e2a\u8fd0\u884c\u65f6\u9519\u8bef\uff0c\u5373\u4f7f\u5728\u8c03\u8bd5\u6a21\u5f0f\u4e0b\u8fd0\u884c\u826f\u597d\uff0c\u4e5f\u53ef\u80fd\u5728\u4f18\u5316\u6a21\u5f0f\u4e0b\u53d1\u751f\uff0c\u6240\u4ee5\u5728\u4f18\u5316\u6a21\u5f0f\u4e0b\u5c1d\u8bd5\u6355\u6349\u8fd9\u4e2a\u9519\u8bef\u662f\u5408\u7406\u7684\u3002\u5bf9\u4e8e\u8fd9\u79cd\u60c5\u51b5\uff0c\u6709\u4e00\u4e2a\n    // <code>AssertThrow</code> \u5b8f\uff1a\u5b83\u50cf <code>Assert</code>\n    // \u5b8f\u4e00\u6837\u68c0\u67e5\u6761\u4ef6\uff0c\u4f46\u4e0d\u4ec5\u4ec5\u662f\u5728\u8c03\u8bd5\u6a21\u5f0f\u4e0b\uff1b\u7136\u540e\u8f93\u51fa\u4e00\u4e2a\u9519\u8bef\u4fe1\u606f\uff0c\u4f46\u4e0d\u662f\u50cf\n    // <code>Assert</code> \u5b8f\u90a3\u6837\u4e2d\u6b62\u7a0b\u5e8f\uff0c\u800c\u662f\u4f7f\u7528C++\u7684 <code>throw</code>\n    // \u547d\u4ee4\u629b\u51fa\u5f02\u5e38\u3002\u8fd9\u6837\uff0c\u4eba\u4eec\u5c31\u6709\u53ef\u80fd\u6355\u6349\u5230\u8fd9\u4e2a\u9519\u8bef\uff0c\u5e76\u91c7\u53d6\u5408\u7406\u7684\u5e94\u5bf9\u63aa\u65bd\u3002\u5176\u4e2d\u4e00\u4e2a\u63aa\u65bd\u662f\u5728\u5168\u5c40\u8303\u56f4\u5185\u7ec6\u5316\u7f51\u683c\uff0c\u56e0\u4e3a\u5982\u679c\u521d\u59cb\u7f51\u683c\u7684\u6bcf\u4e2a\u5355\u5143\u90fd\u81f3\u5c11\u88ab\u7ec6\u5316\u8fc7\u4e00\u6b21\uff0c\u5c31\u4e0d\u4f1a\u51fa\u73b0\u65b9\u5411\u4e0d\u8db3\u7684\u60c5\u51b5\u3002\n\n    AssertThrow(determinant(Y) != 0, ExcInsufficientDirections());\n\n    // \u5982\u679c\u53e6\u4e00\u65b9\u9762\uff0c\u77e9\u9635\u662f\u53ef\u53cd\u8f6c\u7684\uff0c\u90a3\u4e48\u5c31\u53cd\u8f6c\u5b83\uff0c\u7528\u5b83\u4e58\u4ee5\u5176\u4ed6\u6570\u91cf\uff0c\u7136\u540e\u7528\u8fd9\u4e2a\u6570\u91cf\u548c\u6b63\u786e\u7684\u7f51\u683c\u5bbd\u5ea6\u7684\u5e42\u6765\u8ba1\u7b97\u4f30\u8ba1\u8bef\u5dee\u3002\n\n    const Tensor<2, dim> Y_inverse = invert(Y);\n\n    const Tensor<1, dim> gradient = Y_inverse * projected_gradient;\n\n    // \u8fd9\u4e2a\u51fd\u6570\u7684\u6700\u540e\u4e00\u90e8\u5206\u662f\u5c06\u6211\u4eec\u521a\u521a\u8ba1\u7b97\u51fa\u6765\u7684\u5185\u5bb9\u5199\u5165\u8f93\u51fa\u5411\u91cf\u7684\u5143\u7d20\u4e2d\u3002\u8fd9\u4e2a\u5411\u91cf\u7684\u5730\u5740\u5df2\u7ecf\u5b58\u50a8\u5728Scratch\u6570\u636e\u5bf9\u8c61\u4e2d\uff0c\u6211\u4eec\u6240\u8981\u505a\u7684\u5c31\u662f\u77e5\u9053\u5982\u4f55\u5728\u8fd9\u4e2a\u5411\u91cf\u4e2d\u83b7\u5f97\u6b63\u786e\u7684\u5143\u7d20--\u4f46\u6211\u4eec\u53ef\u4ee5\u95ee\u4e00\u4e0b\u6211\u4eec\u6240\u5728\u7684\u5355\u5143\u683c\u662f\u7b2c\u591a\u5c11\u4e2a\u6d3b\u52a8\u5355\u5143\u3002\n\n    scratch_data.error_per_cell(cell->active_cell_index()) =\n      (std::pow(cell->diameter(), 1 + 1.0 * dim / 2) * gradient.norm());\n  }\n} // namespace Step9\n// @sect3{Main function}\n\n//  <code>main</code> \u51fd\u6570\u4e0e\u524d\u9762\u7684\u4f8b\u5b50\u7c7b\u4f3c\u3002\u4e3b\u8981\u533a\u522b\u662f\u6211\u4eec\u4f7f\u7528MultithreadInfo\u6765\u8bbe\u7f6e\u6700\u5927\u7684\u7ebf\u7a0b\u6570\uff08\u66f4\u591a\u4fe1\u606f\u8bf7\u53c2\u89c1\u6587\u6863\u6a21\u5757  @ref threads  \"\u591a\u5904\u7406\u5668\u8bbf\u95ee\u5171\u4eab\u5185\u5b58\u7684\u5e76\u884c\u8ba1\u7b97\"\uff09\u3002\u4f7f\u7528\u7684\u7ebf\u7a0b\u6570\u662f\u73af\u5883\u53d8\u91cfDEAL_II_NUM_THREADS\u548c  <code>set_thread_limit</code>  \u7684\u53c2\u6570\u7684\u6700\u5c0f\u503c\u3002\u5982\u679c\u6ca1\u6709\u7ed9  <code>set_thread_limit</code>  \u7684\u503c\uff0c\u5219\u4f7f\u7528\u82f1\u7279\u5c14\u7ebf\u7a0b\u6784\u5efa\u5757\uff08TBB\uff09\u5e93\u7684\u9ed8\u8ba4\u503c\u3002\u5982\u679c\u7701\u7565\u4e86\u5bf9  <code>set_thread_limit</code>  \u7684\u8c03\u7528\uff0c\u7ebf\u7a0b\u7684\u6570\u91cf\u5c06\u7531 TBB \u9009\u62e9\uff0c\u4e0e DEAL_II_NUM_THREADS\u65e0\u5173\u3002\n\nint main()\n{\n  using namespace dealii;\n  try\n    {\n      MultithreadInfo::set_thread_limit();\n\n      Step9::AdvectionProblem<2> advection_problem_2d;\n      advection_problem_2d.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\n  return 0;\n}\n\n//\n", "meta": {"hexsha": "d8377b45fa455bd5809632d57c062e93ab3af923", "size": 35820, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-9/step-9.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-9/step-9.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-9/step-9.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["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.665615142, "max_line_length": 432, "alphanum_fraction": 0.6540201005, "num_tokens": 14520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5026828076684177}}
{"text": "#pragma once\n\n#include <iostream> // cerr\n#include <random> // mt19937_64, uniform_x_distribution\n#include <vector>\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <iostream>\n\n#include \"inf.hpp\"\n#include \"getInf.hpp\"\n#include \"util.hpp\"\n\nusing namespace boost;\n\ntemplate<typename Number> using Graph = adjacency_list<listS, vecS, directedS, no_property, property<edge_weight_t, Number>>;\ntemplate<typename Number> using Vertex = typename graph_traits<Graph<Number>>::vertex_descriptor;\ntypedef std::pair<int, int> Edge;\n\ntemplate<typename Number>\nstruct graph_t {\n  int V;\n  int E;\n  Edge *edge_array;\n  Number *weights;\n};\n\n#ifdef CUDA\ntemplate<typename Number>\nstruct graph_cuda_t {\n  int V;\n  int E;\n  Edge *edge_array;\n  Number *weights;\n  int *starts;\n};\n#endif\n\ntemplate<typename Number> size_t init_random_adjacency_matrix(Number *adjacencyMatrix, const int n, const double p, const unsigned long seed) {\n  static const Number inf = getInf<Number>();\n  static std::uniform_real_distribution<double> flip(0, 1);\n  static std::uniform_real_distribution<double> choose_weight(1, 100);\n\n  std::mt19937_64 rand_engine(seed);\n\n  size_t e = 0;\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      if (i == j) {\n        adjacencyMatrix[i * n + j] = 0;\n      } else if (flip(rand_engine) < p) {\n        adjacencyMatrix[i * n + j] = choose_weight(rand_engine);\n        e++;\n      } else {\n        adjacencyMatrix[i * n + j] = inf;\n      }\n    }\n  }\n  return e;\n}\n\ntemplate<typename Number> size_t count_edges(const Number *adjacencyMatrix, const int n) {\n  static const Number inf = getInf<Number>();\n  size_t e = 0;\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n  for (int i = 0; i < n * n; i++) {\n    Number weight = adjacencyMatrix[i];\n    if (weight != 0 && weight != inf) {\n#ifdef _OPENMP\n#pragma omp atomic\n#endif\n      e++;\n    }\n  }\n  return e;\n}\n\ntemplate<typename Number> graph_t<Number> * init_graph(const Number *adjacencyMatrix, const int n) {\n  static const Number inf = getInf<Number>();\n  size_t e = count_edges<Number>(adjacencyMatrix, n);\n  Edge *edge_array = new Edge[e];\n  Number *weights = new Number[e];\n  int ei = 0;\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      if (adjacencyMatrix[i * n + j] != 0 && adjacencyMatrix[i * n + j] != inf) {\n#ifdef _OPENMP\n#pragma omp critical (init_graph)\n#endif\n        {\n          edge_array[ei] = Edge(i, j);\n          weights[ei] = adjacencyMatrix[i * n + j];\n          ei++;\n        }\n      }\n    }\n  }\n  graph_t<Number> *gr = new graph_t<Number>;\n  gr->V = n;\n  gr->E = e;\n  gr->edge_array = edge_array;\n  gr->weights = weights;\n  return gr;\n}\n\ntemplate<typename Number> graph_t<Number> * init_random_graph(const int n, const double p, const unsigned long seed) {\n  static const Number inf = getInf<Number>();\n  Number *adjacencyMatrix = new Number[n * n];\n  size_t e = init_random_adjacency_matrix<Number>(adjacencyMatrix, n, p, seed);\n  graph_t<Number> * gr = init_graph<Number>(adjacencyMatrix, n, e);\n  delete[] adjacencyMatrix;\n  return gr;\n}\n\ntemplate<typename Number> void free_graph(const graph_t<Number> *g) {\n  delete[] g->edge_array;\n  delete[] g->weights;\n  delete g;\n}\n\n#ifdef CUDA\n\ntemplate<typename Number> graph_cuda_t<Number> * init_graph_cuda(const Number *adjacencyMatrix, const int n) {\n  static const Number inf = getInf<Number>();\n  size_t e = count_edges<Number>(adjacencyMatrix, n);\n  Edge *edge_array = new Edge[e];\n  Number *weights = new Number[e];\n  int* starts = new int[n + 1];  // Starting point for each edge\n  int ei = 0;\n  for (int i = 0; i < n; i++) {\n    starts[i] = ei;\n    for (int j = 0; j < n; j++) {\n      if (adjacencyMatrix[i * n + j] != 0 && adjacencyMatrix[i * n + j] != inf) {\n#ifdef _OPENMP\n#pragma omp critical (init_graph_cuda)\n#endif\n        {\n          edge_array[ei] = Edge(i, j);\n          weights[ei] = adjacencyMatrix[i * n + j];\n          ei++;\n        }\n      }\n    }\n  }\n\n  starts[n] = ei; // One extra\n\n  graph_cuda_t<Number> *gr = new graph_cuda_t<Number>;\n  gr->V = n;\n  gr->E = e;\n  gr->edge_array = edge_array;\n  gr->weights = weights;\n  gr->starts = starts;\n  return gr;\n}\n\ntemplate<typename Number> graph_cuda_t<Number> * johnson_cuda_random_init(const int n, const double p, const unsigned long seed) {\n  static const Number inf = getInf<Number>();\n  Number* adjacencyMatrix = new Number[n * n];\n  int e = init_random_adjacency_matrix<Number>(adjacencyMatrix, n, p, seed);\n  graph_cuda_t<Number> *gr = init_graph_cuda<Number>(adjacencyMatrix, n);\n  delete[] adjacencyMatrix;\n  return gr;\n}\n\ntemplate<typename Number> void free_graph_cuda(const graph_cuda_t<Number> * g) {\n  delete[] g->edge_array;\n  delete[] g->weights;\n  delete[] g->starts;\n  delete g;\n}\n\ntemplate<typename Number> void johnson_cuda(graph_cuda_t<Number> *gr, Number *distanceMatrix);\ntemplate<typename Number> void johnson_successor_cuda(graph_cuda_t<Number> *gr, Number *distanceMatrix, int *successorMatrix);\n\n#endif\n\ntemplate<typename Number> inline bool bellman_ford(const graph_t<Number> *gr, Number *dist, int src) {\n  static const Number inf = getInf<Number>();\n  int v = gr->V;\n  int e = gr->E;\n  Edge *edges = gr->edge_array;\n  Number *weights = gr->weights;\n\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n  for (int i = 0; i < v; i++) {\n    dist[i] = inf;\n  }\n  dist[src] = 0;\n\n  for (int i = 1; i <= v - 1; i++) {\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n    for (int j = 0; j < e; j++) {\n      int u = std::get<0>(edges[j]);\n      int v = std::get<1>(edges[j]);\n      Number new_dist = weights[j] + dist[u];\n      if (dist[u] != inf && new_dist < dist[v])\n        dist[v] = new_dist;\n    }\n  }\n\n  bool no_neg_cycle = true;\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n  for (int i = 0; i < e; i++) {\n    int u = std::get<0>(edges[i]);\n    int v = std::get<1>(edges[i]);\n    Number weight = weights[i];\n    if (dist[u] != inf && dist[u] + weight < dist[v])\n      no_neg_cycle = false;\n  }\n  return no_neg_cycle;\n}\n\ntemplate<typename Number> void johnson_parallel(const graph_t<Number> *gr, Number *distanceMatrix) {\n  static const Number inf = getInf<Number>();\n  int v = gr->V;\n\n  // Make new graph for Bellman-Ford\n  // First, a new node q is added to the graph, connected by zero-weight edges\n  // to each of the other nodes.\n  graph_t<Number> *bf_graph = new graph_t<Number>;\n  bf_graph->V = v + 1;\n  bf_graph->E = gr->E + v;\n  bf_graph->edge_array = new Edge[bf_graph->E];\n  bf_graph->weights = new Number[bf_graph->E];\n\n  std::memcpy(bf_graph->edge_array, gr->edge_array, gr->E * sizeof(Edge));\n  std::memcpy(bf_graph->weights, gr->weights, gr->E * sizeof(Number));\n  std::memset(&bf_graph->weights[gr->E], 0, v * sizeof(Number));\n\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n  for (int e = 0; e < v; e++) {\n    bf_graph->edge_array[e + gr->E] = Edge(v, e);\n  }\n\n  // Second, the Bellman\u2013Ford algorithm is used, starting from the new vertex q,\n  // to find for each vertex v the minimum weight h(v) of a path from q to v. If\n  // this step detects a negative cycle, the algorithm is terminated.\n  // TODO Can run parallel version?\n  Number *h = new Number[bf_graph->V];\n  bool r = bellman_ford<Number>(bf_graph, h, v);\n  if (!r) {\n    std::cerr << \"\\nNegative Cycles Detected! Terminating Early\\n\";\n    exit(1);\n  }\n\n  // Next the edges of the original graph are reweighted using the values computed\n  // by the Bellman\u2013Ford algorithm: an edge from u to v, having length\n  // w(u,v), is given the new length w(u,v) + h(u) \u2212 h(v).\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n  for (int e = 0; e < gr->E; e++) {\n    int u = std::get<0>(gr->edge_array[e]);\n    int v = std::get<1>(gr->edge_array[e]);\n    gr->weights[e] = gr->weights[e] + h[u] - h[v];\n  }\n\n  Graph<Number> G(gr->edge_array, gr->edge_array + gr->E, gr->weights, v);\n\n#ifdef _OPENMP\n#pragma omp parallel for schedule(dynamic)\n#endif\n  for (int s = 0; s < v; s++) {\n    std::vector <Vertex<Number>> p(num_vertices(G));\n    std::vector<Number> d(num_vertices(G));\n    dijkstra_shortest_paths(G, s, distance_map(&d[0]).distance_inf(inf));\n    for (int vi = 0; vi < v; vi++) {\n      int i = s * v + vi;\n      distanceMatrix[i] = d[vi] + h[vi] - h[s];\n    }\n  }\n\n  delete[] h;\n  free_graph<Number>(bf_graph);\n}\n\ntemplate<typename Number> void johnson_parallel(const graph_t<Number> *gr, Number *distanceMatrix, int *successorMatrix) {\n  static const Number inf = getInf<Number>();\n  int v = gr->V;\n\n  // Make new graph for Bellman-Ford\n  // First, a new node q is added to the graph, connected by zero-weight edges\n  // to each of the other nodes.\n  graph_t<Number> *bf_graph = new graph_t<Number>;\n  bf_graph->V = v + 1;\n  bf_graph->E = gr->E + v;\n  bf_graph->edge_array = new Edge[bf_graph->E];\n  bf_graph->weights = new Number[bf_graph->E];\n\n  std::memcpy(bf_graph->edge_array, gr->edge_array, gr->E * sizeof(Edge));\n  std::memcpy(bf_graph->weights, gr->weights, gr->E * sizeof(Number));\n  std::memset(&bf_graph->weights[gr->E], 0, v * sizeof(Number));\n\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n  for (int e = 0; e < v; e++) {\n    bf_graph->edge_array[e + gr->E] = Edge(v, e);\n  }\n\n  // Second, the Bellman\u2013Ford algorithm is used, starting from the new vertex q,\n  // to find for each vertex v the minimum weight h(v) of a path from q to v. If\n  // this step detects a negative cycle, the algorithm is terminated.\n  // TODO Can run parallel version?\n  Number *h = new Number[bf_graph->V];\n  bool r = bellman_ford<Number>(bf_graph, h, v);\n  if (!r) {\n    std::cerr << \"\\nNegative Cycles Detected! Terminating Early\\n\";\n    exit(1);\n  }\n\n  // Next the edges of the original graph are reweighted using the values computed\n  // by the Bellman\u2013Ford algorithm: an edge from u to v, having length\n  // w(u,v), is given the new length w(u,v) + h(u) \u2212 h(v).\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n  for (int e = 0; e < gr->E; e++) {\n    int u = std::get<0>(gr->edge_array[e]);\n    int v = std::get<1>(gr->edge_array[e]);\n    gr->weights[e] = gr->weights[e] + h[u] - h[v];\n  }\n\n  Graph<Number> G(gr->edge_array, gr->edge_array + gr->E, gr->weights, v);\n\n#ifdef _OPENMP\n#pragma omp parallel for schedule(dynamic)\n#endif\n  for (int s = 0; s < v; s++) {\n    std::vector <Vertex<Number>> p(num_vertices(G));\n    std::vector<Number> d(num_vertices(G));\n    dijkstra_shortest_paths(G, s, distance_map(&d[0]).predecessor_map(&p[0]).distance_inf(inf));\n    for (int vi = 0; vi < v; vi++) {\n      int i = s * v + vi;\n      distanceMatrix[i] = d[vi] + h[vi] - h[s];\n      successorMatrix[vi * v + s] = p[vi];\n    }\n  }\n\n  delete[] h;\n  free_graph<Number>(bf_graph);\n}\n\ntemplate<typename Number> void johnson_parallel_matrix(const Number *adjacencyMatrix, Number **distanceMatrix, const int n) {\n  *distanceMatrix = (Number *) malloc(sizeof(Number) * n * n);\n  memcpy(*distanceMatrix, adjacencyMatrix, sizeof(Number) * n * n);\n#ifdef CUDA\n  graph_cuda_t<Number> *cuda_gr = init_graph_cuda<Number>(adjacencyMatrix, n);\n  johnson_cuda<Number>(cuda_gr, *distanceMatrix);\n  free_graph_cuda<Number>(cuda_gr);\n#else\n  const graph_t<Number> *gr = init_graph<Number>(adjacencyMatrix, n);\n  johnson_parallel<Number>(gr, *distanceMatrix);\n  delete gr;\n#endif\n}\n\ntemplate<typename Number> void johnson_parallel_matrix(const Number *adjacencyMatrix, Number **distanceMatrix, int **successorMatrix, const int n) {\n  *distanceMatrix = (Number *) malloc(sizeof(Number) * n * n);\n  *successorMatrix = (int *) malloc(sizeof(int) * n * n);\n  memcpy(*distanceMatrix, adjacencyMatrix, sizeof(Number) * n * n);\n#ifdef CUDA\n  graph_cuda_t<Number> *cuda_gr = init_graph_cuda<Number>(adjacencyMatrix, n);\n  johnson_successor_cuda<Number>(cuda_gr, *distanceMatrix, *successorMatrix);\n  free_graph_cuda<Number>(cuda_gr);\n#else\n    const graph_t<Number> *gr = init_graph<Number>(adjacencyMatrix, n);\n  johnson_parallel<Number>(gr, *distanceMatrix, *successorMatrix);\n  delete gr;\n#endif\n}\n\ntemplate<typename Number> void free_johnson_parallel_matrix(Number **distanceMatrix) {\n  free(*distanceMatrix);\n}\ntemplate<typename Number> void free_johnson_parallel_matrix(Number **distanceMatrix, int **successorMatrix) {\n  free(*distanceMatrix);\n  free(*successorMatrix);\n}\n\nextern \"C\" void johnson_parallel_matrix_double(const double *adjacencyMatrix, double **distanceMatrix, const int n);\nextern \"C\" void free_johnson_parallel_matrix_double(double **distanceMatrix);\nextern \"C\" void johnson_parallel_matrix_float(const float *adjacencyMatrix, float **distanceMatrix, const int n);\nextern \"C\" void free_johnson_parallel_matrix_float(float **distanceMatrix);\nextern \"C\" void johnson_parallel_matrix_int(const int *adjacencyMatrix, int **distanceMatrix, const int n);\nextern \"C\" void free_johnson_parallel_matrix_int(int **distanceMatrix);\n\nextern \"C\" void johnson_parallel_matrix_successor_double(const double *adjacencyMatrix, double **distanceMatrix, int **successorMatrix, const int n);\nextern \"C\" void free_johnson_parallel_matrix_successor_double(double **distanceMatrix, int **successorMatrix);\nextern \"C\" void johnson_parallel_matrix_successor_float(const float *adjacencyMatrix, float **distanceMatrix, int **successorMatrix, const int n);\nextern \"C\" void free_johnson_parallel_matrix_successor_float(float **distanceMatrix, int **successorMatrix);\nextern \"C\" void johnson_parallel_matrix_successor_int(const int *adjacencyMatrix, int **distanceMatrix, int **successorMatrix, const int n);\nextern \"C\" void free_johnson_parallel_matrix_successor_int(int **distanceMatrix, int **successorMatrix);\n", "meta": {"hexsha": "8b774c0add9a33601f14e172337d31db83134d88", "size": 13525, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/johnson.hpp", "max_stars_repo_name": "kubohiroya/APSP-in-parallel", "max_stars_repo_head_hexsha": "c1f94d29f85129b6eaf3cbdf0c376939b7af3282", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/johnson.hpp", "max_issues_repo_name": "kubohiroya/APSP-in-parallel", "max_issues_repo_head_hexsha": "c1f94d29f85129b6eaf3cbdf0c376939b7af3282", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/johnson.hpp", "max_forks_repo_name": "kubohiroya/APSP-in-parallel", "max_forks_repo_head_hexsha": "c1f94d29f85129b6eaf3cbdf0c376939b7af3282", "max_forks_repo_licenses": ["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.3950617284, "max_line_length": 149, "alphanum_fraction": 0.6731238447, "num_tokens": 3874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5026777706330771}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu> Licensed\n * under the MIT license. See the license file LICENSE.\n */\n\n#include <iostream>\n#include <string>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <pcl/io/ply_io.h>\n#include <pcl/common/transforms.h>\n\n#include \"dpOptTrans/pcHelpers.h\"\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\nvoid ComputeMoments(const pcl::PointCloud<pcl::PointXYZRGBNormal>& pc,\n    Eigen::Matrix3d& S, Eigen::Vector3d& mu) {\n  mu.fill(0.); S.fill(0.);\n  double W = 0.;\n  for (uint32_t i=0; i<pc.size(); ++i) {\n    Eigen::Map<const Eigen::Vector3f> p(&(pc.at(i).x));\n    double w = pc.at(i).curvature; // Stores the weights\n    mu += p.cast<double>()*w;\n    W+=w;\n  }\n  mu /= W;\n  for (uint32_t i=0; i<pc.size(); ++i) {\n    Eigen::Map<const Eigen::Vector3f> p(&(pc.at(i).x));\n    double w = pc.at(i).curvature; // Stores the weights\n    S += w*(p.cast<double>()-mu) * (p.cast<double>()-mu).transpose();\n  }\n  S /= W;\n}\n\nvoid DisplayPcs(const pcl::PointCloud<pcl::PointXYZRGBNormal>& pcA, \n  const pcl::PointCloud<pcl::PointXYZRGBNormal>& pcB, \n  const Eigen::Quaterniond& q_star, const Eigen::Vector3d& t_star,\n  const Eigen::Vector3d& muA,\n  const Eigen::Vector3d& muB,\n  float scale) {\n\n    pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr pcA_ptr = pcA.makeShared();\n    pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr pcB_ptr = pcB.makeShared();\n    // Construct transformed point cloud.\n    pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr pcB_T_ptr(new\n        pcl::PointCloud<pcl::PointXYZRGBNormal>(pcB));\n    for (uint32_t i=0; i<pcB_T_ptr->size(); ++i) {\n      Eigen::Map<Eigen::Vector3f> p(&(pcB_T_ptr->at(i).x));\n      p = q_star.cast<float>().inverse()._transformVector( p - t_star.cast<float>());\n      Eigen::Map<Eigen::Vector3f> n(pcB_T_ptr->at(i).normal);\n      n = q_star.cast<float>().inverse()._transformVector(n);\n      pcB_T_ptr->at(i).rgb = ((int)128) << 16 | ((int)255) << 8 | ((int)128);\n    }\n    for (uint32_t i=0; i<pcA_ptr->size(); ++i) {\n      pcA_ptr->at(i).rgb = ((int)255) << 16 | ((int)128) << 8 | ((int)128);\n    }\n    // Construct surface normal point clouds.\n    pcl::PointCloud<pcl::PointXYZ>::Ptr nA_ptr =\n      pcl::PointCloud<pcl::PointXYZ>::Ptr(new\n          pcl::PointCloud<pcl::PointXYZ>(pcA.size(),1));\n    nA_ptr->getMatrixXfMap(3,4,0) = pcA.getMatrixXfMap(3,12,4);\n    pcl::PointCloud<pcl::PointXYZ>::Ptr nB_ptr =\n      pcl::PointCloud<pcl::PointXYZ>::Ptr(new\n          pcl::PointCloud<pcl::PointXYZ>(pcB.size(),1));\n    nB_ptr->getMatrixXfMap(3,4,0) = pcB.getMatrixXfMap(3,12,4);\n    pcl::PointCloud<pcl::PointXYZ>::Ptr nB_T_ptr =\n      pcl::PointCloud<pcl::PointXYZ>::Ptr(new\n          pcl::PointCloud<pcl::PointXYZ>(*nB_ptr));\n    for (uint32_t i=0; i<nA_ptr->size(); ++i) {\n      nA_ptr->at(i).z -=1.1;\n    }\n    for (uint32_t i=0; i<nB_T_ptr->size(); ++i) {\n      Eigen::Map<Eigen::Vector3f> n(&(nB_T_ptr->at(i).x));\n      n = q_star.cast<float>().inverse()._transformVector(n);\n      n(2) += 1.1;\n    }\n\n    // Otherwise the default is a identity rotation with scaling of\n    // 0.5.\n    pcA_ptr->sensor_orientation_.setIdentity();\n    pcB_ptr->sensor_orientation_.setIdentity();\n    pcB_T_ptr->sensor_orientation_.setIdentity();\n    nA_ptr->sensor_orientation_.setIdentity();\n    nB_ptr->sensor_orientation_.setIdentity();\n    nB_T_ptr->sensor_orientation_.setIdentity();\n\n    boost::shared_ptr<pcl::visualization::PCLVisualizer> viewerPc (new\n        pcl::visualization::PCLVisualizer (\"3D Viewer\"));\n    viewerPc->initCameraParameters ();\n    viewerPc->setBackgroundColor (1., 1., 1.);\n//    viewerPc->addCoordinateSystem (scale);\n\n    pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGBNormal>\n      rgbA(pcA_ptr);\n    pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGBNormal>\n      rgbB(pcB_ptr);\n    pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGBNormal>\n      rgbB_T(pcB_T_ptr);\n    viewerPc->addPointCloud<pcl::PointXYZRGBNormal> (pcA_ptr, rgbA, \"cloudA\");\n//    viewerPc->addPointCloud<pcl::PointXYZRGBNormal> (pcB_ptr, rgbB, \"cloudB\",v1);\n    viewerPc->addPointCloud<pcl::PointXYZRGBNormal> (pcB_T_ptr, rgbB_T,\n        \"cloudB transformed\");\n\n    char label[10];\n    pcl::PointXYZ p;\n    p.x = muA(0); p.y = muA(1); p.z = muA(2);\n    sprintf(label,\"SA%d\",0);\n    viewerPc->addSphere(p, scale, 1,0,0, label);\n    p.x = muB(0); p.y = muB(1); p.z = muB(2);\n    sprintf(label,\"SB%d\",0);\n    viewerPc->addSphere(p, scale, 0.5,1,0.5, label);\n    Eigen::Vector3d mu =\n      q_star.inverse()._transformVector(muB -t_star);\n    p.x = mu(0); p.y = mu(1); p.z = mu(2);\n    sprintf(label,\"S%d\",0);\n    viewerPc->addSphere(p, scale, 0,1,0, label);\n\n    boost::shared_ptr<pcl::visualization::PCLVisualizer> viewerNc (new\n        pcl::visualization::PCLVisualizer (\"3D Viewer\"));\n    viewerNc->initCameraParameters ();\n    viewerNc->setBackgroundColor (0., 0., 0.);\n    viewerNc->addCoordinateSystem (1.0);\n    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> \n      nA_color(nA_ptr, 255, 128, 128);\n    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> \n      nB_color(nB_ptr, 128, 255, 128);\n    viewerNc->addPointCloud<pcl::PointXYZ> (nA_ptr, nA_color,  \n        \"normalsA\");\n//    viewerNc->addPointCloud<pcl::PointXYZRGBNormal> (pcB_ptr, rgbB, \"cloudB\",v1);\n    viewerNc->addPointCloud<pcl::PointXYZ> (nB_T_ptr, nB_color, \n        \"normals B transformed\");\n\n    while (!viewerPc->wasStopped () && !viewerNc->wasStopped()) {\n      viewerPc->spinOnce (50);\n      viewerNc->spinOnce (50);\n      boost::this_thread::sleep (boost::posix_time::microseconds (100000));\n    }\n}\n\nint main(int argc, char** argv) {\n  // Declare the supported options.\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help,h\", \"produce help message\")\n    (\"in_a,a\", po::value<std::string>(), \"path to first input file\")\n    (\"in_b,b\", po::value<std::string>(), \"path to second input file\")\n    (\"out,o\", po::value<std::string>(), \"path to output file\")\n    (\"display,d\", \"display results\")\n    ;\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << desc << \"\\n\";\n    return 1;\n  }\n\n  std::string pathA = \"\";\n  std::string pathB = \"\";\n  std::string pathOut = \"\";\n  //  std::string mode = \"\";\n  //  if(vm.count(\"mode\")) mode = vm[\"mode\"].as<std::string>();\n  if(vm.count(\"in_a\")) pathA = vm[\"in_a\"].as<std::string>();\n  if(vm.count(\"in_b\")) pathB = vm[\"in_b\"].as<std::string>();\n  if(vm.count(\"out\")) pathOut = vm[\"out\"].as<std::string>();\n\n  // Load point clouds.\n  pcl::PointCloud<pcl::PointXYZRGBNormal> pcA, pcB;\n  pcl::PLYReader reader;\n  if (reader.read(pathA, pcA)) \n    std::cout << \"error reading \" << pathA << std::endl;\n  else\n    std::cout << \"loaded pc from \" << pathA << \": \" << pcA.width << \"x\"\n      << pcA.height << std::endl;\n  if (reader.read(pathB, pcB)) \n    std::cout << \"error reading \" << pathB << std::endl;\n  else\n    std::cout << \"loaded pc from \" << pathB << \": \" << pcB.width << \"x\"\n      << pcB.height << std::endl;\n\n  ComputeAreaWeightsPc(pcA);\n  ComputeAreaWeightsPc(pcB);\n\n  Eigen::Vector3d muA, muB;\n  Eigen::Matrix3d SA, SB;\n\n  ComputeMoments(pcA, SA, muA);\n  ComputeMoments(pcB, SB, muB);\n\n  // Assume xB = R*xA + t\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigA(SA);\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigB(SB);\n  Eigen::Matrix3d U = eigA.eigenvectors();\n  Eigen::Matrix3d V = eigB.eigenvectors();\n\n  // Because R apears in a quadratic form we are free to negate it.\n  // Since R \\in R^3 this negates the determinant and makes it +1. -- a\n  // rotation instead of a reflection.\n  double min_cost = 9999999.;\n  Eigen::Matrix3d R_star;\n  Eigen::Vector3d t_star;\n\n  for (uint32_t x=0; x < 3; x++)\n    for (uint32_t y=0; y < 3; y++)\n      for (uint32_t z=0; z < 3; z++)\n        for (float i=-1.; i<=1.; i+=2.) \n          for (float j=-1.; j<=1.; j+=2.) \n            for (float k=-1.; k<=1.; k+=2.) {\n              Eigen::Matrix3d P = Eigen::Matrix3d::Zero();\n              if (x == y || x == z || y == z)\n                continue;\n              P(0, x) = 1;\n              P(1, y) = 1;\n              P(2, z) = 1;\n              Eigen::Matrix3d R_ = V*P*U.inverse();\n              R_.col(0) *= i;\n              R_.col(1) *= j;\n              R_.col(2) *= k;\n              if (R_.determinant() > 0.) {\n                Eigen::Quaterniond q_(R_);\n                Eigen::Vector3d t_ = muB - R_*muA;\n                double c = ComputeClosestPointEucledianCost(pcA, pcB, &R_, &t_); \n                std::cout << \"permutation \" << P << \"\\t cost=\" << c << std::endl;\n                std::cout << q_.coeffs().transpose() \n                  << \"\\tt: \" << t_.transpose() << std::endl;\n                if(min_cost > c) {\n                  min_cost = c;\n                  R_star = R_;\n                  t_star = t_;\n                }\n              }\n            }\n  Eigen::Matrix3d R = R_star;\n  Eigen::Quaterniond q(R);\n  Eigen::Vector3d t = muB - R.transpose()*muA;\n  std::cout << \"R:\\n\"<< R << std::endl;\n  std::cout << \"det(R) = \" << R.determinant() << std::endl;\n  std::cout << \"t: \" << t.transpose() << std::endl;\n  std::cout << \"norm of difference in covariance matrixes after matching: \" \n    << (R*SA*R.transpose() -SB).norm() << std::endl;\n  std::cout << \"norm of the difference in the mean vectors after matching: \" \n    << (muA - R.transpose()*(muB - t)).norm() << std::endl;\n\n  if (vm.count(\"display\")) {\n    std::cout << \"Cov A\" << std::endl << SA << std::endl;\n    std::cout << \"EV A\" << std::endl << U << std::endl;\n    std::cout << \"E A\" << std::endl << eigA.eigenvalues() << std::endl;\n    std::cout << \"mu A \" << std::endl << muA << std::endl;\n    std::cout << \"Cov B\" << std::endl << SB << std::endl;\n    std::cout << \"EV B\" << std::endl << V << std::endl;\n    std::cout << \"E B\" << std::endl << eigB.eigenvalues() << std::endl;\n    std::cout << \"mu B \" << std::endl << muB << std::endl;\n    std::cout << \"Cov B Transformed\" << std::endl\n      << R.transpose()*SB*R << std::endl;\n    std::cout << \"mu B Transformed\" << std::endl \n      << R.transpose()*(muB - t) << std::endl;\n  }\n\n  if (false) {\n    Eigen::Matrix<double,3,6> M;\n    M << 1,-1,0,0,0,0,\n      0,0,1,-1,0,0,\n      0,0,0,0,1,-1;\n    uint32_t k =0;\n    double min_cost = 9999.;\n    Eigen::Matrix3d R_star;\n    Eigen::Vector3d t_star;\n    for(uint32_t i=0; i<6; ++i)\n      for(uint32_t j=0; j<6; ++j) {\n        Eigen::Matrix3d Rperm;\n        Rperm.col(0) = M.col(i);\n        Rperm.col(1) = M.col(j);\n        Rperm.col(2) = M.col(i).cross(M.col(j));\n        if (fabs(Rperm.determinant() -1.) < 1e-6) {\n          //        std::cout << Rperm << std::endl;\n          Eigen::Matrix3d R_ = Rperm*R;\n          Eigen::Quaterniond q_(R_);\n          Eigen::Vector3d t_ = muB - R_*muA;\n          double c = ComputeClosestPointEucledianCost(pcA, pcB, &R_, &t_); \n          std::cout << \"permutation k=\" << k << \"\\t cost=\" << c << std::endl;\n          std::cout << q_.coeffs().transpose() \n            << \"\\tt: \" << t_.transpose() << std::endl;\n          ++k; \n          if(min_cost > c) {\n            min_cost = c;\n            R_star = R_;\n            t_star = t_;\n          }\n        }\n      }\n    q = Eigen::Quaterniond(R_star);\n    t = t_star;\n  }\n  if(pathOut.size() > 1) {\n    std::ofstream out(pathOut + std::string(\".csv\"));\n    out << \"q_w q_x q_y q_z t_x t_y t_z\" << std::endl; \n    out << q.w() << \" \" << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" << t(0)\n      << \" \" << t(1) << \" \" << t(2) << \" \" << std::endl;\n    out.close();\n  }\n\n  if (vm.count(\"display\")) {\n    double scale = sqrt(eigA.eigenvalues().real().maxCoeff())/5.;\n    DisplayPcs(pcA, pcB, q, t, muA, muB, scale);\n  }\n}\n\n", "meta": {"hexsha": "f05cf1e7a63cc93d1775c03da0c78d35ec88db61", "size": 11810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/moment_matched_T3.cpp", "max_stars_repo_name": "jstraub/dpOptTrans", "max_stars_repo_head_hexsha": "b8c6549a140b2b4abefeb2fd5180e805c285e10d", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-06-15T14:41:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T00:03:09.000Z", "max_issues_repo_path": "src/moment_matched_T3.cpp", "max_issues_repo_name": "jstraub/dpOptTrans", "max_issues_repo_head_hexsha": "b8c6549a140b2b4abefeb2fd5180e805c285e10d", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-01-12T04:55:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-19T01:37:13.000Z", "max_forks_repo_path": "src/moment_matched_T3.cpp", "max_forks_repo_name": "jstraub/dpOptTrans", "max_forks_repo_head_hexsha": "b8c6549a140b2b4abefeb2fd5180e805c285e10d", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2016-06-15T14:42:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-28T23:48:33.000Z", "avg_line_length": 37.9742765273, "max_line_length": 85, "alphanum_fraction": 0.5762912786, "num_tokens": 3755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5026777645863636}}
{"text": "#include <iostream>\n#include <stdlib.h>\n#include <stdio.h>\n//#include <omp.h>\n\n#include <boost/pool/object_pool.hpp>\n\n\nconst size_t\tLINE_SIZE = 64;\n\n\nstruct Node\n{\n    Node *l, *r;\n    int i;\n\n    Node(int i2) : l(0), r(0), i(i2)\n    {}\n    Node(Node *l2, int i2, Node *r2) : l(l2), r(r2), i(i2)\n    {}\n\n    int check() const\n    {\n        if (l)\n            return l->check() + i - r->check();\n        else return i;\n    }\n};\n\ntypedef boost::object_pool<Node> NodePool;\n\n\nNode *make(int i, int d, NodePool &store)\n{\n    if (d > 0)\n\t    return store.construct(\tmake(2*i-1, d-1, store),\n\t    \t\t\t\t\t\ti,\n\t    \t\t\t\t\t\tmake(2*i, d-1, store)\t);\n   \treturn store.construct(i);\n}\n\n// int GetThreadCount()\n// {\n// \tcpu_set_t cs;\n// \tCPU_ZERO(&cs);\n// \tsched_getaffinity(0, sizeof(cs), &cs);\n\n// \tint count = 0;\n// \tfor (int i = 0; i < 8; i++)\n// \t{\n// \t\tif (CPU_ISSET(i, &cs))\n// \t\t\tcount++;\n// \t}\n// \treturn count;\n// }\n\nint main(int argc, char *argv[])\n{\n    int min_depth = 4;\n    int max_depth = std::max(min_depth+2,\n                             (argc == 2 ? atoi(argv[1]) : 10));\n    int stretch_depth = max_depth+1;\n    int i;  \n    for(i=0;i<3;i++){ \n\t// Alloc then dealloc stretchdepth tree\n    {\n        NodePool store;\n        Node *c = make(0, stretch_depth, store);\n        std::cout << \"stretch tree of depth \" << stretch_depth << \"\\t \"\n                  << \"check: \" << c->check() << std::endl;\n    }\n\n    NodePool long_lived_store;\n    Node *long_lived_tree = make(0, max_depth, long_lived_store);\n\n\t// buffer to store output of each thread\n\tchar *outputstr = (char*)malloc(LINE_SIZE * (max_depth +1) * sizeof(char));\n\n// \t#pragma omp parallel for default(shared) num_threads(GetThreadCount()) schedule(dynamic, 1)\n    for (int d = min_depth; d <= max_depth; d += 2)\n    {\n        int iterations = 1 << (max_depth - d + min_depth);\n        int c = 0;\n\n        for (int i = 1; i <= iterations; ++i)\n        {\n            NodePool store;\n            Node *a = make(i, d, store), *b = make(-i, d, store);\n            c += a->check() + b->check();\n        }\n\n\t\t// each thread write to separate location\n\t\tsprintf(outputstr + LINE_SIZE * d, \"%d\\t trees of depth %d\\t check: %d\\n\", (2 * iterations), d, c);\n\t}\n\n\t// print all results\n\tfor (int d = min_depth; d <= max_depth; d += 2)\n\t\tprintf(\"%s\", outputstr + (d * LINE_SIZE) );\n\tfree(outputstr);\n\n    std::cout << \"long lived tree of depth \" << max_depth << \"\\t \"\n              << \"check: \" << (long_lived_tree->check()) << \"\\n\";\n    }\n    return 0;\n}\n\n/*\nMAKE:\n/usr/bin/g++ -c -pipe -O3 -fomit-frame-pointer -march=native  -fopenmp binarytrees.gpp-6.c++ -o binarytrees.gpp-6.c++.o &&  \\\n        /usr/bin/g++ binarytrees.gpp-6.c++.o -o binarytrees.gpp-6.gpp_run -fopenmp \n*/\n", "meta": {"hexsha": "ac008eb05c7fc7c59f2771d0ccb8531435bc9f1b", "size": 2723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/shootout/binarytrees/binarytrees.cpp", "max_stars_repo_name": "jb55/clay", "max_stars_repo_head_hexsha": "db0bd2702ab0b6e48965cd85f8859bbd5f60e48e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 185.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T09:33:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T04:53:38.000Z", "max_issues_repo_path": "examples/shootout/binarytrees/binarytrees.cpp", "max_issues_repo_name": "aep/clay", "max_issues_repo_head_hexsha": "92224d71c9d64a32d70a289593c13da7f970ec35", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T06:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2015-12-28T19:07:24.000Z", "max_forks_repo_path": "examples/shootout/binarytrees/binarytrees.cpp", "max_forks_repo_name": "aep/clay", "max_forks_repo_head_hexsha": "92224d71c9d64a32d70a289593c13da7f970ec35", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-01-09T22:24:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T04:54:59.000Z", "avg_line_length": 24.3125, "max_line_length": 125, "alphanum_fraction": 0.5416819684, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867729389246, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.5026777615630069}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <k52/dsp/transform/wavelet/linear_scale.h>\n#include <k52/dsp/transform/wavelet/logarithmic_scale.h>\n#include <k52/common/constants.h>\n\nusing ::k52::common::Constants;\nusing ::k52::dsp::LinearScale;\nusing ::k52::dsp::LogarithmicScale;\nusing ::std::vector;\nusing ::std::invalid_argument;\n\nBOOST_AUTO_TEST_SUITE(scale_tests);\n\nBOOST_AUTO_TEST_SUITE(linear);\n\nBOOST_AUTO_TEST_CASE(min_scale_negative)\n{\n    BOOST_REQUIRE_THROW(LinearScale(-0.1, 10, 7), invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE(min_scale_zero)\n{\n    BOOST_REQUIRE_THROW(LinearScale(0, 10, 7), invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE(max_scale_negative)\n{\n    BOOST_REQUIRE_THROW(LinearScale(0.1, -10, 7), invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE(max_scale_zero)\n{\n    BOOST_REQUIRE_THROW(LinearScale(0.1, 0, 7), invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE(min_greater_than_max)\n{\n    BOOST_REQUIRE_THROW(LinearScale(4, 2, 7), invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE(count_zero)\n{\n    BOOST_REQUIRE_THROW(LinearScale(1, 2, 0), invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE(count_less_than_two)\n{\n    BOOST_REQUIRE_THROW(LinearScale(1, 2, 1), invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE(size)\n{\n    //Prepare\n    LinearScale linear_scale(0.1, 10, 7);\n\n    //Test\n    vector< double > scales = linear_scale.GetScales();\n\n    //Check\n    BOOST_REQUIRE_EQUAL(scales.size(), 7);\n}\n\nBOOST_AUTO_TEST_CASE(scale_values)\n{\n    //Prepare\n    LinearScale linear_scale(0.3, 12, 5);\n\n    //Test\n    vector< double > scales = linear_scale.GetScales();\n\n    //Check\n    BOOST_CHECK_SMALL(scales[0] - 0.3, Constants::Eps);\n    BOOST_CHECK_SMALL(scales[1] - 3.225, Constants::Eps);\n    BOOST_CHECK_SMALL(scales[2] - 6.15, Constants::Eps);\n    BOOST_CHECK_SMALL(scales[3] - 9.075, Constants::Eps);\n    BOOST_CHECK_SMALL(scales[4] - 12, Constants::Eps);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n\nBOOST_AUTO_TEST_SUITE(logarithmic);\n\nBOOST_AUTO_TEST_CASE(min_greater_than_max)\n{\n    BOOST_REQUIRE_THROW(LogarithmicScale logarithmic_scale(100, -100), invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE(min_equal_max)\n{\n    BOOST_REQUIRE_THROW(LogarithmicScale logarithmic_scale(7, 7), invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE(size)\n{\n    //Prepare\n    LogarithmicScale logarithmic_scale(-10, 10);\n\n    //Test\n    vector< double > scales = logarithmic_scale.GetScales();\n\n    //Check\n    BOOST_REQUIRE_EQUAL(scales.size(), 21);\n}\n\nBOOST_AUTO_TEST_CASE(scale_values)\n{\n    //Prepare\n    LogarithmicScale logarithmic_scale(-2, 3);\n\n    //Test\n    vector< double > scales = logarithmic_scale.GetScales();\n\n    //Check\n    BOOST_CHECK_SMALL(scales[0] - 0.25, Constants::Eps);\n    BOOST_CHECK_SMALL(scales[1] - 0.5, Constants::Eps);\n    BOOST_CHECK_SMALL(scales[2] - 1, Constants::Eps);\n    BOOST_CHECK_SMALL(scales[3] - 2, Constants::Eps);\n    BOOST_CHECK_SMALL(scales[4] - 4, Constants::Eps);\n    BOOST_CHECK_SMALL(scales[5] - 8, Constants::Eps);\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n\nBOOST_AUTO_TEST_SUITE_END();", "meta": {"hexsha": "b00c79c63fb49a95c2b18a6094d3e84f1ef861d4", "size": 2981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/unit_tests/dsp/scale.test.cpp", "max_stars_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_stars_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2016-04-14T07:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-22T22:03:20.000Z", "max_issues_repo_path": "src/unit_tests/dsp/scale.test.cpp", "max_issues_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_issues_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2016-04-05T08:49:05.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-29T07:09:00.000Z", "max_forks_repo_path": "src/unit_tests/dsp/scale.test.cpp", "max_forks_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_forks_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-16T07:53:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-12T21:31:51.000Z", "avg_line_length": 23.6587301587, "max_line_length": 89, "alphanum_fraction": 0.7343173432, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5026777534936964}}
{"text": "#include <armadillo>\n\n#include \"DenseMatrix.h\"\n\nstruct DenseMatrix::Impl {\n    arma::dmat RawData;\n\n  public:\n    Impl() = default;\n};\n\nstruct DenseVector::SubspectrumDataImpl {\n    arma::dvec eigenvalues;\n\n  public:\n    SubspectrumDataImpl() = default;\n};\n\nDenseMatrix::DenseMatrix() : pImpl {std::make_unique<DenseMatrix::Impl>()} {}\n\nDenseVector::DenseVector() : pImpl {std::make_unique<DenseVector::SubspectrumDataImpl>()} {}\n\nDenseMatrix::~DenseMatrix() = default;\nDenseMatrix::DenseMatrix(DenseMatrix&&) noexcept = default;\nDenseMatrix& DenseMatrix::operator=(DenseMatrix&&) noexcept = default;\nDenseVector::~DenseVector() = default;\nDenseVector::DenseVector(DenseVector&&) noexcept = default;\nDenseVector& DenseVector::operator=(DenseVector&&) noexcept = default;\n\nvoid DenseMatrix::add_to_position(double value, uint32_t i, uint32_t j) {\n    pImpl->RawData(i, j) += value;\n}\n\nvoid DenseMatrix::assign_to_position(double value, uint32_t i, uint32_t j) {\n    pImpl->RawData(i, j) = value;\n}\n\nstd::ostream& operator<<(std::ostream& os, const DenseMatrix& decomposition) {\n    os << decomposition.pImpl->RawData << std::endl;\n    return os;\n}\n\nstd::ostream& operator<<(std::ostream& os, const DenseVector& raw_data) {\n    os << raw_data.pImpl->eigenvalues << std::endl;\n    return os;\n}\n\nvoid DenseMatrix::resize(\n    uint32_t matrix_in_space_basis_size_i,\n    uint32_t matrix_in_space_basis_size_j) {\n    // TODO: is it the fastest way to initialize pImpl->RawData?\n    pImpl->RawData.resize(matrix_in_space_basis_size_i, matrix_in_space_basis_size_j);\n    pImpl->RawData.fill(arma::fill::zeros);\n}\n\nvoid DenseMatrix::resize_with_nans(\n    uint32_t matrix_in_space_basis_size_i,\n    uint32_t matrix_in_space_basis_size_j) {\n    // TODO: is it the fastest way to initialize pImpl->RawData?\n    pImpl->RawData.resize(matrix_in_space_basis_size_i, matrix_in_space_basis_size_j);\n    pImpl->RawData.fill(arma::datum::nan);\n    //    for (size_t i = 0; i < pImpl->RawData.n_rows; ++i) {\n    //        for (size_t j = 0; j < pImpl->RawData.n_rows; ++j) {\n    //            pImpl->RawData(i, j) = NAN;\n    //        }\n    //    }\n}\n\nvoid DenseMatrix::diagonalize(DenseVector& values, DenseMatrix& vectors) const {\n    arma::eig_sym(values.pImpl->eigenvalues, vectors.pImpl->RawData, pImpl->RawData);\n}\n\nvoid DenseMatrix::diagonalize(DenseVector& values) const {\n    arma::eig_sym(values.pImpl->eigenvalues, pImpl->RawData);\n}\n\nDenseMatrix DenseMatrix::unitary_transform(const DenseMatrix& matrix_to_transform) const {\n    DenseMatrix transformed_matrix;\n    transformed_matrix.pImpl->RawData =\n        pImpl->RawData.t() * matrix_to_transform.pImpl->RawData * pImpl->RawData;\n    return std::move(transformed_matrix);\n}\n\nDenseVector DenseMatrix::return_main_diagonal() const {\n    DenseVector main_diagonal;\n    main_diagonal.pImpl->eigenvalues = pImpl->RawData.diag();\n    return std::move(main_diagonal);\n}\n\ndouble DenseMatrix::operator()(uint32_t i, uint32_t j) const {\n    return pImpl->RawData(i, j);\n}\n\nuint32_t DenseMatrix::size() const {\n    return pImpl->RawData.n_rows;\n}\n\nuint32_t DenseMatrix::size_rows() const {\n    return pImpl->RawData.n_rows;\n}\n\nuint32_t DenseMatrix::size_cols() const {\n    return pImpl->RawData.n_rows;\n}\n\nuint32_t DenseVector::size() const {\n    return pImpl->eigenvalues.size();\n}\n\ndouble DenseVector::operator()(uint32_t i) const {\n    return pImpl->eigenvalues(i);\n}\n\nvoid DenseVector::assign_to_position(double value, uint32_t i) {\n    pImpl->eigenvalues.at(i) = value;\n}\n\nvoid DenseVector::resize(uint32_t new_size) {\n    pImpl->eigenvalues.resize(new_size);\n}\n\nstd::vector<double> concatenate(const std::vector<DenseVector>& dense_vectors) {\n    size_t size = 0;\n    for (const auto& dense_vector : dense_vectors) {\n        size += dense_vector.size();\n    }\n    std::vector<double> result_vector;\n    result_vector.reserve(size);\n    for (const auto& dense_vector : dense_vectors) {\n        result_vector.insert(\n            result_vector.end(),\n            dense_vector.pImpl->eigenvalues.begin(),\n            dense_vector.pImpl->eigenvalues.end());\n    }\n    return result_vector;\n}\n\nbool DenseVector::operator==(const DenseVector& rhs) const {\n    return arma::approx_equal(pImpl->eigenvalues, rhs.pImpl->eigenvalues, \"absdiff\", 0);\n}\n\nbool DenseVector::operator!=(const DenseVector& rhs) const {\n    return !(rhs == *this);\n}\n\nDenseVector DenseVector::divide_and_wise_exp(double denominator) const {\n    DenseVector answer;\n    answer.resize(size());\n    answer.pImpl->eigenvalues = arma::exp(pImpl->eigenvalues / (denominator));\n    return answer;\n}\n\ndouble DenseVector::dot(const DenseVector& rhs) const {\n    return arma::dot(pImpl->eigenvalues, rhs.pImpl->eigenvalues);\n}\n\nDenseVector DenseVector::element_wise_multiplication(const DenseVector& rhs) const {\n    DenseVector answer;\n    answer.pImpl->eigenvalues = pImpl->eigenvalues % rhs.pImpl->eigenvalues;\n    return answer;\n}\n\nvoid DenseVector::concatenate_with(const DenseVector& rhs) {\n    arma::dvec tmp = arma::join_cols(pImpl->eigenvalues, rhs.pImpl->eigenvalues);\n    pImpl->eigenvalues.reset();\n    pImpl->eigenvalues = std::move(tmp);\n}\n\nvoid DenseVector::add_identical_values(size_t number, double value) {\n    arma::dvec tmp;\n    tmp.resize(number);\n    tmp.fill(value);\n    tmp = arma::join_cols(pImpl->eigenvalues, tmp);\n    pImpl->eigenvalues.reset();\n    pImpl->eigenvalues = std::move(tmp);\n}\n\nvoid DenseVector::subtract_minimum() {\n    double minimum = arma::min(pImpl->eigenvalues);\n    pImpl->eigenvalues -= minimum;\n}", "meta": {"hexsha": "d04d298073deb0921fe4ac1e58bf81cbad66d3a6", "size": 5539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/entities/data_structures/DenseMatrix_arma-dmat.cpp", "max_stars_repo_name": "ruthenium96/july", "max_stars_repo_head_hexsha": "62f93b33253cd7324b36c851afc58b6f80c00248", "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/entities/data_structures/DenseMatrix_arma-dmat.cpp", "max_issues_repo_name": "ruthenium96/july", "max_issues_repo_head_hexsha": "62f93b33253cd7324b36c851afc58b6f80c00248", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-11-28T14:29:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T08:16:20.000Z", "max_forks_repo_path": "src/entities/data_structures/DenseMatrix_arma-dmat.cpp", "max_forks_repo_name": "ruthenium96/july", "max_forks_repo_head_hexsha": "62f93b33253cd7324b36c851afc58b6f80c00248", "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.6022099448, "max_line_length": 92, "alphanum_fraction": 0.7089727388, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5026716236944951}}
{"text": "/**\n * @author     : Zhao Chonyyao (cyzhao@zju.edu.cn)\n * @date       : 2021-04-30\n * @description: simple mass spring problem\n * @version    : 1.0\n */\n#include <memory>\n\n#include <boost/property_tree/ptree.hpp>\n\n#include \"Common/error.h\"\n\n// TODO: possible bad idea of having dependence to model in problem module\n#include \"Model/fem/elas_energy.h\"\n#include \"Model/fem/mass_matrix.h\"\n#include \"Model/mass_spring/mass_spring_obj.h\"\n#include \"Model/mass_spring/para.h\"\n\n#include \"Problem/energy/basic_energy.h\"\n#include \"Io/io.h\"\n#include \"Geometry/extract_surface.imp\"\n\n#include \"mass_spring_problem.h\"\n\nnamespace PhysIKA {\nusing namespace std;\nusing namespace Eigen;\n\ntemplate <typename T>\nusing MAT = Eigen::Matrix<T, -1, -1>;\ntemplate <typename T>\nusing VEC = Eigen::Matrix<T, -1, 1>;\n\ntemplate <typename T>\nms_problem_builder<T>::ms_problem_builder(const T* x, const boost::property_tree::ptree& para_tree)\n    : pt_(para_tree)\n{\n    auto blender            = para_tree.get_child(\"blender\");\n    auto simulation_para    = para_tree.get_child(\"simulation_para\");\n    auto common             = para_tree.get_child(\"common\");\n    para::dt                = common.get<double>(\"time_step\", 0.01);\n    para::line_search       = simulation_para.get<int>(\"line_search\", true);  // todo\n    para::density           = common.get<double>(\"density\", 10);\n    para::frame             = common.get<int>(\"frame\", 100);\n    para::newton_fastMS     = simulation_para.get<string>(\"newton_fastMS\");\n    para::stiffness         = simulation_para.get<double>(\"stiffness\", 8000);\n    para::gravity           = common.get<double>(\"gravity\", 9.8);\n    para::object_name       = blender.get<string>(\"surf\");\n    para::out_dir_simulator = common.get<string>(\"out_dir_simulator\");\n    para::simulation_type   = simulation_para.get<string>(\"simulation\", \"static\");\n    para::weight_line_search =\n        simulation_para.get<double>(\"weight_line_search\", 1e-5);\n    para::input_object   = common.get<string>(\"input_object\");\n    para::force_function = simulation_para.get<string>(\"force_function\");\n    para::intensity      = simulation_para.get<double>(\"intensity\");\n    para::coll_z         = simulation_para.get<bool>(\"coll_z\", false);\n    //TODO: need to check exception\n\n    const string      filename = para::input_object;\n    Matrix<T, -1, -1> nods;\n    MatrixXi          cells;\n    IF_ERR(exit, mesh_read_from_vtk<T, 4>(filename.c_str(), nods, cells));\n\n    const size_t num_nods = nods.cols();\n    if (x != nullptr)\n        nods = Map<const MAT<T>>(x, nods.rows(), nods.cols());\n\n    REST_  = nods;\n    cells_ = cells;\n\n    //read fixed points\n    vector<size_t> cons(0);\n    if (para_tree.find(\"input_constraint\") != para_tree.not_found())\n    {\n        const string cons_file_path = common.get<string>(\"input_constraint\");\n        /* IF_ERR(exit, read_fixed_verts_from_csv(cons_file_path.c_str(), cons));*/\n    }\n    cout << \"constrint \" << cons.size() << \" points\" << endl;\n\n    //calc mass vector\n    Matrix<T, -1, 1> mass_vec(num_nods);\n    calc_mass_vector<T>(nods, cells, para::density, mass_vec);\n    // mass_calculator<T, 3, 4, 1, 1, basis_func, quadrature>(nods, cells, para::density, mass_vec);\n\n    cout << \"build energy\" << endl;\n    int ELAS = 0;\n    int GRAV = 1;\n    int KIN  = 2;\n    int POS  = 3;\n    if (pt_.get<string>(\"solver_type\") == \"explicit\")\n        POS = 2;\n\n    ebf_.resize(POS + 1);\n    ebf_[ELAS] = make_shared<MassSpringObj<T>>(para::input_object.c_str(), para::stiffness);\n    char axis  = common.get<char>(\"grav_axis\", 'y') | 0x20;\n\n    ebf_[GRAV] = make_shared<gravity_energy<T, 3>>(num_nods, 1, para::gravity, mass_vec, axis);\n    kinetic_   = make_shared<momentum<T, 3>>(nods.data(), num_nods, mass_vec, para::dt);\n\n    if (pt_.get<string>(\"solver_type\") == \"implicit\")\n        ebf_[KIN] = kinetic_;\n    ebf_[POS] = make_shared<position_constraint<T, 3>>(nods.data(), num_nods, simulation_para.get<double>(\"w_pos\", 1e6), cons);\n\n    //set constraint\n    enum constraint_type\n    {\n        COLL\n    };\n    cbf_.resize(COLL + 1);\n    collider_  = nullptr;\n    cbf_[COLL] = collider_;\n\n    if (pt_.get<string>(\"solver_type\") == \"explicit\")\n    {\n        Map<Matrix<T, -1, 1>> position(REST_.data(), REST_.size());\n        semi_implicit_ = make_shared<semi_implicit<T>>(para::dt, mass_vec, position);\n    }\n}\n\ntemplate <typename T>\nstd::shared_ptr<Problem<T, 3>> ms_problem_builder<T>::build_problem() const\n{\n    cout << \"assemble energy\" << endl;\n    shared_ptr<Functional<T, 3>> energy;\n    try\n    {\n        energy = build_energy_t<T, 3>(ebf_);\n    }\n    catch (std::exception& e)\n    {\n        cerr << e.what() << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    shared_ptr<Constraint<T>> constraint;\n    cout << \"assemble constraint\" << endl;\n    bool all_null = true;\n    for (auto& c : cbf_)\n        if (c != nullptr)\n            all_null = false;\n    if (all_null)\n    {\n        constraint = nullptr;\n        cout << \"WARNGING: No hard constraints.\" << endl;\n    }\n    else\n    {\n        try\n        {\n            constraint = build_constraint_t<T>(cbf_);\n        }\n        catch (std::exception& e)\n        {\n            cerr << e.what() << endl;\n            exit(EXIT_FAILURE);\n        }\n    }\n\n    exit_if(constraint != nullptr && energy->Nx() != constraint->Nx(), \"energy and constraint has different dimension.\");\n    return make_shared<Problem<T, 3>>(energy, constraint);\n}\n\ntemplate <typename T>\nint ms_problem_builder<T>::update_problem(const T* x, const T* v)\n{\n    IF_ERR(return, kinetic_->update_location_and_velocity(x, v));\n    if (collider_ != nullptr)\n        IF_ERR(return, collider_->update(x));\n    return 0;\n}\n\ntemplate class ms_problem_builder<double>;\n\ntemplate class ms_problem_builder<float>;\n\n}  // namespace PhysIKA\n", "meta": {"hexsha": "abeeebf470c050bb20df42261bb26fa223654ba1", "size": 5763, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Source/Dynamics/FiniteElementMethod/Source/Problem/integrated_problem/mass_spring_problem.cc", "max_stars_repo_name": "weikm/sandcarSimulation2", "max_stars_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "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": "Source/Dynamics/FiniteElementMethod/Source/Problem/integrated_problem/mass_spring_problem.cc", "max_issues_repo_name": "weikm/sandcarSimulation2", "max_issues_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "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": "Source/Dynamics/FiniteElementMethod/Source/Problem/integrated_problem/mass_spring_problem.cc", "max_forks_repo_name": "weikm/sandcarSimulation2", "max_forks_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "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.5593220339, "max_line_length": 127, "alphanum_fraction": 0.6284921048, "num_tokens": 1543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5026716236944951}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_DIVROUND2EVEN_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_DIVROUND2EVEN_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/divround2even.hpp>\n#include <boost/simd/include/functions/scalar/round2even.hpp>\n#include <boost/simd/include/functions/scalar/abs.hpp>\n#include <boost/simd/include/functions/scalar/is_even.hpp>\n#include <boost/simd/include/functions/scalar/is_odd.hpp>\n#include <boost/simd/include/functions/scalar/copysign.hpp>\n#include <boost/simd/include/functions/scalar/tofloat.hpp>\n#include <boost/simd/include/constants/valmin.hpp>\n#include <boost/simd/include/constants/valmax.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( divround2even_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< int64_<A0> >)\n                                      (scalar_< int64_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename boost::dispatch::meta::as_integer<A0, unsigned>::type uitype;\n      if (!a0) return  Zero<result_type>();\n      if(a1)\n      {\n        uitype aa0 = abs(a0);\n        uitype aa1 = abs(a1);\n        uitype q = aa0/aa1;\n        uitype rx2 = 2*(aa0-q*aa1);\n        if (rx2 >= aa1)\n        {\n          if ((rx2 == aa1) && is_even(q)) --q;\n          ++q;\n        }\n        return copysign(result_type(q), a0^a1);\n      }\n      else\n        return ((a0>0) ? Valmax<result_type>() : Valmin<result_type>());\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( divround2even_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< signed_<A0> >)\n                                      (scalar_< signed_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      if(a1)\n        return static_cast<result_type >(round2even(static_cast<double>(a0)/static_cast<double>(a1)));\n      else\n      {\n        return (a0) ? ((a0>0) ? Valmax<result_type>() : Valmin<result_type>()) : Zero<result_type>();\n      }\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( divround2even_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< unsigned_<A0> >)\n                                      (scalar_< unsigned_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      if(a1)\n      {\n        result_type q = a0/a1;\n        result_type rx2 = 2*(a0-q*a1);\n        if (rx2 >= a1)\n        {\n          if ((rx2 == a1) && is_even(q)) --q;\n          ++q;\n        }\n        return q;\n      }\n      else\n        return (a0) ? Valmax<result_type>() : Zero<result_type>();\n    }\n  };\n\n#ifdef BOOST_MSVC\n  #pragma warning(push)\n  #pragma warning(disable: 4723) // potential divide by 0\n#endif\n\n  BOOST_DISPATCH_IMPLEMENT          ( divround2even_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< floating_<A0> > )\n                                      (scalar_< floating_<A0> > )\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return round2even(a0/a1);\n    }\n  };\n} } }\n\n#ifdef BOOST_MSVC\n  #pragma warning(pop)\n#endif\n\n#endif\n", "meta": {"hexsha": "cd0b648bbfa6e50a00d92691bca7719ba20e509b", "size": 4058, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/divround2even.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/divround2even.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/divround2even.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 32.9918699187, "max_line_length": 102, "alphanum_fraction": 0.5152784623, "num_tokens": 973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5026716183670039}}
{"text": "// Std includes\n#include <cmath>\n#include <iostream>\n// Thirdparties includes\n#include <Eigen/Dense>\n// Lib includes\n#include \"Eigen/src/Core/Matrix.h\"\n#include \"s0s/runge_kutta_fehlberg.h\"\n#include \"sl0/ellipsoid.h\"\n// Simple includes\n#include \"flow.h\"\n\n// Types\nusing TypeScalar = double;\ntemplate<int Size>\nusing TypeVector = Eigen::Matrix<TypeScalar, Size, 1>;\ntemplate<int Nx, int Ny>\nusing TypeMatrix = Eigen::Matrix<TypeScalar, Nx, Ny>;\n// Space\nconstexpr unsigned int DIM = 3;\nusing TypeSpaceVector = Eigen::Matrix<TypeScalar, DIM, 1>;\nusing TypeSpaceMatrix = Eigen::Matrix<TypeScalar, DIM, DIM>;\n// Ref and View\ntemplate<typename ...Args>\nusing TypeRef = Eigen::Ref<Args...>;\ntemplate<typename ...Args>\nusing TypeView = Eigen::Map<Args...>;\n// Solver\nusing TypeSolver = s0s::SolverRungeKuttaFehlberg<TypeVector<Eigen::Dynamic>, TypeView>;\n// Flow\nusing TypeFlow = Flow<TypeSpaceVector, TypeSpaceMatrix, TypeRef>;\n\nint main () { \n\tTypeSpaceVector x0;\n\tx0 << 0,\n\t\t  0,\n\t\t  0;\n\tTypeSpaceVector p0;\n\tp0 << 1,\n\t\t  0,\n\t\t  0;\n\tTypeSpaceVector p1;\n\tp1 << 0,\n\t\t  1,\n\t\t  0;\n\tdouble t0 = 0.0;\n\tdouble dt = 1e-2;\n\tdouble tEnd = 1.0;\n\t// Create ellipsoid\n\tsl0::Ellipsoid<TypeVector, TypeMatrix, DIM, TypeView, TypeFlow, TypeSolver> ellipsoid(std::make_shared<TypeFlow>(), std::vector<double>({1.0, 1.0, 1.0}));\n\t// Set initial state\n\tellipsoid.sStep->x(ellipsoid.state.data()) = x0;\n\tellipsoid.sStep->axis(ellipsoid.state.data(), 0) = p0;\n\tellipsoid.sStep->axis(ellipsoid.state.data(), 1) = p1;\n\tellipsoid.t = t0;\n\t// Compute\n\tstd::cout << \"Ellipsoid in a simple shear flow : \\n\";\n\tstd::cout << \"\\n\";\n\tstd::cout << \"Orientation after each step : \\n\";\n\tfor(std::size_t i = 0; i < (tEnd - t0)/dt; i++) {\n\t\tellipsoid.update(dt);\n\t\tstd::cout << ellipsoid.sStep->cBasis(ellipsoid.state.data()) << \"\\n\";\n\t}\n\t// out\n\tstd::cout << \"Ellipsoid in a simple shear flow : \\n\";\n\tstd::cout << \"\\n\";\n\tstd::cout << \"Final orientation : \\n\";\n\tstd::cout << ellipsoid.sStep->cBasis(ellipsoid.state.data()) << \"\\n\";\n\tstd::cout << std::endl;\n}\n", "meta": {"hexsha": "361658bcc7b725b20614ac4596efb09e0d51c473", "size": 2018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/ellipsoid/main.cpp", "max_stars_repo_name": "C0PEP0D/sl0", "max_stars_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_stars_repo_licenses": ["MIT"], "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/ellipsoid/main.cpp", "max_issues_repo_name": "C0PEP0D/sl0", "max_issues_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_issues_repo_licenses": ["MIT"], "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/ellipsoid/main.cpp", "max_forks_repo_name": "C0PEP0D/sl0", "max_forks_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_forks_repo_licenses": ["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.4225352113, "max_line_length": 155, "alphanum_fraction": 0.6729435084, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5026716130395125}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGY_SPHERICAL_AREA_BOX_HPP\n#define BOOST_GEOMETRY_STRATEGY_SPHERICAL_AREA_BOX_HPP\n\n\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/srs/sphere.hpp>\n#include <boost/geometry/strategies/spherical/get_radius.hpp>\n#include <boost/geometry/strategy/area.hpp>\n#include <boost/geometry/util/normalize_spheroidal_box_coordinates.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace area\n{\n\n// https://math.stackexchange.com/questions/131735/surface-element-in-spherical-coordinates\n// http://www.cs.cmu.edu/afs/cs/academic/class/16823-s16/www/pdfs/appearance-modeling-3.pdf\n// https://www.astronomyclub.xyz/celestial-sphere-2/solid-angle-on-the-celestial-sphere.html\n// https://mathworld.wolfram.com/SolidAngle.html\n// https://en.wikipedia.org/wiki/Spherical_coordinate_system\n// Note that the equations used in the above articles are spherical polar coordinates.\n// We use spherical equatorial, so the equation is different:\n// assume(y_max > y_min);\n// assume(x_max > x_min);\n// /* because of polar to equatorial conversion */\n// sin(%pi / 2 - y);\n// O: r ^ 2 * cos(y);\n// S: integrate(integrate(O, y, y_min, y_max), x, x_min, x_max);\ntemplate\n<\n    typename RadiusTypeOrSphere = double,\n    typename CalculationType = void\n>\nclass spherical_box\n{\n    typedef typename strategy_detail::get_radius\n        <\n            RadiusTypeOrSphere\n        >::type radius_type;\n\npublic:\n    template <typename Box>\n    struct result_type\n        : strategy::area::detail::result_type\n            <\n                Box,\n                CalculationType\n            >\n    {};\n\n    // For consistency with other strategies the radius is set to 1\n    inline spherical_box()\n        : m_radius(1.0)\n    {}\n\n    template <typename RadiusOrSphere>\n    explicit inline spherical_box(RadiusOrSphere const& radius_or_sphere)\n        : m_radius(strategy_detail::get_radius\n                    <\n                        RadiusOrSphere\n                    >::apply(radius_or_sphere))\n    {}\n    \n    template <typename Box>\n    inline auto apply(Box const& box) const\n    {\n        typedef typename result_type<Box>::type return_type;\n\n        return_type x_min = get_as_radian<min_corner, 0>(box); // lon\n        return_type y_min = get_as_radian<min_corner, 1>(box); // lat\n        return_type x_max = get_as_radian<max_corner, 0>(box);\n        return_type y_max = get_as_radian<max_corner, 1>(box);\n\n        if (x_min == x_max || y_max == y_min)\n        {\n            return return_type(0);\n        }\n\n        math::normalize_spheroidal_box_coordinates<radian>(x_min, y_min, x_max, y_max);\n\n        return (x_max - x_min)\n             * (sin(y_max) - sin(y_min))\n             * return_type(m_radius * m_radius);\n    }\n\n    srs::sphere<radius_type> model() const\n    {\n        return srs::sphere<radius_type>(m_radius);\n    }\n\nprivate:\n    radius_type m_radius;\n};\n\n\n}} // namespace strategy::area\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGY_SPHERICAL_AREA_BOX_HPP\n", "meta": {"hexsha": "8ee29a7789093b481662c6108705330da98c83ac", "size": 3395, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/geometry/strategy/spherical/area_box.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/geometry/strategy/spherical/area_box.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/geometry/strategy/spherical/area_box.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 29.2672413793, "max_line_length": 92, "alphanum_fraction": 0.682179676, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5026716130395125}}
{"text": "\ufeff//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include \"RefWorkloadFactoryHelper.hpp\"\n\n#include <test/TensorHelpers.hpp>\n#include <test/UnitTests.hpp>\n\n#include <reference/RefWorkloadFactory.hpp>\n#include <backendsCommon/test/DetectionPostProcessLayerTestImpl.hpp>\n#include <backendsCommon/test/LayerTests.hpp>\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(Compute_Reference)\nusing FactoryType = armnn::RefWorkloadFactory;\n\n// ============================================================================\n// UNIT tests\n\n// Convolution\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5, SimpleConvolution2d3x5Test, true, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5Uint8, SimpleConvolution2d3x5Uint8Test, true, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5Nhwc, SimpleConvolution2d3x5Test, true, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5Uint8Nhwc, SimpleConvolution2d3x5Uint8Test, true, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5QSymm16, SimpleConvolution2d3x5QSymm16Test, true, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5QSymm16Nhwc, SimpleConvolution2d3x5QSymm16Test, true,\n                     armnn::DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(UnbiasedConvolution2d, SimpleConvolution2d3x5Test, false, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedConvolutionUint8, SimpleConvolution2d3x5Uint8Test, false, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedConvolution2dNhwc, SimpleConvolution2d3x5Test, false, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedConvolutionUint8Nhwc, SimpleConvolution2d3x5Uint8Test, false, armnn::DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution1d, Convolution1dTest, true)\nARMNN_AUTO_TEST_CASE(SimpleConvolution1dUint8, Convolution1dUint8Test, true)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3, SimpleConvolution2d3x3Test, true, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3Uint8, SimpleConvolution2d3x3Uint8Test, true, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3QSymm16, SimpleConvolution2d3x3QSymm16Test, true, armnn::DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3Nhwc, SimpleConvolution2d3x3Test, true, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3Uint8Nhwc, SimpleConvolution2d3x3Uint8Test, true, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3QSymm16Nhwc, SimpleConvolution2d3x3QSymm16Test, true,\n                     armnn::DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(UnbiasedConvolution2dSquare, SimpleConvolution2d3x3Test, false, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedConvolution2dSquareNhwc, SimpleConvolution2d3x3Test, false, armnn::DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(UnbiasedConvolution2dSquareStride2x2Nhwc,\n                     SimpleConvolution2d3x3Stride2x2Test,\n                     false,\n                     armnn::DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution2dAsymmetricPaddingLargerThanHalfKernelSize,\n                     Convolution2dAsymmetricPaddingLargerThanHalfKernelSizeTest,\n                     armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2dAsymmetricPadding, Convolution2dAsymmetricPaddingTest, armnn::DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution2dAsymmetricPaddingLargerThanHalfKernelSizeNhwc,\n                     Convolution2dAsymmetricPaddingLargerThanHalfKernelSizeTest,\n                     armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2dAsymmetricPaddingNhwc,\n                     Convolution2dAsymmetricPaddingTest,\n                     armnn::DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution2dSquareNhwc, SimpleConvolution2d3x3NhwcTest, false)\n\n// Depthwise Convolution\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d, DepthwiseConvolution2dTest, true, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dUint8, DepthwiseConvolution2dUint8Test, true, armnn::DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2d, DepthwiseConvolution2dTest, false, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dUint8,\n                     DepthwiseConvolution2dUint8Test,\n                     false,\n                     armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dQSymm16, DepthwiseConvolution2dInt16Test, true, armnn::DataLayout::NCHW)\n\n// NHWC Depthwise Convolution\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dNhwc, DepthwiseConvolution2dTest, true, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dUint8Nhwc, DepthwiseConvolution2dUint8Test, true, armnn::DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dNhwc, DepthwiseConvolution2dTest, false, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dUint8Nhwc,\n                     DepthwiseConvolution2dUint8Test,\n                     false,\n                     armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleDepthwiseConvolution2d3x3Dilation3x3Nhwc,\n                     SimpleDepthwiseConvolution2d3x3Dilation3x3NhwcTest)\n\n\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthMul1,\n                     DepthwiseConvolution2dDepthMul1Test, true, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthMul1Uint8,\n                     DepthwiseConvolution2dDepthMul1Uint8Test, true, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthMul1Int16,\n                     DepthwiseConvolution2dDepthMul1Int16Test, true, armnn::DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dDepthMul1,\n                     DepthwiseConvolution2dDepthMul1Test, false, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dDepthMul1Uint8,\n                     DepthwiseConvolution2dDepthMul1Uint8Test, false, armnn::DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthMul1Nhwc,\n                     DepthwiseConvolution2dDepthMul1Test, true, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthMul1Uint8Nhwc,\n                     DepthwiseConvolution2dDepthMul1Uint8Test, true, armnn::DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dDepthMul1Nhwc,\n                     DepthwiseConvolution2dDepthMul1Test, false, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dDepthMul1Uint8Nhwc,\n                     DepthwiseConvolution2dDepthMul1Uint8Test, false, armnn::DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dAsymmetric,\n                     DepthwiseConvolution2dAsymmetricTest, true, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dAsymmetric,\n                     DepthwiseConvolution2dAsymmetricTest, false, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dAsymmetricNhwc,\n                     DepthwiseConvolution2dAsymmetricTest, true, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dAsymmetricNhwc,\n                     DepthwiseConvolution2dAsymmetricTest, false, armnn::DataLayout::NHWC)\n\n\n// Pooling\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize2x2Stride2x2, SimpleMaxPooling2dSize2x2Stride2x2Test, false)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize2x2Stride2x2Uint8, SimpleMaxPooling2dSize2x2Stride2x2Uint8Test, false)\n\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize3x3Stride2x4, SimpleMaxPooling2dSize3x3Stride2x4Test, false)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize3x3Stride2x4Uint8, SimpleMaxPooling2dSize3x3Stride2x4Uint8Test, false)\n\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleMaxPooling2d, IgnorePaddingSimpleMaxPooling2dTest)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleMaxPooling2dUint8, IgnorePaddingSimpleMaxPooling2dUint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingMaxPooling2dSize3, IgnorePaddingMaxPooling2dSize3Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingMaxPooling2dSize3Uint8, IgnorePaddingMaxPooling2dSize3Uint8Test)\n\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2d, IgnorePaddingSimpleAveragePooling2dTest)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2dUint8, IgnorePaddingSimpleAveragePooling2dUint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2dNoPadding, IgnorePaddingSimpleAveragePooling2dNoPaddingTest)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2dNoPaddingUint8,\n    IgnorePaddingSimpleAveragePooling2dNoPaddingUint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingAveragePooling2dSize3, IgnorePaddingAveragePooling2dSize3Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingAveragePooling2dSize3Uint8, IgnorePaddingAveragePooling2dSize3Uint8Test)\n\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleL2Pooling2d, IgnorePaddingSimpleL2Pooling2dTest)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleL2Pooling2dUint8, IgnorePaddingSimpleL2Pooling2dUint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingL2Pooling2dSize3, IgnorePaddingL2Pooling2dSize3Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingL2Pooling2dSize3Uint8, IgnorePaddingL2Pooling2dSize3Uint8Test)\n\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2d, SimpleMaxPooling2dTest, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dNhwc, SimpleMaxPooling2dTest, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dUint8, SimpleMaxPooling2dUint8Test, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dUint8Nhwc, SimpleMaxPooling2dUint8Test, armnn::DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(SimpleAveragePooling2d, SimpleAveragePooling2dTest, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleAveragePooling2dNhwc, SimpleAveragePooling2dTest, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleAveragePooling2dUint8, SimpleAveragePooling2dUint8Test, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleAveragePooling2dUint8Nhwc, SimpleAveragePooling2dUint8Test, armnn::DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(IgnorePaddingAveragePooling2dSize3x2Stride2x2,\n                     IgnorePaddingAveragePooling2dSize3x2Stride2x2Test, false)\nARMNN_AUTO_TEST_CASE(IgnorePaddingAveragePooling2dSize3x2Stride2x2NoPadding,\n                     IgnorePaddingAveragePooling2dSize3x2Stride2x2Test, true)\n\nARMNN_AUTO_TEST_CASE(LargeTensorsAveragePooling2d, LargeTensorsAveragePooling2dTest)\nARMNN_AUTO_TEST_CASE(LargeTensorsAveragePooling2dUint8, LargeTensorsAveragePooling2dUint8Test)\n\nARMNN_AUTO_TEST_CASE(SimpleL2Pooling2d, SimpleL2Pooling2dTest, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleL2Pooling2dNhwc, SimpleL2Pooling2dTest, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleL2Pooling2dUint8, SimpleL2Pooling2dUint8Test, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleL2Pooling2dNhwcUint8, SimpleL2Pooling2dUint8Test, armnn::DataLayout::NHWC)\n\nARMNN_AUTO_TEST_CASE(L2Pooling2dSize7, L2Pooling2dSize7Test)\nARMNN_AUTO_TEST_CASE(L2Pooling2dSize7Uint8, L2Pooling2dSize7Uint8Test)\n\nARMNN_AUTO_TEST_CASE(AsymmNonSquarePooling2d, AsymmetricNonSquarePooling2dTest)\nARMNN_AUTO_TEST_CASE(AsymmNonSquarePooling2dUint8, AsymmetricNonSquarePooling2dUint8Test)\n\n// Linear Activation\nARMNN_AUTO_TEST_CASE(ConstantLinearActivation, ConstantLinearActivationTest)\nARMNN_AUTO_TEST_CASE(ConstantLinearActivationUint8, ConstantLinearActivationUint8Test)\nARMNN_AUTO_TEST_CASE(ConstantLinearActivationInt16, ConstantLinearActivationInt16Test)\n\n// Normalization\nARMNN_AUTO_TEST_CASE(SimpleNormalizationAcross, SimpleNormalizationAcrossTest)\nARMNN_AUTO_TEST_CASE(SimpleNormalizationWithin, SimpleNormalizationWithinTest)\nARMNN_AUTO_TEST_CASE(SimpleNormalizationAcrossNhwc, SimpleNormalizationAcrossNhwcTest)\n\n// Softmax\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxBeta1, SimpleSoftmaxTest, 1.0f)\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxBeta2, SimpleSoftmaxTest, 2.0f)\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxBeta1Uint8, SimpleSoftmaxUint8Test, 1.0f)\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxBeta2Uint8, SimpleSoftmaxUint8Test, 2.0f)\n\nARMNN_AUTO_TEST_CASE(Simple3dSoftmax, Simple3dSoftmaxTest, 1.0f)\nARMNN_AUTO_TEST_CASE(Simple3dSoftmaxUint8, Simple3dSoftmaxUint8Test, 1.0f)\n\nARMNN_AUTO_TEST_CASE(Simple4dSoftmax, Simple4dSoftmaxTest, 1.0f)\nARMNN_AUTO_TEST_CASE(Simple4dSoftmaxUint8, Simple4dSoftmaxUint8Test, 1.0f)\n\n// Sigmoid Activation\nARMNN_AUTO_TEST_CASE(SimpleSigmoid, SimpleSigmoidTest)\nARMNN_AUTO_TEST_CASE(SimpleSigmoidUint8, SimpleSigmoidUint8Test)\nARMNN_AUTO_TEST_CASE(SimpleSigmoidInt16, SimpleSigmoidInt16Test)\n\n// BoundedReLU Activation\nARMNN_AUTO_TEST_CASE(ReLu1, BoundedReLuUpperAndLowerBoundTest)\nARMNN_AUTO_TEST_CASE(ReLu6, BoundedReLuUpperBoundOnlyTest)\nARMNN_AUTO_TEST_CASE(ReLu1Uint8, BoundedReLuUint8UpperAndLowerBoundTest)\nARMNN_AUTO_TEST_CASE(ReLu6Uint8, BoundedReLuUint8UpperBoundOnlyTest)\nARMNN_AUTO_TEST_CASE(BoundedReLuInt16, BoundedReLuInt16Test)\n\n// ReLU Activation\nARMNN_AUTO_TEST_CASE(ReLuInt16, ReLuInt16Test)\n\n// SoftReLU Activation\nARMNN_AUTO_TEST_CASE(SoftReLuInt16, SoftReLuInt16Test)\n\n// LeakyReLU Activation\nARMNN_AUTO_TEST_CASE(LeakyReLuInt16, LeakyReLuInt16Test)\n\n// Abs Activation\nARMNN_AUTO_TEST_CASE(AbsInt16, AbsInt16Test)\n\n// Sqrt Activation\nARMNN_AUTO_TEST_CASE(SqrtInt16, SqrtInt16Test)\n\n// Square Activation\nARMNN_AUTO_TEST_CASE(SquareInt16, SquareInt16Test)\n\n// Tanh Activation\nARMNN_AUTO_TEST_CASE(TanhInt16, TanhInt16Test)\n\n\n// Fully Conected\nARMNN_AUTO_TEST_CASE(SimpleFullyConnected, FullyConnectedFloat32Test, false, false)\nARMNN_AUTO_TEST_CASE(FullyConnectedUint8, FullyConnectedUint8Test, false)\nARMNN_AUTO_TEST_CASE(SimpleFullyConnectedWithBias, FullyConnectedFloat32Test, true, false)\nARMNN_AUTO_TEST_CASE(FullyConnectedBiasedUint8, FullyConnectedUint8Test, true)\nARMNN_AUTO_TEST_CASE(SimpleFullyConnectedWithTranspose, FullyConnectedFloat32Test, false, true)\n\nARMNN_AUTO_TEST_CASE(FullyConnectedLarge, FullyConnectedLargeTest, false)\nARMNN_AUTO_TEST_CASE(FullyConnectedLargeTransposed, FullyConnectedLargeTest, true)\n\n// Splitter\nARMNN_AUTO_TEST_CASE(SimpleSplitter, SplitterTest)\nARMNN_AUTO_TEST_CASE(SimpleSplitterUint8, SplitterUint8Test)\n\nARMNN_AUTO_TEST_CASE(CopyViaSplitter, CopyViaSplitterTest)\nARMNN_AUTO_TEST_CASE(CopyViaSplitterUint8, CopyViaSplitterUint8Test)\n\n// Concat\nARMNN_AUTO_TEST_CASE(SimpleConcat, ConcatTest)\nARMNN_AUTO_TEST_CASE(ConcatUint8, ConcatUint8Test)\nARMNN_AUTO_TEST_CASE(ConcatUint8DifferentQParams, ConcatUint8DifferentQParamsTest)\nARMNN_AUTO_TEST_CASE(ConcatUint16, ConcatUint16Test)\n\n// Add\nARMNN_AUTO_TEST_CASE(SimpleAdd, AdditionTest)\nARMNN_AUTO_TEST_CASE(AddBroadcast1Element, AdditionBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(AddBroadcast, AdditionBroadcastTest)\n\nARMNN_AUTO_TEST_CASE(AdditionUint8, AdditionUint8Test)\nARMNN_AUTO_TEST_CASE(AddBroadcastUint8, AdditionBroadcastUint8Test)\nARMNN_AUTO_TEST_CASE(AddBroadcast1ElementUint8, AdditionBroadcast1ElementUint8Test)\n\nARMNN_AUTO_TEST_CASE(AdditionInt16, AdditionInt16Test)\nARMNN_AUTO_TEST_CASE(AddBroadcastInt16, AdditionBroadcastInt16Test)\nARMNN_AUTO_TEST_CASE(AddBroadcast1ElementInt16, AdditionBroadcast1ElementInt16Test)\n\n// Sub\nARMNN_AUTO_TEST_CASE(SimpleSub, SubtractionTest)\nARMNN_AUTO_TEST_CASE(SubBroadcast1Element, SubtractionBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(SubBroadcast, SubtractionBroadcastTest)\n\nARMNN_AUTO_TEST_CASE(SubtractionUint8, SubtractionUint8Test)\nARMNN_AUTO_TEST_CASE(SubBroadcastUint8, SubtractionBroadcastUint8Test)\nARMNN_AUTO_TEST_CASE(SubBroadcast1ElementUint8, SubtractionBroadcast1ElementUint8Test)\n\nARMNN_AUTO_TEST_CASE(SubtractionInt16, SubtractionInt16Test)\nARMNN_AUTO_TEST_CASE(SubBroadcastInt16, SubtractionBroadcastInt16Test)\nARMNN_AUTO_TEST_CASE(SubBroadcast1ElementInt16, SubtractionBroadcast1ElementInt16Test)\n\n// Div\nARMNN_AUTO_TEST_CASE(SimpleDivision, DivisionTest)\nARMNN_AUTO_TEST_CASE(DivisionByZero, DivisionByZeroTest)\nARMNN_AUTO_TEST_CASE(DivisionBroadcast1Element, DivisionBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(DivisionBroadcast1DVector, DivisionBroadcast1DVectorTest)\n// NOTE: division by zero for quantized div needs more attention\n//       see IVGCVSW-1849\nARMNN_AUTO_TEST_CASE(DivisionUint8, DivisionUint8Test)\nARMNN_AUTO_TEST_CASE(DivisionUint8Broadcast1Element, DivisionBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(DivisionUint8Broadcast1DVector, DivisionBroadcast1DVectorUint8Test)\n\nARMNN_AUTO_TEST_CASE(DivisionInt16, DivisionInt16Test)\nARMNN_AUTO_TEST_CASE(DivisionInt16Broadcast1Element, DivisionBroadcast1ElementInt16Test)\nARMNN_AUTO_TEST_CASE(DivisionInt16Broadcast1DVector, DivisionBroadcast1DVectorInt16Test)\n\n// Equal\nARMNN_AUTO_TEST_CASE(SimpleEqual, EqualSimpleTest)\nARMNN_AUTO_TEST_CASE(EqualBroadcast1Element, EqualBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(EqualBroadcast1DVector, EqualBroadcast1DVectorTest)\nARMNN_AUTO_TEST_CASE(EqualUint8, EqualUint8Test)\nARMNN_AUTO_TEST_CASE(EqualBroadcast1ElementUint8, EqualBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(EqualBroadcast1DVectorUint8, EqualBroadcast1DVectorUint8Test)\n\n// Greater\nARMNN_AUTO_TEST_CASE(SimpleGreater, GreaterSimpleTest)\nARMNN_AUTO_TEST_CASE(GreaterBroadcast1Element, GreaterBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(GreaterBroadcast1DVector, GreaterBroadcast1DVectorTest)\nARMNN_AUTO_TEST_CASE(GreaterUint8, GreaterUint8Test)\nARMNN_AUTO_TEST_CASE(GreaterBroadcast1ElementUint8, GreaterBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(GreaterBroadcast1DVectorUint8, GreaterBroadcast1DVectorUint8Test)\n\n// Max\nARMNN_AUTO_TEST_CASE(SimpleMaximum, MaximumSimpleTest)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1Element, MaximumBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1DVector, MaximumBroadcast1DVectorTest)\nARMNN_AUTO_TEST_CASE(MaximumUint8, MaximumUint8Test)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1ElementUint8, MaximumBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1DVectorUint8, MaximumBroadcast1DVectorUint8Test)\nARMNN_AUTO_TEST_CASE(MaximumInt16, MaximumInt16Test)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1ElementInt16, MaximumBroadcast1ElementInt16Test)\nARMNN_AUTO_TEST_CASE(MaximumBroadcast1DVectorInt16, MaximumBroadcast1DVectorInt16Test)\n\n// Min\nARMNN_AUTO_TEST_CASE(SimpleMinimum1, MinimumBroadcast1ElementTest1)\nARMNN_AUTO_TEST_CASE(SimpleMinimum2, MinimumBroadcast1ElementTest2)\nARMNN_AUTO_TEST_CASE(Minimum1DVectorUint8, MinimumBroadcast1DVectorUint8Test)\nARMNN_AUTO_TEST_CASE(MinimumInt16, MinimumInt16Test)\nARMNN_AUTO_TEST_CASE(MinimumBroadcast1ElementInt16, MinimumBroadcast1ElementInt16Test)\nARMNN_AUTO_TEST_CASE(MinimumBroadcast1DVectorInt16, MinimumBroadcast1DVectorInt16Test)\n\n// Mul\nARMNN_AUTO_TEST_CASE(SimpleMultiplication, MultiplicationTest)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1Element, MultiplicationBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1DVector, MultiplicationBroadcast1DVectorTest)\nARMNN_AUTO_TEST_CASE(MultiplicationUint8, MultiplicationUint8Test)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1ElementUint8, MultiplicationBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1DVectorUint8, MultiplicationBroadcast1DVectorUint8Test)\nARMNN_AUTO_TEST_CASE(MultiplicationInt16, MultiplicationInt16Test)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1ElementInt16, MultiplicationBroadcast1ElementInt16Test)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1DVectorInt16, MultiplicationBroadcast1DVectorInt16Test)\n\n// Batch Norm\nARMNN_AUTO_TEST_CASE(BatchNorm, BatchNormTest)\nARMNN_AUTO_TEST_CASE(BatchNormNhwc, BatchNormNhwcTest)\nARMNN_AUTO_TEST_CASE(BatchNormUint8, BatchNormUint8Test)\nARMNN_AUTO_TEST_CASE(BatchNormUint8Nhwc, BatchNormUint8NhwcTest)\n\n// Resize Bilinear - NCHW\nARMNN_AUTO_TEST_CASE(SimpleResizeBilinear, SimpleResizeBilinearTest, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(SimpleResizeBilinearUint8, SimpleResizeBilinearUint8Test)\nARMNN_AUTO_TEST_CASE(ResizeBilinearNop, ResizeBilinearNopTest, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearNopUint8, ResizeBilinearNopUint8Test)\nARMNN_AUTO_TEST_CASE(ResizeBilinearSqMin, ResizeBilinearSqMinTest, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearSqMinUint8, ResizeBilinearSqMinUint8Test)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMin, ResizeBilinearMinTest, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMinUint8, ResizeBilinearMinUint8Test)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMag, ResizeBilinearMagTest, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMagUint8, ResizeBilinearMagUint8Test)\n\n// Resize Bilinear - NHWC\nARMNN_AUTO_TEST_CASE(ResizeBilinearNopNhwc, ResizeBilinearNopTest, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(SimpleResizeBilinearNhwc, SimpleResizeBilinearTest, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearSqMinNhwc, ResizeBilinearSqMinTest, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMinNhwc, ResizeBilinearMinTest, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMagNhwc, ResizeBilinearMagTest, armnn::DataLayout::NHWC)\n\n// Fake Quantization\nARMNN_AUTO_TEST_CASE(FakeQuantization, FakeQuantizationTest)\n\n// L2 Normalization\nARMNN_AUTO_TEST_CASE(L2Normalization1d, L2Normalization1dTest, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(L2Normalization2d, L2Normalization2dTest, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(L2Normalization3d, L2Normalization3dTest, armnn::DataLayout::NCHW)\nARMNN_AUTO_TEST_CASE(L2Normalization4d, L2Normalization4dTest, armnn::DataLayout::NCHW)\n\nARMNN_AUTO_TEST_CASE(L2Normalization1dNhwc, L2Normalization1dTest, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(L2Normalization2dNhwc, L2Normalization2dTest, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(L2Normalization3dNhwc, L2Normalization3dTest, armnn::DataLayout::NHWC)\nARMNN_AUTO_TEST_CASE(L2Normalization4dNhwc, L2Normalization4dTest, armnn::DataLayout::NHWC)\n\n// Pad\nARMNN_AUTO_TEST_CASE(PadFloat322d, PadFloat322dTest)\nARMNN_AUTO_TEST_CASE(PadFloat323d, PadFloat323dTest)\nARMNN_AUTO_TEST_CASE(PadFloat324d, PadFloat324dTest)\n\nARMNN_AUTO_TEST_CASE(PadUint82d, PadUint82dTest)\nARMNN_AUTO_TEST_CASE(PadUint83d, PadUint83dTest)\nARMNN_AUTO_TEST_CASE(PadUint84d, PadUint84dTest)\n\n// Constant\nARMNN_AUTO_TEST_CASE(Constant, ConstantTest)\nARMNN_AUTO_TEST_CASE(ConstantUint8, ConstantUint8CustomQuantizationScaleAndOffsetTest)\nARMNN_AUTO_TEST_CASE(ConstantInt16, ConstantInt16CustomQuantizationScaleAndOffsetTest)\n\n// Concat\nARMNN_AUTO_TEST_CASE(Concatenation1d, Concatenation1dTest)\nARMNN_AUTO_TEST_CASE(Concatenation1dUint8, Concatenation1dUint8Test)\n\nARMNN_AUTO_TEST_CASE(Concatenation2dDim0, Concatenation2dDim0Test)\nARMNN_AUTO_TEST_CASE(Concatenation2dDim0Uint8, Concatenation2dDim0Uint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation2dDim1, Concatenation2dDim1Test)\nARMNN_AUTO_TEST_CASE(Concatenation2dDim1Uint8, Concatenation2dDim1Uint8Test)\n\nARMNN_AUTO_TEST_CASE(Concatenation2dDim0DiffInputDims, Concatenation2dDim0DiffInputDimsTest)\nARMNN_AUTO_TEST_CASE(Concatenation2dDim0DiffInputDimsUint8, Concatenation2dDim0DiffInputDimsUint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation2dDim1DiffInputDims, Concatenation2dDim1DiffInputDimsTest)\nARMNN_AUTO_TEST_CASE(Concatenation2dDim1DiffInputDimsUint8, Concatenation2dDim1DiffInputDimsUint8Test)\n\nARMNN_AUTO_TEST_CASE(Concatenation3dDim0, Concatenation3dDim0Test)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim0Uint8, Concatenation3dDim0Uint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim1, Concatenation3dDim1Test)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim1Uint8, Concatenation3dDim1Uint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim2, Concatenation3dDim2Test, true)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim2Uint8, Concatenation3dDim2Uint8Test, true)\n\nARMNN_AUTO_TEST_CASE(Concatenation3dDim0DiffInputDims, Concatenation3dDim0DiffInputDimsTest)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim0DiffInputDimsUint8, Concatenation3dDim0DiffInputDimsUint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim1DiffInputDims, Concatenation3dDim1DiffInputDimsTest)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim1DiffInputDimsUint8, Concatenation3dDim1DiffInputDimsUint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim2DiffInputDims, Concatenation3dDim2DiffInputDimsTest, true)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim2DiffInputDimsUint8, Concatenation3dDim2DiffInputDimsUint8Test, true)\n\nARMNN_AUTO_TEST_CASE(Concatenation4dDim0, Concatenation4dDim0Test)\nARMNN_AUTO_TEST_CASE(Concatenation4dDim1, Concatenation4dDim1Test)\nARMNN_AUTO_TEST_CASE(Concatenation4dDim2, Concatenation4dDim2Test)\nARMNN_AUTO_TEST_CASE(Concatenation4dDim3, Concatenation4dDim3Test, true)\nARMNN_AUTO_TEST_CASE(Concatenation4dDim0Uint8, Concatenation4dDim0Uint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation4dDim1Uint8, Concatenation4dDim1Uint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation4dDim2Uint8, Concatenation4dDim2Uint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation4dDim3Uint8, Concatenation4dDim3Uint8Test, true)\n\nARMNN_AUTO_TEST_CASE(Concatenation4dDiffShapeDim0, Concatenation4dDiffShapeDim0Test)\nARMNN_AUTO_TEST_CASE(Concatenation4dDiffShapeDim1, Concatenation4dDiffShapeDim1Test)\nARMNN_AUTO_TEST_CASE(Concatenation4dDiffShapeDim2, Concatenation4dDiffShapeDim2Test)\nARMNN_AUTO_TEST_CASE(Concatenation4dDiffShapeDim3, Concatenation4dDiffShapeDim3Test, true)\nARMNN_AUTO_TEST_CASE(Concatenation4dDiffShapeDim0Uint8, Concatenation4dDiffShapeDim0Uint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation4dDiffShapeDim1Uint8, Concatenation4dDiffShapeDim1Uint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation4dDiffShapeDim2Uint8, Concatenation4dDiffShapeDim2Uint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation4dDiffShapeDim3Uint8, Concatenation4dDiffShapeDim3Uint8Test, true)\n\n// Floor\nARMNN_AUTO_TEST_CASE(SimpleFloor, SimpleFloorTest)\n\n// Reshape\nARMNN_AUTO_TEST_CASE(SimpleReshapeFloat32, SimpleReshapeFloat32Test)\nARMNN_AUTO_TEST_CASE(SimpleReshapeUint8, SimpleReshapeUint8Test)\n\n// Rsqrt\nARMNN_AUTO_TEST_CASE(Rsqrt2d, Rsqrt2dTest)\nARMNN_AUTO_TEST_CASE(Rsqrt3d, Rsqrt3dTest)\nARMNN_AUTO_TEST_CASE(RsqrtZero, RsqrtZeroTest)\nARMNN_AUTO_TEST_CASE(RsqrtNegative, RsqrtNegativeTest)\n\n// Permute\nARMNN_AUTO_TEST_CASE(SimplePermuteFloat32, SimplePermuteFloat32Test)\nARMNN_AUTO_TEST_CASE(SimplePermuteUint8, SimplePermuteUint8Test)\nARMNN_AUTO_TEST_CASE(PermuteFloat32ValueSet1, PermuteFloat32ValueSet1Test)\nARMNN_AUTO_TEST_CASE(PermuteFloat32ValueSet2, PermuteFloat32ValueSet2Test)\nARMNN_AUTO_TEST_CASE(PermuteFloat32ValueSet3, PermuteFloat32ValueSet3Test)\n\n// Lstm\nARMNN_AUTO_TEST_CASE(LstmLayerFloat32WithCifgWithPeepholeNoProjection,\n                     LstmLayerFloat32WithCifgWithPeepholeNoProjectionTest)\nARMNN_AUTO_TEST_CASE(LstmLayerFloat32NoCifgNoPeepholeNoProjection,\n                     LstmLayerFloat32NoCifgNoPeepholeNoProjectionTest)\nARMNN_AUTO_TEST_CASE(LstmLayerFloat32NoCifgWithPeepholeWithProjection,\n                     LstmLayerFloat32NoCifgWithPeepholeWithProjectionTest)\n\nARMNN_AUTO_TEST_CASE(LstmLayerInt16NoCifgNoPeepholeNoProjection,\n                     LstmLayerInt16NoCifgNoPeepholeNoProjectionTest)\nARMNN_AUTO_TEST_CASE(LstmLayerInt16WithCifgWithPeepholeNoProjection,\n                     LstmLayerInt16WithCifgWithPeepholeNoProjectionTest)\nARMNN_AUTO_TEST_CASE(LstmLayerInt16NoCifgWithPeepholeWithProjection,\n                     LstmLayerInt16NoCifgWithPeepholeWithProjectionTest)\nARMNN_AUTO_TEST_CASE(LstmLayerInt16NoCifgNoPeepholeNoProjectionInt16Constant,\n                     LstmLayerInt16NoCifgNoPeepholeNoProjectionInt16ConstantTest)\n\n// Convert from Float16 to Float32\nARMNN_AUTO_TEST_CASE(SimpleConvertFp16ToFp32, SimpleConvertFp16ToFp32Test)\n// Convert from Float32 to Float16\nARMNN_AUTO_TEST_CASE(SimpleConvertFp32ToFp16, SimpleConvertFp32ToFp16Test)\n\n// Mean\nARMNN_AUTO_TEST_CASE(MeanUint8Simple, MeanUint8SimpleTest)\nARMNN_AUTO_TEST_CASE(MeanUint8SimpleAxis, MeanUint8SimpleAxisTest)\nARMNN_AUTO_TEST_CASE(MeanUint8KeepDims, MeanUint8KeepDimsTest)\nARMNN_AUTO_TEST_CASE(MeanUint8MultipleDims, MeanUint8MultipleDimsTest)\nARMNN_AUTO_TEST_CASE(MeanVtsUint8, MeanVtsUint8Test)\n\nARMNN_AUTO_TEST_CASE(MeanFloatSimple, MeanFloatSimpleTest)\nARMNN_AUTO_TEST_CASE(MeanFloatSimpleAxis, MeanFloatSimpleAxisTest)\nARMNN_AUTO_TEST_CASE(MeanFloatKeepDims, MeanFloatKeepDimsTest)\nARMNN_AUTO_TEST_CASE(MeanFloatMultipleDims, MeanFloatMultipleDimsTest)\nARMNN_AUTO_TEST_CASE(MeanVtsFloat1, MeanVtsFloat1Test)\nARMNN_AUTO_TEST_CASE(MeanVtsFloat2, MeanVtsFloat2Test)\nARMNN_AUTO_TEST_CASE(MeanVtsFloat3, MeanVtsFloat3Test)\n\nARMNN_AUTO_TEST_CASE(AdditionAfterMaxPool, AdditionAfterMaxPoolTest)\n\n// Space To Batch Nd\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdSimpleFloat32, SpaceToBatchNdSimpleFloat32Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiChannelsFloat32, SpaceToBatchNdMultiChannelsFloat32Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiBlockFloat32, SpaceToBatchNdMultiBlockFloat32Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdPaddingFloat32, SpaceToBatchNdPaddingFloat32Test)\n\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdSimpleUint8, SpaceToBatchNdSimpleUint8Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiChannelsUint8, SpaceToBatchNdMultiChannelsUint8Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiBlockUint8, SpaceToBatchNdMultiBlockUint8Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdPaddingUint8, SpaceToBatchNdPaddingUint8Test)\n\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdSimpleNHWCFloat32, SpaceToBatchNdSimpleNHWCFloat32Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiChannelsNHWCFloat32, SpaceToBatchNdMultiChannelsNHWCFloat32Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiBlockNHWCFloat32, SpaceToBatchNdMultiBlockNHWCFloat32Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdPaddingNHWCFloat32, SpaceToBatchNdPaddingNHWCFloat32Test)\n\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdSimpleNHWCUint8, SpaceToBatchNdSimpleNHWCUint8Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiChannelsNHWCUint8, SpaceToBatchNdMultiChannelsNHWCUint8Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdMultiBlockNHWCUint8, SpaceToBatchNdMultiBlockNHWCUint8Test)\nARMNN_AUTO_TEST_CASE(SpaceToBatchNdPaddingNHWCUint8, SpaceToBatchNdPaddingNHWCUint8Test)\n\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat321, BatchToSpaceNdNhwcFloat32Test1)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat322, BatchToSpaceNdNhwcFloat32Test2)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat323, BatchToSpaceNdNhwcFloat32Test3)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcFloat324, BatchToSpaceNdNhwcFloat32Test4)\n\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwFloat321, BatchToSpaceNdNchwFloat32Test1)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwFloat322, BatchToSpaceNdNchwFloat32Test2)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwFloat323, BatchToSpaceNdNchwFloat32Test3)\n\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcUint1, BatchToSpaceNdNhwcUintTest1)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcUint2, BatchToSpaceNdNhwcUintTest2)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNhwcUint3, BatchToSpaceNdNhwcUintTest3)\n\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwUint1, BatchToSpaceNdNchwUintTest1)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwUint2, BatchToSpaceNdNchwUintTest2)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwUint3, BatchToSpaceNdNchwUintTest3)\nARMNN_AUTO_TEST_CASE(BatchToSpaceNdNchwUint4, BatchToSpaceNdNchwUintTest4)\n\n// Strided Slice\nARMNN_AUTO_TEST_CASE(StridedSlice4DFloat32, StridedSlice4DFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSlice4DReverseFloat32, StridedSlice4DReverseFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceSimpleStrideFloat32, StridedSliceSimpleStrideFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceSimpleRangeMaskFloat32, StridedSliceSimpleRangeMaskFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskFloat32, StridedSliceShrinkAxisMaskFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSlice3DFloat32, StridedSlice3DFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSlice3DReverseFloat32, StridedSlice3DReverseFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSlice2DFloat32, StridedSlice2DFloat32Test)\nARMNN_AUTO_TEST_CASE(StridedSlice2DReverseFloat32, StridedSlice2DReverseFloat32Test)\n\nARMNN_AUTO_TEST_CASE(StridedSlice4DUint8, StridedSlice4DUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSlice4DReverseUint8, StridedSlice4DReverseUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceSimpleStrideUint8, StridedSliceSimpleStrideUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceSimpleRangeMaskUint8, StridedSliceSimpleRangeMaskUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSliceShrinkAxisMaskUint8, StridedSliceShrinkAxisMaskUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSlice3DUint8, StridedSlice3DUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSlice3DReverseUint8, StridedSlice3DReverseUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSlice2DUint8, StridedSlice2DUint8Test)\nARMNN_AUTO_TEST_CASE(StridedSlice2DReverseUint8, StridedSlice2DReverseUint8Test)\n\n// Debug\nARMNN_AUTO_TEST_CASE(Debug4DFloat32, Debug4DFloat32Test)\nARMNN_AUTO_TEST_CASE(Debug3DFloat32, Debug3DFloat32Test)\nARMNN_AUTO_TEST_CASE(Debug2DFloat32, Debug2DFloat32Test)\nARMNN_AUTO_TEST_CASE(Debug1DFloat32, Debug1DFloat32Test)\n\nARMNN_AUTO_TEST_CASE(Debug4DUint8, Debug4DUint8Test)\nARMNN_AUTO_TEST_CASE(Debug3DUint8, Debug3DUint8Test)\nARMNN_AUTO_TEST_CASE(Debug2DUint8, Debug2DUint8Test)\nARMNN_AUTO_TEST_CASE(Debug1DUint8, Debug1DUint8Test)\n\n// Gather\nARMNN_AUTO_TEST_CASE(Gather1DParamsFloat, Gather1DParamsFloatTest)\nARMNN_AUTO_TEST_CASE(Gather1DParamsUint8, Gather1DParamsUint8Test)\nARMNN_AUTO_TEST_CASE(GatherMultiDimParamsFloat, GatherMultiDimParamsFloatTest)\nARMNN_AUTO_TEST_CASE(GatherMultiDimParamsUint8, GatherMultiDimParamsUint8Test)\nARMNN_AUTO_TEST_CASE(GatherMultiDimParamsMultiDimIndicesFloat, GatherMultiDimParamsMultiDimIndicesFloatTest)\nARMNN_AUTO_TEST_CASE(GatherMultiDimParamsMultiDimIndicesUint8, GatherMultiDimParamsMultiDimIndicesUint8Test)\n\n// Detection PostProcess\nBOOST_AUTO_TEST_CASE(DetectionPostProcessRegularNmsFloat)\n{\n    DetectionPostProcessRegularNmsFloatTest<armnn::RefWorkloadFactory>();\n}\nBOOST_AUTO_TEST_CASE(DetectionPostProcessFastNmsFloat)\n{\n    DetectionPostProcessFastNmsFloatTest<armnn::RefWorkloadFactory>();\n}\nBOOST_AUTO_TEST_CASE(DetectionPostProcessRegularNmsUint8)\n{\n    DetectionPostProcessRegularNmsUint8Test<armnn::RefWorkloadFactory>();\n}\nBOOST_AUTO_TEST_CASE(DetectionPostProcessFastNmsUint8)\n{\n    DetectionPostProcessFastNmsUint8Test<armnn::RefWorkloadFactory>();\n}\n\n// Dequantize\nARMNN_AUTO_TEST_CASE(DequantizeSimpleUint8, DequantizeSimpleUint8Test)\nARMNN_AUTO_TEST_CASE(DequantizeOffsetUint8, DequantizeOffsetUint8Test)\nARMNN_AUTO_TEST_CASE(DequantizeSimpleInt16, DequantizeSimpleInt16Test)\n\n// Quantize\nARMNN_AUTO_TEST_CASE(QuantizeSimpleUint8, QuantizeSimpleUint8Test)\nARMNN_AUTO_TEST_CASE(QuantizeClampUint8, QuantizeClampUint8Test)\nARMNN_AUTO_TEST_CASE(QuantizeClampInt16, QuantizeClampInt16Test)\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ed8f02f46d556e52ac68cc98c612ecba9ee1aaf9", "size": 34192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backends/reference/test/RefLayerTests.cpp", "max_stars_repo_name": "sunshinemyson/armnn", "max_stars_repo_head_hexsha": "a723ec5d2ac35948efb5dfd0c121a1a89cb977b7", "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/test/RefLayerTests.cpp", "max_issues_repo_name": "hessed99/armnn", "max_issues_repo_head_hexsha": "a723ec5d2ac35948efb5dfd0c121a1a89cb977b7", "max_issues_repo_licenses": ["MIT"], "max_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/test/RefLayerTests.cpp", "max_forks_repo_name": "hessed99/armnn", "max_forks_repo_head_hexsha": "a723ec5d2ac35948efb5dfd0c121a1a89cb977b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.7781402936, "max_line_length": 119, "alphanum_fraction": 0.884534394, "num_tokens": 9915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5026716130395125}}
{"text": "#include <boost/math/special_functions/ellint_rc.hpp>\n", "meta": {"hexsha": "93051b178522cfa282f6062c4c1e1061a8b0993b", "size": 54, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_ellint_rc.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_ellint_rc.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_ellint_rc.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.0, "max_line_length": 53, "alphanum_fraction": 0.8333333333, "num_tokens": 13, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5026716130395124}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, 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#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_AREA_SURVEYOR_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_AREA_SURVEYOR_HPP\n\n\n#include <boost/mpl/if.hpp>\n\n#include <boost/geometry/arithmetic/determinant.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\nnamespace strategy { namespace area\n{\n\n/*!\n\\brief Area calculation for cartesian points\n\\ingroup strategies\n\\details Calculates area using the Surveyor's formula, a well-known\n    triangulation algorithm\n\\tparam PointOfSegment \\tparam_segment_point\n\\tparam CalculationType \\tparam_calculation\n\n\\qbk{\n[heading See also]\n[link geometry.reference.algorithms.area.area_2_with_strategy area (with strategy)]\n}\n\n*/\ntemplate\n<\n    typename PointOfSegment,\n    typename CalculationType = void\n>\nclass surveyor\n{\npublic :\n    // If user specified a calculation type, use that type,\n    //   whatever it is and whatever the point-type is.\n    // Else, use the pointtype, but at least double\n    typedef typename\n        geofeatures_boost::mpl::if_c\n        <\n            geofeatures_boost::is_void<CalculationType>::type::value,\n            typename select_most_precise\n            <\n                typename coordinate_type<PointOfSegment>::type,\n                double\n            >::type,\n            CalculationType\n        >::type return_type;\n\n\nprivate :\n\n    class summation\n    {\n        friend class surveyor;\n\n        return_type sum;\n    public :\n\n        inline summation() : sum(return_type())\n        {\n            // Strategy supports only 2D areas\n            assert_dimension<PointOfSegment, 2>();\n        }\n        inline return_type area() const\n        {\n            return_type result = sum;\n            return_type const two = 2;\n            result /= two;\n            return result;\n        }\n    };\n\npublic :\n    typedef summation state_type;\n    typedef PointOfSegment segment_point_type;\n\n    static inline void apply(PointOfSegment const& p1,\n                PointOfSegment const& p2,\n                summation& state)\n    {\n        // SUM += x2 * y1 - x1 * y2;\n        state.sum += detail::determinant<return_type>(p2, p1);\n    }\n\n    static inline return_type result(summation const& state)\n    {\n        return state.area();\n    }\n\n};\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\nnamespace services\n{\n    template <typename Point>\n    struct default_strategy<cartesian_tag, Point>\n    {\n        typedef strategy::area::surveyor<Point> type;\n    };\n\n} // namespace services\n\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::area\n\n\n\n}} // namespace geofeatures_boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_AREA_SURVEYOR_HPP\n", "meta": {"hexsha": "7deade88dcc6bbcc6779d3112de07ae7bad97ca8", "size": 3459, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/Headers/Private/GeoFeatures/boost/geometry/strategies/cartesian/area_surveyor.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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": "Pods/Headers/Private/GeoFeatures/boost/geometry/strategies/cartesian/area_surveyor.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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": "Pods/Headers/Private/GeoFeatures/boost/geometry/strategies/cartesian/area_surveyor.hpp", "max_forks_repo_name": "xarvey/Yuuuuuge", "max_forks_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "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.6222222222, "max_line_length": 116, "alphanum_fraction": 0.6900838393, "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5026716023845289}}
{"text": "#ifndef SIMCLASS_H\n#define SIMCLASS_H\n\n#include <stdexcept>\n#include <opencv2/core/core.hpp>\n#include <Eigen/Dense>\n#include <eigen3/Eigen/src/Core/Matrix.h>\n#include <opencv2/opencv.hpp>\n#include <opencv/cxeigen.hpp>\n#include <chrono>\n#include <spline_class.hpp>\n#include <math.h>\n\ntypedef Eigen::Vector2f Point2D;\ntypedef cv::Vec4f PointXYZI;\ntypedef Eigen::Hyperplane<float,2> Line;\ntypedef Eigen::ParametrizedLine<float,2> Ray;\n\nclass Laser{\npublic:\n    Eigen::MatrixXf cam_to_laser, laser_to_cam;\n    Eigen::Vector2f laser_origin, p_left_laser, p_right_laser;\n\n    // // Hardcode laser params for now\n    // float galvo_m = -2.2450289e+01;\n    // float galvo_b = -6.8641598e-01;\n    // int16_t maxADC = 15000;\n    // float thickness = 0.00055;\n    // float divergence = 0.11/2.;\n    // float laser_limit = 14000;\n    // float laser_timestep = 1.5e-5;\n\n    // Previously hardcoded laser params by Raaj,\n    // now exposed to Python API by Sid.\n    float galvo_m;\n    float galvo_b;\n    int16_t maxADC;\n    float thickness;\n    float divergence;\n    float laser_limit;\n    float laser_timestep;\n\n    float getPositionFromAngle(float proj_angle_) const\n    {\n        float galvo_pos = (proj_angle_ - galvo_b)/galvo_m;\n        return galvo_pos;\n    }\n\n    float getAngleFromPosition(float pos_) const\n    {\n        float ang = pos_*galvo_m + galvo_b;\n        return ang;\n    }\n};\n\nclass Input{\npublic:\n    std::string camera_name;\n    cv::Mat rgb_image;\n    cv::Mat depth_image;\n    Eigen::MatrixXf design_pts;\n    std::vector<Eigen::MatrixXf> design_pts_multi;\n    Eigen::MatrixXf design_pts_conv;\n    Eigen::MatrixXf surface_pts;\n};\n\nclass Output{\npublic:\n    std::vector<Eigen::Matrix<float, Eigen::Dynamic, 4>> clouds;\n    std::vector<std::vector<cv::Mat>> images_multi;\n\n    Eigen::MatrixXf output_pts, laser_rays, spline;\n    std::vector<float> angles;\n    std::vector<float> velocities;\n    std::vector<float> accels;\n    std::vector<Eigen::MatrixXf> output_pts_set;\n    std::vector<Eigen::MatrixXf> spline_set;\n};\n\nclass Datum{\npublic:\n    std::string type;\n    std::string camera_name;\n    std::string laser_name;\n    //cv::Mat rgb_image;\n    Eigen::MatrixXf rgb_matrix;\n    //cv::Mat depth_image;\n    Eigen::MatrixXf depth_matrix;\n    Eigen::MatrixXf world_to_rgb;\n    Eigen::MatrixXf world_to_depth;\n    std::map<std::string, Eigen::MatrixXf> cam_to_laser;\n    Eigen::MatrixXf cam_to_world;\n    float fov;\n    cv::Mat distortion;\n    int imgh, imgw;\n    float limit;\n    //Eigen::MatrixXf design_pts;\n\n    float t_max;\n    cv::Mat nmap, nmap_nn, nmap_nn_xoffset, ztoramap;\n    Eigen::MatrixX3f nmap_matrix;\n    cv::Mat midrays[3];\n    Eigen::Vector2f cam_origin;\n    Eigen::Vector2f p_left_cam, p_right_cam;\n    std::map<std::string, Laser> laser_data;\n    std::vector<float> valid_angles;\n    //Eigen::MatrixXf design_pts_conv;\n\n    // Initially hardcoded laser parameters.\n    float galvo_m;\n    float galvo_b;\n    int16_t maxADC;\n    float thickness;\n    float divergence;\n    float laser_limit;\n    float laser_timestep;\n};\n\ntypedef std::vector<std::shared_ptr<Datum>> DatumVector;\n\nclass DatumProcessor{\nprivate:\n    bool set = false;\n    DatumVector c_datums_, l_datums_;\n    std::map<std::string, int> cam_mapping_;\n\n\npublic:\n\n    DatumProcessor(){\n\n    }\n\n    std::vector<cv::Point2f> getImageCoordinates(int imgh, int imgw) {\n        std::vector<cv::Point2f> img_coords;\n        for (int i = 0; i < imgw; i++)\n        {\n            for (int j = 0; j < imgh; j++) {\n                cv::Point2f pt_tmp(i+1,j+1);\n                img_coords.push_back(pt_tmp);\n            }\n        }\n        return img_coords;\n    }\n\n    std::vector<cv::Point2f> getImageCoordinatesXOffset(int imgh, int imgw) {\n        std::vector<cv::Point2f> img_coords;\n        for (int i = 0; i <= imgw; i++)\n        {\n            for (int j = 0; j < imgh; j++) {\n                cv::Point2f pt_tmp(i+1.-0.5,j+1);\n                img_coords.push_back(pt_tmp);\n            }\n        }\n        return img_coords;\n    }\n\n    void createNormalMap(std::shared_ptr<Datum>& datum){\n        datum->nmap_matrix = Eigen::MatrixX3f(datum->imgh*datum->imgw,3);\n        datum->nmap = cv::Mat(datum->imgh, datum->imgw, CV_32FC3); //create 3 channel matrix to store rays for each pixel (x, y, z)\n        datum->nmap_nn = cv::Mat(datum->imgh, datum->imgw, CV_32FC3); //create 3 channel matrix to store rays for each pixel (x, y, z)\n        datum->nmap_nn_xoffset = cv::Mat(datum->imgh, datum->imgw+1, CV_32FC3); //create 3 channel matrix to store rays for each pixel (x, y, z)\n        datum->ztoramap = cv::Mat(datum->imgh, datum->imgw, CV_32FC1);\n\n        std::vector<cv::Point2f> img_coords;\n        std::vector<cv::Point2f> norm_coords(datum->imgh * datum->imgw);\n        img_coords = getImageCoordinates(datum->imgh, datum->imgw);\n\n        cv::Mat KK_;//(KK().rows(), KK().cols(), CV_32FC1, KK().data());\n        cv::Mat Kd_;//(Kd().rows(), Kd().cols(), CV_32FC1, Kd().data());\n        cv::eigen2cv(datum->depth_matrix, KK_);\n        Kd_ = datum->distortion;\n\n        cv::undistortPoints(img_coords, norm_coords, KK_, Kd_);\n\n        for (int i = 0; i < datum->imgw; i++)\n        {\n            for (int j = 0; j < datum->imgh; j++)\n            {\n                int pix_num = i*datum->imgh+j;\n                float x_dir = norm_coords[pix_num].x;\n                float y_dir = norm_coords[pix_num].y;\n                float z_dir = 1.0f;\n                float mag = sqrt(x_dir*x_dir + y_dir*y_dir + z_dir*z_dir);\n                cv::Vec3f pix_ray = cv::Vec3f(x_dir/mag,y_dir/mag,z_dir/mag);\n                cv::Vec3f pix_ray_nn = cv::Vec3f(x_dir,y_dir,z_dir);\n                datum->nmap.at<cv::Vec3f>(j,i) = pix_ray;\n                datum->nmap_nn.at<cv::Vec3f>(j,i) = pix_ray_nn;\n                Eigen::Vector3f vector = Eigen::Vector3f(x_dir/mag,y_dir/mag,z_dir/mag);\n                datum->nmap_matrix.row(j+datum->imgh*i) = vector.transpose();\n                // 3d pt\n                float theta = atan2(vector(0), vector(2));\n                float phi = asin(vector(1)/1);\n                datum->ztoramap.at<float>(j,i) = cos(theta)*cos(phi);\n            }\n        }\n\n        // Split midrays into 3 channels, x(0), y(1), z(2)\n        split(datum->nmap.row(datum->imgh/2-1).clone(),datum->midrays);\n\n        // Compute Valid Angles (If we compute design points with these theta, they are guaranteed to lie on ray)\n        for(int i=0; i<datum->midrays[0].size().width; i++){\n            float x = datum->midrays[0].at<float>(0,i);\n            float y = datum->midrays[1].at<float>(0,i);\n            float z = datum->midrays[2].at<float>(0,i);\n            float theta = -((atan2f(z, x) * 180 / M_PI) - 90);\n            datum->valid_angles.emplace_back(theta);\n        }\n\n        // Set origin point for cx,cy as 0,0\n        Eigen::Vector2f o_pt(0,0);\n        datum->cam_origin = o_pt;\n\n        // Compute the leftmost and rightmost ray that sits on xz plane (Why store at Vector2f)\n        Eigen::Vector3f cam_axis(0,1,0);\n        Eigen::Vector2f left_cam_ray(datum->midrays[0].at<float>(0,0),datum->midrays[2].at<float>(0,0));\n        Eigen::Vector2f right_cam_ray(datum->midrays[0].at<float>(0,datum->imgw-1),datum->midrays[2].at<float>(0,datum->imgw-1));\n\n        // Compute leftmost and rightmost point\n        float z_max = 1;\n        float t = 1.25*z_max/left_cam_ray(1);\n        datum->p_left_cam = datum->cam_origin + t*left_cam_ray;\n        datum->p_right_cam = datum->cam_origin + t*right_cam_ray;\n        datum->t_max = t;\n\n        // Offset Coords\n        std::vector<cv::Point2f> img_coords_xoffset;\n        std::vector<cv::Point2f> norm_coords_xoffset(datum->imgh * (datum->imgw+1));\n        img_coords_xoffset = getImageCoordinatesXOffset(datum->imgh, datum->imgw);\n        cv::undistortPoints(img_coords_xoffset, norm_coords_xoffset, KK_, Kd_);\n\n        // Offset Coords rays\n        for (int i = 0; i <= datum->imgw; i++)\n        {\n            for (int j = 0; j < datum->imgh; j++)\n            {\n                int pix_num = i*datum->imgh+j;\n                float x_dir = norm_coords_xoffset[pix_num].x;\n                float y_dir = norm_coords_xoffset[pix_num].y;\n                float z_dir = 1.0f;\n                cv::Vec3f pix_ray_nn_xoffset = cv::Vec3f(x_dir,y_dir,z_dir);\n                datum->nmap_nn_xoffset.at<cv::Vec3f>(j,i) = pix_ray_nn_xoffset;\n            }\n        }\n\n        // K'p to compute camera ray - https://nghiaho.com/?page_id=363\n        // But what about the distortion param\n    }\n\n    static Eigen::Vector4f createPlaneFromPoints(const Eigen::Matrix3f& _pts)\n    {\n        Eigen::Vector3f P0 = _pts.row(0);\n        Eigen::Vector3f P1 = _pts.row(1);\n        Eigen::Vector3f P2 = _pts.row(2);\n\n        Eigen::Vector3f P0P1 = P1-P0;\n        Eigen::Vector3f P0P2 = P2-P0;\n\n        Eigen::Vector3f n = P0P1.cross(P0P2);\n        float d = P0.dot(n);\n\n        Eigen::Vector4f plane(n(0),n(1),n(2),d);\n\n        return plane;\n    }\n\n    static Laser computeLaserParams(float t_max, Eigen::MatrixXf cam_to_laser, const Datum* l_datum){\n        Laser laser;\n\n        // Laser parameters that were initially hardcoded by Raaj.\n        // Sid has exposed them so that they are set in the Python API.\n        // Hardcode laser params for now\n        laser.galvo_m = l_datum->galvo_m;\n        laser.galvo_b = l_datum->galvo_b;\n        laser.maxADC = l_datum->maxADC;\n        laser.thickness = l_datum->thickness;\n        laser.divergence = l_datum->divergence;\n        laser.laser_limit = l_datum->laser_limit;\n        laser.laser_timestep = l_datum->laser_timestep;\n\n        // Transforms and origin\n        laser.cam_to_laser = cam_to_laser;\n        laser.laser_to_cam = cam_to_laser.inverse();\n        Eigen::Vector2f tmp_laser_origin(laser.laser_to_cam(0,3),laser.laser_to_cam(2,3));\n        laser.laser_origin = tmp_laser_origin;\n\n        // Hardcode laser fov angle limit\n        float thetad_left = laser.getAngleFromPosition(1);\n        float thetad_right = laser.getAngleFromPosition(-1);\n        if(l_datum->fov > 0){\n            thetad_left = -l_datum->fov/2.;\n            thetad_right = l_datum->fov/2.;\n        }\n        // else{\n        //     ROS_WARN(\"Using Default Laser Params\");\n        // }\n\n        // Left points\n        Eigen::Matrix3f laser_pts_left;\n        laser_pts_left <<   0, 0, 0,\n                0, 1, 0,\n                sin(M_PI/180*thetad_left), 0, cos(M_PI/180*thetad_left);\n        Eigen::Vector4f laser_plane_left_lframe = createPlaneFromPoints(laser_pts_left);\n        Eigen::Vector4f laser_plane_left_cframe = laser_plane_left_lframe.transpose()*(laser.laser_to_cam.inverse());\n        Eigen::Vector3f dir_tmp_l(0,-1,0);\n        Eigen::Vector3f las_tmp_l = laser_plane_left_cframe.topLeftCorner(3,1);//drop the distance element from the bottom\n        Eigen::Vector3f l_vec_cframe_left = dir_tmp_l.cross(las_tmp_l);\n        Eigen::Vector2f lvec_tmp_l(l_vec_cframe_left(0),l_vec_cframe_left(2));\n        laser.p_left_laser = laser.laser_origin + t_max*lvec_tmp_l;\n\n        // Right points\n        Eigen::Matrix3f laser_pts_right;\n        laser_pts_right <<  0, 0, 0,\n                0, 1, 0,\n                sin(M_PI/180*thetad_right), 0, cos(M_PI/180*thetad_right);\n        Eigen::Vector4f laser_plane_right_lframe = createPlaneFromPoints(laser_pts_right);\n        Eigen::Vector4f laser_plane_right_cframe = laser_plane_right_lframe.transpose()*(laser.laser_to_cam.inverse());\n        Eigen::Vector3f dir_tmp_r(0,-1,0);\n        Eigen::Vector3f las_tmp_r = laser_plane_right_cframe.topLeftCorner(3,1); //drop the distance element from the bottom\n        Eigen::Vector3f l_vec_cframe_right = dir_tmp_r.cross(las_tmp_r);\n        Eigen::Vector2f lvec_tmp_r(l_vec_cframe_right(0),l_vec_cframe_right(2));\n        laser.p_right_laser = laser.laser_origin + t_max*lvec_tmp_r;\n\n        return laser;\n    }\n\n    void setSensors(DatumVector& c_datums,  DatumVector& l_datums){\n        c_datums_ = c_datums;\n        l_datums_ = l_datums;\n        set = true;\n\n        // Iterate each camera\n        int i=0;\n        for(auto& c_datum : c_datums_){\n\n            // Mapping\n            cam_mapping_[c_datum->camera_name] = i;\n            i++;\n\n            // Create normal map and store various rays and angles\n            createNormalMap(c_datum);\n\n            // For each laser we compute some additional params\n            for(auto& l_datum : l_datums){\n                c_datum->laser_data[l_datum->laser_name] = computeLaserParams(c_datum->t_max, c_datum->cam_to_laser[l_datum->laser_name], l_datum.get());\n            }\n\n        }\n    }\n\n    // Check if the points in cam frame lie within the two modalities\n    static std::vector<int> checkPoints(const std::vector<Point2D>& pts_, const Datum& cam_data, const Laser& laser_data, bool good=true){\n        std::vector<int> good_inds;\n        std::vector<int> bad_inds;\n\n        float x, z;\n        float x1, z1, x2, z2;\n        float d_cam_left, d_cam_right, d_laser_left, d_laser_right;\n\n        int i = 0;\n        for (auto &pt: pts_) {\n            x = pt(0); z = pt(1);\n\n            //check if point is inside left camera bound\n            x1 = cam_data.cam_origin(0); z1 = cam_data.cam_origin(1);\n            x2 = cam_data.p_left_cam(0); z2 = cam_data.p_left_cam(1);\n            d_cam_left = (x - x1) * (z2 - z1) - (z - z1) * (x2 - x1); //d>0 if inside bound\n\n            //check if point is inside right camera bound\n            x2 = cam_data.p_right_cam(0); z2 = cam_data.p_right_cam(1);\n            d_cam_right = (x - x1) * (z2 - z1) - (z - z1) * (x2 - x1); //d<0 if inside bound\n\n            //check if point is inside left projector bound\n            x1 = laser_data.laser_origin(0); z1 = laser_data.laser_origin(1);\n            x2 = laser_data.p_left_laser(0); z2 = laser_data.p_left_laser(1);\n            d_laser_left = (x - x1) * (z2 - z1) - (z - z1) * (x2 - x1); //d>0 if inside bound\n\n            //check if point is inside right projector bound\n            x2 = laser_data.p_right_laser(0); z2 = laser_data.p_right_laser(1);\n            d_laser_right = (x - x1) * (z2 - z1) - (z - z1) * (x2 - x1); //d<0 if inside bound\n\n            if (d_cam_left > 0 && d_laser_left > 0 && d_cam_right < 0 && d_laser_right < 0) {\n                good_inds.push_back(i);\n            }else{\n                bad_inds.push_back(i);\n            }\n            i++;\n        }\n\n        if(good)\n            return good_inds;\n        else\n            return bad_inds;\n    }\n\n    static Eigen::Matrix4Xf findCameraIntersections(const Datum& cam_data, const std::vector<int>& good_inds, const std::vector<Point2D>& pts)\n    {\n        // ASK Question\n        // What does imgh actually refer to. Since we know the camera is rotated. Should I be using imgw\n        // I have changed it to imgw\n\n        // Empty Matrix - Number of points of size rows\n        Eigen::Matrix4Xf design_pts(4, cam_data.imgw);\n        int valid_points = 0;\n\n        // Calculate camera ray intersections for design points\n        Eigen::Vector2f p0(0, 0);\n\n        // Iterate each column/ray of the camera\n        //#pragma omp parallel for shared(cam_data, design_pts)\n        for (int i = 0; i < cam_data.imgw; i++) {\n\n            // Get Ray along mid\n            Eigen::Vector2f dir(cam_data.midrays[0].at<float>(0, i), cam_data.midrays[2].at<float>(0, i));\n            dir.normalize();\n            Ray cam_ray = Ray(p0, dir);\n\n            // Iterate the valid set of points (Need to ensure the points are continuous)\n            bool found_intersection;\n            Eigen::Vector2f intersection_pt;\n            for (int j = 0; j < (good_inds.size() - 1); j++)\n            {\n                Eigen::Vector2f p1(pts[good_inds[j]](0), pts[good_inds[j]](1));\n                Eigen::Vector2f p2(pts[good_inds[j + 1]](0), pts[good_inds[j + 1]](1));\n\n                // Create the intersection point for camera\n                Line p1p2 = Line::Through(p1, p2);\n                Eigen::Vector2f pt = cam_ray.intersectionPoint(p1p2); //guaranteed to be on line from p1 to p2\n\n                // Check if pt is between the two design points\n                // from: https://www.lucidar.me/en/mathematics/check-if-a-point-belongs-on-a-line-segment/\n                Eigen::Vector2f p1p2_vec = p2 - p1;\n                Eigen::Vector2f p1pt_vec = pt - p1;\n\n                float k_p1p2 = p1p2_vec.dot(p1p2_vec); //max distance if point is between p1 and p2;\n                float k_p1pt = p1p2_vec.dot(p1pt_vec);\n\n                if (k_p1pt < 0)\n                    found_intersection = false;\n                else if (k_p1pt > k_p1p2)\n                    found_intersection = false;\n                else if (abs(k_p1pt) < FLT_EPSILON) {\n                    found_intersection = true;\n                    intersection_pt = pt;\n                    break;\n                } else if (abs(k_p1pt - k_p1p2) < FLT_EPSILON) {\n                    found_intersection = true;\n                    intersection_pt = pt;\n                    break;\n                } else if (k_p1pt > 0 && k_p1pt < k_p1p2) {\n                    found_intersection = true;\n                    intersection_pt = pt;\n                    break;\n                }\n                else\n                    found_intersection = false;\n            }\n\n            float cp = (float)i/float(cam_data.imgw);\n            if(cam_data.limit > 0) if(cp > cam_data.limit) found_intersection = false;\n            if(cam_data.limit < 0) if(cp < fabs(cam_data.limit)) found_intersection = false;\n\n            if (found_intersection) {\n                design_pts(0, i) = intersection_pt(0); //x-value of pt\n                design_pts(1, i) = 0; //y-value of pt (zero since in xz plane)\n                design_pts(2, i) = intersection_pt(1); //z-value of pt\n                design_pts(3, i) = 1; // 1 to make pt homogenous\n                valid_points+=1;\n            } else {\n                design_pts(0, i) = 0; //x-value of pt\n                design_pts(1, i) = 0; //y-value of pt (zero since in xz plane)\n                design_pts(2, i) = 0; //z-value of pt\n                design_pts(3, i) = -1; // -1 indicates bad point\n            }\n\n        }\n\n        return design_pts;\n    }\n\n    static Eigen::Matrix4Xf findCameraIntersectionsOpt2(const Datum& cam_data, const std::vector<int>& good_inds, const std::vector<Point2D>& pts)\n    {\n        // Empty Matrix - Number of points of size rows\n        Eigen::Matrix4Xf design_pts(4, cam_data.imgw);\n        int valid_points = 0;\n\n        // Calculate camera ray intersections for design points\n        Eigen::Vector2f p0(0, 0);\n\n        // Store angles\n        float nanVal = std::numeric_limits<float>::quiet_NaN();\n        std::vector<float> angles;\n        angles.resize(pts.size());\n        for(int i=0; i<angles.size(); i++){\n            angles[i] = -((atan2f(pts[i](1), pts[i](0)) * 180 / M_PI) - 90) + 0 + 0;\n        }\n\n        // Bins\n        std::vector<int> bins;\n        bins.resize(cam_data.imgw+1, -1);\n\n        for(int i=0; i<bins.size(); i++){\n            const float& cam_angle = cam_data.valid_angles[i];\n            float left_angle;\n            float right_angle;\n            if(i == 0){\n                left_angle = -100;\n                right_angle = cam_data.valid_angles[i];\n            }else if(i == bins.size()-1){\n                left_angle = cam_data.valid_angles[i-1];\n                right_angle = 100;\n            }else{\n                left_angle = cam_data.valid_angles[i-1];\n                right_angle = cam_data.valid_angles[i];\n            }\n            for (int j = 0; j < (good_inds.size()); j++)\n            {\n                const float& pt_angle = angles[good_inds[j]];\n                if (pt_angle >= left_angle && pt_angle <= right_angle)  {\n                    bins[i] = good_inds[j];\n                    break;\n                }\n            }\n        }\n\n        // Iterate each column/ray of the camera\n        //#pragma omp parallel for shared(cam_data, design_pts)\n        for (int i = 0; i < cam_data.imgw; i++) {\n\n            // Get Ray along mid\n            Eigen::Vector2f dir(cam_data.midrays[0].at<float>(0, i), cam_data.midrays[2].at<float>(0, i));\n            dir.normalize();\n            Ray cam_ray = Ray(p0, dir);\n            float cam_angle = cam_data.valid_angles[i];\n\n            // Iterate the valid set of points (Need to ensure the points are continuous)\n            bool found_intersection = false;\n            Eigen::Vector2f intersection_pt(0.,0.);\n\n            // Start at right bin and search for points\n            int g1 = -1;\n            int g2 = -1;\n            for(int j=i; j>=0; j--){\n                if(bins[j] == -1) continue;\n                g1 = bins[j];\n                break;\n            }\n            for(int j=i+1; j<bins.size(); j++){\n                if(bins[j] == -1) continue;\n                g2 = bins[j];\n                break;\n            }\n\n            if(g1 != -1 && g2 != -1){\n                Eigen::Vector2f p1(pts[g1](0), pts[g1](1));\n                Eigen::Vector2f p2(pts[g2](0), pts[g2](1));\n\n                // Create the intersection point for camera\n                Line p1p2 = Line::Through(p1, p2);\n                Eigen::Vector2f pt = cam_ray.intersectionPoint(p1p2); //guaranteed to be on line from p1 to p2\n\n                // Check if pt is between the two design points\n                // from: https://www.lucidar.me/en/mathematics/check-if-a-point-belongs-on-a-line-segment/\n                Eigen::Vector2f p1p2_vec = p2 - p1;\n                Eigen::Vector2f p1pt_vec = pt - p1;\n\n                float k_p1p2 = p1p2_vec.dot(p1p2_vec); //max distance if point is between p1 and p2;\n                float k_p1pt = p1p2_vec.dot(p1pt_vec);\n\n                if (k_p1pt < 0)\n                    found_intersection = false;\n                else if (k_p1pt > k_p1p2)\n                    found_intersection = false;\n                else if (abs(k_p1pt) < FLT_EPSILON) {\n                    found_intersection = true;\n                    intersection_pt = pt;\n                } else if (abs(k_p1pt - k_p1p2) < FLT_EPSILON) {\n                    found_intersection = true;\n                    intersection_pt = pt;\n                } else if (k_p1pt > 0 && k_p1pt < k_p1p2) {\n                    found_intersection = true;\n                    intersection_pt = pt;\n                }\n                else\n                    found_intersection = false;\n            }\n\n            float cp = (float)i/float(cam_data.imgw);\n            if(cam_data.limit > 0) if(cp > cam_data.limit) found_intersection = false;\n            if(cam_data.limit < 0) if(cp < fabs(cam_data.limit)) found_intersection = false;\n\n            if (found_intersection) {\n                design_pts(0, i) = intersection_pt(0); //x-value of pt\n                design_pts(1, i) = 0; //y-value of pt (zero since in xz plane)\n                design_pts(2, i) = intersection_pt(1); //z-value of pt\n                design_pts(3, i) = 1; // 1 to make pt homogenous\n                valid_points+=1;\n            } else {\n                design_pts(0, i) = 0; //x-value of pt\n                design_pts(1, i) = 0; //y-value of pt (zero since in xz plane)\n                design_pts(2, i) = 0; //z-value of pt\n                design_pts(3, i) = -1; // -1 indicates bad point\n            }\n\n        }\n\n        return design_pts;\n    }\n\n    static Eigen::Matrix4Xf findCameraIntersectionsOpt(const Datum& cam_data, const std::vector<int>& good_inds, const std::vector<Point2D>& pts)\n    {\n        // ASK Question\n        // What does imgh actually refer to. Since we know the camera is rotated. Should I be using imgw\n        // I have changed it to imgw\n\n        // Empty Matrix - Number of points of size rows\n        Eigen::Matrix4Xf design_pts(4, cam_data.imgw);\n        int valid_points = 0;\n\n        // Calculate camera ray intersections for design points\n        Eigen::Vector2f p0(0, 0);\n\n        // Store angles\n        float nanVal = std::numeric_limits<float>::quiet_NaN();\n        std::vector<float> angles;\n        angles.resize(pts.size());\n        for(int i=0; i<angles.size(); i++){\n            angles[i] = -((atan2f(pts[i](1), pts[i](0)) * 180 / M_PI) - 90) + 0 + 0;\n        }\n\n        // Iterate each column/ray of the camera\n        //#pragma omp parallel for shared(cam_data, design_pts)\n        for (int i = 0; i < cam_data.imgw; i++) {\n\n            // Get Ray along mid\n            Eigen::Vector2f dir(cam_data.midrays[0].at<float>(0, i), cam_data.midrays[2].at<float>(0, i));\n            dir.normalize();\n            Ray cam_ray = Ray(p0, dir);\n            float cam_angle = cam_data.valid_angles[i];\n\n            // Iterate the valid set of points (Need to ensure the points are continuous)\n            bool found_intersection;\n            Eigen::Vector2f intersection_pt;\n            for (int j = 0; j < (good_inds.size() - 1); j++)\n            {\n                int p1index = good_inds[j];\n                int p2index = good_inds[j+1];\n\n                float p1angle = angles[p1index];\n                float p2angle = angles[p2index];\n\n                if(p1angle != p2angle)\n                {\n                    float limit = 5;\n                    if(fabs(p1angle - cam_angle) > limit && fabs(p2angle - cam_angle) > limit) continue;\n                    found_intersection= false;\n                }\n\n                Eigen::Vector2f p1(pts[p1index](0), pts[p1index](1));\n                Eigen::Vector2f p2(pts[p2index](0), pts[p2index](1));\n\n                // Create the intersection point for camera\n                Line p1p2 = Line::Through(p1, p2);\n                Eigen::Vector2f pt = cam_ray.intersectionPoint(p1p2); //guaranteed to be on line from p1 to p2\n\n                // Check if pt is between the two design points\n                // from: https://www.lucidar.me/en/mathematics/check-if-a-point-belongs-on-a-line-segment/\n                Eigen::Vector2f p1p2_vec = p2 - p1;\n                Eigen::Vector2f p1pt_vec = pt - p1;\n\n                float k_p1p2 = p1p2_vec.dot(p1p2_vec); //max distance if point is between p1 and p2;\n                float k_p1pt = p1p2_vec.dot(p1pt_vec);\n\n                if (k_p1pt < 0)\n                    found_intersection = false;\n                else if (k_p1pt > k_p1p2)\n                    found_intersection = false;\n                else if (abs(k_p1pt) < FLT_EPSILON) {\n                    found_intersection = true;\n                    intersection_pt = pt;\n                } else if (abs(k_p1pt - k_p1p2) < FLT_EPSILON) {\n                    found_intersection = true;\n                    intersection_pt = pt;\n                } else if (k_p1pt > 0 && k_p1pt < k_p1p2) {\n                    found_intersection = true;\n                    intersection_pt = pt;\n                }\n                else\n                    found_intersection = false;\n\n                if(found_intersection){\n                    //if(p1angle != p2angle)\n                    //    std::cout << cam_angle << \" \" << p1angle << \" \" << p2angle << \" \" << p1index << \" \" << p2index <<  std::endl;\n                    break;\n                }\n            }\n\n            float cp = (float)i/float(cam_data.imgw);\n            if(cam_data.limit > 0) if(cp > cam_data.limit) found_intersection = false;\n            if(cam_data.limit < 0) if(cp < fabs(cam_data.limit)) found_intersection = false;\n\n            if (found_intersection) {\n                design_pts(0, i) = intersection_pt(0); //x-value of pt\n                design_pts(1, i) = 0; //y-value of pt (zero since in xz plane)\n                design_pts(2, i) = intersection_pt(1); //z-value of pt\n                design_pts(3, i) = 1; // 1 to make pt homogenous\n                valid_points+=1;\n            } else {\n                design_pts(0, i) = 0; //x-value of pt\n                design_pts(1, i) = 0; //y-value of pt (zero since in xz plane)\n                design_pts(2, i) = 0; //z-value of pt\n                design_pts(3, i) = -1; // -1 indicates bad point\n            }\n\n        }\n\n        return design_pts;\n    }\n\n\n    static std::vector<int16_t> getLaserPosition(const Eigen::Matrix4Xf& design_pts, const Datum& cam_data, const Laser& laser_data){\n        Eigen::Matrix4Xf design_pts_laser = laser_data.cam_to_laser * design_pts;\n        Eigen::VectorXf laser_angles(cam_data.imgw);\n        std::vector<int16_t> proj_pos(cam_data.imgw);\n\n        // First value of projectors positions should be the first actual valid galvo position so the galvo has time to move there before the camera gets there\n        bool init = false;\n        int16_t first_val = -30000;\n\n        // Calculate laser angles for design points\n        int16_t maxADC = laser_data.maxADC;\n        for (int i = 0; i < cam_data.imgw; i++) {\n            int16_t val = 0;\n            if (design_pts(3,i) == 1) { //check if valid point...invalid points this is -1\n                laser_angles(i) = -((atan2f(design_pts_laser(2, i), design_pts_laser(0, i)) * 180 / M_PI) - 90) + 0 + 0;\n                float pos = laser_data.getPositionFromAngle(laser_angles(i));\n                val = int32_t(roundf(pos * maxADC));\n                if (val > maxADC)\n                    val = maxADC;\n                if (val < -maxADC)\n                    val = -maxADC;\n                if(!init) {\n                    first_val = val;\n                    init = true;\n                }\n            } else {\n                val = -30000; //design point is not good...make sure projector knows by sending an out of range value\n            }\n            proj_pos[i] = val;\n        }\n        proj_pos[0] = first_val; //set the first projector position to the first valid angle\n        return proj_pos;\n    }\n\n    static Eigen::Matrix3f setEulerYPR(float eulerZ, float eulerY, float eulerX) {\n        float ci = std::cos(eulerX); \n        float cj = std::cos(eulerY); \n        float ch = std::cos(eulerZ); \n        float si = std::sin(eulerX); \n        float sj = std::sin(eulerY); \n        float sh = std::sin(eulerZ); \n        float cc = ci * ch; \n        float cs = ci * sh; \n        float sc = si * ch; \n        float ss = si * sh;\n\n        Eigen::Matrix3f rot_matrix;\n        rot_matrix << cj * ch, sj * sc - cs, sj * cc + ss,\n                      cj * sh, sj * ss + cc, sj * cs - sc, \n                      -sj,     cj * si,      cj * ci;\n        \n        return rot_matrix;\n    }\n    \n\n    static Eigen::Matrix4f getTransformMatrix(float yaw, float pitch, float roll, float x, float y, float z){\n        Eigen::Matrix4f transform_matrix;\n        Eigen::Matrix3f rot_matrix = setEulerYPR(roll*M_PI/180., pitch*M_PI/180., yaw*M_PI/180.);\n        transform_matrix(0,0) = rot_matrix(0, 0);\n        transform_matrix(0,1) = rot_matrix(0, 1);\n        transform_matrix(0,2) = rot_matrix(0, 2);\n        transform_matrix(1,0) = rot_matrix(1, 0);\n        transform_matrix(1,1) = rot_matrix(1, 1);\n        transform_matrix(1,2) = rot_matrix(1, 2);\n        transform_matrix(2,0) = rot_matrix(2, 0);\n        transform_matrix(2,1) = rot_matrix(2, 1);\n        transform_matrix(2,2) = rot_matrix(2, 2);\n        transform_matrix(0,3) = x;\n        transform_matrix(1,3) = y;\n        transform_matrix(2,3) = z;\n        transform_matrix(3,0) = 0.;\n        transform_matrix(3,1) = 0.;\n        transform_matrix(3,2) = 0.;\n        transform_matrix(3,3) = 1.;\n        return transform_matrix;\n        //tfMat.get\n    }\n\n    static void intersect(float A, float B, float C, float D, const cv::Vec3f& rayEq, cv::Vec4f& coord3D){\n        float t = -D/(A*rayEq[0] + B*rayEq[1] + C);\n        coord3D[0] = rayEq[0]*t;\n        coord3D[1] = rayEq[1]*t;\n        coord3D[2] = rayEq[2]*t;\n        coord3D[3] = 0;\n    }\n\n    struct Angles{\n        std::vector<float> angles;\n        std::vector<float> velocities;\n        std::vector<float> accels;\n        float max_velo;\n        float summed_peak;\n        Eigen::MatrixXf design_pts;\n        Eigen::MatrixXf output_pts;\n        bool exceed = false;\n    };\n\n    static std::shared_ptr<Angles> calculateAngles(const Eigen::Matrix4Xf& design_pts, const Datum& cam_data, const Laser& laser_data, bool get_pts=true, bool warn=false){\n        std::shared_ptr<Angles> angles_ptr = std::make_shared<Angles>();\n        Angles& angles = *angles_ptr.get();\n        Eigen::Matrix4Xf design_pts_laser = laser_data.cam_to_laser * design_pts;\n\n        // Calculate Galvo angle check\n        float nanVal = std::numeric_limits<float>::quiet_NaN();\n        std::vector<float> laser_angles;\n        laser_angles.resize(design_pts_laser.cols());\n        for(int i=0; i<design_pts_laser.cols(); i++){\n            if(design_pts_laser(3, i) == -1){\n                laser_angles[i] = nanVal;\n                continue;\n            }\n            laser_angles[i] = -((atan2f(design_pts_laser(2, i), design_pts_laser(0, i)) * 180 / M_PI) - 90) + 0 + 0;\n        }\n\n        // Smooth out angle?\n        bool exceed = false;\n        std::vector<float> laser_angles_temp = {laser_angles[0]};\n        std::vector<float> velocities = {0};\n        for(int i=1; i<laser_angles.size(); i++){\n            auto new_pt = laser_angles[i];\n            auto old_pt = laser_angles_temp.back();\n            auto velo = (new_pt - old_pt)/(laser_data.laser_timestep);\n            velocities.emplace_back(velo);\n            if(fabs(velo) > laser_data.laser_limit){\n                new_pt = old_pt + laser_data.laser_limit*laser_data.laser_timestep*copysignf(1.0, velo);\n                exceed = true;\n            }\n            laser_angles_temp.emplace_back(new_pt);\n        }\n        laser_angles = laser_angles_temp;\n        velocities[0] = velocities[1];\n        std::vector<float> accel = {0};\n        for(int i=1; i<velocities.size(); i++){\n            auto new_pt = velocities[i];\n            auto old_pt = velocities[i-1];\n            accel.emplace_back(old_pt - new_pt);\n        }\n        accel[0] = accel[1];\n        angles.angles = laser_angles;\n        angles.velocities = velocities;\n        angles.accels = accel;\n        if(exceed) angles.exceed = true;\n        // if(exceed) if(warn) ROS_WARN(\"Design points have exceeded laser limit\");\n\n        if(!get_pts) return angles_ptr;\n\n        Eigen::Matrix4Xf planes_lframe = Eigen::Matrix4Xf::Zero(4, laser_angles.size());\n        for(int i=0; i<laser_angles.size(); i++){\n            auto laser_angle = laser_angles[i];\n            //if(!std::isnan(laser_angles[i])) std::cout << laser_angle << std::endl;\n\n            // Create a straight plane\n            Eigen::Matrix4Xf straight_plane(4,1);\n            straight_plane(0, 0) = 1.; // should we flip this?\n            straight_plane(1, 0) = 0.;\n            straight_plane(2, 0) = 0.;\n            straight_plane(3, 0) = 0.;\n\n            // Rotation Matrices\n            Eigen::Matrix4f lrotated_matrix = getTransformMatrix(0,laser_angle,0,0,0,0);\n            Eigen::Matrix4Xf lrotated_plane = ((lrotated_matrix.inverse().transpose())*straight_plane);\n            planes_lframe.col(i) = lrotated_plane;\n        }\n\n        // Transform planes to camera frame\n        // https://math.stackexchange.com/questions/1377107/new-plane-equation-after-transformation-of-coordinates\n        Eigen::Matrix4Xf planes_cframe = ((laser_data.laser_to_cam.inverse().transpose())*planes_lframe);\n\n        // Compute Ray Intersection\n        // https://nghiaho.com/?page_id=363\n        float* plane_data = planes_cframe.data();\n        float pixelrows = planes_cframe.cols();\n        Eigen::Matrix4Xf design_pts_new = design_pts;\n        for(int u=0; u<pixelrows; u++){\n            float v = cam_data.imgh/2.- 1;\n\n            // Intersect\n            float A = plane_data[u*4 + 0];\n            float B = plane_data[u*4 + 1];\n            float C = plane_data[u*4 + 2];\n            float D = plane_data[u*4 + 3];\n            cv::Vec4f design_pt;\n            intersect(A, B, C, D, cam_data.nmap_nn.at<cv::Vec3f>(v,u), design_pt);\n\n            // Store\n            design_pts_new(0,u) = design_pt[0];\n            design_pts_new(1,u) = design_pt[1];\n            design_pts_new(2,u) = design_pt[2];\n            design_pts_new(3,u) = design_pt[3];\n        }\n\n        angles.output_pts = design_pts_new;\n\n        return angles_ptr;\n    }\n\n    static std::pair<cv::Mat, cv::Mat> calculateSurface(const Eigen::Matrix4Xf& design_pts, const Datum& cam_data, const Laser& laser_data){\n        auto start = std::chrono::steady_clock::now();\n\n        std::pair<cv::Mat, cv::Mat> surface_data;\n        cv::Mat& surface_pts = surface_data.first;\n        cv::Mat& surface_unc = surface_data.second;\n\n        surface_pts = cv::Mat(cam_data.nmap_nn.size().height, cam_data.nmap_nn.size().width, CV_32FC4);\n\n        // Params\n        float nanVal = std::numeric_limits<float>::quiet_NaN();\n        int numCols = design_pts.cols();\n        int numRows = cam_data.nmap.rows;\n        if(cam_data.nmap.cols != numCols)\n            throw std::runtime_error(\"Nmap and design pts dont match\");\n\n        // Store the points in laser (-1 in last column if invalid)\n        Eigen::Matrix4Xf design_pts_laser = laser_data.cam_to_laser * design_pts;\n\n        // Calculate Galvo angle check\n        std::vector<float> laser_angles;\n        laser_angles.resize(design_pts_laser.cols());\n        for(int i=0; i<design_pts_laser.cols(); i++){\n            if(design_pts_laser(3, i) == -1){\n                laser_angles[i] = nanVal;\n                continue;\n            }\n            laser_angles[i] = -((atan2f(design_pts_laser(2, i), design_pts_laser(0, i)) * 180 / M_PI) - 90) + 0 + 0;\n        }\n\n        // Smooth out angle?\n        bool exceed = false;\n        std::vector<float> laser_angles_temp = {laser_angles[0]};\n        for(int i=1; i<laser_angles.size(); i++){\n            auto new_pt = laser_angles[i];\n            auto old_pt = laser_angles_temp.back();\n            auto velo = (new_pt - old_pt)/(laser_data.laser_timestep);\n\n            if(fabs(velo) > laser_data.laser_limit){\n                new_pt = old_pt + laser_data.laser_limit*laser_data.laser_timestep*copysignf(1.0, velo);\n                exceed = true;\n            }\n            laser_angles_temp.emplace_back(new_pt);\n        }\n\n        Eigen::Matrix4Xf planes_lframe = Eigen::Matrix4Xf::Zero(4, laser_angles.size());\n        for(int i=0; i<laser_angles.size(); i++){\n            auto laser_angle = laser_angles[i];\n            //if(!std::isnan(laser_angles[i])) std::cout << laser_angle << std::endl;\n\n            // Create a straight plane\n            Eigen::Matrix4Xf straight_plane(4,1);\n            straight_plane(0, 0) = 1.; // should we flip this?\n            straight_plane(1, 0) = 0.;\n            straight_plane(2, 0) = 0.;\n            straight_plane(3, 0) = 0.;\n\n            // Rotation Matrices\n            Eigen::Matrix4f lrotated_matrix = getTransformMatrix(0,laser_angle,0,0,0,0);\n            Eigen::Matrix4Xf lrotated_plane = ((lrotated_matrix.inverse().transpose())*straight_plane);\n            planes_lframe.col(i) = lrotated_plane;\n        }\n\n        // Transform planes to camera frame\n        // https://math.stackexchange.com/questions/1377107/new-plane-equation-after-transformation-of-coordinates\n        Eigen::Matrix4Xf planes_cframe = ((laser_data.laser_to_cam.inverse().transpose())*planes_lframe);\n\n        // Compute Ray Intersection\n        // https://nghiaho.com/?page_id=363\n        float* plane_data = planes_cframe.data();\n        for(int v=0; v<surface_pts.size().height; v++){\n            for(int u=0; u<surface_pts.size().width; u++){\n                // Got to handle invalid angles here\n\n                // Intersect\n                float A = plane_data[u*4 + 0];\n                float B = plane_data[u*4 + 1];\n                float C = plane_data[u*4 + 2];\n                float D = plane_data[u*4 + 3];\n                intersect(A, B, C, D, cam_data.nmap_nn.at<cv::Vec3f>(v,u), surface_pts.at<cv::Vec4f>(v,u));\n\n                if(surface_pts.at<cv::Vec4f>(v,u)[2] < 0 || fabs(surface_pts.at<cv::Vec4f>(v,u)[1]) > 3.0){\n                    surface_pts.at<cv::Vec4f>(v,u)[0] = nanVal;\n                    surface_pts.at<cv::Vec4f>(v,u)[1] = nanVal;\n                    surface_pts.at<cv::Vec4f>(v,u)[2] = nanVal;\n                    surface_pts.at<cv::Vec4f>(v,u)[3] = nanVal;\n                }\n            }\n        }\n\n        // Setup Unc\n        surface_unc = cv::Mat(cam_data.imgh, cam_data.imgw, CV_32FC1);\n\n        // Compute the various planes for divergence and thickness\n        Eigen::Matrix4Xf lrotated_planes_lframe = Eigen::Matrix4Xf::Zero(4, laser_angles.size());\n        Eigen::Matrix4Xf rrotated_planes_lframe = Eigen::Matrix4Xf::Zero(4, laser_angles.size());\n        for(int i=0; i<laser_angles.size(); i++){\n            if(std::isnan(laser_angles[i])) continue;\n            float laser_angle = laser_angles[i];\n\n            // Create a straight plane\n            Eigen::Matrix4Xf straight_plane(4,1);\n            straight_plane(0, 0) = 1.;\n            straight_plane(1, 0) = 0.;\n            straight_plane(2, 0) = 0.;\n            straight_plane(3, 0) = 0.;\n\n            // Rotation Matrices\n            Eigen::Matrix4f lrotated_matrix = getTransformMatrix(0,laser_angle,0,0,0,0) * getTransformMatrix(0,0,0,(laser_data.thickness/2),0,0) * getTransformMatrix(0,-laser_data.divergence,0,0,0,0);\n            Eigen::Matrix4f rrotated_matrix = getTransformMatrix(0,laser_angle,0,0,0,0) * getTransformMatrix(0,0,0,-(laser_data.thickness/2),0,0) * getTransformMatrix(0,laser_data.divergence,0,0,0,0);\n\n            // Transform planes\n            Eigen::Matrix4Xf lrotated_plane = ((lrotated_matrix.inverse().transpose())*straight_plane);\n            Eigen::Matrix4Xf rrotated_plane = ((rrotated_matrix.inverse().transpose())*straight_plane);\n\n            // Set it\n            lrotated_planes_lframe.col(i) = lrotated_plane;\n            rrotated_planes_lframe.col(i) = rrotated_plane;\n        }\n\n        // Transform to Cam\n        Eigen::Matrix4Xf lrotated_planes_cframe = ((laser_data.laser_to_cam.inverse().transpose())*lrotated_planes_lframe);\n        Eigen::Matrix4Xf rrotated_planes_cframe = ((laser_data.laser_to_cam.inverse().transpose())*rrotated_planes_lframe);\n\n        // Now iterate\n        float* left_plane_data = lrotated_planes_cframe.data();\n        float* right_plane_data = rrotated_planes_cframe.data();\n        for(int v=0; v<surface_pts.size().height; v++){\n            for(int u=0; u<surface_pts.size().width; u++){\n                // Got to handle invalid angles here\n                // if(std::isnan(laser_angles[u])) continue;\n\n                // Planes\n                float Al = left_plane_data[u*4 + 0];\n                float Bl = left_plane_data[u*4 + 1];\n                float Cl = left_plane_data[u*4 + 2];\n                float Dl = left_plane_data[u*4 + 3];\n                float Ar = right_plane_data[u*4 + 0];\n                float Br = right_plane_data[u*4 + 1];\n                float Cr = right_plane_data[u*4 + 2];\n                float Dr = right_plane_data[u*4 + 3];\n\n                // Range Uncertainty\n                cv::Vec4f intersect_point_bot;\n                intersect(Al, Bl, Cl, Dl, cam_data.nmap_nn.at<cv::Vec3f>(v,u), intersect_point_bot);\n                cv::Vec4f intersect_point_top;\n                intersect(Ar, Br, Cr, Dr, cam_data.nmap_nn.at<cv::Vec3f>(v,u), intersect_point_top);\n                float range_unc = sqrt(pow(intersect_point_bot[0]-intersect_point_top[0], 2)\n                                       + pow(intersect_point_bot[1]-intersect_point_top[1], 2)\n                                       + pow(intersect_point_bot[2]-intersect_point_top[2], 2) );\n                surface_unc.at<float>(v,u) = range_unc;\n\n            }\n        }\n\n        auto end = std::chrono::steady_clock::now();\n        //std::cout << \"Elapsed time in milliseconds : \" << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << \" ms\" << std::endl;\n\n        return surface_data;\n    }\n\n    std::string type2str(int type) {\n        std::string r;\n\n        uchar depth = type & CV_MAT_DEPTH_MASK;\n        uchar chans = 1 + (type >> CV_CN_SHIFT);\n\n        switch ( depth ) {\n            case CV_8U:  r = \"8U\"; break;\n            case CV_8S:  r = \"8S\"; break;\n            case CV_16U: r = \"16U\"; break;\n            case CV_16S: r = \"16S\"; break;\n            case CV_32S: r = \"32S\"; break;\n            case CV_32F: r = \"32F\"; break;\n            case CV_64F: r = \"64F\"; break;\n            default:     r = \"User\"; break;\n        }\n\n        r += \"C\";\n        r += (chans+'0');\n\n        return r;\n    }\n\n    void computeDepthHits(std::pair<cv::Mat,cv::Mat>& surface_data, const cv::Mat& depth_img, const Datum& cam_data){\n        cv::Mat& surface_pts = surface_data.first;\n        cv::Mat& surface_unc = surface_data.second;\n        if(surface_pts.size() != depth_img.size()) throw std::runtime_error(\"Error\");\n\n        // Test against depth map\n        for(int v=0; v<surface_pts.size().height; v++){\n            for(int u=0; u<surface_pts.size().width; u++){\n                cv::Vec4f& coord3D = surface_pts.at<cv::Vec4f>(v,u);\n                float unc = surface_unc.at<float>(v,u);\n                if(std::isnan(unc)) continue;\n                float zval = depth_img.at<float>(v,u);\n                float surface_range = sqrt(coord3D(0)*coord3D(0) + coord3D(1)*coord3D(1) + coord3D(2)*coord3D(2));\n                float depth_range = zval/cam_data.ztoramap.at<float>(v,u);\n                //float error = fabs(coord3D[2] - zval);\n                float error = fabs(depth_range - surface_range);\n                float color = 0;\n                if(error >= 0) color = 255. - 255.*(error/unc);\n                //(error/unc)\n                if(error < unc) coord3D[3] = int(color); // Check this with joe\n            }\n        }\n\n    }\n\n    void transform(cv::Mat& surface_pts, Eigen::MatrixXf matrix){\n        for(int v=0; v<surface_pts.size().height; v++) {\n            for (int u = 0; u < surface_pts.size().width; u++) {\n                cv::Vec4f &coord3D = surface_pts.at<cv::Vec4f>(v, u);\n                float x = coord3D[0]; float y = coord3D[1]; float z = coord3D[2];\n                coord3D[0] = matrix(0,0)*x + matrix(0,1)*y + matrix(0,2)*z + matrix(0,3);\n                coord3D[1] = matrix(1,0)*x + matrix(1,1)*y + matrix(1,2)*z + matrix(1,3);\n                coord3D[2] = matrix(2,0)*x + matrix(2,1)*y + matrix(2,2)*z + matrix(2,3);\n            }\n        }\n    }\n\n    std::shared_ptr<Angles> splineToAngles(Eigen::MatrixXf& spline, std::string cam_name, std::string laser_name){\n        // Get Objects\n        Datum& cam_data = *(c_datums_[cam_mapping_[cam_name]].get());\n        Laser& laser_data = cam_data.laser_data[laser_name];\n\n        // Convert to vec\n        std::vector<Point2D> pts(spline.rows());\n        for(int i=0; i<pts.size(); i++) pts[i] = Point2D(spline(i, 0),spline(i, 1));\n\n        // Compute Angles/Velo/Accel\n        auto good_inds = checkPoints(pts, cam_data, laser_data);\n        auto design_pts = findCameraIntersectionsOpt2(cam_data, good_inds, pts);\n        std::shared_ptr<Angles> angles_ptr = calculateAngles(design_pts, cam_data, laser_data, true, false);\n        Angles& angles = *angles_ptr.get();\n\n        // Smooth and get peaks\n        removeNan(angles.velocities);\n        removeNan(angles.accels);\n        if(angles.accels.size() < 11){\n            return angles_ptr;\n        }\n        std::vector<float> smoothing_kernel = {0.2, 0.2, 0.2, 0.2, 0.2};\n        std::vector<float> edge_kernel = {-1, -2, 0, 1, 2};\n        angles.accels = convolve(angles.accels, smoothing_kernel, 1);\n        auto jerk = convolve(angles.accels, edge_kernel, 1);\n        angles.summed_peak = squaredSum(jerk);\n        angles.max_velo = *std::max_element(angles.velocities.begin(), angles.velocities.end()); // slow. move this out to the calculateAnglesFunc\n        angles.design_pts = design_pts;\n\n        return angles_ptr;\n    }\n\n    std::pair<Eigen::MatrixXf, float> fitSpline(Eigen::MatrixXf& path, std::string cam_name, std::string laser_name){\n        auto begin = std::chrono::steady_clock::now();\n        float best_b = 0;\n        std::tuple<Eigen::MatrixXf, float, bool> best_data;\n\n        // Create copy\n        Eigen::MatrixXf path_copy = path;\n\n        // Special Cases\n        if(path.rows() == 1){\n            Eigen::MatrixXf spline = fitBSpline(path_copy, 1);\n            return std::pair<Eigen::MatrixXf, float>(spline, 0);\n        }else if(path.rows() == 2){\n            float cost = 0;\n            Eigen::MatrixXf spline = fitBSpline(path_copy, 1);\n            std::shared_ptr<Angles> angles = splineToAngles(spline, cam_name, laser_name);\n            // Compute distance\n            Eigen::MatrixXf output_pts = angles->output_pts.transpose();\n            bool exceed_dist = closestDistance(output_pts, path_copy, 0.1);\n            // The points are no longer reaching, so we bias this badly\n            if(exceed_dist){\n                return std::pair<Eigen::MatrixXf, float>(spline, -1);\n            }\n            float delt = 0.01;\n            cost += (1-delt)*angles->summed_peak + delt*angles->max_velo;\n            return std::pair<Eigen::MatrixXf, float>(spline, cost);\n        }\n\n        begin = std::chrono::steady_clock::now();\n\n        // Test annealing\n        float start = 1.8;\n        float end = 11.5;\n        float step = 2;\n        int counter = 0;\n        std::map<float, float> hash1;\n        std::map<float, Eigen::MatrixXf> hash2;\n        std::map<float, bool> hash3;\n        Eigen::MatrixXf best_spline;\n        bool best_invalid;\n        float best_cost;\n        while(1){\n            counter+=1;\n\n            // Test set\n            float lowest_cost = std::numeric_limits<float>::infinity();\n            float curr_best_b = 0;\n            bool curr_invalid = false;\n            Eigen::MatrixXf curr_best_spline;\n            for(auto b : arange<float>(start, end, step, true)){\n                //b = 11.5; //HACK!!!!!!!!!!!\n                float cost = 0;\n                Eigen::MatrixXf spline;\n                bool invalid = false;\n                if(hash1.count(b)){\n                    cost = hash1[b];\n                    spline = hash2[b];\n                    invalid = hash3[b];\n                }else{\n                    setCol(path_copy, 2, b);\n                    spline = fitBSpline(path_copy, 1);\n                    std::shared_ptr<Angles> angles = splineToAngles(spline, cam_name, laser_name);\n                    //Angles angles;\n                    //if(angles.exceed) invalid = true;\n\n                    // Compute distance\n                    Eigen::MatrixXf output_pts = angles->output_pts.transpose();\n                    bool exceed_dist = closestDistance(output_pts, path_copy, 0.1);\n                    // The points are no longer reaching, so we bias this badly\n                    if(exceed_dist){\n                        invalid = true;\n                        cost += 1000000000;\n                    }\n                    float delt = 0.01;\n                    cost += (1-delt)*angles->summed_peak + delt*angles->max_velo;\n                }\n\n                //std::cout << b << \" \" << cost << std::endl;\n\n                // Cost Function\n                hash1[b] = cost;\n                hash2[b] = spline;\n                hash3[b] = invalid;\n                if(cost < lowest_cost){\n                    lowest_cost = cost;\n                    curr_best_spline = spline;\n                    curr_best_b = b;\n                    curr_invalid = invalid;\n                }\n\n            }\n\n            // Update\n            start = curr_best_b - step;\n            end = curr_best_b + step;\n            start = std::max(start, (float)1.8);\n            end = std::min(end, (float)11.5);\n            step /= 2.5;\n            if(counter == 4){\n                best_cost = lowest_cost;\n                best_invalid = curr_invalid;\n                best_b = curr_best_b;\n                best_spline = curr_best_spline;\n                break;\n            }\n        }\n\n        //std::cout << \" \" << best_b << \" \" << best_cost << \" \" << std::endl;\n        if(best_invalid){\n            //ROS_ERROR(\"Invalid\");\n            best_cost = -1;\n        }\n\n        return std::pair<Eigen::MatrixXf, float>(best_spline, best_cost);\n    }\n\n    void eigen_push_back(Eigen::MatrixXf& m, Eigen::Vector2f& values, std::size_t row)\n    {\n        if(row >= m.rows()) {\n            m.conservativeResize(row + 1, Eigen::NoChange);\n        }\n        m.row(row) = values;\n    }\n\n    void evalPath(Eigen::MatrixXf& path, std::string cam_name, std::string laser_name, std::shared_ptr<Output>& output, bool process=false){\n        /*\n         * This function takes in just path (a single path)\n         * sorts them xwise left to right\n         *\n         * I compute the spline -\n         *  fitSpline() - does the optimization via annealing - return best spline\n         *      this will call testSpline() - this does all the angles/gradient compute and returns it in Output object\n         *\n         * Need a cost for checking if the target actually got sampled\n         */\n        Datum& cam_data = *(c_datums_[cam_mapping_[cam_name]].get());\n        Laser& laser_data = cam_data.laser_data[laser_name];\n\n        // Path remove the out of fov points\n        std::vector<Point2D> pts(path.rows());\n        for(int i=0; i<pts.size(); i++) pts[i] = Point2D(path(i, 0),path(i, 1));\n        auto bad_inds = checkPoints(pts, cam_data, laser_data, false);\n        removeRows(path, bad_inds);\n        if(path.rows() == 0){\n            return;\n        }\n\n        std::vector<Eigen::MatrixXf> finalSplines;\n\n        // Start with angle sort for all\n        Eigen::MatrixXf p1 = path;\n        eigenAngleSort(p1);\n        std::pair<Eigen::MatrixXf, float> s1 = fitSpline(p1, cam_name, laser_name);\n        if(s1.second >= 0) {\n            finalSplines.emplace_back(s1.first);\n        }\n\n        // If that failed do xsort\n        if(finalSplines.empty()){\n            Eigen::MatrixXf p2 = path;\n            eigenXSort(p2);\n            std::pair<Eigen::MatrixXf, float> s2 = fitSpline(p2, cam_name, laser_name);\n            if(s2.second >= 0) {\n                finalSplines.emplace_back(s2.first);\n            }\n        }\n\n        // Plan N paths\n        if(finalSplines.empty()){\n\n            // Sort by angles again for all\n            eigenAngleSort(path);\n\n            //TEST INCREASING SPLIT COUNT\n            for(int sc=2; sc<5; sc++){\n                // Generate all continious permutations\n                auto contiguous_perms = generateContPerms(path.rows(), sc);\n                //std::cout << contiguous_perms.size() << std::endl;\n\n                // We could sort the permutations based on average change in angle?\n                auto beginx = std::chrono::steady_clock::now();\n                std::vector<std::pair<int, float>> costs(contiguous_perms.size());\n                for(int i=0; i<contiguous_perms.size(); i++) {\n                    const auto &splits = contiguous_perms[i];\n                    float ychange = 0.;\n                    float ycount = 0.;\n                    for(const auto& split : splits){\n                        if(split.size() > 1) {\n                            for (int j = 1; j < split.size(); j++) {\n                                int rindex = split[j];\n                                int lindex = split[j - 1];\n                                ychange += fabs(path(rindex, 1) - path(lindex, 1));\n                                ycount += 1.;\n                            }\n                        }else{\n                            ycount += 1.;\n                        }\n                    }\n                    float yavg = ychange/ycount;\n                    costs[i] = std::pair<int, float>(i, yavg);\n                }\n                // Sort\n                std::sort(costs.begin(), costs.end(),\n                          [](const std::pair<int, float>& c1, const std::pair<int, float>& c2) {return c1.second < c2.second;});\n                // Reorganize order of perms\n                std::vector<size_t> indicies(costs.size());\n                for(int i=0; i<indicies.size(); i++) indicies[i] = costs[i].first;\n                reorder_naive(contiguous_perms, indicies);\n\n                // Iterate and compute costs to break\n                auto begin = std::chrono::steady_clock::now();\n                bool added = false;\n                int windex = -1;\n                for(int i=0; i<contiguous_perms.size(); i++){\n                    const auto& splits = contiguous_perms[i];\n                    bool valid = true;\n                    float hit_percentage = ((float)i/(float)contiguous_perms.size())*100.;\n                    std::vector<Eigen::MatrixXf> goodSplines;\n                    for(auto& split : splits){\n                        // Generate path\n                        Eigen::MatrixXf split_path = customSort(path, split);\n                        // Compute\n                        std::pair<Eigen::MatrixXf, float> s = fitSpline(split_path, cam_name, laser_name);\n                        if(s.second < 0) valid = false;\n                        else goodSplines.emplace_back(s.first); // hack\n                    }\n                    if(valid){\n                        finalSplines.insert(finalSplines.end(), goodSplines.begin(), goodSplines.end());\n                        added = true;\n                        windex = i;\n                        break;\n                    }\n                    if(hit_percentage > 0.3) break; // Hack to make it faster for more splits\n                }\n                //std::cout << \"split = \" << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - begin).count() << \"[ms]\" << std::endl;\n                if(added) break;\n            }\n\n        }\n\n        // Allocate Outputs\n        if(process) output->output_pts_set.resize(finalSplines.size());\n        output->spline_set.resize(finalSplines.size());\n\n        // Reprocess\n        for(int i=0; i<finalSplines.size(); i++){\n            std::shared_ptr<Output> temp_output = std::make_shared<Output>();\n            if(process){\n                processTest(finalSplines[i], cam_name, laser_name, temp_output, 1);\n                output->output_pts_set[i] = temp_output->output_pts;\n            }\n            output->spline_set[i] = finalSplines[i];\n        }\n    }\n\n    void evalPaths(std::vector<Eigen::MatrixXf>& paths, std::string cam_name, std::string laser_name){\n        if(!cam_mapping_.count(cam_name)) throw std::runtime_error(\"No such camera name\");\n        Datum& cam_data = *(c_datums_[cam_mapping_[cam_name]].get());\n        if(!cam_data.laser_data.count(laser_name)) throw std::runtime_error(\"No such laser name\");\n        Laser& laser_data = cam_data.laser_data[laser_name];\n\n        for(auto& path : paths){\n            std::cout << path << std::endl;\n            std::cout << \"--\" << std::endl;\n        }\n    }\n\n    void processTest(Eigen::MatrixXf& input_pts, std::string cam_name, std::string laser_name, std::shared_ptr<Output>& output, int mode){\n        if(!cam_mapping_.count(cam_name)) throw std::runtime_error(\"No such camera name\");\n        Datum& cam_data = *(c_datums_[cam_mapping_[cam_name]].get());\n\n        if(!cam_data.laser_data.count(laser_name)) throw std::runtime_error(\"No such laser name\");\n        Laser& laser_data = cam_data.laser_data[laser_name];\n\n        // Convert to vec\n        std::vector<Point2D> pts(input_pts.rows());\n        if(mode == 0){\n            for(int i=0; i<pts.size(); i++){\n                pts[i] = Point2D(input_pts(i, 0),input_pts(i, 2));\n            }\n        }else if(mode == 1){\n            for(int i=0; i<pts.size(); i++){\n                pts[i] = Point2D(input_pts(i, 0),input_pts(i, 1));\n            }\n        }\n\n        // Check points inside sensors\n        auto good_inds = checkPoints(pts, cam_data, laser_data);\n\n        // Get true points based on cam ray intersections (Slow)\n        //auto design_pts = findCameraIntersections(cam_data, good_inds, pts);\n        Eigen::Matrix4Xf design_pts = findCameraIntersectionsOpt2(cam_data, good_inds, pts);\n\n        // Get Angles\n        std::shared_ptr<Angles> angles = calculateAngles(design_pts, cam_data, laser_data, true, true);\n\n        // Store\n        output->spline = input_pts;\n        output->output_pts = angles->output_pts;\n        output->angles = angles->angles;\n        output->velocities = angles->velocities;\n        output->accels = angles->accels;\n        //output->laser_rays = rays;\n    }\n\n    void processPointsT(const Eigen::MatrixXf& input_pts, const cv::Mat& depth_img, std::string cam_name, std::string laser_name, cv::Mat& image, std::vector<PointXYZI>& cloud, bool compute_cloud=true){\n        bool debug = false;\n        auto begin = std::chrono::steady_clock::now();\n        auto beginf = std::chrono::steady_clock::now();\n\n        if(!set) throw std::runtime_error(\"Sensors not set\");\n\n        if(!cam_mapping_.count(cam_name)) throw std::runtime_error(\"No such camera name\");\n        Datum& cam_data = *(c_datums_[cam_mapping_[cam_name]].get());\n\n        if(!cam_data.laser_data.count(laser_name)) throw std::runtime_error(\"No such laser name\");\n        Laser& laser_data = cam_data.laser_data[laser_name];\n\n        // Convert to vec\n        std::vector<Point2D> pts(input_pts.rows());\n        for(int i=0; i<pts.size(); i++){\n            pts[i] = Point2D(input_pts(i, 0),input_pts(i, 2));\n        }\n\n        // Check points inside sensors\n        auto good_inds = checkPoints(pts, cam_data, laser_data);\n        \n        // Get true points based on cam ray intersections (Slow)\n        auto design_pts = findCameraIntersectionsOpt(cam_data, good_inds, pts);\n        \n        // Surface Pts\n        auto surface_data = calculateSurface(design_pts, cam_data, laser_data);\n        auto& surface_pts = surface_data.first;\n        \n        // Compute hit\n        computeDepthHits(surface_data, depth_img, cam_data);\n        \n        // Copy to Output.images_multi.\n        surface_pts.copyTo(image);\n\n        // Cloud Compute\n        if(!compute_cloud) return;\n\n        // Downsample\n        float downsample = 2.;\n        if(downsample > 1){\n            float voxelize = 1./((float)downsample);\n            cv::resize(surface_pts, surface_pts, cv::Size(), voxelize, voxelize, cv::INTER_NEAREST);\n        }\n                // cv_bridge::CvImage out_msg;\n        // out_msg.encoding = sensor_msgs::image_encodings::TYPE_32FC4;\n        // out_msg.image = surface_pts;\n        // out_msg.toImageMsg(image);\n        // Store it\n        cloud.resize(surface_pts.size().width*surface_pts.size().height);\n        for(int v=0; v<surface_pts.size().height; v++){\n            for(int u=0; u<surface_pts.size().width; u++){\n                int index = v*surface_pts.size().width + u;\n                const cv::Vec4f& coord3D = surface_pts.at<cv::Vec4f>(v,u);\n                cloud[index] = coord3D;\n            }\n        }\n    }\n};\n\n#endif", "meta": {"hexsha": "e15e1f62fcb3d9e9cac4699668f8327eb25c860d", "size": 62921, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pylc/src/pylc_lib/sim_class.hpp", "max_stars_repo_name": "CMU-Light-Curtains/ObjectDetection", "max_stars_repo_head_hexsha": "d2002f6d1ebcf05a78f179bf0474703ed0211ac0", "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": "pylc/src/pylc_lib/sim_class.hpp", "max_issues_repo_name": "CMU-Light-Curtains/ObjectDetection", "max_issues_repo_head_hexsha": "d2002f6d1ebcf05a78f179bf0474703ed0211ac0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pylc/src/pylc_lib/sim_class.hpp", "max_forks_repo_name": "CMU-Light-Curtains/ObjectDetection", "max_forks_repo_head_hexsha": "d2002f6d1ebcf05a78f179bf0474703ed0211ac0", "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.9908794788, "max_line_length": 202, "alphanum_fraction": 0.5536625292, "num_tokens": 16526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6113819591324416, "lm_q1q2_score": 0.5026716013959088}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"polynome.h\"\n\nBOOST_AUTO_TEST_SUITE(test_polynome)\n\n    BOOST_AUTO_TEST_CASE(initialization_1) {\n        Polynome<long long> p(10);\n        BOOST_CHECK_EQUAL(p.taille(), 1);\n        BOOST_CHECK_EQUAL(p.valeur(42), 10);\n    }\n\n    BOOST_AUTO_TEST_CASE(initialization_2) {\n        Polynome<long long> p{-1, 0, 1};\n        BOOST_CHECK_EQUAL(p.taille(), 3);\n        BOOST_CHECK_EQUAL(p.valeur(2), 3);\n    }\n\n    BOOST_AUTO_TEST_CASE(comparaison) {\n        Polynome<long long> p{-1, 0, 1};\n        Polynome<long long> q{-1, 0, 1};\n        Polynome<long long> r{1, 0, 1};\n        BOOST_CHECK_EQUAL(p, q);\n        BOOST_CHECK_NE(p, r);\n    }\n\n    BOOST_AUTO_TEST_CASE(addition) {\n        Polynome<long long> p{-1, 0, 1};\n        Polynome<long long> q{0, 1};\n        Polynome<long long> r{-1, 1, 1};\n        BOOST_CHECK_EQUAL(p + q, r);\n    }\n\n    BOOST_AUTO_TEST_CASE(soustraction) {\n        Polynome<long long> p{-1, 1, 1};\n        Polynome<long long> q{0, 0, 1};\n        Polynome<long long> r{-1, 1};\n        BOOST_CHECK_EQUAL(p - q, r);\n    }\n\n    BOOST_AUTO_TEST_CASE(multiplication) {\n        Polynome<long long> p{1, -1, 1, -1, 1};\n        Polynome<long long> q{1, 1,};\n        Polynome<long long> r{1, 0, 0, 0, 0, 1};\n        BOOST_CHECK_EQUAL(p * q, r);\n    }\n\n    BOOST_AUTO_TEST_CASE(affiche_1) {\n        Polynome<long long> p{1, -1, 1, -1, 1};\n        std::ostringstream oss;\n        oss << p;\n        BOOST_CHECK_EQUAL(oss.str(), \"X^4 - X^3 + X^2 - X + 1\");\n    }\n\n    BOOST_AUTO_TEST_CASE(affiche_2) {\n        Polynome<long long> p{1, 1,};\n        std::ostringstream oss;\n        oss << p;\n        BOOST_CHECK_EQUAL(oss.str(), \"X + 1\");\n    }\n\n    BOOST_AUTO_TEST_CASE(affiche_3) {\n        Polynome<long long> p{1, 0, 0, 0, 0, 1};\n        std::ostringstream oss;\n        oss << p;\n        BOOST_CHECK_EQUAL(oss.str(), \"X^5 + 1\");\n    }\n\n    BOOST_AUTO_TEST_CASE(division_euclidienne_1) {\n        Polynome<long long> A{0, -2, 3, -1, -1, 1};\n        Polynome<long long> B{1, -1, 1};\n\n\n        Polynome<long long> Q;\n        Polynome<long long> R;\n        Polynome<long long>::division_euclidienne(A, B, Q, R);\n\n        Polynome<long long> Q1{1, -2, 0, 1};\n        Polynome<long long> R1{-1, 1};\n\n        BOOST_CHECK_EQUAL(Q, Q1);\n        BOOST_CHECK_EQUAL(R, R1);\n    }\n\n    BOOST_AUTO_TEST_CASE(division_euclidienne_2) {\n        Polynome<long long> A{-1, 0, 0, 0, 0, 0, 0, 1};\n        Polynome<long long> B{-1, 1};\n\n        Polynome<long long> Q;\n        Polynome<long long> R;\n\n        Polynome<long long>::division_euclidienne(A, B, Q, R);\n        Polynome<long long> Q1{1, 1, 1, 1, 1, 1, 1};\n        Polynome<long long> R1;\n\n        BOOST_CHECK_EQUAL(Q, Q1);\n        BOOST_CHECK_EQUAL(R, R1);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "b87b5e60e212885d9027b9205b61395848791260", "size": 2782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/polynome.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/polynome.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/polynome.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.5445544554, "max_line_length": 64, "alphanum_fraction": 0.5629043853, "num_tokens": 942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.7154239957834732, "lm_q1q2_score": 0.5026068697311867}}
{"text": "//\n//  Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n\n#include <random>\n#include <boost/numeric/ublas/tensor.hpp>\n\n#ifndef BOOST_TEST_DYN_LINK\n#define BOOST_TEST_DYN_LINK \n#endif\n// NOLINTNEXTLINE\n#define BOOST_TEST_MODULE Tensor\n\n\n#include <boost/test/unit_test.hpp>\n#include \"utility.hpp\"\n\nBOOST_AUTO_TEST_SUITE ( test_tensor )\n\nusing test_types = zip<int,float,std::complex<float>>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_tensor_ctor, value,  test_types)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n//    auto a1 = tensor_type{};\n//    BOOST_CHECK_EQUAL( a1.size() , 0ul );\n//    BOOST_CHECK( a1.empty() );\n//    BOOST_CHECK_EQUAL( a1.data() , nullptr);\n\n    auto a2 = tensor_type{1,1};\n    BOOST_CHECK_EQUAL(  a2.size() , 1 );\n    BOOST_CHECK( !a2.empty() );\n    BOOST_CHECK_NE(  a2.data() , nullptr);\n\n    auto a3 = tensor_type{2,1};\n    BOOST_CHECK_EQUAL(  a3.size() , 2 );\n    BOOST_CHECK( !a3.empty() );\n    BOOST_CHECK_NE(  a3.data() , nullptr);\n\n    auto a4 = tensor_type{1,2};\n    BOOST_CHECK_EQUAL(  a4.size() , 2 );\n    BOOST_CHECK( !a4.empty() );\n    BOOST_CHECK_NE(  a4.data() , nullptr);\n\n    auto a5 = tensor_type{2,1};\n    BOOST_CHECK_EQUAL(  a5.size() , 2 );\n    BOOST_CHECK( !a5.empty() );\n    BOOST_CHECK_NE(  a5.data() , nullptr);\n\n    auto a6 = tensor_type{4,3,2};\n    BOOST_CHECK_EQUAL(  a6.size() , 4*3*2 );\n    BOOST_CHECK( !a6.empty() );\n    BOOST_CHECK_NE(  a6.data() , nullptr);\n\n    auto a7 = tensor_type{4,1,2};\n    BOOST_CHECK_EQUAL(  a7.size() , 4*1*2 );\n    BOOST_CHECK( !a7.empty() );\n    BOOST_CHECK_NE(  a7.data() , nullptr);\n\n\n}\n\n\nstruct fixture\n{\n    using extents_type = boost::numeric::ublas::extents<>;\n    fixture()\n      : extents {\n          extents_type{1,1}, // 1\n          extents_type{1,2}, // 2\n          extents_type{2,1}, // 3\n          extents_type{2,3}, // 4\n          extents_type{2,3,1}, // 5\n          extents_type{4,1,3}, // 6\n          extents_type{1,2,3}, // 7\n          extents_type{4,2,3}, // 8\n          extents_type{4,2,3,5}} // 9\n    {\n    }\n    std::vector<extents_type> extents;\n};\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_ctor_extents, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n    auto check = [](auto const& e) {\n        auto t = tensor_type{e};\n        BOOST_CHECK_EQUAL (  t.size() , ublas::product(e) );\n        BOOST_CHECK_EQUAL (  t.rank() , ublas::size(e) );\n        if(ublas::empty(e)) {\n            BOOST_CHECK       ( t.empty()    );\n            BOOST_CHECK_EQUAL ( t.data() , nullptr);\n        }\n        else{\n            BOOST_CHECK       ( !t.empty()    );\n            BOOST_CHECK_NE    (  t.data() , nullptr);\n        }\n    };\n\n    for(auto const& e : extents)\n        check(e);\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_copy_ctor, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n    auto check = [](auto const& e)\n    {\n        auto r = tensor_type{e};\n        auto t = r;\n        BOOST_CHECK_EQUAL (  t.size() , r.size() );\n        BOOST_CHECK_EQUAL (  t.rank() , r.rank() );\n        BOOST_CHECK ( t.strides() == r.strides() );\n        BOOST_CHECK ( t.extents() == r.extents() );\n\n        if(ublas::empty(e)) {\n            BOOST_CHECK       ( t.empty()    );\n            BOOST_CHECK_EQUAL ( t.data() , nullptr);\n        }\n        else{\n            BOOST_CHECK       ( !t.empty()    );\n            BOOST_CHECK_NE    (  t.data() , nullptr);\n        }\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL( t[i], r[i]  );\n    };\n\n    for(auto const& e : extents)\n        check(e);\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_copy_ctor_layout, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n    using other_layout_type = std::conditional_t<std::is_same<ublas::layout::first_order,layout_type>::value, ublas::layout::last_order, ublas::layout::first_order>;\n    using other_tensor_type = ublas::tensor_dynamic<value_type, other_layout_type>;\n\n\n    for(auto const& e : extents)\n    {\n        auto r = tensor_type{e};\n        other_tensor_type t = r;\n        tensor_type q = t;\n\n        BOOST_CHECK_EQUAL (  t.size() , r.size() );\n        BOOST_CHECK_EQUAL (  t.rank() , r.rank() );\n        BOOST_CHECK ( t.extents() == r.extents() );\n\n        BOOST_CHECK_EQUAL (  q.size() , r.size() );\n        BOOST_CHECK_EQUAL (  q.rank() , r.rank() );\n        BOOST_CHECK ( q.strides() == r.strides() );\n        BOOST_CHECK ( q.extents() == r.extents() );\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL( q[i], r[i]  );\n    }\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_copy_move_ctor, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type = ublas::tensor_dynamic<value_type,layout_type>;\n\n    auto check = [](auto const& e)\n    {\n        auto r = tensor_type{e};\n        auto t = std::move(r);\n        BOOST_CHECK_EQUAL (  t.size() , ublas::product(e) );\n        BOOST_CHECK_EQUAL (  t.rank() , ublas::size   (e) );\n\n        if(ublas::empty(e)) {\n            BOOST_CHECK       ( t.empty()    );\n            BOOST_CHECK_EQUAL ( t.data() , nullptr);\n        }\n        else{\n            BOOST_CHECK       ( !t.empty()    );\n            BOOST_CHECK_NE    (  t.data() , nullptr);\n        }\n\n    };\n\n    for(auto const& e : extents)\n        check(e);\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_ctor_extents_init, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type = ublas::tensor_dynamic<value_type,layout_type>;\n\n    std::random_device device{};\n    std::minstd_rand0 generator(device());\n\n    using distribution_type = std::conditional_t<std::is_integral_v<value_type>, std::uniform_int_distribution<>, std::uniform_real_distribution<> >;\n    auto distribution = distribution_type(1,6);\n\n    for(auto const& e : extents){\n        auto r = value_type( static_cast< inner_type_t<value_type> >(distribution(generator)) );\n        auto t = tensor_type{e,r};\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL( t[i], r );\n    }\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_ctor_extents_array, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type = ublas::tensor_dynamic<value_type,layout_type>;\n    using container_type  = typename tensor_type::container_type;\n\n    for(auto const& e : extents) {\n        auto a = container_type(product(e));\n        auto v = value_type {};\n\n        for(auto& aa : a){\n            aa = v;\n            v += value_type{1};\n        }\n        auto t = tensor_type{e, a};\n        v = value_type{};\n\n        for(auto i = 0ul; i < t.size(); ++i, v+=value_type{1})\n            BOOST_CHECK_EQUAL( t[i], v);\n    }\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_read_write_single_index_access, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type = ublas::tensor_dynamic<value_type,layout_type>;\n\n    for(auto const& e : extents) {\n        auto t = tensor_type{e};\n        auto v = value_type {};\n        for(auto i = 0ul; i < t.size(); ++i, v+=value_type{1}){\n            t[i] = v;\n            BOOST_CHECK_EQUAL( t[i], v );\n\n            t(i) = v;\n            BOOST_CHECK_EQUAL( t(i), v );\n        }\n    }\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_read_write_multi_index_access_at, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type = ublas::tensor_dynamic<value_type,layout_type>;\n    auto check1 = [](const tensor_type& t)\n    {\n        auto v = value_type{};\n        for(auto k = 0ul; k < t.size(); ++k){\n            BOOST_CHECK_EQUAL(t[k], v);\n            v+=value_type{1};\n        }\n    };\n\n    auto check2 = [](const tensor_type& t)\n    {\n      std::array<unsigned,2> k = {0,0};\n        auto r = std::is_same<layout_type,ublas::layout::first_order>::value ? 1 : 0;\n        auto q = std::is_same<layout_type,ublas::layout::last_order >::value ? 1 : 0;\n        auto v = value_type{};\n        for(k[r] = 0ul; k[r] < t.size(r); ++k[r]){\n            for(k[q] = 0ul; k[q] < t.size(q); ++k[q]){\n                BOOST_CHECK_EQUAL(t.at(k[0],k[1]), v);\n                v+=value_type{1};\n            }\n        }\n    };\n\n    auto check3 = [](const tensor_type& t)\n    {\n        std::array<unsigned,3> k = {0,0,0};\n        using op_type = std::conditional_t<std::is_same_v<layout_type,ublas::layout::first_order>, std::minus<>, std::plus<>>;\n        auto r = std::is_same_v<layout_type,ublas::layout::first_order> ? 2 : 0;\n        auto o = op_type{};\n        auto v = value_type{};\n        for(k[r] = 0ul; k[r] < t.size(r); ++k[r]){\n            for(k[o(r,1)] = 0ul; k[o(r,1)] < t.size(o(r,1)); ++k[o(r,1)]){\n                for(k[o(r,2)] = 0ul; k[o(r,2)] < t.size(o(r,2)); ++k[o(r,2)]){\n                    BOOST_CHECK_EQUAL(t.at(k[0],k[1],k[2]), v);\n                    v+=value_type{1};\n                }\n            }\n        }\n    };\n\n    auto check4 = [](const tensor_type& t)\n    {\n        std::array<unsigned,4> k = {0,0,0,0};\n        using op_type = std::conditional_t<std::is_same_v<layout_type,ublas::layout::first_order>, std::minus<>, std::plus<>>;\n        auto r = std::is_same_v<layout_type,ublas::layout::first_order> ? 3 : 0;\n        auto o = op_type{};\n        auto v = value_type{};\n        for(k[r] = 0ul; k[r] < t.size(r); ++k[r]){\n            for(k[o(r,1)] = 0ul; k[o(r,1)] < t.size(o(r,1)); ++k[o(r,1)]){\n                for(k[o(r,2)] = 0ul; k[o(r,2)] < t.size(o(r,2)); ++k[o(r,2)]){\n                    for(k[o(r,3)] = 0ul; k[o(r,3)] < t.size(o(r,3)); ++k[o(r,3)]){\n                        BOOST_CHECK_EQUAL(t.at(k[0],k[1],k[2],k[3]), v);\n                        v+=value_type{1};\n                    }\n                }\n            }\n        }\n    };\n\n    auto check = [check1,check2,check3,check4](auto const& e) {\n        auto t = tensor_type{e};\n        auto v = value_type {};\n        for(auto i = 0ul; i < t.size(); ++i){\n            t[i] = v;\n            v+=value_type{1};\n        }\n\n        if(t.rank() == 1) check1(t);\n        else if(t.rank() == 2) check2(t);\n        else if(t.rank() == 3) check3(t);\n        else if(t.rank() == 4) check4(t);\n\n    };\n\n    for(auto const& e : extents)\n        check(e);\n}\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_reshape, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type = ublas::tensor_dynamic<value_type,layout_type>;\n\n    for(auto const& efrom : extents){\n        for(auto const& eto : extents){\n\n            auto v = value_type {};\n            v+=value_type{1};\n            auto t = tensor_type{efrom, v};\n            for(auto i = 0ul; i < t.size(); ++i)\n                BOOST_CHECK_EQUAL( t[i], v );\n\n            auto r = reshape(t,eto);\n            for(auto i = 0ul; i < std::min(ublas::product(efrom),ublas::product(eto)); ++i)\n                BOOST_CHECK_EQUAL( r[i], v );\n\n            BOOST_CHECK_EQUAL (  r.size() , ublas::product(eto) );\n            BOOST_CHECK_EQUAL (  r.rank() , ublas::size   (eto) );\n            BOOST_CHECK ( r.extents() == eto );\n\n            if(efrom != eto){\n                for(auto i = product(efrom); i < t.size(); ++i)\n                    BOOST_CHECK_EQUAL( r[i], value_type{} );\n            }\n        }\n    }\n}\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_swap, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type = ublas::tensor_dynamic<value_type,layout_type>;\n    for(auto const& e_t : extents){\n        for(auto const& e_r : extents) {\n\n            auto v = value_type {} + value_type{1};\n            auto w = value_type {} + value_type{2};\n            auto t = tensor_type{e_t, v};\n            auto r = tensor_type{e_r, w};\n\n            std::swap( r, t );\n\n            for(auto i = 0ul; i < t.size(); ++i)\n                BOOST_CHECK_EQUAL( t[i], w );\n\n            BOOST_CHECK_EQUAL (  t.size() , ublas::product(e_r) );\n            BOOST_CHECK_EQUAL (  t.rank() , ublas::size   (e_r) );\n            BOOST_CHECK ( t.extents() == e_r );\n\n            for(auto i = 0ul; i < r.size(); ++i)\n                BOOST_CHECK_EQUAL( r[i], v );\n\n            BOOST_CHECK_EQUAL (  r.size() , ublas::product(e_t) );\n            BOOST_CHECK_EQUAL (  r.rank() , ublas::size   (e_t) );\n            BOOST_CHECK ( r.extents() == e_t );\n\n\n        }\n    }\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_standard_iterator, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type = ublas::tensor_dynamic<value_type,layout_type>;\n\n    for(auto const& e : extents)\n    {\n        auto v = value_type {} + value_type{1};\n        auto t = tensor_type{e, v};\n\n        BOOST_CHECK_EQUAL( std::distance(t.begin(),  t.end ()), t.size()  );\n        BOOST_CHECK_EQUAL( std::distance(t.rbegin(), t.rend()), t.size()  );\n\n        BOOST_CHECK_EQUAL( std::distance(t.cbegin(),  t.cend ()), t.size() );\n        BOOST_CHECK_EQUAL( std::distance(t.crbegin(), t.crend()), t.size() );\n\n        if(!t.empty()) {\n            BOOST_CHECK(  t.data() ==  std::addressof( *t.begin () )  ) ;\n            BOOST_CHECK(  t.data() ==  std::addressof( *t.cbegin() )  ) ;\n        }\n    }\n}\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_throw, value, test_types, fixture)\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_type  = typename value::first_type;\n  using layout_type = typename value::second_type;\n  using tensor_type = ublas::tensor_dynamic<value_type, layout_type>;\n\n  std::vector<value_type> vec(2);\n  BOOST_CHECK_THROW(tensor_type({5,5},vec), std::invalid_argument);\n\n  auto t = tensor_type{{5,5}};\n  auto i = ublas::index::index_type<4>{};\n  BOOST_CHECK_THROW((void)t.operator()(i,i,i), std::invalid_argument);\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ce16c8916d1495f6ac4821197a5c53cf396574d7", "size": 15792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_tensor.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_tensor.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_tensor.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 32.0975609756, "max_line_length": 165, "alphanum_fraction": 0.5811170213, "num_tokens": 4347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5026068654685649}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \r\n//\r\n// This file is part of the Boost Graph Library\r\n//\r\n// You should have received a copy of the License Agreement for the\r\n// Boost Graph Library along with the software; see the file LICENSE.\r\n// If not, contact Office of Research, Indiana University,\r\n// Bloomington, IN 47405.\r\n//\r\n// Permission to modify the code and to distribute the code is\r\n// granted, provided the text of this NOTICE is retained, a notice if\r\n// the code was modified is included with the above COPYRIGHT NOTICE\r\n// and with the COPYRIGHT NOTICE in the LICENSE file, and that the\r\n// LICENSE file is distributed with the modified code.\r\n//\r\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\r\n// By way of example, but not limitation, Licensor MAKES NO\r\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\r\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\r\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\r\n// OR OTHER RIGHTS.\r\n//=======================================================================\r\n#include <deque>                // to store the vertex ordering\r\n#include <vector>\r\n#include <list>\r\n#include <iostream>\r\n#include <boost/graph/vector_as_graph.hpp>\r\n#include <boost/graph/topological_sort.hpp>\r\n\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  const char *tasks[] = {\r\n    \"pick up kids from school\",\r\n    \"buy groceries (and snacks)\",\r\n    \"get cash at ATM\",\r\n    \"drop off kids at soccer practice\",\r\n    \"cook dinner\",\r\n    \"pick up kids from soccer\",\r\n    \"eat dinner\"\r\n  };\r\n  const int n_tasks = sizeof(tasks) / sizeof(char *);\r\n\r\n  std::vector < std::list < int > > g(n_tasks);\r\n  g[0].push_back(3);\r\n  g[1].push_back(3);\r\n  g[1].push_back(4);\r\n  g[2].push_back(1);\r\n  g[3].push_back(5);\r\n  g[4].push_back(6);\r\n  g[5].push_back(6);\r\n\r\n  std::deque < int >topo_order;\r\n\r\n  topological_sort(g, std::front_inserter(topo_order),\r\n                   vertex_index_map(identity_property_map()));\r\n\r\n  int n = 1;\r\n  for (std::deque < int >::iterator i = topo_order.begin();\r\n       i != topo_order.end(); ++i, ++n)\r\n    std::cout << tasks[*i] << std::endl;\r\n\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "5553631c40b2fd36ca7e1ffc355e62625c9df09c", "size": 2314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/graph/example/topo-sort1.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/graph/example/topo-sort1.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/libs/graph/example/topo-sort1.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5373134328, "max_line_length": 74, "alphanum_fraction": 0.6274848747, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5026068612059429}}
{"text": "// Unit test for the ConicFit class\n// Author: Philipp Allgeuer <pallgeuer@ais.uni-bonn.de>\n\n// Includes\n#include <rc_utils/conicfit.h>\n#include <Eigen/Geometry>\n#include <gtest/gtest.h>\n\n// Namespaces\nusing namespace rc_utils;\n\n// Defines\n#define TOL_HIGH 1e-14\n#define TOL_MED  1e-12\n#define TOL_LOW  1e-10\n\n//\n// Helper functions\n//\n\n// Generate 3D data from 2D data by adding z values of a given mean\nvoid gen3DFrom2D(ConicFit::Points3D& PP, const ConicFit::Points2D& P, double Z)\n{\n\t// Retrieve the size\n\tsize_t N = P.size();\n\t\n\t// Clear the output vector\n\tPP.clear();\n\t\n\t// If size is small then just write the constant z value in\n\tif(N < 3)\n\t{\n\t\tfor(size_t i = 0; i < N; i++)\n\t\t\tPP.push_back(Eigen::Vector3d(P[i].x(), P[i].y(), Z));\n\t\treturn;\n\t}\n\t\n\t// If larger then generate some more interesting data\n\tdouble Nm = 0.5*(N - 1);\n\tfor(size_t i = 0; i < N; i++)\n\t\tPP.push_back(Eigen::Vector3d(P[i].x(), P[i].y(), Z + (0.5*Z + 1.0)*(i - Nm)));\n}\n\n// Generate random weights within a particular interval\nvoid genWeights(ConicFit::Weights& W, size_t N, double minW, double maxW)\n{\n\t// Generate the required weights\n\tW.resize(N);\n\tfor(size_t i = 0; i < N; i++)\n\t\tW[i] = minW + drand48()*(maxW - minW);\n}\n\n// Generate random weights within a particular interval\nvoid genWeights(ConicFit::WeightedPoints2D& WP, double minW, double maxW)\n{\n\t// Generate the required weights\n\tsize_t N = WP.size();\n\tfor(size_t i = 0; i < N; i++)\n\t\tWP[i].z() = minW + drand48()*(maxW - minW);\n}\n\n// Merge a set of weighted points from a set of weights and a set of points\nvoid mergeWeights(ConicFit::WeightedPoints2D& WP, const ConicFit::Points2D& P, const ConicFit::Weights& W)\n{\n\t// Merge the two sets together\n\tsize_t N = std::min(P.size(), W.size());\n\tWP.resize(N);\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tWP[i].head<2>() = P[i];\n\t\tWP[i].z() = W[i];\n\t}\n}\n\n//\n// Test functions\n//\n\n// Test circle fitting\nTEST(ConicFitTest, testFitCircle)\n{\n\t// Declare variables\n\tEigen::Vector2d FC1, FC2, FC3, FC4;\n\tEigen::Vector3d FCC1, FCC2, FCC3, FCC4;\n\tdouble FR1, FR2, FR3, FR4;\n\t\n\t// Generate circular test data\n\tEigen::Vector2d C1(0.6, -0.8), C2(21312.0, -934511.0), C3(0.0, 0.0), C4(-5.6, 6123.0);\n\tdouble R1 = 1.0, R2 = 4.2, R3 = 0.0, R4 = 17.0;\n\tConicFit::Points2D P1, P2, P3, P4;\n\tConicFit::genCircleData(P1, 130, C1, R1);\n\tConicFit::genCircleData(P2, 50, C2, R2);\n\tConicFit::genCircleData(P3, 90, C3, R3);\n\tConicFit::genCircleData(P4, 2000, C4, R4);\n\tdouble Z1 = 0.3, Z2 = 312.0, Z3 = 0.0, Z4 = -93.0;\n\tEigen::Vector3d CC1(C1.x(), C1.y(), Z1), CC2(C2.x(), C2.y(), Z2), CC3(C3.x(), C3.y(), Z3), CC4(C4.x(), C4.y(), Z4);\n\tConicFit::Points3D PP1, PP2, PP3, PP4;\n\tgen3DFrom2D(PP1, P1, Z1);\n\tgen3DFrom2D(PP2, P2, Z2);\n\tgen3DFrom2D(PP3, P3, Z3);\n\tgen3DFrom2D(PP4, P4, Z4);\n\t\n\t// Sanity check the fitting errors of the generated data\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(P1, C1, R1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(P2, C2, R2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(P3, C3, R3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(P4, C4, R4), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(PP1, CC1, R1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(PP2, CC2, R2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(PP3, CC3, R3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(PP4, CC4, R4), TOL_HIGH);\n\t\n\t// Perform circle fitting 2D\n\tFC1.setZero(); FC2.setZero(); FC3.setZero(); FC4.setZero();\n\tFR1 = FR2 = FR3 = FR4 = 0.0;\n\tConicFit::fitCircle(P1, FC1, FR1);\n\tConicFit::fitCircle(P2, FC2, FR2);\n\tConicFit::fitCircle(P3, FC3, FR3);\n\tConicFit::fitCircle(P4, FC4, FR4);\n\t\n\t// Check circle fitting 2D\n\tEXPECT_NEAR(C1.x(), FC1.x(), TOL_HIGH);\n\tEXPECT_NEAR(C1.y(), FC1.y(), TOL_HIGH);\n\tEXPECT_NEAR(R1, FR1, TOL_HIGH);\n\tEXPECT_NEAR(C2.x(), FC2.x(), TOL_HIGH);\n\tEXPECT_NEAR(C2.y(), FC2.y(), TOL_HIGH);\n\tEXPECT_NEAR(R2, FR2, TOL_LOW); // ULP size of C2\n\tEXPECT_NEAR(C3.x(), FC3.x(), TOL_HIGH);\n\tEXPECT_NEAR(C3.y(), FC3.y(), TOL_HIGH);\n\tEXPECT_NEAR(R3, FR3, TOL_HIGH);\n\tEXPECT_NEAR(C4.x(), FC4.x(), TOL_HIGH);\n\tEXPECT_NEAR(C4.y(), FC4.y(), TOL_HIGH);\n\tEXPECT_NEAR(R4, FR4, TOL_HIGH);\n\t\n\t// Check fitting errors 2D\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(P1, FC1, FR1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(P2, FC2, FR2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(P3, FC3, FR3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(P4, FC4, FR4), TOL_HIGH);\n\t\n\t// Perform circle fitting 3D\n\tFCC1.setZero(); FCC2.setZero(); FCC3.setZero(); FCC4.setZero();\n\tFR1 = FR2 = FR3 = FR4 = 0.0;\n\tConicFit::fitCircle(PP1, FCC1, FR1);\n\tConicFit::fitCircle(PP2, FCC2, FR2);\n\tConicFit::fitCircle(PP3, FCC3, FR3);\n\tConicFit::fitCircle(PP4, FCC4, FR4);\n\t\n\t// Check circle fitting 3D\n\tEXPECT_NEAR(CC1.x(), FCC1.x(), TOL_HIGH);\n\tEXPECT_NEAR(CC1.y(), FCC1.y(), TOL_HIGH);\n\tEXPECT_NEAR(CC1.z(), FCC1.z(), TOL_HIGH);\n\tEXPECT_NEAR(R1, FR1, TOL_HIGH);\n\tEXPECT_NEAR(CC2.x(), FCC2.x(), TOL_HIGH);\n\tEXPECT_NEAR(CC2.y(), FCC2.y(), TOL_HIGH);\n\tEXPECT_NEAR(CC2.z(), FCC2.z(), TOL_HIGH);\n\tEXPECT_NEAR(R2, FR2, TOL_LOW); // ULP size of CC2\n\tEXPECT_NEAR(CC3.x(), FCC3.x(), TOL_HIGH);\n\tEXPECT_NEAR(CC3.y(), FCC3.y(), TOL_HIGH);\n\tEXPECT_NEAR(CC3.z(), FCC3.z(), TOL_HIGH);\n\tEXPECT_NEAR(R3, FR3, TOL_HIGH);\n\tEXPECT_NEAR(CC4.x(), FCC4.x(), TOL_HIGH);\n\tEXPECT_NEAR(CC4.y(), FCC4.y(), TOL_HIGH);\n\tEXPECT_NEAR(CC4.z(), FCC4.z(), TOL_HIGH);\n\tEXPECT_NEAR(R4, FR4, TOL_HIGH);\n\t\n\t// Check fitting errors 3D\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(PP1, FCC1, FR1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(PP2, FCC2, FR2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(PP3, FCC3, FR3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(PP4, FCC4, FR4), TOL_HIGH);\n\t\n\t// Perform circle fitting 2D with a known centre\n\tFR1 = FR2 = FR3 = FR4 = 0.0;\n\tConicFit::fitCircleCentred(P1, C1, FR1);\n\tConicFit::fitCircleCentred(P2, C2, FR2);\n\tConicFit::fitCircleCentred(P3, C3, FR3);\n\tConicFit::fitCircleCentred(P4, C4, FR4);\n\t\n\t// Check circle fitting 2D with a known centre\n\tEXPECT_NEAR(R1, FR1, TOL_HIGH);\n\tEXPECT_NEAR(R2, FR2, TOL_LOW); // ULP size of C2\n\tEXPECT_NEAR(R3, FR3, TOL_HIGH);\n\tEXPECT_NEAR(R4, FR4, TOL_MED); // ULP size of C4\n\t\n\t// Check fitting errors 2D with a known centre\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(P1, C1, FR1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(P2, C2, FR2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(P3, C3, FR3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(P4, C4, FR4), TOL_MED);\n\t\n\t// Perform circle fitting 3D with a known centre\n\tFR1 = FR2 = FR3 = FR4 = 0.0;\n\tConicFit::fitCircleCentred(PP1, CC1, FR1);\n\tConicFit::fitCircleCentred(PP2, CC2, FR2);\n\tConicFit::fitCircleCentred(PP3, CC3, FR3);\n\tConicFit::fitCircleCentred(PP4, CC4, FR4);\n\t\n\t// Check circle fitting 3D with a known centre\n\tEXPECT_NEAR(R1, FR1, TOL_HIGH);\n\tEXPECT_NEAR(R2, FR2, TOL_LOW); // ULP size of C2\n\tEXPECT_NEAR(R3, FR3, TOL_HIGH);\n\tEXPECT_NEAR(R4, FR4, TOL_MED); // ULP size of C4\n\t\n\t// Check fitting errors 3D\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(PP1, CC1, FR1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(PP2, CC2, FR2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(PP3, CC3, FR3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleError(PP4, CC4, FR4), TOL_MED);\n}\n\n// Test circle fitting\nTEST(ConicFitTest, testFitCircleWeighted)\n{\n\t// Declare variables\n\tEigen::Vector2d FC1, FC2, FC3, FC4, FC5;\n\tdouble FR1, FR2, FR3, FR4, FR5;\n\t\n\t// Generate circular test data\n\tEigen::Vector2d C1(0.6, -0.8), C2(21312.0, -934511.0), C3(0.0, 0.0), C4(-5.6, 6123.0), C5(1.7, 0.5);\n\tdouble R1 = 1.0, R2 = 4.2, R3 = 0.0, R4 = 17.0, R5 = 4.0;\n\tConicFit::Points2D P1, P2, P3, P4, P5;\n\tConicFit::genCircleData(P1, 130, C1, R1);\n\tConicFit::genCircleData(P2, 50, C2, R2);\n\tConicFit::genCircleData(P3, 90, C3, R3);\n\tConicFit::genCircleData(P4, 2000, C4, R4);\n\tConicFit::genCircleData(P5, 110, C5, R5);\n\tConicFit::Weights W1, W2, W3, W4, W5;\n\tgenWeights(W1, P1.size(), 0.0, 1.0);\n\tgenWeights(W2, P2.size(), 0.5, 3.0);\n\tgenWeights(W3, P3.size(), -1.0, 1.0);\n\tgenWeights(W4, P4.size(), 100.0, 150.0);\n\tgenWeights(W5, P5.size(), 0.0, 1.0);\n\tfor(size_t i = 0; i < 10; i++)\n\t{\n\t\tP5.push_back(Eigen::Vector2d(100.0, -1000.0));\n\t\tP5.push_back(Eigen::Vector2d(-8293.2, 12949.3));\n\t\tP5.push_back(Eigen::Vector2d(72.2, 96.3));\n\t\tW5.push_back(0.0);\n\t\tW5.push_back(0.0);\n\t\tW5.push_back(0.0);\n\t}\n\tConicFit::WeightedPoints2D WP1, WP2, WP3, WP4, WP5;\n\tmergeWeights(WP1, P1, W1);\n\tmergeWeights(WP2, P2, W2);\n\tmergeWeights(WP3, P3, W3);\n\tmergeWeights(WP4, P4, W4);\n\tmergeWeights(WP5, P5, W5);\n\t\n\t// Sanity check the fitting errors of the generated data\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP1, C1, R1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP2, C2, R2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP3, C3, R3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP4, C4, R4), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP5, C5, R5), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P1, W1, C1, R1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P2, W2, C2, R2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P3, W3, C3, R3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P4, W4, C4, R4), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P5, W5, C5, R5), TOL_HIGH);\n\t\n\t// Perform weighted circle fitting 2D (WP form)\n\tFC1.setZero(); FC2.setZero(); FC3.setZero(); FC4.setZero(); FC5.setZero();\n\tFR1 = FR2 = FR3 = FR4 = FR5 = 0.0;\n\tConicFit::fitCircleWeighted(WP1, FC1, FR1);\n\tConicFit::fitCircleWeighted(WP2, FC2, FR2);\n\tConicFit::fitCircleWeighted(WP3, FC3, FR3);\n\tConicFit::fitCircleWeighted(WP4, FC4, FR4);\n\tConicFit::fitCircleWeighted(WP5, FC5, FR5);\n\t\n\t// Check weighted circle fitting 2D (WP form)\n\tEXPECT_NEAR(C1.x(), FC1.x(), TOL_HIGH);\n\tEXPECT_NEAR(C1.y(), FC1.y(), TOL_HIGH);\n\tEXPECT_NEAR(R1, FR1, TOL_HIGH);\n\tEXPECT_NEAR(C2.x(), FC2.x(), TOL_HIGH);\n\tEXPECT_NEAR(C2.y(), FC2.y(), TOL_HIGH);\n\tEXPECT_NEAR(R2, FR2, TOL_LOW);\n\tEXPECT_NEAR(C3.x(), FC3.x(), TOL_HIGH);\n\tEXPECT_NEAR(C3.y(), FC3.y(), TOL_HIGH);\n\tEXPECT_NEAR(R3, FR3, TOL_HIGH);\n\tEXPECT_NEAR(C4.x(), FC4.x(), TOL_HIGH);\n\tEXPECT_NEAR(C4.y(), FC4.y(), TOL_HIGH);\n\tEXPECT_NEAR(R4, FR4, TOL_HIGH);\n\tEXPECT_NEAR(C5.x(), FC5.x(), TOL_LOW);\n\tEXPECT_NEAR(C5.y(), FC5.y(), TOL_LOW);\n\tEXPECT_NEAR(R5, FR5, TOL_LOW);\n\t\n\t// Check fitting errors 2D (WP form)\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP1, FC1, FR1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP2, FC2, FR2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP3, FC3, FR3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP4, FC4, FR4), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP5, FC5, FR5), TOL_LOW);\n\t\n\t// Perform weighted circle fitting 2D (P+W form)\n\tFC1.setZero(); FC2.setZero(); FC3.setZero(); FC4.setZero(); FC5.setZero();\n\tFR1 = FR2 = FR3 = FR4 = FR5 = 0.0;\n\tConicFit::fitCircleWeighted(P1, W1, FC1, FR1);\n\tConicFit::fitCircleWeighted(P2, W2, FC2, FR2);\n\tConicFit::fitCircleWeighted(P3, W3, FC3, FR3);\n\tConicFit::fitCircleWeighted(P4, W4, FC4, FR4);\n\tConicFit::fitCircleWeighted(P5, W5, FC5, FR5);\n\t\n\t// Check weighted circle fitting 2D (P+W form)\n\tEXPECT_NEAR(C1.x(), FC1.x(), TOL_HIGH);\n\tEXPECT_NEAR(C1.y(), FC1.y(), TOL_HIGH);\n\tEXPECT_NEAR(R1, FR1, TOL_HIGH);\n\tEXPECT_NEAR(C2.x(), FC2.x(), TOL_HIGH);\n\tEXPECT_NEAR(C2.y(), FC2.y(), TOL_HIGH);\n\tEXPECT_NEAR(R2, FR2, TOL_LOW);\n\tEXPECT_NEAR(C3.x(), FC3.x(), TOL_HIGH);\n\tEXPECT_NEAR(C3.y(), FC3.y(), TOL_HIGH);\n\tEXPECT_NEAR(R3, FR3, TOL_HIGH);\n\tEXPECT_NEAR(C4.x(), FC4.x(), TOL_HIGH);\n\tEXPECT_NEAR(C4.y(), FC4.y(), TOL_HIGH);\n\tEXPECT_NEAR(R4, FR4, TOL_HIGH);\n\tEXPECT_NEAR(C5.x(), FC5.x(), TOL_LOW);\n\tEXPECT_NEAR(C5.y(), FC5.y(), TOL_LOW);\n\tEXPECT_NEAR(R5, FR5, TOL_LOW);\n\t\n\t// Check fitting errors 2D (P+W form)\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P1, W1, FC1, FR1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P2, W2, FC2, FR2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P3, W3, FC3, FR3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P4, W4, FC4, FR4), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P5, W5, FC5, FR5), TOL_LOW);\n\t\n\t// Perform weighted circle fitting 2D with a known centre (WP form)\n\tFR1 = FR2 = FR3 = FR4 = FR5 = 0.0;\n\tConicFit::fitCircleCentredWeighted(WP1, C1, FR1);\n\tConicFit::fitCircleCentredWeighted(WP2, C2, FR2);\n\tConicFit::fitCircleCentredWeighted(WP3, C3, FR3);\n\tConicFit::fitCircleCentredWeighted(WP4, C4, FR4);\n\tConicFit::fitCircleCentredWeighted(WP5, C5, FR5);\n\t\n\t// Check weighted circle fitting 2D with a known centre (WP form)\n\tEXPECT_NEAR(R1, FR1, TOL_HIGH);\n\tEXPECT_NEAR(R2, FR2, TOL_LOW);\n\tEXPECT_NEAR(R3, FR3, TOL_HIGH);\n\tEXPECT_NEAR(R4, FR4, TOL_HIGH);\n\tEXPECT_NEAR(R5, FR5, TOL_HIGH);\n\t\n\t// Check fitting errors 2D with a known centre (WP form)\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP1, C1, FR1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP2, C2, FR2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP3, C3, FR3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP4, C4, FR4), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(WP5, C5, FR5), TOL_HIGH);\n\t\n\t// Perform weighted circle fitting 2D with a known centre (P+W form)\n\tFR1 = FR2 = FR3 = FR4 = FR5 = 0.0;\n\tConicFit::fitCircleCentredWeighted(P1, W1, C1, FR1);\n\tConicFit::fitCircleCentredWeighted(P2, W2, C2, FR2);\n\tConicFit::fitCircleCentredWeighted(P3, W3, C3, FR3);\n\tConicFit::fitCircleCentredWeighted(P4, W4, C4, FR4);\n\tConicFit::fitCircleCentredWeighted(P5, W5, C5, FR5);\n\t\n\t// Check weighted circle fitting 2D with a known centre (P+W form)\n\tEXPECT_NEAR(R1, FR1, TOL_HIGH);\n\tEXPECT_NEAR(R2, FR2, TOL_LOW);\n\tEXPECT_NEAR(R3, FR3, TOL_HIGH);\n\tEXPECT_NEAR(R4, FR4, TOL_HIGH);\n\tEXPECT_NEAR(R5, FR5, TOL_HIGH);\n\t\n\t// Check fitting errors 2D with a known centre (P+W form)\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P1, W1, C1, FR1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P2, W2, C2, FR2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P3, W3, C3, FR3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P4, W4, C4, FR4), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitCircleErrorWeighted(P5, W5, C5, FR5), TOL_HIGH);\n}\n\n// Test ellipse fitting\nTEST(ConicFitTest, testFitEllipse)\n{\n\t// Declare variables\n\tEigen::Vector2d FC1, FC2, FC3, FC4;\n\tEigen::Vector3d FCC1, FCC2, FCC3, FCC4;\n\tEigen::Matrix2d FA1, FA2, FA3, FA4;\n\t\n\t// Generate elliptical test data\n\tEigen::Vector2d C1(0.6, -0.8), C2(21312.0, -934511.0), C3(0.0, 0.0), C4(-5.6, 6123.0);\n\tEigen::Vector2d R1(1.0, 1.0), R2(4.2, 2.5), R3(0.005, 0.4), R4(17.0, 31.2);\n\tdouble Ang1 = 0.91, Ang2 = 2.12, Ang3 = 1.41, Ang4 = 5.23;\n\tConicFit::Points2D P1, P2, P3, P4;\n\tConicFit::genEllipseData(P1, 130, C1, R1, Ang1);\n\tConicFit::genEllipseData(P2, 50, C2, R2, Ang2);\n\tConicFit::genEllipseData(P3, 90, C3, R3, Ang3);\n\tConicFit::genEllipseData(P4, 2000, C4, R4, Ang4);\n\tdouble Z1 = 0.3, Z2 = 312.0, Z3 = 0.0, Z4 = -93.0;\n\tEigen::Vector3d CC1(C1.x(), C1.y(), Z1), CC2(C2.x(), C2.y(), Z2), CC3(C3.x(), C3.y(), Z3), CC4(C4.x(), C4.y(), Z4);\n\tConicFit::Points3D PP1, PP2, PP3, PP4;\n\tgen3DFrom2D(PP1, P1, Z1);\n\tgen3DFrom2D(PP2, P2, Z2);\n\tgen3DFrom2D(PP3, P3, Z3);\n\tgen3DFrom2D(PP4, P4, Z4);\n\t\n\t// Perform ellipse fitting 2D\n\tFC1.setZero(); FC2.setZero(); FC3.setZero(); FC4.setZero();\n\tFA1.setIdentity(); FA2.setIdentity(); FA3.setIdentity(); FA4.setIdentity();\n\tConicFit::fitEllipse(P1, FC1, FA1);\n\tConicFit::fitEllipse(P2, FC2, FA2);\n\tConicFit::fitEllipse(P3, FC3, FA3);\n\tConicFit::fitEllipse(P4, FC4, FA4);\n\t\n\t// Check ellipse fitting 2D\n\tEXPECT_NEAR(0.0, (FC1 - C1).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FC2 - C2).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FC3 - C3).norm(), TOL_MED);\n\tEXPECT_NEAR(0.0, (FC4 - C4).norm(), TOL_MED);\n\tfor(size_t i = 0; i < P1.size(); i++)\n\t{\n\t\tEigen::Vector2d v = P1[i] - FC1;\n\t\tdouble err = v.transpose() * FA1 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_HIGH);\n\t}\n\tfor(size_t i = 0; i < P2.size(); i++)\n\t{\n\t\tEigen::Vector2d v = P2[i] - FC2;\n\t\tdouble err = v.transpose() * FA2 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_LOW);\n\t}\n\tfor(size_t i = 0; i < P3.size(); i++)\n\t{\n\t\tEigen::Vector2d v = P3[i] - FC3;\n\t\tdouble err = v.transpose() * FA3 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_LOW);\n\t}\n\tfor(size_t i = 0; i < P4.size(); i++)\n\t{\n\t\tEigen::Vector2d v = P4[i] - FC4;\n\t\tdouble err = v.transpose() * FA4 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_MED);\n\t}\n\t\n\t// Check fitting errors 2D\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(P1, C1, FA1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(P2, C2, FA2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(P3, C3, FA3), TOL_MED);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(P4, C4, FA4), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(P1, FC1, FA1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(P2, FC2, FA2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(P3, FC3, FA3), TOL_MED);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(P4, FC4, FA4), TOL_HIGH);\n\t\n\t// Perform ellipse fitting 2D with a known centre\n\tFA1.setIdentity(); FA2.setIdentity(); FA3.setIdentity(); FA4.setIdentity();\n\tConicFit::fitEllipseCentred(P1, C1, FA1);\n\tConicFit::fitEllipseCentred(P2, C2, FA2);\n\tConicFit::fitEllipseCentred(P3, C3, FA3);\n\tConicFit::fitEllipseCentred(P4, C4, FA4);\n\t\n\t// Check ellipse fitting 2D with a known centre\n\tfor(size_t i = 0; i < P1.size(); i++)\n\t{\n\t\tEigen::Vector2d v = P1[i] - C1;\n\t\tdouble err = v.transpose() * FA1 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_HIGH);\n\t}\n\tfor(size_t i = 0; i < P2.size(); i++)\n\t{\n\t\tEigen::Vector2d v = P2[i] - C2;\n\t\tdouble err = v.transpose() * FA2 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_LOW);\n\t}\n\tfor(size_t i = 0; i < P3.size(); i++)\n\t{\n\t\tEigen::Vector2d v = P3[i] - C3;\n\t\tdouble err = v.transpose() * FA3 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_LOW);\n\t}\n\tfor(size_t i = 0; i < P4.size(); i++)\n\t{\n\t\tEigen::Vector2d v = P4[i] - C4;\n\t\tdouble err = v.transpose() * FA4 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_MED);\n\t}\n\t\n\t// Check fitting errors 2D with a known centre\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(P1, C1, FA1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(P2, C2, FA2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(P3, C3, FA3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(P4, C4, FA4), TOL_HIGH);\n\t\n\t// Perform ellipse fitting 3D\n\tFCC1.setZero(); FCC2.setZero(); FCC3.setZero(); FCC4.setZero();\n\tFA1.setIdentity(); FA2.setIdentity(); FA3.setIdentity(); FA4.setIdentity();\n\tConicFit::fitEllipse(PP1, FCC1, FA1);\n\tConicFit::fitEllipse(PP2, FCC2, FA2);\n\tConicFit::fitEllipse(PP3, FCC3, FA3);\n\tConicFit::fitEllipse(PP4, FCC4, FA4);\n\t\n\t// Check ellipse fitting 3D\n\tEXPECT_NEAR(0.0, (FCC1 - CC1).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FCC2 - CC2).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FCC3 - CC3).norm(), TOL_MED);\n\tEXPECT_NEAR(0.0, (FCC4 - CC4).norm(), TOL_MED);\n\tfor(size_t i = 0; i < PP1.size(); i++)\n\t{\n\t\tEigen::Vector2d v = (PP1[i] - FCC1).head<2>();\n\t\tdouble err = v.transpose() * FA1 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_HIGH);\n\t}\n\tfor(size_t i = 0; i < PP2.size(); i++)\n\t{\n\t\tEigen::Vector2d v = (PP2[i] - FCC2).head<2>();\n\t\tdouble err = v.transpose() * FA2 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_LOW);\n\t}\n\tfor(size_t i = 0; i < PP3.size(); i++)\n\t{\n\t\tEigen::Vector2d v = (PP3[i] - FCC3).head<2>();\n\t\tdouble err = v.transpose() * FA3 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_LOW);\n\t}\n\tfor(size_t i = 0; i < PP4.size(); i++)\n\t{\n\t\tEigen::Vector2d v = (PP4[i] - FCC4).head<2>();\n\t\tdouble err = v.transpose() * FA4 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_MED);\n\t}\n\t\n\t// Check fitting errors 3D\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(PP1, CC1, FA1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(PP2, CC2, FA2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(PP3, CC3, FA3), TOL_MED);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(PP4, CC4, FA4), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(PP1, FCC1, FA1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(PP2, FCC2, FA2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(PP3, FCC3, FA3), TOL_MED);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(PP4, FCC4, FA4), TOL_HIGH);\n\t\n\t// Perform ellipse fitting 3D with a known centre\n\tFA1.setIdentity(); FA2.setIdentity(); FA3.setIdentity(); FA4.setIdentity();\n\tConicFit::fitEllipseCentred(PP1, CC1, FA1);\n\tConicFit::fitEllipseCentred(PP2, CC2, FA2);\n\tConicFit::fitEllipseCentred(PP3, CC3, FA3);\n\tConicFit::fitEllipseCentred(PP4, CC4, FA4);\n\t\n\t// Check ellipse fitting 3D with a known centre\n\tfor(size_t i = 0; i < PP1.size(); i++)\n\t{\n\t\tEigen::Vector2d v = (PP1[i] - CC1).head<2>();\n\t\tdouble err = v.transpose() * FA1 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_HIGH);\n\t}\n\tfor(size_t i = 0; i < PP2.size(); i++)\n\t{\n\t\tEigen::Vector2d v = (PP2[i] - CC2).head<2>();\n\t\tdouble err = v.transpose() * FA2 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_LOW);\n\t}\n\tfor(size_t i = 0; i < PP3.size(); i++)\n\t{\n\t\tEigen::Vector2d v = (PP3[i] - CC3).head<2>();\n\t\tdouble err = v.transpose() * FA3 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_LOW);\n\t}\n\tfor(size_t i = 0; i < PP4.size(); i++)\n\t{\n\t\tEigen::Vector2d v = (PP4[i] - CC4).head<2>();\n\t\tdouble err = v.transpose() * FA4 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_MED);\n\t}\n\t\n\t// Check fitting errors 3D with a known centre\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(PP1, CC1, FA1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(PP2, CC2, FA2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(PP3, CC3, FA3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseErrorCoeff(PP4, CC4, FA4), TOL_HIGH);\n\t\n\t// Convert the fitted coefficient matrices to rotation matrices and radii\n\tEigen::Matrix2d FQ1, FQ2, FQ3, FQ4;\n\tEigen::Vector2d FR1, FR2, FR3, FR4;\n\tdouble FAng1, FAng2, FAng3, FAng4;\n\tASSERT_TRUE(ConicFit::ellipseMatrixToAxes(FA1, FQ1, FR1, FAng1));\n\tASSERT_TRUE(ConicFit::ellipseMatrixToAxes(FA2, FQ2, FR2, FAng2));\n\tASSERT_TRUE(ConicFit::ellipseMatrixToAxes(FA3, FQ3, FR3, FAng3));\n\tASSERT_TRUE(ConicFit::ellipseMatrixToAxes(FA4, FQ4, FR4, FAng4));\n\t\n\t// Check the rotation matrices and radii\n\tdouble cFAng1 = cos(FAng1), sFAng1 = sin(FAng1);\n\tdouble cFAng2 = cos(FAng2), sFAng2 = sin(FAng2);\n\tdouble cFAng3 = cos(FAng3), sFAng3 = sin(FAng3);\n\tdouble cFAng4 = cos(FAng4), sFAng4 = sin(FAng4);\n\tEigen::Vector2d lambda1(1.0/(FR1.x()*FR1.x()), 1.0/(FR1.y()*FR1.y()));\n\tEigen::Vector2d lambda2(1.0/(FR2.x()*FR2.x()), 1.0/(FR2.y()*FR2.y()));\n\tEigen::Vector2d lambda3(1.0/(FR3.x()*FR3.x()), 1.0/(FR3.y()*FR3.y()));\n\tEigen::Vector2d lambda4(1.0/(FR4.x()*FR4.x()), 1.0/(FR4.y()*FR4.y()));\n\tEXPECT_NEAR(0.0, (FQ1 * lambda1.asDiagonal() * FQ1.transpose() - FA1).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ2 * lambda2.asDiagonal() * FQ2.transpose() - FA2).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ3 * lambda3.asDiagonal() * FQ3.transpose() - FA3).norm(), TOL_LOW);\n\tEXPECT_NEAR(0.0, (FQ4 * lambda4.asDiagonal() * FQ4.transpose() - FA4).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ1 - (Eigen::Matrix2d() << cFAng1, -sFAng1, sFAng1, cFAng1).finished()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ2 - (Eigen::Matrix2d() << cFAng2, -sFAng2, sFAng2, cFAng2).finished()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ3 - (Eigen::Matrix2d() << cFAng3, -sFAng3, sFAng3, cFAng3).finished()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ4 - (Eigen::Matrix2d() << cFAng4, -sFAng4, sFAng4, cFAng4).finished()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ1.inverse() - FQ1.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ2.inverse() - FQ2.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ3.inverse() - FQ3.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ4.inverse() - FQ4.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(1.0, FQ1.determinant(), TOL_HIGH);\n\tEXPECT_NEAR(1.0, FQ2.determinant(), TOL_HIGH);\n\tEXPECT_NEAR(1.0, FQ3.determinant(), TOL_HIGH);\n\tEXPECT_NEAR(1.0, FQ4.determinant(), TOL_HIGH);\n\tEXPECT_GT(FR1.x(), 0.0);\n\tEXPECT_GT(FR1.y(), 0.0);\n\tEXPECT_GT(FR2.x(), 0.0);\n\tEXPECT_GT(FR2.y(), 0.0);\n\tEXPECT_GT(FR3.x(), 0.0);\n\tEXPECT_GT(FR3.y(), 0.0);\n\tEXPECT_GT(FR4.x(), 0.0);\n\tEXPECT_GT(FR4.y(), 0.0);\n\t\n\t// Convert the rotation matrix and radii to a normalisation matrix\n\tEigen::Matrix2d FW1, FW2, FW3, FW4;\n\tASSERT_TRUE(ConicFit::ellipseAxesToTransform(FQ1, FR1, FW1));\n\tASSERT_TRUE(ConicFit::ellipseAxesToTransform(FQ2, FR2, FW2));\n\tASSERT_TRUE(ConicFit::ellipseAxesToTransform(FQ3, FR3, FW3));\n\tASSERT_TRUE(ConicFit::ellipseAxesToTransform(FQ4, FR4, FW4));\n\t\n\t// Check the normalisation matrices\n\tEXPECT_NEAR(0.0, (FW1*FW1 - FA1).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FW2*FW2 - FA2).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FW3*FW3 - FA3).norm(), TOL_LOW);\n\tEXPECT_NEAR(0.0, (FW4*FW4 - FA4).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FW1 - FW1.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FW2 - FW2.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FW3 - FW3.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FW4 - FW4.transpose()).norm(), TOL_HIGH);\n\tfor(size_t i = 1; i <= 2; i++)\n\t{\n\t\tEXPECT_GT(FW1.topLeftCorner(i,i).determinant(), 0.0); // A matrix is positive definite iff all leading principal minors are positive\n\t\tEXPECT_GT(FW2.topLeftCorner(i,i).determinant(), 0.0);\n\t\tEXPECT_GT(FW3.topLeftCorner(i,i).determinant(), 0.0);\n\t\tEXPECT_GT(FW4.topLeftCorner(i,i).determinant(), 0.0);\n\t}\n\t\n\t// Check fitting errors\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseError(P1, FC1, FW1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseError(P2, FC2, FW2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseError(P3, FC3, FW3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseError(P4, FC4, FW4), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseError(PP1, FCC1, FW1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseError(PP2, FCC2, FW2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseError(PP3, FCC3, FW3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipseError(PP4, FCC4, FW4), TOL_HIGH);\n}\n\n// Test sphere fitting\nTEST(ConicFitTest, testFitSphere)\n{\n\t// Declare variables\n\tEigen::Vector3d FC1, FC2, FC3, FC4;\n\tdouble FR1, FR2, FR3, FR4;\n\t\n\t// Generate spherical test data\n\tEigen::Vector3d C1(0.6, -0.8, 0.4), C2(21312.0, -934511.0, -13123.0), C3(0.0, 0.0, 0.0), C4(-5.6, 6123.0, 9.3);\n\tdouble R1 = 1.0, R2 = 4.2, R3 = 0.0, R4 = 17.0;\n\tConicFit::Points3D PP1, PP2, PP3, PP4;\n\tConicFit::genSphereData(PP1, 13, C1, R1);\n\tConicFit::genSphereData(PP2, 15, C2, R2);\n\tConicFit::genSphereData(PP3, 10, C3, R3);\n\tConicFit::genSphereData(PP4, 45, C4, R4);\n\t\n\t// Sanity check the fitting errors of the generated data\n\tEXPECT_NEAR(0.0, ConicFit::fitSphereError(PP1, C1, R1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitSphereError(PP2, C2, R2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitSphereError(PP3, C3, R3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitSphereError(PP4, C4, R4), TOL_HIGH);\n\t\n\t// Perform sphere fitting\n\tFC1.setZero(); FC2.setZero(); FC3.setZero(); FC4.setZero();\n\tFR1 = FR2 = FR3 = FR4 = 0.0;\n\tConicFit::fitSphere(PP1, FC1, FR1);\n\tConicFit::fitSphere(PP2, FC2, FR2);\n\tConicFit::fitSphere(PP3, FC3, FR3);\n\tConicFit::fitSphere(PP4, FC4, FR4);\n\t\n\t// Check sphere fitting\n\tEXPECT_NEAR(C1.x(), FC1.x(), TOL_HIGH);\n\tEXPECT_NEAR(C1.y(), FC1.y(), TOL_HIGH);\n\tEXPECT_NEAR(C1.z(), FC1.z(), TOL_HIGH);\n\tEXPECT_NEAR(R1, FR1, TOL_HIGH);\n\tEXPECT_NEAR(C2.x(), FC2.x(), TOL_HIGH);\n\tEXPECT_NEAR(C2.y(), FC2.y(), TOL_HIGH);\n\tEXPECT_NEAR(C2.z(), FC2.z(), TOL_HIGH);\n\tEXPECT_NEAR(R2, FR2, TOL_LOW); // ULP size of C2\n\tEXPECT_NEAR(C3.x(), FC3.x(), TOL_HIGH);\n\tEXPECT_NEAR(C3.y(), FC3.y(), TOL_HIGH);\n\tEXPECT_NEAR(C3.z(), FC3.z(), TOL_HIGH);\n\tEXPECT_NEAR(R3, FR3, TOL_HIGH);\n\tEXPECT_NEAR(C4.x(), FC4.x(), TOL_MED);\n\tEXPECT_NEAR(C4.y(), FC4.y(), TOL_MED);\n\tEXPECT_NEAR(C4.z(), FC4.z(), TOL_MED);\n\tEXPECT_NEAR(R4, FR4, TOL_MED); // ULP size of C4\n\t\n\t// Check fitting errors\n\tEXPECT_NEAR(0.0, ConicFit::fitSphereError(PP1, FC1, FR1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitSphereError(PP2, FC2, FR2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitSphereError(PP3, FC3, FR3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitSphereError(PP4, FC4, FR4), TOL_HIGH);\n\t\n\t// Perform sphere fitting with a known centre\n\tFR1 = FR2 = FR3 = FR4 = 0.0;\n\tConicFit::fitSphereCentred(PP1, C1, FR1);\n\tConicFit::fitSphereCentred(PP2, C2, FR2);\n\tConicFit::fitSphereCentred(PP3, C3, FR3);\n\tConicFit::fitSphereCentred(PP4, C4, FR4);\n\t\n\t// Check sphere fitting with a known centre\n\tEXPECT_NEAR(R1, FR1, TOL_HIGH);\n\tEXPECT_NEAR(R2, FR2, TOL_LOW); // ULP size of C2\n\tEXPECT_NEAR(R3, FR3, TOL_HIGH);\n\tEXPECT_NEAR(R4, FR4, TOL_MED); // ULP size of C4\n\t\n\t// Check fitting errors with a known centre\n\tEXPECT_NEAR(0.0, ConicFit::fitSphereError(PP1, C1, FR1), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitSphereError(PP2, C2, FR2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitSphereError(PP3, C3, FR3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitSphereError(PP4, C4, FR4), TOL_MED);\n}\n\n// Test ellipsoid fitting\nTEST(ConicFitTest, testFitEllipsoid)\n{\n\t// Declare variables\n\tEigen::Vector3d FC1, FC2, FC3, FC4;\n\tEigen::Matrix3d FA1, FA2, FA3, FA4;\n\t\n\t// Generate ellipsoidal test data\n\tEigen::Vector3d C1(0.6, -0.8, 0.4), C2(21312.0, -934511.0, -13123.0), C3(0.0, 0.0, 0.0), C4(-5.6, 6123.0, 9.3);\n\tEigen::Vector3d R1(0.7, 0.5, 1.3), R2(6.0, 3.0, 4.5), R3(16.0, 3.0, 1.0), R4(3.0, 17.0, 8.0);\n\tEigen::Matrix3d Q1(Eigen::AngleAxisd(0.83, Eigen::Vector3d(1.0, 1.0, 1.0).normalized()));\n\tEigen::Matrix3d Q2(Eigen::AngleAxisd(2.81, Eigen::Vector3d(-0.4, 0.7, 1.0).normalized()));\n\tEigen::Matrix3d Q3(Eigen::AngleAxisd(1.27, Eigen::Vector3d(0.0, 1.0, 2.0).normalized()));\n\tEigen::Matrix3d Q4(Eigen::AngleAxisd(4.93, Eigen::Vector3d(2.0, -1.0, 0.4).normalized()));\n\tConicFit::Points3D PP1, PP2, PP3, PP4;\n\tConicFit::genEllipsoidData(PP1, 13, C1, R1, Q1);\n\tConicFit::genEllipsoidData(PP2, 15, C2, R2, Q2);\n\tConicFit::genEllipsoidData(PP3, 10, C3, R3, Q3);\n\tConicFit::genEllipsoidData(PP4, 45, C4, R4, Q4);\n\t\n\t// Perform ellipsoid fitting\n\tFC1.setZero(); FC2.setZero(); FC3.setZero(); FC4.setZero();\n\tFA1.setIdentity(); FA2.setIdentity(); FA3.setIdentity(); FA4.setIdentity();\n\tConicFit::fitEllipsoid(PP1, FC1, FA1);\n\tConicFit::fitEllipsoid(PP2, FC2, FA2);\n\tConicFit::fitEllipsoid(PP3, FC3, FA3);\n\tConicFit::fitEllipsoid(PP4, FC4, FA4);\n\t\n\t// Check ellipsoid fitting\n\tEXPECT_NEAR(0.0, (FC1 - C1).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FC2 - C2).norm(), TOL_LOW);\n\tEXPECT_NEAR(0.0, (FC3 - C3).norm(), TOL_MED);\n\tEXPECT_NEAR(0.0, (FC4 - C4).norm(), TOL_HIGH);\n\tfor(size_t i = 0; i < PP1.size(); i++)\n\t{\n\t\tEigen::Vector3d v = PP1[i] - FC1;\n\t\tdouble err = v.transpose() * FA1 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_HIGH);\n\t}\n\tfor(size_t i = 0; i < PP2.size(); i++)\n\t{\n\t\tEigen::Vector3d v = PP2[i] - FC2;\n\t\tdouble err = v.transpose() * FA2 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_LOW);\n\t}\n\tfor(size_t i = 0; i < PP3.size(); i++)\n\t{\n\t\tEigen::Vector3d v = PP3[i] - FC3;\n\t\tdouble err = v.transpose() * FA3 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_MED);\n\t}\n\tfor(size_t i = 0; i < PP4.size(); i++)\n\t{\n\t\tEigen::Vector3d v = PP4[i] - FC4;\n\t\tdouble err = v.transpose() * FA4 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_MED);\n\t}\n\t\n\t// Check fitting errors\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidErrorCoeff(PP1, C1, FA1), TOL_MED);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidErrorCoeff(PP2, C2, FA2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidErrorCoeff(PP3, C3, FA3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidErrorCoeff(PP4, C4, FA4), TOL_MED);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidErrorCoeff(PP1, FC1, FA1), TOL_MED);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidErrorCoeff(PP2, FC2, FA2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidErrorCoeff(PP3, FC3, FA3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidErrorCoeff(PP4, FC4, FA4), TOL_MED);\n\t\n\t// Perform ellipsoid fitting with a known centre\n\tFA1.setIdentity(); FA2.setIdentity(); FA3.setIdentity(); FA4.setIdentity();\n\tConicFit::fitEllipsoidCentred(PP1, C1, FA1);\n\tConicFit::fitEllipsoidCentred(PP2, C2, FA2);\n\tConicFit::fitEllipsoidCentred(PP3, C3, FA3);\n\tConicFit::fitEllipsoidCentred(PP4, C4, FA4);\n\t\n\t// Check ellipsoid fitting with a known centre\n\tfor(size_t i = 0; i < PP1.size(); i++)\n\t{\n\t\tEigen::Vector3d v = PP1[i] - C1;\n\t\tdouble err = v.transpose() * FA1 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_HIGH);\n\t}\n\tfor(size_t i = 0; i < PP2.size(); i++)\n\t{\n\t\tEigen::Vector3d v = PP2[i] - C2;\n\t\tdouble err = v.transpose() * FA2 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_LOW);\n\t}\n\tfor(size_t i = 0; i < PP3.size(); i++)\n\t{\n\t\tEigen::Vector3d v = PP3[i] - C3;\n\t\tdouble err = v.transpose() * FA3 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_MED);\n\t}\n\tfor(size_t i = 0; i < PP4.size(); i++)\n\t{\n\t\tEigen::Vector3d v = PP4[i] - C4;\n\t\tdouble err = v.transpose() * FA4 * v - 1.0;\n\t\tEXPECT_NEAR(0.0, err, TOL_MED);\n\t}\n\t\n\t// Check fitting errors with a known centre\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidErrorCoeff(PP1, C1, FA1), TOL_MED);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidErrorCoeff(PP2, C2, FA2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidErrorCoeff(PP3, C3, FA3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidErrorCoeff(PP4, C4, FA4), TOL_MED);\n\t\n\t// Convert the fitted coefficient matrices to rotation matrices and radii\n\tEigen::Matrix3d FQ1, FQ2, FQ3, FQ4;\n\tEigen::Vector3d FR1, FR2, FR3, FR4;\n\tASSERT_TRUE(ConicFit::ellipsoidMatrixToAxes(FA1, FQ1, FR1));\n\tASSERT_TRUE(ConicFit::ellipsoidMatrixToAxes(FA2, FQ2, FR2));\n\tASSERT_TRUE(ConicFit::ellipsoidMatrixToAxes(FA3, FQ3, FR3));\n\tASSERT_TRUE(ConicFit::ellipsoidMatrixToAxes(FA4, FQ4, FR4));\n\t\n\t// Check the rotation matrices and radii\n\tEigen::Vector3d lambda1(1.0/(FR1.x()*FR1.x()), 1.0/(FR1.y()*FR1.y()), 1.0/(FR1.z()*FR1.z()));\n\tEigen::Vector3d lambda2(1.0/(FR2.x()*FR2.x()), 1.0/(FR2.y()*FR2.y()), 1.0/(FR2.z()*FR2.z()));\n\tEigen::Vector3d lambda3(1.0/(FR3.x()*FR3.x()), 1.0/(FR3.y()*FR3.y()), 1.0/(FR3.z()*FR3.z()));\n\tEigen::Vector3d lambda4(1.0/(FR4.x()*FR4.x()), 1.0/(FR4.y()*FR4.y()), 1.0/(FR4.z()*FR4.z()));\n\tEXPECT_NEAR(0.0, (FQ1 * lambda1.asDiagonal() * FQ1.transpose() - FA1).norm(), TOL_MED);\n\tEXPECT_NEAR(0.0, (FQ2 * lambda2.asDiagonal() * FQ2.transpose() - FA2).norm(), TOL_MED);\n\tEXPECT_NEAR(0.0, (FQ3 * lambda3.asDiagonal() * FQ3.transpose() - FA3).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ4 * lambda4.asDiagonal() * FQ4.transpose() - FA4).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ1.inverse() - FQ1.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ2.inverse() - FQ2.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ3.inverse() - FQ3.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FQ4.inverse() - FQ4.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(1.0, FQ1.determinant(), TOL_HIGH);\n\tEXPECT_NEAR(1.0, FQ2.determinant(), TOL_HIGH);\n\tEXPECT_NEAR(1.0, FQ3.determinant(), TOL_HIGH);\n\tEXPECT_NEAR(1.0, FQ4.determinant(), TOL_HIGH);\n\tEXPECT_GT(FR1.x(), 0.0);\n\tEXPECT_GT(FR1.y(), 0.0);\n\tEXPECT_GT(FR1.z(), 0.0);\n\tEXPECT_GT(FR2.x(), 0.0);\n\tEXPECT_GT(FR2.y(), 0.0);\n\tEXPECT_GT(FR2.z(), 0.0);\n\tEXPECT_GT(FR3.x(), 0.0);\n\tEXPECT_GT(FR3.y(), 0.0);\n\tEXPECT_GT(FR3.z(), 0.0);\n\tEXPECT_GT(FR4.x(), 0.0);\n\tEXPECT_GT(FR4.y(), 0.0);\n\tEXPECT_GT(FR4.z(), 0.0);\n\t\n\t// Convert the rotation matrix and radii to a normalisation matrix\n\tEigen::Matrix3d FW1, FW2, FW3, FW4;\n\tASSERT_TRUE(ConicFit::ellipsoidAxesToTransform(FQ1, FR1, FW1));\n\tASSERT_TRUE(ConicFit::ellipsoidAxesToTransform(FQ2, FR2, FW2));\n\tASSERT_TRUE(ConicFit::ellipsoidAxesToTransform(FQ3, FR3, FW3));\n\tASSERT_TRUE(ConicFit::ellipsoidAxesToTransform(FQ4, FR4, FW4));\n\t\n\t// Check the normalisation matrices\n\tEXPECT_NEAR(0.0, (FW1*FW1 - FA1).norm(), TOL_MED);\n\tEXPECT_NEAR(0.0, (FW2*FW2 - FA2).norm(), TOL_MED);\n\tEXPECT_NEAR(0.0, (FW3*FW3 - FA3).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FW4*FW4 - FA4).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FW1 - FW1.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FW2 - FW2.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FW3 - FW3.transpose()).norm(), TOL_HIGH);\n\tEXPECT_NEAR(0.0, (FW4 - FW4.transpose()).norm(), TOL_HIGH);\n\tfor(size_t i = 1; i <= 3; i++)\n\t{\n\t\tEXPECT_GT(FW1.topLeftCorner(i,i).determinant(), 0.0); // A matrix is positive definite iff all leading principal minors are positive\n\t\tEXPECT_GT(FW2.topLeftCorner(i,i).determinant(), 0.0);\n\t\tEXPECT_GT(FW3.topLeftCorner(i,i).determinant(), 0.0);\n\t\tEXPECT_GT(FW4.topLeftCorner(i,i).determinant(), 0.0);\n\t}\n\t\n\t// Check fitting errors\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidError(PP1, C1, FW1), TOL_MED);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidError(PP2, C2, FW2), TOL_LOW);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidError(PP3, C3, FW3), TOL_HIGH);\n\tEXPECT_NEAR(0.0, ConicFit::fitEllipsoidError(PP4, C4, FW4), TOL_MED);\n}\n\n// Test fitting errors\nTEST(ConicFitTest, testFitError)\n{\n\t// Sanity check fitting error for circle\n\tConicFit::Points2D P1;\n\tConicFit::Weights W1;\n\tConicFit::WeightedPoints2D WP1;\n\tEigen::Vector2d C1(0.6, -0.8);\n\tdouble R1 = 0.5, S1 = 1.3;\n\tConicFit::genCircleData(P1, 60, C1, R1*S1);\n\tgenWeights(W1, P1.size(), 0.0, 1.0);\n\tmergeWeights(WP1, P1, W1);\n\tEXPECT_NEAR(fabs(S1 - 1.0), ConicFit::fitCircleError(P1, C1, R1), TOL_HIGH);\n\tEXPECT_NEAR(fabs(S1 - 1.0), ConicFit::fitCircleErrorWeighted(WP1, C1, R1), TOL_HIGH);\n\tEXPECT_NEAR(fabs(S1 - 1.0), ConicFit::fitCircleErrorWeighted(P1, W1, C1, R1), TOL_HIGH);\n\t\n\t// Sanity check fitting error for ellipse\n\tEigen::Vector2d C2(-0.6, 0.8);\n\tEigen::Vector2d R2(3.0, 1.2);\n\tEigen::Matrix2d W2;\n\tdouble Ang2 = 2.19, S2 = 1.7;\n\tConicFit::Points2D P2;\n\tConicFit::genEllipseData(P2, 60, C2, R2*S2, Ang2);\n\tConicFit::ellipseAxesToTransform((Eigen::Matrix2d() << cos(Ang2), -sin(Ang2), sin(Ang2), cos(Ang2)).finished(), R2, W2);\n\tEXPECT_NEAR(fabs(S2 - 1.0), ConicFit::fitEllipseError(P2, C2, W2), TOL_HIGH);\n\t\n\t// Sanity check fitting error for sphere\n\tConicFit::Points3D PP1;\n\tEigen::Vector3d CC1(0.6, -0.8, 0.4);\n\tdouble RR1 = 7.5, SS1 = 0.6;\n\tConicFit::genSphereData(PP1, 20, CC1, RR1*SS1);\n\tEXPECT_NEAR(fabs(SS1 - 1.0), ConicFit::fitSphereError(PP1, CC1, RR1), TOL_HIGH);\n\t\n\t// Sanity check fitting error for ellipsoid\n\tEigen::Vector3d CC2(1.4, -4.3, -0.5);\n\tEigen::Vector3d RR2(3.3, 1.8, 0.7);\n\tEigen::Matrix3d QQ2(Eigen::AngleAxisd(2.39, Eigen::Vector3d(-0.2, 0.8, 0.4).normalized()));\n\tEigen::Matrix3d WW2;\n\tdouble SS2 = 0.84;\n\tConicFit::Points3D PP2;\n\tConicFit::genEllipsoidData(PP2, 15, CC2, RR2*SS2, QQ2);\n\tConicFit::ellipsoidAxesToTransform(QQ2, RR2, WW2);\n\tEXPECT_NEAR(fabs(SS2 - 1.0), ConicFit::fitEllipsoidError(PP2, CC2, WW2), TOL_HIGH);\n}\n\n// Main function\nint main(int argc, char **argv)\n{\n\t// Ensure repeatability of random number generation\n\tsrand48(0xF9EB283A);\n\t\n\t// Run all the tests\n\t::testing::InitGoogleTest(&argc, argv);\n\treturn RUN_ALL_TESTS();\n}\n// EOF", "meta": {"hexsha": "8a6de5c8d6ab394fa325fd00d2ff394b2e421b75", "size": 38785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nimbro_robotcontrol/util/rc_utils/test/test_conicfit.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/test/test_conicfit.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/test/test_conicfit.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": 40.612565445, "max_line_length": 134, "alphanum_fraction": 0.6785612995, "num_tokens": 15360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5026068608196707}}
{"text": "//\r\n// $Id: InterpolatorTest.cpp 8434 2012-03-29 16:09:22Z chambm $ \r\n//\r\n// Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>\r\n// Copyright 2011 Vanderbilt University\r\n//\r\n// Licensed under the Code Project Open License, Version 1.02 (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.codeproject.com/info/cpol10.aspx\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 \"pwiz/utility/misc/unit.hpp\"\r\n#include \"pwiz/utility/misc/Std.hpp\"\r\n#include \"Interpolator.hpp\"\r\n#include <boost/assign.hpp>\r\n\r\nusing namespace pwiz::util;\r\nusing namespace freicore;\r\nusing namespace boost::assign;\r\n\r\nint main()\r\n{\r\n    try\r\n    {\r\n        {\r\n            vector<double> x; x += 1, 2, 3,  4,  6,  7,  8, 9;\r\n            vector<double> y; y += 1, 8, 27, 64, 64, 27, 8, 1;\r\n            Interpolator test(x, y);\r\n\r\n            unit_assert_equal(1, test.interpolate(x, y, 1), 1e-6);\r\n            unit_assert_equal(8, test.interpolate(x, y, 2), 1e-6);\r\n            unit_assert_equal(27, test.interpolate(x, y, 3), 1e-6);\r\n            unit_assert_equal(64, test.interpolate(x, y, 4), 1e-6);\r\n            //unit_assert_equal(64, test.interpolate(x, y, 5), 1e-6);\r\n            unit_assert_equal(64, test.interpolate(x, y, 6), 1e-6);\r\n            unit_assert_equal(27, test.interpolate(x, y, 7), 1e-6);\r\n            unit_assert_equal(1, test.interpolate(x, y, 9), 1e-6);\r\n\r\n            test.resample(x, y);\r\n            unit_assert_operator_equal(18, x.size() + y.size());\r\n            unit_assert_equal(1, x[0], 1e-6);\r\n            unit_assert_equal(2, x[1], 1e-6);\r\n            unit_assert_equal(8, x[7], 1e-6);\r\n            unit_assert_equal(9, x[8], 1e-6);\r\n\r\n            unit_assert_equal(1, y[0], 1e-6);\r\n            unit_assert_equal(8, y[1], 1e-6);\r\n            unit_assert_equal(27, y[2], 1e-6);\r\n            unit_assert_equal(64, y[3], 1e-6);\r\n            //unit_assert_equal(64, y[4], 1e-6);\r\n            unit_assert_equal(64, y[5], 1e-6);\r\n            unit_assert_equal(27, y[6], 1e-6);\r\n            //unit_assert_equal(8, y[7], 1e-6);\r\n            unit_assert_equal(1, y[8], 1e-6);\r\n        }\r\n\r\n        {\r\n            vector<double> x; x += 1, 3,  4,  5,  6,  7,  9;\r\n            vector<double> y; y += 1, 27, 64, 64, 64, 27, 1;\r\n            Interpolator test(x, y);\r\n\r\n            unit_assert_operator_equal(1, test.interpolate(x, y, 1));\r\n            unit_assert_operator_equal(8, test.interpolate(x, y, 2));\r\n            unit_assert_operator_equal(64, test.interpolate(x, y, 5));\r\n            unit_assert_operator_equal(27, test.interpolate(x, y, 7));\r\n            unit_assert_operator_equal(8, test.interpolate(x, y, 8));\r\n            unit_assert_operator_equal(1, test.interpolate(x, y, 9));\r\n\r\n            test.resample(x, y);\r\n            unit_assert_operator_equal(18, x.size() + y.size());\r\n            unit_assert_operator_equal(1, x[0]);\r\n            unit_assert_operator_equal(2, x[1]);\r\n            unit_assert_operator_equal(8, x[7]);\r\n            unit_assert_operator_equal(9, x[8]);\r\n\r\n            unit_assert_operator_equal(1, y[0]);\r\n            unit_assert_operator_equal(8, y[1]);\r\n            unit_assert_operator_equal(27, y[2]);\r\n            unit_assert_operator_equal(64, y[3]);\r\n            unit_assert_operator_equal(64, y[4]);\r\n            unit_assert_operator_equal(64, y[5]);\r\n            unit_assert_operator_equal(27, y[6]);\r\n            unit_assert_operator_equal(8, y[7]);\r\n            unit_assert_operator_equal(1, y[8]);\r\n        }\r\n    }\r\n    catch (exception& e)\r\n    {\r\n        cerr << e.what() << endl;\r\n        return 1;\r\n    }\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "369d47461f3ce09d3c9d96a43281a5fbefd90d77", "size": 3998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz_tools/Bumbershoot/quameter/InterpolatorTest.cpp", "max_stars_repo_name": "shze/pwizard-deb", "max_stars_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-12-28T21:24:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-18T03:52:05.000Z", "max_issues_repo_path": "pwiz_tools/Bumbershoot/quameter/InterpolatorTest.cpp", "max_issues_repo_name": "shze/pwizard-deb", "max_issues_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "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_tools/Bumbershoot/quameter/InterpolatorTest.cpp", "max_forks_repo_name": "shze/pwizard-deb", "max_forks_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "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.4423076923, "max_line_length": 80, "alphanum_fraction": 0.5725362681, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5026068608196705}}
{"text": "//  (C) Copyright John Maddock 2005.\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#ifdef TEST_STD_HEADERS\r\n#include <complex>\r\n#else\r\n#include <boost/tr1/complex.hpp>\r\n#endif\r\n\r\n#include <boost/test/test_tools.hpp>\r\n#include <boost/test/included/test_exec_monitor.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/type_traits/is_floating_point.hpp>\r\n#include <boost/mpl/if.hpp>\r\n#include <boost/static_assert.hpp>\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\n#ifndef VERBOSE\r\n#undef BOOST_MESSAGE\r\n#define BOOST_MESSAGE(x)\r\n#endif\r\n\r\n//\r\n// This test verifies that the complex-algorithms that are\r\n// overloaded for scalar types produce the same result as casting\r\n// the argument to a complex type, and calling the complex version\r\n// of the algorithm.  Relative errors must be within 2e in order for \r\n// the tests to pass.\r\n//\r\n\r\ntemplate <class T, class U>\r\nvoid do_check(const T& t, const U& u)\r\n{\r\n   static const T two = 2;\r\n   static const T factor = std::pow(two, 1-std::numeric_limits<T>::digits) * 200;\r\n   BOOST_STATIC_ASSERT((::boost::is_same<T,U>::value));\r\n   BOOST_CHECK_CLOSE(t, u, factor);\r\n}\r\n\r\ntemplate <class T, class U>\r\nvoid do_check(const std::complex<T>& t, const std::complex<U>& u)\r\n{\r\n   BOOST_STATIC_ASSERT((::boost::is_same<T,U>::value));\r\n   do_check(t.real(), u.real());\r\n   do_check(t.imag(), u.imag());\r\n}\r\n\r\ntemplate <class T>\r\nvoid check_val(const T& val)\r\n{\r\n   typedef typename boost::mpl::if_< boost::is_floating_point<T>, T, double>::type real_type;\r\n   typedef std::complex<real_type> complex_type;\r\n\r\n   real_type rval = static_cast<real_type>(val);\r\n   complex_type cval = rval;\r\n\r\n   if(val)\r\n   {\r\n      std::cout << \"    Testing std::arg.\\n\";\r\n      do_check(std::arg(cval), std::arg(rval));\r\n      do_check(std::arg(cval), std::arg(val));\r\n   }\r\n   std::cout << \"    Testing std::norm.\\n\";\r\n   do_check(std::norm(cval), std::norm(rval));\r\n   do_check(std::norm(cval), std::norm(val));\r\n   std::cout << \"    Testing std::conj.\\n\";\r\n   do_check(std::conj(cval), std::conj(rval));\r\n   do_check(std::conj(cval), std::conj(val));\r\n   std::cout << \"    Testing std::polar.\\n\";\r\n   do_check(std::polar(val), std::polar(rval));\r\n   do_check(std::polar(val, 0), std::polar(rval, 0));\r\n   do_check(std::polar(val, val), std::polar(rval, rval));\r\n   do_check(std::polar(val, rval), std::polar(rval, val));\r\n   std::cout << \"    Testing std::real.\\n\";\r\n   do_check(std::real(cval), std::real(rval));\r\n   do_check(std::real(cval), std::real(val));\r\n   std::cout << \"    Testing std::imaj.\\n\";\r\n   do_check(std::imag(cval), std::imag(rval));\r\n   do_check(std::imag(cval), std::imag(val));\r\n   if(val && !boost::is_floating_point<T>::value)\r\n   {\r\n      //\r\n      // Note that these tests are not run for floating point\r\n      // types as that would only test the std lib vendor's\r\n      // implementation of pow, not our additional overloads.\r\n      // Note that some std lib's do fail these tests, gcc on\r\n      // Darwin is a particularly bad example !\r\n      //\r\n      std::cout << \"    Testing std::pow.\\n\";\r\n      do_check(std::pow(cval, cval), std::pow(cval, val));\r\n      do_check(std::pow(cval, cval), std::pow(cval, rval));\r\n      do_check(std::pow(cval, cval), std::pow(val, cval));\r\n      do_check(std::pow(cval, cval), std::pow(rval, cval));\r\n   }\r\n}\r\n\r\nvoid do_check(double i)\r\n{\r\n   std::cout << \"Checking type double with value \" << i << std::endl;\r\n   check_val(i);\r\n   std::cout << \"Checking type float with value \" << i << std::endl;\r\n   check_val(static_cast<float>(i));\r\n   std::cout << \"Checking type long double with value \" << i << std::endl;\r\n   check_val(static_cast<long double>(i));\r\n}\r\n\r\nvoid do_check(int i)\r\n{\r\n   std::cout << \"Checking type char with value \" << i << std::endl;\r\n   check_val(static_cast<char>(i));\r\n   std::cout << \"Checking type unsigned char with value \" << i << std::endl;\r\n   check_val(static_cast<unsigned char>(i));\r\n   std::cout << \"Checking type signed char with value \" << i << std::endl;\r\n   check_val(static_cast<signed char>(i));\r\n   std::cout << \"Checking type short with value \" << i << std::endl;\r\n   check_val(static_cast<short>(i));\r\n   std::cout << \"Checking type unsigned short with value \" << i << std::endl;\r\n   check_val(static_cast<unsigned short>(i));\r\n   std::cout << \"Checking type int with value \" << i << std::endl;\r\n   check_val(static_cast<int>(i));\r\n   std::cout << \"Checking type unsigned int with value \" << i << std::endl;\r\n   check_val(static_cast<unsigned int>(i));\r\n   std::cout << \"Checking type long with value \" << i << std::endl;\r\n   check_val(static_cast<long>(i));\r\n   std::cout << \"Checking type unsigned long with value \" << i << std::endl;\r\n   check_val(static_cast<unsigned long>(i));\r\n#ifdef BOOST_HAS_LONG_LONG\r\n   std::cout << \"Checking type long long with value \" << i << std::endl;\r\n   check_val(static_cast<long long>(i));\r\n   std::cout << \"Checking type unsigned long long with value \" << i << std::endl;\r\n   check_val(static_cast<unsigned long long>(i));\r\n#elif defined(BOOST_HAS_MS_INT64)\r\n   std::cout << \"Checking type __int64 with value \" << i << std::endl;\r\n   check_val(static_cast<__int64>(i));\r\n   std::cout << \"Checking type unsigned __int64 with value \" << i << std::endl;\r\n   check_val(static_cast<unsigned __int64>(i));\r\n#endif\r\n   do_check(static_cast<double>(i));\r\n}\r\n\r\nint test_main(int, char*[])\r\n{\r\n   do_check(0);\r\n   do_check(0.0);\r\n   do_check(1);\r\n   do_check(1.5);\r\n   do_check(0.5);\r\n   return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "d52951d9ed4dc142fc5319f0a7c42559485e6813", "size": 5682, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/tr1/test/run_complex_overloads.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/tr1/test/run_complex_overloads.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/tr1/test/run_complex_overloads.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 36.4230769231, "max_line_length": 94, "alphanum_fraction": 0.6393875396, "num_tokens": 1524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.5026068563639123}}
{"text": "\n\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <pybind11/stl.h>\n#include <math.h>\n\n\n#include <Eigen/Dense>\n#include <unordered_map>\n#include <vector>\n#include <random>\n\nnamespace py = pybind11;\n\n// POSTERIOR PVAL FOR T \n// Generate posterior pvals selecting a new or existing table\nEigen::VectorXd posterior_t_cpp(Eigen::VectorXd t_j, Eigen::VectorXd n_jt, \n                           Eigen::VectorXd k_jt, Eigen::VectorXd m_k, Eigen::VectorXd fk,\n                           double gamma, double V, double alpha){\n    \n    // Get table specific topic and counts\n    Eigen::VectorXd k_idx = k_jt(t_j);\n    Eigen::VectorXd n_idx = n_jt(t_j);\n    \n    // If t is not new\n    Eigen::VectorXd post_t = n_idx.cwiseProduct(fk(k_idx)); // element-wise product (scalar * vector)\n    \n    // If t is new\n    double post_t_new = m_k.dot(fk) + gamma/V;\n    post_t(0) = post_t_new * alpha / (gamma + m_k.sum());\n    \n    post_t /= post_t.sum(); // Normalize to generate pvals\n    \n    return post_t;\n    \n}\n    \n\n// Conditional density of x_ji given k and all data items except x_j\nEigen::VectorXd fk_cpp(int word, Eigen::MatrixXd  n_kv){\n    \n    Eigen::VectorXd lik = n_kv.row(word).cwiseQuotient(n_kv.colwise().sum()); // element-wise division(vec / scalar)\n    lik[0] = 0; // First should always be zero\n    \n    return lik;\n}\n    \n    \n// POSTERIOR PVAL FOR K  \n// Compute explicit posterior multinomial-dirichlet posterior distribution\nEigen::VectorXd posterior_k_cpp(int tbl, Eigen::VectorXd k_jt, \n                                Eigen::VectorXd n_jt, Eigen::VectorXd topic_idx, Eigen::MatrixXd n_kv,\n                                Eigen::VectorXd m_k, const std::unordered_map<int, int> n_jtw,\n                                double gamma, double V, double beta){\n    \n    // Topic k of table t\n    int k = k_jt(tbl);\n    double cnt_t = n_jt(tbl);\n    double vbeta = V*beta;\n    \n    // Remove all counts associated with topic k in table t, from overall topic counts (n_k)\n    Eigen::VectorXd n_k = n_kv.colwise().sum();\n    n_k(k) -= cnt_t;\n    n_k = n_k(topic_idx);\n    \n    // Initialized k posterior in log-form for simplicity, this computes f_k^{-X_ji} \n    // has Dirichlet-Multinomial form\n    double log_post_k_new = std::log(gamma) + std::lgamma(vbeta) - std::lgamma(vbeta + cnt_t); // for new k\n    \n    // for old ks, needs to loop since it's a vector\n    m_k = m_k(topic_idx);\n    Eigen::VectorXd log_post_k = m_k.array().log();\n    for (int i = 0; i < log_post_k.size() ; i++){\n        log_post_k(i) += std::lgammaf(n_k(i)) - std::lgammaf(n_k(i) + cnt_t);\n    };\n    \n    // Remove individual word counts associated with topic k\n    // add their contributions to k posterior\n    for (auto item : n_jtw){\n        \n        if (item.second == 0) continue; //if word count is 0 skip\n        \n        //For word w, get counts across topics\n        Eigen::VectorXd w_cnt_k = n_kv.row(item.first);\n        \n        // For specific topic k, remove count from associated table t\n        w_cnt_k(k) -= item.second;\n        w_cnt_k = w_cnt_k(topic_idx);\n        w_cnt_k(0) = 1;\n        \n        // Add contributions of individual observations (words) for k new and k old\n        log_post_k_new += std::lgammaf(item.second + beta) - std::lgammaf(beta);\n        \n        for (int j = 0; j < w_cnt_k.size(); j++){\n            log_post_k(j) += std::lgammaf(w_cnt_k(j) + item.second) - std::lgammaf(w_cnt_k(j));\n        \n        };      \n    };\n  \n    // p-val for new k\n    log_post_k(0) = log_post_k_new;\n    \n    // Bring back to non-log realm\n    double pk_max = log_post_k.maxCoeff();\n        \n    for (int s = 0; s < log_post_k.size(); s++){\n        log_post_k(s) -= pk_max;\n    };\n    \n    log_post_k = log_post_k.array().exp();\n    \n    \n    log_post_k /= log_post_k.sum(); // Normalize\n    \n    \n    return log_post_k;\n\n}\n\n\n// Random Multinomial Sampling in Eigen w/ argmax selection\n// Given a set of pvals and N, gives back index most likely category\n// Ref: \n//   C.S. David, The computer generation of multinomial random variates,\n//   Comp. Stat. Data Anal. 16 (1993) 205-217\n// \n\nint argmax_multinomial_cpp(int N, Eigen::VectorXd pvals){\n\n    // Init random number generated\n    std::random_device rd;\n    std::mt19937 re(rd());\n    \n    // Allocate memory\n    double sum_p = 0.0;\n    double norm = 0.0;\n    int sum_n = 0;\n    int K = pvals.size(); // size of vector (i.e. # of components)\n    Eigen::MatrixXd n_vec(1,K);\n    Eigen::MatrixXd::Index maxRow, maxCol;\n\n    norm += pvals.sum(); // = 1 if pvals are input (sum of components)\n    \n    // For each component (except last one) sample from binomial\n    for (int i=0; i < K-1; i++){\n        \n        // Binomial sampler varies across loop, pvals and remaining N get adjusted \n        std::binomial_distribution<int> binomial(N-sum_n, pvals(i)/(norm - sum_p) );\n       \n\n        if (pvals(i) > 0.0){\n            n_vec(0,i) = binomial(re);\n        }\n        else {\n            n_vec(i) = 0;\n        };\n        \n        sum_p += pvals(i); // adjustment for pvals and remaining n < N\n        sum_n += n_vec(0,i);\n \n    };\n    \n    // For last component allocate remaining N\n    n_vec(0,K-1) = N - sum_n;\n    \n    int max = n_vec.maxCoeff(&maxRow, &maxCol); // Get argmax of vector\n \n    return maxCol;\n     \n}\n\n\n// Pybind11 module referencing\nPYBIND11_MODULE(hdp_funcs, m) {\n    m.doc() = \"pybind11 cpp functions used in hierarchical dirichlet processes topic modeling\",\n    m.def(\"posterior_t_cpp\", &posterior_t_cpp, \"Generate posterior pvals to allocate word to table\"),\n    m.def(\"fk_cpp\", &fk_cpp, \"Conditional distribution necessary for posterior sampling\"),\n    m.def(\"posterior_k_cpp\", &posterior_k_cpp, \"Generate posterior pvals to allocate word to topic\"),\n    m.def(\"argmax_multinomial_cpp\", &argmax_multinomial_cpp, \"Vectorized multinomial random sampling\");\n}\n", "meta": {"hexsha": "ba74f64b7ce6d78fd6d2dc227a78a57decf51651", "size": 5857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hdp/.rendered.hdp_funcs.cpp", "max_stars_repo_name": "datadiarist/hplda", "max_stars_repo_head_hexsha": "a81cf84ea76487e716641bb6dfbf36f18ceac91e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hdp/.rendered.hdp_funcs.cpp", "max_issues_repo_name": "datadiarist/hplda", "max_issues_repo_head_hexsha": "a81cf84ea76487e716641bb6dfbf36f18ceac91e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-24T04:30:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-24T04:30:51.000Z", "max_forks_repo_path": "src/hdp/.rendered.hdp_funcs.cpp", "max_forks_repo_name": "datadiarist/hplda", "max_forks_repo_head_hexsha": "a81cf84ea76487e716641bb6dfbf36f18ceac91e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-01T03:59:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-01T03:59:42.000Z", "avg_line_length": 32.1813186813, "max_line_length": 116, "alphanum_fraction": 0.6124295715, "num_tokens": 1578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5026068522944269}}
{"text": "\r\n//  (C) Copyright John Maddock 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#include <gmpxx.h>\r\n#include <boost/math/common_factor.hpp>\r\n\r\ntemplate mpz_class boost::math::gcd(const mpz_class&, const mpz_class&);\r\ntemplate mpz_class boost::math::lcm(const mpz_class&, const mpz_class&);\r\n\r\nint main()\r\n{\r\n}\r\n", "meta": {"hexsha": "48e560e7955249a90f672ba9cdaee03bf7e3a46f", "size": 467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_common_factor_gmpxx.cpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/math/test/test_common_factor_gmpxx.cpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty-cpp/boost_1_62_0/libs/math/test/test_common_factor_gmpxx.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": 29.1875, "max_line_length": 73, "alphanum_fraction": 0.7173447537, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5025621682284602}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n#include <iomanip>\n#include <Eigen/SparseQR>\n\n#include \"structures.h\"\n#include \"transformations.h\"\n#include \"point_to_point_source_to_target_tait_bryan_wc_jacobian.h\"\n#include \"point_to_point_source_to_target_rodrigues_wc_jacobian.h\"\n#include \"point_to_point_source_to_target_quaternion_wc_jacobian.h\"\n#include \"quaternion_constraint_jacobian.h\"\n#include \"cauchy.h\"\n#include \"point_to_point_source_to_landmark_tait_bryan_wc_jacobian.h\"\n#include \"point_to_point_source_to_landmark_rodrigues_wc_jacobian.h\"\n#include \"point_to_point_source_to_landmark_quaternion_wc_jacobian.h\"\n#include \"point_to_point_source_to_landmark_tait_bryan_wc_cov.h\"\n\nstruct Measurement{\n\tEigen::Vector3d value;\n\tint index_landmark;\n};\n\nstruct Node{\n\tEigen::Affine3d pose;\n\tstd::vector<Measurement> measurements;\n};\n\nstruct PointMeanCov{\n\tEigen::Vector3d mean;\n\tEigen::Matrix3d cov;\n\tEigen::Vector3d coords;\n};\n\nconst unsigned int window_width = 1920;\nconst unsigned int window_height = 1080;\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\nfloat rotate_x = 0.0, rotate_y = 0.0;\nfloat translate_z = -100.0;\nfloat translate_x, translate_y = 0.0;\n\nbool initGL(int *argc, char **argv);\nvoid display();\nvoid keyboard(unsigned char key, int x, int y);\nvoid mouse(int button, int state, int x, int y);\nvoid motion(int x, int y);\nvoid reshape(int w, int h);\nvoid printHelp();\nvoid calculate_ICP_COV(std::vector<PointMeanCov>& data_pi,\n\t\tstd::vector<PointMeanCov>& model_qi, Eigen::Affine3d transform, Eigen::MatrixXd& ICP_COV);\n\nstd::vector<Eigen::Vector3d> landmarks;\nstd::vector<Node> nodes;\nstd::vector<Node> nodesInitial;\n\nvoid draw_ellipse2D(const Eigen::Matrix3d& covar, Eigen::Vector3d& mean, Eigen::Vector3f color, float nstd  = 3)\n{\n\n    Eigen::LLT<Eigen::Matrix<double,3,3> > cholSolver(covar);\n    Eigen::Matrix3d transform = cholSolver.matrixL();\n\n    const double pi = 3.141592;\n    const double di =0.02;\n    const double dj =0.04;\n    const double du =di*2*pi;\n    const double dv =dj*pi;\n    glColor3f(color.x(), color.y(),color.z());\n\n    for (double i = 0; i < 1.0; i+=di) { //horizonal\n\t\tdouble u = i*2*pi;      //0     to  2pi\n\t\tconst Eigen::Vector3d pp0( cos(u), sin (u),0);\n\t\tconst Eigen::Vector3d pp1( cos(u+du), sin(u+du),0);\n\t\tEigen::Vector3d tp0 = transform * (nstd*pp0) + mean;\n\t\tEigen::Vector3d tp1 = transform * (nstd*pp1) + mean;\n\t\tglBegin(GL_LINE_LOOP);\n\t\tglVertex3dv(tp0.data());\n\t\tglVertex3dv(tp1.data());\n\t\tglEnd();\n\t}\n}\n\nvoid compute_covariance (std::vector<Eigen::Vector3d> points, Eigen::Vector3d &mean, Eigen::Matrix3d &cov)\n{\n\tmean.x() = 0;\n\tmean.y() = 0;\n\tmean.z() = 0;\n\n\tfor(size_t i = 0 ; i < points.size(); i++){\n\t\tmean += points[i];\n\t}\n\tmean /= points.size();\n\n    Eigen::Matrix3d covariance;\n    for (int x = 0; x < 3; x ++)\n    {\n        for (int y = 0; y < 3; y ++)\n        {\n            double element =0;\n            for (const auto pp : points)\n            {\n                element += (pp(x) - mean(x)) * (pp(y) - mean(y));\n\n            }\n            covariance(x,y) = element / (points.size());\n        }\n    };\n    cov = covariance;\n}\n\nint main(int argc, char *argv[]){\n\n\tfor(size_t i = 0; i < 10; i++){\n\t\tlandmarks.emplace_back(Eigen::Vector3d((rand()%1000 - 500)*0.1, (rand()%1000 - 500)*0.1, (rand()%1000 - 500)*0.0001));\n\t}\n\n\tfor(size_t i = 0; i < 10; i++){\n\t\tEigen::Affine3d m = Eigen::Affine3d::Identity();\n\t\tm(0,3) = (rand()%1000 - 500)*0.001;\n\t\tm(1,3) = i*5;\n\t\tm(2,3) = 1;\n\t\tNode n;\n\t\tn.pose = m;\n\n\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m);\n\t\tpose.ka = M_PI /4.0;\n\n\t\tn.pose = affine_matrix_from_pose_tait_bryan(pose);\n\n\t\tnodes.emplace_back(n);\n\t}\n\n\tnodesInitial = nodes;\n\n\tfor(size_t i = 0 ; i < nodes.size(); i++){\n\t\tfor(size_t j = 0; j < landmarks.size(); j++){\n\t\t\tMeasurement meas;\n\t\t\tmeas.index_landmark = j;\n\t\t\tmeas.value = nodes[i].pose.inverse() * landmarks[j];\n\t\t\tnodes[i].measurements.emplace_back(meas);\n\t\t}\n\t}\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\n\treturn 0;\n}\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"point to point source to landmark\");\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMotionFunc(motion);\n\n\t// default initialization\n\tglClearColor(1.0, 1.0, 1.0, 1.0);\n\tglEnable(GL_DEPTH_TEST);\n\n\t// viewport\n\tglViewport(0, 0, window_width, window_height);\n\n\t// projection\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) window_width / (GLfloat) window_height, 0.01, 10000.0);\n\tglutReshapeFunc(reshape);\n\n\treturn true;\n}\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\tglLineWidth(2);\n\t/*glBegin(GL_LINES);\n\tglColor3f(1.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(1.0f, 0.0f, 0.0f);\n\n\tglColor3f(0.0f, 1.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 1.0f, 0.0f);\n\n\tglColor3f(0.0f, 0.0f, 1.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 1.0f);\n\tglEnd();*/\n\n\tglColor3f(0, 0, 0);\n\tglBegin(GL_LINES);\n\tfor(const auto &l:landmarks){\n\t\tglVertex3f(l.x() - 1, l.y(), l.z());\n\t\tglVertex3f(l.x() + 1, l.y(), l.z());\n\n\t\tglVertex3f(l.x(), l.y() - 1, l.z());\n\t\tglVertex3f(l.x(), l.y() + 1, l.z());\n\t}\n\tglEnd();\n\n\tglColor3f(1, 0, 0);\n\tglBegin(GL_LINE_STRIP);\n\t\tfor(int i = 0 ; i < nodes.size(); i++){\n\t\t\tglVertex3f(nodes[i].pose(0,3), nodes[i].pose(1,3), nodes[i].pose(2,3));\n\t\t}\n\tglEnd();\n\n\tglColor3f(0,0,0);\n\tglBegin(GL_LINES);\n\t\tfor(int i = 0 ; i < nodesInitial.size(); i++){\n\t\t\tglVertex3f(nodesInitial[i].pose(0,3)-1, nodesInitial[i].pose(1,3), nodesInitial[i].pose(2,3));\n\t\t\tglVertex3f(nodesInitial[i].pose(0,3)+1, nodesInitial[i].pose(1,3), nodesInitial[i].pose(2,3));\n\n\t\t\tglVertex3f(nodesInitial[i].pose(0,3), nodesInitial[i].pose(1,3) - 1, nodesInitial[i].pose(2,3));\n\t\t\tglVertex3f(nodesInitial[i].pose(0,3), nodesInitial[i].pose(1,3) + 1, nodesInitial[i].pose(2,3));\n\t\t}\n\tglEnd();\n\n\tglColor3f(0.6,0.6,0.6);\n\tglBegin(GL_LINES);\n\t\tfor(int i = 0 ; i < nodesInitial.size(); i++){\n\t\t\tglVertex3f(nodesInitial[i].pose(0,3), nodesInitial[i].pose(1,3), nodesInitial[i].pose(2,3));\n\t\t\tglVertex3f(nodes[i].pose(0,3), nodes[i].pose(1,3), nodes[i].pose(2,3));\n\t\t}\n\tglEnd();\n\n\tglColor3f(0, 0, 0);\n\tglBegin(GL_LINES);\n\n\tfor(size_t i = 0 ; i < nodes.size(); i++){\n\t\tfor(size_t j = 0 ; j < nodes[i].measurements.size(); j++){\n\t\t\tEigen::Vector3d meas = nodes[i].pose * nodes[i].measurements[j].value;\n\n\t\t\tglVertex3f(meas.x() - 0.3, meas.y(), meas.z());\n\t\t\tglVertex3f(meas.x() + 0.3, meas.y(), meas.z());\n\n\t\t\tglVertex3f(meas.x(), meas.y() - 0.3, meas.z());\n\t\t\tglVertex3f(meas.x(), meas.y() + 0.3, meas.z());\n\t\t}\n\t}\n\tglEnd();\n\n\tstd::vector<PointMeanCov> lmc;\n\tfor(int i = 0; i < landmarks.size(); i++){\n\t\tstd::vector<Eigen::Vector3d> points;\n\t\tfor(size_t ii = 0 ; ii < nodes.size(); ii++){\n\t\t\tfor(size_t j = 0 ; j < nodes[ii].measurements.size(); j++){\n\t\t\t\tif(nodes[i].measurements[j].index_landmark == i){\n\t\t\t\t\tEigen::Vector3d meas = nodes[ii].pose * nodes[ii].measurements[j].value;\n\t\t\t\t\tpoints.push_back(meas);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tEigen::Vector3d mean;\n\t\tEigen::Matrix3d cov;\n\t\tcompute_covariance (points, mean, cov);\n\t\tdraw_ellipse2D(cov, mean, Eigen::Vector3f(1.0, 0.0, 0.0),1);\n\t\tdraw_ellipse2D(cov, mean, Eigen::Vector3f(0.0, 1.0, 0.0),2);\n\t\tdraw_ellipse2D(cov, mean, Eigen::Vector3f(0.0, 0.0, 1.0),3);\n\t\tPointMeanCov l;\n\t\tl.coords = landmarks[i];\n\t\tl.mean = mean;\n\t\tl.cov = cov;\n\t\tlmc.push_back(l);\n\t}\n\n\tfor(size_t i = 0 ; i < nodes.size(); i++){\n\t\tstd::vector<PointMeanCov> data_pi;\n\t\tstd::vector<PointMeanCov> model_qi;\n\n\t\tfor(size_t j = 0 ; j < nodes[i].measurements.size(); j++){\n\t\t\tPointMeanCov pi;\n\t\t\tpi.coords = nodes[i].measurements[j].value;\n\t\t\tpi.cov = lmc[nodes[i].measurements[j].index_landmark].cov;\n\t\t\tpi.cov(0,0)= 0.03 * 0.03;\n\t\t\tpi.cov(1,1)= 0.03 * 0.03;\n\t\t\tpi.cov(2,2)= 0.03 * 0.03;\n\t\t\tpi.mean = lmc[nodes[i].measurements[j].index_landmark].mean;\n\t\t\tdata_pi.push_back(pi);\n\n\t\t\tPointMeanCov qi = lmc[nodes[i].measurements[j].index_landmark];\n\t\t\tmodel_qi.push_back(qi);\n\t\t}\n\n\t\tEigen::MatrixXd ICP_COV(6,6);\n\t\tICP_COV = Eigen::MatrixXd::Zero(6,6);\n\t\tcalculate_ICP_COV(data_pi, model_qi, nodes[i].pose, ICP_COV);\n\n\t\tEigen::Vector3d mean(nodes[i].pose(0,3), nodes[i].pose(1,3), nodes[i].pose(2,3));\n\t\tEigen::Matrix3d cov;\n\t\tcov(0,0) = ICP_COV(0,0);\n\t\tcov(0,1) = ICP_COV(0,1);\n\t\tcov(0,2) = ICP_COV(0,2);\n\t\tcov(1,0) = ICP_COV(1,0);\n\t\tcov(1,1) = ICP_COV(1,1);\n\t\tcov(1,2) = ICP_COV(1,2);\n\t\tcov(2,0) = ICP_COV(2,0);\n\t\tcov(2,1) = ICP_COV(2,1);\n\t\tcov(2,2) = ICP_COV(2,2);\n\t\tdraw_ellipse2D(cov, mean, Eigen::Vector3f(1,0,0),1);\n\t\tdraw_ellipse2D(cov, mean, Eigen::Vector3f(0,1,0),2);\n\t\tdraw_ellipse2D(cov, mean, Eigen::Vector3f(0,0,1),3);\n\t}\n\tglutSwapBuffers();\n}\n\nvoid keyboard(unsigned char key, int /*x*/, int /*y*/) {\n\tswitch (key) {\n\t\tcase (27): {\n\t\t\tglutDestroyWindow(glutGetWindow());\n\t\t\treturn;\n\t\t}\n\t\tcase 'n':{\n\t\t\tfor(size_t i = 0 ; i < nodes.size(); i++){\n\t\t\t\tTaitBryanPose pose;\n\t\t\t\t\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.5;\n\t\t\t\t\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.5;\n\t\t\t\t\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.0000005;\n\t\t\t\t\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.0000005;\n\t\t\t\t\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.0000005;\n\t\t\t\t\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.005;\n\t\t\t\tnodes[i].pose = nodes[i].pose * affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 't':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0 ; i < nodes.size(); i++){\n\t\t\t\tEigen::Affine3d m = nodes[i].pose;\n\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m);\n\n\t\t\t\tfor(size_t j = 0 ; j < nodes[i].measurements.size(); j++){\n\n\t\t\t\t\tEigen::Vector3d &p_t = landmarks[nodes[i].measurements[j].index_landmark];\n\t\t\t\t\tEigen::Vector3d &p_s = nodes[i].measurements[j].value;\n\n\t\t\t\t\tdouble delta_x;\n\t\t\t\t\tdouble delta_y;\n\t\t\t\t\tdouble delta_z;\n\t\t\t\t\tpoint_to_point_source_to_landmark_tait_bryan_wc(delta_x, delta_y, delta_z,\n\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka,\n\t\t\t\t\t\t\tp_s.x(), p_s.y(), p_s.z(), p_t.x(), p_t.y(), p_t.z());\n\n\t\t\t\t\tEigen::Matrix<double, 3, 9, Eigen::RowMajor> jacobian;\n\t\t\t\t\tpoint_to_point_source_to_landmark_tait_bryan_wc_jacobian(jacobian,\n\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka,\n\t\t\t\t\t\t\tp_s.x(), p_s.y(), p_s.z());\n\n\n\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\tint ic = 6 * i;\n\n\t\t\t\t\tif(jacobian(0,0) != 0.0)tripletListA.emplace_back(ir + 0, ic + 0, -jacobian(0,0));\n\t\t\t\t\tif(jacobian(0,1) != 0.0)tripletListA.emplace_back(ir + 0, ic + 1, -jacobian(0,1));\n\t\t\t\t\tif(jacobian(0,2) != 0.0)tripletListA.emplace_back(ir + 0, ic + 2, -jacobian(0,2));\n\t\t\t\t\tif(jacobian(0,3) != 0.0)tripletListA.emplace_back(ir + 0, ic + 3, -jacobian(0,3));\n\t\t\t\t\tif(jacobian(0,4) != 0.0)tripletListA.emplace_back(ir + 0, ic + 4, -jacobian(0,4));\n\t\t\t\t\tif(jacobian(0,5) != 0.0)tripletListA.emplace_back(ir + 0, ic + 5, -jacobian(0,5));\n\n\t\t\t\t\tic = nodes.size() * 6 + nodes[i].measurements[j].index_landmark * 3;\n\t\t\t\t\tif(jacobian(0,6) != 0.0)tripletListA.emplace_back(ir + 0, ic + 0, -jacobian(0,6));\n\t\t\t\t\tif(jacobian(0,7) != 0.0)tripletListA.emplace_back(ir + 0, ic + 1, -jacobian(0,7));\n\t\t\t\t\tif(jacobian(0,8) != 0.0)tripletListA.emplace_back(ir + 0, ic + 2, -jacobian(0,8));\n\n\t\t\t\t\tic = 6 * i;\n\t\t\t\t\tif(jacobian(1,0) != 0.0)tripletListA.emplace_back(ir + 1, ic + 0, -jacobian(1,0));\n\t\t\t\t\tif(jacobian(1,1) != 0.0)tripletListA.emplace_back(ir + 1, ic + 1, -jacobian(1,1));\n\t\t\t\t\tif(jacobian(1,2) != 0.0)tripletListA.emplace_back(ir + 1, ic + 2, -jacobian(1,2));\n\t\t\t\t\tif(jacobian(1,3) != 0.0)tripletListA.emplace_back(ir + 1, ic + 3, -jacobian(1,3));\n\t\t\t\t\tif(jacobian(1,4) != 0.0)tripletListA.emplace_back(ir + 1, ic + 4, -jacobian(1,4));\n\t\t\t\t\tif(jacobian(1,5) != 0.0)tripletListA.emplace_back(ir + 1, ic + 5, -jacobian(1,5));\n\n\t\t\t\t\tic = nodes.size() * 6 + nodes[i].measurements[j].index_landmark * 3;\n\t\t\t\t\tif(jacobian(1,6) != 0.0)tripletListA.emplace_back(ir + 1, ic + 0, -jacobian(1,6));\n\t\t\t\t\tif(jacobian(1,7) != 0.0)tripletListA.emplace_back(ir + 1, ic + 1, -jacobian(1,7));\n\t\t\t\t\tif(jacobian(1,8) != 0.0)tripletListA.emplace_back(ir + 1, ic + 2, -jacobian(1,8));\n\n\t\t\t\t\tic = 6 * i;\n\t\t\t\t\tif(jacobian(2,0) != 0.0)tripletListA.emplace_back(ir + 2, ic + 0, -jacobian(2,0));\n\t\t\t\t\tif(jacobian(2,1) != 0.0)tripletListA.emplace_back(ir + 2, ic + 1, -jacobian(2,1));\n\t\t\t\t\tif(jacobian(2,2) != 0.0)tripletListA.emplace_back(ir + 2, ic + 2, -jacobian(2,2));\n\t\t\t\t\tif(jacobian(2,3) != 0.0)tripletListA.emplace_back(ir + 2, ic + 3, -jacobian(2,3));\n\t\t\t\t\tif(jacobian(2,4) != 0.0)tripletListA.emplace_back(ir + 2, ic + 4, -jacobian(2,4));\n\t\t\t\t\tif(jacobian(2,5) != 0.0)tripletListA.emplace_back(ir + 2, ic + 5, -jacobian(2,5));\n\n\t\t\t\t\tic = nodes.size() * 6 + nodes[i].measurements[j].index_landmark * 3;\n\t\t\t\t\tif(jacobian(2,6) != 0.0)tripletListA.emplace_back(ir + 2, ic + 0, -jacobian(2,6));\n\t\t\t\t\tif(jacobian(2,7) != 0.0)tripletListA.emplace_back(ir + 2, ic + 1, -jacobian(2,7));\n\t\t\t\t\tif(jacobian(2,8) != 0.0)tripletListA.emplace_back(ir + 2, ic + 2, -jacobian(2,8));\n\n\t\t\t\t\ttripletListP.emplace_back(ir    , ir    , 1);\n\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\n\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta_x);\n\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta_y);\n\t\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta_z);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 10000000000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), nodes.size() * 6 + landmarks.size() * 3);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(nodes.size() * 6 + landmarks.size() * 3, nodes.size() * 6 + landmarks.size() * 3);\n\t\t\tEigen::SparseMatrix<double> AtPB(nodes.size() * 6 + landmarks.size() * 3, 1);\n\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = AtP * matA;\n\t\t\tAtPB = AtP * matB;\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\tstd::cout << it.row() << \" \" << it.col() << \" \" << it.value() << std::endl;\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == nodes.size() * 6 + landmarks.size() * 3){\n\t\t\t\tstd::cout << \"optimization success\" << std::endl;\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0 ; i < nodes.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(nodes[i].pose);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\t\t\t\t\tnodes[i].pose = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\n\t\t\t\tfor(size_t i = 0 ; i < landmarks.size(); i++){\n\t\t\t\t\tlandmarks[i].x() += h_x[counter++];\n\t\t\t\t\tlandmarks[i].y() += h_x[counter++];\n\t\t\t\t\tlandmarks[i].z() += h_x[counter++];\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'r':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0 ; i < nodes.size(); i++){\n\t\t\t\tEigen::Affine3d m = nodes[i].pose;\n\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(m);\n\n\t\t\t\tfor(size_t j = 0 ; j < nodes[i].measurements.size(); j++){\n\n\t\t\t\t\tEigen::Vector3d &p_t = landmarks[nodes[i].measurements[j].index_landmark];\n\t\t\t\t\tEigen::Vector3d &p_s = nodes[i].measurements[j].value;\n\n\t\t\t\t\tdouble delta_x;\n\t\t\t\t\tdouble delta_y;\n\t\t\t\t\tdouble delta_z;\n\t\t\t\t\tpoint_to_point_source_to_landmark_rodrigues_wc(delta_x, delta_y, delta_z,\n\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.sx, pose.sy, pose.sz,\n\t\t\t\t\t\t\tp_s.x(), p_s.y(), p_s.z(), p_t.x(), p_t.y(), p_t.z());\n\n\t\t\t\t\tEigen::Matrix<double, 3, 9, Eigen::RowMajor> jacobian;\n\t\t\t\t\tpoint_to_point_source_to_landmark_rodrigues_wc_jacobian(jacobian,\n\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.sx, pose.sy, pose.sz,\n\t\t\t\t\t\t\tp_s.x(), p_s.y(), p_s.z());\n\n\n\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\tint ic = 6 * i;\n\n\t\t\t\t\tif(jacobian(0,0) != 0.0)tripletListA.emplace_back(ir + 0, ic + 0, -jacobian(0,0));\n\t\t\t\t\tif(jacobian(0,1) != 0.0)tripletListA.emplace_back(ir + 0, ic + 1, -jacobian(0,1));\n\t\t\t\t\tif(jacobian(0,2) != 0.0)tripletListA.emplace_back(ir + 0, ic + 2, -jacobian(0,2));\n\t\t\t\t\tif(jacobian(0,3) != 0.0)tripletListA.emplace_back(ir + 0, ic + 3, -jacobian(0,3));\n\t\t\t\t\tif(jacobian(0,4) != 0.0)tripletListA.emplace_back(ir + 0, ic + 4, -jacobian(0,4));\n\t\t\t\t\tif(jacobian(0,5) != 0.0)tripletListA.emplace_back(ir + 0, ic + 5, -jacobian(0,5));\n\n\t\t\t\t\tic = nodes.size() * 6 + nodes[i].measurements[j].index_landmark * 3;\n\t\t\t\t\tif(jacobian(0,6) != 0.0)tripletListA.emplace_back(ir + 0, ic + 0, -jacobian(0,6));\n\t\t\t\t\tif(jacobian(0,7) != 0.0)tripletListA.emplace_back(ir + 0, ic + 1, -jacobian(0,7));\n\t\t\t\t\tif(jacobian(0,8) != 0.0)tripletListA.emplace_back(ir + 0, ic + 2, -jacobian(0,8));\n\n\t\t\t\t\tic = 6 * i;\n\t\t\t\t\tif(jacobian(1,0) != 0.0)tripletListA.emplace_back(ir + 1, ic + 0, -jacobian(1,0));\n\t\t\t\t\tif(jacobian(1,1) != 0.0)tripletListA.emplace_back(ir + 1, ic + 1, -jacobian(1,1));\n\t\t\t\t\tif(jacobian(1,2) != 0.0)tripletListA.emplace_back(ir + 1, ic + 2, -jacobian(1,2));\n\t\t\t\t\tif(jacobian(1,3) != 0.0)tripletListA.emplace_back(ir + 1, ic + 3, -jacobian(1,3));\n\t\t\t\t\tif(jacobian(1,4) != 0.0)tripletListA.emplace_back(ir + 1, ic + 4, -jacobian(1,4));\n\t\t\t\t\tif(jacobian(1,5) != 0.0)tripletListA.emplace_back(ir + 1, ic + 5, -jacobian(1,5));\n\n\t\t\t\t\tic = nodes.size() * 6 + nodes[i].measurements[j].index_landmark * 3;\n\t\t\t\t\tif(jacobian(1,6) != 0.0)tripletListA.emplace_back(ir + 1, ic + 0, -jacobian(1,6));\n\t\t\t\t\tif(jacobian(1,7) != 0.0)tripletListA.emplace_back(ir + 1, ic + 1, -jacobian(1,7));\n\t\t\t\t\tif(jacobian(1,8) != 0.0)tripletListA.emplace_back(ir + 1, ic + 2, -jacobian(1,8));\n\n\t\t\t\t\tic = 6 * i;\n\t\t\t\t\tif(jacobian(2,0) != 0.0)tripletListA.emplace_back(ir + 2, ic + 0, -jacobian(2,0));\n\t\t\t\t\tif(jacobian(2,1) != 0.0)tripletListA.emplace_back(ir + 2, ic + 1, -jacobian(2,1));\n\t\t\t\t\tif(jacobian(2,2) != 0.0)tripletListA.emplace_back(ir + 2, ic + 2, -jacobian(2,2));\n\t\t\t\t\tif(jacobian(2,3) != 0.0)tripletListA.emplace_back(ir + 2, ic + 3, -jacobian(2,3));\n\t\t\t\t\tif(jacobian(2,4) != 0.0)tripletListA.emplace_back(ir + 2, ic + 4, -jacobian(2,4));\n\t\t\t\t\tif(jacobian(2,5) != 0.0)tripletListA.emplace_back(ir + 2, ic + 5, -jacobian(2,5));\n\n\t\t\t\t\tic = nodes.size() * 6 + nodes[i].measurements[j].index_landmark * 3;\n\t\t\t\t\tif(jacobian(2,6) != 0.0)tripletListA.emplace_back(ir + 2, ic + 0, -jacobian(2,6));\n\t\t\t\t\tif(jacobian(2,7) != 0.0)tripletListA.emplace_back(ir + 2, ic + 1, -jacobian(2,7));\n\t\t\t\t\tif(jacobian(2,8) != 0.0)tripletListA.emplace_back(ir + 2, ic + 2, -jacobian(2,8));\n\n\t\t\t\t\ttripletListP.emplace_back(ir    , ir    , 1);\n\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\n\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta_x);\n\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta_y);\n\t\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta_z);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 10000000000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), nodes.size() * 6 + landmarks.size() * 3);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(nodes.size() * 6 + landmarks.size() * 3, nodes.size() * 6 + landmarks.size() * 3);\n\t\t\tEigen::SparseMatrix<double> AtPB(nodes.size() * 6 + landmarks.size() * 3, 1);\n\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = AtP * matA;\n\t\t\tAtPB = AtP * matB;\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\tstd::cout << it.row() << \" \" << it.col() << \" \" << it.value() << std::endl;\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == nodes.size() * 6 + landmarks.size() * 3){\n\t\t\t\tstd::cout << \"optimization success\" << std::endl;\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0 ; i < nodes.size(); i++){\n\t\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(nodes[i].pose);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.sx += h_x[counter++];\n\t\t\t\t\tpose.sy += h_x[counter++];\n\t\t\t\t\tpose.sz += h_x[counter++];\n\t\t\t\t\tnodes[i].pose = affine_matrix_from_pose_rodrigues(pose);\n\t\t\t\t}\n\n\t\t\t\tfor(size_t i = 0 ; i < landmarks.size(); i++){\n\t\t\t\t\tlandmarks[i].x() += h_x[counter++];\n\t\t\t\t\tlandmarks[i].y() += h_x[counter++];\n\t\t\t\t\tlandmarks[i].z() += h_x[counter++];\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'q':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0 ; i < nodes.size(); i++){\n\t\t\t\tEigen::Affine3d m = nodes[i].pose;\n\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(m);\n\n\t\t\t\tfor(size_t j = 0 ; j < nodes[i].measurements.size(); j++){\n\n\t\t\t\t\tEigen::Vector3d &p_t = landmarks[nodes[i].measurements[j].index_landmark];\n\t\t\t\t\tEigen::Vector3d &p_s = nodes[i].measurements[j].value;\n\n\t\t\t\t\tdouble delta_x;\n\t\t\t\t\tdouble delta_y;\n\t\t\t\t\tdouble delta_z;\n\t\t\t\t\tpoint_to_point_source_to_landmark_quaternion_wc(delta_x, delta_y, delta_z,\n\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.q0, pose.q1, pose.q2, pose.q3,\n\t\t\t\t\t\t\tp_s.x(), p_s.y(), p_s.z(), p_t.x(), p_t.y(), p_t.z());\n\n\t\t\t\t\tEigen::Matrix<double, 3, 10, Eigen::RowMajor> jacobian;\n\t\t\t\t\tpoint_to_point_source_to_landmark_quaternion_wc_jacobian(jacobian,\n\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.q0, pose.q1, pose.q2, pose.q3,\n\t\t\t\t\t\t\tp_s.x(), p_s.y(), p_s.z());\n\n\n\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\tint ic = 7 * i;\n\n\t\t\t\t\tif(jacobian(0,0) != 0.0)tripletListA.emplace_back(ir + 0, ic + 0, -jacobian(0,0));\n\t\t\t\t\tif(jacobian(0,1) != 0.0)tripletListA.emplace_back(ir + 0, ic + 1, -jacobian(0,1));\n\t\t\t\t\tif(jacobian(0,2) != 0.0)tripletListA.emplace_back(ir + 0, ic + 2, -jacobian(0,2));\n\t\t\t\t\tif(jacobian(0,3) != 0.0)tripletListA.emplace_back(ir + 0, ic + 3, -jacobian(0,3));\n\t\t\t\t\tif(jacobian(0,4) != 0.0)tripletListA.emplace_back(ir + 0, ic + 4, -jacobian(0,4));\n\t\t\t\t\tif(jacobian(0,5) != 0.0)tripletListA.emplace_back(ir + 0, ic + 5, -jacobian(0,5));\n\t\t\t\t\tif(jacobian(0,6) != 0.0)tripletListA.emplace_back(ir + 0, ic + 6, -jacobian(0,6));\n\n\t\t\t\t\tic = nodes.size() * 7 + nodes[i].measurements[j].index_landmark * 3;\n\t\t\t\t\tif(jacobian(0,7) != 0.0)tripletListA.emplace_back(ir + 0, ic + 0, -jacobian(0,7));\n\t\t\t\t\tif(jacobian(0,8) != 0.0)tripletListA.emplace_back(ir + 0, ic + 1, -jacobian(0,8));\n\t\t\t\t\tif(jacobian(0,9) != 0.0)tripletListA.emplace_back(ir + 0, ic + 2, -jacobian(0,9));\n\n\t\t\t\t\tic = 7 * i;\n\t\t\t\t\tif(jacobian(1,0) != 0.0)tripletListA.emplace_back(ir + 1, ic + 0, -jacobian(1,0));\n\t\t\t\t\tif(jacobian(1,1) != 0.0)tripletListA.emplace_back(ir + 1, ic + 1, -jacobian(1,1));\n\t\t\t\t\tif(jacobian(1,2) != 0.0)tripletListA.emplace_back(ir + 1, ic + 2, -jacobian(1,2));\n\t\t\t\t\tif(jacobian(1,3) != 0.0)tripletListA.emplace_back(ir + 1, ic + 3, -jacobian(1,3));\n\t\t\t\t\tif(jacobian(1,4) != 0.0)tripletListA.emplace_back(ir + 1, ic + 4, -jacobian(1,4));\n\t\t\t\t\tif(jacobian(1,5) != 0.0)tripletListA.emplace_back(ir + 1, ic + 5, -jacobian(1,5));\n\t\t\t\t\tif(jacobian(1,6) != 0.0)tripletListA.emplace_back(ir + 1, ic + 6, -jacobian(1,6));\n\n\t\t\t\t\tic = nodes.size() * 7 + nodes[i].measurements[j].index_landmark * 3;\n\t\t\t\t\tif(jacobian(1,7) != 0.0)tripletListA.emplace_back(ir + 1, ic + 0, -jacobian(1,7));\n\t\t\t\t\tif(jacobian(1,8) != 0.0)tripletListA.emplace_back(ir + 1, ic + 1, -jacobian(1,8));\n\t\t\t\t\tif(jacobian(1,9) != 0.0)tripletListA.emplace_back(ir + 1, ic + 2, -jacobian(1,9));\n\n\t\t\t\t\tic = 7 * i;\n\t\t\t\t\tif(jacobian(2,0) != 0.0)tripletListA.emplace_back(ir + 2, ic + 0, -jacobian(2,0));\n\t\t\t\t\tif(jacobian(2,1) != 0.0)tripletListA.emplace_back(ir + 2, ic + 1, -jacobian(2,1));\n\t\t\t\t\tif(jacobian(2,2) != 0.0)tripletListA.emplace_back(ir + 2, ic + 2, -jacobian(2,2));\n\t\t\t\t\tif(jacobian(2,3) != 0.0)tripletListA.emplace_back(ir + 2, ic + 3, -jacobian(2,3));\n\t\t\t\t\tif(jacobian(2,4) != 0.0)tripletListA.emplace_back(ir + 2, ic + 4, -jacobian(2,4));\n\t\t\t\t\tif(jacobian(2,5) != 0.0)tripletListA.emplace_back(ir + 2, ic + 5, -jacobian(2,5));\n\t\t\t\t\tif(jacobian(2,6) != 0.0)tripletListA.emplace_back(ir + 2, ic + 6, -jacobian(2,6));\n\n\t\t\t\t\tic = nodes.size() * 7 + nodes[i].measurements[j].index_landmark * 3;\n\t\t\t\t\tif(jacobian(2,7) != 0.0)tripletListA.emplace_back(ir + 2, ic + 0, -jacobian(2,7));\n\t\t\t\t\tif(jacobian(2,8) != 0.0)tripletListA.emplace_back(ir + 2, ic + 1, -jacobian(2,8));\n\t\t\t\t\tif(jacobian(2,9) != 0.0)tripletListA.emplace_back(ir + 2, ic + 2, -jacobian(2,9));\n\n\t\t\t\t\ttripletListP.emplace_back(ir    , ir    , 1);\n\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\n\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta_x);\n\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta_y);\n\t\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta_z);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\t\t\ttripletListA.emplace_back(ir + 6 , 6, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 6 , ir + 6, 10000000000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 6 , 0, 0);\n\n\t\t\tfor(size_t i = 0 ; i < nodes.size(); i++){\n\t\t\t\tint ic = i * 7;\n\t\t\t\tir = tripletListB.size();\n\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(nodes[i].pose);\n\n\t\t\t\tdouble delta;\n\t\t\t\tquaternion_constraint(delta, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\tEigen::Matrix<double, 1, 4> jacobian;\n\t\t\t\tquaternion_constraint_jacobian(jacobian, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\ttripletListA.emplace_back(ir, ic + 3 , -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 4 , -jacobian(0,1));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 5 , -jacobian(0,2));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 6 , -jacobian(0,3));\n\n\t\t\t\ttripletListP.emplace_back(ir, ir, 1000000.0);\n\n\t\t\t\ttripletListB.emplace_back(ir, 0, delta);\n\t\t\t}\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), nodes.size() * 7 + landmarks.size() * 3);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(nodes.size() * 7 + landmarks.size() * 3, nodes.size() * 7 + landmarks.size() * 3);\n\t\t\tEigen::SparseMatrix<double> AtPB(nodes.size() * 7 + landmarks.size() * 3, 1);\n\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = AtP * matA;\n\t\t\tAtPB = AtP * matB;\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\tstd::cout << it.row() << \" \" << it.col() << \" \" << it.value() << std::endl;\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == nodes.size() * 7 + landmarks.size() * 3){\n\t\t\t\tstd::cout << \"optimization success\" << std::endl;\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0 ; i < nodes.size(); i++){\n\t\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(nodes[i].pose);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.q0 += h_x[counter++];\n\t\t\t\t\tpose.q1 += h_x[counter++];\n\t\t\t\t\tpose.q2 += h_x[counter++];\n\t\t\t\t\tpose.q3 += h_x[counter++];\n\t\t\t\t\tnodes[i].pose = affine_matrix_from_pose_quaternion(pose);\n\t\t\t\t}\n\t\t\t\tfor(size_t i = 0 ; i < landmarks.size(); i++){\n\t\t\t\t\tlandmarks[i].x() += h_x[counter++];\n\t\t\t\t\tlandmarks[i].y() += h_x[counter++];\n\t\t\t\t\tlandmarks[i].z() += h_x[counter++];\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintHelp();\n\tglutPostRedisplay();\n}\n\n\nvoid mouse(int button, int state, int x, int y) {\n\tif (state == GLUT_DOWN) {\n\t\tmouse_buttons |= 1 << button;\n\t} else if (state == GLUT_UP) {\n\t\tmouse_buttons = 0;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n}\n\nvoid motion(int x, int y) {\n\tfloat dx, dy;\n\tdx = (float) (x - mouse_old_x);\n\tdy = (float) (y - mouse_old_y);\n\n\tif (mouse_buttons & 1) {\n\t\trotate_x += dy * 0.2f;\n\t\trotate_y += dx * 0.2f;\n\n\t} else if (mouse_buttons & 4) {\n\t\ttranslate_z += dy * 0.05f;\n\t} else if (mouse_buttons & 3) {\n\t\ttranslate_x += dx * 0.05f;\n\t\ttranslate_y -= dy * 0.05f;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w, int h) {\n\tglViewport(0, 0, (GLsizei) w, (GLsizei) h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 10000.0);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid printHelp() {\n\tstd::cout << \"-------help-------\" << std::endl;\n\tstd::cout << \"n: add noise to poses\" << std::endl;\n\tstd::cout << \"t: optimize (Tait-Bryan)\" << std::endl;\n\tstd::cout << \"r: optimize (Rodrigues)\" << std::endl;\n\tstd::cout << \"q: optimize (Quaternion)\" << std::endl;\n}\n\nvoid calculate_ICP_COV(std::vector<PointMeanCov>& data_pi,\n\t\tstd::vector<PointMeanCov>& model_qi, Eigen::Affine3d transform, Eigen::MatrixXd& ICP_COV)\n{\n\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(transform);\n\n    Eigen::MatrixXd d2sum_dbeta2(6,6);\n    d2sum_dbeta2 = Eigen::MatrixXd::Zero(6,6);\n\n    for (size_t s = 0; s < data_pi.size(); ++s )\n    {\n        double pix = data_pi[s].coords.x();\n        double piy = data_pi[s].coords.y();\n        double piz = data_pi[s].coords.z();\n        double qix = model_qi[s].coords.x();\n        double qiy = model_qi[s].coords.y();\n        double qiz = model_qi[s].coords.z();\n\n        Eigen::Matrix<double, 6, 6, Eigen::RowMajor> d2sum_dbeta2i;\n\t\tpoint_to_point_source_to_landmark_tait_bryan_wc_d2sum_dbeta2(d2sum_dbeta2i, pose.px, pose.py, pose.pz, pose.om,\n        \t\t\tpose.fi, pose.ka, pix, piy, piz, qix, qiy, qiz);\n\n        Eigen::MatrixXd d2sum_dbeta2_temp(6,6);\n        d2sum_dbeta2_temp << d2sum_dbeta2i;\n        d2sum_dbeta2 = d2sum_dbeta2 + d2sum_dbeta2_temp;\n    }\n\n    int n = data_pi.size();\n    if (n > 200) n = 200;\n    Eigen::MatrixXd d2sum_dbetadx(6,6*n);\n    for (int k = 0; k < n ; ++k)\n    {\n        double pix = data_pi[k].coords.x();\n        double piy = data_pi[k].coords.y();\n        double piz = data_pi[k].coords.z();\n        double qix = model_qi[k].coords.x();\n        double qiy = model_qi[k].coords.y();\n        double qiz = model_qi[k].coords.z();\n\n        Eigen::MatrixXd d2sum_dbetadx_temp(6,6);\n        Eigen::Matrix<double, 6, 6, Eigen::RowMajor> d2sum_dbetadxi;\n        point_to_point_source_to_landmark_tait_bryan_wc_d2sum_dbetadx(d2sum_dbetadxi, pose.px, pose.py, pose.pz, pose.om,\n        \t\tpose.fi, pose.ka, pix, piy, piz, qix, qiy, qiz);\n\n        d2sum_dbetadx_temp << d2sum_dbetadxi;\n        d2sum_dbetadx.block<6,6>(0,6*k) = d2sum_dbetadx_temp;\n    }\n\n    Eigen::MatrixXd cov_x(6*n,6*n);\n    cov_x = 0.0 * Eigen::MatrixXd::Identity(6*n,6*n);\n\n    for(size_t i = 0; i < n ; i ++){\n    \tint row = i * 6;\n    \tint col = i * 6;\n\n    \tcov_x(row, col + 0) = data_pi[i].cov(0,0);\n    \tcov_x(row, col + 1) = data_pi[i].cov(0,1);\n    \tcov_x(row, col + 2) = data_pi[i].cov(0,2);\n\n    \tcov_x(row + 1, col + 0) = data_pi[i].cov(1,0);\n    \tcov_x(row + 1, col + 1) = data_pi[i].cov(1,1);\n    \tcov_x(row + 1, col + 2) = data_pi[i].cov(1,2);\n\n    \tcov_x(row + 2, col + 0) = data_pi[i].cov(2,0);\n    \tcov_x(row + 2, col + 1) = data_pi[i].cov(2,1);\n    \tcov_x(row + 2, col + 2) = data_pi[i].cov(2,2);\n\n    \tcov_x(row + 3, col + 3 + 0) = model_qi[i].cov(0,0);\n    \tcov_x(row + 3, col + 3 + 1) = model_qi[i].cov(0,1);\n    \tcov_x(row + 3, col + 3 + 2) = model_qi[i].cov(0,2);\n\n    \tcov_x(row + 4, col + 3 + 0) = model_qi[i].cov(1,0);\n    \tcov_x(row + 4, col + 3 + 1) = model_qi[i].cov(1,1);\n    \tcov_x(row + 4, col + 3 + 2) = model_qi[i].cov(1,2);\n\n    \tcov_x(row + 5, col + 3 + 0) = model_qi[i].cov(2,0);\n    \tcov_x(row + 5, col + 3 + 1) = model_qi[i].cov(2,1);\n    \tcov_x(row + 5, col + 3 + 2) = model_qi[i].cov(2,2);\n    }\n    ICP_COV =  d2sum_dbeta2.inverse() * d2sum_dbetadx * cov_x * d2sum_dbetadx.transpose() * d2sum_dbeta2.inverse();\n}\n\n\n\n", "meta": {"hexsha": "617d88ad4310a7a5993c6f936b06ab31993af256", "size": 36593, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/point_to_point_source_to_landmark.cpp", "max_stars_repo_name": "JanuszBedkowski/observation_equations", "max_stars_repo_head_hexsha": "ab241f571a655aebc89870f54e01cb7347382aa9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-11T13:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T22:04:00.000Z", "max_issues_repo_path": "codes/c++Examples/src/point_to_point_source_to_landmark.cpp", "max_issues_repo_name": "JanuszBedkowski/observation_equations", "max_issues_repo_head_hexsha": "ab241f571a655aebc89870f54e01cb7347382aa9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/c++Examples/src/point_to_point_source_to_landmark.cpp", "max_forks_repo_name": "JanuszBedkowski/observation_equations", "max_forks_repo_head_hexsha": "ab241f571a655aebc89870f54e01cb7347382aa9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-30T22:33:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T18:21:21.000Z", "avg_line_length": 36.9253279516, "max_line_length": 121, "alphanum_fraction": 0.6239991255, "num_tokens": 13557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5024910158142024}}
{"text": "/*\n * Copyright 2014-2019, CNRS\n * Copyright 2018-2019, INRIA\n */\n\n#include \"eigenpy/eigenpy.hpp\"\n#include \"eigenpy/geometry.hpp\"\n#include <Eigen/Geometry>\n#include <iostream>\n \nnamespace bp = boost::python;\n\nEigen::AngleAxisd testOutAngleAxis()\n{\n  return Eigen::AngleAxisd(.1,Eigen::Vector3d::UnitZ());\n}\n\ndouble testInAngleAxis(Eigen::AngleAxisd aa)\n{\n  return aa.angle();\n}\n\nEigen::Quaterniond testOutQuaternion()\n{\n  Eigen::Quaterniond res(1,2,3,4);\n  return res;\n}\ndouble testInQuaternion( Eigen::Quaterniond q )\n{\n  return q.norm(); \n}\n\nBOOST_PYTHON_MODULE(geometry)\n{\n  eigenpy::enableEigenPy();\n\n  eigenpy::exposeAngleAxis();\n  eigenpy::exposeQuaternion();\n\n  bp::def(\"testOutAngleAxis\",&testOutAngleAxis);\n  bp::def(\"testInAngleAxis\",&testInAngleAxis);\n\n  bp::def(\"testOutQuaternion\",&testOutQuaternion);\n  bp::def(\"testInQuaternion\",&testInQuaternion);\n\n}\n\n", "meta": {"hexsha": "fc561fe6eef1a1d5943eda1d20bcffb37fac440c", "size": 868, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/geometry.cpp", "max_stars_repo_name": "seanyen/eigenpy", "max_stars_repo_head_hexsha": "e164f03eb13b5fc531dd6b5e7e0f28560f405464", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-12-25T10:05:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:14:25.000Z", "max_issues_repo_path": "unittest/geometry.cpp", "max_issues_repo_name": "seanyen/eigenpy", "max_issues_repo_head_hexsha": "e164f03eb13b5fc531dd6b5e7e0f28560f405464", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 123.0, "max_issues_repo_issues_event_min_datetime": "2015-04-29T09:48:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T02:26:33.000Z", "max_forks_repo_path": "unittest/geometry.cpp", "max_forks_repo_name": "seanyen/eigenpy", "max_forks_repo_head_hexsha": "e164f03eb13b5fc531dd6b5e7e0f28560f405464", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T00:45:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T11:25:43.000Z", "avg_line_length": 18.0833333333, "max_line_length": 56, "alphanum_fraction": 0.7211981567, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5024910132911677}}
{"text": "#pragma once\n\n#include \"mckinnc_ekf/common.hpp\"\n\n#include <vector>\n#include <Eigen/Dense>\n\n/*! \\file\n *  \\brief EKF localization algorithm with support for na&iuml;ve SLAM.\n */\n\nnamespace mckinnc_ekf {\n\n//! 3x3 matrix of doubles representing covariance of a 3-vector.\ntypedef Eigen::Matrix3d Covariance;\n\nclass EKF {\n  public:\n    EKF(const Covariance& modelCovariance,\n        const Observation& observationVariance);\n\n    //! Run a single update of the EKF localization.\n    /*!\n     *  \\param control\n     *  Linear and angular robot controls for the period since the last run,\n     *  and the elapsed time since the last run.\n     *  \\param observations\n     *  Observations of the landmarks.\n     *  \\param likelyLandmarks\n     *  Landmarks that the observations are likely to correspond to.\n     *  \\param newLandmarkUncertaintyThreshold\n     *  Uncertainty above which an observation will be considered a new\n     *  landmark, and will not be used for correction. Set to `INFINITY` to\n     *  always find a landmark for an observation.\n     *  \\return\n     *  New landmarks from unmatched observations.\n     */\n    std::vector<Landmark> run(const Control& control,\n        const std::vector<Observation>& observations,\n        const std::vector<Landmark>& likelyLandmarks,\n        double newLandmarkUncertaintyThreshold);\n\n    //! Current mean of the pose estimation.\n    const Pose& mean() { return mean_; }\n    //! Current covariance of the pose estimation.\n    const Covariance& covariance() { return covariance_; }\n\n  protected:\n    Pose mean_;\n    Covariance covariance_;\n    Covariance modelCovariance_;\n    Eigen::DiagonalMatrix<double, 3> observationCovariance_;\n};\n\n} // namespace\n", "meta": {"hexsha": "5a32f6bf5324bbc7635a19071a9a972fc8d7137e", "size": 1697, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/mckinnc_ekf/include/mckinnc_ekf/ekf.hpp", "max_stars_repo_name": "forember/ros-vagrant-xfce4", "max_stars_repo_head_hexsha": "8a2a8d4766745c1137869bf0980b1f639b49bc2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/mckinnc_ekf/include/mckinnc_ekf/ekf.hpp", "max_issues_repo_name": "forember/ros-vagrant-xfce4", "max_issues_repo_head_hexsha": "8a2a8d4766745c1137869bf0980b1f639b49bc2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/mckinnc_ekf/include/mckinnc_ekf/ekf.hpp", "max_forks_repo_name": "forember/ros-vagrant-xfce4", "max_forks_repo_head_hexsha": "8a2a8d4766745c1137869bf0980b1f639b49bc2e", "max_forks_repo_licenses": ["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.3035714286, "max_line_length": 76, "alphanum_fraction": 0.6965232764, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5024910104863313}}
{"text": "/*\n * Copyright (c) 2009 Carnegie Mellon University.\n *     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,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n *\n */\n\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <vector>\n#include <map>\n#include <time.h>\n\n#include <boost/config/warning_disable.hpp>\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_stl.hpp>\n\n#include <graphlab.hpp>\n#include <graphlab/graph/distributed_graph.hpp>\n\n//shared parameters\nfloat gaussian_kernel_scale_parameter = 0.1;\nfloat threshold_to_discard_small_similarities = 0.0;\nsize_t number_of_nearest_neighbors= 20;\n\n\n//data point\nstruct vertex_data {\n  std::vector<float> x;\n  float D_ii;\n  vertex_data():x(), D_ii(0.0) {};\n  explicit vertex_data(const std::vector<float>& x_in) :\n      x(x_in), D_ii(0.0) {}\n\n  void save(graphlab::oarchive& oarc) const {\n    oarc << x.size();\n    for(size_t i=0;i<x.size();++i)\n      oarc << x[i];\n    oarc << D_ii;\n  }\n\n  void load(graphlab::iarchive& iarc) {\n    size_t size = 0;\n    iarc >> size;\n    for(size_t i=0;i<size;++i){\n      float temp = 0.0;\n      iarc >> temp;\n      x.push_back(temp);\n    }\n    iarc >> D_ii;\n  }\n};\n\n//similarity\nstruct edge_data{\n  float A_ij;\n  bool nearest;\n  edge_data() : A_ij(0.0), nearest(false){}\n  void save(graphlab::oarchive& oarc) const {\n    oarc << A_ij << nearest;\n  }\n  void load(graphlab::iarchive& iarc) {\n    iarc >> A_ij >> nearest;\n  }\n};\n\ntypedef graphlab::distributed_graph<vertex_data, edge_data> graph_type;\n\n\n//[vertex_id] [element1] [element2] [element3] ...\nbool line_parser(graph_type& graph, const std::string& filename,\n    const std::string& line) {\n  if (line.empty()) return true;\n  size_t id = 0;\n  namespace qi = boost::spirit::qi;\n  namespace ascii = boost::spirit::ascii;\n  namespace phoenix = boost::phoenix;\n  vertex_data vtx;\n  const bool success = qi::phrase_parse\n    (line.begin(), line.end(),\n     //  Begin grammar\n     (\n      qi::ulong_[phoenix::ref(id) = qi::_1] >> -qi::char_(\",\") >>\n      (qi::double_[phoenix::push_back(phoenix::ref(vtx.x), qi::_1)] % -qi::char_(\",\") )\n      )\n     ,\n     //  End grammar\n     ascii::space);\n  if (!success) return false;\n  graph.add_vertex(id, vtx);\n\n  for(size_t i=1;i<id;++i){\n    graph.add_edge(i, id);\n  }\n\n  return true;\n}\n\n// helper function to compute similarity between points\nfloat similarity(const std::vector<float>& v1, const std::vector<float>& v2) {\n  float ret = 0.0;\n  for (size_t i = 0; i < v1.size(); ++i) {\n    float tmp = v1[i] - v2[i];\n    ret += tmp * tmp;\n  }\n  return exp(-ret / gaussian_kernel_scale_parameter);\n}\n\n//calculate similarities between data points\nvoid calc_similarities(graph_type::edge_type& edata) {\n  edata.data().A_ij = similarity(edata.source().data().x, edata.target().data().x);\n}\n\n\n//discard small similarities (Optional)\nvoid discard_small_similarity(graph_type::edge_type& edata) {\n  if(edata.data().A_ij < threshold_to_discard_small_similarities)\n    edata.data().A_ij = 0.0;\n}\n\n\n//gather T-nearest neighbor (Optional)\nstruct top_t_similarity{\n  std::vector<size_t> ids;\n  std::vector<float> sims;\n  top_t_similarity(): ids(number_of_nearest_neighbors, std::numeric_limits<size_t>::max()),\n      sims(number_of_nearest_neighbors, -1.0){}\n  top_t_similarity(size_t id, float sim): ids(number_of_nearest_neighbors, std::numeric_limits<size_t>::max()),\n      sims(number_of_nearest_neighbors, -1.0){\n    ids[0] = id;\n    sims[0] = sim;\n  }\n\n  top_t_similarity& operator+=(const top_t_similarity& other){\n    std::vector<size_t> new_ids;\n    std::vector<float> new_sims;\n    size_t pos1=0;\n    size_t pos2=0;\n    while(pos1+pos2 < number_of_nearest_neighbors){\n      if(sims[pos1] >= other.sims[pos2]){\n        new_ids.push_back(ids[pos1]);\n        new_sims.push_back(sims[pos1]);\n        pos1++;\n      }else{\n        new_ids.push_back(other.ids[pos2]);\n        new_sims.push_back(other.sims[pos2]);\n        pos2++;\n      }\n    }\n    ids = new_ids;\n    sims = new_sims;\n    return *this;\n  }\n\n  void save(graphlab::oarchive& oarc) const {\n    oarc << ids.size();\n    for(size_t i=0;i<ids.size();++i)\n      oarc << ids[i];\n    for(size_t i=0;i<sims.size();++i)\n      oarc << sims[i];\n  }\n  void load(graphlab::iarchive& iarc) {\n    ids.clear();\n    sims.clear();\n    size_t size = 0;\n    iarc >> size;\n    for(size_t i=0;i<size;++i){\n      size_t id = 0;\n      iarc >> id;\n      ids.push_back(id);\n    }\n    for(size_t i=0;i<size;++i){\n      float sim = 0;\n      iarc >> sim;\n      sims.push_back(sim);\n    }\n  }\n};\n\n//get T-nearest neighbor and discard others (Optional)\nclass t_nearest: public graphlab::ivertex_program<graph_type,\n  top_t_similarity>, public graphlab::IS_POD_TYPE {\nprivate:\n  float threshold;\n\npublic:\n  t_nearest():threshold(0.0){}\n\n  edge_dir_type gather_edges(icontext_type& context,\n      const vertex_type& vertex) const {\n    return graphlab::ALL_EDGES;\n  }\n  top_t_similarity gather(icontext_type& context, const vertex_type& vertex,\n      edge_type& edge) const {\n    if(edge.target().id() == vertex.id()){//in edge\n      return top_t_similarity(edge.source().id(), edge.data().A_ij);\n    }else{//out edge\n      return top_t_similarity(edge.target().id(), edge.data().A_ij);\n    }\n  }\n\n  //assign a cluster, considering the clusters of neighbors\n  void apply(icontext_type& context, vertex_type& vertex,\n      const gather_type& total) {\n    threshold = total.sims[number_of_nearest_neighbors-1];\n//    std::cout << vertex.id() << \"\\t\" << total.ids[0] << \"-\" << total.sims[0] << \", \"\n//        << total.ids[1] << \"-\" << total.sims[1] << std::endl;\n  }\n\n  edge_dir_type scatter_edges(icontext_type& context,\n      const vertex_type& vertex) const {\n      return graphlab::ALL_EDGES;\n  }\n  void scatter(icontext_type& context, const vertex_type& vertex,\n      edge_type& edge) const {\n    if(edge.data().A_ij >= threshold)\n      edge.data().nearest = true;\n  }\n};\n\n//discard small similarities (Optional)\nvoid make_other_similarities_zero(graph_type::edge_type& edata) {\n  if(edata.data().nearest == false)\n    edata.data().A_ij = 0.0;\n}\n\n\n//compute sums over rows and then take inverse square root\nclass calc_degrees: public graphlab::ivertex_program<graph_type,\n    float>, public graphlab::IS_POD_TYPE {\npublic:\n  //gather A_ij\n  edge_dir_type gather_edges(icontext_type& context,\n      const vertex_type& vertex) const {\n    return graphlab::ALL_EDGES;\n  }\n  float gather(icontext_type& context, const vertex_type& vertex,\n      edge_type& edge) const {\n    return edge.data().A_ij;\n  }\n\n  //assign a cluster, considering the clusters of neighbors\n  void apply(icontext_type& context, vertex_type& vertex,\n      const gather_type& total) {\n    vertex.data().D_ii = 1.0 / sqrt(total);\n  }\n\n  edge_dir_type scatter_edges(icontext_type& context,\n      const vertex_type& vertex) const {\n      return graphlab::NO_EDGES;\n  }\n  void scatter(icontext_type& context, const vertex_type& vertex,\n      edge_type& edge) const {\n  }\n};\n\n//multiply D^-1/2\nvoid mult_D(graph_type::edge_type& edata) {\n  edata.data().A_ij = edata.data().A_ij * edata.source().data().D_ii * edata.target().data().D_ii;\n}\n\nstruct max_min_similarity{\n  float max_sim;\n  float min_sim;\n\n  max_min_similarity(): max_sim(0.0), min_sim(0.0){}\n  explicit max_min_similarity(float similarity): max_sim(similarity),\n      min_sim(similarity){}\n\n  max_min_similarity& operator+=(const max_min_similarity& other){\n    if(max_sim < 1.0 && other.max_sim < 1.0){\n      max_sim = std::max(max_sim, other.max_sim);\n    }else if(other.max_sim < 1.0){\n      max_sim = other.max_sim;\n    }\n    if(min_sim > 0.0 && other.min_sim > 0.0){\n      min_sim = std::min(min_sim, other.min_sim);\n    }else if(other.min_sim > 0.0){\n      min_sim = other.min_sim;\n    }\n    return *this;\n  }\n  void save(graphlab::oarchive& oarc) const {\n    oarc << max_sim << min_sim;\n  }\n  void load(graphlab::iarchive& iarc) {\n    iarc >> max_sim >> min_sim;\n  }\n};\nmax_min_similarity absolute_edge_data(const graph_type::edge_type& edge) {\n  return max_min_similarity(edge.data().A_ij);\n}\n\nstruct max_vid{\n  size_t vid;\n  max_vid(): vid(0){}\n  explicit max_vid(size_t in_vid): vid(in_vid){}\n\n  max_vid& operator+=(const max_vid& other){\n    vid = std::max(vid, other.vid);\n    return *this;\n  }\n  void save(graphlab::oarchive& oarc) const {\n    oarc << vid;\n  }\n  void load(graphlab::iarchive& iarc) {\n    iarc >> vid;\n  }\n};\nmax_vid absolute_vertex_data(const graph_type::vertex_type& vertex) {\n  return max_vid(vertex.id());\n}\n\nclass graph_writer {\npublic:\n  std::string save_vertex(graph_type::vertex_type v) {\n    std::stringstream strm;\n    size_t vid = v.id();\n    if(vid == 0)\n      return \"\";\n    strm << vid << \" \" << vid << \" 1.0\\n\";\n    return strm.str();\n  }\n\n  std::string save_edge(graph_type::edge_type e) {\n    const float& A_ij = e.data().A_ij;\n    std::stringstream strm;\n    if(A_ij > 0.0){\n      strm << e.source().id() << \" \" << e.target().id() << \" \" <<\n          A_ij << \"\\n\";\n      strm << e.target().id() << \" \" << e.source().id() << \" \" <<\n          A_ij << \"\\n\";\n    }\n    return strm.str();\n  }\n};\n\nint main(int argc, char** argv) {\n  std::cout << \"construct graph Laplacian for spectral clustering.\\n\\n\";\n\n  //parse command line\n  std::string datafile;\n  graphlab::command_line_options clopts\n    (\"Constructing graph Laplacian for spectral clustering\");\n  clopts.attach_option(\"data\", datafile,\n                       \"Input file. Each line hold a sample id followed by a white-space or \"\n                       \"comma separated numeric vector. Id should start from 1\");\n  clopts.attach_option(\"sigma\",  gaussian_kernel_scale_parameter,\n                       \"Scale parameter for Gaussian kernel.\");\n  clopts.attach_option(\"similarity-thres\", threshold_to_discard_small_similarities,\n                       \"Threshold to discard small similarities. \");\n  clopts.attach_option(\"t-nearest\", number_of_nearest_neighbors,\n                      \"Number of nearest neighbors (=t). Will use only the t-nearest similarities \"\n                      \"for each datapoint. If set at 0, will use all similarities.\");\n  if(!clopts.parse(argc, argv)) return EXIT_FAILURE;\n  if (datafile == \"\") {\n    std::cout << \"--data is not optional\\n\";\n    return EXIT_FAILURE;\n  }\n  gaussian_kernel_scale_parameter *= 2.0*gaussian_kernel_scale_parameter;\n\n  //construct graph\n  graphlab::mpi_tools::init(argc, argv);\n  graphlab::distributed_control dc;\n  graph_type graph(dc, clopts);\n  graph.load(\n      datafile,\n      line_parser);\n  graph.finalize();\n\n  time_t start, end;\n  time(&start);\n  size_t data_num = graph.map_reduce_vertices<max_vid>(absolute_vertex_data).vid;\n\n  //calculate similarities\n  graph.transform_edges(calc_similarities);\n\n  //show the max similarity less than 1 and the min similarity grater than 0\n  max_min_similarity stat = graph.map_reduce_edges<max_min_similarity>(absolute_edge_data);\n  dc.cout() << \"max squared distance(min similarity): \"\n      << -log(stat.min_sim)*gaussian_kernel_scale_parameter\n      << \"(\" << stat.min_sim << \")\\n\"\n      << \"min squared distance(max similarity):\"\n      << -log(stat.max_sim)*gaussian_kernel_scale_parameter\n      << \"(\" << stat.max_sim << \")\\n\";\n\n\n  //if t is set, use only t-nearest similarities\n  if(number_of_nearest_neighbors > 0){\n    if(number_of_nearest_neighbors > data_num-1)\n      number_of_nearest_neighbors = data_num-1;\n    dc.cout() << \"use only the \" << number_of_nearest_neighbors\n        << \"-nearest similarities for each datapoint\\n\";\n    graphlab::omni_engine<t_nearest> engine_nearest(dc, graph, \"sync\", clopts);\n    engine_nearest.signal_all();\n    engine_nearest.start();\n    graph.transform_edges(make_other_similarities_zero);\n  }\n  //if threshold is set, discard similarities less then the threshold\n  if(threshold_to_discard_small_similarities > 0.0){\n    dc.cout() << \"discard small similarities less than \"\n        << threshold_to_discard_small_similarities << \"\\n\";\n    graph.transform_edges(discard_small_similarity);\n  }\n\n  //sum elements over rows (calculate the degree matrix D)\n  graphlab::omni_engine<calc_degrees> engine(dc, graph, \"sync\", clopts);\n  engine.signal_all();\n  engine.start();\n  //multiply D\n  graph.transform_edges(mult_D);\n  time(&end);\n\n  dc.cout() << \"graph calculation time is \" << (end - start) << \" sec\\n\";\n  dc.cout() << \"writing...\\n\";\n\n  //write results\n  const std::string outputname = datafile + \".glap\";\n  graph.save(\n      outputname + \"_diag\",\n      graph_writer(), false, //set to true if each output file is to be gzipped\n      true, //whether vertices are saved\n      false,1); //whether edges are saved\n  graph.save(\n      outputname + \"_other\",\n      graph_writer(), false, //set to true if each output file is to be gzipped\n      false, //whether vertices are saved\n      true,1); //whether edges are saved\n\n  //write the number of data\n  const std::string datanum_filename = datafile + \".datanum\";\n  std::ofstream ofs(datanum_filename.c_str());\n  if(!ofs) {\n    std::cout << \"can't create file for number of data\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  ofs << data_num;\n\n  graphlab::mpi_tools::finalize();\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "40c6110b27aef953a58093e52f6a024471caeb15", "size": 13784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/clustering/graph_laplacian_for_sc.cpp", "max_stars_repo_name": "RealM10/package", "max_stars_repo_head_hexsha": "3bcec9b677226ee0395e82e908f542aba0ecaad7", "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/clustering/graph_laplacian_for_sc.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/clustering/graph_laplacian_for_sc.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": 29.9652173913, "max_line_length": 111, "alphanum_fraction": 0.6604033662, "num_tokens": 3715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5024910092248143}}
{"text": "#include <Engine/MeshEdit/Parameterize_ASAP.h>\n#include <Eigen/Sparse>\n\nusing namespace Ubpa;\nusing namespace std;\n\nParameterize_ASAP::Parameterize_ASAP(Ptr<TriMesh> triMesh)\n\t:Paramaterize_Basic::Paramaterize_Basic(triMesh)\n{\n\tnP = nV = 0;\n}\n\nParameterize_ASAP::~Parameterize_ASAP()\n{\n\tClear();\n}\n\nvoid Parameterize_ASAP::Parameterization()\n{\n\tclock_t time = clock();\n\tnP = heMesh->NumPolygons();\n\tnV = heMesh->NumVertices();\n\tLocal_Flatten();\n\tInit_Matrix();\n\tSolve();\n\tcout << \"Time:\" <<  clock()- time << endl;\n}\n\n\ncoff_map Parameterize_ASAP::Map_Add(coff_map map1, coff_map map2)\n{\n\tcoff_map result = map1;\n\tfor (auto iter2 = map2.begin(); iter2 != map2.end(); iter2++)\n\t{\n\t\tif (!result.count(iter2->first))\n\t\t\tresult[iter2->first] = iter2->second;\n\t\telse\n\t\t\tresult[iter2->first] += iter2->second;\n\t}\n\treturn result;\n}\n\ndouble Parameterize_ASAP::Map_Derivation(coff_map map_, size_t elem)\n{\n\treturn map_[elem];\n}\n\ncoff_map Parameterize_ASAP::Map_Multiply(coff_map map_, double coef)\n{\n\tcoff_map result;\n\tfor (auto iter = map_.begin(); iter != map_.end(); iter++)\n\t{\n\t\tresult.insert(coff_map::value_type(iter->first, iter->second * coef));\n\t}\n\treturn result;\n}\n\nstd::vector<coff_map> Parameterize_ASAP::Get_elem_map(size_t t, size_t i)\n{\n\tstd::vector<coff_map> elem_vec;\n\tcoff_map elem_x, elem_y;\n\tdouble C1 = 0;\n\tcoff_map C2, C3;\n\tfor (size_t k = 0; k < 3; k++)\n\t{\n\t\tC1 += cotangent_list[t][k] * (delta_x_list[t][k] * delta_x_list[t][k] + delta_y_list[t][k] * delta_y_list[t][k]);\n\t\tC2.insert(coff_map::value_type(vertices_index_hemesh[t][k], cotangent_list[t][k] * delta_x_list[t][k]));\t// x\n\t\tC2.insert(coff_map::value_type(vertices_index_hemesh[t][k] + nV, cotangent_list[t][k] * delta_y_list[t][k]));\t//\ty\n\t\tC2.insert(coff_map::value_type(vertices_index_hemesh[t][(k+1)%3], -cotangent_list[t][k] * delta_x_list[t][k]));\t// x\n\t\tC2.insert(coff_map::value_type(vertices_index_hemesh[t][(k+1)%3] + nV, -cotangent_list[t][k] * delta_y_list[t][k]));\t//\ty\n\n\t\tC3.insert(coff_map::value_type(vertices_index_hemesh[t][k], cotangent_list[t][k] * delta_y_list[t][k]));\t// x\n\t\tC3.insert(coff_map::value_type(vertices_index_hemesh[t][k] + nV, -cotangent_list[t][k] * delta_x_list[t][k]));\t//\ty\n\t\tC3.insert(coff_map::value_type(vertices_index_hemesh[t][(k + 1) % 3], -cotangent_list[t][k] * delta_y_list[t][k]));\t// x\n\t\tC3.insert(coff_map::value_type(vertices_index_hemesh[t][(k + 1) % 3] + nV, cotangent_list[t][k] * delta_x_list[t][k]));\t//\ty\n\t}\n\telem_x.insert(coff_map::value_type(vertices_index_hemesh[t][i], 1));\n\telem_x.insert(coff_map::value_type(vertices_index_hemesh[t][(i+1)%3], -1));\n\telem_y.insert(coff_map::value_type(vertices_index_hemesh[t][i], 1));\n\telem_y.insert(coff_map::value_type(vertices_index_hemesh[t][(i + 1) % 3], -1));\n\n\telem_x = Map_Add(elem_x, Map_Multiply(C2, -delta_x_list[t][i] / C1));\n\telem_x = Map_Add(elem_x, Map_Multiply(C3, -delta_y_list[t][i] / C1));\n\telem_y = Map_Add(elem_y, Map_Multiply(C2, -delta_y_list[t][i] / C1));\n\telem_y = Map_Add(elem_y, Map_Multiply(C3, delta_x_list[t][i] / C1));\n\t\n\telem_vec.push_back(elem_x);\n\telem_vec.push_back(elem_y);\n\tfor (size_t t = 0; t < 2; t++)\n\t{\n\t\tfor (auto it = elem_vec[t].begin(); it != elem_vec[t].end(); it++)\n\t\t\tcout << \"(\" << it->first << \", \" << it->second << \") \";\n\t\tcout << endl;\n\t}\n\n\n\treturn elem_vec;\n}\n\nvoid Parameterize_ASAP::Init_Matrix()\n{\n\tvector<Eigen::Triplet<double>> Lij;\n\tfor (size_t n = 0; n < nV; n++)\n\t{\n\t\tcoff_map coefn[2];\n\t\tfor (size_t t = 0; t < nP; t++)\n\t\t{\n\t\t\tfor (size_t i = 0; i < 3; i++)\n\t\t\t{\n\t\t\t\tvector<coff_map> elem_map = Get_elem_map(t, i);\n\t\t\t\tfor (size_t k = 0; k < 2; k++)\n\t\t\t\t{\n\t\t\t\t\tcoff_map elem = elem_map[k];\n\t\t\t\t\telem = Map_Multiply(Map_Multiply(elem, Map_Derivation(elem, vertices_index_hemesh[t][i]*(k+1))),cotangent_list[t][i]);\n\t\t\t\t\tcoefn[k] = Map_Add(coefn[k], elem);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (size_t k = 0; k < 2; k++)\n\t\t{\n\t\t\tfor (auto iter = coefn[k].begin(); iter != coefn[k].end(); iter++)\n\t\t\t\tif((n<2||(n>=nV&&n<nV+2))&&n==iter->first)\n\t\t\t\t\tLij.push_back(Eigen::Triplet<double>(n*(k+1), iter->first, 1));\n\t\t\t\telse\n\t\t\t\t\tLij.push_back(Eigen::Triplet<double>(n*(k+1), iter->first, iter->second));\n\t\t}\n\t}\n\tCoef_matrix.resize(2 * nV, 2 * nV);\n\tCoef_matrix.setZero();\n\tb_vector.resize(nV * 2);\n\tb_vector.setZero();\n\tb_vector(0) = heMesh->Vertices()[0]->pos[0];\n\tb_vector(0) = heMesh->Vertices()[0]->pos[0];\n\tb_vector(nV) = heMesh->Vertices()[0]->pos[1];\n\tb_vector(nV+1) = heMesh->Vertices()[0]->pos[1];\n\n\tCoef_matrix.setFromTriplets(Lij.begin(), Lij.end());\n\tcout << Coef_matrix;\n\t\n}\n\nvoid Parameterize_ASAP::Solve()\n{\n\tEigen::VectorXd X(2 * nV + 4 * nP);\n\n\tcout << \"Solving Equation...\" << endl;\n\tsolver.compute(Coef_matrix);\n\tX = solver.solve(b_vector);\n\tcout << \"Solving complete\" << endl;\n\n\tfor (size_t i = 0; i < nV; i++)\n\t{\n\t\ttexcoords.push_back(pointf2(X(i), X(i+nV)));\n\t\theMesh->Vertices()[i]->pos.at(0) = X(i);\n\t\theMesh->Vertices()[i]->pos.at(1) = X(i + nV);\n\t\theMesh->Vertices()[i]->pos.at(2) = 0;\n\t}\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nsize_t Parameterize_ASAP::Get_a_index(size_t t)\n{\n\treturn 2 * nV + t;\n}\n\nsize_t Parameterize_ASAP::Get_b_index(size_t t)\n{\n\treturn 2 * nV + nP + t;\n}\n\nveci2 Parameterize_ASAP::Get_u_index(size_t index)\n{\n\treturn veci2(index * 2, index * 2 + 1);\n}\n\nbool Parameterize_ASAP::map_update(size_t index, coff_map& map)\n{\n\tif (index > 2)//\tnot fixed\n\t{\n\t\tif (!map.count(index-3))\n\t\t{\n\t\t\tmap.insert(coff_map::value_type(index - 3, 0));\n\t\t\tmap.insert(coff_map::value_type(index + nV - 6, 0));\n\t\t}\n\t\treturn true;\n\t}\n\telse\n\t\treturn false;\t//\tfixed\n}\n\nstd::vector<std::vector<double>> Parameterize_ASAP::Get_delta_list(size_t index)\n{\n\tif (index)\n\t\treturn delta_y_list;\n\telse\n\t\treturn delta_x_list;\n}", "meta": {"hexsha": "aca1f53a6bc5b78080f5c0cca3f7f67e7ea9a334", "size": 5727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/Parameterize_ASAP.cpp", "max_stars_repo_name": "Chaphlagical/USTC_CG", "max_stars_repo_head_hexsha": "9f8b0321e09e5a05afb1c93303e3c736f78503fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T03:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T01:25:02.000Z", "max_issues_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/Parameterize_ASAP.cpp", "max_issues_repo_name": "lyf7115/USTC_CG", "max_issues_repo_head_hexsha": "9f8b0321e09e5a05afb1c93303e3c736f78503fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/Parameterize_ASAP.cpp", "max_forks_repo_name": "lyf7115/USTC_CG", "max_forks_repo_head_hexsha": "9f8b0321e09e5a05afb1c93303e3c736f78503fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-06-13T13:14:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T07:36:05.000Z", "avg_line_length": 28.9242424242, "max_line_length": 126, "alphanum_fraction": 0.643967173, "num_tokens": 1945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5024910026354259}}
{"text": "/*\n * Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// check memory allocation in some method\n#define EIGEN_RUNTIME_NO_MALLOC\n\n// includes\n// std\n#include <iostream>\n\n// boost\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE PTransformd test\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/unit_test.hpp>\n\n// SpaceVecAlg\n#include <SpaceVecAlg/Conversions.h>\n\nnamespace sva\n{\nstatic constexpr double PI = boost::math::constants::pi<double>();\n}\n\nBOOST_AUTO_TEST_CASE(ConversionsHomogeneous)\n{\n  using namespace Eigen;\n  using namespace sva;\n\n  Matrix4d hom = Matrix4d::Zero();\n  hom(0, 1) = -1;\n  hom(1, 0) = +1;\n  hom(2, 2) = +1;\n  hom(3, 3) = +1;\n  PTransformd pt = conversions::fromHomogeneous(hom, conversions::RightHanded);\n\n  const Vector4d vec(4, 3, 2, 1);\n  Matrix4d homVec = Matrix4d::Identity();\n  homVec.block<4, 1>(0, 3) = vec;\n  PTransformd ptVec = conversions::fromHomogeneous(homVec, conversions::RightHanded);\n\n  Matrix4d hom2 = conversions::toHomogeneous(pt, conversions::RightHanded);\n\n  const PTransformd rotatedPT = ptVec * pt;\n  const Vector4d rotated = hom * vec;\n  const Vector4d rotated2 = hom2 * vec;\n\n  BOOST_CHECK_EQUAL(rotated, rotated2);\n  BOOST_CHECK_EQUAL((rotated.block<3, 1>(0, 0)), rotatedPT.translation());\n}\n\nBOOST_AUTO_TEST_CASE(ConversionsEigenTransform)\n{\n  using namespace Eigen;\n  using namespace sva;\n\n  PTransformd pt(sva::RotX(sva::PI / 2) * sva::RotZ(sva::PI / 4), Eigen::Vector3d(1., 2., 3.));\n  conversions::affine3_t<double> et = conversions::toAffine(pt, conversions::RightHanded);\n  PTransformd pt2 = conversions::fromAffine(et, conversions::RightHanded);\n\n  BOOST_CHECK_SMALL(sva::transformError(pt, pt2).vector().norm(), 1e-12);\n\n  conversions::affine3_t<double> etL = conversions::toAffine(pt, conversions::LeftHanded);\n  PTransformd pt3 = conversions::fromAffine(etL, conversions::LeftHanded);\n\n  BOOST_CHECK_SMALL(sva::transformError(pt, pt3).vector().norm(), 1e-12);\n\n  Eigen::Vector3d vec(5, 7, 12);\n\n  sva::PTransformd transformed = sva::PTransformd(vec) * pt;\n  Eigen::Vector3d affineTransformed = et * vec;\n\n  std::cout << transformed.translation().transpose() << std::endl;\n  std::cout << affineTransformed.transpose() << std::endl;\n\n  BOOST_CHECK_EQUAL(transformed.translation(), affineTransformed);\n}\n", "meta": {"hexsha": "f67f686ed3209be8a25313df75063a384abf88bd", "size": 2295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/ConversionsTest.cpp", "max_stars_repo_name": "gergondet/SpaceVecAlg", "max_stars_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "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": "tests/ConversionsTest.cpp", "max_issues_repo_name": "gergondet/SpaceVecAlg", "max_issues_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "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/ConversionsTest.cpp", "max_forks_repo_name": "gergondet/SpaceVecAlg", "max_forks_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "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.0506329114, "max_line_length": 95, "alphanum_fraction": 0.7241830065, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5024910026354259}}
{"text": "#include \"gtest/gtest.h\"\n\n#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <cassert>\n#include <omp.h>\n\n#include <dataset.h>\n#include <Eigen/Dense>\n\n#include \"logging.h\"\n\n#include \"dbscan_vp.h\"\n\nnamespace {\nstatic const std::string CURRENT_TDIR( CURRENT_TEST_DIR );\n}\n\nusing namespace clustering;\n\nTEST( DBSCAN_VP, TwoClusters )\n{\n    Dataset::Ptr dset = Dataset::create();\n    dset->load_csv( CURRENT_TDIR + \"/csv/vptree01.csv\" );\n\n    DBSCAN_VP::Ptr dbs = boost::make_shared< DBSCAN_VP >( dset );\n    dbs->fit();\n    dbs->predict( 0.01, 5 );\n\n    const DBSCAN_VP::Labels& l = dbs->get_labels();\n\n    for ( size_t i = 0; i < l.size(); ++i ) {\n        LOG( INFO ) << \"Element = \" << i << \" cluster = \" << l[i];\n        if ( i < 5 ) {\n            EXPECT_EQ( l[i], 0 );\n        } else {\n            EXPECT_EQ( l[i], 1 );\n        }\n    }\n}\n\nTEST( DBSCAN_VP, OneCluster )\n{\n    Dataset::Ptr dset = Dataset::create();\n    dset->load_csv( CURRENT_TDIR + \"/csv/vptree02.csv\" );\n\n    DBSCAN_VP::Ptr dbs = boost::make_shared< DBSCAN_VP >( dset );\n    dbs->fit();\n    dbs->predict( 0.01, 5 );\n\n    const DBSCAN_VP::Labels& l = dbs->get_labels();\n\n    for ( size_t i = 0; i < l.size(); ++i ) {\n        LOG( INFO ) << \"Element = \" << i << \" cluster = \" << l[i];\n        if ( i < 6 ) {\n            EXPECT_EQ( l[i], 0 );\n        } else {\n            EXPECT_EQ( l[i], -1 );\n        }\n    }\n}\n\nTEST( DBSCAN_VP, NoClusters )\n{\n    Dataset::Ptr dset = Dataset::create();\n    dset->load_csv( CURRENT_TDIR + \"/csv/vptree03.csv\" );\n\n    DBSCAN_VP::Ptr dbs = boost::make_shared< DBSCAN_VP >( dset );\n    dbs->fit();\n    dbs->predict( 0.01, 2 );\n\n    const DBSCAN_VP::Labels& l = dbs->get_labels();\n\n    for ( size_t i = 0; i < l.size(); ++i ) {\n        LOG( INFO ) << \"Element = \" << i << \" cluster = \" << l[i];\n        EXPECT_EQ( l[i], -1 );\n    }\n}\n\nTEST( DBSCAN_VP, Iris )\n{\n    Dataset::Ptr dset = Dataset::create();\n    dset->load_csv( CURRENT_TDIR + \"/csv/iris.data.txt\" );\n\n    DBSCAN_VP::Ptr dbs = boost::make_shared< DBSCAN_VP >( dset );\n\n    dbs->fit();\n    dbs->predict( 0.4, 5 );\n\n    const DBSCAN_VP::Labels& l = dbs->get_labels();\n\n    for ( size_t i = 0; i < l.size(); ++i ) {\n        LOG( INFO ) << \"Element = \" << i << \" cluster = \" << l[i];\n    }\n}\n\nTEST( DBSCAN_VP, IrisAnalyze )\n{\n    Dataset::Ptr dset = Dataset::create();\n    dset->load_csv( CURRENT_TDIR + \"/csv/iris.data.txt\" );\n\n    DBSCAN_VP::Ptr dbs = boost::make_shared< DBSCAN_VP >( dset );\n\n    dbs->fit();\n    const auto r = dbs->predict_eps( 3u );\n\n    for ( size_t i = 0; i < r.size(); ++i ) {\n        std::cout << ( i + 1 ) << \",\" << r[i] << std::endl;\n    }\n}\n", "meta": {"hexsha": "a597dc30314b0879353c441a651693ac0484681c", "size": 2638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_dbscan_vp.cpp", "max_stars_repo_name": "houwenbo87/DBSCAN", "max_stars_repo_head_hexsha": "3452d32186f2b59f2f1e515cebdf0ce15cb3e2f7", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-18T22:40:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-18T22:40:39.000Z", "max_issues_repo_path": "tests/test_dbscan_vp.cpp", "max_issues_repo_name": "houwenbo87/DBSCAN", "max_issues_repo_head_hexsha": "3452d32186f2b59f2f1e515cebdf0ce15cb3e2f7", "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": "tests/test_dbscan_vp.cpp", "max_forks_repo_name": "houwenbo87/DBSCAN", "max_forks_repo_head_hexsha": "3452d32186f2b59f2f1e515cebdf0ce15cb3e2f7", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T11:06:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T11:06:53.000Z", "avg_line_length": 23.5535714286, "max_line_length": 66, "alphanum_fraction": 0.5352539803, "num_tokens": 840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5024910026354259}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\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#include <iostream>\n\n#include <geometry_test_common.hpp>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/geometry/algorithms/make.hpp>\n#include <boost/geometry/algorithms/append.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/concepts/linestring_concept.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <boost/geometry/io/dsv/write.hpp>\n\n#include <test_common/test_point.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\n#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n#include <initializer_list>\n#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n\n\ntemplate <typename P>\nbg::model::linestring<P> create_linestring()\n{   \n    bg::model::linestring<P> l1;\n    P p1;\n    bg::assign_values(p1, 1, 2, 3);\n    bg::append(l1, p1);\n    return l1;\n}\n\ntemplate <typename L, typename T>\nvoid check_linestring(L& to_check, T x, T y, T z)\n{\n    BOOST_CHECK_EQUAL(bg::get<0>(to_check[0]), x);\n    BOOST_CHECK_EQUAL(bg::get<1>(to_check[0]), y);\n    BOOST_CHECK_EQUAL(bg::get<2>(to_check[0]), z);\n}\n\ntemplate <typename P>\nvoid test_default_constructor()\n{\n    bg::model::linestring<P> l1(create_linestring<P>());\n    check_linestring(l1, 1, 2, 3);\n}\n\ntemplate <typename P>\nvoid test_copy_constructor()\n{\n    bg::model::linestring<P> l1 = create_linestring<P>();\n    check_linestring(l1, 1, 2, 3);\n}\n\ntemplate <typename P>\nvoid test_copy_assignment()\n{\n    bg::model::linestring<P> l1(create_linestring<P>()), l2;\n    l2 = l1;\n    check_linestring(l2, 1, 2, 3);\n}\n\ntemplate <typename P>\nvoid test_concept()\n{   \n    typedef bg::model::linestring<P> L;\n\n    BOOST_CONCEPT_ASSERT( (bg::concepts::ConstLinestring<L>) );\n    BOOST_CONCEPT_ASSERT( (bg::concepts::Linestring<L>) );\n\n    typedef typename bg::coordinate_type<L>::type T;\n    typedef typename bg::point_type<L>::type LP;\n    boost::ignore_unused<T, LP>();\n}\n\ntemplate <typename P>\nvoid test_all()\n{   \n    test_default_constructor<P>();\n    test_copy_constructor<P>();\n    test_copy_assignment<P>();\n    test_concept<P>();\n}\n\ntemplate <typename P>\nvoid test_custom_linestring(std::initializer_list<P> IL)\n{\n    bg::model::linestring<P> l1(IL);\n    std::ostringstream out;\n    out << bg::dsv(l1);\n    BOOST_CHECK_EQUAL(out.str(), \"((1, 2), (2, 3), (3, 4))\");\n}\n\ntemplate <typename P>\nvoid test_custom()\n{   \n#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n    std::initializer_list<P> IL = {P(1, 2), P(2, 3), P(3, 4)};\n    test_custom_linestring<P>(IL);\n#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n}\n\ntemplate <typename CS>\nvoid test_cs()\n{\n    test_all<bg::model::point<int, 3, CS> >();\n    test_all<bg::model::point<float, 3, CS> >();\n    test_all<bg::model::point<double, 3, CS> >();\n\n    test_custom<bg::model::point<double, 2, CS> >();\n}\n\n\nint test_main(int, char* [])\n{   \n    test_cs<bg::cs::cartesian>();\n    test_cs<bg::cs::spherical<bg::degree> >();\n    test_cs<bg::cs::spherical_equatorial<bg::degree> >();\n    test_cs<bg::cs::geographic<bg::degree> >();\n\n    test_custom<bg::model::d2::point_xy<double> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "3f32eee7e452d84cd625568da6729dc115f69d59", "size": 3571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/geometries/linestring.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": "test/geometries/linestring.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": "test/geometries/linestring.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.0656934307, "max_line_length": 79, "alphanum_fraction": 0.6989638757, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.7185944046238982, "lm_q1q2_score": 0.5024803233887255}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operations.hpp\n *\n * \\brief Include all supported operations.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n *\n * <hr/>\n *\n * Copyright (c) 2009, 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_OPERATIONS_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATIONS_HPP\n\n\n#include <boost/numeric/ublasx/operation/abs.hpp>\n#include <boost/numeric/ublasx/operation/all.hpp>\n#include <boost/numeric/ublasx/operation/any.hpp>\n#include <boost/numeric/ublasx/operation/arithmetic_ops.hpp>\n#include <boost/numeric/ublasx/operation/balance.hpp>\n#include <boost/numeric/ublasx/operation/begin.hpp>\n#include <boost/numeric/ublasx/operation/cat.hpp>\n#include <boost/numeric/ublasx/operation/cholesky.hpp>\n#include <boost/numeric/ublasx/operation/cond.hpp>\n#include <boost/numeric/ublasx/operation/cumsum.hpp>\n#include <boost/numeric/ublasx/operation/diag.hpp>\n#include <boost/numeric/ublasx/operation/dot.hpp>\n#include <boost/numeric/ublasx/operation/eigen.hpp>\n#include <boost/numeric/ublasx/operation/empty.hpp>\n#include <boost/numeric/ublasx/operation/end.hpp>\n#include <boost/numeric/ublasx/operation/eps.hpp>\n#include <boost/numeric/ublasx/operation/exp.hpp>\n//#include <boost/numeric/ublasx/operation/expm.hpp>\n#include <boost/numeric/ublasx/operation/eye.hpp>\n#include <boost/numeric/ublasx/operation/find.hpp>\n#include <boost/numeric/ublasx/operation/for_each.hpp>\n#include <boost/numeric/ublasx/operation/hilb.hpp>\n#include <boost/numeric/ublasx/operation/hold.hpp>\n#include <boost/numeric/ublasx/operation/illcond.hpp>\n#include <boost/numeric/ublasx/operation/inv.hpp>\n#include <boost/numeric/ublasx/operation/isfinite.hpp>\n#include <boost/numeric/ublasx/operation/isinf.hpp>\n#include <boost/numeric/ublasx/operation/linspace.hpp>\n#include <boost/numeric/ublasx/operation/log10.hpp>\n#include <boost/numeric/ublasx/operation/log2.hpp>\n#include <boost/numeric/ublasx/operation/log.hpp>\n#include <boost/numeric/ublasx/operation/logspace.hpp>\n#include <boost/numeric/ublasx/operation/lsq.hpp>\n#include <boost/numeric/ublasx/operation/lu.hpp>\n#include <boost/numeric/ublasx/operation/max.hpp>\n#include <boost/numeric/ublasx/operation/min.hpp>\n#include <boost/numeric/ublasx/operation/mldivide.hpp>\n#include <boost/numeric/ublasx/operation/mpow.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/pow.hpp>\n#include <boost/numeric/ublasx/operation/pow2.hpp>\n#include <boost/numeric/ublasx/operation/ql.hpp>\n#include <boost/numeric/ublasx/operation/qr.hpp>\n#include <boost/numeric/ublasx/operation/qz.hpp>\n#include <boost/numeric/ublasx/operation/rank.hpp>\n#include <boost/numeric/ublasx/operation/rcond.hpp>\n#include <boost/numeric/ublasx/operation/realmin.hpp>\n#include <boost/numeric/ublasx/operation/relational_ops.hpp>\n#include <boost/numeric/ublasx/operation/rep.hpp>\n#include <boost/numeric/ublasx/operation/reshape.hpp>\n#include <boost/numeric/ublasx/operation/rot90.hpp>\n#include <boost/numeric/ublasx/operation/round.hpp>\n#include <boost/numeric/ublasx/operation/seq.hpp>\n#include <boost/numeric/ublasx/operation/sign.hpp>\n#include <boost/numeric/ublasx/operation/size.hpp>\n#include <boost/numeric/ublasx/operation/sqr.hpp>\n#include <boost/numeric/ublasx/operation/sqrt.hpp>\n#include <boost/numeric/ublasx/operation/sum.hpp>\n#include <boost/numeric/ublasx/operation/svd.hpp>\n#include <boost/numeric/ublasx/operation/tanh.hpp>\n#include <boost/numeric/ublasx/operation/trace.hpp>\n#include <boost/numeric/ublasx/operation/transform.hpp>\n#include <boost/numeric/ublasx/operation/tril.hpp>\n#include <boost/numeric/ublasx/operation/triu.hpp>\n#include <boost/numeric/ublasx/operation/which.hpp>\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATIONS_HPP\n", "meta": {"hexsha": "81bf2d4553525d6643ae67b72fe6b1d5efd72fa7", "size": 3994, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operations.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/operations.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/operations.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": 43.4130434783, "max_line_length": 66, "alphanum_fraction": 0.7976965448, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5024803104568932}}
{"text": "/*\n * wave_equation.cpp\n *\n *  Created on: 11.07.2017\n *      Author: thies\n */\n\n#include <base/AdaptiveMesh.h>\n#include <base/ConstantMesh.h>\n#include <base/DiscretizedFunction.h>\n#include <base/SpaceTimeMesh.h>\n#include <base/Util.h>\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/numbers.h>\n#include <deal.II/base/point.h>\n#include <deal.II/base/quadrature.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria.h>\n#include <forward/L2RightHandSide.h>\n#include <forward/WaveEquation.h>\n#include <gtest/gtest.h>\n#include <norms/L2L2.h>\n#include <stddef.h>\n#include <iostream>\n#include <memory>\n#include <vector>\n\nnamespace {\n\nusing namespace dealii;\nusing namespace wavepi::forward;\nusing namespace wavepi::base;\nusing namespace wavepi;\n\ntemplate<int dim>\nclass TestF: public LightFunction<dim> {\npublic:\n   virtual ~TestF() = default;\n\n   virtual double evaluate(const Point<dim> &p, const double t) const {\n      if ((t <= 1) && (p.norm() < 0.5))\n         return std::sin(t * 2 * numbers::PI);\n      else\n         return 0.0;\n   }\n};\n\ntemplate<int dim>\nclass TestG: public LightFunction<dim> {\npublic:\n   virtual ~TestG() = default;\n\n   virtual double evaluate(const Point<dim> &p, const double t) const {\n      Point<dim> pc = Point<dim>::unit_vector(0);\n      pc *= 0.5;\n\n      if (std::abs(this->get_time() - 1.0) < 0.5 && (p.distance(pc) < 0.5))\n         return std::sin(this->get_time() * 1 * numbers::PI);\n      else\n         return 0.0;\n   }\n};\n\ntemplate<int dim>\nclass TestH: public LightFunction<dim> {\npublic:\n   virtual ~TestH() = default;\n\n   virtual double evaluate(const Point<dim> &p, const double t) const {\n      return p.norm() * this->get_time();\n   }\n};\n\ntemplate<int dim>\ndouble rho(const Point<dim> &p, double t) {\n   return p.norm() + t + 1.0;\n}\n\ntemplate<int dim>\ndouble c_squared(const Point<dim> &p, double t) {\n   double tmp = p.norm() * t + 1.0;\n\n   return tmp * tmp;\n}\n\ntemplate<int dim>\nclass TestC: public LightFunction<dim> {\npublic:\n   virtual ~TestC() = default;\n\n   virtual double evaluate(const Point<dim> &p, const double t) const {\n      return 1.0 / (rho(p, t) * c_squared(p, t));\n   }\n};\n\ntemplate<int dim>\nclass TestRho: public LightFunction<dim> {\npublic:\n   virtual ~TestRho() = default;\n\n   virtual double evaluate(const Point<dim> &p, const double t) const {\n      return rho(p, t);\n   }\n};\n\ntemplate<int dim>\nclass TestNu: public LightFunction<dim> {\npublic:\n   virtual ~TestNu() = default;\n\n   virtual double evaluate(const Point<dim> &p, const double t) const {\n      // do not just change this, reference_test_nu needs this\n      return p.norm() * t;\n   }\n};\n\ntemplate<int dim>\nclass RhsTestNu: public LightFunction<dim> {\npublic:\n   virtual ~RhsTestNu() = default;\n\n   virtual double evaluate(const Point<dim> &p, const double t) const {\n      // do not just change this, reference_test_nu needs this\n      return nu.evaluate(p, t) * v->evaluate(p, t);\n   }\n\n   RhsTestNu(const std::shared_ptr<LightFunction<dim>> &v)\n         : v(v) {\n      AssertThrow(v, ExcNotInitialized());\n   }\n\nprivate:\n   std::shared_ptr<LightFunction<dim>> v;  // pointer to u'\n   TestNu<dim> nu;\n};\n\ntemplate<int dim>\nclass TestQ: public LightFunction<dim> {\npublic:\n   virtual ~TestQ() = default;\n\n   virtual double evaluate(const Point<dim> &p, const double t) const override {\n      return p.norm() < 0.5 ? std::sin(t / 2 * 2 * numbers::PI) : 0.0;\n   }\n\n   static const Point<dim> q_position;\n};\n\ntemplate<>\nconst Point<1> TestQ<1>::q_position = Point<1>(-1.0);\ntemplate<>\nconst Point<2> TestQ<2>::q_position = Point<2>(-1.0, 0.5);\ntemplate<>\nconst Point<3> TestQ<3>::q_position = Point<3>(-1.0, 0.5, 0.0);\n\ntemplate<int dim>\nclass DiscretizedFunctionDisguise: public LightFunction<dim> {\npublic:\n   DiscretizedFunctionDisguise(std::shared_ptr<DiscretizedFunction<dim>> base)\n         : base(base) {\n   }\n   virtual ~DiscretizedFunctionDisguise() = default;\n\n   virtual double evaluate(const Point<dim> &p, const double t) const {\n      return base->value(p, t);\n   }\nprivate:\n   std::shared_ptr<DiscretizedFunction<dim>> base;\n};\n\n// checks, whether the matrix assembly of discretized parameters works correct\n// (by supplying DiscretizedFunctions and DiscretizedFunctionDisguises)\ntemplate<int dim>\nvoid run_discretized_test(int fe_order, int quad_order, int refines) {\n   Timer timer;\n\n   auto triangulation = std::make_shared<Triangulation<dim>>();\n   GridGenerator::hyper_cube(*triangulation, -1, 1);\n   Util::set_all_boundary_ids(*triangulation, 0);\n   triangulation->refine_global(refines);\n\n   double t_start = 0.0, t_end = 2.0, dt = t_end / 64.0;\n   std::vector<double> times;\n\n   for (size_t i = 0; t_start + i * dt <= t_end; i++)\n      times.push_back(t_start + i * dt);\n\n   FE_Q<dim> fe(fe_order);\n   Quadrature<dim> quad = QGauss<dim>(quad_order);  // exact in poly degree 2n-1 (needed: fe_dim^3)\n\n   std::shared_ptr<SpaceTimeMesh<dim>> mesh = std::make_shared<ConstantMesh<dim>>(times, fe, quad, triangulation);\n\n   deallog << std::endl << \"----------  n_dofs / timestep: \" << mesh->get_dof_handler(0)->n_dofs();\n   deallog << \", n_steps: \" << times.size() << \"  ----------\" << std::endl;\n\n   WaveEquation<dim> wave_eq(mesh);\n\n   /* continuous */\n\n   wave_eq.set_param_rho(std::make_shared<TestRho<dim>>());\n   wave_eq.set_param_c(std::make_shared<TestC<dim>>());\n   wave_eq.set_param_q(std::make_shared<TestQ<dim>>());\n   wave_eq.set_param_nu(std::make_shared<TestNu<dim>>());\n\n   timer.restart();\n   DiscretizedFunction<dim> sol_cont = wave_eq.run(\n         std::make_shared<L2RightHandSide<dim>>(std::make_shared<TestF<dim>>()), WaveEquation<dim>::Forward);\n   sol_cont.set_norm(std::make_shared<norms::L2L2<dim>>());\n\n   timer.stop();\n   deallog << \"continuous params: \" << std::fixed << timer.wall_time() << \" s of wall time\" << std::endl;\n   EXPECT_GT(sol_cont.norm(), 0.0);\n\n   /* discretized */\n\n   TestC<dim> c;\n   auto c_disc = std::make_shared<DiscretizedFunction<dim>>(mesh, c);\n   wave_eq.set_param_c(c_disc);\n\n   TestRho<dim> rho;\n   auto rho_disc = std::make_shared<DiscretizedFunction<dim>>(mesh, rho);\n   wave_eq.set_param_rho(rho_disc);\n\n   TestQ<dim> q;\n   auto q_disc = std::make_shared<DiscretizedFunction<dim>>(mesh, q);\n   wave_eq.set_param_q(q_disc);\n\n   TestNu<dim> nu;\n   auto nu_disc = std::make_shared<DiscretizedFunction<dim>>(mesh, nu);\n   wave_eq.set_param_nu(nu_disc);\n\n   TestF<dim> f;\n   auto f_disc = std::make_shared<DiscretizedFunction<dim>>(mesh, f);\n\n   timer.restart();\n   DiscretizedFunction<dim> sol_disc = wave_eq.run(std::make_shared<L2RightHandSide<dim>>(f_disc),\n         WaveEquation<dim>::Forward);\n   sol_disc.set_norm(std::make_shared<norms::L2L2<dim>>());\n   timer.stop();\n   deallog << \"all discretized: \" << std::fixed << timer.wall_time() << \" s of wall time\" << std::endl;\n   EXPECT_GT(sol_disc.norm(), 0.0);\n\n   /* discretized, q disguised */\n\n   auto c_disguised = std::make_shared<DiscretizedFunctionDisguise<dim>>(c_disc);\n   auto rho_disguised = std::make_shared<DiscretizedFunctionDisguise<dim>>(rho_disc);\n   auto q_disguised = std::make_shared<DiscretizedFunctionDisguise<dim>>(q_disc);\n   auto nu_disguised = std::make_shared<DiscretizedFunctionDisguise<dim>>(nu_disc);\n   auto f_disguised = std::make_shared<DiscretizedFunctionDisguise<dim>>(f_disc);\n\n   wave_eq.set_param_q(q_disguised);\n\n   timer.restart();\n   DiscretizedFunction<dim> sol_disc_except_q = wave_eq.run(std::make_shared<L2RightHandSide<dim>>(f_disc),\n         WaveEquation<dim>::Forward);\n   sol_disc_except_q.set_norm(std::make_shared<norms::L2L2<dim>>());\n   timer.stop();\n   deallog << \"all discretized, q disguised: \" << std::fixed << timer.wall_time() << \" s of wall time\" << std::endl;\n   EXPECT_GT(sol_disc_except_q.norm(), 0.0);\n\n   /* discretized, a disguised */\n\n   wave_eq.set_param_rho(rho_disguised);\n   wave_eq.set_param_q(q_disc);\n\n   timer.restart();\n   DiscretizedFunction<dim> sol_disc_except_a = wave_eq.run(std::make_shared<L2RightHandSide<dim>>(f_disc),\n         WaveEquation<dim>::Forward);\n   sol_disc_except_a.set_norm(std::make_shared<norms::L2L2<dim>>());\n   timer.stop();\n   deallog << \"all discretized, a disguised: \" << std::fixed << timer.wall_time() << \" s of wall time\" << std::endl;\n   EXPECT_GT(sol_disc_except_a.norm(), 0.0);\n\n   /* disguised */\n\n   wave_eq.set_param_nu(nu_disguised);\n   wave_eq.set_param_q(q_disguised);\n   wave_eq.set_param_rho(rho_disguised);\n   wave_eq.set_param_c(c_disguised);\n\n   timer.restart();\n   DiscretizedFunction<dim> sol_disguised = wave_eq.run(std::make_shared<L2RightHandSide<dim>>(f_disguised),\n         WaveEquation<dim>::Forward);\n   sol_disguised.set_norm(std::make_shared<norms::L2L2<dim>>());\n   timer.stop();\n   deallog << \"all discretized and disguised as continuous: \" << std::fixed << timer.wall_time() << \" s of wall time\"\n         << std::endl << std::endl;\n   EXPECT_GT(sol_disguised.norm(), 0.0);\n\n   /* results */\n   DiscretizedFunction<dim> tmp(sol_disc_except_q);\n   tmp -= sol_disguised;\n   double err_disguised_vs_disc_except_q = tmp.norm() / sol_disguised.norm();\n\n   deallog << \"rel. error between disguised discrete and discrete (q disguised): \" << std::scientific\n         << err_disguised_vs_disc_except_q << std::endl;\n   EXPECT_LT(err_disguised_vs_disc_except_q, 1e-6);\n\n   tmp = sol_disc_except_a;\n   tmp -= sol_disguised;\n   double err_disguised_vs_disc_except_a = tmp.norm() / sol_disguised.norm();\n\n   deallog << \"rel. error between disguised discrete and discrete (a disguised): \" << std::scientific\n         << err_disguised_vs_disc_except_a << std::endl;\n   EXPECT_LT(err_disguised_vs_disc_except_a, 1e-6);\n\n   tmp = sol_disc;\n   tmp -= sol_disguised;\n   double err_disguised_vs_disc = tmp.norm() / sol_disguised.norm();\n\n   deallog << \"rel. error between disguised discrete and full discrete: \" << std::scientific << err_disguised_vs_disc\n         << std::endl << std::endl;\n   EXPECT_LT(err_disguised_vs_disc, 1e-6);\n}\n\n// product of sines in space to have dirichlet b.c. in [0,pi], times a sum of sine and cosine in time.\n// its time derivative is the same function with C[1] = C[0]*norm(k), C[0] = -C[1]*norm(k)\ntemplate<int dim>\nclass SeparationAnsatz: public LightFunction<dim> {\npublic:\n   virtual ~SeparationAnsatz() = default;\n\n   virtual double evaluate(const Point<dim> &p, const double t) const {\n      double res = 1;\n\n      for (size_t i = 0; i < dim; i++)\n         res *= std::sin(k[i] * p[i]);\n\n      res *= constants[0] * std::sin(std::sqrt(k.square()) * t) + constants[1] * std::cos(std::sqrt(k.square()) * t);\n      return res;\n   }\n\n   SeparationAnsatz(Point<dim, int> k, Point<2> constants)\n         : k(k), constants(constants) {\n   }\n\nprivate:\n   Point<dim, int> k;\n   Point<2> constants;\n};\n\ntemplate<int dim>\nvoid run_reference_test(std::shared_ptr<SpaceTimeMesh<dim>> mesh, Point<dim, int> k, Point<2> constants, bool expect =\n      true, bool save = false) {\n   deallog << std::endl << \"----------  n_dofs(0): \" << mesh->get_dof_handler(0)->n_dofs();\n   deallog << \", n_steps: \" << mesh->get_times().size() << \"  ----------\" << std::endl;\n\n   WaveEquation<dim> wave_eq(mesh);\n\n   Point<2> derivative_constants;\n   derivative_constants[0] = -constants[1] * std::sqrt(k.square());\n   derivative_constants[1] = constants[0] * std::sqrt(k.square());\n\n   auto u = std::make_shared<SeparationAnsatz<dim>>(k, constants);\n   auto v = std::make_shared<SeparationAnsatz<dim>>(k, derivative_constants);\n\n   wave_eq.set_initial_values_u(u);\n   wave_eq.set_initial_values_v(v);\n\n   DiscretizedFunction<dim> solu = wave_eq.run(\n         std::make_shared<L2RightHandSide<dim>>(std::make_shared<Functions::ZeroFunction<dim>>(1)),\n         WaveEquation<dim>::Forward);\n   DiscretizedFunction<dim> solv = solu.derivative();\n   solu.throw_away_derivative();\n\n   solu.set_norm(std::make_shared<norms::L2L2<dim>>());\n   solv.set_norm(std::make_shared<norms::L2L2<dim>>());\n\n   DiscretizedFunction<dim> refu(mesh, *u);\n   DiscretizedFunction<dim> refv(mesh, *v);\n\n   refu.set_norm(std::make_shared<norms::L2L2<dim>>());\n   refv.set_norm(std::make_shared<norms::L2L2<dim>>());\n\n   DiscretizedFunction<dim> tmp(solu);\n   tmp -= refu;\n   double err_u = tmp.norm() / refu.norm();\n\n   tmp = solv;\n   tmp -= refv;\n   double err_v = tmp.norm() / refv.norm();\n\n   if (expect) {\n      EXPECT_LT(err_u, 1e-1);\n      EXPECT_LT(err_v, 1e-1);\n   }\n\n   if (save) {\n      solu.write_pvd(\"./\", \"solu\", \"u\");\n      refu.write_pvd(\"./\", \"refu\", \"uref\");\n\n      DiscretizedFunction<dim> tmp(solu);\n      tmp -= refu;\n      tmp.write_pvd(\"./\", \"diff\", \"udiff\");\n   }\n\n   deallog << std::scientific << \"forward : rerr(u) = \" << err_u << \", rerr(v) = \" << err_v << std::endl;\n\n   solu = wave_eq.run(std::make_shared<L2RightHandSide<dim>>(std::make_shared<Functions::ZeroFunction<dim>>(1)),\n         WaveEquation<dim>::Backward);\n   solv = solu.derivative();\n   solu.throw_away_derivative();\n\n   solu.set_norm(std::make_shared<norms::L2L2<dim>>());\n   solv.set_norm(std::make_shared<norms::L2L2<dim>>());\n\n   tmp = solu;\n   tmp -= refu;\n   err_u = tmp.norm() / refu.norm();\n\n   tmp = solv;\n   tmp -= refv;\n   err_v = tmp.norm() / refv.norm();\n\n   if (expect) {\n      EXPECT_LT(err_u, 1e-1);\n      EXPECT_LT(err_v, 1e-1);\n   }\n\n   deallog << std::scientific << \"backward: rerr(u) = \" << err_u << \", rerr(v) = \" << err_v << std::endl << std::endl;\n}\n}  // namespace\n\ntemplate<int dim>\nvoid run_reference_test_constant(int fe_order, int quad_order, int refines, Point<dim, int> k, Point<2> constants,\n      double t_end, int steps, bool expect = true, bool save = false) {\n   auto triangulation = std::make_shared<Triangulation<dim>>();\n   GridGenerator::hyper_cube(*triangulation, 0.0, numbers::PI);\n   Util::set_all_boundary_ids(*triangulation, 0);\n   triangulation->refine_global(refines);\n\n   double t_start = 0.0, dt = t_end / steps;\n   std::vector<double> times;\n\n   for (size_t i = 0; t_start + i * dt <= t_end; i++)\n      times.push_back(t_start + i * dt);\n\n   FE_Q<dim> fe(fe_order);\n   Quadrature<dim> quad = QGauss<dim>(quad_order);  // exact in poly degree 2n-1 (needed: fe_dim^3)\n\n   std::shared_ptr<SpaceTimeMesh<dim>> mesh = std::make_shared<ConstantMesh<dim>>(times, fe, quad, triangulation);\n\n   run_reference_test<dim>(mesh, k, constants, expect, save);\n}\n\ntemplate<int dim>\nvoid run_reference_test_nu(int fe_order, int quad_order, int refines, Point<dim, int> k, Point<2> constants,\n      double t_end, int steps, bool expect = true, bool save = false) {\n   auto triangulation = std::make_shared<Triangulation<dim>>();\n   GridGenerator::hyper_cube(*triangulation, 0.0, numbers::PI);\n   Util::set_all_boundary_ids(*triangulation, 0);\n   triangulation->refine_global(refines);\n\n   double t_start = 0.0, dt = t_end / steps;\n   std::vector<double> times;\n\n   for (size_t i = 0; t_start + i * dt <= t_end; i++)\n      times.push_back(t_start + i * dt);\n\n   FE_Q<dim> fe(fe_order);\n   Quadrature<dim> quad = QGauss<dim>(quad_order);  // exact in poly degree 2n-1 (needed: fe_dim^3)\n\n   std::shared_ptr<SpaceTimeMesh<dim>> mesh = std::make_shared<ConstantMesh<dim>>(times, fe, quad, triangulation);\n   deallog << std::endl << \"----------  n_dofs(0): \" << mesh->get_dof_handler(0)->n_dofs();\n   deallog << \", n_steps: \" << mesh->get_times().size() << \"  ----------\" << std::endl;\n\n   Point<2> derivative_constants;\n   derivative_constants[0] = -constants[1] * std::sqrt(k.square());\n   derivative_constants[1] = constants[0] * std::sqrt(k.square());\n\n   auto u = std::make_shared<SeparationAnsatz<dim>>(k, constants);\n   auto v = std::make_shared<SeparationAnsatz<dim>>(k, derivative_constants);\n\n   WaveEquation<dim> wave_eq(mesh);\n   wave_eq.set_param_nu(std::make_shared<TestNu<dim>>());\n\n   wave_eq.set_initial_values_u(u);\n   wave_eq.set_initial_values_v(v);\n\n   auto x = std::make_shared<RhsTestNu<dim>>(v);\n\n   DiscretizedFunction<dim> solu = wave_eq.run(std::make_shared<L2RightHandSide<dim>>(x), WaveEquation<dim>::Forward);\n   DiscretizedFunction<dim> solv = solu.derivative();\n   solu.throw_away_derivative();\n\n   solu.set_norm(std::make_shared<norms::L2L2<dim>>());\n   solv.set_norm(std::make_shared<norms::L2L2<dim>>());\n\n   DiscretizedFunction<dim> refu(mesh, *u);\n   DiscretizedFunction<dim> refv(mesh, *v);\n\n   refu.set_norm(std::make_shared<norms::L2L2<dim>>());\n   refv.set_norm(std::make_shared<norms::L2L2<dim>>());\n\n   DiscretizedFunction<dim> tmp(solu);\n   tmp -= refu;\n   double err_u = tmp.norm() / refu.norm();\n\n   tmp = solv;\n   tmp -= refv;\n   double err_v = tmp.norm() / refv.norm();\n\n   if (expect) {\n      EXPECT_LT(err_u, 1e-1);\n      EXPECT_LT(err_v, 1e-1);\n   }\n\n   if (save) {\n      solu.write_pvd(\"./\", \"solu\", \"u\");\n      refu.write_pvd(\"./\", \"refu\", \"uref\");\n\n      DiscretizedFunction<dim> tmp(solu);\n      tmp -= refu;\n      tmp.write_pvd(\"./\", \"diff\", \"udiff\");\n   }\n\n   deallog << std::scientific << \"forward : rerr(u) = \" << err_u << \", rerr(v) = \" << err_v << std::endl;\n\n   // backward does not work for nu > 0\n   /*\n    wave_eq.set_run_direction(WaveEquation<dim>::Backward);\n    solu = wave_eq.run();\n    solv = solu.derivative();\n    solu.throw_away_derivative();\n\n    solu.set_norm(Norm::L2L2);\n    solv.set_norm(Norm::L2L2);\n\n    tmp = solu;\n    tmp -= refu;\n    err_u = tmp.norm() / refu.norm();\n\n    tmp = solv;\n    tmp -= refv;\n    err_v = tmp.norm() / refv.norm();\n\n    if (expect) {\n    EXPECT_LT(err_u, 1e-1);\n    EXPECT_LT(err_v, 1e-1);\n    }\n\n    deallog << std::scientific << \"backward: rerr(u) = \" << err_u << \", rerr(v) = \" << err_v << std::endl << std::endl;\n    */\n}\n\ntemplate<int dim>\nvoid run_reference_test_adaptive(int fe_order, int quad_order, int refines, Point<dim, int> k, Point<2> constants,\n      double t_end, int steps, bool expect = true, bool save = false) {\n   auto triangulation = std::make_shared<Triangulation<dim>>();\n   GridGenerator::hyper_cube(*triangulation, 0.0, numbers::PI);\n   Util::set_all_boundary_ids(*triangulation, 0);\n   triangulation->refine_global(refines);\n\n   double t_start = 0.0, dt = t_end / steps;\n   std::vector<double> times;\n\n   for (size_t i = 0; t_start + i * dt <= t_end; i++)\n      times.push_back(t_start + i * dt);\n\n   FE_Q<dim> fe(fe_order);\n   Quadrature<dim> quad = QGauss<dim>(quad_order);  // exact in poly degree 2n-1 (needed: fe_dim^3)\n\n   auto mesh = std::make_shared<AdaptiveMesh<dim>>(times, fe, quad, triangulation);\n\n   // flag some cells for refinement, and refine them in some step\n   for (auto cell : triangulation->active_cell_iterators())\n      if (cell->center()[0] > numbers::PI / 2) cell->set_refine_flag();\n\n   std::vector<bool> ref;\n   std::vector<bool> coa;\n\n   triangulation->save_refine_flags(ref);\n   triangulation->save_coarsen_flags(coa);\n\n   for (auto cell : triangulation->active_cell_iterators())\n      cell->clear_refine_flag();\n\n   std::vector<Patch> patches = mesh->get_forward_patches();\n   patches[steps / 4].emplace_back(ref, coa);\n   mesh->set_forward_patches(patches);\n\n   mesh->get_dof_handler(0);\n\n   run_reference_test<dim>(mesh, k, constants, expect, save);\n}\n\ntemplate<int dim>\nvoid run_reference_test_refined(int fe_order, int quad_order, int refines, Point<dim, int> k, Point<2> constants,\n      double t_end, int steps, bool expect = true, bool save = false) {\n   auto triangulation = std::make_shared<Triangulation<dim>>();\n   GridGenerator::hyper_cube(*triangulation, 0.0, numbers::PI);\n   Util::set_all_boundary_ids(*triangulation, 0);\n   triangulation->refine_global(refines);\n\n   // flag some cells for refinement and refine them\n   for (auto cell : triangulation->active_cell_iterators())\n      if (cell->center()[1] > numbers::PI / 2) cell->set_refine_flag();\n\n   triangulation->execute_coarsening_and_refinement();\n\n   double t_start = 0.0, dt = t_end / steps;\n   std::vector<double> times;\n\n   for (size_t i = 0; t_start + i * dt <= t_end; i++)\n      times.push_back(t_start + i * dt);\n\n   FE_Q<dim> fe(fe_order);\n   Quadrature<dim> quad = QGauss<dim>(quad_order);  // exact in poly degree 2n-1 (needed: fe_dim^3)\n\n   auto mesh = std::make_shared<ConstantMesh<dim>>(times, fe, quad, triangulation);\n\n   run_reference_test<dim>(mesh, k, constants, expect, save);\n}\n\nTEST(WaveEquation, DiscretizedParameters1DFE1) {\n   run_discretized_test<1>(1, 3, 8);\n}\n\nTEST(WaveEquation, DiscretizedParameters1DFE2) {\n   run_discretized_test<1>(2, 4, 8);\n}\n\nTEST(WaveEquation, DiscretizedParameters2DFE1) {\n   run_discretized_test<2>(1, 3, 3);\n}\n\nTEST(WaveEquation, DiscretizedParameters2DFE2) {\n   run_discretized_test<2>(2, 4, 3);\n}\n\nTEST(WaveEquation, DiscretizedParameters3DFE1) {\n   run_discretized_test<3>(1, 3, 1);\n}\n\nTEST(WaveEquation, ReferenceTest1DFE1) {\n   for (int steps = 128; steps <= 1024; steps *= 2)\n      run_reference_test_constant<1>(1, 3, 10, Point<1, int>(2), Point<2>(1.0, 1.5), 2 * numbers::PI, steps,\n            steps >= 64);\n\n   for (int refine = 7; refine >= 1; refine--)\n      run_reference_test_constant<1>(1, 3, refine, Point<1, int>(2), Point<2>(1.0, 1.5), 2 * numbers::PI, 1024, false);\n}\n\nTEST(WaveEquation, ReferenceTest1DFE2) {\n   for (int steps = 16; steps <= 128; steps *= 2)\n      run_reference_test_constant<1>(2, 4, 7, Point<1, int>(2), Point<2>(1.0, 1.5), 2 * numbers::PI, steps,\n            steps >= 64);\n\n   for (int refine = 6; refine >= 1; refine--)\n      run_reference_test_constant<1>(2, 4, refine, Point<1, int>(2), Point<2>(1.0, 1.5), 2 * numbers::PI, 128, false);\n}\n\nTEST(WaveEquation, ReferenceTest2DFE1) {\n   for (int steps = 16; steps <= 256; steps *= 2)\n      run_reference_test_constant<2>(1, 3, 5, Point<2, int>(1, 2), Point<2>(1.0, 1.5), 2 * numbers::PI, steps,\n            steps >= 64);\n\n   for (int refine = 5; refine >= 1; refine--)\n      run_reference_test_constant<2>(1, 3, refine, Point<2, int>(1, 2), Point<2>(1.0, 1.5), 2 * numbers::PI, 256,\n            false);\n}\n\nTEST(WaveEquation, ReferenceTestAdaptive2DFE1) {\n   for (int steps = 16; steps <= 256; steps *= 2)\n      run_reference_test_adaptive<2>(1, 3, 5, Point<2, int>(1, 2), Point<2>(1.0, 1.5), 2 * numbers::PI, steps,\n            steps >= 64, false);\n\n   for (int refine = 5; refine >= 1; refine--)\n      run_reference_test_adaptive<2>(1, 3, refine, Point<2, int>(1, 2), Point<2>(1.0, 1.5), 2 * numbers::PI, 256,\n            false);\n}\n\nTEST(WaveEquation, ReferenceTestRefined2DFE1) {\n   for (int steps = 16; steps <= 256; steps *= 2)\n      run_reference_test_refined<2>(1, 3, 5, Point<2, int>(1, 2), Point<2>(1.0, 1.5), 2 * numbers::PI, steps,\n            steps >= 64, false);\n\n   for (int refine = 5; refine >= 1; refine--)\n      run_reference_test_refined<2>(1, 3, refine, Point<2, int>(1, 2), Point<2>(1.0, 1.5), 2 * numbers::PI, 256, false);\n}\n\nTEST(WaveEquation, ReferenceTest3DFE1) {\n   for (int steps = 8; steps <= 32; steps *= 2)\n      run_reference_test_constant<3>(1, 3, 3, Point<3, int>(1, 2, 3), Point<2>(0.7, 1.2), 2 * numbers::PI, steps,\n            steps >= 32);\n\n   for (int refine = 2; refine >= 0; refine--)\n      run_reference_test_constant<3>(1, 3, refine, Point<3, int>(1, 2, 3), Point<2>(0.7, 1.2), 2 * numbers::PI, 32,\n            false);\n}\n\nTEST(WaveEquation, ReferenceTestNu1DFE1) {\n   for (int steps = 128; steps <= 1024; steps *= 2)\n      run_reference_test_nu<1>(1, 3, 10, Point<1, int>(2), Point<2>(1.0, 1.5), 2 * numbers::PI, steps, steps >= 64);\n\n   for (int refine = 7; refine >= 1; refine--)\n      run_reference_test_nu<1>(1, 3, refine, Point<1, int>(2), Point<2>(1.0, 1.5), 2 * numbers::PI, 1024, false);\n}\n\nTEST(WaveEquation, ReferenceTestNu1DFE2) {\n   for (int steps = 16; steps <= 128; steps *= 2)\n      run_reference_test_nu<1>(2, 4, 7, Point<1, int>(2), Point<2>(1.0, 1.5), 2 * numbers::PI, steps, steps >= 64);\n\n   for (int refine = 6; refine >= 1; refine--)\n      run_reference_test_nu<1>(2, 4, refine, Point<1, int>(2), Point<2>(1.0, 1.5), 2 * numbers::PI, 128, false);\n}\n\nTEST(WaveEquation, ReferenceTestNu2DFE1) {\n   for (int steps = 16; steps <= 512; steps *= 2)\n      run_reference_test_nu<2>(1, 3, 6, Point<2, int>(1, 2), Point<2>(1.0, 1.5), 2 * numbers::PI, steps, steps >= 64);\n\n   for (int refine = 5; refine >= 1; refine--)\n      run_reference_test_nu<2>(1, 3, refine, Point<2, int>(1, 2), Point<2>(1.0, 1.5), 2 * numbers::PI, 256, false);\n}\n\nTEST(WaveEquation, ReferenceTestNu3DFE1) {\n   for (int steps = 8; steps <= 32; steps *= 2)\n      run_reference_test_nu<3>(1, 3, 3, Point<3, int>(1, 2, 3), Point<2>(0.7, 1.2), 2 * numbers::PI, steps,\n            steps >= 32);\n\n   for (int refine = 2; refine >= 0; refine--)\n      run_reference_test_nu<3>(1, 3, refine, Point<3, int>(1, 2, 3), Point<2>(0.7, 1.2), 2 * numbers::PI, 32, false);\n}\n", "meta": {"hexsha": "038243c207f485aeafa5948bbefb012a8ab61f43", "size": 24739, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/wave_equation.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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/wave_equation.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/wave_equation.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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.9355281207, "max_line_length": 120, "alphanum_fraction": 0.6534621448, "num_tokens": 7660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.5024200810565878}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE ToTEnergyConverterFactoryTest\n\n#include \"../ToTEnergyConverterFactory.h\"\n#include \"JPetLoggerInclude.h\"\n#include <boost/test/unit_test.hpp>\nusing namespace jpet_common_tools;\nusing namespace tot_energy_converter;\n\n/// Returns Time-over-threshold for given deposited energy\n/// the current parametrization is par1 + par2 * eDep\n/// Returned value in ps, and eDep is given in keV.\ndouble getToT1(double eDep, double par1 = -91958, double par2 = 19341)\n{\n  if (eDep < 0)\n    return 0;\n  double value = par1 + eDep * par2;\n  return value;\n}\n\nBOOST_AUTO_TEST_SUITE(ToTEnergyConverterFactoryTestSuite)\n\nBOOST_AUTO_TEST_CASE(test1)\n{\n  std::string formula1 = \"pol1\";\n  std::vector<double> params1 = {-91958, 19341};\n  std::vector<double> limits1 = {0, 100};\n\n  std::string formula2 = \"[0] + [1] * TMath::Log(x)\";\n  std::vector<double> params2 = {1, -2};\n  std::vector<double> limits2 = {2, 100};\n\n  std::map<std::string, boost::any> options = {\n    {\"ToTEnergyConverterFactory_Energy2ToTParameters_std::vector<double>\", params1},\n    {\"ToTEnergyConverterFactory_Energy2ToTFunction_std::string\", formula1},\n    {\"ToTEnergyConverterFactory_Energy2ToTFunctionLimits_std::vector<double>\", limits1},\n    {\"ToTEnergyConverterFactory_ToT2EnergyParameters_std::vector<double>\", params2},\n    {\"ToTEnergyConverterFactory_ToT2EnergyFunction_std::string\", formula2},\n    {\"ToTEnergyConverterFactory_ToT2EnergyFunctionLimits_std::vector<double>\", limits2}\n  };\n\n  ToTEnergyConverterFactory fact;\n  fact.loadConverterOptions(options);\n  auto conv = fact.getToTConverter();\n  BOOST_CHECK_CLOSE(conv(0), getToT1(0), 0.1);\n  BOOST_CHECK_CLOSE(conv(1), getToT1(1), 0.1);\n  BOOST_CHECK_CLOSE(conv(10), getToT1(10), 0.1);\n  BOOST_CHECK_CLOSE(conv(59.5), getToT1(59.5), 0.1);\n  BOOST_CHECK_CLOSE(conv(99.9), getToT1(99.9), 0.1);\n\n  auto conv2 = fact.getEnergyConverter();\n\n  TF1 funcTest(\"funcTest\", \"[0] + [1] * TMath::Log(x)\", 2, 100);\n  funcTest.SetParameters(1, -2);\n  BOOST_CHECK_CLOSE(conv2(3), funcTest.Eval(3), 0.1);\n  BOOST_CHECK_CLOSE(conv2(5.5), funcTest.Eval(5.5), 0.1);\n  BOOST_CHECK_CLOSE(conv2(45.25), funcTest.Eval(45.25), 0.1);\n  BOOST_CHECK_CLOSE(conv2(91), funcTest.Eval(91), 0.1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f00d5501800acfd1446adff85caa33371852f10e", "size": 2259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LargeBarrelAnalysis/tests/ToTEnergyConverterFactoryTest.cpp", "max_stars_repo_name": "kdulski/j-pet-framework-examples", "max_stars_repo_head_hexsha": "ab2592a2c6cf8f901f5732f8878b750b9a7b6a49", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-12T16:51:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T08:01:34.000Z", "max_issues_repo_path": "LargeBarrelAnalysis/tests/ToTEnergyConverterFactoryTest.cpp", "max_issues_repo_name": "kdulski/j-pet-framework-examples", "max_issues_repo_head_hexsha": "ab2592a2c6cf8f901f5732f8878b750b9a7b6a49", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 89.0, "max_issues_repo_issues_event_min_datetime": "2016-07-23T22:12:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T13:21:29.000Z", "max_forks_repo_path": "LargeBarrelAnalysis/tests/ToTEnergyConverterFactoryTest.cpp", "max_forks_repo_name": "kdulski/j-pet-framework-examples", "max_forks_repo_head_hexsha": "ab2592a2c6cf8f901f5732f8878b750b9a7b6a49", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2016-06-18T17:47:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T12:18:00.000Z", "avg_line_length": 36.435483871, "max_line_length": 88, "alphanum_fraction": 0.7339530766, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5023623197008033}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 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_ARCH_DETAIL_GENERIC_F_LOG_KERNEL_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_DETAIL_GENERIC_F_LOG_KERNEL_HPP_INCLUDED\n\n#include <boost/simd/function/fast.hpp>\n#include <boost/dispatch/meta/scalar_of.hpp>\n#include <boost/simd/function/simd/frexp.hpp>\n#include <boost/simd/function/simd/is_less.hpp>\n#include <boost/simd/function/simd/tofloat.hpp>\n#include <boost/simd/function/simd/seladd.hpp>\n#include <boost/simd/function/simd/minusone.hpp>\n#include <boost/simd/function/simd/sqr.hpp>\n#include <boost/simd/function/simd/multiplies.hpp>\n\n#include <boost/simd/constant/sqrt_2o_2.hpp>\n#include <boost/simd/constant/mone.hpp>\n\n\n#include <boost/simd/arch/detail/scalar/horner.hpp>\n#include <boost/simd/logical.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n\nnamespace boost { namespace simd { namespace detail\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  template < class A0,\n             class Style ,\n             class base_A0 = bd::scalar_of_t<A0>\n           >\n  struct kernel{};\n\n  template < class A0, class style>\n  struct kernel< A0, style, float>\n  {\n    using i_t = bd::as_integer_t<A0, signed>;\n    using s_t = bd::scalar_of_t<A0>;\n\n    static BOOST_FORCEINLINE void log(const A0& a0,\n                           A0& fe,\n                           A0& x,\n                           A0& x2,\n                           A0& y) BOOST_NOEXCEPT\n    {\n      i_t e;\n      x = fast_(frexp)(a0, e);\n      auto xltsqrthf = (x < Sqrt_2o_2<A0>());\n      fe = seladd(xltsqrthf, tofloat(e), Mone<A0>());\n      x =  minusone(seladd(xltsqrthf, x, x));\n      x2 = sqr(x);\n      // performances informations using this kernel for nt2::log\n      // exhaustive and bench tests with g++-4.7 sse4.2 or scalar give:\n      // at most 0.5 ulp  for input in [0, 3.40282e+38]\n      // 2130706656 values computed.\n      // 2127648316 values (99.86%)  within 0.0 ULPs\n      //    3058340 values (0.14%)   within 0.5 ULPs\n      // bench produces  8.9 cycles/value (simd) 34.5 cycles/value (scalar) full computation\n      // bench produces  7.1 cycles/value (simd) 32.2 cycles/value (scalar) with NO_DENORMALS, NO_INVALIDS etc.\n      y =  horner< BOOST_SIMD_HORNER_COEFF_T( s_t\n                                     , 8\n                                     , (0xbda5dff0, //     -8.0993533e-02\n                                        0x3e0229f9, //      1.2711324e-01\n                                        0xbe04d6b7, //     -1.2972532e-01\n                                        0x3e116e80, //      1.4202309e-01\n                                        0xbe2a6aa0, //     -1.6642237e-01\n                                        0x3e4cd0a3, //      2.0001464e-01\n                                        0xbe800064, //     -2.5000298e-01\n                                        0x3eaaaaa9  //      3.3333328e-01\n                                       )\n                                      )>(x)*x*x2;\n    }\n  };\n} } }\n\n\n\n#endif\n", "meta": {"hexsha": "72b07f7e04a74cf6899142ece2946a5dd02dd07a", "size": 3366, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/detail/generic/f_log_kernel.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/arch/detail/generic/f_log_kernel.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/arch/detail/generic/f_log_kernel.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": 37.8202247191, "max_line_length": 111, "alphanum_fraction": 0.5285204991, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5023623145120129}}
{"text": "#include <ros/ros.h>\n#include <math.h>\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n#include <nav_msgs/Odometry.h>\n#include <geometry_msgs/Point.h>\n#include <visualization_msgs/Marker.h>\n#include <tf2_ros/transform_broadcaster.h>\n#include <std_msgs/Empty.h>\n#include \"quadrotor_msgs/PositionCommand.h\"\n#include \"quadrotor_msgs/PolynomialTrajectory.h\"\n\nusing std::vector;\n\nconst int  _DIM_x = 0;\nconst int  _DIM_y = 1;\nconst int  _DIM_z = 2;\n\nenum ServerState{INIT, TRAJ, HOVER} _state = INIT;\nros::Publisher _cmd_pub, _cmd_vis_pub, _track_err_trig_pub;\nEigen::Vector3d _curr_posi;\nEigen::Vector3d _goal_point;\nquadrotor_msgs::PositionCommand _cmd, _last_cmd;\nEigen::Vector3d _initial_pos;\nEigen::Quaterniond _initial_q;\nbool _first_odom = true;\n\n// configuration for polynomial trajectory\nint _n_segment = 0;\nint _traj_id = 0;\nuint32_t _traj_flag = 0;\nEigen::VectorXd _time;\nEigen::MatrixXd _coef[3];\nvector<int> _order;\ndouble _mag_coeff;\nros::Time _final_time = ros::TIME_MIN;\nros::Time _start_time = ros::TIME_MAX;\ndouble _start_yaw = 0.0, _final_yaw = 0.0;\nbool _receive_traj = false;\ndouble _real_yaw;\nEigen::Quaterniond _q;\nEigen::Vector3d _euler;\n\n//yaw control\ndouble _yaw_error, _last_yaw_error, _cum_yaw_error, _slop_yaw_error;\ngeometry_msgs::Point _yaw;\n\n//so3 ctrl\ndouble pos_gain[3] = { 5.7, 5.7, 6.2 };\ndouble vel_gain[3] = { 3.4, 3.4, 4.0 };\n\n/*\n  * use Qingjiushao's method to calculate the value of f(t) = p0 + p1*t^1 + ... + pn*t^n\n  * coeff[i]: pn, pn-1, pn-2, ..., p1, p0\n  * order: n\n  */\ninline double calPosFromCoeff(double t, const Eigen::VectorXd &coeff, const int& order)\n{\n  double f = coeff[0];\n  for (int i=0; i<order; ++i) \n  {\n    f = t * f + coeff[i+1];\n  }\n  return f;\n}\n\ninline double calVelFromCoeff(double t, const Eigen::VectorXd &coeff, const int& order)\n{\n  double f = order * coeff[0];\n  for (int i=0; i<order-1; ++i) \n  {\n    f = t * f + (order - i - 1) * coeff[i+1];\n  }\n  return f;\n}\n\ninline double calAccFromCoeff(double t, const Eigen::VectorXd &coeff, const int& order)\n{\n  double f = order * (order-1) * coeff[0];\n  for (int i=0; i<order - 2; ++i) \n  {\n    f = t * f + (order - i - 1) * (order - i - 2) * coeff[i+1];\n  }\n  return f;\n}\n\ninline void calPVAFromCoeff(Eigen::Vector3d& pos, Eigen::Vector3d& vel, Eigen::Vector3d& acc, \n                            const Eigen::VectorXd &x_coeff, const Eigen::VectorXd &y_coeff, const Eigen::VectorXd &z_coeff, \n                            double t, const int& order)\n{\n  pos[0] = calPosFromCoeff(t, x_coeff, order);\n  pos[1] = calPosFromCoeff(t, y_coeff, order);\n  pos[2] = calPosFromCoeff(t, z_coeff, order);\n  vel[0] = calVelFromCoeff(t, x_coeff, order);\n  vel[1] = calVelFromCoeff(t, y_coeff, order);\n  vel[2] = calVelFromCoeff(t, z_coeff, order);\n  acc[0] = calAccFromCoeff(t, x_coeff, order);\n  acc[1] = calAccFromCoeff(t, y_coeff, order);\n  acc[2] = calAccFromCoeff(t, z_coeff, order);\n}\n\nEigen::Vector3d getRPY(const Eigen::Quaterniond &quat)\n{\n    double rotMat[3][3] = {(1 - 2 * (quat.y() * quat.y() + quat.z() * quat.z())), 2 * (quat.x() * quat.y() - quat.w() * quat.z()), 2 * (quat.x() * quat.z() + quat.w() * quat.y()),\n                           2 * (quat.x() * quat.y() + quat.w() * quat.z()), (1 - 2 * (quat.x() * quat.x() + quat.z() * quat.z())), 2 * (quat.y() * quat.z() - quat.w() * quat.x()),\n                           2 * (quat.x() * quat.z() - quat.w() * quat.y()), 2 * (quat.y() * quat.z() + quat.w() * quat.x()), (1 - 2 * (quat.x() * quat.x() + quat.y() * quat.y()))};\n\n    double yaw, pitch, roll;\n    if (rotMat[2][0] != 1 && rotMat[2][0] != -1)\n    {\n        double yaw1, yaw2, pitch1, pitch2, roll1, roll2;\n        pitch1 = -asin(rotMat[2][0]);\n        pitch2 = M_PI - pitch1;\n        double cos_pitch1 = cos(pitch1);\n        double cos_pitch2 = cos(pitch2);\n        roll1 = atan2(rotMat[2][1] / cos_pitch1, rotMat[2][2] / cos_pitch1);\n        roll2 = atan2(rotMat[2][1] / cos_pitch2, rotMat[2][2] / cos_pitch2);\n        yaw1 = atan2(rotMat[1][0] / cos_pitch1, rotMat[0][0] / cos_pitch1);\n        yaw2 = atan2(rotMat[1][0] / cos_pitch2, rotMat[0][0] / cos_pitch2);\n        if (fabs(pitch1) <= fabs(pitch2))\n        {\n            yaw = yaw1;\n            pitch = pitch1;\n            roll = roll1;\n        }\n        else\n        {\n            yaw = yaw2;\n            pitch = pitch2;\n            roll = roll2;\n        }\n    }\n    else if (rotMat[2][0] == 1)\n    {\n        yaw = 0;\n        pitch = M_PI / 2;\n        roll = yaw + atan2(rotMat[0][1], rotMat[0][2]);\n    }\n    else\n    {\n        yaw = 0;\n        pitch = -M_PI / 2;\n        roll = -yaw + atan2(-rotMat[0][1], -rotMat[0][2]);\n    }\n\n    return Eigen::Vector3d(roll, pitch, yaw);\n}\n\nvoid polyTrajCallback(const quadrotor_msgs::PolynomialTrajectory& traj)\n{\n  if (traj.action == quadrotor_msgs::PolynomialTrajectory::ACTION_ADD)\n  {   \n    ROS_WARN(\"[SERVER] Loading the trajectory.\");\n    if ((int)traj.trajectory_id < _traj_id) return ;\n\n    _state = TRAJ;\n    _traj_flag = quadrotor_msgs::PositionCommand::TRAJECTORY_STATUS_READY;\n    _traj_id = traj.trajectory_id;\n    _n_segment = traj.num_segment;\n    _final_time = _start_time = traj.header.stamp;\n    _time.resize(_n_segment);\n\n    _order.clear();\n    for (int idx = 0; idx < _n_segment; ++idx)\n    {\n      _final_time += ros::Duration(traj.time[idx]);\n      _time(idx) = traj.time[idx];\n      _order.push_back(traj.order[idx]);\n    }\n    _start_yaw = traj.start_yaw;\n    _final_yaw = traj.final_yaw;\n    _mag_coeff = traj.mag_coeff;\n\n    int max_order = *max_element( begin( _order ), end( _order ) ); \n    _coef[_DIM_x] = Eigen::MatrixXd::Zero(max_order + 1, _n_segment);\n    _coef[_DIM_y] = Eigen::MatrixXd::Zero(max_order + 1, _n_segment);\n    _coef[_DIM_z] = Eigen::MatrixXd::Zero(max_order + 1, _n_segment);\n    \n    //ROS_WARN(\"stack the coefficients\");\n    int shift = 0;\n    for (int idx = 0; idx < _n_segment; ++idx)\n    {     \n      int order = traj.order[idx];\n      for (int j = 0; j < (order + 1); ++j)\n      {\n        _coef[_DIM_x](j, idx) = traj.coef_x[shift + j];\n        _coef[_DIM_y](j, idx) = traj.coef_y[shift + j];\n        _coef[_DIM_z](j, idx) = traj.coef_z[shift + j];\n      }\n      shift += (order + 1);\n    }\n\n    //compute the goal\n    _goal_point[0] = calPosFromCoeff(_time(_n_segment-1), _coef[_DIM_x].col(_n_segment-1), _order[_n_segment-1]);\n    _goal_point[1] = calPosFromCoeff(_time(_n_segment-1), _coef[_DIM_y].col(_n_segment-1), _order[_n_segment-1]);\n    _goal_point[2] = calPosFromCoeff(_time(_n_segment-1), _coef[_DIM_z].col(_n_segment-1), _order[_n_segment-1]);\n  \n    _receive_traj = true;\n  }\n  else if (traj.action == quadrotor_msgs::PolynomialTrajectory::ACTION_ABORT) \n  {\n    ROS_WARN(\"[SERVER] Aborting the trajectory! EMERGENCY STOP!!\");\n    _state = HOVER;\n    _traj_flag = quadrotor_msgs::PositionCommand::TRAJECTORY_STATUS_COMPLETED;\n  }\n  else if (traj.action == quadrotor_msgs::PolynomialTrajectory::ACTION_WARN_IMPOSSIBLE)\n  {\n    _state = HOVER;\n    _traj_flag = quadrotor_msgs::PositionCommand::TRAJECTORY_STATUS_IMPOSSIBLE;\n  }\n}\n\nvoid odomCallbck(const nav_msgs::OdometryConstPtr odom)\n{\n  _curr_posi[0] = odom->pose.pose.position.x;\n  _curr_posi[1] = odom->pose.pose.position.y;\n  _curr_posi[2] = odom->pose.pose.position.z;\n  if (_first_odom)\n  {\n    _first_odom = false;\n    _initial_pos[0] = odom->pose.pose.position.x;\n    _initial_pos[1] = odom->pose.pose.position.y;\n    _initial_pos[2] = odom->pose.pose.position.z;\n    _initial_q.w() = odom->pose.pose.orientation.w;\n    _initial_q.x() = odom->pose.pose.orientation.x;\n    _initial_q.y() = odom->pose.pose.orientation.y;\n    _initial_q.z() = odom->pose.pose.orientation.z;\n  }\n\n  /* no publishing before receive traj */\n//  if (!_receive_traj)\n//    return;\n  \n  // #1. check if it is right state\n  if (_state == INIT) \n  {\n    _cmd.header = odom->header;\n\t\t\n    _cmd.position.x = _initial_pos[0];\n    _cmd.position.y = _initial_pos[1];\n    _cmd.position.z = _initial_pos[2];\n\t\t\n    _cmd.velocity.x = 0.0;\n    _cmd.velocity.y = 0.0;\n    _cmd.velocity.z = 0.0;\n    \n    _cmd.acceleration.x = 0.0;\n    _cmd.acceleration.y = 0.0;\n    _cmd.acceleration.z = 0.0;\n\n  }\n  if (_state == HOVER)\n  {\n    _cmd.header = odom  ->header;\n    _cmd.trajectory_flag = quadrotor_msgs::PositionCommand::TRAJECTORY_STATUS_COMPLETED;\n\n    _cmd.position = _last_cmd.position;\n    \n    _cmd.velocity.x = 0.0;\n    _cmd.velocity.y = 0.0;\n    _cmd.velocity.z = 0.0;\n    \n    _cmd.acceleration.x = 0.0;\n    _cmd.acceleration.y = 0.0;\n    _cmd.acceleration.z = 0.0;\n    \n    _cmd.yaw_dot = 0.0;\n    _cmd.yaw = _last_cmd.yaw;\n  }\n  // #2. locate the trajectory segment\n  if (_state == TRAJ)\n  {   \n    //(odom freq >= cmd timer freq) has to be satisfied or it will cause several diffferent cmd in the same time stamp\n    \n    double t = std::max(0.0, (ros::Time::now() - _start_time).toSec());\n    if (t >= (_final_time - _start_time).toSec() - 0.02)\n      _state = HOVER;\n    \n    // #3. calculate the desired states\n    //ROS_WARN(\"[SERVER] the time : %.3lf\\n, n = %d, m = %d\", t, _n_order, _n_segment);\n    for (int idx = 0; idx < _n_segment; ++idx)\n    {\n      if (t > _time[idx] && idx + 1 < _n_segment)\n      {\n        t -= _time[idx];\n      }\n      else\n      { \n        _cmd.header = odom->header;\n\t\t\n        int cur_order = _order[idx];\n        Eigen::Vector3d pos(0.0, 0.0, 0.0), vel(0.0, 0.0, 0.0), acc(0.0, 0.0, 0.0);\n        calPVAFromCoeff(pos, vel, acc, _coef[_DIM_x].col(idx), _coef[_DIM_y].col(idx), _coef[_DIM_z].col(idx), t, cur_order);\n        _cmd.position.x = pos[0];\n        _cmd.position.y = pos[1];\n        _cmd.position.z = pos[2];\n        _cmd.velocity.x = vel[0];\n        _cmd.velocity.y = vel[1];\n        _cmd.velocity.z = vel[2];\n        _cmd.acceleration.x = acc[0];\n        _cmd.acceleration.y = acc[1];\n        _cmd.acceleration.z = acc[2];\n\n\t\t//use look_forward yaw planning\n        double look_forward_time = std::min(1/vel.norm(), std::max(0.0, (_final_time - _start_time).toSec() - t - 0.02));\n        if (look_forward_time == 0)\n        {\n          _cmd.yaw = _last_cmd.yaw;\n        }\n        else\n        {\n          Eigen::Vector3d pos_lf(0.0, 0.0, 0.0), vel_lf(0.0, 0.0, 0.0), acc_lf(0.0, 0.0, 0.0);\n          calPVAFromCoeff(pos_lf, vel_lf, acc_lf, _coef[_DIM_x].col(idx), _coef[_DIM_y].col(idx), _coef[_DIM_z].col(idx), t + look_forward_time, cur_order);\n          //use look_forward yaw planning\n          _cmd.yaw = atan2(pos_lf[1] - pos[1], pos_lf[0] - pos[0]);\n          //use tangent direction for yaw planning\n          //_cmd.yaw = atan2(_cmd.velocity.y, _cmd.velocity.x); //(-pi, pi]\n          double d_yaw = _cmd.yaw - _last_cmd.yaw;\n          if (d_yaw >= M_PI)\n          {\n            d_yaw -= M_PI;\n            d_yaw -= M_PI;\n          }\n          if (d_yaw <= -M_PI)\n          {\n            d_yaw += M_PI;\n            d_yaw += M_PI;\n          }\n          double d_yaw_abs = fabs(d_yaw);\n          if (d_yaw_abs >= 0.02)\n            _cmd.yaw = _last_cmd.yaw + d_yaw / d_yaw_abs * 0.02;\n        }\n        //or use tangent direction for yaw planning\n\n        _last_cmd = _cmd;\n        break;\n      } \n    }\n  }\n  // #4. just publish\n  _cmd_pub.publish(_cmd);\n  Eigen::Vector3d desire_pos(_cmd.position.x, _cmd.position.y, _cmd.position.z);\n\n  static tf2_ros::TransformBroadcaster br_map_ego_desired;\n  geometry_msgs::TransformStamped transformStamped;\n  transformStamped.header.stamp = odom->header.stamp;\n  transformStamped.header.frame_id = \"map\";\n  transformStamped.child_frame_id = \"ego_desired\";\n  transformStamped.transform.translation.x = _cmd.position.x;\n  transformStamped.transform.translation.y = _cmd.position.y;\n  transformStamped.transform.translation.z = _cmd.position.z;\n  Eigen::AngleAxisd aa(_cmd.yaw, Eigen::Vector3d::UnitZ());\n  Eigen::Quaterniond d_q(aa);  \n  transformStamped.transform.rotation.x = d_q.x();\n  transformStamped.transform.rotation.y = d_q.y();\n  transformStamped.transform.rotation.z = d_q.z();\n  transformStamped.transform.rotation.w = d_q.w();\n  br_map_ego_desired.sendTransform(transformStamped);\n\n  if ((_curr_posi - desire_pos).norm() >= 1.0)\n  {\n    std_msgs::Empty empty_msg;\n    _track_err_trig_pub.publish(empty_msg);\n  }\n\n  if ((_curr_posi - _goal_point).norm() <= 0.01) \n    _state = HOVER;\n}\n\nint main(int argc, char** argv)\n{\n  ros::init(argc, argv, \"traj_server\");\n  ros::NodeHandle node;\n\n  ros::Subscriber poly_sub = node.subscribe(\"planning/poly_traj\", 1, polyTrajCallback);\n  ros::Subscriber odom_sub = node.subscribe(\"/curr_state_sub_topic\", 50, odomCallbck, ros::TransportHints().tcpNoDelay());\n  //ros::Timer cmd_timer = node.createTimer(ros::Duration(0.01), cmdCallback);\n  _cmd_pub = node.advertise<quadrotor_msgs::PositionCommand>(\"/position_cmd\", 50);\n  _cmd_vis_pub = node.advertise<visualization_msgs::Marker>(\"planning/position_cmd_vis\", 10);\n  _track_err_trig_pub = node.advertise<std_msgs::Empty>(\"/trig/tracking_err\", 1);\n\n  /* control parameter for so3 control*/\n  _cmd.kx[0] = pos_gain[0];\n  _cmd.kx[1] = pos_gain[1];\n  _cmd.kx[2] = pos_gain[2];\n\n  _cmd.kv[0] = vel_gain[0];\n  _cmd.kv[1] = vel_gain[1];\n  _cmd.kv[2] = vel_gain[2];\n\n  ros::Duration(1.0).sleep();\n  ROS_WARN(\"[Traj server]: ready.\");\n  ros::spin();\n  return 0;\n}\n", "meta": {"hexsha": "d3ccc093db6b26a8790dd5f9d05ada6969bc1beb", "size": 13175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "decision/state_machine/src/traj_server_node.cpp", "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": "decision/state_machine/src/traj_server_node.cpp", "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": "decision/state_machine/src/traj_server_node.cpp", "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": 33.2702020202, "max_line_length": 180, "alphanum_fraction": 0.6179886148, "num_tokens": 4224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5023623145120127}}
{"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 <utility>\n#include <vector>\n#include <random>\n#include <chrono>\n\n#include <boost/geometry/geometry.hpp>\n\n#include \"../includes/concave_hull_k_nearest_neighbours_optimized.hpp\"\n\nnamespace bg = boost::geometry;\nusing bg::dsv;\n\ntypedef bg::model::point<double, 2, bg::cs::cartesian> point_t;\ntypedef bg::model::multi_point<point_t> mpoint_t;\ntypedef bg::model::polygon<point_t> polygon_t;\ntypedef bg::model::segment<point_t> segment_t;\n\nstd::mt19937_64 rang(std::chrono::high_resolution_clock::now().time_since_epoch().count());\n\nint my_rand(int l, int r)\n{\n    if (l > r)\n    {\n        std::swap(l, r);\n    }\n\tstd::uniform_int_distribution <int> uid(l, r);\n\treturn uid(rang);\n}\n\nbool test(mpoint_t &input, mpoint_t &output)\n{\n    // First test is to check if all the points must lie inside or on the concave hull.\n    polygon_t p;\n    for (int i = 0; i < boost::size(output); ++i)\n    {\n        bg::append(p, output[i]);\n    }\n    for (int i = 0; i < boost::size(input); ++i)\n    {\n        if (!(bg::covered_by(input[i], p)))\n        {\n            std::cout << dsv(input[i]) << \"\\n\";\n            return false;\n        }\n    }\n\n    // Second test is to check if no two edges of the concave hull intersects each other.\n    for (int i = 0; i < int(boost::size(output)) - 1; ++i)\n    {\n        segment_t cur(output[i], output[i + 1]);\n        for (int j = 0; j < int(boost::size(output)) - 1; ++j)\n        {\n            if (bg::equals(output[i], output[j]) or bg::equals(output[i], output[j + 1]))\n            {\n                continue;\n            }\n            if (bg::equals(output[i + 1], output[j]) or bg::equals(output[i + 1], output[j + 1]))\n            {\n                continue;\n            }\n            segment_t check(output[j], output[j + 1]);\n            if (bg::intersects(check, cur))\n            {\n                std::cout << dsv(check) << \"\\n\";\n                std::cout << dsv(cur) << \"\\n\";\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nint main()\n{\n    std::cout << std::fixed << std::setprecision(0);\n    #ifdef HOME\n        freopen(\"input.txt\", \"r\", stdin);\n        freopen(\"output.txt\", \"w\", stdout);\n    #endif\n\n    for (int tt = 1; tt <= 50; ++tt) // 50 random test cases\n    {\n        mpoint_t mpt1, hull1, hull2;\n\n        int points = 30, k = 3;\n        for (int i = 0; i < points; ++i)\n        {\n            int x = my_rand(0, 100);\n            int y = my_rand(0, 100);\n            bg::append(mpt1, point_t(x, y));\n        }\n\n        algo3::ConcaveHullKNN(mpt1, hull2, k);\n        assert(test(mpt1, hull2) == true);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "472dad8c207b21fb55fce6898d5928e09da67bdf", "size": 2769, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/concave_hull.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": "test/concave_hull.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": "test/concave_hull.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": 25.6388888889, "max_line_length": 97, "alphanum_fraction": 0.5344889852, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5023623093232222}}
{"text": "#include <boost/math/complex/asinh.hpp>\n", "meta": {"hexsha": "e7bdaf8cc119212c99958536f495b0aff9f1617a", "size": 40, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_complex_asinh.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_complex_asinh.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_complex_asinh.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 20.0, "max_line_length": 39, "alphanum_fraction": 0.775, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5023623041344313}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <bits/stdc++.h>\n#include <ros/ros.h>\n#include <math.h>\n#include <stdio.h>\n#include <dwm1001/anchor.h> \n#include <sensor_msgs/Imu.h>\n#include \"geometry_msgs/PoseStamped.h\"\n#include \"geometry_msgs/TwistStamped.h\"\n#include <tf/transform_broadcaster.h>\n#define PI (double)acos(-1.0)\n\nint flag=0;\ndouble X,P,Q;\nint set_=0;\ndouble theta_meas,theta_meas_1,r,K,P_p,X_p,error_1;\nint set_p=0;\ndouble T,m_last_range_time,u,X_e,M,error,yaw_imu_prev;\ndouble x_1,x_2,y_1,y_2,z_1,z_2;\n\nEigen::Quaternionf q;\nEigen::Quaternionf q_;\nEigen::MatrixXf R_mat(3,3);\nEigen::MatrixXf rpy(3,1);\ngeometry_msgs::PoseStamped pose;\ndouble error_threshold;\ndouble l;\nEigen::Quaternionf q_imu;\nEigen::MatrixXf rpy_imu(3,1);\ndouble yaw_imu;\n\n\nvoid setState(double Y)\n{\n    X = Y;\n}\nvoid setCovariance(double S)\n{\n    P = S;\n}\n\n\n\nvoid Initialize()\n{\n\n    boost::shared_ptr<sensor_msgs::Imu const> final_msg;\n    ros::Duration one_second(0.5);\n    final_msg = ros::topic::waitForMessage<sensor_msgs::Imu>(\"/mavros/imu/data\",one_second);\n    if(final_msg != NULL){\n    q = Eigen::Quaternionf(final_msg->orientation.w, final_msg->orientation.x, final_msg->orientation.y, final_msg->orientation.z);\n    R_mat= q.toRotationMatrix();\n    rpy = q.toRotationMatrix().eulerAngles(2, 1, 0);\n    ROS_WARN(\"yaw initialized %f\",rpy(2,0)*180/PI);\n    X = rpy(2,0)-PI ;\n    }\n    P = 1;\n    \n}\n\nvoid correction_step()\n{   \n    //l = 0.2;\n    theta_meas_1 = (x_2 - x_1) ;\n    if(theta_meas_1>l)\n    theta_meas_1 = l;    \n    //l = std::sqrt( std::pow( x_1 - x_2, 2) + std::pow( y_1 - y_2, 2) + std::pow( z_1 - z_2, 2) ) ;\n    theta_meas = (((theta_meas_1/l)*-90.0) + 90.0);\n    if(theta_meas > 90)\n        theta_meas = (theta_meas )*PI/180;\n    else\n        theta_meas = theta_meas*PI/180;\n\n    r = std::pow(r,2) ;\n    //ROS_WARN(\"runing\");\n    K = P / (P + r );\n    P_p = ( 1 - K ) * P;\n    X_p = X + K * (theta_meas - X);\n    // decide to take the range info or not.\n    flag = 0;\n    //ROS_WARN(\"measured distance %f, angle %f\",theta_meas_1,theta_meas*180/PI);\n    error_1 = std::fabs(X_p - X);\n    if(error_1 < error_threshold){\n        setState(X_p);\n        setCovariance(P_p);\n        set_= 0;\n        return ;\n    } else {\n\n        ROS_WARN(\"Update too large: predicted %f measured-- %f with length %f\", X , theta_meas,l);\n        ROS_WARN(\"measurement setup %f with %f\",x_1,x_2);\n        set_=set_+1;\n        if(set_>10)\n            Initialize();\n        return ;\n    }\n\n}\n\n\nvoid prediction_step(const geometry_msgs::TwistStamped::ConstPtr& msg)\n{\n    T = msg->header.stamp.toSec() - m_last_range_time;\n    if(T>1){\n        T = 1;\n    } else if(T<0){\n        T = 0.02;\n    }\n    \n    u = msg->twist.angular.z;\n    X_e = X + T * u;\n    M = P + Q;\n    m_last_range_time = msg->header.stamp.toSec();\n    error = std::fabs(X-X_e);\n    //ROS_WARN(\"predicted %f\",X_e);\n    if(error < error_threshold){\n        //ROS_WARN(\"\\n sucess too large: %f\", error);\n        set_p=0;\n        setState(X_e);\n        setCovariance(M);\n        return ;\n    } else {\n\n        ROS_WARN(\"\\n Estimate too large: %f\", error);\n        set_p=set_p+1;\n        if(set_p>10)\n            Initialize();\n        return ;\n    }\n\n}\n\n\nvoid tag1_cb(const dwm1001::anchor::ConstPtr& msg)\n{\n    x_1 = msg->x;\n    y_1 = msg->y;\n    z_1 = msg->z;\n    if(flag==1)\n        correction_step();\n}\n\nvoid tag2_cb(const dwm1001::anchor::ConstPtr& msg)\n{\n    x_2 = msg->x;\n    y_2 = msg->y;\n    z_2 = msg->z;\n    flag=1;\n}\n\n\nvoid imu_cb(const sensor_msgs::Imu::ConstPtr& msg)\n{\n    //conerts the acceleration from body frame to earth frame(NED) \n    q_imu = Eigen::Quaternionf(msg->orientation.w, msg->orientation.x, msg->orientation.y, msg->orientation.z);\n\n    //Eigen::MatrixXf rpy(3,1);\n    rpy_imu = q_imu.toRotationMatrix().eulerAngles(0, 1, 2);\n    //acc_ang.header.stamp = ros::Time::now();\n    //acc_ang.vector.x = rpy_imu(0,0)*(180.0/3.14159265358979);\n    //acc_ang.vector.y = rpy_imu(1,0)*(180.0/3.14159265358979);\n    yaw_imu = rpy_imu(2,0);\n\n\n}\n\n\nint main(int argc, char** argv){\n\n    ros::init(argc,argv,\"yaw\");\n    ros::NodeHandle nh;\n    //Initializinging the parameters\n    Initialize();\n    nh.getParam(\"yaw/tag_r\", r);\n    nh.getParam(\"yaw/imu_q\", Q);\n    nh.getParam(\"yaw/distance\", l);\n    nh.getParam(\"yaw/error_threshold\", error_threshold);\n    Q = Q*Q;\n    tf::TransformBroadcaster br;\n    tf::Transform transform;\n\n    //Subscriber and Publisher for the data. remapped in the launch file to the topic required\n    ros::Subscriber anchor_1 = nh.subscribe(\"tag_1\",10,tag1_cb);\n    ros::Subscriber anchor_2 = nh.subscribe(\"tag_2\",10,tag2_cb);\n    ros::Subscriber velocity_sb = nh.subscribe(\"velocity\",10,prediction_step);\n    ros::Subscriber imu_sb = nh.subscribe(\"imu\",10,imu_cb);\n\n    ros::Publisher fused_theta = nh.advertise<geometry_msgs::PoseStamped>(\"yaw_angle\", 10);\n    transform.setOrigin( tf::Vector3(0.0, 0.0, 1.0) );\n    transform.setRotation( tf::Quaternion(0, 0, 0, 1) );\n    ros::Rate loop_rate(30);\n    while(ros::ok()){\n        \n        pose.header.stamp = ros::Time::now();\n        pose.header.frame_id = \"uwb\";\n    if(isnan(X)==1)\n            Initialize();\n        //pose.pose.position.x= X*180/PI;\n        if(abs(yaw_imu_prev - yaw_imu) > 170*PI/180)\n            yaw_imu = yaw_imu_prev;\n        //pose.pose.position.y= abs(yaw_imu*180/PI-16);\n        yaw_imu_prev = yaw_imu;\n        pose.pose.position.z= 0;\n\t//ROS_WARN(\"yaw %f compared %f\",X*180/PI,yaw_imu*180/PI-16);\n        q_ = Eigen::AngleAxisf(0.0, Eigen::Vector3f::UnitX())*Eigen::AngleAxisf(0.0, Eigen::Vector3f::UnitY())*Eigen::AngleAxisf(X, Eigen::Vector3f::UnitZ());\n        pose.pose.orientation.w = q_.w();\n        pose.pose.orientation.x = q_.x();\n        pose.pose.orientation.y = q_.y();\n        pose.pose.orientation.z = q_.z();\n\n        fused_theta.publish(pose);\n        br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), \"local_origin\", \"uwb\"));\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n    return 0;\n}       \n\n", "meta": {"hexsha": "7353552684f789181eda09aa7ac1292ba1b4ccb4", "size": 6049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gazebo_sim/gps_denied/src/yaw.cpp", "max_stars_repo_name": "naveenbiitk/State_Estimation", "max_stars_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-05T06:19:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-05T06:19:20.000Z", "max_issues_repo_path": "gazebo_sim/gps_denied/src/yaw.cpp", "max_issues_repo_name": "naveenbiitk/State_Estimation", "max_issues_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gazebo_sim/gps_denied/src/yaw.cpp", "max_forks_repo_name": "naveenbiitk/State_Estimation", "max_forks_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_forks_repo_licenses": ["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.371040724, "max_line_length": 158, "alphanum_fraction": 0.6124979335, "num_tokens": 1898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5023622989456402}}
{"text": "#include <unordered_set>\n#include <tuple>\n\n#include <Eigen/Core>\n\n#include \"vision.hpp\"\n#include \"world.hpp\"\n\nnamespace cuauv {\nnamespace fishbowl {\n\ncamera::camera(world* w, Eigen::Quaterniond* pq, Eigen::Vector3d* px, const Eigen::Quaterniond& q, const Eigen::Vector3d& x, double f)\n    : pq(pq)\n    , px(px)\n    , q(q)\n    , x(x)\n    , f(f)\n    , w(w)\n    , C(Eigen::Matrix<double, 3, 4>::Zero())\n{\n    step();\n}\n\nvoid camera::step()\n{\n    C.block<3, 3>(0, 0) = (q.conjugate() * pq->conjugate()).matrix();\n    C.col(3) = C.block<3, 3>(0, 0) * (-(*px) - ((*pq) * x));\n}\n\nstd::tuple<double, double, double, double> camera::query(entity_id id)\n{\n    const entity& e = w->get_entity(id);\n    const Eigen::Vector3d tx = e.x;\n    // target position homogenous\n    Eigen::Vector4d txh(tx[0], tx[1], tx[2], 1);\n    // target position in the camera frame\n    Eigen::Vector3d txc = C * txh;\n\n    if (txc[0] == 0) {\n        return std::make_tuple(0, 0, 0, 0);\n    }\n\n    txc[1] *= f/txc[0];\n    txc[2] *= f/txc[0];\n\n    return std::make_tuple(txc[1], txc[2], txc[0] > 0 ? e.get_r() * f/txc[0] : 0, txc[0]);\n}\n\n} // namespace fishbowl\n} // namespace cuauv\n", "meta": {"hexsha": "3cfd49f5bac9acee45bd8bc30e10376114eb818c", "size": 1147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fishbowl/vision.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/vision.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/vision.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": 22.4901960784, "max_line_length": 134, "alphanum_fraction": 0.5684394071, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5023622989456401}}
{"text": "/*\n   Copyright (C) 2019 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#ifndef LATTICE_TYPES_HPP\n#define LATTICE_TYPES_HPP\n\n#include <string>\n#include <Eigen/Dense>\n\nnamespace lattice {\n\nenum boundary_t { open, periodic };\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> basis_t;\n\n// set of spanning vectors\ntypedef Eigen::Matrix<long, Eigen::Dynamic, Eigen::Dynamic> span_t;\n\n// extent vector = diagonal spanning matrix\ntypedef Eigen::Matrix<long, Eigen::Dynamic, 1> extent_t;\n\n// coordinate vector\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1> coordinate_t;\n\n// unitcell offset\ntypedef Eigen::Matrix<long, Eigen::Dynamic, 1> offset_t;\n\n} // end namespace lattice\n\n#endif\n", "meta": {"hexsha": "db844a199049b35b113c1b997aba92f889003f29", "size": 1245, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lattice/types.hpp", "max_stars_repo_name": "todo-group/lattice", "max_stars_repo_head_hexsha": "205a3321ad0cf98bb8924a7e6d494c11b3c395b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-29T07:53:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-29T07:53:57.000Z", "max_issues_repo_path": "model_sample/lattice/types.hpp", "max_issues_repo_name": "chihirokondo/wl_mpi", "max_issues_repo_head_hexsha": "33cb42e6a2649df767d1284c44d3fb11525b423e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model_sample/lattice/types.hpp", "max_forks_repo_name": "chihirokondo/wl_mpi", "max_forks_repo_head_hexsha": "33cb42e6a2649df767d1284c44d3fb11525b423e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-27T07:40:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T04:58:18.000Z", "avg_line_length": 28.2954545455, "max_line_length": 75, "alphanum_fraction": 0.7485943775, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5023614558590366}}
{"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 multi_sensor_gaussian_filter_test.cpp\n * \\date August 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#include <gtest/gtest.h>\n#include \"../typecast.hpp\"\n\n#include <Eigen/Dense>\n\n#include \"gaussian_filter_test_suite.hpp\"\n#include <fl/util/meta.hpp>\n#include <fl/filter/gaussian/quadrature/unscented_quadrature.hpp>\n#include <fl/filter/gaussian/robust_multi_sensor_gaussian_filter.hpp>\n#include <fl/model/sensor/linear_cauchy_sensor.hpp>\n#include <fl/model/sensor/body_tail_sensor.hpp>\n#include <fl/model/sensor/linear_gaussian_sensor.hpp>\n\nusing namespace fl;\n\ntemplate <\n    int StateDimension,\n    int ObsrvDimension,\n    int Count,               // Local observation model count\n    int FilterIterations\n>\nstruct RobustMultiSensorGfTestConfiguration\n{\n    enum : signed int\n    {\n        StateDim = StateDimension,\n        InputDim = 1,\n        ObsrvDim = ObsrvDimension,\n        Iterations = FilterIterations\n    };\n\n    template <typename ModelFactory>\n    struct FilterDefinition\n    {\n        enum : signed int\n        {\n            // compile time size (positive for static and -1 for dynamic)\n            Size  = ExpandSizes<Count, ModelFactory::Sizes>::Value\n        };\n\n        // ================================================================== //\n        // == Define Process Model                                         == //\n        // ================================================================== //\n        typedef typename ModelFactory::LinearTransition Transition;\n\n        // ================================================================== //\n        // == Define Body Tail Observation Model                           == //\n        // ================================================================== //\n        typedef typename ModelFactory::LinearObservation::Obsrv Obsrv;\n        typedef typename ModelFactory::LinearObservation::State State;\n\n        typedef fl::LinearCauchySensor<Obsrv, State> CauchyModel;\n\n        typedef fl::BodyTailSensor<\n                    typename ModelFactory::LinearObservation,\n                    CauchyModel\n                > BodyTailSensor;\n\n        typedef BodyTailSensor LocalSensor;\n\n        // ================================================================== //\n        // == Define Joint Body Tail Observation Model                     == //\n        // ================================================================== //\n        typedef JointSensor<\n                    MultipleOf<LocalSensor, Size>\n                > JointSensor;\n\n        // ================================================================== //\n        // == Define Integration Quadrature                                == //\n        // ================================================================== //\n        typedef UnscentedQuadrature Quadrature;\n\n        // ================================================================== //\n        // == Define the filter                                            == //\n        // ================================================================== //\n        typedef RobustMultiSensorGaussianFilter<\n                    Transition, JointSensor, Quadrature\n                > Type;\n    };\n\n    template <typename ModelFactory>\n    static typename FilterDefinition<ModelFactory>::Type\n    create_filter(ModelFactory&& factory)\n    {\n        typedef FilterDefinition<ModelFactory> Definition;\n\n        typedef typename Definition::Type Filter;\n        typedef typename Definition::CauchyModel CauchyModel;\n        typedef typename Definition::BodyTailSensor BodyTailSensor;\n        typedef typename Definition::JointSensor JointSensor;\n\n        auto body_model = factory.create_sensor();\n        auto tail_model = CauchyModel();\n        tail_model.noise_covariance(tail_model.noise_covariance() * 10.);\n\n        return Filter(\n            factory.create_linear_state_model(),\n            JointSensor(BodyTailSensor(body_model, tail_model, 0.1), Count),\n            typename Definition::Quadrature());\n    }\n};\n\ntypedef ::testing::Types<\n            StaticTest<RobustMultiSensorGfTestConfiguration<6, 3, 48, 30>>\n        > TestTypes;\n\nINSTANTIATE_TYPED_TEST_CASE_P(RobustMultiSensorGaussianFilterTest,\n                              GaussianFilterTest,\n                              TestTypes);\n", "meta": {"hexsha": "0afa9f6baf87167fa4dc60968cca48c0b805306c", "size": 4721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gaussian_filter/robust_multi_sensor_gaussian_filter_test.cpp", "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": "test/gaussian_filter/robust_multi_sensor_gaussian_filter_test.cpp", "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": "test/gaussian_filter/robust_multi_sensor_gaussian_filter_test.cpp", "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": 36.5968992248, "max_line_length": 80, "alphanum_fraction": 0.5255242533, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5023614558590366}}
{"text": "/*\n * pose.hpp\n *\n *  Copyright (c) 2013 Kumar Robotics. All rights reserved.\n *\n *  This file is part of kr_math.\n *\n *  Created on: 28/06/2014\n *      Author: gareth\n */\n\n#ifndef KR_MATH_POSE_H_\n#define KR_MATH_POSE_H_\n\n/* GTSAM include first since it needs to be included before Eigen as they\n * have a custom Eigen version where they overload some Eigen classes. Having it\n * after the Eigen include prevents their Eigen header being included due to\n * header guards\n */\n#ifdef KR_MATH_GTSAM_CONVERSIONS\n#include <gtsam/geometry/Pose3.h>\n#endif\n\n#include \"base_types.hpp\"\n#include <Eigen/Geometry>\n\n#ifdef KR_MATH_ROS_CONVERSIONS\n#include <geometry_msgs/Pose.h>\n#endif\n\nnamespace kr {\n\n/**\n * @brief Pose, an orientation and position in R3.\n *\n * @note Some important notes on convention:\n *\n * When we write _A to B_ transformation (or transform), it is in reference to\n * the operation effecuated by matrix H, such that:\n *\n * b = H * a, where a is a vector in the A frame and b is that same vector\n * in the B frame.\n *\n * kr::Pose stores `q`, which rotates vectors from body to world frame,\n * and `p`, the center of the body as expressed in the world frame.\n *\n * Transforming a vector v from world to camera (body) is performed with:\n *\n * vb = R(q') * (vw - p), where R(.) maps from S(4) to SO(3).\n *\n * It is important to note that p is equivalent to the body origin in world\n * frame, often denoted wTb.\n *\n */\ntemplate <typename Scalar> struct Pose {\nprivate:\n  kr::Quat<Scalar> q_; /**< Orientation (body to world transform, or wRb) */\n  kr::Vec3<Scalar> p_; /**< Position (origin to body vector) */\n\npublic:\n  /**\n   * @brief Construct with identity pose.\n   */\n  Pose() : q_(1, 0, 0, 0) { p_[0] = p_[1] = p_[2] = 0; }\n\n  /**\n   * @brief Copy-ctor\n   */\n  Pose(const Pose<Scalar> &pose) : q_(pose.q_), p_(pose.p_) {}\n\n  /**\n   * @brief Construct from quaternion and position vector.\n   * @param wQb Body to world rotation.\n   * @param pInW Origin to body vector.\n   */\n  Pose(const Quat<Scalar> &wQb, const Vec3<Scalar> &pInW) : q_(wQb), p_(pInW) {}\n\n  /**\n   * @brief Construct from a 4x4 homogenous transformation matrix.\n   * @param bHw 4x4 matrix representing the body to world transform.\n   *\n   * @note wHb is expected to perform the operation: vw = wHb * vb.\n   */\n  Pose(const kr::Mat4<Scalar>& wHb) :\n    q_(wHb.template block<3,3>(0,0)), p_(wHb.template block<3,1>(0,3)) {}\n\n#ifdef KR_MATH_ROS_CONVERSIONS\n  /**\n   * @brief Construct pose from ROS message.\n   * @param geo Instance of geometry_msgs::Pose.\n   * @note Loss of accuracy will occur if Scalar is float32.\n   */\n  Pose(const geometry_msgs::Pose &geo) {\n    q_ = kr::Quat<Scalar>(geo.orientation.w, geo.orientation.x,\n                         geo.orientation.y, geo.orientation.z);\n    p_[0] = geo.position.x;\n    p_[1] = geo.position.y;\n    p_[2] = geo.position.z;\n  }\n\n  /**\n   * @brief Explicit cast to ROS geometry_msgs::Pose.\n   */\n  explicit operator geometry_msgs::Pose() const {\n    geometry_msgs::Pose geo;\n    geo.orientation.w = q_.w();\n    geo.orientation.x = q_.x();\n    geo.orientation.y = q_.y();\n    geo.orientation.z = q_.z();\n    geo.position.x = p_[0];\n    geo.position.y = p_[1];\n    geo.position.z = p_[2];\n    return geo;\n  }\n#endif\n\n#ifdef KR_MATH_GTSAM_CONVERSIONS\n  /**\n   * @brief Construct pose from GTSAM Pose3.\n   * @param gtpose Instance of GTSAM 6DOF pose. GTSAM poses store a body to\n   * world transformation.\n   */\n  Pose(const gtsam::Pose3& gtpose) :\n    q_(gtpose.rotation().toQuaternion().cast<Scalar>()),\n    p_(gtpose.translation().vector().cast<Scalar>()) {}\n\n  /**\n   * @brief Explicit cast to GTSAM Pose3.\n   * @note Converts to the GTSAM convention of body to world.\n   */\n  explicit operator gtsam::Pose3() const {\n    const gtsam::Rot3 rot(q_.template cast<double>());\n    return gtsam::Pose3(rot, gtsam::Point3(p_.template cast<double>()));\n  }\n#endif\n\n  /**\n   * @brief Position of this pose in the world frame.\n   * @return kr::Vec3\n   */\n  const kr::Vec3<Scalar>& p() const { return p_; }\n  kr::Vec3<Scalar>& p() { return p_; }\n\n  /**\n   * @brief Quaternion that performs the body to world rotation on vectors.\n   * @return kr::Quat\n   */\n  const kr::Quat<Scalar>& q() const { return q_; }\n  kr::Quat<Scalar>& q() { return q_; }\n\n  /**\n   * @brief Construct a pose from an rvec/tvec pair.\n   *\n   * @param rvec Rotation vector. If R = exp(rvec), then R*v will rotate vector\n   * v from world to body frame.\n   * @param tvec Translation vector, or t = -R*p.\n   *\n   * @return The corresponding pose.\n   *\n   * @note The vectors accepted here are in the same form produced by OpenCV.\n   */\n  static Pose<Scalar> fromVectors(const Vec3<Scalar>& rvec,\n                                  const Vec3<Scalar>& tvec) {\n    Vec3<Scalar> rnorm(0.0,0.0,0.0);\n    const Scalar rn = rvec.norm();\n    if (rn > std::numeric_limits<Scalar>::epsilon()*10) {\n      rnorm = rvec / rn;\n    }\n    const Eigen::AngleAxis<Scalar> aa(rn, rnorm);\n    Pose<Scalar> pose;\n    pose.q_ = kr::Quat<Scalar>(aa).conjugate();\n    pose.p_ = -(pose.q_.matrix() * tvec);\n    return pose;\n  }\n\n  /**\n   * @brief Convert this pose so that it is expressed in the body frame of the\n   * argument.\n   *\n   * @param alt Treat as identity reference frame.\n   * @return The receiver, as expressed in frame alt.\n   */\n  Pose<Scalar> expressedIn(const Pose<Scalar> &alt) const {\n    const kr::Vec3<Scalar> pn = alt.bRw() * (p_ - alt.p_);\n    return Pose(alt.q_.conjugate() * q_, pn);\n  }\n\n  /**\n   * @brief Generate the inverse transformation.\n   * @return Inverse of this pose: [R^T, -R * p]\n   *\n   * @note If H is the homo. matrix representation of the receiver, then the\n   * returned pose will have representation H' where H * H' = eye(4).\n   */\n  Pose<Scalar> inverse() const {\n    return Pose<Scalar>().expressedIn(*this);\n  }\n\n  /**\n   * @brief Difference between this pose and the argument in world frame.\n   * @param alt Pose to subtract from the receiver.\n   *\n   * @return The difference between the receiver and the argument, as expressed\n   * in the world frame.\n   */\n  Pose<Scalar> difference(const Pose<Scalar> &alt) const {\n    return Pose(alt.q_.conjugate() * q_, p_ - alt.p_);\n  }\n\n  /**\n   * @brief Translation vector of this pose.\n   * @return Vector corresponding to: t = -bRw * p.\n   */\n  kr::Vec3<Scalar> translation() const { return bRw() * -p_; }\n\n  /**\n   * @brief Compose a pose onto the receiver.\n   * @param rhs Pose to multiply/add onto this one.\n   * @return New pose after composition.\n   *\n   * @note It is assumed that `rhs` expresses a pose in the body frame of the\n   * receiver. This operation therefore rotates `rhs` position vector into the\n   * world frame prior to addition. Orientation is composed from the right,\n   * corresponding to a multiplication in the body frame.\n   */\n  Pose<Scalar> composeInBody(const Pose<Scalar>& rhs) const {\n    return Pose(q_ * rhs.q_, p_ + q_.matrix() * rhs.p_);\n  }\n\n  /**\n   * @brief Transform a point into the body frame of this pose.\n   * @param v Point to transform, expressed in the world frame.\n   * @return Point `v` after conversion to the body frame.\n   */\n  kr::Vec3<Scalar> transformToBody(const kr::Vec3<Scalar>& v) const {\n    return bRw() * (v - p_);\n  }\n\n  /**\n   * @brief Transform a point from the body frame of this pose.\n   * @param v Point to transform, expressed in body frame.\n   * @return Point `v` after conversion to the world frame.\n   */\n  kr::Vec3<Scalar> transformFromBody(const kr::Vec3<Scalar>& v) const {\n    return wRb()*v + p_;\n  }\n\n  /**\n   * @brief SE(3) transformation corresponding to this pose.\n   * @return 4x4 matrix that performs the body to world transformation: wHb\n   */\n  kr::Mat4<Scalar> matrix() const {\n    kr::Mat4<Scalar> H;\n    H.template block<3,3>(0,0) = q_.matrix();\n    H.template block<3,1>(0,3) = p_;\n    H(3,0) = H(3,1) = H(3,2) = 0;\n    H(3,3) = 1;\n    return H;\n  }\n\n  /**\n   * @brief Shorthand for body to world rotation.\n   * @note wP = wRb * bP + wTb\n   */\n  kr::Mat3<Scalar> wRb() const {\n    return q_.matrix();\n  }\n\n  /**\n   * @brief Shorthand for world to body roration.\n   * @note bP = bRw * wP + bTw\n   */\n  kr::Mat3<Scalar> bRw() const {\n    return q_.conjugate().matrix();\n  }\n\n  /**\n   * @brief bTw Translation from body to world in body frame\n   * @note bP = bRw * wP + bTw\n   * @note Equivalent to the 'translation' vector.\n   */\n  kr::Vec3<Scalar> bTw() const {\n    return translation(); //  -(bRw() * wTb())\n  }\n\n  /**\n   * @brief Shorthand for translation vector from world origin to body.\n   * @note wP = wRb * bP + wTb\n   */\n  const kr::Vec3<Scalar>& wTb() const {\n    return p_;\n  }\n};\n\ntypedef Pose<float> Posef;\ntypedef Pose<double> Posed;\n\n} // namespace kr\n\n#endif // KR_MATH_POSE_H_\n", "meta": {"hexsha": "d4a6711293703a68941bb26e4bdd6477522efa8a", "size": 8736, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kr_math/include/kr_math/pose.hpp", "max_stars_repo_name": "KumarRobotics/kr_utils", "max_stars_repo_head_hexsha": "049685a8fd9bb8a37490cafeda94b4ab652c829e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-10-12T01:59:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-19T05:03:26.000Z", "max_issues_repo_path": "kr_math/include/kr_math/pose.hpp", "max_issues_repo_name": "KumarRobotics/kr_utils", "max_issues_repo_head_hexsha": "049685a8fd9bb8a37490cafeda94b4ab652c829e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-02-25T08:58:26.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-29T07:25:38.000Z", "max_forks_repo_path": "kr_math/include/kr_math/pose.hpp", "max_forks_repo_name": "KumarRobotics/kr_utils", "max_forks_repo_head_hexsha": "049685a8fd9bb8a37490cafeda94b4ab652c829e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:39:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-19T05:03:30.000Z", "avg_line_length": 29.023255814, "max_line_length": 80, "alphanum_fraction": 0.6365613553, "num_tokens": 2530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.5023284132359102}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/filtered_graph.hpp>\n\nnamespace boost {\n\tenum vertex_component_t { vertex_component = 1111111 };\n\tBOOST_INSTALL_PROPERTY(vertex, component);\n}\n\nusing namespace boost;\n\ntemplate <typename ComponentMap>\nstruct vertexComponent {\n\t\n\tvertexComponent() {}\n\t\n\tvertexComponent(ComponentMap component, int f_component) : m_component(component), m_f_component(f_component) {}\n\t\n\ttemplate <typename Vertex>\n\tbool operator()(const Vertex& v) const {\n\t\treturn (get(m_component, v) == m_f_component);\n\t}\n\t\n\tComponentMap m_component;\n\tint m_f_component;\n};\n\nint main(int argc, char ** argv) {\n\t\n\ttypedef adjacency_list<vecS, vecS, undirectedS, property<vertex_component_t, int> > Graph;\n\t\n\ttypedef property_map<Graph, vertex_component_t>::type ComponentMap;\n\ttypedef filtered_graph<Graph, keep_all,\tvertexComponent<ComponentMap> > FilteredGraph;\n\t\n\tgraph_traits < Graph >::vertex_iterator vi, vi_end;\n\tgraph_traits < Graph >::out_edge_iterator oei, oei_end;\n\tgraph_traits < FilteredGraph >::vertex_iterator fvi, fvi_end;\n\tgraph_traits < FilteredGraph >::out_edge_iterator foei, foei_end;\n\t\n\tGraph * g;\n\tFilteredGraph * fg;\n\t\n\tenum { A, B, C, D, E, F, G, H, I, N };\n\tconst char* name = \"ABCDEFGHI\";\n\tg = new Graph(N);\n\tadd_edge(A, B, *g);\n\tadd_edge(C, D, *g);\n\tadd_edge(D, E, *g);\n\tadd_edge(E, C, *g);\n\tadd_edge(F, A, *g);\n\tadd_edge(F, B, *g);\n\tadd_edge(G, H, *g);\n\tadd_edge(G, I, *g);\n\tadd_edge(H, I, *g);\n\t\n\tstd::cout<<std::endl<<\"Graph out-edges:\"<<std::endl;\n\tfor (tie(vi, vi_end) = vertices(*g); vi != vi_end; ++vi) {\n\t\tstd::cout<<name[*vi]<<\" outedges - \";\n\t\tfor(tie(oei, oei_end)=out_edges(*vi, *g); oei != oei_end; ++oei) {\n\t\t\tstd::cout<<name[source(*oei, *g)]<<\"-->\"<<name[target(*oei, *g)]<<\"  \";\n\t\t}\n\t\tstd::cout<<std::endl;\n\t}\n\tstd::cout<<std::endl;\n\t\n\tint numComponents = connected_components(*g, get(vertex_component, *g));\n\t\n\tstd::cout<<\"Graph has \"<<numComponents<<\" components.\"<<std::endl<<std::endl;\n\t\n\tfor(int i=0; i<numComponents; i++) {\n\t\tkeep_all efilter;\n\t\tvertexComponent<ComponentMap> vfilter(get(vertex_component, *g), i);\n\t\tfg = new FilteredGraph(*g, efilter, vfilter);\n\t\t\n\t\tstd::cout<<\"Filtered graph (component \"<<i<<\") out-edges:\"<<std::endl;\n\t\tfor (tie(fvi, fvi_end) = vertices(*fg); fvi != fvi_end; ++fvi) {    \n\t\t\tstd::cout<<name[*fvi]<<\" outedges - \";    \n\t\t\tfor(tie(foei, foei_end)=out_edges(*fvi, *fg); foei != foei_end; ++foei) {\n\t\t\t\tstd::cout<<name[source(*foei, *fg)]<<\"-->\"<<name[target(*foei, *fg)]<<\"  \";\n\t\t\t}\n\t\t\tstd::cout<<std::endl;\n\t\t}\n\t\tstd::cout<<std::endl;\n\t\t\n\t\tdelete fg;\n\t\tfg = NULL;\n\t}\n\t\n\tdelete g;\n\tg = NULL;\n\t\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "6ce64ad957211448a5440a993d85430b4fdcb19f", "size": 2702, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cppsandbox/main.cpp", "max_stars_repo_name": "preciserobot/rex", "max_stars_repo_head_hexsha": "91b58e22ea45b56b01a2cdd2ea63b253c9edc467", "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": "src/cppsandbox/main.cpp", "max_issues_repo_name": "preciserobot/rex", "max_issues_repo_head_hexsha": "91b58e22ea45b56b01a2cdd2ea63b253c9edc467", "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": "src/cppsandbox/main.cpp", "max_forks_repo_name": "preciserobot/rex", "max_forks_repo_head_hexsha": "91b58e22ea45b56b01a2cdd2ea63b253c9edc467", "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": 28.4421052632, "max_line_length": 113, "alphanum_fraction": 0.6639526277, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5023284005380704}}
{"text": "// Bring in gtest\n#include <gtest/gtest.h>\n#include <boost/cstdint.hpp>\n\n// Helpful functions from libsm\n#include <sm/eigen/gtest.hpp>\n#include <sm/kinematics/quaternion_algebra.hpp>\n#include <sm/kinematics/Transformation.hpp>\n\n\n\nTEST(TransformationTestSuite, testConstructor)\n{\n  using namespace sm::kinematics;\n\n  Transformation T_a_b;\n  Eigen::Matrix4d T;\n  T.setIdentity();\n  \n  sm::eigen::assertNear(T, T_a_b.T(), 1e-10, SM_SOURCE_FILE_POS, \"Checking for the default constructor creating identity\");\n\n}\n\n\nTEST(TransformationTestSuite, testTV4Multiplication)\n{\n  using namespace sm::kinematics;\n\n  for(int i = 0; i < 100; i++)\n    {\n      Transformation T_a_b(quatRandom(), Eigen::Vector3d::Random() * 100);\n      Eigen::Vector4d v_b;\n      v_b.setRandom();\n      v_b *= 100.0;\n      \n      Eigen::Vector4d v_a = T_a_b * v_b;\n      Eigen::Vector4d v_a_prime = T_a_b.T() * v_b;\n      sm::eigen::assertNear(v_a, v_a_prime, 1e-10, SM_SOURCE_FILE_POS, \"Checking for composition equal to matrix multiplication\");\n    }\n\n\n}\n\nTEST(TransformationTestSuite, testTVhMultiplication)\n{\n  using namespace sm::kinematics;\n\n  for(int i = 0; i < 100; i++)\n    {\n      Transformation T_a_b(quatRandom(), Eigen::Vector3d::Random() * 100);\n      Eigen::Vector3d v_b;\n      v_b.setRandom();\n      v_b *= 100.0;\n      HomogeneousPoint V_b(v_b);\n      \n      Eigen::Vector3d v_a = T_a_b * v_b;\n      HomogeneousPoint V_a = T_a_b * V_b;\n      sm::eigen::assertNear(V_a.toEuclidean(), v_a, 1e-10, SM_SOURCE_FILE_POS, \"Checking for composition equal to matrix multiplication\");\n    }\n\n\n}\n\n\nTEST(TransformationTestSuite, testTVMultiplication)\n{\n  using namespace sm::kinematics;\n\n  for(int i = 0; i < 100; i++)\n    {\n      Transformation T_a_b(quatRandom(), Eigen::Vector3d::Random() * 100);\n      Eigen::Vector3d v_b;\n      v_b.setRandom();\n      v_b *= 100.0;\n      \n      Eigen::Vector3d v_a = T_a_b * v_b;\n      Eigen::Vector3d v_a_prime = T_a_b.C() * v_b + T_a_b.t();\n      sm::eigen::assertNear(v_a, v_a_prime, 1e-10, SM_SOURCE_FILE_POS, \"Checking for composition equal to matrix multiplication\");\n    }\n\n\n}\n\n\n\nTEST(TransformationTestSuite, testTTMultiplication)\n{\n  using namespace sm::kinematics;\n\n  for(int i = 0; i < 100; i++)\n    {\n      Transformation T_a_b(quatRandom(), Eigen::Vector3d::Random() * 100);\n      Transformation T_b_c(quatRandom(), Eigen::Vector3d::Random() * 100);\n      \n      Transformation T_a_c = T_a_b * T_b_c;\n      Eigen::Matrix4d T_a_c_prime = T_a_b.T() * T_b_c.T();\n      sm::eigen::assertNear(T_a_c.T(), T_a_c_prime, 1e-10, SM_SOURCE_FILE_POS, \"Checking for composition equal to matrix multiplication\");\n    }\n\n\n}\n\n\nTEST(TransformationTestSuite, testInvert)\n{\n  using namespace sm::kinematics;\n\n  for(int i = 0; i < 100; i++)\n    {\n      Transformation T_a_b(quatRandom(), Eigen::Vector3d::Random());\n\n      Transformation T_b_a = T_a_b.inverse();\n      Transformation T_a_b_prime = T_b_a.inverse();\n      \n      sm::eigen::assertNear(T_a_b_prime.T(), T_a_b.T(), 1e-10, SM_SOURCE_FILE_POS, \"Checking for identity\");\n  \n    }\n}\n\nTEST(TransformationTestSuite, testInvertProducesIdentity)\n{\n  using namespace sm::kinematics;\n\n  for(int i = 0; i < 100; i++)\n    {\n      Transformation T_a_b(quatRandom(), Eigen::Vector3d::Random());      \n      Transformation T_b_a = T_a_b.inverse();\n      Transformation Eye1 = T_a_b * T_b_a;\n      Transformation Eye2 = T_b_a * T_a_b;\n      \n      sm::eigen::assertNear(Eye1.T(), Eigen::Matrix4d::Identity(), 1e-10, SM_SOURCE_FILE_POS, \"Checking for identity\");\n      sm::eigen::assertNear(Eye2.T(), Eigen::Matrix4d::Identity(), 1e-10, SM_SOURCE_FILE_POS, \"Checking for identity\");\n    }\n\n\n}\n", "meta": {"hexsha": "2897741b31f88036944b4b64245eddcfd0662100", "size": 3640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_kinematics/test/TransformationTests.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/test/TransformationTests.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/test/TransformationTests.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": 26.5693430657, "max_line_length": 138, "alphanum_fraction": 0.6634615385, "num_tokens": 1056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5023283958798158}}
{"text": "#define BOOST_TEST_DYN_LINK\n\n// clang-format off\n#include <boost/test/unit_test.hpp>\n// clang-format on\n\n#include <sstream>\n\n#include <nuschl/number.hpp>\n\nBOOST_AUTO_TEST_SUITE(Number)\nBOOST_AUTO_TEST_CASE(comparison) {\n    nuschl::number a(2);\n    nuschl::number b(2);\n    nuschl::number c(3);\n    nuschl::number d(0);\n\n    BOOST_CHECK(a == b);\n    BOOST_CHECK(!(a == c));\n    BOOST_CHECK(a != c);\n    BOOST_CHECK(!(a == c));\n    BOOST_CHECK(a < c);\n    BOOST_CHECK(d < a);\n    BOOST_CHECK(c > a);\n    BOOST_CHECK(b > d);\n}\n\nBOOST_AUTO_TEST_CASE(cast) {\n    nuschl::number a(2);\n    BOOST_CHECK_EQUAL(a.get_value(), 2);\n}\n\nBOOST_AUTO_TEST_CASE(negate) {\n    nuschl::number a(2);\n    BOOST_CHECK_EQUAL((-a).get_value(), -2);\n}\n\nBOOST_AUTO_TEST_CASE(addition) {\n    nuschl::number a(2);\n    nuschl::number b(2);\n    nuschl::number c(4);\n    nuschl::number d(0);\n\n    BOOST_CHECK_EQUAL(a + b, c);\n    BOOST_CHECK_EQUAL(a + d, b);\n}\n\nBOOST_AUTO_TEST_CASE(subtraction) {\n    nuschl::number a(2);\n    nuschl::number b(2);\n    nuschl::number c(4);\n    nuschl::number d(0);\n\n    BOOST_CHECK_EQUAL(a - a, d);\n    BOOST_CHECK_EQUAL(a - b, d);\n    BOOST_CHECK_EQUAL(c - b, b);\n}\n\nBOOST_AUTO_TEST_CASE(multiplication) {\n    nuschl::number a(2);\n    nuschl::number b(2);\n    nuschl::number c(4);\n    nuschl::number d(0);\n\n    BOOST_CHECK_EQUAL(a * b, c);\n    BOOST_CHECK_EQUAL(a * d, d);\n}\n\nBOOST_AUTO_TEST_CASE(division) {\n    nuschl::number a(2);\n    nuschl::number b(2);\n    nuschl::number c(4);\n    nuschl::number d(0);\n\n    BOOST_CHECK_EQUAL(c / b, a);\n    BOOST_CHECK_EQUAL(d / c, d);\n}\n\nBOOST_AUTO_TEST_CASE(ostream) {\n    std::stringstream ss;\n    nuschl::number c(4);\n    ss << c;\n    BOOST_CHECK_EQUAL(ss.str(), \"4\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "837e1eb5172f312ef32bbd1dac1e08b52591951f", "size": 1747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unittests/number.cpp", "max_stars_repo_name": "behlec/nuschl", "max_stars_repo_head_hexsha": "35dbdd6dca8e59387623cc8a23f71324e07ea98c", "max_stars_repo_licenses": ["MIT"], "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/unittests/number.cpp", "max_issues_repo_name": "behlec/nuschl", "max_issues_repo_head_hexsha": "35dbdd6dca8e59387623cc8a23f71324e07ea98c", "max_issues_repo_licenses": ["MIT"], "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/unittests/number.cpp", "max_forks_repo_name": "behlec/nuschl", "max_forks_repo_head_hexsha": "35dbdd6dca8e59387623cc8a23f71324e07ea98c", "max_forks_repo_licenses": ["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.0804597701, "max_line_length": 44, "alphanum_fraction": 0.6302232398, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5023032058414914}}
{"text": "#include \"Common/Common.h\"\n#include \"Demos/Visualization/MiniGL.h\"\n#include \"Demos/Visualization/Selection.h\"\n#include \"Simulation/TimeManager.h\"\n#include <Eigen/Dense>\n#include \"Simulation/SimulationModel.h\"\n#include \"Simulation/TimeStepController.h\"\n#include <iostream>\n#include \"Demos/Visualization/Visualization.h\"\n#include \"Simulation/DistanceFieldCollisionDetection.h\"\n#include \"Utils/OBJLoader.h\"\n#include \"Utils/Logger.h\"\n#include \"Utils/Timing.h\"\n#include \"Utils/FileSystem.h\"\n#include \"Demos/Common/DemoBase.h\"\n#include \"Demos/Common/TweakBarParameters.h\"\n#include \"Simulation/Simulation.h\"\n\n\n// Enable memory leak detection\n#if defined(_DEBUG) && !defined(EIGEN_ALIGN)\n\t#define new DEBUG_NEW \n#endif\n\nusing namespace PBD;\nusing namespace Eigen;\nusing namespace std;\nusing namespace Utilities;\n\nvoid timeStep ();\nvoid buildModel ();\nvoid createMesh();\nvoid render ();\nvoid reset();\nvoid TW_CALL setBendingMethod(const void *value, void *clientData);\nvoid TW_CALL getBendingMethod(void *value, void *clientData);\nvoid TW_CALL setSimulationMethod(const void *value, void *clientData);\nvoid TW_CALL getSimulationMethod(void *value, void *clientData);\nvoid TW_CALL setBendingStiffness(const void* value, void* clientData);\nvoid TW_CALL getBendingStiffness(void* value, void* clientData);\nvoid TW_CALL setDistanceStiffness(const void* value, void* clientData);\nvoid TW_CALL getDistanceStiffness(void* value, void* clientData);\nvoid TW_CALL setXXStiffness(const void* value, void* clientData);\nvoid TW_CALL getXXStiffness(void* value, void* clientData);\nvoid TW_CALL setYYStiffness(const void* value, void* clientData);\nvoid TW_CALL getYYStiffness(void* value, void* clientData);\nvoid TW_CALL setXYStiffness(const void* value, void* clientData);\nvoid TW_CALL getXYStiffness(void* value, void* clientData);\nvoid TW_CALL setXYPoissonRatio(const void* value, void* clientData);\nvoid TW_CALL getXYPoissonRatio(void* value, void* clientData);\nvoid TW_CALL setYXPoissonRatio(const void* value, void* clientData);\nvoid TW_CALL getYXPoissonRatio(void* value, void* clientData);\nvoid TW_CALL setNormalizeStretch(const void* value, void* clientData);\nvoid TW_CALL getNormalizeStretch(void* value, void* clientData);\nvoid TW_CALL setNormalizeShear(const void* value, void* clientData);\nvoid TW_CALL getNormalizeShear(void* value, void* clientData);\n\n\nconst int nRows = 50;\nconst int nCols = 50;\nconst Real width = 10.0;\nconst Real height = 10.0;\nshort simulationMethod = 2;\nshort bendingMethod = 2;\nReal distanceStiffness = 1.0;\nReal xxStiffness = 1.0;\nReal yyStiffness = 1.0;\nReal xyStiffness = 1.0;\nReal xyPoissonRatio = 0.3;\nReal yxPoissonRatio = 0.3;\nbool normalizeStretch = false;\nbool normalizeShear = false;\nReal bendingStiffness = 0.01;\nbool doPause = true;\nDemoBase *base;\nDistanceFieldCollisionDetection cd;\n\n// main \nint main( int argc, char **argv )\n{\n\tREPORT_MEMORY_LEAKS\n\n\tbase = new DemoBase();\n\tbase->init(argc, argv, \"Cloth demo\");\n\n\tSimulationModel *model = new SimulationModel();\n\tmodel->init();\n\tSimulation::getCurrent()->setModel(model);\n\n\tbuildModel();\n\n\tbase->createParameterGUI();\n\n\t// OpenGL\n\tMiniGL::setClientIdleFunc (timeStep);\t\t\n\tMiniGL::addKeyFunc('r', reset);\n\tMiniGL::setClientSceneFunc(render);\t\t\t\n\tMiniGL::setViewport (40.0f, 0.1f, 500.0f, Vector3r (0.0, 10.0, 25.0), Vector3r (0.0, 0.0, 0.0));\n\n\tTwType enumType2 = TwDefineEnum(\"SimulationMethodType\", NULL, 0);\n\tTwAddVarCB(MiniGL::getTweakBar(), \"SimulationMethod\", enumType2, setSimulationMethod, getSimulationMethod, &simulationMethod, \n\t\t\" label='Simulation method' enum='0 {None}, 1 {Distance constraints}, 2 {FEM based PBD}, 3 {Strain based dynamics}, 4 {XPBD distance constraints}' group=Simulation\");\n\tTwType enumType3 = TwDefineEnum(\"BendingMethodType\", NULL, 0);\n\tTwAddVarCB(MiniGL::getTweakBar(), \"BendingMethod\", enumType3, setBendingMethod, getBendingMethod, &bendingMethod, \n\t\t\" label='Bending method' enum='0 {None}, 1 {Dihedral angle}, 2 {Isometric bending}, 3 {XPBD isometric bending}' group=Bending\");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"BendingStiffness\", TW_TYPE_REAL, setBendingStiffness, getBendingStiffness, model, \" label='Bending stiffness'  min=0.0 step=0.1 precision=4 group='Bending' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"DistanceStiffness\", TW_TYPE_REAL, setDistanceStiffness, getDistanceStiffness, model, \" label='Distance constraint stiffness'  min=0.0 step=0.1 precision=4 group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"xxStiffness\", TW_TYPE_REAL, setXXStiffness, getXXStiffness, model, \" label='xx stiffness'  min=0.0 step=0.1 precision=4 group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"yyStiffness\", TW_TYPE_REAL, setYYStiffness, getYYStiffness, model, \" label='yy stiffness'  min=0.0 step=0.1 precision=4 group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"xyStiffness\", TW_TYPE_REAL, setXYStiffness, getXYStiffness, model, \" label='xy stiffness'  min=0.0 step=0.1 precision=4 group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"xyPoissonRatio\", TW_TYPE_REAL, setXYPoissonRatio, getXYPoissonRatio, model, \" label='xy Poisson ratio'  min=0.0 step=0.1 precision=4 group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"yxPoissonRatio\", TW_TYPE_REAL, setYXPoissonRatio, getYXPoissonRatio, model, \" label='yx Poisson ratio'  min=0.0 step=0.1 precision=4 group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"normalizeStretch\", TW_TYPE_BOOL32, setNormalizeStretch, getNormalizeStretch, model, \" label='Normalize stretch' group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"normalizeShear\", TW_TYPE_BOOL32, setNormalizeShear, getNormalizeShear, model, \" label='Normalize shear' group='Cloth' \");\n\n\tMiniGL::mainLoop();\t\n\n\tbase->cleanup();\n\n\tUtilities::Timing::printAverageTimes();\n\tUtilities::Timing::printTimeSums();\n\n\tdelete Simulation::getCurrent();\n\tdelete base;\n\tdelete model;\n\n\treturn 0;\n}\n\nvoid reset()\n{\n\tUtilities::Timing::printAverageTimes();\n\tUtilities::Timing::reset();\n\n\tSimulation::getCurrent()->reset();\n\tbase->getSelectedParticles().clear();\n\n\tSimulation::getCurrent()->getModel()->cleanup();\n\tcd.cleanup();\n\n\tbuildModel();\n}\n\nvoid timeStep ()\n{\n\tconst Real pauseAt = base->getValue<Real>(DemoBase::PAUSE_AT);\n\tif ((pauseAt > 0.0) && (pauseAt < TimeManager::getCurrent()->getTime()))\n\t\tbase->setValue(DemoBase::PAUSE, true);\n\n\tif (base->getValue<bool>(DemoBase::PAUSE))\n\t\treturn;\n\n\t// Simulation code\n\tSimulationModel *model = Simulation::getCurrent()->getModel();\n\tconst unsigned int numSteps = base->getValue<unsigned int>(DemoBase::NUM_STEPS_PER_RENDER);\n\tfor (unsigned int i = 0; i < numSteps; i++)\n\t{\n\t\tSTART_TIMING(\"SimStep\");\n\t\tSimulation::getCurrent()->getTimeStep()->step(*model);\n\t\tSTOP_TIMING_AVG;\n\t}\n\n\tfor (unsigned int i = 0; i < model->getTriangleModels().size(); i++)\n\t\tmodel->getTriangleModels()[i]->updateMeshNormals(model->getParticles());\n}\n\nvoid loadObj(const std::string &filename, VertexData &vd, IndexedFaceMesh &mesh, const Vector3r &scale)\n{\n\tstd::vector<OBJLoader::Vec3f> x;\n\tstd::vector<OBJLoader::Vec3f> normals;\n\tstd::vector<OBJLoader::Vec2f> texCoords;\n\tstd::vector<MeshFaceIndices> faces;\n\tOBJLoader::Vec3f s = { (float)scale[0], (float)scale[1], (float)scale[2] };\n\tOBJLoader::loadObj(filename, &x, &faces, &normals, &texCoords, s);\n\n\tmesh.release();\n\tconst unsigned int nPoints = (unsigned int)x.size();\n\tconst unsigned int nFaces = (unsigned int)faces.size();\n\tconst unsigned int nTexCoords = (unsigned int)texCoords.size();\n\tmesh.initMesh(nPoints, nFaces * 2, nFaces);\n\tvd.reserve(nPoints);\n\tfor (unsigned int i = 0; i < nPoints; i++)\n\t{\n\t\tvd.addVertex(Vector3r(x[i][0], x[i][1], x[i][2]));\n\t}\n\tfor (unsigned int i = 0; i < nTexCoords; i++)\n\t{\n\t\tmesh.addUV(texCoords[i][0], texCoords[i][1]);\n\t}\n\tfor (unsigned int i = 0; i < nFaces; i++)\n\t{\n\t\t// Reduce the indices by one\n\t\tint posIndices[3];\n\t\tint texIndices[3];\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tposIndices[j] = faces[i].posIndices[j] - 1;\n\t\t\tif (nTexCoords > 0)\n\t\t\t{\n\t\t\t\ttexIndices[j] = faces[i].texIndices[j] - 1;\n\t\t\t\tmesh.addUVIndex(texIndices[j]);\n\t\t\t}\n\t\t}\n\n\t\tmesh.addFace(&posIndices[0]);\n\t}\n\tmesh.buildNeighbors();\n\n\tmesh.updateNormals(vd, 0);\n\tmesh.updateVertexNormals(vd);\n\n\tLOG_INFO << \"Number of triangles: \" << nFaces;\n\tLOG_INFO << \"Number of vertices: \" << nPoints;\n}\n\nvoid buildModel ()\n{\n\tTimeManager::getCurrent ()->setTimeStepSize (static_cast<Real>(0.005));\n\n\tcreateMesh();\n\n\t// create static rigid body\n\tstring fileName = FileSystem::normalizePath(base->getExePath() + \"/resources/models/cube.obj\");\n\tIndexedFaceMesh mesh;\n\tVertexData vd;\n\tloadObj(fileName, vd, mesh, Vector3r::Ones());\n\tmesh.setFlatShading(true);\n\n\tstring fileNameTorus = FileSystem::normalizePath(base->getExePath() + \"/resources/models/torus.obj\");\n\tIndexedFaceMesh meshTorus;\n\tVertexData vdTorus;\n\tloadObj(fileNameTorus, vdTorus, meshTorus, Vector3r::Ones());\n\n\tSimulationModel *model = Simulation::getCurrent()->getModel();\n\tSimulationModel::RigidBodyVector &rb = model->getRigidBodies();\n\trb.resize(2);\n\n\t// floor\n\trb[0] = new RigidBody();\n\trb[0]->initBody(1.0,\n\t\tVector3r(0.0, -2.5, 0.0),\n\t\tQuaternionr(1.0, 0.0, 0.0, 0.0),\n\t\tvd, mesh,\n\t\tVector3r(100.0, 1.0, 100.0));\n\trb[0]->setMass(0.0);\n\n\t// torus\n\trb[1] = new RigidBody();\n\trb[1]->initBody(1.0,\n\t\tVector3r(0.0, 1.5, 0.0),\n\t\tQuaternionr(1.0, 0.0, 0.0, 0.0),\n\t\tvdTorus, meshTorus,\n\t\tVector3r(2.0, 2.0, 2.0));\n\trb[1]->setMass(0.0);\n\trb[1]->setFrictionCoeff(static_cast<Real>(0.1));\n\n\tSimulation::getCurrent()->getTimeStep()->setCollisionDetection(*model, &cd);\n\tcd.setTolerance(static_cast<Real>(0.05));\n\n\tconst std::vector<Vector3r> &vertices1 = rb[0]->getGeometry().getVertexDataLocal().getVertices();\n\tconst unsigned int nVert1 = static_cast<unsigned int>(vertices1.size());\n\tcd.addCollisionBox(0, CollisionDetection::CollisionObject::RigidBodyCollisionObjectType, vertices1.data(), nVert1, Vector3r(100.0, 1.0, 100.0));\n\n\tconst std::vector<Vector3r> &vertices2 = rb[1]->getGeometry().getVertexDataLocal().getVertices();\n\tconst unsigned int nVert2 = static_cast<unsigned int>(vertices2.size());\n\tcd.addCollisionTorus(1, CollisionDetection::CollisionObject::RigidBodyCollisionObjectType, vertices2.data(), nVert2, Vector2r(2.0, 1.0));\n\t\n\tSimulationModel::TriangleModelVector &tm = model->getTriangleModels();\n\tParticleData &pd = model->getParticles();\n\tfor (unsigned int i = 0; i < tm.size(); i++)\n\t{\n\t\tconst unsigned int nVert = tm[i]->getParticleMesh().numVertices();\n\t\tunsigned int offset = tm[i]->getIndexOffset();\n\t\ttm[i]->setFrictionCoeff(static_cast<Real>(0.1));\n\t\tcd.addCollisionObjectWithoutGeometry(i, CollisionDetection::CollisionObject::TriangleModelCollisionObjectType, &pd.getPosition(offset), nVert, true);\n\t}\n}\n\nvoid render ()\n{\n\tbase->render();\n}\n\n\n/** Create a particle model mesh \n*/\nvoid createMesh()\n{\n\tSimulationModel* model = Simulation::getCurrent()->getModel();\n\tmodel->addRegularTriangleModel(nCols, nRows,\n\t\tVector3r(-5, 4, -5), AngleAxisr(M_PI * 0.5, Vector3r(1, 0, 0)).matrix(), Vector2r(width, height));\n\n\t// init constraints\n\tfor (unsigned int cm = 0; cm < model->getTriangleModels().size(); cm++)\n\t{\n\t\tdistanceStiffness = 1.0;\n\t\tif (simulationMethod == 4)\n\t\t\tdistanceStiffness = 100000;\n\t\tmodel->addClothConstraints(model->getTriangleModels()[cm], simulationMethod, distanceStiffness, xxStiffness, \n\t\t\tyyStiffness, xyStiffness, xyPoissonRatio, yxPoissonRatio, normalizeStretch, normalizeShear);\n\n\t\tbendingStiffness = 0.01;\n\t\tif (bendingMethod == 3)\n\t\t\tbendingStiffness = 100.0;\n\t\tmodel->addBendingConstraints(model->getTriangleModels()[cm], bendingMethod, bendingStiffness);\n\t}\n\n\tLOG_INFO << \"Number of triangles: \" << model->getTriangleModels()[0]->getParticleMesh().numFaces();\n\tLOG_INFO << \"Number of vertices: \" << nRows*nCols;\n\n}\n\nvoid TW_CALL setBendingMethod(const void *value, void *clientData)\n{\n\tconst short val = *(const short *)(value);\n\t*((short*)clientData) = val;\n\treset();\n}\n\nvoid TW_CALL getBendingMethod(void *value, void *clientData)\n{\n\t*(short *)(value) = *((short*)clientData);\n}\n\nvoid TW_CALL setSimulationMethod(const void *value, void *clientData)\n{\n\tconst short val = *(const short *)(value);\n\t*((short*)clientData) = val;\n\treset();\n}\n\nvoid TW_CALL getSimulationMethod(void *value, void *clientData)\n{\n\t*(short *)(value) = *((short*)clientData);\n}\n\nvoid TW_CALL setBendingStiffness(const void* value, void* clientData)\n{\n\tbendingStiffness = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<DihedralConstraint, Real, &DihedralConstraint::m_stiffness>(bendingStiffness);\n\t((SimulationModel*)clientData)->setConstraintValue<IsometricBendingConstraint, Real, &IsometricBendingConstraint::m_stiffness>(bendingStiffness);\n\t((SimulationModel*)clientData)->setConstraintValue<IsometricBendingConstraint_XPBD, Real, &IsometricBendingConstraint_XPBD::m_stiffness>(bendingStiffness);\n}\n\nvoid TW_CALL getBendingStiffness(void* value, void* clientData)\n{\n\t*(Real*)(value) = bendingStiffness;\n}\n\nvoid TW_CALL setDistanceStiffness(const void* value, void* clientData)\n{\n\tdistanceStiffness = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<DistanceConstraint, Real, &DistanceConstraint::m_stiffness>(distanceStiffness);\n\t((SimulationModel*)clientData)->setConstraintValue<DistanceConstraint_XPBD, Real, &DistanceConstraint_XPBD::m_stiffness>(distanceStiffness);\n}\n\nvoid TW_CALL getDistanceStiffness(void* value, void* clientData)\n{\n\t*(Real*)(value) = distanceStiffness;\n}\n\nvoid TW_CALL setXXStiffness(const void* value, void* clientData)\n{\n\txxStiffness = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<FEMTriangleConstraint, Real, &FEMTriangleConstraint::m_xxStiffness>(xxStiffness);\n\t((SimulationModel*)clientData)->setConstraintValue<StrainTriangleConstraint, Real, &StrainTriangleConstraint::m_xxStiffness>(xxStiffness);\n}\n\nvoid TW_CALL getXXStiffness(void* value, void* clientData)\n{\n\t*(Real*)(value) = xxStiffness;\n}\n\nvoid TW_CALL getYYStiffness(void* value, void* clientData)\n{\n\t*(Real*)(value) = yyStiffness;\n}\n\nvoid TW_CALL setYYStiffness(const void* value, void* clientData)\n{\n\tyyStiffness = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<FEMTriangleConstraint, Real, &FEMTriangleConstraint::m_yyStiffness>(yyStiffness);\n\t((SimulationModel*)clientData)->setConstraintValue<StrainTriangleConstraint, Real, &StrainTriangleConstraint::m_yyStiffness>(yyStiffness);\n}\n\nvoid TW_CALL getXYStiffness(void* value, void* clientData)\n{\n\t*(Real*)(value) = xyStiffness;\n}\n\nvoid TW_CALL setXYStiffness(const void* value, void* clientData)\n{\n\txyStiffness = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<FEMTriangleConstraint, Real, &FEMTriangleConstraint::m_xyStiffness>(xyStiffness);\n\t((SimulationModel*)clientData)->setConstraintValue<StrainTriangleConstraint, Real, &StrainTriangleConstraint::m_xyStiffness>(xyStiffness);\n}\n\nvoid TW_CALL getXYPoissonRatio(void* value, void* clientData)\n{\n\t*(Real*)(value) = xyPoissonRatio;\n}\n\nvoid TW_CALL setXYPoissonRatio(const void* value, void* clientData)\n{\n\txyPoissonRatio = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<FEMTriangleConstraint, Real, &FEMTriangleConstraint::m_xyPoissonRatio>(xyPoissonRatio);\n}\n\nvoid TW_CALL getYXPoissonRatio(void* value, void* clientData)\n{\n\t*(Real*)(value) = yxPoissonRatio;\n}\n\nvoid TW_CALL setYXPoissonRatio(const void* value, void* clientData)\n{\n\tyxPoissonRatio = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<FEMTriangleConstraint, Real, &FEMTriangleConstraint::m_yxPoissonRatio>(yxPoissonRatio);\n}\n\nvoid TW_CALL getNormalizeStretch(void* value, void* clientData)\n{\n\t*(bool*)(value) = normalizeStretch;\n}\n\nvoid TW_CALL setNormalizeStretch(const void* value, void* clientData)\n{\n\tnormalizeStretch = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<StrainTriangleConstraint, bool, &StrainTriangleConstraint::m_normalizeStretch>(normalizeStretch);\n}\n\nvoid TW_CALL getNormalizeShear(void* value, void* clientData)\n{\n\t*(bool*)(value) = normalizeShear;\n}\n\nvoid TW_CALL setNormalizeShear(const void* value, void* clientData)\n{\n\tnormalizeShear= *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<StrainTriangleConstraint, bool, &StrainTriangleConstraint::m_normalizeShear>(normalizeShear);\n}", "meta": {"hexsha": "92ce4f14c73c6518bdbfa4f8df2bf5e78c889819", "size": 16223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Demos/DistanceFieldDemos/ClothCollisionDemo.cpp", "max_stars_repo_name": "mcx/PositionBasedDynamics", "max_stars_repo_head_hexsha": "136469f03f7869666d907ea8d27872b098715f4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1169.0, "max_stars_repo_stars_event_min_datetime": "2016-05-31T03:01:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:38:47.000Z", "max_issues_repo_path": "Demos/DistanceFieldDemos/ClothCollisionDemo.cpp", "max_issues_repo_name": "Taiyuan-Zhang/PositionBasedDynamics", "max_issues_repo_head_hexsha": "136469f03f7869666d907ea8d27872b098715f4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 88.0, "max_issues_repo_issues_event_min_datetime": "2016-06-10T19:09:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T10:50:41.000Z", "max_forks_repo_path": "Demos/DistanceFieldDemos/ClothCollisionDemo.cpp", "max_forks_repo_name": "Taiyuan-Zhang/PositionBasedDynamics", "max_forks_repo_head_hexsha": "136469f03f7869666d907ea8d27872b098715f4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 267.0, "max_forks_repo_forks_event_min_datetime": "2016-06-22T06:44:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T11:55:24.000Z", "avg_line_length": 36.8704545455, "max_line_length": 208, "alphanum_fraction": 0.7459779326, "num_tokens": 4712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5023031975105934}}
{"text": "/////////////////////////////////////////////////////////////////////////////////////////////\n// Copyright (c) 2021 Andreas Milton Maniotis.\n//\n// Email: andreas.maniotis@gmail.com\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n/////////////////////////////////////////////////////////////////////////////////////////////\n\n\n#include \"aml/find.hpp\"\n#include \"aml/conslist.hpp\"\n\n#include <type_traits>\n\n#include <iostream>\n#include <boost/core/demangle.hpp>\n\nnamespace test::find\n{\n    using l0 = aml::conslist<>;\n    using l1 = aml::conslist<void, int, char*>;\n    using l2 = aml::conslist<void, short int, char*, long int>;\n\n\n    template<typename X>\n    struct pred\n    {\n        static constexpr bool eval() { return std::is_integral<X>::value; };\n    };\n\n    using f0 = l0::apply<aml::find<pred>::in>;\n    using f1 = l1::apply<aml::find<pred>::in>;\n\n    using f2 = l2::apply<aml::find<pred>::in>;\n\n    using r0 = aml::conslist<>;\n    using r1 = aml::conslist<int>;\n    using r2 = aml::conslist<short int>;\n\n\n    void test()\n    {\n        static_assert(std::is_same<f0, r0>::value, \"\");\n        static_assert(std::is_same<f1, r1>::value, \"\");\n        static_assert(std::is_same<f2, r2>::value, \"\");\n    }\n}\n\n\n#include <iostream>\n#include <string>\n\n\nint main()\n{\n    void (*test_set[])() = { test::find::test };\n\n    for ( auto test : test_set )\n        test();\n\n    std::cout << __FILE__ << \": \" << sizeof(test_set)/sizeof(test_set[0])  << \" tests passed.\" << std::endl;\n}\n", "meta": {"hexsha": "844f8d298291fa4dbf95f0675c03e262011165d1", "size": 1584, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deprecated-material/test/test_find.cpp", "max_stars_repo_name": "aandriko/libaml", "max_stars_repo_head_hexsha": "9db1a3ac13ef8160a33ed03e861be5d8cc8ea311", "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": "deprecated-material/test/test_find.cpp", "max_issues_repo_name": "aandriko/libaml", "max_issues_repo_head_hexsha": "9db1a3ac13ef8160a33ed03e861be5d8cc8ea311", "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": "deprecated-material/test/test_find.cpp", "max_forks_repo_name": "aandriko/libaml", "max_forks_repo_head_hexsha": "9db1a3ac13ef8160a33ed03e861be5d8cc8ea311", "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": 108, "alphanum_fraction": 0.5391414141, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5023031887937008}}
{"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//[for_each_point_const\n//` Sample using for_each_point, using a function to list coordinates\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\n\ntemplate <typename Point>\nvoid list_coordinates(Point const& p)\n{\n    using boost::geometry::get;\n    std::cout << \"x = \" << get<0>(p) << \" y = \" << get<1>(p) << std::endl;\n}\n\nint main()\n{\n    typedef boost::geometry::model::d2::point_xy<double> point;\n    boost::geometry::model::polygon<point> poly;\n    boost::geometry::read_wkt(\"POLYGON((0 0,0 4,4 0,0 0))\", poly);\n    boost::geometry::for_each_point(poly, list_coordinates<point>);\n    return 0;\n}\n\n//]\n\n\n//[for_each_point_const_output\n/*`\nOutput:\n[pre\nx = 0 y = 0\nx = 0 y = 4\nx = 4 y = 0\nx = 0 y = 0\n]\n*/\n//]\n", "meta": {"hexsha": "43cf2c774fa4150ac6bfe0f88059f4fc610b6bc6", "size": 1148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/for_each_point_const.cpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "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": "libs/geometry/doc/src/examples/algorithms/for_each_point_const.cpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/for_each_point_const.cpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 22.96, "max_line_length": 79, "alphanum_fraction": 0.6846689895, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5022066366741184}}
{"text": "#ifndef EXAMPLES_MPI_DOMAIN_PARTITION_HPP\n#define EXAMPLES_MPI_DOMAIN_PARTITION_HPP\n\n#include <vector>\n#include <utility>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/adapted/boost_array.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\nBOOST_GEOMETRY_REGISTER_BOOST_ARRAY_CS(cs::cartesian)\n\ntemplate <int NDIM>\nclass domain_partition {\n    public:\n        typedef boost::array<ptrdiff_t, NDIM>      point;\n        typedef boost::geometry::model::box<point> box;\n        typedef std::pair<box, int>                process;\n\n        domain_partition(point lo, point hi, int num_processes) {\n            split(box(lo, hi), num_processes);\n\n            for(int i = 0; i < num_processes; ++i)\n                rtree.insert( std::make_pair(subdomains[i], i) );\n        }\n\n        std::pair<int, ptrdiff_t> index(point p) const {\n            namespace bgi = boost::geometry::index;\n\n            for(const process &v : rtree | bgi::adaptors::queried(bgi::intersects(p)) )\n            {\n                return std::make_pair(v.second, local_index(v.first, p));\n            }\n\n            // Unreachable:\n            return std::make_pair(0, 0l);\n        }\n\n        size_t size(size_t process) const {\n            if (process >= subdomains.size()) return 0;\n\n            point lo = subdomains[process].min_corner();\n            point hi = subdomains[process].max_corner();\n\n            size_t v = 1;\n\n            for(int i = 0; i < NDIM; ++i)\n                v *= hi[i] - lo[i] + 1;\n\n            return v;\n        }\n\n        box domain(size_t process) const {\n            if (process < subdomains.size())\n                return subdomains[process];\n            else {\n                point lo;\n                point hi;\n                for(int i = 0; i < NDIM; ++i) {\n                    lo[i] = 0;\n                    hi[i] = -1;\n                }\n                return box(lo, hi);\n            }\n        }\n    private:\n        std::vector<box> subdomains;\n\n        boost::geometry::index::rtree<\n            process,\n            boost::geometry::index::quadratic<16>\n            > rtree;\n\n        static ptrdiff_t local_index(box domain, point p) {\n            point lo = domain.min_corner();\n            point hi = domain.max_corner();\n\n            ptrdiff_t stride = 1, idx = 0;\n            for(int i = 0; i < NDIM; ++i) {\n                idx += (p[i] - lo[i]) * stride;\n                stride *= hi[i] - lo[i] + 1;\n            }\n\n            return idx;\n        }\n\n        void split(box domain, int np) {\n            if (np == 1) {\n                subdomains.push_back(domain);\n                return;\n            }\n\n            point lo = domain.min_corner();\n            point hi = domain.max_corner();\n\n            // Get longest dimension of the domain\n            int wd = 0;\n            for(int i = 1; i < NDIM; ++i)\n                if (hi[i] - lo[i] > hi[wd] - lo[wd]) wd = i;\n\n            ptrdiff_t mid = lo[wd] + (hi[wd] - lo[wd]) * (np / 2) / np;\n\n            box sd1 = domain;\n            box sd2 = domain;\n\n            sd1.max_corner()[wd] = mid;\n            sd2.min_corner()[wd] = mid + 1;\n\n            split(sd1, np / 2);\n            split(sd2, np - np / 2);\n        }\n};\n\n#endif\n", "meta": {"hexsha": "45fae8aca41fe95d15b0d2cdecaed70e4ae75aad", "size": 3256, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/mpi/domain_partition.hpp", "max_stars_repo_name": "tenglongcong/amgcl", "max_stars_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 504.0, "max_stars_repo_stars_event_min_datetime": "2015-03-11T13:50:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:08:55.000Z", "max_issues_repo_path": "examples/mpi/domain_partition.hpp", "max_issues_repo_name": "tenglongcong/amgcl", "max_issues_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 209.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T19:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:44:12.000Z", "max_forks_repo_path": "examples/mpi/domain_partition.hpp", "max_forks_repo_name": "tenglongcong/amgcl", "max_forks_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 92.0, "max_forks_repo_forks_event_min_datetime": "2015-01-04T06:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T09:49:12.000Z", "avg_line_length": 28.0689655172, "max_line_length": 87, "alphanum_fraction": 0.4886363636, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5022066299949701}}
{"text": "#ifndef _MATRIX_OPERATIONS_HPP_\n#define _MATRIX_OPERATIONS_HPP_\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n\nnamespace CIS {\n/// @brief Manual transform implementation, recommend using the following instead\n/// \n/// @verbatim\n///    Eigen::Affine3d transform;\n///    \n///    transform.setIdentity();\n///    \n///    // Define a translation of 2.5 meters on the x axis.\n///    transform.translation() << 2.5, 0.0, 0.0;\n///    \n///    double theta = 0;//boost::math::constants::pi<double>();\n///    // The same rotation matrix as before; tetha radians arround Z axis\n///    transform.rotate (Eigen::AngleAxisd (theta, Eigen::Vector3d::UnitZ()));\n///    \n///    Eigen::Vector3d v3d(1,1,1);\n///\n///    Eigen::Vector3d v3d2 = (transform*v3d).transpose();\n/// @endverbatim\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, 3, 1> transform(const Eigen::Transform<Scalar, 3, Eigen::Affine>& hTrans, const Eigen::Matrix<Scalar, 3, 1>& point){\n   return Eigen::Matrix<Scalar, 3, 1>\n    (\n        hTrans (0, 0) * point(0) + hTrans (0, 1) * point(1) + hTrans (0, 2) * point(2) + hTrans (0, 3),\n        hTrans (1, 0) * point(0) + hTrans (1, 1) * point(1) + hTrans (1, 2) * point(2) + hTrans (1, 3),\n        hTrans (2, 0) * point(0) + hTrans (2, 1) * point(1) + hTrans (2, 2) * point(2) + hTrans (2, 3)\n     );\n\n}\n}\n\n/// @todo provide instructions to replace this with eigen built in functionality\n/// Create transformation matrix from Rotation R and Translation vector P\nEigen::Matrix4d homogeneousmatrix(Eigen::Matrix3d R, Eigen::Vector3d p)\n{\n    Eigen::Matrix4d F = Eigen::Matrix4d::Identity();\n    F.block<3,3>(0,0) = R;\n    F.block<3,1>(0,3) = p;\n    return F;\n}\n\n/// @todo provide instructions to replace this with eigen built in functionality\n/// Computes the inverse of the transformation matrix\nEigen::MatrixXd homogeneousInverse(const Eigen::MatrixXd& F)\n{\n    Eigen::MatrixXd Finv = Eigen::Matrix4d::Identity();\n    Eigen::Matrix3d R = F.block<3,3>(0,0);\n    Eigen::Matrix3d Rtrans = R.transpose();\n    Finv.block<3,3>(0,0) = Rtrans;\n    Finv.block<3,1>(0,3) = -Rtrans*F.block<3,1>(0,3);\n    return Finv;\n}\n\n\n\n/// Swap indexing order of vector of vectors, so if it is row major the returned vv will be column major.\n/// @todo this is pretty inefficient, but the lengthts can vary. Maybe store the data differently\ntemplate<typename T>\nconst std::vector<std::vector<T> > swapIndexing(const std::vector<std::vector<T> >& uv){\n    std::vector<std::vector<T> > vu;\n    for(auto uvi : uv){\n        int i = 0;\n        for(auto vi :uvi){\n            if(i == vu.size()) vu.push_back(std::vector<T>());\n            vu[i].push_back(vi);\n            ++i;\n        }\n    }\n    return vu;\n}\n\n/// @brief combine a vector<vector<T> > into a single vector<T>\ntemplate<typename T>\nconst std::vector<T> concat(const std::vector<std::vector<T> >& uv){\n    std::vector<T> u;\n    for(auto uvi : uv){\n        u.insert(u.end(), uvi.begin(), uvi.end());\n    }\n    return u;\n}\n\n\n\n/// @brief split a large Eigen::MatrixXd by rows into a vector of smaller MatrixXd\nstd::vector<Eigen::MatrixXd> splitRows(const Eigen::MatrixXd& mat,std::size_t numRowsPerMat){\n    \n    std::vector<Eigen::MatrixXd> vec;\n    std::size_t cols = mat.cols();\n    \n    for(std::size_t currentRow = 0; currentRow < mat.rows(); currentRow+=numRowsPerMat){\n        Eigen::MatrixXd partialMat(mat.block(currentRow,0,numRowsPerMat,cols));\n        vec.push_back(partialMat);\n    }\n    \n    return vec;\n}\n\nEigen::MatrixXd concatToMatrix(const std::vector<Eigen::Vector3d>& points){\n    Eigen::MatrixXd mat;\n    mat.resize(points.size(),3);\n    int i = 0;\n    for(Eigen::Vector3d point : points){\n        mat.block<1,3>(i,0) = point.transpose();\n        ++i;\n    }\n    \n    return mat;\n}\n\n\n// splits a stack of vectors that is nx3, into a std::vector of n 3x1 vectors\nstd::vector<Eigen::Vector3d> splitVectors(const Eigen::MatrixXd& mat){\n\tstd::vector<Eigen::Vector3d> vec;\n\t\n\tfor(int i = 0; i < mat.rows(); ++i){\n\t\tvec.push_back(Eigen::Vector3d(mat.block<1,3>(i,0).transpose()));\n\t}\n\t\n\treturn vec;\n}\n\n#endif // _MATRIX_OPERATIONS_HPP_\n", "meta": {"hexsha": "46aa61ba3d3bcd4e77fb88deb80442556008dd08", "size": 4128, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/matrixOperations.hpp", "max_stars_repo_name": "ahundt/cis", "max_stars_repo_head_hexsha": "bd55e8c77ec78994454247ffe7d67f537710a53f", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-17T03:13:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-17T03:13:01.000Z", "max_issues_repo_path": "include/matrixOperations.hpp", "max_issues_repo_name": "ahundt/cis", "max_issues_repo_head_hexsha": "bd55e8c77ec78994454247ffe7d67f537710a53f", "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": "include/matrixOperations.hpp", "max_forks_repo_name": "ahundt/cis", "max_forks_repo_head_hexsha": "bd55e8c77ec78994454247ffe7d67f537710a53f", "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": 31.5114503817, "max_line_length": 138, "alphanum_fraction": 0.6361434109, "num_tokens": 1214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5022066279773267}}
{"text": "#include <boost/math/quadrature/tanh_sinh.hpp>\n", "meta": {"hexsha": "47c5b48e6fb2b0c3626d39d4554cb9a71f68b4cc", "size": 47, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_quadrature_tanh_sinh.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_quadrature_tanh_sinh.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_quadrature_tanh_sinh.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.5, "max_line_length": 46, "alphanum_fraction": 0.8085106383, "num_tokens": 13, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5020927288638933}}
{"text": "#include \"vtkVelodyneHDLPositionReader.h\"\n#include \"vtkVelodyneTransformInterpolator.h\"\n#include \"vtkPointData.h\"\n#include \"vtkTransform.h\"\n\n#include <Eigen/Dense>\n\nEigen::Matrix3d RollPitchYawToMatrix(double roll, double pitch, double yaw)\n{\n  return Eigen::Matrix3d(Eigen::AngleAxisd(yaw, Eigen::Vector3d::UnitZ())\n                  * Eigen::AngleAxisd(pitch, Eigen::Vector3d::UnitY())\n                  * Eigen::AngleAxisd(roll, Eigen::Vector3d::UnitX()));\n}\n\nEigen::Matrix3d RollPitchYawToMatrixDegree(double roll, double pitch, double yaw)\n{\n  return RollPitchYawToMatrix((vtkMath::Pi() / 180.0) * roll,\n                              (vtkMath::Pi() / 180.0) * pitch,\n                              (vtkMath::Pi() / 180.0) * yaw);\n}\n\n// defines an arbitrary order on the columns names\n// this order is expected when passing arrays of double to test functions\n// this order does not have to be the same as the one that is used inside the\n// vtkPolydata, because we do not want to test that this order remain consistent\n// (because the order is not documented and currently based on the behavior of // an iterator on a std::map)\nconst char* arrayNames[17] = { \"lat\",\n                               \"lon\",\n                               \"gpstime\",\n                               \"time\",\n                               \"accel1x\",\n                               \"accel1y\",\n                               \"accel2x\",\n                               \"accel2y\",\n                               \"accel3x\",\n                               \"accel3y\",\n                               \"gyro1\",\n                               \"gyro2\",\n                               \"gyro3\",\n                               \"heading\",\n                               \"temp1\",\n                               \"temp2\",\n                               \"temp3\" };\n\nbool Equal(double a, double b, double epsilon = 1e-6)\n{\n  return std::abs(a - b) <= epsilon;\n}\n\nbool test_point_count(vtkSmartPointer<vtkVelodyneHDLPositionReader> reader,\n                /* expected: */\n                int count)\n{\n  std::cout << \"Testing number of points\" << std::endl;\n  bool isvalid = (reader->GetOutput()->GetNumberOfPoints() == count);\n  if (!isvalid)\n  {\n    std::cerr << \"unexpected number of points\" << std::endl;\n  }\n  return isvalid;\n}\n\nbool test_interpolator_time_range(\n    vtkSmartPointer<vtkVelodyneHDLPositionReader> reader,\n    /* expected: */\n    double tmin,\n    double tmax)\n{\n  std::cout << \"Testing the interpolator time range\" << std::endl;\n  bool isvalid = (Equal(reader->GetInterpolator()->GetMinimumT(),tmin)\n                  && Equal(reader->GetInterpolator()->GetMaximumT(), tmax));\n  if (!isvalid)\n  {\n    std::cerr << \"unexpected interpolator time range\" << std::endl;\n  }\n  return isvalid;\n}\n\n\n// roll pitch and yaw angles in degrees\n// Producing the matrix Rz(yaw) * Ry(pitch) * Rx(roll)\nbool test_interpolator_transform(\n    vtkSmartPointer<vtkVelodyneHDLPositionReader> reader,\n    double t,\n    /* expected: */\n    double posRollPitchYaw[6])\n{\n  vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();\n  reader->GetInterpolator()->InterpolateTransform(t, transform);\n\n  vtkSmartPointer<vtkMatrix4x4> tmp = vtkSmartPointer<vtkMatrix4x4>::New();\n  transform->GetMatrix(tmp);\n\n  Eigen::Matrix3d M = RollPitchYawToMatrixDegree(posRollPitchYaw[3 + 0],\n      posRollPitchYaw[3 + 1],\n      posRollPitchYaw[3 + 2]);\n\n  bool rotationValid = true;\n  for (int i = 0; i < 3; i++)\n  {\n      for (int j = 0; j < 3; j++)\n      {\n        rotationValid &= Equal(tmp->GetElement(i,j), M(i,j));\n      }\n  }\n  if (!rotationValid)\n  {\n    std::cerr << \"Unexpected rotation in transform\" << std::endl;\n  }\n\n  bool translationValid = true;\n  for (int i = 0; i < 3; i++)\n  {\n        if (!Equal(tmp->GetElement(i,3), posRollPitchYaw[i]))\n        {\n          std::cerr << \"For coord \" << i\n                    << std::setprecision(17)\n                    << \" got: \" << tmp->GetElement(i,3)\n                    << \" expecting: \" << posRollPitchYaw[i] << std::endl;\n          translationValid = false;\n        }\n  }\n  if (!translationValid)\n  {\n    std::cerr << \"Unexpected translation in transform\" << std::endl;\n  }\n\n  return (rotationValid && translationValid);\n}\n\n\nbool test_interpolator_transform_count(\n                vtkSmartPointer<vtkVelodyneHDLPositionReader> reader,\n                /* expected: */\n                int count)\n{\n  std::cout << \"Testing number of transforms in interpolator\" << std::endl;\n  bool isvalid = (reader->GetInterpolator()->GetNumberOfTransforms() == count);\n  if (!isvalid)\n  {\n    std::cerr << \"unexpected number of transforms\" << std::endl;\n  }\n  return isvalid;\n}\n\nbool test_point_coords(vtkSmartPointer<vtkVelodyneHDLPositionReader> reader,\n                int id,\n                /* expected: */\n                double coords[3])\n{\n  std::cout << \"Testing coordinates of point: \" << id << std::endl;\n  bool isvalid = true;\n  // check the point value in all 3 coordinates\n  double coordsRead[3];\n  reader->GetOutput()->GetPoint(id, coordsRead);\n  for (int i = 0; i < 3; i++)\n  {\n    isvalid &= Equal(coordsRead[i], coords[i]);\n  }\n  if (!isvalid)\n  {\n    std::cerr << \"unexpected value for coordinates of point \" << id\n              << std::endl;\n  }\n  return isvalid;\n}\n\nbool test_point_arrays(vtkSmartPointer<vtkVelodyneHDLPositionReader> reader,\n                int id,\n                /* expected: */\n                double arrayValues[17])\n{\n  std::cout << \"Testing arrays of point: \" << id << std::endl;\n  bool isvalid = true;\n  // check the point value in all 17 arrays\n  for (int i = 0; i < 17; i++)\n  {\n    if (!Equal(reader->GetOutput()->GetPointData()->GetArray(arrayNames[i])\n               ->GetTuple1(id),\n               arrayValues[i]))\n    {\n      std::cerr << \"unexpected value for point \" << id\n                << \" in array \"\n                << reader->GetOutput()->GetPointData()->GetArrayName(i)\n                << std::endl;\n      isvalid = false;\n    }\n  }\n\n  if (!isvalid)\n  {\n    std::cout << \"values read for point \" << id << \" are: \" << std::endl;\n    std::cout << \"(in the order: \";\n    for (int i = 0; i < 17; i++)\n    {\n      std::cout << arrayNames[i] << \" \";\n    }\n    std::cout << \")\" << std::endl;\n    for (int i = 0; i < 17; i++)\n    {\n      std::cout << std::setprecision(17)\n                << reader->GetOutput()->GetPointData()->GetArray(i)->GetTuple1(id);\n      if (i < 16)\n      {\n        std::cout << \", \";\n      }\n    }\n    std::cout << std::endl;\n  }\n\n  return isvalid;\n}\n\nint main(int argc, char* argv[])\n{\n  if (argc != 2)\n  {\n    std::cerr << \"Wrong number of arguments. Usage: \"\n              << argv[0]\n              << \"<path to \"\n              << \"\\\"HDL32-V2_R into Butterfield into Digital Drive.pcap\\\"\"\n              << \"(from data.kitware.com,\"\n              << \"sha1sum: 1edb06c8c4312cb259dd0417a226c235945ff5b6) >\"\n              << std::endl;\n    return 1;\n  }\n\n  std::string pathToPcap = std::string(argv[1]);\n\n  vtkSmartPointer<vtkVelodyneHDLPositionReader> reader =\n      vtkSmartPointer<vtkVelodyneHDLPositionReader>::New();\n  reader->SetFileName(pathToPcap);\n  reader->Update();\n  // std::cout << *reader->GetOutput() << std::endl; // should you want to inspect the polydata produced\n\n  double point0_arrays[17] =  { 37.139071666666, -121.657165, 78376, 2777073776, 0.9768, 0.108669, 0.970695, -0.272283, -0.068376, -0.272283, 3.12512, -7.42216, -32.52078, 40.6, 36.9146, 38.6582, 42.0001 };\n  double point0_coords[3] =  { 0.0, 0.0, 0.0 };\n  double point8947_arrays[17] = { 37.1387, -121.65492833333, 78421, 2822076651, 0.990231, 0.023199, 0.98901, -0.002442, 0.001221, -0.003663, -8.7894, -4.10172, -28.3214, 257.7, 36.9146, 38.8035, 42.0001 };\n  double point8947_coords[3] =  { 199.2462615966796875,\t-38.420330047607421875,\t0.0 };\n  int numberOfPoints = 8948;\n  int numberOfTransforms = 46;\n  double minTime = 78376.0;\n  double maxTime = 78421.0;\n  double transformMinTime[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 40.6 };\n  double transformMaxTimeMinus1[6] = { 203.09254455566406, -38.180858612060547, 0.0, 0.0, 0.0, -92.3 };\n\n  vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();\n  reader->GetInterpolator()->InterpolateTransform(maxTime - 1.0, transform);\n\n  bool isvalid = true;\n  isvalid &= test_point_count(reader, numberOfPoints);\n  isvalid &= test_point_coords(reader, 0, point0_coords);\n  isvalid &= test_point_arrays(reader, 0, point0_arrays);\n  isvalid &= test_point_coords(reader, 8947, point8947_coords);\n  isvalid &= test_point_arrays(reader, 8947, point8947_arrays);\n\n  isvalid &= test_interpolator_transform_count(reader, numberOfTransforms);\n  isvalid &= test_interpolator_time_range(reader, minTime, maxTime);\n  isvalid &= test_interpolator_transform(reader, minTime, transformMinTime);\n  isvalid &= test_interpolator_transform(reader, maxTime - 1.0, transformMaxTimeMinus1);\n\n  return  isvalid ? 0 : 1;\n}\n", "meta": {"hexsha": "601c58df35899ccd76a2172200477d0d8feff99c", "size": 8921, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "VelodyneHDL/Testing/TestVelodyneHDLPositionReader.cxx", "max_stars_repo_name": "zhihua-wang/VeloView", "max_stars_repo_head_hexsha": "609d3e4c0cf722c512f4b0b2a615208557bb7757", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-10-28T07:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-28T07:03:50.000Z", "max_issues_repo_path": "VelodyneHDL/Testing/TestVelodyneHDLPositionReader.cxx", "max_issues_repo_name": "zactodd/VeloView", "max_issues_repo_head_hexsha": "e0bd72a32464a9f62385ac5ce25df33580ed3cc2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-17T13:25:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T21:26:11.000Z", "max_forks_repo_path": "VelodyneHDL/Testing/TestVelodyneHDLPositionReader.cxx", "max_forks_repo_name": "zactodd/VeloView", "max_forks_repo_head_hexsha": "e0bd72a32464a9f62385ac5ce25df33580ed3cc2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-08T11:28:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T11:28:59.000Z", "avg_line_length": 33.7916666667, "max_line_length": 206, "alphanum_fraction": 0.5872660016, "num_tokens": 2496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5020927146628146}}
{"text": "#include \"include/ellipse.h\"\n#include \"include/component_labelling.h\"\n#include \"include/point_helpers.h\"\n\n#include <cmath>\n#include <Eigen/Cholesky>\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n#include <limits>\n\ntypedef Matrix<double, 5, 5> Matrix5d;\ntypedef Matrix<double, 5, 1> Vector5d;\n\n\nint Ellipse_detector::fit(const Component_labeller& cl, const Gradient& gradient,\n    const Pointlist& raw_points, int tl_x, int tl_y, int dilate) {\n    \n    \n    int width  = gradient.width();\n    int height = gradient.height();\n    \n    const cv::Mat& grad_x = gradient.grad_x();\n    const cv::Mat& grad_y = gradient.grad_y();\n    const cv::Mat& grad_m = gradient.grad_magnitude();\n\n    set<iPoint> boundary;\n\n    const int border = 1;\n    bool edge_touched = false;\n    double mx = 0;\n    double my = 0;\n    for (size_t i=0; i < raw_points.size(); i++) {\n        mx += raw_points[i].x;\n        my += raw_points[i].y;\n        boundary.insert(iPoint(lrint(raw_points[i].x), lrint(raw_points[i].y)) );\n        \n        if (raw_points[i].x <= border || raw_points[i].x >= width - 1 - border ||\n            raw_points[i].y <= border || raw_points[i].y >= height - 1 - border) {\n            \n            edge_touched = true;\n        }\n    }\n    \n    mx /= raw_points.size();\n    my /= raw_points.size();\n    \n    if (edge_touched) return 0; // skip objects that touch the edge of the image (ellipses not really allowed there)\n\n    if (std::isnan(mx) || std::isnan(my)) {\n        return 0; // 0 -> not a circle\n    }\n\n    _dilate(boundary, width, height, dilate);\n    _dilate_outer_only(boundary, width, height);\n\n    Matrix<double, 5, 5> wK;\n    Matrix<double, 5, 1> K; \n    K.setZero();\n    Vector3d l;\n    l.setZero();\n    Matrix<double, 5, 1> rhs;\n    rhs.setZero();\n\n    double sum_c4 = 0;\n\n    wK.setZero();\n    int count = (int)boundary.size();\n    Matrix<double, Eigen::Dynamic, 3> L(count, 3);\n    L.setZero();\n\n    double mean_dist = 0;\n    int counter = 0;\n    for (set<iPoint>::const_iterator it=boundary.begin(); it != boundary.end(); it++) {\n        const int& x_pos = it->first;\n        const int& y_pos = it->second;\n\n        if (grad_m.at<float>(y_pos, x_pos) > 1e-7) {\n            Vector3d v;\n            v << x_pos,y_pos,1;\n            double dist = sqrt( SQR(x_pos-mx) + SQR(y_pos-my) );\n            mean_dist += dist;\n            counter++;\n        }\n    }\n    mean_dist /= counter;\n    double iso_scale = sqrt(2.0) / mean_dist;\n\n    size_t idx = 0;\n    for (set<iPoint>::const_iterator it=boundary.begin(); it != boundary.end(); it++) {\n        const int& x_pos = it->first;\n        const int& y_pos = it->second;\n        \n        if (grad_m.at<float>(y_pos, x_pos) > 1e-7) {\n\n\n            l[0] = grad_x.at<float>(y_pos, x_pos);\n            l[1] = grad_y.at<float>(y_pos, x_pos);\n            l[2] = -(grad_x.at<float>(y_pos, x_pos) * (x_pos-mx) * iso_scale + grad_y.at<float>(y_pos, x_pos) * (y_pos-my) * iso_scale);\n\n            L.row(idx++) = l;\n\n        }\n    }\n\n    for (size_t r=0; r < (size_t)L.rows(); r++) {\n\n        Vector3d l = L.row(r);\n\n        sum_c4 += SQR(SQR(l[2]));\n\n        K[0] = l[0]*l[0];\n        K[1] = l[0]*l[1];\n        K[2] = l[1]*l[1];\n        K[3] = l[0]*l[2];\n        K[4] = l[1]*l[2];\n\n        double weight = (l[0]*l[0] + l[1]*l[1]);\n\n        wK += weight * K * K.transpose();\n\n        rhs -= weight * K*(l[2]*l[2]);\n    }\n    \n    if (rhs.rows() != 5 || rhs.cols() != 1) {\n        printf(\"rhs undefined\\n\");\n        exit(1);\n    }\n    \n    bool has_nans = false;\n    for (size_t ri=0; ri < rhs.rows(); ri++) {\n        if (std::isnan(rhs(ri,0))) {\n            has_nans = true;   \n            return 0;\n        }\n    }\n\n    Vector5d sol;\n    sol = wK.fullPivHouseholderQr().solve(rhs);\n\n    Matrix3d Cstar;\n    Cstar(0, 0) = sol[0];\n    Cstar(0, 1) = sol[1]*0.5;\n    Cstar(0, 2) = sol[3]*0.5;\n    Cstar(1, 0) = sol[1]*0.5;\n    Cstar(1, 1) = sol[2];\n    Cstar(1, 2) = sol[4]*0.5;\n    Cstar(2, 0) = sol[3]*0.5;\n    Cstar(2, 1) = sol[4]*0.5;\n    Cstar(2, 2) = 1;      // F* == 1\n\n\n    Matrix3d C = Cstar.inverse();\n    C *= 1.0/C(2,2);\n    _C = C;\n\n    Matrix<double, 1, 5> s;\n    s.row(0) = sol;\n    double sAAs = (s * wK * (s.transpose()))(0,0);\n    double R = (sAAs - 2*(sol.dot(rhs)) + sum_c4) / double(count - 5);\n    Matrix<double, 5, 5> cov = wK.inverse();\n    cov = cov * R;\n    Matrix2d cov2;\n    cov2(0, 0) = cov(3, 3);\n    cov2(0, 1) = cov(3, 4);\n    cov2(1, 0) = cov(4, 3);\n    cov2(1, 1) = cov(4, 4);\n    JacobiSVD<Matrix2d> svd(cov2, ComputeFullU | ComputeFullV);\n    Matrix2d Vs = svd.matrixV();\n    Vector2d ws = svd.singularValues();\n\n    Matrix2d V;\n    V.row(0) = Vs.row(1);\n    V.row(1) = Vs.row(0);\n\n    Vector2d w;\n    w[0] = ws[1];\n    w[1] = ws[0];\n\n    Vector2d centre_uncertainty;\n    centre_uncertainty[0] = sqrt(w[0]) * 0.25;\n    centre_uncertainty[1] = sqrt(w[1]) * 0.25;\n\n    // shift the ellipse back to the original pixel coordinate system\n    Matrix3d S;\n    S.setIdentity();\n    S(0, 0) = iso_scale;\n    S(1, 1) = iso_scale;\n    C = _C = S.transpose()*C*S;\n    S.setIdentity();\n    S(0, 2) = -(tl_x + mx);\n    S(1, 2) = -(tl_y + my);\n    C = _C = S.transpose()*C*S;\n\n    int result = _matrix_to_ellipse(C);\n\n    if (minor_axis > major_axis) {\n        _C = -_C;\n        _matrix_to_ellipse(C);\n    }\n\n    bool gradient_ok = gradient_check(cl, gradient, raw_points);\n\n    int is_circle = 0;\n\n    if (result == 0 &&\n        major_axis >= min_major_axis &&\n        minor_axis >= min_minor_axis &&\n        gradient_ok) {\n\n        is_circle = 1;\n    }\n\n\n    if (std::isnan(centroid_x) || std::isnan(centroid_y) || std::isnan(major_axis) || std::isnan(minor_axis)) {\n        is_circle = 0;\n    }\n    \n    printf(\"centre (%.2lf, %.2lf), major = %lf, minor = %lf, angle = %lf, is_circle = %d\\n\",\n        centroid_x, centroid_y, major_axis, minor_axis, angle/M_PI*180.0, is_circle);\n        \n    if (is_circle) {\n        scanset.clear();\n        for (size_t i=0; i < raw_points.size(); i++) {\n            int ix = lrint(raw_points[i].x);\n            int iy = lrint(raw_points[i].y);\n            \n            map<int, scanline>::iterator it = scanset.find(iy);\n            if (it == scanset.end()) {\n                scanline sl(ix,ix);\n                scanset.insert(make_pair(iy, sl));\n            }\n            if (ix < scanset[iy].start) {\n                scanset[iy].start = ix;\n            }\n            if (ix > scanset[iy].end) {\n                scanset[iy].end = ix;\n            }\n        }\n        int clabel = cl(lrint(raw_points[0].x), lrint(raw_points[0].y));\n        printf(\"label used for scanset: %d\\n\", clabel);\n        int total = 0;\n        int foreground = 0;\n        for (map<int, scanline>::iterator it=scanset.begin(); it != scanset.end(); it++) {\n            int y=it->first;\n            for (int x=it->second.start; x <= it->second.end; x++) {\n                if (cl(x,y) == clabel) {\n                    foreground++;\n                }\n                total++;\n            }\n        }\n        fg_fraction = double(foreground)/double(total);\n    }        \n    \n    return is_circle;\n}\n\n\nvoid Ellipse_detector::_dilate(set<iPoint>& s, int width, int height, int iters) {\n    const int border = 1;\n\n    if (iters > 0) {\n\n        set<iPoint> gen_s;\n\n        for (int k=0; k < iters; k++) {\n            for (set<iPoint>::const_iterator it=s.begin(); it != s.end(); it++) {\n\n                gen_s.insert(*it);\n\n                int left = max(border, it->first-1);\n                int right = min(width-1-border, it->first+1);\n                int top = max(border, it->second-1);\n                int bottom = min(height-1-border, it->second+1);\n\n                gen_s.insert(iPoint(right, it->second));\n                gen_s.insert(iPoint(right, bottom));\n                gen_s.insert(iPoint(it->first, bottom));\n                gen_s.insert(iPoint(left, bottom));\n                gen_s.insert(iPoint(left, it->second));\n                gen_s.insert(iPoint(left, top));\n                gen_s.insert(iPoint(it->first, top));\n                gen_s.insert(iPoint(right, top));\n\n            }\n            s = gen_s; // copy it back\n        }\n    }\n}\n\nvoid Ellipse_detector::_dilate_outer_only(set<iPoint>& s, int width, int height) {\n    const int border = 1;\n    \n    double cx = 0;\n    double cy = 0;\n    for (set<iPoint>::const_iterator it=s.begin(); it != s.end(); it++) {\n        cx += it->first;\n        cy += it->second;\n    }\n    cx /= s.size();\n    cy /= s.size();\n\n    set<iPoint> gen_s;\n\n    for (set<iPoint>::const_iterator it=s.begin(); it != s.end(); it++) {\n\n        gen_s.insert(*it);\n        \n        Point2d dir(it->first - cx, it->second - cy); // current radial direction\n\n        int left = max(border, it->first-1);\n        int right = min(width-1-border, it->first+1);\n        int top = max(border, it->second-1);\n        int bottom = min(height-1-border, it->second+1);\n\n        if ((right - it->first)*dir.x >= 0) gen_s.insert(iPoint(right, it->second));\n        if ((right - it->first)*dir.x >= 0 && (bottom - it->second)*dir.y >= 0) gen_s.insert(iPoint(right, bottom));\n        if ((bottom - it->second)*dir.y >= 0) gen_s.insert(iPoint(it->first, bottom));\n        if ((left - it->first)*dir.x >= 0 && (bottom - it->second)*dir.y >= 0) gen_s.insert(iPoint(left, bottom));\n        if ((left - it->first)*dir.x >= 0) gen_s.insert(iPoint(left, it->second));\n        if ((left - it->first)*dir.x >= 0 && (top - it->second)*dir.y >= 0) gen_s.insert(iPoint(left, top));\n        if ((top - it->second)*dir.y >= 0) gen_s.insert(iPoint(it->first, top));\n        if ((right - it->first)*dir.x >= 0 && (top - it->second)*dir.y >= 0) gen_s.insert(iPoint(right, top));\n\n    }\n    s = gen_s; // copy it back\n}\n\nint Ellipse_detector::_matrix_to_ellipse(Matrix3d& C) {\n\n    double a = C(0,0);\n    double b = C(0,1)*2;\n    double c = C(1,1);  \n    double d = C(0,2)*2;\n    double e = C(1,2)*2;\n    double f = C(2,2);  \n\n\n    double thetarad = 0.5*atan2(b, a - c);\n    double cost = cos(thetarad);\n    double sint = sin(thetarad);\n    double sin_squared = sint*sint;\n    double cos_squared = cost*cost;\n    double cos_sin = sint*cost;\n\n    double Ao = f;\n    double Au =   d * cost + e * sint;\n    double Av = - d * sint + e * cost;\n    double Auu = a * cos_squared + c * sin_squared + b * cos_sin;\n    double Avv = a * sin_squared + c * cos_squared - b * cos_sin;\n\n    if(Auu==0 || Avv==0) {\n        // invalid ellipse\n        return -1;\n    }\n\n    double tuCentre = - Au/(2*Auu);\n    double tvCentre = - Av/(2*Avv);\n    double wCentre = Ao - Auu*tuCentre*tuCentre - Avv*tvCentre*tvCentre;\n\n    double uCentre = tuCentre * cost - tvCentre * sint;\n    double vCentre = tuCentre * sint + tvCentre * cost;\n\n    double Ru = -wCentre/Auu;\n    double Rv = -wCentre/Avv;\n\n    Ru = sqrt(fabs(Ru))*(Ru < 0 ? -1 : 1);\n    Rv = sqrt(fabs(Rv))*(Rv < 0 ? -1 : 1);\n\n    centroid_x = uCentre;\n    centroid_y = vCentre;\n    major_axis = Ru;\n    minor_axis = Rv;\n    angle = thetarad;\n\n    return 0;\n}\n\ndouble Ellipse_detector::calculate_curve_length(const Pointlist& points) {\n\n    int n = points.size();\n\n    // calculate the curve length of the  boundary\n    double curve_len = 0;\n    double prev_x = points[0].x - centroid_x;\n    double prev_y = points[0].y - centroid_y;\n    for (int i=1; i < n; i++) {\n        double x = points[i].x - centroid_x;\n        double y = points[i].y - centroid_y;\n        curve_len += sqrt(SQR(x - prev_x) + SQR(y - prev_y));\n        prev_x = x;\n        prev_y = y;\n    }\n    curve_len += sqrt(SQR(points[0].x - centroid_x - prev_x) +\n        SQR(points[0].y - centroid_y - prev_y));\n\n    return curve_len;\n}\n\nbool Ellipse_detector::gradient_check(const Component_labeller& cl, const Gradient& gradient, const Pointlist& raw_points) {\n    \n    // gradient just outside ellipse must be perpendicular to ellipse tangent\n    double cosa = cos(-angle);\n    double sina = sin(-angle);\n    int neighbours[8][2] = {\n        {-1, -1}, {0, -1}, {1, -1}, \n        {-1, 0}, {1, 0},\n        {-1,  1}, {0,  1}, {1, 1}\n    };\n    \n    // TODO: we need improved handling for objects falling on the edge of the scene?\n    \n    int not_fg_count = 0;\n    vector<double> phi_diff;\n    for (size_t i=0; i < raw_points.size(); i++) {\n        // now generate a point just outside the ellipse ....\n        int ox = lrint(raw_points[i].x);\n        int oy = lrint(raw_points[i].y);\n        int px = ox;\n        int py = oy;\n        double maxdist = sqrt((px - centroid_x)*(px - centroid_x) + (py - centroid_y)*(py - centroid_y));\n        for (int n=0; n < 8; n++) {\n            int lx = px + neighbours[n][0];\n            int ly = py + neighbours[n][1];\n            \n            if (lx >= 5 && lx < gradient.width() - 5 &&\n                ly >= 5 && ly < gradient.height() - 5) {\n            \n                double dist = sqrt((lx - centroid_x)*(lx - centroid_x) + (ly - centroid_y)*(ly - centroid_y));\n                if (dist > maxdist) {\n                    px = lx;\n                    py = ly;\n                    maxdist = dist;\n                }\n            }\n        }\n        \n        // points just outside ellipse should have labels of 0 or -1 (not foreground)\n        not_fg_count += cl(px, py) <= 0 ? 1 : 0;\n        \n        Point2d d(raw_points[i].x - centroid_x, raw_points[i].y - centroid_y);\n        double rx = cosa*d.x - sina*d.y;\n        double ry = sina*d.x + cosa*d.y;\n        double theta = atan2(ry, rx); // ellipse curve parameter theta\n        Point2d tangent = normalize(Point2d(-major_axis*sin(theta), minor_axis*cos(theta))); \n        // rotate the tangent vector back to image coordinates\n        rx = cosa*tangent.x + sina*tangent.y;\n        ry = (-sina)*tangent.x + cosa*tangent.y;\n        tangent.x = rx; \n        tangent.y = ry; \n        \n        Point2d grad = normalize(Point2d(gradient.grad_x().at<float>(py, px), gradient.grad_y().at<float>(py, px)));\n        \n        double dot = tangent.x*grad.x + tangent.y*grad.y;\n        double phi = acos(dot);\n        \n        phi_diff.push_back(phi/M_PI*180 - 90);\n    }\n    if ((raw_points.size() - not_fg_count) > 1) {\n        return false; // we can leave early here ...\n    }\n    \n    sort(phi_diff.begin(), phi_diff.end());\n    const double phi_percentile = 0.9;\n    \n    double phi_delta = phi_diff[phi_percentile*phi_diff.size()];\n    \n    return (phi_delta < max_ellipse_gradient_error) && phi_delta >= 0;\n}\n\n\n", "meta": {"hexsha": "4b211b31f56dd80defef05c63d11ce5412de5726", "size": 14376, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ellipse.cc", "max_stars_repo_name": "kriolog/mtfmapper", "max_stars_repo_head_hexsha": "b03ddd2cba1d55f259afb9ddc6d4b6c7a802da21", "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/ellipse.cc", "max_issues_repo_name": "kriolog/mtfmapper", "max_issues_repo_head_hexsha": "b03ddd2cba1d55f259afb9ddc6d4b6c7a802da21", "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/ellipse.cc", "max_forks_repo_name": "kriolog/mtfmapper", "max_forks_repo_head_hexsha": "b03ddd2cba1d55f259afb9ddc6d4b6c7a802da21", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-07T01:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-07T01:20:26.000Z", "avg_line_length": 30.3932346723, "max_line_length": 136, "alphanum_fraction": 0.528867557, "num_tokens": 4341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5020927122959677}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/5/problem5.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem5 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem5::solve(10);\n        BOOST_CHECK_EQUAL(res, 2520);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem5::solve();\n        BOOST_CHECK_EQUAL(res, 232792560);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "3a1bd8e67e38096e89e80192bfa13f15b01a286b", "size": 494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem5.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": "tests/1-50/test_problem5.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": "tests/1-50/test_problem5.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.5238095238, "max_line_length": 49, "alphanum_fraction": 0.6761133603, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5020755897233109}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file Transformation.hpp\n/// \\brief Header file for a transformation matrix class.\n/// \\details Light weight transformation class, intended to be fast, and not to provide\n///          unnecessary functionality.\n///\n/// \\author Sean Anderson\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n///\n/// A note on EIGEN_MAKE_ALIGNED_OPERATOR_NEW (Sean Anderson, as of May 23, 2013)\n/// (also see http://eigen.tuxfamily.org/dox-devel/group__TopicStructHavingEigenMembers.html)\n///\n/// Fortunately, Eigen::Matrix3d and Eigen::Vector3d are NOT 16-byte vectorizable,\n/// therefore this class should not require alignment, and can be used normally in STL.\n///\n/// To inform others of the issue, classes that include *fixed-size vectorizable Eigen types*,\n/// see http://eigen.tuxfamily.org/dox-devel/group__TopicFixedSizeVectorizable.html,\n/// must include the above macro! Furthermore, special considerations must be taken if\n/// you want to use them in STL containers, such as std::vector or std::map.\n/// The macro overloads the dynamic \"new\" operator so that it generates\n/// 16-byte-aligned pointers, this MUST be in the public section of the header!\n///\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef LGM_TRANSFORMATION_HPP\n#define LGM_TRANSFORMATION_HPP\n\n#include <Eigen/Dense>\n\nnamespace lgmath {\nnamespace se3 {\n\nclass Transformation\n{\n public:\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Default constructor\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Transformation();\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Copy constructor.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Transformation(const Transformation&) = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Move constructor.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Transformation(Transformation&& T) = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Copy constructor (from Eigen)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  explicit Transformation(const Eigen::Matrix4d& T);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor. The transformation will be T_ba = [C_ba, -C_ba*r_ba_ina; 0 0 0 1]\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Transformation(const Eigen::Matrix3d& C_ba, const Eigen::Vector3d& r_ba_ina);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor. The transformation will be T_ba = vec2tran(xi_ab)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Transformation(const Eigen::Matrix<double,6,1>& xi_ab, unsigned int numTerms = 0);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor. The transformation will be T_ba = vec2tran(xi_ab), xi_ab must be 6x1\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  // explicit because you want operator*(Eigen::Vector4d) and operator*(this) --- ambiguous\n  explicit Transformation(const Eigen::VectorXd& xi_ab);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Destructor. Default implementation.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  ~Transformation() = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Copy assignment operator. Default implementation causes functional failure.\n  /// \\todo (yuchen) Figure out why default does not work.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Transformation& operator=(const Transformation&) = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Move assignment operator. Manually implemented as Eigen doesn't support moving.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Transformation& operator=(Transformation&& T) = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Gets basic matrix representation of the transformation\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Eigen::Matrix4d matrix() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Gets the underlying rotation matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  const Eigen::Matrix3d& C_ba() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Gets the \"forward\" translation r_ba_ina = -C_ba.transpose()*r_ab_inb\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Eigen::Vector3d r_ba_ina() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Gets the underlying r_ab_inb vector.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  const Eigen::Vector3d& r_ab_inb() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get the corresponding Lie algebra using the logarithmic map\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Eigen::Matrix<double,6,1> vec() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get the inverse matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Transformation inverse() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get the 6x6 adjoint transformation matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Eigen::Matrix<double,6,6> adjoint() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Reproject the transformation matrix back onto SE(3). Setting force to false\n  ///        triggers a conditional reproject that only happens if the determinant is of the\n  ///        rotation matrix is poor; this is more efficient than always performing it.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  void reproject(bool force = true);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief In-place right-hand side multiply T_rhs\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual Transformation& operator*=(const Transformation& T_rhs);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Right-hand side multiply T_rhs\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual Transformation operator*(const Transformation& T_rhs) const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief In-place right-hand side multiply this matrix by the inverse of T_rhs\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual Transformation& operator/=(const Transformation& T_rhs);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Right-hand side multiply this matrix by the inverse of T_rhs\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual Transformation operator/(const Transformation& T_rhs) const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Right-hand side multiply this matrix by the homogeneous vector p_a\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Eigen::Vector4d operator*(const Eigen::Ref<const Eigen::Vector4d>& p_a) const;\n\n private:\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// Rotation matrix from a to b\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Eigen::Matrix3d C_ba_;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// Translation vector from b to a, expressed in frame b\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Eigen::Vector3d r_ab_inb_;\n};\n\n} // se3\n} // lgmath\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief print transformation\n//////////////////////////////////////////////////////////////////////////////////////////////\nstd::ostream& operator<<(std::ostream& out, const lgmath::se3::Transformation& T);\n\n#endif // LGM_TRANSFORMATION_HPP\n", "meta": {"hexsha": "ad15ccfe192fe8b85c4689d186a3d641bc2b2f41", "size": 10051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lgmath/se3/Transformation.hpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "include/lgmath/se3/Transformation.hpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "include/lgmath/se3/Transformation.hpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 55.8388888889, "max_line_length": 96, "alphanum_fraction": 0.3392697244, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5020755814897686}}
{"text": "#ifndef DXF_ALGORITHMS_HPP\n#define DXF_ALGORITHMS_HPP\n\n#include \"types.hpp\"\n\n/// SYSTEM\n#include <boost/version.hpp>\n#include <boost/geometry/algorithms/intersection.hpp>\n#include <boost/geometry/algorithms/transform.hpp>\n#include <boost/geometry/algorithms/correct.hpp>\n#include <boost/geometry/algorithms/append.hpp>\n#include <boost/geometry/algorithms/overlaps.hpp>\n#include <boost/geometry/algorithms/within.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n#include <boost/geometry/algorithms/length.hpp>\n#include <boost/geometry/arithmetic/dot_product.hpp>\n\n#include <utility>\n\nnamespace cslibs_boost_geometry {\nnamespace algorithms {\ntemplate<typename PointT>\ninline bool intersection\n(const typename types::Line<PointT>::type       &line_a,\n const typename types::Line<PointT>::type       &line_b,\n typename types::PointSet<PointT>::type   &points)\n{\n    boost::geometry::intersection(line_a, line_b, points);\n    return points.size() > 0;\n}\n\n\ntemplate<typename PointT>\ninline bool intersection\n(const typename types::Line<PointT>::type       &line_a,\n const typename types::Polygon<PointT>::type    &polygon,\n typename types::PointSet<PointT>::type   &points)\n{\n    auto &ring = polygon.outer();\n    auto it_first = ring.begin();\n    auto it_second = it_first + 1;\n    while(it_second != ring.end()) {\n        typename types::Line<PointT>::type line_b(*it_first, *it_second);\n        typename types::PointSet<PointT>::type tmp;\n        if(intersection<PointT>(line_a, line_b, tmp)) {\n            if(tmp.size() == 2) {\n                points = std::move(tmp);\n                return true;\n            } else {\n                points.push_back(tmp.front());\n            }\n        }\n        ++it_first;\n        ++it_second;\n    }\n    return points.size() > 0;\n}\n\n\ntemplate<typename T,\n         typename PointT>\ninline T distance(const PointT &point,\n                  const typename types::Line<PointT>::type &line)\n\n{\n    return boost::geometry::distance(point, line);\n}\n\ntemplate<typename T,\n         typename PointT>\ninline T minEndPointDistance(const typename types::Line<PointT>::type &line_a,\n                             const typename types::Line<PointT>::type &line_b)\n{\n\n    T min = std::numeric_limits<T>::max();\n    const T d0 = boost::geometry::distance(line_a.first,  line_b.first);\n    if(d0 < min)\n        min = d0;\n    const T d1 = boost::geometry::distance(line_a.second, line_b.first);\n    if(d1 < min)\n        min = d1;\n    const T d2 = boost::geometry::distance(line_a.first,  line_b.second);\n    if(d2 < min)\n        min = d2;\n    const T d3 = boost::geometry::distance(line_a.second, line_b.second);\n    if(d3 < min)\n        min = d3;\n    return min;\n}\n\ntemplate<typename T,\n         typename PointT>\ninline T length(const typename types::Line<PointT>::type &line)\n{\n    return std::hypot(line.first.x() - line.second.x(), line.first.y() - line.second.y());\n}\n\ntemplate<typename PointT>\ninline bool intersects\n(const typename types::Line<PointT>::type &line_a,\n const typename types::Line<PointT>::type &line_b)\n\n{\n    return boost::geometry::intersects(line_a, line_b);\n}\n\ntemplate<typename PointT>\ninline bool intersects\n(const typename types::Line<PointT>::type    &line_a,\n const typename types::Polygon<PointT>::type &polygon)\n{\n#ifdef _OPENMP\n    auto &ring = polygon.outer();\n\n    if(ring.size() < 2)\n        return false;\n\n    auto ring_ptr    = ring.data();\n    typename types::Line<PointT>::type line_b(*(ring_ptr + ring.size() - 1), *ring_ptr);\n    bool intersection = intersects<PointT>(line_a, line_b);\n\n#pragma omp parallel for reduction(||:intersection)\n    for(unsigned int i = 0 ; i < ring.size() - 1 ; ++i) {\n        line_b.first  = *(ring_ptr + i);\n        line_b.second = *(ring_ptr + i + 1);\n        intersection |= intersects<PointT>(line_a, line_b);\n    }\n    return intersection;\n#else\n    auto &ring = polygon.outer();\n    auto it_first = ring.begin();\n    auto it_second = it_first + 1;\n\n    while(it_second != ring.end()) {\n        typename types::Line<PointT>::type line_b(*it_first, *it_second);\n        if(intersects<PointT>(line_a, line_b))\n            return true;\n        ++it_first;\n        ++it_second;\n    }\n    return false;\n#endif\n}\n\n\ntemplate<typename PointT, template <typename> class Set>\ninline bool nearestIntersection\n(const typename types::Line<PointT>::type    &line_a,\n const typename Set<PointT>::type            &lines_b,\n typename types::PointSet<PointT>::type      &points)\n{\n    if(lines_b.size() == 0)\n        return false;\n\n    const PointT &origin = line_a.first;\n    double min = std::numeric_limits<double>::max();\n    double dx(0.0), dy(0.0), dsq(0.0);\n    typename types::PointSet<PointT>::type tmp_points;\n\n    for(auto it =\n        lines_b.begin() ;\n        it != lines_b.end() ;\n        ++it) {\n        tmp_points.clear();\n        if(intersection<PointT>(line_a, Set<PointT>::getSegment(it), tmp_points)) {\n            if(tmp_points.size() == 2) {\n                points = std::move(tmp_points);\n                return true;\n            }\n            if(tmp_points.size() == 1) {\n                const PointT &intersection = tmp_points.back();\n                dx  = origin.x() - intersection.x();\n                dy  = origin.y() - intersection.y();\n                dsq = dx * dx + dy * dy;\n                if(dsq < min) {\n                    min = dsq;\n                    std::swap(tmp_points, points);\n                }\n            }\n        }\n    }\n\n    return points.size() > 0;\n}\n\ntemplate<typename PointT>\ninline bool nearestIntersection\n(const typename types::Line<PointT>::type    &line_a,\n const typename types::LineSet<PointT>::type &lines_b,\n typename types::PointSet<PointT>::type      &points)\n{\n    return nearestIntersection<PointT, types::LineSet> (line_a, lines_b, points);\n}\n\ntemplate<typename PointT>\ninline bool nearestIntersection\n(const typename types::Line<PointT>::type           &line_a,\n const typename types::IndexedLineSet<PointT>::type &lines_b,\n typename types::PointSet<PointT>::type       &points)\n{\n    return nearestIntersection<PointT, types::IndexedLineSet> (line_a, lines_b, points);\n}\n\n\ntemplate<typename PointT, template <typename> class Set>\ninline bool nearestIntersection\n(const typename types::Line<PointT>::type    &line_a,\n const typename Set<PointT>::type            &lines_b,\n typename types::PointSet<PointT>::type      &points,\n typename types::Line<PointT>::type          &line_b)\n{\n    if(lines_b.size() == 0)\n        return false;\n\n    const PointT &origin = line_a.first;\n    double min = std::numeric_limits<double>::max();\n    double dx(0.0), dy(0.0), dsq(0.0);\n    typename types::PointSet<PointT>::type tmp_points;\n\n    for(auto it =\n        lines_b.begin() ;\n        it != lines_b.end() ;\n        ++it) {\n        tmp_points.clear();\n        const typename types::Line<PointT>::type &line = Set<PointT>::getSegment(it);\n        if(intersection<PointT>(line_a, line, tmp_points)) {\n            if(tmp_points.size() == 2) {\n                points = std::move(tmp_points);\n                return true;\n            }\n            if(tmp_points.size() == 1) {\n                const PointT &intersection = tmp_points.back();\n                dx  = origin.x() - intersection.x();\n                dy  = origin.y() - intersection.y();\n                dsq = dx * dx + dy * dy;\n                if(dsq < min) {\n                    min = dsq;\n                    line_b = line;\n                    std::swap(tmp_points, points);\n                }\n            }\n        }\n    }\n\n    return points.size() > 0;\n}\n\ntemplate<typename PointT>\ninline bool nearestIntersection\n(const typename types::Line<PointT>::type    &line_a,\n const typename types::LineSet<PointT>::type &lines_b,\n typename types::PointSet<PointT>::type      &points,\n typename types::Line<PointT>::type          &line_b)\n{\n    return nearestIntersection<PointT, types::LineSet> (line_a, lines_b, points, line_b);\n}\n\ntemplate<typename PointT>\ninline bool nearestIntersection\n(const typename types::Line<PointT>::type    &line_a,\n const typename types::IndexedLineSet<PointT>::type &lines_b,\n typename types::PointSet<PointT>::type      &points,\n typename types::Line<PointT>::type          &line_b)\n{\n    return nearestIntersection<PointT, types::IndexedLineSet> (line_a, lines_b, points, line_b);\n}\n\ntemplate<typename PointT,\n         typename T,\n         template <typename> class Set>\ninline T nearestIntersectionDistance\n(const typename types::Line<PointT>::type    &line_a,\n const typename Set<PointT>::type            &lines_b,\n const T default_value)\n{\n    typename types::PointSet<PointT>::type  points;\n    nearestIntersection<PointT, Set> (line_a, lines_b, points);\n\n    if(points.size() == 0)\n        return default_value;\n\n    return boost::geometry::distance(line_a.first, points.front());\n}\n\n\ntemplate<typename T,\n         typename PointT>\ninline T nearestIntersectionDistance\n(const typename types::Line<PointT>::type    &line_a,\n const typename types::LineSet<PointT>::type &lines_b,\n const T default_value)\n{\n    return nearestIntersectionDistance<PointT, T, types::LineSet>(line_a, lines_b, default_value);\n}\n\ntemplate<typename T,\n         typename PointT>\ninline T nearestIntersectionDistance\n(const typename types::Line<PointT>::type           &line_a,\n const typename types::IndexedLineSet<PointT>::type &lines_b,\n const T default_value)\n{\n    return nearestIntersectionDistance<PointT, T, types::IndexedLineSet>(line_a, lines_b, default_value);\n}\n\ntemplate<typename PointT,\n         typename T,\n         template <typename> class Set>\ninline void nearestIntersectionDistance\n(const typename types::Line<PointT>::type    &line_a,\n const typename Set<PointT>::type            &lines_b,\n T &distance,\n T &angle,\n const T default_distance,\n const T default_angle)\n{\n    typename types::PointSet<PointT>::type  points;\n    typename types::Line<PointT>::type      line_b;\n    nearestIntersection<PointT, Set> (line_a, lines_b, points, line_b);\n\n    if(points.size() == 0) {\n        distance = default_distance;\n        angle = default_angle;\n        return;\n    }\n\n    distance = boost::geometry::distance(line_a.first, points.front());\n\n    PointT diff_a(line_a.first.x() - line_a.second.x(),\n                  line_a.first.y() - line_a.second.y());\n    PointT diff_b(line_b.first.x() - line_b.second.x(),\n                  line_b.first.y() - line_b.second.y());\n\n    angle = std::acos((boost::geometry::dot_product(diff_a, diff_b)) /\n                      (boost::geometry::length(line_a)*\n                       boost::geometry::length(line_b)));\n}\n\n\ntemplate<typename T,\n         typename PointT>\ninline void nearestIntersectionDistance\n(const typename types::Line<PointT>::type    &line_a,\n const typename types::LineSet<PointT>::type &lines_b,\n T &distance,\n T &angle,\n const T default_distance,\n const T default_angle)\n{\n    nearestIntersectionDistance<PointT, T, types::LineSet>(line_a, lines_b,\n                                                       distance,\n                                                       angle,\n                                                       default_distance,\n                                                       default_angle);\n}\n\ntemplate<typename T,\n         typename PointT>\ninline void nearestIntersectionDistance\n(const typename types::Line<PointT>::type           &line_a,\n const typename types::IndexedLineSet<PointT>::type &lines_b,\n T &distance,\n T &angle,\n const T default_distance,\n const T default_angle)\n{\n    nearestIntersectionDistance<PointT, T, types::IndexedLineSet>(line_a,\n                                                              lines_b,\n                                                              distance,\n                                                              angle,\n                                                              default_distance,\n                                                              default_angle);\n}\n\ntemplate<typename T,\n         typename PointT>\ninline void nearestIntersectionDistanceBatch(const typename types::LineSet<PointT>::type  &lines_a,\n                                             const typename types::LineSet<PointT>::type  &lines_b,\n                                             const T default_value,\n                                             std::vector<T> &results)\n{\n    results.resize(lines_a.size());\n    auto lines_a_ptr = lines_a.data();\n    auto results_ptr = results.data();\n\n#pragma omp parallel for\n    for(unsigned int i = 0 ; i < lines_a.size() ; ++i) {\n        auto &line = *(lines_a_ptr + i);\n        auto &result = *(results_ptr + i);\n        result = nearestIntersectionDistance<PointT, T, types::LineSet>(line, lines_b, default_value);\n    }\n}\n\ntemplate<typename PointT>\ninline void nearestIntersectionBatch\n(const typename types::LineSet<PointT>::type            &lines_a,\n const typename types::LineSet<PointT>::type            &lines_b,\n typename types::IntersectionResultSet<PointT>::type &results)\n{\n    unsigned int lines_a_size = lines_a.size();\n    results.resize(lines_a_size);\n\n    auto lines_a_ptr = lines_a.data();\n    auto results_ptr = results.data();\n\n#pragma omp parallel for\n    for(unsigned int i = 0 ; i < lines_a_size ; ++i) {\n        auto &result = *(results_ptr + i);\n        auto &line = *(lines_a_ptr + i);\n        result.valid = nearestIntersection<PointT>(line,\n                                                   lines_b,\n                                                   result.result);\n    }\n}\n\ntemplate<typename PointT>\ninline bool translate\n(const PointT                                    &src_point,\n const typename types::Translation<PointT>::type &translation,\n PointT                                    &dst_point)\n{\n    return boost::geometry::transform(src_point, dst_point, translation);\n}\n\n\ntemplate<typename PointT>\ninline bool translate\n(const typename types::Line<PointT>::type        &src_line,\n const typename types::Translation<PointT>::type &translation,\n typename types::Line<PointT>::type        &dst_line)\n{\n    bool success = true;\n    success &= translate<PointT>(src_line.first, translation, dst_line.first);\n    success &= translate<PointT>(src_line.second, translation, dst_line.second);\n    return success;\n}\n\nnamespace impl{\n/**\n * @brief Do translation for more than one geometry.\n * @param src           the source container\n * @param translation   the translation\n * @param dst           the destination container\n * @return              if all translations were susccessful\n */\ntemplate<typename PointT, typename ContainerT, typename TranslationT>\ninline bool foreachTranslation(const ContainerT   &src_container,\n                               const TranslationT &translation,\n                               ContainerT &dst_container)\n{\n    dst_container.resize(src_container.size());\n    auto src_ptr = src_container.data();\n    auto dst_ptr = dst_container.data();\n    bool success = true;\n\n#pragma omp parallel for reduction(&&:success)\n    for(unsigned int i = 0 ; i < src_container.size() ; ++i) {\n        auto &src_geom = *(src_ptr + i);\n        auto &dst_geom = *(dst_ptr + i);\n\n        success &= translate<PointT>\n                (src_geom, translation, dst_geom);\n    }\n    return success;\n}\n}\n\ntemplate<typename PointT>\ninline bool translate\n(const typename types::PointSet<PointT>::type    &src_points,\n const typename types::Translation<PointT>::type &translation,\n typename types::PointSet<PointT>::type    &dst_points)\n{\n    return impl::foreachTranslation<PointT,\n            typename types::PointSet<PointT>::type,\n            typename types::Translation<PointT>::type>\n            (src_points, translation, dst_points);\n}\n\ntemplate<typename PointT>\ninline bool translate\n(const typename types::LineSet<PointT>::type     &src_lines,\n const typename types::Translation<PointT>::type &translation,\n typename types::LineSet<PointT>::type     &dst_lines)\n{\n    return impl::foreachTranslation<PointT,\n            typename types::LineSet<PointT>::type,\n            typename types::Translation<PointT>::type>\n            (src_lines, translation, dst_lines);\n}\n\ntemplate<typename PointT>\ninline bool rotate\n(const PointT                                    &src_point,\n const typename types::Rotation<PointT>::type    &rotation,\n PointT                                          &dst_point)\n{\n    return boost::geometry::transform(src_point, dst_point, rotation);\n}\n\ntemplate<typename PointT>\ninline bool rotate(const typename types::Line<PointT>::type        &src_line,\n                   const typename types::Rotation<PointT>::type    &rotation,\n                   typename types::Line<PointT>::type              &dst_line)\n{\n    return boost::geometry::transform(src_line, dst_line, rotation);\n}\n\n\ntemplate<typename T, typename PointT>\nT dot(const typename types::Line<PointT>::type &line_a,\n           const typename types::Line<PointT>::type &line_b)\n{\n    PointT diff_a(line_a.first.x() - line_a.second.x(),\n                  line_a.first.y() - line_a.second.y());\n    PointT diff_b(line_b.first.x() - line_b.second.x(),\n                  line_b.first.y() - line_b.second.y());\n    return boost::geometry::dot_product(diff_a, diff_b);\n}\n\ntemplate<typename T>\ninline bool equal\n(const T value_1,\n const T value_2,\n const T epsilon)\n{\n    return std::abs(value_1 - value_2) < epsilon;\n}\n\ntemplate<typename PointT>\ninline bool withinExcl\n(const PointT &p,\n const typename types::Polygon<PointT>::type &polygon)\n{\n    return boost::geometry::within(p, polygon);\n}\n\ntemplate<typename PointT>\ninline bool withinExcl\n(const typename types::Line<PointT>::type &line,\n const typename types::Box<PointT>::type &box)\n{\n    return boost::geometry::within(line.first, box) &&\n           boost::geometry::within(line.second, box);\n}\n\ntemplate<typename PointT>\ninline bool lessEqual\n(const PointT &p1,\n const PointT &p2)\n{\n    return p1.x() <= p2.x() && p1.y() <= p2.y();\n}\n\ntemplate<typename PointT>\ninline bool greaterEqual\n(const PointT &p1,\n const PointT &p2)\n{\n    return p1.x() >= p2.x() && p1.y() >= p2.y();\n}\n\ntemplate<typename PointT, typename T>\ninline bool equal\n(const PointT &p1,\n const PointT &p2,\n const T eps)\n{\n    return equal<T>(p1.x(), p2.x(), eps)  && equal(p1.y(), p2.y(), eps);\n}\n\ntemplate<typename PointT, typename T>\ninline bool equal\n(const typename types::Line<PointT>::type &line_a,\n const typename types::Line<PointT>::type &line_b,\n const T eps)\n{\n    return (equal<PointT, T>(line_a.first, line_b.first, eps)  && equal<PointT, T>(line_a.second, line_b.second, eps)) ||\n           (equal<PointT, T>(line_a.first, line_b.second, eps) && equal<PointT, T>(line_a.second, line_b.first, eps));\n}\n\ntemplate<typename T, typename PointT>\nT angle(const typename types::Line<PointT>::type &line_a,\n        const typename types::Line<PointT>::type &line_b)\n{\n    PointT diff_a(line_a.first.x() - line_a.second.x(),\n                  line_a.first.y() - line_a.second.y());\n    PointT diff_b(line_b.first.x() - line_b.second.x(),\n                  line_b.first.y() - line_b.second.y());\n\n    const double norm_a = std::hypot(diff_a.x(), diff_a.y());\n    const double norm_b = std::hypot(diff_b.x(), diff_b.y());\n    if(norm_a == 0.0)\n        return 0.0;\n    if(norm_b == 0.0)\n        return 0.0;\n\n    diff_a.x(diff_a.x() / norm_a);\n    diff_a.y(diff_a.y() / norm_a);\n\n    diff_b.x(diff_b.x() / norm_b);\n    diff_b.y(diff_b.y() / norm_b);\n\n    return std::acos(boost::geometry::dot_product(diff_a, diff_b));\n}\n\ntemplate<typename T, typename PointT>\nT angle(const typename types::Line<PointT>::type &line_a,\n        const typename types::Line<PointT>::type &line_b,\n        const T eps)\n{\n    PointT diff_a(line_a.first.x() - line_a.second.x(),\n                  line_a.first.y() - line_a.second.y());\n    PointT diff_b(line_b.first.x() - line_b.second.x(),\n                  line_b.first.y() - line_b.second.y());\n\n    double a = std::hypot(diff_a.x(), diff_a.y());\n    double b = std::hypot(diff_b.x(), diff_b.y());\n    double c = 0.0;\n\n    if(equal<PointT, T>(line_a.first, line_b.first, eps)) {\n        const double dx = line_a.second.x() - line_b.second.x();\n        const double dy = line_a.second.y() - line_b.second.y();\n        c = std::hypot(dx, dy);\n    } else\n    if(equal<PointT, T>(line_a.first, line_b.second, eps)) {\n        const double dx = line_a.second.x() - line_b.first.x();\n        const double dy = line_a.second.y() - line_b.first.y();\n        c = std::hypot(dx, dy);\n    } else\n    if(equal<PointT, T>(line_a.second, line_b.first, eps)) {\n        std::swap(a,b);\n        const double dx = line_a.first.x() - line_b.second.x();\n        const double dy = line_a.first.y() - line_b.second.y();\n        c = std::hypot(dx, dy);\n    } else\n    if(equal<PointT, T>(line_a.second, line_b.second, eps)) {\n        std::swap(a,b);\n        const double dx = line_a.first.x() - line_b.first.x();\n        const double dy = line_a.first.y() - line_b.first.y();\n        c = std::hypot(dx, dy);\n    } else {\n        return angle<T, PointT>(line_a, line_b);\n    }\n\n    if(a == 0.0)\n        return 0.0;\n    if(b == 0.0)\n        return 0.0;\n\n    double angle = std::acos((a*a + b*b - c*c) / (2 * a * b));\n    return angle == M_PI ? 0.0 : angle;\n}\n\ntemplate<typename T>\ninline bool withinIncl\n(const T p_x,   const T p_y,\n const T min_x, const T min_y,\n const T max_x, const T max_y)\n{\n    return p_x >= min_x && p_y >= min_y &&\n            p_x <= max_x && p_y <= max_y;\n}\n\ntemplate<typename PointT>\ninline bool withinIncl\n(const PointT &p,\n const typename types::Box<PointT>::type &box)\n{\n    const PointT &min = box.min_corner();\n    const PointT &max = box.max_corner();\n    return greaterEqual(p, min) && lessEqual(p, max);\n}\n\ntemplate<typename PointT>\ninline bool withinIncl\n(const typename types::Line<PointT>::type &line,\n const typename types::Box<PointT>::type  &box)\n{\n    return withinIncl(line.first, box) &&\n            withinIncl(line.second, box);\n}\n\ntemplate<typename PointT>\ninline bool withinIncl\n(const typename types::Box<PointT>::type &inner,\n const typename types::Box<PointT>::type &outer)\n{\n    return withinIncl(inner.min_corner(), outer) &&\n            withinIncl(inner.max_corner(), outer);\n}\n\ntemplate<typename PointT>\ninline bool within\n(const typename types::Polygon<PointT>::type &inner,\n const typename types::Polygon<PointT>::type &outer)\n{\n    bool within = true;\n    auto inner_pts_ptr = inner.outer().data();\n#pragma omp parallel for reduction(&&:within)\n    for(unsigned int i = 0 ; i < inner.outer().size() ; ++i) {\n        auto &pt  = *(inner_pts_ptr + i);\n        within &= boost::geometry::within(pt, outer);\n    }\n\n    return within;\n}\n\ntemplate<typename PointT>\ninline bool covered_by(const typename types::Polygon<PointT>::type &covered,\n                       const typename types::Polygon<PointT>::type &by)\n{\n#if BOOST_VERSION >= 105700\n    return boost::geometry::covered_by(covered, by);\n#else\n    if(boost::geometry::intersects(covered, by))\n        return true;\n    if(within<PointT>(covered, by))\n        return true;\n    return false;\n#endif\n}\n\n\ntemplate<typename PointT>\ninline bool touches\n(const typename types::Line<PointT>::type     &line,\n const typename types::Polygon<PointT>::type  &polygon)\n{\n    if(withinExcl<PointT>(line.first, polygon))\n        return true;\n    if(withinExcl<PointT>(line.second, polygon))\n        return true;\n    if(intersects<PointT>(line, polygon))\n        return true;\n\n    return false;\n}\n\ntemplate<typename PointT>\ninline bool touches\n(const typename types::Line<PointT>::type &line,\n const typename types::Box<PointT>::type  &box)\n{\n    if(boost::geometry::within(line.first, box))\n        return true;\n    if(boost::geometry::within(line.second, box))\n        return true;\n\n    const PointT& min = box.min_corner();\n    const PointT& max = box.max_corner();\n    PointT lup (min.x(), max.y());\n    PointT rlo (max.x(), min.y());\n    typename types::Line<PointT>::type t_edge(max, lup);\n    if(intersects<PointT>(line, t_edge))\n        return true;\n    typename types::Line<PointT>::type l_edge(min, lup);\n    if(intersects<PointT>(line, l_edge))\n        return true;\n    typename types::Line<PointT>::type r_edge(max, rlo);\n    if(intersects<PointT>(line, r_edge))\n        return true;\n    typename types::Line<PointT>::type b_edge(min, rlo);\n    if(intersects<PointT>(line, b_edge))\n        return true;\n\n    return false;\n}\n\ntemplate<typename PointT>\ntypename types::Polygon<PointT>::type toPolygon\n(const PointT &min,\n const PointT &max)\n{\n    typename types::Polygon<PointT>::type poly;\n    boost::geometry::append(poly.outer(), PointT(min.x(), min.y()));\n    boost::geometry::append(poly.outer(), PointT(max.x(), min.y()));\n    boost::geometry::append(poly.outer(), PointT(max.x(), max.y()));\n    boost::geometry::append(poly.outer(), PointT(min.x(), max.y()));\n    return poly;\n}\n\ntemplate<typename PointT>\ntypename types::Polygon<PointT>::type toPolygon\n(const typename types::Box<PointT>::type &box)\n{\n    typename types::Polygon<PointT>::type poly;\n    const PointT &min = box.min_corner();\n    const PointT &max = box.max_corner();\n    boost::geometry::append(poly.outer(), PointT(min.x(), min.y()));\n    boost::geometry::append(poly.outer(), PointT(max.x(), min.y()));\n    boost::geometry::append(poly.outer(), PointT(max.x(), max.y()));\n    boost::geometry::append(poly.outer(), PointT(min.x(), max.y()));\n    return poly;\n}\n\ntemplate<typename PointT,\n         typename Periodic>\ninline void polarLineSet\n(const PointT &center,\n const double center_line_orientation,\n const double opening_angle,\n const double angle_increment,\n const double length,\n typename types::LineSet<PointT>::type &lines)\n{\n    unsigned int num_rays = std::floor(opening_angle / angle_increment) + 1;\n    lines.resize(num_rays);\n\n    auto lines_ptr = lines.data();\n    double start_angle = center_line_orientation - opening_angle * 0.5;\n    double angle = 0.0;\n\n#pragma omp parallel for private(angle)\n    for(unsigned int i = 0 ; i < num_rays ; ++i) {\n        auto &line = *(lines_ptr + i);\n        angle = start_angle + i * angle_increment;\n        types::Point2d &origin      = line.first;\n        types::Point2d &destination = line.second;\n        origin.x(center.x());\n        origin.y(center.y());\n        destination.x(center.x() + std::cos(angle) * length);\n        destination.y(center.y() + std::sin(angle) * length);\n    }\n}\n\ntemplate<typename PointT,\n         typename Periodic>\ninline void polarLineSet\n(const PointT &center,\n const double center_line_orientation,\n const double opening_angle,\n const double angle_increment,\n const double length,\n typename types::LineSet<PointT>::type &lines,\n std::vector<double> &angles)\n{\n    unsigned int num_rays = std::floor(opening_angle / angle_increment) + 1;\n    lines.resize(num_rays);\n    angles.resize(num_rays);\n\n    auto angles_ptr = angles.data();\n    auto lines_ptr  = lines.data();\n\n    double start_angle = center_line_orientation - opening_angle * 0.5;\n\n#pragma omp parallel for\n    for(unsigned int i = 0 ; i < num_rays ; ++i) {\n        auto &line  = *(lines_ptr + i);\n        auto &angle = *(angles_ptr + i);\n\n        angle = start_angle + i * angle_increment;\n\n        types::Point2d &origin      = line.first;\n        types::Point2d &destination = line.second;\n        origin.x(center.x());\n        origin.y(center.y());\n        destination.x(center.x() + std::cos(angle) * length);\n        destination.y(center.y() + std::sin(angle) * length);\n    }\n}\n\ntemplate<typename PointT,\n         typename Periodic>\ninline void polarLineSet\n(const PointT         &center,\n const double          center_line_orientation,\n const double          opening_angle,\n const unsigned int    num_rays,\n const double          length,\n typename types::LineSet<PointT>::type &lines)\n{\n    lines.resize(num_rays);\n\n    auto lines_ptr = lines.data();\n\n    double angle_increment(opening_angle / (double) num_rays);\n    double start_angle = center_line_orientation - opening_angle * 0.5;\n    double angle = 0.0;\n    double cos = 1.0;\n    double sin = 0.0;\n\n#pragma omp parallel for private(cos, sin, angle)\n    for(unsigned int i = 0 ; i < num_rays ; ++i) {\n        auto &line = *(lines_ptr + i);\n        angle = start_angle + i * angle_increment;\n        types::Point2d &origin      = line.first;\n        types::Point2d &destination = line.second;\n        origin.x(center.x());\n        origin.y(center.y());\n        Periodic::sin_cos(angle, sin, cos);\n        destination.x(center.x() + cos * length);\n        destination.y(center.y() + sin * length);\n    }\n}\n\ntemplate<typename PointT,\n         typename Periodic>\ninline void polarLineSet\n(const PointT         &center,\n const double          center_line_orientation,\n const double          opening_angle,\n const unsigned int    num_rays,\n const double          length,\n typename types::LineSet<PointT>::type &lines,\n std::vector<double> &angles)\n{\n    lines.resize(num_rays);\n    angles.resize(num_rays);\n    double angle_increment(opening_angle / (double) num_rays);\n    double start_angle = center_line_orientation - opening_angle * 0.5;\n    double cos = 1.0;\n    double sin = 0.0;\n\n    auto lines_ptr = lines.data();\n    auto angles_ptr = angles.data();\n#pragma omp parallel for private(cos, sin)\n    for(unsigned int i = 0 ; i < num_rays ; ++i) {\n        auto &line  = *(lines_ptr + i);\n        auto &angle = *(angles_ptr + i);\n        angle = start_angle + i * angle_increment;\n        types::Point2d &origin      = line.first;\n        types::Point2d &destination = line.second;\n        origin.x(center.x());\n        origin.y(center.y());\n        Periodic::sin_cos(angle, sin, cos);\n        destination.x(center.x() + cos * length);\n        destination.y(center.y() + sin * length);\n    }\n}\n\ntemplate<typename PointT>\ninline void circularPolygonApproximation\n(const PointT &center,\n const double  radius,\n const double  ang_res,\n typename types::Polygon<PointT>::type &polygon)\n{\n    unsigned int iterations = std::floor(2 * M_PI / ang_res + 0.5);\n    double       angle = 0.0;\n\n    for(unsigned int i = 0 ; i < iterations ; ++i, angle -= ang_res) {\n        PointT p;\n        p.x(center.x() + std::cos(angle) * radius);\n        p.y(center.y() + std::sin(angle) * radius);\n        boost::geometry::append(polygon.outer(), p);\n    }\n    boost::geometry::append(polygon.outer(), polygon.outer().front());\n}\n}\n}\n#endif // DXF_ALGORITHMS_HPP\n", "meta": {"hexsha": "60aabe70121fa30a2e4162ed650f6b2cbe82410e", "size": 30370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cslibs_boost_geometry/algorithms.hpp", "max_stars_repo_name": "cogsys-tuebingen/cslibs_boost_geometry", "max_stars_repo_head_hexsha": "a6438e6ef62afb2699173c75430b7f97e0cc451f", "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/cslibs_boost_geometry/algorithms.hpp", "max_issues_repo_name": "cogsys-tuebingen/cslibs_boost_geometry", "max_issues_repo_head_hexsha": "a6438e6ef62afb2699173c75430b7f97e0cc451f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/cslibs_boost_geometry/algorithms.hpp", "max_forks_repo_name": "cogsys-tuebingen/cslibs_boost_geometry", "max_forks_repo_head_hexsha": "a6438e6ef62afb2699173c75430b7f97e0cc451f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-16T09:43:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T09:43:15.000Z", "avg_line_length": 31.8677859391, "max_line_length": 121, "alphanum_fraction": 0.6231807705, "num_tokens": 7214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5019537550856411}}
{"text": "/*\n * main.cpp\n *\n *  Created on: 20 Aug 2018\n *      Author: scsjd\n */\n#include <iostream>\n#include <fstream>\n#include <jsoncpp/json/json.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZ_p.h>\n#include <HE1NDecrypter.h>\n\nvoid usage() {\n    std::cerr << \"[ERROR] Bad number of parameters\" << std::endl;\n    std::cout << \"    Usage: innervalidate <cipher secrets file> <cipher parameters file> <result file> <output file>\" << std::endl;\n}\n\nint main(int argc, char **argv) {\n\tconst char* secretsPath;\n\tconst char* parametersPath;\n\tconst char* resultPath;\n\tconst char* outputPath;\n\tif (argc < 5){\n\t\tusage();\n\t\treturn -1;\n\t}\n\telse{\n\t\tsecretsPath = argv[1];\n\t\tparametersPath = argv[2];\n\t\tresultPath = argv[3];\n\t\toutputPath = argv[4];\n\t}\n\n\tstd::cout << \"Starting innervalidate with the following configuration:\" << std::endl;\n\tstd::cout << \"\\tcipher secrets file: \" << secretsPath << std::endl;\n\tstd::cout << \"\\tcipher parameters file: \" << parametersPath << std::endl;\n\tstd::cout << \"\\tplaintext result file: \" << resultPath << std::endl;\n\tstd::cout << \"\\tciphertext result file: \" << outputPath << std::endl;\n\n\t//read in value from result file\n\tNTL::ZZ result;\n\tstd::ifstream ifs_res(resultPath);\n\tif (ifs_res.is_open()){\n\t\tifs_res >> result;\n\t\tifs_res.close();\n\t}\n\n\tstd::cout << \"Result from computing on plaintexts: \" << result << std::endl;\n\n\t//read in modulus from parameters file\n\tstd::ifstream ifs_params(parametersPath);\n\tif (!ifs_params.is_open()) throw std::ios_base::failure(\"Could not open cipher parameters file.\");\n\tstd::string parameters;\n\tgetline(ifs_params,parameters);\n\tifs_params.close();\n\tJson::Value root;\n\tJson::Reader reader;\n\tNTL::ZZ modulus;\n\tbool parsedOK = reader.parse(parameters, root);\n\tif (parsedOK){\n\t\tmodulus = NTL::conv<NTL::ZZ>(root[\"modulus\"].asCString());\n\t}\n\tstd::cout << \"Modulus: \" << modulus << std::endl;\n\n\t//read in value from output file\n\tNTL::ZZ_p output;\n\tstd::ifstream ifs_out(outputPath);\n\tif (ifs_out.is_open()){\n\t\tNTL::ZZ_p::init(modulus);\n\t\tifs_out >> output;\n\t\tifs_out.close();\n\t}\n\tstd::cout << \"Result from computing on ciphertexts: \" << output << std::endl;\n\n\t//read in secrets and parameters\n\tstd::ifstream ifs_secrets(secretsPath);\n\tif (!ifs_secrets.is_open()) throw std::ios_base::failure(\"Could not open cipher secrets file.\");\n\tstd::string secrets;\n\tgetline(ifs_secrets,secrets);\n\tifs_secrets.close();\n\n\t//decrypt\n\tHE1NDecrypter d;\n\td.readSecretsFromJSON(secrets);\n\tNTL::ZZ decrypted = d.decrypt(output);\n\tstd::cout << \"Decrypted result from computing on ciphertexts: \" << decrypted << std::endl;\n\t//compare with value from result file\n\tif(decrypted==result){\n\t\tstd::cout << \"Result computed correctly\" << std::endl;\n\t}\n\telse{\n\t\tstd::cout << \"Something went wrong\" << std::endl;\n\t\tstd::cout << \"\\tdecrypted=\" << decrypted << std::endl;\n\t\tstd::cout << \"\\tresult=\" << result << std::endl;\n\t}\n}\n", "meta": {"hexsha": "5b76a89af7a3ae7c5d3294b8b46bc3175346cdab", "size": 2836, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/inner_product/innervalidate/main.cpp", "max_stars_repo_name": "TANGO-Project/cryptango", "max_stars_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "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/inner_product/innervalidate/main.cpp", "max_issues_repo_name": "TANGO-Project/cryptango", "max_issues_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "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/inner_product/innervalidate/main.cpp", "max_forks_repo_name": "TANGO-Project/cryptango", "max_forks_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "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.9387755102, "max_line_length": 132, "alphanum_fraction": 0.6727785614, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.501953755085641}}
{"text": "#include <gtest/gtest.h>\n\n#include <lens/OrthogonalLens.h>\n#include <fanTriangleMesh.h>\n#include <objects/TriangleMeshObject.h>\n\n#include <texture/film/SDLFilm.h>\n#include <camera/PointScannerCamera.h>\n#include <texture/film/FreeImageFilm.h>\n#include <fanBufferObject.h>\n#include <objects/TriangleMeshObject.h>\n#include <fanScanner.h>\n\n#include <boost/shared_ptr.hpp>\n\nusing namespace fan;\n\n/*                 ^ z\n *                 |    ^ y\n *                 |   /\n *                 |  /\n *                 | /\n *                 |/\n *                 .------------> x\n *           ^ y  /\n *           |   /\n *    ---------------\n *   |       | / z   |\n *   |       |/      |\n *   |       .-------|--> x\n *   |               |\n *   |               |\n *    ---------------\n *   Screen coordinate\n */\n\n\nTEST(OrthogonalLens,LookThroughPositiveYAxis) {\n    OrthogonalLens lens( fanVector3<float>(0, -100, 0),\n                         fanVector3<float>(0, 0, 0),\n                         fanVector3<float>(0, 0, 1),\n                         fanVector3<float>(100, 100, 100) );\n\n    fanVector<int, 2> size;\n    size[0] = 100; size[1] = 100;\n    fanVector<float, 2> result;\n    fanVector<float, 4> homoPos;\n    fanMatrix<float, 4, 4> pos { 1,0,0,0,\n                                 0,1,0,0,\n                                 0,0,1,0,\n                                 0,0,0,1 };\n    project( transform( pos, fanVector3<float>(0, 0, 1) ),\n                    lens, size,\n                    result, homoPos );\n    EXPECT_EQ( 50, result[0] );\n    EXPECT_EQ( 51, result[1] );\n\n    project( transform( pos, fanVector3<float>( 0, 0, 2 ) ),\n                    lens, size,\n                    result, homoPos );\n\n    EXPECT_EQ( 50, result[0] );\n    EXPECT_EQ( 52, result[1] );\n\n    project( transform( pos, fanVector3<float>( 1, 0, 2 ) ),\n                    lens, size,\n                    result, homoPos );\n\n    EXPECT_EQ( 51, result[0] );\n    EXPECT_EQ( 52, result[1] );\n\n    project( transform( pos, fanVector3<float>( 2, 0, 2 ) ),\n                    lens, size,\n                    result, homoPos );\n\n    EXPECT_EQ( 52, result[0] );\n    EXPECT_EQ( 52, result[1] );\n\n}\n\n/*                 ^ z                                ^\n *                 |    ^ y                   y ^    / x\n *                 |   /                        | /|/\n *                 |  /                         |/ |\n *                 | /                          / /|\n *                 |/                          /|/ |\n *                 .------------>-------------|-.  /\n *                /             x             |   /\n *                                            |  /\n *                                            | /\n *                                            |/\n *\n */\n\nTEST(OrthogonalLens,LookThroughNegativeXAxis) {\n    OrthogonalLens lens( fanVector3<float>(100, 0, 0),\n                         fanVector3<float>(0, 0, 0),\n                         fanVector3<float>(0, 0, 1),\n                         fanVector3<float>(100, 100, 10000) );\n\n    fanVector<int, 2> size;\n    fanVector<float, 4> homoPos;\n    fanMatrix<float, 4, 4> pos { 1,0,0,0,\n                                 0,1,0,0,\n                                 0,0,1,0,\n                                 0,0,0,1 };\n    size[0] = 100; size[1] = 100;\n    fanVector<float, 2> result;\n    project( transform( pos, fanVector3<float>(0, 0, 1) ),\n                    lens, size,\n                    result, homoPos );\n\n    EXPECT_EQ( 50, result[0] );\n    EXPECT_EQ( 51, result[1] );\n\n    project( transform( pos, fanVector3<float>( 0, 0, 2 ) ),\n                    lens, size,\n                    result, homoPos );\n\n    EXPECT_EQ( 50, result[0] );\n    EXPECT_EQ( 52, result[1] );\n\n    project( transform( pos, fanVector3<float>( 0, 1, 2 ) ),\n                    lens, size,\n                    result, homoPos );\n\n    EXPECT_EQ( 51, result[0] );\n    EXPECT_EQ( 52, result[1] );\n\n    project( transform( pos, fanVector3<float>( 0, 2, 2 ) ),\n                    lens, size,\n                    result, homoPos );\n\n    EXPECT_EQ( 52, result[0] );\n    EXPECT_EQ( 52, result[1] );\n\n}\n\nTEST(OrthogonalLens,RenderAxis) {\n    OrthogonalLens lens( fanVector3<float>( 1000, -1000, 1000),\n                         fanVector3<float>(0, 0, 0),\n                         fanVector3<float>(0, 0, 1),\n                         fanVector3<float>(800, 600, 10000) );\n\n    fan::fanVector<int, 2> size;\n    size[0] = 800; size[1] = 600;\n    FreeImageFilm film( size, \"RenderAxis.png\" );\n    fan::fanScene scene;\n\n    boost::shared_ptr<fan::fanBufferObject<fan::fanVector3<float> > >\n        vertices( new fan::fanBufferObject<fan::fanVector3<float> >( 3000 ) );\n    boost::shared_ptr<fan::fanBufferObject<fan::fanTriangle> >\n        faces( new fan::fanBufferObject<fan::fanTriangle>( 0 ) );\n    boost::shared_ptr<fan::fanTriangleMesh>\n        mesh( new fan::fanTriangleMesh() );\n    mesh->mVertices = vertices;\n    mesh->mFaces = faces;\n\n    boost::shared_ptr<TriangleMeshObject>\n        object(new TriangleMeshObject(fanMatrix<float, 4, 4>{1,0,0,0,\n                                                             0,1,0,0,\n                                                             0,0,1,0,\n                                                             0,0,0,1,} ) );\n    object->mMeshes.push_back( mesh );\n    int verticesNum = 0;\n    for ( size_t i = 0; i < 1000; ++i ) {\n        vertices->mBuffer[verticesNum] = fan::fanVector3<float>( i, 0, 0 );\n        ++verticesNum;\n    }\n    for ( size_t i = 0; i < 1000; i+=4 ) {\n        vertices->mBuffer[verticesNum] = fan::fanVector3<float>( 0, i, 0 );\n        ++verticesNum;\n    }\n    for ( size_t i = 0; i < 1000; i+=8 ) {\n        vertices->mBuffer[verticesNum] = fan::fanVector3<float>( 0, 0, i );\n        ++verticesNum;\n    }\n\n    scene.mTriangleMeshObjects.push_back( object );\n    PointScannerCamera camera;\n    camera.takePicture( scene, film, lens );\n    film.develope();\n\n}\n\n", "meta": {"hexsha": "786b565393d193b2f84adffe13ec80efdbc764e3", "size": 5942, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unittest/OrthogonalLens_test.cpp", "max_stars_repo_name": "aurthconan/fanLens", "max_stars_repo_head_hexsha": "d05ce02cd748f21b6a5385892972accce54fd58d", "max_stars_repo_licenses": ["MIT"], "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/unittest/OrthogonalLens_test.cpp", "max_issues_repo_name": "aurthconan/fanLens", "max_issues_repo_head_hexsha": "d05ce02cd748f21b6a5385892972accce54fd58d", "max_issues_repo_licenses": ["MIT"], "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/unittest/OrthogonalLens_test.cpp", "max_forks_repo_name": "aurthconan/fanLens", "max_forks_repo_head_hexsha": "d05ce02cd748f21b6a5385892972accce54fd58d", "max_forks_repo_licenses": ["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.9462365591, "max_line_length": 78, "alphanum_fraction": 0.4308313699, "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5019537500336483}}
{"text": "#include \"network.h\"\n#include <stdlib.h>\n#include <math.h>\n#include <algorithm>\n#include <assert.h>\n#include <armadillo>\n#include <iostream>\n\nvoid relu_kernel(int size, double* data);\nvoid relu_prime_kernel(int size, double* data);\nvoid lin_kernel(int size, double* data);\nvoid lin_prime_kernel(int size, double* data);\nvoid sigmoid_kernel(int size, double* data);\nvoid sigmoid_prime_kernel(int size, double* data);\nvoid tanh_kernel(int size, double* data);\nvoid tanh_prime_kernel(int size, double* data);\n\nstatic const ActivationFunction activation_functions[] = {\n    {false, 0.0, true, 0.0, -1.0, &relu_kernel, &relu_prime_kernel},\n    {false, 0.0, false, 0.0, 0.0, &lin_kernel, &lin_prime_kernel},\n    {true, 1.0, true, 0.0, -1e46, &sigmoid_kernel, &sigmoid_prime_kernel},\n    {true, 1.0, true, -1.0, -1e46, &tanh_kernel, &tanh_prime_kernel}\n};\n\nActivationFunction getActivationFunction(ActivationFunction::Enum func) {\n    return activation_functions[func];\n}\n\nvoid layer_init(Layer* layer, int sI, int sO, ActivationFunction::Enum func, double* parameters) {\n    layer->nInputs = sI;\n    layer->nOutputs = sO;\n    layer->nN = sO;\n    layer->activation = activation_functions[func].activation;\n    layer->activation_prime = activation_functions[func].activation_prime;\n    layer->activation_enum = func;\n    layer->outputs = (double*)calloc(sO, sizeof *layer->outputs);\n    layer->weights = parameters;\n    layer->biases = parameters + sI*sO;\n}\n\nvoid layer_free(Layer* layer) {\n    free(layer->outputs);\n}\n\nvoid layer_compute_z(Layer* layer, const double* inputs) {\n    arma::mat weights(layer->weights, layer->nOutputs, layer->nInputs, false, true);\n    arma::colvec bias(layer->biases, layer->nOutputs, false, true);\n    arma::colvec output(layer->outputs, layer->nOutputs, false, true);\n    arma::colvec input((double*)inputs, layer->nInputs, false, true);\n    output = weights*input + bias;\n}\n\nvoid layer_compute_activation(Layer* layer, const double* inputs) {\n    layer_compute_z(layer, inputs);\n    layer->activation(layer->nOutputs, layer->outputs);\n}\n\n\nNetwork* network_create(int input_size, int num_layers, const int* layer_sizes, \n    int num_activations, const ActivationFunction::Enum* func) {\n    assert(input_size > 0);\n    assert(num_layers > 0);\n    assert(layer_sizes != NULL);\n    assert(func != NULL);\n    Network* n = (Network*)calloc(1, sizeof *n);\n    int layers = num_layers;\n    n->nLayers = layers;\n    n->nHiddenLayers = layers - 1;\n    n->layers = (Layer*)calloc(layers, sizeof *n->layers);\n    n->parameter_size = input_size*layer_sizes[0];\n    for(int i = 1; i < layers; ++i) {\n        n->parameter_size += layer_sizes[i-1]*layer_sizes[i] + layer_sizes[i];\n    }\n    n->parameters = (double*)calloc(n->parameter_size, sizeof *n->parameters);\n    layer_init(n->layers, input_size, layer_sizes[0], func[0], n->parameters);\n    int parameter_index = input_size*layer_sizes[0];\n    for(int i = 1; i < layers; ++i) {\n        layer_init(&n->layers[i], layer_sizes[i-1], layer_sizes[i], func[i],\n            &n->parameters[parameter_index]);\n        parameter_index += layer_sizes[i-1]*layer_sizes[i] + layer_sizes[i];\n    }\n    n->nInputs = input_size;\n    n->nOutputs = layer_sizes[num_layers-1];\n    n->outputs = n->layers[layers-1].outputs;\n    return n;\n}\n\n\nvoid network_load_parameters(Network* n, int parameter_size, const double* parameters) {\n    assert(parameter_size == n->parameter_size);\n    //Copy the parameters to network (copying not always needed?)\n    //memcpy(n->parameters, parameters, parameter_size*sizeof(*parameters));\n    for(int i = 0; i < parameter_size; ++i)\n        n->parameters[i] = parameters[i];\n}\nvoid network_compute(Network* n, int size, const double* input) {\n    assert(size == n->nInputs);\n    layer_compute_activation(&n->layers[0], input);\n    for(int i = 1; i < n->nLayers; ++i) {\n        layer_compute_activation(&n->layers[i], n->layers[i-1].outputs);\n    }\n}\n\nvoid network_destroy(Network* n) {\n    for(int i = 0; i < n->nLayers; ++i) {\n        layer_free(&n->layers[i]);\n    }\n    free(n->layers);\n    free(n->parameters);\n    free(n);\n}\n\nconst double* network_output(Network* n, int* output_size) {\n    if(output_size != NULL)\n        *output_size = n->nOutputs;\n    return n->outputs;\n}\n\n/*Armadillo interface*/\nvoid network_load_parameters(Network* n, const arma::vec& parameters) {\n    network_load_parameters(n, parameters.n_rows, parameters.memptr());\n}\nvoid network_compute(Network* n, const arma::vec& input) {\n    network_compute(n, input.n_rows, input.memptr());\n}\nvoid network_output(Network* n, arma::vec& output) {\n    output = arma::colvec(n->outputs, n->nOutputs, true);\n}\n\n/*Backpropagation specifics*/\n\nvoid layer_update_parameters(Layer* l, const double* input, double* delta, double rate) {\n    //Outer product\n    for(int j = 0; j < l->nInputs; ++j) {\n        double input_ = input[j];\n        for(int k = 0; k < l->nOutputs; ++k) {\n            l->weights[j*l->nOutputs + k] += rate*input_*delta[k];\n        }\n    }\n    for(int k = 0; k < l->nOutputs; ++k)\n        l->biases[k] += rate*delta[k];\n}\n\n/*Function overwrites layer_j_activation_prime with new delta*/\nvoid layer_backpropagate_delta( Layer* kl, Layer* jl, double* layer_j_activation_prime, double* delta) \n{\n    double* new_delta = layer_j_activation_prime;\n    for(int j = 0; j < jl->nOutputs; ++j) {\n        for(int k = 0; k < kl->nOutputs; ++k) {\n            new_delta[j] *= delta[k]*kl->weights[j*kl->nOutputs + k];\n        }\n    }\n}\n\nvoid network_backpropagate(Network* n, const double* inputs, const double* result, double rate) {\n\n    double** temps = (double**)calloc(n->nLayers, sizeof (double*));\n    for(int i = 0; i < n->nLayers; ++i)\n        temps[i] = (double*)calloc(n->layers[i].nOutputs, sizeof(double));\n    //Feedforward and take the z_s (values before activation) into memory\n    layer_compute_z(&n->layers[0], inputs);\n    memcpy(temps[0], n->layers[0].outputs, n->layers[0].nOutputs*sizeof(double));\n    n->layers[0].activation(n->layers[0].nOutputs, n->layers[0].outputs);\n    for(int i = 1; i < n->nLayers; ++i) {\n        Layer* l = &n->layers[i];\n        layer_compute_z(l, n->layers[i-1].outputs);\n        memcpy(temps[i], l->outputs, l->nOutputs*sizeof(double));\n        l->activation(l->nOutputs, l->outputs);\n    }\n    \n    //Backpropagate, at each step one z is replaced with backpropagated delta\n    Layer* last = &n->layers[n->nLayers-1];\n    last->activation_prime(last->nOutputs, temps[n->nLayers-1]);\n    for(int i = 0; i < last->nOutputs; ++i)\n        temps[n->nLayers-1][i] *= (result[i] - n->outputs[i]);\n    for(int i = n->nLayers-1; i > 0; --i) {\n        Layer* k = &n->layers[i];\n        Layer* j = &n->layers[i-1];\n        layer_update_parameters(k, j->outputs, temps[i], rate);\n        j->activation_prime(j->nOutputs, temps[i-1]);\n        layer_backpropagate_delta(k, j, temps[i-1], temps[i]);\n    }\n    layer_update_parameters(&n->layers[0], inputs, temps[0], rate);\n    \n    for(int i = 0; i < n->nLayers; ++i)\n        free(temps[i]);\n    free(temps);\n}\n\n\nvoid relu_kernel(int size, double* data) {\n    for(int i = 0; i < size; ++i) {\n        data[i] = std::max(0.0, data[i]);\n    }\n}\n\nvoid relu_prime_kernel(int size, double* data) {\n    for(int i = 0; i < size; ++i) {\n        data[i] = data[i] < 0.0 ? 0.0 : 1.0;\n    }\n}\n\nvoid lin_kernel(int size, double* data) {\n    return;\n}\n\nvoid lin_prime_kernel(int size, double* data) {\n    for(int i = 0; i < size; ++i)\n        data[i] = 1.0;\n}\n\nvoid sigmoid_kernel(int size, double* data) {\n    for(int i = 0; i< size; ++i) {\n        data[i] = 1.0/(1.0 + exp(-data[i]));\n    }\n}\n\nvoid sigmoid_prime_kernel(int size, double* data) {\n    for(int i = 0; i < size; ++i) {\n        double f = 1.0/(1.0 + exp(-data[i]));\n        data[i] = f*(1-f);\n    }\n}\n\nvoid tanh_kernel(int size, double* data) {\n    for(int i = 0; i < size; ++i) {\n        data[i] = tanh(data[i]);\n    }\n}\n\nvoid tanh_prime_kernel(int size, double* data) {\n    for(int i = 0; i < size; ++i) {\n        data[i] = 1.0 - pow(tanh(data[i]), 2);\n    }\n}", "meta": {"hexsha": "2f7ceded0e600bd541d912c41702ae0ea78ac70d", "size": 8058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/network.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/network.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/network.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.2893617021, "max_line_length": 103, "alphanum_fraction": 0.6342764954, "num_tokens": 2342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5019537449816552}}
{"text": "#include <string>\n#include <iostream>\n#include <stdio.h>\n#include <time.h>\n#include <string.h>\n#include <boost/algorithm/string/trim.hpp>\n//#include <regex>\n\nauto constexpr iso8601_min_year = 1583;\nauto constexpr max_month = 12;\nauto constexpr max_day = 31;\n\nbool check_days_in_manth(int day, int month, int year)\n{\n    static constexpr auto year_fact = 400;\n    static constexpr auto year_dis_fact = 100;\n    static constexpr auto year_dis_fact2 = 4;\n    static const int months[] = {\n        31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31\n    };\n    if (months[month] >= day) {\n        return true;\n    } else {\n        if (month == 1) {\n            if (year % year_fact == 0 || (year % year_dis_fact != 0 && year % year_dis_fact2 == 0)) {\n                return day <= months[month]+1;\n            }\n        }\n    }\n    return false;\n}\n\nbool check_values(int year, int month, int day)\n{\n\n    if (year < iso8601_min_year) {\n        return false;\n    }\n\n    if (month < 1 || month > max_month) {\n        return false;\n    } else {\n        --month;\n    }\n    if (day < 1 || day > max_day) {\n        return false;\n    }\n    return check_days_in_manth(day, month, year);\n}\n\nbool none_iso8601_match(const char* str) {\n    int year = -1, month = -1, day = -1;\n    // in this case we don't know the actual order..\n    static const char* patterns[] = {\n        \"%d/%d/%d\", \"%d:%d:%d\"\n    };\n    for (auto i = std::begin(patterns); i != std::end(patterns); i++) {\n        auto r = sscanf(str, *i, &year, &month, &day);\n        if (r == 3) {\n            if (month > max_month && day <= max_month) {\n                std::swap(month, day);\n            }\n            if (check_values(year, month, day)) {\n                return true;\n            }\n        }\n    }\n    return false;\n}\n\nbool iso8601_submatch(const char* str)\n{\n    int year = -1, month = -1, day = -1;\n    auto r = sscanf(str, \"%4d%2d%2d\", &year, &month, &day);\n    switch (r) {\n        case 1:\n            return false;\n        case 2:\n            return check_values(year, month, 0);\n        case 3:\n            return check_values(year, month, day);\n        default:\n            return false;\n    }\n}\n\nbool iso8601_match(const char* str) \n{\n    int year = -1, month = -1, day = -1;\n    auto r = sscanf(str, \"%4d-%2d-%2d\", &year, &month, &day);  // ISO format yyyy-mm-dd\n    switch (r) {\n        case 1: // only year, this may mean we have no delimiter\n            return iso8601_submatch(str);\n        case 2:\n            return check_values(year, month, 0);\n        case 3:\n            return check_values(year, month, day);\n        default:\n            return iso8601_submatch(str);\n    }\n}\n#if 0\nbool regex_iso8601(const std::string& str) {\n    static const std::regex matcher(\"^(\\\\d{4}(?:(?:(?:\\\\-)?(?:00[1-9]|0[1-9][0-9]|[1-2][0-9][0-9]|3[0-5][0-9]|36[0-6]))?|(?:(?:\\\\-)?(?:1[0-2]|0[1-9]))?|(?:(?:\\\\-)?(?:1[0-2]|0[1-9])(?:\\\\-)?(?:0[1-9]|[12][0-9]|3[01]))?|(?:(?:\\\\-)?W(?:0[1-9]|[1-4][0-9]5[0-3]))?|(?:(?:\\\\-)?W(?:0[1-9]|[1-4][0-9]5[0-3])(?:\\\\-)?[1-7])?)?)$\");\n    if (std::regex_search(str, matcher)) {\n        return true;\n    }\n    return false;\n}\n#endif\nbool is_date(std::string input) {\n    boost::algorithm::trim(input);    \n    if (input.empty()) {\n        return false;\n    }\n    return iso8601_match(input.c_str()) || none_iso8601_match(input.c_str());\n}\n\n", "meta": {"hexsha": "14a00f587ce4af0e44ba90344c36d4a27de3b91e", "size": 3326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/apps/csv_info/src/test_date.cpp", "max_stars_repo_name": "boazsade/machine_learinig_models", "max_stars_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/apps/csv_info/src/test_date.cpp", "max_issues_repo_name": "boazsade/machine_learinig_models", "max_issues_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/apps/csv_info/src/test_date.cpp", "max_forks_repo_name": "boazsade/machine_learinig_models", "max_forks_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_forks_repo_licenses": ["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.9495798319, "max_line_length": 320, "alphanum_fraction": 0.520444979, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5019537449816552}}
{"text": "\n#include <vector>\n#include <map>\n#include <iostream>\n#include <chrono>\n#include <cassert>\n\n#include <boost/optional.hpp>\n#include <boost/variant.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/hawick_circuits.hpp>\n\n#include <Eigen/Core>  // ensure that this is Tensorflow's version of Eigen, not libIGL's -- see CMakeLists for info\n\n#include <igl/opengl/glfw/Viewer.h>\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Triangle_2.h>\n#include <CGAL/intersections.h>\n#include <CGAL/Barycentric_coordinates_2/Triangle_coordinates_2.h>\n\n#include <gurobi_c++.h>\n\n#include \"mesh_intersections.h\"\n\n\n//#define CHECK_FOR_CYCLES  // if set, use boost::hawick_cycles to check the face-graph is acyclic\n//#define CHECK_LINEAR_SOLVE  // if set, check the result of re-solving the linear system defined by the active constraints using Eigen\n//#define RETURN_LINEAR_SOLVE  // if set, return that Eigen solution instead of the Gurobi solution\n//#define VISUALISE_ACTIVE_CONSTRAINTS  // if set, display active constraint set after solving with gurobi\n//#define MEASURE_TIMES  // if set, measure and report cumulative times for building the graph / LP and solving\n\n\ntypedef CGAL::Epeck CGALKernel;\ntypedef CGAL::Point_2<CGALKernel> Point2D;\ntypedef CGAL::Line_2<CGALKernel> Line2D;\ntypedef CGAL::Segment_2<CGALKernel> Segment2D;\ntypedef CGAL::Triangle_2<CGALKernel> Triangle2D;\n\n\nstruct IntersectionVertex\n{\n\tfloat first_z, second_z;\n\tstd::array<float, 3> first_barycentric, second_barycentric;  // corresponding to near/far triangle respectively\n\n\tvoid flip() {\n\t\tstd::swap(first_z, second_z);\n\t\tstd::swap(first_barycentric, second_barycentric);\n\t}\n};\n\nfloat interpolate_barycentric(std::array<float, 3> const &barycentric, float const v0, float const v1, float const v2)\n{\n\treturn v0 * barycentric[0] + v1 * barycentric[1] + v2 * barycentric[2];\n}\n\nfloat get_interpolated_z(std::array<float, 3> const &barycentric, Eigen::Vector3i const &face, Eigen::MatrixXf const &projected_vertices)\n{\n\tauto const z_v0 = projected_vertices(face[0], 2);\n\tauto const z_v1 = projected_vertices(face[1], 2);\n\tauto const z_v2 = projected_vertices(face[2], 2);\n\n\treturn interpolate_barycentric(barycentric, z_v0, z_v1, z_v2);\n}\n\nEigen::Vector3f get_position_from_barycentric(std::array<float, 3> const &barycentric, Eigen::Vector3i const &face, Eigen::MatrixXf const &vertices)\n{\n\tEigen::Vector3f const v0 = vertices.row(face[0]);\n\tEigen::Vector3f const v1 = vertices.row(face[1]);\n\tEigen::Vector3f const v2 = vertices.row(face[2]);\n\treturn v0 * barycentric[0] + v1 * barycentric[1] + v2 * barycentric[2];\n}\n\ntypedef boost::adjacency_list<\n    boost::vecS,\n    boost::vecS,\n    boost::directedS,\n    boost::no_property,\n    std::vector<IntersectionVertex>\n> FaceGraph;\n\ntypedef std::array<float, 3> Barycentric;\n\nstruct TriangleVertex\n{\n\tEigen::Vector3f position;\n\tPoint2D const &position_cgal;\n\tunsigned char index_in_face;\n\n\tBarycentric get_barycentric() const {\n\t\tBarycentric result {0.f, 0.f, 0.f};\n\t\tresult[index_in_face] = 1.f;\n\t\treturn result;\n\t}\n\n\tEigen::Vector2d position_2d() const {\n\t\treturn Eigen::Vector2d(position[0], position[1]);\n\t}\n};\n\ntypedef std::array<TriangleVertex, 3> TriangleVertices;\n\nstruct BBox\n{\n\tfloat min_x, min_y, max_x, max_y;\n\n\texplicit BBox(TriangleVertices const &vertices) :\n\t\tmin_x(std::min(std::min(vertices[0].position[0], vertices[1].position[0]), vertices[2].position[0])),\n\t\tmin_y(std::min(std::min(vertices[0].position[1], vertices[1].position[1]), vertices[2].position[1])),\n\t\tmax_x(std::max(std::max(vertices[0].position[0], vertices[1].position[0]), vertices[2].position[0])),\n\t\tmax_y(std::max(std::max(vertices[0].position[1], vertices[1].position[1]), vertices[2].position[1]))\n\t{\n\t}\n\n\tbool almost_intersects(BBox const &other, float const epsilon) const {\n\t\tif (std::max(min_x, other.min_x) > std::min(max_x, other.max_x) + epsilon)\n\t\t\treturn false;\n\t\telse if (std::max(min_y, other.min_y) > std::min(max_y, other.max_y) + epsilon)\n\t\t\treturn false;\n\t\telse\n\t\t\treturn true;\n\t}\n};\n\nstd::vector<IntersectionVertex> get_intersection_vertices(Eigen::Vector3i const &first_face, TriangleVertices const &first_vertices, Eigen::Vector3i const &second_face, TriangleVertices const &second_vertices)\n{\n\t// Note that if the triangles touch at an edge or vertex, this function *may* return a one-/two-element\n\t// intersection, or *may* return an empty intersection; non-trivial intersections are always returned\n\n\t// Find the set of vertices that are shared by the two triangles; record the index-in-face for each triangle for each such vertex\n\tstd::vector<std::pair<int, int>> shared_vertex_index_indices;\n\tshared_vertex_index_indices.reserve(3);\n\tfor (int first_vertex_index_index = 0; first_vertex_index_index < 3; ++first_vertex_index_index) {\n\t\tfor (int second_vertex_index_index = 0; second_vertex_index_index < 3; ++second_vertex_index_index) {\n\t\t\tif (first_face[first_vertex_index_index] == second_face[second_vertex_index_index]) {\n\t\t\t\tshared_vertex_index_indices.emplace_back(first_vertex_index_index, second_vertex_index_index);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Find the complement of the above set wrt each triangle, i.e. the sets of non-shared vertex-indices-in-face for each triangle\n\tstd::vector<int> first_nonshared_vertex_index_indices, second_nonshared_vertex_index_indices;\n\tfirst_nonshared_vertex_index_indices.reserve(3 - shared_vertex_index_indices.size());\n\tsecond_nonshared_vertex_index_indices.reserve(3 - shared_vertex_index_indices.size());\n\tfor (int vertex_index_index = 0; vertex_index_index < 3; ++vertex_index_index) {\n\t\tbool shared_in_first = false, shared_in_second = false;\n\t\tfor (auto [shared_index_index_in_first, shared_index_index_in_second] : shared_vertex_index_indices) {\n\t\t\tif (shared_index_index_in_first == vertex_index_index)\n\t\t\t\tshared_in_first = true;\n\t\t\tif (shared_index_index_in_second == vertex_index_index)\n\t\t\t\tshared_in_second = true;\n\t\t}\n\t\tif (!shared_in_first)\n\t\t\tfirst_nonshared_vertex_index_indices.push_back(vertex_index_index);\n\t\tif (!shared_in_second)\n\t\t\tsecond_nonshared_vertex_index_indices.push_back(vertex_index_index);\n\t}\n\tassert(shared_vertex_index_indices.size() + first_nonshared_vertex_index_indices.size() == 3);\n\tassert(shared_vertex_index_indices.size() + second_nonshared_vertex_index_indices.size() == 3);\n\n\tauto const triangle_to_cgal = [] (TriangleVertices const &triangle_vertices) {\n\t\treturn Triangle2D{triangle_vertices[0].position_cgal, triangle_vertices[1].position_cgal, triangle_vertices[2].position_cgal};\n\t};\n\n\tauto const get_barycentric = [] (Eigen::Vector2d const &point_d, TriangleVertices const &triangle_vertices) {\n\t\tauto const cross2 = [] (Eigen::Vector2d const &first, Eigen::Vector2d const&second) {\n\t\t\treturn first[0] * second[1] - first[1] * second[0];\n\t\t};\n\t\tEigen::Vector2d const v0 = triangle_vertices[1].position_2d() - triangle_vertices[0].position_2d();\n\t\tEigen::Vector2d const v1 = triangle_vertices[2].position_2d() - triangle_vertices[0].position_2d();\n\t\tEigen::Vector2d const v2 = point_d - triangle_vertices[0].position_2d();\n\t\tauto const denominator = cross2(v0, v1);\n\t\tauto const v = cross2(v2, v1) / denominator;\n\t\tauto const w = cross2(v0, v2) / denominator;\n\t\tauto const u = 1.f - v - w;\n\t\tfloat const bounds_epsilon = 1.e-3;\n\t\tassert(-bounds_epsilon <= u && u <= 1.f + bounds_epsilon);\n\t\tassert(-bounds_epsilon <= v && v <= 1.f + bounds_epsilon);\n\t\tassert(-bounds_epsilon <= w && w <= 1.f + bounds_epsilon);\n\t\treturn Barycentric{static_cast<float>(u), static_cast<float>(v), static_cast<float>(w)};\n\t};\n\n\tauto const get_barycentric_and_z = [&] (Eigen::Vector2d const &point_d, TriangleVertices const &triangle_vertices) {\n\t\tauto const barycentric = get_barycentric(point_d, triangle_vertices);\n\t\tauto const z = interpolate_barycentric(barycentric, triangle_vertices[0].position[2], triangle_vertices[1].position[2], triangle_vertices[2].position[2]);\n\t\treturn std::make_pair(barycentric, z);\n\t};\n\n\tauto const with_barycentrics_and_zs = [&] (Point2D const &point) {\n\t\tEigen::Vector2d const point_d(CGAL::to_double(point[0]), CGAL::to_double(point[1]));\n\t\tauto const [first_barycentric, first_z] = get_barycentric_and_z(point_d, first_vertices);\n\t\tauto const [second_barycentric, second_z] = get_barycentric_and_z(point_d, second_vertices);\n\t\treturn IntersectionVertex{first_z, second_z, first_barycentric, second_barycentric};\n\t};\n\n\tif (shared_vertex_index_indices.size() == 0 || shared_vertex_index_indices.size() == 1) {\n\n\t\tauto const first_triangle = triangle_to_cgal(first_vertices);\n\t\tauto const second_triangle = triangle_to_cgal(second_vertices);\n\n\t\tauto const intersection = CGAL::intersection(first_triangle, second_triangle);\n\t\tif (intersection) {\n\t\t\tif (auto point = boost::get<Point2D>(&*intersection))\n\t\t\t\treturn {};\n\t\t\telse if (auto segment = boost::get<Segment2D>(&*intersection))\n\t\t\t\treturn {};\n\t\t\telse if (auto triangle = boost::get<Triangle2D>(&*intersection))\n\t\t\t\treturn {\n\t\t\t\t\twith_barycentrics_and_zs(triangle->vertex(0)),\n\t\t\t\t\twith_barycentrics_and_zs(triangle->vertex(1)),\n\t\t\t\t\twith_barycentrics_and_zs(triangle->vertex(2))\n\t\t\t\t};\n\t\t\telse if (auto poly = boost::get<std::vector<Point2D>>(&*intersection)) {\n\t\t\t\tstd::vector<IntersectionVertex> result;\n\t\t\t\tresult.reserve(poly->size());\n\t\t\t\tfor (auto const &point : *poly)\n\t\t\t\t\tresult.push_back(with_barycentrics_and_zs(point));\n\t\t\t\treturn result;\n\t\t\t} else\n\t\t\t\tassert(false);\n\t\t} else {\n\t\t\treturn {};\n\t\t}\n\n\t} else if (shared_vertex_index_indices.size() == 2) {\n\n\t\tSegment2D const shared_edge{\n\t\t\tfirst_vertices[shared_vertex_index_indices[0].first].position_cgal,\n\t\t\tfirst_vertices[shared_vertex_index_indices[1].first].position_cgal\n\t\t};\n\t\tPoint2D const first_unshared_vertex = first_vertices[first_nonshared_vertex_index_indices[0]].position_cgal;\n\t\tPoint2D const second_unshared_vertex = second_vertices[second_nonshared_vertex_index_indices[0]].position_cgal;\n\n\t\tLine2D const shared_line = shared_edge.supporting_line();\n\t\tif (shared_line.oriented_side(first_unshared_vertex) == shared_line.oriented_side(second_unshared_vertex)) {\n\n\t\t\t// There is an area intersection; could have two edges crossing, or could have one non-shared vertex inside the other triangle\n\n\t\t\tstd::array<IntersectionVertex, 2> const shared_edge_intersection_vertices {\n\t\t\t\tIntersectionVertex{\n\t\t\t\t\tfirst_vertices[shared_vertex_index_indices[0].first].position[2],\n\t\t\t\t\tsecond_vertices[shared_vertex_index_indices[0].second].position[2],\n\t\t\t\t\tfirst_vertices[shared_vertex_index_indices[0].first].get_barycentric(),\n\t\t\t\t\tsecond_vertices[shared_vertex_index_indices[0].second].get_barycentric()\n\t\t\t\t},\n\t\t\t\tIntersectionVertex{\n\t\t\t\t\tfirst_vertices[shared_vertex_index_indices[1].first].position[2],\n\t\t\t\t\tsecond_vertices[shared_vertex_index_indices[1].second].position[2],\n\t\t\t\t\tfirst_vertices[shared_vertex_index_indices[1].first].get_barycentric(),\n\t\t\t\t\tsecond_vertices[shared_vertex_index_indices[1].second].get_barycentric()\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tauto const first_triangle = triangle_to_cgal(first_vertices);\n\t\t\tauto const second_triangle = triangle_to_cgal(second_vertices);\n\n\t\t\tif (!first_triangle.has_on_unbounded_side(second_unshared_vertex)) {  // not-unbounded accounts for possibility of lying exactly on the boundary\n\t\t\t\tauto const [first_barycentric, first_z] = get_barycentric_and_z(\n\t\t\t\t\tsecond_vertices[second_nonshared_vertex_index_indices[0]].position_2d(),\n\t\t\t\t\tfirst_vertices\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tshared_edge_intersection_vertices[0],\n\t\t\t\t\tshared_edge_intersection_vertices[1],\n\t\t\t\t\tIntersectionVertex{\n\t\t\t\t\t\tfirst_z,\n\t\t\t\t\t\tsecond_vertices[second_nonshared_vertex_index_indices[0]].position[2],\n\t\t\t\t\t\tfirst_barycentric,\n\t\t\t\t\t\tsecond_vertices[second_nonshared_vertex_index_indices[0]].get_barycentric()\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!second_triangle.has_on_unbounded_side(first_unshared_vertex)) {\n\t\t\t\tauto const [second_barycentric, second_z] = get_barycentric_and_z(\n\t\t\t\t\tfirst_vertices[first_nonshared_vertex_index_indices[0]].position_2d(),\n\t\t\t\t\tsecond_vertices\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tshared_edge_intersection_vertices[0],\n\t\t\t\t\tshared_edge_intersection_vertices[1],\n\t\t\t\t\tIntersectionVertex{\n\t\t\t\t\t\tfirst_vertices[first_nonshared_vertex_index_indices[0]].position[2],\n\t\t\t\t\t\tsecond_z,\n\t\t\t\t\t\tfirst_vertices[first_nonshared_vertex_index_indices[0]].get_barycentric(),\n\t\t\t\t\t\tsecond_barycentric\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tstd::array<Segment2D, 2> const first_nonshared_edges {\n\t\t\t\tSegment2D{shared_edge[0], first_unshared_vertex},\n\t\t\t\tSegment2D{shared_edge[1], first_unshared_vertex}\n\t\t\t};\n\t\t\tstd::array<Segment2D, 2> const second_nonshared_edges {\n\t\t\t\tSegment2D{shared_edge[0], second_unshared_vertex},\n\t\t\t\tSegment2D{shared_edge[1], second_unshared_vertex}\n\t\t\t};\n\n\t\t\tauto const check_edge_intersection = [&] (int const first_nonshared_edge_index, int const second_nonshared_edge_index) -> std::optional<std::vector<IntersectionVertex>> {\n\t\t\t\tif (auto const intersection = CGAL::intersection(\n\t\t\t\t\tfirst_nonshared_edges[first_nonshared_edge_index],\n\t\t\t\t\tsecond_nonshared_edges[second_nonshared_edge_index]\n\t\t\t\t)) {\n\t\t\t\t\tif (auto const point = boost::get<Point2D>(&*intersection))\n\t\t\t\t\t\treturn {{shared_edge_intersection_vertices[0], shared_edge_intersection_vertices[1], with_barycentrics_and_zs(*point)}};\n\t\t\t\t\telse\n\t\t\t\t\t\tassert(false);  // this implies the two segments are collinear, in which case the not-on-unbounded-side check above would have passed\n\t\t\t\t} else {\n\t\t\t\t\treturn std::nullopt;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tif (auto const result = check_edge_intersection(0, 1))\n\t\t\t\treturn *result;\n\t\t\tif (auto const result = check_edge_intersection(1, 0))\n\t\t\t\treturn *result;\n\n\t\t\tassert(false);  // ...as the above cases should be exhaustive\n\n\t\t} else {\n\t\t\t// If the two non-shared vertices lie on different sides of the shared edge, then the triangles touch at the edge, but do not intersect\n\t\t\treturn {};\n\t\t}\n\n\t} else {\n\t\tassert(false);\n\t}\n}\n\nFaceGraph get_face_graph_hybrid(Eigen::MatrixXf const &projected_vertices, Eigen::MatrixXi const &faces, Eigen::ArrayXf const &offset_magnitudes)\n{\n\t// This returns a directed graph, whose nodes correspond to faces. Edges represent 'possible bumpings', i.e.\n\t// existence of an edge F --> G implies that F and G overlap in projection, and F is 'further back' than G, hence\n\t// may bump into it when moved 'forward'\n\t// It is 'hybrid' because it uses fast float32 pre-checks to avoid expensive infinite-precision CGAL intersection tests\n\n\tfloat const box_intersection_epsilon = 1.e-2f;\n\n\tFaceGraph graph(faces.rows());\n\n\tstd::vector<Point2D> projected_vertices_cgal;\n\tprojected_vertices_cgal.reserve(projected_vertices.size());\n\tfor (int vertex_index = 0; vertex_index < projected_vertices.rows(); ++vertex_index)\n\t\tprojected_vertices_cgal.push_back(Point2D{projected_vertices(vertex_index, 0), projected_vertices(vertex_index, 1)});\n\n\tfor (int first_face_index = 0; first_face_index < faces.rows(); ++first_face_index) {\n\n\t\tEigen::Vector3i const first_face = faces.row(first_face_index);\n\t\tTriangleVertices const first_face_vertices {\n\t\t\tTriangleVertex{projected_vertices.row(first_face[0]), projected_vertices_cgal[first_face[0]], 0},\n\t\t\tTriangleVertex{projected_vertices.row(first_face[1]), projected_vertices_cgal[first_face[1]], 1},\n\t\t\tTriangleVertex{projected_vertices.row(first_face[2]), projected_vertices_cgal[first_face[2]], 2}\n\t\t};\n\t\tBBox const first_bbox(first_face_vertices);\n\n\t\tfor (int second_face_index = 0; second_face_index < first_face_index; ++second_face_index) {\n\n\t\t\tEigen::Vector3i const second_face = faces.row(second_face_index);\n\t\t\tTriangleVertices const second_face_vertices {\n\t\t\t\tTriangleVertex{projected_vertices.row(second_face[0]), projected_vertices_cgal[second_face[0]], 0},\n\t\t\t\tTriangleVertex{projected_vertices.row(second_face[1]), projected_vertices_cgal[second_face[1]], 1},\n\t\t\t\tTriangleVertex{projected_vertices.row(second_face[2]), projected_vertices_cgal[second_face[2]], 2}\n\t\t\t};\n\t\t\tBBox const second_bbox(second_face_vertices);\n\n\t\t\tif (!first_bbox.almost_intersects(second_bbox, box_intersection_epsilon))\n\t\t\t\tcontinue;\n\n\t\t\tauto const intersection_vertices = get_intersection_vertices(first_face, first_face_vertices, second_face, second_face_vertices);\n\t\t\tif (intersection_vertices.size() < 3)\n\t\t\t\tcontinue;\n\n\t\t\t// This is necessary as some overlapping triangles may share one or two vertices, which then have zero z-difference\n\t\t\tfloat largest_magnitude_second_z_minus_first_z = 0.f;\n\t\t\tfor (auto const &intersection_vertex : intersection_vertices) {\n\t\t\t\tauto const z_difference = intersection_vertex.second_z - intersection_vertex.first_z;\n\t\t\t\tif (std::abs(z_difference) > std::abs(largest_magnitude_second_z_minus_first_z))\n\t\t\t\t\tlargest_magnitude_second_z_minus_first_z = z_difference;\n\t\t\t}\n\t\t\tassert(largest_magnitude_second_z_minus_first_z != 0.f);\n\t\t\tbool const first_nearer_than_second = largest_magnitude_second_z_minus_first_z > 0.f;\n\t\t\tfloat const epsilon = 1.e-4;\n\t\t\tfor (auto const &intersection_vertex : intersection_vertices) {\n\t\t\t\tauto const z_difference = intersection_vertex.second_z - intersection_vertex.first_z;\n\t\t\t\tassert(std::abs(z_difference) < epsilon || (z_difference > 0) == first_nearer_than_second);\n\t\t\t}\n\n\t\t\tif (first_nearer_than_second)\n\t\t\t\tboost::add_edge(first_face_index, second_face_index, intersection_vertices, graph);\n\t\t\telse {\n\t\t\t\tauto flipped_intersection_vertices = intersection_vertices;\n\t\t\t\tfor (auto &intersection_vertex : flipped_intersection_vertices)\n\t\t\t\t\tintersection_vertex.flip();\n\t\t\t\tboost::add_edge(second_face_index, first_face_index, flipped_intersection_vertices, graph);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn graph;\n}\n\nvoid visualise_ordering(std::vector<int> const &face_ordering, Eigen::MatrixXf const &projected_vertices, Eigen::MatrixXi const &faces)\n{\n\tEigen::MatrixXd vertices_d = projected_vertices.cast<double>();\n\tfor (int vertex_index = 0; vertex_index < vertices_d.rows(); ++vertex_index) {\n\t\tif (vertices_d(vertex_index, 2) < -0.01)\n\t\t\tvertices_d(vertex_index, 2) -= 0.1;\n\t\telse if (vertices_d(vertex_index, 2) > 0.01)\n\t\t\tvertices_d(vertex_index, 2) += 0.1;\n\t}\n\n\tigl::opengl::glfw::Viewer viewer;\n\tviewer.data().set_mesh(vertices_d, faces);\n\tviewer.data().set_face_based(true);\n\n\tEigen::MatrixXd face_colours(faces.rows(), 3);\n\tface_colours.setConstant(0.5);\n\tviewer.data().set_colors(face_colours);\n\n\tint current_index_in_ordering = 0;\n\tviewer.callback_key_down = [&] (igl::opengl::glfw::Viewer &viewer, unsigned int key, int mod) {\n\t\tif (key == GLFW_KEY_RIGHT && current_index_in_ordering < face_ordering.size() - 1) {\n\t\t\tface_colours.row(face_ordering[current_index_in_ordering]).setConstant(1.);\n\t\t\t++current_index_in_ordering;\n\t\t\tviewer.data().set_colors(face_colours);\n\t\t\treturn true;\n\t\t} else if (key == GLFW_KEY_LEFT && current_index_in_ordering > 0) {\n\t\t\t--current_index_in_ordering;\n\t\t\tface_colours.row(face_ordering[current_index_in_ordering]).setConstant(0.5);\n\t\t\tviewer.data().set_colors(face_colours);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t};\n\n\tviewer.launch();\n}\n\nvoid visualise_active_constraints(Eigen::MatrixXf const &vertices, Eigen::MatrixXi const &faces, std::vector<int> const &active_vertex_indices, std::vector<std::pair<int, int>> const &active_face_indices)\n{\n\tigl::opengl::glfw::Viewer viewer;\n\tviewer.data().set_mesh(vertices.cast<double>(), faces);\n\tviewer.data().set_face_based(true);\n\n\tEigen::MatrixXd face_colours(faces.rows(), 3);\n\tface_colours.setConstant(0.5);\n\tfor (auto const &[near_face_index, far_face_index] : active_face_indices) {\n\t\tface_colours(near_face_index, 0) = 1.;\n\t\tface_colours(far_face_index, 2) = 1.;\n\t}\n\tviewer.data().set_colors(face_colours);\n\n\tEigen::MatrixXd point_colours(vertices.rows(), 3);\n\tpoint_colours.setZero();\n\tpoint_colours.col(0).setConstant(1.);\n\tfor (auto const &active_vertex_index : active_vertex_indices)\n\t\tpoint_colours.row(active_vertex_index) = Eigen::Vector3d(0., 1., 0.);\n\tviewer.data().set_points(vertices.cast<double>(), point_colours);\n\tviewer.data().point_size = 10;\n\n\tviewer.launch();\n}\n\nfloat const buffer_distance = .05f;  // this is how close triangles are allowed to come to another before they collide\nfloat const initial_z_difference_tolerance = 1.e-4f;  // we allow faces to have passed each other by this far without asserting\n\nstd::pair<std::pair<int, int>, std::pair<int, int>> get_segment_vertex_indices(\n\tEigen::Vector3i const &near_face,\n\tEigen::Vector3i const &far_face,\n\tIntersectionVertex const &intersection_vertex\n) {\n\t// This returns the indices of the vertices at the ends of the two lines that intersect at the given intersection-vertex\n\n\t// If we're at a corner of the near/far face, then return the two edges meeting there\n\n\tfloat const corner_epsilon = 1.e-5;\n\tfloat const edge_epsilon = 1.e-4;\n\n\tauto const check_corners = [&] (\n\t\tstd::array<float, 3> const &barycentric,\n\t\tEigen::Vector3i const &face\n\t) -> std::optional<std::pair<std::pair<int, int>, std::pair<int, int>>> {\n\t\tif (barycentric[0] >= 1. - corner_epsilon)\n\t\t\treturn { {{face[0], face[1]}, {face[0], face[2]}} };\n\t\telse if (barycentric[1] >= 1. - corner_epsilon)\n\t\t\treturn { {{face[1], face[0]}, {face[1], face[2]}} };\n\t\telse if (barycentric[2] >= 1. - corner_epsilon)\n\t\t\treturn { {{face[2], face[0]}, {face[2], face[1]}} };\n\t\telse\n\t\t\treturn {};\n\t};\n\n\tif (auto corner_result = check_corners(intersection_vertex.first_barycentric, near_face))\n\t\treturn *corner_result;\n\tif (auto corner_result = check_corners(intersection_vertex.second_barycentric, far_face))\n\t\treturn *corner_result;\n\n\t// We're not at a corner of either triangle, but we are (necessarily) on an edge of each, and there are zero\n\t// barycentrics (one per triangle) opposite these edges\n\n\tauto const get_edge_opposite_zero_barycentric = [&] (std::array<float, 3> const &barycentric, Eigen::Vector3i const &face) -> std::pair<int, int> {\n\t\tif (barycentric[0] <= edge_epsilon) {\n\t\t\tassert(barycentric[1] > edge_epsilon && barycentric[2] > edge_epsilon);\n\t\t\treturn {face[1], face[2]};\n\t\t}\n\t\telse if (barycentric[1] <= edge_epsilon) {\n\t\t\tassert(barycentric[0] > edge_epsilon && barycentric[2] > edge_epsilon);\n\t\t\treturn {face[0], face[2]};\n\t\t}\n\t\telse if (barycentric[2] <= edge_epsilon) {\n\t\t\tassert(barycentric[0] > edge_epsilon && barycentric[1] > edge_epsilon);\n\t\t\treturn {face[0], face[1]};\n\t\t} else {\n\t\t\tstd::ostringstream message_ss;\n\t\t\tmessage_ss << \"get_segment_vertex_indices::get_edge_opposite_zero_barycentric did not find any barycentric less than \" << edge_epsilon\n\t\t\t\t<< \"; values: \" << barycentric[0] << \", \" << barycentric[1] << \", \" << barycentric[2];\n\t\t\tthrow std::runtime_error(message_ss.str());\n\t\t}\n\t};\n\n\treturn {\n\t\tget_edge_opposite_zero_barycentric(intersection_vertex.first_barycentric, near_face),\n\t\tget_edge_opposite_zero_barycentric(intersection_vertex.second_barycentric, far_face)\n\t};\n}\n\nOffsetMagnitudesAndActiveConstraints solve_for_offsets_gurobi(\n\tEigen::MatrixXf const &projected_vertices,\n\tEigen::MatrixXi const &faces,\n\tFaceGraph const &face_graph,\n\tEigen::ArrayXf const &initial_offset_magnitudes\n) {\n\tstatic GRBEnv gurobi_env;\n\n#ifdef MEASURE_TIMES\n\tauto start = std::chrono::high_resolution_clock::now();\n#endif\n\n\tGRBModel model(gurobi_env);\n#ifdef NDEBUG\n\tmodel.set(GRB_IntParam_LogToConsole, 0);\n#endif\n\tmodel.set(GRB_IntParam_Threads, 1);\n\tmodel.set(GRB_DoubleParam_TimeLimit, 30.);\n\tassert(model.get(GRB_IntAttr_ModelSense) ==  GRB_MINIMIZE);\n\n\tstd::vector<GRBVar> offset_variables;\n\tstd::vector<GRBConstr> offset_greater_than_initial_constraints;\n\toffset_variables.reserve(projected_vertices.rows());\n\tfor (int vertex_index = 0; vertex_index < projected_vertices.rows(); ++vertex_index) {\n\t\t// This defines the objective as the (unweighted) sum of all offset-magnitudes, and the lower-bound on each as the original value\n\t\toffset_variables.push_back(model.addVar(0., std::numeric_limits<double>::infinity(), 1., GRB_CONTINUOUS));\n\t\toffset_greater_than_initial_constraints.push_back(model.addConstr(offset_variables.back() >= initial_offset_magnitudes[vertex_index]));\n\t}\n\n#ifdef CHECK_LINEAR_SOLVE\n\t// This linear system has one row per constraint, and one column per variable (i.e. the offset-magnitudes)\n\t// We first collect all constraints (which do not have an equality solution), then later extract the active ones\n\t// Here, we construct the LHS and RHS explicitly, but for tensorflow, we return a set of face/vertex indices\n\t// describing how to construct them\n\tstd::vector<Eigen::VectorXf> all_push_constraint_linear_matrix_rows;\n\tstd::vector<float> all_push_constraint_linear_vector_elements;\n#endif\n\n\tstd::vector<std::tuple<GRBConstr, int, int, IntersectionVertex const *>> face_pushing_constraints_and_relevant_face_indices_and_intersection_vertex_ptrs;\n\tfor (auto [edge_it, end_edge_it] = boost::edges(face_graph); edge_it != end_edge_it; ++edge_it) {\n\t\tint const near_face_index = boost::source(*edge_it, face_graph);\n\t\tint const far_face_index = boost::target(*edge_it, face_graph);\n\t\tEigen::Vector3i const near_face = faces.row(near_face_index);\n\t\tEigen::Vector3i const far_face = faces.row(far_face_index);\n\t\tfor (auto const &intersection_vertex : face_graph[*edge_it]) {\n\n\t\t\tauto const near_initial_z = get_interpolated_z(\n\t\t\t\tintersection_vertex.first_barycentric,\n\t\t\t\tnear_face,\n\t\t\t\tprojected_vertices\n\t\t\t);\n\t\t\tauto const far_initial_z = get_interpolated_z(\n\t\t\t\tintersection_vertex.second_barycentric,\n\t\t\t\tfar_face,\n\t\t\t\tprojected_vertices\n\t\t\t);\n\n\t\t\tauto const initial_z_difference = far_initial_z - near_initial_z;\n\t\t\tassert(initial_z_difference >= -initial_z_difference_tolerance);\n\t\t\tauto const required_z_difference = std::min(initial_z_difference, buffer_distance);\n\n\t\t\tEigen::VectorXf linear_matrix_row;\n\t\t\tlinear_matrix_row.setZero(projected_vertices.rows());\n\t\t\tfor (int index_in_face = 0; index_in_face < 3; ++index_in_face) {\n\t\t\t\tlinear_matrix_row[near_face[index_in_face]] += intersection_vertex.first_barycentric[index_in_face];\n\t\t\t\tlinear_matrix_row[far_face[index_in_face]] -= intersection_vertex.second_barycentric[index_in_face];\n\t\t\t}\n\t\t\tfloat const linear_vector_element = far_initial_z - near_initial_z - required_z_difference;\n\n\t\t\tif (linear_matrix_row.cwiseAbs().maxCoeff() < 1.e-9 && linear_vector_element == 0.) {\n\t\t\t\t// Such a trivial constraint arises when the intersection-vertex is exactly at a vertex shared between the near and far faces\n\t\t\t\tcontinue;\n\t\t\t} else if (linear_matrix_row.cwiseAbs().maxCoeff() < 1.e-5) {\n\t\t\t\tstd::cout << \"input constraint max-abs-coeff = \" << linear_matrix_row.cwiseAbs().maxCoeff() << \"; rhs = \" << linear_vector_element << std::endl;\n\t\t\t}\n\n#ifdef CHECK_LINEAR_SOLVE\n\t\t\tall_push_constraint_linear_matrix_rows.push_back(linear_matrix_row);\n\t\t\tall_push_constraint_linear_vector_elements.push_back(linear_vector_element);\n#endif\n\n\t\t\tGRBLinExpr const near_offset_magnitude =\n\t\t\t\tintersection_vertex.first_barycentric[0] * offset_variables[near_face[0]] +\n\t\t\t\tintersection_vertex.first_barycentric[1] * offset_variables[near_face[1]] +\n\t\t\t\tintersection_vertex.first_barycentric[2] * offset_variables[near_face[2]];\n\t\t\tGRBLinExpr const far_offset_magnitude =\n\t\t\t\tintersection_vertex.second_barycentric[0] * offset_variables[far_face[0]] +\n\t\t\t\tintersection_vertex.second_barycentric[1] * offset_variables[far_face[1]] +\n\t\t\t\tintersection_vertex.second_barycentric[2] * offset_variables[far_face[2]];\n\n\t\t\tGRBConstr const constraint = model.addConstr(near_initial_z + near_offset_magnitude <= far_initial_z + far_offset_magnitude - required_z_difference);\n\t\t\tface_pushing_constraints_and_relevant_face_indices_and_intersection_vertex_ptrs.push_back({constraint, near_face_index, far_face_index, &intersection_vertex});\n\t\t}\n\t}\n\n#ifdef MEASURE_TIMES\n\tstatic long long total_build_ms = 0;\n\tauto const total_build_ms_incremented = __sync_add_and_fetch(&total_build_ms, std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start).count());\n\tstd::cout << \"gurobi build -> total \" << total_build_ms_incremented << \"ms\\n\";\n\tstart = std::chrono::high_resolution_clock::now();\n#endif\n\n\tmodel.optimize();\n\tauto const optimisation_status = model.get(GRB_IntAttr_Status);\n\tif (optimisation_status != GRB_OPTIMAL) {\n\t\tstd::cout << \"WARNING: optimisation not solved; status = \" << optimisation_status << \"; assuming all lower-bound constraints active\" << std::endl;\n\t\tstd::vector<int> all_vertex_indices(projected_vertices.rows());\n\t\tstd::iota(all_vertex_indices.begin(), all_vertex_indices.end(), 0);\n\t\treturn {initial_offset_magnitudes, all_vertex_indices, {}, {}};\n\t}\n\n#ifdef MEASURE_TIMES\n\tstatic long long total_solve_ms = 0;\n\tauto const total_solve_ms_incremented = __sync_add_and_fetch(&total_solve_ms, std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start).count());\n\tstd::cout << \"gurobi solve -> total \" << total_solve_ms_incremented << \"ms\\n\";\n#endif\n\n#ifdef CHECK_LINEAR_SOLVE\n\tEigen::MatrixXf active_constraint_linear_matrix(0, projected_vertices.rows());\n\tEigen::VectorXf active_constraint_linear_vector(0, 1);\n\tauto append_constraint_to_linear_system = [&] (Eigen::VectorXf const &lhs, float const rhs) {\n\t\tactive_constraint_linear_matrix.conservativeResize(active_constraint_linear_matrix.rows() + 1, active_constraint_linear_matrix.cols());\n\t\tactive_constraint_linear_vector.conservativeResize(active_constraint_linear_vector.rows() + 1);\n\t\tactive_constraint_linear_matrix.row(active_constraint_linear_matrix.rows() - 1) = lhs;\n\t\tactive_constraint_linear_vector[active_constraint_linear_vector.rows() - 1] = rhs;\n\t};\n#endif\n\n\tdouble const slack_epsilon = 1.e-5;  // note that Gurobi's default feasibility tolerance is 1.e-6\n\n\tstd::unique_ptr<double const> const gurobi_offset_magnitudes_ptr(model.get(GRB_DoubleAttr_X, &offset_variables[0], offset_variables.size()));\n\tEigen::VectorXf const gurobi_solved_offset_magnitudes = Eigen::Map<Eigen::VectorXd const>(gurobi_offset_magnitudes_ptr.get(), offset_variables.size()).cast<float>();\n\n\tstd::vector<int> active_bound_constraint_vertex_indices;\n\tfor (int vertex_index = 0; vertex_index < projected_vertices.rows(); ++vertex_index) {\n\t\tdouble const slack = offset_greater_than_initial_constraints[vertex_index].get(GRB_DoubleAttr_Slack);\n\t\tassert(slack <= slack_epsilon);  // these slack variables are negative as the constraints are greater-than\n\t\tif (slack >= -slack_epsilon) {\n\t\t\tactive_bound_constraint_vertex_indices.push_back(vertex_index);\n#ifdef CHECK_LINEAR_SOLVE\n\t\t\tEigen::VectorXf linear_matrix_row;\n\t\t\tlinear_matrix_row.setZero(projected_vertices.rows());\n\t\t\tlinear_matrix_row[vertex_index] = 1.f;\n\t\t\tappend_constraint_to_linear_system(linear_matrix_row, initial_offset_magnitudes[vertex_index]);\n#endif\n\t\t}\n\t}\n\n\tstd::vector<std::pair<int, int>> active_push_constraint_face_indices;  // pairs of near-face, far-face\n\tstd::vector<std::pair<std::pair<int, int>, std::pair<int, int>>> active_push_constraint_vertex_indices;  // identifies the IntersectionVertex as the intersection point of two edges; pairs of first-edge, second-edge -- each a pair of start-vertex, end-vertex\n\tfor (int constraint_index = 0; constraint_index < face_pushing_constraints_and_relevant_face_indices_and_intersection_vertex_ptrs.size(); ++constraint_index) {\n\t\tauto const &[constraint, near_face_index, far_face_index, intersection_vertex_ptr] = face_pushing_constraints_and_relevant_face_indices_and_intersection_vertex_ptrs[constraint_index];\n\t\tdouble const slack = constraint.get(GRB_DoubleAttr_Slack);\n\t\tassert(slack >= -slack_epsilon);  // these slack variables are positive as the constraints are less-than\n\t\tif (slack <= slack_epsilon) {\n\t\t\tactive_push_constraint_face_indices.push_back({near_face_index, far_face_index});\n\t\t\tactive_push_constraint_vertex_indices.push_back(get_segment_vertex_indices(faces.row(near_face_index), faces.row(far_face_index), *intersection_vertex_ptr));\n#ifdef CHECK_LINEAR_SOLVE\n\t\t\tappend_constraint_to_linear_system(\n\t\t\t\tall_push_constraint_linear_matrix_rows[constraint_index],\n\t\t\t\tall_push_constraint_linear_vector_elements[constraint_index]\n\t\t\t);\n#endif\n\t\t}\n\t}\n#ifndef NDEBUG\n\tstd::cout <<\n\t\tactive_bound_constraint_vertex_indices.size() << \"/\" << offset_greater_than_initial_constraints.size() << \" active lower-bound constraints; \" <<\n\t\tactive_push_constraint_face_indices.size() << \"/\" << face_pushing_constraints_and_relevant_face_indices_and_intersection_vertex_ptrs.size() << \" active face-push constraints; \" <<\n\t\tprojected_vertices.rows() << \" variables\" <<\n\t\tstd::endl;\n#endif\n\tassert(active_push_constraint_face_indices.size() == active_push_constraint_vertex_indices.size());\n\tint const active_constraint_count = active_bound_constraint_vertex_indices.size() + active_push_constraint_face_indices.size();\n\tassert(active_constraint_count >= projected_vertices.rows());\n\n#ifdef VISUALISE_ACTIVE_CONSTRAINTS\n\tvisualise_active_constraints(projected_vertices, faces, active_bound_constraint_vertex_indices, active_push_constraint_face_indices);\n#endif\n\n#ifdef CHECK_LINEAR_SOLVE\n\n\tauto const final_row_max = active_constraint_linear_matrix.row(active_constraint_linear_matrix.rows() - 1).cwiseAbs().maxCoeff();\n\tif (final_row_max < 1.e-2)\n\t\tstd::cout << \"final row max abs = \" << final_row_max << std::endl;\n\n\tassert(active_constraint_linear_matrix.rows() == active_constraint_linear_vector.rows() && active_constraint_linear_matrix.rows() == active_constraint_count);\n\tfloat const lambda = 1.e-12f;\n\tEigen::VectorXf const eigen_solved_offset_magnitudes = (\n\t\tactive_constraint_linear_matrix.transpose() * active_constraint_linear_matrix + Eigen::MatrixXf::Identity(active_constraint_linear_matrix.cols(), active_constraint_linear_matrix.cols()) * lambda\n\t).llt().solve(active_constraint_linear_matrix.transpose() * active_constraint_linear_vector);\n\tfor (int vertex_index = 0; vertex_index < projected_vertices.rows(); ++vertex_index) {\n\t\tfloat const gurobi_value = offset_variables[vertex_index].get(GRB_DoubleAttr_X);\n\t\tfloat const eigen_value = eigen_solved_offset_magnitudes[vertex_index];\n\t\tif (std::abs(gurobi_value - eigen_value) > 1.e-2) {\n\t\t\tstd::cout << \"vertex #\" << vertex_index << \": gurobi = \" << gurobi_value << \", eigen = \" << eigen_value;\n\t\t\tif (gurobi_value != 0.)\n\t\t\t\tstd::cout << \"; relative error = \" << std::abs(eigen_value - gurobi_value) / std::abs(gurobi_value) * 100 << \"%\";\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t}\n\n\tfor (int active_constraint_index = 0; active_constraint_index < active_constraint_count; ++active_constraint_index) {\n\t\tauto const lhs_eigen = active_constraint_linear_matrix.row(active_constraint_index).dot(eigen_solved_offset_magnitudes);\n\t\tauto const lhs_gurobi = active_constraint_linear_matrix.row(active_constraint_index).dot(gurobi_solved_offset_magnitudes);\n\t\tauto const rhs = active_constraint_linear_vector[active_constraint_index];\n\t\tif (std::abs(lhs_eigen - rhs) > 1.e-4) {\n\t\t\tstd::cout << \"active constraint #\" << active_constraint_index << \": lhs = \" << lhs_eigen << \", rhs = \" << rhs;\n\t\t\tif (rhs != 0.)\n\t\t\t\tstd::cout << \"; relative error = \" << std::abs(lhs_eigen - rhs) / rhs * 100 << \"%\";\n\t\t\tstd::cout << \" (gurobi lhs = \" << lhs_gurobi << \")\" << std::endl;\n\t\t}\n\t}\n\n#endif\n\n#ifdef RETURN_LINEAR_SOLVE\n\n\treturn {\n\t\teigen_solved_offset_magnitudes.array(),\n\t\tactive_bound_constraint_vertex_indices,\n\t\tactive_push_constraint_face_indices,\n\t\tactive_push_constraint_vertex_indices\n\t};\n\n#else\n\n\treturn {\n\t\tgurobi_solved_offset_magnitudes.array(),\n\t\tactive_bound_constraint_vertex_indices,\n\t\tactive_push_constraint_face_indices,\n\t\tactive_push_constraint_vertex_indices\n\t};\n\n#endif\n}\n\nstruct CycleVisitor {\n\ttemplate<class Cycle>\n\tvoid cycle(Cycle const &, FaceGraph const &) {\n\t\tassert(false);\n\t}\n};\n\nOffsetMagnitudesAndActiveConstraints get_pushed_offset_magnitudes_and_active_constraints(Eigen::MatrixXf const &projected_vertices, Eigen::MatrixXi const &faces, Eigen::ArrayXf const &initial_offset_magnitudes)\n{\n\tassert(projected_vertices.rows() == initial_offset_magnitudes.size());\n\tfor (int vertex_index = 0; vertex_index < projected_vertices.rows(); ++vertex_index)\n\t\tassert(initial_offset_magnitudes[vertex_index] >= 0.f);\n\n#ifdef MEASURE_TIMES\n\tauto start = std::chrono::high_resolution_clock::now();\n#endif\n\n\tauto const face_graph = get_face_graph_hybrid(projected_vertices, faces, initial_offset_magnitudes);\n\n#ifdef MEASURE_TIMES\n\tstatic long long total_ms = 0;\n\tauto const total_ms_incremented = __sync_add_and_fetch(&total_ms, std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start).count());\n\tstd::cout << \"intersections & graph construction -> total \" << total_ms_incremented << \"ms\\n\";\n#endif\n\n#ifdef CHECK_FOR_CYCLES\n\tboost::hawick_circuits(face_graph, CycleVisitor());\n#endif\n\n\treturn solve_for_offsets_gurobi(projected_vertices, faces, face_graph,  initial_offset_magnitudes);\n}\n\n", "meta": {"hexsha": "0f78e7264bb228b1e45572022971067225fdb62f", "size": 36653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mesh_intersections/mesh_intersections.cpp", "max_stars_repo_name": "pmh47/textured-mesh-gen", "max_stars_repo_head_hexsha": "2448b4df496068339d4e1ce400119cfef06432f0", "max_stars_repo_licenses": ["Artistic-1.0-cl8"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T20:34:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T06:56:25.000Z", "max_issues_repo_path": "src/mesh_intersections/mesh_intersections.cpp", "max_issues_repo_name": "pmh47/textured-mesh-gen", "max_issues_repo_head_hexsha": "2448b4df496068339d4e1ce400119cfef06432f0", "max_issues_repo_licenses": ["Artistic-1.0-cl8"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-06-23T09:07:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T03:04:51.000Z", "max_forks_repo_path": "src/mesh_intersections/mesh_intersections.cpp", "max_forks_repo_name": "pmh47/textured-mesh-gen", "max_forks_repo_head_hexsha": "2448b4df496068339d4e1ce400119cfef06432f0", "max_forks_repo_licenses": ["Artistic-1.0-cl8"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-24T03:43:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T15:33:06.000Z", "avg_line_length": 45.9887076537, "max_line_length": 258, "alphanum_fraction": 0.7638392492, "num_tokens": 9331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.501953739929662}}
{"text": "/**  \n * Copyright (c) 2009 Carnegie Mellon University. \n *     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,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n *      http://www.graphlab.ml.cmu.edu\n *\n */\n\n\n/**\n * \\file\n * \n * This file contains an implementation of the weighted-ALS matrix factorization\n * algorithm. As described in:  Collaborative Filtering for Implicit Feedback Datasets Hu, Y.; Koren, Y.; Volinsky, C. IEEE International Conference on Data Mining (ICDM 2008), IEEE (2008). \n *\n * Code written By Danny Bickson, based on code by Joey Gonzalez\n */\n\n#include <Eigen/Dense>\n\n#include <boost/config/warning_disable.hpp>\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_stl.hpp>\n\n\n\n\n// This file defines the serialization code for the eigen types.\n#include \"eigen_serialization.hpp\"\n\n#include <graphlab.hpp>\n#include <graphlab/util/stl_util.hpp>\n#include \"stats.hpp\"\n\n#include <graphlab/macros_def.hpp>\n\nconst int SAFE_NEG_OFFSET = 2; //add 2 to negative node id\n//to prevent -0 and -1 which arenot allowed\n\n/**\n * \\brief We use the eigen library's vector type to represent\n * mathematical vectors.\n */\ntypedef Eigen::VectorXd vec_type;\n\n/**\n * \\brief We use the eigen library's matrix type to represent\n * matrices.\n */\ntypedef Eigen::MatrixXd mat_type;\n\n\n/**\n * \\brief Remap the target id of each edge into a different id space\n * than the source id.\n */\nbool REMAP_TARGET = true;\n\n\n\n/** \n * \\ingroup toolkit_matrix_factorization\n *\n * \\brief the vertex data type which contains the latent factor.\n *\n * Each row and each column in the matrix corresponds to a different\n * vertex in the ALS graph.  Associated with each vertex is a factor\n * (vector) of latent parameters that represent that vertex.  The goal\n * of the ALS algorithm is to find the values for these latent\n * parameters such that the non-zero entries in the matrix can be\n * predicted by taking the dot product of the row and column factors.\n */\nstruct vertex_data {\n  /**\n   * \\brief A shared \"constant\" that specifies the number of latent\n   * values to use.\n   */\n  static size_t NLATENT;\n  /** \\brief The number of times this vertex has been updated. */\n  uint32_t nupdates;\n  /** \\brief The most recent L1 change in the factor value */\n  float residual; //! how much the latent value has changed\n  /** \\brief The latent factor for this vertex */\n  vec_type factor;\n  /** \n   * \\brief Simple default constructor which randomizes the vertex\n   *  data \n   */\n  vertex_data() : nupdates(0), residual(1) { randomize(); } \n  /** \\brief Randomizes the latent factor */\n  void randomize() { factor.resize(NLATENT); factor.setRandom(); }\n  /** \\brief Save the vertex data to a binary archive */\n  void save(graphlab::oarchive& arc) const { \n    arc << nupdates << residual << factor;        \n  }\n  /** \\brief Load the vertex data from a binary archive */\n  void load(graphlab::iarchive& arc) { \n    arc >> nupdates >> residual >> factor;\n  }\n}; // end of vertex data\n\n\nsize_t vertex_data::NLATENT = 20;\n\n/**\n * \\brief The edge data stores the entry in the matrix.\n *\n * In addition the edge data also stores the most recent error estimate.\n */\nstruct edge_data : public graphlab::IS_POD_TYPE {\n  /**\n   * \\brief The type of data on the edge;\n   *\n   * \\li *Train:* the observed value is correct and used in training\n   * \\li *Validate:* the observed value is correct but not used in training\n   * \\li *Predict:* The observed value is not correct and should not be\n   *        used in training.\n   */\n  enum data_role_type { TRAIN, VALIDATE, PREDICT  };\n\n  /** \\brief the observed value for the edge */\n  float obs;\n\n  /** \\brief the weight or time of the observation */\n  float weight; \n  \n  /** \\brief The train/validation/test designation of the edge */\n  data_role_type role;\n\n  /** \\brief basic initialization */\n  edge_data(float obs = 0, data_role_type role = TRAIN, float weight = 1) :\n    obs(obs), weight(weight), role(role) { }\n\n}; // end of edge data\n\n\n/**\n * \\brief The graph type is defined in terms of the vertex and edge\n * data.\n */ \ntypedef graphlab::distributed_graph<vertex_data, edge_data> graph_type;\n\n#include \"implicit.hpp\"\n\nstats_info count_edges(const graph_type::edge_type & edge){\n  stats_info ret;\n\n  if (edge.data().role == edge_data::TRAIN)\n     ret.training_edges = 1;\n  else if (edge.data().role == edge_data::VALIDATE)\n     ret.validation_edges = 1;\n  ret.max_user = (size_t)edge.source().id();\n  ret.max_item = (size_t)edge.target().id();\n  return ret;\n}\n\n\n\n/**\n * \\brief Given a vertex and an edge return the other vertex in the\n * edge.\n */\ninline graph_type::vertex_type\nget_other_vertex(graph_type::edge_type& edge, \n                 const graph_type::vertex_type& vertex) {\n  return vertex.id() == edge.source().id()? edge.target() : edge.source();\n}; // end of get_other_vertex\n\n\n\n\n/**\n * \\brief The gather type used to construct XtX and Xty needed for the ALS\n * update\n *\n * To compute the ALS update we need to compute the sum of \n * \\code\n *  sum: XtX = nbr.factor.transpose() * nbr.factor \n *  sum: Xy  = nbr.factor * edge.obs\n * \\endcode\n * For each of the neighbors of a vertex. \n *\n * To do this in the Gather-Apply-Scatter model the gather function\n * computes and returns a pair consisting of XtX and Xy which are then\n * added. The gather type represents that tuple and provides the\n * necessary gather_type::operator+= operation.\n *\n */\nclass gather_type {\npublic:\n  /**\n   * \\brief Stores the current sum of nbr.factor.transpose() *\n   * nbr.factor\n   */\n  mat_type XtX;\n\n  /**\n   * \\brief Stores the current sum of nbr.factor * edge.obs\n   */\n  vec_type Xy;\n\n  /**\n   * \\brief Stores the weight of this edge\n   */\n  float weight;\n\n  /** \\brief basic default constructor */\n  gather_type() { }\n\n  /**\n   * \\brief This constructor computes XtX and Xy and stores the result\n   * in XtX and Xy\n   */\n  gather_type(const vec_type& X, const double y, const float weight) :\n    XtX(X.size(), X.size()), Xy(X.size()) {\n    XtX.triangularView<Eigen::Upper>() = X * X.transpose() * weight;\n    Xy = X * y * weight;\n  } // end of constructor for gather type\n\n  /** \\brief Save the values to a binary archive */\n  void save(graphlab::oarchive& arc) const { arc << XtX << Xy << weight; }\n\n  /** \\brief Read the values from a binary archive */\n  void load(graphlab::iarchive& arc) { arc >> XtX >> Xy >> weight; }  \n\n  /** \n   * \\brief Computes XtX += other.XtX and Xy += other.Xy updating this\n   * tuples value\n   */\n  gather_type& operator+=(const gather_type& other) {\n    if(other.Xy.size() == 0) {\n      ASSERT_EQ(other.XtX.rows(), 0);\n      ASSERT_EQ(other.XtX.cols(), 0);\n    } else {\n      if(Xy.size() == 0) {\n        ASSERT_EQ(XtX.rows(), 0); \n        ASSERT_EQ(XtX.cols(), 0);\n        XtX = other.XtX; Xy = other.Xy;\n      } else {\n        XtX.triangularView<Eigen::Upper>() += other.XtX;  \n        Xy += other.Xy;\n      }\n    }\n    return *this;\n  } // end of operator+=\n\n}; // end of gather type\n\n\n\n/**\n * \\brief WALS vertex program implements the alternating least squares\n * algorithm in the Gather-Apply-Scatter abstraction.\n *\n * The ALS update treats adjacent vertices (rows or columns) as \"X\"\n * (independent) values and the edges (matrix entries) as observed \"y\"\n * (dependent) values and then updates the current vertex value as a\n * weight \"w\" such that:\n *\n *    y = X * w + noise\n *\n * This is accomplished using the following equation:\n *\n *    w = inv(X' * X) * (X * y)\n *\n * We implement this in the Gather-Apply-Scatter model by:\n *\n *  1) Gather: returns the tuple (X' * X, X * y)\n *     Sum:   (aX' * aX, aX * ay) + (bX' * bX, bX * by) = \n *                 (aX' * aX + bX' * bX, aX * ay + bX * by)\n *\n *  2) Apply: Solves  inv(X' * X) * (X * y)\n *\n *  3) Scatter: schedules the update of adjacent vertices if this\n *      vertex has changed sufficiently and the edge is not well\n *      predicted.\n *\n * \n */ \nclass als_vertex_program : \n  public graphlab::ivertex_program<graph_type, gather_type,\n                                   graphlab::messages::sum_priority>,\n  public graphlab::IS_POD_TYPE {\npublic:\n  /** The convergence tolerance */\n  static double TOLERANCE;\n  static double LAMBDA;\n  static size_t MAX_UPDATES;\n  static double MAXVAL;\n  static double MINVAL;\n \n  /** The set of edges to gather along */\n  edge_dir_type gather_edges(icontext_type& context, \n                             const vertex_type& vertex) const { \n    return graphlab::ALL_EDGES; \n  }; // end of gather_edges \n\n  /** The gather function computes XtX and Xy */\n  gather_type gather(icontext_type& context, const vertex_type& vertex, \n                     edge_type& edge) const {\n    if(edge.data().role == edge_data::TRAIN) {\n      const vertex_type other_vertex = get_other_vertex(edge, vertex);\n      return gather_type(other_vertex.data().factor, edge.data().obs, edge.data().weight);\n    } else return gather_type();\n  } // end of gather function\n\n  /** apply collects the sum of XtX and Xy */\n  void apply(icontext_type& context, vertex_type& vertex,\n             const gather_type& sum) {\n    // Get and reset the vertex data\n    vertex_data& vdata = vertex.data(); \n    // Determine the number of neighbors.  Each vertex has only in or\n    // out edges depending on which side of the graph it is located\n    if(sum.Xy.size() == 0) { vdata.residual = 0; ++vdata.nupdates; return; }\n    mat_type XtX = sum.XtX;\n    vec_type Xy = sum.Xy;\n    // Add regularization\n    for(int i = 0; i < XtX.rows(); ++i) XtX(i,i) += LAMBDA; // /nneighbors;\n    // Solve the least squares problem using eigen ----------------------------\n    const vec_type old_factor = vdata.factor;\n    vdata.factor = XtX.selfadjointView<Eigen::Upper>().ldlt().solve(Xy);\n    // Compute the residual change in the factor factor -----------------------\n    vdata.residual = (vdata.factor - old_factor).cwiseAbs().sum() / XtX.rows();\n    ++vdata.nupdates;\n  } // end of apply\n  \n  /** The edges to scatter along */\n  edge_dir_type scatter_edges(icontext_type& context,\n                              const vertex_type& vertex) const { \n    return graphlab::ALL_EDGES; \n  }; // end of scatter edges\n\n  /** Scatter reschedules neighbors */  \n  void scatter(icontext_type& context, const vertex_type& vertex, \n               edge_type& edge) const {\n    edge_data& edata = edge.data();\n    if(edata.role == edge_data::TRAIN) {\n      const vertex_type other_vertex = get_other_vertex(edge, vertex);\n      const vertex_data& vdata = vertex.data();\n      const vertex_data& other_vdata = other_vertex.data();\n      const double pred = vdata.factor.dot(other_vdata.factor);\n      const float error = std::fabs(edata.obs - pred);\n      const double priority = (error * vdata.residual); \n      // Reschedule neighbors ------------------------------------------------\n      if( priority > TOLERANCE && other_vdata.nupdates < MAX_UPDATES) \n        context.signal(other_vertex, priority);\n    }\n  } // end of scatter function\n\n\n  /**\n   * \\brief Signal all vertices on one side of the bipartite graph\n   */\n  static graphlab::empty signal_left(icontext_type& context,\n                                     const vertex_type& vertex) {\n    if(vertex.num_out_edges() > 0) context.signal(vertex);\n    return graphlab::empty();\n  } // end of signal_left \n\n}; // end of als vertex program\n\n\n\n/**\n * \\brief The graph loader function is a line parser used for\n * distributed graph construction.\n */\ninline bool graph_loader(graph_type& graph, \n                         const std::string& filename,\n                         const std::string& line) {\n  ASSERT_FALSE(line.empty()); \n  namespace qi = boost::spirit::qi;\n  namespace ascii = boost::spirit::ascii;\n  namespace phoenix = boost::phoenix;\n  // Determine the role of the data\n  edge_data::data_role_type role = edge_data::TRAIN;\n  if(boost::ends_with(filename,\".validate\")) role = edge_data::VALIDATE;\n  else if(boost::ends_with(filename, \".predict\")) role = edge_data::PREDICT;\n  // Parse the line\n  std::stringstream strm(line);\n  graph_type::vertex_id_type source_id(-1), target_id(-1);\n  float obs(0), weight(1);\n  strm >> source_id >> target_id;\n\n  // for test files (.predict) no need to read the actual rating value.\n  if(role == edge_data::TRAIN || role == edge_data::VALIDATE){\n    strm >> obs >> weight;\n    if (obs < als_vertex_program::MINVAL || obs > als_vertex_program::MAXVAL)\n      logstream(LOG_FATAL)<<\"Rating values should be between \" << als_vertex_program::MINVAL << \" and \" << als_vertex_program::MAXVAL << \". Got value: \" << obs << \" [ user: \" << source_id << \" to item: \" <<target_id << \" ] \" << std::endl; \n  }\n  target_id = -(graphlab::vertex_id_type(target_id + SAFE_NEG_OFFSET));\n                          \n  // Create an edge and add it to the graph\n  graph.add_edge(source_id, target_id, edge_data(obs, role, weight)); \n  return true; // successful load\n}\n\n\n\n// end of graph_loader\n\n\n\n/**\n * \\brief Given an edge compute the error associated with that edge\n */\ndouble extract_l2_error(const graph_type::edge_type & edge) {\n  double pred = \n    edge.source().data().factor.dot(edge.target().data().factor);\n  pred = std::min(als_vertex_program::MAXVAL, pred);\n  pred = std::max(als_vertex_program::MINVAL, pred);\n  return (edge.data().obs - pred) * (edge.data().obs - pred) * edge.data().weight;\n} // end of extract_l2_error\n\n\n\ndouble als_vertex_program::TOLERANCE = 1e-3;\ndouble als_vertex_program::LAMBDA = 0.01;\nsize_t als_vertex_program::MAX_UPDATES = -1;\ndouble als_vertex_program::MAXVAL = 1e+100;\ndouble als_vertex_program::MINVAL = -1e+100;\n\n\n\n\n\n/**\n * \\brief The error aggregator is used to accumulate the overal\n * prediction error.\n *\n * The error aggregator is itself a \"reduction type\" and contains the\n * two static methods \"map\" and \"finalize\" which operate on\n * error_aggregators and are used by the engine.add_edge_aggregator\n * api.\n */\nstruct error_aggregator : public graphlab::IS_POD_TYPE {\n  typedef als_vertex_program::icontext_type icontext_type;\n  typedef graph_type::edge_type edge_type;\n  double train_error, validation_error;\n  error_aggregator() : \n    train_error(0), validation_error(0){ }\n  error_aggregator& operator+=(const error_aggregator& other) {\n    train_error += other.train_error;\n    validation_error += other.validation_error;\n    return *this;\n  }\n  static error_aggregator map(icontext_type& context, const graph_type::edge_type& edge) {\n    error_aggregator agg;\n    if(edge.data().role == edge_data::TRAIN) {\n      agg.train_error = extract_l2_error(edge); \n    } else if(edge.data().role == edge_data::VALIDATE) {\n      agg.validation_error = extract_l2_error(edge); \n    }\n    return agg;\n  }\n  static void finalize(icontext_type& context, const error_aggregator& agg) {\n    const double train_error = std::sqrt(agg.train_error / info.training_edges);\n    context.cout() << context.elapsed_seconds() << \"\\t\" << train_error;\n    if(info.validation_edges > 0) {\n      const double validation_error = \n        std::sqrt(agg.validation_error / info.validation_edges);\n      context.cout() << \"\\t\" << validation_error; \n    }\n    context.cout() << std::endl;\n  }\n}; // end of error aggregator\n\n\n\n\n/**\n * \\brief The prediction saver is used by the graph.save routine to\n * output the final predictions back to the filesystem.\n */\nstruct prediction_saver {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  std::string save_vertex(const vertex_type& vertex) const {\n    return \"\"; //nop\n  }\n  std::string save_edge(const edge_type& edge) const {\n    if(edge.data().role == edge_data::PREDICT) {\n      std::stringstream strm;\n      const double prediction = \n        edge.source().data().factor.dot(edge.target().data().factor);\n      strm << edge.source().id() << '\\t';\n      if(REMAP_TARGET) strm << (-edge.target().id() - SAFE_NEG_OFFSET) << '\\t';\n      else strm << edge.target().id() << '\\t';\n      strm << prediction << '\\n';\n      return strm.str();\n    } else return \"\";\n  }\n}; // end of prediction_saver\n\n\nstruct linear_model_saver_U {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  /* save the linear model, using the format:\n     nodeid) factor1 factor2 ... factorNLATENT \\n\n  */\n  std::string save_vertex(const vertex_type& vertex) const {\n    if (vertex.num_out_edges() > 0){\n      std::string ret = boost::lexical_cast<std::string>(vertex.id()) + \" \";\n      for (uint i=0; i< vertex_data::NLATENT; i++)\n        ret += boost::lexical_cast<std::string>(vertex.data().factor[i]) + \" \";\n        ret += \"\\n\";\n      return ret;\n    }\n    else return \"\";\n  }\n  std::string save_edge(const edge_type& edge) const {\n    return \"\";\n  }\n}; \n\nstruct linear_model_saver_V {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  /* save the linear model, using the format:\n     nodeid) factor1 factor2 ... factorNLATENT \\n\n  */\n  std::string save_vertex(const vertex_type& vertex) const {\n    if (vertex.num_out_edges() == 0){\n      std::string ret = boost::lexical_cast<std::string>(-vertex.id()-SAFE_NEG_OFFSET) + \") \";\n      for (uint i=0; i< vertex_data::NLATENT; i++)\n        ret += boost::lexical_cast<std::string>(vertex.data().factor[i]) + \" \";\n        ret += \"\\n\";\n      return ret;\n    }\n    else return \"\";\n  }\n  std::string save_edge(const edge_type& edge) const {\n    return \"\";\n  }\n}; \n\n\n\n/**\n * \\brief The engine type used by the ALS matrix factorization\n * algorithm.\n *\n * The ALS matrix factorization algorithm currently uses the\n * synchronous engine.  However we plan to add support for alternative\n * engines in the future.\n */\ntypedef graphlab::omni_engine<als_vertex_program> engine_type;\n\nint main(int argc, char** argv) {\n  global_logger().set_log_level(LOG_INFO);\n  global_logger().set_log_to_console(true);\n\n  // Parse command line options -----------------------------------------------\n  const std::string description = \n    \"Compute the Weighted-ALS factorization of a matrix.\";\n  graphlab::command_line_options clopts(description);\n  std::string input_dir, output_dir;\n  std::string predictions;\n  size_t interval = 10;\n  std::string exec_type = \"synchronous\";\n  clopts.attach_option(\"matrix\", input_dir,\n                       \"The directory containing the matrix file\");\n  clopts.add_positional(\"matrix\");\n  clopts.attach_option(\"D\",  vertex_data::NLATENT,\n                       \"Number of latent parameters to use.\");\n  clopts.attach_option(\"max_iter\", als_vertex_program::MAX_UPDATES,\n                       \"The maxumum number of udpates allowed for a vertex\");\n  clopts.attach_option(\"lambda\", als_vertex_program::LAMBDA, \n                       \"wALS regularization weight\"); \n  clopts.attach_option(\"tol\", als_vertex_program::TOLERANCE,\n                       \"residual termination threshold\");\n  clopts.attach_option(\"maxval\", als_vertex_program::MAXVAL, \"max allowed value\");\n  clopts.attach_option(\"minval\", als_vertex_program::MINVAL, \"min allowed value\");\n  clopts.attach_option(\"interval\", interval, \n                       \"The time in seconds between error reports\");\n  clopts.attach_option(\"predictions\", predictions,\n                       \"The prefix (folder and filename) to save predictions.\");\n  clopts.attach_option(\"engine\", exec_type, \n                       \"The engine type synchronous or asynchronous\");\n  // clopts.attach_option(\"remap\", REMAP_TARGET,\n  //                      \"Renumber target vertex ids (internally) so that they\\n\" \n  //                      \"are in a different range allowing user 0 to connect to movie 0\");\n  clopts.attach_option(\"output\", output_dir,\n                       \"Output results\");\n  if(!clopts.parse(argc, argv) || input_dir == \"\") {\n    std::cout << \"Error in parsing command line arguments.\" << std::endl;\n    clopts.print_description();\n    return EXIT_FAILURE;\n  }\n\n  ///! Initialize control plain using mpi\n  graphlab::mpi_tools::init(argc, argv);\n  graphlab::distributed_control dc;\n  \n  dc.cout() << \"Loading graph.\" << std::endl;\n  graphlab::timer timer; \n  graph_type graph(dc, clopts);  \n  graph.load(input_dir, graph_loader); \n  dc.cout() << \"Loading graph. Finished in \" \n            << timer.current_time() << std::endl;\n\n  if (dc.procid() == 0) \n    add_implicit_edges4<edge_data>(implicitratingtype, graph, dc);\n  \n  dc.cout() << \"Finalizing graph.\" << std::endl;\n  timer.start();\n  graph.finalize();\n  dc.cout() << \"Finalizing graph. Finished in \" \n            << timer.current_time() << std::endl;\n\n\n  dc.cout() \n      << \"========== Graph statistics on proc \" << dc.procid() \n      << \" ===============\"\n      << \"\\n Num vertices: \" << graph.num_vertices()\n      << \"\\n Num edges: \" << graph.num_edges()\n      << \"\\n Num replica: \" << graph.num_replicas()\n      << \"\\n Replica to vertex ratio: \" \n      << float(graph.num_replicas())/graph.num_vertices()\n      << \"\\n --------------------------------------------\" \n      << \"\\n Num local own vertices: \" << graph.num_local_own_vertices()\n      << \"\\n Num local vertices: \" << graph.num_local_vertices()\n      << \"\\n Replica to own ratio: \" \n      << (float)graph.num_local_vertices()/graph.num_local_own_vertices()\n      << \"\\n Num local edges: \" << graph.num_local_edges()\n      //<< \"\\n Begin edge id: \" << graph.global_eid(0)\n      << \"\\n Edge balance ratio: \" \n      << float(graph.num_local_edges())/graph.num_edges()\n      << std::endl;\n \n  dc.cout() << \"Creating engine\" << std::endl;\n  engine_type engine(dc, graph, exec_type, clopts);\n\n  // Add error reporting to the engine\n  const bool success = engine.add_edge_aggregator<error_aggregator>\n    (\"error\", error_aggregator::map, error_aggregator::finalize) &&\n    engine.aggregate_periodic(\"error\", interval);\n  ASSERT_TRUE(success);\n  \n\n  // Signal all vertices on the vertices on the left (liberals) \n  engine.map_reduce_vertices<graphlab::empty>(als_vertex_program::signal_left);\n  info = graph.map_reduce_edges<stats_info>(count_edges);\n  dc.cout()<<\"Training edges: \" << info.training_edges << \" validation edges: \" << info.validation_edges << std::endl;\n\n \n\n  // Run the WALS ---------------------------------------------------------\n  dc.cout() << \"Running Weighted-ALS\" << std::endl;\n  timer.start();\n  engine.start();  \n\n  const double runtime = timer.current_time();\n  dc.cout() << \"----------------------------------------------------------\"\n            << std::endl\n            << \"Final Runtime (seconds):   \" << runtime \n            << std::endl\n            << \"Updates executed: \" << engine.num_updates() << std::endl\n            << \"Update Rate (updates/second): \" \n            << engine.num_updates() / runtime << std::endl;\n\n  // Compute the final training error -----------------------------------------\n  dc.cout() << \"Final error: \" << std::endl;\n  engine.aggregate_now(\"error\");\n\n  // Make predictions ---------------------------------------------------------\n  if(!predictions.empty()) {\n    std::cout << \"Saving predictions\" << std::endl;\n    const bool gzip_output = false;\n    const bool save_vertices = false;\n    const bool save_edges = true;\n    const size_t threads_per_machine = 2;\n\n    //save the predictions\n    graph.save(predictions, prediction_saver(),\n               gzip_output, save_vertices, \n               save_edges, threads_per_machine);\n    //save the linear model\n    graph.save(predictions + \".U\", linear_model_saver_U(),\n\t\tgzip_output, save_edges, save_vertices, threads_per_machine);\n    graph.save(predictions + \".V\", linear_model_saver_V(),\n\t\tgzip_output, save_edges, save_vertices, threads_per_machine);\n  \n  }\n             \n\n\n  graphlab::mpi_tools::finalize();\n  return EXIT_SUCCESS;\n} // end of main\n\n\n\n", "meta": {"hexsha": "4325d52c5c82e7e83b2321257594f6ac783f9ab3", "size": 24299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/collaborative_filtering/wals.cpp", "max_stars_repo_name": "zgdahai/graphlabapi", "max_stars_repo_head_hexsha": "7d66bbda82d4d44cded35f9438e1c9359b0ca64e", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-20T07:41:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T00:52:29.000Z", "max_issues_repo_path": "toolkits/collaborative_filtering/wals.cpp", "max_issues_repo_name": "kesinger/graphlab", "max_issues_repo_head_hexsha": "5acb39d816f33e59433e88a9d3621eb4cf7cb05e", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolkits/collaborative_filtering/wals.cpp", "max_forks_repo_name": "kesinger/graphlab", "max_forks_repo_head_hexsha": "5acb39d816f33e59433e88a9d3621eb4cf7cb05e", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-27T12:40:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T12:40:52.000Z", "avg_line_length": 34.1758087201, "max_line_length": 239, "alphanum_fraction": 0.6466521256, "num_tokens": 5994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5019537348776687}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*!\n Copyright (C) 2007 Allen Kuo\n Copyright (C) 2015 Andres Hernandez\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/*  This example shows how to fit a term structure to a set of bonds\n    using four different fitting methodologies. Though fitting is most\n    useful for large numbers of bonds with non-smooth yield tenor\n    structures, for comparison purposes, relatively smooth bond yields\n    are fit here and compared to known solutions (par coupons), or\n    results generated from the bootstrap fitting method.\n*/\n\n#include <ql/qldefines.hpp>\n#ifdef BOOST_MSVC\n#  include <ql/auto_link.hpp>\n#endif\n#include <ql/termstructures/yield/fittedbonddiscountcurve.hpp>\n#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/termstructures/yield/bondhelpers.hpp>\n#include <ql/termstructures/yield/nonlinearfittingmethods.hpp>\n#include <ql/pricingengines/bond/bondfunctions.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/simpledaycounter.hpp>\n\n#include <boost/timer.hpp>\n#include <iostream>\n#include <iomanip>\n#include <boost/make_shared.hpp>\n\n#define LENGTH(a) (sizeof(a)/sizeof(a[0]))\n\nusing namespace std;\nusing namespace QuantLib;\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib {\n    Integer sessionId() { return 0; }\n}\n#endif\n\n// par-rate approximation\nRate parRate(const YieldTermStructure& yts,\n             const std::vector<Date>& dates,\n             const DayCounter& resultDayCounter) {\n    QL_REQUIRE(dates.size() >= 2, \"at least two dates are required\");\n    Real sum = 0.0;\n    Time dt;\n    for (Size i=1; i<dates.size(); ++i) {\n        dt = resultDayCounter.yearFraction(dates[i-1], dates[i]);\n        QL_REQUIRE(dt>=0.0, \"unsorted dates\");\n        sum += yts.discount(dates[i]) * dt;\n    }\n    Real result = yts.discount(dates.front()) - yts.discount(dates.back());\n    return result/sum;\n}\n\nvoid printOutput(const std::string& tag,\n                 const boost::shared_ptr<FittedBondDiscountCurve>& curve) {\n    cout << tag << endl;\n    cout << \"reference date : \"\n         << curve->referenceDate()\n         << endl;\n    cout << \"number of iterations : \"\n         << curve->fitResults().numberOfIterations()\n         << endl\n         << endl;\n}\n\n\nint main(int, char* []) {\n\n    try {\n\n        boost::timer timer;\n\n        const Size numberOfBonds = 15;\n        Real cleanPrice[numberOfBonds];\n\n        for (Size i=0; i<numberOfBonds; i++) {\n            cleanPrice[i]=100.0;\n        }\n\n        std::vector< boost::shared_ptr<SimpleQuote> > quote;\n        for (Size i=0; i<numberOfBonds; i++) {\n            boost::shared_ptr<SimpleQuote> cp(new SimpleQuote(cleanPrice[i]));\n            quote.push_back(cp);\n        }\n\n        RelinkableHandle<Quote> quoteHandle[numberOfBonds];\n        for (Size i=0; i<numberOfBonds; i++) {\n            quoteHandle[i].linkTo(quote[i]);\n        }\n\n        Integer lengths[] = { 2, 4, 6, 8, 10, 12, 14, 16,\n                              18, 20, 22, 24, 26, 28, 30 };\n        Real coupons[] = { 0.0200, 0.0225, 0.0250, 0.0275, 0.0300,\n                           0.0325, 0.0350, 0.0375, 0.0400, 0.0425,\n                           0.0450, 0.0475, 0.0500, 0.0525, 0.0550 };\n\n        Frequency frequency = Annual;\n        DayCounter dc = SimpleDayCounter();\n        BusinessDayConvention accrualConvention = ModifiedFollowing;\n        BusinessDayConvention convention = ModifiedFollowing;\n        Real redemption = 100.0;\n\n        Calendar calendar = TARGET();\n        Date today = calendar.adjust(Date::todaysDate());\n        Date origToday = today;\n        Settings::instance().evaluationDate() = today;\n\n        // changing bondSettlementDays=3 increases calculation\n        // time of exponentialsplines fitting method\n        Natural bondSettlementDays = 0;\n        Natural curveSettlementDays = 0;\n\n        Date bondSettlementDate = calendar.advance(today, bondSettlementDays*Days);\n\n        cout << endl;\n        cout << \"Today's date: \" << today << endl;\n        cout << \"Bonds' settlement date: \" << bondSettlementDate << endl;\n        cout << \"Calculating fit for 15 bonds.....\" << endl << endl;\n\n        std::vector<boost::shared_ptr<BondHelper> > instrumentsA;\n        std::vector<boost::shared_ptr<RateHelper> > instrumentsB;\n\n        for (Size j=0; j<LENGTH(lengths); j++) {\n\n            Date maturity = calendar.advance(bondSettlementDate, lengths[j]*Years);\n\n            Schedule schedule(bondSettlementDate, maturity, Period(frequency),\n                              calendar, accrualConvention, accrualConvention,\n                              DateGeneration::Backward, false);\n\n            boost::shared_ptr<BondHelper> helperA(\n                     new FixedRateBondHelper(quoteHandle[j],\n                                             bondSettlementDays,\n                                             100.0,\n                                             schedule,\n                                             std::vector<Rate>(1,coupons[j]),\n                                             dc,\n                                             convention,\n                                             redemption));\n\n            boost::shared_ptr<RateHelper> helperB(\n                     new FixedRateBondHelper(quoteHandle[j],\n                                             bondSettlementDays,\n                                             100.0,\n                                             schedule,\n                                             std::vector<Rate>(1, coupons[j]),\n                                             dc,\n                                             convention,\n                                             redemption));\n            instrumentsA.push_back(helperA);\n            instrumentsB.push_back(helperB);\n        }\n\n\n        bool constrainAtZero = true;\n        Real tolerance = 1.0e-10;\n        Size max = 5000;\n\n        boost::shared_ptr<YieldTermStructure> ts0 (\n              new PiecewiseYieldCurve<Discount,LogLinear>(curveSettlementDays,\n                                                          calendar,\n                                                          instrumentsB,\n                                                          dc));\n\n        ExponentialSplinesFitting exponentialSplines(constrainAtZero);\n\n        boost::shared_ptr<FittedBondDiscountCurve> ts1 (\n                  new FittedBondDiscountCurve(curveSettlementDays,\n                                              calendar,\n                                              instrumentsA,\n                                              dc,\n                                              exponentialSplines,\n                                              tolerance,\n                                              max));\n\n        printOutput(\"(a) exponential splines\", ts1);\n\n\n        SimplePolynomialFitting simplePolynomial(3, constrainAtZero);\n\n        boost::shared_ptr<FittedBondDiscountCurve> ts2 (\n                    new FittedBondDiscountCurve(curveSettlementDays,\n                                                calendar,\n                                                instrumentsA,\n                                                dc,\n                                                simplePolynomial,\n                                                tolerance,\n                                                max));\n\n        printOutput(\"(b) simple polynomial\", ts2);\n\n\n        NelsonSiegelFitting nelsonSiegel;\n\n        boost::shared_ptr<FittedBondDiscountCurve> ts3 (\n                        new FittedBondDiscountCurve(curveSettlementDays,\n                                                    calendar,\n                                                    instrumentsA,\n                                                    dc,\n                                                    nelsonSiegel,\n                                                    tolerance,\n                                                    max));\n\n        printOutput(\"(c) Nelson-Siegel\", ts3);\n\n\n        // a cubic bspline curve with 11 knot points, implies\n        // n=6 (constrained problem) basis functions\n\n        Time knots[] =  { -30.0, -20.0,  0.0,  5.0, 10.0, 15.0,\n                           20.0,  25.0, 30.0, 40.0, 50.0 };\n\n        std::vector<Time> knotVector;\n        for (Size i=0; i< LENGTH(knots); i++) {\n            knotVector.push_back(knots[i]);\n        }\n\n        CubicBSplinesFitting cubicBSplines(knotVector, constrainAtZero);\n\n        boost::shared_ptr<FittedBondDiscountCurve> ts4 (\n                       new FittedBondDiscountCurve(curveSettlementDays,\n                                                   calendar,\n                                                   instrumentsA,\n                                                   dc,\n                                                   cubicBSplines,\n                                                   tolerance,\n                                                   max));\n\n        printOutput(\"(d) cubic B-splines\", ts4);\n\n        SvenssonFitting svensson;\n\n        boost::shared_ptr<FittedBondDiscountCurve> ts5 (\n                        new FittedBondDiscountCurve(curveSettlementDays,\n                                                    calendar,\n                                                    instrumentsA,\n                                                    dc,\n                                                    svensson,\n                                                    tolerance,\n                                                    max));\n\n        printOutput(\"(e) Svensson\", ts5);\n\n        Handle<YieldTermStructure> discountCurve(\n            boost::make_shared<FlatForward>(\n                                    curveSettlementDays, calendar, 0.01, dc));\n        SpreadFittingMethod nelsonSiegelSpread(\n                                    boost::make_shared<NelsonSiegelFitting>(),\n                                    discountCurve);\n\n        boost::shared_ptr<FittedBondDiscountCurve> ts6 (\n                        new FittedBondDiscountCurve(curveSettlementDays,\n                                                    calendar,\n                                                    instrumentsA,\n                                                    dc,\n                                                    nelsonSiegelSpread,\n                                                    tolerance,\n                                                    max));\n\n        printOutput(\"(f) Nelson-Siegel spreaded\", ts6);\n\n\n        cout << \"Output par rates for each curve. In this case, \"\n             << endl\n             << \"par rates should equal coupons for these par bonds.\"\n             << endl\n             << endl;\n\n        cout << setw(6) << \"tenor\" << \" | \"\n             << setw(6) << \"coupon\" << \" | \"\n             << setw(6) << \"bstrap\" << \" | \"\n             << setw(6) << \"(a)\" << \" | \"\n             << setw(6) << \"(b)\" << \" | \"\n             << setw(6) << \"(c)\" << \" | \"\n             << setw(6) << \"(d)\" << \" | \"\n             << setw(6) << \"(e)\" << \" | \"\n             << setw(6) << \"(f)\" << endl;\n\n        for (Size i=0; i<instrumentsA.size(); i++) {\n\n            std::vector<boost::shared_ptr<CashFlow> > cfs =\n                instrumentsA[i]->bond()->cashflows();\n\n            Size cfSize = instrumentsA[i]->bond()->cashflows().size();\n            std::vector<Date> keyDates;\n            keyDates.push_back(bondSettlementDate);\n\n            for (Size j=0; j<cfSize-1; j++) {\n                if (!cfs[j]->hasOccurred(bondSettlementDate, false)) {\n                    Date myDate =  cfs[j]->date();\n                    keyDates.push_back(myDate);\n                }\n            }\n\n            Real tenor = dc.yearFraction(today, cfs[cfSize-1]->date());\n\n            cout << setw(6) << fixed << setprecision(3) << tenor << \" | \"\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*coupons[i] << \" | \"\n                 // piecewise bootstrap\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts0,keyDates,dc) << \" | \"\n                 // exponential splines\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts1,keyDates,dc) << \" | \"\n                 // simple polynomial\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts2,keyDates,dc) << \" | \"\n                 // Nelson-Siegel\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts3,keyDates,dc) << \" | \"\n                 // cubic bsplines\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts4,keyDates,dc) << \" | \"\n                 // Svensson\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts5,keyDates,dc)  << \" | \"\n                 // Nelson-Siegel Spreaded\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts6,keyDates,dc) << endl;\n        }\n\n        cout << endl << endl << endl;\n        cout << \"Now add 23 months to today. Par rates should be \"  << endl\n             << \"automatically recalculated because today's date \"  << endl\n             << \"changes.  Par rates will NOT equal coupons (YTM \"  << endl\n             << \"will, with the correct compounding), but the \"     << endl\n             << \"piecewise yield curve par rates can be used as \"   << endl\n             << \"a benchmark for correct par rates.\"\n             << endl\n             << endl;\n\n        today = calendar.advance(origToday,23,Months,convention);\n        Settings::instance().evaluationDate() = today;\n        bondSettlementDate = calendar.advance(today, bondSettlementDays*Days);\n\n        printOutput(\"(a) exponential splines\", ts1);\n\n        printOutput(\"(b) simple polynomial\", ts2);\n\n        printOutput(\"(c) Nelson-Siegel\", ts3);\n\n        printOutput(\"(d) cubic B-splines\", ts4);\n\n        printOutput(\"(e) Svensson\", ts5);\n\n        printOutput(\"(f) Nelson-Siegel spreaded\", ts6);\n\n        cout << endl\n             << endl;\n\n\n        cout << setw(6) << \"tenor\" << \" | \"\n             << setw(6) << \"coupon\" << \" | \"\n             << setw(6) << \"bstrap\" << \" | \"\n             << setw(6) << \"(a)\" << \" | \"\n             << setw(6) << \"(b)\" << \" | \"\n             << setw(6) << \"(c)\" << \" | \"\n             << setw(6) << \"(d)\" << \" | \"\n             << setw(6) << \"(e)\" << \" | \"\n             << setw(6) << \"(f)\" << endl;\n\n        for (Size i=0; i<instrumentsA.size(); i++) {\n\n            std::vector<boost::shared_ptr<CashFlow> > cfs =\n                instrumentsA[i]->bond()->cashflows();\n\n            Size cfSize = instrumentsA[i]->bond()->cashflows().size();\n            std::vector<Date> keyDates;\n            keyDates.push_back(bondSettlementDate);\n\n            for (Size j=0; j<cfSize-1; j++) {\n                if (!cfs[j]->hasOccurred(bondSettlementDate, false)) {\n                    Date myDate =  cfs[j]->date();\n                    keyDates.push_back(myDate);\n                }\n            }\n\n            Real tenor = dc.yearFraction(today, cfs[cfSize-1]->date());\n\n            cout << setw(6) << fixed << setprecision(3) << tenor << \" | \"\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*coupons[i] << \" | \"\n                 // piecewise bootstrap\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts0,keyDates,dc) << \" | \"\n                 // exponential splines\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts1,keyDates,dc) << \" | \"\n                 // simple polynomial\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts2,keyDates,dc) << \" | \"\n                 // Nelson-Siegel\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts3,keyDates,dc) << \" | \"\n                 // cubic bsplines\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts4,keyDates,dc) << \" | \"\n                 // Svensson\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts5,keyDates,dc) << \" | \"\n                 // Nelson-Siegel Spreaded\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts6,keyDates,dc) << endl;\n        }\n\n        cout << endl << endl << endl;\n        cout << \"Now add one more month, for a total of two years \" << endl\n             << \"from the original date. The first instrument is \"  << endl\n             << \"now expired and par rates should again equal \"     << endl\n             << \"coupon values, since clean prices did not change.\"\n             << endl\n             << endl;\n\n        instrumentsA.erase(instrumentsA.begin(),\n                           instrumentsA.begin()+1);\n        instrumentsB.erase(instrumentsB.begin(),\n                           instrumentsB.begin()+1);\n\n        today = calendar.advance(origToday,24,Months,convention);\n        Settings::instance().evaluationDate() = today;\n        bondSettlementDate = calendar.advance(today, bondSettlementDays*Days);\n\n        boost::shared_ptr<YieldTermStructure> ts00 (\n              new PiecewiseYieldCurve<Discount,LogLinear>(curveSettlementDays,\n                                                          calendar,\n                                                          instrumentsB,\n                                                          dc));\n\n        boost::shared_ptr<FittedBondDiscountCurve> ts11 (\n                  new FittedBondDiscountCurve(curveSettlementDays,\n                                              calendar,\n                                              instrumentsA,\n                                              dc,\n                                              exponentialSplines,\n                                              tolerance,\n                                              max));\n\n        printOutput(\"(a) exponential splines\", ts11);\n\n\n        boost::shared_ptr<FittedBondDiscountCurve> ts22 (\n                    new FittedBondDiscountCurve(curveSettlementDays,\n                                                calendar,\n                                                instrumentsA,\n                                                dc,\n                                                simplePolynomial,\n                                                tolerance,\n                                                max));\n\n        printOutput(\"(b) simple polynomial\", ts22);\n\n\n        boost::shared_ptr<FittedBondDiscountCurve> ts33 (\n                        new FittedBondDiscountCurve(curveSettlementDays,\n                                                    calendar,\n                                                    instrumentsA,\n                                                    dc,\n                                                    nelsonSiegel,\n                                                    tolerance,\n                                                    max));\n\n        printOutput(\"(c) Nelson-Siegel\", ts33);\n\n\n        boost::shared_ptr<FittedBondDiscountCurve> ts44 (\n                       new FittedBondDiscountCurve(curveSettlementDays,\n                                                   calendar,\n                                                   instrumentsA,\n                                                   dc,\n                                                   cubicBSplines,\n                                                   tolerance,\n                                                   max));\n\n        printOutput(\"(d) cubic B-splines\", ts44);\n\n        boost::shared_ptr<FittedBondDiscountCurve> ts55 (\n                       new FittedBondDiscountCurve(curveSettlementDays,\n                                                   calendar,\n                                                   instrumentsA,\n                                                   dc,\n                                                   svensson,\n                                                   tolerance,\n                                                   max));\n\n        printOutput(\"(e) Svensson\", ts55);\n\n        boost::shared_ptr<FittedBondDiscountCurve> ts66 (\n                        new FittedBondDiscountCurve(curveSettlementDays,\n                                                    calendar,\n                                                    instrumentsA,\n                                                    dc,\n                                                    nelsonSiegelSpread,\n                                                    tolerance,\n                                                    max));\n\n        printOutput(\"(f) Nelson-Siegel spreaded\", ts66);\n\n        cout << setw(6) << \"tenor\" << \" | \"\n             << setw(6) << \"coupon\" << \" | \"\n             << setw(6) << \"bstrap\" << \" | \"\n             << setw(6) << \"(a)\" << \" | \"\n             << setw(6) << \"(b)\" << \" | \"\n             << setw(6) << \"(c)\" << \" | \"\n             << setw(6) << \"(d)\" << \" | \"\n             << setw(6) << \"(e)\" << \" | \"\n             << setw(6) << \"(f)\" << endl;\n\n        for (Size i=0; i<instrumentsA.size(); i++) {\n\n            std::vector<boost::shared_ptr<CashFlow> > cfs =\n                instrumentsA[i]->bond()->cashflows();\n\n            Size cfSize = instrumentsA[i]->bond()->cashflows().size();\n            std::vector<Date> keyDates;\n            keyDates.push_back(bondSettlementDate);\n\n            for (Size j=0; j<cfSize-1; j++) {\n                if (!cfs[j]->hasOccurred(bondSettlementDate, false)) {\n                    Date myDate =  cfs[j]->date();\n                    keyDates.push_back(myDate);\n                }\n            }\n\n            Real tenor = dc.yearFraction(today, cfs[cfSize-1]->date());\n\n            cout << setw(6) << fixed << setprecision(3) << tenor << \" | \"\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*coupons[i+1] << \" | \"\n                 // piecewise bootstrap\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts00,keyDates,dc) << \" | \"\n                 // exponential splines\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts11,keyDates,dc) << \" | \"\n                 // simple polynomial\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts22,keyDates,dc) << \" | \"\n                 // Nelson-Siegel\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts33,keyDates,dc) << \" | \"\n                 // cubic bsplines\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts44,keyDates,dc) << \" | \"\n                 // Svensson\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts55,keyDates,dc) << \" | \"\n                 // Nelson-Siegel Spreaded\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts66,keyDates,dc) << endl;\n        }\n\n\n        cout << endl << endl << endl;\n        cout << \"Now decrease prices by a small amount, corresponding\"  << endl\n             << \"to a theoretical five basis point parallel + shift of\" << endl\n             << \"the yield curve. Because bond quotes change, the new \" << endl\n             << \"par rates should be recalculated automatically.\"\n             << endl\n             << endl;\n\n        for (Size k=0; k<LENGTH(lengths)-1; k++) {\n\n            Real P = instrumentsA[k]->quote()->value();\n            const Bond& b = *instrumentsA[k]->bond();\n            Rate ytm = BondFunctions::yield(b, P,\n                                            dc, Compounded, frequency,\n                                            today);\n            Time dur = BondFunctions::duration(b, ytm,\n                                               dc, Compounded, frequency,\n                                               Duration::Modified,\n                                               today);\n\n            const Real bpsChange = 5.;\n            // dP = -dur * P * dY\n            Real deltaP = -dur * P * (bpsChange/10000.);\n            quote[k+1]->setValue(P + deltaP);\n        }\n\n\n        cout << setw(6) << \"tenor\" << \" | \"\n             << setw(6) << \"coupon\" << \" | \"\n             << setw(6) << \"bstrap\" << \" | \"\n             << setw(6) << \"(a)\" << \" | \"\n             << setw(6) << \"(b)\" << \" | \"\n             << setw(6) << \"(c)\" << \" | \"\n             << setw(6) << \"(d)\" << \" | \"\n             << setw(6) << \"(e)\" << \" | \"\n             << setw(6) << \"(f)\" << endl;\n\n        for (Size i=0; i<instrumentsA.size(); i++) {\n\n            std::vector<boost::shared_ptr<CashFlow> > cfs =\n                instrumentsA[i]->bond()->cashflows();\n\n            Size cfSize = instrumentsA[i]->bond()->cashflows().size();\n            std::vector<Date> keyDates;\n            keyDates.push_back(bondSettlementDate);\n\n            for (Size j=0; j<cfSize-1; j++) {\n                if (!cfs[j]->hasOccurred(bondSettlementDate, false)) {\n                    Date myDate =  cfs[j]->date();\n                    keyDates.push_back(myDate);\n                }\n            }\n\n            Real tenor = dc.yearFraction(today, cfs[cfSize-1]->date());\n\n            cout << setw(6) << fixed << setprecision(3) << tenor << \" | \"\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*coupons[i+1] << \" | \"\n                 // piecewise bootstrap\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts00,keyDates,dc) << \" | \"\n                 // exponential splines\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts11,keyDates,dc) << \" | \"\n                 // simple polynomial\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts22,keyDates,dc) << \" | \"\n                 // Nelson-Siegel\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts33,keyDates,dc) << \" | \"\n                 // cubic bsplines\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts44,keyDates,dc) << \" | \"\n                 // Svensson\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts55,keyDates,dc) << \" | \"\n                 // Nelson-Siegel Spreaded\n                 << setw(6) << fixed << setprecision(3)\n                 << 100.*parRate(*ts66,keyDates,dc) << endl;\n        }\n\n\n        double seconds = timer.elapsed();\n        Integer hours = int(seconds/3600);\n        seconds -= hours * 3600;\n        Integer minutes = int(seconds/60);\n        seconds -= minutes * 60;\n        std::cout << \" \\nRun completed in \";\n        if (hours > 0)\n            std::cout << hours << \" h \";\n        if (hours > 0 || minutes > 0)\n            std::cout << minutes << \" m \";\n        std::cout << std::fixed << std::setprecision(0)\n                  << seconds << \" s\\n\" << std::endl;\n\n        return 0;\n\n    } catch (std::exception& e) {\n        cerr << e.what() << endl;\n        return 1;\n    } catch (...) {\n        cerr << \"unknown error\" << endl;\n        return 1;\n    }\n\n}\n\n", "meta": {"hexsha": "28838225481025c1046a978e179ff2967745d9ae", "size": 27958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/FittedBondCurve/FittedBondCurve.cpp", "max_stars_repo_name": "grandtiger/quantlib", "max_stars_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-19T11:17:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-19T11:17:48.000Z", "max_issues_repo_path": "Examples/FittedBondCurve/FittedBondCurve.cpp", "max_issues_repo_name": "grandtiger/quantlib", "max_issues_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T18:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-17T18:49:22.000Z", "max_forks_repo_path": "Examples/FittedBondCurve/FittedBondCurve.cpp", "max_forks_repo_name": "grandtiger/quantlib", "max_forks_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "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.0543318649, "max_line_length": 83, "alphanum_fraction": 0.4368338222, "num_tokens": 5898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5019364527601108}}
{"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__TN_HPP_\n#define SMOOTH__TN_HPP_\n\n#include <Eigen/Core>\n\n#include \"internal/lie_group_base.hpp\"\n#include \"internal/macro.hpp\"\n#include \"internal/tn.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief Lie group \\f$\\mathbb{T}(n)\\f$ of \\f$n\\f$-dimensional translations.\n *\n * Memory layout\n * -------------\n * - Group:    \\f$ \\mathbf{t} = [x_1, \\ldots, x_n] \\f$\n * - Tangent:  \\f$ \\mathbf{v} = [v_1, \\ldots, v_n] \\f$\n *\n * Lie group Matrix form\n * ---------------------\n *\n * \\f[\n * \\mathbf{X} =\n * \\begin{bmatrix}\n *  I & \\mathbf{t} \\\\\n *  0 & 1\n * \\end{bmatrix} \\in \\mathbb{R}^{n+1 \\times n+1}\n * \\f]\n *\n * Lie algebra Matrix form\n * -----------------------\n *\n * \\f[\n * \\mathbf{v}^\\wedge =\n * \\begin{bmatrix}\n *  0 & \\mathbf{v} \\\\\n *  0 & 0\n * \\end{bmatrix} \\in \\mathbb{R}^{n+1 \\times n+1}\n * \\f]\n */\ntemplate<typename _Derived>\nclass TnBase : public LieGroupBase<_Derived>\n{\n  using Base = LieGroupBase<_Derived>;\n\nprotected:\n  TnBase() = default;\n\npublic:\n  SMOOTH_INHERIT_TYPEDEFS;\n\n  /**\n   * @brief Euclidean vector (Rn) representation.\n   */\n  Eigen::Map<Eigen::Matrix<Scalar, Dof, 1>> rn() requires is_mutable\n  {\n    return Eigen::Map<Eigen::Matrix<Scalar, Dof, 1>>(static_cast<_Derived &>(*this).data());\n  }\n\n  /**\n   * @brief Euclidean vector (Rn) representation.\n   */\n  Eigen::Map<const Eigen::Matrix<Scalar, Dof, 1>> rn() const\n  {\n    return Eigen::Map<const Eigen::Matrix<Scalar, Dof, 1>>(\n      static_cast<const _Derived &>(*this).data());\n  }\n\n  /**\n   * @brief Translation action on Rn vector.\n   */\n  template<typename EigenDerived>\n  Eigen::Matrix<Scalar, Dof, 1> operator*(const Eigen::MatrixBase<EigenDerived> & v) const\n  {\n    return rn() + v;\n  }\n};\n\n// \\cond\ntemplate<int N, typename _Scalar>\nrequires(N > 0) class Tn;\n// \\endcond\n\n// \\cond\ntemplate<int N, typename _Scalar>\nstruct lie_traits<Tn<N, _Scalar>>\n{\n  static constexpr bool is_mutable = true;\n\n  using Impl   = TnImpl<N, _Scalar>;\n  using Scalar = _Scalar;\n\n  template<typename NewScalar>\n  using PlainObject = Tn<N, NewScalar>;\n};\n// \\endcond\n\n/**\n * @brief Storage implementation of Tn Lie group.\n *\n * @see TnBase for memory layout.\n */\ntemplate<int N, typename _Scalar>\n// \\cond\nrequires(N > 0)\n  // \\endcond\n  class Tn : public TnBase<Tn<N, _Scalar>>\n{\n  using Base = TnBase<Tn<N, _Scalar>>;\n  SMOOTH_GROUP_API(Tn);\n\npublic:\n  /**\n   * @brief Construct from Eigen vector.\n   *\n   * @param rn Eigen vector.\n   */\n  template<typename Derived>\n  Tn(const Eigen::MatrixBase<Derived> & rn) : coeffs_(rn)\n  {}\n};\n\n}  // namespace smooth\n\n// \\cond\ntemplate<int N, typename _Scalar>\nstruct smooth::lie_traits<Eigen::Map<smooth::Tn<N, _Scalar>>>\n    : public lie_traits<smooth::Tn<N, _Scalar>>\n{};\n// \\endcond\n\n/**\n * @brief Memory mapping of Tn Lie group.\n *\n * @see TnBase for memory layout.\n */\ntemplate<int N, typename _Scalar>\nclass Eigen::Map<smooth::Tn<N, _Scalar>> : public smooth::TnBase<Eigen::Map<smooth::Tn<N, _Scalar>>>\n{\n  using Base = smooth::TnBase<Eigen::Map<smooth::Tn<N, _Scalar>>>;\n\n  SMOOTH_MAP_API(Map);\n};\n\n// \\cond\ntemplate<int N, typename _Scalar>\nstruct smooth::lie_traits<Eigen::Map<const smooth::Tn<N, _Scalar>>>\n    : public lie_traits<smooth::Tn<N, _Scalar>>\n{\n  static constexpr bool is_mutable = false;\n};\n// \\endcond\n\n/**\n * @brief Const memory mapping of Tn Lie group.\n *\n * @see TnBase for memory layout.\n */\ntemplate<int N, typename _Scalar>\nclass Eigen::Map<const smooth::Tn<N, _Scalar>>\n    : public smooth::TnBase<Eigen::Map<const smooth::Tn<N, _Scalar>>>\n{\n  using Base = smooth::TnBase<Eigen::Map<const smooth::Tn<N, _Scalar>>>;\n\n  SMOOTH_CONST_MAP_API(Map);\n};\n\nnamespace smooth {\n// \\cond\ntemplate<typename Scalar>\nusing T1 = Tn<1, Scalar>;\ntemplate<typename Scalar>\nusing T2 = Tn<2, Scalar>;\ntemplate<typename Scalar>\nusing T3 = Tn<3, Scalar>;\ntemplate<typename Scalar>\nusing T4 = Tn<4, Scalar>;\ntemplate<typename Scalar>\nusing T5 = Tn<5, Scalar>;\ntemplate<typename Scalar>\nusing T6 = Tn<6, Scalar>;\ntemplate<typename Scalar>\nusing T7 = Tn<7, Scalar>;\ntemplate<typename Scalar>\nusing T8 = Tn<8, Scalar>;\ntemplate<typename Scalar>\nusing T9 = Tn<9, Scalar>;\ntemplate<typename Scalar>\nusing T10 = Tn<10, Scalar>;\n\nusing T1f  = T1<float>;\nusing T2f  = T2<float>;\nusing T3f  = T3<float>;\nusing T4f  = T4<float>;\nusing T5f  = T5<float>;\nusing T6f  = T6<float>;\nusing T7f  = T7<float>;\nusing T8f  = T8<float>;\nusing T9f  = T9<float>;\nusing T10f = T10<float>;\n\nusing T1d  = T1<double>;\nusing T2d  = T2<double>;\nusing T3d  = T3<double>;\nusing T4d  = T4<double>;\nusing T5d  = T5<double>;\nusing T6d  = T6<double>;\nusing T7d  = T7<double>;\nusing T8d  = T8<double>;\nusing T9d  = T9<double>;\nusing T10d = T10<double>;\n// \\endcond\n}  // namespace smooth\n\n#endif  // SMOOTH__TN_HPP_\n", "meta": {"hexsha": "6194f6252bb1cf1763c7328b83a15b1250b71717", "size": 5961, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/tn.hpp", "max_stars_repo_name": "NamDinhRobotics/smooth", "max_stars_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:18.000Z", "max_issues_repo_path": "include/smooth/tn.hpp", "max_issues_repo_name": "NamDinhRobotics/smooth", "max_issues_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_issues_repo_licenses": ["MIT"], "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/tn.hpp", "max_forks_repo_name": "NamDinhRobotics/smooth", "max_forks_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_forks_repo_licenses": ["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.632231405, "max_line_length": 100, "alphanum_fraction": 0.6705250797, "num_tokens": 1770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.6370308082623218, "lm_q1q2_score": 0.5019364400708706}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2018 Adeel Ahmad, Islamabad, Pakistan.\n\n// Contributed and/or modified by Adeel Ahmad,\n//   as part of Google Summer of Code 2018 program.\n\n// This file was modified by Oracle on 2018.\n// Modifications copyright (c) 2018 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// This file is converted from GeographicLib, https://geographiclib.sourceforge.io\n// GeographicLib is originally written by Charles Karney.\n\n// Author: Charles Karney (2008-2017)\n\n// Last updated version of GeographicLib: 1.49\n\n// Original copyright notice:\n\n// Copyright (c) Charles Karney (2008-2017) <charles@karney.com> and licensed\n// under the MIT/X11 License. For more information, see\n// https://geographiclib.sourceforge.io\n\n#ifndef BOOST_GEOMETRY_FORMULAS_KARNEY_DIRECT_HPP\n#define BOOST_GEOMETRY_FORMULAS_KARNEY_DIRECT_HPP\n\n\n#include <boost/array.hpp>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n\n#include <boost/geometry/formulas/flattening.hpp>\n#include <boost/geometry/formulas/result_direct.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/normalize_spheroidal_coordinates.hpp>\n#include <boost/geometry/util/series_expansion.hpp>\n\n\nnamespace boost { namespace geometry { namespace formula\n{\n\nnamespace se = series_expansion;\n\n/*!\n\\brief The solution of the direct problem of geodesics on latlong coordinates,\n       after Karney (2011).\n\\author See\n- Charles F.F Karney, Algorithms for geodesics, 2011\nhttps://arxiv.org/pdf/1109.4448.pdf\n*/\ntemplate <\n    typename CT,\n    bool EnableCoordinates = true,\n    bool EnableReverseAzimuth = false,\n    bool EnableReducedLength = false,\n    bool EnableGeodesicScale = false,\n    size_t SeriesOrder = 8\n>\nclass karney_direct\n{\n    static const bool CalcQuantities = EnableReducedLength || EnableGeodesicScale;\n    static const bool CalcCoordinates = EnableCoordinates || CalcQuantities;\n    static const bool CalcRevAzimuth = EnableReverseAzimuth || CalcCoordinates || CalcQuantities;\n\npublic:\n    typedef result_direct<CT> result_type;\n\n    template <typename T, typename Dist, typename Azi, typename Spheroid>\n    static inline result_type apply(T const& lo1,\n                                    T const& la1,\n                                    Dist const& distance,\n                                    Azi const& azimuth12,\n                                    Spheroid const& spheroid)\n    {\n        result_type result;\n\n        CT lon1 = lo1;\n        CT const lat1 = la1;\n\n        Azi azi12 = azimuth12;\n        math::normalize_azimuth<degree, Azi>(azi12);\n\n        Dist const dist_c0 = 0;\n\n        if (math::equals(distance, dist_c0) || distance < dist_c0)\n        {\n            result.lon2 = lon1;\n            result.lat2 = lat1;\n            return result;\n        }\n\n        CT const c0 = 0;\n        CT const c1 = 1;\n        CT const c2 = 2;\n\n        CT const b = CT(get_radius<2>(spheroid));\n        CT const f = formula::flattening<CT>(spheroid);\n        CT const one_minus_f = c1 - f;\n        CT const two_minus_f = c2 - f;\n\n        CT const n = f / two_minus_f;\n        CT const e2 = f * two_minus_f;\n        CT const ep2 = e2 / math::sqr(one_minus_f);\n\n        CT sin_alpha1, cos_alpha1;\n        math::sin_cos_degrees<CT>(math::round_angle<CT>(azi12), sin_alpha1, cos_alpha1);\n\n        // Find the reduced latitude.\n        CT sin_beta1, cos_beta1;\n        math::sin_cos_degrees<CT>(math::round_angle<CT>(lat1), sin_beta1, cos_beta1);\n        sin_beta1 *= one_minus_f;\n\n        math::normalize_unit_vector<CT>(sin_beta1, cos_beta1);\n\n        cos_beta1 = (std::max)(c0, cos_beta1);\n\n        // Obtain alpha 0 by solving the spherical triangle.\n        CT const sin_alpha0 = sin_alpha1 * cos_beta1;\n        CT const cos_alpha0 = boost::math::hypot(cos_alpha1, sin_alpha1 * sin_beta1);\n\n        CT const k2 = math::sqr(cos_alpha0) * ep2;\n\n        CT const epsilon = k2 / (c2 * (c1 + math::sqrt(c1 + k2)) + k2);\n\n        // Find the coefficients for A1 by computing the\n        // series expansion using Horner scehme.\n        CT const expansion_A1 = se::evaluate_A1<SeriesOrder>(epsilon);\n\n        // Index zero element of coeffs_C1 is unused.\n        se::coeffs_C1<SeriesOrder, CT> const coeffs_C1(epsilon);\n\n        // Tau is an integration variable.\n        CT const tau12 = distance / (b * (c1 + expansion_A1));\n\n        CT const sin_tau12 = sin(tau12);\n        CT const cos_tau12 = cos(tau12);\n\n        CT sin_sigma1 = sin_beta1;\n        CT sin_omega1 = sin_alpha0 * sin_beta1;\n\n        CT cos_sigma1, cos_omega1;\n        cos_sigma1 = cos_omega1 = sin_beta1 != c0 || cos_alpha1 != c0 ? cos_beta1 * cos_alpha1 : c1;\n        math::normalize_unit_vector<CT>(sin_sigma1, cos_sigma1);\n\n        CT const B11 = se::sin_cos_series(sin_sigma1, cos_sigma1, coeffs_C1);\n        CT const sin_B11 = sin(B11);\n        CT const cos_B11 = cos(B11);\n\n        CT const sin_tau1 = sin_sigma1 * cos_B11 + cos_sigma1 * sin_B11;\n        CT const cos_tau1 = cos_sigma1 * cos_B11 - sin_sigma1 * sin_B11;\n\n        // Index zero element of coeffs_C1p is unused.\n        se::coeffs_C1p<SeriesOrder, CT> const coeffs_C1p(epsilon);\n\n        CT const B12 = - se::sin_cos_series\n                             (sin_tau1 * cos_tau12 + cos_tau1 * sin_tau12,\n                              cos_tau1 * cos_tau12 - sin_tau1 * sin_tau12,\n                              coeffs_C1p);\n\n        CT const sigma12 = tau12 - (B12 - B11);\n        CT const sin_sigma12 = sin(sigma12);\n        CT const cos_sigma12 = cos(sigma12);\n\n        CT const sin_sigma2 = sin_sigma1 * cos_sigma12 + cos_sigma1 * sin_sigma12;\n        CT const cos_sigma2 = cos_sigma1 * cos_sigma12 - sin_sigma1 * sin_sigma12;\n\n        if (BOOST_GEOMETRY_CONDITION(CalcRevAzimuth))\n        {\n            CT const sin_alpha2 = sin_alpha0;\n            CT const cos_alpha2 = cos_alpha0 * cos_sigma2;\n\n            result.reverse_azimuth = atan2(sin_alpha2, cos_alpha2);\n\n            // Convert the angle to radians.\n            result.reverse_azimuth /= math::d2r<CT>();\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(CalcCoordinates))\n        {\n            // Find the latitude at the second point.\n            CT const sin_beta2 = cos_alpha0 * sin_sigma2;\n            CT const cos_beta2 = boost::math::hypot(sin_alpha0, cos_alpha0 * cos_sigma2);\n\n            result.lat2 = atan2(sin_beta2, one_minus_f * cos_beta2);\n\n            // Convert the coordinate to radians.\n            result.lat2 /= math::d2r<CT>();\n\n            // Find the longitude at the second point.\n            CT const sin_omega2 = sin_alpha0 * sin_sigma2;\n            CT const cos_omega2 = cos_sigma2;\n\n            CT const omega12 = atan2(sin_omega2 * cos_omega1 - cos_omega2 * sin_omega1,\n                                     cos_omega2 * cos_omega1 + sin_omega2 * sin_omega1);\n\n            se::coeffs_A3<SeriesOrder, CT> const coeffs_A3(n);\n\n            CT const A3 = math::horner_evaluate(epsilon, coeffs_A3.begin(), coeffs_A3.end());\n            CT const A3c = -f * sin_alpha0 * A3;\n\n            se::coeffs_C3<SeriesOrder, CT> const coeffs_C3(n, epsilon);\n\n            CT const B31 = se::sin_cos_series(sin_sigma1, cos_sigma1, coeffs_C3);\n\n            CT const lam12 = omega12 + A3c *\n                             (sigma12 + (se::sin_cos_series\n                                             (sin_sigma2,\n                                              cos_sigma2,\n                                              coeffs_C3) - B31));\n\n            // Convert to radians to get the\n            // longitudinal difference.\n            CT lon12 = lam12 / math::d2r<CT>();\n\n            // Add the longitude at first point to the longitudinal\n            // difference and normalize the result.\n            math::normalize_longitude<degree, CT>(lon1);\n            math::normalize_longitude<degree, CT>(lon12);\n\n            result.lon2 = lon1 + lon12;\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(CalcQuantities))\n        {\n            // Evaluate the coefficients for C2.\n            // Index zero element of coeffs_C2 is unused.\n            se::coeffs_C2<SeriesOrder, CT> const coeffs_C2(epsilon);\n\n            CT const B21 = se::sin_cos_series(sin_sigma1, cos_sigma1, coeffs_C2);\n            CT const B22 = se::sin_cos_series(sin_sigma2, cos_sigma2, coeffs_C2);\n\n            // Find the coefficients for A2 by computing the\n            // series expansion using Horner scehme.\n            CT const expansion_A2 = se::evaluate_A2<SeriesOrder>(epsilon);\n\n            CT const AB1 = (c1 + expansion_A1) * (B12 - B11);\n            CT const AB2 = (c1 + expansion_A2) * (B22 - B21);\n            CT const J12 = (expansion_A1 - expansion_A2) * sigma12 + (AB1 - AB2);\n\n            CT const dn1 = math::sqrt(c1 + ep2 * math::sqr(sin_beta1));\n            CT const dn2 = math::sqrt(c1 + k2 * math::sqr(sin_sigma2));\n\n            // Find the reduced length.\n            result.reduced_length = b * ((dn2 * (cos_sigma1 * sin_sigma2) -\n                                          dn1 * (sin_sigma1 * cos_sigma2)) -\n                                          cos_sigma1 * cos_sigma2 * J12);\n\n            // Find the geodesic scale.\n            CT const t = k2 * (sin_sigma2 - sin_sigma1) *\n                              (sin_sigma2 + sin_sigma1) / (dn1 + dn2);\n\n            result.geodesic_scale = cos_sigma12 +\n                                    (t * sin_sigma2 - cos_sigma2 * J12) *\n                                    sin_sigma1 / dn1;\n        }\n\n        return result;\n    }\n};\n\n}}} // namespace boost::geometry::formula\n\n\n#endif // BOOST_GEOMETRY_FORMULAS_KARNEY_DIRECT_HPP\n", "meta": {"hexsha": "40406840039b9869cb9b7a54bf6a97c6ac7341e4", "size": 9893, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/formulas/karney_direct.hpp", "max_stars_repo_name": "batzn/boost_1_70_0_b1_vc142", "max_stars_repo_head_hexsha": "797b4e63ecc12fdae00c9b9c9d34c9b16177e391", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-25T01:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T17:58:05.000Z", "max_issues_repo_path": "boost/geometry/formulas/karney_direct.hpp", "max_issues_repo_name": "batzn/boost_1_70_0_b1_vc142", "max_issues_repo_head_hexsha": "797b4e63ecc12fdae00c9b9c9d34c9b16177e391", "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/geometry/formulas/karney_direct.hpp", "max_forks_repo_name": "batzn/boost_1_70_0_b1_vc142", "max_forks_repo_head_hexsha": "797b4e63ecc12fdae00c9b9c9d34c9b16177e391", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-05T23:04:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-05T23:04:05.000Z", "avg_line_length": 36.2380952381, "max_line_length": 100, "alphanum_fraction": 0.6094208026, "num_tokens": 2489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5018922113141282}}
{"text": "#define BOOST_TEST_MODULE TicTacToe test\n#include <boost/test/unit_test.hpp>\n\n#include \"System.h\"\n\n#include <future>\n#include <queue>\n#include <thread>\n\nusing namespace omnn::math;\nusing namespace boost::unit_test;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE(TicTacToe_X_Won_test)\n{\n    System ticTacToe;\n\n    DECL_VA(i);\n    ticTacToe << i.Abet({1, 2, 3});\n\n    DECL_VA(v);\n    ticTacToe << v.Equals(1); // encoded cross positions\n\n    // The constrasint of X,Y positions to win\n    DECL_VA(x);\n    DECL_VA(y);\n    ticTacToe << ((x.Equals(i) && y.Equals(i)) || (x.Equals(4_v - i) && y.Equals(i)));\n\n\tDECL_VA(win);\n    auto winExp = (win.Equals(1) && ticTacToe.Total()) || win.Equals(0);\n\n\tstruct EncodedFieldPack { // of encoded field (X only)\n        bool hasXat1_1 : 1;   // bit\n        bool hasXat1_2 : 1;   // bit\n        bool hasXat1_3 : 1;   // bit\n        bool hasXat2_1 : 1;   // bit\n        bool hasXat2_2 : 1;   // bit\n        bool hasXat2_3 : 1;   // bit\n        bool hasXat3_1 : 1;   // bit\n        bool hasXat3_2 : 1;   // bit\n        bool hasXat3_3 : 1;   // bit\n    };\n    // Enumerating all variants and dump matched variants:\n\tunion Variant {\n        int code : 9; // bits\n        EncodedFieldPack pack;\n\t};\n\n\n\n    Variant fieldVariant = {};\n    for (fieldVariant.code = 1 << 9; fieldVariant.code-->0; ) {\n\n        System fieldExpression;\n        fieldExpression << (x.Equals(1) && y.Equals(1) && v.Equals(fieldVariant.pack.hasXat1_1))\n                        << (x.Equals(1) && y.Equals(2) && v.Equals(fieldVariant.pack.hasXat1_2))\n                        << (x.Equals(1) && y.Equals(3) && v.Equals(fieldVariant.pack.hasXat1_3))\n                        << (x.Equals(2) && y.Equals(1) && v.Equals(fieldVariant.pack.hasXat1_1))\n                        << (x.Equals(2) && y.Equals(2) && v.Equals(fieldVariant.pack.hasXat1_2))\n                        << (x.Equals(2) && y.Equals(3) && v.Equals(fieldVariant.pack.hasXat1_3))\n                        << (x.Equals(3) && y.Equals(1) && v.Equals(fieldVariant.pack.hasXat1_1))\n                        << (x.Equals(3) && y.Equals(2) && v.Equals(fieldVariant.pack.hasXat1_2))\n                        << (x.Equals(3) && y.Equals(3) && v.Equals(fieldVariant.pack.hasXat1_3));\n        fieldExpression << winExp;\n\n\t\tauto winSolutions = fieldExpression.Solve(win);\n        if (winSolutions.size() == 1) {\n            auto it = winSolutions.begin();\n            if (*it == 1) {\n                std::cout\n\t\t\t\t\t<< \"Win:\" << (fieldVariant.pack.hasXat1_1 ? 'X' : '0') << (fieldVariant.pack.hasXat1_2 ? 'X' : '0') << (fieldVariant.pack.hasXat1_3 ? 'X' : '0') << std::endl\n\t\t\t\t\t<< \"    \" << (fieldVariant.pack.hasXat2_1 ? 'X' : '0') << (fieldVariant.pack.hasXat2_2 ? 'X' : '0') << (fieldVariant.pack.hasXat2_3 ? 'X' : '0') << std::endl\n\t\t\t\t\t<< \"    \" << (fieldVariant.pack.hasXat3_1 ? 'X' : '0') << (fieldVariant.pack.hasXat3_2 ? 'X' : '0') << (fieldVariant.pack.hasXat3_3 ? 'X' : '0') << std::endl;\n            }\n        } else {\n            for (auto& s : winSolutions) {\n                std::cout << s << std::endl;\n\t\t\t}\n\t\t}\n\t}\n}", "meta": {"hexsha": "90bf7093a1788b90ded0fdcfb3e6c72ad81cd784", "size": 3076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/test/TicTacToe.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/TicTacToe.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/TicTacToe.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": 37.975308642, "max_line_length": 163, "alphanum_fraction": 0.5468140442, "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5018922031408186}}
{"text": "#include <density_estimation/utility/stochastic_process/gaussian_process.h>\n\n#include <Eigen/Cholesky>\n#include <cgv/math/eig.h>\n\n#include <density_estimation/utility/functions.h>\n#include <density_estimation/utility/truncated_multivariate_normal_distribution.h>\n\nusing namespace Eigen;\n\ngaussian_process::gaussian_process(\n  stochastic_process::random_engine_ptr random_engine,\n  unsigned index_set_sample_size,\n  std::function<float(float)> mean,\n  std::function<float(float, float)> covariance)\n  : stochastic_process(random_engine, index_set_sample_size)\n  , mean{ mean }\n  , covariance{ covariance }\n  , standard_normal_distribution{ 0.0f, 1.0f }\n{\n  bool success = determine_covariance_square_root_matrix();\n  if (!success) {\n    throw std::invalid_argument(\n      __func__ + std::string(\": covariance function generates a covariance \"\n                             \"matrix that isn't positive definite\"));\n  }\n\n  determine_mean_vector();\n}\n\ngaussian_process::~gaussian_process() {}\n\nvoid\ngaussian_process::marginal_densities(float arg_min,\n                                     float arg_max,\n                                     unsigned arg_count,\n                                     float random_variable_index,\n                                     float* densities)\n{\n  assert(arg_min <= arg_max);\n  assert(arg_count > 0);\n  float mean = this->mean(random_variable_index);\n  float variance =\n    this->covariance(random_variable_index, random_variable_index);\n  float arg_dx = arg_count > 1 ? (arg_max - arg_min) / (arg_count - 1) : 0;\n  for (unsigned i = 0; i < arg_count; ++i) {\n    float arg = arg_min + i * arg_dx;\n    float diff = arg - mean;\n    float density =\n      expf(-diff * diff / (2.0f * variance)) / sqrtf(2.0f * M_PIf32 * variance);\n    densities[i] = density;\n  }\n}\n\nvoid\ngaussian_process::marginal_densities_truncated(\n  float arg_min,\n  float arg_max,\n  unsigned arg_count,\n  float random_variable_index,\n  const std::vector<range_restriction>& restrictions,\n  float* densities)\n{\n  assert(arg_min <= arg_max);\n  assert(arg_count > 0);\n\n  cgv::math::vec<float> density_vector;\n  density_vector.set_extern_data(arg_count, densities);\n\n  unsigned size = static_cast<unsigned>(restrictions.size()) + 1;\n\n  cgv::math::vec<float> mean{ size };\n  cgv::math::mat<float> sigma{ size, size };\n  cgv::math::vec<float> lower{ size };\n  cgv::math::vec<float> upper{ size };\n\n  for (unsigned i = 0; i < size; ++i) {\n    float curr_random_variable_index = random_variable_index;\n    lower(i) = -std::numeric_limits<float>::infinity();\n    upper(i) = +std::numeric_limits<float>::infinity();\n    if (i < size - 1) {\n      const range_restriction& restriction = restrictions.at(i);\n      curr_random_variable_index = restriction.random_variable_index;\n      lower(i) = restriction.value_min;\n      upper(i) = restriction.value_max;\n    }\n\n    mean(i) = this->mean(random_variable_index);\n\n    for (unsigned j = 0; j < size; ++j) {\n      float other_random_variable_index = random_variable_index;\n      if (j < size - 1) {\n        const range_restriction& restriction = restrictions.at(j);\n        other_random_variable_index = restriction.random_variable_index;\n      }\n\n      sigma(i, j) = this->covariance(curr_random_variable_index,\n                                     other_random_variable_index);\n    }\n  }\n  marginal_truncated_multivariate_normal_density(arg_min,\n                                                 arg_max,\n                                                 arg_count,\n                                                 size - 1,\n                                                 mean,\n                                                 sigma,\n                                                 lower,\n                                                 upper,\n                                                 density_vector);\n}\n\nvoid\ngaussian_process::generate_sample_function(float* sample_function_values)\n{\n  VectorXf standard_normal_vector{ this->index_set_sample_size };\n  for (unsigned i = 0; i < this->index_set_sample_size; ++i) {\n    float value = this->standard_normal_distribution(*this->random_engine);\n    standard_normal_vector(i) = value;\n  }\n\n  Map<VectorXf> sample_function_vector{ sample_function_values,\n                                        this->index_set_sample_size };\n  sample_function_vector =\n    this->mean_vector +\n    this->covariance_square_root_matrix * standard_normal_vector;\n}\n\nvoid\ngaussian_process::determine_mean_vector()\n{\n  this->mean_vector = Eigen::VectorXf(this->index_set_sample_size);\n  for (unsigned i = 0; i < this->index_set_sample_size; ++i) {\n    float random_variable_index = i / (this->index_set_sample_size - 1.0f);\n    float mean = this->mean(random_variable_index);\n    this->mean_vector(i) = mean;\n  }\n}\n\nbool\ngaussian_process::determine_covariance_square_root_matrix()\n{\n  MatrixXf covariance_matrix{ this->index_set_sample_size,\n                              this->index_set_sample_size };\n  for (unsigned i = 0; i < this->index_set_sample_size; ++i) {\n    for (unsigned j = 0; j < this->index_set_sample_size; ++j) {\n      float random_variable_index_1 = i / (this->index_set_sample_size - 1.0f);\n      float random_variable_index_2 = j / (this->index_set_sample_size - 1.0f);\n      float covariance =\n        this->covariance(random_variable_index_1, random_variable_index_2);\n      if (i == j) {\n        covariance += 1e-04f;\n      }\n      covariance_matrix(i, j) = covariance;\n    }\n  }\n\n  LLT<MatrixXf> llt_solver{ covariance_matrix };\n  this->covariance_square_root_matrix = llt_solver.matrixL();\n  if (llt_solver.info() != Eigen::ComputationInfo::Success) {\n    return false;\n  }\n  return true;\n}\n", "meta": {"hexsha": "b1d48e6f978d75fd60caa63d70fc51a281f2c610", "size": 5687, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "plugins/density_estimation/src/utility/stochastic_process/gaussian_process.cxx", "max_stars_repo_name": "tobias-haenel/cgv-density-estimation", "max_stars_repo_head_hexsha": "3be1b07a7b21d1cfd956fb19b5f0d83fb51bd308", "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": "plugins/density_estimation/src/utility/stochastic_process/gaussian_process.cxx", "max_issues_repo_name": "tobias-haenel/cgv-density-estimation", "max_issues_repo_head_hexsha": "3be1b07a7b21d1cfd956fb19b5f0d83fb51bd308", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plugins/density_estimation/src/utility/stochastic_process/gaussian_process.cxx", "max_forks_repo_name": "tobias-haenel/cgv-density-estimation", "max_forks_repo_head_hexsha": "3be1b07a7b21d1cfd956fb19b5f0d83fb51bd308", "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.6768292683, "max_line_length": 82, "alphanum_fraction": 0.6344294004, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5018811125232161}}
{"text": "#include \"mesh.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <elasty/alembic-manager.hpp>\n#include <elasty/fem.hpp>\n#include <mathtoolbox/l-bfgs.hpp>\n#include <timer.hpp>\n#include <vector>\n\nnamespace\n{\n    constexpr double k_youngs_modulus = 600.0;\n    constexpr double k_poisson_ratio  = 0.45;\n\n    constexpr double k_first_lame  = elasty::fem::calcFirstLame(k_youngs_modulus, k_poisson_ratio);\n    constexpr double k_second_lame = elasty::fem::calcSecondLame(k_youngs_modulus, k_poisson_ratio);\n\n    constexpr unsigned k_num_substeps = 2;\n    constexpr double   k_delta_time   = 1.0 / 60.0;\n\n    constexpr double k_damping_factor = 0.0;\n\n    constexpr double k_spring_stiffness    = 1000.0;\n    constexpr double k_collision_stiffness = 100.0;\n\n    enum class Model\n    {\n        CoRotational,\n        StVenantKirchhoff\n    };\n\n    constexpr Model k_model = Model::CoRotational;\n} // namespace\n\nstruct Constraint\n{\n    std::size_t                              vert_index;\n    std::function<Eigen::Vector3d(double t)> motion;\n    double                                   stiffness;\n};\n\nstruct Collision\n{\n    std::size_t     vert_index;\n    Eigen::Vector3d surface_pos;\n    Eigen::Vector3d surface_normal;\n};\n\nclass HalfSpaceCollider\n{\npublic:\n    HalfSpaceCollider(const Eigen::Vector3d& representative_point, const Eigen::Vector3d& normal)\n        : m_representative_point(representative_point), m_normal(normal.normalized())\n    {\n        assert(!normal.isZero());\n    }\n\n    bool testCollision(const Eigen::Vector3d& point, const double tol) const\n    {\n        return (point - m_representative_point).dot(m_normal) < tol;\n    }\n\n    void retrieveCollisionInfo(const Eigen::Vector3d& point,\n                               Eigen::Vector3d&       surface_pos,\n                               Eigen::Vector3d&       surface_normal) const\n    {\n        surface_pos    = point - (point - m_representative_point).dot(m_normal) * m_normal;\n        surface_normal = m_normal;\n    }\n\nprivate:\n    const Eigen::Vector3d m_representative_point;\n    const Eigen::Vector3d m_normal;\n};\n\ntemplate <typename Derived> typename Derived::Scalar calcEnergyDensity(const Eigen::MatrixBase<Derived>& deform_grad)\n{\n    switch (k_model)\n    {\n        case Model::StVenantKirchhoff:\n            return elasty::fem::calcStVenantKirchhoffEnergyDensity(deform_grad, k_first_lame, k_second_lame);\n        case Model::CoRotational:\n            return elasty::fem::calcCoRotationalEnergyDensity(deform_grad, k_first_lame, k_second_lame);\n    }\n}\n\ntemplate <typename Derived>\nEigen::Matrix<typename Derived::Scalar, 3, 3> calcPiolaStress(const Eigen::MatrixBase<Derived>& deform_grad)\n{\n    switch (k_model)\n    {\n        case Model::StVenantKirchhoff:\n            return elasty::fem::calcStVenantKirchhoffPiolaStress(deform_grad, k_first_lame, k_second_lame);\n        case Model::CoRotational:\n            return elasty::fem::calcCoRotationalPiolaStress(deform_grad, k_first_lame, k_second_lame);\n    }\n}\n\nclass VariationalImplicit3dEngine\n{\npublic:\n    VariationalImplicit3dEngine() {}\n\n    void proceedFrame()\n    {\n        const std::size_t num_verts = m_mesh.x_rest.size() / 3;\n        const std::size_t num_elems = m_mesh.elems.cols();\n\n        // Reset forces\n        m_mesh.f = Eigen::VectorXd::Zero(3 * num_verts);\n\n        // Apply gravity force\n        for (std::size_t i = 0; i < num_verts; ++i)\n        {\n            m_mesh.f[i * 3 + 1] += m_mesh.lumped_mass(i * 3 + 1) * (-9.80665);\n        }\n\n        // Calculate the inverse lumped mass matrix\n        const auto W = m_mesh.lumped_mass.cwiseInverse().asDiagonal();\n\n        // Calculate the \"inertia\" position\n        const double&         h = m_delta_physics_time;\n        const Eigen::VectorXd y = m_mesh.x + h * m_mesh.v + h * h * W * m_mesh.f;\n\n        // Define colliders\n        // TODO: Improve the scene setup\n        const HalfSpaceCollider floor{Eigen::Vector3d{0.0, -1.0, 0.0}, Eigen::Vector3d{0.0, 1.0, 0.0}};\n\n        // Detect collisions\n        // TODO: Improve the collision detection algorithtm\n        std::vector<Collision> collisions;\n        for (std::size_t vert_index = 0; vert_index < num_verts; ++vert_index)\n        {\n            const Eigen::Vector3d predicted_pos = y.segment<3>(vert_index * 3);\n\n            if (floor.testCollision(predicted_pos, 0.0))\n            {\n                Eigen::Vector3d surface_pos;\n                Eigen::Vector3d surface_normal;\n                floor.retrieveCollisionInfo(predicted_pos, surface_pos, surface_normal);\n\n                const Collision collision{vert_index, surface_pos, surface_normal};\n                collisions.push_back(collision);\n            }\n        }\n\n        const auto calcInternalPotential = [&](const Eigen::VectorXd& x)\n        {\n            double sum = 0.0;\n\n            // Elastic potential\n            for (std::size_t elem_index = 0; elem_index < num_elems; ++elem_index)\n            {\n                const auto& indices = m_mesh.elems.col(elem_index);\n\n                // Retrieve precomputed values\n                const auto& D_m_inv = m_mesh.rest_shape_mat_inv_array[elem_index];\n                const auto& vol     = m_mesh.volume_array[elem_index];\n\n                // Calculate the deformation gradient $\\mathbf{F}$\n                const auto F = elasty::fem::calcTetrahedronDeformGrad(x.segment<3>(3 * indices[0]),\n                                                                      x.segment<3>(3 * indices[1]),\n                                                                      x.segment<3>(3 * indices[2]),\n                                                                      x.segment<3>(3 * indices[3]),\n                                                                      D_m_inv);\n\n                sum += vol * calcEnergyDensity(F);\n            }\n\n            // Attach-spring potential\n            for (const auto& constraint : m_constraints)\n            {\n                const std::size_t vert_index   = constraint.vert_index;\n                const double&     k            = constraint.stiffness;\n                const auto        p            = x.segment<3>(vert_index * 3);\n                const auto        q            = constraint.motion(m_physics_time + m_delta_physics_time);\n                const double      squared_dist = (p - q).squaredNorm();\n\n                sum += 0.5 * k * squared_dist;\n            }\n\n            // Collision energy\n            for (const auto& collision : collisions)\n            {\n                const auto&  vert_index = collision.vert_index;\n                const auto   pos        = x.segment<3>(vert_index * 3);\n                const auto&  normal     = collision.surface_normal;\n                const double a          = (collision.surface_pos - pos).transpose() * normal;\n\n                if (a > 0.0)\n                {\n                    sum += k_collision_stiffness * a * a;\n                }\n            }\n\n            return sum;\n        };\n\n        const auto calcInternalPotentialGrad = [&](const Eigen::VectorXd& x) -> Eigen::VectorXd\n        {\n            Eigen::VectorXd sum = Eigen::VectorXd::Zero(x.size());\n            for (std::size_t elem_index = 0; elem_index < num_elems; ++elem_index)\n            {\n                const auto& indices = m_mesh.elems.col(elem_index);\n\n                // Retrieve precomputed values\n                const auto& D_m_inv  = m_mesh.rest_shape_mat_inv_array[elem_index];\n                const auto& vol      = m_mesh.volume_array[elem_index];\n                const auto& vec_PFPx = m_mesh.vec_PFPx_array[elem_index];\n\n                // Calculate the deformation gradient $\\mathbf{F}$\n                const auto F = elasty::fem::calcTetrahedronDeformGrad(x.segment<3>(3 * indices[0]),\n                                                                      x.segment<3>(3 * indices[1]),\n                                                                      x.segment<3>(3 * indices[2]),\n                                                                      x.segment<3>(3 * indices[3]),\n                                                                      D_m_inv);\n\n                // Calculate $\\frac{\\partial \\Phi}{\\partial \\mathbf{x}}$ and related values\n                const auto P      = calcPiolaStress(F);\n                const auto vec_P  = Eigen::Map<const Eigen::Matrix<double, 9, 1>>(P.data(), P.size());\n                const auto PPsiPx = vec_PFPx.transpose() * vec_P;\n\n                // Calculate $\\frac{\\partial E}{\\partial \\mathbf{x}}$\n                const auto PEPx = vol * PPsiPx;\n\n                sum.segment<3>(3 * indices[0]) += PEPx.segment<3>(0 * 3);\n                sum.segment<3>(3 * indices[1]) += PEPx.segment<3>(1 * 3);\n                sum.segment<3>(3 * indices[2]) += PEPx.segment<3>(2 * 3);\n                sum.segment<3>(3 * indices[3]) += PEPx.segment<3>(3 * 3);\n            }\n\n            for (const auto& constraint : m_constraints)\n            {\n                const std::size_t vert_index = constraint.vert_index;\n                const double&     k          = constraint.stiffness;\n                const auto        p          = x.segment<3>(vert_index * 3);\n                const auto        q          = constraint.motion(m_physics_time + m_delta_physics_time);\n                const auto        r          = p - q;\n\n                sum.segment<3>(3 * vert_index) += k * r;\n            }\n\n            // Collision energy\n            for (const auto& collision : collisions)\n            {\n                const auto&  vert_index = collision.vert_index;\n                const auto   pos        = x.segment<3>(vert_index * 3);\n                const auto&  normal     = collision.surface_normal;\n                const double a          = (collision.surface_pos - pos).transpose() * normal;\n\n                if (a > 0.0)\n                {\n                    sum.segment<3>(3 * vert_index) += 2.0 * k_collision_stiffness * a * (-normal);\n                }\n            }\n\n            return sum;\n        };\n\n        const auto calcMomentumPotential = [&](const Eigen::VectorXd& x)\n        {\n            return (0.5 / (h * h)) * (x - y).transpose() * m_mesh.lumped_mass.asDiagonal() * (x - y);\n        };\n\n        const auto calcMomentumPotentialGrad = [&](const Eigen::VectorXd& x) -> Eigen::VectorXd\n        {\n            return (1.0 / (h * h)) * m_mesh.lumped_mass.asDiagonal() * (x - y);\n        };\n\n        const auto calcObjective = [&](const Eigen::VectorXd& x)\n        {\n            const double momentum_potential = calcMomentumPotential(x);\n            const double internal_potential = calcInternalPotential(x);\n\n            assert(momentum_potential >= 0.0);\n            assert(internal_potential >= 0.0);\n\n            return momentum_potential + internal_potential;\n        };\n\n        const auto calcObjectiveGrad = [&](const Eigen::VectorXd& x) -> Eigen::VectorXd\n        {\n            return calcMomentumPotentialGrad(x) + calcInternalPotentialGrad(x);\n        };\n\n        // Solve the minimization problem\n        unsigned        num_iters;\n        Eigen::VectorXd x_opt;\n        mathtoolbox::optimization::RunLBfgs(y, calcObjective, calcObjectiveGrad, 1e-06, 50, x_opt, num_iters);\n\n        // Update the internal state\n        m_mesh.v = (1.0 / h) * (x_opt - m_mesh.x);\n        m_mesh.x = x_opt;\n\n        // Apply velocity correction: a naive damping\n        m_mesh.v *= std::exp(-k_damping_factor * m_delta_physics_time);\n\n        // Apply velocity correction: a naive friction\n        for (const auto& collision : collisions)\n        {\n            const auto v_i = m_mesh.v.segment<3>(collision.vert_index * 3);\n\n            m_mesh.v.segment<3>(collision.vert_index * 3) =\n                v_i.dot(collision.surface_normal) * collision.surface_normal;\n        }\n\n        // Update time counter\n        m_physics_time += m_delta_physics_time;\n    }\n\n    void initializeScene()\n    {\n#ifdef USE_EXTERNAL_TETRA_MESH\n        // Load a tetrahedral mesh\n        m_mesh = ReadTetraMesh(\"./assets/torus.mesh\");\n\n        const std::size_t num_verts = m_mesh.x_rest.size() / 3;\n        const std::size_t num_elems = m_mesh.elems.cols();\n\n        // Set initial conditions\n        constexpr double k_pi = 3.141592653589793238;\n\n        const auto offset = Eigen::Vector3d{0.0, 1.5, 0.0};\n        const auto rotate = Eigen::AngleAxisd(0.5 * k_pi, Eigen::Vector3d::UnitX());\n\n        for (std::size_t vert_index = 0; vert_index < num_verts; ++vert_index)\n        {\n            m_mesh.x.segment<3>(vert_index * 3) = offset + rotate * m_mesh.x.segment<3>(vert_index * 3);\n        }\n#else\n        constexpr std::size_t num_blocks_x = 16;\n        constexpr std::size_t num_blocks_y = 4;\n        constexpr std::size_t num_blocks_z = 4;\n        constexpr std::size_t num_verts    = (num_blocks_x + 1) * (num_blocks_y + 1) * (num_blocks_z + 1);\n        constexpr std::size_t num_elems    = num_blocks_x * num_blocks_y * num_blocks_z * 5;\n        constexpr double      scale        = 0.5 / num_blocks_y;\n\n        m_mesh.elems.resize(4, num_elems);\n        m_mesh.x_rest.resize(num_verts * 3);\n\n        for (std::size_t i_z = 0; i_z < num_blocks_z; ++i_z)\n        {\n            for (std::size_t i_y = 0; i_y < num_blocks_y; ++i_y)\n            {\n                for (std::size_t i_x = 0; i_x < num_blocks_x; ++i_x)\n                {\n                    const std::size_t block_index = i_x + num_blocks_x * i_y + num_blocks_x * num_blocks_y * i_z;\n                    const std::size_t vert_base_index =\n                        i_x + (num_blocks_x + 1) * i_y + (num_blocks_x + 1) * (num_blocks_y + 1) * i_z;\n                    const std::size_t     elem_base_index = 5 * block_index;\n                    const Eigen::Vector3d vert_base_pos{i_x, i_y, i_z};\n\n                    const std::size_t indices[] = {vert_base_index,\n                                                   vert_base_index + 1,\n                                                   vert_base_index + (num_blocks_x + 1),\n                                                   vert_base_index + (num_blocks_x + 1) + 1,\n                                                   vert_base_index + (num_blocks_x + 1) * (num_blocks_y + 1),\n                                                   vert_base_index + (num_blocks_x + 1) * (num_blocks_y + 1) + 1,\n                                                   vert_base_index + (num_blocks_x + 1) * (num_blocks_y + 2),\n                                                   vert_base_index + (num_blocks_x + 1) * (num_blocks_y + 2) + 1};\n\n                    m_mesh.elems.col(elem_base_index + 0) << indices[0], indices[4], indices[1], indices[2];\n                    m_mesh.elems.col(elem_base_index + 1) << indices[2], indices[7], indices[1], indices[3];\n                    m_mesh.elems.col(elem_base_index + 2) << indices[6], indices[2], indices[7], indices[4];\n                    m_mesh.elems.col(elem_base_index + 3) << indices[5], indices[1], indices[4], indices[7];\n                    m_mesh.elems.col(elem_base_index + 4) << indices[1], indices[2], indices[4], indices[7];\n\n                    m_mesh.x_rest.segment<3>(indices[0] * 3) << 0.0, 0.0, 0.0;\n                    m_mesh.x_rest.segment<3>(indices[1] * 3) << 1.0, 0.0, 0.0;\n                    m_mesh.x_rest.segment<3>(indices[2] * 3) << 0.0, 1.0, 0.0;\n                    m_mesh.x_rest.segment<3>(indices[3] * 3) << 1.0, 1.0, 0.0;\n                    m_mesh.x_rest.segment<3>(indices[4] * 3) << 0.0, 0.0, 1.0;\n                    m_mesh.x_rest.segment<3>(indices[5] * 3) << 1.0, 0.0, 1.0;\n                    m_mesh.x_rest.segment<3>(indices[6] * 3) << 0.0, 1.0, 1.0;\n                    m_mesh.x_rest.segment<3>(indices[7] * 3) << 1.0, 1.0, 1.0;\n\n                    for (std::size_t i = 0; i < 8; ++i)\n                    {\n                        m_mesh.x_rest.segment<3>(indices[i] * 3) += vert_base_pos;\n                    }\n                }\n            }\n        }\n\n        // Set transform\n        for (std::size_t vert = 0; vert < num_verts; ++vert)\n        {\n            m_mesh.x_rest[3 * vert + 1] -= 0.5 * num_blocks_y;\n            m_mesh.x_rest[3 * vert + 2] -= 0.5 * num_blocks_z;\n        }\n        m_mesh.x_rest *= scale;\n\n        // Initialize other values\n        m_mesh.x = m_mesh.x_rest;\n        m_mesh.v = Eigen::VectorXd::Zero(3 * num_verts);\n        m_mesh.f = Eigen::VectorXd::Zero(3 * num_verts);\n\n        // Set constraints\n        for (std::size_t i_z = 0; i_z < num_blocks_z + 1; ++i_z)\n        {\n            for (std::size_t i_y = 0; i_y < num_blocks_y + 1; ++i_y)\n            {\n                const std::size_t i_x = 0;\n\n                const std::size_t vert_index =\n                    i_x + (num_blocks_x + 1) * i_y + (num_blocks_x + 1) * (num_blocks_y + 1) * i_z;\n\n                const auto motion = [&, vert_index](double) -> Eigen::Vector3d\n                {\n                    return m_mesh.x_rest.segment<3>(vert_index * 3);\n                };\n\n                m_constraints.push_back(Constraint{vert_index, motion, k_spring_stiffness});\n            }\n        }\n        for (std::size_t i_z = 0; i_z < num_blocks_z + 1; ++i_z)\n        {\n            for (std::size_t i_y = 0; i_y < num_blocks_y + 1; ++i_y)\n            {\n                const std::size_t i_x = num_blocks_x;\n\n                const std::size_t vert_index =\n                    i_x + (num_blocks_x + 1) * i_y + (num_blocks_x + 1) * (num_blocks_y + 1) * i_z;\n\n                const auto motion = [&, vert_index](double t) -> Eigen::Vector3d\n                {\n                    constexpr double pi = 3.1415926535897932;\n\n                    const auto ease = [](double x)\n                    {\n                        return x < 0.5 ? 4.0 * x * x * x : 1.0 - 0.5 * std::pow(-2.0 * x + 2.0, 3.0);\n                    };\n\n                    const auto   x_init    = m_mesh.x_rest.segment<3>(vert_index * 3);\n                    const auto   axis      = Eigen::Vector3d::UnitX();\n                    const double t_0       = 0.5;\n                    const double t_1       = t_0 + 2.0;\n                    const double a         = (t < t_0) ? 0.0 : ((t < t_1) ? t - t_0 : t_1 - t_0);\n                    const double b         = ease(a / 2.0);\n                    const double total_rot = 1.5 * pi;\n\n                    return Eigen::AngleAxisd(total_rot * b, axis) * x_init;\n                };\n\n                m_constraints.push_back(Constraint{vert_index, motion, k_spring_stiffness});\n            }\n        }\n#endif\n\n        // Perform precomputation\n        m_mesh.volume_array.resize(num_elems);\n        m_mesh.rest_shape_mat_inv_array.resize(num_elems);\n        m_mesh.vec_PFPx_array.resize(num_elems);\n        for (std::size_t elem_index = 0; elem_index < num_elems; ++elem_index)\n        {\n            const auto& indices = m_mesh.elems.col(elem_index);\n\n            const auto& x_0 = m_mesh.x_rest.segment<3>(3 * indices[0]);\n            const auto& x_1 = m_mesh.x_rest.segment<3>(3 * indices[1]);\n            const auto& x_2 = m_mesh.x_rest.segment<3>(3 * indices[2]);\n            const auto& x_3 = m_mesh.x_rest.segment<3>(3 * indices[3]);\n\n            m_mesh.volume_array[elem_index]             = elasty::fem::calcTetrahedronVolume(x_0, x_1, x_2, x_3);\n            m_mesh.rest_shape_mat_inv_array[elem_index] = elasty::fem::calc3dShapeMatrix(x_0, x_1, x_2, x_3).inverse();\n            m_mesh.vec_PFPx_array[elem_index] =\n                elasty::fem::calcVecTetrahedronPartDeformGradPartPos(m_mesh.rest_shape_mat_inv_array[elem_index]);\n\n            assert(!m_mesh.rest_shape_mat_inv_array[elem_index].hasNaN());\n        }\n        m_mesh.lumped_mass = elasty::fem::calcTetraMeshLumpedMass(m_mesh.x_rest, m_mesh.elems, m_mesh.mass);\n    }\n\n    /// \\brief Getter of the delta physics time.\n    ///\n    /// \\details The value equals to the delta frame time devided by the number of substeps.\n    double getDeltaPhysicsTime() const { return m_delta_physics_time; }\n\n    void setDeltaPhysicsTime(const double delta_physics_time) { m_delta_physics_time = delta_physics_time; }\n\n    const TetraMesh* getMesh() const { return &m_mesh; }\n\nprivate:\n    double m_delta_physics_time = 1.0 / 60.0;\n    double m_physics_time       = 0.0;\n\n    std::vector<Constraint> m_constraints;\n\n    TetraMesh m_mesh;\n};\n\nint main(int argc, char** argv)\n{\n    VariationalImplicit3dEngine engine;\n\n    engine.initializeScene();\n    engine.setDeltaPhysicsTime(k_delta_time / static_cast<double>(k_num_substeps));\n\n    const auto        mesh      = engine.getMesh();\n    const std::size_t num_verts = mesh->x_rest.size() / 3;\n    const std::size_t num_elems = mesh->elems.cols();\n\n    auto alembic_manager = elasty::createTetraMeshAlembicManager(\n        \"./out.abc\", k_delta_time, num_verts, num_elems, mesh->x.data(), mesh->elems.data());\n\n    for (unsigned int frame = 0; frame < 240; ++frame)\n    {\n        timer::Timer t(std::to_string(frame));\n\n        alembic_manager->submitCurrentStatus();\n\n        for (int i = 0; i < k_num_substeps; ++i)\n        {\n            engine.proceedFrame();\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "8679c75e0db4efb38569524fca4295c6a2b0df85", "size": 21093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/variational-implicit-3d/main.cpp", "max_stars_repo_name": "yuki-koyama/elasty", "max_stars_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 176.0, "max_stars_repo_stars_event_min_datetime": "2019-04-27T00:45:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:15:45.000Z", "max_issues_repo_path": "examples/variational-implicit-3d/main.cpp", "max_issues_repo_name": "yuki-koyama/elasty", "max_issues_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2019-04-27T00:00:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T07:01:12.000Z", "max_forks_repo_path": "examples/variational-implicit-3d/main.cpp", "max_forks_repo_name": "yuki-koyama/elasty", "max_forks_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T01:09:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:30:41.000Z", "avg_line_length": 40.5634615385, "max_line_length": 119, "alphanum_fraction": 0.5401792064, "num_tokens": 5329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5018810997588512}}
{"text": "#define BOOST_TEST_MODULE \"FCL_SIMPLE\"\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include \"fcl/intersect.h\"\r\n#include \"fcl/collision.h\"\r\n#include \"fcl/BVH/BVH_model.h\"\r\n#include \"fcl_resources/config.h\"\r\n#include <boost/filesystem.hpp>\r\n#include <sstream>\r\n#include \"fcl/math/vec_nf.h\"\r\n#include \"fcl/math/sampling.h\"\r\n\r\nusing namespace fcl;\r\n\r\nstatic FCL_REAL epsilon = 1e-6;\r\n\r\nstatic bool approx(FCL_REAL x, FCL_REAL y)\r\n{\r\n  return std::abs(x - y) < epsilon;\r\n}\r\n\r\n\r\n\r\ntemplate<std::size_t N>\r\ndouble distance_Vecnf(const Vecnf<N>& a, const Vecnf<N>& b)\r\n{\r\n  double d = 0;\r\n  for(std::size_t i = 0; i < N; ++i)\r\n    d += (a[i] - b[i]) * (a[i] - b[i]);\r\n\r\n  return d;\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(Vec_nf_test)\r\n{\r\n  Vecnf<4> a;\r\n  Vecnf<4> b;\r\n  for(std::size_t i = 0; i < a.dim(); ++i)\r\n    a[i] = i;\r\n  for(std::size_t i = 0; i < b.dim(); ++i)\r\n    b[i] = 1;\r\n\r\n  std::cout << a << std::endl;\r\n  std::cout << b << std::endl;\r\n  std::cout << a + b << std::endl;\r\n  std::cout << a - b << std::endl;\r\n  std::cout << (a -= b) << std::endl;\r\n  std::cout << (a += b) << std::endl;\r\n  std::cout << a * 2 << std::endl;\r\n  std::cout << a / 2 << std::endl;\r\n  std::cout << (a *= 2) << std::endl;\r\n  std::cout << (a /= 2) << std::endl;\r\n  std::cout << a.dot(b) << std::endl;\r\n\r\n  Vecnf<8> c = combine(a, b);\r\n  std::cout << c << std::endl;\r\n\r\n  Vecnf<4> upper, lower;\r\n  for(int i = 0; i < 4; ++i)\r\n    upper[i] = 1;\r\n\r\n  Vecnf<4> aa(std::vector<FCL_REAL>({1,2}));\r\n  std::cout << aa << std::endl;\r\n\r\n  SamplerR<4> sampler(lower, upper);\r\n  for(std::size_t i = 0; i < 10; ++i)\r\n    std::cout << sampler.sample() << std::endl;\r\n\r\n  // Disabled broken test lines. Please see #25.\r\n  // SamplerSE2 sampler2(0, 1, -1, 1);\r\n  // for(std::size_t i = 0; i < 10; ++i)\r\n  //   std::cout << sampler2.sample() << std::endl;\r\n\r\n  SamplerSE3Euler sampler3(Vec3f(0, 0, 0), Vec3f(1, 1, 1));\r\n  for(std::size_t i = 0; i < 10; ++i)\r\n    std::cout << sampler3.sample() << std::endl;\r\n  \r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(projection_test_line)\r\n{\r\n  Vec3f v1(0, 0, 0);\r\n  Vec3f v2(2, 0, 0);\r\n    \r\n  Vec3f p(1, 0, 0);\r\n  Project::ProjectResult res = Project::projectLine(v1, v2, p);\r\n  BOOST_CHECK(res.encode == 3);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.5));\r\n    \r\n  p = Vec3f(-1, 0, 0);\r\n  res = Project::projectLine(v1, v2, p);\r\n  BOOST_CHECK(res.encode == 1);\r\n  BOOST_CHECK(approx(res.sqr_distance, 1));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n\r\n  p = Vec3f(3, 0, 0);\r\n  res = Project::projectLine(v1, v2, p);\r\n  BOOST_CHECK(res.encode == 2);\r\n  BOOST_CHECK(approx(res.sqr_distance, 1));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1));\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(projection_test_triangle)\r\n{\r\n  Vec3f v1(0, 0, 1);\r\n  Vec3f v2(0, 1, 0);\r\n  Vec3f v3(1, 0, 0);\r\n\r\n  Vec3f p(1, 1, 1);\r\n  Project::ProjectResult res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 7);\r\n  BOOST_CHECK(approx(res.sqr_distance, 4/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 1/3.0));\r\n  \r\n  p = Vec3f(0, 0, 1.5);\r\n  res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 1);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n\r\n  p = Vec3f(1.5, 0, 0);\r\n  res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 4);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 1));\r\n\r\n  p = Vec3f(0, 1.5, 0);\r\n  res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 2);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n\r\n  p = Vec3f(1, 1, 0);\r\n  res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 6);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0.5));\r\n\r\n  p = Vec3f(1, 0, 1);\r\n  res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 5);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0.5));\r\n\r\n  p = Vec3f(0, 1, 1);\r\n  res = Project::projectTriangle(v1, v2, v3, p);\r\n  BOOST_CHECK(res.encode == 3);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(projection_test_tetrahedron)\r\n{\r\n  Vec3f v1(0, 0, 1);\r\n  Vec3f v2(0, 1, 0);\r\n  Vec3f v3(1, 0, 0);\r\n  Vec3f v4(1, 1, 1);\r\n\r\n  Vec3f p(0.5, 0.5, 0.5);\r\n  Project::ProjectResult res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 15);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0.25));\r\n\r\n  p = Vec3f(0, 0, 0);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 7);\r\n  BOOST_CHECK(approx(res.sqr_distance, 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n  p = Vec3f(0, 1, 1);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 11);\r\n  BOOST_CHECK(approx(res.sqr_distance, 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 1/3.0));\r\n\r\n  p = Vec3f(1, 1, 0);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 14);\r\n  BOOST_CHECK(approx(res.sqr_distance, 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 1/3.0));\r\n\r\n  p = Vec3f(1, 0, 1);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 13);\r\n  BOOST_CHECK(approx(res.sqr_distance, 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 1/3.0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 1/3.0));\r\n\r\n  p = Vec3f(1.5, 1.5, 1.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 8);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.75));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 1));\r\n\r\n  p = Vec3f(1.5, -0.5, -0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 4);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.75));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 1));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n  p = Vec3f(-0.5, -0.5, 1.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 1);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.75));\r\n  BOOST_CHECK(approx(res.parameterization[0], 1));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n  p = Vec3f(-0.5, 1.5, -0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 2);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.75));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 1));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n  p = Vec3f(0.5, -0.5, 0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 5);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n  p = Vec3f(0.5, 1.5, 0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 10);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0.5));\r\n\r\n  p = Vec3f(1.5, 0.5, 0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 12);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0.5));\r\n    \r\n  p = Vec3f(-0.5, 0.5, 0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 3);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n  p = Vec3f(0.5, 0.5, 1.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 9);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0.5));\r\n    \r\n  p = Vec3f(0.5, 0.5, -0.5);\r\n  res = Project::projectTetrahedra(v1, v2, v3, v4, p);\r\n  BOOST_CHECK(res.encode == 6);\r\n  BOOST_CHECK(approx(res.sqr_distance, 0.25));\r\n  BOOST_CHECK(approx(res.parameterization[0], 0));\r\n  BOOST_CHECK(approx(res.parameterization[1], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[2], 0.5));\r\n  BOOST_CHECK(approx(res.parameterization[3], 0));\r\n\r\n}\r\n", "meta": {"hexsha": "49486f813b84fcf004c6e884dd2f3eecf79d45de", "size": 11098, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_fcl_simple.cpp", "max_stars_repo_name": "tgn3000/fcl", "max_stars_repo_head_hexsha": "dd0dce5023c88c5f98b39234ba8296b15f818e41", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-13T02:38:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T08:03:17.000Z", "max_issues_repo_path": "test/test_fcl_simple.cpp", "max_issues_repo_name": "tgn3000/fcl", "max_issues_repo_head_hexsha": "dd0dce5023c88c5f98b39234ba8296b15f818e41", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-03T11:44:53.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-03T11:44:53.000Z", "max_forks_repo_path": "test/test_fcl_simple.cpp", "max_forks_repo_name": "tgn3000/fcl", "max_forks_repo_head_hexsha": "dd0dce5023c88c5f98b39234ba8296b15f818e41", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-31T09:22:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-30T03:19:24.000Z", "avg_line_length": 35.1202531646, "max_line_length": 78, "alphanum_fraction": 0.6496666066, "num_tokens": 3807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5018416780783056}}
{"text": "/* Copyright \u00a9 2017 Apple Inc. All rights reserved.\n *\n * Use of this source code is governed by a BSD-3-clause license that can\n * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n */\n// Probabilistic Reasoning Library (PRL)\n// Copyright 2009 (see AUTHORS.txt for a list of contributors)\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 2.1 of the License, or (at your option) any later version.\n//\n// This library 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 GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n#ifndef TURI_STL_UTIL_HPP\n#define TURI_STL_UTIL_HPP\n\n\n#include <set>\n#include <map>\n#include <vector>\n#include <algorithm>\n#include <iterator>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <core/logging/assertions.hpp>\n#include <boost/exception/detail/is_output_streamable.hpp>\n\n// #include <core/storage/serialization/serialize.hpp>\n// #include <core/storage/serialization/set.hpp>\n// #include <core/storage/serialization/map.hpp>\n\nnamespace turi {\n\n  /**\n   * \\ingroup util\n   * \\addtogroup set_and_map Set And Map Utilities\n   * \\brief Some mathematical Set and Map routines.\n   * \\{\n   */\n  // Functions on sets\n  //============================================================================\n\n  /**\n   * computes the union of two sets.\n   */\n  template <typename T>\n  std::set<T> set_union(const std::set<T>& a, const std::set<T>& b) {\n    std::set<T> output;\n    std::set_union(a.begin(), a.end(),\n                   b.begin(), b.end(),\n                   std::inserter(output, output.begin()));\n    return output;\n  }\n\n  /**\n   * computes the union of a set and a value.\n   */\n  template <typename T>\n  std::set<T> set_union(const std::set<T>& a, const T& b) {\n    std::set<T> output = a;\n    output.insert(b);\n    return output;\n  }\n\n  /**\n   * computes the intersect of two sets.\n   */\n  template <typename T>\n  std::set<T> set_intersect(const std::set<T>& a, const std::set<T>& b) {\n    std::set<T> output;\n    std::set_intersection(a.begin(), a.end(),\n                          b.begin(), b.end(),\n                          std::inserter(output, output.begin()));\n    return output;\n  }\n\n  /**\n   * computes the difference of two sets.\n   */\n  template <typename T>\n  std::set<T> set_difference(const std::set<T>& a, const std::set<T>& b) {\n    std::set<T> output;\n    std::set_difference(a.begin(), a.end(),\n                        b.begin(), b.end(),\n                        std::inserter(output, output.begin()));\n    return output;\n  }\n\n\n  /**\n   * Subtract a value from a set\n   */\n  template <typename T>\n  std::set<T> set_difference(const std::set<T>& a, const T& b) {\n    std::set<T> output = a;\n    output.erase(b);\n    return output;\n  }\n\n  /**\n   * Partitions a set with a different set.\n   * Returns 2 sets: <s in partition, s not in partition>\n   */\n  template <typename T>\n  std::pair<std::set<T>,std::set<T> >\n  set_partition(const std::set<T>& s, const std::set<T>& partition) {\n    std::set<T> a, b;\n    a = set_intersect(s, partition);\n    b = set_difference(s, partition);\n    return std::make_pair(a, b);\n  }\n\n  /**\n   * Returns true if the two sets are disjoint\n   */\n  template <typename T>\n  bool set_disjoint(const std::set<T>& a, const std::set<T>& b) {\n    return (intersection_size(a,b) == 0);\n  }\n\n  /**\n   * Returns true if the two sets are equal\n   */\n  template <typename T>\n  bool set_equal(const std::set<T>& a, const std::set<T>& b) {\n    if (a.size() != b.size()) return false;\n    return a == b; // defined in <set>\n  }\n\n  /**\n   * Returns true if b is included in a\n   */\n  template <typename T>\n  bool includes(const std::set<T>& a, const std::set<T>& b) {\n    return std::includes(a.begin(), a.end(), b.begin(), b.end());\n  }\n\n  /**\n   * Returns true if $a \\subseteq b$\n   */\n  template <typename T>\n  bool is_subset(const std::set<T>& a, const std::set<T>& b) {\n    return includes(b, a);\n  }\n\n  /**\n   * Returns true if $b \\subseteq a$\n   */\n  template <typename T>\n  bool is_superset(const std::set<T>& a,const std::set<T>& b) {\n    return includes(a, b);\n  }\n\n  /*\n   * \\internal\n   * Prints a container.\n   */\n  template <typename Container>\n  std::ostream& print_range(std::ostream& out, const Container& c,\n                   const std::string& left, const std::string& sep,const std::string& right) {\n\n    out << left;\n\n    for(auto it = c.begin();;) {\n      if(it == c.end())\n        break;\n\n      out << *it;\n\n      ++it;\n\n      if(it != c.end())\n        out << sep;\n    }\n    out << right << std::endl;\n\n    return out;\n  }\n\n\n  /**\n   * Writes a human representation of the set to the supplied stream.\n   */\n  template <typename T>\n  typename boost::enable_if_c<boost::is_output_streamable<T>::value,\n           std::ostream&>::type\n  operator<<(std::ostream& out, const std::set<T>& s) {\n    return print_range(out, s, \"{\", \", \", \"}\");\n  }\n\n  /**\n   * Writes a human representation of a vector to the supplied stream.\n   */\n  template <typename T>\n  typename boost::enable_if_c<boost::is_output_streamable<T>::value,\n           std::ostream&>::type\n  operator<<(std::ostream& out, const std::vector<T>& v) {\n    return print_range(out, v, \"[\", \", \", \"]\");\n  }\n\n\n  // Functions on maps\n  //============================================================================\n\n  /**\n   * constant lookup in a map. assertion failure of key not found in map\n   */\n  template <typename Key, typename T>\n  const T& safe_get(const std::map<Key, T>& map,\n                    const Key& key) {\n    typedef typename std::map<Key, T>::const_iterator iterator;\n    iterator iter = map.find(key);\n    ASSERT_TRUE(iter != map.end());\n    return iter->second;\n  } // end of safe_get\n\n  /**\n   * constant lookup in a map. If key is not found in map,\n   * 'default_value' is returned. Note that this can't return a reference\n   * and must return a copy\n   */\n  template <typename Key, typename T>\n  const T safe_get(const std::map<Key, T>& map,\n                    const Key& key, const T default_value) {\n    typedef typename std::map<Key, T>::const_iterator iterator;\n    iterator iter = map.find(key);\n    if (iter == map.end())   return default_value;\n    else return iter->second;\n  } // end of safe_get\n\n  /**\n   * Transform each key in the map using the key_map\n   * transformation. The resulting map will have the form\n   * output[key_map[i]] = map[i]\n   */\n  template <typename OldKey, typename NewKey, typename T>\n  std::map<NewKey, T>\n  rekey(const std::map<OldKey, T>& map,\n        const std::map<OldKey, NewKey>& key_map) {\n    std::map<NewKey, T> output;\n    typedef std::pair<OldKey, T> pair_type;\n    for(const pair_type& pair: map) {\n      output[safe_get(key_map, pair.first)] = pair.second;\n    }\n    return output;\n  }\n\n  /**\n   * Transform each key in the map using the key_map\n   * transformation. The resulting map will have the form\n   output[i] = remap[map[i]]\n  */\n  template <typename Key, typename OldT, typename NewT>\n  std::map<Key, NewT>\n  remap(const std::map<Key, OldT>& map,\n        const std::map<OldT, NewT>& val_map) {\n    std::map<Key, NewT> output;\n    typedef std::pair<Key, OldT> pair_type;\n    for(const pair_type& pair: map) {\n      output[pair.first] = safe_get(val_map, pair.second);\n    }\n    return output;\n  }\n\n  /**\n   * Inplace version of remap\n   */\n  template <typename Key, typename T>\n  void remap(std::map<Key, T>& map,\n             const std::map<T, T>& val_map) {\n    typedef std::pair<Key, T> pair_type;\n    for(pair_type& pair: map) {\n      pair.second = safe_get(val_map, pair.second);\n    }\n  }\n\n  /**\n   * Computes the union of two maps\n   */\n  template <typename Key, typename T>\n  std::map<Key, T>\n  map_union(const std::map<Key, T>& a,\n            const std::map<Key, T>& b) {\n    // Initialize the output map\n    std::map<Key, T> output;\n    std::set_union(a.begin(), a.end(),\n                   b.begin(), b.end(),\n                   std::inserter(output, output.begin()),\n                   output.value_comp());\n    return output;\n  }\n\n  /**\n   * Computes the intersection of two maps\n   */\n  template <typename Key, typename T>\n  std::map<Key, T>\n  map_intersect(const std::map<Key, T>& a,\n                const std::map<Key, T>& b) {\n    // Initialize the output map\n    std::map<Key, T> output;\n    // compute the intersection\n    std::set_intersection(a.begin(), a.end(),\n                          b.begin(), b.end(),\n                          std::inserter(output, output.begin()),\n                          output.value_comp());\n    return output;\n  }\n\n  /**\n   * Returns the entries of a map whose keys show up in the set keys\n   */\n  template <typename Key, typename T>\n  std::map<Key, T>\n  map_intersect(const std::map<Key, T>& m,\n                const std::set<Key>& keys) {\n    std::map<Key, T> output;\n    for(const Key& key: keys) {\n      typename std::map<Key,T>::const_iterator it = m.find(key);\n      if (it != m.end())\n        output[key] = it->second;\n    }\n    return output;\n  }\n\n  /**\n   * Computes the difference between two maps\n   */\n  template <typename Key, typename T>\n  std::map<Key, T>\n  map_difference(const std::map<Key, T>& a,\n                 const std::map<Key, T>& b) {\n    // Initialize the output map\n    std::map<Key, T> output;\n    // compute the intersection\n    std::set_difference(a.begin(), a.end(),\n                        b.begin(), b.end(),\n                        std::inserter(output, output.begin()),\n                        output.value_comp());\n    return output;\n  }\n\n\n  /**\n   * Returns the set of keys in a map\n   */\n  template <typename Key, typename T>\n  std::set<Key> keys(const std::map<Key, T>& map) {\n    std::set<Key> output;\n    typedef std::pair<Key, T> pair_type;\n    for(const pair_type& pair: map) {\n      output.insert(pair.first);\n    }\n    return output;\n  }\n\n  /**\n   * Get the set of keys in a map as a vector\n   */\n  template <typename Key, typename T>\n  std::vector<Key> keys_as_vector(const std::map<Key, T>& map) {\n    std::vector<Key> output(map.size());\n    typedef std::pair<Key, T> pair_type;\n    size_t i = 0;\n    for(const pair_type& pair: map) {\n      output[i++] = pair.first;\n    }\n    return output;\n  }\n\n\n  /**\n   * Gets the values from a map\n   */\n  template <typename Key, typename T>\n  std::set<T> values(const std::map<Key, T>& map) {\n    std::set<T> output;\n    typedef std::pair<Key, T> pair_type;\n    for(const pair_type& pair: map) {\n      output.insert(pair.second);\n    }\n    return output;\n  }\n\n  /**\n   * Gets a subset of values from a map\n   */\n  template <typename Key, typename T>\n  std::vector<T> values(const std::map<Key, T>& m,\n                        const std::set<Key>& keys) {\n    std::vector<T> output;\n\n    for(const Key &i: keys) {\n      output.push_back(safe_get(m, i));\n    }\n    return output;\n  }\n\n  /**\n   * Gets a subset of values from a map\n   */\n  template <typename Key, typename T>\n  std::vector<T> values(const std::map<Key, T>& m,\n                        const std::vector<Key>& keys) {\n    std::vector<T> output;\n    for(const Key &i: keys) {\n      output.push_back(safe_get(m, i));\n    }\n    return output;\n  }\n\n  /** Creates an identity map (a map from elements to themselves)\n   */\n  template <typename Key>\n  std::map<Key, Key> make_identity_map(const std::set<Key>& keys) {\n    std::map<Key, Key> m;\n    for(const Key& key: keys)\n      m[key] = key;\n    return m;\n  }\n\n  //! Writes a map to the supplied stream.\n  template <typename Key, typename T>\n  std::ostream& operator<<(std::ostream& out, const std::map<Key, T>& m) {\n    out << \"{\";\n    for (typename std::map<Key, T>::const_iterator it = m.begin();\n         it != m.end();) {\n      out << it->first << \"-->\" << it->second;\n      if (++it != m.end()) out << \" \";\n    }\n    out << \"}\";\n    return out;\n  }\n\n  /** Removes white space (space and tabs) from the beginning and end of str,\n      returning the resultant string\n  */\n  inline std::string trim(const std::string& str) {\n    std::string::size_type pos1 = str.find_first_not_of(\" \\t\");\n    std::string::size_type pos2 = str.find_last_not_of(\" \\t\");\n    return str.substr(pos1 == std::string::npos ? 0 : pos1,\n                      pos2 == std::string::npos ? str.size()-1 : pos2-pos1+1);\n  }\n\n  /**\n  * Convenience function for using std streams to convert anything to a string\n  */\n  template<typename T>\n  std::string tostr(const T& t) {\n    std::stringstream strm;\n    strm << t;\n    return strm.str();\n  }\n\n  /**\n  * Convenience function for using std streams to convert a string to anything\n  */\n  template<typename T>\n  T fromstr(const std::string& str) {\n    std::stringstream strm(str);\n    T elem;\n    strm >> elem;\n    ASSERT_FALSE(strm.fail());\n    return elem;\n  }\n\n  /**\n  Returns a string representation of the number,\n  padded to 'npad' characters using the pad_value character\n  */\n  inline std::string pad_number(const size_t number,\n                                const size_t npad,\n                                const char pad_value = '0') {\n    std::stringstream strm;\n    strm << std::setw((int)npad) << std::setfill(pad_value)\n         << number;\n    return strm.str();\n  }\n\n\n  // inline std::string change_suffix(const std::string& fname,\n  //                                  const std::string& new_suffix) {\n  //   size_t pos = fname.rfind('.');\n  //   assert(pos != std::string::npos);\n  //   const std::string new_base(fname.substr(0, pos));\n  //   return new_base + new_suffix;\n  // } // end of change_suffix\n\n\n  /**\n  Using splitchars as delimiters, splits the string into a vector of strings.\n  if auto_trim is true, trim() is called on all the extracted strings\n  before returning.\n  */\n  inline std::vector<std::string> strsplit(const std::string& str,\n                                           const std::string& splitchars,\n                                           const bool auto_trim = false) {\n    std::vector<std::string> tokens;\n    for(size_t beg = 0, end = 0; end != std::string::npos; beg = end+1) {\n      end = str.find_first_of(splitchars, beg);\n      if(auto_trim) {\n        if(end - beg > 0) {\n          std::string tmp = trim(str.substr(beg, end - beg));\n          if(!tmp.empty()) tokens.push_back(tmp);\n        }\n      } else tokens.push_back(str.substr(beg, end - beg));\n    }\n    return tokens;\n    // size_t pos = 0;\n    // while(1) {\n    //   size_t nextpos = s.find_first_of(splitchars, pos);\n    //   if (nextpos != std::string::npos) {\n    //     ret.push_back(s.substr(pos, nextpos - pos));\n    //     pos = nextpos + 1;\n    //   } else {\n    //     ret.push_back(s.substr(pos));\n    //     break;\n    //   }\n    // }\n    // return ret;\n  }\n\n  /**\n   * \\}\n   */\n}; // end of namespace turi\n\n#endif\n", "meta": {"hexsha": "edfff3f1d0dffaddfaa7978ea1549191d0dc09ad", "size": 15197, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/util/stl_util.hpp", "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/core/util/stl_util.hpp", "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/core/util/stl_util.hpp", "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": 28.1948051948, "max_line_length": 94, "alphanum_fraction": 0.58235178, "num_tokens": 3959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5018416677554844}}
{"text": "#include \"include/core/Ellipsoid.h\"\n\n#include \"src/Polygon/Polygon.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <Eigen/Dense>\n\nnamespace g2o\n{\n    ellipsoid::ellipsoid()\n    {\n    }\n\n    // xyz roll pitch yaw half_scale\n    void ellipsoid::fromMinimalVector(const Vector9d& v){\n        Eigen::Quaterniond posequat = zyx_euler_to_quat(v(3),v(4),v(5));\n        pose = SE3Quat(posequat, v.head<3>());\n        scale = v.tail<3>();\n\n        vec_minimal = v;\n    }\n\n    // xyz quaternion, half_scale\n    void ellipsoid::fromVector(const Vector10d& v){\n        pose.fromVector(v.head<7>());\n        scale = v.tail<3>();\n        vec_minimal = toMinimalVector();\n    }\n\n    const Vector3d& ellipsoid::translation() const {return pose.translation();}\n    void ellipsoid::setTranslation(const Vector3d& t_) {pose.setTranslation(t_);}\n    void ellipsoid::setRotation(const Quaterniond& r_) {pose.setRotation(r_);}\n    void ellipsoid::setRotation(const Matrix3d& R) {pose.setRotation(Quaterniond(R));}\n    void ellipsoid::setScale(const Vector3d &scale_) {scale=scale_;}\n\n    // apply update to current ellipsoid. exponential map\n    ellipsoid ellipsoid::exp_update(const Vector9d& update)\n    {\n        ellipsoid res;\n        res.pose = this->pose*SE3Quat::exp(update.head<6>());\n        res.scale = this->scale + update.tail<3>();\n\n        res.UpdateValueFrom(*this);\n        res.vec_minimal = res.toMinimalVector();\n        return res;\n    }\n\n    // TOBE DELETED.\n    ellipsoid ellipsoid::exp_update_XYZABC(const Vector6d& update)\n    {\n        ellipsoid res;\n\n        Vector6d pose_vec; pose_vec << 0, 0, 0, update[0], update[1], update[2];\n        res.pose = this->pose*SE3Quat::exp(pose_vec); \n        res.scale = this->scale + update.tail<3>();\n\n        res.UpdateValueFrom(*this);\n        res.vec_minimal = res.toMinimalVector();\n        return res;\n    }\n\n    Vector9d ellipsoid::ellipsoid_log_error_9dof(const ellipsoid& newone) const\n    {\n        Vector9d res;\n        SE3Quat pose_diff = newone.pose.inverse()*this->pose;\n\n        res.head<6>() = pose_diff.log(); \n        res.tail<3>() = this->scale - newone.scale; \n        return res;        \n    }\n\n    // change front face by rotate along current body z axis. \n    // another way of representing cuboid. representing same cuboid (IOU always 1)\n    ellipsoid ellipsoid::rotate_ellipsoid(double yaw_angle) const // to deal with different front surface of cuboids\n    {\n        ellipsoid res;\n        SE3Quat rot(Eigen::Quaterniond(cos(yaw_angle*0.5),0,0,sin(yaw_angle*0.5)),Vector3d(0,0,0));   // change yaw to rotation.\n        res.pose = this->pose*rot;\n        res.scale = this->scale;\n        \n        res.UpdateValueFrom(*this);\n        res.vec_minimal = res.toMinimalVector();\n\n        const double eps = 1e-6;\n        if ( (std::abs(yaw_angle-M_PI/2.0) < eps) || (std::abs(yaw_angle+M_PI/2.0) < eps) || (std::abs(yaw_angle-3*M_PI/2.0) < eps))\n            std::swap(res.scale(0),res.scale(1));   \n\n        return res;\n    }\n\n    Vector9d ellipsoid::min_log_error_9dof(const ellipsoid& newone, bool print_details) const\n    {\n        bool whether_rotate_ellipsoid=true;  // whether rotate cube to find smallest error\n        if (!whether_rotate_ellipsoid)\n            return ellipsoid_log_error_9dof(newone);\n\n        // NOTE rotating ellipsoid... since we cannot determine the front face consistenly, different front faces indicate different yaw, scale representation.\n        // need to rotate all 360 degrees (global cube might be quite different from local cube)\n        // this requires the sequential object insertion. In this case, object yaw practically should not change much. If we observe a jump, we can use code\n        // here to adjust the yaw.\n        Vector4d rotate_errors_norm; Vector4d rotate_angles(-1,0,1,2); // rotate -90 0 90 180\n        Eigen::Matrix<double, 9, 4> rotate_errors;\n        for (int i=0;i<rotate_errors_norm.rows();i++)\n        {\n            ellipsoid rotated_cuboid = newone.rotate_ellipsoid(rotate_angles(i)*M_PI/2.0);  // rotate new cuboids\n            Vector9d cuboid_error = this->ellipsoid_log_error_9dof(rotated_cuboid);\n            rotate_errors_norm(i) = cuboid_error.norm();\n            rotate_errors.col(i) = cuboid_error;\n        }\n        int min_label;\n        rotate_errors_norm.minCoeff(&min_label);\n        if (print_details)\n            if (min_label!=1)\n                std::cout<<\"Rotate ellipsoid   \"<<min_label<<std::endl;\n        return rotate_errors.col(min_label);\n    }\n\n    // transform a local cuboid to global cuboid  Twc is camera pose. from camera to world\n    ellipsoid ellipsoid::transform_from(const SE3Quat& Twc) const{\n        ellipsoid res;\n        res.pose = Twc*this->pose;\n        res.scale = this->scale;\n        \n        res.UpdateValueFrom(*this);\n        res.vec_minimal = res.toMinimalVector();\n\n        return res;\n    }\n\n    // transform a global cuboid to local cuboid  Twc is camera pose. from camera to world\n    ellipsoid ellipsoid::transform_to(const SE3Quat& Twc) const{\n        ellipsoid res;\n        res.pose = Twc.inverse()*this->pose;\n        res.scale = this->scale;\n\n        res.UpdateValueFrom(*this);\n        res.vec_minimal = res.toMinimalVector();\n        \n        return res;\n    }\n\n    // xyz roll pitch yaw half_scale\n    Vector9d ellipsoid::toMinimalVector() const{\n        Vector9d v;\n        v.head<6>() = pose.toXYZPRYVector();\n        v.tail<3>() = scale;\n        return v;\n    }\n\n    // xyz quaternion, half_scale\n    Vector10d ellipsoid::toVector() const{\n        Vector10d v;\n        v.head<7>() = pose.toVector();\n        v.tail<3>() = scale;\n        return v;\n    }\n\n    Matrix4d ellipsoid::similarityTransform() const\n    {\n        Matrix4d res = pose.to_homogeneous_matrix();    // 4x4 transform matrix\n        Matrix3d scale_mat = scale.asDiagonal();\n        res.topLeftCorner<3,3>() = res.topLeftCorner<3,3>()*scale_mat;\n        return res;\n    }\n\n\n    void ellipsoid::UpdateValueFrom(const g2o::ellipsoid& e){\n        this->miLabel = e.miLabel;\n        this->mbColor = e.mbColor;\n        this->mvColor = e.mvColor;\n        this->miInstanceID = e.miInstanceID;\n\n        this->prob = e.prob;\n    }\n\n    ellipsoid::ellipsoid(const g2o::ellipsoid &e) {\n        pose = e.pose;\n        scale = e.scale;\n        vec_minimal = e.vec_minimal;\n\n        UpdateValueFrom(e);\n    }\n\n    const ellipsoid& ellipsoid::operator=(const g2o::ellipsoid &e) {\n        pose = e.pose;\n        scale = e.scale;\n        vec_minimal = e.vec_minimal;\n\n        UpdateValueFrom(e);\n        return e;\n    }\n\n    // ************* Functions As Ellipsoids ***************\n    Vector2d ellipsoid::projectCenterIntoImagePoint(const SE3Quat& campose_cw, const Matrix3d& Kalib)\n    {\n        Matrix3Xd  P = generateProjectionMatrix(campose_cw, Kalib);\n\n        Vector3d center_pos = pose.translation();\n        Vector4d center_homo = real_to_homo_coord<double>(center_pos);\n        Vector3d u_homo = P * center_homo;\n        Vector2d u = homo_to_real_coord_vec<double>(u_homo);\n\n        return u;\n    }\n\n    // project the ellipsoid into the image plane, and get an ellipse represented by a Vector5d.\n    // Ellipse: x_c, y_c, theta, axis1, axis2\n    Vector5d ellipsoid::projectOntoImageEllipse(const SE3Quat& campose_cw, const Matrix3d& Kalib) const \n    {\n        Matrix4d Q_star = generateQuadric();\n        Matrix3Xd  P = generateProjectionMatrix(campose_cw, Kalib);\n        Matrix3d C_star = P * Q_star * P.transpose();\n        Matrix3d C = C_star.inverse(); \n        C = C / C(2,2); // normalize\n\n        SelfAdjointEigenSolver<Matrix3d> es(C);    // ascending sort by default\n        VectorXd eigens = es.eigenvalues();\n\n        // If it is an ellipse, the sign of eigen values must be :  1 1 -1 \n        // Ref book : Multiple View Geometry in Computer Vision\n        int num_pos = int(eigens(0)>0) +int(eigens(1)>0) +int(eigens(2)>0);\n        int num_neg = int(eigens(0)<0) +int(eigens(1)<0) +int(eigens(2)<0);\n\n        // matrix to equation coefficients: ax^2+bxy+cy^2+dx+ey+f=0\n        double a = C(0,0);\n        double b = C(0,1)*2;\n        double c = C(1,1);\n        double d = C(0,2)*2;\n        double e = C(2,1)*2;\n        double f = C(2,2);\n\n        // get x_c, y_c, theta, axis1, axis2 from coefficients\n        double delta = c*c - 4.0*a*b;\n        double k = (a*f-e*e/4.0) - pow((2*a*e-c*d),2)/(4*(4*a*b-c*c));\n        double theta = 1/2.0*atan2(b,(a-c));\n        double x_c = (b*e-2*c*d)/(4*a*c-b*b);\n        double y_c = (b*d-2*a*e)/(4*a*c-b*b);\n        double a_2 =  2*(a* x_c*x_c+ c * y_c*y_c+ b *x_c*y_c -1) /(a + c + sqrt((a-c)*(a-c)+b*b));\n        double b_2 =  2*(a*x_c*x_c+c*y_c*y_c+b*x_c*y_c -1) /( a + c - sqrt((a-c)*(a-c)+b*b));\n\n        double axis1= sqrt(a_2);\n        double axis2= sqrt(b_2);\n\n        Vector5d output;\n        output << x_c, y_c, theta, axis1, axis2;\n\n        return output;\n    }\n\n    // Get the bounding box from ellipse in image plane\n    Vector4d ellipsoid::getBoundingBoxFromEllipse(Vector5d &ellipse) const\n    {\n        double a = ellipse[3];\n        double b = ellipse[4];\n        double theta = ellipse[2];\n        double x = ellipse[0];\n        double y = ellipse[1];\n        \n        double cos_theta_2 = cos(theta)*cos(theta);\n        double sin_theta_2 = 1- cos_theta_2;\n\n        double x_limit = sqrt(a*a*cos_theta_2+b*b*sin_theta_2);\n        double y_limit = sqrt(a*a*sin_theta_2+b*b*cos_theta_2);\n\n        Vector4d output;\n        output[0] = x-x_limit; // left up\n        output[1] = y-y_limit;\n        output[2] = x+x_limit; // right down\n        output[3] = y+y_limit;\n\n        return output;\n    }\n\n    // Get projection matrix P = K [ R | t ]\n    Matrix3Xd ellipsoid::generateProjectionMatrix(const SE3Quat& campose_cw, const Matrix3d& Kalib) const\n    {\n        Matrix3Xd identity_lefttop;\n        identity_lefttop.resize(3, 4);\n        identity_lefttop.col(3)=Vector3d(0,0,0);\n        identity_lefttop.topLeftCorner<3,3>() = Matrix3d::Identity(3,3);\n\n        Matrix3Xd proj_mat = Kalib * identity_lefttop;\n        proj_mat = proj_mat * campose_cw.to_homogeneous_matrix();\n\n        return proj_mat;\n    }\n\n    // Get Q^*\n    Matrix4d ellipsoid::generateQuadric() const\n    {\n        Vector4d axisVec;\n        axisVec << 1/(scale[0]*scale[0]), 1/(scale[1]*scale[1]), 1/(scale[2]*scale[2]), -1;\n        Matrix4d Q_c = axisVec.asDiagonal();  \n        Matrix4d Q_c_star = Q_c.inverse();  \n        Matrix4d Q_pose_matrix = pose.to_homogeneous_matrix();   // Twm  model in world,  world to model\n        Matrix4d Q_c_star_trans = Q_pose_matrix * Q_c_star * Q_pose_matrix.transpose(); \n\n        return Q_c_star_trans;\n    }\n\n    // Get the projected bounding box in the image plane of the ellipsoid using a camera pose and a calibration matrix.\n    Vector4d ellipsoid::getBoundingBoxFromProjection(const SE3Quat& campose_cw, const Matrix3d& Kalib) const\n    {\n        Vector5d ellipse = projectOntoImageEllipse(campose_cw, Kalib);\n        return getBoundingBoxFromEllipse(ellipse);\n    }\n\n    Vector3d ellipsoid::getColor(){\n        return mvColor.head(3);\n    }\n\n    Vector4d ellipsoid::getColorWithAlpha(){\n        return mvColor;\n    }\n\n    void ellipsoid::setColor(const Vector3d &color_, double alpha){\n        mbColor = true;\n        mvColor.head<3>() = color_;\n        mvColor[3] = alpha;\n\n    }\n\n    bool ellipsoid::isColorSet(){\n        return mbColor;\n    }\n\n    bool ellipsoid::CheckObservability(const SE3Quat& campose_cw)\n    {\n        Vector3d ellipsoid_center = toMinimalVector().head(3);    // Pwo\n        Vector4d center_homo = real_to_homo_coord_vec<double>(ellipsoid_center);\n\n        Eigen::Matrix4d projMat = campose_cw.to_homogeneous_matrix(); // Tcw\n        Vector4d center_inCameraAxis_homo = projMat * center_homo;   // Pco =  Tcw * Pwo\n        Vector3d center_inCameraAxis = homo_to_real_coord_vec<double>(center_inCameraAxis_homo);\n\n        if( center_inCameraAxis_homo(2) < 0)    // if the center is behind the camera ; z<0\n        {\n            return false;\n        }\n        else\n            return true;\n    }\n\n    // calculate the IoU Error between two axis-aligned ellipsoid\n    double ellipsoid::calculateMIoU(const g2o::ellipsoid& e) const\n    {\n        return calculateIntersectionError(*this, e);\n    }\n\n    double ellipsoid::calculateIntersectionOnZ(const g2o::ellipsoid& e1, const g2o::ellipsoid& e2) const\n    {\n        g2o::SE3Quat pose_diff = e1.pose.inverse() * e2.pose;\n        double z1 = 0; double z2 = pose_diff.translation()[2];\n\n        bool flag_oneBigger = false;\n        if( z1 > z2 )\n            flag_oneBigger = true;\n\n        double length;\n        if( flag_oneBigger )\n        {\n            length = (z2 + e2.scale[2]) - (z1 - e1.scale[2]);   \n        }\n        else \n            length = (z1 + e1.scale[2]) - (z2 - e2.scale[2]);  \n\n        if( length < 0 )\n            length = 0;     // if they are not intersected\n        \n        return length;\n    }\n\n    double ellipsoid::calculateArea(const g2o::ellipsoid& e) const\n    {\n        return e.scale[0]*e.scale[1]*e.scale[2]*8;\n    }\n\n    void OutputPolygon(EllipsoidSLAM::Polygon& polygon, double resolution)\n    {\n        int num = polygon.n;\n        for( int i=0;i<num;i++)\n            std::cout << i << \":\" << polygon[i].x << \", \" << polygon[i].y << std::endl;\n        std::cout << std::endl;\n    }\n\n    // Calculate the intersection area after projected the external cubes of two axis-aligned ellipsoids into XY-Plane.\n    double ellipsoid::calculateIntersectionOnXY(const g2o::ellipsoid& e1, const g2o::ellipsoid& e2) const\n    {\n        // First, get the axis-aligned pose error\n        g2o::SE3Quat pose_diff = e1.pose.inverse() * e2.pose;\n        double x_center1 = 0; double y_center1 = 0;\n\n        double x_center2 = pose_diff.translation()[0];\n        double y_center2 = pose_diff.translation()[1];\n\n        double roll,pitch,yaw;\n        quat_to_euler_zyx(pose_diff.rotation(),roll,pitch,yaw);\n\n        double a1 = std::abs(e1.scale[0]);\n        double b1 = std::abs(e1.scale[1]);\n\n        double a2 = std::abs(e2.scale[0]);\n        double b2 = std::abs(e2.scale[1]);\n\n        // Use polygon to calculate the intersection\n        EllipsoidSLAM::Polygon polygon1, polygon2;\n        double resolution = 0.001;  // m / resolution = pixel\n        polygon1.add(cv::Point(a1/resolution, b1/resolution));    // cvPoint only accepts integer, so use resolution to map meter to pixel ( 0.01 resolution means: 1pixel = 0.01m )\n        polygon1.add(cv::Point(-a1/resolution, b1/resolution)); \n        polygon1.add(cv::Point(-a1/resolution, -b1/resolution)); \n        polygon1.add(cv::Point(a1/resolution, -b1/resolution)); \n\n        double c_length = sqrt(a2*a2+b2*b2);\n\n        double init_theta = CV_PI/2.0 - atan2(a2,b2);\n        Vector4d angle_plus_vec;\n        angle_plus_vec << 0, atan2(a2,b2)*2, CV_PI, CV_PI+atan2(a2,b2)*2;\n        for( int n=0;n<4;n++){\n            double angle_plus = angle_plus_vec[n];  // rotate 90deg for four times\n            double point_x = c_length * cos( init_theta - yaw + angle_plus ) + x_center2;\n            double point_y = c_length * sin( init_theta - yaw + angle_plus ) + y_center2;\n            polygon2.add(cv::Point(point_x/resolution, point_y/resolution));  \n        }\n\n        // calculate the intersection\n        EllipsoidSLAM::Polygon interPolygon;\n        EllipsoidSLAM::intersectPolygon(polygon1, polygon2, interPolygon);\n\n        // eliminate resolution.\n        double inter_area = interPolygon.area();\n        double inter_area_in_m = inter_area * resolution * resolution;\n\n        return inter_area_in_m;\n    }\n\n    double ellipsoid::calculateIntersectionError(const g2o::ellipsoid& e1, const g2o::ellipsoid& e2) const\n    {\n        //          AXB          \n        // IoU = ----------\n        //          AUB\n        //   AXB  =  intersection\n        //   AUB  =  A+B-intersection\n\n        // Error of IoU : 1 - IoU\n        double areaA = std::abs(calculateArea(e1));        \n        std::cout << \"areaA : \" << areaA << std::endl;\n\n        double areaB = std::abs(calculateArea(e2));\n        std::cout << \"areaB : \" << areaB << std::endl;\n\n        double proj_inter = calculateIntersectionOnXY(e1,e2);\n        double z_inter = calculateIntersectionOnZ(e1,e2);\n        std::cout << \"projInter : \" << proj_inter << std::endl;\n        std::cout << \"z_inter : \" << z_inter << std::endl;\n\n        double areaIntersection = proj_inter * z_inter;\n        std::cout << \"areaIntersection : \" << areaIntersection << std::endl;\n\n        double MIoU = 1 - ((areaIntersection) / (areaA + areaB - areaIntersection));\n        std::cout << \"MIoU : \" << MIoU << std::endl;\n        std::cout << \"e1 : \" << e1.toMinimalVector().transpose() << std::endl;\n        std::cout << \"e2 : \" << e2.toMinimalVector().transpose() << std::endl;\n\n        return MIoU;\n    }\n\n    // ***************** Functions as Cubes ******************\n\n    // calculate the external cube of the ellipsoid\n    // 8 corners 3*8 matrix, each row is x y z\n    Matrix3Xd ellipsoid::compute3D_BoxCorner() const\n    {\n        Matrix3Xd corners_body;corners_body.resize(3,8);\n        corners_body<< 1, 1, -1, -1, 1, 1, -1, -1,\n                1, -1, -1, 1, 1, -1, -1, 1,\n                -1, -1, -1, -1, 1, 1, 1, 1;\n        Matrix3Xd corners_world = homo_to_real_coord<double>(similarityTransform()*real_to_homo_coord<double>(corners_body));\n        return corners_world;\n    }\n\n    Matrix2Xd ellipsoid::projectOntoImageBoxCorner(const SE3Quat& campose_cw, const Matrix3d& Kalib) const\n    {\n        Matrix3Xd corners_3d_world = compute3D_BoxCorner();\n        Matrix2Xd corner_2d = homo_to_real_coord<double>(Kalib*homo_to_real_coord<double>(campose_cw.to_homogeneous_matrix()*real_to_homo_coord<double>(corners_3d_world)));\n\n        return corner_2d;\n    }\n\n    // get rectangles after projection  [topleft, bottomright]\n    Vector4d ellipsoid::projectOntoImageRect(const SE3Quat& campose_cw, const Matrix3d& Kalib) const\n    {\n        Matrix2Xd corner_2d = projectOntoImageBoxCorner(campose_cw, Kalib);\n        Vector2d bottomright = corner_2d.rowwise().maxCoeff(); // x y\n        Vector2d topleft = corner_2d.rowwise().minCoeff();\n        return Vector4d(topleft(0),topleft(1),bottomright(0),bottomright(1));\n    }\n\n    // get rectangles after projection  [center, width, height]\n    Vector4d ellipsoid::projectOntoImageBbox(const SE3Quat& campose_cw, const Matrix3d& Kalib) const\n    {\n        Vector4d rect_project = projectOntoImageRect(campose_cw, Kalib);  // top_left, bottom_right  x1 y1 x2 y2\n        Vector2d rect_center = (rect_project.tail<2>()+rect_project.head<2>())/2;\n        Vector2d widthheight = rect_project.tail<2>()-rect_project.head<2>();\n        return Vector4d(rect_center(0),rect_center(1),widthheight(0),widthheight(1));\n    }\n\n} // g2o", "meta": {"hexsha": "ef7b9d3d697208c4badf5b1cff58f33eac6b471d", "size": 18796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/Ellipsoid.cpp", "max_stars_repo_name": "cuijiashuo111/Object-oriented-SLAM", "max_stars_repo_head_hexsha": "4b4ade4fff7290ee66b560fbe9755892d6a0388e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 91.0, "max_stars_repo_stars_event_min_datetime": "2020-04-02T06:47:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T02:52:39.000Z", "max_issues_repo_path": "src/core/Ellipsoid.cpp", "max_issues_repo_name": "moshanATucsd/Object-oriented-SLAM", "max_issues_repo_head_hexsha": "40a32cc99843ef1ccfbabadb573137d9063ac53d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-12T08:53:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T06:55:43.000Z", "max_forks_repo_path": "src/core/Ellipsoid.cpp", "max_forks_repo_name": "moshanATucsd/Object-oriented-SLAM", "max_forks_repo_head_hexsha": "40a32cc99843ef1ccfbabadb573137d9063ac53d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2020-04-02T06:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T17:33:55.000Z", "avg_line_length": 37.0, "max_line_length": 180, "alphanum_fraction": 0.6149712705, "num_tokens": 5275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5018416677554843}}
{"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_EXPOCVT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_EXPOCVT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing expocvt capabilities\n\n    Computes the integer conversion of of the exponent bits\n    for a given exponent in a floating type.\n\n    @par semantic:\n    For any given value @c x of floating type @c T:\n\n    @code\n    as_integer_t<T> r = expocvt(x);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    as_integer_t<T> r = toint(x+Maxexponent<T>();\n    @endcode\n\n  **/\n  as_integer_T<Value> expocvt(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/expocvt.hpp>\n#include <boost/simd/function/simd/expocvt.hpp>\n\n#endif\n", "meta": {"hexsha": "fb66e8a05b25e98b0224dc05bba63b60cce92fa6", "size": 1152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/expocvt.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/expocvt.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/expocvt.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": 24.0, "max_line_length": 100, "alphanum_fraction": 0.5928819444, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5018416677554843}}
{"text": "// The MIT License (MIT)\n// \n// Copyright (c) 2015 Jonathan McCluskey and William Harding\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_DYN_LINK\n\n#include <boost/test/unit_test.hpp>\n#include <gmpxx.h>\n#include <iostream>\n\n#include \"Utilities.h\"\n \nBOOST_AUTO_TEST_CASE(utilties_test_1)\n{\n    std::string str = \"Bob\";\n\n    mpz_class num = Utilities::StringToNumber(str);\n\n    // there is an additional null terminator (that is why 0x00 on end)\n    mpz_class expected_num(\"426F62\", 16);\n    BOOST_CHECK(expected_num == num);\n}\n\nBOOST_AUTO_TEST_CASE(utilties_test_2)\n{\n    std::string expected_str = \"Bob\";\n    mpz_class num(\"426F62\", 16);\n\n    std::string str = Utilities::NumberToString(num);\n    BOOST_CHECK_EQUAL(str, expected_str);\n}\n\nBOOST_AUTO_TEST_CASE(utilties_test_3)\n{\n    mpz_class ans = Utilities::FastExp(11, 13, 53);\n    BOOST_CHECK(ans == 52);\n}\n\nBOOST_AUTO_TEST_CASE(utilties_test_4)\n{\n    mpz_class gcd;\n    mpz_class x;\n    mpz_class y;\n\n    std::tie(gcd, x, y) = Utilities::ExtendedGcd(65, 40);\n    BOOST_CHECK(gcd == 5);\n    BOOST_CHECK(x == -3);\n    BOOST_CHECK(y == 5);\n\n    std::tie(gcd, x, y) = Utilities::ExtendedGcd(1239, 735);\n    BOOST_CHECK(gcd == 21);\n    BOOST_CHECK(x == -16);\n    BOOST_CHECK(y == 27);\n}\n", "meta": {"hexsha": "b1d99ad851362d89b620f8e2a7f95acd451b79a7", "size": 2290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libcrypto/test/check_Utilities.cpp", "max_stars_repo_name": "ToadRedCarp/koolkash-digital-cash-protocol", "max_stars_repo_head_hexsha": "ad8b1ed8fdb79658c7d74934db53463d02c5cb42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libcrypto/test/check_Utilities.cpp", "max_issues_repo_name": "ToadRedCarp/koolkash-digital-cash-protocol", "max_issues_repo_head_hexsha": "ad8b1ed8fdb79658c7d74934db53463d02c5cb42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libcrypto/test/check_Utilities.cpp", "max_forks_repo_name": "ToadRedCarp/koolkash-digital-cash-protocol", "max_forks_repo_head_hexsha": "ad8b1ed8fdb79658c7d74934db53463d02c5cb42", "max_forks_repo_licenses": ["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.9459459459, "max_line_length": 81, "alphanum_fraction": 0.7165938865, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.5018416607648377}}
{"text": "#pragma once\n\n#include <boost/multi_array.hpp>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\n// ------------------------------------------------------------\n#include \"aux/hash_specializations.hpp\"\n#include \"laguerren_impl.hpp\"\n\nnamespace boltzmann {\n\ntemplate <typename NUMERIC>\nclass LaguerreN\n{\n public:\n  typedef NUMERIC numeric_t;\n\n public:\n  LaguerreN(int K)\n      : Y_(K + 1)\n      , K_(K)\n      , is_initialized_(false)\n  {\n  }\n\n  void compute(const std::vector<numeric_t> &x);\n  void compute(const numeric_t *x, unsigned int n);\n\n  unsigned int get_npoints() const { return Y_[0].shape()[1]; }\n\n public:\n  typedef boost::multi_array<numeric_t, 2> array_t;\n\n public:\n  const NUMERIC *get(unsigned int k, unsigned int alpha) const;\n  void info() const;\n\n private:\n  std::vector<array_t> Y_;\n  unsigned int K_;\n  bool is_initialized_;\n};\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC>\nvoid\nLaguerreN<NUMERIC>::compute(const std::vector<numeric_t> &x)\n{\n  compute(x.data(), x.size());\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC>\nvoid\nLaguerreN<NUMERIC>::compute(const numeric_t *x, unsigned int n)\n{\n  // L_n-1\n  std::vector<numeric_t> Lnm1(n);\n  // L_n-2\n  std::vector<numeric_t> Lnm2(n);\n\n  for (unsigned int alpha = 0; alpha <= K_; ++alpha) {\n    Y_[alpha].resize(boost::extents[K_ / 2 + 1][n]);\n    // init\n    for (size_t xi = 0; xi < n; ++xi) {\n      Y_[alpha][0][xi] = boost::math::laguerren(0, alpha, x[xi]);\n      Y_[alpha][1][xi] = boost::math::laguerren(1, alpha, x[xi]);\n    }\n\n    for (unsigned int k = 2; k <= K_ / 2; ++k) {\n      for (size_t xi = 0; xi < n; ++xi) {\n        Y_[alpha][k][xi] = boost::math::laguerren_next(\n            k - 1, alpha, x[xi], Y_[alpha][k - 1][xi], Y_[alpha][k - 2][xi]);\n      }\n    }\n  }\n  is_initialized_ = true;\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC>\nconst NUMERIC *\nLaguerreN<NUMERIC>::get(unsigned int k, unsigned int alpha) const\n{\n  assert(is_initialized_);\n  assert(alpha < Y_.size());\n  assert(k < Y_[alpha].shape()[0]);\n  return Y_[alpha][k].origin();\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC>\nvoid\nLaguerreN<NUMERIC>::info() const\n{\n  unsigned long long int nentries = 0;\n  for (unsigned int alpha = 0; alpha < Y_.size(); ++alpha) {\n    nentries += Y_[alpha].shape()[0] * Y_[alpha].shape()[1];\n  }\n\n  std::cout << \" LaguerreN uses \" << nentries * sizeof(NUMERIC) / 1e6 << \" MB\" << std::endl;\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "f21a2564e9b5804c18f7601f3805f88195e0e9d8", "size": 2640, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spectral/laguerren.hpp", "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/laguerren.hpp", "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/laguerren.hpp", "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": 24.6728971963, "max_line_length": 92, "alphanum_fraction": 0.5446969697, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5018416574326628}}
{"text": "//\n// Created by lejonmcgowan on 5/22/16.\n//\n\n#include <Eigen/Dense>\n#include <include/gtest/gtest.h>\n#include <partitioning/Octree.h>\n#include <geometry/Box.h>\nusing namespace std;\n\nstd::ostream& operator<<(std::ostream& ostream, const Eigen::Vector3f vec3)\n{\n    return ostream << \"(\" << vec3[0] << \",\" << vec3[1] << \",\" << vec3[2] << \")\";\n}\n\nTEST(OctreeTest, splitTest)\n{\n    Octree octree(0, Eigen::Vector3f(0, 0, 0), Eigen::Vector3f(1, 1, 1));\n    octree.split();\n    EXPECT_EQ(octree.nodes[0]->minBounds, Eigen::Vector3f(0, 0, 0));\n    EXPECT_EQ(octree.nodes[0]->maxBounds, Eigen::Vector3f(0.5f, 0.5f, 0.5f));\n\n    EXPECT_EQ(octree.nodes[1]->minBounds, Eigen::Vector3f(0, 0, 0.5f));\n    EXPECT_EQ(octree.nodes[1]->maxBounds, Eigen::Vector3f(0.5f, 0.5f, 1.0f));\n\n    EXPECT_EQ(octree.nodes[2]->minBounds, Eigen::Vector3f(0, 0.5f, 0));\n    EXPECT_EQ(octree.nodes[2]->maxBounds, Eigen::Vector3f(0.5f, 1.0f, 0.5f));\n\n    EXPECT_EQ(octree.nodes[3]->minBounds, Eigen::Vector3f(0, 0.5f, 0.5f));\n    EXPECT_EQ(octree.nodes[3]->maxBounds, Eigen::Vector3f(0.5f, 1.0f, 1.0f));\n\n    EXPECT_EQ(octree.nodes[4]->minBounds, Eigen::Vector3f(0.5f, 0, 0));\n    EXPECT_EQ(octree.nodes[4]->maxBounds, Eigen::Vector3f(1.0f, 0.5f, 0.5f));\n\n    EXPECT_EQ(octree.nodes[5]->minBounds, Eigen::Vector3f(0.5f, 0, 0.5f));\n    EXPECT_EQ(octree.nodes[5]->maxBounds, Eigen::Vector3f(1.0f, 0.5f, 1.0f));\n\n    EXPECT_EQ(octree.nodes[6]->minBounds, Eigen::Vector3f(0.5f, 0.5f, 0));\n    EXPECT_EQ(octree.nodes[6]->maxBounds, Eigen::Vector3f(1.0f, 1.0f, 0.5f));\n\n    EXPECT_EQ(octree.nodes[7]->minBounds, Eigen::Vector3f(0.5f, 0.5f, 0.5f));\n    EXPECT_EQ(octree.nodes[7]->maxBounds, Eigen::Vector3f(1.0f, 1.0f, 1.0f));\n}\n\nTEST(OctreeTest, selfSplitTest)\n{\n    Octree::MAX_SHAPES = 4;\n    Octree::MAX_LEVEL = 5;\n\n    Octree octree(0, Eigen::Vector3f(0, 0, 0), Eigen::Vector3f(1, 1, 1));\n    //because I'm lazy and don't want to calulate the bounds again myself\n    Octree octree2(0, Eigen::Vector3f(0, 0, 0), Eigen::Vector3f(1, 1, 1));\n    octree2.split();\n    std::vector<std::shared_ptr<Box>> boxes;\n    for (int i = 0; i < 8; i++)\n    {\n        Eigen::Vector3f origMin = octree2.nodes[i]->minBounds;\n        Eigen::Vector3f origMax = octree2.nodes[i]->maxBounds;\n\n        Eigen::Vector3f min = origMin + 0.25f * (origMax - origMin);\n        Eigen::Vector3f max = origMax - 0.25f * (origMax - origMin);\n        //  cout << min << \" \" << max << endl;\n        auto box = std::make_shared<Box>(min, max);\n        boxes.push_back(box);\n        octree.addShape(box);\n    }\n\n    EXPECT_NE(octree.nodes[0], nullptr);\n\n    EXPECT_EQ(octree.objects.size(), 0);\n\n    for (int i = 0; i < 8; i++)\n    {\n        EXPECT_TRUE(octree.inTree(boxes[i]));\n        EXPECT_EQ(1, octree.nodes[i]->objects.size());\n    }\n}\n\nTEST(OctreeTest, inTreeTest)\n{\n    Octree::MAX_SHAPES = 10;\n    Octree::MAX_LEVEL = 5;\n\n    Octree octree(0, Eigen::Vector3f(0, 0, 0), Eigen::Vector3f(1, 1, 1));\n    octree.split();\n    std::vector<std::shared_ptr<Box>> boxes;\n    for (int i = 0; i < 8; i++)\n    {\n        Eigen::Vector3f origMin = octree.nodes[i]->minBounds;\n        Eigen::Vector3f origMax = octree.nodes[i]->maxBounds;\n        Eigen::Vector3f length = origMax - origMin;\n\n        Eigen::Vector3f min = origMin + 0.25f * (origMax - origMin);\n        Eigen::Vector3f max = origMax - 0.25f * (origMax - origMin);\n        //  cout << min << \" \" << max << endl;\n        auto box = std::make_shared<Box>(min, max);\n        boxes.push_back(box);\n        octree.addShape(box);\n    }\n\n    EXPECT_EQ(octree.objects.size(), 0);\n\n    for (int i = 0; i < 8; i++)\n    {\n        EXPECT_TRUE(octree.inTree(boxes[i]));\n        EXPECT_EQ(1, octree.nodes[i]->objects.size());\n    }\n\n    //add a box which misses the tree entirely\n    auto box = std::make_shared<Box>(Eigen::Vector3f(1, 1, 1), Eigen::Vector3f(1.5f, 1.5f, 1.5f));\n    octree.addShape(box);\n\n    EXPECT_EQ(octree.objects.size(), 0);\n\n    EXPECT_FALSE(octree.inTree(box));\n\n    //add a box which patrially is in root tree\n    box = std::make_shared<Box>(Eigen::Vector3f(0.75, 0.75, 0.75), Eigen::Vector3f(1.5f, 1.5f, 1.5f));\n    octree.addShape(box);\n\n    EXPECT_EQ(octree.objects.size(), 1);\n\n    EXPECT_TRUE(octree.inTree(box));\n\n    for (int i = 0; i < 8; i++)\n        EXPECT_EQ(1, octree.nodes[i]->objects.size());\n\n}\n\nTEST(OctreeTest, indexTest)\n{\n    Octree::MAX_SHAPES = 10;\n    Octree::MAX_LEVEL = 5;\n\n    Octree octree(0, Eigen::Vector3f(0, 0, 0), Eigen::Vector3f(1, 1, 1));\n    octree.split();\n    std::vector<std::shared_ptr<Box>> boxes;\n    for (int i = 0; i < 8; i++)\n    {\n        Eigen::Vector3f origMin = octree.nodes[i]->minBounds;\n        Eigen::Vector3f origMax = octree.nodes[i]->maxBounds;\n\n        Eigen::Vector3f min;\n        Eigen::Vector3f max;\n        //cout << origMin << \" \" << origMax << \" -> \";\n        min = origMin + 0.25f * (origMax - origMin);\n        max = origMax - 0.25f * (origMax - origMin);\n        //  cout << min << \" \" << max << endl;\n        auto box = std::make_shared<Box>(min, max);\n        boxes.push_back(box);\n        octree.addShape(box);\n    }\n\n    EXPECT_EQ(octree.objects.size(), 0);\n\n    for (int i = 0; i < 8; i++)\n    {\n        EXPECT_EQ(i, octree.getIndices(boxes[i]));\n    }\n}\n\nTEST(OctreeTest, simpleRay)\n{\n    Octree octree(0, Eigen::Vector3f(0, 0, 0), Eigen::Vector3f(1, 1, 1));\n    octree.split();\n    octree.nodes[0]->split();\n    Ray ray(Eigen::Vector3f(0.25, 0.25, 0.25), Eigen::Vector3f(0, 1, 0));\n    octree.getShapes(ray);\n}\n\nstd::ostream& ::MathHelper::operator<<(std::ostream& ostream, const Eigen::Vector3f vec3)\n{\n    return ostream << \"(\" << vec3[0] << \",\" << vec3[1] << \",\" << vec3[2] << \")\";\n}", "meta": {"hexsha": "6697277c175d4c9f009e5a66817e522933be0bc2", "size": 5654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/OctreeTest.cpp", "max_stars_repo_name": "lejonmcgowan/JohnnyTracer1", "max_stars_repo_head_hexsha": "123876abdb184a684a60aed7d5676510c1a2ceb0", "max_stars_repo_licenses": ["MIT"], "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/OctreeTest.cpp", "max_issues_repo_name": "lejonmcgowan/JohnnyTracer1", "max_issues_repo_head_hexsha": "123876abdb184a684a60aed7d5676510c1a2ceb0", "max_issues_repo_licenses": ["MIT"], "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/OctreeTest.cpp", "max_forks_repo_name": "lejonmcgowan/JohnnyTracer1", "max_forks_repo_head_hexsha": "123876abdb184a684a60aed7d5676510c1a2ceb0", "max_forks_repo_licenses": ["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.4942528736, "max_line_length": 102, "alphanum_fraction": 0.5985143261, "num_tokens": 2024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5018416504420162}}
{"text": "#include <boost/test/auto_unit_test.hpp>\r\n\r\n\r\n#include <bq.h>\r\n\r\nBOOST_AUTO_TEST_CASE(v2f_construction) {\r\n\tbq::v2f v2(4.f,2.f);\r\n\r\n\tBOOST_CHECK(v2.x == 4.f);\r\n\tBOOST_CHECK(v2.y == 2.f);\r\n}\r\nBOOST_AUTO_TEST_CASE(v2f_add) {\r\n\tbq::v2f v1(4.f,4.f);\r\n\tbq::v2f v2(4.f, 5.f);\r\n\tv1 += v2;\r\n\tBOOST_CHECK(v1.x == 8.f);\r\n\tBOOST_CHECK(v1.y == 9.f);\r\n}\r\nBOOST_AUTO_TEST_CASE(v2i_construction) {\r\n\tbq::v2i v2(4, 2);\r\n\r\n\tBOOST_CHECK(v2.x == 4);\r\n\tBOOST_CHECK(v2.y == 2);\r\n}\r\nBOOST_AUTO_TEST_CASE(v2i_add) {\r\n\tbq::v2i v1(4, 4);\r\n\tbq::v2i v2(4, 5);\r\n\tv1 += v2;\r\n\tBOOST_CHECK(v1.x == 8);\r\n\tBOOST_CHECK(v1.y == 9);\r\n}", "meta": {"hexsha": "df9a6801ef4cc83d42362b22546bacc28539b27d", "size": 599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/TEST_vec.cpp", "max_stars_repo_name": "brodiequinlan/game-framework", "max_stars_repo_head_hexsha": "4243d9b011e0d17da66874fa77b3b6d7a6c5e440", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-20T02:36:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T02:36:28.000Z", "max_issues_repo_path": "test/src/TEST_vec.cpp", "max_issues_repo_name": "Bobsaggetismine/game-framework", "max_issues_repo_head_hexsha": "4243d9b011e0d17da66874fa77b3b6d7a6c5e440", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-11T01:45:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-11T01:47:43.000Z", "max_forks_repo_path": "test/src/TEST_vec.cpp", "max_forks_repo_name": "Bobsaggetismine/game-framework", "max_forks_repo_head_hexsha": "4243d9b011e0d17da66874fa77b3b6d7a6c5e440", "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.3225806452, "max_line_length": 41, "alphanum_fraction": 0.6026711185, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5017975739489056}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2008 Yee Man Chan\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 gjrgarchmodel.cpp file from test-suite\n\n#ifndef cl_adjoint_gjrgarch_model_impl_hpp\n#define cl_adjoint_gjrgarch_model_impl_hpp\n#pragma once\n\n#include \"utilities.hpp\"\n#include \"adjointtestutilities.hpp\"\n#include \"adjointgjrgarchmodeltest.hpp\"\n#include \"adjointtestbase.hpp\"\n\n#include <boost/make_shared.hpp>\n#include <ql/quantlib.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\n\n#define OUTPUT_FOLDER_NAME \"AdjointGjrgarchmodel\"\n\n\nnamespace\n{\n    enum\n    {\n#if defined CL_GRAPH_GEN\n        // Number of points for dependency plots.\n        pointNo = 15,\n        // Number of points for performance plot.\n        iterNo = 15,\n        // Step for portfolio size for performance testing .\n        step = 1,\n#else\n        // Number of points for dependency plots.\n        pointNo = 1,\n        // Number of points for performance plot.\n        iterNo = 1,\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    struct Variation\n    {\n        static std::deque<std::string > get_columns()\n        {\n            static std::deque<std::string > columns =\n            {\n                \"Volatility\", \"\"\n            };\n\n            return columns;\n        }\n\n        template <typename stream_type>\n        friend inline stream_type&\n            operator << (stream_type& stm, Variation& v)\n        {\n                stm << v.volatility_\n                    << \";\" << v.calibrationError_\n                    << std::endl;\n                return stm;\n            }\n\n        Real volatility_;\n        Real calibrationError_;\n    };\n\n    struct GJRGARCHmodelData\n    {\n\n        GJRGARCHmodelData()\n            : settlement_(Date(5, July, 2002))\n            , dayCounter_(Actual365Fixed())\n            , calendar_(TARGET())\n            , strike_(3400)\n        {\n            Settings::instance().evaluationDate() = settlement_;\n\n            t_ = { 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 105 };\n\n            r_ = { 0.0341\n                , 0.0334\n                , 0.0323\n                , 0.0378\n                , 0.0362\n                , 0.0305\n                , 0.0381\n                , 0.0361\n                , 0.0395\n                , 0.0327\n                , 0.0391\n                , 0.0302\n                , 0.0392\n                , 0.0321\n                , 0.0318 };\n\n            v_ = { 0.3145\n                , 0.3153\n                , 0.3382\n                , 0.3464\n                , 0.3491\n                , 0.3827\n                , 0.4358\n                , 0.4436\n                , 0.5467\n                , 0.55\n                , 0.5604\n                , 0.5716\n                , 0.6724\n                , 0.6895\n                , 0.6942};\n        }\n\n        // Calculate model calibration error with given volatilities.\n        Real calculateGJRGARCHmodelCalibrationError(std::vector<Real> vol)\n        {\n            std::vector<Date> dates;\n            std::vector<Rate> rates;\n            dates.push_back(settlement_);\n            rates.push_back(0.0357);\n            for (Size i = 0; i < vol.size(); i++)\n            {\n                dates.push_back(settlement_ + t_[i]);\n                rates.push_back(r_[i]);\n            }\n\n            // Create handle for YieldTermStructure.\n            Handle<YieldTermStructure> riskFreeTS(boost::shared_ptr<YieldTermStructure>(new ZeroCurve(dates, rates, dayCounter_)));\n            Handle<YieldTermStructure> dividendTS(boost::shared_ptr<YieldTermStructure>(new FlatForward(settlement_, Handle<Quote>(boost::shared_ptr<Quote>(new SimpleQuote(0.0))), dayCounter_)));\n\n            Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(4468.17)));\n\n            // Calculate coef.\n            const Real m1 = beta_ + (alpha_ + gamma_*CumulativeNormalDistribution()(lambda_))\n                *(1.0 + lambda_*lambda_) + gamma_*lambda_*std::exp(-lambda_*lambda_ / 2.0)\n                / std::sqrt(2.0*M_PI);\n            const Real v0 = omega_ / (1.0 - m1);\n\n            // Create gjrgarch process for model.\n            boost::shared_ptr<GJRGARCHProcess> process(new GJRGARCHProcess(\n                riskFreeTS, dividendTS, s0, v0,\n                omega_, alpha_, beta_, gamma_, lambda_, daysPerYear_));\n\n            // Create gjrgarch model using gjrgarch process.\n            boost::shared_ptr<GJRGARCHModel> model(new GJRGARCHModel(process));\n\n            // Create engine.\n            boost::shared_ptr<PricingEngine> engine(new AnalyticGJRGARCHEngine(boost::shared_ptr<GJRGARCHModel>(model)));\n\n            std::vector<boost::shared_ptr<CalibrationHelper>> options;\n\n            for (Size i = 0; i < vol.size(); i++)\n            {\n                Handle<Quote> vol(boost::shared_ptr<Quote>(new SimpleQuote(vol[i])));\n                Period maturity((int)(t_[i] / 7.), Weeks);\n\n                // Create calibration helper.\n                boost::shared_ptr<CalibrationHelper> helper(\n                    new HestonModelHelper(maturity, calendar_,\n                    s0->value(), strike_, vol,\n                    riskFreeTS, dividendTS,\n                    CalibrationHelper::ImpliedVolError));\n\n                // Set engine in helper.\n                helper->setPricingEngine(engine);\n                options.push_back(helper);\n            }\n\n            Real error = 0;\n            // Calculate calibration error before calibration.\n            for (Size i = 0; i < vol.size(); ++i)\n            {\n                const Real diff = options[i]->calibrationError()*100.0;\n                error += diff*diff;\n            }\n\n            // Set optimization method.\n            Simplex om(0.01);\n\n            // Calibrate model.\n            model->calibrate(options, om, EndCriteria(20, 10, 1.0e-2, 1.0e-2, 1.0e-2));\n\n            error = 0;\n            // Calculate calibration error after calibration.\n            for (Size i = 0; i < options.size(); ++i)\n            {\n                const Real diff = options[i]->calibrationError()*100.0;\n                error += diff*diff;\n            }\n\n            return error;\n        }\n\n        void calculateFinDiff(std::vector<Real>& vol, double h, std::vector<Real>& sf_Finite)\n        {\n            Size size = vol.size();\n\n            Real totalCalibrationErrorValue = calculateGJRGARCHmodelCalibrationError(vol);\n\n            for (Size i = 0; i < size; i++)\n            {\n                vol[i] += h;\n                sf_Finite[i] = (calculateGJRGARCHmodelCalibrationError(vol) - totalCalibrationErrorValue) / h;\n                vol[i] -= h;\n            }\n        }\n\n        // Cleanup.\n        SavedSettings backup_;\n\n        // Global data.\n        Date settlement_;\n\n        DayCounter dayCounter_;\n        Calendar calendar_;\n\n        std::vector<Integer> t_;\n        std::vector<Real> r_;\n        std::vector<Real> v_;\n\n        Real strike_;\n\n        const Real omega_ = 2.0e-6;\n        const Real alpha_ = 0.024;\n        const Real beta_ = 0.93;\n        const Real gamma_ = 0.059;\n        const Real lambda_ = 0.1;\n        const Real daysPerYear_ = 365.0;\n    };\n\n\n    struct TestData\n        : public GJRGARCHmodelData\n    {\n        struct Test\n        : public cl::AdjointTest<Test>\n        {\n            Test(Size size, TestData* data)\n            : size_(size)\n            , data_(data)\n            , volatility_(size)\n            , totalCalibrationErrorValue_()\n            {\n                setLogger(&data_->outPerform_);\n\n                for (Size i = 0; i < size_; i++)\n                {\n                    volatility_[i] = data->v_[i];\n                }\n\n            }\n\n            Size indepVarNumber() { return size_; }\n\n            Size depVarNumber() { return 1; }\n\n            Size minPerfIteration() { return iterNumFactor; }\n\n            void recordTape()\n            {\n                cl::Independent(volatility_);\n                calculateTotalError();\n                f_ = std::make_unique<cl::tape_function<double>>(volatility_, totalCalibrationErrorValue_);\n            }\n\n            // Calculates total calibration error.\n            void calculateTotalError()\n            {\n                totalCalibrationErrorValue_.push_back(data_->calculateGJRGARCHmodelCalibrationError(volatility_));\n            }\n\n            // Calculates derivatives using finite difference method.\n            void calcAnalytical()\n            {\n                double h = 1.0e-10;  // shift for finite diff. method\n                analyticalResults_.resize(size_);\n                data_->calculateFinDiff(volatility_, h, analyticalResults_);\n            }\n\n            double relativeTol() const { return 1e-2; }\n\n            double absTol() const { return 1e-10; }\n\n            Size size_;\n            TestData* data_;\n            std::vector<cl::tape_double> volatility_;\n            std::vector<cl::tape_double> totalCalibrationErrorValue_;\n        };\n\n        TestData()\n            : GJRGARCHmodelData()\n\n            , outPerform_(OUTPUT_FOLDER_NAME \"//\"\n              , { { \"filename\", \"AdjointPerformance\" }\n                , { \"not_clear\", \"Not\" }\n                , { \"line_box_width\", \"-5\" }\n                , { \"title\", \"Calibration error differentiation performance with respect to volatility\" }\n                , { \"ylabel\", \"Time (s)\" }\n                , { \"xlabel\", \"Number of volatilities\" }\n                , { \"smooth\", \"default\" }\n                , { \"cleanlog\", \"true\" } })\n\n            , outAdjoint_(OUTPUT_FOLDER_NAME \"//\"\n              , { { \"filename\", \"Adjoint\" }\n                , { \"not_clear\", \"Not\" }\n                , { \"smooth\", \"2\" }\n                , { \"title\", \"Calibration error adjoint differentiation performance with respect to volatility\" }\n                , { \"cleanlog\", \"false\" }\n                , { \"ylabel\", \"Time (s)\" }\n                , { \"xlabel\", \"Number of volatilities\" } })\n\n            , outSize_(OUTPUT_FOLDER_NAME \"//\"\n              , { { \"filename\", \"TapeSize\" }\n                , { \"not_clear\", \"Not\" }\n                , { \"title\", \"Tape size dependence on number of volatilities\" }\n                , { \"cleanlog\", \"false\" }\n                , { \"smooth\", \"default\" }\n                , { \"ylabel\", \"Size (MB)\" }\n                , { \"xlabel\", \"Number of volatilities\" } })\n\n            , out_(OUTPUT_FOLDER_NAME \"//output\"\n              , { { \"filename\", \"CalibrErronVol\" }\n                , { \"ylabel\", \"Calibration Error\" }\n                , { \"not_clear\", \"Not\" }\n                , { \"title\", \"Calibration error on volatility\" }\n                , { \"cleanlog\", \"false\" }\n                , { \"smooth\", \"10\" }\n                , { \"xlabel\", \"Volatility\" } })\n        {\n        }\n\n        bool makeOutput()\n        {\n            bool ok = true;\n            if (pointNo > 0)\n            {\n                ok &= recordDependencePlot();\n            }\n            ok &= cl::recordPerformance(*this, iterNo, step);\n            return ok;\n        }\n\n        std::shared_ptr<Test> getTest(size_t size)\n        {\n            return std::make_shared<Test>(size, this);\n        }\n\n        // Makes plots for strike sensitivity dependence.\n        bool recordDependencePlot()\n        {\n            std::vector<Variation> outData(pointNo);\n            auto test = getTest(pointNo);\n            for (Size i = 0; i < pointNo; i++)\n            {\n                outData[i] = { test->volatility_[i], test->data_->calculateGJRGARCHmodelCalibrationError(std::vector<Real>(1, test->volatility_[i])) };\n            }\n            out_ << outData;\n            return true;\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    typedef TestData::Test GJRGARCHmodelTest;\n}\n\n#endif", "meta": {"hexsha": "7c92289f48512b768b69a8e678aa5c375a5013b0", "size": 12750, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointgjrgarchmodelimpl.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/adjointgjrgarchmodelimpl.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/adjointgjrgarchmodelimpl.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": 32.2784810127, "max_line_length": 195, "alphanum_fraction": 0.521254902, "num_tokens": 3005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5017975704591483}}
{"text": "/*\n * ex5.cpp\n *\n * \t\\brief     Fifth exercixe\n *  \\details   This class reads graph-data. It computes the longest shortest path for starting point 1.\n *  \\author    Julia Baumbach\n *  \\date      03.06.2017\n */\n\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\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/timer/timer.hpp>\n#include \"dijkstra.h\"\n\nusing namespace std;\n\n/**\n * \\param SOURCE_FILE_PATH default file path if none is hand over while starting the programm\n */\nconst char* SOURCE_FILE_PATH = \"testgraph.gph\";\n\n/**\n *\\typedef defines a graph by undirected adjacency-list with weighted edges\n */\nusing graph =  boost::adjacency_list<boost::listS, boost::vecS,\n\tboost::undirectedS, boost::no_property,\n\tboost::property<boost::edge_weight_t, int>>;\n/*\n * \\typedef short version for vertex descriptor from boost::graph_traits\n */\nusing vertex_descriptor = boost::graph_traits < graph >::vertex_descriptor;\n\n/*\n * Main function. Reads some graph data from a given file and computes the longest\n * shortest path to vertex with number 1.\n */\nint main(int argc, char* argv[]){\n\t//Initialize timer for time measurement\n\tboost::timer::cpu_timer timer;\n\n\tif(argc != 3){\n\t\tcerr << \"Invalid method call. Please call with ./ex5 -m1/-m2 FILENAME\" << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tstring method = argv[1];\n\tbool boostMethod = false;\n\tif (method.compare(\"-m1\") == 0){\n\t\tcout << \"Using dijkstra from boost-library\" << endl;\n\t\tboostMethod = true;\n\t} else if (method.compare(\"-m2\") == 0){\n\t\tcout << \"Using my dijkstra\" << endl;\n\t} else {\n\t\tcerr << \"Invalid argument. Please type \\\"-m1\\\" for boost-dijkstra or \\\"-m2\\\" for manual dijkstra.\" << endl;\n\t}\n\n\n\tifstream infile;\n\tinfile.open(argv[2], ios::in);\n\tif (!infile){\n\t\tcout << \"File could not be opened.\" << endl;\n\t\treturn 1;\n\t}\n\n\tstring line;\n\tstringstream s;\n\tunsigned int numberVertices;\n\tunsigned int numberEdges;\n\n\t//Read first line\n\tif (getline(infile, line)){\n\t\ts.str(line);\n\t\ts >> numberVertices >> numberEdges;\n\t\t//Number of vertices is one more than the real number of vertices for storing all the vertices correctly (it's 1-based)\n\t\tnumberVertices++;\n\t} else {\n\t\tcerr << \"Empty file. Exit program\" << endl;\n\t\treturn 1;\n\t}\n\n\t//Reading the edge data\n\tEdges edges;\n\tWeightMap weights;\n\tint startEdge;\n\tint endEdge;\n\tint weight;\n\n\twhile (getline(infile, line)){\n\t\tif (!line.empty()){\n\t\t\ts.clear();\n\t\t\ts.str(line);\n\t\t\ts >> startEdge >> endEdge >> weight;\n\t\t\tedges.push_back(make_pair(startEdge, endEdge));\n\t\t\tweights.push_back(weight);\n\t\t}\n\t}\n\tinfile.close();\n\n\n\tWeightMap weightMap(numberVertices);\n\n\tif (boostMethod){\n\t\t//Creating a graph g\n\t\tgraph g{edges.begin(), edges.end(), weights.begin(), numberVertices};\n\n\t\t//storing the shortest paths and its weights\n\t\tvector<vertex_descriptor> directions(numberVertices);\n\n\t\tboost::dijkstra_shortest_paths(g, 1,//\n\t\t\t\tboost::predecessor_map(//\n\t\t\t\t\t\tboost::make_iterator_property_map(directions.begin(), get(boost::vertex_index, g)))//\n\t\t\t\t.distance_map(//\n\t\t\t\t\t\tboost::make_iterator_property_map(weightMap.begin(), get(boost::vertex_index, g))));\n\t}\n\telse {\n\t\tdijkstra myDijkstra(weights, edges, numberVertices);\n\t\tweightMap = myDijkstra.computeShortestPath(1);\n\t}\n\n\t//Compute the longest shortest path\n\tint weightOfLongestShortestPath = -1;\n\tint indexOfVertex = -1;\n\tint totalWeight;\n\tfor(unsigned int i = 2; i < numberVertices; i++){\n\t\ttotalWeight = weightMap[i];\n\t\tif (totalWeight > weightOfLongestShortestPath){\n\t\t\tweightOfLongestShortestPath = totalWeight;\n\t\t\tindexOfVertex = i;\n\t\t}\n\t}\n\n\tcout << \"RESULT VERTEX \" << indexOfVertex << endl;\n\tcout << \"RESULT DIST \" << weightOfLongestShortestPath << endl;\n\n\t//Print measured time\n\tboost::timer::cpu_times times = timer.elapsed();\n\tcout << \"Wall-clock time: \" << times.wall * 1e-9 << \" seconds\" << endl;\n\tcout << \"User-time: \" << times.user * 1e-9 <<  \" seconds\" << endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "523f90e5c2423908d6ac1f6d434f0f7afea7c461", "size": 3992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Julia/ex5/src/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": "Julia/ex5/src/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": "Julia/ex5/src/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": 26.972972973, "max_line_length": 121, "alphanum_fraction": 0.6941382766, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5017975704591482}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include \"test_gamma.hpp\"\n#ifdef TEST_MPFR\n#include <boost/multiprecision/mpfr.hpp>\n#else\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#endif\n\n\nvoid expected_results()\n{\n   //\n   // Define the max and mean errors expected for\n   // various compilers and platforms.\n   //\n   const char* largest_type;\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())\n   {\n      largest_type = \"(long\\\\s+)?double\";\n   }\n   else\n   {\n      largest_type = \"long double\";\n   }\n#else\n   largest_type = \"(long\\\\s+)?double\";\n#endif\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \".*\",                          // test type(s)\n      \".*near 1.*\",                  // test data group\n      \".*lgamma.*\", 100000000000LL, 100000000000LL);    // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \".*\",                          // test type(s)\n      \".*near 0.*\",                  // test data group\n      \".*lgamma.*\", 300000, 100000);    // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \".*\",                          // test type(s)\n      \".*\",                          // test data group\n      \".*\", 110000, 50000);          // test function\n\n   //\n   // Finish off by printing out the compiler/stdlib/platform names,\n   // we do this to make it easier to mark up expected error rates.\n   //\n   std::cout << \"Tests run with \" << BOOST_COMPILER << \", \"\n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n   expected_results();\n   BOOST_MATH_CONTROL_FP;\n\n#ifdef TEST_MPFR\n   typedef boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<450> > mp_type;\n   const char* name = \"number<mpfr_float_backend<450> >\";\n#else\n   typedef boost::multiprecision::number<boost::multiprecision::cpp_bin_float<450> > mp_type;\n   const char* name = \"number<cpp_bin_float<450> >\";\n#endif\n\n   test_gamma(mp_type(0), name);\n}\n", "meta": {"hexsha": "c89b2db9456b07777153b7530a3b6ac743dc48dd", "size": 2653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/multiprecision/test/math/high_prec/test_gamma.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/multiprecision/test/math/high_prec/test_gamma.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": "deps/src/boost_1_65_1/libs/multiprecision/test/math/high_prec/test_gamma.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "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": 34.0128205128, "max_line_length": 162, "alphanum_fraction": 0.5397663023, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5017975693025541}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/include/functions/lognstat.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/fusion/include/vector_tie.hpp>\n\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n\nNT2_TEST_CASE_TPL( lognstat, NT2_REAL_TYPES)\n{\n  using nt2::lognstat;\n  using nt2::tag::lognstat_;\n  using nt2::sqr;\n\n  NT2_TEST_TYPE_IS( (typename boost::dispatch::meta::call<lognstat_(T, T)>::type)\n                  , (std::pair<T,T>)\n                  );\n\n  T mean;\n  T var;\n  T m = T(1.5);\n  T s = T(2.5);\n  T rm = T(1.020027730826997e+02);\n  T rs = T(5.379293910566451e+06);\n {\n    lognstat(m, s, mean, var);\n    NT2_TEST_ULP_EQUAL(var, rs, 0.5);\n    NT2_TEST_ULP_EQUAL(mean, rm, 0.5);\n  }\n\n  {\n    mean = lognstat(m, s, var);\n    NT2_TEST_ULP_EQUAL(var, rs, 0.5);\n    NT2_TEST_ULP_EQUAL(mean, rm, 0.5);\n  }\n\n  {\n    boost::fusion::vector_tie(mean,var) = lognstat(m, s);\n    NT2_TEST_ULP_EQUAL(var, rs, 0.5);\n    NT2_TEST_ULP_EQUAL(mean, rm, 0.5);\n  }\n\n  {\n    std::pair<T,T> p;\n\n    p = lognstat(m, s);\n    NT2_TEST_ULP_EQUAL(p.first, rm, 0.5);\n    NT2_TEST_ULP_EQUAL(p.second, rs, 0.5);\n  }\n}\n", "meta": {"hexsha": "5bb0c37cf8b05aa861c33825fa089d94ff91141a", "size": 1699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/statistics/unit/scalar/lognstat.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/statistics/unit/scalar/lognstat.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/statistics/unit/scalar/lognstat.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 28.3166666667, "max_line_length": 81, "alphanum_fraction": 0.5609181872, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5017975646562023}}
{"text": "/*\n * Copyright 2015 David A. Boyuka II\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 * interval-encoding.cpp\n *\n *  Created on: Dec 2, 2014\n *      Author: David A. Boyuka II\n */\n\n#include <boost/iterator/counting_iterator.hpp>\n\n#include \"pique/encoding/interval/interval-encoding.hpp\"\n\nauto IntervalIndexEncoding::get_region_math_impl(bin_count_t nbins, bin_id_t lb, bin_id_t ub, bool prefer_complement) const -> RMath {\n\tusing regid_t = region_id_t;\n\n\tconst regid_t nregions = (nbins + 1) / 2; // ceil(nbins / 2)\n\tconst regid_t interval_width = nbins / 2; // floor(nbins / 2)\n\t// Examples:\n\t// nbins == 7: [0, 3), [1, 4), [2, 5), [3, 6)   (interval_width = 3, nregions = 4)\n\t// nbins == 8: [0, 4), [1, 5), [2, 6), [3, 7)   (interval_width = 4, nregions = 4)\n\n\t// If the request interval covers the last bin, we have to use complement\n\tbool complement = false;\n\tif (ub == nbins) {\n\t\tub = lb;\n\t\tlb = 0;\n\t\tcomplement = true;\n\t}\n\n\t// There are five cases, based (with modifications) on this seminal paper, page 6, eqn 6: http://dl.acm.org/citation.cfm?id=304201\n\tRMath rmath;\n\tif (ub < nregions) {\n\t\t// lb < ub < nregions from here\n\t\trmath.push_region((regid_t)lb)\n\t\t     .push_region((regid_t)ub)\n\t\t     .push_op(NArySetOperation::DIFFERENCE);\n\t} else if (lb >= nregions) {\n\t\t// ub >= nregions >= interval_width from previous\n\t\t// lb >= nregions >= interval_width from here\n\t\trmath.push_region((regid_t)ub - interval_width)\n\t\t     .push_region((regid_t)lb - interval_width)\n\t\t     .push_op(NArySetOperation::DIFFERENCE);\n\t} else if (ub - lb < interval_width) {\n\t\t// ub >= nregions >= interval_width from previous\n\t\t// lb < nregions from previous\n\t\t// ub - lb < interval_width from here\n\t\trmath.push_region((regid_t)lb)\n\t\t     .push_region((regid_t)ub - interval_width)\n\t\t     .push_op(NArySetOperation::INTERSECTION);\n\t} else if (ub - lb > interval_width) {\n\t\t// ub >= nregions >= interval_width from previous\n\t\t// lb < nregions from previous\n\t\t// ub - lb >= interval_width from previous\n\t\t// ub - lb > interval_width from here\n\t\trmath.push_region((regid_t)lb)\n\t\t     .push_region((regid_t)ub - interval_width)\n\t\t     .push_op(NArySetOperation::UNION);\n\t} else {\n\t\t// ub >= nregions >= interval_width from previous\n\t\t// lb < nregions from previous\n\t\t// ub - lb == interval_width from previous\n\t\trmath.push_region((regid_t)lb);\n\t}\n\n\t// If we are computing the complement, invert the whole calculation at the end\n\tif (complement)\n\t\trmath.push_op(UnarySetOperation::COMPLEMENT);\n\n\treturn rmath;\n}\n\nauto IntervalIndexEncoding::get_encoded_region_definitions_impl(bin_count_t nbins) const -> std::vector< bin_id_vector_t > {\n\tconst region_id_t nregions = (nbins + 1) / 2; // = ceil(nbins/2)\n\tconst region_id_t interval_width = nbins / 2; //  = floor(nbins/2); intervals are of the form [x, x + interval_width)\n\n\tstd::vector< bin_id_vector_t > enc_region_defs;\n\n\tfor (region_id_t enc_region = 0; enc_region < nregions; ++enc_region) {\n\t\tbin_id_vector_t enc_region_def;\n\t\t// ith encoded region = [ith bin, (i+width) bin)\n\t\tenc_region_def.insert(\n\t\t\tenc_region_def.end(),\n\t\t\tboost::counting_iterator< bin_id_t >(enc_region),\n\t\t\tboost::counting_iterator< bin_id_t >(enc_region + interval_width));\n\t\tenc_region_defs.push_back(enc_region_def);\n\t}\n\n\treturn enc_region_defs;\n}\n\nauto IntervalIndexEncoding::get_encoded_regions_impl(region_vector_t bins, const AbstractSetOperations& setops) const -> region_vector_t {\n\tregion_vector_t enc_regions;\n\tconst region_id_t nregions = (bins.size() + 1) / 2; // = ceil(nbins/2)\n\tconst region_id_t interval_width = bins.size() / 2; //  = floor(nbins/2); intervals are of the form [x, x + interval_width)\n\n\tif (nregions > 0) {\n\t\tboost::shared_ptr< RegionEncoding > first_enc_region =\n\t\t\tsetops.dynamic_nary_set_op(bins.begin(), bins.begin() + interval_width, NArySetOperation::UNION);\n\t\tenc_regions.push_back(first_enc_region);\n\t}\n\n\tfor (region_id_t i = 1; i < nregions; ++i) {\n\t\tboost::shared_ptr< RegionEncoding > enc_region;\n\n\t\t// ith encoded region = (i-1)th encoded region - (i-1)th bin + (i-1+w)th bin\n\t\tenc_region = setops.dynamic_binary_set_op(enc_regions[i - 1], bins[i - 1], NArySetOperation::DIFFERENCE);\n\t\tenc_region = setops.dynamic_inplace_binary_set_op(enc_region, bins[i - 1 + interval_width], NArySetOperation::UNION);\n\t\tenc_regions.push_back(enc_region);\n\t}\n\n\treturn enc_regions;\n}\n", "meta": {"hexsha": "ff813958e0fdf9bb406532bc7190d54867161de0", "size": 4850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/encoding/interval/interval-encoding.cpp", "max_stars_repo_name": "daboyuka/PIQUE", "max_stars_repo_head_hexsha": "d0e2ba4cc47aaeaf364b3c76339306e1795adb5e", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/encoding/interval/interval-encoding.cpp", "max_issues_repo_name": "daboyuka/PIQUE", "max_issues_repo_head_hexsha": "d0e2ba4cc47aaeaf364b3c76339306e1795adb5e", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/encoding/interval/interval-encoding.cpp", "max_forks_repo_name": "daboyuka/PIQUE", "max_forks_repo_head_hexsha": "d0e2ba4cc47aaeaf364b3c76339306e1795adb5e", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.890625, "max_line_length": 138, "alphanum_fraction": 0.7057731959, "num_tokens": 1412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5017737479259559}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \r\n// unit/quantity manipulation and conversion\r\n//\r\n// Copyright (C) 2003-2008 Matthias Christian Schabel\r\n// Copyright (C) 2007-2008 Steven Watanabe\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/** \r\n\\file\r\n    \r\n\\brief quaternion.cpp\r\n\r\n\\details\r\nDemonstrate interoperability with Boost.Quaternion.\r\n\r\nOutput:\r\n@verbatim\r\n\r\n//[quaternion_output_1\r\n+L      = (4,3,2,1) m\r\n-L      = (-4,-3,-2,-1) m\r\nL+L     = (8,6,4,2) m\r\nL-L     = (0,0,0,0) m\r\nL*L     = (2,24,16,8) m^2\r\nL/L     = (1,0,0,0) dimensionless \r\nL^3     = (-104,102,68,34) m^3\r\n//]\r\n\r\n//[quaternion_output_2\r\n+L      = (4 m,3 m,2 m,1 m)\r\n-L      = (-4 m,-3 m,-2 m,-1 m)\r\nL+L     = (8 m,6 m,4 m,2 m)\r\nL-L     = (0 m,0 m,0 m,0 m)\r\nL^3     = (-104 m^3,102 m^3,68 m^3,34 m^3)\r\n//]\r\n\r\n@endverbatim\r\n**/\r\n\r\n#include <iostream>\r\n\r\n#include <boost/math/quaternion.hpp>\r\n#include <boost/mpl/list.hpp>\r\n\r\n#include <boost/units/pow.hpp>\r\n#include <boost/units/quantity.hpp>\r\n#include <boost/units/io.hpp>\r\n\r\n#include \"test_system.hpp\"\r\n\r\n#if BOOST_UNITS_HAS_BOOST_TYPEOF\r\n\r\n#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()\r\n\r\nBOOST_TYPEOF_REGISTER_TEMPLATE(boost::math::quaternion, 1)\r\n\r\n#endif\r\n\r\nnamespace boost {\r\n\r\nnamespace units {\r\n\r\n//[quaternion_class_snippet_1a\r\n/// specialize power typeof helper\r\ntemplate<class Y,long N,long D> \r\nstruct power_typeof_helper<boost::math::quaternion<Y>,static_rational<N,D> >\r\n{ \r\n    // boost::math::quaternion only supports integer powers\r\n    BOOST_STATIC_ASSERT(D==1);\r\n    \r\n    typedef boost::math::quaternion<\r\n        typename power_typeof_helper<Y,static_rational<N,D> >::type\r\n    > type; \r\n    \r\n    static type value(const boost::math::quaternion<Y>& x)  \r\n    {   \r\n        return boost::math::pow(x,static_cast<int>(N));\r\n    }\r\n};\r\n//]\r\n\r\n//[quaternion_class_snippet_1b\r\n/// specialize root typeof helper\r\ntemplate<class Y,long N,long D> \r\nstruct root_typeof_helper<boost::math::quaternion<Y>,static_rational<N,D> >\r\n{ \r\n    // boost::math::quaternion only supports integer powers\r\n    BOOST_STATIC_ASSERT(N==1);\r\n    \r\n    typedef boost::math::quaternion<\r\n        typename root_typeof_helper<Y,static_rational<N,D> >::type\r\n    > type; \r\n    \r\n    static type value(const boost::math::quaternion<Y>& x)  \r\n    { \r\n        return boost::math::pow(x,static_cast<int>(D));\r\n    }\r\n};\r\n//]\r\n\r\n//[quaternion_class_snippet_2a\r\n/// specialize power typeof helper for quaternion<quantity<Unit,Y> >\r\ntemplate<class Unit,long N,long D,class Y> \r\nstruct power_typeof_helper<\r\n    boost::math::quaternion<quantity<Unit,Y> >,\r\n    static_rational<N,D> >                \r\n{ \r\n    typedef typename power_typeof_helper<\r\n        Y,\r\n        static_rational<N,D>\r\n    >::type     value_type;\r\n\r\n    typedef typename power_typeof_helper<\r\n        Unit,\r\n        static_rational<N,D>\r\n    >::type  unit_type;\r\n\r\n    typedef quantity<unit_type,value_type>         quantity_type;\r\n    typedef boost::math::quaternion<quantity_type> type; \r\n    \r\n    static type value(const boost::math::quaternion<quantity<Unit,Y> >& x)  \r\n    { \r\n        const boost::math::quaternion<value_type>   tmp = \r\n            pow<static_rational<N,D> >(boost::math::quaternion<Y>(\r\n                x.R_component_1().value(),\r\n                x.R_component_2().value(),\r\n                x.R_component_3().value(),\r\n                x.R_component_4().value()));\r\n        \r\n        return type(quantity_type::from_value(tmp.R_component_1()),\r\n                    quantity_type::from_value(tmp.R_component_2()),\r\n                    quantity_type::from_value(tmp.R_component_3()),\r\n                    quantity_type::from_value(tmp.R_component_4()));\r\n    }\r\n};\r\n//]\r\n\r\n//[quaternion_class_snippet_2b\r\n/// specialize root typeof helper for quaternion<quantity<Unit,Y> >\r\ntemplate<class Unit,long N,long D,class Y> \r\nstruct root_typeof_helper<\r\n    boost::math::quaternion<quantity<Unit,Y> >,\r\n    static_rational<N,D> >                \r\n{ \r\n    typedef typename root_typeof_helper<\r\n        Y,\r\n        static_rational<N,D>\r\n    >::type      value_type;\r\n\r\n    typedef typename root_typeof_helper<\r\n        Unit,\r\n        static_rational<N,D>\r\n    >::type   unit_type;\r\n\r\n    typedef quantity<unit_type,value_type>         quantity_type;\r\n    typedef boost::math::quaternion<quantity_type> type; \r\n    \r\n    static type value(const boost::math::quaternion<quantity<Unit,Y> >& x)  \r\n    { \r\n        const boost::math::quaternion<value_type>   tmp = \r\n            root<static_rational<N,D> >(boost::math::quaternion<Y>(\r\n                x.R_component_1().value(),\r\n                x.R_component_2().value(),\r\n                x.R_component_3().value(),\r\n                x.R_component_4().value()));\r\n        \r\n        return type(quantity_type::from_value(tmp.R_component_1()),\r\n                    quantity_type::from_value(tmp.R_component_2()),\r\n                    quantity_type::from_value(tmp.R_component_3()),\r\n                    quantity_type::from_value(tmp.R_component_4()));\r\n    }\r\n};\r\n//]\r\n\r\n} // namespace units\r\n\r\n} // namespace boost\r\n\r\nint main(void)\r\n{\r\n    using boost::math::quaternion;\r\n    using namespace boost::units;\r\n    using namespace boost::units::test;\r\n    using boost::units::pow;\r\n    \r\n    {\r\n    //[quaternion_snippet_1\r\n    typedef quantity<length,quaternion<double> >     length_dimension;\r\n        \r\n    length_dimension    L(quaternion<double>(4.0,3.0,2.0,1.0)*meters);\r\n    //]\r\n    \r\n    std::cout << \"+L      = \" << +L << std::endl\r\n              << \"-L      = \" << -L << std::endl\r\n              << \"L+L     = \" << L+L << std::endl\r\n              << \"L-L     = \" << L-L << std::endl\r\n              << \"L*L     = \" << L*L << std::endl\r\n              << \"L/L     = \" << L/L << std::endl\r\n              // unfortunately, without qualification msvc still\r\n              // finds boost::math::pow by ADL.\r\n              << \"L^3     = \" << boost::units::pow<3>(L) << std::endl\r\n//              << \"L^(3/2) = \" << pow< static_rational<3,2> >(L) << std::endl\r\n//              << \"3vL     = \" << root<3>(L) << std::endl\r\n//              << \"(3/2)vL = \" << root< static_rational<3,2> >(L) << std::endl\r\n              << std::endl;\r\n    }\r\n    \r\n    {\r\n    //[quaternion_snippet_2\r\n    typedef quaternion<quantity<length> >     length_dimension;\r\n        \r\n    length_dimension    L(4.0*meters,3.0*meters,2.0*meters,1.0*meters);\r\n    //]\r\n    \r\n    std::cout << \"+L      = \" << +L << std::endl\r\n              << \"-L      = \" << -L << std::endl\r\n              << \"L+L     = \" << L+L << std::endl\r\n              << \"L-L     = \" << L-L << std::endl\r\n//              << \"L*L     = \" << L*L << std::endl\r\n//              << \"L/L     = \" << L/L << std::endl\r\n              << \"L^3     = \" << boost::units::pow<3>(L) << std::endl\r\n//              << \"L^(3/2) = \" << pow< static_rational<3,2> >(L) << std::endl\r\n//              << \"3vL     = \" << root<3>(L) << std::endl\r\n//              << \"(3/2)vL = \" << root< static_rational<3,2> >(L) << std::endl\r\n              << std::endl;\r\n    }\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "73839aef8dba10f21ec55e98facaed02c3bb18e3", "size": 7193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/units/example/quaternion.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/units/example/quaternion.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/units/example/quaternion.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": 30.8712446352, "max_line_length": 80, "alphanum_fraction": 0.549005978, "num_tokens": 1957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5017737411841857}}
{"text": "// Copyright Louis Dionne 2013-2017\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/equal.hpp>\r\n#include <boost/hana/ext/std/tuple.hpp>\r\n#include <boost/hana/mult.hpp>\r\n#include <boost/hana/transform.hpp>\r\n#include <boost/hana/tuple.hpp>\r\n#include <boost/hana/type.hpp>\r\n#include <boost/hana/unpack.hpp>\r\n#include <boost/hana/zip_with.hpp>\r\n\r\n#include <tuple>\r\n#include <type_traits>\r\n#include <utility>\r\nnamespace hana = boost::hana;\r\n\r\n\r\n// Basic usage:\r\nstatic_assert(\r\n    hana::zip_with(hana::mult, hana::make_tuple(1, 2, 3, 4), hana::make_tuple(5, 6, 7, 8))\r\n    ==\r\n    hana::make_tuple(5, 12, 21, 32)\r\n, \"\");\r\n\r\n\r\n\r\n// Example of computing a tuple of all the common types of several tuples:\r\ntemplate<typename... Ts>\r\nusing common_tuple_t = typename decltype(\r\n    hana::unpack(\r\n        hana::zip_with(\r\n            hana::metafunction<std::common_type>,\r\n            hana::transform(std::declval<Ts>(), hana::decltype_)...\r\n        ),\r\n        hana::template_<std::tuple>\r\n    )\r\n)::type;\r\n\r\n\r\nstatic_assert(std::is_same<\r\n    common_tuple_t<\r\n        std::tuple<bool, int, unsigned>,\r\n        std::tuple<char, long, long>,\r\n        std::tuple<int, long long, double>\r\n    >,\r\n    std::tuple<int, long long, double>\r\n>::value, \"\");\r\n\r\nint main() { }\r\n", "meta": {"hexsha": "35fc1ef068dc7698bcce78aafa7be28dafc214ae", "size": 1382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/zip_with.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/hana/example/zip_with.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/hana/example/zip_with.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": 26.5769230769, "max_line_length": 91, "alphanum_fraction": 0.6338639653, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5017737359173522}}
{"text": "// Copyright (c) 2020 Graphcore Ltd. All rights reserved.\n#include \"Constraint.hpp\"\n#include \"Scheduler.hpp\"\n\n#include <popsolver/Model.hpp>\n#define BOOST_TEST_MODULE Min\n#include <boost/test/unit_test.hpp>\n\nusing namespace popsolver;\n\nconst Variable a(0);\nconst Variable b(1);\nconst Variable c(2);\n\nBOOST_AUTO_TEST_CASE(PropagateConstrainResult) {\n  Min min(a, {b, c});\n\n  Domains domains;\n  domains.push_back({DataType{15}, DataType{40}}); // a\n  domains.push_back({DataType{20}, DataType{30}}); // b\n  domains.push_back({DataType{25}, DataType{35}}); // c\n\n  Scheduler scheduler(domains, {&min});\n  BOOST_CHECK(min.propagate(scheduler));\n\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].min(), DataType{20});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].max(), DataType{30});\n\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].min(), DataType{20});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].max(), DataType{30});\n\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].min(), DataType{25});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].max(), DataType{35});\n}\n\nBOOST_AUTO_TEST_CASE(PropagateConstrainValues) {\n  Min min(a, {b, c});\n\n  Domains domains;\n  domains.push_back({DataType{15}, DataType{20}}); // a\n  domains.push_back({DataType{0}, DataType{30}});  // b\n  domains.push_back({DataType{10}, DataType{35}}); // c\n\n  Scheduler scheduler(domains, {&min});\n  BOOST_CHECK(min.propagate(scheduler));\n\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].min(), DataType{15});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].max(), DataType{20});\n\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].min(), DataType{15});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].max(), DataType{30});\n\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].min(), DataType{15});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].max(), DataType{35});\n}\n\nBOOST_AUTO_TEST_CASE(PropagateFailsResultUpperBound) {\n  Min min(a, {b, c});\n\n  Domains domains;\n  domains.push_back({DataType{35}, DataType{40}}); // a\n  domains.push_back({DataType{25}, DataType{30}}); // b\n  domains.push_back({DataType{20}, DataType{35}}); // c\n\n  Scheduler scheduler(domains, {&min});\n  BOOST_CHECK(!min.propagate(scheduler));\n}\n\nBOOST_AUTO_TEST_CASE(PropagateFailsResultLowerBound) {\n  Min min(a, {b, c});\n\n  Domains domains;\n  domains.push_back({DataType{0}, DataType{10}});  // a\n  domains.push_back({DataType{15}, DataType{20}}); // b\n  domains.push_back({DataType{25}, DataType{35}}); // c\n\n  Scheduler scheduler(domains, {&min});\n  BOOST_CHECK(!min.propagate(scheduler));\n}\n\nBOOST_AUTO_TEST_CASE(MinimizeBelowVariable) {\n  Model m;\n\n  const auto b = m.addConstant(5);\n  const auto c = m.addVariable(15, 30);\n\n  const auto a = m.min({b, c});\n  auto s = m.minimize(a);\n  BOOST_CHECK_EQUAL(s[a], DataType{5});\n}\n\nBOOST_AUTO_TEST_CASE(MinimizeInsideVariable) {\n  Model m;\n\n  const auto b = m.addConstant(20);\n  const auto c = m.addVariable(15, 30);\n\n  const auto a = m.min({b, c});\n  auto s = m.minimize(a);\n  BOOST_CHECK_EQUAL(s[a], DataType{15});\n}\n\nBOOST_AUTO_TEST_CASE(MinimizeAboveVariable) {\n  Model m;\n\n  const auto b = m.addConstant(35);\n  const auto c = m.addVariable(15, 30);\n\n  const auto a = m.min({b, c});\n  auto s = m.minimize(a);\n  BOOST_CHECK_EQUAL(s[a], DataType{15});\n}\n", "meta": {"hexsha": "704762df7d8129739c297a401e569df2bf4b8397", "size": 3221, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/popsolver/Min.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/popsolver/Min.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/popsolver/Min.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": 28.5044247788, "max_line_length": 67, "alphanum_fraction": 0.7016454517, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6477982179521102, "lm_q1q2_score": 0.5017737359173521}}
{"text": "#include <limits>\n#include <vector>\n#include <gtest/gtest.h>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/math/tools/promotion.hpp>\n\n#include <stan/math/rev.hpp>\n#include <stan/math/prim/fun/sign.hpp>\n#include <stan/math/prim/fun/fabs.hpp>\n#include <stan/math/prim/fun/log1m.hpp>\n\ntemplate <typename T1, typename T2, typename T3, typename T4>\ninline typename boost::math::tools::promote_args<T1, T2, T3, T4>::type\nskew_de_cdf_test(const T1& y, const T2& mu, const T3& sigma, const T4& tau) {\n  using stan::math::log1m;\n  using std::exp;\n  using std::log;\n\n  if (y < mu) {\n    return log(tau) - 2 / sigma * (1 - tau) * (mu - y);\n  } else {\n    return log1m((1 - tau) * exp(-2 / sigma * tau * (y - mu)));\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential,\n     lcdf_computes_correct_gradients) {\n  using stan::math::skew_double_exponential_lcdf;\n\n  for (double ys : {-1.7, 0.2, 0.5, 0.9, 1.1, 3.2, 8.3}) {\n    for (double mus : {-1.8, 0.1, 0.55, 0.89, 1.3, 4.2, 9.3}) {\n      for (double sigmas : {0.1, 1.1, 3.2}) {\n        for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) {\n          stan::math::var y = ys;\n          stan::math::var mu = mus;\n          stan::math::var sigma = sigmas;\n          stan::math::var tau = taus;\n\n          stan::math::var lp = skew_double_exponential_lcdf(y, mu, sigma, tau);\n          std::vector<stan::math::var> theta;\n          theta.push_back(y);\n          theta.push_back(mu);\n          theta.push_back(sigma);\n          theta.push_back(tau);\n          std::vector<double> grads;\n          lp.grad(theta, grads);\n\n          stan::math::var y_true = ys;\n          stan::math::var mu_true = mus;\n          stan::math::var sigma_true = sigmas;\n          stan::math::var tau_true = taus;\n\n          stan::math::var lp_test\n              = skew_de_cdf_test(y_true, mu_true, sigma_true, tau_true);\n          std::vector<stan::math::var> theta_true;\n          theta_true.push_back(y_true);\n          theta_true.push_back(mu_true);\n          theta_true.push_back(sigma_true);\n          theta_true.push_back(tau_true);\n          std::vector<double> grads_true;\n          lp_test.grad(theta_true, grads_true);\n\n          EXPECT_NEAR(grads_true[0], grads[0], 0.001);\n          EXPECT_NEAR(grads_true[1], grads[1], 0.001);\n          EXPECT_NEAR(grads_true[2], grads[2], 0.001);\n          EXPECT_NEAR(grads_true[3], grads[3], 0.001);\n        }\n      }\n    }\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_scalar_arguments) {\n  using stan::math::skew_double_exponential_lcdf;\n\n  for (double ys : {0.2, 0.9, 1.1, 3.2}) {\n    for (double mus : {0.1, 1.3, 3.0}) {\n      for (double sigmas : {0.1, 1.1, 3.2}) {\n        for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) {\n          EXPECT_NEAR(skew_de_cdf_test(ys, mus, sigmas, taus),\n                      skew_double_exponential_lcdf(ys, mus, sigmas, taus),\n                      0.001);\n        }\n      }\n    }\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_vector_arguments) {\n  using stan::math::skew_double_exponential_lcdf;\n\n  std::vector<double> ys{0.2, 0.9, 1.1, 3.2};\n\n  for (double mus : {0.1, 1.3, 3.0}) {\n    for (double sigmas : {0.1, 1.1, 3.2}) {\n      for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) {\n        double x = 0.0;\n        for (double y : ys)\n          x += skew_de_cdf_test(y, mus, sigmas, taus);\n\n        EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus),\n                    0.001);\n      }\n    }\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential,\n     lcdf_works_on_vectorial_y_and_mu) {\n  using stan::math::skew_double_exponential_lcdf;\n  std::vector<double> ys{0.2, 0.9, 1.1};\n  std::vector<double> mus{0.1, 1.3, 3.0};\n\n  for (double sigmas : {0.1, 1.1, 3.2}) {\n    for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) {\n      double x = 0.0;\n      for (int i = 0; i < 3; i++)\n        x += skew_de_cdf_test(ys[i], mus[i], sigmas, taus);\n\n      EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus),\n                  0.001);\n    }\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential,\n     lcdf_works_on_vectorial_y_and_sigma) {\n  using stan::math::skew_double_exponential_lcdf;\n  std::vector<double> ys{0.2, 0.9, 1.1};\n  std::vector<double> sigmas{0.1, 1.1, 3.2};\n\n  for (double mus : {0.1, 1.3, 3.0}) {\n    for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) {\n      double x = 0.0;\n      for (int i = 0; i < 3; i++)\n        x += skew_de_cdf_test(ys[i], mus, sigmas[i], taus);\n\n      EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus),\n                  0.001);\n    }\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential,\n     lcdf_works_on_vectorial_y_and_tau) {\n  using stan::math::skew_double_exponential_lcdf;\n  std::vector<double> ys{0.2, 0.9, 1.1};\n  std::vector<double> taus{0.1, 0.5, 0.9};\n\n  for (double mus : {0.1, 1.3, 3.0}) {\n    for (double sigmas : {0.1, 1.1, 3.2}) {\n      double x = 0.0;\n      for (int i = 0; i < 3; i++)\n        x += skew_de_cdf_test(ys[i], mus, sigmas, taus[i]);\n\n      EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus),\n                  0.001);\n    }\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential,\n     lcdf_works_on_vectorial_mu_sigma_and_tau) {\n  using stan::math::skew_double_exponential_lcdf;\n\n  std::vector<double> mus{0.1, 1.3, 3.0};\n  std::vector<double> sigmas{0.1, 1.1, 3.2};\n  std::vector<double> taus{0.1, 0.5, 0.9};\n\n  for (double ys : {0.1, 1.3, 3.0}) {\n    double x = 0.0;\n    for (int i = 0; i < 3; i++)\n      x += skew_de_cdf_test(ys, mus[i], sigmas[i], taus[i]);\n    EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus), 0.001);\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential, lcdf_check_errors) {\n  using stan::math::skew_double_exponential_lcdf;\n  static double inff = std::numeric_limits<double>::infinity();\n  EXPECT_THROW(stan::math::skew_double_exponential_lcdf(1.0, 0.0, -1, 0.5),\n               std::domain_error);\n  EXPECT_THROW(stan::math::skew_double_exponential_lcdf(1.0, 0.0, 0.1, -0.5),\n               std::domain_error);\n  EXPECT_THROW(stan::math::skew_double_exponential_lcdf(inff, 0.0, 0.1, 1.5),\n               std::domain_error);\n  EXPECT_THROW(stan::math::skew_double_exponential_lcdf(1.0, inff, 0.1, 1.5),\n               std::domain_error);\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential, lcdf_check_inconsistent_size) {\n  using stan::math::skew_double_exponential_lcdf;\n\n  std::vector<double> mus{0.1, 1.3, 3.0};\n  std::vector<double> sigmas{0.1, 1.1, 3.2, 1.0};\n  std::vector<double> taus{0.1, 0.5, 0.9};\n  EXPECT_THROW(stan::math::skew_double_exponential_lcdf(1.0, mus, sigmas, taus),\n               std::invalid_argument);\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential, cdf_log_matches_lcdf) {\n  double y = 0.8;\n  double mu = 2;\n  double sigma = 2.3;\n  double tau = 0.1;\n\n  EXPECT_FLOAT_EQ(\n      (stan::math::skew_double_exponential_lcdf(y, mu, sigma, tau)),\n      (stan::math::skew_double_exponential_cdf_log(y, mu, sigma, tau)));\n\n  EXPECT_FLOAT_EQ(\n      (stan::math::skew_double_exponential_lcdf<double, double, double, double>(\n          y, mu, sigma, tau)),\n      (stan::math::skew_double_exponential_cdf_log<double, double, double,\n                                                   double>(y, mu, sigma, tau)));\n}\n", "meta": {"hexsha": "ab096906b497894b6a68ed315a5570b58875c002", "size": 7290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/skew_double_exponential_cdf_log_test.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/math/prim/prob/skew_double_exponential_cdf_log_test.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": "test/unit/math/prim/prob/skew_double_exponential_cdf_log_test.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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.2876712329, "max_line_length": 80, "alphanum_fraction": 0.6094650206, "num_tokens": 2518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5017737306505188}}
{"text": "#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>  // have to include Eigen/Core before #include <opencv2/core/eigen.hpp> !! \n#include <opencv2/core/eigen.hpp>\n\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace cv;\n\nvoid feature_matching(const Mat& img1, const Mat& img2,\n    std::vector<KeyPoint>& keypoints1,\n    std::vector<KeyPoint>& keypoints2,\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        \n        // compute FAST corners \n        detector->detect(img1, keypoints1);\n        detector->detect(img2, keypoints2);\n\n        // compute BRIEF descriptor\n        descriptor->compute(img1, keypoints1, descriptors_1);\n        descriptor->compute(img2, keypoints2, descriptors_2);\n\n        Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(4);\n        /*\n        FLANNBASED = 1, \n        BRUTEFORCE = 2, \n        BRUTEFORCE_L1 = 3, \n        BRUTEFORCE_HAMMING = 4, \n        BRUTEFORCE_HAMMINGLUT = 5, \n        BRUTEFORCE_SL2 = 6 */\n\n        vector<DMatch> allmatches;\n        matcher->match(descriptors_1, descriptors_2, allmatches);\n\n        // Filter all match points\n        // Find maximum and minimum distance\n        double min_dist = 1000000, max_dist = 0;\n        for ( int i = 0; i < descriptors_1.rows; i++ )\n        {\n            double dist = allmatches[i].distance;\n            if ( dist < min_dist ) min_dist = dist;\n            if ( dist > max_dist ) max_dist = dist;\n        }\n\n        cout << \"max distance: \" << max_dist << endl;\n        cout << \"min distance: \" << min_dist << endl;\n\n        for ( int i = 0; i < descriptors_1.rows; i++ )\n        {\n            if ( allmatches[i].distance <= max ( 2*min_dist, 30.0 ) )\n            {\n                matches.push_back ( allmatches[i] );\n            }\n        }\n    }\n\nvoid pose_estimation_2d2d(\n    std::vector<KeyPoint>& keypoints1,\n    std::vector<KeyPoint>& keypoints2,\n    std::vector< DMatch >& matches,\n    Mat &R, Mat&t){\n\n        Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );\n\n        vector<Point2f> points1;\n        vector<Point2f> points2;\n\n        for ( int i = 0; i < ( int ) matches.size(); i++ )\n        {\n            points1.push_back ( keypoints1[matches[i].queryIdx].pt );\n            points2.push_back ( keypoints2[matches[i].trainIdx].pt );\n        }\n\n\n        Mat fundamental_matrix;\n        fundamental_matrix = findFundamentalMat ( points1, points2, CV_FM_8POINT );\n        cout<<\"fundamental_matrix is \"<<endl<< fundamental_matrix<<endl;\n\n        // Essential matrix\n        Point2d principal_point ( 325.1, 249.7 );\t\n        double focal_length = 521;\t\t\t\n        Mat essential_matrix;\n        essential_matrix = findEssentialMat ( points1, points2, focal_length, principal_point );\n        cout<<\"essential_matrix is \"<<endl<< essential_matrix<<endl;\n\n        // Homography Matrix\n        Mat homography_matrix;\n        homography_matrix = findHomography ( points1, points2, RANSAC, 3 );\n        cout<<\"homography_matrix is \"<<endl<<homography_matrix<<endl;\n\n        // Calculate R and t\n        recoverPose ( essential_matrix, points1, points2, R, t, focal_length, principal_point );\n        cout<<\"R is \"<<endl<<R<<endl;\n        cout<<\"t is \"<<endl<<t<<endl;\n    }\n\nint main(int argc, char** argv){\n    Mat img1 = imread(argv[1], CV_LOAD_IMAGE_COLOR);\n    Mat img2 = imread(argv[2], CV_LOAD_IMAGE_COLOR);\n\n    vector<KeyPoint> keypoints1, keypoints2;\n    vector<DMatch> matches;\n    feature_matching(img1, img2, keypoints1, keypoints2, matches);\n\n    cout<< \"Total \" << matches.size() << \"matched feature points\" << endl;\n\n    // pose estimation for two images\n    Mat R, t;  // Rotation and translation\n    pose_estimation_2d2d(keypoints1, keypoints2, matches, R, t);\n    \n    // epipolar geometry\n    Mat K = ( Mat_<double> (3, 3) << 529.0, 0, 325.1, 0, 521.0, 249.1, 0, 0, 1);\n    Mat t_x = ( Mat_<double> ( 3,3 ) <<\n                0,                      -t.at<double> ( 2,0 ),     t.at<double> ( 1,0 ),\n                t.at<double> ( 2,0 ),      0,                      -t.at<double> ( 0,0 ),\n                -t.at<double> ( 1,0 ),     t.at<double> ( 0,0 ),      0 );\n    \n    for(DMatch mm : matches){\n        Point2d pt1 = Point2d\n           (\n               ( keypoints1[ mm.queryIdx ].pt.x - K.at<double> ( 0,2 ) ) / K.at<double> ( 0,0 ),\n               ( keypoints1[ mm.queryIdx ].pt.y - K.at<double> ( 1,2 ) ) / K.at<double> ( 1,1 )\n           );\n        Mat y1 = ( Mat_<double> ( 3,1 ) << pt1.x, pt1.y, 1 );\n\n        Point2d pt2 = Point2d\n           (\n               ( keypoints2[ mm.trainIdx ].pt.x - K.at<double> ( 0,2 ) ) / K.at<double> ( 0,0 ),\n               ( keypoints2[ mm.trainIdx ].pt.y - K.at<double> ( 1,2 ) ) / K.at<double> ( 1,1 )\n           );\n        Mat y2 = ( Mat_<double> ( 3,1 ) << pt2.x, pt2.y, 1 );\n        Mat d = y2.t() * t_x * R * y1;\n        cout << \"epipolar constraint = \" << d << endl;\n    }\n    \n    Mat E = t_x * R;\n    cout << E.size() << endl;\n    Eigen::Matrix<float, 3, 3> b;\n    cv2eigen(E, b);\n    cout << \"Essential Matrix Eigenvalues and Eigenvectors\" << endl;\n    cout << b.eigenvalues().col(0)[0] << endl;\n    cout << b.eigenvalues().col(0)[1] << endl;\n    cout << b.eigenvalues().col(0)[2] << endl;\n    // cout << b.eigenvectors() << endl;\n    return 0;\n}\n            ", "meta": {"hexsha": "97313aad47e48a0a9ff2066d98ec72021c7f2bea", "size": 5602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "front_end/pose_estimation_2d2d.cpp", "max_stars_repo_name": "shen338/MySLAM", "max_stars_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "front_end/pose_estimation_2d2d.cpp", "max_issues_repo_name": "shen338/MySLAM", "max_issues_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "front_end/pose_estimation_2d2d.cpp", "max_forks_repo_name": "shen338/MySLAM", "max_forks_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_forks_repo_licenses": ["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.9102564103, "max_line_length": 98, "alphanum_fraction": 0.5631917172, "num_tokens": 1614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5017737306505187}}
{"text": "#include <boost/lexical_cast.hpp>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\nusing namespace boost::multiprecision;\r\n\r\nstring lastN(string input, int n) {\r\n\tint inputSize = input.size();\r\n\treturn (n > 0 && inputSize > n) ? input.substr(inputSize - n) : \"\";\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n\tcpp_int sum = 0;\r\n\tfor(cpp_int i = 1; i < 1001; i++) {\r\n\t\tsum += boost::multiprecision::pow(i, (int)i);\r\n\t}\r\n\tcout << lastN(sum.str(), 10) << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "cbc77321141c13f80bc42d44507f3e1a7876da3c", "size": 529, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/1-50/48/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/48/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/48/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": 25.1904761905, "max_line_length": 69, "alphanum_fraction": 0.6351606805, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.5017434364268819}}
{"text": "/*\n * H1H1.cpp\n *\n *  Created on: 13.03.2018\n *      Author: thies\n */\n\n#include <base/Util.h>\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/sparse_direct.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/sparsity_pattern.h>\n#include <deal.II/lac/vector.h>\n#include <norms/H1H1.h>\n#include <stddef.h>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\nnamespace wavepi {\nnamespace norms {\n\nusing namespace dealii;\n\ninline double square(const double x) { return x * x; }\ninline double pow4(const double x) { return x * x * x * x; }\n\ntemplate <int dim>\nH1H1<dim>::H1H1(double alpha, double gamma) : alpha_(alpha), gamma_(gamma) {}\n\ntemplate <int dim>\ndouble H1H1<dim>::norm(const DiscretizedFunction<dim>& u) const {\n  auto mesh = u.get_mesh();\n\n  // we may be able to use v, but this might introduce inconsistencies in the adjoints\n  // Note: this function works even for non-constant meshes.\n  auto deriv = u.calculate_derivative();\n\n  double result = 0;\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    double nrm2 = mesh->get_mass_matrix(i)->matrix_norm_square(u[i]) +\n                  gamma_ * mesh->get_laplace_matrix(i)->matrix_norm_square(u[i]);\n    double nrm2_deriv = mesh->get_mass_matrix(i)->matrix_norm_square(deriv[i]) +\n                        gamma_ * mesh->get_laplace_matrix(i)->matrix_norm_square(deriv[i]);\n\n    // + trapezoidal rule in time:\n    if (i > 0) result += (nrm2 + alpha_ * nrm2_deriv) / 2 * (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n\n    if (i < mesh->length() - 1)\n      result += (nrm2 + alpha_ * nrm2_deriv) / 2 * (std::abs(mesh->get_time(i + 1) - mesh->get_time(i)));\n  }\n\n  return std::sqrt(result);\n}\n\ntemplate <int dim>\ndouble H1H1<dim>::dot(const DiscretizedFunction<dim>& u, const DiscretizedFunction<dim>& v) const {\n  auto mesh     = u.get_mesh();\n  double result = 0.0;\n\n  // we may be able to use v, but this might introduce inconsistencies in the adjoints\n  // Note: this function works even for non-constant meshes.\n  auto deriv  = u.calculate_derivative();\n  auto Vderiv = v.calculate_derivative();\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    double doti = mesh->get_mass_matrix(i)->matrix_scalar_product(u[i], v[i]) +\n                  gamma_ * mesh->get_laplace_matrix(i)->matrix_scalar_product(u[i], v[i]);\n    double doti_deriv = mesh->get_mass_matrix(i)->matrix_scalar_product(deriv[i], Vderiv[i]) +\n                        gamma_ * mesh->get_laplace_matrix(i)->matrix_scalar_product(deriv[i], Vderiv[i]);\n\n    // + trapezoidal rule in time\n    if (i > 0) result += (doti + alpha_ * doti_deriv) / 2 * (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n\n    if (i < mesh->length() - 1)\n      result += (doti + alpha_ * doti_deriv) / 2 * (std::abs(mesh->get_time(i + 1) - mesh->get_time(i)));\n  }\n\n  return result;\n}\n\ntemplate <int dim>\nvoid H1H1<dim>::dot_transform(DiscretizedFunction<dim>& u) {\n  auto mesh = u.get_mesh();\n\n  // X = (T + \\alpha_ D^t T D) * (M+gamma_ L),\n  // M = blocks of mass matrices, D = derivative, T = trapezoidal rule, L = blocks of laplace matrices\n\n  DiscretizedFunction<dim> tmp(mesh, u.get_norm());\n  for (size_t i = 0; i < mesh->length(); i++)\n    mesh->get_laplace_matrix(i)->vmult(tmp[i], u[i]);\n\n  u.mult_mass();\n  u.add(gamma_, tmp);\n\n  auto dx = u.calculate_derivative();\n\n  // trapezoidal rule\n  // (has to happen between D and D^t for dx)\n  for (size_t i = 0; i < mesh->length(); i++) {\n    double factor = 0.0;\n\n    if (i > 0) factor += std::abs(mesh->get_time(i) - mesh->get_time(i - 1)) / 2.0;\n    if (i < mesh->length() - 1) factor += std::abs(mesh->get_time(i + 1) - mesh->get_time(i)) / 2.0;\n\n    dx[i] *= factor;\n    u[i] *= factor;\n  }\n\n  auto dtdx = dx.calculate_derivative_transpose();\n\n  // add derivative term\n  for (size_t i = 0; i < mesh->length(); i++) {\n    u[i].add(alpha_, dtdx[i]);\n  }\n}\n\ntemplate <int dim>\nvoid H1H1<dim>::dot_transform_inverse(DiscretizedFunction<dim>& u) {\n  LogStream::Prefix p(\"h1h1_transform\");\n\n  auto mesh = u.get_mesh();\n  AssertThrow(mesh->length() > 7, ExcInternalError());\n\n  Timer timer;\n  timer.start();\n\n  // space part: solve mass+\u0263*\u0394\n  SparseMatrix<double> system_matrix(*mesh->get_sparsity_pattern(0));\n  system_matrix.copy_from(*mesh->get_mass_matrix(0));\n  system_matrix.add(gamma_, *mesh->get_laplace_matrix(0));\n  Vector<double> sp_tmp(u[0].size());\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    Assert(u[0].size() == u[i].size(), ExcInternalError());\n    LogStream::Prefix p(\"step-\" + Utilities::int_to_string(i, 4));\n\n    SolverControl solver_control(2000, 1e-10 * u[i].l2_norm());\n    SolverCG<> cg(solver_control);\n    PreconditionIdentity precondition = PreconditionIdentity();\n\n    sp_tmp = 0.0;\n    cg.solve(system_matrix, sp_tmp, u[i], precondition);\n    u[i] = sp_tmp;\n  }\n\n  // time part\n  if (umfpack.n() != mesh->length()) factorize_matrix(mesh);\n\n  // just to be sure\n  for (size_t i = 0; i < mesh->length(); i++)\n    Assert(u[i].size() == u[0].size(), ExcInternalError());\n\n  // solve for every DoF\n  Vector<double> tmp(mesh->length());\n\n  for (size_t i = 0; i < u[0].size(); i++) {\n    for (size_t j = 0; j < mesh->length(); j++)\n      tmp[j] = u[j][i];\n\n    umfpack.solve(tmp);\n\n    for (size_t j = 0; j < mesh->length(); j++)\n      u[j][i] = tmp[j];\n  }\n\n  deallog << \"solved in \" << Util::format_duration(timer.wall_time()) << std::endl;\n}\n\ntemplate <int dim>\nvoid H1H1<dim>::factorize_matrix(std::shared_ptr<SpaceTimeMesh<dim>> mesh) {\n  deallog << \"factorizing matrix\" << std::endl;\n\n  SparsityPattern pattern(mesh->length(), mesh->length(), 3);\n\n  pattern.add(0, 0);\n  pattern.add(0, 1);\n  pattern.add(1, 0);\n  pattern.add(1, 1);\n\n  for (size_t i = 2; i < mesh->length() - 2; i++) {\n    // fill row i and column i\n\n    pattern.add(i, i);\n\n    pattern.add(i, i - 2);\n    pattern.add(i - 2, i);\n\n    pattern.add(i, i + 2);\n    pattern.add(i + 2, i);\n  }\n\n  pattern.add(mesh->length() - 2, mesh->length() - 1);\n  pattern.add(mesh->length() - 2, mesh->length() - 1);\n  pattern.add(mesh->length() - 1, mesh->length() - 2);\n  pattern.add(mesh->length() - 1, mesh->length() - 1);\n\n  pattern.compress();\n\n  // coefficients of trapezoidal rule\n  std::vector<double> lambdas(mesh->length(), 0.0);\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    if (i > 0) lambdas[i] += std::abs(mesh->get_time(i) - mesh->get_time(i - 1)) / 2.0;\n\n    if (i < mesh->length() - 1) lambdas[i] += std::abs(mesh->get_time(i + 1) - mesh->get_time(i)) / 2.0;\n  }\n\n  SparseMatrix<double> matrix(pattern);\n\n  double sq20 = 1.0 / square(mesh->get_time(2) - mesh->get_time(0));\n  double sq10 = 1.0 / square(mesh->get_time(1) - mesh->get_time(0));\n  double sq31 = 1.0 / square(mesh->get_time(3) - mesh->get_time(1));\n\n  matrix.set(0, 0, lambdas[1] * sq20 + lambdas[0] * sq10);\n  matrix.set(1, 1, lambdas[2] * sq31 + lambdas[0] * sq10);\n  matrix.set(0, 1, -lambdas[0] * sq10);\n  matrix.set(1, 0, -lambdas[0] * sq10);\n\n  for (size_t i = 2; i < mesh->length() - 2; i++) {\n    // fill row i and column i\n\n    double sq20  = 1.0 / square(mesh->get_time(i + 2) - mesh->get_time(i));\n    double sq0m2 = 1.0 / square(mesh->get_time(i) - mesh->get_time(i - 2));\n\n    matrix.set(i, i, lambdas[i + 1] * sq20 + lambdas[i - 1] * sq0m2);\n\n    matrix.set(i, i - 2, -lambdas[i - 1] * sq0m2);\n    matrix.set(i - 2, i, -lambdas[i - 1] * sq0m2);\n\n    matrix.set(i, i + 2, -lambdas[i + 1] * sq20);\n    matrix.set(i + 2, i, -lambdas[i + 1] * sq20);\n  }\n\n  // (symmetric to the first entries)\n  size_t N = mesh->length() - 1;  // makes it easier to read\n\n  sq20 = 1.0 / square(mesh->get_time(N - 2) - mesh->get_time(N));\n  sq10 = 1.0 / square(mesh->get_time(N - 1) - mesh->get_time(N));\n  sq31 = 1.0 / square(mesh->get_time(N - 3) - mesh->get_time(N - 1));\n\n  matrix.set(N, N - 0, lambdas[N - 1] * sq20 + lambdas[N] * sq10);\n  matrix.set(N - 1, N - 1, lambdas[N - 2] * sq31 + lambdas[N] * sq10);\n  matrix.set(N, N - 1, -lambdas[N] * sq10);\n  matrix.set(N - 1, N, -lambdas[N] * sq10);\n\n  matrix *= alpha_;\n\n  // L2 part (+ trapezoidal rule)\n  for (size_t i = 0; i < mesh->length(); i++)\n    matrix.add(i, i, lambdas[i]);\n\n  umfpack.factorize(matrix);\n}\n\ntemplate <int dim>\nvoid H1H1<dim>::dot_solve_mass_and_transform(DiscretizedFunction<dim>& u) {\n  // X = (T + \\alpha_ D^t T D) * (M+gamma_ L),\n  // M = blocks of mass matrices, D = derivative, T = trapezoidal rule, L = blocks of laplace matrices\n  u.solve_mass();\n  dot_transform(u);\n}\n\ntemplate <int dim>\nvoid H1H1<dim>::dot_mult_mass_and_transform_inverse(DiscretizedFunction<dim>& u) {\n  u.mult_mass();\n  dot_transform_inverse(u);\n}\n\ntemplate <int dim>\nstd::string H1H1<dim>::name() const {\n  return \"H\u00b9([0,T], H\u00b9(\u03a9))\";\n}\n\ntemplate <int dim>\nstd::string H1H1<dim>::unique_id() const {\n  return \"H\u00b9([0,T], H\u00b9(\u03a9)) with \u0263=\" + std::to_string(gamma_) + \", \u03b1=\" + std::to_string(alpha_);\n}\n\ntemplate class H1H1<1>;\ntemplate class H1H1<2>;\ntemplate class H1H1<3>;\n\n} /* namespace norms */\n} /* namespace wavepi */\n", "meta": {"hexsha": "4b7d75afde910569b32f3163dd6ddad7f26a3964", "size": 9084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/norms/H1H1.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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": "lib/norms/H1H1.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/norms/H1H1.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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.2164948454, "max_line_length": 114, "alphanum_fraction": 0.6195508587, "num_tokens": 2999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.5017434285810859}}
{"text": "#include \"calibrate.hpp\"\n\n#include \"parse.hpp\"\n\n#include <Eigen/SVD>\n\n#include <iostream>\n#include <stdexcept>\n\n// Assuming that the photos have been distributed roughly evenly around the\n// circle and that the rotation axis was close to the global vertical axis.\n// The returned vector is the camera space +y vector in IMU coordinates. y is\n// down on the image.\nEigen::Vector3f get_y_axis(std::vector<Eigen::Vector3f> const& photo_gravity) {\n\tEigen::Vector3f vertical_axis = Eigen::Vector3f::Zero();\n\n\tfor (auto const& g : photo_gravity)\n\t\tvertical_axis += g;\n\n\treturn vertical_axis.normalized();\n}\n\n// Assumes that the camera x axis was roughly orthogonal to the world vertcal\n// axis and the photos were taken while rotating exactly around the camera x\n// axis.\nEigen::Vector3f get_x_axis(std::vector<Eigen::Vector3f> const& photo_gravity) {\n\t// Simple linear regression\n\tconst int n = photo_gravity.size();\n\n\tassert(n >= 4);\n\n\tEigen::MatrixXf m(n, 4);\n\tfor (int i = 0; i < n; ++i) {\n\t\tm.block<1, 3>(i, 0) = photo_gravity[i].transpose().normalized();\n\t}\n\n\tm.col(3) = Eigen::VectorXf::Ones(n);\n\n\t// We find a plane through the data. The first three components are\n\t// the normal of the plane, the last component is the offset.\n\tEigen::Vector4f w = m.bdcSvd(Eigen::ComputeFullV).matrixV().col(3);\n\tw /= w.head<3>().norm();\n\n\tEigen::Vector3f normal = w.head<3>();\n\n\t// Here we make sure that the rotation axis was close to orthogonal\n\t// to gravity. The offset of the plane is equal the sin of the\n\t// angle between the rotation axis and a perfectly horizontal line.\n\tconst float sin_angle = w(3);\n\tassert(std::abs(sin_angle) < 0.2);\n\n\t// We check if the camera was rotated in positive or negative\n\t// direction around `normal` by checking how the first and last\n\t// vector split up the circle into sectors and seeing into which\n\t// of the sectors the middle recording falls.\n\n\tstd::array<Eigen::Vector3f, 3> vecs_on_plane = {\n\t    m.block<1, 3>(0, 0), m.block<1, 3>(n / 2, 0), m.block<1, 3>(n - 1, 0)};\n\n\tfor (auto& v : vecs_on_plane)\n\t\tv -= v.dot(normal) * normal;\n\n\tconst Eigen::Vector3f centre_of_positive_sector =\n\t    normal.cross(vecs_on_plane[0]) - normal.cross(vecs_on_plane[2]);\n\n\tif (centre_of_positive_sector.dot(vecs_on_plane[1]) <\n\t    centre_of_positive_sector.dot(vecs_on_plane[0]))\n\t\tnormal *= -1;\n\n\treturn normal;\n}\n\n// Returns the rotation from IMU frame to Camera frame.\nEigen::Quaternionf calibrate(std::ifstream& recording_infile,\n                             int x_session_index, int y_session_index,\n                             int nr_skip_measurements) {\n\tint session_index = -1;\n\n\tbool x_calibrated = false;\n\tbool y_calibrated = false;\n\n\tif (x_session_index == y_session_index) {\n\t\tthrow std::invalid_argument(\n\t\t    \"The indices for calibrating the x and y axes can't be equal.\");\n\t}\n\n\tstd::vector<Eigen::Vector3f> measurements;\n\tmeasurements.reserve(30);\n\n\tstd::vector<Eigen::Vector3f> photo_gravities;\n\n\tEigen::Vector3f x_axis;\n\tEigen::Vector3f y_axis;\n\n\tconst auto run_calibrations = [&]() {\n\t\tif (session_index == x_session_index) {\n\t\t\tx_axis = get_x_axis(photo_gravities);\n\t\t\tx_calibrated = true;\n\t\t} else if (session_index == y_session_index) {\n\t\t\ty_axis = get_y_axis(photo_gravities);\n\t\t\ty_calibrated = true;\n\t\t}\n\t};\n\n\tlog_entry_types entry_type;\n\twhile (read_next_entry(recording_infile, entry_type)) {\n\t\tswitch (entry_type) {\n\t\tcase log_entry_types::photo_event:\n\t\t\tparse_photo(recording_infile).millis;\n\n\t\t\tif (session_index >= 0 && (session_index == x_session_index ||\n\t\t\t                           session_index == y_session_index)) {\n\t\t\t\tEigen::Vector3f g = Eigen::Vector3f::Zero();\n\t\t\t\tint nr_relevant_measurements =\n\t\t\t\t    measurements.size() - nr_skip_measurements;\n\t\t\t\tfor (int i = 0; i < nr_relevant_measurements; ++i)\n\t\t\t\t\tg += measurements[i];\n\t\t\t\tg /= nr_relevant_measurements;\n\n\t\t\t\tphoto_gravities.push_back(g);\n\t\t\t}\n\n\t\t\tmeasurements.clear();\n\t\t\tbreak;\n\t\tcase log_entry_types::startup:\n\n\t\t\tif (session_index >= 0)\n\t\t\t\trun_calibrations();\n\n\t\t\tparse_startup(recording_infile);\n\t\t\tphoto_gravities.clear();\n\t\t\tmeasurements.clear();\n\t\t\t++session_index;\n\t\t\tbreak;\n\t\tcase log_entry_types::gravity_vector:\n\t\t\tmeasurements.push_back(parse_gravity(recording_infile).g);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (session_index >= 0)\n\t\trun_calibrations();\n\n\t// If only one of the axes was calibrated we still want to print the\n\t// result, this is useful for testing.\n\tif (x_calibrated)\n\t\tstd::cout << \"Sensor x axis in IMU coordinates: \" << x_axis.transpose()\n\t\t          << '\\n';\n\tif (y_calibrated)\n\t\tstd::cout << \"Sensor y axis in IMU coordinates: \" << y_axis.transpose()\n\t\t          << '\\n';\n\n\tif (x_calibrated && y_calibrated) {\n\t\t// running a complete calibration\n\n\t\tEigen::Matrix3f rotation_matrix;\n\t\trotation_matrix << x_axis, y_axis, x_axis.cross(y_axis);\n\n\t\t// Invert the rotation because we want to get the conversion from IMU\n\t\t// frame to camera.\n\t\treturn Eigen::Quaternionf(rotation_matrix).conjugate();\n\t} else {\n\t\tif (x_session_index >= session_index)\n\t\t\tthrow std::runtime_error(\"Invalid x session index.\");\n\t\tif (y_session_index >= session_index)\n\t\t\tthrow std::runtime_error(\"Invalid y session index.\");\n\t}\n\n\tthrow std::runtime_error(\"Need both x and y for complete calibration.\");\n}\n", "meta": {"hexsha": "de81f4ab796f8395100127e2287eaa671d09c4cc", "size": 5222, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "recording_parser/calibrate.cpp", "max_stars_repo_name": "Pascal-So/arduino-gravity-recorder", "max_stars_repo_head_hexsha": "665148ae009bd9d24134ed0b7d8149cd691a000c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "recording_parser/calibrate.cpp", "max_issues_repo_name": "Pascal-So/arduino-gravity-recorder", "max_issues_repo_head_hexsha": "665148ae009bd9d24134ed0b7d8149cd691a000c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "recording_parser/calibrate.cpp", "max_forks_repo_name": "Pascal-So/arduino-gravity-recorder", "max_forks_repo_head_hexsha": "665148ae009bd9d24134ed0b7d8149cd691a000c", "max_forks_repo_licenses": ["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.5380116959, "max_line_length": 79, "alphanum_fraction": 0.6953274607, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5017057472199385}}
{"text": "/**\n * @file rrts02-nearestNeighbors.cpp\n * @author Can Erdogan\n * @date Feb 04, 2013\n * @brief Checks if the nearest neighbor computation done by flann is correct.\n */\n\n#include <iostream>\n#include <gtest/gtest.h>\n#include <Eigen/Core>\n#include <dart/dart.hpp>\n#if HAVE_FLANN\n#include <flann/flann.hpp>\n#endif // HAVE_FLANN\n#include \"TestHelpers.hpp\"\n\n/* ********************************************************************************************* */\n#if HAVE_FLANN\nTEST(NEAREST_NEIGHBOR, 2D) {\n\n    // Build the index with the first node\n    flann::Index<flann::L2<double> > index (flann::KDTreeSingleIndexParams(10, true));\n    Eigen::VectorXd p1 (2);\n    p1 << -3.04159, -3.04159;\n    index.buildIndex(flann::Matrix<double>((double*)p1.data(), 1, p1.size()));\n\n    // Add two more points\n    Eigen::Vector2d p2 (-2.96751, -2.97443), p3 (-2.91946, -2.88672);\n    index.addPoints(flann::Matrix<double>((double*)p2.data(), 1, p2.size()));\n    index.addPoints(flann::Matrix<double>((double*)p3.data(), 1, p3.size()));\n\n    // Check the size of the tree\n    EXPECT_EQ(3, (int)index.size());\n\n    // Get the nearest neighbor index for a sample point\n    Eigen::Vector2d sample (-2.26654, 2.2874);\n    int nearest;\n    double distance;\n    const flann::Matrix<double> queryMatrix((double*)sample.data(), 1, sample.size());\n    flann::Matrix<int> nearestMatrix(&nearest, 1, 1);\n    flann::Matrix<double> distanceMatrix(flann::Matrix<double>(&distance, 1, 1));\n    index.knnSearch(queryMatrix, nearestMatrix, distanceMatrix, 1,\n        flann::SearchParams(flann::FLANN_CHECKS_UNLIMITED));\n    EXPECT_EQ(2, nearest);\n\n    // Get the nearest neighbor\n    double* point = index.getPoint(nearest);\n    bool equality = equals(Vector2d(point[0], point[1]), p3, 1e-3);\n    EXPECT_TRUE(equality);\n}\n#endif // HAVE_FLANN\n\n/* ********************************************************************************************* */\nint main(int argc, char* argv[]) {\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "ce30b4ffb1b49ddda52382ff27471fc96cb4e264", "size": 2018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/testNearestNeighbor.cpp", "max_stars_repo_name": "purewind7/CS7496", "max_stars_repo_head_hexsha": "ca0b8376db400f265d9515d8307d928590a1569a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-02-20T15:59:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T04:04:21.000Z", "max_issues_repo_path": "unittests/testNearestNeighbor.cpp", "max_issues_repo_name": "purewind7/CS7496", "max_issues_repo_head_hexsha": "ca0b8376db400f265d9515d8307d928590a1569a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-14T04:12:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-14T04:12:48.000Z", "max_forks_repo_path": "unittests/testNearestNeighbor.cpp", "max_forks_repo_name": "purewind7/CS7496", "max_forks_repo_head_hexsha": "ca0b8376db400f265d9515d8307d928590a1569a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-29T12:41:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T16:38:27.000Z", "avg_line_length": 34.7931034483, "max_line_length": 99, "alphanum_fraction": 0.6060455897, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5016529094977236}}
{"text": "/*\n [auto_generated]\n libs/numeric/odeint/test/trivial_state.cpp\n\n [begin_description]\n This file defines a vector_space 1d class with the appropriate operators.\n [end_description]\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#ifndef VECTOR_SPACE_1D_HPP_INCLUDED\n#define VECTOR_SPACE_1D_HPP_INCLUDED\n\n#include <boost/config.hpp>\n#include <boost/operators.hpp>\n\ntemplate< class T >\nstruct vector_space_1d :\n    boost::additive1< vector_space_1d< T > ,\n    boost::additive2< vector_space_1d< T > , T ,\n    boost::multiplicative1< vector_space_1d< T > ,\n    boost::multiplicative2< vector_space_1d< T > , T\n    > > > >\n{\n    typedef T value_type;\n\n    value_type m_x;\n\n    vector_space_1d( void ) : m_x( 0.0 ) {}\n\n    vector_space_1d& operator+=( const vector_space_1d& p )\n    {\n        m_x += p.m_x;\n        return *this;\n    }\n\n    vector_space_1d& operator-=( const vector_space_1d& p )\n    {\n        m_x -= p.m_x;\n        return *this;\n    }\n\n    vector_space_1d& operator*=( const vector_space_1d& p )\n    {\n        m_x *= p.m_x;\n        return *this;\n    }\n\n    vector_space_1d& operator/=( const vector_space_1d& p )\n    {\n        m_x /= p.m_x;\n        return *this;\n    }\n\n    vector_space_1d& operator+=( const value_type& val )\n    {\n        m_x += val;\n        return *this;\n    }\n\n    vector_space_1d& operator-=( const value_type& val )\n    {\n        m_x -= val;\n        return *this;\n    }\n\n    vector_space_1d& operator*=( const value_type &val )\n    {\n        m_x *= val;\n        return *this;\n    }\n\n    vector_space_1d& operator/=( const value_type &val )\n    {\n        m_x /= val;\n        return *this;\n    }\n};\n\n\ntemplate< class T >\nvector_space_1d< T > abs( const vector_space_1d< T > &v)\n{\n    vector_space_1d< T > tmp;\n    tmp.m_x = std::abs( v.m_x );\n    return tmp;\n}\n\n\ntemplate< class T >\nT max BOOST_PREVENT_MACRO_SUBSTITUTION ( const vector_space_1d< T > &v )\n{\n    return v.m_x;\n}\n\nnamespace boost {\n    namespace numeric {\n        namespace odeint {\n\n            template< class T >\n            struct vector_space_reduce< vector_space_1d< T > >\n            {\n                template< class Op >\n                T operator()( const vector_space_1d< T > &v , Op op , T value )\n                {\n                    return v.m_x;\n                }\n            };\n\n} // odeint\n} // numeric\n} // boost\n\n#endif // VECTOR_SPACE_1D_HPP_INCLUDED\n", "meta": {"hexsha": "9d14d8b80acf099772fcfd792ea15997146241a9", "size": 2551, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/test/vector_space_1d.hpp", "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/test/vector_space_1d.hpp", "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/test/vector_space_1d.hpp", "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": 21.0826446281, "max_line_length": 79, "alphanum_fraction": 0.5997647981, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5016528970082864}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <shz/math/vector.hpp>\n\n/*\n\tVS2012 Compiler Bug makes impossible to use auto keyword for memory aligned structures.\n\tSee: http://connect.microsoft.com/VisualStudio/feedback/details/775238/visual-c-2012-auto-keyword-ignores-structure-memory-alignment\n\tWorkaround: either declare the variable with the 16bytes alignment or don't use the auto keyword\n*/\n\nbool is_aligned(void *p, intptr_t N)\n{\n\treturn (intptr_t)p % N == 0;\n}\n\nBOOST_AUTO_TEST_CASE(vector4fConstructors)\n{\n\tshz::math::vector<shz::math::f32, 4> v(0.f);\n\tBOOST_CHECK(is_aligned(&v, 16));\n\tBOOST_CHECK(v.x == 0.f);\n\tBOOST_CHECK(v.y  == 0.f);\n\tBOOST_CHECK(v.z  == 0.f);\n\tBOOST_CHECK(v.w  == 0.f);\n\n\tv = shz::math::vector<shz::math::f32, 4>(1.f);\n\tBOOST_CHECK(v.data[0]  == 1.f);\n\tBOOST_CHECK(v.data[1]  == 1.f);\n\n\tv = shz::math::vector<shz::math::f32, 4>(1.4f);\n\tv -= 0.4f;\n\tBOOST_CHECK(v.data[0]  == 1.f);\n\tBOOST_CHECK(v.data[1]  == 1.f);\n\tBOOST_CHECK(v.z  == 1.f);\n\tBOOST_CHECK(v.w  == 1.f);\n}\n\nBOOST_AUTO_TEST_CASE(vector4fAdds)\n{\n\tshz::math::vector<shz::math::f32, 4> v(1.4f);\n\tBOOST_CHECK(is_aligned(&v, 16));\n\tv += 0.4f;\n\tBOOST_CHECK(v.x  == 1.8f);\n\tBOOST_CHECK(v.y  == 1.8f);\n\tBOOST_CHECK(v.z  == 1.8f);\n\tBOOST_CHECK(v.w  == 1.8f);\n\n\tshz::math::vector<shz::math::f32, 4> w(-1.4f);\n\tv += w;\n\tBOOST_CHECK_CLOSE(v.data[0], .4f,  0.00001f);\n\tBOOST_CHECK_CLOSE(v.data[1], .4f,  0.00001f);\n}\n\nBOOST_AUTO_TEST_CASE(vector4fSubs)\n{\n\tshz::math::vector<shz::math::f32, 4> v(1.4f);\n\tv -= 0.4f;\n\tBOOST_CHECK(v.data[0]  == 1.f);\n\tBOOST_CHECK(v.data[1]  == 1.f);\n\n\tshz::math::vector<shz::math::f32, 4> w(-1.4f);\n\tv -= w;\n\tBOOST_CHECK_CLOSE(v.data[0], 2.4f,  0.00001f);\n\tBOOST_CHECK_CLOSE(v.data[1], 2.4f,  0.00001f);\n}\n\nBOOST_AUTO_TEST_CASE(vector4fMuls)\n{\n\tshz::math::vector<shz::math::f32, 4> v(1.4f);\n\tv *= 0.5f;\n\tBOOST_CHECK(v.data[0]  == 0.7f);\n\tBOOST_CHECK(v.data[1]  == 0.7f);\n\n\tshz::math::vector<shz::math::f32, 4> w(-1.4f);\n\tv *= w;\n\tBOOST_CHECK_CLOSE(v.data[0], -0.98f,  0.00001f);\n\tBOOST_CHECK_CLOSE(v.data[1], -0.98f,  0.00001f);\n}\n\nBOOST_AUTO_TEST_CASE(vector4fDivs)\n{\n\tshz::math::vector<shz::math::f32, 4> v(1.4f);\n\tv /= 0.5f;\n\tBOOST_CHECK(v.data[0]  == 2.8f);\n\tBOOST_CHECK(v.data[1]  == 2.8f);\n\n\tshz::math::vector<shz::math::f32, 4> w(2.f);\n\tv /= w;\n\tBOOST_CHECK_CLOSE(v.data[0], 1.4f,  0.00001f);\n\tBOOST_CHECK_CLOSE(v.data[1], 1.4f,  0.00001f);\n}\n\nBOOST_AUTO_TEST_CASE(vector4fDot)\n{\n\tshz::math::vector<shz::math::f32, 4> v(1.4f);\n\tshz::math::vector<shz::math::f32, 4> w(0.5f);\n\n\tauto value = v.dot(w); \n\tBOOST_CHECK_CLOSE(value, 2.8f, 0.00001f);\n}\n\nBOOST_AUTO_TEST_CASE(vector4fLength)\n{\n\tshz::math::vector<shz::math::f32, 4> v(1.4f);\n\tBOOST_CHECK_CLOSE(v.length(), 2.8f, 0.01f);\n\tBOOST_CHECK_CLOSE(v.sqrlength(), 7.84f, 0.00001f);\n}\n\nBOOST_AUTO_TEST_CASE(vector4fInverseLength)\n{\n\tshz::math::vector<shz::math::f32, 4> v(1.4f);\n\tBOOST_CHECK_CLOSE(v.inv_length(), 1.f/2.8f, 0.01f);\n\tv = shz::math::vector<shz::math::f32, 4>(0.f);\n\tBOOST_CHECK_CLOSE(v.inv_length(), 0.f, 0.0f);\n}\n\nBOOST_AUTO_TEST_CASE(vector4fNormalize)\n{\n\tshz::math::vector<shz::math::f32, 4> v(1.4f);\n\tshz::math::vector<shz::math::f32, 4> w = v.normalize();\n\tBOOST_CHECK_CLOSE(w.data[0], 0.5f,  0.01f);\n\tBOOST_CHECK_CLOSE(w.data[1], 0.5f,  0.01f);\n\n\tv = shz::math::vector<shz::math::f32, 4>(.0f);\n\tw = v.normalize();\n\tBOOST_CHECK_CLOSE(w.data[0], 0.f,  0.001f);\n\tBOOST_CHECK_CLOSE(w.data[1], 0.f,  0.001f);\n\tBOOST_CHECK_CLOSE(w.data[2], 0.f,  0.001f);\n}\n", "meta": {"hexsha": "99a1d907160f00e88bb0b52d2fbbe284c2b0cf8a", "size": 3434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Math/vector4_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/vector4_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/vector4_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": 26.828125, "max_line_length": 133, "alphanum_fraction": 0.6525917298, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.50165287962007}}
{"text": "/**\n * @file emst_test.cpp\n *\n * Test file for EMST methods.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/emst/dtb.hpp>\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\n#include <mlpack/core/tree/cover_tree.hpp>\n\nusing namespace mlpack;\nusing namespace mlpack::emst;\nusing namespace mlpack::tree;\nusing namespace mlpack::bound;\nusing namespace mlpack::metric;\n\nBOOST_AUTO_TEST_SUITE(EMSTTest);\n\n/**\n * Simple emst test with small, synthetic dataset.  This is an\n * exhaustive test, which checks that each method for performing the calculation\n * (dual-tree, naive) produces the correct results.  The dataset is in one\n * dimension for simplicity -- the correct functionality of distance functions\n * is not tested here.\n */\nBOOST_AUTO_TEST_CASE(ExhaustiveSyntheticTest)\n{\n  // Set up our data.\n  arma::mat data(1, 11);\n  data[0] = 0.05; // Row addressing is unnecessary (they are all 0).\n  data[1] = 0.37;\n  data[2] = 0.15;\n  data[3] = 1.25;\n  data[4] = 5.05;\n  data[5] = -0.22;\n  data[6] = -2.00;\n  data[7] = -1.30;\n  data[8] = 0.45;\n  data[9] = 0.91;\n  data[10] = 1.00;\n\n  arma::mat results;\n\n  // Build the tree by hand to get a leaf size of 1.\n  typedef KDTree<EuclideanDistance, DTBStat, arma::mat> TreeType;\n  std::vector<size_t> oldFromNew;\n  std::vector<size_t> newFromOld;\n  TreeType tree(data, oldFromNew, newFromOld, 1);\n\n  // Create the DTB object and run the calculation.\n  DualTreeBoruvka<> dtb(&tree);\n  dtb.ComputeMST(results);\n\n  // Now the exhaustive check for correctness.\n  if (newFromOld[1] < newFromOld[8])\n  {\n    BOOST_REQUIRE_EQUAL(results(0, 0), newFromOld[1]);\n    BOOST_REQUIRE_EQUAL(results(1, 0), newFromOld[8]);\n  }\n  else\n  {\n    BOOST_REQUIRE_EQUAL(results(1, 0), newFromOld[1]);\n    BOOST_REQUIRE_EQUAL(results(0, 0), newFromOld[8]);\n  }\n  BOOST_REQUIRE_CLOSE(results(2, 0), 0.08, 1e-5);\n\n  if (newFromOld[9] < newFromOld[10])\n  {\n    BOOST_REQUIRE_EQUAL(results(0, 1), newFromOld[9]);\n    BOOST_REQUIRE_EQUAL(results(1, 1), newFromOld[10]);\n  }\n  else\n  {\n    BOOST_REQUIRE_EQUAL(results(1, 1), newFromOld[9]);\n    BOOST_REQUIRE_EQUAL(results(0, 1), newFromOld[10]);\n  }\n  BOOST_REQUIRE_CLOSE(results(2, 1), 0.09, 1e-5);\n\n  if (newFromOld[0] < newFromOld[2])\n  {\n    BOOST_REQUIRE_EQUAL(results(0, 2), newFromOld[0]);\n    BOOST_REQUIRE_EQUAL(results(1, 2), newFromOld[2]);\n  }\n  else\n  {\n    BOOST_REQUIRE_EQUAL(results(1, 2), newFromOld[0]);\n    BOOST_REQUIRE_EQUAL(results(0, 2), newFromOld[2]);\n  }\n  BOOST_REQUIRE_CLOSE(results(2, 2), 0.1, 1e-5);\n\n  if (newFromOld[1] < newFromOld[2])\n  {\n    BOOST_REQUIRE_EQUAL(results(0, 3), newFromOld[1]);\n    BOOST_REQUIRE_EQUAL(results(1, 3), newFromOld[2]);\n  }\n  else\n  {\n    BOOST_REQUIRE_EQUAL(results(1, 3), newFromOld[1]);\n    BOOST_REQUIRE_EQUAL(results(0, 3), newFromOld[2]);\n  }\n  BOOST_REQUIRE_CLOSE(results(2, 3), 0.22, 1e-5);\n\n  if (newFromOld[3] < newFromOld[10])\n  {\n    BOOST_REQUIRE_EQUAL(results(0, 4), newFromOld[3]);\n    BOOST_REQUIRE_EQUAL(results(1, 4), newFromOld[10]);\n  }\n  else\n  {\n    BOOST_REQUIRE_EQUAL(results(1, 4), newFromOld[3]);\n    BOOST_REQUIRE_EQUAL(results(0, 4), newFromOld[10]);\n  }\n  BOOST_REQUIRE_CLOSE(results(2, 4), 0.25, 1e-5);\n\n  if (newFromOld[0] < newFromOld[5])\n  {\n    BOOST_REQUIRE_EQUAL(results(0, 5), newFromOld[0]);\n    BOOST_REQUIRE_EQUAL(results(1, 5), newFromOld[5]);\n  }\n  else\n  {\n    BOOST_REQUIRE_EQUAL(results(1, 5), newFromOld[0]);\n    BOOST_REQUIRE_EQUAL(results(0, 5), newFromOld[5]);\n  }\n  BOOST_REQUIRE_CLOSE(results(2, 5), 0.27, 1e-5);\n\n  if (newFromOld[8] < newFromOld[9])\n  {\n    BOOST_REQUIRE_EQUAL(results(0, 6), newFromOld[8]);\n    BOOST_REQUIRE_EQUAL(results(1, 6), newFromOld[9]);\n  }\n  else\n  {\n    BOOST_REQUIRE_EQUAL(results(1, 6), newFromOld[8]);\n    BOOST_REQUIRE_EQUAL(results(0, 6), newFromOld[9]);\n  }\n  BOOST_REQUIRE_CLOSE(results(2, 6), 0.46, 1e-5);\n\n  if (newFromOld[6] < newFromOld[7])\n  {\n    BOOST_REQUIRE_EQUAL(results(0, 7), newFromOld[6]);\n    BOOST_REQUIRE_EQUAL(results(1, 7), newFromOld[7]);\n  }\n  else\n  {\n    BOOST_REQUIRE_EQUAL(results(1, 7), newFromOld[6]);\n    BOOST_REQUIRE_EQUAL(results(0, 7), newFromOld[7]);\n  }\n  BOOST_REQUIRE_CLOSE(results(2, 7), 0.7, 1e-5);\n\n  if (newFromOld[5] < newFromOld[7])\n  {\n    BOOST_REQUIRE_EQUAL(results(0, 8), newFromOld[5]);\n    BOOST_REQUIRE_EQUAL(results(1, 8), newFromOld[7]);\n  }\n  else\n  {\n    BOOST_REQUIRE_EQUAL(results(1, 8), newFromOld[5]);\n    BOOST_REQUIRE_EQUAL(results(0, 8), newFromOld[7]);\n  }\n  BOOST_REQUIRE_CLOSE(results(2, 8), 1.08, 1e-5);\n\n  if (newFromOld[3] < newFromOld[4])\n  {\n    BOOST_REQUIRE_EQUAL(results(0, 9), newFromOld[3]);\n    BOOST_REQUIRE_EQUAL(results(1, 9), newFromOld[4]);\n  }\n  else\n  {\n    BOOST_REQUIRE_EQUAL(results(1, 9), newFromOld[3]);\n    BOOST_REQUIRE_EQUAL(results(0, 9), newFromOld[4]);\n  }\n  BOOST_REQUIRE_CLOSE(results(2, 9), 3.8, 1e-5);\n}\n\n/**\n * Test the dual tree method against the naive computation.\n *\n * Errors are produced if the results are not identical.\n */\nBOOST_AUTO_TEST_CASE(DualTreeVsNaive)\n{\n  arma::mat inputData;\n\n  // Hard-coded filename: bad!\n  // Code duplication: also bad!\n  if (!data::Load(\"test_data_3_1000.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset test_data_3_1000.csv!\");\n\n  // Set up matrices to work with.\n  arma::mat dualData = inputData;\n  arma::mat naiveData = inputData;\n\n  // Reset parameters from last test.\n  DualTreeBoruvka<> dtb(dualData);\n\n  arma::mat dualResults;\n  dtb.ComputeMST(dualResults);\n\n  // Set naive mode.\n  DualTreeBoruvka<> dtbNaive(naiveData, true);\n\n  arma::mat naiveResults;\n  dtbNaive.ComputeMST(naiveResults);\n\n  BOOST_REQUIRE_EQUAL(dualResults.n_cols, naiveResults.n_cols);\n  BOOST_REQUIRE_EQUAL(dualResults.n_rows, naiveResults.n_rows);\n\n  for (size_t i = 0; i < dualResults.n_cols; i++)\n  {\n    BOOST_REQUIRE_EQUAL(dualResults(0, i), naiveResults(0, i));\n    BOOST_REQUIRE_EQUAL(dualResults(1, i), naiveResults(1, i));\n    BOOST_REQUIRE_CLOSE(dualResults(2, i), naiveResults(2, i), 1e-5);\n  }\n}\n\n/**\n * Make sure the cover tree works fine.\n */\nBOOST_AUTO_TEST_CASE(CoverTreeTest)\n{\n  arma::mat inputData;\n  if (!data::Load(\"test_data_3_1000.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset test_data_3_1000.csv!\");\n\n  DualTreeBoruvka<> bst(inputData);\n  DualTreeBoruvka<EuclideanDistance, arma::mat, StandardCoverTree>\n      ct(inputData);\n\n  arma::mat bstResults;\n  arma::mat coverResults;\n\n  // Run the algorithms.\n  bst.ComputeMST(bstResults);\n  ct.ComputeMST(coverResults);\n\n  for (size_t i = 0; i < bstResults.n_cols; i++)\n  {\n    BOOST_REQUIRE_EQUAL(bstResults(0, i), coverResults(0, i));\n    BOOST_REQUIRE_EQUAL(bstResults(1, i), coverResults(1, i));\n    BOOST_REQUIRE_CLOSE(bstResults(2, i), coverResults(2, i), 1e-5);\n  }\n\n}\n\n/**\n * Test BinarySpaceTree with Ball Bound.\n */\nBOOST_AUTO_TEST_CASE(BallTreeTest)\n{\n  arma::mat inputData;\n  if (!data::Load(\"test_data_3_1000.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset test_data_3_1000.csv!\");\n\n  // naive mode.\n  DualTreeBoruvka<> bst(inputData, true);\n  // Ball tree.\n  DualTreeBoruvka<EuclideanDistance, arma::mat, BallTree> ballt(inputData);\n\n  arma::mat bstResults;\n  arma::mat ballResults;\n\n  // Run the algorithms.\n  bst.ComputeMST(bstResults);\n  ballt.ComputeMST(ballResults);\n\n  for (size_t i = 0; i < bstResults.n_cols; i++)\n  {\n    BOOST_REQUIRE_EQUAL(bstResults(0, i), ballResults(0, i));\n    BOOST_REQUIRE_EQUAL(bstResults(1, i), ballResults(1, i));\n    BOOST_REQUIRE_CLOSE(bstResults(2, i), ballResults(2, i), 1e-5);\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b4776584b15321f6cd2404e4801c1941b1517e16", "size": 7534, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/emst_test.cpp", "max_stars_repo_name": "vj-ug/Contribution-to-mlpack", "max_stars_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T11:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:20.000Z", "max_issues_repo_path": "src/mlpack/tests/emst_test.cpp", "max_issues_repo_name": "vj-ug/Contribution-to-mlpack", "max_issues_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/emst_test.cpp", "max_forks_repo_name": "vj-ug/Contribution-to-mlpack", "max_forks_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "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.0035842294, "max_line_length": 80, "alphanum_fraction": 0.6860897266, "num_tokens": 2423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5016014172417619}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_DIVROUND_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_DIVROUND_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/divround.hpp>\n#include <boost/simd/include/functions/scalar/round.hpp>\n#include <boost/simd/include/functions/scalar/copysign.hpp>\n#include <boost/simd/include/functions/scalar/is_odd.hpp>\n#include <boost/simd/include/constants/valmin.hpp>\n#include <boost/simd/include/constants/valmax.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( divround_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< int64_<A0> >)\n                                      (scalar_< int64_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      if (!a0) return  Zero<result_type>();\n      if(a1)\n      {\n        A0 aa0 = abs(a0);\n        A0 aa1 = abs(a1);\n        result_type q = aa0/aa1;\n        result_type r = aa0-q*aa1;\n        if ((r!= 0) && (r-is_odd(aa1) >= (aa1 >> 1))) ++q;\n        return copysign(q, a0^a1);\n      }\n      else\n        return ((a0>0) ? Valmax<result_type>() : Valmin<result_type>());\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( divround_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< signed_<A0> >)\n                                      (scalar_< signed_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      if(a1)\n        return static_cast<result_type >(round(static_cast<double>(a0)/static_cast<double>(a1)));\n      else\n      {\n        return (a0) ? ((a0>0) ? Valmax<result_type>() : Valmin<result_type>()) : Zero<result_type>();\n      }\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( divround_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< unsigned_<A0> >)\n                                      (scalar_< unsigned_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      if(a1)\n      {\n        result_type q = a0/a1;\n        result_type r = a0-q*a1;\n        if ((r!= 0) && (r-is_odd(a1) >= (a1 >> 1))) ++q;\n        return q;\n      }\n      else\n        return (a0) ? Valmax<result_type>() : Zero<result_type>();\n    }\n  };\n\n#ifdef BOOST_MSVC\n  #pragma warning(push)\n  #pragma warning(disable: 4723) // potential divide by 0\n#endif\n  BOOST_DISPATCH_IMPLEMENT          ( divround_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< floating_<A0> >)\n                                      (scalar_< floating_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return boost::simd::round(a0/a1);\n    }\n  };\n} } }\n\n#ifdef BOOST_MSVC\n  #pragma warning(pop)\n#endif\n\n#endif\n", "meta": {"hexsha": "a31a8443837d194ef9b9ab9a8297eb856836c51c", "size": 3663, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/divround.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/divround.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/divround.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 32.7053571429, "max_line_length": 101, "alphanum_fraction": 0.5012285012, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.5015084906472644}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <vector>\n\n#include \"flux_worker.hpp\"\n\nnamespace boltzmann {\nnamespace impl {\n\n/**\n * @brief \\f$\\langle< \\mathbf{v} \\dot \\mathbf{n} \\phi, f \\rangle\\f$\n *\n * velocity part (in Lagrange basis)\n *\n * upper hemisphere: outflow\n * lower hemisphere: inflow\n *\n */\nclass IdentityBD : public flux_worker\n{\n  using flux_worker::vec_t;\n  using flux_worker::mat_t;\n\n public:\n  IdentityBD(const vec_t& hermite_weights, const vec_t& hermite_nodes)\n      : w_(hermite_weights)\n      , x_(hermite_nodes)\n  {\n  }\n\n  /**\n   *\n   *\n   * @param out Ordering: out(i,j) = f(x_i, y_j)\n   * \\remark{Also see documentation of @ref H2N.}\n   * @param in\n   */\n  virtual void apply(mat_t& out, const mat_t& in, const dealii::Point<2>& dummy) const;\n\n private:\n  const vec_t w_;\n  const vec_t x_;\n};\n\nvoid\nIdentityBD::apply(mat_t& out, const mat_t& in, const dealii::Point<2>& dummy) const\n{\n  AssertDimension(in.rows(), out.rows());\n  AssertDimension(in.cols(), out.cols());\n  AssertDimension(in.cols(), w_.size());\n\n  int N = w_.size();\n\n  out = in;\n\n  // multiply with weights\n  for (int j = 0; j < N; ++j) {\n    for (int i = 0; i < N; ++i) {\n      out(i, j) *= x_[i];\n    }\n  }\n}\n\n}  // end namespace impl\n}  // end namespace boltzmann\n", "meta": {"hexsha": "47802d9e30d21e4943ae3a1870ef44ab99867e47", "size": 1257, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/matrix/bc/impl/mls/identity_helper.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/matrix/bc/impl/mls/identity_helper.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/matrix/bc/impl/mls/identity_helper.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": 18.7611940299, "max_line_length": 87, "alphanum_fraction": 0.6245027844, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5015084906472643}}
{"text": "\n/* multiprecision_float_test.cpp\n*\n* Copyright John Maddock 2015\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$\n*\n* Tests all floating point related generators and distributions with multiprecision types.\n*/\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/debug_adaptor.hpp>\n#include <boost/scoped_ptr.hpp>\n#include <boost/random.hpp>\n#include <sstream>\n\n\ntypedef boost::multiprecision::number<boost::multiprecision::cpp_bin_float_100::backend_type, boost::multiprecision::et_on > big_float;\ntypedef boost::random::subtract_with_carry_01_engine<big_float, 48, 10, 24 > ranlux_big_base_01;\ntypedef boost::random::independent_bits_engine<boost::random::mt19937, 1024, boost::multiprecision::uint1024_t> large_int_generator;\n\ntypedef boost::mpl::list <\n   boost::random::lagged_fibonacci_01_engine<big_float, 48, 44497, 21034 >,\n   boost::random::discard_block_engine< ranlux_big_base_01, 389, 24 >\n> engines;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(generator_test, engine_type, engines)\n{\n   typedef typename engine_type::result_type test_type;\n\n   boost::scoped_ptr<engine_type> gen(new engine_type());\n   unsigned seeds[] = { 1, 2, 3, 4 };\n   unsigned *p1 = seeds, *p2 = seeds + 4;\n   BOOST_CHECK_THROW(gen->seed(p1, p2), std::invalid_argument);\n   gen->seed();\n   gen->seed(2);\n   test_type a = gen->min();\n   test_type b = gen->max();\n   BOOST_CHECK(a < b);\n   for(unsigned i = 0; i < 200; ++i)\n   {\n      test_type r = (*gen)();\n      BOOST_CHECK((boost::math::isfinite)(r));\n      BOOST_CHECK(a <= r);\n      BOOST_CHECK(b >= r);\n   }\n   gen->discard(20);\n\n   std::stringstream ss;\n   ss << std::setprecision(std::numeric_limits<test_type>::digits10 + 3) << *gen;\n   boost::scoped_ptr<engine_type> gen2(new engine_type());\n   ss >> *gen2;\n   BOOST_CHECK(*gen == *gen2);\n   (*gen2)();\n   BOOST_CHECK(*gen != *gen2);\n}\n\ntypedef boost::mpl::list <\n   boost::random::bernoulli_distribution<big_float>,\n   boost::random::beta_distribution<big_float>,\n   boost::random::cauchy_distribution<big_float>,\n   boost::random::chi_squared_distribution<big_float>,\n   boost::random::exponential_distribution<big_float>,\n   boost::random::extreme_value_distribution<big_float>,\n   boost::random::fisher_f_distribution<big_float>,\n   boost::random::gamma_distribution<big_float>,\n   boost::random::laplace_distribution<big_float>,\n   boost::random::lognormal_distribution<big_float>,\n   boost::random::normal_distribution<big_float>,\n#ifndef BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS\n   boost::random::piecewise_constant_distribution<big_float>,\n   boost::random::piecewise_linear_distribution<big_float>,\n#endif\n   boost::random::student_t_distribution<big_float>,\n   boost::random::triangle_distribution<big_float>,\n   //boost::random::uniform_01<big_float>,  // doesn't respect the concept!  But gets used internally anyway.\n   boost::random::uniform_real_distribution<big_float>,\n   boost::random::uniform_on_sphere<big_float>,\n   boost::random::weibull_distribution<big_float>\n> distributions;\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(distributions_test, dist_type, distributions)\n{\n   typedef typename dist_type::result_type result_type;\n   dist_type d;\n   result_type a = (d.min)();\n   result_type b = (d.max)();\n   typename dist_type::param_type p = d.param();\n   boost::ignore_unused(p);\n   d.reset();\n\n   std::stringstream ss;\n   ss << std::setprecision(std::numeric_limits<result_type>::digits10 + 3) << d;\n   dist_type d2;\n   ss >> d2;\n   BOOST_CHECK(d == d2);\n\n   boost::random::mt19937 int_gen;\n\n   for(unsigned i = 0; i < 200; ++i)\n   {\n      result_type r = d(int_gen);\n      BOOST_CHECK((boost::math::isfinite)(r));\n      BOOST_CHECK(r >= a);\n      BOOST_CHECK(r <= b);\n   }\n\n#ifndef BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS\n   large_int_generator big_int_gen;\n\n   for(unsigned i = 0; i < 200; ++i)\n   {\n      result_type r = d(big_int_gen);\n      BOOST_CHECK((boost::math::isfinite)(r));\n      BOOST_CHECK(r >= a);\n      BOOST_CHECK(r <= b);\n   }\n\n   boost::random::discard_block_engine< ranlux_big_base_01, 389, 24 > big_float_gen;\n\n   for(unsigned i = 0; i < 200; ++i)\n   {\n      result_type r = d(big_float_gen);\n      BOOST_CHECK((boost::math::isfinite)(r));\n      BOOST_CHECK(r >= a);\n      BOOST_CHECK(r <= b);\n   }\n#endif\n\n   boost::random::ranlux64_4_01 float_gen;\n\n   for(unsigned i = 0; i < 200; ++i)\n   {\n      result_type r = d(float_gen);\n      BOOST_CHECK((boost::math::isfinite)(r));\n      BOOST_CHECK(r >= a);\n      BOOST_CHECK(r <= b);\n   }\n}\n\n\n\nBOOST_AUTO_TEST_CASE(canonical_test)\n{\n   typedef big_float result_type;\n\n   boost::random::mt19937 int_gen;\n\n   for(unsigned i = 0; i < 200; ++i)\n   {\n      result_type r = boost::random::generate_canonical<big_float, std::numeric_limits<big_float>::digits>(int_gen);\n      BOOST_CHECK((boost::math::isfinite)(r));\n      BOOST_CHECK(r >= 0);\n      BOOST_CHECK(r <= 1);\n   }\n\n   large_int_generator big_int_gen;\n\n   for(unsigned i = 0; i < 200; ++i)\n   {\n      result_type r = boost::random::generate_canonical<big_float, std::numeric_limits<big_float>::digits>(big_int_gen);\n      BOOST_CHECK((boost::math::isfinite)(r));\n      BOOST_CHECK(r >= 0);\n      BOOST_CHECK(r <= 1);\n   }\n\n\n   boost::random::discard_block_engine< ranlux_big_base_01, 389, 24 > big_float_gen;\n\n   for(unsigned i = 0; i < 200; ++i)\n   {\n      result_type r = boost::random::generate_canonical<big_float, std::numeric_limits<big_float>::digits>(big_float_gen);\n      BOOST_CHECK((boost::math::isfinite)(r));\n      BOOST_CHECK(r >= 0);\n      BOOST_CHECK(r <= 1);\n   }\n\n   boost::random::ranlux64_4_01 float_gen;\n\n   for(unsigned i = 0; i < 200; ++i)\n   {\n      result_type r = boost::random::generate_canonical<big_float, std::numeric_limits<big_float>::digits>(float_gen);\n      BOOST_CHECK((boost::math::isfinite)(r));\n      BOOST_CHECK(r >= 0);\n      BOOST_CHECK(r <= 1);\n   }\n\n}\n", "meta": {"hexsha": "6d80db279e97756893f3801f3d59cea48d82510b", "size": 6108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/random/test/multiprecision_float_test.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/random/test/multiprecision_float_test.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/random/test/multiprecision_float_test.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 30.8484848485, "max_line_length": 135, "alphanum_fraction": 0.690897184, "num_tokens": 1671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5015084906472643}}
{"text": "#include \"vds.h\"\n\n#include <math.h>\n#include <stdio.h>\n#include <boost/math/constants/constants.hpp>\n#include \"vector_td_utilities.h\"\n#include <boost/range/combine.hpp>\n#include <boost/range/algorithm.hpp>\n#include \"hoNDArray_math.h\"\n\nconstexpr double GAMMA = 4258.0;        /* Hz/G */\nconstexpr double PI = boost::math::constants::pi<double>();\n\n/* #define TESTCODE \tFor testing as regular C code... */\n\n/*\n  %\n  %\tVARIABLE DENSITY SPIRAL GENERATION:\n  %\t----------------------------------\n  %\n  %\tThis is a general description of how the following C code\n  %\tworks.  This text is taken from a matlab script, vds.m, from\n  %\twhich the C code was derived.  However, note that the C code\n  %\truns considerably faster.\n  %\n  %\n  %\tFunction generates variable density spiral which traces\n  %\tout the trajectory\n  %\t\t\t\t \n  %\t\t\tk(t) = r(t) exp(i*q(t)), \t\t[1]\n  %\n  %\tWhere q IS THE SAME AS theta, and r IS THE SAME AS kr.\n  %\n  %\t\tr and q are chosen to satisfy:\n  %\n  %\t\t1) Maximum gradient amplitudes and slew rates.\n  %\t\t2) Maximum gradient due to FOV, where FOV can\n  %\t\t   vary with k-space radius r, as\n  %\n  %\t\t\tFOV(r) = F0 + F1*r + F2*r*r \t\t[2]\n  %\n  %\n  %\tINPUTS:\n  %\t-------\n  %\tsmax = maximum slew rate G/cm/s\n  %\tgmax = maximum gradient G/cm (limited by Gmax or FOV)\n  %\tT = sampling period (s) for gradient AND acquisition.\n  %\tN = number of interleaves.\n  %\tF0,F1,F2 = FOV coefficients with respect to r - see above.\n  %\trmax= value of k-space radius at which to stop (cm^-1).\n  %\t\trmax = 1/(2*resolution);\n  %\n  %\n  %\tOUTPUTS:\n  %\t--------\n  %\tk = k-space trajectory (kx+iky) in cm-1.\n  %\tg = gradient waveform (Gx+iGy) in G/cm.\n  %\ts = derivative of g (Sx+iSy) in G/cm/s.\n  %\ttime = time points corresponding to above (s).\n  %\tr = k-space radius vs time (used to design spiral)\n  %\ttheta = atan2(ky,kx) = k-space angle vs time.\n  %\n  %\n  %\tMETHODS:\n  %\t--------\n  %\tLet r1 and r2 be the first derivatives of r in [1].\t\n  %\tLet q1 and q2 be the first derivatives of theta in [1].\t\n  %\tAlso, r0 = r, and q0 = theta - sometimes both are used.\n  %\tF = F(r) defined by F0,F1,F2.\n  %\n  %\tDifferentiating [1], we can get G = a(r0,r1,q0,q1,F)\t\n  %\tand differentiating again, we get S = b(r0,r1,r2,q0,q1,q2,F)\n  %\n  %\t(functions a() and b() are reasonably easy to obtain.)\n  %\n  %\tFOV limits put a constraint between r and q:\n  %\n  %\t\tdr/dq = N/(2*pi*F)\t\t\t\t[3]\t\n  %\n  %\tWe can use [3] and the chain rule to give \n  %\n  %\t\tq1 = 2*pi*F/N * r1\t\t\t\t[4]\n  %\n  %\tand\n  %\n  %\t\tq2 = 2*pi/N*dF/dr*r1^2 + 2*pi*F/N*r2\t\t[5]\n  %\n  %\n  %\n  %\tNow using [4] and [5], we can substitute for q1 and q2\n  %\tin functions a() and b(), giving\n  %\n  %\t\tG = c(r0,r1,F)\n  %\tand \tS = d(r0,r1,r2,F,dF/dr)\n  %\n  %\n  %\tUsing the fact that the spiral should be either limited\n  %\tby amplitude (Gradient or FOV limit) or slew rate, we can\n  %\tsolve \n  %\t\t|c(r0,r1,F)| = |Gmax|  \t\t\t\t[6]\n  %\n  %\tanalytically for r1, or\n  %\t\n  %\t  \t|d(r0,r1,r2,F,dF/dr)| = |Smax|\t \t\t[7]\n  %\n  %\tanalytically for r2.\n  %\n  %\t[7] is a quadratic equation in r2.  The smaller of the \n  %\troots is taken, and the real part of the root is used to\n  %\tavoid possible numeric errors - the roots should be real\n  %\talways.\n  %\n  %\tThe choice of whether or not to use [6] or [7], and the\n  %\tsolving for r2 or r1 is done by calcthetadotdot().\n  %\n  %\tOnce the second derivative of theta(q) or r is obtained,\n  %\tit can be integrated to give q1 and r1, and then integrated\n  %\tagain to give q and r.  The gradient waveforms follow from\n  %\tq and r. \t\n  %\n  %\tBrian Hargreaves -- Sept 2000.\n  %\n  %\n*/\n\nnamespace Gadgetron {\n\n\n    /* ----------------------------------------------------------------------- */\n    void calcthetadotdot(double slewmax, double gradmax, double kr,\n                         double krdot, double Tgsample, double Tdsample, int Ninterleaves,\n                         double *fov, int numfov, double *thetadotdot, double *krdotdot)\n    /*\n     * Function calculates the 2nd derivative of kr and theta at each\n     * sample point within calc_vds().  ie, this is the iterative loop\n     * for calc_vds.  See the text at the top of this file for more details\n     * */\n\n    //double slewmax;\t\t/*\tMaximum slew rate, G/cm/s\t\t*/\n    //double gradmax;\t\t/* \tmaximum gradient amplitude, G/cm\t*/\n    //double kr;\t\t/* \tCurrent kr. */\n    //double krdot;\t\t/*\tCurrent krdot. */\n    //double Tgsample;\t/*\tGradient Sample period (s) \t*/\n    //double Tdsample;\t/*\tData Sample period (s) \t\t*/\n    //int Ninterleaves;\t/*\tNumber of interleaves\t\t\t*/\n    //double *fov;\t\t/*\tFOV coefficients\t\t*/\n    //int numfov;\t\t/*\tNumber of FOV coefficients\t\t*/\n    //double *thetadotdot;\t/*\t[output] 2nd derivative of theta.\t*/\n    //double *krdotdot;\t/*\t[output] 2nd derivative of kr\t\t*/\n\n    /* ----------------------------------------------------------------------- */\n    {\n        double fovval = 0;    /* FOV for this value of kr\t*/\n        double dfovdrval = 0;    /* dFOV/dkr for this value of kr\t*/\n        double gmaxfov;        /* FOV-limited Gmax.\t*/\n        double maxkrdot;\n        int count;\n\n        double tpf;    /* Used to simplify expressions. */\n        double tpfsq;    /* \t\" \t\t\"        */\n\n        double qdfA, qdfB, qdfC;    /* Quadratic formula coefficients */\n        double rootparta, rootpartb;\n\n\n        /* Calculate the actual FOV and dFOV/dkr for this R,\n         * based on the fact that the FOV is expressed\n         * as a polynomial in kr.*/\n\n        for (count = 0; count < numfov; count++) {\n            fovval = fovval + fov[count] * pow(kr, count);\n            if (count > 0)\n                dfovdrval = dfovdrval + count * fov[count] * pow(kr, count - 1);\n        }\n\n        /* Calculate FOV limit on gmax.  This is the rate of motion along\n         * a trajectory, and really should not be a limitation.  Thus,\n         * it is reasonable to comment out the following lines. */\n\n        gmaxfov = 1 / GAMMA / fovval / Tdsample;\n        if (gradmax > gmaxfov)\n            gradmax = gmaxfov;\n\n\n        /* Maximum dkr/dt, based on gradient amplitude.  */\n\n        maxkrdot = sqrt(pow(GAMMA * gradmax, 2) / (1 + pow(2 * PI * fovval * kr / Ninterleaves, 2)));\n\n\n        /* These two are just to simplify expressions below */\n        tpf = 2 * PI * fovval / Ninterleaves;\n        tpfsq = pow(tpf, 2);\n\n\n        if (krdot > maxkrdot)    /* Then choose krdotdot so that krdot is in range */\n        {\n            *krdotdot = (maxkrdot - krdot) / Tgsample;\n        } else            /* Choose krdotdot based on max slew rate limit. */\n        {\n\n            /* Set up for quadratic formula solution. */\n\n            qdfA = 1 + tpfsq * kr * kr;\n            qdfB = 2 * tpfsq * kr * krdot * krdot +\n                   2 * tpfsq / fovval * dfovdrval * kr * kr * krdot * krdot;\n            qdfC = pow(tpfsq * kr * krdot * krdot, 2) + 4 * tpfsq * pow(krdot, 4) +\n                   pow(tpf * dfovdrval / fovval * kr * krdot * krdot, 2) +\n                   4 * tpfsq * dfovdrval / fovval * kr * pow(krdot, 4) -\n                   pow(GAMMA * slewmax, 2);\n\n\n            rootparta = -qdfB / (2 * qdfA);\n            rootpartb = qdfB * qdfB / (4 * qdfA * qdfA) - qdfC / qdfA;\n\n            if (rootpartb < 0)    /* Safety check - if complex, take real part.*/\n\n                *krdotdot = rootparta;\n\n            else\n                *krdotdot = rootparta + sqrt(rootpartb);\n\n\n            /* Could check resulting slew rate here, as in q2r21.m. */\n        }\n\n        /* Calculate thetadotdot */\n\n\n        *thetadotdot = tpf * dfovdrval / fovval * krdot * krdot + tpf * (*krdotdot);\n    }\n\n\n    /* ----------------------------------------------------------------------- */\n    void\n    calc_vds(double slewmax, double gradmax, double Tgsample, double Tdsample, int Ninterleaves,\n             double *fov, int numfov, double krmax,\n             int ngmax, double **xgrad, double **ygrad, int *numgrad)\n\n    /*\tFunction designs a variable-density spiral gradient waveform\n     *\tthat is defined by a number of interleaves, resolution (or max number\n     *\tof samples), and field-of-view.\n     *\tThe field-of-view is a polynomial function of the\n     *\tk-space radius, so fov is an array of coefficients so that\n     *\n     *\tFOV = fov[0]+fov[1]*kr+fov[2]*kr^2+ ... +fov[numfov-1]*kr^(numfov-1)\n     *\n     * \tGradient design is subject to a constant-slew-rate-limit model,\n     * \twith maximum slew rate slewmax, and maximum gradient amplitude\n     * \tof gradmax.\n     *\n     * \tTgsample is the gradient sampling rate, and Tdsample is the data\n     * \tsampling rate.  It is highly recommended to OVERSAMPLE the gradient\n     * \tin the design to make the integration more stable.\n     *\n     * */\n\n    //double slewmax;\t\t/*\tMaximum slew rate, G/cm/s\t\t*/\n    //double gradmax;\t\t/* \tmaximum gradient amplitude, G/cm\t*/\n    //double Tgsample;\t/*\tGradient Sample period (s)\t\t*/\n    //double Tdsample;\t/*\tData Sample period (s)\t\t\t*/\n    //int Ninterleaves;\t/*\tNumber of interleaves\t\t\t*/\n    //double *fov;\t\t/*\tFOV coefficients\t\t*/\n    //int numfov;\t\t/*\tNumber of FOV coefficients\t\t*/\n    //double krmax;\t\t/*\tMaximum k-space extent (/cm)\t\t*/\n    //int ngmax;\t\t/*\tMaximum number of gradient samples\t*/\n    //double **xgrad;\t\t/* \t[output] X-component of gradient (G/cm) */\n    //double **ygrad;\t\t/*\t[output] Y-component of gradient (G/cm)\t*/\n    //int *numgrad;\t\t/* \t[output] Number of gradient samples */\n\n    /* ----------------------------------------------------------------------- */\n    {\n        int gradcount = 0;\n\n        double kr = 0;            /* Current value of kr\t*/\n        double krdot = 0;        /* Current value of 1st derivative of kr */\n        double krdotdot = 0;        /* Current value of 2nd derivative of kr */\n\n        double theta = 0;            /* Current value of theta */\n        double thetadot = 0;        /* Current value of 1st derivative of theta */\n        double thetadotdot = 0;        /* Current value of 2nd derivative of theta */\n\n        double lastkx = 0;        /* x-component of last k-location. */\n        double lastky = 0;        /* y-component of last k-location */\n        double kx, ky;            /* x and y components of current k-location */\n\n        double *gxptr, *gyptr;        /* Pointers to gradient variables. */\n\n\n\n        /* First just find the gradient length. */\n\n        while ((kr < krmax) && (gradcount < ngmax)) {\n            calcthetadotdot(slewmax, gradmax, kr, krdot, Tgsample, Tdsample,\n                            Ninterleaves, fov, numfov, &thetadotdot, &krdotdot);\n\n            /* Integrate to obtain new values of kr, krdot, theta and thetadot:*/\n\n            thetadot = thetadot + thetadotdot * Tgsample;\n            theta = theta + thetadot * Tgsample;\n\n            krdot = krdot + krdotdot * Tgsample;\n            kr = kr + krdot * Tgsample;\n\n            gradcount++;\n\n        }\n\n\n\n        /* Allocate memory for gradients. */\n\n        *numgrad = gradcount;\n\n        //*xgrad = (double *)malloc(*numgrad*sizeof(double));\n        //*ygrad = (double *)malloc(*numgrad*sizeof(double));\n\n        *xgrad = new double[*numgrad];\n        *ygrad = new double[*numgrad];\n\n        /* Reset parameters */\n\n        kr = 0;\n        krdot = 0;\n        theta = 0;\n        thetadot = 0;\n        gradcount = 0;\n        gxptr = *xgrad;\n        gyptr = *ygrad;\n\n\n        /* Now re-calculate gradient to find length. */\n\n        while ((kr < krmax) && (gradcount < ngmax)) {\n            calcthetadotdot(slewmax, gradmax, kr, krdot, Tgsample, Tdsample,\n                            Ninterleaves, fov, numfov, &thetadotdot, &krdotdot);\n\n            /* Integrate to obtain new values of kr, krdot, theta and thetadot:*/\n\n            thetadot = thetadot + thetadotdot * Tgsample;\n            theta = theta + thetadot * Tgsample;\n\n            krdot = krdot + krdotdot * Tgsample;\n            kr = kr + krdot * Tgsample;\n\n            /* Define current gradient values from kr and theta. */\n\n            kx = kr * cos(theta);\n            ky = kr * sin(theta);\n            *gxptr++ = (1 / GAMMA / Tgsample) * (kx - lastkx);\n            *gyptr++ = (1 / GAMMA / Tgsample) * (ky - lastky);\n            lastkx = kx;\n            lastky = ky;\n\n            gradcount++;\n        }\n\n    }\n\n\n    /* ----------------------------------------------------------------------- */\n    void\n    calc_traj(double *xgrad, double *ygrad, int ngrad, int Nints, double Tgsamp, double krmax,\n              double **x_trajectory, double **y_trajectory,\n              double **weights) //, double** y_weights)\n    /*\n     *inputs:\n     *      xgrad   X gradient waveform\n     *      ygrad   Y gradient waveform\n     *      ngrad   number of gradient samples\n     *      Nints   number of interleaves\n     *      Tgsamp  sampling time for gradients\n     *\n     *outputs:\n     *      x_trajectory    X position in k-space\n     *      y_trajectory    Y position in k-space\n     *      x_weights       X weighting\n     *      y_weights       Y weighting\n     *\n     **/\n    {\n\n        *x_trajectory = new double[(ngrad * Nints)];\n        *y_trajectory = new double[(ngrad * Nints)];\n        *weights = new double[(ngrad * Nints)];\n\n        double *txptr = *x_trajectory;\n        double *typtr = *y_trajectory;\n        double *wptr = *weights;\n\n        for (int inter = 0; inter < Nints; inter++) {\n            double rotation = (inter * 2 * PI) / Nints;\n            double x_tr = 0;\n            double y_tr = 0;\n            float x_temp, y_temp;\n            for (int gradcount = 0; gradcount < ngrad; gradcount++) {\n                if (gradcount > 0) {\n                    x_tr += (GAMMA) * xgrad[gradcount - 1] * Tgsamp;\n                    y_tr += (GAMMA) * ygrad[gradcount - 1] * Tgsamp;\n                }\n\n                x_temp = (x_tr * cos(rotation)) + (y_tr * sin(rotation));\n                y_temp = -(x_tr * sin(rotation)) + (y_tr * cos(rotation));\n                *(txptr++) = x_temp / krmax;\n                *(typtr++) = y_temp / krmax;\n\n                //abs(g(:)\n                double abs_w = sqrt((pow(xgrad[gradcount], 2)) + (pow(ygrad[gradcount], 2)));\n                double ang_g = xgrad[gradcount] == 0.0 ? PI/2 : atan2(ygrad[gradcount],xgrad[gradcount]);\n\n                double ang_t = x_tr == 0.0 ? PI/2 : atan2(y_tr,x_tr);\n\n                double tp_w = sin(ang_g - ang_t);\n                tp_w = abs_w * abs(tp_w);\n                *wptr++ = tp_w;\n            }\n        }\n    }\n    hoNDArray<float> calculate_weights(const hoNDArray<floatd2> &gradients, const hoNDArray<floatd2> &trajectories) {\n\n        hoNDArray<float> weights(gradients.dimensions());\n\n\n        boost::transform(gradients,trajectories,weights.begin(),\n                [](const floatd2& gradient,const floatd2& trajectory){\n                    auto abs_w = norm(gradient);\n                    auto ang_g = atan2(gradient[1],gradient[0]);\n                    auto ang_t = atan2(trajectory[1],trajectory[0]);\n                    return abs(sin(ang_g-ang_t))*abs_w*2;\n\n        });\n\n        return weights;\n    }\n\n    hoNDArray<float> calculate_weights_Hoge(const hoNDArray<floatd2> &gradients, const hoNDArray<floatd2> &trajectories) {\n\n        hoNDArray<float> weights(gradients.dimensions());\n\n\n        boost::transform(gradients,trajectories,weights.begin(),\n                [](const floatd2& gradient,const floatd2& trajectory){\n                    auto abs_g = norm(gradient);\n                    auto abs_t = norm(trajectory);\n                    auto ang_g = atan2(gradient[1],gradient[0]);\n                    auto ang_t = atan2(trajectory[1],trajectory[0]);\n                    return abs(cos(ang_g-ang_t))*abs_g*abs_t;\n\n        });\n\n        return weights;\n    }\n\n    hoNDArray<floatd2> calculate_trajectories(const hoNDArray<floatd2> &gradients, float sample_time, float krmax) {\n                const int nints = gradients.get_size(1);\n        const int ngrad = gradients.get_size(0);\n\n        auto trajectory = hoNDArray < floatd2 > (gradients.dimensions());\n\n        for (int interleave = 0; interleave < nints; interleave++) {\n            trajectory(0, interleave) = floatd2(0, 0);\n\n            for (int gradcount = 1; gradcount < ngrad; gradcount++) {\n                trajectory(gradcount, interleave) = trajectory(gradcount - 1, interleave) +\n                                                    float(GAMMA) * gradients(gradcount - 1,interleave) * sample_time;\n            }\n        }\n\n        boost::transform(trajectory,trajectory.begin(),[&](auto t){ return t/krmax;});\n        return trajectory;\n    }\n\n\n\n    hoNDArray<floatd2> calculate_vds(double slewmax, double gradmax, double Tgsample, double Tdsample, int Ninterleaves,\n             double *fov, int numfov, double krmax, int ngmax,int max_nsamples){\n\n        double* x_ptr;\n        double* y_ptr;\n        int Nints;\n        calc_vds(slewmax,gradmax,Tgsample,Tdsample,Ninterleaves,fov, numfov,krmax,ngmax,&x_ptr,&y_ptr,&Nints);\n\n        hoNDArray<floatd2> gradient(std::min(Nints,max_nsamples));\n        size_t nsamples = gradient.get_number_of_elements();\n        std::transform(x_ptr,x_ptr+nsamples,y_ptr,gradient.begin(),[](auto x, auto y){return -floatd2(x,y)/2;});\n\n        delete[] x_ptr;\n        delete[] y_ptr;\n        return gradient;\n\n    }\n\n\n    hoNDArray<floatd2>  create_rotations(const hoNDArray<floatd2>& trajectories,int nints) {\n        auto dims = trajectories.dimensions();\n        dims.push_back(nints);\n         hoNDArray < floatd2 > result(dims);\n\n        int ngrad = trajectories.get_number_of_elements();\n        for (int inter = 0; inter < nints; inter++) {\n            double rotation = (inter * 2 * PI) / nints;\n            for (int gradcount = 0; gradcount < ngrad; gradcount++) {\n                floatd2 point = trajectories[gradcount];\n                result(gradcount, inter) = floatd2(point[0] * cos(rotation) + point[1] * sin(rotation),\n                                                  -point[0] * sin(rotation) + point[1] * cos(rotation));\n            }\n        }\n        return result;\n    }\n}\n\n\n", "meta": {"hexsha": "4f1ca17dc24c8fed0ce324a337017955340de8ed", "size": 17962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolboxes/mri/spiral/vds.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "toolboxes/mri/spiral/vds.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolboxes/mri/spiral/vds.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["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.08203125, "max_line_length": 122, "alphanum_fraction": 0.5486026055, "num_tokens": 5151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5015084849820551}}
{"text": "#include <fstream>\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <Eigen/Dense>\n\n\nvoid mapIdToIndex(int id, int& ix_cell, int& iy_cell, int map_width){\n  iy_cell = id / map_width;\n  ix_cell = id - iy_cell * map_width;\n}\n\nstd::vector<int> positionToMapIndex(double x, double y,\n   unsigned int width, unsigned int height, float resolution){\n  std::vector<int> index(2);\n  index[0] = floor(x / resolution) + width / 2;\n  index[1] = floor(y / resolution) + height / 2;\n\n  return index;\n}\n\nvoid findChange(bool& change, int occupation, int current_occupation){\n  if (current_occupation != occupation){\n    if (std::abs(current_occupation + occupation) == 1){\n      change = true;\n    }\n  }\n}\n\ndouble xCircleMinDist(int ix, int iy, int n_cells, Eigen::MatrixXi& map){\n  // https://www.geeksforgeeks.org/bresenhams-circle-drawing-algorithm/\n  float dist_sq = -1;\n  int occupation = map(ix, iy);\n  int x = n_cells;\n  int y = 0;\n  int err = 3 - (n_cells << 1);\n  bool found_change = false;\n\n  int xc, yc;\n  if (occupation != 0){\n    xc = x - 1;\n    yc = y;\n  }\n  else {\n    xc = x;\n    yc = y;\n  }\n\n  while (x >= y){\n    findChange(found_change, occupation, map(ix + x, iy + y)); // 1. octant\n    findChange(found_change, occupation, map(ix + y, iy + x)); // 2. octant\n    findChange(found_change, occupation, map(ix - y, iy + x)); // 3. octant\n    findChange(found_change, occupation, map(ix - x, iy + y)); // 4. octant\n    findChange(found_change, occupation, map(ix - x, iy - y)); // 5. octant\n    findChange(found_change, occupation, map(ix - y, iy - x)); // 6. octant\n    findChange(found_change, occupation, map(ix + y, iy - x)); // 7. octant\n    findChange(found_change, occupation, map(ix + x, iy - y)); // 8. octant\n\n    if (found_change){\n      double dist_sq_temp = xc * xc + yc * yc;\n      if (dist_sq == -1 || dist_sq > dist_sq_temp){\n        dist_sq = dist_sq_temp;\n      }\n    }\n\n    y++;\n    if (err > 0){\n      x--;\n      err += ((y - x) << 2) + 10; //<< 2 -> 4*\n    }\n    else {\n      err += (y << 2) + 6;\n    }\n\n    if (occupation != 0){\n      yc = y - 1;\n      xc = x - 1;\n    }\n    else {\n      yc = y;\n      xc = x;\n    }\n    found_change = false;\n  }\n  if (dist_sq != -1) return sqrt(dist_sq);\n  else return dist_sq;\n}\n\nint main(int argc, char **argv)\n{\n  // Init params\n  int map_width = 2000;\n  int map_height = 2000;\n  float map_resolution = 0.05;\n  Eigen::MatrixXi occ_mat(map_width, map_height);\n\n  // Get path and file name\n  std::string package_path = ros::package::getPath(\"crowdbot_active_slam\");\n  std::string save_directory_path = package_path + \"/\" + argv[1];\n  std::string map_path = save_directory_path + \"/occupancy_grid_map.txt\";\n  std::string save_path = save_directory_path + \"/sdf_map.txt\";\n\n  std::ifstream map_file(map_path.c_str());\n\n  std::string line;\n  int id = 0;\n\n  if (map_file.is_open()){\n    int x_cell, y_cell;\n    while (std::getline(map_file, line)){\n      mapIdToIndex(id, x_cell, y_cell, map_width);\n      std::stringstream ss_ref;\n      ss_ref << line;\n      double p_ref;\n      ss_ref >> p_ref;\n\n      if (p_ref == -1){\n        occ_mat(x_cell, y_cell) = -1;\n      }\n      else if (p_ref >= 50){\n        occ_mat(x_cell, y_cell) = 1;\n      }\n      else {\n        occ_mat(x_cell, y_cell) = 0;\n      }\n      id += 1;\n    }\n  }\n  else {\n    ROS_INFO(\"Failed to open map_file!\");\n  }\n\n  // SDF calculation\n  // World borders (inflated by 1m from wall) for utm_0 world\n  double p1[2] = {-5.5, -13.5};\n  double p2[2] = {24.5, 21.5};\n\n  std::vector<int> p_start = positionToMapIndex(p1[0], p1[1], map_width, map_height, map_resolution);\n  std::vector<int> p_end = positionToMapIndex(p2[0], p2[1], map_width, map_height, map_resolution);\n\n  int sdf_width = p_end[0] - p_start[0] + 1;\n  int sdf_height = p_end[1] - p_start[1] + 1;\n  Eigen::MatrixXd SDF_mat(sdf_width, sdf_height);\n\n  int border = 0;\n  int counter = 0;\n  // Calculate SDF\n  #pragma omp parallel for\n  for (int i = p_start[0]; i <= p_end[0]; i++){\n    int n = 1;\n    double dist = -1;\n    bool not_found = true;\n    for (int j = p_start[1]; j <= p_end[1]; j++){\n      // Search for shortest distance of (i, j) and assign distance to SDF map\n      dist = -1;\n      not_found = true;\n      while (not_found){\n        dist = xCircleMinDist(i, j, n, occ_mat);\n        if (dist == -1){\n          n += 1;\n        }\n        else {\n          not_found = false;\n          double temp_dist = xCircleMinDist(i, j, n + 1, occ_mat);\n          if (dist > temp_dist && temp_dist != -1){\n            dist = temp_dist;\n          }\n          if (n > 2) n -= 2;\n          else n = 1;\n        }\n      }\n\n      if (occ_mat(i, j) == 0){\n        SDF_mat(i - p_start[0], j - p_start[1]) = dist;\n      }\n      else {\n        SDF_mat(i - p_start[0], j - p_start[1]) = -dist;\n      }\n    }\n\n    #pragma omp atomic\n    counter++;\n    int percent = 100 * counter / sdf_width;\n    if (percent >= border){\n      std::cout << percent << \" %\" << std::endl;\n      #pragma omp atomic\n      border += 1;\n    }\n  }\n\n  // Save map\n  std::ofstream sdf_file(save_path.c_str());\n  if (sdf_file.is_open()){\n    sdf_file << SDF_mat;\n    sdf_file.close();\n  }\n  else{\n    ROS_INFO(\"Could not save sdf_map.txt!\");\n  }\n}\n", "meta": {"hexsha": "c870a8b6b53ff6583f88ef5db602b77212484cdb", "size": 5189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_results/scripts/get_SDF.cpp", "max_stars_repo_name": "ethz-asl/crowdbot_active_slam", "max_stars_repo_head_hexsha": "007f1a730e06cea0aaf653dc2f024da1169b9c9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2019-10-03T10:05:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T06:27:05.000Z", "max_issues_repo_path": "test_results/scripts/get_SDF.cpp", "max_issues_repo_name": "ethz-asl/crowdbot_active_slam", "max_issues_repo_head_hexsha": "007f1a730e06cea0aaf653dc2f024da1169b9c9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-07T08:12:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-08T14:40:13.000Z", "max_forks_repo_path": "test_results/scripts/get_SDF.cpp", "max_forks_repo_name": "ethz-asl/crowdbot_active_slam", "max_forks_repo_head_hexsha": "007f1a730e06cea0aaf653dc2f024da1169b9c9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-11-24T15:15:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T07:53:01.000Z", "avg_line_length": 25.945, "max_line_length": 101, "alphanum_fraction": 0.5725573328, "num_tokens": 1621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5015084793168457}}
{"text": "#include <array>\n#include <iostream>\n#include <boost/numeric/odeint.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\nusing state_type = array<double, 3>;\n\nvoid lorenz_param(const state_type& x, state_type& dxdt, double t,\n                  double sigma, double R, double b) {\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\nvoid write_lorenz(const state_type& x, const double t) {\n    cout << t << '\\t' << x[0] << '\\t' << x[1] << '\\t' << x[2]\n         << endl;\n}\n\nint main(int argc, char **argv)\n{\n    const double sigma = 10.0;\n    const double R = 28.0;\n    const double b = 8.0/3.0;\n    using namespace std::placeholders;\n    auto lorenz = bind(lorenz_param, _1, _2, _3, sigma, R, b);\n    state_type x = { 10.0, 1.0, 1.0 }; // initial conditions\n    integrate(lorenz, x, 0.0, 25.0, 0.1, write_lorenz );\n    return 0;\n}\n", "meta": {"hexsha": "ce2d7ffdcbac2745520b55e8729005e8513ba7b6", "size": 907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CPlusPlus/Boost/lorenz.cpp", "max_stars_repo_name": "stijnvanhoey/training-material", "max_stars_repo_head_hexsha": "d8e23c2aefaaafbd6a6d5e059147831c651f21ec", "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": "CPlusPlus/Boost/lorenz.cpp", "max_issues_repo_name": "stijnvanhoey/training-material", "max_issues_repo_head_hexsha": "d8e23c2aefaaafbd6a6d5e059147831c651f21ec", "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": "CPlusPlus/Boost/lorenz.cpp", "max_forks_repo_name": "stijnvanhoey/training-material", "max_forks_repo_head_hexsha": "d8e23c2aefaaafbd6a6d5e059147831c651f21ec", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T22:45:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-07T22:45:34.000Z", "avg_line_length": 27.4848484848, "max_line_length": 66, "alphanum_fraction": 0.5821389195, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812552, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.5014732791903292}}
{"text": "#include \"students_t.h\"\n\n#include <boost/math/distributions/students_t.hpp>\nusing namespace boost::math;\n\ndouble get_t_value(double alpha, size_t df)\n{\n    //http://www.boost.org/doc/libs/1_39_0/libs/math/doc/sf_and_dist/html/\n    //       math_toolkit/dist/stat_tut/weg/st_eg/tut_mean_intervals.html\n    return quantile(complement(students_t(df), alpha / 2));\n}\n", "meta": {"hexsha": "13d2f1a7abc08cf5fc85722da24fba64c5930c03", "size": 363, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/evaluators/students_t.cc", "max_stars_repo_name": "brettdh/instruments", "max_stars_repo_head_hexsha": "7e07c1a9f63c9747360b543d140cff0603aa6f1c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-08-28T09:42:01.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-28T09:42:01.000Z", "max_issues_repo_path": "src/evaluators/students_t.cc", "max_issues_repo_name": "brettdh/instruments", "max_issues_repo_head_hexsha": "7e07c1a9f63c9747360b543d140cff0603aa6f1c", "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/evaluators/students_t.cc", "max_forks_repo_name": "brettdh/instruments", "max_forks_repo_head_hexsha": "7e07c1a9f63c9747360b543d140cff0603aa6f1c", "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.25, "max_line_length": 74, "alphanum_fraction": 0.741046832, "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5014732735479582}}
{"text": "#include <iomanip>\n#include <iostream>\n#include <armadillo>\n\n#include \"GordonNewell.h\"\n\nusing namespace std;\nusing namespace arma;\n\nvoid writeOutput(ofstream& ofstream, const mat& matrix, int K)\n{\n    ofstream << \"////////////////////////////////////////\" << endl;\n    ofstream << \"////////////////\" << \" K := \" << K << \" ////////////////\" << endl;\n    ofstream << \"////////////////////////////////////////\" << endl;\n\n    ofstream << endl;\n\n    for (int i = 0; i < matrix.n_rows; i++)\n        ofstream << \"X_\" << i + 1 << \" = \" << matrix(i, 0) << endl;\n\n    ofstream << endl;\n}\n\nvoid writeOutputBuzen(ofstream& ofstream, const mat& data, const int k, const int n, const double& T)\n{\n    ofstream << \"////////////////////////////////////////\" << endl;\n    ofstream << \"///////////\" << \" K := \" << k << \"; N := \" << n << \"; ///////////\" << endl;\n    ofstream << \"////////////////////////////////////////\" << endl;\n\n    ofstream << endl;\n\n    ofstream << \"T = \" << T << \" [s]\" << endl;\n\n    ofstream << endl;\n    ofstream << left\n        << setw(15) << \"Server #\"\n        << setw(15) << \"U\"\n        << setw(15) << \"X [1/s]\"\n        << setw(15) << \"n_avg\"\n        << setw(15) << \"R [s]\"\n        << endl;\n\n    for (int i = 0; i < data.n_rows; i++)\n    {\n        ofstream << left << setw(15) << i;\n\n        for (int j = 0; j < data.n_cols; j++)\n            ofstream << left << setw(15) << data(i, j);\n        \n        ofstream << endl;\n    }\n\n    ofstream << endl;\n}\n\nint main(int argc, char** argv)\n{\n    ofstream outputStream;\n    outputStream.open(\"potraznje_analiticki.txt\");\n\n    ofstream output10, output15, output20;\n    output10.open(\"rezultati_analiticki_10.txt\");\n    output15.open(\"rezultati_analiticki_15.txt\");\n    output20.open(\"rezultati_analiticki_20.txt\");\n\n    for (int k = 2; k <= 8; k++) \n    {\n        Analyzer gn(k);\n        mat result = gn.GetXMatrix();\n\n        writeOutput(outputStream, result, k);\n\n        for (int mprg = 10; mprg <= 20; mprg += 5)\n        {\n            double T;\n            mat data = gn.GetBuzenOutput(result, mprg, T);\n\n            ofstream* oref;\n            if (mprg == 10)\n                oref = &output10;\n            else if (mprg == 15)\n                oref = &output15;\n            else\n                oref = &output20;\n            \n            writeOutputBuzen(*oref, data, k, mprg, T);\n        }\n    }\n\n    outputStream.close();\n    output10.close();\n    output15.close();\n    output20.close();\n\n    return 0;\n}", "meta": {"hexsha": "366edb053e1930de78bb8d5b0467b8c79e633518", "size": 2463, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/analytics/main.cpp", "max_stars_repo_name": "cvetkovic/prs", "max_stars_repo_head_hexsha": "63a0a388e8544418a7c8f90fcb4a0b25eb9a734e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/analytics/main.cpp", "max_issues_repo_name": "cvetkovic/prs", "max_issues_repo_head_hexsha": "63a0a388e8544418a7c8f90fcb4a0b25eb9a734e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/analytics/main.cpp", "max_forks_repo_name": "cvetkovic/prs", "max_forks_repo_head_hexsha": "63a0a388e8544418a7c8f90fcb4a0b25eb9a734e", "max_forks_repo_licenses": ["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.65625, "max_line_length": 101, "alphanum_fraction": 0.4518879415, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5014692429772536}}
{"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/Adaptors/All.h\"\n#include \"Molassembler/Temple/Functional.h\"\n#include \"Molassembler/Temple/constexpr/Numeric.h\"\n\n// boost algorithm replacements\n#include <boost/algorithm/cxx11/all_of.hpp>\n#include <boost/range/adaptors.hpp>\n#include <boost/range/combine.hpp>\n#include <boost/range/numeric.hpp>\n#include <boost/range/algorithm/transform.hpp>\n\nusing namespace Scine::Molassembler;\n\nPURITY_STRONG double divByThree (unsigned a) {\n  return static_cast<double>(a) / 3.0;\n}\n\nBOOST_AUTO_TEST_CASE(SumTest, *boost::unit_test::label(\"Temple\")) {\n  std::vector<unsigned> instance {0, 1, 2, 3};\n  auto f = Temple::sum(instance);\n\n  BOOST_CHECK(f == 6);\n\n  BOOST_CHECK(\n    boost::accumulate(instance, 0) == 6\n  );\n\n  auto mapped = Temple::map(instance, divByThree);\n  BOOST_CHECK(mapped == std::vector<double>({0, 1.0/3.0, 2.0/3.0, 1}));\n\n  std::vector<double> bmapped;\n  boost::transform(instance, std::back_inserter(bmapped), divByThree);\n  BOOST_CHECK(mapped == bmapped);\n\n  auto pairwiseSum = Temple::map(\n    Temple::Adaptors::sequentialPairs(instance),\n    std::plus<>()\n  );\n\n  BOOST_CHECK(pairwiseSum == std::vector<unsigned>({1,3,5}));\n\n  std::vector<unsigned> bpairwiseSum;\n  boost::transform(\n    instance,\n    boost::adaptors::slice(instance, 1, instance.size() - 1),\n    std::back_inserter(bpairwiseSum),\n    std::plus<>()\n  );\n\n  auto pairwiseSmaller = Temple::accumulate(\n    Temple::map(\n      Temple::Adaptors::sequentialPairs(instance),\n      std::less<>()\n    ),\n    true,\n    std::logical_and<>()\n  );\n\n  auto bpairwiseSmaller = boost::algorithm::all_of(\n    boost::combine(\n      boost::adaptors::slice(instance, 0, instance.size() - 2),\n      boost::adaptors::slice(instance, 1, instance.size() - 1)\n    ),\n    [&](const auto& twoTuple) -> bool {\n      return Temple::invoke(std::less<>(), twoTuple);\n    }\n  );\n\n  static_assert(std::is_same<decltype(bpairwiseSmaller), bool>::value, \"Not a bool??\");\n  BOOST_CHECK(bpairwiseSmaller);\n\n  BOOST_CHECK(pairwiseSmaller);\n\n  std::vector<\n    std::vector<unsigned>\n  > vectorOfVectors {\n    {0, 1, 4},\n    {4, 5}\n  };\n\n  auto mapToSizes = Temple::map(\n    vectorOfVectors,\n    [](const std::vector<unsigned>& vectorUnsigned) -> unsigned {\n      return vectorUnsigned.size();\n    }\n  );\n\n  std::vector<unsigned> bsizes;\n  boost::transform(\n    vectorOfVectors,\n    std::back_inserter(bsizes),\n    [](const std::vector<unsigned>& vectorUnsigned) -> unsigned {\n      return vectorUnsigned.size();\n    }\n  );\n  BOOST_CHECK(bsizes == mapToSizes);\n\n  std::vector<unsigned> unsignedVector {1, 2, 3};\n\n  BOOST_CHECK(\n    Temple::sum(\n      Temple::map(\n        Temple::Adaptors::allPairs(unsignedVector),\n        [](const unsigned a, const unsigned b) -> unsigned {\n          return a + b;\n        }\n      )\n    ) == 12\n  );\n\n  BOOST_CHECK(\n    !Temple::all_of(\n      unsignedVector,\n      [](auto i) -> bool {\n        return i < 2;\n      }\n    )\n  );\n\n  std::vector<double> doubleVector {1.2, 1.5, 1.9};\n\n  BOOST_CHECK(\n    Temple::sum(\n      Temple::map(\n        Temple::Adaptors::allPairs(doubleVector),\n        [](const double a, const double b) -> double {\n          return a + b;\n        }\n      )\n    ) == 9.2\n  );\n}\n\nBOOST_AUTO_TEST_CASE(ReduceTests, *boost::unit_test::label(\"Temple\")) {\n  std::vector<unsigned> values {1, 2, 3, 4, 5};\n  BOOST_CHECK(\n    Temple::accumulate(\n      values,\n      0U,\n      std::plus<>()\n    ) == 15U\n  );\n  BOOST_CHECK(\n    Temple::accumulate(\n      values,\n      1U,\n      std::multiplies<>()\n    ) == 120U\n  );\n}\n\nBOOST_AUTO_TEST_CASE(MinMaxTests, *boost::unit_test::label(\"Temple\")) {\n  const std::vector<unsigned> values {1, 4, 6, 8};\n  BOOST_CHECK(Temple::max(values) == 8);\n  BOOST_CHECK(Temple::min(values) == 1);\n}\n\n\nBOOST_AUTO_TEST_CASE(MapToSameContainerTests, *boost::unit_test::label(\"Temple\")) {\n  std::set<int> f {5, -1, 9};\n\n  auto fMapped = Temple::map_stl(\n    f,\n    [](const int& x) -> double {\n      return x + 1.3;\n    }\n  );\n\n  static_assert(\n    std::is_same<decltype(fMapped), std::set<double>>::value,\n    \"Map to same container does not work as expected\"\n  );\n\n  std::vector<float> values {0, 3.4, 9};\n  auto xMapped = Temple::map(\n    values,\n    [](const float& x) -> unsigned long {\n      return static_cast<unsigned long>(x);\n    }\n  );\n\n  static_assert(\n    std::is_same<decltype(xMapped), std::vector<unsigned long>>::value,\n    \"Map to same container does not work as expected\"\n  );\n}\n", "meta": {"hexsha": "6a79ffd6f8c63f90db9d7db1a3794d860648c149", "size": 4664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Temple/Functional.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "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/Temple/Functional.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/Functional.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "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.9179487179, "max_line_length": 87, "alphanum_fraction": 0.6307890223, "num_tokens": 1319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5014692288968468}}
{"text": "#include \"2019/day14/cpp/include/formula.hpp\"\n\n#include <math.h>\n\n#include <boost/algorithm/string.hpp>\n#include <iostream>\n#include <regex>\n\n#include \"utils/cpp/include/utils.hpp\"\n\nFormula::Formula(std::string file_name) : m_formula() {\n  initialize_formula(file_name);\n}\n\nvoid Formula::initialize_formula(std::string file_name) {\n  auto form = utils::read_file(file_name);\n\n  // Regex to separeate left-hand and right-hand side with \"=>\"\n  std::regex rgx(\"([^=>]+)\");\n  for (auto &f : form) {\n    std::smatch sm;\n    std::vector<std::string> parts;\n    while (regex_search(f, sm, rgx)) {\n      std::string part = sm[0];\n      boost::algorithm::trim(part);\n      parts.push_back(part);\n      f = sm.suffix();\n    }\n\n    // Split the left-hand and right-hand sides into parts\n    std::vector<std::string> LHS, rhs;\n    utils::split_string(parts[0], \",\", LHS);\n    utils::split_string(parts[1], \" \", rhs);\n\n    // Go through the left hand side assign the formula dependency\n    for (auto &lhs : LHS) {\n      boost::algorithm::trim(lhs);\n      std::vector<std::string> t;\n      utils::split_string(lhs, \" \", t);\n      m_formula[t[1]].push_back(\n          std::make_tuple(std::stoi(t[0]), std::stoi(rhs[0]), rhs[1]));\n    }\n  }\n}\n\n// Figure out how much fuel is needed to generate a specific \"key\"\nint64_t Formula::compute(std::string key, int64_t amount) {\n  if (key == \"FUEL\") {\n    return amount;\n  }\n\n  int64_t s = 0;\n  for (auto &form : m_formula[key]) {\n    auto total = compute(std::get<2>(form), amount);\n    s += (std::ceil(total / double(std::get<1>(form))) * std::get<0>(form));\n  }\n  return s;\n}\n\n// Figure out how much fuel can be generated, given <ore>\nint64_t Formula::compute_fuel(int64_t ore) {\n  int64_t fuel_min(ore / compute(\"ORE\", 1)), fuel_max(ore);\n\n  while ((fuel_max - fuel_min) > 1) {\n    int64_t mid = (fuel_min + fuel_max) / int64_t(2);\n\n    if (compute(\"ORE\", mid) <= ore) {\n      fuel_min = mid;\n    } else {\n      fuel_max = mid;\n    }\n  }\n  return fuel_min;\n}", "meta": {"hexsha": "b84bf5a40979c67073db4eecc3d87825b9e5ee4a", "size": 1988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/day14/cpp/src/formula.cpp", "max_stars_repo_name": "ivobatkovic/advent-of-code", "max_stars_repo_head_hexsha": "e43489bcd2307f0f3ac8b0ec4e850f0a201f9944", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-14T16:24:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-06T16:40:13.000Z", "max_issues_repo_path": "2019/day14/cpp/src/formula.cpp", "max_issues_repo_name": "ivobatkovic/advent-of-code", "max_issues_repo_head_hexsha": "e43489bcd2307f0f3ac8b0ec4e850f0a201f9944", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-12-03T14:18:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-03T08:29:32.000Z", "max_forks_repo_path": "2019/day14/cpp/src/formula.cpp", "max_forks_repo_name": "ivobatkovic/advent-of-code", "max_forks_repo_head_hexsha": "e43489bcd2307f0f3ac8b0ec4e850f0a201f9944", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-06T07:25:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T12:42:37.000Z", "avg_line_length": 26.8648648649, "max_line_length": 76, "alphanum_fraction": 0.6192152918, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5014475031573573}}
{"text": "/*\n * ErrorEllipse.hpp\n *\n *  Created on: 01.08.2018\n *      Author: tomlucas\n */\n\n#ifndef OSG_VIZ_ERRORELLIPSE_HPP_\n#define OSG_VIZ_ERRORELLIPSE_HPP_\n\n#include <osg/AutoTransform>\n#include \"../Plugins/state_plugin_estimator.hpp\"\n#include \"../Estimators/Estimator.hpp\"\n#include <osg/PolygonMode>\n#include <Eigen/Eigenvalues>\n#include <math.h>\n\n#include <Eigen_Utils.hpp>\n\n#include <OSG_Utils.hpp>\n#include \"OSG_VIZ_Transform.hpp\"\nnamespace zavi\n::osg_viz {\n\t/**\n\t * This class is used to visualize the covariance of an estimator\n\t *\n\t * just use addErrorEllipse() to show the covariance of an estimator\n\t * @see addErrorEllipse\n\t */\n\tclass ErrorEllipse: public ::osg::PositionAttitudeTransform {\n\n\tpublic:\n\t\t/**\n\t\t * the basic radius of the sphere\n\t\t * @return the basic radius of the sphere\n\t\t */\n\t\tinline osg::Vec3d getBaseRadModifier() {\n\t\t\treturn base_rad;\n\t\t}\n\t\t/**\n\t\t * the sigma intervall\n\t\t * @return the sigma intervall\n\t\t */\n\t\tinline double getSigma() {\n\t\t\treturn sigma;\n\t\t}\n\tprivate:\n\t\tstd::shared_ptr<zavi::plugin::StatePluginEstimator> plugin;     //< shared pointer holding the ode part\n\t\tosg::Vec3d base_rad;//< basic radius of sphere\n\t\tdouble sigma;//sigma intervall\n\t\t/**\n\t\t * Callback to align osg object with ode object\n\t\t */\n\t\tclass estimatorCallback: public osg::NodeCallback {\n\t\tpublic:\n\t\t\tvoid operator()(osg::Node* node, osg::NodeVisitor* nv) {\n\t\t\t\tErrorEllipse *mt = dynamic_cast<ErrorEllipse*>(node);\n\t\t\t\tauto cov = mt->plugin->getPositionError();\n\t\t\t\t//zavi::printf(cov);\n\t\t\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3d> solv(cov);\n\t\t\t\tEigen::Quaterniond quat(solv.eigenvectors());\n\t\t\t\tmt->setAttitude(zavi::osg_viz::eigenToOSGQuat(quat));\n\t\t\t\tEigen::Vector3d scale = solv.eigenvalues().real().array().sqrt();\n\t\t\t\tmt->setScale(zavi::osg_viz::eigenToOSGVector(scale) * mt->getSigma() + mt->getBaseRadModifier());\n\t\t\t\tmt->setPivotPoint(osg::Vec3d(0, 0, 0));\n\t\t\t\tmt->setPosition(mt->plugin->getPositionOSG());\n\t\t\t}\n\t\t};\n\tpublic:\n\t\t/**\n\t\t * Creates a new Transform and adds it to root\n\t\t * @param node  the node which shall be transformed\n\t\t @param estimator estimator to read information\n\t\t * @param root  the group where to add the new transform\n\t\t * @param base_rad the basic radius of the ellipse osg::Vec3d(base_rad,base_rad,base_rad)\n\t\t * @param sigma the sigma intervall default 1\n\t\t */\n\t\tstatic void addErrorEllipse(std::shared_ptr<zavi::estimator::Estimator> estimator,\n\t\t\t\tosg::ref_ptr<osg::Group> root=zavi::osg_viz::root, double base_rad=1, double sigma = 1) {\n\t\t\tstd::shared_ptr<zavi::plugin::StatePluginEstimator> plugin(new zavi::plugin::StatePluginEstimator(estimator));\n\t\t\taddErrorEllipse(plugin,root,base_rad,sigma);\n\t\t}\n\t\t/**\n\t\t * Creates a new Transform and adds it to root\n\t\t * @param node  the node which shall be transformed\n\t\t * @param plugin The StatePlugin to read Information\n\t\t * @param root  the group where to add the new transform\n\t\t * @param base_rad the basic radius of the ellipse osg::Vec3d(base_rad,base_rad,base_rad)\n\t\t * @param sigma the sigma intervall default 1\n\t\t */\n\t\tstatic void addErrorEllipse(\n\t\t\t\tstd::shared_ptr<zavi::plugin::StatePluginEstimator> plugin,\n\t\t\t\tosg::ref_ptr<osg::Group> root=zavi::osg_viz::root, double base_rad=1,double sigma=1) {\n\t\t\tosg::ref_ptr<osg::ShapeDrawable> estimate_sphere(new osg::ShapeDrawable());\n\t\t\testimate_sphere->setShape(new osg::Sphere(osg::Vec3d(0,0,0),1));\n\t\t\tosg::PolygonMode* polymode = new osg::PolygonMode;\n\t\t\tpolymode->setMode(osg::PolygonMode::FRONT_AND_BACK,osg::PolygonMode::LINE);\n\t\t\testimate_sphere->getOrCreateStateSet()->setAttributeAndModes(polymode,osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);\n\t\t\tosg::ref_ptr<zavi::osg_viz::ErrorEllipse> transform(\n\t\t\t\t\tnew zavi::osg_viz::ErrorEllipse(plugin,base_rad,sigma));\n\t\t\ttransform->addChild(estimate_sphere);\n\t\t\t//zavi::osg_viz::OSG_VIZ_Transform::addTransformedNode(transform,plugin,root,false);\n\t\t\ttransform->setReferenceFrame(osg::Transform::ReferenceFrame::RELATIVE_RF);\n\t\t\troot->addChild(transform);\n\t\t}\n\n\t\t/**\n\t\t * Creates the transform object\n\t\t * @param plugin the Stateplugin to read pose information\n\t\t * * @param base_rad the basic radius of the ellipse\n\t\t */\n\t\tErrorEllipse(std::shared_ptr<zavi::plugin::StatePluginEstimator> plugin, double base_rad, double sigma) :\n\t\tplugin(plugin),base_rad(osg::Vec3d(base_rad,base_rad,base_rad)),sigma(sigma) {\n\t\t\tthis->setUpdateCallback(new estimatorCallback());\n\n\t\t}\n\t\t~ErrorEllipse()\n\t\t{\n\t\t}\n\t}\n\t;\n\n}\n//zavi::osg_viz\n\n#endif /* OSG_VIZ_ERRORELLIPSE_HPP_ */\n", "meta": {"hexsha": "62177ec6ef82349589939eb73d42e14619b869b0", "size": 4487, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SixdaysCode/OSG_VIZ/ErrorEllipse.hpp", "max_stars_repo_name": "TomLKoller/ZaVI_TrackCycling", "max_stars_repo_head_hexsha": "7c23bc34e6e58c78ec249f6f55d4e70c7e91d315", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-15T07:20:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T07:20:08.000Z", "max_issues_repo_path": "SixdaysCode/OSG_VIZ/ErrorEllipse.hpp", "max_issues_repo_name": "TomLKoller/ZaVI_TrackCycling", "max_issues_repo_head_hexsha": "7c23bc34e6e58c78ec249f6f55d4e70c7e91d315", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SixdaysCode/OSG_VIZ/ErrorEllipse.hpp", "max_forks_repo_name": "TomLKoller/ZaVI_TrackCycling", "max_forks_repo_head_hexsha": "7c23bc34e6e58c78ec249f6f55d4e70c7e91d315", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-15T07:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T07:20:19.000Z", "avg_line_length": 35.3307086614, "max_line_length": 128, "alphanum_fraction": 0.7191887676, "num_tokens": 1278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.501447498240191}}
{"text": "#include \"cryptonote_config.h\"\n#include \"common/italo.h\"\n#include \"epee/int-util.h\"\n#include <boost/endian/conversion.hpp>\n#include <limits>\n#include <vector>\n#include <boost/lexical_cast.hpp>\n#include <cfenv>\n\n#include \"service_node_rules.h\"\n\nnamespace service_nodes {\n\n// TODO(italo): Move to italo_economy, this will also need access to italo::exp2\nuint64_t get_staking_requirement(cryptonote::network_type m_nettype, uint64_t height, uint8_t hf_version)\n{\n  if (m_nettype == cryptonote::TESTNET || m_nettype == cryptonote::FAKECHAIN)\n      return COIN * 100;\n\n  // For devnet we use the 10% of mainnet requirement at height (650k + H) so that we follow\n  // (proportionally) whatever staking changes happen on mainnet.  (The 650k is because devnet\n  // launched at ~600k mainnet height, so this puts it a little ahead).\n  if (m_nettype == cryptonote::DEVNET)\n      return get_staking_requirement(cryptonote::MAINNET, 600000 + height, hf_version) / 10;\n\n  if (hf_version >= cryptonote::network_version_16_pulse)\n    return 15000'000000000;\n\n  if (hf_version >= cryptonote::network_version_13_enforce_checkpoints)\n  {\n    constexpr int64_t heights[] = {\n        385824,\n        429024,\n        472224,\n        515424,\n        558624,\n        601824,\n        645024,\n    };\n\n    constexpr int64_t lsr[] = {\n        20458'380815527,\n        19332'319724305,\n        18438'564443912,\n        17729'190407764,\n        17166'159862153,\n        16719'282221956,\n        16364'595203882,\n    };\n\n    assert(static_cast<int64_t>(height) >= heights[0]);\n    constexpr uint64_t LAST_HEIGHT      = heights[italo::array_count(heights) - 1];\n    constexpr uint64_t LAST_REQUIREMENT = lsr    [italo::array_count(lsr) - 1];\n    if (height >= LAST_HEIGHT)\n        return LAST_REQUIREMENT;\n\n    size_t i = 0;\n    for (size_t index = 1; index < italo::array_count(heights); index++)\n    {\n      if (heights[index] > static_cast<int64_t>(height))\n      {\n        i = (index - 1);\n        break;\n      }\n    }\n\n    int64_t H      = height;\n    int64_t result = lsr[i] + (H - heights[i]) * ((lsr[i + 1] - lsr[i]) / (heights[i + 1] - heights[i]));\n    return static_cast<uint64_t>(result);\n  }\n\n  uint64_t hardfork_height = 101250;\n  if (height < hardfork_height) height = hardfork_height;\n\n  uint64_t height_adjusted = height - hardfork_height;\n  uint64_t base = 0, variable = 0;\n  std::fesetround(FE_TONEAREST);\n  if (hf_version >= cryptonote::network_version_11_infinite_staking)\n  {\n    base     = 15000 * COIN;\n    variable = (25007.0 * COIN) / italo::exp2(height_adjusted/129600.0);\n  }\n  else\n  {\n    base      = 10000 * COIN;\n    variable  = (35000.0 * COIN) / italo::exp2(height_adjusted/129600.0);\n  }\n\n  uint64_t result = base + variable;\n  return result;\n}\n\nuint64_t portions_to_amount(uint64_t portions, uint64_t staking_requirement)\n{\n  uint64_t hi, lo, resulthi, resultlo;\n  lo = mul128(staking_requirement, portions, &hi);\n  div128_64(hi, lo, STAKING_PORTIONS, &resulthi, &resultlo);\n  return resultlo;\n}\n\nbool check_service_node_portions(uint8_t hf_version, const std::vector<uint64_t>& portions)\n{\n  if (portions.size() > MAX_NUMBER_OF_CONTRIBUTORS) return false;\n\n  uint64_t reserved = 0;\n  for (auto i = 0u; i < portions.size(); ++i)\n  {\n    const uint64_t min_portions = get_min_node_contribution(hf_version, STAKING_PORTIONS, reserved, i);\n    if (portions[i] < min_portions) return false;\n    reserved += portions[i];\n  }\n\n  return reserved <= STAKING_PORTIONS;\n}\n\ncrypto::hash generate_request_stake_unlock_hash(uint32_t nonce)\n{\n  static_assert(sizeof(crypto::hash) == 8 * sizeof(uint32_t) && alignof(crypto::hash) >= alignof(uint32_t));\n  crypto::hash result;\n  boost::endian::native_to_little_inplace(nonce);\n  for (size_t i = 0; i < 8; i++)\n    reinterpret_cast<uint32_t*>(result.data)[i] = nonce;\n  return result;\n}\n\nuint64_t get_locked_key_image_unlock_height(cryptonote::network_type nettype, uint64_t node_register_height, uint64_t curr_height)\n{\n  uint64_t blocks_to_lock = staking_num_lock_blocks(nettype);\n  uint64_t result         = curr_height + (blocks_to_lock / 2);\n  return result;\n}\n\nstatic uint64_t get_min_node_contribution_pre_v11(uint64_t staking_requirement, uint64_t total_reserved)\n{\n  return std::min(staking_requirement - total_reserved, staking_requirement / MAX_NUMBER_OF_CONTRIBUTORS);\n}\n\nuint64_t get_max_node_contribution(uint8_t version, uint64_t staking_requirement, uint64_t total_reserved)\n{\n  if (version >= cryptonote::network_version_16_pulse)\n    return (staking_requirement - total_reserved) * config::MAXIMUM_ACCEPTABLE_STAKE::num\n      / config::MAXIMUM_ACCEPTABLE_STAKE::den;\n  return std::numeric_limits<uint64_t>::max();\n}\n\nuint64_t get_min_node_contribution(uint8_t version, uint64_t staking_requirement, uint64_t total_reserved, size_t num_contributions)\n{\n  if (version < cryptonote::network_version_11_infinite_staking)\n    return get_min_node_contribution_pre_v11(staking_requirement, total_reserved);\n\n  const uint64_t needed = staking_requirement - total_reserved;\n  assert(MAX_NUMBER_OF_CONTRIBUTORS > num_contributions);\n  if (MAX_NUMBER_OF_CONTRIBUTORS <= num_contributions) return UINT64_MAX;\n\n  const size_t num_contributions_remaining_avail = MAX_NUMBER_OF_CONTRIBUTORS - num_contributions;\n  return needed / num_contributions_remaining_avail;\n}\n\nuint64_t get_min_node_contribution_in_portions(uint8_t version, uint64_t staking_requirement, uint64_t total_reserved, size_t num_contributions)\n{\n  uint64_t atomic_amount = get_min_node_contribution(version, staking_requirement, total_reserved, num_contributions);\n  uint64_t result        = (atomic_amount == UINT64_MAX) ? UINT64_MAX : (get_portions_to_make_amount(staking_requirement, atomic_amount));\n  return result;\n}\n\nuint64_t get_portions_to_make_amount(uint64_t staking_requirement, uint64_t amount, uint64_t max_portions)\n{\n  uint64_t lo, hi, resulthi, resultlo;\n  lo = mul128(amount, max_portions, &hi);\n  if (lo > UINT64_MAX - (staking_requirement - 1))\n    hi++;\n  lo += staking_requirement-1;\n  div128_64(hi, lo, staking_requirement, &resulthi, &resultlo);\n  return resultlo;\n}\n\nstatic bool get_portions_from_percent(double cur_percent, uint64_t& portions) {\n  if(cur_percent < 0.0 || cur_percent > 100.0) return false;\n\n  // Fix for truncation issue when operator cut = 100 for a pool Service Node.\n  if (cur_percent == 100.0)\n  {\n    portions = STAKING_PORTIONS;\n  }\n  else\n  {\n    portions = (cur_percent / 100.0) * (double)STAKING_PORTIONS;\n  }\n\n  return true;\n}\n\nbool get_portions_from_percent_str(std::string cut_str, uint64_t& portions) {\n\n  if(!cut_str.empty() && cut_str.back() == '%')\n  {\n    cut_str.pop_back();\n  }\n\n  double cut_percent;\n  try\n  {\n    cut_percent = boost::lexical_cast<double>(cut_str);\n  }\n  catch(...)\n  {\n    return false;\n  }\n\n  return get_portions_from_percent(cut_percent, portions);\n}\n\n} // namespace service_nodes\n", "meta": {"hexsha": "81f07579948d98c444b6fdc2b8f06d292e89963f", "size": 6874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cryptonote_core/service_node_rules.cpp", "max_stars_repo_name": "italocoin-project/italo", "max_stars_repo_head_hexsha": "5e0df560e11732d68a34fb2216d6c6d4322b2f65", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-10-21T02:30:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T06:56:55.000Z", "max_issues_repo_path": "src/cryptonote_core/service_node_rules.cpp", "max_issues_repo_name": "ilie1988/italo", "max_issues_repo_head_hexsha": "cff77cbf2428ad2527e4d7070374ff6165ba6ef7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-10-22T14:34:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-28T12:02:39.000Z", "max_forks_repo_path": "src/cryptonote_core/service_node_rules.cpp", "max_forks_repo_name": "italocoin-project/italo", "max_forks_repo_head_hexsha": "5e0df560e11732d68a34fb2216d6c6d4322b2f65", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-09-22T04:20:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-28T15:27:39.000Z", "avg_line_length": 32.1214953271, "max_line_length": 144, "alphanum_fraction": 0.7219959267, "num_tokens": 1966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5014474933230243}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2008 Jose Aparicio\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 <ql/quantlib.hpp>\n\n#include <boost/timer.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\nusing namespace QuantLib;\n\n#ifdef BOOST_MSVC\n#  ifdef QL_ENABLE_THREAD_SAFE_OBSERVER_PATTERN\n#    include <ql/auto_link.hpp>\n#    define BOOST_LIB_NAME boost_system\n#    include <boost/config/auto_link.hpp>\n#    undef BOOST_LIB_NAME\n#    define BOOST_LIB_NAME boost_thread\n#    include <boost/config/auto_link.hpp>\n#    undef BOOST_LIB_NAME\n#  endif\n#endif\n\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib {\n\n    Integer sessionId() { return 0; }\n\n}\n#endif\n\nint main(int, char* []) {\n\n    try {\n\n        boost::timer timer;\n        std::cout << std::endl;\n\n        /*********************\n         ***  MARKET DATA  ***\n         *********************/\n\n        Calendar calendar = TARGET();\n        Date todaysDate(15, May, 2007);\n        // must be a business day\n        todaysDate = calendar.adjust(todaysDate);\n\n        Settings::instance().evaluationDate() = todaysDate;\n\n        // dummy curve\n        boost::shared_ptr<Quote> flatRate(new SimpleQuote(0.01));\n        Handle<YieldTermStructure> tsCurve(\n              boost::shared_ptr<FlatForward>(\n                      new FlatForward(todaysDate, Handle<Quote>(flatRate),\n                                      Actual365Fixed())));\n\n        /*\n          In Lehmans Brothers \"guide to exotic credit derivatives\"\n          p. 32 there's a simple case, zero flat curve with a flat CDS\n          curve with constant market spreads of 150 bp and RR = 50%\n          corresponds to a flat 3% hazard rate. The implied 1-year\n          survival probability is 97.04% and the 2-years is 94.18%\n        */\n\n        // market\n        Real recovery_rate = 0.5;\n        Real quoted_spreads[] = { 0.0150, 0.0150, 0.0150, 0.0150 };\n        vector<Period> tenors;\n        tenors.push_back(3*Months);\n        tenors.push_back(6*Months);\n        tenors.push_back(1*Years);\n        tenors.push_back(2*Years);\n        vector<Date> maturities;\n        for (Size i=0; i<4; i++) {\n            maturities.push_back(calendar.adjust(todaysDate + tenors[i],\n                                                 Following));\n        }\n\n        std::vector<boost::shared_ptr<DefaultProbabilityHelper> > instruments;\n        for (Size i=0; i<4; i++) {\n            instruments.push_back(boost::shared_ptr<DefaultProbabilityHelper>(\n                new SpreadCdsHelper(\n                              Handle<Quote>(boost::shared_ptr<Quote>(\n                                         new SimpleQuote(quoted_spreads[i]))),\n                              tenors[i],\n                              0,\n                              calendar,\n                              Quarterly,\n                              Following,\n                              DateGeneration::TwentiethIMM,\n                              Actual365Fixed(),\n                              recovery_rate,\n                              tsCurve)));\n        }\n\n        // Bootstrap hazard rates\n        boost::shared_ptr<PiecewiseDefaultCurve<HazardRate, BackwardFlat> >\n           hazardRateStructure(\n               new PiecewiseDefaultCurve<HazardRate, BackwardFlat>(\n                                                           todaysDate,\n                                                           instruments,\n                                                           Actual365Fixed()));\n        vector<pair<Date, Real> > hr_curve_data = hazardRateStructure->nodes();\n\n        cout << \"Calibrated hazard rate values: \" << endl ;\n        for (Size i=0; i<hr_curve_data.size(); i++) {\n            cout << \"hazard rate on \" << hr_curve_data[i].first << \" is \"\n                 << hr_curve_data[i].second << endl;\n        }\n        cout << endl;\n\n        cout << \"Some survival probability values: \" << endl ;\n        cout << \"1Y survival probability: \"\n             << io::percent(hazardRateStructure->survivalProbability(\n                                                        todaysDate + 1*Years))\n             << endl\n             << \"               expected: \"\n             << io::percent(0.9704)\n             << endl;\n        cout << \"2Y survival probability: \"\n             << io::percent(hazardRateStructure->survivalProbability(\n                                                        todaysDate + 2*Years))\n             << endl\n             << \"               expected: \"\n             << io::percent(0.9418)\n             << endl;\n\n        cout << endl << endl;\n\n        // reprice instruments\n        Real nominal = 1000000.0;\n        Handle<DefaultProbabilityTermStructure> probability(hazardRateStructure);\n        boost::shared_ptr<PricingEngine> engine(\n                  new MidPointCdsEngine(probability, recovery_rate, tsCurve));\n\n        Schedule cdsSchedule =\n            MakeSchedule().from(todaysDate).to(maturities[0])\n                          .withFrequency(Quarterly)\n                          .withCalendar(calendar)\n                          .withTerminationDateConvention(Unadjusted)\n                          .withRule(DateGeneration::TwentiethIMM);\n        CreditDefaultSwap cds_3m(Protection::Seller,\n                                 nominal,\n                                 quoted_spreads[0],\n                                 cdsSchedule,\n                                 Following,\n                                 Actual365Fixed());\n\n        cdsSchedule =\n            MakeSchedule().from(todaysDate).to(maturities[1])\n                          .withFrequency(Quarterly)\n                          .withCalendar(calendar)\n                          .withTerminationDateConvention(Unadjusted)\n                          .withRule(DateGeneration::TwentiethIMM);\n        CreditDefaultSwap cds_6m(Protection::Seller,\n                                 nominal,\n                                 quoted_spreads[1],\n                                 cdsSchedule,\n                                 Following,\n                                 Actual365Fixed());\n\n        cdsSchedule =\n            MakeSchedule().from(todaysDate).to(maturities[2])\n                          .withFrequency(Quarterly)\n                          .withCalendar(calendar)\n                          .withTerminationDateConvention(Unadjusted)\n                          .withRule(DateGeneration::TwentiethIMM);\n        CreditDefaultSwap cds_1y(Protection::Seller,\n                                 nominal,\n                                 quoted_spreads[2],\n                                 cdsSchedule,\n                                 Following,\n                                 Actual365Fixed());\n\n        cdsSchedule =\n            MakeSchedule().from(todaysDate).to(maturities[3])\n                          .withFrequency(Quarterly)\n                          .withCalendar(calendar)\n                          .withTerminationDateConvention(Unadjusted)\n                          .withRule(DateGeneration::TwentiethIMM);\n        CreditDefaultSwap cds_2y(Protection::Seller,\n                                 nominal,\n                                 quoted_spreads[3],\n                                 cdsSchedule,\n                                 Following,\n                                 Actual365Fixed());\n\n        cds_3m.setPricingEngine(engine);\n        cds_6m.setPricingEngine(engine);\n        cds_1y.setPricingEngine(engine);\n        cds_2y.setPricingEngine(engine);\n\n        cout << \"Repricing of quoted CDSs employed for calibration: \" << endl;\n        cout << \"3M fair spread: \" << io::rate(cds_3m.fairSpread()) << endl\n             << \"   NPV:         \" << cds_3m.NPV() << endl\n             << \"   default leg: \" << cds_3m.defaultLegNPV() << endl\n             << \"   coupon leg:  \" << cds_3m.couponLegNPV() << endl\n             << endl;\n\n        cout << \"6M fair spread: \" << io::rate(cds_6m.fairSpread()) << endl\n             << \"   NPV:         \" << cds_6m.NPV() << endl\n             << \"   default leg: \" << cds_6m.defaultLegNPV() << endl\n             << \"   coupon leg:  \" << cds_6m.couponLegNPV() << endl\n             << endl;\n\n        cout << \"1Y fair spread: \" << io::rate(cds_1y.fairSpread()) << endl\n             << \"   NPV:         \" << cds_1y.NPV() << endl\n             << \"   default leg: \" << cds_1y.defaultLegNPV() << endl\n             << \"   coupon leg:  \" << cds_1y.couponLegNPV() << endl\n             << endl;\n\n        cout << \"2Y fair spread: \" << io::rate(cds_2y.fairSpread()) << endl\n             << \"   NPV:         \" << cds_2y.NPV() << endl\n             << \"   default leg: \" << cds_2y.defaultLegNPV() << endl\n             << \"   coupon leg:  \" << cds_2y.couponLegNPV() << endl\n             << endl;\n\n        cout << endl << endl;\n\n        Real seconds  = timer.elapsed();\n        Integer hours = Integer(seconds/3600);\n        seconds -= hours * 3600;\n        Integer minutes = Integer(seconds/60);\n        seconds -= minutes * 60;\n        cout << \"Run completed in \";\n        if (hours > 0)\n            cout << hours << \" h \";\n        if (hours > 0 || minutes > 0)\n            cout << minutes << \" m \";\n        cout << fixed << setprecision(0)\n             << seconds << \" s\" << endl;\n\n        return 0;\n    } catch (exception& e) {\n        cerr << e.what() << endl;\n        return 1;\n    } catch (...) {\n        cerr << \"unknown error\" << endl;\n        return 1;\n    }\n}\n\n", "meta": {"hexsha": "05be5980dffdea191152133e48f1bd1586eb8c01", "size": 10106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/CDS/CDS.cpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "Examples/CDS/CDS.cpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/CDS/CDS.cpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 38.7203065134, "max_line_length": 81, "alphanum_fraction": 0.4977241243, "num_tokens": 2147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5014474884058575}}
{"text": "//\n//  IntervalBounder.h\n//  YRoots\n//\n//  Created by Erik Hales Parkinson on 8/14/21.\n//  Copyright \u00a9 2021 Erik Hales Parkinson. All rights reserved.\n//\n\n#ifndef IntervalBounder_h\n#define IntervalBounder_h\n\n#include \"Approximation/ChebyshevApproximation.hpp\"\n#include \"Utilities/Timer.hpp\"\n#include \"Utilities/utilities.hpp\"\n#include <Eigen/Dense>\n\n#include \"IntervalChecking/BoundingIntervalUtilities.hpp\"\n\ntemplate <int Rank>\nclass IntervalBounder {\npublic:\n    IntervalBounder(size_t _rank);\n    double computeBoundingInterval(std::vector<ChebyshevApproximation<Rank> >& _chebyshevApproximations, const std::vector<bool>& _allowedToReduceDim);\n\n    const Interval& getBoundingInterval() {\n        return m_boundingInterval;\n    }\n    \nprotected:\n    double updateBoundingIntervalLinearErrorSolve(std::vector<ChebyshevApproximation<Rank> >& _chebyshevApproximations, const std::vector<bool>& _allowedToReduceDim);\n    double updateBoundingIntervalLipshitzSolve(std::vector<ChebyshevApproximation<Rank> >& _chebyshevApproximations, const std::vector<bool>& _allowedToReduceDim);\n\n    void preconditionPolynomials(std::vector<ChebyshevApproximation<Rank> >& _chebyshevApproximations);\n    \n    double computeLipshitzConstant(const Eigen::VectorXd& poly, size_t dim);\n    void chebValReduce(const Eigen::VectorXd& poly, Eigen::VectorXd& result, size_t dim, double value);\n    double getLiphsitzBoundIncreaseND(const Eigen::VectorXd& poly, double error, double lipshitzConstant, const Interval& boundingInterval, size_t dim);\n    double getExtremeAbsVal(const Eigen::VectorXd& poly, const Interval& boundingInterval, size_t dim);\nprotected:\n    size_t                  m_rank;\n    Interval                m_boundingInterval;\n            \n    //For Bounding Intervals\n    typename EigenTypes<Rank>::Matrix m_linearTerms;\n    typename EigenTypes<Rank>::Vector m_constantTerms;\n    typename EigenTypes<Rank>::Vector m_errorTerms;\n    typename EigenTypes<Rank>::Vector m_errorTermsOfLinear;\n    typename EigenTypes<Rank>::MatrixPowerColumns m_rightHandSideOfLinearSystemErrors;\n    typename Eigen::ColPivHouseholderQR<typename EigenTypes<Rank>::Matrix> m_linearTermsQR;\n    typename EigenTypes<Rank>::MatrixPowerColumns m_linearSystemWithErrorResult;\n    typename EigenTypes<Rank>::Matrix m_linearTermsInverse;\n\n    //The Preconditioned Polynomials\n    size_t m_preconditionPolysDegree;\n    typename EigenTypes<Rank>::Vector m_preconditionedErrors;\n    Eigen::MatrixXd     m_preconditionedPolys;\n    \n    //For Timing\n    static size_t           m_timerLinearErrorSolveIndex;\n    static size_t           m_timerPreconditionPolysIndex;\n    static size_t           m_timerLipshitzSolveIndex;\n    static size_t           m_timerChebValReduceIndex;\n    Timer&                  m_timer = Timer::getInstance();\n};\n\ntemplate<int Rank>\nsize_t IntervalBounder<Rank>::m_timerLinearErrorSolveIndex = -1;\ntemplate<int Rank>\nsize_t IntervalBounder<Rank>::m_timerPreconditionPolysIndex = -1;\ntemplate<int Rank>\nsize_t IntervalBounder<Rank>::m_timerLipshitzSolveIndex = -1;\ntemplate<int Rank>\nsize_t IntervalBounder<Rank>::m_timerChebValReduceIndex = -1;\n\n#include \"IntervalBounder1D.ipp\"\n#include \"IntervalBounderND.ipp\"\n\n#endif /* IntervalBounder_h */\n", "meta": {"hexsha": "30100b2ff29e8421019198f269b973c5709028dd", "size": 3234, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "YRoots/include/IntervalChecking/IntervalBounder.hpp", "max_stars_repo_name": "erikhparkinson/YRoots", "max_stars_repo_head_hexsha": "7907a7245ac37b38a06bc5cc94ad26c7cf5e5905", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "YRoots/include/IntervalChecking/IntervalBounder.hpp", "max_issues_repo_name": "erikhparkinson/YRoots", "max_issues_repo_head_hexsha": "7907a7245ac37b38a06bc5cc94ad26c7cf5e5905", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "YRoots/include/IntervalChecking/IntervalBounder.hpp", "max_forks_repo_name": "erikhparkinson/YRoots", "max_forks_repo_head_hexsha": "7907a7245ac37b38a06bc5cc94ad26c7cf5e5905", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9367088608, "max_line_length": 166, "alphanum_fraction": 0.7631416203, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893520001, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5014396036225462}}
{"text": "#ifndef POUF_VEC_HPP\n#define POUF_VEC_HPP\n\n#include <Eigen/Core>\n\n#include \"real.hpp\"\n\ntemplate<int N = Eigen::Dynamic, class U = real>\nusing vector = Eigen::Matrix<U, N, 1>;\n\nusing vec1 = vector<1>;\nusing vec2 = vector<2>;\nusing vec3 = vector<3>;\nusing vec4 = vector<4>;\nusing vec6 = vector<6>;\nusing vec = vector<>;\n\n\ntemplate<int N, class U>\nstruct traits< vector<N, U> > {\n\n  using scalar_type = scalar<U>;\n  using deriv_type = vector<N, deriv<U> >;\n  \n  static const std::size_t dim = N * traits<U>::dim;\n\n  static scalar_type dot(const vector<N, U>& x,\n                         const vector<N, U>& y) {\n    return x.dot(y);\n  }\n\n  static scalar_type& coord(std::size_t i, vector<N, U>& v) {\n\t// TODO assert this is safe\n    return reinterpret_cast<scalar_type*>(v.data())[i];\n  }\n\n  static const scalar_type& coord(std::size_t i, const vector<N, U>& v) {\n\t// TODO assert this is safe\n    return reinterpret_cast<const scalar_type*>(v.data())[i];\n  }\n\n  static vector<N, U> zero() {\n\treturn vector<N, U>::Constant(traits<U>::zero());\n  }\n\n\n  // additive lie group structure\n  // TODO multiplicative as well?\n  using group_type = vector<N, U>;\n  \n  static group_type id() { return zero(); }\n  static group_type inv(const group_type& x) { return -x; }\n  static group_type prod(const group_type& x, const group_type& y) { return x + y; }\n\n  static group_type exp(const deriv_type& x) { return x; }\n  \n  static const char* name() {\n    static std::string value = \"vec\" + ((N > 0) ? std::to_string(N) : std::string());\n    return value.c_str();\n  }\n\n\n  static deriv_type AdT(const group_type&, const deriv_type& x) { return x; }\n  static deriv_type Ad(const group_type&, const deriv_type& x) { return x; }  \n  \n};\n\n\n\n#endif\n", "meta": {"hexsha": "dc4794415d4fc63bdd8cc81bbd886293f97328b4", "size": 1724, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pouf/core/vec.hpp", "max_stars_repo_name": "maxime-tournier/cpp", "max_stars_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pouf/core/vec.hpp", "max_issues_repo_name": "maxime-tournier/cpp", "max_issues_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pouf/core/vec.hpp", "max_forks_repo_name": "maxime-tournier/cpp", "max_forks_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_forks_repo_licenses": ["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.2816901408, "max_line_length": 85, "alphanum_fraction": 0.6444315545, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5014396036225461}}
{"text": "/*\nProgram to translate text to DNA and vice versa\n*/\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <boost/random/mersenne_twister.hpp>\n//#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/program_options.hpp>\n#include \"../include/PFE.hpp\"\n#include \"../include/EFE.hpp\"\n#include \"../include/DFT.hpp\"\n#include \"../include/helpers.hpp\"\n#include \"../include/encodedecode.hpp\"\n#include \"../include/ReedSolomon.hpp\"\n#include <string>\n#include <fstream>\n#include <streambuf>\n\n\nusing namespace std;\n\n\n\n// define static variables \n\ntypedef int el_t;\ntemplate<> int PFE<el_t>::prime = 47;\ntemplate<> boost::bimap<el_t,el_t> PFE<el_t>::exp_el = boost::bimap<el_t,el_t>();\n\ntypedef PFE<el_t> pfe;\n\ntemplate<> polynomial<pfe> EFE<pfe>::prim_poly = polynomial<pfe>();\ntemplate<> unsigned EFE<pfe>::m = 30;\n\n template<class cf_t> \n    ostream &operator<<(ostream &stream, const vector<cf_t>& x) \n    { \n\tfor(unsigned i = 0; i<x.size(); ++i) stream << x[i] << \"  \";\n\treturn stream; // must return stream \n    }; \n\n\n\nnamespace po = boost::program_options;\n\nint main(int ac, char* av[])\n{\n\n// command line options\n\nint numblocks;\nstring infile;\nstring outfile;\n\nint opt;\npo::options_description desc(\"Allowed options\");\ndesc.add_options()\n    (\"help\", \"produce help message\")\n    (\"encode\", \"encode\")\n    (\"decode\", \"decode\")\n    (\"disturb\", \"draw uniformly at random from the input lines, add errors to each line\")\n\t(\"input\",po::value<string>(&infile)->default_value(\"\"),\"inputfile\")\t\n\t(\"output\",po::value<string>(&outfile)->default_value(\"\"),\"outputfile\")\t\n\t(\"numblocks\",po::value<int>(&numblocks)->default_value(0),\"numblocks\")\t\n;\n\npo::variables_map vm;\npo::store(po::parse_command_line(ac, av, desc), vm);\npo::notify(vm);    \n\nif (vm.count(\"help\")) {\n    cout << desc << \"\\n\";\n    return 1;\n}\n\n\n\n\nconst unsigned l = 3;\nconst unsigned m = 30; // EFE<pfe>::m; // GF(p^m)\nDNAmap<pfe> dnamap;\n\n// initialize the inner code\t\npfe::initialize_exp_el(33);\ntypedef EFE<pfe> efe;\n\nconst unsigned M = 50000;\nconst int prime = PFE<el_t>::prime;\n\nconst unsigned N = 39;\nconst unsigned N_u = 46; // the underlying length of the shortened inner code\nconst unsigned K = 33;\n\n\n// primitive element of the inner code \nconst pfe A = pfe(33);\ntypedef DFT_PRIM<pfe> dftpfe;\ndftpfe dftpfe_d(N,A);\n\nRScode<pfe,dftpfe> innercode(N,K,A,dftpfe_d,N_u);\n\n\n// initialize the outer code\nconst unsigned n = 713; // DFT length, divides 47^33-1\nconst unsigned P = 23;\nconst unsigned Q = 31; // P*Q = n\nconst unsigned k = 594;//\t\n\nEFE<pfe>::m = m;\n\n// initialize the primitive polynomial\npfe ppvv[m+1] = {1,13,15,22,45,  19,34,10,17,5,41,21,  12,3,23,17,27,8,  34,32,7,40,41,1,  32,26,24,32,37,5,1}; // for m=30\t\nvector<pfe> ppv(ppvv, ppvv+m+1);\nEFE<pfe>::prim_poly = polynomial<pfe>(ppv);\n// initialize the element of order n, the Fourier kernel  \npfe aa[m] = {26,35,41,0,24,3,31,8,12,10,9,24,44,11,24,9,43,14,26,32,7,13,15,29,25,38,8,24,40,32}; // element of order 713\nvector<pfe> avv(aa, aa+m); // \nefe a = efe(avv); // this is an element of order n\n\ntypedef DFT_FFT<efe> dftefe;\ndftefe dftefe_d(n,a,P,Q); // Fourier transform for the outer code \n\nRScode<efe,dftefe> outercode(n,k,a,dftefe_d);\n\n// encoder/decoder \nEnDecode<RScode<pfe,dftpfe>, RScode<efe,dftefe>, DNAmap<pfe> > endecode(innercode,outercode,dnamap,l);\n\n\n\n/////////////////////// encode \nif (vm.count(\"encode\")) {\n\t\n\tcout << \"start encoding..\" << endl;\n\n\tif(infile == \"\" || outfile ==\"\"){\n\t\tcout << \"in/outfile not specified \" << endl; \n\t\treturn 0;\n\t}\n\tcout << \"infile:  \" << infile << endl;\n\tcout << \"outfile: \" << outfile << endl;\n\n\n\t// read data\n\tstd::ifstream t(infile.c_str());\n\tstd::string str((std::istreambuf_iterator<char>(t)),std::istreambuf_iterator<char>());\n\n\t// encode\n\tvector<string> urn(n*numblocks);\n\tendecode.encode(str, urn);\n\tnumblocks = endecode.numblocks; \n\t\n\tcout << \"encoded \" << str.size() << \" Bytes to \" << numblocks << \" blocks, resulting in \"\n\t<< n*numblocks << \" DNA segments of length \" << N << \" each.\" << endl;\n    \n\tofstream out;\n\tout.open(outfile.c_str());\n\tfor(unsigned i=0;i<urn.size();++i) out << urn[i] << endl;\n\tout.close();\n\treturn 0;\n}\n\n/////////////////////// decode \nif (vm.count(\"decode\")) {\n\t//cout << \"generate DFT lookup table\"<< endl; \n\ttypedef DFT_FFT<efe> dftefe;\n\tdftefe dftefe_d(n,a,P,Q); // Fourier transform for the outer code \n\t\n\tif(infile == \"\" || outfile ==\"\" || numblocks==0 ) {\n\t\tcout << \"in/outfile/numblocks not specified \" << endl; \n\t\treturn 0;\n\t}\n\tcout << \"infile:  \" << infile << endl;\n\tcout << \"outfile: \" << outfile << endl;\n\tcout << \"numblocks: \"<<numblocks << endl; \n\n\tvector<string> drawnseg;\n\n\t\n\tstring sLine = \"\";\n\tifstream in;\n\tin.open(infile.c_str());\n\twhile (!in.eof()){\n\t\tgetline(in, sLine);\n\t\tdrawnseg.push_back(sLine);\n\t}\n\tdrawnseg.resize(drawnseg.size()-1); // erase the last, empty line\n\n\tstring recstr;\n\tcout << \"start decode..\" << endl;\t\n\tendecode.numblocks = numblocks;\n\tendecode.decode(recstr, drawnseg);\n\t\n\tofstream out;\n\tout.open(outfile.c_str());\n\tout << recstr;\n\tout.close();\n\t\n}\n////////////////////////// disturb\nif (vm.count(\"disturb\")) {\n\t\n\tif(infile == \"\" || outfile ==\"\") {\n\t\tcout << \"in/outfile not specified \" << endl; \n\t\treturn 0;\n\t}\n\tcout << \"infile:  \" << infile << endl;\n\tcout << \"outfile: \" << outfile << endl;\n\t\n\tvector<string> urn;\n\t\n\t\n\tstring sLine = \"\";\n\tifstream in;\n\tin.open(infile.c_str());\n\twhile (!in.eof()){\n\t\tgetline(in, sLine);\n\t\turn.push_back(sLine);\n\t}\n\turn.resize(urn.size()-1); // erase the last, empty line\n\t\n\tboost::mt19937 rng; \t\n\tboost::uniform_int<> unif(0,urn.size()-1); // distribution that maps to 0,..,urn.size()-1\n\tboost::uniform_int<> unif_N(0,N-1); // distribution that maps to 0,..,N-1\n\tboost::uniform_int<> unif_4(0,4-1); // distribution that maps to 0,..,N-1\n\tboost::bernoulli_distribution<> bern(0.013);\n\tboost::bernoulli_distribution<> faircoin(0.5);\n\t\n\tchar nucl[] = \"ACGT\";\n\n\tvector<string> drawnseg(M);\n\t\n\t//write data\n\tofstream out;\n\tout.open(outfile.c_str());\n\t\n\t// draw M times\n\tstring tmpstr;\n\tfor(unsigned i=0;i<M;++i){\n\t\tunsigned randind = unif(rng);\n\t\ttmpstr = urn[randind];\n\t\t\n\t\t// introduce errors\n\t\t\n\t\tfor(unsigned j=0;j<2;++j){\n\t\t\ttmpstr[unif_N(rng)] = nucl[unif_4(rng)];\n\t\t}\n\t\n\t\tunsigned ctr = 0;\n\t\tfor(unsigned j=0;j<tmpstr.size();++j)\n\t\t\tif(bern(rng)) {\n\t\t\t\ttmpstr[j] = nucl[unif_4(rng)];\n\t\t\t\tctr++;\n\t\t\t}\n\t\t\t//cout << ctr << endl;\n\t\t//if(faircoin(rng)) flipvecdir(tmpstr); // flip every second \n\n\t\t// write to file\n\t\tout << tmpstr;\n\t\tif(i!= M-1) out << endl;\n\t}\n\tout.close();\n\n}\n\n}\n", "meta": {"hexsha": "c599d2d6974ed7f06f77d3daf196d2cde4944083", "size": 6584, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulate/texttodna.cpp", "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": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-12-12T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T17:58:00.000Z", "max_issues_repo_path": "simulate/texttodna.cpp", "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": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-22T19:55:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T19:55:28.000Z", "max_forks_repo_path": "simulate/texttodna.cpp", "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": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-21T23:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-21T23:57:51.000Z", "avg_line_length": 24.3851851852, "max_line_length": 124, "alphanum_fraction": 0.6398845687, "num_tokens": 2023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.5014392324962809}}
{"text": "#include <opencv2/opencv.hpp>\n#include <yaml-cpp/yaml.h>\n#include <boost/foreach.hpp>\n#include <boost/bind.hpp>\n#include <Eigen/Dense>\n\n#include \"calotypes/CrossValidation.hpp\"\n#include \"calotypes/CameraCalibration.h\"\n#include \"calotypes/CalibrationLog.h\"\n\n#include \"calotypes/RandomDataSelector.hpp\"\n\nusing namespace calotypes;\n\nint main( int argc, char** argv )\n{\n\t\n\tif( argc < 2 )\n\t{\n\t\tstd::cerr << \"Please specify config file path.\" << std::endl;\n\t\treturn -1;\n\t}\n\t\n\tstd::string configPath( argv[1] );\n\tCalibrationLogReader reader( configPath );\n\t\n\tCameraTrainingData datum;\n\tstd::vector<CameraTrainingData> data;\n\twhile( reader.GetNext( datum ) )\n\t{\n\t\tdata.push_back( datum );\n\t}\n\t\n\tstd::vector<CameraTrainingData> subset;\n\tRandomCameraDataSelector selector;\n// \tselector.SelectData( data, data.size(), subset );\n\tsubset = data;\n\t\n\tCameraTrainingParams params;\n\tparams.optimizeAspectRatio = true;\n\tparams.optimizePrincipalPoint = true;\n\tparams.enableRadialDistortion[0] = true;\n\tparams.enableRadialDistortion[1] = false;\n\t\n\ttypedef CrossValidationTask< CameraModel, CameraTrainingData > CameraCV;\n\tCameraCV::TrainFunc trainer = boost::bind( &TrainCameraModel, _1, _2,\n\t\t\t\t\t\t\t\t\t\t\t   data[0].imageSize, params ); // HACK heh\n\tCameraCV::TestFunc tester = boost::bind( &TestCameraModel, _1, _2 );\n\tCameraCV crossValidation( trainer, tester, subset, 4 );\n\t\n\tunsigned int numFolds = 4;\n\tstd::cout << \"Performing \" << numFolds << \"-fold cross validation...\" << std::endl;\n\tcrossValidation.Validate();\n\tstd::vector< CameraCV::ValidationResult > results = crossValidation.GetResults();\n\t\n\tstd::cout << \"Errors: \" << std::endl;\n\tfor( unsigned int i = 0; i < numFolds; i++ )\n\t{\n\t\tstd::cout << \"\\tFold \" << i << \" test/train: \" << results[i].testError\n\t\t\t\t  << \" \" << results[i].trainingError << std::endl;\n\t\tstd::cout << \"\\tModel \" << results[i].model << std::endl;\n\t}\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "a4a371082674824d5673bb998b03eed6bbcf33dc", "size": 1877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/SimpleCalibration.cpp", "max_stars_repo_name": "Humhu/calotypes", "max_stars_repo_head_hexsha": "a05a809b3b27983332c24d8fb04cb71f47e96763", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-18T14:59:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-18T14:59:39.000Z", "max_issues_repo_path": "app/SimpleCalibration.cpp", "max_issues_repo_name": "Humhu/calotypes", "max_issues_repo_head_hexsha": "a05a809b3b27983332c24d8fb04cb71f47e96763", "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": "app/SimpleCalibration.cpp", "max_forks_repo_name": "Humhu/calotypes", "max_forks_repo_head_hexsha": "a05a809b3b27983332c24d8fb04cb71f47e96763", "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": 28.4393939394, "max_line_length": 84, "alphanum_fraction": 0.694725626, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5014016569950378}}
{"text": "//==============================================================================\n//         Copyright 2016        Numscale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <boost/simd/function/simd/nthroot.hpp>\n#include <boost/simd/constant/valmax.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/pack.hpp>\n#include <exhaustive.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n\n#include <cmath>\n#include <cstdlib>\n\nstruct raw_nth\n{\n  float operator()(float x) const\n  {\n    return bs::nthroot(double(x), 4);\n  }\n};\n\nstruct nth\n{\n  bs::pack<float> operator()(bs::pack<float> x) const\n  {\n    using pi_t = bd::as_integer_t<bs::pack<float>>;\n    return bs::fast_(bs::nthroot)(x, pi_t(4));\n  }\n};\n\nint main(int argc, char* argv[])\n{\n\n  float mini = bs::Zero<float>();\n  float maxi = bs::Valmax<float>();\n  if(argc >= 2) mini = std::atof(argv[1]);\n  if(argc >= 3) maxi = std::atof(argv[2]);\n  bs::exhaustive_test<bs::pack<float>> ( mini\n                                       , maxi\n                                       , nth()\n                                       , raw_nth()\n                                       );\n\n  return 0;\n}\n", "meta": {"hexsha": "1679717de4c40a1ee0f4c05b274c7fa62cb2be06", "size": 1407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exhaustive/function/simd/nthroot.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": "exhaustive/function/simd/nthroot.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": "exhaustive/function/simd/nthroot.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": 28.14, "max_line_length": 80, "alphanum_fraction": 0.4875621891, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5014016569950378}}
{"text": "#include <iostream>\n#include <fstream>\n#include <memory>\n#include <boost/algorithm/string.hpp>\n\nusing namespace std;\n\n/* Becasue I want to use OpenMP,\n * So I must use vector as the container for paras, because openmp require random access iterator.\n * And must use list as the container for results, because vector need to relocate, and therefore not thread-safe.\n */\n\n// type define\ntypedef array<double, 3> Row;\ntypedef shared_ptr< list<Row> > RowList;\ntypedef array<double, 3> Para;\ntypedef shared_ptr< vector<Para> > ParaList;\ntypedef pair<Para, int> Score;\n\n// function defines\nRowList readFile(const string& fileName);\nint sign(const Row& row, const Para& para);\nint errors(const Para& para);\nint predictErrors(const Para& para);\nPara patch(const Para& para, const Row& row);\nParaList analysys(const Para& para);\nScore deepin(const int now, const Para& para, const int limit);\n\n// overloading define\nostream &operator<<(ostream& out, const Para& para) {\n\tout << \"[\" << para[0] << \", \" << para[1] << \", \" << para[2] << \"]\";\n\treturn out;\n}\n\nostream &operator<<(ostream& out, const Score& score) {\n\tout << \"<\" << score.first << \", \" << score.second << \">\";\n\treturn out;\n}\n\n// preset data defines\nPara initPara = {0, 0, 0};\nauto trainFileContent = readFile(\"train_1_5.csv\");\nauto testFileContent = readFile(\"test_1_5.csv\");\n\n// main\nint main(void) {\n\tScore trainResult = deepin(0, initPara, 1);\n\tint predictionError = predictErrors(trainResult.first);\n\n\tcout << \"Train Result: \" << trainResult << endl;\n\tcout << \"Prediction Error: \" << predictionError << endl;\n}\n\n// function implementation\nRowList readFile(const string& fileName) {\n\tifstream inFile(fileName);\n\tstring line;\n\tvector<string> words;\n\tRow nums;\n\tRowList fileContent = static_cast<RowList>(new list<Row>);\n\n\twhile(getline(inFile, line)){\n\t\tboost::split(words, line, boost::is_any_of(\",\"));\n\t\tnums = {\n\t\t\tstod(words[0]),\n\t\t\tstod(words[1]),\n\t\t\tstod(words[2])\n\t\t};\n\t\tfileContent->push_back(nums);\n\t}\n\n\treturn fileContent;\n}\n\ninline int sign(const Row& row, const Para& para) {\n\tdouble result = para[0] * row[0] + para[1] * row[1] + para[2];\n\tif(result >= 0){\n\t\treturn 1;\n\t} else{\n\t\treturn -1;\n\t}\n}\n\nint errors(const Para& para) {\n\tint sum = 0;\n\n\tfor(auto it = trainFileContent->begin(); it != trainFileContent->end(); it++){\n\t\tRow& row = *it;\n\t\tif(sign(row, para) != row[2]){\n\t\t\tsum++;\n\t\t}\n\t}\n\n\treturn sum;\n}\n\nint predictErrors(const Para& para) {\n\tint sum = 0;\n\n\tfor(auto it = testFileContent->begin(); it != testFileContent->end(); it++){\n\t\tRow& row = *it;\n\t\tif(sign(row, para) != row[2]){\n\t\t\tsum++;\n\t\t}\n\t}\n\n\treturn sum;\n}\n\nPara patch(const Para& para, const Row& row) {\n\tPara tryPara = {\n\t\tpara[0] + row[2] * row[0],\n\t\tpara[1] + row[2] * row[1],\n\t\tpara[2] + row[2]\n\t};\n\n\treturn tryPara;\n}\n\nParaList analysys(const Para& para) {\n\tParaList candidatePara = static_cast<ParaList>(new vector<Para>);\n\n\tfor(auto it = trainFileContent->begin(); it != trainFileContent->end(); it++){\n\t\tRow& row = *it;\n\t\tif(sign(row, para) != row[2]){\n\t\t\tcandidatePara->push_back(patch(para, row));\n\t\t}\n\t}\n\n\treturn candidatePara;\n}\n\n\n/* @parameter: init para\n * @return: the best para among the child and sub-child para created by this para.\n */\nScore deepin(const int now, const Para& para, const int limit) {\n\tlist<Score> thisResult;\n\tthisResult.push_back(Score(para, errors(para)));\n\n\tif(now < limit){\n\t\tauto tryParas = *analysys(para);\n\t\tconst unsigned int size = tryParas.size();\n\n\t\t//#pragma omp parallel for\n\t\tfor(unsigned int i = 0; i < size; i++){\n\t\t\tPara& childPara = tryParas[i];\n\t\t\tthisResult.push_back(deepin(now+1, childPara, limit));\n\t\t\tif(now == 0){\n\t\t\t\tcout << \"No: \" << i << \", Score: \" << *thisResult.rbegin() << endl;\n\t\t\t}\n\t\t}\n\t} else{\n\t\tauto tryParas = *analysys(para);\n\t\tconst unsigned int size = tryParas.size();\n\n\t\tfor(unsigned int i = 0; i < size; i++){\n\t\t\tPara& subPara = tryParas[i];\n\t\t\tthisResult.push_back(Score(subPara, errors(subPara)));\n\t\t}\n\t}\n\n\tPara bestPara = thisResult.begin()->first;\n\tint bestError = thisResult.begin()->second;\n\n\tfor(auto it = thisResult.begin(); it != thisResult.end(); it++){\n\t\tif(it->second < bestError){\n\t\t\tbestPara = it->first;\n\t\t\tbestError = it->second;\n\t\t}\n\t}\n\n\treturn(Score(bestPara, bestError));\n}\n", "meta": {"hexsha": "5cb3e567f66452c75fadb60cdd61aec36cc53d2c", "size": 4204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "job1/main.cpp", "max_stars_repo_name": "Preffer/machine-learning-sutd", "max_stars_repo_head_hexsha": "d822a9b623f9bb989e71fb2b509b32008cbf063b", "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": "job1/main.cpp", "max_issues_repo_name": "Preffer/machine-learning-sutd", "max_issues_repo_head_hexsha": "d822a9b623f9bb989e71fb2b509b32008cbf063b", "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": "job1/main.cpp", "max_forks_repo_name": "Preffer/machine-learning-sutd", "max_forks_repo_head_hexsha": "d822a9b623f9bb989e71fb2b509b32008cbf063b", "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.0228571429, "max_line_length": 114, "alphanum_fraction": 0.6548525214, "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5014016516250834}}
{"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   testGaussianFactorGraphB.cpp\n *  @brief  Unit tests for Linear Factor Graph\n *  @author Christian Potthast\n **/\n\n#include <tests/smallExample.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/linear/GaussianBayesNet.h>\n#include <gtsam/linear/GaussianBayesTree.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/base/numericalDerivative.h>\n#include <gtsam/base/Matrix.h>\n#include <gtsam/base/Testable.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/tuple/tuple.hpp>\n#include <boost/assign/std/list.hpp> // for operator +=\n#include <boost/assign/std/set.hpp> // for operator +=\n#include <boost/assign/std/vector.hpp> // for operator +=\nusing namespace boost::assign;\n#include <boost/range/adaptor/map.hpp>\nnamespace br { using namespace boost::range; using namespace boost::adaptors; }\n\n#include <string.h>\n#include <iostream>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace example;\n\ndouble tol=1e-5;\n\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\nstatic auto kUnit2 = noiseModel::Unit::Create(2);\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, equals ) {\n\n  GaussianFactorGraph fg = createGaussianFactorGraph();\n  GaussianFactorGraph fg2 = createGaussianFactorGraph();\n  EXPECT(fg.equals(fg2));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, error ) {\n  GaussianFactorGraph fg = createGaussianFactorGraph();\n  VectorValues cfg = createZeroDelta();\n\n  // note the error is the same as in testNonlinearFactorGraph as a\n  // zero delta config in the linear graph is equivalent to noisy in\n  // non-linear, which is really linear under the hood\n  double actual = fg.error(cfg);\n  DOUBLES_EQUAL( 5.625, actual, 1e-9 );\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, eliminateOne_x1) {\n  GaussianFactorGraph fg = createGaussianFactorGraph();\n\n  GaussianConditional::shared_ptr conditional;\n  auto result = fg.eliminatePartialSequential(Ordering(list_of(X(1))));\n  conditional = result.first->front();\n\n  // create expected Conditional Gaussian\n  Matrix I = 15 * I_2x2, R11 = I, S12 = -0.111111 * I, S13 = -0.444444 * I;\n  Vector d = Vector2(-0.133333, -0.0222222);\n  GaussianConditional expected(X(1), 15 * d, R11, L(1), S12, X(2), S13);\n\n  EXPECT(assert_equal(expected, *conditional, tol));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, eliminateOne_x2) {\n  Ordering ordering;\n  ordering += X(2), L(1), X(1);\n  GaussianFactorGraph fg = createGaussianFactorGraph();\n  auto actual = EliminateQR(fg, Ordering(list_of(X(2)))).first;\n\n  // create expected Conditional Gaussian\n  double sigma = 0.0894427;\n  Matrix I = I_2x2 / sigma, R11 = I, S12 = -0.2 * I, S13 = -0.8 * I;\n  Vector d = Vector2(0.2, -0.14) / sigma;\n  GaussianConditional expected(X(2), d, R11, L(1), S12, X(1), S13, kUnit2);\n\n  EXPECT(assert_equal(expected, *actual, tol));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, eliminateOne_l1) {\n  Ordering ordering;\n  ordering += L(1), X(1), X(2);\n  GaussianFactorGraph fg = createGaussianFactorGraph();\n  auto actual = EliminateQR(fg, Ordering(list_of(L(1)))).first;\n\n  // create expected Conditional Gaussian\n  double sigma = sqrt(2.0) / 10.;\n  Matrix I = I_2x2 / sigma, R11 = I, S12 = -0.5 * I, S13 = -0.5 * I;\n  Vector d = Vector2(-0.1, 0.25) / sigma;\n  GaussianConditional expected(L(1), d, R11, X(1), S12, X(2), S13, kUnit2);\n\n  EXPECT(assert_equal(expected, *actual, tol));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, eliminateOne_x1_fast) {\n  GaussianFactorGraph fg = createGaussianFactorGraph();\n  GaussianConditional::shared_ptr conditional;\n  JacobianFactor::shared_ptr remaining;\n  boost::tie(conditional, remaining) = EliminateQR(fg, Ordering(list_of(X(1))));\n\n  // create expected Conditional Gaussian\n  Matrix I = 15 * I_2x2, R11 = I, S12 = -0.111111 * I, S13 = -0.444444 * I;\n  Vector d = Vector2(-0.133333, -0.0222222);\n  GaussianConditional expected(X(1), 15 * d, R11, L(1), S12, X(2), S13, kUnit2);\n\n  // Create expected remaining new factor\n  JacobianFactor expectedFactor(\n      L(1), (Matrix(4, 2) << 6.87184, 0, 0, 6.87184, 0, 0, 0, 0).finished(),\n      X(2),\n      (Matrix(4, 2) << -5.25494, 0, 0, -5.25494, -7.27607, 0, 0, -7.27607)\n          .finished(),\n      (Vector(4) << -1.21268, 1.73817, -0.727607, 1.45521).finished(),\n      noiseModel::Unit::Create(4));\n\n  EXPECT(assert_equal(expected, *conditional, tol));\n  EXPECT(assert_equal(expectedFactor, *remaining, tol));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, eliminateOne_x2_fast) {\n  GaussianFactorGraph fg = createGaussianFactorGraph();\n  auto actual = EliminateQR(fg, Ordering(list_of(X(2)))).first;\n\n  // create expected Conditional Gaussian\n  double sigma = 0.0894427;\n  Matrix I = I_2x2 / sigma, R11 = -I, S12 = 0.2 * I, S13 = 0.8 * I;\n  Vector d = Vector2(-0.2, 0.14) / sigma;\n  GaussianConditional expected(X(2), d, R11, L(1), S12, X(1), S13, kUnit2);\n\n  EXPECT(assert_equal(expected, *actual, tol));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, eliminateOne_l1_fast) {\n  GaussianFactorGraph fg = createGaussianFactorGraph();\n  auto actual = EliminateQR(fg, Ordering(list_of(L(1)))).first;\n\n  // create expected Conditional Gaussian\n  double sigma = sqrt(2.0) / 10.;\n  Matrix I = I_2x2 / sigma, R11 = -I, S12 = 0.5 * I, S13 = 0.5 * I;\n  Vector d = Vector2(0.1, -0.25) / sigma;\n  GaussianConditional expected(L(1), d, R11, X(1), S12, X(2), S13, kUnit2);\n\n  EXPECT(assert_equal(expected, *actual, tol));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, copying) {\n  // Create a graph\n  GaussianFactorGraph actual = createGaussianFactorGraph();\n\n  // Copy the graph !\n  GaussianFactorGraph copy = actual;\n\n  // now eliminate the copy\n  GaussianBayesNet actual1 = *copy.eliminateSequential();\n\n  // Create the same graph, but not by copying\n  GaussianFactorGraph expected = createGaussianFactorGraph();\n\n  // and check that original is still the same graph\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, CONSTRUCTOR_GaussianBayesNet) {\n  GaussianFactorGraph fg = createGaussianFactorGraph();\n\n  // render with a given ordering\n  GaussianBayesNet CBN = *fg.eliminateSequential();\n\n  // True GaussianFactorGraph\n  GaussianFactorGraph fg2(CBN);\n  GaussianBayesNet CBN2 = *fg2.eliminateSequential();\n  EXPECT(assert_equal(CBN, CBN2));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, optimize_Cholesky) {\n  // create a graph\n  GaussianFactorGraph fg = createGaussianFactorGraph();\n\n  // optimize the graph\n  VectorValues actual = fg.optimize(boost::none, EliminateCholesky);\n\n  // verify\n  VectorValues expected = createCorrectDelta();\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, optimize_QR )\n{\n  // create a graph\n  GaussianFactorGraph fg = createGaussianFactorGraph();\n\n  // optimize the graph\n  VectorValues actual = fg.optimize(boost::none, EliminateQR);\n\n  // verify\n  VectorValues expected = createCorrectDelta();\n  EXPECT(assert_equal(expected,actual));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, combine) {\n  // create a test graph\n  GaussianFactorGraph fg1 = createGaussianFactorGraph();\n\n  // create another factor graph\n  GaussianFactorGraph fg2 = createGaussianFactorGraph();\n\n  // get sizes\n  size_t size1 = fg1.size();\n  size_t size2 = fg2.size();\n\n  // combine them\n  fg1.push_back(fg2);\n\n  EXPECT(size1 + size2 == fg1.size());\n}\n\n/* ************************************************************************* */\n// print a vector of ints if needed for debugging\nvoid print(vector<int> v) {\n  for (size_t k = 0; k < v.size(); k++) cout << v[k] << \" \";\n  cout << endl;\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, createSmoother) {\n  GaussianFactorGraph fg1 = createSmoother(2);\n  LONGS_EQUAL(3, fg1.size());\n  GaussianFactorGraph fg2 = createSmoother(3);\n  LONGS_EQUAL(5, fg2.size());\n}\n\n/* ************************************************************************* */\ndouble error(const VectorValues& x) {\n  GaussianFactorGraph fg = createGaussianFactorGraph();\n  return fg.error(x);\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, multiplication) {\n  GaussianFactorGraph A = createGaussianFactorGraph();\n  VectorValues x = createCorrectDelta();\n  Errors actual = A * x;\n  Errors expected;\n  expected += Vector2(-1.0, -1.0);\n  expected += Vector2(2.0, -1.0);\n  expected += Vector2(0.0, 1.0);\n  expected += Vector2(-1.0, 1.5);\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\n// Extra test on elimination prompted by Michael's email to Frank 1/4/2010\nTEST(GaussianFactorGraph, elimination) {\n  // Create Gaussian Factor Graph\n  GaussianFactorGraph fg;\n  Matrix Ap = I_1x1, An = I_1x1 * -1;\n  Vector b = (Vector(1) << 0.0).finished();\n  SharedDiagonal sigma = noiseModel::Isotropic::Sigma(1, 2.0);\n  fg += JacobianFactor(X(1), An, X(2), Ap, b, sigma);\n  fg += JacobianFactor(X(1), Ap, b, sigma);\n  fg += JacobianFactor(X(2), Ap, b, sigma);\n\n  // Eliminate\n  Ordering ordering;\n  ordering += X(1), X(2);\n  GaussianBayesNet bayesNet = *fg.eliminateSequential();\n\n  // Check matrix\n  Matrix R;\n  Vector d;\n  boost::tie(R, d) = bayesNet.matrix();\n  Matrix expected =\n      (Matrix(2, 2) << 0.707107, -0.353553, 0.0, 0.612372).finished();\n  Matrix expected2 =\n      (Matrix(2, 2) << 0.707107, -0.353553, 0.0, -0.612372).finished();\n  EXPECT(assert_equal(expected, R, 1e-6));\n  EXPECT(equal_with_abs_tol(expected, R, 1e-6) ||\n         equal_with_abs_tol(expected2, R, 1e-6));\n}\n\n/* ************************************************************************* */\n// Tests ported from ConstrainedGaussianFactorGraph\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, constrained_simple) {\n  // get a graph with a constraint in it\n  GaussianFactorGraph fg = createSimpleConstraintGraph();\n  EXPECT(hasConstraints(fg));\n\n  // eliminate and solve\n  VectorValues actual = fg.eliminateSequential()->optimize();\n\n  // verify\n  VectorValues expected = createSimpleConstraintValues();\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, constrained_single) {\n  // get a graph with a constraint in it\n  GaussianFactorGraph fg = createSingleConstraintGraph();\n  EXPECT(hasConstraints(fg));\n\n  // eliminate and solve\n  VectorValues actual = fg.eliminateSequential()->optimize();\n\n  // verify\n  VectorValues expected = createSingleConstraintValues();\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, constrained_multi1) {\n  // get a graph with a constraint in it\n  GaussianFactorGraph fg = createMultiConstraintGraph();\n  EXPECT(hasConstraints(fg));\n\n  // eliminate and solve\n  VectorValues actual = fg.eliminateSequential()->optimize();\n\n  // verify\n  VectorValues expected = createMultiConstraintValues();\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\n\nstatic SharedDiagonal model = noiseModel::Isotropic::Sigma(2,1);\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, replace)\n{\n  Ordering ord; ord += X(1),X(2),X(3),X(4),X(5),X(6);\n  SharedDiagonal noise(noiseModel::Isotropic::Sigma(3, 1.0));\n\n  GaussianFactorGraph::sharedFactor f1(new JacobianFactor(\n      X(1), I_3x3, X(2), I_3x3, Z_3x1, noise));\n  GaussianFactorGraph::sharedFactor f2(new JacobianFactor(\n      X(2), I_3x3, X(3), I_3x3, Z_3x1, noise));\n  GaussianFactorGraph::sharedFactor f3(new JacobianFactor(\n      X(3), I_3x3, X(4), I_3x3, Z_3x1, noise));\n  GaussianFactorGraph::sharedFactor f4(new JacobianFactor(\n      X(5), I_3x3, X(6), I_3x3, Z_3x1, noise));\n\n  GaussianFactorGraph actual;\n  actual.push_back(f1);\n  actual.push_back(f2);\n  actual.push_back(f3);\n  actual.replace(0, f4);\n\n  GaussianFactorGraph expected;\n  expected.push_back(f4);\n  expected.push_back(f2);\n  expected.push_back(f3);\n\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, hasConstraints)\n{\n  FactorGraph<GaussianFactor> fgc1 = createMultiConstraintGraph();\n  EXPECT(hasConstraints(fgc1));\n\n  FactorGraph<GaussianFactor> fgc2 = createSimpleConstraintGraph() ;\n  EXPECT(hasConstraints(fgc2));\n\n  GaussianFactorGraph fg = createGaussianFactorGraph();\n  EXPECT(!hasConstraints(fg));\n}\n\n#include <gtsam/slam/ProjectionFactor.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/sam/RangeFactor.h>\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, conditional_sigma_failure) {\n  // This system derives from a failure case in DDF in which a Bayes Tree\n  // has non-unit sigmas for conditionals in the Bayes Tree, which\n  // should never happen by construction\n\n  // Reason for the failure: using Vector_() is dangerous as having a non-float gets set to zero, resulting in constraints\n  gtsam::Key xC1 = 0, l32 = 1, l41 = 2;\n\n  // noisemodels at nonlinear level\n  gtsam::SharedNoiseModel priorModel = noiseModel::Diagonal::Sigmas((Vector(6) << 0.05, 0.05, 3.0, 0.2, 0.2, 0.2).finished());\n  gtsam::SharedNoiseModel measModel = kUnit2;\n  gtsam::SharedNoiseModel elevationModel = noiseModel::Isotropic::Sigma(1, 3.0);\n\n  double fov = 60; // degrees\n  int imgW = 640; // pixels\n  int imgH = 480; // pixels\n  gtsam::Cal3_S2::shared_ptr K(new gtsam::Cal3_S2(fov, imgW, imgH));\n\n  typedef GenericProjectionFactor<Pose3, Point3> ProjectionFactor;\n\n  double relElevation = 6;\n\n  Values initValues;\n  initValues.insert(xC1,\n      Pose3(Rot3(\n          -1.,           0.0,  1.2246468e-16,\n          0.0,             1.,           0.0,\n          -1.2246468e-16,           0.0,            -1.),\n          Point3(0.511832102, 8.42819594, 5.76841725)));\n  initValues.insert(l32,  Point3(0.364081507, 6.89766221, -0.231582751) );\n  initValues.insert(l41,  Point3(1.61051523, 6.7373052, -0.231582751)   );\n\n  NonlinearFactorGraph factors;\n  factors += PriorFactor<Pose3>(xC1,\n      Pose3(Rot3(\n          -1.,           0.0,  1.2246468e-16,\n          0.0,             1.,           0.0,\n          -1.2246468e-16,           0.0,            -1),\n          Point3(0.511832102, 8.42819594, 5.76841725)), priorModel);\n  factors += ProjectionFactor(Point2(333.648615, 98.61535), measModel, xC1, l32, K);\n  factors += ProjectionFactor(Point2(218.508, 83.8022039), measModel, xC1, l41, K);\n  factors += RangeFactor<Pose3,Point3>(xC1, l32, relElevation, elevationModel);\n  factors += RangeFactor<Pose3,Point3>(xC1, l41, relElevation, elevationModel);\n\n  // Check that sigmas are correct (i.e., unit)\n  GaussianFactorGraph lfg = *factors.linearize(initValues);\n\n  GaussianBayesTree actBT = *lfg.eliminateMultifrontal();\n\n  // Check that all sigmas in an unconstrained bayes tree are set to one\n  for(const GaussianBayesTree::sharedClique& clique: actBT.nodes() | br::map_values) {\n    GaussianConditional::shared_ptr conditional = clique->conditional();\n    //size_t dim = conditional->rows();\n    //EXPECT(assert_equal(gtsam::Vector::Ones(dim), conditional->get_model()->sigmas(), tol));\n    EXPECT(!conditional->get_model());\n  }\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "c4e9d26f5a2a210313333c8561c6f343188bcee9", "size": 16799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testGaussianFactorGraphB.cpp", "max_stars_repo_name": "MisoRobotics/gtsam", "max_stars_repo_head_hexsha": "342f30d148fae84c92ff71705c9e50e0a3683bda", "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/testGaussianFactorGraphB.cpp", "max_issues_repo_name": "MisoRobotics/gtsam", "max_issues_repo_head_hexsha": "342f30d148fae84c92ff71705c9e50e0a3683bda", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-10-30T21:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T18:47:40.000Z", "max_forks_repo_path": "tests/testGaussianFactorGraphB.cpp", "max_forks_repo_name": "MisoRobotics/gtsam", "max_forks_repo_head_hexsha": "342f30d148fae84c92ff71705c9e50e0a3683bda", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-04T18:52:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T18:52:09.000Z", "avg_line_length": 35.8187633262, "max_line_length": 126, "alphanum_fraction": 0.6013453182, "num_tokens": 4427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5014016408851742}}
{"text": "//\n// Created by wei on 10/3/18.\n//\n\n#include <Cuda/Common/TransformCuda.h>\n#include <Eigen/Eigen>\n#include <Open3D/Open3D.h>\n\n#include <gtest/gtest.h>\n\nusing namespace open3d;\nusing namespace open3d::utility;\nusing namespace open3d::cuda;\n\nTEST(TransformCuda, Transform) {\n    using namespace open3d;\n\n    for (int i = 0; i < 1000; ++i) {\n        /* Generate random R & t */\n        Eigen::Vector3d w = Eigen::Vector3d::Random();\n        float theta = w.norm();\n        w = w / theta;\n        Eigen::Matrix3d w_tilde;\n        w_tilde << 0, -w(2), w(1),\n            w(2), 0, -w(0),\n            -w(1), w(0), 0;\n        Eigen::Matrix3d R =\n            Eigen::Matrix3d::Identity()\n            + sin(theta) * w_tilde + (1 - cos(theta)) * (w_tilde * w_tilde);\n        \n        Eigen::Vector3d t = Eigen::Vector3d::Random();\n        Eigen::Matrix4d T = Eigen::Matrix4d::Identity();\n        T.block<3, 3>(0, 0) = R;\n        T.block<3, 1>(0, 3) = t;\n\n\n        TransformCuda transform_cuda;\n        transform_cuda.FromEigen(R, t);\n        float\n            matrix_norm = (T.inverse() - transform_cuda.Inverse().ToEigen()).norm();\n        EXPECT_LE(matrix_norm, 1e-6);\n\n        Vector3f v_cuda;\n        Eigen::Vector3d v = Eigen::Vector3d::Random();\n        v_cuda.FromEigen(v);\n\n        Vector3f Tv_cuda = transform_cuda * v_cuda;\n        float vector_norm = ((T * v.homogeneous()).hnormalized() -\n            (transform_cuda * v_cuda).ToEigen()).norm();\n        EXPECT_LE(vector_norm, 1e-6);\n    }\n    LogInfo(\"Transform tests passed\\n\");\n\n    Vector1f v;\n    v(0) = 1.0f;\n    v = 1.0f * v;\n}\n\nint main(int argc, char **argv) {\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "c943e38833d1dc1de799316b1cd185f594b422c6", "size": 1694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/UnitTest/Cuda/Container/TestTransformCuda.cpp", "max_stars_repo_name": "devshank3/Open3D", "max_stars_repo_head_hexsha": "91611eb562680a41be8a52497bb45d278f2c9377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 113.0, "max_stars_repo_stars_event_min_datetime": "2018-11-12T03:32:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:58:54.000Z", "max_issues_repo_path": "src/UnitTest/Cuda/Container/TestTransformCuda.cpp", "max_issues_repo_name": "llp45135/Open3D", "max_issues_repo_head_hexsha": "ff7003d542c4fcf88a2d9e7fe08508b3e52dc702", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-19T12:09:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T11:55:54.000Z", "max_forks_repo_path": "src/UnitTest/Cuda/Container/TestTransformCuda.cpp", "max_forks_repo_name": "llp45135/Open3D", "max_forks_repo_head_hexsha": "ff7003d542c4fcf88a2d9e7fe08508b3e52dc702", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2018-10-16T20:01:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T08:02:20.000Z", "avg_line_length": 26.8888888889, "max_line_length": 84, "alphanum_fraction": 0.5619834711, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5014016397598084}}
{"text": "/*****************************************************************************\n*\n*     Program: EPTlib\n*     Author: Alessandro Arduino <a.arduino@inrim.it>\n*\n*  MIT License\n*\n*  Copyright (c) 2020-2021  Alessandro Arduino\n*  Istituto Nazionale di Ricerca Metrologica (INRiM)\n*  Strada delle cacce 91, 10135 Torino\n*  ITALY\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#include \"eptlib/finite_difference.h\"\n\n#include <complex>\n#include <iostream>\n\n#include <Eigen/Dense>\n\nusing namespace eptlib;\n\n// FDSavitzkyGolayFilter constructor\nFDSavitzkyGolayFilter::\nFDSavitzkyGolayFilter(const Shape &shape) :\n    shape_(shape),\n    m_vox_(std::accumulate(shape.GetSize().begin(),shape.GetSize().end(),1,std::multiplies<int>())) {\n    double toll = 1e-10;\n    std::array<int,NDIM> mm = shape_.GetSize();\n    // check to have odd shape size\n    assert(m_vox_%2);\n    // get the central voxel address\n    int idx0 = m_vox_/2;\n    std::array<int,NDIM> ii0;\n    for (int d = 0; d<NDIM; ++d) {\n        ii0[d] = mm[d]/2;\n    }\n    // initialise the design matrix\n    int n_row = shape_.GetVolume();\n    int n_col2 = 1 + NDIM;\n    int n_col1 = (NDIM*(NDIM+1))/2;\n    Eigen::MatrixXd F2(n_row,n_col2);\n    Eigen::MatrixXd F1(n_row,n_col1);\n    // fill the design matrix\n    std::array<int,NDIM> ii;\n    std::array<double,NDIM> di;\n    int r = 0;\n    for (ii[2] = 0; ii[2]<mm[2]; ++ii[2]) {\n        for (ii[1] = 0; ii[1]<mm[1]; ++ii[1]) {\n            for (ii[0] = 0; ii[0]<mm[0]; ++ii[0]) {\n                if (shape_[ii]) {\n                    for (int d = 0; d<NDIM; ++d) {\n                        di[d] = ii[d]-ii0[d];\n                    }\n                    // design matrix for even quantities\n                    F2(r,0) = 1.0;\n                    for (int d = 0; d<NDIM; ++d) {\n                        F2(r,1+d) = di[d]*di[d];\n                    }\n                    // design matrix for odd quantities\n                    int c = 0;\n                    for (int d = 0; d<NDIM; ++d) {\n                        F1(r,d) = di[d];\n                        for (int d2 = d+1; d2<NDIM; ++d2) {\n                            F1(r,NDIM+c) = di[d]*di[d2];\n                            ++c;\n                        }\n                    }\n                    ++r;\n                }\n            }\n        }\n    }\n    // check that all lines are filled\n    Eigen::VectorXd v = F2.cwiseAbs().colwise().sum();\n    double ref = v.maxCoeff();\n    for (int d = 0; d<NDIM; ++d) {\n        if (v[d]<toll*ref) {\n            throw std::runtime_error(\"Impossible to set-up the Savitzky-Golay filter with the provided shape: no points along direction \"+std::to_string(d)+\".\");\n        }\n    }\n    v = F1.cwiseAbs().colwise().sum();\n    ref = v.maxCoeff();\n    for (int d = 0; d<NDIM; ++d) {\n        if (v[d]<toll*ref) {\n            throw std::runtime_error(\"Impossible to set-up the Savitzky-Golay filter with the provided shape: no points along direction \"+std::to_string(d)+\".\");\n        }\n    }\n    for (int c = NDIM; c<n_col1; ++c) {\n        if (v[c]<toll*ref) {\n            --n_col1;\n            F1.col(c).swap(F1.col(n_col1));\n            --c;\n        }\n    }\n    F1.conservativeResize(Eigen::NoChange, n_col1);\n    // solve the normal equations\n    Eigen::MatrixXd A;\n    if (shape_.IsSymmetric()) {\n        A = (F2.transpose()*F2).inverse()*F2.transpose();\n    } else {\n        Eigen::MatrixXd F(n_row,n_col2+n_col1);\n        F << F2,F1;\n        A = (F.transpose()*F).inverse()*F.transpose();\n    }\n    // Compute the kernel for the laplacian\n    for (int d = 0; d<NDIM; ++d) {\n        lapl_kernel_[d].resize(m_vox_,0.0);\n        r = 0;\n        for (int idx = 0; idx<m_vox_; ++idx) {\n            if (shape_[idx]) {\n                lapl_kernel_[d][idx] = 2.0*A(1+d,r);\n                ++r;\n            }\n        }\n    }\n    // Compute the kernel for the gradient\n    int c_base = 1+NDIM;\n    if (shape_.IsSymmetric()) {\n        A = (F1.transpose()*F1).inverse()*F1.transpose();\n        c_base = 0;\n    }\n    for (int d = 0; d<NDIM; ++d) {\n        grad_kernel_[d].resize(m_vox_,0.0);\n        r = 0;\n        for (int idx = 0; idx<m_vox_; ++idx) {\n            if (shape_[idx]) {\n                grad_kernel_[d][idx] = A(c_base+d,r);\n                ++r;\n            }\n        }\n    }\n    return;\n}\n\n// FDSavitzkyGolayFilter apply\ntemplate <typename NumType>\nEPTlibError FDSavitzkyGolayFilter::\nApply(const DifferentialOperator diff_op, NumType *dst, const NumType *src, const std::array<int,NDIM> &nn, const std::array<double,NDIM> &dd) const {\n    const int n_vox = std::accumulate(nn.begin(),nn.end(),1,std::multiplies<int>());\n    std::array<int,NDIM> ii;\n    std::array<int,NDIM> rr;\n    std::array<int,NDIM> inc;\n    for (int d = 0; d<NDIM; ++d) {\n        rr[d] = shape_.GetSize()[d]/2;\n    }\n    inc[0] = 1;\n    inc[1] = nn[0]-shape_.GetSize()[0];\n    inc[2] = nn[0]*(nn[1]-shape_.GetSize()[1]);\n    // loop over field voxels\n    for (ii[2] = rr[2]; ii[2]<nn[2]-rr[2]; ++ii[2]) {\n        for (ii[1] = rr[1]; ii[1]<nn[1]-rr[1]; ++ii[1]) {\n            for (ii[0] = rr[0]; ii[0]<nn[0]-rr[0]; ++ii[0]) {\n                std::array<int,NDIM> ii_l;\n                std::vector<NumType> field_crop(m_vox_,0.0);\n                // inner loop over kernel voxels\n                int idx_l = 0;\n                int idx_g = ii[0]-rr[0] + nn[0]*(ii[1]-rr[1] + nn[1]*(ii[2]-rr[2]));\n                for (ii_l[2] = -rr[2]; ii_l[2]<=rr[2]; ++ii_l[2]) {\n                    for (ii_l[1] = -rr[1]; ii_l[1]<=rr[1]; ++ii_l[1]) {\n                        for (ii_l[0] = -rr[0]; ii_l[0]<=rr[0]; ++ii_l[0]) {\n                            if (shape_[idx_l]) {\n                                // set the field_crop to the field value\n                                field_crop[idx_l] = src[idx_g];\n                            }\n                            ++idx_l;\n                            idx_g += inc[0];\n                        }\n                        idx_g += inc[1];\n                    }\n                    idx_g += inc[2];\n                }\n                // compute the derivative\n                int idx = ii[0] + nn[0]*(ii[1] + nn[1]*ii[2]);\n                if (diff_op==DifferentialOperator::GradientX||\n                    diff_op==DifferentialOperator::GradientY||\n                    diff_op==DifferentialOperator::GradientZ) {\n                    int d = static_cast<int>(diff_op) -\n                        static_cast<int>(DifferentialOperator::GradientX);\n                    dst[idx] = FirstOrder(d,field_crop,dd);\n                } else if (diff_op==DifferentialOperator::GradientXX||\n                    diff_op==DifferentialOperator::GradientYY||\n                    diff_op==DifferentialOperator::GradientZZ) {\n                    int d = static_cast<int>(diff_op) -\n                        static_cast<int>(DifferentialOperator::GradientXX);\n                    dst[idx] = SecondOrder(d,field_crop,dd);\n                } else if (diff_op==DifferentialOperator::Laplacian) {\n                    dst[idx] = Laplacian(field_crop,dd);\n                }\n            }\n        }\n    }\n    return EPTlibError::Success;\n}\n\n// FDSavitzkyGolayFilter apply kernel first order derivative\ntemplate <typename NumType>\nNumType FDSavitzkyGolayFilter::\nFirstOrder(const int d, const std::vector<NumType> &field_crop, const std::array<double,NDIM> &dd) const {\n    NumType dst = std::inner_product(grad_kernel_[d].begin(),grad_kernel_[d].end(),field_crop.begin(),static_cast<NumType>(0.0))/dd[d];\n    return dst;\n}\n// FDSavitzkyGolayFilter apply kernel second order derivative\ntemplate <typename NumType>\nNumType FDSavitzkyGolayFilter::\nSecondOrder(const int d, const std::vector<NumType> &field_crop, const std::array<double,NDIM> &dd) const {\n    NumType dst = std::inner_product(lapl_kernel_[d].begin(),lapl_kernel_[d].end(),field_crop.begin(),static_cast<NumType>(0.0))/dd[d]/dd[d];\n    return dst;\n}\n// FDSavitzkyGolayFilter apply kernel laplacian\ntemplate <typename NumType>\nNumType FDSavitzkyGolayFilter::\nLaplacian(const std::vector<NumType> &field_crop, const std::array<double,NDIM> &dd) const {\n    NumType dst = 0.0;\n    for (int d = 0; d<NDIM; ++d) {\n        dst += std::inner_product(lapl_kernel_[d].begin(),lapl_kernel_[d].end(),field_crop.begin(),static_cast<NumType>(0.0))/dd[d]/dd[d];\n    }\n    return dst;\n}\n\n// FDSavitzkyGolayFilter getters\nconst Shape& FDSavitzkyGolayFilter::\nGetShape() const {\n    return shape_;\n}\nconst std::array<std::vector<double>,NDIM>& FDSavitzkyGolayFilter::\nGetLaplKernel() const {\n    return lapl_kernel_;\n}\nconst std::array<std::vector<double>,NDIM>& FDSavitzkyGolayFilter::\nGetGradKernel() const {\n    return grad_kernel_;\n}\n\n// FDSavitzkyGolayFilter specialisations\ntemplate EPTlibError FDSavitzkyGolayFilter::Apply<double>(const DifferentialOperator diff_op,double *dst, const double *src, const std::array<int,NDIM> &nn, const std::array<double,NDIM> &dd) const;\ntemplate EPTlibError FDSavitzkyGolayFilter::Apply<std::complex<double> >(const DifferentialOperator diff_op,std::complex<double> *dst, const std::complex<double> *src, const std::array<int,NDIM> &nn, const std::array<double,NDIM> &dd) const;\ntemplate double FDSavitzkyGolayFilter::FirstOrder<double>(const int d,const std::vector<double> &field_crop,const std::array<double,NDIM> &dd) const;\ntemplate std::complex<double> FDSavitzkyGolayFilter::FirstOrder<std::complex<double> >(const int d,const std::vector<std::complex<double> > &field_crop,const std::array<double,NDIM> &dd) const;\ntemplate double FDSavitzkyGolayFilter::SecondOrder<double>(const int d,const std::vector<double> &field_crop,const std::array<double,NDIM> &dd) const;\ntemplate std::complex<double> FDSavitzkyGolayFilter::SecondOrder<std::complex<double> >(const int d,const std::vector<std::complex<double> > &field_crop,const std::array<double,NDIM> &dd) const;\ntemplate double FDSavitzkyGolayFilter::Laplacian<double>(const std::vector<double> &field_crop,const std::array<double,NDIM> &dd) const;\ntemplate std::complex<double> FDSavitzkyGolayFilter::Laplacian<std::complex<double> >(const std::vector<std::complex<double> > &field_crop,const std::array<double,NDIM> &dd) const;\n\n// Apply the FD filter to an wrapped phase input field.\nEPTlibError eptlib::WrappedPhaseDerivative(const DifferentialOperator diff_op,\n    double *dst, const double *src, const std::array<int,NDIM> &nn,\n    const std::array<double,NDIM> &dd, const FDSavitzkyGolayFilter &fd_filter) {\n    int n_vox = std::accumulate(nn.begin(),nn.end(),1,std::multiplies<int>());\n    // initialize the exponential map\n    std::vector<std::complex<double> > emap(n_vox);\n    for (int idx = 0; idx<n_vox; ++idx) {\n        emap[idx] = std::exp(std::complex<double>(0,src[idx]));\n    }\n    // compute the derivative...\n    if (diff_op==DifferentialOperator::GradientX||\n        diff_op==DifferentialOperator::GradientY||\n        diff_op==DifferentialOperator::GradientZ) {\n        // ...first order\n        std::vector<std::complex<double> > d_emap(n_vox);\n        fd_filter.Apply(diff_op,d_emap.data(),emap.data(),nn,dd);\n        for (int idx = 0; idx<n_vox; ++idx) {\n            dst[idx] = std::imag(d_emap[idx]/emap[idx]);\n        }\n    } else if (diff_op==DifferentialOperator::GradientXX||\n        diff_op==DifferentialOperator::GradientYY||\n        diff_op==DifferentialOperator::GradientZZ) {\n        // ...second order\n        DifferentialOperator diff_op1 = static_cast<DifferentialOperator>(static_cast<int>(diff_op)-static_cast<int>(DifferentialOperator::GradientXX));\n        std::vector<std::complex<double> > d_emap(n_vox);\n        std::vector<std::complex<double> > dd_emap(n_vox);\n        fd_filter.Apply(diff_op1,d_emap.data(),emap.data(),nn,dd);\n        fd_filter.Apply(diff_op,dd_emap.data(),emap.data(),nn,dd);\n        for (int idx = 0; idx<n_vox; ++idx) {\n            dst[idx] = std::imag(d_emap[idx]*d_emap[idx]/emap[idx]/emap[idx] + dd_emap[idx]/emap[idx]);\n        }\n    } else if (diff_op==DifferentialOperator::Laplacian) {\n        // ...laplacian\n        std::vector<std::complex<double> > dx_emap(n_vox);\n        std::vector<std::complex<double> > dy_emap(n_vox);\n        std::vector<std::complex<double> > dz_emap(n_vox);\n        std::vector<std::complex<double> > dd_emap(n_vox);\n        fd_filter.Apply(DifferentialOperator::GradientX,dx_emap.data(),emap.data(),nn,dd);\n        fd_filter.Apply(DifferentialOperator::GradientY,dy_emap.data(),emap.data(),nn,dd);\n        fd_filter.Apply(DifferentialOperator::GradientZ,dz_emap.data(),emap.data(),nn,dd);\n        fd_filter.Apply(DifferentialOperator::Laplacian,dd_emap.data(),emap.data(),nn,dd);\n        for (int idx = 0; idx<n_vox; ++idx) {\n            dst[idx] = std::imag((dx_emap[idx]*dx_emap[idx]+dy_emap[idx]*dy_emap[idx]+dz_emap[idx]*dz_emap[idx])/emap[idx]/emap[idx] + dd_emap[idx]/emap[idx]);\n        }\n    }\n    return EPTlibError::Success;\n}\n", "meta": {"hexsha": "fc0938a4e725fa1d3db7347e72b08136870f14b0", "size": 13947, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/finite_difference.cc", "max_stars_repo_name": "EPTlib/eptlib", "max_stars_repo_head_hexsha": "55610dd9d48f6598cb31de6bc9a913b845c62727", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T22:34:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T00:00:54.000Z", "max_issues_repo_path": "src/finite_difference.cc", "max_issues_repo_name": "EPTlib/eptlib", "max_issues_repo_head_hexsha": "55610dd9d48f6598cb31de6bc9a913b845c62727", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/finite_difference.cc", "max_forks_repo_name": "EPTlib/eptlib", "max_forks_repo_head_hexsha": "55610dd9d48f6598cb31de6bc9a913b845c62727", "max_forks_repo_licenses": ["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.7019230769, "max_line_length": 241, "alphanum_fraction": 0.5893740589, "num_tokens": 3962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5014016290198995}}
{"text": "#include \"../r1_proof.h\"\n#include \"../r1_proof_generator.h\"\n#include \"../sigma_primitives.h\"\n\n#include \"../../test/test_bitcoin.h\"\n\n#include <boost/test/unit_test.hpp>\n\nusing  namespace secp_primitives;\nusing  namespace sigma;\n\nnamespace {\n\nstruct sigma_unit_tests_fixture {\n    // struct sigma_unit_tests_fixture : public TestingSetup {\n    // sigma_unit_tests_fixture() = default;\n    int N;\n    int n;\n    int m;\n    int index;\n    GroupElement g;\n    std::vector<GroupElement> h_gens;\n    Scalar rB;\n    std::vector <Scalar> sigma;\n    std::unique_ptr<R1ProofGenerator<Scalar, GroupElement>> r1prover;\n    R1Proof<Scalar, GroupElement> r1proof;\n    Scalar x;\n    std::vector <std::vector<Scalar>> P_i_k;\n    std::vector<Scalar> f_;\n    std::vector<Scalar> a;\n    std::vector <Scalar> Pk;\n    secp_primitives::Scalar r;\n    std::vector<secp_primitives::GroupElement> commits;\n\n    sigma_unit_tests_fixture() {\n        // sigma_unit_tests_fixture() : TestingSetup(CBaseChainParams::REGTEST) {\n        N = 16;\n        n = 4;\n        index = 13;\n        m = (int)(log(N) / log(n));\n        g.randomize();\n\n        for(int i = 0; i < n * m; ++i ){\n            h_gens.push_back(secp_primitives::GroupElement());\n            h_gens[i].randomize();\n        }\n        rB.randomize();\n        SigmaPrimitives<Scalar,GroupElement>::convert_to_sigma(index, n, m, sigma);\n        r1prover.reset(new R1ProofGenerator<Scalar, GroupElement>(g, h_gens, sigma, rB, n, m));\n\n        Pk.resize(m);\n        for (int k = 0; k < m; ++k) {\n            Pk[k].randomize();\n        }\n        r.randomize();\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<Scalar,GroupElement>::commit(g, zero, h_gens[0], r);\n                commits.push_back(c);\n            }\n            else{\n                commits.push_back(secp_primitives::GroupElement());\n                commits[i].randomize();\n            }\n        }\n        (*r1prover).proof(a, r1proof);\n        x = (*r1prover).x_;\n        P_i_k.resize(N);\n        for (int i = 0; i < N; ++i) {\n            std::vector <Scalar>& coefficients = P_i_k[i];\n            std::vector<uint64_t> I = SigmaPrimitives<Scalar,GroupElement>::convert_to_nal(i, n, m);\n            coefficients.push_back(sigma[I[0]]);\n            coefficients.push_back(a[I[0]]);\n            for (int j = 1; j < m; ++j) {\n                SigmaPrimitives<Scalar,GroupElement>::new_factor(sigma[j * n + I[j]], a[j * n + I[j]], coefficients);\n            }\n            std::reverse(coefficients.begin(), coefficients.end());\n        }\n        f_ = r1proof.f_;\n        std::vector<Scalar> f;\n        for(int j = 0; j < m; ++j){\n            f.push_back(sigma[j * n] * x + a[j * n]);\n            int k = n - 1;\n            for(int i = 0; i < k; ++i){\n                f.push_back(r1proof.f_[j * k + i]);\n            }\n        }\n        f_= f;\n    }\n\n    ~sigma_unit_tests_fixture(){}\n};\n\nBOOST_FIXTURE_TEST_SUITE(sigma_unit_tests,sigma_unit_tests_fixture)\n\nBOOST_AUTO_TEST_CASE(unit_f_and_p_x)\n{\n    for(int i = 0; i < N; ++i){\n        std::vector<uint64_t> I = SigmaPrimitives<Scalar,GroupElement>::convert_to_nal(i, n, m);\n        Scalar f_i(uint64_t(1));\n        Scalar p_i_x(uint64_t(0));\n        for(int j = 0; j < m; ++j){\n            f_i *= f_[j*n + I[j]];\n            p_i_x += (P_i_k[i][j]*x.exponent(j));\n        }\n        if(i==index)\n            p_i_x += (P_i_k[i][m]*x.exponent(m));\n        BOOST_CHECK(f_i==p_i_x);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(unit_commits)\n{\n    Scalar z;\n    z = r * x.exponent(uint64_t(m));\n    Scalar sum;\n    Scalar x_k(uint64_t(1));\n    for (int k = 0; k < m; ++k) {\n        sum += (Pk[k] * x_k);\n        x_k *= x;\n    }\n    z -= sum;\n    GroupElement coommit = SigmaPrimitives<Scalar,GroupElement>::commit(g, Scalar(uint64_t(0)), h_gens[0], z);\n    GroupElement commits_;\n    for(int k = 0; k< m; ++k){\n        commits_ += (SigmaPrimitives<Scalar,GroupElement>::commit(\n                g, Scalar(uint64_t(0)), h_gens[0], Pk[k])) * (x.exponent(k)).negate();\n    }\n    commits_ += (commits[index] * x.exponent(m));\n\n    BOOST_CHECK(coommit == commits_);\n}\n\nBOOST_AUTO_TEST_CASE(unit_G_k_prime)\n{\n    std::vector<Scalar> f_i_;\n    for(int i = 0; i < N; ++i){\n        std::vector<uint64_t> I = SigmaPrimitives<Scalar,GroupElement>::convert_to_nal(i, n, m);\n        Scalar f_i(uint64_t(1));\n        for(int j = 0; j < m; ++j){\n            f_i *= f_[j*n + I[j]];\n        }\n        f_i_.push_back(f_i);\n    }\n\n    secp_primitives::MultiExponent mult(commits, f_i_);\n    GroupElement C = mult.get_multiple();\n\n    GroupElement G;\n    for(int k = 0; k < m; ++k){\n        GroupElement Gk_prime;\n        for(int i = 0; i < N; ++i)\n            Gk_prime += commits[i] * P_i_k[i][k];\n            G += (Gk_prime)* ((x.exponent(k)).negate());\n    }\n    BOOST_CHECK((C + G) == (commits[index] * (x.exponent(m))));\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n}\n", "meta": {"hexsha": "8a1abbd5f01dcc14db47154e302eb6206259e952", "size": 5022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sigma/test/unit_tests.cpp", "max_stars_repo_name": "Beekers-McCluer/NixCore", "max_stars_repo_head_hexsha": "e62cdcd5ac8a089948e9a22e6a3a60d139cb1e4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2018-06-27T22:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-21T01:18:15.000Z", "max_issues_repo_path": "src/sigma/test/unit_tests.cpp", "max_issues_repo_name": "Beekers-McCluer/NixCore", "max_issues_repo_head_hexsha": "e62cdcd5ac8a089948e9a22e6a3a60d139cb1e4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-27T12:43:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T22:23:36.000Z", "max_forks_repo_path": "src/sigma/test/unit_tests.cpp", "max_forks_repo_name": "Beekers-McCluer/NixCore", "max_forks_repo_head_hexsha": "e62cdcd5ac8a089948e9a22e6a3a60d139cb1e4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2018-06-27T16:07:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-21T21:10:38.000Z", "avg_line_length": 30.6219512195, "max_line_length": 117, "alphanum_fraction": 0.5477897252, "num_tokens": 1431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5013618211708286}}
{"text": "/*\nCopyright (c) 2020 Inverse Palindrome\nProceduralX - ECS/SteeringBehaviors.cpp\nhttps://inversepalindrome.com/\n*/\n\n\n#include \"ECS/SteeringBehaviors.hpp\"\n#include \"App/Random.hpp\"\n#include \"App/Constants.hpp\"\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n\n\nb2Vec2 ECS::SteeringBehaviors::move(const b2Vec2& bodyPosition, Direction direction, const b2Vec2& bodyVelocity, float acceleration, float maxSpeed, float mass)\n{\n    switch (direction)\n    {\n    case Direction::Up:\n        return { 0.f, mass * (b2Min(bodyVelocity.y + acceleration, maxSpeed) - bodyVelocity.y) };\n    case Direction::Down:\n        return { 0.f, mass * (b2Max(bodyVelocity.y - acceleration, -maxSpeed) - bodyVelocity.y) };\n    case Direction::Right:\n        return { mass * (b2Min(bodyVelocity.x + acceleration, maxSpeed) - bodyVelocity.x), 0.f };\n    case Direction::Left:\n        return { mass * (b2Max(bodyVelocity.x - acceleration, -maxSpeed) - bodyVelocity.x), 0.f };\n    default:\n        return { 0.f, 0.f };\n    }\n}\n\nb2Vec2 ECS::SteeringBehaviors::seek(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, const b2Vec2& bodyVelocity, float maxSpeed)\n{\n    return desiredVelocity(bodyPosition, targetPosition, maxSpeed) - bodyVelocity;\n}\n\nb2Vec2 ECS::SteeringBehaviors::flee(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, const b2Vec2& bodyVelocity, float maxSpeed)\n{\n    return desiredVelocity(targetPosition, bodyPosition, maxSpeed) - bodyVelocity;\n}\n\nb2Vec2 ECS::SteeringBehaviors::pursue(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, const b2Vec2& bodyVelocity, const b2Vec2& targetVelocity, float maxSpeed)\n{\n    auto predictionFrames = (targetPosition - bodyPosition).Length() / maxSpeed;\n\n    return seek(bodyPosition, targetPosition + predictionFrames * targetVelocity, bodyVelocity, maxSpeed);\n}\n\nb2Vec2 ECS::SteeringBehaviors::evade(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, const b2Vec2& bodyVelocity, const b2Vec2& targetVelocity, float maxSpeed)\n{\n    auto predictionFrames = (targetPosition - bodyPosition).Length() / maxSpeed;\n\n    return flee(bodyPosition, targetPosition + predictionFrames * targetVelocity, bodyVelocity, maxSpeed);\n}\n\nb2Vec2 ECS::SteeringBehaviors::arrive(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, const b2Vec2& bodyVelocity, float slowRadius, float maxSpeed)\n{\n    if (auto radius = (targetPosition - bodyPosition).Length(); radius < slowRadius)\n    {\n        return seek(bodyPosition, targetPosition, bodyVelocity, maxSpeed * radius / slowRadius);\n    }\n\n    return seek(bodyPosition, targetPosition, bodyVelocity, maxSpeed);\n}\n\nb2Vec2 ECS::SteeringBehaviors::wander(const b2Vec2& bodyPosition, const b2Vec2& bodyVelocity, float wanderDistance, float wanderRadius, float wanderRate, float& wanderAngle, float maxSpeed)\n{\n    auto wanderCenter = bodyVelocity;\n    wanderCenter.Normalize();\n    wanderCenter *= wanderDistance;\n    wanderCenter += { wanderRadius* std::cos(wanderAngle), wanderRadius* std::sin(wanderAngle) };\n\n    wanderAngle += App::Random::get(-1.f, 1.f) * wanderRate;\n\n    return seek(bodyPosition, bodyPosition + wanderCenter, bodyVelocity, maxSpeed);\n}\n\nb2Vec2 ECS::SteeringBehaviors::orbit(const b2Vec2& satellitePosition, const b2Vec2& primaryPosition, const b2Vec2& bodyVelocity, float maxSpeed)\n{\n    auto radius = primaryPosition - satellitePosition;\n\n    auto steeringForce = radius.Skew();\n    steeringForce.Normalize();\n    steeringForce *= maxSpeed;\n\n    return steeringForce - bodyVelocity;\n}\n\nb2Vec2 ECS::SteeringBehaviors::alignForce(const b2Vec2& agentPosition, const std::vector<b2Vec2>& neighborVelocities, float alignmentForce)\n{\n    b2Vec2 steeringForce(0.f, 0.f);\n\n    for (const auto& neighborVelocity : neighborVelocities)\n    {\n        steeringForce += neighborVelocity;\n    }\n\n    if (!neighborVelocities.empty())\n    {\n        steeringForce *= 1.f / neighborVelocities.size();\n        steeringForce.Normalize();\n        steeringForce *= alignmentForce;\n    }\n\n    return steeringForce;\n}\n\nb2Vec2 ECS::SteeringBehaviors::cohesionForce(const b2Vec2& agentPosition, const std::vector<b2Vec2>& neighborPositions, float cohesionForce)\n{\n    b2Vec2 steeringForce(0.f, 0.f);\n\n    for (const auto& neighborPosition : neighborPositions)\n    {\n        steeringForce += neighborPosition;\n    }\n\n    if (!neighborPositions.empty())\n    {\n        steeringForce *= 1.f / neighborPositions.size();\n        steeringForce -= agentPosition;\n        steeringForce.Normalize();\n        steeringForce *= cohesionForce;\n    }\n\n    return steeringForce;\n}\n\nb2Vec2 ECS::SteeringBehaviors::separateForce(const b2Vec2& agentPosition, const std::vector<b2Vec2>& neighborPositions, float separationForce)\n{\n    b2Vec2 steeringForce(0.f, 0.f);\n\n    for (const auto& neighborPosition : neighborPositions)\n    {\n        steeringForce += neighborPosition - agentPosition;\n    }\n\n    if (!neighborPositions.empty())\n    {\n        steeringForce *= -1.f / neighborPositions.size();\n        steeringForce.Normalize();\n        steeringForce *= separationForce;\n    }\n\n    return steeringForce;\n}\n\nb2Vec2 ECS::SteeringBehaviors::desiredVelocity(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, float maxSpeed)\n{\n    auto desiredVelocity = targetPosition - bodyPosition;\n    desiredVelocity.Normalize();\n    desiredVelocity *= maxSpeed;\n\n    return desiredVelocity;\n}\n\nfloat ECS::SteeringBehaviors::face(float desiredAngle, float bodyAngle, float bodyAngularVelocity, float bodyInertia)\n{\n    auto nextAngle = bodyAngle + bodyAngularVelocity / App::FRAMES_PER_SECOND;\n    auto totalRotation = std::remainderf(desiredAngle - nextAngle, 2 * boost::math::constants::pi<float>());\n\n    return bodyInertia * totalRotation * App::FRAMES_PER_SECOND;\n}\n\nfloat ECS::SteeringBehaviors::face(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, float bodyAngle, float bodyAngularVelocity, float bodyInertia)\n{\n    auto desiredAngle = std::atan2f(targetPosition.y - bodyPosition.y, targetPosition.x - bodyPosition.x);\n\n    return face(desiredAngle, bodyAngle, bodyAngularVelocity, bodyInertia);\n}", "meta": {"hexsha": "79a29ebf31fe6c5e97d3c76645495676878c319a", "size": 6096, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ECS/SteeringBehaviors.cpp", "max_stars_repo_name": "InversePalindrome/ProceduralX", "max_stars_repo_head_hexsha": "f53d734970be4300f06db295d25e1a012b1a8fd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-06T14:39:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T08:27:54.000Z", "max_issues_repo_path": "src/ECS/SteeringBehaviors.cpp", "max_issues_repo_name": "InversePalindrome/ProceduralX", "max_issues_repo_head_hexsha": "f53d734970be4300f06db295d25e1a012b1a8fd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ECS/SteeringBehaviors.cpp", "max_forks_repo_name": "InversePalindrome/ProceduralX", "max_forks_repo_head_hexsha": "f53d734970be4300f06db295d25e1a012b1a8fd9", "max_forks_repo_licenses": ["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.649122807, "max_line_length": 189, "alphanum_fraction": 0.7326115486, "num_tokens": 1536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.501355219441643}}
{"text": "#include <boost/graph/minimum_degree_ordering.hpp>\n", "meta": {"hexsha": "6e4ef7a9f8094ef53bd08f91c816058eb469d0a8", "size": 51, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_graph_minimum_degree_ordering.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_graph_minimum_degree_ordering.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_graph_minimum_degree_ordering.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.5, "max_line_length": 50, "alphanum_fraction": 0.8431372549, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5013326381533496}}
{"text": "#include \"evaluation.h\"\n#include \"predeal.h\"\n#include <boost/graph/graph_concepts.hpp>\n\nusing namespace std;\n\n\nEigen::Vector3f posediff(const Eigen::Vector3f& x, const Eigen::Vector3f &y)\n{\n  Eigen::Vector3f v;\n  v(0)=abs(x(0)-y(0));\n  v(1)=abs(x(1)-y(1));\n  float x2,y2;\n  if(x(2)<0)\n  {\n    x2=2*M_PI+x(2);\n  }\n  else\n  {\n    x2=x(2);\n  }\n  if(y(2)<0)\n  {\n    y2=2*M_PI+y(2);\n  }\n  else\n  {\n    y2=y(2);\n  }\n  v(2)=abs(x2-y2);\n  return v;\n}\n\nint main()\n{\n   string posedir=\"/home/shaoan/projects/slamEvaluation/data/rgspose.txt\";\n  vector<Eigen::Vector3f> v_pose;\n\n  predeal::readposefile(posedir,v_pose);\n  string maposedir=\"/home/shaoan/projects/slamEvaluation/data/maPose.txt\";\n  vector<Eigen::Vector3f> v_mapose;\n\n  predeal::readposefile(maposedir,v_mapose);\n\n assert(v_mapose.size()==v_pose.size());\n assert(v_pose.size()>0);\n \n     vector<Eigen::Vector3f> differnce;\n     for(int i=0;i<v_pose.size();i++)\n     {\n       Eigen::Vector3f v;\n       v=posediff(v_mapose[i],v_pose[i]);\n       //v=v_mapose[i]-v_pose[i];\n       //cout<<v<<endl;\n       differnce.push_back(v);\n    }\n\n    \n    evaluation eval(differnce);\n    Eigen::Vector2f v2;\n   v2= eval.computeMSE();   \n   cout<<\"\u5e73\u5747\u7edd\u5bf9\u8bef\u5dee\uff1a\"<<endl;\n   cout<<v2<<endl;\n   Eigen::Vector3f v3;\n   v3=eval.computeMAE();\n  cout<<\"\u5e73\u5747\u7edd\u5bf9\u8bef\u5dee\uff1a\"<<endl;\n  cout<<v3<<endl; \n    \n}\n\n", "meta": {"hexsha": "fb7dad20419385dd772d5887943c8b1263d4334e", "size": 1319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "evaluate.cpp", "max_stars_repo_name": "zoumaguanxin/slamEvaluation", "max_stars_repo_head_hexsha": "2ef824291db7c826cb193d31086057cd4d8b07d7", "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": "evaluate.cpp", "max_issues_repo_name": "zoumaguanxin/slamEvaluation", "max_issues_repo_head_hexsha": "2ef824291db7c826cb193d31086057cd4d8b07d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "evaluate.cpp", "max_forks_repo_name": "zoumaguanxin/slamEvaluation", "max_forks_repo_head_hexsha": "2ef824291db7c826cb193d31086057cd4d8b07d7", "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.5774647887, "max_line_length": 76, "alphanum_fraction": 0.606520091, "num_tokens": 470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5013326262420047}}
{"text": "#include <random>\n#include \"Eigen/Dense\"\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n#include \"scalar-typedef.hpp\"\n\n#include \"shared-probability-distributions.hpp\"\n\n#ifndef M_PI\n    #define M_PI 3.14159265358979323846\n#endif\n\nusing namespace Eigen;\n\n// Explicit template instantiation(s)\ntemplate double lpdf_imulti_normal(const Eigen::Matrix<double,Eigen::Dynamic,1> &x,\n                            const Eigen::Matrix<double,Eigen::Dynamic,1> &meanVec,\n                            const Eigen::Matrix<double,Eigen::Dynamic,1> &sdVec);\n\ntemplate double lpdf_imulti_lognormal(const Eigen::Matrix<double,Eigen::Dynamic,1> &x,\n                            const Eigen::Matrix<double,Eigen::Dynamic,1> &meanVec,\n                                      const Eigen::Matrix<double,Eigen::Dynamic,1> &sdVec,\n                                      unsigned int & ifail);\n\n#ifdef USE_DCO_TYPES\ntemplate gt1s_scalar lpdf_imulti_normal(const Eigen::Matrix<gt1s_scalar,Eigen::Dynamic,1> &x,\n                            const Eigen::Matrix<gt1s_scalar,Eigen::Dynamic,1> &meanVec,\n                            const Eigen::Matrix<gt1s_scalar,Eigen::Dynamic,1> &sdVec);\ntemplate ga1s_scalar lpdf_imulti_normal(const Eigen::Matrix<ga1s_scalar,Eigen::Dynamic,1> &x,\n                            const Eigen::Matrix<ga1s_scalar,Eigen::Dynamic,1> &meanVec,\n                            const Eigen::Matrix<ga1s_scalar,Eigen::Dynamic,1> &sdVec);\ntemplate gt2s_ga1s_scalar lpdf_imulti_normal(const Eigen::Matrix<gt2s_ga1s_scalar,Eigen::Dynamic,1> &x,\n                            const Eigen::Matrix<gt2s_ga1s_scalar,Eigen::Dynamic,1> &meanVec,\n                            const Eigen::Matrix<gt2s_ga1s_scalar,Eigen::Dynamic,1> &sdVec);\n\ntemplate gt1s_scalar lpdf_imulti_lognormal(const Eigen::Matrix<gt1s_scalar,Eigen::Dynamic,1> &x,\n                                           const Eigen::Matrix<gt1s_scalar,Eigen::Dynamic,1> &meanVec,\n                                           const Eigen::Matrix<gt1s_scalar,Eigen::Dynamic,1> &sdVec,\n                                           unsigned int & ifail);\ntemplate ga1s_scalar lpdf_imulti_lognormal(const Eigen::Matrix<ga1s_scalar,Eigen::Dynamic,1> &x,\n                            const Eigen::Matrix<ga1s_scalar,Eigen::Dynamic,1> &meanVec,\n                                           const Eigen::Matrix<ga1s_scalar,Eigen::Dynamic,1> &sdVec,\n                                           unsigned int & ifail);\ntemplate gt2s_ga1s_scalar lpdf_imulti_lognormal(const Eigen::Matrix<gt2s_ga1s_scalar,Eigen::Dynamic,1> &x,\n                                                const Eigen::Matrix<gt2s_ga1s_scalar,Eigen::Dynamic,1> &meanVec,\n                                                const Eigen::Matrix<gt2s_ga1s_scalar,Eigen::Dynamic,1> &sdVec,\n                                                unsigned int & ifail);\n#endif\n\ntemplate<typename SCALAR_T>\nSCALAR_T lpdf_univariate_normal(const SCALAR_T & x, const SCALAR_T & mu, const SCALAR_T & sd)\n{\n  const SCALAR_T logSqrt2Pi = 0.5*std::log(2*M_PI);\n  const SCALAR_T z = x - mu;\n  return - logSqrt2Pi - log(sd) - 0.5 * (z * z) / (sd * sd);\n}\n\ntemplate<typename SCALAR_T>\nSCALAR_T lpdf_univariate_lognormal(const SCALAR_T & x, const SCALAR_T & mu, const SCALAR_T & sd)\n{\n  const SCALAR_T logSqrt2Pi = 0.5*std::log(2*M_PI);\n  const SCALAR_T z = log(x) - mu;\n  return -log(x) - logSqrt2Pi - log(sd) - 0.5 * (z * z) / (sd * sd);\n}\n\n\n\n\ntemplate<typename SCALAR_T>\nSCALAR_T lpdf_imulti_lognormal(const Eigen::Matrix<SCALAR_T,Eigen::Dynamic,1> &x,\n                               const Eigen::Matrix<SCALAR_T,Eigen::Dynamic,1> &meanVec,\n                               const Eigen::Matrix<SCALAR_T,Eigen::Dynamic,1> &sdVec,\n                               unsigned int & ifail)\n{\n  SCALAR_T lp = 0;\n  for (int i=0; i < x.size(); ++i){\n    if (x[i] < 0){\n      ifail = 7;\n      return - std::numeric_limits<SCALAR_T>::infinity();;\n    }\n    SCALAR_T mu = log( meanVec[i] / sqrt(1 + pow( sdVec[i] / meanVec[i] , 2.0) ) );\n    SCALAR_T log_sd = sqrt( log( 1 + pow( sdVec[i] / meanVec[i] , 2.0)  ) );\n    lp += lpdf_univariate_lognormal(x[i], mu, log_sd);\n  }\n  return lp;\n}\n\n\ntemplate<typename SCALAR_T>\nSCALAR_T lpdf_imulti_normal(const Eigen::Matrix<SCALAR_T,Eigen::Dynamic,1> &x,\n                            const Eigen::Matrix<SCALAR_T,Eigen::Dynamic,1> &meanVec,\n                            const Eigen::Matrix<SCALAR_T,Eigen::Dynamic,1> &sdVec)\n{\n  SCALAR_T lp = 0;\n  for (int i=0; i < x.size(); ++i){\n    lp += lpdf_univariate_normal(x[i], meanVec[i], sdVec[i]);\n  }\n  return lp;\n}\n\n// downloaded from https://stackoverflow.com/questions/41538095/evaluate-multivariate-normal-gaussian-density-in-c\ndouble lpdf_multi_normal(const Eigen::VectorXd &x, const Eigen::VectorXd &meanVec,\n                         const Eigen::MatrixXd &covMat)\n{\n    // avoid magic numbers in your code. Compilers will be able to compute this at compile time:\n    const double logSqrt2Pi = 0.5*std::log(2*M_PI);\n    typedef Eigen::LLT<Eigen::MatrixXd> Chol;\n    Chol chol(covMat);\n    // Handle non positive definite covariance somehow:\n    if(chol.info()!=Eigen::Success) throw \"decomposition failed!\";\n    const Chol::Traits::MatrixL& L = chol.matrixL();\n    Eigen::VectorXd centredVec = (x - meanVec);\n    // solve  L y = (x - mu) for y\n    double quadform = (L.solve(centredVec)).squaredNorm();\n    // log(|Sigma|^{-1/2} = - 0.5 log( |Sigma| )\n    return -x.rows()*logSqrt2Pi - 0.5*quadform - 0.5 * covMat.colPivHouseholderQr().logAbsDeterminant() ;\n}\n\n// Note - this is not an optimal implementation if generating many samples from dist with the same covariance matrix\nMatrix<double,Dynamic,1> rand_multi_normal(const Matrix<double,Dynamic,1> mean,\n                                           Matrix<double,Dynamic,Dynamic> cov,\n                                           std::mt19937 & gen)\n{\n  std::normal_distribution<> std_normal_rng;\n  Eigen::LLT<Eigen::MatrixXd> llt_of_cov = cov.llt();\n  Eigen::VectorXd z(cov.cols());\n  for (int i = 0; i < cov.cols(); ++i){\n    z(i) = std_normal_rng(gen);\n  }\n  MatrixXd L = llt_of_cov.matrixL();\n  return mean + L  * z;\n}\n\n// Adapted from https://stackoverflow.com/questions/41538095/evaluate-multivariate-normal-gaussian-density-in-c\n#undef MYPREC_VERSION\n#ifdef MYPREC_VERSION\ndouble lpdf_multi_normal(const Eigen::VectorXd &x, const Eigen::VectorXd &meanVec, const Eigen::MatrixXd &precMat)\n{\n    // avoid magic numbers in your code. Compilers will be able to compute this at compile time:\n    // const double logSqrt2Pi = 0.5*std::log(2*M_PI);\n    typedef Eigen::LLT<Eigen::MatrixXd> llt_of_prec;\n    llt_of_prec chol(precMat);\n    // Handle non positive definite covariance somehow:\n    if(chol.info()!=Eigen::Success) throw \"decomposition failed!\";\n    const llt_of_prec::Traits::MatrixL& L = chol.matrixL();\n    double quadform = (L * (x - meanVec)).squaredNorm();\n    // return std::exp(-x.rows()*logSqrt2Pi - 0.5*quadform) / L.determinant();\n    return - 0.5*quadform +  0.5 * precMat.colPivHouseholderQr().logAbsDeterminant();\n}\n#endif\n\n\n#undef STACKOVERFLOW_VERSION\n#ifdef STACKOVERFLOW_VERSION\n// From https://stackoverflow.com/questions/6142576/sample-from-multivariate-normal-gaussian-distribution-in-c\n// October 2019\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#endif\n\n#undef MY_COV_VERSION\n#ifdef MY_COV_VERSION\n// Note - this is less efficient than stackoverflow version if generating many samples from dist with the same covariance matrix\nMatrix<double,Dynamic,1> rand_multi_normal(const Matrix<double,Dynamic,1> mean,\n                                           Matrix<double,Dynamic,Dynamic> covar,\n                                           std::mt19937 & gen,\n                                           std::normal_distribution<> & dist)\n{\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigenSolver(covar);\n  Matrix<double,Dynamic,Dynamic> transform m= eigenSolver.eigenvectors() * eigenSolver.eigenvalues().cwiseSqrt().asDiagonal();\n  return mean + transform * Eigen::VectorXd{ mean.size() }.unaryExpr([&](double x) { return dist(gen); });\n}\n#endif\n\n#undef STAN_PREC_VERSION\n#ifdef STAN_PREC_VERSION\n// From https://mc-stan.org/math/d4/d28/multi__normal__prec__rng_8hpp_source.html\n// October 2019\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/mat/err/check_pos_definite.hpp>\n#include <stan/math/prim/mat/err/check_symmetric.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_positive.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template <typename T_loc, class RNG>\n    inline typename StdVectorBuilder<true, Eigen::VectorXd, T_loc>::type\n    multi_normal_prec_rng(const T_loc &mu, const Eigen::MatrixXd &S, RNG &rng) {\n      using boost::normal_distribution;\n      using boost::variate_generator;\n\n      static const char *function = \"multi_normal_prec_rng\";\n\n      check_positive(function, \"Precision matrix rows\", S.rows());\n      check_finite(function, \"Precision matrix\", S);\n      check_symmetric(function, \"Precision matrix\", S);\n\n      Eigen::LLT<Eigen::MatrixXd> llt_of_S = S.llt();\n      check_pos_definite(function, \"precision matrix argument\", llt_of_S);\n\n      vector_seq_view<T_loc> mu_vec(mu);\n      check_positive(function, \"number of location parameter vectors\",\n                     mu_vec.size());\n      size_t size_mu = mu_vec[0].size();\n\n      size_t N = mu_vec.size();\n\n      for (size_t i = 1; i < N; i++) {\n        int size_mu_new = mu_vec[i].size();\n        check_size_match(function,\n                         \"Size of one of the vectors of \"\n                         \"the location variable\",\n                         size_mu_new,\n                         \"Size of another vector of the \"\n                         \"location variable\",\n                         size_mu);\n      }\n\n      for (size_t i = 0; i < N; i++) {\n        check_finite(function, \"Location parameter\", mu_vec[i]);\n      }\n\n      check_size_match(function, \"Rows of location parameter\", size_mu, \"Rows of S\",\n                       S.rows());\n\n      StdVectorBuilder<true, Eigen::VectorXd, T_loc> output(N);\n\n      variate_generator<RNG &, normal_distribution<>> std_normal_rng(\n                                                                     rng, normal_distribution<>(0, 1));\n\n      for (size_t n = 0; n < N; ++n) {\n        Eigen::VectorXd z(S.cols());\n        for (int i = 0; i < S.cols(); i++)\n          z(i) = std_normal_rng();\n\n        output[n] = Eigen::VectorXd(mu_vec[n]) + llt_of_S.matrixU().solve(z);\n      }\n\n      return output.data();\n    }\n\n  }  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "3578787989f9a6f4d66cd7e6893d85c0c18ba7f3", "size": 11472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/shared-probability-distributions.cpp", "max_stars_repo_name": "p-maybank/bayesian-uq", "max_stars_repo_head_hexsha": "5e3b34aaf33512d94fd417238df5582b3a89170b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-03T22:53:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-03T22:53:53.000Z", "max_issues_repo_path": "source/shared-probability-distributions.cpp", "max_issues_repo_name": "p-maybank/bayesian-uq", "max_issues_repo_head_hexsha": "5e3b34aaf33512d94fd417238df5582b3a89170b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/shared-probability-distributions.cpp", "max_forks_repo_name": "p-maybank/bayesian-uq", "max_forks_repo_head_hexsha": "5e3b34aaf33512d94fd417238df5582b3a89170b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-03T22:57:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T13:29:54.000Z", "avg_line_length": 41.8686131387, "max_line_length": 128, "alphanum_fraction": 0.6268305439, "num_tokens": 2963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959545, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5013326210256125}}
{"text": "#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <cmath>\n#include <vector>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/assign/list_of.hpp>\nusing boost::assign::list_of;\nusing boost::assign::map_list_of;\n\n#include <evaluation/core/PerformanceMeasureUtil.h>\nusing namespace evaluation;\n\n#include <tvgutil/containers/MapUtil.h>\nusing namespace tvgutil;\n\n//#################### TESTS ####################\n\nBOOST_AUTO_TEST_SUITE(test_PerformanceMeasureUtil)\n\nBOOST_AUTO_TEST_CASE(average_measures_test)\n{\n  const float TOL = 1e-5f;\n\n  #define CHECK_CLOSE(L,R) BOOST_CHECK_CLOSE(L,R,TOL)\n\n  PerformanceMeasure m1 = PerformanceMeasureUtil::average_measures(list_of(1.0f)(2.0f)(3.0f));\n  CHECK_CLOSE(m1.get_mean(), 2.0f);\n  BOOST_CHECK_EQUAL(m1.get_sample_count(), 3);\n  CHECK_CLOSE(m1.get_std_dev(), sqrtf(2.0f/3.0f));\n  CHECK_CLOSE(m1.get_variance(), 2.0f/3.0f);\n\n  PerformanceMeasure m2 = PerformanceMeasureUtil::average_measures(list_of(4.0f)(5.0f));\n  CHECK_CLOSE(m2.get_mean(), 4.5f);\n  BOOST_CHECK_EQUAL(m2.get_sample_count(), 2);\n  CHECK_CLOSE(m2.get_std_dev(), 0.5f);\n  CHECK_CLOSE(m2.get_variance(), 0.25f);\n\n  PerformanceMeasure avg = PerformanceMeasureUtil::average_measures(list_of(m1)(m2));\n  CHECK_CLOSE(avg.get_mean(), 3.0f);\n  BOOST_CHECK_EQUAL(avg.get_sample_count(), 5);\n  CHECK_CLOSE(avg.get_std_dev(), sqrtf(2.0f));\n  CHECK_CLOSE(avg.get_variance(), 2.0f);\n\n  #undef CHECK_CLOSE\n}\n\nBOOST_AUTO_TEST_CASE(average_results_test)\n{\n  PerformanceResult r1 = map_list_of(\"A\",1.0f)(\"B\",2.0f);\n  PerformanceResult r2 = map_list_of(\"A\",2.0f)(\"B\",1.0f);\n  PerformanceResult r3 = map_list_of(\"C\",3.0f);\n\n  std::vector<PerformanceResult> results = list_of(r1)(r2)(r3);\n  PerformanceResult rAvg = PerformanceMeasureUtil::average_results(results);\n\n  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(MapUtil::lookup(rAvg, \"A\")),\"1.5 +/- 0.5 (2 samples)\");\n  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(MapUtil::lookup(rAvg, \"B\")),\"1.5 +/- 0.5 (2 samples)\");\n  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(MapUtil::lookup(rAvg, \"C\")),\"3 +/- 0 (1 samples)\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4d09093057f743d1e47c2a9a04f294479a393436", "size": 2129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/evaluation/test_PerformanceMeasureUtil.cpp", "max_stars_repo_name": "torrvision/spaint", "max_stars_repo_head_hexsha": "9cac8100323ea42fe439f66407b832b88f72d2fd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 197.0, "max_stars_repo_stars_event_min_datetime": "2015-10-01T07:23:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T03:02:31.000Z", "max_issues_repo_path": "tests/unit/evaluation/test_PerformanceMeasureUtil.cpp", "max_issues_repo_name": "GucciPrada/spaint", "max_issues_repo_head_hexsha": "b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2016-03-26T13:01:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T09:13:49.000Z", "max_forks_repo_path": "tests/unit/evaluation/test_PerformanceMeasureUtil.cpp", "max_forks_repo_name": "GucciPrada/spaint", "max_forks_repo_head_hexsha": "b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2015-10-03T07:14:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T08:58:18.000Z", "avg_line_length": 33.265625, "max_line_length": 108, "alphanum_fraction": 0.7289807421, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5013326210256124}}
{"text": "\n/* \n * Tsai algorithm 1989, initially ported to Eigen from VISP and then manually modified for efficiency, clearness and more Eigenability\n * \n * Copyright Scuola Superiore Sant'Anna (2016) \n * Emanuele Ruffaldi, e.ruffaldi@sssup.it\n *\n * TODO: exclude collinear pairs\n * TODO: compute residuals for providing a measure of the error \n * \n * Structure optimization (double the memory but faster)\n *    A1,A2,b1,b2,tmp\n *    loop all pairs\n *      exclude bad pairs\n *      write A1 and A2\n *      write b1 and partial b2 the part that doesn't require Rcg\n *    solve Rcg using A1,b1\n *    update b2 using eRcg*cijo.matrix().template block<3,1>(0,3) (so we need to store cijo translation part into tmp)\n *    solve translation for A2,b2\n */\n#include <Eigen/Dense>\n#include <vector>\n#include <iostream>\n#include \"tsai.hpp\"\n\n\n\n/// extracts the translation part\ntemplate <class T>\nstatic Vector3<T> gettx(const Matrix4<T> & x)\n{\n  return x.template block<3,1>(0,3);\n}\n\n/// extracts the translation part\ntemplate <class T>\nstatic Vector3<T> gettx(const Eigen::Transform<T,3,Eigen::Affine> & x)\n{\n  return x.matrix().template block<3,1>(0,3);\n}\n\n/// extracts rotation\ntemplate <class T>\nstatic Matrix3<T> getrot(const Eigen::Transform<T,3,Eigen::Affine> & x)\n{\n  return x.matrix().template block<3,3>(0,0);\n}\n\n/// extracts rotation\ntemplate <class T>\nstatic Matrix3<T> getrot(const Matrix4<T> & x)\n{\n  return x.template block<3,3>(0,0);\n}\n\n/// extracts quat and transform from matrix 4x4\ntemplate <class T>\nstatic void extract(const Matrix4<T> & x,Eigen::Quaternion<T> & q, Vector3<T> & t)\n{\n  q = x.template block<3,3>(0,0);\n  t = x.template block<3,1>(0,3);\n}\n\n/// extract rotation\ntemplate <class T>\nstatic void extract(const Matrix4<T> & x,Eigen::Quaternion<T> & q)\n{\n  q = x.template block<3,3>(0,0);\n}\n\n/// makes affine3f from matrix using extraction\ntemplate <class T>\nstatic void extract(const Matrix4<T> & x,Eigen::Transform<T,3,Eigen::Affine> & a)\n{\n  auto q = x.template block<3,3>(0,0);\n  auto t = x.template block<3,1>(0,3);\n  a.fromPositionOrientationScale(t,q,Vector3<T>(1,1,1));\n}\n\n\n\n\ntemplate <class T>\nstatic inline T sinc(T sx,T x)\n{\n  return fabs(x) < 1e-8 ? 1 : sx/x;\n}\n\ntemplate <class T>\nstatic inline T sinc(T x)\n{\n  return fabs(x) < 1e-8 ? 1 : sin(x)/x;\n}\n\n// modified tsai is: 2 sin(theta/2) axis\n// BUT quaternion real part is:  sin(theta/2) * axis\n// equation 9\n// THIS IS FROM VISP\ntemplate <class T>\nVector3<T> quat2paratsai(const Eigen::Quaternion<T> & q)\n{\n  //Eigen::AngleAxisf aa(q);\n  //return 2*sin(aa.angle()/2)*aa.axis();\n  //return 2*Vector3<T>(q.x(),q.y(),q.z()); \n  const double minimum = 0.0001;\n  Matrix3<T> R(q);\n  Vector3<T> r;\n\n  double s = (R(1,0)-R(0,1))*(R(1,0)-R(0,1))\n    + (R(2,0)-R(0,2))*(R(2,0)-R(0,2))\n    + (R(2,1)-R(1,2))*(R(2,1)-R(1,2));\n   s = sqrt(s)/2.0;\n   double c = (R(0,0)+R(1,1)+R(2,2)-1.0)/2.0;\n   double theta=atan2(s,c);  /* theta in [0, PI] since s > 0 */\n\n  // General case when theta != pi. If theta=pi, c=-1\n  if ( (1+c) > minimum) // Since -1 <= c <= 1, no fabs(1+c) is required\n  {\n    double si = sinc(s,theta);\n\n    r[0] = (R(2,1)-R(1,2))/(2*si);\n    r[1] = (R(0,2)-R(2,0))/(2*si);\n    r[2] = (R(1,0)-R(0,1))/(2*si);\n  }\n  else /* theta near PI */\n  {\n    if ( (R(0,0)-c) < std::numeric_limits<double>::epsilon() )\n      r[0] = 0.;\n    else\n      r[0] = theta*(sqrt((R(0,0)-c)/(1-c)));\n    if ((R(2,1)-R(1,2)) < 0) r[0] = -r[0];\n\n    if ( (R(1,1)-c) < std::numeric_limits<double>::epsilon() )\n      r[1] = 0.;\n    else\n      r[1] = theta*(sqrt((R(1,1)-c)/(1-c)));\n\n    if ((R(0,2)-R(2,0)) < 0) r[1] = -r[1];\n\n    if ( (R(2,2)-c) < std::numeric_limits<double>::epsilon() )\n      r[2] = 0.;\n    else\n      r[2] = theta*(sqrt((R(2,2)-c)/(1-c)));\n\n    if ((R(1,0)-R(0,1)) < 0) r[2] = -r[2];\n  }\n  return r;\n\n}\n\n\ntemplate <class T>\nT paratsaiprime2theta(const Vector3<T> & x)\n{\n  return 2*atan(x.norm()); // eq. 13\n}\n\n\n// port and improve: https://github.com/thomas-moulard/visp-deb/blob/master/src/camera/calibration/vpCalibrationTools.cpp\ntemplate<class T>\nT calibrationTsaiT(const std::vector<Matrix4<T> > & cMo,const std::vector<Matrix4<T> > & rMe, Matrix4<T> &eMc, bool computeResidual)\n{\n  assert(cMo.size() == rMe.size() && !cMo.empty() && \"not empty calibration matrices\");\n  const unsigned int nbPose = cMo.size();\n  Vector3<T> x; // tsaipara result\n  Eigen::Matrix<T,Eigen::Dynamic,3> A((nbPose*(nbPose-1)/2)*3,3); // reused between the two loops over all pairs\n  Eigen::Matrix<T,Eigen::Dynamic,1> B(A.rows(),1);\n  {\n    unsigned int k = 0 ;\n    // for all couples ij\n    for (unsigned int i=0 ; i < nbPose ; i++)\n    {\n      Eigen::Quaternion<T> eiR,ioR;\n      extract(rMe[i],eiR);\n      extract(cMo[i],ioR);\n\n      for (unsigned int j=i+1; j < nbPose ; j++, k+= 3)\n      {\n          Eigen::Quaternion<T> ejR,joR;\n          extract(rMe[j],ejR);\n          extract(cMo[j],joR);\n\n          Eigen::Quaternion<T> rRgij = ejR.conjugate() * eiR;\n          Eigen::Quaternion<T>  cRijo = joR * ioR.conjugate();\n\n          // CODE: theta = sqrt(|rotationalpart of rRgij|) then multiply rotation part by sinc(theta/2)\n          // going from norm theta to scaled by sinc\n\n          // rotation axis (eq 11a,11b,11c)\n          Vector3<T>  rPgij = quat2paratsai<T>(rRgij);\n          Vector3<T>  cPijo = quat2paratsai<T>(cRijo);\n\n          // TODO: in paper we can remove pair if not good\n\n          // skewtsai(Pgij+Pcij) Pcg' = Pcij - Pgij  equation 12\n          A.template block<3,3>(k,0) = skewtsai(Vector3<T>(rPgij + cPijo)) ;\n          B.template block<3,1>(k,0) = cPijo - rPgij;       \n\n#if 0\n          if(k == 0)\n          {            \n            std::cout << \"rPeij0 R\\n\" << Matrix3<T>(rRgij) << std::endl;\n            std::cout << \"rPeij0\\n\" << rPgij.transpose() << std::endl;\n            std::cout << \"rPeij0\\n\" << Eigen::AngleAxisf(rRgij).angle() << \"|\" << Eigen::AngleAxisf(rRgij).axis() << std::endl;\n            std::cout << \"cijPo\\n\" << cPijo.transpose() << std::endl;\n\n            std::cout << \"As0\\n \" << A.template block<3,3>(0,0) << \" \\n b0\" << B.template block<3,1>(0,0).transpose() << std::  endl;\n          }  \n#endif\n      }\n    }\n\n    // the output is in the MODIFIED form\n    x = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(B);\n\n    // convert output to PARAMETRIC eq. 14\n    // Pcg' = 1/(4-|Pcg|^2) Pcg\n    // Pcg  = 2 Pcg' /(1+|Pcg|^2)\n    x = paratsaiprime2paratsai(x);\n\n    // verification of the quality of the vector\n    const double theta = paratsai2theta(x); \n\n    if (std::fabs(theta) < std::numeric_limits<double>::epsilon())\n      x.setZero();\n    // x *= theta/(2*sin(theta/2));     // paratsai => para NOT NEEDED we work in paratsai\n  }\n\n  // Building of the rotation matrix eRc using eq. 10\n  Matrix3<T>  eRcg = paratsai2rot(x);\n\n  {\n    // Building of the system for the translation estimation\n    // for all couples ij\n    unsigned int k = 0 ;\n    for (unsigned int i = 0 ; i < nbPose ; i++)\n    {\n      /*\n      Eigen::Affine3f eiA,ioA;\n      extract(rMe[i],eiA);\n      extract(cMo[i],ioA);\n      */\n\n      Vector3<T>  eiT = gettx(rMe[i]);\n      Vector3<T>  ioT = gettx(cMo[i]);\n      Matrix3<T>  eiR = getrot(rMe[i]);\n\n\n      for (unsigned int j = i+1 ; j < nbPose ; j++, k+= 3)\n      {\n          /*\n          Eigen::Affine3f ejA,joA;\n          extract(rMe[j],rejA);\n          extract(cMo[j],joA);\n          Eigen::Affine3f jiA = ejA.inverse() * eiA; // gij of paper\n          */\n          Vector3<T>  ejT = gettx(rMe[j]);\n          Vector3<T> joT = gettx(cMo[j]);\n          Matrix3<T> ejR = getrot(rMe[j]);\n          Matrix3<T> jiR = ejR.transpose()*eiR;\n\n          // TODO: in paper we can remove pair if not good COLLINEARITY ISSUE\n        \n          // equation 15: (Rgij-I) T = Rcg Tcij - Tgij\n          A.template block<3,3>(k,0) = jiR-Matrix3<T>::Identity();\n          B.template block<3,1>(k,0) = eRcg*joT - jiR*eRcg*ioT + ejR.transpose()*(ejT-eiT);\n      }\n    }\n\n    eMc.setIdentity();\n    eMc.template block<3,3>(0,0) = eRcg;\n    eMc.template block<3,1>(0,3) = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(B);\n\n    // A (n*3,3) x(3,1) - B(n*3,1)\n    return computeResidual ? (A*eMc.template block<3,1>(0,3)-B).squaredNorm()/A.rows() : 0; // this is the variance of result\n }\n}\n\nfloat calibrationTsai(const std::vector<Eigen::Matrix4f> & cMo,\n                      const std::vector<Eigen::Matrix4f> & rMe,\n                      Eigen::Matrix4f &eMc,\n                      bool computeResidual)\n{\n    return calibrationTsaiT<float>(cMo,rMe,eMc,computeResidual);\n}\n\ndouble calibrationTsai(const std::vector<Eigen::Matrix4d> & cMo,\n                       const std::vector<Eigen::Matrix4d> & rMe,\n                       Eigen::Matrix4d &eMc,bool computeResidual)\n{\n    return calibrationTsaiT<double>(cMo,rMe,eMc,computeResidual);\n}\n", "meta": {"hexsha": "ef93bee44c8722f6a687684e0b73027775808c7e", "size": 8783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tsai.cpp", "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.cpp", "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.cpp", "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": 29.976109215, "max_line_length": 134, "alphanum_fraction": 0.580667198, "num_tokens": 3016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.5013326154395799}}
{"text": "#include <iostream>\n#include <cstdlib>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <complex>\n#include <chrono>\n#include <list>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iomanip>\n#include <exception>\n#include <iterator>\n#include <stdexcept>\n#include \"../Matrix.hpp\"\n\nclass Timer {\n private:\n  std::chrono::time_point<std::chrono::high_resolution_clock>\n    start_ = std::chrono::high_resolution_clock::now();\n  std::chrono::time_point<std::chrono::high_resolution_clock>\n    end_ = std::chrono::high_resolution_clock::now();\n  std::chrono::duration<double>\n    duration_ = std::chrono::duration_cast\n    <std::chrono::nanoseconds>(end_-start_);\n public:\n  void start() {\n    start_ = std::chrono::high_resolution_clock::now();\n  }\n  void stop(std::string statement) {\n    end_ = std::chrono::high_resolution_clock::now();\n    duration_ = std::chrono::duration_cast\n      <std::chrono::nanoseconds>(end_-start_);\n    std::cout << log2(duration_.count()) << \" \"+statement << std::endl;\n    start_ = std::chrono::high_resolution_clock::now();\n  }\n  double get_time() {\n    end_ = std::chrono::high_resolution_clock::now();\n    duration_ = std::chrono::duration_cast\n      <std::chrono::nanoseconds>(end_-start_);\n    return log2(duration_.count());\n  }\n};\n\ntypedef Eigen::Triplet<std::complex<double>> Tri;  \ntypedef std::vector<Tri> TriVec;\n\nvoid printMEM() {\n  auto sys = system(\"ps -eo cmd,%mem,%cpu --sort=-%mem | head -n 2 | tail -n 1\");\n}\n\nvoid print_sparse(const std::string& s,\n  const Eigen::SparseMatrix<std::complex<double>>& mat, Matrix& A) {\n  std::cout << s << std::endl;\n  for (int k=0; k<mat.outerSize(); ++k)\n    for (Eigen::SparseMatrix<std::complex<double>>::InnerIterator it(mat,k);\n      it; ++it) {\n      std::cout << it.col() << \" \" << it.row() << \" \" << it.value() << std::endl;\n    }\n    std::cout << std::endl;\n  std::cout << A.map_.to_string() << std::endl;\n}\n\nvoid\nbuild_sparse(const uint64_t& dim, const uint64_t& n, TriVec& tri_vec,\n  std::default_random_engine& rand_gen, \n  std::uniform_real_distribution<double>& urd,\n  Eigen::SparseMatrix<std::complex<double>>& m,\nMatrix& M) {\n  int sys;\n  tri_vec.resize(0);\n  try {\n    tri_vec.resize(dim*dim);\n  } catch(const std::exception& e) {\n    std::cerr << \"build_sparse->try->for->for->\"\n      << \"tri_vec.resize(dim*dim);\"\n      << std::endl;\n    std::cerr << e.what() << std::endl;\n    throw;\n  }\n  std::complex<double> v;\n  uint64_t i = 0;\n  for (uint64_t row = 0; row < dim; row++) {\n    for (uint64_t col = 0; col < dim; col++) {\n      v = std::complex<double>(urd(rand_gen), urd(rand_gen));\n      tri_vec[i]=(Tri(row,col,v));\n      i++;\n    }\n  }\n  auto it = tri_vec.begin();\n  std::advance(it,dim*dim);\n  std::shuffle(tri_vec.begin(), it, rand_gen);\n  try {\n  m.resize(dim,dim);\n  } catch(std::exception& e) {\n    std::cout << e.what() << std::endl;\n    std::cout << \"build_sparse->m.resize(dim,dim);\" << std::endl;\n    throw;\n  }\n  it = tri_vec.begin();\n  std::advance(it,n);\n  m.setFromTriplets(tri_vec.begin(), it);\n  M.map_.clear();\n  for(uint32_t i = 0; i < n; i++) {\n    M.add(tri_vec[i].col(),tri_vec[i].row(),tri_vec[i].value());\n  }\n  //print_sparse(\"m=\",m,M);\n}\n\n\nstruct keep_complex_zero {\n  bool operator() (const int& row, const int& col,\n    const std::complex<double>& val) const {\n    return false;\n  }\n};\n\nvoid dealloc_sparse(Eigen::SparseMatrix<std::complex<double>>& m) {\n  m.setZero();\n  m.prune(keep_complex_zero());\n  m.makeCompressed();\n}\n\nvoid eigen_oper_mult(const Eigen::SparseMatrix<std::complex<double>>& a,\n               const Eigen::SparseMatrix<std::complex<double>>& b,\n                     Eigen::SparseMatrix<std::complex<double>>& c) {\n  for (int k_a=0; k_a<a.outerSize(); ++k_a)\n    for (Eigen::SparseMatrix<std::complex<double>>::InnerIterator\n      it_a(a,k_a); it_a; ++it_a) {\n      for (int k_b=0; k_b<b.outerSize(); ++k_b)\n        for (Eigen::SparseMatrix<std::complex<double>>::InnerIterator\n          it_b(b,k_b); it_b; ++it_b) {\n          c.coeffRef(it_a.row()^it_b.row(), it_a.col()^it_b.col())\n            += it_a.value()*it_b.value();\n        }\n    }\n  //std::cout << c.nonZeros() << std::endl;\n}\n\ndouble compare_objects(Eigen::SparseMatrix<std::complex<double>>& c, Matrix& C) {\n  double v=0;\n  for (int k_c=0; k_c<c.outerSize(); ++k_c)\n    for (Eigen::SparseMatrix<std::complex<double>>::InnerIterator\n      it_c(c,k_c); it_c; ++it_c) {\n      v += std::abs(C.getCoeff(it_c.col(),it_c.row()) - it_c.value());\n    }\n  return v;\n}\n\nvoid test_trad_mult() {\n  Timer stop_watch;\n  std::random_device rd;\n  std::default_random_engine rand_gen(rd());\n  std::uniform_real_distribution<double> urd(-1, 1);\n  Eigen::SparseMatrix<std::complex<double>> a;\n  Eigen::SparseMatrix<std::complex<double>> b;\n  Eigen::SparseMatrix<std::complex<double>> c;\n  Matrix A;\n  Matrix B;\n  Matrix C;\n  TriVec tri_vec;\n  double exp = 2;\n  uint64_t max_qubits = 10;\n  uint64_t max_dim = 1<<max_qubits;\n  uint64_t max_n = uint64_t(pow((max_dim),exp));\n  try{\n    a.reserve(max_n);\n    b.reserve(max_n);\n    c.reserve(max_dim*max_dim);\n    tri_vec = TriVec(max_dim*max_dim);\n    tri_vec.resize(tri_vec.capacity());\n  } catch (const std::exception& e) {\n    std::cerr << e.what() << std::endl;\n    throw;\n  }\n  std::vector<double> times_mult;\n  std::vector<double> times_mult_2;\n  std::vector<double> times_alloc;\n  std::vector<double> times_build;\n  std::vector<double> a_size;\n  std::vector<double> c_size;\n  std::vector<double> times_sort;\n  std::vector<double> times_allocM;\n  std::vector<double> times_multM;\n  std::vector<double> times_mult_2M;\n  uint64_t dim;\n  uint64_t n;\n  for(uint64_t q = 1; q <= (max_qubits); q++ ) {\n    dim = (1<<q);\n    n = uint64_t(pow((dim),exp));\n    std::cout << \"q=\" << q << \" dim=\" << dim << \" n=\" << n << \" dim^2=\"\n      << dim*dim << std::endl;\n    stop_watch.start();\n    //std::cout << \"start build A\" << std::endl;\n    build_sparse(dim,n, tri_vec, rand_gen, urd, a, A);\n    //std::cout << \"start build B\" << std::endl;\n    build_sparse(dim,n, tri_vec, rand_gen, urd, b, B);\n    times_build.push_back(stop_watch.get_time());\n    //////////////////////////////////////////\n    stop_watch.start();\n    c.resize(dim,dim); //set to zero as well\n    times_alloc.push_back(stop_watch.get_time());\n    stop_watch.start();\n    c.setZero();\n    c += a*b;\n    times_mult.push_back(stop_watch.get_time());\n    c_size.push_back(log2(double(c.nonZeros())/double(dim*dim)));\n    a_size.push_back(log2(double(a.nonZeros())/double(dim*dim)));\n    stop_watch.start();\n    c.setZero();\n    c += a*b;\n    times_mult_2.push_back(stop_watch.get_time());\n    /////////////////////////////////////////////\n    stop_watch.start();\n    A.map_.sort_list(); B.map_.sort_list();\n    times_sort.push_back(stop_watch.get_time());\n    stop_watch.start();\n    C.map_.clear();\n    times_allocM.push_back(stop_watch.get_time());\n    stop_watch.start();\n    //std::cout << \"start transpose\" << std::endl;\n    A.transpose_emplace();\n    //std::cout << \"start pesABt\" << std::endl;\n    //C.pesABt(1,B,A);\n    times_multM.push_back(stop_watch.get_time());\n    stop_watch.start();\n    C.map_.clear();\n    //std::cout << \"start pesABt 2nd\" << std::endl;\n    //C.pesABt(1,B,A);\n    times_mult_2M.push_back(stop_watch.get_time());\n    ////////////////////////////////////////////////\n    printMEM();\n    std::cout << \"compare_objects(c,C)=\" << compare_objects(c,C) << std::endl;\n  }\n  \n  std::cout << std::fixed << std::setprecision(3)\n    << std::setw(6) << times_build[0] << \" \"\n    << std::setw(6) << times_alloc[0] << \" \"\n    << std::setw(6) << times_mult[0] << \" \"\n    << std::setw(6) << times_mult_2[0] << \" \"\n    << std::setw(6) << \" \"\n    << std::setw(6) << \" \"\n    << std::setw(6) << times_sort[0] << \" \"\n    << std::setw(6) << times_allocM[0] << \" \"\n    << std::setw(6) << times_multM[0] << \" \"\n    << std::setw(6) << times_mult_2M[0] << \" \"\n    << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  for (int i = 0; i < times_mult.size() - 1; i++) {\n    std::cout << std::fixed << std::setprecision(3)\n              << std::setw(6) << times_build[i+1] - times_build[i] << \" \"\n              << std::setw(6) << times_alloc[i+1] - times_alloc[i] << \" \"\n              << std::setw(6) << times_mult[i+1] - times_mult[i] << \" \"\n              << std::setw(6) << times_mult_2[i+1] - times_mult_2[i] << \" \"\n              << std::setw(6) << a_size[i] << \" \"\n              << std::setw(6) << c_size[i] << \" \"\n              << std::setw(6) << times_sort[i+1]-times_sort[i] << \" \"\n              << std::setw(6) << times_allocM[i+1]-times_allocM[i] << \" \"\n              << std::setw(6) << times_multM[i+1]-times_multM[i] << \" \"\n              << std::setw(6) << times_mult_2M[i+1]-times_mult_2M[i] << \" \"\n              << std::endl;\n  }\n  std::cout << \"----------------------------------------------\" << std::endl;\n  auto end = times_alloc.size() - 1;\n  std::cout << std::fixed << std::setprecision(3)\n    << std::setw(6) << times_build[end] << \" \"\n    << std::setw(6) << times_alloc[end] << \" \"\n    << std::setw(6) << times_mult[end] << \" \"\n    << std::setw(6) << times_mult_2[end] << \" \"\n    << std::setw(6) << a_size[end] << \" \"\n    << std::setw(6) << c_size[end] << \" \"\n    << std::setw(6) << times_sort[end] << \" \"\n    << std::setw(6) << times_allocM[end] << \" \"\n    << std::setw(6) << times_multM[end] << \" \"\n    << std::setw(6) << times_mult_2M[end] << \" \"\n    << std::endl;\n  //print_sparse(\"b=\",b);\n}\n\n\n\n/*\n\n\nvoid test_oper_mult() {\n  Timer stop_watch;\n  std::random_device rd;\n  std::default_random_engine rand_gen(rd());\n  std::uniform_real_distribution<double> urd(-1, 1);\n  auto a = build_sparse(2, rand_gen, urd);\n  auto b = build_sparse(2, rand_gen, urd);\n  auto c = build_sparse(2, rand_gen, urd);\n  std::vector<double> times_mult;\n  std::vector<double> times_mult_2;\n  std::vector<double> times_alloc;\n  for(int q = 1; q < 3; q++ ) {\n    // allocate\n    stop_watch.start();\n    a = build_sparse(q, rand_gen, urd);\n    b = build_sparse(q, rand_gen, urd);\n    times_alloc.push_back(stop_watch.get_time());\n    // first mult\n    dealloc_sparse(c);\n    stop_watch.start();\n    oper_mult(a,b,c);\n    times_mult.push_back(stop_watch.get_time());\n    // second mult\n    dealloc_sparse(c);\n    stop_watch.start();\n    oper_mult(a,b,c);\n    times_mult_2.push_back(stop_watch.get_time());\n  }\n  for (int i = 0; i < times_mult.size() - 1; i++) {\n    std::cout << times_alloc[i+1] - times_alloc[i] << \" \"\n              << times_mult[i+1] - times_mult[i] << \" \"\n              << times_mult_2[i+1] - times_mult_2[i] << std::endl;\n  }\n}\n\n*/\nint main() {\n  /*\n  try {\n    throw std::runtime_error(\"oops\");\n  } catch(const std::exception& e) {\n    std::cerr << \"build_sparse->try->for->for->tri_list.push_back(T(row,col,v))\"\n      << std::endl;\n    std::cerr << e.what() << std::endl;\n    std::cerr << \"build_sparse->try->for->for->tri_list.push_back(T(row,col,v))\"\n      << std::endl;\n    throw;\n  }\n  */\n  test_trad_mult();\n  return 0;\n}\n", "meta": {"hexsha": "2ffdd1c33c85b1591edf71ef4fdaaf07201be770", "size": 11012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_eigen_speed/test_eigen2.cpp", "max_stars_repo_name": "benjamincommeau2/special_container", "max_stars_repo_head_hexsha": "d36d3e8a12572dc5ef985b6ccd06336309eea4fa", "max_stars_repo_licenses": ["MIT"], "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_eigen_speed/test_eigen2.cpp", "max_issues_repo_name": "benjamincommeau2/special_container", "max_issues_repo_head_hexsha": "d36d3e8a12572dc5ef985b6ccd06336309eea4fa", "max_issues_repo_licenses": ["MIT"], "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_eigen_speed/test_eigen2.cpp", "max_forks_repo_name": "benjamincommeau2/special_container", "max_forks_repo_head_hexsha": "d36d3e8a12572dc5ef985b6ccd06336309eea4fa", "max_forks_repo_licenses": ["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.6765578635, "max_line_length": 81, "alphanum_fraction": 0.5800036324, "num_tokens": 3275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6261241772283035, "lm_q1q2_score": 0.5013326150699401}}
{"text": "#pragma once\n#include <vector>\n#include <string>\n#include <random>\n#include <unordered_set>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/SparseExtra>\n\n#include \"buffalo/algo.hpp\"\n#include \"buffalo/concurrent_queue.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nstatic const int EXP_TABLE_SIZE = 1000;\n\nnamespace w2v {\n\nstruct job_t;\nstruct progress_t;\n\n\nclass CW2V : public Algorithm {\npublic:\n    CW2V();\n    ~CW2V();\n\n    void release();\n    bool init(string opt_path);\n    bool parse_option(string out_path);\n\n    void initialize_model(\n            float* L0,\n            int32_t L0_rows,\n            int32_t* index,\n            uint32_t* scale,\n            int32_t* dist,\n            int64_t total_word_count);\n\n    void build_exp_table();\n\n    void launch_workers();\n\n    void add_jobs(\n            int start_x,\n            int next_x,\n            int64_t* indptr,\n            int32_t* sequences);\n\n    void worker(int worker_id);\n\n    double update_parameter(Array<float, 1, Dynamic, RowMajor>& work,\n                            double alpha,\n                            int input_word_idx,\n                            vector<int>& negatives,\n                            bool comtpue_loss);\n\n    void progress_manager();\n    \n    double join();\n\n\nprivate:\n    Json opt_;\n    Map<FactorTypeRowMajor> L0_;\n    uint32_t *scale_;\n    int32_t *index_, *dist_;\n    FactorTypeRowMajor L1_;\n    double alpha_;\n    double total_processed_;\n    vector<double> processed_;\n    int D_;\n\n    float exp_table_[EXP_TABLE_SIZE];\n\n    vector<thread> workers_;\n    thread* progress_manager_;\n    Queue<job_t> job_queue_;\n    Queue<progress_t> progress_queue_;\n};\n\n}\n", "meta": {"hexsha": "25c495dcdceb1c2114e518110ad767326b697fd8", "size": 1687, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/buffalo/algo_impl/w2v/w2v.hpp", "max_stars_repo_name": "awesome-archive/buffalo", "max_stars_repo_head_hexsha": "1bcb76b61161e74324ca71ed05ce0576598798b5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 577.0, "max_stars_repo_stars_event_min_datetime": "2019-08-28T19:56:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T19:44:58.000Z", "max_issues_repo_path": "include/buffalo/algo_impl/w2v/w2v.hpp", "max_issues_repo_name": "awesome-archive/buffalo", "max_issues_repo_head_hexsha": "1bcb76b61161e74324ca71ed05ce0576598798b5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-08-28T23:48:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T02:13:47.000Z", "max_forks_repo_path": "include/buffalo/algo_impl/w2v/w2v.hpp", "max_forks_repo_name": "awesome-archive/buffalo", "max_forks_repo_head_hexsha": "1bcb76b61161e74324ca71ed05ce0576598798b5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 128.0, "max_forks_repo_forks_event_min_datetime": "2019-08-28T21:41:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T17:46:17.000Z", "avg_line_length": 19.8470588235, "max_line_length": 69, "alphanum_fraction": 0.6141078838, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5013326098535474}}
{"text": "#ifndef PLAN_BY_CAPTURE_POINT\n#define PLAN_BY_CAPTURE_POINT\n#include <vector>\n#include <cmath>\n#include <Eigen/Dense>\n#include <deque>\n#include <Eigen/Geometry>\n\n#ifdef PLANNER_DEBUG\nstatic constexpr bool planner_debug = true;\n#else\nstatic constexpr bool planner_debug = false;\n#endif\n\ntemplate <class T>\nstatic void debugPrint(T &&s, const std::string &label)\n{\n    if (planner_debug)\n        std::cout << \"Debug planner:\" << label << \"::\" << std::forward<T>(s) << std::endl;\n}\n\nstatic constexpr double dt = 4.0 / 1000.0;   // sampling period (s)\nstatic constexpr double zh = 0.2;            // height of CoM (m)\nstatic constexpr double g = 9.8;             // gravity (m/s^2)\nstatic constexpr double MAX_X_STRIDE = 0.30; //(m)\nstatic constexpr double MAX_Y_STRIDE = 0.08; //(m)\nstatic constexpr double MIN_Y_STRIDE = 0.03; //(m)\n\nstruct FootPrint\n{\n    double time_;\n    double x_;                  //(m)\u30ed\u30dc\u30c3\u30c8\u306e\u30ed\u30fc\u30ab\u30eb\u5ea7\u6a19\u3067\u306e\u8db3\u914d\u7f6e\u4f4d\u7f6e\n    double y_;                  //(m)\u30ed\u30dc\u30c3\u30c8\u306e\u30ed\u30fc\u30ab\u30eb\u5ea7\u6a19\u3067\u306e\u8db3\u914d\u7f6e\u4f4d\u7f6e\n    bool support_foot_is_right; //\u652f\u6301\u811a\u304c\u3069\u3061\u3089\u304b\n};\n\n/**\n * @brief capture point\u306b\u3088\u308b\u6b69\u884c\u30d1\u30bf\u30fc\u30f3\u751f\u6210\u65b9\u6cd5\n *\n */\nvoid footStepPlannerCapturePoint()\n{\n    double x = 0, y = 0, xinit = 0, yinit = 0;     //(m) CoM\u306e\u30ef\u30fc\u30eb\u30c9\u5ea7\u6a19 {CoM = Center of Mass}\n    double xd = 0, yd = 0, xdinit = 0, ydinit = 0; // CoM\u306e\u901f\u5ea6 v(m/s) xdot(t)\n    double px = 0.0, py = 0.0;                     //(m)\u3000\u7740\u5730\u4f4d\u7f6e\u306e\u30ef\u30fc\u30eb\u30c9\u5ea7\u6a19 \u3053\u308c\u306f\u5b9f\u7528\u7684\u306b\u306f\u30ed\u30fc\u30ab\u30eb\u306e\u65b9\u304c\u826f\u3044\u306e\u3067\u306f\uff1f\uff1f\n    constexpr double Tc = std::sqrt(zh / g);       //\u5fae\u5206\u65b9\u7a0b\u5f0f\u306e\u6642\u5b9a\u6570\n    constexpr double w = std::sqrt(g / zh);\n    const double Tsup = 0.32;\n    int_fast64_t step_n = 0;\n    const int32_t steps_ = 7;\n    const double stride_x = 0.3;\n    const double stride_y = 0.1;\n    double cp_x_target = 0.0, cp_y_target = 0.0;\n    double cp_x_now = 0.0, cp_y_now = 0.0;\n    double cp_x_old = 0.0, cp_y_old = 0.0;\n    debugPrint(Tsup, \"Tsup\");\n    std::deque<std::deque<double>> result;\n    std::ofstream velofs(\"velo.dat\");\n    std::vector<FootPrint> footprint_list(100);\n    for (double t = 0.0; t < (Tsup * static_cast<double>(steps_ * 2 + 1)); ++step_n)\n    {\n        //\u6c7a\u3081\u3089\u308c\u305f\u6b21\u306e\u4e00\u6b69\u3092\u7740\u304f\u5730\u70b9\u307e\u3067\u306e\u904a\u811a\u306e\u79fb\u52d5\u3092\u884c\u3063\u3066\u3044\u308b\u6642\u306e\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3---------------\n        for (double t_tmp = 0.0; t_tmp < Tsup; t_tmp += dt, t += dt)\n        {\n            // double C = std::cosh(t_tmp / Tc);\n            // double S = std::sinh(t_tmp / Tc);\n            double ewt = std::exp(w * t_tmp);\n            double dT = Tsup - t_tmp; //\u6b21\u306eCP\u307e\u3067\u306e\u6642\u9593\n            // x = (xinit - px) * C + Tc * xdinit * S + px; // x,xd\u3068\u3082\u306bn\u6b69\u76ee\u958b\u59cb\u6642\u306e\u72b6\u614b\n            // y = (yinit - py) * C + Tc * ydinit * S + py;\n            // xd = (xinit - px) / Tc * S + xdinit * C;\n            // yd = (yinit - py) / Tc * S + ydinit * C;\n            // cp_x_now = ewt * cp_x_old + (1.0 - ewt)*px; //\u3053\u3053\u3067\u306ecp_target\u306f1\u30eb\u30fc\u30d7\u524d\u306e\u8a71\u3002\n            // cp_y_now = ewt * cp_y_old + (1.0 - ewt)*py;\n            cp_x_now = ewt * cp_x_old + (1.0 - ewt) * px; // CP\u306e\u8ecc\u9053(x)\n            cp_y_now = ewt * cp_y_old + (1.0 - ewt) * py; // CP\u306e\u8ecc\u9053(y)\n            xdinit = xd;\n            ydinit = yd;\n            xd = -w * (x - cp_x_now);\n            yd = -w * (y - cp_y_now);\n            x += dt * xdinit;\n            y += dt * ydinit;\n            // result.push_back({x, y, cp_x_now, cp_y_now});\n            result.push_back({x, y, cp_x_now, cp_y_now});\n            velofs << t << \" \" << xd << \" \" << yd << std::endl;\n        }\n        xinit = x;\n        yinit = y;\n        xdinit = xd;\n        ydinit = yd;\n        //\u6b21\u306e\u4e00\u6b69\u306e\u76ee\u6a19\u4f4d\u7f6e\u3092\u8a08\u7b97------------------\n        double b = std::exp(w * Tsup);\n        std::cout << b << std::endl;\n        double sx = 0.0, sy = 0.0;\n        if (steps_ < step_n)\n        {\n            sx = 0.0;\n            sy = 0.0;\n        }\n        else\n        {\n            sx = stride_x / 2;\n            sy = ((step_n % 2) ? -1 : 1) * stride_y ;\n        }\n        cp_x_old = cp_x_now; //\u6b21\u306e\u4e00\u6b69\u306e\u6700\u521d\u306eCP\u306e\u4f4d\u7f6e\n        cp_y_old = cp_y_now;\n        cp_x_target = cp_x_old + sx;\n        cp_y_target = cp_y_old + sy;\n        if (step_n != 0)\n        {\n            px = 1.0 / (1.0 - b) * cp_x_target - b / (1.0 - b) * cp_x_now;\n            py = 1.0 / (1.0 - b) * cp_y_target - b / (1.0 - b) * cp_y_now;\n        }\n        result.back().push_back(px);\n        result.back().push_back(py);\n    }\n    std::ofstream ofs(\"position.dat\");\n    for (auto &itr : result)\n    {\n        for (auto &item : itr)\n        {\n            ofs << item << \" \";\n        }\n        ofs << std::endl;\n    }\n    // return footprint_list;\n}\n\n#endif // !PLAN_BY_CAPTURE_POINT", "meta": {"hexsha": "891f9f4957989c426d9966c4cac3bb87d2078648", "size": 4390, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "capture_point/plan_by_capture_point.hpp", "max_stars_repo_name": "AD58-3104/bipedal_training", "max_stars_repo_head_hexsha": "f7bca20e12f65ed4be2a9ba93198286682642fca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "capture_point/plan_by_capture_point.hpp", "max_issues_repo_name": "AD58-3104/bipedal_training", "max_issues_repo_head_hexsha": "f7bca20e12f65ed4be2a9ba93198286682642fca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "capture_point/plan_by_capture_point.hpp", "max_forks_repo_name": "AD58-3104/bipedal_training", "max_forks_repo_head_hexsha": "f7bca20e12f65ed4be2a9ba93198286682642fca", "max_forks_repo_licenses": ["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.0310077519, "max_line_length": 91, "alphanum_fraction": 0.5161731207, "num_tokens": 1581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.5012838329513343}}
{"text": "// Copyright (C) 2019 David Harmon and Artificial Necessity\n// This code distributed under zlib, see LICENSE.txt for terms.\n\n#pragma once\n\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include \"mesh.hpp\"\n\n// Use RowMajor so that matrix-vector products are multi-threaded by Eigen\nusing SparseMatrixd = Eigen::SparseMatrix<double,Eigen::RowMajor>;\n//using SparseMatrixd = Eigen::SparseMatrix<double>;\n\nusing SparseTripletd = Eigen::Triplet<double>;\n\nusing VecXd = Eigen::VectorXd;\nusing Vec2d = Eigen::Vector2d;\nusing Vec3d = Eigen::Vector3d;\nusing Mat2d = Eigen::Matrix2d;\nusing Mat3d = Eigen::Matrix3d;\nusing MatXd = Eigen::MatrixXd;\nusing Mat2x3d = Eigen::Matrix<double, 2, 3>;\nusing Mat3x2d = Eigen::Matrix<double, 3, 2>;\n\n\n// Abstract interface to define an energy term\nclass Energy {\npublic:\n    void set_index(int i) { index_ = i; }\n    int index() const { return index_; }\n\n    const Eigen::VectorXd& weights() const { return weights_; };\n    \n    virtual int dim() const = 0;\n\n    virtual Eigen::VectorXd reduce(const Eigen::VectorXd& x) const = 0;\n\n    virtual void get_reduction(std::vector<Eigen::Triplet<double>> &triplets) const = 0;\n    virtual void project(Eigen::VectorXd &zi) const = 0;\n\n    virtual void update(int iter) { }\n\nprotected:\n    Eigen::VectorXd weights_;\n\nprivate:\n    int index_;\n};\n\nclass DynamicEnergy : public Energy {\npublic:\n    virtual void multiply(const Eigen::VectorXd& x,\n                          const Eigen::VectorXd& factor,\n                          const Eigen::VectorXd& shift,\n                          Eigen::VectorXd& out) const = 0;\n};\n\n\nclass BaseEnergy\n{\npublic:\n    virtual ~BaseEnergy() { }\n\n    virtual void precompute(const TriMesh& mesh) = 0;\n\n    virtual void getForceAndHessian(const TriMesh& mesh,\n                                    const Eigen::VectorXd& x,\n\t\t\t\t    Eigen::VectorXd& F,\n\t\t\t\t    SparseMatrixd& dFdx,\n\t\t\t\t    SparseMatrixd& dFdv) const = 0;\n\n    virtual void getHessianPattern(const TriMesh& mesh,\n                                   std::vector<SparseTripletd> &triplets) const = 0;\n\n\n    // XPBD\n    virtual size_t nbrEnergies(const TriMesh& mesh) const { return 0; }\n\n    virtual void perVertexCount(const TriMesh& mesh, std::vector<int>& counts) const { }\n\n    virtual void update(const TriMesh& mesh, const VecXd& x, double dt, VecXd& dx) { }\n    \n    void reset() { lambda_.setZero(); }\n\nprotected:\n    VecXd lambda_; // For XPBD\n};\n", "meta": {"hexsha": "2baf981e1df594bd677afeabe577e1f295528de3", "size": 2436, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/energy.hpp", "max_stars_repo_name": "liuwei792966953/stitch", "max_stars_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-23T05:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-23T05:20:09.000Z", "max_issues_repo_path": "include/energy.hpp", "max_issues_repo_name": "liuwei792966953/stitch", "max_issues_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "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": "include/energy.hpp", "max_forks_repo_name": "liuwei792966953/stitch", "max_forks_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "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": 27.0666666667, "max_line_length": 88, "alphanum_fraction": 0.6559934319, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6113819874558604, "lm_q1q2_score": 0.5012680225938422}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../../data/FluidIndex.hpp\"\n#include <Eigen/Core>\n#include <HISSTools_FFT/HISSTools_FFT.h>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass FFT\n{\n\npublic:\n  using ArrayXcd = Eigen::ArrayXcd;\n  using ArrayXcdRef = Eigen::Ref<ArrayXcd>;\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXdRef = Eigen::Ref<const ArrayXd>;\n\n  FFT() = delete;\n\n  FFT(index size)\n      : mMaxSize(size), mSize(size), mFrameSize(size / 2 + 1),\n        mLog2Size(static_cast<index>(std::log2(size))),\n        mOutputBuffer(mFrameSize), mRealBuffer(mFrameSize),\n        mImagBuffer(mFrameSize)\n  {\n    hisstools_create_setup(&mSetup, asUnsigned(mLog2Size));\n    mSplit.realp = mRealBuffer.data();\n    mSplit.imagp = mImagBuffer.data();\n  }\n\n  ~FFT() { hisstools_destroy_setup(mSetup); }\n\n  FFT(const FFT& other) = delete;\n\n  FFT(FFT&& other) { *this = std::move(other); }\n\n  FFT& operator=(const FFT&) = delete;\n\n  FFT& operator=(FFT&& other)\n  {\n    using std::swap;\n    mMaxSize = other.mMaxSize;\n    mSize = other.mSize;\n    mFrameSize = other.mFrameSize;\n    mLog2Size = other.mLog2Size;\n    swap(mOutputBuffer, other.mOutputBuffer);\n    swap(mRealBuffer, other.mRealBuffer);\n    swap(mImagBuffer, other.mImagBuffer);\n    swap(mSplit, other.mSplit);\n    swap(mSetup, other.mSetup);\n    other.mSetup = nullptr;\n    return *this;\n  }\n\n  void resize(index newSize)\n  {\n    assert(newSize <= mMaxSize);\n    mFrameSize = newSize / 2 + 1;\n    mLog2Size = static_cast<index>(std::log2(newSize));\n    mSize = newSize;\n  }\n\n  Eigen::Ref<ArrayXcd> process(const ArrayXdRef& input)\n  {\n    hisstools_rfft(mSetup, input.data(), &mSplit, asUnsigned(input.size()),\n                   asUnsigned(mLog2Size));\n    mSplit.realp[mFrameSize - 1] = mSplit.imagp[0];\n    mSplit.imagp[mFrameSize - 1] = 0;\n    mSplit.imagp[0] = 0;\n    for (index i = 0; i < mFrameSize; i++)\n    {\n      mOutputBuffer(i) =\n          0.5 * std::complex<double>(mSplit.realp[i], mSplit.imagp[i]);\n    }\n    return mOutputBuffer.segment(0, mFrameSize);\n  }\n\nprotected:\n  index mMaxSize{16384};\n  index mSize{1024};\n  index mFrameSize{513};\n  index mLog2Size{10};\n\n  FFT_SETUP_D         mSetup;\n  FFT_SPLIT_COMPLEX_D mSplit;\n\nprivate:\n  ArrayXcd mOutputBuffer;\n  ArrayXd  mRealBuffer;\n  ArrayXd  mImagBuffer;\n};\n\nclass IFFT : public FFT\n{\n\npublic:\n  IFFT(index size) : FFT(size), mOutputBuffer(size) {}\n\n  using ArrayXcdRef = Eigen::Ref<const ArrayXcd>;\n  using ArrayXdRef = Eigen::Ref<ArrayXd>;\n\n  Eigen::Ref<ArrayXd> process(const Eigen::Ref<const ArrayXcd>& input)\n  {\n    for (index i = 0; i < input.size(); i++)\n    {\n      mSplit.realp[i] = input[i].real();\n      mSplit.imagp[i] = input[i].imag();\n    }\n    mSplit.imagp[0] = mSplit.realp[mFrameSize - 1];\n    hisstools_rifft(mSetup, &mSplit, mOutputBuffer.data(),\n                    asUnsigned(mLog2Size));\n    return mOutputBuffer.segment(0, mSize);\n  }\n\nprivate:\n  ArrayXd mOutputBuffer;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "3995d8a47dc098abfcc8db5c7ff8fc0af4e847a9", "size": 3361, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/FFT.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/FFT.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/FFT.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 25.6564885496, "max_line_length": 75, "alphanum_fraction": 0.669443618, "num_tokens": 973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5012680163639599}}
{"text": "// 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 NETKET_FULLCONNLAYER_HH\n#define NETKET_FULLCONNLAYER_HH\n\n#include <Eigen/Dense>\n#include <complex>\n#include <fstream>\n#include <random>\n#include <string>\n#include <vector>\n#include \"Utils/all_utils.hpp\"\n#include \"Utils/lookup.hpp\"\n#include \"abstract_layer.hpp\"\n\nnamespace netket {\n\nclass FullyConnected : public AbstractLayer {\n  bool usebias_;\n\n  int in_size_;        // input size\n  int out_size_;       // output size\n  int npar_;           // number of parameters in layer\n  MatrixType weight_;  // Weight parameters, W(in_size x out_size)\n  VectorType bias_;    // Bias parameters, b(out_size x 1)\n                       // Note that input of this layer is also the output of\n                       // previous layer\n\n  std::string name_;\n\n  std::size_t scalar_bytesize_;\n\n public:\n  /// Constructor\n  FullyConnected(const int input_size, const int output_size,\n                 const bool use_bias = false)\n      : usebias_(use_bias), in_size_(input_size), out_size_(output_size) {\n    Init();\n  }\n\n  void Init() {\n    scalar_bytesize_ = sizeof(Complex);\n\n    weight_.resize(in_size_, out_size_);\n    bias_.resize(out_size_);\n\n    npar_ = in_size_ * out_size_;\n\n    if (usebias_) {\n      npar_ += out_size_;\n    } else {\n      bias_.setZero();\n    }\n\n    name_ = \"Fully Connected Layer\";\n  }\n\n  std::string Name() const override { return name_; }\n\n  void to_json(json &pars) const override {\n    json layerpar;\n    layerpar[\"Name\"] = \"FullyConnected\";\n    layerpar[\"UseBias\"] = usebias_;\n    layerpar[\"Inputs\"] = in_size_;\n    layerpar[\"Outputs\"] = out_size_;\n    layerpar[\"Bias\"] = bias_;\n    layerpar[\"Weight\"] = weight_;\n\n    pars[\"Layers\"].push_back(layerpar);\n  }\n\n  void from_json(const json &pars) override {\n    if (FieldExists(pars, \"Weight\")) {\n      weight_ = pars[\"Weight\"];\n    } else {\n      weight_.setZero();\n    }\n    if (FieldExists(pars, \"Bias\")) {\n      bias_ = pars[\"Bias\"];\n    } else {\n      bias_.setZero();\n    }\n  }\n\n  void InitRandomPars(int seed, double sigma) override {\n    VectorType par(npar_);\n\n    netket::RandomGaussian(par, seed, sigma);\n\n    SetParameters(par);\n  }\n\n  int Npar() const override { return npar_; }\n\n  int Ninput() const override { return in_size_; }\n\n  int Noutput() const override { return out_size_; }\n\n  void GetParameters(VectorRefType pars) const override {\n    int k = 0;\n    if (usebias_) {\n      std::memcpy(pars.data(), bias_.data(), out_size_ * scalar_bytesize_);\n      k += out_size_;\n    }\n\n    std::memcpy(pars.data() + k, weight_.data(),\n                in_size_ * out_size_ * scalar_bytesize_);\n  }\n\n  void SetParameters(VectorConstRefType pars) override {\n    int k = 0;\n\n    if (usebias_) {\n      std::memcpy(bias_.data(), pars.data() + k, out_size_ * scalar_bytesize_);\n\n      k += out_size_;\n    }\n\n    std::memcpy(weight_.data(), pars.data() + k,\n                in_size_ * out_size_ * scalar_bytesize_);\n  }\n\n  void UpdateLookup(const VectorType &input,\n                    const std::vector<int> &input_changes,\n                    const VectorType &new_input, const VectorType &output,\n                    std::vector<int> &output_changes,\n                    VectorType &new_output) override {\n    const int num_of_changes = input_changes.size();\n    if (num_of_changes == in_size_) {\n      output_changes.resize(out_size_);\n      new_output.resize(out_size_);\n      Forward(new_input, new_output);\n    } else if (num_of_changes > 0) {\n      output_changes.resize(out_size_);\n      new_output = output;\n      UpdateOutput(input, input_changes, new_input, new_output);\n    } else {\n      output_changes.resize(0);\n      new_output.resize(0);\n    }\n  }\n\n  // Feedforward\n  void Forward(const VectorType &input, VectorType &output) override {\n    output = bias_;\n    output.noalias() += weight_.transpose() * input;\n  }\n\n  // Updates theta given the input v, the change in the input (input_changes and\n  // prev_input)\n  inline void UpdateOutput(const VectorType &v,\n                           const std::vector<int> &input_changes,\n                           const VectorType &new_input,\n                           VectorType &new_output) {\n    const int num_of_changes = input_changes.size();\n    for (int s = 0; s < num_of_changes; s++) {\n      const int sf = input_changes[s];\n      new_output += weight_.row(sf) * (new_input(s) - v(sf));\n    }\n  }\n\n  // Computes derivative.\n  void Backprop(const VectorType &prev_layer_output,\n                const VectorType & /*this_layer_output*/,\n                const VectorType &dout, VectorType &din,\n                VectorRefType der) override {\n    // dout = d(L) / d(z)\n    // Derivative for bias, d(L) / d(b) = d(L) / d(z)\n    int k = 0;\n\n    if (usebias_) {\n      Eigen::Map<VectorType> der_b{der.data() + k, out_size_};\n\n      der_b.noalias() = dout;\n      k += out_size_;\n    }\n\n    // Derivative for weights, d(L) / d(W) = [d(L) / d(z)] * in'\n    Eigen::Map<MatrixType> der_w{der.data() + k, in_size_, out_size_};\n\n    der_w.noalias() = prev_layer_output * dout.transpose();\n\n    // Compute d(L) / d_in = W * [d(L) / d(z)]\n    din.noalias() = weight_ * dout;\n  }\n};\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "cb22c6d5a0062f5c20fcb03e27a993e7391de5ed", "size": 5766, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Sources/Machine/Layers/fullconn_layer.hpp", "max_stars_repo_name": "tvieijra/netket", "max_stars_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-29T02:51:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T18:52:33.000Z", "max_issues_repo_path": "Sources/Machine/Layers/fullconn_layer.hpp", "max_issues_repo_name": "tvieijra/netket", "max_issues_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T11:12:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T17:04:41.000Z", "max_forks_repo_path": "Sources/Machine/Layers/fullconn_layer.hpp", "max_forks_repo_name": "tvieijra/netket", "max_forks_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-12-02T07:29:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-04T21:55:21.000Z", "avg_line_length": 28.5445544554, "max_line_length": 80, "alphanum_fraction": 0.6271245231, "num_tokens": 1449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5012680056015419}}
{"text": "#include \"encode_decode.h\"\n#include <queue>\n#include <string>\n#include <unordered_map>\n#include <vector>\n#include <boost/dynamic_bitset.hpp>\n#include \"char_node.h\"\n#include \"encoding.pb.h\"\n#include \"freq_node.h\"\n#include \"inner_node.h\"\n\nnamespace encode_decode {\n\n\tclass Comparator {\n\tpublic:\n\t    bool operator()(const std::shared_ptr<FreqNode>& a, \n\t    \t\t\t\tconst std::shared_ptr<FreqNode>& b) {\n\t        return (a->get_freq() > b->get_freq());\n\t    }\n\t};\n\n\tstd::unordered_map<char, int> count_freq(const std::string& s) {\n\t\tstd::unordered_map<char, int> counter;\n\t\tfor (auto it = s.begin(); it != s.end(); ++it) {\n\t\t\tstd::unordered_map<char,int>::iterator res = counter.find(*it);\n\t\t\tif (res == counter.end()) {\n\t\t\t\tcounter.emplace(*it, 1);\n\t\t\t} else {\n\t\t\t\tres->second = res->second + 1;\n\t\t\t}\n\t\t}\n\t\treturn counter;\n\t}\n\n\tstd::shared_ptr<FreqNode> create_optimal_hufftree(const std::string& s) {\n\n\t\tstd::unordered_map<char, int>&& counter = count_freq(s);\n\n\t\t// We use shared_ptr because the priority queue only provides \n\t\t// access to the top element as a const reference.\n\t\t// Thus, it is impossible to move the ownership of the node or its \n\t\t// child nodes.\n\t\t// Alternatively, we could copy the node out of the queue,\n\t\t// but as we combine nodes into a tree throughout the algorithm,\n\t\t// this would entail copying the entire tree, \n\t\t// making the algorithm O(n^2) rather than O(n lg n).\n\t\tstd::priority_queue<std::shared_ptr<FreqNode>, \n\t\t\t\t\t\t\tstd::vector<std::shared_ptr<FreqNode>>, \n\t\t\t\t\t\t\tComparator> minheap;\n\t\tfor (auto it = counter.begin(); it != counter.end(); ++it) {\n\t\t\t// Allocate each character node on the heap\n\t\t\tminheap.push(std::make_shared<CharNode>(\n\t\t\t\tCharNode(it->first, it->second)));\n\t\t}\n\n\t\tint numchars = minheap.size();\n\t\tfor (int i = 1; i < numchars; ++i) {\n\t\t\tstd::shared_ptr<FreqNode> left(minheap.top());\n\t\t\tminheap.pop();\n\t\t\tstd::shared_ptr<FreqNode> right(minheap.top());\n\t\t\tminheap.pop();\n\t\t\tminheap.push(std::shared_ptr<InnerNode>{\n\t\t\t\tnew InnerNode(left, right)});\n\t\t}\n\t\tstd::shared_ptr<FreqNode> root(minheap.top());\n\t\tminheap.pop();\n\t\treturn root;\n\t}\n\n\tstd::unordered_map<char, boost::dynamic_bitset<>> encode_tree(const FreqNode& root) {\n\t\tstd::unordered_map<char, boost::dynamic_bitset<>> encodings;\n\t\tboost::dynamic_bitset<> bits;\n\t\troot.encode_node(bits, encodings);\n\t\treturn encodings;\n\t}\n\n\tvoid concat_bitsets(boost::dynamic_bitset<>& bits1, \n\t\t\t\t\t\tconst boost::dynamic_bitset<>& bits2) {\n\t\tsize_t orig_size = bits1.size();\n\t\tbits1.resize(orig_size + bits2.size());\n\t\tfor (size_t i = 0; i < bits2.size(); i++) {\n\t\t\tbits1[orig_size + i] = bits2[i];\n\t\t}\n\t}\n\n\tStatus encode_string(const std::unordered_map<char, boost::dynamic_bitset<>>& encodings,\n\t\t\t\t\t   \t const std::string& s,\n\t\t\t\t\t   \t boost::dynamic_bitset<>& bits) {\n\t\tfor (auto it = s.begin(); it != s.end(); ++it) {\n\t\t\tstd::unordered_map<char,boost::dynamic_bitset<>>::const_iterator res = encodings.find(*it);\n\t\t\tif (res == encodings.end()) {\n\t\t\t\treturn Status::kInvalid;\n\t\t\t}\n\t\t\tconcat_bitsets(bits, res->second);\n\t\t}\n\t\treturn Status::kOk;\n\t}\n\n\tStatus from_proto(const FreqNodeProto& proto_node,\n\t \t\t\t      std::shared_ptr<FreqNode>& node) {\n\t\tif (proto_node.type() == FreqNodeProto_Type_CHAR) {\n\t\t\t// TODO: convert to char\n\t\t\tgoogle::protobuf::int32 int_c = proto_node.c();\n\t\t\tchar c = static_cast<char>(int_c);\n\t\t\tint freq = proto_node.freq();\n\t\t\tnode = std::make_shared<CharNode>(CharNode(c, freq));\n\t\t\treturn Status::kOk;\n\t\t} else if (proto_node.type() == FreqNodeProto_Type_INNER) {\n\t\t\tstd::shared_ptr<FreqNode> lc;\n\t\t\tstd::shared_ptr<FreqNode> rc;\n\t\t\tif (from_proto(proto_node.lc(), lc) == Status::kOk &&\n\t\t\t\tfrom_proto(proto_node.rc(), rc) == Status::kOk) {\n\t\t\t\tnode = std::make_shared<InnerNode>(InnerNode(lc, rc));\n\t\t\t\treturn Status::kOk;\n\t\t\t} else {\n\t\t\t\treturn Status::kInvalid;\n\t\t\t}\n\t\t} else {\n\t\t\treturn Status::kInvalid;\n\t\t}\n\t}\n\n\tStatus decode_bits(const FreqNode& root,\n\t\t\t\t\t   const boost::dynamic_bitset<>& encoded_bits,\n\t\t\t\t\t   std::string& decoding) {\n\t\tsize_t bit_index(0);\n\t\twhile (bit_index < encoded_bits.size()) {\n\t\t\tchar c;\n\t\t\tif (root.find_next_char(encoded_bits, bit_index, c) == Status::kOk) {\n\t\t\t\tdecoding.push_back(c);\n\t\t\t} else {\n\t\t\t\t// An invalid status occurs if there are not enough bits \n\t\t\t\t// in the bitset to reach a char node.\n\t\t\t\treturn Status::kInvalid;\n\t\t\t}\n\t\t}\n\t\treturn Status::kOk;\n\t}\n}", "meta": {"hexsha": "f76ed60ba760d9bdb1724d742cbd84ee9c1662f2", "size": 4337, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/encode_decode.cc", "max_stars_repo_name": "nfallen/Huffman-Coding", "max_stars_repo_head_hexsha": "fdb51d66b77884978d4b4cf57313cb8225399bbb", "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/encode_decode.cc", "max_issues_repo_name": "nfallen/Huffman-Coding", "max_issues_repo_head_hexsha": "fdb51d66b77884978d4b4cf57313cb8225399bbb", "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/encode_decode.cc", "max_forks_repo_name": "nfallen/Huffman-Coding", "max_forks_repo_head_hexsha": "fdb51d66b77884978d4b4cf57313cb8225399bbb", "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.2014388489, "max_line_length": 94, "alphanum_fraction": 0.6592114365, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5010907069812667}}
{"text": "//\n// Created by michel on 13-04-21.\n//\n\n#include \"test-helper.h\"\n#include \"org-simple/util/dsp/integration.h\"\n#include <boost/math/special_functions/relative_difference.hpp>\n\nusing namespace org::simple::util::dsp;\n\nstatic bool same(double v1, double v2, double epsilon = 1e-12) {\n  return boost::math::relative_difference(v1, v2) < epsilon;\n}\n\nBOOST_AUTO_TEST_SUITE(org_simple_dsp_integration_Tests)\n\nBOOST_AUTO_TEST_CASE(testInitWithScaleOne) {\n  Coefficients coeffs = Coefficients ::from_count(1.0, 1.0);\n\n  BOOST_CHECK_EQUAL(1.0, coeffs.scale());\n\n  BOOST_CHECK_EQUAL(exp(-1), coeffs.history_multiplier());\n\n  BOOST_CHECK_EQUAL(1.0 - exp(-1), coeffs.input_multiplier());\n  BOOST_CHECK_EQUAL(coeffs.input_multiplier(),\n                    coeffs.input_multiplier_scaled());\n\n  BOOST_CHECK_EQUAL(1.0, coeffs.integration_sample_count());\n}\n\nBOOST_AUTO_TEST_CASE(testInitWithScaleOneAndImplicitOne) {\n  Coefficients coeffs1n = Coefficients ::from_count(1.0);\n  Coefficients coeffs11 = Coefficients ::from_count(1.0, 1.0);\n\n  BOOST_CHECK_EQUAL(coeffs11.scale(), coeffs1n.scale());\n\n  BOOST_CHECK_EQUAL(coeffs11.history_multiplier(),\n                    coeffs1n.history_multiplier());\n\n  BOOST_CHECK_EQUAL(coeffs11.input_multiplier(), coeffs1n.input_multiplier());\n  BOOST_CHECK_EQUAL(coeffs11.input_multiplier_scaled(),\n                    coeffs1n.input_multiplier_scaled());\n\n  BOOST_CHECK_EQUAL(coeffs11.integration_sample_count(),\n                    coeffs1n.integration_sample_count());\n}\n\nBOOST_AUTO_TEST_CASE(testInitWithScaleTwo) {\n  const double scale = 2.0;\n  Coefficients coeffs1 = Coefficients ::from_count(1.0, 1.0);\n  Coefficients coeffs2 = Coefficients ::from_count(1.0, scale);\n\n  BOOST_CHECK_EQUAL(scale, coeffs2.scale());\n\n  BOOST_CHECK_EQUAL(coeffs1.history_multiplier(), coeffs2.history_multiplier());\n\n  BOOST_CHECK_EQUAL(coeffs1.input_multiplier(), coeffs2.input_multiplier());\n  BOOST_CHECK_EQUAL(scale * coeffs1.input_multiplier(),\n                    coeffs2.input_multiplier_scaled());\n\n  BOOST_CHECK_EQUAL(1.0, coeffs2.integration_sample_count());\n}\n\nBOOST_AUTO_TEST_CASE(testCOuntOneScaleOneIntegrationConsistency) {\n  Coefficients coeffs = Coefficients ::from_count(1.0, 1.0);\n  double input = 1.0;\n  double history1 = 0;\n  double history2 = 0;\n  double history3 = 0;\n  double output1;\n  double output2;\n\n  output1 = coeffs.get_integrated(history1, input);\n  output2 = coeffs.integrate_and_get(history2, input);\n  coeffs.integrate(history3, input);\n\n  BOOST_CHECK_EQUAL(output1, output2);\n  BOOST_CHECK_EQUAL(output2, history2);\n  BOOST_CHECK_EQUAL(output2, history3);\n\n  BOOST_CHECK_EQUAL(input * coeffs.input_multiplier(), output1);\n\n  history1 = history2;\n  output1 = coeffs.get_integrated(history1, input);\n  output2 = coeffs.integrate_and_get(history2, input);\n  coeffs.integrate(history3, input);\n\n  BOOST_CHECK_EQUAL(output1, output2);\n  BOOST_CHECK_EQUAL(output2, history2);\n  BOOST_CHECK_EQUAL(output2, history3);\n\n  BOOST_CHECK_EQUAL(coeffs.input_multiplier() * (coeffs.history_multiplier() + input), output1);\n}\n\nBOOST_AUTO_TEST_CASE(testCOuntOneScaleTwoIntegrationConsistency) {\n  double scale = 2;\n  Coefficients coeffs = Coefficients ::from_count(1.0, scale);\n  double input = 1.0;\n  double history1 = 0;\n  double history2 = 0;\n  double history3 = 0;\n  double output1;\n  double output2;\n\n  output1 = coeffs.get_integrated(history1, input);\n  output2 = coeffs.integrate_and_get(history2, input);\n  coeffs.integrate(history3, input);\n\n  BOOST_CHECK_EQUAL(output1, output2);\n  BOOST_CHECK_EQUAL(output2, history2);\n  BOOST_CHECK_EQUAL(output2, history3);\n\n  BOOST_CHECK_EQUAL(input * coeffs.input_multiplier_scaled(), output1);\n\n  history1 = history2;\n  output1 = coeffs.get_integrated(history1, input);\n  output2 = coeffs.integrate_and_get(history2, input);\n  coeffs.integrate(history3, input);\n\n  BOOST_CHECK_EQUAL(output1, output2);\n  BOOST_CHECK_EQUAL(output2, history2);\n  BOOST_CHECK_EQUAL(output2, history3);\n\n  BOOST_CHECK_EQUAL(scale * (coeffs.input_multiplier() * (coeffs.history_multiplier() + input)), output1);\n}\n\nBOOST_AUTO_TEST_CASE(testImpulseResponseSumIsScale) {\n  Coefficients coeffs;\n  for (double samples = 0.5; samples < 5; samples += 0.5) {\n    for (double scale = 0.5; scale < 5; scale += 0.5) {\n      coeffs = Coefficients::from_count_bound(samples, scale);\n      double input = 1;\n      double previous_output = 10 * scale * samples;\n      double output = 0;\n      double previous_sum = -1;\n      double sum = 0;\n      int i = 0;\n      while (++i < 10 || (sum > previous_sum && output < previous_output && output > 1e-8)) {\n        previous_output = output;\n        previous_sum = sum;\n        sum += coeffs.integrate_and_get(output, input);\n        input = 0;\n      }\n      BOOST_CHECK(same(sum, scale, 1e-7));\n      if (!same(sum, scale, 1e-7)) {\n        std::cout << \"Sum=\" << sum << \"; scale=\" << scale << std::endl;\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testStepResponseIsScale) {\n  Coefficients coeffs;\n  for (double samples = 0.5; samples < 5; samples += 0.5) {\n    for (double scale = 0.5; scale < 5; scale += 0.5) {\n      coeffs = Coefficients::from_count_bound(samples, scale);\n      double input = 1;\n      double output = 0;\n      int i = 0;\n      while (++i < 10000 || !same(output, scale)) {\n        coeffs.integrate(output, input);\n      }\n      BOOST_CHECK(same(output, scale, 1e-7));\n      if (!same(output, scale, 1e-7)) {\n        std::cout << \"Output=\" << output << \"; scale=\" << scale << std::endl;\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f6e2efcff4c3ddb00e80f88e7a81d8f2fc9949d0", "size": 5540, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/util/dsp/integration-tests.cc", "max_stars_repo_name": "emmef/org-simple-util", "max_stars_repo_head_hexsha": "80c7ad1c1241ce37c8a312ba1e990ffd5a2db619", "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/util/dsp/integration-tests.cc", "max_issues_repo_name": "emmef/org-simple-util", "max_issues_repo_head_hexsha": "80c7ad1c1241ce37c8a312ba1e990ffd5a2db619", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-09-24T21:26:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-31T13:32:53.000Z", "max_forks_repo_path": "test/util/dsp/integration-tests.cc", "max_forks_repo_name": "emmef/org-simple", "max_forks_repo_head_hexsha": "7b2e4337b68d784e23cecded3c0dfb2ed80ea64a", "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.2093023256, "max_line_length": 106, "alphanum_fraction": 0.70433213, "num_tokens": 1435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5010852786529395}}
{"text": "#include <cmath>\n#include <cstddef>\n#include <vector>\n\n#include <Eigen/Core>\n#include <eigen-checks/gtest.h>\n#include <gtest/gtest.h>\n#include <SuiteSparseQR.hpp>\n\n#include \"truncated-svd-solver/linear-algebra-helpers.h\"\n#include \"truncated-svd-solver/marginalization.h\"\n\nnamespace truncated_svd_solver {\n\nbool getR(cholmod_sparse* A, cholmod_sparse** R, cholmod_common* cholmod) {\n  CHECK_NOTNULL(A);\n  CHECK_NOTNULL(R);\n  CHECK_NOTNULL(cholmod);\n\n  cholmod_sparse* qr_A = cholmod_l_transpose(A, 1, cholmod);\n  SuiteSparseQR<double>(SPQR_ORDERING_FIXED, SPQR_NO_TOL, qr_A->ncol, 0, qr_A,\n                        nullptr, nullptr, nullptr, nullptr, R, nullptr, nullptr,\n                        nullptr, nullptr, cholmod);\n  cholmod_l_free_sparse(&qr_A, cholmod);\n  return cholmod->status;\n}\n\nTEST(TruncatedSvdSolver, Marginalization) {\n  cholmod_common cholmod;\n  cholmod_l_start(&cholmod);\n\n  // Create a random jacobian.\n  Eigen::MatrixXd J = Eigen::MatrixXd::Random(5, 5);\n  Eigen::MatrixXd J_cov_expected = (J.transpose() * J).inverse();\n\n  // Convert to cholmod sparse format.\n  cholmod_sparse* Jt_cholmod =\n      eigenDenseToCholmodSparseCopy(J.transpose(), &cholmod, 1e-16);\n\n  // Test the results.\n  Eigen::MatrixXd NS, CS, Sigma, SigmaP, Omega;\n  const double svLogSum = marginalize(Jt_cholmod, 0, NS, CS, Sigma,\n    SigmaP, Omega);\n\n  EXPECT_NEAR(std::fabs(svLogSum),\n              std::fabs(std::log2(std::fabs(J_cov_expected.determinant()))),\n              1e-8);\n  EXPECT_TRUE(EIGEN_MATRIX_NEAR(Sigma, J_cov_expected, 1e-12));\n\n  cholmod_l_finish(&cholmod);\n}\n\n}  // namespace truncated_svd_solver\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  google::InitGoogleLogging(argv[0]);\n  google::InstallFailureSignalHandler();\\\n  ::testing::FLAGS_gtest_death_test_style = \"threadsafe\";\n  FLAGS_alsologtostderr = true;\n  FLAGS_colorlogtostderr = true;\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "e9df69841131ab0bbbdff7299e6a99c7934c19eb", "size": 1919, "ext": "cc", "lang": "C++", "max_stars_repo_path": "truncated_svd_solver/test/test-marginalization.cc", "max_stars_repo_name": "ethz-asl/truncated_svd_solver", "max_stars_repo_head_hexsha": "12772b2e3a0282e77022f12f67497401ca020f57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2017-02-06T18:05:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T01:56:49.000Z", "max_issues_repo_path": "truncated_svd_solver/test/test-marginalization.cc", "max_issues_repo_name": "ethz-asl/truncated_svd_solver", "max_issues_repo_head_hexsha": "12772b2e3a0282e77022f12f67497401ca020f57", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T16:46:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-14T16:46:52.000Z", "max_forks_repo_path": "truncated_svd_solver/test/test-marginalization.cc", "max_forks_repo_name": "ethz-asl/truncated_svd_solver", "max_forks_repo_head_hexsha": "12772b2e3a0282e77022f12f67497401ca020f57", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-12-27T09:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T23:22:28.000Z", "avg_line_length": 29.984375, "max_line_length": 80, "alphanum_fraction": 0.7097446587, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5010852675954144}}
{"text": "#include <igl/read_triangle_mesh.h>\n#include <igl/get_seconds.h>\n#include <igl/material_colors.h>\n#include <igl/copyleft/marching_cubes.h>\n#include <igl/copyleft/swept_volume.h>\n#include <igl/opengl/glfw/Viewer.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 std;\n  using namespace igl;\n  Eigen::MatrixXi F,SF;\n  Eigen::MatrixXd V,SV,VT;\n  bool show_swept_volume = false;\n  // Define a rigid motion\n  const auto & transform = [](const double t)->Eigen::Affine3d\n  {\n    Eigen::Affine3d T = Eigen::Affine3d::Identity();\n    T.rotate(Eigen::AngleAxisd(t*2.*M_PI,Eigen::Vector3d(0,1,0)));\n    T.translate(Eigen::Vector3d(0,0.125*cos(2.*M_PI*t),0));\n    return T;\n  };\n  // Read in inputs as double precision floating point meshes\n  read_triangle_mesh(\n      TUTORIAL_SHARED_PATH \"/bunny.off\",V,F);\n  cout<<R\"(Usage:\n[space]  Toggle between transforming original mesh and swept volume\n)\";\n  igl::opengl::glfw::Viewer viewer;\n  viewer.data().set_mesh(V,F);\n  viewer.data().set_face_based(true);\n  viewer.core.is_animating = !show_swept_volume;\n  const int grid_size = 50;\n  const int time_steps = 200;\n  const double isolevel = 0.1;\n  std::cerr<<\"Computing swept volume...\";\n  igl::copyleft::swept_volume(\n    V,F,transform,time_steps,grid_size,isolevel,SV,SF);\n  std::cerr<<\" finished.\"<<std::endl;\n\n  viewer.callback_pre_draw =\n    [&](igl::opengl::glfw::Viewer & viewer)->bool\n    {\n      if(!show_swept_volume)\n      {\n        Eigen::Affine3d T = transform(0.25*igl::get_seconds());\n        VT = V*T.matrix().block(0,0,3,3).transpose();\n        Eigen::RowVector3d trans = T.matrix().block(0,3,3,1).transpose();\n        VT = ( VT.rowwise() + trans).eval();\n        viewer.data().set_vertices(VT);\n        viewer.data().compute_normals();\n      }\n      return false;\n    };\n  viewer.callback_key_down =\n    [&](igl::opengl::glfw::Viewer & viewer, unsigned char key, int mod)->bool\n    {\n      switch(key)\n      {\n        default:\n          return false;\n        case ' ':\n          show_swept_volume = !show_swept_volume;\n          viewer.data().clear();\n          if(show_swept_volume)\n          {\n            viewer.data().set_mesh(SV,SF);\n            Eigen::Vector3d ambient = Eigen::Vector3d(SILVER_AMBIENT[0], SILVER_AMBIENT[1], SILVER_AMBIENT[2]);\n            Eigen::Vector3d diffuse = Eigen::Vector3d(SILVER_DIFFUSE[0], SILVER_DIFFUSE[1], SILVER_DIFFUSE[2]);\n            Eigen::Vector3d specular = Eigen::Vector3d(SILVER_SPECULAR[0], SILVER_SPECULAR[1], SILVER_SPECULAR[2]);\n            viewer.data().uniform_colors(ambient,diffuse,specular);\n          }\n          else\n          {\n            viewer.data().set_mesh(V,F);\n          }\n          viewer.core.is_animating = !show_swept_volume;\n          viewer.data().set_face_based(true);\n          break;\n      }\n      return true;\n    };\n  viewer.launch();\n}\n", "meta": {"hexsha": "ab1f5c749992b3e37fdc46e57204915b4ce5908f", "size": 2901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FSDF/libs/libigl-master/tutorial/707_SweptVolume/main.cpp", "max_stars_repo_name": "szat/FSDF", "max_stars_repo_head_hexsha": "076129c0dfd2ac2354cc40ade363b96f4b6248fa", "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": "FSDF/libs/libigl-master/tutorial/707_SweptVolume/main.cpp", "max_issues_repo_name": "szat/FSDF", "max_issues_repo_head_hexsha": "076129c0dfd2ac2354cc40ade363b96f4b6248fa", "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": "FSDF/libs/libigl-master/tutorial/707_SweptVolume/main.cpp", "max_forks_repo_name": "szat/FSDF", "max_forks_repo_head_hexsha": "076129c0dfd2ac2354cc40ade363b96f4b6248fa", "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": 32.595505618, "max_line_length": 115, "alphanum_fraction": 0.6335746294, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5010852675954144}}
{"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\n#include \"Utils/Optimizer/GradientBased/GradientBasedCheck.h\"\n#include \"Utils/Settings.h\"\n#include <Eigen/Core>\n\nnamespace Scine {\nnamespace Utils {\n\nbool GradientBasedCheck::checkConvergence(const Eigen::VectorXd& parameter, double value, const Eigen::VectorXd& gradient) {\n  if (_oldParams.size() != parameter.size()) {\n    _oldParams = Eigen::VectorXd::Zero(parameter.size());\n  }\n  // Generate temporaries\n  Eigen::VectorXd deltaParam = (parameter - _oldParams).eval();\n  double deltaV = value - _oldValue;\n  // Rotate stored old data\n  _oldParams = parameter;\n  _oldValue = value;\n  // Check\n  unsigned int converged = 0;\n  if (gradient.cwiseAbs().maxCoeff() < gradMaxCoeff) {\n    converged++;\n  }\n  if (deltaParam.cwiseAbs().maxCoeff() < stepMaxCoeff) {\n    converged++;\n  }\n  if (sqrt(gradient.squaredNorm() / gradient.size()) < gradRMS) {\n    converged++;\n  }\n  if (sqrt(deltaParam.squaredNorm() / deltaParam.size()) < stepRMS) {\n    converged++;\n  }\n  return ((fabs(deltaV) < deltaValue) && (converged >= requirement));\n}\n\nbool GradientBasedCheck::checkMaxIterations(unsigned int currentIteration) const {\n  return currentIteration >= maxIter;\n}\n\nvoid GradientBasedCheck::setParametersAndValue(const Eigen::VectorXd& parameter, double value) {\n  _oldParams = parameter;\n  _oldValue = value;\n}\n\nvoid GradientBasedCheck::addSettingsDescriptors(UniversalSettings::DescriptorCollection& collection) const {\n  UniversalSettings::DoubleDescriptor step_max_coeff(\n      \"Convergence threshold for step vector's maximum absolute element.\");\n  step_max_coeff.setMinimum(0.0);\n  step_max_coeff.setDefaultValue(stepMaxCoeff);\n  collection.push_back(GradientBasedCheck::gconvStepMaxCoeffKey, step_max_coeff);\n\n  UniversalSettings::DoubleDescriptor step_RMS(\"Convergence threshold for step vector's RMS.\");\n  step_RMS.setMinimum(0.0);\n  step_RMS.setDefaultValue(stepRMS);\n  collection.push_back(GradientBasedCheck::gconvStepRMSKey, step_RMS);\n\n  UniversalSettings::DoubleDescriptor grad_max_coeff(\n      \"Convergence threshold for gradient vector's maximum absolute element.\");\n  grad_max_coeff.setMinimum(0.0);\n  grad_max_coeff.setDefaultValue(gradMaxCoeff);\n  collection.push_back(GradientBasedCheck::gconvGradMaxCoeffKey, grad_max_coeff);\n\n  UniversalSettings::DoubleDescriptor grad_RMS(\"Convergence threshold for gradient vector's RMS.\");\n  grad_RMS.setMinimum(0.0);\n  grad_RMS.setDefaultValue(gradRMS);\n  collection.push_back(GradientBasedCheck::gconvGradRMSKey, grad_RMS);\n\n  UniversalSettings::DoubleDescriptor delta_value(\n      \"Convergence threshold for the absolute difference in the value between the current and the last step.\");\n  delta_value.setMinimum(0.0);\n  delta_value.setDefaultValue(deltaValue);\n  collection.push_back(GradientBasedCheck::gconvDeltaValueKey, delta_value);\n\n  UniversalSettings::IntDescriptor max_iter(\"The maximum number of iterations.\");\n  max_iter.setMinimum(0.0);\n  max_iter.setDefaultValue(maxIter);\n  collection.push_back(GradientBasedCheck::gconvMaxIterKey, max_iter);\n\n  UniversalSettings::IntDescriptor requirements(\n      \"The number of threasholds besides the value one that need to converge for overall convergence.\");\n  requirements.setDefaultValue(requirement);\n  requirements.setMaximum(4);\n  requirements.setMinimum(0);\n  collection.push_back(GradientBasedCheck::gconvRequirementKey, requirements);\n}\n\nvoid GradientBasedCheck::applySettings(const Settings& settings) {\n  stepMaxCoeff = settings.getDouble(GradientBasedCheck::gconvStepMaxCoeffKey);\n  stepRMS = settings.getDouble(GradientBasedCheck::gconvStepRMSKey);\n  gradMaxCoeff = settings.getDouble(GradientBasedCheck::gconvGradMaxCoeffKey);\n  gradRMS = settings.getDouble(GradientBasedCheck::gconvGradRMSKey);\n  deltaValue = settings.getDouble(GradientBasedCheck::gconvDeltaValueKey);\n  maxIter = settings.getInt(GradientBasedCheck::gconvMaxIterKey);\n  requirement = settings.getInt(GradientBasedCheck::gconvRequirementKey);\n}\n\n} // namespace Utils\n} // namespace Scine\n", "meta": {"hexsha": "d6b6bbb38e0352fd0bbc6b49869fc15ef1a808d9", "size": 4191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Optimizer/GradientBased/GradientBasedCheck.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/Optimizer/GradientBased/GradientBasedCheck.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/Optimizer/GradientBased/GradientBasedCheck.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": 39.9142857143, "max_line_length": 124, "alphanum_fraction": 0.7730851825, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.5010852675954144}}
{"text": "// Kinematics plugin for MoveIt! implementing null-space optimization\n// Author: Max Schwarz <max.schwarz@uni-bonn.de>\n\n#include \"apc_kinematics.h\"\n#include \"srdf_cache.h\"\n\n#include <urdf/model.h>\n\n#include <ros/console.h>\n\n#include <boost/make_shared.hpp>\n\n#include <pluginlib/class_list_macros.h>\n\n#include <rbdl/Kinematics.h>\n\n#include <Eigen/Geometry>\n\n#include <eigen_conversions/eigen_msg.h>\n\n#include <angles/angles.h>\n\n#include <math.h>\n\n#include <exception>\n\n#include <visualization_msgs/MarkerArray.h>\n\n/** \\brief Computes the jacobian\n *\n * \\param model   \trigid body model\n * \\param Q       \tstate vector of the joints\n * \\param joint_mapping mapping from the joint ids to the rbdl joint ids\n * \\param body_id \tthe id of the body\n * \\param base_id \tthe id of the base\n * \\param J       \ta matrix where the result will be stored in\n *\n * \\returns A 6 x \\#dof_count matrix of the jacobian\n */\nstatic void _CalcPointRotJacobian (RigidBodyDynamics::Model &model,\n\tconst RigidBodyDynamics::Math::VectorNd &Q,\n\tconst std::vector<int> &joint_mapping,\n\tunsigned int body_id,\n\tunsigned int base_id,\n\tRigidBodyDynamics::Math::MatrixNd &J)\n{\n\tusing namespace RigidBodyDynamics;\n\tusing namespace Math;\n\t\n\t// Convert the joint vector into the rbdl convention\n\tEigen::VectorXd rbdlJoints = Eigen::VectorXd::Zero(model.dof_count);\n\tfor(unsigned int i = 0; i < joint_mapping.size(); ++i)\n\t\trbdlJoints[joint_mapping[i]-1] = Q[i];\n\n\tVector3d point_base_pos = CalcBodyToBaseCoordinates(model, rbdlJoints, body_id, Eigen::VectorXd::Zero(3), false);\n\tSpatialMatrix point_trans = Math::Xtrans_mat (point_base_pos);\n\n\tassert (J.rows() == 6 && J.cols() == (int)joint_mapping.size() );\n\n\tJ.setZero();\n\n\t// we have to make sure that only the joints that contribute to the\n\t// bodies motion also get non-zero columns in the jacobian.\n\t// VectorNd e = VectorNd::Zero(Q.size() + 1);\n\tchar *e = new char[model.dof_count + 1];\n\tif (e == NULL) {\n\t\tstd::cerr << \"Error: allocating memory.\" << std::endl;\n\t\tabort();\n\t}\n\tmemset (&e[0], 0, model.dof_count + 1);\n\n\tunsigned int reference_body_id = body_id;\n\n\tif (model.IsFixedBodyId(body_id)) {\n\t\tunsigned int fbody_id = body_id - model.fixed_body_discriminator;\n\t\treference_body_id = model.mFixedBodies[fbody_id].mMovableParent;\n\t}\n\n\tunsigned int j = reference_body_id;\n\n\t// e[j] is set to 1 if joint j contributes to the jacobian that we are\n\t// computing. For all other joints the column will be zero.\n\t\n\twhile (j != 0) {\n\t\te[j] = 1;\n\t\tj = model.lambda[j];\n\t}\n\t\n\tfor (j = 1; j < model.mBodies.size(); j++) {\n\t\tif (e[j] == 1) {\n\t\t\tSpatialVector S_base;\n\t\t\tS_base = point_trans * spatial_inverse(model.X_base[j].toMatrix()) * model.S[j];\n\n\t\t\t// Map back from the rbdl indices\n\t\t\tint i = std::find(joint_mapping.begin(), joint_mapping.end(), j) - joint_mapping.begin();\n\t\t\t\t\t\n\t\t\tJ.col(i) = S_base;\n\t\t}\n\t}\n\t\n\tdelete[] e;\n}\n\n/**\n * Computes Selectively Damped Least Squares as described by Buss and Kim in:\n * \n * Buss, Samuel R., and Jin-Su Kim. \"Selectively damped least squares for inverse kinematics.\" journal of graphics, gpu, and game tools 10.3 (2005): 37-49.\n * \n * \\param jacobian   \tthe current jacobian\n * \\param e       \tthe pose diff between the end effector and the desired target pose\n * \\param modifiedJ \ta matrix where the modified jacobian will be stored in\n * \\param invModifiedJ \ta matrix where the inverse of the modified jacobian will be stored in\n */\ntemplate<typename _Matrix_Type_>\nvoid sdls(const _Matrix_Type_ &jacobian, Eigen::VectorXd &e, Eigen::MatrixXd &modifiedJ, Eigen::MatrixXd &invModifiedJ, double gamma_max = 0.78539816) //PI/4\n{\t\n\tunsigned int cols = jacobian.cols();\n\tunsigned int rows = jacobian.rows();\n\t\n\t// Calculate the norms of columns of the jacobian\n\tEigen::VectorXd p(cols);\n\tfor(unsigned int j = 0; j<cols; j++)\n\t{\n\t\tp(j) = jacobian.col(j).norm();\n\t}\n\n\tEigen::JacobiSVD< _Matrix_Type_ > svd(jacobian ,Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n\tEigen::VectorXd alpha(rows);\n\tfor(unsigned int i = 0; i<rows; i++)\n\t{\n\t\talpha(i) = svd.matrixU().col(i).transpose() * e;\n\t}\n\t\n\t// Calculate the norms of U\n\tEigen::VectorXd N(rows); // each component of N is 1\n\tfor(unsigned int i = 0; i<rows; i++)\n\t{\n\t\tN(i) = svd.matrixU().col(i).norm();\n\t}\n\t\n\tEigen::VectorXd M(rows);\n\tfor(unsigned int i = 0; i<rows; i++)\n\t{\n\t\tif(std::abs(svd.singularValues()(i)) < 1.0e-4)\n\t\t\tcontinue;\n\t\t\n\t\tdouble tmp = 0.0;\n\t\tfor(unsigned int j = 0; j<cols; j++)\n\t\t{\n\t\t\ttmp += std::abs(svd.matrixV()(j, i)) * p(j);\n\t\t}\n\t\t\n\t\tM(i) = (1.0/svd.singularValues()(i)) * tmp;\n\t}\n\t\n\tEigen::VectorXd gamma(rows);\n\tgamma.setConstant(gamma_max);\n\tfor(unsigned int i = 0; i<rows; i++)\n\t{\n\t\tif(std::abs(svd.singularValues()(i)) < 1.0e-4)\n\t\t\tcontinue;\n\t\t\n\t\tif(N(i)<M(i))\n\t\t{\n\t\t\tgamma(i) *= N(i)/M(i);\n\t\t}\n\t}\n\t\n\tmodifiedJ.setZero();\n\tinvModifiedJ.setZero();\n\t\n\tfor(unsigned int i=0; i<rows; i++)\n\t{\n\t\tif(std::abs(svd.singularValues()(i)) < 1.0e-4)\n\t\t\tcontinue;\n\t\t\n\t\tEigen::VectorXd phi_tmp = (1.0/svd.singularValues()(i)) * alpha(i) * svd.matrixV().col(i);\n\t\tdouble max = phi_tmp.maxCoeff();\n\t\t\n\t\tEigen::MatrixXd modifiedJtmp(rows, cols);\n\t\tmodifiedJtmp = svd.singularValues()(i) * svd.matrixU().col(i) * svd.matrixV().col(i).transpose();\n\t\t\n\t\tEigen::MatrixXd invModifiedJtmp(cols, rows);\n\t\tinvModifiedJtmp = (1.0/svd.singularValues()(i)) * svd.matrixV().col(i) * svd.matrixU().col(i).transpose();\n\t\t\n\t\tif(gamma(i) < max)\n\t\t{\n\t\t\tinvModifiedJtmp *= (gamma(i)/max);\t\n\t\t\tmodifiedJtmp *= (max/gamma(i));\n\t\t}\n\t\t\n\t\tmodifiedJ += modifiedJtmp;\n\t\tinvModifiedJ += invModifiedJtmp;\n\t}\n}\n\n\nnamespace apc_kinematics\n{\n\nAPCKinematics::APCKinematics() \n : m_param_max_iterations(\"/ik/max_iterations\", 1, 1, 100, 20)\n , m_param_max_posdiff(\"/ik/max_posdiff\", 0.0, 0.01, 1.0, 0.1)\n , m_param_angle_weight_slope(\"/ik/angle_weight_slope\", -10.0, 0.1, 0.0, -4.0)\n , m_param_nullspace_optimization(\"/ik/nullspace_optimization\", true)\n , m_param_weight_convenient(\"/ik/cost/weight_convenient\", 0.0, 0.1, 10.0, 1.0)\n , m_param_weight_seed(\"/ik/cost/weight_seed\", 0.0, 0.1, 10.0, 1.0)\n , m_param_weight_limit(\"/ik/cost/weight_limit\", 0.0, 0.1, 10.0, 1.0)\n , m_param_alpha(\"/ik/alpha\", 0.0, 0.01, 1.0, 0.05)\n , m_param_alpha_decay(\"/ik/alpha_decay\", 0.0, 0.01, 1.0, 0.9)\n , m_param_eef_enabled(\"/ik/eef/enabled\", true)\n , m_param_eef_soft_limit_x(\"/ik/eef/soft_limit/x\", 0.0, 0.001, 1.5, 0.005)\n , m_param_eef_soft_limit_z(\"/ik/eef/soft_limit/z\", 0.0, 0.001, 1.5, 0.005)\n , m_param_eef_s(\"/ik/eef/s\", 0.0, 0.001, 5000.0, 0.5)\n , m_param_eef_orient(\"/ik/eef/orient\", 0.0, 0.001, 5000.0, 0.5)\n , m_ik_limit_link(-1)\n{\n}\n\nAPCKinematics::~APCKinematics()\n{\n}\n\nbool APCKinematics::initialize(const std::string& robot_description,\n\tconst std::string& group_name,\n\tconst std::string& base_frame,\n\tconst std::string& tip_frame,\n\tdouble search_discretization)\n{\n\tROS_INFO(\"IK base frame: %s\", base_frame.c_str());\n\tsetValues(robot_description, group_name, base_frame, tip_frame, search_discretization);\n\n\t// Robot model (from URDF model on parameter server)\n\tm_urdf = boost::make_shared<urdf::Model>();\n\tif(!m_urdf->initParam(robot_description))\n\t{\n\t\tROS_ERROR(\"Could not get URDF model\");\n\t\treturn false;\n\t}\n\n\tm_rbdl.initFrom(*m_urdf, base_frame);\n\t\n\tm_srdf = loadSRDF();\n\t\n\t// ... and search for the convenient state and the weighting\n\tbool convenient_state_found = false;\n\tbool weighting_found = false;\n\tstd::vector<srdf::Model::GroupState> groupStates = m_srdf->getGroupStates();\n\tfor(unsigned int i=0; i<groupStates.size(); ++i)\n\t{\n\t\tif(groupStates[i].group_ == group_name && groupStates[i].name_.substr(0, 10) == \"convenient\")\n\t\t{\n\t\t\tm_convenient_state = groupStates[i];\n\t\t\tconvenient_state_found = true;\n\t\t}\n\t\telse if(groupStates[i].group_ == group_name && groupStates[i].name_.substr(0, 9) == \"weighting\")\n\t\t{\n\t\t\tm_weighting = groupStates[i];\n\t\t\tweighting_found = true;\n\t\t}\n\t}\n\t\n\t// we can only use the nullspace opimization if these states exist\n\tm_nullspaceOptimization = weighting_found && convenient_state_found;\n\tif(!m_nullspaceOptimization)\n\t{\n\t\tROS_WARN_STREAM(\"Unable to find convenient state or weighting for group \"<<group_name<<\". Disabling nullspace optimization!\");\t\n\t}\n\n\tunsigned int base_id = m_rbdl.GetBodyId(base_frame.c_str());\n\tif(base_id == (unsigned int)-1)\n\t{\n\t\tROS_ERROR(\"Could not find base frame '%s'\", base_frame.c_str());\n\t\treturn false;\n\t}\n\n\tunsigned int tip = m_rbdl.GetBodyId(tip_frame.c_str());\n\tif(tip == (unsigned int)-1)\n\t{\n\t\tROS_ERROR(\"Could not find tip_frame '%s'\", tip_frame.c_str());\n\t\treturn false;\n\t}\n\n\tif(tip >= m_rbdl.fixed_body_discriminator)\n\t{\n\t\tm_fixedTrans = m_rbdl.mFixedBodies[tip - m_rbdl.fixed_body_discriminator].mParentTransform;\n\t\tm_tip = m_rbdl.mFixedBodies[tip - m_rbdl.fixed_body_discriminator].mMovableParent;\n\t}\n\telse\n\t{\n\t\tm_fixedTrans.E.setIdentity();\n\t\tm_fixedTrans.r.setZero();\n\t\tm_tip = tip;\n\t}\n\n\tdo\n\t{\n\t\tm_links.push_back(tip);\n\t\tm_linkNames.push_back(m_rbdl.GetBodyName(tip));\n\n\t\tif(tip < m_rbdl.fixed_body_discriminator)\n\t\t{\n\t\t\tm_joints.push_back(tip);\n\t\t\tm_jointNames.push_back(m_rbdl.jointName(tip));\n\n\t\t\tboost::shared_ptr<const urdf::Joint> urdfJoint = m_urdf->getJoint(m_jointNames.back());\n\n\t\t\tdouble epsilon;\n\t\t\tif(urdfJoint->type == urdf::Joint::PRISMATIC)\n\t\t\t\tepsilon = 0.001;\n\t\t\telse\n\t\t\t\tepsilon = 2.0 * (M_PI / 180.0);\n\n\t\t\tm_upperLimit.push_back(urdfJoint->limits->upper - epsilon);\n\t\t\tm_lowerLimit.push_back(urdfJoint->limits->lower + epsilon);\n\n\t\t\tROS_DEBUG(\"Solver: Link '%s' with parent joint '%s' (limits: %f to %f)\",\n\t\t\t\tm_linkNames.back().c_str(),\n\t\t\t\tm_jointNames.back().c_str(),\n\t\t\t\tm_lowerLimit.back(), m_upperLimit.back()\n\t\t\t);\n\n\t\t\ttip = m_rbdl.lambda[tip];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tROS_DEBUG(\"Fixed transform link '%s'\", m_linkNames.back().c_str());\n\t\t\ttip = m_rbdl.mFixedBodies[tip - m_rbdl.fixed_body_discriminator].mMovableParent;\n\t\t}\n\t}\n\twhile(tip != 0);\n\n\tm_rbdlMeasuredJointAngles = Eigen::VectorXd::Zero(m_rbdl.dof_count);\n\tm_sub_js = ros::NodeHandle().subscribe(\"/joint_states\", 1,\n\t\t&APCKinematics::handleJointStates, this\n\t);\n\n\t// Disable eef nullspace for arm-only IK\n\tif(group_name.find(\"arm_with_eef\") != std::string::npos)\n\t{\n\t\tm_worldLink = m_rbdl.GetBodyId(\"world\");\n\t\tm_ik_limit_link = m_rbdl.GetBodyId(\"ik_limit_link\");\n\t\tm_ik_wrist_link = m_rbdl.GetBodyId(\"wrist_2_link\");\n\t}\n\telse\n\t{\n\t\tm_worldLink = m_ik_limit_link =  std::numeric_limits<unsigned int>::max();\n\t\tm_ik_wrist_link = std::numeric_limits<unsigned int>::max();\n\t}\n\n\tROS_INFO(\"world link: %u, ik finger link: %u\", m_worldLink, m_ik_limit_link);\n\n\tm_pub_elbowMarker = ros::NodeHandle().advertise<visualization_msgs::MarkerArray>(\n\t\t\"/ik/\" + group_name + \"/elbow\", 1\n\t);\n\n\tstd::string ignoreRoll_param = \"/robot_description_kinematics/\" + group_name + \"/apc_kinematics_ignore_roll\";\n\tros::NodeHandle nh;\n\tnh.param(ignoreRoll_param, m_ignoreRoll, false);\n\n\tROS_INFO(\"Group '%s' is %s roll.\", group_name.c_str(), m_ignoreRoll ? \"ignoring\" : \"not ignoring\");\n\n\tm_limitMarkers.markers.resize(LIMIT_COUNT);\n\tm_limitMarkers.markers[LIMIT_X].type = visualization_msgs::Marker::CUBE;\n\tm_limitMarkers.markers[LIMIT_X].header.frame_id = \"world\";\n\tm_limitMarkers.markers[LIMIT_X].id = LIMIT_X;\n\tm_limitMarkers.markers[LIMIT_X].scale.x = 0.01;\n\tm_limitMarkers.markers[LIMIT_X].scale.y = 5.0;\n\tm_limitMarkers.markers[LIMIT_X].scale.z = 5.0;\n\tm_limitMarkers.markers[LIMIT_X].color.r = 1.0;\n\tm_limitMarkers.markers[LIMIT_X].color.a = 0.3;\n\tm_limitMarkers.markers[LIMIT_X].pose.orientation.w = 1.0;\n\n\tm_limitMarkers.markers[LIMIT_Z].type = visualization_msgs::Marker::CUBE;\n\tm_limitMarkers.markers[LIMIT_Z].header.frame_id = \"world\";\n\tm_limitMarkers.markers[LIMIT_Z].id = LIMIT_Z;\n\tm_limitMarkers.markers[LIMIT_Z].scale.x = 5.0;\n\tm_limitMarkers.markers[LIMIT_Z].scale.y = 5.0;\n\tm_limitMarkers.markers[LIMIT_Z].scale.z = 0.01;\n\tm_limitMarkers.markers[LIMIT_Z].color.b = 1.0;\n\tm_limitMarkers.markers[LIMIT_Z].color.a = 0.3;\n\tm_limitMarkers.markers[LIMIT_Z].pose.orientation.w = 1.0;\n\n\tm_limitMarkers.markers[LIMIT_TABLE].type = visualization_msgs::Marker::CUBE;\n\tm_limitMarkers.markers[LIMIT_TABLE].header.frame_id = \"base_link\";\n\tm_limitMarkers.markers[LIMIT_TABLE].id = LIMIT_TABLE;\n\tm_limitMarkers.markers[LIMIT_TABLE].scale.x = 0.01;\n\tm_limitMarkers.markers[LIMIT_TABLE].scale.y = 5.0;\n\tm_limitMarkers.markers[LIMIT_TABLE].scale.z = 5.0;\n\tm_limitMarkers.markers[LIMIT_TABLE].color.b = 1.0;\n\tm_limitMarkers.markers[LIMIT_TABLE].color.a = 0.3;\n\n\tm_pub_limitMarkers = nh.advertise<visualization_msgs::MarkerArray>(\"limit_markers\", 1);\n\n\treturn true;\n}\n\nbool APCKinematics::getPositionIK(const geometry_msgs::Pose &ik_pose,\n\tconst std::vector<double> &ik_seed_state,\n\tstd::vector<double> &solution,\n\tmoveit_msgs::MoveItErrorCodes &error_code,\n\tconst kinematics::KinematicsQueryOptions &options) const\n{\n\tROS_INFO(\"1\");\n\treturn false;\n}\n\nbool APCKinematics::searchPositionIK(const geometry_msgs::Pose &ik_pose,\n\tconst std::vector<double> &ik_seed_state,\n\tdouble timeout,\n\tstd::vector<double> &solution,\n\tmoveit_msgs::MoveItErrorCodes &error_code,\n\tconst kinematics::KinematicsQueryOptions &options) const\n{\n\tROS_INFO(\"2\");\n\treturn false;\n}\n\nstatic Eigen::Vector3d getEuler(const Eigen::Matrix3d& R)\n{\n// \tEigen::Vector3d e = mat.eulerAngles(2,1,0);\n// \treturn Eigen::Vector3d(e[2], e[1], e[0]);\n// \treturn mat.eulerAngles(0,1,2);\n\n\tEigen::Vector3d p;\n\n\t// euler angles\n\tp( 1 ) = atan2( -R( 2, 0 ), sqrtf( R( 0, 0 )*R( 0, 0 ) + R( 1, 0 )*R( 1, 0 ) ) );\n\tif( fabs( p( 1 ) - 0.5*M_PI ) < 1e-5 ) {\n\t\tp( 2 ) = 0;\n\t\tp( 0 ) = atan2( R( 0, 1 ), R( 1, 1 ) );\n\t}\n\telse if( fabs( p( 1 ) + 0.5*M_PI ) < 1e-5 ) {\n\t\tp( 2 ) = 0;\n\t\tp( 0 ) = -atan2( R( 0, 1 ), R( 1, 1 ) );\n\t}\n\telse {\n\t\tp( 0 ) = atan2( R( 2, 1 ) / cos( p( 1 ) ), R( 2, 2 ) / cos( p( 1 ) ) );\n\t\tp( 2 ) = atan2( R( 1, 0 ) / cos( p( 1 ) ), R( 0, 0 ) / cos( p( 1 ) ) );\n\t}\n\n\treturn p;\n}\n\nstatic Eigen::VectorXd calcPoseDiff(const Eigen::Affine3d& current, const Eigen::Affine3d& target, bool ignoreXRotation)\n{\n\tEigen::VectorXd ret(6);\n\n\tif(ignoreXRotation)\n\t{\n\t\t// Find minimum rotation to rotate target.x onto current.x\n\t\tEigen::Vector3d axis = target.rotation().col(0).cross(current.rotation().col(0));\n\t\tdouble norm = axis.norm();\n\t\tif(norm < 1e-10)\n\t\t\tret.head<3>().setZero();\n\t\telse\n\t\t{\n\t\t\tdouble angle = asin(norm);\n\t\t\taxis.normalize();\n\n\t\t\tEigen::Matrix3d rot;\n\t\t\trot = Eigen::AngleAxisd(angle, axis);\n\n\t\t\tret.head<3>() = getEuler(rot);\n\t\t}\n\t}\n\telse\n\t{\n\t\tret.head<3>() = getEuler(current.rotation() * target.rotation().transpose());\n\t}\n\n\tret.tail<3>() = current.translation() - target.translation();\n\n\treturn ret;\n}\n\nvoid APCKinematics::costFunction(int joint, double q, double seed_q, double* cost, double *costGradient) const\n{\n\tdouble convenient = m_convenient_state.joint_values_.at(m_jointNames[joint])[0];\n\tdouble weight = m_weighting.joint_values_.at(m_jointNames[joint])[0];\n\tdouble angleDiff = 0.1 * (q - convenient);\n\tangleDiff *= pow(weight, 2.0);\n\t\n\tdouble diffFromSeed = q - seed_q;\n\n\tconst double limitStartDiff = 0.1 * M_PI;\n\tconst double limitSlope = 10.0;\n\tdouble maxJointAngleOffset = 0;\n\tdouble minJointAngleOffset = 0;\n\tdouble maxJointAngleOffsetGradient = 0;\n\tdouble minJointAngleOffsetGradient = 0;\n\n\tdouble maxJointAngleDiff = q - (m_upperLimit[joint] - limitStartDiff);\n\tif(maxJointAngleDiff > 0)\n\t{\n\t\tmaxJointAngleOffset = limitSlope * maxJointAngleDiff * maxJointAngleDiff;\n\t\tmaxJointAngleOffsetGradient = 2.0 * limitSlope * maxJointAngleDiff;\n\n// \t\tif(q > m_upperLimit[joint])\n// \t\t\tROS_INFO(\"Joint limit violation %s (%f, upper limit %f) => cost %f\", m_jointNames[joint].c_str(), q, m_upperLimit[joint], maxJointAngleOffset);\n\t}\n\n\tdouble minJointAngleDiff = q - (m_lowerLimit[joint] + limitStartDiff);\n\tif(minJointAngleDiff < 0)\n\t{\n\t\tminJointAngleOffset = limitSlope * minJointAngleDiff * minJointAngleDiff;\n\t\tminJointAngleOffsetGradient = 2.0 * limitSlope * minJointAngleDiff;\n\n// \t\tif(q < m_lowerLimit[joint])\n// \t\t\tROS_INFO(\"Joint limit violation %s (%f, lower limit %f) => cost %f\", m_jointNames[joint].c_str(), q, m_lowerLimit[joint], minJointAngleOffset);\n\t}\n\n\t*cost += m_param_weight_convenient()*angleDiff*angleDiff\n\t\t+ m_param_weight_seed()*diffFromSeed*diffFromSeed \n\t\t+ m_param_weight_limit()*(maxJointAngleOffset + minJointAngleOffset);\n\n\t*costGradient += m_param_weight_convenient() * 2.0 * angleDiff\n\t\t\t+ m_param_weight_seed()* 2.0 * diffFromSeed \n\t\t\t+ m_param_weight_limit()*(maxJointAngleOffsetGradient + minJointAngleOffsetGradient);\n}\n\n\nvoid APCKinematics::wristCostFunction(rbdl_parser::URDF_RBDL_Model& model, const Eigen::VectorXd& currentJointAngles, double* cost, Eigen::VectorXd* costGradient) const\n{\n\tEigen::MatrixXd Jwrist(6, m_joints.size());\n\n\t_CalcPointRotJacobian(model, currentJointAngles, m_joints, m_ik_limit_link, m_base, Jwrist);\n\n\t// We are only interested in the position (bottom three rows)\n// \tJwrist = Jwrist.bottomRows<3>();\n\n\tRigidBodyDynamics::Math::SpatialTransform eefTransform;\n\n\tif (m_ik_limit_link >= model.fixed_body_discriminator) {\n\t\tauto fBody = m_rbdl.mFixedBodies[m_ik_limit_link - m_rbdl.fixed_body_discriminator];\n\t\tauto fixedTransform = fBody.mParentTransform;\n\t\tauto parentPose = model.X_base[fBody.mMovableParent];\n\n\t\teefTransform.E = parentPose.E.transpose() * fixedTransform.E.transpose();\n\t\teefTransform.r = parentPose.r + parentPose.E.transpose() * fixedTransform.r;\n\t}\n\telse\n\t{\n\t\teefTransform.E = model.X_base[m_ik_limit_link].E.transpose();\n\t\teefTransform.r = model.X_base[m_ik_limit_link].r;\n\t}\n\n\tEigen::Vector3d eef = eefTransform.r;\n\n\tRigidBodyDynamics::Math::SpatialTransform worldTransform;\n\n\t// TODO: Can we extract this piece of code? It is used everywhere.\n\tif((unsigned int)m_worldLink >= model.fixed_body_discriminator)\n\t{\n\t\tauto fBody = m_rbdl.mFixedBodies[m_worldLink - m_rbdl.fixed_body_discriminator];\n\t\tauto fixedTransform = fBody.mParentTransform;\n\t\tauto parentPose = model.X_base[fBody.mMovableParent];\n\n\t\tworldTransform.E = fixedTransform.E * parentPose.E;\n\t\tworldTransform.r = parentPose.r + parentPose.E.transpose() * fixedTransform.r;\n\t}\n\telse\n\t\tworldTransform = model.X_base[m_worldLink];\n\n\t// Transform elbow and Jelbow into base_link\n\teef = RigidBodyDynamics::CalcBaseToBodyCoordinates(\n\t\tmodel, Eigen::VectorXd(), m_worldLink, eef, false\n\t);\n\tJwrist.topRows<3>() = worldTransform.E * Jwrist.topRows<3>();\n\tJwrist.bottomRows<3>() = worldTransform.E * Jwrist.bottomRows<3>();\n\n\tvisualization_msgs::MarkerArray markers;\n\t{\n\t\tvisualization_msgs::Marker marker;\n\t\tmarker.header.frame_id = \"base_link\";\n\t\tmarker.header.stamp = ros::Time::now();\n\n\t\tmarker.action = marker.ADD;\n\n\t\tmarker.id = 0;\n\t\tmarker.type = marker.SPHERE;\n\n\t\tmarker.scale.x = 0.1;\n\t\tmarker.scale.y = 0.1;\n\t\tmarker.scale.z = 0.1;\n\n\t\tmarker.pose.position.x = eef.x();\n\t\tmarker.pose.position.y = eef.y();\n\t\tmarker.pose.position.z = eef.z();\n\n\t\tmarker.pose.orientation.w = 1.0;\n\n\t\tmarker.color.a = 1.0;\n\t\tmarker.color.r = 1.0;\n\n\t\tmarkers.markers.push_back(marker);\n\t}\n\n\tm_pub_elbowMarker.publish(markers);\n\n\tdouble colCost = 0;\n\tEigen::VectorXd cost_gradient(m_joints.size());\n\tcost_gradient.setZero();\n\n\tm_limitMarkers.markers[LIMIT_X].pose.position.x = m_param_eef_soft_limit_x();\n\tm_limitMarkers.markers[LIMIT_Z].pose.position.z = m_param_eef_soft_limit_z();\n\n\tif(eef.z() < m_param_eef_soft_limit_z())\n\t{\n\t\tdouble violation = eef.z() - m_param_eef_soft_limit_z();\n\n\t\t// translation\n\t\tcolCost += m_param_eef_s() * pow(violation, 2);\n\n\t\t// fifth row of Jwrist: z component\n\t\tcost_gradient += (2.0 * m_param_eef_s() * violation) * Jwrist.row(5);\n\n\t\t// orientation\n// \t\tdouble pitch = getEuler(eefTransform.E)[1];\n// \t\tcolCost += m_param_eef_orient() * pow(pitch, 2);\n// \t\tcost_gradient += (2.0 * m_param_eef_orient() * pitch) * Jwrist.row(5);\n\t}\n\n\tif(eef.x() > m_param_eef_soft_limit_x())\n\t{\n\t\tdouble violation = eef.x() - m_param_eef_soft_limit_x();\n\n\t\t// translation\n\t\tcolCost += m_param_eef_s() * pow(violation, 2);\n\n\t\t// third row of Jwrist: x component\n\t\tcost_gradient += (2.0 * m_param_eef_s() * violation) * Jwrist.row(3);\n\n\t\t// orientation\n// \t\tdouble pitch = getEuler(eefTransform.E)[1];\n// \t\tcolCost += m_param_eef_orient() * pow(pitch, 2);\n// \t\tcost_gradient += (2.0 * m_param_eef_orient() * pitch) * Jwrist.row(3);\n\t}\n\n\t*cost += colCost;\n\t*costGradient += cost_gradient;\n}\n\nvoid APCKinematics::tableCostFunction(rbdl_parser::URDF_RBDL_Model& model, const Eigen::VectorXd& currentJointAngles, double* cost, Eigen::VectorXd* costGradient) const\n{\n\tEigen::MatrixXd Jwrist(6, m_joints.size());\n\n\t_CalcPointRotJacobian(model, currentJointAngles, m_joints, m_ik_wrist_link, m_base, Jwrist);\n\n\t// We are only interested in the position (bottom three rows)\n// \tJwrist = Jwrist.bottomRows<3>();\n\n\tRigidBodyDynamics::Math::SpatialTransform eefTransform;\n\n\tif (m_ik_wrist_link >= model.fixed_body_discriminator) {\n\t\tauto fBody = m_rbdl.mFixedBodies[m_ik_wrist_link - m_rbdl.fixed_body_discriminator];\n\t\tauto fixedTransform = fBody.mParentTransform;\n\t\tauto parentPose = model.X_base[fBody.mMovableParent];\n\n\t\teefTransform.E = parentPose.E.transpose() * fixedTransform.E.transpose();\n\t\teefTransform.r = parentPose.r + parentPose.E.transpose() * fixedTransform.r;\n\t}\n\telse\n\t{\n\t\teefTransform.E = model.X_base[m_ik_wrist_link].E.transpose();\n\t\teefTransform.r = model.X_base[m_ik_wrist_link].r;\n\t}\n\n\tEigen::Vector3d eef = eefTransform.r;\n\n\tconstexpr double planeAngle = 40.0 * M_PI / 180.0;\n\tEigen::Vector3d planeNormal(0.0, cos(planeAngle), sin(planeAngle));\n\n\tdouble planeDist = 0.45;\n\n\t{\n\t\tEigen::Matrix3d rot;\n\t\trot.col(0) = planeNormal;\n\t\trot.col(1) = -Eigen::Vector3d::UnitX();\n\t\trot.col(2) = rot.col(0).cross(rot.col(1));\n\n\t\tEigen::Affine3d pose;\n\t\tpose = Eigen::Translation3d(planeNormal * planeDist) * rot;\n\n\t\ttf::poseEigenToMsg(pose, m_limitMarkers.markers[LIMIT_TABLE].pose);\n\t}\n\n\tROS_INFO_STREAM(\"eef: \" << eef.transpose());\n\n\tdouble violation = -planeNormal.dot(eef) + planeDist;\n\n\tdouble colCost = 0;\n\tEigen::VectorXd cost_gradient(m_joints.size());\n\tcost_gradient.setZero();\n\n\tROS_INFO(\"violation: %f\", violation);\n\n\tif(violation > 0.0)\n\t{\n\t\tcolCost += m_param_eef_s() * pow(violation, 2);\n\t\tcost_gradient += -(2.0 * m_param_eef_s() * violation) * (planeNormal.transpose() * Jwrist.bottomRows<3>());\n\t}\n\n\t*cost += colCost;\n\t*costGradient += cost_gradient;\n}\n\n\nbool APCKinematics::searchPositionIK(const geometry_msgs::Pose &ik_pose,\n\tconst std::vector<double> &ik_seed_state,\n\tdouble timeout,\n\tconst std::vector<double> &consistency_limits,\n\tstd::vector<double> &solution,\n\tmoveit_msgs::MoveItErrorCodes &error_code,\n\tconst kinematics::KinematicsQueryOptions &options) const\n{\n\tROS_DEBUG(\"IK start\");\n\tros::Time startTime = ros::Time::now();\n\n\trbdl_parser::URDF_RBDL_Model model = m_rbdl;\n\n\tconst double convergence_threshold_posdiff = 1e-6;\n\tconst double convergence_threshold_anglediff = 1e-6;\n\tconst double convergence_threshold_costdiff = 1e-6;\n\tconst double alpha = m_param_alpha();\n\tconst int max_iterations = m_param_max_iterations();\n\tbool nullspace_optimization = m_nullspaceOptimization && m_param_nullspace_optimization();\n\tfloat max_posdiff = m_param_max_posdiff();\n// \tfloat angle_weight_slope = m_param_angle_weight_slope();\n\t\n\tint numJoints = m_joints.size();\n\t\n\tEigen::VectorXd startJointAngles = Eigen::VectorXd::Zero(numJoints);\n\tfor(unsigned int i = 0; i < ik_seed_state.size(); ++i)\n\t\tstartJointAngles[i] = ik_seed_state[i];\n\t\n\tEigen::VectorXd currentJointAngles = startJointAngles;\n\tEigen::Affine3d currentEndEffectorPose;\n\t\n\tEigen::Affine3d targetEndEffectorPose;\n\t{\n\t\tEigen::Affine3d pose;\n\t\ttf::poseMsgToEigen(ik_pose, targetEndEffectorPose);\n\t}\n\n\tEigen::VectorXd poseDiff;\n\tdouble posdiff;\n\tdouble anglediff;\n\tdouble lastCost = 0;\n\tdouble cost = 0;\n\tEigen::VectorXd costGradient = Eigen::VectorXd::Zero(numJoints);\n\tdouble costdiff;\n\n\tint iteration = 0;\n\tbool singular = false;\n\n\tbool haveEEF = m_param_eef_enabled()\n\t\t\t&& m_ik_limit_link < std::numeric_limits<unsigned int>::max()\n\t\t\t&& m_worldLink < std::numeric_limits<unsigned int>::max();\n\n\twhile(iteration < max_iterations)\n\t{\n\t\t// Copy the current joint angles into rbdl convention and update the model\n\t\t// start at the current measured joint angles for the joints that we\n\t\t// do not control in this solver.\n\t\tEigen::VectorXd tmpJoints = m_rbdlMeasuredJointAngles;\n\t\tfor(unsigned int i = 0; i < m_joints.size(); ++i)\n\t\t\ttmpJoints[m_joints[i]-1] = currentJointAngles[i];\n\t\tRigidBodyDynamics::UpdateKinematicsCustom(model, &tmpJoints, 0, 0);\n\n\t\t// Calculate the current end effector pose...\n\t\tconst auto& X = model.X_base[m_tip];\n\t\tcurrentEndEffectorPose.setIdentity();\n\t\tcurrentEndEffectorPose.translate(X.r + X.E.transpose() * m_fixedTrans.r);\n\t\tcurrentEndEffectorPose.rotate(X.E.transpose() * m_fixedTrans.E.transpose());\n\n\t\tposeDiff = calcPoseDiff(currentEndEffectorPose, targetEndEffectorPose, m_ignoreRoll);\n\t\t\n\t\tposdiff = poseDiff.tail<3>().norm();\n\t\tanglediff = poseDiff.head<3>().norm();\n\n\t\t// Weighting matrix for poseDiff\n\t\tEigen::MatrixXd W = Eigen::MatrixXd::Identity(6, 6);\n\t\t\n\t\tif(posdiff > max_posdiff)\n\t\t{\n\t\t\t// Limit the maximal translational posediff\n\t\t\tposeDiff.tail<3>() *= (max_posdiff/posdiff);\n\t\t\t\n// \t\t\tdouble angle_weight =  std::max(1 + angle_weight_slope * (posdiff-max_posdiff), 0.0);\n// \t\t\t\n// \t\t\tW(0,0) = angle_weight;\n// \t\t\tW(1,1) = angle_weight;\n// \t\t\tW(2,2) = angle_weight;\n\t\t}\n\t\t\n\t\tposeDiff = W * poseDiff;\n\n\t\tcost = 0;\n\t\tcostGradient.setZero();\n\t\tbool nullSpaceActive = false;\n\n\t\tif(haveEEF)\n\t\t{\n\t\t\twristCostFunction(model, currentJointAngles, &cost, &costGradient);\n\t\t\ttableCostFunction(model, currentJointAngles, &cost, &costGradient);\n\n\t\t\tnullSpaceActive = true;\n\t\t}\n\n\t\tif(nullspace_optimization)\n\t\t{\n\t\t\t// Calculate the costs for the current state\n\t\t\tfor(unsigned int i = 0; i < m_joints.size(); ++i)\n\t\t\t\tcostFunction(i, currentJointAngles[i], startJointAngles[i], &cost, &costGradient[i]);\n\n\t\t\tnullSpaceActive = true;\n\t\t}\n\n\t\tcostdiff = std::abs(lastCost - cost);\n\n\t\tif( posdiff < convergence_threshold_posdiff\n\t\t && anglediff < convergence_threshold_anglediff\n\t\t && costdiff < convergence_threshold_costdiff)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tlastCost = cost;\n\n\t\tEigen::MatrixXd J(6, numJoints);\n\t\t_CalcPointRotJacobian(model, currentJointAngles, m_joints, m_links.front(), m_base, J);\n\n\t\tif(m_ignoreRoll)\n\t\t{\n\t\t\t// remove the local roll from the jacobian to allow null space optimization to use it\n\n\t\t\t// convert rotation part into local frame\n\t\t\tJ.topRows<3>() = targetEndEffectorPose.rotation().transpose() * J;\n\n\t\t\t// zero roll\n\t\t\tJ.row(0).setZero();\n\n\t\t\t// convert back into global frame\n\t\t\tJ.topRows<3>() = targetEndEffectorPose.rotation() * J;\n\t\t}\n\n\t\tJ = W*J;\n\t\t\n\t\tEigen::MatrixXd modifiedJ(6, numJoints);\n\t\tEigen::MatrixXd invModifiedJ(numJoints, 6);\n\t\t\n\t\tsdls(J, poseDiff, modifiedJ, invModifiedJ);\n\t\t\n\t\tif(invModifiedJ.maxCoeff() > 1e4 || invModifiedJ.minCoeff() < -1e4)\n\t\t{\n\t\t\tROS_WARN(\"invModifiedJ nearly singular\");\n\t\t\titeration = max_iterations;\n\t\t\tsingular = true;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tif(modifiedJ.maxCoeff() > 1e4 || modifiedJ.minCoeff() < -1e4)\n\t\t{\n\t\t\tROS_WARN(\"modifiedJ nearly singular\");\n\t\t\titeration = max_iterations;\n\t\t\tsingular = true;\n\t\t\tbreak;\n\t\t}\n\n \t\tEigen::VectorXd thetaDiff = invModifiedJ * poseDiff;\n\t\t\n\t\tif(nullSpaceActive)\n\t\t{\n\t\t\tEigen::MatrixXd nullspace = Eigen::MatrixXd::Identity(numJoints, numJoints);\n\t\t\t\n\t\t\t// Since the inverse of the jacobian is computed with some damping, the correct nullspace needs also to be computed with a similarly modified jacobian\n\t\t\tnullspace = nullspace - invModifiedJ * modifiedJ;\n\n\t\t\t//decrease the step size in each iteration\n\t\t\tdouble stepsize = alpha * pow(m_param_alpha_decay(), iteration);\n\t\t\t\n\t\t\tthetaDiff += stepsize * nullspace * costGradient;\n\t\t}\n\t\t\n\t\tcurrentJointAngles -= thetaDiff;\n\n\t\titeration++;\n\t\t\n\t\tpruneToLimits(currentJointAngles);\n\t}\n\n\tif(singular) // This should never happen\n\t{\n\t\tROS_INFO(\"No solution found :-(\");\n\t\treturn false;\n\t}\n\n\tsolution.resize(m_joints.size());\n\n\t// This should never happen\n\tfor(unsigned int i = 0; i < m_joints.size(); ++i)\n\t{\n\t\tif(!std::isfinite(currentJointAngles[i]))\n\t\t{\n\t\t\tROS_ERROR(\"NaN in kinematics on joint %d, reporting failure...\", i);\n\t\t\treturn false;\n\t\t}\n\t\tsolution[i] = currentJointAngles[i];\n\t}\n\n \tROS_DEBUG_STREAM(\"IK end (\" << iteration << \" iter).\"/* Solutions: \" << currentJointAngles.transpose()*/);\n\t\n\tROS_DEBUG_STREAM(\"IK end, posdiff: \"<<posdiff<<\" , anglediff: \"<<anglediff);\n\t\n\tros::Time endTime = ros::Time::now();\n       \n\tros::Duration ik_time = endTime - startTime;\n\tROS_DEBUG_STREAM(\"IK end, ik_time in millis: \"<<(ik_time.toSec()*1000.0));\n\n\tm_pub_limitMarkers.publish(m_limitMarkers);\n\n\t\n\t//TODO limit the maximal amount the joint angles are allowed to differ from the start angles\n\n\treturn true;\n}\n\nvoid APCKinematics::pruneToLimits(Eigen::VectorXd &state) const\n{\n\tfor(unsigned int i = 0; i< m_joints.size(); ++i)\n\t{\n\t\tif(state[i] > m_upperLimit[i])\n\t\t{\n\t\t\tstate[i] = m_upperLimit[i];\n\t\t}\n\t\telse if(state[i] < m_lowerLimit[i]) \n\t\t{\n\t\t\tstate[i] = m_lowerLimit[i];\n\t\t}\n\t}\n}\n\nbool APCKinematics::isStateValid(std::vector<double> &state) const\n{\n\tbool result = true;\n\tfor(unsigned int i = 0; i< m_joints.size(); ++i) \n\t{\n\t\tif(state[i] > m_upperLimit[i] || state[i] < m_lowerLimit[i]) \n\t\t{\n\t\t\tresult = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\treturn result;\n}\n\nbool APCKinematics::searchPositionIK(const geometry_msgs::Pose &ik_pose,\n\tconst std::vector<double> &ik_seed_state,\n\tdouble timeout,\n\tstd::vector<double> &solution,\n\tconst IKCallbackFn &solution_callback,\n\tmoveit_msgs::MoveItErrorCodes &error_code,\n\tconst kinematics::KinematicsQueryOptions &options) const\n{\n\tROS_INFO(\"4\");\n\treturn false;\n}\n\nbool APCKinematics::searchPositionIK(const geometry_msgs::Pose &ik_pose,\n\tconst std::vector<double> &ik_seed_state,\n\tdouble timeout,\n\tconst std::vector<double> &consistency_limits,\n\tstd::vector<double> &solution,\n\tconst IKCallbackFn &solution_callback,\n\tmoveit_msgs::MoveItErrorCodes &error_code,\n\tconst kinematics::KinematicsQueryOptions &options) const\n{\n\tROS_INFO(\"5\");\n\treturn false;\n}\n\nbool APCKinematics::getPositionFK(const std::vector<std::string> &link_names,\n\tconst std::vector<double> &joint_angles,\n\tstd::vector<geometry_msgs::Pose> &poses) const\n{\n\trbdl_parser::URDF_RBDL_Model model = m_rbdl;\n\n\tif(joint_angles.size() != m_joints.size())\n\t{\n\t\tROS_ERROR(\"Got invalid joint_angles\");\n\t\treturn false;\n\t}\n\n\tEigen::VectorXd q(m_rbdl.dof_count);\n\n\tfor(unsigned int i = 0; i < m_joints.size(); ++i)\n\t{\n\t\tq[m_joints[i]-1] = joint_angles[i];\n\t}\n\n\tRigidBodyDynamics::UpdateKinematicsCustom(model, &q, 0, 0);\n\n\tposes.resize(link_names.size());\n\tfor(unsigned int i = 0; i < link_names.size(); ++i)\n\t{\n\t\tunsigned int id = model.GetBodyId(link_names[i].c_str());\n\t\tif(id == (unsigned int)-1)\n\t\t{\n\t\t\tROS_ERROR(\"Invalid link '%s' requested for forward kinematics\",\n\t\t\t\tlink_names[i].c_str()\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\n\t\tRigidBodyDynamics::Math::SpatialTransform X = model.X_base[id];\n\n\t\tEigen::Affine3d pose;\n\t\tpose.translate(X.r);\n\t\tpose.rotate(X.E.transpose());\n\n\t\ttf::poseEigenToMsg(pose, poses[i]);\n\t}\n\n\treturn true;\n}\n\nvoid APCKinematics::handleJointStates(const sensor_msgs::JointStateConstPtr& msg)\n{\n\tif(msg->name.size() != msg->position.size())\n\t\treturn;\n\n\tfor(size_t i = 0; i < msg->name.size(); ++i)\n\t{\n\t\tint index = m_rbdl.findJointIndex(msg->name[i]);\n\t\tif(index < 0)\n\t\t\tcontinue;\n\n\t\tm_rbdlMeasuredJointAngles[index-1] = msg->position[i];\n\t}\n}\n\n}\n\nPLUGINLIB_EXPORT_CLASS(apc_kinematics::APCKinematics, kinematics::KinematicsBase)\n", "meta": {"hexsha": "3ae21db1f8ddce5ce6fd93ced73daf3498600cf5", "size": 31171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nimbro_apc/kinematics/apc_kinematics/src/apc_kinematics.cpp", "max_stars_repo_name": "warehouse-picking-automation-challenges/nimbro_picking", "max_stars_repo_head_hexsha": "857eee602beea9eebee45bbb67fce423b28f9db6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2017-11-02T03:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T19:40:15.000Z", "max_issues_repo_path": "nimbro_apc/kinematics/apc_kinematics/src/apc_kinematics.cpp", "max_issues_repo_name": "warehouse-picking-automation-challenges/nimbro_picking", "max_issues_repo_head_hexsha": "857eee602beea9eebee45bbb67fce423b28f9db6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nimbro_apc/kinematics/apc_kinematics/src/apc_kinematics.cpp", "max_forks_repo_name": "warehouse-picking-automation-challenges/nimbro_picking", "max_forks_repo_head_hexsha": "857eee602beea9eebee45bbb67fce423b28f9db6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-16T02:20:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T14:06:35.000Z", "avg_line_length": 29.7433206107, "max_line_length": 168, "alphanum_fraction": 0.7060087902, "num_tokens": 9425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5010852675954144}}
{"text": "\n#ifndef PANACEA_PRIVATE_MATRIXEIGEN_H\n#define PANACEA_PRIVATE_MATRIXEIGEN_H\n#pragma once\n\n// Local PANACEA includes\n#include \"matrix/matrix.hpp\"\n\n// Third party includes\n#include <Eigen/Dense>\n\n// Standard includes\n#include <memory>\n\nnamespace panacea {\n\nclass MatrixEigen : public Matrix {\nprivate:\n  std::unique_ptr<Eigen::MatrixXd> matrix_;\n\npublic:\n  MatrixEigen();\n  virtual ~MatrixEigen() final{};\n  virtual const MatrixType type() const final;\n  virtual MatrixEigen &operator=(const MatrixEigen &mat) final;\n  virtual MatrixEigen &operator=(const Matrix &mat) final;\n  virtual double &operator()(const int row, const int col) final;\n  virtual double operator()(const int row, const int col) const final;\n\n  virtual double getDeterminant() const final;\n\n  virtual bool isZero(const double threshold) const noexcept final;\n\n  virtual void resize(const int rows, const int cols) final;\n\n  virtual void makeIdentity() final;\n  virtual void setZero() final;\n\n  virtual int rows() const final;\n  virtual int cols() const final;\n\n  virtual void print() const final;\n\n  // Local method should not be part of the interface\n  Eigen::MatrixXd pseudoInverse() const;\n};\n\nvoid pseudoInverse(Matrix &return_mat, const MatrixEigen &mat);\n\n} // namespace panacea\n\n#endif // PANACEA_PRIVATE_MATRIXEIGEN_H\n", "meta": {"hexsha": "6765afc246b8f1b16938a1232561b664664b87f0", "size": 1296, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libpanacea/matrix/matrix_eigen.hpp", "max_stars_repo_name": "lanl/PANACEA", "max_stars_repo_head_hexsha": "9779bdb6dcc3be41ea7b286ae55a21bb269e0339", "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/libpanacea/matrix/matrix_eigen.hpp", "max_issues_repo_name": "lanl/PANACEA", "max_issues_repo_head_hexsha": "9779bdb6dcc3be41ea7b286ae55a21bb269e0339", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libpanacea/matrix/matrix_eigen.hpp", "max_forks_repo_name": "lanl/PANACEA", "max_forks_repo_head_hexsha": "9779bdb6dcc3be41ea7b286ae55a21bb269e0339", "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.4528301887, "max_line_length": 70, "alphanum_fraction": 0.7546296296, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.5010852626409703}}
{"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 * Projection matrices to be used with OpenGL.\n * ****************************************************************************\n */\n\n#ifndef CAMERA_PROJECTION_MATRICES_HPP\n#define CAMERA_PROJECTION_MATRICES_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n// http://www.songho.ca/opengl/gl_projectionmatrix.html\n\nnamespace camera\n{\n    \ntemplate<typename T>\nEIGEN_DEVICE_FUNC inline Eigen::Matrix<T,4,4> getOrtographicProjection(T l, T r, T b, T t, T n, T f)\n{\n    Eigen::Matrix<T,4,4> m;\n    \n    m << T(2.0)/(r-l) , T(0.0)       , T(0.0)        , -(r+l)/(r-l),\n         T(0.0)       , T(2.0)/(t-b) , T(0.0)        , -(t+b)/(t-b),\n         T(0.0)       , T(0.0)       , T(-2.0)/(f-n) , -(f+n)/(f-n),\n         T(0.0)       , T(0.0)       , T(0.0)        , T(1.0);\n\n    return m;\n}\n\n// Camera Axis:\n//   X - Right, Y - Up, Z - Back\n// Image Origin:\n//   Bottom Left\n// Caution: Principal point defined with respect to image origin (0,0) at\n//          top left of top-left pixel (not center, and in different frame\n//          of reference to projection function image)\ntemplate<typename CameraModel>\nEIGEN_DEVICE_FUNC inline Eigen::Matrix<typename CameraModel::Scalar,4,4> getPerspectiveProjectionRUBBottomLeft(const CameraModel& cam, typename CameraModel::Scalar N, typename CameraModel::Scalar F)\n{\n    typedef typename CameraModel::Scalar Scalar;\n    \n    const Scalar L = +(cam.u0()) * N / -cam.fx();\n    const Scalar T = +(cam.v0()) * N / cam.fy();\n    const Scalar R = -(cam.width() - cam.u0()) * N / -cam.fx();\n    const Scalar B = -(cam.height() - cam.v0()) * N / cam.fy();\n \n    Eigen::Matrix<typename CameraModel::Scalar,4,4> ret;\n    \n    ret << \n    Scalar(2.0)*N/(R-L) , Scalar(0.0)         , (R+L)/(R-L) , Scalar(0.0),\n    Scalar(0.0)         , Scalar(2.0)*N/(T-B) , (T+B)/(T-B) , Scalar(0.0),\n    Scalar(0.0)         , Scalar(0.0)         ,-(F+N)/(F-N) ,-(Scalar(2.0)*F*N)/(F-N),\n    Scalar(0.0)         , Scalar(0.0)         ,-Scalar(1.0) , Scalar(0.0);\n    \n    return ret;\n}\n\n// Camera Axis:\n//   X - Right, Y - Down, Z - Forward\n// Image Origin:\n//   Top Left\n// Pricipal point specified with image origin (0,0) at top left of top-left pixel (not center)\ntemplate<typename CameraModel>\nEIGEN_DEVICE_FUNC inline Eigen::Matrix<typename CameraModel::Scalar,4,4> getPerspectiveProjectionRDFTopLeft(const CameraModel& cam, typename CameraModel::Scalar N, typename CameraModel::Scalar F)\n{\n    typedef typename CameraModel::Scalar Scalar;\n    \n    const Scalar L = -(cam.u0()) * N / cam.fx();\n    const Scalar T = -(cam.v0()) * N / cam.fy();\n    const Scalar R = +(cam.width() - cam.u0()) * N / cam.fx();\n    const Scalar B = +(cam.height() - cam.v0()) * N / cam.fy();\n        \n    Eigen::Matrix<typename CameraModel::Scalar,4,4> ret;\n    \n    ret << \n    Scalar(2.0)*N/(R-L) , Scalar(0.0)         , (R+L)/(L-R) , Scalar(0.0),\n    Scalar(0.0)         , Scalar(2.0)*N/(T-B) , (T+B)/(B-T) , Scalar(0.0),\n    Scalar(0.0)         , Scalar(0.0)         , (F+N)/(F-N) ,(Scalar(2.0)*F*N)/(N-F),\n    Scalar(0.0)         , Scalar(0.0)         , Scalar(1.0) , Scalar(0.0);\n    \n    return ret;\n}\n\n// Camera Axis:\n//   X - Right, Y - Down, Z - Forward\n// Image Origin:\n//   Bottom Left\n// Pricipal point specified with image origin (0,0) at top left of top-left pixel (not center)\ntemplate<typename CameraModel>\nEIGEN_DEVICE_FUNC inline Eigen::Matrix<typename CameraModel::Scalar,4,4> getPerspectiveProjectionRDFBottomLeft(const CameraModel& cam, typename CameraModel::Scalar N, typename CameraModel::Scalar F)\n{\n    typedef typename CameraModel::Scalar Scalar;\n    \n    const Scalar L = -(cam.u0()) * N / cam.fx();\n    const Scalar T = +(cam.height() - cam.v0()) * N / cam.fy();\n    const Scalar R = +(cam.width() - cam.u0()) * N / cam.fx();\n    const Scalar B = -(cam.v0()) * N / cam.fy();\n    \n    Eigen::Matrix<typename CameraModel::Scalar,4,4> ret;\n    \n    ret << \n    Scalar(2.0)*N/(R-L) , Scalar(0.0)         , (R+L)/(L-R) , Scalar(0.0),\n    Scalar(0.0)         , Scalar(2.0)*N/(T-B) , (T+B)/(B-T) , Scalar(0.0),\n    Scalar(0.0)         , Scalar(0.0)         , (F+N)/(F-N) ,(Scalar(2.0)*F*N)/(N-F),\n    Scalar(0.0)         , Scalar(0.0)         , Scalar(1.0) , Scalar(0.0);\n    \n    return ret;\n}\n\ntemplate<typename CameraModel>\nEIGEN_DEVICE_FUNC inline Eigen::Matrix<typename CameraModel::Scalar,4,4> getPerspectiveProjection(const CameraModel& cam, typename CameraModel::Scalar N, typename CameraModel::Scalar F)\n{\n    return getPerspectiveProjectionRDFTopLeft(cam,N,F);\n}\n\n// NOTE element (2,3) may be wrong\n\ntemplate<typename T>\nEIGEN_DEVICE_FUNC inline Eigen::Matrix<T,4,4> lookAtRUB(const Eigen::Matrix<T,3,1>& eye, const Eigen::Matrix<T,3,1>& center, const Eigen::Matrix<T,3,1>& up)\n{\n    Eigen::Matrix<T,4,4> view_matrix = Eigen::Matrix<T,4,4>::Zero();\n    Eigen::Matrix<T,3,3> R;\n    R.col(2) = (eye-center).normalized();\n    R.col(0) = up.cross(R.col(2)).normalized();\n    R.col(1) = R.col(2).cross(R.col(0));\n    view_matrix.template topLeftCorner<3,3>() = R.transpose();\n    view_matrix.template topRightCorner<3,1>() = -R.transpose() * center;\n    view_matrix.row(3) << T(0.0), T(0.0), T(0.0), T(1.0);\n    return view_matrix;\n}\n\ntemplate<typename T>\nEIGEN_DEVICE_FUNC inline Eigen::Matrix<T,4,4> lookAtRDF(const Eigen::Matrix<T,3,1>& eye, const Eigen::Matrix<T,3,1>& center, const Eigen::Matrix<T,3,1>& up)\n{\n    Eigen::Matrix<T,4,4> view_matrix = Eigen::Matrix<T,4,4>::Zero();\n    Eigen::Matrix<T,3,3> R;\n    R.col(2) = (center-eye).normalized();\n    R.col(0) = R.col(2).cross(up).normalized();\n    R.col(1) = R.col(2).cross(R.col(0));\n    view_matrix.template topLeftCorner<3,3>() = R.transpose();\n    view_matrix.template topRightCorner<3,1>() = -R.transpose() * center;\n    view_matrix.row(3) << T(0.0), T(0.0), T(0.0), T(1.0);\n    return view_matrix;\n}\n\ntemplate<typename T>\nEIGEN_DEVICE_FUNC inline Eigen::Matrix<T,4,4> lookAt(const Eigen::Matrix<T,3,1>& eye, const Eigen::Matrix<T,3,1>& center, const Eigen::Matrix<T,3,1>& up)\n{\n    return lookAtRDF(eye, center, up);\n}\n\n}\n\n#endif // CAMERA_PROJECTION_MATRICES_HPP", "meta": {"hexsha": "74b42f2c55cb8da166a524cc7bf6d4eac55cef34", "size": 7798, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/CameraModels/OpenGLProjectionMatrix.hpp", "max_stars_repo_name": "lukier/camera_models", "max_stars_repo_head_hexsha": "90196141fa4749148b6a7b0adc7af19cb1971039", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2016-11-13T22:17:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T19:59:25.000Z", "max_issues_repo_path": "include/CameraModels/OpenGLProjectionMatrix.hpp", "max_issues_repo_name": "lukier/camera_models", "max_issues_repo_head_hexsha": "90196141fa4749148b6a7b0adc7af19cb1971039", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/CameraModels/OpenGLProjectionMatrix.hpp", "max_forks_repo_name": "lukier/camera_models", "max_forks_repo_head_hexsha": "90196141fa4749148b6a7b0adc7af19cb1971039", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-11-14T00:45:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-02T11:56:50.000Z", "avg_line_length": 42.1513513514, "max_line_length": 198, "alphanum_fraction": 0.6192613491, "num_tokens": 2256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5010852620666517}}
{"text": "/**\r\n * @file Mesh.hpp\r\n * @brief\r\n */\r\n#ifndef MI4_MESH_HPP\r\n#define MI4_MESH_HPP 1\r\n#include <iostream>\r\n#include <vector>\r\n#include <utility>\r\n#include <deque>\r\n#include <map>\r\n#include <cmath>\r\n#include <Eigen/Dense>\r\nnamespace mi4\r\n{\r\n        class Mesh\r\n        {\r\n        private:\r\n                std::string _name;\r\n                std::vector<Eigen::Vector3d> _vertex; /// vertex position\r\n                std::vector<size_t> _index; /// triangles\r\n        public:\r\n                void clone ( const Mesh& mesh )\r\n                {\r\n                        this->init();\r\n\r\n                        for ( int i = 0 ; i < mesh.getNumVertices() ; ++i ) {\r\n                                this->addPoint ( mesh.getPosition ( i ) );\r\n                        }\r\n\r\n                        for ( int i = 0 ; i < mesh.getNumFaces() ; ++i ) {\r\n\r\n                                this->addFace ( mesh.getFaceIndices ( i ) );\r\n                        }\r\n                }\r\n\r\n                size_t addPoint ( const Eigen::Vector3d& p ) const\r\n                {\r\n                        const_cast<Mesh*> ( this )->_vertex.push_back ( p );\r\n                        return this->_vertex.size() - 1;\r\n                }\r\n\r\n                size_t addFace ( const std::vector<size_t>& fidx )\r\n                {\r\n                        if ( fidx.size() != 3 ) {\r\n                                std::cerr << \"only triangle is supported.\" << std::endl;\r\n                                return 0;\r\n                        }\r\n\r\n                        this->_index.insert ( this->_index.end(), fidx.begin(), fidx.end() );\r\n                        return this->_index.size() / 3 ; // ID\r\n                }\r\n\r\n                void addName ( const std::string name = std::string ( \"mesh\" ) )\r\n                {\r\n                        this->_name = name;\r\n                        return;\r\n                }\r\n\r\n                inline bool isValidFaceId ( const size_t faceid ) const\r\n                {\r\n                        return ( faceid < this->getNumFaces() );\r\n                }\r\n\r\n                inline bool isValidVertexId ( const size_t vertexid ) const\r\n                {\r\n                        return ( vertexid < this->getNumVertices() );\r\n                }\r\n\r\n                inline std::vector<size_t> getFaceIndices ( const size_t faceid ) const\r\n                {\r\n                        std::vector<size_t> idx;\r\n\r\n                        if ( this->isValidFaceId ( faceid ) ) {\r\n                                for ( int i = 0 ; i < 3 ; i++ ) {\r\n                                        idx.push_back ( this->_index.at ( faceid * 3 + i ) );\r\n                                }\r\n                        }\r\n\r\n                        return idx;\r\n                }\r\n\r\n                inline Eigen::Vector3d getPosition ( const size_t vertexid ) const\r\n                {\r\n                        if ( this->isValidVertexId ( vertexid ) ) {\r\n                                return this->_vertex.at ( vertexid );\r\n                        }\r\n\r\n                        return Eigen::Vector3d();\r\n                }\r\n\r\n\r\n                Eigen::Vector3d getNormal ( const size_t faceid, bool normalize = true ) const\r\n                {\r\n                        if ( ! this->isValidFaceId ( faceid ) ) {\r\n                                return Eigen::Vector3d();\r\n                        }\r\n\r\n                        auto fidx = this->getFaceIndices ( faceid );\r\n                        Eigen::Vector3d v0 = this->getPosition ( fidx[0] );\r\n                        Eigen::Vector3d v1 = this->getPosition ( fidx[1] ) - v0;\r\n                        Eigen::Vector3d v2 = this->getPosition ( fidx[2] ) - v0;\r\n                        Eigen::Vector3d n = v1.cross ( v2 );\r\n\r\n                        if ( normalize ) {\r\n                                n.normalize();\r\n                        }\r\n\r\n                        return n;\r\n                }\r\n\r\n                inline std::string\r\n                getName ( void ) const\r\n                {\r\n                        return this->_name;\r\n                }\r\n\r\n\r\n                void setPosition ( const size_t vertexid, const Eigen::Vector3d& pos )\r\n                {\r\n                        if ( this->isValidVertexId ( vertexid ) ) {\r\n                                this->_vertex.at ( vertexid ) = pos;\r\n                        }\r\n\r\n                        return;\r\n                };\r\n                void init ( void )\r\n                {\r\n                        this->_vertex.clear();\r\n                        this->_index.clear();\r\n                        return;\r\n                }\r\n\r\n                inline size_t getNumVertices ( void ) const\r\n                {\r\n                        return this->_vertex.size();\r\n                }\r\n\r\n                inline size_t getNumFaces ( void ) const\r\n                {\r\n                        return this->_index.size() / 3;\r\n                }\r\n\r\n                void\r\n                getBoundingBox ( Eigen::Vector3d& bmin, Eigen::Vector3d& bmax )\r\n                {\r\n                        Eigen::AlignedBox3d bbox;\r\n                        const size_t numv = this->getNumVertices();\r\n\r\n                        for ( size_t i = 1 ; i < numv ; ++i ) {\r\n                                bbox.extend ( this->getPosition ( i ) );\r\n                        }\r\n\r\n                        bmin = bbox.min();\r\n                        bmax = bbox.max();\r\n                        return ;\r\n                }\r\n\r\n                void negateOrientation()\r\n                {\r\n                        for ( size_t i = 0 ; i < this->getNumFaces() ; ++i ) {\r\n                                size_t f0 = this->_index [ i * 3 + 0 ];\r\n                                this->_index[ i * 3 + 0 ] = this->_index [ i * 3 + 1];\r\n                                this->_index[ i * 3 + 1 ] = f0;\r\n\r\n                        }\r\n\r\n                }\r\n\r\n                double getArea ( const int faceId ) const\r\n                {\r\n                        std::vector<size_t> index = this->getFaceIndices ( faceId );\r\n                        const Eigen::Vector3d p0 = this->getPosition ( index[0] );\r\n                        const Eigen::Vector3d p1 = this->getPosition ( index[1] );\r\n                        const Eigen::Vector3d p2 = this->getPosition ( index[2] );\r\n                        const Eigen::Vector3d v0 = p1 - p0;\r\n                        const Eigen::Vector3d v1 = p2 - p0;\r\n                        return v0.cross ( v1 ).norm() * 0.5; //|v0^v1|/2\r\n                }\r\n        };\r\n}//namespace mi4\r\n#endif\r\n", "meta": {"hexsha": "8d52c58dfb35e61deef7beaaead83680078f95a3", "size": 6589, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mi4/Mesh.hpp", "max_stars_repo_name": "tmichi/mi4", "max_stars_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_stars_repo_licenses": ["MIT"], "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/mi4/Mesh.hpp", "max_issues_repo_name": "tmichi/mi4", "max_issues_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-28T02:28:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-28T03:00:24.000Z", "max_forks_repo_path": "include/mi4/Mesh.hpp", "max_forks_repo_name": "tmichi/mi4", "max_forks_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_forks_repo_licenses": ["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.0054644809, "max_line_length": 95, "alphanum_fraction": 0.3568067992, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5010496675311074}}
{"text": "#pragma once\n\n// std c++ headers\n#include <cmath>\n\n// mtl headers\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/vector/reduction_functors.hpp>\n#include <boost/numeric/mtl/operation/dot.hpp>\n\n// AMDiS headers\n#include \"operations/assign.hpp\"\n#include \"operations/functors.hpp\"\n\nnamespace AMDiS\n{\n  namespace functors\n  {\n    // unary reduction functors: import from mtl\n    using MTL_VEC::infinity_norm_functor;\n    using MTL_VEC::sum_functor;\n    using MTL_VEC::product_functor;\n    using MTL_VEC::max_functor;\n    using MTL_VEC::min_functor;\n\n    /// Reduction functor to calculate the ||v||_1\n    /** Defines \\ref init, \\ref update and \\ref post_reduction\n     *  so that ||v||_1 := |v_0| + |v_1| + ...:\n     *  init: result = 0,\n     *  update: result += |v_i|,\n     *  post_reduction: result = result\n     **/\n    template <class A>\n    struct one_norm_functor\n    {\n      using result_type = A;\n\n      template <class Value>\n      static void init(Value& value)\n      {\n        using ::math::zero;\n        value= zero(value);\n      }\n\n      template <class Value, class Element>\n      static void update(Value& value, const Element& x)\n      {\n        using std::abs;\n        value+= abs(x);\n      }\n\n      template <class Value>\n      static void finish(Value& value, const Value& value2)\n      {\n        value+= value2;\n      }\n\n      template <class Value>\n      static constexpr Value post_reduction(Value const& value)\n      {\n        return value;\n      }\n    };\n\n\n    /// Reduction functor to calculate the |v|_2\n    /** Defines \\ref init, \\ref update and \\ref post_reduction\n     *  so that ||v||_2 := sqrt(|v_0|^2 + |v_1|^2 + ...):\n     *  init: result = 0,\n     *  update: result += |v_i|^2,\n     *  post_reduction: result = sqrt(result)\n     **/\n    template <class A>\n    struct two_norm_functor\n    {\n      using result_type = A;\n\n      template <class Value>\n      static void init(Value& value)\n      {\n        using ::math::zero;\n        value= zero(value);\n      }\n\n      template <class Value, class Element>\n      static void update(Value& value, Element const& x)\n      {\n        using mtl::squared_abs;\n        value+= squared_abs(x);\n      }\n\n      template <class Value>\n      static void finish(Value& value, Value const& value2)\n      {\n        value+= value2;\n      }\n\n      // After reduction compute square root\n      template <class Value>\n      static Value post_reduction(Value const& value)\n      {\n        using std::sqrt;\n        return sqrt(value);\n      }\n    };\n\n    /// Same as \\ref two_norm_functor without the root at the end:\n    /**\n     *  post_reduction: result = result\n     **/\n    template <class A>\n    struct unary_dot_functor\n      : two_norm_functor<A>\n    {\n      template <typename Value>\n      static Value post_reduction(Value const& value)\n      {\n        return value;\n      }\n    };\n\n    /// \\cond HIDDEN_SYMBOLS\n    template <class A, class B, class ConjOp>\n    struct dot_functor_aux\n    {\n      using result_type = decltype( std::declval<ConjOp>()(std::declval<A>()) * std::declval<B>() );\n\n      template <class Value>\n      static void init(Value& value)\n      {\n        using ::math::zero;\n        value= zero(value);\n      }\n\n      template <class Value, class Element1, class Element2>\n      static void update(Value& value, Element1 const& x, Element2 const& y)\n      {\n        value+= ConjOp()(x) * y;\n      }\n\n      template <class Value>\n      static void finish(Value& value, Value const& value2, Value const& value3)\n      {\n        value+= ConjOp()(value2) * value3;\n      }\n\n      template <class Value>\n      static constexpr Value post_reduction(Value const& value)\n      {\n        return value;\n      }\n    };\n    /// \\endcond\n\n\n    /// Binary reduction functor (scalar product)\n    /** Same as reduction functors, but \\ref update has two arguments:\n     *  init: result = 0,\n     *  update: result += v_i^H * w_i,\n     *  post_reduction: result =result\n     **/\n    template <class A, class B>\n    using dot_functor\n      = dot_functor_aux<A,B, MTL_VEC::detail::with_conj>;\n\n\n    /// Binary reduction functor (scalar product)\n    /** Same as reduction functors, but \\ref update has two arguments:\n     *  init: result = 0,\n     *  update: result += v_i^T * w_i,\n     *  post_reduction: result =result\n     **/\n    template <class A, class B>\n    using dot_real_functor\n      = dot_functor_aux<A,B, MTL_VEC::detail::without_conj>;\n\n\n    template <class ResultType, class InitAssign, class UpdateAssign,\n              class PostOp = identity<ResultType>, class FinishAssign = UpdateAssign>\n    struct general_unary_reduction_functor\n    {\n      using result_type = ResultType;\n\n      template <class Value>\n      static void init(Value& value)\n      {\n        InitAssign()(value);\n      }\n\n      template <class Value, class Element>\n      static void update(Value& value, Element const& x)\n      {\n        UpdateAssign()(value, x);\n      }\n\n      template <class Value>\n      static void finish(Value& value, Value const& value2)\n      {\n        FinishAssign()(value, value2);\n      }\n\n      // After reduction compute square root\n      template <class Value>\n      static constexpr Value post_reduction(Value const& value)\n      {\n        return PostOp()(value);\n      }\n    };\n\n    // max(v0, v1, v2, v3,...)\n    template <class T>\n    using max_reduction_functor\n      = general_unary_reduction_functor<T,\n        AMDiS::assign::min_value<T>, AMDiS::assign::max<T>>;\n\n    // max(|v0|,|v1|,|v2|,...)\n    template <class T>\n    using abs_max_reduction_functor\n      = general_unary_reduction_functor<T,\n        AMDiS::assign::ct_value<T, int, 0>,\n        AMDiS::assign::compose<AMDiS::assign::max<T>, 2, abs<T>>>;\n\n    // min(v0, v1, v2, v3, ...)\n    template <class T>\n    using min_reduction_functor\n      = general_unary_reduction_functor<T,\n        AMDiS::assign::max_value<T>, AMDiS::assign::min<T>>;\n\n    // min(|v0|,|v1|,|v2|,...)\n    template <class T>\n    using abs_min_reduction_functor\n      = general_unary_reduction_functor<T,\n        AMDiS::assign::max_value<T>,\n        AMDiS::assign::compose<AMDiS::assign::min<T>, 2, abs<T>>>;\n\n    // v0+v1+v2+v3+...\n    template <class T>\n    using sum_reduction_functor\n      = general_unary_reduction_functor<T,\n        AMDiS::assign::ct_value<T, int, 0>, AMDiS::assign::plus<T>>;\n\n    // v0*v1*v2*v3*...\n    template <class T>\n    using prod_reduction_functor\n      = general_unary_reduction_functor<T,\n        AMDiS::assign::ct_value<T, int, 1>, AMDiS::assign::multiplies<T>>;\n\n  } // end namespace functors\n} // end namespace AMDiS\n", "meta": {"hexsha": "4e53ab9bf67746072d827f1328ad88bd10d6403a", "size": 6660, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/operations/reduction_functors.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": "src/operations/reduction_functors.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": "src/operations/reduction_functors.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": 26.5338645418, "max_line_length": 100, "alphanum_fraction": 0.6027027027, "num_tokens": 1757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5010496550931988}}
{"text": "#ifndef ILP_TASK_HPP\n#define ILP_TASK_HPP\n\n#include <eigen3/Eigen/Core>\n#include <boost/container_hash/hash.hpp>\n\n#include <utility>\n\nnamespace ilp\n{\n    using index_t = Eigen::Index;\n\n    template <typename T>\n    using matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\n    template <typename T>\n    using rvector = Eigen::Matrix<T, 1, Eigen::Dynamic>;\n\n    template <typename T>\n    using cvector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\n    namespace detail\n    {\n        template <typename T>\n        struct VectorHash\n        {\n            std::size_t operator () (const rvector<T>& row) const\n            {\n                std::size_t seed = 0;\n                for (index_t i = 0; i != row.cols(); ++i)\n                {\n                    boost::hash_combine(seed, row(i, 0));\n                }\n\n                return seed;\n            }\n\n            std::size_t operator () (const cvector<T>& column) const\n            {\n                std::size_t seed = 0;\n                for (index_t i = 0; i != column.rows(); ++i)\n                {\n                    boost::hash_combine(seed, column(i, 0));\n                }\n\n                return seed;\n            }\n        };\n\n    } // namespace detail\n\n    class ilp_task\n    {\n    public:\n        ilp_task(matrix<int> A, cvector<int> b, rvector<int> c);\n        ~ilp_task() = default;\n\n        [[nodiscard]] std::size_t size_m() const;\n        [[nodiscard]] std::size_t size_n() const;\n\n    public:\n        matrix<int> A;\n        cvector<int> b;\n        rvector<int> c;\n        cvector<int> x;\n\n        std::size_t m;\n        std::size_t n;\n    };\n\n    struct ilp_solution\n    {\n        bool is_feasible = false;\n        bool is_bounded = false;\n        cvector<int> x;\n        int c_result = 0;\n        double time = 0;\n    };\n\n} // namespace ilp\n\ntemplate <typename T>\nstd::ostream& operator << (std::ostream& os, const ilp::rvector<T>& vec)\n{\n    bool flag{false};\n\n    os << \"(\";\n    for (ilp::index_t col = 0; col < vec.cols(); ++col)\n    {\n        if (flag)\n        {\n            os << \", \";\n        }\n        flag = true;\n        os << vec(col);\n    }\n    os << \")\";\n    return os;\n}\n\ntemplate <typename T>\nstd::ostream& operator << (std::ostream& os, const ilp::cvector<T>& vec)\n{\n    bool flag{false};\n\n    os << \"(\";\n    for (ilp::index_t row = 0; row < vec.rows(); ++row)\n    {\n        if (flag)\n        {\n            os << \", \";\n        }\n        flag = true;\n        os << vec(row);\n    }\n    os << \")^T\";\n    return os;\n}\n\ntemplate <typename T>\nstd::ostream& operator << (std::ostream& os, const ilp::matrix<T>& A)\n{\n    for (int row = 0; row < A.rows(); ++row)\n    {\n        for (int col = 0; col < A.cols(); ++col)\n        {\n            os << \"   \" << A(row, col) << \" \";\n        }\n\n        if (row != A.rows() - 1)\n        {\n            os <<  \"\\n\";\n        }\n    }\n\n    return os;\n}\n\n#endif // ILP_TASK_HPP\n", "meta": {"hexsha": "70c9db43952a144f44987dafdd8324a82d423204", "size": 2892, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ilp/ilp_task.hpp", "max_stars_repo_name": "pazamelin/ILP_algorithms", "max_stars_repo_head_hexsha": "5ca55f37a2e276d112124a5d02ef7ce686aa20f5", "max_stars_repo_licenses": ["MIT"], "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/ilp/ilp_task.hpp", "max_issues_repo_name": "pazamelin/ILP_algorithms", "max_issues_repo_head_hexsha": "5ca55f37a2e276d112124a5d02ef7ce686aa20f5", "max_issues_repo_licenses": ["MIT"], "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/ilp/ilp_task.hpp", "max_forks_repo_name": "pazamelin/ILP_algorithms", "max_forks_repo_head_hexsha": "5ca55f37a2e276d112124a5d02ef7ce686aa20f5", "max_forks_repo_licenses": ["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.6571428571, "max_line_length": 72, "alphanum_fraction": 0.4664591978, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5010496501487721}}
{"text": "#ifndef visoptslider_hpp\n#define visoptslider_hpp\n\n#include <vector>\n#include <Eigen/Core>\n#include <QGroupBox>\n\nclass QLineEdit;\nclass QSlider;\nnamespace visopt { namespace internal { class VisualizationWidget; } }\n\nnamespace visopt\n{\n    class SlidersWidget : public QGroupBox\n    {\n    public:\n        SlidersWidget(QWidget* parent = nullptr);\n\n        void initialize(const int num_dimensions,\n                        const std::function<double(const Eigen::VectorXd&)>& target_function,\n                        const Eigen::VectorXd& upper_bound,\n                        const Eigen::VectorXd& lower_bound,\n                        const double maximum_value,\n                        const double minimum_value,\n                        const std::vector<std::string>& labels = {},\n                        const bool show_values = false,\n                        const int resolution = 200,\n                        const int visualization_minimum_width = 200,\n                        const int visualization_minimum_height = 32);\n\n        int getNumDimensions() const { return num_dimensions_; }\n        void setNumDimensions(const int num_dimensions)\n        {\n            num_dimensions_ = num_dimensions;\n        }\n\n        const Eigen::VectorXd& getArgument() const { return argument_; }\n\n        void setTargetFunction(const std::function<double(const Eigen::VectorXd&)>& target_function)\n        {\n            target_function_ = target_function;\n        }\n\n        const Eigen::VectorXd& getUpperBound() const { return upper_bound_; }\n        void setUpperBound(const Eigen::VectorXd& upper_bound)\n        {\n            upper_bound_ = upper_bound;\n        }\n\n        const Eigen::VectorXd& getLowerBound() const { return lower_bound_; }\n        void setLowerBound(const Eigen::VectorXd& lower_bound)\n        {\n            lower_bound_ = lower_bound;\n        }\n\n        double getMaximumValue() const { return maximum_value_; }\n        void setMaximumValue(const double maximum_value)\n        {\n            maximum_value_ = maximum_value;\n        }\n\n        double getMinimumValue() const { return minimum_value_; }\n        void setMinimumValue(const double minimum_value)\n        {\n            minimum_value_ = minimum_value;\n        }\n\n        int getResolution() const { return resolution_; }\n        void setResolution(const int resolution)\n        {\n            resolution_ = resolution;\n        }\n\n        double calculateValue(const Eigen::VectorXd& argument) const\n        {\n            return target_function_(argument);\n        }\n\n        void setArgumentAndUpdateSliders(const Eigen::VectorXd& argument);\n\n        void setCallback(const std::function<void(void)>& callback)\n        {\n            callback_ = callback;\n        }\n\n        void setVisualizationMinimumSize(const int minimum_width, const int minimum_height);\n\n    private:\n        void slidersManipulatedViaGui();\n        Eigen::VectorXd calculateArgumentFromCurrentSliders() const;\n        void setSliderValuesUsingCurrentArgument();\n        void setLabelsUsingCurrentArgument();\n\n        int resolution_;\n\n        int num_dimensions_;\n        Eigen::VectorXd argument_;\n        std::function<double(const Eigen::VectorXd&)> target_function_;\n\n        Eigen::VectorXd upper_bound_;\n        Eigen::VectorXd lower_bound_;\n        double maximum_value_;\n        double minimum_value_;\n\n        std::vector<QSlider*> sliders_;\n        std::vector<internal::VisualizationWidget*> visualizations_widgets_;\n        std::vector<QLineEdit*> value_labels_;\n\n        std::function<void(void)> callback_;\n    };\n\n    namespace internal\n    {\n        class VisualizationWidget : public QWidget\n        {\n        public:\n            VisualizationWidget(const int target_dimension,\n                                SlidersWidget* parent,\n                                const int minimum_width,\n                                const int minimum_height);\n\n        protected:\n            void paintEvent(QPaintEvent* event);\n\n        private:\n            const int target_dimension_;\n            const SlidersWidget* parent_widget_ = nullptr;\n        };\n    }\n}\n\n#endif\n", "meta": {"hexsha": "fa23a04ad94601843f20780405f78e000c146aa8", "size": 4134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/visoptslider/visoptslider.hpp", "max_stars_repo_name": "yuki-koyama/visoptslider", "max_stars_repo_head_hexsha": "6443107392e9cb5ee4d215f9eec30e780957bae6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-02-28T13:02:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-10T09:56:25.000Z", "max_issues_repo_path": "include/visoptslider/visoptslider.hpp", "max_issues_repo_name": "yuki-koyama/visoptslider", "max_issues_repo_head_hexsha": "6443107392e9cb5ee4d215f9eec30e780957bae6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-07-09T23:38:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-16T05:23:38.000Z", "max_forks_repo_path": "include/visoptslider/visoptslider.hpp", "max_forks_repo_name": "yuki-koyama/visoptslider", "max_forks_repo_head_hexsha": "6443107392e9cb5ee4d215f9eec30e780957bae6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-03-19T22:33:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-10T09:56:29.000Z", "avg_line_length": 31.0827067669, "max_line_length": 100, "alphanum_fraction": 0.6054668602, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5010496501487721}}
{"text": "/*-----------------------------------------------------------------------------+\r\nInterval Container Library\r\nAuthor: Joachim Faulhaber\r\nCopyright (c) 2007-2010: 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 static_interval.cpp \\file static_interval.cpp\r\n    \\brief Intervals with static interval bounds.\r\n\r\n    Intervals types with static or fixed interval bounds. Statically \r\n    bounded intervals use up to 33% less memory than dynamically\r\n    bounded ones. Of the four possible statically bounded intervals types\r\n    right_open_intervals are the most important ones. We can switch the\r\n    library default to statically bounded intervals by defining\r\n    BOOST_ICL_USE_STATIC_BOUNDED_INTERVALS.\r\n\r\n    \\include static_interval_/static_interval.cpp\r\n*/\r\n//[example_static_interval\r\n#include <iostream>\r\n#include <string>\r\n#include <math.h>\r\n#include <boost/type_traits/is_same.hpp>\r\n\r\n// We can change the library default for the interval types by defining \r\n#define BOOST_ICL_USE_STATIC_BOUNDED_INTERVALS\r\n// prior to other inluces from the icl.\r\n// The interval type that is automatically used with interval\r\n// containers then is the statically bounded right_open_interval.\r\n\r\n#include <boost/icl/interval_set.hpp>\r\n#include <boost/icl/split_interval_set.hpp>\r\n// The statically bounded interval type 'right_open_interval'\r\n// is indirectly included via interval containers.\r\n\r\n\r\n#include \"../toytime.hpp\"\r\n#include <boost/icl/rational.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\nusing namespace boost::icl;\r\n\r\nint main()\r\n{\r\n    cout << \">> Interval Container Library: Sample static_interval.cpp <<\\n\";\r\n    cout << \"------------------------------------------------------------\\n\";\r\n\r\n    // Statically bounded intervals are the user defined library default for \r\n    // interval parameters in interval containers now.\r\n    BOOST_STATIC_ASSERT((\r\n        boost::is_same< interval_set<int>::interval_type\r\n                      , right_open_interval<int> >::value\r\n                      )); \r\n\r\n    BOOST_STATIC_ASSERT((\r\n        boost::is_same< interval_set<float>::interval_type\r\n                      , right_open_interval<float> >::value\r\n                      )); \r\n\r\n    // As we can see the library default both for discrete and continuous\r\n    // domain_types T is 'right_open_interval<T>'.\r\n    // The user defined library default for intervals is also available via \r\n    // the template 'interval':\r\n    BOOST_STATIC_ASSERT((\r\n        boost::is_same< interval<int>::type\r\n                      , right_open_interval<int> >::value\r\n                      )); \r\n\r\n    // Again we are declaring and initializing the four test intervals that have been used\r\n    // in the example 'interval' and 'dynamic_interval'\r\n    interval<int>::type    int_interval  = interval<int>::right_open(3, 8); // shifted the upper bound\r\n    interval<double>::type sqrt_interval = interval<double>::right_open(1/sqrt(2.0), sqrt(2.0));\r\n\r\n    // Interval (\"Barcelona\", \"Boston\"] can not be represented because there is no 'steppable next' on\r\n    // lower bound \"Barcelona\". Ok. this is a different interval:\r\n    interval<string>::type city_interval = interval<string>::right_open(\"Barcelona\", \"Boston\");\r\n\r\n    // Toy Time is discrete again so we can transfrom open(Time(monday,8,30), Time(monday,17,20))\r\n    //                                       to right_open(Time(monday,8,31), Time(monday,17,20))\r\n    interval<Time>::type   time_interval = interval<Time>::right_open(Time(monday,8,31), Time(monday,17,20));\r\n\r\n    cout << \"----- Statically bounded intervals ----------------------------------------\\n\";\r\n    cout << \"right_open_interval<int>   : \" << int_interval  << endl;\r\n    cout << \"right_open_interval<double>: \" << sqrt_interval << \" does \" \r\n                                            << string(contains(sqrt_interval, sqrt(2.0))?\"\":\"NOT\") \r\n                                            << \" contain sqrt(2)\" << endl;\r\n    cout << \"right_open_interval<string>: \" << city_interval << \" does \"  \r\n                                            << string(contains(city_interval,\"Barcelona\")?\"\":\"NOT\") \r\n                                            << \" contain 'Barcelona'\" << endl;\r\n    cout << \"right_open_interval<string>: \" << city_interval << \" does \"  \r\n                                            << string(contains(city_interval, \"Boston\")?\"\":\"NOT\") \r\n                                            << \" contain 'Boston'\" << endl;\r\n    cout << \"right_open_interval<Time>  : \" << time_interval << \"\\n\\n\";\r\n\r\n    // Using statically bounded intervals does not allows to apply operations\r\n    // with elements on all interval containers, if their domain_type is continuous. \r\n    // The code that follows is identical to example 'dynamic_interval'. Only 'internally'\r\n    // the library default for the interval template now is 'right_open_interval' \r\n    interval<rational<int> >::type unit_interval \r\n        = interval<rational<int> >::right_open(rational<int>(0), rational<int>(1));\r\n    interval_set<rational<int> > unit_set(unit_interval);\r\n    interval_set<rational<int> > ratio_set(unit_set);\r\n    // ratio_set -= rational<int>(1,3); // This line will not compile, because we can not\r\n                                        // represent a singleton interval as right_open_interval.\r\n    return 0;\r\n}\r\n\r\n// Program output:\r\n//>> Interval Container Library: Sample static_interval.cpp <<\r\n//------------------------------------------------------------\r\n//----- Statically bounded intervals ----------------------------------------\r\n//right_open_interval<int>   : [3,8)\r\n//right_open_interval<double>: [0.707107,1.41421) does NOT contain sqrt(2)\r\n//right_open_interval<string>: [Barcelona,Boston) does  contain 'Barcelona'\r\n//right_open_interval<string>: [Barcelona,Boston) does NOT contain 'Boston'\r\n//right_open_interval<Time>  : [mon:08:31,mon:17:20)\r\n//]\r\n\r\n", "meta": {"hexsha": "b4b40e61c02b7c7277870aa870104bd91e350b5c", "size": 6272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/icl/example/static_interval_/static_interval.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/static_interval_/static_interval.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/static_interval_/static_interval.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": 50.5806451613, "max_line_length": 110, "alphanum_fraction": 0.6002869898, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872019117029, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5010496426552901}}
{"text": "#include <vector>\n\n#include <boost/mpi.hpp>\n#include <boost/test/minimal.hpp>\n\n#include <elemental.hpp>\n#include <CombBLAS.h>\n#include <SpParMat.h>\n\n#include <skylark.hpp>\n\n#include \"../../base/Gemm.hpp\"\n#include \"../../base/Gemm_detail.hpp\"\n\n/** Typedef DistMatrix and Matrix */\ntypedef elem::Matrix<double> MatrixType;\ntypedef elem::DistMatrix<double, elem::VC, elem::STAR> DistMatrixVCSType;\ntypedef elem::DistMatrix<double> DistMatrixType;\n\ntypedef SpDCCols< size_t, double> col_t;\ntypedef SpParMat< size_t, double, col_t > cbDistMatrixType;\n\nstatic const size_t matrix_size = 50;\n\nstatic MatrixType nn_expected;\nstatic MatrixType tn_expected;\nstatic MatrixType nt_expected;\nstatic MatrixType tt_expected;\n\ntemplate <typename dist_matrix_t>\nvoid check_matrix(const dist_matrix_t &result, const MatrixType &expected,\n                  const std::string error) {\n\n    elem::DistMatrix<double, elem::STAR, elem::STAR> full_result = result;\n    for(size_t j = 0; j < full_result.Height(); j++ )\n        for(size_t i = 0; i < full_result.Width(); i++ ) {\n            if(full_result.GetLocal(j, i) != expected.Get(j, i)) {\n                std::cout << result.GetLocal(j, i) << \" != \"\n                          << expected.Get(j, i)\n                          << \" at index (\" << j << \", \" << i << \")\"\n                          << std::endl;\n                BOOST_FAIL(error.c_str());\n            }\n        }\n}\n\n\nint test_main(int argc, char *argv[]) {\n\n    namespace mpi = boost::mpi;\n\n#ifdef SKYLARK_HAVE_OPENMP\n    int provided;\n    MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);\n#endif\n\n    mpi::environment env (argc, argv);\n    mpi::communicator world;\n\n    elem::Initialize (argc, argv);\n    MPI_Comm mpi_world(world);\n    elem::Grid grid (mpi_world);\n\n    // compute local expected value\n    MatrixType localA(matrix_size, matrix_size);\n    for( size_t j = 0; j < localA.Height(); j++ ) {\n        for( size_t i = 0; i < localA.Width(); i++ ) {\n            double value = j * matrix_size + i + 1;\n            localA.Set(j, i, value);\n        }\n    }\n\n    elem::Ones(nn_expected, matrix_size, matrix_size);\n    elem::Gemm(elem::NORMAL, elem::NORMAL, -1.0, localA, localA,\n                1.5, nn_expected);\n    elem::Ones(nt_expected, matrix_size, matrix_size);\n    elem::Gemm(elem::NORMAL, elem::TRANSPOSE, -1.0, localA, localA,\n                1.5, nt_expected);\n    elem::Ones(tn_expected, matrix_size, matrix_size);\n    elem::Gemm(elem::TRANSPOSE, elem::NORMAL, -1.0, localA, localA,\n                1.5, tn_expected);\n    elem::Ones(tt_expected, matrix_size, matrix_size);\n    elem::Gemm(elem::TRANSPOSE, elem::TRANSPOSE, -1.0, localA, localA,\n                1.5, tt_expected);\n\n\n    // prepare an Elemental matrix with the test data\n    double val = 0.0;\n    elem::DistMatrix<double, elem::STAR, elem::STAR>\n        A_stst(matrix_size, matrix_size, grid);\n    for( size_t j = 0; j < A_stst.LocalHeight(); j++ ) {\n        for( size_t i = 0; i < A_stst.LocalWidth(); i++ ) {\n            val = (j * A_stst.ColStride() + A_stst.ColShift()) * matrix_size +\n                   i * A_stst.RowStride() + A_stst.RowShift() + 1;\n            A_stst.SetLocal(j, i, val);\n        }\n    }\n\n    // and fill a CombBLAS sparse matrix (with the same data)\n    FullyDistVec<size_t, double> cols(matrix_size * matrix_size, 0.0);\n    FullyDistVec<size_t, double> rows(matrix_size * matrix_size, 0.0);\n    FullyDistVec<size_t, double> vals(matrix_size * matrix_size, 0.0);\n\n    for(size_t i = 0; i < matrix_size * matrix_size; ++i) {\n        rows.SetElement(i, floor(i / matrix_size));\n        cols.SetElement(i, i % matrix_size);\n        vals.SetElement(i, static_cast<double>(i+1));\n    }\n\n    cbDistMatrixType B(matrix_size, matrix_size, rows, cols, vals);\n\n\n\n    //std::vector<double> local_matrix;\n    //skylark::base::detail::mixed_gemm_local_part_tt(-1.0, B, A_stst, 0.0,\n            //local_matrix);\n    //for(size_t idx = 0; idx < local_matrix.size(); idx++)\n        //std::cout << local_matrix[idx] << std::endl;\n\n\n    if(world.rank() == 0)\n        std::cout << \"Testing CombBLAS^T x Elemental (VX/*) = Elemental (*/*) :\";\n\n    elem::DistMatrix<double, elem::STAR, elem::STAR>\n        result_stst(matrix_size, matrix_size, grid);\n    for( size_t j = 0; j < result_stst.LocalHeight(); j++ )\n        for( size_t i = 0; i < result_stst.LocalWidth(); i++ )\n            result_stst.SetLocal(j, i, 1.0);\n\n    DistMatrixVCSType A_vcs = A_stst;\n    skylark::base::detail::outer_panel_mixed_gemm_impl_tn(\n            -1.0, B, A_vcs, 1.5, result_stst);\n    check_matrix(result_stst, tn_expected,\n                 \"Result of outer panel TN gemm not as expected\");\n\n    if(world.rank() == 0)\n        std::cout << \"outer panel: OK\" << std::endl;\n\n    if(world.rank() == 0)\n        std::cout << \"Testing CombBLAS x Elemental (*/*) = Elemental (VX/*) :\";\n\n    DistMatrixVCSType result_vcs(matrix_size, matrix_size, grid);\n    for( size_t j = 0; j < result_vcs.LocalHeight(); j++ )\n        for( size_t i = 0; i < result_vcs.LocalWidth(); i++ )\n            result_vcs.SetLocal(j, i, 1.0);\n\n    skylark::base::detail::outer_panel_mixed_gemm_impl_nn(\n            -1.0, B, A_stst, 1.5, result_vcs);\n    check_matrix(result_vcs, nn_expected,\n                 \"Result of outer panel NN gemm not as expected\");\n\n    if(world.rank() == 0)\n        std::cout << \"outer panel: OK\" << std::endl;\n\n    for( size_t j = 0; j < result_vcs.LocalHeight(); j++ )\n        for( size_t i = 0; i < result_vcs.LocalWidth(); i++ )\n            result_vcs.SetLocal(j, i, 1.0);\n\n    skylark::base::detail::inner_panel_mixed_gemm_impl_nn(\n            -1.0, B, A_stst, 1.5, result_vcs);\n    check_matrix(result_vcs, nn_expected,\n                 \"Result of inner panel NN gemm not as expected\");\n\n    if(world.rank() == 0)\n        std::cout << \"inner panel: OK\" << std::endl;\n\n    elem::Finalize();\n\n    return 0;\n}\n\n", "meta": {"hexsha": "3a64ba95bf144de5ed267fe62f712243d29dec83", "size": 5884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/MixedGemmTest.cpp", "max_stars_repo_name": "wangg12/libskylark", "max_stars_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-12T07:26:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T07:26:47.000Z", "max_issues_repo_path": "tests/unit/MixedGemmTest.cpp", "max_issues_repo_name": "cjiyer/libskylark", "max_issues_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "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/unit/MixedGemmTest.cpp", "max_forks_repo_name": "cjiyer/libskylark", "max_forks_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "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.2093023256, "max_line_length": 81, "alphanum_fraction": 0.6046906866, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5010496327664368}}
{"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 \"NoveltyFeature.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass NoveltySegmentation\n{\n\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n\n  NoveltySegmentation(index maxKernelSize, index maxFilterSize)\n      : mNovelty(maxKernelSize, maxFilterSize)\n  {}\n\n  void init(index kernelSize, index filterSize, index nDims)\n  {\n    mNovelty.init(kernelSize, filterSize, nDims);\n    mDebounceCount = 1;\n    mPeakBuffer.setZero(); \n  }\n\n  double processFrame(const RealVectorView input, double threshold,\n                      index minSliceLength)\n  {\n    double detected = 0.;\n\n    mPeakBuffer.segment(0, 2) = mPeakBuffer.segment(1, 2);\n    mPeakBuffer(2) = mNovelty.processFrame(input);\n\n    if (mPeakBuffer(1) > mPeakBuffer(0) && mPeakBuffer(1) > mPeakBuffer(2) &&\n        mPeakBuffer(1) > threshold && mDebounceCount == 0)\n    {\n      detected = 1.0;\n      mDebounceCount = minSliceLength;\n    }\n    else\n    {\n      if (mDebounceCount > 0) mDebounceCount--;\n    }\n    return detected;\n  }\n\nprivate:\n  NoveltyFeature mNovelty;\n  ArrayXd      mPeakBuffer{3};\n  index        mDebounceCount{1};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "abb6480deb7a9c7735918d3542a717f69d11f8cd", "size": 1704, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/NoveltySegmentation.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/NoveltySegmentation.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/NoveltySegmentation.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": 25.4328358209, "max_line_length": 77, "alphanum_fraction": 0.7001173709, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5009951528303733}}
{"text": "#include \"tkdCmdParser.h\"\n\n#include \"nrFourier.h\"\n\n#include \"vnl/vnl_matrix.h\"\n#include \"vnl/vnl_vector.h\"\n#include \"vnl/algo/vnl_determinant.h\"\n#include \"vnl/algo/vnl_svd.h\"\n#include \"vnl/algo/vnl_fft_1d.h\"\n#include \"vnl/algo/vnl_cholesky.h\"\n\n#include \"itkNumericTraits.h\"\n\n#include <stdlib.h>\n#include <math.h>\n#include <fstream>\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"Array.h\"\n#include \"fftw++.h\"\n\nusing namespace Array;\nusing namespace fftwpp;\n\n/**\n * Option list.\n */\nstruct parameters\n{\n\tstd::string inputFileName;\n\tstd::string separation;\n\tbool verbose;\n};\n\n/**\n * General Linear Model (GLM) with autocorrelation prewhitening.\n *\n * Refs:\n * 1. Book: 'Functional MRI an introduction to methods',\n * \t\tP. Jezzard, P.M. Matthews, S.M. Smith, Oxford (2005).\n *\n * 2. Article: 'Temporal autocorrelation in Univariate Modeling of FMRI Data',\n * \t\tM.W. Woolrich, B.D. Ripley, M. Brady and S.M. Smith, Neuroimage 14, 1370-1386 (2001).\n */\nnamespace general_linear_model\n{\n\ttypedef double PixelType;\n\ttypedef vnl_matrix< PixelType > MatrixType;\n\ttypedef vnl_vector< PixelType > VectorType;\n\n\tclass GLM\n\t{\n\tpublic:\n\n\t\t/**\n\t\t * Run glm.\n\t\t */\n\t\tvoid Run( parameters& list )\n\t\t{\n\t\t\t// data Y\n\t\t\tVectorType Y( 8, 0 );\n\t\t\tY( 0 ) = 0.1;\n\t\t\tY( 1 ) = 3.5;\n\t\t\tY( 2 ) = 6.7;\n\t\t\tY( 3 ) = 6.4;\n\t\t\tY( 4 ) = 3.5;\n\t\t\tY( 5 ) = 3.7;\n\t\t\tY( 6 ) = 3.1;\n\t\t\tY( 7 ) = 2.1;\n\n\t\t\t// design matrix X\n\t\t\tMatrixType X( 8, 3 );\n\t\t\tX( 0, 0 ) = 1;\n\t\t\tX( 1, 0 ) = 1;\n\t\t\tX( 2, 0 ) = 1;\n\t\t\tX( 3, 0 ) = 1;\n\t\t\tX( 4, 0 ) = 1;\n\t\t\tX( 5, 0 ) = 1;\n\t\t\tX( 6, 0 ) = 1;\n\t\t\tX( 7, 0 ) = 1;\n\n\t\t\tX( 0, 1 ) = 0;\n\t\t\tX( 1, 1 ) = 0;\n\t\t\tX( 2, 1 ) = 1;\n\t\t\tX( 3, 1 ) = 1;\n\t\t\tX( 4, 1 ) = 0;\n\t\t\tX( 5, 1 ) = 0;\n\t\t\tX( 6, 1 ) = 0;\n\t\t\tX( 7, 1 ) = 0;\n\n\t\t\tX( 0, 2 ) = 0;\n\t\t\tX( 1, 2 ) = 0;\n\t\t\tX( 2, 2 ) = 0;\n\t\t\tX( 3, 2 ) = 0;\n\t\t\tX( 4, 2 ) = 1;\n\t\t\tX( 5, 2 ) = 1;\n\t\t\tX( 6, 2 ) = 0;\n\t\t\tX( 7, 2 ) = 0;\n\n\t\t\t// Toeplitz matrix S\n\t\t\tMatrixType S( Y.size(), Y.size() );\n\t\t\tS.set_identity();\n\n\t\t\t// Adjust for correlation using Cochrane\u2013Orcutt estimation\n\t\t\tVectorType B = OLS( Y, X, S );\n\n\t\t\tstd::cout << \"Betas: \" << B << std::endl;\n\n\t\t\t// Residuals\n\t\t\tVectorType r = Residuals( Y, X, B );\n\n\t\t\tstd::cout << \"Residuals: \" << r << std::endl;\n\n\t\t\t// Raw autocorrelation (all lags)\n\t\t\tVectorType ac = AutoCorrelation( r );\n\n\t\t\tstd::cout << \"Raw autocorrelation: \" << ac << std::endl;\n\n\t\t\t// non-parametric autocorrelation smoothing (M = 2sqrt(N))\n\t\t\tunsigned int M = 2. * std::sqrt( Y.size() );\n\n\t\t\tVectorType sac = TaperedCosineWindow( ac, M );\n\n\t\t\tstd::cout << \"Smoothed autocorrelation (\" << M << \")\" << \": \" << sac << std::endl;\n\n\t\t\t// construct V\n\t\t\tMatrixType V = GetV( sac, true );\n\n\t\t\tvnl_svd< PixelType > svd( V );\n\t\t\t//svd.solve();\n\t\t\tMatrixType W = svd.W();\n\t\t\tMatrixType Vprime = W * W.transpose();\n\n\n\n\t\t\tfor( unsigned int r = 0; r < V.rows(); r++ )\n\t\t\t{\n\t\t\t\tfor( unsigned int c = 0; c < V.cols(); c++ )\n\t\t\t\t{\n\t\t\t\t\tstd::cout << V( r, c ) << \" \";\n\t\t\t\t}\n\t\t\t\tstd::cout << std::endl;\n\t\t\t}\n\n\t\t\tstd::cout << \"UU'\" << std::endl;\n\n\t\t\tfor( unsigned int r = 0; r < Vprime.rows(); r++ )\n\t\t\t{\n\t\t\t\tfor( unsigned int c = 0; c < Vprime.cols(); c++ )\n\t\t\t\t{\n\t\t\t\t\tstd::cout << Vprime( r, c ) << \" \";\n\t\t\t\t}\n\t\t\t\tstd::cout << std::endl;\n\t\t\t}\n\n\n\t\t\texit( 0 );\n\n\t\t\t// refit\n\t\t\t//B = OLS( Y, X, S );\n\t\t}\n\n\tprotected:\n\n\t\t/**\n\t\t * Return inverted Cholesky V=KK'\n\t\t */\n\t\tMatrixType GetInvertedK( const MatrixType& V )\n\t\t{\n\t\t\tvnl_svd< PixelType > svd( V );\n\t\t\tMatrixType pinvV = svd.inverse();\n\n\n\t\t}\n\n\t\t/**\n\t\t * Return V.\n\t\t */\n\t\tMatrixType GetV( const VectorType& v, bool circular )\n\t\t{\n\t\t\tMatrixType result( v.size(), v.size(), 0.0 );\n\n\t\t\tfor( unsigned int r = 0; r < result.rows(); r++ )\n\t\t\t\tfor( unsigned int c = r; c < result.cols(); c++ )\n\t\t\t\t\tresult( r, c ) = v( r );\n\n\t\t\tresult += result.transpose();\n\n\t\t\tresult.fill_diagonal( 1 );\n\n\t\t\treturn result;\n\t\t}\n\n\n\t\t/**\n\t\t * Tukey windowing.\n\t\t *\n\t\t * http://en.wikipedia.org/wiki/Window_function#Tukey_window\n\t\t */\n\t\tVectorType TaperedCosineWindow( const VectorType& ar, unsigned int M )\n\t\t{\n\t\t\tVectorType rho( ar.size(), 0 );\n\n\t\t\tfor ( unsigned int i = 0; i < ar.size(); i++ )\n\t\t\t{\n\t\t\t\tif ( i < M )\n\t\t\t\t{\n\t\t\t\t\tPixelType PI = boost::math::constants::pi< PixelType >();\n\t\t\t\t\trho( i ) = 0.5 * ( 1 + std::cos( ( PI * i ) / M ) ) * ar( i );\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\trho( i ) = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn rho;\n\t\t}\n\n\t\t/**\n\t\t * Cross correlation for all lags\n\t\t * @param a Vector 1 (of length n)\n\t\t * @param b Vector 2 (of length n)\n\t\t * @param output Output vector of length n\n\t\t *\n\t\t * Normalize the sequence so the autocorrelations at zero lag are identically 1.0.\n\t\t */\n\t\tVectorType AutoCorrelation( const VectorType& a )\n\t\t{\n\t\t\tconst int n = a.size();\n\n\t\t\t// added zeropadding!\n\t\t\tint zeropad = (int) pow( 2, ceil( log( a.size() ) / log( 2 ) ) );\n\t\t\tVectorType output( zeropad, 0 );\n\n\t\t\tfor ( int i = 0; i < n; ++i )\n\t\t\t\toutput[i] = a[i];\n\n\t\t\tarray1< PixelType > finput( a.size(), sizeof( Complex ) );\n\t\t\tarray1< Complex > foutput( a.size(), sizeof( Complex ) );\n\t\t\tarray1< Complex > ftemp( a.size(), sizeof( Complex ) );\n\n\t\t\tfor( unsigned int i = 0; i < a.size(); i++ )\n\t\t\t\tfinput[ i ] = a( i );\n\n\t\t\trcfft1d Forward( a.size(), finput, foutput );\n\n\t\t\tForward.fft( finput, foutput ); // fill foutput ...\n\t\t\tForward.fft( finput, ftemp ); // fill ftemp ...\n\n\t\t\tconst PixelType no2 = static_cast< PixelType > ( n >> 1 );\n\n\t\t\tfor ( int i = 2; i < n; i += 2 )\n\t\t\t{\n\t\t\t\tComplex ftmp = foutput[i];\n\t\t\t\tfoutput[i] = ( foutput[i] * ftemp[i] + foutput[i + 1] * ftemp[i + 1] ) / no2;\n\t\t\t\tfoutput[i + 1] = ( foutput[i + 1] * ftemp[i] - ftmp * ftemp[i + 1] ) / no2;\n\t\t\t}\n\n\t\t\tfoutput[0] = foutput[0] * ftemp[0] / no2;\n\t\t\tfoutput[1] = foutput[1] * ftemp[1] / no2;\n\n\t\t\tcrfft1d Backward( a.size(), foutput, finput );\n\t\t\tBackward.fftNormalized( foutput, finput );\n\n\t\t\tVectorType finalOutput( n );\n\n\t\t\t// recrop\n\t\t\tfor ( int i = 0; i < n; ++i )\n\t\t\t\tfinalOutput( i ) = std::abs( foutput( i ) / foutput( 0 ) ); // normalize\n\n\t\t\treturn finalOutput;\n\t\t}\n\n\t\t/**\n\t\t * Return standard deviation.\n\t\t */\n\t\ttemplate< class T >\n\t\tT GetSD( const vnl_vector< T >& distances )\n\t\t{\n\t\t\tint size = distances.size();\n\n\t\t\tif ( size < 2 )\n\t\t\t{\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tT mean = distances.mean();\n\n\t\t\tT sd = 0;\n\t\t\tfor ( int i = 0; i < size; i++ )\n\t\t\t{\n\t\t\t\tsd += pow( distances[i] - mean, 2 );\n\t\t\t}\n\n\t\t\treturn vcl_sqrt( sd / size );\n\t\t}\n\n\t\t/**\n\t\t * Return residuals of fit.\n\t\t */\n\t\tVectorType Residuals( const VectorType& Y, const MatrixType& X, const VectorType& B )\n\t\t{\n\t\t\treturn Y - X * B;\n\n\t\t\t// TODO\n\t\t\t//VectorType r( B.size(), 0 );\n\t\t\t//return r;\n\t\t}\n\n\t\t/**\n\t\t * Ordinary Least Squares ( OLS ) estimation, by finding the\n\t\t * maximum likelihood estimates of a linear regression model.\n\t\t *\n\t\t * Ref: http://en.wikipedia.org/wiki/Ordinary_least_squares\n\t\t */\n\t\tVectorType OLS( const VectorType& Y, const MatrixType& X, const MatrixType& S )\n\t\t{\n\t\t\tif ( Y.size() != X.rows() )\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: The data vector Y and rows of the \"\n\t\t\t\t\t\"design matrix X must have the same length.\" << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\t\t\tif ( X.rows() != S.rows() )\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: The Toeplitz matrix S and \"\n\t\t\t\t\t\"design matrix X must have the same number of rows.\" << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\n\t\t\t// SY = SXB + mu, where mu ~ N( 0, sigma^2 SVS') => Bhat = pinv(SX)SY,\n\t\t\t// where pinv(SX) is the Moore-Penrose pseudoinverse: ((SX)'SX)^-1(SX)'\n\t\t\tvnl_svd< PixelType > svd( ( S * X ).transpose() * S * X );\n\t\t\tMatrixType pinvSX = svd.inverse() * ( S * X ).transpose();\n\n\t\t\treturn pinvSX * S * Y;\n\t\t}\n\t};\n} // end namespace general_linear_model\n\n\n/**\n * Main.\n */\nint main( int argc, char ** argv )\n{\n\ttkd::CmdParser p( argv[0], \"Generalized linear model\" );\n\n\tparameters list;\n\tlist.verbose = false;\n\n\tp.AddArgument( list.inputFileName, \"input\" ) ->AddAlias( \"i\" ) ->SetInput( \"filename\" ) ->SetDescription(\n\t\t\t\"Input file: list of covariate(s) and response function (column format)\" ) ->SetRequired( true );\n\n\tp.AddArgument( list.separation, \"separation\" ) ->AddAlias( \"s\" ) ->SetInput( \"string\" ) ->SetDescription(\n\t\t\t\"Data separator string (default: \\\\t\" );\n\n\tp.AddArgument( list.verbose, \"verbose\" ) ->AddAlias( \"v\" ) ->SetInput( \"bool\" ) ->SetDescription( \"Verbose (default: false\" );\n\n\tif ( !p.Parse( argc, argv ) )\n\t{\n\t\tp.PrintUsage( std::cout );\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tgeneral_linear_model::GLM glm;\n\n\tglm.Run( list );\n\n\treturn EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "5d6476e92301de5150281868c1ef5c7adcf7803c", "size": 8339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/generallinearmodel/generallinearmodel.cpp", "max_stars_repo_name": "wmotte/toolkid", "max_stars_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/generallinearmodel/generallinearmodel.cpp", "max_issues_repo_name": "wmotte/toolkid", "max_issues_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/generallinearmodel/generallinearmodel.cpp", "max_forks_repo_name": "wmotte/toolkid", "max_forks_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_forks_repo_licenses": ["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.2967914439, "max_line_length": 127, "alphanum_fraction": 0.5585801655, "num_tokens": 2945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5009951475885192}}
{"text": "#include <iostream>\n#include <cmath>\n#include <ctime>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <iomanip>\n#include <vector>\n\n#include \"mystuff.h\"\n\nusing namespace mosya;\n\n#ifdef ZAPPY_ZAPPY\n#include \"RandomNormalPair.cpp\"\n#include \"AtoG.cpp\"\n//#include \"GtoA.cpp\"\n//#include \"ProjectPointsOntoEllipse.cpp\"\n//#include \"ProjectPointsOntoHyperbola.cpp\"\n//#include \"ProjectPointsOntoParabola.cpp\"\n//#include \"ProjectPointsOntoConicByEberlyOrig.cpp\"\n#include \"eigen2x2.cpp\"\n#include \"ProjectPointsOntoConicByEberlyModified.cpp\"\n#include \"AdjustProjectedPointsOnConic.cpp\"\n#include \"DistanceToConicApprx.cpp\"\n#include \"ProjectionQuality.cpp\"\n#include \"IsCrossingWindow.cpp\"\n#include \"RootOfCubicEquation.cpp\"\n//#include \"ProjectPointsOntoConicByWEPqz.cpp\"\n//#include \"ProjectPointsOntoConicByWEPeq3Schur.cpp\"\n#include \"ProjectPointsOntoConicByWEPeq3NR.cpp\"\n//#include \"ProjectPointsOntoConicByWEPinv.cpp\"\n//#include \"ProjectPointsOntoConicByQuarticEquation.cpp\"\n#include \"ProjectPointsOntoConicByNewtonAK.cpp\"\n#endif\n\n//  Main program for testing projection methods\n//  Specify the methods by selecting which functions the program calls\n//  Choose double or long double precision in file \"mystuff.h\"\n\nint main()\n{\n    const int n=2,histCols=18,histRows=6,timing=1;\n\n    integers i,j,k,N=0,N0=0,N1=0,N2=0,N3=0,Nmiss=0;\n    int code,hist1[histRows][histCols]={0}, hist2[histRows][histCols]={0};\n\t\n    const reals Window=One,Emin=pow(10.,-histCols-1);  \n\t\n    reals r1,r2;\n    reals E1[histRows][n], E2[histRows][n];\n    double Times[histRows]={0.};\n\t\n    M6x1 A;  \n    M5x1 ParG;\n    Mnx1 X(n,1),Y(n,1),D(n,1),Dmin(n,1),Q(n,1);\n    Mnx1 Xproj(n,1),Yproj(n,1),XprojA(n,1),YprojA(n,1),Xbest(n,1),Ybest(n,1);\n    Mnxm XprojAll(n,histRows),YprojAll(n,histRows);\n\t\n    vector<reals> Xv(n),Yv(n);\n\t\n    clock_t iniTime, finTime;        // auxiliary variables for timing\n    timespec ts1, ts2;\n\t\n    srand ( (unsigned)time(NULL) );  // seed the random generator\n    cout.precision(15);\n\n    while(1)   //  main loop over random conics and points\n\t{\n            //  generate a conic:\n\t\n            RandomNormalPair(r1,r2);  A(0) = r1;  A(1) = r2;\n            RandomNormalPair(r1,r2);  A(2) = r1;  A(3) = r2;\n            RandomNormalPair(r1,r2);  A(4) = r1;  A(5) = r2;\n\t\n            reals eps=1.e-13; RandomNormalPair(r1,r2);  A(2) = A(1)*A(1)/A(0) + eps*r1;  // make it a parabola (if desired)\n\t\n            A.normalize();      //  normalization of the parameter vector (unnecessary)\n\t\n            //  discard the conic if it is of the wrong type:\n\t\n            if (IsCrossingWindow(A,Window)==0)  {  Nmiss++; continue;  }  //  discard conics that do not cross the data window\n\t\n            AtoG(A,ParG,code);                       //   determine the conic type\n            if (code>3) { N0++;  continue; }         //   discard degenerate conics\n\t\n            if (code==1) N1++;   //  count ellipses\n            if (code==2) N2++;   //  count hyperbolas\n            if (code==3) N3++;   //  count parabolas\n            N++;                 //  count all conics together\n\t\n            //   generate n data points:\n\t\n            for (i=0; i<n; i++)\n                {\n                    Xv[i] = Window*(Two*rand()/RAND_MAX - One);\n                    Yv[i] = Window*(Two*rand()/RAND_MAX - One);\n                    X(i) = Xv[i];\n                    Y(i) = Yv[i];\n                    Dmin(i) = REAL_MAX;\n                }\n\n            //   First projection method:\n\t\n            if (timing) {clock_gettime(CLOCK_REALTIME, &ts1);}\n            ProjectPointsOntoConicByWEPeq3NR(X,Y,A,Xproj,Yproj);  //  choose a projection method here\n            if (timing) {clock_gettime(CLOCK_REALTIME, &ts2); Times[0] += (ts2.tv_sec-ts1.tv_sec) + 1.e-9*(ts2.tv_nsec - ts1.tv_nsec);}\n            ProjectionQuality(X,Y,A,Xproj,Yproj,Q);\n            DistanceToConicApprx(X,Y,A,Xproj,Yproj,D);\n            for (i=0; i<n; i++)\n                {\n                    E2[0][i] = Q(i);\n                    if (Dmin(i) > D(i))\n                        {\n                            Dmin(i) = D(i);\n                            Xbest(i) = Xproj(i);\n                            Ybest(i) = Yproj(i);\n                        }\n                }\n            XprojAll.col(0) = Xproj;\n            YprojAll.col(0) = Yproj;\n\t\n            //   Second projection method:\n\t\n            if (timing) {clock_gettime(CLOCK_REALTIME, &ts1);}\n            AdjustProjectedPointsOnConic(X,Y,A,Xproj,Yproj,XprojA,YprojA,2);  //  choose a projection method here\n            Xproj = XprojA;  Yproj = YprojA;\n            if (timing) {clock_gettime(CLOCK_REALTIME, &ts2); Times[1] += (ts2.tv_sec-ts1.tv_sec) + 1.e-9*(ts2.tv_nsec - ts1.tv_nsec);}\n            ProjectionQuality(X,Y,A,Xproj,Yproj,Q);\n            DistanceToConicApprx(X,Y,A,Xproj,Yproj,D);\n            for (i=0; i<n; i++)\n                {\n                    E2[1][i] = Q(i);\n                    if (Dmin(i) > D(i))\n                        {\n                            Dmin(i) = D(i);\n                            Xbest(i) = Xproj(i);\n                            Ybest(i) = Yproj(i);\n                        }\n                }\n            XprojAll.col(1) = Xproj;\n            YprojAll.col(1) = Yproj;\n\t\n            //   Third projection method:\n\n            if (timing) {clock_gettime(CLOCK_REALTIME, &ts1);}\n            ProjectPointsOntoConicByNewtonAK(X,Y,A,Xproj,Yproj);  //  choose a projection method here\n            if (timing) {clock_gettime(CLOCK_REALTIME, &ts2); Times[2] += (ts2.tv_sec-ts1.tv_sec) + 1.e-9*(ts2.tv_nsec - ts1.tv_nsec);}\n            ProjectionQuality(X,Y,A,Xproj,Yproj,Q);\n            DistanceToConicApprx(X,Y,A,Xproj,Yproj,D);\n            for (i=0; i<n; i++)\n                {\n                    E2[2][i] = Q(i);\n                    if (Dmin(i) > D(i))\n                        {\n                            Dmin(i) = D(i);\n                            Xbest(i) = Xproj(i);\n                            Ybest(i) = Yproj(i);\n                        }\n                }\n            XprojAll.col(2) = Xproj;\n            YprojAll.col(2) = Yproj;\n\t\n            //   Fourth projection method:\n        \n            if (timing) {clock_gettime(CLOCK_REALTIME, &ts1);}\n            AdjustProjectedPointsOnConic(X,Y,A,Xproj,Yproj,XprojA,YprojA,2);  //  choose a projection method here\n            Xproj = XprojA;  Yproj = YprojA;\n            if (timing) {clock_gettime(CLOCK_REALTIME, &ts2); Times[3] += (ts2.tv_sec-ts1.tv_sec) + 1.e-9*(ts2.tv_nsec - ts1.tv_nsec);}\n            ProjectionQuality(X,Y,A,Xproj,Yproj,Q);\n            DistanceToConicApprx(X,Y,A,Xproj,Yproj,D);\n            for (i=0; i<n; i++)\n                {\n                    E2[3][i] = Q(i);\n                    if (Dmin(i) > D(i))\n                        {\n                            Dmin(i) = D(i);\n                            Xbest(i) = Xproj(i);\n                            Ybest(i) = Yproj(i);\n                        }\n                }\n            XprojAll.col(3) = Xproj;\n            YprojAll.col(3) = Yproj;\n\t\n            //   Fifth projection method:\n        \n            if (timing) {clock_gettime(CLOCK_REALTIME, &ts1);}\n            ProjectPointsOntoConicByEberlyModified(X,Y,A,Xproj,Yproj);  //  choose a projection method here\n            if (timing) {clock_gettime(CLOCK_REALTIME, &ts2); Times[4] += (ts2.tv_sec-ts1.tv_sec) + 1.e-9*(ts2.tv_nsec - ts1.tv_nsec);}\n            ProjectionQuality(X,Y,A,Xproj,Yproj,Q);\n            DistanceToConicApprx(X,Y,A,Xproj,Yproj,D);\n            for (i=0; i<n; i++)\n                {\n                    E2[4][i] = Q(i);\n                    if (Dmin(i) > D(i))\n                        {\n                            Dmin(i) = D(i);\n                            Xbest(i) = Xproj(i);\n                            Ybest(i) = Yproj(i);\n                        }\n                }\n            XprojAll.col(4) = Xproj;\n            YprojAll.col(4) = Yproj;\n\t\n            //   Sixth projection method:\n        \n            if (timing) {clock_gettime(CLOCK_REALTIME, &ts1);}\n            AdjustProjectedPointsOnConic(X,Y,A,Xproj,Yproj,XprojA,YprojA,2);  //  choose a projection method here\n            Xproj = XprojA;  Yproj = YprojA;\n            if (timing) {clock_gettime(CLOCK_REALTIME, &ts2); Times[5] += (ts2.tv_sec-ts1.tv_sec) + 1.e-9*(ts2.tv_nsec - ts1.tv_nsec);}\n            //if (timing) {cout << endl; cin.ignore();} \n            ProjectionQuality(X,Y,A,Xproj,Yproj,Q);\n            DistanceToConicApprx(X,Y,A,Xproj,Yproj,D);\n            for (i=0; i<n; i++)\n                {\n                    E2[5][i] = Q(i);\n                    if (Dmin(i) > D(i))\n                        {\n                            Dmin(i) = D(i);\n                            Xbest(i) = Xproj(i);\n                            Ybest(i) = Yproj(i);\n                        }\n                }\n            XprojAll.col(5) = Xproj;\n            YprojAll.col(5) = Yproj;\n\t\n            //   Record the results of all projection methods\n        \n            for (i=0; i<n; i++)\n                {\n                    for (j=0; j<histRows; j++)   {  E1[j][i] = sqrt(SQR(XprojAll(i,j)-Xbest(i)) + SQR(YprojAll(i,j)-Ybest(i)));  }\n            \n                    for (j=0; j<histRows; j++)   {  if (E1[j][i] < Emin) E1[j][i] = Emin;  }\n                    for (j=0; j<histRows; j++)   {  if (E2[j][i] < Emin) E2[j][i] = Emin;  }\n                }\n        \n            for (i=0; i<n; i++)\n                {\n                    for (j=0; j<histRows; j++) \n                        {\n                            k = floor(-log10(E1[j][i]));\n                            if (k<1) k=1;  \n                            if (k<=histCols) hist1[j][k-1]++;\n                \n                            k = floor(-log10(E2[j][i]));\n                            if (k<1) k=1;  \n                            if (k<=histCols) hist2[j][k-1]++;\n                        }\n                }\n        \n            if (((N*n)%2000000)==0) \n                {\n                    for (j=0; j<histRows; j++) \n                        {\n                            for (i=0;i<histCols;i++)  cout << setw(6) << hist1[j][i];\n                            cout << endl;\n                        }\n                    cout << endl;\n\t    \n                    for (j=0; j<histRows; j++) \n                        {\n                            for (i=0;i<histCols;i++)  cout << setw(6) << hist2[j][i];\n                            cout << endl;\n                        }\n                    cout << endl;\n\t    \n                    if (timing)\n                        {\n                            cout << \" Runnig times per conic (in milisec): \";\n                            for (j=0; j<histRows; j++) cout << \"  \" << setprecision(5) << Times[j]/N*1000000.;\n                            cout << endl << endl;;\n                        }\n\t    \n                    cout << \" conics used:  N = \" << N << \"  (Ell: \" << N1 << \"  Hyp: \" << N2 << \"  Par: \" << N3 << \") \" << endl;\n                    cout << \" conics removed:  \" << N0 << \" degenetare and \" << Nmiss << \" missing the window\" << endl << endl;\n                }\n            //if ((N*n)>=1000000000) return 0;\n        }\n}\n\n", "meta": {"hexsha": "c7422fd8d0065994f82d98ca26dbcb87462b75a9", "size": 11137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multiview/contrib/mosya_conics/src/main.cpp", "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/contrib/mosya_conics/src/main.cpp", "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/contrib/mosya_conics/src/main.cpp", "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": 39.775, "max_line_length": 135, "alphanum_fraction": 0.4548801293, "num_tokens": 3088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5009951423466645}}
{"text": "/******************************************************************************\n *\n * AMDiS - Adaptive multidimensional simulations\n *\n * Copyright (C) 2013 Dresden University of Technology. All Rights Reserved.\n * Web: https://fusionforge.zih.tu-dresden.de/projects/amdis\n *\n * Authors:\n * Simon Vey, Thomas Witkowski, Andreas Naumann, Simon Praetorius, et al.\n *\n * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\n *\n * This file is part of AMDiS\n *\n * See also license.opensource.txt in the distribution.\n *\n ******************************************************************************/\n\n// Written by Simon Praetorius\n\n\n#ifndef ITL_FGMRES_INCLUDE\n#define ITL_FGMRES_INCLUDE\n\n#include <algorithm>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/multi_vector.hpp>\n#include <boost/numeric/mtl/operation/givens.hpp>\n#include <boost/numeric/mtl/operation/two_norm.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n\n#include \"details.hpp\"\n\nnamespace itl\n{\n\n  /// Flexible Generalized Minimal Residual method (without restart)\n  /// Cite: Youcef Saad, A Flexible Inner-Outer Preconditioned GMRES Algorithm, 1993\n  /** It computes at most kmax_in iterations (or size(x) depending on what is smaller)\n      regardless on whether the termination criterion is reached or not.   **/\n  template <typename Matrix, typename Vector, typename Preconditioner, typename Iteration>\n  int fgmres_full(const Matrix& A, Vector& x, const Vector& b,\n                  Preconditioner& P, Iteration& iter)\n  {\n    using mtl::irange;\n    using mtl::iall;\n    using std::abs;\n    using std::sqrt;\n    using math::reciprocal;\n    typedef typename mtl::Collection<Vector>::value_type Scalar;\n    typedef typename mtl::Collection<Vector>::size_type  Size;\n\n    if (size(b) == 0) throw mtl::logic_error(\"empty rhs vector\");\n\n    const Scalar                zero= math::zero(Scalar()), breakdown_tol= 1.e-16, kappa = 10.0;\n    Scalar                      rho, bnrm2, temp, hr;\n    Size                        k, kmax(std::min(size(x), Size(iter.max_iterations() - iter.iterations())));\n    Vector                      w(resource(x)), r(b - A*x);\n    mtl::matrix::multi_vector<Vector>   V(Vector(resource(x), zero), kmax+1);\n    mtl::matrix::multi_vector<Vector>   Z(Vector(resource(x), zero), kmax+1);\n    mtl::matrix::dense2D<Scalar>        H(kmax+1, kmax);\n\n    mtl::vector::dense_vector<Scalar>   sn(kmax, zero), cs(kmax, zero), s(kmax+1, zero), y(kmax, zero);  // replicated in distributed solvers\n\n    bnrm2 = two_norm(b);\n    if (bnrm2 == zero)\n    {\n      set_to_zero(x);\n      // b == 0 => solution = 0\n      return iter.terminate(bnrm2);\n    }\n\n    rho = two_norm(r);\t\t\t\t// norm of preconditioned residual\n    if (iter.finished(rho))\t\t\t// initial guess is good enough solution\n      return iter;\n\n    V.vector(0) = r * reciprocal(rho);\n    H = zero;\n    s[0] = rho;\n\n    // FGMRES iteration\n    for (k= 0; k < kmax && !iter.finished(rho) ; ++k, ++iter)\n    {\n      Z.vector(k) = solve(P, V.vector(k));\n      w = A * Z.vector(k);\n      temp = two_norm(w);\n\n      for (Size j= 0; j < k+1; j++)\n      {\n        H[j][k] = dot(V.vector(j), w);\n        w -= H[j][k] * V.vector(j);\n      }\n      H[k+1][k]= two_norm(w);\n\n      // reorthogonalization, only if \"heuristic\" condition is fulfilled\n      if (H[k+1][k] < temp * reciprocal(kappa))\n      {\n        for (Size i= 0; i < k+1; i++)\n        {\n          hr = dot(w, V.vector(i));\n          H[i][k] += hr;\n          w -= hr * V.vector(i);\n        }\n        temp = two_norm(w);\n\n        if (temp < H[k+1][k] * reciprocal(kappa))\n        {\n          set_to_zero(w);\n          H[k+1][k] = 0.0;\n        }\n        else\n        {\n          H[k+1][k] = temp;\n        }\n      }\n\n      if (H[k+1][k] < breakdown_tol)\n        return iter.fail(2, \"FGMRES: Singular matrix - nearly hard breakdown\");\n\n      V.vector(k+1) = w * reciprocal(H[k+1][k]);\n\n      // k Given's rotations\n      for(Size i= 0; i < k; i++)\n      {\n        temp =        cs[i]*H[i][k] + sn[i]*H[i+1][k];\n        H[i+1][k] = - sn[i]*H[i][k] + cs[i]*H[i+1][k];\n        H[i][k] = temp;\n      }\n\n      details::rotmat(H[k][k], H[k+1][k], cs[k], sn[k]);\n\n      s[k+1] = -sn[k]*s[k];\n      s[k]   =  cs[k]*s[k];\n      H[k][k] = cs[k]*H[k][k] + sn[k]*H[k+1][k];\n      H[k+1][k] = 0.0;\n\n      rho = std::abs(s[k+1]);\n    }\n\n    // reduce k, to get regular matrix\n    //     while (k > 0 && abs(s[k-1]) <= iter.atol()) k--;\n\n    // iteration is finished -> compute x: solve H*y=g as far as rank of H allows\n    irange range(k);\n    for (; !range.empty(); --range)\n    {\n      try\n      {\n        y[range] = upper_trisolve(H[range][range], s[range]);\n      }\n      catch (mtl::matrix_singular)\n      {\n        continue;    // if singular then try with sub-matrix\n      }\n      break;\n    }\n\n    if (range.finish() < k)\n      std::cerr << \"GMRES orhogonalized with \" << k << \" vectors but matrix singular, can only use \"\n                << range.finish() << \" vectors!\\n\";\n    if (range.empty())\n      return iter.fail(3, \"GMRES did not find any direction to correct x\");\n\n    x += Z.vector(range) * y[range];\n\n    //     r = b - A*x;\n    return iter.terminate(rho);\n  }\n\n  /// Flexible Generalized Minimal Residual method with restart\n  template <typename Matrix, typename Vector, typename LeftPreconditioner,\n            typename RightPreconditioner, typename Iteration>\n  int fgmres(const Matrix& A, Vector& x, const Vector& b,\n             LeftPreconditioner& /*L*/, RightPreconditioner& R,\n             Iteration& iter, typename mtl::Collection<Vector>::size_type restart)\n  {\n    do\n    {\n      Iteration inner(iter);\n      inner.set_max_iterations(std::min(int(iter.iterations()+restart), iter.max_iterations()));\n      inner.suppress_resume(true);\n      fgmres_full(A, x, b, R, inner);\n      iter.update_progress(inner);\n    }\n    while (!iter.finished());\n\n    return iter;\n  }\n\n\n\n} // namespace itl\n\n#endif // ITL_FGMRES_INCLUDE\n\n\n", "meta": {"hexsha": "4464b9328a2fd30e31540bc9178c38fc1bc25536", "size": 6215, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/itl/fgmres.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": "src/solver/itl/fgmres.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": "src/solver/itl/fgmres.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.7673267327, "max_line_length": 141, "alphanum_fraction": 0.5705551086, "num_tokens": 1727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5009951423466645}}
{"text": "#include <boost/math/special_functions/sinc.hpp>\n", "meta": {"hexsha": "c4c0642d50ea71760629021217b196dcc0b7339f", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_sinc.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_sinc.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_sinc.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8163265306, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5009951423466645}}
{"text": "// Copyright (C) 2017 Vicente J. Botet Escriba\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// <experimental/chrono.hpp>\n\n#include <experimental/chrono.hpp>\n\nnamespace stdex = std::experimental;\n\n// Basic frame durations\nusing frames       = std::chrono::duration<int32_t,  std::ratio_multiply<std::ratio<10>,  std::chrono::milliseconds::period>::type>;\nusing subframes    = std::chrono::duration<int32_t,  std::ratio_divide<frames::period,    std::ratio<10>>::type>;\nusing slots        = std::chrono::duration<int32_t,  std::ratio_divide<subframes::period, std::ratio<2>>::type>;\nusing symbols      = std::chrono::duration<int32_t,  std::ratio_divide<slots::period,     std::ratio<7>>::type>;\n\nusing bi_frames     = std::chrono::duration<int32_t,  std::ratio_multiply<std::ratio<2>,    frames::period>::type>;\nusing x_frames     = std::chrono::duration<int32_t,  std::ratio_multiply<std::ratio<1024>, frames::period>::type>;\nusing h_frames     = std::chrono::duration<int32_t,  std::ratio_multiply<std::ratio<1024>, x_frames::period>::type>;\nusing bi_slots      = std::chrono::duration<int32_t,  std::ratio_multiply<std::ratio<2>,    slots::period>::type>;\n\n// relative numbers\nusing h_frame_number    = stdex::chrono::modulo<x_frames,  h_frames,  uint16_t>; //1024\nusing frame_number      = stdex::chrono::modulo<frames,    x_frames,  uint16_t>; //1024\nusing x_frame_number    = frame_number;\n\nusing hx_frame_number    = stdex::chrono::modulo<frames,  h_frames,  uint16_t>; //1024*1024\n\nusing subframe_number   = stdex::chrono::modulo<subframes, frames,     uint8_t>; //10\nusing slot_number       = stdex::chrono::modulo<slots,     subframes,  uint8_t>; //2\nusing symbol_number     = stdex::chrono::modulo<symbols,   slots,      uint8_t>; //7\nusing bi_frame_number    = stdex::chrono::modulo<frames,    bi_frames,   uint8_t>; //2\n\nusing h_subframe_number = stdex::chrono::modulo<subframes, h_frames, uint32_t>; // 10*1240*1024\nusing x_subframe_number = stdex::chrono::modulo<subframes, x_frames, uint16_t>; // 10*1240\nusing bi_subframe_number = stdex::chrono::modulo<subframes, bi_frames, uint8_t>; // 10*2\nusing bi_symbol_number = stdex::chrono::modulo<symbols, bi_slots, uint8_t>;      // 7*2\n\n\ninline constexpr h_subframe_number make_h_subframe_number(x_frame_number xfn, frame_number fn, subframe_number sfn) {\n       return h_subframe_number(xfn.to_duration() + fn.to_duration() + sfn.to_duration()) ;\n}\n\n\ninline constexpr x_subframe_number make_x_subframe_number(frame_number fn, subframe_number sfn) {\n       return x_subframe_number(fn.to_duration() + sfn.to_duration()) ;\n}\n\ninline constexpr bi_subframe_number make_bi_subframe_number(bi_frame_number fn, subframe_number sfn) {\n       return bi_subframe_number(fn.to_duration() + sfn.to_duration()) ;\n}\n\ninline constexpr bi_symbol_number make_bi_subframe_number(slot_number sn, symbol_number syn) {\n       return bi_symbol_number(sn.to_duration() + syn.to_duration()) ;\n}\n\ntemplate <class SubDuration, class Duration, class Rep>\nconstexpr x_frame_number to_x_frame_number(stdex::chrono::modulo<SubDuration, Duration, Rep> m)\n{\n  return stdex::chrono::modulo_cast<x_frame_number, h_frames>(m);\n\n}\n\ntemplate <class SubDuration, class Duration, class Rep>\nconstexpr frame_number to_frame_number(stdex::chrono::modulo<SubDuration, Duration, Rep> m)\n{\n    return stdex::chrono::modulo_cast<frame_number, h_frames>(m);\n}\n\ntemplate <class SubDuration, class Duration, class Rep>\nconstexpr subframe_number to_subframe_number(stdex::chrono::modulo<SubDuration, Duration, Rep> m)\n{\n  return stdex::chrono::modulo_cast<subframe_number, h_frames>(m);\n}\n\ntemplate <class SubDuration, class Duration, class Rep>\nconstexpr slot_number to_slot_number(stdex::chrono::modulo<SubDuration, Duration, Rep> m)\n{\n  return stdex::chrono::modulo_cast<slot_number, h_frames>(m);\n}\n\ntemplate <class SubDuration, class Duration, class Rep>\nconstexpr symbol_number to_symbol_number(stdex::chrono::modulo<SubDuration, Duration, Rep> m)\n{\n  return stdex::chrono::modulo_cast<symbol_number, h_frames>(m);\n}\n\n\n\n// what about defining x_subframe_tuple using tuples as underlying type.\n// This will allow to define it as a strong type inheriting from all the relational operators\n\n// x_subframe_tuple =  tuple<frame_number, subframe_number>\n// x_subframe_tuple =  tuple<modulo<x_frames, frames>, modulo<frames, subframes>>\n// todo: define a tuple_modulo where\n// tuple_modulo<T1, T2, T3> = tuple<modulo<T1, T2>, modulo<T2, T3>>\n//template <class T1, T2, T3>\n//using tuple_modulo = std::tuple<modulo<T1, T2>, modulo<T2, T3>>;\n//  convertible to T3 and modulo<T1, T3>\n//  access to modulo<T1, T2> and modulo<T2, T3>\n// tuple_modulo<T1, T2, T3, T4> = tuple<modulo<T1, T2>, modulo<T2, T3>, modulo<T3, T4>>\n// x_subframe_tuple must define the same operations than x_subframe_number\nstruct x_subframe_tuple {\nprivate:\n    frame_number fn;\n    subframe_number sfn;\npublic:\n\n#if defined __clang__\n    // gcc doesn't accepts this\n    constexpr\n#endif\n    x_subframe_tuple() = default;\n\n    /// pre-condition: fn and sfn are valid\n    constexpr x_subframe_tuple(frame_number fn, subframe_number sfn) : fn(fn), sfn(sfn) {}\n    /// pre-condition: xsfn is valid\n    constexpr x_subframe_tuple(x_subframe_number xsfn) : fn(to_frame_number(xsfn)), sfn(to_subframe_number(xsfn)) {}\n\n    /// pre-condition: fn  isvalid\n    constexpr frame_number frame() const {return fn;}\n    /// pre-condition: sfn is valid\n    constexpr subframe_number subframe() const {return sfn;}\n    /// pre-condition: fn and sfn are valid\n\n    constexpr subframes get_duration() const { return frames(fn) + subframes(sfn); }\n    constexpr x_subframe_number get_modulo() const { return x_subframe_number(get_duration()); }\n\n    constexpr operator subframes() const { return get_duration(); }\n    constexpr x_subframe_number x_subframe() const { return get_modulo(); }\n    constexpr operator x_subframe_number() const { return get_modulo(); }\n\n    // pre-condition 0 <= xsfn.frame() + df < 1024\n    friend constexpr x_subframe_tuple operator+(x_subframe_tuple const& xsfn, const frames& df) noexcept\n    {\n        return { xsfn.fn + df, xsfn.sfn };\n    }\n\n    // pre-condition 0 <= xsfn.frame() - df < 1024\n    friend constexpr x_subframe_tuple operator-(x_subframe_tuple const& xsfn, const frames& df) noexcept\n    {\n        return { xsfn.fn - df, xsfn.sfn };\n    }\n    // pre-condition 0 <= xsfn.frame() - df < 1024\n    friend constexpr x_subframe_tuple operator+(const frames& df, x_subframe_tuple const& xsfn) noexcept\n    {\n        return xsfn + df;\n    }\n\n    friend constexpr subframes operator-(x_subframe_tuple const& x, const x_subframe_tuple& y) noexcept\n    {\n        return subframes(x) - subframes(y);\n    }\n\n    // pre-condition 0 <= xsfn.subframes() + dsf < 1024*10\n    friend JASEL_CXX14_CONSTEXPR x_subframe_tuple operator+(x_subframe_tuple const& xsfn, const subframes& dsf) noexcept\n    {\n        const int cardinal = subframe_number::cardinal;\n        auto dsfni = xsfn.sfn.count() + dsf.count();\n        auto dfni = ((dsfni >= 0)  ? dsfni : dsfni-cardinal+1 ) / cardinal;\n        dsfni = dsfni - dfni * cardinal;\n        return x_subframe_tuple( xsfn.fn + frames(dfni), subframe_number(subframes(dsfni)) );\n    }\n    // pre-condition 0 <= xsfn.subframes() + dsf < 1024*10\n    friend JASEL_CXX14_CONSTEXPR x_subframe_tuple operator+(const subframes& dsf, x_subframe_tuple const& xsfn) noexcept\n    {\n        return xsfn + dsf;\n    }\n    // pre-condition 0 <= xsfn.subframes() - dsf < 1024*10\n    friend JASEL_CXX14_CONSTEXPR x_subframe_tuple operator-(x_subframe_tuple const& xsfn, const subframes& dsf) noexcept\n    {\n        return xsfn + -dsf;\n    }\n\n    // pre-condition 0 <= this->subframes() + df < 1024*10\n    JASEL_CXX14_CONSTEXPR x_subframe_tuple& operator+=(const frames& df) noexcept\n    {\n        *this = *this + df;\n        return *this;\n    }\n    // pre-condition 0 <= this->subframes() - df < 1024*10\n    JASEL_CXX14_CONSTEXPR x_subframe_tuple& operator-=(const frames& df) noexcept\n    {\n        *this = *this - df;\n        return *this;\n    }\n\n    // pre-condition 0 <= this->subframes() +dsf < 1024*10\n    JASEL_CXX14_CONSTEXPR x_subframe_tuple& operator+=(const subframes& dsf) noexcept\n    {\n        *this = *this + dsf;\n        return *this;\n    }\n    // pre-condition 0 <= this->subframes() + subframe(1) < 1024*10\n    JASEL_CXX14_CONSTEXPR x_subframe_tuple& operator++() noexcept\n    {\n        *this = *this + subframes(1);\n        return *this;\n    }\n    // pre-condition 0 <= this->subframes() + subframe(1) < 1024*10\n    JASEL_CXX14_CONSTEXPR x_subframe_tuple operator++(int) noexcept\n    {\n        x_subframe_tuple tmp (*this);\n        ++(*this);\n        return tmp;\n    }\n    // pre-condition 0 <= this->subframes() - dsf < 1024*10\n    JASEL_CXX14_CONSTEXPR x_subframe_tuple& operator-=(const subframes& dsf) noexcept\n    {\n        *this = *this - dsf;\n        return *this;\n    }\n    // pre-condition 0 <= this->subframes() - subframe(1) < 1024*10\n    JASEL_CXX14_CONSTEXPR x_subframe_tuple& operator--() noexcept\n    {\n        *this = *this - subframes(1);\n        return *this;\n    }\n    // pre-condition 0 <= this->subframes() - subframe(1) < 1024*10\n    JASEL_CXX14_CONSTEXPR x_subframe_tuple operator--(int) noexcept\n    {\n        x_subframe_tuple tmp (*this);\n        --(*this);\n        return tmp;\n    }\n};\n\n// operator/ play the role of a factory as it does on Date library.\n// Note that there is no sense to divide a frame_number and subframe_number, we need to first convert to duration\nx_subframe_tuple operator/(frame_number fn, subframe_number sfn)\n{\n    return {fn, sfn};\n}\n\n// Should the following be members?\n// No because for modulo types it is a non-member function\ninline constexpr h_frame_number to_h_frame_number(x_subframe_tuple )\n{\n    return h_frame_number(0);\n}\ninline constexpr x_subframe_number to_x_subframe_number(x_subframe_tuple xsfn)\n{\n    //return xsfn.x_subframe();\n    return make_x_subframe_number(xsfn.frame(), xsfn.subframe());\n}\ninline constexpr frame_number to_frame_number(x_subframe_tuple xsfn)\n{\n    return xsfn.frame();\n}\ninline constexpr subframe_number to_subframe_number(x_subframe_tuple xsfn)\n{\n    return xsfn.subframe();\n}\ninline constexpr slot_number to_slot_number(x_subframe_tuple )\n{\n    return slot_number(0);\n}\ninline constexpr symbol_number to_symbol_number(x_subframe_tuple )\n{\n    return symbol_number(0);\n}\n\nstruct h_subframe_tuple {\n    x_frame_number xfn;\n    frame_number fn;\n    subframe_number sfn;\n    h_subframe_tuple() = default;\n    constexpr h_subframe_tuple(x_frame_number xfn, frame_number fn, subframe_number sfn) : xfn(xfn), fn(fn) , sfn(sfn) {}\n    constexpr operator h_subframe_number() const { return make_h_subframe_number(xfn, fn, sfn); }\n};\n\ninline constexpr h_subframe_number to_h_frame_number(h_subframe_tuple hsfn)\n{\n    return h_subframe_number(hsfn);\n}\ninline constexpr x_frame_number to_x_frame_number(h_subframe_tuple hsfn)\n{\n    return hsfn.xfn;\n}\ninline constexpr frame_number to_frame_number(h_subframe_tuple hsfn)\n{\n    return hsfn.fn;\n}\ninline constexpr subframe_number to_subframe_number(h_subframe_tuple hsfn)\n{\n    return hsfn.sfn;\n}\ninline constexpr slot_number to_slot_number(h_subframe_tuple )\n{\n    return slot_number(0);\n}\ninline constexpr symbol_number to_symbol_number(h_subframe_tuple )\n{\n    return symbol_number(0);\n}\n\nstatic_assert(frame_number::cardinal  == 1024, \"1024 frames are not a x_frame\");\nstatic_assert(subframe_number::cardinal  == 10, \"10 sub frames are not a frame\");\nstatic_assert(bi_subframe_number::cardinal  == 20, \"20 sub frames are not a bi_frame\");\n\nstatic_assert(slots::period::num  == 1, \"\");\nstatic_assert(slots::period::den  == 2000, \"\");\nstatic_assert(symbols::period::num  == 1, \"\");\nstatic_assert(symbols::period::den  == 7*2000, \"\");\n\n//! Auxiliary functions\ninline constexpr bool parity(bi_subframe_number x) {\n  return to_frame_number(x) == frame_number{0};\n}\n\n// todo Add literals\n// h_frames -> _hfs\n// frames -> _xfs\n// subframes -> _sfs\n\n// frame_number -> _fn\n// subframe_number -> _sfn\n// slot_number -> _sn\n// symbol_number -> _syn\n\n\n\n#include <boost/detail/lightweight_test.hpp>\n#include <iostream>\n\nint main()\n{\n  {\n    constexpr   x_subframe_number xsfn =  make_x_subframe_number(frame_number{5}, subframe_number{3});\n    static_assert(xsfn.count()  == 53, \"\");\n\n  }\n  {\n  subframes num_of_sfs{4};\n  num_of_sfs++;\n  frames num_of_fs{2};\n  num_of_fs++;\n  auto x = num_of_fs + num_of_sfs;\n  std::cout << \"sfn = \" << x.count() << \"\\n\";\n  {\n      x_subframe_number xsfn {x};\n      std::cout << \"xsfn = \" << xsfn << \"\\n\";\n      slot_number slotn =  to_slot_number(xsfn);\n      std::cout << \"slotn = \" << slotn << \"\\n\";\n      subframe_number sfn =  to_subframe_number(xsfn);\n      std::cout << \"sfn = \" << sfn << \"\\n\";\n      frame_number fn =  to_frame_number(xsfn);\n      std::cout << \"fn = \" << fn << \"\\n\";\n      x_frame_number xfn =  to_x_frame_number(xsfn);\n      std::cout << \"xfn = \" << xfn << \"\\n\";\n\n      {\n          x_subframe_number xsfn2 { frames(fn) + subframes(sfn) };\n          std::cout << \"xsfn2 = \" << xsfn2 << \"\\n\";\n      }\n      {\n          auto xsfn2 = make_x_subframe_number( fn, sfn );\n          std::cout << \"xsfn2 = \" << xsfn2 << \"\\n\";\n      }\n      {\n          x_subframe_number xsfn2 = make_x_subframe_number( fn, sfn );\n          std::cout << \"xsfn2 = \" << xsfn2 << \"\\n\";\n      }\n      {\n          auto xsfn2 = fn.to_duration() + sfn.to_duration();\n          std::cout << \"xsfn2 = \" << xsfn2.count() << \"\\n\";\n      }\n\n  }\n\n  subframe_number sfn (num_of_sfs) ;\n  frame_number fn (num_of_fs) ;\n  bi_frame_number bfn (num_of_fs) ;\n  bi_subframe_number bsfn = make_bi_subframe_number(bfn,sfn) ;\n  std::cout << \"bsfn = \" << bsfn << \"\\n\";\n\n  std::cout << \"==================\\n\";\n\n  x_subframe_number  x2 = make_x_subframe_number( fn, sfn );\n  std::cout << \"xsfn2= \" << x2 << \"\\n\";\n  bi_subframe_number bsfn2 = stdex::chrono::modulo_cast<bi_subframe_number, h_frames>(x2) ;\n      std::cout << \"bsfn2= \" << bsfn2 << \"\\n\";\n\n  bi_frame_number bfn2 = stdex::chrono::modulo_cast<bi_frame_number, h_frames>(x2) ;\n  std::cout << \"bfn2= \" << bfn2 << \"\\n\";\n\n  x_subframe_number x3 = stdex::chrono::modulo_cast<x_subframe_number, h_frames>(bfn2) ;\n  std::cout << \"x3= \" << x3 << \"\\n\";\n\n  x_subframe_number x4 = stdex::chrono::modulo_cast<x_subframe_number, h_frames>(bsfn2) ;\n  std::cout << \"x4= \" << x4 << \"\\n\";\n  }\n  {\n      frame_number fn {1};\n      subframe_number sfn {2};\n      x_subframe_tuple xsfn = fn/sfn;\n      BOOST_TEST(xsfn.frame().count()==1);\n      BOOST_TEST(xsfn.subframe().count()==2);\n      BOOST_TEST(xsfn.x_subframe().count()==12);\n\n      BOOST_TEST(to_frame_number(xsfn).count()==1);\n      BOOST_TEST(to_subframe_number(xsfn).count()==2);\n      BOOST_TEST(to_x_subframe_number(xsfn).count()==12);\n\n      xsfn += frames(3);\n      BOOST_TEST(xsfn.x_subframe().count()==42);\n      BOOST_TEST(xsfn.frame().count()==4);\n\n      xsfn += subframes(23);\n      std::cout << \"xsfn.x_subframe()= \" << xsfn.x_subframe() << \"\\n\";\n      BOOST_TEST(xsfn.x_subframe().count()==65);\n\n      ++xsfn;\n      BOOST_TEST(xsfn.x_subframe().count()==66);\n\n      --xsfn;\n      BOOST_TEST(xsfn.x_subframe().count()==65);\n\n      auto x1 = xsfn++;\n      BOOST_TEST(x1.x_subframe().count()==65);\n      BOOST_TEST(xsfn.x_subframe().count()==66);\n\n      auto x2 = xsfn--;\n      BOOST_TEST(x2.x_subframe().count()==66);\n      BOOST_TEST(xsfn.x_subframe().count()==65);\n\n  }\n  {\n      frame_number fn {1};\n      subframe_number sfn {2};\n      x_subframe_tuple xsfn = fn/sfn;\n      auto x = xsfn - xsfn;\n      BOOST_TEST(x.count()==0);\n\n  }\n\n  return ::boost::report_errors();\n}\n", "meta": {"hexsha": "c614243b76d57e1a34747f0d305921510475d1a5", "size": 15763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/chrono/frame_types_pass.cpp", "max_stars_repo_name": "jwakely/std-make", "max_stars_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 105.0, "max_stars_repo_stars_event_min_datetime": "2015-01-24T13:26:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T15:36:53.000Z", "max_issues_repo_path": "example/chrono/frame_types_pass.cpp", "max_issues_repo_name": "jwakely/std-make", "max_issues_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2015-09-04T06:57:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T18:01:44.000Z", "max_forks_repo_path": "example/chrono/frame_types_pass.cpp", "max_forks_repo_name": "jwakely/std-make", "max_forks_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2015-01-27T11:09:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T02:23:30.000Z", "avg_line_length": 35.825, "max_line_length": 132, "alphanum_fraction": 0.6782972784, "num_tokens": 4467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.5009841182518888}}
{"text": "/*********************************************************************\n * BSD 3-Clause License\n *\n * Copyright (c) 2020 Northwestern University\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 * @file basis.hpp\n * @author Boston Cleek\n * @date 20 Nov 2020\n * @brief Fourier cosine basis\n */\n#ifndef BASIS_HPP\n#define BASIS_HPP\n\n#include <armadillo>\n\nnamespace ergodic_exploration\n{\nusing arma::imat;\nusing arma::mat;\nusing arma::vec;\n\n/**\n * @brief Fourier cosine basis */\nclass Basis\n{\nprivate:\n  template <class ModelT>\n  friend class ErgodicControl;\n\npublic:\n  /**\n   * @brief Constructor\n   * @param lx - x-axis lenght of domain\n   * @param ly - y-axis lenght of domain\n   * @param num_basis - number of each basis functions per dimension\n   */\n  Basis(double lx, double ly, unsigned int num_basis);\n\n  /**\n   * @brief Compose cosine basis functions given positon\n   * @param x - robot position [x y]\n   * @return cosine basis functions (num_basis^2 x 1)\n   * @details x must be on domain [0 lx] x [0 ly]\n   */\n  vec fourierBasis(const vec& x) const;\n\n  /**\n   * @brief Compose gradient cosine basis functions\n   * @param x - robot position [x y]\n   * @return gradient of each basis function (2 x num_basis^2)\n   * @details x must be on domain [0 lx] x [0 ly]\n   */\n  mat gradFourierBasis(const vec& x) const;\n\n  /**\n   * @brief Compose trajectory fourier coefficients\n   * @param xt - trajectory\n   * @return trajectory fourier coefficients (num_basis^2 x 1)\n   * @details xt must be on domain [0 lx] x [0 ly] and robot heading is not required\n   */\n  vec trajCoeff(const mat& xt) const;\n\n  /**\n   * @brief Compose spatial fourier coefficients\n   * @param phi_vals - target evaluated at each grid cell in phi_grid\n   * @param phi_grid - discretization of fourier domain\n   * @return spatial fourier coefficients (num_basis^2 x 1)\n   * @details phi_grid is not the occupancy grid, the first row contains the\n   * x-cordinates and the second row contains the corresponding y-coordinates.\n   * The index of the elements in phi_vals must correspond to the columns in phi_grid.\n   */\n  vec spatialCoeff(const vec& phi_vals, const mat& phi_grid) const;\n\nprivate:\n  double lx_, ly_;            // length of domain\n  unsigned int total_basis_;  // number of basis functions\n  vec lamdak_;                // frequency coefficients weights\n  imat k_;                    // basis number\n};\n}  // namespace ergodic_exploration\n#endif\n", "meta": {"hexsha": "989773ca5d9568cc4b37943b6f2f6cd65f21265b", "size": 3993, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ergodic_exploration/basis.hpp", "max_stars_repo_name": "bostoncleek/ergodic_exploration", "max_stars_repo_head_hexsha": "430e8293fc864af10088606ed07ed2d74c6a97d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T22:04:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T09:21:27.000Z", "max_issues_repo_path": "include/ergodic_exploration/basis.hpp", "max_issues_repo_name": "bostoncleek/ergodic_exploration", "max_issues_repo_head_hexsha": "430e8293fc864af10088606ed07ed2d74c6a97d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/ergodic_exploration/basis.hpp", "max_forks_repo_name": "bostoncleek/ergodic_exploration", "max_forks_repo_head_hexsha": "430e8293fc864af10088606ed07ed2d74c6a97d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-02-03T07:17:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T14:41:19.000Z", "avg_line_length": 36.6330275229, "max_line_length": 86, "alphanum_fraction": 0.6922113699, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5009441589395685}}
{"text": "#ifndef __ALGORITHM_BASE__\n#define __ALGORITHM_BASE__\n#include <Eigen/Dense>\n#include <ros/ros.h>\n#include <math.h>\n#include <stdexcept>\n\nnamespace manipulation_algorithms{\n  /**\n    Class that defines an algorithm base.\n  **/\n  class AlgorithmBase\n  {\n  public:\n    AlgorithmBase();\n    virtual ~AlgorithmBase();\n\n    /**\n      Obtain the parameters relevant to the controller from the parameter server.\n\n      @param n The nodehandle that will be used to query the parameter server\n      @return False in case of error\n    **/\n    virtual bool getParams(const ros::NodeHandle &n) = 0;\n\n  protected:\n    /**\n      Initialize a nxb matrix from values obtained from the ros parameter\n      server.\n\n      @param M The matrix to be initialized\n      @param configName The parameter server location\n      @param n The ros nodehandle used to query the parameter server\n\n      @return True for success, False otherwise\n    **/\n    virtual bool parseMatrixData(Eigen::MatrixXd &M, const std::string configName, const ros::NodeHandle &n);\n    virtual bool parseMatrixData(Eigen::Matrix3d &M, const std::string configName, const ros::NodeHandle &n);\n\n    /**\n      Fill in a nxn matrix with the given values.\n\n      @param M The matrix to be filled in. Will be set to the size nxn.\n      @param vals A vector with the values to fill in\n    **/\n    virtual void initializeEigenMatrix(Eigen::MatrixXd &M, const std::vector<double> vals);\n    virtual void initializeEigenMatrix(Eigen::Matrix3d &M, const std::vector<double> vals);\n\n    /**\n      Saturates a control output\n\n      @param original The computed output\n      @param max The maximum allowed absolute value for the computed output\n      @return The original, if abs(original) <= max, sign(original)*max otherwise\n    **/\n    virtual double saturateOutput(const double original, const double max);\n\n    /**\n      Computed the skew-symmetric matrix of a 3-dimensional vector.\n\n      @param v The 3-dimensional vector\n      @return The skew-symmetric matrix\n    **/\n    Eigen::Matrix3d computeSkewSymmetric(Eigen::Vector3d v);\n  };\n}\n#endif\n", "meta": {"hexsha": "d8925d7074f3fee63d33535eb4361e56730ad3d9", "size": 2088, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pr2_algorithms/include/pr2_algorithms/algorithm_base.hpp", "max_stars_repo_name": "diogoalmeida/pr2_controller_framework", "max_stars_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pr2_algorithms/include/pr2_algorithms/algorithm_base.hpp", "max_issues_repo_name": "diogoalmeida/pr2_controller_framework", "max_issues_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pr2_algorithms/include/pr2_algorithms/algorithm_base.hpp", "max_forks_repo_name": "diogoalmeida/pr2_controller_framework", "max_forks_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_forks_repo_licenses": ["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.7058823529, "max_line_length": 109, "alphanum_fraction": 0.6954022989, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5009441520446279}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2012, 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/*\nSolutions for testdata were generated with Scilab line:\n\nM=fscanfMat('nsm1.example');e=spec(M);e=gsort(e);rr=real(e);ii=imag(e);e=cat(1, rr, ii); s=strcat(string(e), ' ');write('tmp', s);\n*/\n\n#ifndef NDEBUG\n  #define NDEBUG\n#endif\n  \n//#define VIENNACL_DEBUG_ALL\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <vector>\n\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/qr-method.hpp\"\n\n#include <examples/benchmarks/benchmark-utils.hpp>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nnamespace ublas = boost::numeric::ublas;\n\ntypedef float ScalarType;\n\nconst ScalarType EPS = 0.00001f;\n\nvoid read_matrix_size(std::fstream& f, std::size_t& sz) \n{\n    if(!f.is_open())\n    {\n        throw std::invalid_argument(\"File is not opened\");\n    }\n\n    f >> sz;\n}\n\nvoid read_matrix_body(std::fstream& f, viennacl::matrix<ScalarType>& A)\n{\n    if(!f.is_open())\n    {\n        throw std::invalid_argument(\"File is not opened\");\n    }\n\n    boost::numeric::ublas::matrix<ScalarType> h_A(A.size1(), A.size2());\n\n    for(std::size_t i = 0; i < h_A.size1(); i++) {\n        for(std::size_t j = 0; j < h_A.size2(); j++) {\n            ScalarType val = 0.0;\n            f >> val;\n            h_A(i, j) = val;\n        }\n    }\n\n    viennacl::copy(h_A, A);\n}\n\nvoid read_vector_body(std::fstream& f, ublas::vector<ScalarType>& v) {\n    if(!f.is_open())\n        throw std::invalid_argument(\"File is not opened\");\n\n    for(std::size_t i = 0; i < v.size(); i++)\n    {\n            ScalarType val = 0.0;\n            f >> val;\n            v[i] = val;\n    }\n}\n\nbool check_tridiag(viennacl::matrix<ScalarType>& A_orig)\n{\n    ublas::matrix<ScalarType> A(A_orig.size1(), A_orig.size2());\n    viennacl::copy(A_orig, A);\n\n    for (unsigned int i = 0; i < A.size1(); i++) {\n        for (unsigned int j = 0; j < A.size2(); j++) {\n            if ((std::abs(A(i, j)) > EPS) && ((i - 1) != j) && (i != j) && ((i + 1) != j))\n            {\n                // std::cout << \"Failed at \" << i << \" \" << j << \" \" << A(i, j) << \"\\n\";\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nbool check_hessenberg(viennacl::matrix<ScalarType>& A_orig)\n{\n    ublas::matrix<ScalarType> A(A_orig.size1(), A_orig.size2());\n    viennacl::copy(A_orig, A);\n\n    for (std::size_t i = 0; i < A.size1(); i++) {\n        for (std::size_t j = 0; j < A.size2(); j++) {\n            if ((std::abs(A(i, j)) > EPS) && (i > (j + 1)))\n            {\n                // std::cout << \"Failed at \" << i << \" \" << j << \" \" << A(i, j) << \"\\n\";\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nScalarType matrix_compare(ublas::matrix<ScalarType>& res,\n                            ublas::matrix<ScalarType>& ref) \n{\n    ScalarType diff = 0.0;\n    ScalarType mx = 0.0;\n\n    for(std::size_t i = 0; i < res.size1(); i++)\n    {\n        for(std::size_t j = 0; j < res.size2(); j++)\n        {\n            diff = std::max(diff, std::abs(res(i, j) - ref(i, j)));\n            mx = std::max(mx, res(i, j));\n        }\n    }\n\n    return diff / mx;\n}\n\nScalarType vector_compare(ublas::vector<ScalarType>& res, \n                          ublas::vector<ScalarType>& ref) \n{\n    std::sort(ref.begin(), ref.end());\n    std::sort(res.begin(), res.end());\n\n    ScalarType diff = 0.0;\n    ScalarType mx = 0.0;\n    for(size_t i = 0; i < ref.size(); i++) \n    {\n        diff = std::max(diff, std::abs(res[i] - ref[i]));\n        mx = std::max(mx, res[i]);\n    }\n\n    return diff / mx;\n}\n\nvoid test_eigen(const std::string& fn, bool is_symm) \n{\n    std::cout << \"Reading...\" << \"\\n\";\n    std::size_t sz;\n    // read file\n    std::fstream f(fn.c_str(), std::fstream::in);\n    //read size of input matrix\n    read_matrix_size(f, sz);\n\n    viennacl::matrix<ScalarType> A_input(sz, sz), A_ref(sz, sz), Q(sz, sz);\n    ublas::vector<ScalarType> eigen_ref_re(sz, 0), eigen_ref_im(sz, 0), eigen_re(sz, 0), eigen_im(sz, 0);\n\n    read_matrix_body(f, A_input);\n    \n    read_vector_body(f, eigen_ref_re);\n    \n    if(!is_symm)    \n        read_vector_body(f, eigen_ref_im);\n\n    f.close();\n\n    A_ref = A_input;\n\n    std::cout << \"Calculation...\" << \"\\n\";\n    \n    Timer timer;\n    timer.start();\n\n    if(is_symm)\n        viennacl::linalg::qr_method_sym(A_input, Q, eigen_re);\n    else\n        viennacl::linalg::qr_method_nsm(A_input, Q, eigen_re, eigen_im);\n\n    // std::cout << A_input << \"\\n\";\n    viennacl::ocl::get_queue().finish();\n\n    double time_spend = timer.get();\n\n    std::cout << \"Verification...\" << \"\\n\";\n\n    bool is_hessenberg = check_hessenberg(A_input);\n    bool is_tridiag = check_tridiag(A_input);\n\n    ublas::matrix<ScalarType> result1(sz, sz), result2(sz, sz), tmp(sz, sz);\n    viennacl::copy(A_ref, tmp);\n    viennacl::copy(A_input, result1);\n    viennacl::copy(Q, result2);\n\n    result1 = ublas::prod(result2, result1);\n    result2 = ublas::prod(tmp, result2);\n\n    ScalarType prods_diff = matrix_compare(result1, result2);\n    ScalarType eigen_diff = vector_compare(eigen_ref_re, eigen_re);\n\n    bool is_ok = is_hessenberg;\n\n    if(is_symm)\n        is_ok = is_ok && is_tridiag;\n\n    is_ok = is_ok && (eigen_diff < EPS);\n    is_ok = is_ok && (prods_diff < EPS);\n    \n    // std::cout << A_ref << \"\\n\";\n    // std::cout << A_input << \"\\n\";\n    // std::cout << Q << \"\\n\";\n    // std::cout << eigen_re << \"\\n\";\n    // std::cout << eigen_im << \"\\n\";\n    // std::cout << eigen_ref_re << \"\\n\";\n    // std::cout << eigen_ref_im << \"\\n\";\n    \n    // std::cout << result1 << \"\\n\";\n    // std::cout << result2 << \"\\n\";\n    // std::cout << eigen_ref << \"\\n\";\n    // std::cout << eigen << \"\\n\";\n\n    printf(\"%6s [%dx%d] %40s time = %.4f\\n\", is_ok?\"[[OK]]\":\"[FAIL]\", (int)A_ref.size1(), (int)A_ref.size2(), fn.c_str(), time_spend);\n    printf(\"tridiagonal = %d, hessenberg = %d prod-diff = %f eigen-diff = %f\\n\", is_tridiag, is_hessenberg, prods_diff, eigen_diff);\n}\n\nint main()\n{\n  // test_eigen(\"../../examples/testdata/eigen/symm1.example\", true);\n  // test_eigen(\"../../examples/testdata/eigen/symm2.example\", true);\n  // test_eigen(\"../../examples/testdata/eigen/symm3.example\", true);\n\n  test_eigen(\"../../examples/testdata/eigen/nsm1.example\", false);\n  test_eigen(\"../../examples/testdata/eigen/nsm2.example\", false);\n  test_eigen(\"../../examples/testdata/eigen/nsm3.example\", false);\n  test_eigen(\"../../examples/testdata/eigen/nsm4.example\", false);\n\n  std::cout << std::endl;\n  std::cout << \"------- Test completed --------\" << std::endl;\n  std::cout << std::endl;\n   \n  return EXIT_SUCCESS;\n}", "meta": {"hexsha": "c01cddbe431048bec3f44c0e23a1cb41e286bbd9", "size": 7315, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/qr-method.cpp", "max_stars_repo_name": "bollig/viennacl", "max_stars_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T08:33:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T08:33:10.000Z", "max_issues_repo_path": "tests/src/qr-method.cpp", "max_issues_repo_name": "bollig/viennacl", "max_issues_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_issues_repo_licenses": ["MIT"], "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/qr-method.cpp", "max_forks_repo_name": "bollig/viennacl", "max_forks_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_forks_repo_licenses": ["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.7992125984, "max_line_length": 134, "alphanum_fraction": 0.5391660971, "num_tokens": 2089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6513548578981939, "lm_q1q2_score": 0.5009441485295135}}
{"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_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_HYPOT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-arithmetic\n    This function object computes the hypothenuse length: \\f$(x^2 + y^2)^{1/2}\\f$\n\n\n    @par Header <boost/simd/function/hypot.hpp>\n\n    @par Decorators\n\n     - pedantic_ with this decorator provisions are made to avoid overflow\n       and to compute  @c hypot as accurately as possible in any cases.\n\n     - std_ call std::hypot\n\n    @see sqr, sqrt\n\n    @par Example:\n\n      @snippet hypot.cpp hypot\n\n    @par Possible output:\n\n      @snippet hypot.txt hypot\n\n\n  **/\n  IEEEValue hypot(IEEEValue const& x, IEEEValue const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/hypot.hpp>\n#include <boost/simd/function/scalar/hypot.hpp>\n#include <boost/simd/function/simd/hypot.hpp>\n\n#endif\n", "meta": {"hexsha": "7c9903b10191a732bcff7cb4946d4d766a84fca1", "size": 1277, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/hypot.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/function/hypot.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/function/hypot.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": 23.6481481481, "max_line_length": 100, "alphanum_fraction": 0.5982772122, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5009441468396004}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"algorithms/math/partition_equally.hpp\"\n\nBOOST_AUTO_TEST_SUITE(TestPartitionEquality)\n\nBOOST_AUTO_TEST_CASE(test)\n{\n    {\n        const std::vector<uint32_t> elements = { 2, 1, 4, 5, 3, 3 };\n        const uint32_t numOfPartitions = 3;\n        BOOST_CHECK(\n            Algo::Math::PartitionEqually::CanPartition(elements, numOfPartitions));\n    }\n\n    {\n        const std::vector<uint32_t> elements = { 3, 3, 3, 3 };\n        const uint32_t numOfPartitions = 3;\n        BOOST_CHECK(\n            false == Algo::Math::PartitionEqually::CanPartition(elements, numOfPartitions));\n    }\n\n    {\n        const std::vector<uint32_t> elements = { 40 };\n        const uint32_t numOfPartitions = 3;\n        BOOST_CHECK(\n            false == Algo::Math::PartitionEqually::CanPartition(elements, numOfPartitions));\n    }\n\n    {\n        const std::vector<uint32_t> elements =\n            { 17, 59, 34, 57, 17, 23, 67, 1, 18, 2, 59 };\n        const uint32_t numOfPartitions = 3;\n        BOOST_CHECK(\n            Algo::Math::PartitionEqually::CanPartition(elements, numOfPartitions));\n    }\n\n    {\n        const std::vector<uint32_t> elements =\n            { 1, 2, 3, 4, 5, 5, 7, 7, 8, 10, 12, 19, 25 };\n        const uint32_t numOfPartitions = 3;\n        BOOST_CHECK(\n            Algo::Math::PartitionEqually::CanPartition(elements, numOfPartitions));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "fdcfc4fc77ded3f31c73a45e217f2800c304d24d", "size": 1417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/math/test_partition_equally.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_partition_equally.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_partition_equally.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": 30.1489361702, "max_line_length": 92, "alphanum_fraction": 0.609738885, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5009441364295455}}
{"text": "/**\n * \\ file AttackReleaseFilter.cpp\n */\n\n#include <ATK/Dynamic/AttackReleaseFilter.h>\n\n#include <ATK/Core/InPointerFilter.h>\n#include <ATK/Core/OutPointerFilter.h>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/scoped_array.hpp>\n\n#define PROCESSSIZE (1024*64)\n\nBOOST_AUTO_TEST_CASE( AttackReleaseFilter_triangle_test )\n{\n  boost::scoped_array<float> data(new float[PROCESSSIZE]);\n  for(int64_t i = 0; i < PROCESSSIZE/2; ++i)\n  {\n    data[i] = i / 48000;\n  }\n  for(int64_t i = 0; i < PROCESSSIZE/2; ++i)\n  {\n    data[PROCESSSIZE/2 + i] = (PROCESSSIZE/2 - i) / 48000;\n  }\n  \n  ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);\n  generator.set_output_sampling_rate(48000);\n\n  boost::scoped_array<float> outdata(new float[PROCESSSIZE]);\n\n  ATK::AttackReleaseFilter<float> filter(1);\n  filter.set_attack(std::exp(-1./(48000 * 1e-3)));\n  filter.set_release(std::exp(-1./(48000 * 100e-3)));\n  filter.set_input_sampling_rate(48000);\n  filter.set_input_port(0, &generator, 0);\n\n  ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);\n  output.set_input_sampling_rate(48000);\n  output.set_input_port(0, &filter, 0);\n\n  output.process(PROCESSSIZE);\n  \n  for(int64_t i = 0; i < PROCESSSIZE/2; ++i)\n  {\n    BOOST_REQUIRE_GE(data[i], outdata[i]);\n  }\n  for(int64_t i = 0; i < PROCESSSIZE/2; ++i)\n  {\n    BOOST_REQUIRE_GE(outdata[PROCESSSIZE/2+i], outdata[PROCESSSIZE/2+i-1]);\n  }\n}\n", "meta": {"hexsha": "fe4f29efb34e0ba7edd6713fb25d594b21446d00", "size": 1523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Dynamic/AttackReleaseFilter.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": "tests/Dynamic/AttackReleaseFilter.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": "tests/Dynamic/AttackReleaseFilter.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": 26.7192982456, "max_line_length": 76, "alphanum_fraction": 0.7032173342, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505966, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5008451675796575}}
{"text": "/* p_integrand.cpp */\n#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/interpolators/cubic_hermite.hpp>\n#include <algorithm>\n\nextern \"C\"\n{\n/* Survival function for R^phi*W */\nint RW_marginal_C(double *xval, double phi, double gamma, int n_xval, double *result){\n    double tmp2 = pow(gamma/2, phi)/boost::math::tgamma(0.5);\n    double tmp1, tmp0, a;\n    a = 0.5-phi;\n    \n    for(int i=0; i<n_xval; i++){\n        tmp1 = gamma/(2*pow(xval[i],1/phi));\n        tmp0 = tmp2/(a*xval[i]);\n        result[i] = boost::math::gamma_p(0.5L,tmp1) + boost::math::tgamma((long double)(a+1),tmp1)*tmp0-pow(tmp1,a)*exp(-tmp1)*tmp0;\n    }\n    return 1;\n}\n\n/* Marginal distribution function for R^phi*W + epsilon */\nint pRW_me_interp_C(double *xval, double *xp, double *surv_p, double tau_sqd, double phi, double gamma, int n_xval, int n_grid, double *result){\n    bool tau_bool = (tau_sqd > 0.05);\n    double tp[n_grid];\n    double integrand_p[n_grid];\n    double tmp, tmp_res; /* temporary constant */\n    double tmp_sum = 0; /* temporary trapesoid sum */\n    double sd = sqrt(tau_sqd);\n    double sd_const = sqrt(2)*sd;\n    double sd_const_pi =sqrt(2*M_PI)*sd;\n    int i,j, tmp_int; /* iterative constants */\n\n    for (i = 0; i < n_xval; i++) {\n        if(tau_bool & (xval[i]<820)){\n            /* Calculate integrand on a grid */\n            for(j=0; j<n_grid;j++){\n                tmp = xval[i]-xp[j];\n                tp[j] = tmp;\n                integrand_p[j] = exp(-tmp*tmp/(2*tau_sqd)) * surv_p[j];\n            }\n            \n            /* Numerical integral using the trapesoid method */\n            for(j=0; j<(n_grid-1);j++){\n                tmp_sum+= (tp[j+1]-tp[j])*(integrand_p[j] + integrand_p[j+1])/2;\n            }\n            tmp_res = 0.5*erfc(-xval[i]/sd_const)-tmp_sum/sd_const_pi;\n            tmp_sum = 0;\n            \n            /* CDF value must be greater than 0 */\n            if(tmp_res < 0){\n                tmp_res = 0;\n            }\n            result[i] = tmp_res;\n        }\n        else{\n            tmp_int = RW_marginal_C(&xval[i], phi, gamma, 1, &tmp_res);\n            result[i] = 1-tmp_res;\n        }\n    }\n    \n    return 1;\n}\n\n\n/* Transform to uniform scales from RW mixtures */\nint RW_me_2_unifs(double *X, double *xp, double *Surv, double tau_sqd, double *phi, double gamma,\n                    int n_s, int n_grid, int n_t, double *unifs){\n    int tmp_int, X_lookup, Surv_lookup;\n    for (int i = 0; i<n_s;i++){\n        X_lookup = i*n_t;\n        Surv_lookup = i*n_grid;\n        tmp_int = pRW_me_interp_C(X+X_lookup, xp, Surv+Surv_lookup, tau_sqd, phi[i], gamma, n_t, n_grid, unifs+X_lookup);\n    }\n    \n    return 1;\n}\n\n\n\n/* Get the quantile range for certain probability levels */\nint find_xrange_pRW_me_C(double min_p, double max_p, double min_x, double max_x, double *xp, double *surv_p, double tau_sqd, double phi, double gamma, int n_grid, double *x_range){\n    if (min_x >= max_x){\n        printf(\"Initial value of mix_x must be smaller than max_x.\\n\");\n        exit(EXIT_FAILURE);\n    }\n    \n    /* First the min */\n    double p_min_x;\n    int tmp_int;\n    tmp_int = pRW_me_interp_C(&min_x, xp, surv_p, tau_sqd, phi, gamma, 1, n_grid, &p_min_x);\n    while (p_min_x > min_p){\n        min_x = min_x-40/phi;\n        tmp_int = pRW_me_interp_C(&min_x, xp, surv_p, tau_sqd, phi, gamma, 1, n_grid, &p_min_x);\n    }\n        \n    x_range[0] = min_x;\n    \n    /* Now the max */\n    double p_max_x;\n    tmp_int = pRW_me_interp_C(&max_x, xp, surv_p, tau_sqd, phi, gamma, 1, n_grid, &p_max_x);\n    while (p_max_x < max_p){\n        max_x = max_x*2; /* Upper will set to 20 initially */\n        tmp_int = pRW_me_interp_C(&max_x, xp, surv_p, tau_sqd, phi, gamma, 1, n_grid, &p_max_x);\n    }\n        \n    x_range[1] = max_x;\n    return 1;\n}\n\n/* PCHIP 1-D monotonic cubic interpolation */\nusing boost::math::interpolators::cubic_hermite;\nint pchip(double *x_input, double *y_input, double *x_pred, double *y_pred_res, int n, int n_pred){\n    std::vector<double> x(n);\n    memcpy(&x[0], x_input, n*sizeof(double));\n    std::vector<double> y(n);\n    memcpy(&y[0], y_input, n*sizeof(double));\n   \n    double left_endpoint_derivative = std::numeric_limits<double>::quiet_NaN();\n    double right_endpoint_derivative = std::numeric_limits<double>::quiet_NaN();\n    std::vector<double> s(x.size(), std::numeric_limits<double>::quiet_NaN());\n    if (isnan(left_endpoint_derivative)){\n        // O(h) finite difference derivative:\n        // This, I believe, is the only derivative guaranteed to be monotonic:\n        s[0] = (y[1]-y[0])/(x[1]-x[0]);\n    }else{\n        s[0] = left_endpoint_derivative;\n    }\n\n    for (int k = 1; k < n-1; ++k) {\n        double hkm1 = x[k] - x[k-1];\n        double dkm1 = (y[k] - y[k-1])/hkm1;\n\n        double hk = x[k+1] - x[k];\n        double dk = (y[k+1] - y[k])/hk;\n        double w1 = 2*hk + hkm1;\n        double w2 = hk + 2*hkm1;\n        if ( (dk > 0 && dkm1 < 0) || (dk < 0 && dkm1 > 0) || dk == 0 || dkm1 == 0){\n            s[k] = 0;\n        }else{\n            s[k] = (w1+w2)/(w1/dkm1 + w2/dk);\n        }\n\n    }\n    // Quadratic extrapolation at the other end:\n    if (isnan(right_endpoint_derivative)){\n                s[n-1] = (y[n-1]-y[n-2])/(x[n-1] - x[n-2]);\n    }else{\n                s[n-1] = right_endpoint_derivative;\n    }\n    \n    auto spline = cubic_hermite<std::vector<double>>(std::move(x), std::move(y), std::move(s));\n\n    for(int j=0; j<n_pred; j++){\n        y_pred_res[j] = spline(x_pred[j]);\n    }\n    return 1;\n}\n\n\n/* Quantile inverse function for R^phi*W + epsilon*/\nint qRW_me_interp(double *p, double *xp, double *surv_p, double tau_sqd, double phi, double gamma,\n                  int n_p, int n_grid, double *result,\n                  double *cdf_vals, double *x_vals, int n_x=400, double lower=5, double upper=20\n                ){\n    int tmp_int, i, zeros;\n    double min_p, max_p, delta, tmp_double;\n    bool large_delta_large_x = false;\n    \n    // (1) When phi is varying over space, we need to calculate one quantile for each phi value.\n    // Given more accuarte [lower,upper] values for the single p, we can decrease n_x.\n    if(n_p<2){ n_x=floor(100*(p[0]+0.1));}\n    double x_vals1[n_x+150];\n    double cdf_vals1[n_x+150];\n    \n    // (2) Generate x_vals and cdf_vals to interpolate\n    if(isnan(x_vals[0])){\n        double x_range[2];\n        max_p = *std::max_element(p, p+n_p);\n        min_p = *std::min_element(p, p+n_p);\n        tmp_int = find_xrange_pRW_me_C(min_p, max_p, lower, upper, xp, surv_p, tau_sqd,\n                                       phi, gamma, n_grid, x_range);\n        if (isinf(x_range[1])){   // Upper is set to 20 initially\n            x_range[1] = std::pow(10,20);\n            large_delta_large_x = true;\n        }\n        if (x_range[0]<=0){\n            delta = (0.0001 - x_range[0]) / 149;\n            for(i=0; i<150; i++){\n                x_vals1[i] = x_range[0] + delta * i;\n            }\n            delta = (log(x_range[1])-log(0.0001001)) / (n_x-1);\n            for(i=0; i<n_x; i++){\n                x_vals1[i+150] = exp(log(0.0001001) + delta * i);\n            }\n            n_x=150+n_x;\n        }else{\n            delta = (log(x_range[1])-log(x_range[0])) / (n_x-1);\n            for(i=0; i<n_x; i++){\n                x_vals1[i] = exp(log(x_range[0]) + delta * i);\n            }\n        }\n        tmp_int = pRW_me_interp_C(x_vals1, xp, surv_p, tau_sqd, phi, gamma, n_x, n_grid, cdf_vals1);\n    }else{\n        double x_vals1[n_x];\n        double cdf_vals1[n_x];\n        memcpy(x_vals1, x_vals, n_x*sizeof(double));\n        if(isnan(cdf_vals[0])){\n            tmp_int = pRW_me_interp_C(x_vals1, xp, surv_p, tau_sqd, phi, gamma, n_x, n_grid, cdf_vals1);\n        }else{\n            memcpy(cdf_vals1, cdf_vals, n_x*sizeof(double));\n        }\n    }\n    \n    // (3) Obtain the quantile level using the interpolated function\n    if(!large_delta_large_x){\n        zeros = 0;\n        tmp_double = cdf_vals1[zeros];\n        while (tmp_double==0) {\n            tmp_double = cdf_vals1[++zeros];\n        }\n        tmp_int = pchip(cdf_vals1+zeros, x_vals1+zeros, p, result, n_x-zeros, n_p);\n    }else{\n        int exceeds = 0;\n        for (i=0;i<n_p;i++){\n            if(p[i]>cdf_vals1[n_x-1]) exceeds+=1;\n        }\n        tmp_int = pchip(cdf_vals1, x_vals1, p, result, n_x, n_p-exceeds);\n        for (i=n_p-exceeds;i<n_p;i++){\n            result[i] = x_vals[n_x-1];\n        }\n    }\n    return 1;\n}\n    \n\n/* Density function for R^phi*W */\nint RW_density_C(double *xval, double phi, double gamma, int n_xval, double *result){\n    double tmp2 = pow(gamma/2, phi)/boost::math::tgamma(0.5);\n    double tmp1, tmp0, a;\n    a = 0.5-phi;\n    \n    for(int i=0; i<n_xval; i++){\n        tmp1 = gamma/(2*pow(xval[i],1/phi));\n        tmp0 = tmp2/(a*pow(xval[i],2));\n        result[i] = (boost::math::tgamma((long double)(a+1),tmp1)-pow(tmp1,a)*exp(-tmp1))*tmp0;\n    }\n    return 1;\n}\n\n/* Marginal density function for R^phi*W + epsilon */\nint dRW_me_interp_C(double *xval, double *xp, double *den_p, double tau_sqd, double phi, double gamma, int n_xval, int n_grid, double *result){\n    double thresh_large = 820;\n    if(tau_sqd < 1) {\n        thresh_large = 50;\n    }\n    bool tau_bool = (tau_sqd > 0.05);\n    \n    double tp[n_grid];\n    double integrand_p[n_grid];\n    double tmp, tmp_res; /* temporary constant */\n    double tmp_sum = 0; /* temporary trapesoid sum */\n    double sd = sqrt(tau_sqd);\n    double sd_const_pi =sqrt(2*M_PI)*sd;\n    int i,j, tmp_int; /* iterative constants */\n\n    for (i = 0; i < n_xval; i++) {\n        if(tau_bool & (xval[i]<thresh_large)){\n            /* Calculate integrand on a grid */\n            for(j=0; j<n_grid;j++){\n                tmp = xval[i]-xp[j];\n                tp[j] = tmp;\n                integrand_p[j] = exp(-tmp*tmp/(2*tau_sqd)) * den_p[j];\n            }\n            \n            /* Numerical integral using the trapesoid method */\n            for(j=0; j<(n_grid-1);j++){\n                tmp_sum+= (tp[j+1]-tp[j])*(integrand_p[j] + integrand_p[j+1])/2;\n            }\n            tmp_res = tmp_sum/sd_const_pi;\n            tmp_sum = 0;\n            result[i] = tmp_res;\n        }else if((tau_bool & (xval[i]>=thresh_large))|(!tau_bool & (xval[i]>0))){\n            tmp_int = RW_density_C(&xval[i], phi, gamma, 1, &tmp_res);\n            result[i] = tmp_res;\n        }else{\n            result[i] = 0;\n        }\n    }\n    \n    return 1;\n}\n\nint density_interp_grid(double *xp, double *phi, double gamma, int n_phi, int n_grid, double *Den, double *Surv){\n    int counter = 0;\n    int i,j, tmp_int;\n    double tmp_surv, tmp_den;\n    double tmp2, tmp1, tmp0, a, tmp_incomp, tmp_phi, tmp_phi_inv, tmp_xp;\n    double gamma_half = gamma/2;\n    \n    for(i=0; i<n_phi; i++){\n        tmp_phi = phi[i];\n        a = 0.5-tmp_phi;\n        tmp2 = std::pow(gamma_half, tmp_phi)/(a*sqrt(M_PI));\n        tmp_phi_inv = 1/tmp_phi;\n        for(j=0; j<n_grid; j++){\n            tmp_xp = xp[j];\n            tmp1 = gamma_half/std::pow(tmp_xp,tmp_phi_inv);\n            tmp0 = tmp2/tmp_xp;\n            tmp_incomp = (boost::math::tgamma((long double)(a+1),tmp1)-std::pow(tmp1,a)*exp(-tmp1))*tmp0;\n            Surv[counter] = boost::math::gamma_p(0.5L,tmp1) + tmp_incomp;\n            Den[counter++] = tmp_incomp/tmp_xp;\n        }\n    }\n    return 1;\n}\n\ndouble dgev_C(double y, double loc, double scale, double shape, bool log_out){\n    double t = std::pow(1+shape*((y-loc)/scale), -1/shape);\n    double result;\n    if(log_out){\n        result = -log(scale)+(shape+1)*log(t)-t;\n    }else{\n        result = std::pow(t, shape+1)*exp(-t)/scale;\n    }\n    return result;\n}\n\ndouble dnorm_C(double y, double mean, double sd, bool log_out){\n    double t=(y-mean)/sd;\n    double result;\n    if(log_out){\n        result = -0.5*log(2*M_PI)-log(sd)-0.5*t*t;\n    }else{\n        result = exp(-0.5*t*t)/(sqrt(2*M_PI)*sd);\n    }\n    return result;\n}\n\n/* Thresh_X and Thresh_X_above are required */\n/* xp, den_p and surv_p are required */\n/* Calculate column_wise in C order OR one time  */\ndouble marg_transform_data_mixture_me_likelihood_C(double *Y, double *X, double *X_s, bool *cen, bool *cen_above,\n                                                double *Loc, double *Scale, double *Shape,\n                                                double tau_sqd, double *phi, double gamma,\n                                                double *xp, double *Den, int n_s, int n_grid){\n    double sd = sqrt(tau_sqd);\n    double sd_const = sqrt(2)*sd;\n    double ll=0;\n    double RW_den;\n    int i, tmp_int, Den_lookup;\n    \n    for (i=0; i<n_s; i++){\n        if(cen[i]){\n            ll += log(0.5*erfc(-(X[i]-X_s[i])/sd_const));\n        }else if(cen_above[i]){\n            ll += log(1-0.5*erfc(-(X[i]-X_s[i])/sd_const));\n        }else{\n            Den_lookup = i*n_grid;\n            tmp_int = dRW_me_interp_C(&X[i], xp, &Den[Den_lookup], tau_sqd, phi[i], gamma, 1, n_grid, &RW_den);\n            ll += dnorm_C(X[i], X_s[i], sd, true)+dgev_C(Y[i], Loc[i], Scale[i], Shape[i], true)-log(RW_den);\n        }\n    }\n    return ll;\n}\n\n/* Calculate row_wise in F order OR one location */\ndouble marg_transform_data_mixture_me_likelihood_F(double *Y, double *X, double *X_s, bool *cen, bool *cen_above,\n                                                double *Loc, double *Scale, double *Shape,\n                                                double tau_sqd, double phi, double gamma,\n                                                double *xp, double *den_p, int n_t, int n_grid){\n    double sd = sqrt(tau_sqd);\n    double sd_const = sqrt(2)*sd;\n    double ll=0;\n    double RW_den;\n    int i, tmp_int;\n    \n    for (i=0; i<n_t; i++){\n        if(cen[i]){\n            ll += log(0.5*erfc(-(X[i]-X_s[i])/sd_const));\n        }else if(cen_above[i]){\n            ll += log(1-0.5*erfc(-(X[i]-X_s[i])/sd_const));\n        }else{\n            tmp_int = dRW_me_interp_C(&X[i], xp, den_p, tau_sqd, phi, gamma, 1, n_grid, &RW_den);\n            ll += dnorm_C(X[i], X_s[i], sd, true)+dgev_C(Y[i], Loc[i], Scale[i], Shape[i], true)-log(RW_den);\n        }\n    }\n    return ll;\n}\n\n/* Calculate all locations and all times */\ndouble marg_transform_data_mixture_me_likelihood_global(double *Y, double *X, double *X_s, bool *cen, bool *cen_above,\n                                                double *Loc, double *Scale, double *Shape,\n                                                double tau_sqd, double *phi, double gamma,\n                                                double *xp, double *Den, int n_s, int n_t, int n_grid){\n    \n    double ll=0;\n    int site, tmp_int, Den_lookup, X_lookup;\n    \n    for (site=0; site<n_s; site++){\n        X_lookup = site*n_t;\n        Den_lookup = site*n_grid;\n        ll += marg_transform_data_mixture_me_likelihood_F(&Y[X_lookup], &X[X_lookup], &X_s[X_lookup], &cen[X_lookup], &cen_above[X_lookup], &Loc[X_lookup], &Scale[X_lookup], &Shape[X_lookup], tau_sqd, phi[site], gamma, xp, &Den[Den_lookup], n_t, n_grid);\n    }\n    return ll;\n}\n\n/* Calculate thresh_X and thresh_X_above for an array of phi values */\n// First way: iterate through each prob at each location (Not efficient)\nint Thresh_X_try(double *phi, double *xp, double *Surv, double prob_below, double prob_above, double tau_sqd, double gamma,\n                    double below_approx, double above_approx,\n                    int n_phi, int n_grid, double *Thresh_X, double *Thresh_X_above){\n    int Surv_lookup, tmp_int;\n    int n_x=100;\n    double cdf_vals[n_x], x_vals[n_x];\n    double tmp_res;\n    cdf_vals[0] = std::numeric_limits<double>::quiet_NaN(); x_vals[0] = std::numeric_limits<double>::quiet_NaN();\n    \n    for (int i = 0; i<n_phi;i++){\n        Surv_lookup = i*n_grid;\n        tmp_int = qRW_me_interp(&prob_below, xp, &Surv[Surv_lookup], tau_sqd, phi[i], gamma,\n                          1, n_grid, &tmp_res,\n                          cdf_vals, x_vals, n_x, below_approx-10, below_approx+10);\n        Thresh_X[i] = tmp_res;\n        tmp_int = qRW_me_interp(&prob_above, xp, &Surv[Surv_lookup], tau_sqd, phi[i], gamma,\n                          1, n_grid, &tmp_res,\n                          cdf_vals, x_vals, n_x, above_approx-100, above_approx+200);\n        Thresh_X_above[i] = tmp_res;\n    }\n    \n    return 1;\n}\n\n// Second way: calculate probs altogether at each location\nint X_update(double *phi, double *xp, double *Surv, double *probs, double tau_sqd, double gamma,\n                    double below_approx, double above_approx,\n                    int n_phi, int n_grid, int n_probs, double *X_res){\n    int Surv_lookup, tmp_int, X_lookup;\n    int n_x=100;\n    double cdf_vals[n_x], x_vals[n_x];\n    cdf_vals[0] = std::numeric_limits<double>::quiet_NaN(); x_vals[0] = std::numeric_limits<double>::quiet_NaN();\n    \n    for (int i = 0; i<n_phi;i++){\n        Surv_lookup = i*n_grid;\n        X_lookup = i*n_probs;\n        tmp_int = qRW_me_interp(probs, xp, &Surv[Surv_lookup], tau_sqd, phi[i], gamma,\n                          n_probs, n_grid, X_res + X_lookup,\n                          cdf_vals, x_vals, n_x, below_approx-10, above_approx+200);\n    }\n    \n    return 1;\n}\n\nint unifs_2_RW_me(double *unifs, double *xp, double *Surv, double tau_sqd, double *phi, double gamma,\n                    double below_approx, double above_approx,\n                    int n_phi, int n_grid, int n_probs_each_loc, double *X_res){\n    int Surv_lookup, tmp_int, X_lookup;\n    int n_x=100;\n    double cdf_vals[n_x], x_vals[n_x];\n    cdf_vals[0] = std::numeric_limits<double>::quiet_NaN(); x_vals[0] = std::numeric_limits<double>::quiet_NaN();\n    \n    for (int i = 0; i<n_phi;i++){\n        Surv_lookup = i*n_grid;\n        X_lookup = i*n_probs_each_loc;\n        tmp_int = qRW_me_interp(unifs + X_lookup, xp, &Surv[Surv_lookup], tau_sqd, phi[i], gamma,\n                          n_probs_each_loc, n_grid, X_res + X_lookup,\n                          cdf_vals, x_vals, n_x, below_approx-10, above_approx+200);\n    }\n    \n    return 1;\n}\n\nvoid print_c(double *Y, int n_grid){\n    printf(\"%4.2f %4.2f\\n\",*Y,*(Y+n_grid-1));\n}\n\ndouble print_Vec(double *Y, int n_grid, int n_s){\n    int Den_lookup;\n    for(int i=0; i<n_s; i++){\n        Den_lookup = i*n_grid;\n        print_c(&Y[Den_lookup], n_grid);\n    }\n    \n    return Y[0];\n}\n\n\n}\n", "meta": {"hexsha": "d1607469e1acd2fe4adf2ef0d9132c5bdf66614a", "size": 18293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "p_integrand.cpp", "max_stars_repo_name": "likun-stat/nonstat_model_noXs_global", "max_stars_repo_head_hexsha": "641f2fde7cda51713f5bd5a511fafc452f5fba63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "p_integrand.cpp", "max_issues_repo_name": "likun-stat/nonstat_model_noXs_global", "max_issues_repo_head_hexsha": "641f2fde7cda51713f5bd5a511fafc452f5fba63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "p_integrand.cpp", "max_forks_repo_name": "likun-stat/nonstat_model_noXs_global", "max_forks_repo_head_hexsha": "641f2fde7cda51713f5bd5a511fafc452f5fba63", "max_forks_repo_licenses": ["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.1054766734, "max_line_length": 254, "alphanum_fraction": 0.5611982726, "num_tokens": 5450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5008451675796574}}
{"text": "//\n// ConfusionMatrix.cpp\n// Represents a confusion matrix for multi-class evaluation\n//\n\n#include \"evaluation/ConfusionMatrix.hpp\"\n\n#include <algorithm>\n\n#ifdef __APPLE__\n    #include <eigen3/Eigen/Dense>\n#else\n    #include <Eigen/Dense>\n#endif\n\nnamespace Evaluation\n{\n    // Constructor\n    ConfusionMatrix::ConfusionMatrix(const std::vector<std::string> &classLabels) : m_ClassLabels(classLabels), m_Matrix(classLabels.size(), classLabels.size())\n    {\n        // initialise matrix\n        for (size_t i = 0; i < m_ClassLabels.size(); i++)\n        {\n            for (size_t j = 0; j < m_ClassLabels.size(); j++) {\n                m_Matrix(i, j) = 0;\n            }\n        }\n    }\n\n    // Destructor\n    ConfusionMatrix::~ConfusionMatrix() = default;\n\n    void ConfusionMatrix::AddClassifications(const std::string &predictedClass, const std::string &actualClass, int count)\n    {\n        int x = IndexOfClass(predictedClass);\n        int y = IndexOfClass(actualClass);\n\n        m_Matrix(y, x) = m_Matrix(y, x) + count;\n    }\n\n    // Get the index of class label\n    int ConfusionMatrix::IndexOfClass(const std::string& classLabel) const\n    {\n        auto iter = std::find(m_ClassLabels.begin(), m_ClassLabels.end(), classLabel);\n        if (iter != m_ClassLabels.end()) {\n            return static_cast<int>(std::distance(m_ClassLabels.begin(), iter));\n        }\n        else {\n            return -1;\n        }\n    }\n\n    // Precision\n    float ConfusionMatrix::GetPrecision(const std::string& classLabel) const\n    {\n        int index = IndexOfClass(classLabel);\n        if (index < 0) {\n            return 0.0;\n        }\n\n        float truePositives = m_Matrix(index, index);\n        float total = m_Matrix.colwise().sum()(0);\n\n        if (total == 0.0) {\n            total = 1.0;\n        }\n\n        return (truePositives / total);\n    }\n\n    // Recall\n    float ConfusionMatrix::GetRecall(const std::string &classLabel) const\n    {\n        int index = IndexOfClass(classLabel);\n        if (index < 0) {\n            return 0.0;\n        }\n\n        float truePositives = m_Matrix(index, index);\n\n        float total = m_Matrix.rowwise().sum()(0);\n        if (total == 0.0) {\n            total = 1.0;\n        }\n\n        return (truePositives / total);\n    }\n\n    // Accuracy\n    float ConfusionMatrix::GetAccuracy() const\n    {\n        float correct = m_Matrix.diagonal().sum();\n        float total = m_Matrix.sum();\n\n        if (total == 0) {\n            total = 1.0;\n        }\n\n        return (correct / total);\n    }\n\n    // Output stream\n    std::ostream& operator<<(std::ostream& os, const ConfusionMatrix& cm)\n    {\n        // output headers\n        os << \",\";\n        for (size_t i = 0; i < cm.m_ClassLabels.size(); i++)\n        {\n            os << cm.m_ClassLabels[i];\n            if (i < cm.m_ClassLabels.size() - 1) {\n                os << \",\";\n            }\n        }\n        os << std::endl;\n\n        // output confusion matrix\n        for (int i = 0; i < cm.m_ClassLabels.size(); i++)\n        {\n            os << cm.m_ClassLabels[i] << \",\";\n            for (int j = 0; j < cm.m_ClassLabels.size(); j++)\n            {\n                os << cm.m_Matrix(i, j);\n                if (j < cm.m_ClassLabels.size() - 1) {\n                    os << \",\";\n                }\n            }\n            os << std::endl;\n        }\n\n        return os;\n    }\n\n    // Append other confusion matrix data\n    ConfusionMatrix& ConfusionMatrix::operator+=(const Evaluation::ConfusionMatrix &other) {\n        this->m_Matrix += other.m_Matrix;\n        return *this;\n    }\n}\n", "meta": {"hexsha": "327313ac903920aa05c794a121a770f67ec4590c", "size": 3565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fumarole_localization/src/evaluation/ConfusionMatrix.cpp", "max_stars_repo_name": "asadahmedde/advanced-project-2", "max_stars_repo_head_hexsha": "748f8f9a575cf926646201cecb0e5a8d3bdaf377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fumarole_localization/src/evaluation/ConfusionMatrix.cpp", "max_issues_repo_name": "asadahmedde/advanced-project-2", "max_issues_repo_head_hexsha": "748f8f9a575cf926646201cecb0e5a8d3bdaf377", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fumarole_localization/src/evaluation/ConfusionMatrix.cpp", "max_forks_repo_name": "asadahmedde/advanced-project-2", "max_forks_repo_head_hexsha": "748f8f9a575cf926646201cecb0e5a8d3bdaf377", "max_forks_repo_licenses": ["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.6474820144, "max_line_length": 160, "alphanum_fraction": 0.5321178121, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5008257066347745}}
{"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_MAX_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MAX_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing max capabilities\n\n    Computes the largest of its parameter.\n\n    @par semantic:\n    For any given value @c x and @c y of type @c T:\n\n    @code\n    T r = max(x, y);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r =  (x > y) ? x : y;\n    @endcode\n\n    @par Note:\n\n    With this definition max(x, @ref Nan) should return x...\n\n    On some systems (namely for example vmx in simd mode) the intrinsic used returns Nan as soon x or y is a nan.\n    So the real definition of our max function must add: but if y is Nan the result is system dependent.\n\n    This can be corrected using the conformant_ decorator that ensures the standard behaviour at a cost.\n\n    @see maxnum, maxnummag,  maxmag\n\n  **/\n  Value max(Value const& x, Value const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/max.hpp>\n#include <boost/simd/function/simd/max.hpp>\n\n#endif\n", "meta": {"hexsha": "51c5b7b1bf544809738a5df8e46aa70a34034347", "size": 1467, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/max.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/max.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/max.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 25.2931034483, "max_line_length": 113, "alphanum_fraction": 0.6012269939, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.5008257066347745}}
{"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__DIFF_HPP_\n#define SMOOTH__DIFF_HPP_\n\n/**\n * @file\n * @brief Differentiation on Manifolds.\n */\n\n#include <Eigen/Core>\n#include <type_traits>\n\n#include \"internal/utils.hpp\"\n#include \"manifold.hpp\"\n#include \"wrt.hpp\"\n\nnamespace smooth {\n\n// differentiation module\nnamespace diff {\nnamespace detail {\n\n/**\n * @brief Numerical first-order differentiation in tangent space.\n *\n * @param f function to differentiate\n * @param x reference tuple of function arguments\n * @return \\p std::pair containing value and right derivative: \\f$(f(x), \\mathrm{d}^r f_x)\\f$\n *\n * @note All arguments in x as well as the return type \\f$f(x)\\f$ must satisfy\n * the Manifold concept.\n */\ntemplate<std::size_t K = 1>\n  requires(K >= 1 && K <= 2)\nauto dr_numerical(auto && f, auto && x)\n{\n  using Wrt    = decltype(x);\n  using Result = decltype(std::apply(f, x));\n  using Scalar = ::smooth::Scalar<Result>;\n\n  static constexpr auto NumArgs = std::tuple_size_v<std::decay_t<Wrt>>;\n\n  static_assert(Manifold<Result>, \"f(x) is not a Manifold\");\n\n  const Scalar eps = std::sqrt(Eigen::NumTraits<Scalar>::epsilon());\n\n  // arguments are modified below, so we create a copy of those that come in as const\n  auto x_nc = wrt_copy_if_const(std::forward<Wrt>(x));\n  Result F  = std::apply(f, x_nc);\n\n  // static sizes\n  static constexpr Eigen::Index Nx = wrt_Dof<Wrt>();\n  static constexpr Eigen::Index Ny = Dof<Result>;\n\n  // dynamic sizes\n  Eigen::Index nx = std::apply([](auto &&... args) { return (dof(args) + ...); }, x_nc);\n  Eigen::Index ny = dof<Result>(F);\n\n  // output variable\n  Eigen::Matrix<Scalar, Ny, Nx> J(ny, nx);\n\n  if constexpr (K == 1) {\n    Eigen::Index I0 = 0;\n    utils::static_for<NumArgs>([&](auto i) {\n      auto & w = std::get<i>(x_nc);\n      using W  = std::decay_t<decltype(w)>;\n\n      static constexpr Eigen::Index Nx_j = Dof<W>;\n      const int nx_j                     = dof<W>(w);\n\n      for (auto j = 0; j != nx_j; ++j) {\n        Scalar eps_j = eps;\n        if constexpr (std::is_base_of_v<Eigen::MatrixBase<W>, W>) {\n          // scale step size if we are in Rn\n          eps_j *= abs(w[j]);\n          if (eps_j == 0.) { eps_j = eps; }\n        }\n        w             = rplus<W>(w, (eps_j * Eigen::Vector<Scalar, Nx_j>::Unit(nx_j, j)).eval());\n        J.col(I0 + j) = rminus<Result>(std::apply(f, x_nc), F) / eps_j;\n        w             = rplus<W>(w, (-eps_j * Eigen::Vector<Scalar, Nx_j>::Unit(nx_j, j)).eval());\n      }\n      I0 += nx_j;\n    });\n\n    return std::make_pair(std::move(F), std::move(J));\n  }\n\n  if constexpr (K == 2) {\n    static_assert(Ny == 1, \"2nd derivative only implemented for scalar functions\");\n\n    const auto sqrteps = std::sqrt(eps);\n\n    Eigen::Matrix<Scalar, Nx, Nx> H(nx, nx);\n\n    Eigen::Index I0 = 0;\n    utils::static_for<NumArgs>([&](auto i0) {\n      auto & w0                           = std::get<i0>(x_nc);\n      using W0                            = std::decay_t<decltype(w0)>;\n      static constexpr Eigen::Index Nx_i0 = Dof<W0>;\n      const int nx_i0                     = dof<W0>(w0);\n\n      Eigen::Index I1 = 0;\n      utils::static_for<NumArgs>([&](auto i1) {\n        if (i1 > i0) { return; }\n\n        auto & w1                           = std::get<i1>(x_nc);\n        using W1                            = std::decay_t<decltype(w1)>;\n        static constexpr Eigen::Index Nx_i1 = Dof<W1>;\n        const int nx_i1                     = dof<W1>(w1);\n\n        for (auto k0 = 0; k0 != nx_i0; ++k0) {\n          Scalar eps0 = sqrteps;\n          if constexpr (std::is_base_of_v<Eigen::MatrixBase<W0>, W0>) {\n            eps0 *= abs(w0[k0]);\n            if (eps0 == 0.) { eps0 = sqrteps; }\n          }\n\n          w0               = rplus<W0>(w0, eps0 * Eigen::Vector<Scalar, Nx_i0>::Unit(nx_i0, k0));\n          const Result F10 = std::apply(f, x_nc);\n          w0               = rplus<W0>(w0, -eps0 * Eigen::Vector<Scalar, Nx_i0>::Unit(nx_i0, k0));\n\n          J(0, I0 + k0) = (F10 - F) / eps0;\n\n          for (auto k1 = 0; k1 < (i0 == i1 ? k0 + 1 : nx_i1); ++k1) {\n            Scalar eps1 = sqrteps;\n            if constexpr (std::is_base_of_v<Eigen::MatrixBase<W1>, W1>) {\n              eps1 *= abs(w1[k1]);\n              if (eps1 == 0.) { eps1 = sqrteps; }\n            }\n\n            // do this in order to ensure we return to same point on spaces with non-zero brackets\n            w1               = rplus<W1>(w1, eps1 * Eigen::Vector<Scalar, Nx_i1>::Unit(nx_i1, k1));\n            const Result F01 = std::apply(f, x_nc);\n            w0               = rplus<W0>(w0, eps0 * Eigen::Vector<Scalar, Nx_i0>::Unit(nx_i0, k0));\n            const Result F11 = std::apply(f, x_nc);\n            w0               = rplus<W0>(w0, -eps0 * Eigen::Vector<Scalar, Nx_i0>::Unit(nx_i0, k0));\n            w1               = rplus<W1>(w1, -eps1 * Eigen::Vector<Scalar, Nx_i1>::Unit(nx_i1, k1));\n\n            // hessian is symmetric\n            H(I0 + k0, I1 + k1) = H(I1 + k1, I0 + k0) = (F11 - F01 - F10 + F) / eps0 / eps1;\n          }\n        }\n        I1 += nx_i1;\n      });\n      I0 += nx_i0;\n    });\n\n    return std::make_tuple(std::move(F), std::move(J), std::move(H));\n  }\n}\n\n}  // namespace detail\n\n/**\n * @brief Available differentiation methods\n */\nenum class Type {\n  Numerical,  ///< Numerical (forward) derivatives\n  Autodiff,   ///< Uses the autodiff (https://autodiff.github.io) library; requires  \\p\n              ///< compat/autodiff.hpp\n  Ceres,      ///< Uses the Ceres (http://ceres-solver.org) built-in autodiff; requires \\p\n              ///< compat/ceres.hpp\n  Analytic,   ///< Hand-coded derivative, requires that function returns \\p std::pair \\f$(f(x),\n              ///< \\mathrm{d}^r f_x) \\f$\n  Default     ///< Automatically select type based on availability\n};\n\nstatic constexpr Type DefaultType =\n#ifdef SMOOTH_DIFF_AUTODIFF\n  Type::Autodiff;\n#elif defined SMOOTH_DIFF_CERES\n  Type::Ceres;\n#else\n  Type::Numerical;\n#endif\n\n/**\n * @brief Differentiation in tangent space\n *\n * @tparam K differentiation order (1 or 2)\n * @tparam D differentiation method to use\n *\n * @param f function to differentiate\n * @param x reference tuple of function arguments\n * @return {f(x), dr f(x)} for K = 1, {f(x), dr f(x), d2r f(x)} for K = 2\n *\n * @note Only scalar functions suppored for K = 2\n *\n * @note All arguments in x as well as the return type \\f$f(x)\\f$ must satisfy\n * the Manifold concept.\n */\ntemplate<std::size_t K, Type D>\nauto dr(auto && f, auto && x)\n{\n  using F   = decltype(f);\n  using Wrt = decltype(x);\n\n  if constexpr (D == Type::Numerical) {\n    return detail::dr_numerical<K>(std::forward<F>(f), std::forward<Wrt>(x));\n  } else if constexpr (D == Type::Autodiff) {\n#ifdef SMOOTH_DIFF_AUTODIFF\n    return dr_autodiff<K>(std::forward<F>(f), std::forward<Wrt>(x));\n#else\n    static_assert(D != Type::Autodiff, \"compat/autodiff.hpp header not included\");\n#endif\n  } else if constexpr (D == Type::Ceres) {\n    static_assert(K == 1, \"Only K = 1 supported with Ceres\");\n#ifdef SMOOTH_DIFF_CERES\n    return dr_ceres(std::forward<F>(f), std::forward<Wrt>(x));\n#else\n    static_assert(D != Type::Ceres, \"compat/ceres.hpp header not included\");\n#endif\n  } else if constexpr (D == Type::Analytic) {\n    auto F  = std::apply(f, x);\n    auto dF = std::apply(std::bind_front(std::mem_fn(&std::decay_t<decltype(f)>::jacobian), f), x);\n    if constexpr (K == 1) {\n      return std::make_tuple(std::move(F), std::move(dF));\n    } else if constexpr (K == 2) {\n      auto d2F =\n        std::apply(std::bind_front(std::mem_fn(&std::decay_t<decltype(f)>::hessian), f), x);\n      return std::make_tuple(F, dF, d2F);\n    }\n  } else if constexpr (D == Type::Default) {\n    return dr<K, DefaultType>(std::forward<F>(f), std::forward<Wrt>(x));\n  }\n}\n\n/**\n * @brief Differentiation in tangent space using default method\n *\n * @tparam K differentiation order\n *\n * @param f function to differentiate\n * @param x reference tuple of function arguments\n * @return \\p std::pair containing value and right derivative: \\f$(f(x), \\mathrm{d}^r f_x)\\f$\n *\n * @note All arguments in x as well as the return type \\f$f(x)\\f$ must satisfy\n * the Manifold concept.\n */\ntemplate<std::size_t K = 1>\nauto dr(auto && f, auto && x)\n{\n  return dr<K, Type::Default>(std::forward<decltype(f)>(f), std::forward<decltype(x)>(x));\n}\n\n}  // namespace diff\n}  // namespace smooth\n\n#endif  // SMOOTH__DIFF_HPP_\n", "meta": {"hexsha": "9dcf10ab22dfd1f59f40a9122d461c27b1c236d4", "size": 9586, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/diff.hpp", "max_stars_repo_name": "pettni/smooth", "max_stars_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T21:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T13:26:44.000Z", "max_issues_repo_path": "include/smooth/diff.hpp", "max_issues_repo_name": "pettni/lie", "max_issues_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2021-07-07T21:13:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T04:40:37.000Z", "max_forks_repo_path": "include/smooth/diff.hpp", "max_forks_repo_name": "pettni/lie", "max_forks_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-07-09T07:16:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T14:29:44.000Z", "avg_line_length": 34.9854014599, "max_line_length": 100, "alphanum_fraction": 0.6023367411, "num_tokens": 2731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5008256964380116}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <sensor_msgs/Imu.h>\n#include <trajectory_msgs/MultiDOFJointTrajectory.h>\n#include <std_msgs/Float64MultiArray.h>\n#include <nav_msgs/Path.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <tf/transform_broadcaster.h>\n\n#include <visualization_msgs/Marker.h>\n#include <visualization_msgs/MarkerArray.h>\n\n#include \"scp_planner.hpp\"\n#include <mission.hpp>\n#include <param.hpp>\n\nnamespace SwarmPlanning {\n    class SCPPublisher {\n    public:\n        SCPPublisher(const ros::NodeHandle &_n,\n                     std::shared_ptr<SCPPlanner> _SCPPlanner_obj,\n                     Mission _mission,\n                     Param _param)\n                : n(_n),\n                  SCPPlanner_obj(_SCPPlanner_obj),\n                  mission(_mission),\n                  param(_param) {\n            N = round(SCPPlanner_obj->msgs_traj_info.data[0]);\n            K = round(SCPPlanner_obj->msgs_traj_info.data[1]);\n            h = SCPPlanner_obj->msgs_traj_info.data[2];\n            outdim = 3;\n\n            traj_pubs.resize(N);\n            msgs_traj.resize(N);\n            for (int qi = 0; qi < N; qi++) {\n                std::string mav_name = \"/mav\" + std::to_string(qi);\n                traj_pubs[qi] = n.advertise<nav_msgs::Path>(\"/desired_trajectory\" + mav_name, 1);\n            }\n            colBox_pub = n.advertise<visualization_msgs::MarkerArray>(\"/collision_model\", 1);\n\n            p_curr.resize(N);\n            build_mapping_mtx();\n            std::vector<double> data = SCPPlanner_obj->msgs_traj_input.data;\n            u = Eigen::Map<Eigen::MatrixXd>(data.data(), outdim * N * K, 1);\n            p = P * u + p_start;\n            v = V * u;\n            a = A * u;\n        }\n\n        void update(double current_time) {\n            update_traj(current_time);\n            update_colBox();\n        }\n\n        void publish() {\n            for (int qi = 0; qi < N; qi++) {\n                traj_pubs[qi].publish(msgs_traj[qi]);\n            }\n            colBox_pub.publish(msgs_colBox);\n        }\n\n    private:\n        ros::NodeHandle n;\n        std::shared_ptr<SCPPlanner> SCPPlanner_obj;\n        Mission mission;\n        Param param;\n\n        int N, K, outdim;\n        double h;\n        tf::TransformBroadcaster br;\n        Eigen::MatrixXd P, V, A, J, p_start, p_goal, u, p, v, a;\n        std::vector<Eigen::MatrixXd> p_curr;\n\n        std::vector<ros::Publisher> traj_pubs;\n        ros::Publisher colBox_pub;\n\n        std::vector<nav_msgs::Path> msgs_traj;\n        visualization_msgs::MarkerArray msgs_colBox;\n\n        void build_mapping_mtx() {\n            P = Eigen::MatrixXd::Zero(outdim * N * K, outdim * N * K); // position matrix p = Pu + p_start\n            V = Eigen::MatrixXd::Zero(outdim * N * K, outdim * N * K); // velocity matrix v = Vu, assume v_start = 0\n            A = Eigen::MatrixXd::Identity(outdim * N * K, outdim * N * K); // accelation matrix a = Au\n            J = Eigen::MatrixXd::Zero(outdim * N * K, outdim * N * K); // accelation matrix a = Au\n\n            p_start = Eigen::MatrixXd::Zero(outdim * N * K, 1);\n            p_goal = Eigen::MatrixXd::Zero(outdim * N, 1);\n\n            for (int dim = 0; dim < outdim; dim++) {\n                for (int qi = 0; qi < N; qi++) {\n                    int offset = dim * N * K + qi * K;\n                    for (int k = 0; k < K; k++) {\n                        for (int j = 0; j < k; j++) {\n                            P(offset + k, offset + j) = 0.5 * h * h * (2 * (k - j) - 1);\n                            V(offset + k, offset + j) = h;\n                        }\n                        if (k != 0) {\n                            J(offset + k, offset + k) = 1 / h;\n                            J(offset + k, offset + k - 1) = -1 / h;\n                        }\n\n                        p_start(offset + k, 0) = mission.startState[qi][dim];\n                    }\n                    p_goal(dim * N + qi, 0) = mission.goalState[qi][dim];\n                }\n            }\n        }\n\n        void update_traj(double current_time) {\n            int k = floor(current_time / h);\n            if (k >= K - 1) {\n                return;\n            }\n\n            for (int qi = 0; qi < N; qi++) {\n                msgs_traj[qi].header.frame_id = \"/world\";\n                msgs_traj[qi].header.stamp.sec = current_time;\n\n                p_curr[qi] = Eigen::MatrixXd::Zero(outdim, 1);\n                Eigen::MatrixXd p_0 = Eigen::MatrixXd::Zero(outdim, 1);\n                Eigen::MatrixXd p_1 = Eigen::MatrixXd::Zero(outdim, 1);\n                for (int dim = 0; dim < outdim; dim++) {\n                    p_0(dim, 0) = p(dim * N * K + qi * K + k, 0);\n                    p_1(dim, 0) = p(dim * N * K + qi * K + k + 1, 0);\n                }\n                p_curr[qi] = p_0 + (current_time - k * h) / h * (p_1 - p_0);\n\n                geometry_msgs::PoseStamped pos_des;\n                pos_des.header.frame_id = \"/world\";\n                pos_des.pose.position.x = p_curr[qi](0, 0);\n                pos_des.pose.position.y = p_curr[qi](1, 0);\n                pos_des.pose.position.z = p_curr[qi](2, 0);\n                msgs_traj[qi].poses.emplace_back(pos_des);\n\n                tf::Transform transform;\n                transform.setOrigin(\n                        tf::Vector3(pos_des.pose.position.x, pos_des.pose.position.y, pos_des.pose.position.z));\n                tf::Quaternion q;\n                q.setRPY(0, 0, 0);\n                transform.setRotation(q);\n                br.sendTransform(tf::StampedTransform(transform, ros::Time::now(),\n                                                      \"world\", \"/mav\" + std::to_string(qi) + \"/base_link\"));\n            }\n        }\n\n        // obstacle-collision model\n        void update_colBox() {\n            visualization_msgs::MarkerArray mk_array;\n            for (int qi = 0; qi < N; qi++) {\n                visualization_msgs::Marker mk;\n                mk.header.frame_id = \"world\";\n                mk.ns = \"colBox\";\n                mk.type = visualization_msgs::Marker::SPHERE;\n                mk.action = visualization_msgs::Marker::ADD;\n\n                mk.pose.orientation.x = 0;\n                mk.pose.orientation.y = 0;\n                mk.pose.orientation.z = 0;\n                mk.pose.orientation.w = 1.0;\n\n                mk.id = qi;\n                mk.pose.position.x = p_curr[qi](0, 0);\n                mk.pose.position.y = p_curr[qi](1, 0);\n                mk.pose.position.z = p_curr[qi](2, 0);\n\n                mk.scale.x = 2 * mission.quad_size[qi];\n                mk.scale.y = 2 * mission.quad_size[qi];\n                mk.scale.z = 2 * mission.quad_size[qi];\n\n                mk.color.a = 0.7;\n                mk.color.r = param.color[qi][0];\n                mk.color.g = param.color[qi][1];\n                mk.color.b = param.color[qi][2];\n\n                mk_array.markers.emplace_back(mk);\n\n                mk.ns = \"initTraj\";\n                for (int k = 0; k < K; k++) {\n                    mk.id = 1000 + qi * K + k;\n                    Eigen::MatrixXd picker_i = position_picker(qi, k);\n                    Eigen::MatrixXd p_i = picker_i * p;\n                    mk.pose.position.x = p_i(0, 0);\n                    mk.pose.position.y = p_i(1, 0);\n                    mk.pose.position.z = p_i(2, 0);\n\n                    mk.scale.x = 0.1;\n                    mk.scale.y = 0.1;\n                    mk.scale.z = 0.1;\n\n                    mk.color.a = 0.5;\n                    mk.color.r = param.color[qi][0];\n                    mk.color.g = param.color[qi][1];\n                    mk.color.b = param.color[qi][2];\n\n                    mk_array.markers.emplace_back(mk);\n                }\n            }\n            msgs_colBox = mk_array;\n        }\n\n        Eigen::MatrixXd position_picker(int qi, int k) {\n            Eigen::MatrixXd P_pick = Eigen::MatrixXd::Zero(outdim, outdim * N * K);\n            for (int dim = 0; dim < outdim; dim++) {\n                P_pick(dim, dim * N * K + qi * K + k) = 1;\n            }\n\n            return P_pick;\n        }\n    };\n}", "meta": {"hexsha": "21828fc68821378e30b1f398fbd59991c38b641a", "size": 8060, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "swarm_planner/include/scp_publisher.hpp", "max_stars_repo_name": "snu-larr/swarm_simulator", "max_stars_repo_head_hexsha": "dc3f272158132cda4e1c319c7bd1a965d7bf9c40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T03:50:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T03:50:54.000Z", "max_issues_repo_path": "swarm_planner/include/scp_publisher.hpp", "max_issues_repo_name": "snu-larr/swarm_simulator", "max_issues_repo_head_hexsha": "dc3f272158132cda4e1c319c7bd1a965d7bf9c40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swarm_planner/include/scp_publisher.hpp", "max_forks_repo_name": "snu-larr/swarm_simulator", "max_forks_repo_head_hexsha": "dc3f272158132cda4e1c319c7bd1a965d7bf9c40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T10:58:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T08:19:08.000Z", "avg_line_length": 37.8403755869, "max_line_length": 116, "alphanum_fraction": 0.4694789082, "num_tokens": 2009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.500814815584013}}
{"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_ARCH_COMMON_DETAIL_GENERIC_EXPM1_KERNEL_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_GENERIC_EXPM1_KERNEL_HPP_INCLUDED\n\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/invlog_2.hpp>\n#include <boost/simd/detail/constant/log_2hi.hpp>\n#include <boost/simd/detail/constant/log_2lo.hpp>\n#include <boost/simd/detail/constant/maxexponent.hpp>\n#include <boost/simd/constant/nbmantissabits.hpp>\n#include <boost/simd/function/bitwise_cast.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/ldexp.hpp>\n#include <boost/simd/function/fms.hpp>\n#include <boost/simd/function/fnms.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/oneminus.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/nearbyint.hpp>\n#include <boost/simd/function/shift_left.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/toint.hpp>\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    namespace bd =  boost::dispatch;\n    namespace bs =  boost::simd;\n\n    template < typename A0, typename sA0>\n    struct expm1_kernel;\n\n    template < typename A0 >\n    struct expm1_kernel < A0, float >\n    {\n      // computes expm1 for float or float vectors\n      static BOOST_FORCEINLINE A0 expm1(const A0& a0) BOOST_NOEXCEPT\n      {\n        using i_t = bd::as_integer_t<A0>;\n        using s_t = bd::scalar_of_t<A0>;\n        A0 k  = nearbyint(Invlog_2<A0>()*a0);\n        A0 x = fnms(k, Log_2hi<A0>(), a0);\n        x =  fnms(k, Log_2lo<A0>(), x);\n        A0 hx  = x*Half<A0>();\n        A0 hxs = x*hx;\n        A0 r1 = horn<A0,\n                     0X3F800000UL,// 1\n                     0XBD08887FUL, // -3.3333298E-02\n                     0X3ACF6DB4UL  // 1.5825541E-03\n                     > (hxs);\n        A0 t  = fnms(r1, hx, A0(3));\n        A0 e  = hxs*((r1-t)/(A0(6) - x*t));\n        e  = fms(x, e, hxs);\n        i_t ik =  toint(k);\n        A0 two2mk = bitwise_cast<A0>(shift_left(Maxexponent<A0>()-ik,Nbmantissabits<s_t>()));\n        A0 y = oneminus(two2mk)-(e-x);\n        return ldexp(y, ik);\n      }\n    };\n\n    template < typename A0 >\n    struct expm1_kernel < A0, double >\n    {\n      // computes expm1 for  double or double vectors\n      static  BOOST_FORCEINLINE A0 expm1(const A0& a0) BOOST_NOEXCEPT\n      {\n        using i_t = bd::as_integer_t<A0>;\n        using s_t = bd::scalar_of_t<A0>;\n        A0 k  = nearbyint(Invlog_2<A0>()*a0);\n        A0 hi = fnms(k, Log_2hi<A0>(), a0);\n        A0 lo = k*Log_2lo<A0>();\n        A0 x  = hi-lo;\n        A0 hxs = sqr(x)*Half<A0>();\n        A0 r1 = horn<A0,\n                     0X3FF0000000000000ULL,\n                     0XBFA11111111110F4ULL,\n                     0X3F5A01A019FE5585ULL,\n                     0XBF14CE199EAADBB7ULL,\n                     0X3ED0CFCA86E65239ULL,\n                     0XBE8AFDB76E09C32DULL\n                     > (hxs);\n        A0 t  = A0(3)-r1*Half<A0>()*x;\n        A0 e  = hxs*((r1-t)/(A0(6) - x*t));\n        A0 c = (hi-x)-lo;\n        e  = (x*(e-c)-c)-hxs;\n        i_t ik =  toint(k);\n        A0 two2mk = bitwise_cast<A0>(shift_left(Maxexponent<A0>()-ik,Nbmantissabits<s_t>()));\n        A0 ct1= oneminus(two2mk)-(e-x);\n        A0 ct2= inc((x-(e+two2mk)));\n        A0 y = if_else((k < A0(20)),ct1,ct2);\n        return ldexp(y, ik);\n      }\n    };\n  }\n} }\n#endif\n", "meta": {"hexsha": "e71733efdff299aa23fed2e42e64150d05d0938a", "size": 3984, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/detail/generic/expm1_kernel.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/arch/common/detail/generic/expm1_kernel.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/arch/common/detail/generic/expm1_kernel.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": 35.5714285714, "max_line_length": 100, "alphanum_fraction": 0.5773092369, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5007594939167027}}
{"text": "#include \"VectorFields.h\"\n\n#include <igl/per_vertex_normals.h>\n#include <Eigen/Eigenvalues>\n#include <random>\n\n/* ====================== SETTING UP MATRICES ============================*/\nvoid VectorFields::constructConstraints()\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt1 = chrono::high_resolution_clock::now();\n\tcout << \"> Constructing constraints... \";\n\n\t//construct1CentralConstraint();\n\t//constructRingConstraints();\n\t//constructSpecifiedHardConstraints();\n\t//constructRandomHardConstraints();\n\t//constructSoftConstraints();\n\tconstructInteractiveConstraints();\n\t\n\t//constructSingularities();\n\t//constructHardConstraintsWithSingularities();\n\t//constructHardConstraintsWithSingularities_Cheat();\n\t//constructHardConstraintsWithSingularitiesWithGauss();\n\n\t\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\tcout << \"in \" << duration.count() << \" seconds\" << endl;\n\n\t// Information about constraints\n\t//printf(\"....Num of Constraints = %d\\n\", globalConstraints.size());\n\tprintf(\"....Matrix C size = %dx%d \\n\", C.rows(), C.cols());\n\tprintf(\"....Matrix c size = %dx%d \\n\", c.rows(), c.cols());\n}\n\nvoid VectorFields::construct1CentralConstraint()\n{\n\tvector<Eigen::Triplet<double>>\tCTriplet;\n\tCTriplet.reserve(2);\n\tconst int constNum = 1;\n\t//srand(time(NULL));\n\t//const int centralID = rand()%F.rows(); \n\tconst int centralID = *(NeighRing[0].begin());\n\tcout << \"Face ID is : \" << centralID << endl;\n\n\t// Setting up matrix C\n\tC.resize(2 * constNum, B2D.cols());\n\n\tCTriplet.push_back(Eigen::Triplet<double>(0, 2 * centralID + 0, 1.0));\n\tCTriplet.push_back(Eigen::Triplet<double>(1, 2 * centralID + 1, 1.0));\n\n\tC.setFromTriplets(CTriplet.begin(), CTriplet.end());\n\n\t// Setting up vector c (There are 2 vector c)\n\tc.resize(2 * constNum, 2);\n\tc.col(0) << 1.0, 0.0;\n\tc.col(1) << 0.0, 1.0;\n}\n\nvoid VectorFields::constructRingConstraints()\n{\n\t// Define necessary data/variables\n\tvector<Eigen::Triplet<double>>\tCTriplet;\n\t\n\tconst int outerRingID = 9;\n\tconst int outerBoundaryID = min(outerRingID, (int) NeighRing.size()-3);\n\tconst int constNum = 1 + (int) NeighRing[outerBoundaryID+1].size() + (int) NeighRing[outerBoundaryID + 2].size();\n\tconst int centralID = *(NeighRing[0].begin());\n\tint counter = 0;\n\n\t// Setting up matrix C\n\tC.resize(2 * constNum, B2D.cols());\n\tCTriplet.push_back(Eigen::Triplet<double>(counter++, 2 * centralID + 0, 1.0));\n\tCTriplet.push_back(Eigen::Triplet<double>(counter++, 2 * centralID + 1, 1.0));\n\tfor (int i = outerBoundaryID + 1; i <= outerBoundaryID + 2; i++) {\n\t\tfor (std::set<int, double>::iterator it = NeighRing[i].begin(); it != NeighRing[i].end(); ++it) {\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter++, 2 * (*it) + 0, 1.0));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter++, 2 * (*it) + 1, 1.0));\n\t\t}\n\t}\n\tC.setFromTriplets(CTriplet.begin(), CTriplet.end());\n\n\t// Setting up vector c (There are 2 vector c)\n\tc.resize(2 * constNum, 2);\n\tEigen::VectorXd zeroElements(2 * constNum - 2);\n\tfor (int i = 0; i < zeroElements.size(); i++) zeroElements(i) = 0.0;\n\tc.col(0) << 1.0, 0.0, zeroElements;\n\tc.col(1) << 0.0, 1.0, zeroElements;\n}\n\nvoid VectorFields::pushNewUserConstraints(const int& fInit, const int& fEnd)\n{\n\tuserVisualConstraints.push_back(fInit);\n\tuserVisualConstraints.push_back(fEnd);\n}\n\nvoid VectorFields::constructSpecifiedHardConstraints()\n{\n\t// Define the constraints\n\tconst int numConstraints = 20;\n\tset<int> constraints;\n\t//vector<int> globalConstraints(numConstraints);\n\tglobalConstraints.resize(numConstraints);\n\tEigen::VectorXd D;\n\tD.resize(F.rows());\n\n\t// Initialize the value of D\n\tfor (int i = 0; i < F.rows(); i++) {\n\t\tD(i) = numeric_limits<double>::infinity();\n\t}\n\n\t/* Random number generator */\n\tstd::random_device rd;\t\t\t\t\t\t\t\t// Will be used to obtain a seed for the random number engine\n\tstd::mt19937 gen(rd());\t\t\t\t\t\t\t\t// Standard mersenne_twister_engine seeded with rd()\n\tstd::uniform_int_distribution<> dis(0, F.rows() - 1); // From 0 to F.rows()-1\n\n\tsrand(time(NULL));\n\t//int curPoint = rand() % F.rows();\n\t//int curPoint = 0; \n\tint curPoint = dis(gen);\n\tconstraints.insert(curPoint);\n\n\t// Creating constraints using farthest point sampling\n\tdo {\n\t\tEigen::VectorXi::Index maxIndex;\n\t\tcomputeDijkstraDistanceFaceForSampling(curPoint, D);\n\t\tD.maxCoeff(&maxIndex);\n\t\tconstraints.insert(maxIndex);\n\t\tcurPoint = maxIndex;\n\t} while (constraints.size() < numConstraints);\n\n\t\n\n\tint counter1 = 0;\n\tfor (int i : constraints) {\n\t\tglobalConstraints[counter1++] = i;\n\t}\n\t\t\n\t// For testing only\n\t//computeDijkstraDistanceFaceForSampling(curPoint, D);\n\t//Eigen::VectorXi::Index counterPart;\n\t//D.maxCoeff(&counterPart);\n\t//const int counterPart = AdjMF3N(curPoint, 0);\n\t//globalConstraints[1] = AdjMF3N(0, 0);\n\t//globalConstraints[2] = AdjMF3N(0, 1);\n\t//globalConstraints[3] = AdjMF3N(0, 2);\n\t//printf(\"Constraints = %d\\n\", globalConstraints.size());\n\n\t// Setting up matrix C\n\tEigen::SparseMatrix<double> CTemp;\n\tvector<Eigen::Triplet<double>> CTriplet;\n\tCTriplet.reserve(2 * globalConstraints.size());\n\tc.resize(2 * globalConstraints.size());\n\tEigen::Vector2d cRand;\n\n\tint counter = 0;\n\tfor (int i = 0; i < globalConstraints.size(); i++) {\n\t\tcRand(0) = (double)(rand() % F.rows()) / (double)F.rows();\n\t\tcRand(1) = (double)(rand() % F.rows()) / (double)F.rows();\n\t\tcRand.normalize();\n\n\t\t//const double alpha = M_PI / 2.0; \n\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 0, cos(alpha)));\n\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 1, -sin(alpha)));\n\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 0, 1.0));\n\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * counterPart + 0, 1.0));\n\t\t//c(2 * counter + 0, 0) = 1.0;\n\t\tc(counter, 0) = cRand(0);\n\t\tcounter++;\n\n\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 1, 1.0));\n\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 0, sin(alpha)));\n\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 1, cos(alpha)));\n\t\t//c(2 * counter + 1, 0) = 1.0;\n\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * counterPart + 1, 1.0));\n\t\tc(counter, 0) = cRand(1);\n\t\tcounter++;\n\t}\n\tC.resize(2 * globalConstraints.size(), B2D.rows());\n\tC.setFromTriplets(CTriplet.begin(), CTriplet.end());\n\t//printf(\"Cp=%dx%d\\n\", C.rows(), C.cols());\n}\n\nvoid VectorFields::constructRandomHardConstraints()\n{\n\t// Define the constraints\n\tconst int numConstraints = 20;\n\tset<int> constraints;\n\tglobalConstraints.resize(numConstraints);\n\n\t/* Random number generator */\n\tstd::random_device rd;\t\t\t\t\t\t\t\t// Will be used to obtain a seed for the random number engine\n\tstd::mt19937 gen(rd());\t\t\t\t\t\t\t\t// Standard mersenne_twister_engine seeded with rd()\n\tstd::uniform_int_distribution<> dis(0, F.rows()-1); // From 0 to F.rows()-1\n\t\n\t/* Creating random constraints */\n\tdo {\n\t\tint constraintFace = dis(gen);\n\t\tconstraints.insert(constraintFace);\n\t} while (constraints.size() < numConstraints);\n\t\n\tint counter1 = 0;\n\tfor (int i : constraints) {\n\t\tglobalConstraints[counter1++] = i;\n\t}\n\t\n\t// Setting up matrix C\n\tEigen::SparseMatrix<double> CTemp;\n\tvector<Eigen::Triplet<double>> CTriplet;\n\tCTriplet.reserve(2 * globalConstraints.size());\n\tc.resize(2 * globalConstraints.size());\n\tEigen::Vector2d cRand;\n\n\tint counter = 0;\n\tfor (int i = 0; i < globalConstraints.size(); i++) {\n\t\tcRand(0) = (double)(rand() % F.rows()) / (double) F.rows();\n\t\tcRand(1) = (double)(rand() % F.rows()) / (double)F.rows();\n\t\tcRand.normalize();\n\n\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 0, 1.0));\n\t\tc(counter, 0) = cRand(0);\n\t\tcounter++;\n\n\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 1, 1.0));\n\t\tc(counter, 0) = cRand(1);\n\t\tcounter++;\n\t}\n\tC.resize(2 * globalConstraints.size(), B2D.rows());\n\tC.setFromTriplets(CTriplet.begin(), CTriplet.end());\n}\n\nvoid VectorFields::constructInteractiveConstraints()\n{\n\t/* Define the constraints */\n\tconst int numConstraints = userVisualConstraints.size() / 2; \n\tglobalConstraints.resize(numConstraints);\n\tvector<Eigen::Vector2d> constraintValues(numConstraints);\n\n\t/* Global constraints from user input */\n\tfor (int i = 0; i < userVisualConstraints.size(); i += 2)\n\t{\n\t\t/* Location of constraints */\n\t\tglobalConstraints[i/2] = userVisualConstraints[i];\n\t\t//printf(\"Constraint[%d]: %d-->%d\\n\", i / 2, userVisualConstraints[i], userVisualConstraints[i + 1]);\n\n\t\t/* Getting the constraints + making them into local coordinates */\n\t\tEigen::RowVector3d dir = FC.row(userVisualConstraints[i+1]) - FC.row(userVisualConstraints[i]);\n\t\t//cout << \"___ constraint in 3D: \" << dir << endl;\n\t\tEigen::MatrixXd ALoc(3, 2);\n\t\tALoc = A.block(3 * userVisualConstraints[i], 2 * userVisualConstraints[i], 3, 2);\n\t\tEigen::Vector2d normDir = ALoc.transpose() * dir.transpose();\n\t\tnormDir.normalize();\n\t\t//cout << \"___ constraint in 2D: \" << normDir << endl;\n\t\tconstraintValues[i / 2] = normDir; \n\t}\n\n\t/* Setting up matrix C and column vector c */\n\tEigen::SparseMatrix<double> CTemp;\n\tvector<Eigen::Triplet<double>> CTriplet;\n\tCTriplet.reserve(2 * globalConstraints.size());\n\tc.resize(2 * globalConstraints.size());\n\n\t/* Putting the constraints into action */\n\tint counter = 0;\n\tfor (int i = 0; i < globalConstraints.size(); i++) {\n\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 0, 1.0));\n\t\tc(counter, 0) = constraintValues[i](0);\n\t\tcounter++;\n\n\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 1, 1.0));\n\t\tc(counter, 0) = constraintValues[i](1);\n\t\tcounter++;\n\t}\n\tC.resize(2 * globalConstraints.size(), B2D.rows());\n\tC.setFromTriplets(CTriplet.begin(), CTriplet.end());\n}\nvoid VectorFields::resetInteractiveConstraints()\n{\n\tuserVisualConstraints.clear();\n\tuserVisualConstraints.shrink_to_fit();\n}\n\nvoid VectorFields::constructSingularities()\n{\n\tconst int NUM_SINGS = 2;\n\n\tif (NUM_SINGS > 0)\n\t\tconstructVFAdjacency();\n\t\t//constructVFNeighborsFull();\n\n\tsingularities.resize(NUM_SINGS);\n\tSingNeighCC.resize(NUM_SINGS);\n\n\t// For testing\n\tsharedEdgesVect.resize(NUM_SINGS);\n\n\t//time_t t;\n\t//srand((unsigned)time(&t));\n\tsrand(time(NULL));\n\tfor (int id = 0; id < NUM_SINGS; id++) {\n\t\t// Defining varaibles for singularities\n\t\tconst int SingLocation\t= rand() % V.rows();\n\t\tsingularities[id]\t\t= SingLocation;\n\t\tconst int SingNeighNum\t= VFAdjacency.col(SingLocation).nonZeros(); \n\t\tEigen::SparseMatrix<bool>::InnerIterator it0(VFAdjacency, SingLocation);\n\t\tconst int firstNeigh\t= it0.row(); \n\n\n\t\t// Inserting the first neighbor (the one with lowest index/row number)\n\t\tSingNeighCC[id].resize(SingNeighNum);\n\t\tSingNeighCC[id][0]\t\t= firstNeigh;\n\t\tint curNeigh\t\t\t= firstNeigh;\n\t\tint vertex1\t\t\t\t= SingLocation;\n\n\t\t// Getting the neighboring valence triangles in order\n\t\tfor (int i2 = 1; i2<SingNeighNum; i2++) {\n\t\t\tint vertex2;\n\t\t\t// Setting the vertex on the edge pointing to vertex1 as vertex2 (edge = v2->v1)\n\t\t\tfor (int i = 0; i < F.cols(); i++) {\n\t\t\t\tif (F(curNeigh, i%F.cols()) == vertex1) {\n\t\t\t\t\tvertex2 = F(curNeigh, (i + F.cols() - 1) % F.cols());\n\t\t\t\t}\n\t\t\t}\n\t\t\t//for (std::set<VtoFPair>::iterator it1 = next(VFNeighFull[SingLocation].begin(), 1); it1 != VFNeighFull[SingLocation].end(); ++it1) {\n\t\t\t// Getting the neighboring triangles in order (CCW) \n\t\t\tfor (Eigen::SparseMatrix<bool>::InnerIterator it1(VFAdjacency, SingLocation); it1; ++it1) {\n\t\t\t\tfor (int i = 0; i < F.cols(); i++) {\n\t\t\t\t\tif (F(it1.row(), i) == vertex1 && F(it1.row(), (i + 1) % F.cols()) == vertex2) {\n\t\t\t\t\t\tSingNeighCC[id][i2] = it1.row();\n\t\t\t\t\t\tcurNeigh = it1.row();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Free Memory for VFNeighborsFull\n\tVFAdjacency.resize(0, 0);\n\t//VFNeighFull.clear();\n\t//VFNeighbors.shrink_to_fit();\n}\n\nvoid VectorFields::constructHardConstraintsWithSingularities() \n{\n\t// Define the constraints\n\tconst int numConstraints = 2;\n\tset<int> constraints;\n\n\tglobalConstraints.resize(numConstraints);\n\tEigen::VectorXd D;\n\tD.resize(F.rows());\n\n\t// Initialize the value of D\n\tfor (int i = 0; i < F.rows(); i++) {\n\t\tD(i) = numeric_limits<double>::infinity();\n\t}\n\n\tsrand(time(NULL));\n\tint curPoint = rand() % F.rows();\n\tconstraints.insert(curPoint);\n\n\t// Creating constraints using farthest point sampling\n\tdo {\n\t\tEigen::VectorXi::Index maxIndex;\n\t\tcomputeDijkstraDistanceFaceForSampling(curPoint, D);\n\t\tD.maxCoeff(&maxIndex);\n\t\tconstraints.insert(maxIndex);\n\t\tcurPoint = maxIndex;\n\t} while (constraints.size() < numConstraints);\n\n\tint counter1 = 0;\n\tfor (int i : constraints) {\n\t\tglobalConstraints[counter1++] = i;\n\t}\n\n\tint numSingConstraints = 0;\n\tfor (int i = 0; i < SingNeighCC.size(); i++) {\n\t\t// Use only n-1 neighboring faces as constraints\n\t\tfor (int j = 0; j < (SingNeighCC[i].size() - 1); j++) {\n\t\t\tnumSingConstraints++;\n\t\t}\n\t}\n\n\t// Setting up matrix C and vector c\n\tc.resize(2 * (globalConstraints.size() + numSingConstraints));\n\n\n\t// HARD CONSTRAINTS\n\tEigen::SparseMatrix<double> CTemp;\n\tvector<Eigen::Triplet<double>> CTriplet;\n\tCTriplet.reserve(2 * globalConstraints.size() + 2 * 4 * 7 * SingNeighCC.size());\n\tint counter = 0;\n\tfor (int i = 0; i < globalConstraints.size(); i++) {\n\t\t// Matrix C\n\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 0, 1.0));\n\t\tc(counter++, 0) = sqrt(2.0);\n\t\t//c(counter++, 1) = sqrt(2.0);\n\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 1, 1.0));\n\t\tc(counter++, 0) = sqrt(2.0);\n\t\t//c(counter++, 1) = sqrt(2.0);\n\t}\n\n\n\t// SINGULARITIES CONSTRAINTS\n\tfor (int id = 0; id < SingNeighCC.size(); id++) {\n\t\t// Getting the shared-edges of two neighboring faces For testing\n\t\tsharedEdgesVect[id].resize(2 * SingNeighCC[id].size() - 2);\n\n\t\t// 4. Compute rotation of among its valence\n\t\tconst double rotAngle = 2 * M_PI / (double)SingNeighCC[id].size();\n\t\tconst double cosConst = cos(rotAngle);\n\t\tconst double sinConst = sin(rotAngle);\n\n\t\t// Which case? => determining which edge is the common edge\n\t\tenum class SharedEdgeCase { Case1, Case2, Case3 };\n\t\tSharedEdgeCase edgeCase1, edgeCase2;\n\t\tfor (int i = 0; i < (SingNeighCC[id].size() - 1); i++) {\n\t\t\t// 1. Find shared edge (naively)\n\t\t\tEigen::RowVector3d es;\n\t\t\tfor (int f1 = 0; f1 < F.cols(); f1++) {\n\t\t\t\tfor (int f2 = 0; f2 < F.cols(); f2++) {\n\t\t\t\t\tbool b1 = F(SingNeighCC[id][i], (f1 + 1) % F.cols()) == F(SingNeighCC[id][i + 1], f2);\n\t\t\t\t\tbool b2 = F(SingNeighCC[id][i], f1) == F(SingNeighCC[id][i + 1], (f2 + 1) % F.cols());\n\t\t\t\t\tif (b1 && b2) {\n\t\t\t\t\t\tsharedEdgesVect[id][2 * i + 0] = F(SingNeighCC[id][i], f1);\n\t\t\t\t\t\tsharedEdgesVect[id][2 * i + 1] = F(SingNeighCC[id][i], (f1 + 1) % F.cols());\n\t\t\t\t\t\tes = V.row(F(SingNeighCC[id][i], (f1 + 1) % F.cols())) - V.row(F(SingNeighCC[id][i], f1));\n\t\t\t\t\t\tprintf(\"Shared edge=%d->%d\\n\", F(SingNeighCC[id][i], f1), F(SingNeighCC[id][i], (f1 + 1) % F.cols()));\n\n\t\t\t\t\t\tif (f1 == 0)\t\tedgeCase1 = SharedEdgeCase::Case1;\t// => edge V0->V1 is the shared edge => it takes 0 step to reach v0\n\t\t\t\t\t\telse if (f1 == 1)\tedgeCase1 = SharedEdgeCase::Case3;\t// => edge V1->V2 is the shared edge => it takes 2 step to reach v0\n\t\t\t\t\t\telse if (f1 == 2)\tedgeCase1 = SharedEdgeCase::Case2;\t// => edge V2->V0 is the shared edge => it takes 1 step to reach v0\n\n\t\t\t\t\t\tif (f2 == 0)\t\tedgeCase2 = SharedEdgeCase::Case1;\n\t\t\t\t\t\telse if (f2 == 1)\tedgeCase2 = SharedEdgeCase::Case3;\n\t\t\t\t\t\telse if (f2 == 2)\tedgeCase2 = SharedEdgeCase::Case2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// 2. Find angles between basis1 and shared_edges es\n\t\t\tEigen::VectorXd eVect;\n\t\t\tEigen::RowVector3d b11, b12;\n\t\t\t//b11 = (A.block(3 * SingNeighCC[id][i], 2 * SingNeighCC[id][i] + 0, 3, 1)).transpose();\n\t\t\t//b12 = (A.block(3 * SingNeighCC[id][i], 2 * SingNeighCC[id][i] + 1, 3, 1)).transpose();\n\t\t\teVect = A.block(3 * SingNeighCC[id][i], 2 * SingNeighCC[id][i] + 0, 3, 1);\n\t\t\tb11 << eVect(0), eVect(1), eVect(2);\n\t\t\teVect = A.block(3 * SingNeighCC[id][i], 2 * SingNeighCC[id][i] + 1, 3, 1);\n\t\t\tb12 << eVect(0), eVect(1), eVect(2);\n\t\t\t//cout << \"______B11: \" << b11 << \", B12: \" << b12 << endl;\n\n\t\t\t// Basis 1, Frame 1\n\t\t\tdouble cosR12 = (b11.dot(es)) / (b11.norm()*es.norm());\n\t\t\tif (cosR12 > 1.0) cosR12 = 1.0;\n\t\t\tif (cosR12 <-1.0) cosR12 = -1.0;\n\t\t\tconst double angleR12_1 = (edgeCase1 == SharedEdgeCase::Case2 ? 2 * M_PI - acos(cosR12) : acos(cosR12));\n\t\t\tprintf(\"______[%.2f] Rotation matrix R12_1\\n\", angleR12_1*180.0 / M_PI);\n\t\t\t//const double cosR12_1 = cos(angleR12_1);\n\t\t\t//const double sinR12_1 = sin(angleR12_1);\n\t\t\t//printf(\"______[%.2f] Rotation matrix R12_1 = [%.3f,%.3f; %.3f, %.3f]\\n\", angleR12_1*180.0 / M_PI, cosR12_1, -sinR12_1, sinR12_1, cosR12_1);\n\t\t\t//printf(\"______[%.2f] Rotation matrix R12_1 = [%.3f,%.3f; %.3f, %.3f]\\n\", angleR12_1*180.0 / M_PI, cosR12_1, -sinR12_1, sinR12_1, cosR12_1);\n\n\t\t\t\n\t\t\t// 3. Find angles between basis2 and es\n\t\t\t//es = -es;\n\t\t\tEigen::RowVector3d b21, b22;\n\t\t\t//b21 = (A.block(3 * SingNeighCC[id][i + 1], 2 * SingNeighCC[id][i + 1] + 0, 3, 1)).transpose();\n\t\t\t//b22 = (A.block(3 * SingNeighCC[id][i + 1], 2 * SingNeighCC[id][i + 1] + 1, 3, 1)).transpose();\n\t\t\teVect = A.block(3 * SingNeighCC[id][i + 1], 2 * SingNeighCC[id][i + 1] + 0, 3, 1);\n\t\t\tb21 << eVect(0), eVect(1), eVect(2);\n\t\t\teVect = A.block(3 * SingNeighCC[id][i + 1], 2 * SingNeighCC[id][i + 1] + 1, 3, 1);\n\t\t\tb22 << eVect(0), eVect(1), eVect(2);\n\t\t\t//cout << \"______B21: \" << b21 << \", B22: \" << b22 << endl;\n\n\t\t\t// Basis 2, Frame 1\n\t\t\tdouble cosR21 = (b21.dot(es)) / (b21.norm()*es.norm());\n\t\t\tif (cosR21 > 1.0) cosR21 = 1.0;\n\t\t\tif (cosR21 < -1.0) cosR21 = -1.0;\n\t\t\tdouble angleR21_1 = (edgeCase2 == SharedEdgeCase::Case3 ? 2 * M_PI - acos(cosR21) : acos(cosR21));\n\t\t\tangleR21_1 = 2 * M_PI - angleR21_1; \n\t\t\tprintf(\"______[%.2f] Rotation matrix R22_1 = [%.2f]\\n\", angleR21_1*180.0 / M_PI);\n\t\t\t//const double cosR21_1 = cos(angleR21_1);\n\t\t\t//const double sinR21_1 = sin(angleR21_1);\n\t\t\t//printf(\"______[%.2f] Rotation matrix R22_1 = [%.2f,%.2f; %.2f, %.2f]\\n\", angleR21_1*180.0 / M_PI, cosR21_1, -sinR21_1, sinR21_1, cosR21_1);\n\t\t\t//printf(\"____ To map basis1 -> basis2: rotate by %.2f degree\\n\", (angleR12_1 + angleR21_1)*180.0 / M_PI);\n\n\t\t\tconst double RotAngle = (angleR12_1 + angleR21_1 > 2 * M_PI ? (angleR12_1 + angleR21_1) - 2 * M_PI : angleR12_1 + angleR21_1);\n\t\t\tprintf(\"____ To map basis1 -> basis2: rotate by %.2f degree\\n\", (RotAngle)*180.0 / M_PI);\n\t\t\tconst double cosBasis = cos(RotAngle);\n\t\t\tconst double sinBasis = sin(RotAngle);\n\t\t\t\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, cosR12_1));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -sinR12_1));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -cosR21_1));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, sinR21_1));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, cosR21_1*cosR12_1 + sinR21_1*sinR12_1));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -cosR21_1*sinR12_1 + sinR21_1*cosR12_1));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -1.0));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, 0.0));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, cosBasis));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -sinBasis));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -1.0));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, 0));\n\t\t\tc(counter) = 0.0;\n\t\t\tcounter++;\n\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, sinR12_1));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, cosR12_1 ));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -sinR21_1));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, -cosR21_1 ));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, -sinR21_1*cosR12_1 + cosR21_1*sinR12_1));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, sinR21_1*sinR12_1 + cosR21_1*cosR21_1));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, 0.0));\n\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, -1.0));\n\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, sinBasis));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, cosBasis ));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, 0.0));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, -1.0));\n\t\t\tc(counter) = 0.0;\n\t\t\tcounter++;\n\t\t}\n\t}\n\n\tC.resize(2 * (globalConstraints.size() + numSingConstraints), B2D.rows());\n\tC.setFromTriplets(CTriplet.begin(), CTriplet.end());\n\t//printf(\"Cp=%dx%d\\n\", C.rows(), C.cols());\t\n}\n\nvoid VectorFields::constructHardConstraintsWithSingularities_Cheat()\n{\n\t// Define the constraints\n\tconst int numConstraints = 100;\n\tset<int> constraints;\n\n\tglobalConstraints.resize(numConstraints);\n\tEigen::VectorXd D;\n\tD.resize(F.rows());\n\n\t// Initialize the value of D\n\tfor (int i = 0; i < F.rows(); i++) {\n\t\tD(i) = numeric_limits<double>::infinity();\n\t}\n\n\tsrand(time(NULL));\n\tint curPoint = rand() % F.rows();\n\tconstraints.insert(curPoint);\n\n\t// Creating constraints using farthest point sampling\n\tdo {\n\t\tEigen::VectorXi::Index maxIndex;\n\t\tcomputeDijkstraDistanceFaceForSampling(curPoint, D);\n\t\tD.maxCoeff(&maxIndex);\n\t\tconstraints.insert(maxIndex);\n\t\tcurPoint = maxIndex;\n\t} while (constraints.size() < numConstraints);\n\n\tint counter1 = 0;\n\tfor (int i : constraints) {\n\t\tglobalConstraints[counter1++] = i;\n\t}\n\n\tint numSingConstraints = 0;\n\tfor (int i = 0; i < SingNeighCC.size(); i++) {\n\t\t// Use only n-1 neighboring faces as constraints\n\t\t//for (int j = 0; j < (SingNeighCC[i].size()-1); j++) {\n\t\tfor (int j = 0; j < (SingNeighCC[i].size()); j++) {\n\t\t\tnumSingConstraints++;\n\t\t}\n\t}\n\n\t// Setting up matrix C and vector c\n\tc.resize(2 * (globalConstraints.size() + numSingConstraints));\n\n\n\t// HARD CONSTRAINTS\n\tEigen::SparseMatrix<double> CTemp;\n\tvector<Eigen::Triplet<double>> CTriplet;\n\tCTriplet.reserve(2 * globalConstraints.size() + 2 * 4 * 7 * SingNeighCC.size());\n\tint counter = 0;\n\tfor (int i = 0; i < globalConstraints.size(); i++) {\n\t\t// Matrix C\n\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 0, 1.0));\n\t\tc(counter++, 0) = sqrt(2.0);\n\t\t//c(counter++, 1) = sqrt(2.0);\n\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 1, 1.0));\n\t\tc(counter++, 0) = sqrt(2.0);\n\t\t//c(counter++, 1) = sqrt(2.0);\n\t}\n\n\t// Setting up hard constraints for neighboring faces\n\tEigen::MatrixXd ALoc(3, 2);\n\tEigen::RowVector3d c1, c2, field3D;\n\tEigen::Vector2d field2D; \n\tfor (int id = 0; id < SingNeighCC.size(); id++) {\t\n\t\t//printf(\"This sing has %d neighbors....\", SingNeighCC[id].size());\n\t\tfor (int i = 0; i < (SingNeighCC[id].size()); i++) {\n\t\t\tint i2 = (i < (SingNeighCC[id].size() - 1) ? i+1 : 0);\n\n\t\t\t// Computing the field from one barycenter pointing to another's barycenter\n\t\t\tALoc = A.block(3 * SingNeighCC[id][i], 2 * SingNeighCC[id][i], 3, 2);\n\t\t\tc1 = FC.row(SingNeighCC[id][i]);\n\t\t\tc2 = FC.row(SingNeighCC[id][i2]); \n\t\t\tfield3D = c2 - c1;\n\t\t\t//printf(\"<%.15f, %.15f, %.15f>\\n\", field3D(0), field3D(1), field3D(2));\n\t\t\tfield2D = ALoc.transpose() * field3D.transpose();\n\t\t\tfield2D.normalize();\n\t\t\tfield2D /= 4.0; \n\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, 1.0));\n\t\t\tc(counter) = field2D(0);\n\t\t\tcounter++;\n\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, 1.0));\n\t\t\tc(counter) = field2D(1);\n\t\t\tcounter++;\n\t\t\t//printf(\"Writing to %d(%.3f) and %d(%.3f) \\n\", SingNeighCC[id][i], field2D(0), SingNeighCC[id][i2], field2D(1));\n\t\t}\n\t}\n\n\tC.resize(2 * (globalConstraints.size() + numSingConstraints), B2D.rows());\n\tC.setFromTriplets(CTriplet.begin(), CTriplet.end());\n}\n\nvoid VectorFields::constructHardConstraintsWithSingularitiesWithGauss()\n{\n\t// Define the constraints\n\tconst int numConstraints = 20;\n\tset<int> constraints;\n\n\tglobalConstraints.resize(numConstraints);\n\tEigen::VectorXd D;\n\tD.resize(F.rows());\n\n\t// Initialize the value of D\n\tfor (int i = 0; i < F.rows(); i++) {\n\t\tD(i) = numeric_limits<double>::infinity();\n\t}\n\n\tsrand(time(NULL));\n\tint curPoint = rand() % F.rows();\n\tconstraints.insert(curPoint);\n\n\t// Creating constraints using farthest point sampling\n\tdo {\n\t\tEigen::VectorXi::Index maxIndex;\n\t\tcomputeDijkstraDistanceFaceForSampling(curPoint, D);\n\t\tD.maxCoeff(&maxIndex);\n\t\tconstraints.insert(maxIndex);\n\t\tcurPoint = maxIndex;\n\t} while (constraints.size() < numConstraints);\n\n\tint counter1 = 0;\n\tfor (int i : constraints) {\n\t\tglobalConstraints[counter1++] = i;\n\t}\n\n\tint numSingConstraints = 0;\n\tfor (int i = 0; i < SingNeighCC.size(); i++) {\n\t\t// Use only n-1 neighboring faces as constraints\n\t\t//for (int j = 0; j < (SingNeighCC[i].size()-1); j++) {\n\t\tfor (int j = 0; j < (SingNeighCC[i].size()); j++) {\n\t\t\tnumSingConstraints++;\n\t\t}\n\t}\n\n\t// Setting up matrix C and vector c\n\tc.resize(2 * (globalConstraints.size() + numSingConstraints));\n\n\n\t// HARD CONSTRAINTS\n\tEigen::SparseMatrix<double> CTemp;\n\tvector<Eigen::Triplet<double>> CTriplet;\n\tCTriplet.reserve(2 * globalConstraints.size() + 2 * 4 * 7 * SingNeighCC.size());\n\tint counter = 0;\n\tfor (int i = 0; i < globalConstraints.size(); i++) {\n\t\t// Matrix C\n\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 0, 1.0));\n\t\tc(counter++, 0) = sqrt(2.0);\n\t\t//c(counter++, 1) = sqrt(2.0);\n\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 1, 1.0));\n\t\tc(counter++, 0) = sqrt(2.0);\n\t\t//c(counter++, 1) = sqrt(2.0);\n\t}\n\n\t// Setting up hard constraints for neighboring faces\n\tEigen::MatrixXd\t\tALoc(3, 2);\n\tEigen::RowVector3d\tc1, c2, field3D;\n\tEigen::Vector2d\t\tfield2D;\n\tvector<vector<double>>\t\tinternalAngle(SingNeighCC.size()); \n\tvector<double>\t\t\t\tgaussAngle(SingNeighCC.size());\n\n\t// Local variables to compute angle on each triangle\n\tEigen::Vector3d\t\tedge1, edge2;\n\tdouble\t\t\t\tangle; \n\tint\t\t\t\t\tsingLoc;\n\tfor (int id = 0; id < SingNeighCC.size(); id++)\n\t{\n\t\tinternalAngle[id].resize(SingNeighCC[id].size());\n\t\tgaussAngle[id] = 0.0;\n\n\t\tfor (int i = 0; i < (SingNeighCC[id].size()); i++) \n\t\t{\n\t\t\tint i2 = (i < (SingNeighCC[id].size() - 1) ? i + 1 : 0);\n\n\t\t\t// [a] obtain shared edges\n\t\t\tfor (int f = 0; f < F.cols(); f++) {\n\t\t\t\tif (F(SingNeighCC[id][i],f) == singularities[id])\n\t\t\t\t{\n\t\t\t\t\t// [b] get the two edges\n\t\t\t\t\tedge1 = V.row(F(SingNeighCC[id][i], (f == 0 ? 2 : f - 1))) - V.row(F(SingNeighCC[id][i], f));\n\t\t\t\t\tedge2 = V.row(F(SingNeighCC[id][i], (f == 2 ? 0 : f + 1))) - V.row(F(SingNeighCC[id][i], f)) ;\n\t\t\t\t\tangle = edge2.dot(edge1) / (edge1.norm()*edge2.norm());\n\t\t\t\t\tangle = acos(angle);\n\n\t\t\t\t\t// [c] get the angle\n\t\t\t\t\tinternalAngle[id][i] = angle;\n\t\t\t\t\tgaussAngle[id]\t\t+= angle; \n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Show the angles\n\tfor (int id = 0; id < SingNeighCC.size(); id++)\n\t{\n\t\tprintf(\"__Gauss angle = %.4f\\n\", gaussAngle[id]*180.0/M_PI);\n\t\tfor (int i = 0; i < (SingNeighCC[id].size()); i++) {\n\t\t\tprintf(\"______ angle %d = %.3f \\n\", i, internalAngle[id][i] * 180.0 / M_PI);\n\t\t}\n\t}\n\n\t// SINGULARITIES CONSTRAINTS\n\tfor (int id = 0; id < SingNeighCC.size(); id++) \n\t{\n\t\t// Getting the shared-edges of two neighboring faces For testing\n\t\tsharedEdgesVect[id].resize(2 * SingNeighCC[id].size() - 2);\n\n\t\t// 4. Compute rotation of among its valence\n\t\tconst double rotAngle = gaussAngle[id] / (double)SingNeighCC[id].size();\t// all edges with similar angle => next iter: relative angle\n\t\tconst double cosConst = cos(/*2*M_PI - */rotAngle);\n\t\tconst double sinConst = sin(/*2*M_PI - */rotAngle);\n\t\tprintf(\"Angle=%.3f, sin=%.3f, cos=%.3f\\n\", rotAngle*180.0 / M_PI, sinConst, cosConst);\n\n\t\t/* Give hard constraint on face 1 */\n\t\tEigen::MatrixXd ALoc(3, 2);\n\t\tfor (int f = 0; f < F.cols(); f++) {\n\t\t\tif (F(SingNeighCC[id][0], f) == singularities[id])\n\t\t\t{\n\t\t\t\tEigen::Vector3d edge = V.row(F(SingNeighCC[id][0], (f==0 ? 2 : f-1))) - V.row(F(SingNeighCC[id][0], (f == 2 ? 0 : f + 1)));\n\t\t\t\tALoc = A.block(3 * SingNeighCC[id][0], 2 * SingNeighCC[id][0], 3, 2);\n\t\t\t\tEigen::Vector2d edge2D = ALoc.transpose() * edge; \n\t\t\t\tedge2D = edge2D.normalized() / 4.0; \n\t\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][0]+0, 1.0));\n\t\t\t\tc(counter) = edge2D(0);\n\t\t\t\tcounter++;\n\t\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][0]+1, 1.0));\n\t\t\t\tc(counter) = edge2D(1);\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\n\t\t// Which case? => determining which edge is the common edge\n\t\tenum class SharedEdgeCase { Case1, Case2, Case3 };\n\t\tSharedEdgeCase edgeCase1, edgeCase2;\n\t\tfor (int i = 0; i < (SingNeighCC[id].size() - 1); i++) \n\t\t{\n\t\t\t// 1. Find shared edge (naively)\n\t\t\tEigen::RowVector3d es;\n\t\t\tfor (int f1 = 0; f1 < F.cols(); f1++) {\n\t\t\t\tfor (int f2 = 0; f2 < F.cols(); f2++) {\n\t\t\t\t\tbool b1 = F(SingNeighCC[id][i], (f1 + 1) % F.cols()) == F(SingNeighCC[id][i + 1], f2);\n\t\t\t\t\tbool b2 = F(SingNeighCC[id][i], f1) == F(SingNeighCC[id][i + 1], (f2 + 1) % F.cols());\n\t\t\t\t\tif (b1 && b2) {\n\t\t\t\t\t\tsharedEdgesVect[id][2 * i + 0] = F(SingNeighCC[id][i], f1);\n\t\t\t\t\t\tsharedEdgesVect[id][2 * i + 1] = F(SingNeighCC[id][i], (f1 + 1) % F.cols());\n\t\t\t\t\t\tes = V.row(F(SingNeighCC[id][i], (f1 + 1) % F.cols())) - V.row(F(SingNeighCC[id][i], f1));\n\t\t\t\t\t\tprintf(\"Shared edge=%d->%d\\n\", F(SingNeighCC[id][i], f1), F(SingNeighCC[id][i], (f1 + 1) % F.cols()));\n\n\t\t\t\t\t\tif (f1 == 0)\t\tedgeCase1 = SharedEdgeCase::Case1;\t// => edge V0->V1 is the shared edge => it takes 0 step to reach v0\n\t\t\t\t\t\telse if (f1 == 1)\tedgeCase1 = SharedEdgeCase::Case3;\t// => edge V1->V2 is the shared edge => it takes 2 step to reach v0\n\t\t\t\t\t\telse if (f1 == 2)\tedgeCase1 = SharedEdgeCase::Case2;\t// => edge V2->V0 is the shared edge => it takes 1 step to reach v0\n\n\t\t\t\t\t\tif (f2 == 0)\t\tedgeCase2 = SharedEdgeCase::Case1;\n\t\t\t\t\t\telse if (f2 == 1)\tedgeCase2 = SharedEdgeCase::Case3;\n\t\t\t\t\t\telse if (f2 == 2)\tedgeCase2 = SharedEdgeCase::Case2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// 2. Find angles between basis1 and shared_edges es\n\t\t\tEigen::VectorXd eVect;\n\t\t\tEigen::RowVector3d b11, b12;\n\t\t\teVect = A.block(3 * SingNeighCC[id][i], 2 * SingNeighCC[id][i] + 0, 3, 1);\n\t\t\tb11 << eVect(0), eVect(1), eVect(2);\n\t\t\teVect = A.block(3 * SingNeighCC[id][i], 2 * SingNeighCC[id][i] + 1, 3, 1);\n\t\t\tb12 << eVect(0), eVect(1), eVect(2);\n\t\t\t//cout << \"______B11: \" << b11 << \", B12: \" << b12 << endl;\n\n\t\t\t// Basis 1, Frame 1\n\t\t\tdouble cosR12 = (b11.dot(es)) / (b11.norm()*es.norm());\n\t\t\tif (cosR12 > 1.0) cosR12 = 1.0;\n\t\t\tif (cosR12 <-1.0) cosR12 = -1.0;\n\t\t\tconst double angleR12_1 = (edgeCase1 == SharedEdgeCase::Case2 ? 2 * M_PI - acos(cosR12) : acos(cosR12));\n\t\t\tprintf(\"______[%.2f] Rotation matrix R12_1\\n\", angleR12_1*180.0 / M_PI);\n\n\t\t\t// 3. Find angles between basis2 and es\n\t\t\tEigen::RowVector3d b21, b22;\n\t\t\teVect = A.block(3 * SingNeighCC[id][i + 1], 2 * SingNeighCC[id][i + 1] + 0, 3, 1);\n\t\t\tb21 << eVect(0), eVect(1), eVect(2);\n\t\t\teVect = A.block(3 * SingNeighCC[id][i + 1], 2 * SingNeighCC[id][i + 1] + 1, 3, 1);\n\t\t\tb22 << eVect(0), eVect(1), eVect(2);\n\t\t\t//cout << \"______B21: \" << b21 << \", B22: \" << b22 << endl;\n\n\t\t\t// Basis 2, Frame 1\n\t\t\tdouble cosR21 = (b21.dot(es)) / (b21.norm()*es.norm());\n\t\t\tif (cosR21 > 1.0) cosR21 = 1.0;\n\t\t\tif (cosR21 < -1.0) cosR21 = -1.0;\n\t\t\tdouble angleR21_1 = (edgeCase2 == SharedEdgeCase::Case3 ? 2 * M_PI - acos(cosR21) : acos(cosR21));\n\t\t\tangleR21_1 = 2 * M_PI - angleR21_1;\n\t\t\tprintf(\"______[%.2f] Rotation matrix R22_1 = [%.2f]\\n\", angleR21_1*180.0 / M_PI);\n\t\t\t\n\t\t\tconst double RotAngle = (angleR12_1 + angleR21_1 > 2 * M_PI ? (angleR12_1 + angleR21_1) - 2 * M_PI : angleR12_1 + angleR21_1);\n\t\t\tconst double cosBasis = cos(RotAngle);\n\t\t\tconst double sinBasis = sin(RotAngle);\n\t\t\tprintf(\"____ To map basis1 -> basis2: rotate by %.2f degree (cos=%.2f, cin=%.2f))\\n\", (RotAngle)*180.0 / M_PI, cosBasis, sinBasis);\n\n\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, cosBasis));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -sinBasis));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -cosConst));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, sinConst));\n\t\t\tc(counter) = 0.0;\n\t\t\tcounter++;\n\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, sinBasis));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, cosBasis));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -sinConst));\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, -cosConst));\n\t\t\tc(counter) = 0.0;\n\t\t\tcounter++;\n\t\t}\n\t}\n\n\tC.resize(2 * (globalConstraints.size() + numSingConstraints), B2D.rows());\n\tC.setFromTriplets(CTriplet.begin(), CTriplet.end());\n}\n\nvoid VectorFields::constructSoftConstraints()\n{\n\tconst int NUM_CURVES = 8;\n\tcurvesConstraints.resize(NUM_CURVES);\n\n\tsrand(time(NULL));\n\tint init_, end_; \n\tvector<int> aCurve; \n\t/* Automatic random set up */\n\t//for (int i = 0; i < NUM_CURVES; i++) {\n\t//\tinit_ = rand() % F.rows();\n\t//\t//end_ = rand() % F.rows();\n\t//\tend_ = init_ + 40;\n\t//\tconstructCurvesAsConstraints(init_, end_, aCurve);\n\t//\tcurvesConstraints[i] = aCurve; \n\t//}\n\n\t/* Manual set-up for Armadillo */\n\tint constCounter = 0;\n\t// Head\n\tconstructCurvesAsConstraints(68818,6278, aCurve);\n\tcurvesConstraints[constCounter++] = aCurve;\n\t// Stomach\n\tconstructCurvesAsConstraints(56965, 41616, aCurve);\n\tcurvesConstraints[constCounter++] = aCurve;\n\t// Leg/Foot (R then L)\n\tconstructCurvesAsConstraints(28590, 16119, aCurve);\n\tcurvesConstraints[constCounter++] = aCurve;\n\tconstructCurvesAsConstraints(25037, 571, aCurve);\n\tcurvesConstraints[constCounter++] = aCurve;\n\t// Arm/Hand\n\tconstructCurvesAsConstraints(55454, 6877, aCurve);\n\tcurvesConstraints[constCounter++] = aCurve;\n\tconstructCurvesAsConstraints(49059, 36423, aCurve);\n\tcurvesConstraints[constCounter++] = aCurve;\n\t// Back\n\tconstructCurvesAsConstraints(68331, 72522, aCurve);\n\tcurvesConstraints[constCounter++] = aCurve;\n\t// Tail\n\tconstructCurvesAsConstraints(24056, 1075, aCurve);\n\tcurvesConstraints[constCounter++] = aCurve;\n\n\t/* Project elements to local frame */\n\tprojectCurvesToFrame();\n\n\t/* Get the number of constraints */\n\tint numConstraints = 0;\n\tfor (int i = 0; i < curvesConstraints.size(); i++)\n\t{\n\t\tfor (int j = 0; j < curvesConstraints[i].size() - 1; j++)\n\t\t{\n\t\t\tnumConstraints++;\n\t\t}\n\t}\n\n\t/* Setup to constraint matrix */\n\tc.resize(2 * numConstraints);\n\tC.resize(2 * numConstraints, B2D.cols());\n\n\tint counter = 0;\n\tint elem;\n\tvector<Eigen::Triplet<double>> CTriplet; \n\tfor (int i = 0; i < curvesConstraints.size(); i++)\n\t{\n\t\tfor (int j = 0; j < curvesConstraints[i].size() - 1; j++)\n\t\t{\n\t\t\telem = curvesConstraints[i][j];\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * elem + 0, 1.0));\n\t\t\tc(counter++) = constraintVect2D[i][j](0);\n\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * elem + 1, 1.0));\n\t\t\tc(counter++) = constraintVect2D[i][j](1);\n\t\t}\n\t}\n\n\tC.setFromTriplets(CTriplet.begin(), CTriplet.end());\n}\n\n/* The path will be reversed, from init to end */\nvoid VectorFields::constructCurvesAsConstraints(const int& init, const int& end, vector<int>& curve)\n{\n\tpriority_queue<VertexPair, std::vector<VertexPair>, std::greater<VertexPair>> DistPQueue;\n\tEigen::VectorXd D(F.rows());\n\tEigen::VectorXi prev(F.rows());\n\n\t// Computing distance for initial sample points S\n\tfor (int i = 0; i < F.rows(); i++) {\n\t\tD(i) = numeric_limits<double>::infinity();\n\t\tprev(i) = -1;\n\t}\n\n\tD(end) = 0.0f;\n\tVertexPair vp{ end, D(end) };\n\tDistPQueue.push(vp);\n\n\tcurve.resize(0);\n\tcurve.shrink_to_fit();\n\tcurve.reserve(F.rows() / 2);\n\n\t// For other vertices in mesh\n\t//double distFromCenter;\n\tint neigh;\n\tdo {\n\t\tif (DistPQueue.size() == 0) break;\n\t\tVertexPair vp1 = DistPQueue.top();\n\t\t//distFromCenter = vp1.distance;\n\t\tDistPQueue.pop();\n\n\t\t// Updating the distance for neighbors of vertex of lowest distance in priority queue\n\t\tint const elem = vp1.vId;\n\t\tEigen::Vector3d const c1 = (V.row(F(elem, 0)) + V.row(F(elem, 1)) + V.row(F(elem, 2))) / 3.0;\n\t\tfor (auto it = 0; it != F.cols(); ++it) {\n\t\t\t/* Regular Dikjstra */\n\t\t\tneigh = AdjMF3N(elem, it);\n\t\t\tEigen::Vector3d const c2 = FC.row(neigh);\n\t\t\tdouble dist = (c2 - c1).norm();\n\t\t\t//double tempDist = D(elem) + dist;\n\t\t\tdouble tempDist = (FC.row(end) - FC.row(neigh)).norm();\n\n\t\t\t/* updating the distance */\n\t\t\tif (tempDist < D(neigh)) {\n\t\t\t\tD(neigh) = tempDist;\n\t\t\t\tVertexPair vp2{ neigh,tempDist };\n\t\t\t\tDistPQueue.push(vp2);\n\t\t\t\tprev(neigh) = vp1.vId;\n\t\t\t}\n\t\t}\n\t} while (!DistPQueue.empty());\n\n\t// Obtaining the path <reverse>\n\tint u = init;\n\twhile (prev[u] != -1 && u != end) {\n\t\tcurve.push_back(u);\n\t\tu = prev(u);\n\t}\n\n\tprintf(\"Path from %d to %d has %d elements.\\n\", init, end, curve.size());\n\n\n\tcurve.shrink_to_fit();\n}\n\nvoid VectorFields::projectCurvesToFrame()\n{\n\tEigen::MatrixXd ALoc(3, 2);\n\tEigen::Vector2d vec2D;\n\tEigen::Vector3d vec3D; \n\tint face1, face2, face3;\n\n\tconstraintVect2D.resize(curvesConstraints.size());\n\tfor (int i = 0; i < curvesConstraints.size(); i++)\n\t{\n\t\tconst int curveSize = curvesConstraints[i].size() - 1;\n\t\tconstraintVect2D[i].resize(curveSize);\n\t\tfor (int j = 0; j < curvesConstraints[i].size()-1; j++)\n\t\t{\n\t\t\tface1 = curvesConstraints[i][j];\n\t\t\tface2 = curvesConstraints[i][j + 1];\n\t\t\tALoc = A.block(3 * face1, 2 * face1, 3, 2);\n\t\t\tif (j < curvesConstraints[i].size() - 2)\n\t\t\t{\n\t\t\t\tface3 = curvesConstraints[i][j + 2];\n\t\t\t\t//face3 = curvesConstraints[i][curveSize-1];\n\t\t\t\tvec3D = (FC.row(face3) - FC.row(face1)).transpose();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tvec3D = (FC.row(face2) - FC.row(face1)).transpose();\n\t\t\t}\n\t\t\t\n\t\t\tvec2D = ALoc.transpose() * vec3D;\n\t\t\tvec2D.normalize();\n\t\t\tconstraintVect2D[i][j] = vec2D;\n\t\t\t//cout << \"vec2D= \" << vec2D << endl; \n\t\t}\n\t}\n\n\tcout << \"Fields are projected to 2d frame \" << endl; \n}\n\n//void VectorFields::constructSpecifiedConstraintsWithSingularities()  ==> Version 2.0\n//{\n//\t// Define the constraints\n//\tconst int numConstraints = 4;\n//\tset<int> constraints;\n//\n//\tglobalConstraints.resize(numConstraints);\n//\tEigen::VectorXd D;\n//\tD.resize(F.rows());\n//\n//\t// Initialize the value of D\n//\tfor (int i = 0; i < F.rows(); i++) {\n//\t\tD(i) = numeric_limits<double>::infinity();\n//\t}\n//\n//\tsrand(time(NULL));\n//\tint curPoint = rand() % F.rows();\n//\tconstraints.insert(curPoint);\n//\n//\t// Creating constraints using farthest point sampling\n//\tdo {\n//\t\tEigen::VectorXi::Index maxIndex;\n//\t\tcomputeDijkstraDistanceFaceForSampling(curPoint, D);\n//\t\tD.maxCoeff(&maxIndex);\n//\t\tconstraints.insert(maxIndex);\n//\t\tcurPoint = maxIndex;\n//\t} while (constraints.size() < numConstraints);\n//\n//\tint counter1 = 0;\n//\tfor (int i : constraints) {\n//\t\tglobalConstraints[counter1++] = i;\n//\t}\n//\t\n//\tint numSingConstraints = 0;\n//\tfor (int i = 0; i < SingNeighCC.size(); i++) {\n//\t\t// Use only n-1 neighboring faces as constraints\n//\t\tfor (int j = 0; j < (SingNeighCC[i].size()-1); j++) {\n//\t\t\tnumSingConstraints++;\n//\t\t}\n//\t}\n//\n//\t// Setting up matrix C and vector c\n//\tc.resize(2 * (globalConstraints.size()+numSingConstraints));\n//\n//\n//\t// HARD CONSTRAINTS\n//\tEigen::SparseMatrix<double> CTemp;\n//\tvector<Eigen::Triplet<double>> CTriplet;\n//\tCTriplet.reserve(2 * globalConstraints.size() +  2 * 4 * 7 * SingNeighCC.size());\n//\tint counter = 0;\n//\tfor (int i = 0; i < globalConstraints.size(); i++) {\n//\t\t// Matrix C\n//\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 0, 1.0));\n//\t\tc(counter++, 0) = sqrt(2.0);\n//\t\t//c(counter++, 1) = sqrt(2.0);\n//\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 1, 1.0));\n//\t\tc(counter++, 0) = sqrt(2.0);\n//\t\t//c(counter++, 1) = sqrt(2.0);\n//\t}\n//\n//\t\n//\t// SINGULARITIES CONSTRAINTS\n//\tfor (int id = 0; id < SingNeighCC.size(); id++) {\n//\t\t// For testing\n//\t\tsharedEdgesVect[id].resize(2*SingNeighCC[id].size()-2);\n//\n//\t\t// 4. Compute rotation of among its valence\n//\t\tconst double rotAngle = 2 * M_PI / (double)SingNeighCC[id].size();\n//\t\tconst double cosA = cos(rotAngle);\n//\t\tconst double sinA = sin(rotAngle);\n//\n//\t\t// Which case? => determining which edge is the common edge\n//\t\tenum class SharedEdgeCase {Case1, Case2, Case3};\n//\t\tSharedEdgeCase edgeCase1, edgeCase2; \n//\t\tfor (int i = 0; i < (SingNeighCC[id].size() - 1); i++) {\n//\t\t\t// 1. Find shared edge (naively)\n//\t\t\tEigen::RowVector3d es;\n//\t\t\tfor (int f1 = 0; f1 < F.cols(); f1++) {\n//\t\t\t\tfor (int f2 = 0; f2 < F.cols(); f2++) {\n//\t\t\t\t\tbool b1 = F(SingNeighCC[id][i], (f1+1)%F.cols()) == F(SingNeighCC[id][i + 1], f2);\n//\t\t\t\t\tbool b2 = F(SingNeighCC[id][i], f1) == F(SingNeighCC[id][i + 1], (f2 + 1) % F.cols());\n//\t\t\t\t\tif (b1 && b2) {\n//\t\t\t\t\t\tsharedEdgesVect[id][2 * i + 0] = F(SingNeighCC[id][i], f1);\n//\t\t\t\t\t\tsharedEdgesVect[id][2 * i + 1] = F(SingNeighCC[id][i], (f1 + 1) % F.cols());\n//\t\t\t\t\t\tes = V.row(F(SingNeighCC[id][i], (f1 + 1) % F.cols())) - V.row(F(SingNeighCC[id][i], f1));\n//\t\t\t\t\t\tprintf(\"Shared edge=%d->%d\\n\", F(SingNeighCC[id][i], f1), F(SingNeighCC[id][i], (f1 + 1) % F.cols()));\n//\t\t\t\t\t\t\n//\t\t\t\t\t\tif (f1 == 0)\t\tedgeCase1 = SharedEdgeCase::Case1;\t// => edge V0->V1 is the shared edge => it takes 0 step to reach v0\n//\t\t\t\t\t\telse if(f1==1)\t\tedgeCase1 = SharedEdgeCase::Case3;\t// => edge V1->V2 is the shared edge => it takes 2 step to reach v0\n//\t\t\t\t\t\telse if(f1==2)\t\tedgeCase1 = SharedEdgeCase::Case2;\t// => edge V2->V0 is the shared edge => it takes 1 step to reach v0\n//\n//\t\t\t\t\t\tif (f2 == 0)\t\tedgeCase2 = SharedEdgeCase::Case1;\n//\t\t\t\t\t\telse if (f2 == 1)\tedgeCase2 = SharedEdgeCase::Case3;\n//\t\t\t\t\t\telse if (f2 == 2)\tedgeCase2 = SharedEdgeCase::Case2;\n//\t\t\t\t\t}\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\t// 2. Find angles between basis1 and es\n//\t\t\tEigen::VectorXd eVect;\n//\t\t\tEigen::RowVector3d b11, b12;\n//\t\t\teVect = A.block(3 * SingNeighCC[id][i], 2 * SingNeighCC[id][i]+0, 3, 1);\n//\t\t\tb11 << eVect(0), eVect(1), eVect(2);\n//\t\t\teVect = A.block(3 * SingNeighCC[id][i], 2 * SingNeighCC[id][i]+1, 3, 1);\n//\t\t\tb12 << eVect(0), eVect(1), eVect(2);\n//\t\t\tcout << \"______B11: \" << b11 << \", B12: \" << b12 << endl;\n//\n//\t\t\t// Basis 1, Frame 1\n//\t\t\tdouble cosR12 = (b11.dot(es)) / (b11.norm()*es.norm());\n//\t\t\tif (cosR12 > 1.0) cosR12 = 1.0; \n//\t\t\tif (cosR12 <-1.0) cosR12 = -1.0;\n//\t\t\tconst double angleR12_1 = (edgeCase1==SharedEdgeCase::Case2 ? 2*M_PI - acos(cosR12) : acos(cosR12));\n//\t\t\tconst double cosR12_1 = cos(angleR12_1);\n//\t\t\tconst double sinR12_1 = sin(angleR12_1);\n//\t\t\tprintf(\"______[%.2f] Rotation matrix R12_1 = [%.3f,%.3f; %.3f, %.3f]\\n\", angleR12_1*180.0/M_PI, cosR12_1, -sinR12_1, sinR12_1, cosR12_1);\n//\n//\t\t\t// Basis 1, Frame 2\n//\t\t\tcosR12 = (b12.dot(es)) / (b12.norm()*es.norm());\n//\t\t\tif (cosR12 > 1.0) cosR12 = 1.0;\n//\t\t\tif (cosR12 <-1.0) cosR12 = -1.0;\n//\t\t\tconst double angleR12_2 = (edgeCase1 == SharedEdgeCase::Case1 ? 2 * M_PI - acos(cosR12) : acos(cosR12));\n//\t\t\tconst double cosR12_2 = cos(angleR12_2);\n//\t\t\tconst double sinR12_2 = sin(angleR12_2);\n//\t\t\tprintf(\"______[%.2f] Rotation matrix R12_2 = [%.2f,%.2f; %.2f, %.2f]\\n\", angleR12_2*180.0 / M_PI, cosR12_2, -sinR12_2, sinR12_2, cosR12_2);\n//\n//\t\t\t// 3. Find angles between basis2 and es\n//\t\t\tes = -es; \n//\t\t\tEigen::RowVector3d b21, b22;\n//\t\t\teVect = A.block(3 * SingNeighCC[id][i+1], 2 * SingNeighCC[id][i+1] + 0, 3, 1);\n//\t\t\tb21 << eVect(0), eVect(1), eVect(2);\n//\t\t\teVect = A.block(3 * SingNeighCC[id][i+1], 2 * SingNeighCC[id][i+1] + 1, 3, 1);\n//\t\t\tb22 << eVect(0), eVect(1), eVect(2);\n//\t\t\tcout << \"______B21: \" << b21 << \", B22: \" << b22 << endl;\n//\t\t\t\n//\t\t\t// Basis 2, Frame 1\n//\t\t\tdouble cosR21 = (b21.dot(es)) / (b21.norm()*es.norm());\n//\t\t\tif (cosR21 > 1.0) cosR21 = 1.0;\n//\t\t\tif (cosR21 < -1.0) cosR21 = -1.0;\n//\t\t\tconst double angleR21_1 = (edgeCase2 == SharedEdgeCase::Case2 ? 2 * M_PI - acos(cosR21) : acos(cosR21));\n//\t\t\tconst double cosR21_1 = cos(angleR21_1);\n//\t\t\tconst double sinR21_1 = sin(angleR21_1);\n//\t\t\tprintf(\"______[%.2f] Rotation matrix R22_1 = [%.2f,%.2f; %.2f, %.2f]\\n\", angleR21_1*180.0/M_PI, cosR21_1, -sinR21_1, sinR21_1, cosR21_1);\n//\n//\t\t\t// Basis 2, Frame 2\n//\t\t\tcosR21 = (b22.dot(es)) / (b22.norm()*es.norm());\n//\t\t\tif (cosR21 > 1.0) cosR21 = 1.0;\n//\t\t\tif (cosR21 < -1.0) cosR21 = -1.0;\n//\t\t\tconst double angleR21_2 = (edgeCase2 == SharedEdgeCase::Case1 ? 2 * M_PI - acos(cosR21) : acos(cosR21));\n//\t\t\tconst double cosR21_2 = cos(angleR21_2);\n//\t\t\tconst double sinR21_2 = sin(angleR21_2);\n//\t\t\tprintf(\"______[%.2f] Rotation matrix R22_2 = [%.2f,%.2f; %.2f, %.2f]\\n\", angleR21_2*180.0/M_PI, cosR21_2, -sinR21_2, sinR21_2, cosR21_2);\n//\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, cosR12_1));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -sinR12_1));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -cosR21_1));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, sinR21_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, cosR21_1*cosR12_1+sinR21_1*sinR12_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -cosR21_1*sinR12_1+sinR21_1*cosR12_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -1.0));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, 0.0));\n//\t\t\tc(counter) = 0.0;\n//\t\t\tcounter++;\n//\t\t\t\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, sinR12_1));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, cosR12_1 ));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -sinR21_1));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, -cosR21_1 ));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, -sinR21_1*cosR12_1+cosR21_1*sinR12_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, sinR21_1*sinR12_1+cosR21_1*cosR21_1));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, 0.0));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, -1.0));\n//\t\t\tc(counter) = 0.0;\n//\t\t\tcounter++;\n//\t\t}\n//\t}\n//\n//\tC.resize(2 * (globalConstraints.size()+numSingConstraints), B2D.rows());\n//\tC.setFromTriplets(CTriplet.begin(), CTriplet.end());\n//\t//printf(\"Cp=%dx%d\\n\", C.rows(), C.cols());\t\n//}\n\n//void VectorFields::constructSpecifiedConstraintsWithSingularities() ==> VERSION 1.1\n//{\n//\t// Define the constraints\n//\tconst int numConstraints = 4;\n//\tset<int> constraints;\n//\n//\tglobalConstraints.resize(numConstraints);\n//\tEigen::VectorXd D;\n//\tD.resize(F.rows());\n//\n//\t// Initialize the value of D\n//\tfor (int i = 0; i < F.rows(); i++) {\n//\t\tD(i) = numeric_limits<double>::infinity();\n//\t}\n//\n//\tsrand(time(NULL));\n//\tint curPoint = rand() % F.rows();\n//\tconstraints.insert(curPoint);\n//\n//\t// Creating constraints using farthest point sampling\n//\tdo {\n//\t\tEigen::VectorXi::Index maxIndex;\n//\t\tcomputeDijkstraDistanceFaceForSampling(curPoint, D);\n//\t\tD.maxCoeff(&maxIndex);\n//\t\tconstraints.insert(maxIndex);\n//\t\tcurPoint = maxIndex;\n//\t} while (constraints.size() < numConstraints);\n//\n//\tint counter1 = 0;\n//\tfor (int i : constraints) {\n//\t\tglobalConstraints[counter1++] = i;\n//\t}\n//\t//printf(\"Constraints = %d\\n\", globalConstraints.size());\n//\n//\t//constructSingularities();\n//\n//\tint numSingConstraints = 0;\n//\tfor (int i = 0; i < SingNeighCC.size(); i++) {\n//\t\t// Use only n-1 neighboring faces as constraints\n//\t\tfor (int j = 0; j < (SingNeighCC[i].size() - 1); j++) {\n//\t\t\tnumSingConstraints++;\n//\t\t}\n//\t}\n//\n//\t// Setting up matrix C and vector c\n//\tc.resize(2 * (globalConstraints.size() + 2 * numSingConstraints), 2);\n//\t//printf(\"cBar=%dx%d\\n\", c.rows(), c.cols());\n//\n//\n//\t// HARD CONSTRAINTS\n//\tEigen::SparseMatrix<double> CTemp;\n//\tvector<Eigen::Triplet<double>> CTriplet;\n//\tCTriplet.reserve(2 * globalConstraints.size() + 2 * 2 * 4 * 7 * SingNeighCC.size());\n//\tint counter = 0;\n//\tfor (int i = 0; i < globalConstraints.size(); i++) {\n//\t\t// Matrix C\n//\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 0, 1.0));\n//\t\tc(counter, 0) = sqrt(2.0);\n//\t\tc(counter++, 1) = sqrt(2.0);\n//\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 1, 1.0));\n//\t\tc(counter, 0) = sqrt(2.0);\n//\t\tc(counter++, 1) = sqrt(2.0);\n//\t}\n//\n//\n//\t// SINGULARITIES CONSTRAINTS\n//\tfor (int id = 0; id < SingNeighCC.size(); id++) {\n//\t\t// For testing\n//\t\tsharedEdgesVect[id].resize(2 * SingNeighCC[id].size() - 2);\n//\n//\t\t// 4. Compute rotation of among its valence\n//\t\tconst double rotAngle = 2 * M_PI / (double)SingNeighCC[id].size();\n//\t\tconst double cosA = cos(rotAngle);\n//\t\tconst double sinA = sin(rotAngle);\n//\t\t// Which case?\n//\t\tenum class SharedEdgeCase { Case1, Case2, Case3 };\n//\t\tSharedEdgeCase edgeCase1, edgeCase2;\n//\t\tfor (int i = 0; i < (SingNeighCC[id].size() - 1); i++) {\n//\t\t\t// 1. Find shared edge (naively)\n//\t\t\tEigen::RowVector3d es;\n//\t\t\tfor (int f1 = 0; f1 < F.cols(); f1++) {\n//\t\t\t\tfor (int f2 = 0; f2 < F.cols(); f2++) {\n//\t\t\t\t\tbool b1 = F(SingNeighCC[id][i], (f1 + 1) % F.cols()) == F(SingNeighCC[id][i + 1], f2);\n//\t\t\t\t\tbool b2 = F(SingNeighCC[id][i], f1) == F(SingNeighCC[id][i + 1], (f2 + 1) % F.cols());\n//\t\t\t\t\tif (b1 && b2) {\n//\t\t\t\t\t\tsharedEdgesVect[id][2 * i + 0] = F(SingNeighCC[id][i], f1);\n//\t\t\t\t\t\tsharedEdgesVect[id][2 * i + 1] = F(SingNeighCC[id][i], (f1 + 1) % F.cols());\n//\t\t\t\t\t\tes = V.row(F(SingNeighCC[id][i], (f1 + 1) % F.cols())) - V.row(F(SingNeighCC[id][i], f1));\n//\t\t\t\t\t\tprintf(\"Shared edge=%d->%d\\n\", F(SingNeighCC[id][i], f1), F(SingNeighCC[id][i], (f1 + 1) % F.cols()));\n//\n//\t\t\t\t\t\tif (f1 == 0) edgeCase1 = SharedEdgeCase::Case1;\n//\t\t\t\t\t\telse if (f1 == 1) edgeCase1 = SharedEdgeCase::Case3;\n//\t\t\t\t\t\telse if (f1 == 2) edgeCase1 = SharedEdgeCase::Case2;\n//\n//\t\t\t\t\t\tif (f2 == 0) edgeCase2 = SharedEdgeCase::Case1;\n//\t\t\t\t\t\telse if (f2 == 1) edgeCase2 = SharedEdgeCase::Case3;\n//\t\t\t\t\t\telse if (f2 == 2) edgeCase2 = SharedEdgeCase::Case2;\n//\t\t\t\t\t}\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\t// 2. Find angles between basis1 and es\n//\t\t\tEigen::VectorXd eVect;\n//\t\t\tEigen::RowVector3d b11, b12;\n//\t\t\teVect = A.block(3 * SingNeighCC[id][i], 2 * SingNeighCC[id][i] + 0, 3, 1);\n//\t\t\tb11 << eVect(0), eVect(1), eVect(2);\n//\t\t\teVect = A.block(3 * SingNeighCC[id][i], 2 * SingNeighCC[id][i] + 1, 3, 1);\n//\t\t\tb12 << eVect(0), eVect(1), eVect(2);\n//\t\t\tcout << \"______B11: \" << b11 << \", B12: \" << b12 << endl;\n//\n//\t\t\t// Basis 1, Frame 1\n//\t\t\tdouble cosR12 = (b11.dot(es)) / (b11.norm()*es.norm());\n//\t\t\tif (cosR12 > 1.0) cosR12 = 1.0;\n//\t\t\tif (cosR12 <-1.0) cosR12 = -1.0;\n//\t\t\tconst double angleR12_1 = (edgeCase1 == SharedEdgeCase::Case2 ? 2 * M_PI - acos(cosR12) : acos(cosR12));\n//\t\t\tconst double cosR12_1 = cos(angleR12_1);\n//\t\t\tconst double sinR12_1 = sin(angleR12_1);\n//\t\t\tprintf(\"______[%.2f] Rotation matrix R12_1 = [%.3f,%.3f; %.3f, %.3f]\\n\", angleR12_1*180.0 / M_PI, cosR12_1, -sinR12_1, sinR12_1, cosR12_1);\n//\n//\t\t\t// Basis 1, Frame 2\n//\t\t\tcosR12 = (b12.dot(es)) / (b12.norm()*es.norm());\n//\t\t\tif (cosR12 > 1.0) cosR12 = 1.0;\n//\t\t\tif (cosR12 <-1.0) cosR12 = -1.0;\n//\t\t\tconst double angleR12_2 = (edgeCase1 == SharedEdgeCase::Case1 ? 2 * M_PI - acos(cosR12) : acos(cosR12));\n//\t\t\tconst double cosR12_2 = cos(angleR12_2);\n//\t\t\tconst double sinR12_2 = sin(angleR12_2);\n//\t\t\tprintf(\"______[%.2f] Rotation matrix R12_2 = [%.2f,%.2f; %.2f, %.2f]\\n\", angleR12_2*180.0 / M_PI, cosR12_2, -sinR12_2, sinR12_2, cosR12_2);\n//\n//\t\t\t// 3. Find angles between basis2 and es\n//\t\t\tes = -es;\n//\t\t\tEigen::RowVector3d b21, b22;\n//\t\t\teVect = A.block(3 * SingNeighCC[id][i + 1], 2 * SingNeighCC[id][i + 1] + 0, 3, 1);\n//\t\t\tb21 << eVect(0), eVect(1), eVect(2);\n//\t\t\teVect = A.block(3 * SingNeighCC[id][i + 1], 2 * SingNeighCC[id][i + 1] + 1, 3, 1);\n//\t\t\tb22 << eVect(0), eVect(1), eVect(2);\n//\t\t\tcout << \"______B21: \" << b21 << \", B22: \" << b22 << endl;\n//\n//\t\t\t// Basis 2, Frame 1\n//\t\t\tdouble cosR21 = (b21.dot(es)) / (b21.norm()*es.norm());\n//\t\t\tif (cosR21 > 1.0) cosR21 = 1.0;\n//\t\t\tif (cosR21 < -1.0) cosR21 = -1.0;\n//\t\t\tconst double angleR21_1 = (edgeCase2 == SharedEdgeCase::Case2 ? 2 * M_PI - acos(cosR21) : acos(cosR21));\n//\t\t\tconst double cosR21_1 = cos(angleR21_1);\n//\t\t\tconst double sinR21_1 = sin(angleR21_1);\n//\t\t\tprintf(\"______[%.2f] Rotation matrix R22_1 = [%.2f,%.2f; %.2f, %.2f]\\n\", angleR21_1*180.0 / M_PI, cosR21_1, -sinR21_1, sinR21_1, cosR21_1);\n//\n//\t\t\t// Basis 2, Frame 2\n//\t\t\tcosR21 = (b22.dot(es)) / (b22.norm()*es.norm());\n//\t\t\tif (cosR21 > 1.0) cosR21 = 1.0;\n//\t\t\tif (cosR21 < -1.0) cosR21 = -1.0;\n//\t\t\tconst double angleR21_2 = (edgeCase2 == SharedEdgeCase::Case1 ? 2 * M_PI - acos(cosR21) : acos(cosR21));\n//\t\t\tconst double cosR21_2 = cos(angleR21_2);\n//\t\t\tconst double sinR21_2 = sin(angleR21_2);\n//\t\t\tprintf(\"______[%.2f] Rotation matrix R22_2 = [%.2f,%.2f; %.2f, %.2f]\\n\", angleR21_2*180.0 / M_PI, cosR21_2, -sinR21_2, sinR21_2, cosR21_2);\n//\n//\n//\t\t\t// 5. Assigning singularities constraints\n//\t\t\t// Basis 1 => Frame 1\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, cosA*cosR12_1 - sinA*sinR12_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -cosA*sinR12_1 - sinA*cosR12_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -cosR21_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, sinR21_1));\n//\t\t\tc(counter, 0) = 0.0;\n//\t\t\tc(counter, 1) = 0.0;\n//\t\t\tcounter++;\n//\t\t\t// Basis 1 => Frame 2\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, cosA*cosR12_2 - sinA*sinR12_2));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -cosA*sinR12_2 - sinA*cosR12_2));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -cosR21_2));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, sinR21_2));\n//\t\t\tc(counter, 0) = 0.0;\n//\t\t\tc(counter, 1) = 0.0;\n//\t\t\tcounter++;\n//\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, sinA*cosR12_1 + cosA*sinR12_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -sinA*sinR12_1 + cosA*cosR12_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -sinR21_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, -cosR21_1));\n//\t\t\tc(counter, 0) = 0.0;\n//\t\t\tc(counter, 1) = 0.0;\n//\t\t\tcounter++;\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, sinA*cosR12_2 + cosA*sinR12_2));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -sinA*sinR12_2 + cosA*cosR12_2));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -sinR21_2));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, -cosR21_2));\n//\t\t\tc(counter, 0) = 0.0;\n//\t\t\tc(counter, 1) = 0.0;\n//\t\t\tcounter++;\n//\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, cosA));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -sinA));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -1.0));\n//\t\t\t//c(counter, 0) = 0.0;\n//\t\t\t//c(counter, 1) = 0.0;\n//\t\t\t//counter++;\n//\t\t\t//\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, sinA));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, cosA));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, -1.0));\n//\t\t\t//c(counter, 0) = 0.0;\n//\t\t\t//c(counter, 1) = 0.0;\n//\t\t\t//counter++;\n//\t\t}\n//\t}\n//\n//\tC.resize(2 * (globalConstraints.size() + 2 * numSingConstraints), B2D.rows());\n//\tC.setFromTriplets(CTriplet.begin(), CTriplet.end());\n//\t//printf(\"Cp=%dx%d\\n\", C.rows(), C.cols());\t\n//}\n\n//\n//void VectorFields::constructSpecifiedConstraintsWithSingularities() ==> VERSION 1.0\n//{\n//\t// Define the constraints\n//\tconst int numConstraints = 5;\n//\tset<int> constraints;\n//\n//\tglobalConstraints.resize(numConstraints);\n//\tEigen::VectorXd D;\n//\tD.resize(F.rows());\n//\n//\t// Initialize the value of D\n//\tfor (int i = 0; i < F.rows(); i++) {\n//\t\tD(i) = numeric_limits<double>::infinity();\n//\t}\n//\n//\tsrand(time(NULL));\n//\tint curPoint = rand() % F.rows();\n//\tconstraints.insert(curPoint);\n//\n//\t// Creating constraints using farthest point sampling\n//\tdo {\n//\t\tEigen::VectorXi::Index maxIndex;\n//\t\tcomputeDijkstraDistanceFaceForSampling(curPoint, D);\n//\t\tD.maxCoeff(&maxIndex);\n//\t\tconstraints.insert(maxIndex);\n//\t\tcurPoint = maxIndex;\n//\t} while (constraints.size() <= numConstraints);\n//\n//\tint counter1 = 0;\n//\tfor (int i : constraints) {\n//\t\tglobalConstraints[counter1++] = i;\n//\t}\n//\t//printf(\"Constraints = %d\\n\", globalConstraints.size());\n//\n//\t//constructSingularities();\n//\n//\tint numSingConstraints = 0;\n//\tfor (int i = 0; i < SingNeighCC.size(); i++) {\n//\t\t// Use only n-1 neighboring faces as constraints\n//\t\tfor (int j = 0; j < (SingNeighCC[i].size() - 1); j++) {\n//\t\t\tnumSingConstraints++;\n//\t\t}\n//\t}\n//\n//\t// Setting up matrix C and vector c\n//\tc.resize(2 * (globalConstraints.size() + 2 * numSingConstraints), 2);\n//\t//printf(\"cBar=%dx%d\\n\", c.rows(), c.cols());\n//\n//\n//\t// HARD CONSTRAINTS\n//\tEigen::SparseMatrix<double> CTemp;\n//\tvector<Eigen::Triplet<double>> CTriplet;\n//\tCTriplet.reserve(2 * globalConstraints.size() + 2 * 2 * 4 * 7 * SingNeighCC.size());\n//\tint counter = 0;\n//\tfor (int i = 0; i < globalConstraints.size(); i++) {\n//\t\t// Matrix C\n//\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 0, 1.0));\n//\t\tc(counter, 0) = sqrt(2.0);\n//\t\tc(counter++, 1) = sqrt(2.0);\n//\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * globalConstraints[i] + 1, 1.0));\n//\t\tc(counter, 0) = sqrt(2.0);\n//\t\tc(counter++, 1) = sqrt(2.0);\n//\t}\n//\n//\n//\t// SINGULARITIES CONSTRAINTS\n//\tfor (int id = 0; id < SingNeighCC.size(); id++) {\n//\t\t// For testing\n//\t\tsharedEdgesVect[id].resize(2 * SingNeighCC[id].size() - 2);\n//\n//\t\t// 4. Compute rotation of among its valence\n//\t\tconst double rotAngle = 2 * M_PI / (double)SingNeighCC[id].size();\n//\t\tconst double cosA = cos(rotAngle);\n//\t\tconst double sinA = sin(rotAngle);\n//\t\t// Which case?\n//\t\tenum class SharedEdgeCase { Case1, Case2, Case3 };\n//\t\tSharedEdgeCase edgeCase1, edgeCase2;\n//\t\tfor (int i = 0; i < (SingNeighCC[id].size() - 1); i++) {\n//\t\t\t// 1. Find shared edge (naively)\n//\t\t\tEigen::RowVector3d es;\n//\t\t\tfor (int f1 = 0; f1 < F.cols(); f1++) {\n//\t\t\t\tfor (int f2 = 0; f2 < F.cols(); f2++) {\n//\t\t\t\t\tbool b1 = F(SingNeighCC[id][i], (f1 + 1) % F.cols()) == F(SingNeighCC[id][i + 1], f2);\n//\t\t\t\t\tbool b2 = F(SingNeighCC[id][i], f1) == F(SingNeighCC[id][i + 1], (f2 + 1) % F.cols());\n//\t\t\t\t\tif (b1 && b2) {\n//\t\t\t\t\t\tsharedEdgesVect[id][2 * i + 0] = F(SingNeighCC[id][i], f1);\n//\t\t\t\t\t\tsharedEdgesVect[id][2 * i + 1] = F(SingNeighCC[id][i], (f1 + 1) % F.cols());\n//\t\t\t\t\t\tes = V.row(F(SingNeighCC[id][i], (f1 + 1) % F.cols())) - V.row(F(SingNeighCC[id][i], f1));\n//\t\t\t\t\t\tprintf(\"Shared edge=%d->%d\\n\", F(SingNeighCC[id][i], f1), F(SingNeighCC[id][i], (f1 + 1) % F.cols()));\n//\n//\t\t\t\t\t\tif (f1 == 0) edgeCase1 = SharedEdgeCase::Case1;\n//\t\t\t\t\t\telse if (f1 == 1) edgeCase1 = SharedEdgeCase::Case3;\n//\t\t\t\t\t\telse if (f1 == 2) edgeCase1 = SharedEdgeCase::Case2;\n//\n//\t\t\t\t\t\tif (f2 == 0) edgeCase2 = SharedEdgeCase::Case1;\n//\t\t\t\t\t\telse if (f2 == 1) edgeCase2 = SharedEdgeCase::Case3;\n//\t\t\t\t\t\telse if (f2 == 2) edgeCase2 = SharedEdgeCase::Case2;\n//\t\t\t\t\t}\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\t// 2. Find angles between basis1 and es\n//\t\t\tEigen::VectorXd eVect;\n//\t\t\tEigen::RowVector3d b11, b12;\n//\t\t\teVect = A.block(3 * SingNeighCC[id][i], 2 * SingNeighCC[id][i] + 0, 3, 1);\n//\t\t\tb11 << eVect(0), eVect(1), eVect(2);\n//\t\t\teVect = A.block(3 * SingNeighCC[id][i], 2 * SingNeighCC[id][i] + 1, 3, 1);\n//\t\t\tb12 << eVect(0), eVect(1), eVect(2);\n//\t\t\tcout << \"______B11: \" << b11 << \", B12: \" << b12 << endl;\n//\n//\t\t\t// Basis 1, Frame 1\n//\t\t\tdouble cosR12 = (b11.dot(es)) / (b11.norm()*es.norm());\n//\t\t\tif (cosR12 > 1.0) cosR12 = 1.0;\n//\t\t\tif (cosR12 <-1.0) cosR12 = -1.0;\n//\t\t\tconst double angleR12_1 = (edgeCase1 == SharedEdgeCase::Case2 ? 2 * M_PI - acos(cosR12) : acos(cosR12));\n//\t\t\tconst double cosR12_1 = cos(angleR12_1);\n//\t\t\tconst double sinR12_1 = sin(angleR12_1);\n//\t\t\tprintf(\"______[%.2f] Rotation matrix R12_1 = [%.3f,%.3f; %.3f, %.3f]\\n\", angleR12_1*180.0 / M_PI, cosR12_1, -sinR12_1, sinR12_1, cosR12_1);\n//\n//\t\t\t// Basis 1, Frame 2\n//\t\t\tcosR12 = (b12.dot(es)) / (b12.norm()*es.norm());\n//\t\t\tif (cosR12 > 1.0) cosR12 = 1.0;\n//\t\t\tif (cosR12 <-1.0) cosR12 = -1.0;\n//\t\t\tconst double angleR12_2 = (edgeCase1 == SharedEdgeCase::Case1 ? 2 * M_PI - acos(cosR12) : acos(cosR12));\n//\t\t\tconst double cosR12_2 = cos(angleR12_2);\n//\t\t\tconst double sinR12_2 = sin(angleR12_2);\n//\t\t\tprintf(\"______[%.2f] Rotation matrix R12_2 = [%.2f,%.2f; %.2f, %.2f]\\n\", angleR12_2*180.0 / M_PI, cosR12_2, -sinR12_2, sinR12_2, cosR12_2);\n//\n//\t\t\t// 3. Find angles between basis2 and es\n//\t\t\tes = -es;\n//\t\t\tEigen::RowVector3d b21, b22;\n//\t\t\teVect = A.block(3 * SingNeighCC[id][i + 1], 2 * SingNeighCC[id][i + 1] + 0, 3, 1);\n//\t\t\tb21 << eVect(0), eVect(1), eVect(2);\n//\t\t\teVect = A.block(3 * SingNeighCC[id][i + 1], 2 * SingNeighCC[id][i + 1] + 1, 3, 1);\n//\t\t\tb22 << eVect(0), eVect(1), eVect(2);\n//\t\t\tcout << \"______B21: \" << b21 << \", B22: \" << b22 << endl;\n//\n//\t\t\t// Basis 2, Frame 1\n//\t\t\tdouble cosR21 = (b21.dot(es)) / (b21.norm()*es.norm());\n//\t\t\tif (cosR21 > 1.0) cosR21 = 1.0;\n//\t\t\tif (cosR21 < -1.0) cosR21 = -1.0;\n//\t\t\tconst double angleR21_1 = (edgeCase2 == SharedEdgeCase::Case2 ? 2 * M_PI - acos(cosR21) : acos(cosR21));\n//\t\t\tconst double cosR21_1 = cos(angleR21_1);\n//\t\t\tconst double sinR21_1 = sin(angleR21_1);\n//\t\t\tprintf(\"______[%.2f] Rotation matrix R22_1 = [%.2f,%.2f; %.2f, %.2f]\\n\", angleR21_1*180.0 / M_PI, cosR21_1, -sinR21_1, sinR21_1, cosR21_1);\n//\n//\t\t\t// Basis 2, Frame 2\n//\t\t\tcosR21 = (b22.dot(es)) / (b22.norm()*es.norm());\n//\t\t\tif (cosR21 > 1.0) cosR21 = 1.0;\n//\t\t\tif (cosR21 < -1.0) cosR21 = -1.0;\n//\t\t\tconst double angleR21_2 = (edgeCase2 == SharedEdgeCase::Case1 ? 2 * M_PI - acos(cosR21) : acos(cosR21));\n//\t\t\tconst double cosR21_2 = cos(angleR21_2);\n//\t\t\tconst double sinR21_2 = sin(angleR21_2);\n//\t\t\tprintf(\"______[%.2f] Rotation matrix R22_2 = [%.2f,%.2f; %.2f, %.2f]\\n\", angleR21_2*180.0 / M_PI, cosR21_2, -sinR21_2, sinR21_2, cosR21_2);\n//\n//\n//\t\t\t// 5. Assigning singularities constraints\n//\t\t\t// Basis 1 => Frame 1\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, cosA*cosR12_1 - sinA*sinR12_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -cosA*sinR12_1 - sinA*cosR12_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -cosR21_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, sinR21_1));\n//\t\t\tc(counter, 0) = 0.0;\n//\t\t\tc(counter, 1) = 0.0;\n//\t\t\tcounter++;\n//\t\t\t// Basis 1 => Frame 2\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, cosA*cosR12_2 - sinA*sinR12_2));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -cosA*sinR12_2 - sinA*cosR12_2));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -cosR21_2));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, sinR21_2));\n//\t\t\tc(counter, 0) = 0.0;\n//\t\t\tc(counter, 1) = 0.0;\n//\t\t\tcounter++;\n//\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, sinA*cosR12_1 + cosA*sinR12_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -sinA*sinR12_1 + cosA*cosR12_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -sinR21_1));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, -cosR21_1));\n//\t\t\tc(counter, 0) = 0.0;\n//\t\t\tc(counter, 1) = 0.0;\n//\t\t\tcounter++;\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, sinA*cosR12_2 + cosA*sinR12_2));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -sinA*sinR12_2 + cosA*cosR12_2));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -sinR21_2));\n//\t\t\tCTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, -cosR21_2));\n//\t\t\tc(counter, 0) = 0.0;\n//\t\t\tc(counter, 1) = 0.0;\n//\t\t\tcounter++;\n//\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, cosA));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, -sinA));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 0, -1.0));\n//\t\t\t//c(counter, 0) = 0.0;\n//\t\t\t//c(counter, 1) = 0.0;\n//\t\t\t//counter++;\n//\t\t\t//\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 0, sinA));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i] + 1, cosA));\n//\t\t\t//CTriplet.push_back(Eigen::Triplet<double>(counter, 2 * SingNeighCC[id][i + 1] + 1, -1.0));\n//\t\t\t//c(counter, 0) = 0.0;\n//\t\t\t//c(counter, 1) = 0.0;\n//\t\t\t//counter++;\n//\t\t}\n//\t}\n//\n//\tC.resize(2 * (globalConstraints.size() + 2 * numSingConstraints), B2D.rows());\n//\tC.setFromTriplets(CTriplet.begin(), CTriplet.end());\n//\t//printf(\"Cp=%dx%d\\n\", C.rows(), C.cols());\t\n//}\n//\nvoid VectorFields::setupGlobalProblem()\n{\t\n\tEigen::VectorXd\t\t\t\t\tb, g, h, vEst;\n\tEigen::SparseMatrix<double>\t\tA_LHS;\n\t//Eigen::VectorXd\t\t\t\t\tvEst;\n\tdouble lambda = 0.4; \n\t\n\tconstructConstraints();\n\tsetupRHSGlobalProblemMapped(g, h, vEst, b);\n\tsetupLHSGlobalProblemMapped(A_LHS);\n\tsolveGlobalSystemMappedLDLT(vEst, A_LHS, b);\n\t//solveGlobalSystemMappedLU_GPU();\n\n\t//setupRHSGlobalProblemSoftConstraints(lambda, b);\n\t//setupLHSGlobalProblemSoftConstraints(lambda, A_LHS);\t\t\n\t//solveGlobalSystemMappedLDLTSoftConstraints(A_LHS, b);\n}\n\nvoid VectorFields::setupRHSGlobalProblemMapped(Eigen::VectorXd& g, Eigen::VectorXd& h, Eigen::VectorXd& vEst, Eigen::VectorXd& b)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt1 = chrono::high_resolution_clock::now();\n\tcout << \"> Constructing RHS... \";\n\n\tvEst.resize(B2D.cols());\n\tfor (int i = 0; i < vEst.rows(); i++) {\n\t\tvEst(i) = 0.5;\n\t}\n\n\tg = B2D * vEst;\n\tb.resize(B2D.rows() + c.rows(), c.cols());\n\n\t// First column of b\n\th = C * vEst - c;\n\tb << g, h;\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\tcout << \"in \" << duration.count() << \" seconds\" << endl;\n}\n\nvoid VectorFields::setupLHSGlobalProblemMapped(Eigen::SparseMatrix<double>& A_LHS)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt1 = chrono::high_resolution_clock::now();\n\tcout << \"> Constructing LHS... \";\n\n\tA_LHS.resize(B2D.rows() + C.rows(), B2D.cols() + C.rows());\n\n\tvector<Eigen::Triplet<double>>\tATriplet;\n\tATriplet.reserve(10 * B2D.rows());\t\t// It should be #rows x 4 blocks @ 2 elements (8) + #constraints,\n\t\t\t\t\t\t\t\t\t\t\t// but made it 10 for safety + simplicity\n\n\tfor (int k = 0; k < B2D.outerSize(); ++k) {\n\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(B2D, k); it; ++it) {\n\t\t\tATriplet.push_back(Eigen::Triplet<double>(it.row(), it.col(), it.value()));\n\t\t}\n\t}\n\n\tfor (int k = 0; k < C.outerSize(); ++k) {\n\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(C, k); it; ++it) {\n\t\t\tATriplet.push_back(Eigen::Triplet<double>(B2D.rows() + it.row(), it.col(), it.value()));\n\t\t\tATriplet.push_back(Eigen::Triplet<double>(it.col(), B2D.cols() + it.row(), it.value()));\n\t\t}\n\t}\n\tA_LHS.setFromTriplets(ATriplet.begin(), ATriplet.end());\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\tcout << \"in \" << duration.count() << \" seconds\" << endl;\n}\n\nvoid VectorFields::setupRHSGlobalProblemSoftConstraints(const double& lambda, Eigen::VectorXd& b)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt1 = chrono::high_resolution_clock::now();\n\tcout << \"> Setting up the RHS of the system... \";\n\n\tb = lambda * C.transpose() * c;\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\tcout << \"in \" << duration.count() << \" seconds\" << endl;\n}\n\nvoid VectorFields::setupLHSGlobalProblemSoftConstraints(const double& lambda, Eigen::SparseMatrix<double>& A_LHS)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt1 = chrono::high_resolution_clock::now();\n\tcout << \"> Setting up the LHS of the system... \";\n\n\t//A_LHS = SF2D + lambda*(C.transpose()*C);\n\tA_LHS = SF2D + lambda*C.transpose()*C;\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\tcout << \"in \" << duration.count() << \" seconds\" << endl;\n}\n\n\nvoid VectorFields::solveGlobalSystemMappedLDLT(Eigen::VectorXd& vEst, Eigen::SparseMatrix<double>& A_LHS, Eigen::VectorXd& b)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt1 = chrono::high_resolution_clock::now();\n\tcout << \"> Solving the global system (Pardiso LDLT)... \\n\";\n\n\n\t//cout << \"Starting to solve problem.\" << endl;\n\tXf.resize(B2D.rows());\n\t\n\t// Setting up the solver\n\t//Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> sparseSolver(A_LHS);\n\tEigen::PardisoLDLT<Eigen::SparseMatrix<double>> sparseSolver(A_LHS);\t\n\t//Eigen::PastixLDLT<Eigen::SparseMatrix<double>,1> sparseSolver(A_LHS);\n\n\t// FIRST BASIS\n\tcout << \"....Solving first problem (first frame)...\" << endl;\n\tEigen::VectorXd x = sparseSolver.solve(b);\n\t\n\tif (sparseSolver.info() != Eigen::Success) {\n\t\tcout << \"Cannot solve the linear system. \" << endl;\n\t\tif (sparseSolver.info() == Eigen::NumericalIssue)\n\t\t\tcout << \"NUMERICAL ISSUE. \" << endl;\n\t\tif(sparseSolver.info()==Eigen::InvalidInput)\n\t\t\tcout << \"Input is Invalid. \" << endl;\n\t\tcout << sparseSolver.info() << endl;\n\t\treturn;\n\t}\n\t\n\tXf = -x.block(0, 0, B2D.rows(), 1) + vEst;\n\n\tprintf(\"____Xf size is %dx%d\\n\", Xf.rows(), Xf.cols());\t\n\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\tcout << \"in \" << duration.count() << \" seconds\" << endl;\n}\n\nvoid VectorFields::solveGlobalSystemMappedLU_GPU(Eigen::VectorXd& vEst, Eigen::SparseMatrix<double>& A_LHS, Eigen::VectorXd& b)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt1 = chrono::high_resolution_clock::now();\n\tcout << \"> Solving the global system (LU in GPU)... \\n\";\n\n\t//cout << \"Starting to solve problem.\" << endl;\n\tXf.resize(B2D.rows());\n\n\tEigen::MatrixXd X;\n\tsolveLUinCUDA(A_LHS, b, X);\n\n\n\tXf.col(0) = -X.block(0, 0, B2D.rows(), 1) + vEst;\n\tXf.col(1) = -X.block(0, 1, B2D.rows(), 1) + vEst;\n\t//cout << Xf.block(0, 0, 100, 2) << endl; \n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\tcout << \"..in \" << duration.count() << \" seconds\" << endl;\n}\n\nvoid VectorFields::solveGlobalSystemMappedLDLTSoftConstraints(Eigen::SparseMatrix<double>& A_LHS, Eigen::VectorXd& b)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt1 = chrono::high_resolution_clock::now();\n\tcout << \"> Solving the global system (Pardiso LDLT)... \\n\";\n\n\t//cout << \"Starting to solve problem.\" << endl;\n\tXf.resize(B2D.rows());\n\n\t// Setting up the solver\n\t//Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> sparseSolver(A_LHS);\n\tEigen::PardisoLDLT<Eigen::SparseMatrix<double>> sparseSolver(A_LHS);\n\t//Eigen::PastixLDLT<Eigen::SparseMatrix<double>,1> sparseSolver(A_LHS);\n\n\t// FIRST BASIS\n\tcout << \"....Solving first problem (first frame)...\" << endl;\n\tEigen::VectorXd x = sparseSolver.solve(b);\n\n\tif (sparseSolver.info() != Eigen::Success) {\n\t\tcout << \"Cannot solve the linear system. \" << endl;\n\t\tif (sparseSolver.info() == Eigen::NumericalIssue)\n\t\t\tcout << \"NUMERICAL ISSUE. \" << endl;\n\t\tif (sparseSolver.info() == Eigen::InvalidInput)\n\t\t\tcout << \"Input is Invalid. \" << endl;\n\t\tcout << sparseSolver.info() << endl;\n\t\treturn;\n\t}\n\n\tXf = x;\n\n\tprintf(\"____Xf size is %dx%d\\n\", Xf.rows(), Xf.cols());\n\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\tcout << \"in \" << duration.count() << \" seconds\" << endl;\n}\n\n// RANK-2 TENSOR\nvoid VectorFields::constructMappingMatrix_TensorR2()\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt1 = chrono::high_resolution_clock::now();\n\tcout << \"> Constructing Mapping matrices (Global/World-Coord to Local Frame)... \";\n\n\n\tAT2R.resize(3 * F.rows(), 3 * F.rows());\n\tvector<Eigen::Triplet<double>> ATriplet;\n\tATriplet.reserve(3 * 3 * F.rows());\n\tEigen::Vector3d e, f, n;\n\tEigen::Vector3d eeT, efT, feT, efTfeT, ffT;\n\n\tfor (int i = 0; i < F.rows(); i++) {\n\t\t/* Computing the basic elements */\n\t\te = V.row(F(i, 1)) - V.row(F(i, 0));\n\t\te.normalize();\n\n\t\tn = NF.row(i);\n\t\tn.normalize();\n\n\t\tf = n.cross(e);\n\t\tf.normalize();\n\n\t\t/* Computing the values for tensor */\n\n\n\t\tATriplet.push_back(Eigen::Triplet<double>(3 * i + 0, 2 * i + 0, e(0)));\n\t\tATriplet.push_back(Eigen::Triplet<double>(3 * i + 1, 2 * i + 0, e(1)));\n\t\tATriplet.push_back(Eigen::Triplet<double>(3 * i + 2, 2 * i + 0, e(2)));\n\t\tATriplet.push_back(Eigen::Triplet<double>(3 * i + 0, 2 * i + 1, f(0)));\n\t\tATriplet.push_back(Eigen::Triplet<double>(3 * i + 1, 2 * i + 1, f(1)));\n\t\tATriplet.push_back(Eigen::Triplet<double>(3 * i + 2, 2 * i + 1, f(2)));\n\t}\n\n\tA.setFromTriplets(ATriplet.begin(), ATriplet.end());\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\tcout << \"in \" << duration.count() << \" seconds\" << endl;\n}\n\nvoid VectorFields::constructStiffnessMatrixSF2D_TensorR2(Eigen::SparseMatrix<double>& LapCurl3D, Eigen::SparseMatrix<double>& LapCurl2D, Eigen::SparseMatrix<double>& LapDiv3D, Eigen::SparseMatrix<double>& LapDiv2D)\n{\n\n}\n\nvoid VectorFields::constructStiffnessMatrixCurlPart2D_TensorR2(Eigen::SparseMatrix<double>& LapCurl3D, Eigen::SparseMatrix<double>& LapCurl2D)\n{\n\n}\n\nvoid VectorFields::constructStiffnessMatrixDivPart2D_TensorR2(Eigen::SparseMatrix<double>& LapDiv3D, Eigen::SparseMatrix<double>& LapDiv2D)\n{\n\n}\n\n// APPLICATIONS ON GLOBAL SYSTEM\nvoid VectorFields::computeSmoothing(const double& mu, const Eigen::VectorXd& v_in, Eigen::VectorXd& v_out)\n{\n\t/* First flavour */\n\t//Eigen::SparseMatrix<double> A = MF2D + mu*B2D;\n\tEigen::SparseMatrix<double> A = MF2D + mu*SF2D;\n\n\t/* Second flavour */\n\t//Eigen::SparseMatrix<double> A = MF2D + mu*SF2D*MF2Dinv*SF2D;\n\tEigen::VectorXd b = MF2D*v_in;\n\n\tEigen::PardisoLDLT<Eigen::SparseMatrix<double>> sparseSolver(A);\n\tv_out = sparseSolver.solve(b);\n\n\tdouble in_length = v_in.transpose()*MF2D*v_in;\n\tdouble out_length = v_out.transpose()*MF2D*v_out;\n\tcout << \"IN Length= \" << in_length << endl;\n\tcout << \"OUT length \" << out_length << endl; \n\t\n\n\t/* Computing the L2-norm of the smoothed fields */\n\tdouble diff1 = (v_out - v_in).transpose()*MF2D*(v_out - v_in);\n\tdouble diff2 = v_in.transpose()*MF2D*v_in;\n\tdouble sqrt_norm = sqrt(diff1 / diff2);\n\tprintf(\"The diff of v_out and v_in is %.10f \\n\", sqrt_norm);\n\n\t/* Computing the energy */\n\tdouble energy1 = v_in.transpose() * ((B2D) * v_in);\n\tdouble energy2 = v_out.transpose() * ((B2D) * v_out);\n\tprintf(\"The energy is=%.4f ==> %.4f.\\n\", energy1, energy2);\n}\n\nvoid VectorFields::constructSamples(const int &n)\n{\n\tnumSample = n; \n\n\tchrono::high_resolution_clock::time_point\tt1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\n\tt1 = chrono::high_resolution_clock::now();\n\tfarthestPointSampling();\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\n\tcout << \"> Constructing \" << n << \" samples in \" << duration.count() << \"seconds\" << endl;\n}\n\nvoid VectorFields::farthestPointSampling()\n{\n\tSample.resize(numSample);\n\tEigen::VectorXd D;\n\tD.resize(F.rows());\n\n\t// Initialize the value of D\n\tfor (int i = 0; i < F.rows(); i++) {\n\t\tD(i) = numeric_limits<double>::infinity();\n\t}\n\n\tsrand(time(NULL));\n\tSample[0] = rand() % F.rows();\n\t//Sample[0] = 0;\n\t//Sample[0] = 70267; // Arma 43k\n\t//Sample[0] = 5461;\t// For Armadilo of 10k vertices\n\n\t//computeDijkstraDistanceFaceForSampling(Sample[0], D);\n\t//Eigen::VectorXi::Index maxIndex1;\n\t//D.maxCoeff(&maxIndex1);\n\t//Sample[1] = maxIndex1;\n\n\tfor (int i = 1; i < numSample; i++) {\n\t\tEigen::VectorXi::Index maxIndex;\n\t\tcomputeDijkstraDistanceFaceForSampling(Sample[i-1], D);\n\t\tD.maxCoeff(&maxIndex);\n\t\tSample[i] = maxIndex;\n\t}\n\n\tsampleDistance = D; \n}\n\nvoid VectorFields::constructBasis()\n{\t\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt0, t1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt0 = chrono::high_resolution_clock::now();\n\tcout << \"> Constructing Basis...\\n\";\n\n\tdouble\tcoef = sqrt(pow(1.1, 2) + pow(1.3, 2));\n\tdouble distRatio = coef * sqrt((double)V.rows() / (double) Sample.size());\n\n\t// Setup sizes of each element to construct basis\n\ttry {\n\t\tBasisTemp.resize(2 * F.rows(), 2 * Sample.size());\n\t}\n\tcatch(string &msg) {\n\t\tcout << \"Cannot allocate memory for basis..\" << endl;\n\t}\n\t\n\tBasis.resize(BasisTemp.rows(), BasisTemp.cols());\n\tvector<vector<Eigen::Triplet<double>>> UiTriplet(Sample.size());\n\n\t\n\tcout << \"....Constructing and solving local systems...\";\n\tconst int NUM_PROCESS = 8;\n\tdurations.resize(NUM_PROCESS);\n\n\tfor (int i = 0; i < NUM_PROCESS; i++) {\n\t\tdurations[i] = t1 - t1;\n\t\t//cout << \"Init dur \" << i<< \" = \" << durations[i].count() << \" seconds\" << endl;\n\t}\n\t\n\tint id, tid, ntids, ipts, istart, iproc;\n\t\n\n#pragma omp parallel private(tid,ntids,ipts,istart,id)\t\n\t{\t\t\n\t\tiproc = omp_get_num_procs();\n\t\t//iproc = 1; \n\t\ttid\t\t= omp_get_thread_num();\n\t\tntids\t= omp_get_num_threads();\n\t\tipts\t= (int)ceil(1.00*(double)Sample.size() / (double)ntids);\n\t\tistart\t= tid * ipts;\n\t\tif (tid == ntids - 1) ipts = Sample.size() - istart;\n\t\tif (ipts <= 0) ipts = 0;\n\n\t\tEigen::VectorXd\t\t\t\tD(F.rows());\n\t\tfor (int i = 0; i < F.rows(); i++) {\n\t\t\tD(i) = numeric_limits<double>::infinity();\n\t\t}\n\t\t\n\t\t//cout << \"[\" << tid << \"] Number of processors \" << iproc << \", with \" << ntids << \" threads.\" << endl;\n\n\t\tUiTriplet[tid].reserve(2.0 * ((double)ipts / (double)Sample.size()) * 2 * 10.0 * F.rows());\n\n\t\t// Computing the values of each element\n\t\tfor (id = istart; id < (istart + ipts); id++) {\n\t\t\tif (id >= Sample.size()) break;\n\n\t\t\tvector<Eigen::Triplet<double>> BTriplet, C1Triplet, C2Triplet;\n\n\t\t\tLocalFields localField(id);\n\t\t\t\tt1 = chrono::high_resolution_clock::now();\n\t\t\tlocalField.constructSubdomain(Sample[id], V, F, avgEdgeLength, AdjMF3N, distRatio);\n\t\t\t\tt2 = chrono::high_resolution_clock::now();\n\t\t\t\tdurations[0] += t2 - t1;\n\n\t\t\t\tt1 = chrono::high_resolution_clock::now();\n\t\t\tlocalField.constructBoundary(F, AdjMF3N, AdjMF2Ring);\n\t\t\t\tt2 = chrono::high_resolution_clock::now();\n\t\t\t\tdurations[1] += t2 - t1;\n\n\t\t\t\tt1 = chrono::high_resolution_clock::now();\n\t\t\tlocalField.constructLocalElements(F);\n\t\t\t\tt2 = chrono::high_resolution_clock::now();\n\t\t\t\tdurations[2] += t2 - t1;\n\n\t\t\t\tt1 = chrono::high_resolution_clock::now();\n\t\t\t\t//localField.constructMatrixBLocal(B2D);\n\t\t\t\t//localField.constructMatrixBLocal(B2D, AdjMF2Ring);\n\t\t\t\tlocalField.constructMatrixBLocal(B2D, AdjMF2Ring, BTriplet);\t\t\t\n\t\t\t\tt2 = chrono::high_resolution_clock::now();\n\t\t\t\tdurations[3] += t2 - t1;\n\n\t\t\t\tt1 = chrono::high_resolution_clock::now();\n\t\t\t\tlocalField.constructLocalConstraints(C1Triplet, C2Triplet);\n\t\t\t\t//localField.constructLocalConstraintsWithLaplacian(doubleArea, AdjMF3N, SF2D, C1Triplet, C2Triplet);\n\t\t\t\tt2 = chrono::high_resolution_clock::now();\n\t\t\t\tdurations[4] += t2 - t1;\n\n\t\t\t\tt1 = chrono::high_resolution_clock::now();\n\t\t\tlocalField.setupRHSLocalProblemMapped();\n\t\t\t\tt2 = chrono::high_resolution_clock::now();\n\t\t\t\tdurations[5] += t2 - t1;\n\n\t\t\t\tt1 = chrono::high_resolution_clock::now();\n\t\t\tlocalField.setupLHSLocalProblemMapped(BTriplet, C1Triplet, C2Triplet);\n\t\t\t\tt2 = chrono::high_resolution_clock::now();\n\t\t\t\tdurations[6] += t2 - t1;\n\n\t\t\t\tlocalField.computeDijkstraFaceDistance(V, F, FC, AdjMF3N);\n\n\t\t\t\tt1 = chrono::high_resolution_clock::now();\n\t\t\tlocalField.solveLocalSystemMappedLDLT(UiTriplet[id]);\n\t\t\t\tt2 = chrono::high_resolution_clock::now();\n\t\t\t\tdurations[7] += t2 - t1;\n\t\t\t\n\t\t\t\t//localField.measureXF(doubleArea, J);\n\n\t\t\t\tif (id == 0)\n\t\t\t\t{\n\t\t\t\t\tSubDomain = localField.SubDomain;\n\t\t\t\t\tBoundary = localField.Boundary;\n\t\t\t\t\t//patchDijkstraDist = localField.dijksFaceDistMapped; \n\t\t\t\t}\n\t\t}\n\n\t}\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t0;\n\tcout << \"in \" << duration.count() << \" seconds.\" << endl; \n\n\tcout << \"....Gathering local elements as basis matrix... \";\n\tt1 = chrono::high_resolution_clock::now();\n\tgatherBasisElements(UiTriplet);\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\tcout << \"in \" << duration.count() << \" seconds\" << endl;\n\t\n\tcout << \"....Partition of unity of the basis matrix... \";\n\tt1 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\t//normalizeBasis();\n\tnormalizeBasisAbs();\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\tcout << \"in \" << duration.count() << \" seconds\" << endl;\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t0;\n\tcout << \"..in Total of \" << duration.count() << \" seconds\" << endl;\n\n\t//for (int i = 0; i < NUM_PROCESS; i++) {\n\t\t//printf(\"Process %d takes %.8f seconds.\\n\", i, durations[i].count());\n\t\t//cout << \"BasisTemp matrix is normalized in \" << duration.count() << \" seconds\" << endl;\n\t//}\n\n\t// Information about the process timing\n\tprintf(\"> Basis Timing information \\n\");\n\tprintf(\"....[0] Constructing internal elements: %.8f seconds.\\n\", durations[0].count());\n\tprintf(\"....[1] Constructing boundary: %.8f seconds.\\n\", durations[1].count());\n\tprintf(\"....[2] Constructing local subdomains: %.8f seconds.\\n\", durations[2].count());\n\tprintf(\"....[3] Constructing matrix B local: %.8f seconds.\\n\", durations[3].count());\n\tprintf(\"....[4] Constructing local constraints: %.8f seconds.\\n\", durations[4].count());\n\tprintf(\"....[5] Constructing RHS (mapped): %.8f seconds.\\n\", durations[5].count());\n\tprintf(\"....[6] Constructing LHS (mapped): %.8f seconds.\\n\", durations[6].count());\n\tprintf(\"....[7] Solving local systems (mapped, Pardiso LDLT): %.8f seconds.\\n\", durations[7].count());\n\n\t// Information about Basis\n\tprintf(\"> Basis Structure information \\n\");\n\tprintf(\"....Size = %dx%d\\n\", Basis.rows(), Basis.cols());\n\tprintf(\"....NNZ per row = %.2f\\n\", (double) Basis.nonZeros() / (double) Basis.rows());\n}\n\nvoid VectorFields::gatherBasisElements(const vector<vector<Eigen::Triplet<double>>> &UiTriplet)\n{\n\tvector<Eigen::Triplet<double>> BTriplet;\n\tBasisSum.resize(2 * F.rows(), 2);\n\tfor (int i = 0; i < BasisSum.rows(); i++) {\n\t\tBasisSum(i, 0) = 0.0;\n\t\tBasisSum(i, 1) = 0.0;\n\t}\n\n\tint totalElements = 0;\n\tfor (int j = 0; j < Sample.size(); j++) {\n\t\ttotalElements += UiTriplet[j].size();\n\t}\n\n\tBTriplet.resize(totalElements);\n\tfor (int j = 0; j < Sample.size(); j++) {\n\t\tint tripSize = 0;\n\t\tfor (int k = 0; k < j; k++) {\n\t\t\ttripSize += UiTriplet[k].size();\n\t\t}\n\t\tstd::copy(UiTriplet[j].begin(), UiTriplet[j].end(), BTriplet.begin() + tripSize);\n\t}\n\tBasisTemp.setFromTriplets(BTriplet.begin(), BTriplet.end());\n\n\t//printf(\"A basis matrix (%dx%d) is constructed.\\n\", BasisTemp.rows(), BasisTemp.cols());\n\n\tfor (int k = 0; k < BasisTemp.outerSize(); ++k) {\n\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(BasisTemp, k); it; ++it) {\n\t\t\tBasisSum(it.row(), it.col() % 2) += it.value();\n\t\t}\n\t}\n\n}\n\nvoid VectorFields::normalizeBasis()\n{\n\tEigen::MatrixXd BasisSum(BasisTemp.rows(), 2);\n\tBasisSumN.resize(BasisTemp.rows(), 2);\n\tEigen::MatrixXd normSum(BasisTemp.rows(), 2);\n\tEigen::MatrixXd BasisNorm(F.rows(), 2);\n\tEigen::MatrixXi nonZeros(BasisTemp.rows(), 2);\n\t\tfor (int i = 0; i < nonZeros.rows(); i++) {\n\t\t\tfor (int j = 0; j < nonZeros.cols(); j++) {\n\t\t\t\tnonZeros(i, j) = 0;\n\t\t\t\tBasisSum(i, j) = 0.0;\n\t\t\t\tBasisSumN(i, j) = 0.0;\n\t\t\t}\n\t\t}\n\tvector<Eigen::Triplet<double>> BNTriplet;\n\tBNTriplet.reserve(BasisTemp.nonZeros());\n\n\t// Getting the sum of each pair on each frame AND\n\t// Counting the non-zeros per rows\n\tfor (int k = 0; k < BasisTemp.outerSize(); ++k) {\n\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(BasisTemp, k); it; ++it) {\n\t\t\tBasisSum(it.row(), it.col() % 2) += it.value();\n\t\t\tnonZeros(it.row(), it.col() % 2) += 1;\n\t\t}\n\t}\n\t\n\t// Computing the norm\n\tfor (int i = 0; i < F.rows(); i++) {\n\t\tdouble frame1Norm, frame2Norm, a,b;\n\t\ta = BasisSum(2 * i + 0, 0);\n\t\tb = BasisSum(2 * i + 1, 0);\n\t\tframe1Norm = sqrt(a*a + b*b);\n\n\t\ta = BasisSum(2 * i + 0, 1);\n\t\tb = BasisSum(2 * i + 1, 1);\n\t\tframe2Norm = sqrt(a*a + b*b);\n\n\t\tBasisNorm(i, 0) = frame1Norm;\n\t\tBasisNorm(i, 1) = frame2Norm;\t\t\n\t}\n\n\t// Constructing normalized basis each element of basis\n\tfor (int k = 0; k < BasisTemp.outerSize(); ++k) {\n\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(BasisTemp, k); it; ++it) {\n\t\t\t//double newValue = it.value() / BasisNorm(it.row() / 2, it.col() % 2);\n\t\t\tdouble newValue = it.value();\n\t\t\tBNTriplet.push_back(Eigen::Triplet<double>(it.row(), it.col(), newValue));\n\t\t}\n\t}\n\tBasis.setFromTriplets(BNTriplet.begin(), BNTriplet.end());\t\n\n\t// Check Normalization\n\t// Getting the sum of each pair on each frame\n\tfor (int k = 0; k < Basis.outerSize(); ++k) {\t\t\n\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(Basis, k); it; ++it) {\n\t\t\tBasisSumN(it.row(), it.col() % 2) += it.value();\n\t\t}\n\t}\n\n\t// Computing the norm\n\tfor (int i = 0; i < F.rows(); i++) {\n\t\tdouble frame1Norm, frame2Norm, a, b;\n\t\ta = BasisSumN(2 * i + 0, 0);\n\t\tb = BasisSumN(2 * i + 1, 0);\n\t\tframe1Norm = sqrt(a*a + b*b);\n\n\t\ta = BasisSumN(2 * i + 0, 1);\n\t\tb = BasisSumN(2 * i + 1, 1);\n\t\tframe2Norm = sqrt(a*a + b*b);\n\n\t\tBasisNorm(i, 0) = frame1Norm;\n\t\tBasisNorm(i, 1) = frame2Norm;\n\t}\n\t\n\t// Show result (The sum=> should all be equal to 1\n\t//for (int i = 0; i < F.rows(); i++) {\n\t//\tprintf(\"[%.6f][%.6f]\\n\", BasisSumN.block(2*i,0,2,1).norm(), BasisSumN.block(2 * i, 1, 2, 1).norm());\n\t//}\n\n\tint numNonZeroes = Basis.nonZeros();\n\tint numElements = Basis.rows();\n\t//cout << \"Average non-zeros is \" << (double)numNonZeroes / (double)numElements << endl; \n}\n\n//void VectorFields::normalizeBasisAbs()\n//{\n//\tEigen::MatrixXd BasisSum(BasisTemp.rows(), 2);\n//\tBasisSumN.resize(BasisTemp.rows(), 2);\n//\tEigen::MatrixXd normSum(BasisTemp.rows(), 2);\n//\tEigen::MatrixXd BasisNorm(F.rows(), 2);\n//\tEigen::MatrixXi nonZeros(BasisTemp.rows(), 2);\n//\tfor (int i = 0; i < nonZeros.rows(); i++) {\n//\t\tfor (int j = 0; j < nonZeros.cols(); j++) {\n//\t\t\tnonZeros(i, j) = 0;\n//\t\t\tBasisSum(i, j) = 0.0;\n//\t\t\tBasisSumN(i, j) = 0.0;\n//\t\t}\n//\t}\n//\tvector<Eigen::Triplet<double>> BNTriplet;\n//\n//\n//\t// Getting the sum of each pair on each frame AND\n//\t// Counting the non-zeros per rows\n//\tfor (int k = 0; k < BasisTemp.outerSize(); ++k) {\n//\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(BasisTemp, k); it; ++it) {\n//\t\t\tBasisSum(it.row(), it.col() % 2) += abs(it.value());\n//\t\t\tnonZeros(it.row(), it.col() % 2) += 1;\n//\t\t}\n//\t}\n//\n//\t// Computing the norm\n//\tfor (int i = 0; i < F.rows(); i++) {\n//\t\tdouble frame1Norm, frame2Norm, a, b;\n//\t\ta = BasisSum(2 * i + 0, 0);\n//\t\tb = BasisSum(2 * i + 1, 0);\n//\t\tframe1Norm = sqrt(a*a + b*b);\n//\n//\t\ta = BasisSum(2 * i + 0, 1);\n//\t\tb = BasisSum(2 * i + 1, 1);\n//\t\tframe2Norm = sqrt(a*a + b*b);\n//\n//\t\tBasisNorm(i, 0) = frame1Norm;\n//\t\tBasisNorm(i, 1) = frame2Norm;\n//\t}\n//\n//\t// Constructing normalized basis each element of basis\n//\tfor (int k = 0; k < BasisTemp.outerSize(); ++k) {\n//\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(BasisTemp, k); it; ++it) {\n//\t\t\tdouble newValue = it.value() / BasisNorm(it.row() / 2, it.col() % 2);\n//\t\t\t//double newValue = it.value();\n//\t\t\tBNTriplet.push_back(Eigen::Triplet<double>(it.row(), it.col(), newValue));\n//\t\t}\n//\t}\n//\tBasis.setFromTriplets(BNTriplet.begin(), BNTriplet.end());\n//\n//\t// Check Normalization\n//\t// Getting the sum of each pair on each frame\n//\tfor (int k = 0; k < Basis.outerSize(); ++k) {\n//\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(Basis, k); it; ++it) {\n//\t\t\tBasisSumN(it.row(), it.col() % 2) += it.value();\n//\t\t}\n//\t}\n//\n//\t// Computing the norm\n//\tfor (int i = 0; i < F.rows(); i++) {\n//\t\tdouble frame1Norm, frame2Norm, a, b;\n//\t\ta = BasisSumN(2 * i + 0, 0);\n//\t\tb = BasisSumN(2 * i + 1, 0);\n//\t\tframe1Norm = sqrt(a*a + b*b);\n//\n//\t\ta = BasisSumN(2 * i + 0, 1);\n//\t\tb = BasisSumN(2 * i + 1, 1);\n//\t\tframe2Norm = sqrt(a*a + b*b);\n//\n//\t\tBasisNorm(i, 0) = frame1Norm;\n//\t\tBasisNorm(i, 1) = frame2Norm;\n//\t}\n//\n//\t// Show result (The sum=> should all be equal to 1\n//\t//for (int i = 0; i < F.rows(); i++) {\n//\t//\tprintf(\"[%.6f][%.6f]\\n\", BasisSumN.block(2*i,0,2,1).norm(), BasisSumN.block(2 * i, 1, 2, 1).norm());\n//\t//}\n//\n//\tint numNonZeroes = Basis.nonZeros();\n//\tint numElements = Basis.rows();\n//\tcout << \"Average non-zeros is \" << (double)numNonZeroes / (double)numElements << endl;\n//}\n\nvoid VectorFields::normalizeBasisAbs()\n{\n\tEigen::MatrixXd normSum(F.rows(), 2), normSumN(F.rows(), 2);\n\tBasisSumN.resize(BasisTemp.rows(), 2);\n\tvector<Eigen::Triplet<double>> BNTriplet;\n\tBNTriplet.reserve(BasisTemp.nonZeros());\n\n\tEigen::MatrixXd BasisNorm(F.rows(), 2);\n\n\tfor (int i = 0; i < normSum.rows(); i++) {\n\t\tfor (int j = 0; j < normSum.cols(); j++) {\n\t\t\tnormSum(i, j) = 0.0;\n\t\t\t//normSumN(i, j) = 0.0;\n\t\t\t//BasisSumN(2 * i + 0, j) = 0.0;\n\t\t\t//BasisSumN(2 * i + 1, j) = 0.0;\n\t\t}\n\t}\n\n\t// Getting the sum of norm on each pair on each frame \n\tfor (int k = 0; k < BasisTemp.outerSize(); ++k) {\n\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(BasisTemp, k); it; ++it) {\n\t\t\tif (it.row() % 2 == 1) continue;\n\n\t\t\tdouble a = it.value();\n\t\t\tdouble b = BasisTemp.coeff(it.row() + 1, it.col());\n\t\t\tdouble norm = sqrt(a*a + b*b);\n\t\t\tnormSum(it.row() / 2, it.col() % 2) += norm;\n\t\t}\n\t}\n\n\t\n\t// Normalize the system\n\tfor (int k = 0; k < BasisTemp.outerSize(); ++k) {\n\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(BasisTemp, k); it; ++it) {\n\t\t\tdouble newValue = it.value() / normSum(it.row()/2, it.col()%2);\n\t\t\tnewValue *= (2.0);\n\t\t\t// To have the basis with norm 2.0\n\t\t\tBNTriplet.push_back(Eigen::Triplet<double>(it.row(), it.col(), newValue));\n\t\t\tBasisSumN(it.row(), it.col() % 2) += newValue;\n\t\t}\n\t}\t\n\n\tBasis.setFromTriplets(BNTriplet.begin(), BNTriplet.end());\t\n\n\t//for (int k = 0; k < Basis.outerSize(); ++k) {\n\t//\tfor (Eigen::SparseMatrix<double>::InnerIterator it(Basis, k); it; ++it) {\n\t//\t\tif (it.row() % 2 == 1) continue;\n\t//\n\t//\t\tdouble a = it.value();\n\t//\t\tdouble b = Basis.coeff(it.row() + 1, it.col());\n\t//\t\tdouble norm = sqrt(a*a + b*b);\n\t//\t\tnormSumN(it.row() / 2, it.col() % 2) += norm;\n\t//\t}\n\t//}\n\n\t//for (int k = 0; k < 100; k++) {\n\t//\tprintf(\"--> [%d]=<%.4f,%.4f>\\n\", k, normSumN(k, 0), normSumN(k, 1));\n\t//\tif (k % 2 == 1) continue; \n\t//}\n}\nvoid VectorFields::setAndSolveUserSystem()\n{\n\t// Declare function-scoped variables\n\tEigen::VectorXd\t\t\t\t\tbBar, gBar, hBar, vEstBar;\n\tEigen::SparseMatrix<double>\t\tA_LHSBar;\n\tconst double lambda = 0.4; \n\n\t//setupReducedBiLaplacian();\n\tgetUserConstraints();\n\tsetupRHSUserProblemMapped(gBar, hBar, vEstBar, bBar);\n\tsetupLHSUserProblemMapped(A_LHSBar);\n\tsolveUserSystemMappedLDLT(vEstBar, A_LHSBar, bBar);\n\t//setupRHSUserProblemMappedSoftConstraints(lambda, bBar);\n\t//setupLHSUserProblemMappedSoftConstraints(lambda, A_LHSBar);\n\t//solveUserSystemMappedLDLTSoftConstraints(A_LHSBar, bBar);\n\n\tmapSolutionToFullRes();\n}\n\nvoid VectorFields::setupReducedBiLaplacian()\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt0, t1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt0 = chrono::high_resolution_clock::now();\n\tcout << \"> Computign Reduced Bi-Laplacian...\";\n\n\tB2DBar = Basis.transpose() * B2D * Basis; \n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t0;\n\tcout << \"in \" << duration.count() << \" seconds.\" << endl;\n\tprintf(\".... Local Basis = %dx%d\\n\", B2DBar.rows(), B2DBar.cols());\n\n\t/* Getting the information about nonzeros */\n\tdouble nnz_num = (double)B2DBar.nonZeros() / (double)B2DBar.rows();\n\tdouble nnz_perc = nnz_num / (double)B2DBar.cols();\n\tprintf(\".... NNZ per row = %.2f\\n\", nnz_num);\n\tprintf(\".... Percentage of NNZ = %.20f \\n\", nnz_perc*100);\n\n}\nvoid VectorFields::getUserConstraints()\n{\t\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt0, t1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt0 = chrono::high_resolution_clock::now();\n\tcout << \"> Obtaining user constraints \";\n\n\tconstructConstraints();\n\n\tuserConstraints = globalConstraints; \n\tCBar\t\t\t= C * Basis;\n\tcBar\t\t\t= c;\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t0;\n\tcout << \"in \" << duration.count() << \" seconds.\" << endl;\n\n\tprintf(\".... C_Lobal = %dx%d\\n\", CBar.rows(), CBar.cols());\n\tprintf(\".... c_Lobal = %dx%d\\n\", cBar.rows(), cBar.cols());\n}\n\nvoid VectorFields::setupRHSUserProblemMapped(Eigen::VectorXd& gBar, Eigen::VectorXd& hBar, Eigen::VectorXd& vEstBar, Eigen::VectorXd& bBar)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt0, t1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt0 = chrono::high_resolution_clock::now();\n\tcout << \"> Constructing RHS (mapped)...\";\n\t\n\tvEstBar.resize(B2DBar.rows());\n\tfor (int i = 0; i < vEstBar.rows(); i++) {\n\t\tvEstBar(i) = 0.5;\n\t}\n\n\tgBar = B2DBar * vEstBar;\n\tbBar.resize(B2DBar.rows() + cBar.rows());\n\n\t// Constructing b\n\thBar = CBar * vEstBar - cBar;\n\tbBar<< gBar, hBar;\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t0;\n\tcout << \"in \" << duration.count() << \" seconds.\" << endl;\n}\n\nvoid VectorFields::setupLHSUserProblemMapped(Eigen::SparseMatrix<double>& A_LHSBar)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt0, t1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt0 = chrono::high_resolution_clock::now();\n\tcout << \"> Constructing LHS (mapped)...\";\n\n\n\tA_LHSBar.resize(B2DBar.rows() + CBar.rows(), B2DBar.cols() + CBar.rows());\n\tvector<Eigen::Triplet<double>>\tATriplet;\n\tATriplet.reserve(B2DBar.nonZeros() + 2 * CBar.nonZeros());\n\n\tfor (int k = 0; k < B2DBar.outerSize(); ++k) {\n\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(B2DBar, k); it; ++it) {\n\t\t\tATriplet.push_back(Eigen::Triplet<double>(it.row(), it.col(), it.value()));\n\t\t}\n\t}\n\n\tfor (int k = 0; k < CBar.outerSize(); ++k) {\n\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(CBar, k); it; ++it) {\n\t\t\tATriplet.push_back(Eigen::Triplet<double>(B2DBar.rows() + it.row(), it.col(), it.value()));\n\t\t\tATriplet.push_back(Eigen::Triplet<double>(it.col(), B2DBar.cols() + it.row(), it.value()));\n\t\t}\n\t}\n\tA_LHSBar.setFromTriplets(ATriplet.begin(), ATriplet.end());\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t0;\n\tcout << \"in \" << duration.count() << \" seconds.\" << endl;\n\tprintf(\"....Local LHS = %dx%d\\n\", A_LHSBar.rows(), A_LHSBar.cols());\n}\n\nvoid VectorFields::setupRHSUserProblemMappedSoftConstraints(const double& lambda, Eigen::VectorXd& bBar)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt0, t1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt0 = chrono::high_resolution_clock::now();\n\tcout << \"> Constructing RHS (mapped)...\";\n\n\tbBar = lambda*CBar.transpose() * cBar; \n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t0;\n\tcout << \"in \" << duration.count() << \" seconds.\" << endl;\n}\n\nvoid VectorFields::setupLHSUserProblemMappedSoftConstraints(const double& lambda, Eigen::SparseMatrix<double>& A_LHSBar)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt0, t1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt0 = chrono::high_resolution_clock::now();\n\tcout << \"> Constructing LHS (mapped)...\";\n\n\tEigen::SparseMatrix<double> SF2DBar = Basis.transpose() * SF2D * Basis; \n\t//A_LHSBar = SF2DBar + lambda*CBar.transpose()*CBar; \n\tA_LHSBar = SF2DBar + lambda*CBar.transpose()*CBar;\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t0;\n\tcout << \"in \" << duration.count() << \" seconds.\" << endl;\n}\n\nvoid VectorFields::solveUserSystemMappedLDLT(Eigen::VectorXd& vEstBar, Eigen::SparseMatrix<double>& A_LHSBar, Eigen::VectorXd& bBar)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt0, t1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt0 = chrono::high_resolution_clock::now();\n\tcout << \"> Solving reduced system...\\n\";\n\n\tXLowDim.resize(B2DBar.rows());\n\tXFullDim.resize(Basis.rows());\n\tEigen::SimplicialLDLT<Eigen::SparseMatrix<double>> sparseSolver(A_LHSBar);\n\n\tcout << \"....Solving for the first frame.\\n\";\n\tEigen::VectorXd x = sparseSolver.solve(bBar);\n\n\tif (sparseSolver.info() != Eigen::Success) {\n\t\tcout << \"Cannot solve the linear system. \" << endl;\n\t\tif (sparseSolver.info() == Eigen::NumericalIssue)\n\t\t\tcout << \"NUMERICAL ISSUE. \" << endl;\n\t\tcout << sparseSolver.info() << endl;\n\t\treturn;\n\t}\n\n\tXLowDim.col(0) = -x.block(0, 0, B2DBar.rows(), 1) + vEstBar;\t\n\t\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t0;\n\tcout << \"..in Total of \" << duration.count() << \" seconds.\" << endl;\n\n\t//cout << \"Solution (LowDim) \\n\" << XLowDim << endl; \t\n}\n\nvoid VectorFields::solveUserSystemMappedLDLTSoftConstraints(Eigen::SparseMatrix<double>& A_LHSBar, Eigen::VectorXd& bBar)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt0, t1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt0 = chrono::high_resolution_clock::now();\n\tcout << \"> Solving reduced system...\\n\";\n\n\t//XLowDim.resize(B2DBar.rows());\n\t//XFullDim.resize(Basis.rows());\n\tEigen::SimplicialLDLT<Eigen::SparseMatrix<double>> sparseSolver(A_LHSBar);\n\n\tcout << \"....Solving for the first frame.\\n\";\n\tEigen::VectorXd x = sparseSolver.solve(bBar);\n\n\tif (sparseSolver.info() != Eigen::Success) {\n\t\tcout << \"Cannot solve the linear system. \" << endl;\n\t\tif (sparseSolver.info() == Eigen::NumericalIssue)\n\t\t\tcout << \"NUMERICAL ISSUE. \" << endl;\n\t\tcout << sparseSolver.info() << endl;\n\t\treturn;\n\t}\n\n\tXLowDim = x; \n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t0;\n\tcout << \"..in Total of \" << duration.count() << \" seconds.\" << endl;\n}\n\nvoid VectorFields::mapSolutionToFullRes()\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt0, t1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt0 = chrono::high_resolution_clock::now();\n\tcout << \"> Mapping to full-resolution...\";\n\n\tXFullDim = Basis * XLowDim;\n\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t0;\n\tcout << \" in \" << duration.count() << \" seconds.\" << endl;\n\n\tprintf(\"....XFull (%dx%d) =  Basis (%dx%d) * XLowDim (%dx%d) \\n\", XFullDim.rows(), XFullDim.cols(), Basis.rows(), Basis.cols(), XLowDim.rows(), XLowDim.cols());\n}\n\nvoid VectorFields::obtainUserVectorFields()\n{\n\tcout << \"Hello there \\n\" << endl; \n}\n\nvoid VectorFields::measureApproxAccuracyL2Norm()\n{\n\tEigen::VectorXd diffV = Xf - XFullDim;\n\tdouble xf = Xf.transpose() * MF2D * Xf;\n\tdouble diff = diffV.transpose() * MF2D * diffV;\n\tconst double L2norm = sqrt(diff / xf);\n\n\tprintf(\"Diff 0 = %.10f (%.4f / %.4f) \\n\", L2norm, diff, xf); \t\n\tprintf(\"Max Error = %.3f \\n\", diffV.maxCoeff() / xf);\n\tprintf(\"MSE = %.3f \\n\", (diffV.sum()/diffV.size()) / xf);\n}\n\nvoid VectorFields::measureDirichletEnergy()\n{\n\tdouble dirichlet = Xf.transpose() * ((B2D * MF2D) * Xf);\n\tcout << \"__Dirichlet Energy\\n \\t__FullRes: \" << dirichlet; \n\tdirichlet = XFullDim.transpose() * ((B2D * MF2D) * XFullDim); \n\tcout << \": Reduced: \" << dirichlet << endl; \n\n}\n\nvoid VectorFields::measureU1andJU0()\n{\n\t//Eigen::VectorXd JXf0 = J*BasisTemp.col(0);\n\t//Eigen::VectorXd diff = Eigen::VectorXd(BasisTemp.col(1)) - JXf0;\n\t//\n\t//double norm1 = JXf0.transpose() * MF2D * JXf0;\n\t//double norm2 = diff.transpose()* MF2D * diff; \n\t//double diffNorm = sqrt(norm2 / norm1);\n\t//cout << \"_____|Xf(1)-J*Xf(0)|M = \" << diffNorm << endl; \n}\n\n/* ====================== APPLICATIONS ON REDUCED SYSTEM ============================*/\nvoid VectorFields::computeSmoothingApprox(const double& mu, const Eigen::VectorXd& v_in, Eigen::VectorXd& v_out)\n{\n\t/* Reduced Matrices */\n\tEigen::SparseMatrix<double> MF2DBar = (Basis.transpose()*MF2D)*Basis; \n\tEigen::SparseMatrix<double> SF2DBar = (Basis.transpose()*SF2D)*Basis;\n\tEigen::VectorXd v_inBar = Basis.transpose()*v_in;\n\tEigen::VectorXd v_outBar;\n\tcout << \"The reduced matrices are set up\\n\"; \n\t/* First flavour */\n\tEigen::SparseMatrix<double> AL = MF2DBar + mu*SF2DBar ;\n\n\t/* Second flavour */\n\t//Eigen::SparseMatrix<double> A = MF2DBar + mu*SF2DBar*(Basis.transpose()*MF2Dinv*Basis)*SF2DBar;\n\tEigen::VectorXd b = MF2DBar*v_inBar;\n\n\tEigen::PardisoLDLT<Eigen::SparseMatrix<double>> sparseSolver(AL);\n\tv_outBar = sparseSolver.solve(b);\n\tv_out = Basis*v_outBar;\n\tcout << \"VOUT \\n\" << v_out.block(0, 0, 100, 1) << endl; \n\n\t/* Computing the L2-norm of the smoothed fields w.r.t input*/\n\tdouble diff1 = (v_out - v_in).transpose()*MF2D*(v_out - v_in);\n\tdouble diff2 = v_in.transpose()*MF2D*v_in;\n\tdouble sqrt_norm = sqrt(diff1 / diff2);\n\tprintf(\"The diff of v_out and v_in is %.10f \\n\", sqrt_norm);\n\n\t/* Computing the energy */\n\tdouble energy1 = v_in.transpose() * ((B2D * MF2D) * v_in);\n\tdouble energy2 = v_out.transpose() * ((B2D * MF2D) * v_out);\n\tprintf(\"The energy is=%.4f ==> %.4f.\\n\", energy1, energy2);\n}\n\nvoid VectorFields::ConstructCurvatureTensor(igl::opengl::glfw::Viewer &viewer)\n{\n\tcout << \"Constructing curvature tensor \\n\";\n\tcout << \"__Computing vertex normal\\n\";\n\t/* Getting normals on each vertex */\n\tEigen::MatrixXd NV;\n\tigl::per_vertex_normals(V, F, NV);\n\n\t/* Declare local variable for the loop here, to avoid excessive allocation (constructor) + de-allocation (destructor) */\n\tdouble f2Form1, f2Form2, f2Form3;\n\tEigen::Vector3d t1, t2, t3, e1, e2, e3, n1, n2, n3, nTemp, nT; \n\tEigen::Matrix3d m1, m2, m3, mT;\n\tEigen::Matrix2d mT2D;\n\tCurvatureTensor2D.resize(2 * F.rows(), 2 * F.rows());\n\tCurvatureTensor2D.reserve(2 * 2 * F.rows());\t\t\t// 2*F rows, each with 2 non-zero entries\n\tvector<Eigen::Triplet<double>> CTriplet;\n\tCTriplet.reserve(2 * 2 * F.rows());\t\t\t\t\t\t// 2*F rows, each with 2 non-zero entries\n\tconst double scale = 0.2 * avgEdgeLength; \n\n\tcout << \"__Computing curvature tensor\\n\";\n\t/* Loop over all faces */\n\tfor (int i = 0; i < F.rows(); i++)\n\t{\n\t\t/* Getting the edges */\n\t\te1 = (V.row(F(i, 1)) - V.row(F(i, 0))).transpose();\n\t\te2 = (V.row(F(i, 2)) - V.row(F(i, 1))).transpose();\n\t\te3 = (V.row(F(i, 0)) - V.row(F(i, 2))).transpose();\n\n\t\t/* Getting the rotated edge (CW, 90, on triangle plane->uses triangle normal)*/\n\t\tnT = (NF.row(i)).transpose();\n\t\tnT.normalize();\n\t\tt1 = e1.cross(nT);\n\t\tt2 = e2.cross(nT);\n\t\tt3 = e3.cross(nT);\n\t\t\t\t\n\t\t/* Getting normals for each edge center (average of two vertices) */\n\t\t/* NOT THE MOST Efficient implementation */\n\t\t\t/* Get the first neighbor's normal*/\n\t\tfor (int j = 0; j < F.cols(); j++)\t\t// Loop over 3 neighbors of i-th face\n\t\t{\n\t\t\tint neigh = AdjMF3N(i, j);\n\t\t\tfor (int k = 0; k < F.cols(); k++)\t// Loop over 3 vertices of the j-th neighbor\n\t\t\t{\n\t\t\t\tif (F(i, 0) == F(neigh, (k + 1) % F.cols()) && F(i, 1) == F(neigh, k))\n\t\t\t\t{\n\t\t\t\t\tnTemp = (NF.row(neigh)).transpose();\n\t\t\t\t\tnTemp.normalize();\n\t\t\t\t\tn1 = nT + nTemp;\n\t\t\t\t\tn1.normalize();\n\t\t\t\t\t//printf(\"____ The 1st edge: %d->%d to Triangle %d (%d, %d, %d)\\n\", F(i, 0), F(i, 1), neigh, F(neigh, 0), F(neigh, 1), F(neigh, 2));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\t/* Get the second neighbor's normal*/\n\t\tfor (int j = 0; j < F.cols(); j++)\t\t// Loop over 3 neighbors of i-th face\n\t\t{\n\t\t\tint neigh = AdjMF3N(i, j);\n\t\t\tfor (int k = 0; k < F.cols(); k++)\t// Loop over 3 vertices of the j-th neighbor\n\t\t\t{\n\t\t\t\tif (F(i, 1) == F(neigh, (k + 1) % F.cols()) && F(i, 2) == F(neigh, k))\n\t\t\t\t{\n\t\t\t\t\tnTemp = (NF.row(neigh)).transpose();\n\t\t\t\t\tnTemp.normalize();\n\t\t\t\t\tn2 = nT + nTemp;\n\t\t\t\t\tn2.normalize();\n\t\t\t\t\t//printf(\"____ The 2nd edge: %d->%d to Triangle %d (%d, %d, %d)\\n\", F(i, 1), F(i, 2), neigh, F(neigh, 0), F(neigh, 1), F(neigh, 2));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\t/* Get the third neighbor neighbor's normal */\n\t\tfor (int j = 0; j < F.cols(); j++)\t\t// Loop over 3 neighbors of i-th face\n\t\t{\n\t\t\tint neigh = AdjMF3N(i, j);\n\t\t\tfor (int k = 0; k < F.cols(); k++)\t// Loop over 3 vertices of the j-th neighbor\n\t\t\t{\n\t\t\t\tif (F(i, 2) == F(neigh, (k + 1) % F.cols()) && F(i, 0) == F(neigh, k))\n\t\t\t\t{\n\t\t\t\t\tnTemp = (NF.row(neigh)).transpose();\n\t\t\t\t\tnTemp.normalize();\n\t\t\t\t\tn3 = nT + nTemp;\n\t\t\t\t\tn3.normalize();\n\t\t\t\t\t//printf(\"____ The 3rd edge: %d->%d to Triangle %d (%d, %d, %d)\\n\", F(i, 2), F(i, 0), neigh, F(neigh, 0), F(neigh, 1), F(neigh, 2));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t/* Computing 2nd Fundamental form */\n\t\tf2Form1 = 2.0 * (n2 - n3).dot(e1);\n\t\tf2Form2 = 2.0 * (n3 - n1).dot(e2);\n\t\tf2Form3 = 2.0 * (n1 - n2).dot(e3);\n\n\t\t/* Computing the outer product */\n\t\tm1 = (f2Form2 + f2Form3 - f2Form1) * (t1 * t1.transpose());\n\t\tm2 = (f2Form3 + f2Form1 - f2Form2) * (t2 * t2.transpose());\n\t\tm3 = (f2Form1 + f2Form2 - f2Form3) * (t3 * t3.transpose());\n\n\t\t/* Computing the curvature tensor on each face */\n\t\tmT = ( m1 + m2 + m3) / (2.0*doubleArea(i)*doubleArea(i));\n\n\t\t/* Inserting the 2x2 matrix*/\n\t\tEigen::MatrixXd ALoc = A.block(3 * i, 2 * i, 3, 2);\n\t\tmT2D = ALoc.transpose() * mT * ALoc;\n\t\tCTriplet.push_back(Eigen::Triplet<double>(2 * i + 0, 2 * i + 0, mT2D(0, 0)));\n\t\tCTriplet.push_back(Eigen::Triplet<double>(2 * i + 1, 2 * i + 0, mT2D(1, 0)));\n\t\tCTriplet.push_back(Eigen::Triplet<double>(2 * i + 0, 2 * i + 1, mT2D(0, 1)));\n\t\tCTriplet.push_back(Eigen::Triplet<double>(2 * i + 1, 2 * i + 1, mT2D(1, 1)));\n\n\t\t/* For testing purpose only*/\n\t\tif (i <= 20)\n\t\t{\n\t\t\t// Showing edges\n\t\t\tviewer.data().add_edges(V.row(F(i, 0)), V.row(F(i, 0)) + e1.transpose(), Eigen::RowVector3d(0.9, 0.0, 0.0));\n\t\t\tviewer.data().add_edges(V.row(F(i, 1)), V.row(F(i, 1)) + e2.transpose(), Eigen::RowVector3d(0.0, 0.7, 0.0));\n\t\t\tviewer.data().add_edges(V.row(F(i, 2)), V.row(F(i, 2)) + e3.transpose(), Eigen::RowVector3d(0.0, 0.0, 1.0));\n\n\t\t\t// Showing rotated edge => t\n\t\t\tviewer.data().add_edges(V.row(F(i, 0)) + e1.transpose() / 2.0, V.row(F(i, 0)) + e1.transpose() / 2.0 + scale*t1.transpose(), Eigen::RowVector3d(0.9, 0.0, 0.0));\n\t\t\tviewer.data().add_edges(V.row(F(i, 1)) + e2.transpose() / 2.0, V.row(F(i, 1)) + e2.transpose() / 2.0 + scale*t2.transpose(), Eigen::RowVector3d(0.0, 0.7, 0.0));\n\t\t\tviewer.data().add_edges(V.row(F(i, 2)) + e3.transpose() / 2.0, V.row(F(i, 2)) + e3.transpose() / 2.0 + scale*t3.transpose(), Eigen::RowVector3d(0.0, 0.0, 1.0));\n\n\t\t\t// Showing the normals  ni\n\t\t\tviewer.data().add_edges(V.row(F(i, 0)) + e1.transpose() / 2.0, V.row(F(i, 0)) + e1.transpose() / 2.0 + scale*n1.transpose(), Eigen::RowVector3d(0.9, 0.0, 0.0));\n\t\t\tviewer.data().add_edges(V.row(F(i, 1)) + e2.transpose() / 2.0, V.row(F(i, 1)) + e2.transpose() / 2.0 + scale*n2.transpose(), Eigen::RowVector3d(0.0, 0.7, 0.0));\n\t\t\tviewer.data().add_edges(V.row(F(i, 2)) + e3.transpose() / 2.0, V.row(F(i, 2)) + e3.transpose() / 2.0 + scale*n3.transpose(), Eigen::RowVector3d(0.0, 0.0, 1.0));\n\n\t\t\tcout << \"MT=\" << i << endl << \": \" << mT << endl;\n\t\t\tcout << \"MT2D=\" << i << endl << \": \" << mT2D << endl;\n\t\t\t//cout << \"M1=\" << f2Form1 << endl << \": \" << m1 << endl;\n\t\t\t//cout << \"M2=\" << f2Form2 << endl << \": \" << m2 << endl;\n\t\t\t//cout << \"M3=\" << f2Form3 << endl << \": \" << m3 << endl;\n\t\t}\n\t}\n\tCurvatureTensor2D.setFromTriplets(CTriplet.begin(), CTriplet.end());\n}\n\n// [OLD] Wrong implementation\n//void VectorFields::ConstructCurvatureTensor()\n//{\n//\t/* Obtain the principal curvature using LibIGL (vertex-based) */\n//\tEigen::MatrixXd PD1, PD2;\n//\tEigen::VectorXd PV1, PV2;\n//\tigl::principal_curvature(V, F, PD1, PD2, PV1, PV2);\n//\n//\t/* Test on curvature and mean curvature*/\n//\tdouble meanCurve1 = 0.5*(PV1(0) + PV2(0));\n//\tdouble curveDir1 = PD1.row(0).dot(PD2.row(0));\n//\tprintf(\"Mean=%.4f | dot=%.4f \\n\", meanCurve1, curveDir1);\n//\tmeanCurve1 = 0.5*(PV1(1) + PV2(1));\n//\tcurveDir1 = PD1.row(1).dot(PD2.row(1));\n//\tprintf(\"Mean=%.4f | dot=%.4f \\n\", meanCurve1, curveDir1);\n//\n//\t/* Covert the vertex-based to face-based principal curvatures */\n//\tEigen::MatrixXd CurvatureTensor3D;\n//\tCurvatureTensor3D.setZero(3 * F.rows(), 2);\n//\tfor (int i = 0; i < F.rows(); i++)\n//\t{\n//\t\tfor (int j = 0; j < F.cols(); j++)\n//\t\t{\n//\t\t\t/* Maximum curvature direction */\n//\t\t\tCurvatureTensor3D.block(3 * i, 0, 3, 1) += (PD1.row(F(i, j))).transpose() / 3.0;\n//\t\t\t/* Minimum curvature direction */\n//\t\t\tCurvatureTensor3D.block(3 * i, 1, 3, 1) += (PD2.row(F(i, j))).transpose() / 3.0;\n//\t\t}\n//\t\t//CurvatureTensor3D.row(i) /= double(F.cols());\t\t\n//\t}\n//\n//\tCurvatureTensor = A.transpose() * CurvatureTensor3D;\n//\n//}\n\n\n/* Temporary functions*/\n\n\nvoid sortEigenIndex(double eig1, double eig2, double eig3, int& smallest, int& middle, int& largest)\n{\n\tif (eig1 > eig2)\n\t{\n\t\tif (eig1 > eig3)\n\t\t{\n\t\t\tlargest = 0;\n\t\t\tif (eig2 > eig3)\n\t\t\t{\n\t\t\t\tmiddle = 1;\n\t\t\t\tsmallest = 2; \n\t\t\t} \n\t\t\telse\n\t\t\t{\n\t\t\t\tmiddle = 2; \n\t\t\t\tsmallest = 1; \n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlargest = 2; \n\t\t\tmiddle = 0;\n\t\t\tsmallest = 1; \n\t\t}\n\t}\n\telse if (eig2 > eig3)\n\t{\n\t\tlargest = 1;\n\t\tif (eig1 > eig3)\n\t\t{\n\t\t\tmiddle = 0;\n\t\t\tsmallest = 2; \n\t\t} \n\t\telse\n\t\t{\n\t\t\tmiddle = 2;\n\t\t\tsmallest = 0;\n\t\t}\n\t} \n\telse\n\t{\n\t\tlargest = 2; \n\t\tmiddle = 1;\n\t\tsmallest = 0;\n\t}\n\n\tprintf(\"Eig1=%.4f, Eig2=%.4f, Eig3=%.4f  | smallest: %d, middle: %d, largest: %d\\n\", eig1, eig2, eig3, smallest, middle, largest);\n}\n\nvoid VectorFields::ComputeCurvatureFields()\n{\n\t/* Resizing the principal curvatures */\n\tCurvatureTensorField2D.resize(2 * F.rows(), 2);\n\n\t/* Local variables */\n\tEigen::MatrixXd MLoc2D(2, 2), TensorLoc2D(2, 2), EigFields2D;\n\tEigen::VectorXd eigVals2D;\n\n\n\t/* Dummy mass matrix*/\n\tMLoc2D << 1.0, 0.0,\t\t\t0.0, 1.0; \n\tint smallest, middle, largest; \n\t/* Computing the eigenvectors => principal curvatures */\n\n\t/* Making the construction parallel*/\n\tint id, tid, ntids, ipts, istart, iproc;\n#pragma omp parallel private(tid,ntids,ipts,istart,id)\t\n\t{\n\t\tiproc = omp_get_num_procs();\n\t\t//iproc = 1; \n\t\ttid = omp_get_thread_num();\n\t\tntids = omp_get_num_threads();\n\t\tipts = (int)ceil(1.00*(double)Sample.size() / (double)ntids);\n\t\tistart = tid * ipts;\n\t\tif (tid == ntids - 1) ipts = Sample.size() - istart;\n\t\tif (ipts <= 0) ipts = 0;\n\n\t\tEigen::VectorXd\t\t\t\tD(F.rows());\n\t\tfor (int i = 0; i < F.rows(); i++) {\n\t\t\tD(i) = numeric_limits<double>::infinity();\n\t\t}\n\n\t\t//cout << \"[\" << tid << \"] Number of processors \" << iproc << \", with \" << ntids << \" threads.\" << endl;\n\t\t// Computing the values of each element\n\t\tfor (id = istart; id < (istart + ipts); id++) {\n\t\t\tTensorLoc2D = CurvatureTensor2D.block(2 * id, 2 * id, 2, 2);\n\t\t\tcomputeEigenGPU(TensorLoc2D, MLoc2D, EigFields2D, eigVals2D);\n\t\t\t//sortEigenIndex(abs(eigVals(0)), abs(eigVals(1)), abs(eigVals(2)), smallest, middle, largest);\n\t\t\tif ((eigVals2D(0)) >(eigVals2D(1))) { largest = 0; smallest = 1; }\n\t\t\telse { largest = 1; smallest = 0; }\n\t\t\t//printf(\"__[%d] eigVal1=%.4f, eigVec[%.4f;%.4f]  \\t eigVal2=%.4f, eigVec[%.4f;%.4f]\\n\",\n\t\t\t//\t\ti, eigVals2D(0), EigFields2D(0, 0), EigFields2D(1, 0),\n\t\t\t//\t\t   eigVals2D(1), EigFields2D(0, 1), EigFields2D(1, 1));\n\n\t\t\tCurvatureTensorField2D.block(2 * id, 0, 2, 1) = EigFields2D.col(largest);\n\t\t\tCurvatureTensorField2D.block(2 * id, 1, 2, 1) = EigFields2D.col(smallest);\n\t\t}\n\t}\n\t\n\t//for (int i = 0; i < F.rows(); i++)\n\t//{\n\t//\tTensorLoc2D = CurvatureTensor2D.block(2 * i, 2 * i, 2, 2);\n\t//\tcomputeEigenGPU(TensorLoc2D, MLoc2D, EigFields2D, eigVals2D);\n\t//\t//sortEigenIndex(abs(eigVals(0)), abs(eigVals(1)), abs(eigVals(2)), smallest, middle, largest);\n\t//\tif ((eigVals2D(0)) > (eigVals2D(1))) { largest = 0; smallest = 1; }\n\t//\telse { largest = 1; smallest = 0; }\n\t//\t//printf(\"__[%d] eigVal1=%.4f, eigVec[%.4f;%.4f]  \\t eigVal2=%.4f, eigVec[%.4f;%.4f]\\n\",\n\t//\t//\t\ti, eigVals2D(0), EigFields2D(0, 0), EigFields2D(1, 0),\n\t//\t//\t\t   eigVals2D(1), EigFields2D(0, 1), EigFields2D(1, 1));\n\t//\n\t//\tCurvatureTensorField2D.block(2 * i, 0, 2, 1) = EigFields2D.col(largest);\n\t//\tCurvatureTensorField2D.block(2 * i, 1, 2, 1) = EigFields2D.col(smallest);\n\t//}\n}\n\n/* ====================== MESH-RELATED FUNCTIONS ============================*/\nvoid VectorFields::readMesh(const string &meshFile)\n{\n\t// For Timing\n\tchrono::high_resolution_clock::time_point\tt1, t2;\n\tchrono::duration<double>\t\t\t\t\tduration;\n\tt1 = chrono::high_resolution_clock::now();\t\n\tcout << \"> Reading mesh... \";\n\n\t// For actual work of reading mesh object\n\tV.resize(0, 0);\n\tF.resize(0, 0);\n\n\tif (meshFile.substr(meshFile.find_last_of(\".\") + 1) == \"off\") {\n\t\tigl::readOFF(meshFile, V, F);\n\t}\n\telse if (meshFile.substr(meshFile.find_last_of(\".\") + 1) == \"obj\") {\n\t\tigl::readOBJ(meshFile, V, F);\n\t}\n\telse {\n\t\tcout << \"Error! File type can be either .OFF or .OBJ only.\" << endl;\n\t\tcout << \"Program will exit in 2 seconds.\" << endl;\n\t\tSleep(2000);\n\t\texit(10);\n\t}\n\n\tt2 = chrono::high_resolution_clock::now();\n\tduration = t2 - t1;\n\tcout << \"in \" << duration.count() << \" seconds\" << endl;\n\n\t// Printing Mesh-related information\n\tprintf(\"....V=%dx%d\\n\", V.rows(), V.cols());\n\tprintf(\"....F=%dx%d\\n\", F.rows(), F.cols());\n}\n\nvoid VectorFields::readArrowMesh(const string &meshFile)\n{\n\t// For actual work of reading mesh object\n\tVArrow.resize(0, 0);\n\tFArrow.resize(0, 0);\n\n\tif (meshFile.substr(meshFile.find_last_of(\".\") + 1) == \"off\") {\n\t\tigl::readOFF(meshFile, VArrow, FArrow);\n\t}\n\telse if (meshFile.substr(meshFile.find_last_of(\".\") + 1) == \"obj\") {\n\t\tigl::readOBJ(meshFile, VArrow, FArrow);\n\t}\n\telse {\n\t\tcout << \"Error! File type can be either .OFF or .OBJ only.\" << endl;\n\t\tcout << \"Program will exit in 2 seconds.\" << endl;\n\t\tSleep(2000);\n\t\texit(10);\n\t}\n\n\tprintf(\"....V=%dx%d\\n\", VArrow.rows(), VArrow.cols());\n\tprintf(\"....F=%dx%d\\n\", FArrow.rows(), FArrow.cols());\n}\n\nvoid VectorFields::getVF(Eigen::MatrixXd &V, Eigen::MatrixXi &F)\n{\n\tV = this->V;\n\tF = this->F;\n}\n\nvoid VectorFields::computeFaceCenter()\n{\n\tFC.resize(F.rows(), 3);\n\n\tfor (int i = 0; i < F.rows(); i++) {\n\t\tFC.row(i) = (V.row(F(i, 0)) + V.row(F(i, 1)) + V.row(F(i, 2))) / 3.0;\n\t}\n\n}\n\n\n//void VectorFields::visualizeSparseMatrixInMatlab(const Eigen::SparseMatrix<double> &M)\n//{\n//\tprintf(\"Size of M=%dx%d\\n\", M.rows(), M.cols());\n//\n//\tusing namespace matlab::engine;\n//\tEngine *ep;\n//\tmxArray *MM = NULL, *MS = NULL, *result = NULL, *eigVecResult, *nEigs;\n//\n//\tconst int NNZ_M = M.nonZeros();\n//\tint nnzMCounter = 0;\n//\n//\tdouble\t*srm = (double*)malloc(NNZ_M * sizeof(double));\n//\tmwIndex *irm = (mwIndex*)malloc(NNZ_M * sizeof(mwIndex));\n//\tmwIndex *jcm = (mwIndex*)malloc((M.cols() + 1) * sizeof(mwIndex));\n//\n//\tMM = mxCreateSparse(M.rows(), M.cols(), NNZ_M, mxREAL);\n//\tsrm = mxGetPr(MM);\n//\tirm = mxGetIr(MM);\n//\tjcm = mxGetJc(MM);\n//\n//\t// Getting matrix M\n//\tjcm[0] = nnzMCounter;\n//\tfor (int i = 0; i < M.outerSize(); i++) {\n//\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(M, i); it; ++it) {\n//\t\t\tsrm[nnzMCounter] = it.value();\n//\t\t\tirm[nnzMCounter] = it.row();\n//\t\t\tnnzMCounter++;\n//\t\t}\n//\t\tjcm[i + 1] = nnzMCounter;\n//\t}\n//\n//\t// Start Matlab Engine\n//\tep = engOpen(NULL);\n//\tif (!(ep = engOpen(\"\"))) {\n//\t\tfprintf(stderr, \"\\nCan't start MATLAB engine\\n\");\n//\t\tcout << \"CANNOT START MATLAB \" << endl;\n//\t}\n//\telse {\n//\t\tcout << \"MATLAB STARTS. OH YEAH!!!\" << endl;\n//\t}\n//\n//\tengPutVariable(ep, \"M\", MM);\n//\tengEvalString(ep, \"spy(M)\");\n//}", "meta": {"hexsha": "4b78e416774a445e8f42a0c9c6c5d93aa955f79d", "size": 114920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Local Fields/VectorFields.cpp", "max_stars_repo_name": "a-nasikun/LocalFields", "max_stars_repo_head_hexsha": "75aeda114f5a8a9da4954a5d8172a71a5e47fd10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Local Fields/VectorFields.cpp", "max_issues_repo_name": "a-nasikun/LocalFields", "max_issues_repo_head_hexsha": "75aeda114f5a8a9da4954a5d8172a71a5e47fd10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Local Fields/VectorFields.cpp", "max_forks_repo_name": "a-nasikun/LocalFields", "max_forks_repo_head_hexsha": "75aeda114f5a8a9da4954a5d8172a71a5e47fd10", "max_forks_repo_licenses": ["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.8451426739, "max_line_length": 214, "alphanum_fraction": 0.6275234946, "num_tokens": 40704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5007560924841232}}
{"text": "#ifndef MOCHIMOCHI_ADAGRAD_RDA_HPP_\n#define MOCHIMOCHI_ADAGRAD_RDA_HPP_\n\n#include <Eigen/Dense>\n#include <boost/serialization/serialization.hpp>\n#include <boost/serialization/nvp.hpp>\n#include <boost/serialization/split_member.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <fstream>\n#include \"../../functions/enumerate.hpp\"\n#include \"../factory/binary_oml.hpp\"\n\nclass ADAGRAD_RDA : public BinaryOML {\nprivate :\n  const std::size_t kDim;\n  const double kEta;\n  const double kLambda;\n\nprivate :\n  std::size_t _timestep;\n  Eigen::VectorXd _w;\n  Eigen::VectorXd _h;\n  Eigen::VectorXd _g;\n\npublic :\n  ADAGRAD_RDA(const std::size_t dim, const double eta, const double lambda)\n    : kDim(dim),\n      kEta(eta),\n      kLambda(lambda),\n      _timestep(0),\n      _w(Eigen::VectorXd::Zero(kDim)),\n      _h(Eigen::VectorXd::Zero(kDim)),\n      _g(Eigen::VectorXd::Zero(kDim)) {\n    static_assert(std::numeric_limits<decltype(dim)>::max() > 0, \"Dimension Error. (Dimension > 0)\");\n    static_assert(std::numeric_limits<decltype(eta)>::max() > 0, \"Hyper Parameter Error. (eta > 0)\");\n    static_assert(std::numeric_limits<decltype(lambda)>::max() > 0, \"Hyper Parameter Error. (lambda > 0)\");\n    assert(dim > 0);\n    assert(eta > 0);\n    assert(lambda > 0);\n  }\n\n  virtual ~ADAGRAD_RDA() { }\n\nprivate :\n\n  double calculate_margin(const Eigen::VectorXd& x) const {\n    return _w.dot(x);\n  }\n\n  double suffer_loss(const Eigen::VectorXd& x, const int y) const {\n    return std::max(0.0, 1.0 - y * _w.dot(x));\n  }\n\npublic :\n\n  std::string name() const override {\n    return std::string(\"ADAGRAD_RDA\");\n  }\n\n  bool update(const Eigen::VectorXd& feature, const int label) override {\n    if (suffer_loss(feature, label) <= 0.0) { return false; }\n\n    _timestep++;\n    functions::enumerate(feature.data(), feature.data() + feature.size(), 0,\n                       [&](const int index, const double value) {\n                         const auto gradiant = -label * value;\n                         _g[index] += gradiant;\n                         _h[index] += gradiant * gradiant;\n\n                         const auto sign = _g[index] >= 0 ? 1 : -1;\n                         const auto eta = kEta / std::sqrt(_h[index]);\n                         const auto u = std::abs(_g[index]) / _timestep;\n\n                         _w[index] = (u <= kLambda) ? 0.0 : -sign * eta * _timestep * (u - kLambda);\n                       });\n    return true;\n  }\n\n  int predict(const Eigen::VectorXd& x) const override {\n    return calculate_margin(x) > 0.0 ? 1 : -1;\n  }\n\n  void save(const std::string& filename) override {\n    std::ofstream ofs(filename);\n    assert(ofs);\n    boost::archive::text_oarchive oa(ofs);\n    oa << *this;\n    ofs.close();\n  }\n\n  void load(const std::string& filename) override {\n    std::ifstream ifs(filename);\n    assert(ifs);\n    boost::archive::text_iarchive ia(ifs);\n    ia >> *this;\n    ifs.close();\n  }\n\nprivate :\n  friend class boost::serialization::access;\n  BOOST_SERIALIZATION_SPLIT_MEMBER();\n  template <class Archive>\n  void save(Archive& ar, const unsigned int version) const {\n    std::vector<double> w_vector(_w.data(), _w.data() + _w.size());\n    std::vector<double> h_vector(_h.data(), _h.data() + _h.size());\n    std::vector<double> g_vector(_g.data(), _g.data() + _g.size());\n\n    ar & boost::serialization::make_nvp(\"w\", w_vector);\n    ar & boost::serialization::make_nvp(\"h\", h_vector);\n    ar & boost::serialization::make_nvp(\"g\", g_vector);\n    ar & boost::serialization::make_nvp(\"dimension\", const_cast<std::size_t&>(kDim));\n    ar & boost::serialization::make_nvp(\"eta\", const_cast<double&>(kEta));\n    ar & boost::serialization::make_nvp(\"lambda\", const_cast<double&>(kLambda));\n    ar & boost::serialization::make_nvp(\"timestep\", _timestep);\n  }\n\n  template <class Archive>\n  void load(Archive& ar, const unsigned int version) {\n    std::vector<double> w_vector;\n    std::vector<double> h_vector;\n    std::vector<double> g_vector;\n\n    ar & boost::serialization::make_nvp(\"w\", w_vector);\n    ar & boost::serialization::make_nvp(\"h\", h_vector);\n    ar & boost::serialization::make_nvp(\"g\", g_vector);\n    ar & boost::serialization::make_nvp(\"dimension\", const_cast<std::size_t&>(kDim));\n    ar & boost::serialization::make_nvp(\"eta\", const_cast<double&>(kEta));\n    ar & boost::serialization::make_nvp(\"lambda\", const_cast<double&>(kLambda));\n    ar & boost::serialization::make_nvp(\"timestep\", _timestep);\n\n    _w = Eigen::Map<Eigen::VectorXd>(&w_vector[0], w_vector.size());\n    _h = Eigen::Map<Eigen::VectorXd>(&h_vector[0], h_vector.size());\n    _g = Eigen::Map<Eigen::VectorXd>(&g_vector[0], g_vector.size());\n  }\n\n};\n\n#endif //MOCHIMOCHI_ADAGRAD_RDA_HPP_\n", "meta": {"hexsha": "e4e2a0a499e30028df446a3961acc4250de3b2cb", "size": 4770, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mochimochi/classifier/binary/adagrad_rda.hpp", "max_stars_repo_name": "georgeslabreche/MochiMochi", "max_stars_repo_head_hexsha": "6ed0e8e078504a068a812735567d196f5d88e69f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mochimochi/classifier/binary/adagrad_rda.hpp", "max_issues_repo_name": "georgeslabreche/MochiMochi", "max_issues_repo_head_hexsha": "6ed0e8e078504a068a812735567d196f5d88e69f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mochimochi/classifier/binary/adagrad_rda.hpp", "max_forks_repo_name": "georgeslabreche/MochiMochi", "max_forks_repo_head_hexsha": "6ed0e8e078504a068a812735567d196f5d88e69f", "max_forks_repo_licenses": ["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.829787234, "max_line_length": 107, "alphanum_fraction": 0.6371069182, "num_tokens": 1291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.5007560871746474}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2015-2016 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef MG_PROLONGATION_HH\n#define MG_PROLONGATION_HH\n\n#include <boost/fusion/include/vector.hpp>\n#include <boost/timer/timer.hpp>\n\n#include \"fem/barycentric.hh\"\n#include \"fem/spaces.hh\"\n#include \"linalg/dynamicMatrix.hh\"\n#include \"linalg/localMatrices.hh\"\n#include \"linalg/threadedMatrix.hh\"\n#include \"utilities/threading.hh\"\n#include \"utilities/timing.hh\"\n\nnamespace Kaskade\n{\n  /**\n   * \\ingroup iterative\n   * \\brief Computes an interpolation-based prolongation matrix from a (supposedly) coarser space to a finer space.\n   *\n   * \\tparam CoarseSpace a FEFunctionSpace type\n   * \\tparam FineSpace a FEFunctionSpace type\n   *\n   * \\param coarseSpace the (supposedly) coarser space (domain)\n   * \\param fineSpace   the (supposedly) finer space (image)\n   *\n   * Both function spaces have to be defined on the very same grid view.\n   */\n  template <class CoarseSpace, class FineSpace>\n  NumaBCRSMatrix<Dune::FieldMatrix<double,1,1>> prolongation(CoarseSpace const& coarseSpace, FineSpace const& fineSpace)\n  {\n    namespace bf = boost::fusion;\n\n    Timings& timer = Timings::instance();\n    timer.start(\"space prolongation\");\n\n    std::vector<bf::vector<std::vector<size_t>,std::vector<size_t>,\n                           DynamicMatrix<Dune::FieldMatrix<typename FineSpace::Scalar,1,1>>>> interpolationData(fineSpace.gridView().size(0));\n\n    // Intermediate shape function values, declared here to prevent frequent reallocations\n    typename CoarseSpace::Mapper::ShapeFunctionSet::SfValueArray afValues;\n\n    // Step through all the cells and perform local interpolation on each cell.\n    // TODO: do this in parallel\n    for (auto const& cell: elements(fineSpace.gridView()))\n    {\n      auto index = fineSpace.indexSet().index(cell);\n\n      auto const& fineIndices = fineSpace.mapper().globalIndices(index);\n      auto const& coarseIndices = coarseSpace.mapper().globalIndices(index);\n\n      std::copy(fineIndices.begin(),  fineIndices.end(),  std::back_inserter(bf::at_c<0>(interpolationData[index])));\n      std::copy(coarseIndices.begin(),coarseIndices.end(),std::back_inserter(bf::at_c<1>(interpolationData[index])));\n\n      auto const& fineSfs = fineSpace.mapper().shapefunctions(cell);\n      auto const& coarseSfs = coarseSpace.mapper().shapefunctions(cell);\n\n      // Obtain interpolation nodes of target on this cell\n      auto const& iNodes(fineSpace.mapper().shapefunctions(cell).interpolationNodes());\n\n      // Evaluate coarse space global shape functions\n      evaluateGlobalShapeFunctions(coarseSpace,cell,iNodes,afValues,coarseSfs);\n\n      // Interpolate fine space global values\n      approximateGlobalValues(fineSpace,cell,afValues,bf::at_c<2>(interpolationData[index]),fineSfs);\n    }\n    timer.stop(\"space prolongation\");\n\n    timer.start(\"matrix creation\");\n    // Create a sparse prolongation matrix sparsity pattern. Note that the local prolongation matrices\n    // are often sparse (e.g. for Lagrangian elements). We filter out the zero entries in order not to\n    // create too densely populated prolongations, which in turn lead to very expensive conjugation\n    // computations.\n    NumaCRSPatternCreator<size_t> creator(fineSpace.degreesOfFreedom(),coarseSpace.degreesOfFreedom());\n    for (auto const& block: interpolationData)\n      for (int i=0; i<bf::at_c<0>(block).size(); ++i)\n        for (int j=0; j<bf::at_c<1>(block).size(); ++j)\n        {\n          auto entry = bf::at_c<2>(block)[i][j];\n          if (std::abs(entry) > 1e-12)\n            creator.addElement(bf::at_c<0>(block)[i],bf::at_c<1>(block)[j]);\n        }\n\n    // Now create and fill the matrix itself. Overwrite already existing entries\n    // (this means the weighing is just \"last one wins\"\n    NumaBCRSMatrix<Dune::FieldMatrix<double,1,1>,size_t> p(creator);\n    for (auto const& block: interpolationData)\n      for (int i=0; i<bf::at_c<0>(block).size(); ++i)\n        for (int j=0; j<bf::at_c<1>(block).size(); ++j)\n        {\n          auto entry = bf::at_c<2>(block)[i][j];\n          if (std::abs(entry) > 1e-12)\n            p[bf::at_c<0>(block)[i]][bf::at_c<1>(block)[j]] = entry;\n        }\n\n    timer.stop(\"matrix creation\");\n    return p;\n  }\n\n  // ---------------------------------------------------------------------------------------------------------\n\n  /**\n   * \\ingroup iterative\n   * \\brief Computes a stack of prolongation matrices for higher order finite element spaces.\n   *\n   * This computes a stack of prolongation matrices for a scale of finite element spaces with\n   * increasing polynomial ansatz order. From level to level, the ansatz order is doubled (maybe +1\n   * for odd degrees).\n   *\n   * \\tparam Mapper a finite element local to global mapper with scalar shape functions.\n   */\n  template <class Mapper>\n  std::vector<NumaBCRSMatrix<Dune::FieldMatrix<double,1,1>>> prolongationStack(FEFunctionSpace<Mapper> const& space)\n  {\n    std::vector<NumaBCRSMatrix<Dune::FieldMatrix<double,1,1>>> stack;\n    int p = space.mapper().maxOrder();\n\n    if (p > 1) // there is some need for prolongation\n    {\n      H1Space<typename Mapper::Grid> coarseSpace(space.gridManager(),space.gridView(),p/2);  // a coarser space (lower order)\n      stack = prolongationStack(coarseSpace);\n      stack.push_back(prolongation(coarseSpace,space));\n    }\n\n    return stack;\n  }\n\n  // ---------------------------------------------------------------------------------------------------------\n\n  /// \\cond internals\n  namespace ProlongationDetail\n  {\n    struct Node\n    {\n      size_t p, q; // global (fine grid) indices of parent vertices\n      int level;   // level of the vertex\n    };\n  }\n  /// \\endcond\n\n  /**\n   * \\ingroup iterative\n   * \\brief A prolongation operator for P1 finite elements from a coarser grid level to the next finer level.\n   *\n   * For P1 finite elements on simplicial grids, the prolongation from a coarser level to the next finer is a matrix \\f$ P \\f$\n   * in which each row contains either one entry of value 1 (if the vertex is already contained in the coarser level grid)\n   * or two entries that sum up to 1 (if the vertex is created on the finer level by bisecting the edge between two parent\n   * nodes). In the latter case, the two entries default to 0.5 each.\n   *\n   * Storing this as a sparse matrix data structure is quite inefficient.\n   *\n   * This class is a specialized implementation of such prolongation matrices.\n   */\n  class MGProlongation\n  {\n  public:\n    /**\n     * \\brief Constructor.\n     * \\param parents a sequence of node information. The parent indices for fine grid nodes shall refer to the fine grid numbering.\n     * \\param indexInCoarse a vector of length of fine grid vertices. For each coarse grid node, it contains the index of that node\n     *                      in the coarse grid.\n     * \\param nc the number of coarse grid nodes (i.e. number of columns in P)\n     * \\param fineLevel the level of fine grid nodes\n     */\n    MGProlongation(std::vector<ProlongationDetail::Node> const& parents, std::vector<size_t> const& indexInCoarse, size_t nc, int fineLevel);\n\n    /**\n     * \\brief Returns the parent nodes indices.\n     *\n     * For a fine grid node, this returns the parent node indices in the coarse grid. For a coarse\n     * grid node, the \"parent indices\" coincide and refer to the node index in the coarse grid.\n     */\n    std::array<size_t,2> const& parents(size_t i) const\n    {\n      return entries[i];\n    }\n\n    /**\n     * \\brief Matrix vector multiplcation (update mode).\n     *\n     * This computes \\f$ f \\leftarrow f + Pc \\f$.\n     *\n     * \\param f the fine grid target vector. It has to have the correct size.\n     */\n    template <class Vector>\n    void umv(Vector const& c, Vector& f) const\n    {\n      assert(f.size()==entries.size());\n      assert(c.size()==nc);\n\n      for (size_t row=0; row<entries.size(); ++row)\n      {\n        auto e = entries[row];\n        f[row] += 0.5*(c[e[0]] + c[e[1]]);\n      }\n    }\n\n    /**\n     * \\brief Matrix vector multiplcation.\n     *\n     * This computes \\f$ f \\leftarrow Pc \\f$, and is faster than but equivalent to\n     * \\code\n     * f = 0;\n     * umv(c,f);\n     * \\endcode\n     *\n     * \\param f the fine grid target vector. It has to have the correct size.\n     */\n    template <class Vector>\n    void mv(Vector const& c, Vector& f) const\n    {\n      assert(f.size()==entries.size());\n      assert(c.size()==nc);\n\n      for (size_t row=0; row<entries.size(); ++row)\n      {\n        auto e = entries[row];\n        f[row] = 0.5*(c[e[0]] + c[e[1]]);\n      }\n    }\n\n    /**\n     * \\brief Transpose matrix vector multiplication\n     *\n     * This computes \\f$ c \\leftarrow P^T f \\f$.\n     *\n     * \\param c the coarse grid target vector. It is resized to contain the result.\n     */\n    template <class Vector>\n    void mtv(Vector const& f, Vector& c) const\n    {\n      assert(f.size()==entries.size());\n      if (c.size()!=nc)\n        c.resize(nc);\n      for (size_t i=0; i<c.N(); ++i)\n        c[i] = 0;\n\n      for (size_t row=0; row<entries.size(); ++row)\n      {\n        c[entries[row][0]] += 0.5*f[row];\n        c[entries[row][1]] += 0.5*f[row];\n      }\n    }\n\n    /**\n     * \\brief The number of rows.\n     */\n    size_t N() const\n    {\n      return entries.size();\n    }\n\n    /**\n     * \\brief The number of columns.\n     */\n    size_t M() const\n    {\n      return nc;\n    }\n\n    /**\n     * \\brief Galerkin projection of fine grid matrices.\n     * This computes \\f$ P^T A P \\f$.\n     *\n     * \\tparam Entry the entry type of Galerkin matrix to be projected, in general a quadratic Dune::FieldMatrix type\n     * \\tparam Index the Index type of the matrix to be projected\n     *\n     * \\param A the quadratic fine level Galerkin matrix of size \\f$ N\\times N \\f$ to be projected\n     * \\param onlyLowerTriangle if true, only the lower triangular part of symmetric A is touched, and only the lower triangular part of \\f$ P^T A P\\f$ is created\n     */\n    template <class Entry, class Index>\n    NumaBCRSMatrix<Entry,Index> galerkinProjection(NumaBCRSMatrix<Entry,Index> const& A, bool onlyLowerTriangle = false) const\n    {\n      assert(A.N()==N() && A.M()==N());\n      Timings& timer = Timings::instance();\n\n      // First, create the sparsity pattern of the projected matrix.\n      NumaCRSPatternCreator<Index> creator(M(),M(),onlyLowerTriangle);\n\n      // If C = P^T A P, we have that C_{ij} = \\sum_{k,l} P_{ki} P_{lj} A_{kl}. Hence, the entry A_{kl} contributes to\n      // all C_{ij} for which there are nonzero entries P_{ki} and P_{lj} in the rows k and l of P. Thus we can simply\n      // run through all nonzeros A_{kl} of A, look up the column indices i,j of rows k and l of P, and flag C_{ij}\n      // as nonzero.\n\n      // Step through all entries of A\n      timer.start(\"h conjugation pattern\");\n      for (Index k=0; k<A.N(); ++k)\n      {\n        auto const& is = entries[k];                        // indices i for which Pki != 0\n        auto row = A[k];\n        for (auto ca=row.begin(); ca!=row.end(); ++ca)\n        {\n          Index const l = ca.index();\n          auto const& js = entries[l];                      // indices j for which Plj != 0\n          // add all combinations i,j\n          if (is[0]==is[1] && js[0]==js[1])\n            creator.addElement(is[0],js[0]);\n          else\n            creator.addElements(std::begin(is),std::end(is),std::begin(js),std::end(js));\n\n          if (onlyLowerTriangle && k>l)                     // subdiagonal entry (k,l) of A -> entry (l,k) must be treated implicitly:\n            creator.addElements(std::begin(js),std::end(js),std::begin(is),std::end(is)); // add all combinations (j,i)\n        }\n      }\n      timer.stop(\"h conjugation pattern\");\n\n      // An alternative way of computing the sparsity pattern would be to use that the nonzero entries j in column i\n      // of C are exactly those for which there is k with (nonzero P_{jk} and there is l with (nonzero P_{il} and A_{lk})).\n      // Hence we can obtain the column index set J directly by the following steps:\n      // (i) find all l with P_{li} nonzero -> L  [requires to access columns of P - compute the transpose patterns once]\n      // (ii) find all k with A_{lk} nonzero for some l in L -> K  [probably sorting K and removing doubled entries would be a good idea here]\n      // (iii) find all j with P_{kj} nonzero for some k in K -> J\n      // Compared to the above implementation this would have the following (dis)advantages\n      // + easy to do in parallel (since write operations are separated)\n      // + fewer scattered write accesses to memory\n      // - more complex implementation\n      // - requires the transpose pattern of P\n\n      // Create the sparse matrix.\n      timer.start(\"matrix creation\");\n      NumaBCRSMatrix<Entry,Index> pap(creator);\n      timer.stop(\"matrix creation\");\n\n      // Fill the sparse matrix PAP. This is done as before by stepping through all Akl entries and scatter\n      // Pki*Plj*Akl into PAPij.\n      timer.start(\"matrix conjugation\");\n      for (Index k=0; k<A.N(); ++k)\n      {\n        auto const& is = entries[k];\n        auto row = A[k];\n        for (auto ca=row.begin(); ca!=row.end(); ++ca)\n        {\n          Index const l = ca.index();\n          auto const& js = entries[l];\n\n          if (is[0]==is[1] && js[0]==js[1])               // a coarse grid node - this means four identical contributions\n            pap[is[0]][js[0]] += *ca;                     // with factor 1/4. Substitute with one contribution with factor 1.\n          else\n          {\n            auto pap0 = pap[is[0]];\n            pap0[js[0]] += 0.25 * *ca;\n            pap0[js[1]] += 0.25 * *ca;\n\n            auto pap1 = pap[is[1]];\n            pap1[js[0]] += 0.25 * *ca;\n            pap1[js[1]] += 0.25 * *ca;\n          }\n\n          if (onlyLowerTriangle)\n            abort();  // not yet implemented\n        }\n      }\n      timer.stop(\"matrix conjugation\");\n\n      return pap;\n    }\n\n  private:\n    // Internally we treat all rows equally: A row with one entry of value one is represented as\n    // two entries which sum up to 1 (that happen to reference the same column index...). This allows a\n    // very simple and uniform implementation. The vector entries contains the column indices of\n    // the two entries in each row.\n    std::vector<std::array<size_t,2>> entries;\n\n    // Number of columns (i.e. coarse grid nodes).\n    size_t nc;\n  };\n\n  std::ostream& operator<<(std::ostream& out, MGProlongation const& p);\n\n  /**\n   * \\ingroup multigrid\n   * \\brief Creates a Galerkin projected Matrix \\f$ P^T A P \\f$ from a prolongation \\f$ P \\f$ and a\n   *        symmetric matrix \\f$ A \\f$.\n   * \\param onlyLowerTriangle if true, A contains onl the lower triangular part of the symmetric matrix.\n   */\n  template <class Entry, class Index>\n  auto conjugation(MGProlongation const& p, NumaBCRSMatrix<Entry,Index> const& a, bool onlyLowerTriangle)\n  {\n    return p.template galerkinProjection(a,onlyLowerTriangle);\n  }\n\n  // ---------------------------------------------------------------------------------------------------------\n\n  /// \\cond internals\n  namespace ProlongationDetail\n  {\n    // For each corner of the given cell, if there are any of them which are not corners of the father cell\n    // (i.e. created by bisection of an edge), enter the parent vertices into the parents vector.\n    template <class LeafView, class Cell, class Parents>\n    void computeParents(LeafView const& leafView, Cell const& cell, Parents& parents)\n    {\n      // If this cell is a coarse grid cell, none of its vertices have parents, and we're done.\n      if (!cell.hasFather())\n        return;\n\n      int const dim = LeafView::dimension;\n\n      // For each corner, check its position in the parent. If it has barycentric coordinates with one\n      // entry approximately one (all others zero), it is a corner of the father cell and will be treated\n      // later (or has already been treated). Otherwise there will be two entries 0.5 (all others zero),\n      // and these entries denote father corners which are the parents.\n      assert(cell.type().isSimplex());\n      auto const& geo = cell.geometryInFather();\n      int nCorners = geo.corners();\n      for (int i=0; i<nCorners; ++i)\n      {\n        // TODO: We could first obtain the index of the corner and check whether its parents have\n        //       already been determined, and skip the geometric considerations in that case.\n        //       This should save some time.\n        //       On the other hand, obtaining indices can also be expensive, and in the current\n        //       implementation we only have to get them for corners that actually are no corners\n        //       in the father cell. This saves some time, too.\n        //       We should check which option is faster, and whether it makes a big difference in\n        //       the first place.\n\n        // barycentric coordinates of corner in the father cell\n        auto b = barycentric(geo.corner(i));\n\n        // find potential parent vertices (those with barycentric coordinates 0.5)\n        int pcount = 0;\n        int pc[2];\n        for (int k=0; k<b.N(); ++k)                         // check all barycentric coordinates\n          if (std::abs(b[k]-0.5) < 0.01)                    // if close to 0.5 accept\n          {\n            pc[pcount] = (k+1) % (dim+1);                   // map barycentric coordinate number to Dune corner number\n            ++pcount;                                       // note down that we've found one more parent vertex\n          }\n\n        if (pcount == 2)                                    //  corner i is a father edge midpoint\n        {\n          auto const& is = leafView.indexSet();\n          parents.push_back(std::make_pair(is.index(cell.template subEntity<dim>(i)),\n                                           Node{is.index(cell.father().template subEntity<dim>(pc[0])),\n                                                is.index(cell.father().template subEntity<dim>(pc[1])),\n                                                cell.level()}));\n        }\n      }\n    }\n\n    /**\n     * \\ingroup multigrid\n     * \\brief Creates a stack of prolongations from parent-child relationships in grids\n     * \\param level\n     */\n    std::vector<MGProlongation> makeProlongationStack(std::vector<Node> parents, int level, size_t minNodes);\n  };\n  /// \\endcond\n\n  // ---------------------------------------------------------------------------------------------------------\n\n  /**\n   * \\ingroup multigrid\n   * \\brief Computes a sequence of prolongation matrices for P1 finite elements in hierarchical grids.\n   *\n   * We assume that each vertex not contained in the coarse grid has been created by bisecting an edge,\n   * such that there are exactly two \"parent vertices\".\n   * \\tparam Grid the Dune grid type on which the P1 space is defined. The grid has to be a simplicial grid.\n   * \\param grid the grid itself\n   * \\param minNodes minimum number of nodes to keep as coarse grid\n   */\n  template <class GridMan>\n  std::vector<MGProlongation> prolongationStack(GridMan const& gridman, size_t minNodes=0)\n  {\n    Timings& timer = Timings::instance();\n\n    auto const& grid = gridman.grid();\n    auto const& leafView = grid.leafGridView();\n    auto const& cellRanges = gridman.cellRanges(grid.levelGridView(0));\n\n    // In parallel compute the parent nodes for edge midpoints cell by cell\n    timer.start(\"parent computation\");\n    std::vector<std::vector<std::pair<size_t,ProlongationDetail::Node>>> myParents(cellRanges.maxRanges());\n    parallelFor([&](int k, int n)\n    {\n      for (auto const& coarseCell: cellRanges.range(n,k))\n        for (auto const& cell: descendantElements(coarseCell,grid.maxLevel()))\n          ProlongationDetail::computeParents(leafView,cell,myParents[k]);\n    },myParents.size());\n\n    // Now that all parent nodes have been identified, consolidate them in an easily\n    // indexable array.\n    std::vector<ProlongationDetail::Node> parents(leafView.size(leafView.dimension),ProlongationDetail::Node{0,0,-1});\n    for (auto const& ps: myParents)\n      for (auto const& p: ps)\n        parents[p.first] = p.second;\n    timer.stop(\"parent computation\");\n\n\n    // Now construct the prolongation matrices for all levels.\n    timer.start(\"made stack parents\");\n    auto ps = ProlongationDetail::makeProlongationStack(std::move(parents),grid.maxLevel(),minNodes);\n    timer.stop(\"made stack parents\");\n    return ps;\n  }\n\n\n  // ---------------------------------------------------------------------------------------------------------\n\n  /**\n   * \\ingroup multigrid\n   * \\brief Class for multigrid stacks.\n   *\n   * This provides the storage of and access to prolongations and projected Galerkin matrices,\n   * but leaves the construction of these to derived classes.\n   */\n  template <class Prolongation, class Entry, class Index>\n  class MultiGridStack\n  {\n  public:\n\n    /**\n     * \\brief Constructor\n     *\n     * This takes both a stack of prolongations and a matching stack of projected\n     */\n    MultiGridStack(std::vector<Prolongation>&& ps, std::vector<NumaBCRSMatrix<Entry,Index>>&& as)\n    : prolongations(std::move(ps)), galerkinMatrices(std::move(as))\n    {\n      assert(prolongations.size()+1==galerkinMatrices.size());\n    }\n\n    /**\n     * \\brief Constructor\n     *\n     * This takes a stack of prolongations and creates the stack of projected Galerkin matrices from the given\n     * fine grid matrix. Most useful for geometric multigrid, where the prolongations are defined solely in terms of the grid.\n     *\n     * \\see makeMultiGridStack\n     */\n    MultiGridStack(std::vector<Prolongation>&& ps, NumaBCRSMatrix<Entry,Index>&& A, bool onlyLowerTriangle)\n    {\n      Timings& timer = Timings::instance();\n\n      prolongations = std::move(ps);\n      galerkinMatrices.push_back(std::move(A));\n\n      assert((prolongations.size() == 0) || (prolongations.back().N() == galerkinMatrices[0].N()));\n      assert(galerkinMatrices[0].N() == galerkinMatrices[0].M());\n\n      // Step through the prolongations from top level to bottom\n      timer.start(\"matrix projection\");\n      for (auto pi=prolongations.crbegin(); pi!=prolongations.crend(); ++pi)\n        galerkinMatrices.insert(galerkinMatrices.begin(),conjugation(*pi,galerkinMatrices.front(),onlyLowerTriangle));\n      timer.stop(\"matrix projection\");\n    }\n\n    MultiGridStack(MultiGridStack&& other) = default;\n\n    /**\n     * \\brief The number of grid levels\n     */\n    int levels() const\n    {\n      return galerkinMatrices.size();\n    }\n\n    /**\n     * \\brief Returns the prolongation from given level to next higher one.\n     * \\param level precondition 0 <= level < levels()-1\n     */\n    Prolongation const& p(int level) const\n    {\n      return prolongations[level];\n    }\n\n    /**\n     * \\brief Returns the projected Galerkin matrix on the given level.\n     * \\param level precondition 1 <= level < levels()\n     */\n    NumaBCRSMatrix<Entry,Index> const& a(int level) const\n    {\n      return galerkinMatrices[level];\n    }\n\n    /**\n     * \\brief Returns the projected Galerkin matrix on the coarsest level.\n     *\n     * This is explicitly a mutable reference, such that the coarse grid matrix can be moved\n     * from. This is useful, as in the multigrid, the coarsest level matrix is not referenced\n     * (the coarse grid preconditioner has its own copy, maybe obtained by moving from here...).\n     */\n    NumaBCRSMatrix<Entry,Index>& coarseGridMatrix()\n    {\n      return galerkinMatrices[0];\n    }\n\n    void report(std::ostream& out) const\n    {\n      for (auto const& p: prolongations)\n        out << \"Prolongation:\\n\" << p;\n\n      for (auto const& a: galerkinMatrices)\n        out << \"GalerkinMatrix: \\n\" << a;\n    }\n\n  private:\n    std::vector<Prolongation>                 prolongations;    // prolongations grid i -> i+1, i=0,...,n-1\n    std::vector<NumaBCRSMatrix<Entry,Index>>  galerkinMatrices; // Galerkin matrices on grid i, i=0,...,n\n  };\n\n  template <typename Prolongations, typename Entry, typename Index>\n  std::ostream& operator<<(std::ostream& out, MultiGridStack<Prolongations,Entry,Index> const& mgStack) { mgStack.report(out); return out; }\n\n  /**\n   * \\ingroup multigrid\n   * \\brief Convenience routine for creating multigrid stacks\n   *\n   * Given a stack of prolongations and the top level Galerkin matrix, this creates the complete stack\n   * including all projected Galerkin matrices.\n   *\n   * \\param ps a vector of prolongation matrices\n   * \\param A the top level (finest) Galerkin matrix to be projected down\n   * \\param onlyLowerTriangle if true, only the lower triangular part of A will be referenced\n   */\n  template <class Prolongation, class Entry, class Index>\n  MultiGridStack<Prolongation,Entry,Index> makeMultiGridStack(std::vector<Prolongation>&& ps, NumaBCRSMatrix<Entry,Index>&& A,\n                                                              bool onlyLowerTriangle)\n  {\n    return MultiGridStack<Prolongation,Entry,Index>(std::move(ps),std::move(A),onlyLowerTriangle);\n  }\n\n  /**\n   * \\ingroup multigrid\n   * \\brief convenience routine for creating multigrid stacks based on geometric coarsening for P1 elements\n   */\n  template <class GridMan, class Entry, class Index>\n  MultiGridStack<MGProlongation,Entry,Index> makeGeometricMultiGridStack(GridMan const& gridManager, NumaBCRSMatrix<Entry,Index>&& A,\n                                                                         size_t minNodes=10000, bool onlyLowerTriangle=false)\n  {\n    return MultiGridStack<MGProlongation,Entry,Index>(prolongationStack(gridManager,minNodes),std::move(A),onlyLowerTriangle);\n  }\n\n  /**\n   * \\ingroup multigrid\n   * \\brief Creates stack of prolongations and projected Galerkin matrices.\n   *\n   * \\param A the symmetric sparse matrix\n   * \\param n stop the coarsening if the number of rows/cols drops below this number\n   * \\param onlyLowerTriangle if true, only the lower triangular part of symmetric A is accessed\n   */\n  template <class Entry, class Index>\n  MultiGridStack<MGProlongation,Entry,Index> makeAlgebraicMultigridStack(NumaBCRSMatrix<Entry,Index>&& A,\n                                                                         Index n=0, bool onlyLowerTriangle=false);\n\n\n  /**\n   * \\ingroup multigrid\n   * \\brief convenience routine for creating multigrid stacks based on coarsening by reducing the ansatz order from P to P1\n   */\n  template <typename FineSpace, typename Matrix>\n  auto makePMultiGridStack(FineSpace const& space, Matrix&& A, bool onlyLowerTriangle)\n  {\n    std::vector<NumaBCRSMatrix<Dune::FieldMatrix<double,1,1>>> prolongations;\n\n    if (space.mapper().maxOrder() > 1)\n    {\n      H1Space<typename FineSpace::Grid> coarseSpace(space.gridManager(),space.gridView(),1);  // a coarser space (lower order)\n      prolongations.push_back(prolongation(coarseSpace,space));\n    }\n\n    return makeMultiGridStack(std::move(prolongations),std::move(A),onlyLowerTriangle);\n  }\n\n  /**\n   * \\ingroup multigrid\n   * \\brief convenience routine for creating multigrid stacks between two spaces.\n   *\n   * An approximation of the projected Galerkin matrix is provided. Often, this can be assembled much more\n   * efficiently than projected.\n   */\n  template <typename FineSpace, typename CoarseSpace, typename Matrix>\n  auto makePMultiGridStack(FineSpace const& fineSpace, Matrix&& fA, CoarseSpace const& coarseSpace, Matrix&& cA)\n  {\n    using Prolongation = NumaBCRSMatrix<Dune::FieldMatrix<double,1,1>>;\n    std::vector<Prolongation> prolongations;\n    prolongations.push_back(prolongation(coarseSpace,fineSpace));\n\n    std::vector<Matrix> matrices{std::move(cA),std::move(fA)};\n\n    return MultiGridStack<Prolongation,typename Matrix::block_type,\n                                       typename Matrix::size_type>(std::move(prolongations),std::move(matrices));\n  }\n\n}\n\n#endif\n", "meta": {"hexsha": "fb5de0d7f50322ab72b603f6656ee46b1ab8a689", "size": 28659, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/mg/prolongation.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/mg/prolongation.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:33.000Z", "max_forks_repo_path": "Kaskade/mg/prolongation.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 40.9414285714, "max_line_length": 162, "alphanum_fraction": 0.6170487456, "num_tokens": 7120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5007560858371057}}
{"text": "#ifndef QUADRATIC_B_SPLINE_HPP\n#define QUADRATIC_B_SPLINE_HPP\n\n#include <cassert>\n#include <array>\n#include <Eigen/Dense>\n\nnamespace polyfem {\n\tclass QuadraticBSpline\n\t{\n\tpublic:\n\t\tQuadraticBSpline() { }\n\t\tQuadraticBSpline(const std::array<double, 4> &knots)\n\t\t: knots_(knots)\n\t\t{ }\n\t\t\n\t\tvoid init(const std::array<double, 4> &knots);\n\n\t\tvoid interpolate(const Eigen::MatrixXd &ts, Eigen::MatrixXd &result) const;\n\t\tdouble interpolate(const double t) const;\n\n\t\tvoid derivative(const Eigen::MatrixXd &ts, Eigen::MatrixXd &result) const;\n\t\tdouble derivative(const double t) const;\n\n\tprivate:\n\t\tstd::array<double, 4> knots_;\n\t};\n}\n#endif //QUADRATIC_B_SPLINE_HPP\n", "meta": {"hexsha": "028db8b459c5ad52c383879f2baf695174c51c0b", "size": 660, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/basis/function/QuadraticBSpline.hpp", "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": "src/basis/function/QuadraticBSpline.hpp", "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": "src/basis/function/QuadraticBSpline.hpp", "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": 22.0, "max_line_length": 77, "alphanum_fraction": 0.7303030303, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5007560858371057}}
{"text": "#include <opencv2/opencv.hpp>\n#include <vector>\n#include <string>\n#include <Eigen/Core>\n#include <pangolin/pangolin.h>\n#include <unistd.h>\n\nusing namespace std;\nusing namespace Eigen;\n\n// path for left and right images\nstring left_file = \"./left.png\";\nstring right_file = \"./right.png\";\n\n// Already written, just need to declare\nvoid showPointCloud(\n    const vector<Vector4d, Eigen::aligned_allocator<Vector4d>> &pointcloud);\n\nint main(int argc, char **argv) {\n\n    // camera intrinsics \n    double fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n    // baseline\n    double b = 0.573;\n\n    // read the images\n    cv::Mat left = cv::imread(left_file, 0);\n    cv::Mat right = cv::imread(right_file, 0);\n    // use SGBM (semi-global batch matching) in opencv to calculate the parallex\n    cv::Ptr<cv::StereoSGBM> sgbm = cv::StereoSGBM::create(\n        0, 96, 9, 8 * 9 * 9, 32 * 9 * 9, 1, 63, 10, 100, 32);    // magic numbers\n    cv::Mat disparity_sgbm, disparity;\n    sgbm->compute(left, right, disparity_sgbm);\n    disparity_sgbm.convertTo(disparity, CV_32F, 1.0 / 16.0f);\n\n    // the result point cloud\n    vector<Vector4d, Eigen::aligned_allocator<Vector4d>> pointcloud;\n\n    // If it runs slowly, change u,v into u += 2, v += 2\n    for (int v = 0; v < left.rows; v++)\n        for (int u = 0; u < left.cols; u++) {\n            if (disparity.at<float>(v, u) <= 0.0 || disparity.at<float>(v, u) >= 96.0) continue;\n\n            Vector4d point(0, 0, 0, left.at<uchar>(v, u) / 255.0); // (x, y, z, color)\n\n            // (Important) Use the stereo model to calculate the depth and stereo coordinates of the point\n            double x = (u - cx) / fx;\n            double y = (v - cy) / fy;\n            double depth = fx * b / (disparity.at<float>(v, u));\n            point[0] = x * depth;\n            point[1] = y * depth;\n            point[2] = depth;\n\n            pointcloud.push_back(point);\n        }\n\n    cv::imshow(\"disparity\", disparity / 96.0);\n    cv::waitKey(0);\n    // draw the point cloud\n    showPointCloud(pointcloud);\n    return 0;\n}\n\nvoid showPointCloud(const vector<Vector4d, Eigen::aligned_allocator<Vector4d>> &pointcloud) {\n\n    if (pointcloud.empty()) {\n        cerr << \"Point cloud is empty!\" << endl;\n        return;\n    }\n\n    pangolin::CreateWindowAndBind(\"Point Cloud 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    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        glPointSize(2);\n        glBegin(GL_POINTS);\n        for (auto &p: pointcloud) {\n            glColor3f(p[3], p[3], p[3]);\n            glVertex3d(p[0], p[1], p[2]);\n        }\n        glEnd();\n        pangolin::FinishFrame();\n        usleep(5000);   // sleep 5 ms\n    }\n    return;\n}", "meta": {"hexsha": "29b3f57a820d7726c28e9c256c42a419823c421c", "size": 3291, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch5/stereo/stereoVision.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": "ch5/stereo/stereoVision.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": "ch5/stereo/stereoVision.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": 32.2647058824, "max_line_length": 106, "alphanum_fraction": 0.5961713765, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925404, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5007560818651715}}
{"text": "// Copyright Louis Dionne 2013-2016\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#include <boost/hana/and.hpp>\n#include <boost/hana/any_of.hpp>\n#include <boost/hana/flatten.hpp>\n#include <boost/hana/functional/compose.hpp>\n#include <boost/hana/functional/partial.hpp>\n#include <boost/hana/fwd/ap.hpp>\n#include <boost/hana/fwd/equal.hpp>\n#include <boost/hana/fwd/find_if.hpp>\n#include <boost/hana/fwd/lift.hpp>\n#include <boost/hana/fwd/union.hpp>\n#include <boost/hana/if.hpp>\n#include <boost/hana/is_subset.hpp>\n#include <boost/hana/optional.hpp>\n#include <boost/hana/transform.hpp>\nnamespace hana = boost::hana;\n\n\n// A `Monad` for searching infinite sets in finite time.\n//\n// Taken from http://goo.gl/XJeDy8.\nstruct infinite_set_tag { };\n\ntemplate <typename Find>\nstruct infinite_set {\n    Find find;\n    using hana_tag = infinite_set_tag;\n};\n\ntemplate <typename Pred>\nconstexpr infinite_set<Pred> make_infinite_set(Pred pred) {\n    return {pred};\n}\n\ntemplate <typename X>\nconstexpr auto singleton(X x) {\n    return make_infinite_set([=](auto /*p*/) { return x; });\n}\n\ntemplate <typename X, typename Y>\nconstexpr auto doubleton(X x, Y y) {\n    return make_infinite_set([=](auto p) {\n        return hana::if_(p(x), x, y);\n    });\n}\n\nnamespace boost { namespace hana {\n    template <>\n    struct union_impl<infinite_set_tag> {\n        template <typename Xs, typename Ys>\n        static constexpr auto apply(Xs xs, Ys ys) {\n            return flatten(doubleton(xs, ys));\n        }\n    };\n\n    //////////////////////////////////////////////////////////////////////////\n    // Comparable\n    //////////////////////////////////////////////////////////////////////////\n    template <>\n    struct equal_impl<infinite_set_tag, infinite_set_tag> {\n        template <typename Xs, typename Ys>\n        static constexpr auto apply(Xs xs, Ys ys)\n        { return and_(is_subset(xs, ys), is_subset(ys, xs)); }\n    };\n\n\n    //////////////////////////////////////////////////////////////////////////\n    // Functor\n    //////////////////////////////////////////////////////////////////////////\n    template <>\n    struct transform_impl<infinite_set_tag> {\n        template <typename Set, typename F>\n        static constexpr auto apply(Set set, F f) {\n            return make_infinite_set([=](auto q) {\n                return f(set.find(compose(q, f)));\n            });\n        }\n    };\n\n    //////////////////////////////////////////////////////////////////////////\n    // Applicative\n    //////////////////////////////////////////////////////////////////////////\n    template <>\n    struct lift_impl<infinite_set_tag> {\n        template <typename X>\n        static constexpr auto apply(X x)\n        { return singleton(x); }\n    };\n\n    template <>\n    struct ap_impl<infinite_set_tag> {\n        template <typename F, typename Set>\n        static constexpr auto apply(F fset, Set set) {\n            return flatten(transform(fset, partial(transform, set)));\n        }\n    };\n\n    //////////////////////////////////////////////////////////////////////////\n    // Monad\n    //////////////////////////////////////////////////////////////////////////\n    template <>\n    struct flatten_impl<infinite_set_tag> {\n        template <typename Set>\n        static constexpr auto apply(Set set) {\n            return make_infinite_set([=](auto p) {\n                return set.find([=](auto set) {\n                    return any_of(set, p);\n                }).find(p);\n            });\n        }\n    };\n\n    //////////////////////////////////////////////////////////////////////////\n    // Searchable\n    //////////////////////////////////////////////////////////////////////////\n    template <>\n    struct find_if_impl<infinite_set_tag> {\n        template <typename Set, typename Pred>\n        static constexpr auto apply(Set set, Pred p) {\n            auto x = set.find(p);\n            return if_(p(x), hana::just(x), hana::nothing);\n        }\n    };\n\n    template <>\n    struct any_of_impl<infinite_set_tag> {\n        template <typename Set, typename Pred>\n        static constexpr auto apply(Set set, Pred p) {\n            return p(set.find(p));\n        }\n    };\n}} // end namespace boost::hana\n\n//////////////////////////////////////////////////////////////////////////////\n// Tests\n//////////////////////////////////////////////////////////////////////////////\n\n#include <boost/hana/any_of.hpp>\n#include <boost/hana/ap.hpp>\n#include <boost/hana/assert.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/find_if.hpp>\n#include <boost/hana/flatten.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/is_subset.hpp>\n#include <boost/hana/lift.hpp>\n#include <boost/hana/not.hpp>\n#include <boost/hana/optional.hpp>\n#include <boost/hana/plus.hpp>\n#include <boost/hana/transform.hpp>\n#include <boost/hana/union.hpp>\nnamespace hana = boost::hana;\n\n\ntemplate <int i>\nconstexpr int n = i;\n\ntemplate <int i>\nconstexpr auto c = hana::int_c<i>;\n\nint main() {\n    auto f = [](auto n) { return n + hana::int_c<10>; };\n    auto g = [](auto n) { return n + hana::int_c<100>; };\n\n    // union_\n    {\n        BOOST_HANA_CONSTANT_CHECK(hana::equal(\n            hana::union_(singleton(c<0>), singleton(c<0>)),\n            singleton(c<0>)\n        ));\n        BOOST_HANA_CONSTANT_CHECK(hana::equal(\n            hana::union_(singleton(c<0>), singleton(c<1>)),\n            doubleton(c<0>, c<1>)\n        ));\n        BOOST_HANA_CONSTANT_CHECK(hana::equal(\n            hana::union_(singleton(c<0>), doubleton(c<0>, c<1>)),\n            doubleton(c<0>, c<1>)\n        ));\n    }\n\n    // Comparable\n    {\n        // equal\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(singleton(n<0>), singleton(n<0>)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::equal(singleton(n<0>), singleton(n<1>))));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(singleton(n<0>), doubleton(n<0>, n<0>)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::equal(singleton(n<0>), doubleton(n<0>, n<1>))));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::equal(singleton(n<0>), doubleton(n<1>, n<1>))));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(doubleton(n<0>, n<1>), doubleton(n<0>, n<1>)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(doubleton(n<0>, n<1>), doubleton(n<1>, n<0>)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::equal(doubleton(n<0>, n<1>), doubleton(n<0>, n<0>))));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::equal(doubleton(n<0>, n<1>), doubleton(n<3>, n<4>))));\n        }\n    }\n\n    // Functor\n    {\n        // transform\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::transform(singleton(n<0>), f),\n                singleton(f(n<0>))\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::transform(doubleton(n<0>, n<1>), f),\n                doubleton(f(n<0>), f(n<1>))\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::transform(doubleton(n<0>, n<0>), f),\n                singleton(f(n<0>))\n            ));\n        }\n    }\n\n    // Applicative\n    {\n        // ap\n        {\n            BOOST_HANA_CONSTANT_CHECK(hana::equal(\n                hana::ap(singleton(f), singleton(c<0>)),\n                singleton(f(c<0>))\n            ));\n            BOOST_HANA_CONSTANT_CHECK(hana::equal(\n                hana::ap(singleton(f), doubleton(c<0>, c<1>)),\n                doubleton(f(c<0>), f(c<1>))\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(hana::equal(\n                hana::ap(doubleton(f, g), singleton(c<0>)),\n                doubleton(f(c<0>), g(c<0>))\n            ));\n            BOOST_HANA_CONSTANT_CHECK(hana::equal(\n                hana::ap(doubleton(f, g), doubleton(c<0>, c<1>)),\n                hana::union_(doubleton(f(c<0>), f(c<1>)),\n                             doubleton(g(c<0>), g(c<1>)))\n            ));\n        }\n\n        // lift\n        {\n            BOOST_HANA_CONSTANT_CHECK(hana::equal(\n                hana::lift<infinite_set_tag>(c<0>),\n                singleton(c<0>)\n            ));\n        }\n    }\n\n    // Monad\n    {\n        // flatten\n        {\n            BOOST_HANA_CONSTANT_CHECK(hana::equal(\n                hana::flatten(singleton(singleton(c<0>))),\n                singleton(c<0>)\n            ));\n            BOOST_HANA_CONSTANT_CHECK(hana::equal(\n                hana::flatten(singleton(doubleton(c<0>, c<1>))),\n                doubleton(c<0>, c<1>)\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(hana::equal(\n                hana::flatten(doubleton(singleton(c<0>), singleton(c<1>))),\n                doubleton(c<0>, c<1>)\n            ));\n            BOOST_HANA_CONSTANT_CHECK(hana::equal(\n                hana::flatten(doubleton(doubleton(c<0>, c<1>), singleton(c<2>))),\n                hana::union_(doubleton(c<0>, c<1>), singleton(c<2>))\n            ));\n            BOOST_HANA_CONSTANT_CHECK(hana::equal(\n                hana::flatten(doubleton(singleton(c<0>), doubleton(c<1>, c<2>))),\n                hana::union_(doubleton(c<0>, c<1>), singleton(c<2>))\n            ));\n            BOOST_HANA_CONSTANT_CHECK(hana::equal(\n                hana::flatten(doubleton(doubleton(c<0>, c<1>), doubleton(c<2>, c<3>))),\n                hana::union_(doubleton(c<0>, c<1>), doubleton(c<2>, c<3>))\n            ));\n        }\n    }\n\n    // Searchable\n    {\n        // any_of\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::any_of(singleton(n<0>), hana::equal.to(n<0>)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::any_of(singleton(n<0>), hana::equal.to(n<1>))));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::any_of(doubleton(n<0>, n<1>), hana::equal.to(n<0>)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::any_of(doubleton(n<0>, n<1>), hana::equal.to(n<1>)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::any_of(doubleton(n<0>, n<1>), hana::equal.to(n<2>))));\n        }\n\n        // find_if\n        {\n            BOOST_HANA_CONSTANT_CHECK(hana::find_if(singleton(c<0>), hana::equal.to(c<0>)) == hana::just(c<0>));\n            BOOST_HANA_CONSTANT_CHECK(hana::find_if(singleton(c<1>), hana::equal.to(c<0>)) == hana::nothing);\n\n            BOOST_HANA_CONSTANT_CHECK(hana::find_if(doubleton(c<0>, c<1>), hana::equal.to(c<0>)) == hana::just(c<0>));\n            BOOST_HANA_CONSTANT_CHECK(hana::find_if(doubleton(c<0>, c<1>), hana::equal.to(c<1>)) == hana::just(c<1>));\n            BOOST_HANA_CONSTANT_CHECK(hana::find_if(doubleton(c<0>, c<1>), hana::equal.to(c<2>)) == hana::nothing);\n        }\n\n        // is_subset\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::is_subset(singleton(n<0>), singleton(n<0>)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::is_subset(singleton(n<1>), singleton(n<0>))));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::is_subset(singleton(n<0>), doubleton(n<0>, n<1>)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::is_subset(singleton(n<1>), doubleton(n<0>, n<1>)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::is_subset(singleton(n<2>), doubleton(n<0>, n<1>))));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::is_subset(doubleton(n<0>, n<1>), doubleton(n<0>, n<1>)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::is_subset(doubleton(n<0>, n<2>), doubleton(n<0>, n<1>))));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::is_subset(doubleton(n<2>, n<3>), doubleton(n<0>, n<1>))));\n        }\n    }\n}\n", "meta": {"hexsha": "0bec7a51c108293f9bb211b9bb2aa00b76908dd3", "size": 11502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.62.0/libs/hana/example/misc/infinite_set.cpp", "max_stars_repo_name": "sita1999/arangodb", "max_stars_repo_head_hexsha": "6a4f462fa209010cd064f99e63d85ce1d432c500", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2016-03-04T15:44:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T11:06:25.000Z", "max_issues_repo_path": "3rdParty/boost/1.62.0/libs/hana/example/misc/infinite_set.cpp", "max_issues_repo_name": "lipper/arangodb", "max_issues_repo_head_hexsha": "66ea1fd4946668192e3f0d1060f0844f324ad7b8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2016-02-29T17:59:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-05T04:59:26.000Z", "max_forks_repo_path": "3rdParty/boost/1.62.0/libs/hana/example/misc/infinite_set.cpp", "max_forks_repo_name": "lipper/arangodb", "max_forks_repo_head_hexsha": "66ea1fd4946668192e3f0d1060f0844f324ad7b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-11-02T09:37:09.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-05T06:38:49.000Z", "avg_line_length": 35.7204968944, "max_line_length": 118, "alphanum_fraction": 0.5224308816, "num_tokens": 2910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.5007300285350624}}
{"text": "#include <vector>\n#include <algorithm>\n#include <opencv2/opencv.hpp>\n#include <Eigen/Dense>\n#include <chrono>\n\n#include <spline_solver/hermite_spline.hpp>\n#include <spline_solver/draw.hpp>\n\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\n\nMat3f frame(1080, 1920);\nconst double scale = (double)max(frame.cols, frame.rows);\n\n#define WINDOW1 \"w1\"\n\n\nvector<Vector2d> points;\n\nVector2i last_click_point;\nchrono::time_point<std::chrono::steady_clock> last_click_time;\n\ntemplate<typename Spline>\nSpline fit_and_draw_spline()\n{\n    Spline sp;\n\n    frame.setTo(Scalar(0.0f,0.0f, 0.0f)); // clear frame\n\n    if (points.size() >= 3)\n    {\n        typename Spline::Solver solver;\n\n        Matrix<double, 2, Spline::Polynomial1::RequiredValues - 1> start;\n        Matrix<double, 2, Spline::Polynomial1::RequiredValues - 1> end;\n\n        start.setZero();\n        end.setZero();\n\n        sp = solver.solve(points, start, end);\n        draw_spline(sp, frame, Vector2d(scale, scale));\n    }\n\n    for (int k = 0; k < points.size(); ++k)\n    {\n        circle(frame, Point((int)(points[k].x() * scale), (int)(points[k].y() * scale)), 5.0, Scalar(0.0f, 1.0f, 0.0f), FILLED);\n    }\n\n    imshow(WINDOW1, frame);\n\n    return sp;\n}\n\nvoid click_callback(int event, int x, int y, int flags, void* userdata)\n{\n    if (flags != (EVENT_FLAG_CTRLKEY | EVENT_FLAG_LBUTTON))\n    {\n        return ;\n    }\n\n    Vector2i click_point(x, y);\n    std::chrono::duration<double> diff = std::chrono::steady_clock::now() - last_click_time;\n\n    // Debounce\n    if (last_click_point == click_point || diff.count() < 0.05)\n    {\n        return ;\n    }\n\n    cout << \"Left mouse button is clicked while pressing CTRL key - position (\" << x << \", \" << y << \")\" << endl;\n\n    points.push_back(click_point.cast<double>() / scale);\n    fit_and_draw_spline<QuinticHermiteSpline<2>>();\n\n    last_click_time = std::chrono::steady_clock::now();\n    last_click_point = click_point;\n}\n\nint main(int argc, char **argv)\n{\n    namedWindow(WINDOW1, 1);\n    setMouseCallback(WINDOW1, click_callback, NULL);\n\n    cout << \"Click on a spot with the left mouse button and hold down CTRL to add a point to the spline.\" << endl;\n\n    imshow(WINDOW1, frame);\n    waitKey(0);\n\n    fit_and_draw_spline<CubicHermiteSpline<2>>();\n    waitKey(0);\n\n    return 0;\n}\n", "meta": {"hexsha": "bef2aed80a1f475e2d545f5ee434375a51dae2ab", "size": 2306, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "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": "main.cpp", "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": "main.cpp", "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": 24.0208333333, "max_line_length": 128, "alphanum_fraction": 0.6474414571, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303384097947, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.5007300191563031}}
{"text": "// Copyright (c) 2017 Graphcore Ltd. All rights reserved.\n\n#ifndef poplibs_test_Rnn_hpp\n#define poplibs_test_Rnn_hpp\n\n/**\n * Functions to compute forward, backward and weight update phases of a Vanilla\n * RNN\n */\n\n#include <boost/multi_array.hpp>\n#include <popnn/NonLinearityDef.hpp>\n\nnamespace poplibs_test {\nnamespace rnn {\n\n/**\n * Computes the forward non-recursive part of the RNN\n *\n * Dimensions:\n *  x:\n *  [sequence][batch][input channel]\n * weights:\n *  [input channel][output channel]\n * y:\n *  [sequence][batch][output channel]\n *\n */\nvoid forwardWeightInput(const boost::multi_array_ref<double, 3> x,\n                        const boost::multi_array_ref<double, 2> weights,\n                        const boost::multi_array_ref<double, 3> y);\n\n/**\n * Computes the recursive part of a RNN. The sequence length is derived from the\n * input x. The initial value of the output isis in yInit.\n *\n * sequence_length = x.shape()[0]\n *\n * for (s = 0; s != sequence_length; ++s) {\n *   yPrev = s == 0 ? yInit : y(s - 1, :);\n *   y(s, :) = NonLinearity(weights * yPrev + x(s, :) + bias)\n * }\n *\n * Dimensions:\n *  x:\n *  [sequence][batch][output channel]\n *  yInit:\n *  [batch][output channel]\n *  weights:\n *  [input channel][output channel]\n *  bias:\n *  [output channel]\n *  y:[sequence][batch][output channel]\n */\nvoid forwardIterate(const boost::multi_array_ref<double, 3> x,\n                    const boost::multi_array_ref<double, 2> yInit,\n                    const boost::multi_array_ref<double, 2> weights,\n                    const boost::multi_array_ref<double, 1> bias,\n                    boost::multi_array_ref<double, 3> y,\n                    popnn::NonLinearityType nonLinearityType);\n\n/**\n * Computes the backward pass of a RNN sequence.\n *\n * Loss gradients are computed at the summer and at the input in case these need\n * to be backpropagated to previous layers.\n *\n * Dimensions:\n * acts:\n * [sequence][batch][output channel]\n * nextLayerGrads:\n * [sequence][batch][output channel]\n * weightsInput:\n * [input channel][output channel]\n * weightsOutput:\n * [output channel][output channel]\n * prevLayerGrads:\n * [sequence][batch][input channel]\n * gradientSum:\n * [sequence][batch][output channel]\n */\nvoid backward(const boost::multi_array_ref<double, 3> acts,\n              const boost::multi_array_ref<double, 3> nextLayerGrads,\n              const boost::multi_array_ref<double, 2> weightsInput,\n              const boost::multi_array_ref<double, 2> weightsFeedback,\n              boost::multi_array_ref<double, 3> prevLayerGrads,\n              boost::multi_array_ref<double, 3> gradientSum,\n              popnn::NonLinearityType nonLinearityType);\n\n/**\n * Compute the parameter deltas for the whole sequence of an RNN\n *\n * The deltas are computed for all the parameters across sequence steps and\n * batch elements.\n *\n * Dimensions:\n * actsIn:\n * [sequence][batch][input channel]\n * initState:\n * [batch][output channel]\n * actsOut:\n * [sequence][batch][output channel]\n * gradientSum:\n * [sequence][batch][output channel]\n * weightsInputDeltas\n * [input channel][output channel]\n * weightsFeedbackDeltas\n * [output channel][output channel]\n * biasesDeltas\n * [output channel]\n */\nvoid paramUpdate(const boost::multi_array_ref<double, 3> actsIn,\n                 const boost::multi_array_ref<double, 2> initState,\n                 const boost::multi_array_ref<double, 3> actsOut,\n                 const boost::multi_array_ref<double, 3> gradientSum,\n                 boost::multi_array_ref<double, 2> weightsInputDeltas,\n                 boost::multi_array_ref<double, 2> weightsFeedbackDeltas,\n                 boost::multi_array_ref<double, 1> biasesDeltas);\n\n} // End namespace rnn.\n} // End namespace poplibs_test.\n\n#endif // poplibs_test_Rnn_hpp\n", "meta": {"hexsha": "d3247635c0835c2c810a2c433997010ef0afe398", "size": 3779, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/poplibs_test/Rnn.hpp", "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": "include/poplibs_test/Rnn.hpp", "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": "include/poplibs_test/Rnn.hpp", "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": 30.4758064516, "max_line_length": 80, "alphanum_fraction": 0.6596983329, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5007300175938857}}
{"text": "#ifndef BOOST_METAPARSE_GETTING_STARTED_10_HPP\r\n#define BOOST_METAPARSE_GETTING_STARTED_10_HPP\r\n\r\n// Automatically generated header file\r\n\r\n// Definitions before section 9\r\n#include \"9.hpp\"\r\n\r\n// Definitions of section 9\r\n#include <boost/mpl/negate.hpp>\r\n\r\nusing unary_exp1 = \r\n foldr_start_with_parser< \r\n   minus_token, \r\n   int_token, \r\n   boost::mpl::lambda<boost::mpl::negate<boost::mpl::_1>>::type \r\n >;\r\n\r\nusing mult_exp4 = \r\n foldl_start_with_parser< \r\n   sequence<one_of<times_token, divides_token>, unary_exp1>, \r\n   unary_exp1, \r\n   boost::mpl::quote2<binary_op> \r\n >;\r\n\r\nusing exp_parser18 = \r\n build_parser< \r\n   foldl_start_with_parser< \r\n     sequence<one_of<plus_token, minus_token>, mult_exp4>, \r\n     mult_exp4, \r\n     boost::mpl::quote2<binary_op> \r\n   > \r\n >;\r\n\r\n// query:\r\n//    exp_parser18::apply<BOOST_METAPARSE_STRING(\"---13\")>::type\r\n\r\n// query:\r\n//    exp_parser18::apply<BOOST_METAPARSE_STRING(\"13\")>::type\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "6811b599b527b15c71371e29b3ef4179e4a15791", "size": 948, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/getting_started/10.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": 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/metaparse/example/getting_started/10.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": "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/metaparse/example/getting_started/10.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": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 22.0465116279, "max_line_length": 65, "alphanum_fraction": 0.6877637131, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5007300175938857}}
{"text": "#include <armadillo>\n#include <complex>\n#include <fftw3.h>\n\nstruct FilterWorker\n{\n    //Members\n    const int nwin;       //Window size for data\n    const int npad;       //Zero padding for the FFTs\n\n    //Filter parameters\n    const float alpha;      //Power of spectral filter\n    const float beta;       //Strength of spectral filter\n    const float lowpass;    //Wavelength of low pass filter\n\n\n    //Private arrays\n    arma::cx_fmat chip;      //Chip of data\n    arma::cx_fmat SP;        //Spectral filter matrix\n    arma::cx_fmat LP;        //Low pass filter matrix\n    arma::cx_fmat  GW;        //Gaussian smoothing window\n    arma::cx_fmat work;       //Temporary arrays\n    arma::cx_fmat workpad;    \n\n\n    //Private plans\n    fftwf_plan fwdplan;         //Stores forward plan\n    fftwf_plan invplan;         //Stores inverse plan\n\n    fftwf_plan fwdpadplan;      //FFT with padding\n    fftwf_plan invpadplan;      //IFFT with padding\n\n    //Functions\n    inline int nfft()     //Sum of data window + padding\n    {\n        return npad + nwin;\n    };\n\n    inline int nfftpad()    //Sum of data window + padding + gaussian padding\n    {\n        return nfft() + 8;\n    };\n\n    inline void setupPlans();     //Set up FFT plans\n    inline void destroyPlans();   //Destroy FFT plans\n    inline void setupLowPass();   //Setup Butterwortjh filter\n    inline void setupGaussian();  //Setup Gaussian window\n    inline void filter();         //Do the actual filtering\n\n    inline void zeros()\n    {\n        SP.zeros();\n        chip.zeros();\n    };\n\n    //Constructor\n    FilterWorker(int nwin_,int npad_, float a_, float b_, float l_):\n        nwin(nwin_),\n        npad(npad_),\n        alpha(a_),\n        beta(b_),\n        lowpass(l_),\n        chip(npad_ + nwin_, npad_ + nwin_),\n        SP(npad_ + nwin_, npad_ + nwin_),\n        LP(npad_ + nwin_, npad_ + nwin_),\n        GW(npad_ + nwin_ + 8, npad_ + nwin_ + 8),\n        work(npad_ + nwin_, npad_ + nwin_),\n        workpad(npad_ + nwin_ + 8, npad_ + nwin_ + 8)\n    {\n        setupPlans();\n        setupLowPass();\n        setupGaussian();\n    };\n\n    //Destructor\n    ~FilterWorker()\n    {\n        destroyPlans();\n    };\n};\n\n//In memory setting of imaginary part to zero\ninline void setImagPartToZero(arma::cx_fmat &mat)\n{\n    arma::fmat spread  = arma::fmat( (float*) mat.memptr(), 2 * mat.n_rows,\n                                        mat.n_cols, false);\n    spread.rows(arma::regspace<arma::uvec>(1,2,spread.n_rows-1)).zeros();\n}\n\n\n//See if any element is non-zero\ninline bool hasNonZero(arma::cx_fmat &mat)\n{\n    arma::fvec spread = arma::fvec( (float*) mat.memptr(), 2*mat.n_rows*mat.n_cols, false);\n    return arma::any(spread);\n}\n\n\n//Find median of complex matrix\ninline std::complex<float> findMedian(arma::cx_fmat &mat)\n{\n    arma::cx_fvec spread = arma::cx_fvec( (std::complex<float>*) mat.memptr(), mat.n_rows*mat.n_cols, false);\n    return arma::median(spread);\n}\n\n//FFTshift to handline padding. Not to confuse with actual FFTshift.\ninline void FFTrepack(arma::cx_fmat &src, arma::cx_fmat &dst, int nsize)\n{\n    dst.zeros();\n    int halfsize = nsize/2;\n\n    //Quad BR to TL\n    dst.submat(0,0, halfsize - 1, halfsize-1) = src.submat(halfsize, halfsize, nsize-1, nsize-1);\n    \n    //Quad TL to BR\n    dst.submat(halfsize, halfsize, nsize-1, nsize-1) = src.submat(0,0,halfsize-1, halfsize-1);\n\n    //Quad TR to BL\n    dst.submat(halfsize, 0, nsize-1, halfsize-1) = src.submat(0, halfsize, halfsize-1, nsize-1);\n\n    //Quad BL to TR\n    dst.submat(0, halfsize, halfsize-1, nsize-1) = src.submat(halfsize, 0, nsize-1, halfsize-1);\n}\n\n//Create in place FFT plans\ninline void FilterWorker::setupPlans()\n{\n    int nsize = nfft();\n\n    int nlarge = nfftpad();\n\n    //Forward FFT plan\n    fwdplan = fftwf_plan_dft_2d(nsize, nsize, (fftwf_complex*) chip.memptr(), (fftwf_complex*) chip.memptr(), FFTW_FORWARD, FFTW_MEASURE);\n\n    //Inverse FFT plan\n    invplan = fftwf_plan_dft_2d(nsize, nsize, (fftwf_complex*) chip.memptr(), (fftwf_complex*) chip.memptr(), FFTW_BACKWARD, FFTW_MEASURE);\n\n    //Forward FFT plan for gaussian filtering\n    fwdpadplan = fftwf_plan_dft_2d(nlarge, nlarge, (fftwf_complex*) workpad.memptr(), (fftwf_complex*) workpad.memptr(), FFTW_FORWARD, FFTW_MEASURE);\n\n    //Inverse FFT plan\n    invpadplan = fftwf_plan_dft_2d(nlarge, nlarge, (fftwf_complex*) workpad.memptr(), (fftwf_complex*) workpad.memptr(), FFTW_BACKWARD, FFTW_MEASURE);\n\n\n}\n\n\n//Destroy FFT plans\ninline void FilterWorker::destroyPlans()\n{\n    fftwf_destroy_plan(fwdplan);\n    fftwf_destroy_plan(invplan);\n    fftwf_destroy_plan(fwdpadplan);\n    fftwf_destroy_plan(invpadplan);\n}\n\n\ninline void FilterWorker::setupLowPass()\n{\n    int nsize = nfft();\n    \n    if (lowpass <= 0.0f)\n    {\n        LP.zeros();\n    }\n    else\n    {\n        LP.ones();\n        float freq0 = 1.0f / lowpass;\n        for(int ii=0; ii< nsize; ii++)\n        {\n            float ff = (ii >= (nsize/2))? (ii-nsize) : ii;\n            ff /= (1.0f*nsize);\n\n            float butter = 1.0f / (1.0f + std::pow(ff/freq0, 10.0f));\n            \n//            std::cout << \"Butter: \" << ff << \" \" << std::pow(ff/lowpass, 10.0f) << \"\\n\";\n            LP.row(ii) *= std::complex<float>(butter,0.0f);\n            LP.col(ii) *= std::complex<float>(butter,0.0f);\n        }\n    }\n}\n\ninline void FilterWorker::setupGaussian()\n{\n    //gausswin(7)\n    arma::fvec gwin = {0.04393693f,0.24935221f,0.70664828f,1.0f,0.70664828f,0.24935221f,0.04393693f};\n\n    int nsize = nfftpad();\n    arma::cx_fvec padded(nsize);\n    padded.zeros();\n\n    //Wrap around\n    for (int ii=0; ii<4; ii++)\n        padded[ii].real(gwin[3+ii]);\n\n    for (int ii=0; ii<3;ii++)\n        padded[nsize-3+ii].real(gwin[ii]);\n\n\n    //Symmetric 2D from 1D array\n    workpad.ones();\n    for (int ii=0; ii<nsize; ii++)\n    {\n        workpad.row(ii) *= padded[ii];\n        workpad.col(ii) *= padded[ii];\n    }\n\n    //chip.submat(0,0,3,3).print();\n\n    //Convert to spectra and store\n    fftwf_execute(fwdpadplan);\n    GW = workpad/(1.0f * nsize * nsize);\n    workpad.zeros();\n\n}\n\n\n//Assumes that data has already been copied into the chip\ninline void FilterWorker::filter()\n{\n    int nsize = nfft();\n    int nlarge = nfftpad();\n\n\n    //Zero padding\n    chip.tail_cols(npad).zeros();\n    chip.tail_rows(npad).zeros();\n\n    //If chip is empty, skip all processing\n    bool status = hasNonZero(chip);\n    if (!status)\n    {\n        chip.zeros();\n        return;\n    }\n\n    //If spectral component is desired.\n    if (beta > 0.0f)\n    {\n\n        //Execute FFT\n        fftwf_execute(fwdplan);\n\n        //Copy to temporary array\n        work.zeros();\n        work.set_real(arma::abs(chip));\n\n        //Execute FFTshift\n        FFTrepack(work, workpad, work.n_rows);\n\n        //convert abs value of spectra to time domain\n        fftwf_execute(fwdpadplan);\n\n        //multiply with gaussian spectra \n        workpad %= GW;\n\n        //Inverse FFT to complete convolution\n        fftwf_execute(invpadplan);\n\n        //Execute IFFTshift\n        FFTrepack(workpad, work, work.n_rows);\n\n\n        //Setting imaginary part to zero\n        setImagPartToZero(work);\n\n        //Compute median\n        std::complex<float> median = findMedian(work);\n//        std::cout << \"Median = \" << median << \"\\n\";\n\n        //Scale by median if needed\n        if (median != 0.0f)\n        {\n            work /= median;\n        }\n\n        //Raise to power\n        work = arma::pow(work, alpha);\n        work -= std::complex<float>(1.0f,0.0f);\n\n\n        for(int ii=0; ii< work.n_elem; ii++)\n        {\n            float val = work[ii].real();\n            val = (val > 0.0f)? val: 0.0f;\n            work[ii].real(val);\n        }\n\n        work *= beta;\n    }\n    else\n    {\n        work.zeros();\n    }\n\n    //Combine low pass and spectral component here\n    chip %= (work + LP)/(1.0f * nsize * nsize);\n\n    /*std::cout << \"Start \\n\";\n    chip.submat(0,0,4,4).print();\n    std::cout << \"Mid \\n\";\n    chip.submat(13,13,17,17).print();\n    std::cout << \"End \\n\";\n    chip.submat(27,27,31,31).print();*/\n\n\n    //Perform inverse FFT\n    fftwf_execute(invplan);\n\n    return;\n}\n \n", "meta": {"hexsha": "241fc43698f627a957151349e1004d059265749c", "size": 8094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fringe/filter.hpp", "max_stars_repo_name": "piyushrpt/fringe", "max_stars_repo_head_hexsha": "63388b96b98940d84f981899f955cdb4382a2c71", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T18:57:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:35:53.000Z", "max_issues_repo_path": "include/fringe/filter.hpp", "max_issues_repo_name": "piyushrpt/fringe", "max_issues_repo_head_hexsha": "63388b96b98940d84f981899f955cdb4382a2c71", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2020-04-12T12:11:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T06:00:21.000Z", "max_forks_repo_path": "include/fringe/filter.hpp", "max_forks_repo_name": "piyushrpt/fringe", "max_forks_repo_head_hexsha": "63388b96b98940d84f981899f955cdb4382a2c71", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2020-03-29T14:39:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T02:04:27.000Z", "avg_line_length": 25.7770700637, "max_line_length": 150, "alphanum_fraction": 0.5878428466, "num_tokens": 2432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.5007091406726385}}
{"text": "\n\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n#include <string>\n#include <boost/algorithm/string.hpp>\n\n#include \"projectrtpsoundfile.h\"\n#include \"projectrtptonegen.h\"\n\n\n/*!md\nWe need to be able to generate tones. This is following the standard: https://www.itu.int/dms_pub/itu-t/opb/sp/T-SP-E.180-2010-PDF-E.pdf. Looping will be handled by soundsoup. So this section only needs to handle one cycle of the tone. We allocate memory required to generate the tone at the sample rate but not completley!\n\nOur goal is to be efficient, so we do not generate tis on the fly - most tones will be generated into wav files and played when required.\n\nIf we want to play a tone continuously we should find a nicely looped file (e.g 1S will mean all frequencies in the file will hit zero at the end of the file). This would simplify our generation.\n\nIn the standard we have definitions such as:\n\nUnited Kingdom of Great Britain\nand Northern Ireland\nBusy tone - 400 0.375 on 0.375 off\nCongestion tone - 400 0.4 on 0.35 off 0.225 on 0.525 off\nDial tone - 50//350+440 continuous\nNumber unobtainable tone - 400 continuous\nPay tone - 400 0.125 on 0.125 off\nPayphone recognition tone - 1200/800 0.2 on 0.2 off 0.2 on 2.0 off\nRinging tone - 400+450//400x25//400x16 2/3 0.4 on 0.2 off 0.4 on 2.0 off\n\ni.e. Tone - Frequency - Cadence\n\nThe frequency is\n\nFrequency in Hz:\nf1\u00d7f2 f1 is modulated by f2\nf1+f2 the juxtaposition of two frequencies f1 and f2 without modulation\nf1/f2 f1 is followed by f2\nf1//f2 in some exchanges frequency f1 is used and in others frequency f2 is used.\nCadence in seconds: ON \u2013 OFF\n\nTry to keep our definitions as close to the standard. We also have to introduce some other items:\n\n* Amplitude\n* Change (in frequency or amplitude) - frequency can be handled by modulated\n\nTake ringing tone:\n\n400+450//400x25//400x16 2/3 0.4 on 0.2 off 0.4 on 2.0 off\n\nWe can ignore the // in our definition as we can simply choose the most common one.\nSo either 400+450 or 400x25\nThree does not appear ot be anything in the standard relating to the 2/3?\n\nAmplitude can be introduced by *\nso\n\n400+450 becomes 400+450*0.75 (every frequency will have its amplitude reduced).\n400x25*0.75 is then also suported.\n\nIncreasing tones such as:\n950/1400/1800\n\nCadence\n950/1400/1800/0:333/333/333/1000\nNote, we have introduced a final /0 to indicate silence. The cadences will iterated through for every / in the frequency list and is in mS (the standard lists in seconds). We don't need to support loops as soundsoup supports loops.\nFor:\n950/1400/1800/0:333\nMeans each section will be 333mS.\n\nChange\n400+450*0.75~0 will reduce the amplitude from 0.75 to 0 during that cadence period\n400~450 will increase the frequency during that cadence period\n\nNote 400+450x300 is not supported.\n\n*/\n\nstatic void gentone( int16_t *outbuffer, int sizeofblock, double startfrequency, double endfrequency, double startamp, double endamp, int samplerate )\n{\n  if( 0 == startfrequency && 0 == endfrequency ) return;\n\n  double angle;\n  double ampatpos = startamp;\n  double amppersample = ( endamp - startamp ) / sizeofblock;\n  double freqpersample = ( endfrequency - startfrequency ) / sizeofblock;\n  double frequencyatpos = startfrequency;\n  if( 0 == startfrequency )\n  {\n    angle = 0;\n  }\n  else\n  {\n    angle = ( 2 * M_PI ) / ( double ) samplerate * startfrequency;\n  }\n\n  for( int i = 0; i < sizeofblock; i++ )\n  {\n    *outbuffer += static_cast< int16_t >( ( sin( angle * i ) * SHRT_MAX * ampatpos ) );\n    outbuffer++;\n\n    ampatpos += amppersample;\n    frequencyatpos += freqpersample;\n\n    if( 0 == frequencyatpos )\n    {\n      angle = 0;\n    }\n    else\n    {\n      angle = ( 2 * M_PI ) / ( double ) samplerate * frequencyatpos;\n    }\n  }\n}\n\n\nstatic void gen( std::string tone, std::string filename )\n{\n  vectorofstrings freqscadence;\n  boost::split( freqscadence, tone, boost::is_any_of( \":\" ) );\n\n  if( 2 != freqscadence.size() )\n  {\n    std::cerr << \"You must supply a cadence, eg. 400:1000\" << std::endl;\n    return;\n  }\n\n  vectorofstrings frequencies;\n  vectorofstrings cadences;\n  boost::split( frequencies, freqscadence[ 0 ], boost::is_any_of( \"/\" ) );\n  boost::split( cadences, freqscadence[ 1 ], boost::is_any_of( \"/\" ) );\n\n  uint8_t *readbuffer = nullptr;\n  wavheader outwavheader;\n  initwav( &outwavheader );\n\n  /* 1. Calculate total time */\n  vectorofstrings::iterator it;\n  vectorofstrings cadenceparts;\n  int cadencepos = 0;\n  int cadencetotal = 0;\n  for( it = frequencies.begin(); it != frequencies.end(); it++ )\n  {\n    cadencetotal += std::atoi( cadences[ cadencepos ].c_str() );\n    cadencepos = ( cadencepos + 1 ) % cadences.size();\n  }\n\n  std::cout << \"Total time is \" << cadencetotal << \"mS\" << std::endl;\n\n  /* 2. Allocate enough memory */\n  outwavheader.subchunksize = cadencetotal * outwavheader.sample_rate / 1000 * 2 /* 2 bytes per sample */;\n  outwavheader.chunksize = outwavheader.subchunksize + 36;\n\n  readbuffer = new uint8_t[ outwavheader.chunksize ];\n  memset( readbuffer, 0, outwavheader.chunksize );\n\n  /* 3. Generate tones */\n  int pos = 0;\n  cadencepos = 0;\n  for( it = frequencies.begin(); it != frequencies.end(); it++ )\n  {\n    /* Current cadence. */\n    int cadence = std::atoi( cadences[ cadencepos ].c_str() );\n    cadencepos = ( cadencepos + 1 ) % cadences.size();\n\n    int16_t *outbuffer = ( int16_t * ) &readbuffer[ pos * 2 ];\n    int sizeofblock = outwavheader.sample_rate * cadence / 1000 /*mS*/;\n\n    /* current frequency */\n    /* *it could be 400+450 or or 400x25 450+450*0.75 or 450~480 or 450+450*0.75~1 */\n    vectorofstrings freqamp;\n    boost::split( freqamp, *it, boost::is_any_of( \"*\" ) );\n    double startamp = 1;\n    double endamp = 1;\n    if( freqamp.size() > 1 )\n    {\n      vectorofstrings ampfromto;\n      boost::split( ampfromto, freqamp[ 1 ], boost::is_any_of( \"~\" ) );\n      startamp = std::atof( ampfromto[ 0 ].c_str() );\n      endamp = startamp;\n      if( ampfromto.size() > 1 )\n      {\n        endamp = std::atof( ampfromto[ 1 ].c_str() );\n      }\n    }\n    vectorofstrings freqparts;\n    boost::split( freqparts, freqamp[ 0 ], boost::is_any_of( \"+x~\" ) );\n\n    double startfreq = -1;\n    double endfreq = -1;\n\n    std::size_t found = freqamp[ 0 ].find_first_of( \"+x~\" );\n    if( std::string::npos == found )\n    {\n      startfreq = std::atof( freqparts[ 0 ].c_str() );\n      gentone( outbuffer, sizeofblock, startfreq, startfreq, startamp, endamp, outwavheader.sample_rate );\n      goto continueloop;\n    }\n    else\n    {\n      switch( freqamp[ 0 ][ found ] )\n      {\n        case '+':\n        {\n          for( auto freqit = freqparts.begin(); freqit != freqparts.end(); freqit++ )\n          {\n            startfreq = std::atof( freqit->c_str() );\n            gentone( outbuffer, sizeofblock, startfreq, startfreq, startamp, endamp, outwavheader.sample_rate );\n          }\n          break;\n        }\n        case '~':\n        {\n          startfreq = std::atof( freqparts[ 0 ].c_str() );\n          endfreq = std::atof( freqparts[ 1 ].c_str() );\n          gentone( outbuffer, sizeofblock, startfreq, endfreq, startamp, endamp, outwavheader.sample_rate );\n          break;\n        }\n      }\n    }\n\ncontinueloop:\n    pos += sizeofblock;\n  }\n\n\n  /* Write */\n  int file = open( filename.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR );\n  __off_t position = lseek( file, 0, SEEK_END );\n  if( 0 == position )\n  {\n    write( file, &outwavheader, sizeof( wavheader ) );\n    write( file, readbuffer, outwavheader.chunksize );\n  }\n  else\n  {\n    wavheader currentheader;\n    lseek( file, 0, SEEK_SET );\n    read( file, &currentheader, sizeof( wavheader ) );\n    lseek( file, 0, SEEK_END );\n\n    if( currentheader.audio_format == outwavheader.audio_format &&\n          currentheader.sample_rate == outwavheader.sample_rate )\n    {\n      /* Ok, good enough! */\n      currentheader.chunksize += outwavheader.chunksize;\n      currentheader.subchunksize += outwavheader.subchunksize;\n\n      lseek( file, 0, SEEK_SET );\n      write( file, &currentheader, sizeof( wavheader ) );\n      lseek( file, 0, SEEK_END );\n      write( file, readbuffer, outwavheader.chunksize );\n    }\n    else\n    {\n      std::cerr << \"File format to append should be the same\" << std::endl;\n    }\n  }\n\n  /* Clean up */\n  if( nullptr != readbuffer )\n  {\n    delete[] readbuffer;\n  }\n\n  close( file );\n}\n\n/*!md\n## gentone\nFor test purposes only. Generate a tone into a wav file base on the 2 params.\n*/\nvoid gentone( const char *tone, const char *file )\n{\n  gen( tone, file );\n}\n", "meta": {"hexsha": "e95b7776bd19e9dca63e90712284b9ce41a7e6c0", "size": 8488, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/projectrtptonegen.cpp", "max_stars_repo_name": "tinpotnick/projectrtp", "max_stars_repo_head_hexsha": "6f3b6ea651addc1a90339debcec77f6071f6d3e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/projectrtptonegen.cpp", "max_issues_repo_name": "tinpotnick/projectrtp", "max_issues_repo_head_hexsha": "6f3b6ea651addc1a90339debcec77f6071f6d3e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-07-12T14:21:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T14:43:52.000Z", "max_forks_repo_path": "src/projectrtptonegen.cpp", "max_forks_repo_name": "tinpotnick/projectrtp", "max_forks_repo_head_hexsha": "6f3b6ea651addc1a90339debcec77f6071f6d3e8", "max_forks_repo_licenses": ["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.3142857143, "max_line_length": 323, "alphanum_fraction": 0.6598727615, "num_tokens": 2530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.5007091367043756}}
{"text": "#include \"graph.hpp\"\n\n#include <unordered_map>\n#include <filesystem>\n#include <limits>\n\n#include <boost/serialization/unordered_map.hpp>\n\n#include \"utils.hpp\"\n\nnamespace graphs {\nbool Graph::serialize(const fs::path& filename) const {\n    auto cname = filename;\n    return ::graphs::serialize(cname.concat(\"-gph.dmp\"), m_data);\n}\n\nbool Graph::deserialize(const fs::path& filename) {\n    auto cname = filename;\n    cname.concat(\"-gph.dmp\");\n    if (!std::filesystem::exists(cname)) { return false; }\n    return ::graphs::deserialize(cname, m_data);\n}\n} // namespace graphs\n\nnamespace graphs {\nbool Graph::add_edge_one_way(Edge&& e, Distance d) noexcept {\n    auto[from, to] = e;\n    if (from == to) { return false; }\n    return m_data[from].insert({ to, d }).second;\n}\n\nbool Graph::add_edge_two_way(Edge&& e, Distance d) noexcept {\n    auto[from, to] = e;\n    if (from == to) { return false; }\n    return m_data[from].insert({ to, d }).second && m_data[to].insert({ from, d }).second;\n}\n\nauto Graph::dijkstra(Node s) const -> std::pair<ShortestPaths, Trail> {\n    constexpr auto INF = std::numeric_limits<double>::max();\n\n    std::unordered_map<Node, Distance> distances;\n    std::set<std::pair<Distance, Node>> set;\n    std::unordered_map<Node, Node> previous;\n\n    for (const auto&[node, _]: nodes()) { distances[node] = INF; }\n\n    distances[s] = 0;\n    set.insert({ distances[s], s });\n    while (!set.empty()) {\n        auto[_, v] = *set.begin();\n        set.erase(set.begin());\n        for (const auto& u: nodes().at(v)) {\n            auto[to, length] = u;\n            if (distances[v] + length < distances[to]) {\n                set.erase({ distances[to], to });\n                distances[to] = distances[v] + length;\n                previous[to] = v;\n                set.insert({ distances[to], to });\n            }\n        }\n    }\n\n    return { distances, previous };\n}\n} // namespace graph\n", "meta": {"hexsha": "4b08f8e2c327bfdaf324b4e62f795dfdd1dc4df7", "size": 1899, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/graph.cpp", "max_stars_repo_name": "team-cringe/graphs", "max_stars_repo_head_hexsha": "f84e2a4c3cae3b5c2493926c84536b9f81b1ed22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/graph.cpp", "max_issues_repo_name": "team-cringe/graphs", "max_issues_repo_head_hexsha": "f84e2a4c3cae3b5c2493926c84536b9f81b1ed22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graph.cpp", "max_forks_repo_name": "team-cringe/graphs", "max_forks_repo_head_hexsha": "f84e2a4c3cae3b5c2493926c84536b9f81b1ed22", "max_forks_repo_licenses": ["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.7727272727, "max_line_length": 90, "alphanum_fraction": 0.5992627699, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5006621219806718}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2012, 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#ifndef NDEBUG\n #define NDEBUG\n#endif\n\n//\n// *** System\n//\n#include <iostream>\n\n//\n// *** Boost\n//\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n\n//\n// *** ViennaCL\n//\n//#define VIENNACL_DEBUG_ALL\n#define VIENNACL_HAVE_UBLAS 1\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/coordinate_matrix.hpp\"\n#include \"viennacl/ell_matrix.hpp\"\n#include \"viennacl/hyb_matrix.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n#include \"viennacl/linalg/ilu.hpp\"\n#include \"viennacl/linalg/detail/ilu/common.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n#include \"examples/tutorial/Random.hpp\"\n#include \"examples/tutorial/vector-io.hpp\"\n\n//\n// -------------------------------------------------------------\n//\nusing namespace boost::numeric;\n//\n// -------------------------------------------------------------\n//\ntemplate <typename ScalarType>\nScalarType diff(ScalarType & s1, viennacl::scalar<ScalarType> & s2) \n{\n   if (s1 != s2)\n      return (s1 - s2) / std::max(fabs(s1), std::fabs(s2));\n   return 0;\n}\n\ntemplate <typename ScalarType>\nScalarType diff(ublas::vector<ScalarType> & v1, viennacl::vector<ScalarType> & v2)\n{\n   ublas::vector<ScalarType> v2_cpu(v2.size());\n   viennacl::backend::finish();\n   viennacl::copy(v2.begin(), v2.end(), v2_cpu.begin());\n\n   for (unsigned int i=0;i<v1.size(); ++i)\n   {\n      if ( std::max( std::fabs(v2_cpu[i]), std::fabs(v1[i]) ) > 0 )\n      {\n        //if (std::max( std::fabs(v2_cpu[i]), std::fabs(v1[i]) ) < 1e-10 )  //absolute tolerance (avoid round-off issues)\n        //  v2_cpu[i] = 0;\n        //else\n          v2_cpu[i] = std::fabs(v2_cpu[i] - v1[i]) / std::max( std::fabs(v2_cpu[i]), std::fabs(v1[i]) );\n      }\n      else\n         v2_cpu[i] = 0.0;\n      \n      if (v2_cpu[i] > 0.0001)\n      {\n        //std::cout << \"Neighbor: \"      << i-1 << \": \" << v1[i-1] << \" vs. \" << v2_cpu[i-1] << std::endl;\n        std::cout << \"Error at entry \" << i   << \": \" << v1[i]   << \" vs. \" << v2_cpu[i]   << std::endl;\n        //std::cout << \"Neighbor: \"      << i+1 << \": \" << v1[i+1] << \" vs. \" << v2_cpu[i+1] << std::endl;\n        exit(0);\n      }\n   }\n\n   return norm_inf(v2_cpu);\n}\n\n\ntemplate <typename ScalarType, typename VCL_MATRIX>\nScalarType diff(ublas::compressed_matrix<ScalarType> & cpu_matrix, VCL_MATRIX & gpu_matrix)\n{\n  typedef ublas::compressed_matrix<ScalarType>  CPU_MATRIX;\n  CPU_MATRIX from_gpu;\n   \n  viennacl::backend::finish();\n  viennacl::copy(gpu_matrix, from_gpu);\n\n  ScalarType error = 0;\n   \n  //step 1: compare all entries from cpu_matrix with gpu_matrix:\n  //std::cout << \"Ublas matrix: \" << std::endl;\n  for (typename CPU_MATRIX::const_iterator1 row_it = cpu_matrix.begin1();\n        row_it != cpu_matrix.end1();\n        ++row_it)\n  {\n    //std::cout << \"Row \" << row_it.index1() << \": \" << std::endl;\n    for (typename CPU_MATRIX::const_iterator2 col_it = row_it.begin();\n          col_it != row_it.end();\n          ++col_it)\n    {\n      //std::cout << \"(\" << col_it.index2() << \", \" << *col_it << std::endl;\n      ScalarType current_error = 0;\n      \n      if ( std::max( std::fabs(cpu_matrix(col_it.index1(), col_it.index2())), \n                      std::fabs(from_gpu(col_it.index1(), col_it.index2()))   ) > 0 )\n        current_error = std::fabs(cpu_matrix(col_it.index1(), col_it.index2()) - from_gpu(col_it.index1(), col_it.index2())) \n                          / std::max( std::fabs(cpu_matrix(col_it.index1(), col_it.index2())), \n                                      std::fabs(from_gpu(col_it.index1(), col_it.index2()))   );\n      if (current_error > error)\n        error = current_error;\n    }\n  }\n\n  //step 2: compare all entries from gpu_matrix with cpu_matrix (sparsity pattern might differ):\n  //std::cout << \"ViennaCL matrix: \" << std::endl;\n  for (typename CPU_MATRIX::const_iterator1 row_it = from_gpu.begin1();\n        row_it != from_gpu.end1();\n        ++row_it)\n  {\n    //std::cout << \"Row \" << row_it.index1() << \": \" << std::endl;\n    for (typename CPU_MATRIX::const_iterator2 col_it = row_it.begin();\n          col_it != row_it.end();\n          ++col_it)\n    {\n      //std::cout << \"(\" << col_it.index2() << \", \" << *col_it << std::endl;\n      ScalarType current_error = 0;\n      \n      if ( std::max( std::fabs(cpu_matrix(col_it.index1(), col_it.index2())), \n                      std::fabs(from_gpu(col_it.index1(), col_it.index2()))   ) > 0 )\n        current_error = std::fabs(cpu_matrix(col_it.index1(), col_it.index2()) - from_gpu(col_it.index1(), col_it.index2())) \n                          / std::max( std::fabs(cpu_matrix(col_it.index1(), col_it.index2())), \n                                      std::fabs(from_gpu(col_it.index1(), col_it.index2()))   );\n      if (current_error > error)\n        error = current_error;\n    }\n  }\n\n  return error;\n}\n\n\ntemplate< typename NumericT, typename VCL_MATRIX, typename Epsilon >\nint resize_test(Epsilon const& epsilon)\n{\n   int retval = EXIT_SUCCESS;\n   \n   ublas::compressed_matrix<NumericT> ublas_matrix(5,5);\n   VCL_MATRIX vcl_matrix;    \n   \n   ublas_matrix(0,0) = 10.0; ublas_matrix(0, 1) = 0.1; ublas_matrix(0, 2) = 0.2; ublas_matrix(0, 3) = 0.3; ublas_matrix(0, 4) = 0.4;\n   ublas_matrix(1,0) = 1.0; ublas_matrix(1, 1) = 1.1; ublas_matrix(1, 2) = 1.2; ublas_matrix(1, 3) = 1.3; ublas_matrix(1, 4) = 1.4;\n   ublas_matrix(2,0) = 2.0; ublas_matrix(2, 1) = 2.1; ublas_matrix(2, 2) = 2.2; ublas_matrix(2, 3) = 2.3; ublas_matrix(2, 4) = 2.4;\n   ublas_matrix(3,0) = 3.0; ublas_matrix(3, 1) = 3.1; ublas_matrix(3, 2) = 3.2; ublas_matrix(3, 3) = 3.3; ublas_matrix(3, 4) = 3.4;\n   ublas_matrix(4,0) = 4.0; ublas_matrix(4, 1) = 4.1; ublas_matrix(4, 2) = 4.2; ublas_matrix(4, 3) = 4.3; ublas_matrix(4, 4) = 4.4;\n   \n   viennacl::copy(ublas_matrix, vcl_matrix);\n   ublas::compressed_matrix<NumericT> other_matrix(ublas_matrix.size1(), ublas_matrix.size2());\n   viennacl::copy(vcl_matrix, other_matrix);\n   \n   std::cout << \"Checking for equality after copy...\" << std::endl;   \n    if( std::fabs(diff(ublas_matrix, vcl_matrix)) > epsilon )\n    {\n        std::cout << \"# Error at operation: equality after copy with sparse matrix\" << std::endl;\n        std::cout << \"  diff: \" << std::fabs(diff(ublas_matrix, vcl_matrix)) << std::endl;\n        return EXIT_FAILURE;\n    }\n   \n   std::cout << \"Testing resize to larger...\" << std::endl;\n   ublas_matrix.resize(10, 10, false); //ublas does not allow preserve = true here\n   ublas_matrix(0,0) = 10.0; ublas_matrix(0, 1) = 0.1; ublas_matrix(0, 2) = 0.2; ublas_matrix(0, 3) = 0.3; ublas_matrix(0, 4) = 0.4;\n   ublas_matrix(1,0) = 1.0; ublas_matrix(1, 1) = 1.1; ublas_matrix(1, 2) = 1.2; ublas_matrix(1, 3) = 1.3; ublas_matrix(1, 4) = 1.4;\n   ublas_matrix(2,0) = 2.0; ublas_matrix(2, 1) = 2.1; ublas_matrix(2, 2) = 2.2; ublas_matrix(2, 3) = 2.3; ublas_matrix(2, 4) = 2.4;\n   ublas_matrix(3,0) = 3.0; ublas_matrix(3, 1) = 3.1; ublas_matrix(3, 2) = 3.2; ublas_matrix(3, 3) = 3.3; ublas_matrix(3, 4) = 3.4;\n   ublas_matrix(4,0) = 4.0; ublas_matrix(4, 1) = 4.1; ublas_matrix(4, 2) = 4.2; ublas_matrix(4, 3) = 4.3; ublas_matrix(4, 4) = 4.4;\n   //std::cout << ublas_matrix << std::endl;\n   \n   vcl_matrix.resize(10, 10, true);\n   \n    if( std::fabs(diff(ublas_matrix, vcl_matrix)) > epsilon )\n    {\n        std::cout << \"# Error at operation: resize (to larger) with sparse matrix\" << std::endl;\n        std::cout << \"  diff: \" << std::fabs(diff(ublas_matrix, vcl_matrix)) << std::endl;\n        return EXIT_FAILURE;\n    }\n\n   ublas_matrix(5,5) = 5.5; ublas_matrix(5, 6) = 5.6; ublas_matrix(5, 7) = 5.7; ublas_matrix(5, 8) = 5.8; ublas_matrix(5, 9) = 5.9;\n   ublas_matrix(6,5) = 6.5; ublas_matrix(6, 6) = 6.6; ublas_matrix(6, 7) = 6.7; ublas_matrix(6, 8) = 6.8; ublas_matrix(6, 9) = 6.9;\n   ublas_matrix(7,5) = 7.5; ublas_matrix(7, 6) = 7.6; ublas_matrix(7, 7) = 7.7; ublas_matrix(7, 8) = 7.8; ublas_matrix(7, 9) = 7.9;\n   ublas_matrix(8,5) = 8.5; ublas_matrix(8, 6) = 8.6; ublas_matrix(8, 7) = 8.7; ublas_matrix(8, 8) = 8.8; ublas_matrix(8, 9) = 8.9;\n   ublas_matrix(9,5) = 9.5; ublas_matrix(9, 6) = 9.6; ublas_matrix(9, 7) = 9.7; ublas_matrix(9, 8) = 9.8; ublas_matrix(9, 9) = 9.9;\n   viennacl::copy(ublas_matrix, vcl_matrix);\n    \n   std::cout << \"Testing resize to smaller...\" << std::endl;\n   ublas_matrix.resize(7, 7, false); //ublas does not allow preserve = true here\n   ublas_matrix(0,0) = 10.0; ublas_matrix(0, 1) = 0.1; ublas_matrix(0, 2) = 0.2; ublas_matrix(0, 3) = 0.3; ublas_matrix(0, 4) = 0.4;\n   ublas_matrix(1,0) = 1.0; ublas_matrix(1, 1) = 1.1; ublas_matrix(1, 2) = 1.2; ublas_matrix(1, 3) = 1.3; ublas_matrix(1, 4) = 1.4;\n   ublas_matrix(2,0) = 2.0; ublas_matrix(2, 1) = 2.1; ublas_matrix(2, 2) = 2.2; ublas_matrix(2, 3) = 2.3; ublas_matrix(2, 4) = 2.4;\n   ublas_matrix(3,0) = 3.0; ublas_matrix(3, 1) = 3.1; ublas_matrix(3, 2) = 3.2; ublas_matrix(3, 3) = 3.3; ublas_matrix(3, 4) = 3.4;\n   ublas_matrix(4,0) = 4.0; ublas_matrix(4, 1) = 4.1; ublas_matrix(4, 2) = 4.2; ublas_matrix(4, 3) = 4.3; ublas_matrix(4, 4) = 4.4;\n   ublas_matrix(5,5) = 5.5; ublas_matrix(5, 6) = 5.6; ublas_matrix(5, 7) = 5.7; ublas_matrix(5, 8) = 5.8; ublas_matrix(5, 9) = 5.9;\n   ublas_matrix(6,5) = 6.5; ublas_matrix(6, 6) = 6.6; ublas_matrix(6, 7) = 6.7; ublas_matrix(6, 8) = 6.8; ublas_matrix(6, 9) = 6.9;\n\n   vcl_matrix.resize(7, 7);\n\n   //std::cout << ublas_matrix << std::endl;\n    if( std::fabs(diff(ublas_matrix, vcl_matrix)) > epsilon )\n    {\n        std::cout << \"# Error at operation: resize (to smaller) with sparse matrix\" << std::endl;\n        std::cout << \"  diff: \" << std::fabs(diff(ublas_matrix, vcl_matrix)) << std::endl;\n        retval = EXIT_FAILURE;\n    }\n    \n   ublas::vector<NumericT> ublas_vec = ublas::scalar_vector<NumericT>(ublas_matrix.size1(), 3.1415);\n   viennacl::vector<NumericT> vcl_vec(ublas_matrix.size1());\n   \n   \n  std::cout << \"Testing transposed unit lower triangular solve: compressed_matrix\" << std::endl;\n  viennacl::copy(ublas_vec, vcl_vec);\n  std::cout << \"matrix: \" << ublas_matrix << std::endl;\n  std::cout << \"vector: \" << ublas_vec << std::endl;\n  std::cout << \"ViennaCL matrix size: \" << vcl_matrix.size1() << \" x \" << vcl_matrix.size2() << std::endl;\n  \n  std::cout << \"ublas...\" << std::endl;\n  boost::numeric::ublas::inplace_solve((ublas_matrix), ublas_vec, boost::numeric::ublas::unit_lower_tag());\n  std::cout << \"ViennaCL...\" << std::endl;\n  viennacl::linalg::inplace_solve((vcl_matrix), vcl_vec, viennacl::linalg::unit_lower_tag());\n  \n  /*\n  std::list< viennacl::backend::mem_handle > multifrontal_L_row_index_arrays_;\n  std::list< viennacl::backend::mem_handle > multifrontal_L_row_buffers_;\n  std::list< viennacl::backend::mem_handle > multifrontal_L_col_buffers_;\n  std::list< viennacl::backend::mem_handle > multifrontal_L_element_buffers_;\n  std::list< std::size_t > multifrontal_L_row_elimination_num_list_;\n  \n  viennacl::vector<NumericT> multifrontal_U_diagonal_;\n  \n  viennacl::linalg::detail::multifrontal_setup_L(vcl_matrix,\n                                                  multifrontal_U_diagonal_, //dummy\n                                                  multifrontal_L_row_index_arrays_,\n                                                  multifrontal_L_row_buffers_,\n                                                  multifrontal_L_col_buffers_,\n                                                  multifrontal_L_element_buffers_,\n                                                  multifrontal_L_row_elimination_num_list_);\n  \n  viennacl::linalg::detail::multifrontal_substitute(vcl_vec,\n                                                    multifrontal_L_row_index_arrays_,\n                                                    multifrontal_L_row_buffers_,\n                                                    multifrontal_L_col_buffers_,\n                                                    multifrontal_L_element_buffers_,\n                                                    multifrontal_L_row_elimination_num_list_);\n  \n  \n  std::cout << \"ublas...\" << std::endl;\n  boost::numeric::ublas::inplace_solve((ublas_matrix), ublas_vec, boost::numeric::ublas::upper_tag());\n  std::cout << \"ViennaCL...\" << std::endl;\n  std::list< viennacl::backend::mem_handle > multifrontal_U_row_index_arrays_;\n  std::list< viennacl::backend::mem_handle > multifrontal_U_row_buffers_;\n  std::list< viennacl::backend::mem_handle > multifrontal_U_col_buffers_;\n  std::list< viennacl::backend::mem_handle > multifrontal_U_element_buffers_;\n  std::list< std::size_t > multifrontal_U_row_elimination_num_list_;\n  \n  multifrontal_U_diagonal_.resize(vcl_matrix.size1(), false);\n  viennacl::linalg::single_threaded::detail::row_info(vcl_matrix, multifrontal_U_diagonal_, viennacl::linalg::detail::SPARSE_ROW_DIAGONAL);\n  viennacl::linalg::detail::multifrontal_setup_U(vcl_matrix,\n                                                 multifrontal_U_diagonal_,\n                                                 multifrontal_U_row_index_arrays_,\n                                                 multifrontal_U_row_buffers_,\n                                                 multifrontal_U_col_buffers_,\n                                                 multifrontal_U_element_buffers_,\n                                                 multifrontal_U_row_elimination_num_list_);\n  \n  vcl_vec = viennacl::linalg::element_div(vcl_vec, multifrontal_U_diagonal_);\n  viennacl::linalg::detail::multifrontal_substitute(vcl_vec,\n                                                    multifrontal_U_row_index_arrays_,\n                                                    multifrontal_U_row_buffers_,\n                                                    multifrontal_U_col_buffers_,\n                                                    multifrontal_U_element_buffers_,\n                                                    multifrontal_U_row_elimination_num_list_);\n  */\n  for (std::size_t i=0; i<ublas_vec.size(); ++i)\n  {\n    std::cout << ublas_vec[i] << \" vs. \" << vcl_vec[i] << std::endl;\n  }\n\n  /*std::cout << \"Testing transposed unit upper triangular solve: compressed_matrix\" << std::endl;\n  viennacl::copy(ublas_vec, vcl_vec);\n  std::cout << \"matrix: \" << ublas_matrix << std::endl;\n  std::cout << \"vector: \" << ublas_vec << std::endl;\n  std::cout << \"ViennaCL matrix size: \" << vcl_matrix.size1() << \" x \" << vcl_matrix.size2() << std::endl;\n  \n  std::cout << \"ublas...\" << std::endl;\n  boost::numeric::ublas::inplace_solve((ublas_matrix), ublas_vec, boost::numeric::ublas::lower_tag());\n  std::cout << \"ViennaCL...\" << std::endl;\n  viennacl::linalg::inplace_solve((vcl_matrix), vcl_vec, viennacl::linalg::lower_tag());\n  \n  for (std::size_t i=0; i<ublas_vec.size(); ++i)\n  {\n    std::cout << ublas_vec[i] << \" vs. \" << vcl_vec[i] << std::endl;\n  }*/\n  \n  return retval;\n}\n\n\n//\n// -------------------------------------------------------------\n//\ntemplate< typename NumericT, typename Epsilon >\nint test(Epsilon const& epsilon)\n{\n  std::cout << \"Testing resizing of compressed_matrix...\" << std::endl;\n  int retval = resize_test<NumericT, viennacl::compressed_matrix<NumericT> >(epsilon);\n  if (retval != EXIT_SUCCESS)\n    return retval;\n  std::cout << \"Testing resizing of coordinate_matrix...\" << std::endl;\n  //if (retval != EXIT_FAILURE)\n  //  retval = resize_test<NumericT, viennacl::coordinate_matrix<NumericT> >(epsilon);\n  //else\n  //  return retval;\n  \n  // --------------------------------------------------------------------------            \n  ublas::vector<NumericT> rhs;\n  ublas::vector<NumericT> result;\n  ublas::compressed_matrix<NumericT> ublas_matrix;\n\n  if (!viennacl::io::read_matrix_market_file(ublas_matrix, \"../../examples/testdata/mat65k.mtx\"))\n  {\n    std::cout << \"Error reading Matrix file\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  //unsigned int cg_mat_size = cg_mat.size(); \n  std::cout << \"done reading matrix\" << std::endl;\n  \n\n  rhs.resize(ublas_matrix.size2());\n  for (std::size_t i=0; i<rhs.size(); ++i)\n  {\n    ublas_matrix(i,i) = NumericT(0.5);   // Get rid of round-off errors by making row-sums unequal to zero:\n    rhs[i] = NumericT(1) + random<NumericT>();\n  }\n\n  result = rhs;\n  \n\n  viennacl::vector<NumericT> vcl_rhs(rhs.size());\n  viennacl::vector<NumericT> vcl_result(result.size()); \n  viennacl::vector<NumericT> vcl_result2(result.size()); \n  viennacl::compressed_matrix<NumericT> vcl_compressed_matrix(rhs.size(), rhs.size());\n  viennacl::coordinate_matrix<NumericT> vcl_coordinate_matrix(rhs.size(), rhs.size());\n  viennacl::ell_matrix<NumericT> vcl_ell_matrix;\n  viennacl::hyb_matrix<NumericT> vcl_hyb_matrix;\n\n  viennacl::copy(rhs.begin(), rhs.end(), vcl_rhs.begin());\n  viennacl::copy(ublas_matrix, vcl_compressed_matrix);\n  viennacl::copy(ublas_matrix, vcl_coordinate_matrix);\n\n  // --------------------------------------------------------------------------          \n  std::cout << \"Testing products: ublas\" << std::endl;\n  result     = viennacl::linalg::prod(ublas_matrix, rhs);\n  \n  std::cout << \"Testing products: compressed_matrix\" << std::endl;\n  vcl_result = viennacl::linalg::prod(vcl_compressed_matrix, vcl_rhs);\n  \n  if( std::fabs(diff(result, vcl_result)) > epsilon )\n  {\n    std::cout << \"# Error at operation: matrix-vector product with compressed_matrix\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n  \n  //\n  // Triangular solvers for A \\ b:\n  //\n  ublas::compressed_matrix<NumericT> ublas_matrix_trans = trans(ublas_matrix); //note: triangular solvers with uBLAS show atrocious performance, while transposed solvers are quite okay. To keep execution times short, we use a double-transpose-trick in the following.\n\n  std::cout << \"Testing unit upper triangular solve: compressed_matrix\" << std::endl;\n  result = rhs;\n  viennacl::copy(result, vcl_result);\n  boost::numeric::ublas::inplace_solve(trans(ublas_matrix_trans), result, boost::numeric::ublas::unit_upper_tag());\n  viennacl::linalg::inplace_solve(vcl_compressed_matrix, vcl_result, viennacl::linalg::unit_upper_tag());\n  \n  if( std::fabs(diff(result, vcl_result)) > epsilon )\n  {\n    std::cout << \"# Error at operation: unit upper triangular solve with compressed_matrix\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n\n  std::cout << \"Testing upper triangular solve: compressed_matrix\" << std::endl;\n  result = rhs;\n  viennacl::copy(result, vcl_result);\n  boost::numeric::ublas::inplace_solve(trans(ublas_matrix_trans), result, boost::numeric::ublas::upper_tag());\n  viennacl::linalg::inplace_solve(vcl_compressed_matrix, vcl_result, viennacl::linalg::upper_tag());\n  \n  if( std::fabs(diff(result, vcl_result)) > epsilon )\n  {\n    std::cout << \"# Error at operation: upper triangular solve with compressed_matrix\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n    retval = EXIT_FAILURE;\n  }  \n  \n  std::cout << \"Testing unit lower triangular solve: compressed_matrix\" << std::endl;\n  result = rhs;\n  viennacl::copy(result, vcl_result);\n  boost::numeric::ublas::inplace_solve(trans(ublas_matrix_trans), result, boost::numeric::ublas::unit_lower_tag());\n  viennacl::linalg::inplace_solve(vcl_compressed_matrix, vcl_result, viennacl::linalg::unit_lower_tag());\n  \n  /*std::list< viennacl::backend::mem_handle > multifrontal_L_row_index_arrays_;\n  std::list< viennacl::backend::mem_handle > multifrontal_L_row_buffers_;\n  std::list< viennacl::backend::mem_handle > multifrontal_L_col_buffers_;\n  std::list< viennacl::backend::mem_handle > multifrontal_L_element_buffers_;\n  std::list< std::size_t > multifrontal_L_row_elimination_num_list_;\n  \n  viennacl::vector<NumericT> multifrontal_U_diagonal_;\n  \n  viennacl::switch_memory_domain(multifrontal_U_diagonal_, viennacl::MAIN_MEMORY);\n  multifrontal_U_diagonal_.resize(vcl_compressed_matrix.size1(), false);\n  viennacl::linalg::single_threaded::detail::row_info(vcl_compressed_matrix, multifrontal_U_diagonal_, viennacl::linalg::detail::SPARSE_ROW_DIAGONAL);\n  \n  viennacl::linalg::detail::multifrontal_setup_L(vcl_compressed_matrix,\n                                                  multifrontal_U_diagonal_, //dummy\n                                                  multifrontal_L_row_index_arrays_,\n                                                  multifrontal_L_row_buffers_,\n                                                  multifrontal_L_col_buffers_,\n                                                  multifrontal_L_element_buffers_,\n                                                  multifrontal_L_row_elimination_num_list_);\n  \n  viennacl::linalg::detail::multifrontal_substitute(vcl_result,\n                                                    multifrontal_L_row_index_arrays_,\n                                                    multifrontal_L_row_buffers_,\n                                                    multifrontal_L_col_buffers_,\n                                                    multifrontal_L_element_buffers_,\n                                                    multifrontal_L_row_elimination_num_list_);*/\n  \n  \n  if( std::fabs(diff(result, vcl_result)) > epsilon )\n  {\n    std::cout << \"# Error at operation: unit lower triangular solve with compressed_matrix\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n\n  \n  std::cout << \"Testing lower triangular solve: compressed_matrix\" << std::endl;\n  result = rhs;\n  viennacl::copy(result, vcl_result);\n  boost::numeric::ublas::inplace_solve(trans(ublas_matrix_trans), result, boost::numeric::ublas::lower_tag());\n  viennacl::linalg::inplace_solve(vcl_compressed_matrix, vcl_result, viennacl::linalg::lower_tag());\n  \n  /*std::list< viennacl::backend::mem_handle > multifrontal_U_row_index_arrays_;\n  std::list< viennacl::backend::mem_handle > multifrontal_U_row_buffers_;\n  std::list< viennacl::backend::mem_handle > multifrontal_U_col_buffers_;\n  std::list< viennacl::backend::mem_handle > multifrontal_U_element_buffers_;\n  std::list< std::size_t > multifrontal_U_row_elimination_num_list_;\n  \n  multifrontal_U_diagonal_.resize(vcl_compressed_matrix.size1(), false);\n  viennacl::linalg::single_threaded::detail::row_info(vcl_compressed_matrix, multifrontal_U_diagonal_, viennacl::linalg::detail::SPARSE_ROW_DIAGONAL);\n  viennacl::linalg::detail::multifrontal_setup_U(vcl_compressed_matrix,\n                                                 multifrontal_U_diagonal_,\n                                                 multifrontal_U_row_index_arrays_,\n                                                 multifrontal_U_row_buffers_,\n                                                 multifrontal_U_col_buffers_,\n                                                 multifrontal_U_element_buffers_,\n                                                 multifrontal_U_row_elimination_num_list_);\n  \n  vcl_result = viennacl::linalg::element_div(vcl_result, multifrontal_U_diagonal_);\n  viennacl::linalg::detail::multifrontal_substitute(vcl_result,\n                                                    multifrontal_U_row_index_arrays_,\n                                                    multifrontal_U_row_buffers_,\n                                                    multifrontal_U_col_buffers_,\n                                                    multifrontal_U_element_buffers_,\n                                                    multifrontal_U_row_elimination_num_list_);*/\n  \n  \n  if( std::fabs(diff(result, vcl_result)) > epsilon )\n  {\n    std::cout << \"# Error at operation: lower triangular solve with compressed_matrix\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n  \n/*  \n  std::cout << \"Testing lower triangular solve: compressed_matrix\" << std::endl;\n  result = rhs;\n  viennacl::copy(result, vcl_result);\n  boost::numeric::ublas::inplace_solve(ublas_matrix, result, boost::numeric::ublas::lower_tag());\n  viennacl::linalg::inplace_solve(vcl_compressed_matrix, vcl_result, viennacl::linalg::lower_tag());\n  \n  if( std::fabs(diff(result, vcl_result)) > epsilon )\n  {\n    std::cout << \"# Error at operation: lower triangular solve with compressed_matrix\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n    retval = EXIT_FAILURE;\n  }*/\n  \n  //\n  // Triangular solvers for A^T \\ b\n  //\n\n  std::cout << \"Testing transposed unit upper triangular solve: compressed_matrix\" << std::endl;\n  result = rhs;\n  viennacl::copy(result, vcl_result);\n  boost::numeric::ublas::inplace_solve(trans(ublas_matrix), result, boost::numeric::ublas::unit_upper_tag());\n  viennacl::linalg::inplace_solve(trans(vcl_compressed_matrix), vcl_result, viennacl::linalg::unit_upper_tag());\n  \n  if( std::fabs(diff(result, vcl_result)) > epsilon )\n  {\n    std::cout << \"# Error at operation: unit upper triangular solve with compressed_matrix\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n  \n  std::cout << \"Testing transposed upper triangular solve: compressed_matrix\" << std::endl;\n  result = rhs;\n  viennacl::copy(result, vcl_result);\n  boost::numeric::ublas::inplace_solve(trans(ublas_matrix), result, boost::numeric::ublas::upper_tag());\n  viennacl::linalg::inplace_solve(trans(vcl_compressed_matrix), vcl_result, viennacl::linalg::upper_tag());\n  \n  if( std::fabs(diff(result, vcl_result)) > epsilon )\n  {\n    std::cout << \"# Error at operation: upper triangular solve with compressed_matrix\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n  \n  \n  std::cout << \"Testing transposed unit lower triangular solve: compressed_matrix\" << std::endl;\n  result = rhs;\n  viennacl::copy(result, vcl_result);\n  boost::numeric::ublas::inplace_solve(trans(ublas_matrix), result, boost::numeric::ublas::unit_lower_tag());\n  viennacl::linalg::inplace_solve(trans(vcl_compressed_matrix), vcl_result, viennacl::linalg::unit_lower_tag());\n  \n  if( std::fabs(diff(result, vcl_result)) > epsilon )\n  {\n    std::cout << \"# Error at operation: unit lower triangular solve with compressed_matrix\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n  \n  std::cout << \"Testing transposed lower triangular solve: compressed_matrix\" << std::endl;\n  result = rhs;\n  viennacl::copy(result, vcl_result);\n  boost::numeric::ublas::inplace_solve(trans(ublas_matrix), result, boost::numeric::ublas::lower_tag());\n  viennacl::linalg::inplace_solve(trans(vcl_compressed_matrix), vcl_result, viennacl::linalg::lower_tag());\n  \n  if( std::fabs(diff(result, vcl_result)) > epsilon )\n  {\n    std::cout << \"# Error at operation: lower triangular solve with compressed_matrix\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n  \n\n  \n  \n  \n  \n\n  std::cout << \"Testing products: coordinate_matrix\" << std::endl;\n  result     = viennacl::linalg::prod(ublas_matrix, rhs);\n  vcl_result = viennacl::linalg::prod(vcl_coordinate_matrix, vcl_rhs);\n  \n  if( std::fabs(diff(result, vcl_result)) > epsilon )\n  {\n    std::cout << \"# Error at operation: matrix-vector product with coordinate_matrix\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n  \n  //std::cout << \"Copying ell_matrix\" << std::endl;\n  viennacl::copy(ublas_matrix, vcl_ell_matrix);\n  ublas_matrix.clear();\n  viennacl::copy(vcl_ell_matrix, ublas_matrix);// just to check that it's works\n\n\n  std::cout << \"Testing products: ell_matrix\" << std::endl;\n  vcl_result.clear();\n  vcl_result = viennacl::linalg::prod(vcl_ell_matrix, vcl_rhs);\n  //viennacl::linalg::prod_impl(vcl_ell_matrix, vcl_rhs, vcl_result);\n  //std::cout << vcl_result << \"\\n\";\n  //std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n  //std::cout << \"First entry of result vector: \" << vcl_result[0] << std::endl;\n  \n  if( std::fabs(diff(result, vcl_result)) > epsilon )\n  {\n    std::cout << \"# Error at operation: matrix-vector product with ell_matrix\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n  \n  \n  //std::cout << \"Copying hyb_matrix\" << std::endl;\n  viennacl::copy(ublas_matrix, vcl_hyb_matrix);\n  ublas_matrix.clear();\n  viennacl::copy(vcl_hyb_matrix, ublas_matrix);// just to check that it's works\n  viennacl::copy(ublas_matrix, vcl_hyb_matrix);\n\n  std::cout << \"Testing products: hyb_matrix\" << std::endl;\n  vcl_result.clear();\n  vcl_result = viennacl::linalg::prod(vcl_hyb_matrix, vcl_rhs);\n  //viennacl::linalg::prod_impl(vcl_hyb_matrix, vcl_rhs, vcl_result);\n  //std::cout << vcl_result << \"\\n\";\n  //std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n  //std::cout << \"First entry of result vector: \" << vcl_result[0] << std::endl;\n  \n  if( std::fabs(diff(result, vcl_result)) > epsilon )\n  {\n    std::cout << \"# Error at operation: matrix-vector product with hyb_matrix\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n\n  \n  // --------------------------------------------------------------------------            \n  // --------------------------------------------------------------------------            \n  NumericT alpha = static_cast<NumericT>(2.786);\n  NumericT beta = static_cast<NumericT>(1.432);\n  copy(rhs.begin(), rhs.end(), vcl_rhs.begin());\n  copy(result.begin(), result.end(), vcl_result.begin());\n  copy(result.begin(), result.end(), vcl_result2.begin());\n\n  std::cout << \"Testing scaled additions of products and vectors\" << std::endl;\n  result     = alpha * viennacl::linalg::prod(ublas_matrix, rhs) + beta * result;\n  vcl_result2 = alpha * viennacl::linalg::prod(vcl_compressed_matrix, vcl_rhs) + beta * vcl_result;\n\n  if( std::fabs(diff(result, vcl_result2)) > epsilon )\n  {\n    std::cout << \"# Error at operation: matrix-vector product (compressed_matrix) with scaled additions\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result2)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n\n  \n  vcl_result2.clear();\n  vcl_result2 = alpha * viennacl::linalg::prod(vcl_coordinate_matrix, vcl_rhs) + beta * vcl_result;\n\n  if( std::fabs(diff(result, vcl_result2)) > epsilon )\n  {\n    std::cout << \"# Error at operation: matrix-vector product (coordinate_matrix) with scaled additions\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result2)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n\n  vcl_result2.clear();\n  vcl_result2 = alpha * viennacl::linalg::prod(vcl_ell_matrix, vcl_rhs) + beta * vcl_result;\n\n  if( std::fabs(diff(result, vcl_result2)) > epsilon )\n  {\n    std::cout << \"# Error at operation: matrix-vector product (ell_matrix) with scaled additions\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result2)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n\n  vcl_result2.clear();\n  vcl_result2 = alpha * viennacl::linalg::prod(vcl_hyb_matrix, vcl_rhs) + beta * vcl_result;\n\n  if( std::fabs(diff(result, vcl_result2)) > epsilon )\n  {\n    std::cout << \"# Error at operation: matrix-vector product (hyb_matrix) with scaled additions\" << std::endl;\n    std::cout << \"  diff: \" << std::fabs(diff(result, vcl_result2)) << std::endl;\n    retval = EXIT_FAILURE;\n  }\n  \n  \n  // --------------------------------------------------------------------------            \n  return retval;\n}\n//\n// -------------------------------------------------------------\n//\nint main()\n{\n  std::cout << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << \"## Test :: Sparse Matrices\" << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << std::endl;\n\n  int retval = EXIT_SUCCESS;\n\n  std::cout << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << std::endl;\n  {\n    typedef float NumericT;\n    NumericT epsilon = static_cast<NumericT>(1E-4);\n    std::cout << \"# Testing setup:\" << std::endl;\n    std::cout << \"  eps:     \" << epsilon << std::endl;\n    std::cout << \"  numeric: float\" << std::endl;\n    retval = test<NumericT>(epsilon);\n    if( retval == EXIT_SUCCESS )\n        std::cout << \"# Test passed\" << std::endl;\n    else\n        return retval;\n  }\n  std::cout << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << std::endl;\n  \n#ifdef VIENNACL_HAVE_OPENCL\n  if( viennacl::ocl::current_device().double_support() )\n#endif\n  {\n    {\n      typedef double NumericT;\n      NumericT epsilon = 1.0E-13;\n      std::cout << \"# Testing setup:\" << std::endl;\n      std::cout << \"  eps:     \" << epsilon << std::endl;\n      std::cout << \"  numeric: double\" << std::endl;\n      retval = test<NumericT>(epsilon);\n      if( retval == EXIT_SUCCESS )\n        std::cout << \"# Test passed\" << std::endl;\n      else\n        return retval;\n    }\n    std::cout << std::endl;\n    std::cout << \"----------------------------------------------\" << std::endl;\n    std::cout << std::endl;\n  }\n#ifdef VIENNACL_HAVE_OPENCL\n  else\n    std::cout << \"No double precision support, skipping test...\" << std::endl;\n#endif\n  \n  \n  std::cout << std::endl;\n  std::cout << \"------- Test completed --------\" << std::endl;\n  std::cout << std::endl;\n  \n  return retval;\n}\n", "meta": {"hexsha": "2c6d7f06a21db564abbfab2fbef813abb65e34a6", "size": 34851, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/sparse.cpp", "max_stars_repo_name": "bollig/viennacl", "max_stars_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T08:33:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T08:33:10.000Z", "max_issues_repo_path": "tests/src/sparse.cpp", "max_issues_repo_name": "bollig/viennacl", "max_issues_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_issues_repo_licenses": ["MIT"], "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/sparse.cpp", "max_forks_repo_name": "bollig/viennacl", "max_forks_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_forks_repo_licenses": ["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.8565789474, "max_line_length": 266, "alphanum_fraction": 0.6009870592, "num_tokens": 9874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5006621171937313}}
{"text": "/*********************************************************************\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2011, Willow Garage, Inc.\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 Willow Garage 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: Ioan Sucan */\n\n// We need this to create a temporary uBLAS vector from a C-style array without copying data\n#define BOOST_UBLAS_SHALLOW_ARRAY_ADAPTOR\n#include \"ompl/base/StateSpace.h\"\n#include \"ompl/base/ProjectionEvaluator.h\"\n#include \"ompl/util/Exception.h\"\n#include \"ompl/util/RandomNumbers.h\"\n#include \"ompl/tools/config/MagicConstants.h\"\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <functional>\n#include <cmath>\n#include <cstring>\n#include <limits>\n\nompl::base::ProjectionMatrix::Matrix ompl::base::ProjectionMatrix::ComputeRandom(const unsigned int from, const unsigned int to, const std::vector<double> &scale)\n{\n    namespace nu = boost::numeric::ublas;\n\n    RNG rng;\n    Matrix projection(to, from);\n\n    for (unsigned int j = 0 ; j < from ; ++j)\n    {\n        if (scale.size() == from && fabs(scale[j]) < std::numeric_limits<double>::epsilon())\n            nu::column(projection, j) = nu::zero_vector<double>(to);\n        else\n            for (unsigned int i = 0 ; i < to ; ++i)\n                projection(i, j) = rng.gaussian01();\n    }\n\n    for (unsigned int i = 0 ; i < to ; ++i)\n    {\n        nu::matrix_row<Matrix> row(projection, i);\n        for (unsigned int j = 0 ; j < i ; ++j)\n        {\n            nu::matrix_row<Matrix> prevRow(projection, j);\n            // subtract projection\n            row -= inner_prod(row, prevRow) * prevRow;\n        }\n        // normalize\n        row /= norm_2(row);\n    }\n\n    assert(scale.size() == from || scale.size() == 0);\n    if (scale.size() == from)\n    {\n        unsigned int z = 0;\n        for (unsigned int i = 0 ; i < from ; ++i)\n        {\n            if (fabs(scale[i]) < std::numeric_limits<double>::epsilon())\n                z++;\n            else\n                nu::column(projection, i) /= scale[i];\n        }\n        if (z == from)\n            OMPL_WARN(\"Computed projection matrix is all 0s\");\n    }\n    return projection;\n}\n\nompl::base::ProjectionMatrix::Matrix ompl::base::ProjectionMatrix::ComputeRandom(const unsigned int from, const unsigned int to)\n{\n    return ComputeRandom(from, to, std::vector<double>());\n}\n\nvoid ompl::base::ProjectionMatrix::computeRandom(const unsigned int from, const unsigned int to, const std::vector<double> &scale)\n{\n    mat = ComputeRandom(from, to, scale);\n}\n\nvoid ompl::base::ProjectionMatrix::computeRandom(const unsigned int from, const unsigned int to)\n{\n    mat = ComputeRandom(from, to);\n}\n\nvoid ompl::base::ProjectionMatrix::project(const double *from, EuclideanProjection& to) const\n{\n    namespace nu = boost::numeric::ublas;\n    // create a temporary uBLAS vector from a C-style array without copying data\n    nu::shallow_array_adaptor<const double> tmp1(mat.size2(), from);\n    nu::vector<double, nu::shallow_array_adaptor<const double> > tmp2(mat.size2(), tmp1);\n    to = prod(mat, tmp2);\n}\n\nvoid ompl::base::ProjectionMatrix::print(std::ostream &out) const\n{\n    out << mat << std::endl;\n}\n\nompl::base::ProjectionEvaluator::ProjectionEvaluator(const StateSpace *space) :\n    space_(space),\n    bounds_(0), estimatedBounds_(0),\n    defaultCellSizes_(true), cellSizesWereInferred_(false)\n{\n    params_.declareParam<double>(\"cellsize_factor\", std::bind(&ProjectionEvaluator::mulCellSizes, this, std::placeholders::_1));\n}\n\nompl::base::ProjectionEvaluator::ProjectionEvaluator(const StateSpacePtr &space) :\n    space_(space.get()),\n    bounds_(0), estimatedBounds_(0),\n    defaultCellSizes_(true), cellSizesWereInferred_(false)\n{\n    params_.declareParam<double>(\"cellsize_factor\", std::bind(&ProjectionEvaluator::mulCellSizes, this, std::placeholders::_1));\n}\n\nompl::base::ProjectionEvaluator::~ProjectionEvaluator()\n{\n}\n\nbool ompl::base::ProjectionEvaluator::userConfigured() const\n{\n    return !defaultCellSizes_ && !cellSizesWereInferred_;\n}\n\nvoid ompl::base::ProjectionEvaluator::setCellSizes(const std::vector<double> &cellSizes)\n{\n    defaultCellSizes_ = false;\n    cellSizesWereInferred_ = false;\n    cellSizes_ = cellSizes;\n    checkCellSizes();\n}\n\nvoid ompl::base::ProjectionEvaluator::setBounds(const RealVectorBounds &bounds)\n{\n    bounds_ = bounds;\n    checkBounds();\n}\n\nvoid ompl::base::ProjectionEvaluator::setCellSizes(unsigned int dim, double cellSize)\n{\n    if (cellSizes_.size() >= dim)\n        OMPL_ERROR(\"Dimension %u is not defined for projection evaluator\", dim);\n    else\n    {\n        std::vector<double> c = cellSizes_;\n        c[dim] = cellSize;\n        setCellSizes(c);\n    }\n}\n\ndouble ompl::base::ProjectionEvaluator::getCellSizes(unsigned int dim) const\n{\n    if (cellSizes_.size() > dim)\n        return cellSizes_[dim];\n    OMPL_ERROR(\"Dimension %u is not defined for projection evaluator\", dim);\n    return 0.0;\n}\n\nvoid ompl::base::ProjectionEvaluator::mulCellSizes(double factor)\n{\n    if (cellSizes_.size() == getDimension())\n    {\n        std::vector<double> c(cellSizes_.size());\n        for (std::size_t i = 0 ; i < cellSizes_.size() ; ++i)\n            c[i] = cellSizes_[i] * factor;\n        setCellSizes(c);\n    }\n}\n\nvoid ompl::base::ProjectionEvaluator::checkCellSizes() const\n{\n    if (getDimension() <= 0)\n        throw Exception(\"Dimension of projection needs to be larger than 0\");\n    if (cellSizes_.size() != getDimension())\n        throw Exception(\"Number of dimensions in projection space does not match number of cell sizes\");\n}\n\nvoid ompl::base::ProjectionEvaluator::checkBounds() const\n{\n    bounds_.check();\n    if (hasBounds() && bounds_.low.size() != getDimension())\n        throw Exception(\"Number of dimensions in projection space does not match dimension of bounds\");\n}\n\nvoid ompl::base::ProjectionEvaluator::defaultCellSizes()\n{\n}\n\n/// @cond IGNORE\nnamespace ompl\n{\n    namespace base\n    {\n\n        static inline void computeCoordinatesHelper(const std::vector<double> &cellSizes, const EuclideanProjection &projection, ProjectionCoordinates &coord)\n        {\n            const std::size_t dim = cellSizes.size();\n            coord.resize(dim);\n            for (unsigned int i = 0 ; i < dim ; ++i)\n                coord[i] = (int)floor(projection(i)/cellSizes[i]);\n        }\n    }\n}\n/// @endcond\n\nvoid ompl::base::ProjectionEvaluator::inferBounds()\n{\n    if (estimatedBounds_.low.empty())\n        estimateBounds();\n    bounds_ = estimatedBounds_;\n}\n\nvoid ompl::base::ProjectionEvaluator::estimateBounds()\n{\n    unsigned int dim = getDimension();\n    estimatedBounds_.resize(dim);\n    if (dim > 0)\n    {\n        StateSamplerPtr sampler = space_->allocStateSampler();\n        State *s = space_->allocState();\n        EuclideanProjection proj(dim);\n\n        estimatedBounds_.setLow(std::numeric_limits<double>::infinity());\n        estimatedBounds_.setHigh(-std::numeric_limits<double>::infinity());\n\n        for (unsigned int i = 0 ; i < magic::PROJECTION_EXTENTS_SAMPLES ; ++i)\n        {\n            sampler->sampleUniform(s);\n            project(s, proj);\n            for (unsigned int j = 0 ; j < dim ; ++j)\n            {\n                if (estimatedBounds_.low[j] > proj[j])\n                    estimatedBounds_.low[j] = proj[j];\n                if (estimatedBounds_.high[j] < proj[j])\n                    estimatedBounds_.high[j] = proj[j];\n            }\n        }\n        // make bounding box 10% larger (5% padding on each side)\n        std::vector<double> diff(estimatedBounds_.getDifference());\n        for (unsigned int j = 0; j < dim; ++j)\n        {\n            estimatedBounds_.low[j] -= magic::PROJECTION_EXPAND_FACTOR * diff[j];\n            estimatedBounds_.high[j] += magic::PROJECTION_EXPAND_FACTOR * diff[j];\n        }\n\n        space_->freeState(s);\n    }\n}\n\nvoid ompl::base::ProjectionEvaluator::inferCellSizes()\n{\n    cellSizesWereInferred_ = true;\n    if (!hasBounds())\n        inferBounds();\n    unsigned int dim = getDimension();\n    cellSizes_.resize(dim);\n    for (unsigned int j = 0 ; j < dim ; ++j)\n    {\n        cellSizes_[j] = (bounds_.high[j] - bounds_.low[j]) / magic::PROJECTION_DIMENSION_SPLITS;\n        if (cellSizes_[j] < std::numeric_limits<double>::epsilon())\n        {\n            cellSizes_[j] = 1.0;\n            OMPL_WARN(\"Inferred cell size for dimension %u of a projection for state space %s is 0. Setting arbitrary value of 1 instead.\",\n                      j, space_->getName().c_str());\n        }\n    }\n}\n\nvoid ompl::base::ProjectionEvaluator::setup()\n{\n    typedef void(ProjectionEvaluator::*setCellSizesFunctionType)(unsigned int, double);\n    typedef double(ProjectionEvaluator::*getCellSizesFunctionType)(unsigned int) const;\n\n    if (defaultCellSizes_)\n        defaultCellSizes();\n\n    if ((cellSizes_.size() == 0 && getDimension() > 0) || cellSizesWereInferred_)\n        inferCellSizes();\n\n    checkCellSizes();\n    checkBounds();\n\n    unsigned int dim = getDimension();\n    for (unsigned int i = 0 ; i < dim ; ++i)\n        params_.declareParam<double>(\"cellsize.\" + std::to_string(i),\n                                     std::bind((setCellSizesFunctionType)&ProjectionEvaluator::setCellSizes, this, i, std::placeholders::_1),\n                                     std::bind((getCellSizesFunctionType)&ProjectionEvaluator::getCellSizes, this, i));\n}\n\nvoid ompl::base::ProjectionEvaluator::computeCoordinates(const EuclideanProjection &projection, ProjectionCoordinates &coord) const\n{\n    computeCoordinatesHelper(cellSizes_, projection, coord);\n}\n\nvoid ompl::base::ProjectionEvaluator::printSettings(std::ostream &out) const\n{\n    out << \"Projection of dimension \" << getDimension() << std::endl;\n    out << \"Cell sizes\";\n    if (cellSizesWereInferred_)\n        out << \" (inferred by sampling)\";\n    else\n    {\n        if (defaultCellSizes_)\n            out << \" (computed defaults)\";\n        else\n            out << \" (set by user)\";\n    }\n    out << \": [\";\n    for (unsigned int i = 0 ; i < cellSizes_.size() ; ++i)\n    {\n        out << cellSizes_[i];\n        if (i + 1 < cellSizes_.size())\n            out << ' ';\n    }\n    out << ']' << std::endl;\n}\n\nvoid ompl::base::ProjectionEvaluator::printProjection(const EuclideanProjection &projection, std::ostream &out) const\n{\n    out << projection << std::endl;\n}\n\nompl::base::SubspaceProjectionEvaluator::SubspaceProjectionEvaluator(const StateSpace *space, unsigned int index, const ProjectionEvaluatorPtr &projToUse) :\n    ProjectionEvaluator(space), index_(index), specifiedProj_(projToUse)\n{\n    if (!space_->isCompound())\n        throw Exception(\"Cannot construct a subspace projection evaluator for a space that is not compound\");\n    if (space_->as<CompoundStateSpace>()->getSubspaceCount() <= index_)\n        throw Exception(\"State space \" + space_->getName() + \" does not have a subspace at index \" + std::to_string(index_));\n}\n\nvoid ompl::base::SubspaceProjectionEvaluator::setup()\n{\n    if (specifiedProj_)\n        proj_ = specifiedProj_;\n    else\n        proj_ = space_->as<CompoundStateSpace>()->getSubspace(index_)->getDefaultProjection();\n    if (!proj_)\n        throw Exception(\"No projection specified for subspace at index \" + std::to_string(index_));\n\n    cellSizes_ = proj_->getCellSizes();\n    ProjectionEvaluator::setup();\n}\n\nunsigned int ompl::base::SubspaceProjectionEvaluator::getDimension() const\n{\n    return proj_->getDimension();\n}\n\nvoid ompl::base::SubspaceProjectionEvaluator::project(const State *state, EuclideanProjection &projection) const\n{\n    proj_->project(state->as<CompoundState>()->components[index_], projection);\n}\n", "meta": {"hexsha": "b45a2860a7bfe300c2eec449c17105c370854700", "size": 13166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/base/src/ProjectionEvaluator.cpp", "max_stars_repo_name": "wzxd/project-ompl", "max_stars_repo_head_hexsha": "3f7bb0e0f4840292ad7092d7380cce142de0f521", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-08T11:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-14T12:14:35.000Z", "max_issues_repo_path": "src/ompl/base/src/ProjectionEvaluator.cpp", "max_issues_repo_name": "edward0im/DesiredOrientationRRT", "max_issues_repo_head_hexsha": "c62a9cf2c472380937d0a0ab379b5f9140767f51", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-03T03:42:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-03T03:42:55.000Z", "max_forks_repo_path": "src/ompl/base/src/ProjectionEvaluator.cpp", "max_forks_repo_name": "edward0im/DesiredOrientationRRT", "max_forks_repo_head_hexsha": "c62a9cf2c472380937d0a0ab379b5f9140767f51", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-06-11T00:49:39.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-03T07:09:30.000Z", "avg_line_length": 34.6473684211, "max_line_length": 162, "alphanum_fraction": 0.6530457238, "num_tokens": 3121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5006225396605313}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.\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_RANDOM_STRATEGIES_SPHERICAL_UNIFORM_INVERSE_TRANSFORM_SAMPLING_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_RANDOM_STRATEGIES_SPHERICAL_UNIFORM_INVERSE_TRANSFORM_SAMPLING_HPP\n\n#include <random>\n#include <random>\n\n#include <boost/geometry/algorithms/equals.hpp>\n\n#include <boost/geometry/extensions/random/strategies/uniform_point_distribution.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace uniform_point_distribution\n{\n\ntemplate\n<\n    typename Point,\n    typename DomainGeometry,\n    int Dim\n>\nstruct uniform_inverse_transform_sampling\n{};\n\ntemplate\n<\n    typename Point,\n    typename DomainGeometry\n>\nstruct uniform_inverse_transform_sampling<Point, DomainGeometry, 2>\n{\n    uniform_inverse_transform_sampling(DomainGeometry const& g) {}\n    bool equals(DomainGeometry const& l_domain,\n                DomainGeometry const& r_domain,\n                uniform_inverse_transform_sampling const& r_strategy) const\n    {\n        return boost::geometry::equals(l_domain.domain(), r_domain.domain());\n    }\n    template<typename Gen>\n    Point apply(Gen& g, DomainGeometry const& d)\n    {\n        Point out;\n        typedef typename coordinate_type<Point>::type coordinate_type;\n        typedef typename select_most_precise\n            <\n                coordinate_type,\n                double\n            >::type computation_type;\n        std::uniform_real_distribution<computation_type> lon_dist(\n            get_as_radian<0, 0>(d),\n            get_as_radian<1, 0>(d));\n        set_from_radian<0>(out, lon_dist(g));\n\n        coordinate_type lat1 = get_as_radian<0, 1>(d);\n        coordinate_type lat2 = get_as_radian<1, 1>(d);\n        coordinate_type x1   = (1.0 - std::cos(lat1)) / 2,\n                        x2   = (1.0 - std::cos(lat2)) / 2;\n        std::uniform_real_distribution<computation_type> x_dist(\n            std::min(x1, x2),\n            std::max(x1, x2));\n        coordinate_type x = x_dist(g);\n        set_from_radian<1>(out, std::acos(1.0 - 2.0 * x));\n        return out;\n    }\n    void reset(DomainGeometry const&) {};\n};\n\ntemplate\n<\n    typename Point,\n    typename DomainGeometry\n>\nstruct uniform_inverse_transform_sampling<Point, DomainGeometry, 3>\n{\n    uniform_inverse_transform_sampling(DomainGeometry const& g) {}\n    bool equals(DomainGeometry const& l_domain,\n                DomainGeometry const& r_domain,\n                uniform_inverse_transform_sampling const& r_strategy) const\n    {\n        return boost::geometry::equals(l_domain.domain(), r_domain.domain());\n    }\n    template<typename Gen>\n    Point apply(Gen& g, DomainGeometry const& d)\n    {\n        uniform_inverse_transform_sampling<Point, DomainGeometry, 2> helper(d);\n        Point out = helper.apply(g, d);\n        typedef typename coordinate_type<Point>::type coordinate_type;\n        typedef typename select_most_precise\n            <\n                coordinate_type,\n                double\n            >::type computation_type;\n        coordinate_type r1 = get<0, 2>(d);\n        coordinate_type r2 = get<1, 2>(d);\n        std::uniform_real_distribution<computation_type>\n            r_dist( r1 * r1 * r1 , r2 * r2 * r2 );\n        set<2>(out, std::cbrt(r_dist(g)));\n        return out;\n    }\n    void reset(DomainGeometry const&) {};\n};\n\nnamespace services {\n\ntemplate\n<\n    typename Point,\n    typename DomainGeometry\n>\nstruct default_strategy\n<\n    Point,\n    DomainGeometry,\n    box_tag,\n    single_tag, //There are no MultiBoxes right now\n    2,\n    spherical_tag\n> : public uniform_inverse_transform_sampling<Point, DomainGeometry, 2> {\n    typedef uniform_inverse_transform_sampling<Point, DomainGeometry, 2> base;\n    using base::base;\n};\n\ntemplate\n<\n    typename Point,\n    typename DomainGeometry\n>\nstruct default_strategy\n<\n    Point,\n    DomainGeometry,\n    box_tag,\n    single_tag, //There are no MultiBoxes right now\n    3,\n    spherical_tag\n> : public uniform_inverse_transform_sampling<Point, DomainGeometry, 3> {\n    typedef uniform_inverse_transform_sampling<Point, DomainGeometry, 3> base;\n    using base::base;\n};\n\n} // namespace services\n\n}} // namespace strategy::uniform_point_distribution\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_RANDOM_STRATEGIES_SPHERICAL_UNIFORM_INVERSE_TRANSFORM_SAMPLING_HPP\n", "meta": {"hexsha": "95389f2f6fa3dd1fd6d52944dd7eecc3c7aaa532", "size": 4598, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/random/strategies/spherical/uniform_inverse_transform_sampling.hpp", "max_stars_repo_name": "BoostGSoC19/geometry", "max_stars_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T19:33:37.000Z", "max_issues_repo_path": "include/boost/geometry/extensions/random/strategies/spherical/uniform_inverse_transform_sampling.hpp", "max_issues_repo_name": "BoostGSoC19/geometry", "max_issues_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "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/geometry/extensions/random/strategies/spherical/uniform_inverse_transform_sampling.hpp", "max_forks_repo_name": "BoostGSoC19/geometry", "max_forks_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T04:54:35.000Z", "avg_line_length": 29.2866242038, "max_line_length": 102, "alphanum_fraction": 0.6857329274, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5006225345561632}}
{"text": "/* ----------------------------------------------------------------------\n *\n *                    *** Smooth Mach Dynamics ***\n *\n * This file is part of the USER-SMD package for LAMMPS.\n * Copyright (2014) Georg C. Ganzenmueller, georg.ganzenmueller@emi.fhg.de\n * Fraunhofer Ernst-Mach Institute for High-Speed Dynamics, EMI,\n * Eckerstrasse 4, D-79104 Freiburg i.Br, Germany.\n *\n * ----------------------------------------------------------------------- */\n\n/* ----------------------------------------------------------------------\n LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator\n http://lammps.sandia.gov, Sandia National Laboratories\n Steve Plimpton, sjplimp@sandia.gov\n\n Copyright (2003) Sandia Corporation.  Under the terms of Contract\n DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains\n certain rights in this software.  This software is distributed under\n the GNU General Public License.\n\n See the README file in the top-level LAMMPS directory.\n ------------------------------------------------------------------------- */\n\n#include <string.h>\n#include \"compute_smd_tlsph_stress.h\"\n#include \"atom.h\"\n#include \"update.h\"\n#include \"modify.h\"\n#include \"comm.h\"\n#include \"force.h\"\n#include \"memory.h\"\n#include \"error.h\"\n#include \"pair.h\"\n#include <Eigen/Eigen>\nusing namespace Eigen;\nusing namespace LAMMPS_NS;\n\n\n/*\n * deviator of a tensor\n */\nstatic Matrix3d Deviator(Matrix3d M) {\n\tMatrix3d eye;\n\teye.setIdentity();\n\teye *= M.trace() / 3.0;\n\treturn M - eye;\n}\n\n/* ---------------------------------------------------------------------- */\n\nComputeSMDTLSPHStress::ComputeSMDTLSPHStress(LAMMPS *lmp, int narg, char **arg) :\n\t\tCompute(lmp, narg, arg) {\n\tif (narg != 3)\n\t\terror->all(FLERR, \"Illegal compute smd/tlsph_stress command\");\n\n\tperatom_flag = 1;\n\tsize_peratom_cols = 7;\n\n\tnmax = 0;\n\tstress_array = NULL;\n}\n\n/* ---------------------------------------------------------------------- */\n\nComputeSMDTLSPHStress::~ComputeSMDTLSPHStress() {\n\tmemory->sfree(stress_array);\n}\n\n/* ---------------------------------------------------------------------- */\n\nvoid ComputeSMDTLSPHStress::init() {\n\n\tint count = 0;\n\tfor (int i = 0; i < modify->ncompute; i++)\n\t\tif (strcmp(modify->compute[i]->style, \"smd/tlsph_stress\") == 0)\n\t\t\tcount++;\n\tif (count > 1 && comm->me == 0)\n\t\terror->warning(FLERR, \"More than one compute smd/tlsph_stress\");\n}\n\n/* ---------------------------------------------------------------------- */\n\nvoid ComputeSMDTLSPHStress::compute_peratom() {\n\tinvoked_peratom = update->ntimestep;\n\tMatrix3d stress_deviator;\n\tdouble von_mises_stress;\n\n\t// grow vector array if necessary\n\n\tif (atom->nmax > nmax) {\n\t\tmemory->destroy(stress_array);\n\t\tnmax = atom->nmax;\n\t\tmemory->create(stress_array, nmax, size_peratom_cols, \"stresstensorVector\");\n\t\tarray_atom = stress_array;\n\t}\n\n\tint itmp = 0;\n\tMatrix3d *T = (Matrix3d *) force->pair->extract(\"smd/tlsph/stressTensor_ptr\", itmp);\n\tif (T == NULL) {\n\t\terror->all(FLERR, \"compute smd/tlsph_stress could not access stress tensors. Are the matching pair styles present?\");\n\t}\n\tint nlocal = atom->nlocal;\n\tint *mask = atom->mask;\n\n\tfor (int i = 0; i < nlocal; i++) {\n\t\tif (mask[i] & groupbit) {\n\t\t\tstress_deviator = Deviator(T[i]);\n\t\t\tvon_mises_stress = sqrt(3. / 2.) * stress_deviator.norm();\n\t\t\tstress_array[i][0] = T[i](0, 0); // xx\n\t\t\tstress_array[i][1] = T[i](1, 1); // yy\n\t\t\tstress_array[i][2] = T[i](2, 2); // zz\n\t\t\tstress_array[i][3] = T[i](0, 1); // xy\n\t\t\tstress_array[i][4] = T[i](0, 2); // xz\n\t\t\tstress_array[i][5] = T[i](1, 2); // yz\n\t\t\tstress_array[i][6] = von_mises_stress;\n\t\t} else {\n\t\t\tfor (int j = 0; j < size_peratom_cols; j++) {\n\t\t\t\tstress_array[i][j] = 0.0;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/* ----------------------------------------------------------------------\n memory usage of local atom-based array\n ------------------------------------------------------------------------- */\n\ndouble ComputeSMDTLSPHStress::memory_usage() {\n\tdouble bytes = size_peratom_cols * nmax * sizeof(double);\n\treturn bytes;\n}\n", "meta": {"hexsha": "d1fce57f9290fdff43ab4406ecaef1539cb800d7", "size": 3997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/USER-SMD/compute_smd_tlsph_stress.cpp", "max_stars_repo_name": "luwei0917/GlpG_Nature_Communication", "max_stars_repo_head_hexsha": "a7f4f8b526e633b158dc606050e8993d70734943", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-28T15:04:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-28T15:04:55.000Z", "max_issues_repo_path": "src/USER-SMD/compute_smd_tlsph_stress.cpp", "max_issues_repo_name": "luwei0917/GlpG_Nature_Communication", "max_issues_repo_head_hexsha": "a7f4f8b526e633b158dc606050e8993d70734943", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/USER-SMD/compute_smd_tlsph_stress.cpp", "max_forks_repo_name": "luwei0917/GlpG_Nature_Communication", "max_forks_repo_head_hexsha": "a7f4f8b526e633b158dc606050e8993d70734943", "max_forks_repo_licenses": ["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.0526315789, "max_line_length": 119, "alphanum_fraction": 0.5524143107, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.5006225345561632}}
{"text": "#include \"mex.h\"\n#include <Eigen/Dense>\n#include \"../radialpose.h\"\n#include \"../misc/ransac_estimator.h\"\n#include <RansacLib/ransac.h>\n\nusing namespace radialpose;\n\nvoid print_usage() {\n\tmexPrintf(\"[R,t,f,params] = ransac_radialpose_mex(x,X,solver,tol,[min_iter],[max_iter]);\\n\");\n\tmexPrintf(\" Solvers:\\n\");\n\tmexPrintf(\"  1 - D(1,0) - 5p -- Larsson et al.  ICCV 2019\\n\");\n\tmexPrintf(\"  2 - D(2,0) - 5p -- Larsson et al.  ICCV 2019\\n\");\n\tmexPrintf(\"  3 - D(3,0) - 5p -- Larsson et al.  ICCV 2019  (Minimal)\\n\");\n\tmexPrintf(\"  4 - D(3,3) - 8p -- Larsson et al.  ICCV 2019\\n\");\n\tmexPrintf(\"  5 - U(1,0) - 5p -- Larsson et al.  ICCV 2019\\n\");\n\tmexPrintf(\"  6 - U(0,1) - 4p -- Larsson et al.  ICCV 2017  (Minimal, Non-planar)\\n\");\n\tmexPrintf(\"  7 - U(0,1) - 4p -- Bujnak et al.   ACCV 2010  (Minimal, Non-planar)\\n\");\n\tmexPrintf(\"  8 - U(0,1) - 5p -- Kukelova et al. ICCV 2013\\n\");\n\tmexPrintf(\"  9 - U(0,2) - 5p -- Kukelova et al. ICCV 2013\\n\");\n\tmexPrintf(\" 10 - U(0,3) - 5p -- Kukelova et al. ICCV 2013  (Minimal)\\n\");\n\tmexPrintf(\" 11 - U(0,1) - 4p -- Oskarsson       arxiv 2018 (Minimal, Planar)\\n\");\n\tmexPrintf(\" 12 - N/A    - 5p -- Kukelova et al. ICCV 2013  (Minimal, 1D Radial)\\n\\n\");\n}\n\nvoid save_pose(int nlhs, mxArray *plhs[], Camera pose) {\n\tint n_sols = 1;\n\tint n_params = 0;\n\tif (n_sols > 0)\n\t\tn_params = pose.dist_params.size();\n\n\tif (nlhs >= 1) {\n\t\tplhs[0] = mxCreateDoubleMatrix(3, 3, mxREAL);\n\t\tdouble *p = mxGetPr(plhs[0]);\t\t\n\t\tfor (int j = 0; j < 9; ++j)\n\t\t\tp[j] = pose.R(j);\n\t}\n\tif (nlhs >= 2) {\n\t\tplhs[1] = mxCreateDoubleMatrix(3, 1, mxREAL);\n\t\tdouble *p = mxGetPr(plhs[1]);\t\t\n\t\tfor (int j = 0; j < 3; ++j)\n\t\t\tp[j] = pose.t(j);\n\t}\n\tif (nlhs >= 3) {\n\t\tplhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL);\n\t\tdouble *p = mxGetPr(plhs[2]);\t\t\n\t\t*p = pose.focal;\n\n\t}\n\tif (nlhs >= 4) {\n\t\tplhs[3] = mxCreateDoubleMatrix(n_params, 1, mxREAL);\n\t\tdouble *p = mxGetPr(plhs[3]);\t\t\n\t\tfor (int j = 0; j < n_params; ++j)\n\t\t\tp[j] = pose.dist_params[j];\n\t}\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n\tif (nrhs < 4 || nrhs > 7) {\n\t\tprint_usage();\n\t\tmexErrMsgTxt(\"Incorrect number of input arguments.\");\n\t}\n\tif (nlhs > 4) {\n\t\tprint_usage();\n\t\tmexErrMsgTxt(\"Wrong number of output arguments.\");\n\t}\n\n\tif (mxGetM(prhs[0]) != 2) {\n\t\tprint_usage();\n\t\tmexErrMsgTxt(\"First input must be 2 x N matrix.\");\n\t}\n\tif (mxGetM(prhs[1]) != 3) {\n\t\tprint_usage();\n\t\tmexErrMsgTxt(\"Second input must be 3 x N matrix.\");\n\t}\n\tif (mxGetN(prhs[0]) != mxGetN(prhs[1])) {\n\t\tprint_usage();\n\t\tmexErrMsgTxt(\"Not the same number of 2D points and 3D points.\");\n\t}\n\n\tdouble tol = 5.0;\n\tif (nrhs >= 4) {\n\t\ttol = mxGetScalar(prhs[3]);\n\t}\n\n\transac_lib::LORansacOptions options;\n\toptions.squared_inlier_threshold_ = tol * tol;\n\n\toptions.final_least_squares_ = true;\n\n\tif (nrhs >= 5)\n\t\toptions.min_num_iterations_ = static_cast<int>(mxGetScalar(prhs[4]));\n\tif (nrhs >= 6)\n\t\toptions.max_num_iterations_ = static_cast<int>(mxGetScalar(prhs[5]));\n\n\tdouble damp_factor = 0.0;\n\tif (nrhs >= 7) {\n\t\tdamp_factor = mxGetScalar(prhs[6]);\n\t}\n\n\tEigen::Matrix<double, 2, Eigen::Dynamic> x = Eigen::Map<Eigen::Matrix<double, 2, Eigen::Dynamic>>(mxGetPr(prhs[0]), 2, mxGetN(prhs[0]));\n\tEigen::Matrix<double, 3, Eigen::Dynamic> X = Eigen::Map<Eigen::Matrix<double, 3, Eigen::Dynamic>>(mxGetPr(prhs[1]), 3, mxGetN(prhs[1]));\n\tint solver_idx = static_cast<int>(mxGetScalar(prhs[2]));\n\n\transac_lib::RansacStatistics ransac_stats;\n\tint inliers = 0;\n\tCamera best_model;\n\tbest_model.R = Eigen::Matrix3d::Identity();\n\tbest_model.t = Eigen::Vector3d::Zero();\n\n\n\tif (solver_idx == 1) { // D(1,0)\t\n\t\tradialpose::larsson_iccv19::Solver<1, 0, true> estimator;\n\t\testimator.damp_factor = damp_factor;\n\t\tradialpose::RansacEstimator<larsson_iccv19::Solver<1, 0, true>> solver(x, X, estimator);\n\t\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\t\tstd::vector<Camera>,\n\t\t\tRansacEstimator<larsson_iccv19::Solver<1, 0, true>>> lomsac;\n\t\tinliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\t} else if (solver_idx == 2) { // D(2,0)\n\t\tradialpose::larsson_iccv19::Solver<2, 0, true> estimator;\n\t\testimator.damp_factor = damp_factor;\n\t\tradialpose::RansacEstimator<larsson_iccv19::Solver<2, 0, true>> solver(x, X, estimator);\n\t\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\t\tstd::vector<Camera>,\n\t\t\tRansacEstimator<larsson_iccv19::Solver<2, 0, true>>> lomsac;\n\t\tinliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\t} else if (solver_idx == 3) { // D(3,0)\n\t\tradialpose::larsson_iccv19::Solver<3, 0, true> estimator;\t\t\n\t\testimator.damp_factor = damp_factor;\n\t\tradialpose::RansacEstimator<larsson_iccv19::Solver<3, 0, true>> solver(x, X, estimator);\n\t\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\t\tstd::vector<Camera>,\n\t\t\tRansacEstimator<larsson_iccv19::Solver<3, 0, true>>> lomsac;\n\t\tinliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\t} else if (solver_idx == 4) { // D(3,3)\n\t\tradialpose::larsson_iccv19::Solver<3, 3, true> estimator;\n\t\testimator.damp_factor = damp_factor;\n\t\tradialpose::RansacEstimator<larsson_iccv19::Solver<3, 3, true>> solver(x, X, estimator);\n\t\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\t\tstd::vector<Camera>,\n\t\t\tRansacEstimator<larsson_iccv19::Solver<3, 3, true>>> lomsac;\n\t\tinliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\t} else if (solver_idx == 5) { // U(1,0)\n\t\tradialpose::larsson_iccv19::Solver<1, 0, false> estimator;\n\t\testimator.damp_factor = damp_factor;\n\t\tradialpose::RansacEstimator<larsson_iccv19::Solver<1, 0, false>> solver(x, X, estimator);\n\t\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\t\tstd::vector<Camera>,\n\t\t\tRansacEstimator<larsson_iccv19::Solver<1, 0, false>>> lomsac;\n\t\tinliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\t} else if (solver_idx == 6) { // U(0,1)\n\t\tradialpose::larsson_iccv17::NonPlanarSolver estimator;\n\t\tradialpose::RansacEstimator<larsson_iccv17::NonPlanarSolver> solver(x, X, estimator);\n\t\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\t\tstd::vector<Camera>,\n\t\t\tRansacEstimator<larsson_iccv17::NonPlanarSolver>> lomsac;\n\t\tinliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\t} else if (solver_idx == 7) {  // U(0,1)\n\t\tradialpose::bujnak_accv10::NonPlanarSolver estimator;\n\t\tradialpose::RansacEstimator<bujnak_accv10::NonPlanarSolver> solver(x, X, estimator);\n\t\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\t\tstd::vector<Camera>,\n\t\t\tRansacEstimator<bujnak_accv10::NonPlanarSolver>> lomsac;\n\t\tinliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\t} else if (solver_idx == 8) {  // U(0,1)\n\t\tradialpose::kukelova_iccv13::Solver estimator(1);\t\n\t\tradialpose::RansacEstimator<kukelova_iccv13::Solver> solver(x, X, estimator);\n\t\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\t\tstd::vector<Camera>,\n\t\t\tRansacEstimator<kukelova_iccv13::Solver>> lomsac;\n\t\tinliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\t} else if (solver_idx == 9) {  // U(0,2)\n\t\tradialpose::kukelova_iccv13::Solver estimator(2);\n\t\tradialpose::RansacEstimator<kukelova_iccv13::Solver> solver(x, X, estimator);\n\t\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\t\tstd::vector<Camera>,\n\t\t\tRansacEstimator<kukelova_iccv13::Solver>> lomsac;\n\t\tinliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\n\t} else if (solver_idx == 10) { // U(0,3)\n\t\tradialpose::kukelova_iccv13::Solver estimator(3);\n\t\tradialpose::RansacEstimator<kukelova_iccv13::Solver> solver(x, X, estimator);\n\t\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\t\tstd::vector<Camera>,\n\t\t\tRansacEstimator<kukelova_iccv13::Solver>> lomsac;\n\t\tinliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\n\t} else if (solver_idx == 11) {  // U(0,1)\n\t\tradialpose::oskarsson_arxiv18::PlanarSolver estimator;\n\t\tradialpose::RansacEstimator<oskarsson_arxiv18::PlanarSolver> solver(x, X, estimator);\n\t\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\t\tstd::vector<Camera>,\n\t\t\tRansacEstimator<oskarsson_arxiv18::PlanarSolver>> lomsac;\n\t\tinliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\n\t} else if (solver_idx == 12) {  // N/A\n\t\tradialpose::kukelova_iccv13::Radial1DSolver estimator;\n\t\tradialpose::RansacEstimator<kukelova_iccv13::Radial1DSolver> solver(x, X, estimator);\n\t\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\t\tstd::vector<Camera>,\n\t\t\tRansacEstimator<kukelova_iccv13::Radial1DSolver>> lomsac;\n\t\tsolver.use_local_opt = false;\n\t\tinliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\t} else {\n\t\tprint_usage();\n\t\tmexErrMsgTxt(\"Solver NYI.\\n\");\n\t}\n\n\tsave_pose(nlhs, plhs, best_model);\n\n}\n", "meta": {"hexsha": "39b5c522c03d578a1ad08d5eb1cb5029e009940d", "size": 8574, "ext": "cc", "lang": "C++", "max_stars_repo_path": "matlab/ransac_radialpose_mex.cc", "max_stars_repo_name": "vlarsson/radialpose", "max_stars_repo_head_hexsha": "e620fc208f573820ade6a6fe321731d0f3eb082d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T02:48:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:28:29.000Z", "max_issues_repo_path": "matlab/ransac_radialpose_mex.cc", "max_issues_repo_name": "vlarsson/radialpose", "max_issues_repo_head_hexsha": "e620fc208f573820ade6a6fe321731d0f3eb082d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-31T16:16:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T19:39:41.000Z", "max_forks_repo_path": "matlab/ransac_radialpose_mex.cc", "max_forks_repo_name": "vlarsson/radialpose", "max_forks_repo_head_hexsha": "e620fc208f573820ade6a6fe321731d0f3eb082d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-11-04T21:38:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T20:41:11.000Z", "avg_line_length": 37.9380530973, "max_line_length": 137, "alphanum_fraction": 0.6932586891, "num_tokens": 3124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.500622529451795}}
{"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_ref_snip8\r\n\r\n#include <boost/math/distributions/negative_binomial.hpp>\r\n\r\nusing namespace boost::math;\r\nusing namespace boost::math::policies;\r\n\r\ntypedef negative_binomial_distribution<\r\n      double, \r\n      policy<discrete_quantile<integer_round_nearest> > \r\n   > dist_type;\r\n   \r\n// Lower quantile rounded up:\r\ndouble x = quantile(dist_type(20, 0.3), 0.05);\r\n// Upper quantile rounded down:\r\ndouble y = quantile(complement(dist_type(20, 0.3), 0.05));\r\n\r\n//]\r\n\r\n#include <iostream>\r\n\r\nint main()\r\n{\r\n   std::cout << x << \" \" << y << std::endl;\r\n}\r\n", "meta": {"hexsha": "a7e33f94457188c649ae2aba9a08386ff1847e21", "size": 927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/policy_ref_snip8.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_ref_snip8.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_ref_snip8.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": 27.2647058824, "max_line_length": 69, "alphanum_fraction": 0.690399137, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5006225294517949}}
{"text": "#include \"rand_state.hpp\"\n#include \"pauli_product.cpp\"\n#include <armadillo>\n#include <cmath>\n#include <stdlib.h>\n\nusing namespace std;\nusing namespace arma;\n\nvoid apply_rand_gate(unsigned int q1, unsigned int q2, cx_dvec &psi)\n{\n  int x1, x2, z1, z2;\n  x1 = rand()%2;\n  x2 = rand()%2;\n  z1 = rand()%2;\n  z2 = rand()%2;\n\n  int x, z;\n  x = (x1<<q1) + (x2<<q2);\n  z = (z1<<q1) + (z2<<q2);\n\n  double theta = (double)rand() / (double)RAND_MAX * 3.14159265358979;\n\n  apply_ppr(x, z, theta, psi);\n}\n\ncx_dvec rand_haar(unsigned int n_q)\n{\n  cx_vec psi;\n  psi.randn(1<<n_q);\n  psi = normalise(psi, 2);\n  return psi;\n}\n\ncx_dvec scrambled_1d(unsigned int n_q, unsigned int depth)\n{\n  cx_vec psi;\n  psi.zeros(1<<n_q);\n  psi(0) = 1;\n  for (int d=0; d<depth; d++)\n    {\n      if (d%2==0)\n\t{\n\t  for (int i=0; i<n_q; i++)\n\t    {\n\t      if (i%2==0)\n\t\t{\n\t\t  if (i<n_q-1)\n\t\t      apply_rand_gate(i, i+1, psi);\n\t\t  //\t\t  else\n\t\t  //\t\t      apply_rand_gate(i,0, psi);\n\t\t}\n\t    }\n\t}\n      else\n\t{\n\t  for (int i=0; i<n_q; i++)\n\t    {\n\t      if (i%2==1)\n\t\t{\n\t\t  if (i<n_q-1)\n\t\t      apply_rand_gate(i, i+1, psi);\n\t\t  //\t\t  else\n\t\t  //\t\t      apply_rand_gate(i,0, psi);\n\t\t}\n\t    }\n\t}\n    }\n  return psi;\n}\n", "meta": {"hexsha": "520b9a74f0575c681b8f144520e931d289abd6bf", "size": 1181, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/rand_state.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++/rand_state.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++/rand_state.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": 16.6338028169, "max_line_length": 70, "alphanum_fraction": 0.533446232, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5005387890487143}}
{"text": "/*\n * Copyright (c) 2021. Kun Huang.\n * This Source Code Form is subject to the terms of the Apache License, v. 2.0.\n */\n\n//\n// Created by huangkun on 2021/7/9.\n//\n\n#ifndef OPENGV2_UTILITY_HPP\n#define OPENGV2_UTILITY_HPP\n\n#include <functional>\n#include <numeric>\n#include <unordered_map>\n\n#include <Eigen/Eigen>\n#include <Eigen/StdVector>\n#include <nanoflann.hpp>\n//#include <cereal/cereal.hpp>\n\nnamespace opengv2 {\n    template<typename EigenMatrixType>\n    using vectorofEigenMatrix = std::vector<EigenMatrixType, Eigen::aligned_allocator<EigenMatrixType>>;\n\n    template<typename T>\n    struct EigenMatrixCompare {\n        inline bool operator()(const T &lhs, const T &rhs) const {\n            return lhs.norm() < rhs.norm();\n        }\n    };\n\n    /**\n     * @brief Hash function for Eigen matrix and vector.\n     * The code is from `hash_combine` function of the Boost library. See\n     * http://www.boost.org/doc/libs/1_55_0/doc/html/hash/reference.html#boost.hash_combine .\n     */\n    template<typename T>\n    struct EigenMatrixHash : std::unary_function<T, size_t> {\n        std::size_t operator()(T const &matrix) const {\n            // Note that it is oblivious to the storage order of Eigen matrix (column- or\n            // row-major). It will give you the same hash value for two different matrices if they\n            // are the transpose of each other in different storage order.\n            size_t seed = 0;\n            for (size_t i = 0; i < matrix.size(); ++i) {\n                auto elem = *(matrix.data() + i);\n                seed ^= std::hash<typename T::Scalar>()(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            }\n            return seed;\n        }\n    };\n\n    /**\n     * @brief Generic functor base for use with the Eigen-nonlinear optimization\n     * toolbox. Please refer to the Eigen-documentation for further information.\n     */\n    template<typename Scalar, int NX = Eigen::Dynamic, int NY = Eigen::Dynamic>\n    struct EigenOptimizationFunctor {\n        enum {\n            InputsAtCompileTime = NX,\n            ValuesAtCompileTime = NY\n        };\n        typedef Eigen::Matrix<Scalar, InputsAtCompileTime, 1> InputType;\n        typedef Eigen::Matrix<Scalar, ValuesAtCompileTime, 1> ValueType;\n        typedef Eigen::Matrix<Scalar, ValuesAtCompileTime, InputsAtCompileTime> JacobianType;\n\n        const int m_inputs, m_values;\n\n        EigenOptimizationFunctor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\n\n        EigenOptimizationFunctor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n        int inputs() const { return m_inputs; }\n\n        int values() const { return m_values; }\n\n        // you should define that in the subclass :\n        // void operator() (const InputType& x, ValueType* v, JacobianType* _j=0) const;\n    };\n\n    struct pair_hash {\n        template<class T1, class T2>\n        std::size_t operator()(const std::pair<T1, T2> &pair) const {\n            return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);\n        }\n    };\n\n    /**\n     * @brief Fit normal distribution.\n     * @tparam T\n     * @param v\n     * @param mean\n     * @param stdev\n     */\n    template<class T>\n    inline void fitNormal(const std::vector<T> &v, T &mean, T &stdev) {\n        double sum = std::accumulate(v.begin(), v.end(), 0.0);\n        mean = sum / v.size();\n\n        std::vector<T> diff(v.size());\n        std::transform(v.begin(), v.end(), diff.begin(), [mean](T x) { return x - mean; });\n        double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);\n        stdev = std::sqrt(sq_sum / (v.size() - 1));\n    }\n}\n\nnamespace nanoflann {\n    template<typename T>\n    struct SO3DataSetAdaptor {\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        explicit SO3DataSetAdaptor(const opengv2::vectorofEigenMatrix<Eigen::Quaternion<T>> &Q_set) : QSet(Q_set) {}\n\n        const opengv2::vectorofEigenMatrix<Eigen::Quaternion<T>> &QSet;\n\n        // Must return the number of data points\n        inline size_t kdtree_get_point_count() const { return QSet.size(); }\n\n        // Returns the dim'th component of the idx'th point in the class:\n        // Since this is inlined and the \"dim\" argument is typically an immediate value, the\n        //  \"if/else's\" are actually solved at compile time.\n        inline T kdtree_get_pt(const size_t idx, const size_t dim) const {\n            return QSet[idx].coeffs()[dim];\n        }\n\n        // Optional bounding-box computation: return false to default to a standard bbox computation loop.\n        //   Return true if the BBOX was already computed by the class and returned in \"bb\" so it can be avoided to redo it again.\n        //   Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds)\n        template<class BBOX>\n        bool kdtree_get_bbox(BBOX & /* bb */) const { return false; }\n    };\n\n    template<typename num_t>\n    using SO3_KDTree = KDTreeSingleIndexAdaptor<SO3_Adaptor<num_t, SO3DataSetAdaptor<num_t>>, SO3DataSetAdaptor<num_t>, 4>;\n}\n\n/*namespace cereal {\n    template<class Archive, class Derived>\n    inline\n    typename std::enable_if<\n            traits::is_output_serializable < BinaryData < typename Derived::Scalar>, Archive>::value, void>\n\n    ::type\n    save(Archive &ar, Eigen::PlainObjectBase<Derived> const &m) {\n        typedef Eigen::PlainObjectBase<Derived> ArrT;\n        if (ArrT::RowsAtCompileTime == Eigen::Dynamic) ar(m.rows());\n        if (ArrT::ColsAtCompileTime == Eigen::Dynamic) ar(m.cols());\n        ar(binary_data(m.data(), m.size() * sizeof(typename Derived::Scalar)));\n    }\n\n    template<class Archive, class Derived>\n    inline\n    typename std::enable_if<\n            traits::is_input_serializable < BinaryData < typename Derived::Scalar>, Archive>::value, void>\n\n    ::type\n    load(Archive &ar, Eigen::PlainObjectBase<Derived> &m) {\n        typedef Eigen::PlainObjectBase<Derived> ArrT;\n        Eigen::Index rows = ArrT::RowsAtCompileTime, cols = ArrT::ColsAtCompileTime;\n        if (rows == Eigen::Dynamic) ar(rows);\n        if (cols == Eigen::Dynamic) ar(cols);\n        m.resize(rows, cols);\n        ar(binary_data(m.data(), static_cast<std::size_t>(rows * cols * sizeof(typename Derived::Scalar))));\n    }\n\n    template<class Archive, class Scalar, int Options>\n    inline void serialize(Archive &ar, ::Eigen::Quaternion<Scalar, Options> &quat) {\n        ar(make_nvp(\"w\", quat.w()), make_nvp(\"x\", quat.x()), make_nvp(\"y\", quat.y()), make_nvp(\"z\", quat.z()));\n    }\n}*/\n\n#endif //OPENGV2_UTILITY_HPP\n", "meta": {"hexsha": "f052c8c65debc2dc6cb4664351e2797370ce2d4f", "size": 6538, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/utility/include/opengv2/utility/utility.hpp", "max_stars_repo_name": "MobilePerceptionLab/EventCameraCalibration", "max_stars_repo_head_hexsha": "debd774ac989674b500caf27641b7ad4e94681e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T03:21:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T03:40:54.000Z", "max_issues_repo_path": "modules/core/utility/include/opengv2/utility/utility.hpp", "max_issues_repo_name": "MobilePerceptionLab/MultiCamCalib", "max_issues_repo_head_hexsha": "2f0e94228c2c4aea7f20c26e3e8daa6321ce8022", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-25T02:55:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T15:18:45.000Z", "max_forks_repo_path": "modules/core/utility/include/opengv2/utility/utility.hpp", "max_forks_repo_name": "MobilePerceptionLab/MultiCamCalib", "max_forks_repo_head_hexsha": "2f0e94228c2c4aea7f20c26e3e8daa6321ce8022", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-11T12:29:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T03:41:01.000Z", "avg_line_length": 37.7919075145, "max_line_length": 130, "alphanum_fraction": 0.6370449679, "num_tokens": 1649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5004151021906066}}
{"text": "#ifndef SS_MATRIX_HPP\r\n#define SS_MATRIX_HPP\r\n\r\n#include <Eigen/Dense>\r\n#include <ss/data/data.hpp>\r\n\r\n/*\r\n * This file defines convenient functions for manipulating an Eigen matrix.\r\n */\r\n\r\nnamespace SS\r\n{\r\n    typedef Eigen::MatrixXd Matrix;\r\n    typedef Eigen::VectorXd Vector;\r\n    \r\n    namespace MatrixUtils\r\n    {\r\n        // Apply a functor to every element in the matrix\r\n        template <typename F> void each(const Matrix &m, F f)\r\n        {\r\n            for (auto i = 0; i < m.rows(); i++)\r\n            {\r\n                for (auto j = 0; j < m.cols(); j++)\r\n                {\r\n                    f(i, j, m(i, j));\r\n                }\r\n            }\r\n        }\r\n\r\n        template <typename Iter> static Vector vector(const Iter &x)\r\n        {\r\n            Vector X(x.size());\r\n            \r\n            auto i = 0;\r\n            \r\n            for (const auto &t : x)\r\n            {\r\n                X(i++) = t;\r\n            }\r\n\r\n            return X;\r\n        }\r\n        \r\n        template <typename T> static Matrix matrix(const T *t, Counts n)\r\n        {\r\n            Matrix X(n, 1);\r\n\r\n            for (auto i = 0; i < n; i++, t++)\r\n            {\r\n                X(i, 0) = *t;\r\n            }\r\n            \r\n            return X;\r\n        }\r\n        \r\n        template <typename Iter> static Matrix matrix(const Iter &x)\r\n        {\r\n            Matrix X(x.size(), 1);\r\n            \r\n            auto i = 0;\r\n            \r\n            for (const auto &t : x)\r\n            {\r\n                X(i++, 0) = t;\r\n            }\r\n            \r\n            return X;\r\n        }\r\n\r\n        struct MatrixCount\r\n        {\r\n            // Row sums\r\n            Eigen::VectorXd rsums;\r\n            \r\n            // Column sums\r\n            Eigen::VectorXd csums;\r\n\r\n            // Overall sums\r\n            Real sums = 0;\r\n        };\r\n\r\n        inline MatrixCount count(const Matrix &m)\r\n        {\r\n            MatrixCount c;\r\n            \r\n            c.rsums = Eigen::VectorXd(m.rows());\r\n            c.csums = Eigen::VectorXd(m.cols());\r\n\r\n            c.rsums.setConstant(0);\r\n            c.csums.setConstant(0);\r\n            \r\n            MatrixUtils::each(m, [&](Index i, Index j, Real x)\r\n            {\r\n                c.sums += x;\r\n                c.rsums(i) += x;\r\n                c.csums(j) += x;\r\n            });\r\n            \r\n            return c;\r\n        }\r\n    }\r\n}\r\n\r\n#endif", "meta": {"hexsha": "0d679a26847564009936e82eb471be66d9808b95", "size": 2392, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stats/ss/matrix.hpp", "max_stars_repo_name": "danielnavarrogomez/Anaquin", "max_stars_repo_head_hexsha": "563dbeb25aff15a55e4309432a967812cbfa0c98", "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/stats/ss/matrix.hpp", "max_issues_repo_name": "danielnavarrogomez/Anaquin", "max_issues_repo_head_hexsha": "563dbeb25aff15a55e4309432a967812cbfa0c98", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stats/ss/matrix.hpp", "max_forks_repo_name": "danielnavarrogomez/Anaquin", "max_forks_repo_head_hexsha": "563dbeb25aff15a55e4309432a967812cbfa0c98", "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.0, "max_line_length": 76, "alphanum_fraction": 0.3704013378, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.500415093415038}}
{"text": "/* boost random/additive_combine.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: additive_combine.hpp 71018 2011-04-05 21:27:52Z steven_watanabe $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_ADDITIVE_COMBINE_HPP\n#define BOOST_RANDOM_ADDITIVE_COMBINE_HPP\n\n#include <istream>\n#include <iosfwd>\n#include <algorithm> // for std::min and std::max\n#include <boost/config.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/random/detail/config.hpp>\n#include <boost/random/detail/operators.hpp>\n#include <boost/random/detail/seed.hpp>\n#include <boost/random/linear_congruential.hpp>\n\nnamespace boost {\nnamespace random {\n\n/**\n * An instantiation of class template @c additive_combine_engine models a\n * \\pseudo_random_number_generator. It combines two multiplicative\n * \\linear_congruential_engine number generators, i.e. those with @c c = 0.\n * It is described in\n *\n *  @blockquote\n *  \"Efficient and Portable Combined Random Number Generators\", Pierre L'Ecuyer,\n *  Communications of the ACM, Vol. 31, No. 6, June 1988, pp. 742-749, 774\n *  @endblockquote\n *\n * The template parameters MLCG1 and MLCG2 shall denote two different\n * \\linear_congruential_engine number generators, each with c = 0. Each\n * invocation returns a random number\n * X(n) := (MLCG1(n) - MLCG2(n)) mod (m1 - 1),\n * where m1 denotes the modulus of MLCG1. \n */\ntemplate<class MLCG1, class MLCG2>\nclass additive_combine_engine\n{\npublic:\n    typedef MLCG1 first_base;\n    typedef MLCG2 second_base;\n    typedef typename MLCG1::result_type result_type;\n\n    // Required by old Boost.Random concept\n    BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);\n    /**\n     * Returns the smallest value that the generator can produce\n     */\n    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return 1; }\n    /**\n     * Returns the largest value that the generator can produce\n     */\n    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return MLCG1::modulus-1; }\n\n    /**\n     * Constructs an @c additive_combine_engine using the\n     * default constructors of the two base generators.\n     */\n    additive_combine_engine() : _mlcg1(), _mlcg2() { }\n    /**\n     * Constructs an @c additive_combine_engine, using seed as\n     * the constructor argument for both base generators.\n     */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(additive_combine_engine,\n        result_type, seed_arg)\n    {\n        _mlcg1.seed(seed_arg);\n        _mlcg2.seed(seed_arg);\n    }\n    /**\n     * Constructs an @c additive_combine_engine, using seq as\n     * the constructor argument for both base generators.\n     *\n     * @xmlwarning\n     * The semantics of this function are liable to change.\n     * A @c seed_seq is designed to generate all the seeds\n     * in one shot, but this seeds the two base engines\n     * independantly and probably ends up giving the same\n     * sequence to both.\n     * @endxmlwarning\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(additive_combine_engine,\n        SeedSeq, seq)\n    {\n        _mlcg1.seed(seq);\n        _mlcg2.seed(seq);\n    }\n    /**\n     * Constructs an @c additive_combine_engine, using\n     * @c seed1 and @c seed2 as the constructor argument to\n     * the first and second base generators, respectively.\n     */\n    additive_combine_engine(typename MLCG1::result_type seed1, \n                            typename MLCG2::result_type seed2)\n      : _mlcg1(seed1), _mlcg2(seed2) { }\n    /**\n     * Contructs an @c additive_combine_engine with\n     * values from the range defined by the input iterators first\n     * and last.  first will be modified to point to the element\n     * after the last one used.\n     *\n     * Throws: @c std::invalid_argument if the input range is too small.\n     *\n     * Exception Safety: Basic\n     */\n    template<class It> additive_combine_engine(It& first, It last)\n      : _mlcg1(first, last), _mlcg2(first, last) { }\n\n    /**\n     * Seeds an @c additive_combine_engine using the default\n     * seeds of the two base generators.\n     */\n    void seed()\n    {\n        _mlcg1.seed();\n        _mlcg2.seed();\n    }\n\n    /**\n     * Seeds an @c additive_combine_engine, using @c seed as the\n     * seed for both base generators.\n     */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(additive_combine_engine,\n        result_type, seed_arg)\n    {\n        _mlcg1.seed(seed_arg);\n        _mlcg2.seed(seed_arg);\n    }\n\n    /**\n     * Seeds an @c additive_combine_engine, using @c seq to\n     * seed both base generators.\n     *\n     * See the warning on the corresponding constructor.\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(additive_combine_engine,\n        SeedSeq, seq)\n    {\n        _mlcg1.seed(seq);\n        _mlcg2.seed(seq);\n    }\n\n    /**\n     * Seeds an @c additive_combine generator, using @c seed1 and @c seed2 as\n     * the seeds to the first and second base generators, respectively.\n     */\n    void seed(typename MLCG1::result_type seed1,\n              typename MLCG2::result_type seed2)\n    {\n        _mlcg1.seed(seed1);\n        _mlcg2.seed(seed2);\n    }\n\n    /**\n     * Seeds an @c additive_combine_engine with\n     * values from the range defined by the input iterators first\n     * and last.  first will be modified to point to the element\n     * after the last one used.\n     *\n     * Throws: @c std::invalid_argument if the input range is too small.\n     *\n     * Exception Safety: Basic\n     */\n    template<class It> void seed(It& first, It last)\n    {\n        _mlcg1.seed(first, last);\n        _mlcg2.seed(first, last);\n    }\n\n    /** Returns the next value of the generator. */\n    result_type operator()() {\n        result_type val1 = _mlcg1();\n        result_type val2 = _mlcg2();\n        if(val2 < val1) return val1 - val2;\n        else return val1 - val2 + MLCG1::modulus - 1;\n    }\n  \n    /** Fills a range with random values */\n    template<class Iter>\n    void generate(Iter first, Iter last)\n    { detail::generate_from_int(*this, first, last); }\n\n    /** Advances the state of the generator by @c z. */\n    void discard(boost::uintmax_t z)\n    {\n        _mlcg1.discard(z);\n        _mlcg2.discard(z);\n    }\n\n    /**\n     * Writes the state of an @c additive_combine_engine to a @c\n     * std::ostream.  The textual representation of an @c\n     * additive_combine_engine is the textual representation of\n     * the first base generator followed by the textual representation\n     * of the second base generator.\n     */\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, additive_combine_engine, r)\n    { os << r._mlcg1 << ' ' << r._mlcg2; return os; }\n\n    /**\n     * Reads the state of an @c additive_combine_engine from a\n     * @c std::istream.\n     */\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, additive_combine_engine, r)\n    { is >> r._mlcg1 >> std::ws >> r._mlcg2; return is; }\n\n    /**\n     * Returns: true iff the two @c additive_combine_engines will\n     * produce the same sequence of values.\n     */\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(additive_combine_engine, x, y)\n    { return x._mlcg1 == y._mlcg1 && x._mlcg2 == y._mlcg2; }\n    /**\n     * Returns: true iff the two @c additive_combine_engines will\n     * produce different sequences of values.\n     */\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(additive_combine_engine)\n\nprivate:\n    MLCG1 _mlcg1;\n    MLCG2 _mlcg2;\n};\n\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\ntemplate<class MLCG1, class MLCG2>\nconst bool additive_combine_engine<MLCG1, MLCG2>::has_fixed_range;\n#endif\n\n/// \\cond show_deprecated\n\n/** Provided for backwards compatibility. */\ntemplate<class MLCG1, class MLCG2, typename MLCG1::result_type val = 0>\nclass additive_combine : public additive_combine_engine<MLCG1, MLCG2>\n{\n    typedef additive_combine_engine<MLCG1, MLCG2> base_t;\npublic:\n    typedef typename base_t::result_type result_type;\n    additive_combine() {}\n    template<class T>\n    additive_combine(T& arg) : base_t(arg) {}\n    template<class T>\n    additive_combine(const T& arg) : base_t(arg) {}\n    template<class It>\n    additive_combine(It& first, It last) : base_t(first, last) {}\n};\n\n/// \\endcond\n\n/**\n * The specialization \\ecuyer1988 was suggested in\n *\n *  @blockquote\n *  \"Efficient and Portable Combined Random Number Generators\", Pierre L'Ecuyer,\n *  Communications of the ACM, Vol. 31, No. 6, June 1988, pp. 742-749, 774\n *  @endblockquote\n */\ntypedef additive_combine_engine<\n    linear_congruential_engine<uint32_t, 40014, 0, 2147483563>,\n    linear_congruential_engine<uint32_t, 40692, 0, 2147483399>\n> ecuyer1988;\n\n} // namespace random\n\nusing random::ecuyer1988;\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_ADDITIVE_COMBINE_HPP\n", "meta": {"hexsha": "b4cb63cd57c9577546edcb009627242c9c839f17", "size": 8892, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost/boost/random/additive_combine.hpp", "max_stars_repo_name": "creatologist/openFrameworks0084", "max_stars_repo_head_hexsha": "aa74f188f105b62fbcecb7baf2b41d56d97cf7bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 130.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T23:34:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T19:22:35.000Z", "max_issues_repo_path": "Boost_1_49/boost/random/additive_combine.hpp", "max_issues_repo_name": "jjzhang166/WinUtil4", "max_issues_repo_head_hexsha": "7c7b1e9bbe2fb6177bb066d74764d10711748ec5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2015-07-22T07:35:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T16:03:06.000Z", "max_forks_repo_path": "Boost_1_49/boost/random/additive_combine.hpp", "max_forks_repo_name": "jjzhang166/WinUtil4", "max_forks_repo_head_hexsha": "7c7b1e9bbe2fb6177bb066d74764d10711748ec5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 44.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T09:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T08:09:17.000Z", "avg_line_length": 31.3098591549, "max_line_length": 80, "alphanum_fraction": 0.6772379667, "num_tokens": 2315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5004150890754856}}
{"text": "/*\n * Common.hpp\n *\n *  Created on: Feb 9, 2014\n *      Author: Bloeschm\n */\n\n#ifndef LWF_COMMON_HPP_\n#define LWF_COMMON_HPP_\n\n#include <map>\n#include <type_traits>\n#include <tuple>\n#include <Eigen/Dense>\n#include <iostream>\n#include \"kindr/Core\"\n#include \"lightweight_filtering/PropertyHandler.hpp\"\n\ntypedef kindr::RotationQuaternionPD QPD;\ntypedef kindr::RotationMatrixPD MPD;\ntypedef Eigen::Vector3d V3D;\ntypedef Eigen::Matrix3d M3D;\ntypedef Eigen::VectorXd VXD;\ntypedef Eigen::MatrixXd MXD;\ninline M3D gSM(const V3D& vec){\n  return kindr::getSkewMatrixFromVector(vec);\n}\n\nstatic void enforceSymmetry(MXD& mat){\n  mat = 0.5*(mat+mat.transpose()).eval();\n}\n\ninline M3D Lmat (const V3D& a) {\n  return kindr::getJacobianOfExponentialMap(a);\n}\n\nnamespace LWF{\n  enum FilteringMode{\n    ModeEKF,\n    ModeUKF,\n    ModeIEKF\n  };\n}\n\n#endif /* LWF_COMMON_HPP_ */\n", "meta": {"hexsha": "0827fd4e66e10df174b173a4c5ca53922bd71fb9", "size": 857, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lightweight_filtering/common.hpp", "max_stars_repo_name": "evar-sd/lightweight_filtering", "max_stars_repo_head_hexsha": "0c8517a5eb19a00a4f8d36dac4ffdc45dac6a363", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2017-04-26T02:54:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T19:12:52.000Z", "max_issues_repo_path": "include/lightweight_filtering/common.hpp", "max_issues_repo_name": "evar-sd/lightweight_filtering", "max_issues_repo_head_hexsha": "0c8517a5eb19a00a4f8d36dac4ffdc45dac6a363", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-02-16T17:13:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-24T07:42:25.000Z", "max_forks_repo_path": "include/lightweight_filtering/common.hpp", "max_forks_repo_name": "evar-sd/lightweight_filtering", "max_forks_repo_head_hexsha": "0c8517a5eb19a00a4f8d36dac4ffdc45dac6a363", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-05-17T13:47:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T06:09:20.000Z", "avg_line_length": 18.6304347826, "max_line_length": 52, "alphanum_fraction": 0.7246207701, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5003971118798672}}
{"text": "// Header\n#include \"Translate.hpp\"\n\n// Boost\n#include <boost/foreach.hpp>\n#define foreach BOOST_FOREACH\n\nnamespace QuadProgMm {\n  /* From QuadProg++:\n\n  The problem is in the expression:\n\n  min 0.5 * x G x + g0 x\n  s.t.\n      CE^T x + ce0 = 0\n      CI^T x + ci0 >= 0\n\n   The matrix and vectors dimensions are as follows:\n       G: n * n\n      g0: n\n\n      CE: n * p\n     ce0: p\n\n      CI: n * m\n     ci0: m\n\n       x: n\n  */\n  Translation::Translation(const std::set<Variable>& variables_, int p, int m) :\n    Translation(\n      std::vector<Variable>(variables_.begin(), variables_.end()),\n      variables_.size(),\n      p,\n      m\n    )\n  {}\n\n  Translation::Translation(const std::vector<Variable>& variables_, int n, int p, int m) :\n    variables(variables_),\n    G(n, n), g0(n), g00(0),\n    CE(n, p), ce0(p),\n    CI(n, m), ci0(m)\n  {}\n\n  void translate(\n    const std::vector<Variable>& variables,\n    const QuadraticExpression& q,\n    quadprogpp::Matrix<double>& G,\n    quadprogpp::Vector<double>& g0,\n    double& g00\n  ) {\n    int index1 = 0;\n    foreach(Variable v1, variables) {\n      int index2 = 0;\n      foreach(Variable v2, variables) {\n        const double coeff = q.getQuadraticCoefficient(v1, v2);\n        if (index1 == index2) {\n          G[index1][index1] = 2 * coeff;\n        } else {\n          G[index1][index2] = coeff;\n          G[index2][index1] = coeff;\n        }\n        ++index2;\n      }\n      ++index1;\n    }\n\n    int index = 0;\n    foreach(Variable v, variables) {\n      g0[index] = q.getLinearCoefficient(v);\n      ++index;\n    }\n\n    g00 = q.getConstantCoefficient();\n  }\n\n  void translate(\n    const std::vector<Variable>& variables,\n    const LinearExpression& l,\n    quadprogpp::Matrix<double>& CIE,\n    quadprogpp::Vector<double>& cie0,\n    int indexIE\n  ) {\n    int index = 0;\n    foreach(Variable v, variables) {\n      CIE[index][indexIE] = l.getLinearCoefficient(v);\n      ++index;\n    }\n\n    cie0[indexIE] = l.getConstantCoefficient();\n  }\n\n  Translation translate(const QuadraticExpression& q, const std::vector<Constraint>& constraints) {\n    int p = 0;\n    int m = 0;\n    std::set<Variable> variables = q.getVariables();\n    foreach(Constraint c, constraints) {\n      switch(c.getType()) {\n        case Constraint::ZERO:\n          ++p;\n          break;\n        case Constraint::POSITIVE:\n          ++m;\n          break;\n      }\n      const std::set<Variable> constraintVariables = c.getLinearExpression().getVariables();\n      variables.insert(constraintVariables.begin(), constraintVariables.end());\n    }\n\n    Translation t(variables, p, m);\n\n    translate(t.variables, q, t.G, t.g0, t.g00);\n\n    int indexE = 0;\n    int indexI = 0;\n    foreach(Constraint c, constraints) {\n      const LinearExpression& l = c.getLinearExpression();\n\n      switch(c.getType()) {\n        case Constraint::ZERO:\n          translate(t.variables, l, t.CE, t.ce0, indexE);\n          ++indexE;\n          break;\n        case Constraint::POSITIVE:\n          translate(t.variables, l, t.CI, t.ci0, indexI);\n          ++indexI;\n          break;\n      }\n    }\n\n    return t;\n  }\n}\n", "meta": {"hexsha": "38ec77c68601b7e11ef74e85b63ba5337c423b0c", "size": 3094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Translate.cpp", "max_stars_repo_name": "jacquev6/QuadProgMm", "max_stars_repo_head_hexsha": "992ccd82a00bfcbe724d2bcc12a8ceffbffcc8b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-03T15:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-24T01:10:29.000Z", "max_issues_repo_path": "src/Translate.cpp", "max_issues_repo_name": "jacquev6/QuadProgMm", "max_issues_repo_head_hexsha": "992ccd82a00bfcbe724d2bcc12a8ceffbffcc8b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Translate.cpp", "max_forks_repo_name": "jacquev6/QuadProgMm", "max_forks_repo_head_hexsha": "992ccd82a00bfcbe724d2bcc12a8ceffbffcc8b2", "max_forks_repo_licenses": ["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.9185185185, "max_line_length": 99, "alphanum_fraction": 0.5730446025, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5003971068901364}}
{"text": "/**\n *  This test ensures that the sketch application (for CombBLAS matrices) is\n *  done correctly (on-the-fly matrix multiplication in the code is compared\n *  to true matrix multiplication).\n *  This test builds on the following assumptions:\n *\n *      - CombBLAS PSpGEMM returns the correct result, and\n *      - the random numbers in row_idx and row_value (see\n *        hash_transform_data_t) are drawn from the promised distributions.\n */\n\n\n#include <vector>\n\n#include <boost/mpi.hpp>\n#include <boost/test/minimal.hpp>\n\n//FIXME: ugly, fix header problem!\n#define SKYLARK_SKETCH_HPP 1\n\n#define SKYLARK_NO_ANY\n#include \"El.hpp\"\n#include \"../../base/sparse_matrix.hpp\"\n\n#include \"../../base/context.hpp\"\n#include \"../../utility/distributions.hpp\"\n#include \"../../sketch/hash_transform.hpp\"\n\ntypedef FullyDistVec<size_t, double> mpi_vector_t;\ntypedef SpDCCols<size_t, double> col_t;\ntypedef SpParMat<size_t, double, col_t> DistMatrixType;\ntypedef PlusTimesSRing<double, double> PTDD;\ntypedef skylark::base::sparse_matrix_t<double> LocalMatrixType;\n\n\ntemplate < typename InputMatrixType,\n           typename OutputMatrixType = InputMatrixType >\nstruct Dummy_t : public skylark::sketch::hash_transform_t<\n    InputMatrixType, OutputMatrixType,\n    boost::random::uniform_int_distribution,\n    skylark::utility::rademacher_distribution_t > {\n\n    typedef skylark::sketch::hash_transform_t<\n        InputMatrixType, OutputMatrixType,\n        boost::random::uniform_int_distribution,\n        skylark::utility::rademacher_distribution_t >\n            hash_t;\n\n    Dummy_t(int N, int S, skylark::base::context_t& context)\n        : skylark::sketch::hash_transform_t<InputMatrixType, OutputMatrixType,\n          boost::random::uniform_int_distribution,\n          skylark::utility::rademacher_distribution_t>(N, S, context)\n    {}\n\n    std::vector<size_t> getRowIdx() { return hash_t::row_idx; }\n    std::vector<double> getRowValues() { return hash_t::row_value; }\n};\n\n\ntemplate<typename sketch_t>\nvoid compute_sketch_matrix(sketch_t sketch, const DistMatrixType &A,\n                           DistMatrixType &result) {\n\n    std::vector<size_t> row_idx = sketch.getRowIdx();\n    std::vector<double> row_val = sketch.getRowValues();\n\n    // PI generated by random number gen\n    size_t sketch_size = row_val.size();\n    mpi_vector_t cols(sketch_size);\n    mpi_vector_t rows(sketch_size);\n    mpi_vector_t vals(sketch_size);\n\n    for(size_t i = 0; i < sketch_size; ++i) {\n        cols.SetElement(i, i);\n        rows.SetElement(i, row_idx[i]);\n        vals.SetElement(i, row_val[i]);\n    }\n\n    result = DistMatrixType(result.getnrow(), result.getncol(),\n                            rows, cols, vals);\n}\n\n\nint test_main(int argc, char *argv[]) {\n\n    //////////////////////////////////////////////////////////////////////////\n    //[> Parameters <]\n\n    //FIXME: use random sizes?\n    const size_t n   = 200;\n    const size_t m   = 100;\n    const size_t n_s = 120;\n    const size_t m_s = 60;\n\n    //////////////////////////////////////////////////////////////////////////\n    //[> Setup test <]\n    namespace mpi = boost::mpi;\n    mpi::environment env(argc, argv);\n    mpi::communicator world;\n    const size_t rank = world.rank();\n\n    skylark::base::context_t context (0);\n\n    double count = 1.0;\n\n    const size_t matrix_full = n * m;\n    mpi_vector_t colsf(matrix_full);\n    mpi_vector_t rowsf(matrix_full);\n    mpi_vector_t valsf(matrix_full);\n\n    for(size_t i = 0; i < matrix_full; ++i) {\n        colsf.SetElement(i, i % m);\n        rowsf.SetElement(i, i / m);\n        valsf.SetElement(i, count);\n        count++;\n    }\n\n    DistMatrixType A(n, m, rowsf, colsf, valsf);\n\n\n    //////////////////////////////////////////////////////////////////////////\n    //[> Column wise application DistSparseMatrix -> DistSparseMatrix <]\n\n    //[> 1. Create the sketching matrix <]\n    Dummy_t<DistMatrixType, DistMatrixType> Sparse(n, n_s, context);\n\n    //[> 2. Create space for the sketched matrix <]\n    mpi_vector_t zero;\n    DistMatrixType sketch_A(n_s, m, zero, zero, zero);\n\n    //[> 3. Apply the transform <]\n    Sparse.apply(A, sketch_A, skylark::sketch::columnwise_tag());\n\n    //[> 4. Build structure to compare <]\n    DistMatrixType pi_sketch(n_s, n, zero, zero, zero);\n    compute_sketch_matrix(Sparse, A, pi_sketch);\n    DistMatrixType expected_A = Mult_AnXBn_Synch<PTDD, double, col_t>(pi_sketch, A, false, false);\n    if (!static_cast<bool>(expected_A == sketch_A))\n        BOOST_FAIL(\"Result of colwise (dist -> dist) application not as expected\");\n\n    //////////////////////////////////////////////////////////////////////////\n    //[> Column wise application DistSparseMatrix -> LocalSparseMatrix <]\n\n    Dummy_t<DistMatrixType, LocalMatrixType> LocalSparse(n, n_s, context);\n    LocalMatrixType local_sketch_A;\n    LocalSparse.apply(A, local_sketch_A, skylark::sketch::columnwise_tag());\n\n    if(rank == 0) {\n        std::vector<size_t> row_idx = LocalSparse.getRowIdx();\n        std::vector<double> row_val = LocalSparse.getRowValues();\n\n        // PI generated by random number gen\n        int sketch_size = row_val.size();\n        typename LocalMatrixType::coords_t coords;\n        for(int i = 0; i < sketch_size; ++i) {\n            typename LocalMatrixType::coord_tuple_t new_entry(row_idx[i], i, row_val[i]);\n            coords.push_back(new_entry);\n        }\n\n        LocalMatrixType pi_sketch_l;\n        pi_sketch_l.set(coords);\n\n        typename LocalMatrixType::coords_t coords_new;\n        const int* indptr = pi_sketch_l.indptr();\n        const int* indices = pi_sketch_l.indices();\n        const double* values = pi_sketch_l.locked_values();\n\n        // multiply with vector where an entry has the value:\n        //   col_idx + row_idx * m + 1.\n        // See creation of A.\n        for(int col = 0; col < pi_sketch_l.width(); col++) {\n            for(int idx = indptr[col]; idx < indptr[col + 1]; idx++) {\n                for(int ccol = 0; ccol < m; ++ccol) {\n                    typename LocalMatrixType::coord_tuple_t new_entry(indices[idx],\n                            ccol, values[idx] * (ccol + col * m + 1));\n                    coords_new.push_back(new_entry);\n                }\n            }\n        }\n\n        LocalMatrixType expected_A_l;\n        expected_A_l.set(coords_new, n_s, m);\n\n        if (!static_cast<bool>(expected_A_l == local_sketch_A))\n            BOOST_FAIL(\"Result of local colwise application not as expected\");\n    }\n\n\n    //////////////////////////////////////////////////////////////////////////\n    //[> Row wise application DistSparseMatrix -> DistSparseMatrix <]\n\n    //[> 1. Create the sketching matrix <]\n    Dummy_t<DistMatrixType, DistMatrixType> Sparse_r(m, m_s, context);\n\n    //[> 2. Create space for the sketched matrix <]\n    DistMatrixType sketch_A_r(n, m_s, zero, zero, zero);\n\n    //[> 3. Apply the transform <]\n    Sparse_r.apply(A, sketch_A_r, skylark::sketch::rowwise_tag());\n\n    //[> 4. Build structure to compare <]\n    DistMatrixType pi_sketch_r(m_s, m, zero, zero, zero);\n    compute_sketch_matrix(Sparse_r, A, pi_sketch_r);\n    pi_sketch_r.Transpose();\n    DistMatrixType expected_AR = PSpGEMM<PTDD>(A, pi_sketch_r);\n\n    if (!static_cast<bool>(expected_AR == sketch_A_r))\n        BOOST_FAIL(\"Result of rowwise (dist -> dist) application not as expected\");\n\n    return 0;\n}\n", "meta": {"hexsha": "d943881d85be939c48957a142110b9482a62cce3", "size": 7348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/SparseSketchApplyCombBLASTest.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": "tests/unit/SparseSketchApplyCombBLASTest.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": "tests/unit/SparseSketchApplyCombBLASTest.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": 34.6603773585, "max_line_length": 98, "alphanum_fraction": 0.6207131192, "num_tokens": 1792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.500397104307145}}
{"text": "// Copyright 2020 Gareth Cross\n#pragma once\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n\n// Numerical tolerances for tests.\nnamespace tol {\nstatic constexpr double kDeci = 1.0e-1;\nstatic constexpr double kCenti = 1.0e-2;\nstatic constexpr double kMilli = 1.0e-3;\nstatic constexpr double kMicro = 1.0e-6;\nstatic constexpr double kNano = 1.0e-9;\nstatic constexpr double kPico = 1.0e-12;\n}  // namespace tol\n\n// Print variable w/ name.\n#define PRINT(x) printImpl(#x, x)\n\ntemplate <typename Xpr>\nvoid printImpl(const std::string& name, Xpr xpr) {\n  std::cout << name << \"=\" << xpr << std::endl;\n}\n\n// Define a test on a class.\n#define TEST_FIXTURE(object, function) \\\n  TEST_F(object, function) { function(); }\n\n// Macro to compare eigen matrices and print a nice error.\n#define EXPECT_EIGEN_NEAR(a, b, tol) EXPECT_PRED_FORMAT3(math::expectEigenNear, a, b, tol)\n#define ASSERT_EIGEN_NEAR(a, b, tol) ASSERT_PRED_FORMAT3(math::expectEigenNear, a, b, tol)\n\nnamespace math {\n\n// 300 randomly generated rotation vectors (range 0 to 2pi), used for testing.\nextern const std::vector<Eigen::Vector3d> kRandomRotationVectorsZero2Pi;\n\n// 300 more in 0 to pi.\nextern const std::vector<Eigen::Vector3d> kRandomRotationVectorsZeroPi;\n\n// Compare two eigen matrices. Use EXPECT_EIGEN_NEAR()\ntemplate <typename Ta, typename Tb>\ntesting::AssertionResult expectEigenNear(const std::string& name_a, const std::string& name_b,\n                                         const std::string& name_tol,\n                                         const Eigen::MatrixBase<Ta>& a,\n                                         const Eigen::MatrixBase<Tb>& b, double tolerance) {\n  if (a.rows() != b.rows() || a.cols() != b.cols()) {\n    return testing::AssertionFailure()\n           << \"Dimensions of \" << name_a << \" and \" << name_b << \" do not match.\";\n  }\n  for (int i = 0; i < a.rows(); ++i) {\n    for (int j = 0; j < a.cols(); ++j) {\n      const double delta = a(i, j) - b(i, j);\n      if (std::abs(delta) > tolerance || std::isnan(delta)) {\n        const std::string index_str = \"(\" + std::to_string(i) + \", \" + std::to_string(j) + \")\";\n        return testing::AssertionFailure()\n               << \"Matrix equality \" << name_a << \" == \" << name_b << \" failed because:\\n\"\n               << name_a << index_str << \" - \" << name_b << index_str << \" = \" << delta << \" > \"\n               << name_tol << \"\\nWhere \" << name_a << \" evaluates to:\\n\"\n               << a << \"\\n and \" << name_b << \" evaluates to:\\n\"\n               << b << \"\\n and \" << name_tol << \" evaluates to: \" << tolerance << \"\\n\";\n      }\n    }\n  }\n  return testing::AssertionSuccess();\n}\n\n/// Create a vector in the specified range.\n/// Begins at `start` and increments by `step` until >= `end`.\nstd::vector<double> Range(double start, double end, double step);\n/**\n * @brief Exponential map via power series. Computes the value of exp(A), where A is a square\n *  matrix.\n * @note Refer to:\n *  \"Chapter 4: Basics of Classical Lie Groups: The Exponential Map,\n *   Lie Groups, and Lie Algebras\" - Jean Gallier\n * @param num_terms Number of terms in power series. Note that large values\n *  will result in floating-point underflow, so be careful.\n */\ntemplate <typename Scalar, int Rows, int Cols>\nEigen::Matrix<Scalar, Rows, Cols> ExpMatrixSeries(const Eigen::Matrix<Scalar, Rows, Cols>& A,\n                                                  const int num_terms = 15) {\n  Eigen::Matrix<double, Rows, Cols> A_power, solution;\n  A_power.setIdentity();\n  double fac_accum = 1;\n  solution.setIdentity();  //  term 0\n  for (int p = 1; p < num_terms; ++p) {\n    A_power *= A.template cast<double>();\n    fac_accum *= p;\n    solution.noalias() += A_power / fac_accum;\n  }\n  return solution.template cast<Scalar>();\n}\n\n}  // namespace math\n", "meta": {"hexsha": "3382278225503799d75021496afad7ca0b9426de", "size": 3765, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/test_utils.hpp", "max_stars_repo_name": "gareth-cross/geometry_utils", "max_stars_repo_head_hexsha": "cc687d19559c2055b68e7f8708af3595e7f93917", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-16T21:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T21:05:15.000Z", "max_issues_repo_path": "test/test_utils.hpp", "max_issues_repo_name": "gareth-cross/geometry_utils", "max_issues_repo_head_hexsha": "cc687d19559c2055b68e7f8708af3595e7f93917", "max_issues_repo_licenses": ["MIT"], "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_utils.hpp", "max_forks_repo_name": "gareth-cross/geometry_utils", "max_forks_repo_head_hexsha": "cc687d19559c2055b68e7f8708af3595e7f93917", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-07T10:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-17T14:36:02.000Z", "avg_line_length": 39.6315789474, "max_line_length": 96, "alphanum_fraction": 0.6183266932, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5003971031919009}}
{"text": "#pragma once\n#include <random>\n#include <bitset>\n#include <fstream>\n#include <ios>\n#include <string>\n#include <cassert>\n#include <Eigen/Eigen>\n#include <Eigen/Sparse>\n\n#include <tbb/tbb.h>\n\n#include <nlohmann/json.hpp>\n\n#include \"Utilities/type_traits.hpp\"\n#include \"Utilities/Utility.hpp\"\n#include \"Serializers/SerializeEigen.hpp\"\n\nnamespace yannq\n{\n//! \\ingroup Machines\n//! RBM machine\ntemplate<typename T>\nclass CorrelatedRBM\n{\n\tstatic_assert(std::is_floating_point<T>::value || is_complex_type<T>::value, \"T must be floating or complex\");\npublic:\n\tusing Scalar = T;\n\tusing RealScalar = typename yannq::remove_complex<T>::type;\n\n\tusing Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\n\tusing RealVector = Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>;\n\t\n\tusing DataT = std::tuple<Eigen::VectorXi, Vector>;\n\nprivate:\n\tuint32_t n_; //# of qubits\n\tuint32_t m_; //# of hidden units\n\n\tbool useBias_;\n\n\tEigen::SparseMatrix<int> correl_; \n\n\n\tMatrix W_; //W should be m by (n + k)\n\tVector a_; //a is length n + k\n\tVector b_; //b is length m\n\npublic:\n\t/* \\param n number of qubits\n\t * \\param m number of hidden units\n\t * \\param correl n \\times k matrix. For each column, 1 is given at the location of\n\t * a qubit involving a correlation. C_k = \\prod_{l, correl(l,k)=1} s_l\n\t * */\n\tCorrelatedRBM(uint32_t n, uint32_t m, \n\t\t\tconst Eigen::SparseMatrix<int>& correl, bool useBias = true) noexcept\n\t\t: n_(n), m_(m), useBias_(useBias), correl_{correl}, \n\t\tW_(m,n+correl.cols()), a_(n+correl.cols()), b_(m) \n\t{\n\t\tcorrel_.makeCompressed();\n\t\ta_.setZero();\n\t\tb_.setZero();\n\t\tW_.setZero();\n\t}\n\n\tCorrelatedRBM() noexcept\n\t\t: useBias_{true}\n\t{\n\t}\n\n\ttemplate<typename U, std::enable_if_t<std::is_convertible_v<U, T> && !std::is_same_v<U, T>, int> = 0>\n\tCorrelatedRBM(const CorrelatedRBM<U>& rhs) \n\t\t: n_{rhs.getN()}, m_{rhs.getM()}, useBias_{rhs.useBias()}, correl_{rhs.correl_}\n\t{\n\t\tW_ = rhs.getW().template cast<T>();\n\t\ta_ = rhs.getA().template cast<T>();\n\t\tb_ = rhs.getB().template cast<T>();\n\t}\n\n\tCorrelatedRBM(const CorrelatedRBM& rhs) /* noexcept */ = default;\n\tCorrelatedRBM(CorrelatedRBM&& rhs) /* noexcept */ = default;\n\n\ttemplate<typename U, std::enable_if_t<std::is_convertible_v<U, T> && !std::is_same_v<U, T>, int> = 0>\n\tCorrelatedRBM& operator=(const CorrelatedRBM<U>& rhs) \n\t{\n\t\tn_ = rhs.n_;\n\t\tm_ = rhs.m_;\n\t\tuseBias_ = rhs.useBias_;\n\t\tcorrel_ = rhs.correl_;\n\n\t\tW_ = rhs.W_.template cast<T>();\n\t\ta_ = rhs.a_.template cast<T>();\n\t\tb_ = rhs.b_.template cast<T>();\n\n\t\treturn *this;\n\t}\n\n\tCorrelatedRBM& operator=(const CorrelatedRBM& rhs) /* noexcept */ = default;\n\tCorrelatedRBM& operator=(CorrelatedRBM&& rhs) /* noexcept */ = default;\n\n\ttemplate<typename U, std::enable_if_t<std::is_convertible_v<T, U>, int> = 0>\n\tCorrelatedRBM<U> cast() const\n\t{\n\t\tCorrelatedRBM<U> res(n_, m_, correl_, useBias_);\n\t\tres.setA(a_.template cast<U>());\n\t\tres.setB(b_.template cast<U>());\n\t\tres.setW(W_.template cast<U>());\n\t\treturn res;\n\t}\n\n\tnlohmann::json desc() const\n\t{\n\t\treturn nlohmann::json\n\t\t{\n\t\t\t{\"name\", \"CorrelatedRBM\"},\n\t\t\t{\"useBias\", useBias_},\n\t\t\t{\"k\", correl_.rows()},\n\t\t\t{\"n\", n_},\n\t\t\t{\"m\", m_}\n\t\t};\n\t}\n\n\tinline uint32_t getN() const\n\t{\n\t\treturn n_;\n\t}\n\tinline uint32_t getM() const\n\t{\n\t\treturn m_;\n\t}\n\n\tinline uint32_t getK() const\n\t{\n\t\treturn correl_.cols();\n\t}\n\n\tinline uint32_t getDim() const\n\t{\n\t\tauto k = getK();\n\t\tif(useBias_)\n\t\t\treturn (n_ + k)*m_ + n_ + k + m_;\n\t\telse\n\t\t\treturn (n_ + k)*m_;\n\t}\n\n\n\tinline bool useBias() const\n\t{\n\t\treturn useBias_;\n\t}\n\n\tEigen::VectorXi calcCorrel(const Eigen::VectorXi& sigma) const\n\t{\n\t\tEigen::VectorXi c = Eigen::VectorXi::Ones(getK());\n\t\tfor(uint32_t l = 0; l < getK(); ++l) //cols (outer)\n\t\t{\n\t\t\tfor(Eigen::SparseMatrix<int>::InnerIterator it(correl_, l); it; ++it)\n\t\t\t{\n\t\t\t\tc(l) *= sigma(it.row());\n\t\t\t}\n\t\t}\n\t\treturn c;\n\t}\n\n\t/**\n\t * \\param ss is sigma plus correl\n\t */\n\tinline Vector calcTheta(const Eigen::VectorXi& ss) const\n\t{\n\t\tassert(ss.size() == n_ + getK());\n\t\tVector s = ss.cast<T>();\n\t\treturn W_*s + b_;\n\t}\n\n\tvoid setUseBias(bool newBias)\n\t{\n\t\tuseBias_ = newBias;\n\t}\n\n\tvoid resize(uint32_t n, uint32_t m)\n\t{\n\t\tn_ = n;\n\t\tm_ = m;\n\n\t\ta_.resize(n);\n\t\tb_.resize(m + getK());\n\t\tW_.resize(m + getK(),n);\n\n\t\tif(!useBias_)\n\t\t{\n\t\t\ta_.setZero();\n\t\t\tb_.setZero();\n\t\t}\n\t}\n\n\tvoid conservativeResize(uint32_t newM)\n\t{\n\t\tVector newB = Vector::Zero(newM);\n\t\tnewB.head(m_) = b_;\n\n\t\tMatrix newW = Matrix::Zero(newM, n_ + getK());\n\t\tnewW.topRows(m_) = W_;\n\n\t\tm_ = newM;\n\t\tb_ = std::move(newB);\n\t\tW_ = std::move(newW);\n\t}\n\n\tvoid setCorrel(const Eigen::SparseMatrix<int>& correl)\n\t{\n\t\tcorrel_ = correl;\n\t}\n\n\tvoid setW(const Eigen::Ref<const Matrix>& m)\n\t{\n\t\tassert(m.rows() == W_.rows() && m.cols() == W_.cols());\n\t\tW_ = m;\n\t}\n\n\tvoid setA(const VectorConstRef& A)\n\t{\n\t\tassert(A.size() == a_.size());\n\t\tif(!useBias_)\n\t\t\treturn ;\n\t\ta_ = A;\n\t}\n\n\tvoid setB(const VectorConstRef& B)\n\t{\n\t\tassert(B.size() == b_.size());\n\t\tif(!useBias_)\n\t\t\treturn ;\n\t\tb_ = B;\n\t}\n\n\n\tinline const T& W(uint32_t j, uint32_t i) const\n\t{\n\t\treturn W_.coeff(j,i);\n\t}\n\tinline const T& A(uint32_t i) const\n\t{\n\t\treturn a_.coeff(i);\n\t}\n\tinline const T& B(uint32_t j) const\n\t{\n\t\treturn b_.coeff(j);\n\t}\n\n\tinline T& W(uint32_t j, uint32_t i) \n\t{\n\t\treturn W_.coeffRef(j,i);\n\t}\n\tinline T& A(uint32_t i) \n\t{\n\t\treturn a_.coeffRef(i);\n\t}\n\tinline T& B(uint32_t j) \n\t{\n\t\treturn b_.coeffRef(j);\n\t}\n\n\tEigen::SparseMatrix<int> getCorrel() const\n\t{\n\t\treturn correl_;\n\t}\n\n\t\n\tconst Matrix& getW() const & { return W_; } \n\tMatrix getW() && { return std::move(W_); } \n\n\tconst Vector& getA() const & { return a_; } \n\tVector getA() && { return std::move(a_); } \n\n\tconst Vector& getB() const & { return b_; } \n\tVector getB() && { return std::move(b_); } \n\n\n\t//! update Bias A by adding v\n\tvoid updateA(const VectorConstRef& v)\n\t{\n\t\tassert(useBias_);\n\t\ta_ += v;\n\t}\n\t//! update Bias B by adding v\n\tvoid updateB(const VectorConstRef& v)\n\t{\n\t\tassert(useBias_);\n\t\tb_ += v;\n\t}\n\t//! update the weight W by adding m\n\tvoid updateW(const Eigen::Ref<const Matrix>& m)\n\t{\n\t\tW_ += m;\n\t}\n\n\t//! update all parameters.\n\tvoid updateParams(const VectorConstRef& m)\n\t{\n\t\tassert(m.size() == getDim());\n\t\tuint32_t k = getK();\n\t\tW_ += Eigen::Map<const Matrix>(m.data(), m_, n_ + k);\n\t\tif(!useBias_)\n\t\t\treturn ;\n\t\ta_ += Eigen::Map<const Vector>(m.data() + m_*(n_ + k), n_ + k);\n\t\tb_ += Eigen::Map<const Vector>(m.data() + m_*(n_ + k) + n_ + k, m_);\n\t}\n\n\tVector getParams() const\n\t{\n\t\tconst auto k = getK();\n\t\tVector res(getDim());\n\t\tres.head((n_+k)*m_) = Eigen::Map<const Vector>(W_.data(), W_.size());\n\t\tif(!useBias_)\n\t\t\treturn res;\n\n\t\tres.segment((n_ + k)*m_, n_ + k) = a_;\n\t\tres.segment((n_ + k)*m_ + n_ + k, m_) = b_;\n\t\treturn res;\n\t}\n\n\tvoid setParams(const VectorConstRef& r)\n\t{\n\t\tassert(r.size() == getDim());\n\t\tconst auto k = getK();\n\t\tEigen::Map<Vector>(W_.data(), W_.size()) = r.head((n_ + k)*m_);\n\t\tif(!useBias_)\n\t\t\treturn ;\n\t\ta_ = r.segment((n_+k)*m_, n_ + k);\n\t\tb_ = r.segment((n_+k)*m_ + n_ + k, m_);\n\t}\n\n\tbool hasNaN() const\n\t{\n\t\treturn a_.hasNaN() || b_.hasNaN() || W_.hasNaN();\n\t}\n\n\t/* When T is real type */\n\ttemplate <typename RandomEngine, class U=T,\n            \tstd::enable_if_t < !is_complex_type<U>::value, int > = 0 >\n\tvoid initializeRandom(RandomEngine& re, T sigma = 1e-3)\n\t{\n\t\tconst auto k = getK();\n\t\tstd::normal_distribution<T> nd{0, sigma};\n\t\tif(useBias_)\n\t\t{\n\t\t\tfor(uint32_t i = 0u; i < n_ + k; i++)\n\t\t\t{\n\t\t\t\ta_.coeffRef(i) = nd(re);\n\t\t\t}\n\t\t\tfor(uint32_t i = 0u; i < m_; i++)\n\t\t\t{\n\t\t\t\tb_.coeffRef(i) = nd(re);\n\t\t\t}\n\t\t}\n\t\tfor(uint32_t j = 0u; j < n_ + k; j++)\n\t\t{\n\t\t\tfor(uint32_t i = 0u; i < m_; i++)\n\t\t\t{\n\t\t\t\tW_.coeffRef(i, j) = nd(re);\n\t\t\t}\n\t\t}\n\t}\n\n\t/* When T is complex type */\n\ttemplate <typename RandomEngine, class U=T,\n               std::enable_if_t < is_complex_type<U>::value, int > = 0 >\n\tvoid initializeRandom(RandomEngine& re, typename remove_complex<T>::type sigma = 1e-3)\n\t{\n\t\tconst auto k = getK();\n\t\tstd::normal_distribution<typename remove_complex<T>::type> nd{0, sigma};\n\t\t\n\t\tif(useBias_)\n\t\t{\n\t\t\tfor(uint32_t i = 0u; i < n_ + k; i++)\n\t\t\t{\n\t\t\t\ta_.coeffRef(i) = T{nd(re), nd(re)};\n\t\t\t}\n\t\t\tfor(uint32_t i = 0u; i < m_; i++)\n\t\t\t{\n\t\t\t\tb_.coeffRef(i) = T{nd(re), nd(re)};\n\t\t\t}\n\t\t}\n\t\tfor(uint32_t j = 0; j < n_ + k; j++)\n\t\t{\n\t\t\tfor(uint32_t i = 0u; i < m_; i++)\n\t\t\t{\n\t\t\t\tW_.coeffRef(i, j) = T{nd(re), nd(re)};\n\t\t\t}\n\t\t}\n\t}\n\n\tbool operator==(const CorrelatedRBM<T>& rhs) const\n\t{\n\t\tif(n_ != rhs.n_ || m_ != rhs.m_ || getK() != rhs.getK())\n\t\t\treturn false;\n\t\tif((correl_ - rhs.corre_).norm() > 1e-6)\n\t\t\treturn false;\n\t\tif(useBias_)\n\t\t\treturn (a_ == rhs.a_) && (b_ == rhs.b_) && (W_ == rhs.W_);\n\t\telse\n\t\t\treturn (W_ == rhs.W_);\n\t}\n\n\tstd::tuple<Eigen::VectorXi, Vector> makeData(const Eigen::VectorXi& sigma) const\n\t{\n\t\tEigen::VectorXi ss(n_ + getK());\n\t\tss.head(n_) = sigma;\n\t\tss.tail(getK()) = calcCorrel(sigma);\n\t\treturn std::make_tuple(ss, calcTheta(ss));\n\t}\n\n\tT logCoeff(const std::tuple<Eigen::VectorXi, Vector>& t) const\n\t{\n\t\tusing std::cosh;\n\n\t\tVector ss = std::get<0>(t).template cast<T>();\n\t\tT s = a_.transpose()*ss;\n\t\tfor(uint32_t j = 0u; j < m_; j++)\n\t\t{\n\t\t\ts += logCosh(std::get<1>(t).coeff(j));\n\t\t}\n\t\treturn s;\n\t}\n\n\tT coeff(const std::tuple<Eigen::VectorXi, Vector>& t) const\n\t{\n\t\tusing std::cosh;\n\n\t\tVector ss = std::get<0>(t).template cast<T>();\n\t\tT s = a_.transpose()*ss;\n\t\tT p = exp(s) * std::get<1>(t).array().cosh().prod();\n\t\treturn p;\n\t}\n\n\tVector logDeriv(const std::tuple<Eigen::VectorXi, Vector>& t) const \n\t{ \n\t\tVector res(getDim()); \n\t\tconst auto k = getK();\n\n\t\tVector tanhs = std::get<1>(t).array().tanh(); \n\t\tVector ss = std::get<0>(t).template cast<Scalar>();\n\t\t\n\t\tfor(uint32_t i = 0u; i < n_ + k; i++) \n\t\t{ \n\t\t\tres.segment(i*m_, m_) = ss(i)*tanhs; \n\t\t}\n\t\tif(!useBias_)\n\t\t\treturn res;\n\t\tres.segment((n_+k)*m_, n_ + k) = ss;\n\t\tres.segment((n_+k)*m_ + n_ + k, m_) = tanhs; \n\t\treturn res; \n\t} \n};\n\n\ntemplate<typename T>\ntypename CorrelatedRBM<T>::Vector getPsi(const CorrelatedRBM<T>& qs, bool normalize)\n{\n\tconst uint32_t n = qs.getN();\n\ttypename CorrelatedRBM<T>::Vector psi(1u<<n);\n\ttbb::parallel_for(0u, (1u << n),\n\t\t[n, &qs, &psi](uint32_t idx)\n\t{\n\t\tauto s = toSigma(n, idx);\n\t\tpsi(idx) = qs.coeff(qs.makeData(s));\n\t});\n\tif(normalize)\n\t\tpsi.normalize();\n\treturn psi;\n}\n\ntemplate<typename T, typename Iterable> //Iterable must be random access iterable\ntypename CorrelatedRBM<T>::Vector getPsi(const CorrelatedRBM<T>& qs, Iterable&& basis, bool normalize)\n{\n\tconst uint32_t n = qs.getN();\n\ttypename CorrelatedRBM<T>::Vector psi(basis.size());\n\n\ttbb::parallel_for(std::size_t(0u), basis.size(),\n\t\t[n, &qs, &psi, &basis](std::size_t idx)\n\t{\n\t\tauto s = toSigma(n, basis[idx]);\n\t\tpsi(idx) = qs.coeff(qs.makeData(s));\n\t});\n\tif(normalize)\n\t\tpsi.normalize();\n\treturn psi;\n}\n}//namespace yannq\n", "meta": {"hexsha": "dc9df8a4950849c371a4004832af374cdb50cb8a", "size": 10751, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Machines/CorrelatedRBM.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/CorrelatedRBM.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/CorrelatedRBM.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.7631578947, "max_line_length": 111, "alphanum_fraction": 0.6127802065, "num_tokens": 3646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5003971019004053}}
{"text": "#include <catch.hpp>\n\n#include <sstream>\n\n#include <boost/units/systems/si.hpp>\n\n#include <UnitConvert.hpp>\n#include <UnitConvert/GlobalUnitRegistry.hpp>\n\n\nTEST_CASE(\"UnitRegisty Tests\")\n{\n  using namespace UnitConvert;\n  UnitRegistry ureg;\n  CHECK(ureg.size() == 0);\n\n  SECTION(\"Adding derived units from strings\")\n  {\n    // add base units to the registry\n    ureg.addBaseUnit<Dimension::Name::Length>(\"cm\");\n    ureg.addBaseUnit<Dimension::Name::Mass>(\"g\");\n    ureg.addBaseUnit<Dimension::Name::Time>(\"s\");\n    ureg.addBaseUnit<Dimension::Name::Temperature>(\"K\");\n    CHECK(ureg.size() == 4);\n\n    // add some derived units\n    ureg.addUnit(\"m = 100 cm\");\n    ureg.addUnit(\"1 in = 2.54 cm\");\n    ureg.addUnit(\"1 ft = 12 in\");\n    ureg.addUnit(\"1 J = 1 kg*m^2*s^-2\");\n    ureg.addUnit(\"1 W = 1 J/s\");\n    ureg.addUnit(\"1 cal = 4.184 J\");\n    ureg.addUnit(\"1 degC = K - 273.15\");\n    ureg.addUnit(\"C = K - 273.15\");\n    ureg.addUnit(\"delta_K = K\");\n    ureg.addUnit(\"delta_C = delta_K\");\n\n    Quantity<double> q;\n\n    q = ureg.makeQuantity<double>(24, \"cm\");\n    CHECK(q.to(\"m\").value() == Approx(0.24));\n    CHECK(q.to(\"cm\").value() == Approx(24));\n    CHECK(q.to(\"mcm\").value() == Approx(24000));\n    CHECK(q.to(\"mm\").value() == Approx(240));\n    CHECK(q.to_base_units().value() == Approx(24));\n\n    q = ureg.makeQuantity<double>(10, \"in\");\n    CHECK(q.to_base_units().value() == Approx(25.4));\n\n    q = ureg.makeQuantity<double>(1, \"J\");\n    // base units are g and cm so...\n    // kg m^-2 s^-2   g/kg cm/m cm/m = 1000 100 100 g cm^-2 s^-2 = 10,000,000 g\n    // cm^-2 s^-2\n    CHECK(q.to_base_units().value() == Approx(1e7));\n\n    q = ureg.makeQuantity<double>(2, \"cal\");\n    CHECK(q.to_base_units().value() == Approx(2 * 4.184 * 1e7));\n\n    q = ureg.makeQuantity<double>(\"100 degC\");\n    CHECK(q.to(\"K\").value() == Approx(373.15));\n    CHECK(q.to_base_units().value() == Approx(373.15));\n\n    CHECK(q.unit().is_offset());\n    CHECK(q.unit().offset() == Approx(-273.15));\n    CHECK(!q.to(\"K\").unit().is_offset());\n    CHECK(q.to(\"K\").unit().offset() == Approx(0));\n    // to_base_units will return a quantity with an offset unit here,\n    // but the offset will be zero.\n    CHECK(q.to_base_units().unit().is_offset());\n    CHECK(q.to_base_units().unit().offset() == Approx(0));\n\n    CHECK(ureg.makeQuantity<double>(\"20 C\").to(\"K\").value() == Approx(293.15));\n    CHECK(ureg.makeQuantity<double>(\"20 1/delta_C\").to(\"1/K\").value() ==\n          Approx(20));\n    CHECK(\n        ureg.makeQuantity<double>(\"1 cal / g / delta_C\").to(\"J/g/K\").value() ==\n        Approx(4.184));\n  }\n\n  SECTION(\"Loading derived units from stream\")\n  {\n    // add base units to the registry\n    ureg.addBaseUnit<Dimension::Name::Length>(\"cm\");\n    ureg.addBaseUnit<Dimension::Name::Mass>(\"g\");\n    ureg.addBaseUnit<Dimension::Name::Time>(\"s\");\n\n    std::string units =\n        \"m = 100 cm\\n\\n N = kg m / s^2\\n # comment\\nJ = N m\\nW = J/s\";\n    std::stringstream in(units);\n    ureg.loadUnits(in);\n\n    CHECK(ureg.makeQuantity<double>(10, \"g m^2 / s^3\").to(\"W\").value() == 0.01);\n  }\n\n  SECTION(\"Loading units from file\")\n  {\n    ureg.loadUnits(\"unit_definitions.txt\");\n\n    CHECK(ureg.makeQuantity<double>(10, \"g m^2 / s^3\").to(\"W\").value() == 0.01);\n    CHECK(ureg.makeQuantity<double>(5, \"m / s^2\").to(\"gravity\").value() ==\n          Approx(5 / 9.80665));\n    CHECK(ureg.makeQuantity<double>(5, \"gravity\").to(\"m/s^2\").value() ==\n          Approx(5 * 9.80665));\n\n    // H2O is a unit for pressure. 1 H2O is 9806.65 Pa\n    CHECK(ureg.makeQuantity<double>(5, \"H2O\").to(\"Pa/m\").value() ==\n          Approx(5 * 9806.65));\n  }\n\n  SECTION(\"Adding base units from strings\")\n  {\n    ureg.addUnit(\"m = [L]\");\n    ureg.addUnit(\"g = [M]\");\n    ureg.addUnit(\"s = [T]\");\n    ureg.addUnit(\"K = [THETA]\");\n    ureg.addUnit(\"A = [I]\");\n    ureg.addUnit(\"mol = [N]\");\n    ureg.addUnit(\"cd = [J]\");\n    ureg.addUnit(\"rad = [1]\");\n\n    ureg.addUnit(\"100 cm = m\");\n    ureg.addUnit(\"in = 2.54 cm\");\n    ureg.addUnit(\"ft = 12 in\");\n    ureg.addUnit(\"J = 1 kg*m^2*s^-2\");\n    ureg.addUnit(\"W = 1 J/s\");\n    ureg.addUnit(\"cal = 4.184 J\");\n\n    CHECK(ureg.makeQuantity<double>(\"2 m\").to(\"cm\").value() == Approx(200));\n    CHECK(ureg.makeQuantity<double>(\"2 m\").to(\"in\").value() ==\n          Approx(200 / 2.54));\n  }\n\n  SECTION(\"Parsing errors\")\n  {\n    CHECK_THROWS(ureg.getUnit(\"m\"));\n    CHECK_THROWS(ureg.makeUnit(\"m\"));\n    CHECK_THROWS(ureg.getUnit(\"[L]\"));\n    CHECK_NOTHROW(ureg.makeUnit(\"[L]\"));\n    CHECK_THROWS(ureg.makeQuantity<double>(\"10\"));\n\n  }\n}\n\nTEST_CASE(\"Global Unit Registry Tests\")\n{\n  using namespace UnitConvert;\n  SECTION(\"First Usage\")\n  {\n    UnitRegistry& ureg = getGlobalUnitRegistry();\n\n    CHECK(ureg.makeQuantity<double>(\"2 m\").to(\"cm\").value() == Approx(200));\n    CHECK(ureg.makeQuantity<double>(\"2 J\").to(\"kg cm^2 / s^2\").value() ==\n          Approx(2. * 100 * 100));\n    CHECK(ureg.makeQuantity<float>(\"0 degC\").to(\"degF\").value() == Approx(32));\n  }\n\n  SECTION(\"Second Usage\")\n  {\n    UnitRegistry& ureg = getGlobalUnitRegistry();\n\n    CHECK(ureg.makeQuantity<double>(\"2 m\").to(\"cm\").value() == Approx(200));\n    CHECK(ureg.makeQuantity<double>(\"2 J\").to(\"kg cm^2 / s^2\").value() ==\n          Approx(2. * 100 * 100));\n    CHECK(ureg.makeQuantity<float>(\"0 degC\").to(\"degF\").value() == Approx(32));\n\n  }\n\n  SECTION(\"Obscure conversions\")\n  {\n    UnitRegistry& ureg = getGlobalUnitRegistry();\n\n    auto q = ureg.makeQuantity<float>(\"2 pound\");\n    CHECK(q.to(\"kg\").value() == Approx(0.90718474));\n    CHECK(q.to(\"electron_mass\").value() == Approx(9.95879467317e+29));\n    CHECK(q.to(\"carat\").value() == Approx(4535.9237));\n    CHECK(q.to(\"metric_ton\").value() == Approx(0.00090718474));\n    CHECK(q.to(\"bag\").value() == Approx(0.0212765957447));\n    CHECK(q.to(\"grain\").value() == Approx(14000.0));\n    CHECK(q.to(\"oz\").value() == Approx(32));\n    CHECK(q.to(\"short_ton\").value() == Approx(0.001));\n\n  }\n\n}\n\nTEST_CASE(\"UnitRegisty Adding Unit Tests\")\n{\n  using namespace UnitConvert;\n  UnitRegistry ureg;\n  CHECK(ureg.size() == 0);\n\n  ureg.addUnit(\"m = [L]\");\n  ureg.addUnit(\"cm = 0.01 m\");\n\n  CHECK(ureg.makeQuantity<double>(\"2 m\").to(\"cm\").value() == Approx(200));\n\n  CHECK_THROWS(ureg.addUnit(\"cm = 10 m\"));\n  CHECK(ureg.makeQuantity<double>(\"2 m\").to(\"cm\").value() == Approx(200));\n\n  ureg.existing_unit_policy = UnitRegistry::EXISTING_UNIT_POLICY::Warn;\n  ureg.addUnit(\"cm = 10 m\");\n  CHECK(ureg.makeQuantity<double>(\"2 m\").to(\"cm\").value() == Approx(200));\n\n  ureg.existing_unit_policy = UnitRegistry::EXISTING_UNIT_POLICY::Ignore;\n  ureg.addUnit(\"cm = 10 m\");\n  CHECK(ureg.makeQuantity<double>(\"2 m\").to(\"cm\").value() == Approx(200));\n\n  ureg.existing_unit_policy = UnitRegistry::EXISTING_UNIT_POLICY::Overwrite;\n  ureg.addUnit(\"cm = 10 m\");\n  CHECK(ureg.makeQuantity<double>(\"2 m\").to(\"cm\").value() == Approx(0.2));\n\n\n\n\n\n\n}\n", "meta": {"hexsha": "4679347594182a35c46c330c0858e63279d003c1", "size": 6822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/CatchTests/UnitRegistry.cpp", "max_stars_repo_name": "CD3/UnitConvert", "max_stars_repo_head_hexsha": "06530130a952ac67bd3d88b2b7791a147c69db64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-22T11:01:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-22T11:01:10.000Z", "max_issues_repo_path": "testing/CatchTests/UnitRegistry.cpp", "max_issues_repo_name": "CD3/UnitConvert", "max_issues_repo_head_hexsha": "06530130a952ac67bd3d88b2b7791a147c69db64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-13T15:12:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T22:32:23.000Z", "max_forks_repo_path": "testing/CatchTests/UnitRegistry.cpp", "max_forks_repo_name": "CD3/UnitConvert", "max_forks_repo_head_hexsha": "06530130a952ac67bd3d88b2b7791a147c69db64", "max_forks_repo_licenses": ["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.2935779817, "max_line_length": 80, "alphanum_fraction": 0.5995309293, "num_tokens": 2151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5003970969106744}}
{"text": "#include <iostream>\n//\n#include <polyvec/api.hpp>\n#include <polyvec/curve-tracer/bezier_merging.hpp>\n#include <polyvec/core/log.hpp>\n#include <polyvec/misc.hpp>\n#include <polyvec/utils/num.hpp>\n#include <polyvec/io/vtk_curve_writer.hpp>\n#include <polyvec/geometry/winding_number.hpp>\n//\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nNAMESPACE_BEGIN()\n::polyvec::BezierCurve build_bezier(const Eigen::Matrix<double, 2, 4> ctrl) {\n  ::polyvec::BezierCurve bz;\n  bz.set_control_points(ctrl);\n  return bz;\n};\nNAMESPACE_END()\n\nNAMESPACE_BEGIN(polyvectest)\nNAMESPACE_BEGIN(BezierMerging)\n\nint potrace_params(int, char**) {\n  // Creat the points and then test the mapping\n  Eigen::Matrix<double, 2, 3> points0;\n  Eigen::Matrix<double, 2, 4> yy;\n  Eigen::Matrix2d A;\n  Eigen::Vector2d b;\n  Eigen::Matrix2d Amanu;\n  Eigen::Vector2d bmanu;\n  polyvec::VtkCurveWriter writer;\n\n  points0.col(0) << 2, 10;\n  points0.col(1) << 5, 7;\n  points0.col(2) << 4, 12;\n\n  //\n  // First Just Create a bezier and draw it\n  //\n  const double alpha_manu = 0.8;\n  const double beta_manu = 0.3;\n\n  yy.col(0) = points0.col(0);\n  yy.col(1) = ::polyvec::Num::lerp<Eigen::Vector2d>(points0.col(0),\n                                                    points0.col(1), alpha_manu);\n  yy.col(2) = ::polyvec::Num::lerp<Eigen::Vector2d>(points0.col(2),\n                                                    points0.col(1), beta_manu);\n  yy.col(3) = points0.col(2);\n\n  writer.add_polyline(points0);\n  writer.add_point(yy.col(0));\n  writer.add_point(yy.col(1));\n  writer.add_point(yy.col(2));\n  writer.add_point(yy.col(3));\n  writer.add_polyline(build_bezier(yy).get_tesselation2());\n  writer.dump(\"test_dump/potrace_params_00.vtk\");\n  writer.clear();\n\n  //\n  // Now create the potrace parameterization\n  //\n  ::polyfit::BezierMerging::PointParameters point_params{yy};\n  assert_break(point_params.is_potracable());\n  {\n    double alpha, beta;\n    Eigen::Vector2d oo;\n    bool is;\n    point_params.is_potracable(is, oo, alpha, beta);\n    assert_break(is == true);\n    assert_break(std::abs(alpha - alpha_manu) < 1e-8);\n    assert_break(std::abs(beta - beta_manu) < 1e-8);\n    assert_break((oo - points0.col(1)).norm() < 1e-8);\n  }\n  ::polyfit::BezierMerging::PotraceParameters potrace_params =\n      point_params.as_potrace_params();\n\n  writer.add_polyline(\n      build_bezier(potrace_params.get_yy().control_points).get_tesselation2());\n  writer.dump(\"test_dump/potrace_params_01.vtk\");\n  writer.clear();\n\n  //\n  // Now draw the closest equiparam bezier\n  //\n\n  writer.add_polyline(\n      build_bezier(potrace_params.equiparamed().get_yy().control_points)\n          .get_tesselation2());\n  writer.dump(\"test_dump/potrace_params_02.vtk\");\n  writer.clear();\n\n  //\n  // Now check that the area works\n  //\n  Eigen::Matrix2Xd tess;\n  tess = build_bezier(yy).get_tesselation2();\n  double area_tess;\n  {\n    bool is_ccw;\n    polyvec::WindingNumber::compute_orientation(tess, is_ccw, area_tess);\n  }\n  double area_analytic = potrace_params.get_areay();\n  double area_eqp_analytic = potrace_params.equiparamed().get_areay();\n\n  printf(\"Testing area \\n\");\n  printf(\"areas: tess: %.6f, ana: %.6f, anaeq: %.6f \\n\", area_tess,\n         area_analytic, area_eqp_analytic);\n\n  //\n  // Now check that the tangent things works\n  //\n  printf(\"Testing inverse tangent solver \\n\");\n  {\n    ::polyvec::BezierCurve bzcurve = build_bezier(yy);\n    for (int i = 1; i < 99 ; ++i) {\n      double t_solved;\n      bool success;\n\n      const double t = 1. / 99 * i;\n      const Eigen::Vector2d tan = bzcurve.dposdt(t).normalized();\n      potrace_params.t_for_tangent(tan, t_solved, success);\n\n      assert_break( success );\n      assert_break( std::abs(t-t_solved) < 1e-10 );\n    }\n  }\n\n  return EXIT_FAILURE;\n}\n\nNAMESPACE_END(BezierMerging)\nNAMESPACE_END(polyvectest)\n", "meta": {"hexsha": "5685d9ae4c874170051509089fec49e127053d01", "size": 3799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/tests/bezier_merging/_potrace_params.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/_potrace_params.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/_potrace_params.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": 28.1407407407, "max_line_length": 80, "alphanum_fraction": 0.6693866807, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5003970945039343}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2016 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 \"rips_complex\"\n#include <boost/test/unit_test.hpp>\n\n#include <cmath>  // float comparison\n#include <limits>\n#include <string>\n#include <vector>\n#include <algorithm>    // std::max\n\n#include <gudhi/Rips_complex.h>\n#include <gudhi/Sparse_rips_complex.h>\n// to construct Rips_complex from a OFF file of points\n#include <gudhi/Points_off_io.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/distance_functions.h>\n#include <gudhi/reader_utils.h>\n#include <gudhi/Unitary_tests_utils.h>\n\n// Type definitions\nusing Point = std::vector<double>;\nusing Simplex_tree = Gudhi::Simplex_tree<>;\nusing Filtration_value = Simplex_tree::Filtration_value;\nusing Rips_complex = Gudhi::rips_complex::Rips_complex<Simplex_tree::Filtration_value>;\nusing Sparse_rips_complex = Gudhi::rips_complex::Sparse_rips_complex<Simplex_tree::Filtration_value>;\nusing Distance_matrix = std::vector<std::vector<Filtration_value>>;\n\nBOOST_AUTO_TEST_CASE(RIPS_DOC_OFF_file) {\n  // ----------------------------------------------------------------------------\n  //\n  // Init of a Rips complex from a OFF file\n  //\n  // ----------------------------------------------------------------------------\n  std::string off_file_name(\"alphacomplexdoc.off\");\n  double rips_threshold = 12.0;\n  std::cout << \"========== OFF FILE NAME = \" << off_file_name << \" - Rips threshold=\" <<\n      rips_threshold << \"==========\" << std::endl;\n\n  Gudhi::Points_off_reader<Point> off_reader(off_file_name);\n  Rips_complex rips_complex_from_file(off_reader.get_point_cloud(), rips_threshold, Gudhi::Euclidean_distance());\n\n  const int DIMENSION_1 = 1;\n  Simplex_tree st;\n  rips_complex_from_file.create_complex(st, DIMENSION_1);\n  std::cout << \"st.dimension()=\" << st.dimension() << std::endl;\n  BOOST_CHECK(st.dimension() == DIMENSION_1);\n\n  const int NUMBER_OF_VERTICES = 7;\n  std::cout << \"st.num_vertices()=\" << st.num_vertices() << std::endl;\n  BOOST_CHECK(st.num_vertices() == NUMBER_OF_VERTICES);\n\n  std::cout << \"st.num_simplices()=\" << st.num_simplices() << std::endl;\n  BOOST_CHECK(st.num_simplices() == 18);\n\n  // Check filtration values of vertices is 0.0\n  for (auto f_simplex : st.skeleton_simplex_range(0)) {\n    BOOST_CHECK(st.filtration(f_simplex) == 0.0);\n  }\n\n  // Check filtration values of edges\n  for (auto f_simplex : st.skeleton_simplex_range(DIMENSION_1)) {\n    if (DIMENSION_1 == st.dimension(f_simplex)) {\n      std::vector<Point> vp;\n      std::cout << \"vertex = (\";\n      for (auto vertex : st.simplex_vertex_range(f_simplex)) {\n        std::cout << vertex << \",\";\n        vp.push_back(off_reader.get_point_cloud().at(vertex));\n      }\n      std::cout << \") - distance =\" << Gudhi::Euclidean_distance()(vp.at(0), vp.at(1)) <<\n          \" - filtration =\" << st.filtration(f_simplex) << std::endl;\n      BOOST_CHECK(vp.size() == 2);\n      GUDHI_TEST_FLOAT_EQUALITY_CHECK(st.filtration(f_simplex), Gudhi::Euclidean_distance()(vp.at(0), vp.at(1)));\n    }\n  }\n\n  const int DIMENSION_2 = 2;\n  Simplex_tree st2;\n  rips_complex_from_file.create_complex(st2, DIMENSION_2);\n  std::cout << \"st2.dimension()=\" << st2.dimension() << std::endl;\n  BOOST_CHECK(st2.dimension() == DIMENSION_2);\n  \n  std::cout << \"st2.num_vertices()=\" << st2.num_vertices() << std::endl;\n  BOOST_CHECK(st2.num_vertices() == NUMBER_OF_VERTICES);\n\n  std::cout << \"st2.num_simplices()=\" << st2.num_simplices() << std::endl;\n  BOOST_CHECK(st2.num_simplices() == 23);\n\n  Simplex_tree::Filtration_value f01 = st2.filtration(st2.find({0, 1}));\n  Simplex_tree::Filtration_value f02 = st2.filtration(st2.find({0, 2}));\n  Simplex_tree::Filtration_value f12 = st2.filtration(st2.find({1, 2}));\n  Simplex_tree::Filtration_value f012 = st2.filtration(st2.find({0, 1, 2}));\n  std::cout << \"f012= \" << f012 << \" | f01= \" << f01 << \" - f02= \" << f02 << \" - f12= \" << f12 << std::endl;\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(f012, std::max(f01, std::max(f02,f12)));\n  \n  Simplex_tree::Filtration_value f45 = st2.filtration(st2.find({4, 5}));\n  Simplex_tree::Filtration_value f56 = st2.filtration(st2.find({5, 6}));\n  Simplex_tree::Filtration_value f46 = st2.filtration(st2.find({4, 6}));\n  Simplex_tree::Filtration_value f456 = st2.filtration(st2.find({4, 5, 6}));\n  std::cout << \"f456= \" << f456 << \" | f45= \" << f45 << \" - f56= \" << f56 << \" - f46= \" << f46 << std::endl;\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(f456, std::max(f45, std::max(f56,f46)));\n\n  const int DIMENSION_3 = 3;\n  Simplex_tree st3;\n  rips_complex_from_file.create_complex(st3, DIMENSION_3);\n  std::cout << \"st3.dimension()=\" << st3.dimension() << std::endl;\n  BOOST_CHECK(st3.dimension() == DIMENSION_3);\n  \n  std::cout << \"st3.num_vertices()=\" << st3.num_vertices() << std::endl;\n  BOOST_CHECK(st3.num_vertices() == NUMBER_OF_VERTICES);\n\n  std::cout << \"st3.num_simplices()=\" << st3.num_simplices() << std::endl;\n  BOOST_CHECK(st3.num_simplices() == 24);\n\n  Simplex_tree::Filtration_value f123 = st3.filtration(st3.find({1, 2, 3}));\n  Simplex_tree::Filtration_value f013 = st3.filtration(st3.find({0, 1, 3}));\n  Simplex_tree::Filtration_value f023 = st3.filtration(st3.find({0, 2, 3}));\n  Simplex_tree::Filtration_value f0123 = st3.filtration(st3.find({0, 1, 2, 3}));\n  std::cout << \"f0123= \" << f0123 << \" | f012= \" << f012 << \" - f123= \" << f123 << \" - f013= \" << f013 <<\n      \" - f023= \" << f023 << std::endl;\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(f0123, std::max(f012, std::max(f123, std::max(f013, f023))));\n\n}\n\nusing Vector_of_points = std::vector<Point>;\n\nbool is_point_in_list(Vector_of_points points_list, Point point) {\n  for (auto& point_in_list : points_list) {\n    if (point_in_list == point) {\n      return true;  // point found\n    }\n  }\n  return false;  // point not found\n}\n\nclass Custom_square_euclidean_distance {\n public:\n  template< typename Point >\n  auto operator()(const Point& p1, const Point& p2) -> typename Point::value_type {\n    auto it1 = p1.begin();\n    auto it2 = p2.begin();\n    typename Point::value_type dist = 0.;\n    for (; it1 != p1.end(); ++it1, ++it2) {\n      typename Point::value_type tmp = (*it1) - (*it2);\n      dist += tmp*tmp;\n    }\n    return dist;\n  }\n};\n\nBOOST_AUTO_TEST_CASE(Rips_complex_from_points) {\n  // ----------------------------------------------------------------------------\n  // Init of a list of points\n  // ----------------------------------------------------------------------------\n  Vector_of_points points;\n  std::vector<double> coords = { 0.0, 0.0, 0.0, 1.0 };\n  points.push_back(Point(coords.begin(), coords.end()));\n  coords = { 0.0, 0.0, 1.0, 0.0 };\n  points.push_back(Point(coords.begin(), coords.end()));\n  coords = { 0.0, 1.0, 0.0, 0.0 };\n  points.push_back(Point(coords.begin(), coords.end()));\n  coords = { 1.0, 0.0, 0.0, 0.0 };\n  points.push_back(Point(coords.begin(), coords.end()));\n\n  // ----------------------------------------------------------------------------\n  // Init of a Rips complex from the list of points\n  // ----------------------------------------------------------------------------\n  Rips_complex rips_complex_from_points(points, 2.0, Custom_square_euclidean_distance());\n\n  std::cout << \"========== Rips_complex_from_points ==========\" << std::endl;\n  Simplex_tree st;\n  const int DIMENSION = 3;\n  rips_complex_from_points.create_complex(st, DIMENSION);\n\n  // Another way to check num_simplices\n  std::cout << \"Iterator on Rips complex simplices in the filtration order, with [filtration value]:\" << std::endl;\n  int num_simplices = 0;\n  for (auto f_simplex : st.filtration_simplex_range()) {\n    num_simplices++;\n    std::cout << \"   ( \";\n    for (auto vertex : st.simplex_vertex_range(f_simplex)) {\n      std::cout << vertex << \" \";\n    }\n    std::cout << \") -> \" << \"[\" << st.filtration(f_simplex) << \"] \";\n    std::cout << std::endl;\n  }\n  BOOST_CHECK(num_simplices == 15);\n  std::cout << \"st.num_simplices()=\" << st.num_simplices() << std::endl;\n  BOOST_CHECK(st.num_simplices() == 15);\n\n  std::cout << \"st.dimension()=\" << st.dimension() << std::endl;\n  BOOST_CHECK(st.dimension() == DIMENSION);\n  std::cout << \"st.num_vertices()=\" << st.num_vertices() << std::endl;\n  BOOST_CHECK(st.num_vertices() == 4);\n\n  for (auto f_simplex : st.filtration_simplex_range()) {\n    std::cout << \"dimension(\" << st.dimension(f_simplex) << \") - f = \" << st.filtration(f_simplex) << std::endl;\n    switch (st.dimension(f_simplex)) {\n      case 0:\n        GUDHI_TEST_FLOAT_EQUALITY_CHECK(st.filtration(f_simplex), 0.0);\n        break;\n      case 1:\n      case 2:\n      case 3:\n        GUDHI_TEST_FLOAT_EQUALITY_CHECK(st.filtration(f_simplex), 2.0);\n        break;\n      default:\n        BOOST_CHECK(false);  // Shall not happen\n        break;\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(Sparse_rips_complex_from_points) {\n  // This is a clone of the test above\n  // ----------------------------------------------------------------------------\n  // Init of a list of points\n  // ----------------------------------------------------------------------------\n  Vector_of_points points;\n  std::vector<double> coords = { 0.0, 0.0, 0.0, 1.0 };\n  points.push_back(Point(coords.begin(), coords.end()));\n  coords = { 0.0, 0.0, 1.0, 0.0 };\n  points.push_back(Point(coords.begin(), coords.end()));\n  coords = { 0.0, 1.0, 0.0, 0.0 };\n  points.push_back(Point(coords.begin(), coords.end()));\n  coords = { 1.0, 0.0, 0.0, 0.0 };\n  points.push_back(Point(coords.begin(), coords.end()));\n\n  // ----------------------------------------------------------------------------\n  // Init of a Rips complex from the list of points\n  // ----------------------------------------------------------------------------\n  // .001 is small enough that we get a deterministic result matching the exact Rips\n  Sparse_rips_complex sparse_rips(points, Custom_square_euclidean_distance(), .001);\n\n  std::cout << \"========== Sparse_rips_complex_from_points ==========\" << std::endl;\n  Simplex_tree st;\n  const int DIMENSION = 3;\n  sparse_rips.create_complex(st, DIMENSION);\n\n  // Another way to check num_simplices\n  std::cout << \"Iterator on Rips complex simplices in the filtration order, with [filtration value]:\" << std::endl;\n  int num_simplices = 0;\n  for (auto f_simplex : st.filtration_simplex_range()) {\n    num_simplices++;\n    std::cout << \"   ( \";\n    for (auto vertex : st.simplex_vertex_range(f_simplex)) {\n      std::cout << vertex << \" \";\n    }\n    std::cout << \") -> \" << \"[\" << st.filtration(f_simplex) << \"] \";\n    std::cout << std::endl;\n  }\n  BOOST_CHECK(num_simplices == 15);\n  std::cout << \"st.num_simplices()=\" << st.num_simplices() << std::endl;\n  BOOST_CHECK(st.num_simplices() == 15);\n\n  std::cout << \"st.dimension()=\" << st.dimension() << std::endl;\n  BOOST_CHECK(st.dimension() == DIMENSION);\n  std::cout << \"st.num_vertices()=\" << st.num_vertices() << std::endl;\n  BOOST_CHECK(st.num_vertices() == 4);\n\n  for (auto f_simplex : st.filtration_simplex_range()) {\n    std::cout << \"dimension(\" << st.dimension(f_simplex) << \") - f = \" << st.filtration(f_simplex) << std::endl;\n    switch (st.dimension(f_simplex)) {\n      case 0:\n        GUDHI_TEST_FLOAT_EQUALITY_CHECK(st.filtration(f_simplex), 0.0);\n        break;\n      case 1:\n      case 2:\n      case 3:\n        GUDHI_TEST_FLOAT_EQUALITY_CHECK(st.filtration(f_simplex), 2.0);\n        break;\n      default:\n        BOOST_CHECK(false);  // Shall not happen\n        break;\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(Rips_doc_csv_file) {\n  // ----------------------------------------------------------------------------\n  //\n  // Init of a Rips complex from a OFF file\n  //\n  // ----------------------------------------------------------------------------\n  std::string csv_file_name(\"full_square_distance_matrix.csv\");\n  double rips_threshold = 12.0;\n  std::cout << \"========== CSV FILE NAME = \" << csv_file_name << \" - Rips threshold=\" <<\n      rips_threshold << \"==========\" << std::endl;\n\n  Distance_matrix distances = Gudhi::read_lower_triangular_matrix_from_csv_file<Filtration_value>(csv_file_name);\n  Rips_complex rips_complex_from_file(distances, rips_threshold);\n\n  const int DIMENSION_1 = 1;\n  Simplex_tree st;\n  rips_complex_from_file.create_complex(st, DIMENSION_1);\n  std::cout << \"st.dimension()=\" << st.dimension() << std::endl;\n  BOOST_CHECK(st.dimension() == DIMENSION_1);\n\n  const int NUMBER_OF_VERTICES = 7;\n  std::cout << \"st.num_vertices()=\" << st.num_vertices() << std::endl;\n  BOOST_CHECK(st.num_vertices() == NUMBER_OF_VERTICES);\n\n  std::cout << \"st.num_simplices()=\" << st.num_simplices() << std::endl;\n  BOOST_CHECK(st.num_simplices() == 18);\n\n  // Check filtration values of vertices is 0.0\n  for (auto f_simplex : st.skeleton_simplex_range(0)) {\n    BOOST_CHECK(st.filtration(f_simplex) == 0.0);\n  }\n\n  // Check filtration values of edges\n  for (auto f_simplex : st.skeleton_simplex_range(DIMENSION_1)) {\n    if (DIMENSION_1 == st.dimension(f_simplex)) {\n      std::vector<Simplex_tree::Vertex_handle> vvh;\n      std::cout << \"vertex = (\";\n      for (auto vertex : st.simplex_vertex_range(f_simplex)) {\n        std::cout << vertex << \",\";\n        vvh.push_back(vertex);\n      }\n      std::cout << \") - filtration =\" << st.filtration(f_simplex) << std::endl;\n      BOOST_CHECK(vvh.size() == 2);\n      GUDHI_TEST_FLOAT_EQUALITY_CHECK(st.filtration(f_simplex), distances[vvh.at(0)][vvh.at(1)]);\n    }\n  }\n\n  const int DIMENSION_2 = 2;\n  Simplex_tree st2;\n  rips_complex_from_file.create_complex(st2, DIMENSION_2);\n  std::cout << \"st2.dimension()=\" << st2.dimension() << std::endl;\n  BOOST_CHECK(st2.dimension() == DIMENSION_2);\n  \n  std::cout << \"st2.num_vertices()=\" << st2.num_vertices() << std::endl;\n  BOOST_CHECK(st2.num_vertices() == NUMBER_OF_VERTICES);\n\n  std::cout << \"st2.num_simplices()=\" << st2.num_simplices() << std::endl;\n  BOOST_CHECK(st2.num_simplices() == 23);\n\n  Simplex_tree::Filtration_value f01 = st2.filtration(st2.find({0, 1}));\n  Simplex_tree::Filtration_value f02 = st2.filtration(st2.find({0, 2}));\n  Simplex_tree::Filtration_value f12 = st2.filtration(st2.find({1, 2}));\n  Simplex_tree::Filtration_value f012 = st2.filtration(st2.find({0, 1, 2}));\n  std::cout << \"f012= \" << f012 << \" | f01= \" << f01 << \" - f02= \" << f02 << \" - f12= \" << f12 << std::endl;\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(f012, std::max(f01, std::max(f02,f12)));\n  \n  Simplex_tree::Filtration_value f45 = st2.filtration(st2.find({4, 5}));\n  Simplex_tree::Filtration_value f56 = st2.filtration(st2.find({5, 6}));\n  Simplex_tree::Filtration_value f46 = st2.filtration(st2.find({4, 6}));\n  Simplex_tree::Filtration_value f456 = st2.filtration(st2.find({4, 5, 6}));\n  std::cout << \"f456= \" << f456 << \" | f45= \" << f45 << \" - f56= \" << f56 << \" - f46= \" << f46 << std::endl;\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(f456, std::max(f45, std::max(f56,f46)));\n\n  const int DIMENSION_3 = 3;\n  Simplex_tree st3;\n  rips_complex_from_file.create_complex(st3, DIMENSION_3);\n  std::cout << \"st3.dimension()=\" << st3.dimension() << std::endl;\n  BOOST_CHECK(st3.dimension() == DIMENSION_3);\n  \n  std::cout << \"st3.num_vertices()=\" << st3.num_vertices() << std::endl;\n  BOOST_CHECK(st3.num_vertices() == NUMBER_OF_VERTICES);\n\n  std::cout << \"st3.num_simplices()=\" << st3.num_simplices() << std::endl;\n  BOOST_CHECK(st3.num_simplices() == 24);\n\n  Simplex_tree::Filtration_value f123 = st3.filtration(st3.find({1, 2, 3}));\n  Simplex_tree::Filtration_value f013 = st3.filtration(st3.find({0, 1, 3}));\n  Simplex_tree::Filtration_value f023 = st3.filtration(st3.find({0, 2, 3}));\n  Simplex_tree::Filtration_value f0123 = st3.filtration(st3.find({0, 1, 2, 3}));\n  std::cout << \"f0123= \" << f0123 << \" | f012= \" << f012 << \" - f123= \" << f123 << \" - f013= \" << f013 <<\n      \" - f023= \" << f023 << std::endl;\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(f0123, std::max(f012, std::max(f123, std::max(f013, f023))));\n\n}\n\n#ifdef GUDHI_DEBUG\nBOOST_AUTO_TEST_CASE(Rips_create_complex_throw) {\n  // ----------------------------------------------------------------------------\n  //\n  // Init of a Rips complex from a OFF file\n  //\n  // ----------------------------------------------------------------------------\n  std::string off_file_name(\"alphacomplexdoc.off\");\n  double rips_threshold = 12.0;\n  std::cout << \"========== OFF FILE NAME = \" << off_file_name << \" - Rips threshold=\" <<\n      rips_threshold << \"==========\" << std::endl;\n\n  Gudhi::Points_off_reader<Point> off_reader(off_file_name);\n  Rips_complex rips_complex_from_file(off_reader.get_point_cloud(), rips_threshold, Gudhi::Euclidean_distance());\n\n  Simplex_tree stree;\n  std::vector<int> simplex = {0, 1, 2};\n  stree.insert_simplex_and_subfaces(simplex);\n  std::cout << \"Check exception throw in debug mode\" << std::endl;\n  // throw excpt because stree is not empty\n  BOOST_CHECK_THROW (rips_complex_from_file.create_complex(stree, 1), std::invalid_argument);\n}\n#endif\n", "meta": {"hexsha": "1225f8df4e0a8ae6765de9fbfa0c94d66d886df3", "size": 17101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Rips_complex/test/test_rips_complex.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/Rips_complex/test/test_rips_complex.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/Rips_complex/test/test_rips_complex.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": 42.1206896552, "max_line_length": 115, "alphanum_fraction": 0.6138822291, "num_tokens": 4948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.500364526143858}}
{"text": "/*  \nThe MIT License\n\nCopyright (c) 2020-2022 Zhepei Wang\n                        Hongkai Ye\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies 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\nTHE SOFTWARE.\n*/\n#ifndef ROOT_FINDER_HPP\n#define ROOT_FINDER_HPP\n\n#define _USE_MATH_DEFINES\n#include <cfloat>\n#include <cmath>\n#include <set>\n#include <Eigen/Eigen>\n\nnamespace RootFinderParam\n{\n    constexpr size_t highestOrder = 64;\n}\n\nnamespace RootFinderPriv\n{\n\n    inline int polyMod(double *u, double *v, double *r, int lu, int lv)\n    // Modulus of u(x)/v(x)\n    // The leading coefficient of v, i.e., v[0], must be 1.0 or -1.0\n    // The length of u, v, and r are lu, lv, and lu, respectively\n    {\n        int orderu = lu - 1;\n        int orderv = lv - 1;\n\n        memcpy(r, u, lu * sizeof(double));\n\n        if (v[0] < 0.0)\n        {\n            for (int i = orderv + 1; i <= orderu; i += 2)\n            {\n                r[i] = -r[i];\n            }\n            for (int i = 0; i <= orderu - orderv; i++)\n            {\n                for (int j = i + 1; j <= orderv + i; j++)\n                {\n                    r[j] = -r[j] - r[i] * v[j - i];\n                }\n            }\n        }\n        else\n        {\n            for (int i = 0; i <= orderu - orderv; i++)\n            {\n                for (int j = i + 1; j <= orderv + i; j++)\n                {\n                    r[j] = r[j] - r[i] * v[j - i];\n                }\n            }\n        }\n\n        int k = orderv - 1;\n        while (k >= 0 && fabs(r[orderu - k]) < DBL_EPSILON)\n        {\n            r[orderu - k] = 0.0;\n            k--;\n        }\n\n        return (k <= 0) ? 1 : (k + 1);\n    }\n\n    inline double polyEval(double *p, int len, double x)\n    // Evaluate the polynomial p(x), which has len coefficients\n    // Note: Horner scheme should not be employed here !!!\n    // Horner scheme has bad numerical stability despite of its efficiency.\n    // These errors are particularly troublesome for root-finding algorithms.\n    // When the polynomial is evaluated near a zero, catastrophic\n    // cancellation (subtracting two nearby numbers) is guaranteed to occur.\n    // Therefore, Horner scheme may slow down some root-finding algorithms.\n    {\n        double retVal = 0.0;\n\n        if (len > 0)\n        {\n            if (fabs(x) < DBL_EPSILON)\n            {\n                retVal = p[len - 1];\n            }\n            else if (x == 1.0)\n            {\n                for (int i = len - 1; i >= 0; i--)\n                {\n                    retVal += p[i];\n                }\n            }\n            else\n            {\n                double xn = 1.0;\n\n                for (int i = len - 1; i >= 0; i--)\n                {\n                    retVal += p[i] * xn;\n                    xn *= x;\n                }\n            }\n        }\n\n        return retVal;\n    }\n\n    inline std::set<double> solveCub(double a, double b, double c, double d)\n    // Calculate all roots of a*x^3 + b*x^2 + c*x + d = 0\n    {\n        std::set<double> roots;\n\n        constexpr double cos120 = -0.50;\n        constexpr double sin120 = 0.866025403784438646764;\n\n        if (fabs(d) < DBL_EPSILON)\n        {\n            // First solution is x = 0\n            roots.insert(0.0);\n\n            // Converting to a quadratic equation\n            d = c;\n            c = b;\n            b = a;\n            a = 0.0;\n        }\n\n        if (fabs(a) < DBL_EPSILON)\n        {\n            if (fabs(b) < DBL_EPSILON)\n            {\n                // Linear equation\n                if (fabs(c) > DBL_EPSILON)\n                    roots.insert(-d / c);\n            }\n            else\n            {\n                // Quadratic equation\n                double discriminant = c * c - 4.0 * b * d;\n                if (discriminant >= 0)\n                {\n                    double inv2b = 1.0 / (2.0 * b);\n                    double y = sqrt(discriminant);\n                    roots.insert((-c + y) * inv2b);\n                    roots.insert((-c - y) * inv2b);\n                }\n            }\n        }\n        else\n        {\n            // Cubic equation\n            double inva = 1.0 / a;\n            double invaa = inva * inva;\n            double bb = b * b;\n            double bover3a = b * (1.0 / 3.0) * inva;\n            double p = (3.0 * a * c - bb) * (1.0 / 3.0) * invaa;\n            double halfq = (2.0 * bb * b - 9.0 * a * b * c + 27.0 * a * a * d) * (0.5 / 27.0) * invaa * inva;\n            double yy = p * p * p / 27.0 + halfq * halfq;\n\n            if (yy > DBL_EPSILON)\n            {\n                // Sqrt is positive: one real solution\n                double y = sqrt(yy);\n                double uuu = -halfq + y;\n                double vvv = -halfq - y;\n                double www = fabs(uuu) > fabs(vvv) ? uuu : vvv;\n                double w = (www < 0) ? -pow(fabs(www), 1.0 / 3.0) : pow(www, 1.0 / 3.0);\n                roots.insert(w - p / (3.0 * w) - bover3a);\n            }\n            else if (yy < -DBL_EPSILON)\n            {\n                // Sqrt is negative: three real solutions\n                double x = -halfq;\n                double y = sqrt(-yy);\n                double theta;\n                double r;\n                double ux;\n                double uyi;\n                // Convert to polar form\n                if (fabs(x) > DBL_EPSILON)\n                {\n                    theta = (x > 0.0) ? atan(y / x) : (atan(y / x) + M_PI);\n                    r = sqrt(x * x - yy);\n                }\n                else\n                {\n                    // Vertical line\n                    theta = M_PI / 2.0;\n                    r = y;\n                }\n                // Calculate cube root\n                theta /= 3.0;\n                r = pow(r, 1.0 / 3.0);\n                // Convert to complex coordinate\n                ux = cos(theta) * r;\n                uyi = sin(theta) * r;\n                // First solution\n                roots.insert(ux + ux - bover3a);\n                // Second solution, rotate +120 degrees\n                roots.insert(2.0 * (ux * cos120 - uyi * sin120) - bover3a);\n                // Third solution, rotate -120 degrees\n                roots.insert(2.0 * (ux * cos120 + uyi * sin120) - bover3a);\n            }\n            else\n            {\n                // Sqrt is zero: two real solutions\n                double www = -halfq;\n                double w = (www < 0.0) ? -pow(fabs(www), 1.0 / 3.0) : pow(www, 1.0 / 3.0);\n                // First solution\n                roots.insert(w + w - bover3a);\n                // Second solution, rotate +120 degrees\n                roots.insert(2.0 * w * cos120 - bover3a);\n            }\n        }\n        return roots;\n    }\n\n    inline int solveResolvent(double *x, double a, double b, double c)\n    // Solve resolvent eqaution of corresponding Quartic equation\n    // The input x must be of length 3\n    // Number of zeros are returned\n    {\n        double a2 = a * a;\n        double q = (a2 - 3.0 * b) / 9.0;\n        double r = (a * (2.0 * a2 - 9.0 * b) + 27.0 * c) / 54.0;\n        double r2 = r * r;\n        double q3 = q * q * q;\n        double A, B;\n        if (r2 < q3)\n        {\n            double t = r / sqrt(q3);\n            if (t < -1.0)\n            {\n                t = -1.0;\n            }\n            if (t > 1.0)\n            {\n                t = 1.0;\n            }\n            t = acos(t);\n            a /= 3.0;\n            q = -2.0 * sqrt(q);\n            x[0] = q * cos(t / 3.0) - a;\n            x[1] = q * cos((t + M_PI * 2.0) / 3.0) - a;\n            x[2] = q * cos((t - M_PI * 2.0) / 3.0) - a;\n            return 3;\n        }\n        else\n        {\n            A = -pow(fabs(r) + sqrt(r2 - q3), 1.0 / 3.0);\n            if (r < 0.0)\n            {\n                A = -A;\n            }\n            B = (0.0 == A ? 0.0 : q / A);\n\n            a /= 3.0;\n            x[0] = (A + B) - a;\n            x[1] = -0.5 * (A + B) - a;\n            x[2] = 0.5 * sqrt(3.0) * (A - B);\n            if (fabs(x[2]) < DBL_EPSILON)\n            {\n                x[2] = x[1];\n                return 2;\n            }\n\n            return 1;\n        }\n    }\n\n    inline std::set<double> solveQuartMonic(double a, double b, double c, double d)\n    // Calculate all roots of the monic quartic equation:\n    // x^4 + a*x^3 + b*x^2 + c*x +d = 0\n    {\n        std::set<double> roots;\n\n        double a3 = -b;\n        double b3 = a * c - 4.0 * d;\n        double c3 = -a * a * d - c * c + 4.0 * b * d;\n\n        // Solve the resolvent: y^3 - b*y^2 + (ac - 4*d)*y - a^2*d - c^2 + 4*b*d = 0\n        double x3[3];\n        int iZeroes = solveResolvent(x3, a3, b3, c3);\n\n        double q1, q2, p1, p2, D, sqrtD, y;\n\n        y = x3[0];\n        // Choosing Y with maximal absolute value.\n        if (iZeroes != 1)\n        {\n            if (fabs(x3[1]) > fabs(y))\n            {\n                y = x3[1];\n            }\n            if (fabs(x3[2]) > fabs(y))\n            {\n                y = x3[2];\n            }\n        }\n\n        // h1 + h2 = y && h1*h2 = d  <=>  h^2 - y*h + d = 0    (h === q)\n\n        D = y * y - 4.0 * d;\n        if (fabs(D) < DBL_EPSILON) //In other words: D == 0\n        {\n            q1 = q2 = y * 0.5;\n            // g1 + g2 = a && g1 + g2 = b - y   <=>   g^2 - a*g + b - y = 0    (p === g)\n            D = a * a - 4.0 * (b - y);\n            if (fabs(D) < DBL_EPSILON) //In other words: D == 0\n            {\n                p1 = p2 = a * 0.5;\n            }\n            else\n            {\n                sqrtD = sqrt(D);\n                p1 = (a + sqrtD) * 0.5;\n                p2 = (a - sqrtD) * 0.5;\n            }\n        }\n        else\n        {\n            sqrtD = sqrt(D);\n            q1 = (y + sqrtD) * 0.5;\n            q2 = (y - sqrtD) * 0.5;\n            // g1 + g2 = a && g1*h2 + g2*h1 = c   ( && g === p )  Krammer\n            p1 = (a * q1 - c) / (q1 - q2);\n            p2 = (c - a * q2) / (q1 - q2);\n        }\n\n        // Solve the quadratic equation: x^2 + p1*x + q1 = 0\n        D = p1 * p1 - 4.0 * q1;\n        if (fabs(D) < DBL_EPSILON)\n        {\n            roots.insert(-p1 * 0.5);\n        }\n        else if (D > 0.0)\n        {\n            sqrtD = sqrt(D);\n            roots.insert((-p1 + sqrtD) * 0.5);\n            roots.insert((-p1 - sqrtD) * 0.5);\n        }\n\n        // Solve the quadratic equation: x^2 + p2*x + q2 = 0\n        D = p2 * p2 - 4.0 * q2;\n        if (fabs(D) < DBL_EPSILON)\n        {\n            roots.insert(-p2 * 0.5);\n        }\n        else if (D > 0.0)\n        {\n            sqrtD = sqrt(D);\n            roots.insert((-p2 + sqrtD) * 0.5);\n            roots.insert((-p2 - sqrtD) * 0.5);\n        }\n\n        return roots;\n    }\n\n    inline std::set<double> solveQuart(double a, double b, double c, double d, double e)\n    // Calculate the quartic equation: a*x^4 + b*x^3 + c*x^2 + d*x + e = 0\n    // All coefficients can be zero\n    {\n        if (fabs(a) < DBL_EPSILON)\n        {\n            return solveCub(b, c, d, e);\n        }\n        else\n        {\n            return solveQuartMonic(b / a, c / a, d / a, e / a);\n        }\n    }\n\n    inline std::set<double> eigenSolveRealRoots(const Eigen::VectorXd &coeffs, double lbound, double ubound, double tol)\n    // Calculate roots of coeffs(x) inside (lbound, rbound) by computing eigen values of its companion matrix\n    // Complex roots with magnitude of imaginary part less than tol are considered real\n    {\n        std::set<double> rts;\n\n        int order = (int)coeffs.size() - 1;\n        Eigen::VectorXd monicCoeffs(order + 1);\n        monicCoeffs << 1.0, coeffs.tail(order) / coeffs(0);\n\n        Eigen::MatrixXd companionMat(order, order);\n        companionMat.setZero();\n        companionMat(0, order - 1) = -monicCoeffs(order);\n        for (int i = 1; i < order; i++)\n        {\n            companionMat(i, i - 1) = 1.0;\n            companionMat(i, order - 1) = -monicCoeffs(order - i);\n        }\n        Eigen::VectorXcd eivals = companionMat.eigenvalues();\n        double real;\n        int eivalsNum = eivals.size();\n        for (int i = 0; i < eivalsNum; i++)\n        {\n            real = eivals(i).real();\n            if (eivals(i).imag() < tol && real > lbound && real < ubound)\n                rts.insert(real);\n        }\n\n        return rts;\n    }\n\n    inline double numSignVar(double x, double **sturmSeqs, int *szSeq, int len)\n    // Calculate the number of sign variations of the Sturm sequences at x\n    // The i-th sequence with size szSeq[i] stored in sturmSeqs[i][], 0 <= i < len\n    {\n        double y, lasty;\n        int signVar = 0;\n        lasty = polyEval(sturmSeqs[0], szSeq[0], x);\n        for (int i = 1; i < len; i++)\n        {\n            y = polyEval(sturmSeqs[i], szSeq[i], x);\n            if (lasty == 0.0 || lasty * y < 0.0)\n            {\n                ++signVar;\n            }\n            lasty = y;\n        }\n\n        return signVar;\n    };\n\n    inline void polyDeri(double *coeffs, double *dcoeffs, int len)\n    // Calculate the derivative poly coefficients of a given poly\n    {\n        int horder = len - 1;\n        for (int i = 0; i < horder; i++)\n        {\n            dcoeffs[i] = (horder - i) * coeffs[i];\n        }\n        return;\n    }\n\n    template <typename F, typename DF>\n    inline double safeNewton(const F &func, const DF &dfunc,\n                             const double &l, const double &h,\n                             const double &tol, const int &maxIts)\n    // Safe Newton Method\n    // Requirements: f(l)*f(h)<=0\n    {\n        double xh, xl;\n        double fl = func(l);\n        double fh = func(h);\n        if (fl == 0.0)\n        {\n            return l;\n        }\n        if (fh == 0.0)\n        {\n            return h;\n        }\n        if (fl < 0.0)\n        {\n            xl = l;\n            xh = h;\n        }\n        else\n        {\n            xh = l;\n            xl = h;\n        }\n\n        double rts = 0.5 * (xl + xh);\n        double dxold = fabs(xh - xl);\n        double dx = dxold;\n        double f = func(rts);\n        double df = dfunc(rts);\n        double temp;\n        for (int j = 0; j < maxIts; j++)\n        {\n            if ((((rts - xh) * df - f) * ((rts - xl) * df - f) > 0.0) ||\n                (fabs(2.0 * f) > fabs(dxold * df)))\n            {\n                dxold = dx;\n                dx = 0.5 * (xh - xl);\n                rts = xl + dx;\n                if (xl == rts)\n                {\n                    break;\n                }\n            }\n            else\n            {\n                dxold = dx;\n                dx = f / df;\n                temp = rts;\n                rts -= dx;\n                if (temp == rts)\n                {\n                    break;\n                }\n            }\n\n            if (fabs(dx) < tol)\n            {\n                break;\n            }\n\n            f = func(rts);\n            df = dfunc(rts);\n            if (f < 0.0)\n            {\n                xl = rts;\n            }\n            else\n            {\n                xh = rts;\n            }\n        }\n\n        return rts;\n    }\n\n    inline double shrinkInterval(double *coeffs, int numCoeffs, double lbound, double ubound, double tol)\n    // Calculate a single zero of poly coeffs(x) inside [lbound, ubound]\n    // Requirements: coeffs(lbound)*coeffs(ubound) < 0, lbound < ubound\n    {\n        double *dcoeffs = new double[numCoeffs - 1];\n        polyDeri(coeffs, dcoeffs, numCoeffs);\n        auto func = [&coeffs, &numCoeffs](double x)\n        { return polyEval(coeffs, numCoeffs, x); };\n        auto dfunc = [&dcoeffs, &numCoeffs](double x)\n        { return polyEval(dcoeffs, numCoeffs - 1, x); };\n        constexpr int maxDblIts = 128;\n        double rts = safeNewton(func, dfunc, lbound, ubound, tol, maxDblIts);\n        delete[] dcoeffs;\n        return rts;\n    }\n\n    inline void recurIsolate(double l, double r, double fl, double fr, int lnv, int rnv,\n                             double tol, double **sturmSeqs, int *szSeq, int len,\n                             std::set<double> &rts)\n    // Isolate all roots of sturmSeqs[0](x) inside interval (l, r) recursively and store them in rts\n    // Requirements: fl := sturmSeqs[0](l) != 0, fr := sturmSeqs[0](r) != 0, l < r,\n    //               lnv != rnv, lnv = numSignVar(l), rnv = numSignVar(r)\n    //               sturmSeqs[0](x) must have at least one root inside (l, r)\n    {\n        int nrts = lnv - rnv;\n        double fm;\n        double m;\n\n        if (nrts == 0)\n        {\n            return;\n        }\n        else if (nrts == 1)\n        {\n            if (fl * fr < 0)\n            {\n                rts.insert(shrinkInterval(sturmSeqs[0], szSeq[0], l, r, tol));\n                return;\n            }\n            else\n            {\n                // Bisect when non of above works\n                int maxDblIts = 128;\n\n                for (int i = 0; i < maxDblIts; i++)\n                {\n                    // Calculate the root with even multiplicity\n                    if (fl * fr < 0)\n                    {\n                        rts.insert(shrinkInterval(sturmSeqs[1], szSeq[1], l, r, tol));\n                        return;\n                    }\n\n                    m = (l + r) / 2.0;\n                    fm = polyEval(sturmSeqs[0], szSeq[0], m);\n\n                    if (fm == 0 || fabs(r - l) < tol)\n                    {\n                        rts.insert(m);\n                        return;\n                    }\n                    else\n                    {\n                        if (lnv == numSignVar(m, sturmSeqs, szSeq, len))\n                        {\n                            l = m;\n                            fl = fm;\n                        }\n                        else\n                        {\n                            r = m;\n                            fr = fm;\n                        }\n                    }\n                }\n\n                rts.insert(m);\n                return;\n            }\n        }\n        else if (nrts > 1)\n        {\n            // More than one root exists in the interval\n            int maxDblIts = 128;\n\n            int mnv;\n            int bias = 0;\n            bool biased = false;\n            for (int i = 0; i < maxDblIts; i++)\n            {\n                bias = biased ? bias : 0;\n                if (!biased)\n                {\n                    m = (l + r) / 2.0;\n                }\n                else\n                {\n                    m = (r - l) / pow(2.0, bias + 1.0) + l;\n                    biased = false;\n                }\n                mnv = numSignVar(m, sturmSeqs, szSeq, len);\n\n                if (fabs(r - l) < tol)\n                {\n                    rts.insert(m);\n                    return;\n                }\n                else\n                {\n                    fm = polyEval(sturmSeqs[0], szSeq[0], m);\n                    if (fm == 0)\n                    {\n                        bias++;\n                        biased = true;\n                    }\n                    else if (lnv != mnv && rnv != mnv)\n                    {\n                        recurIsolate(l, m, fl, fm, lnv, mnv, tol, sturmSeqs, szSeq, len, rts);\n                        recurIsolate(m, r, fm, fr, mnv, rnv, tol, sturmSeqs, szSeq, len, rts);\n                        return;\n                    }\n                    else if (lnv == mnv)\n                    {\n                        l = m;\n                        fl = fm;\n                    }\n                    else\n                    {\n                        r = m;\n                        fr = fm;\n                    }\n                }\n            }\n\n            rts.insert(m);\n            return;\n        }\n    };\n\n    inline std::set<double> isolateRealRoots(const Eigen::VectorXd &coeffs, double lbound, double ubound, double tol)\n    // Calculate roots of coeffs(x) inside (lbound, rbound) leveraging Sturm theory\n    // Requirement: leading coefficient must be nonzero\n    //              coeffs(lbound) != 0, coeffs(rbound) != 0, lbound < rbound\n    {\n        std::set<double> rts;\n\n        // Calculate monic coefficients\n        int order = (int)coeffs.size() - 1;\n        Eigen::VectorXd monicCoeffs(order + 1);\n        monicCoeffs << 1.0, coeffs.tail(order) / coeffs(0);\n\n        // Calculate Cauchy\u2019s bound for the roots of a polynomial\n        double rho_c = 1 + monicCoeffs.tail(order).cwiseAbs().maxCoeff();\n\n        // Calculate Kojima\u2019s bound for the roots of a polynomial\n        Eigen::VectorXd nonzeroCoeffs(order + 1);\n        nonzeroCoeffs.setZero();\n        int nonzeros = 0;\n        double tempEle;\n        for (int i = 0; i < order + 1; i++)\n        {\n            tempEle = monicCoeffs(i);\n            if (fabs(tempEle) >= DBL_EPSILON)\n            {\n                nonzeroCoeffs(nonzeros++) = tempEle;\n            }\n        }\n        nonzeroCoeffs = nonzeroCoeffs.head(nonzeros).eval();\n        Eigen::VectorXd kojimaVec = nonzeroCoeffs.tail(nonzeros - 1).cwiseQuotient(nonzeroCoeffs.head(nonzeros - 1)).cwiseAbs();\n        kojimaVec.tail(1) /= 2.0;\n        double rho_k = 2.0 * kojimaVec.maxCoeff();\n\n        // Choose a sharper one then loosen it by 1.0 to get an open interval\n        double rho = std::min(rho_c, rho_k) + 1.0;\n\n        // Tighten the bound to search in\n        lbound = std::max(lbound, -rho);\n        ubound = std::min(ubound, rho);\n\n        // Build Sturm sequence\n        int len = monicCoeffs.size();\n        double sturmSeqs[(RootFinderParam::highestOrder + 1) * (RootFinderParam::highestOrder + 1)];\n        int szSeq[RootFinderParam::highestOrder + 1] = {0}; // Explicit ini as zero (gcc may neglect this in -O3)\n        double *offsetSeq[RootFinderParam::highestOrder + 1];\n        int num = 0;\n\n        for (int i = 0; i < len; i++)\n        {\n            sturmSeqs[i] = monicCoeffs(i);\n            sturmSeqs[i + 1 + len] = (order - i) * sturmSeqs[i] / order;\n        }\n        szSeq[0] = len;\n        szSeq[1] = len - 1;\n        offsetSeq[0] = sturmSeqs + len - szSeq[0];\n        offsetSeq[1] = sturmSeqs + 2 * len - szSeq[1];\n\n        num += 2;\n\n        bool remainderConstant = false;\n        int idx = 0;\n        while (!remainderConstant)\n        {\n            szSeq[idx + 2] = polyMod(offsetSeq[idx],\n                                     offsetSeq[idx + 1],\n                                     &(sturmSeqs[(idx + 3) * len - szSeq[idx]]),\n                                     szSeq[idx], szSeq[idx + 1]);\n            offsetSeq[idx + 2] = sturmSeqs + (idx + 3) * len - szSeq[idx + 2];\n\n            remainderConstant = szSeq[idx + 2] == 1;\n            for (int i = 1; i < szSeq[idx + 2]; i++)\n            {\n                offsetSeq[idx + 2][i] /= -fabs(offsetSeq[idx + 2][0]);\n            }\n            offsetSeq[idx + 2][0] = offsetSeq[idx + 2][0] > 0.0 ? -1.0 : 1.0;\n            num++;\n            idx++;\n        }\n\n        // Isolate all distinct roots inside the open interval recursively\n        recurIsolate(lbound, ubound,\n                     polyEval(offsetSeq[0], szSeq[0], lbound),\n                     polyEval(offsetSeq[0], szSeq[0], ubound),\n                     numSignVar(lbound, offsetSeq, szSeq, len),\n                     numSignVar(ubound, offsetSeq, szSeq, len),\n                     tol, offsetSeq, szSeq, len, rts);\n\n        return rts;\n    }\n\n} // namespace RootFinderPriv\n\nnamespace RootFinder\n{\n\n    inline Eigen::VectorXd polyConv(const Eigen::VectorXd &lCoef, const Eigen::VectorXd &rCoef)\n    // Calculate the convolution of lCoef(x) and rCoef(x)\n    {\n        Eigen::VectorXd result(lCoef.size() + rCoef.size() - 1);\n        result.setZero();\n        for (int i = 0; i < result.size(); i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                result(i) += (j < lCoef.size() && (i - j) < rCoef.size()) ? (lCoef(j) * rCoef(i - j)) : 0;\n            }\n        }\n\n        return result;\n    }\n\n    // // This function needs FFTW 3 and only performs better when the scale is large\n    // inline Eigen::VectorXd polyConvFFT(const Eigen::VectorXd &lCoef, const Eigen::VectorXd &rCoef)\n    // // Calculate the convolution of lCoef(x) and rCoef(x) using FFT\n    // // This function is fast when orders of both poly are larger than 100\n    // {\n    //     int paddedLen = lCoef.size() + rCoef.size() - 1;\n    //     int complexLen = paddedLen / 2 + 1;\n    //     Eigen::VectorXd result(paddedLen);\n    //     double *rBuffer = fftw_alloc_real(paddedLen);\n    //     // Construct FFT plan and buffers\n    //     fftw_complex *cForwardBuffer = fftw_alloc_complex(complexLen);\n    //     fftw_complex *cBackwardBuffer = fftw_alloc_complex(complexLen);\n    //     fftw_plan forwardPlan = fftw_plan_dft_r2c_1d(paddedLen, rBuffer, cForwardBuffer,\n    //                                                  FFTW_ESTIMATE | FFTW_DESTROY_INPUT);\n    //     fftw_plan backwardPlan = fftw_plan_dft_c2r_1d(paddedLen, cBackwardBuffer, rBuffer,\n    //                                                   FFTW_ESTIMATE | FFTW_DESTROY_INPUT);\n    //     // Pad lCoef by zeros\n    //     int len = lCoef.size();\n    //     for (int i = 0; i < len; i++)\n    //     {\n    //         rBuffer[i] = lCoef(i);\n    //     }\n    //     for (int i = len; i < paddedLen; i++)\n    //     {\n    //         rBuffer[i] = 0.0;\n    //     }\n    //     // Compute fft(pad(lCoef(x)) and back it up\n    //     fftw_execute(forwardPlan);\n    //     memcpy(cBackwardBuffer, cForwardBuffer, sizeof(fftw_complex) * complexLen);\n    //     // Pad rCoef by zeros\n    //     len = rCoef.size();\n    //     for (int i = 0; i < len; i++)\n    //     {\n    //         rBuffer[i] = rCoef(i);\n    //     }\n    //     for (int i = len; i < paddedLen; i++)\n    //     {\n    //         rBuffer[i] = 0.0;\n    //     }\n    //     // Compute fft(pad(rCoef(x))\n    //     fftw_execute(forwardPlan);\n    //     // Compute fft(pad(lCoef(x)).fft(pad(rCoef(x))\n    //     double real, imag;\n    //     for (int i = 0; i < complexLen; i++)\n    //     {\n    //         real = cBackwardBuffer[i][0];\n    //         imag = cBackwardBuffer[i][1];\n    //         cBackwardBuffer[i][0] = real * cForwardBuffer[i][0] -\n    //                                 imag * cForwardBuffer[i][1];\n    //         cBackwardBuffer[i][1] = imag * cForwardBuffer[i][0] +\n    //                                 real * cForwardBuffer[i][1];\n    //     }\n    //     // Compute ifft(fft(pad(lCoef(x)).fft(pad(rCoef(x)))\n    //     fftw_execute(backwardPlan);\n    //     // Recover the original intensity\n    //     double intensity = 1.0 / paddedLen;\n    //     for (int i = 0; i < paddedLen; i++)\n    //     {\n    //         result(i) = rBuffer[i] * intensity;\n    //     }\n    //     // Destruct FFT plan and buffers\n    //     fftw_destroy_plan(forwardPlan);\n    //     fftw_destroy_plan(backwardPlan);\n    //     fftw_free(rBuffer);\n    //     fftw_free(cForwardBuffer);\n    //     fftw_free(cBackwardBuffer);\n    //     return result;\n    // }\n\n    inline Eigen::VectorXd polySqr(const Eigen::VectorXd &coef)\n    // Calculate self-convolution of coef(x)\n    {\n        int coefSize = coef.size();\n        int resultSize = coefSize * 2 - 1;\n        int lbound, rbound;\n        Eigen::VectorXd result(resultSize);\n        double temp;\n        for (int i = 0; i < resultSize; i++)\n        {\n            temp = 0;\n            lbound = i - coefSize + 1;\n            lbound = lbound > 0 ? lbound : 0;\n            rbound = coefSize < (i + 1) ? coefSize : (i + 1);\n            rbound += lbound;\n            if (rbound & 1) //faster than rbound % 2 == 1\n            {\n                rbound >>= 1; //faster than rbound /= 2\n                temp += coef(rbound) * coef(rbound);\n            }\n            else\n            {\n                rbound >>= 1; //faster than rbound /= 2\n            }\n\n            for (int j = lbound; j < rbound; j++)\n            {\n                temp += 2.0 * coef(j) * coef(i - j);\n            }\n            result(i) = temp;\n        }\n\n        return result;\n    }\n\n    inline double polyVal(const Eigen::VectorXd &coeffs, double x,\n                          bool numericalStability = true)\n    // Evaluate the polynomial at x, i.e., coeffs(x)\n    // Horner scheme is faster yet less stable\n    // Stable one should be used when coeffs(x) is close to 0.0\n    {\n        double retVal = 0.0;\n        int order = (int)coeffs.size() - 1;\n\n        if (order >= 0)\n        {\n            if (fabs(x) < DBL_EPSILON)\n            {\n                retVal = coeffs(order);\n            }\n            else if (x == 1.0)\n            {\n                retVal = coeffs.sum();\n            }\n            else\n            {\n                if (numericalStability)\n                {\n                    double xn = 1.0;\n\n                    for (int i = order; i >= 0; i--)\n                    {\n                        retVal += coeffs(i) * xn;\n                        xn *= x;\n                    }\n                }\n                else\n                {\n                    int len = coeffs.size();\n\n                    for (int i = 0; i < len; i++)\n                    {\n                        retVal = retVal * x + coeffs(i);\n                    }\n                }\n            }\n        }\n\n        return retVal;\n    }\n\n    inline int countRoots(const Eigen::VectorXd &coeffs, double l, double r)\n    // Count the number of distinct roots of coeffs(x) inside (l, r), leveraging Sturm theory\n    // Boundary values, i.e., coeffs(l) and coeffs(r), must be nonzero\n    {\n        int nRoots = 0;\n\n        int originalSize = coeffs.size();\n        int valid = originalSize;\n        for (int i = 0; i < originalSize; i++)\n        {\n            if (fabs(coeffs(i)) < DBL_EPSILON)\n            {\n                valid--;\n            }\n            else\n            {\n                break;\n            }\n        }\n\n        if (valid > 0 && fabs(coeffs(originalSize - 1)) > DBL_EPSILON)\n        {\n            Eigen::VectorXd monicCoeffs(valid);\n            monicCoeffs << 1.0, coeffs.segment(originalSize - valid + 1, valid - 1) / coeffs(originalSize - valid);\n\n            // Build the Sturm sequence\n            int len = monicCoeffs.size();\n            int order = len - 1;\n            double sturmSeqs[(RootFinderParam::highestOrder + 1) * (RootFinderParam::highestOrder + 1)];\n            int szSeq[RootFinderParam::highestOrder + 1] = {0}; // Explicit ini as zero (gcc may neglect this in -O3)\n            int num = 0;\n\n            for (int i = 0; i < len; i++)\n            {\n                sturmSeqs[i] = monicCoeffs(i);\n                sturmSeqs[i + 1 + len] = (order - i) * sturmSeqs[i] / order;\n            }\n            szSeq[0] = len;\n            szSeq[1] = len - 1;\n            num += 2;\n\n            bool remainderConstant = false;\n            int idx = 0;\n            while (!remainderConstant)\n            {\n                szSeq[idx + 2] = RootFinderPriv::polyMod(&(sturmSeqs[(idx + 1) * len - szSeq[idx]]),\n                                                         &(sturmSeqs[(idx + 2) * len - szSeq[idx + 1]]),\n                                                         &(sturmSeqs[(idx + 3) * len - szSeq[idx]]),\n                                                         szSeq[idx], szSeq[idx + 1]);\n                remainderConstant = szSeq[idx + 2] == 1;\n                for (int i = 1; i < szSeq[idx + 2]; i++)\n                {\n                    sturmSeqs[(idx + 3) * len - szSeq[idx + 2] + i] /= -fabs(sturmSeqs[(idx + 3) * len - szSeq[idx + 2]]);\n                }\n                sturmSeqs[(idx + 3) * len - szSeq[idx + 2]] /= -fabs(sturmSeqs[(idx + 3) * len - szSeq[idx + 2]]);\n                num++;\n                idx++;\n            }\n\n            // Count numbers of sign variations at two boundaries\n            double yl, lastyl, yr, lastyr;\n            lastyl = RootFinderPriv::polyEval(&(sturmSeqs[len - szSeq[0]]), szSeq[0], l);\n            lastyr = RootFinderPriv::polyEval(&(sturmSeqs[len - szSeq[0]]), szSeq[0], r);\n            for (int i = 1; i < num; i++)\n            {\n                yl = RootFinderPriv::polyEval(&(sturmSeqs[(i + 1) * len - szSeq[i]]), szSeq[i], l);\n                yr = RootFinderPriv::polyEval(&(sturmSeqs[(i + 1) * len - szSeq[i]]), szSeq[i], r);\n                if (lastyl == 0.0 || lastyl * yl < 0.0)\n                {\n                    ++nRoots;\n                }\n                if (lastyr == 0.0 || lastyr * yr < 0.0)\n                {\n                    --nRoots;\n                }\n                lastyl = yl;\n                lastyr = yr;\n            }\n        }\n\n        return nRoots;\n    }\n\n    inline std::set<double> solvePolynomial(const Eigen::VectorXd &coeffs, double lbound, double ubound, double tol, bool isolation = true)\n    // Calculate roots of coeffs(x) inside (lbound, rbound)\n    //\n    // Closed-form solutions are employed for reduced_order < 5\n    // isolation = true:\n    //                    Sturm' theory and some geometrical property are employed to bracket each root\n    //                    Safe-Newton is employed to shrink the interval efficiently\n    // isolation = false:\n    //                    Eigen values of polynomial companion matrix are calculated\n    //\n    // Requirement: leading coefficient must be nonzero\n    //              coeffs(lbound) != 0, coeffs(rbound) != 0, lbound < rbound\n    {\n        std::set<double> rts;\n\n        int valid = coeffs.size();\n        for (int i = 0; i < coeffs.size(); i++)\n        {\n            if (fabs(coeffs(i)) < DBL_EPSILON)\n            {\n                valid--;\n            }\n            else\n            {\n                break;\n            }\n        }\n\n        int offset = 0;\n        int nonzeros = valid;\n        if (valid > 0)\n        {\n            for (int i = 0; i < valid; i++)\n            {\n                if (fabs(coeffs(coeffs.size() - i - 1)) < DBL_EPSILON)\n                {\n                    nonzeros--;\n                    offset++;\n                }\n                else\n                {\n                    break;\n                }\n            }\n        }\n\n        if (nonzeros == 0)\n        {\n            rts.insert(INFINITY);\n            rts.insert(-INFINITY);\n        }\n        else if (nonzeros == 1 && offset == 0)\n        {\n            rts.clear();\n        }\n        else\n        {\n            Eigen::VectorXd ncoeffs(std::max(5, nonzeros));\n            ncoeffs.setZero();\n            ncoeffs.tail(nonzeros) << coeffs.segment(coeffs.size() - valid, nonzeros);\n\n            if (nonzeros <= 5)\n            {\n                rts = RootFinderPriv::solveQuart(ncoeffs(0), ncoeffs(1), ncoeffs(2), ncoeffs(3), ncoeffs(4));\n            }\n            else\n            {\n                if (isolation)\n                {\n                    rts = RootFinderPriv::isolateRealRoots(ncoeffs, lbound, ubound, tol);\n                }\n                else\n                {\n                    rts = RootFinderPriv::eigenSolveRealRoots(ncoeffs, lbound, ubound, tol);\n                }\n            }\n\n            if (offset > 0)\n            {\n                rts.insert(0.0);\n            }\n        }\n\n        for (auto it = rts.begin(); it != rts.end();)\n        {\n            if (*it > lbound && *it < ubound)\n            {\n                it++;\n            }\n            else\n            {\n                it = rts.erase(it);\n            }\n        }\n\n        return rts;\n    }\n\n} // namespace RootFinder\n\n#endif", "meta": {"hexsha": "28f48ad15be150e4e9a2cde386ee14b0e91bde1d", "size": 36134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "planning/poly_traj_utils/include/poly_traj_utils/root_finder.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": "planning/poly_traj_utils/include/poly_traj_utils/root_finder.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": "planning/poly_traj_utils/include/poly_traj_utils/root_finder.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": 32.3781362007, "max_line_length": 139, "alphanum_fraction": 0.426744894, "num_tokens": 9742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.500364526143858}}
{"text": "/**\n * @file : cartesian_product.h\n * @author : Vikas Dhiman\n * @date: Wed July 11 2013\n */\n\n#pragma once\n\n#include <boost/function.hpp>\n#include <boost/iterator/filter_iterator.hpp>\n#include <boost/type_traits.hpp>\n#include <boost/utility/result_of.hpp>\n#include <vector>\n\n#include <boost/lambda/lambda.hpp>\nnamespace bl = boost::lambda; \n\n\nnamespace occgrid {\n\n/**\n * @brief: Produces a cartesian product of assignments to a Iterator of\n * variable nodes\n *\n * @type : InputIterator : A type of Iterator of VariableNodes\n * @type : PossibleValueIter : A type of Iterator of VariableNodes\n */\ntemplate<typename InputIterator, typename SampleSpaceMap>\nclass CartesianProduct {\nprivate:\n  typedef typename std::iterator_traits<InputIterator>::value_type Vnode;\n  typedef typename SampleSpaceMap::value_type::first_type PossibleValueIter;\n  typedef typename std::iterator_traits<PossibleValueIter>::value_type Value;\n\n  // Nodes with possible assignments\n\tconst InputIterator nodes_begin_;\n  const InputIterator nodes_end_;\n\n  const SampleSpaceMap& cdmap_;\n\n  // A vector of value iterators pointing to the current value of each node\n  std::vector< PossibleValueIter > current_val_;\n  \n  // last_iteration_\n  bool last_iteration_;\n\npublic:\n  CartesianProduct(\n      InputIterator nodes_begin,\n      InputIterator nodes_end,\n      SampleSpaceMap cdmap)\n    : nodes_begin_(nodes_begin),\n    nodes_end_(nodes_end),\n    cdmap_(cdmap),\n    current_val_(),\n    last_iteration_(false)\n    {\n      // Initialize all values\n      for (InputIterator it = nodes_begin_; it != nodes_end_; ++it) {\n        current_val_.push_back(get(cdmap_, *it).first);\n      }\n    }\n\n  /// Return the next assignment\n  // TODO: We don't need to accept a property map type, we can just do by\n  // transformed iterator over a map object\n  template<typename PropertyMap>\n  bool next(PropertyMap &assign) {\n    bool carry_over = true;\n    typedef typename std::vector< PossibleValueIter >::iterator val_it_it;\n    val_it_it node_val_it_it(current_val_.begin());\n    InputIterator node_it(nodes_begin_);\n    for(;(node_val_it_it != current_val_.end()) \n        && (node_it != nodes_end_);\n        ++ node_val_it_it, ++ node_it) \n    {\n      PossibleValueIter &node_val_it = *node_val_it_it;\n      const Vnode &node = *node_it;\n      PossibleValueIter poss_val_end(get(cdmap_, node).second);\n      Value val = *node_val_it;\n      //std::cout << node << \" -> \" << val << std::endl;\n      assign[node] = val;\n\n      if (carry_over)\n        node_val_it ++;\n\n      if (node_val_it == poss_val_end) {\n        // loop around and carry over the carry_over\n        node_val_it = get(cdmap_, node).first;\n        // values exhausted carry over to next loop\n        carry_over = true;\n      } else {\n        // nothing to carry over to next loop\n        carry_over = false;\n      }\n    }\n    // If we complete the loop that means we have exhausted all possible cases\n    bool is_last_iteration = last_iteration_;\n    last_iteration_ = (carry_over);\n    return (! is_last_iteration);\n  }\n};\n\ntemplate<typename Real,\n  //typename UnaryFunction,\n  typename InputIterator,\n  typename SampleSpaceMap,\n  typename Assignment\n  >\n// typename UnaryFunction::result_type\nReal\nsummaryOf(\n\t\tconst boost::function<Real (const Assignment&)> &func,\n    //UnaryFunction &func,\n\t\tInputIterator dependent_nodes_begin,\n\t\tInputIterator dependent_nodes_end,\n    const SampleSpaceMap& cdmap,\n\t\tconst typename std::iterator_traits<InputIterator>::value_type &x,\n    //const typename Assignment::value_type &xv\n    const typename SampleSpaceMap::value_type::first_type::value_type &xv\n    )\n{\n  BOOST_AUTO_TPL(fi_begin,\n      boost::make_filter_iterator(\n        (x != bl::_1), dependent_nodes_begin, dependent_nodes_end));\n  BOOST_AUTO_TPL(fi_end,  \n      boost::make_filter_iterator(\n        (x != bl::_1), dependent_nodes_end, dependent_nodes_end));\n  typedef BOOST_TYPEOF_TPL(fi_begin) filter_iterator;\n\n  CartesianProduct<filter_iterator, SampleSpaceMap> poss_assign(fi_begin, fi_end, cdmap);\n  Real summary(0);\n  Assignment assign;\n  assign[x] = xv;\n  while (poss_assign.next(assign)) {\n    Real fa = func(assign);\n    summary += fa;\n  }\n  return summary;\n}\n\ntemplate<typename Real,\n  //typename UnaryFunction,\n  typename InputIterator,\n  typename SampleSpaceMap,\n  typename Assignment\n  >\n// typename UnaryFunction::result_type\nReal\nmaxOf(\n\t\tconst boost::function<Real (const Assignment&)> &func,\n    //UnaryFunction &func,\n\t\tInputIterator dependent_nodes_begin,\n\t\tInputIterator dependent_nodes_end,\n    const SampleSpaceMap& cdmap,\n\t\tconst typename std::iterator_traits<InputIterator>::value_type &x,\n    //const typename Assignment::value_type &xv\n    const typename SampleSpaceMap::value_type::first_type::value_type &xv\n    )\n{\n  // typedef typename boost::remove_reference<\n  //   typename UnaryFunction::argument_type>::type const_assignment_type;\n  // typedef typename boost::remove_const<const_assignment_type>::type Assignment;\n  // typedef typename UnaryFunction::result_type Real;\n  typedef typename std::iterator_traits<InputIterator>::value_type Vnode;\n\n  // filter iterator to get all neighbors except var\n  BOOST_AUTO_TPL(fi_begin,\n      boost::make_filter_iterator(\n        (x != bl::_1), dependent_nodes_begin, dependent_nodes_end));\n  BOOST_AUTO_TPL(fi_end,  \n      boost::make_filter_iterator(\n        (x != bl::_1), dependent_nodes_end, dependent_nodes_end));\n  typedef BOOST_TYPEOF_TPL(fi_begin) filter_iterator;\n\n  CartesianProduct<filter_iterator, SampleSpaceMap> poss_assign(fi_begin, fi_end, cdmap);\n  Real mx(0);\n  Assignment assign;\n  assign[x] = xv;\n  while (poss_assign.next(assign)) {\n    Real fa = func(assign);\n    using std::max;\n    mx = max(mx, fa);\n  }\n  return mx;\n}\n} // namespace occgrid\n", "meta": {"hexsha": "0b35f10f89b63c55a0000ba310535ca70bf04e89", "size": 5764, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/OccupancyGrid/cartesian_product.hpp", "max_stars_repo_name": "wecacuee/modern-occupancy-grid", "max_stars_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-03-14T16:24:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T05:39:06.000Z", "max_issues_repo_path": "include/OccupancyGrid/cartesian_product.hpp", "max_issues_repo_name": "wecacuee/modern-occupancy-grid", "max_issues_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/OccupancyGrid/cartesian_product.hpp", "max_forks_repo_name": "wecacuee/modern-occupancy-grid", "max_forks_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-08-10T02:02:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-20T12:20:29.000Z", "avg_line_length": 30.6595744681, "max_line_length": 89, "alphanum_fraction": 0.7139139486, "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5003645214186221}}
{"text": "\ufeff#ifndef EIGEN_HELPERS_HPP\n#define EIGEN_HELPERS_HPP\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n#include <Eigen/Jacobi>\n#include <Eigen/SVD>\n#include <Eigen/StdVector>\n#include <functional>\n#include <iostream>\n#include <map>\n#include <type_traits>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <vector>\n\n#include \"arc_exceptions.hpp\"\n#include \"eigen_typedefs.hpp\"\n#include \"math_helpers.hpp\"\n#include \"vector_math.hpp\"\n\nnamespace EigenHelpers {\n////////////////////////////////////////////////////////////////////////////\n// Misc\n////////////////////////////////////////////////////////////////////////////\n\ninline bool Equal3d(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2) {\n  if ((v1.x() == v2.x()) && (v1.y() == v2.y()) && (v1.z() == v2.z())) {\n    return true;\n  } else {\n    return false;\n  }\n}\n\ninline bool Equal4d(const Eigen::Vector4d& v1, const Eigen::Vector4d& v2) {\n  if ((v1(0) == v2(0)) && (v1(1) == v2(1)) && (v1(2) == v2(2)) && (v1(3) == v2(3))) {\n    return true;\n  } else {\n    return false;\n  }\n}\n\ninline bool CloseEnough(const Eigen::Vector2d& v1, const Eigen::Vector2d& v2, const double threshold) {\n  return CloseEnough(v1.x(), v2.x(), threshold) && CloseEnough(v1.y(), v2.y(), threshold);\n}\n\ninline bool CloseEnough(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, const double threshold) {\n  double real_threshold = std::abs(threshold);\n  if (std::abs(v1.x() - v2.x()) > real_threshold) {\n    return false;\n  }\n  if (std::abs(v1.y() - v2.y()) > real_threshold) {\n    return false;\n  }\n  if (std::abs(v1.z() - v2.z()) > real_threshold) {\n    return false;\n  }\n  return true;\n}\n\ntemplate <typename EigenType, typename Allocator = Eigen::aligned_allocator<EigenType>>\ninline bool CloseEnough(const std::vector<EigenType, Allocator>& a, const std::vector<EigenType, Allocator>& b,\n                        const double threshold) {\n  if (a.size() != b.size()) {\n    return false;\n  }\n  for (size_t idx = 0; idx < a.size(); idx++) {\n    if (!CloseEnough(a[idx], b[idx], threshold)) {\n      return false;\n    }\n  }\n  return true;\n}\n\ntemplate <typename EigenType, typename Allocator = Eigen::aligned_allocator<EigenType>>\ninline bool IsApprox(\n    const std::vector<EigenType, Allocator>& a, const std::vector<EigenType, Allocator>& b,\n    const typename EigenType::Scalar& precision = Eigen::NumTraits<typename EigenType::Scalar>::dummy_precision()) {\n  if (a.size() != b.size()) {\n    return false;\n  }\n  for (size_t idx = 0; idx < a.size(); idx++) {\n    if (!a[idx].isApprox(b[idx], precision)) {\n      return false;\n    }\n  }\n  return true;\n}\n\ntemplate <typename Derived>\ninline Eigen::MatrixXd ClampNorm(const Eigen::MatrixBase<Derived>& item_to_clamp, const double max_norm) {\n  assert(max_norm > 0 && \"You must pass a maximum norm that is positive\");\n  const double current_norm = item_to_clamp.norm();\n  if (current_norm > max_norm) {\n    return item_to_clamp * (max_norm / current_norm);\n  }\n  return item_to_clamp;\n}\n\n////////////////////////////////////////////////////////////////////////////\n// Vectors of Eigen data transformations\n////////////////////////////////////////////////////////////////////////////\n\ntemplate <typename _Scalar, int _Dim, int _Mode, int _Options, typename EigenType, typename Allocator>\ninline std::vector<EigenType, Allocator> TransformData(\n    const Eigen::Transform<_Scalar, _Dim, _Mode, _Options>& transform, const std::vector<EigenType, Allocator>& data) {\n  std::vector<EigenType, Allocator> retval;\n  retval.reserve(data.size());\n  for (const auto& item : data) {\n    retval.push_back(transform * item);\n  }\n  return retval;\n}\n\n////////////////////////////////////////////////////////////////////////////\n// Kinematics functions\n////////////////////////////////////////////////////////////////////////////\n\ninline Eigen::Vector3d RotateVector(const Eigen::Quaterniond& quat, const Eigen::Vector3d& vec) {\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\ninline Eigen::Vector3d RotateVectorReverse(const Eigen::Quaterniond& quat, const Eigen::Vector3d& vec) {\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\ninline Eigen::VectorXd SafeNormal(const Eigen::VectorXd& vec) {\n  const double norm = vec.norm();\n  if (norm > std::numeric_limits<double>::epsilon()) {\n    return vec / norm;\n  } else {\n    return vec;\n  }\n}\n\ninline double SquaredNorm(const std::vector<double>& vec) {\n  double squared_norm = 0.0;\n  for (size_t idx = 0; idx < vec.size(); idx++) {\n    const double element = vec[idx];\n    squared_norm += (element * element);\n  }\n  return squared_norm;\n}\n\ninline double Norm(const std::vector<double>& vec) { return std::sqrt(SquaredNorm(vec)); }\n\ninline Eigen::Matrix3d Skew(const Eigen::Vector3d& vector) {\n  Eigen::Matrix3d skewed;\n  skewed << 0.0, -vector.z(), vector.y(), vector.z(), 0.0, -vector.x(), -vector.y(), vector.x(), 0.0;\n  return skewed;\n}\n\ninline Eigen::Vector3d Unskew(const Eigen::Matrix3d& matrix) {\n  const Eigen::Matrix3d matrix_symetric = (matrix - matrix.transpose()) / 2.0;\n  const Eigen::Vector3d unskewed(matrix_symetric(2, 1), matrix_symetric(0, 2), matrix_symetric(1, 0));\n  return unskewed;\n}\n\ninline Eigen::Matrix4d TwistHat(const Eigen::Matrix<double, 6, 1>& twist) {\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\ninline Eigen::Matrix<double, 6, 1> TwistUnhat(const Eigen::Matrix4d& hatted_twist) {\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\ntemplate <int _Mode>\ninline Eigen::Matrix<double, 6, 6> AdjointFromTransform(const Eigen::Transform<double, 3, _Mode>& transform) {\n  EIGEN_STATIC_ASSERT(_Mode == Eigen::Affine || _Mode == Eigen::Isometry,\n                      \"THIS FUNCTION IS ONLY INTENDED FOR HOMOGENEOUS TRANSFORMS!!!\");\n  const Eigen::Matrix3d rotation = transform.rotation();\n  const Eigen::Vector3d translation = transform.translation();\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\ntemplate <int _Mode>\ninline Eigen::Matrix<double, 6, 1> TransformTwist(const Eigen::Transform<double, 3, _Mode>& transform,\n                                                  const Eigen::Matrix<double, 6, 1>& initial_twist) {\n  EIGEN_STATIC_ASSERT(_Mode == Eigen::Affine || _Mode == Eigen::Isometry,\n                      \"THIS FUNCTION IS ONLY INTENDED FOR HOMOGENEOUS TRANSFORMS!!!\");\n  return (Eigen::Matrix<double, 6, 1>)(EigenHelpers::AdjointFromTransform(transform) * initial_twist);\n}\n\ntemplate <int _Mode>\ninline Eigen::Matrix<double, 6, 1> TwistBetweenTransforms(const Eigen::Transform<double, 3, _Mode>& start,\n                                                          const Eigen::Transform<double, 3, _Mode>& end) {\n  EIGEN_STATIC_ASSERT(_Mode == Eigen::Affine || _Mode == Eigen::Isometry,\n                      \"THIS FUNCTION IS ONLY INTENDED FOR HOMOGENEOUS TRANSFORMS!!!\");\n  const Eigen::Transform<double, 3, _Mode> t_diff = start.inverse(_Mode) * end;\n  return TwistUnhat(t_diff.matrix().log());\n}\n\ninline Eigen::Matrix3d ExpMatrixExact(const Eigen::Matrix3d& hatted_rot_velocity, const double delta_t) {\n  assert(std::abs(Unskew(hatted_rot_velocity).norm() - 1.0) < 1e-10);\n  const Eigen::Matrix3d exp_matrix = Eigen::Matrix3d::Identity() + (hatted_rot_velocity * sin(delta_t)) +\n                                     (hatted_rot_velocity * hatted_rot_velocity * (1.0 - cos(delta_t)));\n  return exp_matrix;\n}\n\ninline Eigen::Isometry3d ExpTwist(const Eigen::Matrix<double, 6, 1>& twist, const double delta_t) {\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    const double scaled_delta_t = delta_t * rot_velocity_norm;\n    const Eigen::Vector3d scaled_trans_velocity = trans_velocity / rot_velocity_norm;\n    const Eigen::Vector3d scaled_rot_velocity = rot_velocity / rot_velocity_norm;\n    const Eigen::Matrix3d rotation_displacement = ExpMatrixExact(Skew(scaled_rot_velocity), scaled_delta_t);\n    const Eigen::Vector3d translation_displacement =\n        ((Eigen::Matrix3d::Identity() - rotation_displacement) * scaled_rot_velocity.cross(scaled_trans_velocity)) +\n        (scaled_rot_velocity * scaled_rot_velocity.transpose() * 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  } else {\n    if ((trans_velocity_norm >= 1e-100) || (rot_velocity_norm == 0.0)) {\n      raw_transform.block<3, 1>(0, 3) = trans_velocity * delta_t;\n    } else {\n      std::cerr << \"*** WARNING - YOU MAY ENCOUNTER NUMERICAL INSTABILITY IN EXPTWIST(...) WITH TRANS & ROT VELOCITY \"\n                   \"NORM < 1e-100 ***\"\n                << std::endl;\n      const double scaled_delta_t = delta_t * rot_velocity_norm;\n      const Eigen::Vector3d scaled_trans_velocity = trans_velocity / rot_velocity_norm;\n      const Eigen::Vector3d scaled_rot_velocity = rot_velocity / rot_velocity_norm;\n      const Eigen::Matrix3d rotation_displacement = ExpMatrixExact(Skew(scaled_rot_velocity), scaled_delta_t);\n      const Eigen::Vector3d translation_displacement =\n          ((Eigen::Matrix3d::Identity() - rotation_displacement) * scaled_rot_velocity.cross(scaled_trans_velocity)) +\n          (scaled_rot_velocity * scaled_rot_velocity.transpose() * 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\n////////////////////////////////////////////////////////////////////////////\n// Interpolation functions\n////////////////////////////////////////////////////////////////////////////\n\ntemplate <typename T, int ROWS>\ninline Eigen::Matrix<T, ROWS, 1> Interpolate(const Eigen::Matrix<T, ROWS, 1>& v1, const Eigen::Matrix<T, ROWS, 1>& v2,\n                                             const double ratio) {\n  // Safety check sizes\n  if (v1.size() != v2.size()) {\n    throw_arc_exception(std::invalid_argument, \"Vectors v1 and v2 must be the same size\");\n  }\n  // Safety check ratio\n  const double real_ratio = SafetyCheckUnitInterval(ratio);\n  // Interpolate\n  // This is the numerically stable version, rather than  (p1 + (p2 - p1) * real_ratio)\n  return ((v1 * (1.0 - real_ratio)) + (v2 * real_ratio));\n}\n\ninline Eigen::Quaterniond Interpolate(const Eigen::Quaterniond& q1, const Eigen::Quaterniond& q2, const double ratio) {\n  // Safety check ratio\n  const double real_ratio = SafetyCheckUnitInterval(ratio);\n  // Interpolate\n  return q1.slerp(real_ratio, q2);\n}\n\ninline Eigen::Isometry3d Interpolate(const Eigen::Isometry3d& t1, const Eigen::Isometry3d& t2, const double ratio) {\n  // Safety check ratio\n  const double real_ratio = SafetyCheckUnitInterval(ratio);\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 = Interpolate(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\n////////////////////////////////////////////////////////////////////////////\n// Distance functions\n////////////////////////////////////////////////////////////////////////////\n\ninline double SquaredDistance(const Eigen::Vector2d& v1, const Eigen::Vector2d& v2) {\n  const double xd = v2.x() - v1.x();\n  const double yd = v2.y() - v1.y();\n  return ((xd * xd) + (yd * yd));\n}\n\ninline double Distance(const Eigen::Vector2d& v1, const Eigen::Vector2d& v2) { return sqrt(SquaredDistance(v1, v2)); }\n\ninline double SquaredDistance(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2) {\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\ninline double Distance(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2) { return sqrt(SquaredDistance(v1, v2)); }\n\ninline double SquaredDistance(const Eigen::VectorXd& v1, const Eigen::VectorXd& v2) {\n  assert(v1.size() == v2.size());\n  return (v2 - v1).squaredNorm();\n}\n\ninline double Distance(const Eigen::VectorXd& v1, const Eigen::VectorXd& v2) { return (v2 - v1).norm(); }\n\n// From here: https://chrischoy.github.io/research/measuring-rotation/\n// This assumes that the incomming quaternions are normalized\ninline double Distance(const Eigen::Quaterniond& q1, const Eigen::Quaterniond& q2) {\n  const double dq = std::abs((q1.w() * q2.w()) + (q1.x() * q2.x()) + (q1.y() * q2.y()) + (q1.z() * q2.z()));\n  if (dq < (1.0 - std::numeric_limits<double>::epsilon())) {\n    return acos(2.0 * (dq * dq) - 1.0);\n  } else {\n    return 0.0;\n  }\n}\n\n// From here: http://www.boris-belousov.net/2016/12/01/quat-dist/#rotation-matrices\n// Returns the minimum angular rotation needed to align r1 and r2\n// Assumes that r1 and r2 are proper rotation matrices\ninline double Distance(const Eigen::Matrix3d& r1, const Eigen::Matrix3d& r2) {\n  const auto delta = r1 * r2.transpose();\n  const auto tr = delta.trace();\n  return acos((tr - 1.0) / 2.0);\n}\n\ninline double Distance(const Eigen::Isometry3d& t1, const Eigen::Isometry3d& t2, const double alpha = 0.5) {\n  assert(alpha >= 0.0);\n  assert(alpha <= 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 - alpha);\n  const double qdist = Distance(q1, q2) * (alpha);\n  return vdist + qdist;\n}\n\ninline double CalculateTotalDistance(const EigenHelpers::VectorVector3d& points) {\n  double distance = 0;\n\n  for (size_t idx = 1; idx < points.size(); ++idx) {\n    const double delta = (points[idx] - points[idx - 1]).norm();\n    distance += delta;\n  }\n\n  return distance;\n}\n\ninline std::vector<double> CalculateIndividualDistances(const EigenHelpers::VectorVector3d& points) {\n  std::vector<double> distances(points.size());\n\n  if (points.size() > 0) {\n    distances[0] = 0.0;\n    for (size_t idx = 1; idx < points.size(); ++idx) {\n      distances[idx] = (points[idx] - points[idx - 1]).norm();\n    }\n  }\n\n  return distances;\n}\n\ninline std::vector<double> CalculateCumulativeDistances(const EigenHelpers::VectorVector3d& points) {\n  std::vector<double> distances(points.size());\n\n  if (points.size() > 0) {\n    distances[0] = 0.0;\n    for (size_t idx = 1; idx < points.size(); ++idx) {\n      const double delta = (points[idx] - points[idx - 1]).norm();\n      distances[idx] = distances[idx - 1] + delta;\n    }\n  }\n\n  return distances;\n}\n\n/**\n * @brief Computes the squared distance between each point in a given set\n *\n * @param set The set of points to compute distances on, arranged with each point as a column\n *\n * @return The distances between each pair of nodes\n */\ntemplate <typename ScalarType, int VectorLength, int NumVectors>\ninline Eigen::Matrix<double, NumVectors, NumVectors> CalculateSquaredDistanceMatrix(\n    const Eigen::Matrix<ScalarType, VectorLength, NumVectors>& set) {\n  assert(set.cols() > 0);\n  const ssize_t num_vectors = set.cols();  // TODO: if NumVectors != Eigen::Dynamic, this is known at compile time\n\n  Eigen::MatrixXd squared_dist(num_vectors, num_vectors);\n#ifdef ENABLE_PARALLEL_DISTANCE_MATRIX\n#pragma omp parallel for\n#endif\n  for (ssize_t i = 0; i < num_vectors; i++) {\n    squared_dist(i, i) = 0.0;\n    for (ssize_t j = i + 1; j < num_vectors; j++) {\n      const double sq_dist = (set.col(i) - set.col(j)).squaredNorm();\n      squared_dist(i, j) = sq_dist;\n      squared_dist(j, i) = sq_dist;\n    }\n  }\n\n  return squared_dist;\n}\n\n/**\n * @brief Computes the distance between each point in a given set\n *\n * @param set The set of points to compute distances on, arranged with each point as a column\n *\n * @return The distances between each pair of nodes\n */\ntemplate <typename ScalarType, int VectorLength, int NumVectors>\ninline Eigen::Matrix<double, NumVectors, NumVectors> CalculateDistanceMatrix(\n    const Eigen::Matrix<ScalarType, VectorLength, NumVectors>& set) {\n  return CalculateSquaredDistanceMatrix(set).cwiseSqrt();\n}\n\n/**\n * @brief Computes the squared distance between a given point, and every point in a set\n *\n * @param set The set of points to compute distances on, arranged with each point as a column\n * @param point The point to measure the distance to\n *\n * @return The distances between each pair of nodes\n */\ntemplate <typename ScalarType, int VectorLength, int NumVectors>\ninline Eigen::Matrix<double, NumVectors, 1> CalculateSquaredDistanceToSet(\n    const Eigen::Matrix<ScalarType, VectorLength, NumVectors>& set,\n    const Eigen::Matrix<ScalarType, VectorLength, 1>& point) {\n  return (set.colwise() - point).colwise().squaredNorm();\n}\n\n/**\n * @brief Computes the distance between a given point, and every point in a set\n *\n * @param set The set of points to compute distances on, arranged with each point as a column\n * @param point The point to measure the distance to\n *\n * @return The distances between each pair of nodes\n */\ntemplate <typename ScalarType, int VectorLength, int NumVectors>\ninline Eigen::Matrix<double, NumVectors, 1> CalculateDistanceToSet(\n    const Eigen::Matrix<ScalarType, VectorLength, NumVectors>& set,\n    const Eigen::Matrix<ScalarType, VectorLength, 1>& point) {\n  return CalculateSquaredDistanceToSet(set, point).cwiseSqrt();\n}\n\n/**\n * @brief Finds the closest point in the set to a given point\n *\n * @param set The set of points to compute distances on, arranged with each point as a column\n * @param point The point to measure the distance to\n *\n * @return The index of the point in the set\n */\ntemplate <typename ScalarType, int VectorLength, int NumVectors>\ninline ssize_t ClosestPointInSet(const Eigen::Matrix<ScalarType, VectorLength, NumVectors>& set,\n                                 const Eigen::Matrix<ScalarType, VectorLength, 1>& point) {\n  assert(set.cols() > 0);\n  ssize_t min_ind = 0;\n  const Eigen::VectorXd squared_dist = CalculateSquaredDistanceToSet(set, point);\n  squared_dist.minCoeff(&min_ind);\n  return min_ind;\n}\n\n/**\n * @brief Calculates the squared distance between every point in A and every point in B.\n *\n * @param A (D x M) matrix of points\n * @param B (D x N) matrix of points\n *\n * @return (M X N) matrix of distances between points\n */\ntemplate <typename DerivedA, typename DerivedB>\ninline Eigen::Matrix<double, Eigen::MatrixBase<DerivedA>::ColsAtCompileTime,\n                     Eigen::MatrixBase<DerivedB>::ColsAtCompileTime>\nSquaredDistancesBetweenPointSets(const Eigen::MatrixBase<DerivedA>& A, const Eigen::MatrixBase<DerivedB>& B) {\n  using namespace Eigen;\n  Matrix<double, MatrixBase<DerivedA>::ColsAtCompileTime, MatrixBase<DerivedB>::ColsAtCompileTime> distances_sq;\n  if (MatrixBase<DerivedA>::ColsAtCompileTime == Dynamic || MatrixBase<DerivedB>::ColsAtCompileTime == Dynamic) {\n    distances_sq.resize(A.cols(), B.cols());\n  }\n\n  for (ssize_t i = 0; i < B.cols(); ++i) {\n    distances_sq.col(i) = (A.colwise() - B.col(i)).colwise().squaredNorm();\n  }\n\n  return distances_sq;\n}\n\n////////////////////////////////////////////////////////////////////////////\n// Conversion functions\n////////////////////////////////////////////////////////////////////////////\n\ninline Eigen::Quaterniond QuaternionFromRPY(const double R, const double P, const double Y) {\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 */\ninline Eigen::Quaterniond QuaternionFromUrdfRPY(const double R, const double P, const double Y) {\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\ninline Eigen::Vector3d EulerAnglesFromRotationMatrix(const Eigen::Matrix3d& rot_matrix) {\n  const Eigen::Vector3d euler_angles = rot_matrix.eulerAngles(0, 1, 2);  // Use XYZ angles\n  return euler_angles;\n}\n\n// Returns XYZ Euler angles\ninline Eigen::Vector3d EulerAnglesFromQuaternion(const Eigen::Quaterniond& quat) {\n  return EulerAnglesFromRotationMatrix(quat.toRotationMatrix());\n}\n\n// Returns XYZ Euler angles\ninline Eigen::Vector3d EulerAnglesFromIsometry3d(const Eigen::Isometry3d& trans) {\n  return EulerAnglesFromRotationMatrix(trans.rotation());\n}\n\ninline Eigen::Isometry3d TransformFromRPY(const double x, const double y, const double z, const double roll,\n                                          const double pitch, const double yaw) {\n  const Eigen::Isometry3d transform = Eigen::Translation3d(x, y, z) * QuaternionFromRPY(roll, pitch, yaw);\n  return transform;\n}\n\ninline Eigen::Isometry3d TransformFromRPY(const Eigen::Vector3d& translation, const Eigen::Vector3d& rotation) {\n  const Eigen::Isometry3d transform =\n      (Eigen::Translation3d)translation * QuaternionFromRPY(rotation.x(), rotation.y(), rotation.z());\n  return transform;\n}\n\ninline Eigen::Isometry3d TransformFromRPY(const Eigen::VectorXd& components) {\n  assert(components.size() == 6);\n  const Eigen::Isometry3d transform = Eigen::Translation3d(components(0), components(1), components(2)) *\n                                      QuaternionFromRPY(components(3), components(4), components(5));\n  return transform;\n}\n\ninline Eigen::VectorXd TransformToRPY(const Eigen::Isometry3d& transform) {\n  Eigen::VectorXd components = Eigen::VectorXd::Zero(6);\n  const Eigen::Vector3d translation = transform.translation();\n  const Eigen::Vector3d rotation = EulerAnglesFromRotationMatrix(transform.rotation());\n  components << translation, rotation;\n  return components;\n}\n\ninline Eigen::Vector3d StdVectorDoubleToEigenVector3d(const std::vector<double>& vector) {\n  assert(vector.size() == 3 && \"std::vector<double> source vector is not 3 elements in size\");\n  return Eigen::Vector3d(vector[0], vector[1], vector[2]);\n}\n\ninline Eigen::VectorXd StdVectorDoubleToEigenVectorXd(const std::vector<double>& vector) {\n  Eigen::VectorXd eigen_vector(vector.size());\n  for (size_t idx = 0; idx < vector.size(); idx++) {\n    const double val = vector[idx];\n    eigen_vector((ssize_t)idx) = val;\n  }\n  return eigen_vector;\n}\n\ninline std::vector<double> EigenVector3dToStdVectorDouble(const Eigen::Vector3d& point) {\n  return std::vector<double>{point.x(), point.y(), point.z()};\n}\n\ninline std::vector<double> EigenVectorXdToStdVectorDouble(const Eigen::VectorXd& eigen_vector) {\n  std::vector<double> vector((size_t)eigen_vector.size());\n  for (size_t idx = 0; idx < (size_t)eigen_vector.size(); idx++) {\n    const double val = eigen_vector[(ssize_t)idx];\n    vector[idx] = val;\n  }\n  return vector;\n}\n\ntemplate <typename T, int LENGTH, typename Allocator>\ninline Eigen::Matrix<T, Eigen::Dynamic, 1> VectorEigenVectorToEigenVectorX(\n    const std::vector<Eigen::Matrix<T, LENGTH, 1>, Allocator>& vector_eigen_input) {\n  assert(vector_eigen_input.size() > 0);\n\n  Eigen::Matrix<T, Eigen::Dynamic, 1> eigen_result;\n  eigen_result.resize((ssize_t)vector_eigen_input.size() * vector_eigen_input[0].rows());\n\n  for (size_t idx = 0; idx < vector_eigen_input.size(); idx++) {\n    eigen_result.segment((ssize_t)idx * LENGTH, LENGTH) = vector_eigen_input[idx];\n  }\n\n  return eigen_result;\n}\n\ntemplate <typename T, int LENGTH>\ninline std::vector<Eigen::Matrix<T, LENGTH, 1>, Eigen::aligned_allocator<Eigen::Matrix<T, LENGTH, 1>>>\nEigenVectorXToVectorEigenVector(const Eigen::VectorXd& eigen_input)\n// TODO: Why can't I use the more generic version?\n//    inline std::vector<Eigen::Matrix<T, LENGTH, 1>, Eigen::aligned_allocator<Eigen::Matrix<T, LENGTH, 1>>>\n//    EigenVectorXToVectorEigenVector(const Eigen::Matrix<T, Eigen::Dynamic, 1>& eigen_input)\n{\n  assert(eigen_input.rows() % LENGTH == 0);\n  size_t num_vectors = eigen_input.rows() / LENGTH;\n\n  std::vector<Eigen::Matrix<T, LENGTH, 1>, Eigen::aligned_allocator<Eigen::Matrix<T, LENGTH, 1>>> vector_eigen_output(\n      num_vectors);\n\n  for (size_t idx = 0; idx < num_vectors; idx++) {\n    vector_eigen_output[idx] = eigen_input.segment<LENGTH>((ssize_t)idx * LENGTH);\n  }\n\n  return vector_eigen_output;\n}\n\ntemplate <typename T, int LENGTH>\ninline std::vector<Eigen::Matrix<T, LENGTH, 1>, Eigen::aligned_allocator<Eigen::Matrix<T, LENGTH, 1>>>\nStdVectorXToVectorEigenVector(const std::vector<T>& std_input) {\n  assert(std_input.size() % LENGTH == 0);\n  const size_t num_vectors = std_input.size() / LENGTH;\n\n  std::vector<Eigen::Matrix<T, LENGTH, 1>, Eigen::aligned_allocator<Eigen::Matrix<T, LENGTH, 1>>> vector_eigen_output(\n      num_vectors);\n\n  for (size_t vec_idx = 0; vec_idx < num_vectors; vec_idx++) {\n    for (size_t inner_idx = 0; inner_idx < LENGTH; ++inner_idx) {\n      vector_eigen_output[vec_idx](inner_idx) = std_input[vec_idx * LENGTH + inner_idx];\n    }\n  }\n\n  return vector_eigen_output;\n}\n\ntemplate <typename T>\ninline std::vector<T> EigenVectorXToStdVector(const Eigen::Matrix<T, Eigen::Dynamic, 1>& eig_vec) {\n  std::vector<T> std_vec(eig_vec.data(), eig_vec.data() + eig_vec.size());\n  return std_vec;\n}\n\ntemplate <typename T>\ninline Eigen::Matrix<T, Eigen::Dynamic, 1> StdVectorToEigenVectorX(const std::vector<T>& std_vec) {\n  Eigen::Matrix<T, Eigen::Dynamic, 1> eig_vec(std_vec.size());\n  memcpy(eig_vec.data(), std_vec.data(), std_vec.size() * sizeof(T));\n  return eig_vec;\n}\n\n// Takes <x, y, z, w> as is the ROS custom!\ninline Eigen::Quaterniond StdVectorDoubleToEigenQuaterniond(const std::vector<double>& vector) {\n  if (vector.size() != 4) {\n    std::cerr << \"Quaterniond source vector is not 4 elements in size\" << std::endl;\n    assert(false);\n  }\n  Eigen::Quaterniond eigen_quaternion(vector[3], vector[0], vector[1], vector[2]);\n  return eigen_quaternion;\n}\n\n// Returns <x, y, z, w> as is the ROS custom!\ninline std::vector<double> EigenQuaterniondToStdVectorDouble(const Eigen::Quaterniond& quat) {\n  return std::vector<double>{quat.x(), quat.y(), quat.z(), quat.w()};\n}\n\n////////////////////////////////////////////////////////////////////////////\n// Averaging functions\n// Numerically more stable averages taken from http://people.ds.cam.ac.uk/fanf2/hermes/doc/antiforgery/stats.pdf\n////////////////////////////////////////////////////////////////////////////\n\n/**\n * This function is really only going to work well for \"approximately continuous\"\n *  types, i.e. floats and doubles, due to the implementation\n */\ntemplate <typename ScalarType, int Rows, typename Allocator = std::allocator<Eigen::Matrix<ScalarType, Rows, 1>>>\ninline Eigen::Matrix<ScalarType, Rows, 1> AverageEigenVector(\n    const std::vector<Eigen::Matrix<ScalarType, Rows, 1>, Allocator>& vectors,\n    const std::vector<double>& weights = std::vector<double>()) {\n  // Get the weights\n  assert(vectors.size() > 0);\n  assert((weights.size() == vectors.size()) || (weights.size() == 0));\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() && weights[starting_idx] == 0.0) {\n    starting_idx++;\n  }\n  // If all weights are zero, result is undefined\n  assert(starting_idx < vectors.size());\n  // Start the recursive definition with the base case\n  Eigen::Matrix<ScalarType, Rows, 1> avg_vector = vectors[starting_idx];\n  const double starting_weight = use_weights ? std::abs(weights[starting_idx]) : 1.0;\n  assert(starting_weight > 0.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 < vectors.size(); ++idx) {\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 Eigen::Matrix<ScalarType, Rows, 1> prev_avg_vector = avg_vector;\n    const Eigen::Matrix<ScalarType, Rows, 1>& current = vectors[idx];\n    avg_vector = prev_avg_vector + (effective_weight * (current - prev_avg_vector));\n  }\n  return avg_vector;\n}\n\ninline Eigen::Vector3d AverageEigenVector3d(const EigenHelpers::VectorVector3d& vectors,\n                                            const std::vector<double>& weights = std::vector<double>()) {\n  return AverageEigenVector(vectors, weights);\n}\n\ninline Eigen::VectorXd AverageEigenVectorXd(const std::vector<Eigen::VectorXd>& vectors,\n                                            const std::vector<double>& weights = std::vector<double>()) {\n  return AverageEigenVector(vectors, weights);\n}\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 full explanation\n */\ninline Eigen::Quaterniond AverageEigenQuaterniond(const EigenHelpers::VectorQuaterniond& quaternions,\n                                                  const std::vector<double>& weights = std::vector<double>()) {\n  // Get the weights\n  const bool use_weights = weights.size() == quaternions.size() ? true : false;\n  assert(quaternions.size() > 0);\n  assert((weights.size() == quaternions.size()) || (weights.size() == 0));\n  // Shortcut the process if there is only 1 quaternion\n  if (quaternions.size() == 1) {\n    assert(weights.size() == 0 || weights[0] != 0.0);\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    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(), weight * q.x(), weight * q.y(), weight * q.z();\n  }\n  // Make the matrix square\n  const Eigen::Matrix<double, 4, 4> qqtranspose_matrix = q_matrix * q_matrix.transpose();\n  // Compute the eigenvectors and eigenvalues of the qqtranspose matrix\n  const Eigen::EigenSolver<Eigen::Matrix<double, 4, 4>> solver(qqtranspose_matrix);\n  const Eigen::EigenSolver<Eigen::Matrix<double, 4, 4>>::EigenvalueType eigen_values = solver.eigenvalues();\n  const Eigen::EigenSolver<Eigen::Matrix<double, 4, 4>>::EigenvectorsType eigen_vectors = solver.eigenvectors();\n  // Extract the eigenvector corresponding to the largest eigenvalue\n  double max_eigenvalue = -INFINITY;\n  int64_t max_eigenvector_index = -1;\n  for (size_t idx = 0; idx < 4; idx++) {\n    const double current_eigenvalue = eigen_values((long)idx).real();\n    if (current_eigenvalue > max_eigenvalue) {\n      max_eigenvalue = current_eigenvalue;\n      max_eigenvector_index = (int64_t)idx;\n    }\n  }\n  assert(max_eigenvector_index >= 0);\n  // Note that these are already normalized!\n  const Eigen::Vector4cd best_eigenvector = eigen_vectors.col((long)max_eigenvector_index);\n  // Convert back into a quaternion\n  const Eigen::Quaterniond average_q(best_eigenvector(0).real(), best_eigenvector(1).real(), best_eigenvector(2).real(),\n                                     best_eigenvector(3).real());\n  return average_q;\n}\n\ninline Eigen::Isometry3d AverageEigenIsometry3d(const EigenHelpers::VectorIsometry3d& transforms,\n                                                const std::vector<double>& weights = std::vector<double>()) {\n  assert(transforms.size() > 0);\n  assert((weights.size() == transforms.size()) || (weights.size() == 0));\n  // Shortcut the process if there is only 1 transform\n  if (transforms.size() == 1) {\n    assert(weights.size() == 0 || weights[0] != 0.0);\n    return transforms[0];\n  }\n  // Extract components\n  EigenHelpers::VectorVector3d translations(transforms.size());\n  EigenHelpers::VectorQuaterniond rotations(transforms.size());\n  for (size_t idx = 0; idx < transforms.size(); idx++) {\n    translations[idx] = transforms[idx].translation();\n    rotations[idx] = Eigen::Quaterniond(transforms[idx].rotation());\n  }\n  // Average\n  const Eigen::Vector3d average_translation = AverageEigenVector(translations, weights);\n  const Eigen::Quaterniond average_rotation = AverageEigenQuaterniond(rotations, weights);\n  // Make the average transform\n  const Eigen::Isometry3d average_transform = (Eigen::Translation3d)average_translation * average_rotation;\n  return average_transform;\n}\n\n////////////////////////////////////////////////////////////////////////////\n// Projection/Rejection functions\n////////////////////////////////////////////////////////////////////////////\n\n// Projects vector_to_project onto base_vector and returns the portion that is parallel to base_vector\ntemplate <typename DerivedB, typename DerivedV>\ninline Eigen::Matrix<typename DerivedB::Scalar, Eigen::Dynamic, 1> VectorProjection(\n    const Eigen::MatrixBase<DerivedB>& base_vector, const Eigen::MatrixBase<DerivedV>& vector_to_project) {\n  EIGEN_STATIC_ASSERT_VECTOR_ONLY(DerivedB);\n  EIGEN_STATIC_ASSERT_VECTOR_ONLY(DerivedV);\n  EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(DerivedB, DerivedV)\n  static_assert(std::is_same<typename DerivedB::Scalar, typename DerivedV::Scalar>::value,\n                \"base_vector and vector_to_project must have the same data type\");\n  // Perform projection\n  const typename DerivedB::Scalar b_squared_norm = base_vector.squaredNorm();\n  if (b_squared_norm > 0) {\n    return (base_vector.dot(vector_to_project) / b_squared_norm) * base_vector;\n  } else {\n    return Eigen::Matrix<typename DerivedB::Scalar, Eigen::Dynamic, 1>::Zero(base_vector.rows());\n  }\n}\n\n// Projects vector_to_project onto base_vector and returns the portion that is perpendicular to base_vector\ntemplate <typename DerivedB, typename DerivedV>\ninline Eigen::Matrix<typename DerivedB::Scalar, Eigen::Dynamic, 1> VectorRejection(\n    const Eigen::MatrixBase<DerivedB>& base_vector, const Eigen::MatrixBase<DerivedV>& vector_to_reject) {\n  // Rejection is defined in relation to projection\n  return vector_to_reject - VectorProjection(base_vector, vector_to_reject);\n}\n\n// Intended only for planes in 3-D, not hyperplanes (see Hyperplane class)\ntemplate <typename DerivedB1, typename DerivedB2, typename DerivedV>\ninline Eigen::Vector3d VectorProjectionToPlane(const Eigen::MatrixBase<DerivedB1>& plane_vector1,\n                                               const Eigen::MatrixBase<DerivedB2>& plane_vector2,\n                                               const Eigen::MatrixBase<DerivedV>& vector) {\n  EIGEN_STATIC_ASSERT_VECTOR_ONLY(DerivedB1);\n  EIGEN_STATIC_ASSERT_VECTOR_ONLY(DerivedB2);\n  EIGEN_STATIC_ASSERT_VECTOR_ONLY(DerivedV);\n  EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(DerivedB1, DerivedV);\n  EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(DerivedB2, DerivedV);\n\n  const Eigen::Vector3d unit_plane_vector1 = plane_vector1.normalized();\n  const Eigen::Vector3d unit_plane_vector2 = plane_vector2.normalized();\n\n  // Error/numerical problems check input\n  const double plane_vector_dot_product_mag = std::abs(unit_plane_vector1.dot(unit_plane_vector2));\n  if (IsApprox(plane_vector_dot_product_mag, 1.0, 1e-10)) {\n    throw_arc_exception(std::invalid_argument, \"Plane vectors do not define a valid plane\");\n  }\n\n  // Get the normal to the plane, then reject any component of the vector that is parallel\n  const Eigen::Vector3d normal = unit_plane_vector1.cross(unit_plane_vector2);\n  return VectorRejection(normal, vector);\n}\n\n////////////////////////////////////////////////////////////////////////////\n// Geometry functions\n////////////////////////////////////////////////////////////////////////////\n\n/**\n * @brief DistanceToLine\n * Math taken from http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html\n * x = x0\n * point_on_line = x1\n * unit_vector = x2 - x1 / |x2 - x1|\n * @param point_on_line\n * @param unit_vector\n * @param x\n * @return The distance to the line, and the displacement along the line\n */\ninline std::pair<double, double> DistanceToLine(const Eigen::Vector3d& point_on_line,\n                                                const Eigen::Vector3d& unit_vector, const Eigen::Vector3d& x) {\n  // Ensure that our input data is valid\n  const auto real_unit_vector = unit_vector.normalized();\n  if (!CloseEnough(unit_vector.norm(), 1.0, 1e-13)) {\n    std::cerr << \"[Distance to line]: unit vector was not normalized: \" << unit_vector.transpose()\n              << \" Norm: \" << unit_vector.norm() << std::endl;\n  }\n\n  const auto delta = x - point_on_line;\n  const double displacement_along_line = real_unit_vector.dot(delta);\n  const auto x_projected_onto_line = point_on_line + real_unit_vector * displacement_along_line;\n  const double distance_to_line = (x_projected_onto_line - x).norm();\n\n  // A simple neccescary (but not sufficient) check to look for math errors\n  assert(IsApprox(distance_to_line * distance_to_line + displacement_along_line * displacement_along_line,\n                  delta.squaredNorm(), 1e-10));\n\n  return std::make_pair(distance_to_line, displacement_along_line);\n}\n\n// We want to constrain all vectors \"r\" to lie within a specified angle of the cone direction.\n// I.e. cone_direction.transpose() * r / norm(r) >= cos(angle)\n// or cone_direction.transpose() * r_normalized >= min_normalized_dot_product\n// It is assumed that cone_direction is already normalized\n// Returns the normal vectors that point out of a pyramid approximation of the cone\ninline VectorVector3d ConvertConeToPyramid(const Eigen::Vector3d& cone_direction,\n                                           const double min_normalized_dot_product) {\n  // Build a vector that is garunteed to be perpendicular to cone_direction, and non-zero\n  auto tmp = VectorRejection(cone_direction, Eigen::Vector3d::UnitX());\n  tmp += VectorRejection(cone_direction, Eigen::Vector3d::UnitY());\n  tmp += VectorRejection(cone_direction, Eigen::Vector3d::UnitZ());\n\n  assert(tmp.norm() > 1e-6);\n  tmp.normalize();\n\n  const Eigen::Vector3d p1 = tmp;\n  const Eigen::Vector3d p2 = cone_direction.cross(p1).normalized();\n  const Eigen::Vector3d p3 = -p1;\n  const Eigen::Vector3d p4 = -p2;\n\n  const double theta_max = std::acos(min_normalized_dot_product);\n  const double dist = std::tan(theta_max);\n\n  const Eigen::Vector3d ray1 = cone_direction + dist * p1;\n  const Eigen::Vector3d ray2 = cone_direction + dist * p2;\n  const Eigen::Vector3d ray3 = cone_direction + dist * p3;\n  const Eigen::Vector3d ray4 = cone_direction + dist * p4;\n\n  VectorVector3d normals(4);\n  normals[0] = -ray1.cross(ray2).normalized();\n  normals[1] = -ray2.cross(ray3).normalized();\n  normals[2] = -ray3.cross(ray4).normalized();\n  normals[3] = -ray4.cross(ray1).normalized();\n\n  return normals;\n}\n\n////////////////////////////////////////////////////////////////////////////\n// (Weighted) dot product, norm, and angle functions\n////////////////////////////////////////////////////////////////////////////\n\n// Returns the (non-negative) angle defined by the vectors (b - a), and (b - c)\ntemplate <typename DerivedA, typename DerivedB, typename DerivedC>\ninline double AngleDefinedByPoints(const Eigen::MatrixBase<DerivedA>& a, const Eigen::MatrixBase<DerivedB>& b,\n                                   const Eigen::MatrixBase<DerivedC>& c) {\n  // Check for potential numerical problems\n  if (a.isApprox(b) || (b.isApprox(c))) {\n    std::cerr << \"Warning: Potential numerical stability problems in AngleDefinedByPoints\\n\";\n  }\n\n  // Do the actual math here\n  const auto vec1 = (a - b).normalized();\n  const auto vec2 = (c - b).normalized();\n  const double cosine_raw = vec1.dot(vec2);\n  const double cosine = std::max(-1.0, std::min(cosine_raw, 1.0));\n  return std::acos(cosine);\n}\n\ninline double WeightedDotProduct(const Eigen::VectorXd& vec1, const Eigen::VectorXd& vec2,\n                                 const Eigen::VectorXd& weights) {\n  return vec1.cwiseProduct(weights).dot(vec2);\n}\n\ninline double WeightedSquaredNorm(const Eigen::VectorXd& vec, const Eigen::VectorXd weights) {\n  return WeightedDotProduct(vec, vec, weights);\n}\n\ninline double WeightedNorm(const Eigen::VectorXd& vec, const Eigen::VectorXd& weights) {\n  return std::sqrt(WeightedSquaredNorm(vec, weights));\n}\n\ninline double WeightedCosineAngleBetweenVectors(const Eigen::VectorXd& vec1, const Eigen::VectorXd& vec2,\n                                                const Eigen::VectorXd& weights) {\n  const double vec1_norm = WeightedNorm(vec1, weights);\n  const double vec2_norm = WeightedNorm(vec2, weights);\n  assert(vec1_norm > 0 && vec2_norm > 0);\n  const double result = WeightedDotProduct(vec1, vec2, weights) / (vec1_norm * vec2_norm);\n  return std::max(-1.0, std::min(result, 1.0));\n}\n\ninline double WeightedAngleBetweenVectors(const Eigen::VectorXd& vec1, const Eigen::VectorXd& vec2,\n                                          const Eigen::VectorXd& weights) {\n  return std::acos(WeightedCosineAngleBetweenVectors(vec1, vec2, weights));\n}\n\n////////////////////////////////////////////////////////////////////////////\n// Other auxiliary functions\n////////////////////////////////////////////////////////////////////////////\n\nclass Hyperplane {\n protected:\n  Eigen::VectorXd plane_origin_;\n  Eigen::VectorXd plane_normal_;\n\n public:\n  Hyperplane(const Eigen::VectorXd& origin, const Eigen::VectorXd& normal) {\n    assert(origin.size() == normal.size());\n    plane_origin_ = origin;\n    plane_normal_ = normal;\n  }\n\n  Hyperplane() {}\n\n  size_t GetDimensionality() const { return (size_t)plane_origin_.size(); }\n\n  const Eigen::VectorXd& GetOrigin() const { return plane_origin_; }\n\n  const Eigen::VectorXd& GetNormal() const { return plane_normal_; }\n\n  double GetNormedDotProduct(const Eigen::VectorXd& point) const {\n    assert(point.size() == plane_origin_.size());\n    const Eigen::VectorXd check_vector = point - plane_origin_;\n    const Eigen::VectorXd check_vector_normed = EigenHelpers::SafeNormal(check_vector);\n    const double dot_product = check_vector_normed.dot(plane_normal_);\n    return dot_product;\n  }\n\n  double GetRawDotProduct(const Eigen::VectorXd& point) const {\n    assert(point.size() == plane_origin_.size());\n    const Eigen::VectorXd check_vector = point - plane_origin_;\n    const double dot_product = check_vector.dot(plane_normal_);\n    return dot_product;\n  }\n\n  Eigen::VectorXd RejectVectorOntoPlane(const Eigen::VectorXd& vector) const {\n    return VectorProjection(plane_normal_, vector);\n  }\n\n  double GetSquaredDistanceToPlane(const Eigen::VectorXd& point) const {\n    const Eigen::VectorXd origin_to_point_vector = point - plane_origin_;\n    return VectorProjection(plane_normal_, origin_to_point_vector).squaredNorm();\n  }\n\n  double GetDistanceToPlane(const Eigen::VectorXd& point) const {\n    const Eigen::VectorXd origin_to_point_vector = point - plane_origin_;\n    return VectorProjection(plane_normal_, origin_to_point_vector).norm();\n  }\n\n  Eigen::VectorXd ProjectVectorOntoPlane(const Eigen::VectorXd& vector) const {\n    return VectorRejection(plane_normal_, vector);\n  }\n\n  Eigen::VectorXd ProjectPointOntoPlane(const Eigen::VectorXd& point) const {\n    const Eigen::VectorXd origin_to_point_vector = point - plane_origin_;\n    const Eigen::VectorXd projected_to_point_vector = VectorRejection(plane_normal_, origin_to_point_vector);\n    const Eigen::VectorXd projected_point = plane_origin_ + projected_to_point_vector;\n    return projected_point;\n  }\n};\n\n/*\n * Returns a pair of <centroid point, normal vector> defining the plane\n */\ninline Hyperplane FitPlaneToPoints(const std::vector<Eigen::VectorXd>& points) {\n  // Subtract out the centroid\n  const Eigen::VectorXd centroid = EigenHelpers::AverageEigenVectorXd(points);\n  Eigen::MatrixXd centered_points(centroid.size(), points.size());\n  for (size_t idx = 0; idx < points.size(); idx++) {\n    const Eigen::VectorXd& current_point = points[idx];\n    centered_points.block(0, (ssize_t)idx, centroid.size(), 1) = (current_point - centroid);\n  }\n  // Compute SVD of the centered points\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(centered_points, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  // Get results of SVD\n  const Eigen::JacobiSVD<Eigen::MatrixXd>::SingularValuesType& singular_values = svd.singularValues();\n  const Eigen::JacobiSVD<Eigen::MatrixXd>::MatrixUType& u_matrix = svd.matrixU();\n  // Get the left singular vector corresponding to the minimum singular value\n  double minimum_singular_value = INFINITY;\n  ssize_t best_singular_value_index = -1;\n  for (ssize_t idx = 0; idx < singular_values.size(); idx++) {\n    const std::complex<double> current_singular_value = singular_values(idx);\n    if (current_singular_value.real() < minimum_singular_value) {\n      minimum_singular_value = current_singular_value.real();\n      best_singular_value_index = idx;\n    }\n  }\n  assert(best_singular_value_index >= 0);\n  // The corresponding left singular vector is the normal vector of the best-fit plane\n  const Eigen::VectorXd best_left_singular_vector = u_matrix.col(best_singular_value_index);\n  const Eigen::VectorXd normal_vector = EigenHelpers::SafeNormal(best_left_singular_vector);\n  return Hyperplane(centroid, normal_vector);\n}\n\ninline double SuggestedRcond() { return 0.001; }\n\n// Derived from code by Yohann Solaro ( http://listengine.tuxfamily.org/lists.tuxfamily.org/eigen/2010/01/msg00187.html\n// ) see : http://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse#The_general_case_and_the_SVD_method\ninline Eigen::MatrixXd Pinv(const Eigen::MatrixXd& b, const double rcond, const bool enable_flip = true) {\n  bool flip = false;\n  Eigen::MatrixXd a;\n  if (enable_flip && (b.rows() < b.cols())) {\n    a = b.transpose();\n    flip = true;\n  } else {\n    a = b;\n  }\n  // SVD\n  Eigen::JacobiSVD<Eigen::MatrixXd> svdA;\n  svdA.compute(a, Eigen::ComputeFullU | Eigen::ComputeThinV);\n  Eigen::JacobiSVD<Eigen::MatrixXd>::SingularValuesType vSingular = svdA.singularValues();\n  // Build a diagonal matrix with the Inverted Singular values\n  // The pseudo inverted singular matrix is easy to compute :\n  // is formed by replacing every nonzero entry by its reciprocal (inversing).\n  Eigen::VectorXd vPseudoInvertedSingular(svdA.matrixV().cols());\n  for (int iRow = 0; iRow < vSingular.rows(); iRow++) {\n    if (std::abs(vSingular(iRow)) <= rcond)  // Todo : Put epsilon in parameter\n    {\n      vPseudoInvertedSingular(iRow) = 0.0;\n    } else {\n      vPseudoInvertedSingular(iRow) = 1.0 / vSingular(iRow);\n    }\n  }\n  // A little optimization here\n  const Eigen::MatrixXd mAdjointU =\n      svdA.matrixU().adjoint().block(0, 0, vSingular.rows(), svdA.matrixU().adjoint().cols());\n// Yes, this is ugly. This is to suppress a warning on type conversion related to Eigen operations\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wconversion\"\n  // Pseudo-Inversion : V * S * U'\n  const Eigen::MatrixXd a_pinv = (svdA.matrixV() * vPseudoInvertedSingular.asDiagonal()) * mAdjointU;\n#pragma GCC diagnostic pop\n  // Flip back if need be\n  if (flip) {\n    return a_pinv.transpose();\n  } else {\n    return a_pinv;\n  }\n}\n\n/**\n * @brief WeightedLeastSquaresSolver Solves the minimization problem min || Ax - b ||^2 for x, using weights w in the\n * norm If the problem is ill-conditioned, adds in a damping factor. This is equivalent to solving A^T * diag(W) * A * x\n * = A^T * diag(W) * b for x.\n * @param A size M x N with M > N\n * @param b size M x 1\n * @param w size M x 1\n * @param damping_threshold The smallest singular value we allow in A^T * W * A before we apply damping\n * @param damping_value The damping value we apply to the main diagonal of A^T * W * A if we exceed the threshold\n * @return size N x 1\n */\ninline Eigen::VectorXd WeightedLeastSquaresSolver(const Eigen::MatrixXd& A, const Eigen::VectorXd& b,\n                                                  const Eigen::VectorXd& w, const double damping_threshold,\n                                                  const double damping_value) {\n// Yes, this is ugly. This is to suppress a warning on type conversion related to Eigen operations\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wconversion\"\n  Eigen::MatrixXd lhs = A.transpose() * w.asDiagonal() * A;\n#pragma GCC diagnostic pop\n  const double minimum_singular_value = lhs.jacobiSvd().singularValues().minCoeff();\n\n  if (minimum_singular_value < damping_threshold) {\n    lhs += damping_value * Eigen::MatrixXd::Identity(lhs.rows(), lhs.cols());\n  }\n\n  // With the damping we can assume that the left side is positive definite, so use LLT to solve this\n  return lhs.llt().solve(A.transpose() * w.cwiseProduct(b));\n}\n\ninline Eigen::VectorXd UnderdeterminedSolver(const Eigen::MatrixXd& A, const Eigen::VectorXd& b,\n                                             const double damping_threshold, const double damping_value) {\n  assert(A.cols() > A.rows());\n// Yes, this is ugly. This is to suppress a warning on type conversion related to Eigen operations\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wconversion\"\n  Eigen::MatrixXd damped = A * A.transpose();\n#pragma GCC diagnostic pop\n  const double minimum_singular_value = damped.jacobiSvd().singularValues().minCoeff();\n\n  if (minimum_singular_value < damping_threshold) {\n    damped += damping_value * Eigen::MatrixXd::Identity(damped.rows(), damped.cols());\n  }\n\n  // With the damping we can assume that what we are inverting is positive definite, so use LLT to solve this\n  return A.transpose() * damped.llt().solve(b);\n}\n}  // namespace EigenHelpers\n\n#endif  // EIGEN_HELPERS_HPP\n", "meta": {"hexsha": "75c62bd4824b17af53396d350e01d57992366d20", "size": 50695, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arc_utilities/eigen_helpers.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/eigen_helpers.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/eigen_helpers.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": 43.1814310051, "max_line_length": 120, "alphanum_fraction": 0.6814676004, "num_tokens": 12800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553656, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.500364521418622}}
{"text": "/* Copyright 2017 The sfcpp Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n\n#pragma once\n\n#include <geo/ConvexPolytope.hpp>\n\n#include <Eigen/Dense>\n#include <memory>\n#include <ostream>\n#include <vector>\n\nnamespace sfcpp {\nnamespace sfc {\n/**\n * This class can be used to specify a curve geometrically.\n */\nstruct CurveSpecification {\n  // Dimension of embedding space\n  size_t d;\n  // Matrix containing the points of the root polytope as columns\n  Eigen::MatrixXd rootPoints;\n  // A lookup table representing the child state function S^c\n  std::vector<std::vector<size_t>> grammar;\n  // Transition matrices, corresponding to the matrices M^{s,j} from the thesis.\n  std::vector<std::vector<Eigen::MatrixXd>> transitionMats;\n\n  /**\n   * This equals b in the paper (the branching factor).\n   */\n  size_t getNumChildren() const { return grammar[0].size(); }\n\n  size_t getNumStates() const { return grammar.size(); }\n\n  /**\n   * For d = 2, this function returns a local model of the Sierpinski curve.\n   * For d > 2, it produces a local model of a Sierpinski-like d-dimensional curve which apparently\n   * converges to a continuous curve but whose simplices appear to degenerate in shape with\n   * increasing level.\n   */\n  static std::shared_ptr<CurveSpecification> getSierpinskiCurveSpecification(size_t d = 2);\n  /**\n   * A custom curve whose limit curve is not continuous.\n   */\n  static std::shared_ptr<CurveSpecification> getCustomCurveSpecification1();\n\n  /**\n   * Semi-local model of the Gosper curve.\n   */\n  static std::shared_ptr<CurveSpecification> getGosperCurveSpecification();\n\n  /**\n   * Semi-local model of the beta Omega curve.\n   */\n  static std::shared_ptr<CurveSpecification> getBetaOmegaCurveSpecification();\n\n  friend std::ostream &operator<<(std::ostream &stream, CurveSpecification const &spec);\n};\n\n} /* namespace sfc */\n} /* namespace sfcpp */\n", "meta": {"hexsha": "d157378971985c0ccbe3a859bca1871b674a1d7b", "size": 2455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/sfc/CurveSpecification.hpp", "max_stars_repo_name": "dholzmueller/sfcpp", "max_stars_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-10-20T07:53:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T15:54:54.000Z", "max_issues_repo_path": "src/sfc/CurveSpecification.hpp", "max_issues_repo_name": "dholzmueller/sfcpp", "max_issues_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sfc/CurveSpecification.hpp", "max_forks_repo_name": "dholzmueller/sfcpp", "max_forks_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-10-20T20:02:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-02T12:47:53.000Z", "avg_line_length": 33.1756756757, "max_line_length": 99, "alphanum_fraction": 0.7128309572, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5003645175614561}}
{"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_TENPOWER_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_TENPOWER_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing tenpower capabilities\n\n    Returns \\f$10^n\\f$ in the floating type associated to\n    the integral type of parameter n\n\n    @par semantic:\n    For any given value n  of integral type @c I\n\n    @code\n    as_floating_t<I> r = tenpower(n);\n    @endcode\n\n    code is similar to:\n\n    @code\n    auto r = exp10(as_floating_t<I>(n));\n    @endcode\n\n    @par Note:\n\n    This function is not defined for floating entries and intended to be used for\n    small integer values.\n\n    @see exp10\n\n  **/\n  const boost::dispatch::functor<tag::tenpower_> tenpower = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/tenpower.hpp>\n#include <boost/simd/function/simd/tenpower.hpp>\n\n#endif\n", "meta": {"hexsha": "61a223e902a5973360eda76637e8b21f9f14893c", "size": 1327, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/tenpower.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/tenpower.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/tenpower.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": 23.6964285714, "max_line_length": 100, "alphanum_fraction": 0.6036171816, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5002657610084317}}
{"text": "//===----------------------------------------------------------------------===//\n//\n// NAME         : dedupe\n// SUMMARY      : Removes non-critical edges from a graph.\n// COPYRIGHT    : (c) 2018 Sean Donnellan. All Rights Reserved.\n// LICENSE      : The MIT License (see LICENSE.txt for details)\n// DESCRIPTION: : Reports the edges that should be removed from graph as they\n//                are not along the critical path.\n//\n// The mathematical name for this is transitive reduction.\n//\n// ATTENTION:\n// Do not bother with this, bascially when I started working on it  I struggled\n// to find anything that matched what I was trying to do. After finally getting\n// this to work, I then came across tred which lead me to the keywords\n// \"transitive reduction.\". Tred however was not the silver bullet I was\n// looking for, as it did have a problem  (https://stackoverflow.com/a/30554721)\n// as I was seeing it taking hours and hours on my graphs. This requires\n// GraphViz 2.42 and later.\n//\n// RECOMMENDED REPLACEMENT:\n//    tred from GraphViz - transitive reduction filter for directed graphs\n//\n// It is designed for graphs which match the following criteria:\n// - Effectively a tree.\n// - Directed\n// - No cycles\n// - Multiple leaves/roots.\n//\n// The high level view goal is to keep the longest paths between two vertices\n// and remove the short paths. It does this by determining which edges to\n// remove and utilises another tool to apply the changes.\n//\n//===----------------------------------------------------------------------===//\n//\n// Development notes:\n//   g++ -O3 -Wall -Wextra --std=c++1y dedupe.cpp -lboost_graph\n//\n// This tool makes use of the Boost.Graph library and the following link\n// provides a good starting point.\n// http://www.boost.org/doc/libs/1_66_0/libs/graph/doc/table_of_contents.html\n//\n// Possible options:\n// - Use Floyd-Warshall algorithm  to find the shortest paths by assigning\n//   negative weights so A -> C is considered -1 but A -> B ->C is considered\n//   -2 so is shorter.\n//\n//===----------------------------------------------------------------------===//\n\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/topological_sort.hpp>\n\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n\n// Boost.Graph supports two ways defining how the properties of the graphs\n// are set-up. The types using each method are defined in their own namespace,\n// named after the method (way). Switching between the two is done at\n// compile time.\nnamespace property_lists\n{\n    // The following graph uses uses property lists. From my reading these are\n    // discouraged but are still supported for existing code.\n    using vertex_p =\n        boost::property<boost::vertex_name_t, std::string,\n                        boost::property<boost::vertex_color_t, float>>;\n    using edge_p = boost::no_property;\n    using graph_t = boost::adjacency_list<boost::vecS, boost::vecS,\n                                          boost::directedS, vertex_p, edge_p>;\n\n    struct VertexToName\n    {\n        VertexToName(const graph_t& graph)\n            : index_to_name(boost::get(boost::vertex_name, graph))\n        {\n        }\n\n        std::string operator()(graph_t::vertex_descriptor vertex) const\n        {\n            return boost::get(index_to_name, vertex);\n        }\n\n        decltype(boost::get(boost::vertex_name,\n                            std::declval<graph_t>())) index_to_name;\n    };\n}\n\nnamespace bundled_properties\n{\n    // The following graph uses bundled_properties.\n    // http://www.boost.org/doc/libs/1_66_0/libs/graph/doc/bundles.html\n\n    struct Vertex\n    {\n        std::string name;\n    };\n\n    // The graphs have no properties (all the edges have a  weights of 1\n    // and they are never styled differently).\n    struct Edge\n    {\n    };\n\n    using graph_t = boost::adjacency_list<boost::vecS, boost::vecS,\n                                          boost::directedS, Vertex, Edge>;\n\n    struct VertexToName\n    {\n        VertexToName(const graph_t& graph) : graph(graph) {}\n\n        std::string operator()(graph_t::vertex_descriptor vertex) const\n        {\n            return graph[vertex].name;\n        }\n\n      private:\n        const graph_t& graph;\n    };\n}\n\n#define USE_PROPERTY_LISTS\n#ifdef USE_PROPERTY_LISTS\nusing graph_t = property_lists::graph_t;\nusing vertex_to_name_t = property_lists::VertexToName;\n#else\nusing graph_t = bundled_properties::graph_t;\nusing vertex_to_name_t = bundled_properties::VertexToName;\n#endif\nusing vertex_t = graph_t::vertex_descriptor;\nusing path_t = std::vector<graph_t::vertex_descriptor>;\n\n// Set-up the properties for reading from a GraphViz file.\nvoid setup_properties(property_lists::graph_t* graph,\n                      boost::dynamic_properties* dp);\nvoid setup_properties(bundled_properties::graph_t* graph,\n                      boost::dynamic_properties* dp);\n\n// Return the length of the longest path between u and v in graph.\nstd::size_t longest_path_length(const graph_t& graph, vertex_t u, vertex_t v);\n\n// Returns the length of the first path between u and v in graph that is\n// non-trival, that is to say is not simply the edge (u, v)\nstd::size_t length_first_non_trival_path(const graph_t& graph, vertex_t u,\n                                         vertex_t v);\n\ntemplate <typename Report>\nvoid all_paths_helper(vertex_t from, vertex_t to, graph_t const& g,\n                      path_t& path, Report const& callback)\n{\n    path.push_back(from);\n\n    if (from == to)\n    {\n        // Ideally we would check the result of callback if it had one\n        // otherwise ignore it.\n        callback(path);\n    }\n    else\n    {\n        for (auto out : make_iterator_range(out_edges(from, g)))\n        {\n            auto v = target(out, g);\n            // The following statement would always be true in our graphs.\n            // assert(path.end() == std::find(path.begin(), path.end(), v));\n            all_paths_helper(v, to, g, path, callback);\n        }\n    }\n\n    path.pop_back();\n}\n\ntemplate <typename Report>\nvoid all_paths(vertex_t from, vertex_t to, graph_t const& graph,\n               Report const& callback)\n{\n    path_t state;\n    all_paths_helper(from, to, graph, state, callback);\n}\n\nvoid setup_properties(property_lists::graph_t* graph,\n                      boost::dynamic_properties* dp)\n{\n    boost::property_map<property_lists::graph_t, boost::vertex_name_t>::type\n        name = boost::get(boost::vertex_name, *graph);\n    dp->property(\"node_id\", name);\n}\n\nvoid setup_properties(bundled_properties::graph_t* graph,\n                      boost::dynamic_properties* dp)\n{\n    dp->property(\"node_id\",\n                 boost::get(&bundled_properties::Vertex::name, *graph));\n}\n\nstd::size_t longest_path_length(const graph_t& graph, vertex_t u, vertex_t v)\n{\n    std::size_t longestPathLength = 0;\n    all_paths(u, v, graph, [&](path_t const& path) {\n        if (longestPathLength < path.size())\n        {\n            longestPathLength = path.size();\n        }\n    });\n    return longestPathLength;\n}\n\nstd::size_t length_first_non_trival_path(const graph_t& graph, vertex_t u,\n                                         vertex_t v)\n{\n    // Assume there exists an edge from (u, v) otherwise this function\n    // wouldn't have be called.\n    std::size_t longestPathLength = 2;\n\n    struct path_found_exception\n    {\n    };\n    const auto callback = [&](path_t const& path) {\n        if (longestPathLength < path.size())\n        {\n            longestPathLength = path.size();\n            throw path_found_exception();\n        }\n    };\n\n    path_t state;\n    try\n    {\n        all_paths_helper(u, v, graph, state, callback);\n    }\n    catch (const path_found_exception&)\n    {\n    }\n\n    return longestPathLength;\n}\n\nvoid find_edges_to_remove(const graph_t& graph)\n{\n    // For each edge (u, v) or (source, target) in the graph:\n    // - Determine if there exists a path from u to v that doesn't involve the\n    // edge.\n    // - If there is such a path flag the edge for removal.\n\n    // const auto limit = std::numeric_limits<std::size_t>::max();\n    const auto edge_process_limit = 150;\n\n    const vertex_to_name_t vertex_to_name(graph);\n    const auto edge_count = boost::num_edges(graph);\n    std::size_t current_edge = 0;\n    for (const auto& edge : boost::make_iterator_range(boost::edges(graph)))\n    {\n        const auto& u = boost::source(edge, graph);\n        const auto& v = boost::target(edge, graph);\n\n        // Find if there exists a path from u to v that isn't just u -> v.\n        if (length_first_non_trival_path(graph, u, v) > 2)\n        {\n            // Remove the short path as there is a longer path we must\n            // travel to get to v.\n            std::cout << \"Remove:Edge:\" << vertex_to_name(u) << \":\"\n                      << vertex_to_name(v) << std::endl;\n        }\n        ++current_edge;\n        std::cerr << \"Progress:Removal:\" << current_edge << \":\" << edge_count\n                  << std::endl;\n        if (current_edge > edge_process_limit)\n        {\n            std::cerr << \"Progress:Removal:Reached limit:\"\n                      << edge_process_limit << std::endl;\n            break;\n        }\n    }\n}\n\nint main(int argc, const char* argv[])\n{\n    std::istream* input = &std::cin;\n\n    std::fstream inputFile;\n    if (argc == 2)\n    {\n        inputFile.open(argv[1], std::fstream::in);\n        if (!inputFile)\n        {\n            std::cerr << \"Failed to open file\" << std::endl;\n            return 1;\n        }\n\n        input = &inputFile;\n    }\n    else if (argc == 1)\n    {\n        // The input stream already points to standard in.\n    }\n    else\n    {\n        std::cerr << \"usage: \" << argv[0] << \" [dot file]\" << std::endl;\n        return 1;\n    }\n\n    graph_t graph(0);\n    boost::dynamic_properties dp(boost::ignore_other_properties);\n    setup_properties(&graph, &dp);\n    bool status = boost::read_graphviz(*input, graph, dp, \"node_id\");\n    if (!status)\n    {\n        std::cerr << \"Failed to read file\" << std::endl;\n        return 1;\n    }\n\n    find_edges_to_remove(graph);\n    return 0;\n}\n", "meta": {"hexsha": "53db0b3fd66b1482bb784fb14de0ac9ce75c135e", "size": 10079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dedupe/dedupe.cpp", "max_stars_repo_name": "donno/warehouse51", "max_stars_repo_head_hexsha": "7ec968825734ee69a4fb1e6e46cb4e416741d5e9", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dedupe/dedupe.cpp", "max_issues_repo_name": "donno/warehouse51", "max_issues_repo_head_hexsha": "7ec968825734ee69a4fb1e6e46cb4e416741d5e9", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dedupe/dedupe.cpp", "max_forks_repo_name": "donno/warehouse51", "max_forks_repo_head_hexsha": "7ec968825734ee69a4fb1e6e46cb4e416741d5e9", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8955696203, "max_line_length": 80, "alphanum_fraction": 0.6124615537, "num_tokens": 2329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5002657491951908}}
{"text": "#include <tiny.h>\n#include <convex.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\nBOOST_AUTO_TEST_SUITE(convex_outside_vertex_edge);\n\nBOOST_AUTO_TEST_CASE(case_by_case_test)\n{\n  typedef tiny::MathTypes<double>     math_types;\n  typedef math_types::vector3_type   V;\n\n  V const a = V::make(1.0, 0.0, 0.0);\n  V const b = V::make(0.0, 0.0, 0.0);\n\n  // First we use a test point that does not lie on the line\n\n  // Front side of A voronoi plane\n  {\n    V p = V::make( 2.0, 1.0,  1.0);\n    bool outside = convex::outside_vertex_edge_voronoi_plane(p, a, b);\n    BOOST_CHECK( outside );\n  }\n  // Back side of A voronoi plane\n  {\n    V p = V::make( 0.0, 1.0,  1.0);\n    bool outside = convex::outside_vertex_edge_voronoi_plane(p, a, b);\n    BOOST_CHECK( !outside );\n  }\n  // In A voronoi plane\n  {\n    V p = V::make( 1.0, 1.0,  1.0);\n    bool outside = convex::outside_vertex_edge_voronoi_plane(p, a, b);\n    BOOST_CHECK( outside );\n  }\n\n  // Front side of B voronoi plane\n  {\n    V p = V::make( -1.0, 1.0,  1.0);\n    bool outside = convex::outside_vertex_edge_voronoi_plane(p, b, a);\n    BOOST_CHECK( outside );\n  }\n  // Back side of B voronoi plane\n  {\n    V p = V::make( 1.0, 1.0,  1.0);\n    bool outside = convex::outside_vertex_edge_voronoi_plane(p, b, a);\n    BOOST_CHECK( !outside );\n  }\n  // In B voronoi plane\n  {\n    V p = V::make( 0.0, 1.0,  1.0);\n    bool outside = convex::outside_vertex_edge_voronoi_plane(p, b, a);\n    BOOST_CHECK( outside );\n  }\n\n  // Second we use a test point that lies on the line\n\n  // Front side of A voronoi plane\n  {\n    V p = V::make( 2.0, 0.0,  0.0);\n    bool outside = convex::outside_vertex_edge_voronoi_plane(p, a, b);\n    BOOST_CHECK( outside );\n  }\n  // Back side of A voronoi plane\n  {\n    V p = V::make( 0.0, 0.0,  0.0);\n    bool outside = convex::outside_vertex_edge_voronoi_plane(p, a, b);\n    BOOST_CHECK( !outside );\n  }\n  // In A voronoi plane\n  {\n    V p = V::make( 1.0, 0.0,  0.0);\n    bool outside = convex::outside_vertex_edge_voronoi_plane(p, a, b);\n    BOOST_CHECK( outside );\n  }\n\n  // Front side of B voronoi plane\n  {\n    V p = V::make( -1.0, 0.0,  0.0);\n    bool outside = convex::outside_vertex_edge_voronoi_plane(p, b, a);\n    BOOST_CHECK( outside );\n  }\n  // Back side of B voronoi plane\n  {\n    V p = V::make( 1.0, 0.0,  0.0);\n    bool outside = convex::outside_vertex_edge_voronoi_plane(p, b, a);\n    BOOST_CHECK( !outside );\n  }\n  // In B voronoi plane\n  {\n    V p = V::make( 0.0, 0.0,  0.0);\n    bool outside = convex::outside_vertex_edge_voronoi_plane(p, b, a );\n    BOOST_CHECK( outside );\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "df1c1244442a6f3b53106fec2bdc743380cfe728", "size": 2750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/CONVEX/unit_tests/convex_outside_vertex_edge/convex_outside_vertex_edge.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/CONVEX/unit_tests/convex_outside_vertex_edge/convex_outside_vertex_edge.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/CONVEX/unit_tests/convex_outside_vertex_edge/convex_outside_vertex_edge.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": 26.9607843137, "max_line_length": 71, "alphanum_fraction": 0.6327272727, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5002657491951908}}
{"text": "#include <doctest/doctest.h>  // for TestCase, TEST_CASE\n// #include <__config>                 // for std\n// #include <__hash_table>             // for operator!=\n#include <boost/utility/string_view.hpp>  // for boost::string_view\n#include <ckpttn/netlist.hpp>             // for Netlist, Netlist<>::nodeview_t\n#include <ckpttn/netlist_algo.hpp>        // for min_maximal_matching, min_vertex_...\n#include <py2cpp/dict.hpp>                // for dict\n#include <py2cpp/range.hpp>               // for _iterator, iterable_wrapper\n#include <py2cpp/set.hpp>                 // for set\n\nusing namespace std;\n\nextern auto create_test_netlist() -> SimpleNetlist;  // import create_test_netlist\nextern auto create_dwarf() -> SimpleNetlist;         // import create_dwarf\nextern auto readNetD(boost::string_view netDFileName) -> SimpleNetlist;\nextern void readAre(SimpleNetlist& H, boost::string_view areFileName);\n// extern tuple<py::set<node_t>, int>\n// min_net_cover_pd(SimpleNetlist &, const vector<int> &);\n\nusing node_t = SimpleNetlist::node_t;\n\nTEST_CASE(\"Test min_vertex_cover dwarf\") {\n    const auto H = create_dwarf();\n    py::dict<node_t, int> weight{};\n    py::set<node_t> covset{};\n    for (auto node : H) {\n        weight[node] = 1;\n        // covset[node] = false;\n    }\n    min_vertex_cover(H, weight, covset);\n}\n\n//\n// Primal-dual algorithm for minimum vertex cover problem\n//\n\nTEST_CASE(\"Test min_maximal_matching dwarf\") {\n    const auto H = create_dwarf();\n    // const auto N = H.number_of_nets();\n    py::dict<node_t, int> weight{};\n    py::set<node_t> matchset{};\n    py::set<node_t> dep{};\n    for (auto net : H.nets) {\n        // matchset[net] = false;\n        weight[net] = 1;\n    }\n    // for (auto v : H)\n    // {\n    //     dep[v] = false;\n    // }\n    min_maximal_matching(H, weight, matchset, dep);\n}\n", "meta": {"hexsha": "7738d2b65641566abffbb7a24861a907aaad1b48", "size": 1825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/source/test_netlist_algo.cpp", "max_stars_repo_name": "luk036/ckpttn-cpp", "max_stars_repo_head_hexsha": "9d15cdadf5e6b968e6e6a9d5e3db500256a11a6f", "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/source/test_netlist_algo.cpp", "max_issues_repo_name": "luk036/ckpttn-cpp", "max_issues_repo_head_hexsha": "9d15cdadf5e6b968e6e6a9d5e3db500256a11a6f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-24T12:00:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-11T04:35:10.000Z", "max_forks_repo_path": "test/source/test_netlist_algo.cpp", "max_forks_repo_name": "luk036/ckpttn-cpp", "max_forks_repo_head_hexsha": "9d15cdadf5e6b968e6e6a9d5e3db500256a11a6f", "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": 34.4339622642, "max_line_length": 85, "alphanum_fraction": 0.6323287671, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5002657491951907}}
{"text": "/* Boost test/fmod.cpp\n * test the fmod with specially crafted integer intervals\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/interval.hpp>\n#include <boost/numeric/interval/arith.hpp>\n#include <boost/numeric/interval/arith2.hpp>\n#include <boost/numeric/interval/utility.hpp>\n#include <boost/numeric/interval/checking.hpp>\n#include <boost/numeric/interval/rounding.hpp>\n#include <boost/core/lightweight_test.hpp>\n#include \"bugs.hpp\"\n\nstruct my_rounded_arith {\n  int sub_down(int x, int y) { return x - y; }\n  int sub_up  (int x, int y) { return x - y; }\n  int mul_down(int x, int y) { return x * y; }\n  int mul_up  (int x, int y) { return x * y; }\n  int div_down(int x, int y) {\n    int q = x / y;\n    return (x % y < 0) ? (q - 1) : q;\n  }\n  int int_down(int x) { return x; }\n};\n\nusing namespace boost;\nusing namespace numeric;\nusing namespace interval_lib;\n\ntypedef change_rounding<interval<int>, save_state_nothing<my_rounded_arith> >::type I;\n\nint main() {\n\n  BOOST_TEST(equal(fmod(I(6,9), 7), I(6,9)));\n  BOOST_TEST(equal(fmod(6, I(7,8)), I(6,6)));\n  BOOST_TEST(equal(fmod(I(6,9), I(7,8)), I(6,9)));\n\n  BOOST_TEST(equal(fmod(I(13,17), 7), I(6,10)));\n  BOOST_TEST(equal(fmod(13, I(7,8)), I(5,6)));\n  BOOST_TEST(equal(fmod(I(13,17), I(7,8)), I(5,10)));\n\n  BOOST_TEST(equal(fmod(I(-17,-13), 7), I(4,8)));\n  BOOST_TEST(equal(fmod(-17, I(7,8)), I(4,7)));\n  BOOST_TEST(equal(fmod(I(-17,-13), I(7,8)), I(4,11)));\n\n  return boost::report_errors();\n}\n", "meta": {"hexsha": "11e88ed1fd9e6852a8b05f04a4c9f7dae8ca7c52", "size": 1643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fmod.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/fmod.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/fmod.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": 30.4259259259, "max_line_length": 86, "alphanum_fraction": 0.665855143, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370423, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5002657447738194}}
{"text": "#include <boost/random.hpp> //needed for random range generation\n#include \"common.hh\"\n#include \"exodusII.h\"\n#include <thread>\n\n#ifndef DOMAIN_LENGTH\n    #error Your need to define DOMAIN_LENGTH in a common header file\n#endif\n\nusing namespace std;\n\nvoid get_queries_specific_feature_sizes(testing_config config, std::vector<std::vector<bbox>> &all_queries, std::vector<double> &queries_percent_data_covered\n    ) \n{\n    typedef boost::variate_generator<boost::mt19937&, boost::uniform_real<double>> generator;\n    vector<double> domain_lengths;\n    for(size_t i = 0; i < config.domain_lower_bounds.size(); i++) {\n        domain_lengths.push_back(config.domain_upper_bounds[i]-config.domain_lower_bounds[i]);\n        if(DEBUG) {\n            cout << \"domain_lengths[\" << i << \"]: \" << domain_lengths[i] << endl;\n            cout << \"config.domain_upper_bounds[\" << i << \"]: \" << config.domain_upper_bounds[i] << endl;\n            cout << \"config.domain_lower_bounds[\" << i << \"]: \" << config.domain_lower_bounds[i] << endl;\n        }\n    }\n\n    //feature = .001% of data -> .001% of domain space\n    //value adjusted slightly so we find closer the correct amount of data\n    double frac1 = cbrt(90100);\n    double extra_extra_small_x_length = domain_lengths[0]/frac1;\n    double extra_extra_small_y_length = domain_lengths[1]/frac1;\n    double extra_extra_small_z_length = domain_lengths[2]/frac1;\n\n    //feature = .1% of data -> .1% of domain space\n    //value adjusted slightly so we find closer the correct amount of data\n    double frac2 = cbrt(1050);\n    double small_x_length = domain_lengths[0]/frac2;\n    double small_y_length = domain_lengths[1]/frac2;\n    double small_z_length = domain_lengths[2]/frac2;\n\n    //feature = 1% of data -> 1% of domain space\n    //value adjusted slightly so we find closer the correct amount of data\n    double frac3 = cbrt(125);\n    double med_x_length = domain_lengths[0]/frac3;\n    double med_y_length = domain_lengths[1]/frac3;\n    double med_z_length = domain_lengths[2]/frac3;\n\n    //feature = 10% of data -> 10% of domain space\n    //value adjusted significantly so we find closer the correct amount of data\n    double frac4 = cbrt(19.2);\n    double large_x_length = domain_lengths[0]/frac4;\n    double large_y_length = domain_lengths[1]/frac4;\n    double large_z_length = domain_lengths[2]/frac4;\n\n    std::vector<std::vector<double>> all_query_sizes = {\n        {extra_extra_small_x_length, extra_extra_small_y_length, extra_extra_small_z_length},\n        {small_x_length, small_y_length, small_z_length},\n        {med_x_length, med_y_length, med_z_length}\n        ,{large_x_length, large_y_length, large_z_length}\n    };\n    all_queries.resize(all_query_sizes.size());\n    std::vector<double> query_percent = {.001, .1, 1, 10};\n    queries_percent_data_covered = query_percent;\n\n    boost::mt19937 rng;\n    //want it to be reproducible\n    rng.seed(100);\n\n    boost::uniform_real<double> range_x(config.domain_lower_bounds[0], config.domain_upper_bounds[0]);\n    boost::uniform_real<double> range_y(config.domain_lower_bounds[1], config.domain_upper_bounds[1]);\n    boost::uniform_real<double> range_z(config.domain_lower_bounds[2], config.domain_upper_bounds[2]);\n\n    //separate them so the queries sets of a particular frequency are independent from the other frequencies\n    std::vector<std::vector<generator>> generators = {\n        {generator(rng, range_x), generator(rng, range_y), generator(rng, range_z)},\n        {generator(rng, range_x), generator(rng, range_y), generator(rng, range_z)},\n        {generator(rng, range_x), generator(rng, range_y), generator(rng, range_z)},\n        {generator(rng, range_x), generator(rng, range_y), generator(rng, range_z)}\n    };\n\n    //only do 1/10 as many queries of the extra large size to save time\n    std::vector<size_t> num_queries = {config.num_queries, config.num_queries, config.num_queries, config.num_queries/10};\n\n    if(DEBUG) {\n        std::cout << \"all_query_sizes.size(): \" << all_query_sizes.size() << std::endl;\n        cout << \"config.num_queries: \" << config.num_queries << endl;\n        cout << \"config.domain_lower_bounds.size(): \" << config.domain_lower_bounds.size() << endl;\n    }\n    for(size_t i = 0; i < all_query_sizes.size(); i++) {\n        for(size_t j = 0; j < num_queries[i]; j++) {\n            point query_lower_corner(config.domain_lower_bounds.size()), query_upper_corner(config.domain_lower_bounds.size());\n            for(size_t k = 0; k < config.domain_lower_bounds.size(); k++) {\n                query_lower_corner[k] = generators[i][k]();\n                double len = all_query_sizes[i][k];\n                while(query_lower_corner[k] + len > config.domain_upper_bounds[k]) {\n                    if(DEBUG) {\n                        std::cout << \"found an instance where pt exceeds bounds\" << std::endl;\n                        std::cout << \"query_lower_corner[\" << k << \"]: \" << query_lower_corner[k] << \", len: \" << len << \", domain_upper_bounds[\" << k << \"]: \" << config.domain_upper_bounds[k] << std::endl;                        \n                    }\n\n                    query_lower_corner[k] = generators[i][k]();\n                }\n                query_upper_corner[k] = query_lower_corner[k] + len;\n            }\n\n            all_queries[i].push_back(bbox(query_lower_corner, query_upper_corner));\n            if(DEBUG) {\n                std::cout << \"query: \";\n                print_bbox(all_queries[i].back());\n            }\n        }\n    }\n    if(DEBUG) {\n        std::cout << \"done with get_queries_specific_feature_sizes\" << std::endl;\n    }\n}\n\nvoid get_queries_random_feature_sizes(testing_config config, std::vector<bbox> &queries) {\n    boost::mt19937 rng;\n    //want it to be reproducible\n    rng.seed(100);\n    vector<double> domain_lengths;\n    for(size_t i = 0; i < config.domain_lower_bounds.size(); i++) {\n        domain_lengths.push_back(config.domain_upper_bounds[i]-config.domain_upper_bounds[i]);\n    }\n\n    boost::uniform_real<double> range_x(config.domain_lower_bounds[0], config.domain_upper_bounds[0]);\n    boost::uniform_real<double> range_y(config.domain_lower_bounds[1], config.domain_upper_bounds[1]);\n    boost::uniform_real<double> range_z(config.domain_lower_bounds[2], config.domain_upper_bounds[2]);\n    boost::uniform_real<double> range_x_length(domain_lengths[0]/1000, domain_lengths[0]/10);\n    boost::uniform_real<double> range_y_length(domain_lengths[1]/1000, domain_lengths[1]/10);\n    boost::uniform_real<double> range_z_length(domain_lengths[2]/1000, domain_lengths[2]/10);\n\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > rnd_x(rng, range_x);\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > rnd_y(rng, range_y);\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > rnd_z(rng, range_z);\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > rnd_length_x(rng, range_x_length);\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > rnd_length_y(rng, range_y_length);\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > rnd_length_z(rng, range_z_length);\n\n    for(size_t i = 0; i < config.num_queries; i++) {\n        double x = rnd_x();\n        double y = rnd_y();\n        double z = rnd_z();\n        double x_len = rnd_length_x();\n        double y_len = rnd_length_y();\n        double z_len = rnd_length_z();\n        queries.push_back(bbox(point({x, y, z}),point({x+x_len, y+y_len, z+z_len})));\n        if(DEBUG) {\n            std::cout << \"query: \";\n            print_bbox(queries.back());\n        }\n    }\n}\n\nvoid get_small_queries(std::vector<bbox> &queries) {\n    queries.push_back(std::make_pair(point({0,0,0}),point({1,1,1})));\n    queries.push_back(std::make_pair(point({.5,.5,.5}),point({1,1,1})));\n}\n\nvoid get_random_data(testing_config config, std::vector<point> &pts, std::vector<size_t> &indices) {\n    boost::mt19937 rng;\n    //want it to be reproducible\n    rng.seed(100);\n\n    vector<double> domain_lengths;\n    for(size_t i = 0; i < config.domain_lower_bounds.size(); i++) {\n        domain_lengths.push_back(config.domain_upper_bounds[i]-config.domain_upper_bounds[i]);\n    }\n    boost::uniform_real<double> range_x(config.domain_lower_bounds[0], config.domain_upper_bounds[0]);\n    boost::uniform_real<double> range_y(config.domain_lower_bounds[1], config.domain_upper_bounds[1]);\n    boost::uniform_real<double> range_z(config.domain_lower_bounds[2], config.domain_upper_bounds[2]);\n    boost::uniform_real<double> range_x_length(domain_lengths[0]/1000, domain_lengths[0]/10);\n    boost::uniform_real<double> range_y_length(domain_lengths[1]/1000, domain_lengths[1]/10);\n    boost::uniform_real<double> range_z_length(domain_lengths[2]/1000, domain_lengths[2]/10);\n\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > rnd_x(rng, range_x);\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > rnd_y(rng, range_y);\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > rnd_z(rng, range_z);\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > rnd_length_x(rng, range_x_length);\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > rnd_length_y(rng, range_y_length);\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > rnd_length_z(rng, range_z_length);\n\n    if(DEBUG) {\n        std::cout << \"about to make points\" << std::endl;\n    }\n\n    if(config.data_type == POINTS) {\n        for(size_t i = 0; i < config.num_data_pts; i++) {\n            double x = rnd_x();\n            double y = rnd_y();\n            double z = rnd_z();\n            pts.push_back(point({x, y, z}));\n            indices.push_back(i);\n\n            if(DEBUG) {\n                if(i < 100) {\n                    std::cout << \"pt: \";\n                    print_point(pts.back());\n                }\n            }\n        }        \n    }\n    else if(config.data_type == BBOXES) {\n        for(size_t i = 0; i < config.num_data_pts; i++) {\n            double x = rnd_x();\n            double y = rnd_y();\n            double z = rnd_z();\n            double x_len = rnd_length_x();\n            double y_len = rnd_length_y();\n            double z_len = rnd_length_z();\n            pts.push_back(point({x, y, z}));\n            pts.push_back(point({x+x_len, y+y_len, z+z_len}));\n            indices.push_back(i);\n            if(DEBUG) {\n                if(i < 100) {\n                    std::cout << \"box: \";\n                    print_bbox(bbox(pts[pts.size()-2], pts.back()));\n                }\n            }\n        }        \n    }\n    else if(config.data_type == TRIANGLES) {\n        for(size_t i = 0; i < config.num_data_pts; i++) {\n            double x = rnd_x();\n            double y = rnd_y();\n            double z = rnd_z();\n            double x_len = rnd_length_x();\n            double y_len = rnd_length_y();\n            double z_len = rnd_length_z();\n            double x_len2 = rnd_length_x();\n            double y_len2 = rnd_length_y();\n            double z_len2 = rnd_length_z();\n            pts.push_back(point({x, y, z}));\n            pts.push_back(point({x+x_len, y+y_len, z+z_len}));\n            pts.push_back(point({x+x_len2, y+y_len2, z+z_len2}));\n            indices.push_back(i);\n            if(DEBUG) {\n                if(i < 100) {\n                    std::cout << \"triangle: \" << std::endl;\n                    print_point(pts[pts.size()-3]);\n                    print_point(pts[pts.size()-2]);\n                    print_point(pts[pts.size()-1]);\n                }\n            }\n        }\n    }\n    else {\n        std::cerr << \"Error in get_random_data. The config.data_type of \" << config.data_type << \" did not match one of the expected categories\" << std::endl;\n    }\n    if(DEBUG) {\n        std::cout << \"done with make points\" << std::endl;        \n    }\n}\n\nvoid get_regular_mesh_data(testing_config config, std::vector<point> &pts, std::vector<size_t> &indices) {\n    if(DEBUG) {\n        std::cout << \"about to make points\" << std::endl;\n    }\n    if(config.data_type == POINTS) {\n        size_t index = 0;\n        for(double i = 0; i < DOMAIN_LENGTH; i++) {\n            for(double j = 0; j < DOMAIN_LENGTH; j++) {\n                for(double k = 0; k < DOMAIN_LENGTH; k++) {\n                    pts.push_back({i, j, k});\n                    indices.push_back(index);\n                    index += 1;   \n                }\n            }\n        }\n    }\n    else if(config.data_type == BBOXES) {\n        size_t index = 0;\n        for(double i = 0; i < std::floor(DOMAIN_LENGTH/2); i++) {\n            for(double j = 0; j < std::floor(DOMAIN_LENGTH/2); j++) {\n                for(double k = 0; k < std::floor(DOMAIN_LENGTH/2); k++) {\n                    pts.push_back({i, j, k});\n                    pts.push_back({i+1, j+1, k+1});\n                    indices.push_back(index);   \n                    index += 1;\n                }\n            }\n        }\n    }\n    else if(config.data_type == TRIANGLES) {\n        std::vector<point> temp;\n        for(double i = 0; i < DOMAIN_LENGTH; i++) {\n            for(double j = 0; j < DOMAIN_LENGTH; j++) {\n                for(double k = 0; k < DOMAIN_LENGTH; k++) {\n                     temp.push_back({i, j, k});        \n                }\n            }\n        } \n        for(int i = 0; i < (temp.size()/3); i++) {\n            pts.push_back(temp[i]);\n            pts.push_back(temp[i+DOMAIN_LENGTH]);\n            pts.push_back(temp[i+DOMAIN_LENGTH*DOMAIN_LENGTH]);\n            indices.push_back(i);\n        }                \n    }\n    if(DEBUG) {\n        std::cout << \"done with make points\" << std::endl;\n    }\n}\n\nint exodus_open_file(std::string file_name) {\n    int error, exodus_id = -1;\n    //size of the reals as used by the cpu and as stored\n    int cpu_word_size = 8;\n    int io_word_size = 0;\n    float database_version;\n    int retry_count = 0;\n    while(exodus_id < 0 && retry_count < 100) {\n        exodus_id = ex_open (file_name.c_str(), EX_READ, &cpu_word_size, &io_word_size, &database_version);\n        retry_count += 1;\n        //sleep just in case there is file system contention\n        std::this_thread::sleep_for(1000ms);\n    }\n    if(exodus_id < 0) {\n        std::cerr << \"error in ex_open\" << std::endl;\n        exit(-1);\n    }\n\n    return exodus_id;\n\n}\n\nvoid exodus_read_vertex_coordinates(int exodus_id, vector<double> &x_coords, vector<double> &y_coords, vector<double> &z_coords) {\n    int num_dim , num_nodes, num_elem, num_elem_blocks, num_node_sets, num_side_sets;\n    char  db_title[MAX_STR_LENGTH];\n    if(ex_get_init (exodus_id, db_title, &num_dim, &num_nodes, &num_elem, &num_elem_blocks, &num_node_sets, &num_side_sets)) {\n        std::cerr << \"error in ex_get_init\" << std::endl;\n        exit(-1);        \n    }\n\n    x_coords.resize(num_nodes);\n    y_coords.resize(num_nodes);\n    z_coords.resize(num_nodes); \n    if(ex_get_coord(exodus_id , &x_coords[0], &y_coords[0], &z_coords[0])) {\n        std::cerr << \"error in ex_get_coord\" << std::endl;\n        exit(-1);          \n    }\n}\n\n\nvoid exodus_read_vertex_coordinates(int exodus_id, std::vector<point> &coords, bbox &domain_bounds, uint32_t &num_nodes) {\n    double domain_lower_bounds[3] = {DBL_MAX, DBL_MAX, DBL_MAX};\n    double domain_upper_bounds[3] = {-DBL_MAX, -DBL_MAX, -DBL_MAX};\n\n    int num_dim, num_elem, num_elem_blocks, num_node_sets, num_side_sets;\n    char  db_title[MAX_STR_LENGTH];\n    if(ex_get_init (exodus_id, db_title, &num_dim, &num_nodes, &num_elem, &num_elem_blocks, &num_node_sets, &num_side_sets)) {\n        std::cerr << \"error in ex_get_init\" << std::endl;\n        exit(-1);             \n    }\n\n    vector<double> x_coords, y_coords, z_coords;\n    x_coords.resize(num_nodes);\n    y_coords.resize(num_nodes);\n    z_coords.resize(num_nodes); \n    if(ex_get_coord(exodus_id , &x_coords[0], &y_coords[0], &z_coords[0])) {\n        std::cerr << \"error in ex_get_coord\" << std::endl;\n        exit(-1);     \n    }\n\n    for(int i = 0; i < num_nodes; i++) {\n        coords.push_back(point({x_coords[i], y_coords[i], z_coords[i]}));\n\n        domain_lower_bounds[0] = std::min(domain_lower_bounds[0], x_coords[i]);\n        domain_upper_bounds[0] = std::max(domain_upper_bounds[0], x_coords[i]);\n        domain_lower_bounds[1] = std::min(domain_lower_bounds[1], y_coords[i]);\n        domain_upper_bounds[1] = std::max(domain_upper_bounds[1], y_coords[i]);\n        domain_lower_bounds[2] = std::min(domain_lower_bounds[2], z_coords[i]);\n        domain_upper_bounds[2] = std::max(domain_upper_bounds[2], z_coords[i]);\n    }\n\n\n    domain_bounds = bbox(point({domain_lower_bounds[0], domain_lower_bounds[1], domain_lower_bounds[2]}), \n                         point({domain_upper_bounds[0], domain_upper_bounds[1], domain_upper_bounds[2]})\n                    );\n}\n\n\nvoid exodus_read_vertex_coordinates(const std::string &full_file_path, std::vector<point> &coords, bbox &domain_bounds, uint32_t &num_nodes) {\n    int exodus_id = exodus_open_file(full_file_path);\n    exodus_read_vertex_coordinates(exodus_id, coords, domain_bounds, num_nodes);\n    ex_close (exodus_id);\n}\n\n\nvoid exodus_get_element_connectivity(int exodus_id, int elem_block_id, vector<uint32_t> &node_connectivity, uint32_t &num_nodes_per_elem) {\n    int error, num_elem_in_block, num_edges_per_elem, num_faces_per_elem, num_attr_per_elem;\n    char elem_description[MAX_STR_LENGTH +1];\n\n    if(ex_get_block(exodus_id, EX_ELEM_BLOCK, elem_block_id, elem_description, &num_elem_in_block, &num_nodes_per_elem, &num_edges_per_elem, &num_faces_per_elem, &num_attr_per_elem)) {\n        cerr << \"error with ex_get_block\" << endl;\n        exit(-1);\n    }\n    else {\n        if(num_elem_in_block > 0) {\n            /* read  element  connectivity  */\n            int *edge_connectivity = (int *)  calloc(num_edges_per_elem*num_elem_in_block ,sizeof(int ));\n            int *face_connectivity = (int *)  calloc(num_faces_per_elem*num_elem_in_block ,sizeof(int ));\n            node_connectivity.resize(num_nodes_per_elem*num_elem_in_block);\n\n            if(ex_get_conn(exodus_id, EX_ELEM_BLOCK, elem_block_id, &node_connectivity[0], edge_connectivity, face_connectivity)) {\n                cerr << \"error with ex_get_conn, error: \" << error << endl;\n                exit(-1);\n            }\n\n            free(edge_connectivity);\n            free(face_connectivity);    \n        }  \n    }\n}\n\nvoid exodus_read_element_bboxes(const std::string &full_file_path, std::vector<point> &element_bboxes_as_pts, bbox &domain_bounds,\n    uint32_t &num_nodes, vector<vector<size_t>> &node_ids_per_elem) \n{\n    double domain_lower_bounds[3] = {DBL_MAX, DBL_MAX, DBL_MAX};\n    double domain_upper_bounds[3] = {-DBL_MAX, -DBL_MAX, -DBL_MAX};\n\n    int exodus_id = exodus_open_file(full_file_path);\n\n    int num_dim, num_elem, num_elem_blocks, num_node_sets, num_side_sets;\n    char  db_title[MAX_STR_LENGTH];\n    if(ex_get_init (exodus_id, db_title, &num_dim, &num_nodes, &num_elem, &num_elem_blocks, &num_node_sets, &num_side_sets)) {\n        std::cerr << \"Error with ex_get_init\" << std::endl;\n        exit(-1);\n    }\n    if(!RETRIEVE_NODES_FOR_BBOXES) {\n        num_nodes = num_elem; //want to keep track of the number of bounding boxes, not the number of nodes\n    }\n\n    vector<vector<uint32_t>> connectivity_lists(num_elem_blocks);\n    uint32_t num_nodes_per_elem[num_elem_blocks];\n\n    /* read in the ids for the element blocks */\n    vector<int> elem_block_ids(num_elem_blocks);\n\n    if(ex_get_ids (exodus_id, EX_ELEM_BLOCK, &elem_block_ids[0] )) {\n        std::cerr << \"error with ex_get_ids\" << std::endl;\n        exit(-1);\n    }\n\n    for(size_t i = 0; i < num_elem_blocks; i++) {\n        int elem_block_id = elem_block_ids[i];\n        exodus_get_element_connectivity(exodus_id, elem_block_id, connectivity_lists[i], num_nodes_per_elem[i]);\n    }\n\n    element_bboxes_as_pts.reserve(num_elem);\n    vector<double> x_coords, y_coords, z_coords;\n    exodus_read_vertex_coordinates(exodus_id, x_coords, y_coords, z_coords);\n    ex_close (exodus_id);\n\n    for(size_t i = 0; i < connectivity_lists.size(); i++) {\n        size_t elem_size = num_nodes_per_elem[i];\n        // cout << \"new elem\" << endl;\n        for(size_t j = 0; j < connectivity_lists[i].size(); j += elem_size) {\n            double mins[3] = {DBL_MAX, DBL_MAX, DBL_MAX};\n            double maxes[3] = {-DBL_MAX, -DBL_MAX, -DBL_MAX};\n            vector<size_t> node_ids;\n            for(size_t k = 0; k < elem_size; k++) {\n                size_t node_id = connectivity_lists[i][j+k]-1; //node_ids start at 1 instead of 0\n                node_ids.push_back(node_id);\n                mins[0] = std::min(mins[0], x_coords[node_id]);\n                maxes[0] = std::max(maxes[0], x_coords[node_id]);\n                mins[1] = std::min(mins[1], y_coords[node_id]);\n                maxes[1] = std::max(maxes[1], y_coords[node_id]);\n                mins[2] = std::min(mins[2], z_coords[node_id]);\n                maxes[2] = std::max(maxes[2], z_coords[node_id]);\n            }\n            node_ids_per_elem.push_back(node_ids);\n            element_bboxes_as_pts.push_back(point({mins[0], mins[1], mins[2]}));\n            element_bboxes_as_pts.push_back(point({maxes[0], maxes[1], maxes[2]}));\n            domain_lower_bounds[0] = std::min(domain_lower_bounds[0], mins[0]);\n            domain_upper_bounds[0] = std::max(domain_upper_bounds[0], maxes[0]);\n            domain_lower_bounds[1] = std::min(domain_lower_bounds[1], mins[1]);\n            domain_upper_bounds[1] = std::max(domain_upper_bounds[1], maxes[1]);\n            domain_lower_bounds[2] = std::min(domain_lower_bounds[2], mins[2]);\n            domain_upper_bounds[2] = std::max(domain_upper_bounds[2], maxes[2]);\n        }\n    }    \n    domain_bounds = bbox(point({domain_lower_bounds[0], domain_lower_bounds[1], domain_lower_bounds[2]}), \n                         point({domain_upper_bounds[0], domain_upper_bounds[1], domain_upper_bounds[2]})\n                    );\n\n}\n\n\nvoid get_data_from_exodus_file(DataType data_type, const std::string &full_file_path, std::vector<point> &mesh_coords, \n    bbox &domain_bounds, uint32_t &num_data_pts) \n{\n    exodus_read_vertex_coordinates(full_file_path, mesh_coords, domain_bounds, num_data_pts);\n}\n\nvoid get_data_from_exodus_file(DataType data_type, const std::string &full_file_path, std::vector<point> &mesh_coords, bbox &domain_bounds,\n    uint32_t &num_data_pts, vector<vector<size_t>> &node_ids_per_elem) \n{\n    exodus_read_element_bboxes(full_file_path, mesh_coords, domain_bounds, num_data_pts, node_ids_per_elem);\n}\n\n\n", "meta": {"hexsha": "4cbc20570e86d847557b07e403837553c77744e5", "size": 22635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/benchmark/data_and_query_generation.cpp", "max_stars_repo_name": "mlawsonca/benchmarking_suite_range_searching_libraries", "max_stars_repo_head_hexsha": "85f2e6be47633836e56684636851eeb393c46d7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-07T18:46:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T18:46:56.000Z", "max_issues_repo_path": "src/benchmark/data_and_query_generation.cpp", "max_issues_repo_name": "mlawsonca/benchmarking_suite_range_searching_libraries", "max_issues_repo_head_hexsha": "85f2e6be47633836e56684636851eeb393c46d7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/benchmark/data_and_query_generation.cpp", "max_forks_repo_name": "mlawsonca/benchmarking_suite_range_searching_libraries", "max_forks_repo_head_hexsha": "85f2e6be47633836e56684636851eeb393c46d7d", "max_forks_repo_licenses": ["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.0, "max_line_length": 230, "alphanum_fraction": 0.6279213607, "num_tokens": 5750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.500265742793487}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// pdf.hpp                                                                   //\n//                                                                           //\n//  Copyright 2010 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_NON_PARAMETRIC_EMPIRICAL_DISTRIBUTION_PDF_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_EMPIRICAL_DISTRIBUTION_PDF_HPP_ER_2010\n#include <boost/range.hpp>\n#include <boost/numeric/conversion/converter.hpp>\n\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/parameters/accumulator.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n\n#include <boost/statistics/detail/non_parametric/empirical_distribution/count.hpp>\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace empirical_distribution{\nnamespace impl{\n\n    // T can be an integer or a float\n    template<typename T,typename T1>\n\tclass pdf : public boost::accumulators::accumulator_base\n    {\n        typedef boost::accumulators::dont_care dont_care_;\n\n        public:\n\n        typedef T1 result_type;\n        typedef T sample_type;\n\n        pdf(dont_care_){}\n\n        void operator()(dont_care_){}\n\t\t\n        template<typename Args>\n        result_type result(const Args& args)const{\n            typedef std::size_t size_;\n            namespace ns = empirical_distribution;\n            namespace ac = boost::accumulators;\n            size_ i =  ns::extract::count( \n                args[ac::accumulator], \n                args[ ac::sample ] \n            );\n            size_ n = ac::extract::count( args[ ac::accumulator ] );\n            typedef boost::numeric::converter<T1,size_> converter_;\n            return converter_::convert( i ) / converter_::convert( n );\n        }\n\n    };\n    \n}// impl\nnamespace tag\n{\n    template<typename T1>\n    struct pdf: boost::accumulators::depends_on<\n        empirical_distribution::tag::count,\n        accumulators::tag::count\n    >\n    {\n        struct impl{\n            template<typename T,typename W>\n            struct apply{\n                typedef empirical_distribution::impl::pdf<T,T1> type;\n            };\n        };\n    };\n}// tag\nnamespace result_of{\n\n    template<typename T1,typename AccSet>\n    struct pdf{\n    \ttypedef empirical_distribution::tag::pdf<T1> tag_;\n        typedef typename\n            boost::accumulators::detail::template \n            \textractor_result<AccSet,tag_>::type type; \n    };\n\n}// result_of\nnamespace extract\n{\n\n    template<typename T1,typename AccSet,typename T>\n    typename detail::empirical_distribution\n        ::result_of::template pdf<T1,AccSet>::type\n  \tpdf(AccSet const& acc,const T& x)\n    { \n        namespace ac = boost::accumulators;\n        namespace ns = detail::empirical_distribution;\n    \ttypedef ns::tag::pdf<T1> tag_;\n        return ac::extract_result<tag_>( acc, ( ac::sample = x ) );\n  \t}\n\n}// extract\n}// empirical_distribution\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "10891fb3ea0200501623e92b75e011bfa1fe9d04", "size": 3477, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/empirical_distribution/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": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/empirical_distribution/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": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/empirical_distribution/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": 32.1944444444, "max_line_length": 85, "alphanum_fraction": 0.6028185217, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.500265738372116}}
{"text": "#pragma once\r\n#ifndef CELL_LIST_HPP\r\n#define CELL_LIST_HPP\r\n\r\n//c++ libraries\r\n#include <iosfwd>\r\n// eigen libraries\r\n#include <Eigen/Dense>\r\n// ann - structure\r\n#include \"src/struc/structure_fwd.hpp\"\r\n\r\nclass CellList{\r\nprivate:\r\n\tint natoms_; //number of atoms\r\n\tstd::vector<Eigen::Vector3i> cell_;//cell of atom - natoms\r\n\tint dim_[3];//dimension of the cell list\r\n\tdouble flen_[3];//fractional length of the cell lists\r\n\tstd::vector<std::vector<int> > atoms_;//the atoms in each cell - dim^3\r\npublic:\r\n\t//==== constructors/destructors ====\r\n\tCellList(){defaults();}\r\n\tCellList(double rc, const Structure& struc){compute(rc,struc);}\r\n\t~CellList(){}\r\n\t\r\n\t//==== operators ====\r\n\tfriend std::ostream& operator<<(std::ostream& out, const CellList& cellList);\r\n\t\r\n\t//==== access ====\r\n\tint dim(int i)const{return dim_[i];}\r\n\tdouble flen(int i)const{return flen_[i];}\r\n\tconst Eigen::Vector3i& cell(int i)const{return cell_[i];}\r\n\tconst std::vector<int>& atoms(int i, int j, int k)const;\r\n\tconst std::vector<int>& atoms(const Eigen::Vector3i& i)const;\r\n\t\r\n\t//==== member functions ====\r\n\tvoid defaults();\r\n\tvoid clear(){defaults();}\r\n\tint index(int i, int j, int k)const;\r\n\tvoid compute(double rc, const Structure& struc);\r\n};\r\n\r\n#endif", "meta": {"hexsha": "77fb003364ad8565eaac084620ec481bafafbd0f", "size": 1233, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/struc/cell_list.hpp", "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/struc/cell_list.hpp", "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/struc/cell_list.hpp", "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": 29.3571428571, "max_line_length": 79, "alphanum_fraction": 0.6682887267, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5002657373819498}}
{"text": "// Copyright 2008-2010 Gordon Woodhull\n// Distributed under the Boost Software License, Version 1.0. \n// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/msm/mpl_graph/breadth_first_search.hpp>\n#include <boost/msm/mpl_graph/adjacency_list_graph.hpp>\n#include <boost/msm/mpl_graph/incidence_list_graph.hpp>\n\n#include <iostream>\n\nnamespace mpl_graph = boost::msm::mpl_graph;\nnamespace mpl = boost::mpl;\n\n// vertices\nstruct A{}; struct B{}; struct C{}; struct D{}; struct E{}; struct F{}; struct G{};\n\n// edges\nstruct A_B{}; struct B_C{}; struct C_D{}; struct C_E{}; struct C_F{}; struct B_F{};\n\n\n\n/* \n    incidence list test graph:\n    A -> B -> C -\\--> D\n           \\     |--> E\n            \\    \\--> F\n             \\-----/\n*/           \n\ntypedef mpl::vector<mpl::vector<A_B,A,B>,\n               mpl::vector<B_C,B,C>,\n               mpl::vector<C_D,C,D>,\n               mpl::vector<C_E,C,E>,\n               mpl::vector<C_F,C,F>,\n               mpl::vector<B_F,B,F> >\n    some_incidence_list;\ntypedef mpl_graph::incidence_list_graph<some_incidence_list> some_incidence_list_graph;\n\n\n\n/* \n    adjacency list test graph:\n    A -> B -> C -\\--> D\n           \\     |--> E\n            \\    \\--> F\n             \\-----/\n    G\n*/           \n\ntypedef mpl::vector<\n            mpl::pair<A, mpl::vector<mpl::pair<A_B, B> > >,\n            mpl::pair<B, mpl::vector<mpl::pair<B_C, C>,\n                                     mpl::pair<B_F, F> > >,\n            mpl::pair<C, mpl::vector<mpl::pair<C_D, D>,\n                                     mpl::pair<C_E, E>,\n                                     mpl::pair<C_F, F> > >,\n            mpl::pair<G, mpl::vector<> > >\n    some_adjacency_list;\ntypedef mpl_graph::adjacency_list_graph<some_adjacency_list> some_adjacency_list_graph;\n\n\nstruct preordering_visitor : mpl_graph::bfs_default_visitor_operations {    \n    template<typename Vertex, typename Graph, typename State>\n    struct discover_vertex :\n        mpl::push_back<State, Vertex>\n    {};\n};\n\nstruct postordering_visitor : mpl_graph::bfs_default_visitor_operations {    \n    template<typename Vertex, typename Graph, typename State>\n    struct finish_vertex :\n        mpl::push_back<State, Vertex>\n    {};\n};\n\nstruct examine_edge_visitor : mpl_graph::bfs_default_visitor_operations {    \n    template<typename Edge, typename Graph, typename State>\n    struct examine_edge :\n        mpl::push_back<State, Edge>\n    {};\n};\n\nstruct tree_edge_visitor : mpl_graph::bfs_default_visitor_operations {    \n    template<typename Edge, typename Graph, typename State>\n    struct tree_edge :\n        mpl::push_back<State, Edge>\n    {};\n};\n  \n// adjacency list tests\n\n// preordering, start from A\ntypedef mpl::first<mpl_graph::\n    breadth_first_search<some_adjacency_list_graph, \n                         preordering_visitor, \n                         mpl::vector<>, \n                         A>::type>::type \n                preorder_adj_a;\nBOOST_MPL_ASSERT(( mpl::equal<preorder_adj_a::type, mpl::vector<A,B,C,F,D,E> > ));\n\n// examine edges, start from A\ntypedef mpl::first<mpl_graph::\n    breadth_first_search<some_adjacency_list_graph, \n                         examine_edge_visitor,\n                         mpl::vector<>,\n                         A>::type>::type \n                ex_edges_adj_a;\nBOOST_MPL_ASSERT(( mpl::equal<ex_edges_adj_a::type, mpl::vector<A_B,B_C,B_F,C_D,C_E,C_F> > ));\n\n// tree edges, start from A\ntypedef mpl::first<mpl_graph::\n    breadth_first_search<some_adjacency_list_graph, \n                         tree_edge_visitor, \n                         mpl::vector<>,\n                         A>::type>::type \n                tree_edges_adj_a;\nBOOST_MPL_ASSERT(( mpl::equal<tree_edges_adj_a::type, mpl::vector<A_B,B_C,B_F,C_D,C_E> > ));\n\n// preordering, search all, default start node (first)\ntypedef mpl::first<mpl_graph::\n    breadth_first_search_all<some_adjacency_list_graph,\n                             preordering_visitor, \n                             mpl::vector<> >::type>::type \n                preorder_adj;\nBOOST_MPL_ASSERT(( mpl::equal<preorder_adj::type, mpl::vector<A,B,C,F,D,E,G> > ));\n\n// postordering, starting at A (same as preordering because BFS fully processes one vertex b4 moving to next)\ntypedef mpl::first<mpl_graph::\n    breadth_first_search<some_adjacency_list_graph,\n                         postordering_visitor,\n                         mpl::vector<>,\n                         A>::type>::type \n                postorder_adj_a;\nBOOST_MPL_ASSERT(( mpl::equal<postorder_adj_a::type, mpl::vector<A,B,C,F,D,E> > ));\n\n// postordering, default start node (same as preordering because BFS fully processes one vertex b4 moving to next)\ntypedef mpl::first<mpl_graph::\n    breadth_first_search_all<some_adjacency_list_graph,\n                             postordering_visitor,\n                             mpl::vector<> >::type>::type \n                postorder_adj;\nBOOST_MPL_ASSERT(( mpl::equal<postorder_adj::type, mpl::vector<A,B,C,F,D,E,G> > ));\n\n// preordering starting at C\ntypedef mpl::first<mpl_graph::\n    breadth_first_search<some_adjacency_list_graph,\n                         preordering_visitor, \n                         mpl::vector<>,\n                         C>::type>::type \n                preorder_adj_from_c;\nBOOST_MPL_ASSERT(( mpl::equal<preorder_adj_from_c::type, mpl::vector<C,D,E,F> > ));\n\n// preordering, search all, starting at C\ntypedef mpl::first<mpl_graph::\n    breadth_first_search_all<some_adjacency_list_graph,\n                             preordering_visitor,\n                             mpl::vector<>,\n                             C>::type>::type \n                preorder_adj_from_c_all;\nBOOST_MPL_ASSERT(( mpl::equal<preorder_adj_from_c_all::type, mpl::vector<C,D,E,F,A,B,G> > ));\n\n\n// incidence list tests\n\n// preordering, start from A\ntypedef mpl::first<mpl_graph::\n    breadth_first_search<some_incidence_list_graph, \n                         preordering_visitor, \n                         mpl::vector<>,\n                         A>::type>::type \n                preorder_inc_a;\nBOOST_MPL_ASSERT(( mpl::equal<preorder_inc_a::type, mpl::vector<A,B,C,F,D,E> > ));\n\n// preordering, start from C\ntypedef mpl::first<mpl_graph::\n    breadth_first_search<some_incidence_list_graph, \n                         preordering_visitor, \n                         mpl::vector<>,\n                         C>::type>::type \n                preorder_inc_c;\nBOOST_MPL_ASSERT(( mpl::equal<preorder_inc_c::type, mpl::vector<C,D,E,F> > ));\n\n// preordering, default start node (first)\ntypedef mpl::first<mpl_graph::\n    breadth_first_search_all<some_incidence_list_graph,\n                             preordering_visitor,\n                             mpl::vector<> >::type>::type \n                preorder_inc;\nBOOST_MPL_ASSERT(( mpl::equal<preorder_inc::type, mpl::vector<A,B,C,F,D,E> > ));\n\n// postordering, default start node\ntypedef mpl::first<mpl_graph::\n    breadth_first_search_all<some_incidence_list_graph,\n                             postordering_visitor,\n                             mpl::vector<> >::type>::type \n                postorder_inc;\nBOOST_MPL_ASSERT(( mpl::equal<postorder_inc::type, mpl::vector<A,B,C,F,D,E> > ));\n\n// preordering, search all, starting at C\ntypedef mpl::first<mpl_graph::\n    breadth_first_search_all<some_incidence_list_graph,\n                             preordering_visitor,\n                             mpl::vector<>,\n                             C>::type>::type \n                preorder_inc_from_c;\nBOOST_MPL_ASSERT(( mpl::equal<preorder_inc_from_c::type, mpl::vector<C,D,E,F,A,B> > ));\n\n\nint main() {\n    return 0;\n}", "meta": {"hexsha": "3b73651ff71e8f3dc93cdee57185bba618fa796e", "size": 7654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/msm/example/mpl_graph/breadth_first_search.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/msm/example/mpl_graph/breadth_first_search.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/msm/example/mpl_graph/breadth_first_search.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": 36.2748815166, "max_line_length": 114, "alphanum_fraction": 0.5851842174, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.5002634051935011}}
{"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_CCMATH_CEIL_HPP\n#define BOOST_MATH_CCMATH_CEIL_HPP\n\n#include <cmath>\n#include <type_traits>\n#include <boost/math/tools/is_constant_evaluated.hpp>\n#include <boost/math/ccmath/floor.hpp>\n#include <boost/math/ccmath/abs.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n\nnamespace boost::math::ccmath {\n\nnamespace detail {\n\ntemplate <typename T>\ninline constexpr T ceil_impl(T arg) noexcept\n{\n    T result = boost::math::ccmath::floor(arg);\n\n    if(result == arg)\n    {\n        return result;\n    }\n    else\n    {\n        return result + 1;\n    }\n}\n\n} // Namespace detail\n\ntemplate <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>\ninline constexpr Real ceil(Real arg) noexcept\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(arg))\n    {\n        return boost::math::ccmath::abs(arg) == Real(0) ? arg :\n               boost::math::ccmath::isinf(arg) ? arg :\n               boost::math::ccmath::isnan(arg) ? arg :\n               boost::math::ccmath::detail::ceil_impl(arg);\n    }\n    else\n    {\n        using std::ceil;\n        return ceil(arg);\n    }\n}\n\ntemplate <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>\ninline constexpr double ceil(Z arg) noexcept\n{\n    return boost::math::ccmath::ceil(static_cast<double>(arg));\n}\n\ninline constexpr float ceilf(float arg) noexcept\n{\n    return boost::math::ccmath::ceil(arg);\n}\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline constexpr long double ceill(long double arg) noexcept\n{\n    return boost::math::ccmath::ceil(arg);\n}\n#endif\n\n} // Namespaces\n\n#endif // BOOST_MATH_CCMATH_CEIL_HPP\n", "meta": {"hexsha": "34ab2bb6b376d456167348492e7be81f931ce005", "size": 1855, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/ccmath/ceil.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/ccmath/ceil.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/ccmath/ceil.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": 24.4078947368, "max_line_length": 82, "alphanum_fraction": 0.6835579515, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5002633915009712}}
{"text": "#include <exception>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <boost/program_options.hpp>\n\n#include <nit/eval/card.h>\n#include <nit/eval/card_set.h>\n#include <nit/util/combinations.h>\n\n#include \"guard.h\"\n\nnamespace po = boost::program_options;\n\nnamespace {\n\nint runColex(int argc, char** argv) {\n  // set up the program options, handle the help case, and extract the values.\n  po::options_description desc(\n      \"nit-colex, a utility which prints all combinations \"\n      \"of poker hands, using canonical suits, or only ranks\");\n\n  // clang-format off\n  desc.add_options()\n      (\"help,?\", \"produce help message\")\n      (\"num-cards,n\", po::value<std::size_t>()->default_value(2),\n       \"number of cards in hands\")\n      (\"ranks\", \"print the set of rank values\");\n  // clang-format on\n\n  po::variables_map vm;\n  try {\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n  } catch (const std::exception& err) {\n    std::cerr << \"Option error: \" << err.what() << \"\\n\\n\" << desc << std::endl;\n    return 1;\n  }\n  po::notify(vm);\n\n  // check for help\n  if (vm.count(\"help\") || argc == 1) {\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  // extract the options\n  std::size_t num_cards = vm[\"num-cards\"].as<std::size_t>();\n\n  std::set<nit::CardSet> canonicalHands;\n  std::map<std::string, std::size_t> rankHands;\n  nit::combinations cards(52, num_cards);\n  do {\n    nit::CardSet hand;\n    for (std::size_t i = 0; i < num_cards; i++) {\n      hand.insert(nit::Card(cards[i]));\n    }\n    canonicalHands.insert(hand.canonize());\n    rankHands[hand.rankstr()] = hand.rankColex();\n  } while (cards.next());\n\n  if (vm.count(\"ranks\") > 0) {\n    for (auto& rankHand : rankHands)\n      std::cout << rankHand.first << \": \" << rankHand.second << '\\n';\n  } else {\n    for (const auto& canonicalHand : canonicalHands) {\n      std::cout << canonicalHand.str() << \": \" << canonicalHand.colex() << '\\n';\n    }\n  }\n\n  return 0;\n}\n\n}  // namespace\n\nint main(int argc, char** argv) {\n  return guard([&argc, &argv] { return runColex(argc, argv); });\n}\n", "meta": {"hexsha": "ef76cf69cefbf4f3558e43a09ecc868183ef5508", "size": 2070, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cli/nit-colex.cc", "max_stars_repo_name": "rakhimov/nit", "max_stars_repo_head_hexsha": "2f87132c2fa8cc7c4c62f7b55f5e2e340708bede", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-06-04T23:37:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-22T21:59:53.000Z", "max_issues_repo_path": "cli/nit-colex.cc", "max_issues_repo_name": "jaimindarji88/nit", "max_issues_repo_head_hexsha": "efb0cb8e221a2a0837ec074150955ac5b769d0dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-06-01T06:50:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-04T00:37:25.000Z", "max_forks_repo_path": "cli/nit-colex.cc", "max_forks_repo_name": "jaimindarji88/nit", "max_forks_repo_head_hexsha": "efb0cb8e221a2a0837ec074150955ac5b769d0dc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-27T17:29:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T20:04:42.000Z", "avg_line_length": 26.2025316456, "max_line_length": 80, "alphanum_fraction": 0.6183574879, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5002633874992971}}
{"text": "//  (C) Copyright John Maddock 2008.\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_TR1_CMATH_HPP_INCLUDED\n#  define BOOST_TR1_CMATH_HPP_INCLUDED\n#  include <boost/tr1/detail/config.hpp>\n\n#ifdef BOOST_HAS_TR1_CMATH\n\n#  if defined(BOOST_HAS_INCLUDE_NEXT) && !defined(BOOST_TR1_DISABLE_INCLUDE_NEXT)\n#     include_next BOOST_TR1_HEADER(cmath)\n#  else\n#     include <boost/tr1/detail/config_all.hpp>\n#     include BOOST_TR1_HEADER(cmath)\n#  endif\n\n#else\n\n#include <boost/math/tr1.hpp>\n\nnamespace std{ namespace tr1{\n\nusing boost::math::tr1::assoc_laguerre;\nusing boost::math::tr1::assoc_laguerref;\nusing boost::math::tr1::assoc_laguerrel;\n// [5.2.1.2] associated Legendre functions:\nusing boost::math::tr1::assoc_legendre;\nusing boost::math::tr1::assoc_legendref;\nusing boost::math::tr1::assoc_legendrel;\n// [5.2.1.3] beta function:\nusing boost::math::tr1::beta;\nusing boost::math::tr1::betaf;\nusing boost::math::tr1::betal;\n// [5.2.1.4] (complete) elliptic integral of the first kind:\nusing boost::math::tr1::comp_ellint_1;\nusing boost::math::tr1::comp_ellint_1f;\nusing boost::math::tr1::comp_ellint_1l;\n// [5.2.1.5] (complete) elliptic integral of the second kind:\nusing boost::math::tr1::comp_ellint_2;\nusing boost::math::tr1::comp_ellint_2f;\nusing boost::math::tr1::comp_ellint_2l;\n// [5.2.1.6] (complete) elliptic integral of the third kind:\nusing boost::math::tr1::comp_ellint_3;\nusing boost::math::tr1::comp_ellint_3f;\nusing boost::math::tr1::comp_ellint_3l;\n#if 0\n// [5.2.1.7] confluent hypergeometric functions:\nusing boost::math::tr1::conf_hyperg;\nusing boost::math::tr1::conf_hypergf;\nusing boost::math::tr1::conf_hypergl;\n#endif\n// [5.2.1.8] regular modified cylindrical Bessel functions:\nusing boost::math::tr1::cyl_bessel_i;\nusing boost::math::tr1::cyl_bessel_if;\nusing boost::math::tr1::cyl_bessel_il;\n// [5.2.1.9] cylindrical Bessel functions (of the first kind):\nusing boost::math::tr1::cyl_bessel_j;\nusing boost::math::tr1::cyl_bessel_jf;\nusing boost::math::tr1::cyl_bessel_jl;\n// [5.2.1.10] irregular modified cylindrical Bessel functions:\nusing boost::math::tr1::cyl_bessel_k;\nusing boost::math::tr1::cyl_bessel_kf;\nusing boost::math::tr1::cyl_bessel_kl;\n// [5.2.1.11] cylindrical Neumann functions;\n// cylindrical Bessel functions (of the second kind):\nusing boost::math::tr1::cyl_neumann;\nusing boost::math::tr1::cyl_neumannf;\nusing boost::math::tr1::cyl_neumannl;\n// [5.2.1.12] (incomplete) elliptic integral of the first kind:\nusing boost::math::tr1::ellint_1;\nusing boost::math::tr1::ellint_1f;\nusing boost::math::tr1::ellint_1l;\n// [5.2.1.13] (incomplete) elliptic integral of the second kind:\nusing boost::math::tr1::ellint_2;\nusing boost::math::tr1::ellint_2f;\nusing boost::math::tr1::ellint_2l;\n// [5.2.1.14] (incomplete) elliptic integral of the third kind:\nusing boost::math::tr1::ellint_3;\nusing boost::math::tr1::ellint_3f;\nusing boost::math::tr1::ellint_3l;\n// [5.2.1.15] exponential integral:\nusing boost::math::tr1::expint;\nusing boost::math::tr1::expintf;\nusing boost::math::tr1::expintl;\n// [5.2.1.16] Hermite polynomials:\nusing boost::math::tr1::hermite;\nusing boost::math::tr1::hermitef;\nusing boost::math::tr1::hermitel;\n#if 0\n// [5.2.1.17] hypergeometric functions:\nusing boost::math::tr1::hyperg;\nusing boost::math::tr1::hypergf;\nusing boost::math::tr1::hypergl;\n#endif\n// [5.2.1.18] Laguerre polynomials:\nusing boost::math::tr1::laguerre;\nusing boost::math::tr1::laguerref;\nusing boost::math::tr1::laguerrel;\n// [5.2.1.19] Legendre polynomials:\nusing boost::math::tr1::legendre;\nusing boost::math::tr1::legendref;\nusing boost::math::tr1::legendrel;\n// [5.2.1.20] Riemann zeta function:\nusing boost::math::tr1::riemann_zeta;\nusing boost::math::tr1::riemann_zetaf;\nusing boost::math::tr1::riemann_zetal;\n// [5.2.1.21] spherical Bessel functions (of the first kind):\nusing boost::math::tr1::sph_bessel;\nusing boost::math::tr1::sph_besself;\nusing boost::math::tr1::sph_bessell;\n// [5.2.1.22] spherical associated Legendre functions:\nusing boost::math::tr1::sph_legendre;\nusing boost::math::tr1::sph_legendref;\nusing boost::math::tr1::sph_legendrel;\n// [5.2.1.23] spherical Neumann functions;\n// spherical Bessel functions (of the second kind):\nusing boost::math::tr1::sph_neumann;\nusing boost::math::tr1::sph_neumannf;\nusing boost::math::tr1::sph_neumannl;\n\n// types\nusing boost::math::tr1::double_t;\nusing boost::math::tr1::float_t;\n// functions\nusing boost::math::tr1::acosh;\nusing boost::math::tr1::acoshf;\nusing boost::math::tr1::acoshl;\nusing boost::math::tr1::asinh;\nusing boost::math::tr1::asinhf;\nusing boost::math::tr1::asinhl;\nusing boost::math::tr1::atanh;\nusing boost::math::tr1::atanhf;\nusing boost::math::tr1::atanhl;\nusing boost::math::tr1::cbrt;\nusing boost::math::tr1::cbrtf;\nusing boost::math::tr1::cbrtl;\nusing boost::math::tr1::copysign;\nusing boost::math::tr1::copysignf;\nusing boost::math::tr1::copysignl;\nusing boost::math::tr1::erf;\nusing boost::math::tr1::erff;\nusing boost::math::tr1::erfl;\nusing boost::math::tr1::erfc;\nusing boost::math::tr1::erfcf;\nusing boost::math::tr1::erfcl;\n#if 0\nusing boost::math::tr1::exp2;\nusing boost::math::tr1::exp2f;\nusing boost::math::tr1::exp2l;\n#endif\nusing boost::math::tr1::expm1;\nusing boost::math::tr1::expm1f;\nusing boost::math::tr1::expm1l;\n#if 0\nusing boost::math::tr1::fdim;\nusing boost::math::tr1::fdimf;\nusing boost::math::tr1::fdiml;\nusing boost::math::tr1::fma;\nusing boost::math::tr1::fmaf;\nusing boost::math::tr1::fmal;\n#endif\nusing boost::math::tr1::fmax;\nusing boost::math::tr1::fmaxf;\nusing boost::math::tr1::fmaxl;\nusing boost::math::tr1::fmin;\nusing boost::math::tr1::fminf;\nusing boost::math::tr1::fminl;\nusing boost::math::tr1::hypot;\nusing boost::math::tr1::hypotf;\nusing boost::math::tr1::hypotl;\n#if 0\nusing boost::math::tr1::ilogb;\nusing boost::math::tr1::ilogbf;\nusing boost::math::tr1::ilogbl;\n#endif\nusing boost::math::tr1::lgamma;\nusing boost::math::tr1::lgammaf;\nusing boost::math::tr1::lgammal;\n#if 0\nusing boost::math::tr1::llrint;\nusing boost::math::tr1::llrintf;\nusing boost::math::tr1::llrintl;\n#endif\nusing boost::math::tr1::llround;\nusing boost::math::tr1::llroundf;\nusing boost::math::tr1::llroundl;\nusing boost::math::tr1::log1p;\nusing boost::math::tr1::log1pf;\nusing boost::math::tr1::log1pl;\n#if 0\nusing boost::math::tr1::log2;\nusing boost::math::tr1::log2f;\nusing boost::math::tr1::log2l;\nusing boost::math::tr1::logb;\nusing boost::math::tr1::logbf;\nusing boost::math::tr1::logbl;\nusing boost::math::tr1::lrint;\nusing boost::math::tr1::lrintf;\nusing boost::math::tr1::lrintl;\n#endif\nusing boost::math::tr1::lround;\nusing boost::math::tr1::lroundf;\nusing boost::math::tr1::lroundl;\n#if 0\nusing boost::math::tr1::nan;\nusing boost::math::tr1::nanf;\nusing boost::math::tr1::nanl;\nusing boost::math::tr1::nearbyint;\nusing boost::math::tr1::nearbyintf;\nusing boost::math::tr1::nearbyintl;\n#endif\nusing boost::math::tr1::nextafter;\nusing boost::math::tr1::nextafterf;\nusing boost::math::tr1::nextafterl;\nusing boost::math::tr1::nexttoward;\nusing boost::math::tr1::nexttowardf;\nusing boost::math::tr1::nexttowardl;\n#if 0\nusing boost::math::tr1::remainder;\nusing boost::math::tr1::remainderf;\nusing boost::math::tr1::remainderl;\nusing boost::math::tr1::remquo;\nusing boost::math::tr1::remquof;\nusing boost::math::tr1::remquol;\nusing boost::math::tr1::rint;\nusing boost::math::tr1::rintf;\nusing boost::math::tr1::rintl;\n#endif\nusing boost::math::tr1::round;\nusing boost::math::tr1::roundf;\nusing boost::math::tr1::roundl;\n#if 0\nusing boost::math::tr1::scalbln;\nusing boost::math::tr1::scalblnf;\nusing boost::math::tr1::scalblnl;\nusing boost::math::tr1::scalbn;\nusing boost::math::tr1::scalbnf;\nusing boost::math::tr1::scalbnl;\n#endif\nusing boost::math::tr1::tgamma;\nusing boost::math::tr1::tgammaf;\nusing boost::math::tr1::tgammal;\nusing boost::math::tr1::trunc;\nusing boost::math::tr1::truncf;\nusing boost::math::tr1::truncl;\n// C99 macros defined as C++ templates\nusing boost::math::tr1::signbit;\nusing boost::math::tr1::fpclassify;\nusing boost::math::tr1::isfinite;\nusing boost::math::tr1::isinf;\nusing boost::math::tr1::isnan;\nusing boost::math::tr1::isnormal;\n#if 0\nusing boost::math::tr1::isgreater;\nusing boost::math::tr1::isgreaterequal;\nusing boost::math::tr1::isless;\nusing boost::math::tr1::islessequal;\nusing boost::math::tr1::islessgreater;\nusing boost::math::tr1::isunordered;\n#endif\n} } // namespaces\n\n#endif // BOOST_HAS_TR1_CMATH\n\n#endif // BOOST_TR1_CMATH_HPP_INCLUDED\n", "meta": {"hexsha": "d692b3c00504ab6506dfab301755bacbbdd33ee4", "size": 8577, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/tr1/cmath.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "boost/boost/tr1/cmath.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1074.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T15:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-22T20:28:39.000Z", "max_forks_repo_path": "boost/boost/tr1/cmath.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 32.0037313433, "max_line_length": 81, "alphanum_fraction": 0.730908243, "num_tokens": 2983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5002633834976227}}
{"text": "/**\n * @file\n * @brief Solution of general second-order elliptic boundary value problem with\n * linear finite elements from a Gmsh generated mesh\n * @author Simon Meierhans\n * @date   January 2019\n * @copyright MIT License\n */\n\n#include <fstream>\n#include <iomanip>\n\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/refinement/refinement.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <boost/filesystem.hpp>\n\nint main() {\n  // abbreviations for types\n  using size_type = lf::base::size_type;\n  using glb_idx_t = lf::assemble::glb_idx_t;\n  using coord_t = Eigen::Vector2d;\n\n  // find path to mesh\n  boost::filesystem::path here = __FILE__;\n  auto mesh_path = here.parent_path() / \"meshes/square.msh\";\n\n  // load mesh of square computational domain\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  const lf::io::GmshReader reader(std::move(mesh_factory), mesh_path.string());\n\n  // get pointer to mesh\n  auto mesh = reader.mesh();\n\n  // Count the number of edges with von Neumann boundary condition\n  auto physical_entity_nr_neu = reader.PhysicalEntityName2Nr(\"neu\");\n  int num_neumann = 0;\n  for (auto e : mesh->Entities(1)) {\n    if (reader.IsPhysicalEntity(*e, physical_entity_nr_neu)) {\n      ++num_neumann;\n    }\n  }\n  std::cout << \"boundary edges with von Neumann boundary condition: \"\n            << num_neumann << \"\\n\";\n\n  // Count the number of edges with Dirichlet boundary condition\n  auto physical_entity_nr_dir = reader.PhysicalEntityName2Nr(\"dir\");\n  int num_dirichlet = 0;\n  for (auto e : mesh->Entities(1)) {\n    if (reader.IsPhysicalEntity(*e, physical_entity_nr_dir)) {\n      ++num_dirichlet;\n    }\n  }\n  std::cout << \"boundary edges with Dirichlet boundary condition: \"\n            << num_dirichlet << \"\\n\";\n\n  // set up finite element space\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh);\n\n  // set up dof handler\n  const lf::assemble::DofHandler& dofh{fe_space->LocGlobMap()};\n\n  // Dimension of finite element space`\n  const size_type N_dofs(dofh.NumDofs());\n\n  // identity mesh function for very simple problem\n  lf::uscalfe::MeshFunctionConstant mf_identity(1.0);\n\n  auto zero = [](const Eigen::Vector2d & /*x*/) -> double { return 0.; };\n  lf::uscalfe::MeshFunctionGlobal mf_zero{zero};\n\n  // Matrix in triplet format holding Galerkin matrix, zero initially.\n  lf::assemble::COOMatrix<double> A(N_dofs, N_dofs);\n\n  // Obtain an object that computes the element matrix for the\n  // volumne part of the bilinear form\n  lf::uscalfe::ReactionDiffusionElementMatrixProvider elmat_builder(\n      fe_space, mf_identity, mf_identity);\n\n  // Invoke assembly on cells (co-dimension = 0)\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elmat_builder, A);\n\n  // Right-hand side vector; has to be set to zero initially\n  Eigen::Matrix<double, Eigen::Dynamic, 1> phi(N_dofs);\n  phi.setZero();\n\n  // Initialize object taking care of local computations on all cells for the\n  // source f. The source is the identity function\n  lf::uscalfe::ScalarLoadElementVectorProvider elvec_builder(fe_space,\n                                                             mf_identity);\n  // Invoke assembly on cells (codim == 0)\n  AssembleVectorLocally(0, dofh, elvec_builder, phi);\n\n  if (num_neumann > 0) {\n    // Select von Neumann edges\n    auto edge_sel_neu = [&reader, physical_entity_nr_neu](\n                            const lf::mesh::Entity& edge) -> bool {\n      return reader.IsPhysicalEntity(edge, physical_entity_nr_neu);\n    };\n\n    // Add contributions of von Neumann boundary conditions\n    lf::uscalfe::ScalarLoadEdgeVectorProvider<double, decltype(mf_identity),\n                                              decltype(edge_sel_neu)>\n        elvec_builder_neu(fe_space, mf_identity, edge_sel_neu);\n    AssembleVectorLocally(1, dofh, elvec_builder_neu, phi);\n  }\n\n  if (num_dirichlet > 0) {\n    // Select Dirichlet edges\n    auto edge_sel_dir = [&reader, physical_entity_nr_dir](\n                            const lf::mesh::Entity& edge) -> bool {\n      return reader.IsPhysicalEntity(edge, physical_entity_nr_dir);\n    };\n\n    // Obtain specification for shape functions on edges\n    std::shared_ptr<const lf::uscalfe::ScalarReferenceFiniteElement<double>>\n        rsf_edge_p = fe_space->ShapeFunctionLayout(lf::base::RefEl::kSegment());\n    LF_ASSERT_MSG(rsf_edge_p != nullptr, \"FE specification for edges missing\");\n\n    // Fetch flags and values for degrees of freedom located on Dirichlet\n    // edges.\n    // bd_flags strictly speaking would not be necessary here since only\n    // boundary edges are flagged as 'dir' anyway. In other cases this might\n    // however be necessary.\n    auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(fe_space->Mesh(), 1)};\n    auto ess_bdc_flags_values{lf::uscalfe::InitEssentialConditionFromFunction(\n        dofh, *rsf_edge_p,\n        [&edge_sel_dir, &bd_flags](const lf::mesh::Entity& edge) -> bool {\n          return (bd_flags(edge) && edge_sel_dir(edge));\n        },\n        mf_zero)};\n    // Eliminate Dirichlet dofs from linear system\n    lf::assemble::FixFlaggedSolutionComponents<double>(\n        [&ess_bdc_flags_values](glb_idx_t gdof_idx) {\n          return ess_bdc_flags_values[gdof_idx];\n        },\n        A, phi);\n  }\n  // Assembly completed: Convert COO matrix into CRS format using Eigen's\n  // internal conversion routines.\n  Eigen::SparseMatrix<double> A_crs = A.makeSparse();\n\n  // Solve linear system using Eigen's sparse direct elimination\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(A_crs);\n  Eigen::VectorXd sol_vec = solver.solve(phi);\n\n  // Compute H1 Norm\n  if (N_dofs > 0) {\n    // Version 1: Using Mesh Functions\n    auto mf_FE = lf::uscalfe::MeshFunctionFE(fe_space, sol_vec);\n    auto mf_GradFe = lf::uscalfe::MeshFunctionGradFE(fe_space, sol_vec);\n    auto h1_norm = std::sqrt(IntegrateMeshFunction(\n        *mesh, squaredNorm(mf_FE) + squaredNorm(mf_GradFe), 2));\n\n    std::cout << \"Computed H1 Norm: \" << h1_norm << std::endl;\n\n    // Version 2: Compute Energy by assembling Stiffness matrix/mass matrix\n    lf::assemble::COOMatrix<double> Stiffness(N_dofs, N_dofs);\n    lf::uscalfe::ReactionDiffusionElementMatrixProvider stiffness_mat_builder(\n        fe_space, mf_identity, mf_zero);\n    lf::assemble::AssembleMatrixLocally(0, dofh, dofh, stiffness_mat_builder,\n                                        Stiffness);\n    Eigen::SparseMatrix<double> Stiffness_crs = Stiffness.makeSparse();\n\n    // Matrix in triplet format holding Mass matrix.\n    lf::assemble::COOMatrix<double> Mass(N_dofs, N_dofs);\n    lf::uscalfe::ReactionDiffusionElementMatrixProvider mass_mat_builder(\n        fe_space, mf_zero, mf_identity);\n    lf::assemble::AssembleMatrixLocally(0, dofh, dofh, mass_mat_builder, Mass);\n    Eigen::SparseMatrix<double> Mass_crs = Mass.makeSparse();\n\n    // h1_seminorm_sq = \\mu' A \\mu\n    double h1_semi2 = sol_vec.transpose() * (Stiffness_crs * sol_vec);\n    // l2_norm_sq = \\mu' M \\mu\n    double l22 = sol_vec.transpose() * Mass_crs * sol_vec;\n\n    std::cout << \"Computed H1 Norm: \" << std::sqrt(h1_semi2 + l22) << \"\\n\";\n  }\n}\n", "meta": {"hexsha": "61f1478c2e53b52642bcc305d006be6a20ad8e4d", "size": 7251, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/ellbvp_msh/ellbvp_msh_demo.cc", "max_stars_repo_name": "liaowangh/lehrfempp", "max_stars_repo_head_hexsha": "ece8f84cdc333bbc95846c7e712d591bfdadf9ab", "max_stars_repo_licenses": ["MIT"], "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/ellbvp_msh/ellbvp_msh_demo.cc", "max_issues_repo_name": "liaowangh/lehrfempp", "max_issues_repo_head_hexsha": "ece8f84cdc333bbc95846c7e712d591bfdadf9ab", "max_issues_repo_licenses": ["MIT"], "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/ellbvp_msh/ellbvp_msh_demo.cc", "max_forks_repo_name": "liaowangh/lehrfempp", "max_forks_repo_head_hexsha": "ece8f84cdc333bbc95846c7e712d591bfdadf9ab", "max_forks_repo_licenses": ["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.7754010695, "max_line_length": 80, "alphanum_fraction": 0.6869397325, "num_tokens": 1910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5001836372810823}}
{"text": "/* boost random/triangle_distribution.hpp header file\r\n *\r\n * Copyright Jens Maurer 2000-2001\r\n * Permission to use, copy, modify, sell, and distribute this software\r\n * is hereby granted without fee provided that the above copyright notice\r\n * appears in all copies and that both that copyright notice and this\r\n * permission notice appear in supporting documentation,\r\n *\r\n * Jens Maurer makes no representations about the suitability of this\r\n * software for any purpose. It is provided \"as is\" without express or\r\n * implied warranty.\r\n *\r\n * See http://www.boost.org for most recent version including documentation.\r\n *\r\n * $Id: triangle_distribution.hpp,v 1.9 2002/12/22 22:03:11 jmaurer Exp $\r\n *\r\n * Revision history\r\n *  2001-02-18  moved to individual header files\r\n */\r\n\r\n#ifndef BOOST_RANDOM_TRIANGLE_DISTRIBUTION_HPP\r\n#define BOOST_RANDOM_TRIANGLE_DISTRIBUTION_HPP\r\n\r\n#include <cmath>\r\n#include <cassert>\r\n#include <boost/random/uniform_01.hpp>\r\n\r\nnamespace boost {\r\n\r\n// triangle distribution, with a smallest, b most probable, and c largest\r\n// value.\r\ntemplate<class UniformRandomNumberGenerator, class RealType = double,\r\n        class Adaptor = uniform_01<UniformRandomNumberGenerator, RealType> >\r\nclass triangle_distribution\r\n{\r\npublic:\r\n  typedef Adaptor adaptor_type;\r\n  typedef UniformRandomNumberGenerator base_type;\r\n  typedef RealType result_type;\r\n\r\n  explicit triangle_distribution(base_type & rng,\r\n                                 result_type a = result_type(0),\r\n                                 result_type b = result_type(0.5),\r\n                                 result_type c = result_type(1))\r\n    : _rng(rng), _a(a), _b(b), _c(c)\r\n  {\r\n    assert(_a <= _b && _b <= _c);\r\n    init();\r\n  }\r\n\r\n  // compiler-generated copy ctor and assignment operator are fine\r\n\r\n  adaptor_type& adaptor() { return _rng; }\r\n  base_type& base() const { return _rng.base(); }\r\n  void reset() { _rng.reset(); }\r\n\r\n  result_type operator()()\r\n  {\r\n#ifndef BOOST_NO_STDC_NAMESPACE\r\n    using std::sqrt;\r\n#endif\r\n    result_type u = _rng();\r\n    if( u <= q1 )\r\n      return _a + p1*sqrt(u);\r\n    else\r\n      return _c - d3*sqrt(d2*u-d1);\r\n  }\r\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\r\n  friend bool operator==(const triangle_distribution& x, \r\n                         const triangle_distribution& y)\r\n  { return x._a == y._a && x._b == y._b && x._c == y._c && x._rng == y._rng; }\r\n\r\n#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS\r\n  template<class CharT, class Traits>\r\n  friend std::basic_ostream<CharT,Traits>&\r\n  operator<<(std::basic_ostream<CharT,Traits>& os, const triangle_distribution& td)\r\n  {\r\n    os << td._a << \" \" << td._b << \" \" << td._c;\r\n    return os;\r\n  }\r\n\r\n  template<class CharT, class Traits>\r\n  friend std::basic_istream<CharT,Traits>&\r\n  operator>>(std::basic_istream<CharT,Traits>& is, triangle_distribution& td)\r\n  {\r\n    is >> std::ws >> td._a >> std::ws >> td._b >> std::ws >> td._c;\r\n    td.init();\r\n    return is;\r\n  }\r\n#endif\r\n\r\n#else\r\n  // Use a member function\r\n  bool operator==(const triangle_distribution& rhs) const\r\n  { return _a == rhs._a && _b == rhs._b && _c == rhs._c && _rng == rhs._rng;  }\r\n#endif\r\n\r\nprivate:\r\n  void init()\r\n  {\r\n#ifndef BOOST_NO_STDC_NAMESPACE\r\n    using std::sqrt;\r\n#endif\r\n    d1 = _b - _a;\r\n    d2 = _c - _a;\r\n    d3 = sqrt(_c - _b);\r\n    q1 = d1 / d2;\r\n    p1 = sqrt(d1 * d2);\r\n  }\r\n\r\n  adaptor_type _rng;\r\n  result_type _a, _b, _c;\r\n  result_type d1, d2, d3, q1, p1;\r\n};\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_RANDOM_TRIANGLE_DISTRIBUTION_HPP\r\n", "meta": {"hexsha": "4db01fea4a65f63c391dd045a51ebfe7b9e08df2", "size": 3521, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/boost/random/triangle_distribution.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T06:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:24:28.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/boost/random/triangle_distribution.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "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/boost_1_30_0/boost/random/triangle_distribution.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-17T10:01:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-11T20:17:27.000Z", "avg_line_length": 29.5882352941, "max_line_length": 84, "alphanum_fraction": 0.6444191991, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5001836324478239}}
{"text": "#ifndef COMP_EIG_HH\n#define COMP_EIG_HH\n\n#include <armadillo>\n#include <cassert>\n\n// sort and compare eigenvectors and eigenvalues\nstatic double comp_eig(arma::vec Avalues, arma::mat Avectors, arma::vec Bvalues, arma::mat Bvectors) {\n  assert(size(Avalues) == size(Bvalues));\n  assert(size(Avectors) == size(Bvectors));\n  assert(Avalues.n_elem == Avectors.n_rows && Avectors.is_square());\n\n  size_t M = Avalues.n_elem;\n\n  // normalize and sort A eigenvalues (quick and dirty algorithm)\n  for(size_t i = 0; i < M; i++) {\n    // Avectors.col(i) = arma::normalise(Avectors.col(i));\n\n    size_t k = i;\n    for(size_t j = i + 1; j < M; j++) {\n      if(Avalues(j) < Avalues(k))\n        k = j;\n    }\n    if(i == k) continue;\n    Avalues.swap_rows(i, k);\n    Avectors.swap_cols(i, k);\n  }\n\n  // sort B eigenvalues (quick and dirty algorithm)\n  for(size_t i = 0; i < M; i++) {\n    // Bvectors.col(i) = arma::normalise(Bvectors.col(i));\n\n    size_t k = i;\n    for(size_t j = i + 1; j < M; j++) {\n      if(Bvalues(j) < Bvalues(k))\n        k = j;\n    }\n    if(i == k) continue;\n    Bvalues.swap_rows(i, k);\n    Bvectors.swap_cols(i, k);\n  }\n\n  // fix antiparallell eigenvectors in A and B\n  for(size_t i = 0; i < M; i++) {\n    if(arma::dot(Avectors.col(i), Bvectors.col(i)) < 0)\n      Bvectors.col(i) = - Bvectors.col(i);\n  }\n\n  // fix maximal difference between eigenvalues or eigenvectors\n  const double values_error = arma::abs(Avalues - Bvalues).max();\n  const double vectors_error = arma::abs(Avectors - Bvectors).max();\n\n  // return error metric\n  return std::max(values_error, vectors_error);\n}\n\n#endif\n", "meta": {"hexsha": "88ea3bd21b588bd04ec8ba36e409a6283819535b", "size": 1598, "ext": "hh", "lang": "C++", "max_stars_repo_path": "project2/code-fredrik/comp_eig.hh", "max_stars_repo_name": "frxstrem/fys3150", "max_stars_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project2/code-fredrik/comp_eig.hh", "max_issues_repo_name": "frxstrem/fys3150", "max_issues_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project2/code-fredrik/comp_eig.hh", "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": 27.5517241379, "max_line_length": 102, "alphanum_fraction": 0.6251564456, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5001836189081814}}
{"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#include <iostream>\n\n#include <boost/bind.hpp>\n#include <memory>\n#include <boost/make_shared.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/sphericalStateConversions.h\"\n#include \"Tudat/Astrodynamics/ReferenceFrames/aerodynamicAngleCalculator.h\"\n#include \"Tudat/Astrodynamics/ReferenceFrames/referenceFrameTransformations.h\"\n#include \"Tudat/Mathematics/BasicMathematics/coordinateConversions.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Mathematics/BasicMathematics/rotationRepresentations.h\"\n\nnamespace tudat\n{\n\nnamespace reference_frames\n{\n\n//! Function to get a string representing a 'named identification' of a reference frame.\nstd::string getAerodynamicFrameName( const AerodynamicsReferenceFrames frame )\n{\n    std::string frameName;\n    switch( frame )\n    {\n    case inertial_frame:\n        frameName = \"inertial frame \";\n        break;\n    case corotating_frame:\n        frameName = \"corotating frame \";\n        break;\n    case vertical_frame:\n        frameName = \"vertical frame \";\n        break;\n    case trajectory_frame:\n        frameName = \"trajectory frame \";\n        break;\n    case aerodynamic_frame:\n        frameName = \"aerodynamic frame \";\n        break;\n    case body_frame:\n        frameName = \"body frame \";\n        break;\n    default:\n        std::string errorMessage = \"Error, aerodynamic frame type \" +\n                std::to_string( frame ) +\n                \"not found when retrieving frame name \";\n        throw std::runtime_error( errorMessage );\n    }\n    return frameName;\n}\n\n//! Function to get a string representing a 'named identification' of an aerodynamic angle\nstd::string getAerodynamicAngleName( const AerodynamicsReferenceFrameAngles angle )\n{\n    std::string angleName;\n    switch( angle )\n    {\n    case latitude_angle:\n        angleName = \"latitude angle \";\n        break;\n    case longitude_angle:\n        angleName = \"longitude angle \";\n        break;\n    case heading_angle:\n        angleName = \"heading angle \";\n        break;\n    case flight_path_angle:\n        angleName = \"flight path angle \";\n        break;\n    case angle_of_attack:\n        angleName = \"angle of attack \";\n        break;\n    case angle_of_sideslip:\n        angleName = \"sideslip angle \";\n        break;\n    case bank_angle:\n        angleName = \"bank angle \";\n        break;\n    default:\n        std::string errorMessage = \"Error, aerodynamic angle type \" +\n                std::to_string( angle ) +\n                \"not found when retrieving angle name \";\n        throw std::runtime_error( errorMessage );\n    }\n    return angleName;\n}\n\n\n//! Function to update the orientation angles to the current state.\nvoid AerodynamicAngleCalculator::update( const double currentTime, const bool updateBodyOrientation )\n{\n    // Clear all current rotation matrices.\n    currentRotationMatrices_.clear( );\n\n    // Get current body-fixed state.\n    if( !( currentTime == currentTime_ ) )\n    {\n        currentBodyFixedGroundSpeedBasedState_ = bodyFixedStateFunction_( );\n        currentRotationFromCorotatingToInertialFrame_ = rotationFromCorotatingToInertialFrame_( );\n\n        Eigen::Vector3d sphericalCoordinates = coordinate_conversions::convertCartesianToSpherical< double >(\n                    currentBodyFixedGroundSpeedBasedState_.segment( 0, 3 ) );\n\n        // Calculate latitude and longitude.\n        currentAerodynamicAngles_[ latitude_angle ] =\n                mathematical_constants::PI / 2.0 - sphericalCoordinates( 1 );\n        currentAerodynamicAngles_[ longitude_angle ] = sphericalCoordinates( 2 );\n\n        // Compute wind velocity vector\n        Eigen::Vector3d localWindVelocity = Eigen::Vector3d::Zero( );\n        if( windModel_ != nullptr )\n        {\n            localWindVelocity = windModel_->getCurrentWindVelocity(\n                        shapeModel_->getAltitude( currentBodyFixedGroundSpeedBasedState_.segment( 0, 3 ) ),\n                        currentAerodynamicAngles_[ longitude_angle ],\n                        currentAerodynamicAngles_[ latitude_angle ],\n                        currentTime );\n        }\n\n        // Compute airspeed-based velocity vector\n        currentBodyFixedAirspeedBasedState_ = currentBodyFixedGroundSpeedBasedState_;\n        currentBodyFixedAirspeedBasedState_.segment( 3, 3 ) += localWindVelocity;\n\n        // Calculate vertical <-> aerodynamic <-> body-fixed angles if neede.\n        if( calculateVerticalToAerodynamicFrame_ )\n        {\n            Eigen::Vector3d verticalFrameVelocity =\n                    getRotatingPlanetocentricToLocalVerticalFrameTransformationQuaternion(\n                        currentAerodynamicAngles_.at( longitude_angle ),\n                        currentAerodynamicAngles_.at( latitude_angle ) ) *\n                    currentBodyFixedAirspeedBasedState_.segment( 3, 3 );\n\n            currentAerodynamicAngles_[ heading_angle ] = calculateHeadingAngle( verticalFrameVelocity );\n            currentAerodynamicAngles_[ flight_path_angle ] =\n                    calculateFlightPathAngle( verticalFrameVelocity );\n        }\n\n        currentTime_ = currentTime;\n    }\n\n    if( updateBodyOrientation  && !( currentBodyAngleTime_ == currentTime ) )\n    {\n        if( !( angleUpdateFunction_ == nullptr ) )\n        {\n            angleUpdateFunction_( currentTime );\n        }\n\n        if( !( angleOfAttackFunction_ == nullptr ) )\n        {\n            currentAerodynamicAngles_[ angle_of_attack ] = angleOfAttackFunction_( );\n        }\n\n        if( !( angleOfSideslipFunction_ == nullptr ) )\n        {\n            currentAerodynamicAngles_[ angle_of_sideslip ] = angleOfSideslipFunction_( );\n        }\n\n        if( !( bankAngleFunction_ == nullptr ) )\n        {\n            currentAerodynamicAngles_[ bank_angle ] = bankAngleFunction_( );\n        }\n\n        currentBodyAngleTime_ = currentTime;\n    }\n    else if( !( currentBodyAngleTime_ == currentTime ) )\n    {\n        currentAerodynamicAngles_[ angle_of_attack ] = 0.0;\n        currentAerodynamicAngles_[ angle_of_sideslip ] = 0.0;\n        currentAerodynamicAngles_[ bank_angle ] = 0.0;\n    }\n}\n\n//! Function to get the rotation quaternion between two frames\nEigen::Quaterniond AerodynamicAngleCalculator::getRotationQuaternionBetweenFrames(\n        const AerodynamicsReferenceFrames originalFrame,\n        const AerodynamicsReferenceFrames targetFrame )\n{\n    // Initialize rotation to identity matrix.\n    Eigen::Quaterniond rotationToFrame = Eigen::Quaterniond( Eigen::Matrix3d::Identity( ) );\n\n    // Check if update settings are consistent with requested frames.\n    if( !calculateVerticalToAerodynamicFrame_ &&\n            ( originalFrame > vertical_frame || targetFrame > vertical_frame ) )\n    {\n        throw std::runtime_error( \"Error in AerodynamicAngleCalculator, instance ends at vertical frame\" );\n    }\n\n    // Set current frame pair.\n    std::pair< AerodynamicsReferenceFrames, AerodynamicsReferenceFrames > currentRotationPair =\n            std::make_pair( originalFrame, targetFrame );\n\n    // Calculate rotation matrix if current rotation is not yet calculated.\n    if( currentRotationMatrices_.count( currentRotationPair ) == 0 )\n    {\n        // Get indices of required frames.\n        int currentFrameIndex = static_cast< int >( originalFrame );\n        int targetFrameIndex = static_cast< int >( targetFrame );\n\n        // Check if any rotation is needed.\n        if( currentFrameIndex != targetFrameIndex )\n        {\n            // Check 'direction' of transformation through AerodynamicsReferenceFrames list.\n            bool isTargetFrameUp;\n            if( targetFrameIndex > currentFrameIndex )\n            {\n                isTargetFrameUp = 1;\n            }\n            else if( targetFrameIndex < currentFrameIndex )\n            {\n                isTargetFrameUp = 0;\n            }\n            else\n            {\n                throw std::runtime_error(\n                            \"Error when identifying target frame direction in AerodynamicAngleCalculator.\" );\n            }\n\n            // Add rotation sequence until final frame is reached.\n            while( currentFrameIndex != targetFrameIndex )\n            {\n                switch( currentFrameIndex )\n                {\n                case static_cast< int >( inertial_frame ):\n                    if( isTargetFrameUp )\n                    {\n                        rotationToFrame = currentRotationFromCorotatingToInertialFrame_.inverse( ) *\n                                rotationToFrame;\n                    }\n                    else\n                    {\n                        throw std::runtime_error(\n                                    \"Error, inertial_frame is end frame in AerodynamicAngleCalculator\" );\n                    }\n                    break;\n                case static_cast< int >( corotating_frame ):\n                    if( isTargetFrameUp )\n                    {\n                        rotationToFrame =\n                                getRotatingPlanetocentricToLocalVerticalFrameTransformationQuaternion(\n                                    currentAerodynamicAngles_.at( longitude_angle ),\n                                    currentAerodynamicAngles_.at( latitude_angle ) ) *\n                                rotationToFrame;\n                    }\n                    else\n                    {\n                        rotationToFrame = currentRotationFromCorotatingToInertialFrame_ *\n                                rotationToFrame;\n                    }\n                    break;\n                case static_cast< int >( vertical_frame ):\n                    if( isTargetFrameUp )\n                    {\n\n                        rotationToFrame =\n                                getLocalVerticalFrameToTrajectoryTransformationQuaternion(\n                                    currentAerodynamicAngles_.at( flight_path_angle ),\n                                    currentAerodynamicAngles_.at( heading_angle ) ) * rotationToFrame;\n                    }\n                    else\n                    {\n                        rotationToFrame =\n                                getLocalVerticalToRotatingPlanetocentricFrameTransformationQuaternion(\n                                    currentAerodynamicAngles_.at( longitude_angle ),\n                                    currentAerodynamicAngles_.at( latitude_angle ) ) *\n                                rotationToFrame;\n                    }\n                    break;\n                case static_cast< int >( trajectory_frame ):\n                    if( isTargetFrameUp )\n                    {\n                        rotationToFrame =\n                                getTrajectoryToAerodynamicFrameTransformationQuaternion(\n                                    currentAerodynamicAngles_.at( bank_angle ) ) *\n                                rotationToFrame;\n                    }\n                    else\n                    {\n                        rotationToFrame =\n                                getTrajectoryToLocalVerticalFrameTransformationQuaternion(\n                                    currentAerodynamicAngles_.at( flight_path_angle ),\n                                    currentAerodynamicAngles_.at( heading_angle ) ) *\n                                rotationToFrame;\n                    }\n                    break;\n                case static_cast< int >( aerodynamic_frame ):\n                    if( isTargetFrameUp )\n                    {\n                        rotationToFrame =\n                                getAirspeedBasedAerodynamicToBodyFrameTransformationQuaternion(\n                                    currentAerodynamicAngles_.at( angle_of_attack ),\n                                    currentAerodynamicAngles_.at( angle_of_sideslip ) ) *\n                                rotationToFrame;\n                    }\n                    else\n                    {\n                        rotationToFrame =\n                                getAerodynamicToTrajectoryFrameTransformationQuaternion(\n                                    currentAerodynamicAngles_.at( bank_angle ) ) *\n                                rotationToFrame;\n                    }\n                    break;\n                case static_cast< int >( body_frame ):\n                    if( isTargetFrameUp )\n                    {\n                        throw std::runtime_error(\n                                    \"Error, body frame is end frame in AerodynamicAngleCalculator.\" );\n                    }\n                    else\n                    {\n                        rotationToFrame =\n                                getBodyToAirspeedBasedAerodynamicFrameTransformationQuaternion(\n                                    currentAerodynamicAngles_.at( angle_of_attack ),\n                                    currentAerodynamicAngles_.at( angle_of_sideslip ) ) *\n                                rotationToFrame;\n                    }\n                    break;\n                default:\n                    throw std::runtime_error(\n                                \"Error, index \" + std::to_string( currentFrameIndex ) +\n                                \"not found in AerodynamicAngleCalculator.\" );\n                }\n\n                // Increment/decrement current frame.\n                if( isTargetFrameUp )\n                {\n                    currentFrameIndex++;\n                }\n                else\n                {\n                    currentFrameIndex--;\n                }\n            }\n        }\n\n        // Set current rotation (as well as inverse).\n        currentRotationMatrices_[ currentRotationPair ] = rotationToFrame;\n        currentRotationMatrices_[ std::make_pair( targetFrame, originalFrame ) ] =\n                rotationToFrame.inverse( );\n    }\n    else\n    {\n        rotationToFrame = currentRotationMatrices_.at( currentRotationPair );\n    }\n\n    return rotationToFrame;\n}\n\n//! Function to get a single orientation angle.\ndouble AerodynamicAngleCalculator::getAerodynamicAngle(\n        const AerodynamicsReferenceFrameAngles angleId )\n{\n    double angleValue = TUDAT_NAN;\n    if( currentAerodynamicAngles_.count( angleId ) == 0 )\n    {\n        throw std::runtime_error( \"Error in AerodynamicAngleCalculator, angle \" +\n                                  std::to_string( angleId ) + \" not found\" );\n    }\n    else\n    {\n        angleValue = currentAerodynamicAngles_.at( angleId );\n    }\n    return angleValue;\n}\n\n//! Function to set the trajectory<->body-fixed orientation angles.\nvoid AerodynamicAngleCalculator::setOrientationAngleFunctions(\n        const std::function< double( ) > angleOfAttackFunction,\n        const std::function< double( ) > angleOfSideslipFunction,\n        const std::function< double( ) > bankAngleFunction,\n        const std::function< void( const double ) > angleUpdateFunction )\n{\n    if( !( angleOfAttackFunction == nullptr ) )\n    {\n        if( !( angleOfAttackFunction_ == nullptr ) )\n        {\n            std::cerr << \"Warning, overriding existing angle of attack function in AerodynamicAngleCalculator\" << std::endl;\n        }\n        angleOfAttackFunction_ = angleOfAttackFunction;\n    }\n\n    if( !( angleOfSideslipFunction == nullptr ) )\n    {\n        if( !( angleOfSideslipFunction_ == nullptr ) )\n        {\n            std::cerr << \"Warning, overriding existing angle of sideslip function in AerodynamicAngleCalculator\" << std::endl;\n        }\n        angleOfSideslipFunction_ = angleOfSideslipFunction;\n    }\n\n    if( !( bankAngleFunction == nullptr ) )\n    {\n        if( !( bankAngleFunction_ == nullptr ) )\n        {\n            std::cerr << \"Warning, overriding existing bank angle function in AerodynamicAngleCalculator\" << std::endl;\n        }\n        bankAngleFunction_ = bankAngleFunction;\n    }\n\n    if( !( angleUpdateFunction == nullptr ) )\n    {\n        if( !( angleUpdateFunction_ == nullptr ) )\n        {\n            std::cerr << \"Warning, overriding existing aerodynamic angle update function in AerodynamicAngleCalculator\" << std::endl;\n        }\n        angleUpdateFunction_ = angleUpdateFunction;\n    }\n}\n\n//! Function to set constant trajectory<->body-fixed orientation angles.\nvoid AerodynamicAngleCalculator::setOrientationAngleFunctions(\n        const double angleOfAttack,\n        const double angleOfSideslip,\n        const double bankAngle )\n{\n    std::function< double( ) > angleOfAttackFunction =\n            ( ( angleOfAttack == angleOfAttack ) ? [ = ]( ){ return angleOfAttack; } : std::function< double( ) >( ) );\n    std::function< double( ) > angleOfSideslipFunction =\n            ( ( angleOfSideslip == angleOfSideslip ) ? [ = ]( ){ return angleOfSideslip; } : std::function< double( ) >( ) );\n    std::function< double( ) > bankAngleFunction =\n            ( ( bankAngle == bankAngle ) ? [ = ]( ){ return bankAngle; }: std::function< double( ) >( ) );\n    setOrientationAngleFunctions( angleOfAttackFunction, angleOfSideslipFunction, bankAngleFunction );\n}\n\n//! Get a function to transform aerodynamic force from local to propagation frame.\nstd::function< Eigen::Vector3d( const Eigen::Vector3d& ) >\ngetAerodynamicForceTransformationFunction(\n        const std::shared_ptr< AerodynamicAngleCalculator > aerodynamicAngleCalculator,\n        const AerodynamicsReferenceFrames accelerationFrame,\n        const std::function< Eigen::Quaterniond( ) > bodyFixedToInertialFrameFunction,\n        const AerodynamicsReferenceFrames propagationFrame )\n{\n    std::function< Eigen::Vector3d( const Eigen::Vector3d& ) > transformationFunction;\n\n    // If propagation frame is the inertial frame, use bodyFixedToInertialFrameFunction.\n    if( propagationFrame == inertial_frame )\n    {\n        std::vector< std::function< Eigen::Vector3d( const Eigen::Vector3d& ) > > rotationsList;\n\n        // Get accelerationFrame to corotating frame transformation.\n        std::function< Eigen::Quaterniond( ) > firstRotation =\n                std::bind( &AerodynamicAngleCalculator::getRotationQuaternionBetweenFrames,\n                             aerodynamicAngleCalculator, accelerationFrame, corotating_frame );\n        rotationsList.push_back(\n                    std::bind( &transformVectorFromQuaternionFunction,\n                                 std::placeholders::_1, firstRotation ) );\n\n        // Add corotating to inertial frame.\n        rotationsList.push_back(\n                    std::bind( &transformVectorFromQuaternionFunction,\n                                 std::placeholders::_1, bodyFixedToInertialFrameFunction ) );\n\n        // Create transformation function.\n        transformationFunction = std::bind( &transformVectorFromVectorFunctions,\n                                              std::placeholders::_1, rotationsList );\n    }\n    else\n    {\n        // Get accelerationFrame to propagationFrame frame transformation directly.\n        std::function< Eigen::Quaterniond( ) > rotationFunction =\n                std::bind( &AerodynamicAngleCalculator::getRotationQuaternionBetweenFrames,\n                             aerodynamicAngleCalculator, accelerationFrame, propagationFrame );\n\n        // Create transformation function.\n        transformationFunction = std::bind( &transformVectorFromQuaternionFunction, std::placeholders::_1,\n                                              rotationFunction );\n    }\n\n    return transformationFunction;\n}\n\n//! Function to update the aerodynamic angles to current time.\nvoid AerodynamicAnglesClosure::updateAngles( const double currentTime )\n{\n    // Retrieve rotation matrix that is to be converted to orientation angles.\n    currentRotationFromBodyToTrajectoryFrame_ =\n            ( ( imposedRotationFromInertialToBodyFixedFrame_( currentTime ).toRotationMatrix( ) *\n                aerodynamicAngleCalculator_->getRotationQuaternionBetweenFrames(\n                    trajectory_frame, inertial_frame ).toRotationMatrix( ) ) ).transpose( );\n\n    // Compute associated Euler angles and set as orientation angles.\n    Eigen::Vector3d eulerAngles = basic_mathematics::get132EulerAnglesFromRotationMatrix(\n                currentRotationFromBodyToTrajectoryFrame_ );\n    currentBankAngle_ = eulerAngles( 0 );\n    currentAngleOfSideslip_ = eulerAngles( 1 );\n    currentAngleOfAttack_ = -eulerAngles( 2 );\n}\n\n//! Function to make aerodynamic angle computation consistent with imposed body-fixed to inertial rotation.\nvoid setAerodynamicDependentOrientationCalculatorClosure(\n        const std::function< Eigen::Quaterniond( const double ) > imposedRotationFromInertialToBodyFixedFrame,\n        std::shared_ptr< AerodynamicAngleCalculator > aerodynamicAngleCalculator )\n{\n    std::shared_ptr< AerodynamicAnglesClosure > aerodynamicAnglesClosure =\n            std::make_shared< AerodynamicAnglesClosure >(\n                imposedRotationFromInertialToBodyFixedFrame, aerodynamicAngleCalculator );\n    aerodynamicAngleCalculator->setOrientationAngleFunctions(\n                std::bind( &AerodynamicAnglesClosure::getCurrentAngleOfAttack, aerodynamicAnglesClosure ),\n                std::bind( &AerodynamicAnglesClosure::getCurrentAngleOfSideslip, aerodynamicAnglesClosure ),\n                std::bind( &AerodynamicAnglesClosure::getCurrentBankAngle, aerodynamicAnglesClosure ),\n                std::bind( &AerodynamicAnglesClosure::updateAngles, aerodynamicAnglesClosure, std::placeholders::_1 ) );\n}\n\n//! Function to make aerodynamic angle computation consistent with existing DependentOrientationCalculator\nvoid setAerodynamicDependentOrientationCalculatorClosure(\n        std::shared_ptr< DependentOrientationCalculator > dependentOrientationCalculator,\n        std::shared_ptr< AerodynamicAngleCalculator > aerodynamicAngleCalculator )\n{\n    std::function< Eigen::Quaterniond( const double ) > imposedRotationFromInertialToBodyFixedFrame =\n            std::bind( &DependentOrientationCalculator::computeAndGetRotationToLocalFrame, dependentOrientationCalculator, std::placeholders::_1 );\n    setAerodynamicDependentOrientationCalculatorClosure(\n                imposedRotationFromInertialToBodyFixedFrame,\n                aerodynamicAngleCalculator );\n}\n\n//! Function to make aerodynamic angle computation consistent with existing rotational ephemeris\nvoid setAerodynamicDependentOrientationCalculatorClosure(\n        std::shared_ptr< ephemerides::RotationalEphemeris > rotationalEphemeris,\n        std::shared_ptr< AerodynamicAngleCalculator > aerodynamicAngleCalculator )\n{\n    setAerodynamicDependentOrientationCalculatorClosure(\n                std::bind( &ephemerides::RotationalEphemeris::getRotationToTargetFrame,\n                             rotationalEphemeris, std::placeholders::_1 ),\n                aerodynamicAngleCalculator );\n}\n\n} // namespace reference_frames\n\n} // namespace tudat\n\n\n\n", "meta": {"hexsha": "6086c2cf6a9024fd9f3d5027c72d5607d0af11a3", "size": 23119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/ReferenceFrames/aerodynamicAngleCalculator.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/ReferenceFrames/aerodynamicAngleCalculator.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/ReferenceFrames/aerodynamicAngleCalculator.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": 42.576427256, "max_line_length": 147, "alphanum_fraction": 0.6134348371, "num_tokens": 4503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.50015173152914}}
{"text": "#include \"refill/measurement_models/linear_measurement_model.h\"\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\nnamespace refill {\n\nclass LinearMeasurementModelTest : public ::testing::Test {\n public:\n  LinearMeasurementModelTest()\n      : measurement_noise_{2},\n        measurement_mapping_{Eigen::Matrix2d::Identity()},\n        noise_mapping_{Eigen::Matrix2d::Identity()} {}\n\n  GaussianDistribution measurement_noise_;\n\n  Eigen::Matrix2d measurement_mapping_;\n  Eigen::Matrix2d noise_mapping_;\n};\n\nTEST_F(LinearMeasurementModelTest, ConstructorTest) {\n  LinearMeasurementModel measurement_model_1;\n\n  EXPECT_EQ(0, measurement_model_1.getStateDim());\n  EXPECT_EQ(0, measurement_model_1.getMeasurementDim());\n  EXPECT_EQ(0, measurement_model_1.getNoiseDim());\n\n  GaussianDistribution measurement_noise(Eigen::Vector2d::Zero(),\n                                         Eigen::Matrix2d::Identity());\n\n  LinearMeasurementModel measurement_model_2(Eigen::Matrix2d::Identity(),\n                                             measurement_noise);\n\n  EXPECT_EQ(2, measurement_model_2.getStateDim());\n  EXPECT_EQ(2, measurement_model_2.getMeasurementDim());\n  EXPECT_EQ(2, measurement_model_2.getNoiseDim());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(),\n            measurement_model_2.getMeasurementMapping());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), measurement_model_2.getNoiseMapping());\n\n  LinearMeasurementModel measurement_model_3(Eigen::Matrix2d::Identity(),\n                                             measurement_noise,\n                                             Eigen::Matrix2d::Ones());\n\n  EXPECT_EQ(2, measurement_model_3.getStateDim());\n  EXPECT_EQ(2, measurement_model_3.getMeasurementDim());\n  EXPECT_EQ(2, measurement_model_3.getNoiseDim());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(),\n            measurement_model_3.getMeasurementMapping());\n  EXPECT_EQ(Eigen::Matrix2d::Ones(), measurement_model_3.getNoiseMapping());\n}\n\nTEST_F(LinearMeasurementModelTest, SetterTest) {\n  GaussianDistribution measurement_noise(Eigen::Vector2d::Zero(),\n                                         Eigen::Matrix2d::Identity());\n\n  LinearMeasurementModel measurement_model;\n\n  measurement_model.setModelParameters(Eigen::Matrix2d::Identity(),\n                                             measurement_noise);\n\n  EXPECT_EQ(2, measurement_model.getStateDim());\n  EXPECT_EQ(2, measurement_model.getMeasurementDim());\n  EXPECT_EQ(2, measurement_model.getNoiseDim());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(),\n            measurement_model.getMeasurementMapping());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), measurement_model.getNoiseMapping());\n\n  measurement_noise.setDistributionParameters(Eigen::Vector3d::Zero(),\n                                              Eigen::Matrix3d::Identity());\n\n  measurement_model.setModelParameters(Eigen::Matrix3d::Identity(),\n                                             measurement_noise,\n                                             Eigen::Matrix3d::Ones());\n\n  EXPECT_EQ(3, measurement_model.getStateDim());\n  EXPECT_EQ(3, measurement_model.getMeasurementDim());\n  EXPECT_EQ(3, measurement_model.getNoiseDim());\n  EXPECT_EQ(Eigen::Matrix3d::Identity(),\n            measurement_model.getMeasurementMapping());\n  EXPECT_EQ(Eigen::Matrix3d::Ones(), measurement_model.getNoiseMapping());\n}\n\nTEST_F(LinearMeasurementModelTest, GetterTest) {\n  GaussianDistribution measurement_noise(Eigen::Vector2d::Zero(),\n                                         Eigen::Matrix2d::Identity());\n\n  LinearMeasurementModel measurement_model(Eigen::Matrix2d::Identity(),\n                                           measurement_noise,\n                                           Eigen::Matrix2d::Ones());\n\n  EXPECT_EQ(Eigen::Matrix2d::Identity(),\n            measurement_model.getMeasurementMapping());\n  EXPECT_EQ(Eigen::Matrix2d::Ones(), measurement_model.getNoiseMapping());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(),\n            measurement_model.getMeasurementJacobian(Eigen::Vector2d::Zero()));\n  EXPECT_EQ(Eigen::Matrix2d::Ones(),\n            measurement_model.getNoiseJacobian(Eigen::Vector2d::Zero()));\n}\n\nTEST_F(LinearMeasurementModelTest, ObservationTest) {\n  GaussianDistribution measurement_noise(Eigen::Vector2d::Zero(),\n                                         Eigen::Matrix2d::Identity());\n\n  LinearMeasurementModel measurement_model(Eigen::Matrix2d::Identity(),\n                                           measurement_noise,\n                                           Eigen::Matrix2d::Ones());\n\n  EXPECT_EQ(\n      Eigen::Vector2d::Constant(3.0),\n      measurement_model.observe(Eigen::Vector2d::Ones(),\n                                Eigen::Vector2d::Ones()));\n}\n\nTEST_F(LinearMeasurementModelTest, GetLikelihoodTest) {\n  LinearMeasurementModel measurement_model(measurement_mapping_,\n                                           measurement_noise_,\n                                           noise_mapping_);\n\n  Eigen::Vector2d measurement{Eigen::Vector2d::Constant(1)};\n  Eigen::Vector2d state{Eigen::Vector2d::Constant(1)};\n\n  double expected_likelihood{1.0 / (2.0 * M_PI)};\n\n  EXPECT_EQ(expected_likelihood,\n            measurement_model.getLikelihood(state, measurement));\n}\n\nTEST_F(LinearMeasurementModelTest, GetLikelihoodVectorizedTest) {\n  LinearMeasurementModel measurement_model(measurement_mapping_,\n                                           measurement_noise_,\n                                           noise_mapping_);\n\n  Eigen::Vector2d measurement{Eigen::Vector2d::Constant(1)};\n  Eigen::Matrix2d sampled_state{Eigen::Matrix2d::Constant(1)};\n\n  Eigen::Vector2d expected_likelihood{\n      Eigen::Vector2d::Constant(1.0 / (2 * M_PI))};\n\n  EXPECT_EQ(expected_likelihood, measurement_model.getLikelihoodVectorized(\n                                     sampled_state, measurement));\n}\n\n}  // namespace refill\n", "meta": {"hexsha": "75f1a954749cf8243f5674d18087f7f89c54d7f0", "size": 5825, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/linear_measurement_model_test.cc", "max_stars_repo_name": "jwidauer/refill", "max_stars_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-13T07:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T11:26:34.000Z", "max_issues_repo_path": "src/tests/linear_measurement_model_test.cc", "max_issues_repo_name": "jwidauer/refill", "max_issues_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/linear_measurement_model_test.cc", "max_forks_repo_name": "jwidauer/refill", "max_forks_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T13:21:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T20:33:20.000Z", "avg_line_length": 40.1724137931, "max_line_length": 80, "alphanum_fraction": 0.6528755365, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.50015173152914}}
{"text": "// Copyright (c) 2005-2009  INRIA Sophia-Antipolis (France).\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org)\n//\n// $URL$\n// $Id$\n// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial\n//\n//\n// Author(s)     : Sebastien Loriot, Sylvain Pion\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/CGAL_Ipelet_base.h>\n#include <CGAL/Regular_triangulation_2.h>\n#include <CGAL/Constrained_Delaunay_triangulation_2.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Alpha_shape_2.h>\n#include <CGAL/Alpha_shape_face_base_2.h>\n#include <CGAL/Alpha_shape_vertex_base_2.h>\n#include <boost/format.hpp>\n\n\nnamespace CGAL_alpha_shapes{\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel       Kernel;\ntypedef CGAL::Regular_triangulation_vertex_base_2<Kernel>         Rvb;\ntypedef CGAL::Alpha_shape_vertex_base_2<Kernel,Rvb>               Vb;\ntypedef CGAL::Regular_triangulation_face_base_2<Kernel>           Rf;\ntypedef CGAL::Alpha_shape_face_base_2<Kernel,Rf>                  Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb,Fb>               Tds;\ntypedef CGAL::Regular_triangulation_2<Kernel,Tds>                 Regular;\ntypedef CGAL::Alpha_shape_2<Regular>                              Alpha_shape_2;\n\nconst std::string  sublabel[] = {\n  \"k-th Alpha-shape\", \"Help\"\n};\n\nconst std::string  helpmsg[] = {\n  \"Draw alpha-shape for the k-th critical alpha value\"\n};\n\n\nclass ASphapeIpelet\n  : public CGAL::Ipelet_base<Kernel,2> {\npublic:\n  ASphapeIpelet()\n    : CGAL::Ipelet_base<Kernel,2>(\"Alpha-shapes\",sublabel,helpmsg){}\n  void protected_run(int);\n};\n\n\nvoid ASphapeIpelet::protected_run(int fn)\n{\n  if (fn==1) {\n    show_help();\n    return;\n  }\n\n  std::list<Weighted_point_2> LWP;\n\n  std::list<Circle_2> cir_list;\n  std::list<Point_2> pt_list;\n\n\n\n\n  read_active_objects(\n    CGAL::dispatch_or_drop_output<Point_2,Circle_2>(std::back_inserter(pt_list),\n                                                    std::back_inserter(cir_list))\n  );\n\n\n  if (pt_list.empty() && cir_list.empty()) {\n    print_error_message(\"No circle nor point selected\");\n    return;\n  }\n\n\n  for (std::list<Point_2>::iterator it=pt_list.begin();it!=pt_list.end();++it)\n    LWP.push_back(Weighted_point_2(*it,0));\n  for (std::list<Circle_2>::iterator it=cir_list.begin();it!=cir_list.end();++it)\n    LWP.push_back(Weighted_point_2(it->center(),it->squared_radius()));\n\n  Alpha_shape_2 A(LWP.begin(),LWP.end());\n  int alpha=-1;\n  int nb_ret;\n  boost::tie(nb_ret,alpha)=request_value_from_user<int>((boost::format(\"# Spectral critical value (0-%d)\") % A.number_of_alphas()).str() );\n  if (nb_ret == -1) return;\n\n  if(alpha<0 || (std::size_t) alpha>A.number_of_alphas()){\n    print_error_message(\"Not a good value\");\n    return;\n  }\n\n\n  A.set_alpha(alpha==0?(std::max)(std::numeric_limits<double>::epsilon(),A.get_nth_alpha(0)/2.):\n              (std::size_t) alpha==A.number_of_alphas()?A.get_nth_alpha(alpha-1)+1:A.get_nth_alpha(alpha-1)/2.+A.get_nth_alpha(alpha)/2.);\n  for ( Alpha_shape_2::Alpha_shape_edges_iterator it=A.alpha_shape_edges_begin();it!=A.alpha_shape_edges_end();++it)\n    draw_in_ipe(A.segment(*it));\n\n  for (Alpha_shape_2::Finite_faces_iterator it=A.finite_faces_begin();it!=A.finite_faces_end();++it){\n    if (A.classify(it)==Alpha_shape_2::INTERIOR){\n      std::list<Point_2> LP;\n      LP.push_back(Point_2(it->vertex(0)->point()));\n      LP.push_back(Point_2(it->vertex(1)->point()));\n      LP.push_back(Point_2(it->vertex(2)->point()));\n      draw_polyline_in_ipe(LP.begin(),LP.end(),true,false,true);\n    }\n  }\n  group_selected_objects_();\n  return;\n}\n\n}\n\n\nCGAL_IPELET(CGAL_alpha_shapes::ASphapeIpelet)\n\n\n", "meta": {"hexsha": "f5423b0ab1967151ef21066953816f81d225314c", "size": 3673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CGAL_ipelets/demo/CGAL_ipelets/alpha_shapes.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "CGAL_ipelets/demo/CGAL_ipelets/alpha_shapes.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "CGAL_ipelets/demo/CGAL_ipelets/alpha_shapes.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.3553719008, "max_line_length": 139, "alphanum_fraction": 0.6869044378, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5001517265603189}}
{"text": "#ifndef LIBRE_BOOK_MATRIX\n#define LIBRE_BOOK_MATRIX\n\n#include <iostream>\n#include <vector>\n#include <map>\n#include <string>\n#include <fstream>\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"primes/primes.hpp\"\n\nusing namespace boost::multiprecision;\ntypedef number<cpp_int_backend<2048, 2048, unsigned_magnitude, unchecked, void>> uint2048_t;\n\nnamespace Libre {\n\tclass BookMatrix {\n\t\tprivate:\n\t\t\tstd::map<std::string, uint2048_t> words;\n\t\t\tstd::vector<uint2048_t> matrix;\n\t\t\tLibre::Primes primes;\n\t\tpublic:\n\t\t\tBookMatrix(const std::string &);\n\t\t\tBookMatrix() = default;\n\t\t\t~BookMatrix() = default;\n\t\t\tvoid load_file(const std::string &);\n\t\t\tconst std::map<std::string, uint2048_t> & get_words();\n\t\t\tbool verse_has_word(const std::string &, const size_t &);\n\t\t\tbool verse_has_mod_index(const uint2048_t &, const size_t &);\n\t};\n}\n\n#endif\n", "meta": {"hexsha": "46c53b9eef3628ff0a8eb63edee31c9d055cb655", "size": 843, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/book_matrix/book_matrix.hpp", "max_stars_repo_name": "LibreTextus/LibreTextus", "max_stars_repo_head_hexsha": "a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-08-26T06:18:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-16T17:22:29.000Z", "max_issues_repo_path": "src/book_matrix/book_matrix.hpp", "max_issues_repo_name": "LibreTextus/LibreTextus", "max_issues_repo_head_hexsha": "a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3", "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/book_matrix/book_matrix.hpp", "max_forks_repo_name": "LibreTextus/LibreTextus", "max_forks_repo_head_hexsha": "a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7941176471, "max_line_length": 92, "alphanum_fraction": 0.7283511269, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5001517215914977}}
{"text": "#ifndef PYTHONIC_INCLUDE_NUMPY_SQRT_HPP\n#define PYTHONIC_INCLUDE_NUMPY_SQRT_HPP\n\n#include \"pythonic/include/utils/functor.hpp\"\n#include \"pythonic/include/types/ndarray.hpp\"\n#include \"pythonic/include/utils/numpy_traits.hpp\"\n\n#include <boost/simd/function/sqrt.hpp>\n#include <cmath>\n\nPYTHONIC_NS_BEGIN\n\nnamespace numpy\n{\n  namespace wrapper\n  {\n    template <class T>\n    std::complex<T> sqrt(std::complex<T> const &val)\n    {\n      return std::sqrt(val);\n    }\n    template <class T>\n    auto sqrt(T const &val) -> decltype(boost::simd::sqrt(val))\n    {\n      return boost::simd::sqrt(val);\n    }\n  }\n\n#define NUMPY_NARY_FUNC_NAME sqrt\n#define NUMPY_NARY_FUNC_SYM wrapper::sqrt\n#include \"pythonic/include/types/numpy_nary_expr.hpp\"\n}\nPYTHONIC_NS_END\n\n#endif\n", "meta": {"hexsha": "72a745599d1b7623cd72f19bbfc1407c7974e399", "size": 758, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pythran/pythonic/include/numpy/sqrt.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-24T00:33:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-24T00:33:03.000Z", "max_issues_repo_path": "pythran/pythonic/include/numpy/sqrt.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": "pythran/pythonic/include/numpy/sqrt.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "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.0555555556, "max_line_length": 63, "alphanum_fraction": 0.72823219, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5001517215914976}}
{"text": "#include <cmath>\n#include \"../include/array.h\"\n#include <iostream>\n#include \"GPU_Advection.h\"\n#include \"BimocqSolver.h\"\n#include <boost/filesystem.hpp>\n\nint main(int argc, char** argv) {\n    uint ni;\n    uint nj;\n    uint nk;\n    uint total_frame;\n    float L;\n    float h;\n    float dt;\n    float mapping_blend_coeff;\n    float viscosity;\n    float half_width;\n    float smoke_rise;\n    float smoke_drop;\n    Scheme sim_scheme;\n    string filepath = \"../Out\";\n    boost::filesystem::create_directories(filepath);\n\n    std::vector<Emitter> emitter_list;\n    std::vector<Boundary> boundary_list;\n\n    // 3D vortex collision example setup\n    if (1)\n    {\n        // simulation resolution\n\t    ni = 100;\n\t    nj = 200;\n\t    nk = 200;\n\t    total_frame = 300;\n\t    // length in x direction\n\t    L = 0.2f;\n\t    // grid size for simulation\n\t    h = L / ni;\n\t    // time step\n\t    dt = 0.08f;\n\t    // smoke properties\n\t    smoke_rise = 0.f;\n\t    smoke_drop = 0.f;\n\t    viscosity = 1.0*1e-6;\n\t    // blend coefficient that will blend 1-level mapping result with 2-level mapping result\n        // phi_t = blend_coeff * phi_curr + (1 - blend_coeff) * phi_prev\n        mapping_blend_coeff = 1.f;\n        // levelset half width, used when blending semi-lagrangian result near the boundary\n        half_width = 3.f;\n        // simulation scheme, semi-lagrangian, MacCormack, Reflection and BIMOCQ are implemented\n        sim_scheme = BIMOCQ;\n        auto vel_func_a = [](Vec3f pos)\n        {\n            Vec3f center(0.04f, 0.2f, 0.2f);\n            Vec2f dir = Vec2f(pos[1] - center[1], pos[2] - center[2]);\n            dir = normalized(dir);\n            float theta = acos(dot(dir, Vec2f(1.f, 0.f)));\n            float vel_x = 0.06f*(1.0f + 0.01f*cos(8.f*theta));\n            float vel_y = 0.f;\n            float vel_z = 0.f;\n            return Vec3f(vel_x, vel_y, vel_z);\n        };\n        auto vel_func_b = [](Vec3f pos)\n        {\n            Vec3f center(0.16f, 0.201f, 0.2f);\n            Vec2f dir = Vec2f(pos[1] - center[1], pos[2] - center[2]);\n            dir = normalized(dir);\n            float theta = acos(dot(dir, Vec2f(1.f, 0.f)));\n            float vel_x = -0.06f*(1.0f + 0.01f*cos(8.f*theta));\n            float vel_y = 0.f;\n            float vel_z = 0.f;\n            return Vec3f(vel_x, vel_y, vel_z);\n        };\n        openvdb::FloatGrid::Ptr sphere_sdf_a = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>(0.015f, openvdb::Vec3f(0.f,0.f,0.f), h, half_width);\n        openvdb::FloatGrid::Ptr sphere_sdf_b = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>(0.015f, openvdb::Vec3f(0.f,0.f,0.f), h, half_width);\n        Emitter e_sphere_a(10, 1.f, 50.f, Vec3f(0.04f, 0.2f, 0.2f), sphere_sdf_a, [](float frame)->Vec3f{return Vec3f(0.f, 0.f, 0.f);}, vel_func_a);\n        Emitter e_sphere_b(10, 1.f, 50.f, Vec3f(0.16f, 0.201f, 0.2f), sphere_sdf_b, [](float frame)->Vec3f{return Vec3f(0.f, 0.f, 0.f);}, vel_func_b);\n        emitter_list.push_back(e_sphere_a);\n        emitter_list.push_back(e_sphere_b);\n    }\n\n\tauto *myGPUmapper = new gpuMapper(ni, nj, nk, h);\n\tBimocqSolver mysolver(ni, nj, nk, L, viscosity, mapping_blend_coeff, sim_scheme, myGPUmapper);\n\tmysolver.setSmoke(smoke_rise, smoke_drop, emitter_list);\n    mysolver.setBoundary(boundary_list);\n\tfor (uint i = 0; i < total_frame; i++)\n\t{\n        cout << \"Frame \" << i << \" Starts !!!\" << std::endl;\n\t    mysolver.updateBoundary(i, dt);\n\t\tmysolver.advance(i, dt);\n        mysolver.outputResult(i, filepath);\n    }\n\treturn 0;\n}", "meta": {"hexsha": "35bbfe92ae1ff729455a98e3ad367f490c02413f", "size": 3503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bimocq3D/main.cpp", "max_stars_repo_name": "ziyinq/Bimocq", "max_stars_repo_head_hexsha": "39c6f5779a11d67d67c39138f0e254158d210068", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 343.0, "max_stars_repo_stars_event_min_datetime": "2019-06-28T15:08:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T04:54:47.000Z", "max_issues_repo_path": "src/bimocq3D/main.cpp", "max_issues_repo_name": "lwkobe/Bimocq", "max_issues_repo_head_hexsha": "39c6f5779a11d67d67c39138f0e254158d210068", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-06-29T09:32:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-08T23:10:02.000Z", "max_forks_repo_path": "src/bimocq3D/main.cpp", "max_forks_repo_name": "lwkobe/Bimocq", "max_forks_repo_head_hexsha": "39c6f5779a11d67d67c39138f0e254158d210068", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 69.0, "max_forks_repo_forks_event_min_datetime": "2019-07-10T00:46:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T09:06:21.000Z", "avg_line_length": 36.8736842105, "max_line_length": 156, "alphanum_fraction": 0.6000570939, "num_tokens": 1106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5001517215914976}}
{"text": "#pragma once\n\n#include \"deom.hpp\"\n#include \"algebra.hpp\"\n#include <Eigen/Eigenvalues>\n#include <experimental/random>\n\n// syl\uff1a solve syl equation AX-XB=C\n// note here A and B are both hermmitian, so it canbe deocomposite to URU^T VSV^T where R and S are diag matrices, the equation then canbe convert to URU^TX-XVSV^T=C multi U^T on left and V on right so we can get RU^TXV-U^TXVS=U^TCV, denote U^TXV as Y and U^TCV as D,so \\sum_j (R_ij Y_jk - Y_ij S_jk) = D_ik and note that R and S are diag matrices so R_ii Y_ik - Y_ik S_kk = D_ik.\n// SelfAdjointEigenSolver(A,B) -> R S U V\n// Y_ik = (U^TCV)_ik / (R_ii - S_kk)\n// X = UYV^T\n// check AX-XB=C\n// note that syl_complex will deal with no SelfAdjoint situation, but we will no use that in normal scenario.\n// pref\n// syl :1Gflops 10000000 at 3.6s\n// syl_debug :1Gflops 10000000 at 3.85s\n// syl_complex :2Gflops 10000000 at 5.4s\n\nvoid syl(MatrixNcd &X, MatrixNcd &A, MatrixNcd &B, MatrixNcd &C) {\n  SelfAdjointEigenSolver<MatrixNcd> eigensolverA(A);\n  SelfAdjointEigenSolver<MatrixNcd> eigensolverB(B);\n  auto R = eigensolverA.eigenvalues();\n  auto S = eigensolverB.eigenvalues();\n  MatrixNcd U = eigensolverA.eigenvectors();\n  MatrixNcd V = eigensolverB.eigenvectors();\n  MatrixNcd Y = MatrixNcd::Zero();\n  MatrixNcd D = U.transpose() * C * V;\n\n  for (int i = 0; i < NSYS; i++) {\n    for (int j = 0; j < NSYS; j++) {\n      Y(i, j) = D(i, j) / (R(i) - S(j));\n    }\n  }\n  X = U * Y * V.transpose();\n}\n\nvoid syl_debug(MatrixNcd &X, MatrixNcd &A, MatrixNcd &B, MatrixNcd &C) {\n  SelfAdjointEigenSolver<MatrixNcd> eigensolverA(A);\n  SelfAdjointEigenSolver<MatrixNcd> eigensolverB(B);\n  if (eigensolverA.info() != Success || eigensolverB.info() != Success)\n    abort();\n  auto R = eigensolverA.eigenvalues();\n  auto S = eigensolverB.eigenvalues();\n  MatrixNcd U = eigensolverA.eigenvectors();\n  MatrixNcd V = eigensolverB.eigenvectors();\n  MatrixNcd Y = MatrixNcd::Zero();\n  MatrixNcd D = U.transpose() * C * V;\n\n  for (int i = 0; i < NSYS; i++) {\n    for (int j = 0; j < NSYS; j++) {\n      Y(i, j) = D(i, j) / (R(i) - S(j));\n    }\n  }\n  X = U * Y * V.transpose();\n  if (is_valid(A * X - X * B - C)) {\n    exit(1);\n  }\n}\n\nvoid syl_complex(MatrixNcd &X, MatrixNcd &A, MatrixNcd &B, MatrixNcd &C) {\n  ComplexEigenSolver<MatrixNcd> eigensolverA(A);\n  ComplexEigenSolver<MatrixNcd> eigensolverB(B);\n  auto R = eigensolverA.eigenvalues();\n  auto S = eigensolverB.eigenvalues();\n  MatrixNcd U = eigensolverA.eigenvectors();\n  MatrixNcd V = eigensolverB.eigenvectors();\n  MatrixNcd Y = MatrixNcd::Zero();\n  MatrixNcd D = U.inverse() * C * V;\n\n  for (int i = 0; i < NSYS; i++) {\n    for (int j = 0; j < NSYS; j++) {\n      Y(i, j) = D(i, j) / (R(i) - S(j));\n    }\n  }\n  X = U * Y * V.inverse();\n}\n\nvoid syl_complex_debug(MatrixNcd &X, MatrixNcd &A, MatrixNcd &B, MatrixNcd &C) {\n  ComplexEigenSolver<MatrixNcd> eigensolverA(A);\n  ComplexEigenSolver<MatrixNcd> eigensolverB(B);\n  if (eigensolverA.info() != Success || eigensolverB.info() != Success)\n    abort();\n  auto R = eigensolverA.eigenvalues();\n  auto S = eigensolverB.eigenvalues();\n  MatrixNcd U = eigensolverA.eigenvectors();\n  MatrixNcd V = eigensolverB.eigenvectors();\n  MatrixNcd Y = MatrixNcd::Zero();\n  MatrixNcd D = U.inverse() * C * V;\n\n  for (int i = 0; i < NSYS; i++) {\n    for (int j = 0; j < NSYS; j++) {\n      Y(i, j) = D(i, j) / (R(i) - S(j));\n    }\n  }\n  X = U * Y * V.inverse();\n  if (is_valid(A * X - X * B - C)) {\n    exit(1);\n  }\n}\n\n// int main(int argc, const char **argv) {\n//   MatrixNcd A;\n//   MatrixNcd B;\n//   MatrixNcd C;\n//   MatrixNcd X;\n//   std::srand(std::time(0));\n//   A(0, 0) = std::experimental::randint(-999, 999);\n//   A(1, 1) = std::experimental::randint(-999, 999);\n//   A(0, 1) = std::experimental::randint(-999, 999);\n//   A(1, 0) = A(0, 1);\n\n//   B(0, 0) = std::experimental::randint(-999, 999);\n//   B(1, 1) = std::experimental::randint(-999, 999);\n//   B(0, 1) = std::experimental::randint(-999, 999);\n//   B(1, 0) = B(0, 1);\n\n//   C(0, 0) = (double)std::experimental::randint(-999, 999) + (complex<double>)1i * (double)std::experimental::randint(-999, 999);\n//   C(1, 1) = (double)std::experimental::randint(-999, 999) + (complex<double>)1i * (double)std::experimental::randint(-999, 999);\n//   C(0, 1) = (double)std::experimental::randint(-999, 999) + (complex<double>)1i * (double)std::experimental::randint(-999, 999);\n//   C(1, 0) = (double)std::experimental::randint(-999, 999) + (complex<double>)1i * (double)std::experimental::randint(-999, 999);\n//   for (size_t i = 0; i < 10000000; i++) {\n//     syl_complex(X, A, B, C);\n//   }\n//   return 0;\n// }\n", "meta": {"hexsha": "25ac9fd9db34981e1718249e705c83b048629263", "size": 4594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bose/1d-corr/linearalgebra.hpp", "max_stars_repo_name": "chem12346789/deom_mpi", "max_stars_repo_head_hexsha": "66b03eb5855e31b587368bb42c5897c3829e1fa0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-21T11:01:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T11:01:52.000Z", "max_issues_repo_path": "fermi/1d-corr/linearalgebra.hpp", "max_issues_repo_name": "chem12346789/deom_mpi", "max_issues_repo_head_hexsha": "66b03eb5855e31b587368bb42c5897c3829e1fa0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fermi/1d-corr/linearalgebra.hpp", "max_forks_repo_name": "chem12346789/deom_mpi", "max_forks_repo_head_hexsha": "66b03eb5855e31b587368bb42c5897c3829e1fa0", "max_forks_repo_licenses": ["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.1732283465, "max_line_length": 380, "alphanum_fraction": 0.6236395298, "num_tokens": 1721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5001484504562307}}
{"text": "/*\n *  Distributed under the MIT License (See accompanying file /LICENSE )\n */\n#include \"recti/recti.hpp\"\n// #include <boost/multiprecision/cpp_int.hpp>\n#include <doctest/doctest.h>\n#include <iostream>\n\nusing namespace recti;\n\nTEST_CASE(\"vector2\")\n{\n    // using boost::multiprecision::cpp_int;\n    // static_assert(Integral<cpp_int>);\n    const auto a = 3;\n    const auto b = 4;\n    const auto c = 5;\n    const auto d = 6;\n    // const auto f = -30;\n    // const auto g = 4;\n    // const auto z = 0;\n    // const auto h = -g;\n\n    const auto p = vector2 {a, b};\n    const auto q = vector2 {c, d};\n\n    CHECK(vector2 {8, 10} == (p + q));\n    CHECK(vector2 {-2, -2} == (p - q));\n    CHECK(vector2 {6, 8} == (p * 2));\n    CHECK(vector2 {4, 5} == (p + q) / 2);\n    CHECK(p != q);\n}\n", "meta": {"hexsha": "f31b6f121323c601793e543d9ec8e446d37db139", "size": 779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/test/src/test_vector2.cpp", "max_stars_repo_name": "luk036/physdes", "max_stars_repo_head_hexsha": "1a6a6c06a92798cc36d5efd70a968f545d406568", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-30T04:51:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-30T04:51:25.000Z", "max_issues_repo_path": "lib/test/src/test_vector2.cpp", "max_issues_repo_name": "luk036/physdes", "max_issues_repo_head_hexsha": "1a6a6c06a92798cc36d5efd70a968f545d406568", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-19T10:28:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-11T04:11:51.000Z", "max_forks_repo_path": "lib/test/src/test_vector2.cpp", "max_forks_repo_name": "luk036/physdes", "max_forks_repo_head_hexsha": "1a6a6c06a92798cc36d5efd70a968f545d406568", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-11T05:12:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-11T05:12:37.000Z", "avg_line_length": 23.6060606061, "max_line_length": 71, "alphanum_fraction": 0.567394095, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5001484411488918}}
{"text": "//==================================================================================================\n/*!\n  @file\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_ARCH_COMMON_SIMD_FUNCTION_ERFC_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_ERFC_HPP_INCLUDED\n\n#include <boost/simd/arch/common/detail/generic/erf_kernel.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/constant/zero.hpp>\n\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/if_zero_else.hpp>\n#include <boost/simd/function/is_equal.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/logical_andnot.hpp>\n#include <boost/simd/function/oneminus.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/nbtrue.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/constant/inf.hpp>\n#endif\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD_IF ( erfc_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::double_<A0>, X>\n                          )\n  {\n    A0 operator() (const A0& a0) const BOOST_NOEXCEPT\n    {\n      A0 x =  bs::abs(a0);\n      A0 xx =  bs::sqr(x);\n      A0 lim1 = A0(0.65);\n      A0 lim2 = A0(2.2);\n      auto test0 = bs::is_ltz(a0);\n      auto test1 = bs::is_less(x, lim1);\n      A0 r1 = bs::Zero<A0>();\n      std::size_t nb = bs::nbtrue(test1);\n      if(nb > 0)\n      {\n        r1 = bs::oneminus(x*detail::erf_kernel<A0>::erf1(xx));\n        if (nb >= A0::static_size)\n          return bs::if_else(test0, bs::Two<A0>()-r1, r1);\n      }\n      auto test2 = bs::is_less(x, lim2);\n      auto test3 = bs::logical_andnot(test2, test1);\n      A0 ex = bs::exp(-xx);\n\n      std::size_t nb1 = bs::nbtrue(test3);\n      if(nb1 > 0)\n      {\n        A0 z = ex*detail::erf_kernel<A0>::erfc2(x);\n        r1 = bs::if_else(test1, r1, z);\n        nb += nb1;\n        if (nb >= A0::static_size)\n          return bs::if_else(test0, Two<A0>()-r1, r1);\n      }\n      A0 z =  ex*detail::erf_kernel<A0>::erfc3(x);\n      r1 = bs::if_else(test2, r1, z);\n#ifndef BOOST_SIMD_NO_INFINITIES\n      r1 = if_zero_else( is_equal(x, Inf<A0>()), r1);\n#endif\n      return  bs::if_else(test0, bs::Two<A0>()-r1, r1);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( erfc_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::single_<A0>, X>\n                          )\n  {\n    A0 operator() (const A0& a0) const BOOST_NOEXCEPT\n    {\n      A0 x =  bs::abs(a0);\n      auto test0 = bs::is_ltz(a0);\n      A0 r1 = bs::Zero<A0>();\n      auto test1 = bs::is_less(x, bs::Ratio<A0, 2, 3>());\n      A0 z = x/inc(x);\n\n      std::size_t nb = bs::nbtrue(test1);\n      if(nb > 0)\n      {\n        r1 = detail::erf_kernel<A0>::erfc3(z);\n        if (nb >= A0::static_size)\n          return bs::if_else(test0, bs::Two<A0>()-r1, r1);\n      }\n      z -= A0(0.4);\n      A0 r2 = exp(-sqr(x))*detail::erf_kernel<A0>::erfc2(z);\n      r1 = if_else(test1, r1, r2);\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      r1 = if_zero_else( is_equal(x, Inf<A0>()), r1);\n      #endif\n      return bs::if_else(test0, bs::Two<A0>()-r1, r1);\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "b73dd21ec98856f9444d64dafca3400098fdb105", "size": 4004, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/erfc.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/arch/common/simd/function/erfc.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/arch/common/simd/function/erfc.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": 32.8196721311, "max_line_length": 100, "alphanum_fraction": 0.5549450549, "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.500148436495222}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n\n#include <Eigen/LU>\n\n// N.B. this would equally work with Eigen-types that are not predefined. For example replacing\n// all occurrences of \"Eigen::MatrixXd\" with \"MatD\", with the following definition:\n//\n//  typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatD;\n\n// ----------------\n// regular C++ code\n// ----------------\n\nEigen::MatrixXd inv(const Eigen::MatrixXd &xs)\n{\n  return xs.inverse();\n}\n\ndouble det(const Eigen::MatrixXd &xs)\n{\n  return xs.determinant();\n}\n\n// ----------------\n// Python interface\n// ----------------\n\nnamespace py = pybind11;\n\nPYBIND11_MODULE(example,m)\n{\n  m.doc() = \"pybind11 example plugin\";\n\n  m.def(\"inv\", &inv);\n\n  m.def(\"det\", &det);\n}\n", "meta": {"hexsha": "f4c6f71bfd592d9263946c9c24787f5f9411fcd2", "size": 763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "05_numpy-2D_cpp-eigen/example.cpp", "max_stars_repo_name": "oldboldpilot/pybind11_examples", "max_stars_repo_head_hexsha": "dcc5aa26f151013298541d28976d17579af3fe27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 430.0, "max_stars_repo_stars_event_min_datetime": "2017-05-31T05:02:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:17:20.000Z", "max_issues_repo_path": "05_numpy-2D_cpp-eigen/example.cpp", "max_issues_repo_name": "oldboldpilot/pybind11_examples", "max_issues_repo_head_hexsha": "dcc5aa26f151013298541d28976d17579af3fe27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-01-31T00:46:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T07:05:25.000Z", "max_forks_repo_path": "05_numpy-2D_cpp-eigen/example.cpp", "max_forks_repo_name": "oldboldpilot/pybind11_examples", "max_forks_repo_head_hexsha": "dcc5aa26f151013298541d28976d17579af3fe27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 69.0, "max_forks_repo_forks_event_min_datetime": "2017-09-06T03:22:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T09:17:21.000Z", "avg_line_length": 19.5641025641, "max_line_length": 95, "alphanum_fraction": 0.622542595, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5001117627520458}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2013   MetaScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <boost/simd/sdk/simd/native.hpp>\n#include <boost/simd/include/functions/multiplies.hpp>\n#include <boost/simd/include/functions/plus.hpp>\n#include <boost/simd/include/functions/fma.hpp>\n#include <boost/simd/include/functions/sqr.hpp>\n#include <boost/simd/include/functions/splat.hpp>\n#include <boost/simd/include/constants/real_splat.hpp>\n#include <nt2/polynomials/functions/scalar/impl/horner.hpp>\n\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n\ntypedef float T;\ntypedef boost::simd::native<T, BOOST_SIMD_DEFAULT_EXTENSION> vT;\ntypedef vT::native_type nT;\n#define C0 0x3c19c53b\n#define C1 0x3b4c779c\n#define C2 0x3cc821b5\n#define C3 0x3d5ac5c9\n#define C4 0x3e0896dd\n\nextern \"C\"\n{\n\n/* horner0_case:\n *   vmulps  .LC0(%rip), %ymm0, %ymm1\n *   vaddps  .LC1(%rip), %ymm1, %ymm1\n *   vmulps  %ymm1, %ymm0, %ymm1\n *   vaddps  .LC2(%rip), %ymm1, %ymm1\n *   vmulps  %ymm1, %ymm0, %ymm1\n *   vaddps  .LC3(%rip), %ymm1, %ymm1\n *   vmulps  %ymm1, %ymm0, %ymm0\n *   vaddps  .LC4(%rip), %ymm0, %ymm0\n *   ret\n */\nBOOST_FORCEINLINE vT horner0_case_impl(vT const& x)\n{\n  return nt2::horner< NT2_HORNER_COEFF(T, 5, (C0, C1, C2, C3, C4)) >(x);\n}\nBOOST_NOINLINE nT horner0_case(nT x_)\n{\n  vT x = x_;\n  return horner0_case_impl(x);\n}\n\nBOOST_FORCEINLINE vT horner1_case_impl(vT const& x)\n{\n  using boost::simd::fma;\n  using boost::simd::single_constant;\n  return fma(x, fma(x, fma(x, fma(x, single_constant<vT, C0>(), single_constant<vT, C1>()), single_constant<vT, C2>()), single_constant<vT, C3>()), single_constant<vT, C4>());\n}\nBOOST_NOINLINE nT horner1_case(nT x_)\n{\n  vT x = x_;\n  return horner1_case_impl(x);\n}\n\nBOOST_FORCEINLINE vT horner2_case_impl(vT const& x)\n{\n  using boost::simd::fma;\n  using boost::simd::single_constant;\n\n  vT y = single_constant<vT, C0>();\n  vT c = single_constant<vT, C1>();\n\n  y = fma(x, y, c);\n  c = single_constant<vT, C2>();\n  y = fma(x, y, c);\n  c = single_constant<vT, C3>();\n  y = fma(x, y, c);\n  c = single_constant<vT, C4>();\n  y = fma(x, y, c);\n\n  return y;\n}\nBOOST_NOINLINE nT horner2_case(nT x_)\n{\n  vT x = x_;\n  return horner2_case_impl(x);\n}\n\n/* estrin_case:\n *   vmulps  .LC1(%rip), %ymm0, %ymm1\n *   vmulps  .LC3(%rip), %ymm0, %ymm2\n *   vmulps  %ymm0, %ymm0, %ymm0\n *   vaddps  .LC2(%rip), %ymm1, %ymm1\n *   vaddps  .LC4(%rip), %ymm2, %ymm2\n *   vmulps  %ymm1, %ymm0, %ymm1\n *   vmulps  %ymm0, %ymm0, %ymm0\n *   vaddps  %ymm2, %ymm1, %ymm1\n *   vmulps  .LC0(%rip), %ymm0, %ymm0\n *   vaddps  %ymm1, %ymm0, %ymm0\n *   ret\n */\nBOOST_FORCEINLINE vT estrin_case_impl(vT const& x)\n{\n  using boost::simd::fma;\n  using boost::simd::sqr;\n  using boost::simd::single_constant;\n\n  return fma(sqr(x)*sqr(x), single_constant<vT, C0>(), fma(sqr(x), fma(x, single_constant<vT, C1>(), single_constant<vT, C2>()), fma(x, single_constant<vT, C3>(), single_constant<vT, C4>())));\n}\nBOOST_NOINLINE nT estrin_case(nT x_)\n{\n  vT x = x_;\n  return estrin_case_impl(x);\n}\n\n}\n\nNT2_TEST_CASE(consistency_test)\n{\n  vT x = boost::simd::splat<vT>(10.2);\n\n  vT y1 = horner0_case(x);\n  vT y2 = horner1_case(x);\n  vT y3 = horner2_case(x);\n  vT y4 = estrin_case(x);\n\n  NT2_TEST_ULP_EQUAL(y1, y2, 0.5);\n  NT2_TEST_ULP_EQUAL(y1, y3, 0.5);\n  NT2_TEST_ULP_EQUAL(y1, y4, 0.5);\n}\n", "meta": {"hexsha": "ffb7e0d2b70b4504da9dfd5fc2b4cf62f8ed3fc6", "size": 3765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/polynomials/bench/simd/horner.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/polynomials/bench/simd/horner.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/polynomials/bench/simd/horner.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 28.3082706767, "max_line_length": 192, "alphanum_fraction": 0.627622842, "num_tokens": 1357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6959583250334527, "lm_q1q2_score": 0.5001117498320443}}
{"text": "//\n// Created by James Noeckel on 12/2/19.\n//\n\n#include <Eigen/Dense>\n#include <geometry/primitives3/compute_basis.h>\n#include \"BoundedPlane.h\"\n#include \"intersect_planes.h\"\n#include \"geometry/csg1d.h\"\n\nusing namespace Eigen;\n\nBoundedPlane::BoundedPlane(std::shared_ptr<Primitive> shape, const Ref<const Matrix<double, 3, 3>> &basis, double offset) : shapes_(1), basis_(basis), offset_(offset) {\n    shapes_[0] = (std::move(shape));\n    setCurrentShape(0);\n}\n\nBoundedPlane::BoundedPlane(const Ref< const Eigen::Matrix<double, 3, 1>> &normal, double offset) : offset_(offset) {\n    basis_.row(2) = normal.transpose();\n    basis_.block<2, 3>(0, 0) = compute_basis(normal);\n}\n\nvoid BoundedPlane::changeBasis(const Ref< const Eigen::Matrix2d> &newbasis) {\n    basis_.block<2, 3>(0, 0) = newbasis * basis_.block<2, 3>(0, 0);\n}\n\nvoid BoundedPlane::flip() {\n    basis_.row(2) = -basis_.row(2);\n    basis_.row(0) = -basis_.row(0);\n    offset_ = -offset_;\n}\n\ndouble BoundedPlane::offset() const {\n    return offset_;\n}\n\nVector3d BoundedPlane::normal() const {\n    return basis_.row(2).transpose();\n}\n\nMatrixX3d BoundedPlane::points3D() const {\n    MatrixX2d pts = curr_shape_ptr_->points();\n    return points3D(pts);\n}\n\nMatrixX3d BoundedPlane::points3D(const Ref<const MatrixX2d> &points) const {\n    return (points * basis_.block<2, 3>(0, 0)).rowwise() - offset_ * basis_.row(2);\n}\n\nMatrixX2d BoundedPlane::project(const Ref<const MatrixX3d> &points) const {\n    return points * basis_.block<2, 3>(0, 0).transpose();\n}\n\nVectorXd BoundedPlane::normalDistance(const Eigen::Ref<const Eigen::MatrixX3d> &points) const {\n    return (points * basis_.row(2).transpose()).array() + offset_;\n}\n\nconst Matrix<double, 3, 3> &BoundedPlane::basis() const {\n    return basis_;\n}\n\nbool BoundedPlane::contains(const Ref<const Vector2d> &point, double margin) const {\n    return curr_shape_ptr_->contains(point, margin);\n}\n\nbool BoundedPlane::contains3D(const Ref<const Vector3d> &point, double threshold, double margin, double offset) const {\n    if (threshold < 0 || std::abs(basis_.row(2) * point + offset_ - offset) <= threshold) {\n        RowVector2d p2d = project(point.transpose());\n        return contains(p2d.transpose(), margin);\n    }\n    return false;\n}\n\nbool BoundedPlane::intersectRay(const Ref<const Vector3d> &ray_origin, const Ref<const Vector3d> &ray_direction, double &t, bool ignore_shape, double margin) const {\n    Vector3d plane_center = - offset_ * basis_.row(2).transpose();\n    Vector3d offset = plane_center - ray_origin;\n    t = (-offset_- basis_.row(2) * ray_origin)/(basis_.row(2) * ray_direction);\n    if (t > 0) {\n        if (!ignore_shape && hasShape()) {\n            Vector3d projected_pt = ray_origin + t * ray_direction;\n            return contains(project(projected_pt.transpose()).transpose());\n        } else {\n            return true;\n        }\n    }\n    return false;\n}\n\nvoid BoundedPlane::intersectHelper(const Eigen::Vector3d &p, const Eigen::Vector3d &d, MultiRay3d &outRay, double margin) const {\n    outRay.o = p;\n    outRay.d = d;\n    if (hasShape()) {\n        Matrix<double, 2, 3> pd;\n        pd << p.transpose(), d.transpose();\n        Matrix<double, 2, 2> pd2d = project(pd);\n        Ray2d ray2d(pd2d.row(0).transpose(), pd2d.row(1).transpose());\n        auto intersections = curr_shape_ptr_->intersect(ray2d);\n        double intersectionLength = 0;\n        if (!intersections.empty() && intersections.size() % 2 == 0) {\n            for (size_t j = 0; j < intersections.size(); j += 2) {\n                intersectionLength += intersections[j + 1].t - intersections[j].t;\n            }\n        }\n        if (margin > 0) {\n            Eigen::Vector2d n(pd2d.row(1).y(), -pd2d.row(1).x());\n            for (int i = -1; i <= 1; i += 2) {\n                auto offsetIntersections = curr_shape_ptr_->intersect(\n                        Ray2d(pd2d.row(0).transpose() + (i * margin) * n, pd2d.row(1).transpose()));\n                if (!offsetIntersections.empty() && offsetIntersections.size() % 2 == 0) {\n                    double offsetLength = 0;\n                    for (int j = 0; j < offsetIntersections.size(); j += 2) {\n                        offsetLength += offsetIntersections[j + 1].t - offsetIntersections[j].t;\n                    }\n                    if (offsetLength > intersectionLength) {\n                        intersectionLength = offsetLength;\n                        intersections = std::move(offsetIntersections);\n                    }\n                }\n            }\n        }\n        if (!intersections.empty() && intersections.size() % 2 == 0) {\n            for (size_t i = 0; i < intersections.size(); i += 2) {\n                outRay.ranges.emplace_back(intersections[i].t, intersections[i + 1].t);\n            }\n        }\n    } else {\n        outRay.ranges.emplace_back(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max());\n    }\n}\n\nbool BoundedPlane::intersect(const BoundedPlane &other, MultiRay3d &outRay, double margin) const {\n    // get point-vector line intersection of planes\n    Vector3d p;\n    Vector3d d;\n    intersect_planes(basis_.row(2), other.basis_.row(2), offset_, other.offset_, p, d);\n    MultiRay3d rayThis;\n    intersectHelper(p, d, rayThis, margin);\n    MultiRay3d rayOther;\n    other.intersectHelper(p, d, rayOther, margin);\n    outRay = rayThis;\n    outRay.ranges = csg1d(rayThis.ranges, rayOther.ranges);\n    if (margin > 0) {\n        //stitch together ranges closer than margin, and remove ranges smaller than margin\n        std::vector<std::pair<double, double>> newRanges;\n        newRanges.reserve(outRay.size());\n        for (size_t i = 0; i < outRay.size(); ++i) {\n            if (i < outRay.size() - 1 && outRay.ranges[i + 1].first - outRay.ranges[i].second < margin) {\n                newRanges.emplace_back(outRay.ranges[i].first, outRay.ranges[i + 1].second);\n                ++i;\n                continue;\n            } else {\n                newRanges.push_back(outRay.ranges[i]);\n            }\n        }\n        newRanges.erase(std::remove_if(newRanges.begin(), newRanges.end(),\n                                       [=](const auto &range) { return range.second - range.first < margin; }),\n                        newRanges.end());\n        outRay.ranges = std::move(newRanges);\n    }\n    return !outRay.ranges.empty();\n\n}\n\nvoid BoundedPlane::addShape(int idx, std::shared_ptr<Primitive> shape) {\n    shapes_[idx] = std::move(shape);\n}\n\nvoid BoundedPlane::setCurrentShape(int idx) {\n    if (shapes_.find(idx) != shapes_.end()) {\n        curr_shape_ptr_ = shapes_[idx].get();\n    } else {\n        curr_shape_ptr_ = nullptr;\n    }\n    curr_shape_id_ = idx;\n}\n\nvoid BoundedPlane::clearCurrentShape() {\n    curr_shape_ptr_ = nullptr;\n}\n\nvoid BoundedPlane::clearShapes() {\n\n}\n\nint BoundedPlane::getCurrentShape() const {\n    return curr_shape_id_;\n}\n\nint BoundedPlane::getNumShapes() const {\n    return shapes_.size();\n}\n\nvoid BoundedPlane::serialize(std::ostream &o) const {\n    Eigen::MatrixXd basisd = basis();\n    basisd.resize(1, 9);\n    o << \"<plane basis=\\\"\" << basisd << \"\\\" offset=\\\"\" << offset() << \"\\\">\" << std::endl;\n//    if (hasShape())\n//        o << *curr_shape_ptr_ << std::endl;\n    o << \"</plane>\";\n}\n\nbool BoundedPlane::overlap(const BoundedPlane &other, double threshold, double margin, double offset) const {\n    //Eigen::MatrixX2d projected = project(other.points3D());\n    Eigen::MatrixX3d points = other.points3D();\n    for (int i=0; i < points.rows(); i++) {\n        if (contains3D(points.row(i).transpose(), threshold, margin, offset)) {\n            return true;\n        }\n    }\n    points = points3D();\n    for (int i=0; i < points.rows(); i++) {\n        if (other.contains3D((points.row(i) + basis_.row(2) * offset).transpose(), threshold, margin)) {\n            return true;\n        }\n    }\n    return false;\n}\n\nconst Primitive &BoundedPlane::getShape(int idx) const {\n    return *(shapes_.find(idx)->second);\n}\n\nPrimitive &BoundedPlane::getShape(int idx) {\n    return *(shapes_.find(idx)->second);\n}\n\nbool BoundedPlane::hasShape(int idx) const {\n    return shapes_.find(idx) != shapes_.end();\n}\n\nbool BoundedPlane::hasShape() const {\n    return curr_shape_ptr_ != nullptr;\n}\n\nstd::ostream &operator<<(std::ostream &o, const BoundedPlane &plane) {\n    plane.serialize(o);\n    return o;\n}\n\n\n", "meta": {"hexsha": "994ab7f6a7ea4a011880cb4060f59e0a836750a0", "size": 8323, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/primitives3/BoundedPlane.cpp", "max_stars_repo_name": "ShnitzelKiller/Reverse-Engineering-Carpentry", "max_stars_repo_head_hexsha": "585b5ff053c7e3bf286b663a584bc83687691bd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T07:28:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T21:12:40.000Z", "max_issues_repo_path": "src/geometry/primitives3/BoundedPlane.cpp", "max_issues_repo_name": "ShnitzelKiller/Reverse-Engineering-Carpentry", "max_issues_repo_head_hexsha": "585b5ff053c7e3bf286b663a584bc83687691bd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-21T14:40:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-26T01:19:38.000Z", "max_forks_repo_path": "src/geometry/primitives3/BoundedPlane.cpp", "max_forks_repo_name": "ShnitzelKiller/Reverse-Engineering-Carpentry", "max_forks_repo_head_hexsha": "585b5ff053c7e3bf286b663a584bc83687691bd6", "max_forks_repo_licenses": ["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.5352697095, "max_line_length": 168, "alphanum_fraction": 0.6123993752, "num_tokens": 2212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672089305841, "lm_q2_score": 0.6187804478040617, "lm_q1q2_score": 0.5000161893978452}}
{"text": "#ifndef RANDOM_HPP_INCLUDED\r\n#define RANDOM_HPP_INCLUDED\r\n\n#include \"e8core/plugin/plugin.hpp\"\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <stdint.h>\n#include <time.h>\n\n/**E8.Include random.hpp\n */\n\nconst uint32_t RANDOM_MAX = 4294967295ul; /*!< 2^32 - 1*/\n\n/**E8.Class RandomNumberGenerator RandomNumberGenerator|\u0413\u0435\u043d\u0435\u0440\u0430\u0442\u043e\u0440\u0421\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0445\u0427\u0438\u0441\u0435\u043b\n */\nclass RandomNumberGenerator {\n\n    boost::random::mt19937 gen;\n\npublic:\n    RandomNumberGenerator() : gen(time(0)) {}\n    RandomNumberGenerator(long seed) : gen(seed) {}\n\n    uint32_t\n    next(uint32_t lo = 0, uint32_t hi = RANDOM_MAX)\n    {\n        boost::random::uniform_int_distribution<> dist(lo, hi);\n        return dist(gen);\n    }\n\n    /**E8.Constructor [IN:\u0417\u0435\u0440\u043d\u043e]\n     */\n    static RandomNumberGenerator* Constructor(E8_IN Seed);\n\n    /**E8.Method RandomNumber|\u0421\u043b\u0443\u0447\u0430\u0439\u043d\u043e\u0435\u0427\u0438\u0441\u043b\u043e int [IN:LO] [IN:HI]\n     */\n    long RandomNumber(E8_IN LO, E8_IN HI);\n\n};\n/*E8.EndClass*/\n\r\n#endif // RANDOM_HPP_INCLUDED\r\n", "meta": {"hexsha": "17e8ff3b41da1b21e956a099fea46da1ead8c8a4", "size": 1015, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "engine/plugins/e8std/random.hpp", "max_stars_repo_name": "dmpas/e8engine", "max_stars_repo_head_hexsha": "27390fa096fa721be5f8a868a844fbb20f6ebc9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-17T07:28:02.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-17T07:28:02.000Z", "max_issues_repo_path": "engine/plugins/e8std/random.hpp", "max_issues_repo_name": "dmpas/e8engine", "max_issues_repo_head_hexsha": "27390fa096fa721be5f8a868a844fbb20f6ebc9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "engine/plugins/e8std/random.hpp", "max_forks_repo_name": "dmpas/e8engine", "max_forks_repo_head_hexsha": "27390fa096fa721be5f8a868a844fbb20f6ebc9c", "max_forks_repo_licenses": ["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.5555555556, "max_line_length": 79, "alphanum_fraction": 0.6975369458, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5000161808963631}}
{"text": "/*\nCopyright (c) 2020 ETH Zurich\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\nAuthor: Katrin Lasinger\n*/\n\n#define _USE_MATH_DEFINES\n\n#include <numeric>\n#include <vector>\n#include <algorithm>\n#include <omp.h>\n#include \"mex.h\"\n#include <math.h>\n#include \"FastExp64.h\"\n\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n\n// Code adapted from Johannes L. Schoeneberger\n// Copyright (c) 2018, ETH Zurich and UNC Chapel Hill.\n//https://github.com/colmap/colmap/blob/master/src/base/triangulation.cc\nEigen::Vector3d TriangulatePoint(const Eigen::Matrix<double, 3, 4>& proj_matrix1,\n                                 const Eigen::Matrix<double, 3, 4>& proj_matrix2,\n                                 const double point1x, const double point1y,\n                                 const double point2x, const double point2y) {\n  Eigen::Matrix4d A;\n\n  A.row(0) = point1x * proj_matrix1.row(2) - proj_matrix1.row(0);\n  A.row(1) = point1y * proj_matrix1.row(2) - proj_matrix1.row(1);\n  A.row(2) = point2x * proj_matrix2.row(2) - proj_matrix2.row(0);\n  A.row(3) = point2y * proj_matrix2.row(2) - proj_matrix2.row(1);\n\n  Eigen::JacobiSVD<Eigen::Matrix4d> svd(A, Eigen::ComputeFullV);\n\n  return svd.matrixV().col(3).hnormalized();\n}\n\n\n Vector2d polynomialCameraForward( Matrix<double, 19, 1> a_x, Matrix<double, 19, 1> a_y, Vector3d pt3d ){\n\tdouble pX = pt3d[0];\n\tdouble pY = pt3d[1];\n\tdouble pZ = pt3d[2];\n\n\tMatrix<double, 19, 1> A;\n\tA << 1, pX, pY, pZ, pX*pX, pX*pY, pY*pY, pX*pZ, pY*pZ, pZ*pZ, pX*pX*pX, pX*pX*pY, pX*pY*pY, pY*pY*pY, pX*pX*pZ, pX*pY*pZ, pY*pY*pZ, pX*pZ*pZ, pY*pZ*pZ;\n\n\tVector2d pt2d;\n\tpt2d[0] = A.dot(a_x);\n\tpt2d[1] = A.dot(a_y);\n\n\treturn pt2d;\n\n }\n\ntemplate <class Vec19_>\nVector3d TriangulatePoint_poly(Vec19_ a_x0, Vec19_ a_y0, Vec19_ a_x1, Vec19_ a_y1, Vector2d p0, Vector2d p1)\n{\n\tdouble thresh = 0.001;\n\tVector3d pt3d(0,0,0); //seems to be sufficient enough to just initialize with 0\n\n\tfor(int iterations = 0; iterations<1000; iterations++ )\n\t{\n\n        // check new projection\n        Vector2d pt2dEst_1 = polynomialCameraForward(a_x0,a_y0,pt3d);\n        Vector2d pt2dEst_2 = polynomialCameraForward(a_x1,a_y1,pt3d);\n\n        Vector2d diff1 = p0-pt2dEst_1;\n        Vector2d diff2 = p1-pt2dEst_2;\n\n        if (diff1.norm()<thresh && diff2.norm()<thresh){\n            break;\n\t\t}\n\n        double pX = pt3d[0];\n\t\tdouble pY = pt3d[1];\n\t\tdouble pZ = pt3d[2];\n\n        Vec19_ A_dX, A_dY, A_dZ;\n\t    A_dX << 0, 1, 0, 0, 2*pX, pY, 0, pZ, 0, 0, 3*pX*pX, 2*pX*pY, pY*pY, 0, 2*pX*pZ, pY*pZ, 0, pZ*pZ, 0;\n\t    A_dY << 0, 0, 1, 0, 0, pX, 2*pY, 0, pZ, 0, 0, pX*pX, pX*2*pY, 3*pY*pY, 0, pX*pZ, 2*pY*pZ, 0, pZ*pZ;\n\t    A_dZ << 0, 0, 0, 1, 0, 0, 0, pX, pY, 2*pZ, 0, 0, 0, 0, pX*pX, pX*pY, pY*pY, pX*2*pZ, pY*2*pZ;\n\n\t\tMatrixXd A(4,3);\n\n        A(0,0) = A_dX.dot(a_x0);\n        A(1,0) = A_dX.dot(a_y0);\n\t\tA(2,0) = A_dX.dot(a_x1);\n        A(3,0) = A_dX.dot(a_y1);\n\t\tA(0,1) = A_dY.dot(a_x0);\n        A(1,1) = A_dY.dot(a_y0);\n\t\tA(2,1) = A_dY.dot(a_x1);\n        A(3,1) = A_dY.dot(a_y1);\n        A(0,2) = A_dZ.dot(a_x0);\n        A(1,2) = A_dZ.dot(a_y0);\n\t\tA(2,2) = A_dZ.dot(a_x1);\n        A(3,2) = A_dZ.dot(a_y1);\n\n        Vector4d delta_x;\n\t\tdelta_x << diff1(0), diff1(1), diff2(0), diff2(1);\n\n        //delta_X = A\\delta_x;\n\t\tVector3d delta_X = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(delta_x);\n\n        pt3d = pt3d+delta_X;\n\n\t}\n\n\treturn pt3d;\n\n}\n\nVector3d polynomialCameraImg2World(Matrix<double, 19, 1> a_x, Matrix<double, 19, 1> a_y, Vector2d pt2d, double depth)\n{\n\tdouble thresh = 0.001;\n\tVector3d pt3d(0,0,depth); //seems to be sufficient enough to just initialize with 0\n\n\tfor(int iterations = 0; iterations<1000; iterations++ )\n\t{\n\n        // check new projection\n        Vector2d pt2dEst = polynomialCameraForward(a_x,a_y,pt3d);\n\n        Vector2d diff = pt2d-pt2dEst;\n\n        if (diff.norm()<thresh){\n            break;\n\t\t}\n\n        double pX = pt3d[0];\n\t\tdouble pY = pt3d[1];\n\t\tdouble pZ = pt3d[2];\n\n        Matrix<double, 19, 1> A_dX, A_dY, A_dZ;\n\t    A_dX << 0, 1, 0, 0, 2*pX, pY, 0, pZ, 0, 0, 3*pX*pX, 2*pX*pY, pY*pY, 0, 2*pX*pZ, pY*pZ, 0, pZ*pZ, 0;\n\t    A_dY << 0, 0, 1, 0, 0, pX, 2*pY, 0, pZ, 0, 0, pX*pX, pX*2*pY, 3*pY*pY, 0, pX*pZ, 2*pY*pZ, 0, pZ*pZ;\n\t    //A_dZ << 0, 0, 0, 1, 0, 0, 0, pX, pY, 2*pZ, 0, 0, 0, 0, pX*pX, pX*pY, pY*pY, pX*2*pZ, pY*2*pZ;\n\n\t\tMatrixXd A(2,2);\n\n        A(0,0) = A_dX.dot(a_x);\n        A(1,0) = A_dX.dot(a_y);\n\t\tA(0,1) = A_dY.dot(a_x);\n        A(1,1) = A_dY.dot(a_y);\n\n        Vector2d delta_x;\n\t\tdelta_x << diff(0), diff(1);\n\n\t\tVector2d delta_X = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(delta_x);\n\n        pt3d(0) = pt3d(0)+delta_X(0);\n        pt3d(1) = pt3d(1)+delta_X(1);\n\n\t}\n\n\treturn pt3d;\n}\n\n\n/// matlab calling - polynomial camera model\nvoid triangulatePartPoly ( int nlhs, mxArray *plhs[],\n                int nrhs, const mxArray *prhs[])\n{\n\n  typedef double Scalar;\n  typedef Matrix<double, 19, 1> Vector19d;\n  \n\n  Scalar *output1;\n\n  const mxArray *cell_array_ptr_in = prhs[0]; // per cam 2d array of xy coordinates+intensity of 2d part pos\n  std::vector< Scalar*> part;\n  const mxArray *cell_element_ptr;\n  const mxArray *cell_element_ptr2;\n  mwIndex jcell;\n\n  int numcam = mxGetNumberOfElements(cell_array_ptr_in);\n\n  \n  part.resize(numcam);\n  std::vector<int> numPart(numcam,0);\n\n  for (jcell=0; jcell<numcam; jcell++) {\n\t  cell_element_ptr = mxGetCell(cell_array_ptr_in,jcell);\n\n\t  const mwSize* dims = mxGetDimensions(cell_element_ptr);\n\n\t  numPart[jcell] = dims[1];\n\n\t  part[jcell] = (Scalar*) mxGetPr(cell_element_ptr);\n  }\n\n  const mxArray *cell_array_ptr_in_a = prhs[1]; // per cam: 19x2 coefficients of camera model\n  std::vector< Vector19d > a_x;\n  std::vector< Vector19d > a_y;\n  a_x.resize(numcam);\n  a_y.resize(numcam);\n\n  for (jcell=0; jcell<numcam; jcell++) {\n\t  cell_element_ptr = mxGetCell(cell_array_ptr_in_a,jcell);\n\n\t  Scalar* a_vec = (Scalar*) mxGetPr(cell_element_ptr);\n\t  for (int i=0;i<19;i++){\n\t\ta_x[jcell](i) = a_vec[i];\n\t\ta_y[jcell](i) = a_vec[i+19];\n\t  }\n\n  }\n  int N       = (int)  (*mxGetPr(prhs[2]));\n  int M       = (int)  (*mxGetPr(prhs[3]));\n  int L       = (int)  (*mxGetPr(prhs[4]));\n  Scalar triangError = (Scalar)  (*mxGetPr(prhs[5]));\n  Scalar triangErrorSq = triangError*triangError;\n\n  Scalar integralWeight = 1.0/sqrt(2.0*M_PI);\n\n  std::vector< Scalar > part3d; //list of 3d pts incl intensity (so 4d)\n\n  std::vector<std::vector<Scalar> > local(omp_get_max_threads());\n  std::vector<int> numTriangulatedPts(omp_get_max_threads(),0);\n#pragma omp parallel //num_threads(1)\n{\n\tint np = omp_get_num_threads();\n\t\n\tint currThreadNum = omp_get_thread_num();\n\t\n  //iterate over 2d peaks of cam0\n  //#pragma omp parallel for\n#pragma omp for //schedule(static)\n  for(int i=0;i<numPart[0];i++){\n\n\tVector2d pt_ref;\n\tpt_ref << part[0][i*3],part[0][i*3+1];\n\tScalar distSq = pow(floor(pt_ref(0)+0.5)-pt_ref(0),2)+pow(floor(pt_ref(1)+0.5)-pt_ref(1),2);\n\tScalar int_ref = part[0][i*3+2]/integralWeight/ exp(-distSq); //sigma=1\n\n    //first slice (at z=0)\n\tVector3d pt3d_front = polynomialCameraImg2World( a_x[0], a_y[0], pt_ref, 0 );\n    //last slice (at z=L-1)\n    Vector3d pt3d_back = polynomialCameraImg2World( a_x[0], a_y[0], pt_ref, L-1 );\n\t\n    //project 3d start and end pt to image\n    Vector2d front_epi = polynomialCameraForward( a_x[1], a_y[1], pt3d_front );\n\tVector2d back_epi = polynomialCameraForward( a_x[1], a_y[1], pt3d_back );\n\n    Scalar maxBB_x = std::max(front_epi(0),back_epi(0)) + triangError;\n    Scalar maxBB_y = std::max(front_epi(1),back_epi(1)) + triangError;\n    Scalar minBB_x = std::min(front_epi(0),back_epi(0)) - triangError;\n    Scalar minBB_y = std::min(front_epi(1),back_epi(1)) - triangError;\n\n\tScalar lowerTerm = std::sqrt(std::pow(back_epi(0)-front_epi(0),2)+std::pow(back_epi(1)-front_epi(1),2));\n\n    int numPtsOnLine=0;\n    int numFound3dpts=0;\n    int idxCurrPt = numTriangulatedPts[currThreadNum];\n\n    //get distance of pts to epipolar line\n    for (int j=1; j<numPart[1];j++){\n\n\n\t\tif(part[1][j*3]<minBB_x || part[1][j*3]>maxBB_x || part[1][j*3+1]<minBB_y || part[1][j*3+1]>maxBB_y)\n\t\t\tcontinue;\n\n       // compute distance\n       Scalar upperTerm = abs((back_epi(0)-front_epi(0))*(front_epi(1)-part[1][j*3+1])-(front_epi(0)-part[1][j*3])*(back_epi(1)-front_epi(1)));\n       Scalar d = upperTerm/lowerTerm;\n\n       if (d > triangError)\n           continue;\n\n       numPtsOnLine++;\n\n\t   Vector3d pt3d = TriangulatePoint_poly(a_x[0],a_y[0],a_x[1],a_y[1],pt_ref,Vector2d(part[1][j*3],part[1][j*3+1]));\n\t   \n\n       // can add a check if pt is actually within volume (since my\n       // epipolar line is alway from z=0 to z=L-1 it could be that part\n       // of the ray is outside of the volume to the sides)\n       // possible check for x and y should be sufficient\n\t   // assuming that N is already size including padding (so minus also for upper bound)\n       if( pt3d(0) < 0 || pt3d(0) > N-1 || pt3d(1) < 0 || pt3d(1) > M-1 || pt3d(2) < 0 || pt3d(2) > L-1)\n           continue;\n\n\t\tbool match=true;\n\n\t   // loop over remaining cams\n\t   for (int c=2;c<numcam;c++){\n\t\t   if(match == false) //if no match in prev other cam\n\t\t\t   continue;\n\t\t   match = false;\n\t\t   Vector2d pt2d_proj = polynomialCameraForward( a_x[c], a_y[c], pt3d );\n\n\t\t   Scalar maxBB_x_oc = pt2d_proj(0) + triangError;\n           Scalar maxBB_y_oc = pt2d_proj(1) + triangError;\n           Scalar minBB_x_oc = pt2d_proj(0) - triangError;\n           Scalar minBB_y_oc = pt2d_proj(1) - triangError;\n\n\t\t   for (int k=1; k<numPart[c];k++){\n\n\t\t\t   if(part[c][k*3]<minBB_x_oc || part[c][k*3]>maxBB_x_oc || part[c][k*3+1]<minBB_y_oc || part[c][k*3+1]>maxBB_y_oc)\n\t\t\t\t   continue;\n\n\t\t\t   if (pow(part[c][k*3]-pt2d_proj(0),2) + (pow(part[c][k*3+1]-pt2d_proj(1),2)) >triangErrorSq)\n\t\t\t\t\tcontinue;\n\n\t\t\t   match = true;\n\t\t   }\n\t   }\n\n\t   if(match){\n\t\t   numTriangulatedPts[currThreadNum]++;\n\t\t   numFound3dpts++; \n\t\t   local[currThreadNum].push_back(pt3d(0));\n\t\t   local[currThreadNum].push_back(pt3d(1));\n\t\t   local[currThreadNum].push_back(pt3d(2));\n\t\t   local[currThreadNum].push_back(int_ref);\n\n\t   }\n\n\t}\n    \n    //distribute intensity over found ref pts\n    if(numFound3dpts>1){\n\t\tfor(int ii=0;ii<numFound3dpts;ii++)\n\t\t\tlocal[currThreadNum][(idxCurrPt+ii)*4+3] = int_ref*(Scalar)4/(Scalar)(3+numFound3dpts);\n\t}\n  }\n}\n\nfor (int p = 0; p < omp_get_max_threads(); ++p){\n\tif (numTriangulatedPts[p] >0)\n\t\tpart3d.insert(part3d.end(),local[p].begin(),local[p].end());\n}\n\nint numTriangulatedPtsAll = part3d.size()/4;\n\n  //------------------------------------------------------------------------------\n  //write back to matlab\n\n  plhs[0] = mxCreateDoubleMatrix( 4, numTriangulatedPtsAll, mxREAL);\n  output1  = mxGetPr(plhs[0]);\n  for (int i=0;i<part3d.size();i++)\n      output1[i] = part3d[i];\n\n \n\n}\n\n/// matlab calling\nvoid triangulatePart ( int nlhs, mxArray *plhs[],\n                int nrhs, const mxArray *prhs[])\n{\n\n  typedef double Scalar;\n\n  Scalar *output1;\n\n  \n\n  const mxArray *cell_array_ptr_in = prhs[0]; // per cam 2d array of xy coordinates+intensity of 2d part pos\n  std::vector< Scalar*> part;\n  const mxArray *cell_element_ptr;\n  const mxArray *cell_element_ptr2;\n  mwIndex jcell;\n\n  int numcam = mxGetNumberOfElements(cell_array_ptr_in);\n\n  \n  part.resize(numcam);\n  std::vector<int> numPart(numcam,0);\n\n  for (jcell=0; jcell<numcam; jcell++) {\n\t  cell_element_ptr = mxGetCell(cell_array_ptr_in,jcell);\n\n\t  const mwSize* dims = mxGetDimensions(cell_element_ptr);\n\n\t  numPart[jcell] = dims[1];\n\n\t  part[jcell] = (Scalar*) mxGetPr(cell_element_ptr);\n  }\n\n  const mxArray *cell_array_ptr_in_P = prhs[1]; // per cam 2d array of xy coordinates+intensity of 2d part pos\n  const mxArray *cell_array_ptr_in_C = prhs[2];\n  std::vector< Matrix<Scalar, 3, 4> > P;\n  std::vector< Vector3d > C;\n  P.resize(numcam);\n  C.resize(numcam);\n\n  for (jcell=0; jcell<numcam; jcell++) {\n\t  cell_element_ptr = mxGetCell(cell_array_ptr_in_P,jcell);\n\t  cell_element_ptr2 = mxGetCell(cell_array_ptr_in_C,jcell);\n\n\t  Scalar* p_vec = (Scalar*) mxGetPr(cell_element_ptr);\n\t  for(int j=0;j<4;j++)\n\t\tfor (int i=0;i<3;i++)\n\t\t\t  P[jcell](i,j) = p_vec[i+j*3];\n\n\t  Scalar* c_vec = (Scalar*) mxGetPr(cell_element_ptr2);\n\t\tfor (int i=0;i<3;i++)\n\t\t\t  C[jcell](i) = c_vec[i];\n  }\n  int N       = (int)  (*mxGetPr(prhs[3]));\n  int M       = (int)  (*mxGetPr(prhs[4]));\n  int L       = (int)  (*mxGetPr(prhs[5]));\n  Scalar triangError = (Scalar)  (*mxGetPr(prhs[6]));\n  Scalar triangErrorSq = triangError*triangError;\n\n\t  \n\n \n  Scalar test = P[0](1,2);\n  Scalar integralWeight = 1.0/sqrt(2.0*M_PI);\n\n  std::vector< Scalar > part3d; //list of 3d pts incl intensity (so 4d)\n  \n  Matrix3d M_inv = P[0].block<3,3>(0,0).inverse();\n  Matrix3d M2_inv = P[1].block<3,3>(0,0).inverse();\n  Vector3d Pcol = P[0].col(3);\n\n  std::vector<std::vector<Scalar> > local(omp_get_max_threads());\n  std::vector<int> numTriangulatedPts(omp_get_max_threads(),0);\n#pragma omp parallel //num_threads(1)\n{\n\n\tint np = omp_get_num_threads();\n\t\n\tint currThreadNum = omp_get_thread_num();\n\t\n  //iterate over 2d peaks of cam0\n  //#pragma omp parallel for\n#pragma omp for //schedule(static)\n  for(int i=0;i<numPart[0];i++){\n\n\tVector3d pt_ref;\n\tpt_ref << part[0][i*3],part[0][i*3+1],1;\n\tScalar distSq = pow(floor(pt_ref(0)+0.5)-pt_ref(0),2)+pow(floor(pt_ref(1)+0.5)-pt_ref(1),2);\n\tScalar int_ref = part[0][i*3+2]/integralWeight/ exp(-distSq); //sigma=1\n\n\tVector3d pt;\n\tpt = M_inv * (pt_ref - Pcol);\n\n    Vector3d x1=C[0];\n    Vector3d x2=pt;\n    Vector3d x21 = x2-x1;\n    Scalar dvN = -x21(2);\n\n    //first slice (at z=0)\n    Scalar dx1Z = x1(2);\n    Scalar t = dx1Z/dvN;\n    Vector4d pt3d_front;\n\tpt3d_front << x1 + t*x21,1;\n    //last slice (at z=L-1)\n    dx1Z = x1(2)-(L-1);\n    t = dx1Z/dvN;\n    Vector4d pt3d_back;\n\tpt3d_back << x1 + t*x21,1;\n\n\n\n    //project 3d start and end pt to image\n    Vector3d front_epi = P[1]*pt3d_front;\n    front_epi = front_epi/front_epi(2);\n    Vector3d back_epi = P[1]*pt3d_back;\n    back_epi = back_epi/back_epi(2);\n\n    Scalar maxBB_x = std::max(front_epi(0),back_epi(0)) + triangError;\n    Scalar maxBB_y = std::max(front_epi(1),back_epi(1)) + triangError;\n    Scalar minBB_x = std::min(front_epi(0),back_epi(0)) - triangError;\n    Scalar minBB_y = std::min(front_epi(1),back_epi(1)) - triangError;\n\n\tScalar lowerTerm = std::sqrt(std::pow(back_epi(0)-front_epi(0),2)+std::pow(back_epi(1)-front_epi(1),2));\n\n    int numPtsOnLine=0;\n    int numFound3dpts=0;\n    int idxCurrPt = numTriangulatedPts[currThreadNum];\n\n    //get distance of pts to epipolar line\n    for (int j=1; j<numPart[1];j++){\n\n\t\t\n\t\t// if outside bounding box ignore\n\t\tif(part[1][j*3]<minBB_x || part[1][j*3]>maxBB_x || part[1][j*3+1]<minBB_y || part[1][j*3+1]>maxBB_y)\n\t\t\tcontinue;\n\n       // compute distance\n       Scalar upperTerm = abs((back_epi(0)-front_epi(0))*(front_epi(1)-part[1][j*3+1])-(front_epi(0)-part[1][j*3])*(back_epi(1)-front_epi(1)));\n       Scalar d = upperTerm/lowerTerm;\n\n       if (d > triangError)\n           continue;\n\n       numPtsOnLine++;\n\n\t   Vector3d pt3d = TriangulatePoint(P[0],P[1],pt_ref(0),pt_ref(1),part[1][j*3],part[1][j*3+1]);\n\t   \n\n       // can add a check if pt is actually within volume (since my\n       // epipolar line is alway from z=0 to z=L-1 it could be that part\n       // of the ray is outside of the volume to the sides)\n       // possible check for x and y should be sufficient\n\t   // assuming that N is already size including padding (so minus also for upper bound)\n       if( pt3d(0) < 0 || pt3d(0) > N-1 || pt3d(1) < 0 || pt3d(1) > M-1 || pt3d(2) < 0 || pt3d(2) > L-1)\n           continue;\n\n\t   \n\t\tVector4d pt3d_hom;\n\t\tpt3d_hom << pt3d,1;\n\n\t\tbool match=true;\n\n\t   // loop over remaining cams\n\t   for (int c=2;c<numcam;c++){\n\t\t   if(match == false) //if no match in prev other cam\n\t\t\t   continue;\n\t\t   match = false;\n\t\t   Vector3d pt2d_proj = P[c]*pt3d_hom;\n\t\t   pt2d_proj = pt2d_proj/pt2d_proj(2);\n\n\t\t   Scalar maxBB_x_oc = pt2d_proj(0) + triangError;\n           Scalar maxBB_y_oc = pt2d_proj(1) + triangError;\n           Scalar minBB_x_oc = pt2d_proj(0) - triangError;\n           Scalar minBB_y_oc = pt2d_proj(1) - triangError;\n\n\t\t   for (int k=1; k<numPart[c];k++){\n\t\t\t   //Vector3d pt_cam_other;\n\t\t\t   //pt_cam_other << part[c][k*3],part[c][k*3+1],1;\n\n\t\t\t   //if(pt_cam_other(0)<minBB_x_oc || pt_cam_other(0)>maxBB_x_oc || pt_cam_other(1)<minBB_y_oc || pt_cam_other(1)>maxBB_y_oc)\n\t\t\t//\t   continue;\n\n\t\t\t  // if (pow(pt_cam_other(0)-pt2d_proj(0),2) + (pow(pt_cam_other(1)-pt2d_proj(1),2)) >triangErrorSq)\n\t\t\t\t//\tcontinue;\n\n\t\t\t   if(part[c][k*3]<minBB_x_oc || part[c][k*3]>maxBB_x_oc || part[c][k*3+1]<minBB_y_oc || part[c][k*3+1]>maxBB_y_oc)\n\t\t\t\t   continue;\n\n\t\t\t   if (pow(part[c][k*3]-pt2d_proj(0),2) + (pow(part[c][k*3+1]-pt2d_proj(1),2)) >triangErrorSq)\n\t\t\t\t\tcontinue;\n\n\t\t\t   match = true;\n\t\t   }\n\t   }\n\n\t   if(match){\n\t\t   numTriangulatedPts[currThreadNum]++;\n\t\t   numFound3dpts++;\n\t\t   local[currThreadNum].push_back(pt3d(0));\n\t\t   local[currThreadNum].push_back(pt3d(1));\n\t\t   local[currThreadNum].push_back(pt3d(2));\n\t\t   local[currThreadNum].push_back(int_ref);\n\t   }\n\n\t}\n    \n    //distribute intensity over found ref pts\n    if(numFound3dpts>1){\n\t\tfor(int ii=0;ii<numFound3dpts;ii++)\n\t\t\tlocal[currThreadNum][(idxCurrPt+ii)*4+3] = int_ref*(Scalar)4/(Scalar)(3+numFound3dpts);\n\t}\n\n\n  }\n\n\n}\n\nfor (int p = 0; p < omp_get_max_threads(); ++p){\n\tif (numTriangulatedPts[p] >0)\n\t\tpart3d.insert(part3d.end(),local[p].begin(),local[p].end());\n}\n\n\n\nint numTriangulatedPtsAll = part3d.size()/4;\n\n  //input: cell array of 2d pts per cam incl intensity, P (and others?) \n  //output: triangulated 3d pts (get 0:n part per 2d pt)\n\n  //------------------------------------------------------------------------------\n  //write back to matlab\n\n  plhs[0] = mxCreateDoubleMatrix( 4, numTriangulatedPtsAll, mxREAL);\n  output1  = mxGetPr(plhs[0]);\n  for (int i=0;i<part3d.size();i++)\n      output1[i] = part3d[i];\n\n}", "meta": {"hexsha": "9d974cfe41437014d0f7220ea8c9cbc8b45833c4", "size": 18786, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Source/TriangulatePart.cpp", "max_stars_repo_name": "lasinger/3d-fluid-flow", "max_stars_repo_head_hexsha": "f8c22ad33db45cfcd3716f72d3f115a94e766285", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-07T13:18:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T11:15:59.000Z", "max_issues_repo_path": "src/Source/TriangulatePart.cpp", "max_issues_repo_name": "lasinger/3d-fluid-flow", "max_issues_repo_head_hexsha": "f8c22ad33db45cfcd3716f72d3f115a94e766285", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Source/TriangulatePart.cpp", "max_forks_repo_name": "lasinger/3d-fluid-flow", "max_forks_repo_head_hexsha": "f8c22ad33db45cfcd3716f72d3f115a94e766285", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-07T13:24:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T11:16:00.000Z", "avg_line_length": 30.9489291598, "max_line_length": 152, "alphanum_fraction": 0.6333972107, "num_tokens": 6619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5000161808963631}}
{"text": "#include \"icp.h\"\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <Eigen/Geometry>\n\nnamespace cuda_icp{\nEigen::Matrix4d TransformVector6dToMatrix4d(const Eigen::Matrix<double, 6, 1> &input) {\n    Eigen::Matrix4d output;\n    output.setIdentity();\n    output.block<3, 3>(0, 0) =\n            (Eigen::AngleAxisd(input(2), Eigen::Vector3d::UnitZ()) *\n             Eigen::AngleAxisd(input(1), Eigen::Vector3d::UnitY()) *\n             Eigen::AngleAxisd(input(0), Eigen::Vector3d::UnitX()))\n                    .matrix();\n    output.block<3, 1>(0, 3) = input.block<3, 1>(3, 0);\n    return output;\n}\n\nMat4x4f eigen_to_custom(const Eigen::Matrix4f& extrinsic){\n    Mat4x4f result;\n    for(uint32_t i=0; i<4; i++){\n        for(uint32_t j=0; j<4; j++){\n            result[i][j] = extrinsic(i, j);\n        }\n    }\n    return result;\n}\n\nMat4x4f eigen_slover_666(float *A, float *b)\n{\n    Eigen::Matrix<float, 6, 6> A_eigen(A);\n    Eigen::Matrix<float, 6, 1> b_eigen(b);\n    // ICP point to plane may be unstable, refer to\n    // https://www.cs.princeton.edu/~smr/papers/icpstability.pdf\n    // add a term ||x|| to make update reasonably small:\n    // f = ||(Rp + T - q) * n|| + penalty * ||X||   ==>\n    // (ATA + Identity * penalty) * X = B\n    Eigen::Matrix6d iden = Eigen::Matrix6d::Identity();\n    double penalty = 0.01;\n    Eigen::Matrix6d ATA_with_pen = A_eigen.cast<double>() + penalty*iden;\n    \n    const Eigen::Matrix<double, 6, 1> update = ATA_with_pen.ldlt().solve(b_eigen.cast<double>());    \n    Eigen::Matrix4d extrinsic = TransformVector6dToMatrix4d(update);\n    return eigen_to_custom(extrinsic.cast<float>());\n}\n\nvoid transform_pcd(std::vector<Vec3f>& model_pcd, Mat4x4f& trans){\n\n#pragma omp parallel for\n    for(uint32_t i=0; i < model_pcd.size(); i++){\n        Vec3f& pcd = model_pcd[i];\n        float new_x = trans[0][0]*pcd.x + trans[0][1]*pcd.y + trans[0][2]*pcd.z + trans[0][3];\n        float new_y = trans[1][0]*pcd.x + trans[1][1]*pcd.y + trans[1][2]*pcd.z + trans[1][3];\n        float new_z = trans[2][0]*pcd.x + trans[2][1]*pcd.y + trans[2][2]*pcd.z + trans[2][3];\n        pcd.x = new_x;\n        pcd.y = new_y;\n        pcd.z = new_z;\n    }\n}\n\ntemplate<class T>\nvoid cpu_exclusive_scan_serial(T* start, uint32_t N){\n    T cache = start[0];\n    start[0] = 0;\n    for (uint32_t i = 1; i < N; i++)\n    {\n        T temp = cache + start[i-1];\n        cache = start[i];\n        start[i] = temp;\n    }\n}\n\ntemplate<class T>\nstd::vector<Vec3f> depth2cloud_cpu(T* depth, uint32_t width, uint32_t height, Mat3x3f& K,\n                                uint32_t stride, uint32_t tl_x, uint32_t tl_y)\n{\n    std::vector<uint32_t> mask(width*height/stride/stride, 0);\n\n#pragma omp parallel for collapse(2)\n    for(uint32_t x=0; x<width/stride; x++){\n        for(uint32_t y=0; y<height/stride; y++){\n            if(depth[x*stride + y*stride*width] > 0) mask[x + y*width] = 1;\n        }\n    }\n\n    // scan to find map: depth idx --> cloud idx\n    uint32_t mask_back_temp = mask.back();\n\n    // without cuda this can't be used\n#ifdef CUDA_ON\n//    thrust::exclusive_scan(thrust::host, mask.begin(), mask.end(), mask.begin(), 0); // in-place scan\n    cpu_exclusive_scan_serial(mask.data(), mask.size()); // serial version is better in cpu maybe\n#else\n    cpu_exclusive_scan_serial(mask.data(), mask.size());\n#endif\n    uint32_t total_pcd_num = mask.back() + mask_back_temp;\n\n    std::vector<Vec3f> cloud(total_pcd_num);\n\n#pragma omp parallel for collapse(2)\n    for(uint32_t x=0; x<width/stride; x++){\n        for(uint32_t y=0; y<height/stride; y++){\n\n            uint32_t idx_depth = x*stride + y*stride*width;\n            uint32_t idx_mask = x + y*width;\n\n            if(depth[idx_depth] <= 0) continue;\n\n            float z_pcd = depth[idx_depth]/1000.0f;\n            float x_pcd = (x + tl_x - K[0][2])/K[0][0]*z_pcd;\n            float y_pcd = (y + tl_y - K[1][2])/K[1][1]*z_pcd;\n\n            cloud[mask[idx_mask]] = {x_pcd, y_pcd, z_pcd};\n        }\n    }\n    return cloud;\n}\n\ntemplate std::vector<Vec3f> depth2cloud_cpu(int32_t* depth, uint32_t width, uint32_t height, Mat3x3f& K,\n                                uint32_t stride, uint32_t tl_x, uint32_t tl_y);\ntemplate std::vector<Vec3f> depth2cloud_cpu(uint16_t* depth, uint32_t width, uint32_t height, Mat3x3f& K,\n                                            uint32_t stride, uint32_t tl_x, uint32_t tl_y);\n\n\ntemplate<class Scene>\nRegistrationResult ICP_Point2Plane_cpu(std::vector<Vec3f> &model_pcd, const Scene scene,\n                                       const ICPConvergenceCriteria criteria)\n{\n    RegistrationResult result;\n    RegistrationResult backup;\n\n    std::vector<float> A_host(36, 0);\n    std::vector<float> b_host(6, 0);\n    thrust__pcd2Ab<Scene> trasnformer(scene);\n\n    // use one extra turn\n    for(uint32_t iter=0; iter<=criteria.max_iteration_; iter++){\n\n        Vec29f reducer;\n\n#pragma omp declare reduction( + : Vec29f : omp_out += omp_in) \\\n                       initializer (omp_priv = Vec29f::Zero())\n\n#pragma omp parallel for reduction(+: reducer)\n        for(size_t pcd_iter=0; pcd_iter<model_pcd.size(); pcd_iter++){\n            Vec29f result = trasnformer(model_pcd[pcd_iter]);\n            reducer += result;\n        }\n\n        Vec29f& Ab_tight = reducer;\n\n        backup = result;\n\n        float& count = Ab_tight[28];\n        float& total_error = Ab_tight[27];\n        if(count == 0) return result;  // avoid divid 0\n\n        result.fitness_ = float(count) / model_pcd.size();\n        result.inlier_rmse_ = std::sqrt(total_error / count);\n\n        // last extra iter, just compute fitness & mse\n        if(iter == criteria.max_iteration_) return result;\n\n        if(std::abs(result.fitness_ - backup.fitness_) < criteria.relative_fitness_ &&\n           std::abs(result.inlier_rmse_ - backup.inlier_rmse_) < criteria.relative_rmse_){\n            return result;\n        }\n\n        for(int i=0; i<6; i++) b_host[i] = Ab_tight[21 + i];\n\n        int shift = 0;\n        for(int y=0; y<6; y++){\n            for(int x=y; x<6; x++){\n                A_host[x + y*6] = Ab_tight[shift];\n                A_host[y + x*6] = Ab_tight[shift];\n                shift++;\n            }\n        }\n\n        Mat4x4f extrinsic = eigen_slover_666(A_host.data(), b_host.data());\n\n        transform_pcd(model_pcd, extrinsic);\n        result.transformation_ = extrinsic * result.transformation_;\n    }\n\n    // never arrive here\n    return result;\n}\n\ntemplate RegistrationResult ICP_Point2Plane_cpu(std::vector<Vec3f> &model_pcd, const Scene_projective scene,\nconst ICPConvergenceCriteria criteria);\ntemplate RegistrationResult ICP_Point2Plane_cpu(std::vector<Vec3f> &model_pcd, const Scene_nn scene,\nconst ICPConvergenceCriteria criteria);\n\n\n/// !!!!!!!!!!!!!!!!!!!!! legacy\n// just for test and comparation\ntemplate<class Scene>\nRegistrationResult ICP_Point2Plane_cpu_global_memory_version(std::vector<Vec3f> &model_pcd, const Scene scene,\n                                       const ICPConvergenceCriteria criteria)\n{\n    RegistrationResult result;\n    RegistrationResult backup;\n\n    // buffer can make pcd handling indenpendent\n    // may waste memory, but make it easy to parallel\n    Eigen::Matrix<float, Eigen::Dynamic, 6> A_buffer(model_pcd.size(), 6); A_buffer.setZero();\n    Eigen::Matrix<float, Eigen::Dynamic, 1> b_buffer(model_pcd.size(), 1); b_buffer.setZero();\n\n    std::vector<uint32_t> valid_buffer(model_pcd.size(), 0);\n\n    // use one extra turn\n    for(uint32_t iter=0; iter<=criteria.max_iteration_; iter++){\n\n#pragma omp parallel for\n        for(uint32_t i = 0; i<model_pcd.size(); i++){\n            const auto& src_pcd = model_pcd[i];\n\n            Vec3f dst_pcd, dst_normal; bool valid;\n            scene.query(src_pcd, dst_pcd, dst_normal, valid);\n            if(valid){\n\n                // dot\n                b_buffer(i) = (dst_pcd - src_pcd).x * dst_normal.x +\n                              (dst_pcd - src_pcd).y * dst_normal.y +\n                              (dst_pcd - src_pcd).z * dst_normal.z;\n\n                // cross\n                A_buffer(i, 0) = dst_normal.z*src_pcd.y - dst_normal.y*src_pcd.z;\n                A_buffer(i, 1) = dst_normal.x*src_pcd.z - dst_normal.z*src_pcd.x;\n                A_buffer(i, 2) = dst_normal.y*src_pcd.x - dst_normal.x*src_pcd.y;\n\n                A_buffer(i, 3) = dst_normal.x;\n                A_buffer(i, 4) = dst_normal.y;\n                A_buffer(i, 5) = dst_normal.z;\n\n                valid_buffer[i] = 1;\n            }else{\n                b_buffer(i) = 0;\n\n                A_buffer(i, 0) = 0;\n                A_buffer(i, 1) = 0;\n                A_buffer(i, 2) = 0;\n                A_buffer(i, 3) = 0;\n                A_buffer(i, 4) = 0;\n                A_buffer(i, 5) = 0;\n\n                valid_buffer[i] = 0;\n            }\n            // else: invalid is 0 in A & b, ATA ATb means adding 0,\n            // so don't need to consider valid_buffer, just multi matrix\n        }\n\n        uint32_t count = 0;\n        float total_error = 0;\n#pragma omp parallel for reduction(+:count, total_error)\n        for(uint32_t i=0; i<model_pcd.size(); i++){\n            count += valid_buffer[i];\n            total_error += (b_buffer(i)*b_buffer(i));\n        }\n\n        backup = result;\n\n        if(count == 0) return result;  // avoid divid 0\n\n        result.fitness_ = float(count) / model_pcd.size();\n        result.inlier_rmse_ = std::sqrt(total_error / count);\n\n//        {\n//            std::cout << \" --- cpu --- \" << iter << \" --- cpu ---\" << std::endl;\n//            std::cout << \"total error: \" << total_error << std::endl;\n//            std::cout << \"result.fitness_: \" << result.fitness_ << std::endl;\n//            std::cout << \"result.inlier_rmse_: \" << result.inlier_rmse_ << std::endl;\n//            std::cout << \" --- cpu --- \" << iter << \" --- cpu ---\" << std::endl << std::endl;\n//        }\n\n        // last extra iter, just compute fitness & mse\n        if(iter == criteria.max_iteration_) return result;\n\n        if(std::abs(result.fitness_ - backup.fitness_) < criteria.relative_fitness_ &&\n           std::abs(result.inlier_rmse_ - backup.inlier_rmse_) < criteria.relative_rmse_){\n            return result;\n        }\n\n        Eigen::Matrix<float, 6, 6> A = A_buffer.transpose()*A_buffer;\n        Eigen::Matrix<float, 6, 1> b = A_buffer.transpose()*b_buffer;\n\n//        std::cout << \"~~~~~~~~A~~~~~~\" << std::endl;\n//        std::cout << A;\n//        std::cout << \"\\n~~~~~~~~~~~~~~\\n\" << std::endl;\n\n//        std::cout << \"~~~~~~~~b~~~~~~\" << std::endl;\n//        std::cout << b;\n//        std::cout << \"\\n~~~~~~~~~~~~~~\\n\" << std::endl;\n\n        Mat4x4f extrinsic = eigen_slover_666(A.data(), b.data());\n\n//        std::cout << \"~~extrinsic~~~~\" << std::endl;\n//        std::cout << extrinsic;\n//        std::cout << \"\\n~~~~~~~~~~~~~~\\n\" << std::endl;\n\n        transform_pcd(model_pcd, extrinsic);\n        result.transformation_ = extrinsic * result.transformation_;\n    }\n\n    // never arrive here\n    return result;\n}\n\ntemplate RegistrationResult ICP_Point2Plane_cpu_global_memory_version(std::vector<Vec3f> &model_pcd, const Scene_projective scene,\nconst ICPConvergenceCriteria criteria);\ntemplate RegistrationResult ICP_Point2Plane_cpu_global_memory_version(std::vector<Vec3f> &model_pcd, const Scene_nn scene,\nconst ICPConvergenceCriteria criteria);\n}\n\n\n\n\n\n", "meta": {"hexsha": "602f09356a18fc92e0a9661ac0b89c7fdf43399e", "size": 11309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cuda_icp/icp.cpp", "max_stars_repo_name": "meiqua/pose_refine", "max_stars_repo_head_hexsha": "84e44b30f6b7300938468609b9ad52328df20896", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2019-03-13T06:10:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T09:15:25.000Z", "max_issues_repo_path": "cuda_icp/icp.cpp", "max_issues_repo_name": "meiqua/pose_refine", "max_issues_repo_head_hexsha": "84e44b30f6b7300938468609b9ad52328df20896", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-07-12T06:06:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-30T06:13:29.000Z", "max_forks_repo_path": "cuda_icp/icp.cpp", "max_forks_repo_name": "meiqua/pose_refine", "max_forks_repo_head_hexsha": "84e44b30f6b7300938468609b9ad52328df20896", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2019-03-28T07:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T03:14:14.000Z", "avg_line_length": 35.340625, "max_line_length": 130, "alphanum_fraction": 0.5819258997, "num_tokens": 3177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5000161808963631}}
{"text": "//\n// Project: panoramachine\n// File: Utils.cpp\n//\n// Copyright (c) 2021 Miika 'Lehdari' Lehtim\u00e4ki\n// You may use, distribute and modify this code under the terms\n// of the licence specified in file LICENSE which is distributed\n// with this source code package.\n//\n\n#include \"Utils.hpp\"\n#include <algorithm>\n#include <opencv2/highgui.hpp>\n#include <Eigen/SVD>\n\n\nnamespace {\n\n    Vec3f fullSaturation(float x)\n    {\n        x *= (6.0f/(2.0f*M_PI));\n        return Vec3f(\n            std::clamp(2.0f-std::abs(x-4.0f), 0.0f, 1.0f),\n            std::clamp(2.0f-std::abs(x-2.0f), 0.0f, 1.0f),\n            std::clamp(std::abs(x-3.0f)-1.0f, 0.0f, 1.0f));\n    }\n\n}\n\nvoid gammaCorrect(cv::Mat& image, float gamma)\n{\n    for (int j=0; j<image.rows; ++j) {\n        auto* r = image.ptr<float>(j);\n        for (int i=0; i<image.cols*3; ++i) {\n            r[i] = std::pow(r[i], gamma);\n        }\n    }\n}\n\ncv::Mat correctImage(const cv::Mat& image, const cv::Mat& correction)\n{\n    cv::Mat image2 = image.clone();\n\n    for (int j=0; j<image.rows; ++j) {\n        auto* rImage2 = image2.ptr<Vec3f>(j);\n        auto* rCorrection = correction.ptr<Vec2f>(j);\n        for (int i=0; i<image.cols; ++i) {\n            Vec2f p(i+0.5f, j+0.5f);\n\n            rImage2[i] = sampleMatCubic<Vec3f>(image, p + rCorrection[i]);\n        }\n    }\n\n    return image2;\n}\n\nvoid show2ChannelImage(const std::string& windowName, const cv::Mat& image)\n{\n    cv::Mat image2(image.rows, image.cols, CV_32FC3);\n\n    float maxNorm = 1.0e-8f;\n    for (int j=0; j<image.rows; ++j) {\n        auto* p = image.ptr<Vec2f>(j);\n        auto* p2 = image2.ptr<Vec3f>(j);\n        for (int i=0; i<image.cols; ++i) {\n            p2[i] = fullSaturation(std::atan2(p[i](1), p[i](0))+M_PI);\n            float norm = p[i].norm();\n            if (norm > maxNorm)\n                maxNorm = norm;\n        }\n    }\n\n    for (int j=0; j<image.rows; ++j) {\n        auto* p = image.ptr<Vec2f>(j);\n        auto* p2 = image2.ptr<Vec3f>(j);\n        for (int i=0; i<image.cols; ++i) {\n            p2[i] *= p[i].norm() / maxNorm;\n        }\n    }\n\n    cv::imshow(windowName, image2);\n}\n\ncv::Mat load2ChannelImage(const std::string& filename)\n{\n    cv::Mat img1 = cv::imread(filename, cv::IMREAD_ANYCOLOR | cv::IMREAD_ANYDEPTH);\n    cv::Mat img2(img1.rows, img1.cols, CV_32FC2);\n\n    for (int j=0; j<img1.rows; ++j) {\n        auto* r = img1.ptr<Vec3f>(j);\n        auto* r2 = img2.ptr<Vec2f>(j);\n        for (int i=0; i<img1.cols; ++i) {\n            r2[i] = r[i].block<2,1>(0,0);\n        }\n    }\n\n    return img2;\n}\n\nMat3f computeHomography(const std::vector<Vec2f>& x, const std::vector<Vec2f>& y)\n{\n    assert(x.size() == y.size());\n\n    Mat3d h;\n    Eigen::MatrixXd p;\n    p.resize(x.size()*2, 9);\n    for (int i=0; i<x.size(); ++i) {\n        Vec2d xx = x[i].cast<double>();\n        Vec2d yy = y[i].cast<double>();\n        p.block<2,9>(i*2,0) = createPointMatchingMatrix(xx, yy);\n    }\n    Eigen::JacobiSVD<decltype(p)> svd(p, Eigen::ComputeThinV);\n    Eigen::Matrix<double, 9, 1> hv = svd.matrixV().block<9,1>(0,8);\n    h = Eigen::Map<Mat3d>(hv.data());\n    h /= h(2,2);\n    return h.transpose().cast<float>();\n}\n", "meta": {"hexsha": "40abb5959e9fc1424f9a6f7c6b16156c6aea3a7c", "size": 3138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils.cpp", "max_stars_repo_name": "Lehdari/Panoramachine", "max_stars_repo_head_hexsha": "af00840e8a2b2f5cd8bde4e8cd4037b9c7d43178", "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/Utils.cpp", "max_issues_repo_name": "Lehdari/Panoramachine", "max_issues_repo_head_hexsha": "af00840e8a2b2f5cd8bde4e8cd4037b9c7d43178", "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/Utils.cpp", "max_forks_repo_name": "Lehdari/Panoramachine", "max_forks_repo_head_hexsha": "af00840e8a2b2f5cd8bde4e8cd4037b9c7d43178", "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": 26.593220339, "max_line_length": 83, "alphanum_fraction": 0.5436583811, "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5000161808963631}}
{"text": "#ifndef LDLT_H\n#define LDLT_H\n#include <Eigen/Dense>\n#include \"mtao/type_utils.h\"\n\nnamespace mtao::solvers::cholesky {\n\ntemplate <typename Matrix>\nstruct DenseLDLT_MIC0\n{\n    typedef typename Matrix::Scalar Scalar;\n    template <typename A, typename B, typename C>\n    inline Scalar tripleVectorProduct(const A & a, const B & b, const C & c){\n        return a.cwiseProduct(b).dot(c);\n    }\n    inline Scalar tripleProduct(const Matrix & a, uint i, uint j)\n    {\n        return tripleVectorProduct(a.row(i).head(j),a.row(j).head(j),a.diagonal().head(j));\n    }\n    DenseLDLT_MIC0(const Matrix & A)\n    {\n        LD=A.template triangularView<Eigen::Lower>();\n        int i,j;\n        for(i=0; i<A.rows(); ++i)\n        {\n            for(j=0; j<i; ++j)\n                if(std::abs(LD(j,j))>0.0001)\n                {\n                    LD(i,j)-=tripleProduct(LD,i,j);\n                    LD(i,j)/=LD(j,j);\n                }\n                else\n                {\n                    LD(i,j)=0;\n                }\n            LD(i,i) -= tripleProduct(LD,i,i);\n        }\n\n    }\n    template <typename Vector>\n    void solve(const Vector & b, Vector & x)\n    {\n        x = LD.template triangularView<Eigen::UnitLower>().solve(b);\n        x.noalias() = x.cwiseQuotient(LD.diagonal());//safe beacuse it's a dot\n        LD.template triangularView<Eigen::UnitLower>().transpose().solveInPlace(x);\n    }\n    Matrix getA()\n    {\n        Matrix A = LD.template triangularView<Eigen::UnitLower>().transpose();\n        A = LD.diagonal().asDiagonal() * A;\n        A = LD.template triangularView<Eigen::UnitLower>() * A;\n\n        return A;\n    }\nprivate:\n    Matrix LD;\n};\n\n\n\n\n\ntemplate <typename Matrix, typename Vector>\nstruct SparseLDLT_MIC0\n{\n    typedef typename Matrix::Scalar Scalar;\n    SparseLDLT_MIC0() {}\n    SparseLDLT_MIC0(const Matrix & A, const Vector& v): SparseLDLT_MIC0(A) {}\n    SparseLDLT_MIC0(const Matrix & A)\n    {\n        // L=tril(A);\n        L=A.template triangularView<Eigen::StrictlyLower>();//Don't copy the diagonal\n        for(int i=0; i<L.rows(); ++i)\n        {\n            if(L.coeff(i,i)!=0)\n                L.coeffRef(i,i)=0;\n        }\n        Dinv=D=A.diagonal();\n\n\n\n        // for k=1:size(L,2)\n        for(int k=0; k<A.rows(); ++k)//k is the column that we're infecting the remaining columns with\n        {//L(:,k)\n\n\n\n            //Solidify the current column values\n            //==================================\n            if(D(k)==0) continue;\n            if(Dinv(k)<0.25*D(k))//If D has shrunk too much since it started\n                Dinv(k)=1/D(k);\n            else\n                Dinv(k)=1/Dinv(k);\n//            L.innerVector(k) *= Dinv(k);\n            L.innerVector(k) = L.innerVector(k) *  Dinv(k);\n\n            //Add k terms to all of the following columns\n            //===========================================\n            for(typename Matrix::InnerIterator it(L,k); it; ++it)// -L(i,k)*D(k)*L(j,k)\n            {\n                int j = it.row();//j>k\n                if(j<=k) continue;\n                Scalar missing=0;\n                Scalar multiplier=it.value();//L(j,k)*D(k)\n\n                typename Matrix::InnerIterator k_it(L,k);\n                typename Matrix::InnerIterator j_it(L,j);\n                //move down teh column of L(:,k) to collect missing elements in the match with A(:,j)\n                //i=k_it.row()\n\n                while (k_it && k_it.row()<j){//L(i,k)\n                    while(j_it)//L(i,j) occasionally\n                    {\n                        if(j_it.row() < k_it.row())\n                            ++j_it;\n                        else if(j_it.row() == k_it.row())//L(i,k) are L(i,j) are nonzero\n                            break;\n                        else\n                        {\n                            missing += k_it.value();//L(i,k) will fill something not in L(i,j)\n                            break;\n                        }\n                    }\n                    ++k_it;\n                }\n\n\n                if(k_it && j_it.row() == j)\n                {\n                    Dinv(j) -= it.value() * multiplier;\n                }\n\n\n                typename Matrix::InnerIterator j_it2(L,j);\n                while(k_it && j_it2)\n                {\n                    if(j_it2.row() < k_it.row())\n                        ++j_it2;\n                    else if(j_it2.row() == k_it.row())//L(i,k) and L(i,j) are both nonzero, -=L(i,k)*L(j,k)*D(k)\n                    {\n                        j_it2.valueRef() -= multiplier * k_it.value() ;//k_it.value()=L(i,k)\n                        ++j_it2;\n                        ++k_it;\n                    }\n                    else\n                    {\n                        missing+=k_it.value();\n                        ++k_it;\n                    }\n                }\n\n                while(k_it)\n                {\n                    missing+=k_it.value();\n                    ++k_it;\n                }\n                Dinv(j)-=0.97*missing*multiplier;\n            }\n        }\n\n        /*\n           std::cout << L << std::endl;\n           */\n\n    }\n    void solve(const Vector & b, Vector & x)\n    {\n        x = L.template triangularView<Eigen::UnitLower>().solve(b);\n        x.noalias() = x.cwiseProduct(Dinv);//safe beacuse it's a dot\n        L.transpose().template triangularView<Eigen::UnitUpper>().solveInPlace(x);\n    }\n    Matrix getA()\n    {\n        Matrix\n                A = L.template triangularView<Eigen::UnitLower>();\n        A = A * D.asDiagonal();\n        A = A * L.template triangularView<Eigen::UnitLower>().transpose();\n\n        return A;\n    }\nprivate:\n    Matrix L;\n    Vector D,Dinv;\n};\n\n\ntemplate <typename MatrixType, typename VectorType>\nusing LDLT_MIC0 = std::conditional_t<\nstd::is_base_of_v<Eigen::SparseMatrixBase<MatrixType>,MatrixType>,\n    SparseLDLT_MIC0<MatrixType,VectorType>,\n    DenseLDLT_MIC0<MatrixType>>;\n\n\n}\n\n#endif\n", "meta": {"hexsha": "ffae447088b3db3f316277466f709d0b9ffee0cc", "size": 5898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/solvers/cholesky/ldlt.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/solvers/cholesky/ldlt.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/solvers/cholesky/ldlt.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7878787879, "max_line_length": 112, "alphanum_fraction": 0.4593082401, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.500016169455907}}
{"text": "/*\n  High Performance Astrophysical Reconstruction and Processing (HARP)\n  (c) 2014-2015, The Regents of the University of California, \n  through Lawrence Berkeley National Laboratory.  See top\n  level LICENSE file for details.\n*/\n\n/*\n\n  This toy example implements an image \"calculator\" using a stack (think RPN calculator).  The input JSON\n  document specifies images and operators.  After running \"make check\", there will be some test data\n  files created in HARP/src/tests/testdata/.  If you \"cd\" into that directory, you can test this example\n  by running:\n\n  $>  harp_example_imgstack --par imgstack.json\n\n  NOTE:  this is just an example, and does not have several checks on the input JSON document that would\n  be required for production code.  For example, this code does not check that the first operation is a\n  \"PUSH\" or that the stack has a single image remaining at the end.\n\n*/\n\n\n#include <deque>\n#include <iostream>\n#include <cstdio>\n\n#include <boost/program_options.hpp>\n\n#include <harp.hpp>\n\n\nusing namespace std;\nusing namespace harp;\n\nnamespace popts = boost::program_options;\n\n\nint main ( int argc, char *argv[] ) {\n\n  double tstart;\n  double tstop;\n\n  cout.precision ( 12 );\n  cerr.precision ( 12 );\n\n  string jsonpar = \"\";\n  string outfile = \"imgstack.fits.out\";\n  \n  // Parse commandline options\n  \n  popts::options_description desc ( \"Allowed Options\" );\n  \n  desc.add_options()\n  ( \"help,h\", \"display usage information\" )\n  ( \"out\", popts::value<string>( &outfile ), \"output image file\" )\n  ( \"par\", popts::value<string>( &jsonpar ), \"JSON parameter file\" )\n  ;\n\n  popts::variables_map vm;\n\n  popts::store(popts::command_line_parser( argc, argv ).options(desc).run(), vm);\n  \n  popts::notify(vm);\n\n  if ( ( argc < 2 ) || vm.count( \"help\" ) || ( ! vm.count( \"par\" ) ) ) {\n    cerr << endl;\n    cerr << desc << endl;\n    return 0;\n  }\n\n  // Read JSON into a property tree\n  \n  boost::property_tree::ptree params;\n  boost::property_tree::json_parser::read_json ( jsonpar, params );\n\n  // This is our stack\n\n  std::deque < vector_double > stack;\n\n  size_t checkrows = 0;\n  size_t checkcols = 0;\n\n  // iterate over the input images and operators\n\n  boost::property_tree::ptree::const_iterator v = params.begin();\n\n  while ( v != params.end() ) {\n\n    if ( v->first == \"PUSH\" ) {\n      // we are pushing a new image onto the stack.  we don't care what format it is\n      // so we use the factory method to instantiate the image from parameters specified\n      // in the JSON.\n\n      image_p img = load_image ( v->second );\n\n      if ( checkrows == 0 ) {\n        // this is the first image\n\n        checkrows = img->n_rows();\n        checkcols = img->n_cols();\n      } else {\n        // verify that the image dimensions are consistent\n\n        if ( ( checkrows != img->n_rows() ) || ( checkcols != img->n_cols() ) ) {\n          HARP_THROW( \"inconsistent image dimensions on the stack\" );\n        }\n      }\n\n      stack.push_front ( vector_double() );\n      stack[0].resize ( checkrows * checkcols );\n\n      img->values ( stack[0] );\n\n      // img goes out of scope here and the raw pointer it wraps is deleted.\n\n    } else if ( v->first == \"ADD\" ) {\n\n      stack[1] += stack[0];\n      stack.pop_front();\n\n    } else if ( v->first == \"SUB\" ) {\n\n      stack[1] -= stack[0];\n      stack.pop_front();\n\n    } else if ( v->first == \"MUL\" ) {\n\n      stack[1] = boost::numeric::ublas::element_prod ( stack[1], stack[0] );\n      stack.pop_front();\n\n    } else if ( v->first == \"DIV\" ) {\n\n      stack[1] = boost::numeric::ublas::element_div ( stack[1], stack[0] );\n      stack.pop_front();\n\n    } else {\n\n      HARP_THROW( \"undefined stack operator\" );\n\n    }\n\n    ++v;\n\n  }\n\n  // write out the output image.  when writing data, we know exactly what format we are\n  // writing and do not use the factory technique- we just instantiate the class directly.\n\n  // for this example, we don't care about the inverse variance of each image (we ignored it\n  // above).  here we just write fake data.\n\n  vector_double fake_invvar ( checkrows * checkcols );\n  for ( size_t i = 0; i < fake_invvar.size(); ++i ) {\n    fake_invvar[i] = 1.0;\n  }\n\n  image_fits::write ( outfile, checkrows, stack[0], fake_invvar );\n\n  return 0;\n}\n\n\n\n", "meta": {"hexsha": "941eec6402f3285b746d3d8f45aa4c0479bc6f6a", "size": 4228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/apps/harp_example_imgstack.cpp", "max_stars_repo_name": "tskisner/HARP", "max_stars_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "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/apps/harp_example_imgstack.cpp", "max_issues_repo_name": "tskisner/HARP", "max_issues_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "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/apps/harp_example_imgstack.cpp", "max_forks_repo_name": "tskisner/HARP", "max_forks_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "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": 25.6242424242, "max_line_length": 105, "alphanum_fraction": 0.637653737, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5000014995097062}}
{"text": "#include <gtest/gtest.h>\n#include <boost/random.hpp>\n#include <map>\n#include <queue>\n#include <string>\n\n#include \"Octree.hpp\"\n\nnamespace\n{\n\nclass NaiveNeighborSearch\n{\n public:\n  void initialize(const std::shared_ptr<Eigen::Matrix3Xd>& points)\n  {\n    data_ = points;\n  }\n\n  template <typename Distance>\n  bool findNeighbor(const Eigen::Vector3d& query, size_t& resultIndex, double minDistance = -1.0)\n  {\n    if (data_->cols() == 0) return false;\n\n    double maxDistance = std::numeric_limits<double>::infinity();\n    double sqrMinDistance = (minDistance < 0) ? minDistance : Distance::sqr(minDistance);\n    resultIndex = std::numeric_limits<size_t>::max();\n    for (size_t i = 0; i < data_->cols(); ++i)\n    {\n      double dist = Distance::compute(query, data_->col(i));\n      if ((dist > sqrMinDistance) && (dist < maxDistance))\n      {\n        maxDistance = dist;\n        resultIndex = i;\n      }\n    }\n\n    return true;\n  }\n\n  template <typename Distance>\n  void radiusNeighbors(const Eigen::Vector3d& query, double radius, std::vector<size_t>& resultIndices)\n  {\n    resultIndices.clear();\n    double sqrRadius = Distance::sqr(radius);\n\n    for (size_t i = 0; i < data_->cols(); ++i)\n    {\n      if (Distance::compute(query, data_->col(i)) < sqrRadius)\n      {\n        resultIndices.push_back(i);\n      }\n    }\n  }\n\n protected:\n  std::shared_ptr<Eigen::Matrix3Xd> data_;\n};\n\n// The fixture for testing class Foo.\nclass OctreeTest : public ::testing::Test\n{\n public:\n  typedef unibn::Octree::Octant Octant;\n\n protected:\n  // helper methods to access the protected parts of octree for consistency\n  // checks.\n  const typename unibn::Octree::Octant* getRoot(const unibn::Octree& oct)\n  {\n    return oct.root_;\n  }\n\n  const std::vector<size_t>& getSuccessors(const unibn::Octree& oct)\n  {\n    return oct.successors_;\n  }\n\n  template <typename Distance>\n  bool overlaps(const Eigen::Vector3d& query, double radius, double sqRadius, const Octant* o)\n  {\n    return unibn::Octree::template overlaps<Distance>(query, radius, sqRadius, o);\n  }\n};\n\nvoid randomPoints(Eigen::Matrix3Xd& pts, size_t N, uint32_t seed = 0)\n{\n  boost::mt11213b mtwister(seed);\n  boost::uniform_01<> gen;\n  pts.resize(3, N);\n  // generate N random points in [-5.0,5.0] x [-5.0,5.0] x [-5.0,5.0]...\n  for (size_t i = 0; i < N; ++i)\n  {\n    Eigen::Vector3d p(10.0 * gen(mtwister) - 5.0, 10.0 * gen(mtwister) - 5.0, 10.0 * gen(mtwister) - 5.0);\n    pts.col(i) = p;\n  }\n}\n\nTEST_F(OctreeTest, Initialize)\n{\n\n  size_t N = 1000;\n  unibn::OctreeParams params;\n  params.bucketSize = 16;\n\n  unibn::Octree oct;\n\n  const Octant* root = getRoot(oct);\n  const std::vector<size_t>& successors = getSuccessors(oct);\n\n  ASSERT_EQ(0, root);\n\n  std::shared_ptr<Eigen::Matrix3Xd> points(new Eigen::Matrix3Xd);\n  randomPoints(*points, N, 1337);\n\n  oct.initialize(points, params);\n\n  root = getRoot(oct);\n\n  // check first some pre-requisits.\n  ASSERT_EQ(true, (root != 0));\n  ASSERT_EQ(N, successors.size());\n\n  std::vector<size_t> elementCount(N, 0);\n  size_t idx = root->start;\n  for (size_t i = 0; i < N; ++i)\n  {\n    ASSERT_LT(idx, N);\n    ASSERT_LE(successors[idx], N);\n    elementCount[idx] += 1;\n    ASSERT_EQ(1, elementCount[idx]);\n    idx = successors[idx];\n  }\n\n  // check that each index was found.\n  for (size_t i = 0; i < N; ++i)\n  {\n    ASSERT_EQ(1, elementCount[i]);\n  }\n\n  // test if each Octant contains only points inside the octant and child\n  // octants have only real subsets of parents!\n  std::queue<const Octant*> queue;\n  queue.push(root);\n  std::vector<size_t> assignment(N, std::numeric_limits<size_t>::max());\n\n  while (!queue.empty())\n  {\n    const Octant* octant = queue.front();\n    queue.pop();\n\n    // check points.\n    ASSERT_LT(octant->start, N);\n\n    // test if each point assigned to a octant really is inside the octant.\n\n    size_t idx = octant->start;\n    size_t lastIdx = octant->start;\n    for (size_t i = 0; i < octant->size; ++i)\n    {\n      Eigen::Vector3d p = points->col(idx) - octant->center;\n\n      ASSERT_LE(std::abs(p[0]), octant->extent);\n      ASSERT_LE(std::abs(p[1]), octant->extent);\n      ASSERT_LE(std::abs(p[2]), octant->extent);\n      assignment[idx] = std::numeric_limits<size_t>::max();  // reset of child assignments.\n      lastIdx = idx;\n      idx = successors[idx];\n    }\n    ASSERT_EQ(octant->end, lastIdx);\n\n    bool shouldBeLeaf = true;\n    Octant* firstchild = 0;\n    Octant* lastchild = 0;\n    size_t pointSum = 0;\n\n    for (size_t c = 0; c < 8; ++c)\n    {\n      Octant* child = octant->child[c];\n      if (child == 0) continue;\n      shouldBeLeaf = false;\n\n      // child nodes should have start end intervals, which are true subsets of\n      // the parent.\n      if (firstchild == 0) firstchild = child;\n      // the child nodes should have intervals, where succ(e_{c-1}) == s_{c},\n      // and \\sum_c size(c) = parent size!\n      if (lastchild != 0) ASSERT_EQ(child->start, successors[lastchild->end]);\n\n      pointSum += child->size;\n      lastchild = child;\n      size_t idx = child->start;\n      for (size_t i = 0; i < child->size; ++i)\n      {\n        // check if points are uniquely assigned to single child octant.\n        ASSERT_EQ(std::numeric_limits<size_t>::max(), assignment[idx]);\n        assignment[idx] = c;\n        idx = successors[idx];\n      }\n\n      queue.push(child);\n    }\n\n    // consistent start/end of octant and its first and last children.\n    if (firstchild != 0) ASSERT_EQ(octant->start, firstchild->start);\n    if (lastchild != 0) ASSERT_EQ(octant->end, lastchild->end);\n\n    // check leafs flag.\n    ASSERT_EQ(shouldBeLeaf, octant->isLeaf);\n    ASSERT_EQ((octant->size <= params.bucketSize), octant->isLeaf);\n\n    // test if every point is assigned to a child octant.\n    if (!octant->isLeaf)\n    {\n      ASSERT_EQ(octant->size, pointSum);\n      size_t idx = octant->start;\n      for (size_t i = 0; i < octant->size; ++i)\n      {\n        ASSERT_LT(assignment[idx], std::numeric_limits<size_t>::max());\n        idx = successors[idx];\n      }\n    }\n  }\n}\n\nTEST_F(OctreeTest, Initialize_minExtent)\n{\n\n  size_t N = 1000;\n  unibn::OctreeParams params;\n  params.bucketSize = 16;\n  params.minExtent = 1.0f;\n\n  unibn::Octree oct;\n\n  const Octant* root = getRoot(oct);\n  const std::vector<size_t>& successors = getSuccessors(oct);\n\n  ASSERT_EQ(0, root);\n\n  std::shared_ptr<Eigen::Matrix3Xd> points(new Eigen::Matrix3Xd);\n  randomPoints(*points, N, 1337);\n\n  oct.initialize(points, params);\n\n  root = getRoot(oct);\n\n  // check first some pre-requisits.\n  ASSERT_EQ(true, (root != 0));\n  ASSERT_EQ(N, successors.size());\n\n  std::vector<size_t> elementCount(N, 0);\n  size_t idx = root->start;\n  for (size_t i = 0; i < N; ++i)\n  {\n    ASSERT_LT(idx, N);\n    ASSERT_LE(successors[idx], N);\n    elementCount[idx] += 1;\n    ASSERT_EQ(1, elementCount[idx]);\n    idx = successors[idx];\n  }\n\n  // check that each index was found.\n  for (size_t i = 0; i < N; ++i)\n  {\n    ASSERT_EQ(1, elementCount[i]);\n  }\n\n  // test if each Octant contains only points inside the octant and child\n  // octants have only real subsets of parents!\n  std::queue<const Octant*> queue;\n  queue.push(root);\n  std::vector<size_t> assignment(N, std::numeric_limits<size_t>::max());\n\n  while (!queue.empty())\n  {\n    const Octant* octant = queue.front();\n    queue.pop();\n\n    // check points.\n    ASSERT_LT(octant->start, N);\n\n    // test if each point assigned to a octant really is inside the octant.\n\n    size_t idx = octant->start;\n    size_t lastIdx = octant->start;\n    for (size_t i = 0; i < octant->size; ++i)\n    {\n      Eigen::Vector3d p = points->col(idx) - octant->center;\n\n      ASSERT_LE(std::abs(p[0]), octant->extent);\n      ASSERT_LE(std::abs(p[1]), octant->extent);\n      ASSERT_LE(std::abs(p[2]), octant->extent);\n      assignment[idx] = std::numeric_limits<size_t>::max();  // reset of child assignments.\n      lastIdx = idx;\n      idx = successors[idx];\n    }\n    ASSERT_EQ(octant->end, lastIdx);\n\n    bool shouldBeLeaf = true;\n    Octant* firstchild = 0;\n    Octant* lastchild = 0;\n    size_t pointSum = 0;\n\n    for (size_t c = 0; c < 8; ++c)\n    {\n      Octant* child = octant->child[c];\n      if (child == 0) continue;\n      shouldBeLeaf = false;\n\n      // child nodes should have start end intervals, which are true subsets of\n      // the parent.\n      if (firstchild == 0) firstchild = child;\n      // the child nodes should have intervals, where succ(e_{c-1}) == s_{c},\n      // and \\sum_c size(c) = parent size!\n      if (lastchild != 0) ASSERT_EQ(child->start, successors[lastchild->end]);\n\n      pointSum += child->size;\n      lastchild = child;\n      size_t idx = child->start;\n      for (size_t i = 0; i < child->size; ++i)\n      {\n        // check if points are uniquely assigned to single child octant.\n        ASSERT_EQ(std::numeric_limits<size_t>::max(), assignment[idx]);\n        assignment[idx] = c;\n        idx = successors[idx];\n      }\n\n      queue.push(child);\n    }\n\n    // consistent start/end of octant and its first and last children.\n    if (firstchild != 0) ASSERT_EQ(octant->start, firstchild->start);\n    if (lastchild != 0) ASSERT_EQ(octant->end, lastchild->end);\n\n    // check leafs flag.\n    ASSERT_EQ(shouldBeLeaf, octant->isLeaf);\n    ASSERT_EQ((octant->size <= params.bucketSize || octant->extent < 2.0f * params.minExtent), octant->isLeaf);\n    ASSERT_GE(octant->extent, params.minExtent);\n\n    // test if every point is assigned to a child octant.\n    if (!octant->isLeaf)\n    {\n      ASSERT_EQ(octant->size, pointSum);\n      size_t idx = octant->start;\n      for (size_t i = 0; i < octant->size; ++i)\n      {\n        ASSERT_LT(assignment[idx], std::numeric_limits<size_t>::max());\n        idx = successors[idx];\n      }\n    }\n  }\n}\n\nTEST_F(OctreeTest, FindNeighbor)\n{\n  // compare with bruteforce search.\n  size_t N = 1000;\n\n  boost::mt11213b mtwister(1234);\n  boost::uniform_int<> uni_dist(0, N - 1);\n\n  std::shared_ptr<Eigen::Matrix3Xd> points(new Eigen::Matrix3Xd);\n  randomPoints(*points, N, 1234);\n\n  NaiveNeighborSearch bruteforce;\n  bruteforce.initialize(points);\n  unibn::Octree octree;\n  octree.initialize(points);\n\n  for (size_t i = 0; i < 10; ++i)\n  {\n    size_t index = uni_dist(mtwister);\n    const Eigen::Vector3d& query = points->col(index);\n\n    // allow self-match\n    size_t brute_result;\n    bruteforce.findNeighbor<unibn::L2Distance>(query, brute_result);\n    ASSERT_EQ(index, brute_result);\n\n    size_t octree_result;\n    octree.findNeighbor<unibn::L2Distance>(query, octree_result);\n    ASSERT_EQ(brute_result, octree_result);\n\n    // disallow self-match\n    size_t bfneighbor;\n    bruteforce.findNeighbor<unibn::L2Distance>(query, bfneighbor, 0.3);\n    size_t octneighbor;\n    octree.findNeighbor<unibn::L2Distance>(query, octneighbor, 0.3);\n\n    ASSERT_EQ(bfneighbor, octneighbor);\n  }\n}\n\ntemplate <typename T>\nbool similarVectors(std::vector<T>& vec1, std::vector<T>& vec2)\n{\n  if (vec1.size() != vec2.size())\n  {\n    std::cout << \"expected size = \" << vec1.size() << \", but got size = \" << vec2.size() << std::endl;\n    return false;\n  }\n\n  for (uint32_t i = 0; i < vec1.size(); ++i)\n  {\n    bool found = false;\n    for (uint32_t j = 0; j < vec2.size(); ++j)\n    {\n      if (vec1[i] == vec2[j])\n      {\n        found = true;\n        break;\n      }\n    }\n    if (!found)\n    {\n      std::cout << i << \"-th element (\" << vec1[i] << \") not found.\" << std::endl;\n      return false;\n    }\n  }\n\n  return true;\n}\n\nTEST_F(OctreeTest, RadiusNeighbors)\n{\n  size_t N = 1000;\n\n  boost::mt11213b mtwister(1234);\n  boost::uniform_int<> uni_dist(0, N - 1);\n\n  std::shared_ptr<Eigen::Matrix3Xd> points(new Eigen::Matrix3Xd);\n  randomPoints(*points, N, 1234);\n\n  NaiveNeighborSearch bruteforce;\n  bruteforce.initialize(points);\n  unibn::Octree octree;\n  octree.initialize(points);\n\n  double radii[4] = {0.5, 1.0, 2.0, 5.0};\n\n  for (size_t r = 0; r < 4; ++r)\n  {\n    for (size_t i = 0; i < 10; ++i)\n    {\n      std::vector<size_t> neighborsBruteforce;\n      std::vector<size_t> neighborsOctree;\n\n      const Eigen::Vector3d& query = points->col(uni_dist(mtwister));\n\n      bruteforce.radiusNeighbors<unibn::L2Distance>(query, radii[r], neighborsBruteforce);\n      octree.radiusNeighbors<unibn::L2Distance>(query, radii[r], neighborsOctree);\n      ASSERT_EQ(true, similarVectors(neighborsBruteforce, neighborsOctree));\n\n      bruteforce.radiusNeighbors<unibn::L1Distance>(query, radii[r], neighborsBruteforce);\n      octree.radiusNeighbors<unibn::L1Distance>(query, radii[r], neighborsOctree);\n\n      ASSERT_EQ(true, similarVectors(neighborsBruteforce, neighborsOctree));\n\n      bruteforce.radiusNeighbors<unibn::MaxDistance>(query, radii[r], neighborsBruteforce);\n      octree.radiusNeighbors<unibn::MaxDistance>(query, radii[r], neighborsOctree);\n\n      ASSERT_EQ(true, similarVectors(neighborsBruteforce, neighborsOctree));\n    }\n  }\n}\n\nTEST_F(OctreeTest, OverlapTest)\n{\n  Octant octant;\n\n  octant.center = Eigen::Vector3d(1.0, 1.0, 1.0);\n  octant.extent = 0.5;\n\n  // completely inside\n  Eigen::Vector3d query(1.25, 1.25, 0.5);\n  double radius = 1.0;\n\n  ASSERT_TRUE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n\n  // faces of octant.\n  query = Eigen::Vector3d(1.75, 1.0, 1.0);\n  radius = 0.5;\n\n  ASSERT_TRUE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n\n  query = Eigen::Vector3d(1.0, 1.75, 1.0);\n  ASSERT_TRUE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n\n  query = Eigen::Vector3d(1.0, 1.0, 1.75);\n  ASSERT_TRUE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n\n  query = Eigen::Vector3d(1.0, 1.0, 2.75);\n  ASSERT_FALSE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n\n  // Edge cases:\n  query = Eigen::Vector3d(1.65, 1.65, 1.25);\n  ASSERT_TRUE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n\n  query = Eigen::Vector3d(1.25, 1.65, 1.65);\n  ASSERT_TRUE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n\n  query = Eigen::Vector3d(1.65, 1.25, 1.75);\n  ASSERT_TRUE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n\n  query = Eigen::Vector3d(1.9, 1.25, 1.9);\n  ASSERT_FALSE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n\n  query = Eigen::Vector3d(1.25, 1.9, 1.9);\n  ASSERT_FALSE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n\n  query = Eigen::Vector3d(1.9, 1.9, 1.25);\n  ASSERT_FALSE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n\n  // corner cases:\n  query = Eigen::Vector3d(1.65, 1.65, 1.65);\n  ASSERT_TRUE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n\n  query = Eigen::Vector3d(1.95, 1.95, 1.95);\n  ASSERT_FALSE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n\n  // edge special case, see Issue #3 -- Edge\n  octant.center = Eigen::Vector3d(0.025, -0.025, -0.025);\n  octant.extent = 0.025;\n\n  query = Eigen::Vector3d(0.025, 0.025, 0.025);\n  radius = 0.025;\n\n  ASSERT_FALSE(overlaps<unibn::L2Distance>(query, radius, radius * radius, &octant));\n}\n}  // namespace\n\nint main(int argc, char** argv)\n{\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "9aba800d581e2a01b91bdb27fc45960d3b47e9d1", "size": 15162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/octree-test.cpp", "max_stars_repo_name": "sheikware/octree", "max_stars_repo_head_hexsha": "acdc5b0ec09728cfbf993676b057d592a9e9a12a", "max_stars_repo_licenses": ["MIT"], "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/octree-test.cpp", "max_issues_repo_name": "sheikware/octree", "max_issues_repo_head_hexsha": "acdc5b0ec09728cfbf993676b057d592a9e9a12a", "max_issues_repo_licenses": ["MIT"], "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/octree-test.cpp", "max_forks_repo_name": "sheikware/octree", "max_forks_repo_head_hexsha": "acdc5b0ec09728cfbf993676b057d592a9e9a12a", "max_forks_repo_licenses": ["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.1821561338, "max_line_length": 111, "alphanum_fraction": 0.639757288, "num_tokens": 4650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5000014956971668}}
{"text": "#define BOOST_TEST_MODULE boxed\n#include <boost/test/included/unit_test.hpp>\n\n#include <iron/math/PrimeStash.hpp>\n\nBOOST_AUTO_TEST_SUITE(boxed)\n\nBOOST_AUTO_TEST_CASE(IsDivisibleByAnyOfTest)\n{\n  std::vector<uint64_t> previous;\n  previous.push_back(2);\n  previous.push_back(3);\n  previous.push_back(5);\n  previous.push_back(7);\n  previous.push_back(11);\n\n  // Success checks\n  BOOST_CHECK( iron::PrimeStash::isDivisibleByAnyOf(2,  previous));\n  BOOST_CHECK( iron::PrimeStash::isDivisibleByAnyOf(3,  previous));\n  BOOST_CHECK( iron::PrimeStash::isDivisibleByAnyOf(4,  previous));\n\n  // Failure checks\n  BOOST_CHECK(!iron::PrimeStash::isDivisibleByAnyOf(1,  previous));\n  BOOST_CHECK(!iron::PrimeStash::isDivisibleByAnyOf(13, previous));\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "e8000ee5ae211df31b0adcf5e96a56acb0f15d0a", "size": 767, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/iron/math/PrimeStashTest.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/PrimeStashTest.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/PrimeStashTest.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.5666666667, "max_line_length": 67, "alphanum_fraction": 0.7666232073, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5000014943672214}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#define _USE_MATH_DEFINES // for MSVC to define _M_PI_2\n#include <nt2/elliptic/include/functions/am.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#include <nt2/include/functions/colon.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/pio_2.hpp>\n\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/basic.hpp>\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n// double Jacobi_am(double u, char arg, double x)                             //\n//                                                                            //\n//  Description:                                                              //\n//     Let F(phi,k) = F(phi \\ alpha) = F(phi | m) be Legendre's elliptic      //\n//     function of the first kind with modulus k, modular angle alpha where   //\n//     k = sin(alpha) or parameter m where m = k^2, i.e.                      //\n//        F(phi,k) = Integral(0,phi) dtheta / sqrt(1 - k^2 sin^2(theta))      //\n//        F(phi \\ alpha) = Integral(0,phi) dtheta /                           //\n//                                        sqrt(1 - sin^2(alpha) sin^2(theta)) //\n//        F(phi | m) = Integral(0,phi) dtheta / sqrt(1 - m sin^2(theta))      //\n//                                                                            //\n//     This Jacobi elliptic amplitude function, am, is defined as             //\n//               am(u,k) = am(u \\ alpha) = am(u | m)  = phi                   //\n//     where u = F(phi,k) = F(phi \\ alpha) = F(phi | m).                      //\n//                                                                            //\n//     The common mean method, sometimes called the Gauss transform method,   //\n//     is a variant of the descending Landen transformation in which two      //\n//     sequences are formed: Setting a[0] = 1 and g[0] = 1-m, a[i] is the     //\n//     arithmetic average and g[i] is the geometric mean of a[i-1] and g[i-1],//\n//     i.e. a[i+1] = (a[i] + g[i])/2 and g[i+1] = sqrt(a[i]*g[i]).  The       //\n//     sequences, a[i] and g[i], satisfy the inequalities                     //\n//     g[0] < g[1] < ... < a[1] < a[0].  Further, lim g[n] = lim a[n].        //\n//                                                                            //\n//     Set phi[n] = 2^n a[n] u, the recursively compute phi[n-1] by           //\n//        phi[n-1] = [ phi[n] + arcsin( c[n] sin(phi[n]) / a[n] ] / 2         //\n//     for until n = 1.  Then am(u,k) = am(u \\ alpha) = am(u | m) = phi[0].   //\n//                                                                            //\n//  Arguments:                                                                //\n//     double  u                                                              //\n//                The first argument of am(u,x) corresponding to the value of //\n//                the elliptic integral of the first kind u = F(am(u,x),x).   //\n//     char    arg                                                            //\n//                The type of argument of the second argument of am():        //\n//                  If arg = 'k', then x = k, the modulus of F(phi,k).        //\n//                  If arg = 'a', then x = alpha, the modular angle of        //\n//                                F(phi \\ alpha), alpha in radians.           //\n//                  If arg = 'm', then x = m, the parameter of F(phi | m).    //\n//                  The value of arg defaults to 'k'.                         //\n//     double  x                                                              //\n//                The second argument of the amplitude function am(u,x)       //\n//                corresponding to the second argument of the elliptic        //\n//                integral of the first kind F(phi,x).  'x' may the the       //\n//                modulus, modular angle, or parameter depending on the value //\n//                of 'arg'.  If 'arg' = 'm', then x must be between 0 and 1   //\n//                inclusively and if 'arg' = 'k', then x must be between -1   //\n//                and 1 inclusively.                                          //\n//                                                                            //\n//  Return Value:                                                             //\n//     The amplitude am(u,m) in radians.                                      //\n//                                                                            //\n//  Example:                                                                  //\n//     double u, x;                                                           //\n//     double am;                                                             //\n//     char   arg;                                                            //\n//                                                                            //\n//     ( code to initialize u, arg, and x )                                   //\n//                                                                            //\n//     phi = Jacobi_am( u, arg, x );                                          //\n////////////////////////////////////////////////////////////////////////////////\n\n#include <math.h>           // required for sqrtl(), fabsl(), fabs(), asinl(),\n                            // atan(), sinl(), and M_PI_2\n#include <float.h>          // required for LDBL_EPSILON\n\n\ndouble Jacobi_am(double u, char arg,  double x)\n{\n  static const int N = 30;            // More than sufficient for extended precision\n                                     // Near m = 1, usually an N of 10 would do.\n   long double a[N+1];\n   long double g[N+1];\n   long double c[N+1];\n   long double two_n;\n   long double phi;\n   long double k;\n   int n;\n\n                        // Check special case x = 0 //\n                        // i.e. k = m = alpha = 0.  //\n\n   if ( x == 0.0 ) return u;\n\n   switch (arg) {\n      case 'a': k = sinl( fabsl((long double) x) ); break;\n      case 'm': k = sqrtl( fabsl((long double) x) ); break;\n      default:  k = (long double) fabs(x);\n   }\n\n                   // Check special case k = 1 //\n\n   if ( k == 1.0 ) return 2.0 * atan( exp(u) ) - M_PI_2;\n\n         // If k > 1, then perform a Jacobi modulus transformation. //\n         // Initialize the sequence of arithmetic and geometric     //\n         // means, a = 1, g = k'.                                   //\n\n   a[0] = 1.0L;\n   g[0] = sqrtl(1.0L - k * k);\n   c[0] = k;\n\n   // Perform the sequence of Gaussian transformations of arithmetic and //\n   // geometric means of successive arithmetic and geometric means until //\n   // the two means converge to a common mean (upto machine accuracy)    //\n   // starting with a = 1 and g = k', which were set above.              //\n\n   two_n = 1.0L;\n   for (n = 0; n < N; n++) {\n      if ( fabsl(a[n] - g[n]) < (a[n] * LDBL_EPSILON) ) break;\n      two_n += two_n;\n      a[n+1] = 0.5L * (a[n] + g[n]);\n      g[n+1] = sqrtl(a[n] * g[n]);\n      c[n+1] = 0.5L * (a[n] - g[n]);\n   }\n\n         // Prepare for the inverse transformation of phi = x * cm. //\n\n   phi = two_n * a[n] * u;\n\n                      // Perform backward substitution //\n\n   for (; n > 0; n--) phi = 0.5L * ( phi + asinl( c[n] * sinl(phi) / a[n]) );\n\n   return (double) phi;\n}\n\n\n\n\n\nNT2_TEST_CASE_TPL ( am_real,  NT2_REAL_TYPES)\n{\n  using nt2::am;\n  using nt2::tag::am_;\n  typedef typename nt2::meta::call<am_(T,T)>::type r_t;\n  typedef T wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_ULP_EQUAL(am(nt2::Inf<T>(), T(0)), nt2::Inf<r_t>(), 1.0);\n  NT2_TEST_ULP_EQUAL(am(nt2::Minf<T>(), T(0)), nt2::Minf<r_t>(), 1.0);\n  NT2_TEST_ULP_EQUAL(am(nt2::Nan<T>(), T(0)), nt2::Nan<r_t>(), 1.0);\n  NT2_TEST_ULP_EQUAL(am(nt2::Inf<T>(), T(0.5)), nt2::Nan<r_t>(), 1.0);\n  NT2_TEST_ULP_EQUAL(am(nt2::Minf<T>(), T(0.5)), nt2::Nan<r_t>(), 1.0);\n  NT2_TEST_ULP_EQUAL(am(nt2::Nan<T>(), T(0.5)), nt2::Nan<r_t>(), 1.0);\n  NT2_TEST_ULP_EQUAL(am(nt2::Inf<T>(), T(1)), nt2::Pio_2<r_t>(), 1.0);\n  NT2_TEST_ULP_EQUAL(am(nt2::Minf<T>(), T(1)), -nt2::Pio_2<r_t>(), 1.0);\n  NT2_TEST_ULP_EQUAL(am(nt2::Nan<T>(), T(1)), nt2::Nan<r_t>(), 1.0);\n#endif\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(am(nt2::One<T>(),T(0)),    Jacobi_am(nt2::One<r_t>(),'x',T(0)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Pio_2<T>(),T(0)),  Jacobi_am(nt2::Pio_2<r_t>(),'x',T(0)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Zero<T>(),T(0)),   Jacobi_am(nt2::Zero<r_t>(),'x',T(0)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::One<T>(),T(0.5)),  Jacobi_am(nt2::One<T>(),'x',T(0.5)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Pio_2<T>(),T(0.5)),Jacobi_am(nt2::Pio_2<T>(),'x', T(0.5)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Zero<T>(),T(0.5)), Jacobi_am(nt2::Zero<T>(),'x', T(0.5)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::One<T>(),T(1)),    Jacobi_am(nt2::One<T>(),'x',T(1)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Pio_2<T>(),T(1)),  Jacobi_am(nt2::Pio_2<T>(),'x', T(1)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Zero<T>(),T(1)),   Jacobi_am(nt2::Zero<T>(),'x', T(1)), 1);\n\n  NT2_TEST_ULP_EQUAL(am(nt2::One<T>(),  T(0),  'a'),    Jacobi_am(nt2::One<r_t>(),  'a',T(0)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Pio_2<T>(),T(0),  'a'),  Jacobi_am(nt2::Pio_2<r_t>(),  'a',T(0)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Zero<T>(), T(0),  'a'),   Jacobi_am(nt2::Zero<r_t>(),  'a',T(0)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::One<T>(),  T(0.5), 'a'),  Jacobi_am(nt2::One<T>(),    'a',T(0.5)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Pio_2<T>(),T(0.5), 'a'),Jacobi_am(nt2::Pio_2<T>(),    'a', T(0.5)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Zero<T>(), T(0.5), 'a'), Jacobi_am(nt2::Zero<T>(),    'a', T(0.5)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::One<T>(),  T(1),  'a'),    Jacobi_am(nt2::One<T>(),    'a',T(1)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Pio_2<T>(),T(1),  'a'),  Jacobi_am(nt2::Pio_2<T>(),    'a', T(1)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Zero<T>(), T(1),  'a'),   Jacobi_am(nt2::Zero<T>(),    'a', T(1)), 1);\n\n  NT2_TEST_ULP_EQUAL(am(nt2::One<T>(),  T(0),  'm'),    Jacobi_am(nt2::One<r_t>(),  'm',T(0) ), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Pio_2<T>(),T(0),  'm'),  Jacobi_am(nt2::Pio_2<r_t>(),  'm',T(0)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Zero<T>(), T(0),  'm'),   Jacobi_am(nt2::Zero<r_t>(),  'm',T(0)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::One<T>(),  T(0.5), 'm'),  Jacobi_am(nt2::One<T>(),    'm',T(0.5)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Pio_2<T>(),T(0.5), 'm'),Jacobi_am(nt2::Pio_2<T>(),    'm', T(0.5)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Zero<T>(), T(0.5), 'm'), Jacobi_am(nt2::Zero<T>(),    'm', T(0.5)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::One<T>(),  T(1),  'm'),    Jacobi_am(nt2::One<T>(),    'm',T(1)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Pio_2<T>(),T(1),  'm'),  Jacobi_am(nt2::Pio_2<T>(),    'm', T(1)), 1);\n  NT2_TEST_ULP_EQUAL(am(nt2::Zero<T>(), T(1),  'm'),   Jacobi_am(nt2::Zero<T>(),    'm', T(1)), 1);\n}\n", "meta": {"hexsha": "3b1b5981ffe185d153204db7cffe9bab63cc0974", "size": 11763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/elliptic/unit/scalar/am.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/elliptic/unit/scalar/am.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "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": "modules/core/elliptic/unit/scalar/am.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 55.4858490566, "max_line_length": 100, "alphanum_fraction": 0.4438493582, "num_tokens": 3423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.500001492460952}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// series.hpp                                                                //\n//                                                                           //\n//  Copyright 2010 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_NON_PARAMETRIC_EMPIRICAL_DISTRIBUTION_KOLMOGOROV_SMIRNOV_STATISTIC_SERIES_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_EMPIRICAL_DISTRIBUTION_KOLMOGOROV_SMIRNOV_STATISTIC_SERIES_HPP_ER_2010\n#include <cmath>\n#include <boost/numeric/conversion/converter.hpp>\n#include <boost/accumulators/framework/accumulator_set.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/statistics/detail/non_parametric/empirical_distribution/kolmogorov_smirnov_statistic/value.hpp>\n\nnamespace boost{ \nnamespace statistics{\nnamespace detail{\nnamespace empirical_distribution{\nnamespace kolmogorov_smirnov_statistic{\n\ntemplate<typename T1>\nstruct series_data\n{\n    typedef std::size_t size_type; \n    series_data(){} \n    size_type count; T1 value;\n};\n\ntemplate<typename T>\nstd::ostream&\noperator<<(std::ostream& os,const series_data<T>& data)\n{\n    return os << '('<< data.count << ',' << data.value << ')';\n}\n\n\n// Generates a series_data whose value is the Kolmogorov-Smirnov statistic\n// for distribution dist, at each of the sample sizes \n//    offset + {base^i : i = first_p,...,last_p };\n// Each sample is drawn from gen(). \ntemplate<typename D,typename G,typename It>\nvoid series(\n    const D& dist,\n    G& gen,\n    long offset,    // 1\n    long base,      // 10\n    int first_p,   // 0\n    int last_p,    // 5\n    It iter\n){\n    namespace ac = boost::accumulators;\n    namespace ed = boost::statistics::detail::empirical_distribution;\n\tnamespace ks = ed::kolmogorov_smirnov_statistic;\n    typedef typename D::value_type val_;\n    typedef std::size_t size_;\n    typedef ks::tag::value<val_> tag_;\n    typedef series_data<val_> series_data_;\n    typedef typename G::result_type sample_;\n    typedef ac::stats<tag_> stats_;\n    typedef ac::accumulator_set<sample_,stats_> acc_;\n    acc_ acc;\n\n    typedef boost::numeric::converter<long double,long> int_float_;\n    typedef boost::numeric::converter<long, long double> float_int_;\n    \n    long m = float_int_::convert( \n        std::pow( int_float_::convert( base ), first_p )\n    );\n    long new_count;\n    series_data_ series_data;\n    series_data.count = 0;\n \n    for(long p = first_p; p < last_p; p++){\n        new_count = ( offset + m );\n        for( long i = series_data.count; i < new_count; i++ ){ acc( gen() ); }\n        series_data.count = new_count;\n        series_data.value = ks::extract::value<val_>( acc, dist );\n        ( *iter ) = series_data;\n        m *= base;\n    }\n        \n}\n\n}// kolmogorov_smirnov_statistic\n}// empirical_distribution\n}// detail\n}// statistics\n}// boost\n\n#endif\n\n", "meta": {"hexsha": "78dbbfc2c83b8fca3fc26c749c7f661c53e42d61", "size": 3160, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/empirical_distribution/kolmogorov_smirnov_statistic/series.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": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/empirical_distribution/kolmogorov_smirnov_statistic/series.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": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/empirical_distribution/kolmogorov_smirnov_statistic/series.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.9784946237, "max_line_length": 117, "alphanum_fraction": 0.6278481013, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5000014873184675}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <unordered_map>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing namespace boost::multiprecision;\nint main() {\n    long long int n; cin >> n;\n    long long int ans = 0;\n    unordered_map<cpp_int, bool> Map;\n    for (long long int i = 2; i * i <= n; i++) {\n        cpp_int tmp = i;\n        while(tmp <= n) {\n            tmp *= i;\n            if (tmp <= n) {\n                if (Map[tmp]) continue;\n                else ans++, Map[tmp] = true;\n            }\n        }\n    }\n    cout << n - ans << endl;\n}\n", "meta": {"hexsha": "3042ca62071c406d8e702f819d3a9c6955893d51", "size": 610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc193/c/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/abc193/c/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/abc193/c/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": 24.4, "max_line_length": 48, "alphanum_fraction": 0.5278688525, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5000014821759828}}
{"text": "#ifndef INFECTEE_H\n#define INFECTEE_H\n\n#include <iostream>\n#include <random>\n#include <vector>\n#include <Eigen/Core>\n\ntypedef unsigned int uint;\n\nconst uint N_STATES = 8; // number of different infection statuses\n\n// Default settings for simulation\n// https://softwareengineering.stackexchange.com/a/329733\nstruct params_struct\n{\n    double latent_period_shape = 2.; // gamma\n    double latent_period_scale = 5.;\n    double incub_factor_min = 0.8; // uniform\n    double incub_factor_max = 1.2;\n    double infect_period_shape = 1.; // gamma\n    double infect_period_scale = 5.;\n    double p_recovery = 0.3;          // bernoulli\n    double recover_period_shape = 4.; // gamma\n    double recover_period_scale = 3.;\n    double dying_period_shape = 4. / 9.; // gamma\n    double dying_period_scale = 9.;\n    double infect_delta = 2.941; // avg time between infections\n    double max_time = 364.;           // max model time (e.g. days)\n    double output_interval = 7.;    // interval of output (e.g. week)\n    double timestep = 0.2;\n    uint max_infected = 100000;  // stop iterating if reached\n    bool verbose = false;  // true for printing progress etc.\n};\n\n// Infection states (ref. Infection.istatus)\nconst std::string States[N_STATES]{\n    \"latent\",\n    \"symptoms_non_infectious\",\n    \"latent_infectious\",\n    \"symptoms\",\n    \"recovering\",\n    \"dying\",\n    \"recovered\",\n    \"dead\"};\n\nclass Infectee\n{\n    public:\n        Infectee(Infectee *infector, double infection_time, std::mt19937_64 &prng, params_struct params);\n        ~Infectee();\n\n        bool can_infect() const;           // Return whether self can infect others.\n        bool is_reported() const;          // Return whether infection has been reported.\n        std::string status() const;        // Return current status from the State enum.\n\n        std::vector<Infectee *> update(double time, std::mt19937_64 &prng, params_struct params); // Depending on time, update status of infection and possibly infect someone.\n\n    private:\n        const Infectee *infector;          // The individual who caused infection.\n        const double infection_time;       // Time of infection.\n\n        Infectee *infect(Infectee *other); // Mark `other` as infected by self.\n        std::vector<Infectee *> infected;  // Individuals infected by self.\n        int n_infected() const;            // Return the number of infected by self.\n\n        std::vector<uint> status_trajectory;     // Progression of infection with respect to infection states.\n        Eigen::ArrayXd end_times;                // End times of phases in `status_trajectory`.\n        std::vector<uint>::iterator status_iter; // Iterator for `status_trajectory`.\n\n        int istatus() const;               // Return the index to current status;\n        double time_next() const;          // Return time of next phase in infection.\n        double time_last_infection;        // Time of latest infection by self.\n\n        std::bernoulli_distribution rInfect;  // random engine for infecting\n\n    friend class Outbreak;\n    friend std::ostream &operator<<(std::ostream &os, Infectee const &inf);\n};\n\n// Allow printing a representation of Infectee objects\ninline std::ostream &operator<<(std::ostream &os, Infectee const &inf)\n{\n    os << \"Individual \" << &inf << \" was infected at t=\" << inf.infection_time;\n    os << \" and has infected \" << inf.n_infected() << \" others: \";\n    for (int i = 0; i < inf.n_infected(); ++i)\n    {\n        os << ' ' << inf.infected[i];\n        os.flush();\n    }\n    return os;\n}\n\n#endif", "meta": {"hexsha": "66bdc9ada4c92037afc62cb8f4cd6f2fa2518fcc", "size": 3532, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "infectee.hpp", "max_stars_repo_name": "vuolleko/outbreak", "max_stars_repo_head_hexsha": "182f687a05bf6086194684dd9d2b4bfaafba2c1f", "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": "infectee.hpp", "max_issues_repo_name": "vuolleko/outbreak", "max_issues_repo_head_hexsha": "182f687a05bf6086194684dd9d2b4bfaafba2c1f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "infectee.hpp", "max_forks_repo_name": "vuolleko/outbreak", "max_forks_repo_head_hexsha": "182f687a05bf6086194684dd9d2b4bfaafba2c1f", "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.5744680851, "max_line_length": 175, "alphanum_fraction": 0.6500566251, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5000014802697132}}
